3221437
{"version":0,"id":"4fa67f2236750907c75605b66bcb93fbdecc4321cb1fee5237200ffb7e82cebe","main":"/lib/node.js","imports":{},"resolutions":{"/lib/adopt.js":{"#package":"/package.json","hyper-proto-peer/lib/adopt.js":"/node_modules/hyper-proto-peer/lib/adopt.js"},"/lib/choose-bundle.js":{"#package":"/package.json"},"/lib/favela-api.js":{"#package":"/package.json"},"/lib/hosting.js":{"#package":"/package.json","atproto-identity/lib/hosting.js":"/node_modules/atproto-identity/lib/hosting.js","bare-path":"/node_modules/bare-path/index.js","hyper-proto-peer/lib/hosting-cli.js":"/node_modules/hyper-proto-peer/lib/hosting-cli.js"},"/lib/mint.js":{"#package":"/package.json","hyper-proto-peer/lib/mint.js":"/node_modules/hyper-proto-peer/lib/mint.js"},"/lib/node.js":{"#package":"/package.json","./adopt.js":"/lib/adopt.js","./favela-api.js":"/lib/favela-api.js","./hosting.js":"/lib/hosting.js","./mint.js":"/lib/mint.js","./ota.js":"/lib/ota.js","./repair-store-backend.js":"/lib/repair-store-backend.js","./roster.js":"/lib/roster.js","./session.js":"/lib/session.js","./shell-handoff.js":"/lib/shell-handoff.js","./utf8.js":"/lib/utf8.js","atproto-identity/lib/device-chain.js":"/node_modules/atproto-identity/lib/device-chain.js","atproto-identity/lib/vault.js":"/node_modules/atproto-identity/lib/vault.js","atproto-store/lib/tid.js":"/node_modules/atproto-store/lib/tid.js","b4a":"/node_modules/b4a/index.js","bare-fetch":"/node_modules/bare-fetch/index.js","bare-fs":"/node_modules/bare-fs/index.js","bare-path":"/node_modules/bare-path/index.js","bare-process":"/node_modules/bare-process/index.js","favela-web/bin/favela-web.js":"/node_modules/favela-web/bin/favela-web.js","favela-web/lib/bare-globals.js":"/node_modules/favela-web/lib/bare-globals.js","favela-web/lib/blob-serve.js":"/node_modules/favela-web/lib/blob-serve.js","favela-web/lib/render.js":"/node_modules/favela-web/lib/render.js","favela-web/lib/writer.js":"/node_modules/favela-web/lib/writer.js","hyper-proto-peer/lib/config.js":"/node_modules/hyper-proto-peer/lib/config.js","hyper-proto-peer/lib/device-node.js":"/node_modules/hyper-proto-peer/lib/device-node.js","hyper-svc":"/node_modules/hyper-svc/index.js"},"/lib/ota.js":{"#package":"/package.json","./choose-bundle.js":"/lib/choose-bundle.js","bare-fs":"/node_modules/bare-fs/index.js","bare-path":"/node_modules/bare-path/index.js","hyper-overlay/tree":"/node_modules/hyper-overlay/lib/tree.js","hypercore-crypto":"/node_modules/hypercore-crypto/index.js","pgh-runtime":"/node_modules/pgh-runtime/index.js","pgh/network-fetcher":"/node_modules/pgh/lib/network-fetcher.js","pgh/resolve-release":"/node_modules/pgh/lib/resolve-release.js"},"/lib/repair-store-backend.js":{"#package":"/package.json"},"/lib/roster.js":{"#package":"/package.json"},"/lib/session.js":{"#package":"/package.json","atproto-identity/lib/atproto-identity.js":"/node_modules/atproto-identity/lib/atproto-identity.js","atproto-identity/lib/auth.js":"/node_modules/atproto-identity/lib/auth.js","hypercore-crypto":"/node_modules/hypercore-crypto/index.js"},"/lib/shell-handoff.js":{"#package":"/package.json"},"/lib/utf8.js":{"#package":"/package.json"},"/node_modules/atproto-identity/lib/atproto-identity.js":{"#package":"/node_modules/atproto-identity/package.json","./did-key.js":"/node_modules/atproto-identity/lib/did-key.js","./did-plc.js":"/node_modules/atproto-identity/lib/did-plc.js","@noble/curves/secp256k1":"/node_modules/atproto-identity/node_modules/@noble/curves/esm/secp256k1.js","@noble/hashes/sha2":"/node_modules/atproto-identity/node_modules/@noble/hashes/esm/sha2.js","@scure/bip32":"/node_modules/atproto-identity/node_modules/@scure/bip32/lib/esm/index.js","@scure/bip39":"/node_modules/atproto-identity/node_modules/@scure/bip39/esm/index.js","multiformats/bases/base64":"/node_modules/atproto-identity/node_modules/multiformats/dist/src/bases/base64.js"},"/node_modules/atproto-identity/lib/auth.js":{"#package":"/node_modules/atproto-identity/package.json","@noble/curves/secp256k1":"/node_modules/atproto-identity/node_modules/@noble/curves/esm/secp256k1.js","@noble/hashes/hmac":"/node_modules/atproto-identity/node_modules/@noble/hashes/esm/hmac.js","@noble/hashes/scrypt":"/node_modules/atproto-identity/node_modules/@noble/hashes/esm/scrypt.js","@noble/hashes/sha2":"/node_modules/atproto-identity/node_modules/@noble/hashes/esm/sha2.js","hypercore-crypto":"/node_modules/atproto-identity/node_modules/hypercore-crypto/index.js"},"/node_modules/atproto-identity/lib/device-chain.js":{"#package":"/node_modules/atproto-identity/package.json","b4a":"/node_modules/atproto-identity/node_modules/b4a/index.js","keet-identity-key":"/node_modules/atproto-identity/node_modules/keet-identity-key/index.js"},"/node_modules/atproto-identity/lib/did-key.js":{"#package":"/node_modules/atproto-identity/package.json","multiformats/bases/base58":"/node_modules/atproto-identity/node_modules/multiformats/dist/src/bases/base58.js"},"/node_modules/atproto-identity/lib/did-plc.js":{"#package":"/node_modules/atproto-identity/package.json","@ipld/dag-cbor":"/node_modules/atproto-identity/node_modules/@ipld/dag-cbor/src/index.js","@noble/hashes/sha2":"/node_modules/atproto-identity/node_modules/@noble/hashes/esm/sha2.js","multiformats/bases/base32":"/node_modules/atproto-identity/node_modules/multiformats/dist/src/bases/base32.js","multiformats/cid":"/node_modules/atproto-identity/node_modules/multiformats/dist/src/cid.js","multiformats/hashes/digest":"/node_modules/atproto-identity/node_modules/multiformats/dist/src/hashes/digest.js"},"/node_modules/atproto-identity/lib/hosting.js":{"#package":"/node_modules/atproto-identity/package.json","./atproto-identity.js":"/node_modules/atproto-identity/lib/atproto-identity.js"},"/node_modules/atproto-identity/lib/vault.js":{"#package":"/node_modules/atproto-identity/package.json","b4a":"/node_modules/atproto-identity/node_modules/b4a/index.js","sodium-native":"/node_modules/atproto-identity/node_modules/sodium-native/index.js"},"/node_modules/atproto-identity/node_modules/@ipld/dag-cbor/package.json":{},"/node_modules/atproto-identity/node_modules/@ipld/dag-cbor/src/index.js":{"#package":"/node_modules/atproto-identity/node_modules/@ipld/dag-cbor/package.json","cborg":"/node_modules/atproto-identity/node_modules/cborg/cborg.js","multiformats/cid":"/node_modules/atproto-identity/node_modules/multiformats/dist/src/cid.js"},"/node_modules/atproto-identity/node_modules/@noble/curves/esm/_shortw_utils.js":{"#package":"/node_modules/atproto-identity/node_modules/@noble/curves/esm/package.json","./abstract/weierstrass.js":"/node_modules/atproto-identity/node_modules/@noble/curves/esm/abstract/weierstrass.js"},"/node_modules/atproto-identity/node_modules/@noble/curves/esm/abstract/curve.js":{"#package":"/node_modules/atproto-identity/node_modules/@noble/curves/esm/package.json","../utils.js":"/node_modules/atproto-identity/node_modules/@noble/curves/esm/utils.js","./modular.js":"/node_modules/atproto-identity/node_modules/@noble/curves/esm/abstract/modular.js"},"/node_modules/atproto-identity/node_modules/@noble/curves/esm/abstract/hash-to-curve.js":{"#package":"/node_modules/atproto-identity/node_modules/@noble/curves/esm/package.json","../utils.js":"/node_modules/atproto-identity/node_modules/@noble/curves/esm/utils.js","./modular.js":"/node_modules/atproto-identity/node_modules/@noble/curves/esm/abstract/modular.js"},"/node_modules/atproto-identity/node_modules/@noble/curves/esm/abstract/modular.js":{"#package":"/node_modules/atproto-identity/node_modules/@noble/curves/esm/package.json","../utils.js":"/node_modules/atproto-identity/node_modules/@noble/curves/esm/utils.js"},"/node_modules/atproto-identity/node_modules/@noble/curves/esm/abstract/weierstrass.js":{"#package":"/node_modules/atproto-identity/node_modules/@noble/curves/esm/package.json","../utils.js":"/node_modules/atproto-identity/node_modules/@noble/curves/esm/utils.js","./curve.js":"/node_modules/atproto-identity/node_modules/@noble/curves/esm/abstract/curve.js","./modular.js":"/node_modules/atproto-identity/node_modules/@noble/curves/esm/abstract/modular.js","@noble/hashes/hmac.js":"/node_modules/atproto-identity/node_modules/@noble/hashes/esm/hmac.js","@noble/hashes/utils":"/node_modules/atproto-identity/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/atproto-identity/node_modules/@noble/curves/esm/package.json":{},"/node_modules/atproto-identity/node_modules/@noble/curves/esm/secp256k1.js":{"#package":"/node_modules/atproto-identity/node_modules/@noble/curves/esm/package.json","./_shortw_utils.js":"/node_modules/atproto-identity/node_modules/@noble/curves/esm/_shortw_utils.js","./abstract/hash-to-curve.js":"/node_modules/atproto-identity/node_modules/@noble/curves/esm/abstract/hash-to-curve.js","./abstract/modular.js":"/node_modules/atproto-identity/node_modules/@noble/curves/esm/abstract/modular.js","./abstract/weierstrass.js":"/node_modules/atproto-identity/node_modules/@noble/curves/esm/abstract/weierstrass.js","./utils.js":"/node_modules/atproto-identity/node_modules/@noble/curves/esm/utils.js","@noble/hashes/sha2.js":"/node_modules/atproto-identity/node_modules/@noble/hashes/esm/sha2.js","@noble/hashes/utils.js":"/node_modules/atproto-identity/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/atproto-identity/node_modules/@noble/curves/esm/utils.js":{"#package":"/node_modules/atproto-identity/node_modules/@noble/curves/esm/package.json","@noble/hashes/utils.js":"/node_modules/atproto-identity/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/atproto-identity/node_modules/@noble/hashes/esm/_md.js":{"#package":"/node_modules/atproto-identity/node_modules/@noble/hashes/esm/package.json","./utils.js":"/node_modules/atproto-identity/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/atproto-identity/node_modules/@noble/hashes/esm/_u64.js":{"#package":"/node_modules/atproto-identity/node_modules/@noble/hashes/esm/package.json"},"/node_modules/atproto-identity/node_modules/@noble/hashes/esm/crypto.js":{"#package":"/node_modules/atproto-identity/node_modules/@noble/hashes/esm/package.json"},"/node_modules/atproto-identity/node_modules/@noble/hashes/esm/hmac.js":{"#package":"/node_modules/atproto-identity/node_modules/@noble/hashes/esm/package.json","./utils.js":"/node_modules/atproto-identity/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/atproto-identity/node_modules/@noble/hashes/esm/legacy.js":{"#package":"/node_modules/atproto-identity/node_modules/@noble/hashes/esm/package.json","./_md.js":"/node_modules/atproto-identity/node_modules/@noble/hashes/esm/_md.js","./utils.js":"/node_modules/atproto-identity/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/atproto-identity/node_modules/@noble/hashes/esm/package.json":{},"/node_modules/atproto-identity/node_modules/@noble/hashes/esm/pbkdf2.js":{"#package":"/node_modules/atproto-identity/node_modules/@noble/hashes/esm/package.json","./hmac.js":"/node_modules/atproto-identity/node_modules/@noble/hashes/esm/hmac.js","./utils.js":"/node_modules/atproto-identity/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/atproto-identity/node_modules/@noble/hashes/esm/scrypt.js":{"#package":"/node_modules/atproto-identity/node_modules/@noble/hashes/esm/package.json","./pbkdf2.js":"/node_modules/atproto-identity/node_modules/@noble/hashes/esm/pbkdf2.js","./sha2.js":"/node_modules/atproto-identity/node_modules/@noble/hashes/esm/sha2.js","./utils.js":"/node_modules/atproto-identity/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/atproto-identity/node_modules/@noble/hashes/esm/sha2.js":{"#package":"/node_modules/atproto-identity/node_modules/@noble/hashes/esm/package.json","./_md.js":"/node_modules/atproto-identity/node_modules/@noble/hashes/esm/_md.js","./_u64.js":"/node_modules/atproto-identity/node_modules/@noble/hashes/esm/_u64.js","./utils.js":"/node_modules/atproto-identity/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/atproto-identity/node_modules/@noble/hashes/esm/utils.js":{"#package":"/node_modules/atproto-identity/node_modules/@noble/hashes/esm/package.json","@noble/hashes/crypto":"/node_modules/atproto-identity/node_modules/@noble/hashes/esm/crypto.js"},"/node_modules/atproto-identity/node_modules/@scure/base/lib/esm/index.js":{"#package":"/node_modules/atproto-identity/node_modules/@scure/base/lib/esm/package.json"},"/node_modules/atproto-identity/node_modules/@scure/base/lib/esm/package.json":{},"/node_modules/atproto-identity/node_modules/@scure/bip32/lib/esm/index.js":{"#package":"/node_modules/atproto-identity/node_modules/@scure/bip32/lib/esm/package.json","@noble/curves/abstract/modular":"/node_modules/atproto-identity/node_modules/@noble/curves/esm/abstract/modular.js","@noble/curves/secp256k1":"/node_modules/atproto-identity/node_modules/@noble/curves/esm/secp256k1.js","@noble/hashes/hmac":"/node_modules/atproto-identity/node_modules/@noble/hashes/esm/hmac.js","@noble/hashes/legacy":"/node_modules/atproto-identity/node_modules/@noble/hashes/esm/legacy.js","@noble/hashes/sha2":"/node_modules/atproto-identity/node_modules/@noble/hashes/esm/sha2.js","@noble/hashes/utils":"/node_modules/atproto-identity/node_modules/@noble/hashes/esm/utils.js","@scure/base":"/node_modules/atproto-identity/node_modules/@scure/base/lib/esm/index.js"},"/node_modules/atproto-identity/node_modules/@scure/bip32/lib/esm/package.json":{},"/node_modules/atproto-identity/node_modules/@scure/bip39/esm/index.js":{"#package":"/node_modules/atproto-identity/node_modules/@scure/bip39/esm/package.json","@noble/hashes/pbkdf2":"/node_modules/atproto-identity/node_modules/@noble/hashes/esm/pbkdf2.js","@noble/hashes/sha2":"/node_modules/atproto-identity/node_modules/@noble/hashes/esm/sha2.js","@noble/hashes/utils":"/node_modules/atproto-identity/node_modules/@noble/hashes/esm/utils.js","@scure/base":"/node_modules/atproto-identity/node_modules/@scure/base/lib/esm/index.js"},"/node_modules/atproto-identity/node_modules/@scure/bip39/esm/package.json":{},"/node_modules/atproto-identity/node_modules/b4a/index.js":{"#package":"/node_modules/atproto-identity/node_modules/b4a/package.json"},"/node_modules/atproto-identity/node_modules/b4a/package.json":{},"/node_modules/atproto-identity/node_modules/bare-ansi-escapes/index.js":{"#package":"/node_modules/atproto-identity/node_modules/bare-ansi-escapes/package.json"},"/node_modules/atproto-identity/node_modules/bare-ansi-escapes/package.json":{},"/node_modules/atproto-identity/node_modules/bare-assert/index.js":{"#package":"/node_modules/atproto-identity/node_modules/bare-assert/package.json","bare-inspect":"/node_modules/atproto-identity/node_modules/bare-inspect/index.js"},"/node_modules/atproto-identity/node_modules/bare-assert/package.json":{},"/node_modules/atproto-identity/node_modules/bare-inspect/binding.js":{"#package":"/node_modules/atproto-identity/node_modules/bare-inspect/package.json",".":"linked:libbare-inspect.3.1.4.so"},"/node_modules/atproto-identity/node_modules/bare-inspect/index.js":{"#package":"/node_modules/atproto-identity/node_modules/bare-inspect/package.json","./binding":"/node_modules/atproto-identity/node_modules/bare-inspect/binding.js","bare-ansi-escapes":"/node_modules/atproto-identity/node_modules/bare-ansi-escapes/index.js","bare-type":"/node_modules/atproto-identity/node_modules/bare-type/index.js"},"/node_modules/atproto-identity/node_modules/bare-inspect/package.json":{},"/node_modules/atproto-identity/node_modules/bare-type/binding.js":{"#package":"/node_modules/atproto-identity/node_modules/bare-type/package.json",".":"linked:libbare-type.1.1.0.so"},"/node_modules/atproto-identity/node_modules/bare-type/index.js":{"#package":"/node_modules/atproto-identity/node_modules/bare-type/package.json","./binding":"/node_modules/atproto-identity/node_modules/bare-type/binding.js"},"/node_modules/atproto-identity/node_modules/bare-type/package.json":{},"/node_modules/atproto-identity/node_modules/bip39-mnemonic/index.js":{"#package":"/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json","./wordlist":"/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/index.js","b4a":"/node_modules/atproto-identity/node_modules/b4a/index.js","nanoassert":"/node_modules/atproto-identity/node_modules/nanoassert/index.js","sodium-universal":"/node_modules/atproto-identity/node_modules/sodium-universal/index.js"},"/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json":{},"/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/chinese_simplified.json":{"#package":"/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json"},"/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/chinese_traditional.json":{"#package":"/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json"},"/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/czech.json":{"#package":"/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json"},"/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/english.json":{"#package":"/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json"},"/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/french.json":{"#package":"/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json"},"/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/index.js":{"#package":"/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json","./chinese_simplified.json":"/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/chinese_simplified.json","./chinese_traditional.json":"/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/chinese_traditional.json","./czech.json":"/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/czech.json","./english.json":"/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/english.json","./french.json":"/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/french.json","./italian.json":"/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/italian.json","./japanese.json":"/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/japanese.json","./korean.json":"/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/korean.json","./lookup.json":"/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/lookup.json","./portuguese.json":"/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/portuguese.json","./russian.json":"/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/russian.json","./spanish.json":"/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/spanish.json","./turkish.json":"/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/turkish.json"},"/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/italian.json":{"#package":"/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json"},"/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/japanese.json":{"#package":"/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json"},"/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/korean.json":{"#package":"/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json"},"/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/lookup.json":{"#package":"/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json"},"/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/portuguese.json":{"#package":"/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json"},"/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/russian.json":{"#package":"/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json"},"/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/spanish.json":{"#package":"/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json"},"/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/turkish.json":{"#package":"/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json"},"/node_modules/atproto-identity/node_modules/cborg/cborg.js":{"#package":"/node_modules/atproto-identity/node_modules/cborg/package.json","./lib/decode.js":"/node_modules/atproto-identity/node_modules/cborg/lib/decode.js","./lib/encode.js":"/node_modules/atproto-identity/node_modules/cborg/lib/encode.js","./lib/tagged.js":"/node_modules/atproto-identity/node_modules/cborg/lib/tagged.js","./lib/token.js":"/node_modules/atproto-identity/node_modules/cborg/lib/token.js"},"/node_modules/atproto-identity/node_modules/cborg/lib/0uint.js":{"#package":"/node_modules/atproto-identity/node_modules/cborg/package.json","./common.js":"/node_modules/atproto-identity/node_modules/cborg/lib/common.js","./token.js":"/node_modules/atproto-identity/node_modules/cborg/lib/token.js"},"/node_modules/atproto-identity/node_modules/cborg/lib/1negint.js":{"#package":"/node_modules/atproto-identity/node_modules/cborg/package.json","./0uint.js":"/node_modules/atproto-identity/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/atproto-identity/node_modules/cborg/lib/common.js","./token.js":"/node_modules/atproto-identity/node_modules/cborg/lib/token.js"},"/node_modules/atproto-identity/node_modules/cborg/lib/2bytes.js":{"#package":"/node_modules/atproto-identity/node_modules/cborg/package.json","./0uint.js":"/node_modules/atproto-identity/node_modules/cborg/lib/0uint.js","./byte-utils.js":"/node_modules/atproto-identity/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/atproto-identity/node_modules/cborg/lib/common.js","./token.js":"/node_modules/atproto-identity/node_modules/cborg/lib/token.js"},"/node_modules/atproto-identity/node_modules/cborg/lib/3string.js":{"#package":"/node_modules/atproto-identity/node_modules/cborg/package.json","./0uint.js":"/node_modules/atproto-identity/node_modules/cborg/lib/0uint.js","./2bytes.js":"/node_modules/atproto-identity/node_modules/cborg/lib/2bytes.js","./common.js":"/node_modules/atproto-identity/node_modules/cborg/lib/common.js","./token.js":"/node_modules/atproto-identity/node_modules/cborg/lib/token.js"},"/node_modules/atproto-identity/node_modules/cborg/lib/4array.js":{"#package":"/node_modules/atproto-identity/node_modules/cborg/package.json","./0uint.js":"/node_modules/atproto-identity/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/atproto-identity/node_modules/cborg/lib/common.js","./token.js":"/node_modules/atproto-identity/node_modules/cborg/lib/token.js"},"/node_modules/atproto-identity/node_modules/cborg/lib/5map.js":{"#package":"/node_modules/atproto-identity/node_modules/cborg/package.json","./0uint.js":"/node_modules/atproto-identity/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/atproto-identity/node_modules/cborg/lib/common.js","./token.js":"/node_modules/atproto-identity/node_modules/cborg/lib/token.js"},"/node_modules/atproto-identity/node_modules/cborg/lib/6tag.js":{"#package":"/node_modules/atproto-identity/node_modules/cborg/package.json","./0uint.js":"/node_modules/atproto-identity/node_modules/cborg/lib/0uint.js","./token.js":"/node_modules/atproto-identity/node_modules/cborg/lib/token.js"},"/node_modules/atproto-identity/node_modules/cborg/lib/7float.js":{"#package":"/node_modules/atproto-identity/node_modules/cborg/package.json","./0uint.js":"/node_modules/atproto-identity/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/atproto-identity/node_modules/cborg/lib/common.js","./token.js":"/node_modules/atproto-identity/node_modules/cborg/lib/token.js"},"/node_modules/atproto-identity/node_modules/cborg/lib/bl.js":{"#package":"/node_modules/atproto-identity/node_modules/cborg/package.json","./byte-utils.js":"/node_modules/atproto-identity/node_modules/cborg/lib/byte-utils.js"},"/node_modules/atproto-identity/node_modules/cborg/lib/byte-utils.js":{"#package":"/node_modules/atproto-identity/node_modules/cborg/package.json"},"/node_modules/atproto-identity/node_modules/cborg/lib/common.js":{"#package":"/node_modules/atproto-identity/node_modules/cborg/package.json"},"/node_modules/atproto-identity/node_modules/cborg/lib/decode.js":{"#package":"/node_modules/atproto-identity/node_modules/cborg/package.json","./byte-utils.js":"/node_modules/atproto-identity/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/atproto-identity/node_modules/cborg/lib/common.js","./jump.js":"/node_modules/atproto-identity/node_modules/cborg/lib/jump.js","./token.js":"/node_modules/atproto-identity/node_modules/cborg/lib/token.js"},"/node_modules/atproto-identity/node_modules/cborg/lib/encode.js":{"#package":"/node_modules/atproto-identity/node_modules/cborg/package.json","./0uint.js":"/node_modules/atproto-identity/node_modules/cborg/lib/0uint.js","./1negint.js":"/node_modules/atproto-identity/node_modules/cborg/lib/1negint.js","./2bytes.js":"/node_modules/atproto-identity/node_modules/cborg/lib/2bytes.js","./3string.js":"/node_modules/atproto-identity/node_modules/cborg/lib/3string.js","./4array.js":"/node_modules/atproto-identity/node_modules/cborg/lib/4array.js","./5map.js":"/node_modules/atproto-identity/node_modules/cborg/lib/5map.js","./6tag.js":"/node_modules/atproto-identity/node_modules/cborg/lib/6tag.js","./7float.js":"/node_modules/atproto-identity/node_modules/cborg/lib/7float.js","./bl.js":"/node_modules/atproto-identity/node_modules/cborg/lib/bl.js","./byte-utils.js":"/node_modules/atproto-identity/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/atproto-identity/node_modules/cborg/lib/common.js","./is.js":"/node_modules/atproto-identity/node_modules/cborg/lib/is.js","./jump.js":"/node_modules/atproto-identity/node_modules/cborg/lib/jump.js","./token.js":"/node_modules/atproto-identity/node_modules/cborg/lib/token.js"},"/node_modules/atproto-identity/node_modules/cborg/lib/is.js":{"#package":"/node_modules/atproto-identity/node_modules/cborg/package.json"},"/node_modules/atproto-identity/node_modules/cborg/lib/jump.js":{"#package":"/node_modules/atproto-identity/node_modules/cborg/package.json","./0uint.js":"/node_modules/atproto-identity/node_modules/cborg/lib/0uint.js","./1negint.js":"/node_modules/atproto-identity/node_modules/cborg/lib/1negint.js","./2bytes.js":"/node_modules/atproto-identity/node_modules/cborg/lib/2bytes.js","./3string.js":"/node_modules/atproto-identity/node_modules/cborg/lib/3string.js","./4array.js":"/node_modules/atproto-identity/node_modules/cborg/lib/4array.js","./5map.js":"/node_modules/atproto-identity/node_modules/cborg/lib/5map.js","./6tag.js":"/node_modules/atproto-identity/node_modules/cborg/lib/6tag.js","./7float.js":"/node_modules/atproto-identity/node_modules/cborg/lib/7float.js","./byte-utils.js":"/node_modules/atproto-identity/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/atproto-identity/node_modules/cborg/lib/common.js","./token.js":"/node_modules/atproto-identity/node_modules/cborg/lib/token.js"},"/node_modules/atproto-identity/node_modules/cborg/lib/tagged.js":{"#package":"/node_modules/atproto-identity/node_modules/cborg/package.json"},"/node_modules/atproto-identity/node_modules/cborg/lib/token.js":{"#package":"/node_modules/atproto-identity/node_modules/cborg/package.json"},"/node_modules/atproto-identity/node_modules/cborg/package.json":{},"/node_modules/atproto-identity/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/atproto-identity/node_modules/compact-encoding/package.json"},"/node_modules/atproto-identity/node_modules/compact-encoding/index.js":{"#package":"/node_modules/atproto-identity/node_modules/compact-encoding/package.json","./endian":"/node_modules/atproto-identity/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/atproto-identity/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/atproto-identity/node_modules/compact-encoding/raw.js","b4a":"/node_modules/atproto-identity/node_modules/b4a/index.js"},"/node_modules/atproto-identity/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/atproto-identity/node_modules/compact-encoding/package.json"},"/node_modules/atproto-identity/node_modules/compact-encoding/package.json":{},"/node_modules/atproto-identity/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/atproto-identity/node_modules/compact-encoding/package.json","./endian":"/node_modules/atproto-identity/node_modules/compact-encoding/endian.js","b4a":"/node_modules/atproto-identity/node_modules/b4a/index.js"},"/node_modules/atproto-identity/node_modules/hypercore-crypto/index.js":{"#package":"/node_modules/atproto-identity/node_modules/hypercore-crypto/package.json","b4a":"/node_modules/atproto-identity/node_modules/b4a/index.js","compact-encoding":"/node_modules/atproto-identity/node_modules/compact-encoding/index.js","sodium-universal":"/node_modules/atproto-identity/node_modules/sodium-universal/index.js"},"/node_modules/atproto-identity/node_modules/hypercore-crypto/package.json":{},"/node_modules/atproto-identity/node_modules/keet-identity-key/index.js":{"#package":"/node_modules/atproto-identity/node_modules/keet-identity-key/package.json","./lib/crypto":"/node_modules/atproto-identity/node_modules/keet-identity-key/lib/crypto.js","./lib/encoding":"/node_modules/atproto-identity/node_modules/keet-identity-key/lib/encoding.js","./lib/keychain":"/node_modules/atproto-identity/node_modules/keet-identity-key/lib/keychain.js","b4a":"/node_modules/atproto-identity/node_modules/b4a/index.js","compact-encoding":"/node_modules/atproto-identity/node_modules/compact-encoding/index.js"},"/node_modules/atproto-identity/node_modules/keet-identity-key/lib/crypto.js":{"#package":"/node_modules/atproto-identity/node_modules/keet-identity-key/package.json","b4a":"/node_modules/atproto-identity/node_modules/b4a/index.js","sodium-universal":"/node_modules/atproto-identity/node_modules/sodium-universal/index.js"},"/node_modules/atproto-identity/node_modules/keet-identity-key/lib/encoding.js":{"#package":"/node_modules/atproto-identity/node_modules/keet-identity-key/package.json","compact-encoding":"/node_modules/atproto-identity/node_modules/compact-encoding/index.js"},"/node_modules/atproto-identity/node_modules/keet-identity-key/lib/keychain.js":{"#package":"/node_modules/atproto-identity/node_modules/keet-identity-key/package.json","./crypto":"/node_modules/atproto-identity/node_modules/keet-identity-key/lib/crypto.js","b4a":"/node_modules/atproto-identity/node_modules/b4a/index.js","bip39-mnemonic":"/node_modules/atproto-identity/node_modules/bip39-mnemonic/index.js","compact-encoding":"/node_modules/atproto-identity/node_modules/compact-encoding/index.js","nanoassert":"/node_modules/atproto-identity/node_modules/nanoassert/index.js","sodium-hmac":"/node_modules/atproto-identity/node_modules/sodium-hmac/index.js","sodium-universal":"/node_modules/atproto-identity/node_modules/sodium-universal/index.js"},"/node_modules/atproto-identity/node_modules/keet-identity-key/package.json":{},"/node_modules/atproto-identity/node_modules/multiformats/dist/src/bases/base.js":{"#package":"/node_modules/atproto-identity/node_modules/multiformats/package.json","../bytes.js":"/node_modules/atproto-identity/node_modules/multiformats/dist/src/bytes.js","../vendor/base-x.js":"/node_modules/atproto-identity/node_modules/multiformats/dist/src/vendor/base-x.js"},"/node_modules/atproto-identity/node_modules/multiformats/dist/src/bases/base32.js":{"#package":"/node_modules/atproto-identity/node_modules/multiformats/package.json","./base.js":"/node_modules/atproto-identity/node_modules/multiformats/dist/src/bases/base.js"},"/node_modules/atproto-identity/node_modules/multiformats/dist/src/bases/base36.js":{"#package":"/node_modules/atproto-identity/node_modules/multiformats/package.json","./base.js":"/node_modules/atproto-identity/node_modules/multiformats/dist/src/bases/base.js"},"/node_modules/atproto-identity/node_modules/multiformats/dist/src/bases/base58.js":{"#package":"/node_modules/atproto-identity/node_modules/multiformats/package.json","./base.js":"/node_modules/atproto-identity/node_modules/multiformats/dist/src/bases/base.js"},"/node_modules/atproto-identity/node_modules/multiformats/dist/src/bases/base64.js":{"#package":"/node_modules/atproto-identity/node_modules/multiformats/package.json","./base.js":"/node_modules/atproto-identity/node_modules/multiformats/dist/src/bases/base.js"},"/node_modules/atproto-identity/node_modules/multiformats/dist/src/bytes.js":{"#package":"/node_modules/atproto-identity/node_modules/multiformats/package.json"},"/node_modules/atproto-identity/node_modules/multiformats/dist/src/cid.js":{"#package":"/node_modules/atproto-identity/node_modules/multiformats/package.json","./bases/base32.js":"/node_modules/atproto-identity/node_modules/multiformats/dist/src/bases/base32.js","./bases/base36.js":"/node_modules/atproto-identity/node_modules/multiformats/dist/src/bases/base36.js","./bases/base58.js":"/node_modules/atproto-identity/node_modules/multiformats/dist/src/bases/base58.js","./bytes.js":"/node_modules/atproto-identity/node_modules/multiformats/dist/src/bytes.js","./hashes/digest.js":"/node_modules/atproto-identity/node_modules/multiformats/dist/src/hashes/digest.js","./link/interface.js":"/node_modules/atproto-identity/node_modules/multiformats/dist/src/link/interface.js","./varint.js":"/node_modules/atproto-identity/node_modules/multiformats/dist/src/varint.js"},"/node_modules/atproto-identity/node_modules/multiformats/dist/src/hashes/digest.js":{"#package":"/node_modules/atproto-identity/node_modules/multiformats/package.json","../bytes.js":"/node_modules/atproto-identity/node_modules/multiformats/dist/src/bytes.js","../varint.js":"/node_modules/atproto-identity/node_modules/multiformats/dist/src/varint.js"},"/node_modules/atproto-identity/node_modules/multiformats/dist/src/link/interface.js":{"#package":"/node_modules/atproto-identity/node_modules/multiformats/package.json"},"/node_modules/atproto-identity/node_modules/multiformats/dist/src/varint.js":{"#package":"/node_modules/atproto-identity/node_modules/multiformats/package.json","./vendor/varint.js":"/node_modules/atproto-identity/node_modules/multiformats/dist/src/vendor/varint.js"},"/node_modules/atproto-identity/node_modules/multiformats/dist/src/vendor/base-x.js":{"#package":"/node_modules/atproto-identity/node_modules/multiformats/package.json"},"/node_modules/atproto-identity/node_modules/multiformats/dist/src/vendor/varint.js":{"#package":"/node_modules/atproto-identity/node_modules/multiformats/package.json"},"/node_modules/atproto-identity/node_modules/multiformats/package.json":{},"/node_modules/atproto-identity/node_modules/nanoassert/index.js":{"#package":"/node_modules/atproto-identity/node_modules/nanoassert/package.json"},"/node_modules/atproto-identity/node_modules/nanoassert/package.json":{},"/node_modules/atproto-identity/node_modules/require-addon/lib/bare.js":{"#package":"/node_modules/atproto-identity/node_modules/require-addon/package.json"},"/node_modules/atproto-identity/node_modules/require-addon/package.json":{},"/node_modules/atproto-identity/node_modules/sodium-hmac/hash/sha256.js":{"#package":"/node_modules/atproto-identity/node_modules/sodium-hmac/package.json","sodium-universal":"/node_modules/atproto-identity/node_modules/sodium-universal/index.js"},"/node_modules/atproto-identity/node_modules/sodium-hmac/hash/sha512.js":{"#package":"/node_modules/atproto-identity/node_modules/sodium-hmac/package.json","sodium-universal":"/node_modules/atproto-identity/node_modules/sodium-universal/index.js"},"/node_modules/atproto-identity/node_modules/sodium-hmac/index.js":{"#package":"/node_modules/atproto-identity/node_modules/sodium-hmac/package.json","./hash/sha256":"/node_modules/atproto-identity/node_modules/sodium-hmac/hash/sha256.js","./hash/sha512":"/node_modules/atproto-identity/node_modules/sodium-hmac/hash/sha512.js","b4a":"/node_modules/atproto-identity/node_modules/b4a/index.js"},"/node_modules/atproto-identity/node_modules/sodium-hmac/package.json":{},"/node_modules/atproto-identity/node_modules/sodium-native/binding.js":{"#package":"/node_modules/atproto-identity/node_modules/sodium-native/package.json",".":"linked:libsodium-native.5.1.0.so","require-addon":"/node_modules/atproto-identity/node_modules/require-addon/lib/bare.js"},"/node_modules/atproto-identity/node_modules/sodium-native/index.js":{"#package":"/node_modules/atproto-identity/node_modules/sodium-native/package.json","./binding":"/node_modules/atproto-identity/node_modules/sodium-native/binding.js","assert":"/node_modules/atproto-identity/node_modules/bare-assert/index.js","which-runtime":"/node_modules/atproto-identity/node_modules/which-runtime/index.js"},"/node_modules/atproto-identity/node_modules/sodium-native/package.json":{},"/node_modules/atproto-identity/node_modules/sodium-universal/index.js":{"#package":"/node_modules/atproto-identity/node_modules/sodium-universal/package.json","sodium-native":"/node_modules/atproto-identity/node_modules/sodium-native/index.js"},"/node_modules/atproto-identity/node_modules/sodium-universal/package.json":{},"/node_modules/atproto-identity/node_modules/which-runtime/index.js":{"#package":"/node_modules/atproto-identity/node_modules/which-runtime/package.json"},"/node_modules/atproto-identity/node_modules/which-runtime/package.json":{},"/node_modules/atproto-identity/package.json":{},"/node_modules/atproto-store/lib/tid.js":{"#package":"/node_modules/atproto-store/package.json"},"/node_modules/atproto-store/package.json":{},"/node_modules/b4a/index.js":{"#package":"/node_modules/b4a/package.json"},"/node_modules/b4a/package.json":{},"/node_modules/bare-abort/binding.js":{"#package":"/node_modules/bare-abort/package.json",".":"linked:libbare-abort.2.0.13.so"},"/node_modules/bare-abort/index.js":{"#package":"/node_modules/bare-abort/package.json","./binding":"/node_modules/bare-abort/binding.js"},"/node_modules/bare-abort/package.json":{},"/node_modules/bare-ansi-escapes/index.js":{"#package":"/node_modules/bare-ansi-escapes/package.json"},"/node_modules/bare-ansi-escapes/package.json":{},"/node_modules/bare-assert/index.js":{"#package":"/node_modules/bare-assert/package.json","bare-inspect":"/node_modules/bare-inspect/index.js"},"/node_modules/bare-assert/package.json":{},"/node_modules/bare-buffer/binding.js":{"#package":"/node_modules/bare-buffer/package.json",".":"linked:libbare-buffer.3.6.2.so"},"/node_modules/bare-buffer/index.js":{"#package":"/node_modules/bare-buffer/package.json","./binding":"/node_modules/bare-buffer/binding.js","./lib/ascii":"/node_modules/bare-buffer/lib/ascii.js","./lib/base64":"/node_modules/bare-buffer/lib/base64.js","./lib/base64url":"/node_modules/bare-buffer/lib/base64url.js","./lib/constants":"/node_modules/bare-buffer/lib/constants.js","./lib/hex":"/node_modules/bare-buffer/lib/hex.js","./lib/latin1":"/node_modules/bare-buffer/lib/latin1.js","./lib/utf16le":"/node_modules/bare-buffer/lib/utf16le.js","./lib/utf8":"/node_modules/bare-buffer/lib/utf8.js"},"/node_modules/bare-buffer/lib/ascii.js":{"#package":"/node_modules/bare-buffer/package.json","../binding":"/node_modules/bare-buffer/binding.js"},"/node_modules/bare-buffer/lib/base64.js":{"#package":"/node_modules/bare-buffer/package.json","../binding":"/node_modules/bare-buffer/binding.js"},"/node_modules/bare-buffer/lib/base64url.js":{"#package":"/node_modules/bare-buffer/package.json","../binding":"/node_modules/bare-buffer/binding.js"},"/node_modules/bare-buffer/lib/constants.js":{"#package":"/node_modules/bare-buffer/package.json","../binding":"/node_modules/bare-buffer/binding.js"},"/node_modules/bare-buffer/lib/hex.js":{"#package":"/node_modules/bare-buffer/package.json","../binding":"/node_modules/bare-buffer/binding.js"},"/node_modules/bare-buffer/lib/latin1.js":{"#package":"/node_modules/bare-buffer/package.json","../binding":"/node_modules/bare-buffer/binding.js"},"/node_modules/bare-buffer/lib/utf16le.js":{"#package":"/node_modules/bare-buffer/package.json","../binding":"/node_modules/bare-buffer/binding.js"},"/node_modules/bare-buffer/lib/utf8.js":{"#package":"/node_modules/bare-buffer/package.json","../binding":"/node_modules/bare-buffer/binding.js"},"/node_modules/bare-buffer/package.json":{},"/node_modules/bare-dns/binding.js":{"#package":"/node_modules/bare-dns/package.json",".":"linked:libbare-dns.2.2.0.so"},"/node_modules/bare-dns/index.js":{"#package":"/node_modules/bare-dns/package.json","./binding":"/node_modules/bare-dns/binding.js","./lib/constants":"/node_modules/bare-dns/lib/constants.js","./lib/errors":"/node_modules/bare-dns/lib/errors.js","./lib/promises":"/node_modules/bare-dns/lib/promises.js","./lib/resolver":"/node_modules/bare-dns/lib/resolver.js"},"/node_modules/bare-dns/lib/constants.js":{"#package":"/node_modules/bare-dns/package.json"},"/node_modules/bare-dns/lib/errors.js":{"#package":"/node_modules/bare-dns/package.json","./constants":"/node_modules/bare-dns/lib/constants.js"},"/node_modules/bare-dns/lib/promises.js":{"#package":"/node_modules/bare-dns/package.json","../":"/node_modules/bare-dns/index.js","./constants":"/node_modules/bare-dns/lib/constants.js","./errors":"/node_modules/bare-dns/lib/errors.js","./resolver":"/node_modules/bare-dns/lib/resolver.js"},"/node_modules/bare-dns/lib/records.js":{"#package":"/node_modules/bare-dns/package.json"},"/node_modules/bare-dns/lib/resolver.js":{"#package":"/node_modules/bare-dns/package.json","../binding":"/node_modules/bare-dns/binding.js","./constants":"/node_modules/bare-dns/lib/constants.js","./errors":"/node_modules/bare-dns/lib/errors.js","./records":"/node_modules/bare-dns/lib/records.js"},"/node_modules/bare-dns/package.json":{},"/node_modules/bare-env/index.js":{"#package":"/node_modules/bare-env/package.json","bare-os":"/node_modules/bare-os/index.js"},"/node_modules/bare-env/package.json":{},"/node_modules/bare-events/index.js":{"#package":"/node_modules/bare-events/package.json","./lib/errors":"/node_modules/bare-events/lib/errors.js"},"/node_modules/bare-events/lib/errors.js":{"#package":"/node_modules/bare-events/package.json"},"/node_modules/bare-events/package.json":{},"/node_modules/bare-fetch/index.js":{"#package":"/node_modules/bare-fetch/package.json","./lib/errors":"/node_modules/bare-fetch/lib/errors.js","./lib/headers":"/node_modules/bare-fetch/lib/headers.js","./lib/request":"/node_modules/bare-fetch/lib/request.js","./lib/response":"/node_modules/bare-fetch/lib/response.js","./lib/response-stream":"/node_modules/bare-fetch/lib/response-stream.js","bare-http1":"/node_modules/bare-http1/index.js","bare-https":"/node_modules/bare-https/index.js","bare-stream/web":"/node_modules/bare-stream/web.js"},"/node_modules/bare-fetch/lib/body.js":{"#package":"/node_modules/bare-fetch/package.json","./errors":"/node_modules/bare-fetch/lib/errors.js","./headers":"/node_modules/bare-fetch/lib/headers.js","bare-form-data":"/node_modules/bare-form-data/index.js","bare-stream/web":"/node_modules/bare-stream/web.js","bare-url":"/node_modules/bare-url/index.js"},"/node_modules/bare-fetch/lib/errors.js":{"#package":"/node_modules/bare-fetch/package.json"},"/node_modules/bare-fetch/lib/headers.js":{"#package":"/node_modules/bare-fetch/package.json","./errors":"/node_modules/bare-fetch/lib/errors.js","bare-mime":"/node_modules/bare-mime/index.js"},"/node_modules/bare-fetch/lib/request.js":{"#package":"/node_modules/bare-fetch/package.json","./body":"/node_modules/bare-fetch/lib/body.js","./errors":"/node_modules/bare-fetch/lib/errors.js","./headers":"/node_modules/bare-fetch/lib/headers.js","bare-url":"/node_modules/bare-url/index.js"},"/node_modules/bare-fetch/lib/response-stream.js":{"#package":"/node_modules/bare-fetch/package.json","bare-stream":"/node_modules/bare-stream/index.js","bare-zlib":"/node_modules/bare-zlib/index.js"},"/node_modules/bare-fetch/lib/response.js":{"#package":"/node_modules/bare-fetch/package.json","./body":"/node_modules/bare-fetch/lib/body.js","./errors":"/node_modules/bare-fetch/lib/errors.js","./headers":"/node_modules/bare-fetch/lib/headers.js"},"/node_modules/bare-fetch/package.json":{},"/node_modules/bare-form-data/index.js":{"#package":"/node_modules/bare-form-data/package.json","./lib/errors":"/node_modules/bare-form-data/lib/errors.js","bare-buffer":"/node_modules/bare-buffer/index.js","bare-stream/web":"/node_modules/bare-stream/web.js"},"/node_modules/bare-form-data/lib/errors.js":{"#package":"/node_modules/bare-form-data/package.json"},"/node_modules/bare-form-data/package.json":{},"/node_modules/bare-fs/binding.js":{"#package":"/node_modules/bare-fs/package.json",".":"linked:libbare-fs.4.7.4.so"},"/node_modules/bare-fs/index.js":{"#package":"/node_modules/bare-fs/package.json","./binding":"/node_modules/bare-fs/binding.js","./lib/constants":"/node_modules/bare-fs/lib/constants.js","./lib/errors":"/node_modules/bare-fs/lib/errors.js","./promises":"/node_modules/bare-fs/promises.js","bare-events":"/node_modules/bare-events/index.js","bare-path":"/node_modules/bare-path/index.js","bare-stream":"/node_modules/bare-stream/index.js","bare-url":"/node_modules/bare-url/index.js","fast-fifo":"/node_modules/fast-fifo/index.js"},"/node_modules/bare-fs/lib/constants.js":{"#package":"/node_modules/bare-fs/package.json","../binding":"/node_modules/bare-fs/binding.js"},"/node_modules/bare-fs/lib/errors.js":{"#package":"/node_modules/bare-fs/package.json","../binding":"/node_modules/bare-fs/binding.js"},"/node_modules/bare-fs/package.json":{},"/node_modules/bare-fs/promises.js":{"#package":"/node_modules/bare-fs/package.json",".":"/node_modules/bare-fs/index.js","bare-events":"/node_modules/bare-events/index.js"},"/node_modules/bare-hrtime/binding.js":{"#package":"/node_modules/bare-hrtime/package.json",".":"linked:libbare-hrtime.2.1.1.so"},"/node_modules/bare-hrtime/index.js":{"#package":"/node_modules/bare-hrtime/package.json","./binding":"/node_modules/bare-hrtime/binding.js"},"/node_modules/bare-hrtime/package.json":{},"/node_modules/bare-http-parser/index.js":{"#package":"/node_modules/bare-http-parser/package.json","./lib/errors":"/node_modules/bare-http-parser/lib/errors.js"},"/node_modules/bare-http-parser/lib/errors.js":{"#package":"/node_modules/bare-http-parser/package.json"},"/node_modules/bare-http-parser/package.json":{},"/node_modules/bare-http1/index.js":{"#package":"/node_modules/bare-http1/package.json","./lib/agent":"/node_modules/bare-http1/lib/agent.js","./lib/client-connection":"/node_modules/bare-http1/lib/client-connection.js","./lib/client-request":"/node_modules/bare-http1/lib/client-request.js","./lib/constants":"/node_modules/bare-http1/lib/constants.js","./lib/errors":"/node_modules/bare-http1/lib/errors.js","./lib/incoming-message":"/node_modules/bare-http1/lib/incoming-message.js","./lib/outgoing-message":"/node_modules/bare-http1/lib/outgoing-message.js","./lib/server":"/node_modules/bare-http1/lib/server.js","./lib/server-connection":"/node_modules/bare-http1/lib/server-connection.js","./lib/server-response":"/node_modules/bare-http1/lib/server-response.js"},"/node_modules/bare-http1/lib/agent.js":{"#package":"/node_modules/bare-http1/package.json","./client-connection":"/node_modules/bare-http1/lib/client-connection.js","./errors":"/node_modules/bare-http1/lib/errors.js","bare-events":"/node_modules/bare-events/index.js","bare-tcp":"/node_modules/bare-tcp/index.js"},"/node_modules/bare-http1/lib/client-connection.js":{"#package":"/node_modules/bare-http1/package.json","./errors":"/node_modules/bare-http1/lib/errors.js","./incoming-message":"/node_modules/bare-http1/lib/incoming-message.js","bare-http-parser":"/node_modules/bare-http-parser/index.js"},"/node_modules/bare-http1/lib/client-request.js":{"#package":"/node_modules/bare-http1/package.json","./agent":"/node_modules/bare-http1/lib/agent.js","./outgoing-message":"/node_modules/bare-http1/lib/outgoing-message.js","./validate":"/node_modules/bare-http1/lib/validate.js"},"/node_modules/bare-http1/lib/constants.js":{"#package":"/node_modules/bare-http1/package.json"},"/node_modules/bare-http1/lib/errors.js":{"#package":"/node_modules/bare-http1/package.json"},"/node_modules/bare-http1/lib/incoming-message.js":{"#package":"/node_modules/bare-http1/package.json","bare-stream":"/node_modules/bare-stream/index.js"},"/node_modules/bare-http1/lib/outgoing-message.js":{"#package":"/node_modules/bare-http1/package.json","./errors":"/node_modules/bare-http1/lib/errors.js","./validate":"/node_modules/bare-http1/lib/validate.js","bare-stream":"/node_modules/bare-stream/index.js"},"/node_modules/bare-http1/lib/server-connection.js":{"#package":"/node_modules/bare-http1/package.json","./incoming-message":"/node_modules/bare-http1/lib/incoming-message.js","./server-response":"/node_modules/bare-http1/lib/server-response.js","bare-http-parser":"/node_modules/bare-http-parser/index.js","bare-stream":"/node_modules/bare-stream/index.js"},"/node_modules/bare-http1/lib/server-response.js":{"#package":"/node_modules/bare-http1/package.json","./constants":"/node_modules/bare-http1/lib/constants.js","./outgoing-message":"/node_modules/bare-http1/lib/outgoing-message.js","./validate":"/node_modules/bare-http1/lib/validate.js","bare-stream":"/node_modules/bare-stream/index.js"},"/node_modules/bare-http1/lib/server.js":{"#package":"/node_modules/bare-http1/package.json","./server-connection":"/node_modules/bare-http1/lib/server-connection.js","bare-tcp":"/node_modules/bare-tcp/index.js"},"/node_modules/bare-http1/lib/validate.js":{"#package":"/node_modules/bare-http1/package.json","./errors":"/node_modules/bare-http1/lib/errors.js"},"/node_modules/bare-http1/package.json":{},"/node_modules/bare-https/index.js":{"#package":"/node_modules/bare-https/package.json","./lib/agent":"/node_modules/bare-https/lib/agent.js","./lib/client-request":"/node_modules/bare-https/lib/client-request.js","./lib/server":"/node_modules/bare-https/lib/server.js"},"/node_modules/bare-https/lib/agent.js":{"#package":"/node_modules/bare-https/package.json","./socket":"/node_modules/bare-https/lib/socket.js","bare-http1":"/node_modules/bare-http1/index.js"},"/node_modules/bare-https/lib/client-request.js":{"#package":"/node_modules/bare-https/package.json","./agent":"/node_modules/bare-https/lib/agent.js","bare-http1":"/node_modules/bare-http1/index.js"},"/node_modules/bare-https/lib/server.js":{"#package":"/node_modules/bare-https/package.json","./socket":"/node_modules/bare-https/lib/socket.js","bare-http1":"/node_modules/bare-http1/index.js","bare-tcp":"/node_modules/bare-tcp/index.js"},"/node_modules/bare-https/lib/socket.js":{"#package":"/node_modules/bare-https/package.json","bare-tls":"/node_modules/bare-tls/index.js"},"/node_modules/bare-https/package.json":{},"/node_modules/bare-inspect/binding.js":{"#package":"/node_modules/bare-inspect/package.json",".":"linked:libbare-inspect.3.1.4.so"},"/node_modules/bare-inspect/index.js":{"#package":"/node_modules/bare-inspect/package.json","./binding":"/node_modules/bare-inspect/binding.js","bare-ansi-escapes":"/node_modules/bare-ansi-escapes/index.js","bare-type":"/node_modules/bare-type/index.js"},"/node_modules/bare-inspect/package.json":{},"/node_modules/bare-mime/index.js":{"#package":"/node_modules/bare-mime/package.json"},"/node_modules/bare-mime/package.json":{},"/node_modules/bare-net/index.js":{"#package":"/node_modules/bare-net/package.json","./lib/constants":"/node_modules/bare-net/lib/constants.js","./lib/errors":"/node_modules/bare-net/lib/errors.js","bare-events":"/node_modules/bare-events/index.js","bare-pipe":"/node_modules/bare-pipe/index.js","bare-stream":"/node_modules/bare-stream/index.js","bare-tcp":"/node_modules/bare-tcp/index.js"},"/node_modules/bare-net/lib/constants.js":{"#package":"/node_modules/bare-net/package.json"},"/node_modules/bare-net/lib/errors.js":{"#package":"/node_modules/bare-net/package.json"},"/node_modules/bare-net/package.json":{},"/node_modules/bare-os/binding.js":{"#package":"/node_modules/bare-os/package.json",".":"linked:libbare-os.3.9.3.so"},"/node_modules/bare-os/index.js":{"#package":"/node_modules/bare-os/package.json","./binding":"/node_modules/bare-os/binding.js","./lib/constants":"/node_modules/bare-os/lib/constants.js","./lib/errors":"/node_modules/bare-os/lib/errors.js"},"/node_modules/bare-os/lib/constants.js":{"#package":"/node_modules/bare-os/package.json","../binding":"/node_modules/bare-os/binding.js"},"/node_modules/bare-os/lib/errors.js":{"#package":"/node_modules/bare-os/package.json"},"/node_modules/bare-os/package.json":{},"/node_modules/bare-path/binding.js":{"#package":"/node_modules/bare-path/package.json",".":"linked:libbare-path.3.1.1.so"},"/node_modules/bare-path/index.js":{"#package":"/node_modules/bare-path/package.json","./lib/posix":"/node_modules/bare-path/lib/posix.js","./lib/win32":"/node_modules/bare-path/lib/win32.js"},"/node_modules/bare-path/lib/constants.js":{"#package":"/node_modules/bare-path/package.json"},"/node_modules/bare-path/lib/posix.js":{"#package":"/node_modules/bare-path/package.json","../binding":"/node_modules/bare-path/binding.js","./constants":"/node_modules/bare-path/lib/constants.js","./shared":"/node_modules/bare-path/lib/shared.js","./win32":"/node_modules/bare-path/lib/win32.js"},"/node_modules/bare-path/lib/shared.js":{"#package":"/node_modules/bare-path/package.json","./constants":"/node_modules/bare-path/lib/constants.js"},"/node_modules/bare-path/lib/win32.js":{"#package":"/node_modules/bare-path/package.json","../binding":"/node_modules/bare-path/binding.js","./constants":"/node_modules/bare-path/lib/constants.js","./posix":"/node_modules/bare-path/lib/posix.js","./shared":"/node_modules/bare-path/lib/shared.js"},"/node_modules/bare-path/package.json":{},"/node_modules/bare-pipe/binding.js":{"#package":"/node_modules/bare-pipe/package.json",".":"linked:libbare-pipe.4.2.3.so"},"/node_modules/bare-pipe/index.js":{"#package":"/node_modules/bare-pipe/package.json","./binding":"/node_modules/bare-pipe/binding.js","./lib/constants":"/node_modules/bare-pipe/lib/constants.js","./lib/errors":"/node_modules/bare-pipe/lib/errors.js","bare-events":"/node_modules/bare-events/index.js","bare-stream":"/node_modules/bare-stream/index.js"},"/node_modules/bare-pipe/lib/constants.js":{"#package":"/node_modules/bare-pipe/package.json","../binding":"/node_modules/bare-pipe/binding.js"},"/node_modules/bare-pipe/lib/errors.js":{"#package":"/node_modules/bare-pipe/package.json"},"/node_modules/bare-pipe/package.json":{},"/node_modules/bare-posix/package.json":{},"/node_modules/bare-posix/unsupported.js":{"#package":"/node_modules/bare-posix/package.json"},"/node_modules/bare-process/index.js":{"#package":"/node_modules/bare-process/package.json","bare-abort":"/node_modules/bare-abort/index.js","bare-env":"/node_modules/bare-env/index.js","bare-events":"/node_modules/bare-events/index.js","bare-hrtime":"/node_modules/bare-hrtime/index.js","bare-os":"/node_modules/bare-os/index.js","bare-posix":"/node_modules/bare-posix/unsupported.js","bare-signals":"/node_modules/bare-signals/index.js","bare-stdio":"/node_modules/bare-stdio/index.js"},"/node_modules/bare-process/package.json":{},"/node_modules/bare-signals/binding.js":{"#package":"/node_modules/bare-signals/package.json",".":"linked:libbare-signals.5.0.0.so"},"/node_modules/bare-signals/index.js":{"#package":"/node_modules/bare-signals/package.json","./binding":"/node_modules/bare-signals/binding.js","./lib/emitter":"/node_modules/bare-signals/lib/emitter.js","./lib/errors":"/node_modules/bare-signals/lib/errors.js","bare-events":"/node_modules/bare-events/index.js"},"/node_modules/bare-signals/lib/emitter.js":{"#package":"/node_modules/bare-signals/package.json","..":"/node_modules/bare-signals/index.js","bare-events":"/node_modules/bare-events/index.js"},"/node_modules/bare-signals/lib/errors.js":{"#package":"/node_modules/bare-signals/package.json"},"/node_modules/bare-signals/package.json":{},"/node_modules/bare-stdio/binding.js":{"#package":"/node_modules/bare-stdio/package.json",".":"linked:libbare-stdio.1.0.3.so"},"/node_modules/bare-stdio/index.js":{"#package":"/node_modules/bare-stdio/package.json","./binding":"/node_modules/bare-stdio/binding.js","bare-fs":"/node_modules/bare-fs/index.js","bare-pipe":"/node_modules/bare-pipe/index.js","bare-tty":"/node_modules/bare-tty/index.js"},"/node_modules/bare-stdio/package.json":{},"/node_modules/bare-stream/index.js":{"#package":"/node_modules/bare-stream/package.json","./web":"/node_modules/bare-stream/web.js","b4a":"/node_modules/b4a/index.js","streamx":"/node_modules/streamx/index.js"},"/node_modules/bare-stream/package.json":{},"/node_modules/bare-stream/web.js":{"#package":"/node_modules/bare-stream/package.json","streamx":"/node_modules/streamx/index.js","teex":"/node_modules/teex/index.js"},"/node_modules/bare-tcp/binding.js":{"#package":"/node_modules/bare-tcp/package.json",".":"linked:libbare-tcp.2.5.4.so"},"/node_modules/bare-tcp/index.js":{"#package":"/node_modules/bare-tcp/package.json","./binding":"/node_modules/bare-tcp/binding.js","./lib/constants":"/node_modules/bare-tcp/lib/constants.js","./lib/errors":"/node_modules/bare-tcp/lib/errors.js","./lib/ip":"/node_modules/bare-tcp/lib/ip.js","bare-dns":"/node_modules/bare-dns/index.js","bare-events":"/node_modules/bare-events/index.js","bare-stream":"/node_modules/bare-stream/index.js"},"/node_modules/bare-tcp/lib/constants.js":{"#package":"/node_modules/bare-tcp/package.json"},"/node_modules/bare-tcp/lib/errors.js":{"#package":"/node_modules/bare-tcp/package.json"},"/node_modules/bare-tcp/lib/ip.js":{"#package":"/node_modules/bare-tcp/package.json"},"/node_modules/bare-tcp/package.json":{},"/node_modules/bare-tls/binding.js":{"#package":"/node_modules/bare-tls/package.json",".":"linked:libbare-tls.3.1.8.so"},"/node_modules/bare-tls/index.js":{"#package":"/node_modules/bare-tls/package.json","./binding":"/node_modules/bare-tls/binding.js","./lib/constants":"/node_modules/bare-tls/lib/constants.js","./lib/errors":"/node_modules/bare-tls/lib/errors.js","./net":"/node_modules/bare-tls/net.js","bare-stream":"/node_modules/bare-stream/index.js"},"/node_modules/bare-tls/lib/constants.js":{"#package":"/node_modules/bare-tls/package.json"},"/node_modules/bare-tls/lib/errors.js":{"#package":"/node_modules/bare-tls/package.json"},"/node_modules/bare-tls/net.js":{"#package":"/node_modules/bare-tls/package.json","bare-events":"/node_modules/bare-events/index.js","bare-net":"/node_modules/bare-net/index.js","bare-tls":"/node_modules/bare-tls/index.js"},"/node_modules/bare-tls/package.json":{},"/node_modules/bare-tty/binding.js":{"#package":"/node_modules/bare-tty/package.json",".":"linked:libbare-tty.5.1.2.so"},"/node_modules/bare-tty/index.js":{"#package":"/node_modules/bare-tty/package.json","./binding":"/node_modules/bare-tty/binding.js","./lib/constants":"/node_modules/bare-tty/lib/constants.js","bare-signals":"/node_modules/bare-signals/index.js","bare-stream":"/node_modules/bare-stream/index.js"},"/node_modules/bare-tty/lib/constants.js":{"#package":"/node_modules/bare-tty/package.json","../binding":"/node_modules/bare-tty/binding.js"},"/node_modules/bare-tty/package.json":{},"/node_modules/bare-type/binding.js":{"#package":"/node_modules/bare-type/package.json",".":"linked:libbare-type.1.1.0.so"},"/node_modules/bare-type/index.js":{"#package":"/node_modules/bare-type/package.json","./binding":"/node_modules/bare-type/binding.js"},"/node_modules/bare-type/package.json":{},"/node_modules/bare-url/binding.js":{"#package":"/node_modules/bare-url/package.json",".":"linked:libbare-url.2.5.1.so"},"/node_modules/bare-url/index.js":{"#package":"/node_modules/bare-url/package.json","./binding":"/node_modules/bare-url/binding.js","./lib/errors":"/node_modules/bare-url/lib/errors.js","./lib/url-search-params":"/node_modules/bare-url/lib/url-search-params.js","bare-path":"/node_modules/bare-path/index.js"},"/node_modules/bare-url/lib/errors.js":{"#package":"/node_modules/bare-url/package.json"},"/node_modules/bare-url/lib/url-search-params.js":{"#package":"/node_modules/bare-url/package.json","../binding":"/node_modules/bare-url/binding.js"},"/node_modules/bare-url/package.json":{},"/node_modules/bare-zlib/binding.js":{"#package":"/node_modules/bare-zlib/package.json",".":"linked:libbare-zlib.1.4.1.so"},"/node_modules/bare-zlib/index.js":{"#package":"/node_modules/bare-zlib/package.json","./binding":"/node_modules/bare-zlib/binding.js","./lib/constants":"/node_modules/bare-zlib/lib/constants.js","./lib/errors":"/node_modules/bare-zlib/lib/errors.js","bare-stream":"/node_modules/bare-stream/index.js"},"/node_modules/bare-zlib/lib/constants.js":{"#package":"/node_modules/bare-zlib/package.json","../binding":"/node_modules/bare-zlib/binding.js"},"/node_modules/bare-zlib/lib/errors.js":{"#package":"/node_modules/bare-zlib/package.json"},"/node_modules/bare-zlib/package.json":{},"/node_modules/blind-pairing-core/index.js":{"#package":"/node_modules/blind-pairing-core/package.json","./lib/errors":"/node_modules/blind-pairing-core/lib/errors.js","./lib/messages":"/node_modules/blind-pairing-core/lib/messages.js","b4a":"/node_modules/b4a/index.js","compact-encoding":"/node_modules/compact-encoding/index.js","events":"/node_modules/bare-events/index.js","hypercore-crypto":"/node_modules/hypercore-crypto/index.js","sodium-universal":"/node_modules/sodium-universal/index.js"},"/node_modules/blind-pairing-core/lib/errors.js":{"#package":"/node_modules/blind-pairing-core/package.json"},"/node_modules/blind-pairing-core/lib/messages.js":{"#package":"/node_modules/blind-pairing-core/package.json","bogon":"/node_modules/bogon/index.js","compact-encoding":"/node_modules/compact-encoding/index.js"},"/node_modules/blind-pairing-core/package.json":{},"/node_modules/bogon/index.js":{"#package":"/node_modules/bogon/package.json","b4a":"/node_modules/b4a/index.js","compact-encoding":"/node_modules/compact-encoding/index.js"},"/node_modules/bogon/package.json":{},"/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/compact-encoding/package.json"},"/node_modules/compact-encoding/index.js":{"#package":"/node_modules/compact-encoding/package.json","./endian":"/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/compact-encoding/raw.js","b4a":"/node_modules/b4a/index.js"},"/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/compact-encoding/package.json"},"/node_modules/compact-encoding/package.json":{},"/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/compact-encoding/package.json","./endian":"/node_modules/compact-encoding/endian.js","b4a":"/node_modules/b4a/index.js"},"/node_modules/events-universal/bare.js":{"#package":"/node_modules/events-universal/package.json","bare-events":"/node_modules/bare-events/index.js"},"/node_modules/events-universal/package.json":{},"/node_modules/fast-fifo/fixed-size.js":{"#package":"/node_modules/fast-fifo/package.json"},"/node_modules/fast-fifo/index.js":{"#package":"/node_modules/fast-fifo/package.json","./fixed-size":"/node_modules/fast-fifo/fixed-size.js"},"/node_modules/fast-fifo/package.json":{},"/node_modules/favela-web/bin/favela-web.js":{"#package":"/node_modules/favela-web/package.json","../lib/ap-followers.js":"/node_modules/favela-web/lib/ap-followers.js","../lib/ap-inbox.js":"/node_modules/favela-web/lib/ap-inbox.js","../lib/appview.js":"/node_modules/favela-web/lib/appview.js","../lib/auth.js":"/node_modules/favela-web/lib/auth.js","../lib/bare-globals.js":"/node_modules/favela-web/lib/bare-globals.js","../lib/blob-refs.js":"/node_modules/favela-web/lib/blob-refs.js","../lib/blob-serve.js":"/node_modules/favela-web/lib/blob-serve.js","../lib/bookmarks.js":"/node_modules/favela-web/lib/bookmarks.js","../lib/bounded-fetch.js":"/node_modules/favela-web/lib/bounded-fetch.js","../lib/check.js":"/node_modules/favela-web/lib/check.js","../lib/cli.js":"/node_modules/favela-web/lib/cli.js","../lib/communities.js":"/node_modules/favela-web/lib/communities.js","../lib/constellation.js":"/node_modules/favela-web/lib/constellation.js","../lib/dns-txt.js":"/node_modules/favela-web/lib/dns-txt.js","../lib/feed-reactor.js":"/node_modules/favela-web/lib/feed-reactor.js","../lib/feedgen.js":"/node_modules/favela-web/lib/feedgen.js","../lib/followers.js":"/node_modules/favela-web/lib/followers.js","../lib/fronts-diag.js":"/node_modules/favela-web/lib/fronts-diag.js","../lib/gate-policy.js":"/node_modules/favela-web/lib/gate-policy.js","../lib/handles.js":"/node_modules/favela-web/lib/handles.js","../lib/hosted-dids.js":"/node_modules/favela-web/lib/hosted-dids.js","../lib/inbound.js":"/node_modules/favela-web/lib/inbound.js","../lib/label-firehose.js":"/node_modules/favela-web/lib/label-firehose.js","../lib/labeler-export.js":"/node_modules/favela-web/lib/labeler-export.js","../lib/labeler.js":"/node_modules/favela-web/lib/labeler.js","../lib/labels.js":"/node_modules/favela-web/lib/labels.js","../lib/lens-import.js":"/node_modules/favela-web/lib/lens-import.js","../lib/lenses.js":"/node_modules/favela-web/lib/lenses.js","../lib/lists.js":"/node_modules/favela-web/lib/lists.js","../lib/mutes.js":"/node_modules/favela-web/lib/mutes.js","../lib/notifications.js":"/node_modules/favela-web/lib/notifications.js","../lib/pairing.js":"/node_modules/favela-web/lib/pairing.js","../lib/plc.js":"/node_modules/favela-web/lib/plc.js","../lib/postgate.js":"/node_modules/favela-web/lib/postgate.js","../lib/record-fetch.js":"/node_modules/favela-web/lib/record-fetch.js","../lib/render.js":"/node_modules/favela-web/lib/render.js","../lib/repair-bytes.js":"/node_modules/favela-web/lib/repair-bytes.js","../lib/repo-sync.js":"/node_modules/favela-web/lib/repo-sync.js","../lib/retention.js":"/node_modules/favela-web/lib/retention.js","../lib/roster.js":"/node_modules/favela-web/lib/roster.js","../lib/scopes.js":"/node_modules/favela-web/lib/scopes.js","../lib/sidecar.js":"/node_modules/favela-web/lib/sidecar.js","../lib/spacedust-socket.js":"/node_modules/favela-web/lib/spacedust-socket.js","../lib/static.js":"/node_modules/favela-web/lib/static.js","../lib/strongref.js":"/node_modules/favela-web/lib/strongref.js","../lib/threadgate.js":"/node_modules/favela-web/lib/threadgate.js","../lib/version.js":"/node_modules/favela-web/lib/version.js","../lib/writer.js":"/node_modules/favela-web/lib/writer.js","atproto-did-peer":"/node_modules/favela-web/node_modules/atproto-did-peer/index.js","atproto-identity/lib/discovery.js":"/node_modules/favela-web/node_modules/atproto-identity/lib/discovery.js","atproto-identity/lib/labels.js":"/node_modules/favela-web/node_modules/atproto-identity/lib/labels.js","atproto-identity/lib/plc-directory.js":"/node_modules/favela-web/node_modules/atproto-identity/lib/plc-directory.js","atproto-store/lib/corestore.js":"/node_modules/favela-web/node_modules/atproto-store/lib/corestore.js","atproto-store/lib/firehose.js":"/node_modules/favela-web/node_modules/atproto-store/lib/firehose.js","atproto-store/lib/overlay-repo-store.js":"/node_modules/favela-web/node_modules/atproto-store/lib/overlay-repo-store.js","atproto-store/lib/tid.js":"/node_modules/favela-web/node_modules/atproto-store/lib/tid.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","bare-fs":"/node_modules/favela-web/node_modules/bare-fs/index.js","bare-fs/promises":"/node_modules/favela-web/node_modules/bare-fs/promises.js","bare-http1":"/node_modules/favela-web/node_modules/bare-http1/index.js","bare-net":"/node_modules/favela-web/node_modules/bare-net/index.js","bare-os":"/node_modules/favela-web/node_modules/bare-os/index.js","bare-path":"/node_modules/favela-web/node_modules/bare-path/index.js","bare-ws":"/node_modules/favela-web/node_modules/bare-ws/index.js","corestore":"/node_modules/favela-web/node_modules/corestore/index.js","favela-community":"/node_modules/favela-web/node_modules/favela-community/index.js","hyper-proto-peer/lib/adopt.js":"/node_modules/favela-web/node_modules/hyper-proto-peer/lib/adopt.js","hyper-svc":"/node_modules/favela-web/node_modules/hyper-svc/index.js","hyperbee":"/node_modules/favela-web/node_modules/hyperbee/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/hypercore-crypto/index.js","hyperswarm":"/node_modules/favela-web/node_modules/hyperswarm/index.js"},"/node_modules/favela-web/lib/ap-followers.js":{"#package":"/node_modules/favela-web/package.json"},"/node_modules/favela-web/lib/ap-inbox.js":{"#package":"/node_modules/favela-web/package.json"},"/node_modules/favela-web/lib/appview.js":{"#package":"/node_modules/favela-web/package.json","./handles.js":"/node_modules/favela-web/lib/handles.js","./hosted-dids.js":"/node_modules/favela-web/lib/hosted-dids.js","./scopes.js":"/node_modules/favela-web/lib/scopes.js","./search.js":"/node_modules/favela-web/lib/search.js","@ipld/dag-cbor":"/node_modules/favela-web/node_modules/@ipld/dag-cbor/src/index.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","hyperbee":"/node_modules/favela-web/node_modules/hyperbee/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/hypercore-crypto/index.js"},"/node_modules/favela-web/lib/auth.js":{"#package":"/node_modules/favela-web/package.json","./sessions.js":"/node_modules/favela-web/lib/sessions.js","atproto-identity/lib/web-auth.js":"/node_modules/favela-web/node_modules/atproto-identity/lib/web-auth.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","hyper-identity/auth/providers/atproto":"/node_modules/favela-web/node_modules/hyper-identity/lib/auth/providers/atproto.js","hypercore-crypto":"/node_modules/favela-web/node_modules/hypercore-crypto/index.js"},"/node_modules/favela-web/lib/bare-globals.js":{"#package":"/node_modules/favela-web/package.json","bare-process":"/node_modules/favela-web/node_modules/bare-process/index.js"},"/node_modules/favela-web/lib/blob-refs.js":{"#package":"/node_modules/favela-web/package.json","./render.js":"/node_modules/favela-web/lib/render.js","atproto-repo/lib/cid.js":"/node_modules/favela-web/node_modules/atproto-repo/lib/cid.js"},"/node_modules/favela-web/lib/blob-serve.js":{"#package":"/node_modules/favela-web/package.json","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/hypercore-crypto/index.js"},"/node_modules/favela-web/lib/bookmarks.js":{"#package":"/node_modules/favela-web/package.json"},"/node_modules/favela-web/lib/bounded-fetch.js":{"#package":"/node_modules/favela-web/package.json","bare-fetch":"/node_modules/favela-web/node_modules/bare-fetch/index.js","bare-http1":"/node_modules/favela-web/node_modules/bare-http1/index.js","bare-https":"/node_modules/favela-web/node_modules/bare-https/index.js"},"/node_modules/favela-web/lib/check.js":{"#package":"/node_modules/favela-web/package.json"},"/node_modules/favela-web/lib/cli.js":{"#package":"/node_modules/favela-web/package.json","./blob-serve.js":"/node_modules/favela-web/lib/blob-serve.js","./conformance.js":"/node_modules/favela-web/lib/conformance.js","./pairing.js":"/node_modules/favela-web/lib/pairing.js","./repair-strongrefs.js":"/node_modules/favela-web/lib/repair-strongrefs.js","./writer.js":"/node_modules/favela-web/lib/writer.js","atproto-store/lib/overlay-repo-store.js":"/node_modules/favela-web/node_modules/atproto-store/lib/overlay-repo-store.js","bare-fetch/global":"/node_modules/favela-web/node_modules/bare-fetch/global.js","bare-path":"/node_modules/favela-web/node_modules/bare-path/index.js","bare-process":"/node_modules/favela-web/node_modules/bare-process/index.js","hyper-proto-peer/lib/adopt.js":"/node_modules/favela-web/node_modules/hyper-proto-peer/lib/adopt.js","hyper-svc":"/node_modules/favela-web/node_modules/hyper-svc/index.js"},"/node_modules/favela-web/lib/communities.js":{"#package":"/node_modules/favela-web/package.json"},"/node_modules/favela-web/lib/conformance.js":{"#package":"/node_modules/favela-web/package.json"},"/node_modules/favela-web/lib/constellation.js":{"#package":"/node_modules/favela-web/package.json","./link-drain.js":"/node_modules/favela-web/lib/link-drain.js","./spacedust.js":"/node_modules/favela-web/lib/spacedust.js"},"/node_modules/favela-web/lib/curators.js":{"#package":"/node_modules/favela-web/package.json"},"/node_modules/favela-web/lib/dns-txt.js":{"#package":"/node_modules/favela-web/package.json"},"/node_modules/favela-web/lib/facets.js":{"#package":"/node_modules/favela-web/package.json"},"/node_modules/favela-web/lib/feed-reactor.js":{"#package":"/node_modules/favela-web/package.json"},"/node_modules/favela-web/lib/feedgen.js":{"#package":"/node_modules/favela-web/package.json","./curators.js":"/node_modules/favela-web/lib/curators.js"},"/node_modules/favela-web/lib/followers.js":{"#package":"/node_modules/favela-web/package.json"},"/node_modules/favela-web/lib/fronts-diag.js":{"#package":"/node_modules/favela-web/package.json"},"/node_modules/favela-web/lib/gate-policy.js":{"#package":"/node_modules/favela-web/package.json"},"/node_modules/favela-web/lib/handles.js":{"#package":"/node_modules/favela-web/package.json"},"/node_modules/favela-web/lib/hosted-dids.js":{"#package":"/node_modules/favela-web/package.json"},"/node_modules/favela-web/lib/inbound.js":{"#package":"/node_modules/favela-web/package.json","./constellation.js":"/node_modules/favela-web/lib/constellation.js","./link-drain.js":"/node_modules/favela-web/lib/link-drain.js","./record-fetch.js":"/node_modules/favela-web/lib/record-fetch.js","./retention.js":"/node_modules/favela-web/lib/retention.js","./spacedust.js":"/node_modules/favela-web/lib/spacedust.js"},"/node_modules/favela-web/lib/label-firehose.js":{"#package":"/node_modules/favela-web/package.json","@ipld/dag-cbor":"/node_modules/favela-web/node_modules/@ipld/dag-cbor/src/index.js","atproto-identity/lib/labels.js":"/node_modules/favela-web/node_modules/atproto-identity/lib/labels.js"},"/node_modules/favela-web/lib/labeler-export.js":{"#package":"/node_modules/favela-web/package.json","b4a":"/node_modules/favela-web/node_modules/b4a/index.js"},"/node_modules/favela-web/lib/labeler.js":{"#package":"/node_modules/favela-web/package.json","atproto-identity/lib/atproto-identity.js":"/node_modules/favela-web/node_modules/atproto-identity/lib/atproto-identity.js","atproto-identity/lib/labels.js":"/node_modules/favela-web/node_modules/atproto-identity/lib/labels.js"},"/node_modules/favela-web/lib/labels.js":{"#package":"/node_modules/favela-web/package.json","hyperbee":"/node_modules/favela-web/node_modules/hyperbee/index.js"},"/node_modules/favela-web/lib/lens-import.js":{"#package":"/node_modules/favela-web/package.json"},"/node_modules/favela-web/lib/lenses.js":{"#package":"/node_modules/favela-web/package.json"},"/node_modules/favela-web/lib/link-drain.js":{"#package":"/node_modules/favela-web/package.json"},"/node_modules/favela-web/lib/lists.js":{"#package":"/node_modules/favela-web/package.json"},"/node_modules/favela-web/lib/mutes.js":{"#package":"/node_modules/favela-web/package.json"},"/node_modules/favela-web/lib/notifications.js":{"#package":"/node_modules/favela-web/package.json"},"/node_modules/favela-web/lib/pairing.js":{"#package":"/node_modules/favela-web/package.json","atproto-room/lib/pairing.js":"/node_modules/favela-web/node_modules/atproto-room/lib/pairing.js"},"/node_modules/favela-web/lib/plc.js":{"#package":"/node_modules/favela-web/package.json","atproto-identity/lib/did-key.js":"/node_modules/favela-web/node_modules/atproto-identity/lib/did-key.js"},"/node_modules/favela-web/lib/postgate.js":{"#package":"/node_modules/favela-web/package.json"},"/node_modules/favela-web/lib/reach.js":{"#package":"/node_modules/favela-web/package.json","./scopes.js":"/node_modules/favela-web/lib/scopes.js"},"/node_modules/favela-web/lib/record-fetch.js":{"#package":"/node_modules/favela-web/package.json","atproto-identity/lib/did-key.js":"/node_modules/favela-web/node_modules/atproto-identity/lib/did-key.js","atproto-identity/lib/plc-directory.js":"/node_modules/favela-web/node_modules/atproto-identity/lib/plc-directory.js","atproto-repo/lib/cid.js":"/node_modules/favela-web/node_modules/atproto-repo/lib/cid.js","atproto-repo/lib/commit.js":"/node_modules/favela-web/node_modules/atproto-repo/lib/commit.js","atproto-repo/lib/mst.js":"/node_modules/favela-web/node_modules/atproto-repo/lib/mst.js","atproto-repo/lib/repo.js":"/node_modules/favela-web/node_modules/atproto-repo/lib/repo.js"},"/node_modules/favela-web/lib/render.js":{"#package":"/node_modules/favela-web/package.json","./blob-serve.js":"/node_modules/favela-web/lib/blob-serve.js","./reach.js":"/node_modules/favela-web/lib/reach.js","./scopes.js":"/node_modules/favela-web/lib/scopes.js","./version.js":"/node_modules/favela-web/lib/version.js"},"/node_modules/favela-web/lib/repair-bytes.js":{"#package":"/node_modules/favela-web/package.json","@ipld/dag-cbor":"/node_modules/favela-web/node_modules/@ipld/dag-cbor/src/index.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js"},"/node_modules/favela-web/lib/repair-strongrefs.js":{"#package":"/node_modules/favela-web/package.json","./strongref.js":"/node_modules/favela-web/lib/strongref.js"},"/node_modules/favela-web/lib/repo-sync.js":{"#package":"/node_modules/favela-web/package.json","@ipld/dag-cbor":"/node_modules/favela-web/node_modules/@ipld/dag-cbor/src/index.js","atproto-repo/lib/commit.js":"/node_modules/favela-web/node_modules/atproto-repo/lib/commit.js","atproto-repo/lib/repo.js":"/node_modules/favela-web/node_modules/atproto-repo/lib/repo.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js"},"/node_modules/favela-web/lib/retention.js":{"#package":"/node_modules/favela-web/package.json","./appview.js":"/node_modules/favela-web/lib/appview.js","@ipld/dag-cbor":"/node_modules/favela-web/node_modules/@ipld/dag-cbor/src/index.js","atproto-repo/lib/cid.js":"/node_modules/favela-web/node_modules/atproto-repo/lib/cid.js"},"/node_modules/favela-web/lib/roster.js":{"#package":"/node_modules/favela-web/package.json"},"/node_modules/favela-web/lib/scopes.js":{"#package":"/node_modules/favela-web/package.json"},"/node_modules/favela-web/lib/search.js":{"#package":"/node_modules/favela-web/package.json"},"/node_modules/favela-web/lib/sessions.js":{"#package":"/node_modules/favela-web/package.json","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/hypercore-crypto/index.js"},"/node_modules/favela-web/lib/sidecar.js":{"#package":"/node_modules/favela-web/package.json","bare-fs":"/node_modules/favela-web/node_modules/bare-fs/index.js","bare-os":"/node_modules/favela-web/node_modules/bare-os/index.js","bare-path":"/node_modules/favela-web/node_modules/bare-path/index.js","bare-process":"/node_modules/favela-web/node_modules/bare-process/index.js","hyper-svc":"/node_modules/favela-web/node_modules/hyper-svc/index.js"},"/node_modules/favela-web/lib/spacedust-socket.js":{"#package":"/node_modules/favela-web/package.json","./spacedust.js":"/node_modules/favela-web/lib/spacedust.js","bare-ws":"/node_modules/favela-web/node_modules/bare-ws/index.js"},"/node_modules/favela-web/lib/spacedust.js":{"#package":"/node_modules/favela-web/package.json"},"/node_modules/favela-web/lib/static.js":{"#package":"/node_modules/favela-web/package.json","../web/static-assets.js":"/node_modules/favela-web/web/static-assets.js","bare-fs/promises":"/node_modules/favela-web/node_modules/bare-fs/promises.js","bare-path":"/node_modules/favela-web/node_modules/bare-path/index.js","bare-url":"/node_modules/favela-web/node_modules/bare-url/index.js"},"/node_modules/favela-web/lib/strongref.js":{"#package":"/node_modules/favela-web/package.json","atproto-repo/lib/cid.js":"/node_modules/favela-web/node_modules/atproto-repo/lib/cid.js"},"/node_modules/favela-web/lib/threadgate.js":{"#package":"/node_modules/favela-web/package.json"},"/node_modules/favela-web/lib/version.js":{"#package":"/node_modules/favela-web/package.json","../package.json":"/node_modules/favela-web/package.json"},"/node_modules/favela-web/lib/writer.js":{"#package":"/node_modules/favela-web/package.json","./facets.js":"/node_modules/favela-web/lib/facets.js","./scopes.js":"/node_modules/favela-web/lib/scopes.js","atproto-store/lib/tid.js":"/node_modules/favela-web/node_modules/atproto-store/lib/tid.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/compact-encoding/index.js","hyper-svc":"/node_modules/favela-web/node_modules/hyper-svc/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/hypercore-crypto/index.js","hyperswarm":"/node_modules/favela-web/node_modules/hyperswarm/index.js","protomux-rpc":"/node_modules/favela-web/node_modules/protomux-rpc/index.js"},"/node_modules/favela-web/node_modules/@hyperswarm/secret-stream/index.js":{"#package":"/node_modules/favela-web/node_modules/@hyperswarm/secret-stream/package.json","./lib/bridge":"/node_modules/favela-web/node_modules/@hyperswarm/secret-stream/lib/bridge.js","./lib/handshake":"/node_modules/favela-web/node_modules/@hyperswarm/secret-stream/lib/handshake.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/hypercore-crypto/index.js","sodium-secretstream":"/node_modules/favela-web/node_modules/sodium-secretstream/index.js","sodium-universal":"/node_modules/favela-web/node_modules/sodium-universal/index.js","streamx":"/node_modules/favela-web/node_modules/streamx/index.js","timeout-refresh":"/node_modules/favela-web/node_modules/timeout-refresh/index.js","unslab":"/node_modules/favela-web/node_modules/unslab/index.js"},"/node_modules/favela-web/node_modules/@hyperswarm/secret-stream/lib/bridge.js":{"#package":"/node_modules/favela-web/node_modules/@hyperswarm/secret-stream/package.json","streamx":"/node_modules/favela-web/node_modules/streamx/index.js"},"/node_modules/favela-web/node_modules/@hyperswarm/secret-stream/lib/handshake.js":{"#package":"/node_modules/favela-web/node_modules/@hyperswarm/secret-stream/package.json","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","noise-curve-ed":"/node_modules/favela-web/node_modules/noise-curve-ed/index.js","noise-handshake":"/node_modules/favela-web/node_modules/noise-handshake/noise.js","sodium-universal":"/node_modules/favela-web/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/@hyperswarm/secret-stream/package.json":{},"/node_modules/favela-web/node_modules/@ipld/dag-cbor/package.json":{},"/node_modules/favela-web/node_modules/@ipld/dag-cbor/src/index.js":{"#package":"/node_modules/favela-web/node_modules/@ipld/dag-cbor/package.json","cborg":"/node_modules/favela-web/node_modules/cborg/cborg.js","multiformats/cid":"/node_modules/favela-web/node_modules/multiformats/dist/src/cid.js"},"/node_modules/favela-web/node_modules/adaptive-timeout/index.js":{"#package":"/node_modules/favela-web/node_modules/adaptive-timeout/package.json","xache":"/node_modules/favela-web/node_modules/xache/index.js"},"/node_modules/favela-web/node_modules/adaptive-timeout/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/package.json","./lib/did-peer.js":"/node_modules/favela-web/node_modules/atproto-did-peer/lib/did-peer.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/lib/did-peer.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/package.json","atproto-repo/lib/commit.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/lib/commit.js","atproto-repo/lib/repo.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/lib/repo.js","atproto-store/lib/firehose.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/lib/firehose.js","atproto-store/lib/read-view.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/lib/read-view.js","atproto-store/lib/repo-diff.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/lib/repo-diff.js","atproto-store/lib/repo-store.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/lib/repo-store.js","atproto-store/lib/sequencer.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/lib/sequencer.js","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/compact-encoding/index.js","protomux":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/protomux/index.js","protomux-rpc":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/protomux-rpc/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/lib/car.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/package.json","@ipld/dag-cbor":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/src/index.js","multiformats/cid":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/cid.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/lib/cid.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/package.json","@ipld/dag-cbor":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/src/index.js","@noble/hashes/sha2":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/sha2.js","multiformats/cid":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/cid.js","multiformats/codecs/raw":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/codecs/raw.js","multiformats/hashes/digest":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/hashes/digest.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/lib/commit.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/package.json","./cid.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/lib/cid.js","@ipld/dag-cbor":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/src/index.js","@noble/curves/secp256k1":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/secp256k1.js","@noble/hashes/sha2":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/sha2.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/lib/mst.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/package.json","./cid.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/lib/cid.js","@ipld/dag-cbor":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/src/index.js","@noble/hashes/sha2":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/sha2.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/lib/repo.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/package.json","./car.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/lib/car.js","./cid.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/lib/cid.js","./commit.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/lib/commit.js","./mst.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/lib/mst.js","@ipld/dag-cbor":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/src/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/src/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/package.json","cborg":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/cborg.js","multiformats/cid":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/cid.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/_shortw_utils.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json","./abstract/weierstrass.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/weierstrass.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/curve.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json","../utils.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/utils.js","./modular.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/modular.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/hash-to-curve.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json","../utils.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/utils.js","./modular.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/modular.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/modular.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json","../utils.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/utils.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/weierstrass.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json","../utils.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/utils.js","./curve.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/curve.js","./modular.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/modular.js","@noble/hashes/hmac.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/hmac.js","@noble/hashes/utils":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/secp256k1.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json","./_shortw_utils.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/_shortw_utils.js","./abstract/hash-to-curve.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/hash-to-curve.js","./abstract/modular.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/modular.js","./abstract/weierstrass.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/weierstrass.js","./utils.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/utils.js","@noble/hashes/sha2.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/sha2.js","@noble/hashes/utils.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/utils.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json","@noble/hashes/utils.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/_md.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json","./utils.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/_u64.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/crypto.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/hmac.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json","./utils.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/sha2.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json","./_md.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/_md.js","./_u64.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/_u64.js","./utils.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json","@noble/hashes/crypto":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/crypto.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/cborg.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/package.json","./lib/decode.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/decode.js","./lib/encode.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/encode.js","./lib/tagged.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/tagged.js","./lib/token.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/package.json","./common.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/1negint.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/2bytes.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./byte-utils.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/3string.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./2bytes.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/2bytes.js","./common.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/4array.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/5map.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/6tag.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./token.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/7float.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/bl.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/package.json","./byte-utils.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/byte-utils.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/byte-utils.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/common.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/decode.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/package.json","./byte-utils.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./jump.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/jump.js","./token.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/encode.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./1negint.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/1negint.js","./2bytes.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/2bytes.js","./3string.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/3string.js","./4array.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/4array.js","./5map.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/5map.js","./6tag.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/6tag.js","./7float.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/7float.js","./bl.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/bl.js","./byte-utils.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./is.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/is.js","./jump.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/jump.js","./token.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/is.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/jump.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./1negint.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/1negint.js","./2bytes.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/2bytes.js","./3string.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/3string.js","./4array.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/4array.js","./5map.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/5map.js","./6tag.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/6tag.js","./7float.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/7float.js","./byte-utils.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/tagged.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/token.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/multiformats/package.json","../bytes.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/bytes.js","../vendor/base-x.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/vendor/base-x.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base32.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/multiformats/package.json","./base.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base36.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/multiformats/package.json","./base.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base58.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/multiformats/package.json","./base.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/bytes.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/multiformats/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/cid.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/multiformats/package.json","./bases/base32.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base32.js","./bases/base36.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base36.js","./bases/base58.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base58.js","./bytes.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/bytes.js","./hashes/digest.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/hashes/digest.js","./link/interface.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/link/interface.js","./varint.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/varint.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/codecs/raw.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/multiformats/package.json","../bytes.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/bytes.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/hashes/digest.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/multiformats/package.json","../bytes.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/bytes.js","../varint.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/varint.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/link/interface.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/multiformats/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/varint.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/multiformats/package.json","./vendor/varint.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/vendor/varint.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/vendor/base-x.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/multiformats/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/vendor/varint.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/multiformats/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/multiformats/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/lib/corestore.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/package.json","corestore":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/corestore/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/lib/firehose.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/package.json","@ipld/dag-cbor":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/@ipld/dag-cbor/src/index.js","atproto-repo/lib/commit.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/lib/commit.js","atproto-repo/lib/repo.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/lib/repo.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/lib/read-view.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/package.json","@ipld/dag-cbor":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/@ipld/dag-cbor/src/index.js","atproto-repo/lib/cid.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/lib/cid.js","atproto-repo/lib/commit.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/lib/commit.js","atproto-repo/lib/mst.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/lib/mst.js","atproto-repo/lib/repo.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/lib/repo.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/lib/repo-diff.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/package.json","./firehose.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/lib/firehose.js","atproto-repo/lib/repo.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/lib/repo.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/lib/repo-store.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/package.json","./corestore.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/lib/corestore.js","@ipld/dag-cbor":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/@ipld/dag-cbor/src/index.js","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/b4a/index.js","corestore":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/corestore/index.js","hyperbee":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hyperbee/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/lib/sequencer.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/package.json","./firehose.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/lib/firehose.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/@hyperswarm/secret-stream/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/@hyperswarm/secret-stream/package.json","./lib/bridge":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/@hyperswarm/secret-stream/lib/bridge.js","./lib/handshake":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/@hyperswarm/secret-stream/lib/handshake.js","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/b4a/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-crypto/index.js","sodium-secretstream":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/sodium-secretstream/index.js","sodium-universal":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/sodium-universal/index.js","streamx":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/streamx/index.js","timeout-refresh":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/timeout-refresh/index.js","unslab":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/unslab/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/@hyperswarm/secret-stream/lib/bridge.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/@hyperswarm/secret-stream/package.json","streamx":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/streamx/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/@hyperswarm/secret-stream/lib/handshake.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/@hyperswarm/secret-stream/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/b4a/index.js","noise-curve-ed":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/noise-curve-ed/index.js","noise-handshake":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/noise-handshake/noise.js","sodium-universal":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/@hyperswarm/secret-stream/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/@ipld/dag-cbor/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/@ipld/dag-cbor/src/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/@ipld/dag-cbor/package.json","cborg":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/cborg.js","multiformats/cid":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/cid.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/lib/car.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/package.json","@ipld/dag-cbor":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/src/index.js","multiformats/cid":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/cid.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/lib/cid.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/package.json","@ipld/dag-cbor":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/src/index.js","@noble/hashes/sha2":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/sha2.js","multiformats/cid":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/cid.js","multiformats/codecs/raw":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/codecs/raw.js","multiformats/hashes/digest":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/hashes/digest.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/lib/commit.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/package.json","./cid.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/lib/cid.js","@ipld/dag-cbor":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/src/index.js","@noble/curves/secp256k1":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/secp256k1.js","@noble/hashes/sha2":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/sha2.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/lib/mst.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/package.json","./cid.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/lib/cid.js","@ipld/dag-cbor":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/src/index.js","@noble/hashes/sha2":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/sha2.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/lib/repo.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/package.json","./car.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/lib/car.js","./cid.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/lib/cid.js","./commit.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/lib/commit.js","./mst.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/lib/mst.js","@ipld/dag-cbor":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/src/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/src/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/package.json","cborg":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/cborg.js","multiformats/cid":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/cid.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/_shortw_utils.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json","./abstract/weierstrass.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/weierstrass.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/curve.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json","../utils.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/utils.js","./modular.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/modular.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/hash-to-curve.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json","../utils.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/utils.js","./modular.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/modular.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/modular.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json","../utils.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/utils.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/weierstrass.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json","../utils.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/utils.js","./curve.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/curve.js","./modular.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/modular.js","@noble/hashes/hmac.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/hmac.js","@noble/hashes/utils":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/secp256k1.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json","./_shortw_utils.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/_shortw_utils.js","./abstract/hash-to-curve.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/hash-to-curve.js","./abstract/modular.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/modular.js","./abstract/weierstrass.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/weierstrass.js","./utils.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/utils.js","@noble/hashes/sha2.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/sha2.js","@noble/hashes/utils.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/utils.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json","@noble/hashes/utils.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/_md.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json","./utils.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/_u64.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/crypto.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/hmac.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json","./utils.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/sha2.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json","./_md.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/_md.js","./_u64.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/_u64.js","./utils.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json","@noble/hashes/crypto":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/crypto.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/cborg.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json","./lib/decode.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/decode.js","./lib/encode.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/encode.js","./lib/tagged.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/tagged.js","./lib/token.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json","./common.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/1negint.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/2bytes.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./byte-utils.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/3string.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./2bytes.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/2bytes.js","./common.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/4array.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/5map.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/6tag.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./token.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/7float.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/bl.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json","./byte-utils.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/byte-utils.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/byte-utils.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/common.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/decode.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json","./byte-utils.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./jump.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/jump.js","./token.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/encode.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./1negint.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/1negint.js","./2bytes.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/2bytes.js","./3string.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/3string.js","./4array.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/4array.js","./5map.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/5map.js","./6tag.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/6tag.js","./7float.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/7float.js","./bl.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/bl.js","./byte-utils.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./is.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/is.js","./jump.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/jump.js","./token.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/is.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/jump.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./1negint.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/1negint.js","./2bytes.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/2bytes.js","./3string.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/3string.js","./4array.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/4array.js","./5map.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/5map.js","./6tag.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/6tag.js","./7float.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/7float.js","./byte-utils.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/tagged.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/token.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/package.json","../bytes.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bytes.js","../vendor/base-x.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/vendor/base-x.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base32.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/package.json","./base.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base36.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/package.json","./base.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base58.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/package.json","./base.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bytes.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/cid.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/package.json","./bases/base32.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base32.js","./bases/base36.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base36.js","./bases/base58.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base58.js","./bytes.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bytes.js","./hashes/digest.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/hashes/digest.js","./link/interface.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/link/interface.js","./varint.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/varint.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/codecs/raw.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/package.json","../bytes.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bytes.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/hashes/digest.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/package.json","../bytes.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bytes.js","../varint.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/varint.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/link/interface.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/varint.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/package.json","./vendor/varint.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/vendor/varint.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/vendor/base-x.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/vendor/varint.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/b4a/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/b4a/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/b4a/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-ansi-escapes/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-ansi-escapes/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-ansi-escapes/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-assert/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-assert/package.json","bare-inspect":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-inspect/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-assert/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-events/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-events/package.json","./lib/errors":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-events/lib/errors.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-events/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-events/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-events/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-fs/binding.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-fs/package.json",".":"linked:libbare-fs.4.7.3.so"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-fs/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-fs/package.json","./binding":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-fs/binding.js","./lib/constants":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-fs/lib/constants.js","./lib/errors":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-fs/lib/errors.js","./promises":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-fs/promises.js","bare-events":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-events/index.js","bare-path":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-path/index.js","bare-stream":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-stream/index.js","bare-url":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-url/index.js","fast-fifo":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/fast-fifo/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-fs/lib/constants.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-fs/package.json","../binding":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-fs/binding.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-fs/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-fs/package.json","bare-os":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-os/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-fs/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-fs/promises.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-fs/package.json",".":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-fs/index.js","bare-events":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-events/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-inspect/binding.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-inspect/package.json",".":"linked:libbare-inspect.3.1.4.so"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-inspect/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-inspect/package.json","./binding":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-inspect/binding.js","bare-ansi-escapes":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-ansi-escapes/index.js","bare-type":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-type/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-inspect/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-os/binding.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-os/package.json",".":"linked:libbare-os.3.9.3.so"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-os/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-os/package.json","./binding":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-os/binding.js","./lib/constants":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-os/lib/constants.js","./lib/errors":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-os/lib/errors.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-os/lib/constants.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-os/package.json","../binding":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-os/binding.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-os/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-os/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-os/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-path/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-path/package.json","./lib/posix":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-path/lib/posix.js","./lib/win32":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-path/lib/win32.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-path/lib/constants.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-path/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-path/lib/posix.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-path/package.json","./constants":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-path/lib/constants.js","./shared":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-path/lib/shared.js","./win32":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-path/lib/win32.js","bare-os":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-os/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-path/lib/shared.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-path/package.json","./constants":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-path/lib/constants.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-path/lib/win32.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-path/package.json","./constants":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-path/lib/constants.js","./posix":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-path/lib/posix.js","./shared":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-path/lib/shared.js","bare-os":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-os/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-path/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-stream/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-stream/package.json","./web":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-stream/web.js","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/b4a/index.js","streamx":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/streamx/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-stream/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-stream/web.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-stream/package.json","streamx":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/streamx/index.js","teex":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/teex/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-type/binding.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-type/package.json",".":"linked:libbare-type.1.1.0.so"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-type/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-type/package.json","./binding":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-type/binding.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-type/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-url/binding.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-url/package.json",".":"linked:libbare-url.2.4.5.so"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-url/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-url/package.json","./binding":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-url/binding.js","./lib/errors":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-url/lib/errors.js","./lib/url-search-params":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-url/lib/url-search-params.js","bare-path":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-path/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-url/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-url/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-url/lib/url-search-params.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-url/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-url/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/big-sparse-array/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/big-sparse-array/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/big-sparse-array/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/cborg.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/package.json","./lib/decode.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/decode.js","./lib/encode.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/encode.js","./lib/tagged.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/tagged.js","./lib/token.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/0uint.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/package.json","./common.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/1negint.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/2bytes.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/0uint.js","./byte-utils.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/3string.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/0uint.js","./2bytes.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/2bytes.js","./common.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/4array.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/5map.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/6tag.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/0uint.js","./token.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/7float.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/bl.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/package.json","./byte-utils.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/byte-utils.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/byte-utils.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/common.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/decode.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/package.json","./byte-utils.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/common.js","./jump.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/jump.js","./token.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/encode.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/0uint.js","./1negint.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/1negint.js","./2bytes.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/2bytes.js","./3string.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/3string.js","./4array.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/4array.js","./5map.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/5map.js","./6tag.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/6tag.js","./7float.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/7float.js","./bl.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/bl.js","./byte-utils.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/common.js","./is.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/is.js","./jump.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/jump.js","./token.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/is.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/jump.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/0uint.js","./1negint.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/1negint.js","./2bytes.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/2bytes.js","./3string.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/3string.js","./4array.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/4array.js","./5map.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/5map.js","./6tag.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/6tag.js","./7float.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/7float.js","./byte-utils.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/tagged.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/token.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/codecs/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/codecs/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/codecs/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/compact-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/compact-encoding/raw.js","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/compact-encoding/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/compact-encoding/endian.js","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/corestore/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/corestore/package.json","./lib/audit.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/corestore/lib/audit.js","./lib/notify.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/corestore/lib/notify.js","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/b4a/index.js","hypercore":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-crypto/index.js","hypercore-errors":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-errors/index.js","hypercore-id-encoding":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-id-encoding/index.js","ready-resource":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/ready-resource/index.js","sodium-universal":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/sodium-universal/index.js","which-runtime":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/which-runtime/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/corestore/lib/audit.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/corestore/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/corestore/lib/notify.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/corestore/package.json","events":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-events/index.js","streamx":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/streamx/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/corestore/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/debounceify/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/debounceify/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/debounceify/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/device-file/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/device-file/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/b4a/index.js","fd-lock":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/fd-lock/index.js","fs":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-fs/index.js","fs-native-extensions":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/fs-native-extensions/index.js","path":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-path/index.js","ready-resource":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/ready-resource/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/device-file/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/events-universal/bare.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/events-universal/package.json","bare-events":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-events/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/events-universal/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/fast-fifo/fixed-size.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/fast-fifo/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/fast-fifo/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/fast-fifo/package.json","./fixed-size":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/fast-fifo/fixed-size.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/fast-fifo/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/fd-lock/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/fd-lock/package.json","fs":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-fs/index.js","fs-native-extensions":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/fs-native-extensions/index.js","ready-resource":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/ready-resource/index.js","resource-on-exit":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/resource-on-exit/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/fd-lock/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/flat-tree/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/flat-tree/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/flat-tree/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/fs-native-extensions/binding.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/fs-native-extensions/package.json",".":"linked:libfs-native-extensions.1.5.0.so","require-addon":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/require-addon/lib/bare.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/fs-native-extensions/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/fs-native-extensions/package.json","./binding":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/fs-native-extensions/binding.js","which-runtime":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/which-runtime/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/fs-native-extensions/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hyperbee/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hyperbee/package.json","./iterators/diff":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hyperbee/iterators/diff.js","./iterators/history":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hyperbee/iterators/history.js","./iterators/local":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hyperbee/iterators/local.js","./iterators/range":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hyperbee/iterators/range.js","./lib/extension":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hyperbee/lib/extension.js","./lib/messages":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hyperbee/lib/messages.js","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/b4a/index.js","codecs":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/codecs/index.js","debounceify":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/debounceify/index.js","hypercore-errors":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-errors/index.js","mutexify/promise":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/mutexify/promise.js","rache":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/rache/index.js","ready-resource":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/ready-resource/index.js","resolve-reject-promise":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/resolve-reject-promise/index.js","safety-catch":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/safety-catch/index.js","streamx":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/streamx/index.js","unslab":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/unslab/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hyperbee/iterators/diff.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hyperbee/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hyperbee/iterators/history.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hyperbee/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hyperbee/iterators/local.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hyperbee/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hyperbee/iterators/range.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hyperbee/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hyperbee/lib/extension.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hyperbee/package.json","./messages":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hyperbee/lib/messages.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hyperbee/lib/messages.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hyperbee/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/b4a/index.js","protocol-buffers-encodings":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/protocol-buffers-encodings/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hyperbee/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-crypto/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-crypto/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/compact-encoding/index.js","sodium-universal":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-crypto/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-errors/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-errors/package.json","hypercore-id-encoding":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-id-encoding/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-errors/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-id-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-id-encoding/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/b4a/index.js","z32":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/z32/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-id-encoding/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-storage/encoding/external.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-storage/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-storage/encoding/spec/hyperschema/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-storage/package.json","../../external.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-storage/encoding/external.js","hyperschema/runtime":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hyperschema/runtime.cjs"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-storage/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-storage/package.json","./lib/keys.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-storage/lib/keys.js","./lib/streams.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-storage/lib/streams.js","./lib/tx.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-storage/lib/tx.js","./lib/view.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-storage/lib/view.js","./migrations/0":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-storage/migrations/0/index.js","./migrations/1":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-storage/migrations/1/index.js","device-file":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/device-file/index.js","fs":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-fs/index.js","path":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-path/index.js","resolve-reject-promise":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/resolve-reject-promise/index.js","rocksdb-native":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/rocksdb-native/index.js","scope-lock":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/scope-lock/index.js","xache":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/xache/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-storage/lib/block-dependency-stream.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-storage/package.json","./keys":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-storage/lib/keys.js","streamx":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/streamx/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-storage/lib/close-error-stream.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-storage/package.json","streamx":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/streamx/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-storage/lib/keys.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-storage/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/compact-encoding/index.js","index-encoder":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/index-encoder/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-storage/lib/streams.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-storage/package.json","../encoding/spec/hyperschema":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-storage/encoding/spec/hyperschema/index.js","./block-dependency-stream.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-storage/lib/block-dependency-stream.js","./keys.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-storage/lib/keys.js","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-storage/lib/tx.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-storage/package.json","../encoding/spec/hyperschema":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-storage/encoding/spec/hyperschema/index.js","./keys.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-storage/lib/keys.js","./view.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-storage/lib/view.js","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/compact-encoding/index.js","flat-tree":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/flat-tree/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-storage/lib/view.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-storage/package.json","./close-error-stream.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-storage/lib/close-error-stream.js","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/b4a/index.js","streamx":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/streamx/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-storage/migrations/0/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-storage/package.json","../../lib/tx.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-storage/lib/tx.js","../../lib/view.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-storage/lib/view.js","./messages.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-storage/migrations/0/messages.js","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/compact-encoding/index.js","flat-tree":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/flat-tree/index.js","fs":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-fs/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-crypto/index.js","path":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-path/index.js","streamx":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/streamx/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-storage/migrations/0/messages.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-storage/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/compact-encoding/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-storage/migrations/1/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-storage/package.json","../../encoding/spec/hyperschema":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-storage/encoding/spec/hyperschema/index.js","../../lib/keys.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-storage/lib/keys.js","../../lib/tx.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-storage/lib/tx.js","../../lib/view.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-storage/lib/view.js","compact-encoding":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/compact-encoding/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-storage/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/package.json","./lib/caps":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/caps.js","./lib/core":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/core.js","./lib/default-encryption":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/default-encryption.js","./lib/download":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/download.js","./lib/feature-flags":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/feature-flags.js","./lib/fully-remote-proof":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/fully-remote-proof.js","./lib/info":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/info.js","./lib/inspect":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/inspect.js","./lib/mark-bitfield":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/mark-bitfield.js","./lib/merkle-tree":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/merkle-tree.js","./lib/replicator":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/replicator.js","./lib/streams":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/streams.js","./lib/verifier":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/verifier.js","./lib/wants":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/wants.js","@hyperswarm/secret-stream":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/@hyperswarm/secret-stream/index.js","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/compact-encoding/index.js","events":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-events/index.js","flat-tree":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/flat-tree/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-crypto/index.js","hypercore-errors":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-errors/index.js","hypercore-id-encoding":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-id-encoding/index.js","hypercore-storage":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-storage/index.js","is-options":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/is-options/index.js","nanoassert":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/nanoassert/index.js","protomux":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/protomux/index.js","safety-catch":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/safety-catch/index.js","unslab":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/unslab/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/audit.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/package.json","./merkle-tree":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/merkle-tree.js","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/b4a/index.js","flat-tree":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/flat-tree/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-crypto/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/bit-interlude.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/package.json","./compat":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/compat.js","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/bitfield.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/package.json","./compat":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/compat.js","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/b4a/index.js","big-sparse-array":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/big-sparse-array/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/caps.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/compact-encoding/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-crypto/index.js","sodium-universal":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/compat.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/package.json","quickbit-universal":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/quickbit-universal/index.js","quickbit-universal/fallback":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/quickbit-universal/fallback.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/copy-prologue.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/package.json","./bitfield":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/bitfield.js","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/b4a/index.js","flat-tree":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/flat-tree/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-crypto/index.js","quickbit-universal":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/quickbit-universal/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/core.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/package.json","./audit":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/audit.js","./bit-interlude":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/bit-interlude.js","./bitfield":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/bitfield.js","./copy-prologue":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/copy-prologue.js","./merkle-tree":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/merkle-tree.js","./mutex":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/mutex.js","./remote-bitfield":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/remote-bitfield.js","./replicator":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/replicator.js","./session-state":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/session-state.js","./verifier":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/verifier.js","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/b4a/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-crypto/index.js","hypercore-errors":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-errors/index.js","unslab":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/unslab/index.js","z32":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/z32/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/default-encryption.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/package.json","./caps":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/caps.js","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/compact-encoding/index.js","sodium-universal":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/download.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/feature-flags.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/fully-remote-proof.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/package.json","./merkle-tree.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/merkle-tree.js","./messages.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/messages.js","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/compact-encoding/index.js","flat-tree":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/flat-tree/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-crypto/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/hotswap-queue.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/info.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/inspect.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/mark-bitfield.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/package.json","./compat":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/compat.js","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/b4a/index.js","big-sparse-array":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/big-sparse-array/index.js","streamx":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/streamx/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/merkle-tree.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/package.json","./caps":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/caps.js","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/b4a/index.js","flat-tree":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/flat-tree/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-crypto/index.js","hypercore-errors":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-errors/index.js","unslab":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/unslab/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/messages.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/package.json","./caps":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/caps.js","compact-encoding":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/compact-encoding/index.js","hypercore-errors":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-errors/index.js","unslab":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/unslab/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/multisig.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/package.json","./merkle-tree":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/merkle-tree.js","./messages":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/messages.js","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/compact-encoding/index.js","flat-tree":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/flat-tree/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/mutex.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/receiver-queue.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/package.json","fast-fifo":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/fast-fifo/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/remote-bitfield.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/package.json","./compat":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/compat.js","big-sparse-array":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/big-sparse-array/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/replicator.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/package.json","./caps":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/caps.js","./hotswap-queue":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/hotswap-queue.js","./merkle-tree":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/merkle-tree.js","./messages":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/messages.js","./mutex":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/mutex.js","./receiver-queue":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/receiver-queue.js","./remote-bitfield":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/remote-bitfield.js","./wants":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/wants.js","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/b4a/index.js","flat-tree":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/flat-tree/index.js","hypercore-errors":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-errors/index.js","random-array-iterator":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/random-array-iterator/index.js","safety-catch":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/safety-catch/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/session-state.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/package.json","./bitfield":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/bitfield.js","./merkle-tree":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/merkle-tree.js","./mutex":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/mutex.js","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/b4a/index.js","flat-tree":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/flat-tree/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-crypto/index.js","hypercore-errors":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-errors/index.js","hypercore-storage":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-storage/index.js","nanoassert":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/nanoassert/index.js","quickbit-universal":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/quickbit-universal/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/streams.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/package.json","streamx":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/streamx/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/verifier.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/package.json","./caps":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/caps.js","./messages":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/messages.js","./multisig":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/multisig.js","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/compact-encoding/index.js","flat-tree":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/flat-tree/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-crypto/index.js","hypercore-errors":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-errors/index.js","unslab":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/unslab/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/wants.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hyperschema/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hyperschema/runtime.cjs":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hyperschema/package.json","compact-encoding":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/compact-encoding/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/index-encoder/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/index-encoder/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/index-encoder/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/is-options/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/is-options/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/is-options/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/bases/base.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/multiformats/package.json","../bytes.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/bytes.js","../vendor/base-x.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/vendor/base-x.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/bases/base32.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/multiformats/package.json","./base.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/bases/base.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/bases/base36.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/multiformats/package.json","./base.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/bases/base.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/bases/base58.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/multiformats/package.json","./base.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/bases/base.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/bytes.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/multiformats/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/cid.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/multiformats/package.json","./bases/base32.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/bases/base32.js","./bases/base36.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/bases/base36.js","./bases/base58.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/bases/base58.js","./bytes.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/bytes.js","./hashes/digest.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/hashes/digest.js","./link/interface.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/link/interface.js","./varint.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/varint.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/hashes/digest.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/multiformats/package.json","../bytes.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/bytes.js","../varint.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/varint.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/link/interface.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/multiformats/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/varint.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/multiformats/package.json","./vendor/varint.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/vendor/varint.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/vendor/base-x.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/multiformats/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/vendor/varint.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/multiformats/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/multiformats/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/mutexify/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/mutexify/package.json","queue-tick":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/queue-tick/process-next-tick.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/mutexify/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/mutexify/promise.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/mutexify/package.json",".":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/mutexify/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/nanoassert/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/nanoassert/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/nanoassert/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/noise-curve-ed/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/noise-curve-ed/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/b4a/index.js","nanoassert":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/nanoassert/index.js","sodium-universal":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/noise-curve-ed/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/noise-handshake/cipher.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/noise-handshake/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/b4a/index.js","sodium-universal":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/noise-handshake/dh.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/noise-handshake/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/b4a/index.js","nanoassert":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/nanoassert/index.js","sodium-universal":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/noise-handshake/hkdf.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/noise-handshake/package.json","./hmac":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/noise-handshake/hmac.js","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/noise-handshake/hmac.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/noise-handshake/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/b4a/index.js","sodium-universal":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/noise-handshake/noise.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/noise-handshake/package.json","./hkdf":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/noise-handshake/hkdf.js","./symmetric-state":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/noise-handshake/symmetric-state.js","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/b4a/index.js","nanoassert":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/nanoassert/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/noise-handshake/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/noise-handshake/symmetric-state.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/noise-handshake/package.json","./cipher":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/noise-handshake/cipher.js","./dh":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/noise-handshake/dh.js","./hkdf":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/noise-handshake/hkdf.js","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/b4a/index.js","nanoassert":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/nanoassert/index.js","sodium-universal":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/protocol-buffers-encodings/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/protocol-buffers-encodings/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/b4a/index.js","signed-varint":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/signed-varint/index.js","varint":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/varint/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/protocol-buffers-encodings/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/protomux/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/protomux/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/compact-encoding/index.js","queue-tick":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/queue-tick/process-next-tick.js","safety-catch":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/safety-catch/index.js","unslab":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/unslab/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/protomux/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/queue-tick/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/queue-tick/process-next-tick.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/queue-tick/package.json","./queue-microtask":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/queue-tick/queue-microtask.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/queue-tick/queue-microtask.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/queue-tick/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/quickbit-native/binding.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/quickbit-native/package.json",".":"linked:libquickbit-native.2.4.8.so","require-addon":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/require-addon/lib/bare.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/quickbit-native/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/quickbit-native/package.json","./binding":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/quickbit-native/binding.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/quickbit-native/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/quickbit-universal/fallback.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/quickbit-universal/package.json","simdle-universal":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/simdle-universal/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/quickbit-universal/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/quickbit-universal/package.json","./fallback":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/quickbit-universal/fallback.js","quickbit-native":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/quickbit-native/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/quickbit-universal/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/rache/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/rache/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/rache/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/random-array-iterator/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/random-array-iterator/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/random-array-iterator/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/ready-resource/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/ready-resource/package.json","events":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-events/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/ready-resource/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/refcounter/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/refcounter/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/refcounter/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/require-addon/lib/bare.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/require-addon/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/require-addon/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/resolve-reject-promise/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/resolve-reject-promise/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/resolve-reject-promise/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/resource-on-exit/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/resource-on-exit/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/resource-on-exit/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/rocksdb-native/binding.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/rocksdb-native/package.json",".":"linked:librocksdb-native.3.17.2.so","require-addon":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/require-addon/lib/bare.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/rocksdb-native/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/rocksdb-native/package.json","./lib/column-family":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/rocksdb-native/lib/column-family.js","./lib/constants":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/rocksdb-native/lib/constants.js","./lib/filter-policy":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/rocksdb-native/lib/filter-policy.js","./lib/iterator":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/rocksdb-native/lib/iterator.js","./lib/snapshot":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/rocksdb-native/lib/snapshot.js","./lib/state":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/rocksdb-native/lib/state.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/rocksdb-native/lib/batch.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/rocksdb-native/package.json","../binding":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/rocksdb-native/binding.js","compact-encoding":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/compact-encoding/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/rocksdb-native/lib/column-family.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/rocksdb-native/package.json","../binding":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/rocksdb-native/binding.js","./constants":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/rocksdb-native/lib/constants.js","./filter-policy":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/rocksdb-native/lib/filter-policy.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/rocksdb-native/lib/constants.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/rocksdb-native/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/rocksdb-native/lib/filter-policy.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/rocksdb-native/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/rocksdb-native/lib/iterator.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/rocksdb-native/package.json","../binding":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/rocksdb-native/binding.js","compact-encoding":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/compact-encoding/index.js","streamx":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/streamx/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/rocksdb-native/lib/snapshot.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/rocksdb-native/package.json","../binding":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/rocksdb-native/binding.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/rocksdb-native/lib/state.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/rocksdb-native/package.json","../binding":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/rocksdb-native/binding.js","./batch":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/rocksdb-native/lib/batch.js","./column-family":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/rocksdb-native/lib/column-family.js","./constants":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/rocksdb-native/lib/constants.js","compact-encoding":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/compact-encoding/index.js","ready-resource":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/ready-resource/index.js","refcounter":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/refcounter/index.js","resolve-reject-promise":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/resolve-reject-promise/index.js","signal-promise":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/signal-promise/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/rocksdb-native/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/safety-catch/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/safety-catch/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/safety-catch/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/scope-lock/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/scope-lock/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/scope-lock/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/signal-promise/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/signal-promise/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/signal-promise/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/signed-varint/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/signed-varint/package.json","varint":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/varint/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/signed-varint/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/simdle-native/binding.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/simdle-native/package.json",".":"linked:libsimdle-native.1.3.9.so","require-addon":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/require-addon/lib/bare.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/simdle-native/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/simdle-native/package.json","./binding":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/simdle-native/binding.js","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/simdle-native/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/simdle-universal/fallback.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/simdle-universal/package.json","./scalar":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/simdle-universal/scalar.js","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/simdle-universal/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/simdle-universal/package.json","./fallback":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/simdle-universal/fallback.js","simdle-native":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/simdle-native/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/simdle-universal/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/simdle-universal/scalar.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/simdle-universal/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/sodium-native/binding.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/sodium-native/package.json",".":"linked:libsodium-native.5.1.0.so","require-addon":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/require-addon/lib/bare.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/sodium-native/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/sodium-native/package.json","./binding":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/sodium-native/binding.js","assert":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-assert/index.js","which-runtime":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/which-runtime/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/sodium-native/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/sodium-secretstream/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/sodium-secretstream/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/b4a/index.js","sodium-universal":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/sodium-secretstream/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/sodium-universal/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/sodium-universal/package.json","sodium-native":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/sodium-native/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/sodium-universal/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/streamx/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/streamx/package.json","./lib/errors.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/streamx/lib/errors.js","events-universal":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/events-universal/bare.js","fast-fifo":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/fast-fifo/index.js","text-decoder":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/text-decoder/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/streamx/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/streamx/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/streamx/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/teex/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/teex/package.json","streamx":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/streamx/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/teex/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/text-decoder/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/text-decoder/package.json","./lib/pass-through-decoder":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/text-decoder/lib/pass-through-decoder.js","./lib/utf8-decoder":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/text-decoder/lib/utf8-decoder.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/text-decoder/lib/pass-through-decoder.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/text-decoder/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/text-decoder/lib/utf8-decoder.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/text-decoder/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/text-decoder/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/timeout-refresh/browser.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/timeout-refresh/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/timeout-refresh/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/timeout-refresh/package.json","./browser":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/timeout-refresh/browser.js","./node":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/timeout-refresh/node.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/timeout-refresh/node.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/timeout-refresh/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/timeout-refresh/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/unslab/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/unslab/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/unslab/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/varint/decode.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/varint/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/varint/encode.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/varint/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/varint/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/varint/package.json","./decode.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/varint/decode.js","./encode.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/varint/encode.js","./length.js":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/varint/length.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/varint/length.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/varint/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/varint/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/which-runtime/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/which-runtime/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/which-runtime/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/xache/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/xache/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/xache/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/z32/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/z32/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/z32/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/b4a/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/b4a/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/b4a/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/bare-events/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/bare-events/package.json","./lib/errors":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/bare-events/lib/errors.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/bare-events/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/bare-events/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/bare-events/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/bits-to-bytes/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/bits-to-bytes/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/bits-to-bytes/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/compact-encoding-bitfield/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/compact-encoding-bitfield/package.json","compact-encoding":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/raw.js","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/endian.js","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/compact-encoding-bitfield/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/compact-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/compact-encoding/raw.js","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/compact-encoding/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/compact-encoding/endian.js","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/protomux-rpc/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/protomux-rpc/package.json","./lib/errors":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/protomux-rpc/lib/errors.js","bits-to-bytes":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/bits-to-bytes/index.js","compact-encoding":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/protomux-rpc/node_modules/compact-encoding/index.js","compact-encoding-bitfield":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/compact-encoding-bitfield/index.js","events":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/bare-events/index.js","protomux":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/protomux/index.js","safety-catch":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/safety-catch/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/protomux-rpc/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/protomux-rpc/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/protomux-rpc/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/protomux-rpc/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/protomux-rpc/node_modules/compact-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/protomux-rpc/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/protomux-rpc/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/protomux-rpc/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/protomux-rpc/node_modules/compact-encoding/raw.js","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/protomux-rpc/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/protomux-rpc/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/protomux-rpc/node_modules/compact-encoding/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/protomux-rpc/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/protomux-rpc/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/protomux-rpc/node_modules/compact-encoding/endian.js","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/protomux-rpc/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/protomux/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/protomux/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/protomux/node_modules/compact-encoding/index.js","queue-tick":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/queue-tick/process-next-tick.js","safety-catch":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/safety-catch/index.js","unslab":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/unslab/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/protomux/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/protomux/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/protomux/node_modules/compact-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/protomux/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/protomux/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/protomux/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/protomux/node_modules/compact-encoding/raw.js","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/protomux/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/protomux/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/protomux/node_modules/compact-encoding/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/protomux/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/protomux/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/protomux/node_modules/compact-encoding/endian.js","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/protomux/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/queue-tick/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/queue-tick/process-next-tick.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/queue-tick/package.json","./queue-microtask":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/queue-tick/queue-microtask.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/queue-tick/queue-microtask.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/queue-tick/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/safety-catch/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/safety-catch/package.json"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/safety-catch/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/unslab/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/unslab/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/unslab/package.json":{},"/node_modules/favela-web/node_modules/atproto-did-peer/package.json":{},"/node_modules/favela-web/node_modules/atproto-identity/lib/atproto-identity.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/package.json","./did-key.js":"/node_modules/favela-web/node_modules/atproto-identity/lib/did-key.js","./did-plc.js":"/node_modules/favela-web/node_modules/atproto-identity/lib/did-plc.js","@noble/curves/secp256k1":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/curves/esm/secp256k1.js","@noble/hashes/sha2":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/hashes/esm/sha2.js","@scure/bip32":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@scure/bip32/lib/esm/index.js","@scure/bip39":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@scure/bip39/esm/index.js","multiformats/bases/base64":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/multiformats/dist/src/bases/base64.js"},"/node_modules/favela-web/node_modules/atproto-identity/lib/auth.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/package.json","@noble/curves/secp256k1":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/curves/esm/secp256k1.js","@noble/hashes/hmac":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/hashes/esm/hmac.js","@noble/hashes/scrypt":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/hashes/esm/scrypt.js","@noble/hashes/sha2":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/hashes/esm/sha2.js","hypercore-crypto":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/hypercore-crypto/index.js"},"/node_modules/favela-web/node_modules/atproto-identity/lib/did-key.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/package.json","multiformats/bases/base58":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/multiformats/dist/src/bases/base58.js"},"/node_modules/favela-web/node_modules/atproto-identity/lib/did-plc.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/package.json","@ipld/dag-cbor":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@ipld/dag-cbor/src/index.js","@noble/hashes/sha2":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/hashes/esm/sha2.js","multiformats/bases/base32":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/multiformats/dist/src/bases/base32.js","multiformats/cid":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/multiformats/dist/src/cid.js","multiformats/hashes/digest":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/multiformats/dist/src/hashes/digest.js"},"/node_modules/favela-web/node_modules/atproto-identity/lib/discovery.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/package.json","hypercore-crypto":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/hypercore-crypto/index.js"},"/node_modules/favela-web/node_modules/atproto-identity/lib/labels.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/package.json","./plc-directory.js":"/node_modules/favela-web/node_modules/atproto-identity/lib/plc-directory.js","@ipld/dag-cbor":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@ipld/dag-cbor/src/index.js","@noble/curves/secp256k1":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/curves/esm/secp256k1.js","@noble/hashes/sha2":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/hashes/esm/sha2.js"},"/node_modules/favela-web/node_modules/atproto-identity/lib/plc-directory.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/package.json","./atproto-identity.js":"/node_modules/favela-web/node_modules/atproto-identity/lib/atproto-identity.js","./did-key.js":"/node_modules/favela-web/node_modules/atproto-identity/lib/did-key.js","./did-plc.js":"/node_modules/favela-web/node_modules/atproto-identity/lib/did-plc.js","@noble/curves/p256":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/curves/esm/p256.js","@noble/curves/secp256k1":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/curves/esm/secp256k1.js","@noble/hashes/sha2":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/hashes/esm/sha2.js"},"/node_modules/favela-web/node_modules/atproto-identity/lib/web-auth.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/package.json","./auth.js":"/node_modules/favela-web/node_modules/atproto-identity/lib/auth.js"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@ipld/dag-cbor/package.json":{},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@ipld/dag-cbor/src/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@ipld/dag-cbor/package.json","cborg":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/cborg.js","multiformats/cid":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/multiformats/dist/src/cid.js"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/curves/esm/_shortw_utils.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/curves/esm/package.json","./abstract/weierstrass.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/curves/esm/abstract/weierstrass.js"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/curves/esm/abstract/curve.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/curves/esm/package.json","../utils.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/curves/esm/utils.js","./modular.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/curves/esm/abstract/modular.js"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/curves/esm/abstract/hash-to-curve.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/curves/esm/package.json","../utils.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/curves/esm/utils.js","./modular.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/curves/esm/abstract/modular.js"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/curves/esm/abstract/modular.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/curves/esm/package.json","../utils.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/curves/esm/utils.js"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/curves/esm/abstract/weierstrass.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/curves/esm/package.json","../utils.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/curves/esm/utils.js","./curve.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/curves/esm/abstract/curve.js","./modular.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/curves/esm/abstract/modular.js","@noble/hashes/hmac.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/hashes/esm/hmac.js","@noble/hashes/utils":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/curves/esm/nist.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/curves/esm/package.json","./_shortw_utils.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/curves/esm/_shortw_utils.js","./abstract/hash-to-curve.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/curves/esm/abstract/hash-to-curve.js","./abstract/modular.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/curves/esm/abstract/modular.js","./abstract/weierstrass.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/curves/esm/abstract/weierstrass.js","@noble/hashes/sha2.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/hashes/esm/sha2.js"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/curves/esm/p256.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/curves/esm/package.json","./abstract/hash-to-curve.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/curves/esm/abstract/hash-to-curve.js","./nist.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/curves/esm/nist.js"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/curves/esm/package.json":{},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/curves/esm/secp256k1.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/curves/esm/package.json","./_shortw_utils.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/curves/esm/_shortw_utils.js","./abstract/hash-to-curve.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/curves/esm/abstract/hash-to-curve.js","./abstract/modular.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/curves/esm/abstract/modular.js","./abstract/weierstrass.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/curves/esm/abstract/weierstrass.js","./utils.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/curves/esm/utils.js","@noble/hashes/sha2.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/hashes/esm/sha2.js","@noble/hashes/utils.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/curves/esm/utils.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/curves/esm/package.json","@noble/hashes/utils.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/hashes/esm/_md.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/hashes/esm/package.json","./utils.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/hashes/esm/_u64.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/hashes/esm/package.json"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/hashes/esm/crypto.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/hashes/esm/package.json"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/hashes/esm/hmac.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/hashes/esm/package.json","./utils.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/hashes/esm/legacy.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/hashes/esm/package.json","./_md.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/hashes/esm/_md.js","./utils.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/hashes/esm/package.json":{},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/hashes/esm/pbkdf2.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/hashes/esm/package.json","./hmac.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/hashes/esm/hmac.js","./utils.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/hashes/esm/scrypt.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/hashes/esm/package.json","./pbkdf2.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/hashes/esm/pbkdf2.js","./sha2.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/hashes/esm/sha2.js","./utils.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/hashes/esm/sha2.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/hashes/esm/package.json","./_md.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/hashes/esm/_md.js","./_u64.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/hashes/esm/_u64.js","./utils.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/hashes/esm/utils.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/hashes/esm/package.json","@noble/hashes/crypto":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/hashes/esm/crypto.js"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@scure/base/lib/esm/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@scure/base/lib/esm/package.json"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@scure/base/lib/esm/package.json":{},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@scure/bip32/lib/esm/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@scure/bip32/lib/esm/package.json","@noble/curves/abstract/modular":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/curves/esm/abstract/modular.js","@noble/curves/secp256k1":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/curves/esm/secp256k1.js","@noble/hashes/hmac":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/hashes/esm/hmac.js","@noble/hashes/legacy":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/hashes/esm/legacy.js","@noble/hashes/sha2":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/hashes/esm/sha2.js","@noble/hashes/utils":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/hashes/esm/utils.js","@scure/base":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@scure/base/lib/esm/index.js"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@scure/bip32/lib/esm/package.json":{},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@scure/bip39/esm/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@scure/bip39/esm/package.json","@noble/hashes/pbkdf2":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/hashes/esm/pbkdf2.js","@noble/hashes/sha2":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/hashes/esm/sha2.js","@noble/hashes/utils":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/hashes/esm/utils.js","@scure/base":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@scure/base/lib/esm/index.js"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@scure/bip39/esm/package.json":{},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/b4a/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/b4a/package.json"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/b4a/package.json":{},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/bare-ansi-escapes/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/bare-ansi-escapes/package.json"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/bare-ansi-escapes/package.json":{},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/bare-assert/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/bare-assert/package.json","bare-inspect":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/bare-inspect/index.js"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/bare-assert/package.json":{},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/bare-inspect/binding.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/bare-inspect/package.json",".":"linked:libbare-inspect.3.1.4.so"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/bare-inspect/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/bare-inspect/package.json","./binding":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/bare-inspect/binding.js","bare-ansi-escapes":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/bare-ansi-escapes/index.js","bare-type":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/bare-type/index.js"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/bare-inspect/package.json":{},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/bare-type/binding.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/bare-type/package.json",".":"linked:libbare-type.1.1.0.so"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/bare-type/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/bare-type/package.json","./binding":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/bare-type/binding.js"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/bare-type/package.json":{},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/cborg.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/package.json","./lib/decode.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/decode.js","./lib/encode.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/encode.js","./lib/tagged.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/tagged.js","./lib/token.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/0uint.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/package.json","./common.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/1negint.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/2bytes.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/0uint.js","./byte-utils.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/3string.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/0uint.js","./2bytes.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/2bytes.js","./common.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/4array.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/5map.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/6tag.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/0uint.js","./token.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/7float.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/bl.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/package.json","./byte-utils.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/byte-utils.js"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/byte-utils.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/package.json"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/common.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/package.json"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/decode.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/package.json","./byte-utils.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/common.js","./jump.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/jump.js","./token.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/encode.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/0uint.js","./1negint.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/1negint.js","./2bytes.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/2bytes.js","./3string.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/3string.js","./4array.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/4array.js","./5map.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/5map.js","./6tag.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/6tag.js","./7float.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/7float.js","./bl.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/bl.js","./byte-utils.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/common.js","./is.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/is.js","./jump.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/jump.js","./token.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/is.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/package.json"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/jump.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/0uint.js","./1negint.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/1negint.js","./2bytes.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/2bytes.js","./3string.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/3string.js","./4array.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/4array.js","./5map.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/5map.js","./6tag.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/6tag.js","./7float.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/7float.js","./byte-utils.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/tagged.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/package.json"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/token.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/package.json"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/package.json":{},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/compact-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/compact-encoding/raw.js","b4a":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/compact-encoding/package.json":{},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/compact-encoding/endian.js","b4a":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/hypercore-crypto/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/hypercore-crypto/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/compact-encoding/index.js","sodium-universal":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/hypercore-crypto/package.json":{},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/multiformats/dist/src/bases/base.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/multiformats/package.json","../bytes.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/multiformats/dist/src/bytes.js","../vendor/base-x.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/multiformats/dist/src/vendor/base-x.js"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/multiformats/dist/src/bases/base32.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/multiformats/package.json","./base.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/multiformats/dist/src/bases/base.js"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/multiformats/dist/src/bases/base36.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/multiformats/package.json","./base.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/multiformats/dist/src/bases/base.js"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/multiformats/dist/src/bases/base58.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/multiformats/package.json","./base.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/multiformats/dist/src/bases/base.js"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/multiformats/dist/src/bases/base64.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/multiformats/package.json","./base.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/multiformats/dist/src/bases/base.js"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/multiformats/dist/src/bytes.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/multiformats/package.json"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/multiformats/dist/src/cid.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/multiformats/package.json","./bases/base32.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/multiformats/dist/src/bases/base32.js","./bases/base36.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/multiformats/dist/src/bases/base36.js","./bases/base58.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/multiformats/dist/src/bases/base58.js","./bytes.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/multiformats/dist/src/bytes.js","./hashes/digest.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/multiformats/dist/src/hashes/digest.js","./link/interface.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/multiformats/dist/src/link/interface.js","./varint.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/multiformats/dist/src/varint.js"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/multiformats/dist/src/hashes/digest.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/multiformats/package.json","../bytes.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/multiformats/dist/src/bytes.js","../varint.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/multiformats/dist/src/varint.js"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/multiformats/dist/src/link/interface.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/multiformats/package.json"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/multiformats/dist/src/varint.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/multiformats/package.json","./vendor/varint.js":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/multiformats/dist/src/vendor/varint.js"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/multiformats/dist/src/vendor/base-x.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/multiformats/package.json"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/multiformats/dist/src/vendor/varint.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/multiformats/package.json"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/multiformats/package.json":{},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/require-addon/lib/bare.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/require-addon/package.json"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/require-addon/package.json":{},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/sodium-native/binding.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/sodium-native/package.json",".":"linked:libsodium-native.5.1.0.so","require-addon":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/require-addon/lib/bare.js"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/sodium-native/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/sodium-native/package.json","./binding":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/sodium-native/binding.js","assert":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/bare-assert/index.js","which-runtime":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/which-runtime/index.js"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/sodium-native/package.json":{},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/sodium-universal/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/sodium-universal/package.json","sodium-native":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/sodium-native/index.js"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/sodium-universal/package.json":{},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/which-runtime/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-identity/node_modules/which-runtime/package.json"},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/which-runtime/package.json":{},"/node_modules/favela-web/node_modules/atproto-identity/package.json":{},"/node_modules/favela-web/node_modules/atproto-repo/lib/car.js":{"#package":"/node_modules/favela-web/node_modules/atproto-repo/package.json","@ipld/dag-cbor":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/src/index.js","multiformats/cid":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/multiformats/dist/src/cid.js"},"/node_modules/favela-web/node_modules/atproto-repo/lib/cid.js":{"#package":"/node_modules/favela-web/node_modules/atproto-repo/package.json","@ipld/dag-cbor":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/src/index.js","@noble/hashes/sha2":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/hashes/esm/sha2.js","multiformats/cid":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/multiformats/dist/src/cid.js","multiformats/codecs/raw":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/multiformats/dist/src/codecs/raw.js","multiformats/hashes/digest":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/multiformats/dist/src/hashes/digest.js"},"/node_modules/favela-web/node_modules/atproto-repo/lib/commit.js":{"#package":"/node_modules/favela-web/node_modules/atproto-repo/package.json","./cid.js":"/node_modules/favela-web/node_modules/atproto-repo/lib/cid.js","@ipld/dag-cbor":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/src/index.js","@noble/curves/secp256k1":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/curves/esm/secp256k1.js","@noble/hashes/sha2":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/hashes/esm/sha2.js"},"/node_modules/favela-web/node_modules/atproto-repo/lib/mst.js":{"#package":"/node_modules/favela-web/node_modules/atproto-repo/package.json","./cid.js":"/node_modules/favela-web/node_modules/atproto-repo/lib/cid.js","@ipld/dag-cbor":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/src/index.js","@noble/hashes/sha2":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/hashes/esm/sha2.js"},"/node_modules/favela-web/node_modules/atproto-repo/lib/repo.js":{"#package":"/node_modules/favela-web/node_modules/atproto-repo/package.json","./car.js":"/node_modules/favela-web/node_modules/atproto-repo/lib/car.js","./cid.js":"/node_modules/favela-web/node_modules/atproto-repo/lib/cid.js","./commit.js":"/node_modules/favela-web/node_modules/atproto-repo/lib/commit.js","./mst.js":"/node_modules/favela-web/node_modules/atproto-repo/lib/mst.js","@ipld/dag-cbor":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/src/index.js"},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/package.json":{},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/src/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/package.json","cborg":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/cborg.js","multiformats/cid":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/multiformats/dist/src/cid.js"},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/curves/esm/_shortw_utils.js":{"#package":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json","./abstract/weierstrass.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/weierstrass.js"},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/curve.js":{"#package":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json","../utils.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/curves/esm/utils.js","./modular.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/modular.js"},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/hash-to-curve.js":{"#package":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json","../utils.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/curves/esm/utils.js","./modular.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/modular.js"},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/modular.js":{"#package":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json","../utils.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/curves/esm/utils.js"},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/weierstrass.js":{"#package":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json","../utils.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/curves/esm/utils.js","./curve.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/curve.js","./modular.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/modular.js","@noble/hashes/hmac.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/hashes/esm/hmac.js","@noble/hashes/utils":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json":{},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/curves/esm/secp256k1.js":{"#package":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json","./_shortw_utils.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/curves/esm/_shortw_utils.js","./abstract/hash-to-curve.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/hash-to-curve.js","./abstract/modular.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/modular.js","./abstract/weierstrass.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/weierstrass.js","./utils.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/curves/esm/utils.js","@noble/hashes/sha2.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/hashes/esm/sha2.js","@noble/hashes/utils.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/curves/esm/utils.js":{"#package":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json","@noble/hashes/utils.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/hashes/esm/_md.js":{"#package":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json","./utils.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/hashes/esm/_u64.js":{"#package":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json"},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/hashes/esm/crypto.js":{"#package":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json"},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/hashes/esm/hmac.js":{"#package":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json","./utils.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json":{},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/hashes/esm/sha2.js":{"#package":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json","./_md.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/hashes/esm/_md.js","./_u64.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/hashes/esm/_u64.js","./utils.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js":{"#package":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json","@noble/hashes/crypto":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/hashes/esm/crypto.js"},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/cborg.js":{"#package":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/package.json","./lib/decode.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/decode.js","./lib/encode.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/encode.js","./lib/tagged.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/tagged.js","./lib/token.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js":{"#package":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/package.json","./common.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/1negint.js":{"#package":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/2bytes.js":{"#package":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./byte-utils.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/3string.js":{"#package":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./2bytes.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/2bytes.js","./common.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/4array.js":{"#package":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/5map.js":{"#package":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/6tag.js":{"#package":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./token.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/7float.js":{"#package":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/bl.js":{"#package":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/package.json","./byte-utils.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/byte-utils.js"},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/byte-utils.js":{"#package":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/package.json"},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/common.js":{"#package":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/package.json"},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/decode.js":{"#package":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/package.json","./byte-utils.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./jump.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/jump.js","./token.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/encode.js":{"#package":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./1negint.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/1negint.js","./2bytes.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/2bytes.js","./3string.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/3string.js","./4array.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/4array.js","./5map.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/5map.js","./6tag.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/6tag.js","./7float.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/7float.js","./bl.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/bl.js","./byte-utils.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./is.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/is.js","./jump.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/jump.js","./token.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/is.js":{"#package":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/package.json"},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/jump.js":{"#package":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./1negint.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/1negint.js","./2bytes.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/2bytes.js","./3string.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/3string.js","./4array.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/4array.js","./5map.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/5map.js","./6tag.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/6tag.js","./7float.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/7float.js","./byte-utils.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/tagged.js":{"#package":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/package.json"},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/token.js":{"#package":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/package.json"},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/package.json":{},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base.js":{"#package":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/multiformats/package.json","../bytes.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/multiformats/dist/src/bytes.js","../vendor/base-x.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/multiformats/dist/src/vendor/base-x.js"},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base32.js":{"#package":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/multiformats/package.json","./base.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base.js"},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base36.js":{"#package":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/multiformats/package.json","./base.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base.js"},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base58.js":{"#package":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/multiformats/package.json","./base.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base.js"},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/multiformats/dist/src/bytes.js":{"#package":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/multiformats/package.json"},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/multiformats/dist/src/cid.js":{"#package":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/multiformats/package.json","./bases/base32.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base32.js","./bases/base36.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base36.js","./bases/base58.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base58.js","./bytes.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/multiformats/dist/src/bytes.js","./hashes/digest.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/multiformats/dist/src/hashes/digest.js","./link/interface.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/multiformats/dist/src/link/interface.js","./varint.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/multiformats/dist/src/varint.js"},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/multiformats/dist/src/codecs/raw.js":{"#package":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/multiformats/package.json","../bytes.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/multiformats/dist/src/bytes.js"},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/multiformats/dist/src/hashes/digest.js":{"#package":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/multiformats/package.json","../bytes.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/multiformats/dist/src/bytes.js","../varint.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/multiformats/dist/src/varint.js"},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/multiformats/dist/src/link/interface.js":{"#package":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/multiformats/package.json"},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/multiformats/dist/src/varint.js":{"#package":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/multiformats/package.json","./vendor/varint.js":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/multiformats/dist/src/vendor/varint.js"},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/multiformats/dist/src/vendor/base-x.js":{"#package":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/multiformats/package.json"},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/multiformats/dist/src/vendor/varint.js":{"#package":"/node_modules/favela-web/node_modules/atproto-repo/node_modules/multiformats/package.json"},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/multiformats/package.json":{},"/node_modules/favela-web/node_modules/atproto-repo/package.json":{},"/node_modules/favela-web/node_modules/atproto-room/lib/pairing.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js","blind-pairing":"/node_modules/favela-web/node_modules/atproto-room/node_modules/blind-pairing/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hypercore-crypto/index.js","hyperswarm":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperswarm/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/@hyperswarm/secret-stream/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/@hyperswarm/secret-stream/package.json","./lib/bridge":"/node_modules/favela-web/node_modules/atproto-room/node_modules/@hyperswarm/secret-stream/lib/bridge.js","./lib/handshake":"/node_modules/favela-web/node_modules/atproto-room/node_modules/@hyperswarm/secret-stream/lib/handshake.js","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hypercore-crypto/index.js","sodium-secretstream":"/node_modules/favela-web/node_modules/atproto-room/node_modules/sodium-secretstream/index.js","sodium-universal":"/node_modules/favela-web/node_modules/atproto-room/node_modules/sodium-universal/index.js","streamx":"/node_modules/favela-web/node_modules/atproto-room/node_modules/streamx/index.js","timeout-refresh":"/node_modules/favela-web/node_modules/atproto-room/node_modules/timeout-refresh/index.js","unslab":"/node_modules/favela-web/node_modules/atproto-room/node_modules/unslab/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/@hyperswarm/secret-stream/lib/bridge.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/@hyperswarm/secret-stream/package.json","streamx":"/node_modules/favela-web/node_modules/atproto-room/node_modules/streamx/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/@hyperswarm/secret-stream/lib/handshake.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/@hyperswarm/secret-stream/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js","noise-curve-ed":"/node_modules/favela-web/node_modules/atproto-room/node_modules/noise-curve-ed/index.js","noise-handshake":"/node_modules/favela-web/node_modules/atproto-room/node_modules/noise-handshake/noise.js","sodium-universal":"/node_modules/favela-web/node_modules/atproto-room/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/@hyperswarm/secret-stream/package.json":{},"/node_modules/favela-web/node_modules/atproto-room/node_modules/adaptive-timeout/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/adaptive-timeout/package.json","xache":"/node_modules/favela-web/node_modules/atproto-room/node_modules/xache/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/adaptive-timeout/package.json":{},"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/package.json"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/package.json":{},"/node_modules/favela-web/node_modules/atproto-room/node_modules/bare-ansi-escapes/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/bare-ansi-escapes/package.json"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/bare-ansi-escapes/package.json":{},"/node_modules/favela-web/node_modules/atproto-room/node_modules/bare-assert/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/bare-assert/package.json","bare-inspect":"/node_modules/favela-web/node_modules/atproto-room/node_modules/bare-inspect/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/bare-assert/package.json":{},"/node_modules/favela-web/node_modules/atproto-room/node_modules/bare-events/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/bare-events/package.json","./lib/errors":"/node_modules/favela-web/node_modules/atproto-room/node_modules/bare-events/lib/errors.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/bare-events/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/bare-events/package.json"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/bare-events/package.json":{},"/node_modules/favela-web/node_modules/atproto-room/node_modules/bare-inspect/binding.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/bare-inspect/package.json",".":"linked:libbare-inspect.3.1.4.so"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/bare-inspect/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/bare-inspect/package.json","./binding":"/node_modules/favela-web/node_modules/atproto-room/node_modules/bare-inspect/binding.js","bare-ansi-escapes":"/node_modules/favela-web/node_modules/atproto-room/node_modules/bare-ansi-escapes/index.js","bare-type":"/node_modules/favela-web/node_modules/atproto-room/node_modules/bare-type/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/bare-inspect/package.json":{},"/node_modules/favela-web/node_modules/atproto-room/node_modules/bare-type/binding.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/bare-type/package.json",".":"linked:libbare-type.1.1.0.so"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/bare-type/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/bare-type/package.json","./binding":"/node_modules/favela-web/node_modules/atproto-room/node_modules/bare-type/binding.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/bare-type/package.json":{},"/node_modules/favela-web/node_modules/atproto-room/node_modules/bits-to-bytes/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/bits-to-bytes/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/bits-to-bytes/package.json":{},"/node_modules/favela-web/node_modules/atproto-room/node_modules/blind-pairing/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/blind-pairing/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js","blind-pairing-core":"/node_modules/favela-web/node_modules/blind-pairing-core/index.js","compact-encoding":"/node_modules/favela-web/node_modules/atproto-room/node_modules/compact-encoding/index.js","debounceify":"/node_modules/favela-web/node_modules/atproto-room/node_modules/debounceify/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hypercore-crypto/index.js","is-options":"/node_modules/favela-web/node_modules/atproto-room/node_modules/is-options/index.js","protomux":"/node_modules/favela-web/node_modules/atproto-room/node_modules/protomux/index.js","ready-resource":"/node_modules/favela-web/node_modules/atproto-room/node_modules/ready-resource/index.js","safety-catch":"/node_modules/favela-web/node_modules/atproto-room/node_modules/safety-catch/index.js","xache":"/node_modules/favela-web/node_modules/atproto-room/node_modules/xache/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/blind-pairing/package.json":{},"/node_modules/favela-web/node_modules/atproto-room/node_modules/blind-relay/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/blind-relay/package.json","./lib/errors":"/node_modules/favela-web/node_modules/atproto-room/node_modules/blind-relay/lib/errors.js","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js","bits-to-bytes":"/node_modules/favela-web/node_modules/atproto-room/node_modules/bits-to-bytes/index.js","compact-encoding":"/node_modules/favela-web/node_modules/atproto-room/node_modules/blind-relay/node_modules/compact-encoding/index.js","compact-encoding-bitfield":"/node_modules/favela-web/node_modules/atproto-room/node_modules/compact-encoding-bitfield/index.js","events":"/node_modules/favela-web/node_modules/atproto-room/node_modules/bare-events/index.js","protomux":"/node_modules/favela-web/node_modules/atproto-room/node_modules/protomux/index.js","sodium-universal":"/node_modules/favela-web/node_modules/atproto-room/node_modules/sodium-universal/index.js","streamx":"/node_modules/favela-web/node_modules/atproto-room/node_modules/streamx/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/blind-relay/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/blind-relay/package.json"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/blind-relay/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/blind-relay/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/blind-relay/node_modules/compact-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/blind-relay/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/atproto-room/node_modules/blind-relay/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/favela-web/node_modules/atproto-room/node_modules/blind-relay/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/favela-web/node_modules/atproto-room/node_modules/blind-relay/node_modules/compact-encoding/raw.js","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/blind-relay/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/blind-relay/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/blind-relay/node_modules/compact-encoding/package.json":{},"/node_modules/favela-web/node_modules/atproto-room/node_modules/blind-relay/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/blind-relay/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/atproto-room/node_modules/blind-relay/node_modules/compact-encoding/endian.js","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/blind-relay/package.json":{},"/node_modules/favela-web/node_modules/atproto-room/node_modules/bogon/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/bogon/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/atproto-room/node_modules/bogon/node_modules/compact-encoding/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/bogon/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/bogon/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/bogon/node_modules/compact-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/bogon/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/atproto-room/node_modules/bogon/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/favela-web/node_modules/atproto-room/node_modules/bogon/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/favela-web/node_modules/atproto-room/node_modules/bogon/node_modules/compact-encoding/raw.js","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/bogon/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/bogon/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/bogon/node_modules/compact-encoding/package.json":{},"/node_modules/favela-web/node_modules/atproto-room/node_modules/bogon/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/bogon/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/atproto-room/node_modules/bogon/node_modules/compact-encoding/endian.js","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/bogon/package.json":{},"/node_modules/favela-web/node_modules/atproto-room/node_modules/compact-encoding-bitfield/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/compact-encoding-bitfield/package.json","compact-encoding":"/node_modules/favela-web/node_modules/atproto-room/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/atproto-room/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/favela-web/node_modules/atproto-room/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/favela-web/node_modules/atproto-room/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/raw.js","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/package.json":{},"/node_modules/favela-web/node_modules/atproto-room/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/atproto-room/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/endian.js","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/compact-encoding-bitfield/package.json":{},"/node_modules/favela-web/node_modules/atproto-room/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/compact-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/atproto-room/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/favela-web/node_modules/atproto-room/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/favela-web/node_modules/atproto-room/node_modules/compact-encoding/raw.js","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/compact-encoding/package.json":{},"/node_modules/favela-web/node_modules/atproto-room/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/atproto-room/node_modules/compact-encoding/endian.js","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/debounceify/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/debounceify/package.json"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/debounceify/package.json":{},"/node_modules/favela-web/node_modules/atproto-room/node_modules/dht-rpc/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/dht-rpc/package.json","./lib/commands":"/node_modules/favela-web/node_modules/atproto-room/node_modules/dht-rpc/lib/commands.js","./lib/errors":"/node_modules/favela-web/node_modules/atproto-room/node_modules/dht-rpc/lib/errors.js","./lib/health":"/node_modules/favela-web/node_modules/atproto-room/node_modules/dht-rpc/lib/health.js","./lib/io":"/node_modules/favela-web/node_modules/atproto-room/node_modules/dht-rpc/lib/io.js","./lib/peer":"/node_modules/favela-web/node_modules/atproto-room/node_modules/dht-rpc/lib/peer.js","./lib/query":"/node_modules/favela-web/node_modules/atproto-room/node_modules/dht-rpc/lib/query.js","./lib/session":"/node_modules/favela-web/node_modules/atproto-room/node_modules/dht-rpc/lib/session.js","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/atproto-room/node_modules/dht-rpc/node_modules/compact-encoding/index.js","events":"/node_modules/favela-web/node_modules/atproto-room/node_modules/bare-events/index.js","kademlia-routing-table":"/node_modules/favela-web/node_modules/atproto-room/node_modules/kademlia-routing-table/index.js","nat-sampler":"/node_modules/favela-web/node_modules/atproto-room/node_modules/nat-sampler/index.js","sodium-universal":"/node_modules/favela-web/node_modules/atproto-room/node_modules/sodium-universal/index.js","time-ordered-set":"/node_modules/favela-web/node_modules/atproto-room/node_modules/time-ordered-set/index.js","udx-native":"/node_modules/favela-web/node_modules/atproto-room/node_modules/udx-native/lib/udx.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/dht-rpc/lib/commands.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/dht-rpc/package.json"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/dht-rpc/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/dht-rpc/package.json"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/dht-rpc/lib/health.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/dht-rpc/package.json"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/dht-rpc/lib/io.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/dht-rpc/package.json","./errors":"/node_modules/favela-web/node_modules/atproto-room/node_modules/dht-rpc/lib/errors.js","./peer":"/node_modules/favela-web/node_modules/atproto-room/node_modules/dht-rpc/lib/peer.js","adaptive-timeout":"/node_modules/favela-web/node_modules/atproto-room/node_modules/adaptive-timeout/index.js","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/atproto-room/node_modules/dht-rpc/node_modules/compact-encoding/index.js","fast-fifo":"/node_modules/favela-web/node_modules/atproto-room/node_modules/fast-fifo/index.js","sodium-universal":"/node_modules/favela-web/node_modules/atproto-room/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/dht-rpc/lib/peer.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/dht-rpc/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/atproto-room/node_modules/dht-rpc/node_modules/compact-encoding/index.js","sodium-universal":"/node_modules/favela-web/node_modules/atproto-room/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/dht-rpc/lib/query.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/dht-rpc/package.json","./commands":"/node_modules/favela-web/node_modules/atproto-room/node_modules/dht-rpc/lib/commands.js","./peer":"/node_modules/favela-web/node_modules/atproto-room/node_modules/dht-rpc/lib/peer.js","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js","streamx":"/node_modules/favela-web/node_modules/atproto-room/node_modules/streamx/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/dht-rpc/lib/session.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/dht-rpc/package.json"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/dht-rpc/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/dht-rpc/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/dht-rpc/node_modules/compact-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/dht-rpc/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/atproto-room/node_modules/dht-rpc/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/favela-web/node_modules/atproto-room/node_modules/dht-rpc/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/favela-web/node_modules/atproto-room/node_modules/dht-rpc/node_modules/compact-encoding/raw.js","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/dht-rpc/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/dht-rpc/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/dht-rpc/node_modules/compact-encoding/package.json":{},"/node_modules/favela-web/node_modules/atproto-room/node_modules/dht-rpc/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/dht-rpc/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/atproto-room/node_modules/dht-rpc/node_modules/compact-encoding/endian.js","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/dht-rpc/package.json":{},"/node_modules/favela-web/node_modules/atproto-room/node_modules/events-universal/bare.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/events-universal/package.json","bare-events":"/node_modules/favela-web/node_modules/atproto-room/node_modules/bare-events/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/events-universal/package.json":{},"/node_modules/favela-web/node_modules/atproto-room/node_modules/fast-fifo/fixed-size.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/fast-fifo/package.json"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/fast-fifo/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/fast-fifo/package.json","./fixed-size":"/node_modules/favela-web/node_modules/atproto-room/node_modules/fast-fifo/fixed-size.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/fast-fifo/package.json":{},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hypercore-crypto/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hypercore-crypto/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hypercore-crypto/node_modules/compact-encoding/index.js","sodium-universal":"/node_modules/favela-web/node_modules/atproto-room/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hypercore-crypto/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hypercore-crypto/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hypercore-crypto/node_modules/compact-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hypercore-crypto/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hypercore-crypto/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hypercore-crypto/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hypercore-crypto/node_modules/compact-encoding/raw.js","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hypercore-crypto/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hypercore-crypto/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hypercore-crypto/node_modules/compact-encoding/package.json":{},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hypercore-crypto/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hypercore-crypto/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hypercore-crypto/node_modules/compact-encoding/endian.js","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hypercore-crypto/package.json":{},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hypercore-id-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hypercore-id-encoding/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js","z32":"/node_modules/favela-web/node_modules/atproto-room/node_modules/z32/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hypercore-id-encoding/package.json":{},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht-address/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht-address/package.json","./spec/hyperschema":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht-address/spec/hyperschema/index.js","compact-encoding":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht-address/node_modules/compact-encoding/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht-address/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht-address/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht-address/node_modules/compact-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht-address/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht-address/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht-address/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht-address/node_modules/compact-encoding/raw.js","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht-address/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht-address/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht-address/node_modules/compact-encoding/package.json":{},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht-address/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht-address/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht-address/node_modules/compact-encoding/endian.js","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht-address/package.json":{},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht-address/spec/hyperschema/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht-address/package.json","hyperschema/runtime":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperschema/runtime.cjs"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/package.json","./lib/connect":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/connect.js","./lib/connection-pool":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/connection-pool.js","./lib/constants":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/constants.js","./lib/crypto":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/crypto.js","./lib/errors":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/errors.js","./lib/messages":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/messages.js","./lib/persistent":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/persistent.js","./lib/raw-stream-set":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/raw-stream-set.js","./lib/router":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/router.js","./lib/server":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/server.js","./lib/socket-pool":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/socket-pool.js","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/index.js","dht-rpc":"/node_modules/favela-web/node_modules/atproto-room/node_modules/dht-rpc/index.js","safety-catch":"/node_modules/favela-web/node_modules/atproto-room/node_modules/safety-catch/index.js","sodium-universal":"/node_modules/favela-web/node_modules/atproto-room/node_modules/sodium-universal/index.js","xache":"/node_modules/favela-web/node_modules/atproto-room/node_modules/xache/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/announcer.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/package.json","./constants":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/constants.js","./encode":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/encode.js","./messages":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/messages.js","./persistent":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/persistent.js","./sleeper":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/sleeper.js","compact-encoding":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/index.js","safety-catch":"/node_modules/favela-web/node_modules/atproto-room/node_modules/safety-catch/index.js","signal-promise":"/node_modules/favela-web/node_modules/atproto-room/node_modules/signal-promise/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/connect.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/package.json","./constants":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/constants.js","./crypto":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/crypto.js","./errors":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/errors.js","./holepuncher":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/holepuncher.js","./noise-wrap":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/noise-wrap.js","./relay-connection":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/relay-connection.js","./secure-payload":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/secure-payload.js","./semaphore":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/semaphore.js","./sleeper":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/sleeper.js","@hyperswarm/secret-stream":"/node_modules/favela-web/node_modules/atproto-room/node_modules/@hyperswarm/secret-stream/index.js","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js","blind-relay":"/node_modules/favela-web/node_modules/atproto-room/node_modules/blind-relay/index.js","bogon":"/node_modules/favela-web/node_modules/atproto-room/node_modules/bogon/index.js","hypercore-id-encoding":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hypercore-id-encoding/index.js","hyperdht-address":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht-address/index.js","safety-catch":"/node_modules/favela-web/node_modules/atproto-room/node_modules/safety-catch/index.js","unslab":"/node_modules/favela-web/node_modules/atproto-room/node_modules/unslab/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/connection-pool.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/package.json","./errors":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/errors.js","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js","events":"/node_modules/favela-web/node_modules/atproto-room/node_modules/bare-events/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/constants.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/package.json","hypercore-crypto":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hypercore-crypto/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/crypto.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js","sodium-universal":"/node_modules/favela-web/node_modules/atproto-room/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/encode.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/package.json"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/holepuncher.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/package.json","./constants":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/constants.js","./nat":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/nat.js","./sleeper":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/sleeper.js","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/messages.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/package.json","compact-encoding":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/nat.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/package.json","../lib/constants":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/constants.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/noise-wrap.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/package.json","./constants":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/constants.js","./errors":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/errors.js","./messages":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/messages.js","@hyperswarm/secret-stream":"/node_modules/favela-web/node_modules/atproto-room/node_modules/@hyperswarm/secret-stream/index.js","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/index.js","noise-curve-ed":"/node_modules/favela-web/node_modules/atproto-room/node_modules/noise-curve-ed/index.js","noise-handshake":"/node_modules/favela-web/node_modules/atproto-room/node_modules/noise-handshake/noise.js","sodium-universal":"/node_modules/favela-web/node_modules/atproto-room/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/persistent.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/package.json","./constants":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/constants.js","./encode":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/encode.js","./messages":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/messages.js","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/index.js","record-cache":"/node_modules/favela-web/node_modules/atproto-room/node_modules/record-cache/index.js","sodium-universal":"/node_modules/favela-web/node_modules/atproto-room/node_modules/sodium-universal/index.js","unslab":"/node_modules/favela-web/node_modules/atproto-room/node_modules/unslab/index.js","xache":"/node_modules/favela-web/node_modules/atproto-room/node_modules/xache/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/raw-stream-set.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/package.json"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/relay-connection.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js","safety-catch":"/node_modules/favela-web/node_modules/atproto-room/node_modules/safety-catch/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/router.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/package.json","./constants":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/constants.js","./errors":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/errors.js","./messages":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/messages.js","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/index.js","safety-catch":"/node_modules/favela-web/node_modules/atproto-room/node_modules/safety-catch/index.js","xache":"/node_modules/favela-web/node_modules/atproto-room/node_modules/xache/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/secure-payload.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/package.json","./messages":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/messages.js","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js","sodium-universal":"/node_modules/favela-web/node_modules/atproto-room/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/semaphore.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/package.json"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/server.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/package.json","./announcer":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/announcer.js","./constants":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/constants.js","./crypto":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/crypto.js","./errors":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/errors.js","./holepuncher":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/holepuncher.js","./noise-wrap":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/noise-wrap.js","./relay-connection":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/relay-connection.js","./secure-payload":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/secure-payload.js","@hyperswarm/secret-stream":"/node_modules/favela-web/node_modules/atproto-room/node_modules/@hyperswarm/secret-stream/index.js","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js","blind-relay":"/node_modules/favela-web/node_modules/atproto-room/node_modules/blind-relay/index.js","bogon":"/node_modules/favela-web/node_modules/atproto-room/node_modules/bogon/index.js","events":"/node_modules/favela-web/node_modules/atproto-room/node_modules/bare-events/index.js","safety-catch":"/node_modules/favela-web/node_modules/atproto-room/node_modules/safety-catch/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/sleeper.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/package.json"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/socket-pool.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/raw.js","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/package.json":{},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/endian.js","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/package.json":{},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperschema/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperschema/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperschema/node_modules/compact-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperschema/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperschema/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperschema/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperschema/node_modules/compact-encoding/raw.js","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperschema/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperschema/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperschema/node_modules/compact-encoding/package.json":{},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperschema/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperschema/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperschema/node_modules/compact-encoding/endian.js","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperschema/package.json":{},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperschema/runtime.cjs":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperschema/package.json","compact-encoding":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperschema/node_modules/compact-encoding/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperswarm/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperswarm/package.json","./lib/connection-set":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperswarm/lib/connection-set.js","./lib/peer-discovery":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperswarm/lib/peer-discovery.js","./lib/peer-info":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperswarm/lib/peer-info.js","./lib/retry-timer":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperswarm/lib/retry-timer.js","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js","events":"/node_modules/favela-web/node_modules/atproto-room/node_modules/bare-events/index.js","hyperdht":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/index.js","shuffled-priority-queue":"/node_modules/favela-web/node_modules/atproto-room/node_modules/shuffled-priority-queue/index.js","streamx":"/node_modules/favela-web/node_modules/atproto-room/node_modules/streamx/index.js","unslab":"/node_modules/favela-web/node_modules/atproto-room/node_modules/unslab/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperswarm/lib/bulk-timer.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperswarm/package.json"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperswarm/lib/connection-set.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperswarm/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperswarm/lib/peer-discovery.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperswarm/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js","safety-catch":"/node_modules/favela-web/node_modules/atproto-room/node_modules/safety-catch/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperswarm/lib/peer-info.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperswarm/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js","events":"/node_modules/favela-web/node_modules/atproto-room/node_modules/bare-events/index.js","unslab":"/node_modules/favela-web/node_modules/atproto-room/node_modules/unslab/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperswarm/lib/retry-timer.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperswarm/package.json","./bulk-timer":"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperswarm/lib/bulk-timer.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperswarm/package.json":{},"/node_modules/favela-web/node_modules/atproto-room/node_modules/is-options/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/is-options/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/is-options/package.json":{},"/node_modules/favela-web/node_modules/atproto-room/node_modules/kademlia-routing-table/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/kademlia-routing-table/package.json","events":"/node_modules/favela-web/node_modules/atproto-room/node_modules/bare-events/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/kademlia-routing-table/package.json":{},"/node_modules/favela-web/node_modules/atproto-room/node_modules/nanoassert/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/nanoassert/package.json"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/nanoassert/package.json":{},"/node_modules/favela-web/node_modules/atproto-room/node_modules/nat-sampler/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/nat-sampler/package.json"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/nat-sampler/package.json":{},"/node_modules/favela-web/node_modules/atproto-room/node_modules/noise-curve-ed/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/noise-curve-ed/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js","nanoassert":"/node_modules/favela-web/node_modules/atproto-room/node_modules/nanoassert/index.js","sodium-universal":"/node_modules/favela-web/node_modules/atproto-room/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/noise-curve-ed/package.json":{},"/node_modules/favela-web/node_modules/atproto-room/node_modules/noise-handshake/cipher.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/noise-handshake/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js","sodium-universal":"/node_modules/favela-web/node_modules/atproto-room/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/noise-handshake/dh.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/noise-handshake/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js","nanoassert":"/node_modules/favela-web/node_modules/atproto-room/node_modules/nanoassert/index.js","sodium-universal":"/node_modules/favela-web/node_modules/atproto-room/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/noise-handshake/hkdf.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/noise-handshake/package.json","./hmac":"/node_modules/favela-web/node_modules/atproto-room/node_modules/noise-handshake/hmac.js","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/noise-handshake/hmac.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/noise-handshake/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js","sodium-universal":"/node_modules/favela-web/node_modules/atproto-room/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/noise-handshake/noise.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/noise-handshake/package.json","./hkdf":"/node_modules/favela-web/node_modules/atproto-room/node_modules/noise-handshake/hkdf.js","./symmetric-state":"/node_modules/favela-web/node_modules/atproto-room/node_modules/noise-handshake/symmetric-state.js","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js","nanoassert":"/node_modules/favela-web/node_modules/atproto-room/node_modules/nanoassert/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/noise-handshake/package.json":{},"/node_modules/favela-web/node_modules/atproto-room/node_modules/noise-handshake/symmetric-state.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/noise-handshake/package.json","./cipher":"/node_modules/favela-web/node_modules/atproto-room/node_modules/noise-handshake/cipher.js","./dh":"/node_modules/favela-web/node_modules/atproto-room/node_modules/noise-handshake/dh.js","./hkdf":"/node_modules/favela-web/node_modules/atproto-room/node_modules/noise-handshake/hkdf.js","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js","nanoassert":"/node_modules/favela-web/node_modules/atproto-room/node_modules/nanoassert/index.js","sodium-universal":"/node_modules/favela-web/node_modules/atproto-room/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/protomux/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/protomux/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/atproto-room/node_modules/protomux/node_modules/compact-encoding/index.js","queue-tick":"/node_modules/favela-web/node_modules/atproto-room/node_modules/queue-tick/process-next-tick.js","safety-catch":"/node_modules/favela-web/node_modules/atproto-room/node_modules/safety-catch/index.js","unslab":"/node_modules/favela-web/node_modules/atproto-room/node_modules/unslab/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/protomux/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/protomux/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/protomux/node_modules/compact-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/protomux/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/atproto-room/node_modules/protomux/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/favela-web/node_modules/atproto-room/node_modules/protomux/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/favela-web/node_modules/atproto-room/node_modules/protomux/node_modules/compact-encoding/raw.js","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/protomux/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/protomux/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/protomux/node_modules/compact-encoding/package.json":{},"/node_modules/favela-web/node_modules/atproto-room/node_modules/protomux/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/protomux/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/atproto-room/node_modules/protomux/node_modules/compact-encoding/endian.js","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/protomux/package.json":{},"/node_modules/favela-web/node_modules/atproto-room/node_modules/queue-tick/package.json":{},"/node_modules/favela-web/node_modules/atproto-room/node_modules/queue-tick/process-next-tick.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/queue-tick/package.json","./queue-microtask":"/node_modules/favela-web/node_modules/atproto-room/node_modules/queue-tick/queue-microtask.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/queue-tick/queue-microtask.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/queue-tick/package.json"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/ready-resource/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/ready-resource/package.json","events":"/node_modules/favela-web/node_modules/atproto-room/node_modules/bare-events/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/ready-resource/package.json":{},"/node_modules/favela-web/node_modules/atproto-room/node_modules/record-cache/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/record-cache/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/record-cache/package.json":{},"/node_modules/favela-web/node_modules/atproto-room/node_modules/require-addon/lib/bare.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/require-addon/package.json"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/require-addon/package.json":{},"/node_modules/favela-web/node_modules/atproto-room/node_modules/safety-catch/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/safety-catch/package.json"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/safety-catch/package.json":{},"/node_modules/favela-web/node_modules/atproto-room/node_modules/shuffled-priority-queue/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/shuffled-priority-queue/package.json","unordered-set":"/node_modules/favela-web/node_modules/atproto-room/node_modules/unordered-set/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/shuffled-priority-queue/package.json":{},"/node_modules/favela-web/node_modules/atproto-room/node_modules/signal-promise/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/signal-promise/package.json"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/signal-promise/package.json":{},"/node_modules/favela-web/node_modules/atproto-room/node_modules/sodium-native/binding.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/sodium-native/package.json",".":"linked:libsodium-native.5.1.0.so","require-addon":"/node_modules/favela-web/node_modules/atproto-room/node_modules/require-addon/lib/bare.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/sodium-native/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/sodium-native/package.json","./binding":"/node_modules/favela-web/node_modules/atproto-room/node_modules/sodium-native/binding.js","assert":"/node_modules/favela-web/node_modules/atproto-room/node_modules/bare-assert/index.js","which-runtime":"/node_modules/favela-web/node_modules/atproto-room/node_modules/which-runtime/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/sodium-native/package.json":{},"/node_modules/favela-web/node_modules/atproto-room/node_modules/sodium-secretstream/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/sodium-secretstream/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js","sodium-universal":"/node_modules/favela-web/node_modules/atproto-room/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/sodium-secretstream/package.json":{},"/node_modules/favela-web/node_modules/atproto-room/node_modules/sodium-universal/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/sodium-universal/package.json","sodium-native":"/node_modules/favela-web/node_modules/atproto-room/node_modules/sodium-native/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/sodium-universal/package.json":{},"/node_modules/favela-web/node_modules/atproto-room/node_modules/streamx/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/streamx/package.json","./lib/errors.js":"/node_modules/favela-web/node_modules/atproto-room/node_modules/streamx/lib/errors.js","events-universal":"/node_modules/favela-web/node_modules/atproto-room/node_modules/events-universal/bare.js","fast-fifo":"/node_modules/favela-web/node_modules/atproto-room/node_modules/fast-fifo/index.js","text-decoder":"/node_modules/favela-web/node_modules/atproto-room/node_modules/text-decoder/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/streamx/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/streamx/package.json"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/streamx/package.json":{},"/node_modules/favela-web/node_modules/atproto-room/node_modules/text-decoder/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/text-decoder/package.json","./lib/pass-through-decoder":"/node_modules/favela-web/node_modules/atproto-room/node_modules/text-decoder/lib/pass-through-decoder.js","./lib/utf8-decoder":"/node_modules/favela-web/node_modules/atproto-room/node_modules/text-decoder/lib/utf8-decoder.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/text-decoder/lib/pass-through-decoder.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/text-decoder/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/text-decoder/lib/utf8-decoder.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/text-decoder/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/text-decoder/package.json":{},"/node_modules/favela-web/node_modules/atproto-room/node_modules/time-ordered-set/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/time-ordered-set/package.json"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/time-ordered-set/package.json":{},"/node_modules/favela-web/node_modules/atproto-room/node_modules/timeout-refresh/browser.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/timeout-refresh/package.json"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/timeout-refresh/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/timeout-refresh/package.json","./browser":"/node_modules/favela-web/node_modules/atproto-room/node_modules/timeout-refresh/browser.js","./node":"/node_modules/favela-web/node_modules/atproto-room/node_modules/timeout-refresh/node.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/timeout-refresh/node.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/timeout-refresh/package.json"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/timeout-refresh/package.json":{},"/node_modules/favela-web/node_modules/atproto-room/node_modules/udx-native/binding.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/udx-native/package.json",".":"linked:libudx-native.1.20.7.so","require-addon":"/node_modules/favela-web/node_modules/atproto-room/node_modules/require-addon/lib/bare.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/udx-native/lib/ip.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/udx-native/package.json"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/udx-native/lib/network-interfaces.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/udx-native/package.json","../binding":"/node_modules/favela-web/node_modules/atproto-room/node_modules/udx-native/binding.js","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js","events":"/node_modules/favela-web/node_modules/atproto-room/node_modules/bare-events/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/udx-native/lib/socket.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/udx-native/package.json","../binding":"/node_modules/favela-web/node_modules/atproto-room/node_modules/udx-native/binding.js","./ip":"/node_modules/favela-web/node_modules/atproto-room/node_modules/udx-native/lib/ip.js","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js","events":"/node_modules/favela-web/node_modules/atproto-room/node_modules/bare-events/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/udx-native/lib/stream.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/udx-native/package.json","../binding":"/node_modules/favela-web/node_modules/atproto-room/node_modules/udx-native/binding.js","./ip":"/node_modules/favela-web/node_modules/atproto-room/node_modules/udx-native/lib/ip.js","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js","streamx":"/node_modules/favela-web/node_modules/atproto-room/node_modules/streamx/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/udx-native/lib/udx.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/udx-native/package.json","../binding":"/node_modules/favela-web/node_modules/atproto-room/node_modules/udx-native/binding.js","./ip":"/node_modules/favela-web/node_modules/atproto-room/node_modules/udx-native/lib/ip.js","./network-interfaces":"/node_modules/favela-web/node_modules/atproto-room/node_modules/udx-native/lib/network-interfaces.js","./socket":"/node_modules/favela-web/node_modules/atproto-room/node_modules/udx-native/lib/socket.js","./stream":"/node_modules/favela-web/node_modules/atproto-room/node_modules/udx-native/lib/stream.js","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/udx-native/package.json":{},"/node_modules/favela-web/node_modules/atproto-room/node_modules/unordered-set/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/unordered-set/package.json"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/unordered-set/package.json":{},"/node_modules/favela-web/node_modules/atproto-room/node_modules/unslab/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/unslab/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/unslab/package.json":{},"/node_modules/favela-web/node_modules/atproto-room/node_modules/which-runtime/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/which-runtime/package.json"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/which-runtime/package.json":{},"/node_modules/favela-web/node_modules/atproto-room/node_modules/xache/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/xache/package.json"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/xache/package.json":{},"/node_modules/favela-web/node_modules/atproto-room/node_modules/z32/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-room/node_modules/z32/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-room/node_modules/z32/package.json":{},"/node_modules/favela-web/node_modules/atproto-room/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/lib/corestore.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/package.json","corestore":"/node_modules/favela-web/node_modules/atproto-store/node_modules/corestore/index.js"},"/node_modules/favela-web/node_modules/atproto-store/lib/firehose.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/package.json","@ipld/dag-cbor":"/node_modules/favela-web/node_modules/atproto-store/node_modules/@ipld/dag-cbor/src/index.js","atproto-repo/lib/commit.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/lib/commit.js","atproto-repo/lib/repo.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/lib/repo.js"},"/node_modules/favela-web/node_modules/atproto-store/lib/overlay-repo-store.js":{"#node:fs":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-fs/index.js","#node:path":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-path/index.js","#package":"/node_modules/favela-web/node_modules/atproto-store/package.json","./tid.js":"/node_modules/favela-web/node_modules/atproto-store/lib/tid.js","@ipld/dag-cbor":"/node_modules/favela-web/node_modules/atproto-store/node_modules/@ipld/dag-cbor/src/index.js","b4a":"/node_modules/favela-web/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-store/lib/tid.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/package.json"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/@hyperswarm/secret-stream/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/@hyperswarm/secret-stream/package.json","./lib/bridge":"/node_modules/favela-web/node_modules/atproto-store/node_modules/@hyperswarm/secret-stream/lib/bridge.js","./lib/handshake":"/node_modules/favela-web/node_modules/atproto-store/node_modules/@hyperswarm/secret-stream/lib/handshake.js","b4a":"/node_modules/favela-web/node_modules/atproto-store/node_modules/b4a/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-crypto/index.js","sodium-secretstream":"/node_modules/favela-web/node_modules/atproto-store/node_modules/sodium-secretstream/index.js","sodium-universal":"/node_modules/favela-web/node_modules/atproto-store/node_modules/sodium-universal/index.js","streamx":"/node_modules/favela-web/node_modules/atproto-store/node_modules/streamx/index.js","timeout-refresh":"/node_modules/favela-web/node_modules/atproto-store/node_modules/timeout-refresh/index.js","unslab":"/node_modules/favela-web/node_modules/atproto-store/node_modules/unslab/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/@hyperswarm/secret-stream/lib/bridge.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/@hyperswarm/secret-stream/package.json","streamx":"/node_modules/favela-web/node_modules/atproto-store/node_modules/streamx/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/@hyperswarm/secret-stream/lib/handshake.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/@hyperswarm/secret-stream/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-store/node_modules/b4a/index.js","noise-curve-ed":"/node_modules/favela-web/node_modules/atproto-store/node_modules/noise-curve-ed/index.js","noise-handshake":"/node_modules/favela-web/node_modules/atproto-store/node_modules/noise-handshake/noise.js","sodium-universal":"/node_modules/favela-web/node_modules/atproto-store/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/@hyperswarm/secret-stream/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/@ipld/dag-cbor/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/@ipld/dag-cbor/src/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/@ipld/dag-cbor/package.json","cborg":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/cborg.js","multiformats/cid":"/node_modules/favela-web/node_modules/atproto-store/node_modules/multiformats/dist/src/cid.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/lib/car.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/package.json","@ipld/dag-cbor":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/src/index.js","multiformats/cid":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/cid.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/lib/cid.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/package.json","@ipld/dag-cbor":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/src/index.js","@noble/hashes/sha2":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/sha2.js","multiformats/cid":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/cid.js","multiformats/codecs/raw":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/codecs/raw.js","multiformats/hashes/digest":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/hashes/digest.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/lib/commit.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/package.json","./cid.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/lib/cid.js","@ipld/dag-cbor":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/src/index.js","@noble/curves/secp256k1":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/secp256k1.js","@noble/hashes/sha2":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/sha2.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/lib/mst.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/package.json","./cid.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/lib/cid.js","@ipld/dag-cbor":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/src/index.js","@noble/hashes/sha2":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/sha2.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/lib/repo.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/package.json","./car.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/lib/car.js","./cid.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/lib/cid.js","./commit.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/lib/commit.js","./mst.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/lib/mst.js","@ipld/dag-cbor":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/src/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/src/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/package.json","cborg":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/cborg.js","multiformats/cid":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/cid.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/_shortw_utils.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json","./abstract/weierstrass.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/weierstrass.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/curve.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json","../utils.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/utils.js","./modular.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/modular.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/hash-to-curve.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json","../utils.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/utils.js","./modular.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/modular.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/modular.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json","../utils.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/utils.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/weierstrass.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json","../utils.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/utils.js","./curve.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/curve.js","./modular.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/modular.js","@noble/hashes/hmac.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/hmac.js","@noble/hashes/utils":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/secp256k1.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json","./_shortw_utils.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/_shortw_utils.js","./abstract/hash-to-curve.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/hash-to-curve.js","./abstract/modular.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/modular.js","./abstract/weierstrass.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/weierstrass.js","./utils.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/utils.js","@noble/hashes/sha2.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/sha2.js","@noble/hashes/utils.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/utils.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json","@noble/hashes/utils.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/_md.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json","./utils.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/_u64.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/crypto.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/hmac.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json","./utils.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/sha2.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json","./_md.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/_md.js","./_u64.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/_u64.js","./utils.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json","@noble/hashes/crypto":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/crypto.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/cborg.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json","./lib/decode.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/decode.js","./lib/encode.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/encode.js","./lib/tagged.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/tagged.js","./lib/token.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json","./common.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/1negint.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/2bytes.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./byte-utils.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/3string.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./2bytes.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/2bytes.js","./common.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/4array.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/5map.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/6tag.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./token.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/7float.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/bl.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json","./byte-utils.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/byte-utils.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/byte-utils.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/common.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/decode.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json","./byte-utils.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./jump.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/jump.js","./token.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/encode.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./1negint.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/1negint.js","./2bytes.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/2bytes.js","./3string.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/3string.js","./4array.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/4array.js","./5map.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/5map.js","./6tag.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/6tag.js","./7float.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/7float.js","./bl.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/bl.js","./byte-utils.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./is.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/is.js","./jump.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/jump.js","./token.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/is.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/jump.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./1negint.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/1negint.js","./2bytes.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/2bytes.js","./3string.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/3string.js","./4array.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/4array.js","./5map.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/5map.js","./6tag.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/6tag.js","./7float.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/7float.js","./byte-utils.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/tagged.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/token.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/package.json","../bytes.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bytes.js","../vendor/base-x.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/vendor/base-x.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base32.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/package.json","./base.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base36.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/package.json","./base.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base58.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/package.json","./base.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bytes.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/package.json"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/cid.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/package.json","./bases/base32.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base32.js","./bases/base36.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base36.js","./bases/base58.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base58.js","./bytes.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bytes.js","./hashes/digest.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/hashes/digest.js","./link/interface.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/link/interface.js","./varint.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/varint.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/codecs/raw.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/package.json","../bytes.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bytes.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/hashes/digest.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/package.json","../bytes.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bytes.js","../varint.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/varint.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/link/interface.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/package.json"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/varint.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/package.json","./vendor/varint.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/vendor/varint.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/vendor/base-x.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/package.json"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/vendor/varint.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/package.json"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/b4a/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/b4a/package.json"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/b4a/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-ansi-escapes/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-ansi-escapes/package.json"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-ansi-escapes/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-assert/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-assert/package.json","bare-inspect":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-inspect/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-assert/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-events/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-events/package.json","./lib/errors":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-events/lib/errors.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-events/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-events/package.json"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-events/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-fs/binding.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-fs/package.json",".":"linked:libbare-fs.4.7.3.so"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-fs/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-fs/package.json","./binding":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-fs/binding.js","./lib/constants":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-fs/lib/constants.js","./lib/errors":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-fs/lib/errors.js","./promises":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-fs/promises.js","bare-events":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-events/index.js","bare-path":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-path/index.js","bare-stream":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-stream/index.js","bare-url":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-url/index.js","fast-fifo":"/node_modules/favela-web/node_modules/atproto-store/node_modules/fast-fifo/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-fs/lib/constants.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-fs/package.json","../binding":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-fs/binding.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-fs/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-fs/package.json","bare-os":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-os/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-fs/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-fs/promises.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-fs/package.json",".":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-fs/index.js","bare-events":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-events/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-inspect/binding.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-inspect/package.json",".":"linked:libbare-inspect.3.1.4.so"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-inspect/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-inspect/package.json","./binding":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-inspect/binding.js","bare-ansi-escapes":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-ansi-escapes/index.js","bare-type":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-type/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-inspect/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-os/binding.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-os/package.json",".":"linked:libbare-os.3.9.3.so"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-os/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-os/package.json","./binding":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-os/binding.js","./lib/constants":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-os/lib/constants.js","./lib/errors":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-os/lib/errors.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-os/lib/constants.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-os/package.json","../binding":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-os/binding.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-os/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-os/package.json"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-os/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-path/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-path/package.json","./lib/posix":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-path/lib/posix.js","./lib/win32":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-path/lib/win32.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-path/lib/constants.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-path/package.json"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-path/lib/posix.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-path/package.json","./constants":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-path/lib/constants.js","./shared":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-path/lib/shared.js","./win32":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-path/lib/win32.js","bare-os":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-os/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-path/lib/shared.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-path/package.json","./constants":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-path/lib/constants.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-path/lib/win32.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-path/package.json","./constants":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-path/lib/constants.js","./posix":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-path/lib/posix.js","./shared":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-path/lib/shared.js","bare-os":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-os/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-path/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-stream/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-stream/package.json","./web":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-stream/web.js","b4a":"/node_modules/favela-web/node_modules/atproto-store/node_modules/b4a/index.js","streamx":"/node_modules/favela-web/node_modules/atproto-store/node_modules/streamx/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-stream/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-stream/web.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-stream/package.json","streamx":"/node_modules/favela-web/node_modules/atproto-store/node_modules/streamx/index.js","teex":"/node_modules/favela-web/node_modules/atproto-store/node_modules/teex/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-type/binding.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-type/package.json",".":"linked:libbare-type.1.1.0.so"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-type/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-type/package.json","./binding":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-type/binding.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-type/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-url/binding.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-url/package.json",".":"linked:libbare-url.2.4.5.so"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-url/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-url/package.json","./binding":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-url/binding.js","./lib/errors":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-url/lib/errors.js","./lib/url-search-params":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-url/lib/url-search-params.js","bare-path":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-path/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-url/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-url/package.json"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-url/lib/url-search-params.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-url/package.json"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-url/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/big-sparse-array/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/big-sparse-array/package.json"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/big-sparse-array/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/cborg.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/package.json","./lib/decode.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/decode.js","./lib/encode.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/encode.js","./lib/tagged.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/tagged.js","./lib/token.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/0uint.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/package.json","./common.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/1negint.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/2bytes.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/0uint.js","./byte-utils.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/3string.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/0uint.js","./2bytes.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/2bytes.js","./common.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/4array.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/5map.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/6tag.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/0uint.js","./token.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/7float.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/bl.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/package.json","./byte-utils.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/byte-utils.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/byte-utils.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/package.json"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/common.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/package.json"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/decode.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/package.json","./byte-utils.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/common.js","./jump.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/jump.js","./token.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/encode.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/0uint.js","./1negint.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/1negint.js","./2bytes.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/2bytes.js","./3string.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/3string.js","./4array.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/4array.js","./5map.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/5map.js","./6tag.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/6tag.js","./7float.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/7float.js","./bl.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/bl.js","./byte-utils.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/common.js","./is.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/is.js","./jump.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/jump.js","./token.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/is.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/package.json"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/jump.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/0uint.js","./1negint.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/1negint.js","./2bytes.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/2bytes.js","./3string.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/3string.js","./4array.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/4array.js","./5map.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/5map.js","./6tag.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/6tag.js","./7float.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/7float.js","./byte-utils.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/tagged.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/package.json"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/token.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/package.json"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/compact-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/atproto-store/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/favela-web/node_modules/atproto-store/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/favela-web/node_modules/atproto-store/node_modules/compact-encoding/raw.js","b4a":"/node_modules/favela-web/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/compact-encoding/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/atproto-store/node_modules/compact-encoding/endian.js","b4a":"/node_modules/favela-web/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/corestore/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/corestore/package.json","./lib/audit.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/corestore/lib/audit.js","./lib/notify.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/corestore/lib/notify.js","b4a":"/node_modules/favela-web/node_modules/atproto-store/node_modules/b4a/index.js","hypercore":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-crypto/index.js","hypercore-errors":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-errors/index.js","hypercore-id-encoding":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-id-encoding/index.js","ready-resource":"/node_modules/favela-web/node_modules/atproto-store/node_modules/ready-resource/index.js","sodium-universal":"/node_modules/favela-web/node_modules/atproto-store/node_modules/sodium-universal/index.js","which-runtime":"/node_modules/favela-web/node_modules/atproto-store/node_modules/which-runtime/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/corestore/lib/audit.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/corestore/package.json"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/corestore/lib/notify.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/corestore/package.json","events":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-events/index.js","streamx":"/node_modules/favela-web/node_modules/atproto-store/node_modules/streamx/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/corestore/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/device-file/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/device-file/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-store/node_modules/b4a/index.js","fd-lock":"/node_modules/favela-web/node_modules/atproto-store/node_modules/fd-lock/index.js","fs":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-fs/index.js","fs-native-extensions":"/node_modules/favela-web/node_modules/atproto-store/node_modules/fs-native-extensions/index.js","path":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-path/index.js","ready-resource":"/node_modules/favela-web/node_modules/atproto-store/node_modules/ready-resource/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/device-file/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/events-universal/bare.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/events-universal/package.json","bare-events":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-events/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/events-universal/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/fast-fifo/fixed-size.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/fast-fifo/package.json"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/fast-fifo/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/fast-fifo/package.json","./fixed-size":"/node_modules/favela-web/node_modules/atproto-store/node_modules/fast-fifo/fixed-size.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/fast-fifo/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/fd-lock/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/fd-lock/package.json","fs":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-fs/index.js","fs-native-extensions":"/node_modules/favela-web/node_modules/atproto-store/node_modules/fs-native-extensions/index.js","ready-resource":"/node_modules/favela-web/node_modules/atproto-store/node_modules/ready-resource/index.js","resource-on-exit":"/node_modules/favela-web/node_modules/atproto-store/node_modules/resource-on-exit/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/fd-lock/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/flat-tree/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/flat-tree/package.json"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/flat-tree/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/fs-native-extensions/binding.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/fs-native-extensions/package.json",".":"linked:libfs-native-extensions.1.5.0.so","require-addon":"/node_modules/favela-web/node_modules/atproto-store/node_modules/require-addon/lib/bare.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/fs-native-extensions/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/fs-native-extensions/package.json","./binding":"/node_modules/favela-web/node_modules/atproto-store/node_modules/fs-native-extensions/binding.js","which-runtime":"/node_modules/favela-web/node_modules/atproto-store/node_modules/which-runtime/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/fs-native-extensions/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-crypto/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-crypto/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-store/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/atproto-store/node_modules/compact-encoding/index.js","sodium-universal":"/node_modules/favela-web/node_modules/atproto-store/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-crypto/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-errors/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-errors/package.json","hypercore-id-encoding":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-id-encoding/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-errors/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-id-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-id-encoding/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-store/node_modules/b4a/index.js","z32":"/node_modules/favela-web/node_modules/atproto-store/node_modules/z32/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-id-encoding/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-storage/encoding/external.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-storage/package.json"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-storage/encoding/spec/hyperschema/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-storage/package.json","../../external.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-storage/encoding/external.js","hyperschema/runtime":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hyperschema/runtime.cjs"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-storage/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-storage/package.json","./lib/keys.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-storage/lib/keys.js","./lib/streams.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-storage/lib/streams.js","./lib/tx.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-storage/lib/tx.js","./lib/view.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-storage/lib/view.js","./migrations/0":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-storage/migrations/0/index.js","./migrations/1":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-storage/migrations/1/index.js","device-file":"/node_modules/favela-web/node_modules/atproto-store/node_modules/device-file/index.js","fs":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-fs/index.js","path":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-path/index.js","resolve-reject-promise":"/node_modules/favela-web/node_modules/atproto-store/node_modules/resolve-reject-promise/index.js","rocksdb-native":"/node_modules/favela-web/node_modules/atproto-store/node_modules/rocksdb-native/index.js","scope-lock":"/node_modules/favela-web/node_modules/atproto-store/node_modules/scope-lock/index.js","xache":"/node_modules/favela-web/node_modules/atproto-store/node_modules/xache/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-storage/lib/block-dependency-stream.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-storage/package.json","./keys":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-storage/lib/keys.js","streamx":"/node_modules/favela-web/node_modules/atproto-store/node_modules/streamx/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-storage/lib/close-error-stream.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-storage/package.json","streamx":"/node_modules/favela-web/node_modules/atproto-store/node_modules/streamx/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-storage/lib/keys.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-storage/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-store/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/atproto-store/node_modules/compact-encoding/index.js","index-encoder":"/node_modules/favela-web/node_modules/atproto-store/node_modules/index-encoder/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-storage/lib/streams.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-storage/package.json","../encoding/spec/hyperschema":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-storage/encoding/spec/hyperschema/index.js","./block-dependency-stream.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-storage/lib/block-dependency-stream.js","./keys.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-storage/lib/keys.js","b4a":"/node_modules/favela-web/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-storage/lib/tx.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-storage/package.json","../encoding/spec/hyperschema":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-storage/encoding/spec/hyperschema/index.js","./keys.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-storage/lib/keys.js","./view.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-storage/lib/view.js","b4a":"/node_modules/favela-web/node_modules/atproto-store/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/atproto-store/node_modules/compact-encoding/index.js","flat-tree":"/node_modules/favela-web/node_modules/atproto-store/node_modules/flat-tree/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-storage/lib/view.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-storage/package.json","./close-error-stream.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-storage/lib/close-error-stream.js","b4a":"/node_modules/favela-web/node_modules/atproto-store/node_modules/b4a/index.js","streamx":"/node_modules/favela-web/node_modules/atproto-store/node_modules/streamx/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-storage/migrations/0/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-storage/package.json","../../lib/tx.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-storage/lib/tx.js","../../lib/view.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-storage/lib/view.js","./messages.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-storage/migrations/0/messages.js","b4a":"/node_modules/favela-web/node_modules/atproto-store/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/atproto-store/node_modules/compact-encoding/index.js","flat-tree":"/node_modules/favela-web/node_modules/atproto-store/node_modules/flat-tree/index.js","fs":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-fs/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-crypto/index.js","path":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-path/index.js","streamx":"/node_modules/favela-web/node_modules/atproto-store/node_modules/streamx/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-storage/migrations/0/messages.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-storage/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-store/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/atproto-store/node_modules/compact-encoding/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-storage/migrations/1/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-storage/package.json","../../encoding/spec/hyperschema":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-storage/encoding/spec/hyperschema/index.js","../../lib/keys.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-storage/lib/keys.js","../../lib/tx.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-storage/lib/tx.js","../../lib/view.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-storage/lib/view.js","compact-encoding":"/node_modules/favela-web/node_modules/atproto-store/node_modules/compact-encoding/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-storage/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/package.json","./lib/caps":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/caps.js","./lib/core":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/core.js","./lib/default-encryption":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/default-encryption.js","./lib/download":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/download.js","./lib/feature-flags":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/feature-flags.js","./lib/fully-remote-proof":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/fully-remote-proof.js","./lib/info":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/info.js","./lib/inspect":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/inspect.js","./lib/mark-bitfield":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/mark-bitfield.js","./lib/merkle-tree":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/merkle-tree.js","./lib/replicator":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/replicator.js","./lib/streams":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/streams.js","./lib/verifier":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/verifier.js","./lib/wants":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/wants.js","@hyperswarm/secret-stream":"/node_modules/favela-web/node_modules/atproto-store/node_modules/@hyperswarm/secret-stream/index.js","b4a":"/node_modules/favela-web/node_modules/atproto-store/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/atproto-store/node_modules/compact-encoding/index.js","events":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-events/index.js","flat-tree":"/node_modules/favela-web/node_modules/atproto-store/node_modules/flat-tree/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-crypto/index.js","hypercore-errors":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-errors/index.js","hypercore-id-encoding":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-id-encoding/index.js","hypercore-storage":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-storage/index.js","is-options":"/node_modules/favela-web/node_modules/atproto-store/node_modules/is-options/index.js","nanoassert":"/node_modules/favela-web/node_modules/atproto-store/node_modules/nanoassert/index.js","protomux":"/node_modules/favela-web/node_modules/atproto-store/node_modules/protomux/index.js","safety-catch":"/node_modules/favela-web/node_modules/atproto-store/node_modules/safety-catch/index.js","unslab":"/node_modules/favela-web/node_modules/atproto-store/node_modules/unslab/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/audit.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/package.json","./merkle-tree":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/merkle-tree.js","b4a":"/node_modules/favela-web/node_modules/atproto-store/node_modules/b4a/index.js","flat-tree":"/node_modules/favela-web/node_modules/atproto-store/node_modules/flat-tree/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-crypto/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/bit-interlude.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/package.json","./compat":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/compat.js","b4a":"/node_modules/favela-web/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/bitfield.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/package.json","./compat":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/compat.js","b4a":"/node_modules/favela-web/node_modules/atproto-store/node_modules/b4a/index.js","big-sparse-array":"/node_modules/favela-web/node_modules/atproto-store/node_modules/big-sparse-array/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/caps.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-store/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/atproto-store/node_modules/compact-encoding/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-crypto/index.js","sodium-universal":"/node_modules/favela-web/node_modules/atproto-store/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/compat.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/package.json","quickbit-universal":"/node_modules/favela-web/node_modules/atproto-store/node_modules/quickbit-universal/index.js","quickbit-universal/fallback":"/node_modules/favela-web/node_modules/atproto-store/node_modules/quickbit-universal/fallback.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/copy-prologue.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/package.json","./bitfield":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/bitfield.js","b4a":"/node_modules/favela-web/node_modules/atproto-store/node_modules/b4a/index.js","flat-tree":"/node_modules/favela-web/node_modules/atproto-store/node_modules/flat-tree/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-crypto/index.js","quickbit-universal":"/node_modules/favela-web/node_modules/atproto-store/node_modules/quickbit-universal/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/core.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/package.json","./audit":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/audit.js","./bit-interlude":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/bit-interlude.js","./bitfield":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/bitfield.js","./copy-prologue":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/copy-prologue.js","./merkle-tree":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/merkle-tree.js","./mutex":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/mutex.js","./remote-bitfield":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/remote-bitfield.js","./replicator":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/replicator.js","./session-state":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/session-state.js","./verifier":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/verifier.js","b4a":"/node_modules/favela-web/node_modules/atproto-store/node_modules/b4a/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-crypto/index.js","hypercore-errors":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-errors/index.js","unslab":"/node_modules/favela-web/node_modules/atproto-store/node_modules/unslab/index.js","z32":"/node_modules/favela-web/node_modules/atproto-store/node_modules/z32/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/default-encryption.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/package.json","./caps":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/caps.js","b4a":"/node_modules/favela-web/node_modules/atproto-store/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/atproto-store/node_modules/compact-encoding/index.js","sodium-universal":"/node_modules/favela-web/node_modules/atproto-store/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/download.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/package.json"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/feature-flags.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/package.json"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/fully-remote-proof.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/package.json","./merkle-tree.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/merkle-tree.js","./messages.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/messages.js","b4a":"/node_modules/favela-web/node_modules/atproto-store/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/atproto-store/node_modules/compact-encoding/index.js","flat-tree":"/node_modules/favela-web/node_modules/atproto-store/node_modules/flat-tree/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-crypto/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/hotswap-queue.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/package.json"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/info.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/package.json"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/inspect.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/mark-bitfield.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/package.json","./compat":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/compat.js","b4a":"/node_modules/favela-web/node_modules/atproto-store/node_modules/b4a/index.js","big-sparse-array":"/node_modules/favela-web/node_modules/atproto-store/node_modules/big-sparse-array/index.js","streamx":"/node_modules/favela-web/node_modules/atproto-store/node_modules/streamx/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/merkle-tree.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/package.json","./caps":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/caps.js","b4a":"/node_modules/favela-web/node_modules/atproto-store/node_modules/b4a/index.js","flat-tree":"/node_modules/favela-web/node_modules/atproto-store/node_modules/flat-tree/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-crypto/index.js","hypercore-errors":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-errors/index.js","unslab":"/node_modules/favela-web/node_modules/atproto-store/node_modules/unslab/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/messages.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/package.json","./caps":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/caps.js","compact-encoding":"/node_modules/favela-web/node_modules/atproto-store/node_modules/compact-encoding/index.js","hypercore-errors":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-errors/index.js","unslab":"/node_modules/favela-web/node_modules/atproto-store/node_modules/unslab/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/multisig.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/package.json","./merkle-tree":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/merkle-tree.js","./messages":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/messages.js","b4a":"/node_modules/favela-web/node_modules/atproto-store/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/atproto-store/node_modules/compact-encoding/index.js","flat-tree":"/node_modules/favela-web/node_modules/atproto-store/node_modules/flat-tree/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/mutex.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/package.json"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/receiver-queue.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/package.json","fast-fifo":"/node_modules/favela-web/node_modules/atproto-store/node_modules/fast-fifo/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/remote-bitfield.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/package.json","./compat":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/compat.js","big-sparse-array":"/node_modules/favela-web/node_modules/atproto-store/node_modules/big-sparse-array/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/replicator.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/package.json","./caps":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/caps.js","./hotswap-queue":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/hotswap-queue.js","./merkle-tree":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/merkle-tree.js","./messages":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/messages.js","./mutex":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/mutex.js","./receiver-queue":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/receiver-queue.js","./remote-bitfield":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/remote-bitfield.js","./wants":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/wants.js","b4a":"/node_modules/favela-web/node_modules/atproto-store/node_modules/b4a/index.js","flat-tree":"/node_modules/favela-web/node_modules/atproto-store/node_modules/flat-tree/index.js","hypercore-errors":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-errors/index.js","random-array-iterator":"/node_modules/favela-web/node_modules/atproto-store/node_modules/random-array-iterator/index.js","safety-catch":"/node_modules/favela-web/node_modules/atproto-store/node_modules/safety-catch/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/session-state.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/package.json","./bitfield":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/bitfield.js","./merkle-tree":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/merkle-tree.js","./mutex":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/mutex.js","b4a":"/node_modules/favela-web/node_modules/atproto-store/node_modules/b4a/index.js","flat-tree":"/node_modules/favela-web/node_modules/atproto-store/node_modules/flat-tree/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-crypto/index.js","hypercore-errors":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-errors/index.js","hypercore-storage":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-storage/index.js","nanoassert":"/node_modules/favela-web/node_modules/atproto-store/node_modules/nanoassert/index.js","quickbit-universal":"/node_modules/favela-web/node_modules/atproto-store/node_modules/quickbit-universal/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/streams.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/package.json","streamx":"/node_modules/favela-web/node_modules/atproto-store/node_modules/streamx/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/verifier.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/package.json","./caps":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/caps.js","./messages":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/messages.js","./multisig":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/multisig.js","b4a":"/node_modules/favela-web/node_modules/atproto-store/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/atproto-store/node_modules/compact-encoding/index.js","flat-tree":"/node_modules/favela-web/node_modules/atproto-store/node_modules/flat-tree/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-crypto/index.js","hypercore-errors":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-errors/index.js","unslab":"/node_modules/favela-web/node_modules/atproto-store/node_modules/unslab/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/wants.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/package.json"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hyperschema/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hyperschema/runtime.cjs":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/hyperschema/package.json","compact-encoding":"/node_modules/favela-web/node_modules/atproto-store/node_modules/compact-encoding/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/index-encoder/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/index-encoder/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/index-encoder/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/is-options/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/is-options/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/is-options/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/multiformats/dist/src/bases/base.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/multiformats/package.json","../bytes.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/multiformats/dist/src/bytes.js","../vendor/base-x.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/multiformats/dist/src/vendor/base-x.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/multiformats/dist/src/bases/base32.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/multiformats/package.json","./base.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/multiformats/dist/src/bases/base.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/multiformats/dist/src/bases/base36.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/multiformats/package.json","./base.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/multiformats/dist/src/bases/base.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/multiformats/dist/src/bases/base58.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/multiformats/package.json","./base.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/multiformats/dist/src/bases/base.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/multiformats/dist/src/bytes.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/multiformats/package.json"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/multiformats/dist/src/cid.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/multiformats/package.json","./bases/base32.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/multiformats/dist/src/bases/base32.js","./bases/base36.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/multiformats/dist/src/bases/base36.js","./bases/base58.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/multiformats/dist/src/bases/base58.js","./bytes.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/multiformats/dist/src/bytes.js","./hashes/digest.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/multiformats/dist/src/hashes/digest.js","./link/interface.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/multiformats/dist/src/link/interface.js","./varint.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/multiformats/dist/src/varint.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/multiformats/dist/src/hashes/digest.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/multiformats/package.json","../bytes.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/multiformats/dist/src/bytes.js","../varint.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/multiformats/dist/src/varint.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/multiformats/dist/src/link/interface.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/multiformats/package.json"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/multiformats/dist/src/varint.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/multiformats/package.json","./vendor/varint.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/multiformats/dist/src/vendor/varint.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/multiformats/dist/src/vendor/base-x.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/multiformats/package.json"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/multiformats/dist/src/vendor/varint.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/multiformats/package.json"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/multiformats/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/nanoassert/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/nanoassert/package.json"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/nanoassert/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/noise-curve-ed/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/noise-curve-ed/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-store/node_modules/b4a/index.js","nanoassert":"/node_modules/favela-web/node_modules/atproto-store/node_modules/nanoassert/index.js","sodium-universal":"/node_modules/favela-web/node_modules/atproto-store/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/noise-curve-ed/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/noise-handshake/cipher.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/noise-handshake/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-store/node_modules/b4a/index.js","sodium-universal":"/node_modules/favela-web/node_modules/atproto-store/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/noise-handshake/dh.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/noise-handshake/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-store/node_modules/b4a/index.js","nanoassert":"/node_modules/favela-web/node_modules/atproto-store/node_modules/nanoassert/index.js","sodium-universal":"/node_modules/favela-web/node_modules/atproto-store/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/noise-handshake/hkdf.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/noise-handshake/package.json","./hmac":"/node_modules/favela-web/node_modules/atproto-store/node_modules/noise-handshake/hmac.js","b4a":"/node_modules/favela-web/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/noise-handshake/hmac.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/noise-handshake/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-store/node_modules/b4a/index.js","sodium-universal":"/node_modules/favela-web/node_modules/atproto-store/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/noise-handshake/noise.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/noise-handshake/package.json","./hkdf":"/node_modules/favela-web/node_modules/atproto-store/node_modules/noise-handshake/hkdf.js","./symmetric-state":"/node_modules/favela-web/node_modules/atproto-store/node_modules/noise-handshake/symmetric-state.js","b4a":"/node_modules/favela-web/node_modules/atproto-store/node_modules/b4a/index.js","nanoassert":"/node_modules/favela-web/node_modules/atproto-store/node_modules/nanoassert/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/noise-handshake/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/noise-handshake/symmetric-state.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/noise-handshake/package.json","./cipher":"/node_modules/favela-web/node_modules/atproto-store/node_modules/noise-handshake/cipher.js","./dh":"/node_modules/favela-web/node_modules/atproto-store/node_modules/noise-handshake/dh.js","./hkdf":"/node_modules/favela-web/node_modules/atproto-store/node_modules/noise-handshake/hkdf.js","b4a":"/node_modules/favela-web/node_modules/atproto-store/node_modules/b4a/index.js","nanoassert":"/node_modules/favela-web/node_modules/atproto-store/node_modules/nanoassert/index.js","sodium-universal":"/node_modules/favela-web/node_modules/atproto-store/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/protomux/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/protomux/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-store/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/atproto-store/node_modules/compact-encoding/index.js","queue-tick":"/node_modules/favela-web/node_modules/atproto-store/node_modules/queue-tick/process-next-tick.js","safety-catch":"/node_modules/favela-web/node_modules/atproto-store/node_modules/safety-catch/index.js","unslab":"/node_modules/favela-web/node_modules/atproto-store/node_modules/unslab/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/protomux/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/queue-tick/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/queue-tick/process-next-tick.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/queue-tick/package.json","./queue-microtask":"/node_modules/favela-web/node_modules/atproto-store/node_modules/queue-tick/queue-microtask.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/queue-tick/queue-microtask.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/queue-tick/package.json"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/quickbit-native/binding.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/quickbit-native/package.json",".":"linked:libquickbit-native.2.4.8.so","require-addon":"/node_modules/favela-web/node_modules/atproto-store/node_modules/require-addon/lib/bare.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/quickbit-native/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/quickbit-native/package.json","./binding":"/node_modules/favela-web/node_modules/atproto-store/node_modules/quickbit-native/binding.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/quickbit-native/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/quickbit-universal/fallback.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/quickbit-universal/package.json","simdle-universal":"/node_modules/favela-web/node_modules/atproto-store/node_modules/simdle-universal/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/quickbit-universal/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/quickbit-universal/package.json","./fallback":"/node_modules/favela-web/node_modules/atproto-store/node_modules/quickbit-universal/fallback.js","quickbit-native":"/node_modules/favela-web/node_modules/atproto-store/node_modules/quickbit-native/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/quickbit-universal/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/random-array-iterator/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/random-array-iterator/package.json"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/random-array-iterator/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/ready-resource/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/ready-resource/package.json","events":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-events/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/ready-resource/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/refcounter/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/refcounter/package.json"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/refcounter/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/require-addon/lib/bare.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/require-addon/package.json"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/require-addon/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/resolve-reject-promise/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/resolve-reject-promise/package.json"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/resolve-reject-promise/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/resource-on-exit/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/resource-on-exit/package.json"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/resource-on-exit/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/rocksdb-native/binding.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/rocksdb-native/package.json",".":"linked:librocksdb-native.3.17.2.so","require-addon":"/node_modules/favela-web/node_modules/atproto-store/node_modules/require-addon/lib/bare.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/rocksdb-native/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/rocksdb-native/package.json","./lib/column-family":"/node_modules/favela-web/node_modules/atproto-store/node_modules/rocksdb-native/lib/column-family.js","./lib/constants":"/node_modules/favela-web/node_modules/atproto-store/node_modules/rocksdb-native/lib/constants.js","./lib/filter-policy":"/node_modules/favela-web/node_modules/atproto-store/node_modules/rocksdb-native/lib/filter-policy.js","./lib/iterator":"/node_modules/favela-web/node_modules/atproto-store/node_modules/rocksdb-native/lib/iterator.js","./lib/snapshot":"/node_modules/favela-web/node_modules/atproto-store/node_modules/rocksdb-native/lib/snapshot.js","./lib/state":"/node_modules/favela-web/node_modules/atproto-store/node_modules/rocksdb-native/lib/state.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/rocksdb-native/lib/batch.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/rocksdb-native/package.json","../binding":"/node_modules/favela-web/node_modules/atproto-store/node_modules/rocksdb-native/binding.js","compact-encoding":"/node_modules/favela-web/node_modules/atproto-store/node_modules/compact-encoding/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/rocksdb-native/lib/column-family.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/rocksdb-native/package.json","../binding":"/node_modules/favela-web/node_modules/atproto-store/node_modules/rocksdb-native/binding.js","./constants":"/node_modules/favela-web/node_modules/atproto-store/node_modules/rocksdb-native/lib/constants.js","./filter-policy":"/node_modules/favela-web/node_modules/atproto-store/node_modules/rocksdb-native/lib/filter-policy.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/rocksdb-native/lib/constants.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/rocksdb-native/package.json"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/rocksdb-native/lib/filter-policy.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/rocksdb-native/package.json"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/rocksdb-native/lib/iterator.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/rocksdb-native/package.json","../binding":"/node_modules/favela-web/node_modules/atproto-store/node_modules/rocksdb-native/binding.js","compact-encoding":"/node_modules/favela-web/node_modules/atproto-store/node_modules/compact-encoding/index.js","streamx":"/node_modules/favela-web/node_modules/atproto-store/node_modules/streamx/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/rocksdb-native/lib/snapshot.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/rocksdb-native/package.json","../binding":"/node_modules/favela-web/node_modules/atproto-store/node_modules/rocksdb-native/binding.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/rocksdb-native/lib/state.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/rocksdb-native/package.json","../binding":"/node_modules/favela-web/node_modules/atproto-store/node_modules/rocksdb-native/binding.js","./batch":"/node_modules/favela-web/node_modules/atproto-store/node_modules/rocksdb-native/lib/batch.js","./column-family":"/node_modules/favela-web/node_modules/atproto-store/node_modules/rocksdb-native/lib/column-family.js","./constants":"/node_modules/favela-web/node_modules/atproto-store/node_modules/rocksdb-native/lib/constants.js","compact-encoding":"/node_modules/favela-web/node_modules/atproto-store/node_modules/compact-encoding/index.js","ready-resource":"/node_modules/favela-web/node_modules/atproto-store/node_modules/ready-resource/index.js","refcounter":"/node_modules/favela-web/node_modules/atproto-store/node_modules/refcounter/index.js","resolve-reject-promise":"/node_modules/favela-web/node_modules/atproto-store/node_modules/resolve-reject-promise/index.js","signal-promise":"/node_modules/favela-web/node_modules/atproto-store/node_modules/signal-promise/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/rocksdb-native/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/safety-catch/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/safety-catch/package.json"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/safety-catch/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/scope-lock/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/scope-lock/package.json"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/scope-lock/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/signal-promise/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/signal-promise/package.json"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/signal-promise/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/simdle-native/binding.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/simdle-native/package.json",".":"linked:libsimdle-native.1.3.9.so","require-addon":"/node_modules/favela-web/node_modules/atproto-store/node_modules/require-addon/lib/bare.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/simdle-native/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/simdle-native/package.json","./binding":"/node_modules/favela-web/node_modules/atproto-store/node_modules/simdle-native/binding.js","b4a":"/node_modules/favela-web/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/simdle-native/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/simdle-universal/fallback.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/simdle-universal/package.json","./scalar":"/node_modules/favela-web/node_modules/atproto-store/node_modules/simdle-universal/scalar.js","b4a":"/node_modules/favela-web/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/simdle-universal/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/simdle-universal/package.json","./fallback":"/node_modules/favela-web/node_modules/atproto-store/node_modules/simdle-universal/fallback.js","simdle-native":"/node_modules/favela-web/node_modules/atproto-store/node_modules/simdle-native/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/simdle-universal/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/simdle-universal/scalar.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/simdle-universal/package.json"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/sodium-native/binding.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/sodium-native/package.json",".":"linked:libsodium-native.5.1.0.so","require-addon":"/node_modules/favela-web/node_modules/atproto-store/node_modules/require-addon/lib/bare.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/sodium-native/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/sodium-native/package.json","./binding":"/node_modules/favela-web/node_modules/atproto-store/node_modules/sodium-native/binding.js","assert":"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-assert/index.js","which-runtime":"/node_modules/favela-web/node_modules/atproto-store/node_modules/which-runtime/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/sodium-native/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/sodium-secretstream/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/sodium-secretstream/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-store/node_modules/b4a/index.js","sodium-universal":"/node_modules/favela-web/node_modules/atproto-store/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/sodium-secretstream/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/sodium-universal/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/sodium-universal/package.json","sodium-native":"/node_modules/favela-web/node_modules/atproto-store/node_modules/sodium-native/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/sodium-universal/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/streamx/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/streamx/package.json","./lib/errors.js":"/node_modules/favela-web/node_modules/atproto-store/node_modules/streamx/lib/errors.js","events-universal":"/node_modules/favela-web/node_modules/atproto-store/node_modules/events-universal/bare.js","fast-fifo":"/node_modules/favela-web/node_modules/atproto-store/node_modules/fast-fifo/index.js","text-decoder":"/node_modules/favela-web/node_modules/atproto-store/node_modules/text-decoder/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/streamx/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/streamx/package.json"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/streamx/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/teex/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/teex/package.json","streamx":"/node_modules/favela-web/node_modules/atproto-store/node_modules/streamx/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/teex/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/text-decoder/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/text-decoder/package.json","./lib/pass-through-decoder":"/node_modules/favela-web/node_modules/atproto-store/node_modules/text-decoder/lib/pass-through-decoder.js","./lib/utf8-decoder":"/node_modules/favela-web/node_modules/atproto-store/node_modules/text-decoder/lib/utf8-decoder.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/text-decoder/lib/pass-through-decoder.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/text-decoder/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/text-decoder/lib/utf8-decoder.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/text-decoder/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/text-decoder/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/timeout-refresh/browser.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/timeout-refresh/package.json"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/timeout-refresh/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/timeout-refresh/package.json","./browser":"/node_modules/favela-web/node_modules/atproto-store/node_modules/timeout-refresh/browser.js","./node":"/node_modules/favela-web/node_modules/atproto-store/node_modules/timeout-refresh/node.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/timeout-refresh/node.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/timeout-refresh/package.json"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/timeout-refresh/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/unslab/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/unslab/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/unslab/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/which-runtime/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/which-runtime/package.json"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/which-runtime/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/xache/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/xache/package.json"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/xache/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/node_modules/z32/index.js":{"#package":"/node_modules/favela-web/node_modules/atproto-store/node_modules/z32/package.json","b4a":"/node_modules/favela-web/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/atproto-store/node_modules/z32/package.json":{},"/node_modules/favela-web/node_modules/atproto-store/package.json":{},"/node_modules/favela-web/node_modules/b4a/index.js":{"#package":"/node_modules/favela-web/node_modules/b4a/package.json"},"/node_modules/favela-web/node_modules/b4a/package.json":{},"/node_modules/favela-web/node_modules/bare-abort/binding.js":{"#package":"/node_modules/favela-web/node_modules/bare-abort/package.json",".":"linked:libbare-abort.2.0.13.so"},"/node_modules/favela-web/node_modules/bare-abort/index.js":{"#package":"/node_modules/favela-web/node_modules/bare-abort/package.json","./binding":"/node_modules/favela-web/node_modules/bare-abort/binding.js"},"/node_modules/favela-web/node_modules/bare-abort/package.json":{},"/node_modules/favela-web/node_modules/bare-ansi-escapes/index.js":{"#package":"/node_modules/favela-web/node_modules/bare-ansi-escapes/package.json"},"/node_modules/favela-web/node_modules/bare-ansi-escapes/package.json":{},"/node_modules/favela-web/node_modules/bare-assert/index.js":{"#package":"/node_modules/favela-web/node_modules/bare-assert/package.json","bare-inspect":"/node_modules/favela-web/node_modules/bare-inspect/index.js"},"/node_modules/favela-web/node_modules/bare-assert/package.json":{},"/node_modules/favela-web/node_modules/bare-buffer/binding.js":{"#package":"/node_modules/favela-web/node_modules/bare-buffer/package.json",".":"linked:libbare-buffer.3.6.2.so"},"/node_modules/favela-web/node_modules/bare-buffer/index.js":{"#package":"/node_modules/favela-web/node_modules/bare-buffer/package.json","./binding":"/node_modules/favela-web/node_modules/bare-buffer/binding.js","./lib/ascii":"/node_modules/favela-web/node_modules/bare-buffer/lib/ascii.js","./lib/base64":"/node_modules/favela-web/node_modules/bare-buffer/lib/base64.js","./lib/base64url":"/node_modules/favela-web/node_modules/bare-buffer/lib/base64url.js","./lib/constants":"/node_modules/favela-web/node_modules/bare-buffer/lib/constants.js","./lib/hex":"/node_modules/favela-web/node_modules/bare-buffer/lib/hex.js","./lib/latin1":"/node_modules/favela-web/node_modules/bare-buffer/lib/latin1.js","./lib/utf16le":"/node_modules/favela-web/node_modules/bare-buffer/lib/utf16le.js","./lib/utf8":"/node_modules/favela-web/node_modules/bare-buffer/lib/utf8.js"},"/node_modules/favela-web/node_modules/bare-buffer/lib/ascii.js":{"#package":"/node_modules/favela-web/node_modules/bare-buffer/package.json","../binding":"/node_modules/favela-web/node_modules/bare-buffer/binding.js"},"/node_modules/favela-web/node_modules/bare-buffer/lib/base64.js":{"#package":"/node_modules/favela-web/node_modules/bare-buffer/package.json","../binding":"/node_modules/favela-web/node_modules/bare-buffer/binding.js"},"/node_modules/favela-web/node_modules/bare-buffer/lib/base64url.js":{"#package":"/node_modules/favela-web/node_modules/bare-buffer/package.json","../binding":"/node_modules/favela-web/node_modules/bare-buffer/binding.js"},"/node_modules/favela-web/node_modules/bare-buffer/lib/constants.js":{"#package":"/node_modules/favela-web/node_modules/bare-buffer/package.json","../binding":"/node_modules/favela-web/node_modules/bare-buffer/binding.js"},"/node_modules/favela-web/node_modules/bare-buffer/lib/hex.js":{"#package":"/node_modules/favela-web/node_modules/bare-buffer/package.json","../binding":"/node_modules/favela-web/node_modules/bare-buffer/binding.js"},"/node_modules/favela-web/node_modules/bare-buffer/lib/latin1.js":{"#package":"/node_modules/favela-web/node_modules/bare-buffer/package.json","../binding":"/node_modules/favela-web/node_modules/bare-buffer/binding.js"},"/node_modules/favela-web/node_modules/bare-buffer/lib/utf16le.js":{"#package":"/node_modules/favela-web/node_modules/bare-buffer/package.json","../binding":"/node_modules/favela-web/node_modules/bare-buffer/binding.js"},"/node_modules/favela-web/node_modules/bare-buffer/lib/utf8.js":{"#package":"/node_modules/favela-web/node_modules/bare-buffer/package.json","../binding":"/node_modules/favela-web/node_modules/bare-buffer/binding.js"},"/node_modules/favela-web/node_modules/bare-buffer/package.json":{},"/node_modules/favela-web/node_modules/bare-crypto/binding.js":{"#package":"/node_modules/favela-web/node_modules/bare-crypto/package.json",".":"linked:libbare-crypto.1.15.3.so"},"/node_modules/favela-web/node_modules/bare-crypto/index.js":{"#package":"/node_modules/favela-web/node_modules/bare-crypto/package.json","./lib/cipher":"/node_modules/favela-web/node_modules/bare-crypto/lib/cipher.js","./lib/constants":"/node_modules/favela-web/node_modules/bare-crypto/lib/constants.js","./lib/hash":"/node_modules/favela-web/node_modules/bare-crypto/lib/hash.js","./lib/hmac":"/node_modules/favela-web/node_modules/bare-crypto/lib/hmac.js","./lib/key":"/node_modules/favela-web/node_modules/bare-crypto/lib/key.js","./lib/pbkdf2":"/node_modules/favela-web/node_modules/bare-crypto/lib/pbkdf2.js","./lib/random":"/node_modules/favela-web/node_modules/bare-crypto/lib/random.js","./lib/signature":"/node_modules/favela-web/node_modules/bare-crypto/lib/signature.js","./lib/timing":"/node_modules/favela-web/node_modules/bare-crypto/lib/timing.js","./web":"/node_modules/favela-web/node_modules/bare-crypto/web.js"},"/node_modules/favela-web/node_modules/bare-crypto/lib/cipher.js":{"#package":"/node_modules/favela-web/node_modules/bare-crypto/package.json","../binding":"/node_modules/favela-web/node_modules/bare-crypto/binding.js","./constants":"/node_modules/favela-web/node_modules/bare-crypto/lib/constants.js","bare-assert":"/node_modules/favela-web/node_modules/bare-assert/index.js","bare-stream":"/node_modules/favela-web/node_modules/bare-stream/index.js"},"/node_modules/favela-web/node_modules/bare-crypto/lib/constants.js":{"#package":"/node_modules/favela-web/node_modules/bare-crypto/package.json","../binding":"/node_modules/favela-web/node_modules/bare-crypto/binding.js","./errors":"/node_modules/favela-web/node_modules/bare-crypto/lib/errors.js","bare-assert":"/node_modules/favela-web/node_modules/bare-assert/index.js"},"/node_modules/favela-web/node_modules/bare-crypto/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/bare-crypto/package.json"},"/node_modules/favela-web/node_modules/bare-crypto/lib/hash.js":{"#package":"/node_modules/favela-web/node_modules/bare-crypto/package.json","../binding":"/node_modules/favela-web/node_modules/bare-crypto/binding.js","./constants":"/node_modules/favela-web/node_modules/bare-crypto/lib/constants.js","bare-assert":"/node_modules/favela-web/node_modules/bare-assert/index.js","bare-stream":"/node_modules/favela-web/node_modules/bare-stream/index.js"},"/node_modules/favela-web/node_modules/bare-crypto/lib/hmac.js":{"#package":"/node_modules/favela-web/node_modules/bare-crypto/package.json","../binding":"/node_modules/favela-web/node_modules/bare-crypto/binding.js","./constants":"/node_modules/favela-web/node_modules/bare-crypto/lib/constants.js","bare-assert":"/node_modules/favela-web/node_modules/bare-assert/index.js","bare-stream":"/node_modules/favela-web/node_modules/bare-stream/index.js"},"/node_modules/favela-web/node_modules/bare-crypto/lib/key.js":{"#package":"/node_modules/favela-web/node_modules/bare-crypto/package.json","../binding":"/node_modules/favela-web/node_modules/bare-crypto/binding.js","./constants":"/node_modules/favela-web/node_modules/bare-crypto/lib/constants.js"},"/node_modules/favela-web/node_modules/bare-crypto/lib/pbkdf2.js":{"#package":"/node_modules/favela-web/node_modules/bare-crypto/package.json","../binding":"/node_modules/favela-web/node_modules/bare-crypto/binding.js","./constants":"/node_modules/favela-web/node_modules/bare-crypto/lib/constants.js","bare-assert":"/node_modules/favela-web/node_modules/bare-assert/index.js"},"/node_modules/favela-web/node_modules/bare-crypto/lib/random.js":{"#package":"/node_modules/favela-web/node_modules/bare-crypto/package.json","../binding":"/node_modules/favela-web/node_modules/bare-crypto/binding.js","bare-assert":"/node_modules/favela-web/node_modules/bare-assert/index.js"},"/node_modules/favela-web/node_modules/bare-crypto/lib/signature.js":{"#package":"/node_modules/favela-web/node_modules/bare-crypto/package.json","../binding":"/node_modules/favela-web/node_modules/bare-crypto/binding.js","./constants":"/node_modules/favela-web/node_modules/bare-crypto/lib/constants.js","./key":"/node_modules/favela-web/node_modules/bare-crypto/lib/key.js","bare-assert":"/node_modules/favela-web/node_modules/bare-assert/index.js"},"/node_modules/favela-web/node_modules/bare-crypto/lib/timing.js":{"#package":"/node_modules/favela-web/node_modules/bare-crypto/package.json","../binding":"/node_modules/favela-web/node_modules/bare-crypto/binding.js","bare-assert":"/node_modules/favela-web/node_modules/bare-assert/index.js"},"/node_modules/favela-web/node_modules/bare-crypto/lib/web/algorithm/ed25519.js":{"#package":"/node_modules/favela-web/node_modules/bare-crypto/package.json","../../..":"/node_modules/favela-web/node_modules/bare-crypto/index.js","../../../binding":"/node_modules/favela-web/node_modules/bare-crypto/binding.js","../../errors":"/node_modules/favela-web/node_modules/bare-crypto/lib/errors.js","../../key":"/node_modules/favela-web/node_modules/bare-crypto/lib/key.js","../crypto-key":"/node_modules/favela-web/node_modules/bare-crypto/lib/web/crypto-key.js"},"/node_modules/favela-web/node_modules/bare-crypto/lib/web/algorithm/hmac.js":{"#package":"/node_modules/favela-web/node_modules/bare-crypto/package.json","../../..":"/node_modules/favela-web/node_modules/bare-crypto/index.js","../../errors":"/node_modules/favela-web/node_modules/bare-crypto/lib/errors.js","../../key":"/node_modules/favela-web/node_modules/bare-crypto/lib/key.js","../crypto-key":"/node_modules/favela-web/node_modules/bare-crypto/lib/web/crypto-key.js"},"/node_modules/favela-web/node_modules/bare-crypto/lib/web/algorithm/pbkdf2.js":{"#package":"/node_modules/favela-web/node_modules/bare-crypto/package.json","../../..":"/node_modules/favela-web/node_modules/bare-crypto/index.js","../../errors":"/node_modules/favela-web/node_modules/bare-crypto/lib/errors.js","../../key":"/node_modules/favela-web/node_modules/bare-crypto/lib/key.js","../crypto-key":"/node_modules/favela-web/node_modules/bare-crypto/lib/web/crypto-key.js"},"/node_modules/favela-web/node_modules/bare-crypto/lib/web/algorithm/sha.js":{"#package":"/node_modules/favela-web/node_modules/bare-crypto/package.json","../../..":"/node_modules/favela-web/node_modules/bare-crypto/index.js"},"/node_modules/favela-web/node_modules/bare-crypto/lib/web/crypto-key.js":{"#package":"/node_modules/favela-web/node_modules/bare-crypto/package.json"},"/node_modules/favela-web/node_modules/bare-crypto/package.json":{},"/node_modules/favela-web/node_modules/bare-crypto/web.js":{"#package":"/node_modules/favela-web/node_modules/bare-crypto/package.json",".":"/node_modules/favela-web/node_modules/bare-crypto/index.js","./lib/errors":"/node_modules/favela-web/node_modules/bare-crypto/lib/errors.js","./lib/web/algorithm/ed25519":"/node_modules/favela-web/node_modules/bare-crypto/lib/web/algorithm/ed25519.js","./lib/web/algorithm/hmac":"/node_modules/favela-web/node_modules/bare-crypto/lib/web/algorithm/hmac.js","./lib/web/algorithm/pbkdf2":"/node_modules/favela-web/node_modules/bare-crypto/lib/web/algorithm/pbkdf2.js","./lib/web/algorithm/sha":"/node_modules/favela-web/node_modules/bare-crypto/lib/web/algorithm/sha.js","./lib/web/crypto-key":"/node_modules/favela-web/node_modules/bare-crypto/lib/web/crypto-key.js"},"/node_modules/favela-web/node_modules/bare-dns/binding.js":{"#package":"/node_modules/favela-web/node_modules/bare-dns/package.json",".":"linked:libbare-dns.2.1.4.so"},"/node_modules/favela-web/node_modules/bare-dns/index.js":{"#package":"/node_modules/favela-web/node_modules/bare-dns/package.json","./binding":"/node_modules/favela-web/node_modules/bare-dns/binding.js"},"/node_modules/favela-web/node_modules/bare-dns/package.json":{},"/node_modules/favela-web/node_modules/bare-env/index.js":{"#package":"/node_modules/favela-web/node_modules/bare-env/package.json","bare-os":"/node_modules/favela-web/node_modules/bare-os/index.js"},"/node_modules/favela-web/node_modules/bare-env/package.json":{},"/node_modules/favela-web/node_modules/bare-events/index.js":{"#package":"/node_modules/favela-web/node_modules/bare-events/package.json","./lib/errors":"/node_modules/favela-web/node_modules/bare-events/lib/errors.js"},"/node_modules/favela-web/node_modules/bare-events/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/bare-events/package.json"},"/node_modules/favela-web/node_modules/bare-events/package.json":{},"/node_modules/favela-web/node_modules/bare-fetch/global.js":{"#package":"/node_modules/favela-web/node_modules/bare-fetch/package.json",".":"/node_modules/favela-web/node_modules/bare-fetch/index.js"},"/node_modules/favela-web/node_modules/bare-fetch/index.js":{"#package":"/node_modules/favela-web/node_modules/bare-fetch/package.json","./lib/errors":"/node_modules/favela-web/node_modules/bare-fetch/lib/errors.js","./lib/headers":"/node_modules/favela-web/node_modules/bare-fetch/lib/headers.js","./lib/request":"/node_modules/favela-web/node_modules/bare-fetch/lib/request.js","./lib/response":"/node_modules/favela-web/node_modules/bare-fetch/lib/response.js","./lib/response-stream":"/node_modules/favela-web/node_modules/bare-fetch/lib/response-stream.js","bare-http1":"/node_modules/favela-web/node_modules/bare-http1/index.js","bare-https":"/node_modules/favela-web/node_modules/bare-https/index.js","bare-stream/web":"/node_modules/favela-web/node_modules/bare-stream/web.js"},"/node_modules/favela-web/node_modules/bare-fetch/lib/body.js":{"#package":"/node_modules/favela-web/node_modules/bare-fetch/package.json","./errors":"/node_modules/favela-web/node_modules/bare-fetch/lib/errors.js","./headers":"/node_modules/favela-web/node_modules/bare-fetch/lib/headers.js","bare-form-data":"/node_modules/favela-web/node_modules/bare-form-data/index.js","bare-stream/web":"/node_modules/favela-web/node_modules/bare-stream/web.js","bare-url":"/node_modules/favela-web/node_modules/bare-url/index.js"},"/node_modules/favela-web/node_modules/bare-fetch/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/bare-fetch/package.json"},"/node_modules/favela-web/node_modules/bare-fetch/lib/headers.js":{"#package":"/node_modules/favela-web/node_modules/bare-fetch/package.json","./errors":"/node_modules/favela-web/node_modules/bare-fetch/lib/errors.js","bare-mime":"/node_modules/favela-web/node_modules/bare-mime/index.js"},"/node_modules/favela-web/node_modules/bare-fetch/lib/request.js":{"#package":"/node_modules/favela-web/node_modules/bare-fetch/package.json","./body":"/node_modules/favela-web/node_modules/bare-fetch/lib/body.js","./errors":"/node_modules/favela-web/node_modules/bare-fetch/lib/errors.js","./headers":"/node_modules/favela-web/node_modules/bare-fetch/lib/headers.js","bare-url":"/node_modules/favela-web/node_modules/bare-url/index.js"},"/node_modules/favela-web/node_modules/bare-fetch/lib/response-stream.js":{"#package":"/node_modules/favela-web/node_modules/bare-fetch/package.json","bare-stream":"/node_modules/favela-web/node_modules/bare-stream/index.js","bare-zlib":"/node_modules/favela-web/node_modules/bare-zlib/index.js"},"/node_modules/favela-web/node_modules/bare-fetch/lib/response.js":{"#package":"/node_modules/favela-web/node_modules/bare-fetch/package.json","./body":"/node_modules/favela-web/node_modules/bare-fetch/lib/body.js","./errors":"/node_modules/favela-web/node_modules/bare-fetch/lib/errors.js","./headers":"/node_modules/favela-web/node_modules/bare-fetch/lib/headers.js"},"/node_modules/favela-web/node_modules/bare-fetch/package.json":{},"/node_modules/favela-web/node_modules/bare-form-data/index.js":{"#package":"/node_modules/favela-web/node_modules/bare-form-data/package.json","./lib/errors":"/node_modules/favela-web/node_modules/bare-form-data/lib/errors.js","bare-buffer":"/node_modules/favela-web/node_modules/bare-buffer/index.js","bare-stream/web":"/node_modules/favela-web/node_modules/bare-stream/web.js"},"/node_modules/favela-web/node_modules/bare-form-data/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/bare-form-data/package.json"},"/node_modules/favela-web/node_modules/bare-form-data/package.json":{},"/node_modules/favela-web/node_modules/bare-fs/binding.js":{"#package":"/node_modules/favela-web/node_modules/bare-fs/package.json",".":"linked:libbare-fs.4.7.4.so"},"/node_modules/favela-web/node_modules/bare-fs/index.js":{"#package":"/node_modules/favela-web/node_modules/bare-fs/package.json","./binding":"/node_modules/favela-web/node_modules/bare-fs/binding.js","./lib/constants":"/node_modules/favela-web/node_modules/bare-fs/lib/constants.js","./lib/errors":"/node_modules/favela-web/node_modules/bare-fs/lib/errors.js","./promises":"/node_modules/favela-web/node_modules/bare-fs/promises.js","bare-events":"/node_modules/favela-web/node_modules/bare-events/index.js","bare-path":"/node_modules/favela-web/node_modules/bare-path/index.js","bare-stream":"/node_modules/favela-web/node_modules/bare-stream/index.js","bare-url":"/node_modules/favela-web/node_modules/bare-url/index.js","fast-fifo":"/node_modules/favela-web/node_modules/fast-fifo/index.js"},"/node_modules/favela-web/node_modules/bare-fs/lib/constants.js":{"#package":"/node_modules/favela-web/node_modules/bare-fs/package.json","../binding":"/node_modules/favela-web/node_modules/bare-fs/binding.js"},"/node_modules/favela-web/node_modules/bare-fs/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/bare-fs/package.json","../binding":"/node_modules/favela-web/node_modules/bare-fs/binding.js"},"/node_modules/favela-web/node_modules/bare-fs/package.json":{},"/node_modules/favela-web/node_modules/bare-fs/promises.js":{"#package":"/node_modules/favela-web/node_modules/bare-fs/package.json",".":"/node_modules/favela-web/node_modules/bare-fs/index.js","bare-events":"/node_modules/favela-web/node_modules/bare-events/index.js"},"/node_modules/favela-web/node_modules/bare-hrtime/binding.js":{"#package":"/node_modules/favela-web/node_modules/bare-hrtime/package.json",".":"linked:libbare-hrtime.2.1.1.so"},"/node_modules/favela-web/node_modules/bare-hrtime/index.js":{"#package":"/node_modules/favela-web/node_modules/bare-hrtime/package.json","./binding":"/node_modules/favela-web/node_modules/bare-hrtime/binding.js"},"/node_modules/favela-web/node_modules/bare-hrtime/package.json":{},"/node_modules/favela-web/node_modules/bare-http-parser/index.js":{"#package":"/node_modules/favela-web/node_modules/bare-http-parser/package.json","./lib/errors":"/node_modules/favela-web/node_modules/bare-http-parser/lib/errors.js"},"/node_modules/favela-web/node_modules/bare-http-parser/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/bare-http-parser/package.json"},"/node_modules/favela-web/node_modules/bare-http-parser/package.json":{},"/node_modules/favela-web/node_modules/bare-http1/index.js":{"#package":"/node_modules/favela-web/node_modules/bare-http1/package.json","./lib/agent":"/node_modules/favela-web/node_modules/bare-http1/lib/agent.js","./lib/client-connection":"/node_modules/favela-web/node_modules/bare-http1/lib/client-connection.js","./lib/client-request":"/node_modules/favela-web/node_modules/bare-http1/lib/client-request.js","./lib/constants":"/node_modules/favela-web/node_modules/bare-http1/lib/constants.js","./lib/errors":"/node_modules/favela-web/node_modules/bare-http1/lib/errors.js","./lib/incoming-message":"/node_modules/favela-web/node_modules/bare-http1/lib/incoming-message.js","./lib/outgoing-message":"/node_modules/favela-web/node_modules/bare-http1/lib/outgoing-message.js","./lib/server":"/node_modules/favela-web/node_modules/bare-http1/lib/server.js","./lib/server-connection":"/node_modules/favela-web/node_modules/bare-http1/lib/server-connection.js","./lib/server-response":"/node_modules/favela-web/node_modules/bare-http1/lib/server-response.js"},"/node_modules/favela-web/node_modules/bare-http1/lib/agent.js":{"#package":"/node_modules/favela-web/node_modules/bare-http1/package.json","./client-connection":"/node_modules/favela-web/node_modules/bare-http1/lib/client-connection.js","./errors":"/node_modules/favela-web/node_modules/bare-http1/lib/errors.js","bare-events":"/node_modules/favela-web/node_modules/bare-events/index.js","bare-tcp":"/node_modules/favela-web/node_modules/bare-tcp/index.js"},"/node_modules/favela-web/node_modules/bare-http1/lib/client-connection.js":{"#package":"/node_modules/favela-web/node_modules/bare-http1/package.json","./errors":"/node_modules/favela-web/node_modules/bare-http1/lib/errors.js","./incoming-message":"/node_modules/favela-web/node_modules/bare-http1/lib/incoming-message.js","bare-http-parser":"/node_modules/favela-web/node_modules/bare-http-parser/index.js"},"/node_modules/favela-web/node_modules/bare-http1/lib/client-request.js":{"#package":"/node_modules/favela-web/node_modules/bare-http1/package.json","./agent":"/node_modules/favela-web/node_modules/bare-http1/lib/agent.js","./outgoing-message":"/node_modules/favela-web/node_modules/bare-http1/lib/outgoing-message.js","./validate":"/node_modules/favela-web/node_modules/bare-http1/lib/validate.js"},"/node_modules/favela-web/node_modules/bare-http1/lib/constants.js":{"#package":"/node_modules/favela-web/node_modules/bare-http1/package.json"},"/node_modules/favela-web/node_modules/bare-http1/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/bare-http1/package.json"},"/node_modules/favela-web/node_modules/bare-http1/lib/incoming-message.js":{"#package":"/node_modules/favela-web/node_modules/bare-http1/package.json","bare-stream":"/node_modules/favela-web/node_modules/bare-stream/index.js"},"/node_modules/favela-web/node_modules/bare-http1/lib/outgoing-message.js":{"#package":"/node_modules/favela-web/node_modules/bare-http1/package.json","./errors":"/node_modules/favela-web/node_modules/bare-http1/lib/errors.js","./validate":"/node_modules/favela-web/node_modules/bare-http1/lib/validate.js","bare-stream":"/node_modules/favela-web/node_modules/bare-stream/index.js"},"/node_modules/favela-web/node_modules/bare-http1/lib/server-connection.js":{"#package":"/node_modules/favela-web/node_modules/bare-http1/package.json","./incoming-message":"/node_modules/favela-web/node_modules/bare-http1/lib/incoming-message.js","./server-response":"/node_modules/favela-web/node_modules/bare-http1/lib/server-response.js","bare-http-parser":"/node_modules/favela-web/node_modules/bare-http-parser/index.js","bare-stream":"/node_modules/favela-web/node_modules/bare-stream/index.js"},"/node_modules/favela-web/node_modules/bare-http1/lib/server-response.js":{"#package":"/node_modules/favela-web/node_modules/bare-http1/package.json","./constants":"/node_modules/favela-web/node_modules/bare-http1/lib/constants.js","./outgoing-message":"/node_modules/favela-web/node_modules/bare-http1/lib/outgoing-message.js","./validate":"/node_modules/favela-web/node_modules/bare-http1/lib/validate.js","bare-stream":"/node_modules/favela-web/node_modules/bare-stream/index.js"},"/node_modules/favela-web/node_modules/bare-http1/lib/server.js":{"#package":"/node_modules/favela-web/node_modules/bare-http1/package.json","./server-connection":"/node_modules/favela-web/node_modules/bare-http1/lib/server-connection.js","bare-tcp":"/node_modules/favela-web/node_modules/bare-tcp/index.js"},"/node_modules/favela-web/node_modules/bare-http1/lib/validate.js":{"#package":"/node_modules/favela-web/node_modules/bare-http1/package.json","./errors":"/node_modules/favela-web/node_modules/bare-http1/lib/errors.js"},"/node_modules/favela-web/node_modules/bare-http1/package.json":{},"/node_modules/favela-web/node_modules/bare-https/index.js":{"#package":"/node_modules/favela-web/node_modules/bare-https/package.json","./lib/agent":"/node_modules/favela-web/node_modules/bare-https/lib/agent.js","./lib/client-request":"/node_modules/favela-web/node_modules/bare-https/lib/client-request.js","./lib/server":"/node_modules/favela-web/node_modules/bare-https/lib/server.js"},"/node_modules/favela-web/node_modules/bare-https/lib/agent.js":{"#package":"/node_modules/favela-web/node_modules/bare-https/package.json","./socket":"/node_modules/favela-web/node_modules/bare-https/lib/socket.js","bare-http1":"/node_modules/favela-web/node_modules/bare-http1/index.js"},"/node_modules/favela-web/node_modules/bare-https/lib/client-request.js":{"#package":"/node_modules/favela-web/node_modules/bare-https/package.json","./agent":"/node_modules/favela-web/node_modules/bare-https/lib/agent.js","bare-http1":"/node_modules/favela-web/node_modules/bare-http1/index.js"},"/node_modules/favela-web/node_modules/bare-https/lib/server.js":{"#package":"/node_modules/favela-web/node_modules/bare-https/package.json","./socket":"/node_modules/favela-web/node_modules/bare-https/lib/socket.js","bare-http1":"/node_modules/favela-web/node_modules/bare-http1/index.js","bare-tcp":"/node_modules/favela-web/node_modules/bare-tcp/index.js"},"/node_modules/favela-web/node_modules/bare-https/lib/socket.js":{"#package":"/node_modules/favela-web/node_modules/bare-https/package.json","bare-tls":"/node_modules/favela-web/node_modules/bare-tls/index.js"},"/node_modules/favela-web/node_modules/bare-https/package.json":{},"/node_modules/favela-web/node_modules/bare-inspect/binding.js":{"#package":"/node_modules/favela-web/node_modules/bare-inspect/package.json",".":"linked:libbare-inspect.3.1.4.so"},"/node_modules/favela-web/node_modules/bare-inspect/index.js":{"#package":"/node_modules/favela-web/node_modules/bare-inspect/package.json","./binding":"/node_modules/favela-web/node_modules/bare-inspect/binding.js","bare-ansi-escapes":"/node_modules/favela-web/node_modules/bare-ansi-escapes/index.js","bare-type":"/node_modules/favela-web/node_modules/bare-type/index.js"},"/node_modules/favela-web/node_modules/bare-inspect/package.json":{},"/node_modules/favela-web/node_modules/bare-mime/index.js":{"#package":"/node_modules/favela-web/node_modules/bare-mime/package.json"},"/node_modules/favela-web/node_modules/bare-mime/package.json":{},"/node_modules/favela-web/node_modules/bare-net/index.js":{"#package":"/node_modules/favela-web/node_modules/bare-net/package.json","./lib/constants":"/node_modules/favela-web/node_modules/bare-net/lib/constants.js","bare-events":"/node_modules/favela-web/node_modules/bare-events/index.js","bare-pipe":"/node_modules/favela-web/node_modules/bare-pipe/index.js","bare-stream":"/node_modules/favela-web/node_modules/bare-stream/index.js","bare-tcp":"/node_modules/favela-web/node_modules/bare-tcp/index.js"},"/node_modules/favela-web/node_modules/bare-net/lib/constants.js":{"#package":"/node_modules/favela-web/node_modules/bare-net/package.json"},"/node_modules/favela-web/node_modules/bare-net/package.json":{},"/node_modules/favela-web/node_modules/bare-os/binding.js":{"#package":"/node_modules/favela-web/node_modules/bare-os/package.json",".":"linked:libbare-os.3.9.3.so"},"/node_modules/favela-web/node_modules/bare-os/index.js":{"#package":"/node_modules/favela-web/node_modules/bare-os/package.json","./binding":"/node_modules/favela-web/node_modules/bare-os/binding.js","./lib/constants":"/node_modules/favela-web/node_modules/bare-os/lib/constants.js","./lib/errors":"/node_modules/favela-web/node_modules/bare-os/lib/errors.js"},"/node_modules/favela-web/node_modules/bare-os/lib/constants.js":{"#package":"/node_modules/favela-web/node_modules/bare-os/package.json","../binding":"/node_modules/favela-web/node_modules/bare-os/binding.js"},"/node_modules/favela-web/node_modules/bare-os/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/bare-os/package.json"},"/node_modules/favela-web/node_modules/bare-os/package.json":{},"/node_modules/favela-web/node_modules/bare-path/binding.js":{"#package":"/node_modules/favela-web/node_modules/bare-path/package.json",".":"linked:libbare-path.3.1.1.so"},"/node_modules/favela-web/node_modules/bare-path/index.js":{"#package":"/node_modules/favela-web/node_modules/bare-path/package.json","./lib/posix":"/node_modules/favela-web/node_modules/bare-path/lib/posix.js","./lib/win32":"/node_modules/favela-web/node_modules/bare-path/lib/win32.js"},"/node_modules/favela-web/node_modules/bare-path/lib/constants.js":{"#package":"/node_modules/favela-web/node_modules/bare-path/package.json"},"/node_modules/favela-web/node_modules/bare-path/lib/posix.js":{"#package":"/node_modules/favela-web/node_modules/bare-path/package.json","../binding":"/node_modules/favela-web/node_modules/bare-path/binding.js","./constants":"/node_modules/favela-web/node_modules/bare-path/lib/constants.js","./shared":"/node_modules/favela-web/node_modules/bare-path/lib/shared.js","./win32":"/node_modules/favela-web/node_modules/bare-path/lib/win32.js"},"/node_modules/favela-web/node_modules/bare-path/lib/shared.js":{"#package":"/node_modules/favela-web/node_modules/bare-path/package.json","./constants":"/node_modules/favela-web/node_modules/bare-path/lib/constants.js"},"/node_modules/favela-web/node_modules/bare-path/lib/win32.js":{"#package":"/node_modules/favela-web/node_modules/bare-path/package.json","../binding":"/node_modules/favela-web/node_modules/bare-path/binding.js","./constants":"/node_modules/favela-web/node_modules/bare-path/lib/constants.js","./posix":"/node_modules/favela-web/node_modules/bare-path/lib/posix.js","./shared":"/node_modules/favela-web/node_modules/bare-path/lib/shared.js"},"/node_modules/favela-web/node_modules/bare-path/package.json":{},"/node_modules/favela-web/node_modules/bare-pipe/binding.js":{"#package":"/node_modules/favela-web/node_modules/bare-pipe/package.json",".":"linked:libbare-pipe.4.2.2.so"},"/node_modules/favela-web/node_modules/bare-pipe/index.js":{"#package":"/node_modules/favela-web/node_modules/bare-pipe/package.json","./binding":"/node_modules/favela-web/node_modules/bare-pipe/binding.js","./lib/constants":"/node_modules/favela-web/node_modules/bare-pipe/lib/constants.js","./lib/errors":"/node_modules/favela-web/node_modules/bare-pipe/lib/errors.js","bare-events":"/node_modules/favela-web/node_modules/bare-events/index.js","bare-stream":"/node_modules/favela-web/node_modules/bare-stream/index.js"},"/node_modules/favela-web/node_modules/bare-pipe/lib/constants.js":{"#package":"/node_modules/favela-web/node_modules/bare-pipe/package.json","../binding":"/node_modules/favela-web/node_modules/bare-pipe/binding.js"},"/node_modules/favela-web/node_modules/bare-pipe/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/bare-pipe/package.json"},"/node_modules/favela-web/node_modules/bare-pipe/package.json":{},"/node_modules/favela-web/node_modules/bare-posix/package.json":{},"/node_modules/favela-web/node_modules/bare-posix/unsupported.js":{"#package":"/node_modules/favela-web/node_modules/bare-posix/package.json"},"/node_modules/favela-web/node_modules/bare-process/index.js":{"#package":"/node_modules/favela-web/node_modules/bare-process/package.json","bare-abort":"/node_modules/favela-web/node_modules/bare-abort/index.js","bare-env":"/node_modules/favela-web/node_modules/bare-env/index.js","bare-events":"/node_modules/favela-web/node_modules/bare-events/index.js","bare-hrtime":"/node_modules/favela-web/node_modules/bare-hrtime/index.js","bare-os":"/node_modules/favela-web/node_modules/bare-os/index.js","bare-posix":"/node_modules/favela-web/node_modules/bare-posix/unsupported.js","bare-signals":"/node_modules/favela-web/node_modules/bare-signals/index.js","bare-stdio":"/node_modules/favela-web/node_modules/bare-stdio/index.js"},"/node_modules/favela-web/node_modules/bare-process/package.json":{},"/node_modules/favela-web/node_modules/bare-signals/binding.js":{"#package":"/node_modules/favela-web/node_modules/bare-signals/package.json",".":"linked:libbare-signals.5.0.0.so"},"/node_modules/favela-web/node_modules/bare-signals/index.js":{"#package":"/node_modules/favela-web/node_modules/bare-signals/package.json","./binding":"/node_modules/favela-web/node_modules/bare-signals/binding.js","./lib/emitter":"/node_modules/favela-web/node_modules/bare-signals/lib/emitter.js","./lib/errors":"/node_modules/favela-web/node_modules/bare-signals/lib/errors.js","bare-events":"/node_modules/favela-web/node_modules/bare-events/index.js"},"/node_modules/favela-web/node_modules/bare-signals/lib/emitter.js":{"#package":"/node_modules/favela-web/node_modules/bare-signals/package.json","..":"/node_modules/favela-web/node_modules/bare-signals/index.js","bare-events":"/node_modules/favela-web/node_modules/bare-events/index.js"},"/node_modules/favela-web/node_modules/bare-signals/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/bare-signals/package.json"},"/node_modules/favela-web/node_modules/bare-signals/package.json":{},"/node_modules/favela-web/node_modules/bare-stdio/binding.js":{"#package":"/node_modules/favela-web/node_modules/bare-stdio/package.json",".":"linked:libbare-stdio.1.0.3.so"},"/node_modules/favela-web/node_modules/bare-stdio/index.js":{"#package":"/node_modules/favela-web/node_modules/bare-stdio/package.json","./binding":"/node_modules/favela-web/node_modules/bare-stdio/binding.js","bare-fs":"/node_modules/favela-web/node_modules/bare-fs/index.js","bare-pipe":"/node_modules/favela-web/node_modules/bare-pipe/index.js","bare-tty":"/node_modules/favela-web/node_modules/bare-tty/index.js"},"/node_modules/favela-web/node_modules/bare-stdio/package.json":{},"/node_modules/favela-web/node_modules/bare-stream/index.js":{"#package":"/node_modules/favela-web/node_modules/bare-stream/package.json","./web":"/node_modules/favela-web/node_modules/bare-stream/web.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","streamx":"/node_modules/favela-web/node_modules/streamx/index.js"},"/node_modules/favela-web/node_modules/bare-stream/package.json":{},"/node_modules/favela-web/node_modules/bare-stream/web.js":{"#package":"/node_modules/favela-web/node_modules/bare-stream/package.json","streamx":"/node_modules/favela-web/node_modules/streamx/index.js","teex":"/node_modules/favela-web/node_modules/teex/index.js"},"/node_modules/favela-web/node_modules/bare-tcp/binding.js":{"#package":"/node_modules/favela-web/node_modules/bare-tcp/package.json",".":"linked:libbare-tcp.2.5.2.so"},"/node_modules/favela-web/node_modules/bare-tcp/index.js":{"#package":"/node_modules/favela-web/node_modules/bare-tcp/package.json","./binding":"/node_modules/favela-web/node_modules/bare-tcp/binding.js","./lib/constants":"/node_modules/favela-web/node_modules/bare-tcp/lib/constants.js","./lib/errors":"/node_modules/favela-web/node_modules/bare-tcp/lib/errors.js","./lib/ip":"/node_modules/favela-web/node_modules/bare-tcp/lib/ip.js","bare-dns":"/node_modules/favela-web/node_modules/bare-dns/index.js","bare-events":"/node_modules/favela-web/node_modules/bare-events/index.js","bare-stream":"/node_modules/favela-web/node_modules/bare-stream/index.js"},"/node_modules/favela-web/node_modules/bare-tcp/lib/constants.js":{"#package":"/node_modules/favela-web/node_modules/bare-tcp/package.json"},"/node_modules/favela-web/node_modules/bare-tcp/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/bare-tcp/package.json"},"/node_modules/favela-web/node_modules/bare-tcp/lib/ip.js":{"#package":"/node_modules/favela-web/node_modules/bare-tcp/package.json"},"/node_modules/favela-web/node_modules/bare-tcp/package.json":{},"/node_modules/favela-web/node_modules/bare-tls/binding.js":{"#package":"/node_modules/favela-web/node_modules/bare-tls/package.json",".":"linked:libbare-tls.3.1.7.so"},"/node_modules/favela-web/node_modules/bare-tls/index.js":{"#package":"/node_modules/favela-web/node_modules/bare-tls/package.json","./binding":"/node_modules/favela-web/node_modules/bare-tls/binding.js","./lib/constants":"/node_modules/favela-web/node_modules/bare-tls/lib/constants.js","./lib/errors":"/node_modules/favela-web/node_modules/bare-tls/lib/errors.js","./net":"/node_modules/favela-web/node_modules/bare-tls/net.js","bare-stream":"/node_modules/favela-web/node_modules/bare-stream/index.js"},"/node_modules/favela-web/node_modules/bare-tls/lib/constants.js":{"#package":"/node_modules/favela-web/node_modules/bare-tls/package.json"},"/node_modules/favela-web/node_modules/bare-tls/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/bare-tls/package.json"},"/node_modules/favela-web/node_modules/bare-tls/net.js":{"#package":"/node_modules/favela-web/node_modules/bare-tls/package.json","bare-events":"/node_modules/favela-web/node_modules/bare-events/index.js","bare-net":"/node_modules/favela-web/node_modules/bare-net/index.js","bare-tls":"/node_modules/favela-web/node_modules/bare-tls/index.js"},"/node_modules/favela-web/node_modules/bare-tls/package.json":{},"/node_modules/favela-web/node_modules/bare-tty/binding.js":{"#package":"/node_modules/favela-web/node_modules/bare-tty/package.json",".":"linked:libbare-tty.5.1.2.so"},"/node_modules/favela-web/node_modules/bare-tty/index.js":{"#package":"/node_modules/favela-web/node_modules/bare-tty/package.json","./binding":"/node_modules/favela-web/node_modules/bare-tty/binding.js","./lib/constants":"/node_modules/favela-web/node_modules/bare-tty/lib/constants.js","bare-signals":"/node_modules/favela-web/node_modules/bare-signals/index.js","bare-stream":"/node_modules/favela-web/node_modules/bare-stream/index.js"},"/node_modules/favela-web/node_modules/bare-tty/lib/constants.js":{"#package":"/node_modules/favela-web/node_modules/bare-tty/package.json","../binding":"/node_modules/favela-web/node_modules/bare-tty/binding.js"},"/node_modules/favela-web/node_modules/bare-tty/package.json":{},"/node_modules/favela-web/node_modules/bare-type/binding.js":{"#package":"/node_modules/favela-web/node_modules/bare-type/package.json",".":"linked:libbare-type.1.1.0.so"},"/node_modules/favela-web/node_modules/bare-type/index.js":{"#package":"/node_modules/favela-web/node_modules/bare-type/package.json","./binding":"/node_modules/favela-web/node_modules/bare-type/binding.js"},"/node_modules/favela-web/node_modules/bare-type/package.json":{},"/node_modules/favela-web/node_modules/bare-url/binding.js":{"#package":"/node_modules/favela-web/node_modules/bare-url/package.json",".":"linked:libbare-url.2.4.5.so"},"/node_modules/favela-web/node_modules/bare-url/index.js":{"#package":"/node_modules/favela-web/node_modules/bare-url/package.json","./binding":"/node_modules/favela-web/node_modules/bare-url/binding.js","./lib/errors":"/node_modules/favela-web/node_modules/bare-url/lib/errors.js","./lib/url-search-params":"/node_modules/favela-web/node_modules/bare-url/lib/url-search-params.js","bare-path":"/node_modules/favela-web/node_modules/bare-path/index.js"},"/node_modules/favela-web/node_modules/bare-url/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/bare-url/package.json"},"/node_modules/favela-web/node_modules/bare-url/lib/url-search-params.js":{"#package":"/node_modules/favela-web/node_modules/bare-url/package.json"},"/node_modules/favela-web/node_modules/bare-url/package.json":{},"/node_modules/favela-web/node_modules/bare-ws/index.js":{"#package":"/node_modules/favela-web/node_modules/bare-ws/package.json","./lib/server":"/node_modules/favela-web/node_modules/bare-ws/lib/server.js","./lib/socket":"/node_modules/favela-web/node_modules/bare-ws/lib/socket.js"},"/node_modules/favela-web/node_modules/bare-ws/lib/constants.js":{"#package":"/node_modules/favela-web/node_modules/bare-ws/package.json"},"/node_modules/favela-web/node_modules/bare-ws/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/bare-ws/package.json","./constants":"/node_modules/favela-web/node_modules/bare-ws/lib/constants.js"},"/node_modules/favela-web/node_modules/bare-ws/lib/frame.js":{"#package":"/node_modules/favela-web/node_modules/bare-ws/package.json","./errors":"/node_modules/favela-web/node_modules/bare-ws/lib/errors.js","bare-crypto":"/node_modules/favela-web/node_modules/bare-crypto/index.js"},"/node_modules/favela-web/node_modules/bare-ws/lib/server.js":{"#package":"/node_modules/favela-web/node_modules/bare-ws/package.json","./constants":"/node_modules/favela-web/node_modules/bare-ws/lib/constants.js","./errors":"/node_modules/favela-web/node_modules/bare-ws/lib/errors.js","./socket":"/node_modules/favela-web/node_modules/bare-ws/lib/socket.js","bare-crypto":"/node_modules/favela-web/node_modules/bare-crypto/index.js","bare-events":"/node_modules/favela-web/node_modules/bare-events/index.js","bare-http1":"/node_modules/favela-web/node_modules/bare-http1/index.js","bare-https":"/node_modules/favela-web/node_modules/bare-https/index.js"},"/node_modules/favela-web/node_modules/bare-ws/lib/socket.js":{"#package":"/node_modules/favela-web/node_modules/bare-ws/package.json","./constants":"/node_modules/favela-web/node_modules/bare-ws/lib/constants.js","./errors":"/node_modules/favela-web/node_modules/bare-ws/lib/errors.js","./frame":"/node_modules/favela-web/node_modules/bare-ws/lib/frame.js","bare-crypto":"/node_modules/favela-web/node_modules/bare-crypto/index.js","bare-http1":"/node_modules/favela-web/node_modules/bare-http1/index.js","bare-https":"/node_modules/favela-web/node_modules/bare-https/index.js","bare-stream":"/node_modules/favela-web/node_modules/bare-stream/index.js"},"/node_modules/favela-web/node_modules/bare-ws/package.json":{},"/node_modules/favela-web/node_modules/bare-zlib/binding.js":{"#package":"/node_modules/favela-web/node_modules/bare-zlib/package.json",".":"linked:libbare-zlib.1.4.1.so"},"/node_modules/favela-web/node_modules/bare-zlib/index.js":{"#package":"/node_modules/favela-web/node_modules/bare-zlib/package.json","./binding":"/node_modules/favela-web/node_modules/bare-zlib/binding.js","./lib/constants":"/node_modules/favela-web/node_modules/bare-zlib/lib/constants.js","./lib/errors":"/node_modules/favela-web/node_modules/bare-zlib/lib/errors.js","bare-stream":"/node_modules/favela-web/node_modules/bare-stream/index.js"},"/node_modules/favela-web/node_modules/bare-zlib/lib/constants.js":{"#package":"/node_modules/favela-web/node_modules/bare-zlib/package.json","../binding":"/node_modules/favela-web/node_modules/bare-zlib/binding.js"},"/node_modules/favela-web/node_modules/bare-zlib/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/bare-zlib/package.json"},"/node_modules/favela-web/node_modules/bare-zlib/package.json":{},"/node_modules/favela-web/node_modules/big-sparse-array/index.js":{"#package":"/node_modules/favela-web/node_modules/big-sparse-array/package.json"},"/node_modules/favela-web/node_modules/big-sparse-array/package.json":{},"/node_modules/favela-web/node_modules/bits-to-bytes/index.js":{"#package":"/node_modules/favela-web/node_modules/bits-to-bytes/package.json","b4a":"/node_modules/favela-web/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/bits-to-bytes/package.json":{},"/node_modules/favela-web/node_modules/blind-pairing-core/index.js":{"#package":"/node_modules/favela-web/node_modules/blind-pairing-core/package.json","./lib/errors":"/node_modules/favela-web/node_modules/blind-pairing-core/lib/errors.js","./lib/messages":"/node_modules/favela-web/node_modules/blind-pairing-core/lib/messages.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/blind-pairing-core/node_modules/compact-encoding/index.js","events":"/node_modules/favela-web/node_modules/bare-events/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/hypercore-crypto/index.js","sodium-universal":"/node_modules/favela-web/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/blind-pairing-core/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/blind-pairing-core/package.json"},"/node_modules/favela-web/node_modules/blind-pairing-core/lib/messages.js":{"#package":"/node_modules/favela-web/node_modules/blind-pairing-core/package.json","bogon":"/node_modules/favela-web/node_modules/bogon/index.js","compact-encoding":"/node_modules/favela-web/node_modules/blind-pairing-core/node_modules/compact-encoding/index.js"},"/node_modules/favela-web/node_modules/blind-pairing-core/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/favela-web/node_modules/blind-pairing-core/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/blind-pairing-core/node_modules/compact-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/blind-pairing-core/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/blind-pairing-core/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/favela-web/node_modules/blind-pairing-core/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/favela-web/node_modules/blind-pairing-core/node_modules/compact-encoding/raw.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/blind-pairing-core/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/favela-web/node_modules/blind-pairing-core/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/blind-pairing-core/node_modules/compact-encoding/package.json":{},"/node_modules/favela-web/node_modules/blind-pairing-core/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/favela-web/node_modules/blind-pairing-core/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/blind-pairing-core/node_modules/compact-encoding/endian.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/blind-pairing-core/package.json":{},"/node_modules/favela-web/node_modules/blind-relay/index.js":{"#package":"/node_modules/favela-web/node_modules/blind-relay/package.json","./lib/errors":"/node_modules/favela-web/node_modules/blind-relay/lib/errors.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","bits-to-bytes":"/node_modules/favela-web/node_modules/bits-to-bytes/index.js","compact-encoding":"/node_modules/favela-web/node_modules/blind-relay/node_modules/compact-encoding/index.js","compact-encoding-bitfield":"/node_modules/favela-web/node_modules/compact-encoding-bitfield/index.js","events":"/node_modules/favela-web/node_modules/bare-events/index.js","protomux":"/node_modules/favela-web/node_modules/protomux/index.js","sodium-universal":"/node_modules/favela-web/node_modules/sodium-universal/index.js","streamx":"/node_modules/favela-web/node_modules/streamx/index.js"},"/node_modules/favela-web/node_modules/blind-relay/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/blind-relay/package.json"},"/node_modules/favela-web/node_modules/blind-relay/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/favela-web/node_modules/blind-relay/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/blind-relay/node_modules/compact-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/blind-relay/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/blind-relay/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/favela-web/node_modules/blind-relay/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/favela-web/node_modules/blind-relay/node_modules/compact-encoding/raw.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/blind-relay/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/favela-web/node_modules/blind-relay/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/blind-relay/node_modules/compact-encoding/package.json":{},"/node_modules/favela-web/node_modules/blind-relay/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/favela-web/node_modules/blind-relay/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/blind-relay/node_modules/compact-encoding/endian.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/blind-relay/package.json":{},"/node_modules/favela-web/node_modules/bogon/index.js":{"#package":"/node_modules/favela-web/node_modules/bogon/package.json","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/bogon/node_modules/compact-encoding/index.js"},"/node_modules/favela-web/node_modules/bogon/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/favela-web/node_modules/bogon/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/bogon/node_modules/compact-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/bogon/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/bogon/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/favela-web/node_modules/bogon/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/favela-web/node_modules/bogon/node_modules/compact-encoding/raw.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/bogon/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/favela-web/node_modules/bogon/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/bogon/node_modules/compact-encoding/package.json":{},"/node_modules/favela-web/node_modules/bogon/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/favela-web/node_modules/bogon/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/bogon/node_modules/compact-encoding/endian.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/bogon/package.json":{},"/node_modules/favela-web/node_modules/cborg/cborg.js":{"#package":"/node_modules/favela-web/node_modules/cborg/package.json","./lib/decode.js":"/node_modules/favela-web/node_modules/cborg/lib/decode.js","./lib/encode.js":"/node_modules/favela-web/node_modules/cborg/lib/encode.js","./lib/tagged.js":"/node_modules/favela-web/node_modules/cborg/lib/tagged.js","./lib/token.js":"/node_modules/favela-web/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/cborg/lib/0uint.js":{"#package":"/node_modules/favela-web/node_modules/cborg/package.json","./common.js":"/node_modules/favela-web/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/cborg/lib/1negint.js":{"#package":"/node_modules/favela-web/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/favela-web/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/cborg/lib/2bytes.js":{"#package":"/node_modules/favela-web/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/cborg/lib/0uint.js","./byte-utils.js":"/node_modules/favela-web/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/favela-web/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/cborg/lib/3string.js":{"#package":"/node_modules/favela-web/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/cborg/lib/0uint.js","./2bytes.js":"/node_modules/favela-web/node_modules/cborg/lib/2bytes.js","./common.js":"/node_modules/favela-web/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/cborg/lib/4array.js":{"#package":"/node_modules/favela-web/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/favela-web/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/cborg/lib/5map.js":{"#package":"/node_modules/favela-web/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/favela-web/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/cborg/lib/6tag.js":{"#package":"/node_modules/favela-web/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/cborg/lib/0uint.js","./token.js":"/node_modules/favela-web/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/cborg/lib/7float.js":{"#package":"/node_modules/favela-web/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/favela-web/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/cborg/lib/bl.js":{"#package":"/node_modules/favela-web/node_modules/cborg/package.json","./byte-utils.js":"/node_modules/favela-web/node_modules/cborg/lib/byte-utils.js"},"/node_modules/favela-web/node_modules/cborg/lib/byte-utils.js":{"#package":"/node_modules/favela-web/node_modules/cborg/package.json"},"/node_modules/favela-web/node_modules/cborg/lib/common.js":{"#package":"/node_modules/favela-web/node_modules/cborg/package.json"},"/node_modules/favela-web/node_modules/cborg/lib/decode.js":{"#package":"/node_modules/favela-web/node_modules/cborg/package.json","./byte-utils.js":"/node_modules/favela-web/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/favela-web/node_modules/cborg/lib/common.js","./jump.js":"/node_modules/favela-web/node_modules/cborg/lib/jump.js","./token.js":"/node_modules/favela-web/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/cborg/lib/encode.js":{"#package":"/node_modules/favela-web/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/cborg/lib/0uint.js","./1negint.js":"/node_modules/favela-web/node_modules/cborg/lib/1negint.js","./2bytes.js":"/node_modules/favela-web/node_modules/cborg/lib/2bytes.js","./3string.js":"/node_modules/favela-web/node_modules/cborg/lib/3string.js","./4array.js":"/node_modules/favela-web/node_modules/cborg/lib/4array.js","./5map.js":"/node_modules/favela-web/node_modules/cborg/lib/5map.js","./6tag.js":"/node_modules/favela-web/node_modules/cborg/lib/6tag.js","./7float.js":"/node_modules/favela-web/node_modules/cborg/lib/7float.js","./bl.js":"/node_modules/favela-web/node_modules/cborg/lib/bl.js","./byte-utils.js":"/node_modules/favela-web/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/favela-web/node_modules/cborg/lib/common.js","./is.js":"/node_modules/favela-web/node_modules/cborg/lib/is.js","./jump.js":"/node_modules/favela-web/node_modules/cborg/lib/jump.js","./token.js":"/node_modules/favela-web/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/cborg/lib/is.js":{"#package":"/node_modules/favela-web/node_modules/cborg/package.json"},"/node_modules/favela-web/node_modules/cborg/lib/jump.js":{"#package":"/node_modules/favela-web/node_modules/cborg/package.json","./0uint.js":"/node_modules/favela-web/node_modules/cborg/lib/0uint.js","./1negint.js":"/node_modules/favela-web/node_modules/cborg/lib/1negint.js","./2bytes.js":"/node_modules/favela-web/node_modules/cborg/lib/2bytes.js","./3string.js":"/node_modules/favela-web/node_modules/cborg/lib/3string.js","./4array.js":"/node_modules/favela-web/node_modules/cborg/lib/4array.js","./5map.js":"/node_modules/favela-web/node_modules/cborg/lib/5map.js","./6tag.js":"/node_modules/favela-web/node_modules/cborg/lib/6tag.js","./7float.js":"/node_modules/favela-web/node_modules/cborg/lib/7float.js","./byte-utils.js":"/node_modules/favela-web/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/favela-web/node_modules/cborg/lib/common.js","./token.js":"/node_modules/favela-web/node_modules/cborg/lib/token.js"},"/node_modules/favela-web/node_modules/cborg/lib/tagged.js":{"#package":"/node_modules/favela-web/node_modules/cborg/package.json"},"/node_modules/favela-web/node_modules/cborg/lib/token.js":{"#package":"/node_modules/favela-web/node_modules/cborg/package.json"},"/node_modules/favela-web/node_modules/cborg/package.json":{},"/node_modules/favela-web/node_modules/codecs/index.js":{"#package":"/node_modules/favela-web/node_modules/codecs/package.json","b4a":"/node_modules/favela-web/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/codecs/package.json":{},"/node_modules/favela-web/node_modules/compact-encoding-bitfield/index.js":{"#package":"/node_modules/favela-web/node_modules/compact-encoding-bitfield/package.json","compact-encoding":"/node_modules/favela-web/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/index.js"},"/node_modules/favela-web/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/favela-web/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/favela-web/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/favela-web/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/raw.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/favela-web/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/package.json":{},"/node_modules/favela-web/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/favela-web/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/endian.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/compact-encoding-bitfield/package.json":{},"/node_modules/favela-web/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/favela-web/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/compact-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/favela-web/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/favela-web/node_modules/compact-encoding/raw.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/favela-web/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/compact-encoding/package.json":{},"/node_modules/favela-web/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/favela-web/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/compact-encoding/endian.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/corestore/index.js":{"#package":"/node_modules/favela-web/node_modules/corestore/package.json","./lib/audit.js":"/node_modules/favela-web/node_modules/corestore/lib/audit.js","./lib/notify.js":"/node_modules/favela-web/node_modules/corestore/lib/notify.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","hypercore":"/node_modules/favela-web/node_modules/hypercore/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/hypercore-crypto/index.js","hypercore-errors":"/node_modules/favela-web/node_modules/hypercore-errors/index.js","hypercore-id-encoding":"/node_modules/favela-web/node_modules/hypercore-id-encoding/index.js","ready-resource":"/node_modules/favela-web/node_modules/ready-resource/index.js","sodium-universal":"/node_modules/favela-web/node_modules/sodium-universal/index.js","which-runtime":"/node_modules/favela-web/node_modules/which-runtime/index.js"},"/node_modules/favela-web/node_modules/corestore/lib/audit.js":{"#package":"/node_modules/favela-web/node_modules/corestore/package.json"},"/node_modules/favela-web/node_modules/corestore/lib/notify.js":{"#package":"/node_modules/favela-web/node_modules/corestore/package.json","events":"/node_modules/favela-web/node_modules/bare-events/index.js","streamx":"/node_modules/favela-web/node_modules/streamx/index.js"},"/node_modules/favela-web/node_modules/corestore/package.json":{},"/node_modules/favela-web/node_modules/debounceify/index.js":{"#package":"/node_modules/favela-web/node_modules/debounceify/package.json"},"/node_modules/favela-web/node_modules/debounceify/package.json":{},"/node_modules/favela-web/node_modules/device-file/index.js":{"#package":"/node_modules/favela-web/node_modules/device-file/package.json","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","fd-lock":"/node_modules/favela-web/node_modules/fd-lock/index.js","fs":"/node_modules/favela-web/node_modules/bare-fs/index.js","fs-native-extensions":"/node_modules/favela-web/node_modules/fs-native-extensions/index.js","path":"/node_modules/favela-web/node_modules/bare-path/index.js","ready-resource":"/node_modules/favela-web/node_modules/ready-resource/index.js"},"/node_modules/favela-web/node_modules/device-file/package.json":{},"/node_modules/favela-web/node_modules/dht-rpc/index.js":{"#package":"/node_modules/favela-web/node_modules/dht-rpc/package.json","./lib/commands":"/node_modules/favela-web/node_modules/dht-rpc/lib/commands.js","./lib/errors":"/node_modules/favela-web/node_modules/dht-rpc/lib/errors.js","./lib/health":"/node_modules/favela-web/node_modules/dht-rpc/lib/health.js","./lib/io":"/node_modules/favela-web/node_modules/dht-rpc/lib/io.js","./lib/peer":"/node_modules/favela-web/node_modules/dht-rpc/lib/peer.js","./lib/query":"/node_modules/favela-web/node_modules/dht-rpc/lib/query.js","./lib/session":"/node_modules/favela-web/node_modules/dht-rpc/lib/session.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/dht-rpc/node_modules/compact-encoding/index.js","events":"/node_modules/favela-web/node_modules/bare-events/index.js","kademlia-routing-table":"/node_modules/favela-web/node_modules/kademlia-routing-table/index.js","nat-sampler":"/node_modules/favela-web/node_modules/nat-sampler/index.js","sodium-universal":"/node_modules/favela-web/node_modules/sodium-universal/index.js","time-ordered-set":"/node_modules/favela-web/node_modules/time-ordered-set/index.js","udx-native":"/node_modules/favela-web/node_modules/udx-native/lib/udx.js"},"/node_modules/favela-web/node_modules/dht-rpc/lib/commands.js":{"#package":"/node_modules/favela-web/node_modules/dht-rpc/package.json"},"/node_modules/favela-web/node_modules/dht-rpc/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/dht-rpc/package.json"},"/node_modules/favela-web/node_modules/dht-rpc/lib/health.js":{"#package":"/node_modules/favela-web/node_modules/dht-rpc/package.json"},"/node_modules/favela-web/node_modules/dht-rpc/lib/io.js":{"#package":"/node_modules/favela-web/node_modules/dht-rpc/package.json","./errors":"/node_modules/favela-web/node_modules/dht-rpc/lib/errors.js","./peer":"/node_modules/favela-web/node_modules/dht-rpc/lib/peer.js","adaptive-timeout":"/node_modules/favela-web/node_modules/adaptive-timeout/index.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/dht-rpc/node_modules/compact-encoding/index.js","fast-fifo":"/node_modules/favela-web/node_modules/fast-fifo/index.js","sodium-universal":"/node_modules/favela-web/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/dht-rpc/lib/peer.js":{"#package":"/node_modules/favela-web/node_modules/dht-rpc/package.json","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/dht-rpc/node_modules/compact-encoding/index.js","sodium-universal":"/node_modules/favela-web/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/dht-rpc/lib/query.js":{"#package":"/node_modules/favela-web/node_modules/dht-rpc/package.json","./commands":"/node_modules/favela-web/node_modules/dht-rpc/lib/commands.js","./peer":"/node_modules/favela-web/node_modules/dht-rpc/lib/peer.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","streamx":"/node_modules/favela-web/node_modules/streamx/index.js"},"/node_modules/favela-web/node_modules/dht-rpc/lib/session.js":{"#package":"/node_modules/favela-web/node_modules/dht-rpc/package.json"},"/node_modules/favela-web/node_modules/dht-rpc/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/favela-web/node_modules/dht-rpc/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/dht-rpc/node_modules/compact-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/dht-rpc/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/dht-rpc/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/favela-web/node_modules/dht-rpc/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/favela-web/node_modules/dht-rpc/node_modules/compact-encoding/raw.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/dht-rpc/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/favela-web/node_modules/dht-rpc/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/dht-rpc/node_modules/compact-encoding/package.json":{},"/node_modules/favela-web/node_modules/dht-rpc/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/favela-web/node_modules/dht-rpc/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/dht-rpc/node_modules/compact-encoding/endian.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/dht-rpc/package.json":{},"/node_modules/favela-web/node_modules/events-universal/bare.js":{"#package":"/node_modules/favela-web/node_modules/events-universal/package.json","bare-events":"/node_modules/favela-web/node_modules/bare-events/index.js"},"/node_modules/favela-web/node_modules/events-universal/package.json":{},"/node_modules/favela-web/node_modules/fast-fifo/fixed-size.js":{"#package":"/node_modules/favela-web/node_modules/fast-fifo/package.json"},"/node_modules/favela-web/node_modules/fast-fifo/index.js":{"#package":"/node_modules/favela-web/node_modules/fast-fifo/package.json","./fixed-size":"/node_modules/favela-web/node_modules/fast-fifo/fixed-size.js"},"/node_modules/favela-web/node_modules/fast-fifo/package.json":{},"/node_modules/favela-web/node_modules/favela-community/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/package.json","./lib/community-room.js":"/node_modules/favela-web/node_modules/favela-community/lib/community-room.js","./lib/discovery.js":"/node_modules/favela-web/node_modules/favela-community/lib/discovery.js","./lib/feed-registry.js":"/node_modules/favela-web/node_modules/favela-community/lib/feed-registry.js","./lib/feed-schema.js":"/node_modules/favela-web/node_modules/favela-community/lib/feed-schema.js","./lib/schema.js":"/node_modules/favela-web/node_modules/favela-community/lib/schema.js"},"/node_modules/favela-web/node_modules/favela-community/lib/community-room.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/package.json","./schema.js":"/node_modules/favela-web/node_modules/favela-community/lib/schema.js","hyper-rooms/lib/room.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/lib/room.js"},"/node_modules/favela-web/node_modules/favela-community/lib/discovery.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/package.json","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/b4a/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/favela-community/node_modules/hypercore-crypto/index.js"},"/node_modules/favela-web/node_modules/favela-community/lib/feed-registry.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/package.json","./feed-schema.js":"/node_modules/favela-web/node_modules/favela-community/lib/feed-schema.js","hyper-rooms/lib/room.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/lib/room.js"},"/node_modules/favela-web/node_modules/favela-community/lib/feed-schema.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/package.json","hyper-rooms/lib/json-schema.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/lib/json-schema.js"},"/node_modules/favela-web/node_modules/favela-community/lib/schema.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/package.json","hyper-rooms/lib/json-schema.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/lib/json-schema.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/b4a/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/b4a/package.json"},"/node_modules/favela-web/node_modules/favela-community/node_modules/b4a/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/bare-ansi-escapes/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/bare-ansi-escapes/package.json"},"/node_modules/favela-web/node_modules/favela-community/node_modules/bare-ansi-escapes/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/bare-assert/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/bare-assert/package.json","bare-inspect":"/node_modules/favela-web/node_modules/favela-community/node_modules/bare-inspect/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/bare-assert/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/bare-inspect/binding.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/bare-inspect/package.json",".":"linked:libbare-inspect.3.1.4.so"},"/node_modules/favela-web/node_modules/favela-community/node_modules/bare-inspect/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/bare-inspect/package.json","./binding":"/node_modules/favela-web/node_modules/favela-community/node_modules/bare-inspect/binding.js","bare-ansi-escapes":"/node_modules/favela-web/node_modules/favela-community/node_modules/bare-ansi-escapes/index.js","bare-type":"/node_modules/favela-web/node_modules/favela-community/node_modules/bare-type/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/bare-inspect/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/bare-type/binding.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/bare-type/package.json",".":"linked:libbare-type.1.1.0.so"},"/node_modules/favela-web/node_modules/favela-community/node_modules/bare-type/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/bare-type/package.json","./binding":"/node_modules/favela-web/node_modules/favela-community/node_modules/bare-type/binding.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/bare-type/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/favela-community/node_modules/compact-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/favela-community/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/favela-web/node_modules/favela-community/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/favela-web/node_modules/favela-community/node_modules/compact-encoding/raw.js","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/favela-community/node_modules/compact-encoding/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/favela-community/node_modules/compact-encoding/endian.js","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/lib/json-schema.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/package.json","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/lib/room.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/package.json","autobase":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/index.js","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js","hyperbee":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hyperbee/index.js","hypercore":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-crypto/index.js","ready-resource":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/ready-resource/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/@hyperswarm/secret-stream/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/@hyperswarm/secret-stream/package.json","./lib/bridge":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/@hyperswarm/secret-stream/lib/bridge.js","./lib/handshake":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/@hyperswarm/secret-stream/lib/handshake.js","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-crypto/index.js","sodium-secretstream":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/sodium-secretstream/index.js","sodium-universal":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/sodium-universal/index.js","streamx":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/streamx/index.js","timeout-refresh":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/timeout-refresh/index.js","unslab":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/unslab/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/@hyperswarm/secret-stream/lib/bridge.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/@hyperswarm/secret-stream/package.json","streamx":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/streamx/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/@hyperswarm/secret-stream/lib/handshake.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/@hyperswarm/secret-stream/package.json","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js","noise-curve-ed":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/noise-curve-ed/index.js","noise-handshake":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/noise-handshake/noise.js","sodium-universal":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/@hyperswarm/secret-stream/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/encoding/legacy.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/package.json","compact-encoding":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/compact-encoding/index.js","index-encoder":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/index-encoder/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/encoding/spec/autobase/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/package.json","../../legacy.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/encoding/legacy.js","hyperschema/runtime":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hyperschema/runtime.cjs"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/package.json","./lib/active-writers.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/active-writers.js","./lib/append-batch.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/append-batch.js","./lib/apply-calls.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/apply-calls.js","./lib/apply-state.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/apply-state.js","./lib/boot.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/boot.js","./lib/caps.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/caps.js","./lib/encryption.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/encryption.js","./lib/fast-forward.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/fast-forward.js","./lib/linearizer.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/linearizer.js","./lib/local-state.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/local-state.js","./lib/messages.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/messages.js","./lib/store.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/store.js","./lib/system.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/system.js","./lib/timer.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/timer.js","./lib/updates.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/updates.js","./lib/values.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/values.js","./lib/wakeup.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/wakeup.js","./lib/writer.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/writer.js","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/compact-encoding/index.js","core-coupler":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/core-coupler/index.js","debounceify":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/debounceify/index.js","encryption-encoding":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/encryption-encoding/index.js","hypercore":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/index.js","hypercore-id-encoding":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-id-encoding/index.js","nanoassert":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/nanoassert/index.js","protomux-wakeup":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/protomux-wakeup/index.js","ready-resource":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/ready-resource/index.js","resolve-reject-promise":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/resolve-reject-promise/index.js","safety-catch":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/safety-catch/index.js","scope-lock":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/scope-lock/index.js","signal-promise":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/signal-promise/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/active-writers.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/package.json","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/append-batch.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/package.json","signal-promise":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/signal-promise/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/apply-calls.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/package.json"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/apply-state.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/package.json","./apply-calls.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/apply-calls.js","./caps.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/caps.js","./encryption.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/encryption.js","./fork.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/fork.js","./local-state.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/local-state.js","./messages.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/messages.js","./system.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/system.js","./updates.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/updates.js","./values.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/values.js","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/compact-encoding/index.js","hypercore":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-crypto/index.js","hypercore/lib/multisig.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/multisig.js","nanoassert":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/nanoassert/index.js","ready-resource":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/ready-resource/index.js","safety-catch":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/safety-catch/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/boot.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/package.json","./messages.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/messages.js","compact-encoding":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/compact-encoding/index.js","encryption-encoding":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/encryption-encoding/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/caps.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/package.json","hypercore-crypto":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-crypto/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/clock.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/package.json","tiny-buffer-map":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/tiny-buffer-map/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/consensus.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/package.json","./clock.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/clock.js","tiny-buffer-map":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/tiny-buffer-map/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/encryption.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/package.json","./caps.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/caps.js","./messages.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/messages.js","./system.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/system.js","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/compact-encoding/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-crypto/index.js","hypercore/lib/default-encryption.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/default-encryption.js","ready-resource":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/ready-resource/index.js","resolve-reject-promise":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/resolve-reject-promise/index.js","sodium-universal":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/fast-forward.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/package.json","./encryption.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/encryption.js","./system.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/system.js","resolve-reject-promise":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/resolve-reject-promise/index.js","safety-catch":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/safety-catch/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/fork.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/package.json","./encryption.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/encryption.js","./messages.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/messages.js","./system.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/system.js","compact-encoding":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/compact-encoding/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/linearizer.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/package.json","./clock.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/clock.js","./consensus.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/consensus.js","./topolist.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/topolist.js","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js","nanoassert":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/nanoassert/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/local-state.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/package.json","./messages.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/messages.js","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/compact-encoding/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/messages.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/package.json","../encoding/spec/autobase":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/encoding/spec/autobase/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/node-buffer.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/package.json"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/store.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/package.json","./messages.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/messages.js","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/compact-encoding/index.js","hypercore":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-crypto/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/system.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/package.json","./caps.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/caps.js","./messages.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/messages.js","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/compact-encoding/index.js","hyperbee":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hyperbee/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-crypto/index.js","ready-resource":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/ready-resource/index.js","sub-encoder":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/sub-encoder/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/timer.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/package.json","safety-catch":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/safety-catch/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/topolist.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/package.json","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js","nanoassert":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/nanoassert/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/updates.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/package.json"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/values.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/package.json","./caps.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/caps.js","./encryption.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/encryption.js","./messages.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/messages.js","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/compact-encoding/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-crypto/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/wakeup.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/package.json","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/compact-encoding/index.js","ready-resource":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/ready-resource/index.js","safety-catch":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/safety-catch/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/writer.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/package.json","./linearizer.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/linearizer.js","./node-buffer.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/node-buffer.js","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/compact-encoding/index.js","nanoassert":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/nanoassert/index.js","ready-resource":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/ready-resource/index.js","signal-promise":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/signal-promise/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/package.json"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-ansi-escapes/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-ansi-escapes/package.json"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-ansi-escapes/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-assert/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-assert/package.json","bare-inspect":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-inspect/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-assert/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-events/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-events/package.json","./lib/errors":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-events/lib/errors.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-events/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-events/package.json"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-events/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-fs/binding.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-fs/package.json",".":"linked:libbare-fs.4.7.4.so"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-fs/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-fs/package.json","./binding":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-fs/binding.js","./lib/constants":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-fs/lib/constants.js","./lib/errors":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-fs/lib/errors.js","./promises":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-fs/promises.js","bare-events":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-events/index.js","bare-path":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-path/index.js","bare-stream":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-stream/index.js","bare-url":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-url/index.js","fast-fifo":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/fast-fifo/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-fs/lib/constants.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-fs/package.json","../binding":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-fs/binding.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-fs/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-fs/package.json","../binding":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-fs/binding.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-fs/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-fs/promises.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-fs/package.json",".":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-fs/index.js","bare-events":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-events/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-inspect/binding.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-inspect/package.json",".":"linked:libbare-inspect.3.1.4.so"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-inspect/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-inspect/package.json","./binding":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-inspect/binding.js","bare-ansi-escapes":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-ansi-escapes/index.js","bare-type":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-type/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-inspect/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-os/binding.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-os/package.json",".":"linked:libbare-os.3.8.7.so"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-os/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-os/package.json","./binding":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-os/binding.js","./lib/constants":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-os/lib/constants.js","./lib/errors":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-os/lib/errors.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-os/lib/constants.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-os/package.json","../binding":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-os/binding.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-os/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-os/package.json"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-os/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-path/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-path/package.json","./lib/posix":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-path/lib/posix.js","./lib/win32":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-path/lib/win32.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-path/lib/constants.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-path/package.json"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-path/lib/posix.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-path/package.json","./constants":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-path/lib/constants.js","./shared":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-path/lib/shared.js","./win32":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-path/lib/win32.js","bare-os":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-os/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-path/lib/shared.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-path/package.json","./constants":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-path/lib/constants.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-path/lib/win32.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-path/package.json","./constants":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-path/lib/constants.js","./posix":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-path/lib/posix.js","./shared":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-path/lib/shared.js","bare-os":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-os/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-path/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-stream/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-stream/package.json","./web":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-stream/web.js","streamx":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/streamx/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-stream/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-stream/web.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-stream/package.json","streamx":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/streamx/index.js","teex":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/teex/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-type/binding.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-type/package.json",".":"linked:libbare-type.1.1.0.so"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-type/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-type/package.json","./binding":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-type/binding.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-type/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-url/binding.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-url/package.json",".":"linked:libbare-url.2.4.0.so"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-url/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-url/package.json","./binding":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-url/binding.js","./lib/errors":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-url/lib/errors.js","./lib/url-search-params":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-url/lib/url-search-params.js","bare-path":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-path/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-url/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-url/package.json"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-url/lib/url-search-params.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-url/package.json"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-url/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/big-sparse-array/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/big-sparse-array/package.json"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/big-sparse-array/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/codecs/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/codecs/package.json","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/codecs/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/compact-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/compact-encoding/raw.js","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/compact-encoding/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/compact-encoding/endian.js","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/core-coupler/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/core-coupler/package.json","safety-catch":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/safety-catch/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/core-coupler/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/debounceify/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/debounceify/package.json"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/debounceify/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/device-file/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/device-file/package.json","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js","fd-lock":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/fd-lock/index.js","fs":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-fs/index.js","fs-native-extensions":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/fs-native-extensions/index.js","path":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-path/index.js","ready-resource":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/ready-resource/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/device-file/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/encryption-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/encryption-encoding/package.json","./spec/hyperschema":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/encryption-encoding/spec/hyperschema/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/encryption-encoding/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/encryption-encoding/spec/hyperschema/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/encryption-encoding/package.json","hyperschema/runtime":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hyperschema/runtime.cjs"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/events-universal/bare.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/events-universal/package.json","bare-events":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-events/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/events-universal/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/fast-fifo/fixed-size.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/fast-fifo/package.json"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/fast-fifo/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/fast-fifo/package.json","./fixed-size":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/fast-fifo/fixed-size.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/fast-fifo/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/fd-lock/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/fd-lock/package.json","fs":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-fs/index.js","fs-native-extensions":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/fs-native-extensions/index.js","ready-resource":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/ready-resource/index.js","resource-on-exit":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/resource-on-exit/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/fd-lock/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/flat-tree/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/flat-tree/package.json"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/flat-tree/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/fs-native-extensions/binding.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/fs-native-extensions/package.json",".":"linked:libfs-native-extensions.1.4.5.so","require-addon":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/require-addon/lib/bare.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/fs-native-extensions/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/fs-native-extensions/package.json","./binding":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/fs-native-extensions/binding.js","which-runtime":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/which-runtime/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/fs-native-extensions/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hyperbee/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hyperbee/package.json","./iterators/diff":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hyperbee/iterators/diff.js","./iterators/history":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hyperbee/iterators/history.js","./iterators/local":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hyperbee/iterators/local.js","./iterators/range":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hyperbee/iterators/range.js","./lib/extension":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hyperbee/lib/extension.js","./lib/messages":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hyperbee/lib/messages.js","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js","codecs":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/codecs/index.js","debounceify":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/debounceify/index.js","hypercore-errors":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-errors/index.js","mutexify/promise":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/mutexify/promise.js","rache":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/rache/index.js","ready-resource":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/ready-resource/index.js","resolve-reject-promise":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/resolve-reject-promise/index.js","safety-catch":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/safety-catch/index.js","streamx":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/streamx/index.js","unslab":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/unslab/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hyperbee/iterators/diff.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hyperbee/package.json","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hyperbee/iterators/history.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hyperbee/package.json"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hyperbee/iterators/local.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hyperbee/package.json"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hyperbee/iterators/range.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hyperbee/package.json","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hyperbee/lib/extension.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hyperbee/package.json","./messages":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hyperbee/lib/messages.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hyperbee/lib/messages.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hyperbee/package.json","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js","protocol-buffers-encodings":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/protocol-buffers-encodings/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hyperbee/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-crypto/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-crypto/package.json","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/compact-encoding/index.js","sodium-universal":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-crypto/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-errors/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-errors/package.json","hypercore-id-encoding":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-id-encoding/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-errors/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-id-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-id-encoding/package.json","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js","z32":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/z32/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-id-encoding/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-storage/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-storage/package.json","./lib/keys.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-storage/lib/keys.js","./lib/streams.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-storage/lib/streams.js","./lib/tx.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-storage/lib/tx.js","./lib/view.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-storage/lib/view.js","./migrations/0":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-storage/migrations/0/index.js","device-file":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/device-file/index.js","fs":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-fs/index.js","path":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-path/index.js","resolve-reject-promise":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/resolve-reject-promise/index.js","rocksdb-native":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/rocksdb-native/index.js","scope-lock":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/scope-lock/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-storage/lib/block-dependency-stream.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-storage/package.json","./keys":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-storage/lib/keys.js","streamx":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/streamx/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-storage/lib/close-error-stream.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-storage/package.json","streamx":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/streamx/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-storage/lib/keys.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-storage/package.json","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/compact-encoding/index.js","index-encoder":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/index-encoder/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-storage/lib/streams.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-storage/package.json","../spec/hyperschema":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-storage/spec/hyperschema/index.js","./block-dependency-stream.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-storage/lib/block-dependency-stream.js","./keys.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-storage/lib/keys.js","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-storage/lib/tx.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-storage/package.json","../spec/hyperschema":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-storage/spec/hyperschema/index.js","./keys.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-storage/lib/keys.js","./view.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-storage/lib/view.js","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js","flat-tree":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/flat-tree/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-storage/lib/view.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-storage/package.json","./close-error-stream.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-storage/lib/close-error-stream.js","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js","streamx":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/streamx/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-storage/migrations/0/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-storage/package.json","../../lib/tx.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-storage/lib/tx.js","../../lib/view.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-storage/lib/view.js","./messages.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-storage/migrations/0/messages.js","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/compact-encoding/index.js","flat-tree":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/flat-tree/index.js","fs":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-fs/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-crypto/index.js","path":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-path/index.js","streamx":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/streamx/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-storage/migrations/0/messages.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-storage/package.json","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/compact-encoding/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-storage/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-storage/spec/hyperschema/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-storage/package.json","hyperschema/runtime":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hyperschema/runtime.cjs"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/package.json","./lib/caps":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/caps.js","./lib/core":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/core.js","./lib/default-encryption":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/default-encryption.js","./lib/download":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/download.js","./lib/feature-flags":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/feature-flags.js","./lib/fully-remote-proof":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/fully-remote-proof.js","./lib/info":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/info.js","./lib/inspect":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/inspect.js","./lib/mark-bitfield":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/mark-bitfield.js","./lib/merkle-tree":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/merkle-tree.js","./lib/replicator":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/replicator.js","./lib/streams":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/streams.js","./lib/verifier":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/verifier.js","./lib/wants":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/wants.js","@hyperswarm/secret-stream":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/@hyperswarm/secret-stream/index.js","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/compact-encoding/index.js","events":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-events/index.js","flat-tree":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/flat-tree/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-crypto/index.js","hypercore-errors":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-errors/index.js","hypercore-id-encoding":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-id-encoding/index.js","hypercore-storage":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-storage/index.js","is-options":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/is-options/index.js","nanoassert":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/nanoassert/index.js","protomux":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/protomux/index.js","safety-catch":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/safety-catch/index.js","unslab":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/unslab/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/audit.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/package.json","./merkle-tree":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/merkle-tree.js","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js","flat-tree":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/flat-tree/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-crypto/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/bit-interlude.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/package.json","./compat":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/compat.js","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/bitfield.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/package.json","./compat":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/compat.js","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js","big-sparse-array":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/big-sparse-array/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/caps.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/package.json","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/compact-encoding/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-crypto/index.js","sodium-universal":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/compat.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/package.json","quickbit-universal":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/quickbit-universal/index.js","quickbit-universal/fallback":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/quickbit-universal/fallback.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/copy-prologue.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/package.json","./bitfield":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/bitfield.js","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js","flat-tree":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/flat-tree/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-crypto/index.js","quickbit-universal":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/quickbit-universal/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/core.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/package.json","./audit":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/audit.js","./bit-interlude":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/bit-interlude.js","./bitfield":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/bitfield.js","./copy-prologue":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/copy-prologue.js","./merkle-tree":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/merkle-tree.js","./mutex":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/mutex.js","./remote-bitfield":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/remote-bitfield.js","./replicator":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/replicator.js","./session-state":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/session-state.js","./verifier":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/verifier.js","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-crypto/index.js","hypercore-errors":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-errors/index.js","unslab":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/unslab/index.js","z32":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/z32/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/default-encryption.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/package.json","./caps":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/caps.js","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/compact-encoding/index.js","sodium-universal":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/download.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/package.json"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/feature-flags.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/package.json"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/fully-remote-proof.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/package.json","./merkle-tree.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/merkle-tree.js","./messages.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/messages.js","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/compact-encoding/index.js","flat-tree":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/flat-tree/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-crypto/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/hotswap-queue.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/package.json"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/info.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/package.json"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/inspect.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/package.json","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/mark-bitfield.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/package.json","./compat":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/compat.js","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js","big-sparse-array":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/big-sparse-array/index.js","streamx":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/streamx/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/merkle-tree.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/package.json","./caps":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/caps.js","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js","flat-tree":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/flat-tree/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-crypto/index.js","hypercore-errors":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-errors/index.js","unslab":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/unslab/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/messages.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/package.json","./caps":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/caps.js","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/compact-encoding/index.js","hypercore-errors":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-errors/index.js","unslab":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/unslab/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/multisig.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/package.json","./merkle-tree":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/merkle-tree.js","./messages":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/messages.js","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/compact-encoding/index.js","flat-tree":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/flat-tree/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/mutex.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/package.json"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/receiver-queue.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/package.json","fast-fifo":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/fast-fifo/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/remote-bitfield.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/package.json","./compat":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/compat.js","big-sparse-array":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/big-sparse-array/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/replicator.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/package.json","./caps":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/caps.js","./hotswap-queue":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/hotswap-queue.js","./merkle-tree":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/merkle-tree.js","./messages":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/messages.js","./mutex":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/mutex.js","./receiver-queue":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/receiver-queue.js","./remote-bitfield":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/remote-bitfield.js","./wants":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/wants.js","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js","flat-tree":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/flat-tree/index.js","hypercore-errors":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-errors/index.js","random-array-iterator":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/random-array-iterator/index.js","safety-catch":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/safety-catch/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/session-state.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/package.json","./bitfield":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/bitfield.js","./merkle-tree":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/merkle-tree.js","./mutex":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/mutex.js","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js","flat-tree":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/flat-tree/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-crypto/index.js","hypercore-errors":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-errors/index.js","hypercore-storage":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-storage/index.js","nanoassert":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/nanoassert/index.js","quickbit-universal":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/quickbit-universal/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/streams.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/package.json","streamx":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/streamx/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/verifier.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/package.json","./caps":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/caps.js","./messages":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/messages.js","./multisig":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/multisig.js","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/compact-encoding/index.js","flat-tree":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/flat-tree/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-crypto/index.js","hypercore-errors":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-errors/index.js","unslab":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/unslab/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/wants.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/package.json"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hyperschema/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hyperschema/runtime.cjs":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hyperschema/package.json","compact-encoding":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/compact-encoding/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/index-encoder/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/index-encoder/package.json","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/index-encoder/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/is-options/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/is-options/package.json","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/is-options/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/mutexify/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/mutexify/package.json","queue-tick":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/queue-tick/process-next-tick.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/mutexify/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/mutexify/promise.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/mutexify/package.json",".":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/mutexify/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/nanoassert/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/nanoassert/package.json"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/nanoassert/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/noise-curve-ed/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/noise-curve-ed/package.json","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js","nanoassert":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/nanoassert/index.js","sodium-universal":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/noise-curve-ed/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/noise-handshake/cipher.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/noise-handshake/package.json","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js","sodium-universal":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/noise-handshake/dh.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/noise-handshake/package.json","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js","nanoassert":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/nanoassert/index.js","sodium-universal":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/noise-handshake/hkdf.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/noise-handshake/package.json","./hmac":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/noise-handshake/hmac.js","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/noise-handshake/hmac.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/noise-handshake/package.json","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js","sodium-universal":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/noise-handshake/noise.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/noise-handshake/package.json","./hkdf":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/noise-handshake/hkdf.js","./symmetric-state":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/noise-handshake/symmetric-state.js","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js","nanoassert":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/nanoassert/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/noise-handshake/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/noise-handshake/symmetric-state.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/noise-handshake/package.json","./cipher":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/noise-handshake/cipher.js","./dh":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/noise-handshake/dh.js","./hkdf":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/noise-handshake/hkdf.js","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js","nanoassert":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/nanoassert/index.js","sodium-universal":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/protocol-buffers-encodings/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/protocol-buffers-encodings/package.json","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js","signed-varint":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/signed-varint/index.js","varint":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/varint/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/protocol-buffers-encodings/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/protomux-wakeup/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/protomux-wakeup/package.json","./spec/hyperschema":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/protomux-wakeup/spec/hyperschema/index.js","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-crypto/index.js","protomux":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/protomux/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/protomux-wakeup/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/protomux-wakeup/spec/hyperschema/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/protomux-wakeup/package.json","hyperschema/runtime":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hyperschema/runtime.cjs"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/protomux/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/protomux/package.json","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/compact-encoding/index.js","queue-tick":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/queue-tick/process-next-tick.js","safety-catch":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/safety-catch/index.js","unslab":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/unslab/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/protomux/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/queue-tick/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/queue-tick/process-next-tick.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/queue-tick/package.json","./queue-microtask":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/queue-tick/queue-microtask.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/queue-tick/queue-microtask.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/queue-tick/package.json"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/quickbit-native/binding.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/quickbit-native/package.json",".":"linked:libquickbit-native.2.4.8.so","require-addon":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/require-addon/lib/bare.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/quickbit-native/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/quickbit-native/package.json","./binding":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/quickbit-native/binding.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/quickbit-native/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/quickbit-universal/fallback.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/quickbit-universal/package.json","simdle-universal":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/simdle-universal/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/quickbit-universal/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/quickbit-universal/package.json","./fallback":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/quickbit-universal/fallback.js","quickbit-native":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/quickbit-native/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/quickbit-universal/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/rache/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/rache/package.json"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/rache/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/random-array-iterator/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/random-array-iterator/package.json"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/random-array-iterator/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/ready-resource/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/ready-resource/package.json","events":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-events/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/ready-resource/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/refcounter/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/refcounter/package.json"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/refcounter/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/require-addon/lib/bare.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/require-addon/package.json"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/require-addon/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/resolve-reject-promise/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/resolve-reject-promise/package.json"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/resolve-reject-promise/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/resource-on-exit/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/resource-on-exit/package.json"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/resource-on-exit/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/rocksdb-native/binding.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/rocksdb-native/package.json",".":"linked:librocksdb-native.3.15.0.so","require-addon":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/require-addon/lib/bare.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/rocksdb-native/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/rocksdb-native/package.json","./lib/column-family":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/rocksdb-native/lib/column-family.js","./lib/constants":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/rocksdb-native/lib/constants.js","./lib/filter-policy":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/rocksdb-native/lib/filter-policy.js","./lib/iterator":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/rocksdb-native/lib/iterator.js","./lib/snapshot":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/rocksdb-native/lib/snapshot.js","./lib/state":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/rocksdb-native/lib/state.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/rocksdb-native/lib/batch.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/rocksdb-native/package.json","../binding":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/rocksdb-native/binding.js","compact-encoding":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/compact-encoding/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/rocksdb-native/lib/column-family.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/rocksdb-native/package.json","../binding":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/rocksdb-native/binding.js","./constants":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/rocksdb-native/lib/constants.js","./filter-policy":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/rocksdb-native/lib/filter-policy.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/rocksdb-native/lib/constants.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/rocksdb-native/package.json"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/rocksdb-native/lib/filter-policy.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/rocksdb-native/package.json"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/rocksdb-native/lib/iterator.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/rocksdb-native/package.json","../binding":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/rocksdb-native/binding.js","compact-encoding":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/compact-encoding/index.js","streamx":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/streamx/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/rocksdb-native/lib/snapshot.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/rocksdb-native/package.json","../binding":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/rocksdb-native/binding.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/rocksdb-native/lib/state.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/rocksdb-native/package.json","../binding":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/rocksdb-native/binding.js","./batch":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/rocksdb-native/lib/batch.js","./column-family":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/rocksdb-native/lib/column-family.js","./constants":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/rocksdb-native/lib/constants.js","compact-encoding":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/compact-encoding/index.js","ready-resource":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/ready-resource/index.js","refcounter":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/refcounter/index.js","resolve-reject-promise":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/resolve-reject-promise/index.js","signal-promise":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/signal-promise/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/rocksdb-native/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/safety-catch/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/safety-catch/package.json"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/safety-catch/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/scope-lock/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/scope-lock/package.json"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/scope-lock/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/signal-promise/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/signal-promise/package.json"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/signal-promise/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/signed-varint/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/signed-varint/package.json","varint":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/varint/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/signed-varint/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/simdle-native/binding.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/simdle-native/package.json",".":"linked:libsimdle-native.1.3.9.so","require-addon":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/require-addon/lib/bare.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/simdle-native/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/simdle-native/package.json","./binding":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/simdle-native/binding.js","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/simdle-native/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/simdle-universal/fallback.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/simdle-universal/package.json","./scalar":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/simdle-universal/scalar.js","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/simdle-universal/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/simdle-universal/package.json","./fallback":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/simdle-universal/fallback.js","simdle-native":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/simdle-native/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/simdle-universal/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/simdle-universal/scalar.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/simdle-universal/package.json"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/sodium-native/binding.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/sodium-native/package.json",".":"linked:libsodium-native.5.1.0.so","require-addon":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/require-addon/lib/bare.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/sodium-native/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/sodium-native/package.json","./binding":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/sodium-native/binding.js","assert":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-assert/index.js","which-runtime":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/which-runtime/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/sodium-native/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/sodium-secretstream/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/sodium-secretstream/package.json","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js","sodium-universal":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/sodium-secretstream/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/sodium-universal/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/sodium-universal/package.json","sodium-native":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/sodium-native/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/sodium-universal/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/streamx/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/streamx/package.json","events-universal":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/events-universal/bare.js","fast-fifo":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/fast-fifo/index.js","text-decoder":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/text-decoder/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/streamx/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/sub-encoder/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/sub-encoder/package.json","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js","codecs":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/codecs/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/sub-encoder/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/teex/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/teex/package.json","streamx":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/streamx/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/teex/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/text-decoder/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/text-decoder/package.json","./lib/pass-through-decoder":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/text-decoder/lib/pass-through-decoder.js","./lib/utf8-decoder":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/text-decoder/lib/utf8-decoder.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/text-decoder/lib/pass-through-decoder.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/text-decoder/package.json","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/text-decoder/lib/utf8-decoder.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/text-decoder/package.json","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/text-decoder/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/timeout-refresh/browser.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/timeout-refresh/package.json"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/timeout-refresh/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/timeout-refresh/package.json","./browser":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/timeout-refresh/browser.js","./node":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/timeout-refresh/node.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/timeout-refresh/node.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/timeout-refresh/package.json"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/timeout-refresh/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/tiny-buffer-map/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/tiny-buffer-map/package.json","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/tiny-buffer-map/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/unslab/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/unslab/package.json","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/unslab/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/varint/decode.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/varint/package.json"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/varint/encode.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/varint/package.json"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/varint/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/varint/package.json","./decode.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/varint/decode.js","./encode.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/varint/encode.js","./length.js":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/varint/length.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/varint/length.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/varint/package.json"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/varint/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/which-runtime/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/which-runtime/package.json"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/which-runtime/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/z32/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/z32/package.json","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/z32/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/hypercore-crypto/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/hypercore-crypto/package.json","b4a":"/node_modules/favela-web/node_modules/favela-community/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/favela-community/node_modules/compact-encoding/index.js","sodium-universal":"/node_modules/favela-web/node_modules/favela-community/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/hypercore-crypto/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/require-addon/lib/bare.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/require-addon/package.json"},"/node_modules/favela-web/node_modules/favela-community/node_modules/require-addon/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/sodium-native/binding.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/sodium-native/package.json",".":"linked:libsodium-native.5.1.0.so","require-addon":"/node_modules/favela-web/node_modules/favela-community/node_modules/require-addon/lib/bare.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/sodium-native/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/sodium-native/package.json","./binding":"/node_modules/favela-web/node_modules/favela-community/node_modules/sodium-native/binding.js","assert":"/node_modules/favela-web/node_modules/favela-community/node_modules/bare-assert/index.js","which-runtime":"/node_modules/favela-web/node_modules/favela-community/node_modules/which-runtime/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/sodium-native/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/sodium-universal/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/sodium-universal/package.json","sodium-native":"/node_modules/favela-web/node_modules/favela-community/node_modules/sodium-native/index.js"},"/node_modules/favela-web/node_modules/favela-community/node_modules/sodium-universal/package.json":{},"/node_modules/favela-web/node_modules/favela-community/node_modules/which-runtime/index.js":{"#package":"/node_modules/favela-web/node_modules/favela-community/node_modules/which-runtime/package.json"},"/node_modules/favela-web/node_modules/favela-community/node_modules/which-runtime/package.json":{},"/node_modules/favela-web/node_modules/favela-community/package.json":{},"/node_modules/favela-web/node_modules/fd-lock/index.js":{"#package":"/node_modules/favela-web/node_modules/fd-lock/package.json","fs":"/node_modules/favela-web/node_modules/bare-fs/index.js","fs-native-extensions":"/node_modules/favela-web/node_modules/fs-native-extensions/index.js","ready-resource":"/node_modules/favela-web/node_modules/ready-resource/index.js","resource-on-exit":"/node_modules/favela-web/node_modules/resource-on-exit/index.js"},"/node_modules/favela-web/node_modules/fd-lock/package.json":{},"/node_modules/favela-web/node_modules/flat-tree/index.js":{"#package":"/node_modules/favela-web/node_modules/flat-tree/package.json"},"/node_modules/favela-web/node_modules/flat-tree/package.json":{},"/node_modules/favela-web/node_modules/fs-native-extensions/binding.js":{"#package":"/node_modules/favela-web/node_modules/fs-native-extensions/package.json",".":"linked:libfs-native-extensions.1.5.0.so","require-addon":"/node_modules/favela-web/node_modules/require-addon/lib/bare.js"},"/node_modules/favela-web/node_modules/fs-native-extensions/index.js":{"#package":"/node_modules/favela-web/node_modules/fs-native-extensions/package.json","./binding":"/node_modules/favela-web/node_modules/fs-native-extensions/binding.js","which-runtime":"/node_modules/favela-web/node_modules/which-runtime/index.js"},"/node_modules/favela-web/node_modules/fs-native-extensions/package.json":{},"/node_modules/favela-web/node_modules/hyper-identity/lib/auth/base-provider.js":{"#package":"/node_modules/favela-web/node_modules/hyper-identity/package.json"},"/node_modules/favela-web/node_modules/hyper-identity/lib/auth/providers/atproto.js":{"#package":"/node_modules/favela-web/node_modules/hyper-identity/package.json","../base-provider.js":"/node_modules/favela-web/node_modules/hyper-identity/lib/auth/base-provider.js"},"/node_modules/favela-web/node_modules/hyper-identity/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/lib/adopt.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/package.json","./coowner.js":"/node_modules/favela-web/node_modules/hyper-proto-peer/lib/coowner.js","atproto-room/lib/pairing.js":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/lib/pairing.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/lib/config.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/package.json","bare-fs":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-fs/index.js","bare-os":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-os/index.js","bare-path":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-path/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/lib/coowner.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/package.json","./config.js":"/node_modules/favela-web/node_modules/hyper-proto-peer/lib/config.js","atproto-identity/lib/device-chain.js":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/lib/device-chain.js","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/b4a/index.js","bare-fs":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-fs/index.js","keet-identity-key":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/keet-identity-key/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/lib/device-chain.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/package.json","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/b4a/index.js","keet-identity-key":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/keet-identity-key/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/b4a/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/b4a/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/b4a/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-ansi-escapes/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-ansi-escapes/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-ansi-escapes/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-assert/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-assert/package.json","bare-inspect":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-inspect/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-assert/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-inspect/binding.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-inspect/package.json",".":"linked:libbare-inspect.3.1.4.so"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-inspect/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-inspect/package.json","./binding":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-inspect/binding.js","bare-ansi-escapes":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-ansi-escapes/index.js","bare-type":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-type/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-inspect/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-type/binding.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-type/package.json",".":"linked:libbare-type.1.1.0.so"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-type/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-type/package.json","./binding":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-type/binding.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-type/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json","./wordlist":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/index.js","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/b4a/index.js","nanoassert":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/nanoassert/index.js","sodium-universal":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/chinese_simplified.json":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/chinese_traditional.json":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/czech.json":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/english.json":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/french.json":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json","./chinese_simplified.json":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/chinese_simplified.json","./chinese_traditional.json":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/chinese_traditional.json","./czech.json":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/czech.json","./english.json":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/english.json","./french.json":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/french.json","./italian.json":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/italian.json","./japanese.json":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/japanese.json","./korean.json":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/korean.json","./lookup.json":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/lookup.json","./portuguese.json":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/portuguese.json","./russian.json":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/russian.json","./spanish.json":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/spanish.json","./turkish.json":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/turkish.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/italian.json":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/japanese.json":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/korean.json":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/lookup.json":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/portuguese.json":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/russian.json":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/spanish.json":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/turkish.json":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/compact-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/compact-encoding/raw.js","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/compact-encoding/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/compact-encoding/endian.js","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/keet-identity-key/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/keet-identity-key/package.json","./lib/crypto":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/keet-identity-key/lib/crypto.js","./lib/encoding":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/keet-identity-key/lib/encoding.js","./lib/keychain":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/keet-identity-key/lib/keychain.js","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/compact-encoding/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/keet-identity-key/lib/crypto.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/keet-identity-key/package.json","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/b4a/index.js","sodium-universal":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/keet-identity-key/lib/encoding.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/keet-identity-key/package.json","compact-encoding":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/compact-encoding/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/keet-identity-key/lib/keychain.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/keet-identity-key/package.json","./crypto":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/keet-identity-key/lib/crypto.js","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/b4a/index.js","bip39-mnemonic":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/index.js","compact-encoding":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/compact-encoding/index.js","nanoassert":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/nanoassert/index.js","sodium-hmac":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-hmac/index.js","sodium-universal":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/keet-identity-key/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/nanoassert/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/nanoassert/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/nanoassert/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/require-addon/lib/bare.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/require-addon/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/require-addon/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-hmac/hash/sha256.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-hmac/package.json","sodium-universal":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-hmac/hash/sha512.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-hmac/package.json","sodium-universal":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-hmac/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-hmac/package.json","./hash/sha256":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-hmac/hash/sha256.js","./hash/sha512":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-hmac/hash/sha512.js","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-hmac/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-native/binding.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-native/package.json",".":"linked:libsodium-native.5.1.0.so","require-addon":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/require-addon/lib/bare.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-native/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-native/package.json","./binding":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-native/binding.js","assert":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-assert/index.js","which-runtime":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/which-runtime/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-native/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-universal/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-universal/package.json","sodium-native":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-native/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-universal/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/which-runtime/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/which-runtime/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/which-runtime/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/lib/pairing.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/package.json","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","blind-pairing":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-pairing/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/index.js","hyperswarm":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperswarm/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/@hyperswarm/secret-stream/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/@hyperswarm/secret-stream/package.json","./lib/bridge":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/@hyperswarm/secret-stream/lib/bridge.js","./lib/handshake":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/@hyperswarm/secret-stream/lib/handshake.js","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/index.js","sodium-secretstream":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-secretstream/index.js","sodium-universal":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-universal/index.js","streamx":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/streamx/index.js","timeout-refresh":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/timeout-refresh/index.js","unslab":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/unslab/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/@hyperswarm/secret-stream/lib/bridge.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/@hyperswarm/secret-stream/package.json","streamx":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/streamx/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/@hyperswarm/secret-stream/lib/handshake.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/@hyperswarm/secret-stream/package.json","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","noise-curve-ed":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-curve-ed/index.js","noise-handshake":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-handshake/noise.js","sodium-universal":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/@hyperswarm/secret-stream/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/adaptive-timeout/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/adaptive-timeout/package.json","xache":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/xache/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/adaptive-timeout/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-ansi-escapes/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-ansi-escapes/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-ansi-escapes/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-assert/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-assert/package.json","bare-inspect":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-inspect/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-assert/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-events/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-events/package.json","./lib/errors":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-events/lib/errors.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-events/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-events/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-events/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-inspect/binding.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-inspect/package.json",".":"linked:libbare-inspect.3.1.4.so"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-inspect/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-inspect/package.json","./binding":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-inspect/binding.js","bare-ansi-escapes":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-ansi-escapes/index.js","bare-type":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-type/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-inspect/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-type/binding.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-type/package.json",".":"linked:libbare-type.1.1.0.so"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-type/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-type/package.json","./binding":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-type/binding.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-type/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bits-to-bytes/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bits-to-bytes/package.json","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bits-to-bytes/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-pairing/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-pairing/package.json","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","blind-pairing-core":"/node_modules/favela-web/node_modules/blind-pairing-core/index.js","compact-encoding":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding/index.js","debounceify":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/debounceify/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/index.js","is-options":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/is-options/index.js","protomux":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux/index.js","ready-resource":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/ready-resource/index.js","safety-catch":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/safety-catch/index.js","xache":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/xache/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-pairing/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-relay/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-relay/package.json","./lib/errors":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-relay/lib/errors.js","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","bits-to-bytes":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bits-to-bytes/index.js","compact-encoding":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-relay/node_modules/compact-encoding/index.js","compact-encoding-bitfield":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding-bitfield/index.js","events":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-events/index.js","protomux":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux/index.js","sodium-universal":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-universal/index.js","streamx":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/streamx/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-relay/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-relay/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-relay/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-relay/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-relay/node_modules/compact-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-relay/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-relay/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-relay/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-relay/node_modules/compact-encoding/raw.js","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-relay/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-relay/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-relay/node_modules/compact-encoding/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-relay/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-relay/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-relay/node_modules/compact-encoding/endian.js","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-relay/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bogon/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bogon/package.json","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bogon/node_modules/compact-encoding/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bogon/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bogon/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bogon/node_modules/compact-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bogon/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bogon/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bogon/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bogon/node_modules/compact-encoding/raw.js","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bogon/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bogon/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bogon/node_modules/compact-encoding/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bogon/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bogon/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bogon/node_modules/compact-encoding/endian.js","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bogon/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding-bitfield/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding-bitfield/package.json","compact-encoding":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/raw.js","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/endian.js","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding-bitfield/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding/raw.js","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding/endian.js","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/debounceify/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/debounceify/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/debounceify/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/package.json","./lib/commands":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/lib/commands.js","./lib/errors":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/lib/errors.js","./lib/health":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/lib/health.js","./lib/io":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/lib/io.js","./lib/peer":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/lib/peer.js","./lib/query":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/lib/query.js","./lib/session":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/lib/session.js","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/node_modules/compact-encoding/index.js","events":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-events/index.js","kademlia-routing-table":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/kademlia-routing-table/index.js","nat-sampler":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/nat-sampler/index.js","sodium-universal":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-universal/index.js","time-ordered-set":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/time-ordered-set/index.js","udx-native":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/udx-native/lib/udx.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/lib/commands.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/lib/health.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/lib/io.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/package.json","./errors":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/lib/errors.js","./peer":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/lib/peer.js","adaptive-timeout":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/adaptive-timeout/index.js","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/node_modules/compact-encoding/index.js","fast-fifo":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/fast-fifo/index.js","sodium-universal":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/lib/peer.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/package.json","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/node_modules/compact-encoding/index.js","sodium-universal":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/lib/query.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/package.json","./commands":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/lib/commands.js","./peer":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/lib/peer.js","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","streamx":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/streamx/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/lib/session.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/node_modules/compact-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/node_modules/compact-encoding/raw.js","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/node_modules/compact-encoding/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/node_modules/compact-encoding/endian.js","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/events-universal/bare.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/events-universal/package.json","bare-events":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-events/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/events-universal/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/fast-fifo/fixed-size.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/fast-fifo/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/fast-fifo/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/fast-fifo/package.json","./fixed-size":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/fast-fifo/fixed-size.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/fast-fifo/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/package.json","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/node_modules/compact-encoding/index.js","sodium-universal":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/node_modules/compact-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/node_modules/compact-encoding/raw.js","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/node_modules/compact-encoding/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/node_modules/compact-encoding/endian.js","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-id-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-id-encoding/package.json","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","z32":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/z32/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-id-encoding/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht-address/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht-address/package.json","./spec/hyperschema":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht-address/spec/hyperschema/index.js","compact-encoding":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht-address/node_modules/compact-encoding/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht-address/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht-address/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht-address/node_modules/compact-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht-address/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht-address/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht-address/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht-address/node_modules/compact-encoding/raw.js","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht-address/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht-address/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht-address/node_modules/compact-encoding/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht-address/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht-address/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht-address/node_modules/compact-encoding/endian.js","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht-address/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht-address/spec/hyperschema/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht-address/package.json","hyperschema/runtime":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperschema/runtime.cjs"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/package.json","./lib/connect":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/connect.js","./lib/connection-pool":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/connection-pool.js","./lib/constants":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/constants.js","./lib/crypto":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/crypto.js","./lib/errors":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/errors.js","./lib/messages":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/messages.js","./lib/persistent":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/persistent.js","./lib/raw-stream-set":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/raw-stream-set.js","./lib/router":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/router.js","./lib/server":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/server.js","./lib/socket-pool":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/socket-pool.js","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/index.js","dht-rpc":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/index.js","safety-catch":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/safety-catch/index.js","sodium-universal":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-universal/index.js","xache":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/xache/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/announcer.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/package.json","./constants":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/constants.js","./encode":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/encode.js","./messages":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/messages.js","./persistent":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/persistent.js","./sleeper":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/sleeper.js","compact-encoding":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/index.js","safety-catch":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/safety-catch/index.js","signal-promise":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/signal-promise/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/connect.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/package.json","./constants":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/constants.js","./crypto":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/crypto.js","./errors":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/errors.js","./holepuncher":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/holepuncher.js","./noise-wrap":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/noise-wrap.js","./relay-connection":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/relay-connection.js","./secure-payload":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/secure-payload.js","./semaphore":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/semaphore.js","./sleeper":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/sleeper.js","@hyperswarm/secret-stream":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/@hyperswarm/secret-stream/index.js","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","blind-relay":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-relay/index.js","bogon":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bogon/index.js","hypercore-id-encoding":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-id-encoding/index.js","hyperdht-address":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht-address/index.js","safety-catch":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/safety-catch/index.js","unslab":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/unslab/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/connection-pool.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/package.json","./errors":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/errors.js","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","events":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-events/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/constants.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/package.json","hypercore-crypto":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/crypto.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/package.json","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","sodium-universal":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/encode.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/package.json","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/holepuncher.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/package.json","./constants":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/constants.js","./nat":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/nat.js","./sleeper":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/sleeper.js","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/messages.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/package.json","compact-encoding":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/nat.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/package.json","../lib/constants":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/constants.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/noise-wrap.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/package.json","./constants":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/constants.js","./errors":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/errors.js","./messages":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/messages.js","@hyperswarm/secret-stream":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/@hyperswarm/secret-stream/index.js","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/index.js","noise-curve-ed":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-curve-ed/index.js","noise-handshake":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-handshake/noise.js","sodium-universal":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/persistent.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/package.json","./constants":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/constants.js","./encode":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/encode.js","./messages":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/messages.js","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/index.js","record-cache":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/record-cache/index.js","sodium-universal":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-universal/index.js","unslab":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/unslab/index.js","xache":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/xache/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/raw-stream-set.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/relay-connection.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/package.json","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","safety-catch":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/safety-catch/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/router.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/package.json","./constants":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/constants.js","./errors":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/errors.js","./messages":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/messages.js","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/index.js","safety-catch":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/safety-catch/index.js","xache":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/xache/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/secure-payload.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/package.json","./messages":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/messages.js","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","sodium-universal":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/semaphore.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/server.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/package.json","./announcer":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/announcer.js","./constants":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/constants.js","./crypto":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/crypto.js","./errors":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/errors.js","./holepuncher":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/holepuncher.js","./noise-wrap":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/noise-wrap.js","./relay-connection":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/relay-connection.js","./secure-payload":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/secure-payload.js","@hyperswarm/secret-stream":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/@hyperswarm/secret-stream/index.js","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","blind-relay":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-relay/index.js","bogon":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bogon/index.js","events":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-events/index.js","safety-catch":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/safety-catch/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/sleeper.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/socket-pool.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/package.json","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/raw.js","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/endian.js","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperschema/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperschema/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperschema/node_modules/compact-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperschema/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperschema/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperschema/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperschema/node_modules/compact-encoding/raw.js","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperschema/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperschema/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperschema/node_modules/compact-encoding/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperschema/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperschema/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperschema/node_modules/compact-encoding/endian.js","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperschema/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperschema/runtime.cjs":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperschema/package.json","compact-encoding":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperschema/node_modules/compact-encoding/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperswarm/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperswarm/package.json","./lib/connection-set":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperswarm/lib/connection-set.js","./lib/peer-discovery":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperswarm/lib/peer-discovery.js","./lib/peer-info":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperswarm/lib/peer-info.js","./lib/retry-timer":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperswarm/lib/retry-timer.js","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","events":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-events/index.js","hyperdht":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/index.js","shuffled-priority-queue":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/shuffled-priority-queue/index.js","streamx":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/streamx/index.js","unslab":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/unslab/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperswarm/lib/bulk-timer.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperswarm/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperswarm/lib/connection-set.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperswarm/package.json","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperswarm/lib/peer-discovery.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperswarm/package.json","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","safety-catch":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/safety-catch/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperswarm/lib/peer-info.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperswarm/package.json","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","events":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-events/index.js","unslab":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/unslab/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperswarm/lib/retry-timer.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperswarm/package.json","./bulk-timer":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperswarm/lib/bulk-timer.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperswarm/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/is-options/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/is-options/package.json","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/is-options/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/kademlia-routing-table/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/kademlia-routing-table/package.json","events":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-events/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/kademlia-routing-table/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/nanoassert/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/nanoassert/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/nanoassert/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/nat-sampler/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/nat-sampler/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/nat-sampler/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-curve-ed/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-curve-ed/package.json","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","nanoassert":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/nanoassert/index.js","sodium-universal":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-curve-ed/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-handshake/cipher.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-handshake/package.json","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","sodium-universal":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-handshake/dh.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-handshake/package.json","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","nanoassert":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/nanoassert/index.js","sodium-universal":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-handshake/hkdf.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-handshake/package.json","./hmac":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-handshake/hmac.js","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-handshake/hmac.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-handshake/package.json","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","sodium-universal":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-handshake/noise.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-handshake/package.json","./hkdf":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-handshake/hkdf.js","./symmetric-state":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-handshake/symmetric-state.js","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","nanoassert":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/nanoassert/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-handshake/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-handshake/symmetric-state.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-handshake/package.json","./cipher":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-handshake/cipher.js","./dh":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-handshake/dh.js","./hkdf":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-handshake/hkdf.js","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","nanoassert":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/nanoassert/index.js","sodium-universal":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux/package.json","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux/node_modules/compact-encoding/index.js","queue-tick":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/queue-tick/process-next-tick.js","safety-catch":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/safety-catch/index.js","unslab":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/unslab/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux/node_modules/compact-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux/node_modules/compact-encoding/raw.js","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux/node_modules/compact-encoding/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux/node_modules/compact-encoding/endian.js","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/queue-tick/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/queue-tick/process-next-tick.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/queue-tick/package.json","./queue-microtask":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/queue-tick/queue-microtask.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/queue-tick/queue-microtask.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/queue-tick/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/ready-resource/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/ready-resource/package.json","events":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-events/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/ready-resource/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/record-cache/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/record-cache/package.json","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/record-cache/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/require-addon/lib/bare.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/require-addon/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/require-addon/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/safety-catch/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/safety-catch/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/safety-catch/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/shuffled-priority-queue/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/shuffled-priority-queue/package.json","unordered-set":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/unordered-set/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/shuffled-priority-queue/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/signal-promise/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/signal-promise/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/signal-promise/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-native/binding.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-native/package.json",".":"linked:libsodium-native.5.1.0.so","require-addon":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/require-addon/lib/bare.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-native/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-native/package.json","./binding":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-native/binding.js","assert":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-assert/index.js","which-runtime":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/which-runtime/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-native/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-secretstream/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-secretstream/package.json","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","sodium-universal":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-secretstream/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-universal/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-universal/package.json","sodium-native":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-native/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-universal/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/streamx/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/streamx/package.json","./lib/errors.js":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/streamx/lib/errors.js","events-universal":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/events-universal/bare.js","fast-fifo":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/fast-fifo/index.js","text-decoder":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/text-decoder/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/streamx/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/streamx/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/streamx/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/text-decoder/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/text-decoder/package.json","./lib/pass-through-decoder":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/text-decoder/lib/pass-through-decoder.js","./lib/utf8-decoder":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/text-decoder/lib/utf8-decoder.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/text-decoder/lib/pass-through-decoder.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/text-decoder/package.json","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/text-decoder/lib/utf8-decoder.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/text-decoder/package.json","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/text-decoder/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/time-ordered-set/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/time-ordered-set/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/time-ordered-set/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/timeout-refresh/browser.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/timeout-refresh/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/timeout-refresh/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/timeout-refresh/package.json","./browser":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/timeout-refresh/browser.js","./node":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/timeout-refresh/node.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/timeout-refresh/node.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/timeout-refresh/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/timeout-refresh/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/udx-native/binding.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/udx-native/package.json",".":"linked:libudx-native.1.20.7.so","require-addon":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/require-addon/lib/bare.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/udx-native/lib/ip.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/udx-native/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/udx-native/lib/network-interfaces.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/udx-native/package.json","../binding":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/udx-native/binding.js","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","events":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-events/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/udx-native/lib/socket.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/udx-native/package.json","../binding":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/udx-native/binding.js","./ip":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/udx-native/lib/ip.js","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","events":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-events/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/udx-native/lib/stream.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/udx-native/package.json","../binding":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/udx-native/binding.js","./ip":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/udx-native/lib/ip.js","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","streamx":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/streamx/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/udx-native/lib/udx.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/udx-native/package.json","../binding":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/udx-native/binding.js","./ip":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/udx-native/lib/ip.js","./network-interfaces":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/udx-native/lib/network-interfaces.js","./socket":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/udx-native/lib/socket.js","./stream":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/udx-native/lib/stream.js","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/udx-native/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/unordered-set/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/unordered-set/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/unordered-set/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/unslab/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/unslab/package.json","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/unslab/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/which-runtime/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/which-runtime/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/which-runtime/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/xache/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/xache/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/xache/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/z32/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/z32/package.json","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/z32/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/b4a/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/b4a/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/b4a/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-ansi-escapes/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-ansi-escapes/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-ansi-escapes/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-assert/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-assert/package.json","bare-inspect":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-inspect/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-assert/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-events/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-events/package.json","./lib/errors":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-events/lib/errors.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-events/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-events/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-events/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-fs/binding.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-fs/package.json",".":"linked:libbare-fs.4.7.3.so"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-fs/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-fs/package.json","./binding":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-fs/binding.js","./lib/constants":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-fs/lib/constants.js","./lib/errors":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-fs/lib/errors.js","./promises":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-fs/promises.js","bare-events":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-events/index.js","bare-path":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-path/index.js","bare-stream":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-stream/index.js","bare-url":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-url/index.js","fast-fifo":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/fast-fifo/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-fs/lib/constants.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-fs/package.json","../binding":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-fs/binding.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-fs/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-fs/package.json","bare-os":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-os/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-fs/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-fs/promises.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-fs/package.json",".":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-fs/index.js","bare-events":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-events/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-inspect/binding.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-inspect/package.json",".":"linked:libbare-inspect.3.1.4.so"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-inspect/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-inspect/package.json","./binding":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-inspect/binding.js","bare-ansi-escapes":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-ansi-escapes/index.js","bare-type":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-type/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-inspect/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-os/binding.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-os/package.json",".":"linked:libbare-os.3.9.3.so"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-os/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-os/package.json","./binding":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-os/binding.js","./lib/constants":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-os/lib/constants.js","./lib/errors":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-os/lib/errors.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-os/lib/constants.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-os/package.json","../binding":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-os/binding.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-os/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-os/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-os/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-path/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-path/package.json","./lib/posix":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-path/lib/posix.js","./lib/win32":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-path/lib/win32.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-path/lib/constants.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-path/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-path/lib/posix.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-path/package.json","./constants":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-path/lib/constants.js","./shared":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-path/lib/shared.js","./win32":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-path/lib/win32.js","bare-os":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-os/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-path/lib/shared.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-path/package.json","./constants":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-path/lib/constants.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-path/lib/win32.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-path/package.json","./constants":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-path/lib/constants.js","./posix":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-path/lib/posix.js","./shared":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-path/lib/shared.js","bare-os":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-os/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-path/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-stream/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-stream/package.json","./web":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-stream/web.js","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/b4a/index.js","streamx":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/streamx/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-stream/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-stream/web.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-stream/package.json","streamx":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/streamx/index.js","teex":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/teex/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-type/binding.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-type/package.json",".":"linked:libbare-type.1.1.0.so"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-type/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-type/package.json","./binding":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-type/binding.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-type/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-url/binding.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-url/package.json",".":"linked:libbare-url.2.4.5.so"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-url/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-url/package.json","./binding":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-url/binding.js","./lib/errors":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-url/lib/errors.js","./lib/url-search-params":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-url/lib/url-search-params.js","bare-path":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-path/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-url/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-url/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-url/lib/url-search-params.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-url/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-url/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/package.json","./wordlist":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/index.js","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/b4a/index.js","nanoassert":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/nanoassert/index.js","sodium-universal":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/chinese_simplified.json":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/chinese_traditional.json":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/czech.json":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/english.json":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/french.json":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/package.json","./chinese_simplified.json":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/chinese_simplified.json","./chinese_traditional.json":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/chinese_traditional.json","./czech.json":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/czech.json","./english.json":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/english.json","./french.json":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/french.json","./italian.json":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/italian.json","./japanese.json":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/japanese.json","./korean.json":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/korean.json","./lookup.json":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/lookup.json","./portuguese.json":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/portuguese.json","./russian.json":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/russian.json","./spanish.json":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/spanish.json","./turkish.json":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/turkish.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/italian.json":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/japanese.json":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/korean.json":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/lookup.json":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/portuguese.json":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/russian.json":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/spanish.json":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/turkish.json":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/events-universal/bare.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/events-universal/package.json","bare-events":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-events/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/events-universal/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/fast-fifo/fixed-size.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/fast-fifo/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/fast-fifo/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/fast-fifo/package.json","./fixed-size":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/fast-fifo/fixed-size.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/fast-fifo/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/keet-identity-key/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/keet-identity-key/package.json","./lib/crypto":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/keet-identity-key/lib/crypto.js","./lib/encoding":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/keet-identity-key/lib/encoding.js","./lib/keychain":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/keet-identity-key/lib/keychain.js","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/keet-identity-key/node_modules/compact-encoding/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/keet-identity-key/lib/crypto.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/keet-identity-key/package.json","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/b4a/index.js","sodium-universal":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/keet-identity-key/lib/encoding.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/keet-identity-key/package.json","compact-encoding":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/keet-identity-key/node_modules/compact-encoding/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/keet-identity-key/lib/keychain.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/keet-identity-key/package.json","./crypto":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/keet-identity-key/lib/crypto.js","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/b4a/index.js","bip39-mnemonic":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/index.js","compact-encoding":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/keet-identity-key/node_modules/compact-encoding/index.js","nanoassert":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/nanoassert/index.js","sodium-hmac":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/sodium-hmac/index.js","sodium-universal":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/keet-identity-key/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/keet-identity-key/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/keet-identity-key/node_modules/compact-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/keet-identity-key/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/keet-identity-key/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/keet-identity-key/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/keet-identity-key/node_modules/compact-encoding/raw.js","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/keet-identity-key/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/keet-identity-key/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/keet-identity-key/node_modules/compact-encoding/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/keet-identity-key/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/keet-identity-key/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/keet-identity-key/node_modules/compact-encoding/endian.js","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/keet-identity-key/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/nanoassert/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/nanoassert/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/nanoassert/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/require-addon/lib/bare.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/require-addon/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/require-addon/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/sodium-hmac/hash/sha256.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/sodium-hmac/package.json","sodium-universal":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/sodium-hmac/hash/sha512.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/sodium-hmac/package.json","sodium-universal":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/sodium-hmac/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/sodium-hmac/package.json","./hash/sha256":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/sodium-hmac/hash/sha256.js","./hash/sha512":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/sodium-hmac/hash/sha512.js","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/sodium-hmac/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/sodium-native/binding.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/sodium-native/package.json",".":"linked:libsodium-native.5.1.0.so","require-addon":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/require-addon/lib/bare.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/sodium-native/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/sodium-native/package.json","./binding":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/sodium-native/binding.js","assert":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-assert/index.js","which-runtime":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/which-runtime/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/sodium-native/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/sodium-universal/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/sodium-universal/package.json","sodium-native":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/sodium-native/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/sodium-universal/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/streamx/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/streamx/package.json","./lib/errors.js":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/streamx/lib/errors.js","events-universal":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/events-universal/bare.js","fast-fifo":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/fast-fifo/index.js","text-decoder":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/text-decoder/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/streamx/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/streamx/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/streamx/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/teex/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/teex/package.json","streamx":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/streamx/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/teex/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/text-decoder/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/text-decoder/package.json","./lib/pass-through-decoder":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/text-decoder/lib/pass-through-decoder.js","./lib/utf8-decoder":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/text-decoder/lib/utf8-decoder.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/text-decoder/lib/pass-through-decoder.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/text-decoder/package.json","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/text-decoder/lib/utf8-decoder.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/text-decoder/package.json","b4a":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/text-decoder/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/which-runtime/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/which-runtime/package.json"},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/which-runtime/package.json":{},"/node_modules/favela-web/node_modules/hyper-proto-peer/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/package.json","./lib/client.js":"/node_modules/favela-web/node_modules/hyper-svc/lib/client.js","./lib/frame.js":"/node_modules/favela-web/node_modules/hyper-svc/lib/frame.js","./lib/service.js":"/node_modules/favela-web/node_modules/hyper-svc/lib/service.js","./lib/transports/swarm-rpc.js":"/node_modules/favela-web/node_modules/hyper-svc/lib/transports/swarm-rpc.js"},"/node_modules/favela-web/node_modules/hyper-svc/lib/client.js":{"#node:fs/promises":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-fs/promises.js","#node:http":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http1/index.js","#node:url":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-url/index.js","#package":"/node_modules/favela-web/node_modules/hyper-svc/package.json","./frame.js":"/node_modules/favela-web/node_modules/hyper-svc/lib/frame.js","./transports/swarm-rpc.js":"/node_modules/favela-web/node_modules/hyper-svc/lib/transports/swarm-rpc.js","./uds-backend.js":"/node_modules/favela-web/node_modules/hyper-svc/lib/uds-backend.js","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hypercore-crypto/index.js","hyperswarm":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperswarm/index.js","protomux":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/protomux/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/lib/frame.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/package.json","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/lib/service.js":{"#node:process":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-process/index.js","#package":"/node_modules/favela-web/node_modules/hyper-svc/package.json","./transports/http.js":"/node_modules/favela-web/node_modules/hyper-svc/lib/transports/http.js","./transports/swarm.js":"/node_modules/favela-web/node_modules/hyper-svc/lib/transports/swarm.js","./transports/uds.js":"/node_modules/favela-web/node_modules/hyper-svc/lib/transports/uds.js","ready-resource":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/ready-resource/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/lib/transports/http.js":{"#node:http":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http1/index.js","#package":"/node_modules/favela-web/node_modules/hyper-svc/package.json","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/lib/transports/swarm-rpc.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/package.json","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding/index.js","protomux":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/protomux/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/lib/transports/swarm.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/package.json","./swarm-rpc.js":"/node_modules/favela-web/node_modules/hyper-svc/lib/transports/swarm-rpc.js","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js","hyperswarm":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperswarm/index.js","protomux":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/protomux/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/lib/transports/uds.js":{"#node:fs/promises":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-fs/promises.js","#node:process":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-process/index.js","#package":"/node_modules/favela-web/node_modules/hyper-svc/package.json","../frame.js":"/node_modules/favela-web/node_modules/hyper-svc/lib/frame.js","../uds-backend.js":"/node_modules/favela-web/node_modules/hyper-svc/lib/uds-backend.js"},"/node_modules/favela-web/node_modules/hyper-svc/lib/uds-backend.js":{"#node:net":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-net/index.js","#package":"/node_modules/favela-web/node_modules/hyper-svc/package.json","bare-abstract-socket":"deferred:bare-abstract-socket"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/package.json","./lib/bridge":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/lib/bridge.js","./lib/handshake":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/lib/handshake.js","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hypercore-crypto/index.js","sodium-secretstream":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/sodium-secretstream/index.js","sodium-universal":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/sodium-universal/index.js","streamx":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/streamx/index.js","timeout-refresh":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/timeout-refresh/index.js","unslab":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/unslab/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/lib/bridge.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/package.json","streamx":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/streamx/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/lib/handshake.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/package.json","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js","noise-curve-ed":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/noise-curve-ed/index.js","noise-handshake":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/noise-handshake/noise.js","sodium-universal":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/adaptive-timeout/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/adaptive-timeout/package.json","xache":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/xache/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/adaptive-timeout/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-abort/binding.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-abort/package.json",".":"linked:libbare-abort.2.0.13.so"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-abort/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-abort/package.json","./binding":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-abort/binding.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-abort/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-ansi-escapes/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-ansi-escapes/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-ansi-escapes/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-assert/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-assert/package.json","bare-inspect":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-inspect/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-assert/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-dns/binding.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-dns/package.json",".":"linked:libbare-dns.2.1.4.so"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-dns/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-dns/package.json","./binding":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-dns/binding.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-dns/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-env/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-env/package.json","bare-os":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-os/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-env/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-events/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-events/package.json","./lib/errors":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-events/lib/errors.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-events/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-events/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-events/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-fs/binding.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-fs/package.json",".":"linked:libbare-fs.4.7.2.so"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-fs/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-fs/package.json","./binding":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-fs/binding.js","./lib/constants":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-fs/lib/constants.js","./lib/errors":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-fs/lib/errors.js","./promises":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-fs/promises.js","bare-events":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-events/index.js","bare-path":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-path/index.js","bare-stream":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-stream/index.js","bare-url":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-url/index.js","fast-fifo":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/fast-fifo/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-fs/lib/constants.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-fs/package.json","../binding":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-fs/binding.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-fs/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-fs/package.json","bare-os":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-os/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-fs/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-fs/promises.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-fs/package.json",".":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-fs/index.js","bare-events":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-events/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-hrtime/binding.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-hrtime/package.json",".":"linked:libbare-hrtime.2.1.1.so"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-hrtime/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-hrtime/package.json","./binding":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-hrtime/binding.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-hrtime/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http-parser/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http-parser/package.json","./lib/errors":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http-parser/lib/errors.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http-parser/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http-parser/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http-parser/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http1/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http1/package.json","./lib/agent":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http1/lib/agent.js","./lib/client-connection":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http1/lib/client-connection.js","./lib/client-request":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http1/lib/client-request.js","./lib/constants":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http1/lib/constants.js","./lib/errors":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http1/lib/errors.js","./lib/incoming-message":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http1/lib/incoming-message.js","./lib/outgoing-message":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http1/lib/outgoing-message.js","./lib/server":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http1/lib/server.js","./lib/server-connection":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http1/lib/server-connection.js","./lib/server-response":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http1/lib/server-response.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http1/lib/agent.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http1/package.json","./client-connection":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http1/lib/client-connection.js","./errors":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http1/lib/errors.js","bare-events":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-events/index.js","bare-tcp":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-tcp/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http1/lib/client-connection.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http1/package.json","./errors":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http1/lib/errors.js","./incoming-message":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http1/lib/incoming-message.js","bare-http-parser":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http-parser/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http1/lib/client-request.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http1/package.json","./agent":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http1/lib/agent.js","./outgoing-message":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http1/lib/outgoing-message.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http1/lib/constants.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http1/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http1/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http1/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http1/lib/incoming-message.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http1/package.json","bare-stream":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-stream/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http1/lib/outgoing-message.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http1/package.json","./errors":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http1/lib/errors.js","bare-stream":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-stream/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http1/lib/server-connection.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http1/package.json","./incoming-message":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http1/lib/incoming-message.js","./server-response":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http1/lib/server-response.js","bare-http-parser":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http-parser/index.js","bare-stream":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-stream/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http1/lib/server-response.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http1/package.json","./constants":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http1/lib/constants.js","./outgoing-message":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http1/lib/outgoing-message.js","bare-stream":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-stream/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http1/lib/server.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http1/package.json","./server-connection":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http1/lib/server-connection.js","bare-tcp":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-tcp/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http1/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-inspect/binding.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-inspect/package.json",".":"linked:libbare-inspect.3.1.4.so"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-inspect/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-inspect/package.json","./binding":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-inspect/binding.js","bare-ansi-escapes":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-ansi-escapes/index.js","bare-type":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-type/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-inspect/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-net/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-net/package.json","bare-events":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-events/index.js","bare-pipe":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/index.js","bare-stream":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-stream/index.js","bare-tcp":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-dns/binding.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-dns/package.json",".":"linked:libbare-dns.1.0.5.so"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-dns/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-dns/package.json","./binding":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-dns/binding.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-dns/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/binding.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/package.json",".":"linked:libbare-pipe.3.3.8.so"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/package.json","./binding":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/binding.js","./lib/constants":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/lib/constants.js","./lib/errors":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/lib/errors.js","bare-events":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-events/index.js","bare-stream":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-stream/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/lib/constants.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/binding.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/package.json",".":"linked:libbare-tcp.1.9.1.so"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/package.json","./binding":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/binding.js","./lib/constants":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/lib/constants.js","./lib/errors":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/lib/errors.js","./lib/ip":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/lib/ip.js","bare-dns":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-dns/index.js","bare-events":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-events/index.js","bare-stream":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-stream/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/lib/constants.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/lib/ip.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-net/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-os/binding.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-os/package.json",".":"linked:libbare-os.3.9.1.so"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-os/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-os/package.json","./binding":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-os/binding.js","./lib/constants":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-os/lib/constants.js","./lib/errors":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-os/lib/errors.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-os/lib/constants.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-os/package.json","../binding":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-os/binding.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-os/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-os/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-os/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-path/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-path/package.json","./lib/posix":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-path/lib/posix.js","./lib/win32":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-path/lib/win32.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-path/lib/constants.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-path/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-path/lib/posix.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-path/package.json","./constants":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-path/lib/constants.js","./shared":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-path/lib/shared.js","./win32":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-path/lib/win32.js","bare-os":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-os/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-path/lib/shared.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-path/package.json","./constants":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-path/lib/constants.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-path/lib/win32.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-path/package.json","./constants":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-path/lib/constants.js","./posix":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-path/lib/posix.js","./shared":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-path/lib/shared.js","bare-os":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-os/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-path/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-pipe/binding.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-pipe/package.json",".":"linked:libbare-pipe.4.1.5.so"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-pipe/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-pipe/package.json","./binding":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-pipe/binding.js","./lib/constants":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-pipe/lib/constants.js","./lib/errors":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-pipe/lib/errors.js","bare-events":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-events/index.js","bare-stream":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-stream/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-pipe/lib/constants.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-pipe/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-pipe/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-pipe/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-pipe/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-process/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-process/package.json","bare-abort":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-abort/index.js","bare-env":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-env/index.js","bare-events":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-events/index.js","bare-hrtime":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-hrtime/index.js","bare-os":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-os/index.js","bare-signals":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-signals/index.js","bare-stdio":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-stdio/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-process/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-signals/binding.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-signals/package.json",".":"linked:libbare-signals.4.2.0.so"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-signals/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-signals/package.json","./binding":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-signals/binding.js","./lib/emitter":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-signals/lib/emitter.js","./lib/errors":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-signals/lib/errors.js","bare-events":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-events/index.js","bare-os":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-os/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-signals/lib/emitter.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-signals/package.json","..":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-signals/index.js","bare-events":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-events/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-signals/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-signals/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-signals/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-stdio/binding.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-stdio/package.json",".":"linked:libbare-stdio.1.0.2.so"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-stdio/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-stdio/package.json","./binding":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-stdio/binding.js","bare-fs":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-fs/index.js","bare-pipe":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-pipe/index.js","bare-tty":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-tty/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-stdio/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-stream/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-stream/package.json","./web":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-stream/web.js","streamx":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/streamx/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-stream/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-stream/web.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-stream/package.json","streamx":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/streamx/index.js","teex":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/teex/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-tcp/binding.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-tcp/package.json",".":"linked:libbare-tcp.2.2.12.so"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-tcp/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-tcp/package.json","./binding":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-tcp/binding.js","./lib/constants":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-tcp/lib/constants.js","./lib/errors":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-tcp/lib/errors.js","./lib/ip":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-tcp/lib/ip.js","bare-dns":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-dns/index.js","bare-events":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-events/index.js","bare-stream":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-stream/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-tcp/lib/constants.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-tcp/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-tcp/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-tcp/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-tcp/lib/ip.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-tcp/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-tcp/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-tty/binding.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-tty/package.json",".":"linked:libbare-tty.5.1.0.so"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-tty/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-tty/package.json","./binding":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-tty/binding.js","./lib/constants":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-tty/lib/constants.js","bare-signals":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-signals/index.js","bare-stream":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-stream/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-tty/lib/constants.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-tty/package.json","../binding":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-tty/binding.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-tty/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-type/binding.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-type/package.json",".":"linked:libbare-type.1.1.0.so"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-type/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-type/package.json","./binding":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-type/binding.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-type/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-url/binding.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-url/package.json",".":"linked:libbare-url.2.4.2.so"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-url/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-url/package.json","./binding":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-url/binding.js","./lib/errors":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-url/lib/errors.js","./lib/url-search-params":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-url/lib/url-search-params.js","bare-path":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-path/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-url/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-url/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-url/lib/url-search-params.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-url/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-url/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bits-to-bytes/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bits-to-bytes/package.json","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bits-to-bytes/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/blind-relay/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/blind-relay/package.json","./lib/errors":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/blind-relay/lib/errors.js","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js","bits-to-bytes":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bits-to-bytes/index.js","compact-encoding":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/index.js","compact-encoding-bitfield":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/index.js","events":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-events/index.js","protomux":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/protomux/index.js","sodium-universal":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/sodium-universal/index.js","streamx":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/streamx/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/blind-relay/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/blind-relay/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/raw.js","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/endian.js","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/blind-relay/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bogon/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bogon/package.json","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/index.js","compact-encoding-net":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding-net/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/raw.js","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/endian.js","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bogon/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/package.json","compact-encoding":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/raw.js","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/endian.js","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding-net/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding-net/package.json","compact-encoding":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/raw.js","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/endian.js","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding-net/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding/raw.js","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding/endian.js","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/dht-rpc/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/dht-rpc/package.json","./lib/commands":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/dht-rpc/lib/commands.js","./lib/errors":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/dht-rpc/lib/errors.js","./lib/health":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/dht-rpc/lib/health.js","./lib/io":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/dht-rpc/lib/io.js","./lib/peer":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/dht-rpc/lib/peer.js","./lib/query":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/dht-rpc/lib/query.js","./lib/session":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/dht-rpc/lib/session.js","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/index.js","events":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-events/index.js","kademlia-routing-table":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/kademlia-routing-table/index.js","nat-sampler":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/nat-sampler/index.js","sodium-universal":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/sodium-universal/index.js","time-ordered-set":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/time-ordered-set/index.js","udx-native":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/udx-native/lib/udx.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/dht-rpc/lib/commands.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/dht-rpc/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/dht-rpc/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/dht-rpc/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/dht-rpc/lib/health.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/dht-rpc/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/dht-rpc/lib/io.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/dht-rpc/package.json","./errors":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/dht-rpc/lib/errors.js","./peer":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/dht-rpc/lib/peer.js","adaptive-timeout":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/adaptive-timeout/index.js","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/index.js","fast-fifo":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/fast-fifo/index.js","sodium-universal":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/dht-rpc/lib/peer.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/dht-rpc/package.json","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/index.js","compact-encoding-net":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding-net/index.js","sodium-universal":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/dht-rpc/lib/query.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/dht-rpc/package.json","./commands":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/dht-rpc/lib/commands.js","./peer":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/dht-rpc/lib/peer.js","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js","streamx":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/streamx/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/dht-rpc/lib/session.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/dht-rpc/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/raw.js","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/endian.js","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/dht-rpc/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/events-universal/bare.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/events-universal/package.json","bare-events":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-events/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/events-universal/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/fast-fifo/fixed-size.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/fast-fifo/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/fast-fifo/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/fast-fifo/package.json","./fixed-size":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/fast-fifo/fixed-size.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/fast-fifo/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hypercore-crypto/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hypercore-crypto/package.json","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/index.js","sodium-universal":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/raw.js","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/endian.js","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hypercore-crypto/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hypercore-id-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hypercore-id-encoding/package.json","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js","z32":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/z32/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hypercore-id-encoding/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht-address/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht-address/package.json","./spec/hyperschema":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht-address/spec/hyperschema/index.js","compact-encoding":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/raw.js","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/endian.js","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht-address/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht-address/spec/hyperschema/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht-address/package.json","hyperschema/runtime":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperschema/runtime.cjs"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/package.json","./lib/connect":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/connect.js","./lib/connection-pool":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/connection-pool.js","./lib/constants":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/constants.js","./lib/crypto":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/crypto.js","./lib/errors":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/errors.js","./lib/messages":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/messages.js","./lib/persistent":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/persistent.js","./lib/raw-stream-set":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/raw-stream-set.js","./lib/router":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/router.js","./lib/server":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/server.js","./lib/socket-pool":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/socket-pool.js","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/index.js","dht-rpc":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/dht-rpc/index.js","safety-catch":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/safety-catch/index.js","sodium-universal":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/sodium-universal/index.js","xache":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/xache/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/announcer.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/package.json","./constants":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/constants.js","./encode":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/encode.js","./messages":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/messages.js","./persistent":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/persistent.js","./sleeper":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/sleeper.js","compact-encoding":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/index.js","safety-catch":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/safety-catch/index.js","signal-promise":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/signal-promise/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/connect.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/package.json","./constants":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/constants.js","./crypto":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/crypto.js","./errors":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/errors.js","./holepuncher":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/holepuncher.js","./noise-wrap":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/noise-wrap.js","./secure-payload":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/secure-payload.js","./semaphore":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/semaphore.js","./sleeper":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/sleeper.js","@hyperswarm/secret-stream":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/index.js","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js","blind-relay":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/blind-relay/index.js","bogon":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bogon/index.js","hypercore-id-encoding":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hypercore-id-encoding/index.js","hyperdht-address":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht-address/index.js","safety-catch":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/safety-catch/index.js","unslab":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/unslab/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/connection-pool.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/package.json","./errors":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/errors.js","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js","events":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-events/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/constants.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/package.json","hypercore-crypto":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hypercore-crypto/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/crypto.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/package.json","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js","sodium-universal":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/encode.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/package.json","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/holepuncher.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/package.json","./constants":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/constants.js","./nat":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/nat.js","./sleeper":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/sleeper.js","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/messages.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/package.json","compact-encoding":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/nat.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/package.json","../lib/constants":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/constants.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/noise-wrap.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/package.json","./constants":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/constants.js","./errors":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/errors.js","./messages":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/messages.js","@hyperswarm/secret-stream":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/index.js","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/index.js","noise-curve-ed":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/noise-curve-ed/index.js","noise-handshake":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/noise-handshake/noise.js","sodium-universal":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/persistent.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/package.json","./constants":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/constants.js","./encode":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/encode.js","./messages":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/messages.js","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/index.js","record-cache":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/record-cache/index.js","sodium-universal":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/sodium-universal/index.js","unslab":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/unslab/index.js","xache":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/xache/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/raw-stream-set.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/router.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/package.json","./constants":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/constants.js","./errors":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/errors.js","./messages":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/messages.js","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/index.js","safety-catch":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/safety-catch/index.js","xache":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/xache/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/secure-payload.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/package.json","./messages":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/messages.js","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js","sodium-universal":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/semaphore.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/server.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/package.json","./announcer":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/announcer.js","./constants":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/constants.js","./crypto":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/crypto.js","./errors":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/errors.js","./holepuncher":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/holepuncher.js","./noise-wrap":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/noise-wrap.js","./secure-payload":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/secure-payload.js","@hyperswarm/secret-stream":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/index.js","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js","blind-relay":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/blind-relay/index.js","bogon":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bogon/index.js","events":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-events/index.js","safety-catch":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/safety-catch/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/sleeper.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/socket-pool.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/package.json","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/raw.js","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/endian.js","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/raw.js","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/endian.js","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperschema/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperschema/runtime.cjs":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperschema/package.json","compact-encoding":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperswarm/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperswarm/package.json","./lib/connection-set":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperswarm/lib/connection-set.js","./lib/peer-discovery":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperswarm/lib/peer-discovery.js","./lib/peer-info":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperswarm/lib/peer-info.js","./lib/retry-timer":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperswarm/lib/retry-timer.js","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js","events":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-events/index.js","hyperdht":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/index.js","shuffled-priority-queue":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/shuffled-priority-queue/index.js","streamx":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/streamx/index.js","unslab":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/unslab/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperswarm/lib/bulk-timer.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperswarm/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperswarm/lib/connection-set.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperswarm/package.json","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperswarm/lib/peer-discovery.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperswarm/package.json","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js","safety-catch":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/safety-catch/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperswarm/lib/peer-info.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperswarm/package.json","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js","events":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-events/index.js","unslab":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/unslab/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperswarm/lib/retry-timer.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperswarm/package.json","./bulk-timer":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperswarm/lib/bulk-timer.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperswarm/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/kademlia-routing-table/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/kademlia-routing-table/package.json","events":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-events/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/kademlia-routing-table/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/nanoassert/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/nanoassert/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/nanoassert/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/nat-sampler/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/nat-sampler/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/nat-sampler/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/noise-curve-ed/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/noise-curve-ed/package.json","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js","nanoassert":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/nanoassert/index.js","sodium-universal":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/noise-curve-ed/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/noise-handshake/cipher.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/noise-handshake/package.json","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js","sodium-universal":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/noise-handshake/dh.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/noise-handshake/package.json","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js","nanoassert":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/nanoassert/index.js","sodium-universal":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/noise-handshake/hkdf.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/noise-handshake/package.json","./hmac":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/noise-handshake/hmac.js","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/noise-handshake/hmac.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/noise-handshake/package.json","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js","sodium-universal":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/noise-handshake/noise.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/noise-handshake/package.json","./hkdf":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/noise-handshake/hkdf.js","./symmetric-state":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/noise-handshake/symmetric-state.js","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js","nanoassert":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/nanoassert/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/noise-handshake/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/noise-handshake/symmetric-state.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/noise-handshake/package.json","./cipher":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/noise-handshake/cipher.js","./dh":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/noise-handshake/dh.js","./hkdf":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/noise-handshake/hkdf.js","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js","nanoassert":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/nanoassert/index.js","sodium-universal":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/protomux/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/protomux/package.json","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding/index.js","queue-tick":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/queue-tick/process-next-tick.js","safety-catch":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/safety-catch/index.js","unslab":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/unslab/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/protomux/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/queue-tick/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/queue-tick/process-next-tick.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/queue-tick/package.json","./queue-microtask":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/queue-tick/queue-microtask.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/queue-tick/queue-microtask.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/queue-tick/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/ready-resource/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/ready-resource/package.json","events":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-events/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/ready-resource/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/record-cache/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/record-cache/package.json","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/record-cache/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/require-addon/lib/bare.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/require-addon/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/require-addon/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/safety-catch/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/safety-catch/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/safety-catch/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/shuffled-priority-queue/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/shuffled-priority-queue/package.json","unordered-set":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/unordered-set/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/shuffled-priority-queue/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/signal-promise/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/signal-promise/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/signal-promise/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/sodium-native/binding.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/sodium-native/package.json",".":"linked:libsodium-native.5.1.0.so","require-addon":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/require-addon/lib/bare.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/sodium-native/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/sodium-native/package.json","./binding":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/sodium-native/binding.js","assert":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-assert/index.js","which-runtime":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/which-runtime/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/sodium-native/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/sodium-secretstream/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/sodium-secretstream/package.json","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js","sodium-universal":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/sodium-secretstream/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/sodium-universal/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/sodium-universal/package.json","sodium-native":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/sodium-native/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/sodium-universal/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/streamx/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/streamx/package.json","events-universal":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/events-universal/bare.js","fast-fifo":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/fast-fifo/index.js","text-decoder":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/text-decoder/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/streamx/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/teex/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/teex/package.json","streamx":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/streamx/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/teex/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/text-decoder/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/text-decoder/package.json","./lib/pass-through-decoder":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/text-decoder/lib/pass-through-decoder.js","./lib/utf8-decoder":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/text-decoder/lib/utf8-decoder.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/text-decoder/lib/pass-through-decoder.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/text-decoder/package.json","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/text-decoder/lib/utf8-decoder.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/text-decoder/package.json","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/text-decoder/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/time-ordered-set/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/time-ordered-set/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/time-ordered-set/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/timeout-refresh/browser.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/timeout-refresh/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/timeout-refresh/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/timeout-refresh/package.json","./browser":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/timeout-refresh/browser.js","./node":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/timeout-refresh/node.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/timeout-refresh/node.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/timeout-refresh/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/timeout-refresh/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/udx-native/binding.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/udx-native/package.json",".":"linked:libudx-native.1.19.2.so","require-addon":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/require-addon/lib/bare.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/udx-native/lib/ip.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/udx-native/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/udx-native/lib/network-interfaces.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/udx-native/package.json","../binding":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/udx-native/binding.js","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js","events":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-events/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/udx-native/lib/socket.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/udx-native/package.json","../binding":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/udx-native/binding.js","./ip":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/udx-native/lib/ip.js","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js","events":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-events/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/udx-native/lib/stream.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/udx-native/package.json","../binding":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/udx-native/binding.js","./ip":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/udx-native/lib/ip.js","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js","streamx":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/streamx/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/udx-native/lib/udx.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/udx-native/package.json","../binding":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/udx-native/binding.js","./ip":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/udx-native/lib/ip.js","./network-interfaces":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/udx-native/lib/network-interfaces.js","./socket":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/udx-native/lib/socket.js","./stream":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/udx-native/lib/stream.js","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/udx-native/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/unordered-set/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/unordered-set/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/unordered-set/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/unslab/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/unslab/package.json","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/unslab/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/which-runtime/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/which-runtime/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/which-runtime/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/xache/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/xache/package.json"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/xache/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/z32/index.js":{"#package":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/z32/package.json","b4a":"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/z32/package.json":{},"/node_modules/favela-web/node_modules/hyper-svc/package.json":{},"/node_modules/favela-web/node_modules/hyperbee/index.js":{"#package":"/node_modules/favela-web/node_modules/hyperbee/package.json","./iterators/diff":"/node_modules/favela-web/node_modules/hyperbee/iterators/diff.js","./iterators/history":"/node_modules/favela-web/node_modules/hyperbee/iterators/history.js","./iterators/local":"/node_modules/favela-web/node_modules/hyperbee/iterators/local.js","./iterators/range":"/node_modules/favela-web/node_modules/hyperbee/iterators/range.js","./lib/extension":"/node_modules/favela-web/node_modules/hyperbee/lib/extension.js","./lib/messages":"/node_modules/favela-web/node_modules/hyperbee/lib/messages.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","codecs":"/node_modules/favela-web/node_modules/codecs/index.js","debounceify":"/node_modules/favela-web/node_modules/debounceify/index.js","hypercore-errors":"/node_modules/favela-web/node_modules/hypercore-errors/index.js","mutexify/promise":"/node_modules/favela-web/node_modules/mutexify/promise.js","rache":"/node_modules/favela-web/node_modules/rache/index.js","ready-resource":"/node_modules/favela-web/node_modules/ready-resource/index.js","resolve-reject-promise":"/node_modules/favela-web/node_modules/resolve-reject-promise/index.js","safety-catch":"/node_modules/favela-web/node_modules/safety-catch/index.js","streamx":"/node_modules/favela-web/node_modules/streamx/index.js","unslab":"/node_modules/favela-web/node_modules/unslab/index.js"},"/node_modules/favela-web/node_modules/hyperbee/iterators/diff.js":{"#package":"/node_modules/favela-web/node_modules/hyperbee/package.json","b4a":"/node_modules/favela-web/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyperbee/iterators/history.js":{"#package":"/node_modules/favela-web/node_modules/hyperbee/package.json"},"/node_modules/favela-web/node_modules/hyperbee/iterators/local.js":{"#package":"/node_modules/favela-web/node_modules/hyperbee/package.json"},"/node_modules/favela-web/node_modules/hyperbee/iterators/range.js":{"#package":"/node_modules/favela-web/node_modules/hyperbee/package.json","b4a":"/node_modules/favela-web/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyperbee/lib/extension.js":{"#package":"/node_modules/favela-web/node_modules/hyperbee/package.json","./messages":"/node_modules/favela-web/node_modules/hyperbee/lib/messages.js"},"/node_modules/favela-web/node_modules/hyperbee/lib/messages.js":{"#package":"/node_modules/favela-web/node_modules/hyperbee/package.json","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","protocol-buffers-encodings":"/node_modules/favela-web/node_modules/protocol-buffers-encodings/index.js"},"/node_modules/favela-web/node_modules/hyperbee/package.json":{},"/node_modules/favela-web/node_modules/hypercore-crypto/index.js":{"#package":"/node_modules/favela-web/node_modules/hypercore-crypto/package.json","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/hypercore-crypto/node_modules/compact-encoding/index.js","sodium-universal":"/node_modules/favela-web/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/hypercore-crypto/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/favela-web/node_modules/hypercore-crypto/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/hypercore-crypto/node_modules/compact-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/hypercore-crypto/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/hypercore-crypto/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/favela-web/node_modules/hypercore-crypto/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/favela-web/node_modules/hypercore-crypto/node_modules/compact-encoding/raw.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hypercore-crypto/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/favela-web/node_modules/hypercore-crypto/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/hypercore-crypto/node_modules/compact-encoding/package.json":{},"/node_modules/favela-web/node_modules/hypercore-crypto/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/favela-web/node_modules/hypercore-crypto/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/hypercore-crypto/node_modules/compact-encoding/endian.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hypercore-crypto/package.json":{},"/node_modules/favela-web/node_modules/hypercore-errors/index.js":{"#package":"/node_modules/favela-web/node_modules/hypercore-errors/package.json","hypercore-id-encoding":"/node_modules/favela-web/node_modules/hypercore-id-encoding/index.js"},"/node_modules/favela-web/node_modules/hypercore-errors/package.json":{},"/node_modules/favela-web/node_modules/hypercore-id-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/hypercore-id-encoding/package.json","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","z32":"/node_modules/favela-web/node_modules/z32/index.js"},"/node_modules/favela-web/node_modules/hypercore-id-encoding/package.json":{},"/node_modules/favela-web/node_modules/hypercore-storage/encoding/external.js":{"#package":"/node_modules/favela-web/node_modules/hypercore-storage/package.json"},"/node_modules/favela-web/node_modules/hypercore-storage/encoding/spec/hyperschema/index.js":{"#package":"/node_modules/favela-web/node_modules/hypercore-storage/package.json","../../external.js":"/node_modules/favela-web/node_modules/hypercore-storage/encoding/external.js","hyperschema/runtime":"/node_modules/favela-web/node_modules/hyperschema/runtime.cjs"},"/node_modules/favela-web/node_modules/hypercore-storage/index.js":{"#package":"/node_modules/favela-web/node_modules/hypercore-storage/package.json","./lib/keys.js":"/node_modules/favela-web/node_modules/hypercore-storage/lib/keys.js","./lib/streams.js":"/node_modules/favela-web/node_modules/hypercore-storage/lib/streams.js","./lib/tx.js":"/node_modules/favela-web/node_modules/hypercore-storage/lib/tx.js","./lib/view.js":"/node_modules/favela-web/node_modules/hypercore-storage/lib/view.js","./migrations/0":"/node_modules/favela-web/node_modules/hypercore-storage/migrations/0/index.js","./migrations/1":"/node_modules/favela-web/node_modules/hypercore-storage/migrations/1/index.js","device-file":"/node_modules/favela-web/node_modules/device-file/index.js","fs":"/node_modules/favela-web/node_modules/bare-fs/index.js","path":"/node_modules/favela-web/node_modules/bare-path/index.js","resolve-reject-promise":"/node_modules/favela-web/node_modules/resolve-reject-promise/index.js","rocksdb-native":"/node_modules/favela-web/node_modules/rocksdb-native/index.js","scope-lock":"/node_modules/favela-web/node_modules/scope-lock/index.js","xache":"/node_modules/favela-web/node_modules/xache/index.js"},"/node_modules/favela-web/node_modules/hypercore-storage/lib/block-dependency-stream.js":{"#package":"/node_modules/favela-web/node_modules/hypercore-storage/package.json","./keys":"/node_modules/favela-web/node_modules/hypercore-storage/lib/keys.js","streamx":"/node_modules/favela-web/node_modules/streamx/index.js"},"/node_modules/favela-web/node_modules/hypercore-storage/lib/close-error-stream.js":{"#package":"/node_modules/favela-web/node_modules/hypercore-storage/package.json","streamx":"/node_modules/favela-web/node_modules/streamx/index.js"},"/node_modules/favela-web/node_modules/hypercore-storage/lib/keys.js":{"#package":"/node_modules/favela-web/node_modules/hypercore-storage/package.json","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/hypercore-storage/node_modules/compact-encoding/index.js","index-encoder":"/node_modules/favela-web/node_modules/index-encoder/index.js"},"/node_modules/favela-web/node_modules/hypercore-storage/lib/streams.js":{"#package":"/node_modules/favela-web/node_modules/hypercore-storage/package.json","../encoding/spec/hyperschema":"/node_modules/favela-web/node_modules/hypercore-storage/encoding/spec/hyperschema/index.js","./block-dependency-stream.js":"/node_modules/favela-web/node_modules/hypercore-storage/lib/block-dependency-stream.js","./keys.js":"/node_modules/favela-web/node_modules/hypercore-storage/lib/keys.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hypercore-storage/lib/tx.js":{"#package":"/node_modules/favela-web/node_modules/hypercore-storage/package.json","../encoding/spec/hyperschema":"/node_modules/favela-web/node_modules/hypercore-storage/encoding/spec/hyperschema/index.js","./keys.js":"/node_modules/favela-web/node_modules/hypercore-storage/lib/keys.js","./view.js":"/node_modules/favela-web/node_modules/hypercore-storage/lib/view.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/hypercore-storage/node_modules/compact-encoding/index.js","flat-tree":"/node_modules/favela-web/node_modules/flat-tree/index.js"},"/node_modules/favela-web/node_modules/hypercore-storage/lib/view.js":{"#package":"/node_modules/favela-web/node_modules/hypercore-storage/package.json","./close-error-stream.js":"/node_modules/favela-web/node_modules/hypercore-storage/lib/close-error-stream.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","streamx":"/node_modules/favela-web/node_modules/streamx/index.js"},"/node_modules/favela-web/node_modules/hypercore-storage/migrations/0/index.js":{"#package":"/node_modules/favela-web/node_modules/hypercore-storage/package.json","../../lib/tx.js":"/node_modules/favela-web/node_modules/hypercore-storage/lib/tx.js","../../lib/view.js":"/node_modules/favela-web/node_modules/hypercore-storage/lib/view.js","./messages.js":"/node_modules/favela-web/node_modules/hypercore-storage/migrations/0/messages.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/hypercore-storage/node_modules/compact-encoding/index.js","flat-tree":"/node_modules/favela-web/node_modules/flat-tree/index.js","fs":"/node_modules/favela-web/node_modules/bare-fs/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/hypercore-crypto/index.js","path":"/node_modules/favela-web/node_modules/bare-path/index.js","streamx":"/node_modules/favela-web/node_modules/streamx/index.js"},"/node_modules/favela-web/node_modules/hypercore-storage/migrations/0/messages.js":{"#package":"/node_modules/favela-web/node_modules/hypercore-storage/package.json","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/hypercore-storage/node_modules/compact-encoding/index.js"},"/node_modules/favela-web/node_modules/hypercore-storage/migrations/1/index.js":{"#package":"/node_modules/favela-web/node_modules/hypercore-storage/package.json","../../encoding/spec/hyperschema":"/node_modules/favela-web/node_modules/hypercore-storage/encoding/spec/hyperschema/index.js","../../lib/keys.js":"/node_modules/favela-web/node_modules/hypercore-storage/lib/keys.js","../../lib/tx.js":"/node_modules/favela-web/node_modules/hypercore-storage/lib/tx.js","../../lib/view.js":"/node_modules/favela-web/node_modules/hypercore-storage/lib/view.js","compact-encoding":"/node_modules/favela-web/node_modules/hypercore-storage/node_modules/compact-encoding/index.js"},"/node_modules/favela-web/node_modules/hypercore-storage/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/favela-web/node_modules/hypercore-storage/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/hypercore-storage/node_modules/compact-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/hypercore-storage/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/hypercore-storage/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/favela-web/node_modules/hypercore-storage/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/favela-web/node_modules/hypercore-storage/node_modules/compact-encoding/raw.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hypercore-storage/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/favela-web/node_modules/hypercore-storage/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/hypercore-storage/node_modules/compact-encoding/package.json":{},"/node_modules/favela-web/node_modules/hypercore-storage/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/favela-web/node_modules/hypercore-storage/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/hypercore-storage/node_modules/compact-encoding/endian.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hypercore-storage/package.json":{},"/node_modules/favela-web/node_modules/hypercore/index.js":{"#package":"/node_modules/favela-web/node_modules/hypercore/package.json","./lib/caps":"/node_modules/favela-web/node_modules/hypercore/lib/caps.js","./lib/core":"/node_modules/favela-web/node_modules/hypercore/lib/core.js","./lib/default-encryption":"/node_modules/favela-web/node_modules/hypercore/lib/default-encryption.js","./lib/download":"/node_modules/favela-web/node_modules/hypercore/lib/download.js","./lib/feature-flags":"/node_modules/favela-web/node_modules/hypercore/lib/feature-flags.js","./lib/fully-remote-proof":"/node_modules/favela-web/node_modules/hypercore/lib/fully-remote-proof.js","./lib/info":"/node_modules/favela-web/node_modules/hypercore/lib/info.js","./lib/inspect":"/node_modules/favela-web/node_modules/hypercore/lib/inspect.js","./lib/mark-bitfield":"/node_modules/favela-web/node_modules/hypercore/lib/mark-bitfield.js","./lib/merkle-tree":"/node_modules/favela-web/node_modules/hypercore/lib/merkle-tree.js","./lib/replicator":"/node_modules/favela-web/node_modules/hypercore/lib/replicator.js","./lib/streams":"/node_modules/favela-web/node_modules/hypercore/lib/streams.js","./lib/verifier":"/node_modules/favela-web/node_modules/hypercore/lib/verifier.js","./lib/wants":"/node_modules/favela-web/node_modules/hypercore/lib/wants.js","@hyperswarm/secret-stream":"/node_modules/favela-web/node_modules/@hyperswarm/secret-stream/index.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/hypercore/node_modules/compact-encoding/index.js","events":"/node_modules/favela-web/node_modules/bare-events/index.js","flat-tree":"/node_modules/favela-web/node_modules/flat-tree/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/hypercore-crypto/index.js","hypercore-errors":"/node_modules/favela-web/node_modules/hypercore-errors/index.js","hypercore-id-encoding":"/node_modules/favela-web/node_modules/hypercore-id-encoding/index.js","hypercore-storage":"/node_modules/favela-web/node_modules/hypercore-storage/index.js","is-options":"/node_modules/favela-web/node_modules/is-options/index.js","nanoassert":"/node_modules/favela-web/node_modules/nanoassert/index.js","protomux":"/node_modules/favela-web/node_modules/protomux/index.js","safety-catch":"/node_modules/favela-web/node_modules/safety-catch/index.js","unslab":"/node_modules/favela-web/node_modules/unslab/index.js"},"/node_modules/favela-web/node_modules/hypercore/lib/audit.js":{"#package":"/node_modules/favela-web/node_modules/hypercore/package.json","./merkle-tree":"/node_modules/favela-web/node_modules/hypercore/lib/merkle-tree.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","flat-tree":"/node_modules/favela-web/node_modules/flat-tree/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/hypercore-crypto/index.js"},"/node_modules/favela-web/node_modules/hypercore/lib/bit-interlude.js":{"#package":"/node_modules/favela-web/node_modules/hypercore/package.json","./compat":"/node_modules/favela-web/node_modules/hypercore/lib/compat.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hypercore/lib/bitfield.js":{"#package":"/node_modules/favela-web/node_modules/hypercore/package.json","./compat":"/node_modules/favela-web/node_modules/hypercore/lib/compat.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","big-sparse-array":"/node_modules/favela-web/node_modules/big-sparse-array/index.js"},"/node_modules/favela-web/node_modules/hypercore/lib/caps.js":{"#package":"/node_modules/favela-web/node_modules/hypercore/package.json","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/hypercore/node_modules/compact-encoding/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/hypercore-crypto/index.js","sodium-universal":"/node_modules/favela-web/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/hypercore/lib/compat.js":{"#package":"/node_modules/favela-web/node_modules/hypercore/package.json","quickbit-universal":"/node_modules/favela-web/node_modules/quickbit-universal/index.js","quickbit-universal/fallback":"/node_modules/favela-web/node_modules/quickbit-universal/fallback.js"},"/node_modules/favela-web/node_modules/hypercore/lib/copy-prologue.js":{"#package":"/node_modules/favela-web/node_modules/hypercore/package.json","./bitfield":"/node_modules/favela-web/node_modules/hypercore/lib/bitfield.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","flat-tree":"/node_modules/favela-web/node_modules/flat-tree/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/hypercore-crypto/index.js","quickbit-universal":"/node_modules/favela-web/node_modules/quickbit-universal/index.js"},"/node_modules/favela-web/node_modules/hypercore/lib/core.js":{"#package":"/node_modules/favela-web/node_modules/hypercore/package.json","./audit":"/node_modules/favela-web/node_modules/hypercore/lib/audit.js","./bit-interlude":"/node_modules/favela-web/node_modules/hypercore/lib/bit-interlude.js","./bitfield":"/node_modules/favela-web/node_modules/hypercore/lib/bitfield.js","./copy-prologue":"/node_modules/favela-web/node_modules/hypercore/lib/copy-prologue.js","./merkle-tree":"/node_modules/favela-web/node_modules/hypercore/lib/merkle-tree.js","./mutex":"/node_modules/favela-web/node_modules/hypercore/lib/mutex.js","./remote-bitfield":"/node_modules/favela-web/node_modules/hypercore/lib/remote-bitfield.js","./replicator":"/node_modules/favela-web/node_modules/hypercore/lib/replicator.js","./session-state":"/node_modules/favela-web/node_modules/hypercore/lib/session-state.js","./verifier":"/node_modules/favela-web/node_modules/hypercore/lib/verifier.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/hypercore-crypto/index.js","hypercore-errors":"/node_modules/favela-web/node_modules/hypercore-errors/index.js","unslab":"/node_modules/favela-web/node_modules/unslab/index.js","z32":"/node_modules/favela-web/node_modules/z32/index.js"},"/node_modules/favela-web/node_modules/hypercore/lib/default-encryption.js":{"#package":"/node_modules/favela-web/node_modules/hypercore/package.json","./caps":"/node_modules/favela-web/node_modules/hypercore/lib/caps.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/hypercore/node_modules/compact-encoding/index.js","sodium-universal":"/node_modules/favela-web/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/hypercore/lib/download.js":{"#package":"/node_modules/favela-web/node_modules/hypercore/package.json"},"/node_modules/favela-web/node_modules/hypercore/lib/feature-flags.js":{"#package":"/node_modules/favela-web/node_modules/hypercore/package.json"},"/node_modules/favela-web/node_modules/hypercore/lib/fully-remote-proof.js":{"#package":"/node_modules/favela-web/node_modules/hypercore/package.json","./merkle-tree.js":"/node_modules/favela-web/node_modules/hypercore/lib/merkle-tree.js","./messages.js":"/node_modules/favela-web/node_modules/hypercore/lib/messages.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/hypercore/node_modules/compact-encoding/index.js","flat-tree":"/node_modules/favela-web/node_modules/flat-tree/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/hypercore-crypto/index.js"},"/node_modules/favela-web/node_modules/hypercore/lib/hotswap-queue.js":{"#package":"/node_modules/favela-web/node_modules/hypercore/package.json"},"/node_modules/favela-web/node_modules/hypercore/lib/info.js":{"#package":"/node_modules/favela-web/node_modules/hypercore/package.json"},"/node_modules/favela-web/node_modules/hypercore/lib/inspect.js":{"#package":"/node_modules/favela-web/node_modules/hypercore/package.json","b4a":"/node_modules/favela-web/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hypercore/lib/mark-bitfield.js":{"#package":"/node_modules/favela-web/node_modules/hypercore/package.json","./compat":"/node_modules/favela-web/node_modules/hypercore/lib/compat.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","big-sparse-array":"/node_modules/favela-web/node_modules/big-sparse-array/index.js","streamx":"/node_modules/favela-web/node_modules/streamx/index.js"},"/node_modules/favela-web/node_modules/hypercore/lib/merkle-tree.js":{"#package":"/node_modules/favela-web/node_modules/hypercore/package.json","./caps":"/node_modules/favela-web/node_modules/hypercore/lib/caps.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","flat-tree":"/node_modules/favela-web/node_modules/flat-tree/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/hypercore-crypto/index.js","hypercore-errors":"/node_modules/favela-web/node_modules/hypercore-errors/index.js","unslab":"/node_modules/favela-web/node_modules/unslab/index.js"},"/node_modules/favela-web/node_modules/hypercore/lib/messages.js":{"#package":"/node_modules/favela-web/node_modules/hypercore/package.json","./caps":"/node_modules/favela-web/node_modules/hypercore/lib/caps.js","compact-encoding":"/node_modules/favela-web/node_modules/hypercore/node_modules/compact-encoding/index.js","hypercore-errors":"/node_modules/favela-web/node_modules/hypercore-errors/index.js","unslab":"/node_modules/favela-web/node_modules/unslab/index.js"},"/node_modules/favela-web/node_modules/hypercore/lib/multisig.js":{"#package":"/node_modules/favela-web/node_modules/hypercore/package.json","./merkle-tree":"/node_modules/favela-web/node_modules/hypercore/lib/merkle-tree.js","./messages":"/node_modules/favela-web/node_modules/hypercore/lib/messages.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/hypercore/node_modules/compact-encoding/index.js","flat-tree":"/node_modules/favela-web/node_modules/flat-tree/index.js"},"/node_modules/favela-web/node_modules/hypercore/lib/mutex.js":{"#package":"/node_modules/favela-web/node_modules/hypercore/package.json"},"/node_modules/favela-web/node_modules/hypercore/lib/receiver-queue.js":{"#package":"/node_modules/favela-web/node_modules/hypercore/package.json","fast-fifo":"/node_modules/favela-web/node_modules/fast-fifo/index.js"},"/node_modules/favela-web/node_modules/hypercore/lib/remote-bitfield.js":{"#package":"/node_modules/favela-web/node_modules/hypercore/package.json","./compat":"/node_modules/favela-web/node_modules/hypercore/lib/compat.js","big-sparse-array":"/node_modules/favela-web/node_modules/big-sparse-array/index.js"},"/node_modules/favela-web/node_modules/hypercore/lib/replicator.js":{"#package":"/node_modules/favela-web/node_modules/hypercore/package.json","./caps":"/node_modules/favela-web/node_modules/hypercore/lib/caps.js","./hotswap-queue":"/node_modules/favela-web/node_modules/hypercore/lib/hotswap-queue.js","./merkle-tree":"/node_modules/favela-web/node_modules/hypercore/lib/merkle-tree.js","./messages":"/node_modules/favela-web/node_modules/hypercore/lib/messages.js","./mutex":"/node_modules/favela-web/node_modules/hypercore/lib/mutex.js","./receiver-queue":"/node_modules/favela-web/node_modules/hypercore/lib/receiver-queue.js","./remote-bitfield":"/node_modules/favela-web/node_modules/hypercore/lib/remote-bitfield.js","./wants":"/node_modules/favela-web/node_modules/hypercore/lib/wants.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","flat-tree":"/node_modules/favela-web/node_modules/flat-tree/index.js","hypercore-errors":"/node_modules/favela-web/node_modules/hypercore-errors/index.js","random-array-iterator":"/node_modules/favela-web/node_modules/random-array-iterator/index.js","safety-catch":"/node_modules/favela-web/node_modules/safety-catch/index.js"},"/node_modules/favela-web/node_modules/hypercore/lib/session-state.js":{"#package":"/node_modules/favela-web/node_modules/hypercore/package.json","./bitfield":"/node_modules/favela-web/node_modules/hypercore/lib/bitfield.js","./merkle-tree":"/node_modules/favela-web/node_modules/hypercore/lib/merkle-tree.js","./mutex":"/node_modules/favela-web/node_modules/hypercore/lib/mutex.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","flat-tree":"/node_modules/favela-web/node_modules/flat-tree/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/hypercore-crypto/index.js","hypercore-errors":"/node_modules/favela-web/node_modules/hypercore-errors/index.js","hypercore-storage":"/node_modules/favela-web/node_modules/hypercore-storage/index.js","nanoassert":"/node_modules/favela-web/node_modules/nanoassert/index.js","quickbit-universal":"/node_modules/favela-web/node_modules/quickbit-universal/index.js"},"/node_modules/favela-web/node_modules/hypercore/lib/streams.js":{"#package":"/node_modules/favela-web/node_modules/hypercore/package.json","streamx":"/node_modules/favela-web/node_modules/streamx/index.js"},"/node_modules/favela-web/node_modules/hypercore/lib/verifier.js":{"#package":"/node_modules/favela-web/node_modules/hypercore/package.json","./caps":"/node_modules/favela-web/node_modules/hypercore/lib/caps.js","./messages":"/node_modules/favela-web/node_modules/hypercore/lib/messages.js","./multisig":"/node_modules/favela-web/node_modules/hypercore/lib/multisig.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/hypercore/node_modules/compact-encoding/index.js","flat-tree":"/node_modules/favela-web/node_modules/flat-tree/index.js","hypercore-crypto":"/node_modules/favela-web/node_modules/hypercore-crypto/index.js","hypercore-errors":"/node_modules/favela-web/node_modules/hypercore-errors/index.js","unslab":"/node_modules/favela-web/node_modules/unslab/index.js"},"/node_modules/favela-web/node_modules/hypercore/lib/wants.js":{"#package":"/node_modules/favela-web/node_modules/hypercore/package.json"},"/node_modules/favela-web/node_modules/hypercore/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/favela-web/node_modules/hypercore/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/hypercore/node_modules/compact-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/hypercore/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/hypercore/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/favela-web/node_modules/hypercore/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/favela-web/node_modules/hypercore/node_modules/compact-encoding/raw.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hypercore/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/favela-web/node_modules/hypercore/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/hypercore/node_modules/compact-encoding/package.json":{},"/node_modules/favela-web/node_modules/hypercore/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/favela-web/node_modules/hypercore/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/hypercore/node_modules/compact-encoding/endian.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hypercore/package.json":{},"/node_modules/favela-web/node_modules/hyperdht-address/index.js":{"#package":"/node_modules/favela-web/node_modules/hyperdht-address/package.json","./spec/hyperschema":"/node_modules/favela-web/node_modules/hyperdht-address/spec/hyperschema/index.js","compact-encoding":"/node_modules/favela-web/node_modules/hyperdht-address/node_modules/compact-encoding/index.js"},"/node_modules/favela-web/node_modules/hyperdht-address/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/favela-web/node_modules/hyperdht-address/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/hyperdht-address/node_modules/compact-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/hyperdht-address/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/hyperdht-address/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/favela-web/node_modules/hyperdht-address/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/favela-web/node_modules/hyperdht-address/node_modules/compact-encoding/raw.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyperdht-address/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/favela-web/node_modules/hyperdht-address/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/hyperdht-address/node_modules/compact-encoding/package.json":{},"/node_modules/favela-web/node_modules/hyperdht-address/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/favela-web/node_modules/hyperdht-address/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/hyperdht-address/node_modules/compact-encoding/endian.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyperdht-address/package.json":{},"/node_modules/favela-web/node_modules/hyperdht-address/spec/hyperschema/index.js":{"#package":"/node_modules/favela-web/node_modules/hyperdht-address/package.json","hyperschema/runtime":"/node_modules/favela-web/node_modules/hyperschema/runtime.cjs"},"/node_modules/favela-web/node_modules/hyperdht/index.js":{"#package":"/node_modules/favela-web/node_modules/hyperdht/package.json","./lib/connect":"/node_modules/favela-web/node_modules/hyperdht/lib/connect.js","./lib/connection-pool":"/node_modules/favela-web/node_modules/hyperdht/lib/connection-pool.js","./lib/constants":"/node_modules/favela-web/node_modules/hyperdht/lib/constants.js","./lib/crypto":"/node_modules/favela-web/node_modules/hyperdht/lib/crypto.js","./lib/errors":"/node_modules/favela-web/node_modules/hyperdht/lib/errors.js","./lib/messages":"/node_modules/favela-web/node_modules/hyperdht/lib/messages.js","./lib/persistent":"/node_modules/favela-web/node_modules/hyperdht/lib/persistent.js","./lib/raw-stream-set":"/node_modules/favela-web/node_modules/hyperdht/lib/raw-stream-set.js","./lib/router":"/node_modules/favela-web/node_modules/hyperdht/lib/router.js","./lib/server":"/node_modules/favela-web/node_modules/hyperdht/lib/server.js","./lib/socket-pool":"/node_modules/favela-web/node_modules/hyperdht/lib/socket-pool.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/hyperdht/node_modules/compact-encoding/index.js","dht-rpc":"/node_modules/favela-web/node_modules/dht-rpc/index.js","safety-catch":"/node_modules/favela-web/node_modules/safety-catch/index.js","sodium-universal":"/node_modules/favela-web/node_modules/sodium-universal/index.js","xache":"/node_modules/favela-web/node_modules/xache/index.js"},"/node_modules/favela-web/node_modules/hyperdht/lib/announcer.js":{"#package":"/node_modules/favela-web/node_modules/hyperdht/package.json","./constants":"/node_modules/favela-web/node_modules/hyperdht/lib/constants.js","./encode":"/node_modules/favela-web/node_modules/hyperdht/lib/encode.js","./messages":"/node_modules/favela-web/node_modules/hyperdht/lib/messages.js","./persistent":"/node_modules/favela-web/node_modules/hyperdht/lib/persistent.js","./sleeper":"/node_modules/favela-web/node_modules/hyperdht/lib/sleeper.js","compact-encoding":"/node_modules/favela-web/node_modules/hyperdht/node_modules/compact-encoding/index.js","safety-catch":"/node_modules/favela-web/node_modules/safety-catch/index.js","signal-promise":"/node_modules/favela-web/node_modules/signal-promise/index.js"},"/node_modules/favela-web/node_modules/hyperdht/lib/connect.js":{"#package":"/node_modules/favela-web/node_modules/hyperdht/package.json","./constants":"/node_modules/favela-web/node_modules/hyperdht/lib/constants.js","./crypto":"/node_modules/favela-web/node_modules/hyperdht/lib/crypto.js","./errors":"/node_modules/favela-web/node_modules/hyperdht/lib/errors.js","./holepuncher":"/node_modules/favela-web/node_modules/hyperdht/lib/holepuncher.js","./noise-wrap":"/node_modules/favela-web/node_modules/hyperdht/lib/noise-wrap.js","./relay-connection":"/node_modules/favela-web/node_modules/hyperdht/lib/relay-connection.js","./secure-payload":"/node_modules/favela-web/node_modules/hyperdht/lib/secure-payload.js","./semaphore":"/node_modules/favela-web/node_modules/hyperdht/lib/semaphore.js","./sleeper":"/node_modules/favela-web/node_modules/hyperdht/lib/sleeper.js","@hyperswarm/secret-stream":"/node_modules/favela-web/node_modules/@hyperswarm/secret-stream/index.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","blind-relay":"/node_modules/favela-web/node_modules/blind-relay/index.js","bogon":"/node_modules/favela-web/node_modules/bogon/index.js","hypercore-id-encoding":"/node_modules/favela-web/node_modules/hypercore-id-encoding/index.js","hyperdht-address":"/node_modules/favela-web/node_modules/hyperdht-address/index.js","safety-catch":"/node_modules/favela-web/node_modules/safety-catch/index.js","unslab":"/node_modules/favela-web/node_modules/unslab/index.js"},"/node_modules/favela-web/node_modules/hyperdht/lib/connection-pool.js":{"#package":"/node_modules/favela-web/node_modules/hyperdht/package.json","./errors":"/node_modules/favela-web/node_modules/hyperdht/lib/errors.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","events":"/node_modules/favela-web/node_modules/bare-events/index.js"},"/node_modules/favela-web/node_modules/hyperdht/lib/constants.js":{"#package":"/node_modules/favela-web/node_modules/hyperdht/package.json","hypercore-crypto":"/node_modules/favela-web/node_modules/hypercore-crypto/index.js"},"/node_modules/favela-web/node_modules/hyperdht/lib/crypto.js":{"#package":"/node_modules/favela-web/node_modules/hyperdht/package.json","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","sodium-universal":"/node_modules/favela-web/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/hyperdht/lib/encode.js":{"#package":"/node_modules/favela-web/node_modules/hyperdht/package.json","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/hyperdht/node_modules/compact-encoding/index.js"},"/node_modules/favela-web/node_modules/hyperdht/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/hyperdht/package.json"},"/node_modules/favela-web/node_modules/hyperdht/lib/holepuncher.js":{"#package":"/node_modules/favela-web/node_modules/hyperdht/package.json","./constants":"/node_modules/favela-web/node_modules/hyperdht/lib/constants.js","./nat":"/node_modules/favela-web/node_modules/hyperdht/lib/nat.js","./sleeper":"/node_modules/favela-web/node_modules/hyperdht/lib/sleeper.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyperdht/lib/messages.js":{"#package":"/node_modules/favela-web/node_modules/hyperdht/package.json","compact-encoding":"/node_modules/favela-web/node_modules/hyperdht/node_modules/compact-encoding/index.js"},"/node_modules/favela-web/node_modules/hyperdht/lib/nat.js":{"#package":"/node_modules/favela-web/node_modules/hyperdht/package.json","../lib/constants":"/node_modules/favela-web/node_modules/hyperdht/lib/constants.js"},"/node_modules/favela-web/node_modules/hyperdht/lib/noise-wrap.js":{"#package":"/node_modules/favela-web/node_modules/hyperdht/package.json","./constants":"/node_modules/favela-web/node_modules/hyperdht/lib/constants.js","./errors":"/node_modules/favela-web/node_modules/hyperdht/lib/errors.js","./messages":"/node_modules/favela-web/node_modules/hyperdht/lib/messages.js","@hyperswarm/secret-stream":"/node_modules/favela-web/node_modules/@hyperswarm/secret-stream/index.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/hyperdht/node_modules/compact-encoding/index.js","noise-curve-ed":"/node_modules/favela-web/node_modules/noise-curve-ed/index.js","noise-handshake":"/node_modules/favela-web/node_modules/noise-handshake/noise.js","sodium-universal":"/node_modules/favela-web/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/hyperdht/lib/persistent.js":{"#package":"/node_modules/favela-web/node_modules/hyperdht/package.json","./constants":"/node_modules/favela-web/node_modules/hyperdht/lib/constants.js","./encode":"/node_modules/favela-web/node_modules/hyperdht/lib/encode.js","./messages":"/node_modules/favela-web/node_modules/hyperdht/lib/messages.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/hyperdht/node_modules/compact-encoding/index.js","record-cache":"/node_modules/favela-web/node_modules/record-cache/index.js","sodium-universal":"/node_modules/favela-web/node_modules/sodium-universal/index.js","unslab":"/node_modules/favela-web/node_modules/unslab/index.js","xache":"/node_modules/favela-web/node_modules/xache/index.js"},"/node_modules/favela-web/node_modules/hyperdht/lib/raw-stream-set.js":{"#package":"/node_modules/favela-web/node_modules/hyperdht/package.json"},"/node_modules/favela-web/node_modules/hyperdht/lib/relay-connection.js":{"#package":"/node_modules/favela-web/node_modules/hyperdht/package.json","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","safety-catch":"/node_modules/favela-web/node_modules/safety-catch/index.js"},"/node_modules/favela-web/node_modules/hyperdht/lib/router.js":{"#package":"/node_modules/favela-web/node_modules/hyperdht/package.json","./constants":"/node_modules/favela-web/node_modules/hyperdht/lib/constants.js","./errors":"/node_modules/favela-web/node_modules/hyperdht/lib/errors.js","./messages":"/node_modules/favela-web/node_modules/hyperdht/lib/messages.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/hyperdht/node_modules/compact-encoding/index.js","safety-catch":"/node_modules/favela-web/node_modules/safety-catch/index.js","xache":"/node_modules/favela-web/node_modules/xache/index.js"},"/node_modules/favela-web/node_modules/hyperdht/lib/secure-payload.js":{"#package":"/node_modules/favela-web/node_modules/hyperdht/package.json","./messages":"/node_modules/favela-web/node_modules/hyperdht/lib/messages.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","sodium-universal":"/node_modules/favela-web/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/hyperdht/lib/semaphore.js":{"#package":"/node_modules/favela-web/node_modules/hyperdht/package.json"},"/node_modules/favela-web/node_modules/hyperdht/lib/server.js":{"#package":"/node_modules/favela-web/node_modules/hyperdht/package.json","./announcer":"/node_modules/favela-web/node_modules/hyperdht/lib/announcer.js","./constants":"/node_modules/favela-web/node_modules/hyperdht/lib/constants.js","./crypto":"/node_modules/favela-web/node_modules/hyperdht/lib/crypto.js","./errors":"/node_modules/favela-web/node_modules/hyperdht/lib/errors.js","./holepuncher":"/node_modules/favela-web/node_modules/hyperdht/lib/holepuncher.js","./noise-wrap":"/node_modules/favela-web/node_modules/hyperdht/lib/noise-wrap.js","./relay-connection":"/node_modules/favela-web/node_modules/hyperdht/lib/relay-connection.js","./secure-payload":"/node_modules/favela-web/node_modules/hyperdht/lib/secure-payload.js","@hyperswarm/secret-stream":"/node_modules/favela-web/node_modules/@hyperswarm/secret-stream/index.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","blind-relay":"/node_modules/favela-web/node_modules/blind-relay/index.js","bogon":"/node_modules/favela-web/node_modules/bogon/index.js","events":"/node_modules/favela-web/node_modules/bare-events/index.js","safety-catch":"/node_modules/favela-web/node_modules/safety-catch/index.js"},"/node_modules/favela-web/node_modules/hyperdht/lib/sleeper.js":{"#package":"/node_modules/favela-web/node_modules/hyperdht/package.json"},"/node_modules/favela-web/node_modules/hyperdht/lib/socket-pool.js":{"#package":"/node_modules/favela-web/node_modules/hyperdht/package.json","b4a":"/node_modules/favela-web/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyperdht/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/favela-web/node_modules/hyperdht/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/hyperdht/node_modules/compact-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/hyperdht/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/hyperdht/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/favela-web/node_modules/hyperdht/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/favela-web/node_modules/hyperdht/node_modules/compact-encoding/raw.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyperdht/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/favela-web/node_modules/hyperdht/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/hyperdht/node_modules/compact-encoding/package.json":{},"/node_modules/favela-web/node_modules/hyperdht/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/favela-web/node_modules/hyperdht/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/hyperdht/node_modules/compact-encoding/endian.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyperdht/package.json":{},"/node_modules/favela-web/node_modules/hyperschema/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/favela-web/node_modules/hyperschema/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/hyperschema/node_modules/compact-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/hyperschema/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/hyperschema/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/favela-web/node_modules/hyperschema/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/favela-web/node_modules/hyperschema/node_modules/compact-encoding/raw.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyperschema/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/favela-web/node_modules/hyperschema/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/hyperschema/node_modules/compact-encoding/package.json":{},"/node_modules/favela-web/node_modules/hyperschema/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/favela-web/node_modules/hyperschema/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/hyperschema/node_modules/compact-encoding/endian.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyperschema/package.json":{},"/node_modules/favela-web/node_modules/hyperschema/runtime.cjs":{"#package":"/node_modules/favela-web/node_modules/hyperschema/package.json","compact-encoding":"/node_modules/favela-web/node_modules/hyperschema/node_modules/compact-encoding/index.js"},"/node_modules/favela-web/node_modules/hyperswarm/index.js":{"#package":"/node_modules/favela-web/node_modules/hyperswarm/package.json","./lib/connection-set":"/node_modules/favela-web/node_modules/hyperswarm/lib/connection-set.js","./lib/peer-discovery":"/node_modules/favela-web/node_modules/hyperswarm/lib/peer-discovery.js","./lib/peer-info":"/node_modules/favela-web/node_modules/hyperswarm/lib/peer-info.js","./lib/retry-timer":"/node_modules/favela-web/node_modules/hyperswarm/lib/retry-timer.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","events":"/node_modules/favela-web/node_modules/bare-events/index.js","hyperdht":"/node_modules/favela-web/node_modules/hyperdht/index.js","shuffled-priority-queue":"/node_modules/favela-web/node_modules/shuffled-priority-queue/index.js","streamx":"/node_modules/favela-web/node_modules/streamx/index.js","unslab":"/node_modules/favela-web/node_modules/unslab/index.js"},"/node_modules/favela-web/node_modules/hyperswarm/lib/bulk-timer.js":{"#package":"/node_modules/favela-web/node_modules/hyperswarm/package.json"},"/node_modules/favela-web/node_modules/hyperswarm/lib/connection-set.js":{"#package":"/node_modules/favela-web/node_modules/hyperswarm/package.json","b4a":"/node_modules/favela-web/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/hyperswarm/lib/peer-discovery.js":{"#package":"/node_modules/favela-web/node_modules/hyperswarm/package.json","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","safety-catch":"/node_modules/favela-web/node_modules/safety-catch/index.js"},"/node_modules/favela-web/node_modules/hyperswarm/lib/peer-info.js":{"#package":"/node_modules/favela-web/node_modules/hyperswarm/package.json","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","events":"/node_modules/favela-web/node_modules/bare-events/index.js","unslab":"/node_modules/favela-web/node_modules/unslab/index.js"},"/node_modules/favela-web/node_modules/hyperswarm/lib/retry-timer.js":{"#package":"/node_modules/favela-web/node_modules/hyperswarm/package.json","./bulk-timer":"/node_modules/favela-web/node_modules/hyperswarm/lib/bulk-timer.js"},"/node_modules/favela-web/node_modules/hyperswarm/package.json":{},"/node_modules/favela-web/node_modules/index-encoder/index.js":{"#package":"/node_modules/favela-web/node_modules/index-encoder/package.json","b4a":"/node_modules/favela-web/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/index-encoder/package.json":{},"/node_modules/favela-web/node_modules/is-options/index.js":{"#package":"/node_modules/favela-web/node_modules/is-options/package.json","b4a":"/node_modules/favela-web/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/is-options/package.json":{},"/node_modules/favela-web/node_modules/kademlia-routing-table/index.js":{"#package":"/node_modules/favela-web/node_modules/kademlia-routing-table/package.json","events":"/node_modules/favela-web/node_modules/bare-events/index.js"},"/node_modules/favela-web/node_modules/kademlia-routing-table/package.json":{},"/node_modules/favela-web/node_modules/multiformats/dist/src/bases/base.js":{"#package":"/node_modules/favela-web/node_modules/multiformats/package.json","../bytes.js":"/node_modules/favela-web/node_modules/multiformats/dist/src/bytes.js","../vendor/base-x.js":"/node_modules/favela-web/node_modules/multiformats/dist/src/vendor/base-x.js"},"/node_modules/favela-web/node_modules/multiformats/dist/src/bases/base32.js":{"#package":"/node_modules/favela-web/node_modules/multiformats/package.json","./base.js":"/node_modules/favela-web/node_modules/multiformats/dist/src/bases/base.js"},"/node_modules/favela-web/node_modules/multiformats/dist/src/bases/base36.js":{"#package":"/node_modules/favela-web/node_modules/multiformats/package.json","./base.js":"/node_modules/favela-web/node_modules/multiformats/dist/src/bases/base.js"},"/node_modules/favela-web/node_modules/multiformats/dist/src/bases/base58.js":{"#package":"/node_modules/favela-web/node_modules/multiformats/package.json","./base.js":"/node_modules/favela-web/node_modules/multiformats/dist/src/bases/base.js"},"/node_modules/favela-web/node_modules/multiformats/dist/src/bytes.js":{"#package":"/node_modules/favela-web/node_modules/multiformats/package.json"},"/node_modules/favela-web/node_modules/multiformats/dist/src/cid.js":{"#package":"/node_modules/favela-web/node_modules/multiformats/package.json","./bases/base32.js":"/node_modules/favela-web/node_modules/multiformats/dist/src/bases/base32.js","./bases/base36.js":"/node_modules/favela-web/node_modules/multiformats/dist/src/bases/base36.js","./bases/base58.js":"/node_modules/favela-web/node_modules/multiformats/dist/src/bases/base58.js","./bytes.js":"/node_modules/favela-web/node_modules/multiformats/dist/src/bytes.js","./hashes/digest.js":"/node_modules/favela-web/node_modules/multiformats/dist/src/hashes/digest.js","./link/interface.js":"/node_modules/favela-web/node_modules/multiformats/dist/src/link/interface.js","./varint.js":"/node_modules/favela-web/node_modules/multiformats/dist/src/varint.js"},"/node_modules/favela-web/node_modules/multiformats/dist/src/hashes/digest.js":{"#package":"/node_modules/favela-web/node_modules/multiformats/package.json","../bytes.js":"/node_modules/favela-web/node_modules/multiformats/dist/src/bytes.js","../varint.js":"/node_modules/favela-web/node_modules/multiformats/dist/src/varint.js"},"/node_modules/favela-web/node_modules/multiformats/dist/src/link/interface.js":{"#package":"/node_modules/favela-web/node_modules/multiformats/package.json"},"/node_modules/favela-web/node_modules/multiformats/dist/src/varint.js":{"#package":"/node_modules/favela-web/node_modules/multiformats/package.json","./vendor/varint.js":"/node_modules/favela-web/node_modules/multiformats/dist/src/vendor/varint.js"},"/node_modules/favela-web/node_modules/multiformats/dist/src/vendor/base-x.js":{"#package":"/node_modules/favela-web/node_modules/multiformats/package.json"},"/node_modules/favela-web/node_modules/multiformats/dist/src/vendor/varint.js":{"#package":"/node_modules/favela-web/node_modules/multiformats/package.json"},"/node_modules/favela-web/node_modules/multiformats/package.json":{},"/node_modules/favela-web/node_modules/mutexify/index.js":{"#package":"/node_modules/favela-web/node_modules/mutexify/package.json","queue-tick":"/node_modules/favela-web/node_modules/queue-tick/process-next-tick.js"},"/node_modules/favela-web/node_modules/mutexify/package.json":{},"/node_modules/favela-web/node_modules/mutexify/promise.js":{"#package":"/node_modules/favela-web/node_modules/mutexify/package.json",".":"/node_modules/favela-web/node_modules/mutexify/index.js"},"/node_modules/favela-web/node_modules/nanoassert/index.js":{"#package":"/node_modules/favela-web/node_modules/nanoassert/package.json"},"/node_modules/favela-web/node_modules/nanoassert/package.json":{},"/node_modules/favela-web/node_modules/nat-sampler/index.js":{"#package":"/node_modules/favela-web/node_modules/nat-sampler/package.json"},"/node_modules/favela-web/node_modules/nat-sampler/package.json":{},"/node_modules/favela-web/node_modules/noise-curve-ed/index.js":{"#package":"/node_modules/favela-web/node_modules/noise-curve-ed/package.json","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","nanoassert":"/node_modules/favela-web/node_modules/nanoassert/index.js","sodium-universal":"/node_modules/favela-web/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/noise-curve-ed/package.json":{},"/node_modules/favela-web/node_modules/noise-handshake/cipher.js":{"#package":"/node_modules/favela-web/node_modules/noise-handshake/package.json","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","sodium-universal":"/node_modules/favela-web/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/noise-handshake/dh.js":{"#package":"/node_modules/favela-web/node_modules/noise-handshake/package.json","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","nanoassert":"/node_modules/favela-web/node_modules/nanoassert/index.js","sodium-universal":"/node_modules/favela-web/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/noise-handshake/hkdf.js":{"#package":"/node_modules/favela-web/node_modules/noise-handshake/package.json","./hmac":"/node_modules/favela-web/node_modules/noise-handshake/hmac.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/noise-handshake/hmac.js":{"#package":"/node_modules/favela-web/node_modules/noise-handshake/package.json","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","sodium-universal":"/node_modules/favela-web/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/noise-handshake/noise.js":{"#package":"/node_modules/favela-web/node_modules/noise-handshake/package.json","./hkdf":"/node_modules/favela-web/node_modules/noise-handshake/hkdf.js","./symmetric-state":"/node_modules/favela-web/node_modules/noise-handshake/symmetric-state.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","nanoassert":"/node_modules/favela-web/node_modules/nanoassert/index.js"},"/node_modules/favela-web/node_modules/noise-handshake/package.json":{},"/node_modules/favela-web/node_modules/noise-handshake/symmetric-state.js":{"#package":"/node_modules/favela-web/node_modules/noise-handshake/package.json","./cipher":"/node_modules/favela-web/node_modules/noise-handshake/cipher.js","./dh":"/node_modules/favela-web/node_modules/noise-handshake/dh.js","./hkdf":"/node_modules/favela-web/node_modules/noise-handshake/hkdf.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","nanoassert":"/node_modules/favela-web/node_modules/nanoassert/index.js","sodium-universal":"/node_modules/favela-web/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/protocol-buffers-encodings/index.js":{"#package":"/node_modules/favela-web/node_modules/protocol-buffers-encodings/package.json","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","signed-varint":"/node_modules/favela-web/node_modules/signed-varint/index.js","varint":"/node_modules/favela-web/node_modules/varint/index.js"},"/node_modules/favela-web/node_modules/protocol-buffers-encodings/package.json":{},"/node_modules/favela-web/node_modules/protomux-rpc/index.js":{"#package":"/node_modules/favela-web/node_modules/protomux-rpc/package.json","./lib/errors":"/node_modules/favela-web/node_modules/protomux-rpc/lib/errors.js","bits-to-bytes":"/node_modules/favela-web/node_modules/bits-to-bytes/index.js","compact-encoding":"/node_modules/favela-web/node_modules/protomux-rpc/node_modules/compact-encoding/index.js","compact-encoding-bitfield":"/node_modules/favela-web/node_modules/compact-encoding-bitfield/index.js","events":"/node_modules/favela-web/node_modules/bare-events/index.js","protomux":"/node_modules/favela-web/node_modules/protomux/index.js","safety-catch":"/node_modules/favela-web/node_modules/safety-catch/index.js"},"/node_modules/favela-web/node_modules/protomux-rpc/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/protomux-rpc/package.json"},"/node_modules/favela-web/node_modules/protomux-rpc/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/favela-web/node_modules/protomux-rpc/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/protomux-rpc/node_modules/compact-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/protomux-rpc/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/protomux-rpc/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/favela-web/node_modules/protomux-rpc/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/favela-web/node_modules/protomux-rpc/node_modules/compact-encoding/raw.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/protomux-rpc/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/favela-web/node_modules/protomux-rpc/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/protomux-rpc/node_modules/compact-encoding/package.json":{},"/node_modules/favela-web/node_modules/protomux-rpc/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/favela-web/node_modules/protomux-rpc/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/protomux-rpc/node_modules/compact-encoding/endian.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/protomux-rpc/package.json":{},"/node_modules/favela-web/node_modules/protomux/index.js":{"#package":"/node_modules/favela-web/node_modules/protomux/package.json","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","compact-encoding":"/node_modules/favela-web/node_modules/protomux/node_modules/compact-encoding/index.js","queue-tick":"/node_modules/favela-web/node_modules/queue-tick/process-next-tick.js","safety-catch":"/node_modules/favela-web/node_modules/safety-catch/index.js","unslab":"/node_modules/favela-web/node_modules/unslab/index.js"},"/node_modules/favela-web/node_modules/protomux/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/favela-web/node_modules/protomux/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/protomux/node_modules/compact-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/protomux/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/protomux/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/favela-web/node_modules/protomux/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/favela-web/node_modules/protomux/node_modules/compact-encoding/raw.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/protomux/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/favela-web/node_modules/protomux/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/protomux/node_modules/compact-encoding/package.json":{},"/node_modules/favela-web/node_modules/protomux/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/favela-web/node_modules/protomux/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/protomux/node_modules/compact-encoding/endian.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/protomux/package.json":{},"/node_modules/favela-web/node_modules/queue-tick/package.json":{},"/node_modules/favela-web/node_modules/queue-tick/process-next-tick.js":{"#package":"/node_modules/favela-web/node_modules/queue-tick/package.json","./queue-microtask":"/node_modules/favela-web/node_modules/queue-tick/queue-microtask.js"},"/node_modules/favela-web/node_modules/queue-tick/queue-microtask.js":{"#package":"/node_modules/favela-web/node_modules/queue-tick/package.json"},"/node_modules/favela-web/node_modules/quickbit-native/binding.js":{"#package":"/node_modules/favela-web/node_modules/quickbit-native/package.json",".":"linked:libquickbit-native.2.4.8.so","require-addon":"/node_modules/favela-web/node_modules/require-addon/lib/bare.js"},"/node_modules/favela-web/node_modules/quickbit-native/index.js":{"#package":"/node_modules/favela-web/node_modules/quickbit-native/package.json","./binding":"/node_modules/favela-web/node_modules/quickbit-native/binding.js"},"/node_modules/favela-web/node_modules/quickbit-native/package.json":{},"/node_modules/favela-web/node_modules/quickbit-universal/fallback.js":{"#package":"/node_modules/favela-web/node_modules/quickbit-universal/package.json","simdle-universal":"/node_modules/favela-web/node_modules/simdle-universal/index.js"},"/node_modules/favela-web/node_modules/quickbit-universal/index.js":{"#package":"/node_modules/favela-web/node_modules/quickbit-universal/package.json","./fallback":"/node_modules/favela-web/node_modules/quickbit-universal/fallback.js","quickbit-native":"/node_modules/favela-web/node_modules/quickbit-native/index.js"},"/node_modules/favela-web/node_modules/quickbit-universal/package.json":{},"/node_modules/favela-web/node_modules/rache/index.js":{"#package":"/node_modules/favela-web/node_modules/rache/package.json"},"/node_modules/favela-web/node_modules/rache/package.json":{},"/node_modules/favela-web/node_modules/random-array-iterator/index.js":{"#package":"/node_modules/favela-web/node_modules/random-array-iterator/package.json"},"/node_modules/favela-web/node_modules/random-array-iterator/package.json":{},"/node_modules/favela-web/node_modules/ready-resource/index.js":{"#package":"/node_modules/favela-web/node_modules/ready-resource/package.json","events":"/node_modules/favela-web/node_modules/bare-events/index.js"},"/node_modules/favela-web/node_modules/ready-resource/package.json":{},"/node_modules/favela-web/node_modules/record-cache/index.js":{"#package":"/node_modules/favela-web/node_modules/record-cache/package.json","b4a":"/node_modules/favela-web/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/record-cache/package.json":{},"/node_modules/favela-web/node_modules/refcounter/index.js":{"#package":"/node_modules/favela-web/node_modules/refcounter/package.json"},"/node_modules/favela-web/node_modules/refcounter/package.json":{},"/node_modules/favela-web/node_modules/require-addon/lib/bare.js":{"#package":"/node_modules/favela-web/node_modules/require-addon/package.json"},"/node_modules/favela-web/node_modules/require-addon/package.json":{},"/node_modules/favela-web/node_modules/resolve-reject-promise/index.js":{"#package":"/node_modules/favela-web/node_modules/resolve-reject-promise/package.json"},"/node_modules/favela-web/node_modules/resolve-reject-promise/package.json":{},"/node_modules/favela-web/node_modules/resource-on-exit/index.js":{"#package":"/node_modules/favela-web/node_modules/resource-on-exit/package.json"},"/node_modules/favela-web/node_modules/resource-on-exit/package.json":{},"/node_modules/favela-web/node_modules/rocksdb-native/binding.js":{"#package":"/node_modules/favela-web/node_modules/rocksdb-native/package.json",".":"linked:librocksdb-native.3.17.2.so","require-addon":"/node_modules/favela-web/node_modules/require-addon/lib/bare.js"},"/node_modules/favela-web/node_modules/rocksdb-native/index.js":{"#package":"/node_modules/favela-web/node_modules/rocksdb-native/package.json","./lib/column-family":"/node_modules/favela-web/node_modules/rocksdb-native/lib/column-family.js","./lib/constants":"/node_modules/favela-web/node_modules/rocksdb-native/lib/constants.js","./lib/filter-policy":"/node_modules/favela-web/node_modules/rocksdb-native/lib/filter-policy.js","./lib/iterator":"/node_modules/favela-web/node_modules/rocksdb-native/lib/iterator.js","./lib/snapshot":"/node_modules/favela-web/node_modules/rocksdb-native/lib/snapshot.js","./lib/state":"/node_modules/favela-web/node_modules/rocksdb-native/lib/state.js"},"/node_modules/favela-web/node_modules/rocksdb-native/lib/batch.js":{"#package":"/node_modules/favela-web/node_modules/rocksdb-native/package.json","../binding":"/node_modules/favela-web/node_modules/rocksdb-native/binding.js","compact-encoding":"/node_modules/favela-web/node_modules/rocksdb-native/node_modules/compact-encoding/index.js"},"/node_modules/favela-web/node_modules/rocksdb-native/lib/column-family.js":{"#package":"/node_modules/favela-web/node_modules/rocksdb-native/package.json","../binding":"/node_modules/favela-web/node_modules/rocksdb-native/binding.js","./constants":"/node_modules/favela-web/node_modules/rocksdb-native/lib/constants.js","./filter-policy":"/node_modules/favela-web/node_modules/rocksdb-native/lib/filter-policy.js"},"/node_modules/favela-web/node_modules/rocksdb-native/lib/constants.js":{"#package":"/node_modules/favela-web/node_modules/rocksdb-native/package.json"},"/node_modules/favela-web/node_modules/rocksdb-native/lib/filter-policy.js":{"#package":"/node_modules/favela-web/node_modules/rocksdb-native/package.json"},"/node_modules/favela-web/node_modules/rocksdb-native/lib/iterator.js":{"#package":"/node_modules/favela-web/node_modules/rocksdb-native/package.json","../binding":"/node_modules/favela-web/node_modules/rocksdb-native/binding.js","compact-encoding":"/node_modules/favela-web/node_modules/rocksdb-native/node_modules/compact-encoding/index.js","streamx":"/node_modules/favela-web/node_modules/streamx/index.js"},"/node_modules/favela-web/node_modules/rocksdb-native/lib/snapshot.js":{"#package":"/node_modules/favela-web/node_modules/rocksdb-native/package.json","../binding":"/node_modules/favela-web/node_modules/rocksdb-native/binding.js"},"/node_modules/favela-web/node_modules/rocksdb-native/lib/state.js":{"#package":"/node_modules/favela-web/node_modules/rocksdb-native/package.json","../binding":"/node_modules/favela-web/node_modules/rocksdb-native/binding.js","./batch":"/node_modules/favela-web/node_modules/rocksdb-native/lib/batch.js","./column-family":"/node_modules/favela-web/node_modules/rocksdb-native/lib/column-family.js","./constants":"/node_modules/favela-web/node_modules/rocksdb-native/lib/constants.js","compact-encoding":"/node_modules/favela-web/node_modules/rocksdb-native/node_modules/compact-encoding/index.js","ready-resource":"/node_modules/favela-web/node_modules/ready-resource/index.js","refcounter":"/node_modules/favela-web/node_modules/refcounter/index.js","resolve-reject-promise":"/node_modules/favela-web/node_modules/resolve-reject-promise/index.js","signal-promise":"/node_modules/favela-web/node_modules/signal-promise/index.js"},"/node_modules/favela-web/node_modules/rocksdb-native/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/favela-web/node_modules/rocksdb-native/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/rocksdb-native/node_modules/compact-encoding/index.js":{"#package":"/node_modules/favela-web/node_modules/rocksdb-native/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/rocksdb-native/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/favela-web/node_modules/rocksdb-native/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/favela-web/node_modules/rocksdb-native/node_modules/compact-encoding/raw.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/rocksdb-native/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/favela-web/node_modules/rocksdb-native/node_modules/compact-encoding/package.json"},"/node_modules/favela-web/node_modules/rocksdb-native/node_modules/compact-encoding/package.json":{},"/node_modules/favela-web/node_modules/rocksdb-native/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/favela-web/node_modules/rocksdb-native/node_modules/compact-encoding/package.json","./endian":"/node_modules/favela-web/node_modules/rocksdb-native/node_modules/compact-encoding/endian.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/rocksdb-native/package.json":{},"/node_modules/favela-web/node_modules/safety-catch/index.js":{"#package":"/node_modules/favela-web/node_modules/safety-catch/package.json"},"/node_modules/favela-web/node_modules/safety-catch/package.json":{},"/node_modules/favela-web/node_modules/scope-lock/index.js":{"#package":"/node_modules/favela-web/node_modules/scope-lock/package.json"},"/node_modules/favela-web/node_modules/scope-lock/package.json":{},"/node_modules/favela-web/node_modules/shuffled-priority-queue/index.js":{"#package":"/node_modules/favela-web/node_modules/shuffled-priority-queue/package.json","unordered-set":"/node_modules/favela-web/node_modules/unordered-set/index.js"},"/node_modules/favela-web/node_modules/shuffled-priority-queue/package.json":{},"/node_modules/favela-web/node_modules/signal-promise/index.js":{"#package":"/node_modules/favela-web/node_modules/signal-promise/package.json"},"/node_modules/favela-web/node_modules/signal-promise/package.json":{},"/node_modules/favela-web/node_modules/signed-varint/index.js":{"#package":"/node_modules/favela-web/node_modules/signed-varint/package.json","varint":"/node_modules/favela-web/node_modules/varint/index.js"},"/node_modules/favela-web/node_modules/signed-varint/package.json":{},"/node_modules/favela-web/node_modules/simdle-native/binding.js":{"#package":"/node_modules/favela-web/node_modules/simdle-native/package.json",".":"linked:libsimdle-native.1.3.9.so","require-addon":"/node_modules/favela-web/node_modules/require-addon/lib/bare.js"},"/node_modules/favela-web/node_modules/simdle-native/index.js":{"#package":"/node_modules/favela-web/node_modules/simdle-native/package.json","./binding":"/node_modules/favela-web/node_modules/simdle-native/binding.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/simdle-native/package.json":{},"/node_modules/favela-web/node_modules/simdle-universal/fallback.js":{"#package":"/node_modules/favela-web/node_modules/simdle-universal/package.json","./scalar":"/node_modules/favela-web/node_modules/simdle-universal/scalar.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/simdle-universal/index.js":{"#package":"/node_modules/favela-web/node_modules/simdle-universal/package.json","./fallback":"/node_modules/favela-web/node_modules/simdle-universal/fallback.js","simdle-native":"/node_modules/favela-web/node_modules/simdle-native/index.js"},"/node_modules/favela-web/node_modules/simdle-universal/package.json":{},"/node_modules/favela-web/node_modules/simdle-universal/scalar.js":{"#package":"/node_modules/favela-web/node_modules/simdle-universal/package.json"},"/node_modules/favela-web/node_modules/sodium-native/binding.js":{"#package":"/node_modules/favela-web/node_modules/sodium-native/package.json",".":"linked:libsodium-native.5.1.0.so","require-addon":"/node_modules/favela-web/node_modules/require-addon/lib/bare.js"},"/node_modules/favela-web/node_modules/sodium-native/index.js":{"#package":"/node_modules/favela-web/node_modules/sodium-native/package.json","./binding":"/node_modules/favela-web/node_modules/sodium-native/binding.js","assert":"/node_modules/favela-web/node_modules/bare-assert/index.js","which-runtime":"/node_modules/favela-web/node_modules/which-runtime/index.js"},"/node_modules/favela-web/node_modules/sodium-native/package.json":{},"/node_modules/favela-web/node_modules/sodium-secretstream/index.js":{"#package":"/node_modules/favela-web/node_modules/sodium-secretstream/package.json","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","sodium-universal":"/node_modules/favela-web/node_modules/sodium-universal/index.js"},"/node_modules/favela-web/node_modules/sodium-secretstream/package.json":{},"/node_modules/favela-web/node_modules/sodium-universal/index.js":{"#package":"/node_modules/favela-web/node_modules/sodium-universal/package.json","sodium-native":"/node_modules/favela-web/node_modules/sodium-native/index.js"},"/node_modules/favela-web/node_modules/sodium-universal/package.json":{},"/node_modules/favela-web/node_modules/streamx/index.js":{"#package":"/node_modules/favela-web/node_modules/streamx/package.json","./lib/errors.js":"/node_modules/favela-web/node_modules/streamx/lib/errors.js","events-universal":"/node_modules/favela-web/node_modules/events-universal/bare.js","fast-fifo":"/node_modules/favela-web/node_modules/fast-fifo/index.js","text-decoder":"/node_modules/favela-web/node_modules/text-decoder/index.js"},"/node_modules/favela-web/node_modules/streamx/lib/errors.js":{"#package":"/node_modules/favela-web/node_modules/streamx/package.json"},"/node_modules/favela-web/node_modules/streamx/package.json":{},"/node_modules/favela-web/node_modules/teex/index.js":{"#package":"/node_modules/favela-web/node_modules/teex/package.json","streamx":"/node_modules/favela-web/node_modules/streamx/index.js"},"/node_modules/favela-web/node_modules/teex/package.json":{},"/node_modules/favela-web/node_modules/text-decoder/index.js":{"#package":"/node_modules/favela-web/node_modules/text-decoder/package.json","./lib/pass-through-decoder":"/node_modules/favela-web/node_modules/text-decoder/lib/pass-through-decoder.js","./lib/utf8-decoder":"/node_modules/favela-web/node_modules/text-decoder/lib/utf8-decoder.js"},"/node_modules/favela-web/node_modules/text-decoder/lib/pass-through-decoder.js":{"#package":"/node_modules/favela-web/node_modules/text-decoder/package.json","b4a":"/node_modules/favela-web/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/text-decoder/lib/utf8-decoder.js":{"#package":"/node_modules/favela-web/node_modules/text-decoder/package.json","b4a":"/node_modules/favela-web/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/text-decoder/package.json":{},"/node_modules/favela-web/node_modules/time-ordered-set/index.js":{"#package":"/node_modules/favela-web/node_modules/time-ordered-set/package.json"},"/node_modules/favela-web/node_modules/time-ordered-set/package.json":{},"/node_modules/favela-web/node_modules/timeout-refresh/browser.js":{"#package":"/node_modules/favela-web/node_modules/timeout-refresh/package.json"},"/node_modules/favela-web/node_modules/timeout-refresh/index.js":{"#package":"/node_modules/favela-web/node_modules/timeout-refresh/package.json","./browser":"/node_modules/favela-web/node_modules/timeout-refresh/browser.js","./node":"/node_modules/favela-web/node_modules/timeout-refresh/node.js"},"/node_modules/favela-web/node_modules/timeout-refresh/node.js":{"#package":"/node_modules/favela-web/node_modules/timeout-refresh/package.json"},"/node_modules/favela-web/node_modules/timeout-refresh/package.json":{},"/node_modules/favela-web/node_modules/udx-native/binding.js":{"#package":"/node_modules/favela-web/node_modules/udx-native/package.json",".":"linked:libudx-native.1.20.7.so","require-addon":"/node_modules/favela-web/node_modules/require-addon/lib/bare.js"},"/node_modules/favela-web/node_modules/udx-native/lib/ip.js":{"#package":"/node_modules/favela-web/node_modules/udx-native/package.json"},"/node_modules/favela-web/node_modules/udx-native/lib/network-interfaces.js":{"#package":"/node_modules/favela-web/node_modules/udx-native/package.json","../binding":"/node_modules/favela-web/node_modules/udx-native/binding.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","events":"/node_modules/favela-web/node_modules/bare-events/index.js"},"/node_modules/favela-web/node_modules/udx-native/lib/socket.js":{"#package":"/node_modules/favela-web/node_modules/udx-native/package.json","../binding":"/node_modules/favela-web/node_modules/udx-native/binding.js","./ip":"/node_modules/favela-web/node_modules/udx-native/lib/ip.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","events":"/node_modules/favela-web/node_modules/bare-events/index.js"},"/node_modules/favela-web/node_modules/udx-native/lib/stream.js":{"#package":"/node_modules/favela-web/node_modules/udx-native/package.json","../binding":"/node_modules/favela-web/node_modules/udx-native/binding.js","./ip":"/node_modules/favela-web/node_modules/udx-native/lib/ip.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js","streamx":"/node_modules/favela-web/node_modules/streamx/index.js"},"/node_modules/favela-web/node_modules/udx-native/lib/udx.js":{"#package":"/node_modules/favela-web/node_modules/udx-native/package.json","../binding":"/node_modules/favela-web/node_modules/udx-native/binding.js","./ip":"/node_modules/favela-web/node_modules/udx-native/lib/ip.js","./network-interfaces":"/node_modules/favela-web/node_modules/udx-native/lib/network-interfaces.js","./socket":"/node_modules/favela-web/node_modules/udx-native/lib/socket.js","./stream":"/node_modules/favela-web/node_modules/udx-native/lib/stream.js","b4a":"/node_modules/favela-web/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/udx-native/package.json":{},"/node_modules/favela-web/node_modules/unordered-set/index.js":{"#package":"/node_modules/favela-web/node_modules/unordered-set/package.json"},"/node_modules/favela-web/node_modules/unordered-set/package.json":{},"/node_modules/favela-web/node_modules/unslab/index.js":{"#package":"/node_modules/favela-web/node_modules/unslab/package.json","b4a":"/node_modules/favela-web/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/unslab/package.json":{},"/node_modules/favela-web/node_modules/varint/decode.js":{"#package":"/node_modules/favela-web/node_modules/varint/package.json"},"/node_modules/favela-web/node_modules/varint/encode.js":{"#package":"/node_modules/favela-web/node_modules/varint/package.json"},"/node_modules/favela-web/node_modules/varint/index.js":{"#package":"/node_modules/favela-web/node_modules/varint/package.json","./decode.js":"/node_modules/favela-web/node_modules/varint/decode.js","./encode.js":"/node_modules/favela-web/node_modules/varint/encode.js","./length.js":"/node_modules/favela-web/node_modules/varint/length.js"},"/node_modules/favela-web/node_modules/varint/length.js":{"#package":"/node_modules/favela-web/node_modules/varint/package.json"},"/node_modules/favela-web/node_modules/varint/package.json":{},"/node_modules/favela-web/node_modules/which-runtime/index.js":{"#package":"/node_modules/favela-web/node_modules/which-runtime/package.json"},"/node_modules/favela-web/node_modules/which-runtime/package.json":{},"/node_modules/favela-web/node_modules/xache/index.js":{"#package":"/node_modules/favela-web/node_modules/xache/package.json"},"/node_modules/favela-web/node_modules/xache/package.json":{},"/node_modules/favela-web/node_modules/z32/index.js":{"#package":"/node_modules/favela-web/node_modules/z32/package.json","b4a":"/node_modules/favela-web/node_modules/b4a/index.js"},"/node_modules/favela-web/node_modules/z32/package.json":{},"/node_modules/favela-web/package.json":{},"/node_modules/favela-web/web/static-assets.js":{"#package":"/node_modules/favela-web/package.json"},"/node_modules/hyper-overlay/lib/tree.js":{"#fs":"/node_modules/hyper-overlay/node_modules/bare-fs/index.js","#package":"/node_modules/hyper-overlay/package.json","#path":"/node_modules/hyper-overlay/node_modules/bare-path/index.js","compact-encoding":"/node_modules/hyper-overlay/node_modules/compact-encoding/index.js","hypercore-crypto":"/node_modules/hyper-overlay/node_modules/hypercore-crypto/index.js"},"/node_modules/hyper-overlay/node_modules/b4a/index.js":{"#package":"/node_modules/hyper-overlay/node_modules/b4a/package.json"},"/node_modules/hyper-overlay/node_modules/b4a/package.json":{},"/node_modules/hyper-overlay/node_modules/bare-ansi-escapes/index.js":{"#package":"/node_modules/hyper-overlay/node_modules/bare-ansi-escapes/package.json"},"/node_modules/hyper-overlay/node_modules/bare-ansi-escapes/package.json":{},"/node_modules/hyper-overlay/node_modules/bare-assert/index.js":{"#package":"/node_modules/hyper-overlay/node_modules/bare-assert/package.json","bare-inspect":"/node_modules/hyper-overlay/node_modules/bare-inspect/index.js"},"/node_modules/hyper-overlay/node_modules/bare-assert/package.json":{},"/node_modules/hyper-overlay/node_modules/bare-events/index.js":{"#package":"/node_modules/hyper-overlay/node_modules/bare-events/package.json","./lib/errors":"/node_modules/hyper-overlay/node_modules/bare-events/lib/errors.js"},"/node_modules/hyper-overlay/node_modules/bare-events/lib/errors.js":{"#package":"/node_modules/hyper-overlay/node_modules/bare-events/package.json"},"/node_modules/hyper-overlay/node_modules/bare-events/package.json":{},"/node_modules/hyper-overlay/node_modules/bare-fs/binding.js":{"#package":"/node_modules/hyper-overlay/node_modules/bare-fs/package.json",".":"linked:libbare-fs.4.7.2.so"},"/node_modules/hyper-overlay/node_modules/bare-fs/index.js":{"#package":"/node_modules/hyper-overlay/node_modules/bare-fs/package.json","./binding":"/node_modules/hyper-overlay/node_modules/bare-fs/binding.js","./lib/constants":"/node_modules/hyper-overlay/node_modules/bare-fs/lib/constants.js","./lib/errors":"/node_modules/hyper-overlay/node_modules/bare-fs/lib/errors.js","./promises":"/node_modules/hyper-overlay/node_modules/bare-fs/promises.js","bare-events":"/node_modules/hyper-overlay/node_modules/bare-events/index.js","bare-path":"/node_modules/hyper-overlay/node_modules/bare-path/index.js","bare-stream":"/node_modules/hyper-overlay/node_modules/bare-stream/index.js","bare-url":"/node_modules/hyper-overlay/node_modules/bare-url/index.js","fast-fifo":"/node_modules/hyper-overlay/node_modules/fast-fifo/index.js"},"/node_modules/hyper-overlay/node_modules/bare-fs/lib/constants.js":{"#package":"/node_modules/hyper-overlay/node_modules/bare-fs/package.json","../binding":"/node_modules/hyper-overlay/node_modules/bare-fs/binding.js"},"/node_modules/hyper-overlay/node_modules/bare-fs/lib/errors.js":{"#package":"/node_modules/hyper-overlay/node_modules/bare-fs/package.json","bare-os":"/node_modules/hyper-overlay/node_modules/bare-os/index.js"},"/node_modules/hyper-overlay/node_modules/bare-fs/package.json":{},"/node_modules/hyper-overlay/node_modules/bare-fs/promises.js":{"#package":"/node_modules/hyper-overlay/node_modules/bare-fs/package.json",".":"/node_modules/hyper-overlay/node_modules/bare-fs/index.js","bare-events":"/node_modules/hyper-overlay/node_modules/bare-events/index.js"},"/node_modules/hyper-overlay/node_modules/bare-inspect/binding.js":{"#package":"/node_modules/hyper-overlay/node_modules/bare-inspect/package.json",".":"linked:libbare-inspect.3.1.4.so"},"/node_modules/hyper-overlay/node_modules/bare-inspect/index.js":{"#package":"/node_modules/hyper-overlay/node_modules/bare-inspect/package.json","./binding":"/node_modules/hyper-overlay/node_modules/bare-inspect/binding.js","bare-ansi-escapes":"/node_modules/hyper-overlay/node_modules/bare-ansi-escapes/index.js","bare-type":"/node_modules/hyper-overlay/node_modules/bare-type/index.js"},"/node_modules/hyper-overlay/node_modules/bare-inspect/package.json":{},"/node_modules/hyper-overlay/node_modules/bare-os/binding.js":{"#package":"/node_modules/hyper-overlay/node_modules/bare-os/package.json",".":"linked:libbare-os.3.9.1.so"},"/node_modules/hyper-overlay/node_modules/bare-os/index.js":{"#package":"/node_modules/hyper-overlay/node_modules/bare-os/package.json","./binding":"/node_modules/hyper-overlay/node_modules/bare-os/binding.js","./lib/constants":"/node_modules/hyper-overlay/node_modules/bare-os/lib/constants.js","./lib/errors":"/node_modules/hyper-overlay/node_modules/bare-os/lib/errors.js"},"/node_modules/hyper-overlay/node_modules/bare-os/lib/constants.js":{"#package":"/node_modules/hyper-overlay/node_modules/bare-os/package.json","../binding":"/node_modules/hyper-overlay/node_modules/bare-os/binding.js"},"/node_modules/hyper-overlay/node_modules/bare-os/lib/errors.js":{"#package":"/node_modules/hyper-overlay/node_modules/bare-os/package.json"},"/node_modules/hyper-overlay/node_modules/bare-os/package.json":{},"/node_modules/hyper-overlay/node_modules/bare-path/index.js":{"#package":"/node_modules/hyper-overlay/node_modules/bare-path/package.json","./lib/posix":"/node_modules/hyper-overlay/node_modules/bare-path/lib/posix.js","./lib/win32":"/node_modules/hyper-overlay/node_modules/bare-path/lib/win32.js"},"/node_modules/hyper-overlay/node_modules/bare-path/lib/constants.js":{"#package":"/node_modules/hyper-overlay/node_modules/bare-path/package.json"},"/node_modules/hyper-overlay/node_modules/bare-path/lib/posix.js":{"#package":"/node_modules/hyper-overlay/node_modules/bare-path/package.json","./constants":"/node_modules/hyper-overlay/node_modules/bare-path/lib/constants.js","./shared":"/node_modules/hyper-overlay/node_modules/bare-path/lib/shared.js","./win32":"/node_modules/hyper-overlay/node_modules/bare-path/lib/win32.js","bare-os":"/node_modules/hyper-overlay/node_modules/bare-os/index.js"},"/node_modules/hyper-overlay/node_modules/bare-path/lib/shared.js":{"#package":"/node_modules/hyper-overlay/node_modules/bare-path/package.json","./constants":"/node_modules/hyper-overlay/node_modules/bare-path/lib/constants.js"},"/node_modules/hyper-overlay/node_modules/bare-path/lib/win32.js":{"#package":"/node_modules/hyper-overlay/node_modules/bare-path/package.json","./constants":"/node_modules/hyper-overlay/node_modules/bare-path/lib/constants.js","./posix":"/node_modules/hyper-overlay/node_modules/bare-path/lib/posix.js","./shared":"/node_modules/hyper-overlay/node_modules/bare-path/lib/shared.js","bare-os":"/node_modules/hyper-overlay/node_modules/bare-os/index.js"},"/node_modules/hyper-overlay/node_modules/bare-path/package.json":{},"/node_modules/hyper-overlay/node_modules/bare-stream/index.js":{"#package":"/node_modules/hyper-overlay/node_modules/bare-stream/package.json","./web":"/node_modules/hyper-overlay/node_modules/bare-stream/web.js","b4a":"/node_modules/hyper-overlay/node_modules/b4a/index.js","streamx":"/node_modules/hyper-overlay/node_modules/streamx/index.js"},"/node_modules/hyper-overlay/node_modules/bare-stream/package.json":{},"/node_modules/hyper-overlay/node_modules/bare-stream/web.js":{"#package":"/node_modules/hyper-overlay/node_modules/bare-stream/package.json","streamx":"/node_modules/hyper-overlay/node_modules/streamx/index.js","teex":"/node_modules/hyper-overlay/node_modules/teex/index.js"},"/node_modules/hyper-overlay/node_modules/bare-type/binding.js":{"#package":"/node_modules/hyper-overlay/node_modules/bare-type/package.json",".":"linked:libbare-type.1.1.0.so"},"/node_modules/hyper-overlay/node_modules/bare-type/index.js":{"#package":"/node_modules/hyper-overlay/node_modules/bare-type/package.json","./binding":"/node_modules/hyper-overlay/node_modules/bare-type/binding.js"},"/node_modules/hyper-overlay/node_modules/bare-type/package.json":{},"/node_modules/hyper-overlay/node_modules/bare-url/binding.js":{"#package":"/node_modules/hyper-overlay/node_modules/bare-url/package.json",".":"linked:libbare-url.2.4.5.so"},"/node_modules/hyper-overlay/node_modules/bare-url/index.js":{"#package":"/node_modules/hyper-overlay/node_modules/bare-url/package.json","./binding":"/node_modules/hyper-overlay/node_modules/bare-url/binding.js","./lib/errors":"/node_modules/hyper-overlay/node_modules/bare-url/lib/errors.js","./lib/url-search-params":"/node_modules/hyper-overlay/node_modules/bare-url/lib/url-search-params.js","bare-path":"/node_modules/hyper-overlay/node_modules/bare-path/index.js"},"/node_modules/hyper-overlay/node_modules/bare-url/lib/errors.js":{"#package":"/node_modules/hyper-overlay/node_modules/bare-url/package.json"},"/node_modules/hyper-overlay/node_modules/bare-url/lib/url-search-params.js":{"#package":"/node_modules/hyper-overlay/node_modules/bare-url/package.json"},"/node_modules/hyper-overlay/node_modules/bare-url/package.json":{},"/node_modules/hyper-overlay/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/hyper-overlay/node_modules/compact-encoding/package.json"},"/node_modules/hyper-overlay/node_modules/compact-encoding/index.js":{"#package":"/node_modules/hyper-overlay/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-overlay/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/hyper-overlay/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/hyper-overlay/node_modules/compact-encoding/raw.js","b4a":"/node_modules/hyper-overlay/node_modules/b4a/index.js"},"/node_modules/hyper-overlay/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/hyper-overlay/node_modules/compact-encoding/package.json"},"/node_modules/hyper-overlay/node_modules/compact-encoding/package.json":{},"/node_modules/hyper-overlay/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/hyper-overlay/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-overlay/node_modules/compact-encoding/endian.js","b4a":"/node_modules/hyper-overlay/node_modules/b4a/index.js"},"/node_modules/hyper-overlay/node_modules/events-universal/bare.js":{"#package":"/node_modules/hyper-overlay/node_modules/events-universal/package.json","bare-events":"/node_modules/hyper-overlay/node_modules/bare-events/index.js"},"/node_modules/hyper-overlay/node_modules/events-universal/package.json":{},"/node_modules/hyper-overlay/node_modules/fast-fifo/fixed-size.js":{"#package":"/node_modules/hyper-overlay/node_modules/fast-fifo/package.json"},"/node_modules/hyper-overlay/node_modules/fast-fifo/index.js":{"#package":"/node_modules/hyper-overlay/node_modules/fast-fifo/package.json","./fixed-size":"/node_modules/hyper-overlay/node_modules/fast-fifo/fixed-size.js"},"/node_modules/hyper-overlay/node_modules/fast-fifo/package.json":{},"/node_modules/hyper-overlay/node_modules/hypercore-crypto/index.js":{"#package":"/node_modules/hyper-overlay/node_modules/hypercore-crypto/package.json","b4a":"/node_modules/hyper-overlay/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-overlay/node_modules/compact-encoding/index.js","sodium-universal":"/node_modules/hyper-overlay/node_modules/sodium-universal/index.js"},"/node_modules/hyper-overlay/node_modules/hypercore-crypto/package.json":{},"/node_modules/hyper-overlay/node_modules/require-addon/lib/bare.js":{"#package":"/node_modules/hyper-overlay/node_modules/require-addon/package.json"},"/node_modules/hyper-overlay/node_modules/require-addon/package.json":{},"/node_modules/hyper-overlay/node_modules/sodium-native/binding.js":{"#package":"/node_modules/hyper-overlay/node_modules/sodium-native/package.json",".":"linked:libsodium-native.5.1.0.so","require-addon":"/node_modules/hyper-overlay/node_modules/require-addon/lib/bare.js"},"/node_modules/hyper-overlay/node_modules/sodium-native/index.js":{"#package":"/node_modules/hyper-overlay/node_modules/sodium-native/package.json","./binding":"/node_modules/hyper-overlay/node_modules/sodium-native/binding.js","assert":"/node_modules/hyper-overlay/node_modules/bare-assert/index.js","which-runtime":"/node_modules/hyper-overlay/node_modules/which-runtime/index.js"},"/node_modules/hyper-overlay/node_modules/sodium-native/package.json":{},"/node_modules/hyper-overlay/node_modules/sodium-universal/index.js":{"#package":"/node_modules/hyper-overlay/node_modules/sodium-universal/package.json","sodium-native":"/node_modules/hyper-overlay/node_modules/sodium-native/index.js"},"/node_modules/hyper-overlay/node_modules/sodium-universal/package.json":{},"/node_modules/hyper-overlay/node_modules/streamx/index.js":{"#package":"/node_modules/hyper-overlay/node_modules/streamx/package.json","./lib/errors.js":"/node_modules/hyper-overlay/node_modules/streamx/lib/errors.js","events-universal":"/node_modules/hyper-overlay/node_modules/events-universal/bare.js","fast-fifo":"/node_modules/hyper-overlay/node_modules/fast-fifo/index.js","text-decoder":"/node_modules/hyper-overlay/node_modules/text-decoder/index.js"},"/node_modules/hyper-overlay/node_modules/streamx/lib/errors.js":{"#package":"/node_modules/hyper-overlay/node_modules/streamx/package.json"},"/node_modules/hyper-overlay/node_modules/streamx/package.json":{},"/node_modules/hyper-overlay/node_modules/teex/index.js":{"#package":"/node_modules/hyper-overlay/node_modules/teex/package.json","streamx":"/node_modules/hyper-overlay/node_modules/streamx/index.js"},"/node_modules/hyper-overlay/node_modules/teex/package.json":{},"/node_modules/hyper-overlay/node_modules/text-decoder/index.js":{"#package":"/node_modules/hyper-overlay/node_modules/text-decoder/package.json","./lib/pass-through-decoder":"/node_modules/hyper-overlay/node_modules/text-decoder/lib/pass-through-decoder.js","./lib/utf8-decoder":"/node_modules/hyper-overlay/node_modules/text-decoder/lib/utf8-decoder.js"},"/node_modules/hyper-overlay/node_modules/text-decoder/lib/pass-through-decoder.js":{"#package":"/node_modules/hyper-overlay/node_modules/text-decoder/package.json","b4a":"/node_modules/hyper-overlay/node_modules/b4a/index.js"},"/node_modules/hyper-overlay/node_modules/text-decoder/lib/utf8-decoder.js":{"#package":"/node_modules/hyper-overlay/node_modules/text-decoder/package.json","b4a":"/node_modules/hyper-overlay/node_modules/b4a/index.js"},"/node_modules/hyper-overlay/node_modules/text-decoder/package.json":{},"/node_modules/hyper-overlay/node_modules/which-runtime/index.js":{"#package":"/node_modules/hyper-overlay/node_modules/which-runtime/package.json"},"/node_modules/hyper-overlay/node_modules/which-runtime/package.json":{},"/node_modules/hyper-overlay/package.json":{},"/node_modules/hyper-proto-peer/lib/adopt.js":{"#package":"/node_modules/hyper-proto-peer/package.json","./coowner.js":"/node_modules/hyper-proto-peer/lib/coowner.js","atproto-room/lib/pairing.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/lib/pairing.js"},"/node_modules/hyper-proto-peer/lib/config.js":{"#package":"/node_modules/hyper-proto-peer/package.json","bare-fs":"/node_modules/hyper-proto-peer/node_modules/bare-fs/index.js","bare-os":"/node_modules/hyper-proto-peer/node_modules/bare-os/index.js","bare-path":"/node_modules/hyper-proto-peer/node_modules/bare-path/index.js"},"/node_modules/hyper-proto-peer/lib/conflict-watch.js":{"#package":"/node_modules/hyper-proto-peer/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/lib/coowner.js":{"#package":"/node_modules/hyper-proto-peer/package.json","./config.js":"/node_modules/hyper-proto-peer/lib/config.js","atproto-identity/lib/device-chain.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/lib/device-chain.js","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js","bare-fs":"/node_modules/hyper-proto-peer/node_modules/bare-fs/index.js","keet-identity-key":"/node_modules/hyper-proto-peer/node_modules/keet-identity-key/index.js"},"/node_modules/hyper-proto-peer/lib/device-node.js":{"#package":"/node_modules/hyper-proto-peer/package.json","./config.js":"/node_modules/hyper-proto-peer/lib/config.js","./conflict-watch.js":"/node_modules/hyper-proto-peer/lib/conflict-watch.js","./dual-blob-store.js":"/node_modules/hyper-proto-peer/lib/dual-blob-store.js","./reconcile-retry.js":"/node_modules/hyper-proto-peer/lib/reconcile-retry.js","./serve-device-uds.js":"/node_modules/hyper-proto-peer/lib/serve-device-uds.js","./serve-device.js":"/node_modules/hyper-proto-peer/lib/serve-device.js","./sessions.js":"/node_modules/hyper-proto-peer/lib/sessions.js","./swarm-device.js":"/node_modules/hyper-proto-peer/lib/swarm-device.js","./swarm-keypair.js":"/node_modules/hyper-proto-peer/lib/swarm-keypair.js","atproto-identity":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/lib/atproto-identity.js","atproto-repo/lib/repo.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/lib/repo.js","atproto-room/lib/membership.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/lib/membership.js","atproto-room/lib/serve-membrane.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/lib/serve-membrane.js","atproto-room/lib/state-base.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/lib/state-base.js","atproto-store/lib/account-registry.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/lib/account-registry.js","atproto-store/lib/blob-pointer-store.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/lib/blob-pointer-store.js","atproto-store/lib/blob-store.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/lib/blob-store.js","atproto-store/lib/corestore.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/lib/corestore.js","atproto-store/lib/overlay-blob-store.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/lib/overlay-blob-store.js","atproto-store/lib/overlay-repo-store.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/lib/overlay-repo-store.js","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js","bare-fs":"/node_modules/hyper-proto-peer/node_modules/bare-fs/index.js","bare-path":"/node_modules/hyper-proto-peer/node_modules/bare-path/index.js","bare-process":"/node_modules/hyper-proto-peer/node_modules/bare-process/index.js","hyper-overlay":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/index.js","hypercore-crypto":"/node_modules/hyper-proto-peer/node_modules/hypercore-crypto/index.js","hyperswarm":"/node_modules/hyper-proto-peer/node_modules/hyperswarm/index.js","multiformats/cid":"/node_modules/hyper-proto-peer/node_modules/multiformats/dist/src/cid.js","protomux":"/node_modules/hyper-proto-peer/node_modules/protomux/index.js","protomux-wakeup":"/node_modules/hyper-proto-peer/node_modules/protomux-wakeup/index.js"},"/node_modules/hyper-proto-peer/lib/dual-blob-store.js":{"#package":"/node_modules/hyper-proto-peer/package.json"},"/node_modules/hyper-proto-peer/lib/hosting-cli.js":{"#package":"/node_modules/hyper-proto-peer/package.json","atproto-identity":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/lib/atproto-identity.js","atproto-identity/lib/hosting.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/lib/hosting.js","atproto-identity/lib/plc-directory.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/lib/plc-directory.js","atproto-identity/lib/vault.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/lib/vault.js","bare-fetch/global":"/node_modules/hyper-proto-peer/node_modules/bare-fetch/global.js","bare-fs":"/node_modules/hyper-proto-peer/node_modules/bare-fs/index.js"},"/node_modules/hyper-proto-peer/lib/mint.js":{"#package":"/node_modules/hyper-proto-peer/package.json","./config.js":"/node_modules/hyper-proto-peer/lib/config.js","./coowner.js":"/node_modules/hyper-proto-peer/lib/coowner.js","./device-node.js":"/node_modules/hyper-proto-peer/lib/device-node.js","atproto-identity/lib/plc-directory.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/lib/plc-directory.js","atproto-room/lib/membership.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/lib/membership.js","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js","bare-fetch/global":"/node_modules/hyper-proto-peer/node_modules/bare-fetch/global.js","keet-identity-key":"/node_modules/hyper-proto-peer/node_modules/keet-identity-key/index.js"},"/node_modules/hyper-proto-peer/lib/reconcile-retry.js":{"#package":"/node_modules/hyper-proto-peer/package.json"},"/node_modules/hyper-proto-peer/lib/serve-device-uds.js":{"#package":"/node_modules/hyper-proto-peer/package.json","./conflict-watch.js":"/node_modules/hyper-proto-peer/lib/conflict-watch.js","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js","bare-fs":"/node_modules/hyper-proto-peer/node_modules/bare-fs/index.js","hyper-svc":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/index.js"},"/node_modules/hyper-proto-peer/lib/serve-device.js":{"#package":"/node_modules/hyper-proto-peer/package.json","./conflict-watch.js":"/node_modules/hyper-proto-peer/lib/conflict-watch.js","atproto-identity/lib/discovery.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/lib/discovery.js","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/compact-encoding/index.js","protomux-rpc":"/node_modules/hyper-proto-peer/node_modules/protomux-rpc/index.js"},"/node_modules/hyper-proto-peer/lib/sessions.js":{"#package":"/node_modules/hyper-proto-peer/package.json","atproto-identity/lib/auth.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/lib/auth.js"},"/node_modules/hyper-proto-peer/lib/swarm-device.js":{"#package":"/node_modules/hyper-proto-peer/package.json","@ipld/dag-cbor":"/node_modules/hyper-proto-peer/node_modules/@ipld/dag-cbor/src/index.js","atproto-identity/lib/auth.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/lib/auth.js","atproto-room/lib/lease.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/lib/lease.js","atproto-room/lib/membership.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/lib/membership.js","atproto-room/lib/repo-base.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/lib/repo-base.js","atproto-room/lib/signer.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/lib/signer.js","atproto-store/lib/pointer-substrate.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/lib/pointer-substrate.js","atproto-store/lib/read-view.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/lib/read-view.js","atproto-store/lib/tid.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/lib/tid.js","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js","multiformats/cid":"/node_modules/hyper-proto-peer/node_modules/multiformats/dist/src/cid.js"},"/node_modules/hyper-proto-peer/lib/swarm-keypair.js":{"#package":"/node_modules/hyper-proto-peer/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js","bare-fs":"/node_modules/hyper-proto-peer/node_modules/bare-fs/index.js","bare-path":"/node_modules/hyper-proto-peer/node_modules/bare-path/index.js","hypercore-crypto":"/node_modules/hyper-proto-peer/node_modules/hypercore-crypto/index.js"},"/node_modules/hyper-proto-peer/node_modules/@hyperswarm/secret-stream/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/@hyperswarm/secret-stream/package.json","./lib/bridge":"/node_modules/hyper-proto-peer/node_modules/@hyperswarm/secret-stream/lib/bridge.js","./lib/handshake":"/node_modules/hyper-proto-peer/node_modules/@hyperswarm/secret-stream/lib/handshake.js","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js","hypercore-crypto":"/node_modules/hyper-proto-peer/node_modules/hypercore-crypto/index.js","sodium-secretstream":"/node_modules/hyper-proto-peer/node_modules/sodium-secretstream/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/sodium-universal/index.js","streamx":"/node_modules/hyper-proto-peer/node_modules/streamx/index.js","timeout-refresh":"/node_modules/hyper-proto-peer/node_modules/timeout-refresh/index.js","unslab":"/node_modules/hyper-proto-peer/node_modules/unslab/index.js"},"/node_modules/hyper-proto-peer/node_modules/@hyperswarm/secret-stream/lib/bridge.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/@hyperswarm/secret-stream/package.json","streamx":"/node_modules/hyper-proto-peer/node_modules/streamx/index.js"},"/node_modules/hyper-proto-peer/node_modules/@hyperswarm/secret-stream/lib/handshake.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/@hyperswarm/secret-stream/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js","noise-curve-ed":"/node_modules/hyper-proto-peer/node_modules/noise-curve-ed/index.js","noise-handshake":"/node_modules/hyper-proto-peer/node_modules/noise-handshake/noise.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/@hyperswarm/secret-stream/package.json":{},"/node_modules/hyper-proto-peer/node_modules/@ipld/dag-cbor/package.json":{},"/node_modules/hyper-proto-peer/node_modules/@ipld/dag-cbor/src/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/@ipld/dag-cbor/package.json","cborg":"/node_modules/hyper-proto-peer/node_modules/cborg/cborg.js","multiformats/cid":"/node_modules/hyper-proto-peer/node_modules/multiformats/dist/src/cid.js"},"/node_modules/hyper-proto-peer/node_modules/adaptive-timeout/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/adaptive-timeout/package.json","xache":"/node_modules/hyper-proto-peer/node_modules/xache/index.js"},"/node_modules/hyper-proto-peer/node_modules/adaptive-timeout/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/lib/atproto-identity.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/package.json","./did-key.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/lib/did-key.js","./did-plc.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/lib/did-plc.js","@noble/curves/secp256k1":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/curves/esm/secp256k1.js","@noble/hashes/sha2":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/hashes/esm/sha2.js","@scure/bip32":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@scure/bip32/lib/esm/index.js","@scure/bip39":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@scure/bip39/esm/index.js","multiformats/bases/base64":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/multiformats/dist/src/bases/base64.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/lib/auth.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/package.json","@noble/curves/secp256k1":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/curves/esm/secp256k1.js","@noble/hashes/hmac":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/hashes/esm/hmac.js","@noble/hashes/scrypt":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/hashes/esm/scrypt.js","@noble/hashes/sha2":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/hashes/esm/sha2.js","hypercore-crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/hypercore-crypto/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/lib/device-chain.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/b4a/index.js","keet-identity-key":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/keet-identity-key/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/lib/did-key.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/package.json","multiformats/bases/base58":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/multiformats/dist/src/bases/base58.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/lib/did-plc.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/package.json","@ipld/dag-cbor":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@ipld/dag-cbor/src/index.js","@noble/hashes/sha2":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/hashes/esm/sha2.js","multiformats/bases/base32":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/multiformats/dist/src/bases/base32.js","multiformats/cid":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/multiformats/dist/src/cid.js","multiformats/hashes/digest":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/multiformats/dist/src/hashes/digest.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/lib/discovery.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/package.json","hypercore-crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/hypercore-crypto/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/lib/hosting.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/package.json","./atproto-identity.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/lib/atproto-identity.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/lib/plc-directory.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/package.json","./atproto-identity.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/lib/atproto-identity.js","./did-key.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/lib/did-key.js","./did-plc.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/lib/did-plc.js","@noble/curves/p256":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/curves/esm/p256.js","@noble/curves/secp256k1":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/curves/esm/secp256k1.js","@noble/hashes/sha2":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/hashes/esm/sha2.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/lib/vault.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/b4a/index.js","sodium-native":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-native/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@ipld/dag-cbor/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@ipld/dag-cbor/src/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@ipld/dag-cbor/package.json","cborg":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/cborg.js","multiformats/cid":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/multiformats/dist/src/cid.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/curves/esm/_shortw_utils.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/curves/esm/package.json","./abstract/weierstrass.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/curves/esm/abstract/weierstrass.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/curves/esm/abstract/curve.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/curves/esm/package.json","../utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/curves/esm/utils.js","./modular.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/curves/esm/abstract/modular.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/curves/esm/abstract/hash-to-curve.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/curves/esm/package.json","../utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/curves/esm/utils.js","./modular.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/curves/esm/abstract/modular.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/curves/esm/abstract/modular.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/curves/esm/package.json","../utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/curves/esm/utils.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/curves/esm/abstract/weierstrass.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/curves/esm/package.json","../utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/curves/esm/utils.js","./curve.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/curves/esm/abstract/curve.js","./modular.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/curves/esm/abstract/modular.js","@noble/hashes/hmac.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/hashes/esm/hmac.js","@noble/hashes/utils":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/curves/esm/nist.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/curves/esm/package.json","./_shortw_utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/curves/esm/_shortw_utils.js","./abstract/hash-to-curve.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/curves/esm/abstract/hash-to-curve.js","./abstract/modular.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/curves/esm/abstract/modular.js","./abstract/weierstrass.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/curves/esm/abstract/weierstrass.js","@noble/hashes/sha2.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/hashes/esm/sha2.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/curves/esm/p256.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/curves/esm/package.json","./abstract/hash-to-curve.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/curves/esm/abstract/hash-to-curve.js","./nist.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/curves/esm/nist.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/curves/esm/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/curves/esm/secp256k1.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/curves/esm/package.json","./_shortw_utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/curves/esm/_shortw_utils.js","./abstract/hash-to-curve.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/curves/esm/abstract/hash-to-curve.js","./abstract/modular.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/curves/esm/abstract/modular.js","./abstract/weierstrass.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/curves/esm/abstract/weierstrass.js","./utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/curves/esm/utils.js","@noble/hashes/sha2.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/hashes/esm/sha2.js","@noble/hashes/utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/curves/esm/utils.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/curves/esm/package.json","@noble/hashes/utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/hashes/esm/_md.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/hashes/esm/package.json","./utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/hashes/esm/_u64.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/hashes/esm/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/hashes/esm/crypto.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/hashes/esm/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/hashes/esm/hmac.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/hashes/esm/package.json","./utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/hashes/esm/legacy.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/hashes/esm/package.json","./_md.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/hashes/esm/_md.js","./utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/hashes/esm/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/hashes/esm/pbkdf2.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/hashes/esm/package.json","./hmac.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/hashes/esm/hmac.js","./utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/hashes/esm/scrypt.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/hashes/esm/package.json","./pbkdf2.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/hashes/esm/pbkdf2.js","./sha2.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/hashes/esm/sha2.js","./utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/hashes/esm/sha2.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/hashes/esm/package.json","./_md.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/hashes/esm/_md.js","./_u64.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/hashes/esm/_u64.js","./utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/hashes/esm/utils.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/hashes/esm/package.json","@noble/hashes/crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/hashes/esm/crypto.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@scure/base/lib/esm/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@scure/base/lib/esm/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@scure/base/lib/esm/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@scure/bip32/lib/esm/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@scure/bip32/lib/esm/package.json","@noble/curves/abstract/modular":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/curves/esm/abstract/modular.js","@noble/curves/secp256k1":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/curves/esm/secp256k1.js","@noble/hashes/hmac":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/hashes/esm/hmac.js","@noble/hashes/legacy":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/hashes/esm/legacy.js","@noble/hashes/sha2":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/hashes/esm/sha2.js","@noble/hashes/utils":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/hashes/esm/utils.js","@scure/base":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@scure/base/lib/esm/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@scure/bip32/lib/esm/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@scure/bip39/esm/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@scure/bip39/esm/package.json","@noble/hashes/pbkdf2":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/hashes/esm/pbkdf2.js","@noble/hashes/sha2":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/hashes/esm/sha2.js","@noble/hashes/utils":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/hashes/esm/utils.js","@scure/base":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@scure/base/lib/esm/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@scure/bip39/esm/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/b4a/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/b4a/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/b4a/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-ansi-escapes/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-ansi-escapes/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-ansi-escapes/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-assert/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-assert/package.json","bare-inspect":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-inspect/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-assert/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-inspect/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-inspect/package.json",".":"linked:libbare-inspect.3.1.4.so"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-inspect/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-inspect/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-inspect/binding.js","bare-ansi-escapes":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-ansi-escapes/index.js","bare-type":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-type/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-inspect/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-type/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-type/package.json",".":"linked:libbare-type.1.1.0.so"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-type/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-type/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-type/binding.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-type/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json","./wordlist":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/index.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/b4a/index.js","nanoassert":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/nanoassert/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/chinese_simplified.json":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/chinese_traditional.json":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/czech.json":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/english.json":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/french.json":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json","./chinese_simplified.json":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/chinese_simplified.json","./chinese_traditional.json":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/chinese_traditional.json","./czech.json":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/czech.json","./english.json":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/english.json","./french.json":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/french.json","./italian.json":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/italian.json","./japanese.json":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/japanese.json","./korean.json":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/korean.json","./lookup.json":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/lookup.json","./portuguese.json":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/portuguese.json","./russian.json":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/russian.json","./spanish.json":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/spanish.json","./turkish.json":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/turkish.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/italian.json":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/japanese.json":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/korean.json":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/lookup.json":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/portuguese.json":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/russian.json":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/spanish.json":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/turkish.json":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/cborg.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/package.json","./lib/decode.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/decode.js","./lib/encode.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/encode.js","./lib/tagged.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/tagged.js","./lib/token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/0uint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/package.json","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/1negint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/2bytes.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/0uint.js","./byte-utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/3string.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/0uint.js","./2bytes.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/2bytes.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/4array.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/5map.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/6tag.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/0uint.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/7float.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/bl.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/package.json","./byte-utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/byte-utils.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/byte-utils.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/common.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/decode.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/package.json","./byte-utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/common.js","./jump.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/jump.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/encode.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/0uint.js","./1negint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/1negint.js","./2bytes.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/2bytes.js","./3string.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/3string.js","./4array.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/4array.js","./5map.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/5map.js","./6tag.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/6tag.js","./7float.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/7float.js","./bl.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/bl.js","./byte-utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/common.js","./is.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/is.js","./jump.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/jump.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/is.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/jump.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/0uint.js","./1negint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/1negint.js","./2bytes.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/2bytes.js","./3string.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/3string.js","./4array.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/4array.js","./5map.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/5map.js","./6tag.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/6tag.js","./7float.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/7float.js","./byte-utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/tagged.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/token.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/compact-encoding/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/compact-encoding/raw.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/compact-encoding/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/compact-encoding/endian.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/hypercore-crypto/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/hypercore-crypto/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/compact-encoding/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/hypercore-crypto/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/keet-identity-key/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/keet-identity-key/package.json","./lib/crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/keet-identity-key/lib/crypto.js","./lib/encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/keet-identity-key/lib/encoding.js","./lib/keychain":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/keet-identity-key/lib/keychain.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/compact-encoding/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/keet-identity-key/lib/crypto.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/keet-identity-key/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/b4a/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/keet-identity-key/lib/encoding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/keet-identity-key/package.json","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/compact-encoding/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/keet-identity-key/lib/keychain.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/keet-identity-key/package.json","./crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/keet-identity-key/lib/crypto.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/b4a/index.js","bip39-mnemonic":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/compact-encoding/index.js","nanoassert":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/nanoassert/index.js","sodium-hmac":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-hmac/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/keet-identity-key/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/multiformats/dist/src/bases/base.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/multiformats/package.json","../bytes.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/multiformats/dist/src/bytes.js","../vendor/base-x.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/multiformats/dist/src/vendor/base-x.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/multiformats/dist/src/bases/base32.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/multiformats/package.json","./base.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/multiformats/dist/src/bases/base.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/multiformats/dist/src/bases/base36.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/multiformats/package.json","./base.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/multiformats/dist/src/bases/base.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/multiformats/dist/src/bases/base58.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/multiformats/package.json","./base.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/multiformats/dist/src/bases/base.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/multiformats/dist/src/bases/base64.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/multiformats/package.json","./base.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/multiformats/dist/src/bases/base.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/multiformats/dist/src/bytes.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/multiformats/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/multiformats/dist/src/cid.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/multiformats/package.json","./bases/base32.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/multiformats/dist/src/bases/base32.js","./bases/base36.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/multiformats/dist/src/bases/base36.js","./bases/base58.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/multiformats/dist/src/bases/base58.js","./bytes.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/multiformats/dist/src/bytes.js","./hashes/digest.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/multiformats/dist/src/hashes/digest.js","./link/interface.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/multiformats/dist/src/link/interface.js","./varint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/multiformats/dist/src/varint.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/multiformats/dist/src/hashes/digest.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/multiformats/package.json","../bytes.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/multiformats/dist/src/bytes.js","../varint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/multiformats/dist/src/varint.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/multiformats/dist/src/link/interface.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/multiformats/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/multiformats/dist/src/varint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/multiformats/package.json","./vendor/varint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/multiformats/dist/src/vendor/varint.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/multiformats/dist/src/vendor/base-x.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/multiformats/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/multiformats/dist/src/vendor/varint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/multiformats/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/multiformats/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/nanoassert/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/nanoassert/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/nanoassert/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/require-addon/lib/bare.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/require-addon/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/require-addon/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-hmac/hash/sha256.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-hmac/package.json","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-hmac/hash/sha512.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-hmac/package.json","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-hmac/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-hmac/package.json","./hash/sha256":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-hmac/hash/sha256.js","./hash/sha512":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-hmac/hash/sha512.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-hmac/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-native/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-native/package.json",".":"linked:libsodium-native.5.1.0.so","require-addon":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/require-addon/lib/bare.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-native/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-native/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-native/binding.js","assert":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-assert/index.js","which-runtime":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/which-runtime/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-native/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-universal/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-universal/package.json","sodium-native":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-native/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-universal/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/which-runtime/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/which-runtime/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/which-runtime/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/lib/car.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/package.json","@ipld/dag-cbor":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/src/index.js","multiformats/cid":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/cid.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/lib/cid.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/package.json","@ipld/dag-cbor":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/src/index.js","@noble/hashes/sha2":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/sha2.js","multiformats/cid":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/cid.js","multiformats/codecs/raw":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/codecs/raw.js","multiformats/hashes/digest":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/hashes/digest.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/lib/commit.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/package.json","./cid.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/lib/cid.js","@ipld/dag-cbor":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/src/index.js","@noble/curves/secp256k1":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/secp256k1.js","@noble/hashes/sha2":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/sha2.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/lib/mst.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/package.json","./cid.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/lib/cid.js","@ipld/dag-cbor":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/src/index.js","@noble/hashes/sha2":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/sha2.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/lib/repo.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/package.json","./car.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/lib/car.js","./cid.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/lib/cid.js","./commit.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/lib/commit.js","./mst.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/lib/mst.js","@ipld/dag-cbor":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/src/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/src/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/package.json","cborg":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/cborg.js","multiformats/cid":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/cid.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/_shortw_utils.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json","./abstract/weierstrass.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/weierstrass.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/curve.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json","../utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/utils.js","./modular.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/modular.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/hash-to-curve.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json","../utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/utils.js","./modular.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/modular.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/modular.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json","../utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/utils.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/weierstrass.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json","../utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/utils.js","./curve.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/curve.js","./modular.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/modular.js","@noble/hashes/hmac.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/hmac.js","@noble/hashes/utils":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/secp256k1.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json","./_shortw_utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/_shortw_utils.js","./abstract/hash-to-curve.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/hash-to-curve.js","./abstract/modular.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/modular.js","./abstract/weierstrass.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/weierstrass.js","./utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/utils.js","@noble/hashes/sha2.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/sha2.js","@noble/hashes/utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/utils.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json","@noble/hashes/utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/_md.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json","./utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/_u64.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/crypto.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/hmac.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json","./utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/sha2.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json","./_md.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/_md.js","./_u64.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/_u64.js","./utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json","@noble/hashes/crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/crypto.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/cborg.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/package.json","./lib/decode.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/decode.js","./lib/encode.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/encode.js","./lib/tagged.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/tagged.js","./lib/token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/package.json","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/1negint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/2bytes.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./byte-utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/3string.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./2bytes.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/2bytes.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/4array.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/5map.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/6tag.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/7float.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/bl.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/package.json","./byte-utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/byte-utils.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/byte-utils.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/common.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/decode.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/package.json","./byte-utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./jump.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/jump.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/encode.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./1negint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/1negint.js","./2bytes.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/2bytes.js","./3string.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/3string.js","./4array.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/4array.js","./5map.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/5map.js","./6tag.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/6tag.js","./7float.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/7float.js","./bl.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/bl.js","./byte-utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./is.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/is.js","./jump.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/jump.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/is.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/jump.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./1negint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/1negint.js","./2bytes.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/2bytes.js","./3string.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/3string.js","./4array.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/4array.js","./5map.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/5map.js","./6tag.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/6tag.js","./7float.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/7float.js","./byte-utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/tagged.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/token.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/multiformats/package.json","../bytes.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/bytes.js","../vendor/base-x.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/vendor/base-x.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base32.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/multiformats/package.json","./base.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base36.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/multiformats/package.json","./base.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base58.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/multiformats/package.json","./base.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/bytes.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/multiformats/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/cid.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/multiformats/package.json","./bases/base32.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base32.js","./bases/base36.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base36.js","./bases/base58.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base58.js","./bytes.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/bytes.js","./hashes/digest.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/hashes/digest.js","./link/interface.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/link/interface.js","./varint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/varint.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/codecs/raw.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/multiformats/package.json","../bytes.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/bytes.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/hashes/digest.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/multiformats/package.json","../bytes.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/bytes.js","../varint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/varint.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/link/interface.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/multiformats/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/varint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/multiformats/package.json","./vendor/varint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/vendor/varint.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/vendor/base-x.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/multiformats/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/vendor/varint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/multiformats/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/multiformats/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/lib/lease.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/lib/membership.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/package.json","atproto-identity/lib/device-chain.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/lib/device-chain.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding/index.js","keet-identity-key":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/keet-identity-key/index.js","keet-identity-key/lib/encoding.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/keet-identity-key/lib/encoding.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/lib/pairing.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","blind-pairing":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-pairing/index.js","hypercore-crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/index.js","hyperswarm":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperswarm/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/lib/repo-base.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/lib/serve-membrane.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/package.json","@ipld/dag-cbor":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/@ipld/dag-cbor/src/index.js","atproto-identity/lib/discovery.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/lib/discovery.js","atproto-repo/lib/cid.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/lib/cid.js","atproto-repo/lib/mst.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/lib/mst.js","atproto-store/lib/repo-store.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/lib/repo-store.js","atproto-store/lib/sequencer.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/lib/sequencer.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding/index.js","multiformats/cid":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/multiformats/dist/src/cid.js","protomux":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux/index.js","protomux-rpc":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux-rpc/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/lib/signer-presence-channel.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/package.json","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding/index.js","protomux":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/lib/signer-presence.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/lib/signer.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/package.json","@ipld/dag-cbor":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/@ipld/dag-cbor/src/index.js","atproto-repo/lib/cid.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/lib/cid.js","atproto-repo/lib/commit.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/lib/commit.js","atproto-repo/lib/mst.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/lib/mst.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/lib/state-base.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/package.json","../spec/state-base/contract/hyperdb/index.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/spec/state-base/contract/hyperdb/index.js","../spec/state-base/contract/hyperdispatch/index.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/spec/state-base/contract/hyperdispatch/index.js","./signer-presence-channel.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/lib/signer-presence-channel.js","./signer-presence.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/lib/signer-presence.js","autobase":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/index.js","bare-fs":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-fs/index.js","bare-path":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-path/index.js","bare-process":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-process/index.js","corestore":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/corestore/index.js","hypercore":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/index.js","hypercore-crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/index.js","hypercore/lib/verifier":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/verifier.js","hyperdb":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdb/index.js","hyperswarm":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperswarm/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/@hyperswarm/secret-stream/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/@hyperswarm/secret-stream/package.json","./lib/bridge":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/@hyperswarm/secret-stream/lib/bridge.js","./lib/handshake":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/@hyperswarm/secret-stream/lib/handshake.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","hypercore-crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/index.js","sodium-secretstream":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-secretstream/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-universal/index.js","streamx":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/streamx/index.js","timeout-refresh":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/timeout-refresh/index.js","unslab":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/unslab/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/@hyperswarm/secret-stream/lib/bridge.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/@hyperswarm/secret-stream/package.json","streamx":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/streamx/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/@hyperswarm/secret-stream/lib/handshake.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/@hyperswarm/secret-stream/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","noise-curve-ed":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-curve-ed/index.js","noise-handshake":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-handshake/noise.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/@hyperswarm/secret-stream/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/@ipld/dag-cbor/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/@ipld/dag-cbor/src/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/@ipld/dag-cbor/package.json","cborg":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/cborg.js","multiformats/cid":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/multiformats/dist/src/cid.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/adaptive-timeout/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/adaptive-timeout/package.json","xache":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/xache/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/adaptive-timeout/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/lib/device-chain.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/b4a/index.js","keet-identity-key":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/keet-identity-key/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/lib/discovery.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/package.json","hypercore-crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/hypercore-crypto/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/b4a/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/b4a/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/b4a/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bare-ansi-escapes/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bare-ansi-escapes/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bare-ansi-escapes/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bare-assert/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bare-assert/package.json","bare-inspect":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bare-inspect/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bare-assert/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bare-inspect/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bare-inspect/package.json",".":"linked:libbare-inspect.3.1.4.so"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bare-inspect/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bare-inspect/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bare-inspect/binding.js","bare-ansi-escapes":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bare-ansi-escapes/index.js","bare-type":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bare-type/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bare-inspect/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bare-type/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bare-type/package.json",".":"linked:libbare-type.1.1.0.so"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bare-type/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bare-type/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bare-type/binding.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bare-type/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bip39-mnemonic/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json","./wordlist":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/index.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/b4a/index.js","nanoassert":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/nanoassert/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/chinese_simplified.json":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/chinese_traditional.json":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/czech.json":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/english.json":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/french.json":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json","./chinese_simplified.json":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/chinese_simplified.json","./chinese_traditional.json":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/chinese_traditional.json","./czech.json":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/czech.json","./english.json":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/english.json","./french.json":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/french.json","./italian.json":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/italian.json","./japanese.json":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/japanese.json","./korean.json":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/korean.json","./lookup.json":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/lookup.json","./portuguese.json":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/portuguese.json","./russian.json":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/russian.json","./spanish.json":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/spanish.json","./turkish.json":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/turkish.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/italian.json":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/japanese.json":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/korean.json":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/lookup.json":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/portuguese.json":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/russian.json":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/spanish.json":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/turkish.json":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/compact-encoding/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/compact-encoding/raw.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/compact-encoding/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/compact-encoding/endian.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/hypercore-crypto/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/hypercore-crypto/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/compact-encoding/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/hypercore-crypto/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/keet-identity-key/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/keet-identity-key/package.json","./lib/crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/keet-identity-key/lib/crypto.js","./lib/encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/keet-identity-key/lib/encoding.js","./lib/keychain":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/keet-identity-key/lib/keychain.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/compact-encoding/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/keet-identity-key/lib/crypto.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/keet-identity-key/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/b4a/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/keet-identity-key/lib/encoding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/keet-identity-key/package.json","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/compact-encoding/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/keet-identity-key/lib/keychain.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/keet-identity-key/package.json","./crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/keet-identity-key/lib/crypto.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/b4a/index.js","bip39-mnemonic":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bip39-mnemonic/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/compact-encoding/index.js","nanoassert":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/nanoassert/index.js","sodium-hmac":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/sodium-hmac/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/keet-identity-key/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/nanoassert/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/nanoassert/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/nanoassert/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/require-addon/lib/bare.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/require-addon/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/require-addon/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/sodium-hmac/hash/sha256.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/sodium-hmac/package.json","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/sodium-hmac/hash/sha512.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/sodium-hmac/package.json","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/sodium-hmac/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/sodium-hmac/package.json","./hash/sha256":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/sodium-hmac/hash/sha256.js","./hash/sha512":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/sodium-hmac/hash/sha512.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/sodium-hmac/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/sodium-native/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/sodium-native/package.json",".":"linked:libsodium-native.5.1.0.so","require-addon":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/require-addon/lib/bare.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/sodium-native/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/sodium-native/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/sodium-native/binding.js","assert":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bare-assert/index.js","which-runtime":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/which-runtime/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/sodium-native/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/sodium-universal/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/sodium-universal/package.json","sodium-native":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/sodium-native/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/sodium-universal/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/which-runtime/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/which-runtime/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/which-runtime/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/lib/cid.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/package.json","@ipld/dag-cbor":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/src/index.js","@noble/hashes/sha2":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/hashes/esm/sha2.js","multiformats/cid":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/multiformats/dist/src/cid.js","multiformats/codecs/raw":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/multiformats/dist/src/codecs/raw.js","multiformats/hashes/digest":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/multiformats/dist/src/hashes/digest.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/lib/commit.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/package.json","./cid.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/lib/cid.js","@ipld/dag-cbor":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/src/index.js","@noble/curves/secp256k1":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/curves/esm/secp256k1.js","@noble/hashes/sha2":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/hashes/esm/sha2.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/lib/mst.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/package.json","./cid.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/lib/cid.js","@ipld/dag-cbor":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/src/index.js","@noble/hashes/sha2":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/hashes/esm/sha2.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/src/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/package.json","cborg":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/cborg.js","multiformats/cid":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/multiformats/dist/src/cid.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/curves/esm/_shortw_utils.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json","./abstract/weierstrass.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/weierstrass.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/curve.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json","../utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/curves/esm/utils.js","./modular.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/modular.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/hash-to-curve.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json","../utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/curves/esm/utils.js","./modular.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/modular.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/modular.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json","../utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/curves/esm/utils.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/weierstrass.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json","../utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/curves/esm/utils.js","./curve.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/curve.js","./modular.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/modular.js","@noble/hashes/hmac.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/hashes/esm/hmac.js","@noble/hashes/utils":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/curves/esm/secp256k1.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json","./_shortw_utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/curves/esm/_shortw_utils.js","./abstract/hash-to-curve.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/hash-to-curve.js","./abstract/modular.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/modular.js","./abstract/weierstrass.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/weierstrass.js","./utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/curves/esm/utils.js","@noble/hashes/sha2.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/hashes/esm/sha2.js","@noble/hashes/utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/curves/esm/utils.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json","@noble/hashes/utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/hashes/esm/_md.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json","./utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/hashes/esm/_u64.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/hashes/esm/crypto.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/hashes/esm/hmac.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json","./utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/hashes/esm/sha2.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json","./_md.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/hashes/esm/_md.js","./_u64.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/hashes/esm/_u64.js","./utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json","@noble/hashes/crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/hashes/esm/crypto.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/cborg.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/package.json","./lib/decode.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/decode.js","./lib/encode.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/encode.js","./lib/tagged.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/tagged.js","./lib/token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/package.json","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/1negint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/2bytes.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./byte-utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/3string.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./2bytes.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/2bytes.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/4array.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/5map.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/6tag.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/7float.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/bl.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/package.json","./byte-utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/byte-utils.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/byte-utils.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/common.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/decode.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/package.json","./byte-utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./jump.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/jump.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/encode.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./1negint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/1negint.js","./2bytes.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/2bytes.js","./3string.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/3string.js","./4array.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/4array.js","./5map.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/5map.js","./6tag.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/6tag.js","./7float.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/7float.js","./bl.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/bl.js","./byte-utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./is.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/is.js","./jump.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/jump.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/is.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/jump.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./1negint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/1negint.js","./2bytes.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/2bytes.js","./3string.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/3string.js","./4array.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/4array.js","./5map.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/5map.js","./6tag.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/6tag.js","./7float.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/7float.js","./byte-utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/tagged.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/token.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/multiformats/package.json","../bytes.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/multiformats/dist/src/bytes.js","../vendor/base-x.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/multiformats/dist/src/vendor/base-x.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base32.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/multiformats/package.json","./base.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base36.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/multiformats/package.json","./base.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base58.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/multiformats/package.json","./base.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/multiformats/dist/src/bytes.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/multiformats/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/multiformats/dist/src/cid.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/multiformats/package.json","./bases/base32.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base32.js","./bases/base36.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base36.js","./bases/base58.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base58.js","./bytes.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/multiformats/dist/src/bytes.js","./hashes/digest.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/multiformats/dist/src/hashes/digest.js","./link/interface.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/multiformats/dist/src/link/interface.js","./varint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/multiformats/dist/src/varint.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/multiformats/dist/src/codecs/raw.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/multiformats/package.json","../bytes.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/multiformats/dist/src/bytes.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/multiformats/dist/src/hashes/digest.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/multiformats/package.json","../bytes.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/multiformats/dist/src/bytes.js","../varint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/multiformats/dist/src/varint.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/multiformats/dist/src/link/interface.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/multiformats/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/multiformats/dist/src/varint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/multiformats/package.json","./vendor/varint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/multiformats/dist/src/vendor/varint.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/multiformats/dist/src/vendor/base-x.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/multiformats/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/multiformats/dist/src/vendor/varint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/multiformats/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/multiformats/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/lib/corestore.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/package.json","corestore":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/corestore/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/lib/firehose.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/package.json","@ipld/dag-cbor":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/@ipld/dag-cbor/src/index.js","atproto-repo/lib/commit.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/lib/commit.js","atproto-repo/lib/repo.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/lib/repo.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/lib/repo-store.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/package.json","./corestore.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/lib/corestore.js","@ipld/dag-cbor":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/@ipld/dag-cbor/src/index.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/b4a/index.js","corestore":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/corestore/index.js","hyperbee":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hyperbee/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/lib/sequencer.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/package.json","./firehose.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/lib/firehose.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/@hyperswarm/secret-stream/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/@hyperswarm/secret-stream/package.json","./lib/bridge":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/@hyperswarm/secret-stream/lib/bridge.js","./lib/handshake":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/@hyperswarm/secret-stream/lib/handshake.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/b4a/index.js","hypercore-crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-crypto/index.js","sodium-secretstream":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/sodium-secretstream/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/sodium-universal/index.js","streamx":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/streamx/index.js","timeout-refresh":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/timeout-refresh/index.js","unslab":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/unslab/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/@hyperswarm/secret-stream/lib/bridge.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/@hyperswarm/secret-stream/package.json","streamx":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/streamx/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/@hyperswarm/secret-stream/lib/handshake.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/@hyperswarm/secret-stream/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/b4a/index.js","noise-curve-ed":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/noise-curve-ed/index.js","noise-handshake":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/noise-handshake/noise.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/@hyperswarm/secret-stream/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/@ipld/dag-cbor/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/@ipld/dag-cbor/src/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/@ipld/dag-cbor/package.json","cborg":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/cborg.js","multiformats/cid":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/multiformats/dist/src/cid.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/lib/car.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/package.json","@ipld/dag-cbor":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/src/index.js","multiformats/cid":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/cid.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/lib/cid.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/package.json","@ipld/dag-cbor":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/src/index.js","@noble/hashes/sha2":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/sha2.js","multiformats/cid":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/cid.js","multiformats/codecs/raw":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/codecs/raw.js","multiformats/hashes/digest":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/hashes/digest.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/lib/commit.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/package.json","./cid.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/lib/cid.js","@ipld/dag-cbor":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/src/index.js","@noble/curves/secp256k1":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/secp256k1.js","@noble/hashes/sha2":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/sha2.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/lib/mst.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/package.json","./cid.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/lib/cid.js","@ipld/dag-cbor":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/src/index.js","@noble/hashes/sha2":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/sha2.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/lib/repo.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/package.json","./car.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/lib/car.js","./cid.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/lib/cid.js","./commit.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/lib/commit.js","./mst.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/lib/mst.js","@ipld/dag-cbor":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/src/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/src/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/package.json","cborg":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/cborg.js","multiformats/cid":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/cid.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/_shortw_utils.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json","./abstract/weierstrass.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/weierstrass.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/curve.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json","../utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/utils.js","./modular.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/modular.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/hash-to-curve.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json","../utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/utils.js","./modular.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/modular.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/modular.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json","../utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/utils.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/weierstrass.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json","../utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/utils.js","./curve.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/curve.js","./modular.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/modular.js","@noble/hashes/hmac.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/hmac.js","@noble/hashes/utils":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/secp256k1.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json","./_shortw_utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/_shortw_utils.js","./abstract/hash-to-curve.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/hash-to-curve.js","./abstract/modular.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/modular.js","./abstract/weierstrass.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/weierstrass.js","./utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/utils.js","@noble/hashes/sha2.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/sha2.js","@noble/hashes/utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/utils.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json","@noble/hashes/utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/_md.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json","./utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/_u64.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/crypto.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/hmac.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json","./utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/sha2.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json","./_md.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/_md.js","./_u64.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/_u64.js","./utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json","@noble/hashes/crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/crypto.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/cborg.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json","./lib/decode.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/decode.js","./lib/encode.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/encode.js","./lib/tagged.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/tagged.js","./lib/token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/1negint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/2bytes.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./byte-utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/3string.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./2bytes.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/2bytes.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/4array.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/5map.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/6tag.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/7float.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/bl.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json","./byte-utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/byte-utils.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/byte-utils.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/common.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/decode.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json","./byte-utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./jump.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/jump.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/encode.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./1negint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/1negint.js","./2bytes.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/2bytes.js","./3string.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/3string.js","./4array.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/4array.js","./5map.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/5map.js","./6tag.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/6tag.js","./7float.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/7float.js","./bl.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/bl.js","./byte-utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./is.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/is.js","./jump.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/jump.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/is.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/jump.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./1negint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/1negint.js","./2bytes.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/2bytes.js","./3string.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/3string.js","./4array.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/4array.js","./5map.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/5map.js","./6tag.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/6tag.js","./7float.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/7float.js","./byte-utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/tagged.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/token.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/package.json","../bytes.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bytes.js","../vendor/base-x.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/vendor/base-x.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base32.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/package.json","./base.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base36.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/package.json","./base.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base58.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/package.json","./base.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bytes.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/cid.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/package.json","./bases/base32.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base32.js","./bases/base36.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base36.js","./bases/base58.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base58.js","./bytes.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bytes.js","./hashes/digest.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/hashes/digest.js","./link/interface.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/link/interface.js","./varint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/varint.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/codecs/raw.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/package.json","../bytes.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bytes.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/hashes/digest.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/package.json","../bytes.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bytes.js","../varint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/varint.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/link/interface.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/varint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/package.json","./vendor/varint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/vendor/varint.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/vendor/base-x.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/vendor/varint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/b4a/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/b4a/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/b4a/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-ansi-escapes/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-ansi-escapes/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-ansi-escapes/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-assert/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-assert/package.json","bare-inspect":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-inspect/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-assert/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-events/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-events/package.json","./lib/errors":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-events/lib/errors.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-events/lib/errors.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-events/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-events/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-fs/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-fs/package.json",".":"linked:libbare-fs.4.7.3.so"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-fs/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-fs/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-fs/binding.js","./lib/constants":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-fs/lib/constants.js","./lib/errors":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-fs/lib/errors.js","./promises":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-fs/promises.js","bare-events":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-events/index.js","bare-path":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-path/index.js","bare-stream":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-stream/index.js","bare-url":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-url/index.js","fast-fifo":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/fast-fifo/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-fs/lib/constants.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-fs/package.json","../binding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-fs/binding.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-fs/lib/errors.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-fs/package.json","bare-os":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-os/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-fs/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-fs/promises.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-fs/package.json",".":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-fs/index.js","bare-events":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-events/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-inspect/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-inspect/package.json",".":"linked:libbare-inspect.3.1.4.so"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-inspect/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-inspect/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-inspect/binding.js","bare-ansi-escapes":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-ansi-escapes/index.js","bare-type":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-type/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-inspect/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-os/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-os/package.json",".":"linked:libbare-os.3.9.3.so"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-os/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-os/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-os/binding.js","./lib/constants":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-os/lib/constants.js","./lib/errors":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-os/lib/errors.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-os/lib/constants.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-os/package.json","../binding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-os/binding.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-os/lib/errors.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-os/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-os/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-path/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-path/package.json","./lib/posix":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-path/lib/posix.js","./lib/win32":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-path/lib/win32.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-path/lib/constants.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-path/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-path/lib/posix.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-path/package.json","./constants":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-path/lib/constants.js","./shared":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-path/lib/shared.js","./win32":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-path/lib/win32.js","bare-os":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-os/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-path/lib/shared.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-path/package.json","./constants":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-path/lib/constants.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-path/lib/win32.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-path/package.json","./constants":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-path/lib/constants.js","./posix":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-path/lib/posix.js","./shared":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-path/lib/shared.js","bare-os":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-os/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-path/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-stream/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-stream/package.json","./web":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-stream/web.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/b4a/index.js","streamx":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/streamx/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-stream/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-stream/web.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-stream/package.json","streamx":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/streamx/index.js","teex":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/teex/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-type/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-type/package.json",".":"linked:libbare-type.1.1.0.so"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-type/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-type/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-type/binding.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-type/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-url/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-url/package.json",".":"linked:libbare-url.2.4.5.so"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-url/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-url/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-url/binding.js","./lib/errors":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-url/lib/errors.js","./lib/url-search-params":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-url/lib/url-search-params.js","bare-path":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-path/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-url/lib/errors.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-url/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-url/lib/url-search-params.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-url/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-url/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/big-sparse-array/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/big-sparse-array/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/big-sparse-array/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/cborg.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/package.json","./lib/decode.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/decode.js","./lib/encode.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/encode.js","./lib/tagged.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/tagged.js","./lib/token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/0uint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/package.json","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/1negint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/2bytes.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/0uint.js","./byte-utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/3string.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/0uint.js","./2bytes.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/2bytes.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/4array.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/5map.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/6tag.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/0uint.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/7float.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/bl.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/package.json","./byte-utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/byte-utils.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/byte-utils.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/common.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/decode.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/package.json","./byte-utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/common.js","./jump.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/jump.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/encode.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/0uint.js","./1negint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/1negint.js","./2bytes.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/2bytes.js","./3string.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/3string.js","./4array.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/4array.js","./5map.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/5map.js","./6tag.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/6tag.js","./7float.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/7float.js","./bl.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/bl.js","./byte-utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/common.js","./is.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/is.js","./jump.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/jump.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/is.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/jump.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/0uint.js","./1negint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/1negint.js","./2bytes.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/2bytes.js","./3string.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/3string.js","./4array.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/4array.js","./5map.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/5map.js","./6tag.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/6tag.js","./7float.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/7float.js","./byte-utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/tagged.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/token.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/codecs/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/codecs/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/codecs/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/compact-encoding/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/compact-encoding/raw.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/compact-encoding/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/compact-encoding/endian.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/corestore/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/corestore/package.json","./lib/audit.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/corestore/lib/audit.js","./lib/notify.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/corestore/lib/notify.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/b4a/index.js","hypercore":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/index.js","hypercore-crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-crypto/index.js","hypercore-errors":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-errors/index.js","hypercore-id-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-id-encoding/index.js","ready-resource":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/ready-resource/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/sodium-universal/index.js","which-runtime":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/which-runtime/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/corestore/lib/audit.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/corestore/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/corestore/lib/notify.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/corestore/package.json","events":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-events/index.js","streamx":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/streamx/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/corestore/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/debounceify/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/debounceify/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/debounceify/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/device-file/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/device-file/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/b4a/index.js","fd-lock":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/fd-lock/index.js","fs":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-fs/index.js","fs-native-extensions":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/fs-native-extensions/index.js","path":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-path/index.js","ready-resource":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/ready-resource/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/device-file/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/events-universal/bare.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/events-universal/package.json","bare-events":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-events/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/events-universal/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/fast-fifo/fixed-size.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/fast-fifo/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/fast-fifo/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/fast-fifo/package.json","./fixed-size":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/fast-fifo/fixed-size.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/fast-fifo/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/fd-lock/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/fd-lock/package.json","fs":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-fs/index.js","fs-native-extensions":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/fs-native-extensions/index.js","ready-resource":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/ready-resource/index.js","resource-on-exit":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/resource-on-exit/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/fd-lock/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/flat-tree/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/flat-tree/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/flat-tree/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/fs-native-extensions/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/fs-native-extensions/package.json",".":"linked:libfs-native-extensions.1.5.0.so","require-addon":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/require-addon/lib/bare.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/fs-native-extensions/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/fs-native-extensions/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/fs-native-extensions/binding.js","which-runtime":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/which-runtime/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/fs-native-extensions/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hyperbee/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hyperbee/package.json","./iterators/diff":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hyperbee/iterators/diff.js","./iterators/history":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hyperbee/iterators/history.js","./iterators/local":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hyperbee/iterators/local.js","./iterators/range":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hyperbee/iterators/range.js","./lib/extension":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hyperbee/lib/extension.js","./lib/messages":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hyperbee/lib/messages.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/b4a/index.js","codecs":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/codecs/index.js","debounceify":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/debounceify/index.js","hypercore-errors":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-errors/index.js","mutexify/promise":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/mutexify/promise.js","rache":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/rache/index.js","ready-resource":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/ready-resource/index.js","resolve-reject-promise":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/resolve-reject-promise/index.js","safety-catch":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/safety-catch/index.js","streamx":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/streamx/index.js","unslab":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/unslab/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hyperbee/iterators/diff.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hyperbee/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hyperbee/iterators/history.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hyperbee/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hyperbee/iterators/local.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hyperbee/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hyperbee/iterators/range.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hyperbee/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hyperbee/lib/extension.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hyperbee/package.json","./messages":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hyperbee/lib/messages.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hyperbee/lib/messages.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hyperbee/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/b4a/index.js","protocol-buffers-encodings":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/protocol-buffers-encodings/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hyperbee/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-crypto/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-crypto/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/compact-encoding/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-crypto/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-errors/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-errors/package.json","hypercore-id-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-id-encoding/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-errors/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-id-encoding/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-id-encoding/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/b4a/index.js","z32":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/z32/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-id-encoding/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-storage/encoding/external.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-storage/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-storage/encoding/spec/hyperschema/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-storage/package.json","../../external.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-storage/encoding/external.js","hyperschema/runtime":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hyperschema/runtime.cjs"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-storage/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-storage/package.json","./lib/keys.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-storage/lib/keys.js","./lib/streams.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-storage/lib/streams.js","./lib/tx.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-storage/lib/tx.js","./lib/view.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-storage/lib/view.js","./migrations/0":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-storage/migrations/0/index.js","./migrations/1":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-storage/migrations/1/index.js","device-file":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/device-file/index.js","fs":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-fs/index.js","path":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-path/index.js","resolve-reject-promise":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/resolve-reject-promise/index.js","rocksdb-native":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/rocksdb-native/index.js","scope-lock":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/scope-lock/index.js","xache":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/xache/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-storage/lib/block-dependency-stream.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-storage/package.json","./keys":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-storage/lib/keys.js","streamx":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/streamx/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-storage/lib/close-error-stream.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-storage/package.json","streamx":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/streamx/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-storage/lib/keys.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-storage/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/compact-encoding/index.js","index-encoder":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/index-encoder/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-storage/lib/streams.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-storage/package.json","../encoding/spec/hyperschema":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-storage/encoding/spec/hyperschema/index.js","./block-dependency-stream.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-storage/lib/block-dependency-stream.js","./keys.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-storage/lib/keys.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-storage/lib/tx.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-storage/package.json","../encoding/spec/hyperschema":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-storage/encoding/spec/hyperschema/index.js","./keys.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-storage/lib/keys.js","./view.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-storage/lib/view.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/compact-encoding/index.js","flat-tree":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/flat-tree/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-storage/lib/view.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-storage/package.json","./close-error-stream.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-storage/lib/close-error-stream.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/b4a/index.js","streamx":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/streamx/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-storage/migrations/0/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-storage/package.json","../../lib/tx.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-storage/lib/tx.js","../../lib/view.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-storage/lib/view.js","./messages.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-storage/migrations/0/messages.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/compact-encoding/index.js","flat-tree":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/flat-tree/index.js","fs":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-fs/index.js","hypercore-crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-crypto/index.js","path":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-path/index.js","streamx":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/streamx/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-storage/migrations/0/messages.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-storage/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/compact-encoding/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-storage/migrations/1/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-storage/package.json","../../encoding/spec/hyperschema":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-storage/encoding/spec/hyperschema/index.js","../../lib/keys.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-storage/lib/keys.js","../../lib/tx.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-storage/lib/tx.js","../../lib/view.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-storage/lib/view.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/compact-encoding/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-storage/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/package.json","./lib/caps":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/caps.js","./lib/core":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/core.js","./lib/default-encryption":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/default-encryption.js","./lib/download":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/download.js","./lib/feature-flags":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/feature-flags.js","./lib/fully-remote-proof":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/fully-remote-proof.js","./lib/info":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/info.js","./lib/inspect":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/inspect.js","./lib/mark-bitfield":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/mark-bitfield.js","./lib/merkle-tree":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/merkle-tree.js","./lib/replicator":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/replicator.js","./lib/streams":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/streams.js","./lib/verifier":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/verifier.js","./lib/wants":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/wants.js","@hyperswarm/secret-stream":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/@hyperswarm/secret-stream/index.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/compact-encoding/index.js","events":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-events/index.js","flat-tree":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/flat-tree/index.js","hypercore-crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-crypto/index.js","hypercore-errors":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-errors/index.js","hypercore-id-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-id-encoding/index.js","hypercore-storage":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-storage/index.js","is-options":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/is-options/index.js","nanoassert":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/nanoassert/index.js","protomux":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/protomux/index.js","safety-catch":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/safety-catch/index.js","unslab":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/unslab/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/audit.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/package.json","./merkle-tree":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/merkle-tree.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/b4a/index.js","flat-tree":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/flat-tree/index.js","hypercore-crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-crypto/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/bit-interlude.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/package.json","./compat":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/compat.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/bitfield.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/package.json","./compat":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/compat.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/b4a/index.js","big-sparse-array":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/big-sparse-array/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/caps.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/compact-encoding/index.js","hypercore-crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-crypto/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/compat.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/package.json","quickbit-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/quickbit-universal/index.js","quickbit-universal/fallback":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/quickbit-universal/fallback.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/copy-prologue.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/package.json","./bitfield":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/bitfield.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/b4a/index.js","flat-tree":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/flat-tree/index.js","hypercore-crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-crypto/index.js","quickbit-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/quickbit-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/core.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/package.json","./audit":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/audit.js","./bit-interlude":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/bit-interlude.js","./bitfield":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/bitfield.js","./copy-prologue":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/copy-prologue.js","./merkle-tree":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/merkle-tree.js","./mutex":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/mutex.js","./remote-bitfield":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/remote-bitfield.js","./replicator":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/replicator.js","./session-state":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/session-state.js","./verifier":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/verifier.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/b4a/index.js","hypercore-crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-crypto/index.js","hypercore-errors":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-errors/index.js","unslab":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/unslab/index.js","z32":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/z32/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/default-encryption.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/package.json","./caps":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/caps.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/compact-encoding/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/download.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/feature-flags.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/fully-remote-proof.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/package.json","./merkle-tree.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/merkle-tree.js","./messages.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/messages.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/compact-encoding/index.js","flat-tree":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/flat-tree/index.js","hypercore-crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-crypto/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/hotswap-queue.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/info.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/inspect.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/mark-bitfield.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/package.json","./compat":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/compat.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/b4a/index.js","big-sparse-array":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/big-sparse-array/index.js","streamx":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/streamx/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/merkle-tree.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/package.json","./caps":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/caps.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/b4a/index.js","flat-tree":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/flat-tree/index.js","hypercore-crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-crypto/index.js","hypercore-errors":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-errors/index.js","unslab":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/unslab/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/messages.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/package.json","./caps":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/caps.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/compact-encoding/index.js","hypercore-errors":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-errors/index.js","unslab":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/unslab/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/multisig.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/package.json","./merkle-tree":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/merkle-tree.js","./messages":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/messages.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/compact-encoding/index.js","flat-tree":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/flat-tree/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/mutex.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/receiver-queue.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/package.json","fast-fifo":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/fast-fifo/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/remote-bitfield.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/package.json","./compat":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/compat.js","big-sparse-array":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/big-sparse-array/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/replicator.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/package.json","./caps":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/caps.js","./hotswap-queue":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/hotswap-queue.js","./merkle-tree":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/merkle-tree.js","./messages":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/messages.js","./mutex":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/mutex.js","./receiver-queue":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/receiver-queue.js","./remote-bitfield":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/remote-bitfield.js","./wants":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/wants.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/b4a/index.js","flat-tree":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/flat-tree/index.js","hypercore-errors":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-errors/index.js","random-array-iterator":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/random-array-iterator/index.js","safety-catch":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/safety-catch/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/session-state.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/package.json","./bitfield":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/bitfield.js","./merkle-tree":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/merkle-tree.js","./mutex":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/mutex.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/b4a/index.js","flat-tree":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/flat-tree/index.js","hypercore-crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-crypto/index.js","hypercore-errors":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-errors/index.js","hypercore-storage":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-storage/index.js","nanoassert":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/nanoassert/index.js","quickbit-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/quickbit-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/streams.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/package.json","streamx":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/streamx/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/verifier.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/package.json","./caps":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/caps.js","./messages":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/messages.js","./multisig":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/multisig.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/compact-encoding/index.js","flat-tree":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/flat-tree/index.js","hypercore-crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-crypto/index.js","hypercore-errors":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-errors/index.js","unslab":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/unslab/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/wants.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hyperschema/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hyperschema/runtime.cjs":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hyperschema/package.json","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/compact-encoding/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/index-encoder/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/index-encoder/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/index-encoder/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/is-options/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/is-options/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/is-options/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/multiformats/dist/src/bases/base.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/multiformats/package.json","../bytes.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/multiformats/dist/src/bytes.js","../vendor/base-x.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/multiformats/dist/src/vendor/base-x.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/multiformats/dist/src/bases/base32.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/multiformats/package.json","./base.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/multiformats/dist/src/bases/base.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/multiformats/dist/src/bases/base36.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/multiformats/package.json","./base.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/multiformats/dist/src/bases/base.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/multiformats/dist/src/bases/base58.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/multiformats/package.json","./base.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/multiformats/dist/src/bases/base.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/multiformats/dist/src/bytes.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/multiformats/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/multiformats/dist/src/cid.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/multiformats/package.json","./bases/base32.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/multiformats/dist/src/bases/base32.js","./bases/base36.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/multiformats/dist/src/bases/base36.js","./bases/base58.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/multiformats/dist/src/bases/base58.js","./bytes.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/multiformats/dist/src/bytes.js","./hashes/digest.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/multiformats/dist/src/hashes/digest.js","./link/interface.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/multiformats/dist/src/link/interface.js","./varint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/multiformats/dist/src/varint.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/multiformats/dist/src/hashes/digest.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/multiformats/package.json","../bytes.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/multiformats/dist/src/bytes.js","../varint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/multiformats/dist/src/varint.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/multiformats/dist/src/link/interface.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/multiformats/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/multiformats/dist/src/varint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/multiformats/package.json","./vendor/varint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/multiformats/dist/src/vendor/varint.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/multiformats/dist/src/vendor/base-x.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/multiformats/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/multiformats/dist/src/vendor/varint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/multiformats/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/multiformats/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/mutexify/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/mutexify/package.json","queue-tick":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/queue-tick/process-next-tick.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/mutexify/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/mutexify/promise.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/mutexify/package.json",".":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/mutexify/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/nanoassert/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/nanoassert/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/nanoassert/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/noise-curve-ed/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/noise-curve-ed/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/b4a/index.js","nanoassert":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/nanoassert/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/noise-curve-ed/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/noise-handshake/cipher.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/noise-handshake/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/b4a/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/noise-handshake/dh.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/noise-handshake/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/b4a/index.js","nanoassert":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/nanoassert/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/noise-handshake/hkdf.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/noise-handshake/package.json","./hmac":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/noise-handshake/hmac.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/noise-handshake/hmac.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/noise-handshake/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/b4a/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/noise-handshake/noise.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/noise-handshake/package.json","./hkdf":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/noise-handshake/hkdf.js","./symmetric-state":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/noise-handshake/symmetric-state.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/b4a/index.js","nanoassert":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/nanoassert/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/noise-handshake/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/noise-handshake/symmetric-state.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/noise-handshake/package.json","./cipher":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/noise-handshake/cipher.js","./dh":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/noise-handshake/dh.js","./hkdf":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/noise-handshake/hkdf.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/b4a/index.js","nanoassert":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/nanoassert/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/protocol-buffers-encodings/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/protocol-buffers-encodings/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/b4a/index.js","signed-varint":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/signed-varint/index.js","varint":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/varint/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/protocol-buffers-encodings/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/protomux/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/protomux/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/compact-encoding/index.js","queue-tick":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/queue-tick/process-next-tick.js","safety-catch":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/safety-catch/index.js","unslab":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/unslab/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/protomux/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/queue-tick/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/queue-tick/process-next-tick.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/queue-tick/package.json","./queue-microtask":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/queue-tick/queue-microtask.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/queue-tick/queue-microtask.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/queue-tick/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/quickbit-native/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/quickbit-native/package.json",".":"linked:libquickbit-native.2.4.8.so","require-addon":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/require-addon/lib/bare.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/quickbit-native/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/quickbit-native/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/quickbit-native/binding.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/quickbit-native/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/quickbit-universal/fallback.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/quickbit-universal/package.json","simdle-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/simdle-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/quickbit-universal/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/quickbit-universal/package.json","./fallback":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/quickbit-universal/fallback.js","quickbit-native":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/quickbit-native/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/quickbit-universal/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/rache/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/rache/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/rache/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/random-array-iterator/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/random-array-iterator/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/random-array-iterator/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/ready-resource/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/ready-resource/package.json","events":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-events/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/ready-resource/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/refcounter/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/refcounter/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/refcounter/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/require-addon/lib/bare.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/require-addon/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/require-addon/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/resolve-reject-promise/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/resolve-reject-promise/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/resolve-reject-promise/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/resource-on-exit/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/resource-on-exit/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/resource-on-exit/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/rocksdb-native/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/rocksdb-native/package.json",".":"linked:librocksdb-native.3.17.2.so","require-addon":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/require-addon/lib/bare.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/rocksdb-native/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/rocksdb-native/package.json","./lib/column-family":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/rocksdb-native/lib/column-family.js","./lib/constants":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/rocksdb-native/lib/constants.js","./lib/filter-policy":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/rocksdb-native/lib/filter-policy.js","./lib/iterator":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/rocksdb-native/lib/iterator.js","./lib/snapshot":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/rocksdb-native/lib/snapshot.js","./lib/state":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/rocksdb-native/lib/state.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/rocksdb-native/lib/batch.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/rocksdb-native/package.json","../binding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/rocksdb-native/binding.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/compact-encoding/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/rocksdb-native/lib/column-family.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/rocksdb-native/package.json","../binding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/rocksdb-native/binding.js","./constants":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/rocksdb-native/lib/constants.js","./filter-policy":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/rocksdb-native/lib/filter-policy.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/rocksdb-native/lib/constants.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/rocksdb-native/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/rocksdb-native/lib/filter-policy.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/rocksdb-native/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/rocksdb-native/lib/iterator.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/rocksdb-native/package.json","../binding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/rocksdb-native/binding.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/compact-encoding/index.js","streamx":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/streamx/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/rocksdb-native/lib/snapshot.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/rocksdb-native/package.json","../binding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/rocksdb-native/binding.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/rocksdb-native/lib/state.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/rocksdb-native/package.json","../binding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/rocksdb-native/binding.js","./batch":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/rocksdb-native/lib/batch.js","./column-family":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/rocksdb-native/lib/column-family.js","./constants":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/rocksdb-native/lib/constants.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/compact-encoding/index.js","ready-resource":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/ready-resource/index.js","refcounter":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/refcounter/index.js","resolve-reject-promise":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/resolve-reject-promise/index.js","signal-promise":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/signal-promise/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/rocksdb-native/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/safety-catch/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/safety-catch/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/safety-catch/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/scope-lock/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/scope-lock/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/scope-lock/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/signal-promise/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/signal-promise/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/signal-promise/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/signed-varint/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/signed-varint/package.json","varint":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/varint/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/signed-varint/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/simdle-native/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/simdle-native/package.json",".":"linked:libsimdle-native.1.3.9.so","require-addon":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/require-addon/lib/bare.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/simdle-native/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/simdle-native/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/simdle-native/binding.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/simdle-native/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/simdle-universal/fallback.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/simdle-universal/package.json","./scalar":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/simdle-universal/scalar.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/simdle-universal/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/simdle-universal/package.json","./fallback":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/simdle-universal/fallback.js","simdle-native":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/simdle-native/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/simdle-universal/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/simdle-universal/scalar.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/simdle-universal/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/sodium-native/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/sodium-native/package.json",".":"linked:libsodium-native.5.1.0.so","require-addon":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/require-addon/lib/bare.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/sodium-native/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/sodium-native/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/sodium-native/binding.js","assert":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-assert/index.js","which-runtime":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/which-runtime/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/sodium-native/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/sodium-secretstream/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/sodium-secretstream/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/b4a/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/sodium-secretstream/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/sodium-universal/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/sodium-universal/package.json","sodium-native":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/sodium-native/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/sodium-universal/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/streamx/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/streamx/package.json","./lib/errors.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/streamx/lib/errors.js","events-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/events-universal/bare.js","fast-fifo":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/fast-fifo/index.js","text-decoder":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/text-decoder/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/streamx/lib/errors.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/streamx/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/streamx/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/teex/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/teex/package.json","streamx":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/streamx/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/teex/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/text-decoder/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/text-decoder/package.json","./lib/pass-through-decoder":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/text-decoder/lib/pass-through-decoder.js","./lib/utf8-decoder":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/text-decoder/lib/utf8-decoder.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/text-decoder/lib/pass-through-decoder.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/text-decoder/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/text-decoder/lib/utf8-decoder.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/text-decoder/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/text-decoder/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/timeout-refresh/browser.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/timeout-refresh/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/timeout-refresh/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/timeout-refresh/package.json","./browser":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/timeout-refresh/browser.js","./node":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/timeout-refresh/node.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/timeout-refresh/node.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/timeout-refresh/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/timeout-refresh/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/unslab/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/unslab/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/unslab/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/varint/decode.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/varint/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/varint/encode.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/varint/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/varint/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/varint/package.json","./decode.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/varint/decode.js","./encode.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/varint/encode.js","./length.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/varint/length.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/varint/length.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/varint/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/varint/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/which-runtime/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/which-runtime/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/which-runtime/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/xache/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/xache/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/xache/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/z32/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/z32/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/z32/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/encoding/legacy.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/package.json","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/node_modules/compact-encoding/index.js","index-encoder":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/index-encoder/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/encoding/spec/autobase/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/package.json","../../legacy.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/encoding/legacy.js","hyperschema/runtime":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperschema/runtime.cjs"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/package.json","./lib/active-writers.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/active-writers.js","./lib/append-batch.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/append-batch.js","./lib/apply-calls.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/apply-calls.js","./lib/apply-state.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/apply-state.js","./lib/boot.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/boot.js","./lib/caps.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/caps.js","./lib/encryption.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/encryption.js","./lib/fast-forward.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/fast-forward.js","./lib/linearizer.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/linearizer.js","./lib/local-state.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/local-state.js","./lib/messages.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/messages.js","./lib/store.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/store.js","./lib/system.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/system.js","./lib/timer.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/timer.js","./lib/updates.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/updates.js","./lib/values.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/values.js","./lib/wakeup.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/wakeup.js","./lib/writer.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/writer.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/node_modules/compact-encoding/index.js","core-coupler":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/core-coupler/index.js","debounceify":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/debounceify/index.js","encryption-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/encryption-encoding/index.js","hypercore":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/index.js","hypercore-id-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-id-encoding/index.js","nanoassert":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/nanoassert/index.js","protomux-wakeup":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux-wakeup/index.js","ready-resource":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/ready-resource/index.js","resolve-reject-promise":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/resolve-reject-promise/index.js","safety-catch":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/safety-catch/index.js","scope-lock":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/scope-lock/index.js","signal-promise":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/signal-promise/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/active-writers.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/append-batch.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/package.json","signal-promise":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/signal-promise/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/apply-calls.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/apply-state.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/package.json","./apply-calls.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/apply-calls.js","./caps.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/caps.js","./encryption.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/encryption.js","./fork.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/fork.js","./local-state.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/local-state.js","./messages.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/messages.js","./system.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/system.js","./updates.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/updates.js","./values.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/values.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/node_modules/compact-encoding/index.js","hypercore":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/index.js","hypercore-crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/index.js","hypercore/lib/multisig.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/multisig.js","nanoassert":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/nanoassert/index.js","ready-resource":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/ready-resource/index.js","safety-catch":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/safety-catch/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/boot.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/package.json","./messages.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/messages.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/node_modules/compact-encoding/index.js","encryption-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/encryption-encoding/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/caps.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/package.json","hypercore-crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/clock.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/package.json","tiny-buffer-map":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/tiny-buffer-map/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/consensus.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/package.json","./clock.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/clock.js","tiny-buffer-map":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/tiny-buffer-map/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/encryption.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/package.json","./caps.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/caps.js","./messages.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/messages.js","./system.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/system.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/node_modules/compact-encoding/index.js","hypercore-crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/index.js","hypercore/lib/default-encryption.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/default-encryption.js","ready-resource":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/ready-resource/index.js","resolve-reject-promise":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/resolve-reject-promise/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/fast-forward.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/package.json","./encryption.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/encryption.js","./system.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/system.js","resolve-reject-promise":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/resolve-reject-promise/index.js","safety-catch":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/safety-catch/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/fork.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/package.json","./encryption.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/encryption.js","./messages.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/messages.js","./system.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/system.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/node_modules/compact-encoding/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/linearizer.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/package.json","./clock.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/clock.js","./consensus.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/consensus.js","./topolist.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/topolist.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","nanoassert":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/nanoassert/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/local-state.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/package.json","./messages.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/messages.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/node_modules/compact-encoding/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/messages.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/package.json","../encoding/spec/autobase":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/encoding/spec/autobase/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/node-buffer.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/store.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/package.json","./messages.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/messages.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/node_modules/compact-encoding/index.js","hypercore":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/index.js","hypercore-crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/system.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/package.json","./caps.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/caps.js","./messages.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/messages.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/node_modules/compact-encoding/index.js","hyperbee":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperbee/index.js","hypercore-crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/index.js","ready-resource":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/ready-resource/index.js","sub-encoder":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sub-encoder/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/timer.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/package.json","safety-catch":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/safety-catch/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/topolist.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","nanoassert":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/nanoassert/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/updates.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/values.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/package.json","./caps.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/caps.js","./encryption.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/encryption.js","./messages.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/messages.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/node_modules/compact-encoding/index.js","hypercore-crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/wakeup.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/node_modules/compact-encoding/index.js","ready-resource":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/ready-resource/index.js","safety-catch":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/safety-catch/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/writer.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/package.json","./linearizer.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/linearizer.js","./node-buffer.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/node-buffer.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/node_modules/compact-encoding/index.js","nanoassert":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/nanoassert/index.js","ready-resource":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/ready-resource/index.js","signal-promise":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/signal-promise/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/node_modules/compact-encoding/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/node_modules/compact-encoding/raw.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/node_modules/compact-encoding/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/node_modules/compact-encoding/endian.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-abort/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-abort/package.json",".":"linked:libbare-abort.2.0.13.so"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-abort/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-abort/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-abort/binding.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-abort/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-ansi-escapes/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-ansi-escapes/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-ansi-escapes/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-assert/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-assert/package.json","bare-inspect":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-inspect/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-assert/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-env/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-env/package.json","bare-os":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-os/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-env/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-events/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-events/package.json","./lib/errors":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-events/lib/errors.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-events/lib/errors.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-events/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-events/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-fs/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-fs/package.json",".":"linked:libbare-fs.4.7.4.so"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-fs/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-fs/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-fs/binding.js","./lib/constants":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-fs/lib/constants.js","./lib/errors":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-fs/lib/errors.js","./promises":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-fs/promises.js","bare-events":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-events/index.js","bare-path":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-path/index.js","bare-stream":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-stream/index.js","bare-url":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-url/index.js","fast-fifo":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/fast-fifo/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-fs/lib/constants.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-fs/package.json","../binding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-fs/binding.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-fs/lib/errors.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-fs/package.json","../binding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-fs/binding.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-fs/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-fs/promises.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-fs/package.json",".":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-fs/index.js","bare-events":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-events/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-hrtime/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-hrtime/package.json",".":"linked:libbare-hrtime.2.1.1.so"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-hrtime/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-hrtime/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-hrtime/binding.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-hrtime/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-inspect/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-inspect/package.json",".":"linked:libbare-inspect.3.1.4.so"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-inspect/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-inspect/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-inspect/binding.js","bare-ansi-escapes":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-ansi-escapes/index.js","bare-type":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-type/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-inspect/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-os/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-os/package.json",".":"linked:libbare-os.3.9.3.so"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-os/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-os/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-os/binding.js","./lib/constants":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-os/lib/constants.js","./lib/errors":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-os/lib/errors.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-os/lib/constants.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-os/package.json","../binding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-os/binding.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-os/lib/errors.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-os/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-os/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-path/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-path/package.json",".":"linked:libbare-path.3.1.1.so"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-path/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-path/package.json","./lib/posix":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-path/lib/posix.js","./lib/win32":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-path/lib/win32.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-path/lib/constants.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-path/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-path/lib/posix.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-path/package.json","../binding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-path/binding.js","./constants":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-path/lib/constants.js","./shared":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-path/lib/shared.js","./win32":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-path/lib/win32.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-path/lib/shared.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-path/package.json","./constants":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-path/lib/constants.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-path/lib/win32.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-path/package.json","../binding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-path/binding.js","./constants":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-path/lib/constants.js","./posix":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-path/lib/posix.js","./shared":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-path/lib/shared.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-path/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-pipe/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-pipe/package.json",".":"linked:libbare-pipe.4.2.2.so"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-pipe/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-pipe/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-pipe/binding.js","./lib/constants":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-pipe/lib/constants.js","./lib/errors":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-pipe/lib/errors.js","bare-events":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-events/index.js","bare-stream":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-stream/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-pipe/lib/constants.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-pipe/package.json","../binding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-pipe/binding.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-pipe/lib/errors.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-pipe/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-pipe/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-posix/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-posix/unsupported.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-posix/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-process/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-process/package.json","bare-abort":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-abort/index.js","bare-env":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-env/index.js","bare-events":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-events/index.js","bare-hrtime":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-hrtime/index.js","bare-os":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-os/index.js","bare-posix":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-posix/unsupported.js","bare-signals":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-signals/index.js","bare-stdio":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-stdio/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-process/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-signals/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-signals/package.json",".":"linked:libbare-signals.5.0.0.so"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-signals/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-signals/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-signals/binding.js","./lib/emitter":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-signals/lib/emitter.js","./lib/errors":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-signals/lib/errors.js","bare-events":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-events/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-signals/lib/emitter.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-signals/package.json","..":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-signals/index.js","bare-events":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-events/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-signals/lib/errors.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-signals/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-signals/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-stdio/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-stdio/package.json",".":"linked:libbare-stdio.1.0.3.so"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-stdio/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-stdio/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-stdio/binding.js","bare-fs":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-fs/index.js","bare-pipe":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-pipe/index.js","bare-tty":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-tty/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-stdio/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-stream/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-stream/package.json","./web":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-stream/web.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","streamx":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/streamx/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-stream/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-stream/web.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-stream/package.json","streamx":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/streamx/index.js","teex":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/teex/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-tty/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-tty/package.json",".":"linked:libbare-tty.5.1.2.so"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-tty/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-tty/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-tty/binding.js","./lib/constants":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-tty/lib/constants.js","bare-signals":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-signals/index.js","bare-stream":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-stream/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-tty/lib/constants.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-tty/package.json","../binding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-tty/binding.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-tty/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-type/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-type/package.json",".":"linked:libbare-type.1.1.0.so"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-type/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-type/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-type/binding.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-type/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-url/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-url/package.json",".":"linked:libbare-url.2.4.5.so"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-url/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-url/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-url/binding.js","./lib/errors":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-url/lib/errors.js","./lib/url-search-params":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-url/lib/url-search-params.js","bare-path":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-path/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-url/lib/errors.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-url/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-url/lib/url-search-params.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-url/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-url/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/big-sparse-array/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/big-sparse-array/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/big-sparse-array/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bip39-mnemonic/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bip39-mnemonic/package.json","./wordlist":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bip39-mnemonic/wordlist/index.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","nanoassert":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/nanoassert/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bip39-mnemonic/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bip39-mnemonic/wordlist/chinese_simplified.json":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bip39-mnemonic/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bip39-mnemonic/wordlist/chinese_traditional.json":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bip39-mnemonic/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bip39-mnemonic/wordlist/czech.json":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bip39-mnemonic/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bip39-mnemonic/wordlist/english.json":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bip39-mnemonic/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bip39-mnemonic/wordlist/french.json":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bip39-mnemonic/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bip39-mnemonic/wordlist/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bip39-mnemonic/package.json","./chinese_simplified.json":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bip39-mnemonic/wordlist/chinese_simplified.json","./chinese_traditional.json":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bip39-mnemonic/wordlist/chinese_traditional.json","./czech.json":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bip39-mnemonic/wordlist/czech.json","./english.json":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bip39-mnemonic/wordlist/english.json","./french.json":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bip39-mnemonic/wordlist/french.json","./italian.json":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bip39-mnemonic/wordlist/italian.json","./japanese.json":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bip39-mnemonic/wordlist/japanese.json","./korean.json":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bip39-mnemonic/wordlist/korean.json","./lookup.json":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bip39-mnemonic/wordlist/lookup.json","./portuguese.json":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bip39-mnemonic/wordlist/portuguese.json","./russian.json":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bip39-mnemonic/wordlist/russian.json","./spanish.json":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bip39-mnemonic/wordlist/spanish.json","./turkish.json":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bip39-mnemonic/wordlist/turkish.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bip39-mnemonic/wordlist/italian.json":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bip39-mnemonic/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bip39-mnemonic/wordlist/japanese.json":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bip39-mnemonic/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bip39-mnemonic/wordlist/korean.json":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bip39-mnemonic/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bip39-mnemonic/wordlist/lookup.json":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bip39-mnemonic/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bip39-mnemonic/wordlist/portuguese.json":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bip39-mnemonic/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bip39-mnemonic/wordlist/russian.json":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bip39-mnemonic/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bip39-mnemonic/wordlist/spanish.json":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bip39-mnemonic/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bip39-mnemonic/wordlist/turkish.json":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bip39-mnemonic/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bits-to-bytes/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bits-to-bytes/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bits-to-bytes/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-pairing/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-pairing/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","blind-pairing-core":"/node_modules/blind-pairing-core/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding/index.js","debounceify":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/debounceify/index.js","hypercore-crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/index.js","is-options":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/is-options/index.js","protomux":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux/index.js","ready-resource":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/ready-resource/index.js","safety-catch":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/safety-catch/index.js","xache":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/xache/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-pairing/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-relay/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-relay/package.json","./lib/errors":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-relay/lib/errors.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","bits-to-bytes":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bits-to-bytes/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-relay/node_modules/compact-encoding/index.js","compact-encoding-bitfield":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding-bitfield/index.js","events":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-events/index.js","protomux":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-universal/index.js","streamx":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/streamx/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-relay/lib/errors.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-relay/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-relay/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-relay/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-relay/node_modules/compact-encoding/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-relay/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-relay/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-relay/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-relay/node_modules/compact-encoding/raw.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-relay/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-relay/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-relay/node_modules/compact-encoding/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-relay/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-relay/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-relay/node_modules/compact-encoding/endian.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-relay/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bogon/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bogon/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bogon/node_modules/compact-encoding/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bogon/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bogon/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bogon/node_modules/compact-encoding/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bogon/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bogon/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bogon/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bogon/node_modules/compact-encoding/raw.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bogon/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bogon/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bogon/node_modules/compact-encoding/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bogon/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bogon/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bogon/node_modules/compact-encoding/endian.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bogon/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/cborg.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/package.json","./lib/decode.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/decode.js","./lib/encode.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/encode.js","./lib/tagged.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/tagged.js","./lib/token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/0uint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/package.json","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/1negint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/2bytes.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/0uint.js","./byte-utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/3string.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/0uint.js","./2bytes.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/2bytes.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/4array.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/5map.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/6tag.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/0uint.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/7float.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/bl.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/package.json","./byte-utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/byte-utils.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/byte-utils.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/common.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/decode.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/package.json","./byte-utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/common.js","./jump.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/jump.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/encode.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/0uint.js","./1negint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/1negint.js","./2bytes.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/2bytes.js","./3string.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/3string.js","./4array.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/4array.js","./5map.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/5map.js","./6tag.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/6tag.js","./7float.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/7float.js","./bl.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/bl.js","./byte-utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/common.js","./is.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/is.js","./jump.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/jump.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/is.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/jump.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/0uint.js","./1negint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/1negint.js","./2bytes.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/2bytes.js","./3string.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/3string.js","./4array.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/4array.js","./5map.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/5map.js","./6tag.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/6tag.js","./7float.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/7float.js","./byte-utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/tagged.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/token.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/codecs/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/codecs/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/codecs/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding-bitfield/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding-bitfield/package.json","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/raw.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/endian.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding-bitfield/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding/raw.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding/endian.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/core-coupler/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/core-coupler/package.json","safety-catch":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/safety-catch/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/core-coupler/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/corestore/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/corestore/package.json","./lib/audit.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/corestore/lib/audit.js","./lib/notify.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/corestore/lib/notify.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","hypercore":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/index.js","hypercore-crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/index.js","hypercore-errors":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-errors/index.js","hypercore-id-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-id-encoding/index.js","ready-resource":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/ready-resource/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-universal/index.js","which-runtime":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/which-runtime/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/corestore/lib/audit.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/corestore/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/corestore/lib/notify.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/corestore/package.json","events":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-events/index.js","streamx":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/streamx/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/corestore/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/debounceify/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/debounceify/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/debounceify/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/device-file/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/device-file/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","fd-lock":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/fd-lock/index.js","fs":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-fs/index.js","fs-native-extensions":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/fs-native-extensions/index.js","path":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-path/index.js","ready-resource":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/ready-resource/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/device-file/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/package.json","./lib/commands":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/lib/commands.js","./lib/errors":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/lib/errors.js","./lib/health":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/lib/health.js","./lib/io":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/lib/io.js","./lib/peer":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/lib/peer.js","./lib/query":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/lib/query.js","./lib/session":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/lib/session.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/node_modules/compact-encoding/index.js","events":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-events/index.js","kademlia-routing-table":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/kademlia-routing-table/index.js","nat-sampler":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/nat-sampler/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-universal/index.js","time-ordered-set":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/time-ordered-set/index.js","udx-native":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/udx-native/lib/udx.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/lib/commands.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/lib/errors.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/lib/health.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/lib/io.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/package.json","./errors":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/lib/errors.js","./peer":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/lib/peer.js","adaptive-timeout":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/adaptive-timeout/index.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/node_modules/compact-encoding/index.js","fast-fifo":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/fast-fifo/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/lib/peer.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/node_modules/compact-encoding/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/lib/query.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/package.json","./commands":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/lib/commands.js","./peer":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/lib/peer.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","streamx":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/streamx/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/lib/session.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/node_modules/compact-encoding/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/node_modules/compact-encoding/raw.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/node_modules/compact-encoding/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/node_modules/compact-encoding/endian.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/encryption-encoding/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/encryption-encoding/package.json","./spec/hyperschema":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/encryption-encoding/spec/hyperschema/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/encryption-encoding/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/encryption-encoding/spec/hyperschema/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/encryption-encoding/package.json","hyperschema/runtime":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperschema/runtime.cjs"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/events-universal/bare.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/events-universal/package.json","bare-events":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-events/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/events-universal/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/fast-fifo/fixed-size.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/fast-fifo/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/fast-fifo/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/fast-fifo/package.json","./fixed-size":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/fast-fifo/fixed-size.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/fast-fifo/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/fd-lock/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/fd-lock/package.json","fs":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-fs/index.js","fs-native-extensions":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/fs-native-extensions/index.js","ready-resource":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/ready-resource/index.js","resource-on-exit":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/resource-on-exit/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/fd-lock/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/flat-tree/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/flat-tree/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/flat-tree/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/fs-native-extensions/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/fs-native-extensions/package.json",".":"linked:libfs-native-extensions.1.5.0.so","require-addon":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/require-addon/lib/bare.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/fs-native-extensions/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/fs-native-extensions/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/fs-native-extensions/binding.js","which-runtime":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/which-runtime/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/fs-native-extensions/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperbee/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperbee/package.json","./iterators/diff":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperbee/iterators/diff.js","./iterators/history":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperbee/iterators/history.js","./iterators/local":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperbee/iterators/local.js","./iterators/range":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperbee/iterators/range.js","./lib/extension":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperbee/lib/extension.js","./lib/messages":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperbee/lib/messages.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","codecs":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/codecs/index.js","debounceify":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/debounceify/index.js","hypercore-errors":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-errors/index.js","mutexify/promise":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/mutexify/promise.js","rache":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rache/index.js","ready-resource":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/ready-resource/index.js","resolve-reject-promise":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/resolve-reject-promise/index.js","safety-catch":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/safety-catch/index.js","streamx":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/streamx/index.js","unslab":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/unslab/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperbee/iterators/diff.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperbee/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperbee/iterators/history.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperbee/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperbee/iterators/local.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperbee/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperbee/iterators/range.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperbee/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperbee/lib/extension.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperbee/package.json","./messages":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperbee/lib/messages.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperbee/lib/messages.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperbee/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","protocol-buffers-encodings":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protocol-buffers-encodings/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperbee/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/node_modules/compact-encoding/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/node_modules/compact-encoding/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/node_modules/compact-encoding/raw.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/node_modules/compact-encoding/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/node_modules/compact-encoding/endian.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-errors/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-errors/package.json","hypercore-id-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-id-encoding/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-errors/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-id-encoding/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-id-encoding/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","z32":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/z32/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-id-encoding/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/encoding/external.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/encoding/spec/hyperschema/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/package.json","../../external.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/encoding/external.js","hyperschema/runtime":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperschema/runtime.cjs"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/package.json","./lib/keys.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/lib/keys.js","./lib/streams.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/lib/streams.js","./lib/tx.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/lib/tx.js","./lib/view.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/lib/view.js","./migrations/0":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/migrations/0/index.js","./migrations/1":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/migrations/1/index.js","device-file":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/device-file/index.js","fs":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-fs/index.js","path":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-path/index.js","resolve-reject-promise":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/resolve-reject-promise/index.js","rocksdb-native":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/index.js","scope-lock":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/scope-lock/index.js","xache":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/xache/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/lib/block-dependency-stream.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/package.json","./keys":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/lib/keys.js","streamx":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/streamx/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/lib/close-error-stream.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/package.json","streamx":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/streamx/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/lib/keys.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/node_modules/compact-encoding/index.js","index-encoder":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/index-encoder/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/lib/streams.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/package.json","../encoding/spec/hyperschema":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/encoding/spec/hyperschema/index.js","./block-dependency-stream.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/lib/block-dependency-stream.js","./keys.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/lib/keys.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/lib/tx.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/package.json","../encoding/spec/hyperschema":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/encoding/spec/hyperschema/index.js","./keys.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/lib/keys.js","./view.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/lib/view.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/node_modules/compact-encoding/index.js","flat-tree":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/flat-tree/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/lib/view.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/package.json","./close-error-stream.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/lib/close-error-stream.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","streamx":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/streamx/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/migrations/0/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/package.json","../../lib/tx.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/lib/tx.js","../../lib/view.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/lib/view.js","./messages.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/migrations/0/messages.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/node_modules/compact-encoding/index.js","flat-tree":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/flat-tree/index.js","fs":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-fs/index.js","hypercore-crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/index.js","path":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-path/index.js","streamx":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/streamx/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/migrations/0/messages.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/node_modules/compact-encoding/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/migrations/1/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/package.json","../../encoding/spec/hyperschema":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/encoding/spec/hyperschema/index.js","../../lib/keys.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/lib/keys.js","../../lib/tx.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/lib/tx.js","../../lib/view.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/lib/view.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/node_modules/compact-encoding/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/node_modules/compact-encoding/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/node_modules/compact-encoding/raw.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/node_modules/compact-encoding/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/node_modules/compact-encoding/endian.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/package.json","./lib/caps":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/caps.js","./lib/core":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/core.js","./lib/default-encryption":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/default-encryption.js","./lib/download":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/download.js","./lib/feature-flags":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/feature-flags.js","./lib/fully-remote-proof":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/fully-remote-proof.js","./lib/info":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/info.js","./lib/inspect":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/inspect.js","./lib/mark-bitfield":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/mark-bitfield.js","./lib/merkle-tree":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/merkle-tree.js","./lib/replicator":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/replicator.js","./lib/streams":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/streams.js","./lib/verifier":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/verifier.js","./lib/wants":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/wants.js","@hyperswarm/secret-stream":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/@hyperswarm/secret-stream/index.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/node_modules/compact-encoding/index.js","events":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-events/index.js","flat-tree":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/flat-tree/index.js","hypercore-crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/index.js","hypercore-errors":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-errors/index.js","hypercore-id-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-id-encoding/index.js","hypercore-storage":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/index.js","is-options":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/is-options/index.js","nanoassert":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/nanoassert/index.js","protomux":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux/index.js","safety-catch":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/safety-catch/index.js","unslab":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/unslab/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/audit.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/package.json","./merkle-tree":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/merkle-tree.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","flat-tree":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/flat-tree/index.js","hypercore-crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/bit-interlude.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/package.json","./compat":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/compat.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/bitfield.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/package.json","./compat":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/compat.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","big-sparse-array":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/big-sparse-array/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/caps.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/node_modules/compact-encoding/index.js","hypercore-crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/compat.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/package.json","quickbit-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/quickbit-universal/index.js","quickbit-universal/fallback":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/quickbit-universal/fallback.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/copy-prologue.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/package.json","./bitfield":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/bitfield.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","flat-tree":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/flat-tree/index.js","hypercore-crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/index.js","quickbit-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/quickbit-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/core.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/package.json","./audit":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/audit.js","./bit-interlude":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/bit-interlude.js","./bitfield":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/bitfield.js","./copy-prologue":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/copy-prologue.js","./merkle-tree":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/merkle-tree.js","./mutex":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/mutex.js","./remote-bitfield":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/remote-bitfield.js","./replicator":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/replicator.js","./session-state":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/session-state.js","./verifier":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/verifier.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","hypercore-crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/index.js","hypercore-errors":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-errors/index.js","unslab":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/unslab/index.js","z32":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/z32/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/default-encryption.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/package.json","./caps":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/caps.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/node_modules/compact-encoding/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/download.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/feature-flags.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/fully-remote-proof.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/package.json","./merkle-tree.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/merkle-tree.js","./messages.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/messages.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/node_modules/compact-encoding/index.js","flat-tree":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/flat-tree/index.js","hypercore-crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/hotswap-queue.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/info.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/inspect.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/mark-bitfield.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/package.json","./compat":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/compat.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","big-sparse-array":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/big-sparse-array/index.js","streamx":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/streamx/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/merkle-tree.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/package.json","./caps":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/caps.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","flat-tree":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/flat-tree/index.js","hypercore-crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/index.js","hypercore-errors":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-errors/index.js","unslab":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/unslab/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/messages.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/package.json","./caps":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/caps.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/node_modules/compact-encoding/index.js","hypercore-errors":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-errors/index.js","unslab":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/unslab/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/multisig.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/package.json","./merkle-tree":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/merkle-tree.js","./messages":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/messages.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/node_modules/compact-encoding/index.js","flat-tree":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/flat-tree/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/mutex.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/receiver-queue.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/package.json","fast-fifo":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/fast-fifo/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/remote-bitfield.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/package.json","./compat":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/compat.js","big-sparse-array":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/big-sparse-array/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/replicator.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/package.json","./caps":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/caps.js","./hotswap-queue":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/hotswap-queue.js","./merkle-tree":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/merkle-tree.js","./messages":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/messages.js","./mutex":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/mutex.js","./receiver-queue":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/receiver-queue.js","./remote-bitfield":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/remote-bitfield.js","./wants":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/wants.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","flat-tree":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/flat-tree/index.js","hypercore-errors":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-errors/index.js","random-array-iterator":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/random-array-iterator/index.js","safety-catch":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/safety-catch/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/session-state.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/package.json","./bitfield":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/bitfield.js","./merkle-tree":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/merkle-tree.js","./mutex":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/mutex.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","flat-tree":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/flat-tree/index.js","hypercore-crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/index.js","hypercore-errors":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-errors/index.js","hypercore-storage":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/index.js","nanoassert":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/nanoassert/index.js","quickbit-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/quickbit-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/streams.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/package.json","streamx":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/streamx/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/verifier.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/package.json","./caps":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/caps.js","./messages":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/messages.js","./multisig":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/multisig.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/node_modules/compact-encoding/index.js","flat-tree":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/flat-tree/index.js","hypercore-crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/index.js","hypercore-errors":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-errors/index.js","unslab":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/unslab/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/wants.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/node_modules/compact-encoding/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/node_modules/compact-encoding/raw.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/node_modules/compact-encoding/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/node_modules/compact-encoding/endian.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdb/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdb/package.json","./lib/definition.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdb/lib/definition.js","./lib/engine/bee.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdb/lib/engine/bee.js","./lib/engine/bee2.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdb/lib/engine/bee2.js","./lib/engine/rocks.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdb/lib/engine/rocks.js","./lib/stream.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdb/lib/stream.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdb/lib/changes-stream.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdb/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdb/lib/definition.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdb/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdb/lib/engine/bee.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdb/package.json","../changes-stream.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdb/lib/changes-stream.js","../sessions.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdb/lib/sessions.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdb/node_modules/compact-encoding/index.js","hyperbee":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperbee/index.js","hypercore":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/index.js","refcounter":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/refcounter/index.js","scope-lock":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/scope-lock/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdb/lib/engine/bee2.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdb/package.json","../changes-stream.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdb/lib/changes-stream.js","../sessions.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdb/lib/sessions.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdb/node_modules/compact-encoding/index.js","hypercore":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/index.js","refcounter":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/refcounter/index.js","scope-lock":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/scope-lock/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdb/lib/engine/rocks.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdb/package.json","../sessions.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdb/lib/sessions.js","rocksdb-native":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/index.js","scope-lock":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/scope-lock/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdb/lib/sessions.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdb/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdb/lib/stream.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdb/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","streamx":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/streamx/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdb/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdb/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdb/node_modules/compact-encoding/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdb/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdb/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdb/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdb/node_modules/compact-encoding/raw.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdb/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdb/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdb/node_modules/compact-encoding/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdb/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdb/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdb/node_modules/compact-encoding/endian.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdb/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdb/runtime.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdb/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdb/node_modules/compact-encoding/index.js","index-encoder":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/index-encoder/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht-address/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht-address/package.json","./spec/hyperschema":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht-address/spec/hyperschema/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht-address/node_modules/compact-encoding/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht-address/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht-address/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht-address/node_modules/compact-encoding/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht-address/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht-address/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht-address/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht-address/node_modules/compact-encoding/raw.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht-address/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht-address/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht-address/node_modules/compact-encoding/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht-address/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht-address/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht-address/node_modules/compact-encoding/endian.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht-address/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht-address/spec/hyperschema/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht-address/package.json","hyperschema/runtime":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperschema/runtime.cjs"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/package.json","./lib/connect":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/connect.js","./lib/connection-pool":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/connection-pool.js","./lib/constants":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/constants.js","./lib/crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/crypto.js","./lib/errors":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/errors.js","./lib/messages":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/messages.js","./lib/persistent":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/persistent.js","./lib/raw-stream-set":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/raw-stream-set.js","./lib/router":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/router.js","./lib/server":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/server.js","./lib/socket-pool":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/socket-pool.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/index.js","dht-rpc":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/index.js","safety-catch":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/safety-catch/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-universal/index.js","xache":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/xache/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/announcer.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/package.json","./constants":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/constants.js","./encode":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/encode.js","./messages":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/messages.js","./persistent":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/persistent.js","./sleeper":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/sleeper.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/index.js","safety-catch":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/safety-catch/index.js","signal-promise":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/signal-promise/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/connect.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/package.json","./constants":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/constants.js","./crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/crypto.js","./errors":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/errors.js","./holepuncher":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/holepuncher.js","./noise-wrap":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/noise-wrap.js","./relay-connection":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/relay-connection.js","./secure-payload":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/secure-payload.js","./semaphore":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/semaphore.js","./sleeper":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/sleeper.js","@hyperswarm/secret-stream":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/@hyperswarm/secret-stream/index.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","blind-relay":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-relay/index.js","bogon":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bogon/index.js","hypercore-id-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-id-encoding/index.js","hyperdht-address":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht-address/index.js","safety-catch":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/safety-catch/index.js","unslab":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/unslab/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/connection-pool.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/package.json","./errors":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/errors.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","events":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-events/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/constants.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/package.json","hypercore-crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/crypto.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/encode.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/errors.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/holepuncher.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/package.json","./constants":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/constants.js","./nat":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/nat.js","./sleeper":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/sleeper.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/messages.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/package.json","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/nat.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/package.json","../lib/constants":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/constants.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/noise-wrap.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/package.json","./constants":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/constants.js","./errors":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/errors.js","./messages":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/messages.js","@hyperswarm/secret-stream":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/@hyperswarm/secret-stream/index.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/index.js","noise-curve-ed":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-curve-ed/index.js","noise-handshake":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-handshake/noise.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/persistent.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/package.json","./constants":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/constants.js","./encode":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/encode.js","./messages":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/messages.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/index.js","record-cache":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/record-cache/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-universal/index.js","unslab":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/unslab/index.js","xache":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/xache/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/raw-stream-set.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/relay-connection.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","safety-catch":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/safety-catch/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/router.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/package.json","./constants":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/constants.js","./errors":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/errors.js","./messages":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/messages.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/index.js","safety-catch":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/safety-catch/index.js","xache":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/xache/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/secure-payload.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/package.json","./messages":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/messages.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/semaphore.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/server.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/package.json","./announcer":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/announcer.js","./constants":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/constants.js","./crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/crypto.js","./errors":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/errors.js","./holepuncher":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/holepuncher.js","./noise-wrap":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/noise-wrap.js","./relay-connection":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/relay-connection.js","./secure-payload":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/secure-payload.js","@hyperswarm/secret-stream":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/@hyperswarm/secret-stream/index.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","blind-relay":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-relay/index.js","bogon":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bogon/index.js","events":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-events/index.js","safety-catch":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/safety-catch/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/sleeper.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/socket-pool.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/raw.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/endian.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdispatch/lib/errors.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdispatch/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdispatch/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdispatch/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdispatch/node_modules/compact-encoding/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdispatch/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdispatch/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdispatch/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdispatch/node_modules/compact-encoding/raw.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdispatch/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdispatch/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdispatch/node_modules/compact-encoding/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdispatch/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdispatch/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdispatch/node_modules/compact-encoding/endian.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdispatch/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdispatch/runtime.cjs":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdispatch/package.json","./lib/errors.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdispatch/lib/errors.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdispatch/node_modules/compact-encoding/index.js","nanoassert":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/nanoassert/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperschema/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperschema/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperschema/node_modules/compact-encoding/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperschema/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperschema/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperschema/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperschema/node_modules/compact-encoding/raw.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperschema/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperschema/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperschema/node_modules/compact-encoding/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperschema/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperschema/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperschema/node_modules/compact-encoding/endian.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperschema/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperschema/runtime.cjs":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperschema/package.json","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperschema/node_modules/compact-encoding/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperswarm/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperswarm/package.json","./lib/connection-set":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperswarm/lib/connection-set.js","./lib/peer-discovery":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperswarm/lib/peer-discovery.js","./lib/peer-info":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperswarm/lib/peer-info.js","./lib/retry-timer":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperswarm/lib/retry-timer.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","events":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-events/index.js","hyperdht":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/index.js","shuffled-priority-queue":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/shuffled-priority-queue/index.js","streamx":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/streamx/index.js","unslab":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/unslab/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperswarm/lib/bulk-timer.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperswarm/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperswarm/lib/connection-set.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperswarm/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperswarm/lib/peer-discovery.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperswarm/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","safety-catch":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/safety-catch/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperswarm/lib/peer-info.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperswarm/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","events":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-events/index.js","unslab":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/unslab/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperswarm/lib/retry-timer.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperswarm/package.json","./bulk-timer":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperswarm/lib/bulk-timer.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperswarm/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/index-encoder/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/index-encoder/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/index-encoder/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/is-options/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/is-options/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/is-options/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/kademlia-routing-table/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/kademlia-routing-table/package.json","events":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-events/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/kademlia-routing-table/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/keet-identity-key/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/keet-identity-key/package.json","./lib/crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/keet-identity-key/lib/crypto.js","./lib/encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/keet-identity-key/lib/encoding.js","./lib/keychain":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/keet-identity-key/lib/keychain.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/keet-identity-key/node_modules/compact-encoding/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/keet-identity-key/lib/crypto.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/keet-identity-key/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/keet-identity-key/lib/encoding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/keet-identity-key/package.json","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/keet-identity-key/node_modules/compact-encoding/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/keet-identity-key/lib/keychain.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/keet-identity-key/package.json","./crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/keet-identity-key/lib/crypto.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","bip39-mnemonic":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bip39-mnemonic/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/keet-identity-key/node_modules/compact-encoding/index.js","nanoassert":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/nanoassert/index.js","sodium-hmac":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-hmac/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/keet-identity-key/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/keet-identity-key/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/keet-identity-key/node_modules/compact-encoding/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/keet-identity-key/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/keet-identity-key/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/keet-identity-key/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/keet-identity-key/node_modules/compact-encoding/raw.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/keet-identity-key/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/keet-identity-key/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/keet-identity-key/node_modules/compact-encoding/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/keet-identity-key/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/keet-identity-key/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/keet-identity-key/node_modules/compact-encoding/endian.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/keet-identity-key/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/multiformats/dist/src/bases/base.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/multiformats/package.json","../bytes.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/multiformats/dist/src/bytes.js","../vendor/base-x.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/multiformats/dist/src/vendor/base-x.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/multiformats/dist/src/bases/base32.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/multiformats/package.json","./base.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/multiformats/dist/src/bases/base.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/multiformats/dist/src/bases/base36.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/multiformats/package.json","./base.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/multiformats/dist/src/bases/base.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/multiformats/dist/src/bases/base58.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/multiformats/package.json","./base.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/multiformats/dist/src/bases/base.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/multiformats/dist/src/bytes.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/multiformats/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/multiformats/dist/src/cid.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/multiformats/package.json","./bases/base32.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/multiformats/dist/src/bases/base32.js","./bases/base36.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/multiformats/dist/src/bases/base36.js","./bases/base58.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/multiformats/dist/src/bases/base58.js","./bytes.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/multiformats/dist/src/bytes.js","./hashes/digest.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/multiformats/dist/src/hashes/digest.js","./link/interface.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/multiformats/dist/src/link/interface.js","./varint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/multiformats/dist/src/varint.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/multiformats/dist/src/hashes/digest.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/multiformats/package.json","../bytes.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/multiformats/dist/src/bytes.js","../varint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/multiformats/dist/src/varint.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/multiformats/dist/src/link/interface.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/multiformats/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/multiformats/dist/src/varint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/multiformats/package.json","./vendor/varint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/multiformats/dist/src/vendor/varint.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/multiformats/dist/src/vendor/base-x.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/multiformats/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/multiformats/dist/src/vendor/varint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/multiformats/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/multiformats/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/mutexify/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/mutexify/package.json","queue-tick":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/queue-tick/process-next-tick.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/mutexify/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/mutexify/promise.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/mutexify/package.json",".":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/mutexify/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/nanoassert/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/nanoassert/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/nanoassert/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/nat-sampler/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/nat-sampler/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/nat-sampler/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-curve-ed/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-curve-ed/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","nanoassert":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/nanoassert/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-curve-ed/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-handshake/cipher.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-handshake/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-handshake/dh.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-handshake/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","nanoassert":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/nanoassert/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-handshake/hkdf.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-handshake/package.json","./hmac":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-handshake/hmac.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-handshake/hmac.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-handshake/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-handshake/noise.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-handshake/package.json","./hkdf":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-handshake/hkdf.js","./symmetric-state":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-handshake/symmetric-state.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","nanoassert":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/nanoassert/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-handshake/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-handshake/symmetric-state.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-handshake/package.json","./cipher":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-handshake/cipher.js","./dh":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-handshake/dh.js","./hkdf":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-handshake/hkdf.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","nanoassert":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/nanoassert/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protocol-buffers-encodings/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protocol-buffers-encodings/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","signed-varint":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/signed-varint/index.js","varint":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/varint/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protocol-buffers-encodings/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux-rpc/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux-rpc/package.json","./lib/errors":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux-rpc/lib/errors.js","bits-to-bytes":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bits-to-bytes/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux-rpc/node_modules/compact-encoding/index.js","compact-encoding-bitfield":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding-bitfield/index.js","events":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-events/index.js","protomux":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux/index.js","safety-catch":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/safety-catch/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux-rpc/lib/errors.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux-rpc/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux-rpc/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux-rpc/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux-rpc/node_modules/compact-encoding/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux-rpc/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux-rpc/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux-rpc/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux-rpc/node_modules/compact-encoding/raw.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux-rpc/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux-rpc/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux-rpc/node_modules/compact-encoding/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux-rpc/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux-rpc/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux-rpc/node_modules/compact-encoding/endian.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux-rpc/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux-wakeup/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux-wakeup/package.json","./spec/hyperschema":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux-wakeup/spec/hyperschema/index.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","hypercore-crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/index.js","protomux":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux-wakeup/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux-wakeup/spec/hyperschema/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux-wakeup/package.json","hyperschema/runtime":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperschema/runtime.cjs"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux/node_modules/compact-encoding/index.js","queue-tick":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/queue-tick/process-next-tick.js","safety-catch":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/safety-catch/index.js","unslab":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/unslab/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux/node_modules/compact-encoding/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux/node_modules/compact-encoding/raw.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux/node_modules/compact-encoding/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux/node_modules/compact-encoding/endian.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/queue-tick/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/queue-tick/process-next-tick.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/queue-tick/package.json","./queue-microtask":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/queue-tick/queue-microtask.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/queue-tick/queue-microtask.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/queue-tick/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/quickbit-native/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/quickbit-native/package.json",".":"linked:libquickbit-native.2.4.8.so","require-addon":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/require-addon/lib/bare.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/quickbit-native/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/quickbit-native/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/quickbit-native/binding.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/quickbit-native/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/quickbit-universal/fallback.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/quickbit-universal/package.json","simdle-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/simdle-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/quickbit-universal/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/quickbit-universal/package.json","./fallback":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/quickbit-universal/fallback.js","quickbit-native":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/quickbit-native/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/quickbit-universal/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rache/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rache/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rache/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/random-array-iterator/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/random-array-iterator/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/random-array-iterator/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/ready-resource/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/ready-resource/package.json","events":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-events/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/ready-resource/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/record-cache/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/record-cache/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/record-cache/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/refcounter/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/refcounter/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/refcounter/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/require-addon/lib/bare.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/require-addon/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/require-addon/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/resolve-reject-promise/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/resolve-reject-promise/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/resolve-reject-promise/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/resource-on-exit/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/resource-on-exit/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/resource-on-exit/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/package.json",".":"linked:librocksdb-native.3.17.2.so","require-addon":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/require-addon/lib/bare.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/package.json","./lib/column-family":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/lib/column-family.js","./lib/constants":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/lib/constants.js","./lib/filter-policy":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/lib/filter-policy.js","./lib/iterator":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/lib/iterator.js","./lib/snapshot":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/lib/snapshot.js","./lib/state":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/lib/state.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/lib/batch.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/package.json","../binding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/binding.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/node_modules/compact-encoding/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/lib/column-family.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/package.json","../binding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/binding.js","./constants":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/lib/constants.js","./filter-policy":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/lib/filter-policy.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/lib/constants.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/lib/filter-policy.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/lib/iterator.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/package.json","../binding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/binding.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/node_modules/compact-encoding/index.js","streamx":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/streamx/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/lib/snapshot.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/package.json","../binding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/binding.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/lib/state.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/package.json","../binding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/binding.js","./batch":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/lib/batch.js","./column-family":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/lib/column-family.js","./constants":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/lib/constants.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/node_modules/compact-encoding/index.js","ready-resource":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/ready-resource/index.js","refcounter":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/refcounter/index.js","resolve-reject-promise":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/resolve-reject-promise/index.js","signal-promise":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/signal-promise/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/node_modules/compact-encoding/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/node_modules/compact-encoding/raw.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/node_modules/compact-encoding/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/node_modules/compact-encoding/endian.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/safety-catch/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/safety-catch/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/safety-catch/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/scope-lock/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/scope-lock/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/scope-lock/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/shuffled-priority-queue/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/shuffled-priority-queue/package.json","unordered-set":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/unordered-set/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/shuffled-priority-queue/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/signal-promise/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/signal-promise/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/signal-promise/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/signed-varint/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/signed-varint/package.json","varint":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/varint/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/signed-varint/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/simdle-native/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/simdle-native/package.json",".":"linked:libsimdle-native.1.3.9.so","require-addon":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/require-addon/lib/bare.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/simdle-native/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/simdle-native/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/simdle-native/binding.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/simdle-native/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/simdle-universal/fallback.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/simdle-universal/package.json","./scalar":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/simdle-universal/scalar.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/simdle-universal/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/simdle-universal/package.json","./fallback":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/simdle-universal/fallback.js","simdle-native":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/simdle-native/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/simdle-universal/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/simdle-universal/scalar.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/simdle-universal/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-hmac/hash/sha256.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-hmac/package.json","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-hmac/hash/sha512.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-hmac/package.json","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-hmac/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-hmac/package.json","./hash/sha256":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-hmac/hash/sha256.js","./hash/sha512":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-hmac/hash/sha512.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-hmac/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-native/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-native/package.json",".":"linked:libsodium-native.5.1.0.so","require-addon":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/require-addon/lib/bare.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-native/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-native/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-native/binding.js","assert":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-assert/index.js","which-runtime":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/which-runtime/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-native/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-secretstream/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-secretstream/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-secretstream/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-universal/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-universal/package.json","sodium-native":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-native/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-universal/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/streamx/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/streamx/package.json","./lib/errors.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/streamx/lib/errors.js","events-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/events-universal/bare.js","fast-fifo":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/fast-fifo/index.js","text-decoder":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/text-decoder/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/streamx/lib/errors.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/streamx/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/streamx/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sub-encoder/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sub-encoder/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","codecs":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/codecs/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sub-encoder/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/teex/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/teex/package.json","streamx":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/streamx/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/teex/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/text-decoder/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/text-decoder/package.json","./lib/pass-through-decoder":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/text-decoder/lib/pass-through-decoder.js","./lib/utf8-decoder":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/text-decoder/lib/utf8-decoder.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/text-decoder/lib/pass-through-decoder.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/text-decoder/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/text-decoder/lib/utf8-decoder.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/text-decoder/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/text-decoder/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/time-ordered-set/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/time-ordered-set/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/time-ordered-set/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/timeout-refresh/browser.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/timeout-refresh/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/timeout-refresh/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/timeout-refresh/package.json","./browser":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/timeout-refresh/browser.js","./node":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/timeout-refresh/node.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/timeout-refresh/node.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/timeout-refresh/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/timeout-refresh/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/tiny-buffer-map/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/tiny-buffer-map/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/tiny-buffer-map/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/udx-native/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/udx-native/package.json",".":"linked:libudx-native.1.20.7.so","require-addon":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/require-addon/lib/bare.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/udx-native/lib/ip.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/udx-native/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/udx-native/lib/network-interfaces.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/udx-native/package.json","../binding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/udx-native/binding.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","events":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-events/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/udx-native/lib/socket.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/udx-native/package.json","../binding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/udx-native/binding.js","./ip":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/udx-native/lib/ip.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","events":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-events/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/udx-native/lib/stream.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/udx-native/package.json","../binding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/udx-native/binding.js","./ip":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/udx-native/lib/ip.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js","streamx":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/streamx/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/udx-native/lib/udx.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/udx-native/package.json","../binding":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/udx-native/binding.js","./ip":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/udx-native/lib/ip.js","./network-interfaces":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/udx-native/lib/network-interfaces.js","./socket":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/udx-native/lib/socket.js","./stream":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/udx-native/lib/stream.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/udx-native/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/unordered-set/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/unordered-set/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/unordered-set/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/unslab/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/unslab/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/unslab/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/varint/decode.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/varint/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/varint/encode.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/varint/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/varint/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/varint/package.json","./decode.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/varint/decode.js","./encode.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/varint/encode.js","./length.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/varint/length.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/varint/length.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/varint/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/varint/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/which-runtime/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/which-runtime/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/which-runtime/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/xache/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/xache/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/xache/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/z32/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/z32/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/z32/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-room/spec/state-base/contract/hyperdb/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/spec/state-base/package.json","./messages.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/spec/state-base/contract/hyperdb/messages.js","hyperdb/runtime":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdb/runtime.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/spec/state-base/contract/hyperdb/messages.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/spec/state-base/package.json","hyperschema/runtime":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperschema/runtime.cjs"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/spec/state-base/contract/hyperdispatch/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/spec/state-base/package.json","./messages.js":"/node_modules/hyper-proto-peer/node_modules/atproto-room/spec/state-base/contract/hyperdispatch/messages.js","hyperdispatch/runtime":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdispatch/runtime.cjs"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/spec/state-base/contract/hyperdispatch/messages.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-room/spec/state-base/package.json","hyperschema/runtime":"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperschema/runtime.cjs"},"/node_modules/hyper-proto-peer/node_modules/atproto-room/spec/state-base/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/lib/account-registry.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/package.json","hyperbee":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hyperbee/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/lib/blob-pointer-store.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/lib/blob-store.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/package.json","./corestore.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/lib/corestore.js","atproto-repo/lib/cid.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/lib/cid.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/b4a/index.js","corestore":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/corestore/index.js","hyperbee":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hyperbee/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/lib/corestore.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/package.json","corestore":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/corestore/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/lib/overlay-blob-store.js":{"#node:fs":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-fs/index.js","#node:path":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-path/index.js","#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/package.json","./corestore.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/lib/corestore.js","atproto-repo/lib/cid.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/lib/cid.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/b4a/index.js","corestore":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/corestore/index.js","hyperbee":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hyperbee/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/lib/overlay-repo-store.js":{"#node:fs":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-fs/index.js","#node:path":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-path/index.js","#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/package.json","./tid.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/lib/tid.js","@ipld/dag-cbor":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/@ipld/dag-cbor/src/index.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/lib/pointer-substrate.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/lib/read-view.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/package.json","@ipld/dag-cbor":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/@ipld/dag-cbor/src/index.js","atproto-repo/lib/cid.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/lib/cid.js","atproto-repo/lib/commit.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/lib/commit.js","atproto-repo/lib/mst.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/lib/mst.js","atproto-repo/lib/repo.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/lib/repo.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/lib/tid.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/@hyperswarm/secret-stream/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/@hyperswarm/secret-stream/package.json","./lib/bridge":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/@hyperswarm/secret-stream/lib/bridge.js","./lib/handshake":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/@hyperswarm/secret-stream/lib/handshake.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/b4a/index.js","hypercore-crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-crypto/index.js","sodium-secretstream":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/sodium-secretstream/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/sodium-universal/index.js","streamx":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/streamx/index.js","timeout-refresh":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/timeout-refresh/index.js","unslab":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/unslab/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/@hyperswarm/secret-stream/lib/bridge.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/@hyperswarm/secret-stream/package.json","streamx":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/streamx/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/@hyperswarm/secret-stream/lib/handshake.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/@hyperswarm/secret-stream/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/b4a/index.js","noise-curve-ed":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/noise-curve-ed/index.js","noise-handshake":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/noise-handshake/noise.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/@hyperswarm/secret-stream/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/@ipld/dag-cbor/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/@ipld/dag-cbor/src/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/@ipld/dag-cbor/package.json","cborg":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/cborg.js","multiformats/cid":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/cid.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/lib/car.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/package.json","@ipld/dag-cbor":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/src/index.js","multiformats/cid":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/cid.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/lib/cid.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/package.json","@ipld/dag-cbor":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/src/index.js","@noble/hashes/sha2":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/sha2.js","multiformats/cid":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/cid.js","multiformats/codecs/raw":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/codecs/raw.js","multiformats/hashes/digest":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/hashes/digest.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/lib/commit.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/package.json","./cid.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/lib/cid.js","@ipld/dag-cbor":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/src/index.js","@noble/curves/secp256k1":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/secp256k1.js","@noble/hashes/sha2":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/sha2.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/lib/mst.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/package.json","./cid.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/lib/cid.js","@ipld/dag-cbor":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/src/index.js","@noble/hashes/sha2":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/sha2.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/lib/repo.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/package.json","./car.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/lib/car.js","./cid.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/lib/cid.js","./commit.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/lib/commit.js","./mst.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/lib/mst.js","@ipld/dag-cbor":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/src/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/src/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/package.json","cborg":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/cborg.js","multiformats/cid":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/cid.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/_shortw_utils.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json","./abstract/weierstrass.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/weierstrass.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/curve.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json","../utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/utils.js","./modular.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/modular.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/hash-to-curve.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json","../utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/utils.js","./modular.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/modular.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/modular.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json","../utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/utils.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/weierstrass.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json","../utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/utils.js","./curve.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/curve.js","./modular.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/modular.js","@noble/hashes/hmac.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/hmac.js","@noble/hashes/utils":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/secp256k1.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json","./_shortw_utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/_shortw_utils.js","./abstract/hash-to-curve.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/hash-to-curve.js","./abstract/modular.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/modular.js","./abstract/weierstrass.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/weierstrass.js","./utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/utils.js","@noble/hashes/sha2.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/sha2.js","@noble/hashes/utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/utils.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json","@noble/hashes/utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/_md.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json","./utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/_u64.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/crypto.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/hmac.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json","./utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/sha2.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json","./_md.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/_md.js","./_u64.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/_u64.js","./utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json","@noble/hashes/crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/crypto.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/cborg.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json","./lib/decode.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/decode.js","./lib/encode.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/encode.js","./lib/tagged.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/tagged.js","./lib/token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/1negint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/2bytes.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./byte-utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/3string.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./2bytes.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/2bytes.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/4array.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/5map.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/6tag.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/7float.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/bl.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json","./byte-utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/byte-utils.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/byte-utils.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/common.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/decode.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json","./byte-utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./jump.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/jump.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/encode.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./1negint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/1negint.js","./2bytes.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/2bytes.js","./3string.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/3string.js","./4array.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/4array.js","./5map.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/5map.js","./6tag.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/6tag.js","./7float.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/7float.js","./bl.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/bl.js","./byte-utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./is.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/is.js","./jump.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/jump.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/is.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/jump.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js","./1negint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/1negint.js","./2bytes.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/2bytes.js","./3string.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/3string.js","./4array.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/4array.js","./5map.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/5map.js","./6tag.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/6tag.js","./7float.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/7float.js","./byte-utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/tagged.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/token.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/package.json","../bytes.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bytes.js","../vendor/base-x.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/vendor/base-x.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base32.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/package.json","./base.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base36.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/package.json","./base.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base58.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/package.json","./base.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bytes.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/cid.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/package.json","./bases/base32.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base32.js","./bases/base36.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base36.js","./bases/base58.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base58.js","./bytes.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bytes.js","./hashes/digest.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/hashes/digest.js","./link/interface.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/link/interface.js","./varint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/varint.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/codecs/raw.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/package.json","../bytes.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bytes.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/hashes/digest.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/package.json","../bytes.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bytes.js","../varint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/varint.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/link/interface.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/varint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/package.json","./vendor/varint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/vendor/varint.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/vendor/base-x.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/vendor/varint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/b4a/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/b4a/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/b4a/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-ansi-escapes/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-ansi-escapes/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-ansi-escapes/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-assert/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-assert/package.json","bare-inspect":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-inspect/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-assert/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-events/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-events/package.json","./lib/errors":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-events/lib/errors.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-events/lib/errors.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-events/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-events/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-fs/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-fs/package.json",".":"linked:libbare-fs.4.7.3.so"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-fs/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-fs/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-fs/binding.js","./lib/constants":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-fs/lib/constants.js","./lib/errors":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-fs/lib/errors.js","./promises":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-fs/promises.js","bare-events":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-events/index.js","bare-path":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-path/index.js","bare-stream":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-stream/index.js","bare-url":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-url/index.js","fast-fifo":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/fast-fifo/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-fs/lib/constants.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-fs/package.json","../binding":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-fs/binding.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-fs/lib/errors.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-fs/package.json","bare-os":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-os/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-fs/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-fs/promises.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-fs/package.json",".":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-fs/index.js","bare-events":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-events/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-inspect/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-inspect/package.json",".":"linked:libbare-inspect.3.1.4.so"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-inspect/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-inspect/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-inspect/binding.js","bare-ansi-escapes":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-ansi-escapes/index.js","bare-type":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-type/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-inspect/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-os/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-os/package.json",".":"linked:libbare-os.3.9.3.so"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-os/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-os/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-os/binding.js","./lib/constants":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-os/lib/constants.js","./lib/errors":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-os/lib/errors.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-os/lib/constants.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-os/package.json","../binding":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-os/binding.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-os/lib/errors.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-os/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-os/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-path/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-path/package.json","./lib/posix":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-path/lib/posix.js","./lib/win32":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-path/lib/win32.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-path/lib/constants.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-path/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-path/lib/posix.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-path/package.json","./constants":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-path/lib/constants.js","./shared":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-path/lib/shared.js","./win32":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-path/lib/win32.js","bare-os":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-os/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-path/lib/shared.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-path/package.json","./constants":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-path/lib/constants.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-path/lib/win32.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-path/package.json","./constants":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-path/lib/constants.js","./posix":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-path/lib/posix.js","./shared":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-path/lib/shared.js","bare-os":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-os/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-path/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-stream/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-stream/package.json","./web":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-stream/web.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/b4a/index.js","streamx":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/streamx/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-stream/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-stream/web.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-stream/package.json","streamx":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/streamx/index.js","teex":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/teex/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-type/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-type/package.json",".":"linked:libbare-type.1.1.0.so"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-type/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-type/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-type/binding.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-type/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-url/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-url/package.json",".":"linked:libbare-url.2.4.5.so"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-url/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-url/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-url/binding.js","./lib/errors":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-url/lib/errors.js","./lib/url-search-params":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-url/lib/url-search-params.js","bare-path":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-path/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-url/lib/errors.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-url/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-url/lib/url-search-params.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-url/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-url/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/big-sparse-array/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/big-sparse-array/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/big-sparse-array/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/cborg.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/package.json","./lib/decode.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/decode.js","./lib/encode.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/encode.js","./lib/tagged.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/tagged.js","./lib/token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/0uint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/package.json","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/1negint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/2bytes.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/0uint.js","./byte-utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/3string.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/0uint.js","./2bytes.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/2bytes.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/4array.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/5map.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/6tag.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/0uint.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/7float.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/bl.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/package.json","./byte-utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/byte-utils.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/byte-utils.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/common.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/decode.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/package.json","./byte-utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/common.js","./jump.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/jump.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/encode.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/0uint.js","./1negint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/1negint.js","./2bytes.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/2bytes.js","./3string.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/3string.js","./4array.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/4array.js","./5map.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/5map.js","./6tag.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/6tag.js","./7float.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/7float.js","./bl.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/bl.js","./byte-utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/common.js","./is.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/is.js","./jump.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/jump.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/is.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/jump.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/0uint.js","./1negint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/1negint.js","./2bytes.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/2bytes.js","./3string.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/3string.js","./4array.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/4array.js","./5map.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/5map.js","./6tag.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/6tag.js","./7float.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/7float.js","./byte-utils.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/tagged.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/token.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/codecs/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/codecs/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/codecs/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/compact-encoding/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/compact-encoding/raw.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/compact-encoding/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/compact-encoding/endian.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/corestore/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/corestore/package.json","./lib/audit.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/corestore/lib/audit.js","./lib/notify.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/corestore/lib/notify.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/b4a/index.js","hypercore":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/index.js","hypercore-crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-crypto/index.js","hypercore-errors":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-errors/index.js","hypercore-id-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-id-encoding/index.js","ready-resource":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/ready-resource/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/sodium-universal/index.js","which-runtime":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/which-runtime/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/corestore/lib/audit.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/corestore/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/corestore/lib/notify.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/corestore/package.json","events":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-events/index.js","streamx":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/streamx/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/corestore/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/debounceify/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/debounceify/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/debounceify/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/device-file/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/device-file/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/b4a/index.js","fd-lock":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/fd-lock/index.js","fs":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-fs/index.js","fs-native-extensions":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/fs-native-extensions/index.js","path":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-path/index.js","ready-resource":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/ready-resource/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/device-file/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/events-universal/bare.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/events-universal/package.json","bare-events":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-events/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/events-universal/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/fast-fifo/fixed-size.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/fast-fifo/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/fast-fifo/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/fast-fifo/package.json","./fixed-size":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/fast-fifo/fixed-size.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/fast-fifo/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/fd-lock/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/fd-lock/package.json","fs":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-fs/index.js","fs-native-extensions":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/fs-native-extensions/index.js","ready-resource":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/ready-resource/index.js","resource-on-exit":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/resource-on-exit/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/fd-lock/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/flat-tree/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/flat-tree/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/flat-tree/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/fs-native-extensions/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/fs-native-extensions/package.json",".":"linked:libfs-native-extensions.1.5.0.so","require-addon":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/require-addon/lib/bare.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/fs-native-extensions/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/fs-native-extensions/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/fs-native-extensions/binding.js","which-runtime":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/which-runtime/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/fs-native-extensions/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hyperbee/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hyperbee/package.json","./iterators/diff":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hyperbee/iterators/diff.js","./iterators/history":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hyperbee/iterators/history.js","./iterators/local":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hyperbee/iterators/local.js","./iterators/range":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hyperbee/iterators/range.js","./lib/extension":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hyperbee/lib/extension.js","./lib/messages":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hyperbee/lib/messages.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/b4a/index.js","codecs":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/codecs/index.js","debounceify":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/debounceify/index.js","hypercore-errors":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-errors/index.js","mutexify/promise":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/mutexify/promise.js","rache":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/rache/index.js","ready-resource":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/ready-resource/index.js","resolve-reject-promise":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/resolve-reject-promise/index.js","safety-catch":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/safety-catch/index.js","streamx":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/streamx/index.js","unslab":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/unslab/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hyperbee/iterators/diff.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hyperbee/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hyperbee/iterators/history.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hyperbee/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hyperbee/iterators/local.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hyperbee/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hyperbee/iterators/range.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hyperbee/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hyperbee/lib/extension.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hyperbee/package.json","./messages":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hyperbee/lib/messages.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hyperbee/lib/messages.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hyperbee/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/b4a/index.js","protocol-buffers-encodings":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/protocol-buffers-encodings/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hyperbee/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-crypto/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-crypto/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/compact-encoding/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-crypto/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-errors/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-errors/package.json","hypercore-id-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-id-encoding/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-errors/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-id-encoding/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-id-encoding/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/b4a/index.js","z32":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/z32/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-id-encoding/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-storage/encoding/external.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-storage/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-storage/encoding/spec/hyperschema/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-storage/package.json","../../external.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-storage/encoding/external.js","hyperschema/runtime":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hyperschema/runtime.cjs"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-storage/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-storage/package.json","./lib/keys.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-storage/lib/keys.js","./lib/streams.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-storage/lib/streams.js","./lib/tx.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-storage/lib/tx.js","./lib/view.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-storage/lib/view.js","./migrations/0":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-storage/migrations/0/index.js","./migrations/1":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-storage/migrations/1/index.js","device-file":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/device-file/index.js","fs":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-fs/index.js","path":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-path/index.js","resolve-reject-promise":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/resolve-reject-promise/index.js","rocksdb-native":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/rocksdb-native/index.js","scope-lock":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/scope-lock/index.js","xache":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/xache/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-storage/lib/block-dependency-stream.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-storage/package.json","./keys":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-storage/lib/keys.js","streamx":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/streamx/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-storage/lib/close-error-stream.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-storage/package.json","streamx":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/streamx/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-storage/lib/keys.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-storage/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/compact-encoding/index.js","index-encoder":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/index-encoder/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-storage/lib/streams.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-storage/package.json","../encoding/spec/hyperschema":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-storage/encoding/spec/hyperschema/index.js","./block-dependency-stream.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-storage/lib/block-dependency-stream.js","./keys.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-storage/lib/keys.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-storage/lib/tx.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-storage/package.json","../encoding/spec/hyperschema":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-storage/encoding/spec/hyperschema/index.js","./keys.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-storage/lib/keys.js","./view.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-storage/lib/view.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/compact-encoding/index.js","flat-tree":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/flat-tree/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-storage/lib/view.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-storage/package.json","./close-error-stream.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-storage/lib/close-error-stream.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/b4a/index.js","streamx":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/streamx/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-storage/migrations/0/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-storage/package.json","../../lib/tx.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-storage/lib/tx.js","../../lib/view.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-storage/lib/view.js","./messages.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-storage/migrations/0/messages.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/compact-encoding/index.js","flat-tree":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/flat-tree/index.js","fs":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-fs/index.js","hypercore-crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-crypto/index.js","path":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-path/index.js","streamx":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/streamx/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-storage/migrations/0/messages.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-storage/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/compact-encoding/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-storage/migrations/1/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-storage/package.json","../../encoding/spec/hyperschema":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-storage/encoding/spec/hyperschema/index.js","../../lib/keys.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-storage/lib/keys.js","../../lib/tx.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-storage/lib/tx.js","../../lib/view.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-storage/lib/view.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/compact-encoding/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-storage/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/package.json","./lib/caps":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/caps.js","./lib/core":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/core.js","./lib/default-encryption":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/default-encryption.js","./lib/download":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/download.js","./lib/feature-flags":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/feature-flags.js","./lib/fully-remote-proof":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/fully-remote-proof.js","./lib/info":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/info.js","./lib/inspect":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/inspect.js","./lib/mark-bitfield":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/mark-bitfield.js","./lib/merkle-tree":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/merkle-tree.js","./lib/replicator":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/replicator.js","./lib/streams":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/streams.js","./lib/verifier":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/verifier.js","./lib/wants":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/wants.js","@hyperswarm/secret-stream":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/@hyperswarm/secret-stream/index.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/compact-encoding/index.js","events":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-events/index.js","flat-tree":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/flat-tree/index.js","hypercore-crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-crypto/index.js","hypercore-errors":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-errors/index.js","hypercore-id-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-id-encoding/index.js","hypercore-storage":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-storage/index.js","is-options":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/is-options/index.js","nanoassert":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/nanoassert/index.js","protomux":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/protomux/index.js","safety-catch":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/safety-catch/index.js","unslab":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/unslab/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/audit.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/package.json","./merkle-tree":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/merkle-tree.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/b4a/index.js","flat-tree":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/flat-tree/index.js","hypercore-crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-crypto/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/bit-interlude.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/package.json","./compat":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/compat.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/bitfield.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/package.json","./compat":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/compat.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/b4a/index.js","big-sparse-array":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/big-sparse-array/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/caps.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/compact-encoding/index.js","hypercore-crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-crypto/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/compat.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/package.json","quickbit-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/quickbit-universal/index.js","quickbit-universal/fallback":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/quickbit-universal/fallback.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/copy-prologue.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/package.json","./bitfield":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/bitfield.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/b4a/index.js","flat-tree":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/flat-tree/index.js","hypercore-crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-crypto/index.js","quickbit-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/quickbit-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/core.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/package.json","./audit":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/audit.js","./bit-interlude":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/bit-interlude.js","./bitfield":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/bitfield.js","./copy-prologue":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/copy-prologue.js","./merkle-tree":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/merkle-tree.js","./mutex":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/mutex.js","./remote-bitfield":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/remote-bitfield.js","./replicator":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/replicator.js","./session-state":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/session-state.js","./verifier":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/verifier.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/b4a/index.js","hypercore-crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-crypto/index.js","hypercore-errors":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-errors/index.js","unslab":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/unslab/index.js","z32":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/z32/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/default-encryption.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/package.json","./caps":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/caps.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/compact-encoding/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/download.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/feature-flags.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/fully-remote-proof.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/package.json","./merkle-tree.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/merkle-tree.js","./messages.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/messages.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/compact-encoding/index.js","flat-tree":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/flat-tree/index.js","hypercore-crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-crypto/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/hotswap-queue.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/info.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/inspect.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/mark-bitfield.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/package.json","./compat":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/compat.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/b4a/index.js","big-sparse-array":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/big-sparse-array/index.js","streamx":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/streamx/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/merkle-tree.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/package.json","./caps":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/caps.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/b4a/index.js","flat-tree":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/flat-tree/index.js","hypercore-crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-crypto/index.js","hypercore-errors":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-errors/index.js","unslab":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/unslab/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/messages.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/package.json","./caps":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/caps.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/compact-encoding/index.js","hypercore-errors":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-errors/index.js","unslab":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/unslab/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/multisig.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/package.json","./merkle-tree":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/merkle-tree.js","./messages":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/messages.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/compact-encoding/index.js","flat-tree":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/flat-tree/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/mutex.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/receiver-queue.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/package.json","fast-fifo":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/fast-fifo/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/remote-bitfield.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/package.json","./compat":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/compat.js","big-sparse-array":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/big-sparse-array/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/replicator.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/package.json","./caps":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/caps.js","./hotswap-queue":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/hotswap-queue.js","./merkle-tree":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/merkle-tree.js","./messages":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/messages.js","./mutex":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/mutex.js","./receiver-queue":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/receiver-queue.js","./remote-bitfield":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/remote-bitfield.js","./wants":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/wants.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/b4a/index.js","flat-tree":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/flat-tree/index.js","hypercore-errors":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-errors/index.js","random-array-iterator":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/random-array-iterator/index.js","safety-catch":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/safety-catch/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/session-state.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/package.json","./bitfield":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/bitfield.js","./merkle-tree":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/merkle-tree.js","./mutex":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/mutex.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/b4a/index.js","flat-tree":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/flat-tree/index.js","hypercore-crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-crypto/index.js","hypercore-errors":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-errors/index.js","hypercore-storage":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-storage/index.js","nanoassert":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/nanoassert/index.js","quickbit-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/quickbit-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/streams.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/package.json","streamx":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/streamx/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/verifier.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/package.json","./caps":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/caps.js","./messages":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/messages.js","./multisig":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/multisig.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/compact-encoding/index.js","flat-tree":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/flat-tree/index.js","hypercore-crypto":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-crypto/index.js","hypercore-errors":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-errors/index.js","unslab":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/unslab/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/wants.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hyperschema/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hyperschema/runtime.cjs":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hyperschema/package.json","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/compact-encoding/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/index-encoder/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/index-encoder/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/index-encoder/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/is-options/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/is-options/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/is-options/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/bases/base.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/multiformats/package.json","../bytes.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/bytes.js","../vendor/base-x.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/vendor/base-x.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/bases/base32.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/multiformats/package.json","./base.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/bases/base.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/bases/base36.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/multiformats/package.json","./base.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/bases/base.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/bases/base58.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/multiformats/package.json","./base.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/bases/base.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/bytes.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/multiformats/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/cid.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/multiformats/package.json","./bases/base32.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/bases/base32.js","./bases/base36.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/bases/base36.js","./bases/base58.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/bases/base58.js","./bytes.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/bytes.js","./hashes/digest.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/hashes/digest.js","./link/interface.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/link/interface.js","./varint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/varint.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/hashes/digest.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/multiformats/package.json","../bytes.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/bytes.js","../varint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/varint.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/link/interface.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/multiformats/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/varint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/multiformats/package.json","./vendor/varint.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/vendor/varint.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/vendor/base-x.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/multiformats/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/vendor/varint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/multiformats/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/multiformats/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/mutexify/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/mutexify/package.json","queue-tick":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/queue-tick/process-next-tick.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/mutexify/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/mutexify/promise.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/mutexify/package.json",".":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/mutexify/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/nanoassert/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/nanoassert/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/nanoassert/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/noise-curve-ed/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/noise-curve-ed/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/b4a/index.js","nanoassert":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/nanoassert/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/noise-curve-ed/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/noise-handshake/cipher.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/noise-handshake/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/b4a/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/noise-handshake/dh.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/noise-handshake/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/b4a/index.js","nanoassert":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/nanoassert/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/noise-handshake/hkdf.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/noise-handshake/package.json","./hmac":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/noise-handshake/hmac.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/noise-handshake/hmac.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/noise-handshake/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/b4a/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/noise-handshake/noise.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/noise-handshake/package.json","./hkdf":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/noise-handshake/hkdf.js","./symmetric-state":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/noise-handshake/symmetric-state.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/b4a/index.js","nanoassert":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/nanoassert/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/noise-handshake/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/noise-handshake/symmetric-state.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/noise-handshake/package.json","./cipher":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/noise-handshake/cipher.js","./dh":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/noise-handshake/dh.js","./hkdf":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/noise-handshake/hkdf.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/b4a/index.js","nanoassert":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/nanoassert/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/protocol-buffers-encodings/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/protocol-buffers-encodings/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/b4a/index.js","signed-varint":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/signed-varint/index.js","varint":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/varint/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/protocol-buffers-encodings/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/protomux/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/protomux/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/compact-encoding/index.js","queue-tick":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/queue-tick/process-next-tick.js","safety-catch":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/safety-catch/index.js","unslab":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/unslab/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/protomux/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/queue-tick/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/queue-tick/process-next-tick.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/queue-tick/package.json","./queue-microtask":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/queue-tick/queue-microtask.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/queue-tick/queue-microtask.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/queue-tick/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/quickbit-native/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/quickbit-native/package.json",".":"linked:libquickbit-native.2.4.8.so","require-addon":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/require-addon/lib/bare.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/quickbit-native/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/quickbit-native/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/quickbit-native/binding.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/quickbit-native/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/quickbit-universal/fallback.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/quickbit-universal/package.json","simdle-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/simdle-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/quickbit-universal/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/quickbit-universal/package.json","./fallback":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/quickbit-universal/fallback.js","quickbit-native":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/quickbit-native/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/quickbit-universal/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/rache/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/rache/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/rache/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/random-array-iterator/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/random-array-iterator/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/random-array-iterator/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/ready-resource/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/ready-resource/package.json","events":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-events/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/ready-resource/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/refcounter/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/refcounter/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/refcounter/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/require-addon/lib/bare.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/require-addon/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/require-addon/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/resolve-reject-promise/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/resolve-reject-promise/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/resolve-reject-promise/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/resource-on-exit/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/resource-on-exit/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/resource-on-exit/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/rocksdb-native/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/rocksdb-native/package.json",".":"linked:librocksdb-native.3.17.2.so","require-addon":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/require-addon/lib/bare.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/rocksdb-native/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/rocksdb-native/package.json","./lib/column-family":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/rocksdb-native/lib/column-family.js","./lib/constants":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/rocksdb-native/lib/constants.js","./lib/filter-policy":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/rocksdb-native/lib/filter-policy.js","./lib/iterator":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/rocksdb-native/lib/iterator.js","./lib/snapshot":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/rocksdb-native/lib/snapshot.js","./lib/state":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/rocksdb-native/lib/state.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/rocksdb-native/lib/batch.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/rocksdb-native/package.json","../binding":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/rocksdb-native/binding.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/compact-encoding/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/rocksdb-native/lib/column-family.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/rocksdb-native/package.json","../binding":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/rocksdb-native/binding.js","./constants":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/rocksdb-native/lib/constants.js","./filter-policy":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/rocksdb-native/lib/filter-policy.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/rocksdb-native/lib/constants.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/rocksdb-native/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/rocksdb-native/lib/filter-policy.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/rocksdb-native/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/rocksdb-native/lib/iterator.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/rocksdb-native/package.json","../binding":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/rocksdb-native/binding.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/compact-encoding/index.js","streamx":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/streamx/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/rocksdb-native/lib/snapshot.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/rocksdb-native/package.json","../binding":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/rocksdb-native/binding.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/rocksdb-native/lib/state.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/rocksdb-native/package.json","../binding":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/rocksdb-native/binding.js","./batch":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/rocksdb-native/lib/batch.js","./column-family":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/rocksdb-native/lib/column-family.js","./constants":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/rocksdb-native/lib/constants.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/compact-encoding/index.js","ready-resource":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/ready-resource/index.js","refcounter":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/refcounter/index.js","resolve-reject-promise":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/resolve-reject-promise/index.js","signal-promise":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/signal-promise/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/rocksdb-native/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/safety-catch/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/safety-catch/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/safety-catch/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/scope-lock/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/scope-lock/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/scope-lock/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/signal-promise/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/signal-promise/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/signal-promise/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/signed-varint/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/signed-varint/package.json","varint":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/varint/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/signed-varint/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/simdle-native/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/simdle-native/package.json",".":"linked:libsimdle-native.1.3.9.so","require-addon":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/require-addon/lib/bare.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/simdle-native/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/simdle-native/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/simdle-native/binding.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/simdle-native/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/simdle-universal/fallback.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/simdle-universal/package.json","./scalar":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/simdle-universal/scalar.js","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/simdle-universal/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/simdle-universal/package.json","./fallback":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/simdle-universal/fallback.js","simdle-native":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/simdle-native/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/simdle-universal/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/simdle-universal/scalar.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/simdle-universal/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/sodium-native/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/sodium-native/package.json",".":"linked:libsodium-native.5.1.0.so","require-addon":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/require-addon/lib/bare.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/sodium-native/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/sodium-native/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/sodium-native/binding.js","assert":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-assert/index.js","which-runtime":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/which-runtime/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/sodium-native/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/sodium-secretstream/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/sodium-secretstream/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/b4a/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/sodium-secretstream/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/sodium-universal/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/sodium-universal/package.json","sodium-native":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/sodium-native/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/sodium-universal/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/streamx/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/streamx/package.json","./lib/errors.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/streamx/lib/errors.js","events-universal":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/events-universal/bare.js","fast-fifo":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/fast-fifo/index.js","text-decoder":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/text-decoder/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/streamx/lib/errors.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/streamx/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/streamx/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/teex/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/teex/package.json","streamx":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/streamx/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/teex/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/text-decoder/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/text-decoder/package.json","./lib/pass-through-decoder":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/text-decoder/lib/pass-through-decoder.js","./lib/utf8-decoder":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/text-decoder/lib/utf8-decoder.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/text-decoder/lib/pass-through-decoder.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/text-decoder/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/text-decoder/lib/utf8-decoder.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/text-decoder/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/text-decoder/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/timeout-refresh/browser.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/timeout-refresh/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/timeout-refresh/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/timeout-refresh/package.json","./browser":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/timeout-refresh/browser.js","./node":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/timeout-refresh/node.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/timeout-refresh/node.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/timeout-refresh/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/timeout-refresh/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/unslab/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/unslab/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/unslab/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/varint/decode.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/varint/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/varint/encode.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/varint/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/varint/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/varint/package.json","./decode.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/varint/decode.js","./encode.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/varint/encode.js","./length.js":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/varint/length.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/varint/length.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/varint/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/varint/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/which-runtime/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/which-runtime/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/which-runtime/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/xache/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/xache/package.json"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/xache/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/z32/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/z32/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/z32/package.json":{},"/node_modules/hyper-proto-peer/node_modules/atproto-store/package.json":{},"/node_modules/hyper-proto-peer/node_modules/b4a/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/b4a/package.json"},"/node_modules/hyper-proto-peer/node_modules/b4a/package.json":{},"/node_modules/hyper-proto-peer/node_modules/bare-abort/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-abort/package.json",".":"linked:libbare-abort.2.0.13.so"},"/node_modules/hyper-proto-peer/node_modules/bare-abort/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-abort/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/bare-abort/binding.js"},"/node_modules/hyper-proto-peer/node_modules/bare-abort/package.json":{},"/node_modules/hyper-proto-peer/node_modules/bare-ansi-escapes/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-ansi-escapes/package.json"},"/node_modules/hyper-proto-peer/node_modules/bare-ansi-escapes/package.json":{},"/node_modules/hyper-proto-peer/node_modules/bare-assert/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-assert/package.json","bare-inspect":"/node_modules/hyper-proto-peer/node_modules/bare-inspect/index.js"},"/node_modules/hyper-proto-peer/node_modules/bare-assert/package.json":{},"/node_modules/hyper-proto-peer/node_modules/bare-buffer/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-buffer/package.json",".":"linked:libbare-buffer.3.6.1.so"},"/node_modules/hyper-proto-peer/node_modules/bare-buffer/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-buffer/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/bare-buffer/binding.js","./lib/ascii":"/node_modules/hyper-proto-peer/node_modules/bare-buffer/lib/ascii.js","./lib/base64":"/node_modules/hyper-proto-peer/node_modules/bare-buffer/lib/base64.js","./lib/base64url":"/node_modules/hyper-proto-peer/node_modules/bare-buffer/lib/base64url.js","./lib/constants":"/node_modules/hyper-proto-peer/node_modules/bare-buffer/lib/constants.js","./lib/hex":"/node_modules/hyper-proto-peer/node_modules/bare-buffer/lib/hex.js","./lib/latin1":"/node_modules/hyper-proto-peer/node_modules/bare-buffer/lib/latin1.js","./lib/utf16le":"/node_modules/hyper-proto-peer/node_modules/bare-buffer/lib/utf16le.js","./lib/utf8":"/node_modules/hyper-proto-peer/node_modules/bare-buffer/lib/utf8.js"},"/node_modules/hyper-proto-peer/node_modules/bare-buffer/lib/ascii.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-buffer/package.json","../binding":"/node_modules/hyper-proto-peer/node_modules/bare-buffer/binding.js"},"/node_modules/hyper-proto-peer/node_modules/bare-buffer/lib/base64.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-buffer/package.json","../binding":"/node_modules/hyper-proto-peer/node_modules/bare-buffer/binding.js"},"/node_modules/hyper-proto-peer/node_modules/bare-buffer/lib/base64url.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-buffer/package.json","../binding":"/node_modules/hyper-proto-peer/node_modules/bare-buffer/binding.js"},"/node_modules/hyper-proto-peer/node_modules/bare-buffer/lib/constants.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-buffer/package.json","../binding":"/node_modules/hyper-proto-peer/node_modules/bare-buffer/binding.js"},"/node_modules/hyper-proto-peer/node_modules/bare-buffer/lib/hex.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-buffer/package.json","../binding":"/node_modules/hyper-proto-peer/node_modules/bare-buffer/binding.js"},"/node_modules/hyper-proto-peer/node_modules/bare-buffer/lib/latin1.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-buffer/package.json","../binding":"/node_modules/hyper-proto-peer/node_modules/bare-buffer/binding.js"},"/node_modules/hyper-proto-peer/node_modules/bare-buffer/lib/utf16le.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-buffer/package.json","../binding":"/node_modules/hyper-proto-peer/node_modules/bare-buffer/binding.js"},"/node_modules/hyper-proto-peer/node_modules/bare-buffer/lib/utf8.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-buffer/package.json","../binding":"/node_modules/hyper-proto-peer/node_modules/bare-buffer/binding.js"},"/node_modules/hyper-proto-peer/node_modules/bare-buffer/package.json":{},"/node_modules/hyper-proto-peer/node_modules/bare-dns/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-dns/package.json",".":"linked:libbare-dns.2.1.4.so"},"/node_modules/hyper-proto-peer/node_modules/bare-dns/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-dns/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/bare-dns/binding.js"},"/node_modules/hyper-proto-peer/node_modules/bare-dns/package.json":{},"/node_modules/hyper-proto-peer/node_modules/bare-env/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-env/package.json","bare-os":"/node_modules/hyper-proto-peer/node_modules/bare-os/index.js"},"/node_modules/hyper-proto-peer/node_modules/bare-env/package.json":{},"/node_modules/hyper-proto-peer/node_modules/bare-events/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-events/package.json","./lib/errors":"/node_modules/hyper-proto-peer/node_modules/bare-events/lib/errors.js"},"/node_modules/hyper-proto-peer/node_modules/bare-events/lib/errors.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-events/package.json"},"/node_modules/hyper-proto-peer/node_modules/bare-events/package.json":{},"/node_modules/hyper-proto-peer/node_modules/bare-fetch/global.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-fetch/package.json",".":"/node_modules/hyper-proto-peer/node_modules/bare-fetch/index.js"},"/node_modules/hyper-proto-peer/node_modules/bare-fetch/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-fetch/package.json","./lib/errors":"/node_modules/hyper-proto-peer/node_modules/bare-fetch/lib/errors.js","./lib/headers":"/node_modules/hyper-proto-peer/node_modules/bare-fetch/lib/headers.js","./lib/request":"/node_modules/hyper-proto-peer/node_modules/bare-fetch/lib/request.js","./lib/response":"/node_modules/hyper-proto-peer/node_modules/bare-fetch/lib/response.js","./lib/response-stream":"/node_modules/hyper-proto-peer/node_modules/bare-fetch/lib/response-stream.js","bare-http1":"/node_modules/hyper-proto-peer/node_modules/bare-http1/index.js","bare-https":"/node_modules/hyper-proto-peer/node_modules/bare-https/index.js","bare-stream/web":"/node_modules/hyper-proto-peer/node_modules/bare-stream/web.js"},"/node_modules/hyper-proto-peer/node_modules/bare-fetch/lib/body.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-fetch/package.json","./errors":"/node_modules/hyper-proto-peer/node_modules/bare-fetch/lib/errors.js","./headers":"/node_modules/hyper-proto-peer/node_modules/bare-fetch/lib/headers.js","bare-form-data":"/node_modules/hyper-proto-peer/node_modules/bare-form-data/index.js","bare-stream/web":"/node_modules/hyper-proto-peer/node_modules/bare-stream/web.js","bare-url":"/node_modules/hyper-proto-peer/node_modules/bare-url/index.js"},"/node_modules/hyper-proto-peer/node_modules/bare-fetch/lib/errors.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-fetch/package.json"},"/node_modules/hyper-proto-peer/node_modules/bare-fetch/lib/headers.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-fetch/package.json","./errors":"/node_modules/hyper-proto-peer/node_modules/bare-fetch/lib/errors.js","bare-mime":"/node_modules/hyper-proto-peer/node_modules/bare-mime/index.js"},"/node_modules/hyper-proto-peer/node_modules/bare-fetch/lib/request.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-fetch/package.json","./body":"/node_modules/hyper-proto-peer/node_modules/bare-fetch/lib/body.js","./errors":"/node_modules/hyper-proto-peer/node_modules/bare-fetch/lib/errors.js","./headers":"/node_modules/hyper-proto-peer/node_modules/bare-fetch/lib/headers.js","bare-url":"/node_modules/hyper-proto-peer/node_modules/bare-url/index.js"},"/node_modules/hyper-proto-peer/node_modules/bare-fetch/lib/response-stream.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-fetch/package.json","bare-stream":"/node_modules/hyper-proto-peer/node_modules/bare-stream/index.js","bare-zlib":"/node_modules/hyper-proto-peer/node_modules/bare-zlib/index.js"},"/node_modules/hyper-proto-peer/node_modules/bare-fetch/lib/response.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-fetch/package.json","./body":"/node_modules/hyper-proto-peer/node_modules/bare-fetch/lib/body.js","./errors":"/node_modules/hyper-proto-peer/node_modules/bare-fetch/lib/errors.js","./headers":"/node_modules/hyper-proto-peer/node_modules/bare-fetch/lib/headers.js"},"/node_modules/hyper-proto-peer/node_modules/bare-fetch/package.json":{},"/node_modules/hyper-proto-peer/node_modules/bare-form-data/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-form-data/package.json","./lib/errors":"/node_modules/hyper-proto-peer/node_modules/bare-form-data/lib/errors.js","bare-buffer":"/node_modules/hyper-proto-peer/node_modules/bare-buffer/index.js","bare-stream/web":"/node_modules/hyper-proto-peer/node_modules/bare-stream/web.js"},"/node_modules/hyper-proto-peer/node_modules/bare-form-data/lib/errors.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-form-data/package.json"},"/node_modules/hyper-proto-peer/node_modules/bare-form-data/package.json":{},"/node_modules/hyper-proto-peer/node_modules/bare-fs/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-fs/package.json",".":"linked:libbare-fs.4.7.3.so"},"/node_modules/hyper-proto-peer/node_modules/bare-fs/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-fs/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/bare-fs/binding.js","./lib/constants":"/node_modules/hyper-proto-peer/node_modules/bare-fs/lib/constants.js","./lib/errors":"/node_modules/hyper-proto-peer/node_modules/bare-fs/lib/errors.js","./promises":"/node_modules/hyper-proto-peer/node_modules/bare-fs/promises.js","bare-events":"/node_modules/hyper-proto-peer/node_modules/bare-events/index.js","bare-path":"/node_modules/hyper-proto-peer/node_modules/bare-path/index.js","bare-stream":"/node_modules/hyper-proto-peer/node_modules/bare-stream/index.js","bare-url":"/node_modules/hyper-proto-peer/node_modules/bare-url/index.js","fast-fifo":"/node_modules/hyper-proto-peer/node_modules/fast-fifo/index.js"},"/node_modules/hyper-proto-peer/node_modules/bare-fs/lib/constants.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-fs/package.json","../binding":"/node_modules/hyper-proto-peer/node_modules/bare-fs/binding.js"},"/node_modules/hyper-proto-peer/node_modules/bare-fs/lib/errors.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-fs/package.json","bare-os":"/node_modules/hyper-proto-peer/node_modules/bare-os/index.js"},"/node_modules/hyper-proto-peer/node_modules/bare-fs/package.json":{},"/node_modules/hyper-proto-peer/node_modules/bare-fs/promises.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-fs/package.json",".":"/node_modules/hyper-proto-peer/node_modules/bare-fs/index.js","bare-events":"/node_modules/hyper-proto-peer/node_modules/bare-events/index.js"},"/node_modules/hyper-proto-peer/node_modules/bare-hrtime/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-hrtime/package.json",".":"linked:libbare-hrtime.2.1.1.so"},"/node_modules/hyper-proto-peer/node_modules/bare-hrtime/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-hrtime/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/bare-hrtime/binding.js"},"/node_modules/hyper-proto-peer/node_modules/bare-hrtime/package.json":{},"/node_modules/hyper-proto-peer/node_modules/bare-http-parser/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-http-parser/package.json","./lib/errors":"/node_modules/hyper-proto-peer/node_modules/bare-http-parser/lib/errors.js"},"/node_modules/hyper-proto-peer/node_modules/bare-http-parser/lib/errors.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-http-parser/package.json"},"/node_modules/hyper-proto-peer/node_modules/bare-http-parser/package.json":{},"/node_modules/hyper-proto-peer/node_modules/bare-http1/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-http1/package.json","./lib/agent":"/node_modules/hyper-proto-peer/node_modules/bare-http1/lib/agent.js","./lib/client-connection":"/node_modules/hyper-proto-peer/node_modules/bare-http1/lib/client-connection.js","./lib/client-request":"/node_modules/hyper-proto-peer/node_modules/bare-http1/lib/client-request.js","./lib/constants":"/node_modules/hyper-proto-peer/node_modules/bare-http1/lib/constants.js","./lib/errors":"/node_modules/hyper-proto-peer/node_modules/bare-http1/lib/errors.js","./lib/incoming-message":"/node_modules/hyper-proto-peer/node_modules/bare-http1/lib/incoming-message.js","./lib/outgoing-message":"/node_modules/hyper-proto-peer/node_modules/bare-http1/lib/outgoing-message.js","./lib/server":"/node_modules/hyper-proto-peer/node_modules/bare-http1/lib/server.js","./lib/server-connection":"/node_modules/hyper-proto-peer/node_modules/bare-http1/lib/server-connection.js","./lib/server-response":"/node_modules/hyper-proto-peer/node_modules/bare-http1/lib/server-response.js"},"/node_modules/hyper-proto-peer/node_modules/bare-http1/lib/agent.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-http1/package.json","./client-connection":"/node_modules/hyper-proto-peer/node_modules/bare-http1/lib/client-connection.js","./errors":"/node_modules/hyper-proto-peer/node_modules/bare-http1/lib/errors.js","bare-events":"/node_modules/hyper-proto-peer/node_modules/bare-events/index.js","bare-tcp":"/node_modules/hyper-proto-peer/node_modules/bare-tcp/index.js"},"/node_modules/hyper-proto-peer/node_modules/bare-http1/lib/client-connection.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-http1/package.json","./errors":"/node_modules/hyper-proto-peer/node_modules/bare-http1/lib/errors.js","./incoming-message":"/node_modules/hyper-proto-peer/node_modules/bare-http1/lib/incoming-message.js","bare-http-parser":"/node_modules/hyper-proto-peer/node_modules/bare-http-parser/index.js"},"/node_modules/hyper-proto-peer/node_modules/bare-http1/lib/client-request.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-http1/package.json","./agent":"/node_modules/hyper-proto-peer/node_modules/bare-http1/lib/agent.js","./outgoing-message":"/node_modules/hyper-proto-peer/node_modules/bare-http1/lib/outgoing-message.js","./validate":"/node_modules/hyper-proto-peer/node_modules/bare-http1/lib/validate.js"},"/node_modules/hyper-proto-peer/node_modules/bare-http1/lib/constants.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-http1/package.json"},"/node_modules/hyper-proto-peer/node_modules/bare-http1/lib/errors.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-http1/package.json"},"/node_modules/hyper-proto-peer/node_modules/bare-http1/lib/incoming-message.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-http1/package.json","bare-stream":"/node_modules/hyper-proto-peer/node_modules/bare-stream/index.js"},"/node_modules/hyper-proto-peer/node_modules/bare-http1/lib/outgoing-message.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-http1/package.json","./errors":"/node_modules/hyper-proto-peer/node_modules/bare-http1/lib/errors.js","./validate":"/node_modules/hyper-proto-peer/node_modules/bare-http1/lib/validate.js","bare-stream":"/node_modules/hyper-proto-peer/node_modules/bare-stream/index.js"},"/node_modules/hyper-proto-peer/node_modules/bare-http1/lib/server-connection.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-http1/package.json","./incoming-message":"/node_modules/hyper-proto-peer/node_modules/bare-http1/lib/incoming-message.js","./server-response":"/node_modules/hyper-proto-peer/node_modules/bare-http1/lib/server-response.js","bare-http-parser":"/node_modules/hyper-proto-peer/node_modules/bare-http-parser/index.js","bare-stream":"/node_modules/hyper-proto-peer/node_modules/bare-stream/index.js"},"/node_modules/hyper-proto-peer/node_modules/bare-http1/lib/server-response.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-http1/package.json","./constants":"/node_modules/hyper-proto-peer/node_modules/bare-http1/lib/constants.js","./outgoing-message":"/node_modules/hyper-proto-peer/node_modules/bare-http1/lib/outgoing-message.js","./validate":"/node_modules/hyper-proto-peer/node_modules/bare-http1/lib/validate.js","bare-stream":"/node_modules/hyper-proto-peer/node_modules/bare-stream/index.js"},"/node_modules/hyper-proto-peer/node_modules/bare-http1/lib/server.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-http1/package.json","./server-connection":"/node_modules/hyper-proto-peer/node_modules/bare-http1/lib/server-connection.js","bare-tcp":"/node_modules/hyper-proto-peer/node_modules/bare-tcp/index.js"},"/node_modules/hyper-proto-peer/node_modules/bare-http1/lib/validate.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-http1/package.json","./errors":"/node_modules/hyper-proto-peer/node_modules/bare-http1/lib/errors.js"},"/node_modules/hyper-proto-peer/node_modules/bare-http1/package.json":{},"/node_modules/hyper-proto-peer/node_modules/bare-https/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-https/package.json","./lib/agent":"/node_modules/hyper-proto-peer/node_modules/bare-https/lib/agent.js","./lib/client-request":"/node_modules/hyper-proto-peer/node_modules/bare-https/lib/client-request.js","./lib/server":"/node_modules/hyper-proto-peer/node_modules/bare-https/lib/server.js"},"/node_modules/hyper-proto-peer/node_modules/bare-https/lib/agent.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-https/package.json","./socket":"/node_modules/hyper-proto-peer/node_modules/bare-https/lib/socket.js","bare-http1":"/node_modules/hyper-proto-peer/node_modules/bare-http1/index.js"},"/node_modules/hyper-proto-peer/node_modules/bare-https/lib/client-request.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-https/package.json","./agent":"/node_modules/hyper-proto-peer/node_modules/bare-https/lib/agent.js","bare-http1":"/node_modules/hyper-proto-peer/node_modules/bare-http1/index.js"},"/node_modules/hyper-proto-peer/node_modules/bare-https/lib/server.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-https/package.json","./socket":"/node_modules/hyper-proto-peer/node_modules/bare-https/lib/socket.js","bare-http1":"/node_modules/hyper-proto-peer/node_modules/bare-http1/index.js","bare-tcp":"/node_modules/hyper-proto-peer/node_modules/bare-tcp/index.js"},"/node_modules/hyper-proto-peer/node_modules/bare-https/lib/socket.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-https/package.json","bare-tls":"/node_modules/hyper-proto-peer/node_modules/bare-tls/index.js"},"/node_modules/hyper-proto-peer/node_modules/bare-https/package.json":{},"/node_modules/hyper-proto-peer/node_modules/bare-inspect/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-inspect/package.json",".":"linked:libbare-inspect.3.1.4.so"},"/node_modules/hyper-proto-peer/node_modules/bare-inspect/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-inspect/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/bare-inspect/binding.js","bare-ansi-escapes":"/node_modules/hyper-proto-peer/node_modules/bare-ansi-escapes/index.js","bare-type":"/node_modules/hyper-proto-peer/node_modules/bare-type/index.js"},"/node_modules/hyper-proto-peer/node_modules/bare-inspect/package.json":{},"/node_modules/hyper-proto-peer/node_modules/bare-mime/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-mime/package.json"},"/node_modules/hyper-proto-peer/node_modules/bare-mime/package.json":{},"/node_modules/hyper-proto-peer/node_modules/bare-net/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-net/package.json","./lib/constants":"/node_modules/hyper-proto-peer/node_modules/bare-net/lib/constants.js","bare-events":"/node_modules/hyper-proto-peer/node_modules/bare-events/index.js","bare-pipe":"/node_modules/hyper-proto-peer/node_modules/bare-pipe/index.js","bare-stream":"/node_modules/hyper-proto-peer/node_modules/bare-stream/index.js","bare-tcp":"/node_modules/hyper-proto-peer/node_modules/bare-tcp/index.js"},"/node_modules/hyper-proto-peer/node_modules/bare-net/lib/constants.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-net/package.json"},"/node_modules/hyper-proto-peer/node_modules/bare-net/package.json":{},"/node_modules/hyper-proto-peer/node_modules/bare-os/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-os/package.json",".":"linked:libbare-os.3.9.3.so"},"/node_modules/hyper-proto-peer/node_modules/bare-os/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-os/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/bare-os/binding.js","./lib/constants":"/node_modules/hyper-proto-peer/node_modules/bare-os/lib/constants.js","./lib/errors":"/node_modules/hyper-proto-peer/node_modules/bare-os/lib/errors.js"},"/node_modules/hyper-proto-peer/node_modules/bare-os/lib/constants.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-os/package.json","../binding":"/node_modules/hyper-proto-peer/node_modules/bare-os/binding.js"},"/node_modules/hyper-proto-peer/node_modules/bare-os/lib/errors.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-os/package.json"},"/node_modules/hyper-proto-peer/node_modules/bare-os/package.json":{},"/node_modules/hyper-proto-peer/node_modules/bare-path/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-path/package.json","./lib/posix":"/node_modules/hyper-proto-peer/node_modules/bare-path/lib/posix.js","./lib/win32":"/node_modules/hyper-proto-peer/node_modules/bare-path/lib/win32.js"},"/node_modules/hyper-proto-peer/node_modules/bare-path/lib/constants.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-path/package.json"},"/node_modules/hyper-proto-peer/node_modules/bare-path/lib/posix.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-path/package.json","./constants":"/node_modules/hyper-proto-peer/node_modules/bare-path/lib/constants.js","./shared":"/node_modules/hyper-proto-peer/node_modules/bare-path/lib/shared.js","./win32":"/node_modules/hyper-proto-peer/node_modules/bare-path/lib/win32.js","bare-os":"/node_modules/hyper-proto-peer/node_modules/bare-os/index.js"},"/node_modules/hyper-proto-peer/node_modules/bare-path/lib/shared.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-path/package.json","./constants":"/node_modules/hyper-proto-peer/node_modules/bare-path/lib/constants.js"},"/node_modules/hyper-proto-peer/node_modules/bare-path/lib/win32.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-path/package.json","./constants":"/node_modules/hyper-proto-peer/node_modules/bare-path/lib/constants.js","./posix":"/node_modules/hyper-proto-peer/node_modules/bare-path/lib/posix.js","./shared":"/node_modules/hyper-proto-peer/node_modules/bare-path/lib/shared.js","bare-os":"/node_modules/hyper-proto-peer/node_modules/bare-os/index.js"},"/node_modules/hyper-proto-peer/node_modules/bare-path/package.json":{},"/node_modules/hyper-proto-peer/node_modules/bare-pipe/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-pipe/package.json",".":"linked:libbare-pipe.4.2.2.so"},"/node_modules/hyper-proto-peer/node_modules/bare-pipe/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-pipe/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/bare-pipe/binding.js","./lib/constants":"/node_modules/hyper-proto-peer/node_modules/bare-pipe/lib/constants.js","./lib/errors":"/node_modules/hyper-proto-peer/node_modules/bare-pipe/lib/errors.js","bare-events":"/node_modules/hyper-proto-peer/node_modules/bare-events/index.js","bare-stream":"/node_modules/hyper-proto-peer/node_modules/bare-stream/index.js"},"/node_modules/hyper-proto-peer/node_modules/bare-pipe/lib/constants.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-pipe/package.json","../binding":"/node_modules/hyper-proto-peer/node_modules/bare-pipe/binding.js"},"/node_modules/hyper-proto-peer/node_modules/bare-pipe/lib/errors.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-pipe/package.json"},"/node_modules/hyper-proto-peer/node_modules/bare-pipe/package.json":{},"/node_modules/hyper-proto-peer/node_modules/bare-posix/package.json":{},"/node_modules/hyper-proto-peer/node_modules/bare-posix/unsupported.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-posix/package.json"},"/node_modules/hyper-proto-peer/node_modules/bare-process/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-process/package.json","bare-abort":"/node_modules/hyper-proto-peer/node_modules/bare-abort/index.js","bare-env":"/node_modules/hyper-proto-peer/node_modules/bare-env/index.js","bare-events":"/node_modules/hyper-proto-peer/node_modules/bare-events/index.js","bare-hrtime":"/node_modules/hyper-proto-peer/node_modules/bare-hrtime/index.js","bare-os":"/node_modules/hyper-proto-peer/node_modules/bare-os/index.js","bare-posix":"/node_modules/hyper-proto-peer/node_modules/bare-posix/unsupported.js","bare-signals":"/node_modules/hyper-proto-peer/node_modules/bare-signals/index.js","bare-stdio":"/node_modules/hyper-proto-peer/node_modules/bare-stdio/index.js"},"/node_modules/hyper-proto-peer/node_modules/bare-process/package.json":{},"/node_modules/hyper-proto-peer/node_modules/bare-signals/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-signals/package.json",".":"linked:libbare-signals.4.2.0.so"},"/node_modules/hyper-proto-peer/node_modules/bare-signals/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-signals/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/bare-signals/binding.js","./lib/emitter":"/node_modules/hyper-proto-peer/node_modules/bare-signals/lib/emitter.js","./lib/errors":"/node_modules/hyper-proto-peer/node_modules/bare-signals/lib/errors.js","bare-events":"/node_modules/hyper-proto-peer/node_modules/bare-events/index.js","bare-os":"/node_modules/hyper-proto-peer/node_modules/bare-os/index.js"},"/node_modules/hyper-proto-peer/node_modules/bare-signals/lib/emitter.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-signals/package.json","..":"/node_modules/hyper-proto-peer/node_modules/bare-signals/index.js","bare-events":"/node_modules/hyper-proto-peer/node_modules/bare-events/index.js"},"/node_modules/hyper-proto-peer/node_modules/bare-signals/lib/errors.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-signals/package.json"},"/node_modules/hyper-proto-peer/node_modules/bare-signals/package.json":{},"/node_modules/hyper-proto-peer/node_modules/bare-stdio/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-stdio/package.json",".":"linked:libbare-stdio.1.0.2.so"},"/node_modules/hyper-proto-peer/node_modules/bare-stdio/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-stdio/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/bare-stdio/binding.js","bare-fs":"/node_modules/hyper-proto-peer/node_modules/bare-fs/index.js","bare-pipe":"/node_modules/hyper-proto-peer/node_modules/bare-pipe/index.js","bare-tty":"/node_modules/hyper-proto-peer/node_modules/bare-tty/index.js"},"/node_modules/hyper-proto-peer/node_modules/bare-stdio/package.json":{},"/node_modules/hyper-proto-peer/node_modules/bare-stream/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-stream/package.json","./web":"/node_modules/hyper-proto-peer/node_modules/bare-stream/web.js","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js","streamx":"/node_modules/hyper-proto-peer/node_modules/streamx/index.js"},"/node_modules/hyper-proto-peer/node_modules/bare-stream/package.json":{},"/node_modules/hyper-proto-peer/node_modules/bare-stream/web.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-stream/package.json","streamx":"/node_modules/hyper-proto-peer/node_modules/streamx/index.js","teex":"/node_modules/hyper-proto-peer/node_modules/teex/index.js"},"/node_modules/hyper-proto-peer/node_modules/bare-tcp/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-tcp/package.json",".":"linked:libbare-tcp.2.5.1.so"},"/node_modules/hyper-proto-peer/node_modules/bare-tcp/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-tcp/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/bare-tcp/binding.js","./lib/constants":"/node_modules/hyper-proto-peer/node_modules/bare-tcp/lib/constants.js","./lib/errors":"/node_modules/hyper-proto-peer/node_modules/bare-tcp/lib/errors.js","./lib/ip":"/node_modules/hyper-proto-peer/node_modules/bare-tcp/lib/ip.js","bare-dns":"/node_modules/hyper-proto-peer/node_modules/bare-dns/index.js","bare-events":"/node_modules/hyper-proto-peer/node_modules/bare-events/index.js","bare-stream":"/node_modules/hyper-proto-peer/node_modules/bare-stream/index.js"},"/node_modules/hyper-proto-peer/node_modules/bare-tcp/lib/constants.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-tcp/package.json"},"/node_modules/hyper-proto-peer/node_modules/bare-tcp/lib/errors.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-tcp/package.json"},"/node_modules/hyper-proto-peer/node_modules/bare-tcp/lib/ip.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-tcp/package.json"},"/node_modules/hyper-proto-peer/node_modules/bare-tcp/package.json":{},"/node_modules/hyper-proto-peer/node_modules/bare-tls/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-tls/package.json",".":"linked:libbare-tls.3.1.7.so"},"/node_modules/hyper-proto-peer/node_modules/bare-tls/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-tls/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/bare-tls/binding.js","./lib/constants":"/node_modules/hyper-proto-peer/node_modules/bare-tls/lib/constants.js","./lib/errors":"/node_modules/hyper-proto-peer/node_modules/bare-tls/lib/errors.js","./net":"/node_modules/hyper-proto-peer/node_modules/bare-tls/net.js","bare-stream":"/node_modules/hyper-proto-peer/node_modules/bare-stream/index.js"},"/node_modules/hyper-proto-peer/node_modules/bare-tls/lib/constants.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-tls/package.json"},"/node_modules/hyper-proto-peer/node_modules/bare-tls/lib/errors.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-tls/package.json"},"/node_modules/hyper-proto-peer/node_modules/bare-tls/net.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-tls/package.json","bare-events":"/node_modules/hyper-proto-peer/node_modules/bare-events/index.js","bare-net":"/node_modules/hyper-proto-peer/node_modules/bare-net/index.js","bare-tls":"/node_modules/hyper-proto-peer/node_modules/bare-tls/index.js"},"/node_modules/hyper-proto-peer/node_modules/bare-tls/package.json":{},"/node_modules/hyper-proto-peer/node_modules/bare-tty/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-tty/package.json",".":"linked:libbare-tty.5.1.1.so"},"/node_modules/hyper-proto-peer/node_modules/bare-tty/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-tty/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/bare-tty/binding.js","./lib/constants":"/node_modules/hyper-proto-peer/node_modules/bare-tty/lib/constants.js","bare-signals":"/node_modules/hyper-proto-peer/node_modules/bare-signals/index.js","bare-stream":"/node_modules/hyper-proto-peer/node_modules/bare-stream/index.js"},"/node_modules/hyper-proto-peer/node_modules/bare-tty/lib/constants.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-tty/package.json","../binding":"/node_modules/hyper-proto-peer/node_modules/bare-tty/binding.js"},"/node_modules/hyper-proto-peer/node_modules/bare-tty/package.json":{},"/node_modules/hyper-proto-peer/node_modules/bare-type/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-type/package.json",".":"linked:libbare-type.1.1.0.so"},"/node_modules/hyper-proto-peer/node_modules/bare-type/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-type/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/bare-type/binding.js"},"/node_modules/hyper-proto-peer/node_modules/bare-type/package.json":{},"/node_modules/hyper-proto-peer/node_modules/bare-url/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-url/package.json",".":"linked:libbare-url.2.4.5.so"},"/node_modules/hyper-proto-peer/node_modules/bare-url/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-url/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/bare-url/binding.js","./lib/errors":"/node_modules/hyper-proto-peer/node_modules/bare-url/lib/errors.js","./lib/url-search-params":"/node_modules/hyper-proto-peer/node_modules/bare-url/lib/url-search-params.js","bare-path":"/node_modules/hyper-proto-peer/node_modules/bare-path/index.js"},"/node_modules/hyper-proto-peer/node_modules/bare-url/lib/errors.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-url/package.json"},"/node_modules/hyper-proto-peer/node_modules/bare-url/lib/url-search-params.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-url/package.json"},"/node_modules/hyper-proto-peer/node_modules/bare-url/package.json":{},"/node_modules/hyper-proto-peer/node_modules/bare-zlib/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-zlib/package.json",".":"linked:libbare-zlib.1.4.0.so"},"/node_modules/hyper-proto-peer/node_modules/bare-zlib/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-zlib/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/bare-zlib/binding.js","./lib/constants":"/node_modules/hyper-proto-peer/node_modules/bare-zlib/lib/constants.js","./lib/errors":"/node_modules/hyper-proto-peer/node_modules/bare-zlib/lib/errors.js","bare-stream":"/node_modules/hyper-proto-peer/node_modules/bare-stream/index.js"},"/node_modules/hyper-proto-peer/node_modules/bare-zlib/lib/constants.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-zlib/package.json","../binding":"/node_modules/hyper-proto-peer/node_modules/bare-zlib/binding.js"},"/node_modules/hyper-proto-peer/node_modules/bare-zlib/lib/errors.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bare-zlib/package.json"},"/node_modules/hyper-proto-peer/node_modules/bare-zlib/package.json":{},"/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/package.json","./wordlist":"/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/index.js","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js","nanoassert":"/node_modules/hyper-proto-peer/node_modules/nanoassert/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/package.json":{},"/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/chinese_simplified.json":{"#package":"/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/package.json"},"/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/chinese_traditional.json":{"#package":"/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/package.json"},"/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/czech.json":{"#package":"/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/package.json"},"/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/english.json":{"#package":"/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/package.json"},"/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/french.json":{"#package":"/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/package.json"},"/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/package.json","./chinese_simplified.json":"/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/chinese_simplified.json","./chinese_traditional.json":"/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/chinese_traditional.json","./czech.json":"/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/czech.json","./english.json":"/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/english.json","./french.json":"/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/french.json","./italian.json":"/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/italian.json","./japanese.json":"/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/japanese.json","./korean.json":"/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/korean.json","./lookup.json":"/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/lookup.json","./portuguese.json":"/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/portuguese.json","./russian.json":"/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/russian.json","./spanish.json":"/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/spanish.json","./turkish.json":"/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/turkish.json"},"/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/italian.json":{"#package":"/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/package.json"},"/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/japanese.json":{"#package":"/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/package.json"},"/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/korean.json":{"#package":"/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/package.json"},"/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/lookup.json":{"#package":"/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/package.json"},"/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/portuguese.json":{"#package":"/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/package.json"},"/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/russian.json":{"#package":"/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/package.json"},"/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/spanish.json":{"#package":"/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/package.json"},"/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/turkish.json":{"#package":"/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/package.json"},"/node_modules/hyper-proto-peer/node_modules/bits-to-bytes/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bits-to-bytes/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/bits-to-bytes/package.json":{},"/node_modules/hyper-proto-peer/node_modules/blind-relay/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/blind-relay/package.json","./lib/errors":"/node_modules/hyper-proto-peer/node_modules/blind-relay/lib/errors.js","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js","bits-to-bytes":"/node_modules/hyper-proto-peer/node_modules/bits-to-bytes/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/blind-relay/node_modules/compact-encoding/index.js","compact-encoding-bitfield":"/node_modules/hyper-proto-peer/node_modules/compact-encoding-bitfield/index.js","events":"/node_modules/hyper-proto-peer/node_modules/bare-events/index.js","protomux":"/node_modules/hyper-proto-peer/node_modules/protomux/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/sodium-universal/index.js","streamx":"/node_modules/hyper-proto-peer/node_modules/streamx/index.js"},"/node_modules/hyper-proto-peer/node_modules/blind-relay/lib/errors.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/blind-relay/package.json"},"/node_modules/hyper-proto-peer/node_modules/blind-relay/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/blind-relay/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/blind-relay/node_modules/compact-encoding/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/blind-relay/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/blind-relay/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/hyper-proto-peer/node_modules/blind-relay/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/hyper-proto-peer/node_modules/blind-relay/node_modules/compact-encoding/raw.js","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/blind-relay/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/blind-relay/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/blind-relay/node_modules/compact-encoding/package.json":{},"/node_modules/hyper-proto-peer/node_modules/blind-relay/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/blind-relay/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/blind-relay/node_modules/compact-encoding/endian.js","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/blind-relay/package.json":{},"/node_modules/hyper-proto-peer/node_modules/bogon/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bogon/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/bogon/node_modules/compact-encoding/index.js"},"/node_modules/hyper-proto-peer/node_modules/bogon/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bogon/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/bogon/node_modules/compact-encoding/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bogon/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/bogon/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/hyper-proto-peer/node_modules/bogon/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/hyper-proto-peer/node_modules/bogon/node_modules/compact-encoding/raw.js","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/bogon/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bogon/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/bogon/node_modules/compact-encoding/package.json":{},"/node_modules/hyper-proto-peer/node_modules/bogon/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/bogon/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/bogon/node_modules/compact-encoding/endian.js","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/bogon/package.json":{},"/node_modules/hyper-proto-peer/node_modules/cborg/cborg.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/cborg/package.json","./lib/decode.js":"/node_modules/hyper-proto-peer/node_modules/cborg/lib/decode.js","./lib/encode.js":"/node_modules/hyper-proto-peer/node_modules/cborg/lib/encode.js","./lib/tagged.js":"/node_modules/hyper-proto-peer/node_modules/cborg/lib/tagged.js","./lib/token.js":"/node_modules/hyper-proto-peer/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/cborg/lib/0uint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/cborg/package.json","./common.js":"/node_modules/hyper-proto-peer/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/cborg/lib/1negint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/cborg/lib/2bytes.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/cborg/lib/0uint.js","./byte-utils.js":"/node_modules/hyper-proto-peer/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/cborg/lib/3string.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/cborg/lib/0uint.js","./2bytes.js":"/node_modules/hyper-proto-peer/node_modules/cborg/lib/2bytes.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/cborg/lib/4array.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/cborg/lib/5map.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/cborg/lib/6tag.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/cborg/lib/0uint.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/cborg/lib/7float.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/cborg/lib/0uint.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/cborg/lib/bl.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/cborg/package.json","./byte-utils.js":"/node_modules/hyper-proto-peer/node_modules/cborg/lib/byte-utils.js"},"/node_modules/hyper-proto-peer/node_modules/cborg/lib/byte-utils.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/cborg/package.json"},"/node_modules/hyper-proto-peer/node_modules/cborg/lib/common.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/cborg/package.json"},"/node_modules/hyper-proto-peer/node_modules/cborg/lib/decode.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/cborg/package.json","./byte-utils.js":"/node_modules/hyper-proto-peer/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/cborg/lib/common.js","./jump.js":"/node_modules/hyper-proto-peer/node_modules/cborg/lib/jump.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/cborg/lib/encode.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/cborg/lib/0uint.js","./1negint.js":"/node_modules/hyper-proto-peer/node_modules/cborg/lib/1negint.js","./2bytes.js":"/node_modules/hyper-proto-peer/node_modules/cborg/lib/2bytes.js","./3string.js":"/node_modules/hyper-proto-peer/node_modules/cborg/lib/3string.js","./4array.js":"/node_modules/hyper-proto-peer/node_modules/cborg/lib/4array.js","./5map.js":"/node_modules/hyper-proto-peer/node_modules/cborg/lib/5map.js","./6tag.js":"/node_modules/hyper-proto-peer/node_modules/cborg/lib/6tag.js","./7float.js":"/node_modules/hyper-proto-peer/node_modules/cborg/lib/7float.js","./bl.js":"/node_modules/hyper-proto-peer/node_modules/cborg/lib/bl.js","./byte-utils.js":"/node_modules/hyper-proto-peer/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/cborg/lib/common.js","./is.js":"/node_modules/hyper-proto-peer/node_modules/cborg/lib/is.js","./jump.js":"/node_modules/hyper-proto-peer/node_modules/cborg/lib/jump.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/cborg/lib/is.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/cborg/package.json"},"/node_modules/hyper-proto-peer/node_modules/cborg/lib/jump.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/cborg/package.json","./0uint.js":"/node_modules/hyper-proto-peer/node_modules/cborg/lib/0uint.js","./1negint.js":"/node_modules/hyper-proto-peer/node_modules/cborg/lib/1negint.js","./2bytes.js":"/node_modules/hyper-proto-peer/node_modules/cborg/lib/2bytes.js","./3string.js":"/node_modules/hyper-proto-peer/node_modules/cborg/lib/3string.js","./4array.js":"/node_modules/hyper-proto-peer/node_modules/cborg/lib/4array.js","./5map.js":"/node_modules/hyper-proto-peer/node_modules/cborg/lib/5map.js","./6tag.js":"/node_modules/hyper-proto-peer/node_modules/cborg/lib/6tag.js","./7float.js":"/node_modules/hyper-proto-peer/node_modules/cborg/lib/7float.js","./byte-utils.js":"/node_modules/hyper-proto-peer/node_modules/cborg/lib/byte-utils.js","./common.js":"/node_modules/hyper-proto-peer/node_modules/cborg/lib/common.js","./token.js":"/node_modules/hyper-proto-peer/node_modules/cborg/lib/token.js"},"/node_modules/hyper-proto-peer/node_modules/cborg/lib/tagged.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/cborg/package.json"},"/node_modules/hyper-proto-peer/node_modules/cborg/lib/token.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/cborg/package.json"},"/node_modules/hyper-proto-peer/node_modules/cborg/package.json":{},"/node_modules/hyper-proto-peer/node_modules/compact-encoding-bitfield/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/compact-encoding-bitfield/package.json","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/index.js"},"/node_modules/hyper-proto-peer/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/hyper-proto-peer/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/hyper-proto-peer/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/raw.js","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/package.json":{},"/node_modules/hyper-proto-peer/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/endian.js","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/compact-encoding-bitfield/package.json":{},"/node_modules/hyper-proto-peer/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/compact-encoding/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/hyper-proto-peer/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/hyper-proto-peer/node_modules/compact-encoding/raw.js","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/compact-encoding/package.json":{},"/node_modules/hyper-proto-peer/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/compact-encoding/endian.js","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/dht-rpc/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/dht-rpc/package.json","./lib/commands":"/node_modules/hyper-proto-peer/node_modules/dht-rpc/lib/commands.js","./lib/errors":"/node_modules/hyper-proto-peer/node_modules/dht-rpc/lib/errors.js","./lib/health":"/node_modules/hyper-proto-peer/node_modules/dht-rpc/lib/health.js","./lib/io":"/node_modules/hyper-proto-peer/node_modules/dht-rpc/lib/io.js","./lib/peer":"/node_modules/hyper-proto-peer/node_modules/dht-rpc/lib/peer.js","./lib/query":"/node_modules/hyper-proto-peer/node_modules/dht-rpc/lib/query.js","./lib/session":"/node_modules/hyper-proto-peer/node_modules/dht-rpc/lib/session.js","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/dht-rpc/node_modules/compact-encoding/index.js","events":"/node_modules/hyper-proto-peer/node_modules/bare-events/index.js","kademlia-routing-table":"/node_modules/hyper-proto-peer/node_modules/kademlia-routing-table/index.js","nat-sampler":"/node_modules/hyper-proto-peer/node_modules/nat-sampler/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/sodium-universal/index.js","time-ordered-set":"/node_modules/hyper-proto-peer/node_modules/time-ordered-set/index.js","udx-native":"/node_modules/hyper-proto-peer/node_modules/udx-native/lib/udx.js"},"/node_modules/hyper-proto-peer/node_modules/dht-rpc/lib/commands.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/dht-rpc/package.json"},"/node_modules/hyper-proto-peer/node_modules/dht-rpc/lib/errors.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/dht-rpc/package.json"},"/node_modules/hyper-proto-peer/node_modules/dht-rpc/lib/health.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/dht-rpc/package.json"},"/node_modules/hyper-proto-peer/node_modules/dht-rpc/lib/io.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/dht-rpc/package.json","./errors":"/node_modules/hyper-proto-peer/node_modules/dht-rpc/lib/errors.js","./peer":"/node_modules/hyper-proto-peer/node_modules/dht-rpc/lib/peer.js","adaptive-timeout":"/node_modules/hyper-proto-peer/node_modules/adaptive-timeout/index.js","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/dht-rpc/node_modules/compact-encoding/index.js","fast-fifo":"/node_modules/hyper-proto-peer/node_modules/fast-fifo/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/dht-rpc/lib/peer.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/dht-rpc/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/dht-rpc/node_modules/compact-encoding/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/dht-rpc/lib/query.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/dht-rpc/package.json","./commands":"/node_modules/hyper-proto-peer/node_modules/dht-rpc/lib/commands.js","./peer":"/node_modules/hyper-proto-peer/node_modules/dht-rpc/lib/peer.js","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js","streamx":"/node_modules/hyper-proto-peer/node_modules/streamx/index.js"},"/node_modules/hyper-proto-peer/node_modules/dht-rpc/lib/session.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/dht-rpc/package.json"},"/node_modules/hyper-proto-peer/node_modules/dht-rpc/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/dht-rpc/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/dht-rpc/node_modules/compact-encoding/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/dht-rpc/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/dht-rpc/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/hyper-proto-peer/node_modules/dht-rpc/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/hyper-proto-peer/node_modules/dht-rpc/node_modules/compact-encoding/raw.js","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/dht-rpc/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/dht-rpc/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/dht-rpc/node_modules/compact-encoding/package.json":{},"/node_modules/hyper-proto-peer/node_modules/dht-rpc/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/dht-rpc/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/dht-rpc/node_modules/compact-encoding/endian.js","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/dht-rpc/package.json":{},"/node_modules/hyper-proto-peer/node_modules/events-universal/bare.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/events-universal/package.json","bare-events":"/node_modules/hyper-proto-peer/node_modules/bare-events/index.js"},"/node_modules/hyper-proto-peer/node_modules/events-universal/package.json":{},"/node_modules/hyper-proto-peer/node_modules/fast-fifo/fixed-size.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/fast-fifo/package.json"},"/node_modules/hyper-proto-peer/node_modules/fast-fifo/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/fast-fifo/package.json","./fixed-size":"/node_modules/hyper-proto-peer/node_modules/fast-fifo/fixed-size.js"},"/node_modules/hyper-proto-peer/node_modules/fast-fifo/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/package.json","./lib/chunk-scheduler.js":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/lib/chunk-scheduler.js","./lib/chunker.js":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/lib/chunker.js","./lib/file-index.js":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/lib/file-index.js","./lib/ignore.js":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/lib/ignore.js","./lib/manifest.js":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/lib/manifest.js","./lib/messages.js":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/lib/messages.js","./lib/overlay.js":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/lib/overlay.js","./lib/pointer.js":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/lib/pointer.js","./lib/protocol.js":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/lib/protocol.js","./lib/sync-engine.js":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/lib/sync-engine.js","./lib/transfer.js":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/lib/transfer.js","./lib/tree.js":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/lib/tree.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/lib/chunk-scheduler.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/package.json","./chunker.js":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/lib/chunker.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/lib/chunker.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/package.json","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/compact-encoding/index.js","hypercore-crypto":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/hypercore-crypto/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/lib/file-index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/package.json","hyperbee":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/hyperbee/index.js","ready-resource":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/ready-resource/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/lib/ignore.js":{"#fs":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-fs/index.js","#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/package.json","#path":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-path/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/lib/manifest.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/package.json","#zlib":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-zlib/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/lib/messages.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/package.json","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/compact-encoding/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/lib/overlay.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/package.json","./chunker.js":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/lib/chunker.js","./file-index.js":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/lib/file-index.js","./protocol.js":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/lib/protocol.js","./sync-engine.js":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/lib/sync-engine.js","./transfer.js":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/lib/transfer.js","bare-fs":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-fs/index.js","bare-os":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-os/index.js","bare-path":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-path/index.js","hypercore-crypto":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/hypercore-crypto/index.js","ready-resource":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/ready-resource/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/lib/pointer.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/lib/protocol.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/package.json","./chunk-scheduler.js":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/lib/chunk-scheduler.js","./chunker.js":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/lib/chunker.js","./messages.js":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/lib/messages.js","bare-fs":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-fs/index.js","bare-path":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-path/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/lib/sync-engine.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/package.json","ready-resource":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/ready-resource/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/lib/transfer.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/package.json","./chunker.js":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/lib/chunker.js","bare-fs":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-fs/index.js","bare-os":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-os/index.js","bare-path":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-path/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/compact-encoding/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/lib/tree.js":{"#fs":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-fs/index.js","#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/package.json","#path":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-path/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/compact-encoding/index.js","hypercore-crypto":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/hypercore-crypto/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/b4a/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/b4a/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/b4a/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-ansi-escapes/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-ansi-escapes/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-ansi-escapes/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-assert/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-assert/package.json","bare-inspect":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-inspect/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-assert/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-events/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-events/package.json","./lib/errors":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-events/lib/errors.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-events/lib/errors.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-events/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-events/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-fs/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-fs/package.json",".":"linked:libbare-fs.4.7.2.so"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-fs/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-fs/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-fs/binding.js","./lib/constants":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-fs/lib/constants.js","./lib/errors":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-fs/lib/errors.js","./promises":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-fs/promises.js","bare-events":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-events/index.js","bare-path":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-path/index.js","bare-stream":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-stream/index.js","bare-url":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-url/index.js","fast-fifo":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/fast-fifo/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-fs/lib/constants.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-fs/package.json","../binding":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-fs/binding.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-fs/lib/errors.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-fs/package.json","bare-os":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-os/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-fs/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-fs/promises.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-fs/package.json",".":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-fs/index.js","bare-events":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-events/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-inspect/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-inspect/package.json",".":"linked:libbare-inspect.3.1.4.so"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-inspect/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-inspect/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-inspect/binding.js","bare-ansi-escapes":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-ansi-escapes/index.js","bare-type":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-type/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-inspect/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-os/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-os/package.json",".":"linked:libbare-os.3.9.1.so"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-os/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-os/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-os/binding.js","./lib/constants":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-os/lib/constants.js","./lib/errors":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-os/lib/errors.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-os/lib/constants.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-os/package.json","../binding":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-os/binding.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-os/lib/errors.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-os/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-os/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-path/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-path/package.json","./lib/posix":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-path/lib/posix.js","./lib/win32":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-path/lib/win32.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-path/lib/constants.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-path/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-path/lib/posix.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-path/package.json","./constants":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-path/lib/constants.js","./shared":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-path/lib/shared.js","./win32":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-path/lib/win32.js","bare-os":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-os/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-path/lib/shared.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-path/package.json","./constants":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-path/lib/constants.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-path/lib/win32.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-path/package.json","./constants":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-path/lib/constants.js","./posix":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-path/lib/posix.js","./shared":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-path/lib/shared.js","bare-os":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-os/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-path/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-stream/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-stream/package.json","./web":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-stream/web.js","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/b4a/index.js","streamx":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/streamx/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-stream/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-stream/web.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-stream/package.json","streamx":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/streamx/index.js","teex":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/teex/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-type/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-type/package.json",".":"linked:libbare-type.1.1.0.so"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-type/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-type/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-type/binding.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-type/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-url/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-url/package.json",".":"linked:libbare-url.2.4.5.so"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-url/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-url/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-url/binding.js","./lib/errors":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-url/lib/errors.js","./lib/url-search-params":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-url/lib/url-search-params.js","bare-path":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-path/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-url/lib/errors.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-url/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-url/lib/url-search-params.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-url/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-url/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-zlib/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-zlib/package.json",".":"linked:libbare-zlib.1.4.0.so"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-zlib/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-zlib/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-zlib/binding.js","./lib/constants":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-zlib/lib/constants.js","./lib/errors":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-zlib/lib/errors.js","bare-stream":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-stream/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-zlib/lib/constants.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-zlib/package.json","../binding":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-zlib/binding.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-zlib/lib/errors.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-zlib/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-zlib/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/codecs/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/codecs/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/codecs/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/compact-encoding/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/compact-encoding/raw.js","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/compact-encoding/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/compact-encoding/endian.js","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/debounceify/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/debounceify/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/debounceify/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/events-universal/bare.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/events-universal/package.json","bare-events":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-events/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/events-universal/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/fast-fifo/fixed-size.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/fast-fifo/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/fast-fifo/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/fast-fifo/package.json","./fixed-size":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/fast-fifo/fixed-size.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/fast-fifo/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/hyperbee/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/hyperbee/package.json","./iterators/diff":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/hyperbee/iterators/diff.js","./iterators/history":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/hyperbee/iterators/history.js","./iterators/local":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/hyperbee/iterators/local.js","./iterators/range":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/hyperbee/iterators/range.js","./lib/extension":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/hyperbee/lib/extension.js","./lib/messages":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/hyperbee/lib/messages.js","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/b4a/index.js","codecs":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/codecs/index.js","debounceify":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/debounceify/index.js","hypercore-errors":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/hypercore-errors/index.js","mutexify/promise":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/mutexify/promise.js","rache":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/rache/index.js","ready-resource":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/ready-resource/index.js","resolve-reject-promise":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/resolve-reject-promise/index.js","safety-catch":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/safety-catch/index.js","streamx":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/streamx/index.js","unslab":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/unslab/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/hyperbee/iterators/diff.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/hyperbee/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/hyperbee/iterators/history.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/hyperbee/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/hyperbee/iterators/local.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/hyperbee/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/hyperbee/iterators/range.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/hyperbee/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/hyperbee/lib/extension.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/hyperbee/package.json","./messages":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/hyperbee/lib/messages.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/hyperbee/lib/messages.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/hyperbee/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/b4a/index.js","protocol-buffers-encodings":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/protocol-buffers-encodings/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/hyperbee/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/hypercore-crypto/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/hypercore-crypto/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/compact-encoding/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/hypercore-crypto/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/hypercore-errors/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/hypercore-errors/package.json","hypercore-id-encoding":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/hypercore-id-encoding/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/hypercore-errors/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/hypercore-id-encoding/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/hypercore-id-encoding/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/b4a/index.js","z32":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/z32/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/hypercore-id-encoding/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/mutexify/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/mutexify/package.json","queue-tick":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/queue-tick/process-next-tick.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/mutexify/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/mutexify/promise.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/mutexify/package.json",".":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/mutexify/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/protocol-buffers-encodings/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/protocol-buffers-encodings/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/b4a/index.js","signed-varint":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/signed-varint/index.js","varint":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/varint/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/protocol-buffers-encodings/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/queue-tick/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/queue-tick/process-next-tick.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/queue-tick/package.json","./queue-microtask":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/queue-tick/queue-microtask.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/queue-tick/queue-microtask.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/queue-tick/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/rache/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/rache/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/rache/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/ready-resource/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/ready-resource/package.json","events":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-events/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/ready-resource/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/require-addon/lib/bare.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/require-addon/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/require-addon/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/resolve-reject-promise/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/resolve-reject-promise/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/resolve-reject-promise/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/safety-catch/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/safety-catch/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/safety-catch/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/signed-varint/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/signed-varint/package.json","varint":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/varint/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/signed-varint/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/sodium-native/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/sodium-native/package.json",".":"linked:libsodium-native.5.1.0.so","require-addon":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/require-addon/lib/bare.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/sodium-native/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/sodium-native/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/sodium-native/binding.js","assert":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-assert/index.js","which-runtime":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/which-runtime/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/sodium-native/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/sodium-universal/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/sodium-universal/package.json","sodium-native":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/sodium-native/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/sodium-universal/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/streamx/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/streamx/package.json","./lib/errors.js":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/streamx/lib/errors.js","events-universal":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/events-universal/bare.js","fast-fifo":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/fast-fifo/index.js","text-decoder":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/text-decoder/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/streamx/lib/errors.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/streamx/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/streamx/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/teex/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/teex/package.json","streamx":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/streamx/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/teex/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/text-decoder/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/text-decoder/package.json","./lib/pass-through-decoder":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/text-decoder/lib/pass-through-decoder.js","./lib/utf8-decoder":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/text-decoder/lib/utf8-decoder.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/text-decoder/lib/pass-through-decoder.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/text-decoder/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/text-decoder/lib/utf8-decoder.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/text-decoder/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/text-decoder/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/unslab/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/unslab/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/unslab/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/varint/decode.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/varint/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/varint/encode.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/varint/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/varint/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/varint/package.json","./decode.js":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/varint/decode.js","./encode.js":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/varint/encode.js","./length.js":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/varint/length.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/varint/length.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/varint/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/varint/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/which-runtime/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/which-runtime/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/which-runtime/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/z32/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/z32/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/z32/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/package.json","./lib/client.js":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/lib/client.js","./lib/frame.js":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/lib/frame.js","./lib/service.js":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/lib/service.js","./lib/transports/swarm-rpc.js":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/lib/transports/swarm-rpc.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/lib/client.js":{"#node:fs/promises":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-fs/promises.js","#node:http":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http1/index.js","#node:url":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-url/index.js","#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/package.json","./frame.js":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/lib/frame.js","./transports/swarm-rpc.js":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/lib/transports/swarm-rpc.js","./uds-backend.js":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/lib/uds-backend.js","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js","hypercore-crypto":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hypercore-crypto/index.js","hyperswarm":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperswarm/index.js","protomux":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/protomux/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/lib/frame.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/lib/service.js":{"#node:process":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-process/index.js","#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/package.json","./transports/http.js":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/lib/transports/http.js","./transports/swarm.js":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/lib/transports/swarm.js","./transports/uds.js":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/lib/transports/uds.js","ready-resource":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/ready-resource/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/lib/transports/http.js":{"#node:http":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http1/index.js","#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/lib/transports/swarm-rpc.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding/index.js","protomux":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/protomux/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/lib/transports/swarm.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/package.json","./swarm-rpc.js":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/lib/transports/swarm-rpc.js","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js","hyperswarm":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperswarm/index.js","protomux":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/protomux/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/lib/transports/uds.js":{"#node:fs/promises":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-fs/promises.js","#node:process":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-process/index.js","#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/package.json","../frame.js":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/lib/frame.js","../uds-backend.js":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/lib/uds-backend.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/lib/uds-backend.js":{"#node:net":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-net/index.js","#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/package.json","bare-abstract-socket":"deferred:bare-abstract-socket"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/package.json","./lib/bridge":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/lib/bridge.js","./lib/handshake":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/lib/handshake.js","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js","hypercore-crypto":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hypercore-crypto/index.js","sodium-secretstream":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/sodium-secretstream/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/sodium-universal/index.js","streamx":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/streamx/index.js","timeout-refresh":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/timeout-refresh/index.js","unslab":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/unslab/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/lib/bridge.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/package.json","streamx":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/streamx/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/lib/handshake.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js","noise-curve-ed":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/noise-curve-ed/index.js","noise-handshake":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/noise-handshake/noise.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/adaptive-timeout/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/adaptive-timeout/package.json","xache":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/xache/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/adaptive-timeout/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-abort/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-abort/package.json",".":"linked:libbare-abort.2.0.13.so"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-abort/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-abort/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-abort/binding.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-abort/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-ansi-escapes/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-ansi-escapes/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-ansi-escapes/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-assert/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-assert/package.json","bare-inspect":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-inspect/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-assert/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-dns/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-dns/package.json",".":"linked:libbare-dns.2.1.4.so"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-dns/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-dns/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-dns/binding.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-dns/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-env/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-env/package.json","bare-os":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-os/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-env/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-events/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-events/package.json","./lib/errors":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-events/lib/errors.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-events/lib/errors.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-events/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-events/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-fs/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-fs/package.json",".":"linked:libbare-fs.4.7.2.so"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-fs/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-fs/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-fs/binding.js","./lib/constants":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-fs/lib/constants.js","./lib/errors":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-fs/lib/errors.js","./promises":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-fs/promises.js","bare-events":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-events/index.js","bare-path":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-path/index.js","bare-stream":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-stream/index.js","bare-url":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-url/index.js","fast-fifo":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/fast-fifo/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-fs/lib/constants.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-fs/package.json","../binding":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-fs/binding.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-fs/lib/errors.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-fs/package.json","bare-os":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-os/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-fs/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-fs/promises.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-fs/package.json",".":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-fs/index.js","bare-events":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-events/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-hrtime/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-hrtime/package.json",".":"linked:libbare-hrtime.2.1.1.so"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-hrtime/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-hrtime/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-hrtime/binding.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-hrtime/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http-parser/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http-parser/package.json","./lib/errors":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http-parser/lib/errors.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http-parser/lib/errors.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http-parser/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http-parser/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http1/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http1/package.json","./lib/agent":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http1/lib/agent.js","./lib/client-connection":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http1/lib/client-connection.js","./lib/client-request":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http1/lib/client-request.js","./lib/constants":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http1/lib/constants.js","./lib/errors":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http1/lib/errors.js","./lib/incoming-message":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http1/lib/incoming-message.js","./lib/outgoing-message":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http1/lib/outgoing-message.js","./lib/server":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http1/lib/server.js","./lib/server-connection":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http1/lib/server-connection.js","./lib/server-response":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http1/lib/server-response.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http1/lib/agent.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http1/package.json","./client-connection":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http1/lib/client-connection.js","./errors":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http1/lib/errors.js","bare-events":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-events/index.js","bare-tcp":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-tcp/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http1/lib/client-connection.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http1/package.json","./errors":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http1/lib/errors.js","./incoming-message":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http1/lib/incoming-message.js","bare-http-parser":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http-parser/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http1/lib/client-request.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http1/package.json","./agent":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http1/lib/agent.js","./outgoing-message":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http1/lib/outgoing-message.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http1/lib/constants.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http1/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http1/lib/errors.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http1/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http1/lib/incoming-message.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http1/package.json","bare-stream":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-stream/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http1/lib/outgoing-message.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http1/package.json","./errors":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http1/lib/errors.js","bare-stream":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-stream/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http1/lib/server-connection.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http1/package.json","./incoming-message":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http1/lib/incoming-message.js","./server-response":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http1/lib/server-response.js","bare-http-parser":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http-parser/index.js","bare-stream":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-stream/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http1/lib/server-response.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http1/package.json","./constants":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http1/lib/constants.js","./outgoing-message":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http1/lib/outgoing-message.js","bare-stream":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-stream/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http1/lib/server.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http1/package.json","./server-connection":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http1/lib/server-connection.js","bare-tcp":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-tcp/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http1/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-inspect/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-inspect/package.json",".":"linked:libbare-inspect.3.1.4.so"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-inspect/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-inspect/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-inspect/binding.js","bare-ansi-escapes":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-ansi-escapes/index.js","bare-type":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-type/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-inspect/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-net/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-net/package.json","bare-events":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-events/index.js","bare-pipe":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/index.js","bare-stream":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-stream/index.js","bare-tcp":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-dns/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-dns/package.json",".":"linked:libbare-dns.1.0.5.so"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-dns/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-dns/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-dns/binding.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-dns/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/package.json",".":"linked:libbare-pipe.3.3.8.so"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/binding.js","./lib/constants":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/lib/constants.js","./lib/errors":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/lib/errors.js","bare-events":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-events/index.js","bare-stream":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-stream/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/lib/constants.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/lib/errors.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/package.json",".":"linked:libbare-tcp.1.9.1.so"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/binding.js","./lib/constants":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/lib/constants.js","./lib/errors":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/lib/errors.js","./lib/ip":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/lib/ip.js","bare-dns":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-dns/index.js","bare-events":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-events/index.js","bare-stream":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-stream/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/lib/constants.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/lib/errors.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/lib/ip.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-net/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-os/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-os/package.json",".":"linked:libbare-os.3.9.1.so"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-os/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-os/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-os/binding.js","./lib/constants":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-os/lib/constants.js","./lib/errors":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-os/lib/errors.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-os/lib/constants.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-os/package.json","../binding":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-os/binding.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-os/lib/errors.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-os/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-os/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-path/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-path/package.json","./lib/posix":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-path/lib/posix.js","./lib/win32":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-path/lib/win32.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-path/lib/constants.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-path/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-path/lib/posix.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-path/package.json","./constants":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-path/lib/constants.js","./shared":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-path/lib/shared.js","./win32":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-path/lib/win32.js","bare-os":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-os/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-path/lib/shared.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-path/package.json","./constants":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-path/lib/constants.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-path/lib/win32.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-path/package.json","./constants":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-path/lib/constants.js","./posix":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-path/lib/posix.js","./shared":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-path/lib/shared.js","bare-os":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-os/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-path/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-pipe/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-pipe/package.json",".":"linked:libbare-pipe.4.1.5.so"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-pipe/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-pipe/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-pipe/binding.js","./lib/constants":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-pipe/lib/constants.js","./lib/errors":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-pipe/lib/errors.js","bare-events":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-events/index.js","bare-stream":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-stream/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-pipe/lib/constants.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-pipe/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-pipe/lib/errors.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-pipe/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-pipe/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-process/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-process/package.json","bare-abort":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-abort/index.js","bare-env":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-env/index.js","bare-events":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-events/index.js","bare-hrtime":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-hrtime/index.js","bare-os":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-os/index.js","bare-signals":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-signals/index.js","bare-stdio":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-stdio/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-process/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-signals/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-signals/package.json",".":"linked:libbare-signals.4.2.0.so"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-signals/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-signals/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-signals/binding.js","./lib/emitter":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-signals/lib/emitter.js","./lib/errors":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-signals/lib/errors.js","bare-events":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-events/index.js","bare-os":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-os/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-signals/lib/emitter.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-signals/package.json","..":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-signals/index.js","bare-events":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-events/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-signals/lib/errors.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-signals/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-signals/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-stdio/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-stdio/package.json",".":"linked:libbare-stdio.1.0.2.so"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-stdio/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-stdio/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-stdio/binding.js","bare-fs":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-fs/index.js","bare-pipe":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-pipe/index.js","bare-tty":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-tty/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-stdio/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-stream/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-stream/package.json","./web":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-stream/web.js","streamx":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/streamx/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-stream/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-stream/web.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-stream/package.json","streamx":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/streamx/index.js","teex":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/teex/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-tcp/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-tcp/package.json",".":"linked:libbare-tcp.2.2.12.so"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-tcp/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-tcp/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-tcp/binding.js","./lib/constants":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-tcp/lib/constants.js","./lib/errors":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-tcp/lib/errors.js","./lib/ip":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-tcp/lib/ip.js","bare-dns":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-dns/index.js","bare-events":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-events/index.js","bare-stream":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-stream/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-tcp/lib/constants.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-tcp/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-tcp/lib/errors.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-tcp/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-tcp/lib/ip.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-tcp/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-tcp/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-tty/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-tty/package.json",".":"linked:libbare-tty.5.1.0.so"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-tty/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-tty/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-tty/binding.js","./lib/constants":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-tty/lib/constants.js","bare-signals":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-signals/index.js","bare-stream":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-stream/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-tty/lib/constants.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-tty/package.json","../binding":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-tty/binding.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-tty/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-type/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-type/package.json",".":"linked:libbare-type.1.1.0.so"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-type/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-type/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-type/binding.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-type/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-url/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-url/package.json",".":"linked:libbare-url.2.4.2.so"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-url/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-url/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-url/binding.js","./lib/errors":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-url/lib/errors.js","./lib/url-search-params":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-url/lib/url-search-params.js","bare-path":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-path/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-url/lib/errors.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-url/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-url/lib/url-search-params.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-url/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-url/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bits-to-bytes/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bits-to-bytes/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bits-to-bytes/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/blind-relay/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/blind-relay/package.json","./lib/errors":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/blind-relay/lib/errors.js","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js","bits-to-bytes":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bits-to-bytes/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/index.js","compact-encoding-bitfield":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/index.js","events":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-events/index.js","protomux":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/protomux/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/sodium-universal/index.js","streamx":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/streamx/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/blind-relay/lib/errors.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/blind-relay/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/raw.js","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/endian.js","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/blind-relay/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bogon/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bogon/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/index.js","compact-encoding-net":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding-net/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/raw.js","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/endian.js","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bogon/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/package.json","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/raw.js","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/endian.js","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding-net/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding-net/package.json","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/raw.js","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/endian.js","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding-net/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding/raw.js","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding/endian.js","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/dht-rpc/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/dht-rpc/package.json","./lib/commands":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/dht-rpc/lib/commands.js","./lib/errors":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/dht-rpc/lib/errors.js","./lib/health":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/dht-rpc/lib/health.js","./lib/io":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/dht-rpc/lib/io.js","./lib/peer":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/dht-rpc/lib/peer.js","./lib/query":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/dht-rpc/lib/query.js","./lib/session":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/dht-rpc/lib/session.js","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/index.js","events":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-events/index.js","kademlia-routing-table":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/kademlia-routing-table/index.js","nat-sampler":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/nat-sampler/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/sodium-universal/index.js","time-ordered-set":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/time-ordered-set/index.js","udx-native":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/udx-native/lib/udx.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/dht-rpc/lib/commands.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/dht-rpc/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/dht-rpc/lib/errors.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/dht-rpc/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/dht-rpc/lib/health.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/dht-rpc/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/dht-rpc/lib/io.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/dht-rpc/package.json","./errors":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/dht-rpc/lib/errors.js","./peer":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/dht-rpc/lib/peer.js","adaptive-timeout":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/adaptive-timeout/index.js","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/index.js","fast-fifo":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/fast-fifo/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/dht-rpc/lib/peer.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/dht-rpc/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/index.js","compact-encoding-net":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding-net/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/dht-rpc/lib/query.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/dht-rpc/package.json","./commands":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/dht-rpc/lib/commands.js","./peer":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/dht-rpc/lib/peer.js","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js","streamx":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/streamx/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/dht-rpc/lib/session.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/dht-rpc/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/raw.js","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/endian.js","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/dht-rpc/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/events-universal/bare.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/events-universal/package.json","bare-events":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-events/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/events-universal/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/fast-fifo/fixed-size.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/fast-fifo/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/fast-fifo/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/fast-fifo/package.json","./fixed-size":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/fast-fifo/fixed-size.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/fast-fifo/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hypercore-crypto/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hypercore-crypto/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/raw.js","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/endian.js","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hypercore-crypto/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hypercore-id-encoding/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hypercore-id-encoding/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js","z32":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/z32/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hypercore-id-encoding/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht-address/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht-address/package.json","./spec/hyperschema":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht-address/spec/hyperschema/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/raw.js","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/endian.js","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht-address/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht-address/spec/hyperschema/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht-address/package.json","hyperschema/runtime":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperschema/runtime.cjs"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/package.json","./lib/connect":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/connect.js","./lib/connection-pool":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/connection-pool.js","./lib/constants":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/constants.js","./lib/crypto":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/crypto.js","./lib/errors":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/errors.js","./lib/messages":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/messages.js","./lib/persistent":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/persistent.js","./lib/raw-stream-set":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/raw-stream-set.js","./lib/router":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/router.js","./lib/server":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/server.js","./lib/socket-pool":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/socket-pool.js","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/index.js","dht-rpc":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/dht-rpc/index.js","safety-catch":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/safety-catch/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/sodium-universal/index.js","xache":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/xache/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/announcer.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/package.json","./constants":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/constants.js","./encode":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/encode.js","./messages":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/messages.js","./persistent":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/persistent.js","./sleeper":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/sleeper.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/index.js","safety-catch":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/safety-catch/index.js","signal-promise":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/signal-promise/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/connect.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/package.json","./constants":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/constants.js","./crypto":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/crypto.js","./errors":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/errors.js","./holepuncher":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/holepuncher.js","./noise-wrap":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/noise-wrap.js","./secure-payload":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/secure-payload.js","./semaphore":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/semaphore.js","./sleeper":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/sleeper.js","@hyperswarm/secret-stream":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/index.js","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js","blind-relay":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/blind-relay/index.js","bogon":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bogon/index.js","hypercore-id-encoding":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hypercore-id-encoding/index.js","hyperdht-address":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht-address/index.js","safety-catch":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/safety-catch/index.js","unslab":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/unslab/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/connection-pool.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/package.json","./errors":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/errors.js","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js","events":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-events/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/constants.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/package.json","hypercore-crypto":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hypercore-crypto/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/crypto.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/encode.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/errors.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/holepuncher.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/package.json","./constants":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/constants.js","./nat":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/nat.js","./sleeper":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/sleeper.js","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/messages.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/package.json","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/nat.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/package.json","../lib/constants":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/constants.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/noise-wrap.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/package.json","./constants":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/constants.js","./errors":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/errors.js","./messages":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/messages.js","@hyperswarm/secret-stream":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/index.js","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/index.js","noise-curve-ed":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/noise-curve-ed/index.js","noise-handshake":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/noise-handshake/noise.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/persistent.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/package.json","./constants":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/constants.js","./encode":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/encode.js","./messages":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/messages.js","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/index.js","record-cache":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/record-cache/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/sodium-universal/index.js","unslab":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/unslab/index.js","xache":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/xache/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/raw-stream-set.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/router.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/package.json","./constants":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/constants.js","./errors":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/errors.js","./messages":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/messages.js","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/index.js","safety-catch":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/safety-catch/index.js","xache":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/xache/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/secure-payload.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/package.json","./messages":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/messages.js","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/semaphore.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/server.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/package.json","./announcer":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/announcer.js","./constants":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/constants.js","./crypto":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/crypto.js","./errors":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/errors.js","./holepuncher":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/holepuncher.js","./noise-wrap":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/noise-wrap.js","./secure-payload":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/secure-payload.js","@hyperswarm/secret-stream":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/index.js","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js","blind-relay":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/blind-relay/index.js","bogon":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bogon/index.js","events":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-events/index.js","safety-catch":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/safety-catch/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/sleeper.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/socket-pool.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/raw.js","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/endian.js","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/raw.js","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/endian.js","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperschema/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperschema/runtime.cjs":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperschema/package.json","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperswarm/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperswarm/package.json","./lib/connection-set":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperswarm/lib/connection-set.js","./lib/peer-discovery":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperswarm/lib/peer-discovery.js","./lib/peer-info":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperswarm/lib/peer-info.js","./lib/retry-timer":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperswarm/lib/retry-timer.js","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js","events":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-events/index.js","hyperdht":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/index.js","shuffled-priority-queue":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/shuffled-priority-queue/index.js","streamx":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/streamx/index.js","unslab":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/unslab/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperswarm/lib/bulk-timer.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperswarm/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperswarm/lib/connection-set.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperswarm/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperswarm/lib/peer-discovery.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperswarm/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js","safety-catch":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/safety-catch/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperswarm/lib/peer-info.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperswarm/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js","events":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-events/index.js","unslab":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/unslab/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperswarm/lib/retry-timer.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperswarm/package.json","./bulk-timer":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperswarm/lib/bulk-timer.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperswarm/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/kademlia-routing-table/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/kademlia-routing-table/package.json","events":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-events/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/kademlia-routing-table/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/nanoassert/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/nanoassert/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/nanoassert/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/nat-sampler/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/nat-sampler/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/nat-sampler/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/noise-curve-ed/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/noise-curve-ed/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js","nanoassert":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/nanoassert/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/noise-curve-ed/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/noise-handshake/cipher.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/noise-handshake/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/noise-handshake/dh.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/noise-handshake/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js","nanoassert":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/nanoassert/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/noise-handshake/hkdf.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/noise-handshake/package.json","./hmac":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/noise-handshake/hmac.js","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/noise-handshake/hmac.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/noise-handshake/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/noise-handshake/noise.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/noise-handshake/package.json","./hkdf":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/noise-handshake/hkdf.js","./symmetric-state":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/noise-handshake/symmetric-state.js","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js","nanoassert":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/nanoassert/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/noise-handshake/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/noise-handshake/symmetric-state.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/noise-handshake/package.json","./cipher":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/noise-handshake/cipher.js","./dh":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/noise-handshake/dh.js","./hkdf":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/noise-handshake/hkdf.js","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js","nanoassert":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/nanoassert/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/protomux/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/protomux/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding/index.js","queue-tick":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/queue-tick/process-next-tick.js","safety-catch":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/safety-catch/index.js","unslab":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/unslab/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/protomux/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/queue-tick/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/queue-tick/process-next-tick.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/queue-tick/package.json","./queue-microtask":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/queue-tick/queue-microtask.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/queue-tick/queue-microtask.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/queue-tick/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/ready-resource/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/ready-resource/package.json","events":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-events/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/ready-resource/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/record-cache/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/record-cache/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/record-cache/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/require-addon/lib/bare.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/require-addon/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/require-addon/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/safety-catch/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/safety-catch/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/safety-catch/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/shuffled-priority-queue/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/shuffled-priority-queue/package.json","unordered-set":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/unordered-set/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/shuffled-priority-queue/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/signal-promise/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/signal-promise/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/signal-promise/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/sodium-native/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/sodium-native/package.json",".":"linked:libsodium-native.5.1.0.so","require-addon":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/require-addon/lib/bare.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/sodium-native/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/sodium-native/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/sodium-native/binding.js","assert":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-assert/index.js","which-runtime":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/which-runtime/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/sodium-native/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/sodium-secretstream/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/sodium-secretstream/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/sodium-secretstream/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/sodium-universal/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/sodium-universal/package.json","sodium-native":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/sodium-native/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/sodium-universal/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/streamx/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/streamx/package.json","events-universal":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/events-universal/bare.js","fast-fifo":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/fast-fifo/index.js","text-decoder":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/text-decoder/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/streamx/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/teex/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/teex/package.json","streamx":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/streamx/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/teex/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/text-decoder/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/text-decoder/package.json","./lib/pass-through-decoder":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/text-decoder/lib/pass-through-decoder.js","./lib/utf8-decoder":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/text-decoder/lib/utf8-decoder.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/text-decoder/lib/pass-through-decoder.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/text-decoder/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/text-decoder/lib/utf8-decoder.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/text-decoder/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/text-decoder/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/time-ordered-set/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/time-ordered-set/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/time-ordered-set/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/timeout-refresh/browser.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/timeout-refresh/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/timeout-refresh/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/timeout-refresh/package.json","./browser":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/timeout-refresh/browser.js","./node":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/timeout-refresh/node.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/timeout-refresh/node.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/timeout-refresh/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/timeout-refresh/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/udx-native/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/udx-native/package.json",".":"linked:libudx-native.1.19.2.so","require-addon":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/require-addon/lib/bare.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/udx-native/lib/ip.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/udx-native/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/udx-native/lib/network-interfaces.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/udx-native/package.json","../binding":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/udx-native/binding.js","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js","events":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-events/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/udx-native/lib/socket.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/udx-native/package.json","../binding":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/udx-native/binding.js","./ip":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/udx-native/lib/ip.js","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js","events":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-events/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/udx-native/lib/stream.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/udx-native/package.json","../binding":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/udx-native/binding.js","./ip":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/udx-native/lib/ip.js","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js","streamx":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/streamx/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/udx-native/lib/udx.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/udx-native/package.json","../binding":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/udx-native/binding.js","./ip":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/udx-native/lib/ip.js","./network-interfaces":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/udx-native/lib/network-interfaces.js","./socket":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/udx-native/lib/socket.js","./stream":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/udx-native/lib/stream.js","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/udx-native/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/unordered-set/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/unordered-set/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/unordered-set/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/unslab/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/unslab/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/unslab/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/which-runtime/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/which-runtime/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/which-runtime/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/xache/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/xache/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/xache/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/z32/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/z32/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/z32/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hypercore-crypto/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hypercore-crypto/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/hypercore-crypto/node_modules/compact-encoding/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/hypercore-crypto/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hypercore-crypto/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/hypercore-crypto/node_modules/compact-encoding/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hypercore-crypto/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/hypercore-crypto/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/hyper-proto-peer/node_modules/hypercore-crypto/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/hyper-proto-peer/node_modules/hypercore-crypto/node_modules/compact-encoding/raw.js","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/hypercore-crypto/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hypercore-crypto/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/hypercore-crypto/node_modules/compact-encoding/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hypercore-crypto/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hypercore-crypto/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/hypercore-crypto/node_modules/compact-encoding/endian.js","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/hypercore-crypto/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hypercore-id-encoding/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hypercore-id-encoding/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js","z32":"/node_modules/hyper-proto-peer/node_modules/z32/index.js"},"/node_modules/hyper-proto-peer/node_modules/hypercore-id-encoding/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyperdht-address/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyperdht-address/package.json","./spec/hyperschema":"/node_modules/hyper-proto-peer/node_modules/hyperdht-address/spec/hyperschema/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/hyperdht-address/node_modules/compact-encoding/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyperdht-address/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyperdht-address/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyperdht-address/node_modules/compact-encoding/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyperdht-address/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/hyperdht-address/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/hyper-proto-peer/node_modules/hyperdht-address/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/hyper-proto-peer/node_modules/hyperdht-address/node_modules/compact-encoding/raw.js","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyperdht-address/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyperdht-address/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyperdht-address/node_modules/compact-encoding/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyperdht-address/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyperdht-address/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/hyperdht-address/node_modules/compact-encoding/endian.js","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyperdht-address/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyperdht-address/spec/hyperschema/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyperdht-address/package.json","hyperschema/runtime":"/node_modules/hyper-proto-peer/node_modules/hyperschema/runtime.cjs"},"/node_modules/hyper-proto-peer/node_modules/hyperdht/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyperdht/package.json","./lib/connect":"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/connect.js","./lib/connection-pool":"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/connection-pool.js","./lib/constants":"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/constants.js","./lib/crypto":"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/crypto.js","./lib/errors":"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/errors.js","./lib/messages":"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/messages.js","./lib/persistent":"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/persistent.js","./lib/raw-stream-set":"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/raw-stream-set.js","./lib/router":"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/router.js","./lib/server":"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/server.js","./lib/socket-pool":"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/socket-pool.js","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/hyperdht/node_modules/compact-encoding/index.js","dht-rpc":"/node_modules/hyper-proto-peer/node_modules/dht-rpc/index.js","safety-catch":"/node_modules/hyper-proto-peer/node_modules/safety-catch/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/sodium-universal/index.js","xache":"/node_modules/hyper-proto-peer/node_modules/xache/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/announcer.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyperdht/package.json","./constants":"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/constants.js","./encode":"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/encode.js","./messages":"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/messages.js","./persistent":"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/persistent.js","./sleeper":"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/sleeper.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/hyperdht/node_modules/compact-encoding/index.js","safety-catch":"/node_modules/hyper-proto-peer/node_modules/safety-catch/index.js","signal-promise":"/node_modules/hyper-proto-peer/node_modules/signal-promise/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/connect.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyperdht/package.json","./constants":"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/constants.js","./crypto":"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/crypto.js","./errors":"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/errors.js","./holepuncher":"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/holepuncher.js","./noise-wrap":"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/noise-wrap.js","./secure-payload":"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/secure-payload.js","./semaphore":"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/semaphore.js","./sleeper":"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/sleeper.js","@hyperswarm/secret-stream":"/node_modules/hyper-proto-peer/node_modules/@hyperswarm/secret-stream/index.js","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js","blind-relay":"/node_modules/hyper-proto-peer/node_modules/blind-relay/index.js","bogon":"/node_modules/hyper-proto-peer/node_modules/bogon/index.js","hypercore-id-encoding":"/node_modules/hyper-proto-peer/node_modules/hypercore-id-encoding/index.js","hyperdht-address":"/node_modules/hyper-proto-peer/node_modules/hyperdht-address/index.js","safety-catch":"/node_modules/hyper-proto-peer/node_modules/safety-catch/index.js","unslab":"/node_modules/hyper-proto-peer/node_modules/unslab/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/connection-pool.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyperdht/package.json","./errors":"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/errors.js","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js","events":"/node_modules/hyper-proto-peer/node_modules/bare-events/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/constants.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyperdht/package.json","hypercore-crypto":"/node_modules/hyper-proto-peer/node_modules/hypercore-crypto/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/crypto.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyperdht/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/encode.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyperdht/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/hyperdht/node_modules/compact-encoding/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/errors.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyperdht/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/holepuncher.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyperdht/package.json","./constants":"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/constants.js","./nat":"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/nat.js","./sleeper":"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/sleeper.js","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/messages.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyperdht/package.json","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/hyperdht/node_modules/compact-encoding/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/nat.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyperdht/package.json","../lib/constants":"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/constants.js"},"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/noise-wrap.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyperdht/package.json","./constants":"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/constants.js","./errors":"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/errors.js","./messages":"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/messages.js","@hyperswarm/secret-stream":"/node_modules/hyper-proto-peer/node_modules/@hyperswarm/secret-stream/index.js","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/hyperdht/node_modules/compact-encoding/index.js","noise-curve-ed":"/node_modules/hyper-proto-peer/node_modules/noise-curve-ed/index.js","noise-handshake":"/node_modules/hyper-proto-peer/node_modules/noise-handshake/noise.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/persistent.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyperdht/package.json","./constants":"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/constants.js","./encode":"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/encode.js","./messages":"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/messages.js","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/hyperdht/node_modules/compact-encoding/index.js","record-cache":"/node_modules/hyper-proto-peer/node_modules/record-cache/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/sodium-universal/index.js","unslab":"/node_modules/hyper-proto-peer/node_modules/unslab/index.js","xache":"/node_modules/hyper-proto-peer/node_modules/xache/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/raw-stream-set.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyperdht/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/router.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyperdht/package.json","./constants":"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/constants.js","./errors":"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/errors.js","./messages":"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/messages.js","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/hyperdht/node_modules/compact-encoding/index.js","safety-catch":"/node_modules/hyper-proto-peer/node_modules/safety-catch/index.js","xache":"/node_modules/hyper-proto-peer/node_modules/xache/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/secure-payload.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyperdht/package.json","./messages":"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/messages.js","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/semaphore.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyperdht/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/server.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyperdht/package.json","./announcer":"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/announcer.js","./constants":"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/constants.js","./crypto":"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/crypto.js","./errors":"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/errors.js","./holepuncher":"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/holepuncher.js","./noise-wrap":"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/noise-wrap.js","./secure-payload":"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/secure-payload.js","@hyperswarm/secret-stream":"/node_modules/hyper-proto-peer/node_modules/@hyperswarm/secret-stream/index.js","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js","blind-relay":"/node_modules/hyper-proto-peer/node_modules/blind-relay/index.js","bogon":"/node_modules/hyper-proto-peer/node_modules/bogon/index.js","events":"/node_modules/hyper-proto-peer/node_modules/bare-events/index.js","safety-catch":"/node_modules/hyper-proto-peer/node_modules/safety-catch/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/sleeper.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyperdht/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/socket-pool.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyperdht/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyperdht/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyperdht/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyperdht/node_modules/compact-encoding/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyperdht/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/hyperdht/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/hyper-proto-peer/node_modules/hyperdht/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/hyper-proto-peer/node_modules/hyperdht/node_modules/compact-encoding/raw.js","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyperdht/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyperdht/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyperdht/node_modules/compact-encoding/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyperdht/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyperdht/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/hyperdht/node_modules/compact-encoding/endian.js","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyperdht/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyperschema/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyperschema/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyperschema/node_modules/compact-encoding/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyperschema/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/hyperschema/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/hyper-proto-peer/node_modules/hyperschema/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/hyper-proto-peer/node_modules/hyperschema/node_modules/compact-encoding/raw.js","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyperschema/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyperschema/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyperschema/node_modules/compact-encoding/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyperschema/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyperschema/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/hyperschema/node_modules/compact-encoding/endian.js","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyperschema/package.json":{},"/node_modules/hyper-proto-peer/node_modules/hyperschema/runtime.cjs":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyperschema/package.json","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/hyperschema/node_modules/compact-encoding/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyperswarm/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyperswarm/package.json","./lib/connection-set":"/node_modules/hyper-proto-peer/node_modules/hyperswarm/lib/connection-set.js","./lib/peer-discovery":"/node_modules/hyper-proto-peer/node_modules/hyperswarm/lib/peer-discovery.js","./lib/peer-info":"/node_modules/hyper-proto-peer/node_modules/hyperswarm/lib/peer-info.js","./lib/retry-timer":"/node_modules/hyper-proto-peer/node_modules/hyperswarm/lib/retry-timer.js","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js","events":"/node_modules/hyper-proto-peer/node_modules/bare-events/index.js","hyperdht":"/node_modules/hyper-proto-peer/node_modules/hyperdht/index.js","shuffled-priority-queue":"/node_modules/hyper-proto-peer/node_modules/shuffled-priority-queue/index.js","streamx":"/node_modules/hyper-proto-peer/node_modules/streamx/index.js","unslab":"/node_modules/hyper-proto-peer/node_modules/unslab/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyperswarm/lib/bulk-timer.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyperswarm/package.json"},"/node_modules/hyper-proto-peer/node_modules/hyperswarm/lib/connection-set.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyperswarm/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyperswarm/lib/peer-discovery.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyperswarm/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js","safety-catch":"/node_modules/hyper-proto-peer/node_modules/safety-catch/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyperswarm/lib/peer-info.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyperswarm/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js","events":"/node_modules/hyper-proto-peer/node_modules/bare-events/index.js","unslab":"/node_modules/hyper-proto-peer/node_modules/unslab/index.js"},"/node_modules/hyper-proto-peer/node_modules/hyperswarm/lib/retry-timer.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/hyperswarm/package.json","./bulk-timer":"/node_modules/hyper-proto-peer/node_modules/hyperswarm/lib/bulk-timer.js"},"/node_modules/hyper-proto-peer/node_modules/hyperswarm/package.json":{},"/node_modules/hyper-proto-peer/node_modules/kademlia-routing-table/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/kademlia-routing-table/package.json","events":"/node_modules/hyper-proto-peer/node_modules/bare-events/index.js"},"/node_modules/hyper-proto-peer/node_modules/kademlia-routing-table/package.json":{},"/node_modules/hyper-proto-peer/node_modules/keet-identity-key/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/keet-identity-key/package.json","./lib/crypto":"/node_modules/hyper-proto-peer/node_modules/keet-identity-key/lib/crypto.js","./lib/encoding":"/node_modules/hyper-proto-peer/node_modules/keet-identity-key/lib/encoding.js","./lib/keychain":"/node_modules/hyper-proto-peer/node_modules/keet-identity-key/lib/keychain.js","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/keet-identity-key/node_modules/compact-encoding/index.js"},"/node_modules/hyper-proto-peer/node_modules/keet-identity-key/lib/crypto.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/keet-identity-key/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/keet-identity-key/lib/encoding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/keet-identity-key/package.json","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/keet-identity-key/node_modules/compact-encoding/index.js"},"/node_modules/hyper-proto-peer/node_modules/keet-identity-key/lib/keychain.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/keet-identity-key/package.json","./crypto":"/node_modules/hyper-proto-peer/node_modules/keet-identity-key/lib/crypto.js","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js","bip39-mnemonic":"/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/keet-identity-key/node_modules/compact-encoding/index.js","nanoassert":"/node_modules/hyper-proto-peer/node_modules/nanoassert/index.js","sodium-hmac":"/node_modules/hyper-proto-peer/node_modules/sodium-hmac/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/keet-identity-key/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/keet-identity-key/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/keet-identity-key/node_modules/compact-encoding/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/keet-identity-key/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/keet-identity-key/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/hyper-proto-peer/node_modules/keet-identity-key/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/hyper-proto-peer/node_modules/keet-identity-key/node_modules/compact-encoding/raw.js","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/keet-identity-key/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/keet-identity-key/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/keet-identity-key/node_modules/compact-encoding/package.json":{},"/node_modules/hyper-proto-peer/node_modules/keet-identity-key/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/keet-identity-key/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/keet-identity-key/node_modules/compact-encoding/endian.js","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/keet-identity-key/package.json":{},"/node_modules/hyper-proto-peer/node_modules/multiformats/dist/src/bases/base.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/multiformats/package.json","../bytes.js":"/node_modules/hyper-proto-peer/node_modules/multiformats/dist/src/bytes.js","../vendor/base-x.js":"/node_modules/hyper-proto-peer/node_modules/multiformats/dist/src/vendor/base-x.js"},"/node_modules/hyper-proto-peer/node_modules/multiformats/dist/src/bases/base32.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/multiformats/package.json","./base.js":"/node_modules/hyper-proto-peer/node_modules/multiformats/dist/src/bases/base.js"},"/node_modules/hyper-proto-peer/node_modules/multiformats/dist/src/bases/base36.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/multiformats/package.json","./base.js":"/node_modules/hyper-proto-peer/node_modules/multiformats/dist/src/bases/base.js"},"/node_modules/hyper-proto-peer/node_modules/multiformats/dist/src/bases/base58.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/multiformats/package.json","./base.js":"/node_modules/hyper-proto-peer/node_modules/multiformats/dist/src/bases/base.js"},"/node_modules/hyper-proto-peer/node_modules/multiformats/dist/src/bytes.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/multiformats/package.json"},"/node_modules/hyper-proto-peer/node_modules/multiformats/dist/src/cid.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/multiformats/package.json","./bases/base32.js":"/node_modules/hyper-proto-peer/node_modules/multiformats/dist/src/bases/base32.js","./bases/base36.js":"/node_modules/hyper-proto-peer/node_modules/multiformats/dist/src/bases/base36.js","./bases/base58.js":"/node_modules/hyper-proto-peer/node_modules/multiformats/dist/src/bases/base58.js","./bytes.js":"/node_modules/hyper-proto-peer/node_modules/multiformats/dist/src/bytes.js","./hashes/digest.js":"/node_modules/hyper-proto-peer/node_modules/multiformats/dist/src/hashes/digest.js","./link/interface.js":"/node_modules/hyper-proto-peer/node_modules/multiformats/dist/src/link/interface.js","./varint.js":"/node_modules/hyper-proto-peer/node_modules/multiformats/dist/src/varint.js"},"/node_modules/hyper-proto-peer/node_modules/multiformats/dist/src/hashes/digest.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/multiformats/package.json","../bytes.js":"/node_modules/hyper-proto-peer/node_modules/multiformats/dist/src/bytes.js","../varint.js":"/node_modules/hyper-proto-peer/node_modules/multiformats/dist/src/varint.js"},"/node_modules/hyper-proto-peer/node_modules/multiformats/dist/src/link/interface.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/multiformats/package.json"},"/node_modules/hyper-proto-peer/node_modules/multiformats/dist/src/varint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/multiformats/package.json","./vendor/varint.js":"/node_modules/hyper-proto-peer/node_modules/multiformats/dist/src/vendor/varint.js"},"/node_modules/hyper-proto-peer/node_modules/multiformats/dist/src/vendor/base-x.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/multiformats/package.json"},"/node_modules/hyper-proto-peer/node_modules/multiformats/dist/src/vendor/varint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/multiformats/package.json"},"/node_modules/hyper-proto-peer/node_modules/multiformats/package.json":{},"/node_modules/hyper-proto-peer/node_modules/nanoassert/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/nanoassert/package.json"},"/node_modules/hyper-proto-peer/node_modules/nanoassert/package.json":{},"/node_modules/hyper-proto-peer/node_modules/nat-sampler/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/nat-sampler/package.json"},"/node_modules/hyper-proto-peer/node_modules/nat-sampler/package.json":{},"/node_modules/hyper-proto-peer/node_modules/noise-curve-ed/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/noise-curve-ed/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js","nanoassert":"/node_modules/hyper-proto-peer/node_modules/nanoassert/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/noise-curve-ed/package.json":{},"/node_modules/hyper-proto-peer/node_modules/noise-handshake/cipher.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/noise-handshake/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/noise-handshake/dh.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/noise-handshake/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js","nanoassert":"/node_modules/hyper-proto-peer/node_modules/nanoassert/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/noise-handshake/hkdf.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/noise-handshake/package.json","./hmac":"/node_modules/hyper-proto-peer/node_modules/noise-handshake/hmac.js","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/noise-handshake/hmac.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/noise-handshake/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/noise-handshake/noise.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/noise-handshake/package.json","./hkdf":"/node_modules/hyper-proto-peer/node_modules/noise-handshake/hkdf.js","./symmetric-state":"/node_modules/hyper-proto-peer/node_modules/noise-handshake/symmetric-state.js","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js","nanoassert":"/node_modules/hyper-proto-peer/node_modules/nanoassert/index.js"},"/node_modules/hyper-proto-peer/node_modules/noise-handshake/package.json":{},"/node_modules/hyper-proto-peer/node_modules/noise-handshake/symmetric-state.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/noise-handshake/package.json","./cipher":"/node_modules/hyper-proto-peer/node_modules/noise-handshake/cipher.js","./dh":"/node_modules/hyper-proto-peer/node_modules/noise-handshake/dh.js","./hkdf":"/node_modules/hyper-proto-peer/node_modules/noise-handshake/hkdf.js","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js","nanoassert":"/node_modules/hyper-proto-peer/node_modules/nanoassert/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/protomux-rpc/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/protomux-rpc/package.json","./lib/errors":"/node_modules/hyper-proto-peer/node_modules/protomux-rpc/lib/errors.js","bits-to-bytes":"/node_modules/hyper-proto-peer/node_modules/bits-to-bytes/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/protomux-rpc/node_modules/compact-encoding/index.js","compact-encoding-bitfield":"/node_modules/hyper-proto-peer/node_modules/compact-encoding-bitfield/index.js","events":"/node_modules/hyper-proto-peer/node_modules/bare-events/index.js","protomux":"/node_modules/hyper-proto-peer/node_modules/protomux/index.js","safety-catch":"/node_modules/hyper-proto-peer/node_modules/safety-catch/index.js"},"/node_modules/hyper-proto-peer/node_modules/protomux-rpc/lib/errors.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/protomux-rpc/package.json"},"/node_modules/hyper-proto-peer/node_modules/protomux-rpc/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/protomux-rpc/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/protomux-rpc/node_modules/compact-encoding/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/protomux-rpc/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/protomux-rpc/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/hyper-proto-peer/node_modules/protomux-rpc/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/hyper-proto-peer/node_modules/protomux-rpc/node_modules/compact-encoding/raw.js","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/protomux-rpc/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/protomux-rpc/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/protomux-rpc/node_modules/compact-encoding/package.json":{},"/node_modules/hyper-proto-peer/node_modules/protomux-rpc/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/protomux-rpc/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/protomux-rpc/node_modules/compact-encoding/endian.js","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/protomux-rpc/package.json":{},"/node_modules/hyper-proto-peer/node_modules/protomux-wakeup/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/protomux-wakeup/package.json","./spec/hyperschema":"/node_modules/hyper-proto-peer/node_modules/protomux-wakeup/spec/hyperschema/index.js","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js","hypercore-crypto":"/node_modules/hyper-proto-peer/node_modules/hypercore-crypto/index.js","protomux":"/node_modules/hyper-proto-peer/node_modules/protomux/index.js"},"/node_modules/hyper-proto-peer/node_modules/protomux-wakeup/package.json":{},"/node_modules/hyper-proto-peer/node_modules/protomux-wakeup/spec/hyperschema/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/protomux-wakeup/package.json","hyperschema/runtime":"/node_modules/hyper-proto-peer/node_modules/hyperschema/runtime.cjs"},"/node_modules/hyper-proto-peer/node_modules/protomux/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/protomux/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-proto-peer/node_modules/protomux/node_modules/compact-encoding/index.js","queue-tick":"/node_modules/hyper-proto-peer/node_modules/queue-tick/process-next-tick.js","safety-catch":"/node_modules/hyper-proto-peer/node_modules/safety-catch/index.js","unslab":"/node_modules/hyper-proto-peer/node_modules/unslab/index.js"},"/node_modules/hyper-proto-peer/node_modules/protomux/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/protomux/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/protomux/node_modules/compact-encoding/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/protomux/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/protomux/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/hyper-proto-peer/node_modules/protomux/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/hyper-proto-peer/node_modules/protomux/node_modules/compact-encoding/raw.js","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/protomux/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/protomux/node_modules/compact-encoding/package.json"},"/node_modules/hyper-proto-peer/node_modules/protomux/node_modules/compact-encoding/package.json":{},"/node_modules/hyper-proto-peer/node_modules/protomux/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/protomux/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-proto-peer/node_modules/protomux/node_modules/compact-encoding/endian.js","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/protomux/package.json":{},"/node_modules/hyper-proto-peer/node_modules/queue-tick/package.json":{},"/node_modules/hyper-proto-peer/node_modules/queue-tick/process-next-tick.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/queue-tick/package.json","./queue-microtask":"/node_modules/hyper-proto-peer/node_modules/queue-tick/queue-microtask.js"},"/node_modules/hyper-proto-peer/node_modules/queue-tick/queue-microtask.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/queue-tick/package.json"},"/node_modules/hyper-proto-peer/node_modules/record-cache/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/record-cache/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/record-cache/package.json":{},"/node_modules/hyper-proto-peer/node_modules/require-addon/lib/bare.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/require-addon/package.json"},"/node_modules/hyper-proto-peer/node_modules/require-addon/package.json":{},"/node_modules/hyper-proto-peer/node_modules/safety-catch/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/safety-catch/package.json"},"/node_modules/hyper-proto-peer/node_modules/safety-catch/package.json":{},"/node_modules/hyper-proto-peer/node_modules/shuffled-priority-queue/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/shuffled-priority-queue/package.json","unordered-set":"/node_modules/hyper-proto-peer/node_modules/unordered-set/index.js"},"/node_modules/hyper-proto-peer/node_modules/shuffled-priority-queue/package.json":{},"/node_modules/hyper-proto-peer/node_modules/signal-promise/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/signal-promise/package.json"},"/node_modules/hyper-proto-peer/node_modules/signal-promise/package.json":{},"/node_modules/hyper-proto-peer/node_modules/sodium-hmac/hash/sha256.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/sodium-hmac/package.json","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/sodium-hmac/hash/sha512.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/sodium-hmac/package.json","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/sodium-hmac/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/sodium-hmac/package.json","./hash/sha256":"/node_modules/hyper-proto-peer/node_modules/sodium-hmac/hash/sha256.js","./hash/sha512":"/node_modules/hyper-proto-peer/node_modules/sodium-hmac/hash/sha512.js","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/sodium-hmac/package.json":{},"/node_modules/hyper-proto-peer/node_modules/sodium-native/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/sodium-native/package.json",".":"linked:libsodium-native.5.1.0.so","require-addon":"/node_modules/hyper-proto-peer/node_modules/require-addon/lib/bare.js"},"/node_modules/hyper-proto-peer/node_modules/sodium-native/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/sodium-native/package.json","./binding":"/node_modules/hyper-proto-peer/node_modules/sodium-native/binding.js","assert":"/node_modules/hyper-proto-peer/node_modules/bare-assert/index.js","which-runtime":"/node_modules/hyper-proto-peer/node_modules/which-runtime/index.js"},"/node_modules/hyper-proto-peer/node_modules/sodium-native/package.json":{},"/node_modules/hyper-proto-peer/node_modules/sodium-secretstream/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/sodium-secretstream/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js","sodium-universal":"/node_modules/hyper-proto-peer/node_modules/sodium-universal/index.js"},"/node_modules/hyper-proto-peer/node_modules/sodium-secretstream/package.json":{},"/node_modules/hyper-proto-peer/node_modules/sodium-universal/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/sodium-universal/package.json","sodium-native":"/node_modules/hyper-proto-peer/node_modules/sodium-native/index.js"},"/node_modules/hyper-proto-peer/node_modules/sodium-universal/package.json":{},"/node_modules/hyper-proto-peer/node_modules/streamx/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/streamx/package.json","./lib/errors.js":"/node_modules/hyper-proto-peer/node_modules/streamx/lib/errors.js","events-universal":"/node_modules/hyper-proto-peer/node_modules/events-universal/bare.js","fast-fifo":"/node_modules/hyper-proto-peer/node_modules/fast-fifo/index.js","text-decoder":"/node_modules/hyper-proto-peer/node_modules/text-decoder/index.js"},"/node_modules/hyper-proto-peer/node_modules/streamx/lib/errors.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/streamx/package.json"},"/node_modules/hyper-proto-peer/node_modules/streamx/package.json":{},"/node_modules/hyper-proto-peer/node_modules/teex/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/teex/package.json","streamx":"/node_modules/hyper-proto-peer/node_modules/streamx/index.js"},"/node_modules/hyper-proto-peer/node_modules/teex/package.json":{},"/node_modules/hyper-proto-peer/node_modules/text-decoder/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/text-decoder/package.json","./lib/pass-through-decoder":"/node_modules/hyper-proto-peer/node_modules/text-decoder/lib/pass-through-decoder.js","./lib/utf8-decoder":"/node_modules/hyper-proto-peer/node_modules/text-decoder/lib/utf8-decoder.js"},"/node_modules/hyper-proto-peer/node_modules/text-decoder/lib/pass-through-decoder.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/text-decoder/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/text-decoder/lib/utf8-decoder.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/text-decoder/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/text-decoder/package.json":{},"/node_modules/hyper-proto-peer/node_modules/time-ordered-set/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/time-ordered-set/package.json"},"/node_modules/hyper-proto-peer/node_modules/time-ordered-set/package.json":{},"/node_modules/hyper-proto-peer/node_modules/timeout-refresh/browser.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/timeout-refresh/package.json"},"/node_modules/hyper-proto-peer/node_modules/timeout-refresh/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/timeout-refresh/package.json","./browser":"/node_modules/hyper-proto-peer/node_modules/timeout-refresh/browser.js","./node":"/node_modules/hyper-proto-peer/node_modules/timeout-refresh/node.js"},"/node_modules/hyper-proto-peer/node_modules/timeout-refresh/node.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/timeout-refresh/package.json"},"/node_modules/hyper-proto-peer/node_modules/timeout-refresh/package.json":{},"/node_modules/hyper-proto-peer/node_modules/udx-native/binding.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/udx-native/package.json",".":"linked:libudx-native.1.20.7.so","require-addon":"/node_modules/hyper-proto-peer/node_modules/require-addon/lib/bare.js"},"/node_modules/hyper-proto-peer/node_modules/udx-native/lib/ip.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/udx-native/package.json"},"/node_modules/hyper-proto-peer/node_modules/udx-native/lib/network-interfaces.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/udx-native/package.json","../binding":"/node_modules/hyper-proto-peer/node_modules/udx-native/binding.js","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js","events":"/node_modules/hyper-proto-peer/node_modules/bare-events/index.js"},"/node_modules/hyper-proto-peer/node_modules/udx-native/lib/socket.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/udx-native/package.json","../binding":"/node_modules/hyper-proto-peer/node_modules/udx-native/binding.js","./ip":"/node_modules/hyper-proto-peer/node_modules/udx-native/lib/ip.js","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js","events":"/node_modules/hyper-proto-peer/node_modules/bare-events/index.js"},"/node_modules/hyper-proto-peer/node_modules/udx-native/lib/stream.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/udx-native/package.json","../binding":"/node_modules/hyper-proto-peer/node_modules/udx-native/binding.js","./ip":"/node_modules/hyper-proto-peer/node_modules/udx-native/lib/ip.js","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js","streamx":"/node_modules/hyper-proto-peer/node_modules/streamx/index.js"},"/node_modules/hyper-proto-peer/node_modules/udx-native/lib/udx.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/udx-native/package.json","../binding":"/node_modules/hyper-proto-peer/node_modules/udx-native/binding.js","./ip":"/node_modules/hyper-proto-peer/node_modules/udx-native/lib/ip.js","./network-interfaces":"/node_modules/hyper-proto-peer/node_modules/udx-native/lib/network-interfaces.js","./socket":"/node_modules/hyper-proto-peer/node_modules/udx-native/lib/socket.js","./stream":"/node_modules/hyper-proto-peer/node_modules/udx-native/lib/stream.js","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/udx-native/package.json":{},"/node_modules/hyper-proto-peer/node_modules/unordered-set/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/unordered-set/package.json"},"/node_modules/hyper-proto-peer/node_modules/unordered-set/package.json":{},"/node_modules/hyper-proto-peer/node_modules/unslab/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/unslab/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/unslab/package.json":{},"/node_modules/hyper-proto-peer/node_modules/which-runtime/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/which-runtime/package.json"},"/node_modules/hyper-proto-peer/node_modules/which-runtime/package.json":{},"/node_modules/hyper-proto-peer/node_modules/xache/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/xache/package.json"},"/node_modules/hyper-proto-peer/node_modules/xache/package.json":{},"/node_modules/hyper-proto-peer/node_modules/z32/index.js":{"#package":"/node_modules/hyper-proto-peer/node_modules/z32/package.json","b4a":"/node_modules/hyper-proto-peer/node_modules/b4a/index.js"},"/node_modules/hyper-proto-peer/node_modules/z32/package.json":{},"/node_modules/hyper-proto-peer/package.json":{},"/node_modules/hyper-svc/index.js":{"#package":"/node_modules/hyper-svc/package.json","./lib/client.js":"/node_modules/hyper-svc/lib/client.js","./lib/frame.js":"/node_modules/hyper-svc/lib/frame.js","./lib/service.js":"/node_modules/hyper-svc/lib/service.js","./lib/transports/swarm-rpc.js":"/node_modules/hyper-svc/lib/transports/swarm-rpc.js"},"/node_modules/hyper-svc/lib/client.js":{"#node:fs/promises":"/node_modules/hyper-svc/node_modules/bare-fs/promises.js","#node:http":"/node_modules/hyper-svc/node_modules/bare-http1/index.js","#node:url":"/node_modules/hyper-svc/node_modules/bare-url/index.js","#package":"/node_modules/hyper-svc/package.json","./frame.js":"/node_modules/hyper-svc/lib/frame.js","./transports/swarm-rpc.js":"/node_modules/hyper-svc/lib/transports/swarm-rpc.js","./uds-backend.js":"/node_modules/hyper-svc/lib/uds-backend.js","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js","hypercore-crypto":"/node_modules/hyper-svc/node_modules/hypercore-crypto/index.js","hyperswarm":"/node_modules/hyper-svc/node_modules/hyperswarm/index.js","protomux":"/node_modules/hyper-svc/node_modules/protomux/index.js"},"/node_modules/hyper-svc/lib/frame.js":{"#package":"/node_modules/hyper-svc/package.json","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-svc/lib/service.js":{"#node:process":"/node_modules/hyper-svc/node_modules/bare-process/index.js","#package":"/node_modules/hyper-svc/package.json","./transports/http.js":"/node_modules/hyper-svc/lib/transports/http.js","./transports/swarm.js":"/node_modules/hyper-svc/lib/transports/swarm.js","./transports/uds.js":"/node_modules/hyper-svc/lib/transports/uds.js","ready-resource":"/node_modules/hyper-svc/node_modules/ready-resource/index.js"},"/node_modules/hyper-svc/lib/transports/http.js":{"#node:http":"/node_modules/hyper-svc/node_modules/bare-http1/index.js","#package":"/node_modules/hyper-svc/package.json","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-svc/lib/transports/swarm-rpc.js":{"#package":"/node_modules/hyper-svc/package.json","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-svc/node_modules/compact-encoding/index.js","protomux":"/node_modules/hyper-svc/node_modules/protomux/index.js"},"/node_modules/hyper-svc/lib/transports/swarm.js":{"#package":"/node_modules/hyper-svc/package.json","./swarm-rpc.js":"/node_modules/hyper-svc/lib/transports/swarm-rpc.js","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js","hyperswarm":"/node_modules/hyper-svc/node_modules/hyperswarm/index.js","protomux":"/node_modules/hyper-svc/node_modules/protomux/index.js"},"/node_modules/hyper-svc/lib/transports/uds.js":{"#node:fs/promises":"/node_modules/hyper-svc/node_modules/bare-fs/promises.js","#node:process":"/node_modules/hyper-svc/node_modules/bare-process/index.js","#package":"/node_modules/hyper-svc/package.json","../frame.js":"/node_modules/hyper-svc/lib/frame.js","../uds-backend.js":"/node_modules/hyper-svc/lib/uds-backend.js"},"/node_modules/hyper-svc/lib/uds-backend.js":{"#node:net":"/node_modules/hyper-svc/node_modules/bare-net/index.js","#package":"/node_modules/hyper-svc/package.json","bare-abstract-socket":"deferred:bare-abstract-socket"},"/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/index.js":{"#package":"/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/package.json","./lib/bridge":"/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/lib/bridge.js","./lib/handshake":"/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/lib/handshake.js","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js","hypercore-crypto":"/node_modules/hyper-svc/node_modules/hypercore-crypto/index.js","sodium-secretstream":"/node_modules/hyper-svc/node_modules/sodium-secretstream/index.js","sodium-universal":"/node_modules/hyper-svc/node_modules/sodium-universal/index.js","streamx":"/node_modules/hyper-svc/node_modules/streamx/index.js","timeout-refresh":"/node_modules/hyper-svc/node_modules/timeout-refresh/index.js","unslab":"/node_modules/hyper-svc/node_modules/unslab/index.js"},"/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/lib/bridge.js":{"#package":"/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/package.json","streamx":"/node_modules/hyper-svc/node_modules/streamx/index.js"},"/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/lib/handshake.js":{"#package":"/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/package.json","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js","noise-curve-ed":"/node_modules/hyper-svc/node_modules/noise-curve-ed/index.js","noise-handshake":"/node_modules/hyper-svc/node_modules/noise-handshake/noise.js","sodium-universal":"/node_modules/hyper-svc/node_modules/sodium-universal/index.js"},"/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/package.json":{},"/node_modules/hyper-svc/node_modules/adaptive-timeout/index.js":{"#package":"/node_modules/hyper-svc/node_modules/adaptive-timeout/package.json","xache":"/node_modules/hyper-svc/node_modules/xache/index.js"},"/node_modules/hyper-svc/node_modules/adaptive-timeout/package.json":{},"/node_modules/hyper-svc/node_modules/b4a/index.js":{"#package":"/node_modules/hyper-svc/node_modules/b4a/package.json"},"/node_modules/hyper-svc/node_modules/b4a/package.json":{},"/node_modules/hyper-svc/node_modules/bare-abort/binding.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-abort/package.json",".":"linked:libbare-abort.2.0.13.so"},"/node_modules/hyper-svc/node_modules/bare-abort/index.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-abort/package.json","./binding":"/node_modules/hyper-svc/node_modules/bare-abort/binding.js"},"/node_modules/hyper-svc/node_modules/bare-abort/package.json":{},"/node_modules/hyper-svc/node_modules/bare-ansi-escapes/index.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-ansi-escapes/package.json"},"/node_modules/hyper-svc/node_modules/bare-ansi-escapes/package.json":{},"/node_modules/hyper-svc/node_modules/bare-assert/index.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-assert/package.json","bare-inspect":"/node_modules/hyper-svc/node_modules/bare-inspect/index.js"},"/node_modules/hyper-svc/node_modules/bare-assert/package.json":{},"/node_modules/hyper-svc/node_modules/bare-dns/binding.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-dns/package.json",".":"linked:libbare-dns.2.1.4.so"},"/node_modules/hyper-svc/node_modules/bare-dns/index.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-dns/package.json","./binding":"/node_modules/hyper-svc/node_modules/bare-dns/binding.js"},"/node_modules/hyper-svc/node_modules/bare-dns/package.json":{},"/node_modules/hyper-svc/node_modules/bare-env/index.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-env/package.json","bare-os":"/node_modules/hyper-svc/node_modules/bare-os/index.js"},"/node_modules/hyper-svc/node_modules/bare-env/package.json":{},"/node_modules/hyper-svc/node_modules/bare-events/index.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-events/package.json","./lib/errors":"/node_modules/hyper-svc/node_modules/bare-events/lib/errors.js"},"/node_modules/hyper-svc/node_modules/bare-events/lib/errors.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-events/package.json"},"/node_modules/hyper-svc/node_modules/bare-events/package.json":{},"/node_modules/hyper-svc/node_modules/bare-fs/binding.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-fs/package.json",".":"linked:libbare-fs.4.7.2.so"},"/node_modules/hyper-svc/node_modules/bare-fs/index.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-fs/package.json","./binding":"/node_modules/hyper-svc/node_modules/bare-fs/binding.js","./lib/constants":"/node_modules/hyper-svc/node_modules/bare-fs/lib/constants.js","./lib/errors":"/node_modules/hyper-svc/node_modules/bare-fs/lib/errors.js","./promises":"/node_modules/hyper-svc/node_modules/bare-fs/promises.js","bare-events":"/node_modules/hyper-svc/node_modules/bare-events/index.js","bare-path":"/node_modules/hyper-svc/node_modules/bare-path/index.js","bare-stream":"/node_modules/hyper-svc/node_modules/bare-stream/index.js","bare-url":"/node_modules/hyper-svc/node_modules/bare-url/index.js","fast-fifo":"/node_modules/hyper-svc/node_modules/fast-fifo/index.js"},"/node_modules/hyper-svc/node_modules/bare-fs/lib/constants.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-fs/package.json","../binding":"/node_modules/hyper-svc/node_modules/bare-fs/binding.js"},"/node_modules/hyper-svc/node_modules/bare-fs/lib/errors.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-fs/package.json","bare-os":"/node_modules/hyper-svc/node_modules/bare-os/index.js"},"/node_modules/hyper-svc/node_modules/bare-fs/package.json":{},"/node_modules/hyper-svc/node_modules/bare-fs/promises.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-fs/package.json",".":"/node_modules/hyper-svc/node_modules/bare-fs/index.js","bare-events":"/node_modules/hyper-svc/node_modules/bare-events/index.js"},"/node_modules/hyper-svc/node_modules/bare-hrtime/binding.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-hrtime/package.json",".":"linked:libbare-hrtime.2.1.1.so"},"/node_modules/hyper-svc/node_modules/bare-hrtime/index.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-hrtime/package.json","./binding":"/node_modules/hyper-svc/node_modules/bare-hrtime/binding.js"},"/node_modules/hyper-svc/node_modules/bare-hrtime/package.json":{},"/node_modules/hyper-svc/node_modules/bare-http-parser/index.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-http-parser/package.json","./lib/errors":"/node_modules/hyper-svc/node_modules/bare-http-parser/lib/errors.js"},"/node_modules/hyper-svc/node_modules/bare-http-parser/lib/errors.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-http-parser/package.json"},"/node_modules/hyper-svc/node_modules/bare-http-parser/package.json":{},"/node_modules/hyper-svc/node_modules/bare-http1/index.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-http1/package.json","./lib/agent":"/node_modules/hyper-svc/node_modules/bare-http1/lib/agent.js","./lib/client-connection":"/node_modules/hyper-svc/node_modules/bare-http1/lib/client-connection.js","./lib/client-request":"/node_modules/hyper-svc/node_modules/bare-http1/lib/client-request.js","./lib/constants":"/node_modules/hyper-svc/node_modules/bare-http1/lib/constants.js","./lib/errors":"/node_modules/hyper-svc/node_modules/bare-http1/lib/errors.js","./lib/incoming-message":"/node_modules/hyper-svc/node_modules/bare-http1/lib/incoming-message.js","./lib/outgoing-message":"/node_modules/hyper-svc/node_modules/bare-http1/lib/outgoing-message.js","./lib/server":"/node_modules/hyper-svc/node_modules/bare-http1/lib/server.js","./lib/server-connection":"/node_modules/hyper-svc/node_modules/bare-http1/lib/server-connection.js","./lib/server-response":"/node_modules/hyper-svc/node_modules/bare-http1/lib/server-response.js"},"/node_modules/hyper-svc/node_modules/bare-http1/lib/agent.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-http1/package.json","./client-connection":"/node_modules/hyper-svc/node_modules/bare-http1/lib/client-connection.js","./errors":"/node_modules/hyper-svc/node_modules/bare-http1/lib/errors.js","bare-events":"/node_modules/hyper-svc/node_modules/bare-events/index.js","bare-tcp":"/node_modules/hyper-svc/node_modules/bare-tcp/index.js"},"/node_modules/hyper-svc/node_modules/bare-http1/lib/client-connection.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-http1/package.json","./errors":"/node_modules/hyper-svc/node_modules/bare-http1/lib/errors.js","./incoming-message":"/node_modules/hyper-svc/node_modules/bare-http1/lib/incoming-message.js","bare-http-parser":"/node_modules/hyper-svc/node_modules/bare-http-parser/index.js"},"/node_modules/hyper-svc/node_modules/bare-http1/lib/client-request.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-http1/package.json","./agent":"/node_modules/hyper-svc/node_modules/bare-http1/lib/agent.js","./outgoing-message":"/node_modules/hyper-svc/node_modules/bare-http1/lib/outgoing-message.js"},"/node_modules/hyper-svc/node_modules/bare-http1/lib/constants.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-http1/package.json"},"/node_modules/hyper-svc/node_modules/bare-http1/lib/errors.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-http1/package.json"},"/node_modules/hyper-svc/node_modules/bare-http1/lib/incoming-message.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-http1/package.json","bare-stream":"/node_modules/hyper-svc/node_modules/bare-stream/index.js"},"/node_modules/hyper-svc/node_modules/bare-http1/lib/outgoing-message.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-http1/package.json","./errors":"/node_modules/hyper-svc/node_modules/bare-http1/lib/errors.js","bare-stream":"/node_modules/hyper-svc/node_modules/bare-stream/index.js"},"/node_modules/hyper-svc/node_modules/bare-http1/lib/server-connection.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-http1/package.json","./incoming-message":"/node_modules/hyper-svc/node_modules/bare-http1/lib/incoming-message.js","./server-response":"/node_modules/hyper-svc/node_modules/bare-http1/lib/server-response.js","bare-http-parser":"/node_modules/hyper-svc/node_modules/bare-http-parser/index.js","bare-stream":"/node_modules/hyper-svc/node_modules/bare-stream/index.js"},"/node_modules/hyper-svc/node_modules/bare-http1/lib/server-response.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-http1/package.json","./constants":"/node_modules/hyper-svc/node_modules/bare-http1/lib/constants.js","./outgoing-message":"/node_modules/hyper-svc/node_modules/bare-http1/lib/outgoing-message.js","bare-stream":"/node_modules/hyper-svc/node_modules/bare-stream/index.js"},"/node_modules/hyper-svc/node_modules/bare-http1/lib/server.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-http1/package.json","./server-connection":"/node_modules/hyper-svc/node_modules/bare-http1/lib/server-connection.js","bare-tcp":"/node_modules/hyper-svc/node_modules/bare-tcp/index.js"},"/node_modules/hyper-svc/node_modules/bare-http1/package.json":{},"/node_modules/hyper-svc/node_modules/bare-inspect/binding.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-inspect/package.json",".":"linked:libbare-inspect.3.1.4.so"},"/node_modules/hyper-svc/node_modules/bare-inspect/index.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-inspect/package.json","./binding":"/node_modules/hyper-svc/node_modules/bare-inspect/binding.js","bare-ansi-escapes":"/node_modules/hyper-svc/node_modules/bare-ansi-escapes/index.js","bare-type":"/node_modules/hyper-svc/node_modules/bare-type/index.js"},"/node_modules/hyper-svc/node_modules/bare-inspect/package.json":{},"/node_modules/hyper-svc/node_modules/bare-net/index.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-net/package.json","bare-events":"/node_modules/hyper-svc/node_modules/bare-events/index.js","bare-pipe":"/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/index.js","bare-stream":"/node_modules/hyper-svc/node_modules/bare-stream/index.js","bare-tcp":"/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/index.js"},"/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-dns/binding.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-dns/package.json",".":"linked:libbare-dns.1.0.5.so"},"/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-dns/index.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-dns/package.json","./binding":"/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-dns/binding.js"},"/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-dns/package.json":{},"/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/binding.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/package.json",".":"linked:libbare-pipe.3.3.8.so"},"/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/index.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/package.json","./binding":"/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/binding.js","./lib/constants":"/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/lib/constants.js","./lib/errors":"/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/lib/errors.js","bare-events":"/node_modules/hyper-svc/node_modules/bare-events/index.js","bare-stream":"/node_modules/hyper-svc/node_modules/bare-stream/index.js"},"/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/lib/constants.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/package.json"},"/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/lib/errors.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/package.json"},"/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/package.json":{},"/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/binding.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/package.json",".":"linked:libbare-tcp.1.9.1.so"},"/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/index.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/package.json","./binding":"/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/binding.js","./lib/constants":"/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/lib/constants.js","./lib/errors":"/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/lib/errors.js","./lib/ip":"/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/lib/ip.js","bare-dns":"/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-dns/index.js","bare-events":"/node_modules/hyper-svc/node_modules/bare-events/index.js","bare-stream":"/node_modules/hyper-svc/node_modules/bare-stream/index.js"},"/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/lib/constants.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/package.json"},"/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/lib/errors.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/package.json"},"/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/lib/ip.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/package.json"},"/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/package.json":{},"/node_modules/hyper-svc/node_modules/bare-net/package.json":{},"/node_modules/hyper-svc/node_modules/bare-os/binding.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-os/package.json",".":"linked:libbare-os.3.9.1.so"},"/node_modules/hyper-svc/node_modules/bare-os/index.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-os/package.json","./binding":"/node_modules/hyper-svc/node_modules/bare-os/binding.js","./lib/constants":"/node_modules/hyper-svc/node_modules/bare-os/lib/constants.js","./lib/errors":"/node_modules/hyper-svc/node_modules/bare-os/lib/errors.js"},"/node_modules/hyper-svc/node_modules/bare-os/lib/constants.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-os/package.json","../binding":"/node_modules/hyper-svc/node_modules/bare-os/binding.js"},"/node_modules/hyper-svc/node_modules/bare-os/lib/errors.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-os/package.json"},"/node_modules/hyper-svc/node_modules/bare-os/package.json":{},"/node_modules/hyper-svc/node_modules/bare-path/index.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-path/package.json","./lib/posix":"/node_modules/hyper-svc/node_modules/bare-path/lib/posix.js","./lib/win32":"/node_modules/hyper-svc/node_modules/bare-path/lib/win32.js"},"/node_modules/hyper-svc/node_modules/bare-path/lib/constants.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-path/package.json"},"/node_modules/hyper-svc/node_modules/bare-path/lib/posix.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-path/package.json","./constants":"/node_modules/hyper-svc/node_modules/bare-path/lib/constants.js","./shared":"/node_modules/hyper-svc/node_modules/bare-path/lib/shared.js","./win32":"/node_modules/hyper-svc/node_modules/bare-path/lib/win32.js","bare-os":"/node_modules/hyper-svc/node_modules/bare-os/index.js"},"/node_modules/hyper-svc/node_modules/bare-path/lib/shared.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-path/package.json","./constants":"/node_modules/hyper-svc/node_modules/bare-path/lib/constants.js"},"/node_modules/hyper-svc/node_modules/bare-path/lib/win32.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-path/package.json","./constants":"/node_modules/hyper-svc/node_modules/bare-path/lib/constants.js","./posix":"/node_modules/hyper-svc/node_modules/bare-path/lib/posix.js","./shared":"/node_modules/hyper-svc/node_modules/bare-path/lib/shared.js","bare-os":"/node_modules/hyper-svc/node_modules/bare-os/index.js"},"/node_modules/hyper-svc/node_modules/bare-path/package.json":{},"/node_modules/hyper-svc/node_modules/bare-pipe/binding.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-pipe/package.json",".":"linked:libbare-pipe.4.1.5.so"},"/node_modules/hyper-svc/node_modules/bare-pipe/index.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-pipe/package.json","./binding":"/node_modules/hyper-svc/node_modules/bare-pipe/binding.js","./lib/constants":"/node_modules/hyper-svc/node_modules/bare-pipe/lib/constants.js","./lib/errors":"/node_modules/hyper-svc/node_modules/bare-pipe/lib/errors.js","bare-events":"/node_modules/hyper-svc/node_modules/bare-events/index.js","bare-stream":"/node_modules/hyper-svc/node_modules/bare-stream/index.js"},"/node_modules/hyper-svc/node_modules/bare-pipe/lib/constants.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-pipe/package.json"},"/node_modules/hyper-svc/node_modules/bare-pipe/lib/errors.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-pipe/package.json"},"/node_modules/hyper-svc/node_modules/bare-pipe/package.json":{},"/node_modules/hyper-svc/node_modules/bare-process/index.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-process/package.json","bare-abort":"/node_modules/hyper-svc/node_modules/bare-abort/index.js","bare-env":"/node_modules/hyper-svc/node_modules/bare-env/index.js","bare-events":"/node_modules/hyper-svc/node_modules/bare-events/index.js","bare-hrtime":"/node_modules/hyper-svc/node_modules/bare-hrtime/index.js","bare-os":"/node_modules/hyper-svc/node_modules/bare-os/index.js","bare-signals":"/node_modules/hyper-svc/node_modules/bare-signals/index.js","bare-stdio":"/node_modules/hyper-svc/node_modules/bare-stdio/index.js"},"/node_modules/hyper-svc/node_modules/bare-process/package.json":{},"/node_modules/hyper-svc/node_modules/bare-signals/binding.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-signals/package.json",".":"linked:libbare-signals.4.2.0.so"},"/node_modules/hyper-svc/node_modules/bare-signals/index.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-signals/package.json","./binding":"/node_modules/hyper-svc/node_modules/bare-signals/binding.js","./lib/emitter":"/node_modules/hyper-svc/node_modules/bare-signals/lib/emitter.js","./lib/errors":"/node_modules/hyper-svc/node_modules/bare-signals/lib/errors.js","bare-events":"/node_modules/hyper-svc/node_modules/bare-events/index.js","bare-os":"/node_modules/hyper-svc/node_modules/bare-os/index.js"},"/node_modules/hyper-svc/node_modules/bare-signals/lib/emitter.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-signals/package.json","..":"/node_modules/hyper-svc/node_modules/bare-signals/index.js","bare-events":"/node_modules/hyper-svc/node_modules/bare-events/index.js"},"/node_modules/hyper-svc/node_modules/bare-signals/lib/errors.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-signals/package.json"},"/node_modules/hyper-svc/node_modules/bare-signals/package.json":{},"/node_modules/hyper-svc/node_modules/bare-stdio/binding.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-stdio/package.json",".":"linked:libbare-stdio.1.0.2.so"},"/node_modules/hyper-svc/node_modules/bare-stdio/index.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-stdio/package.json","./binding":"/node_modules/hyper-svc/node_modules/bare-stdio/binding.js","bare-fs":"/node_modules/hyper-svc/node_modules/bare-fs/index.js","bare-pipe":"/node_modules/hyper-svc/node_modules/bare-pipe/index.js","bare-tty":"/node_modules/hyper-svc/node_modules/bare-tty/index.js"},"/node_modules/hyper-svc/node_modules/bare-stdio/package.json":{},"/node_modules/hyper-svc/node_modules/bare-stream/index.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-stream/package.json","./web":"/node_modules/hyper-svc/node_modules/bare-stream/web.js","streamx":"/node_modules/hyper-svc/node_modules/streamx/index.js"},"/node_modules/hyper-svc/node_modules/bare-stream/package.json":{},"/node_modules/hyper-svc/node_modules/bare-stream/web.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-stream/package.json","streamx":"/node_modules/hyper-svc/node_modules/streamx/index.js","teex":"/node_modules/hyper-svc/node_modules/teex/index.js"},"/node_modules/hyper-svc/node_modules/bare-tcp/binding.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-tcp/package.json",".":"linked:libbare-tcp.2.2.12.so"},"/node_modules/hyper-svc/node_modules/bare-tcp/index.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-tcp/package.json","./binding":"/node_modules/hyper-svc/node_modules/bare-tcp/binding.js","./lib/constants":"/node_modules/hyper-svc/node_modules/bare-tcp/lib/constants.js","./lib/errors":"/node_modules/hyper-svc/node_modules/bare-tcp/lib/errors.js","./lib/ip":"/node_modules/hyper-svc/node_modules/bare-tcp/lib/ip.js","bare-dns":"/node_modules/hyper-svc/node_modules/bare-dns/index.js","bare-events":"/node_modules/hyper-svc/node_modules/bare-events/index.js","bare-stream":"/node_modules/hyper-svc/node_modules/bare-stream/index.js"},"/node_modules/hyper-svc/node_modules/bare-tcp/lib/constants.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-tcp/package.json"},"/node_modules/hyper-svc/node_modules/bare-tcp/lib/errors.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-tcp/package.json"},"/node_modules/hyper-svc/node_modules/bare-tcp/lib/ip.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-tcp/package.json"},"/node_modules/hyper-svc/node_modules/bare-tcp/package.json":{},"/node_modules/hyper-svc/node_modules/bare-tty/binding.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-tty/package.json",".":"linked:libbare-tty.5.1.0.so"},"/node_modules/hyper-svc/node_modules/bare-tty/index.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-tty/package.json","./binding":"/node_modules/hyper-svc/node_modules/bare-tty/binding.js","./lib/constants":"/node_modules/hyper-svc/node_modules/bare-tty/lib/constants.js","bare-signals":"/node_modules/hyper-svc/node_modules/bare-signals/index.js","bare-stream":"/node_modules/hyper-svc/node_modules/bare-stream/index.js"},"/node_modules/hyper-svc/node_modules/bare-tty/lib/constants.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-tty/package.json","../binding":"/node_modules/hyper-svc/node_modules/bare-tty/binding.js"},"/node_modules/hyper-svc/node_modules/bare-tty/package.json":{},"/node_modules/hyper-svc/node_modules/bare-type/binding.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-type/package.json",".":"linked:libbare-type.1.1.0.so"},"/node_modules/hyper-svc/node_modules/bare-type/index.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-type/package.json","./binding":"/node_modules/hyper-svc/node_modules/bare-type/binding.js"},"/node_modules/hyper-svc/node_modules/bare-type/package.json":{},"/node_modules/hyper-svc/node_modules/bare-url/binding.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-url/package.json",".":"linked:libbare-url.2.4.2.so"},"/node_modules/hyper-svc/node_modules/bare-url/index.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-url/package.json","./binding":"/node_modules/hyper-svc/node_modules/bare-url/binding.js","./lib/errors":"/node_modules/hyper-svc/node_modules/bare-url/lib/errors.js","./lib/url-search-params":"/node_modules/hyper-svc/node_modules/bare-url/lib/url-search-params.js","bare-path":"/node_modules/hyper-svc/node_modules/bare-path/index.js"},"/node_modules/hyper-svc/node_modules/bare-url/lib/errors.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-url/package.json"},"/node_modules/hyper-svc/node_modules/bare-url/lib/url-search-params.js":{"#package":"/node_modules/hyper-svc/node_modules/bare-url/package.json"},"/node_modules/hyper-svc/node_modules/bare-url/package.json":{},"/node_modules/hyper-svc/node_modules/bits-to-bytes/index.js":{"#package":"/node_modules/hyper-svc/node_modules/bits-to-bytes/package.json","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-svc/node_modules/bits-to-bytes/package.json":{},"/node_modules/hyper-svc/node_modules/blind-relay/index.js":{"#package":"/node_modules/hyper-svc/node_modules/blind-relay/package.json","./lib/errors":"/node_modules/hyper-svc/node_modules/blind-relay/lib/errors.js","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js","bits-to-bytes":"/node_modules/hyper-svc/node_modules/bits-to-bytes/index.js","compact-encoding":"/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/index.js","compact-encoding-bitfield":"/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/index.js","events":"/node_modules/hyper-svc/node_modules/bare-events/index.js","protomux":"/node_modules/hyper-svc/node_modules/protomux/index.js","sodium-universal":"/node_modules/hyper-svc/node_modules/sodium-universal/index.js","streamx":"/node_modules/hyper-svc/node_modules/streamx/index.js"},"/node_modules/hyper-svc/node_modules/blind-relay/lib/errors.js":{"#package":"/node_modules/hyper-svc/node_modules/blind-relay/package.json"},"/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/package.json"},"/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/index.js":{"#package":"/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/raw.js","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/package.json"},"/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/package.json":{},"/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/endian.js","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-svc/node_modules/blind-relay/package.json":{},"/node_modules/hyper-svc/node_modules/bogon/index.js":{"#package":"/node_modules/hyper-svc/node_modules/bogon/package.json","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/index.js","compact-encoding-net":"/node_modules/hyper-svc/node_modules/compact-encoding-net/index.js"},"/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/package.json"},"/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/index.js":{"#package":"/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/raw.js","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/package.json"},"/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/package.json":{},"/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/endian.js","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-svc/node_modules/bogon/package.json":{},"/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/index.js":{"#package":"/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/package.json","compact-encoding":"/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/index.js"},"/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/package.json"},"/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/index.js":{"#package":"/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/raw.js","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/package.json"},"/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/package.json":{},"/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/endian.js","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/package.json":{},"/node_modules/hyper-svc/node_modules/compact-encoding-net/index.js":{"#package":"/node_modules/hyper-svc/node_modules/compact-encoding-net/package.json","compact-encoding":"/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/index.js"},"/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/package.json"},"/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/index.js":{"#package":"/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/raw.js","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/package.json"},"/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/package.json":{},"/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/endian.js","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-svc/node_modules/compact-encoding-net/package.json":{},"/node_modules/hyper-svc/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/hyper-svc/node_modules/compact-encoding/package.json"},"/node_modules/hyper-svc/node_modules/compact-encoding/index.js":{"#package":"/node_modules/hyper-svc/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-svc/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/hyper-svc/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/hyper-svc/node_modules/compact-encoding/raw.js","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-svc/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/hyper-svc/node_modules/compact-encoding/package.json"},"/node_modules/hyper-svc/node_modules/compact-encoding/package.json":{},"/node_modules/hyper-svc/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/hyper-svc/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-svc/node_modules/compact-encoding/endian.js","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-svc/node_modules/dht-rpc/index.js":{"#package":"/node_modules/hyper-svc/node_modules/dht-rpc/package.json","./lib/commands":"/node_modules/hyper-svc/node_modules/dht-rpc/lib/commands.js","./lib/errors":"/node_modules/hyper-svc/node_modules/dht-rpc/lib/errors.js","./lib/health":"/node_modules/hyper-svc/node_modules/dht-rpc/lib/health.js","./lib/io":"/node_modules/hyper-svc/node_modules/dht-rpc/lib/io.js","./lib/peer":"/node_modules/hyper-svc/node_modules/dht-rpc/lib/peer.js","./lib/query":"/node_modules/hyper-svc/node_modules/dht-rpc/lib/query.js","./lib/session":"/node_modules/hyper-svc/node_modules/dht-rpc/lib/session.js","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/index.js","events":"/node_modules/hyper-svc/node_modules/bare-events/index.js","kademlia-routing-table":"/node_modules/hyper-svc/node_modules/kademlia-routing-table/index.js","nat-sampler":"/node_modules/hyper-svc/node_modules/nat-sampler/index.js","sodium-universal":"/node_modules/hyper-svc/node_modules/sodium-universal/index.js","time-ordered-set":"/node_modules/hyper-svc/node_modules/time-ordered-set/index.js","udx-native":"/node_modules/hyper-svc/node_modules/udx-native/lib/udx.js"},"/node_modules/hyper-svc/node_modules/dht-rpc/lib/commands.js":{"#package":"/node_modules/hyper-svc/node_modules/dht-rpc/package.json"},"/node_modules/hyper-svc/node_modules/dht-rpc/lib/errors.js":{"#package":"/node_modules/hyper-svc/node_modules/dht-rpc/package.json"},"/node_modules/hyper-svc/node_modules/dht-rpc/lib/health.js":{"#package":"/node_modules/hyper-svc/node_modules/dht-rpc/package.json"},"/node_modules/hyper-svc/node_modules/dht-rpc/lib/io.js":{"#package":"/node_modules/hyper-svc/node_modules/dht-rpc/package.json","./errors":"/node_modules/hyper-svc/node_modules/dht-rpc/lib/errors.js","./peer":"/node_modules/hyper-svc/node_modules/dht-rpc/lib/peer.js","adaptive-timeout":"/node_modules/hyper-svc/node_modules/adaptive-timeout/index.js","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/index.js","fast-fifo":"/node_modules/hyper-svc/node_modules/fast-fifo/index.js","sodium-universal":"/node_modules/hyper-svc/node_modules/sodium-universal/index.js"},"/node_modules/hyper-svc/node_modules/dht-rpc/lib/peer.js":{"#package":"/node_modules/hyper-svc/node_modules/dht-rpc/package.json","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/index.js","compact-encoding-net":"/node_modules/hyper-svc/node_modules/compact-encoding-net/index.js","sodium-universal":"/node_modules/hyper-svc/node_modules/sodium-universal/index.js"},"/node_modules/hyper-svc/node_modules/dht-rpc/lib/query.js":{"#package":"/node_modules/hyper-svc/node_modules/dht-rpc/package.json","./commands":"/node_modules/hyper-svc/node_modules/dht-rpc/lib/commands.js","./peer":"/node_modules/hyper-svc/node_modules/dht-rpc/lib/peer.js","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js","streamx":"/node_modules/hyper-svc/node_modules/streamx/index.js"},"/node_modules/hyper-svc/node_modules/dht-rpc/lib/session.js":{"#package":"/node_modules/hyper-svc/node_modules/dht-rpc/package.json"},"/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/package.json"},"/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/index.js":{"#package":"/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/raw.js","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/package.json"},"/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/package.json":{},"/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/endian.js","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-svc/node_modules/dht-rpc/package.json":{},"/node_modules/hyper-svc/node_modules/events-universal/bare.js":{"#package":"/node_modules/hyper-svc/node_modules/events-universal/package.json","bare-events":"/node_modules/hyper-svc/node_modules/bare-events/index.js"},"/node_modules/hyper-svc/node_modules/events-universal/package.json":{},"/node_modules/hyper-svc/node_modules/fast-fifo/fixed-size.js":{"#package":"/node_modules/hyper-svc/node_modules/fast-fifo/package.json"},"/node_modules/hyper-svc/node_modules/fast-fifo/index.js":{"#package":"/node_modules/hyper-svc/node_modules/fast-fifo/package.json","./fixed-size":"/node_modules/hyper-svc/node_modules/fast-fifo/fixed-size.js"},"/node_modules/hyper-svc/node_modules/fast-fifo/package.json":{},"/node_modules/hyper-svc/node_modules/hypercore-crypto/index.js":{"#package":"/node_modules/hyper-svc/node_modules/hypercore-crypto/package.json","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/index.js","sodium-universal":"/node_modules/hyper-svc/node_modules/sodium-universal/index.js"},"/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/package.json"},"/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/index.js":{"#package":"/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/raw.js","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/package.json"},"/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/package.json":{},"/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/endian.js","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-svc/node_modules/hypercore-crypto/package.json":{},"/node_modules/hyper-svc/node_modules/hypercore-id-encoding/index.js":{"#package":"/node_modules/hyper-svc/node_modules/hypercore-id-encoding/package.json","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js","z32":"/node_modules/hyper-svc/node_modules/z32/index.js"},"/node_modules/hyper-svc/node_modules/hypercore-id-encoding/package.json":{},"/node_modules/hyper-svc/node_modules/hyperdht-address/index.js":{"#package":"/node_modules/hyper-svc/node_modules/hyperdht-address/package.json","./spec/hyperschema":"/node_modules/hyper-svc/node_modules/hyperdht-address/spec/hyperschema/index.js","compact-encoding":"/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/index.js"},"/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/package.json"},"/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/index.js":{"#package":"/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/raw.js","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/package.json"},"/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/package.json":{},"/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/endian.js","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-svc/node_modules/hyperdht-address/package.json":{},"/node_modules/hyper-svc/node_modules/hyperdht-address/spec/hyperschema/index.js":{"#package":"/node_modules/hyper-svc/node_modules/hyperdht-address/package.json","hyperschema/runtime":"/node_modules/hyper-svc/node_modules/hyperschema/runtime.cjs"},"/node_modules/hyper-svc/node_modules/hyperdht/index.js":{"#package":"/node_modules/hyper-svc/node_modules/hyperdht/package.json","./lib/connect":"/node_modules/hyper-svc/node_modules/hyperdht/lib/connect.js","./lib/connection-pool":"/node_modules/hyper-svc/node_modules/hyperdht/lib/connection-pool.js","./lib/constants":"/node_modules/hyper-svc/node_modules/hyperdht/lib/constants.js","./lib/crypto":"/node_modules/hyper-svc/node_modules/hyperdht/lib/crypto.js","./lib/errors":"/node_modules/hyper-svc/node_modules/hyperdht/lib/errors.js","./lib/messages":"/node_modules/hyper-svc/node_modules/hyperdht/lib/messages.js","./lib/persistent":"/node_modules/hyper-svc/node_modules/hyperdht/lib/persistent.js","./lib/raw-stream-set":"/node_modules/hyper-svc/node_modules/hyperdht/lib/raw-stream-set.js","./lib/router":"/node_modules/hyper-svc/node_modules/hyperdht/lib/router.js","./lib/server":"/node_modules/hyper-svc/node_modules/hyperdht/lib/server.js","./lib/socket-pool":"/node_modules/hyper-svc/node_modules/hyperdht/lib/socket-pool.js","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/index.js","dht-rpc":"/node_modules/hyper-svc/node_modules/dht-rpc/index.js","safety-catch":"/node_modules/hyper-svc/node_modules/safety-catch/index.js","sodium-universal":"/node_modules/hyper-svc/node_modules/sodium-universal/index.js","xache":"/node_modules/hyper-svc/node_modules/xache/index.js"},"/node_modules/hyper-svc/node_modules/hyperdht/lib/announcer.js":{"#package":"/node_modules/hyper-svc/node_modules/hyperdht/package.json","./constants":"/node_modules/hyper-svc/node_modules/hyperdht/lib/constants.js","./encode":"/node_modules/hyper-svc/node_modules/hyperdht/lib/encode.js","./messages":"/node_modules/hyper-svc/node_modules/hyperdht/lib/messages.js","./persistent":"/node_modules/hyper-svc/node_modules/hyperdht/lib/persistent.js","./sleeper":"/node_modules/hyper-svc/node_modules/hyperdht/lib/sleeper.js","compact-encoding":"/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/index.js","safety-catch":"/node_modules/hyper-svc/node_modules/safety-catch/index.js","signal-promise":"/node_modules/hyper-svc/node_modules/signal-promise/index.js"},"/node_modules/hyper-svc/node_modules/hyperdht/lib/connect.js":{"#package":"/node_modules/hyper-svc/node_modules/hyperdht/package.json","./constants":"/node_modules/hyper-svc/node_modules/hyperdht/lib/constants.js","./crypto":"/node_modules/hyper-svc/node_modules/hyperdht/lib/crypto.js","./errors":"/node_modules/hyper-svc/node_modules/hyperdht/lib/errors.js","./holepuncher":"/node_modules/hyper-svc/node_modules/hyperdht/lib/holepuncher.js","./noise-wrap":"/node_modules/hyper-svc/node_modules/hyperdht/lib/noise-wrap.js","./secure-payload":"/node_modules/hyper-svc/node_modules/hyperdht/lib/secure-payload.js","./semaphore":"/node_modules/hyper-svc/node_modules/hyperdht/lib/semaphore.js","./sleeper":"/node_modules/hyper-svc/node_modules/hyperdht/lib/sleeper.js","@hyperswarm/secret-stream":"/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/index.js","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js","blind-relay":"/node_modules/hyper-svc/node_modules/blind-relay/index.js","bogon":"/node_modules/hyper-svc/node_modules/bogon/index.js","hypercore-id-encoding":"/node_modules/hyper-svc/node_modules/hypercore-id-encoding/index.js","hyperdht-address":"/node_modules/hyper-svc/node_modules/hyperdht-address/index.js","safety-catch":"/node_modules/hyper-svc/node_modules/safety-catch/index.js","unslab":"/node_modules/hyper-svc/node_modules/unslab/index.js"},"/node_modules/hyper-svc/node_modules/hyperdht/lib/connection-pool.js":{"#package":"/node_modules/hyper-svc/node_modules/hyperdht/package.json","./errors":"/node_modules/hyper-svc/node_modules/hyperdht/lib/errors.js","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js","events":"/node_modules/hyper-svc/node_modules/bare-events/index.js"},"/node_modules/hyper-svc/node_modules/hyperdht/lib/constants.js":{"#package":"/node_modules/hyper-svc/node_modules/hyperdht/package.json","hypercore-crypto":"/node_modules/hyper-svc/node_modules/hypercore-crypto/index.js"},"/node_modules/hyper-svc/node_modules/hyperdht/lib/crypto.js":{"#package":"/node_modules/hyper-svc/node_modules/hyperdht/package.json","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js","sodium-universal":"/node_modules/hyper-svc/node_modules/sodium-universal/index.js"},"/node_modules/hyper-svc/node_modules/hyperdht/lib/encode.js":{"#package":"/node_modules/hyper-svc/node_modules/hyperdht/package.json","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/index.js"},"/node_modules/hyper-svc/node_modules/hyperdht/lib/errors.js":{"#package":"/node_modules/hyper-svc/node_modules/hyperdht/package.json"},"/node_modules/hyper-svc/node_modules/hyperdht/lib/holepuncher.js":{"#package":"/node_modules/hyper-svc/node_modules/hyperdht/package.json","./constants":"/node_modules/hyper-svc/node_modules/hyperdht/lib/constants.js","./nat":"/node_modules/hyper-svc/node_modules/hyperdht/lib/nat.js","./sleeper":"/node_modules/hyper-svc/node_modules/hyperdht/lib/sleeper.js","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-svc/node_modules/hyperdht/lib/messages.js":{"#package":"/node_modules/hyper-svc/node_modules/hyperdht/package.json","compact-encoding":"/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/index.js"},"/node_modules/hyper-svc/node_modules/hyperdht/lib/nat.js":{"#package":"/node_modules/hyper-svc/node_modules/hyperdht/package.json","../lib/constants":"/node_modules/hyper-svc/node_modules/hyperdht/lib/constants.js"},"/node_modules/hyper-svc/node_modules/hyperdht/lib/noise-wrap.js":{"#package":"/node_modules/hyper-svc/node_modules/hyperdht/package.json","./constants":"/node_modules/hyper-svc/node_modules/hyperdht/lib/constants.js","./errors":"/node_modules/hyper-svc/node_modules/hyperdht/lib/errors.js","./messages":"/node_modules/hyper-svc/node_modules/hyperdht/lib/messages.js","@hyperswarm/secret-stream":"/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/index.js","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/index.js","noise-curve-ed":"/node_modules/hyper-svc/node_modules/noise-curve-ed/index.js","noise-handshake":"/node_modules/hyper-svc/node_modules/noise-handshake/noise.js","sodium-universal":"/node_modules/hyper-svc/node_modules/sodium-universal/index.js"},"/node_modules/hyper-svc/node_modules/hyperdht/lib/persistent.js":{"#package":"/node_modules/hyper-svc/node_modules/hyperdht/package.json","./constants":"/node_modules/hyper-svc/node_modules/hyperdht/lib/constants.js","./encode":"/node_modules/hyper-svc/node_modules/hyperdht/lib/encode.js","./messages":"/node_modules/hyper-svc/node_modules/hyperdht/lib/messages.js","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/index.js","record-cache":"/node_modules/hyper-svc/node_modules/record-cache/index.js","sodium-universal":"/node_modules/hyper-svc/node_modules/sodium-universal/index.js","unslab":"/node_modules/hyper-svc/node_modules/unslab/index.js","xache":"/node_modules/hyper-svc/node_modules/xache/index.js"},"/node_modules/hyper-svc/node_modules/hyperdht/lib/raw-stream-set.js":{"#package":"/node_modules/hyper-svc/node_modules/hyperdht/package.json"},"/node_modules/hyper-svc/node_modules/hyperdht/lib/router.js":{"#package":"/node_modules/hyper-svc/node_modules/hyperdht/package.json","./constants":"/node_modules/hyper-svc/node_modules/hyperdht/lib/constants.js","./errors":"/node_modules/hyper-svc/node_modules/hyperdht/lib/errors.js","./messages":"/node_modules/hyper-svc/node_modules/hyperdht/lib/messages.js","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/index.js","safety-catch":"/node_modules/hyper-svc/node_modules/safety-catch/index.js","xache":"/node_modules/hyper-svc/node_modules/xache/index.js"},"/node_modules/hyper-svc/node_modules/hyperdht/lib/secure-payload.js":{"#package":"/node_modules/hyper-svc/node_modules/hyperdht/package.json","./messages":"/node_modules/hyper-svc/node_modules/hyperdht/lib/messages.js","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js","sodium-universal":"/node_modules/hyper-svc/node_modules/sodium-universal/index.js"},"/node_modules/hyper-svc/node_modules/hyperdht/lib/semaphore.js":{"#package":"/node_modules/hyper-svc/node_modules/hyperdht/package.json"},"/node_modules/hyper-svc/node_modules/hyperdht/lib/server.js":{"#package":"/node_modules/hyper-svc/node_modules/hyperdht/package.json","./announcer":"/node_modules/hyper-svc/node_modules/hyperdht/lib/announcer.js","./constants":"/node_modules/hyper-svc/node_modules/hyperdht/lib/constants.js","./crypto":"/node_modules/hyper-svc/node_modules/hyperdht/lib/crypto.js","./errors":"/node_modules/hyper-svc/node_modules/hyperdht/lib/errors.js","./holepuncher":"/node_modules/hyper-svc/node_modules/hyperdht/lib/holepuncher.js","./noise-wrap":"/node_modules/hyper-svc/node_modules/hyperdht/lib/noise-wrap.js","./secure-payload":"/node_modules/hyper-svc/node_modules/hyperdht/lib/secure-payload.js","@hyperswarm/secret-stream":"/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/index.js","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js","blind-relay":"/node_modules/hyper-svc/node_modules/blind-relay/index.js","bogon":"/node_modules/hyper-svc/node_modules/bogon/index.js","events":"/node_modules/hyper-svc/node_modules/bare-events/index.js","safety-catch":"/node_modules/hyper-svc/node_modules/safety-catch/index.js"},"/node_modules/hyper-svc/node_modules/hyperdht/lib/sleeper.js":{"#package":"/node_modules/hyper-svc/node_modules/hyperdht/package.json"},"/node_modules/hyper-svc/node_modules/hyperdht/lib/socket-pool.js":{"#package":"/node_modules/hyper-svc/node_modules/hyperdht/package.json","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/package.json"},"/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/index.js":{"#package":"/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/raw.js","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/package.json"},"/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/package.json":{},"/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/endian.js","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-svc/node_modules/hyperdht/package.json":{},"/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/package.json"},"/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/index.js":{"#package":"/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/raw.js","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/package.json"},"/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/package.json":{},"/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/package.json","./endian":"/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/endian.js","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-svc/node_modules/hyperschema/package.json":{},"/node_modules/hyper-svc/node_modules/hyperschema/runtime.cjs":{"#package":"/node_modules/hyper-svc/node_modules/hyperschema/package.json","compact-encoding":"/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/index.js"},"/node_modules/hyper-svc/node_modules/hyperswarm/index.js":{"#package":"/node_modules/hyper-svc/node_modules/hyperswarm/package.json","./lib/connection-set":"/node_modules/hyper-svc/node_modules/hyperswarm/lib/connection-set.js","./lib/peer-discovery":"/node_modules/hyper-svc/node_modules/hyperswarm/lib/peer-discovery.js","./lib/peer-info":"/node_modules/hyper-svc/node_modules/hyperswarm/lib/peer-info.js","./lib/retry-timer":"/node_modules/hyper-svc/node_modules/hyperswarm/lib/retry-timer.js","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js","events":"/node_modules/hyper-svc/node_modules/bare-events/index.js","hyperdht":"/node_modules/hyper-svc/node_modules/hyperdht/index.js","shuffled-priority-queue":"/node_modules/hyper-svc/node_modules/shuffled-priority-queue/index.js","streamx":"/node_modules/hyper-svc/node_modules/streamx/index.js","unslab":"/node_modules/hyper-svc/node_modules/unslab/index.js"},"/node_modules/hyper-svc/node_modules/hyperswarm/lib/bulk-timer.js":{"#package":"/node_modules/hyper-svc/node_modules/hyperswarm/package.json"},"/node_modules/hyper-svc/node_modules/hyperswarm/lib/connection-set.js":{"#package":"/node_modules/hyper-svc/node_modules/hyperswarm/package.json","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-svc/node_modules/hyperswarm/lib/peer-discovery.js":{"#package":"/node_modules/hyper-svc/node_modules/hyperswarm/package.json","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js","safety-catch":"/node_modules/hyper-svc/node_modules/safety-catch/index.js"},"/node_modules/hyper-svc/node_modules/hyperswarm/lib/peer-info.js":{"#package":"/node_modules/hyper-svc/node_modules/hyperswarm/package.json","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js","events":"/node_modules/hyper-svc/node_modules/bare-events/index.js","unslab":"/node_modules/hyper-svc/node_modules/unslab/index.js"},"/node_modules/hyper-svc/node_modules/hyperswarm/lib/retry-timer.js":{"#package":"/node_modules/hyper-svc/node_modules/hyperswarm/package.json","./bulk-timer":"/node_modules/hyper-svc/node_modules/hyperswarm/lib/bulk-timer.js"},"/node_modules/hyper-svc/node_modules/hyperswarm/package.json":{},"/node_modules/hyper-svc/node_modules/kademlia-routing-table/index.js":{"#package":"/node_modules/hyper-svc/node_modules/kademlia-routing-table/package.json","events":"/node_modules/hyper-svc/node_modules/bare-events/index.js"},"/node_modules/hyper-svc/node_modules/kademlia-routing-table/package.json":{},"/node_modules/hyper-svc/node_modules/nanoassert/index.js":{"#package":"/node_modules/hyper-svc/node_modules/nanoassert/package.json"},"/node_modules/hyper-svc/node_modules/nanoassert/package.json":{},"/node_modules/hyper-svc/node_modules/nat-sampler/index.js":{"#package":"/node_modules/hyper-svc/node_modules/nat-sampler/package.json"},"/node_modules/hyper-svc/node_modules/nat-sampler/package.json":{},"/node_modules/hyper-svc/node_modules/noise-curve-ed/index.js":{"#package":"/node_modules/hyper-svc/node_modules/noise-curve-ed/package.json","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js","nanoassert":"/node_modules/hyper-svc/node_modules/nanoassert/index.js","sodium-universal":"/node_modules/hyper-svc/node_modules/sodium-universal/index.js"},"/node_modules/hyper-svc/node_modules/noise-curve-ed/package.json":{},"/node_modules/hyper-svc/node_modules/noise-handshake/cipher.js":{"#package":"/node_modules/hyper-svc/node_modules/noise-handshake/package.json","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js","sodium-universal":"/node_modules/hyper-svc/node_modules/sodium-universal/index.js"},"/node_modules/hyper-svc/node_modules/noise-handshake/dh.js":{"#package":"/node_modules/hyper-svc/node_modules/noise-handshake/package.json","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js","nanoassert":"/node_modules/hyper-svc/node_modules/nanoassert/index.js","sodium-universal":"/node_modules/hyper-svc/node_modules/sodium-universal/index.js"},"/node_modules/hyper-svc/node_modules/noise-handshake/hkdf.js":{"#package":"/node_modules/hyper-svc/node_modules/noise-handshake/package.json","./hmac":"/node_modules/hyper-svc/node_modules/noise-handshake/hmac.js","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-svc/node_modules/noise-handshake/hmac.js":{"#package":"/node_modules/hyper-svc/node_modules/noise-handshake/package.json","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js","sodium-universal":"/node_modules/hyper-svc/node_modules/sodium-universal/index.js"},"/node_modules/hyper-svc/node_modules/noise-handshake/noise.js":{"#package":"/node_modules/hyper-svc/node_modules/noise-handshake/package.json","./hkdf":"/node_modules/hyper-svc/node_modules/noise-handshake/hkdf.js","./symmetric-state":"/node_modules/hyper-svc/node_modules/noise-handshake/symmetric-state.js","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js","nanoassert":"/node_modules/hyper-svc/node_modules/nanoassert/index.js"},"/node_modules/hyper-svc/node_modules/noise-handshake/package.json":{},"/node_modules/hyper-svc/node_modules/noise-handshake/symmetric-state.js":{"#package":"/node_modules/hyper-svc/node_modules/noise-handshake/package.json","./cipher":"/node_modules/hyper-svc/node_modules/noise-handshake/cipher.js","./dh":"/node_modules/hyper-svc/node_modules/noise-handshake/dh.js","./hkdf":"/node_modules/hyper-svc/node_modules/noise-handshake/hkdf.js","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js","nanoassert":"/node_modules/hyper-svc/node_modules/nanoassert/index.js","sodium-universal":"/node_modules/hyper-svc/node_modules/sodium-universal/index.js"},"/node_modules/hyper-svc/node_modules/protomux/index.js":{"#package":"/node_modules/hyper-svc/node_modules/protomux/package.json","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js","compact-encoding":"/node_modules/hyper-svc/node_modules/compact-encoding/index.js","queue-tick":"/node_modules/hyper-svc/node_modules/queue-tick/process-next-tick.js","safety-catch":"/node_modules/hyper-svc/node_modules/safety-catch/index.js","unslab":"/node_modules/hyper-svc/node_modules/unslab/index.js"},"/node_modules/hyper-svc/node_modules/protomux/package.json":{},"/node_modules/hyper-svc/node_modules/queue-tick/package.json":{},"/node_modules/hyper-svc/node_modules/queue-tick/process-next-tick.js":{"#package":"/node_modules/hyper-svc/node_modules/queue-tick/package.json","./queue-microtask":"/node_modules/hyper-svc/node_modules/queue-tick/queue-microtask.js"},"/node_modules/hyper-svc/node_modules/queue-tick/queue-microtask.js":{"#package":"/node_modules/hyper-svc/node_modules/queue-tick/package.json"},"/node_modules/hyper-svc/node_modules/ready-resource/index.js":{"#package":"/node_modules/hyper-svc/node_modules/ready-resource/package.json","events":"/node_modules/hyper-svc/node_modules/bare-events/index.js"},"/node_modules/hyper-svc/node_modules/ready-resource/package.json":{},"/node_modules/hyper-svc/node_modules/record-cache/index.js":{"#package":"/node_modules/hyper-svc/node_modules/record-cache/package.json","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-svc/node_modules/record-cache/package.json":{},"/node_modules/hyper-svc/node_modules/require-addon/lib/bare.js":{"#package":"/node_modules/hyper-svc/node_modules/require-addon/package.json"},"/node_modules/hyper-svc/node_modules/require-addon/package.json":{},"/node_modules/hyper-svc/node_modules/safety-catch/index.js":{"#package":"/node_modules/hyper-svc/node_modules/safety-catch/package.json"},"/node_modules/hyper-svc/node_modules/safety-catch/package.json":{},"/node_modules/hyper-svc/node_modules/shuffled-priority-queue/index.js":{"#package":"/node_modules/hyper-svc/node_modules/shuffled-priority-queue/package.json","unordered-set":"/node_modules/hyper-svc/node_modules/unordered-set/index.js"},"/node_modules/hyper-svc/node_modules/shuffled-priority-queue/package.json":{},"/node_modules/hyper-svc/node_modules/signal-promise/index.js":{"#package":"/node_modules/hyper-svc/node_modules/signal-promise/package.json"},"/node_modules/hyper-svc/node_modules/signal-promise/package.json":{},"/node_modules/hyper-svc/node_modules/sodium-native/binding.js":{"#package":"/node_modules/hyper-svc/node_modules/sodium-native/package.json",".":"linked:libsodium-native.5.1.0.so","require-addon":"/node_modules/hyper-svc/node_modules/require-addon/lib/bare.js"},"/node_modules/hyper-svc/node_modules/sodium-native/index.js":{"#package":"/node_modules/hyper-svc/node_modules/sodium-native/package.json","./binding":"/node_modules/hyper-svc/node_modules/sodium-native/binding.js","assert":"/node_modules/hyper-svc/node_modules/bare-assert/index.js","which-runtime":"/node_modules/hyper-svc/node_modules/which-runtime/index.js"},"/node_modules/hyper-svc/node_modules/sodium-native/package.json":{},"/node_modules/hyper-svc/node_modules/sodium-secretstream/index.js":{"#package":"/node_modules/hyper-svc/node_modules/sodium-secretstream/package.json","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js","sodium-universal":"/node_modules/hyper-svc/node_modules/sodium-universal/index.js"},"/node_modules/hyper-svc/node_modules/sodium-secretstream/package.json":{},"/node_modules/hyper-svc/node_modules/sodium-universal/index.js":{"#package":"/node_modules/hyper-svc/node_modules/sodium-universal/package.json","sodium-native":"/node_modules/hyper-svc/node_modules/sodium-native/index.js"},"/node_modules/hyper-svc/node_modules/sodium-universal/package.json":{},"/node_modules/hyper-svc/node_modules/streamx/index.js":{"#package":"/node_modules/hyper-svc/node_modules/streamx/package.json","events-universal":"/node_modules/hyper-svc/node_modules/events-universal/bare.js","fast-fifo":"/node_modules/hyper-svc/node_modules/fast-fifo/index.js","text-decoder":"/node_modules/hyper-svc/node_modules/text-decoder/index.js"},"/node_modules/hyper-svc/node_modules/streamx/package.json":{},"/node_modules/hyper-svc/node_modules/teex/index.js":{"#package":"/node_modules/hyper-svc/node_modules/teex/package.json","streamx":"/node_modules/hyper-svc/node_modules/streamx/index.js"},"/node_modules/hyper-svc/node_modules/teex/package.json":{},"/node_modules/hyper-svc/node_modules/text-decoder/index.js":{"#package":"/node_modules/hyper-svc/node_modules/text-decoder/package.json","./lib/pass-through-decoder":"/node_modules/hyper-svc/node_modules/text-decoder/lib/pass-through-decoder.js","./lib/utf8-decoder":"/node_modules/hyper-svc/node_modules/text-decoder/lib/utf8-decoder.js"},"/node_modules/hyper-svc/node_modules/text-decoder/lib/pass-through-decoder.js":{"#package":"/node_modules/hyper-svc/node_modules/text-decoder/package.json","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-svc/node_modules/text-decoder/lib/utf8-decoder.js":{"#package":"/node_modules/hyper-svc/node_modules/text-decoder/package.json","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-svc/node_modules/text-decoder/package.json":{},"/node_modules/hyper-svc/node_modules/time-ordered-set/index.js":{"#package":"/node_modules/hyper-svc/node_modules/time-ordered-set/package.json"},"/node_modules/hyper-svc/node_modules/time-ordered-set/package.json":{},"/node_modules/hyper-svc/node_modules/timeout-refresh/browser.js":{"#package":"/node_modules/hyper-svc/node_modules/timeout-refresh/package.json"},"/node_modules/hyper-svc/node_modules/timeout-refresh/index.js":{"#package":"/node_modules/hyper-svc/node_modules/timeout-refresh/package.json","./browser":"/node_modules/hyper-svc/node_modules/timeout-refresh/browser.js","./node":"/node_modules/hyper-svc/node_modules/timeout-refresh/node.js"},"/node_modules/hyper-svc/node_modules/timeout-refresh/node.js":{"#package":"/node_modules/hyper-svc/node_modules/timeout-refresh/package.json"},"/node_modules/hyper-svc/node_modules/timeout-refresh/package.json":{},"/node_modules/hyper-svc/node_modules/udx-native/binding.js":{"#package":"/node_modules/hyper-svc/node_modules/udx-native/package.json",".":"linked:libudx-native.1.19.2.so","require-addon":"/node_modules/hyper-svc/node_modules/require-addon/lib/bare.js"},"/node_modules/hyper-svc/node_modules/udx-native/lib/ip.js":{"#package":"/node_modules/hyper-svc/node_modules/udx-native/package.json"},"/node_modules/hyper-svc/node_modules/udx-native/lib/network-interfaces.js":{"#package":"/node_modules/hyper-svc/node_modules/udx-native/package.json","../binding":"/node_modules/hyper-svc/node_modules/udx-native/binding.js","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js","events":"/node_modules/hyper-svc/node_modules/bare-events/index.js"},"/node_modules/hyper-svc/node_modules/udx-native/lib/socket.js":{"#package":"/node_modules/hyper-svc/node_modules/udx-native/package.json","../binding":"/node_modules/hyper-svc/node_modules/udx-native/binding.js","./ip":"/node_modules/hyper-svc/node_modules/udx-native/lib/ip.js","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js","events":"/node_modules/hyper-svc/node_modules/bare-events/index.js"},"/node_modules/hyper-svc/node_modules/udx-native/lib/stream.js":{"#package":"/node_modules/hyper-svc/node_modules/udx-native/package.json","../binding":"/node_modules/hyper-svc/node_modules/udx-native/binding.js","./ip":"/node_modules/hyper-svc/node_modules/udx-native/lib/ip.js","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js","streamx":"/node_modules/hyper-svc/node_modules/streamx/index.js"},"/node_modules/hyper-svc/node_modules/udx-native/lib/udx.js":{"#package":"/node_modules/hyper-svc/node_modules/udx-native/package.json","../binding":"/node_modules/hyper-svc/node_modules/udx-native/binding.js","./ip":"/node_modules/hyper-svc/node_modules/udx-native/lib/ip.js","./network-interfaces":"/node_modules/hyper-svc/node_modules/udx-native/lib/network-interfaces.js","./socket":"/node_modules/hyper-svc/node_modules/udx-native/lib/socket.js","./stream":"/node_modules/hyper-svc/node_modules/udx-native/lib/stream.js","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-svc/node_modules/udx-native/package.json":{},"/node_modules/hyper-svc/node_modules/unordered-set/index.js":{"#package":"/node_modules/hyper-svc/node_modules/unordered-set/package.json"},"/node_modules/hyper-svc/node_modules/unordered-set/package.json":{},"/node_modules/hyper-svc/node_modules/unslab/index.js":{"#package":"/node_modules/hyper-svc/node_modules/unslab/package.json","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-svc/node_modules/unslab/package.json":{},"/node_modules/hyper-svc/node_modules/which-runtime/index.js":{"#package":"/node_modules/hyper-svc/node_modules/which-runtime/package.json"},"/node_modules/hyper-svc/node_modules/which-runtime/package.json":{},"/node_modules/hyper-svc/node_modules/xache/index.js":{"#package":"/node_modules/hyper-svc/node_modules/xache/package.json"},"/node_modules/hyper-svc/node_modules/xache/package.json":{},"/node_modules/hyper-svc/node_modules/z32/index.js":{"#package":"/node_modules/hyper-svc/node_modules/z32/package.json","b4a":"/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/hyper-svc/node_modules/z32/package.json":{},"/node_modules/hyper-svc/package.json":{},"/node_modules/hypercore-crypto/index.js":{"#package":"/node_modules/hypercore-crypto/package.json","b4a":"/node_modules/b4a/index.js","compact-encoding":"/node_modules/compact-encoding/index.js","sodium-universal":"/node_modules/sodium-universal/index.js"},"/node_modules/hypercore-crypto/package.json":{},"/node_modules/pgh-runtime/index.js":{"#node:events":"/node_modules/pgh-runtime/node_modules/bare-events/index.js","#package":"/node_modules/pgh-runtime/package.json","hyper-overlay/tree":"/node_modules/pgh-runtime/node_modules/hyper-overlay/lib/tree.js"},"/node_modules/pgh-runtime/node_modules/bare-events/index.js":{"#package":"/node_modules/pgh-runtime/node_modules/bare-events/package.json","./lib/errors":"/node_modules/pgh-runtime/node_modules/bare-events/lib/errors.js"},"/node_modules/pgh-runtime/node_modules/bare-events/lib/errors.js":{"#package":"/node_modules/pgh-runtime/node_modules/bare-events/package.json"},"/node_modules/pgh-runtime/node_modules/bare-events/package.json":{},"/node_modules/pgh-runtime/node_modules/hyper-overlay/lib/tree.js":{"#fs":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-fs/index.js","#package":"/node_modules/pgh-runtime/node_modules/hyper-overlay/package.json","#path":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-path/index.js","compact-encoding":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/compact-encoding/index.js","hypercore-crypto":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/hypercore-crypto/index.js"},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/b4a/index.js":{"#package":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/b4a/package.json"},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/b4a/package.json":{},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-ansi-escapes/index.js":{"#package":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-ansi-escapes/package.json"},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-ansi-escapes/package.json":{},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-assert/index.js":{"#package":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-assert/package.json","bare-inspect":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-inspect/index.js"},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-assert/package.json":{},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-events/index.js":{"#package":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-events/package.json","./lib/errors":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-events/lib/errors.js"},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-events/lib/errors.js":{"#package":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-events/package.json"},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-events/package.json":{},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-fs/binding.js":{"#package":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-fs/package.json",".":"linked:libbare-fs.4.7.2.so"},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-fs/index.js":{"#package":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-fs/package.json","./binding":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-fs/binding.js","./lib/constants":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-fs/lib/constants.js","./lib/errors":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-fs/lib/errors.js","./promises":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-fs/promises.js","bare-events":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-events/index.js","bare-path":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-path/index.js","bare-stream":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-stream/index.js","bare-url":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-url/index.js","fast-fifo":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/fast-fifo/index.js"},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-fs/lib/constants.js":{"#package":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-fs/package.json","../binding":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-fs/binding.js"},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-fs/lib/errors.js":{"#package":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-fs/package.json","bare-os":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-os/index.js"},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-fs/package.json":{},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-fs/promises.js":{"#package":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-fs/package.json",".":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-fs/index.js","bare-events":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-events/index.js"},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-inspect/binding.js":{"#package":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-inspect/package.json",".":"linked:libbare-inspect.3.1.4.so"},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-inspect/index.js":{"#package":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-inspect/package.json","./binding":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-inspect/binding.js","bare-ansi-escapes":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-ansi-escapes/index.js","bare-type":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-type/index.js"},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-inspect/package.json":{},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-os/binding.js":{"#package":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-os/package.json",".":"linked:libbare-os.3.9.1.so"},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-os/index.js":{"#package":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-os/package.json","./binding":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-os/binding.js","./lib/constants":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-os/lib/constants.js","./lib/errors":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-os/lib/errors.js"},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-os/lib/constants.js":{"#package":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-os/package.json","../binding":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-os/binding.js"},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-os/lib/errors.js":{"#package":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-os/package.json"},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-os/package.json":{},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-path/index.js":{"#package":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-path/package.json","./lib/posix":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-path/lib/posix.js","./lib/win32":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-path/lib/win32.js"},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-path/lib/constants.js":{"#package":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-path/package.json"},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-path/lib/posix.js":{"#package":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-path/package.json","./constants":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-path/lib/constants.js","./shared":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-path/lib/shared.js","./win32":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-path/lib/win32.js","bare-os":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-os/index.js"},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-path/lib/shared.js":{"#package":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-path/package.json","./constants":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-path/lib/constants.js"},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-path/lib/win32.js":{"#package":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-path/package.json","./constants":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-path/lib/constants.js","./posix":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-path/lib/posix.js","./shared":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-path/lib/shared.js","bare-os":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-os/index.js"},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-path/package.json":{},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-stream/index.js":{"#package":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-stream/package.json","./web":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-stream/web.js","b4a":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/b4a/index.js","streamx":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/streamx/index.js"},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-stream/package.json":{},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-stream/web.js":{"#package":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-stream/package.json","streamx":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/streamx/index.js","teex":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/teex/index.js"},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-type/binding.js":{"#package":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-type/package.json",".":"linked:libbare-type.1.1.0.so"},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-type/index.js":{"#package":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-type/package.json","./binding":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-type/binding.js"},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-type/package.json":{},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-url/binding.js":{"#package":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-url/package.json",".":"linked:libbare-url.2.4.5.so"},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-url/index.js":{"#package":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-url/package.json","./binding":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-url/binding.js","./lib/errors":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-url/lib/errors.js","./lib/url-search-params":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-url/lib/url-search-params.js","bare-path":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-path/index.js"},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-url/lib/errors.js":{"#package":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-url/package.json"},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-url/lib/url-search-params.js":{"#package":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-url/package.json"},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-url/package.json":{},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/compact-encoding/package.json"},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/compact-encoding/index.js":{"#package":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/compact-encoding/package.json","./endian":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/compact-encoding/raw.js","b4a":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/b4a/index.js"},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/compact-encoding/package.json"},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/compact-encoding/package.json":{},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/compact-encoding/package.json","./endian":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/compact-encoding/endian.js","b4a":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/b4a/index.js"},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/events-universal/bare.js":{"#package":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/events-universal/package.json","bare-events":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-events/index.js"},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/events-universal/package.json":{},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/fast-fifo/fixed-size.js":{"#package":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/fast-fifo/package.json"},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/fast-fifo/index.js":{"#package":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/fast-fifo/package.json","./fixed-size":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/fast-fifo/fixed-size.js"},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/fast-fifo/package.json":{},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/hypercore-crypto/index.js":{"#package":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/hypercore-crypto/package.json","b4a":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/b4a/index.js","compact-encoding":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/compact-encoding/index.js","sodium-universal":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/sodium-universal/index.js"},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/hypercore-crypto/package.json":{},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/require-addon/lib/bare.js":{"#package":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/require-addon/package.json"},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/require-addon/package.json":{},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/sodium-native/binding.js":{"#package":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/sodium-native/package.json",".":"linked:libsodium-native.5.1.0.so","require-addon":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/require-addon/lib/bare.js"},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/sodium-native/index.js":{"#package":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/sodium-native/package.json","./binding":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/sodium-native/binding.js","assert":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-assert/index.js","which-runtime":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/which-runtime/index.js"},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/sodium-native/package.json":{},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/sodium-universal/index.js":{"#package":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/sodium-universal/package.json","sodium-native":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/sodium-native/index.js"},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/sodium-universal/package.json":{},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/streamx/index.js":{"#package":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/streamx/package.json","./lib/errors.js":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/streamx/lib/errors.js","events-universal":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/events-universal/bare.js","fast-fifo":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/fast-fifo/index.js","text-decoder":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/text-decoder/index.js"},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/streamx/lib/errors.js":{"#package":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/streamx/package.json"},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/streamx/package.json":{},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/teex/index.js":{"#package":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/teex/package.json","streamx":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/streamx/index.js"},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/teex/package.json":{},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/text-decoder/index.js":{"#package":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/text-decoder/package.json","./lib/pass-through-decoder":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/text-decoder/lib/pass-through-decoder.js","./lib/utf8-decoder":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/text-decoder/lib/utf8-decoder.js"},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/text-decoder/lib/pass-through-decoder.js":{"#package":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/text-decoder/package.json","b4a":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/b4a/index.js"},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/text-decoder/lib/utf8-decoder.js":{"#package":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/text-decoder/package.json","b4a":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/b4a/index.js"},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/text-decoder/package.json":{},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/which-runtime/index.js":{"#package":"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/which-runtime/package.json"},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/which-runtime/package.json":{},"/node_modules/pgh-runtime/node_modules/hyper-overlay/package.json":{},"/node_modules/pgh-runtime/package.json":{},"/node_modules/pgh/lib/network-fetcher.js":{"#node:fs":"/node_modules/pgh/node_modules/bare-fs/index.js","#node:os":"/node_modules/pgh/node_modules/bare-os/index.js","#node:path":"/node_modules/pgh/node_modules/bare-path/index.js","#package":"/node_modules/pgh/package.json","./release-registry.js":"/node_modules/pgh/lib/release-registry.js","b4a":"/node_modules/pgh/node_modules/b4a/index.js","corestore":"/node_modules/pgh/node_modules/corestore/index.js","hyper-overlay/file-index":"/node_modules/pgh/node_modules/hyper-overlay/lib/file-index.js","hyper-overlay/protocol":"/node_modules/pgh/node_modules/hyper-overlay/lib/protocol.js","hyper-overlay/transfer":"/node_modules/pgh/node_modules/hyper-overlay/lib/transfer.js","hyper-overlay/tree":"/node_modules/pgh/node_modules/hyper-overlay/lib/tree.js","hypercore-crypto":"/node_modules/pgh/node_modules/hypercore-crypto/index.js","hyperswarm":"/node_modules/pgh/node_modules/hyperswarm/index.js","protomux":"/node_modules/pgh/node_modules/protomux/index.js"},"/node_modules/pgh/lib/release-registry.js":{"#package":"/node_modules/pgh/package.json","autobase":"/node_modules/pgh/node_modules/autobase/index.js","b4a":"/node_modules/pgh/node_modules/b4a/index.js","hyperbee":"/node_modules/pgh/node_modules/hyperbee/index.js","hypercore-crypto":"/node_modules/pgh/node_modules/hypercore-crypto/index.js","sodium-native":"/node_modules/pgh/node_modules/sodium-native/index.js"},"/node_modules/pgh/lib/resolve-release.js":{"#node:fs":"/node_modules/pgh/node_modules/bare-fs/index.js","#node:os":"/node_modules/pgh/node_modules/bare-os/index.js","#node:path":"/node_modules/pgh/node_modules/bare-path/index.js","#node:process":"/node_modules/pgh/node_modules/bare-process/index.js","#package":"/node_modules/pgh/package.json","./release-registry.js":"/node_modules/pgh/lib/release-registry.js","b4a":"/node_modules/pgh/node_modules/b4a/index.js","corestore":"/node_modules/pgh/node_modules/corestore/index.js","hyper-svc":"/node_modules/pgh/node_modules/hyper-svc/index.js","hyperswarm":"/node_modules/pgh/node_modules/hyperswarm/index.js"},"/node_modules/pgh/node_modules/@hyperswarm/secret-stream/index.js":{"#package":"/node_modules/pgh/node_modules/@hyperswarm/secret-stream/package.json","./lib/bridge":"/node_modules/pgh/node_modules/@hyperswarm/secret-stream/lib/bridge.js","./lib/handshake":"/node_modules/pgh/node_modules/@hyperswarm/secret-stream/lib/handshake.js","b4a":"/node_modules/pgh/node_modules/b4a/index.js","hypercore-crypto":"/node_modules/pgh/node_modules/hypercore-crypto/index.js","sodium-secretstream":"/node_modules/pgh/node_modules/sodium-secretstream/index.js","sodium-universal":"/node_modules/pgh/node_modules/sodium-universal/index.js","streamx":"/node_modules/pgh/node_modules/streamx/index.js","timeout-refresh":"/node_modules/pgh/node_modules/timeout-refresh/index.js","unslab":"/node_modules/pgh/node_modules/unslab/index.js"},"/node_modules/pgh/node_modules/@hyperswarm/secret-stream/lib/bridge.js":{"#package":"/node_modules/pgh/node_modules/@hyperswarm/secret-stream/package.json","streamx":"/node_modules/pgh/node_modules/streamx/index.js"},"/node_modules/pgh/node_modules/@hyperswarm/secret-stream/lib/handshake.js":{"#package":"/node_modules/pgh/node_modules/@hyperswarm/secret-stream/package.json","b4a":"/node_modules/pgh/node_modules/b4a/index.js","noise-curve-ed":"/node_modules/pgh/node_modules/noise-curve-ed/index.js","noise-handshake":"/node_modules/pgh/node_modules/noise-handshake/noise.js","sodium-universal":"/node_modules/pgh/node_modules/sodium-universal/index.js"},"/node_modules/pgh/node_modules/@hyperswarm/secret-stream/package.json":{},"/node_modules/pgh/node_modules/adaptive-timeout/index.js":{"#package":"/node_modules/pgh/node_modules/adaptive-timeout/package.json","xache":"/node_modules/pgh/node_modules/xache/index.js"},"/node_modules/pgh/node_modules/adaptive-timeout/package.json":{},"/node_modules/pgh/node_modules/autobase/encoding/legacy.js":{"#package":"/node_modules/pgh/node_modules/autobase/package.json","compact-encoding":"/node_modules/pgh/node_modules/compact-encoding/index.js","index-encoder":"/node_modules/pgh/node_modules/index-encoder/index.js"},"/node_modules/pgh/node_modules/autobase/encoding/spec/autobase/index.js":{"#package":"/node_modules/pgh/node_modules/autobase/package.json","../../legacy.js":"/node_modules/pgh/node_modules/autobase/encoding/legacy.js","hyperschema/runtime":"/node_modules/pgh/node_modules/hyperschema/runtime.cjs"},"/node_modules/pgh/node_modules/autobase/index.js":{"#package":"/node_modules/pgh/node_modules/autobase/package.json","./lib/active-writers.js":"/node_modules/pgh/node_modules/autobase/lib/active-writers.js","./lib/append-batch.js":"/node_modules/pgh/node_modules/autobase/lib/append-batch.js","./lib/apply-calls.js":"/node_modules/pgh/node_modules/autobase/lib/apply-calls.js","./lib/apply-state.js":"/node_modules/pgh/node_modules/autobase/lib/apply-state.js","./lib/boot.js":"/node_modules/pgh/node_modules/autobase/lib/boot.js","./lib/caps.js":"/node_modules/pgh/node_modules/autobase/lib/caps.js","./lib/encryption.js":"/node_modules/pgh/node_modules/autobase/lib/encryption.js","./lib/fast-forward.js":"/node_modules/pgh/node_modules/autobase/lib/fast-forward.js","./lib/linearizer.js":"/node_modules/pgh/node_modules/autobase/lib/linearizer.js","./lib/local-state.js":"/node_modules/pgh/node_modules/autobase/lib/local-state.js","./lib/messages.js":"/node_modules/pgh/node_modules/autobase/lib/messages.js","./lib/store.js":"/node_modules/pgh/node_modules/autobase/lib/store.js","./lib/system.js":"/node_modules/pgh/node_modules/autobase/lib/system.js","./lib/timer.js":"/node_modules/pgh/node_modules/autobase/lib/timer.js","./lib/updates.js":"/node_modules/pgh/node_modules/autobase/lib/updates.js","./lib/values.js":"/node_modules/pgh/node_modules/autobase/lib/values.js","./lib/wakeup.js":"/node_modules/pgh/node_modules/autobase/lib/wakeup.js","./lib/writer.js":"/node_modules/pgh/node_modules/autobase/lib/writer.js","b4a":"/node_modules/pgh/node_modules/b4a/index.js","compact-encoding":"/node_modules/pgh/node_modules/compact-encoding/index.js","core-coupler":"/node_modules/pgh/node_modules/core-coupler/index.js","debounceify":"/node_modules/pgh/node_modules/debounceify/index.js","encryption-encoding":"/node_modules/pgh/node_modules/encryption-encoding/index.js","hypercore":"/node_modules/pgh/node_modules/hypercore/index.js","hypercore-id-encoding":"/node_modules/pgh/node_modules/hypercore-id-encoding/index.js","nanoassert":"/node_modules/pgh/node_modules/nanoassert/index.js","protomux-wakeup":"/node_modules/pgh/node_modules/protomux-wakeup/index.js","ready-resource":"/node_modules/pgh/node_modules/ready-resource/index.js","resolve-reject-promise":"/node_modules/pgh/node_modules/resolve-reject-promise/index.js","safety-catch":"/node_modules/pgh/node_modules/safety-catch/index.js","scope-lock":"/node_modules/pgh/node_modules/scope-lock/index.js","signal-promise":"/node_modules/pgh/node_modules/signal-promise/index.js"},"/node_modules/pgh/node_modules/autobase/lib/active-writers.js":{"#package":"/node_modules/pgh/node_modules/autobase/package.json","b4a":"/node_modules/pgh/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/autobase/lib/append-batch.js":{"#package":"/node_modules/pgh/node_modules/autobase/package.json","signal-promise":"/node_modules/pgh/node_modules/signal-promise/index.js"},"/node_modules/pgh/node_modules/autobase/lib/apply-calls.js":{"#package":"/node_modules/pgh/node_modules/autobase/package.json"},"/node_modules/pgh/node_modules/autobase/lib/apply-state.js":{"#package":"/node_modules/pgh/node_modules/autobase/package.json","./apply-calls.js":"/node_modules/pgh/node_modules/autobase/lib/apply-calls.js","./caps.js":"/node_modules/pgh/node_modules/autobase/lib/caps.js","./encryption.js":"/node_modules/pgh/node_modules/autobase/lib/encryption.js","./fork.js":"/node_modules/pgh/node_modules/autobase/lib/fork.js","./local-state.js":"/node_modules/pgh/node_modules/autobase/lib/local-state.js","./messages.js":"/node_modules/pgh/node_modules/autobase/lib/messages.js","./system.js":"/node_modules/pgh/node_modules/autobase/lib/system.js","./updates.js":"/node_modules/pgh/node_modules/autobase/lib/updates.js","./values.js":"/node_modules/pgh/node_modules/autobase/lib/values.js","b4a":"/node_modules/pgh/node_modules/b4a/index.js","compact-encoding":"/node_modules/pgh/node_modules/compact-encoding/index.js","hypercore":"/node_modules/pgh/node_modules/hypercore/index.js","hypercore-crypto":"/node_modules/pgh/node_modules/hypercore-crypto/index.js","hypercore/lib/multisig.js":"/node_modules/pgh/node_modules/hypercore/lib/multisig.js","nanoassert":"/node_modules/pgh/node_modules/nanoassert/index.js","ready-resource":"/node_modules/pgh/node_modules/ready-resource/index.js","safety-catch":"/node_modules/pgh/node_modules/safety-catch/index.js"},"/node_modules/pgh/node_modules/autobase/lib/boot.js":{"#package":"/node_modules/pgh/node_modules/autobase/package.json","./messages.js":"/node_modules/pgh/node_modules/autobase/lib/messages.js","compact-encoding":"/node_modules/pgh/node_modules/compact-encoding/index.js","encryption-encoding":"/node_modules/pgh/node_modules/encryption-encoding/index.js"},"/node_modules/pgh/node_modules/autobase/lib/caps.js":{"#package":"/node_modules/pgh/node_modules/autobase/package.json","hypercore-crypto":"/node_modules/pgh/node_modules/hypercore-crypto/index.js"},"/node_modules/pgh/node_modules/autobase/lib/clock.js":{"#package":"/node_modules/pgh/node_modules/autobase/package.json","tiny-buffer-map":"/node_modules/pgh/node_modules/tiny-buffer-map/index.js"},"/node_modules/pgh/node_modules/autobase/lib/consensus.js":{"#package":"/node_modules/pgh/node_modules/autobase/package.json","./clock.js":"/node_modules/pgh/node_modules/autobase/lib/clock.js","tiny-buffer-map":"/node_modules/pgh/node_modules/tiny-buffer-map/index.js"},"/node_modules/pgh/node_modules/autobase/lib/encryption.js":{"#package":"/node_modules/pgh/node_modules/autobase/package.json","./caps.js":"/node_modules/pgh/node_modules/autobase/lib/caps.js","./messages.js":"/node_modules/pgh/node_modules/autobase/lib/messages.js","./system.js":"/node_modules/pgh/node_modules/autobase/lib/system.js","b4a":"/node_modules/pgh/node_modules/b4a/index.js","compact-encoding":"/node_modules/pgh/node_modules/compact-encoding/index.js","hypercore-crypto":"/node_modules/pgh/node_modules/hypercore-crypto/index.js","hypercore/lib/default-encryption.js":"/node_modules/pgh/node_modules/hypercore/lib/default-encryption.js","ready-resource":"/node_modules/pgh/node_modules/ready-resource/index.js","resolve-reject-promise":"/node_modules/pgh/node_modules/resolve-reject-promise/index.js","sodium-universal":"/node_modules/pgh/node_modules/sodium-universal/index.js"},"/node_modules/pgh/node_modules/autobase/lib/fast-forward.js":{"#package":"/node_modules/pgh/node_modules/autobase/package.json","./encryption.js":"/node_modules/pgh/node_modules/autobase/lib/encryption.js","./system.js":"/node_modules/pgh/node_modules/autobase/lib/system.js","resolve-reject-promise":"/node_modules/pgh/node_modules/resolve-reject-promise/index.js","safety-catch":"/node_modules/pgh/node_modules/safety-catch/index.js"},"/node_modules/pgh/node_modules/autobase/lib/fork.js":{"#package":"/node_modules/pgh/node_modules/autobase/package.json","./encryption.js":"/node_modules/pgh/node_modules/autobase/lib/encryption.js","./messages.js":"/node_modules/pgh/node_modules/autobase/lib/messages.js","./system.js":"/node_modules/pgh/node_modules/autobase/lib/system.js","compact-encoding":"/node_modules/pgh/node_modules/compact-encoding/index.js"},"/node_modules/pgh/node_modules/autobase/lib/linearizer.js":{"#package":"/node_modules/pgh/node_modules/autobase/package.json","./clock.js":"/node_modules/pgh/node_modules/autobase/lib/clock.js","./consensus.js":"/node_modules/pgh/node_modules/autobase/lib/consensus.js","./topolist.js":"/node_modules/pgh/node_modules/autobase/lib/topolist.js","b4a":"/node_modules/pgh/node_modules/b4a/index.js","nanoassert":"/node_modules/pgh/node_modules/nanoassert/index.js"},"/node_modules/pgh/node_modules/autobase/lib/local-state.js":{"#package":"/node_modules/pgh/node_modules/autobase/package.json","./messages.js":"/node_modules/pgh/node_modules/autobase/lib/messages.js","b4a":"/node_modules/pgh/node_modules/b4a/index.js","compact-encoding":"/node_modules/pgh/node_modules/compact-encoding/index.js"},"/node_modules/pgh/node_modules/autobase/lib/messages.js":{"#package":"/node_modules/pgh/node_modules/autobase/package.json","../encoding/spec/autobase":"/node_modules/pgh/node_modules/autobase/encoding/spec/autobase/index.js"},"/node_modules/pgh/node_modules/autobase/lib/node-buffer.js":{"#package":"/node_modules/pgh/node_modules/autobase/package.json"},"/node_modules/pgh/node_modules/autobase/lib/store.js":{"#package":"/node_modules/pgh/node_modules/autobase/package.json","./messages.js":"/node_modules/pgh/node_modules/autobase/lib/messages.js","b4a":"/node_modules/pgh/node_modules/b4a/index.js","compact-encoding":"/node_modules/pgh/node_modules/compact-encoding/index.js","hypercore":"/node_modules/pgh/node_modules/hypercore/index.js","hypercore-crypto":"/node_modules/pgh/node_modules/hypercore-crypto/index.js"},"/node_modules/pgh/node_modules/autobase/lib/system.js":{"#package":"/node_modules/pgh/node_modules/autobase/package.json","./caps.js":"/node_modules/pgh/node_modules/autobase/lib/caps.js","./messages.js":"/node_modules/pgh/node_modules/autobase/lib/messages.js","b4a":"/node_modules/pgh/node_modules/b4a/index.js","compact-encoding":"/node_modules/pgh/node_modules/compact-encoding/index.js","hyperbee":"/node_modules/pgh/node_modules/hyperbee/index.js","hypercore-crypto":"/node_modules/pgh/node_modules/hypercore-crypto/index.js","ready-resource":"/node_modules/pgh/node_modules/ready-resource/index.js","sub-encoder":"/node_modules/pgh/node_modules/sub-encoder/index.js"},"/node_modules/pgh/node_modules/autobase/lib/timer.js":{"#package":"/node_modules/pgh/node_modules/autobase/package.json","safety-catch":"/node_modules/pgh/node_modules/safety-catch/index.js"},"/node_modules/pgh/node_modules/autobase/lib/topolist.js":{"#package":"/node_modules/pgh/node_modules/autobase/package.json","b4a":"/node_modules/pgh/node_modules/b4a/index.js","nanoassert":"/node_modules/pgh/node_modules/nanoassert/index.js"},"/node_modules/pgh/node_modules/autobase/lib/updates.js":{"#package":"/node_modules/pgh/node_modules/autobase/package.json"},"/node_modules/pgh/node_modules/autobase/lib/values.js":{"#package":"/node_modules/pgh/node_modules/autobase/package.json","./caps.js":"/node_modules/pgh/node_modules/autobase/lib/caps.js","./encryption.js":"/node_modules/pgh/node_modules/autobase/lib/encryption.js","./messages.js":"/node_modules/pgh/node_modules/autobase/lib/messages.js","b4a":"/node_modules/pgh/node_modules/b4a/index.js","compact-encoding":"/node_modules/pgh/node_modules/compact-encoding/index.js","hypercore-crypto":"/node_modules/pgh/node_modules/hypercore-crypto/index.js"},"/node_modules/pgh/node_modules/autobase/lib/wakeup.js":{"#package":"/node_modules/pgh/node_modules/autobase/package.json","b4a":"/node_modules/pgh/node_modules/b4a/index.js","compact-encoding":"/node_modules/pgh/node_modules/compact-encoding/index.js","ready-resource":"/node_modules/pgh/node_modules/ready-resource/index.js","safety-catch":"/node_modules/pgh/node_modules/safety-catch/index.js"},"/node_modules/pgh/node_modules/autobase/lib/writer.js":{"#package":"/node_modules/pgh/node_modules/autobase/package.json","./linearizer.js":"/node_modules/pgh/node_modules/autobase/lib/linearizer.js","./node-buffer.js":"/node_modules/pgh/node_modules/autobase/lib/node-buffer.js","b4a":"/node_modules/pgh/node_modules/b4a/index.js","compact-encoding":"/node_modules/pgh/node_modules/compact-encoding/index.js","nanoassert":"/node_modules/pgh/node_modules/nanoassert/index.js","ready-resource":"/node_modules/pgh/node_modules/ready-resource/index.js","signal-promise":"/node_modules/pgh/node_modules/signal-promise/index.js"},"/node_modules/pgh/node_modules/autobase/package.json":{},"/node_modules/pgh/node_modules/b4a/index.js":{"#package":"/node_modules/pgh/node_modules/b4a/package.json"},"/node_modules/pgh/node_modules/b4a/package.json":{},"/node_modules/pgh/node_modules/bare-abort/binding.js":{"#package":"/node_modules/pgh/node_modules/bare-abort/package.json",".":"linked:libbare-abort.2.0.13.so"},"/node_modules/pgh/node_modules/bare-abort/index.js":{"#package":"/node_modules/pgh/node_modules/bare-abort/package.json","./binding":"/node_modules/pgh/node_modules/bare-abort/binding.js"},"/node_modules/pgh/node_modules/bare-abort/package.json":{},"/node_modules/pgh/node_modules/bare-ansi-escapes/index.js":{"#package":"/node_modules/pgh/node_modules/bare-ansi-escapes/package.json"},"/node_modules/pgh/node_modules/bare-ansi-escapes/package.json":{},"/node_modules/pgh/node_modules/bare-assert/index.js":{"#package":"/node_modules/pgh/node_modules/bare-assert/package.json","bare-inspect":"/node_modules/pgh/node_modules/bare-inspect/index.js"},"/node_modules/pgh/node_modules/bare-assert/package.json":{},"/node_modules/pgh/node_modules/bare-env/index.js":{"#package":"/node_modules/pgh/node_modules/bare-env/package.json","bare-os":"/node_modules/pgh/node_modules/bare-os/index.js"},"/node_modules/pgh/node_modules/bare-env/package.json":{},"/node_modules/pgh/node_modules/bare-events/index.js":{"#package":"/node_modules/pgh/node_modules/bare-events/package.json","./lib/errors":"/node_modules/pgh/node_modules/bare-events/lib/errors.js"},"/node_modules/pgh/node_modules/bare-events/lib/errors.js":{"#package":"/node_modules/pgh/node_modules/bare-events/package.json"},"/node_modules/pgh/node_modules/bare-events/package.json":{},"/node_modules/pgh/node_modules/bare-fs/binding.js":{"#package":"/node_modules/pgh/node_modules/bare-fs/package.json",".":"linked:libbare-fs.4.7.2.so"},"/node_modules/pgh/node_modules/bare-fs/index.js":{"#package":"/node_modules/pgh/node_modules/bare-fs/package.json","./binding":"/node_modules/pgh/node_modules/bare-fs/binding.js","./lib/constants":"/node_modules/pgh/node_modules/bare-fs/lib/constants.js","./lib/errors":"/node_modules/pgh/node_modules/bare-fs/lib/errors.js","./promises":"/node_modules/pgh/node_modules/bare-fs/promises.js","bare-events":"/node_modules/pgh/node_modules/bare-events/index.js","bare-path":"/node_modules/pgh/node_modules/bare-path/index.js","bare-stream":"/node_modules/pgh/node_modules/bare-stream/index.js","bare-url":"/node_modules/pgh/node_modules/bare-url/index.js","fast-fifo":"/node_modules/pgh/node_modules/fast-fifo/index.js"},"/node_modules/pgh/node_modules/bare-fs/lib/constants.js":{"#package":"/node_modules/pgh/node_modules/bare-fs/package.json","../binding":"/node_modules/pgh/node_modules/bare-fs/binding.js"},"/node_modules/pgh/node_modules/bare-fs/lib/errors.js":{"#package":"/node_modules/pgh/node_modules/bare-fs/package.json","bare-os":"/node_modules/pgh/node_modules/bare-os/index.js"},"/node_modules/pgh/node_modules/bare-fs/package.json":{},"/node_modules/pgh/node_modules/bare-fs/promises.js":{"#package":"/node_modules/pgh/node_modules/bare-fs/package.json",".":"/node_modules/pgh/node_modules/bare-fs/index.js","bare-events":"/node_modules/pgh/node_modules/bare-events/index.js"},"/node_modules/pgh/node_modules/bare-hrtime/binding.js":{"#package":"/node_modules/pgh/node_modules/bare-hrtime/package.json",".":"linked:libbare-hrtime.2.1.1.so"},"/node_modules/pgh/node_modules/bare-hrtime/index.js":{"#package":"/node_modules/pgh/node_modules/bare-hrtime/package.json","./binding":"/node_modules/pgh/node_modules/bare-hrtime/binding.js"},"/node_modules/pgh/node_modules/bare-hrtime/package.json":{},"/node_modules/pgh/node_modules/bare-inspect/binding.js":{"#package":"/node_modules/pgh/node_modules/bare-inspect/package.json",".":"linked:libbare-inspect.3.1.4.so"},"/node_modules/pgh/node_modules/bare-inspect/index.js":{"#package":"/node_modules/pgh/node_modules/bare-inspect/package.json","./binding":"/node_modules/pgh/node_modules/bare-inspect/binding.js","bare-ansi-escapes":"/node_modules/pgh/node_modules/bare-ansi-escapes/index.js","bare-type":"/node_modules/pgh/node_modules/bare-type/index.js"},"/node_modules/pgh/node_modules/bare-inspect/package.json":{},"/node_modules/pgh/node_modules/bare-os/binding.js":{"#package":"/node_modules/pgh/node_modules/bare-os/package.json",".":"linked:libbare-os.3.9.1.so"},"/node_modules/pgh/node_modules/bare-os/index.js":{"#package":"/node_modules/pgh/node_modules/bare-os/package.json","./binding":"/node_modules/pgh/node_modules/bare-os/binding.js","./lib/constants":"/node_modules/pgh/node_modules/bare-os/lib/constants.js","./lib/errors":"/node_modules/pgh/node_modules/bare-os/lib/errors.js"},"/node_modules/pgh/node_modules/bare-os/lib/constants.js":{"#package":"/node_modules/pgh/node_modules/bare-os/package.json","../binding":"/node_modules/pgh/node_modules/bare-os/binding.js"},"/node_modules/pgh/node_modules/bare-os/lib/errors.js":{"#package":"/node_modules/pgh/node_modules/bare-os/package.json"},"/node_modules/pgh/node_modules/bare-os/package.json":{},"/node_modules/pgh/node_modules/bare-path/index.js":{"#package":"/node_modules/pgh/node_modules/bare-path/package.json","./lib/posix":"/node_modules/pgh/node_modules/bare-path/lib/posix.js","./lib/win32":"/node_modules/pgh/node_modules/bare-path/lib/win32.js"},"/node_modules/pgh/node_modules/bare-path/lib/constants.js":{"#package":"/node_modules/pgh/node_modules/bare-path/package.json"},"/node_modules/pgh/node_modules/bare-path/lib/posix.js":{"#package":"/node_modules/pgh/node_modules/bare-path/package.json","./constants":"/node_modules/pgh/node_modules/bare-path/lib/constants.js","./shared":"/node_modules/pgh/node_modules/bare-path/lib/shared.js","./win32":"/node_modules/pgh/node_modules/bare-path/lib/win32.js","bare-os":"/node_modules/pgh/node_modules/bare-os/index.js"},"/node_modules/pgh/node_modules/bare-path/lib/shared.js":{"#package":"/node_modules/pgh/node_modules/bare-path/package.json","./constants":"/node_modules/pgh/node_modules/bare-path/lib/constants.js"},"/node_modules/pgh/node_modules/bare-path/lib/win32.js":{"#package":"/node_modules/pgh/node_modules/bare-path/package.json","./constants":"/node_modules/pgh/node_modules/bare-path/lib/constants.js","./posix":"/node_modules/pgh/node_modules/bare-path/lib/posix.js","./shared":"/node_modules/pgh/node_modules/bare-path/lib/shared.js","bare-os":"/node_modules/pgh/node_modules/bare-os/index.js"},"/node_modules/pgh/node_modules/bare-path/package.json":{},"/node_modules/pgh/node_modules/bare-process/index.js":{"#package":"/node_modules/pgh/node_modules/bare-process/package.json","bare-abort":"/node_modules/pgh/node_modules/bare-abort/index.js","bare-env":"/node_modules/pgh/node_modules/bare-env/index.js","bare-events":"/node_modules/pgh/node_modules/bare-events/index.js","bare-hrtime":"/node_modules/pgh/node_modules/bare-hrtime/index.js","bare-os":"/node_modules/pgh/node_modules/bare-os/index.js","bare-signals":"/node_modules/pgh/node_modules/bare-signals/index.js","bare-stdio":"/node_modules/pgh/node_modules/bare-stdio/index.js"},"/node_modules/pgh/node_modules/bare-process/package.json":{},"/node_modules/pgh/node_modules/bare-signals/binding.js":{"#package":"/node_modules/pgh/node_modules/bare-signals/package.json",".":"linked:libbare-signals.4.2.0.so"},"/node_modules/pgh/node_modules/bare-signals/index.js":{"#package":"/node_modules/pgh/node_modules/bare-signals/package.json","./binding":"/node_modules/pgh/node_modules/bare-signals/binding.js","./lib/emitter":"/node_modules/pgh/node_modules/bare-signals/lib/emitter.js","./lib/errors":"/node_modules/pgh/node_modules/bare-signals/lib/errors.js","bare-events":"/node_modules/pgh/node_modules/bare-events/index.js","bare-os":"/node_modules/pgh/node_modules/bare-os/index.js"},"/node_modules/pgh/node_modules/bare-signals/lib/emitter.js":{"#package":"/node_modules/pgh/node_modules/bare-signals/package.json","..":"/node_modules/pgh/node_modules/bare-signals/index.js","bare-events":"/node_modules/pgh/node_modules/bare-events/index.js"},"/node_modules/pgh/node_modules/bare-signals/lib/errors.js":{"#package":"/node_modules/pgh/node_modules/bare-signals/package.json"},"/node_modules/pgh/node_modules/bare-signals/package.json":{},"/node_modules/pgh/node_modules/bare-stdio/binding.js":{"#package":"/node_modules/pgh/node_modules/bare-stdio/package.json",".":"linked:libbare-stdio.1.0.2.so"},"/node_modules/pgh/node_modules/bare-stdio/index.js":{"#package":"/node_modules/pgh/node_modules/bare-stdio/package.json","./binding":"/node_modules/pgh/node_modules/bare-stdio/binding.js","bare-fs":"/node_modules/pgh/node_modules/bare-fs/index.js","bare-pipe":"/node_modules/pgh/node_modules/bare-stdio/node_modules/bare-pipe/index.js","bare-tty":"/node_modules/pgh/node_modules/bare-tty/index.js"},"/node_modules/pgh/node_modules/bare-stdio/node_modules/bare-pipe/binding.js":{"#package":"/node_modules/pgh/node_modules/bare-stdio/node_modules/bare-pipe/package.json",".":"linked:libbare-pipe.4.2.0.so"},"/node_modules/pgh/node_modules/bare-stdio/node_modules/bare-pipe/index.js":{"#package":"/node_modules/pgh/node_modules/bare-stdio/node_modules/bare-pipe/package.json","./binding":"/node_modules/pgh/node_modules/bare-stdio/node_modules/bare-pipe/binding.js","./lib/constants":"/node_modules/pgh/node_modules/bare-stdio/node_modules/bare-pipe/lib/constants.js","./lib/errors":"/node_modules/pgh/node_modules/bare-stdio/node_modules/bare-pipe/lib/errors.js","bare-events":"/node_modules/pgh/node_modules/bare-events/index.js","bare-stream":"/node_modules/pgh/node_modules/bare-stream/index.js"},"/node_modules/pgh/node_modules/bare-stdio/node_modules/bare-pipe/lib/constants.js":{"#package":"/node_modules/pgh/node_modules/bare-stdio/node_modules/bare-pipe/package.json","../binding":"/node_modules/pgh/node_modules/bare-stdio/node_modules/bare-pipe/binding.js"},"/node_modules/pgh/node_modules/bare-stdio/node_modules/bare-pipe/lib/errors.js":{"#package":"/node_modules/pgh/node_modules/bare-stdio/node_modules/bare-pipe/package.json"},"/node_modules/pgh/node_modules/bare-stdio/node_modules/bare-pipe/package.json":{},"/node_modules/pgh/node_modules/bare-stdio/package.json":{},"/node_modules/pgh/node_modules/bare-stream/index.js":{"#package":"/node_modules/pgh/node_modules/bare-stream/package.json","./web":"/node_modules/pgh/node_modules/bare-stream/web.js","streamx":"/node_modules/pgh/node_modules/streamx/index.js"},"/node_modules/pgh/node_modules/bare-stream/package.json":{},"/node_modules/pgh/node_modules/bare-stream/web.js":{"#package":"/node_modules/pgh/node_modules/bare-stream/package.json","streamx":"/node_modules/pgh/node_modules/streamx/index.js","teex":"/node_modules/pgh/node_modules/teex/index.js"},"/node_modules/pgh/node_modules/bare-tty/binding.js":{"#package":"/node_modules/pgh/node_modules/bare-tty/package.json",".":"linked:libbare-tty.5.1.0.so"},"/node_modules/pgh/node_modules/bare-tty/index.js":{"#package":"/node_modules/pgh/node_modules/bare-tty/package.json","./binding":"/node_modules/pgh/node_modules/bare-tty/binding.js","./lib/constants":"/node_modules/pgh/node_modules/bare-tty/lib/constants.js","bare-signals":"/node_modules/pgh/node_modules/bare-signals/index.js","bare-stream":"/node_modules/pgh/node_modules/bare-stream/index.js"},"/node_modules/pgh/node_modules/bare-tty/lib/constants.js":{"#package":"/node_modules/pgh/node_modules/bare-tty/package.json","../binding":"/node_modules/pgh/node_modules/bare-tty/binding.js"},"/node_modules/pgh/node_modules/bare-tty/package.json":{},"/node_modules/pgh/node_modules/bare-type/binding.js":{"#package":"/node_modules/pgh/node_modules/bare-type/package.json",".":"linked:libbare-type.1.1.0.so"},"/node_modules/pgh/node_modules/bare-type/index.js":{"#package":"/node_modules/pgh/node_modules/bare-type/package.json","./binding":"/node_modules/pgh/node_modules/bare-type/binding.js"},"/node_modules/pgh/node_modules/bare-type/package.json":{},"/node_modules/pgh/node_modules/bare-url/binding.js":{"#package":"/node_modules/pgh/node_modules/bare-url/package.json",".":"linked:libbare-url.2.4.5.so"},"/node_modules/pgh/node_modules/bare-url/index.js":{"#package":"/node_modules/pgh/node_modules/bare-url/package.json","./binding":"/node_modules/pgh/node_modules/bare-url/binding.js","./lib/errors":"/node_modules/pgh/node_modules/bare-url/lib/errors.js","./lib/url-search-params":"/node_modules/pgh/node_modules/bare-url/lib/url-search-params.js","bare-path":"/node_modules/pgh/node_modules/bare-path/index.js"},"/node_modules/pgh/node_modules/bare-url/lib/errors.js":{"#package":"/node_modules/pgh/node_modules/bare-url/package.json"},"/node_modules/pgh/node_modules/bare-url/lib/url-search-params.js":{"#package":"/node_modules/pgh/node_modules/bare-url/package.json"},"/node_modules/pgh/node_modules/bare-url/package.json":{},"/node_modules/pgh/node_modules/big-sparse-array/index.js":{"#package":"/node_modules/pgh/node_modules/big-sparse-array/package.json"},"/node_modules/pgh/node_modules/big-sparse-array/package.json":{},"/node_modules/pgh/node_modules/bits-to-bytes/index.js":{"#package":"/node_modules/pgh/node_modules/bits-to-bytes/package.json","b4a":"/node_modules/pgh/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/bits-to-bytes/package.json":{},"/node_modules/pgh/node_modules/blind-relay/index.js":{"#package":"/node_modules/pgh/node_modules/blind-relay/package.json","./lib/errors":"/node_modules/pgh/node_modules/blind-relay/lib/errors.js","b4a":"/node_modules/pgh/node_modules/b4a/index.js","bits-to-bytes":"/node_modules/pgh/node_modules/bits-to-bytes/index.js","compact-encoding":"/node_modules/pgh/node_modules/compact-encoding/index.js","compact-encoding-bitfield":"/node_modules/pgh/node_modules/compact-encoding-bitfield/index.js","events":"/node_modules/pgh/node_modules/bare-events/index.js","protomux":"/node_modules/pgh/node_modules/protomux/index.js","sodium-universal":"/node_modules/pgh/node_modules/sodium-universal/index.js","streamx":"/node_modules/pgh/node_modules/streamx/index.js"},"/node_modules/pgh/node_modules/blind-relay/lib/errors.js":{"#package":"/node_modules/pgh/node_modules/blind-relay/package.json"},"/node_modules/pgh/node_modules/blind-relay/package.json":{},"/node_modules/pgh/node_modules/bogon/index.js":{"#package":"/node_modules/pgh/node_modules/bogon/package.json","b4a":"/node_modules/pgh/node_modules/b4a/index.js","compact-encoding":"/node_modules/pgh/node_modules/compact-encoding/index.js"},"/node_modules/pgh/node_modules/bogon/package.json":{},"/node_modules/pgh/node_modules/codecs/index.js":{"#package":"/node_modules/pgh/node_modules/codecs/package.json","b4a":"/node_modules/pgh/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/codecs/package.json":{},"/node_modules/pgh/node_modules/compact-encoding-bitfield/index.js":{"#package":"/node_modules/pgh/node_modules/compact-encoding-bitfield/package.json","compact-encoding":"/node_modules/pgh/node_modules/compact-encoding/index.js"},"/node_modules/pgh/node_modules/compact-encoding-bitfield/package.json":{},"/node_modules/pgh/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/pgh/node_modules/compact-encoding/package.json"},"/node_modules/pgh/node_modules/compact-encoding/index.js":{"#package":"/node_modules/pgh/node_modules/compact-encoding/package.json","./endian":"/node_modules/pgh/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/pgh/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/pgh/node_modules/compact-encoding/raw.js","b4a":"/node_modules/pgh/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/pgh/node_modules/compact-encoding/package.json"},"/node_modules/pgh/node_modules/compact-encoding/package.json":{},"/node_modules/pgh/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/pgh/node_modules/compact-encoding/package.json","./endian":"/node_modules/pgh/node_modules/compact-encoding/endian.js","b4a":"/node_modules/pgh/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/core-coupler/index.js":{"#package":"/node_modules/pgh/node_modules/core-coupler/package.json","safety-catch":"/node_modules/pgh/node_modules/safety-catch/index.js"},"/node_modules/pgh/node_modules/core-coupler/package.json":{},"/node_modules/pgh/node_modules/corestore/index.js":{"#package":"/node_modules/pgh/node_modules/corestore/package.json","./lib/audit.js":"/node_modules/pgh/node_modules/corestore/lib/audit.js","./lib/notify.js":"/node_modules/pgh/node_modules/corestore/lib/notify.js","b4a":"/node_modules/pgh/node_modules/b4a/index.js","hypercore":"/node_modules/pgh/node_modules/hypercore/index.js","hypercore-crypto":"/node_modules/pgh/node_modules/hypercore-crypto/index.js","hypercore-errors":"/node_modules/pgh/node_modules/hypercore-errors/index.js","hypercore-id-encoding":"/node_modules/pgh/node_modules/hypercore-id-encoding/index.js","ready-resource":"/node_modules/pgh/node_modules/ready-resource/index.js","sodium-universal":"/node_modules/pgh/node_modules/sodium-universal/index.js","which-runtime":"/node_modules/pgh/node_modules/which-runtime/index.js"},"/node_modules/pgh/node_modules/corestore/lib/audit.js":{"#package":"/node_modules/pgh/node_modules/corestore/package.json"},"/node_modules/pgh/node_modules/corestore/lib/notify.js":{"#package":"/node_modules/pgh/node_modules/corestore/package.json","events":"/node_modules/pgh/node_modules/bare-events/index.js","streamx":"/node_modules/pgh/node_modules/streamx/index.js"},"/node_modules/pgh/node_modules/corestore/package.json":{},"/node_modules/pgh/node_modules/debounceify/index.js":{"#package":"/node_modules/pgh/node_modules/debounceify/package.json"},"/node_modules/pgh/node_modules/debounceify/package.json":{},"/node_modules/pgh/node_modules/device-file/index.js":{"#package":"/node_modules/pgh/node_modules/device-file/package.json","b4a":"/node_modules/pgh/node_modules/b4a/index.js","fd-lock":"/node_modules/pgh/node_modules/fd-lock/index.js","fs":"/node_modules/pgh/node_modules/bare-fs/index.js","fs-native-extensions":"/node_modules/pgh/node_modules/fs-native-extensions/index.js","path":"/node_modules/pgh/node_modules/bare-path/index.js","ready-resource":"/node_modules/pgh/node_modules/ready-resource/index.js"},"/node_modules/pgh/node_modules/device-file/package.json":{},"/node_modules/pgh/node_modules/dht-rpc/index.js":{"#package":"/node_modules/pgh/node_modules/dht-rpc/package.json","./lib/commands":"/node_modules/pgh/node_modules/dht-rpc/lib/commands.js","./lib/errors":"/node_modules/pgh/node_modules/dht-rpc/lib/errors.js","./lib/health":"/node_modules/pgh/node_modules/dht-rpc/lib/health.js","./lib/io":"/node_modules/pgh/node_modules/dht-rpc/lib/io.js","./lib/peer":"/node_modules/pgh/node_modules/dht-rpc/lib/peer.js","./lib/query":"/node_modules/pgh/node_modules/dht-rpc/lib/query.js","./lib/session":"/node_modules/pgh/node_modules/dht-rpc/lib/session.js","b4a":"/node_modules/pgh/node_modules/b4a/index.js","compact-encoding":"/node_modules/pgh/node_modules/compact-encoding/index.js","events":"/node_modules/pgh/node_modules/bare-events/index.js","kademlia-routing-table":"/node_modules/pgh/node_modules/kademlia-routing-table/index.js","nat-sampler":"/node_modules/pgh/node_modules/nat-sampler/index.js","sodium-universal":"/node_modules/pgh/node_modules/sodium-universal/index.js","time-ordered-set":"/node_modules/pgh/node_modules/time-ordered-set/index.js","udx-native":"/node_modules/pgh/node_modules/udx-native/lib/udx.js"},"/node_modules/pgh/node_modules/dht-rpc/lib/commands.js":{"#package":"/node_modules/pgh/node_modules/dht-rpc/package.json"},"/node_modules/pgh/node_modules/dht-rpc/lib/errors.js":{"#package":"/node_modules/pgh/node_modules/dht-rpc/package.json"},"/node_modules/pgh/node_modules/dht-rpc/lib/health.js":{"#package":"/node_modules/pgh/node_modules/dht-rpc/package.json"},"/node_modules/pgh/node_modules/dht-rpc/lib/io.js":{"#package":"/node_modules/pgh/node_modules/dht-rpc/package.json","./errors":"/node_modules/pgh/node_modules/dht-rpc/lib/errors.js","./peer":"/node_modules/pgh/node_modules/dht-rpc/lib/peer.js","adaptive-timeout":"/node_modules/pgh/node_modules/adaptive-timeout/index.js","b4a":"/node_modules/pgh/node_modules/b4a/index.js","compact-encoding":"/node_modules/pgh/node_modules/compact-encoding/index.js","fast-fifo":"/node_modules/pgh/node_modules/fast-fifo/index.js","sodium-universal":"/node_modules/pgh/node_modules/sodium-universal/index.js"},"/node_modules/pgh/node_modules/dht-rpc/lib/peer.js":{"#package":"/node_modules/pgh/node_modules/dht-rpc/package.json","b4a":"/node_modules/pgh/node_modules/b4a/index.js","compact-encoding":"/node_modules/pgh/node_modules/compact-encoding/index.js","sodium-universal":"/node_modules/pgh/node_modules/sodium-universal/index.js"},"/node_modules/pgh/node_modules/dht-rpc/lib/query.js":{"#package":"/node_modules/pgh/node_modules/dht-rpc/package.json","./commands":"/node_modules/pgh/node_modules/dht-rpc/lib/commands.js","./peer":"/node_modules/pgh/node_modules/dht-rpc/lib/peer.js","b4a":"/node_modules/pgh/node_modules/b4a/index.js","streamx":"/node_modules/pgh/node_modules/streamx/index.js"},"/node_modules/pgh/node_modules/dht-rpc/lib/session.js":{"#package":"/node_modules/pgh/node_modules/dht-rpc/package.json"},"/node_modules/pgh/node_modules/dht-rpc/package.json":{},"/node_modules/pgh/node_modules/encryption-encoding/index.js":{"#package":"/node_modules/pgh/node_modules/encryption-encoding/package.json","./spec/hyperschema":"/node_modules/pgh/node_modules/encryption-encoding/spec/hyperschema/index.js"},"/node_modules/pgh/node_modules/encryption-encoding/package.json":{},"/node_modules/pgh/node_modules/encryption-encoding/spec/hyperschema/index.js":{"#package":"/node_modules/pgh/node_modules/encryption-encoding/package.json","hyperschema/runtime":"/node_modules/pgh/node_modules/hyperschema/runtime.cjs"},"/node_modules/pgh/node_modules/events-universal/bare.js":{"#package":"/node_modules/pgh/node_modules/events-universal/package.json","bare-events":"/node_modules/pgh/node_modules/bare-events/index.js"},"/node_modules/pgh/node_modules/events-universal/package.json":{},"/node_modules/pgh/node_modules/fast-fifo/fixed-size.js":{"#package":"/node_modules/pgh/node_modules/fast-fifo/package.json"},"/node_modules/pgh/node_modules/fast-fifo/index.js":{"#package":"/node_modules/pgh/node_modules/fast-fifo/package.json","./fixed-size":"/node_modules/pgh/node_modules/fast-fifo/fixed-size.js"},"/node_modules/pgh/node_modules/fast-fifo/package.json":{},"/node_modules/pgh/node_modules/fd-lock/index.js":{"#package":"/node_modules/pgh/node_modules/fd-lock/package.json","fs":"/node_modules/pgh/node_modules/bare-fs/index.js","fs-native-extensions":"/node_modules/pgh/node_modules/fs-native-extensions/index.js","ready-resource":"/node_modules/pgh/node_modules/ready-resource/index.js","resource-on-exit":"/node_modules/pgh/node_modules/resource-on-exit/index.js"},"/node_modules/pgh/node_modules/fd-lock/package.json":{},"/node_modules/pgh/node_modules/flat-tree/index.js":{"#package":"/node_modules/pgh/node_modules/flat-tree/package.json"},"/node_modules/pgh/node_modules/flat-tree/package.json":{},"/node_modules/pgh/node_modules/fs-native-extensions/binding.js":{"#package":"/node_modules/pgh/node_modules/fs-native-extensions/package.json",".":"linked:libfs-native-extensions.1.5.0.so","require-addon":"/node_modules/pgh/node_modules/require-addon/lib/bare.js"},"/node_modules/pgh/node_modules/fs-native-extensions/index.js":{"#package":"/node_modules/pgh/node_modules/fs-native-extensions/package.json","./binding":"/node_modules/pgh/node_modules/fs-native-extensions/binding.js","which-runtime":"/node_modules/pgh/node_modules/which-runtime/index.js"},"/node_modules/pgh/node_modules/fs-native-extensions/package.json":{},"/node_modules/pgh/node_modules/hyper-overlay/lib/chunk-scheduler.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/package.json","./chunker.js":"/node_modules/pgh/node_modules/hyper-overlay/lib/chunker.js"},"/node_modules/pgh/node_modules/hyper-overlay/lib/chunker.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/package.json","compact-encoding":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/compact-encoding/index.js","hypercore-crypto":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/hypercore-crypto/index.js","sodium-universal":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/sodium-universal/index.js"},"/node_modules/pgh/node_modules/hyper-overlay/lib/file-index.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/package.json","hyperbee":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/hyperbee/index.js","ready-resource":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/ready-resource/index.js"},"/node_modules/pgh/node_modules/hyper-overlay/lib/messages.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/package.json","compact-encoding":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/compact-encoding/index.js"},"/node_modules/pgh/node_modules/hyper-overlay/lib/protocol.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/package.json","./chunk-scheduler.js":"/node_modules/pgh/node_modules/hyper-overlay/lib/chunk-scheduler.js","./chunker.js":"/node_modules/pgh/node_modules/hyper-overlay/lib/chunker.js","./messages.js":"/node_modules/pgh/node_modules/hyper-overlay/lib/messages.js","bare-fs":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-fs/index.js","bare-path":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-path/index.js"},"/node_modules/pgh/node_modules/hyper-overlay/lib/transfer.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/package.json","./chunker.js":"/node_modules/pgh/node_modules/hyper-overlay/lib/chunker.js","bare-fs":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-fs/index.js","bare-os":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-os/index.js","bare-path":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-path/index.js","compact-encoding":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/compact-encoding/index.js","sodium-universal":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/sodium-universal/index.js"},"/node_modules/pgh/node_modules/hyper-overlay/lib/tree.js":{"#fs":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-fs/index.js","#package":"/node_modules/pgh/node_modules/hyper-overlay/package.json","#path":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-path/index.js","compact-encoding":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/compact-encoding/index.js","hypercore-crypto":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/hypercore-crypto/index.js"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/b4a/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/b4a/package.json"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/b4a/package.json":{},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-ansi-escapes/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-ansi-escapes/package.json"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-ansi-escapes/package.json":{},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-assert/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-assert/package.json","bare-inspect":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-inspect/index.js"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-assert/package.json":{},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-events/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-events/package.json","./lib/errors":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-events/lib/errors.js"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-events/lib/errors.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-events/package.json"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-events/package.json":{},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-fs/binding.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-fs/package.json",".":"linked:libbare-fs.4.7.2.so"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-fs/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-fs/package.json","./binding":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-fs/binding.js","./lib/constants":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-fs/lib/constants.js","./lib/errors":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-fs/lib/errors.js","./promises":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-fs/promises.js","bare-events":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-events/index.js","bare-path":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-path/index.js","bare-stream":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-stream/index.js","bare-url":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-url/index.js","fast-fifo":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/fast-fifo/index.js"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-fs/lib/constants.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-fs/package.json","../binding":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-fs/binding.js"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-fs/lib/errors.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-fs/package.json","bare-os":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-os/index.js"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-fs/package.json":{},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-fs/promises.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-fs/package.json",".":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-fs/index.js","bare-events":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-events/index.js"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-inspect/binding.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-inspect/package.json",".":"linked:libbare-inspect.3.1.4.so"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-inspect/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-inspect/package.json","./binding":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-inspect/binding.js","bare-ansi-escapes":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-ansi-escapes/index.js","bare-type":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-type/index.js"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-inspect/package.json":{},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-os/binding.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-os/package.json",".":"linked:libbare-os.3.9.1.so"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-os/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-os/package.json","./binding":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-os/binding.js","./lib/constants":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-os/lib/constants.js","./lib/errors":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-os/lib/errors.js"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-os/lib/constants.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-os/package.json","../binding":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-os/binding.js"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-os/lib/errors.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-os/package.json"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-os/package.json":{},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-path/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-path/package.json","./lib/posix":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-path/lib/posix.js","./lib/win32":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-path/lib/win32.js"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-path/lib/constants.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-path/package.json"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-path/lib/posix.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-path/package.json","./constants":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-path/lib/constants.js","./shared":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-path/lib/shared.js","./win32":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-path/lib/win32.js","bare-os":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-os/index.js"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-path/lib/shared.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-path/package.json","./constants":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-path/lib/constants.js"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-path/lib/win32.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-path/package.json","./constants":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-path/lib/constants.js","./posix":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-path/lib/posix.js","./shared":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-path/lib/shared.js","bare-os":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-os/index.js"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-path/package.json":{},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-stream/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-stream/package.json","./web":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-stream/web.js","b4a":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/b4a/index.js","streamx":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/streamx/index.js"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-stream/package.json":{},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-stream/web.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-stream/package.json","streamx":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/streamx/index.js","teex":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/teex/index.js"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-type/binding.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-type/package.json",".":"linked:libbare-type.1.1.0.so"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-type/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-type/package.json","./binding":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-type/binding.js"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-type/package.json":{},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-url/binding.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-url/package.json",".":"linked:libbare-url.2.4.5.so"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-url/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-url/package.json","./binding":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-url/binding.js","./lib/errors":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-url/lib/errors.js","./lib/url-search-params":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-url/lib/url-search-params.js","bare-path":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-path/index.js"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-url/lib/errors.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-url/package.json"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-url/lib/url-search-params.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-url/package.json"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-url/package.json":{},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/codecs/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/codecs/package.json","b4a":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/codecs/package.json":{},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/compact-encoding/package.json"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/compact-encoding/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/compact-encoding/package.json","./endian":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/compact-encoding/raw.js","b4a":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/compact-encoding/package.json"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/compact-encoding/package.json":{},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/compact-encoding/package.json","./endian":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/compact-encoding/endian.js","b4a":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/debounceify/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/debounceify/package.json"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/debounceify/package.json":{},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/events-universal/bare.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/events-universal/package.json","bare-events":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-events/index.js"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/events-universal/package.json":{},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/fast-fifo/fixed-size.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/fast-fifo/package.json"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/fast-fifo/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/fast-fifo/package.json","./fixed-size":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/fast-fifo/fixed-size.js"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/fast-fifo/package.json":{},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/hyperbee/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/hyperbee/package.json","./iterators/diff":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/hyperbee/iterators/diff.js","./iterators/history":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/hyperbee/iterators/history.js","./iterators/local":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/hyperbee/iterators/local.js","./iterators/range":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/hyperbee/iterators/range.js","./lib/extension":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/hyperbee/lib/extension.js","./lib/messages":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/hyperbee/lib/messages.js","b4a":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/b4a/index.js","codecs":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/codecs/index.js","debounceify":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/debounceify/index.js","hypercore-errors":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/hypercore-errors/index.js","mutexify/promise":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/mutexify/promise.js","rache":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/rache/index.js","ready-resource":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/ready-resource/index.js","resolve-reject-promise":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/resolve-reject-promise/index.js","safety-catch":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/safety-catch/index.js","streamx":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/streamx/index.js","unslab":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/unslab/index.js"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/hyperbee/iterators/diff.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/hyperbee/package.json","b4a":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/hyperbee/iterators/history.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/hyperbee/package.json"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/hyperbee/iterators/local.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/hyperbee/package.json"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/hyperbee/iterators/range.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/hyperbee/package.json","b4a":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/hyperbee/lib/extension.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/hyperbee/package.json","./messages":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/hyperbee/lib/messages.js"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/hyperbee/lib/messages.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/hyperbee/package.json","b4a":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/b4a/index.js","protocol-buffers-encodings":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/protocol-buffers-encodings/index.js"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/hyperbee/package.json":{},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/hypercore-crypto/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/hypercore-crypto/package.json","b4a":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/b4a/index.js","compact-encoding":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/compact-encoding/index.js","sodium-universal":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/sodium-universal/index.js"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/hypercore-crypto/package.json":{},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/hypercore-errors/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/hypercore-errors/package.json","hypercore-id-encoding":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/hypercore-id-encoding/index.js"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/hypercore-errors/package.json":{},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/hypercore-id-encoding/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/hypercore-id-encoding/package.json","b4a":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/b4a/index.js","z32":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/z32/index.js"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/hypercore-id-encoding/package.json":{},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/mutexify/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/mutexify/package.json","queue-tick":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/queue-tick/process-next-tick.js"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/mutexify/package.json":{},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/mutexify/promise.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/mutexify/package.json",".":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/mutexify/index.js"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/protocol-buffers-encodings/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/protocol-buffers-encodings/package.json","b4a":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/b4a/index.js","signed-varint":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/signed-varint/index.js","varint":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/varint/index.js"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/protocol-buffers-encodings/package.json":{},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/queue-tick/package.json":{},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/queue-tick/process-next-tick.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/queue-tick/package.json","./queue-microtask":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/queue-tick/queue-microtask.js"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/queue-tick/queue-microtask.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/queue-tick/package.json"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/rache/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/rache/package.json"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/rache/package.json":{},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/ready-resource/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/ready-resource/package.json","events":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-events/index.js"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/ready-resource/package.json":{},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/require-addon/lib/bare.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/require-addon/package.json"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/require-addon/package.json":{},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/resolve-reject-promise/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/resolve-reject-promise/package.json"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/resolve-reject-promise/package.json":{},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/safety-catch/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/safety-catch/package.json"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/safety-catch/package.json":{},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/signed-varint/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/signed-varint/package.json","varint":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/varint/index.js"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/signed-varint/package.json":{},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/sodium-native/binding.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/sodium-native/package.json",".":"linked:libsodium-native.5.1.0.so","require-addon":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/require-addon/lib/bare.js"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/sodium-native/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/sodium-native/package.json","./binding":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/sodium-native/binding.js","assert":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-assert/index.js","which-runtime":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/which-runtime/index.js"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/sodium-native/package.json":{},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/sodium-universal/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/sodium-universal/package.json","sodium-native":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/sodium-native/index.js"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/sodium-universal/package.json":{},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/streamx/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/streamx/package.json","./lib/errors.js":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/streamx/lib/errors.js","events-universal":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/events-universal/bare.js","fast-fifo":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/fast-fifo/index.js","text-decoder":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/text-decoder/index.js"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/streamx/lib/errors.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/streamx/package.json"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/streamx/package.json":{},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/teex/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/teex/package.json","streamx":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/streamx/index.js"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/teex/package.json":{},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/text-decoder/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/text-decoder/package.json","./lib/pass-through-decoder":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/text-decoder/lib/pass-through-decoder.js","./lib/utf8-decoder":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/text-decoder/lib/utf8-decoder.js"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/text-decoder/lib/pass-through-decoder.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/text-decoder/package.json","b4a":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/text-decoder/lib/utf8-decoder.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/text-decoder/package.json","b4a":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/text-decoder/package.json":{},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/unslab/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/unslab/package.json","b4a":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/unslab/package.json":{},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/varint/decode.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/varint/package.json"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/varint/encode.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/varint/package.json"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/varint/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/varint/package.json","./decode.js":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/varint/decode.js","./encode.js":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/varint/encode.js","./length.js":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/varint/length.js"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/varint/length.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/varint/package.json"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/varint/package.json":{},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/which-runtime/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/which-runtime/package.json"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/which-runtime/package.json":{},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/z32/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/z32/package.json","b4a":"/node_modules/pgh/node_modules/hyper-overlay/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/z32/package.json":{},"/node_modules/pgh/node_modules/hyper-overlay/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/package.json","./lib/client.js":"/node_modules/pgh/node_modules/hyper-svc/lib/client.js","./lib/frame.js":"/node_modules/pgh/node_modules/hyper-svc/lib/frame.js","./lib/service.js":"/node_modules/pgh/node_modules/hyper-svc/lib/service.js","./lib/transports/swarm-rpc.js":"/node_modules/pgh/node_modules/hyper-svc/lib/transports/swarm-rpc.js"},"/node_modules/pgh/node_modules/hyper-svc/lib/client.js":{"#node:fs/promises":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-fs/promises.js","#node:http":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http1/index.js","#node:url":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-url/index.js","#package":"/node_modules/pgh/node_modules/hyper-svc/package.json","./frame.js":"/node_modules/pgh/node_modules/hyper-svc/lib/frame.js","./transports/swarm-rpc.js":"/node_modules/pgh/node_modules/hyper-svc/lib/transports/swarm-rpc.js","./uds-backend.js":"/node_modules/pgh/node_modules/hyper-svc/lib/uds-backend.js","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js","hypercore-crypto":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hypercore-crypto/index.js","hyperswarm":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperswarm/index.js","protomux":"/node_modules/pgh/node_modules/hyper-svc/node_modules/protomux/index.js"},"/node_modules/pgh/node_modules/hyper-svc/lib/frame.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/package.json","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/hyper-svc/lib/service.js":{"#node:process":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-process/index.js","#package":"/node_modules/pgh/node_modules/hyper-svc/package.json","./transports/http.js":"/node_modules/pgh/node_modules/hyper-svc/lib/transports/http.js","./transports/swarm.js":"/node_modules/pgh/node_modules/hyper-svc/lib/transports/swarm.js","./transports/uds.js":"/node_modules/pgh/node_modules/hyper-svc/lib/transports/uds.js","ready-resource":"/node_modules/pgh/node_modules/hyper-svc/node_modules/ready-resource/index.js"},"/node_modules/pgh/node_modules/hyper-svc/lib/transports/http.js":{"#node:http":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http1/index.js","#package":"/node_modules/pgh/node_modules/hyper-svc/package.json","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/hyper-svc/lib/transports/swarm-rpc.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/package.json","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js","compact-encoding":"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding/index.js","protomux":"/node_modules/pgh/node_modules/hyper-svc/node_modules/protomux/index.js"},"/node_modules/pgh/node_modules/hyper-svc/lib/transports/swarm.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/package.json","./swarm-rpc.js":"/node_modules/pgh/node_modules/hyper-svc/lib/transports/swarm-rpc.js","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js","hyperswarm":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperswarm/index.js","protomux":"/node_modules/pgh/node_modules/hyper-svc/node_modules/protomux/index.js"},"/node_modules/pgh/node_modules/hyper-svc/lib/transports/uds.js":{"#node:fs/promises":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-fs/promises.js","#node:process":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-process/index.js","#package":"/node_modules/pgh/node_modules/hyper-svc/package.json","../frame.js":"/node_modules/pgh/node_modules/hyper-svc/lib/frame.js","../uds-backend.js":"/node_modules/pgh/node_modules/hyper-svc/lib/uds-backend.js"},"/node_modules/pgh/node_modules/hyper-svc/lib/uds-backend.js":{"#node:net":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-net/index.js","#package":"/node_modules/pgh/node_modules/hyper-svc/package.json","bare-abstract-socket":"deferred:bare-abstract-socket"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/package.json","./lib/bridge":"/node_modules/pgh/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/lib/bridge.js","./lib/handshake":"/node_modules/pgh/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/lib/handshake.js","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js","hypercore-crypto":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hypercore-crypto/index.js","sodium-secretstream":"/node_modules/pgh/node_modules/hyper-svc/node_modules/sodium-secretstream/index.js","sodium-universal":"/node_modules/pgh/node_modules/hyper-svc/node_modules/sodium-universal/index.js","streamx":"/node_modules/pgh/node_modules/hyper-svc/node_modules/streamx/index.js","timeout-refresh":"/node_modules/pgh/node_modules/hyper-svc/node_modules/timeout-refresh/index.js","unslab":"/node_modules/pgh/node_modules/hyper-svc/node_modules/unslab/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/lib/bridge.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/package.json","streamx":"/node_modules/pgh/node_modules/hyper-svc/node_modules/streamx/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/lib/handshake.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/package.json","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js","noise-curve-ed":"/node_modules/pgh/node_modules/hyper-svc/node_modules/noise-curve-ed/index.js","noise-handshake":"/node_modules/pgh/node_modules/hyper-svc/node_modules/noise-handshake/noise.js","sodium-universal":"/node_modules/pgh/node_modules/hyper-svc/node_modules/sodium-universal/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/adaptive-timeout/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/adaptive-timeout/package.json","xache":"/node_modules/pgh/node_modules/hyper-svc/node_modules/xache/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/adaptive-timeout/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-abort/binding.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-abort/package.json",".":"linked:libbare-abort.2.0.13.so"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-abort/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-abort/package.json","./binding":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-abort/binding.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-abort/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-ansi-escapes/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-ansi-escapes/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-ansi-escapes/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-assert/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-assert/package.json","bare-inspect":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-inspect/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-assert/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-dns/binding.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-dns/package.json",".":"linked:libbare-dns.2.1.4.so"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-dns/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-dns/package.json","./binding":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-dns/binding.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-dns/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-env/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-env/package.json","bare-os":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-os/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-env/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-events/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-events/package.json","./lib/errors":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-events/lib/errors.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-events/lib/errors.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-events/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-events/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-fs/binding.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-fs/package.json",".":"linked:libbare-fs.4.7.2.so"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-fs/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-fs/package.json","./binding":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-fs/binding.js","./lib/constants":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-fs/lib/constants.js","./lib/errors":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-fs/lib/errors.js","./promises":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-fs/promises.js","bare-events":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-events/index.js","bare-path":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-path/index.js","bare-stream":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-stream/index.js","bare-url":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-url/index.js","fast-fifo":"/node_modules/pgh/node_modules/hyper-svc/node_modules/fast-fifo/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-fs/lib/constants.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-fs/package.json","../binding":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-fs/binding.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-fs/lib/errors.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-fs/package.json","bare-os":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-os/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-fs/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-fs/promises.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-fs/package.json",".":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-fs/index.js","bare-events":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-events/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-hrtime/binding.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-hrtime/package.json",".":"linked:libbare-hrtime.2.1.1.so"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-hrtime/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-hrtime/package.json","./binding":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-hrtime/binding.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-hrtime/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http-parser/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http-parser/package.json","./lib/errors":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http-parser/lib/errors.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http-parser/lib/errors.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http-parser/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http-parser/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http1/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http1/package.json","./lib/agent":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http1/lib/agent.js","./lib/client-connection":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http1/lib/client-connection.js","./lib/client-request":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http1/lib/client-request.js","./lib/constants":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http1/lib/constants.js","./lib/errors":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http1/lib/errors.js","./lib/incoming-message":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http1/lib/incoming-message.js","./lib/outgoing-message":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http1/lib/outgoing-message.js","./lib/server":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http1/lib/server.js","./lib/server-connection":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http1/lib/server-connection.js","./lib/server-response":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http1/lib/server-response.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http1/lib/agent.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http1/package.json","./client-connection":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http1/lib/client-connection.js","./errors":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http1/lib/errors.js","bare-events":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-events/index.js","bare-tcp":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-tcp/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http1/lib/client-connection.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http1/package.json","./errors":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http1/lib/errors.js","./incoming-message":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http1/lib/incoming-message.js","bare-http-parser":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http-parser/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http1/lib/client-request.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http1/package.json","./agent":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http1/lib/agent.js","./outgoing-message":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http1/lib/outgoing-message.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http1/lib/constants.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http1/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http1/lib/errors.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http1/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http1/lib/incoming-message.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http1/package.json","bare-stream":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-stream/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http1/lib/outgoing-message.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http1/package.json","./errors":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http1/lib/errors.js","bare-stream":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-stream/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http1/lib/server-connection.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http1/package.json","./incoming-message":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http1/lib/incoming-message.js","./server-response":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http1/lib/server-response.js","bare-http-parser":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http-parser/index.js","bare-stream":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-stream/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http1/lib/server-response.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http1/package.json","./constants":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http1/lib/constants.js","./outgoing-message":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http1/lib/outgoing-message.js","bare-stream":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-stream/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http1/lib/server.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http1/package.json","./server-connection":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http1/lib/server-connection.js","bare-tcp":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-tcp/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http1/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-inspect/binding.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-inspect/package.json",".":"linked:libbare-inspect.3.1.4.so"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-inspect/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-inspect/package.json","./binding":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-inspect/binding.js","bare-ansi-escapes":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-ansi-escapes/index.js","bare-type":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-type/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-inspect/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-net/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-net/package.json","bare-events":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-events/index.js","bare-pipe":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/index.js","bare-stream":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-stream/index.js","bare-tcp":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-dns/binding.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-dns/package.json",".":"linked:libbare-dns.1.0.5.so"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-dns/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-dns/package.json","./binding":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-dns/binding.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-dns/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/binding.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/package.json",".":"linked:libbare-pipe.3.3.8.so"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/package.json","./binding":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/binding.js","./lib/constants":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/lib/constants.js","./lib/errors":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/lib/errors.js","bare-events":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-events/index.js","bare-stream":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-stream/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/lib/constants.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/lib/errors.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/binding.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/package.json",".":"linked:libbare-tcp.1.9.1.so"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/package.json","./binding":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/binding.js","./lib/constants":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/lib/constants.js","./lib/errors":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/lib/errors.js","./lib/ip":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/lib/ip.js","bare-dns":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-dns/index.js","bare-events":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-events/index.js","bare-stream":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-stream/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/lib/constants.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/lib/errors.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/lib/ip.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-net/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-os/binding.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-os/package.json",".":"linked:libbare-os.3.9.1.so"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-os/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-os/package.json","./binding":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-os/binding.js","./lib/constants":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-os/lib/constants.js","./lib/errors":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-os/lib/errors.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-os/lib/constants.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-os/package.json","../binding":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-os/binding.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-os/lib/errors.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-os/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-os/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-path/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-path/package.json","./lib/posix":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-path/lib/posix.js","./lib/win32":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-path/lib/win32.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-path/lib/constants.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-path/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-path/lib/posix.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-path/package.json","./constants":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-path/lib/constants.js","./shared":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-path/lib/shared.js","./win32":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-path/lib/win32.js","bare-os":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-os/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-path/lib/shared.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-path/package.json","./constants":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-path/lib/constants.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-path/lib/win32.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-path/package.json","./constants":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-path/lib/constants.js","./posix":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-path/lib/posix.js","./shared":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-path/lib/shared.js","bare-os":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-os/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-path/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-pipe/binding.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-pipe/package.json",".":"linked:libbare-pipe.4.1.5.so"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-pipe/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-pipe/package.json","./binding":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-pipe/binding.js","./lib/constants":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-pipe/lib/constants.js","./lib/errors":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-pipe/lib/errors.js","bare-events":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-events/index.js","bare-stream":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-stream/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-pipe/lib/constants.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-pipe/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-pipe/lib/errors.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-pipe/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-pipe/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-process/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-process/package.json","bare-abort":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-abort/index.js","bare-env":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-env/index.js","bare-events":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-events/index.js","bare-hrtime":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-hrtime/index.js","bare-os":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-os/index.js","bare-signals":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-signals/index.js","bare-stdio":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-stdio/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-process/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-signals/binding.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-signals/package.json",".":"linked:libbare-signals.4.2.0.so"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-signals/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-signals/package.json","./binding":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-signals/binding.js","./lib/emitter":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-signals/lib/emitter.js","./lib/errors":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-signals/lib/errors.js","bare-events":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-events/index.js","bare-os":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-os/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-signals/lib/emitter.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-signals/package.json","..":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-signals/index.js","bare-events":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-events/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-signals/lib/errors.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-signals/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-signals/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-stdio/binding.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-stdio/package.json",".":"linked:libbare-stdio.1.0.2.so"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-stdio/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-stdio/package.json","./binding":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-stdio/binding.js","bare-fs":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-fs/index.js","bare-pipe":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-pipe/index.js","bare-tty":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-tty/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-stdio/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-stream/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-stream/package.json","./web":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-stream/web.js","streamx":"/node_modules/pgh/node_modules/hyper-svc/node_modules/streamx/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-stream/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-stream/web.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-stream/package.json","streamx":"/node_modules/pgh/node_modules/hyper-svc/node_modules/streamx/index.js","teex":"/node_modules/pgh/node_modules/hyper-svc/node_modules/teex/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-tcp/binding.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-tcp/package.json",".":"linked:libbare-tcp.2.2.12.so"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-tcp/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-tcp/package.json","./binding":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-tcp/binding.js","./lib/constants":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-tcp/lib/constants.js","./lib/errors":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-tcp/lib/errors.js","./lib/ip":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-tcp/lib/ip.js","bare-dns":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-dns/index.js","bare-events":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-events/index.js","bare-stream":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-stream/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-tcp/lib/constants.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-tcp/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-tcp/lib/errors.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-tcp/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-tcp/lib/ip.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-tcp/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-tcp/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-tty/binding.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-tty/package.json",".":"linked:libbare-tty.5.1.0.so"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-tty/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-tty/package.json","./binding":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-tty/binding.js","./lib/constants":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-tty/lib/constants.js","bare-signals":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-signals/index.js","bare-stream":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-stream/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-tty/lib/constants.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-tty/package.json","../binding":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-tty/binding.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-tty/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-type/binding.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-type/package.json",".":"linked:libbare-type.1.1.0.so"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-type/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-type/package.json","./binding":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-type/binding.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-type/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-url/binding.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-url/package.json",".":"linked:libbare-url.2.4.2.so"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-url/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-url/package.json","./binding":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-url/binding.js","./lib/errors":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-url/lib/errors.js","./lib/url-search-params":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-url/lib/url-search-params.js","bare-path":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-path/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-url/lib/errors.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-url/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-url/lib/url-search-params.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-url/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-url/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bits-to-bytes/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bits-to-bytes/package.json","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bits-to-bytes/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/blind-relay/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/blind-relay/package.json","./lib/errors":"/node_modules/pgh/node_modules/hyper-svc/node_modules/blind-relay/lib/errors.js","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js","bits-to-bytes":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bits-to-bytes/index.js","compact-encoding":"/node_modules/pgh/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/index.js","compact-encoding-bitfield":"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/index.js","events":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-events/index.js","protomux":"/node_modules/pgh/node_modules/hyper-svc/node_modules/protomux/index.js","sodium-universal":"/node_modules/pgh/node_modules/hyper-svc/node_modules/sodium-universal/index.js","streamx":"/node_modules/pgh/node_modules/hyper-svc/node_modules/streamx/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/blind-relay/lib/errors.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/blind-relay/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/package.json","./endian":"/node_modules/pgh/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/pgh/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/pgh/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/raw.js","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/package.json","./endian":"/node_modules/pgh/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/endian.js","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/blind-relay/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bogon/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bogon/package.json","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js","compact-encoding":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/index.js","compact-encoding-net":"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding-net/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/package.json","./endian":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/raw.js","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/package.json","./endian":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/endian.js","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bogon/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/package.json","compact-encoding":"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/package.json","./endian":"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/raw.js","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/package.json","./endian":"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/endian.js","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding-net/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding-net/package.json","compact-encoding":"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/package.json","./endian":"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/raw.js","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/package.json","./endian":"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/endian.js","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding-net/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding/package.json","./endian":"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding/raw.js","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding/package.json","./endian":"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding/endian.js","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/dht-rpc/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/dht-rpc/package.json","./lib/commands":"/node_modules/pgh/node_modules/hyper-svc/node_modules/dht-rpc/lib/commands.js","./lib/errors":"/node_modules/pgh/node_modules/hyper-svc/node_modules/dht-rpc/lib/errors.js","./lib/health":"/node_modules/pgh/node_modules/hyper-svc/node_modules/dht-rpc/lib/health.js","./lib/io":"/node_modules/pgh/node_modules/hyper-svc/node_modules/dht-rpc/lib/io.js","./lib/peer":"/node_modules/pgh/node_modules/hyper-svc/node_modules/dht-rpc/lib/peer.js","./lib/query":"/node_modules/pgh/node_modules/hyper-svc/node_modules/dht-rpc/lib/query.js","./lib/session":"/node_modules/pgh/node_modules/hyper-svc/node_modules/dht-rpc/lib/session.js","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js","compact-encoding":"/node_modules/pgh/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/index.js","events":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-events/index.js","kademlia-routing-table":"/node_modules/pgh/node_modules/hyper-svc/node_modules/kademlia-routing-table/index.js","nat-sampler":"/node_modules/pgh/node_modules/hyper-svc/node_modules/nat-sampler/index.js","sodium-universal":"/node_modules/pgh/node_modules/hyper-svc/node_modules/sodium-universal/index.js","time-ordered-set":"/node_modules/pgh/node_modules/hyper-svc/node_modules/time-ordered-set/index.js","udx-native":"/node_modules/pgh/node_modules/hyper-svc/node_modules/udx-native/lib/udx.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/dht-rpc/lib/commands.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/dht-rpc/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/dht-rpc/lib/errors.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/dht-rpc/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/dht-rpc/lib/health.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/dht-rpc/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/dht-rpc/lib/io.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/dht-rpc/package.json","./errors":"/node_modules/pgh/node_modules/hyper-svc/node_modules/dht-rpc/lib/errors.js","./peer":"/node_modules/pgh/node_modules/hyper-svc/node_modules/dht-rpc/lib/peer.js","adaptive-timeout":"/node_modules/pgh/node_modules/hyper-svc/node_modules/adaptive-timeout/index.js","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js","compact-encoding":"/node_modules/pgh/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/index.js","fast-fifo":"/node_modules/pgh/node_modules/hyper-svc/node_modules/fast-fifo/index.js","sodium-universal":"/node_modules/pgh/node_modules/hyper-svc/node_modules/sodium-universal/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/dht-rpc/lib/peer.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/dht-rpc/package.json","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js","compact-encoding":"/node_modules/pgh/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/index.js","compact-encoding-net":"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding-net/index.js","sodium-universal":"/node_modules/pgh/node_modules/hyper-svc/node_modules/sodium-universal/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/dht-rpc/lib/query.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/dht-rpc/package.json","./commands":"/node_modules/pgh/node_modules/hyper-svc/node_modules/dht-rpc/lib/commands.js","./peer":"/node_modules/pgh/node_modules/hyper-svc/node_modules/dht-rpc/lib/peer.js","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js","streamx":"/node_modules/pgh/node_modules/hyper-svc/node_modules/streamx/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/dht-rpc/lib/session.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/dht-rpc/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/package.json","./endian":"/node_modules/pgh/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/pgh/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/pgh/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/raw.js","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/package.json","./endian":"/node_modules/pgh/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/endian.js","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/dht-rpc/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/events-universal/bare.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/events-universal/package.json","bare-events":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-events/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/events-universal/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/fast-fifo/fixed-size.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/fast-fifo/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/fast-fifo/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/fast-fifo/package.json","./fixed-size":"/node_modules/pgh/node_modules/hyper-svc/node_modules/fast-fifo/fixed-size.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/fast-fifo/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hypercore-crypto/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hypercore-crypto/package.json","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js","compact-encoding":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/index.js","sodium-universal":"/node_modules/pgh/node_modules/hyper-svc/node_modules/sodium-universal/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/package.json","./endian":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/raw.js","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/package.json","./endian":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/endian.js","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hypercore-crypto/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hypercore-id-encoding/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hypercore-id-encoding/package.json","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js","z32":"/node_modules/pgh/node_modules/hyper-svc/node_modules/z32/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hypercore-id-encoding/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht-address/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht-address/package.json","./spec/hyperschema":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht-address/spec/hyperschema/index.js","compact-encoding":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/package.json","./endian":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/raw.js","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/package.json","./endian":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/endian.js","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht-address/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht-address/spec/hyperschema/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht-address/package.json","hyperschema/runtime":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperschema/runtime.cjs"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/package.json","./lib/connect":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/connect.js","./lib/connection-pool":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/connection-pool.js","./lib/constants":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/constants.js","./lib/crypto":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/crypto.js","./lib/errors":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/errors.js","./lib/messages":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/messages.js","./lib/persistent":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/persistent.js","./lib/raw-stream-set":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/raw-stream-set.js","./lib/router":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/router.js","./lib/server":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/server.js","./lib/socket-pool":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/socket-pool.js","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js","compact-encoding":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/index.js","dht-rpc":"/node_modules/pgh/node_modules/hyper-svc/node_modules/dht-rpc/index.js","safety-catch":"/node_modules/pgh/node_modules/hyper-svc/node_modules/safety-catch/index.js","sodium-universal":"/node_modules/pgh/node_modules/hyper-svc/node_modules/sodium-universal/index.js","xache":"/node_modules/pgh/node_modules/hyper-svc/node_modules/xache/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/announcer.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/package.json","./constants":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/constants.js","./encode":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/encode.js","./messages":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/messages.js","./persistent":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/persistent.js","./sleeper":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/sleeper.js","compact-encoding":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/index.js","safety-catch":"/node_modules/pgh/node_modules/hyper-svc/node_modules/safety-catch/index.js","signal-promise":"/node_modules/pgh/node_modules/hyper-svc/node_modules/signal-promise/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/connect.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/package.json","./constants":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/constants.js","./crypto":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/crypto.js","./errors":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/errors.js","./holepuncher":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/holepuncher.js","./noise-wrap":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/noise-wrap.js","./secure-payload":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/secure-payload.js","./semaphore":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/semaphore.js","./sleeper":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/sleeper.js","@hyperswarm/secret-stream":"/node_modules/pgh/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/index.js","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js","blind-relay":"/node_modules/pgh/node_modules/hyper-svc/node_modules/blind-relay/index.js","bogon":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bogon/index.js","hypercore-id-encoding":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hypercore-id-encoding/index.js","hyperdht-address":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht-address/index.js","safety-catch":"/node_modules/pgh/node_modules/hyper-svc/node_modules/safety-catch/index.js","unslab":"/node_modules/pgh/node_modules/hyper-svc/node_modules/unslab/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/connection-pool.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/package.json","./errors":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/errors.js","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js","events":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-events/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/constants.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/package.json","hypercore-crypto":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hypercore-crypto/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/crypto.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/package.json","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js","sodium-universal":"/node_modules/pgh/node_modules/hyper-svc/node_modules/sodium-universal/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/encode.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/package.json","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js","compact-encoding":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/errors.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/holepuncher.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/package.json","./constants":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/constants.js","./nat":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/nat.js","./sleeper":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/sleeper.js","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/messages.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/package.json","compact-encoding":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/nat.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/package.json","../lib/constants":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/constants.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/noise-wrap.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/package.json","./constants":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/constants.js","./errors":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/errors.js","./messages":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/messages.js","@hyperswarm/secret-stream":"/node_modules/pgh/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/index.js","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js","compact-encoding":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/index.js","noise-curve-ed":"/node_modules/pgh/node_modules/hyper-svc/node_modules/noise-curve-ed/index.js","noise-handshake":"/node_modules/pgh/node_modules/hyper-svc/node_modules/noise-handshake/noise.js","sodium-universal":"/node_modules/pgh/node_modules/hyper-svc/node_modules/sodium-universal/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/persistent.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/package.json","./constants":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/constants.js","./encode":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/encode.js","./messages":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/messages.js","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js","compact-encoding":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/index.js","record-cache":"/node_modules/pgh/node_modules/hyper-svc/node_modules/record-cache/index.js","sodium-universal":"/node_modules/pgh/node_modules/hyper-svc/node_modules/sodium-universal/index.js","unslab":"/node_modules/pgh/node_modules/hyper-svc/node_modules/unslab/index.js","xache":"/node_modules/pgh/node_modules/hyper-svc/node_modules/xache/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/raw-stream-set.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/router.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/package.json","./constants":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/constants.js","./errors":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/errors.js","./messages":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/messages.js","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js","compact-encoding":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/index.js","safety-catch":"/node_modules/pgh/node_modules/hyper-svc/node_modules/safety-catch/index.js","xache":"/node_modules/pgh/node_modules/hyper-svc/node_modules/xache/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/secure-payload.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/package.json","./messages":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/messages.js","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js","sodium-universal":"/node_modules/pgh/node_modules/hyper-svc/node_modules/sodium-universal/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/semaphore.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/server.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/package.json","./announcer":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/announcer.js","./constants":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/constants.js","./crypto":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/crypto.js","./errors":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/errors.js","./holepuncher":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/holepuncher.js","./noise-wrap":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/noise-wrap.js","./secure-payload":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/secure-payload.js","@hyperswarm/secret-stream":"/node_modules/pgh/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/index.js","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js","blind-relay":"/node_modules/pgh/node_modules/hyper-svc/node_modules/blind-relay/index.js","bogon":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bogon/index.js","events":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-events/index.js","safety-catch":"/node_modules/pgh/node_modules/hyper-svc/node_modules/safety-catch/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/sleeper.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/socket-pool.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/package.json","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/package.json","./endian":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/raw.js","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/package.json","./endian":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/endian.js","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/endian.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/package.json","./endian":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/endian.js","./lexint":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/lexint.js","./raw":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/raw.js","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/lexint.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/raw.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/package.json","./endian":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/endian.js","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperschema/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperschema/runtime.cjs":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperschema/package.json","compact-encoding":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperswarm/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperswarm/package.json","./lib/connection-set":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperswarm/lib/connection-set.js","./lib/peer-discovery":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperswarm/lib/peer-discovery.js","./lib/peer-info":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperswarm/lib/peer-info.js","./lib/retry-timer":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperswarm/lib/retry-timer.js","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js","events":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-events/index.js","hyperdht":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/index.js","shuffled-priority-queue":"/node_modules/pgh/node_modules/hyper-svc/node_modules/shuffled-priority-queue/index.js","streamx":"/node_modules/pgh/node_modules/hyper-svc/node_modules/streamx/index.js","unslab":"/node_modules/pgh/node_modules/hyper-svc/node_modules/unslab/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperswarm/lib/bulk-timer.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperswarm/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperswarm/lib/connection-set.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperswarm/package.json","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperswarm/lib/peer-discovery.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperswarm/package.json","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js","safety-catch":"/node_modules/pgh/node_modules/hyper-svc/node_modules/safety-catch/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperswarm/lib/peer-info.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperswarm/package.json","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js","events":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-events/index.js","unslab":"/node_modules/pgh/node_modules/hyper-svc/node_modules/unslab/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperswarm/lib/retry-timer.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperswarm/package.json","./bulk-timer":"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperswarm/lib/bulk-timer.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperswarm/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/kademlia-routing-table/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/kademlia-routing-table/package.json","events":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-events/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/kademlia-routing-table/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/nanoassert/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/nanoassert/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/nanoassert/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/nat-sampler/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/nat-sampler/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/nat-sampler/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/noise-curve-ed/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/noise-curve-ed/package.json","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js","nanoassert":"/node_modules/pgh/node_modules/hyper-svc/node_modules/nanoassert/index.js","sodium-universal":"/node_modules/pgh/node_modules/hyper-svc/node_modules/sodium-universal/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/noise-curve-ed/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/noise-handshake/cipher.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/noise-handshake/package.json","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js","sodium-universal":"/node_modules/pgh/node_modules/hyper-svc/node_modules/sodium-universal/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/noise-handshake/dh.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/noise-handshake/package.json","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js","nanoassert":"/node_modules/pgh/node_modules/hyper-svc/node_modules/nanoassert/index.js","sodium-universal":"/node_modules/pgh/node_modules/hyper-svc/node_modules/sodium-universal/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/noise-handshake/hkdf.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/noise-handshake/package.json","./hmac":"/node_modules/pgh/node_modules/hyper-svc/node_modules/noise-handshake/hmac.js","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/noise-handshake/hmac.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/noise-handshake/package.json","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js","sodium-universal":"/node_modules/pgh/node_modules/hyper-svc/node_modules/sodium-universal/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/noise-handshake/noise.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/noise-handshake/package.json","./hkdf":"/node_modules/pgh/node_modules/hyper-svc/node_modules/noise-handshake/hkdf.js","./symmetric-state":"/node_modules/pgh/node_modules/hyper-svc/node_modules/noise-handshake/symmetric-state.js","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js","nanoassert":"/node_modules/pgh/node_modules/hyper-svc/node_modules/nanoassert/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/noise-handshake/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/noise-handshake/symmetric-state.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/noise-handshake/package.json","./cipher":"/node_modules/pgh/node_modules/hyper-svc/node_modules/noise-handshake/cipher.js","./dh":"/node_modules/pgh/node_modules/hyper-svc/node_modules/noise-handshake/dh.js","./hkdf":"/node_modules/pgh/node_modules/hyper-svc/node_modules/noise-handshake/hkdf.js","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js","nanoassert":"/node_modules/pgh/node_modules/hyper-svc/node_modules/nanoassert/index.js","sodium-universal":"/node_modules/pgh/node_modules/hyper-svc/node_modules/sodium-universal/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/protomux/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/protomux/package.json","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js","compact-encoding":"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding/index.js","queue-tick":"/node_modules/pgh/node_modules/hyper-svc/node_modules/queue-tick/process-next-tick.js","safety-catch":"/node_modules/pgh/node_modules/hyper-svc/node_modules/safety-catch/index.js","unslab":"/node_modules/pgh/node_modules/hyper-svc/node_modules/unslab/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/protomux/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/queue-tick/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/queue-tick/process-next-tick.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/queue-tick/package.json","./queue-microtask":"/node_modules/pgh/node_modules/hyper-svc/node_modules/queue-tick/queue-microtask.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/queue-tick/queue-microtask.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/queue-tick/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/ready-resource/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/ready-resource/package.json","events":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-events/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/ready-resource/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/record-cache/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/record-cache/package.json","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/record-cache/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/require-addon/lib/bare.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/require-addon/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/require-addon/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/safety-catch/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/safety-catch/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/safety-catch/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/shuffled-priority-queue/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/shuffled-priority-queue/package.json","unordered-set":"/node_modules/pgh/node_modules/hyper-svc/node_modules/unordered-set/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/shuffled-priority-queue/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/signal-promise/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/signal-promise/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/signal-promise/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/sodium-native/binding.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/sodium-native/package.json",".":"linked:libsodium-native.5.1.0.so","require-addon":"/node_modules/pgh/node_modules/hyper-svc/node_modules/require-addon/lib/bare.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/sodium-native/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/sodium-native/package.json","./binding":"/node_modules/pgh/node_modules/hyper-svc/node_modules/sodium-native/binding.js","assert":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-assert/index.js","which-runtime":"/node_modules/pgh/node_modules/hyper-svc/node_modules/which-runtime/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/sodium-native/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/sodium-secretstream/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/sodium-secretstream/package.json","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js","sodium-universal":"/node_modules/pgh/node_modules/hyper-svc/node_modules/sodium-universal/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/sodium-secretstream/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/sodium-universal/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/sodium-universal/package.json","sodium-native":"/node_modules/pgh/node_modules/hyper-svc/node_modules/sodium-native/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/sodium-universal/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/streamx/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/streamx/package.json","events-universal":"/node_modules/pgh/node_modules/hyper-svc/node_modules/events-universal/bare.js","fast-fifo":"/node_modules/pgh/node_modules/hyper-svc/node_modules/fast-fifo/index.js","text-decoder":"/node_modules/pgh/node_modules/hyper-svc/node_modules/text-decoder/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/streamx/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/teex/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/teex/package.json","streamx":"/node_modules/pgh/node_modules/hyper-svc/node_modules/streamx/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/teex/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/text-decoder/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/text-decoder/package.json","./lib/pass-through-decoder":"/node_modules/pgh/node_modules/hyper-svc/node_modules/text-decoder/lib/pass-through-decoder.js","./lib/utf8-decoder":"/node_modules/pgh/node_modules/hyper-svc/node_modules/text-decoder/lib/utf8-decoder.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/text-decoder/lib/pass-through-decoder.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/text-decoder/package.json","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/text-decoder/lib/utf8-decoder.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/text-decoder/package.json","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/text-decoder/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/time-ordered-set/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/time-ordered-set/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/time-ordered-set/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/timeout-refresh/browser.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/timeout-refresh/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/timeout-refresh/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/timeout-refresh/package.json","./browser":"/node_modules/pgh/node_modules/hyper-svc/node_modules/timeout-refresh/browser.js","./node":"/node_modules/pgh/node_modules/hyper-svc/node_modules/timeout-refresh/node.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/timeout-refresh/node.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/timeout-refresh/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/timeout-refresh/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/udx-native/binding.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/udx-native/package.json",".":"linked:libudx-native.1.19.2.so","require-addon":"/node_modules/pgh/node_modules/hyper-svc/node_modules/require-addon/lib/bare.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/udx-native/lib/ip.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/udx-native/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/udx-native/lib/network-interfaces.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/udx-native/package.json","../binding":"/node_modules/pgh/node_modules/hyper-svc/node_modules/udx-native/binding.js","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js","events":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-events/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/udx-native/lib/socket.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/udx-native/package.json","../binding":"/node_modules/pgh/node_modules/hyper-svc/node_modules/udx-native/binding.js","./ip":"/node_modules/pgh/node_modules/hyper-svc/node_modules/udx-native/lib/ip.js","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js","events":"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-events/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/udx-native/lib/stream.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/udx-native/package.json","../binding":"/node_modules/pgh/node_modules/hyper-svc/node_modules/udx-native/binding.js","./ip":"/node_modules/pgh/node_modules/hyper-svc/node_modules/udx-native/lib/ip.js","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js","streamx":"/node_modules/pgh/node_modules/hyper-svc/node_modules/streamx/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/udx-native/lib/udx.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/udx-native/package.json","../binding":"/node_modules/pgh/node_modules/hyper-svc/node_modules/udx-native/binding.js","./ip":"/node_modules/pgh/node_modules/hyper-svc/node_modules/udx-native/lib/ip.js","./network-interfaces":"/node_modules/pgh/node_modules/hyper-svc/node_modules/udx-native/lib/network-interfaces.js","./socket":"/node_modules/pgh/node_modules/hyper-svc/node_modules/udx-native/lib/socket.js","./stream":"/node_modules/pgh/node_modules/hyper-svc/node_modules/udx-native/lib/stream.js","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/udx-native/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/unordered-set/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/unordered-set/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/unordered-set/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/unslab/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/unslab/package.json","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/unslab/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/which-runtime/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/which-runtime/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/which-runtime/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/xache/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/xache/package.json"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/xache/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/node_modules/z32/index.js":{"#package":"/node_modules/pgh/node_modules/hyper-svc/node_modules/z32/package.json","b4a":"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/hyper-svc/node_modules/z32/package.json":{},"/node_modules/pgh/node_modules/hyper-svc/package.json":{},"/node_modules/pgh/node_modules/hyperbee/index.js":{"#package":"/node_modules/pgh/node_modules/hyperbee/package.json","./iterators/diff":"/node_modules/pgh/node_modules/hyperbee/iterators/diff.js","./iterators/history":"/node_modules/pgh/node_modules/hyperbee/iterators/history.js","./iterators/local":"/node_modules/pgh/node_modules/hyperbee/iterators/local.js","./iterators/range":"/node_modules/pgh/node_modules/hyperbee/iterators/range.js","./lib/extension":"/node_modules/pgh/node_modules/hyperbee/lib/extension.js","./lib/messages":"/node_modules/pgh/node_modules/hyperbee/lib/messages.js","b4a":"/node_modules/pgh/node_modules/b4a/index.js","codecs":"/node_modules/pgh/node_modules/codecs/index.js","debounceify":"/node_modules/pgh/node_modules/debounceify/index.js","hypercore-errors":"/node_modules/pgh/node_modules/hypercore-errors/index.js","mutexify/promise":"/node_modules/pgh/node_modules/mutexify/promise.js","rache":"/node_modules/pgh/node_modules/rache/index.js","ready-resource":"/node_modules/pgh/node_modules/ready-resource/index.js","resolve-reject-promise":"/node_modules/pgh/node_modules/resolve-reject-promise/index.js","safety-catch":"/node_modules/pgh/node_modules/safety-catch/index.js","streamx":"/node_modules/pgh/node_modules/streamx/index.js","unslab":"/node_modules/pgh/node_modules/unslab/index.js"},"/node_modules/pgh/node_modules/hyperbee/iterators/diff.js":{"#package":"/node_modules/pgh/node_modules/hyperbee/package.json","b4a":"/node_modules/pgh/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/hyperbee/iterators/history.js":{"#package":"/node_modules/pgh/node_modules/hyperbee/package.json"},"/node_modules/pgh/node_modules/hyperbee/iterators/local.js":{"#package":"/node_modules/pgh/node_modules/hyperbee/package.json"},"/node_modules/pgh/node_modules/hyperbee/iterators/range.js":{"#package":"/node_modules/pgh/node_modules/hyperbee/package.json","b4a":"/node_modules/pgh/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/hyperbee/lib/extension.js":{"#package":"/node_modules/pgh/node_modules/hyperbee/package.json","./messages":"/node_modules/pgh/node_modules/hyperbee/lib/messages.js"},"/node_modules/pgh/node_modules/hyperbee/lib/messages.js":{"#package":"/node_modules/pgh/node_modules/hyperbee/package.json","b4a":"/node_modules/pgh/node_modules/b4a/index.js","protocol-buffers-encodings":"/node_modules/pgh/node_modules/protocol-buffers-encodings/index.js"},"/node_modules/pgh/node_modules/hyperbee/package.json":{},"/node_modules/pgh/node_modules/hypercore-crypto/index.js":{"#package":"/node_modules/pgh/node_modules/hypercore-crypto/package.json","b4a":"/node_modules/pgh/node_modules/b4a/index.js","compact-encoding":"/node_modules/pgh/node_modules/compact-encoding/index.js","sodium-universal":"/node_modules/pgh/node_modules/sodium-universal/index.js"},"/node_modules/pgh/node_modules/hypercore-crypto/package.json":{},"/node_modules/pgh/node_modules/hypercore-errors/index.js":{"#package":"/node_modules/pgh/node_modules/hypercore-errors/package.json","hypercore-id-encoding":"/node_modules/pgh/node_modules/hypercore-id-encoding/index.js"},"/node_modules/pgh/node_modules/hypercore-errors/package.json":{},"/node_modules/pgh/node_modules/hypercore-id-encoding/index.js":{"#package":"/node_modules/pgh/node_modules/hypercore-id-encoding/package.json","b4a":"/node_modules/pgh/node_modules/b4a/index.js","z32":"/node_modules/pgh/node_modules/z32/index.js"},"/node_modules/pgh/node_modules/hypercore-id-encoding/package.json":{},"/node_modules/pgh/node_modules/hypercore-storage/encoding/external.js":{"#package":"/node_modules/pgh/node_modules/hypercore-storage/package.json"},"/node_modules/pgh/node_modules/hypercore-storage/encoding/spec/hyperschema/index.js":{"#package":"/node_modules/pgh/node_modules/hypercore-storage/package.json","../../external.js":"/node_modules/pgh/node_modules/hypercore-storage/encoding/external.js","hyperschema/runtime":"/node_modules/pgh/node_modules/hyperschema/runtime.cjs"},"/node_modules/pgh/node_modules/hypercore-storage/index.js":{"#package":"/node_modules/pgh/node_modules/hypercore-storage/package.json","./lib/keys.js":"/node_modules/pgh/node_modules/hypercore-storage/lib/keys.js","./lib/streams.js":"/node_modules/pgh/node_modules/hypercore-storage/lib/streams.js","./lib/tx.js":"/node_modules/pgh/node_modules/hypercore-storage/lib/tx.js","./lib/view.js":"/node_modules/pgh/node_modules/hypercore-storage/lib/view.js","./migrations/0":"/node_modules/pgh/node_modules/hypercore-storage/migrations/0/index.js","./migrations/1":"/node_modules/pgh/node_modules/hypercore-storage/migrations/1/index.js","device-file":"/node_modules/pgh/node_modules/device-file/index.js","fs":"/node_modules/pgh/node_modules/bare-fs/index.js","path":"/node_modules/pgh/node_modules/bare-path/index.js","resolve-reject-promise":"/node_modules/pgh/node_modules/resolve-reject-promise/index.js","rocksdb-native":"/node_modules/pgh/node_modules/rocksdb-native/index.js","scope-lock":"/node_modules/pgh/node_modules/scope-lock/index.js"},"/node_modules/pgh/node_modules/hypercore-storage/lib/block-dependency-stream.js":{"#package":"/node_modules/pgh/node_modules/hypercore-storage/package.json","./keys":"/node_modules/pgh/node_modules/hypercore-storage/lib/keys.js","streamx":"/node_modules/pgh/node_modules/streamx/index.js"},"/node_modules/pgh/node_modules/hypercore-storage/lib/close-error-stream.js":{"#package":"/node_modules/pgh/node_modules/hypercore-storage/package.json","streamx":"/node_modules/pgh/node_modules/streamx/index.js"},"/node_modules/pgh/node_modules/hypercore-storage/lib/keys.js":{"#package":"/node_modules/pgh/node_modules/hypercore-storage/package.json","b4a":"/node_modules/pgh/node_modules/b4a/index.js","compact-encoding":"/node_modules/pgh/node_modules/compact-encoding/index.js","index-encoder":"/node_modules/pgh/node_modules/index-encoder/index.js"},"/node_modules/pgh/node_modules/hypercore-storage/lib/streams.js":{"#package":"/node_modules/pgh/node_modules/hypercore-storage/package.json","../encoding/spec/hyperschema":"/node_modules/pgh/node_modules/hypercore-storage/encoding/spec/hyperschema/index.js","./block-dependency-stream.js":"/node_modules/pgh/node_modules/hypercore-storage/lib/block-dependency-stream.js","./keys.js":"/node_modules/pgh/node_modules/hypercore-storage/lib/keys.js","b4a":"/node_modules/pgh/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/hypercore-storage/lib/tx.js":{"#package":"/node_modules/pgh/node_modules/hypercore-storage/package.json","../encoding/spec/hyperschema":"/node_modules/pgh/node_modules/hypercore-storage/encoding/spec/hyperschema/index.js","./keys.js":"/node_modules/pgh/node_modules/hypercore-storage/lib/keys.js","./view.js":"/node_modules/pgh/node_modules/hypercore-storage/lib/view.js","b4a":"/node_modules/pgh/node_modules/b4a/index.js","compact-encoding":"/node_modules/pgh/node_modules/compact-encoding/index.js","flat-tree":"/node_modules/pgh/node_modules/flat-tree/index.js"},"/node_modules/pgh/node_modules/hypercore-storage/lib/view.js":{"#package":"/node_modules/pgh/node_modules/hypercore-storage/package.json","./close-error-stream.js":"/node_modules/pgh/node_modules/hypercore-storage/lib/close-error-stream.js","b4a":"/node_modules/pgh/node_modules/b4a/index.js","streamx":"/node_modules/pgh/node_modules/streamx/index.js"},"/node_modules/pgh/node_modules/hypercore-storage/migrations/0/index.js":{"#package":"/node_modules/pgh/node_modules/hypercore-storage/package.json","../../lib/tx.js":"/node_modules/pgh/node_modules/hypercore-storage/lib/tx.js","../../lib/view.js":"/node_modules/pgh/node_modules/hypercore-storage/lib/view.js","./messages.js":"/node_modules/pgh/node_modules/hypercore-storage/migrations/0/messages.js","b4a":"/node_modules/pgh/node_modules/b4a/index.js","compact-encoding":"/node_modules/pgh/node_modules/compact-encoding/index.js","flat-tree":"/node_modules/pgh/node_modules/flat-tree/index.js","fs":"/node_modules/pgh/node_modules/bare-fs/index.js","hypercore-crypto":"/node_modules/pgh/node_modules/hypercore-crypto/index.js","path":"/node_modules/pgh/node_modules/bare-path/index.js","streamx":"/node_modules/pgh/node_modules/streamx/index.js"},"/node_modules/pgh/node_modules/hypercore-storage/migrations/0/messages.js":{"#package":"/node_modules/pgh/node_modules/hypercore-storage/package.json","b4a":"/node_modules/pgh/node_modules/b4a/index.js","compact-encoding":"/node_modules/pgh/node_modules/compact-encoding/index.js"},"/node_modules/pgh/node_modules/hypercore-storage/migrations/1/index.js":{"#package":"/node_modules/pgh/node_modules/hypercore-storage/package.json","../../encoding/spec/hyperschema":"/node_modules/pgh/node_modules/hypercore-storage/encoding/spec/hyperschema/index.js","../../lib/keys.js":"/node_modules/pgh/node_modules/hypercore-storage/lib/keys.js","../../lib/tx.js":"/node_modules/pgh/node_modules/hypercore-storage/lib/tx.js","../../lib/view.js":"/node_modules/pgh/node_modules/hypercore-storage/lib/view.js","compact-encoding":"/node_modules/pgh/node_modules/compact-encoding/index.js"},"/node_modules/pgh/node_modules/hypercore-storage/package.json":{},"/node_modules/pgh/node_modules/hypercore/index.js":{"#package":"/node_modules/pgh/node_modules/hypercore/package.json","./lib/caps":"/node_modules/pgh/node_modules/hypercore/lib/caps.js","./lib/core":"/node_modules/pgh/node_modules/hypercore/lib/core.js","./lib/default-encryption":"/node_modules/pgh/node_modules/hypercore/lib/default-encryption.js","./lib/download":"/node_modules/pgh/node_modules/hypercore/lib/download.js","./lib/feature-flags":"/node_modules/pgh/node_modules/hypercore/lib/feature-flags.js","./lib/fully-remote-proof":"/node_modules/pgh/node_modules/hypercore/lib/fully-remote-proof.js","./lib/info":"/node_modules/pgh/node_modules/hypercore/lib/info.js","./lib/inspect":"/node_modules/pgh/node_modules/hypercore/lib/inspect.js","./lib/mark-bitfield":"/node_modules/pgh/node_modules/hypercore/lib/mark-bitfield.js","./lib/merkle-tree":"/node_modules/pgh/node_modules/hypercore/lib/merkle-tree.js","./lib/replicator":"/node_modules/pgh/node_modules/hypercore/lib/replicator.js","./lib/streams":"/node_modules/pgh/node_modules/hypercore/lib/streams.js","./lib/verifier":"/node_modules/pgh/node_modules/hypercore/lib/verifier.js","./lib/wants":"/node_modules/pgh/node_modules/hypercore/lib/wants.js","@hyperswarm/secret-stream":"/node_modules/pgh/node_modules/@hyperswarm/secret-stream/index.js","b4a":"/node_modules/pgh/node_modules/b4a/index.js","compact-encoding":"/node_modules/pgh/node_modules/compact-encoding/index.js","events":"/node_modules/pgh/node_modules/bare-events/index.js","flat-tree":"/node_modules/pgh/node_modules/flat-tree/index.js","hypercore-crypto":"/node_modules/pgh/node_modules/hypercore-crypto/index.js","hypercore-errors":"/node_modules/pgh/node_modules/hypercore-errors/index.js","hypercore-id-encoding":"/node_modules/pgh/node_modules/hypercore-id-encoding/index.js","hypercore-storage":"/node_modules/pgh/node_modules/hypercore-storage/index.js","is-options":"/node_modules/pgh/node_modules/is-options/index.js","nanoassert":"/node_modules/pgh/node_modules/nanoassert/index.js","protomux":"/node_modules/pgh/node_modules/protomux/index.js","safety-catch":"/node_modules/pgh/node_modules/safety-catch/index.js","unslab":"/node_modules/pgh/node_modules/unslab/index.js"},"/node_modules/pgh/node_modules/hypercore/lib/audit.js":{"#package":"/node_modules/pgh/node_modules/hypercore/package.json","./merkle-tree":"/node_modules/pgh/node_modules/hypercore/lib/merkle-tree.js","b4a":"/node_modules/pgh/node_modules/b4a/index.js","flat-tree":"/node_modules/pgh/node_modules/flat-tree/index.js","hypercore-crypto":"/node_modules/pgh/node_modules/hypercore-crypto/index.js"},"/node_modules/pgh/node_modules/hypercore/lib/bit-interlude.js":{"#package":"/node_modules/pgh/node_modules/hypercore/package.json","./compat":"/node_modules/pgh/node_modules/hypercore/lib/compat.js","b4a":"/node_modules/pgh/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/hypercore/lib/bitfield.js":{"#package":"/node_modules/pgh/node_modules/hypercore/package.json","./compat":"/node_modules/pgh/node_modules/hypercore/lib/compat.js","b4a":"/node_modules/pgh/node_modules/b4a/index.js","big-sparse-array":"/node_modules/pgh/node_modules/big-sparse-array/index.js"},"/node_modules/pgh/node_modules/hypercore/lib/caps.js":{"#package":"/node_modules/pgh/node_modules/hypercore/package.json","b4a":"/node_modules/pgh/node_modules/b4a/index.js","compact-encoding":"/node_modules/pgh/node_modules/compact-encoding/index.js","hypercore-crypto":"/node_modules/pgh/node_modules/hypercore-crypto/index.js","sodium-universal":"/node_modules/pgh/node_modules/sodium-universal/index.js"},"/node_modules/pgh/node_modules/hypercore/lib/compat.js":{"#package":"/node_modules/pgh/node_modules/hypercore/package.json","quickbit-universal":"/node_modules/pgh/node_modules/quickbit-universal/index.js","quickbit-universal/fallback":"/node_modules/pgh/node_modules/quickbit-universal/fallback.js"},"/node_modules/pgh/node_modules/hypercore/lib/copy-prologue.js":{"#package":"/node_modules/pgh/node_modules/hypercore/package.json","./bitfield":"/node_modules/pgh/node_modules/hypercore/lib/bitfield.js","b4a":"/node_modules/pgh/node_modules/b4a/index.js","flat-tree":"/node_modules/pgh/node_modules/flat-tree/index.js","hypercore-crypto":"/node_modules/pgh/node_modules/hypercore-crypto/index.js","quickbit-universal":"/node_modules/pgh/node_modules/quickbit-universal/index.js"},"/node_modules/pgh/node_modules/hypercore/lib/core.js":{"#package":"/node_modules/pgh/node_modules/hypercore/package.json","./audit":"/node_modules/pgh/node_modules/hypercore/lib/audit.js","./bit-interlude":"/node_modules/pgh/node_modules/hypercore/lib/bit-interlude.js","./bitfield":"/node_modules/pgh/node_modules/hypercore/lib/bitfield.js","./copy-prologue":"/node_modules/pgh/node_modules/hypercore/lib/copy-prologue.js","./merkle-tree":"/node_modules/pgh/node_modules/hypercore/lib/merkle-tree.js","./mutex":"/node_modules/pgh/node_modules/hypercore/lib/mutex.js","./remote-bitfield":"/node_modules/pgh/node_modules/hypercore/lib/remote-bitfield.js","./replicator":"/node_modules/pgh/node_modules/hypercore/lib/replicator.js","./session-state":"/node_modules/pgh/node_modules/hypercore/lib/session-state.js","./verifier":"/node_modules/pgh/node_modules/hypercore/lib/verifier.js","b4a":"/node_modules/pgh/node_modules/b4a/index.js","hypercore-crypto":"/node_modules/pgh/node_modules/hypercore-crypto/index.js","hypercore-errors":"/node_modules/pgh/node_modules/hypercore-errors/index.js","unslab":"/node_modules/pgh/node_modules/unslab/index.js","z32":"/node_modules/pgh/node_modules/z32/index.js"},"/node_modules/pgh/node_modules/hypercore/lib/default-encryption.js":{"#package":"/node_modules/pgh/node_modules/hypercore/package.json","./caps":"/node_modules/pgh/node_modules/hypercore/lib/caps.js","b4a":"/node_modules/pgh/node_modules/b4a/index.js","compact-encoding":"/node_modules/pgh/node_modules/compact-encoding/index.js","sodium-universal":"/node_modules/pgh/node_modules/sodium-universal/index.js"},"/node_modules/pgh/node_modules/hypercore/lib/download.js":{"#package":"/node_modules/pgh/node_modules/hypercore/package.json"},"/node_modules/pgh/node_modules/hypercore/lib/feature-flags.js":{"#package":"/node_modules/pgh/node_modules/hypercore/package.json"},"/node_modules/pgh/node_modules/hypercore/lib/fully-remote-proof.js":{"#package":"/node_modules/pgh/node_modules/hypercore/package.json","./merkle-tree.js":"/node_modules/pgh/node_modules/hypercore/lib/merkle-tree.js","./messages.js":"/node_modules/pgh/node_modules/hypercore/lib/messages.js","b4a":"/node_modules/pgh/node_modules/b4a/index.js","compact-encoding":"/node_modules/pgh/node_modules/compact-encoding/index.js","flat-tree":"/node_modules/pgh/node_modules/flat-tree/index.js","hypercore-crypto":"/node_modules/pgh/node_modules/hypercore-crypto/index.js"},"/node_modules/pgh/node_modules/hypercore/lib/hotswap-queue.js":{"#package":"/node_modules/pgh/node_modules/hypercore/package.json"},"/node_modules/pgh/node_modules/hypercore/lib/info.js":{"#package":"/node_modules/pgh/node_modules/hypercore/package.json"},"/node_modules/pgh/node_modules/hypercore/lib/inspect.js":{"#package":"/node_modules/pgh/node_modules/hypercore/package.json","b4a":"/node_modules/pgh/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/hypercore/lib/mark-bitfield.js":{"#package":"/node_modules/pgh/node_modules/hypercore/package.json","./compat":"/node_modules/pgh/node_modules/hypercore/lib/compat.js","b4a":"/node_modules/pgh/node_modules/b4a/index.js","big-sparse-array":"/node_modules/pgh/node_modules/big-sparse-array/index.js","streamx":"/node_modules/pgh/node_modules/streamx/index.js"},"/node_modules/pgh/node_modules/hypercore/lib/merkle-tree.js":{"#package":"/node_modules/pgh/node_modules/hypercore/package.json","./caps":"/node_modules/pgh/node_modules/hypercore/lib/caps.js","b4a":"/node_modules/pgh/node_modules/b4a/index.js","flat-tree":"/node_modules/pgh/node_modules/flat-tree/index.js","hypercore-crypto":"/node_modules/pgh/node_modules/hypercore-crypto/index.js","hypercore-errors":"/node_modules/pgh/node_modules/hypercore-errors/index.js","unslab":"/node_modules/pgh/node_modules/unslab/index.js"},"/node_modules/pgh/node_modules/hypercore/lib/messages.js":{"#package":"/node_modules/pgh/node_modules/hypercore/package.json","./caps":"/node_modules/pgh/node_modules/hypercore/lib/caps.js","compact-encoding":"/node_modules/pgh/node_modules/compact-encoding/index.js","hypercore-errors":"/node_modules/pgh/node_modules/hypercore-errors/index.js","unslab":"/node_modules/pgh/node_modules/unslab/index.js"},"/node_modules/pgh/node_modules/hypercore/lib/multisig.js":{"#package":"/node_modules/pgh/node_modules/hypercore/package.json","./merkle-tree":"/node_modules/pgh/node_modules/hypercore/lib/merkle-tree.js","./messages":"/node_modules/pgh/node_modules/hypercore/lib/messages.js","b4a":"/node_modules/pgh/node_modules/b4a/index.js","compact-encoding":"/node_modules/pgh/node_modules/compact-encoding/index.js","flat-tree":"/node_modules/pgh/node_modules/flat-tree/index.js"},"/node_modules/pgh/node_modules/hypercore/lib/mutex.js":{"#package":"/node_modules/pgh/node_modules/hypercore/package.json"},"/node_modules/pgh/node_modules/hypercore/lib/receiver-queue.js":{"#package":"/node_modules/pgh/node_modules/hypercore/package.json","fast-fifo":"/node_modules/pgh/node_modules/fast-fifo/index.js"},"/node_modules/pgh/node_modules/hypercore/lib/remote-bitfield.js":{"#package":"/node_modules/pgh/node_modules/hypercore/package.json","./compat":"/node_modules/pgh/node_modules/hypercore/lib/compat.js","big-sparse-array":"/node_modules/pgh/node_modules/big-sparse-array/index.js"},"/node_modules/pgh/node_modules/hypercore/lib/replicator.js":{"#package":"/node_modules/pgh/node_modules/hypercore/package.json","./caps":"/node_modules/pgh/node_modules/hypercore/lib/caps.js","./hotswap-queue":"/node_modules/pgh/node_modules/hypercore/lib/hotswap-queue.js","./merkle-tree":"/node_modules/pgh/node_modules/hypercore/lib/merkle-tree.js","./messages":"/node_modules/pgh/node_modules/hypercore/lib/messages.js","./mutex":"/node_modules/pgh/node_modules/hypercore/lib/mutex.js","./receiver-queue":"/node_modules/pgh/node_modules/hypercore/lib/receiver-queue.js","./remote-bitfield":"/node_modules/pgh/node_modules/hypercore/lib/remote-bitfield.js","./wants":"/node_modules/pgh/node_modules/hypercore/lib/wants.js","b4a":"/node_modules/pgh/node_modules/b4a/index.js","flat-tree":"/node_modules/pgh/node_modules/flat-tree/index.js","hypercore-errors":"/node_modules/pgh/node_modules/hypercore-errors/index.js","random-array-iterator":"/node_modules/pgh/node_modules/random-array-iterator/index.js","safety-catch":"/node_modules/pgh/node_modules/safety-catch/index.js"},"/node_modules/pgh/node_modules/hypercore/lib/session-state.js":{"#package":"/node_modules/pgh/node_modules/hypercore/package.json","./bitfield":"/node_modules/pgh/node_modules/hypercore/lib/bitfield.js","./merkle-tree":"/node_modules/pgh/node_modules/hypercore/lib/merkle-tree.js","./mutex":"/node_modules/pgh/node_modules/hypercore/lib/mutex.js","b4a":"/node_modules/pgh/node_modules/b4a/index.js","flat-tree":"/node_modules/pgh/node_modules/flat-tree/index.js","hypercore-crypto":"/node_modules/pgh/node_modules/hypercore-crypto/index.js","hypercore-errors":"/node_modules/pgh/node_modules/hypercore-errors/index.js","hypercore-storage":"/node_modules/pgh/node_modules/hypercore-storage/index.js","nanoassert":"/node_modules/pgh/node_modules/nanoassert/index.js","quickbit-universal":"/node_modules/pgh/node_modules/quickbit-universal/index.js"},"/node_modules/pgh/node_modules/hypercore/lib/streams.js":{"#package":"/node_modules/pgh/node_modules/hypercore/package.json","streamx":"/node_modules/pgh/node_modules/streamx/index.js"},"/node_modules/pgh/node_modules/hypercore/lib/verifier.js":{"#package":"/node_modules/pgh/node_modules/hypercore/package.json","./caps":"/node_modules/pgh/node_modules/hypercore/lib/caps.js","./messages":"/node_modules/pgh/node_modules/hypercore/lib/messages.js","./multisig":"/node_modules/pgh/node_modules/hypercore/lib/multisig.js","b4a":"/node_modules/pgh/node_modules/b4a/index.js","compact-encoding":"/node_modules/pgh/node_modules/compact-encoding/index.js","flat-tree":"/node_modules/pgh/node_modules/flat-tree/index.js","hypercore-crypto":"/node_modules/pgh/node_modules/hypercore-crypto/index.js","hypercore-errors":"/node_modules/pgh/node_modules/hypercore-errors/index.js","unslab":"/node_modules/pgh/node_modules/unslab/index.js"},"/node_modules/pgh/node_modules/hypercore/lib/wants.js":{"#package":"/node_modules/pgh/node_modules/hypercore/package.json"},"/node_modules/pgh/node_modules/hypercore/package.json":{},"/node_modules/pgh/node_modules/hyperdht-address/index.js":{"#package":"/node_modules/pgh/node_modules/hyperdht-address/package.json","./spec/hyperschema":"/node_modules/pgh/node_modules/hyperdht-address/spec/hyperschema/index.js","compact-encoding":"/node_modules/pgh/node_modules/compact-encoding/index.js"},"/node_modules/pgh/node_modules/hyperdht-address/package.json":{},"/node_modules/pgh/node_modules/hyperdht-address/spec/hyperschema/index.js":{"#package":"/node_modules/pgh/node_modules/hyperdht-address/package.json","hyperschema/runtime":"/node_modules/pgh/node_modules/hyperschema/runtime.cjs"},"/node_modules/pgh/node_modules/hyperdht/index.js":{"#package":"/node_modules/pgh/node_modules/hyperdht/package.json","./lib/connect":"/node_modules/pgh/node_modules/hyperdht/lib/connect.js","./lib/connection-pool":"/node_modules/pgh/node_modules/hyperdht/lib/connection-pool.js","./lib/constants":"/node_modules/pgh/node_modules/hyperdht/lib/constants.js","./lib/crypto":"/node_modules/pgh/node_modules/hyperdht/lib/crypto.js","./lib/errors":"/node_modules/pgh/node_modules/hyperdht/lib/errors.js","./lib/messages":"/node_modules/pgh/node_modules/hyperdht/lib/messages.js","./lib/persistent":"/node_modules/pgh/node_modules/hyperdht/lib/persistent.js","./lib/raw-stream-set":"/node_modules/pgh/node_modules/hyperdht/lib/raw-stream-set.js","./lib/router":"/node_modules/pgh/node_modules/hyperdht/lib/router.js","./lib/server":"/node_modules/pgh/node_modules/hyperdht/lib/server.js","./lib/socket-pool":"/node_modules/pgh/node_modules/hyperdht/lib/socket-pool.js","b4a":"/node_modules/pgh/node_modules/b4a/index.js","compact-encoding":"/node_modules/pgh/node_modules/compact-encoding/index.js","dht-rpc":"/node_modules/pgh/node_modules/dht-rpc/index.js","safety-catch":"/node_modules/pgh/node_modules/safety-catch/index.js","sodium-universal":"/node_modules/pgh/node_modules/sodium-universal/index.js","xache":"/node_modules/pgh/node_modules/xache/index.js"},"/node_modules/pgh/node_modules/hyperdht/lib/announcer.js":{"#package":"/node_modules/pgh/node_modules/hyperdht/package.json","./constants":"/node_modules/pgh/node_modules/hyperdht/lib/constants.js","./encode":"/node_modules/pgh/node_modules/hyperdht/lib/encode.js","./messages":"/node_modules/pgh/node_modules/hyperdht/lib/messages.js","./persistent":"/node_modules/pgh/node_modules/hyperdht/lib/persistent.js","./sleeper":"/node_modules/pgh/node_modules/hyperdht/lib/sleeper.js","compact-encoding":"/node_modules/pgh/node_modules/compact-encoding/index.js","safety-catch":"/node_modules/pgh/node_modules/safety-catch/index.js","signal-promise":"/node_modules/pgh/node_modules/signal-promise/index.js"},"/node_modules/pgh/node_modules/hyperdht/lib/connect.js":{"#package":"/node_modules/pgh/node_modules/hyperdht/package.json","./constants":"/node_modules/pgh/node_modules/hyperdht/lib/constants.js","./crypto":"/node_modules/pgh/node_modules/hyperdht/lib/crypto.js","./errors":"/node_modules/pgh/node_modules/hyperdht/lib/errors.js","./holepuncher":"/node_modules/pgh/node_modules/hyperdht/lib/holepuncher.js","./noise-wrap":"/node_modules/pgh/node_modules/hyperdht/lib/noise-wrap.js","./secure-payload":"/node_modules/pgh/node_modules/hyperdht/lib/secure-payload.js","./semaphore":"/node_modules/pgh/node_modules/hyperdht/lib/semaphore.js","./sleeper":"/node_modules/pgh/node_modules/hyperdht/lib/sleeper.js","@hyperswarm/secret-stream":"/node_modules/pgh/node_modules/@hyperswarm/secret-stream/index.js","b4a":"/node_modules/pgh/node_modules/b4a/index.js","blind-relay":"/node_modules/pgh/node_modules/blind-relay/index.js","bogon":"/node_modules/pgh/node_modules/bogon/index.js","hypercore-id-encoding":"/node_modules/pgh/node_modules/hypercore-id-encoding/index.js","hyperdht-address":"/node_modules/pgh/node_modules/hyperdht-address/index.js","safety-catch":"/node_modules/pgh/node_modules/safety-catch/index.js","unslab":"/node_modules/pgh/node_modules/unslab/index.js"},"/node_modules/pgh/node_modules/hyperdht/lib/connection-pool.js":{"#package":"/node_modules/pgh/node_modules/hyperdht/package.json","./errors":"/node_modules/pgh/node_modules/hyperdht/lib/errors.js","b4a":"/node_modules/pgh/node_modules/b4a/index.js","events":"/node_modules/pgh/node_modules/bare-events/index.js"},"/node_modules/pgh/node_modules/hyperdht/lib/constants.js":{"#package":"/node_modules/pgh/node_modules/hyperdht/package.json","hypercore-crypto":"/node_modules/pgh/node_modules/hypercore-crypto/index.js"},"/node_modules/pgh/node_modules/hyperdht/lib/crypto.js":{"#package":"/node_modules/pgh/node_modules/hyperdht/package.json","b4a":"/node_modules/pgh/node_modules/b4a/index.js","sodium-universal":"/node_modules/pgh/node_modules/sodium-universal/index.js"},"/node_modules/pgh/node_modules/hyperdht/lib/encode.js":{"#package":"/node_modules/pgh/node_modules/hyperdht/package.json","b4a":"/node_modules/pgh/node_modules/b4a/index.js","compact-encoding":"/node_modules/pgh/node_modules/compact-encoding/index.js"},"/node_modules/pgh/node_modules/hyperdht/lib/errors.js":{"#package":"/node_modules/pgh/node_modules/hyperdht/package.json"},"/node_modules/pgh/node_modules/hyperdht/lib/holepuncher.js":{"#package":"/node_modules/pgh/node_modules/hyperdht/package.json","./constants":"/node_modules/pgh/node_modules/hyperdht/lib/constants.js","./nat":"/node_modules/pgh/node_modules/hyperdht/lib/nat.js","./sleeper":"/node_modules/pgh/node_modules/hyperdht/lib/sleeper.js","b4a":"/node_modules/pgh/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/hyperdht/lib/messages.js":{"#package":"/node_modules/pgh/node_modules/hyperdht/package.json","compact-encoding":"/node_modules/pgh/node_modules/compact-encoding/index.js"},"/node_modules/pgh/node_modules/hyperdht/lib/nat.js":{"#package":"/node_modules/pgh/node_modules/hyperdht/package.json","../lib/constants":"/node_modules/pgh/node_modules/hyperdht/lib/constants.js"},"/node_modules/pgh/node_modules/hyperdht/lib/noise-wrap.js":{"#package":"/node_modules/pgh/node_modules/hyperdht/package.json","./constants":"/node_modules/pgh/node_modules/hyperdht/lib/constants.js","./errors":"/node_modules/pgh/node_modules/hyperdht/lib/errors.js","./messages":"/node_modules/pgh/node_modules/hyperdht/lib/messages.js","@hyperswarm/secret-stream":"/node_modules/pgh/node_modules/@hyperswarm/secret-stream/index.js","b4a":"/node_modules/pgh/node_modules/b4a/index.js","compact-encoding":"/node_modules/pgh/node_modules/compact-encoding/index.js","noise-curve-ed":"/node_modules/pgh/node_modules/noise-curve-ed/index.js","noise-handshake":"/node_modules/pgh/node_modules/noise-handshake/noise.js","sodium-universal":"/node_modules/pgh/node_modules/sodium-universal/index.js"},"/node_modules/pgh/node_modules/hyperdht/lib/persistent.js":{"#package":"/node_modules/pgh/node_modules/hyperdht/package.json","./constants":"/node_modules/pgh/node_modules/hyperdht/lib/constants.js","./encode":"/node_modules/pgh/node_modules/hyperdht/lib/encode.js","./messages":"/node_modules/pgh/node_modules/hyperdht/lib/messages.js","b4a":"/node_modules/pgh/node_modules/b4a/index.js","compact-encoding":"/node_modules/pgh/node_modules/compact-encoding/index.js","record-cache":"/node_modules/pgh/node_modules/record-cache/index.js","sodium-universal":"/node_modules/pgh/node_modules/sodium-universal/index.js","unslab":"/node_modules/pgh/node_modules/unslab/index.js","xache":"/node_modules/pgh/node_modules/xache/index.js"},"/node_modules/pgh/node_modules/hyperdht/lib/raw-stream-set.js":{"#package":"/node_modules/pgh/node_modules/hyperdht/package.json"},"/node_modules/pgh/node_modules/hyperdht/lib/router.js":{"#package":"/node_modules/pgh/node_modules/hyperdht/package.json","./constants":"/node_modules/pgh/node_modules/hyperdht/lib/constants.js","./errors":"/node_modules/pgh/node_modules/hyperdht/lib/errors.js","./messages":"/node_modules/pgh/node_modules/hyperdht/lib/messages.js","b4a":"/node_modules/pgh/node_modules/b4a/index.js","compact-encoding":"/node_modules/pgh/node_modules/compact-encoding/index.js","safety-catch":"/node_modules/pgh/node_modules/safety-catch/index.js","xache":"/node_modules/pgh/node_modules/xache/index.js"},"/node_modules/pgh/node_modules/hyperdht/lib/secure-payload.js":{"#package":"/node_modules/pgh/node_modules/hyperdht/package.json","./messages":"/node_modules/pgh/node_modules/hyperdht/lib/messages.js","b4a":"/node_modules/pgh/node_modules/b4a/index.js","sodium-universal":"/node_modules/pgh/node_modules/sodium-universal/index.js"},"/node_modules/pgh/node_modules/hyperdht/lib/semaphore.js":{"#package":"/node_modules/pgh/node_modules/hyperdht/package.json"},"/node_modules/pgh/node_modules/hyperdht/lib/server.js":{"#package":"/node_modules/pgh/node_modules/hyperdht/package.json","./announcer":"/node_modules/pgh/node_modules/hyperdht/lib/announcer.js","./constants":"/node_modules/pgh/node_modules/hyperdht/lib/constants.js","./crypto":"/node_modules/pgh/node_modules/hyperdht/lib/crypto.js","./errors":"/node_modules/pgh/node_modules/hyperdht/lib/errors.js","./holepuncher":"/node_modules/pgh/node_modules/hyperdht/lib/holepuncher.js","./noise-wrap":"/node_modules/pgh/node_modules/hyperdht/lib/noise-wrap.js","./secure-payload":"/node_modules/pgh/node_modules/hyperdht/lib/secure-payload.js","@hyperswarm/secret-stream":"/node_modules/pgh/node_modules/@hyperswarm/secret-stream/index.js","b4a":"/node_modules/pgh/node_modules/b4a/index.js","blind-relay":"/node_modules/pgh/node_modules/blind-relay/index.js","bogon":"/node_modules/pgh/node_modules/bogon/index.js","events":"/node_modules/pgh/node_modules/bare-events/index.js","safety-catch":"/node_modules/pgh/node_modules/safety-catch/index.js"},"/node_modules/pgh/node_modules/hyperdht/lib/sleeper.js":{"#package":"/node_modules/pgh/node_modules/hyperdht/package.json"},"/node_modules/pgh/node_modules/hyperdht/lib/socket-pool.js":{"#package":"/node_modules/pgh/node_modules/hyperdht/package.json","b4a":"/node_modules/pgh/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/hyperdht/package.json":{},"/node_modules/pgh/node_modules/hyperschema/package.json":{},"/node_modules/pgh/node_modules/hyperschema/runtime.cjs":{"#package":"/node_modules/pgh/node_modules/hyperschema/package.json","compact-encoding":"/node_modules/pgh/node_modules/compact-encoding/index.js"},"/node_modules/pgh/node_modules/hyperswarm/index.js":{"#package":"/node_modules/pgh/node_modules/hyperswarm/package.json","./lib/connection-set":"/node_modules/pgh/node_modules/hyperswarm/lib/connection-set.js","./lib/peer-discovery":"/node_modules/pgh/node_modules/hyperswarm/lib/peer-discovery.js","./lib/peer-info":"/node_modules/pgh/node_modules/hyperswarm/lib/peer-info.js","./lib/retry-timer":"/node_modules/pgh/node_modules/hyperswarm/lib/retry-timer.js","b4a":"/node_modules/pgh/node_modules/b4a/index.js","events":"/node_modules/pgh/node_modules/bare-events/index.js","hyperdht":"/node_modules/pgh/node_modules/hyperdht/index.js","shuffled-priority-queue":"/node_modules/pgh/node_modules/shuffled-priority-queue/index.js","streamx":"/node_modules/pgh/node_modules/streamx/index.js","unslab":"/node_modules/pgh/node_modules/unslab/index.js"},"/node_modules/pgh/node_modules/hyperswarm/lib/bulk-timer.js":{"#package":"/node_modules/pgh/node_modules/hyperswarm/package.json"},"/node_modules/pgh/node_modules/hyperswarm/lib/connection-set.js":{"#package":"/node_modules/pgh/node_modules/hyperswarm/package.json","b4a":"/node_modules/pgh/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/hyperswarm/lib/peer-discovery.js":{"#package":"/node_modules/pgh/node_modules/hyperswarm/package.json","b4a":"/node_modules/pgh/node_modules/b4a/index.js","safety-catch":"/node_modules/pgh/node_modules/safety-catch/index.js"},"/node_modules/pgh/node_modules/hyperswarm/lib/peer-info.js":{"#package":"/node_modules/pgh/node_modules/hyperswarm/package.json","b4a":"/node_modules/pgh/node_modules/b4a/index.js","events":"/node_modules/pgh/node_modules/bare-events/index.js","unslab":"/node_modules/pgh/node_modules/unslab/index.js"},"/node_modules/pgh/node_modules/hyperswarm/lib/retry-timer.js":{"#package":"/node_modules/pgh/node_modules/hyperswarm/package.json","./bulk-timer":"/node_modules/pgh/node_modules/hyperswarm/lib/bulk-timer.js"},"/node_modules/pgh/node_modules/hyperswarm/package.json":{},"/node_modules/pgh/node_modules/index-encoder/index.js":{"#package":"/node_modules/pgh/node_modules/index-encoder/package.json","b4a":"/node_modules/pgh/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/index-encoder/package.json":{},"/node_modules/pgh/node_modules/is-options/index.js":{"#package":"/node_modules/pgh/node_modules/is-options/package.json","b4a":"/node_modules/pgh/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/is-options/package.json":{},"/node_modules/pgh/node_modules/kademlia-routing-table/index.js":{"#package":"/node_modules/pgh/node_modules/kademlia-routing-table/package.json","events":"/node_modules/pgh/node_modules/bare-events/index.js"},"/node_modules/pgh/node_modules/kademlia-routing-table/package.json":{},"/node_modules/pgh/node_modules/mutexify/index.js":{"#package":"/node_modules/pgh/node_modules/mutexify/package.json","queue-tick":"/node_modules/pgh/node_modules/queue-tick/process-next-tick.js"},"/node_modules/pgh/node_modules/mutexify/package.json":{},"/node_modules/pgh/node_modules/mutexify/promise.js":{"#package":"/node_modules/pgh/node_modules/mutexify/package.json",".":"/node_modules/pgh/node_modules/mutexify/index.js"},"/node_modules/pgh/node_modules/nanoassert/index.js":{"#package":"/node_modules/pgh/node_modules/nanoassert/package.json"},"/node_modules/pgh/node_modules/nanoassert/package.json":{},"/node_modules/pgh/node_modules/nat-sampler/index.js":{"#package":"/node_modules/pgh/node_modules/nat-sampler/package.json"},"/node_modules/pgh/node_modules/nat-sampler/package.json":{},"/node_modules/pgh/node_modules/noise-curve-ed/index.js":{"#package":"/node_modules/pgh/node_modules/noise-curve-ed/package.json","b4a":"/node_modules/pgh/node_modules/b4a/index.js","nanoassert":"/node_modules/pgh/node_modules/nanoassert/index.js","sodium-universal":"/node_modules/pgh/node_modules/sodium-universal/index.js"},"/node_modules/pgh/node_modules/noise-curve-ed/package.json":{},"/node_modules/pgh/node_modules/noise-handshake/cipher.js":{"#package":"/node_modules/pgh/node_modules/noise-handshake/package.json","b4a":"/node_modules/pgh/node_modules/b4a/index.js","sodium-universal":"/node_modules/pgh/node_modules/sodium-universal/index.js"},"/node_modules/pgh/node_modules/noise-handshake/dh.js":{"#package":"/node_modules/pgh/node_modules/noise-handshake/package.json","b4a":"/node_modules/pgh/node_modules/b4a/index.js","nanoassert":"/node_modules/pgh/node_modules/nanoassert/index.js","sodium-universal":"/node_modules/pgh/node_modules/sodium-universal/index.js"},"/node_modules/pgh/node_modules/noise-handshake/hkdf.js":{"#package":"/node_modules/pgh/node_modules/noise-handshake/package.json","./hmac":"/node_modules/pgh/node_modules/noise-handshake/hmac.js","b4a":"/node_modules/pgh/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/noise-handshake/hmac.js":{"#package":"/node_modules/pgh/node_modules/noise-handshake/package.json","b4a":"/node_modules/pgh/node_modules/b4a/index.js","sodium-universal":"/node_modules/pgh/node_modules/sodium-universal/index.js"},"/node_modules/pgh/node_modules/noise-handshake/noise.js":{"#package":"/node_modules/pgh/node_modules/noise-handshake/package.json","./hkdf":"/node_modules/pgh/node_modules/noise-handshake/hkdf.js","./symmetric-state":"/node_modules/pgh/node_modules/noise-handshake/symmetric-state.js","b4a":"/node_modules/pgh/node_modules/b4a/index.js","nanoassert":"/node_modules/pgh/node_modules/nanoassert/index.js"},"/node_modules/pgh/node_modules/noise-handshake/package.json":{},"/node_modules/pgh/node_modules/noise-handshake/symmetric-state.js":{"#package":"/node_modules/pgh/node_modules/noise-handshake/package.json","./cipher":"/node_modules/pgh/node_modules/noise-handshake/cipher.js","./dh":"/node_modules/pgh/node_modules/noise-handshake/dh.js","./hkdf":"/node_modules/pgh/node_modules/noise-handshake/hkdf.js","b4a":"/node_modules/pgh/node_modules/b4a/index.js","nanoassert":"/node_modules/pgh/node_modules/nanoassert/index.js","sodium-universal":"/node_modules/pgh/node_modules/sodium-universal/index.js"},"/node_modules/pgh/node_modules/protocol-buffers-encodings/index.js":{"#package":"/node_modules/pgh/node_modules/protocol-buffers-encodings/package.json","b4a":"/node_modules/pgh/node_modules/b4a/index.js","signed-varint":"/node_modules/pgh/node_modules/signed-varint/index.js","varint":"/node_modules/pgh/node_modules/varint/index.js"},"/node_modules/pgh/node_modules/protocol-buffers-encodings/package.json":{},"/node_modules/pgh/node_modules/protomux-wakeup/index.js":{"#package":"/node_modules/pgh/node_modules/protomux-wakeup/package.json","./spec/hyperschema":"/node_modules/pgh/node_modules/protomux-wakeup/spec/hyperschema/index.js","b4a":"/node_modules/pgh/node_modules/b4a/index.js","hypercore-crypto":"/node_modules/pgh/node_modules/hypercore-crypto/index.js","protomux":"/node_modules/pgh/node_modules/protomux/index.js"},"/node_modules/pgh/node_modules/protomux-wakeup/package.json":{},"/node_modules/pgh/node_modules/protomux-wakeup/spec/hyperschema/index.js":{"#package":"/node_modules/pgh/node_modules/protomux-wakeup/package.json","hyperschema/runtime":"/node_modules/pgh/node_modules/hyperschema/runtime.cjs"},"/node_modules/pgh/node_modules/protomux/index.js":{"#package":"/node_modules/pgh/node_modules/protomux/package.json","b4a":"/node_modules/pgh/node_modules/b4a/index.js","compact-encoding":"/node_modules/pgh/node_modules/compact-encoding/index.js","queue-tick":"/node_modules/pgh/node_modules/queue-tick/process-next-tick.js","safety-catch":"/node_modules/pgh/node_modules/safety-catch/index.js","unslab":"/node_modules/pgh/node_modules/unslab/index.js"},"/node_modules/pgh/node_modules/protomux/package.json":{},"/node_modules/pgh/node_modules/queue-tick/package.json":{},"/node_modules/pgh/node_modules/queue-tick/process-next-tick.js":{"#package":"/node_modules/pgh/node_modules/queue-tick/package.json","./queue-microtask":"/node_modules/pgh/node_modules/queue-tick/queue-microtask.js"},"/node_modules/pgh/node_modules/queue-tick/queue-microtask.js":{"#package":"/node_modules/pgh/node_modules/queue-tick/package.json"},"/node_modules/pgh/node_modules/quickbit-native/binding.js":{"#package":"/node_modules/pgh/node_modules/quickbit-native/package.json",".":"linked:libquickbit-native.2.4.8.so","require-addon":"/node_modules/pgh/node_modules/require-addon/lib/bare.js"},"/node_modules/pgh/node_modules/quickbit-native/index.js":{"#package":"/node_modules/pgh/node_modules/quickbit-native/package.json","./binding":"/node_modules/pgh/node_modules/quickbit-native/binding.js"},"/node_modules/pgh/node_modules/quickbit-native/package.json":{},"/node_modules/pgh/node_modules/quickbit-universal/fallback.js":{"#package":"/node_modules/pgh/node_modules/quickbit-universal/package.json","simdle-universal":"/node_modules/pgh/node_modules/simdle-universal/index.js"},"/node_modules/pgh/node_modules/quickbit-universal/index.js":{"#package":"/node_modules/pgh/node_modules/quickbit-universal/package.json","./fallback":"/node_modules/pgh/node_modules/quickbit-universal/fallback.js","quickbit-native":"/node_modules/pgh/node_modules/quickbit-native/index.js"},"/node_modules/pgh/node_modules/quickbit-universal/package.json":{},"/node_modules/pgh/node_modules/rache/index.js":{"#package":"/node_modules/pgh/node_modules/rache/package.json"},"/node_modules/pgh/node_modules/rache/package.json":{},"/node_modules/pgh/node_modules/random-array-iterator/index.js":{"#package":"/node_modules/pgh/node_modules/random-array-iterator/package.json"},"/node_modules/pgh/node_modules/random-array-iterator/package.json":{},"/node_modules/pgh/node_modules/ready-resource/index.js":{"#package":"/node_modules/pgh/node_modules/ready-resource/package.json","events":"/node_modules/pgh/node_modules/bare-events/index.js"},"/node_modules/pgh/node_modules/ready-resource/package.json":{},"/node_modules/pgh/node_modules/record-cache/index.js":{"#package":"/node_modules/pgh/node_modules/record-cache/package.json","b4a":"/node_modules/pgh/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/record-cache/package.json":{},"/node_modules/pgh/node_modules/refcounter/index.js":{"#package":"/node_modules/pgh/node_modules/refcounter/package.json"},"/node_modules/pgh/node_modules/refcounter/package.json":{},"/node_modules/pgh/node_modules/require-addon/lib/bare.js":{"#package":"/node_modules/pgh/node_modules/require-addon/package.json"},"/node_modules/pgh/node_modules/require-addon/package.json":{},"/node_modules/pgh/node_modules/resolve-reject-promise/index.js":{"#package":"/node_modules/pgh/node_modules/resolve-reject-promise/package.json"},"/node_modules/pgh/node_modules/resolve-reject-promise/package.json":{},"/node_modules/pgh/node_modules/resource-on-exit/index.js":{"#package":"/node_modules/pgh/node_modules/resource-on-exit/package.json"},"/node_modules/pgh/node_modules/resource-on-exit/package.json":{},"/node_modules/pgh/node_modules/rocksdb-native/binding.js":{"#package":"/node_modules/pgh/node_modules/rocksdb-native/package.json",".":"linked:librocksdb-native.3.15.2.so","require-addon":"/node_modules/pgh/node_modules/require-addon/lib/bare.js"},"/node_modules/pgh/node_modules/rocksdb-native/index.js":{"#package":"/node_modules/pgh/node_modules/rocksdb-native/package.json","./lib/column-family":"/node_modules/pgh/node_modules/rocksdb-native/lib/column-family.js","./lib/constants":"/node_modules/pgh/node_modules/rocksdb-native/lib/constants.js","./lib/filter-policy":"/node_modules/pgh/node_modules/rocksdb-native/lib/filter-policy.js","./lib/iterator":"/node_modules/pgh/node_modules/rocksdb-native/lib/iterator.js","./lib/snapshot":"/node_modules/pgh/node_modules/rocksdb-native/lib/snapshot.js","./lib/state":"/node_modules/pgh/node_modules/rocksdb-native/lib/state.js"},"/node_modules/pgh/node_modules/rocksdb-native/lib/batch.js":{"#package":"/node_modules/pgh/node_modules/rocksdb-native/package.json","../binding":"/node_modules/pgh/node_modules/rocksdb-native/binding.js","compact-encoding":"/node_modules/pgh/node_modules/compact-encoding/index.js"},"/node_modules/pgh/node_modules/rocksdb-native/lib/column-family.js":{"#package":"/node_modules/pgh/node_modules/rocksdb-native/package.json","../binding":"/node_modules/pgh/node_modules/rocksdb-native/binding.js","./constants":"/node_modules/pgh/node_modules/rocksdb-native/lib/constants.js","./filter-policy":"/node_modules/pgh/node_modules/rocksdb-native/lib/filter-policy.js"},"/node_modules/pgh/node_modules/rocksdb-native/lib/constants.js":{"#package":"/node_modules/pgh/node_modules/rocksdb-native/package.json"},"/node_modules/pgh/node_modules/rocksdb-native/lib/filter-policy.js":{"#package":"/node_modules/pgh/node_modules/rocksdb-native/package.json"},"/node_modules/pgh/node_modules/rocksdb-native/lib/iterator.js":{"#package":"/node_modules/pgh/node_modules/rocksdb-native/package.json","../binding":"/node_modules/pgh/node_modules/rocksdb-native/binding.js","compact-encoding":"/node_modules/pgh/node_modules/compact-encoding/index.js","streamx":"/node_modules/pgh/node_modules/streamx/index.js"},"/node_modules/pgh/node_modules/rocksdb-native/lib/snapshot.js":{"#package":"/node_modules/pgh/node_modules/rocksdb-native/package.json","../binding":"/node_modules/pgh/node_modules/rocksdb-native/binding.js"},"/node_modules/pgh/node_modules/rocksdb-native/lib/state.js":{"#package":"/node_modules/pgh/node_modules/rocksdb-native/package.json","../binding":"/node_modules/pgh/node_modules/rocksdb-native/binding.js","./batch":"/node_modules/pgh/node_modules/rocksdb-native/lib/batch.js","./column-family":"/node_modules/pgh/node_modules/rocksdb-native/lib/column-family.js","./constants":"/node_modules/pgh/node_modules/rocksdb-native/lib/constants.js","compact-encoding":"/node_modules/pgh/node_modules/compact-encoding/index.js","ready-resource":"/node_modules/pgh/node_modules/ready-resource/index.js","refcounter":"/node_modules/pgh/node_modules/refcounter/index.js","resolve-reject-promise":"/node_modules/pgh/node_modules/resolve-reject-promise/index.js","signal-promise":"/node_modules/pgh/node_modules/signal-promise/index.js"},"/node_modules/pgh/node_modules/rocksdb-native/package.json":{},"/node_modules/pgh/node_modules/safety-catch/index.js":{"#package":"/node_modules/pgh/node_modules/safety-catch/package.json"},"/node_modules/pgh/node_modules/safety-catch/package.json":{},"/node_modules/pgh/node_modules/scope-lock/index.js":{"#package":"/node_modules/pgh/node_modules/scope-lock/package.json"},"/node_modules/pgh/node_modules/scope-lock/package.json":{},"/node_modules/pgh/node_modules/shuffled-priority-queue/index.js":{"#package":"/node_modules/pgh/node_modules/shuffled-priority-queue/package.json","unordered-set":"/node_modules/pgh/node_modules/unordered-set/index.js"},"/node_modules/pgh/node_modules/shuffled-priority-queue/package.json":{},"/node_modules/pgh/node_modules/signal-promise/index.js":{"#package":"/node_modules/pgh/node_modules/signal-promise/package.json"},"/node_modules/pgh/node_modules/signal-promise/package.json":{},"/node_modules/pgh/node_modules/signed-varint/index.js":{"#package":"/node_modules/pgh/node_modules/signed-varint/package.json","varint":"/node_modules/pgh/node_modules/varint/index.js"},"/node_modules/pgh/node_modules/signed-varint/package.json":{},"/node_modules/pgh/node_modules/simdle-native/binding.js":{"#package":"/node_modules/pgh/node_modules/simdle-native/package.json",".":"linked:libsimdle-native.1.3.9.so","require-addon":"/node_modules/pgh/node_modules/require-addon/lib/bare.js"},"/node_modules/pgh/node_modules/simdle-native/index.js":{"#package":"/node_modules/pgh/node_modules/simdle-native/package.json","./binding":"/node_modules/pgh/node_modules/simdle-native/binding.js","b4a":"/node_modules/pgh/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/simdle-native/package.json":{},"/node_modules/pgh/node_modules/simdle-universal/fallback.js":{"#package":"/node_modules/pgh/node_modules/simdle-universal/package.json","./scalar":"/node_modules/pgh/node_modules/simdle-universal/scalar.js","b4a":"/node_modules/pgh/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/simdle-universal/index.js":{"#package":"/node_modules/pgh/node_modules/simdle-universal/package.json","./fallback":"/node_modules/pgh/node_modules/simdle-universal/fallback.js","simdle-native":"/node_modules/pgh/node_modules/simdle-native/index.js"},"/node_modules/pgh/node_modules/simdle-universal/package.json":{},"/node_modules/pgh/node_modules/simdle-universal/scalar.js":{"#package":"/node_modules/pgh/node_modules/simdle-universal/package.json"},"/node_modules/pgh/node_modules/sodium-native/binding.js":{"#package":"/node_modules/pgh/node_modules/sodium-native/package.json",".":"linked:libsodium-native.5.1.0.so","require-addon":"/node_modules/pgh/node_modules/require-addon/lib/bare.js"},"/node_modules/pgh/node_modules/sodium-native/index.js":{"#package":"/node_modules/pgh/node_modules/sodium-native/package.json","./binding":"/node_modules/pgh/node_modules/sodium-native/binding.js","assert":"/node_modules/pgh/node_modules/bare-assert/index.js","which-runtime":"/node_modules/pgh/node_modules/which-runtime/index.js"},"/node_modules/pgh/node_modules/sodium-native/package.json":{},"/node_modules/pgh/node_modules/sodium-secretstream/index.js":{"#package":"/node_modules/pgh/node_modules/sodium-secretstream/package.json","b4a":"/node_modules/pgh/node_modules/b4a/index.js","sodium-universal":"/node_modules/pgh/node_modules/sodium-universal/index.js"},"/node_modules/pgh/node_modules/sodium-secretstream/package.json":{},"/node_modules/pgh/node_modules/sodium-universal/index.js":{"#package":"/node_modules/pgh/node_modules/sodium-universal/package.json","sodium-native":"/node_modules/pgh/node_modules/sodium-native/index.js"},"/node_modules/pgh/node_modules/sodium-universal/package.json":{},"/node_modules/pgh/node_modules/streamx/index.js":{"#package":"/node_modules/pgh/node_modules/streamx/package.json","./lib/errors.js":"/node_modules/pgh/node_modules/streamx/lib/errors.js","events-universal":"/node_modules/pgh/node_modules/events-universal/bare.js","fast-fifo":"/node_modules/pgh/node_modules/fast-fifo/index.js","text-decoder":"/node_modules/pgh/node_modules/text-decoder/index.js"},"/node_modules/pgh/node_modules/streamx/lib/errors.js":{"#package":"/node_modules/pgh/node_modules/streamx/package.json"},"/node_modules/pgh/node_modules/streamx/package.json":{},"/node_modules/pgh/node_modules/sub-encoder/index.js":{"#package":"/node_modules/pgh/node_modules/sub-encoder/package.json","b4a":"/node_modules/pgh/node_modules/b4a/index.js","codecs":"/node_modules/pgh/node_modules/codecs/index.js"},"/node_modules/pgh/node_modules/sub-encoder/package.json":{},"/node_modules/pgh/node_modules/teex/index.js":{"#package":"/node_modules/pgh/node_modules/teex/package.json","streamx":"/node_modules/pgh/node_modules/streamx/index.js"},"/node_modules/pgh/node_modules/teex/package.json":{},"/node_modules/pgh/node_modules/text-decoder/index.js":{"#package":"/node_modules/pgh/node_modules/text-decoder/package.json","./lib/pass-through-decoder":"/node_modules/pgh/node_modules/text-decoder/lib/pass-through-decoder.js","./lib/utf8-decoder":"/node_modules/pgh/node_modules/text-decoder/lib/utf8-decoder.js"},"/node_modules/pgh/node_modules/text-decoder/lib/pass-through-decoder.js":{"#package":"/node_modules/pgh/node_modules/text-decoder/package.json","b4a":"/node_modules/pgh/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/text-decoder/lib/utf8-decoder.js":{"#package":"/node_modules/pgh/node_modules/text-decoder/package.json","b4a":"/node_modules/pgh/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/text-decoder/package.json":{},"/node_modules/pgh/node_modules/time-ordered-set/index.js":{"#package":"/node_modules/pgh/node_modules/time-ordered-set/package.json"},"/node_modules/pgh/node_modules/time-ordered-set/package.json":{},"/node_modules/pgh/node_modules/timeout-refresh/browser.js":{"#package":"/node_modules/pgh/node_modules/timeout-refresh/package.json"},"/node_modules/pgh/node_modules/timeout-refresh/index.js":{"#package":"/node_modules/pgh/node_modules/timeout-refresh/package.json","./browser":"/node_modules/pgh/node_modules/timeout-refresh/browser.js","./node":"/node_modules/pgh/node_modules/timeout-refresh/node.js"},"/node_modules/pgh/node_modules/timeout-refresh/node.js":{"#package":"/node_modules/pgh/node_modules/timeout-refresh/package.json"},"/node_modules/pgh/node_modules/timeout-refresh/package.json":{},"/node_modules/pgh/node_modules/tiny-buffer-map/index.js":{"#package":"/node_modules/pgh/node_modules/tiny-buffer-map/package.json","b4a":"/node_modules/pgh/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/tiny-buffer-map/package.json":{},"/node_modules/pgh/node_modules/udx-native/binding.js":{"#package":"/node_modules/pgh/node_modules/udx-native/package.json",".":"linked:libudx-native.1.20.6.so","require-addon":"/node_modules/pgh/node_modules/require-addon/lib/bare.js"},"/node_modules/pgh/node_modules/udx-native/lib/ip.js":{"#package":"/node_modules/pgh/node_modules/udx-native/package.json"},"/node_modules/pgh/node_modules/udx-native/lib/network-interfaces.js":{"#package":"/node_modules/pgh/node_modules/udx-native/package.json","../binding":"/node_modules/pgh/node_modules/udx-native/binding.js","b4a":"/node_modules/pgh/node_modules/b4a/index.js","events":"/node_modules/pgh/node_modules/bare-events/index.js"},"/node_modules/pgh/node_modules/udx-native/lib/socket.js":{"#package":"/node_modules/pgh/node_modules/udx-native/package.json","../binding":"/node_modules/pgh/node_modules/udx-native/binding.js","./ip":"/node_modules/pgh/node_modules/udx-native/lib/ip.js","b4a":"/node_modules/pgh/node_modules/b4a/index.js","events":"/node_modules/pgh/node_modules/bare-events/index.js"},"/node_modules/pgh/node_modules/udx-native/lib/stream.js":{"#package":"/node_modules/pgh/node_modules/udx-native/package.json","../binding":"/node_modules/pgh/node_modules/udx-native/binding.js","./ip":"/node_modules/pgh/node_modules/udx-native/lib/ip.js","b4a":"/node_modules/pgh/node_modules/b4a/index.js","streamx":"/node_modules/pgh/node_modules/streamx/index.js"},"/node_modules/pgh/node_modules/udx-native/lib/udx.js":{"#package":"/node_modules/pgh/node_modules/udx-native/package.json","../binding":"/node_modules/pgh/node_modules/udx-native/binding.js","./ip":"/node_modules/pgh/node_modules/udx-native/lib/ip.js","./network-interfaces":"/node_modules/pgh/node_modules/udx-native/lib/network-interfaces.js","./socket":"/node_modules/pgh/node_modules/udx-native/lib/socket.js","./stream":"/node_modules/pgh/node_modules/udx-native/lib/stream.js","b4a":"/node_modules/pgh/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/udx-native/package.json":{},"/node_modules/pgh/node_modules/unordered-set/index.js":{"#package":"/node_modules/pgh/node_modules/unordered-set/package.json"},"/node_modules/pgh/node_modules/unordered-set/package.json":{},"/node_modules/pgh/node_modules/unslab/index.js":{"#package":"/node_modules/pgh/node_modules/unslab/package.json","b4a":"/node_modules/pgh/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/unslab/package.json":{},"/node_modules/pgh/node_modules/varint/decode.js":{"#package":"/node_modules/pgh/node_modules/varint/package.json"},"/node_modules/pgh/node_modules/varint/encode.js":{"#package":"/node_modules/pgh/node_modules/varint/package.json"},"/node_modules/pgh/node_modules/varint/index.js":{"#package":"/node_modules/pgh/node_modules/varint/package.json","./decode.js":"/node_modules/pgh/node_modules/varint/decode.js","./encode.js":"/node_modules/pgh/node_modules/varint/encode.js","./length.js":"/node_modules/pgh/node_modules/varint/length.js"},"/node_modules/pgh/node_modules/varint/length.js":{"#package":"/node_modules/pgh/node_modules/varint/package.json"},"/node_modules/pgh/node_modules/varint/package.json":{},"/node_modules/pgh/node_modules/which-runtime/index.js":{"#package":"/node_modules/pgh/node_modules/which-runtime/package.json"},"/node_modules/pgh/node_modules/which-runtime/package.json":{},"/node_modules/pgh/node_modules/xache/index.js":{"#package":"/node_modules/pgh/node_modules/xache/package.json"},"/node_modules/pgh/node_modules/xache/package.json":{},"/node_modules/pgh/node_modules/z32/index.js":{"#package":"/node_modules/pgh/node_modules/z32/package.json","b4a":"/node_modules/pgh/node_modules/b4a/index.js"},"/node_modules/pgh/node_modules/z32/package.json":{},"/node_modules/pgh/package.json":{},"/node_modules/require-addon/lib/bare.js":{"#package":"/node_modules/require-addon/package.json"},"/node_modules/require-addon/package.json":{},"/node_modules/sodium-native/binding.js":{"#package":"/node_modules/sodium-native/package.json",".":"linked:libsodium-native.5.1.0.so","require-addon":"/node_modules/require-addon/lib/bare.js"},"/node_modules/sodium-native/index.js":{"#package":"/node_modules/sodium-native/package.json","./binding":"/node_modules/sodium-native/binding.js","assert":"/node_modules/bare-assert/index.js","which-runtime":"/node_modules/which-runtime/index.js"},"/node_modules/sodium-native/package.json":{},"/node_modules/sodium-universal/index.js":{"#package":"/node_modules/sodium-universal/package.json","sodium-native":"/node_modules/sodium-native/index.js"},"/node_modules/sodium-universal/package.json":{},"/node_modules/streamx/index.js":{"#package":"/node_modules/streamx/package.json","./lib/errors.js":"/node_modules/streamx/lib/errors.js","events-universal":"/node_modules/events-universal/bare.js","fast-fifo":"/node_modules/fast-fifo/index.js","text-decoder":"/node_modules/text-decoder/index.js"},"/node_modules/streamx/lib/errors.js":{"#package":"/node_modules/streamx/package.json"},"/node_modules/streamx/package.json":{},"/node_modules/teex/index.js":{"#package":"/node_modules/teex/package.json","streamx":"/node_modules/streamx/index.js"},"/node_modules/teex/package.json":{},"/node_modules/text-decoder/index.js":{"#package":"/node_modules/text-decoder/package.json","./lib/pass-through-decoder":"/node_modules/text-decoder/lib/pass-through-decoder.js","./lib/utf8-decoder":"/node_modules/text-decoder/lib/utf8-decoder.js"},"/node_modules/text-decoder/lib/pass-through-decoder.js":{"#package":"/node_modules/text-decoder/package.json","b4a":"/node_modules/b4a/index.js"},"/node_modules/text-decoder/lib/utf8-decoder.js":{"#package":"/node_modules/text-decoder/package.json","b4a":"/node_modules/b4a/index.js"},"/node_modules/text-decoder/package.json":{},"/node_modules/which-runtime/index.js":{"#package":"/node_modules/which-runtime/package.json"},"/node_modules/which-runtime/package.json":{},"/package.json":{}},"addons":["linked:libbare-abort.2.0.13.so","linked:libbare-buffer.3.6.1.so","linked:libbare-buffer.3.6.2.so","linked:libbare-crypto.1.15.3.so","linked:libbare-dns.1.0.5.so","linked:libbare-dns.2.1.4.so","linked:libbare-dns.2.2.0.so","linked:libbare-fs.4.7.2.so","linked:libbare-fs.4.7.3.so","linked:libbare-fs.4.7.4.so","linked:libbare-hrtime.2.1.1.so","linked:libbare-inspect.3.1.4.so","linked:libbare-os.3.8.7.so","linked:libbare-os.3.9.1.so","linked:libbare-os.3.9.3.so","linked:libbare-path.3.1.1.so","linked:libbare-pipe.3.3.8.so","linked:libbare-pipe.4.1.5.so","linked:libbare-pipe.4.2.0.so","linked:libbare-pipe.4.2.2.so","linked:libbare-pipe.4.2.3.so","linked:libbare-signals.4.2.0.so","linked:libbare-signals.5.0.0.so","linked:libbare-stdio.1.0.2.so","linked:libbare-stdio.1.0.3.so","linked:libbare-tcp.1.9.1.so","linked:libbare-tcp.2.2.12.so","linked:libbare-tcp.2.5.1.so","linked:libbare-tcp.2.5.2.so","linked:libbare-tcp.2.5.4.so","linked:libbare-tls.3.1.7.so","linked:libbare-tls.3.1.8.so","linked:libbare-tty.5.1.0.so","linked:libbare-tty.5.1.1.so","linked:libbare-tty.5.1.2.so","linked:libbare-type.1.1.0.so","linked:libbare-url.2.4.0.so","linked:libbare-url.2.4.2.so","linked:libbare-url.2.4.5.so","linked:libbare-url.2.5.1.so","linked:libbare-zlib.1.4.0.so","linked:libbare-zlib.1.4.1.so","linked:libfs-native-extensions.1.4.5.so","linked:libfs-native-extensions.1.5.0.so","linked:libquickbit-native.2.4.8.so","linked:librocksdb-native.3.15.0.so","linked:librocksdb-native.3.15.2.so","linked:librocksdb-native.3.17.2.so","linked:libsimdle-native.1.3.9.so","linked:libsodium-native.5.1.0.so","linked:libudx-native.1.19.2.so","linked:libudx-native.1.20.6.so","linked:libudx-native.1.20.7.so"],"assets":[],"files":{"/lib/adopt.js":{"offset":0,"length":530,"mode":420},"/lib/choose-bundle.js":{"offset":530,"length":5108,"mode":420},"/lib/favela-api.js":{"offset":5638,"length":6150,"mode":420},"/lib/hosting.js":{"offset":11788,"length":2086,"mode":420},"/lib/mint.js":{"offset":13874,"length":519,"mode":420},"/lib/node.js":{"offset":14393,"length":61842,"mode":420},"/lib/ota.js":{"offset":76235,"length":24823,"mode":420},"/lib/repair-store-backend.js":{"offset":101058,"length":4398,"mode":420},"/lib/roster.js":{"offset":105456,"length":3821,"mode":420},"/lib/session.js":{"offset":109277,"length":9962,"mode":420},"/lib/shell-handoff.js":{"offset":119239,"length":5802,"mode":420},"/lib/utf8.js":{"offset":125041,"length":4296,"mode":420},"/node_modules/atproto-identity/lib/atproto-identity.js":{"offset":129337,"length":12646,"mode":420},"/node_modules/atproto-identity/lib/auth.js":{"offset":141983,"length":6575,"mode":420},"/node_modules/atproto-identity/lib/device-chain.js":{"offset":148558,"length":4232,"mode":420},"/node_modules/atproto-identity/lib/did-key.js":{"offset":152790,"length":2104,"mode":420},"/node_modules/atproto-identity/lib/did-plc.js":{"offset":154894,"length":2424,"mode":420},"/node_modules/atproto-identity/lib/hosting.js":{"offset":157318,"length":7965,"mode":420},"/node_modules/atproto-identity/lib/vault.js":{"offset":165283,"length":7529,"mode":420},"/node_modules/atproto-identity/node_modules/@ipld/dag-cbor/package.json":{"offset":172812,"length":3961,"mode":420},"/node_modules/atproto-identity/node_modules/@ipld/dag-cbor/src/index.js":{"offset":176773,"length":4040,"mode":420},"/node_modules/atproto-identity/node_modules/@noble/curves/esm/_shortw_utils.js":{"offset":180813,"length":589,"mode":420},"/node_modules/atproto-identity/node_modules/@noble/curves/esm/abstract/curve.js":{"offset":181402,"length":18539,"mode":420},"/node_modules/atproto-identity/node_modules/@noble/curves/esm/abstract/hash-to-curve.js":{"offset":199941,"length":8097,"mode":420},"/node_modules/atproto-identity/node_modules/@noble/curves/esm/abstract/modular.js":{"offset":208038,"length":21647,"mode":420},"/node_modules/atproto-identity/node_modules/@noble/curves/esm/abstract/weierstrass.js":{"offset":229685,"length":58901,"mode":420},"/node_modules/atproto-identity/node_modules/@noble/curves/esm/package.json":{"offset":288586,"length":47,"mode":420},"/node_modules/atproto-identity/node_modules/@noble/curves/esm/secp256k1.js":{"offset":288633,"length":12507,"mode":420},"/node_modules/atproto-identity/node_modules/@noble/curves/esm/utils.js":{"offset":301140,"length":12067,"mode":420},"/node_modules/atproto-identity/node_modules/@noble/hashes/esm/_md.js":{"offset":313207,"length":6192,"mode":420},"/node_modules/atproto-identity/node_modules/@noble/hashes/esm/_u64.js":{"offset":319399,"length":3081,"mode":420},"/node_modules/atproto-identity/node_modules/@noble/hashes/esm/crypto.js":{"offset":322480,"length":146,"mode":420},"/node_modules/atproto-identity/node_modules/@noble/hashes/esm/hmac.js":{"offset":322626,"length":2962,"mode":420},"/node_modules/atproto-identity/node_modules/@noble/hashes/esm/legacy.js":{"offset":325588,"length":9872,"mode":420},"/node_modules/atproto-identity/node_modules/@noble/hashes/esm/package.json":{"offset":335460,"length":147,"mode":420},"/node_modules/atproto-identity/node_modules/@noble/hashes/esm/pbkdf2.js":{"offset":335607,"length":3867,"mode":420},"/node_modules/atproto-identity/node_modules/@noble/hashes/esm/scrypt.js":{"offset":339474,"length":10103,"mode":420},"/node_modules/atproto-identity/node_modules/@noble/hashes/esm/sha2.js":{"offset":349577,"length":16832,"mode":420},"/node_modules/atproto-identity/node_modules/@noble/hashes/esm/utils.js":{"offset":366409,"length":10538,"mode":420},"/node_modules/atproto-identity/node_modules/@scure/base/lib/esm/index.js":{"offset":376947,"length":24662,"mode":420},"/node_modules/atproto-identity/node_modules/@scure/base/lib/esm/package.json":{"offset":401609,"length":43,"mode":420},"/node_modules/atproto-identity/node_modules/@scure/bip32/lib/esm/index.js":{"offset":401652,"length":10475,"mode":420},"/node_modules/atproto-identity/node_modules/@scure/bip32/lib/esm/package.json":{"offset":412127,"length":46,"mode":420},"/node_modules/atproto-identity/node_modules/@scure/bip39/esm/index.js":{"offset":412173,"length":6595,"mode":420},"/node_modules/atproto-identity/node_modules/@scure/bip39/esm/package.json":{"offset":418768,"length":22,"mode":420},"/node_modules/atproto-identity/node_modules/b4a/index.js":{"offset":418790,"length":4054,"mode":420},"/node_modules/atproto-identity/node_modules/b4a/package.json":{"offset":422844,"length":1245,"mode":420},"/node_modules/atproto-identity/node_modules/bare-ansi-escapes/index.js":{"offset":424089,"length":2255,"mode":420},"/node_modules/atproto-identity/node_modules/bare-ansi-escapes/package.json":{"offset":426344,"length":1178,"mode":420},"/node_modules/atproto-identity/node_modules/bare-assert/index.js":{"offset":427522,"length":2192,"mode":420},"/node_modules/atproto-identity/node_modules/bare-assert/package.json":{"offset":429714,"length":835,"mode":420},"/node_modules/atproto-identity/node_modules/bare-inspect/binding.js":{"offset":430549,"length":33,"mode":420},"/node_modules/atproto-identity/node_modules/bare-inspect/index.js":{"offset":430582,"length":23856,"mode":420},"/node_modules/atproto-identity/node_modules/bare-inspect/package.json":{"offset":454438,"length":1041,"mode":420},"/node_modules/atproto-identity/node_modules/bare-type/binding.js":{"offset":455479,"length":33,"mode":420},"/node_modules/atproto-identity/node_modules/bare-type/index.js":{"offset":455512,"length":4566,"mode":420},"/node_modules/atproto-identity/node_modules/bare-type/package.json":{"offset":460078,"length":938,"mode":420},"/node_modules/atproto-identity/node_modules/bip39-mnemonic/index.js":{"offset":461016,"length":4554,"mode":420},"/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json":{"offset":465570,"length":789,"mode":420},"/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/chinese_simplified.json":{"offset":466359,"length":12289,"mode":420},"/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/chinese_traditional.json":{"offset":478648,"length":12289,"mode":420},"/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/czech.json":{"offset":490937,"length":19042,"mode":420},"/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/english.json":{"offset":509979,"length":17213,"mode":420},"/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/french.json":{"offset":527192,"length":20874,"mode":420},"/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/index.js":{"offset":548066,"length":1406,"mode":420},"/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/italian.json":{"offset":549472,"length":20130,"mode":420},"/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/japanese.json":{"offset":569602,"length":30520,"mode":420},"/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/korean.json":{"offset":600122,"length":41929,"mode":420},"/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/lookup.json":{"offset":642051,"length":592224,"mode":420},"/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/portuguese.json":{"offset":1234275,"length":19768,"mode":420},"/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/russian.json":{"offset":1254043,"length":30635,"mode":420},"/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/spanish.json":{"offset":1284678,"length":18093,"mode":420},"/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/turkish.json":{"offset":1302771,"length":19421,"mode":420},"/node_modules/atproto-identity/node_modules/cborg/cborg.js":{"offset":1322192,"length":944,"mode":420},"/node_modules/atproto-identity/node_modules/cborg/lib/0uint.js":{"offset":1323136,"length":6580,"mode":420},"/node_modules/atproto-identity/node_modules/cborg/lib/1negint.js":{"offset":1329716,"length":2980,"mode":420},"/node_modules/atproto-identity/node_modules/cborg/lib/2bytes.js":{"offset":1332696,"length":3451,"mode":420},"/node_modules/atproto-identity/node_modules/cborg/lib/3string.js":{"offset":1336147,"length":3340,"mode":420},"/node_modules/atproto-identity/node_modules/cborg/lib/4array.js":{"offset":1339487,"length":2944,"mode":420},"/node_modules/atproto-identity/node_modules/cborg/lib/5map.js":{"offset":1342431,"length":2917,"mode":420},"/node_modules/atproto-identity/node_modules/cborg/lib/6tag.js":{"offset":1345348,"length":1957,"mode":420},"/node_modules/atproto-identity/node_modules/cborg/lib/7float.js":{"offset":1347305,"length":8633,"mode":420},"/node_modules/atproto-identity/node_modules/cborg/lib/bl.js":{"offset":1355938,"length":5316,"mode":420},"/node_modules/atproto-identity/node_modules/cborg/lib/byte-utils.js":{"offset":1361254,"length":8172,"mode":420},"/node_modules/atproto-identity/node_modules/cborg/lib/common.js":{"offset":1369426,"length":598,"mode":420},"/node_modules/atproto-identity/node_modules/cborg/lib/decode.js":{"offset":1370024,"length":9008,"mode":420},"/node_modules/atproto-identity/node_modules/cborg/lib/encode.js":{"offset":1379032,"length":21407,"mode":420},"/node_modules/atproto-identity/node_modules/cborg/lib/is.js":{"offset":1400439,"length":2061,"mode":420},"/node_modules/atproto-identity/node_modules/cborg/lib/jump.js":{"offset":1402500,"length":7859,"mode":420},"/node_modules/atproto-identity/node_modules/cborg/lib/tagged.js":{"offset":1410359,"length":2821,"mode":420},"/node_modules/atproto-identity/node_modules/cborg/lib/token.js":{"offset":1413180,"length":2019,"mode":420},"/node_modules/atproto-identity/node_modules/cborg/package.json":{"offset":1415199,"length":4241,"mode":420},"/node_modules/atproto-identity/node_modules/compact-encoding/endian.js":{"offset":1419440,"length":105,"mode":420},"/node_modules/atproto-identity/node_modules/compact-encoding/index.js":{"offset":1419545,"length":26406,"mode":420},"/node_modules/atproto-identity/node_modules/compact-encoding/lexint.js":{"offset":1445951,"length":2851,"mode":420},"/node_modules/atproto-identity/node_modules/compact-encoding/package.json":{"offset":1448802,"length":866,"mode":420},"/node_modules/atproto-identity/node_modules/compact-encoding/raw.js":{"offset":1449668,"length":3977,"mode":420},"/node_modules/atproto-identity/node_modules/hypercore-crypto/index.js":{"offset":1453645,"length":5031,"mode":420},"/node_modules/atproto-identity/node_modules/hypercore-crypto/package.json":{"offset":1458676,"length":1007,"mode":420},"/node_modules/atproto-identity/node_modules/keet-identity-key/index.js":{"offset":1459683,"length":6320,"mode":420},"/node_modules/atproto-identity/node_modules/keet-identity-key/lib/crypto.js":{"offset":1466003,"length":552,"mode":420},"/node_modules/atproto-identity/node_modules/keet-identity-key/lib/encoding.js":{"offset":1466555,"length":3695,"mode":420},"/node_modules/atproto-identity/node_modules/keet-identity-key/lib/keychain.js":{"offset":1470250,"length":3080,"mode":420},"/node_modules/atproto-identity/node_modules/keet-identity-key/package.json":{"offset":1473330,"length":887,"mode":420},"/node_modules/atproto-identity/node_modules/multiformats/dist/src/bases/base.js":{"offset":1474217,"length":6266,"mode":420},"/node_modules/atproto-identity/node_modules/multiformats/dist/src/bases/base32.js":{"offset":1480483,"length":1443,"mode":420},"/node_modules/atproto-identity/node_modules/multiformats/dist/src/bases/base36.js":{"offset":1481926,"length":327,"mode":420},"/node_modules/atproto-identity/node_modules/multiformats/dist/src/bases/base58.js":{"offset":1482253,"length":379,"mode":420},"/node_modules/atproto-identity/node_modules/multiformats/dist/src/bases/base64.js":{"offset":1482632,"length":793,"mode":420},"/node_modules/atproto-identity/node_modules/multiformats/dist/src/bytes.js":{"offset":1483425,"length":1246,"mode":420},"/node_modules/atproto-identity/node_modules/multiformats/dist/src/cid.js":{"offset":1484671,"length":13430,"mode":420},"/node_modules/atproto-identity/node_modules/multiformats/dist/src/hashes/digest.js":{"offset":1498101,"length":1915,"mode":420},"/node_modules/atproto-identity/node_modules/multiformats/dist/src/link/interface.js":{"offset":1500016,"length":48,"mode":420},"/node_modules/atproto-identity/node_modules/multiformats/dist/src/varint.js":{"offset":1500064,"length":398,"mode":420},"/node_modules/atproto-identity/node_modules/multiformats/dist/src/vendor/base-x.js":{"offset":1500462,"length":5458,"mode":420},"/node_modules/atproto-identity/node_modules/multiformats/dist/src/vendor/varint.js":{"offset":1505920,"length":2107,"mode":420},"/node_modules/atproto-identity/node_modules/multiformats/package.json":{"offset":1508027,"length":8176,"mode":420},"/node_modules/atproto-identity/node_modules/nanoassert/index.js":{"offset":1516203,"length":438,"mode":420},"/node_modules/atproto-identity/node_modules/nanoassert/package.json":{"offset":1516641,"length":647,"mode":420},"/node_modules/atproto-identity/node_modules/require-addon/lib/bare.js":{"offset":1517288,"length":45,"mode":420},"/node_modules/atproto-identity/node_modules/require-addon/package.json":{"offset":1517333,"length":1449,"mode":420},"/node_modules/atproto-identity/node_modules/sodium-hmac/hash/sha256.js":{"offset":1518782,"length":284,"mode":420},"/node_modules/atproto-identity/node_modules/sodium-hmac/hash/sha512.js":{"offset":1519066,"length":284,"mode":420},"/node_modules/atproto-identity/node_modules/sodium-hmac/index.js":{"offset":1519350,"length":2063,"mode":420},"/node_modules/atproto-identity/node_modules/sodium-hmac/package.json":{"offset":1521413,"length":670,"mode":420},"/node_modules/atproto-identity/node_modules/sodium-native/binding.js":{"offset":1522083,"length":89,"mode":420},"/node_modules/atproto-identity/node_modules/sodium-native/index.js":{"offset":1522172,"length":107894,"mode":420},"/node_modules/atproto-identity/node_modules/sodium-native/package.json":{"offset":1630066,"length":1478,"mode":420},"/node_modules/atproto-identity/node_modules/sodium-universal/index.js":{"offset":1631544,"length":42,"mode":420},"/node_modules/atproto-identity/node_modules/sodium-universal/package.json":{"offset":1631586,"length":1217,"mode":420},"/node_modules/atproto-identity/node_modules/which-runtime/index.js":{"offset":1632803,"length":1469,"mode":420},"/node_modules/atproto-identity/node_modules/which-runtime/package.json":{"offset":1634272,"length":863,"mode":420},"/node_modules/atproto-identity/package.json":{"offset":1635135,"length":791,"mode":420},"/node_modules/atproto-store/lib/tid.js":{"offset":1635926,"length":1681,"mode":420},"/node_modules/atproto-store/package.json":{"offset":1637607,"length":932,"mode":420},"/node_modules/b4a/index.js":{"offset":1638539,"length":4054,"mode":420},"/node_modules/b4a/package.json":{"offset":1642593,"length":1245,"mode":420},"/node_modules/bare-abort/binding.js":{"offset":1643838,"length":33,"mode":420},"/node_modules/bare-abort/index.js":{"offset":1643871,"length":69,"mode":420},"/node_modules/bare-abort/package.json":{"offset":1643940,"length":886,"mode":420},"/node_modules/bare-ansi-escapes/index.js":{"offset":1644826,"length":2255,"mode":420},"/node_modules/bare-ansi-escapes/package.json":{"offset":1647081,"length":1178,"mode":420},"/node_modules/bare-assert/index.js":{"offset":1648259,"length":2192,"mode":420},"/node_modules/bare-assert/package.json":{"offset":1650451,"length":835,"mode":420},"/node_modules/bare-buffer/binding.js":{"offset":1651286,"length":33,"mode":420},"/node_modules/bare-buffer/index.js":{"offset":1651319,"length":28020,"mode":420},"/node_modules/bare-buffer/lib/ascii.js":{"offset":1679339,"length":613,"mode":420},"/node_modules/bare-buffer/lib/base64.js":{"offset":1679952,"length":531,"mode":420},"/node_modules/bare-buffer/lib/base64url.js":{"offset":1680483,"length":534,"mode":420},"/node_modules/bare-buffer/lib/constants.js":{"offset":1681017,"length":74,"mode":420},"/node_modules/bare-buffer/lib/hex.js":{"offset":1681091,"length":392,"mode":420},"/node_modules/bare-buffer/lib/latin1.js":{"offset":1681483,"length":392,"mode":420},"/node_modules/bare-buffer/lib/utf16le.js":{"offset":1681875,"length":398,"mode":420},"/node_modules/bare-buffer/lib/utf8.js":{"offset":1682273,"length":519,"mode":420},"/node_modules/bare-buffer/package.json":{"offset":1682792,"length":1324,"mode":420},"/node_modules/bare-dns/binding.js":{"offset":1684116,"length":33,"mode":420},"/node_modules/bare-dns/index.js":{"offset":1684149,"length":3228,"mode":420},"/node_modules/bare-dns/lib/constants.js":{"offset":1687377,"length":851,"mode":420},"/node_modules/bare-dns/lib/errors.js":{"offset":1688228,"length":1242,"mode":420},"/node_modules/bare-dns/lib/promises.js":{"offset":1689470,"length":4824,"mode":420},"/node_modules/bare-dns/lib/records.js":{"offset":1694294,"length":3754,"mode":420},"/node_modules/bare-dns/lib/resolver.js":{"offset":1698048,"length":5504,"mode":420},"/node_modules/bare-dns/package.json":{"offset":1703552,"length":1578,"mode":420},"/node_modules/bare-env/index.js":{"offset":1705130,"length":1017,"mode":420},"/node_modules/bare-env/package.json":{"offset":1706147,"length":944,"mode":420},"/node_modules/bare-events/index.js":{"offset":1707091,"length":8307,"mode":420},"/node_modules/bare-events/lib/errors.js":{"offset":1715398,"length":671,"mode":420},"/node_modules/bare-events/package.json":{"offset":1716069,"length":1504,"mode":420},"/node_modules/bare-fetch/index.js":{"offset":1717573,"length":4061,"mode":420},"/node_modules/bare-fetch/lib/body.js":{"offset":1721634,"length":6397,"mode":420},"/node_modules/bare-fetch/lib/errors.js":{"offset":1728031,"length":1207,"mode":420},"/node_modules/bare-fetch/lib/headers.js":{"offset":1729238,"length":5064,"mode":420},"/node_modules/bare-fetch/lib/request.js":{"offset":1734302,"length":1690,"mode":420},"/node_modules/bare-fetch/lib/response-stream.js":{"offset":1735992,"length":1134,"mode":420},"/node_modules/bare-fetch/lib/response.js":{"offset":1737126,"length":1426,"mode":420},"/node_modules/bare-fetch/package.json":{"offset":1738552,"length":2066,"mode":420},"/node_modules/bare-form-data/index.js":{"offset":1740618,"length":5715,"mode":420},"/node_modules/bare-form-data/lib/errors.js":{"offset":1746333,"length":412,"mode":420},"/node_modules/bare-form-data/package.json":{"offset":1746745,"length":1004,"mode":420},"/node_modules/bare-fs/binding.js":{"offset":1747749,"length":33,"mode":420},"/node_modules/bare-fs/index.js":{"offset":1747782,"length":58907,"mode":420},"/node_modules/bare-fs/lib/constants.js":{"offset":1806689,"length":1494,"mode":420},"/node_modules/bare-fs/lib/errors.js":{"offset":1808183,"length":1166,"mode":420},"/node_modules/bare-fs/package.json":{"offset":1809349,"length":1654,"mode":420},"/node_modules/bare-fs/promises.js":{"offset":1811003,"length":2401,"mode":420},"/node_modules/bare-hrtime/binding.js":{"offset":1813404,"length":33,"mode":420},"/node_modules/bare-hrtime/index.js":{"offset":1813437,"length":319,"mode":420},"/node_modules/bare-hrtime/package.json":{"offset":1813756,"length":905,"mode":420},"/node_modules/bare-http-parser/index.js":{"offset":1814661,"length":17995,"mode":420},"/node_modules/bare-http-parser/lib/errors.js":{"offset":1832656,"length":845,"mode":420},"/node_modules/bare-http-parser/package.json":{"offset":1833501,"length":907,"mode":420},"/node_modules/bare-http1/index.js":{"offset":1834408,"length":2188,"mode":420},"/node_modules/bare-http1/lib/agent.js":{"offset":1836596,"length":4498,"mode":420},"/node_modules/bare-http1/lib/client-connection.js":{"offset":1841094,"length":3663,"mode":420},"/node_modules/bare-http1/lib/client-request.js":{"offset":1844757,"length":3734,"mode":420},"/node_modules/bare-http1/lib/constants.js":{"offset":1848491,"length":2016,"mode":420},"/node_modules/bare-http1/lib/errors.js":{"offset":1850507,"length":889,"mode":420},"/node_modules/bare-http1/lib/incoming-message.js":{"offset":1851396,"length":1568,"mode":420},"/node_modules/bare-http1/lib/outgoing-message.js":{"offset":1852964,"length":1635,"mode":420},"/node_modules/bare-http1/lib/server-connection.js":{"offset":1854599,"length":4041,"mode":420},"/node_modules/bare-http1/lib/server-response.js":{"offset":1858640,"length":3704,"mode":420},"/node_modules/bare-http1/lib/server.js":{"offset":1862344,"length":977,"mode":420},"/node_modules/bare-http1/lib/validate.js":{"offset":1863321,"length":1458,"mode":420},"/node_modules/bare-http1/package.json":{"offset":1864779,"length":1510,"mode":420},"/node_modules/bare-https/index.js":{"offset":1866289,"length":1498,"mode":420},"/node_modules/bare-https/lib/agent.js":{"offset":1867787,"length":394,"mode":420},"/node_modules/bare-https/lib/client-request.js":{"offset":1868181,"length":464,"mode":420},"/node_modules/bare-https/lib/server.js":{"offset":1868645,"length":1072,"mode":420},"/node_modules/bare-https/lib/socket.js":{"offset":1869717,"length":464,"mode":420},"/node_modules/bare-https/package.json":{"offset":1870181,"length":1028,"mode":420},"/node_modules/bare-inspect/binding.js":{"offset":1871209,"length":33,"mode":420},"/node_modules/bare-inspect/index.js":{"offset":1871242,"length":23856,"mode":420},"/node_modules/bare-inspect/package.json":{"offset":1895098,"length":1041,"mode":420},"/node_modules/bare-mime/index.js":{"offset":1896139,"length":4184,"mode":420},"/node_modules/bare-mime/package.json":{"offset":1900323,"length":808,"mode":420},"/node_modules/bare-net/index.js":{"offset":1901131,"length":9496,"mode":420},"/node_modules/bare-net/lib/constants.js":{"offset":1910627,"length":125,"mode":420},"/node_modules/bare-net/lib/errors.js":{"offset":1910752,"length":377,"mode":420},"/node_modules/bare-net/package.json":{"offset":1911129,"length":1245,"mode":420},"/node_modules/bare-os/binding.js":{"offset":1912374,"length":33,"mode":420},"/node_modules/bare-os/index.js":{"offset":1912407,"length":5216,"mode":420},"/node_modules/bare-os/lib/constants.js":{"offset":1917623,"length":143,"mode":420},"/node_modules/bare-os/lib/errors.js":{"offset":1917766,"length":453,"mode":420},"/node_modules/bare-os/package.json":{"offset":1918219,"length":1257,"mode":420},"/node_modules/bare-path/binding.js":{"offset":1919476,"length":33,"mode":420},"/node_modules/bare-path/index.js":{"offset":1919509,"length":287,"mode":420},"/node_modules/bare-path/lib/constants.js":{"offset":1919796,"length":247,"mode":420},"/node_modules/bare-path/lib/posix.js":{"offset":1920043,"length":6399,"mode":420},"/node_modules/bare-path/lib/shared.js":{"offset":1926442,"length":2148,"mode":420},"/node_modules/bare-path/lib/win32.js":{"offset":1928590,"length":13987,"mode":420},"/node_modules/bare-path/package.json":{"offset":1942577,"length":1106,"mode":420},"/node_modules/bare-pipe/binding.js":{"offset":1943683,"length":33,"mode":420},"/node_modules/bare-pipe/index.js":{"offset":1943716,"length":14499,"mode":420},"/node_modules/bare-pipe/lib/constants.js":{"offset":1958215,"length":352,"mode":420},"/node_modules/bare-pipe/lib/errors.js":{"offset":1958567,"length":699,"mode":420},"/node_modules/bare-pipe/package.json":{"offset":1959266,"length":1396,"mode":420},"/node_modules/bare-posix/package.json":{"offset":1960662,"length":1091,"mode":420},"/node_modules/bare-posix/unsupported.js":{"offset":1961753,"length":723,"mode":420},"/node_modules/bare-process/index.js":{"offset":1962476,"length":3189,"mode":420},"/node_modules/bare-process/package.json":{"offset":1965665,"length":1283,"mode":420},"/node_modules/bare-signals/binding.js":{"offset":1966948,"length":33,"mode":420},"/node_modules/bare-signals/index.js":{"offset":1966981,"length":1412,"mode":420},"/node_modules/bare-signals/lib/emitter.js":{"offset":1968393,"length":1260,"mode":420},"/node_modules/bare-signals/lib/errors.js":{"offset":1969653,"length":479,"mode":420},"/node_modules/bare-signals/package.json":{"offset":1970132,"length":1227,"mode":420},"/node_modules/bare-stdio/binding.js":{"offset":1971359,"length":33,"mode":420},"/node_modules/bare-stdio/index.js":{"offset":1971392,"length":1525,"mode":420},"/node_modules/bare-stdio/package.json":{"offset":1972917,"length":1232,"mode":420},"/node_modules/bare-stream/index.js":{"offset":1974149,"length":10904,"mode":420},"/node_modules/bare-stream/package.json":{"offset":1985053,"length":1676,"mode":420},"/node_modules/bare-stream/web.js":{"offset":1986729,"length":13980,"mode":420},"/node_modules/bare-tcp/binding.js":{"offset":2000709,"length":33,"mode":420},"/node_modules/bare-tcp/index.js":{"offset":2000742,"length":17400,"mode":420},"/node_modules/bare-tcp/lib/constants.js":{"offset":2018142,"length":167,"mode":420},"/node_modules/bare-tcp/lib/errors.js":{"offset":2018309,"length":797,"mode":420},"/node_modules/bare-tcp/lib/ip.js":{"offset":2019106,"length":2204,"mode":420},"/node_modules/bare-tcp/package.json":{"offset":2021310,"length":1400,"mode":420},"/node_modules/bare-tls/binding.js":{"offset":2022710,"length":33,"mode":420},"/node_modules/bare-tls/index.js":{"offset":2022743,"length":6951,"mode":420},"/node_modules/bare-tls/lib/constants.js":{"offset":2029694,"length":74,"mode":420},"/node_modules/bare-tls/lib/errors.js":{"offset":2029768,"length":358,"mode":420},"/node_modules/bare-tls/net.js":{"offset":2030126,"length":2563,"mode":420},"/node_modules/bare-tls/package.json":{"offset":2032689,"length":1454,"mode":420},"/node_modules/bare-tty/binding.js":{"offset":2034143,"length":33,"mode":420},"/node_modules/bare-tty/index.js":{"offset":2034176,"length":4638,"mode":420},"/node_modules/bare-tty/lib/constants.js":{"offset":2038814,"length":442,"mode":420},"/node_modules/bare-tty/package.json":{"offset":2039256,"length":1211,"mode":420},"/node_modules/bare-type/binding.js":{"offset":2040467,"length":33,"mode":420},"/node_modules/bare-type/index.js":{"offset":2040500,"length":4566,"mode":420},"/node_modules/bare-type/package.json":{"offset":2045066,"length":938,"mode":420},"/node_modules/bare-url/binding.js":{"offset":2046004,"length":33,"mode":420},"/node_modules/bare-url/index.js":{"offset":2046037,"length":9449,"mode":420},"/node_modules/bare-url/lib/errors.js":{"offset":2055486,"length":778,"mode":420},"/node_modules/bare-url/lib/url-search-params.js":{"offset":2056264,"length":4376,"mode":420},"/node_modules/bare-url/package.json":{"offset":2060640,"length":1219,"mode":420},"/node_modules/bare-zlib/binding.js":{"offset":2061859,"length":33,"mode":420},"/node_modules/bare-zlib/index.js":{"offset":2061892,"length":8166,"mode":420},"/node_modules/bare-zlib/lib/constants.js":{"offset":2070058,"length":74,"mode":420},"/node_modules/bare-zlib/lib/errors.js":{"offset":2070132,"length":1096,"mode":420},"/node_modules/bare-zlib/package.json":{"offset":2071228,"length":1463,"mode":420},"/node_modules/blind-pairing-core/index.js":{"offset":2072691,"length":10961,"mode":420},"/node_modules/blind-pairing-core/lib/errors.js":{"offset":2083652,"length":725,"mode":420},"/node_modules/blind-pairing-core/lib/messages.js":{"offset":2084377,"length":6120,"mode":420},"/node_modules/blind-pairing-core/package.json":{"offset":2090497,"length":1062,"mode":420},"/node_modules/bogon/index.js":{"offset":2091559,"length":4004,"mode":420},"/node_modules/bogon/package.json":{"offset":2095563,"length":656,"mode":420},"/node_modules/compact-encoding/endian.js":{"offset":2096219,"length":105,"mode":420},"/node_modules/compact-encoding/index.js":{"offset":2096324,"length":26406,"mode":420},"/node_modules/compact-encoding/lexint.js":{"offset":2122730,"length":2851,"mode":420},"/node_modules/compact-encoding/package.json":{"offset":2125581,"length":866,"mode":420},"/node_modules/compact-encoding/raw.js":{"offset":2126447,"length":3977,"mode":420},"/node_modules/events-universal/bare.js":{"offset":2130424,"length":40,"mode":420},"/node_modules/events-universal/package.json":{"offset":2130464,"length":908,"mode":420},"/node_modules/fast-fifo/fixed-size.js":{"offset":2131372,"length":875,"mode":420},"/node_modules/fast-fifo/index.js":{"offset":2132247,"length":972,"mode":420},"/node_modules/fast-fifo/package.json":{"offset":2133219,"length":682,"mode":420},"/node_modules/favela-web/bin/favela-web.js":{"offset":2133901,"length":226987,"mode":420},"/node_modules/favela-web/lib/ap-followers.js":{"offset":2360888,"length":6134,"mode":420},"/node_modules/favela-web/lib/ap-inbox.js":{"offset":2367022,"length":2558,"mode":420},"/node_modules/favela-web/lib/appview.js":{"offset":2369580,"length":67917,"mode":420},"/node_modules/favela-web/lib/auth.js":{"offset":2437497,"length":6054,"mode":420},"/node_modules/favela-web/lib/bare-globals.js":{"offset":2443551,"length":1388,"mode":420},"/node_modules/favela-web/lib/blob-refs.js":{"offset":2444939,"length":7294,"mode":420},"/node_modules/favela-web/lib/blob-serve.js":{"offset":2452233,"length":2461,"mode":420},"/node_modules/favela-web/lib/bookmarks.js":{"offset":2454694,"length":2881,"mode":420},"/node_modules/favela-web/lib/bounded-fetch.js":{"offset":2457575,"length":5676,"mode":420},"/node_modules/favela-web/lib/check.js":{"offset":2463251,"length":8852,"mode":420},"/node_modules/favela-web/lib/cli.js":{"offset":2472103,"length":38603,"mode":420},"/node_modules/favela-web/lib/communities.js":{"offset":2510706,"length":4508,"mode":420},"/node_modules/favela-web/lib/conformance.js":{"offset":2515214,"length":11265,"mode":420},"/node_modules/favela-web/lib/constellation.js":{"offset":2526479,"length":8533,"mode":420},"/node_modules/favela-web/lib/curators.js":{"offset":2535012,"length":2978,"mode":420},"/node_modules/favela-web/lib/dns-txt.js":{"offset":2537990,"length":12306,"mode":420},"/node_modules/favela-web/lib/facets.js":{"offset":2550296,"length":5077,"mode":420},"/node_modules/favela-web/lib/feed-reactor.js":{"offset":2555373,"length":3518,"mode":420},"/node_modules/favela-web/lib/feedgen.js":{"offset":2558891,"length":9113,"mode":420},"/node_modules/favela-web/lib/followers.js":{"offset":2568004,"length":5358,"mode":420},"/node_modules/favela-web/lib/fronts-diag.js":{"offset":2573362,"length":4663,"mode":420},"/node_modules/favela-web/lib/gate-policy.js":{"offset":2578025,"length":4015,"mode":420},"/node_modules/favela-web/lib/handles.js":{"offset":2582040,"length":5869,"mode":420},"/node_modules/favela-web/lib/hosted-dids.js":{"offset":2587909,"length":4200,"mode":420},"/node_modules/favela-web/lib/inbound.js":{"offset":2592109,"length":9948,"mode":420},"/node_modules/favela-web/lib/label-firehose.js":{"offset":2602057,"length":3846,"mode":420},"/node_modules/favela-web/lib/labeler-export.js":{"offset":2605903,"length":5752,"mode":420},"/node_modules/favela-web/lib/labeler.js":{"offset":2611655,"length":3078,"mode":420},"/node_modules/favela-web/lib/labels.js":{"offset":2614733,"length":3460,"mode":420},"/node_modules/favela-web/lib/lens-import.js":{"offset":2618193,"length":12311,"mode":420},"/node_modules/favela-web/lib/lenses.js":{"offset":2630504,"length":6321,"mode":420},"/node_modules/favela-web/lib/link-drain.js":{"offset":2636825,"length":9194,"mode":420},"/node_modules/favela-web/lib/lists.js":{"offset":2646019,"length":6453,"mode":420},"/node_modules/favela-web/lib/mutes.js":{"offset":2652472,"length":3942,"mode":420},"/node_modules/favela-web/lib/notifications.js":{"offset":2656414,"length":5790,"mode":420},"/node_modules/favela-web/lib/pairing.js":{"offset":2662204,"length":980,"mode":420},"/node_modules/favela-web/lib/plc.js":{"offset":2663184,"length":987,"mode":420},"/node_modules/favela-web/lib/postgate.js":{"offset":2664171,"length":3480,"mode":420},"/node_modules/favela-web/lib/reach.js":{"offset":2667651,"length":3681,"mode":420},"/node_modules/favela-web/lib/record-fetch.js":{"offset":2671332,"length":9923,"mode":420},"/node_modules/favela-web/lib/render.js":{"offset":2681255,"length":163274,"mode":420},"/node_modules/favela-web/lib/repair-bytes.js":{"offset":2844529,"length":6965,"mode":420},"/node_modules/favela-web/lib/repair-strongrefs.js":{"offset":2851494,"length":5360,"mode":420},"/node_modules/favela-web/lib/repo-sync.js":{"offset":2856854,"length":16188,"mode":420},"/node_modules/favela-web/lib/retention.js":{"offset":2873042,"length":12293,"mode":420},"/node_modules/favela-web/lib/roster.js":{"offset":2885335,"length":2994,"mode":420},"/node_modules/favela-web/lib/scopes.js":{"offset":2888329,"length":2261,"mode":420},"/node_modules/favela-web/lib/search.js":{"offset":2890590,"length":4439,"mode":420},"/node_modules/favela-web/lib/sessions.js":{"offset":2895029,"length":3925,"mode":420},"/node_modules/favela-web/lib/sidecar.js":{"offset":2898954,"length":2976,"mode":420},"/node_modules/favela-web/lib/spacedust-socket.js":{"offset":2901930,"length":1334,"mode":420},"/node_modules/favela-web/lib/spacedust.js":{"offset":2903264,"length":16822,"mode":420},"/node_modules/favela-web/lib/static.js":{"offset":2920086,"length":3074,"mode":420},"/node_modules/favela-web/lib/strongref.js":{"offset":2923160,"length":2411,"mode":420},"/node_modules/favela-web/lib/threadgate.js":{"offset":2925571,"length":6244,"mode":420},"/node_modules/favela-web/lib/version.js":{"offset":2931815,"length":1023,"mode":420},"/node_modules/favela-web/lib/writer.js":{"offset":2932838,"length":18512,"mode":420},"/node_modules/favela-web/node_modules/@hyperswarm/secret-stream/index.js":{"offset":2951350,"length":16722,"mode":420},"/node_modules/favela-web/node_modules/@hyperswarm/secret-stream/lib/bridge.js":{"offset":2968072,"length":1273,"mode":420},"/node_modules/favela-web/node_modules/@hyperswarm/secret-stream/lib/handshake.js":{"offset":2969345,"length":1950,"mode":420},"/node_modules/favela-web/node_modules/@hyperswarm/secret-stream/package.json":{"offset":2971295,"length":1132,"mode":420},"/node_modules/favela-web/node_modules/@ipld/dag-cbor/package.json":{"offset":2972427,"length":3961,"mode":420},"/node_modules/favela-web/node_modules/@ipld/dag-cbor/src/index.js":{"offset":2976388,"length":4040,"mode":420},"/node_modules/favela-web/node_modules/adaptive-timeout/index.js":{"offset":2980428,"length":2424,"mode":420},"/node_modules/favela-web/node_modules/adaptive-timeout/package.json":{"offset":2982852,"length":972,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/index.js":{"offset":2983824,"length":92,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/lib/did-peer.js":{"offset":2983916,"length":67028,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/lib/car.js":{"offset":3050944,"length":3112,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/lib/cid.js":{"offset":3054056,"length":1924,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/lib/commit.js":{"offset":3055980,"length":1471,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/lib/mst.js":{"offset":3057451,"length":13309,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/lib/repo.js":{"offset":3070760,"length":4610,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/package.json":{"offset":3075370,"length":3961,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/src/index.js":{"offset":3079331,"length":4040,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/_shortw_utils.js":{"offset":3083371,"length":589,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/curve.js":{"offset":3083960,"length":18539,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/hash-to-curve.js":{"offset":3102499,"length":8097,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/modular.js":{"offset":3110596,"length":21647,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/weierstrass.js":{"offset":3132243,"length":58901,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json":{"offset":3191144,"length":47,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/secp256k1.js":{"offset":3191191,"length":12507,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/utils.js":{"offset":3203698,"length":12067,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/_md.js":{"offset":3215765,"length":6192,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/_u64.js":{"offset":3221957,"length":3081,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/crypto.js":{"offset":3225038,"length":146,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/hmac.js":{"offset":3225184,"length":2962,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json":{"offset":3228146,"length":147,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/sha2.js":{"offset":3228293,"length":16832,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js":{"offset":3245125,"length":10538,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/cborg.js":{"offset":3255663,"length":944,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js":{"offset":3256607,"length":6580,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/1negint.js":{"offset":3263187,"length":2980,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/2bytes.js":{"offset":3266167,"length":3451,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/3string.js":{"offset":3269618,"length":3340,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/4array.js":{"offset":3272958,"length":2944,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/5map.js":{"offset":3275902,"length":2917,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/6tag.js":{"offset":3278819,"length":1957,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/7float.js":{"offset":3280776,"length":8633,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/bl.js":{"offset":3289409,"length":5316,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/byte-utils.js":{"offset":3294725,"length":8172,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/common.js":{"offset":3302897,"length":598,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/decode.js":{"offset":3303495,"length":9008,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/encode.js":{"offset":3312503,"length":21407,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/is.js":{"offset":3333910,"length":2061,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/jump.js":{"offset":3335971,"length":7859,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/tagged.js":{"offset":3343830,"length":2821,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/lib/token.js":{"offset":3346651,"length":2019,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/cborg/package.json":{"offset":3348670,"length":4241,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base.js":{"offset":3352911,"length":6266,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base32.js":{"offset":3359177,"length":1443,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base36.js":{"offset":3360620,"length":327,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base58.js":{"offset":3360947,"length":379,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/bytes.js":{"offset":3361326,"length":1246,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/cid.js":{"offset":3362572,"length":13430,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/codecs/raw.js":{"offset":3376002,"length":238,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/hashes/digest.js":{"offset":3376240,"length":1915,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/link/interface.js":{"offset":3378155,"length":48,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/varint.js":{"offset":3378203,"length":398,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/vendor/base-x.js":{"offset":3378601,"length":5458,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/vendor/varint.js":{"offset":3384059,"length":2107,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/node_modules/multiformats/package.json":{"offset":3386166,"length":8176,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-repo/package.json":{"offset":3394342,"length":652,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/lib/corestore.js":{"offset":3394994,"length":1775,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/lib/firehose.js":{"offset":3396769,"length":4606,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/lib/read-view.js":{"offset":3401375,"length":6487,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/lib/repo-diff.js":{"offset":3407862,"length":12435,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/lib/repo-store.js":{"offset":3420297,"length":4701,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/lib/sequencer.js":{"offset":3424998,"length":3045,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/@hyperswarm/secret-stream/index.js":{"offset":3428043,"length":16722,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/@hyperswarm/secret-stream/lib/bridge.js":{"offset":3444765,"length":1273,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/@hyperswarm/secret-stream/lib/handshake.js":{"offset":3446038,"length":1950,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/@hyperswarm/secret-stream/package.json":{"offset":3447988,"length":1132,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/@ipld/dag-cbor/package.json":{"offset":3449120,"length":3961,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/@ipld/dag-cbor/src/index.js":{"offset":3453081,"length":4040,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/lib/car.js":{"offset":3457121,"length":3112,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/lib/cid.js":{"offset":3460233,"length":1924,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/lib/commit.js":{"offset":3462157,"length":1471,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/lib/mst.js":{"offset":3463628,"length":13309,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/lib/repo.js":{"offset":3476937,"length":4610,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/package.json":{"offset":3481547,"length":3961,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/src/index.js":{"offset":3485508,"length":4040,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/_shortw_utils.js":{"offset":3489548,"length":589,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/curve.js":{"offset":3490137,"length":18539,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/hash-to-curve.js":{"offset":3508676,"length":8097,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/modular.js":{"offset":3516773,"length":21647,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/weierstrass.js":{"offset":3538420,"length":58901,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json":{"offset":3597321,"length":47,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/secp256k1.js":{"offset":3597368,"length":12507,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/utils.js":{"offset":3609875,"length":12067,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/_md.js":{"offset":3621942,"length":6192,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/_u64.js":{"offset":3628134,"length":3081,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/crypto.js":{"offset":3631215,"length":146,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/hmac.js":{"offset":3631361,"length":2962,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json":{"offset":3634323,"length":147,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/sha2.js":{"offset":3634470,"length":16832,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js":{"offset":3651302,"length":10538,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/cborg.js":{"offset":3661840,"length":944,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js":{"offset":3662784,"length":6580,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/1negint.js":{"offset":3669364,"length":2980,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/2bytes.js":{"offset":3672344,"length":3451,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/3string.js":{"offset":3675795,"length":3340,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/4array.js":{"offset":3679135,"length":2944,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/5map.js":{"offset":3682079,"length":2917,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/6tag.js":{"offset":3684996,"length":1957,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/7float.js":{"offset":3686953,"length":8633,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/bl.js":{"offset":3695586,"length":5316,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/byte-utils.js":{"offset":3700902,"length":8172,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/common.js":{"offset":3709074,"length":598,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/decode.js":{"offset":3709672,"length":9008,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/encode.js":{"offset":3718680,"length":21407,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/is.js":{"offset":3740087,"length":2061,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/jump.js":{"offset":3742148,"length":7859,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/tagged.js":{"offset":3750007,"length":2821,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/token.js":{"offset":3752828,"length":2019,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json":{"offset":3754847,"length":4241,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base.js":{"offset":3759088,"length":6266,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base32.js":{"offset":3765354,"length":1443,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base36.js":{"offset":3766797,"length":327,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base58.js":{"offset":3767124,"length":379,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bytes.js":{"offset":3767503,"length":1246,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/cid.js":{"offset":3768749,"length":13430,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/codecs/raw.js":{"offset":3782179,"length":238,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/hashes/digest.js":{"offset":3782417,"length":1915,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/link/interface.js":{"offset":3784332,"length":48,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/varint.js":{"offset":3784380,"length":398,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/vendor/base-x.js":{"offset":3784778,"length":5458,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/vendor/varint.js":{"offset":3790236,"length":2107,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/package.json":{"offset":3792343,"length":8176,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/atproto-repo/package.json":{"offset":3800519,"length":652,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/b4a/index.js":{"offset":3801171,"length":4054,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/b4a/package.json":{"offset":3805225,"length":1245,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-ansi-escapes/index.js":{"offset":3806470,"length":2255,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-ansi-escapes/package.json":{"offset":3808725,"length":1178,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-assert/index.js":{"offset":3809903,"length":2192,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-assert/package.json":{"offset":3812095,"length":835,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-events/index.js":{"offset":3812930,"length":8307,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-events/lib/errors.js":{"offset":3821237,"length":671,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-events/package.json":{"offset":3821908,"length":1504,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-fs/binding.js":{"offset":3823412,"length":33,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-fs/index.js":{"offset":3823445,"length":58907,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-fs/lib/constants.js":{"offset":3882352,"length":1494,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-fs/lib/errors.js":{"offset":3883846,"length":1163,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-fs/package.json":{"offset":3885009,"length":1654,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-fs/promises.js":{"offset":3886663,"length":2401,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-inspect/binding.js":{"offset":3889064,"length":33,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-inspect/index.js":{"offset":3889097,"length":23856,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-inspect/package.json":{"offset":3912953,"length":1041,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-os/binding.js":{"offset":3913994,"length":33,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-os/index.js":{"offset":3914027,"length":5216,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-os/lib/constants.js":{"offset":3919243,"length":143,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-os/lib/errors.js":{"offset":3919386,"length":453,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-os/package.json":{"offset":3919839,"length":1257,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-path/index.js":{"offset":3921096,"length":287,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-path/lib/constants.js":{"offset":3921383,"length":247,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-path/lib/posix.js":{"offset":3921630,"length":6005,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-path/lib/shared.js":{"offset":3927635,"length":1926,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-path/lib/win32.js":{"offset":3929561,"length":13591,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-path/package.json":{"offset":3943152,"length":1036,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-stream/index.js":{"offset":3944188,"length":10904,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-stream/package.json":{"offset":3955092,"length":1676,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-stream/web.js":{"offset":3956768,"length":13980,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-type/binding.js":{"offset":3970748,"length":33,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-type/index.js":{"offset":3970781,"length":4566,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-type/package.json":{"offset":3975347,"length":938,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-url/binding.js":{"offset":3976285,"length":33,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-url/index.js":{"offset":3976318,"length":9449,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-url/lib/errors.js":{"offset":3985767,"length":778,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-url/lib/url-search-params.js":{"offset":3986545,"length":4331,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/bare-url/package.json":{"offset":3990876,"length":1219,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/big-sparse-array/index.js":{"offset":3992095,"length":2471,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/big-sparse-array/package.json":{"offset":3994566,"length":636,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/cborg.js":{"offset":3995202,"length":944,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/0uint.js":{"offset":3996146,"length":6580,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/1negint.js":{"offset":4002726,"length":2980,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/2bytes.js":{"offset":4005706,"length":3451,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/3string.js":{"offset":4009157,"length":3340,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/4array.js":{"offset":4012497,"length":2944,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/5map.js":{"offset":4015441,"length":2917,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/6tag.js":{"offset":4018358,"length":1957,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/7float.js":{"offset":4020315,"length":8633,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/bl.js":{"offset":4028948,"length":5316,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/byte-utils.js":{"offset":4034264,"length":8172,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/common.js":{"offset":4042436,"length":598,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/decode.js":{"offset":4043034,"length":9008,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/encode.js":{"offset":4052042,"length":21407,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/is.js":{"offset":4073449,"length":2061,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/jump.js":{"offset":4075510,"length":7859,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/tagged.js":{"offset":4083369,"length":2821,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/lib/token.js":{"offset":4086190,"length":2019,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/cborg/package.json":{"offset":4088209,"length":4241,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/codecs/index.js":{"offset":4092450,"length":2416,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/codecs/package.json":{"offset":4094866,"length":655,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/compact-encoding/endian.js":{"offset":4095521,"length":105,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/compact-encoding/index.js":{"offset":4095626,"length":26406,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/compact-encoding/lexint.js":{"offset":4122032,"length":2851,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/compact-encoding/package.json":{"offset":4124883,"length":866,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/compact-encoding/raw.js":{"offset":4125749,"length":3977,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/corestore/index.js":{"offset":4129726,"length":19847,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/corestore/lib/audit.js":{"offset":4149573,"length":475,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/corestore/lib/notify.js":{"offset":4150048,"length":630,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/corestore/package.json":{"offset":4150678,"length":1350,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/debounceify/index.js":{"offset":4152028,"length":585,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/debounceify/package.json":{"offset":4152613,"length":567,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/device-file/index.js":{"offset":4153180,"length":6394,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/device-file/package.json":{"offset":4159574,"length":1190,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/events-universal/bare.js":{"offset":4160764,"length":40,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/events-universal/package.json":{"offset":4160804,"length":908,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/fast-fifo/fixed-size.js":{"offset":4161712,"length":875,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/fast-fifo/index.js":{"offset":4162587,"length":972,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/fast-fifo/package.json":{"offset":4163559,"length":682,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/fd-lock/index.js":{"offset":4164241,"length":1755,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/fd-lock/package.json":{"offset":4165996,"length":1099,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/flat-tree/index.js":{"offset":4167095,"length":8164,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/flat-tree/package.json":{"offset":4175259,"length":631,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/fs-native-extensions/binding.js":{"offset":4175890,"length":90,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/fs-native-extensions/index.js":{"offset":4175980,"length":7239,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/fs-native-extensions/package.json":{"offset":4183219,"length":1790,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hyperbee/index.js":{"offset":4185009,"length":46445,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hyperbee/iterators/diff.js":{"offset":4231454,"length":5358,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hyperbee/iterators/history.js":{"offset":4236812,"length":1631,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hyperbee/iterators/local.js":{"offset":4238443,"length":1170,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hyperbee/iterators/range.js":{"offset":4239613,"length":5869,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hyperbee/lib/extension.js":{"offset":4245482,"length":3488,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hyperbee/lib/messages.js":{"offset":4248970,"length":28162,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hyperbee/package.json":{"offset":4277132,"length":1585,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-crypto/index.js":{"offset":4278717,"length":5031,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-crypto/package.json":{"offset":4283748,"length":1007,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-errors/index.js":{"offset":4284755,"length":4896,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-errors/package.json":{"offset":4289651,"length":688,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-id-encoding/index.js":{"offset":4290339,"length":923,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-id-encoding/package.json":{"offset":4291262,"length":799,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-storage/encoding/external.js":{"offset":4292061,"length":264,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-storage/encoding/spec/hyperschema/index.js":{"offset":4292325,"length":16796,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-storage/index.js":{"offset":4309121,"length":33493,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-storage/lib/block-dependency-stream.js":{"offset":4342614,"length":2557,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-storage/lib/close-error-stream.js":{"offset":4345171,"length":276,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-storage/lib/keys.js":{"offset":4345447,"length":8751,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-storage/lib/streams.js":{"offset":4354198,"length":5686,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-storage/lib/tx.js":{"offset":4359884,"length":11683,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-storage/lib/view.js":{"offset":4371567,"length":8379,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-storage/migrations/0/index.js":{"offset":4379946,"length":20125,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-storage/migrations/0/messages.js":{"offset":4400071,"length":26402,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-storage/migrations/1/index.js":{"offset":4426473,"length":1181,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore-storage/package.json":{"offset":4427654,"length":1827,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/index.js":{"offset":4429481,"length":40241,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/audit.js":{"offset":4469722,"length":3834,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/bit-interlude.js":{"offset":4473556,"length":4257,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/bitfield.js":{"offset":4477813,"length":12115,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/caps.js":{"offset":4489928,"length":1537,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/compat.js":{"offset":4491465,"length":477,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/copy-prologue.js":{"offset":4491942,"length":5999,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/core.js":{"offset":4497941,"length":28356,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/default-encryption.js":{"offset":4526297,"length":3453,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/download.js":{"offset":4529750,"length":1278,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/feature-flags.js":{"offset":4531028,"length":38,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/fully-remote-proof.js":{"offset":4531066,"length":3470,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/hotswap-queue.js":{"offset":4534536,"length":1498,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/info.js":{"offset":4536034,"length":1517,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/inspect.js":{"offset":4537551,"length":1983,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/mark-bitfield.js":{"offset":4539534,"length":2589,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/merkle-tree.js":{"offset":4542123,"length":34353,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/messages.js":{"offset":4576476,"length":28313,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/multisig.js":{"offset":4604789,"length":2851,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/mutex.js":{"offset":4607640,"length":1028,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/receiver-queue.js":{"offset":4608668,"length":1413,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/remote-bitfield.js":{"offset":4610081,"length":8124,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/replicator.js":{"offset":4618205,"length":88868,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/session-state.js":{"offset":4707073,"length":36297,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/streams.js":{"offset":4743370,"length":3034,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/verifier.js":{"offset":4746404,"length":9926,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/lib/wants.js":{"offset":4756330,"length":7204,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hypercore/package.json":{"offset":4763534,"length":2196,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hyperschema/package.json":{"offset":4765730,"length":1555,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/hyperschema/runtime.cjs":{"offset":4767285,"length":54,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/index-encoder/index.js":{"offset":4767339,"length":10596,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/index-encoder/package.json":{"offset":4777935,"length":928,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/is-options/index.js":{"offset":4778863,"length":140,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/is-options/package.json":{"offset":4779003,"length":605,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/bases/base.js":{"offset":4779608,"length":6266,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/bases/base32.js":{"offset":4785874,"length":1443,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/bases/base36.js":{"offset":4787317,"length":327,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/bases/base58.js":{"offset":4787644,"length":379,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/bytes.js":{"offset":4788023,"length":1246,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/cid.js":{"offset":4789269,"length":13430,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/hashes/digest.js":{"offset":4802699,"length":1915,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/link/interface.js":{"offset":4804614,"length":48,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/varint.js":{"offset":4804662,"length":398,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/vendor/base-x.js":{"offset":4805060,"length":5458,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/vendor/varint.js":{"offset":4810518,"length":2107,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/multiformats/package.json":{"offset":4812625,"length":8176,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/mutexify/index.js":{"offset":4820801,"length":536,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/mutexify/package.json":{"offset":4821337,"length":679,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/mutexify/promise.js":{"offset":4822016,"length":324,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/nanoassert/index.js":{"offset":4822340,"length":438,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/nanoassert/package.json":{"offset":4822778,"length":647,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/noise-curve-ed/index.js":{"offset":4823425,"length":1642,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/noise-curve-ed/package.json":{"offset":4825067,"length":808,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/noise-handshake/cipher.js":{"offset":4825875,"length":2817,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/noise-handshake/dh.js":{"offset":4828692,"length":1439,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/noise-handshake/hkdf.js":{"offset":4830131,"length":1092,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/noise-handshake/hmac.js":{"offset":4831223,"length":1273,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/noise-handshake/noise.js":{"offset":4832496,"length":6437,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/noise-handshake/package.json":{"offset":4838933,"length":638,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/noise-handshake/symmetric-state.js":{"offset":4839571,"length":2206,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/protocol-buffers-encodings/index.js":{"offset":4841777,"length":6489,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/protocol-buffers-encodings/package.json":{"offset":4848266,"length":719,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/protomux/index.js":{"offset":4848985,"length":19741,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/protomux/package.json":{"offset":4868726,"length":1059,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/queue-tick/package.json":{"offset":4869785,"length":669,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/queue-tick/process-next-tick.js":{"offset":4870454,"length":160,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/queue-tick/queue-microtask.js":{"offset":4870614,"length":108,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/quickbit-native/binding.js":{"offset":4870722,"length":90,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/quickbit-native/index.js":{"offset":4870812,"length":4683,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/quickbit-native/package.json":{"offset":4875495,"length":1104,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/quickbit-universal/fallback.js":{"offset":4876599,"length":10204,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/quickbit-universal/index.js":{"offset":4886803,"length":442,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/quickbit-universal/package.json":{"offset":4887245,"length":908,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/rache/index.js":{"offset":4888153,"length":2463,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/rache/package.json":{"offset":4890616,"length":602,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/random-array-iterator/index.js":{"offset":4891218,"length":1001,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/random-array-iterator/package.json":{"offset":4892219,"length":700,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/ready-resource/index.js":{"offset":4892919,"length":1091,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/ready-resource/package.json":{"offset":4894010,"length":812,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/refcounter/index.js":{"offset":4894822,"length":611,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/refcounter/package.json":{"offset":4895433,"length":451,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/require-addon/lib/bare.js":{"offset":4895884,"length":45,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/require-addon/package.json":{"offset":4895929,"length":1449,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/resolve-reject-promise/index.js":{"offset":4897378,"length":443,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/resolve-reject-promise/package.json":{"offset":4897821,"length":581,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/resource-on-exit/index.js":{"offset":4898402,"length":361,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/resource-on-exit/package.json":{"offset":4898763,"length":496,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/rocksdb-native/binding.js":{"offset":4899259,"length":90,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/rocksdb-native/index.js":{"offset":4899349,"length":5304,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/rocksdb-native/lib/batch.js":{"offset":4904653,"length":9605,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/rocksdb-native/lib/column-family.js":{"offset":4914258,"length":2930,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/rocksdb-native/lib/constants.js":{"offset":4917188,"length":621,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/rocksdb-native/lib/filter-policy.js":{"offset":4917809,"length":437,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/rocksdb-native/lib/iterator.js":{"offset":4918246,"length":4311,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/rocksdb-native/lib/snapshot.js":{"offset":4922557,"length":503,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/rocksdb-native/lib/state.js":{"offset":4923060,"length":13115,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/rocksdb-native/package.json":{"offset":4936175,"length":1863,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/safety-catch/index.js":{"offset":4938038,"length":543,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/safety-catch/package.json":{"offset":4938581,"length":547,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/scope-lock/index.js":{"offset":4939128,"length":1821,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/scope-lock/package.json":{"offset":4940949,"length":611,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/signal-promise/index.js":{"offset":4941560,"length":1252,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/signal-promise/package.json":{"offset":4942812,"length":503,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/signed-varint/index.js":{"offset":4943315,"length":435,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/signed-varint/package.json":{"offset":4943750,"length":523,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/simdle-native/binding.js":{"offset":4944273,"length":90,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/simdle-native/index.js":{"offset":4944363,"length":3474,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/simdle-native/package.json":{"offset":4947837,"length":1115,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/simdle-universal/fallback.js":{"offset":4948952,"length":5137,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/simdle-universal/index.js":{"offset":4954089,"length":103,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/simdle-universal/package.json":{"offset":4954192,"length":879,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/simdle-universal/scalar.js":{"offset":4955071,"length":469,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/sodium-native/binding.js":{"offset":4955540,"length":89,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/sodium-native/index.js":{"offset":4955629,"length":107894,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/sodium-native/package.json":{"offset":5063523,"length":1478,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/sodium-secretstream/index.js":{"offset":5065001,"length":2257,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/sodium-secretstream/package.json":{"offset":5067258,"length":657,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/sodium-universal/index.js":{"offset":5067915,"length":42,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/sodium-universal/package.json":{"offset":5067957,"length":1217,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/streamx/index.js":{"offset":5069174,"length":34248,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/streamx/lib/errors.js":{"offset":5103422,"length":1096,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/streamx/package.json":{"offset":5104518,"length":1225,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/teex/index.js":{"offset":5105743,"length":1107,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/teex/package.json":{"offset":5106850,"length":608,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/text-decoder/index.js":{"offset":5107458,"length":1371,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/text-decoder/lib/pass-through-decoder.js":{"offset":5108829,"length":269,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/text-decoder/lib/utf8-decoder.js":{"offset":5109098,"length":4429,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/text-decoder/package.json":{"offset":5113527,"length":990,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/timeout-refresh/browser.js":{"offset":5114517,"length":1098,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/timeout-refresh/index.js":{"offset":5115615,"length":184,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/timeout-refresh/node.js":{"offset":5115799,"length":928,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/timeout-refresh/package.json":{"offset":5116727,"length":619,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/unslab/index.js":{"offset":5117346,"length":913,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/unslab/package.json":{"offset":5118259,"length":613,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/varint/decode.js":{"offset":5118872,"length":508,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/varint/encode.js":{"offset":5119380,"length":452,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/varint/index.js":{"offset":5119832,"length":134,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/varint/length.js":{"offset":5119966,"length":471,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/varint/package.json":{"offset":5120437,"length":511,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/which-runtime/index.js":{"offset":5120948,"length":1469,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/which-runtime/package.json":{"offset":5122417,"length":863,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/xache/index.js":{"offset":5123280,"length":2477,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/xache/package.json":{"offset":5125757,"length":672,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/z32/index.js":{"offset":5126429,"length":2654,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/node_modules/z32/package.json":{"offset":5129083,"length":701,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/atproto-store/package.json":{"offset":5129784,"length":932,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/b4a/index.js":{"offset":5130716,"length":4054,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/b4a/package.json":{"offset":5134770,"length":1245,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/bare-events/index.js":{"offset":5136015,"length":8307,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/bare-events/lib/errors.js":{"offset":5144322,"length":671,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/bare-events/package.json":{"offset":5144993,"length":1504,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/bits-to-bytes/index.js":{"offset":5146497,"length":3083,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/bits-to-bytes/package.json":{"offset":5149580,"length":708,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/compact-encoding-bitfield/index.js":{"offset":5150288,"length":1967,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/endian.js":{"offset":5152255,"length":105,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/index.js":{"offset":5152360,"length":26406,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/lexint.js":{"offset":5178766,"length":2851,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/package.json":{"offset":5181617,"length":866,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/raw.js":{"offset":5182483,"length":3977,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/compact-encoding-bitfield/package.json":{"offset":5186460,"length":1109,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/compact-encoding/endian.js":{"offset":5187569,"length":105,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/compact-encoding/index.js":{"offset":5187674,"length":24454,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/compact-encoding/lexint.js":{"offset":5212128,"length":2851,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/compact-encoding/package.json":{"offset":5214979,"length":786,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/compact-encoding/raw.js":{"offset":5215765,"length":4093,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/protomux-rpc/index.js":{"offset":5219858,"length":9087,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/protomux-rpc/lib/errors.js":{"offset":5228945,"length":1273,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/protomux-rpc/node_modules/compact-encoding/endian.js":{"offset":5230218,"length":105,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/protomux-rpc/node_modules/compact-encoding/index.js":{"offset":5230323,"length":26406,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/protomux-rpc/node_modules/compact-encoding/lexint.js":{"offset":5256729,"length":2851,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/protomux-rpc/node_modules/compact-encoding/package.json":{"offset":5259580,"length":866,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/protomux-rpc/node_modules/compact-encoding/raw.js":{"offset":5260446,"length":3977,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/protomux-rpc/package.json":{"offset":5264423,"length":1188,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/protomux/index.js":{"offset":5265611,"length":19741,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/protomux/node_modules/compact-encoding/endian.js":{"offset":5285352,"length":105,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/protomux/node_modules/compact-encoding/index.js":{"offset":5285457,"length":26406,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/protomux/node_modules/compact-encoding/lexint.js":{"offset":5311863,"length":2851,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/protomux/node_modules/compact-encoding/package.json":{"offset":5314714,"length":866,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/protomux/node_modules/compact-encoding/raw.js":{"offset":5315580,"length":3977,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/protomux/package.json":{"offset":5319557,"length":1059,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/queue-tick/package.json":{"offset":5320616,"length":669,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/queue-tick/process-next-tick.js":{"offset":5321285,"length":160,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/queue-tick/queue-microtask.js":{"offset":5321445,"length":108,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/safety-catch/index.js":{"offset":5321553,"length":543,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/safety-catch/package.json":{"offset":5322096,"length":547,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/unslab/index.js":{"offset":5322643,"length":913,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/node_modules/unslab/package.json":{"offset":5323556,"length":613,"mode":420},"/node_modules/favela-web/node_modules/atproto-did-peer/package.json":{"offset":5324169,"length":1243,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/lib/atproto-identity.js":{"offset":5325412,"length":12646,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/lib/auth.js":{"offset":5338058,"length":6575,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/lib/did-key.js":{"offset":5344633,"length":2104,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/lib/did-plc.js":{"offset":5346737,"length":2424,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/lib/discovery.js":{"offset":5349161,"length":1010,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/lib/labels.js":{"offset":5350171,"length":2980,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/lib/plc-directory.js":{"offset":5353151,"length":9458,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/lib/web-auth.js":{"offset":5362609,"length":3862,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@ipld/dag-cbor/package.json":{"offset":5366471,"length":3961,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@ipld/dag-cbor/src/index.js":{"offset":5370432,"length":4040,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/curves/esm/_shortw_utils.js":{"offset":5374472,"length":589,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/curves/esm/abstract/curve.js":{"offset":5375061,"length":18539,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/curves/esm/abstract/hash-to-curve.js":{"offset":5393600,"length":8097,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/curves/esm/abstract/modular.js":{"offset":5401697,"length":21647,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/curves/esm/abstract/weierstrass.js":{"offset":5423344,"length":58901,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/curves/esm/nist.js":{"offset":5482245,"length":6148,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/curves/esm/p256.js":{"offset":5488393,"length":769,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/curves/esm/package.json":{"offset":5489162,"length":47,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/curves/esm/secp256k1.js":{"offset":5489209,"length":12507,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/curves/esm/utils.js":{"offset":5501716,"length":12067,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/hashes/esm/_md.js":{"offset":5513783,"length":6192,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/hashes/esm/_u64.js":{"offset":5519975,"length":3081,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/hashes/esm/crypto.js":{"offset":5523056,"length":146,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/hashes/esm/hmac.js":{"offset":5523202,"length":2962,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/hashes/esm/legacy.js":{"offset":5526164,"length":9872,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/hashes/esm/package.json":{"offset":5536036,"length":147,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/hashes/esm/pbkdf2.js":{"offset":5536183,"length":3867,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/hashes/esm/scrypt.js":{"offset":5540050,"length":10103,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/hashes/esm/sha2.js":{"offset":5550153,"length":16832,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@noble/hashes/esm/utils.js":{"offset":5566985,"length":10538,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@scure/base/lib/esm/index.js":{"offset":5577523,"length":24662,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@scure/base/lib/esm/package.json":{"offset":5602185,"length":43,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@scure/bip32/lib/esm/index.js":{"offset":5602228,"length":10475,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@scure/bip32/lib/esm/package.json":{"offset":5612703,"length":46,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@scure/bip39/esm/index.js":{"offset":5612749,"length":6595,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/@scure/bip39/esm/package.json":{"offset":5619344,"length":22,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/b4a/index.js":{"offset":5619366,"length":4054,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/b4a/package.json":{"offset":5623420,"length":1245,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/bare-ansi-escapes/index.js":{"offset":5624665,"length":2255,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/bare-ansi-escapes/package.json":{"offset":5626920,"length":1178,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/bare-assert/index.js":{"offset":5628098,"length":2192,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/bare-assert/package.json":{"offset":5630290,"length":835,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/bare-inspect/binding.js":{"offset":5631125,"length":33,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/bare-inspect/index.js":{"offset":5631158,"length":23856,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/bare-inspect/package.json":{"offset":5655014,"length":1041,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/bare-type/binding.js":{"offset":5656055,"length":33,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/bare-type/index.js":{"offset":5656088,"length":4566,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/bare-type/package.json":{"offset":5660654,"length":938,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/cborg.js":{"offset":5661592,"length":944,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/0uint.js":{"offset":5662536,"length":6580,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/1negint.js":{"offset":5669116,"length":2980,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/2bytes.js":{"offset":5672096,"length":3451,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/3string.js":{"offset":5675547,"length":3340,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/4array.js":{"offset":5678887,"length":2944,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/5map.js":{"offset":5681831,"length":2917,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/6tag.js":{"offset":5684748,"length":1957,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/7float.js":{"offset":5686705,"length":8633,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/bl.js":{"offset":5695338,"length":5316,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/byte-utils.js":{"offset":5700654,"length":8172,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/common.js":{"offset":5708826,"length":598,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/decode.js":{"offset":5709424,"length":9008,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/encode.js":{"offset":5718432,"length":21407,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/is.js":{"offset":5739839,"length":2061,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/jump.js":{"offset":5741900,"length":7859,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/tagged.js":{"offset":5749759,"length":2821,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/lib/token.js":{"offset":5752580,"length":2019,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/cborg/package.json":{"offset":5754599,"length":4241,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/compact-encoding/endian.js":{"offset":5758840,"length":105,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/compact-encoding/index.js":{"offset":5758945,"length":26406,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/compact-encoding/lexint.js":{"offset":5785351,"length":2851,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/compact-encoding/package.json":{"offset":5788202,"length":866,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/compact-encoding/raw.js":{"offset":5789068,"length":3977,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/hypercore-crypto/index.js":{"offset":5793045,"length":5031,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/hypercore-crypto/package.json":{"offset":5798076,"length":1007,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/multiformats/dist/src/bases/base.js":{"offset":5799083,"length":6266,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/multiformats/dist/src/bases/base32.js":{"offset":5805349,"length":1443,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/multiformats/dist/src/bases/base36.js":{"offset":5806792,"length":327,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/multiformats/dist/src/bases/base58.js":{"offset":5807119,"length":379,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/multiformats/dist/src/bases/base64.js":{"offset":5807498,"length":793,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/multiformats/dist/src/bytes.js":{"offset":5808291,"length":1246,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/multiformats/dist/src/cid.js":{"offset":5809537,"length":13430,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/multiformats/dist/src/hashes/digest.js":{"offset":5822967,"length":1915,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/multiformats/dist/src/link/interface.js":{"offset":5824882,"length":48,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/multiformats/dist/src/varint.js":{"offset":5824930,"length":398,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/multiformats/dist/src/vendor/base-x.js":{"offset":5825328,"length":5458,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/multiformats/dist/src/vendor/varint.js":{"offset":5830786,"length":2107,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/multiformats/package.json":{"offset":5832893,"length":8176,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/require-addon/lib/bare.js":{"offset":5841069,"length":45,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/require-addon/package.json":{"offset":5841114,"length":1449,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/sodium-native/binding.js":{"offset":5842563,"length":89,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/sodium-native/index.js":{"offset":5842652,"length":107894,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/sodium-native/package.json":{"offset":5950546,"length":1478,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/sodium-universal/index.js":{"offset":5952024,"length":42,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/sodium-universal/package.json":{"offset":5952066,"length":1217,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/which-runtime/index.js":{"offset":5953283,"length":1469,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/node_modules/which-runtime/package.json":{"offset":5954752,"length":863,"mode":420},"/node_modules/favela-web/node_modules/atproto-identity/package.json":{"offset":5955615,"length":791,"mode":420},"/node_modules/favela-web/node_modules/atproto-repo/lib/car.js":{"offset":5956406,"length":3112,"mode":420},"/node_modules/favela-web/node_modules/atproto-repo/lib/cid.js":{"offset":5959518,"length":1924,"mode":420},"/node_modules/favela-web/node_modules/atproto-repo/lib/commit.js":{"offset":5961442,"length":1471,"mode":420},"/node_modules/favela-web/node_modules/atproto-repo/lib/mst.js":{"offset":5962913,"length":13309,"mode":420},"/node_modules/favela-web/node_modules/atproto-repo/lib/repo.js":{"offset":5976222,"length":4610,"mode":420},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/package.json":{"offset":5980832,"length":3961,"mode":420},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/src/index.js":{"offset":5984793,"length":4040,"mode":420},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/curves/esm/_shortw_utils.js":{"offset":5988833,"length":589,"mode":420},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/curve.js":{"offset":5989422,"length":18539,"mode":420},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/hash-to-curve.js":{"offset":6007961,"length":8097,"mode":420},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/modular.js":{"offset":6016058,"length":21647,"mode":420},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/weierstrass.js":{"offset":6037705,"length":58901,"mode":420},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json":{"offset":6096606,"length":47,"mode":420},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/curves/esm/secp256k1.js":{"offset":6096653,"length":12507,"mode":420},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/curves/esm/utils.js":{"offset":6109160,"length":12067,"mode":420},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/hashes/esm/_md.js":{"offset":6121227,"length":6192,"mode":420},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/hashes/esm/_u64.js":{"offset":6127419,"length":3081,"mode":420},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/hashes/esm/crypto.js":{"offset":6130500,"length":146,"mode":420},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/hashes/esm/hmac.js":{"offset":6130646,"length":2962,"mode":420},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json":{"offset":6133608,"length":147,"mode":420},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/hashes/esm/sha2.js":{"offset":6133755,"length":16832,"mode":420},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js":{"offset":6150587,"length":10538,"mode":420},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/cborg.js":{"offset":6161125,"length":944,"mode":420},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js":{"offset":6162069,"length":6580,"mode":420},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/1negint.js":{"offset":6168649,"length":2980,"mode":420},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/2bytes.js":{"offset":6171629,"length":3451,"mode":420},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/3string.js":{"offset":6175080,"length":3340,"mode":420},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/4array.js":{"offset":6178420,"length":2944,"mode":420},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/5map.js":{"offset":6181364,"length":2917,"mode":420},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/6tag.js":{"offset":6184281,"length":1957,"mode":420},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/7float.js":{"offset":6186238,"length":8633,"mode":420},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/bl.js":{"offset":6194871,"length":5316,"mode":420},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/byte-utils.js":{"offset":6200187,"length":8172,"mode":420},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/common.js":{"offset":6208359,"length":598,"mode":420},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/decode.js":{"offset":6208957,"length":9008,"mode":420},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/encode.js":{"offset":6217965,"length":21407,"mode":420},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/is.js":{"offset":6239372,"length":2061,"mode":420},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/jump.js":{"offset":6241433,"length":7859,"mode":420},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/tagged.js":{"offset":6249292,"length":2821,"mode":420},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/lib/token.js":{"offset":6252113,"length":2019,"mode":420},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/cborg/package.json":{"offset":6254132,"length":4241,"mode":420},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base.js":{"offset":6258373,"length":6266,"mode":420},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base32.js":{"offset":6264639,"length":1443,"mode":420},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base36.js":{"offset":6266082,"length":327,"mode":420},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base58.js":{"offset":6266409,"length":379,"mode":420},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/multiformats/dist/src/bytes.js":{"offset":6266788,"length":1246,"mode":420},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/multiformats/dist/src/cid.js":{"offset":6268034,"length":13430,"mode":420},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/multiformats/dist/src/codecs/raw.js":{"offset":6281464,"length":238,"mode":420},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/multiformats/dist/src/hashes/digest.js":{"offset":6281702,"length":1915,"mode":420},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/multiformats/dist/src/link/interface.js":{"offset":6283617,"length":48,"mode":420},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/multiformats/dist/src/varint.js":{"offset":6283665,"length":398,"mode":420},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/multiformats/dist/src/vendor/base-x.js":{"offset":6284063,"length":5458,"mode":420},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/multiformats/dist/src/vendor/varint.js":{"offset":6289521,"length":2107,"mode":420},"/node_modules/favela-web/node_modules/atproto-repo/node_modules/multiformats/package.json":{"offset":6291628,"length":8176,"mode":420},"/node_modules/favela-web/node_modules/atproto-repo/package.json":{"offset":6299804,"length":652,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/lib/pairing.js":{"offset":6300456,"length":5903,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/@hyperswarm/secret-stream/index.js":{"offset":6306359,"length":16722,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/@hyperswarm/secret-stream/lib/bridge.js":{"offset":6323081,"length":1273,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/@hyperswarm/secret-stream/lib/handshake.js":{"offset":6324354,"length":1950,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/@hyperswarm/secret-stream/package.json":{"offset":6326304,"length":1132,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/adaptive-timeout/index.js":{"offset":6327436,"length":2424,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/adaptive-timeout/package.json":{"offset":6329860,"length":972,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/index.js":{"offset":6330832,"length":4054,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/b4a/package.json":{"offset":6334886,"length":1245,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/bare-ansi-escapes/index.js":{"offset":6336131,"length":2255,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/bare-ansi-escapes/package.json":{"offset":6338386,"length":1178,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/bare-assert/index.js":{"offset":6339564,"length":2192,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/bare-assert/package.json":{"offset":6341756,"length":835,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/bare-events/index.js":{"offset":6342591,"length":8307,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/bare-events/lib/errors.js":{"offset":6350898,"length":671,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/bare-events/package.json":{"offset":6351569,"length":1504,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/bare-inspect/binding.js":{"offset":6353073,"length":33,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/bare-inspect/index.js":{"offset":6353106,"length":23856,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/bare-inspect/package.json":{"offset":6376962,"length":1041,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/bare-type/binding.js":{"offset":6378003,"length":33,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/bare-type/index.js":{"offset":6378036,"length":4566,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/bare-type/package.json":{"offset":6382602,"length":938,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/bits-to-bytes/index.js":{"offset":6383540,"length":3083,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/bits-to-bytes/package.json":{"offset":6386623,"length":708,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/blind-pairing/index.js":{"offset":6387331,"length":16910,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/blind-pairing/package.json":{"offset":6404241,"length":1000,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/blind-relay/index.js":{"offset":6405241,"length":13411,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/blind-relay/lib/errors.js":{"offset":6418652,"length":1036,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/blind-relay/node_modules/compact-encoding/endian.js":{"offset":6419688,"length":105,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/blind-relay/node_modules/compact-encoding/index.js":{"offset":6419793,"length":26406,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/blind-relay/node_modules/compact-encoding/lexint.js":{"offset":6446199,"length":2851,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/blind-relay/node_modules/compact-encoding/package.json":{"offset":6449050,"length":866,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/blind-relay/node_modules/compact-encoding/raw.js":{"offset":6449916,"length":3977,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/blind-relay/package.json":{"offset":6453893,"length":1231,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/bogon/index.js":{"offset":6455124,"length":4004,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/bogon/node_modules/compact-encoding/endian.js":{"offset":6459128,"length":105,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/bogon/node_modules/compact-encoding/index.js":{"offset":6459233,"length":26406,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/bogon/node_modules/compact-encoding/lexint.js":{"offset":6485639,"length":2851,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/bogon/node_modules/compact-encoding/package.json":{"offset":6488490,"length":866,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/bogon/node_modules/compact-encoding/raw.js":{"offset":6489356,"length":3977,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/bogon/package.json":{"offset":6493333,"length":656,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/compact-encoding-bitfield/index.js":{"offset":6493989,"length":1967,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/endian.js":{"offset":6495956,"length":105,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/index.js":{"offset":6496061,"length":26406,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/lexint.js":{"offset":6522467,"length":2851,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/package.json":{"offset":6525318,"length":866,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/raw.js":{"offset":6526184,"length":3977,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/compact-encoding-bitfield/package.json":{"offset":6530161,"length":1109,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/compact-encoding/endian.js":{"offset":6531270,"length":105,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/compact-encoding/index.js":{"offset":6531375,"length":24454,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/compact-encoding/lexint.js":{"offset":6555829,"length":2851,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/compact-encoding/package.json":{"offset":6558680,"length":786,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/compact-encoding/raw.js":{"offset":6559466,"length":4093,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/debounceify/index.js":{"offset":6563559,"length":585,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/debounceify/package.json":{"offset":6564144,"length":567,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/dht-rpc/index.js":{"offset":6564711,"length":29079,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/dht-rpc/lib/commands.js":{"offset":6593790,"length":107,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/dht-rpc/lib/errors.js":{"offset":6593897,"length":719,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/dht-rpc/lib/health.js":{"offset":6594616,"length":2998,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/dht-rpc/lib/io.js":{"offset":6597614,"length":16605,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/dht-rpc/lib/peer.js":{"offset":6614219,"length":583,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/dht-rpc/lib/query.js":{"offset":6614802,"length":9899,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/dht-rpc/lib/session.js":{"offset":6624701,"length":1103,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/dht-rpc/node_modules/compact-encoding/endian.js":{"offset":6625804,"length":105,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/dht-rpc/node_modules/compact-encoding/index.js":{"offset":6625909,"length":26406,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/dht-rpc/node_modules/compact-encoding/lexint.js":{"offset":6652315,"length":2851,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/dht-rpc/node_modules/compact-encoding/package.json":{"offset":6655166,"length":866,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/dht-rpc/node_modules/compact-encoding/raw.js":{"offset":6656032,"length":3977,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/dht-rpc/package.json":{"offset":6660009,"length":1396,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/events-universal/bare.js":{"offset":6661405,"length":40,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/events-universal/package.json":{"offset":6661445,"length":908,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/fast-fifo/fixed-size.js":{"offset":6662353,"length":875,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/fast-fifo/index.js":{"offset":6663228,"length":972,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/fast-fifo/package.json":{"offset":6664200,"length":682,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hypercore-crypto/index.js":{"offset":6664882,"length":5031,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hypercore-crypto/node_modules/compact-encoding/endian.js":{"offset":6669913,"length":105,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hypercore-crypto/node_modules/compact-encoding/index.js":{"offset":6670018,"length":26406,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hypercore-crypto/node_modules/compact-encoding/lexint.js":{"offset":6696424,"length":2851,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hypercore-crypto/node_modules/compact-encoding/package.json":{"offset":6699275,"length":866,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hypercore-crypto/node_modules/compact-encoding/raw.js":{"offset":6700141,"length":3977,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hypercore-crypto/package.json":{"offset":6704118,"length":1007,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hypercore-id-encoding/index.js":{"offset":6705125,"length":923,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hypercore-id-encoding/package.json":{"offset":6706048,"length":799,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht-address/index.js":{"offset":6706847,"length":357,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht-address/node_modules/compact-encoding/endian.js":{"offset":6707204,"length":105,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht-address/node_modules/compact-encoding/index.js":{"offset":6707309,"length":26406,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht-address/node_modules/compact-encoding/lexint.js":{"offset":6733715,"length":2851,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht-address/node_modules/compact-encoding/package.json":{"offset":6736566,"length":866,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht-address/node_modules/compact-encoding/raw.js":{"offset":6737432,"length":3977,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht-address/package.json":{"offset":6741409,"length":1046,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht-address/spec/hyperschema/index.js":{"offset":6742455,"length":2106,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/index.js":{"offset":6744561,"length":16589,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/announcer.js":{"offset":6761150,"length":7533,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/connect.js":{"offset":6768683,"length":25203,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/connection-pool.js":{"offset":6793886,"length":3050,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/constants.js":{"offset":6796936,"length":1178,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/crypto.js":{"offset":6798114,"length":632,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/encode.js":{"offset":6798746,"length":446,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/errors.js":{"offset":6799192,"length":3713,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/holepuncher.js":{"offset":6802905,"length":10003,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/messages.js":{"offset":6812908,"length":12057,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/nat.js":{"offset":6824965,"length":4714,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/noise-wrap.js":{"offset":6829679,"length":1669,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/persistent.js":{"offset":6831348,"length":8361,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/raw-stream-set.js":{"offset":6839709,"length":1511,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/relay-connection.js":{"offset":6841220,"length":2062,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/router.js":{"offset":6843282,"length":6978,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/secure-payload.js":{"offset":6850260,"length":1491,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/semaphore.js":{"offset":6851751,"length":1577,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/server.js":{"offset":6853328,"length":22065,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/sleeper.js":{"offset":6875393,"length":690,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/lib/socket-pool.js":{"offset":6876083,"length":4343,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/endian.js":{"offset":6880426,"length":105,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/index.js":{"offset":6880531,"length":26406,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/lexint.js":{"offset":6906937,"length":2851,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/package.json":{"offset":6909788,"length":866,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/raw.js":{"offset":6910654,"length":3977,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperdht/package.json":{"offset":6914631,"length":2007,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperschema/node_modules/compact-encoding/endian.js":{"offset":6916638,"length":105,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperschema/node_modules/compact-encoding/index.js":{"offset":6916743,"length":26406,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperschema/node_modules/compact-encoding/lexint.js":{"offset":6943149,"length":2851,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperschema/node_modules/compact-encoding/package.json":{"offset":6946000,"length":866,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperschema/node_modules/compact-encoding/raw.js":{"offset":6946866,"length":3977,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperschema/package.json":{"offset":6950843,"length":1555,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperschema/runtime.cjs":{"offset":6952398,"length":54,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperswarm/index.js":{"offset":6952452,"length":18589,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperswarm/lib/bulk-timer.js":{"offset":6971041,"length":728,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperswarm/lib/connection-set.js":{"offset":6971769,"length":823,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperswarm/lib/peer-discovery.js":{"offset":6972592,"length":9296,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperswarm/lib/peer-info.js":{"offset":6981888,"length":2688,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperswarm/lib/retry-timer.js":{"offset":6984576,"length":1889,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/hyperswarm/package.json":{"offset":6986465,"length":1515,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/is-options/index.js":{"offset":6987980,"length":140,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/is-options/package.json":{"offset":6988120,"length":605,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/kademlia-routing-table/index.js":{"offset":6988725,"length":4145,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/kademlia-routing-table/package.json":{"offset":6992870,"length":967,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/nanoassert/index.js":{"offset":6993837,"length":438,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/nanoassert/package.json":{"offset":6994275,"length":647,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/nat-sampler/index.js":{"offset":6994922,"length":1550,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/nat-sampler/package.json":{"offset":6996472,"length":608,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/noise-curve-ed/index.js":{"offset":6997080,"length":1642,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/noise-curve-ed/package.json":{"offset":6998722,"length":808,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/noise-handshake/cipher.js":{"offset":6999530,"length":2817,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/noise-handshake/dh.js":{"offset":7002347,"length":1439,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/noise-handshake/hkdf.js":{"offset":7003786,"length":1092,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/noise-handshake/hmac.js":{"offset":7004878,"length":1273,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/noise-handshake/noise.js":{"offset":7006151,"length":6437,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/noise-handshake/package.json":{"offset":7012588,"length":638,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/noise-handshake/symmetric-state.js":{"offset":7013226,"length":2206,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/protomux/index.js":{"offset":7015432,"length":19741,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/protomux/node_modules/compact-encoding/endian.js":{"offset":7035173,"length":105,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/protomux/node_modules/compact-encoding/index.js":{"offset":7035278,"length":26406,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/protomux/node_modules/compact-encoding/lexint.js":{"offset":7061684,"length":2851,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/protomux/node_modules/compact-encoding/package.json":{"offset":7064535,"length":866,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/protomux/node_modules/compact-encoding/raw.js":{"offset":7065401,"length":3977,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/protomux/package.json":{"offset":7069378,"length":1059,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/queue-tick/package.json":{"offset":7070437,"length":669,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/queue-tick/process-next-tick.js":{"offset":7071106,"length":160,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/queue-tick/queue-microtask.js":{"offset":7071266,"length":108,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/ready-resource/index.js":{"offset":7071374,"length":1091,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/ready-resource/package.json":{"offset":7072465,"length":812,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/record-cache/index.js":{"offset":7073277,"length":3668,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/record-cache/package.json":{"offset":7076945,"length":612,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/require-addon/lib/bare.js":{"offset":7077557,"length":45,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/require-addon/package.json":{"offset":7077602,"length":1449,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/safety-catch/index.js":{"offset":7079051,"length":543,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/safety-catch/package.json":{"offset":7079594,"length":547,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/shuffled-priority-queue/index.js":{"offset":7080141,"length":2607,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/shuffled-priority-queue/package.json":{"offset":7082748,"length":691,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/signal-promise/index.js":{"offset":7083439,"length":1252,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/signal-promise/package.json":{"offset":7084691,"length":503,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/sodium-native/binding.js":{"offset":7085194,"length":89,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/sodium-native/index.js":{"offset":7085283,"length":107894,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/sodium-native/package.json":{"offset":7193177,"length":1478,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/sodium-secretstream/index.js":{"offset":7194655,"length":2257,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/sodium-secretstream/package.json":{"offset":7196912,"length":657,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/sodium-universal/index.js":{"offset":7197569,"length":42,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/sodium-universal/package.json":{"offset":7197611,"length":1217,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/streamx/index.js":{"offset":7198828,"length":34248,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/streamx/lib/errors.js":{"offset":7233076,"length":1096,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/streamx/package.json":{"offset":7234172,"length":1225,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/text-decoder/index.js":{"offset":7235397,"length":1371,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/text-decoder/lib/pass-through-decoder.js":{"offset":7236768,"length":269,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/text-decoder/lib/utf8-decoder.js":{"offset":7237037,"length":4429,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/text-decoder/package.json":{"offset":7241466,"length":990,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/time-ordered-set/index.js":{"offset":7242456,"length":1444,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/time-ordered-set/package.json":{"offset":7243900,"length":666,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/timeout-refresh/browser.js":{"offset":7244566,"length":1098,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/timeout-refresh/index.js":{"offset":7245664,"length":184,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/timeout-refresh/node.js":{"offset":7245848,"length":928,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/timeout-refresh/package.json":{"offset":7246776,"length":619,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/udx-native/binding.js":{"offset":7247395,"length":90,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/udx-native/lib/ip.js":{"offset":7247485,"length":2204,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/udx-native/lib/network-interfaces.js":{"offset":7249689,"length":1341,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/udx-native/lib/socket.js":{"offset":7251030,"length":7557,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/udx-native/lib/stream.js":{"offset":7258587,"length":13050,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/udx-native/lib/udx.js":{"offset":7271637,"length":2868,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/udx-native/package.json":{"offset":7274505,"length":1665,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/unordered-set/index.js":{"offset":7276170,"length":677,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/unordered-set/package.json":{"offset":7276847,"length":654,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/unslab/index.js":{"offset":7277501,"length":913,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/unslab/package.json":{"offset":7278414,"length":613,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/which-runtime/index.js":{"offset":7279027,"length":1469,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/which-runtime/package.json":{"offset":7280496,"length":863,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/xache/index.js":{"offset":7281359,"length":2378,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/xache/package.json":{"offset":7283737,"length":584,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/z32/index.js":{"offset":7284321,"length":2654,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/node_modules/z32/package.json":{"offset":7286975,"length":701,"mode":420},"/node_modules/favela-web/node_modules/atproto-room/package.json":{"offset":7287676,"length":1441,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/lib/corestore.js":{"offset":7289117,"length":1775,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/lib/firehose.js":{"offset":7290892,"length":4606,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/lib/overlay-repo-store.js":{"offset":7295498,"length":20497,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/lib/tid.js":{"offset":7315995,"length":1681,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/@hyperswarm/secret-stream/index.js":{"offset":7317676,"length":16722,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/@hyperswarm/secret-stream/lib/bridge.js":{"offset":7334398,"length":1273,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/@hyperswarm/secret-stream/lib/handshake.js":{"offset":7335671,"length":1950,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/@hyperswarm/secret-stream/package.json":{"offset":7337621,"length":1132,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/@ipld/dag-cbor/package.json":{"offset":7338753,"length":3961,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/@ipld/dag-cbor/src/index.js":{"offset":7342714,"length":4040,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/lib/car.js":{"offset":7346754,"length":3112,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/lib/cid.js":{"offset":7349866,"length":1924,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/lib/commit.js":{"offset":7351790,"length":1471,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/lib/mst.js":{"offset":7353261,"length":13309,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/lib/repo.js":{"offset":7366570,"length":4610,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/package.json":{"offset":7371180,"length":3961,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/src/index.js":{"offset":7375141,"length":4040,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/_shortw_utils.js":{"offset":7379181,"length":589,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/curve.js":{"offset":7379770,"length":18539,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/hash-to-curve.js":{"offset":7398309,"length":8097,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/modular.js":{"offset":7406406,"length":21647,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/weierstrass.js":{"offset":7428053,"length":58901,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json":{"offset":7486954,"length":47,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/secp256k1.js":{"offset":7487001,"length":12507,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/utils.js":{"offset":7499508,"length":12067,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/_md.js":{"offset":7511575,"length":6192,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/_u64.js":{"offset":7517767,"length":3081,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/crypto.js":{"offset":7520848,"length":146,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/hmac.js":{"offset":7520994,"length":2962,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json":{"offset":7523956,"length":147,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/sha2.js":{"offset":7524103,"length":16832,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js":{"offset":7540935,"length":10538,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/cborg.js":{"offset":7551473,"length":944,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js":{"offset":7552417,"length":6580,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/1negint.js":{"offset":7558997,"length":2980,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/2bytes.js":{"offset":7561977,"length":3451,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/3string.js":{"offset":7565428,"length":3340,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/4array.js":{"offset":7568768,"length":2944,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/5map.js":{"offset":7571712,"length":2917,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/6tag.js":{"offset":7574629,"length":1957,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/7float.js":{"offset":7576586,"length":8633,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/bl.js":{"offset":7585219,"length":5316,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/byte-utils.js":{"offset":7590535,"length":8172,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/common.js":{"offset":7598707,"length":598,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/decode.js":{"offset":7599305,"length":9008,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/encode.js":{"offset":7608313,"length":21407,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/is.js":{"offset":7629720,"length":2061,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/jump.js":{"offset":7631781,"length":7859,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/tagged.js":{"offset":7639640,"length":2821,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/token.js":{"offset":7642461,"length":2019,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json":{"offset":7644480,"length":4241,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base.js":{"offset":7648721,"length":6266,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base32.js":{"offset":7654987,"length":1443,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base36.js":{"offset":7656430,"length":327,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base58.js":{"offset":7656757,"length":379,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bytes.js":{"offset":7657136,"length":1246,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/cid.js":{"offset":7658382,"length":13430,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/codecs/raw.js":{"offset":7671812,"length":238,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/hashes/digest.js":{"offset":7672050,"length":1915,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/link/interface.js":{"offset":7673965,"length":48,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/varint.js":{"offset":7674013,"length":398,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/vendor/base-x.js":{"offset":7674411,"length":5458,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/vendor/varint.js":{"offset":7679869,"length":2107,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/package.json":{"offset":7681976,"length":8176,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/atproto-repo/package.json":{"offset":7690152,"length":652,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/b4a/index.js":{"offset":7690804,"length":4054,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/b4a/package.json":{"offset":7694858,"length":1245,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-ansi-escapes/index.js":{"offset":7696103,"length":2255,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-ansi-escapes/package.json":{"offset":7698358,"length":1178,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-assert/index.js":{"offset":7699536,"length":2192,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-assert/package.json":{"offset":7701728,"length":835,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-events/index.js":{"offset":7702563,"length":8307,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-events/lib/errors.js":{"offset":7710870,"length":671,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-events/package.json":{"offset":7711541,"length":1504,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-fs/binding.js":{"offset":7713045,"length":33,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-fs/index.js":{"offset":7713078,"length":58907,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-fs/lib/constants.js":{"offset":7771985,"length":1494,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-fs/lib/errors.js":{"offset":7773479,"length":1163,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-fs/package.json":{"offset":7774642,"length":1654,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-fs/promises.js":{"offset":7776296,"length":2401,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-inspect/binding.js":{"offset":7778697,"length":33,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-inspect/index.js":{"offset":7778730,"length":23856,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-inspect/package.json":{"offset":7802586,"length":1041,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-os/binding.js":{"offset":7803627,"length":33,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-os/index.js":{"offset":7803660,"length":5216,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-os/lib/constants.js":{"offset":7808876,"length":143,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-os/lib/errors.js":{"offset":7809019,"length":453,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-os/package.json":{"offset":7809472,"length":1257,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-path/index.js":{"offset":7810729,"length":287,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-path/lib/constants.js":{"offset":7811016,"length":247,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-path/lib/posix.js":{"offset":7811263,"length":6005,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-path/lib/shared.js":{"offset":7817268,"length":1926,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-path/lib/win32.js":{"offset":7819194,"length":13591,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-path/package.json":{"offset":7832785,"length":1036,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-stream/index.js":{"offset":7833821,"length":10904,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-stream/package.json":{"offset":7844725,"length":1676,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-stream/web.js":{"offset":7846401,"length":13980,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-type/binding.js":{"offset":7860381,"length":33,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-type/index.js":{"offset":7860414,"length":4566,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-type/package.json":{"offset":7864980,"length":938,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-url/binding.js":{"offset":7865918,"length":33,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-url/index.js":{"offset":7865951,"length":9449,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-url/lib/errors.js":{"offset":7875400,"length":778,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-url/lib/url-search-params.js":{"offset":7876178,"length":4331,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/bare-url/package.json":{"offset":7880509,"length":1219,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/big-sparse-array/index.js":{"offset":7881728,"length":2471,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/big-sparse-array/package.json":{"offset":7884199,"length":636,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/cborg.js":{"offset":7884835,"length":944,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/0uint.js":{"offset":7885779,"length":6580,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/1negint.js":{"offset":7892359,"length":2980,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/2bytes.js":{"offset":7895339,"length":3451,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/3string.js":{"offset":7898790,"length":3340,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/4array.js":{"offset":7902130,"length":2944,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/5map.js":{"offset":7905074,"length":2917,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/6tag.js":{"offset":7907991,"length":1957,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/7float.js":{"offset":7909948,"length":8633,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/bl.js":{"offset":7918581,"length":5316,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/byte-utils.js":{"offset":7923897,"length":8172,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/common.js":{"offset":7932069,"length":598,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/decode.js":{"offset":7932667,"length":9008,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/encode.js":{"offset":7941675,"length":21407,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/is.js":{"offset":7963082,"length":2061,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/jump.js":{"offset":7965143,"length":7859,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/tagged.js":{"offset":7973002,"length":2821,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/lib/token.js":{"offset":7975823,"length":2019,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/cborg/package.json":{"offset":7977842,"length":4241,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/compact-encoding/endian.js":{"offset":7982083,"length":105,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/compact-encoding/index.js":{"offset":7982188,"length":26406,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/compact-encoding/lexint.js":{"offset":8008594,"length":2851,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/compact-encoding/package.json":{"offset":8011445,"length":866,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/compact-encoding/raw.js":{"offset":8012311,"length":3977,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/corestore/index.js":{"offset":8016288,"length":19847,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/corestore/lib/audit.js":{"offset":8036135,"length":475,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/corestore/lib/notify.js":{"offset":8036610,"length":630,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/corestore/package.json":{"offset":8037240,"length":1350,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/device-file/index.js":{"offset":8038590,"length":6394,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/device-file/package.json":{"offset":8044984,"length":1190,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/events-universal/bare.js":{"offset":8046174,"length":40,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/events-universal/package.json":{"offset":8046214,"length":908,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/fast-fifo/fixed-size.js":{"offset":8047122,"length":875,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/fast-fifo/index.js":{"offset":8047997,"length":972,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/fast-fifo/package.json":{"offset":8048969,"length":682,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/fd-lock/index.js":{"offset":8049651,"length":1755,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/fd-lock/package.json":{"offset":8051406,"length":1099,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/flat-tree/index.js":{"offset":8052505,"length":8164,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/flat-tree/package.json":{"offset":8060669,"length":631,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/fs-native-extensions/binding.js":{"offset":8061300,"length":90,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/fs-native-extensions/index.js":{"offset":8061390,"length":7239,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/fs-native-extensions/package.json":{"offset":8068629,"length":1790,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-crypto/index.js":{"offset":8070419,"length":5031,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-crypto/package.json":{"offset":8075450,"length":1007,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-errors/index.js":{"offset":8076457,"length":4896,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-errors/package.json":{"offset":8081353,"length":688,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-id-encoding/index.js":{"offset":8082041,"length":923,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-id-encoding/package.json":{"offset":8082964,"length":799,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-storage/encoding/external.js":{"offset":8083763,"length":264,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-storage/encoding/spec/hyperschema/index.js":{"offset":8084027,"length":16796,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-storage/index.js":{"offset":8100823,"length":33493,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-storage/lib/block-dependency-stream.js":{"offset":8134316,"length":2557,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-storage/lib/close-error-stream.js":{"offset":8136873,"length":276,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-storage/lib/keys.js":{"offset":8137149,"length":8751,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-storage/lib/streams.js":{"offset":8145900,"length":5686,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-storage/lib/tx.js":{"offset":8151586,"length":11683,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-storage/lib/view.js":{"offset":8163269,"length":8379,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-storage/migrations/0/index.js":{"offset":8171648,"length":20125,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-storage/migrations/0/messages.js":{"offset":8191773,"length":26402,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-storage/migrations/1/index.js":{"offset":8218175,"length":1181,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore-storage/package.json":{"offset":8219356,"length":1827,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/index.js":{"offset":8221183,"length":40241,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/audit.js":{"offset":8261424,"length":3834,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/bit-interlude.js":{"offset":8265258,"length":4257,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/bitfield.js":{"offset":8269515,"length":12115,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/caps.js":{"offset":8281630,"length":1537,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/compat.js":{"offset":8283167,"length":477,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/copy-prologue.js":{"offset":8283644,"length":5999,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/core.js":{"offset":8289643,"length":28356,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/default-encryption.js":{"offset":8317999,"length":3453,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/download.js":{"offset":8321452,"length":1278,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/feature-flags.js":{"offset":8322730,"length":38,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/fully-remote-proof.js":{"offset":8322768,"length":3470,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/hotswap-queue.js":{"offset":8326238,"length":1498,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/info.js":{"offset":8327736,"length":1517,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/inspect.js":{"offset":8329253,"length":1983,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/mark-bitfield.js":{"offset":8331236,"length":2589,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/merkle-tree.js":{"offset":8333825,"length":34353,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/messages.js":{"offset":8368178,"length":28313,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/multisig.js":{"offset":8396491,"length":2851,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/mutex.js":{"offset":8399342,"length":1028,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/receiver-queue.js":{"offset":8400370,"length":1413,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/remote-bitfield.js":{"offset":8401783,"length":8124,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/replicator.js":{"offset":8409907,"length":88868,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/session-state.js":{"offset":8498775,"length":36297,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/streams.js":{"offset":8535072,"length":3034,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/verifier.js":{"offset":8538106,"length":9926,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/lib/wants.js":{"offset":8548032,"length":7204,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hypercore/package.json":{"offset":8555236,"length":2196,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hyperschema/package.json":{"offset":8557432,"length":1555,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/hyperschema/runtime.cjs":{"offset":8558987,"length":54,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/index-encoder/index.js":{"offset":8559041,"length":10596,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/index-encoder/package.json":{"offset":8569637,"length":928,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/is-options/index.js":{"offset":8570565,"length":140,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/is-options/package.json":{"offset":8570705,"length":605,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/multiformats/dist/src/bases/base.js":{"offset":8571310,"length":6266,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/multiformats/dist/src/bases/base32.js":{"offset":8577576,"length":1443,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/multiformats/dist/src/bases/base36.js":{"offset":8579019,"length":327,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/multiformats/dist/src/bases/base58.js":{"offset":8579346,"length":379,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/multiformats/dist/src/bytes.js":{"offset":8579725,"length":1246,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/multiformats/dist/src/cid.js":{"offset":8580971,"length":13430,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/multiformats/dist/src/hashes/digest.js":{"offset":8594401,"length":1915,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/multiformats/dist/src/link/interface.js":{"offset":8596316,"length":48,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/multiformats/dist/src/varint.js":{"offset":8596364,"length":398,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/multiformats/dist/src/vendor/base-x.js":{"offset":8596762,"length":5458,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/multiformats/dist/src/vendor/varint.js":{"offset":8602220,"length":2107,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/multiformats/package.json":{"offset":8604327,"length":8176,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/nanoassert/index.js":{"offset":8612503,"length":438,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/nanoassert/package.json":{"offset":8612941,"length":647,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/noise-curve-ed/index.js":{"offset":8613588,"length":1642,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/noise-curve-ed/package.json":{"offset":8615230,"length":808,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/noise-handshake/cipher.js":{"offset":8616038,"length":2817,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/noise-handshake/dh.js":{"offset":8618855,"length":1439,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/noise-handshake/hkdf.js":{"offset":8620294,"length":1092,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/noise-handshake/hmac.js":{"offset":8621386,"length":1273,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/noise-handshake/noise.js":{"offset":8622659,"length":6437,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/noise-handshake/package.json":{"offset":8629096,"length":638,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/noise-handshake/symmetric-state.js":{"offset":8629734,"length":2206,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/protomux/index.js":{"offset":8631940,"length":19741,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/protomux/package.json":{"offset":8651681,"length":1059,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/queue-tick/package.json":{"offset":8652740,"length":669,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/queue-tick/process-next-tick.js":{"offset":8653409,"length":160,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/queue-tick/queue-microtask.js":{"offset":8653569,"length":108,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/quickbit-native/binding.js":{"offset":8653677,"length":90,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/quickbit-native/index.js":{"offset":8653767,"length":4683,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/quickbit-native/package.json":{"offset":8658450,"length":1104,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/quickbit-universal/fallback.js":{"offset":8659554,"length":10204,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/quickbit-universal/index.js":{"offset":8669758,"length":442,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/quickbit-universal/package.json":{"offset":8670200,"length":908,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/random-array-iterator/index.js":{"offset":8671108,"length":1001,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/random-array-iterator/package.json":{"offset":8672109,"length":700,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/ready-resource/index.js":{"offset":8672809,"length":1091,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/ready-resource/package.json":{"offset":8673900,"length":812,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/refcounter/index.js":{"offset":8674712,"length":611,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/refcounter/package.json":{"offset":8675323,"length":451,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/require-addon/lib/bare.js":{"offset":8675774,"length":45,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/require-addon/package.json":{"offset":8675819,"length":1449,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/resolve-reject-promise/index.js":{"offset":8677268,"length":443,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/resolve-reject-promise/package.json":{"offset":8677711,"length":581,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/resource-on-exit/index.js":{"offset":8678292,"length":361,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/resource-on-exit/package.json":{"offset":8678653,"length":496,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/rocksdb-native/binding.js":{"offset":8679149,"length":90,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/rocksdb-native/index.js":{"offset":8679239,"length":5304,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/rocksdb-native/lib/batch.js":{"offset":8684543,"length":9605,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/rocksdb-native/lib/column-family.js":{"offset":8694148,"length":2930,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/rocksdb-native/lib/constants.js":{"offset":8697078,"length":621,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/rocksdb-native/lib/filter-policy.js":{"offset":8697699,"length":437,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/rocksdb-native/lib/iterator.js":{"offset":8698136,"length":4311,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/rocksdb-native/lib/snapshot.js":{"offset":8702447,"length":503,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/rocksdb-native/lib/state.js":{"offset":8702950,"length":13115,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/rocksdb-native/package.json":{"offset":8716065,"length":1863,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/safety-catch/index.js":{"offset":8717928,"length":543,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/safety-catch/package.json":{"offset":8718471,"length":547,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/scope-lock/index.js":{"offset":8719018,"length":1821,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/scope-lock/package.json":{"offset":8720839,"length":611,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/signal-promise/index.js":{"offset":8721450,"length":1252,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/signal-promise/package.json":{"offset":8722702,"length":503,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/simdle-native/binding.js":{"offset":8723205,"length":90,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/simdle-native/index.js":{"offset":8723295,"length":3474,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/simdle-native/package.json":{"offset":8726769,"length":1115,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/simdle-universal/fallback.js":{"offset":8727884,"length":5137,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/simdle-universal/index.js":{"offset":8733021,"length":103,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/simdle-universal/package.json":{"offset":8733124,"length":879,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/simdle-universal/scalar.js":{"offset":8734003,"length":469,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/sodium-native/binding.js":{"offset":8734472,"length":89,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/sodium-native/index.js":{"offset":8734561,"length":107894,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/sodium-native/package.json":{"offset":8842455,"length":1478,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/sodium-secretstream/index.js":{"offset":8843933,"length":2257,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/sodium-secretstream/package.json":{"offset":8846190,"length":657,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/sodium-universal/index.js":{"offset":8846847,"length":42,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/sodium-universal/package.json":{"offset":8846889,"length":1217,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/streamx/index.js":{"offset":8848106,"length":34248,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/streamx/lib/errors.js":{"offset":8882354,"length":1096,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/streamx/package.json":{"offset":8883450,"length":1225,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/teex/index.js":{"offset":8884675,"length":1107,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/teex/package.json":{"offset":8885782,"length":608,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/text-decoder/index.js":{"offset":8886390,"length":1371,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/text-decoder/lib/pass-through-decoder.js":{"offset":8887761,"length":269,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/text-decoder/lib/utf8-decoder.js":{"offset":8888030,"length":4429,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/text-decoder/package.json":{"offset":8892459,"length":990,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/timeout-refresh/browser.js":{"offset":8893449,"length":1098,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/timeout-refresh/index.js":{"offset":8894547,"length":184,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/timeout-refresh/node.js":{"offset":8894731,"length":928,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/timeout-refresh/package.json":{"offset":8895659,"length":619,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/unslab/index.js":{"offset":8896278,"length":913,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/unslab/package.json":{"offset":8897191,"length":613,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/which-runtime/index.js":{"offset":8897804,"length":1469,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/which-runtime/package.json":{"offset":8899273,"length":863,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/xache/index.js":{"offset":8900136,"length":2477,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/xache/package.json":{"offset":8902613,"length":672,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/z32/index.js":{"offset":8903285,"length":2654,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/node_modules/z32/package.json":{"offset":8905939,"length":701,"mode":420},"/node_modules/favela-web/node_modules/atproto-store/package.json":{"offset":8906640,"length":932,"mode":420},"/node_modules/favela-web/node_modules/b4a/index.js":{"offset":8907572,"length":4054,"mode":420},"/node_modules/favela-web/node_modules/b4a/package.json":{"offset":8911626,"length":1245,"mode":420},"/node_modules/favela-web/node_modules/bare-abort/binding.js":{"offset":8912871,"length":33,"mode":420},"/node_modules/favela-web/node_modules/bare-abort/index.js":{"offset":8912904,"length":69,"mode":420},"/node_modules/favela-web/node_modules/bare-abort/package.json":{"offset":8912973,"length":886,"mode":420},"/node_modules/favela-web/node_modules/bare-ansi-escapes/index.js":{"offset":8913859,"length":2255,"mode":420},"/node_modules/favela-web/node_modules/bare-ansi-escapes/package.json":{"offset":8916114,"length":1178,"mode":420},"/node_modules/favela-web/node_modules/bare-assert/index.js":{"offset":8917292,"length":2192,"mode":420},"/node_modules/favela-web/node_modules/bare-assert/package.json":{"offset":8919484,"length":835,"mode":420},"/node_modules/favela-web/node_modules/bare-buffer/binding.js":{"offset":8920319,"length":33,"mode":420},"/node_modules/favela-web/node_modules/bare-buffer/index.js":{"offset":8920352,"length":28020,"mode":420},"/node_modules/favela-web/node_modules/bare-buffer/lib/ascii.js":{"offset":8948372,"length":613,"mode":420},"/node_modules/favela-web/node_modules/bare-buffer/lib/base64.js":{"offset":8948985,"length":531,"mode":420},"/node_modules/favela-web/node_modules/bare-buffer/lib/base64url.js":{"offset":8949516,"length":534,"mode":420},"/node_modules/favela-web/node_modules/bare-buffer/lib/constants.js":{"offset":8950050,"length":74,"mode":420},"/node_modules/favela-web/node_modules/bare-buffer/lib/hex.js":{"offset":8950124,"length":392,"mode":420},"/node_modules/favela-web/node_modules/bare-buffer/lib/latin1.js":{"offset":8950516,"length":392,"mode":420},"/node_modules/favela-web/node_modules/bare-buffer/lib/utf16le.js":{"offset":8950908,"length":398,"mode":420},"/node_modules/favela-web/node_modules/bare-buffer/lib/utf8.js":{"offset":8951306,"length":519,"mode":420},"/node_modules/favela-web/node_modules/bare-buffer/package.json":{"offset":8951825,"length":1324,"mode":420},"/node_modules/favela-web/node_modules/bare-crypto/binding.js":{"offset":8953149,"length":33,"mode":420},"/node_modules/favela-web/node_modules/bare-crypto/index.js":{"offset":8953182,"length":1706,"mode":420},"/node_modules/favela-web/node_modules/bare-crypto/lib/cipher.js":{"offset":8954888,"length":8357,"mode":420},"/node_modules/favela-web/node_modules/bare-crypto/lib/constants.js":{"offset":8963245,"length":2504,"mode":420},"/node_modules/favela-web/node_modules/bare-crypto/lib/errors.js":{"offset":8965749,"length":957,"mode":420},"/node_modules/favela-web/node_modules/bare-crypto/lib/hash.js":{"offset":8966706,"length":2121,"mode":420},"/node_modules/favela-web/node_modules/bare-crypto/lib/hmac.js":{"offset":8968827,"length":1311,"mode":420},"/node_modules/favela-web/node_modules/bare-crypto/lib/key.js":{"offset":8970138,"length":2535,"mode":420},"/node_modules/favela-web/node_modules/bare-crypto/lib/pbkdf2.js":{"offset":8972673,"length":1059,"mode":420},"/node_modules/favela-web/node_modules/bare-crypto/lib/random.js":{"offset":8973732,"length":2014,"mode":420},"/node_modules/favela-web/node_modules/bare-crypto/lib/signature.js":{"offset":8975746,"length":1369,"mode":420},"/node_modules/favela-web/node_modules/bare-crypto/lib/timing.js":{"offset":8977115,"length":660,"mode":420},"/node_modules/favela-web/node_modules/bare-crypto/lib/web/algorithm/ed25519.js":{"offset":8977775,"length":7039,"mode":420},"/node_modules/favela-web/node_modules/bare-crypto/lib/web/algorithm/hmac.js":{"offset":8984814,"length":5356,"mode":420},"/node_modules/favela-web/node_modules/bare-crypto/lib/web/algorithm/pbkdf2.js":{"offset":8990170,"length":1563,"mode":420},"/node_modules/favela-web/node_modules/bare-crypto/lib/web/algorithm/sha.js":{"offset":8991733,"length":299,"mode":420},"/node_modules/favela-web/node_modules/bare-crypto/lib/web/crypto-key.js":{"offset":8992032,"length":1185,"mode":420},"/node_modules/favela-web/node_modules/bare-crypto/package.json":{"offset":8993217,"length":1618,"mode":420},"/node_modules/favela-web/node_modules/bare-crypto/web.js":{"offset":8994835,"length":7537,"mode":420},"/node_modules/favela-web/node_modules/bare-dns/binding.js":{"offset":9002372,"length":33,"mode":420},"/node_modules/favela-web/node_modules/bare-dns/index.js":{"offset":9002405,"length":1345,"mode":420},"/node_modules/favela-web/node_modules/bare-dns/package.json":{"offset":9003750,"length":968,"mode":420},"/node_modules/favela-web/node_modules/bare-env/index.js":{"offset":9004718,"length":1017,"mode":420},"/node_modules/favela-web/node_modules/bare-env/package.json":{"offset":9005735,"length":944,"mode":420},"/node_modules/favela-web/node_modules/bare-events/index.js":{"offset":9006679,"length":8307,"mode":420},"/node_modules/favela-web/node_modules/bare-events/lib/errors.js":{"offset":9014986,"length":671,"mode":420},"/node_modules/favela-web/node_modules/bare-events/package.json":{"offset":9015657,"length":1504,"mode":420},"/node_modules/favela-web/node_modules/bare-fetch/global.js":{"offset":9017161,"length":144,"mode":420},"/node_modules/favela-web/node_modules/bare-fetch/index.js":{"offset":9017305,"length":4061,"mode":420},"/node_modules/favela-web/node_modules/bare-fetch/lib/body.js":{"offset":9021366,"length":6397,"mode":420},"/node_modules/favela-web/node_modules/bare-fetch/lib/errors.js":{"offset":9027763,"length":1207,"mode":420},"/node_modules/favela-web/node_modules/bare-fetch/lib/headers.js":{"offset":9028970,"length":5064,"mode":420},"/node_modules/favela-web/node_modules/bare-fetch/lib/request.js":{"offset":9034034,"length":1690,"mode":420},"/node_modules/favela-web/node_modules/bare-fetch/lib/response-stream.js":{"offset":9035724,"length":1134,"mode":420},"/node_modules/favela-web/node_modules/bare-fetch/lib/response.js":{"offset":9036858,"length":1426,"mode":420},"/node_modules/favela-web/node_modules/bare-fetch/package.json":{"offset":9038284,"length":2066,"mode":420},"/node_modules/favela-web/node_modules/bare-form-data/index.js":{"offset":9040350,"length":5715,"mode":420},"/node_modules/favela-web/node_modules/bare-form-data/lib/errors.js":{"offset":9046065,"length":412,"mode":420},"/node_modules/favela-web/node_modules/bare-form-data/package.json":{"offset":9046477,"length":1004,"mode":420},"/node_modules/favela-web/node_modules/bare-fs/binding.js":{"offset":9047481,"length":33,"mode":420},"/node_modules/favela-web/node_modules/bare-fs/index.js":{"offset":9047514,"length":58907,"mode":420},"/node_modules/favela-web/node_modules/bare-fs/lib/constants.js":{"offset":9106421,"length":1494,"mode":420},"/node_modules/favela-web/node_modules/bare-fs/lib/errors.js":{"offset":9107915,"length":1166,"mode":420},"/node_modules/favela-web/node_modules/bare-fs/package.json":{"offset":9109081,"length":1654,"mode":420},"/node_modules/favela-web/node_modules/bare-fs/promises.js":{"offset":9110735,"length":2401,"mode":420},"/node_modules/favela-web/node_modules/bare-hrtime/binding.js":{"offset":9113136,"length":33,"mode":420},"/node_modules/favela-web/node_modules/bare-hrtime/index.js":{"offset":9113169,"length":319,"mode":420},"/node_modules/favela-web/node_modules/bare-hrtime/package.json":{"offset":9113488,"length":905,"mode":420},"/node_modules/favela-web/node_modules/bare-http-parser/index.js":{"offset":9114393,"length":17995,"mode":420},"/node_modules/favela-web/node_modules/bare-http-parser/lib/errors.js":{"offset":9132388,"length":845,"mode":420},"/node_modules/favela-web/node_modules/bare-http-parser/package.json":{"offset":9133233,"length":907,"mode":420},"/node_modules/favela-web/node_modules/bare-http1/index.js":{"offset":9134140,"length":2188,"mode":420},"/node_modules/favela-web/node_modules/bare-http1/lib/agent.js":{"offset":9136328,"length":4498,"mode":420},"/node_modules/favela-web/node_modules/bare-http1/lib/client-connection.js":{"offset":9140826,"length":3663,"mode":420},"/node_modules/favela-web/node_modules/bare-http1/lib/client-request.js":{"offset":9144489,"length":3734,"mode":420},"/node_modules/favela-web/node_modules/bare-http1/lib/constants.js":{"offset":9148223,"length":2016,"mode":420},"/node_modules/favela-web/node_modules/bare-http1/lib/errors.js":{"offset":9150239,"length":889,"mode":420},"/node_modules/favela-web/node_modules/bare-http1/lib/incoming-message.js":{"offset":9151128,"length":1568,"mode":420},"/node_modules/favela-web/node_modules/bare-http1/lib/outgoing-message.js":{"offset":9152696,"length":1635,"mode":420},"/node_modules/favela-web/node_modules/bare-http1/lib/server-connection.js":{"offset":9154331,"length":4041,"mode":420},"/node_modules/favela-web/node_modules/bare-http1/lib/server-response.js":{"offset":9158372,"length":3704,"mode":420},"/node_modules/favela-web/node_modules/bare-http1/lib/server.js":{"offset":9162076,"length":977,"mode":420},"/node_modules/favela-web/node_modules/bare-http1/lib/validate.js":{"offset":9163053,"length":1458,"mode":420},"/node_modules/favela-web/node_modules/bare-http1/package.json":{"offset":9164511,"length":1510,"mode":420},"/node_modules/favela-web/node_modules/bare-https/index.js":{"offset":9166021,"length":1498,"mode":420},"/node_modules/favela-web/node_modules/bare-https/lib/agent.js":{"offset":9167519,"length":394,"mode":420},"/node_modules/favela-web/node_modules/bare-https/lib/client-request.js":{"offset":9167913,"length":464,"mode":420},"/node_modules/favela-web/node_modules/bare-https/lib/server.js":{"offset":9168377,"length":1072,"mode":420},"/node_modules/favela-web/node_modules/bare-https/lib/socket.js":{"offset":9169449,"length":464,"mode":420},"/node_modules/favela-web/node_modules/bare-https/package.json":{"offset":9169913,"length":1028,"mode":420},"/node_modules/favela-web/node_modules/bare-inspect/binding.js":{"offset":9170941,"length":33,"mode":420},"/node_modules/favela-web/node_modules/bare-inspect/index.js":{"offset":9170974,"length":23856,"mode":420},"/node_modules/favela-web/node_modules/bare-inspect/package.json":{"offset":9194830,"length":1041,"mode":420},"/node_modules/favela-web/node_modules/bare-mime/index.js":{"offset":9195871,"length":4184,"mode":420},"/node_modules/favela-web/node_modules/bare-mime/package.json":{"offset":9200055,"length":808,"mode":420},"/node_modules/favela-web/node_modules/bare-net/index.js":{"offset":9200863,"length":9005,"mode":420},"/node_modules/favela-web/node_modules/bare-net/lib/constants.js":{"offset":9209868,"length":91,"mode":420},"/node_modules/favela-web/node_modules/bare-net/package.json":{"offset":9209959,"length":1149,"mode":420},"/node_modules/favela-web/node_modules/bare-os/binding.js":{"offset":9211108,"length":33,"mode":420},"/node_modules/favela-web/node_modules/bare-os/index.js":{"offset":9211141,"length":5216,"mode":420},"/node_modules/favela-web/node_modules/bare-os/lib/constants.js":{"offset":9216357,"length":143,"mode":420},"/node_modules/favela-web/node_modules/bare-os/lib/errors.js":{"offset":9216500,"length":453,"mode":420},"/node_modules/favela-web/node_modules/bare-os/package.json":{"offset":9216953,"length":1257,"mode":420},"/node_modules/favela-web/node_modules/bare-path/binding.js":{"offset":9218210,"length":33,"mode":420},"/node_modules/favela-web/node_modules/bare-path/index.js":{"offset":9218243,"length":287,"mode":420},"/node_modules/favela-web/node_modules/bare-path/lib/constants.js":{"offset":9218530,"length":247,"mode":420},"/node_modules/favela-web/node_modules/bare-path/lib/posix.js":{"offset":9218777,"length":6399,"mode":420},"/node_modules/favela-web/node_modules/bare-path/lib/shared.js":{"offset":9225176,"length":2148,"mode":420},"/node_modules/favela-web/node_modules/bare-path/lib/win32.js":{"offset":9227324,"length":13987,"mode":420},"/node_modules/favela-web/node_modules/bare-path/package.json":{"offset":9241311,"length":1106,"mode":420},"/node_modules/favela-web/node_modules/bare-pipe/binding.js":{"offset":9242417,"length":33,"mode":420},"/node_modules/favela-web/node_modules/bare-pipe/index.js":{"offset":9242450,"length":14357,"mode":420},"/node_modules/favela-web/node_modules/bare-pipe/lib/constants.js":{"offset":9256807,"length":352,"mode":420},"/node_modules/favela-web/node_modules/bare-pipe/lib/errors.js":{"offset":9257159,"length":699,"mode":420},"/node_modules/favela-web/node_modules/bare-pipe/package.json":{"offset":9257858,"length":1396,"mode":420},"/node_modules/favela-web/node_modules/bare-posix/package.json":{"offset":9259254,"length":1091,"mode":420},"/node_modules/favela-web/node_modules/bare-posix/unsupported.js":{"offset":9260345,"length":723,"mode":420},"/node_modules/favela-web/node_modules/bare-process/index.js":{"offset":9261068,"length":3189,"mode":420},"/node_modules/favela-web/node_modules/bare-process/package.json":{"offset":9264257,"length":1283,"mode":420},"/node_modules/favela-web/node_modules/bare-signals/binding.js":{"offset":9265540,"length":33,"mode":420},"/node_modules/favela-web/node_modules/bare-signals/index.js":{"offset":9265573,"length":1412,"mode":420},"/node_modules/favela-web/node_modules/bare-signals/lib/emitter.js":{"offset":9266985,"length":1260,"mode":420},"/node_modules/favela-web/node_modules/bare-signals/lib/errors.js":{"offset":9268245,"length":479,"mode":420},"/node_modules/favela-web/node_modules/bare-signals/package.json":{"offset":9268724,"length":1227,"mode":420},"/node_modules/favela-web/node_modules/bare-stdio/binding.js":{"offset":9269951,"length":33,"mode":420},"/node_modules/favela-web/node_modules/bare-stdio/index.js":{"offset":9269984,"length":1525,"mode":420},"/node_modules/favela-web/node_modules/bare-stdio/package.json":{"offset":9271509,"length":1232,"mode":420},"/node_modules/favela-web/node_modules/bare-stream/index.js":{"offset":9272741,"length":10904,"mode":420},"/node_modules/favela-web/node_modules/bare-stream/package.json":{"offset":9283645,"length":1676,"mode":420},"/node_modules/favela-web/node_modules/bare-stream/web.js":{"offset":9285321,"length":13980,"mode":420},"/node_modules/favela-web/node_modules/bare-tcp/binding.js":{"offset":9299301,"length":33,"mode":420},"/node_modules/favela-web/node_modules/bare-tcp/index.js":{"offset":9299334,"length":17298,"mode":420},"/node_modules/favela-web/node_modules/bare-tcp/lib/constants.js":{"offset":9316632,"length":167,"mode":420},"/node_modules/favela-web/node_modules/bare-tcp/lib/errors.js":{"offset":9316799,"length":797,"mode":420},"/node_modules/favela-web/node_modules/bare-tcp/lib/ip.js":{"offset":9317596,"length":2204,"mode":420},"/node_modules/favela-web/node_modules/bare-tcp/package.json":{"offset":9319800,"length":1400,"mode":420},"/node_modules/favela-web/node_modules/bare-tls/binding.js":{"offset":9321200,"length":33,"mode":420},"/node_modules/favela-web/node_modules/bare-tls/index.js":{"offset":9321233,"length":6951,"mode":420},"/node_modules/favela-web/node_modules/bare-tls/lib/constants.js":{"offset":9328184,"length":74,"mode":420},"/node_modules/favela-web/node_modules/bare-tls/lib/errors.js":{"offset":9328258,"length":358,"mode":420},"/node_modules/favela-web/node_modules/bare-tls/net.js":{"offset":9328616,"length":2563,"mode":420},"/node_modules/favela-web/node_modules/bare-tls/package.json":{"offset":9331179,"length":1454,"mode":420},"/node_modules/favela-web/node_modules/bare-tty/binding.js":{"offset":9332633,"length":33,"mode":420},"/node_modules/favela-web/node_modules/bare-tty/index.js":{"offset":9332666,"length":4638,"mode":420},"/node_modules/favela-web/node_modules/bare-tty/lib/constants.js":{"offset":9337304,"length":442,"mode":420},"/node_modules/favela-web/node_modules/bare-tty/package.json":{"offset":9337746,"length":1211,"mode":420},"/node_modules/favela-web/node_modules/bare-type/binding.js":{"offset":9338957,"length":33,"mode":420},"/node_modules/favela-web/node_modules/bare-type/index.js":{"offset":9338990,"length":4566,"mode":420},"/node_modules/favela-web/node_modules/bare-type/package.json":{"offset":9343556,"length":938,"mode":420},"/node_modules/favela-web/node_modules/bare-url/binding.js":{"offset":9344494,"length":33,"mode":420},"/node_modules/favela-web/node_modules/bare-url/index.js":{"offset":9344527,"length":9449,"mode":420},"/node_modules/favela-web/node_modules/bare-url/lib/errors.js":{"offset":9353976,"length":778,"mode":420},"/node_modules/favela-web/node_modules/bare-url/lib/url-search-params.js":{"offset":9354754,"length":4331,"mode":420},"/node_modules/favela-web/node_modules/bare-url/package.json":{"offset":9359085,"length":1219,"mode":420},"/node_modules/favela-web/node_modules/bare-ws/index.js":{"offset":9360304,"length":82,"mode":420},"/node_modules/favela-web/node_modules/bare-ws/lib/constants.js":{"offset":9360386,"length":432,"mode":420},"/node_modules/favela-web/node_modules/bare-ws/lib/errors.js":{"offset":9360818,"length":4032,"mode":420},"/node_modules/favela-web/node_modules/bare-ws/lib/frame.js":{"offset":9364850,"length":3709,"mode":420},"/node_modules/favela-web/node_modules/bare-ws/lib/server.js":{"offset":9368559,"length":2773,"mode":420},"/node_modules/favela-web/node_modules/bare-ws/lib/socket.js":{"offset":9371332,"length":7072,"mode":420},"/node_modules/favela-web/node_modules/bare-ws/package.json":{"offset":9378404,"length":1667,"mode":420},"/node_modules/favela-web/node_modules/bare-zlib/binding.js":{"offset":9380071,"length":33,"mode":420},"/node_modules/favela-web/node_modules/bare-zlib/index.js":{"offset":9380104,"length":8166,"mode":420},"/node_modules/favela-web/node_modules/bare-zlib/lib/constants.js":{"offset":9388270,"length":74,"mode":420},"/node_modules/favela-web/node_modules/bare-zlib/lib/errors.js":{"offset":9388344,"length":1096,"mode":420},"/node_modules/favela-web/node_modules/bare-zlib/package.json":{"offset":9389440,"length":1463,"mode":420},"/node_modules/favela-web/node_modules/big-sparse-array/index.js":{"offset":9390903,"length":2471,"mode":420},"/node_modules/favela-web/node_modules/big-sparse-array/package.json":{"offset":9393374,"length":636,"mode":420},"/node_modules/favela-web/node_modules/bits-to-bytes/index.js":{"offset":9394010,"length":3083,"mode":420},"/node_modules/favela-web/node_modules/bits-to-bytes/package.json":{"offset":9397093,"length":708,"mode":420},"/node_modules/favela-web/node_modules/blind-pairing-core/index.js":{"offset":9397801,"length":10961,"mode":420},"/node_modules/favela-web/node_modules/blind-pairing-core/lib/errors.js":{"offset":9408762,"length":725,"mode":420},"/node_modules/favela-web/node_modules/blind-pairing-core/lib/messages.js":{"offset":9409487,"length":6120,"mode":420},"/node_modules/favela-web/node_modules/blind-pairing-core/node_modules/compact-encoding/endian.js":{"offset":9415607,"length":105,"mode":420},"/node_modules/favela-web/node_modules/blind-pairing-core/node_modules/compact-encoding/index.js":{"offset":9415712,"length":26406,"mode":420},"/node_modules/favela-web/node_modules/blind-pairing-core/node_modules/compact-encoding/lexint.js":{"offset":9442118,"length":2851,"mode":420},"/node_modules/favela-web/node_modules/blind-pairing-core/node_modules/compact-encoding/package.json":{"offset":9444969,"length":866,"mode":420},"/node_modules/favela-web/node_modules/blind-pairing-core/node_modules/compact-encoding/raw.js":{"offset":9445835,"length":3977,"mode":420},"/node_modules/favela-web/node_modules/blind-pairing-core/package.json":{"offset":9449812,"length":1062,"mode":420},"/node_modules/favela-web/node_modules/blind-relay/index.js":{"offset":9450874,"length":13411,"mode":420},"/node_modules/favela-web/node_modules/blind-relay/lib/errors.js":{"offset":9464285,"length":1036,"mode":420},"/node_modules/favela-web/node_modules/blind-relay/node_modules/compact-encoding/endian.js":{"offset":9465321,"length":105,"mode":420},"/node_modules/favela-web/node_modules/blind-relay/node_modules/compact-encoding/index.js":{"offset":9465426,"length":26406,"mode":420},"/node_modules/favela-web/node_modules/blind-relay/node_modules/compact-encoding/lexint.js":{"offset":9491832,"length":2851,"mode":420},"/node_modules/favela-web/node_modules/blind-relay/node_modules/compact-encoding/package.json":{"offset":9494683,"length":866,"mode":420},"/node_modules/favela-web/node_modules/blind-relay/node_modules/compact-encoding/raw.js":{"offset":9495549,"length":3977,"mode":420},"/node_modules/favela-web/node_modules/blind-relay/package.json":{"offset":9499526,"length":1231,"mode":420},"/node_modules/favela-web/node_modules/bogon/index.js":{"offset":9500757,"length":4004,"mode":420},"/node_modules/favela-web/node_modules/bogon/node_modules/compact-encoding/endian.js":{"offset":9504761,"length":105,"mode":420},"/node_modules/favela-web/node_modules/bogon/node_modules/compact-encoding/index.js":{"offset":9504866,"length":26406,"mode":420},"/node_modules/favela-web/node_modules/bogon/node_modules/compact-encoding/lexint.js":{"offset":9531272,"length":2851,"mode":420},"/node_modules/favela-web/node_modules/bogon/node_modules/compact-encoding/package.json":{"offset":9534123,"length":866,"mode":420},"/node_modules/favela-web/node_modules/bogon/node_modules/compact-encoding/raw.js":{"offset":9534989,"length":3977,"mode":420},"/node_modules/favela-web/node_modules/bogon/package.json":{"offset":9538966,"length":656,"mode":420},"/node_modules/favela-web/node_modules/cborg/cborg.js":{"offset":9539622,"length":944,"mode":420},"/node_modules/favela-web/node_modules/cborg/lib/0uint.js":{"offset":9540566,"length":6580,"mode":420},"/node_modules/favela-web/node_modules/cborg/lib/1negint.js":{"offset":9547146,"length":2980,"mode":420},"/node_modules/favela-web/node_modules/cborg/lib/2bytes.js":{"offset":9550126,"length":3451,"mode":420},"/node_modules/favela-web/node_modules/cborg/lib/3string.js":{"offset":9553577,"length":3340,"mode":420},"/node_modules/favela-web/node_modules/cborg/lib/4array.js":{"offset":9556917,"length":2944,"mode":420},"/node_modules/favela-web/node_modules/cborg/lib/5map.js":{"offset":9559861,"length":2917,"mode":420},"/node_modules/favela-web/node_modules/cborg/lib/6tag.js":{"offset":9562778,"length":1957,"mode":420},"/node_modules/favela-web/node_modules/cborg/lib/7float.js":{"offset":9564735,"length":8633,"mode":420},"/node_modules/favela-web/node_modules/cborg/lib/bl.js":{"offset":9573368,"length":5505,"mode":420},"/node_modules/favela-web/node_modules/cborg/lib/byte-utils.js":{"offset":9578873,"length":8369,"mode":420},"/node_modules/favela-web/node_modules/cborg/lib/common.js":{"offset":9587242,"length":598,"mode":420},"/node_modules/favela-web/node_modules/cborg/lib/decode.js":{"offset":9587840,"length":9008,"mode":420},"/node_modules/favela-web/node_modules/cborg/lib/encode.js":{"offset":9596848,"length":21957,"mode":420},"/node_modules/favela-web/node_modules/cborg/lib/is.js":{"offset":9618805,"length":2061,"mode":420},"/node_modules/favela-web/node_modules/cborg/lib/jump.js":{"offset":9620866,"length":7942,"mode":420},"/node_modules/favela-web/node_modules/cborg/lib/tagged.js":{"offset":9628808,"length":2821,"mode":420},"/node_modules/favela-web/node_modules/cborg/lib/token.js":{"offset":9631629,"length":2019,"mode":420},"/node_modules/favela-web/node_modules/cborg/package.json":{"offset":9633648,"length":4241,"mode":420},"/node_modules/favela-web/node_modules/codecs/index.js":{"offset":9637889,"length":2416,"mode":420},"/node_modules/favela-web/node_modules/codecs/package.json":{"offset":9640305,"length":655,"mode":420},"/node_modules/favela-web/node_modules/compact-encoding-bitfield/index.js":{"offset":9640960,"length":1967,"mode":420},"/node_modules/favela-web/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/endian.js":{"offset":9642927,"length":105,"mode":420},"/node_modules/favela-web/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/index.js":{"offset":9643032,"length":26406,"mode":420},"/node_modules/favela-web/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/lexint.js":{"offset":9669438,"length":2851,"mode":420},"/node_modules/favela-web/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/package.json":{"offset":9672289,"length":866,"mode":420},"/node_modules/favela-web/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/raw.js":{"offset":9673155,"length":3977,"mode":420},"/node_modules/favela-web/node_modules/compact-encoding-bitfield/package.json":{"offset":9677132,"length":1109,"mode":420},"/node_modules/favela-web/node_modules/compact-encoding/endian.js":{"offset":9678241,"length":105,"mode":420},"/node_modules/favela-web/node_modules/compact-encoding/index.js":{"offset":9678346,"length":24454,"mode":420},"/node_modules/favela-web/node_modules/compact-encoding/lexint.js":{"offset":9702800,"length":2851,"mode":420},"/node_modules/favela-web/node_modules/compact-encoding/package.json":{"offset":9705651,"length":786,"mode":420},"/node_modules/favela-web/node_modules/compact-encoding/raw.js":{"offset":9706437,"length":4093,"mode":420},"/node_modules/favela-web/node_modules/corestore/index.js":{"offset":9710530,"length":19847,"mode":420},"/node_modules/favela-web/node_modules/corestore/lib/audit.js":{"offset":9730377,"length":475,"mode":420},"/node_modules/favela-web/node_modules/corestore/lib/notify.js":{"offset":9730852,"length":630,"mode":420},"/node_modules/favela-web/node_modules/corestore/package.json":{"offset":9731482,"length":1350,"mode":420},"/node_modules/favela-web/node_modules/debounceify/index.js":{"offset":9732832,"length":585,"mode":420},"/node_modules/favela-web/node_modules/debounceify/package.json":{"offset":9733417,"length":567,"mode":420},"/node_modules/favela-web/node_modules/device-file/index.js":{"offset":9733984,"length":6394,"mode":420},"/node_modules/favela-web/node_modules/device-file/package.json":{"offset":9740378,"length":1190,"mode":420},"/node_modules/favela-web/node_modules/dht-rpc/index.js":{"offset":9741568,"length":29079,"mode":420},"/node_modules/favela-web/node_modules/dht-rpc/lib/commands.js":{"offset":9770647,"length":107,"mode":420},"/node_modules/favela-web/node_modules/dht-rpc/lib/errors.js":{"offset":9770754,"length":719,"mode":420},"/node_modules/favela-web/node_modules/dht-rpc/lib/health.js":{"offset":9771473,"length":2998,"mode":420},"/node_modules/favela-web/node_modules/dht-rpc/lib/io.js":{"offset":9774471,"length":16605,"mode":420},"/node_modules/favela-web/node_modules/dht-rpc/lib/peer.js":{"offset":9791076,"length":583,"mode":420},"/node_modules/favela-web/node_modules/dht-rpc/lib/query.js":{"offset":9791659,"length":9899,"mode":420},"/node_modules/favela-web/node_modules/dht-rpc/lib/session.js":{"offset":9801558,"length":1103,"mode":420},"/node_modules/favela-web/node_modules/dht-rpc/node_modules/compact-encoding/endian.js":{"offset":9802661,"length":105,"mode":420},"/node_modules/favela-web/node_modules/dht-rpc/node_modules/compact-encoding/index.js":{"offset":9802766,"length":26406,"mode":420},"/node_modules/favela-web/node_modules/dht-rpc/node_modules/compact-encoding/lexint.js":{"offset":9829172,"length":2851,"mode":420},"/node_modules/favela-web/node_modules/dht-rpc/node_modules/compact-encoding/package.json":{"offset":9832023,"length":866,"mode":420},"/node_modules/favela-web/node_modules/dht-rpc/node_modules/compact-encoding/raw.js":{"offset":9832889,"length":3977,"mode":420},"/node_modules/favela-web/node_modules/dht-rpc/package.json":{"offset":9836866,"length":1396,"mode":420},"/node_modules/favela-web/node_modules/events-universal/bare.js":{"offset":9838262,"length":40,"mode":420},"/node_modules/favela-web/node_modules/events-universal/package.json":{"offset":9838302,"length":908,"mode":420},"/node_modules/favela-web/node_modules/fast-fifo/fixed-size.js":{"offset":9839210,"length":875,"mode":420},"/node_modules/favela-web/node_modules/fast-fifo/index.js":{"offset":9840085,"length":972,"mode":420},"/node_modules/favela-web/node_modules/fast-fifo/package.json":{"offset":9841057,"length":682,"mode":420},"/node_modules/favela-web/node_modules/favela-community/index.js":{"offset":9841739,"length":602,"mode":420},"/node_modules/favela-web/node_modules/favela-community/lib/community-room.js":{"offset":9842341,"length":13897,"mode":420},"/node_modules/favela-web/node_modules/favela-community/lib/discovery.js":{"offset":9856238,"length":5311,"mode":420},"/node_modules/favela-web/node_modules/favela-community/lib/feed-registry.js":{"offset":9861549,"length":9993,"mode":420},"/node_modules/favela-web/node_modules/favela-community/lib/feed-schema.js":{"offset":9871542,"length":3421,"mode":420},"/node_modules/favela-web/node_modules/favela-community/lib/schema.js":{"offset":9874963,"length":3815,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/b4a/index.js":{"offset":9878778,"length":4054,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/b4a/package.json":{"offset":9882832,"length":1245,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/bare-ansi-escapes/index.js":{"offset":9884077,"length":2255,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/bare-ansi-escapes/package.json":{"offset":9886332,"length":1178,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/bare-assert/index.js":{"offset":9887510,"length":2192,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/bare-assert/package.json":{"offset":9889702,"length":835,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/bare-inspect/binding.js":{"offset":9890537,"length":33,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/bare-inspect/index.js":{"offset":9890570,"length":23856,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/bare-inspect/package.json":{"offset":9914426,"length":1041,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/bare-type/binding.js":{"offset":9915467,"length":33,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/bare-type/index.js":{"offset":9915500,"length":4566,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/bare-type/package.json":{"offset":9920066,"length":938,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/compact-encoding/endian.js":{"offset":9921004,"length":105,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/compact-encoding/index.js":{"offset":9921109,"length":26406,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/compact-encoding/lexint.js":{"offset":9947515,"length":2851,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/compact-encoding/package.json":{"offset":9950366,"length":866,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/compact-encoding/raw.js":{"offset":9951232,"length":3977,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/lib/json-schema.js":{"offset":9955209,"length":1408,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/lib/room.js":{"offset":9956617,"length":20920,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/@hyperswarm/secret-stream/index.js":{"offset":9977537,"length":16722,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/@hyperswarm/secret-stream/lib/bridge.js":{"offset":9994259,"length":1273,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/@hyperswarm/secret-stream/lib/handshake.js":{"offset":9995532,"length":1950,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/@hyperswarm/secret-stream/package.json":{"offset":9997482,"length":1132,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/encoding/legacy.js":{"offset":9998614,"length":8848,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/encoding/spec/autobase/index.js":{"offset":10007462,"length":18918,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/index.js":{"offset":10026380,"length":59358,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/active-writers.js":{"offset":10085738,"length":736,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/append-batch.js":{"offset":10086474,"length":1426,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/apply-calls.js":{"offset":10087900,"length":2275,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/apply-state.js":{"offset":10090175,"length":46121,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/boot.js":{"offset":10136296,"length":4599,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/caps.js":{"offset":10140895,"length":505,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/clock.js":{"offset":10141400,"length":749,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/consensus.js":{"offset":10142149,"length":11754,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/encryption.js":{"offset":10153903,"length":9444,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/fast-forward.js":{"offset":10163347,"length":5714,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/fork.js":{"offset":10169061,"length":4148,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/linearizer.js":{"offset":10173209,"length":9696,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/local-state.js":{"offset":10182905,"length":2013,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/messages.js":{"offset":10184918,"length":827,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/node-buffer.js":{"offset":10185745,"length":1563,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/store.js":{"offset":10187308,"length":14341,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/system.js":{"offset":10201649,"length":20176,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/timer.js":{"offset":10221825,"length":2937,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/topolist.js":{"offset":10224762,"length":5108,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/updates.js":{"offset":10229870,"length":1068,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/values.js":{"offset":10230938,"length":1539,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/wakeup.js":{"offset":10232477,"length":4034,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/lib/writer.js":{"offset":10236511,"length":8901,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/autobase/package.json":{"offset":10245412,"length":2328,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/index.js":{"offset":10247740,"length":4054,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/b4a/package.json":{"offset":10251794,"length":1140,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-ansi-escapes/index.js":{"offset":10252934,"length":2255,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-ansi-escapes/package.json":{"offset":10255189,"length":1178,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-assert/index.js":{"offset":10256367,"length":2192,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-assert/package.json":{"offset":10258559,"length":835,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-events/index.js":{"offset":10259394,"length":8033,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-events/lib/errors.js":{"offset":10267427,"length":671,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-events/package.json":{"offset":10268098,"length":1399,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-fs/binding.js":{"offset":10269497,"length":33,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-fs/index.js":{"offset":10269530,"length":58907,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-fs/lib/constants.js":{"offset":10328437,"length":1494,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-fs/lib/errors.js":{"offset":10329931,"length":1166,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-fs/package.json":{"offset":10331097,"length":1654,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-fs/promises.js":{"offset":10332751,"length":2401,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-inspect/binding.js":{"offset":10335152,"length":33,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-inspect/index.js":{"offset":10335185,"length":23856,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-inspect/package.json":{"offset":10359041,"length":1041,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-os/binding.js":{"offset":10360082,"length":33,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-os/index.js":{"offset":10360115,"length":3162,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-os/lib/constants.js":{"offset":10363277,"length":143,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-os/lib/errors.js":{"offset":10363420,"length":479,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-os/package.json":{"offset":10363899,"length":1138,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-path/index.js":{"offset":10365037,"length":306,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-path/lib/constants.js":{"offset":10365343,"length":247,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-path/lib/posix.js":{"offset":10365590,"length":5991,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-path/lib/shared.js":{"offset":10371581,"length":1888,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-path/lib/win32.js":{"offset":10373469,"length":13427,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-path/package.json":{"offset":10386896,"length":796,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-stream/index.js":{"offset":10387692,"length":10913,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-stream/package.json":{"offset":10398605,"length":1579,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-stream/web.js":{"offset":10400184,"length":13712,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-type/binding.js":{"offset":10413896,"length":33,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-type/index.js":{"offset":10413929,"length":4566,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-type/package.json":{"offset":10418495,"length":938,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-url/binding.js":{"offset":10419433,"length":33,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-url/index.js":{"offset":10419466,"length":9308,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-url/lib/errors.js":{"offset":10428774,"length":778,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-url/lib/url-search-params.js":{"offset":10429552,"length":4286,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/bare-url/package.json":{"offset":10433838,"length":1105,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/big-sparse-array/index.js":{"offset":10434943,"length":2471,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/big-sparse-array/package.json":{"offset":10437414,"length":636,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/codecs/index.js":{"offset":10438050,"length":2416,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/codecs/package.json":{"offset":10440466,"length":655,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/compact-encoding/endian.js":{"offset":10441121,"length":105,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/compact-encoding/index.js":{"offset":10441226,"length":24454,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/compact-encoding/lexint.js":{"offset":10465680,"length":2851,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/compact-encoding/package.json":{"offset":10468531,"length":786,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/compact-encoding/raw.js":{"offset":10469317,"length":4093,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/core-coupler/index.js":{"offset":10473410,"length":2243,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/core-coupler/package.json":{"offset":10475653,"length":599,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/debounceify/index.js":{"offset":10476252,"length":585,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/debounceify/package.json":{"offset":10476837,"length":567,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/device-file/index.js":{"offset":10477404,"length":6394,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/device-file/package.json":{"offset":10483798,"length":1190,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/encryption-encoding/index.js":{"offset":10484988,"length":378,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/encryption-encoding/package.json":{"offset":10485366,"length":1234,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/encryption-encoding/spec/hyperschema/index.js":{"offset":10486600,"length":1749,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/events-universal/bare.js":{"offset":10488349,"length":40,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/events-universal/package.json":{"offset":10488389,"length":908,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/fast-fifo/fixed-size.js":{"offset":10489297,"length":875,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/fast-fifo/index.js":{"offset":10490172,"length":972,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/fast-fifo/package.json":{"offset":10491144,"length":682,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/fd-lock/index.js":{"offset":10491826,"length":1661,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/fd-lock/package.json":{"offset":10493487,"length":1099,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/flat-tree/index.js":{"offset":10494586,"length":8164,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/flat-tree/package.json":{"offset":10502750,"length":631,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/fs-native-extensions/binding.js":{"offset":10503381,"length":90,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/fs-native-extensions/index.js":{"offset":10503471,"length":5718,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/fs-native-extensions/package.json":{"offset":10509189,"length":1699,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hyperbee/index.js":{"offset":10510888,"length":46445,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hyperbee/iterators/diff.js":{"offset":10557333,"length":5358,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hyperbee/iterators/history.js":{"offset":10562691,"length":1631,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hyperbee/iterators/local.js":{"offset":10564322,"length":1170,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hyperbee/iterators/range.js":{"offset":10565492,"length":5869,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hyperbee/lib/extension.js":{"offset":10571361,"length":3488,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hyperbee/lib/messages.js":{"offset":10574849,"length":28162,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hyperbee/package.json":{"offset":10603011,"length":1585,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-crypto/index.js":{"offset":10604596,"length":5040,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-crypto/package.json":{"offset":10609636,"length":771,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-errors/index.js":{"offset":10610407,"length":4896,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-errors/package.json":{"offset":10615303,"length":688,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-id-encoding/index.js":{"offset":10615991,"length":923,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-id-encoding/package.json":{"offset":10616914,"length":799,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-storage/index.js":{"offset":10617713,"length":30790,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-storage/lib/block-dependency-stream.js":{"offset":10648503,"length":2557,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-storage/lib/close-error-stream.js":{"offset":10651060,"length":276,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-storage/lib/keys.js":{"offset":10651336,"length":7943,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-storage/lib/streams.js":{"offset":10659279,"length":5297,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-storage/lib/tx.js":{"offset":10664576,"length":9039,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-storage/lib/view.js":{"offset":10673615,"length":8379,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-storage/migrations/0/index.js":{"offset":10681994,"length":20125,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-storage/migrations/0/messages.js":{"offset":10702119,"length":26210,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-storage/package.json":{"offset":10728329,"length":1589,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore-storage/spec/hyperschema/index.js":{"offset":10729918,"length":13254,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/index.js":{"offset":10743172,"length":39432,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/audit.js":{"offset":10782604,"length":3834,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/bit-interlude.js":{"offset":10786438,"length":4257,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/bitfield.js":{"offset":10790695,"length":12115,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/caps.js":{"offset":10802810,"length":1537,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/compat.js":{"offset":10804347,"length":477,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/copy-prologue.js":{"offset":10804824,"length":5999,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/core.js":{"offset":10810823,"length":27263,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/default-encryption.js":{"offset":10838086,"length":3453,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/download.js":{"offset":10841539,"length":1278,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/feature-flags.js":{"offset":10842817,"length":38,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/fully-remote-proof.js":{"offset":10842855,"length":3470,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/hotswap-queue.js":{"offset":10846325,"length":1498,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/info.js":{"offset":10847823,"length":1517,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/inspect.js":{"offset":10849340,"length":1983,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/mark-bitfield.js":{"offset":10851323,"length":2589,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/merkle-tree.js":{"offset":10853912,"length":34353,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/messages.js":{"offset":10888265,"length":28353,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/multisig.js":{"offset":10916618,"length":2851,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/mutex.js":{"offset":10919469,"length":1028,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/receiver-queue.js":{"offset":10920497,"length":1413,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/remote-bitfield.js":{"offset":10921910,"length":8124,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/replicator.js":{"offset":10930034,"length":88126,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/session-state.js":{"offset":11018160,"length":34757,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/streams.js":{"offset":11052917,"length":3034,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/verifier.js":{"offset":11055951,"length":9678,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/lib/wants.js":{"offset":11065629,"length":7204,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hypercore/package.json":{"offset":11072833,"length":2197,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hyperschema/package.json":{"offset":11075030,"length":1556,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/hyperschema/runtime.cjs":{"offset":11076586,"length":54,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/index-encoder/index.js":{"offset":11076640,"length":10596,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/index-encoder/package.json":{"offset":11087236,"length":928,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/is-options/index.js":{"offset":11088164,"length":140,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/is-options/package.json":{"offset":11088304,"length":605,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/mutexify/index.js":{"offset":11088909,"length":536,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/mutexify/package.json":{"offset":11089445,"length":679,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/mutexify/promise.js":{"offset":11090124,"length":324,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/nanoassert/index.js":{"offset":11090448,"length":438,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/nanoassert/package.json":{"offset":11090886,"length":647,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/noise-curve-ed/index.js":{"offset":11091533,"length":1642,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/noise-curve-ed/package.json":{"offset":11093175,"length":808,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/noise-handshake/cipher.js":{"offset":11093983,"length":2817,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/noise-handshake/dh.js":{"offset":11096800,"length":1439,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/noise-handshake/hkdf.js":{"offset":11098239,"length":1092,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/noise-handshake/hmac.js":{"offset":11099331,"length":1273,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/noise-handshake/noise.js":{"offset":11100604,"length":6437,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/noise-handshake/package.json":{"offset":11107041,"length":638,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/noise-handshake/symmetric-state.js":{"offset":11107679,"length":2206,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/protocol-buffers-encodings/index.js":{"offset":11109885,"length":6489,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/protocol-buffers-encodings/package.json":{"offset":11116374,"length":719,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/protomux-wakeup/index.js":{"offset":11117093,"length":16824,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/protomux-wakeup/package.json":{"offset":11133917,"length":972,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/protomux-wakeup/spec/hyperschema/index.js":{"offset":11134889,"length":3335,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/protomux/index.js":{"offset":11138224,"length":18996,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/protomux/package.json":{"offset":11157220,"length":816,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/queue-tick/package.json":{"offset":11158036,"length":669,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/queue-tick/process-next-tick.js":{"offset":11158705,"length":160,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/queue-tick/queue-microtask.js":{"offset":11158865,"length":108,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/quickbit-native/binding.js":{"offset":11158973,"length":90,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/quickbit-native/index.js":{"offset":11159063,"length":4683,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/quickbit-native/package.json":{"offset":11163746,"length":1104,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/quickbit-universal/fallback.js":{"offset":11164850,"length":10204,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/quickbit-universal/index.js":{"offset":11175054,"length":442,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/quickbit-universal/package.json":{"offset":11175496,"length":908,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/rache/index.js":{"offset":11176404,"length":2463,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/rache/package.json":{"offset":11178867,"length":602,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/random-array-iterator/index.js":{"offset":11179469,"length":1001,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/random-array-iterator/package.json":{"offset":11180470,"length":700,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/ready-resource/index.js":{"offset":11181170,"length":1091,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/ready-resource/package.json":{"offset":11182261,"length":812,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/refcounter/index.js":{"offset":11183073,"length":611,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/refcounter/package.json":{"offset":11183684,"length":451,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/require-addon/lib/bare.js":{"offset":11184135,"length":45,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/require-addon/package.json":{"offset":11184180,"length":1449,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/resolve-reject-promise/index.js":{"offset":11185629,"length":443,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/resolve-reject-promise/package.json":{"offset":11186072,"length":581,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/resource-on-exit/index.js":{"offset":11186653,"length":361,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/resource-on-exit/package.json":{"offset":11187014,"length":496,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/rocksdb-native/binding.js":{"offset":11187510,"length":90,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/rocksdb-native/index.js":{"offset":11187600,"length":4758,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/rocksdb-native/lib/batch.js":{"offset":11192358,"length":9605,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/rocksdb-native/lib/column-family.js":{"offset":11201963,"length":2849,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/rocksdb-native/lib/constants.js":{"offset":11204812,"length":399,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/rocksdb-native/lib/filter-policy.js":{"offset":11205211,"length":437,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/rocksdb-native/lib/iterator.js":{"offset":11205648,"length":4311,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/rocksdb-native/lib/snapshot.js":{"offset":11209959,"length":503,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/rocksdb-native/lib/state.js":{"offset":11210462,"length":10338,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/rocksdb-native/package.json":{"offset":11220800,"length":1827,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/safety-catch/index.js":{"offset":11222627,"length":543,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/safety-catch/package.json":{"offset":11223170,"length":547,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/scope-lock/index.js":{"offset":11223717,"length":1821,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/scope-lock/package.json":{"offset":11225538,"length":611,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/signal-promise/index.js":{"offset":11226149,"length":1252,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/signal-promise/package.json":{"offset":11227401,"length":503,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/signed-varint/index.js":{"offset":11227904,"length":435,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/signed-varint/package.json":{"offset":11228339,"length":523,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/simdle-native/binding.js":{"offset":11228862,"length":90,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/simdle-native/index.js":{"offset":11228952,"length":3474,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/simdle-native/package.json":{"offset":11232426,"length":1115,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/simdle-universal/fallback.js":{"offset":11233541,"length":5137,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/simdle-universal/index.js":{"offset":11238678,"length":103,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/simdle-universal/package.json":{"offset":11238781,"length":879,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/simdle-universal/scalar.js":{"offset":11239660,"length":469,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/sodium-native/binding.js":{"offset":11240129,"length":89,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/sodium-native/index.js":{"offset":11240218,"length":107894,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/sodium-native/package.json":{"offset":11348112,"length":1478,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/sodium-secretstream/index.js":{"offset":11349590,"length":2257,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/sodium-secretstream/package.json":{"offset":11351847,"length":657,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/sodium-universal/index.js":{"offset":11352504,"length":42,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/sodium-universal/package.json":{"offset":11352546,"length":1217,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/streamx/index.js":{"offset":11353763,"length":33510,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/streamx/package.json":{"offset":11387273,"length":912,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/sub-encoder/index.js":{"offset":11388185,"length":1968,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/sub-encoder/package.json":{"offset":11390153,"length":908,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/teex/index.js":{"offset":11391061,"length":1107,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/teex/package.json":{"offset":11392168,"length":608,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/text-decoder/index.js":{"offset":11392776,"length":1371,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/text-decoder/lib/pass-through-decoder.js":{"offset":11394147,"length":269,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/text-decoder/lib/utf8-decoder.js":{"offset":11394416,"length":4429,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/text-decoder/package.json":{"offset":11398845,"length":990,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/timeout-refresh/browser.js":{"offset":11399835,"length":1098,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/timeout-refresh/index.js":{"offset":11400933,"length":184,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/timeout-refresh/node.js":{"offset":11401117,"length":928,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/timeout-refresh/package.json":{"offset":11402045,"length":619,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/tiny-buffer-map/index.js":{"offset":11402664,"length":936,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/tiny-buffer-map/package.json":{"offset":11403600,"length":650,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/unslab/index.js":{"offset":11404250,"length":913,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/unslab/package.json":{"offset":11405163,"length":613,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/varint/decode.js":{"offset":11405776,"length":508,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/varint/encode.js":{"offset":11406284,"length":452,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/varint/index.js":{"offset":11406736,"length":134,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/varint/length.js":{"offset":11406870,"length":471,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/varint/package.json":{"offset":11407341,"length":511,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/which-runtime/index.js":{"offset":11407852,"length":1231,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/which-runtime/package.json":{"offset":11409083,"length":602,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/z32/index.js":{"offset":11409685,"length":2654,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/node_modules/z32/package.json":{"offset":11412339,"length":701,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hyper-rooms/package.json":{"offset":11413040,"length":700,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hypercore-crypto/index.js":{"offset":11413740,"length":5031,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/hypercore-crypto/package.json":{"offset":11418771,"length":1007,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/require-addon/lib/bare.js":{"offset":11419778,"length":45,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/require-addon/package.json":{"offset":11419823,"length":1449,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/sodium-native/binding.js":{"offset":11421272,"length":89,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/sodium-native/index.js":{"offset":11421361,"length":107894,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/sodium-native/package.json":{"offset":11529255,"length":1478,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/sodium-universal/index.js":{"offset":11530733,"length":42,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/sodium-universal/package.json":{"offset":11530775,"length":1217,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/which-runtime/index.js":{"offset":11531992,"length":1469,"mode":420},"/node_modules/favela-web/node_modules/favela-community/node_modules/which-runtime/package.json":{"offset":11533461,"length":863,"mode":420},"/node_modules/favela-web/node_modules/favela-community/package.json":{"offset":11534324,"length":875,"mode":420},"/node_modules/favela-web/node_modules/fd-lock/index.js":{"offset":11535199,"length":1755,"mode":420},"/node_modules/favela-web/node_modules/fd-lock/package.json":{"offset":11536954,"length":1099,"mode":420},"/node_modules/favela-web/node_modules/flat-tree/index.js":{"offset":11538053,"length":8164,"mode":420},"/node_modules/favela-web/node_modules/flat-tree/package.json":{"offset":11546217,"length":631,"mode":420},"/node_modules/favela-web/node_modules/fs-native-extensions/binding.js":{"offset":11546848,"length":90,"mode":420},"/node_modules/favela-web/node_modules/fs-native-extensions/index.js":{"offset":11546938,"length":7239,"mode":420},"/node_modules/favela-web/node_modules/fs-native-extensions/package.json":{"offset":11554177,"length":1790,"mode":420},"/node_modules/favela-web/node_modules/hyper-identity/lib/auth/base-provider.js":{"offset":11555967,"length":915,"mode":420},"/node_modules/favela-web/node_modules/hyper-identity/lib/auth/providers/atproto.js":{"offset":11556882,"length":2138,"mode":420},"/node_modules/favela-web/node_modules/hyper-identity/package.json":{"offset":11559020,"length":3138,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/lib/adopt.js":{"offset":11562158,"length":6797,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/lib/config.js":{"offset":11568955,"length":7290,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/lib/coowner.js":{"offset":11576245,"length":15305,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/lib/device-chain.js":{"offset":11591550,"length":4232,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/b4a/index.js":{"offset":11595782,"length":4054,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/b4a/package.json":{"offset":11599836,"length":1245,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-ansi-escapes/index.js":{"offset":11601081,"length":2255,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-ansi-escapes/package.json":{"offset":11603336,"length":1178,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-assert/index.js":{"offset":11604514,"length":2192,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-assert/package.json":{"offset":11606706,"length":835,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-inspect/binding.js":{"offset":11607541,"length":33,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-inspect/index.js":{"offset":11607574,"length":23856,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-inspect/package.json":{"offset":11631430,"length":1041,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-type/binding.js":{"offset":11632471,"length":33,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-type/index.js":{"offset":11632504,"length":4566,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-type/package.json":{"offset":11637070,"length":938,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/index.js":{"offset":11638008,"length":4554,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json":{"offset":11642562,"length":789,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/chinese_simplified.json":{"offset":11643351,"length":12289,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/chinese_traditional.json":{"offset":11655640,"length":12289,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/czech.json":{"offset":11667929,"length":19042,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/english.json":{"offset":11686971,"length":17213,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/french.json":{"offset":11704184,"length":20874,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/index.js":{"offset":11725058,"length":1406,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/italian.json":{"offset":11726464,"length":20130,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/japanese.json":{"offset":11746594,"length":30520,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/korean.json":{"offset":11777114,"length":41929,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/lookup.json":{"offset":11819043,"length":592224,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/portuguese.json":{"offset":12411267,"length":19768,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/russian.json":{"offset":12431035,"length":30635,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/spanish.json":{"offset":12461670,"length":18093,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/turkish.json":{"offset":12479763,"length":19421,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/compact-encoding/endian.js":{"offset":12499184,"length":105,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/compact-encoding/index.js":{"offset":12499289,"length":26406,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/compact-encoding/lexint.js":{"offset":12525695,"length":2851,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/compact-encoding/package.json":{"offset":12528546,"length":866,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/compact-encoding/raw.js":{"offset":12529412,"length":3977,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/keet-identity-key/index.js":{"offset":12533389,"length":6320,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/keet-identity-key/lib/crypto.js":{"offset":12539709,"length":552,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/keet-identity-key/lib/encoding.js":{"offset":12540261,"length":3695,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/keet-identity-key/lib/keychain.js":{"offset":12543956,"length":3080,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/keet-identity-key/package.json":{"offset":12547036,"length":887,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/nanoassert/index.js":{"offset":12547923,"length":438,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/nanoassert/package.json":{"offset":12548361,"length":647,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/require-addon/lib/bare.js":{"offset":12549008,"length":45,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/require-addon/package.json":{"offset":12549053,"length":1449,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-hmac/hash/sha256.js":{"offset":12550502,"length":284,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-hmac/hash/sha512.js":{"offset":12550786,"length":284,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-hmac/index.js":{"offset":12551070,"length":2063,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-hmac/package.json":{"offset":12553133,"length":670,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-native/binding.js":{"offset":12553803,"length":89,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-native/index.js":{"offset":12553892,"length":107894,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-native/package.json":{"offset":12661786,"length":1478,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-universal/index.js":{"offset":12663264,"length":42,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-universal/package.json":{"offset":12663306,"length":1217,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/which-runtime/index.js":{"offset":12664523,"length":1469,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/which-runtime/package.json":{"offset":12665992,"length":863,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-identity/package.json":{"offset":12666855,"length":791,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/lib/pairing.js":{"offset":12667646,"length":5903,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/@hyperswarm/secret-stream/index.js":{"offset":12673549,"length":16722,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/@hyperswarm/secret-stream/lib/bridge.js":{"offset":12690271,"length":1273,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/@hyperswarm/secret-stream/lib/handshake.js":{"offset":12691544,"length":1950,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/@hyperswarm/secret-stream/package.json":{"offset":12693494,"length":1132,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/adaptive-timeout/index.js":{"offset":12694626,"length":2424,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/adaptive-timeout/package.json":{"offset":12697050,"length":972,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js":{"offset":12698022,"length":4054,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/package.json":{"offset":12702076,"length":1245,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-ansi-escapes/index.js":{"offset":12703321,"length":2255,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-ansi-escapes/package.json":{"offset":12705576,"length":1178,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-assert/index.js":{"offset":12706754,"length":2192,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-assert/package.json":{"offset":12708946,"length":835,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-events/index.js":{"offset":12709781,"length":8307,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-events/lib/errors.js":{"offset":12718088,"length":671,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-events/package.json":{"offset":12718759,"length":1504,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-inspect/binding.js":{"offset":12720263,"length":33,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-inspect/index.js":{"offset":12720296,"length":23856,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-inspect/package.json":{"offset":12744152,"length":1041,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-type/binding.js":{"offset":12745193,"length":33,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-type/index.js":{"offset":12745226,"length":4566,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-type/package.json":{"offset":12749792,"length":938,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bits-to-bytes/index.js":{"offset":12750730,"length":3083,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bits-to-bytes/package.json":{"offset":12753813,"length":708,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-pairing/index.js":{"offset":12754521,"length":16910,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-pairing/package.json":{"offset":12771431,"length":1000,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-relay/index.js":{"offset":12772431,"length":13411,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-relay/lib/errors.js":{"offset":12785842,"length":1036,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-relay/node_modules/compact-encoding/endian.js":{"offset":12786878,"length":105,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-relay/node_modules/compact-encoding/index.js":{"offset":12786983,"length":26406,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-relay/node_modules/compact-encoding/lexint.js":{"offset":12813389,"length":2851,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-relay/node_modules/compact-encoding/package.json":{"offset":12816240,"length":866,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-relay/node_modules/compact-encoding/raw.js":{"offset":12817106,"length":3977,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-relay/package.json":{"offset":12821083,"length":1231,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bogon/index.js":{"offset":12822314,"length":4004,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bogon/node_modules/compact-encoding/endian.js":{"offset":12826318,"length":105,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bogon/node_modules/compact-encoding/index.js":{"offset":12826423,"length":26406,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bogon/node_modules/compact-encoding/lexint.js":{"offset":12852829,"length":2851,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bogon/node_modules/compact-encoding/package.json":{"offset":12855680,"length":866,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bogon/node_modules/compact-encoding/raw.js":{"offset":12856546,"length":3977,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bogon/package.json":{"offset":12860523,"length":656,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding-bitfield/index.js":{"offset":12861179,"length":1967,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/endian.js":{"offset":12863146,"length":105,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/index.js":{"offset":12863251,"length":26406,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/lexint.js":{"offset":12889657,"length":2851,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/package.json":{"offset":12892508,"length":866,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/raw.js":{"offset":12893374,"length":3977,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding-bitfield/package.json":{"offset":12897351,"length":1109,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding/endian.js":{"offset":12898460,"length":105,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding/index.js":{"offset":12898565,"length":24454,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding/lexint.js":{"offset":12923019,"length":2851,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding/package.json":{"offset":12925870,"length":786,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding/raw.js":{"offset":12926656,"length":4093,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/debounceify/index.js":{"offset":12930749,"length":585,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/debounceify/package.json":{"offset":12931334,"length":567,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/index.js":{"offset":12931901,"length":29079,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/lib/commands.js":{"offset":12960980,"length":107,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/lib/errors.js":{"offset":12961087,"length":719,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/lib/health.js":{"offset":12961806,"length":2998,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/lib/io.js":{"offset":12964804,"length":16605,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/lib/peer.js":{"offset":12981409,"length":583,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/lib/query.js":{"offset":12981992,"length":9899,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/lib/session.js":{"offset":12991891,"length":1103,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/node_modules/compact-encoding/endian.js":{"offset":12992994,"length":105,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/node_modules/compact-encoding/index.js":{"offset":12993099,"length":26406,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/node_modules/compact-encoding/lexint.js":{"offset":13019505,"length":2851,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/node_modules/compact-encoding/package.json":{"offset":13022356,"length":866,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/node_modules/compact-encoding/raw.js":{"offset":13023222,"length":3977,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/package.json":{"offset":13027199,"length":1396,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/events-universal/bare.js":{"offset":13028595,"length":40,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/events-universal/package.json":{"offset":13028635,"length":908,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/fast-fifo/fixed-size.js":{"offset":13029543,"length":875,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/fast-fifo/index.js":{"offset":13030418,"length":972,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/fast-fifo/package.json":{"offset":13031390,"length":682,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/index.js":{"offset":13032072,"length":5031,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/node_modules/compact-encoding/endian.js":{"offset":13037103,"length":105,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/node_modules/compact-encoding/index.js":{"offset":13037208,"length":26406,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/node_modules/compact-encoding/lexint.js":{"offset":13063614,"length":2851,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/node_modules/compact-encoding/package.json":{"offset":13066465,"length":866,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/node_modules/compact-encoding/raw.js":{"offset":13067331,"length":3977,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/package.json":{"offset":13071308,"length":1007,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-id-encoding/index.js":{"offset":13072315,"length":923,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-id-encoding/package.json":{"offset":13073238,"length":799,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht-address/index.js":{"offset":13074037,"length":357,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht-address/node_modules/compact-encoding/endian.js":{"offset":13074394,"length":105,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht-address/node_modules/compact-encoding/index.js":{"offset":13074499,"length":26406,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht-address/node_modules/compact-encoding/lexint.js":{"offset":13100905,"length":2851,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht-address/node_modules/compact-encoding/package.json":{"offset":13103756,"length":866,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht-address/node_modules/compact-encoding/raw.js":{"offset":13104622,"length":3977,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht-address/package.json":{"offset":13108599,"length":1046,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht-address/spec/hyperschema/index.js":{"offset":13109645,"length":2106,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/index.js":{"offset":13111751,"length":16589,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/announcer.js":{"offset":13128340,"length":7533,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/connect.js":{"offset":13135873,"length":25203,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/connection-pool.js":{"offset":13161076,"length":3050,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/constants.js":{"offset":13164126,"length":1178,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/crypto.js":{"offset":13165304,"length":632,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/encode.js":{"offset":13165936,"length":446,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/errors.js":{"offset":13166382,"length":3713,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/holepuncher.js":{"offset":13170095,"length":10003,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/messages.js":{"offset":13180098,"length":12057,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/nat.js":{"offset":13192155,"length":4714,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/noise-wrap.js":{"offset":13196869,"length":1669,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/persistent.js":{"offset":13198538,"length":8361,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/raw-stream-set.js":{"offset":13206899,"length":1511,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/relay-connection.js":{"offset":13208410,"length":2062,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/router.js":{"offset":13210472,"length":6978,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/secure-payload.js":{"offset":13217450,"length":1491,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/semaphore.js":{"offset":13218941,"length":1577,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/server.js":{"offset":13220518,"length":22065,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/sleeper.js":{"offset":13242583,"length":690,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/socket-pool.js":{"offset":13243273,"length":4343,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/endian.js":{"offset":13247616,"length":105,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/index.js":{"offset":13247721,"length":26406,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/lexint.js":{"offset":13274127,"length":2851,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/package.json":{"offset":13276978,"length":866,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/raw.js":{"offset":13277844,"length":3977,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/package.json":{"offset":13281821,"length":2007,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperschema/node_modules/compact-encoding/endian.js":{"offset":13283828,"length":105,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperschema/node_modules/compact-encoding/index.js":{"offset":13283933,"length":26406,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperschema/node_modules/compact-encoding/lexint.js":{"offset":13310339,"length":2851,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperschema/node_modules/compact-encoding/package.json":{"offset":13313190,"length":866,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperschema/node_modules/compact-encoding/raw.js":{"offset":13314056,"length":3977,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperschema/package.json":{"offset":13318033,"length":1555,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperschema/runtime.cjs":{"offset":13319588,"length":54,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperswarm/index.js":{"offset":13319642,"length":18589,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperswarm/lib/bulk-timer.js":{"offset":13338231,"length":728,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperswarm/lib/connection-set.js":{"offset":13338959,"length":823,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperswarm/lib/peer-discovery.js":{"offset":13339782,"length":9296,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperswarm/lib/peer-info.js":{"offset":13349078,"length":2688,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperswarm/lib/retry-timer.js":{"offset":13351766,"length":1889,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperswarm/package.json":{"offset":13353655,"length":1515,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/is-options/index.js":{"offset":13355170,"length":140,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/is-options/package.json":{"offset":13355310,"length":605,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/kademlia-routing-table/index.js":{"offset":13355915,"length":4145,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/kademlia-routing-table/package.json":{"offset":13360060,"length":967,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/nanoassert/index.js":{"offset":13361027,"length":438,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/nanoassert/package.json":{"offset":13361465,"length":647,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/nat-sampler/index.js":{"offset":13362112,"length":1550,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/nat-sampler/package.json":{"offset":13363662,"length":608,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-curve-ed/index.js":{"offset":13364270,"length":1642,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-curve-ed/package.json":{"offset":13365912,"length":808,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-handshake/cipher.js":{"offset":13366720,"length":2817,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-handshake/dh.js":{"offset":13369537,"length":1439,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-handshake/hkdf.js":{"offset":13370976,"length":1092,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-handshake/hmac.js":{"offset":13372068,"length":1273,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-handshake/noise.js":{"offset":13373341,"length":6437,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-handshake/package.json":{"offset":13379778,"length":638,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-handshake/symmetric-state.js":{"offset":13380416,"length":2206,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux/index.js":{"offset":13382622,"length":19741,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux/node_modules/compact-encoding/endian.js":{"offset":13402363,"length":105,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux/node_modules/compact-encoding/index.js":{"offset":13402468,"length":26406,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux/node_modules/compact-encoding/lexint.js":{"offset":13428874,"length":2851,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux/node_modules/compact-encoding/package.json":{"offset":13431725,"length":866,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux/node_modules/compact-encoding/raw.js":{"offset":13432591,"length":3977,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux/package.json":{"offset":13436568,"length":1059,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/queue-tick/package.json":{"offset":13437627,"length":669,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/queue-tick/process-next-tick.js":{"offset":13438296,"length":160,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/queue-tick/queue-microtask.js":{"offset":13438456,"length":108,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/ready-resource/index.js":{"offset":13438564,"length":1091,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/ready-resource/package.json":{"offset":13439655,"length":812,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/record-cache/index.js":{"offset":13440467,"length":3668,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/record-cache/package.json":{"offset":13444135,"length":612,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/require-addon/lib/bare.js":{"offset":13444747,"length":45,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/require-addon/package.json":{"offset":13444792,"length":1449,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/safety-catch/index.js":{"offset":13446241,"length":543,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/safety-catch/package.json":{"offset":13446784,"length":547,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/shuffled-priority-queue/index.js":{"offset":13447331,"length":2607,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/shuffled-priority-queue/package.json":{"offset":13449938,"length":691,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/signal-promise/index.js":{"offset":13450629,"length":1252,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/signal-promise/package.json":{"offset":13451881,"length":503,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-native/binding.js":{"offset":13452384,"length":89,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-native/index.js":{"offset":13452473,"length":107894,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-native/package.json":{"offset":13560367,"length":1478,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-secretstream/index.js":{"offset":13561845,"length":2257,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-secretstream/package.json":{"offset":13564102,"length":657,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-universal/index.js":{"offset":13564759,"length":42,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-universal/package.json":{"offset":13564801,"length":1217,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/streamx/index.js":{"offset":13566018,"length":34248,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/streamx/lib/errors.js":{"offset":13600266,"length":1096,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/streamx/package.json":{"offset":13601362,"length":1225,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/text-decoder/index.js":{"offset":13602587,"length":1371,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/text-decoder/lib/pass-through-decoder.js":{"offset":13603958,"length":269,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/text-decoder/lib/utf8-decoder.js":{"offset":13604227,"length":4429,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/text-decoder/package.json":{"offset":13608656,"length":990,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/time-ordered-set/index.js":{"offset":13609646,"length":1444,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/time-ordered-set/package.json":{"offset":13611090,"length":666,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/timeout-refresh/browser.js":{"offset":13611756,"length":1098,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/timeout-refresh/index.js":{"offset":13612854,"length":184,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/timeout-refresh/node.js":{"offset":13613038,"length":928,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/timeout-refresh/package.json":{"offset":13613966,"length":619,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/udx-native/binding.js":{"offset":13614585,"length":90,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/udx-native/lib/ip.js":{"offset":13614675,"length":2204,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/udx-native/lib/network-interfaces.js":{"offset":13616879,"length":1341,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/udx-native/lib/socket.js":{"offset":13618220,"length":7557,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/udx-native/lib/stream.js":{"offset":13625777,"length":13050,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/udx-native/lib/udx.js":{"offset":13638827,"length":2868,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/udx-native/package.json":{"offset":13641695,"length":1665,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/unordered-set/index.js":{"offset":13643360,"length":677,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/unordered-set/package.json":{"offset":13644037,"length":654,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/unslab/index.js":{"offset":13644691,"length":913,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/unslab/package.json":{"offset":13645604,"length":613,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/which-runtime/index.js":{"offset":13646217,"length":1469,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/which-runtime/package.json":{"offset":13647686,"length":863,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/xache/index.js":{"offset":13648549,"length":2378,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/xache/package.json":{"offset":13650927,"length":584,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/z32/index.js":{"offset":13651511,"length":2654,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/z32/package.json":{"offset":13654165,"length":701,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/atproto-room/package.json":{"offset":13654866,"length":1441,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/b4a/index.js":{"offset":13656307,"length":4054,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/b4a/package.json":{"offset":13660361,"length":1245,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-ansi-escapes/index.js":{"offset":13661606,"length":2255,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-ansi-escapes/package.json":{"offset":13663861,"length":1178,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-assert/index.js":{"offset":13665039,"length":2192,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-assert/package.json":{"offset":13667231,"length":835,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-events/index.js":{"offset":13668066,"length":8307,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-events/lib/errors.js":{"offset":13676373,"length":671,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-events/package.json":{"offset":13677044,"length":1504,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-fs/binding.js":{"offset":13678548,"length":33,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-fs/index.js":{"offset":13678581,"length":58907,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-fs/lib/constants.js":{"offset":13737488,"length":1494,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-fs/lib/errors.js":{"offset":13738982,"length":1163,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-fs/package.json":{"offset":13740145,"length":1654,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-fs/promises.js":{"offset":13741799,"length":2401,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-inspect/binding.js":{"offset":13744200,"length":33,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-inspect/index.js":{"offset":13744233,"length":23856,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-inspect/package.json":{"offset":13768089,"length":1041,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-os/binding.js":{"offset":13769130,"length":33,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-os/index.js":{"offset":13769163,"length":5216,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-os/lib/constants.js":{"offset":13774379,"length":143,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-os/lib/errors.js":{"offset":13774522,"length":453,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-os/package.json":{"offset":13774975,"length":1257,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-path/index.js":{"offset":13776232,"length":287,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-path/lib/constants.js":{"offset":13776519,"length":247,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-path/lib/posix.js":{"offset":13776766,"length":6005,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-path/lib/shared.js":{"offset":13782771,"length":1926,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-path/lib/win32.js":{"offset":13784697,"length":13591,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-path/package.json":{"offset":13798288,"length":1036,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-stream/index.js":{"offset":13799324,"length":10904,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-stream/package.json":{"offset":13810228,"length":1676,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-stream/web.js":{"offset":13811904,"length":13980,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-type/binding.js":{"offset":13825884,"length":33,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-type/index.js":{"offset":13825917,"length":4566,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-type/package.json":{"offset":13830483,"length":938,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-url/binding.js":{"offset":13831421,"length":33,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-url/index.js":{"offset":13831454,"length":9449,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-url/lib/errors.js":{"offset":13840903,"length":778,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-url/lib/url-search-params.js":{"offset":13841681,"length":4331,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bare-url/package.json":{"offset":13846012,"length":1219,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/index.js":{"offset":13847231,"length":4554,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/package.json":{"offset":13851785,"length":789,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/chinese_simplified.json":{"offset":13852574,"length":12289,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/chinese_traditional.json":{"offset":13864863,"length":12289,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/czech.json":{"offset":13877152,"length":19042,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/english.json":{"offset":13896194,"length":17213,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/french.json":{"offset":13913407,"length":20874,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/index.js":{"offset":13934281,"length":1406,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/italian.json":{"offset":13935687,"length":20130,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/japanese.json":{"offset":13955817,"length":30520,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/korean.json":{"offset":13986337,"length":41929,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/lookup.json":{"offset":14028266,"length":592224,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/portuguese.json":{"offset":14620490,"length":19768,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/russian.json":{"offset":14640258,"length":30635,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/spanish.json":{"offset":14670893,"length":18093,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/turkish.json":{"offset":14688986,"length":19421,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/events-universal/bare.js":{"offset":14708407,"length":40,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/events-universal/package.json":{"offset":14708447,"length":908,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/fast-fifo/fixed-size.js":{"offset":14709355,"length":875,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/fast-fifo/index.js":{"offset":14710230,"length":972,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/fast-fifo/package.json":{"offset":14711202,"length":682,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/keet-identity-key/index.js":{"offset":14711884,"length":6320,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/keet-identity-key/lib/crypto.js":{"offset":14718204,"length":552,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/keet-identity-key/lib/encoding.js":{"offset":14718756,"length":3695,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/keet-identity-key/lib/keychain.js":{"offset":14722451,"length":3080,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/keet-identity-key/node_modules/compact-encoding/endian.js":{"offset":14725531,"length":105,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/keet-identity-key/node_modules/compact-encoding/index.js":{"offset":14725636,"length":26406,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/keet-identity-key/node_modules/compact-encoding/lexint.js":{"offset":14752042,"length":2851,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/keet-identity-key/node_modules/compact-encoding/package.json":{"offset":14754893,"length":866,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/keet-identity-key/node_modules/compact-encoding/raw.js":{"offset":14755759,"length":3977,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/keet-identity-key/package.json":{"offset":14759736,"length":887,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/nanoassert/index.js":{"offset":14760623,"length":438,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/nanoassert/package.json":{"offset":14761061,"length":647,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/require-addon/lib/bare.js":{"offset":14761708,"length":45,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/require-addon/package.json":{"offset":14761753,"length":1449,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/sodium-hmac/hash/sha256.js":{"offset":14763202,"length":284,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/sodium-hmac/hash/sha512.js":{"offset":14763486,"length":284,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/sodium-hmac/index.js":{"offset":14763770,"length":2063,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/sodium-hmac/package.json":{"offset":14765833,"length":670,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/sodium-native/binding.js":{"offset":14766503,"length":89,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/sodium-native/index.js":{"offset":14766592,"length":107894,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/sodium-native/package.json":{"offset":14874486,"length":1478,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/sodium-universal/index.js":{"offset":14875964,"length":42,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/sodium-universal/package.json":{"offset":14876006,"length":1217,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/streamx/index.js":{"offset":14877223,"length":34248,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/streamx/lib/errors.js":{"offset":14911471,"length":1096,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/streamx/package.json":{"offset":14912567,"length":1225,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/teex/index.js":{"offset":14913792,"length":1107,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/teex/package.json":{"offset":14914899,"length":608,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/text-decoder/index.js":{"offset":14915507,"length":1371,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/text-decoder/lib/pass-through-decoder.js":{"offset":14916878,"length":269,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/text-decoder/lib/utf8-decoder.js":{"offset":14917147,"length":4429,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/text-decoder/package.json":{"offset":14921576,"length":990,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/which-runtime/index.js":{"offset":14922566,"length":1469,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/node_modules/which-runtime/package.json":{"offset":14924035,"length":863,"mode":420},"/node_modules/favela-web/node_modules/hyper-proto-peer/package.json":{"offset":14924898,"length":2256,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/index.js":{"offset":14927154,"length":424,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/lib/client.js":{"offset":14927578,"length":14860,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/lib/frame.js":{"offset":14942438,"length":1862,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/lib/service.js":{"offset":14944300,"length":11770,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/lib/transports/http.js":{"offset":14956070,"length":7998,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/lib/transports/swarm-rpc.js":{"offset":14964068,"length":4427,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/lib/transports/swarm.js":{"offset":14968495,"length":8308,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/lib/transports/uds.js":{"offset":14976803,"length":8779,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/lib/uds-backend.js":{"offset":14985582,"length":1568,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/index.js":{"offset":14987150,"length":16722,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/lib/bridge.js":{"offset":15003872,"length":1273,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/lib/handshake.js":{"offset":15005145,"length":1950,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/package.json":{"offset":15007095,"length":1132,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/adaptive-timeout/index.js":{"offset":15008227,"length":2424,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/adaptive-timeout/package.json":{"offset":15010651,"length":972,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/index.js":{"offset":15011623,"length":4054,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/b4a/package.json":{"offset":15015677,"length":1245,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-abort/binding.js":{"offset":15016922,"length":33,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-abort/index.js":{"offset":15016955,"length":69,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-abort/package.json":{"offset":15017024,"length":886,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-ansi-escapes/index.js":{"offset":15017910,"length":2255,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-ansi-escapes/package.json":{"offset":15020165,"length":1178,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-assert/index.js":{"offset":15021343,"length":2192,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-assert/package.json":{"offset":15023535,"length":835,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-dns/binding.js":{"offset":15024370,"length":33,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-dns/index.js":{"offset":15024403,"length":1345,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-dns/package.json":{"offset":15025748,"length":968,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-env/index.js":{"offset":15026716,"length":1023,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-env/package.json":{"offset":15027739,"length":649,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-events/index.js":{"offset":15028388,"length":8033,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-events/lib/errors.js":{"offset":15036421,"length":671,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-events/package.json":{"offset":15037092,"length":1399,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-fs/binding.js":{"offset":15038491,"length":33,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-fs/index.js":{"offset":15038524,"length":58907,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-fs/lib/constants.js":{"offset":15097431,"length":1494,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-fs/lib/errors.js":{"offset":15098925,"length":1163,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-fs/package.json":{"offset":15100088,"length":1654,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-fs/promises.js":{"offset":15101742,"length":2401,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-hrtime/binding.js":{"offset":15104143,"length":33,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-hrtime/index.js":{"offset":15104176,"length":319,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-hrtime/package.json":{"offset":15104495,"length":905,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http-parser/index.js":{"offset":15105400,"length":17480,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http-parser/lib/errors.js":{"offset":15122880,"length":845,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http-parser/package.json":{"offset":15123725,"length":793,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http1/index.js":{"offset":15124518,"length":2188,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http1/lib/agent.js":{"offset":15126706,"length":4498,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http1/lib/client-connection.js":{"offset":15131204,"length":3663,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http1/lib/client-request.js":{"offset":15134867,"length":3286,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http1/lib/constants.js":{"offset":15138153,"length":2016,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http1/lib/errors.js":{"offset":15140169,"length":634,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http1/lib/incoming-message.js":{"offset":15140803,"length":1568,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http1/lib/outgoing-message.js":{"offset":15142371,"length":1291,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http1/lib/server-connection.js":{"offset":15143662,"length":4041,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http1/lib/server-response.js":{"offset":15147703,"length":3183,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http1/lib/server.js":{"offset":15150886,"length":977,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-http1/package.json":{"offset":15151863,"length":1510,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-inspect/binding.js":{"offset":15153373,"length":33,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-inspect/index.js":{"offset":15153406,"length":23856,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-inspect/package.json":{"offset":15177262,"length":1041,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-net/index.js":{"offset":15178303,"length":6868,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-dns/binding.js":{"offset":15185171,"length":33,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-dns/index.js":{"offset":15185204,"length":860,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-dns/package.json":{"offset":15186064,"length":772,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/binding.js":{"offset":15186836,"length":33,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/index.js":{"offset":15186869,"length":10947,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/lib/constants.js":{"offset":15197816,"length":188,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/lib/errors.js":{"offset":15198004,"length":668,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/package.json":{"offset":15198672,"length":962,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/binding.js":{"offset":15199634,"length":33,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/index.js":{"offset":15199667,"length":12710,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/lib/constants.js":{"offset":15212377,"length":167,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/lib/errors.js":{"offset":15212544,"length":799,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/lib/ip.js":{"offset":15213343,"length":2179,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/package.json":{"offset":15215522,"length":959,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-net/package.json":{"offset":15216481,"length":793,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-os/binding.js":{"offset":15217274,"length":33,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-os/index.js":{"offset":15217307,"length":3224,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-os/lib/constants.js":{"offset":15220531,"length":143,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-os/lib/errors.js":{"offset":15220674,"length":453,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-os/package.json":{"offset":15221127,"length":1257,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-path/index.js":{"offset":15222384,"length":306,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-path/lib/constants.js":{"offset":15222690,"length":247,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-path/lib/posix.js":{"offset":15222937,"length":5991,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-path/lib/shared.js":{"offset":15228928,"length":1888,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-path/lib/win32.js":{"offset":15230816,"length":13427,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-path/package.json":{"offset":15244243,"length":796,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-pipe/binding.js":{"offset":15245039,"length":33,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-pipe/index.js":{"offset":15245072,"length":10769,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-pipe/lib/constants.js":{"offset":15255841,"length":208,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-pipe/lib/errors.js":{"offset":15256049,"length":599,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-pipe/package.json":{"offset":15256648,"length":1256,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-process/index.js":{"offset":15257904,"length":2689,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-process/package.json":{"offset":15260593,"length":1255,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-signals/binding.js":{"offset":15261848,"length":33,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-signals/index.js":{"offset":15261881,"length":1517,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-signals/lib/emitter.js":{"offset":15263398,"length":1278,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-signals/lib/errors.js":{"offset":15264676,"length":479,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-signals/package.json":{"offset":15265155,"length":1112,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-stdio/binding.js":{"offset":15266267,"length":33,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-stdio/index.js":{"offset":15266300,"length":1525,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-stdio/package.json":{"offset":15267825,"length":1319,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-stream/index.js":{"offset":15269144,"length":10913,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-stream/package.json":{"offset":15280057,"length":1655,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-stream/web.js":{"offset":15281712,"length":13980,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-tcp/binding.js":{"offset":15295692,"length":33,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-tcp/index.js":{"offset":15295725,"length":15054,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-tcp/lib/constants.js":{"offset":15310779,"length":167,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-tcp/lib/errors.js":{"offset":15310946,"length":711,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-tcp/lib/ip.js":{"offset":15311657,"length":2204,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-tcp/package.json":{"offset":15313861,"length":1243,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-tty/binding.js":{"offset":15315104,"length":33,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-tty/index.js":{"offset":15315137,"length":4469,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-tty/lib/constants.js":{"offset":15319606,"length":442,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-tty/package.json":{"offset":15320048,"length":1097,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-type/binding.js":{"offset":15321145,"length":33,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-type/index.js":{"offset":15321178,"length":4566,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-type/package.json":{"offset":15325744,"length":938,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-url/binding.js":{"offset":15326682,"length":33,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-url/index.js":{"offset":15326715,"length":9308,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-url/lib/errors.js":{"offset":15336023,"length":778,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-url/lib/url-search-params.js":{"offset":15336801,"length":4331,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bare-url/package.json":{"offset":15341132,"length":1219,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bits-to-bytes/index.js":{"offset":15342351,"length":3083,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bits-to-bytes/package.json":{"offset":15345434,"length":708,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/blind-relay/index.js":{"offset":15346142,"length":13256,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/blind-relay/lib/errors.js":{"offset":15359398,"length":1036,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/endian.js":{"offset":15360434,"length":105,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/index.js":{"offset":15360539,"length":24454,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/lexint.js":{"offset":15384993,"length":2851,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/package.json":{"offset":15387844,"length":786,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/raw.js":{"offset":15388630,"length":4093,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/blind-relay/package.json":{"offset":15392723,"length":1232,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bogon/index.js":{"offset":15393955,"length":4052,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/endian.js":{"offset":15398007,"length":105,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/index.js":{"offset":15398112,"length":24454,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/lexint.js":{"offset":15422566,"length":2851,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/package.json":{"offset":15425417,"length":786,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/raw.js":{"offset":15426203,"length":4093,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/bogon/package.json":{"offset":15430296,"length":657,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/index.js":{"offset":15430953,"length":1963,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/endian.js":{"offset":15432916,"length":105,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/index.js":{"offset":15433021,"length":24454,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/lexint.js":{"offset":15457475,"length":2851,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/package.json":{"offset":15460326,"length":786,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/raw.js":{"offset":15461112,"length":4093,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/package.json":{"offset":15465205,"length":827,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding-net/index.js":{"offset":15466032,"length":4109,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/endian.js":{"offset":15470141,"length":105,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/index.js":{"offset":15470246,"length":24454,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/lexint.js":{"offset":15494700,"length":2851,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/package.json":{"offset":15497551,"length":786,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/raw.js":{"offset":15498337,"length":4093,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding-net/package.json":{"offset":15502430,"length":734,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding/endian.js":{"offset":15503164,"length":105,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding/index.js":{"offset":15503269,"length":26135,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding/lexint.js":{"offset":15529404,"length":2851,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding/package.json":{"offset":15532255,"length":866,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/compact-encoding/raw.js":{"offset":15533121,"length":3977,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/dht-rpc/index.js":{"offset":15537098,"length":29079,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/dht-rpc/lib/commands.js":{"offset":15566177,"length":107,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/dht-rpc/lib/errors.js":{"offset":15566284,"length":719,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/dht-rpc/lib/health.js":{"offset":15567003,"length":2998,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/dht-rpc/lib/io.js":{"offset":15570001,"length":16605,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/dht-rpc/lib/peer.js":{"offset":15586606,"length":631,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/dht-rpc/lib/query.js":{"offset":15587237,"length":9899,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/dht-rpc/lib/session.js":{"offset":15597136,"length":1103,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/endian.js":{"offset":15598239,"length":105,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/index.js":{"offset":15598344,"length":24454,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/lexint.js":{"offset":15622798,"length":2851,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/package.json":{"offset":15625649,"length":786,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/raw.js":{"offset":15626435,"length":4093,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/dht-rpc/package.json":{"offset":15630528,"length":1397,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/events-universal/bare.js":{"offset":15631925,"length":40,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/events-universal/package.json":{"offset":15631965,"length":908,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/fast-fifo/fixed-size.js":{"offset":15632873,"length":875,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/fast-fifo/index.js":{"offset":15633748,"length":972,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/fast-fifo/package.json":{"offset":15634720,"length":682,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hypercore-crypto/index.js":{"offset":15635402,"length":5040,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/endian.js":{"offset":15640442,"length":105,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/index.js":{"offset":15640547,"length":24454,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/lexint.js":{"offset":15665001,"length":2851,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/package.json":{"offset":15667852,"length":786,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/raw.js":{"offset":15668638,"length":4093,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hypercore-crypto/package.json":{"offset":15672731,"length":771,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hypercore-id-encoding/index.js":{"offset":15673502,"length":923,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hypercore-id-encoding/package.json":{"offset":15674425,"length":799,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht-address/index.js":{"offset":15675224,"length":357,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/endian.js":{"offset":15675581,"length":105,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/index.js":{"offset":15675686,"length":24454,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/lexint.js":{"offset":15700140,"length":2851,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/package.json":{"offset":15702991,"length":786,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/raw.js":{"offset":15703777,"length":4093,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht-address/package.json":{"offset":15707870,"length":1047,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht-address/spec/hyperschema/index.js":{"offset":15708917,"length":2106,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/index.js":{"offset":15711023,"length":16611,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/announcer.js":{"offset":15727634,"length":7533,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/connect.js":{"offset":15735167,"length":24788,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/connection-pool.js":{"offset":15759955,"length":3050,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/constants.js":{"offset":15763005,"length":1276,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/crypto.js":{"offset":15764281,"length":632,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/encode.js":{"offset":15764913,"length":446,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/errors.js":{"offset":15765359,"length":3712,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/holepuncher.js":{"offset":15769071,"length":10003,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/messages.js":{"offset":15779074,"length":11789,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/nat.js":{"offset":15790863,"length":4714,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/noise-wrap.js":{"offset":15795577,"length":1669,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/persistent.js":{"offset":15797246,"length":8361,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/raw-stream-set.js":{"offset":15805607,"length":1511,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/router.js":{"offset":15807118,"length":6978,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/secure-payload.js":{"offset":15814096,"length":1491,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/semaphore.js":{"offset":15815587,"length":1577,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/server.js":{"offset":15817164,"length":21300,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/sleeper.js":{"offset":15838464,"length":690,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/lib/socket-pool.js":{"offset":15839154,"length":4343,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/endian.js":{"offset":15843497,"length":105,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/index.js":{"offset":15843602,"length":24454,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/lexint.js":{"offset":15868056,"length":2851,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/package.json":{"offset":15870907,"length":786,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/raw.js":{"offset":15871693,"length":4093,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperdht/package.json":{"offset":15875786,"length":2007,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/endian.js":{"offset":15877793,"length":105,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/index.js":{"offset":15877898,"length":24454,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/lexint.js":{"offset":15902352,"length":2851,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/package.json":{"offset":15905203,"length":786,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/raw.js":{"offset":15905989,"length":4093,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperschema/package.json":{"offset":15910082,"length":1556,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperschema/runtime.cjs":{"offset":15911638,"length":54,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperswarm/index.js":{"offset":15911692,"length":18589,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperswarm/lib/bulk-timer.js":{"offset":15930281,"length":728,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperswarm/lib/connection-set.js":{"offset":15931009,"length":823,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperswarm/lib/peer-discovery.js":{"offset":15931832,"length":9296,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperswarm/lib/peer-info.js":{"offset":15941128,"length":2688,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperswarm/lib/retry-timer.js":{"offset":15943816,"length":1889,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/hyperswarm/package.json":{"offset":15945705,"length":1515,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/kademlia-routing-table/index.js":{"offset":15947220,"length":4145,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/kademlia-routing-table/package.json":{"offset":15951365,"length":967,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/nanoassert/index.js":{"offset":15952332,"length":438,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/nanoassert/package.json":{"offset":15952770,"length":647,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/nat-sampler/index.js":{"offset":15953417,"length":1550,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/nat-sampler/package.json":{"offset":15954967,"length":608,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/noise-curve-ed/index.js":{"offset":15955575,"length":1642,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/noise-curve-ed/package.json":{"offset":15957217,"length":808,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/noise-handshake/cipher.js":{"offset":15958025,"length":2817,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/noise-handshake/dh.js":{"offset":15960842,"length":1439,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/noise-handshake/hkdf.js":{"offset":15962281,"length":1092,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/noise-handshake/hmac.js":{"offset":15963373,"length":1273,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/noise-handshake/noise.js":{"offset":15964646,"length":6437,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/noise-handshake/package.json":{"offset":15971083,"length":638,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/noise-handshake/symmetric-state.js":{"offset":15971721,"length":2206,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/protomux/index.js":{"offset":15973927,"length":19741,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/protomux/package.json":{"offset":15993668,"length":1059,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/queue-tick/package.json":{"offset":15994727,"length":669,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/queue-tick/process-next-tick.js":{"offset":15995396,"length":160,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/queue-tick/queue-microtask.js":{"offset":15995556,"length":108,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/ready-resource/index.js":{"offset":15995664,"length":1091,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/ready-resource/package.json":{"offset":15996755,"length":812,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/record-cache/index.js":{"offset":15997567,"length":3668,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/record-cache/package.json":{"offset":16001235,"length":612,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/require-addon/lib/bare.js":{"offset":16001847,"length":45,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/require-addon/package.json":{"offset":16001892,"length":1449,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/safety-catch/index.js":{"offset":16003341,"length":543,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/safety-catch/package.json":{"offset":16003884,"length":547,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/shuffled-priority-queue/index.js":{"offset":16004431,"length":2607,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/shuffled-priority-queue/package.json":{"offset":16007038,"length":691,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/signal-promise/index.js":{"offset":16007729,"length":1252,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/signal-promise/package.json":{"offset":16008981,"length":503,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/sodium-native/binding.js":{"offset":16009484,"length":89,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/sodium-native/index.js":{"offset":16009573,"length":107894,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/sodium-native/package.json":{"offset":16117467,"length":1478,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/sodium-secretstream/index.js":{"offset":16118945,"length":2257,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/sodium-secretstream/package.json":{"offset":16121202,"length":657,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/sodium-universal/index.js":{"offset":16121859,"length":42,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/sodium-universal/package.json":{"offset":16121901,"length":1217,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/streamx/index.js":{"offset":16123118,"length":33510,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/streamx/package.json":{"offset":16156628,"length":912,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/teex/index.js":{"offset":16157540,"length":1107,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/teex/package.json":{"offset":16158647,"length":608,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/text-decoder/index.js":{"offset":16159255,"length":1371,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/text-decoder/lib/pass-through-decoder.js":{"offset":16160626,"length":269,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/text-decoder/lib/utf8-decoder.js":{"offset":16160895,"length":4429,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/text-decoder/package.json":{"offset":16165324,"length":990,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/time-ordered-set/index.js":{"offset":16166314,"length":1444,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/time-ordered-set/package.json":{"offset":16167758,"length":666,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/timeout-refresh/browser.js":{"offset":16168424,"length":1098,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/timeout-refresh/index.js":{"offset":16169522,"length":184,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/timeout-refresh/node.js":{"offset":16169706,"length":928,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/timeout-refresh/package.json":{"offset":16170634,"length":619,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/udx-native/binding.js":{"offset":16171253,"length":90,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/udx-native/lib/ip.js":{"offset":16171343,"length":2204,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/udx-native/lib/network-interfaces.js":{"offset":16173547,"length":1341,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/udx-native/lib/socket.js":{"offset":16174888,"length":7557,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/udx-native/lib/stream.js":{"offset":16182445,"length":12706,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/udx-native/lib/udx.js":{"offset":16195151,"length":2868,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/udx-native/package.json":{"offset":16198019,"length":1615,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/unordered-set/index.js":{"offset":16199634,"length":677,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/unordered-set/package.json":{"offset":16200311,"length":654,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/unslab/index.js":{"offset":16200965,"length":913,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/unslab/package.json":{"offset":16201878,"length":613,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/which-runtime/index.js":{"offset":16202491,"length":1231,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/which-runtime/package.json":{"offset":16203722,"length":602,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/xache/index.js":{"offset":16204324,"length":2378,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/xache/package.json":{"offset":16206702,"length":584,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/z32/index.js":{"offset":16207286,"length":2654,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/node_modules/z32/package.json":{"offset":16209940,"length":701,"mode":420},"/node_modules/favela-web/node_modules/hyper-svc/package.json":{"offset":16210641,"length":1873,"mode":420},"/node_modules/favela-web/node_modules/hyperbee/index.js":{"offset":16212514,"length":46445,"mode":420},"/node_modules/favela-web/node_modules/hyperbee/iterators/diff.js":{"offset":16258959,"length":5358,"mode":420},"/node_modules/favela-web/node_modules/hyperbee/iterators/history.js":{"offset":16264317,"length":1631,"mode":420},"/node_modules/favela-web/node_modules/hyperbee/iterators/local.js":{"offset":16265948,"length":1170,"mode":420},"/node_modules/favela-web/node_modules/hyperbee/iterators/range.js":{"offset":16267118,"length":5869,"mode":420},"/node_modules/favela-web/node_modules/hyperbee/lib/extension.js":{"offset":16272987,"length":3488,"mode":420},"/node_modules/favela-web/node_modules/hyperbee/lib/messages.js":{"offset":16276475,"length":28162,"mode":420},"/node_modules/favela-web/node_modules/hyperbee/package.json":{"offset":16304637,"length":1585,"mode":420},"/node_modules/favela-web/node_modules/hypercore-crypto/index.js":{"offset":16306222,"length":5031,"mode":420},"/node_modules/favela-web/node_modules/hypercore-crypto/node_modules/compact-encoding/endian.js":{"offset":16311253,"length":105,"mode":420},"/node_modules/favela-web/node_modules/hypercore-crypto/node_modules/compact-encoding/index.js":{"offset":16311358,"length":26406,"mode":420},"/node_modules/favela-web/node_modules/hypercore-crypto/node_modules/compact-encoding/lexint.js":{"offset":16337764,"length":2851,"mode":420},"/node_modules/favela-web/node_modules/hypercore-crypto/node_modules/compact-encoding/package.json":{"offset":16340615,"length":866,"mode":420},"/node_modules/favela-web/node_modules/hypercore-crypto/node_modules/compact-encoding/raw.js":{"offset":16341481,"length":3977,"mode":420},"/node_modules/favela-web/node_modules/hypercore-crypto/package.json":{"offset":16345458,"length":1007,"mode":420},"/node_modules/favela-web/node_modules/hypercore-errors/index.js":{"offset":16346465,"length":4896,"mode":420},"/node_modules/favela-web/node_modules/hypercore-errors/package.json":{"offset":16351361,"length":688,"mode":420},"/node_modules/favela-web/node_modules/hypercore-id-encoding/index.js":{"offset":16352049,"length":923,"mode":420},"/node_modules/favela-web/node_modules/hypercore-id-encoding/package.json":{"offset":16352972,"length":799,"mode":420},"/node_modules/favela-web/node_modules/hypercore-storage/encoding/external.js":{"offset":16353771,"length":264,"mode":420},"/node_modules/favela-web/node_modules/hypercore-storage/encoding/spec/hyperschema/index.js":{"offset":16354035,"length":16796,"mode":420},"/node_modules/favela-web/node_modules/hypercore-storage/index.js":{"offset":16370831,"length":33493,"mode":420},"/node_modules/favela-web/node_modules/hypercore-storage/lib/block-dependency-stream.js":{"offset":16404324,"length":2557,"mode":420},"/node_modules/favela-web/node_modules/hypercore-storage/lib/close-error-stream.js":{"offset":16406881,"length":276,"mode":420},"/node_modules/favela-web/node_modules/hypercore-storage/lib/keys.js":{"offset":16407157,"length":8751,"mode":420},"/node_modules/favela-web/node_modules/hypercore-storage/lib/streams.js":{"offset":16415908,"length":5686,"mode":420},"/node_modules/favela-web/node_modules/hypercore-storage/lib/tx.js":{"offset":16421594,"length":11683,"mode":420},"/node_modules/favela-web/node_modules/hypercore-storage/lib/view.js":{"offset":16433277,"length":8379,"mode":420},"/node_modules/favela-web/node_modules/hypercore-storage/migrations/0/index.js":{"offset":16441656,"length":20125,"mode":420},"/node_modules/favela-web/node_modules/hypercore-storage/migrations/0/messages.js":{"offset":16461781,"length":26402,"mode":420},"/node_modules/favela-web/node_modules/hypercore-storage/migrations/1/index.js":{"offset":16488183,"length":1181,"mode":420},"/node_modules/favela-web/node_modules/hypercore-storage/node_modules/compact-encoding/endian.js":{"offset":16489364,"length":105,"mode":420},"/node_modules/favela-web/node_modules/hypercore-storage/node_modules/compact-encoding/index.js":{"offset":16489469,"length":26406,"mode":420},"/node_modules/favela-web/node_modules/hypercore-storage/node_modules/compact-encoding/lexint.js":{"offset":16515875,"length":2851,"mode":420},"/node_modules/favela-web/node_modules/hypercore-storage/node_modules/compact-encoding/package.json":{"offset":16518726,"length":866,"mode":420},"/node_modules/favela-web/node_modules/hypercore-storage/node_modules/compact-encoding/raw.js":{"offset":16519592,"length":3977,"mode":420},"/node_modules/favela-web/node_modules/hypercore-storage/package.json":{"offset":16523569,"length":1827,"mode":420},"/node_modules/favela-web/node_modules/hypercore/index.js":{"offset":16525396,"length":40241,"mode":420},"/node_modules/favela-web/node_modules/hypercore/lib/audit.js":{"offset":16565637,"length":3834,"mode":420},"/node_modules/favela-web/node_modules/hypercore/lib/bit-interlude.js":{"offset":16569471,"length":4257,"mode":420},"/node_modules/favela-web/node_modules/hypercore/lib/bitfield.js":{"offset":16573728,"length":12115,"mode":420},"/node_modules/favela-web/node_modules/hypercore/lib/caps.js":{"offset":16585843,"length":1537,"mode":420},"/node_modules/favela-web/node_modules/hypercore/lib/compat.js":{"offset":16587380,"length":477,"mode":420},"/node_modules/favela-web/node_modules/hypercore/lib/copy-prologue.js":{"offset":16587857,"length":5999,"mode":420},"/node_modules/favela-web/node_modules/hypercore/lib/core.js":{"offset":16593856,"length":28356,"mode":420},"/node_modules/favela-web/node_modules/hypercore/lib/default-encryption.js":{"offset":16622212,"length":3453,"mode":420},"/node_modules/favela-web/node_modules/hypercore/lib/download.js":{"offset":16625665,"length":1278,"mode":420},"/node_modules/favela-web/node_modules/hypercore/lib/feature-flags.js":{"offset":16626943,"length":38,"mode":420},"/node_modules/favela-web/node_modules/hypercore/lib/fully-remote-proof.js":{"offset":16626981,"length":3470,"mode":420},"/node_modules/favela-web/node_modules/hypercore/lib/hotswap-queue.js":{"offset":16630451,"length":1498,"mode":420},"/node_modules/favela-web/node_modules/hypercore/lib/info.js":{"offset":16631949,"length":1517,"mode":420},"/node_modules/favela-web/node_modules/hypercore/lib/inspect.js":{"offset":16633466,"length":1983,"mode":420},"/node_modules/favela-web/node_modules/hypercore/lib/mark-bitfield.js":{"offset":16635449,"length":2589,"mode":420},"/node_modules/favela-web/node_modules/hypercore/lib/merkle-tree.js":{"offset":16638038,"length":34353,"mode":420},"/node_modules/favela-web/node_modules/hypercore/lib/messages.js":{"offset":16672391,"length":28313,"mode":420},"/node_modules/favela-web/node_modules/hypercore/lib/multisig.js":{"offset":16700704,"length":2851,"mode":420},"/node_modules/favela-web/node_modules/hypercore/lib/mutex.js":{"offset":16703555,"length":1028,"mode":420},"/node_modules/favela-web/node_modules/hypercore/lib/receiver-queue.js":{"offset":16704583,"length":1413,"mode":420},"/node_modules/favela-web/node_modules/hypercore/lib/remote-bitfield.js":{"offset":16705996,"length":8124,"mode":420},"/node_modules/favela-web/node_modules/hypercore/lib/replicator.js":{"offset":16714120,"length":88908,"mode":420},"/node_modules/favela-web/node_modules/hypercore/lib/session-state.js":{"offset":16803028,"length":36297,"mode":420},"/node_modules/favela-web/node_modules/hypercore/lib/streams.js":{"offset":16839325,"length":3034,"mode":420},"/node_modules/favela-web/node_modules/hypercore/lib/verifier.js":{"offset":16842359,"length":9926,"mode":420},"/node_modules/favela-web/node_modules/hypercore/lib/wants.js":{"offset":16852285,"length":7204,"mode":420},"/node_modules/favela-web/node_modules/hypercore/node_modules/compact-encoding/endian.js":{"offset":16859489,"length":105,"mode":420},"/node_modules/favela-web/node_modules/hypercore/node_modules/compact-encoding/index.js":{"offset":16859594,"length":26406,"mode":420},"/node_modules/favela-web/node_modules/hypercore/node_modules/compact-encoding/lexint.js":{"offset":16886000,"length":2851,"mode":420},"/node_modules/favela-web/node_modules/hypercore/node_modules/compact-encoding/package.json":{"offset":16888851,"length":866,"mode":420},"/node_modules/favela-web/node_modules/hypercore/node_modules/compact-encoding/raw.js":{"offset":16889717,"length":3977,"mode":420},"/node_modules/favela-web/node_modules/hypercore/package.json":{"offset":16893694,"length":2196,"mode":420},"/node_modules/favela-web/node_modules/hyperdht-address/index.js":{"offset":16895890,"length":357,"mode":420},"/node_modules/favela-web/node_modules/hyperdht-address/node_modules/compact-encoding/endian.js":{"offset":16896247,"length":105,"mode":420},"/node_modules/favela-web/node_modules/hyperdht-address/node_modules/compact-encoding/index.js":{"offset":16896352,"length":26406,"mode":420},"/node_modules/favela-web/node_modules/hyperdht-address/node_modules/compact-encoding/lexint.js":{"offset":16922758,"length":2851,"mode":420},"/node_modules/favela-web/node_modules/hyperdht-address/node_modules/compact-encoding/package.json":{"offset":16925609,"length":866,"mode":420},"/node_modules/favela-web/node_modules/hyperdht-address/node_modules/compact-encoding/raw.js":{"offset":16926475,"length":3977,"mode":420},"/node_modules/favela-web/node_modules/hyperdht-address/package.json":{"offset":16930452,"length":1046,"mode":420},"/node_modules/favela-web/node_modules/hyperdht-address/spec/hyperschema/index.js":{"offset":16931498,"length":2106,"mode":420},"/node_modules/favela-web/node_modules/hyperdht/index.js":{"offset":16933604,"length":16589,"mode":420},"/node_modules/favela-web/node_modules/hyperdht/lib/announcer.js":{"offset":16950193,"length":7533,"mode":420},"/node_modules/favela-web/node_modules/hyperdht/lib/connect.js":{"offset":16957726,"length":25203,"mode":420},"/node_modules/favela-web/node_modules/hyperdht/lib/connection-pool.js":{"offset":16982929,"length":3050,"mode":420},"/node_modules/favela-web/node_modules/hyperdht/lib/constants.js":{"offset":16985979,"length":1178,"mode":420},"/node_modules/favela-web/node_modules/hyperdht/lib/crypto.js":{"offset":16987157,"length":632,"mode":420},"/node_modules/favela-web/node_modules/hyperdht/lib/encode.js":{"offset":16987789,"length":446,"mode":420},"/node_modules/favela-web/node_modules/hyperdht/lib/errors.js":{"offset":16988235,"length":3713,"mode":420},"/node_modules/favela-web/node_modules/hyperdht/lib/holepuncher.js":{"offset":16991948,"length":10003,"mode":420},"/node_modules/favela-web/node_modules/hyperdht/lib/messages.js":{"offset":17001951,"length":12057,"mode":420},"/node_modules/favela-web/node_modules/hyperdht/lib/nat.js":{"offset":17014008,"length":4714,"mode":420},"/node_modules/favela-web/node_modules/hyperdht/lib/noise-wrap.js":{"offset":17018722,"length":1669,"mode":420},"/node_modules/favela-web/node_modules/hyperdht/lib/persistent.js":{"offset":17020391,"length":8361,"mode":420},"/node_modules/favela-web/node_modules/hyperdht/lib/raw-stream-set.js":{"offset":17028752,"length":1511,"mode":420},"/node_modules/favela-web/node_modules/hyperdht/lib/relay-connection.js":{"offset":17030263,"length":2062,"mode":420},"/node_modules/favela-web/node_modules/hyperdht/lib/router.js":{"offset":17032325,"length":6978,"mode":420},"/node_modules/favela-web/node_modules/hyperdht/lib/secure-payload.js":{"offset":17039303,"length":1491,"mode":420},"/node_modules/favela-web/node_modules/hyperdht/lib/semaphore.js":{"offset":17040794,"length":1577,"mode":420},"/node_modules/favela-web/node_modules/hyperdht/lib/server.js":{"offset":17042371,"length":22065,"mode":420},"/node_modules/favela-web/node_modules/hyperdht/lib/sleeper.js":{"offset":17064436,"length":690,"mode":420},"/node_modules/favela-web/node_modules/hyperdht/lib/socket-pool.js":{"offset":17065126,"length":4343,"mode":420},"/node_modules/favela-web/node_modules/hyperdht/node_modules/compact-encoding/endian.js":{"offset":17069469,"length":105,"mode":420},"/node_modules/favela-web/node_modules/hyperdht/node_modules/compact-encoding/index.js":{"offset":17069574,"length":26406,"mode":420},"/node_modules/favela-web/node_modules/hyperdht/node_modules/compact-encoding/lexint.js":{"offset":17095980,"length":2851,"mode":420},"/node_modules/favela-web/node_modules/hyperdht/node_modules/compact-encoding/package.json":{"offset":17098831,"length":866,"mode":420},"/node_modules/favela-web/node_modules/hyperdht/node_modules/compact-encoding/raw.js":{"offset":17099697,"length":3977,"mode":420},"/node_modules/favela-web/node_modules/hyperdht/package.json":{"offset":17103674,"length":2007,"mode":420},"/node_modules/favela-web/node_modules/hyperschema/node_modules/compact-encoding/endian.js":{"offset":17105681,"length":105,"mode":420},"/node_modules/favela-web/node_modules/hyperschema/node_modules/compact-encoding/index.js":{"offset":17105786,"length":26406,"mode":420},"/node_modules/favela-web/node_modules/hyperschema/node_modules/compact-encoding/lexint.js":{"offset":17132192,"length":2851,"mode":420},"/node_modules/favela-web/node_modules/hyperschema/node_modules/compact-encoding/package.json":{"offset":17135043,"length":866,"mode":420},"/node_modules/favela-web/node_modules/hyperschema/node_modules/compact-encoding/raw.js":{"offset":17135909,"length":3977,"mode":420},"/node_modules/favela-web/node_modules/hyperschema/package.json":{"offset":17139886,"length":1555,"mode":420},"/node_modules/favela-web/node_modules/hyperschema/runtime.cjs":{"offset":17141441,"length":54,"mode":420},"/node_modules/favela-web/node_modules/hyperswarm/index.js":{"offset":17141495,"length":18589,"mode":420},"/node_modules/favela-web/node_modules/hyperswarm/lib/bulk-timer.js":{"offset":17160084,"length":728,"mode":420},"/node_modules/favela-web/node_modules/hyperswarm/lib/connection-set.js":{"offset":17160812,"length":823,"mode":420},"/node_modules/favela-web/node_modules/hyperswarm/lib/peer-discovery.js":{"offset":17161635,"length":9296,"mode":420},"/node_modules/favela-web/node_modules/hyperswarm/lib/peer-info.js":{"offset":17170931,"length":2688,"mode":420},"/node_modules/favela-web/node_modules/hyperswarm/lib/retry-timer.js":{"offset":17173619,"length":1889,"mode":420},"/node_modules/favela-web/node_modules/hyperswarm/package.json":{"offset":17175508,"length":1515,"mode":420},"/node_modules/favela-web/node_modules/index-encoder/index.js":{"offset":17177023,"length":10596,"mode":420},"/node_modules/favela-web/node_modules/index-encoder/package.json":{"offset":17187619,"length":928,"mode":420},"/node_modules/favela-web/node_modules/is-options/index.js":{"offset":17188547,"length":140,"mode":420},"/node_modules/favela-web/node_modules/is-options/package.json":{"offset":17188687,"length":605,"mode":420},"/node_modules/favela-web/node_modules/kademlia-routing-table/index.js":{"offset":17189292,"length":4145,"mode":420},"/node_modules/favela-web/node_modules/kademlia-routing-table/package.json":{"offset":17193437,"length":967,"mode":420},"/node_modules/favela-web/node_modules/multiformats/dist/src/bases/base.js":{"offset":17194404,"length":6266,"mode":420},"/node_modules/favela-web/node_modules/multiformats/dist/src/bases/base32.js":{"offset":17200670,"length":1443,"mode":420},"/node_modules/favela-web/node_modules/multiformats/dist/src/bases/base36.js":{"offset":17202113,"length":327,"mode":420},"/node_modules/favela-web/node_modules/multiformats/dist/src/bases/base58.js":{"offset":17202440,"length":379,"mode":420},"/node_modules/favela-web/node_modules/multiformats/dist/src/bytes.js":{"offset":17202819,"length":1246,"mode":420},"/node_modules/favela-web/node_modules/multiformats/dist/src/cid.js":{"offset":17204065,"length":13430,"mode":420},"/node_modules/favela-web/node_modules/multiformats/dist/src/hashes/digest.js":{"offset":17217495,"length":1915,"mode":420},"/node_modules/favela-web/node_modules/multiformats/dist/src/link/interface.js":{"offset":17219410,"length":48,"mode":420},"/node_modules/favela-web/node_modules/multiformats/dist/src/varint.js":{"offset":17219458,"length":398,"mode":420},"/node_modules/favela-web/node_modules/multiformats/dist/src/vendor/base-x.js":{"offset":17219856,"length":5458,"mode":420},"/node_modules/favela-web/node_modules/multiformats/dist/src/vendor/varint.js":{"offset":17225314,"length":2107,"mode":420},"/node_modules/favela-web/node_modules/multiformats/package.json":{"offset":17227421,"length":8176,"mode":420},"/node_modules/favela-web/node_modules/mutexify/index.js":{"offset":17235597,"length":536,"mode":420},"/node_modules/favela-web/node_modules/mutexify/package.json":{"offset":17236133,"length":679,"mode":420},"/node_modules/favela-web/node_modules/mutexify/promise.js":{"offset":17236812,"length":324,"mode":420},"/node_modules/favela-web/node_modules/nanoassert/index.js":{"offset":17237136,"length":438,"mode":420},"/node_modules/favela-web/node_modules/nanoassert/package.json":{"offset":17237574,"length":647,"mode":420},"/node_modules/favela-web/node_modules/nat-sampler/index.js":{"offset":17238221,"length":1550,"mode":420},"/node_modules/favela-web/node_modules/nat-sampler/package.json":{"offset":17239771,"length":608,"mode":420},"/node_modules/favela-web/node_modules/noise-curve-ed/index.js":{"offset":17240379,"length":1642,"mode":420},"/node_modules/favela-web/node_modules/noise-curve-ed/package.json":{"offset":17242021,"length":808,"mode":420},"/node_modules/favela-web/node_modules/noise-handshake/cipher.js":{"offset":17242829,"length":2817,"mode":420},"/node_modules/favela-web/node_modules/noise-handshake/dh.js":{"offset":17245646,"length":1439,"mode":420},"/node_modules/favela-web/node_modules/noise-handshake/hkdf.js":{"offset":17247085,"length":1092,"mode":420},"/node_modules/favela-web/node_modules/noise-handshake/hmac.js":{"offset":17248177,"length":1273,"mode":420},"/node_modules/favela-web/node_modules/noise-handshake/noise.js":{"offset":17249450,"length":6437,"mode":420},"/node_modules/favela-web/node_modules/noise-handshake/package.json":{"offset":17255887,"length":638,"mode":420},"/node_modules/favela-web/node_modules/noise-handshake/symmetric-state.js":{"offset":17256525,"length":2206,"mode":420},"/node_modules/favela-web/node_modules/protocol-buffers-encodings/index.js":{"offset":17258731,"length":6489,"mode":420},"/node_modules/favela-web/node_modules/protocol-buffers-encodings/package.json":{"offset":17265220,"length":719,"mode":420},"/node_modules/favela-web/node_modules/protomux-rpc/index.js":{"offset":17265939,"length":9087,"mode":420},"/node_modules/favela-web/node_modules/protomux-rpc/lib/errors.js":{"offset":17275026,"length":1273,"mode":420},"/node_modules/favela-web/node_modules/protomux-rpc/node_modules/compact-encoding/endian.js":{"offset":17276299,"length":105,"mode":420},"/node_modules/favela-web/node_modules/protomux-rpc/node_modules/compact-encoding/index.js":{"offset":17276404,"length":26406,"mode":420},"/node_modules/favela-web/node_modules/protomux-rpc/node_modules/compact-encoding/lexint.js":{"offset":17302810,"length":2851,"mode":420},"/node_modules/favela-web/node_modules/protomux-rpc/node_modules/compact-encoding/package.json":{"offset":17305661,"length":866,"mode":420},"/node_modules/favela-web/node_modules/protomux-rpc/node_modules/compact-encoding/raw.js":{"offset":17306527,"length":3977,"mode":420},"/node_modules/favela-web/node_modules/protomux-rpc/package.json":{"offset":17310504,"length":1188,"mode":420},"/node_modules/favela-web/node_modules/protomux/index.js":{"offset":17311692,"length":19741,"mode":420},"/node_modules/favela-web/node_modules/protomux/node_modules/compact-encoding/endian.js":{"offset":17331433,"length":105,"mode":420},"/node_modules/favela-web/node_modules/protomux/node_modules/compact-encoding/index.js":{"offset":17331538,"length":26406,"mode":420},"/node_modules/favela-web/node_modules/protomux/node_modules/compact-encoding/lexint.js":{"offset":17357944,"length":2851,"mode":420},"/node_modules/favela-web/node_modules/protomux/node_modules/compact-encoding/package.json":{"offset":17360795,"length":866,"mode":420},"/node_modules/favela-web/node_modules/protomux/node_modules/compact-encoding/raw.js":{"offset":17361661,"length":3977,"mode":420},"/node_modules/favela-web/node_modules/protomux/package.json":{"offset":17365638,"length":1059,"mode":420},"/node_modules/favela-web/node_modules/queue-tick/package.json":{"offset":17366697,"length":669,"mode":420},"/node_modules/favela-web/node_modules/queue-tick/process-next-tick.js":{"offset":17367366,"length":160,"mode":420},"/node_modules/favela-web/node_modules/queue-tick/queue-microtask.js":{"offset":17367526,"length":108,"mode":420},"/node_modules/favela-web/node_modules/quickbit-native/binding.js":{"offset":17367634,"length":90,"mode":420},"/node_modules/favela-web/node_modules/quickbit-native/index.js":{"offset":17367724,"length":4683,"mode":420},"/node_modules/favela-web/node_modules/quickbit-native/package.json":{"offset":17372407,"length":1104,"mode":420},"/node_modules/favela-web/node_modules/quickbit-universal/fallback.js":{"offset":17373511,"length":10204,"mode":420},"/node_modules/favela-web/node_modules/quickbit-universal/index.js":{"offset":17383715,"length":442,"mode":420},"/node_modules/favela-web/node_modules/quickbit-universal/package.json":{"offset":17384157,"length":908,"mode":420},"/node_modules/favela-web/node_modules/rache/index.js":{"offset":17385065,"length":2463,"mode":420},"/node_modules/favela-web/node_modules/rache/package.json":{"offset":17387528,"length":602,"mode":420},"/node_modules/favela-web/node_modules/random-array-iterator/index.js":{"offset":17388130,"length":1001,"mode":420},"/node_modules/favela-web/node_modules/random-array-iterator/package.json":{"offset":17389131,"length":700,"mode":420},"/node_modules/favela-web/node_modules/ready-resource/index.js":{"offset":17389831,"length":1091,"mode":420},"/node_modules/favela-web/node_modules/ready-resource/package.json":{"offset":17390922,"length":812,"mode":420},"/node_modules/favela-web/node_modules/record-cache/index.js":{"offset":17391734,"length":3668,"mode":420},"/node_modules/favela-web/node_modules/record-cache/package.json":{"offset":17395402,"length":612,"mode":420},"/node_modules/favela-web/node_modules/refcounter/index.js":{"offset":17396014,"length":611,"mode":420},"/node_modules/favela-web/node_modules/refcounter/package.json":{"offset":17396625,"length":451,"mode":420},"/node_modules/favela-web/node_modules/require-addon/lib/bare.js":{"offset":17397076,"length":45,"mode":420},"/node_modules/favela-web/node_modules/require-addon/package.json":{"offset":17397121,"length":1449,"mode":420},"/node_modules/favela-web/node_modules/resolve-reject-promise/index.js":{"offset":17398570,"length":443,"mode":420},"/node_modules/favela-web/node_modules/resolve-reject-promise/package.json":{"offset":17399013,"length":581,"mode":420},"/node_modules/favela-web/node_modules/resource-on-exit/index.js":{"offset":17399594,"length":361,"mode":420},"/node_modules/favela-web/node_modules/resource-on-exit/package.json":{"offset":17399955,"length":496,"mode":420},"/node_modules/favela-web/node_modules/rocksdb-native/binding.js":{"offset":17400451,"length":90,"mode":420},"/node_modules/favela-web/node_modules/rocksdb-native/index.js":{"offset":17400541,"length":5304,"mode":420},"/node_modules/favela-web/node_modules/rocksdb-native/lib/batch.js":{"offset":17405845,"length":9605,"mode":420},"/node_modules/favela-web/node_modules/rocksdb-native/lib/column-family.js":{"offset":17415450,"length":2930,"mode":420},"/node_modules/favela-web/node_modules/rocksdb-native/lib/constants.js":{"offset":17418380,"length":621,"mode":420},"/node_modules/favela-web/node_modules/rocksdb-native/lib/filter-policy.js":{"offset":17419001,"length":437,"mode":420},"/node_modules/favela-web/node_modules/rocksdb-native/lib/iterator.js":{"offset":17419438,"length":4311,"mode":420},"/node_modules/favela-web/node_modules/rocksdb-native/lib/snapshot.js":{"offset":17423749,"length":503,"mode":420},"/node_modules/favela-web/node_modules/rocksdb-native/lib/state.js":{"offset":17424252,"length":13115,"mode":420},"/node_modules/favela-web/node_modules/rocksdb-native/node_modules/compact-encoding/endian.js":{"offset":17437367,"length":105,"mode":420},"/node_modules/favela-web/node_modules/rocksdb-native/node_modules/compact-encoding/index.js":{"offset":17437472,"length":26406,"mode":420},"/node_modules/favela-web/node_modules/rocksdb-native/node_modules/compact-encoding/lexint.js":{"offset":17463878,"length":2851,"mode":420},"/node_modules/favela-web/node_modules/rocksdb-native/node_modules/compact-encoding/package.json":{"offset":17466729,"length":866,"mode":420},"/node_modules/favela-web/node_modules/rocksdb-native/node_modules/compact-encoding/raw.js":{"offset":17467595,"length":3977,"mode":420},"/node_modules/favela-web/node_modules/rocksdb-native/package.json":{"offset":17471572,"length":1863,"mode":420},"/node_modules/favela-web/node_modules/safety-catch/index.js":{"offset":17473435,"length":543,"mode":420},"/node_modules/favela-web/node_modules/safety-catch/package.json":{"offset":17473978,"length":547,"mode":420},"/node_modules/favela-web/node_modules/scope-lock/index.js":{"offset":17474525,"length":1821,"mode":420},"/node_modules/favela-web/node_modules/scope-lock/package.json":{"offset":17476346,"length":611,"mode":420},"/node_modules/favela-web/node_modules/shuffled-priority-queue/index.js":{"offset":17476957,"length":2607,"mode":420},"/node_modules/favela-web/node_modules/shuffled-priority-queue/package.json":{"offset":17479564,"length":691,"mode":420},"/node_modules/favela-web/node_modules/signal-promise/index.js":{"offset":17480255,"length":1252,"mode":420},"/node_modules/favela-web/node_modules/signal-promise/package.json":{"offset":17481507,"length":503,"mode":420},"/node_modules/favela-web/node_modules/signed-varint/index.js":{"offset":17482010,"length":435,"mode":420},"/node_modules/favela-web/node_modules/signed-varint/package.json":{"offset":17482445,"length":523,"mode":420},"/node_modules/favela-web/node_modules/simdle-native/binding.js":{"offset":17482968,"length":90,"mode":420},"/node_modules/favela-web/node_modules/simdle-native/index.js":{"offset":17483058,"length":3474,"mode":420},"/node_modules/favela-web/node_modules/simdle-native/package.json":{"offset":17486532,"length":1115,"mode":420},"/node_modules/favela-web/node_modules/simdle-universal/fallback.js":{"offset":17487647,"length":5137,"mode":420},"/node_modules/favela-web/node_modules/simdle-universal/index.js":{"offset":17492784,"length":103,"mode":420},"/node_modules/favela-web/node_modules/simdle-universal/package.json":{"offset":17492887,"length":879,"mode":420},"/node_modules/favela-web/node_modules/simdle-universal/scalar.js":{"offset":17493766,"length":469,"mode":420},"/node_modules/favela-web/node_modules/sodium-native/binding.js":{"offset":17494235,"length":89,"mode":420},"/node_modules/favela-web/node_modules/sodium-native/index.js":{"offset":17494324,"length":107894,"mode":420},"/node_modules/favela-web/node_modules/sodium-native/package.json":{"offset":17602218,"length":1478,"mode":420},"/node_modules/favela-web/node_modules/sodium-secretstream/index.js":{"offset":17603696,"length":2257,"mode":420},"/node_modules/favela-web/node_modules/sodium-secretstream/package.json":{"offset":17605953,"length":657,"mode":420},"/node_modules/favela-web/node_modules/sodium-universal/index.js":{"offset":17606610,"length":42,"mode":420},"/node_modules/favela-web/node_modules/sodium-universal/package.json":{"offset":17606652,"length":1217,"mode":420},"/node_modules/favela-web/node_modules/streamx/index.js":{"offset":17607869,"length":34248,"mode":420},"/node_modules/favela-web/node_modules/streamx/lib/errors.js":{"offset":17642117,"length":1096,"mode":420},"/node_modules/favela-web/node_modules/streamx/package.json":{"offset":17643213,"length":1225,"mode":420},"/node_modules/favela-web/node_modules/teex/index.js":{"offset":17644438,"length":1107,"mode":420},"/node_modules/favela-web/node_modules/teex/package.json":{"offset":17645545,"length":608,"mode":420},"/node_modules/favela-web/node_modules/text-decoder/index.js":{"offset":17646153,"length":1371,"mode":420},"/node_modules/favela-web/node_modules/text-decoder/lib/pass-through-decoder.js":{"offset":17647524,"length":269,"mode":420},"/node_modules/favela-web/node_modules/text-decoder/lib/utf8-decoder.js":{"offset":17647793,"length":4429,"mode":420},"/node_modules/favela-web/node_modules/text-decoder/package.json":{"offset":17652222,"length":990,"mode":420},"/node_modules/favela-web/node_modules/time-ordered-set/index.js":{"offset":17653212,"length":1444,"mode":420},"/node_modules/favela-web/node_modules/time-ordered-set/package.json":{"offset":17654656,"length":666,"mode":420},"/node_modules/favela-web/node_modules/timeout-refresh/browser.js":{"offset":17655322,"length":1098,"mode":420},"/node_modules/favela-web/node_modules/timeout-refresh/index.js":{"offset":17656420,"length":184,"mode":420},"/node_modules/favela-web/node_modules/timeout-refresh/node.js":{"offset":17656604,"length":928,"mode":420},"/node_modules/favela-web/node_modules/timeout-refresh/package.json":{"offset":17657532,"length":619,"mode":420},"/node_modules/favela-web/node_modules/udx-native/binding.js":{"offset":17658151,"length":90,"mode":420},"/node_modules/favela-web/node_modules/udx-native/lib/ip.js":{"offset":17658241,"length":2204,"mode":420},"/node_modules/favela-web/node_modules/udx-native/lib/network-interfaces.js":{"offset":17660445,"length":1341,"mode":420},"/node_modules/favela-web/node_modules/udx-native/lib/socket.js":{"offset":17661786,"length":7557,"mode":420},"/node_modules/favela-web/node_modules/udx-native/lib/stream.js":{"offset":17669343,"length":13050,"mode":420},"/node_modules/favela-web/node_modules/udx-native/lib/udx.js":{"offset":17682393,"length":2868,"mode":420},"/node_modules/favela-web/node_modules/udx-native/package.json":{"offset":17685261,"length":1665,"mode":420},"/node_modules/favela-web/node_modules/unordered-set/index.js":{"offset":17686926,"length":677,"mode":420},"/node_modules/favela-web/node_modules/unordered-set/package.json":{"offset":17687603,"length":654,"mode":420},"/node_modules/favela-web/node_modules/unslab/index.js":{"offset":17688257,"length":913,"mode":420},"/node_modules/favela-web/node_modules/unslab/package.json":{"offset":17689170,"length":613,"mode":420},"/node_modules/favela-web/node_modules/varint/decode.js":{"offset":17689783,"length":508,"mode":420},"/node_modules/favela-web/node_modules/varint/encode.js":{"offset":17690291,"length":452,"mode":420},"/node_modules/favela-web/node_modules/varint/index.js":{"offset":17690743,"length":134,"mode":420},"/node_modules/favela-web/node_modules/varint/length.js":{"offset":17690877,"length":471,"mode":420},"/node_modules/favela-web/node_modules/varint/package.json":{"offset":17691348,"length":511,"mode":420},"/node_modules/favela-web/node_modules/which-runtime/index.js":{"offset":17691859,"length":1469,"mode":420},"/node_modules/favela-web/node_modules/which-runtime/package.json":{"offset":17693328,"length":863,"mode":420},"/node_modules/favela-web/node_modules/xache/index.js":{"offset":17694191,"length":2378,"mode":420},"/node_modules/favela-web/node_modules/xache/package.json":{"offset":17696569,"length":584,"mode":420},"/node_modules/favela-web/node_modules/z32/index.js":{"offset":17697153,"length":2654,"mode":420},"/node_modules/favela-web/node_modules/z32/package.json":{"offset":17699807,"length":701,"mode":420},"/node_modules/favela-web/package.json":{"offset":17700508,"length":4881,"mode":420},"/node_modules/favela-web/web/static-assets.js":{"offset":17705389,"length":98056,"mode":420},"/node_modules/hyper-overlay/lib/tree.js":{"offset":17803445,"length":14077,"mode":420},"/node_modules/hyper-overlay/node_modules/b4a/index.js":{"offset":17817522,"length":4054,"mode":420},"/node_modules/hyper-overlay/node_modules/b4a/package.json":{"offset":17821576,"length":1245,"mode":420},"/node_modules/hyper-overlay/node_modules/bare-ansi-escapes/index.js":{"offset":17822821,"length":2255,"mode":420},"/node_modules/hyper-overlay/node_modules/bare-ansi-escapes/package.json":{"offset":17825076,"length":1178,"mode":420},"/node_modules/hyper-overlay/node_modules/bare-assert/index.js":{"offset":17826254,"length":2192,"mode":420},"/node_modules/hyper-overlay/node_modules/bare-assert/package.json":{"offset":17828446,"length":835,"mode":420},"/node_modules/hyper-overlay/node_modules/bare-events/index.js":{"offset":17829281,"length":8307,"mode":420},"/node_modules/hyper-overlay/node_modules/bare-events/lib/errors.js":{"offset":17837588,"length":671,"mode":420},"/node_modules/hyper-overlay/node_modules/bare-events/package.json":{"offset":17838259,"length":1504,"mode":420},"/node_modules/hyper-overlay/node_modules/bare-fs/binding.js":{"offset":17839763,"length":33,"mode":420},"/node_modules/hyper-overlay/node_modules/bare-fs/index.js":{"offset":17839796,"length":58907,"mode":420},"/node_modules/hyper-overlay/node_modules/bare-fs/lib/constants.js":{"offset":17898703,"length":1494,"mode":420},"/node_modules/hyper-overlay/node_modules/bare-fs/lib/errors.js":{"offset":17900197,"length":1163,"mode":420},"/node_modules/hyper-overlay/node_modules/bare-fs/package.json":{"offset":17901360,"length":1654,"mode":420},"/node_modules/hyper-overlay/node_modules/bare-fs/promises.js":{"offset":17903014,"length":2401,"mode":420},"/node_modules/hyper-overlay/node_modules/bare-inspect/binding.js":{"offset":17905415,"length":33,"mode":420},"/node_modules/hyper-overlay/node_modules/bare-inspect/index.js":{"offset":17905448,"length":23856,"mode":420},"/node_modules/hyper-overlay/node_modules/bare-inspect/package.json":{"offset":17929304,"length":1041,"mode":420},"/node_modules/hyper-overlay/node_modules/bare-os/binding.js":{"offset":17930345,"length":33,"mode":420},"/node_modules/hyper-overlay/node_modules/bare-os/index.js":{"offset":17930378,"length":3224,"mode":420},"/node_modules/hyper-overlay/node_modules/bare-os/lib/constants.js":{"offset":17933602,"length":143,"mode":420},"/node_modules/hyper-overlay/node_modules/bare-os/lib/errors.js":{"offset":17933745,"length":453,"mode":420},"/node_modules/hyper-overlay/node_modules/bare-os/package.json":{"offset":17934198,"length":1257,"mode":420},"/node_modules/hyper-overlay/node_modules/bare-path/index.js":{"offset":17935455,"length":287,"mode":420},"/node_modules/hyper-overlay/node_modules/bare-path/lib/constants.js":{"offset":17935742,"length":247,"mode":420},"/node_modules/hyper-overlay/node_modules/bare-path/lib/posix.js":{"offset":17935989,"length":6005,"mode":420},"/node_modules/hyper-overlay/node_modules/bare-path/lib/shared.js":{"offset":17941994,"length":1926,"mode":420},"/node_modules/hyper-overlay/node_modules/bare-path/lib/win32.js":{"offset":17943920,"length":13591,"mode":420},"/node_modules/hyper-overlay/node_modules/bare-path/package.json":{"offset":17957511,"length":1036,"mode":420},"/node_modules/hyper-overlay/node_modules/bare-stream/index.js":{"offset":17958547,"length":10904,"mode":420},"/node_modules/hyper-overlay/node_modules/bare-stream/package.json":{"offset":17969451,"length":1676,"mode":420},"/node_modules/hyper-overlay/node_modules/bare-stream/web.js":{"offset":17971127,"length":13980,"mode":420},"/node_modules/hyper-overlay/node_modules/bare-type/binding.js":{"offset":17985107,"length":33,"mode":420},"/node_modules/hyper-overlay/node_modules/bare-type/index.js":{"offset":17985140,"length":4566,"mode":420},"/node_modules/hyper-overlay/node_modules/bare-type/package.json":{"offset":17989706,"length":938,"mode":420},"/node_modules/hyper-overlay/node_modules/bare-url/binding.js":{"offset":17990644,"length":33,"mode":420},"/node_modules/hyper-overlay/node_modules/bare-url/index.js":{"offset":17990677,"length":9449,"mode":420},"/node_modules/hyper-overlay/node_modules/bare-url/lib/errors.js":{"offset":18000126,"length":778,"mode":420},"/node_modules/hyper-overlay/node_modules/bare-url/lib/url-search-params.js":{"offset":18000904,"length":4331,"mode":420},"/node_modules/hyper-overlay/node_modules/bare-url/package.json":{"offset":18005235,"length":1219,"mode":420},"/node_modules/hyper-overlay/node_modules/compact-encoding/endian.js":{"offset":18006454,"length":105,"mode":420},"/node_modules/hyper-overlay/node_modules/compact-encoding/index.js":{"offset":18006559,"length":26135,"mode":420},"/node_modules/hyper-overlay/node_modules/compact-encoding/lexint.js":{"offset":18032694,"length":2851,"mode":420},"/node_modules/hyper-overlay/node_modules/compact-encoding/package.json":{"offset":18035545,"length":866,"mode":420},"/node_modules/hyper-overlay/node_modules/compact-encoding/raw.js":{"offset":18036411,"length":3977,"mode":420},"/node_modules/hyper-overlay/node_modules/events-universal/bare.js":{"offset":18040388,"length":40,"mode":420},"/node_modules/hyper-overlay/node_modules/events-universal/package.json":{"offset":18040428,"length":908,"mode":420},"/node_modules/hyper-overlay/node_modules/fast-fifo/fixed-size.js":{"offset":18041336,"length":875,"mode":420},"/node_modules/hyper-overlay/node_modules/fast-fifo/index.js":{"offset":18042211,"length":972,"mode":420},"/node_modules/hyper-overlay/node_modules/fast-fifo/package.json":{"offset":18043183,"length":682,"mode":420},"/node_modules/hyper-overlay/node_modules/hypercore-crypto/index.js":{"offset":18043865,"length":5031,"mode":420},"/node_modules/hyper-overlay/node_modules/hypercore-crypto/package.json":{"offset":18048896,"length":1007,"mode":420},"/node_modules/hyper-overlay/node_modules/require-addon/lib/bare.js":{"offset":18049903,"length":45,"mode":420},"/node_modules/hyper-overlay/node_modules/require-addon/package.json":{"offset":18049948,"length":1449,"mode":420},"/node_modules/hyper-overlay/node_modules/sodium-native/binding.js":{"offset":18051397,"length":89,"mode":420},"/node_modules/hyper-overlay/node_modules/sodium-native/index.js":{"offset":18051486,"length":107894,"mode":420},"/node_modules/hyper-overlay/node_modules/sodium-native/package.json":{"offset":18159380,"length":1478,"mode":420},"/node_modules/hyper-overlay/node_modules/sodium-universal/index.js":{"offset":18160858,"length":42,"mode":420},"/node_modules/hyper-overlay/node_modules/sodium-universal/package.json":{"offset":18160900,"length":1217,"mode":420},"/node_modules/hyper-overlay/node_modules/streamx/index.js":{"offset":18162117,"length":34248,"mode":420},"/node_modules/hyper-overlay/node_modules/streamx/lib/errors.js":{"offset":18196365,"length":1096,"mode":420},"/node_modules/hyper-overlay/node_modules/streamx/package.json":{"offset":18197461,"length":1225,"mode":420},"/node_modules/hyper-overlay/node_modules/teex/index.js":{"offset":18198686,"length":1107,"mode":420},"/node_modules/hyper-overlay/node_modules/teex/package.json":{"offset":18199793,"length":608,"mode":420},"/node_modules/hyper-overlay/node_modules/text-decoder/index.js":{"offset":18200401,"length":1371,"mode":420},"/node_modules/hyper-overlay/node_modules/text-decoder/lib/pass-through-decoder.js":{"offset":18201772,"length":269,"mode":420},"/node_modules/hyper-overlay/node_modules/text-decoder/lib/utf8-decoder.js":{"offset":18202041,"length":4429,"mode":420},"/node_modules/hyper-overlay/node_modules/text-decoder/package.json":{"offset":18206470,"length":990,"mode":420},"/node_modules/hyper-overlay/node_modules/which-runtime/index.js":{"offset":18207460,"length":1469,"mode":420},"/node_modules/hyper-overlay/node_modules/which-runtime/package.json":{"offset":18208929,"length":863,"mode":420},"/node_modules/hyper-overlay/package.json":{"offset":18209792,"length":2132,"mode":420},"/node_modules/hyper-proto-peer/lib/adopt.js":{"offset":18211924,"length":6797,"mode":420},"/node_modules/hyper-proto-peer/lib/config.js":{"offset":18218721,"length":7290,"mode":420},"/node_modules/hyper-proto-peer/lib/conflict-watch.js":{"offset":18226011,"length":6096,"mode":420},"/node_modules/hyper-proto-peer/lib/coowner.js":{"offset":18232107,"length":15305,"mode":420},"/node_modules/hyper-proto-peer/lib/device-node.js":{"offset":18247412,"length":69854,"mode":420},"/node_modules/hyper-proto-peer/lib/dual-blob-store.js":{"offset":18317266,"length":3360,"mode":420},"/node_modules/hyper-proto-peer/lib/hosting-cli.js":{"offset":18320626,"length":9782,"mode":420},"/node_modules/hyper-proto-peer/lib/mint.js":{"offset":18330408,"length":10256,"mode":420},"/node_modules/hyper-proto-peer/lib/reconcile-retry.js":{"offset":18340664,"length":3109,"mode":420},"/node_modules/hyper-proto-peer/lib/serve-device-uds.js":{"offset":18343773,"length":13689,"mode":420},"/node_modules/hyper-proto-peer/lib/serve-device.js":{"offset":18357462,"length":13525,"mode":420},"/node_modules/hyper-proto-peer/lib/sessions.js":{"offset":18370987,"length":2860,"mode":420},"/node_modules/hyper-proto-peer/lib/swarm-device.js":{"offset":18373847,"length":63405,"mode":420},"/node_modules/hyper-proto-peer/lib/swarm-keypair.js":{"offset":18437252,"length":2344,"mode":420},"/node_modules/hyper-proto-peer/node_modules/@hyperswarm/secret-stream/index.js":{"offset":18439596,"length":16722,"mode":420},"/node_modules/hyper-proto-peer/node_modules/@hyperswarm/secret-stream/lib/bridge.js":{"offset":18456318,"length":1273,"mode":420},"/node_modules/hyper-proto-peer/node_modules/@hyperswarm/secret-stream/lib/handshake.js":{"offset":18457591,"length":1950,"mode":420},"/node_modules/hyper-proto-peer/node_modules/@hyperswarm/secret-stream/package.json":{"offset":18459541,"length":1132,"mode":420},"/node_modules/hyper-proto-peer/node_modules/@ipld/dag-cbor/package.json":{"offset":18460673,"length":3961,"mode":420},"/node_modules/hyper-proto-peer/node_modules/@ipld/dag-cbor/src/index.js":{"offset":18464634,"length":4040,"mode":420},"/node_modules/hyper-proto-peer/node_modules/adaptive-timeout/index.js":{"offset":18468674,"length":2424,"mode":420},"/node_modules/hyper-proto-peer/node_modules/adaptive-timeout/package.json":{"offset":18471098,"length":972,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/lib/atproto-identity.js":{"offset":18472070,"length":12646,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/lib/auth.js":{"offset":18484716,"length":6575,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/lib/device-chain.js":{"offset":18491291,"length":4232,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/lib/did-key.js":{"offset":18495523,"length":2104,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/lib/did-plc.js":{"offset":18497627,"length":2424,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/lib/discovery.js":{"offset":18500051,"length":1010,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/lib/hosting.js":{"offset":18501061,"length":7965,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/lib/plc-directory.js":{"offset":18509026,"length":9458,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/lib/vault.js":{"offset":18518484,"length":7529,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@ipld/dag-cbor/package.json":{"offset":18526013,"length":3961,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@ipld/dag-cbor/src/index.js":{"offset":18529974,"length":4040,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/curves/esm/_shortw_utils.js":{"offset":18534014,"length":589,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/curves/esm/abstract/curve.js":{"offset":18534603,"length":18539,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/curves/esm/abstract/hash-to-curve.js":{"offset":18553142,"length":8097,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/curves/esm/abstract/modular.js":{"offset":18561239,"length":21647,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/curves/esm/abstract/weierstrass.js":{"offset":18582886,"length":58901,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/curves/esm/nist.js":{"offset":18641787,"length":6148,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/curves/esm/p256.js":{"offset":18647935,"length":769,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/curves/esm/package.json":{"offset":18648704,"length":47,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/curves/esm/secp256k1.js":{"offset":18648751,"length":12507,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/curves/esm/utils.js":{"offset":18661258,"length":12067,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/hashes/esm/_md.js":{"offset":18673325,"length":6192,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/hashes/esm/_u64.js":{"offset":18679517,"length":3081,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/hashes/esm/crypto.js":{"offset":18682598,"length":146,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/hashes/esm/hmac.js":{"offset":18682744,"length":2962,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/hashes/esm/legacy.js":{"offset":18685706,"length":9872,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/hashes/esm/package.json":{"offset":18695578,"length":147,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/hashes/esm/pbkdf2.js":{"offset":18695725,"length":3867,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/hashes/esm/scrypt.js":{"offset":18699592,"length":10103,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/hashes/esm/sha2.js":{"offset":18709695,"length":16832,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@noble/hashes/esm/utils.js":{"offset":18726527,"length":10538,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@scure/base/lib/esm/index.js":{"offset":18737065,"length":24662,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@scure/base/lib/esm/package.json":{"offset":18761727,"length":43,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@scure/bip32/lib/esm/index.js":{"offset":18761770,"length":10475,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@scure/bip32/lib/esm/package.json":{"offset":18772245,"length":46,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@scure/bip39/esm/index.js":{"offset":18772291,"length":6595,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/@scure/bip39/esm/package.json":{"offset":18778886,"length":22,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/b4a/index.js":{"offset":18778908,"length":4054,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/b4a/package.json":{"offset":18782962,"length":1245,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-ansi-escapes/index.js":{"offset":18784207,"length":2255,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-ansi-escapes/package.json":{"offset":18786462,"length":1178,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-assert/index.js":{"offset":18787640,"length":2192,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-assert/package.json":{"offset":18789832,"length":835,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-inspect/binding.js":{"offset":18790667,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-inspect/index.js":{"offset":18790700,"length":23856,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-inspect/package.json":{"offset":18814556,"length":1041,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-type/binding.js":{"offset":18815597,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-type/index.js":{"offset":18815630,"length":4566,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bare-type/package.json":{"offset":18820196,"length":938,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/index.js":{"offset":18821134,"length":4554,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json":{"offset":18825688,"length":789,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/chinese_simplified.json":{"offset":18826477,"length":12289,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/chinese_traditional.json":{"offset":18838766,"length":12289,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/czech.json":{"offset":18851055,"length":19042,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/english.json":{"offset":18870097,"length":17213,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/french.json":{"offset":18887310,"length":20874,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/index.js":{"offset":18908184,"length":1406,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/italian.json":{"offset":18909590,"length":20130,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/japanese.json":{"offset":18929720,"length":30520,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/korean.json":{"offset":18960240,"length":41929,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/lookup.json":{"offset":19002169,"length":592224,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/portuguese.json":{"offset":19594393,"length":19768,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/russian.json":{"offset":19614161,"length":30635,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/spanish.json":{"offset":19644796,"length":18093,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/turkish.json":{"offset":19662889,"length":19421,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/cborg.js":{"offset":19682310,"length":944,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/0uint.js":{"offset":19683254,"length":6580,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/1negint.js":{"offset":19689834,"length":2980,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/2bytes.js":{"offset":19692814,"length":3451,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/3string.js":{"offset":19696265,"length":3340,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/4array.js":{"offset":19699605,"length":2944,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/5map.js":{"offset":19702549,"length":2917,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/6tag.js":{"offset":19705466,"length":1957,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/7float.js":{"offset":19707423,"length":8633,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/bl.js":{"offset":19716056,"length":5316,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/byte-utils.js":{"offset":19721372,"length":8172,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/common.js":{"offset":19729544,"length":598,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/decode.js":{"offset":19730142,"length":9008,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/encode.js":{"offset":19739150,"length":21407,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/is.js":{"offset":19760557,"length":2061,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/jump.js":{"offset":19762618,"length":7859,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/tagged.js":{"offset":19770477,"length":2821,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/lib/token.js":{"offset":19773298,"length":2019,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/cborg/package.json":{"offset":19775317,"length":4241,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/compact-encoding/endian.js":{"offset":19779558,"length":105,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/compact-encoding/index.js":{"offset":19779663,"length":26406,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/compact-encoding/lexint.js":{"offset":19806069,"length":2851,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/compact-encoding/package.json":{"offset":19808920,"length":866,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/compact-encoding/raw.js":{"offset":19809786,"length":3977,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/hypercore-crypto/index.js":{"offset":19813763,"length":5031,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/hypercore-crypto/package.json":{"offset":19818794,"length":1007,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/keet-identity-key/index.js":{"offset":19819801,"length":6320,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/keet-identity-key/lib/crypto.js":{"offset":19826121,"length":552,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/keet-identity-key/lib/encoding.js":{"offset":19826673,"length":3695,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/keet-identity-key/lib/keychain.js":{"offset":19830368,"length":3080,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/keet-identity-key/package.json":{"offset":19833448,"length":887,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/multiformats/dist/src/bases/base.js":{"offset":19834335,"length":6266,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/multiformats/dist/src/bases/base32.js":{"offset":19840601,"length":1443,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/multiformats/dist/src/bases/base36.js":{"offset":19842044,"length":327,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/multiformats/dist/src/bases/base58.js":{"offset":19842371,"length":379,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/multiformats/dist/src/bases/base64.js":{"offset":19842750,"length":793,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/multiformats/dist/src/bytes.js":{"offset":19843543,"length":1246,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/multiformats/dist/src/cid.js":{"offset":19844789,"length":13430,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/multiformats/dist/src/hashes/digest.js":{"offset":19858219,"length":1915,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/multiformats/dist/src/link/interface.js":{"offset":19860134,"length":48,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/multiformats/dist/src/varint.js":{"offset":19860182,"length":398,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/multiformats/dist/src/vendor/base-x.js":{"offset":19860580,"length":5458,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/multiformats/dist/src/vendor/varint.js":{"offset":19866038,"length":2107,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/multiformats/package.json":{"offset":19868145,"length":8176,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/nanoassert/index.js":{"offset":19876321,"length":438,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/nanoassert/package.json":{"offset":19876759,"length":647,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/require-addon/lib/bare.js":{"offset":19877406,"length":45,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/require-addon/package.json":{"offset":19877451,"length":1449,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-hmac/hash/sha256.js":{"offset":19878900,"length":284,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-hmac/hash/sha512.js":{"offset":19879184,"length":284,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-hmac/index.js":{"offset":19879468,"length":2063,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-hmac/package.json":{"offset":19881531,"length":670,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-native/binding.js":{"offset":19882201,"length":89,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-native/index.js":{"offset":19882290,"length":107894,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-native/package.json":{"offset":19990184,"length":1478,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-universal/index.js":{"offset":19991662,"length":42,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/sodium-universal/package.json":{"offset":19991704,"length":1217,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/which-runtime/index.js":{"offset":19992921,"length":1469,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/node_modules/which-runtime/package.json":{"offset":19994390,"length":863,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-identity/package.json":{"offset":19995253,"length":791,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/lib/car.js":{"offset":19996044,"length":3112,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/lib/cid.js":{"offset":19999156,"length":1924,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/lib/commit.js":{"offset":20001080,"length":1471,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/lib/mst.js":{"offset":20002551,"length":13309,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/lib/repo.js":{"offset":20015860,"length":4610,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/package.json":{"offset":20020470,"length":3961,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/src/index.js":{"offset":20024431,"length":4040,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/_shortw_utils.js":{"offset":20028471,"length":589,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/curve.js":{"offset":20029060,"length":18539,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/hash-to-curve.js":{"offset":20047599,"length":8097,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/modular.js":{"offset":20055696,"length":21647,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/weierstrass.js":{"offset":20077343,"length":58901,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json":{"offset":20136244,"length":47,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/secp256k1.js":{"offset":20136291,"length":12507,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/curves/esm/utils.js":{"offset":20148798,"length":12067,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/_md.js":{"offset":20160865,"length":6192,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/_u64.js":{"offset":20167057,"length":3081,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/crypto.js":{"offset":20170138,"length":146,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/hmac.js":{"offset":20170284,"length":2962,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json":{"offset":20173246,"length":147,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/sha2.js":{"offset":20173393,"length":16832,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js":{"offset":20190225,"length":10538,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/cborg.js":{"offset":20200763,"length":944,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js":{"offset":20201707,"length":6580,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/1negint.js":{"offset":20208287,"length":2980,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/2bytes.js":{"offset":20211267,"length":3451,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/3string.js":{"offset":20214718,"length":3340,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/4array.js":{"offset":20218058,"length":2944,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/5map.js":{"offset":20221002,"length":2917,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/6tag.js":{"offset":20223919,"length":1957,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/7float.js":{"offset":20225876,"length":8633,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/bl.js":{"offset":20234509,"length":5316,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/byte-utils.js":{"offset":20239825,"length":8172,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/common.js":{"offset":20247997,"length":598,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/decode.js":{"offset":20248595,"length":9008,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/encode.js":{"offset":20257603,"length":21407,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/is.js":{"offset":20279010,"length":2061,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/jump.js":{"offset":20281071,"length":7859,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/tagged.js":{"offset":20288930,"length":2821,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/lib/token.js":{"offset":20291751,"length":2019,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/cborg/package.json":{"offset":20293770,"length":4241,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base.js":{"offset":20298011,"length":6266,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base32.js":{"offset":20304277,"length":1443,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base36.js":{"offset":20305720,"length":327,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base58.js":{"offset":20306047,"length":379,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/bytes.js":{"offset":20306426,"length":1246,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/cid.js":{"offset":20307672,"length":13430,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/codecs/raw.js":{"offset":20321102,"length":238,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/hashes/digest.js":{"offset":20321340,"length":1915,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/link/interface.js":{"offset":20323255,"length":48,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/varint.js":{"offset":20323303,"length":398,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/vendor/base-x.js":{"offset":20323701,"length":5458,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/multiformats/dist/src/vendor/varint.js":{"offset":20329159,"length":2107,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/node_modules/multiformats/package.json":{"offset":20331266,"length":8176,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-repo/package.json":{"offset":20339442,"length":652,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/lib/lease.js":{"offset":20340094,"length":5061,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/lib/membership.js":{"offset":20345155,"length":3239,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/lib/pairing.js":{"offset":20348394,"length":5903,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/lib/repo-base.js":{"offset":20354297,"length":6477,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/lib/serve-membrane.js":{"offset":20360774,"length":27833,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/lib/signer-presence-channel.js":{"offset":20388607,"length":3971,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/lib/signer-presence.js":{"offset":20392578,"length":6721,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/lib/signer.js":{"offset":20399299,"length":4692,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/lib/state-base.js":{"offset":20403991,"length":95689,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/@hyperswarm/secret-stream/index.js":{"offset":20499680,"length":16722,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/@hyperswarm/secret-stream/lib/bridge.js":{"offset":20516402,"length":1273,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/@hyperswarm/secret-stream/lib/handshake.js":{"offset":20517675,"length":1950,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/@hyperswarm/secret-stream/package.json":{"offset":20519625,"length":1132,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/@ipld/dag-cbor/package.json":{"offset":20520757,"length":3961,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/@ipld/dag-cbor/src/index.js":{"offset":20524718,"length":4040,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/adaptive-timeout/index.js":{"offset":20528758,"length":2424,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/adaptive-timeout/package.json":{"offset":20531182,"length":972,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/lib/device-chain.js":{"offset":20532154,"length":4232,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/lib/discovery.js":{"offset":20536386,"length":1010,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/b4a/index.js":{"offset":20537396,"length":4054,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/b4a/package.json":{"offset":20541450,"length":1245,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bare-ansi-escapes/index.js":{"offset":20542695,"length":2255,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bare-ansi-escapes/package.json":{"offset":20544950,"length":1178,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bare-assert/index.js":{"offset":20546128,"length":2192,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bare-assert/package.json":{"offset":20548320,"length":835,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bare-inspect/binding.js":{"offset":20549155,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bare-inspect/index.js":{"offset":20549188,"length":23856,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bare-inspect/package.json":{"offset":20573044,"length":1041,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bare-type/binding.js":{"offset":20574085,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bare-type/index.js":{"offset":20574118,"length":4566,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bare-type/package.json":{"offset":20578684,"length":938,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bip39-mnemonic/index.js":{"offset":20579622,"length":4554,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bip39-mnemonic/package.json":{"offset":20584176,"length":789,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/chinese_simplified.json":{"offset":20584965,"length":12289,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/chinese_traditional.json":{"offset":20597254,"length":12289,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/czech.json":{"offset":20609543,"length":19042,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/english.json":{"offset":20628585,"length":17213,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/french.json":{"offset":20645798,"length":20874,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/index.js":{"offset":20666672,"length":1406,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/italian.json":{"offset":20668078,"length":20130,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/japanese.json":{"offset":20688208,"length":30520,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/korean.json":{"offset":20718728,"length":41929,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/lookup.json":{"offset":20760657,"length":592224,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/portuguese.json":{"offset":21352881,"length":19768,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/russian.json":{"offset":21372649,"length":30635,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/spanish.json":{"offset":21403284,"length":18093,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/bip39-mnemonic/wordlist/turkish.json":{"offset":21421377,"length":19421,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/compact-encoding/endian.js":{"offset":21440798,"length":105,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/compact-encoding/index.js":{"offset":21440903,"length":26406,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/compact-encoding/lexint.js":{"offset":21467309,"length":2851,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/compact-encoding/package.json":{"offset":21470160,"length":866,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/compact-encoding/raw.js":{"offset":21471026,"length":3977,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/hypercore-crypto/index.js":{"offset":21475003,"length":5031,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/hypercore-crypto/package.json":{"offset":21480034,"length":1007,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/keet-identity-key/index.js":{"offset":21481041,"length":6320,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/keet-identity-key/lib/crypto.js":{"offset":21487361,"length":552,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/keet-identity-key/lib/encoding.js":{"offset":21487913,"length":3695,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/keet-identity-key/lib/keychain.js":{"offset":21491608,"length":3080,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/keet-identity-key/package.json":{"offset":21494688,"length":887,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/nanoassert/index.js":{"offset":21495575,"length":438,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/nanoassert/package.json":{"offset":21496013,"length":647,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/require-addon/lib/bare.js":{"offset":21496660,"length":45,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/require-addon/package.json":{"offset":21496705,"length":1449,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/sodium-hmac/hash/sha256.js":{"offset":21498154,"length":284,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/sodium-hmac/hash/sha512.js":{"offset":21498438,"length":284,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/sodium-hmac/index.js":{"offset":21498722,"length":2063,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/sodium-hmac/package.json":{"offset":21500785,"length":670,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/sodium-native/binding.js":{"offset":21501455,"length":89,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/sodium-native/index.js":{"offset":21501544,"length":107894,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/sodium-native/package.json":{"offset":21609438,"length":1478,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/sodium-universal/index.js":{"offset":21610916,"length":42,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/sodium-universal/package.json":{"offset":21610958,"length":1217,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/which-runtime/index.js":{"offset":21612175,"length":1469,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/node_modules/which-runtime/package.json":{"offset":21613644,"length":863,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-identity/package.json":{"offset":21614507,"length":791,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/lib/cid.js":{"offset":21615298,"length":1924,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/lib/commit.js":{"offset":21617222,"length":1471,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/lib/mst.js":{"offset":21618693,"length":13309,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/package.json":{"offset":21632002,"length":3961,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/src/index.js":{"offset":21635963,"length":4040,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/curves/esm/_shortw_utils.js":{"offset":21640003,"length":589,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/curve.js":{"offset":21640592,"length":18539,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/hash-to-curve.js":{"offset":21659131,"length":8097,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/modular.js":{"offset":21667228,"length":21647,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/weierstrass.js":{"offset":21688875,"length":58901,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json":{"offset":21747776,"length":47,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/curves/esm/secp256k1.js":{"offset":21747823,"length":12507,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/curves/esm/utils.js":{"offset":21760330,"length":12067,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/hashes/esm/_md.js":{"offset":21772397,"length":6192,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/hashes/esm/_u64.js":{"offset":21778589,"length":3081,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/hashes/esm/crypto.js":{"offset":21781670,"length":146,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/hashes/esm/hmac.js":{"offset":21781816,"length":2962,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json":{"offset":21784778,"length":147,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/hashes/esm/sha2.js":{"offset":21784925,"length":16832,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js":{"offset":21801757,"length":10538,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/cborg.js":{"offset":21812295,"length":944,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js":{"offset":21813239,"length":6580,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/1negint.js":{"offset":21819819,"length":2980,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/2bytes.js":{"offset":21822799,"length":3451,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/3string.js":{"offset":21826250,"length":3340,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/4array.js":{"offset":21829590,"length":2944,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/5map.js":{"offset":21832534,"length":2917,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/6tag.js":{"offset":21835451,"length":1957,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/7float.js":{"offset":21837408,"length":8633,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/bl.js":{"offset":21846041,"length":5316,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/byte-utils.js":{"offset":21851357,"length":8172,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/common.js":{"offset":21859529,"length":598,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/decode.js":{"offset":21860127,"length":9008,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/encode.js":{"offset":21869135,"length":21407,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/is.js":{"offset":21890542,"length":2061,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/jump.js":{"offset":21892603,"length":7859,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/tagged.js":{"offset":21900462,"length":2821,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/lib/token.js":{"offset":21903283,"length":2019,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/cborg/package.json":{"offset":21905302,"length":4241,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base.js":{"offset":21909543,"length":6266,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base32.js":{"offset":21915809,"length":1443,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base36.js":{"offset":21917252,"length":327,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base58.js":{"offset":21917579,"length":379,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/multiformats/dist/src/bytes.js":{"offset":21917958,"length":1246,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/multiformats/dist/src/cid.js":{"offset":21919204,"length":13430,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/multiformats/dist/src/codecs/raw.js":{"offset":21932634,"length":238,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/multiformats/dist/src/hashes/digest.js":{"offset":21932872,"length":1915,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/multiformats/dist/src/link/interface.js":{"offset":21934787,"length":48,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/multiformats/dist/src/varint.js":{"offset":21934835,"length":398,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/multiformats/dist/src/vendor/base-x.js":{"offset":21935233,"length":5458,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/multiformats/dist/src/vendor/varint.js":{"offset":21940691,"length":2107,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/node_modules/multiformats/package.json":{"offset":21942798,"length":8176,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-repo/package.json":{"offset":21950974,"length":652,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/lib/corestore.js":{"offset":21951626,"length":1775,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/lib/firehose.js":{"offset":21953401,"length":4606,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/lib/repo-store.js":{"offset":21958007,"length":4701,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/lib/sequencer.js":{"offset":21962708,"length":3045,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/@hyperswarm/secret-stream/index.js":{"offset":21965753,"length":16722,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/@hyperswarm/secret-stream/lib/bridge.js":{"offset":21982475,"length":1273,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/@hyperswarm/secret-stream/lib/handshake.js":{"offset":21983748,"length":1950,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/@hyperswarm/secret-stream/package.json":{"offset":21985698,"length":1132,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/@ipld/dag-cbor/package.json":{"offset":21986830,"length":3961,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/@ipld/dag-cbor/src/index.js":{"offset":21990791,"length":4040,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/lib/car.js":{"offset":21994831,"length":3112,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/lib/cid.js":{"offset":21997943,"length":1924,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/lib/commit.js":{"offset":21999867,"length":1471,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/lib/mst.js":{"offset":22001338,"length":13309,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/lib/repo.js":{"offset":22014647,"length":4610,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/package.json":{"offset":22019257,"length":3961,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/src/index.js":{"offset":22023218,"length":4040,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/_shortw_utils.js":{"offset":22027258,"length":589,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/curve.js":{"offset":22027847,"length":18539,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/hash-to-curve.js":{"offset":22046386,"length":8097,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/modular.js":{"offset":22054483,"length":21647,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/weierstrass.js":{"offset":22076130,"length":58901,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json":{"offset":22135031,"length":47,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/secp256k1.js":{"offset":22135078,"length":12507,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/utils.js":{"offset":22147585,"length":12067,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/_md.js":{"offset":22159652,"length":6192,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/_u64.js":{"offset":22165844,"length":3081,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/crypto.js":{"offset":22168925,"length":146,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/hmac.js":{"offset":22169071,"length":2962,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json":{"offset":22172033,"length":147,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/sha2.js":{"offset":22172180,"length":16832,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js":{"offset":22189012,"length":10538,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/cborg.js":{"offset":22199550,"length":944,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js":{"offset":22200494,"length":6580,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/1negint.js":{"offset":22207074,"length":2980,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/2bytes.js":{"offset":22210054,"length":3451,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/3string.js":{"offset":22213505,"length":3340,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/4array.js":{"offset":22216845,"length":2944,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/5map.js":{"offset":22219789,"length":2917,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/6tag.js":{"offset":22222706,"length":1957,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/7float.js":{"offset":22224663,"length":8633,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/bl.js":{"offset":22233296,"length":5316,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/byte-utils.js":{"offset":22238612,"length":8172,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/common.js":{"offset":22246784,"length":598,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/decode.js":{"offset":22247382,"length":9008,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/encode.js":{"offset":22256390,"length":21407,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/is.js":{"offset":22277797,"length":2061,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/jump.js":{"offset":22279858,"length":7859,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/tagged.js":{"offset":22287717,"length":2821,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/token.js":{"offset":22290538,"length":2019,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json":{"offset":22292557,"length":4241,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base.js":{"offset":22296798,"length":6266,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base32.js":{"offset":22303064,"length":1443,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base36.js":{"offset":22304507,"length":327,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base58.js":{"offset":22304834,"length":379,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bytes.js":{"offset":22305213,"length":1246,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/cid.js":{"offset":22306459,"length":13430,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/codecs/raw.js":{"offset":22319889,"length":238,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/hashes/digest.js":{"offset":22320127,"length":1915,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/link/interface.js":{"offset":22322042,"length":48,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/varint.js":{"offset":22322090,"length":398,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/vendor/base-x.js":{"offset":22322488,"length":5458,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/vendor/varint.js":{"offset":22327946,"length":2107,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/package.json":{"offset":22330053,"length":8176,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/atproto-repo/package.json":{"offset":22338229,"length":652,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/b4a/index.js":{"offset":22338881,"length":4054,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/b4a/package.json":{"offset":22342935,"length":1245,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-ansi-escapes/index.js":{"offset":22344180,"length":2255,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-ansi-escapes/package.json":{"offset":22346435,"length":1178,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-assert/index.js":{"offset":22347613,"length":2192,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-assert/package.json":{"offset":22349805,"length":835,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-events/index.js":{"offset":22350640,"length":8307,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-events/lib/errors.js":{"offset":22358947,"length":671,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-events/package.json":{"offset":22359618,"length":1504,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-fs/binding.js":{"offset":22361122,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-fs/index.js":{"offset":22361155,"length":58907,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-fs/lib/constants.js":{"offset":22420062,"length":1494,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-fs/lib/errors.js":{"offset":22421556,"length":1163,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-fs/package.json":{"offset":22422719,"length":1654,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-fs/promises.js":{"offset":22424373,"length":2401,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-inspect/binding.js":{"offset":22426774,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-inspect/index.js":{"offset":22426807,"length":23856,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-inspect/package.json":{"offset":22450663,"length":1041,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-os/binding.js":{"offset":22451704,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-os/index.js":{"offset":22451737,"length":5216,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-os/lib/constants.js":{"offset":22456953,"length":143,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-os/lib/errors.js":{"offset":22457096,"length":453,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-os/package.json":{"offset":22457549,"length":1257,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-path/index.js":{"offset":22458806,"length":287,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-path/lib/constants.js":{"offset":22459093,"length":247,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-path/lib/posix.js":{"offset":22459340,"length":6005,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-path/lib/shared.js":{"offset":22465345,"length":1926,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-path/lib/win32.js":{"offset":22467271,"length":13591,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-path/package.json":{"offset":22480862,"length":1036,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-stream/index.js":{"offset":22481898,"length":10904,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-stream/package.json":{"offset":22492802,"length":1676,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-stream/web.js":{"offset":22494478,"length":13980,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-type/binding.js":{"offset":22508458,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-type/index.js":{"offset":22508491,"length":4566,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-type/package.json":{"offset":22513057,"length":938,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-url/binding.js":{"offset":22513995,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-url/index.js":{"offset":22514028,"length":9449,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-url/lib/errors.js":{"offset":22523477,"length":778,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-url/lib/url-search-params.js":{"offset":22524255,"length":4331,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/bare-url/package.json":{"offset":22528586,"length":1219,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/big-sparse-array/index.js":{"offset":22529805,"length":2471,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/big-sparse-array/package.json":{"offset":22532276,"length":636,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/cborg.js":{"offset":22532912,"length":944,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/0uint.js":{"offset":22533856,"length":6580,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/1negint.js":{"offset":22540436,"length":2980,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/2bytes.js":{"offset":22543416,"length":3451,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/3string.js":{"offset":22546867,"length":3340,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/4array.js":{"offset":22550207,"length":2944,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/5map.js":{"offset":22553151,"length":2917,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/6tag.js":{"offset":22556068,"length":1957,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/7float.js":{"offset":22558025,"length":8633,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/bl.js":{"offset":22566658,"length":5316,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/byte-utils.js":{"offset":22571974,"length":8172,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/common.js":{"offset":22580146,"length":598,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/decode.js":{"offset":22580744,"length":9008,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/encode.js":{"offset":22589752,"length":21407,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/is.js":{"offset":22611159,"length":2061,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/jump.js":{"offset":22613220,"length":7859,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/tagged.js":{"offset":22621079,"length":2821,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/lib/token.js":{"offset":22623900,"length":2019,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/cborg/package.json":{"offset":22625919,"length":4241,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/codecs/index.js":{"offset":22630160,"length":2416,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/codecs/package.json":{"offset":22632576,"length":655,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/compact-encoding/endian.js":{"offset":22633231,"length":105,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/compact-encoding/index.js":{"offset":22633336,"length":26406,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/compact-encoding/lexint.js":{"offset":22659742,"length":2851,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/compact-encoding/package.json":{"offset":22662593,"length":866,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/compact-encoding/raw.js":{"offset":22663459,"length":3977,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/corestore/index.js":{"offset":22667436,"length":19847,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/corestore/lib/audit.js":{"offset":22687283,"length":475,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/corestore/lib/notify.js":{"offset":22687758,"length":630,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/corestore/package.json":{"offset":22688388,"length":1350,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/debounceify/index.js":{"offset":22689738,"length":585,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/debounceify/package.json":{"offset":22690323,"length":567,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/device-file/index.js":{"offset":22690890,"length":6394,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/device-file/package.json":{"offset":22697284,"length":1190,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/events-universal/bare.js":{"offset":22698474,"length":40,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/events-universal/package.json":{"offset":22698514,"length":908,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/fast-fifo/fixed-size.js":{"offset":22699422,"length":875,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/fast-fifo/index.js":{"offset":22700297,"length":972,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/fast-fifo/package.json":{"offset":22701269,"length":682,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/fd-lock/index.js":{"offset":22701951,"length":1755,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/fd-lock/package.json":{"offset":22703706,"length":1099,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/flat-tree/index.js":{"offset":22704805,"length":8164,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/flat-tree/package.json":{"offset":22712969,"length":631,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/fs-native-extensions/binding.js":{"offset":22713600,"length":90,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/fs-native-extensions/index.js":{"offset":22713690,"length":7239,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/fs-native-extensions/package.json":{"offset":22720929,"length":1790,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hyperbee/index.js":{"offset":22722719,"length":46445,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hyperbee/iterators/diff.js":{"offset":22769164,"length":5358,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hyperbee/iterators/history.js":{"offset":22774522,"length":1631,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hyperbee/iterators/local.js":{"offset":22776153,"length":1170,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hyperbee/iterators/range.js":{"offset":22777323,"length":5869,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hyperbee/lib/extension.js":{"offset":22783192,"length":3488,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hyperbee/lib/messages.js":{"offset":22786680,"length":28162,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hyperbee/package.json":{"offset":22814842,"length":1585,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-crypto/index.js":{"offset":22816427,"length":5031,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-crypto/package.json":{"offset":22821458,"length":1007,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-errors/index.js":{"offset":22822465,"length":4896,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-errors/package.json":{"offset":22827361,"length":688,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-id-encoding/index.js":{"offset":22828049,"length":923,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-id-encoding/package.json":{"offset":22828972,"length":799,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-storage/encoding/external.js":{"offset":22829771,"length":264,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-storage/encoding/spec/hyperschema/index.js":{"offset":22830035,"length":16796,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-storage/index.js":{"offset":22846831,"length":33493,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-storage/lib/block-dependency-stream.js":{"offset":22880324,"length":2557,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-storage/lib/close-error-stream.js":{"offset":22882881,"length":276,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-storage/lib/keys.js":{"offset":22883157,"length":8751,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-storage/lib/streams.js":{"offset":22891908,"length":5686,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-storage/lib/tx.js":{"offset":22897594,"length":11683,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-storage/lib/view.js":{"offset":22909277,"length":8379,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-storage/migrations/0/index.js":{"offset":22917656,"length":20125,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-storage/migrations/0/messages.js":{"offset":22937781,"length":26402,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-storage/migrations/1/index.js":{"offset":22964183,"length":1181,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore-storage/package.json":{"offset":22965364,"length":1827,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/index.js":{"offset":22967191,"length":40241,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/audit.js":{"offset":23007432,"length":3834,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/bit-interlude.js":{"offset":23011266,"length":4257,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/bitfield.js":{"offset":23015523,"length":12115,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/caps.js":{"offset":23027638,"length":1537,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/compat.js":{"offset":23029175,"length":477,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/copy-prologue.js":{"offset":23029652,"length":5999,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/core.js":{"offset":23035651,"length":28356,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/default-encryption.js":{"offset":23064007,"length":3453,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/download.js":{"offset":23067460,"length":1278,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/feature-flags.js":{"offset":23068738,"length":38,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/fully-remote-proof.js":{"offset":23068776,"length":3470,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/hotswap-queue.js":{"offset":23072246,"length":1498,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/info.js":{"offset":23073744,"length":1517,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/inspect.js":{"offset":23075261,"length":1983,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/mark-bitfield.js":{"offset":23077244,"length":2589,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/merkle-tree.js":{"offset":23079833,"length":34353,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/messages.js":{"offset":23114186,"length":28313,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/multisig.js":{"offset":23142499,"length":2851,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/mutex.js":{"offset":23145350,"length":1028,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/receiver-queue.js":{"offset":23146378,"length":1413,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/remote-bitfield.js":{"offset":23147791,"length":8124,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/replicator.js":{"offset":23155915,"length":88868,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/session-state.js":{"offset":23244783,"length":36297,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/streams.js":{"offset":23281080,"length":3034,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/verifier.js":{"offset":23284114,"length":9926,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/lib/wants.js":{"offset":23294040,"length":7204,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hypercore/package.json":{"offset":23301244,"length":2196,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hyperschema/package.json":{"offset":23303440,"length":1555,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/hyperschema/runtime.cjs":{"offset":23304995,"length":54,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/index-encoder/index.js":{"offset":23305049,"length":10596,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/index-encoder/package.json":{"offset":23315645,"length":928,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/is-options/index.js":{"offset":23316573,"length":140,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/is-options/package.json":{"offset":23316713,"length":605,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/multiformats/dist/src/bases/base.js":{"offset":23317318,"length":6266,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/multiformats/dist/src/bases/base32.js":{"offset":23323584,"length":1443,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/multiformats/dist/src/bases/base36.js":{"offset":23325027,"length":327,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/multiformats/dist/src/bases/base58.js":{"offset":23325354,"length":379,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/multiformats/dist/src/bytes.js":{"offset":23325733,"length":1246,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/multiformats/dist/src/cid.js":{"offset":23326979,"length":13430,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/multiformats/dist/src/hashes/digest.js":{"offset":23340409,"length":1915,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/multiformats/dist/src/link/interface.js":{"offset":23342324,"length":48,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/multiformats/dist/src/varint.js":{"offset":23342372,"length":398,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/multiformats/dist/src/vendor/base-x.js":{"offset":23342770,"length":5458,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/multiformats/dist/src/vendor/varint.js":{"offset":23348228,"length":2107,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/multiformats/package.json":{"offset":23350335,"length":8176,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/mutexify/index.js":{"offset":23358511,"length":536,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/mutexify/package.json":{"offset":23359047,"length":679,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/mutexify/promise.js":{"offset":23359726,"length":324,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/nanoassert/index.js":{"offset":23360050,"length":438,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/nanoassert/package.json":{"offset":23360488,"length":647,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/noise-curve-ed/index.js":{"offset":23361135,"length":1642,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/noise-curve-ed/package.json":{"offset":23362777,"length":808,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/noise-handshake/cipher.js":{"offset":23363585,"length":2817,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/noise-handshake/dh.js":{"offset":23366402,"length":1439,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/noise-handshake/hkdf.js":{"offset":23367841,"length":1092,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/noise-handshake/hmac.js":{"offset":23368933,"length":1273,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/noise-handshake/noise.js":{"offset":23370206,"length":6437,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/noise-handshake/package.json":{"offset":23376643,"length":638,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/noise-handshake/symmetric-state.js":{"offset":23377281,"length":2206,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/protocol-buffers-encodings/index.js":{"offset":23379487,"length":6489,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/protocol-buffers-encodings/package.json":{"offset":23385976,"length":719,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/protomux/index.js":{"offset":23386695,"length":19741,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/protomux/package.json":{"offset":23406436,"length":1059,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/queue-tick/package.json":{"offset":23407495,"length":669,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/queue-tick/process-next-tick.js":{"offset":23408164,"length":160,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/queue-tick/queue-microtask.js":{"offset":23408324,"length":108,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/quickbit-native/binding.js":{"offset":23408432,"length":90,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/quickbit-native/index.js":{"offset":23408522,"length":4683,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/quickbit-native/package.json":{"offset":23413205,"length":1104,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/quickbit-universal/fallback.js":{"offset":23414309,"length":10204,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/quickbit-universal/index.js":{"offset":23424513,"length":442,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/quickbit-universal/package.json":{"offset":23424955,"length":908,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/rache/index.js":{"offset":23425863,"length":2463,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/rache/package.json":{"offset":23428326,"length":602,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/random-array-iterator/index.js":{"offset":23428928,"length":1001,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/random-array-iterator/package.json":{"offset":23429929,"length":700,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/ready-resource/index.js":{"offset":23430629,"length":1091,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/ready-resource/package.json":{"offset":23431720,"length":812,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/refcounter/index.js":{"offset":23432532,"length":611,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/refcounter/package.json":{"offset":23433143,"length":451,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/require-addon/lib/bare.js":{"offset":23433594,"length":45,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/require-addon/package.json":{"offset":23433639,"length":1449,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/resolve-reject-promise/index.js":{"offset":23435088,"length":443,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/resolve-reject-promise/package.json":{"offset":23435531,"length":581,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/resource-on-exit/index.js":{"offset":23436112,"length":361,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/resource-on-exit/package.json":{"offset":23436473,"length":496,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/rocksdb-native/binding.js":{"offset":23436969,"length":90,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/rocksdb-native/index.js":{"offset":23437059,"length":5304,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/rocksdb-native/lib/batch.js":{"offset":23442363,"length":9605,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/rocksdb-native/lib/column-family.js":{"offset":23451968,"length":2930,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/rocksdb-native/lib/constants.js":{"offset":23454898,"length":621,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/rocksdb-native/lib/filter-policy.js":{"offset":23455519,"length":437,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/rocksdb-native/lib/iterator.js":{"offset":23455956,"length":4311,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/rocksdb-native/lib/snapshot.js":{"offset":23460267,"length":503,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/rocksdb-native/lib/state.js":{"offset":23460770,"length":13115,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/rocksdb-native/package.json":{"offset":23473885,"length":1863,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/safety-catch/index.js":{"offset":23475748,"length":543,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/safety-catch/package.json":{"offset":23476291,"length":547,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/scope-lock/index.js":{"offset":23476838,"length":1821,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/scope-lock/package.json":{"offset":23478659,"length":611,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/signal-promise/index.js":{"offset":23479270,"length":1252,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/signal-promise/package.json":{"offset":23480522,"length":503,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/signed-varint/index.js":{"offset":23481025,"length":435,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/signed-varint/package.json":{"offset":23481460,"length":523,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/simdle-native/binding.js":{"offset":23481983,"length":90,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/simdle-native/index.js":{"offset":23482073,"length":3474,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/simdle-native/package.json":{"offset":23485547,"length":1115,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/simdle-universal/fallback.js":{"offset":23486662,"length":5137,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/simdle-universal/index.js":{"offset":23491799,"length":103,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/simdle-universal/package.json":{"offset":23491902,"length":879,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/simdle-universal/scalar.js":{"offset":23492781,"length":469,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/sodium-native/binding.js":{"offset":23493250,"length":89,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/sodium-native/index.js":{"offset":23493339,"length":107894,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/sodium-native/package.json":{"offset":23601233,"length":1478,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/sodium-secretstream/index.js":{"offset":23602711,"length":2257,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/sodium-secretstream/package.json":{"offset":23604968,"length":657,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/sodium-universal/index.js":{"offset":23605625,"length":42,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/sodium-universal/package.json":{"offset":23605667,"length":1217,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/streamx/index.js":{"offset":23606884,"length":34248,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/streamx/lib/errors.js":{"offset":23641132,"length":1096,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/streamx/package.json":{"offset":23642228,"length":1225,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/teex/index.js":{"offset":23643453,"length":1107,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/teex/package.json":{"offset":23644560,"length":608,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/text-decoder/index.js":{"offset":23645168,"length":1371,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/text-decoder/lib/pass-through-decoder.js":{"offset":23646539,"length":269,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/text-decoder/lib/utf8-decoder.js":{"offset":23646808,"length":4429,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/text-decoder/package.json":{"offset":23651237,"length":990,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/timeout-refresh/browser.js":{"offset":23652227,"length":1098,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/timeout-refresh/index.js":{"offset":23653325,"length":184,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/timeout-refresh/node.js":{"offset":23653509,"length":928,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/timeout-refresh/package.json":{"offset":23654437,"length":619,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/unslab/index.js":{"offset":23655056,"length":913,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/unslab/package.json":{"offset":23655969,"length":613,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/varint/decode.js":{"offset":23656582,"length":508,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/varint/encode.js":{"offset":23657090,"length":452,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/varint/index.js":{"offset":23657542,"length":134,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/varint/length.js":{"offset":23657676,"length":471,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/varint/package.json":{"offset":23658147,"length":511,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/which-runtime/index.js":{"offset":23658658,"length":1469,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/which-runtime/package.json":{"offset":23660127,"length":863,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/xache/index.js":{"offset":23660990,"length":2477,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/xache/package.json":{"offset":23663467,"length":672,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/z32/index.js":{"offset":23664139,"length":2654,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/z32/package.json":{"offset":23666793,"length":701,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/package.json":{"offset":23667494,"length":932,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/encoding/legacy.js":{"offset":23668426,"length":8969,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/encoding/spec/autobase/index.js":{"offset":23677395,"length":18905,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/index.js":{"offset":23696300,"length":59358,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/active-writers.js":{"offset":23755658,"length":736,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/append-batch.js":{"offset":23756394,"length":1426,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/apply-calls.js":{"offset":23757820,"length":2275,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/apply-state.js":{"offset":23760095,"length":46121,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/boot.js":{"offset":23806216,"length":4599,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/caps.js":{"offset":23810815,"length":505,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/clock.js":{"offset":23811320,"length":749,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/consensus.js":{"offset":23812069,"length":11754,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/encryption.js":{"offset":23823823,"length":9444,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/fast-forward.js":{"offset":23833267,"length":5714,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/fork.js":{"offset":23838981,"length":4148,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/linearizer.js":{"offset":23843129,"length":9696,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/local-state.js":{"offset":23852825,"length":2013,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/messages.js":{"offset":23854838,"length":827,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/node-buffer.js":{"offset":23855665,"length":1563,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/store.js":{"offset":23857228,"length":14341,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/system.js":{"offset":23871569,"length":20176,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/timer.js":{"offset":23891745,"length":2937,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/topolist.js":{"offset":23894682,"length":5108,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/updates.js":{"offset":23899790,"length":1109,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/values.js":{"offset":23900899,"length":1539,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/wakeup.js":{"offset":23902438,"length":4034,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/lib/writer.js":{"offset":23906472,"length":8901,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/node_modules/compact-encoding/endian.js":{"offset":23915373,"length":105,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/node_modules/compact-encoding/index.js":{"offset":23915478,"length":26406,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/node_modules/compact-encoding/lexint.js":{"offset":23941884,"length":2851,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/node_modules/compact-encoding/package.json":{"offset":23944735,"length":866,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/node_modules/compact-encoding/raw.js":{"offset":23945601,"length":3977,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/autobase/package.json":{"offset":23949578,"length":2327,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/index.js":{"offset":23951905,"length":4054,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/b4a/package.json":{"offset":23955959,"length":1245,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-abort/binding.js":{"offset":23957204,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-abort/index.js":{"offset":23957237,"length":69,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-abort/package.json":{"offset":23957306,"length":886,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-ansi-escapes/index.js":{"offset":23958192,"length":2255,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-ansi-escapes/package.json":{"offset":23960447,"length":1178,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-assert/index.js":{"offset":23961625,"length":2192,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-assert/package.json":{"offset":23963817,"length":835,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-env/index.js":{"offset":23964652,"length":1017,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-env/package.json":{"offset":23965669,"length":944,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-events/index.js":{"offset":23966613,"length":8307,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-events/lib/errors.js":{"offset":23974920,"length":671,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-events/package.json":{"offset":23975591,"length":1504,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-fs/binding.js":{"offset":23977095,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-fs/index.js":{"offset":23977128,"length":58907,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-fs/lib/constants.js":{"offset":24036035,"length":1494,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-fs/lib/errors.js":{"offset":24037529,"length":1166,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-fs/package.json":{"offset":24038695,"length":1654,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-fs/promises.js":{"offset":24040349,"length":2401,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-hrtime/binding.js":{"offset":24042750,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-hrtime/index.js":{"offset":24042783,"length":319,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-hrtime/package.json":{"offset":24043102,"length":905,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-inspect/binding.js":{"offset":24044007,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-inspect/index.js":{"offset":24044040,"length":23856,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-inspect/package.json":{"offset":24067896,"length":1041,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-os/binding.js":{"offset":24068937,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-os/index.js":{"offset":24068970,"length":5216,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-os/lib/constants.js":{"offset":24074186,"length":143,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-os/lib/errors.js":{"offset":24074329,"length":453,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-os/package.json":{"offset":24074782,"length":1257,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-path/binding.js":{"offset":24076039,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-path/index.js":{"offset":24076072,"length":287,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-path/lib/constants.js":{"offset":24076359,"length":247,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-path/lib/posix.js":{"offset":24076606,"length":6399,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-path/lib/shared.js":{"offset":24083005,"length":2148,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-path/lib/win32.js":{"offset":24085153,"length":13987,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-path/package.json":{"offset":24099140,"length":1106,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-pipe/binding.js":{"offset":24100246,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-pipe/index.js":{"offset":24100279,"length":14357,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-pipe/lib/constants.js":{"offset":24114636,"length":352,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-pipe/lib/errors.js":{"offset":24114988,"length":699,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-pipe/package.json":{"offset":24115687,"length":1396,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-posix/package.json":{"offset":24117083,"length":1091,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-posix/unsupported.js":{"offset":24118174,"length":723,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-process/index.js":{"offset":24118897,"length":3189,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-process/package.json":{"offset":24122086,"length":1283,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-signals/binding.js":{"offset":24123369,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-signals/index.js":{"offset":24123402,"length":1412,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-signals/lib/emitter.js":{"offset":24124814,"length":1260,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-signals/lib/errors.js":{"offset":24126074,"length":479,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-signals/package.json":{"offset":24126553,"length":1227,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-stdio/binding.js":{"offset":24127780,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-stdio/index.js":{"offset":24127813,"length":1525,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-stdio/package.json":{"offset":24129338,"length":1232,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-stream/index.js":{"offset":24130570,"length":10904,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-stream/package.json":{"offset":24141474,"length":1676,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-stream/web.js":{"offset":24143150,"length":13980,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-tty/binding.js":{"offset":24157130,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-tty/index.js":{"offset":24157163,"length":4638,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-tty/lib/constants.js":{"offset":24161801,"length":442,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-tty/package.json":{"offset":24162243,"length":1211,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-type/binding.js":{"offset":24163454,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-type/index.js":{"offset":24163487,"length":4566,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-type/package.json":{"offset":24168053,"length":938,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-url/binding.js":{"offset":24168991,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-url/index.js":{"offset":24169024,"length":9449,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-url/lib/errors.js":{"offset":24178473,"length":778,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-url/lib/url-search-params.js":{"offset":24179251,"length":4331,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bare-url/package.json":{"offset":24183582,"length":1219,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/big-sparse-array/index.js":{"offset":24184801,"length":2471,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/big-sparse-array/package.json":{"offset":24187272,"length":636,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bip39-mnemonic/index.js":{"offset":24187908,"length":4554,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bip39-mnemonic/package.json":{"offset":24192462,"length":789,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bip39-mnemonic/wordlist/chinese_simplified.json":{"offset":24193251,"length":12289,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bip39-mnemonic/wordlist/chinese_traditional.json":{"offset":24205540,"length":12289,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bip39-mnemonic/wordlist/czech.json":{"offset":24217829,"length":19042,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bip39-mnemonic/wordlist/english.json":{"offset":24236871,"length":17213,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bip39-mnemonic/wordlist/french.json":{"offset":24254084,"length":20874,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bip39-mnemonic/wordlist/index.js":{"offset":24274958,"length":1406,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bip39-mnemonic/wordlist/italian.json":{"offset":24276364,"length":20130,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bip39-mnemonic/wordlist/japanese.json":{"offset":24296494,"length":30520,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bip39-mnemonic/wordlist/korean.json":{"offset":24327014,"length":41929,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bip39-mnemonic/wordlist/lookup.json":{"offset":24368943,"length":592224,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bip39-mnemonic/wordlist/portuguese.json":{"offset":24961167,"length":19768,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bip39-mnemonic/wordlist/russian.json":{"offset":24980935,"length":30635,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bip39-mnemonic/wordlist/spanish.json":{"offset":25011570,"length":18093,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bip39-mnemonic/wordlist/turkish.json":{"offset":25029663,"length":19421,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bits-to-bytes/index.js":{"offset":25049084,"length":3083,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bits-to-bytes/package.json":{"offset":25052167,"length":708,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-pairing/index.js":{"offset":25052875,"length":16910,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-pairing/package.json":{"offset":25069785,"length":1000,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-relay/index.js":{"offset":25070785,"length":13411,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-relay/lib/errors.js":{"offset":25084196,"length":1036,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-relay/node_modules/compact-encoding/endian.js":{"offset":25085232,"length":105,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-relay/node_modules/compact-encoding/index.js":{"offset":25085337,"length":26406,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-relay/node_modules/compact-encoding/lexint.js":{"offset":25111743,"length":2851,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-relay/node_modules/compact-encoding/package.json":{"offset":25114594,"length":866,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-relay/node_modules/compact-encoding/raw.js":{"offset":25115460,"length":3977,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/blind-relay/package.json":{"offset":25119437,"length":1231,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bogon/index.js":{"offset":25120668,"length":4004,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bogon/node_modules/compact-encoding/endian.js":{"offset":25124672,"length":105,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bogon/node_modules/compact-encoding/index.js":{"offset":25124777,"length":26406,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bogon/node_modules/compact-encoding/lexint.js":{"offset":25151183,"length":2851,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bogon/node_modules/compact-encoding/package.json":{"offset":25154034,"length":866,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bogon/node_modules/compact-encoding/raw.js":{"offset":25154900,"length":3977,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/bogon/package.json":{"offset":25158877,"length":656,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/cborg.js":{"offset":25159533,"length":944,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/0uint.js":{"offset":25160477,"length":6580,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/1negint.js":{"offset":25167057,"length":2980,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/2bytes.js":{"offset":25170037,"length":3451,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/3string.js":{"offset":25173488,"length":3340,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/4array.js":{"offset":25176828,"length":2944,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/5map.js":{"offset":25179772,"length":2917,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/6tag.js":{"offset":25182689,"length":1957,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/7float.js":{"offset":25184646,"length":8633,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/bl.js":{"offset":25193279,"length":5505,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/byte-utils.js":{"offset":25198784,"length":8369,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/common.js":{"offset":25207153,"length":598,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/decode.js":{"offset":25207751,"length":9008,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/encode.js":{"offset":25216759,"length":21957,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/is.js":{"offset":25238716,"length":2061,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/jump.js":{"offset":25240777,"length":7942,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/tagged.js":{"offset":25248719,"length":2821,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/lib/token.js":{"offset":25251540,"length":2019,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/cborg/package.json":{"offset":25253559,"length":4241,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/codecs/index.js":{"offset":25257800,"length":2416,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/codecs/package.json":{"offset":25260216,"length":655,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding-bitfield/index.js":{"offset":25260871,"length":1967,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/endian.js":{"offset":25262838,"length":105,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/index.js":{"offset":25262943,"length":26406,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/lexint.js":{"offset":25289349,"length":2851,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/package.json":{"offset":25292200,"length":866,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/raw.js":{"offset":25293066,"length":3977,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding-bitfield/package.json":{"offset":25297043,"length":1109,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding/endian.js":{"offset":25298152,"length":105,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding/index.js":{"offset":25298257,"length":24454,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding/lexint.js":{"offset":25322711,"length":2851,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding/package.json":{"offset":25325562,"length":786,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/compact-encoding/raw.js":{"offset":25326348,"length":4093,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/core-coupler/index.js":{"offset":25330441,"length":2243,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/core-coupler/package.json":{"offset":25332684,"length":599,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/corestore/index.js":{"offset":25333283,"length":19847,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/corestore/lib/audit.js":{"offset":25353130,"length":475,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/corestore/lib/notify.js":{"offset":25353605,"length":630,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/corestore/package.json":{"offset":25354235,"length":1350,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/debounceify/index.js":{"offset":25355585,"length":585,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/debounceify/package.json":{"offset":25356170,"length":567,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/device-file/index.js":{"offset":25356737,"length":6394,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/device-file/package.json":{"offset":25363131,"length":1190,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/index.js":{"offset":25364321,"length":29079,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/lib/commands.js":{"offset":25393400,"length":107,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/lib/errors.js":{"offset":25393507,"length":719,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/lib/health.js":{"offset":25394226,"length":2998,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/lib/io.js":{"offset":25397224,"length":16605,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/lib/peer.js":{"offset":25413829,"length":583,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/lib/query.js":{"offset":25414412,"length":9899,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/lib/session.js":{"offset":25424311,"length":1103,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/node_modules/compact-encoding/endian.js":{"offset":25425414,"length":105,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/node_modules/compact-encoding/index.js":{"offset":25425519,"length":26406,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/node_modules/compact-encoding/lexint.js":{"offset":25451925,"length":2851,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/node_modules/compact-encoding/package.json":{"offset":25454776,"length":866,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/node_modules/compact-encoding/raw.js":{"offset":25455642,"length":3977,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/dht-rpc/package.json":{"offset":25459619,"length":1396,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/encryption-encoding/index.js":{"offset":25461015,"length":378,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/encryption-encoding/package.json":{"offset":25461393,"length":1234,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/encryption-encoding/spec/hyperschema/index.js":{"offset":25462627,"length":1749,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/events-universal/bare.js":{"offset":25464376,"length":40,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/events-universal/package.json":{"offset":25464416,"length":908,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/fast-fifo/fixed-size.js":{"offset":25465324,"length":875,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/fast-fifo/index.js":{"offset":25466199,"length":972,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/fast-fifo/package.json":{"offset":25467171,"length":682,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/fd-lock/index.js":{"offset":25467853,"length":1755,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/fd-lock/package.json":{"offset":25469608,"length":1099,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/flat-tree/index.js":{"offset":25470707,"length":8164,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/flat-tree/package.json":{"offset":25478871,"length":631,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/fs-native-extensions/binding.js":{"offset":25479502,"length":90,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/fs-native-extensions/index.js":{"offset":25479592,"length":7239,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/fs-native-extensions/package.json":{"offset":25486831,"length":1790,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperbee/index.js":{"offset":25488621,"length":46445,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperbee/iterators/diff.js":{"offset":25535066,"length":5358,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperbee/iterators/history.js":{"offset":25540424,"length":1631,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperbee/iterators/local.js":{"offset":25542055,"length":1170,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperbee/iterators/range.js":{"offset":25543225,"length":5869,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperbee/lib/extension.js":{"offset":25549094,"length":3488,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperbee/lib/messages.js":{"offset":25552582,"length":28162,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperbee/package.json":{"offset":25580744,"length":1585,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/index.js":{"offset":25582329,"length":5031,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/node_modules/compact-encoding/endian.js":{"offset":25587360,"length":105,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/node_modules/compact-encoding/index.js":{"offset":25587465,"length":26406,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/node_modules/compact-encoding/lexint.js":{"offset":25613871,"length":2851,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/node_modules/compact-encoding/package.json":{"offset":25616722,"length":866,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/node_modules/compact-encoding/raw.js":{"offset":25617588,"length":3977,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-crypto/package.json":{"offset":25621565,"length":1007,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-errors/index.js":{"offset":25622572,"length":4896,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-errors/package.json":{"offset":25627468,"length":688,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-id-encoding/index.js":{"offset":25628156,"length":923,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-id-encoding/package.json":{"offset":25629079,"length":799,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/encoding/external.js":{"offset":25629878,"length":264,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/encoding/spec/hyperschema/index.js":{"offset":25630142,"length":16796,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/index.js":{"offset":25646938,"length":33493,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/lib/block-dependency-stream.js":{"offset":25680431,"length":2557,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/lib/close-error-stream.js":{"offset":25682988,"length":276,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/lib/keys.js":{"offset":25683264,"length":8751,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/lib/streams.js":{"offset":25692015,"length":5686,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/lib/tx.js":{"offset":25697701,"length":11683,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/lib/view.js":{"offset":25709384,"length":8379,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/migrations/0/index.js":{"offset":25717763,"length":20125,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/migrations/0/messages.js":{"offset":25737888,"length":26402,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/migrations/1/index.js":{"offset":25764290,"length":1181,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/node_modules/compact-encoding/endian.js":{"offset":25765471,"length":105,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/node_modules/compact-encoding/index.js":{"offset":25765576,"length":26406,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/node_modules/compact-encoding/lexint.js":{"offset":25791982,"length":2851,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/node_modules/compact-encoding/package.json":{"offset":25794833,"length":866,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/node_modules/compact-encoding/raw.js":{"offset":25795699,"length":3977,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore-storage/package.json":{"offset":25799676,"length":1827,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/index.js":{"offset":25801503,"length":40241,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/audit.js":{"offset":25841744,"length":3834,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/bit-interlude.js":{"offset":25845578,"length":4257,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/bitfield.js":{"offset":25849835,"length":12115,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/caps.js":{"offset":25861950,"length":1537,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/compat.js":{"offset":25863487,"length":477,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/copy-prologue.js":{"offset":25863964,"length":5999,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/core.js":{"offset":25869963,"length":28356,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/default-encryption.js":{"offset":25898319,"length":3453,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/download.js":{"offset":25901772,"length":1278,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/feature-flags.js":{"offset":25903050,"length":38,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/fully-remote-proof.js":{"offset":25903088,"length":3470,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/hotswap-queue.js":{"offset":25906558,"length":1498,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/info.js":{"offset":25908056,"length":1517,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/inspect.js":{"offset":25909573,"length":1983,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/mark-bitfield.js":{"offset":25911556,"length":2589,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/merkle-tree.js":{"offset":25914145,"length":34353,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/messages.js":{"offset":25948498,"length":28313,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/multisig.js":{"offset":25976811,"length":2851,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/mutex.js":{"offset":25979662,"length":1028,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/receiver-queue.js":{"offset":25980690,"length":1413,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/remote-bitfield.js":{"offset":25982103,"length":8124,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/replicator.js":{"offset":25990227,"length":88908,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/session-state.js":{"offset":26079135,"length":36297,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/streams.js":{"offset":26115432,"length":3034,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/verifier.js":{"offset":26118466,"length":9926,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/lib/wants.js":{"offset":26128392,"length":7204,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/node_modules/compact-encoding/endian.js":{"offset":26135596,"length":105,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/node_modules/compact-encoding/index.js":{"offset":26135701,"length":26406,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/node_modules/compact-encoding/lexint.js":{"offset":26162107,"length":2851,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/node_modules/compact-encoding/package.json":{"offset":26164958,"length":866,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/node_modules/compact-encoding/raw.js":{"offset":26165824,"length":3977,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hypercore/package.json":{"offset":26169801,"length":2196,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdb/index.js":{"offset":26171997,"length":21368,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdb/lib/changes-stream.js":{"offset":26193365,"length":327,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdb/lib/definition.js":{"offset":26193692,"length":910,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdb/lib/engine/bee.js":{"offset":26194602,"length":4520,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdb/lib/engine/bee2.js":{"offset":26199122,"length":5083,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdb/lib/engine/rocks.js":{"offset":26204205,"length":4370,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdb/lib/sessions.js":{"offset":26208575,"length":711,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdb/lib/stream.js":{"offset":26209286,"length":6213,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdb/node_modules/compact-encoding/endian.js":{"offset":26215499,"length":105,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdb/node_modules/compact-encoding/index.js":{"offset":26215604,"length":26406,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdb/node_modules/compact-encoding/lexint.js":{"offset":26242010,"length":2851,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdb/node_modules/compact-encoding/package.json":{"offset":26244861,"length":866,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdb/node_modules/compact-encoding/raw.js":{"offset":26245727,"length":3977,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdb/package.json":{"offset":26249704,"length":1756,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdb/runtime.js":{"offset":26251460,"length":119,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht-address/index.js":{"offset":26251579,"length":357,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht-address/node_modules/compact-encoding/endian.js":{"offset":26251936,"length":105,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht-address/node_modules/compact-encoding/index.js":{"offset":26252041,"length":26406,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht-address/node_modules/compact-encoding/lexint.js":{"offset":26278447,"length":2851,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht-address/node_modules/compact-encoding/package.json":{"offset":26281298,"length":866,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht-address/node_modules/compact-encoding/raw.js":{"offset":26282164,"length":3977,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht-address/package.json":{"offset":26286141,"length":1046,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht-address/spec/hyperschema/index.js":{"offset":26287187,"length":2106,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/index.js":{"offset":26289293,"length":16589,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/announcer.js":{"offset":26305882,"length":7533,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/connect.js":{"offset":26313415,"length":25203,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/connection-pool.js":{"offset":26338618,"length":3050,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/constants.js":{"offset":26341668,"length":1178,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/crypto.js":{"offset":26342846,"length":632,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/encode.js":{"offset":26343478,"length":446,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/errors.js":{"offset":26343924,"length":3713,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/holepuncher.js":{"offset":26347637,"length":10003,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/messages.js":{"offset":26357640,"length":12057,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/nat.js":{"offset":26369697,"length":4714,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/noise-wrap.js":{"offset":26374411,"length":1669,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/persistent.js":{"offset":26376080,"length":8361,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/raw-stream-set.js":{"offset":26384441,"length":1511,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/relay-connection.js":{"offset":26385952,"length":2062,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/router.js":{"offset":26388014,"length":6978,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/secure-payload.js":{"offset":26394992,"length":1491,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/semaphore.js":{"offset":26396483,"length":1577,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/server.js":{"offset":26398060,"length":22065,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/sleeper.js":{"offset":26420125,"length":690,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/lib/socket-pool.js":{"offset":26420815,"length":4343,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/endian.js":{"offset":26425158,"length":105,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/index.js":{"offset":26425263,"length":26406,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/lexint.js":{"offset":26451669,"length":2851,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/package.json":{"offset":26454520,"length":866,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/node_modules/compact-encoding/raw.js":{"offset":26455386,"length":3977,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdht/package.json":{"offset":26459363,"length":2007,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdispatch/lib/errors.js":{"offset":26461370,"length":1055,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdispatch/node_modules/compact-encoding/endian.js":{"offset":26462425,"length":105,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdispatch/node_modules/compact-encoding/index.js":{"offset":26462530,"length":26406,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdispatch/node_modules/compact-encoding/lexint.js":{"offset":26488936,"length":2851,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdispatch/node_modules/compact-encoding/package.json":{"offset":26491787,"length":866,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdispatch/node_modules/compact-encoding/raw.js":{"offset":26492653,"length":3977,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdispatch/package.json":{"offset":26496630,"length":1622,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperdispatch/runtime.cjs":{"offset":26498252,"length":199,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperschema/node_modules/compact-encoding/endian.js":{"offset":26498451,"length":105,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperschema/node_modules/compact-encoding/index.js":{"offset":26498556,"length":26406,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperschema/node_modules/compact-encoding/lexint.js":{"offset":26524962,"length":2851,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperschema/node_modules/compact-encoding/package.json":{"offset":26527813,"length":866,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperschema/node_modules/compact-encoding/raw.js":{"offset":26528679,"length":3977,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperschema/package.json":{"offset":26532656,"length":1555,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperschema/runtime.cjs":{"offset":26534211,"length":54,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperswarm/index.js":{"offset":26534265,"length":18589,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperswarm/lib/bulk-timer.js":{"offset":26552854,"length":728,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperswarm/lib/connection-set.js":{"offset":26553582,"length":823,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperswarm/lib/peer-discovery.js":{"offset":26554405,"length":9296,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperswarm/lib/peer-info.js":{"offset":26563701,"length":2688,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperswarm/lib/retry-timer.js":{"offset":26566389,"length":1889,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/hyperswarm/package.json":{"offset":26568278,"length":1515,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/index-encoder/index.js":{"offset":26569793,"length":10596,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/index-encoder/package.json":{"offset":26580389,"length":928,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/is-options/index.js":{"offset":26581317,"length":140,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/is-options/package.json":{"offset":26581457,"length":605,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/kademlia-routing-table/index.js":{"offset":26582062,"length":4145,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/kademlia-routing-table/package.json":{"offset":26586207,"length":967,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/keet-identity-key/index.js":{"offset":26587174,"length":6320,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/keet-identity-key/lib/crypto.js":{"offset":26593494,"length":552,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/keet-identity-key/lib/encoding.js":{"offset":26594046,"length":3695,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/keet-identity-key/lib/keychain.js":{"offset":26597741,"length":3080,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/keet-identity-key/node_modules/compact-encoding/endian.js":{"offset":26600821,"length":105,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/keet-identity-key/node_modules/compact-encoding/index.js":{"offset":26600926,"length":26406,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/keet-identity-key/node_modules/compact-encoding/lexint.js":{"offset":26627332,"length":2851,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/keet-identity-key/node_modules/compact-encoding/package.json":{"offset":26630183,"length":866,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/keet-identity-key/node_modules/compact-encoding/raw.js":{"offset":26631049,"length":3977,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/keet-identity-key/package.json":{"offset":26635026,"length":887,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/multiformats/dist/src/bases/base.js":{"offset":26635913,"length":6266,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/multiformats/dist/src/bases/base32.js":{"offset":26642179,"length":1443,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/multiformats/dist/src/bases/base36.js":{"offset":26643622,"length":327,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/multiformats/dist/src/bases/base58.js":{"offset":26643949,"length":379,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/multiformats/dist/src/bytes.js":{"offset":26644328,"length":1246,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/multiformats/dist/src/cid.js":{"offset":26645574,"length":13430,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/multiformats/dist/src/hashes/digest.js":{"offset":26659004,"length":1915,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/multiformats/dist/src/link/interface.js":{"offset":26660919,"length":48,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/multiformats/dist/src/varint.js":{"offset":26660967,"length":398,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/multiformats/dist/src/vendor/base-x.js":{"offset":26661365,"length":5458,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/multiformats/dist/src/vendor/varint.js":{"offset":26666823,"length":2107,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/multiformats/package.json":{"offset":26668930,"length":8176,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/mutexify/index.js":{"offset":26677106,"length":536,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/mutexify/package.json":{"offset":26677642,"length":679,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/mutexify/promise.js":{"offset":26678321,"length":324,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/nanoassert/index.js":{"offset":26678645,"length":438,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/nanoassert/package.json":{"offset":26679083,"length":647,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/nat-sampler/index.js":{"offset":26679730,"length":1550,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/nat-sampler/package.json":{"offset":26681280,"length":608,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-curve-ed/index.js":{"offset":26681888,"length":1642,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-curve-ed/package.json":{"offset":26683530,"length":808,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-handshake/cipher.js":{"offset":26684338,"length":2817,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-handshake/dh.js":{"offset":26687155,"length":1439,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-handshake/hkdf.js":{"offset":26688594,"length":1092,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-handshake/hmac.js":{"offset":26689686,"length":1273,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-handshake/noise.js":{"offset":26690959,"length":6437,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-handshake/package.json":{"offset":26697396,"length":638,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/noise-handshake/symmetric-state.js":{"offset":26698034,"length":2206,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protocol-buffers-encodings/index.js":{"offset":26700240,"length":6489,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protocol-buffers-encodings/package.json":{"offset":26706729,"length":719,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux-rpc/index.js":{"offset":26707448,"length":9087,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux-rpc/lib/errors.js":{"offset":26716535,"length":1273,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux-rpc/node_modules/compact-encoding/endian.js":{"offset":26717808,"length":105,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux-rpc/node_modules/compact-encoding/index.js":{"offset":26717913,"length":26406,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux-rpc/node_modules/compact-encoding/lexint.js":{"offset":26744319,"length":2851,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux-rpc/node_modules/compact-encoding/package.json":{"offset":26747170,"length":866,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux-rpc/node_modules/compact-encoding/raw.js":{"offset":26748036,"length":3977,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux-rpc/package.json":{"offset":26752013,"length":1188,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux-wakeup/index.js":{"offset":26753201,"length":16824,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux-wakeup/package.json":{"offset":26770025,"length":972,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux-wakeup/spec/hyperschema/index.js":{"offset":26770997,"length":3335,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux/index.js":{"offset":26774332,"length":19741,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux/node_modules/compact-encoding/endian.js":{"offset":26794073,"length":105,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux/node_modules/compact-encoding/index.js":{"offset":26794178,"length":26406,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux/node_modules/compact-encoding/lexint.js":{"offset":26820584,"length":2851,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux/node_modules/compact-encoding/package.json":{"offset":26823435,"length":866,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux/node_modules/compact-encoding/raw.js":{"offset":26824301,"length":3977,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/protomux/package.json":{"offset":26828278,"length":1059,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/queue-tick/package.json":{"offset":26829337,"length":669,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/queue-tick/process-next-tick.js":{"offset":26830006,"length":160,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/queue-tick/queue-microtask.js":{"offset":26830166,"length":108,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/quickbit-native/binding.js":{"offset":26830274,"length":90,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/quickbit-native/index.js":{"offset":26830364,"length":4683,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/quickbit-native/package.json":{"offset":26835047,"length":1104,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/quickbit-universal/fallback.js":{"offset":26836151,"length":10204,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/quickbit-universal/index.js":{"offset":26846355,"length":442,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/quickbit-universal/package.json":{"offset":26846797,"length":908,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rache/index.js":{"offset":26847705,"length":2463,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rache/package.json":{"offset":26850168,"length":602,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/random-array-iterator/index.js":{"offset":26850770,"length":1001,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/random-array-iterator/package.json":{"offset":26851771,"length":700,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/ready-resource/index.js":{"offset":26852471,"length":1091,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/ready-resource/package.json":{"offset":26853562,"length":812,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/record-cache/index.js":{"offset":26854374,"length":3668,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/record-cache/package.json":{"offset":26858042,"length":612,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/refcounter/index.js":{"offset":26858654,"length":611,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/refcounter/package.json":{"offset":26859265,"length":451,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/require-addon/lib/bare.js":{"offset":26859716,"length":45,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/require-addon/package.json":{"offset":26859761,"length":1449,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/resolve-reject-promise/index.js":{"offset":26861210,"length":443,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/resolve-reject-promise/package.json":{"offset":26861653,"length":581,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/resource-on-exit/index.js":{"offset":26862234,"length":361,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/resource-on-exit/package.json":{"offset":26862595,"length":496,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/binding.js":{"offset":26863091,"length":90,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/index.js":{"offset":26863181,"length":5304,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/lib/batch.js":{"offset":26868485,"length":9605,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/lib/column-family.js":{"offset":26878090,"length":2930,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/lib/constants.js":{"offset":26881020,"length":621,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/lib/filter-policy.js":{"offset":26881641,"length":437,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/lib/iterator.js":{"offset":26882078,"length":4311,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/lib/snapshot.js":{"offset":26886389,"length":503,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/lib/state.js":{"offset":26886892,"length":13115,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/node_modules/compact-encoding/endian.js":{"offset":26900007,"length":105,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/node_modules/compact-encoding/index.js":{"offset":26900112,"length":26406,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/node_modules/compact-encoding/lexint.js":{"offset":26926518,"length":2851,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/node_modules/compact-encoding/package.json":{"offset":26929369,"length":866,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/node_modules/compact-encoding/raw.js":{"offset":26930235,"length":3977,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/rocksdb-native/package.json":{"offset":26934212,"length":1863,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/safety-catch/index.js":{"offset":26936075,"length":543,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/safety-catch/package.json":{"offset":26936618,"length":547,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/scope-lock/index.js":{"offset":26937165,"length":1821,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/scope-lock/package.json":{"offset":26938986,"length":611,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/shuffled-priority-queue/index.js":{"offset":26939597,"length":2607,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/shuffled-priority-queue/package.json":{"offset":26942204,"length":691,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/signal-promise/index.js":{"offset":26942895,"length":1252,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/signal-promise/package.json":{"offset":26944147,"length":503,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/signed-varint/index.js":{"offset":26944650,"length":435,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/signed-varint/package.json":{"offset":26945085,"length":523,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/simdle-native/binding.js":{"offset":26945608,"length":90,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/simdle-native/index.js":{"offset":26945698,"length":3474,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/simdle-native/package.json":{"offset":26949172,"length":1115,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/simdle-universal/fallback.js":{"offset":26950287,"length":5137,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/simdle-universal/index.js":{"offset":26955424,"length":103,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/simdle-universal/package.json":{"offset":26955527,"length":879,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/simdle-universal/scalar.js":{"offset":26956406,"length":469,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-hmac/hash/sha256.js":{"offset":26956875,"length":284,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-hmac/hash/sha512.js":{"offset":26957159,"length":284,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-hmac/index.js":{"offset":26957443,"length":2063,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-hmac/package.json":{"offset":26959506,"length":670,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-native/binding.js":{"offset":26960176,"length":89,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-native/index.js":{"offset":26960265,"length":107894,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-native/package.json":{"offset":27068159,"length":1478,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-secretstream/index.js":{"offset":27069637,"length":2257,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-secretstream/package.json":{"offset":27071894,"length":657,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-universal/index.js":{"offset":27072551,"length":42,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sodium-universal/package.json":{"offset":27072593,"length":1217,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/streamx/index.js":{"offset":27073810,"length":34248,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/streamx/lib/errors.js":{"offset":27108058,"length":1096,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/streamx/package.json":{"offset":27109154,"length":1225,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sub-encoder/index.js":{"offset":27110379,"length":1968,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/sub-encoder/package.json":{"offset":27112347,"length":908,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/teex/index.js":{"offset":27113255,"length":1107,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/teex/package.json":{"offset":27114362,"length":608,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/text-decoder/index.js":{"offset":27114970,"length":1371,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/text-decoder/lib/pass-through-decoder.js":{"offset":27116341,"length":269,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/text-decoder/lib/utf8-decoder.js":{"offset":27116610,"length":4429,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/text-decoder/package.json":{"offset":27121039,"length":990,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/time-ordered-set/index.js":{"offset":27122029,"length":1444,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/time-ordered-set/package.json":{"offset":27123473,"length":666,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/timeout-refresh/browser.js":{"offset":27124139,"length":1098,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/timeout-refresh/index.js":{"offset":27125237,"length":184,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/timeout-refresh/node.js":{"offset":27125421,"length":928,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/timeout-refresh/package.json":{"offset":27126349,"length":619,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/tiny-buffer-map/index.js":{"offset":27126968,"length":936,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/tiny-buffer-map/package.json":{"offset":27127904,"length":650,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/udx-native/binding.js":{"offset":27128554,"length":90,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/udx-native/lib/ip.js":{"offset":27128644,"length":2204,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/udx-native/lib/network-interfaces.js":{"offset":27130848,"length":1341,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/udx-native/lib/socket.js":{"offset":27132189,"length":7557,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/udx-native/lib/stream.js":{"offset":27139746,"length":13050,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/udx-native/lib/udx.js":{"offset":27152796,"length":2868,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/udx-native/package.json":{"offset":27155664,"length":1665,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/unordered-set/index.js":{"offset":27157329,"length":677,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/unordered-set/package.json":{"offset":27158006,"length":654,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/unslab/index.js":{"offset":27158660,"length":913,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/unslab/package.json":{"offset":27159573,"length":613,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/varint/decode.js":{"offset":27160186,"length":508,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/varint/encode.js":{"offset":27160694,"length":452,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/varint/index.js":{"offset":27161146,"length":134,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/varint/length.js":{"offset":27161280,"length":471,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/varint/package.json":{"offset":27161751,"length":511,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/which-runtime/index.js":{"offset":27162262,"length":1469,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/which-runtime/package.json":{"offset":27163731,"length":863,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/xache/index.js":{"offset":27164594,"length":2378,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/xache/package.json":{"offset":27166972,"length":584,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/z32/index.js":{"offset":27167556,"length":2654,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/node_modules/z32/package.json":{"offset":27170210,"length":701,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/package.json":{"offset":27170911,"length":1441,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/spec/state-base/contract/hyperdb/index.js":{"offset":27172352,"length":2637,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/spec/state-base/contract/hyperdb/messages.js":{"offset":27174989,"length":3767,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/spec/state-base/contract/hyperdispatch/index.js":{"offset":27178756,"length":2669,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/spec/state-base/contract/hyperdispatch/messages.js":{"offset":27181425,"length":2877,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-room/spec/state-base/package.json":{"offset":27184302,"length":23,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/lib/account-registry.js":{"offset":27184325,"length":1535,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/lib/blob-pointer-store.js":{"offset":27185860,"length":11248,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/lib/blob-store.js":{"offset":27197108,"length":2977,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/lib/corestore.js":{"offset":27200085,"length":1775,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/lib/overlay-blob-store.js":{"offset":27201860,"length":8778,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/lib/overlay-repo-store.js":{"offset":27210638,"length":20497,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/lib/pointer-substrate.js":{"offset":27231135,"length":12507,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/lib/read-view.js":{"offset":27243642,"length":6487,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/lib/tid.js":{"offset":27250129,"length":1681,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/@hyperswarm/secret-stream/index.js":{"offset":27251810,"length":16722,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/@hyperswarm/secret-stream/lib/bridge.js":{"offset":27268532,"length":1273,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/@hyperswarm/secret-stream/lib/handshake.js":{"offset":27269805,"length":1950,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/@hyperswarm/secret-stream/package.json":{"offset":27271755,"length":1132,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/@ipld/dag-cbor/package.json":{"offset":27272887,"length":3961,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/@ipld/dag-cbor/src/index.js":{"offset":27276848,"length":4040,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/lib/car.js":{"offset":27280888,"length":3112,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/lib/cid.js":{"offset":27284000,"length":1924,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/lib/commit.js":{"offset":27285924,"length":1471,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/lib/mst.js":{"offset":27287395,"length":13309,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/lib/repo.js":{"offset":27300704,"length":4610,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/package.json":{"offset":27305314,"length":3961,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@ipld/dag-cbor/src/index.js":{"offset":27309275,"length":4040,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/_shortw_utils.js":{"offset":27313315,"length":589,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/curve.js":{"offset":27313904,"length":18539,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/hash-to-curve.js":{"offset":27332443,"length":8097,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/modular.js":{"offset":27340540,"length":21647,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/abstract/weierstrass.js":{"offset":27362187,"length":58901,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/package.json":{"offset":27421088,"length":47,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/secp256k1.js":{"offset":27421135,"length":12507,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/curves/esm/utils.js":{"offset":27433642,"length":12067,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/_md.js":{"offset":27445709,"length":6192,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/_u64.js":{"offset":27451901,"length":3081,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/crypto.js":{"offset":27454982,"length":146,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/hmac.js":{"offset":27455128,"length":2962,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/package.json":{"offset":27458090,"length":147,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/sha2.js":{"offset":27458237,"length":16832,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/@noble/hashes/esm/utils.js":{"offset":27475069,"length":10538,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/cborg.js":{"offset":27485607,"length":944,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/0uint.js":{"offset":27486551,"length":6580,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/1negint.js":{"offset":27493131,"length":2980,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/2bytes.js":{"offset":27496111,"length":3451,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/3string.js":{"offset":27499562,"length":3340,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/4array.js":{"offset":27502902,"length":2944,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/5map.js":{"offset":27505846,"length":2917,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/6tag.js":{"offset":27508763,"length":1957,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/7float.js":{"offset":27510720,"length":8633,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/bl.js":{"offset":27519353,"length":5316,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/byte-utils.js":{"offset":27524669,"length":8172,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/common.js":{"offset":27532841,"length":598,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/decode.js":{"offset":27533439,"length":9008,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/encode.js":{"offset":27542447,"length":21407,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/is.js":{"offset":27563854,"length":2061,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/jump.js":{"offset":27565915,"length":7859,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/tagged.js":{"offset":27573774,"length":2821,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/lib/token.js":{"offset":27576595,"length":2019,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/cborg/package.json":{"offset":27578614,"length":4241,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base.js":{"offset":27582855,"length":6266,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base32.js":{"offset":27589121,"length":1443,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base36.js":{"offset":27590564,"length":327,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bases/base58.js":{"offset":27590891,"length":379,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/bytes.js":{"offset":27591270,"length":1246,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/cid.js":{"offset":27592516,"length":13430,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/codecs/raw.js":{"offset":27605946,"length":238,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/hashes/digest.js":{"offset":27606184,"length":1915,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/link/interface.js":{"offset":27608099,"length":48,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/varint.js":{"offset":27608147,"length":398,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/vendor/base-x.js":{"offset":27608545,"length":5458,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/dist/src/vendor/varint.js":{"offset":27614003,"length":2107,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/node_modules/multiformats/package.json":{"offset":27616110,"length":8176,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/atproto-repo/package.json":{"offset":27624286,"length":652,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/b4a/index.js":{"offset":27624938,"length":4054,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/b4a/package.json":{"offset":27628992,"length":1245,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-ansi-escapes/index.js":{"offset":27630237,"length":2255,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-ansi-escapes/package.json":{"offset":27632492,"length":1178,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-assert/index.js":{"offset":27633670,"length":2192,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-assert/package.json":{"offset":27635862,"length":835,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-events/index.js":{"offset":27636697,"length":8307,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-events/lib/errors.js":{"offset":27645004,"length":671,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-events/package.json":{"offset":27645675,"length":1504,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-fs/binding.js":{"offset":27647179,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-fs/index.js":{"offset":27647212,"length":58907,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-fs/lib/constants.js":{"offset":27706119,"length":1494,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-fs/lib/errors.js":{"offset":27707613,"length":1163,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-fs/package.json":{"offset":27708776,"length":1654,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-fs/promises.js":{"offset":27710430,"length":2401,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-inspect/binding.js":{"offset":27712831,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-inspect/index.js":{"offset":27712864,"length":23856,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-inspect/package.json":{"offset":27736720,"length":1041,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-os/binding.js":{"offset":27737761,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-os/index.js":{"offset":27737794,"length":5216,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-os/lib/constants.js":{"offset":27743010,"length":143,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-os/lib/errors.js":{"offset":27743153,"length":453,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-os/package.json":{"offset":27743606,"length":1257,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-path/index.js":{"offset":27744863,"length":287,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-path/lib/constants.js":{"offset":27745150,"length":247,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-path/lib/posix.js":{"offset":27745397,"length":6005,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-path/lib/shared.js":{"offset":27751402,"length":1926,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-path/lib/win32.js":{"offset":27753328,"length":13591,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-path/package.json":{"offset":27766919,"length":1036,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-stream/index.js":{"offset":27767955,"length":10904,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-stream/package.json":{"offset":27778859,"length":1676,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-stream/web.js":{"offset":27780535,"length":13980,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-type/binding.js":{"offset":27794515,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-type/index.js":{"offset":27794548,"length":4566,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-type/package.json":{"offset":27799114,"length":938,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-url/binding.js":{"offset":27800052,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-url/index.js":{"offset":27800085,"length":9449,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-url/lib/errors.js":{"offset":27809534,"length":778,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-url/lib/url-search-params.js":{"offset":27810312,"length":4331,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/bare-url/package.json":{"offset":27814643,"length":1219,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/big-sparse-array/index.js":{"offset":27815862,"length":2471,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/big-sparse-array/package.json":{"offset":27818333,"length":636,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/cborg.js":{"offset":27818969,"length":944,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/0uint.js":{"offset":27819913,"length":6580,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/1negint.js":{"offset":27826493,"length":2980,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/2bytes.js":{"offset":27829473,"length":3451,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/3string.js":{"offset":27832924,"length":3340,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/4array.js":{"offset":27836264,"length":2944,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/5map.js":{"offset":27839208,"length":2917,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/6tag.js":{"offset":27842125,"length":1957,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/7float.js":{"offset":27844082,"length":8633,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/bl.js":{"offset":27852715,"length":5316,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/byte-utils.js":{"offset":27858031,"length":8172,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/common.js":{"offset":27866203,"length":598,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/decode.js":{"offset":27866801,"length":9008,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/encode.js":{"offset":27875809,"length":21407,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/is.js":{"offset":27897216,"length":2061,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/jump.js":{"offset":27899277,"length":7859,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/tagged.js":{"offset":27907136,"length":2821,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/lib/token.js":{"offset":27909957,"length":2019,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/cborg/package.json":{"offset":27911976,"length":4241,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/codecs/index.js":{"offset":27916217,"length":2416,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/codecs/package.json":{"offset":27918633,"length":655,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/compact-encoding/endian.js":{"offset":27919288,"length":105,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/compact-encoding/index.js":{"offset":27919393,"length":26406,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/compact-encoding/lexint.js":{"offset":27945799,"length":2851,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/compact-encoding/package.json":{"offset":27948650,"length":866,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/compact-encoding/raw.js":{"offset":27949516,"length":3977,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/corestore/index.js":{"offset":27953493,"length":19847,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/corestore/lib/audit.js":{"offset":27973340,"length":475,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/corestore/lib/notify.js":{"offset":27973815,"length":630,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/corestore/package.json":{"offset":27974445,"length":1350,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/debounceify/index.js":{"offset":27975795,"length":585,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/debounceify/package.json":{"offset":27976380,"length":567,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/device-file/index.js":{"offset":27976947,"length":6394,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/device-file/package.json":{"offset":27983341,"length":1190,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/events-universal/bare.js":{"offset":27984531,"length":40,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/events-universal/package.json":{"offset":27984571,"length":908,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/fast-fifo/fixed-size.js":{"offset":27985479,"length":875,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/fast-fifo/index.js":{"offset":27986354,"length":972,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/fast-fifo/package.json":{"offset":27987326,"length":682,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/fd-lock/index.js":{"offset":27988008,"length":1755,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/fd-lock/package.json":{"offset":27989763,"length":1099,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/flat-tree/index.js":{"offset":27990862,"length":8164,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/flat-tree/package.json":{"offset":27999026,"length":631,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/fs-native-extensions/binding.js":{"offset":27999657,"length":90,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/fs-native-extensions/index.js":{"offset":27999747,"length":7239,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/fs-native-extensions/package.json":{"offset":28006986,"length":1790,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hyperbee/index.js":{"offset":28008776,"length":46445,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hyperbee/iterators/diff.js":{"offset":28055221,"length":5358,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hyperbee/iterators/history.js":{"offset":28060579,"length":1631,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hyperbee/iterators/local.js":{"offset":28062210,"length":1170,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hyperbee/iterators/range.js":{"offset":28063380,"length":5869,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hyperbee/lib/extension.js":{"offset":28069249,"length":3488,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hyperbee/lib/messages.js":{"offset":28072737,"length":28162,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hyperbee/package.json":{"offset":28100899,"length":1585,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-crypto/index.js":{"offset":28102484,"length":5031,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-crypto/package.json":{"offset":28107515,"length":1007,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-errors/index.js":{"offset":28108522,"length":4896,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-errors/package.json":{"offset":28113418,"length":688,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-id-encoding/index.js":{"offset":28114106,"length":923,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-id-encoding/package.json":{"offset":28115029,"length":799,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-storage/encoding/external.js":{"offset":28115828,"length":264,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-storage/encoding/spec/hyperschema/index.js":{"offset":28116092,"length":16796,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-storage/index.js":{"offset":28132888,"length":33493,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-storage/lib/block-dependency-stream.js":{"offset":28166381,"length":2557,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-storage/lib/close-error-stream.js":{"offset":28168938,"length":276,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-storage/lib/keys.js":{"offset":28169214,"length":8751,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-storage/lib/streams.js":{"offset":28177965,"length":5686,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-storage/lib/tx.js":{"offset":28183651,"length":11683,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-storage/lib/view.js":{"offset":28195334,"length":8379,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-storage/migrations/0/index.js":{"offset":28203713,"length":20125,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-storage/migrations/0/messages.js":{"offset":28223838,"length":26402,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-storage/migrations/1/index.js":{"offset":28250240,"length":1181,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore-storage/package.json":{"offset":28251421,"length":1827,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/index.js":{"offset":28253248,"length":40241,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/audit.js":{"offset":28293489,"length":3834,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/bit-interlude.js":{"offset":28297323,"length":4257,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/bitfield.js":{"offset":28301580,"length":12115,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/caps.js":{"offset":28313695,"length":1537,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/compat.js":{"offset":28315232,"length":477,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/copy-prologue.js":{"offset":28315709,"length":5999,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/core.js":{"offset":28321708,"length":28356,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/default-encryption.js":{"offset":28350064,"length":3453,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/download.js":{"offset":28353517,"length":1278,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/feature-flags.js":{"offset":28354795,"length":38,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/fully-remote-proof.js":{"offset":28354833,"length":3470,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/hotswap-queue.js":{"offset":28358303,"length":1498,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/info.js":{"offset":28359801,"length":1517,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/inspect.js":{"offset":28361318,"length":1983,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/mark-bitfield.js":{"offset":28363301,"length":2589,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/merkle-tree.js":{"offset":28365890,"length":34353,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/messages.js":{"offset":28400243,"length":28313,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/multisig.js":{"offset":28428556,"length":2851,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/mutex.js":{"offset":28431407,"length":1028,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/receiver-queue.js":{"offset":28432435,"length":1413,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/remote-bitfield.js":{"offset":28433848,"length":8124,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/replicator.js":{"offset":28441972,"length":88868,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/session-state.js":{"offset":28530840,"length":36297,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/streams.js":{"offset":28567137,"length":3034,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/verifier.js":{"offset":28570171,"length":9926,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/lib/wants.js":{"offset":28580097,"length":7204,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hypercore/package.json":{"offset":28587301,"length":2196,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hyperschema/package.json":{"offset":28589497,"length":1555,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/hyperschema/runtime.cjs":{"offset":28591052,"length":54,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/index-encoder/index.js":{"offset":28591106,"length":10596,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/index-encoder/package.json":{"offset":28601702,"length":928,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/is-options/index.js":{"offset":28602630,"length":140,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/is-options/package.json":{"offset":28602770,"length":605,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/bases/base.js":{"offset":28603375,"length":6266,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/bases/base32.js":{"offset":28609641,"length":1443,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/bases/base36.js":{"offset":28611084,"length":327,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/bases/base58.js":{"offset":28611411,"length":379,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/bytes.js":{"offset":28611790,"length":1246,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/cid.js":{"offset":28613036,"length":13430,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/hashes/digest.js":{"offset":28626466,"length":1915,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/link/interface.js":{"offset":28628381,"length":48,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/varint.js":{"offset":28628429,"length":398,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/vendor/base-x.js":{"offset":28628827,"length":5458,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/multiformats/dist/src/vendor/varint.js":{"offset":28634285,"length":2107,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/multiformats/package.json":{"offset":28636392,"length":8176,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/mutexify/index.js":{"offset":28644568,"length":536,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/mutexify/package.json":{"offset":28645104,"length":679,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/mutexify/promise.js":{"offset":28645783,"length":324,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/nanoassert/index.js":{"offset":28646107,"length":438,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/nanoassert/package.json":{"offset":28646545,"length":647,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/noise-curve-ed/index.js":{"offset":28647192,"length":1642,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/noise-curve-ed/package.json":{"offset":28648834,"length":808,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/noise-handshake/cipher.js":{"offset":28649642,"length":2817,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/noise-handshake/dh.js":{"offset":28652459,"length":1439,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/noise-handshake/hkdf.js":{"offset":28653898,"length":1092,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/noise-handshake/hmac.js":{"offset":28654990,"length":1273,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/noise-handshake/noise.js":{"offset":28656263,"length":6437,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/noise-handshake/package.json":{"offset":28662700,"length":638,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/noise-handshake/symmetric-state.js":{"offset":28663338,"length":2206,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/protocol-buffers-encodings/index.js":{"offset":28665544,"length":6489,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/protocol-buffers-encodings/package.json":{"offset":28672033,"length":719,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/protomux/index.js":{"offset":28672752,"length":19741,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/protomux/package.json":{"offset":28692493,"length":1059,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/queue-tick/package.json":{"offset":28693552,"length":669,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/queue-tick/process-next-tick.js":{"offset":28694221,"length":160,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/queue-tick/queue-microtask.js":{"offset":28694381,"length":108,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/quickbit-native/binding.js":{"offset":28694489,"length":90,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/quickbit-native/index.js":{"offset":28694579,"length":4683,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/quickbit-native/package.json":{"offset":28699262,"length":1104,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/quickbit-universal/fallback.js":{"offset":28700366,"length":10204,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/quickbit-universal/index.js":{"offset":28710570,"length":442,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/quickbit-universal/package.json":{"offset":28711012,"length":908,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/rache/index.js":{"offset":28711920,"length":2463,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/rache/package.json":{"offset":28714383,"length":602,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/random-array-iterator/index.js":{"offset":28714985,"length":1001,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/random-array-iterator/package.json":{"offset":28715986,"length":700,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/ready-resource/index.js":{"offset":28716686,"length":1091,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/ready-resource/package.json":{"offset":28717777,"length":812,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/refcounter/index.js":{"offset":28718589,"length":611,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/refcounter/package.json":{"offset":28719200,"length":451,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/require-addon/lib/bare.js":{"offset":28719651,"length":45,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/require-addon/package.json":{"offset":28719696,"length":1449,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/resolve-reject-promise/index.js":{"offset":28721145,"length":443,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/resolve-reject-promise/package.json":{"offset":28721588,"length":581,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/resource-on-exit/index.js":{"offset":28722169,"length":361,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/resource-on-exit/package.json":{"offset":28722530,"length":496,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/rocksdb-native/binding.js":{"offset":28723026,"length":90,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/rocksdb-native/index.js":{"offset":28723116,"length":5304,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/rocksdb-native/lib/batch.js":{"offset":28728420,"length":9605,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/rocksdb-native/lib/column-family.js":{"offset":28738025,"length":2930,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/rocksdb-native/lib/constants.js":{"offset":28740955,"length":621,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/rocksdb-native/lib/filter-policy.js":{"offset":28741576,"length":437,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/rocksdb-native/lib/iterator.js":{"offset":28742013,"length":4311,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/rocksdb-native/lib/snapshot.js":{"offset":28746324,"length":503,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/rocksdb-native/lib/state.js":{"offset":28746827,"length":13115,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/rocksdb-native/package.json":{"offset":28759942,"length":1863,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/safety-catch/index.js":{"offset":28761805,"length":543,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/safety-catch/package.json":{"offset":28762348,"length":547,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/scope-lock/index.js":{"offset":28762895,"length":1821,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/scope-lock/package.json":{"offset":28764716,"length":611,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/signal-promise/index.js":{"offset":28765327,"length":1252,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/signal-promise/package.json":{"offset":28766579,"length":503,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/signed-varint/index.js":{"offset":28767082,"length":435,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/signed-varint/package.json":{"offset":28767517,"length":523,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/simdle-native/binding.js":{"offset":28768040,"length":90,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/simdle-native/index.js":{"offset":28768130,"length":3474,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/simdle-native/package.json":{"offset":28771604,"length":1115,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/simdle-universal/fallback.js":{"offset":28772719,"length":5137,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/simdle-universal/index.js":{"offset":28777856,"length":103,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/simdle-universal/package.json":{"offset":28777959,"length":879,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/simdle-universal/scalar.js":{"offset":28778838,"length":469,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/sodium-native/binding.js":{"offset":28779307,"length":89,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/sodium-native/index.js":{"offset":28779396,"length":107894,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/sodium-native/package.json":{"offset":28887290,"length":1478,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/sodium-secretstream/index.js":{"offset":28888768,"length":2257,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/sodium-secretstream/package.json":{"offset":28891025,"length":657,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/sodium-universal/index.js":{"offset":28891682,"length":42,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/sodium-universal/package.json":{"offset":28891724,"length":1217,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/streamx/index.js":{"offset":28892941,"length":34248,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/streamx/lib/errors.js":{"offset":28927189,"length":1096,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/streamx/package.json":{"offset":28928285,"length":1225,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/teex/index.js":{"offset":28929510,"length":1107,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/teex/package.json":{"offset":28930617,"length":608,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/text-decoder/index.js":{"offset":28931225,"length":1371,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/text-decoder/lib/pass-through-decoder.js":{"offset":28932596,"length":269,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/text-decoder/lib/utf8-decoder.js":{"offset":28932865,"length":4429,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/text-decoder/package.json":{"offset":28937294,"length":990,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/timeout-refresh/browser.js":{"offset":28938284,"length":1098,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/timeout-refresh/index.js":{"offset":28939382,"length":184,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/timeout-refresh/node.js":{"offset":28939566,"length":928,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/timeout-refresh/package.json":{"offset":28940494,"length":619,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/unslab/index.js":{"offset":28941113,"length":913,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/unslab/package.json":{"offset":28942026,"length":613,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/varint/decode.js":{"offset":28942639,"length":508,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/varint/encode.js":{"offset":28943147,"length":452,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/varint/index.js":{"offset":28943599,"length":134,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/varint/length.js":{"offset":28943733,"length":471,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/varint/package.json":{"offset":28944204,"length":511,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/which-runtime/index.js":{"offset":28944715,"length":1469,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/which-runtime/package.json":{"offset":28946184,"length":863,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/xache/index.js":{"offset":28947047,"length":2477,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/xache/package.json":{"offset":28949524,"length":672,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/z32/index.js":{"offset":28950196,"length":2654,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/node_modules/z32/package.json":{"offset":28952850,"length":701,"mode":420},"/node_modules/hyper-proto-peer/node_modules/atproto-store/package.json":{"offset":28953551,"length":932,"mode":420},"/node_modules/hyper-proto-peer/node_modules/b4a/index.js":{"offset":28954483,"length":4054,"mode":420},"/node_modules/hyper-proto-peer/node_modules/b4a/package.json":{"offset":28958537,"length":1245,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-abort/binding.js":{"offset":28959782,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-abort/index.js":{"offset":28959815,"length":69,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-abort/package.json":{"offset":28959884,"length":886,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-ansi-escapes/index.js":{"offset":28960770,"length":2255,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-ansi-escapes/package.json":{"offset":28963025,"length":1178,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-assert/index.js":{"offset":28964203,"length":2192,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-assert/package.json":{"offset":28966395,"length":835,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-buffer/binding.js":{"offset":28967230,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-buffer/index.js":{"offset":28967263,"length":28020,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-buffer/lib/ascii.js":{"offset":28995283,"length":613,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-buffer/lib/base64.js":{"offset":28995896,"length":531,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-buffer/lib/base64url.js":{"offset":28996427,"length":534,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-buffer/lib/constants.js":{"offset":28996961,"length":74,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-buffer/lib/hex.js":{"offset":28997035,"length":392,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-buffer/lib/latin1.js":{"offset":28997427,"length":392,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-buffer/lib/utf16le.js":{"offset":28997819,"length":398,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-buffer/lib/utf8.js":{"offset":28998217,"length":519,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-buffer/package.json":{"offset":28998736,"length":1324,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-dns/binding.js":{"offset":29000060,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-dns/index.js":{"offset":29000093,"length":1345,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-dns/package.json":{"offset":29001438,"length":968,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-env/index.js":{"offset":29002406,"length":1023,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-env/package.json":{"offset":29003429,"length":649,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-events/index.js":{"offset":29004078,"length":8307,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-events/lib/errors.js":{"offset":29012385,"length":671,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-events/package.json":{"offset":29013056,"length":1504,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-fetch/global.js":{"offset":29014560,"length":144,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-fetch/index.js":{"offset":29014704,"length":4061,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-fetch/lib/body.js":{"offset":29018765,"length":6397,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-fetch/lib/errors.js":{"offset":29025162,"length":1207,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-fetch/lib/headers.js":{"offset":29026369,"length":5064,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-fetch/lib/request.js":{"offset":29031433,"length":1690,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-fetch/lib/response-stream.js":{"offset":29033123,"length":1134,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-fetch/lib/response.js":{"offset":29034257,"length":1426,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-fetch/package.json":{"offset":29035683,"length":2066,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-form-data/index.js":{"offset":29037749,"length":5715,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-form-data/lib/errors.js":{"offset":29043464,"length":412,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-form-data/package.json":{"offset":29043876,"length":1004,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-fs/binding.js":{"offset":29044880,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-fs/index.js":{"offset":29044913,"length":58907,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-fs/lib/constants.js":{"offset":29103820,"length":1494,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-fs/lib/errors.js":{"offset":29105314,"length":1163,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-fs/package.json":{"offset":29106477,"length":1654,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-fs/promises.js":{"offset":29108131,"length":2401,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-hrtime/binding.js":{"offset":29110532,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-hrtime/index.js":{"offset":29110565,"length":319,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-hrtime/package.json":{"offset":29110884,"length":905,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-http-parser/index.js":{"offset":29111789,"length":17995,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-http-parser/lib/errors.js":{"offset":29129784,"length":845,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-http-parser/package.json":{"offset":29130629,"length":907,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-http1/index.js":{"offset":29131536,"length":2188,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-http1/lib/agent.js":{"offset":29133724,"length":4498,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-http1/lib/client-connection.js":{"offset":29138222,"length":3663,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-http1/lib/client-request.js":{"offset":29141885,"length":3734,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-http1/lib/constants.js":{"offset":29145619,"length":2016,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-http1/lib/errors.js":{"offset":29147635,"length":889,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-http1/lib/incoming-message.js":{"offset":29148524,"length":1568,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-http1/lib/outgoing-message.js":{"offset":29150092,"length":1635,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-http1/lib/server-connection.js":{"offset":29151727,"length":4041,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-http1/lib/server-response.js":{"offset":29155768,"length":3704,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-http1/lib/server.js":{"offset":29159472,"length":977,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-http1/lib/validate.js":{"offset":29160449,"length":1458,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-http1/package.json":{"offset":29161907,"length":1510,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-https/index.js":{"offset":29163417,"length":1498,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-https/lib/agent.js":{"offset":29164915,"length":394,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-https/lib/client-request.js":{"offset":29165309,"length":464,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-https/lib/server.js":{"offset":29165773,"length":1072,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-https/lib/socket.js":{"offset":29166845,"length":464,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-https/package.json":{"offset":29167309,"length":1028,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-inspect/binding.js":{"offset":29168337,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-inspect/index.js":{"offset":29168370,"length":23856,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-inspect/package.json":{"offset":29192226,"length":1041,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-mime/index.js":{"offset":29193267,"length":4184,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-mime/package.json":{"offset":29197451,"length":808,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-net/index.js":{"offset":29198259,"length":9005,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-net/lib/constants.js":{"offset":29207264,"length":91,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-net/package.json":{"offset":29207355,"length":1149,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-os/binding.js":{"offset":29208504,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-os/index.js":{"offset":29208537,"length":5216,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-os/lib/constants.js":{"offset":29213753,"length":143,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-os/lib/errors.js":{"offset":29213896,"length":453,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-os/package.json":{"offset":29214349,"length":1257,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-path/index.js":{"offset":29215606,"length":287,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-path/lib/constants.js":{"offset":29215893,"length":247,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-path/lib/posix.js":{"offset":29216140,"length":6005,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-path/lib/shared.js":{"offset":29222145,"length":1926,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-path/lib/win32.js":{"offset":29224071,"length":13591,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-path/package.json":{"offset":29237662,"length":1036,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-pipe/binding.js":{"offset":29238698,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-pipe/index.js":{"offset":29238731,"length":14357,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-pipe/lib/constants.js":{"offset":29253088,"length":352,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-pipe/lib/errors.js":{"offset":29253440,"length":699,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-pipe/package.json":{"offset":29254139,"length":1396,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-posix/package.json":{"offset":29255535,"length":1091,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-posix/unsupported.js":{"offset":29256626,"length":723,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-process/index.js":{"offset":29257349,"length":3189,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-process/package.json":{"offset":29260538,"length":1283,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-signals/binding.js":{"offset":29261821,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-signals/index.js":{"offset":29261854,"length":1517,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-signals/lib/emitter.js":{"offset":29263371,"length":1278,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-signals/lib/errors.js":{"offset":29264649,"length":479,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-signals/package.json":{"offset":29265128,"length":1112,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-stdio/binding.js":{"offset":29266240,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-stdio/index.js":{"offset":29266273,"length":1525,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-stdio/package.json":{"offset":29267798,"length":1319,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-stream/index.js":{"offset":29269117,"length":10904,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-stream/package.json":{"offset":29280021,"length":1676,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-stream/web.js":{"offset":29281697,"length":13980,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-tcp/binding.js":{"offset":29295677,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-tcp/index.js":{"offset":29295710,"length":17212,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-tcp/lib/constants.js":{"offset":29312922,"length":167,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-tcp/lib/errors.js":{"offset":29313089,"length":797,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-tcp/lib/ip.js":{"offset":29313886,"length":2204,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-tcp/package.json":{"offset":29316090,"length":1400,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-tls/binding.js":{"offset":29317490,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-tls/index.js":{"offset":29317523,"length":6951,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-tls/lib/constants.js":{"offset":29324474,"length":74,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-tls/lib/errors.js":{"offset":29324548,"length":358,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-tls/net.js":{"offset":29324906,"length":2563,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-tls/package.json":{"offset":29327469,"length":1454,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-tty/binding.js":{"offset":29328923,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-tty/index.js":{"offset":29328956,"length":4638,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-tty/lib/constants.js":{"offset":29333594,"length":442,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-tty/package.json":{"offset":29334036,"length":1211,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-type/binding.js":{"offset":29335247,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-type/index.js":{"offset":29335280,"length":4566,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-type/package.json":{"offset":29339846,"length":938,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-url/binding.js":{"offset":29340784,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-url/index.js":{"offset":29340817,"length":9449,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-url/lib/errors.js":{"offset":29350266,"length":778,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-url/lib/url-search-params.js":{"offset":29351044,"length":4331,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-url/package.json":{"offset":29355375,"length":1219,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-zlib/binding.js":{"offset":29356594,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-zlib/index.js":{"offset":29356627,"length":8166,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-zlib/lib/constants.js":{"offset":29364793,"length":74,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-zlib/lib/errors.js":{"offset":29364867,"length":1096,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bare-zlib/package.json":{"offset":29365963,"length":1463,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/index.js":{"offset":29367426,"length":4554,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/package.json":{"offset":29371980,"length":789,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/chinese_simplified.json":{"offset":29372769,"length":12289,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/chinese_traditional.json":{"offset":29385058,"length":12289,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/czech.json":{"offset":29397347,"length":19042,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/english.json":{"offset":29416389,"length":17213,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/french.json":{"offset":29433602,"length":20874,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/index.js":{"offset":29454476,"length":1406,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/italian.json":{"offset":29455882,"length":20130,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/japanese.json":{"offset":29476012,"length":30520,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/korean.json":{"offset":29506532,"length":41929,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/lookup.json":{"offset":29548461,"length":592224,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/portuguese.json":{"offset":30140685,"length":19768,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/russian.json":{"offset":30160453,"length":30635,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/spanish.json":{"offset":30191088,"length":18093,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bip39-mnemonic/wordlist/turkish.json":{"offset":30209181,"length":19421,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bits-to-bytes/index.js":{"offset":30228602,"length":3083,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bits-to-bytes/package.json":{"offset":30231685,"length":708,"mode":420},"/node_modules/hyper-proto-peer/node_modules/blind-relay/index.js":{"offset":30232393,"length":13411,"mode":420},"/node_modules/hyper-proto-peer/node_modules/blind-relay/lib/errors.js":{"offset":30245804,"length":1036,"mode":420},"/node_modules/hyper-proto-peer/node_modules/blind-relay/node_modules/compact-encoding/endian.js":{"offset":30246840,"length":105,"mode":420},"/node_modules/hyper-proto-peer/node_modules/blind-relay/node_modules/compact-encoding/index.js":{"offset":30246945,"length":26406,"mode":420},"/node_modules/hyper-proto-peer/node_modules/blind-relay/node_modules/compact-encoding/lexint.js":{"offset":30273351,"length":2851,"mode":420},"/node_modules/hyper-proto-peer/node_modules/blind-relay/node_modules/compact-encoding/package.json":{"offset":30276202,"length":866,"mode":420},"/node_modules/hyper-proto-peer/node_modules/blind-relay/node_modules/compact-encoding/raw.js":{"offset":30277068,"length":3977,"mode":420},"/node_modules/hyper-proto-peer/node_modules/blind-relay/package.json":{"offset":30281045,"length":1231,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bogon/index.js":{"offset":30282276,"length":4004,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bogon/node_modules/compact-encoding/endian.js":{"offset":30286280,"length":105,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bogon/node_modules/compact-encoding/index.js":{"offset":30286385,"length":26406,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bogon/node_modules/compact-encoding/lexint.js":{"offset":30312791,"length":2851,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bogon/node_modules/compact-encoding/package.json":{"offset":30315642,"length":866,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bogon/node_modules/compact-encoding/raw.js":{"offset":30316508,"length":3977,"mode":420},"/node_modules/hyper-proto-peer/node_modules/bogon/package.json":{"offset":30320485,"length":656,"mode":420},"/node_modules/hyper-proto-peer/node_modules/cborg/cborg.js":{"offset":30321141,"length":944,"mode":420},"/node_modules/hyper-proto-peer/node_modules/cborg/lib/0uint.js":{"offset":30322085,"length":6580,"mode":420},"/node_modules/hyper-proto-peer/node_modules/cborg/lib/1negint.js":{"offset":30328665,"length":2980,"mode":420},"/node_modules/hyper-proto-peer/node_modules/cborg/lib/2bytes.js":{"offset":30331645,"length":3451,"mode":420},"/node_modules/hyper-proto-peer/node_modules/cborg/lib/3string.js":{"offset":30335096,"length":3340,"mode":420},"/node_modules/hyper-proto-peer/node_modules/cborg/lib/4array.js":{"offset":30338436,"length":2944,"mode":420},"/node_modules/hyper-proto-peer/node_modules/cborg/lib/5map.js":{"offset":30341380,"length":2917,"mode":420},"/node_modules/hyper-proto-peer/node_modules/cborg/lib/6tag.js":{"offset":30344297,"length":1957,"mode":420},"/node_modules/hyper-proto-peer/node_modules/cborg/lib/7float.js":{"offset":30346254,"length":8633,"mode":420},"/node_modules/hyper-proto-peer/node_modules/cborg/lib/bl.js":{"offset":30354887,"length":5505,"mode":420},"/node_modules/hyper-proto-peer/node_modules/cborg/lib/byte-utils.js":{"offset":30360392,"length":8369,"mode":420},"/node_modules/hyper-proto-peer/node_modules/cborg/lib/common.js":{"offset":30368761,"length":598,"mode":420},"/node_modules/hyper-proto-peer/node_modules/cborg/lib/decode.js":{"offset":30369359,"length":9008,"mode":420},"/node_modules/hyper-proto-peer/node_modules/cborg/lib/encode.js":{"offset":30378367,"length":21957,"mode":420},"/node_modules/hyper-proto-peer/node_modules/cborg/lib/is.js":{"offset":30400324,"length":2061,"mode":420},"/node_modules/hyper-proto-peer/node_modules/cborg/lib/jump.js":{"offset":30402385,"length":7942,"mode":420},"/node_modules/hyper-proto-peer/node_modules/cborg/lib/tagged.js":{"offset":30410327,"length":2821,"mode":420},"/node_modules/hyper-proto-peer/node_modules/cborg/lib/token.js":{"offset":30413148,"length":2019,"mode":420},"/node_modules/hyper-proto-peer/node_modules/cborg/package.json":{"offset":30415167,"length":4241,"mode":420},"/node_modules/hyper-proto-peer/node_modules/compact-encoding-bitfield/index.js":{"offset":30419408,"length":1967,"mode":420},"/node_modules/hyper-proto-peer/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/endian.js":{"offset":30421375,"length":105,"mode":420},"/node_modules/hyper-proto-peer/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/index.js":{"offset":30421480,"length":26406,"mode":420},"/node_modules/hyper-proto-peer/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/lexint.js":{"offset":30447886,"length":2851,"mode":420},"/node_modules/hyper-proto-peer/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/package.json":{"offset":30450737,"length":866,"mode":420},"/node_modules/hyper-proto-peer/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/raw.js":{"offset":30451603,"length":3977,"mode":420},"/node_modules/hyper-proto-peer/node_modules/compact-encoding-bitfield/package.json":{"offset":30455580,"length":1109,"mode":420},"/node_modules/hyper-proto-peer/node_modules/compact-encoding/endian.js":{"offset":30456689,"length":105,"mode":420},"/node_modules/hyper-proto-peer/node_modules/compact-encoding/index.js":{"offset":30456794,"length":24454,"mode":420},"/node_modules/hyper-proto-peer/node_modules/compact-encoding/lexint.js":{"offset":30481248,"length":2851,"mode":420},"/node_modules/hyper-proto-peer/node_modules/compact-encoding/package.json":{"offset":30484099,"length":786,"mode":420},"/node_modules/hyper-proto-peer/node_modules/compact-encoding/raw.js":{"offset":30484885,"length":4093,"mode":420},"/node_modules/hyper-proto-peer/node_modules/dht-rpc/index.js":{"offset":30488978,"length":29079,"mode":420},"/node_modules/hyper-proto-peer/node_modules/dht-rpc/lib/commands.js":{"offset":30518057,"length":107,"mode":420},"/node_modules/hyper-proto-peer/node_modules/dht-rpc/lib/errors.js":{"offset":30518164,"length":719,"mode":420},"/node_modules/hyper-proto-peer/node_modules/dht-rpc/lib/health.js":{"offset":30518883,"length":2998,"mode":420},"/node_modules/hyper-proto-peer/node_modules/dht-rpc/lib/io.js":{"offset":30521881,"length":16605,"mode":420},"/node_modules/hyper-proto-peer/node_modules/dht-rpc/lib/peer.js":{"offset":30538486,"length":583,"mode":420},"/node_modules/hyper-proto-peer/node_modules/dht-rpc/lib/query.js":{"offset":30539069,"length":9899,"mode":420},"/node_modules/hyper-proto-peer/node_modules/dht-rpc/lib/session.js":{"offset":30548968,"length":1103,"mode":420},"/node_modules/hyper-proto-peer/node_modules/dht-rpc/node_modules/compact-encoding/endian.js":{"offset":30550071,"length":105,"mode":420},"/node_modules/hyper-proto-peer/node_modules/dht-rpc/node_modules/compact-encoding/index.js":{"offset":30550176,"length":26406,"mode":420},"/node_modules/hyper-proto-peer/node_modules/dht-rpc/node_modules/compact-encoding/lexint.js":{"offset":30576582,"length":2851,"mode":420},"/node_modules/hyper-proto-peer/node_modules/dht-rpc/node_modules/compact-encoding/package.json":{"offset":30579433,"length":866,"mode":420},"/node_modules/hyper-proto-peer/node_modules/dht-rpc/node_modules/compact-encoding/raw.js":{"offset":30580299,"length":3977,"mode":420},"/node_modules/hyper-proto-peer/node_modules/dht-rpc/package.json":{"offset":30584276,"length":1396,"mode":420},"/node_modules/hyper-proto-peer/node_modules/events-universal/bare.js":{"offset":30585672,"length":40,"mode":420},"/node_modules/hyper-proto-peer/node_modules/events-universal/package.json":{"offset":30585712,"length":908,"mode":420},"/node_modules/hyper-proto-peer/node_modules/fast-fifo/fixed-size.js":{"offset":30586620,"length":875,"mode":420},"/node_modules/hyper-proto-peer/node_modules/fast-fifo/index.js":{"offset":30587495,"length":972,"mode":420},"/node_modules/hyper-proto-peer/node_modules/fast-fifo/package.json":{"offset":30588467,"length":682,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/index.js":{"offset":30589149,"length":2334,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/lib/chunk-scheduler.js":{"offset":30591483,"length":18133,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/lib/chunker.js":{"offset":30609616,"length":14180,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/lib/file-index.js":{"offset":30623796,"length":20487,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/lib/ignore.js":{"offset":30644283,"length":4047,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/lib/manifest.js":{"offset":30648330,"length":2360,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/lib/messages.js":{"offset":30650690,"length":15242,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/lib/overlay.js":{"offset":30665932,"length":26332,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/lib/pointer.js":{"offset":30692264,"length":3986,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/lib/protocol.js":{"offset":30696250,"length":50117,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/lib/sync-engine.js":{"offset":30746367,"length":12006,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/lib/transfer.js":{"offset":30758373,"length":33515,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/lib/tree.js":{"offset":30791888,"length":14077,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/b4a/index.js":{"offset":30805965,"length":4054,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/b4a/package.json":{"offset":30810019,"length":1245,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-ansi-escapes/index.js":{"offset":30811264,"length":2255,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-ansi-escapes/package.json":{"offset":30813519,"length":1178,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-assert/index.js":{"offset":30814697,"length":2192,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-assert/package.json":{"offset":30816889,"length":835,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-events/index.js":{"offset":30817724,"length":8307,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-events/lib/errors.js":{"offset":30826031,"length":671,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-events/package.json":{"offset":30826702,"length":1504,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-fs/binding.js":{"offset":30828206,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-fs/index.js":{"offset":30828239,"length":58907,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-fs/lib/constants.js":{"offset":30887146,"length":1494,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-fs/lib/errors.js":{"offset":30888640,"length":1163,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-fs/package.json":{"offset":30889803,"length":1654,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-fs/promises.js":{"offset":30891457,"length":2401,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-inspect/binding.js":{"offset":30893858,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-inspect/index.js":{"offset":30893891,"length":23856,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-inspect/package.json":{"offset":30917747,"length":1041,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-os/binding.js":{"offset":30918788,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-os/index.js":{"offset":30918821,"length":3224,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-os/lib/constants.js":{"offset":30922045,"length":143,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-os/lib/errors.js":{"offset":30922188,"length":453,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-os/package.json":{"offset":30922641,"length":1257,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-path/index.js":{"offset":30923898,"length":287,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-path/lib/constants.js":{"offset":30924185,"length":247,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-path/lib/posix.js":{"offset":30924432,"length":6005,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-path/lib/shared.js":{"offset":30930437,"length":1926,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-path/lib/win32.js":{"offset":30932363,"length":13591,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-path/package.json":{"offset":30945954,"length":1036,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-stream/index.js":{"offset":30946990,"length":10904,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-stream/package.json":{"offset":30957894,"length":1676,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-stream/web.js":{"offset":30959570,"length":13980,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-type/binding.js":{"offset":30973550,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-type/index.js":{"offset":30973583,"length":4566,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-type/package.json":{"offset":30978149,"length":938,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-url/binding.js":{"offset":30979087,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-url/index.js":{"offset":30979120,"length":9449,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-url/lib/errors.js":{"offset":30988569,"length":778,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-url/lib/url-search-params.js":{"offset":30989347,"length":4331,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-url/package.json":{"offset":30993678,"length":1219,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-zlib/binding.js":{"offset":30994897,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-zlib/index.js":{"offset":30994930,"length":8166,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-zlib/lib/constants.js":{"offset":31003096,"length":74,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-zlib/lib/errors.js":{"offset":31003170,"length":1096,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/bare-zlib/package.json":{"offset":31004266,"length":1463,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/codecs/index.js":{"offset":31005729,"length":2416,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/codecs/package.json":{"offset":31008145,"length":655,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/compact-encoding/endian.js":{"offset":31008800,"length":105,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/compact-encoding/index.js":{"offset":31008905,"length":26135,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/compact-encoding/lexint.js":{"offset":31035040,"length":2851,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/compact-encoding/package.json":{"offset":31037891,"length":866,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/compact-encoding/raw.js":{"offset":31038757,"length":3977,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/debounceify/index.js":{"offset":31042734,"length":585,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/debounceify/package.json":{"offset":31043319,"length":567,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/events-universal/bare.js":{"offset":31043886,"length":40,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/events-universal/package.json":{"offset":31043926,"length":908,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/fast-fifo/fixed-size.js":{"offset":31044834,"length":875,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/fast-fifo/index.js":{"offset":31045709,"length":972,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/fast-fifo/package.json":{"offset":31046681,"length":682,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/hyperbee/index.js":{"offset":31047363,"length":46445,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/hyperbee/iterators/diff.js":{"offset":31093808,"length":5358,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/hyperbee/iterators/history.js":{"offset":31099166,"length":1631,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/hyperbee/iterators/local.js":{"offset":31100797,"length":1170,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/hyperbee/iterators/range.js":{"offset":31101967,"length":5869,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/hyperbee/lib/extension.js":{"offset":31107836,"length":3488,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/hyperbee/lib/messages.js":{"offset":31111324,"length":28162,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/hyperbee/package.json":{"offset":31139486,"length":1585,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/hypercore-crypto/index.js":{"offset":31141071,"length":5031,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/hypercore-crypto/package.json":{"offset":31146102,"length":1007,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/hypercore-errors/index.js":{"offset":31147109,"length":4896,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/hypercore-errors/package.json":{"offset":31152005,"length":688,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/hypercore-id-encoding/index.js":{"offset":31152693,"length":923,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/hypercore-id-encoding/package.json":{"offset":31153616,"length":799,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/mutexify/index.js":{"offset":31154415,"length":536,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/mutexify/package.json":{"offset":31154951,"length":679,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/mutexify/promise.js":{"offset":31155630,"length":324,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/protocol-buffers-encodings/index.js":{"offset":31155954,"length":6489,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/protocol-buffers-encodings/package.json":{"offset":31162443,"length":719,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/queue-tick/package.json":{"offset":31163162,"length":669,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/queue-tick/process-next-tick.js":{"offset":31163831,"length":160,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/queue-tick/queue-microtask.js":{"offset":31163991,"length":108,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/rache/index.js":{"offset":31164099,"length":2463,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/rache/package.json":{"offset":31166562,"length":602,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/ready-resource/index.js":{"offset":31167164,"length":1091,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/ready-resource/package.json":{"offset":31168255,"length":812,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/require-addon/lib/bare.js":{"offset":31169067,"length":45,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/require-addon/package.json":{"offset":31169112,"length":1449,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/resolve-reject-promise/index.js":{"offset":31170561,"length":443,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/resolve-reject-promise/package.json":{"offset":31171004,"length":581,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/safety-catch/index.js":{"offset":31171585,"length":543,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/safety-catch/package.json":{"offset":31172128,"length":547,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/signed-varint/index.js":{"offset":31172675,"length":435,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/signed-varint/package.json":{"offset":31173110,"length":523,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/sodium-native/binding.js":{"offset":31173633,"length":89,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/sodium-native/index.js":{"offset":31173722,"length":107894,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/sodium-native/package.json":{"offset":31281616,"length":1478,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/sodium-universal/index.js":{"offset":31283094,"length":42,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/sodium-universal/package.json":{"offset":31283136,"length":1217,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/streamx/index.js":{"offset":31284353,"length":34248,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/streamx/lib/errors.js":{"offset":31318601,"length":1096,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/streamx/package.json":{"offset":31319697,"length":1225,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/teex/index.js":{"offset":31320922,"length":1107,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/teex/package.json":{"offset":31322029,"length":608,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/text-decoder/index.js":{"offset":31322637,"length":1371,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/text-decoder/lib/pass-through-decoder.js":{"offset":31324008,"length":269,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/text-decoder/lib/utf8-decoder.js":{"offset":31324277,"length":4429,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/text-decoder/package.json":{"offset":31328706,"length":990,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/unslab/index.js":{"offset":31329696,"length":913,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/unslab/package.json":{"offset":31330609,"length":613,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/varint/decode.js":{"offset":31331222,"length":508,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/varint/encode.js":{"offset":31331730,"length":452,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/varint/index.js":{"offset":31332182,"length":134,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/varint/length.js":{"offset":31332316,"length":471,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/varint/package.json":{"offset":31332787,"length":511,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/which-runtime/index.js":{"offset":31333298,"length":1469,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/which-runtime/package.json":{"offset":31334767,"length":863,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/z32/index.js":{"offset":31335630,"length":2654,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/node_modules/z32/package.json":{"offset":31338284,"length":701,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-overlay/package.json":{"offset":31338985,"length":2132,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/index.js":{"offset":31341117,"length":424,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/lib/client.js":{"offset":31341541,"length":14860,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/lib/frame.js":{"offset":31356401,"length":1862,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/lib/service.js":{"offset":31358263,"length":11770,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/lib/transports/http.js":{"offset":31370033,"length":7998,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/lib/transports/swarm-rpc.js":{"offset":31378031,"length":4427,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/lib/transports/swarm.js":{"offset":31382458,"length":8308,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/lib/transports/uds.js":{"offset":31390766,"length":8779,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/lib/uds-backend.js":{"offset":31399545,"length":1568,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/index.js":{"offset":31401113,"length":16722,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/lib/bridge.js":{"offset":31417835,"length":1273,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/lib/handshake.js":{"offset":31419108,"length":1950,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/package.json":{"offset":31421058,"length":1132,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/adaptive-timeout/index.js":{"offset":31422190,"length":2424,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/adaptive-timeout/package.json":{"offset":31424614,"length":972,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/index.js":{"offset":31425586,"length":4054,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/b4a/package.json":{"offset":31429640,"length":1245,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-abort/binding.js":{"offset":31430885,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-abort/index.js":{"offset":31430918,"length":69,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-abort/package.json":{"offset":31430987,"length":886,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-ansi-escapes/index.js":{"offset":31431873,"length":2255,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-ansi-escapes/package.json":{"offset":31434128,"length":1178,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-assert/index.js":{"offset":31435306,"length":2192,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-assert/package.json":{"offset":31437498,"length":835,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-dns/binding.js":{"offset":31438333,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-dns/index.js":{"offset":31438366,"length":1345,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-dns/package.json":{"offset":31439711,"length":968,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-env/index.js":{"offset":31440679,"length":1023,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-env/package.json":{"offset":31441702,"length":649,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-events/index.js":{"offset":31442351,"length":8033,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-events/lib/errors.js":{"offset":31450384,"length":671,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-events/package.json":{"offset":31451055,"length":1399,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-fs/binding.js":{"offset":31452454,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-fs/index.js":{"offset":31452487,"length":58907,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-fs/lib/constants.js":{"offset":31511394,"length":1494,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-fs/lib/errors.js":{"offset":31512888,"length":1163,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-fs/package.json":{"offset":31514051,"length":1654,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-fs/promises.js":{"offset":31515705,"length":2401,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-hrtime/binding.js":{"offset":31518106,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-hrtime/index.js":{"offset":31518139,"length":319,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-hrtime/package.json":{"offset":31518458,"length":905,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http-parser/index.js":{"offset":31519363,"length":17480,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http-parser/lib/errors.js":{"offset":31536843,"length":845,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http-parser/package.json":{"offset":31537688,"length":793,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http1/index.js":{"offset":31538481,"length":2188,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http1/lib/agent.js":{"offset":31540669,"length":4498,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http1/lib/client-connection.js":{"offset":31545167,"length":3663,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http1/lib/client-request.js":{"offset":31548830,"length":3286,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http1/lib/constants.js":{"offset":31552116,"length":2016,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http1/lib/errors.js":{"offset":31554132,"length":634,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http1/lib/incoming-message.js":{"offset":31554766,"length":1568,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http1/lib/outgoing-message.js":{"offset":31556334,"length":1291,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http1/lib/server-connection.js":{"offset":31557625,"length":4041,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http1/lib/server-response.js":{"offset":31561666,"length":3183,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http1/lib/server.js":{"offset":31564849,"length":977,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-http1/package.json":{"offset":31565826,"length":1510,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-inspect/binding.js":{"offset":31567336,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-inspect/index.js":{"offset":31567369,"length":23856,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-inspect/package.json":{"offset":31591225,"length":1041,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-net/index.js":{"offset":31592266,"length":6868,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-dns/binding.js":{"offset":31599134,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-dns/index.js":{"offset":31599167,"length":860,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-dns/package.json":{"offset":31600027,"length":772,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/binding.js":{"offset":31600799,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/index.js":{"offset":31600832,"length":10947,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/lib/constants.js":{"offset":31611779,"length":188,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/lib/errors.js":{"offset":31611967,"length":668,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/package.json":{"offset":31612635,"length":962,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/binding.js":{"offset":31613597,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/index.js":{"offset":31613630,"length":12710,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/lib/constants.js":{"offset":31626340,"length":167,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/lib/errors.js":{"offset":31626507,"length":799,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/lib/ip.js":{"offset":31627306,"length":2179,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/package.json":{"offset":31629485,"length":959,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-net/package.json":{"offset":31630444,"length":793,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-os/binding.js":{"offset":31631237,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-os/index.js":{"offset":31631270,"length":3224,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-os/lib/constants.js":{"offset":31634494,"length":143,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-os/lib/errors.js":{"offset":31634637,"length":453,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-os/package.json":{"offset":31635090,"length":1257,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-path/index.js":{"offset":31636347,"length":306,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-path/lib/constants.js":{"offset":31636653,"length":247,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-path/lib/posix.js":{"offset":31636900,"length":5991,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-path/lib/shared.js":{"offset":31642891,"length":1888,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-path/lib/win32.js":{"offset":31644779,"length":13427,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-path/package.json":{"offset":31658206,"length":796,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-pipe/binding.js":{"offset":31659002,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-pipe/index.js":{"offset":31659035,"length":10769,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-pipe/lib/constants.js":{"offset":31669804,"length":208,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-pipe/lib/errors.js":{"offset":31670012,"length":599,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-pipe/package.json":{"offset":31670611,"length":1256,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-process/index.js":{"offset":31671867,"length":2689,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-process/package.json":{"offset":31674556,"length":1255,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-signals/binding.js":{"offset":31675811,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-signals/index.js":{"offset":31675844,"length":1517,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-signals/lib/emitter.js":{"offset":31677361,"length":1278,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-signals/lib/errors.js":{"offset":31678639,"length":479,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-signals/package.json":{"offset":31679118,"length":1112,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-stdio/binding.js":{"offset":31680230,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-stdio/index.js":{"offset":31680263,"length":1525,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-stdio/package.json":{"offset":31681788,"length":1319,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-stream/index.js":{"offset":31683107,"length":10913,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-stream/package.json":{"offset":31694020,"length":1655,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-stream/web.js":{"offset":31695675,"length":13980,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-tcp/binding.js":{"offset":31709655,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-tcp/index.js":{"offset":31709688,"length":15054,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-tcp/lib/constants.js":{"offset":31724742,"length":167,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-tcp/lib/errors.js":{"offset":31724909,"length":711,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-tcp/lib/ip.js":{"offset":31725620,"length":2204,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-tcp/package.json":{"offset":31727824,"length":1243,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-tty/binding.js":{"offset":31729067,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-tty/index.js":{"offset":31729100,"length":4469,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-tty/lib/constants.js":{"offset":31733569,"length":442,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-tty/package.json":{"offset":31734011,"length":1097,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-type/binding.js":{"offset":31735108,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-type/index.js":{"offset":31735141,"length":4566,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-type/package.json":{"offset":31739707,"length":938,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-url/binding.js":{"offset":31740645,"length":33,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-url/index.js":{"offset":31740678,"length":9308,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-url/lib/errors.js":{"offset":31749986,"length":778,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-url/lib/url-search-params.js":{"offset":31750764,"length":4331,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bare-url/package.json":{"offset":31755095,"length":1219,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bits-to-bytes/index.js":{"offset":31756314,"length":3083,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bits-to-bytes/package.json":{"offset":31759397,"length":708,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/blind-relay/index.js":{"offset":31760105,"length":13256,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/blind-relay/lib/errors.js":{"offset":31773361,"length":1036,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/endian.js":{"offset":31774397,"length":105,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/index.js":{"offset":31774502,"length":24454,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/lexint.js":{"offset":31798956,"length":2851,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/package.json":{"offset":31801807,"length":786,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/raw.js":{"offset":31802593,"length":4093,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/blind-relay/package.json":{"offset":31806686,"length":1232,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bogon/index.js":{"offset":31807918,"length":4052,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/endian.js":{"offset":31811970,"length":105,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/index.js":{"offset":31812075,"length":24454,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/lexint.js":{"offset":31836529,"length":2851,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/package.json":{"offset":31839380,"length":786,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/raw.js":{"offset":31840166,"length":4093,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/bogon/package.json":{"offset":31844259,"length":657,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/index.js":{"offset":31844916,"length":1963,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/endian.js":{"offset":31846879,"length":105,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/index.js":{"offset":31846984,"length":24454,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/lexint.js":{"offset":31871438,"length":2851,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/package.json":{"offset":31874289,"length":786,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/raw.js":{"offset":31875075,"length":4093,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/package.json":{"offset":31879168,"length":827,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding-net/index.js":{"offset":31879995,"length":4109,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/endian.js":{"offset":31884104,"length":105,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/index.js":{"offset":31884209,"length":24454,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/lexint.js":{"offset":31908663,"length":2851,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/package.json":{"offset":31911514,"length":786,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/raw.js":{"offset":31912300,"length":4093,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding-net/package.json":{"offset":31916393,"length":734,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding/endian.js":{"offset":31917127,"length":105,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding/index.js":{"offset":31917232,"length":26135,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding/lexint.js":{"offset":31943367,"length":2851,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding/package.json":{"offset":31946218,"length":866,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/compact-encoding/raw.js":{"offset":31947084,"length":3977,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/dht-rpc/index.js":{"offset":31951061,"length":29079,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/dht-rpc/lib/commands.js":{"offset":31980140,"length":107,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/dht-rpc/lib/errors.js":{"offset":31980247,"length":719,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/dht-rpc/lib/health.js":{"offset":31980966,"length":2998,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/dht-rpc/lib/io.js":{"offset":31983964,"length":16605,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/dht-rpc/lib/peer.js":{"offset":32000569,"length":631,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/dht-rpc/lib/query.js":{"offset":32001200,"length":9899,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/dht-rpc/lib/session.js":{"offset":32011099,"length":1103,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/endian.js":{"offset":32012202,"length":105,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/index.js":{"offset":32012307,"length":24454,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/lexint.js":{"offset":32036761,"length":2851,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/package.json":{"offset":32039612,"length":786,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/raw.js":{"offset":32040398,"length":4093,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/dht-rpc/package.json":{"offset":32044491,"length":1397,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/events-universal/bare.js":{"offset":32045888,"length":40,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/events-universal/package.json":{"offset":32045928,"length":908,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/fast-fifo/fixed-size.js":{"offset":32046836,"length":875,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/fast-fifo/index.js":{"offset":32047711,"length":972,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/fast-fifo/package.json":{"offset":32048683,"length":682,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hypercore-crypto/index.js":{"offset":32049365,"length":5040,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/endian.js":{"offset":32054405,"length":105,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/index.js":{"offset":32054510,"length":24454,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/lexint.js":{"offset":32078964,"length":2851,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/package.json":{"offset":32081815,"length":786,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/raw.js":{"offset":32082601,"length":4093,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hypercore-crypto/package.json":{"offset":32086694,"length":771,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hypercore-id-encoding/index.js":{"offset":32087465,"length":923,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hypercore-id-encoding/package.json":{"offset":32088388,"length":799,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht-address/index.js":{"offset":32089187,"length":357,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/endian.js":{"offset":32089544,"length":105,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/index.js":{"offset":32089649,"length":24454,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/lexint.js":{"offset":32114103,"length":2851,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/package.json":{"offset":32116954,"length":786,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/raw.js":{"offset":32117740,"length":4093,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht-address/package.json":{"offset":32121833,"length":1047,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht-address/spec/hyperschema/index.js":{"offset":32122880,"length":2106,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/index.js":{"offset":32124986,"length":16611,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/announcer.js":{"offset":32141597,"length":7533,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/connect.js":{"offset":32149130,"length":24788,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/connection-pool.js":{"offset":32173918,"length":3050,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/constants.js":{"offset":32176968,"length":1276,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/crypto.js":{"offset":32178244,"length":632,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/encode.js":{"offset":32178876,"length":446,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/errors.js":{"offset":32179322,"length":3712,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/holepuncher.js":{"offset":32183034,"length":10003,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/messages.js":{"offset":32193037,"length":11789,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/nat.js":{"offset":32204826,"length":4714,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/noise-wrap.js":{"offset":32209540,"length":1669,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/persistent.js":{"offset":32211209,"length":8361,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/raw-stream-set.js":{"offset":32219570,"length":1511,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/router.js":{"offset":32221081,"length":6978,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/secure-payload.js":{"offset":32228059,"length":1491,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/semaphore.js":{"offset":32229550,"length":1577,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/server.js":{"offset":32231127,"length":21300,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/sleeper.js":{"offset":32252427,"length":690,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/lib/socket-pool.js":{"offset":32253117,"length":4343,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/endian.js":{"offset":32257460,"length":105,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/index.js":{"offset":32257565,"length":24454,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/lexint.js":{"offset":32282019,"length":2851,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/package.json":{"offset":32284870,"length":786,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/raw.js":{"offset":32285656,"length":4093,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperdht/package.json":{"offset":32289749,"length":2007,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/endian.js":{"offset":32291756,"length":105,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/index.js":{"offset":32291861,"length":24454,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/lexint.js":{"offset":32316315,"length":2851,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/package.json":{"offset":32319166,"length":786,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/raw.js":{"offset":32319952,"length":4093,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperschema/package.json":{"offset":32324045,"length":1556,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperschema/runtime.cjs":{"offset":32325601,"length":54,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperswarm/index.js":{"offset":32325655,"length":18589,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperswarm/lib/bulk-timer.js":{"offset":32344244,"length":728,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperswarm/lib/connection-set.js":{"offset":32344972,"length":823,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperswarm/lib/peer-discovery.js":{"offset":32345795,"length":9296,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperswarm/lib/peer-info.js":{"offset":32355091,"length":2688,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperswarm/lib/retry-timer.js":{"offset":32357779,"length":1889,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/hyperswarm/package.json":{"offset":32359668,"length":1515,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/kademlia-routing-table/index.js":{"offset":32361183,"length":4145,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/kademlia-routing-table/package.json":{"offset":32365328,"length":967,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/nanoassert/index.js":{"offset":32366295,"length":438,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/nanoassert/package.json":{"offset":32366733,"length":647,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/nat-sampler/index.js":{"offset":32367380,"length":1550,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/nat-sampler/package.json":{"offset":32368930,"length":608,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/noise-curve-ed/index.js":{"offset":32369538,"length":1642,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/noise-curve-ed/package.json":{"offset":32371180,"length":808,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/noise-handshake/cipher.js":{"offset":32371988,"length":2817,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/noise-handshake/dh.js":{"offset":32374805,"length":1439,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/noise-handshake/hkdf.js":{"offset":32376244,"length":1092,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/noise-handshake/hmac.js":{"offset":32377336,"length":1273,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/noise-handshake/noise.js":{"offset":32378609,"length":6437,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/noise-handshake/package.json":{"offset":32385046,"length":638,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/noise-handshake/symmetric-state.js":{"offset":32385684,"length":2206,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/protomux/index.js":{"offset":32387890,"length":19741,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/protomux/package.json":{"offset":32407631,"length":1059,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/queue-tick/package.json":{"offset":32408690,"length":669,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/queue-tick/process-next-tick.js":{"offset":32409359,"length":160,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/queue-tick/queue-microtask.js":{"offset":32409519,"length":108,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/ready-resource/index.js":{"offset":32409627,"length":1091,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/ready-resource/package.json":{"offset":32410718,"length":812,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/record-cache/index.js":{"offset":32411530,"length":3668,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/record-cache/package.json":{"offset":32415198,"length":612,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/require-addon/lib/bare.js":{"offset":32415810,"length":45,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/require-addon/package.json":{"offset":32415855,"length":1449,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/safety-catch/index.js":{"offset":32417304,"length":543,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/safety-catch/package.json":{"offset":32417847,"length":547,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/shuffled-priority-queue/index.js":{"offset":32418394,"length":2607,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/shuffled-priority-queue/package.json":{"offset":32421001,"length":691,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/signal-promise/index.js":{"offset":32421692,"length":1252,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/signal-promise/package.json":{"offset":32422944,"length":503,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/sodium-native/binding.js":{"offset":32423447,"length":89,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/sodium-native/index.js":{"offset":32423536,"length":107894,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/sodium-native/package.json":{"offset":32531430,"length":1478,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/sodium-secretstream/index.js":{"offset":32532908,"length":2257,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/sodium-secretstream/package.json":{"offset":32535165,"length":657,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/sodium-universal/index.js":{"offset":32535822,"length":42,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/sodium-universal/package.json":{"offset":32535864,"length":1217,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/streamx/index.js":{"offset":32537081,"length":33510,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/streamx/package.json":{"offset":32570591,"length":912,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/teex/index.js":{"offset":32571503,"length":1107,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/teex/package.json":{"offset":32572610,"length":608,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/text-decoder/index.js":{"offset":32573218,"length":1371,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/text-decoder/lib/pass-through-decoder.js":{"offset":32574589,"length":269,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/text-decoder/lib/utf8-decoder.js":{"offset":32574858,"length":4429,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/text-decoder/package.json":{"offset":32579287,"length":990,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/time-ordered-set/index.js":{"offset":32580277,"length":1444,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/time-ordered-set/package.json":{"offset":32581721,"length":666,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/timeout-refresh/browser.js":{"offset":32582387,"length":1098,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/timeout-refresh/index.js":{"offset":32583485,"length":184,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/timeout-refresh/node.js":{"offset":32583669,"length":928,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/timeout-refresh/package.json":{"offset":32584597,"length":619,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/udx-native/binding.js":{"offset":32585216,"length":90,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/udx-native/lib/ip.js":{"offset":32585306,"length":2204,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/udx-native/lib/network-interfaces.js":{"offset":32587510,"length":1341,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/udx-native/lib/socket.js":{"offset":32588851,"length":7557,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/udx-native/lib/stream.js":{"offset":32596408,"length":12706,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/udx-native/lib/udx.js":{"offset":32609114,"length":2868,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/udx-native/package.json":{"offset":32611982,"length":1615,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/unordered-set/index.js":{"offset":32613597,"length":677,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/unordered-set/package.json":{"offset":32614274,"length":654,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/unslab/index.js":{"offset":32614928,"length":913,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/unslab/package.json":{"offset":32615841,"length":613,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/which-runtime/index.js":{"offset":32616454,"length":1231,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/which-runtime/package.json":{"offset":32617685,"length":602,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/xache/index.js":{"offset":32618287,"length":2378,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/xache/package.json":{"offset":32620665,"length":584,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/z32/index.js":{"offset":32621249,"length":2654,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/node_modules/z32/package.json":{"offset":32623903,"length":701,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyper-svc/package.json":{"offset":32624604,"length":1873,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hypercore-crypto/index.js":{"offset":32626477,"length":5031,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hypercore-crypto/node_modules/compact-encoding/endian.js":{"offset":32631508,"length":105,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hypercore-crypto/node_modules/compact-encoding/index.js":{"offset":32631613,"length":26406,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hypercore-crypto/node_modules/compact-encoding/lexint.js":{"offset":32658019,"length":2851,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hypercore-crypto/node_modules/compact-encoding/package.json":{"offset":32660870,"length":866,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hypercore-crypto/node_modules/compact-encoding/raw.js":{"offset":32661736,"length":3977,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hypercore-crypto/package.json":{"offset":32665713,"length":1007,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hypercore-id-encoding/index.js":{"offset":32666720,"length":923,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hypercore-id-encoding/package.json":{"offset":32667643,"length":799,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyperdht-address/index.js":{"offset":32668442,"length":357,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyperdht-address/node_modules/compact-encoding/endian.js":{"offset":32668799,"length":105,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyperdht-address/node_modules/compact-encoding/index.js":{"offset":32668904,"length":26406,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyperdht-address/node_modules/compact-encoding/lexint.js":{"offset":32695310,"length":2851,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyperdht-address/node_modules/compact-encoding/package.json":{"offset":32698161,"length":866,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyperdht-address/node_modules/compact-encoding/raw.js":{"offset":32699027,"length":3977,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyperdht-address/package.json":{"offset":32703004,"length":1046,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyperdht-address/spec/hyperschema/index.js":{"offset":32704050,"length":2106,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyperdht/index.js":{"offset":32706156,"length":16611,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/announcer.js":{"offset":32722767,"length":7533,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/connect.js":{"offset":32730300,"length":24788,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/connection-pool.js":{"offset":32755088,"length":3050,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/constants.js":{"offset":32758138,"length":1276,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/crypto.js":{"offset":32759414,"length":632,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/encode.js":{"offset":32760046,"length":446,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/errors.js":{"offset":32760492,"length":3712,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/holepuncher.js":{"offset":32764204,"length":10003,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/messages.js":{"offset":32774207,"length":12057,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/nat.js":{"offset":32786264,"length":4714,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/noise-wrap.js":{"offset":32790978,"length":1669,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/persistent.js":{"offset":32792647,"length":8361,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/raw-stream-set.js":{"offset":32801008,"length":1511,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/router.js":{"offset":32802519,"length":6978,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/secure-payload.js":{"offset":32809497,"length":1491,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/semaphore.js":{"offset":32810988,"length":1577,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/server.js":{"offset":32812565,"length":21300,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/sleeper.js":{"offset":32833865,"length":690,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyperdht/lib/socket-pool.js":{"offset":32834555,"length":4343,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyperdht/node_modules/compact-encoding/endian.js":{"offset":32838898,"length":105,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyperdht/node_modules/compact-encoding/index.js":{"offset":32839003,"length":26406,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyperdht/node_modules/compact-encoding/lexint.js":{"offset":32865409,"length":2851,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyperdht/node_modules/compact-encoding/package.json":{"offset":32868260,"length":866,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyperdht/node_modules/compact-encoding/raw.js":{"offset":32869126,"length":3977,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyperdht/package.json":{"offset":32873103,"length":2007,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyperschema/node_modules/compact-encoding/endian.js":{"offset":32875110,"length":105,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyperschema/node_modules/compact-encoding/index.js":{"offset":32875215,"length":26406,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyperschema/node_modules/compact-encoding/lexint.js":{"offset":32901621,"length":2851,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyperschema/node_modules/compact-encoding/package.json":{"offset":32904472,"length":866,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyperschema/node_modules/compact-encoding/raw.js":{"offset":32905338,"length":3977,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyperschema/package.json":{"offset":32909315,"length":1555,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyperschema/runtime.cjs":{"offset":32910870,"length":54,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyperswarm/index.js":{"offset":32910924,"length":18589,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyperswarm/lib/bulk-timer.js":{"offset":32929513,"length":728,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyperswarm/lib/connection-set.js":{"offset":32930241,"length":823,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyperswarm/lib/peer-discovery.js":{"offset":32931064,"length":9296,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyperswarm/lib/peer-info.js":{"offset":32940360,"length":2688,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyperswarm/lib/retry-timer.js":{"offset":32943048,"length":1889,"mode":420},"/node_modules/hyper-proto-peer/node_modules/hyperswarm/package.json":{"offset":32944937,"length":1515,"mode":420},"/node_modules/hyper-proto-peer/node_modules/kademlia-routing-table/index.js":{"offset":32946452,"length":4145,"mode":420},"/node_modules/hyper-proto-peer/node_modules/kademlia-routing-table/package.json":{"offset":32950597,"length":967,"mode":420},"/node_modules/hyper-proto-peer/node_modules/keet-identity-key/index.js":{"offset":32951564,"length":6320,"mode":420},"/node_modules/hyper-proto-peer/node_modules/keet-identity-key/lib/crypto.js":{"offset":32957884,"length":552,"mode":420},"/node_modules/hyper-proto-peer/node_modules/keet-identity-key/lib/encoding.js":{"offset":32958436,"length":3695,"mode":420},"/node_modules/hyper-proto-peer/node_modules/keet-identity-key/lib/keychain.js":{"offset":32962131,"length":3080,"mode":420},"/node_modules/hyper-proto-peer/node_modules/keet-identity-key/node_modules/compact-encoding/endian.js":{"offset":32965211,"length":105,"mode":420},"/node_modules/hyper-proto-peer/node_modules/keet-identity-key/node_modules/compact-encoding/index.js":{"offset":32965316,"length":26406,"mode":420},"/node_modules/hyper-proto-peer/node_modules/keet-identity-key/node_modules/compact-encoding/lexint.js":{"offset":32991722,"length":2851,"mode":420},"/node_modules/hyper-proto-peer/node_modules/keet-identity-key/node_modules/compact-encoding/package.json":{"offset":32994573,"length":866,"mode":420},"/node_modules/hyper-proto-peer/node_modules/keet-identity-key/node_modules/compact-encoding/raw.js":{"offset":32995439,"length":3977,"mode":420},"/node_modules/hyper-proto-peer/node_modules/keet-identity-key/package.json":{"offset":32999416,"length":887,"mode":420},"/node_modules/hyper-proto-peer/node_modules/multiformats/dist/src/bases/base.js":{"offset":33000303,"length":6266,"mode":420},"/node_modules/hyper-proto-peer/node_modules/multiformats/dist/src/bases/base32.js":{"offset":33006569,"length":1443,"mode":420},"/node_modules/hyper-proto-peer/node_modules/multiformats/dist/src/bases/base36.js":{"offset":33008012,"length":327,"mode":420},"/node_modules/hyper-proto-peer/node_modules/multiformats/dist/src/bases/base58.js":{"offset":33008339,"length":379,"mode":420},"/node_modules/hyper-proto-peer/node_modules/multiformats/dist/src/bytes.js":{"offset":33008718,"length":1246,"mode":420},"/node_modules/hyper-proto-peer/node_modules/multiformats/dist/src/cid.js":{"offset":33009964,"length":13430,"mode":420},"/node_modules/hyper-proto-peer/node_modules/multiformats/dist/src/hashes/digest.js":{"offset":33023394,"length":1915,"mode":420},"/node_modules/hyper-proto-peer/node_modules/multiformats/dist/src/link/interface.js":{"offset":33025309,"length":48,"mode":420},"/node_modules/hyper-proto-peer/node_modules/multiformats/dist/src/varint.js":{"offset":33025357,"length":398,"mode":420},"/node_modules/hyper-proto-peer/node_modules/multiformats/dist/src/vendor/base-x.js":{"offset":33025755,"length":5458,"mode":420},"/node_modules/hyper-proto-peer/node_modules/multiformats/dist/src/vendor/varint.js":{"offset":33031213,"length":2107,"mode":420},"/node_modules/hyper-proto-peer/node_modules/multiformats/package.json":{"offset":33033320,"length":8176,"mode":420},"/node_modules/hyper-proto-peer/node_modules/nanoassert/index.js":{"offset":33041496,"length":438,"mode":420},"/node_modules/hyper-proto-peer/node_modules/nanoassert/package.json":{"offset":33041934,"length":647,"mode":420},"/node_modules/hyper-proto-peer/node_modules/nat-sampler/index.js":{"offset":33042581,"length":1550,"mode":420},"/node_modules/hyper-proto-peer/node_modules/nat-sampler/package.json":{"offset":33044131,"length":608,"mode":420},"/node_modules/hyper-proto-peer/node_modules/noise-curve-ed/index.js":{"offset":33044739,"length":1642,"mode":420},"/node_modules/hyper-proto-peer/node_modules/noise-curve-ed/package.json":{"offset":33046381,"length":808,"mode":420},"/node_modules/hyper-proto-peer/node_modules/noise-handshake/cipher.js":{"offset":33047189,"length":2817,"mode":420},"/node_modules/hyper-proto-peer/node_modules/noise-handshake/dh.js":{"offset":33050006,"length":1439,"mode":420},"/node_modules/hyper-proto-peer/node_modules/noise-handshake/hkdf.js":{"offset":33051445,"length":1092,"mode":420},"/node_modules/hyper-proto-peer/node_modules/noise-handshake/hmac.js":{"offset":33052537,"length":1273,"mode":420},"/node_modules/hyper-proto-peer/node_modules/noise-handshake/noise.js":{"offset":33053810,"length":6437,"mode":420},"/node_modules/hyper-proto-peer/node_modules/noise-handshake/package.json":{"offset":33060247,"length":638,"mode":420},"/node_modules/hyper-proto-peer/node_modules/noise-handshake/symmetric-state.js":{"offset":33060885,"length":2206,"mode":420},"/node_modules/hyper-proto-peer/node_modules/protomux-rpc/index.js":{"offset":33063091,"length":9087,"mode":420},"/node_modules/hyper-proto-peer/node_modules/protomux-rpc/lib/errors.js":{"offset":33072178,"length":1273,"mode":420},"/node_modules/hyper-proto-peer/node_modules/protomux-rpc/node_modules/compact-encoding/endian.js":{"offset":33073451,"length":105,"mode":420},"/node_modules/hyper-proto-peer/node_modules/protomux-rpc/node_modules/compact-encoding/index.js":{"offset":33073556,"length":26406,"mode":420},"/node_modules/hyper-proto-peer/node_modules/protomux-rpc/node_modules/compact-encoding/lexint.js":{"offset":33099962,"length":2851,"mode":420},"/node_modules/hyper-proto-peer/node_modules/protomux-rpc/node_modules/compact-encoding/package.json":{"offset":33102813,"length":866,"mode":420},"/node_modules/hyper-proto-peer/node_modules/protomux-rpc/node_modules/compact-encoding/raw.js":{"offset":33103679,"length":3977,"mode":420},"/node_modules/hyper-proto-peer/node_modules/protomux-rpc/package.json":{"offset":33107656,"length":1188,"mode":420},"/node_modules/hyper-proto-peer/node_modules/protomux-wakeup/index.js":{"offset":33108844,"length":16824,"mode":420},"/node_modules/hyper-proto-peer/node_modules/protomux-wakeup/package.json":{"offset":33125668,"length":972,"mode":420},"/node_modules/hyper-proto-peer/node_modules/protomux-wakeup/spec/hyperschema/index.js":{"offset":33126640,"length":3335,"mode":420},"/node_modules/hyper-proto-peer/node_modules/protomux/index.js":{"offset":33129975,"length":19741,"mode":420},"/node_modules/hyper-proto-peer/node_modules/protomux/node_modules/compact-encoding/endian.js":{"offset":33149716,"length":105,"mode":420},"/node_modules/hyper-proto-peer/node_modules/protomux/node_modules/compact-encoding/index.js":{"offset":33149821,"length":26406,"mode":420},"/node_modules/hyper-proto-peer/node_modules/protomux/node_modules/compact-encoding/lexint.js":{"offset":33176227,"length":2851,"mode":420},"/node_modules/hyper-proto-peer/node_modules/protomux/node_modules/compact-encoding/package.json":{"offset":33179078,"length":866,"mode":420},"/node_modules/hyper-proto-peer/node_modules/protomux/node_modules/compact-encoding/raw.js":{"offset":33179944,"length":3977,"mode":420},"/node_modules/hyper-proto-peer/node_modules/protomux/package.json":{"offset":33183921,"length":1059,"mode":420},"/node_modules/hyper-proto-peer/node_modules/queue-tick/package.json":{"offset":33184980,"length":669,"mode":420},"/node_modules/hyper-proto-peer/node_modules/queue-tick/process-next-tick.js":{"offset":33185649,"length":160,"mode":420},"/node_modules/hyper-proto-peer/node_modules/queue-tick/queue-microtask.js":{"offset":33185809,"length":108,"mode":420},"/node_modules/hyper-proto-peer/node_modules/record-cache/index.js":{"offset":33185917,"length":3668,"mode":420},"/node_modules/hyper-proto-peer/node_modules/record-cache/package.json":{"offset":33189585,"length":612,"mode":420},"/node_modules/hyper-proto-peer/node_modules/require-addon/lib/bare.js":{"offset":33190197,"length":45,"mode":420},"/node_modules/hyper-proto-peer/node_modules/require-addon/package.json":{"offset":33190242,"length":1449,"mode":420},"/node_modules/hyper-proto-peer/node_modules/safety-catch/index.js":{"offset":33191691,"length":543,"mode":420},"/node_modules/hyper-proto-peer/node_modules/safety-catch/package.json":{"offset":33192234,"length":547,"mode":420},"/node_modules/hyper-proto-peer/node_modules/shuffled-priority-queue/index.js":{"offset":33192781,"length":2607,"mode":420},"/node_modules/hyper-proto-peer/node_modules/shuffled-priority-queue/package.json":{"offset":33195388,"length":691,"mode":420},"/node_modules/hyper-proto-peer/node_modules/signal-promise/index.js":{"offset":33196079,"length":1252,"mode":420},"/node_modules/hyper-proto-peer/node_modules/signal-promise/package.json":{"offset":33197331,"length":503,"mode":420},"/node_modules/hyper-proto-peer/node_modules/sodium-hmac/hash/sha256.js":{"offset":33197834,"length":284,"mode":420},"/node_modules/hyper-proto-peer/node_modules/sodium-hmac/hash/sha512.js":{"offset":33198118,"length":284,"mode":420},"/node_modules/hyper-proto-peer/node_modules/sodium-hmac/index.js":{"offset":33198402,"length":2063,"mode":420},"/node_modules/hyper-proto-peer/node_modules/sodium-hmac/package.json":{"offset":33200465,"length":670,"mode":420},"/node_modules/hyper-proto-peer/node_modules/sodium-native/binding.js":{"offset":33201135,"length":89,"mode":420},"/node_modules/hyper-proto-peer/node_modules/sodium-native/index.js":{"offset":33201224,"length":107894,"mode":420},"/node_modules/hyper-proto-peer/node_modules/sodium-native/package.json":{"offset":33309118,"length":1478,"mode":420},"/node_modules/hyper-proto-peer/node_modules/sodium-secretstream/index.js":{"offset":33310596,"length":2257,"mode":420},"/node_modules/hyper-proto-peer/node_modules/sodium-secretstream/package.json":{"offset":33312853,"length":657,"mode":420},"/node_modules/hyper-proto-peer/node_modules/sodium-universal/index.js":{"offset":33313510,"length":42,"mode":420},"/node_modules/hyper-proto-peer/node_modules/sodium-universal/package.json":{"offset":33313552,"length":1217,"mode":420},"/node_modules/hyper-proto-peer/node_modules/streamx/index.js":{"offset":33314769,"length":34248,"mode":420},"/node_modules/hyper-proto-peer/node_modules/streamx/lib/errors.js":{"offset":33349017,"length":1096,"mode":420},"/node_modules/hyper-proto-peer/node_modules/streamx/package.json":{"offset":33350113,"length":1225,"mode":420},"/node_modules/hyper-proto-peer/node_modules/teex/index.js":{"offset":33351338,"length":1107,"mode":420},"/node_modules/hyper-proto-peer/node_modules/teex/package.json":{"offset":33352445,"length":608,"mode":420},"/node_modules/hyper-proto-peer/node_modules/text-decoder/index.js":{"offset":33353053,"length":1371,"mode":420},"/node_modules/hyper-proto-peer/node_modules/text-decoder/lib/pass-through-decoder.js":{"offset":33354424,"length":269,"mode":420},"/node_modules/hyper-proto-peer/node_modules/text-decoder/lib/utf8-decoder.js":{"offset":33354693,"length":4429,"mode":420},"/node_modules/hyper-proto-peer/node_modules/text-decoder/package.json":{"offset":33359122,"length":990,"mode":420},"/node_modules/hyper-proto-peer/node_modules/time-ordered-set/index.js":{"offset":33360112,"length":1444,"mode":420},"/node_modules/hyper-proto-peer/node_modules/time-ordered-set/package.json":{"offset":33361556,"length":666,"mode":420},"/node_modules/hyper-proto-peer/node_modules/timeout-refresh/browser.js":{"offset":33362222,"length":1098,"mode":420},"/node_modules/hyper-proto-peer/node_modules/timeout-refresh/index.js":{"offset":33363320,"length":184,"mode":420},"/node_modules/hyper-proto-peer/node_modules/timeout-refresh/node.js":{"offset":33363504,"length":928,"mode":420},"/node_modules/hyper-proto-peer/node_modules/timeout-refresh/package.json":{"offset":33364432,"length":619,"mode":420},"/node_modules/hyper-proto-peer/node_modules/udx-native/binding.js":{"offset":33365051,"length":90,"mode":420},"/node_modules/hyper-proto-peer/node_modules/udx-native/lib/ip.js":{"offset":33365141,"length":2204,"mode":420},"/node_modules/hyper-proto-peer/node_modules/udx-native/lib/network-interfaces.js":{"offset":33367345,"length":1341,"mode":420},"/node_modules/hyper-proto-peer/node_modules/udx-native/lib/socket.js":{"offset":33368686,"length":7557,"mode":420},"/node_modules/hyper-proto-peer/node_modules/udx-native/lib/stream.js":{"offset":33376243,"length":13050,"mode":420},"/node_modules/hyper-proto-peer/node_modules/udx-native/lib/udx.js":{"offset":33389293,"length":2868,"mode":420},"/node_modules/hyper-proto-peer/node_modules/udx-native/package.json":{"offset":33392161,"length":1665,"mode":420},"/node_modules/hyper-proto-peer/node_modules/unordered-set/index.js":{"offset":33393826,"length":677,"mode":420},"/node_modules/hyper-proto-peer/node_modules/unordered-set/package.json":{"offset":33394503,"length":654,"mode":420},"/node_modules/hyper-proto-peer/node_modules/unslab/index.js":{"offset":33395157,"length":913,"mode":420},"/node_modules/hyper-proto-peer/node_modules/unslab/package.json":{"offset":33396070,"length":613,"mode":420},"/node_modules/hyper-proto-peer/node_modules/which-runtime/index.js":{"offset":33396683,"length":1469,"mode":420},"/node_modules/hyper-proto-peer/node_modules/which-runtime/package.json":{"offset":33398152,"length":863,"mode":420},"/node_modules/hyper-proto-peer/node_modules/xache/index.js":{"offset":33399015,"length":2378,"mode":420},"/node_modules/hyper-proto-peer/node_modules/xache/package.json":{"offset":33401393,"length":584,"mode":420},"/node_modules/hyper-proto-peer/node_modules/z32/index.js":{"offset":33401977,"length":2654,"mode":420},"/node_modules/hyper-proto-peer/node_modules/z32/package.json":{"offset":33404631,"length":701,"mode":420},"/node_modules/hyper-proto-peer/package.json":{"offset":33405332,"length":2256,"mode":420},"/node_modules/hyper-svc/index.js":{"offset":33407588,"length":424,"mode":420},"/node_modules/hyper-svc/lib/client.js":{"offset":33408012,"length":14860,"mode":420},"/node_modules/hyper-svc/lib/frame.js":{"offset":33422872,"length":1862,"mode":420},"/node_modules/hyper-svc/lib/service.js":{"offset":33424734,"length":11770,"mode":420},"/node_modules/hyper-svc/lib/transports/http.js":{"offset":33436504,"length":7998,"mode":420},"/node_modules/hyper-svc/lib/transports/swarm-rpc.js":{"offset":33444502,"length":4427,"mode":420},"/node_modules/hyper-svc/lib/transports/swarm.js":{"offset":33448929,"length":8308,"mode":420},"/node_modules/hyper-svc/lib/transports/uds.js":{"offset":33457237,"length":8779,"mode":420},"/node_modules/hyper-svc/lib/uds-backend.js":{"offset":33466016,"length":1568,"mode":420},"/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/index.js":{"offset":33467584,"length":16722,"mode":420},"/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/lib/bridge.js":{"offset":33484306,"length":1273,"mode":420},"/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/lib/handshake.js":{"offset":33485579,"length":1950,"mode":420},"/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/package.json":{"offset":33487529,"length":1132,"mode":420},"/node_modules/hyper-svc/node_modules/adaptive-timeout/index.js":{"offset":33488661,"length":2424,"mode":420},"/node_modules/hyper-svc/node_modules/adaptive-timeout/package.json":{"offset":33491085,"length":972,"mode":420},"/node_modules/hyper-svc/node_modules/b4a/index.js":{"offset":33492057,"length":4054,"mode":420},"/node_modules/hyper-svc/node_modules/b4a/package.json":{"offset":33496111,"length":1245,"mode":420},"/node_modules/hyper-svc/node_modules/bare-abort/binding.js":{"offset":33497356,"length":33,"mode":420},"/node_modules/hyper-svc/node_modules/bare-abort/index.js":{"offset":33497389,"length":69,"mode":420},"/node_modules/hyper-svc/node_modules/bare-abort/package.json":{"offset":33497458,"length":886,"mode":420},"/node_modules/hyper-svc/node_modules/bare-ansi-escapes/index.js":{"offset":33498344,"length":2255,"mode":420},"/node_modules/hyper-svc/node_modules/bare-ansi-escapes/package.json":{"offset":33500599,"length":1178,"mode":420},"/node_modules/hyper-svc/node_modules/bare-assert/index.js":{"offset":33501777,"length":2192,"mode":420},"/node_modules/hyper-svc/node_modules/bare-assert/package.json":{"offset":33503969,"length":835,"mode":420},"/node_modules/hyper-svc/node_modules/bare-dns/binding.js":{"offset":33504804,"length":33,"mode":420},"/node_modules/hyper-svc/node_modules/bare-dns/index.js":{"offset":33504837,"length":1345,"mode":420},"/node_modules/hyper-svc/node_modules/bare-dns/package.json":{"offset":33506182,"length":968,"mode":420},"/node_modules/hyper-svc/node_modules/bare-env/index.js":{"offset":33507150,"length":1023,"mode":420},"/node_modules/hyper-svc/node_modules/bare-env/package.json":{"offset":33508173,"length":649,"mode":420},"/node_modules/hyper-svc/node_modules/bare-events/index.js":{"offset":33508822,"length":8033,"mode":420},"/node_modules/hyper-svc/node_modules/bare-events/lib/errors.js":{"offset":33516855,"length":671,"mode":420},"/node_modules/hyper-svc/node_modules/bare-events/package.json":{"offset":33517526,"length":1399,"mode":420},"/node_modules/hyper-svc/node_modules/bare-fs/binding.js":{"offset":33518925,"length":33,"mode":420},"/node_modules/hyper-svc/node_modules/bare-fs/index.js":{"offset":33518958,"length":58907,"mode":420},"/node_modules/hyper-svc/node_modules/bare-fs/lib/constants.js":{"offset":33577865,"length":1494,"mode":420},"/node_modules/hyper-svc/node_modules/bare-fs/lib/errors.js":{"offset":33579359,"length":1163,"mode":420},"/node_modules/hyper-svc/node_modules/bare-fs/package.json":{"offset":33580522,"length":1654,"mode":420},"/node_modules/hyper-svc/node_modules/bare-fs/promises.js":{"offset":33582176,"length":2401,"mode":420},"/node_modules/hyper-svc/node_modules/bare-hrtime/binding.js":{"offset":33584577,"length":33,"mode":420},"/node_modules/hyper-svc/node_modules/bare-hrtime/index.js":{"offset":33584610,"length":319,"mode":420},"/node_modules/hyper-svc/node_modules/bare-hrtime/package.json":{"offset":33584929,"length":905,"mode":420},"/node_modules/hyper-svc/node_modules/bare-http-parser/index.js":{"offset":33585834,"length":17480,"mode":420},"/node_modules/hyper-svc/node_modules/bare-http-parser/lib/errors.js":{"offset":33603314,"length":845,"mode":420},"/node_modules/hyper-svc/node_modules/bare-http-parser/package.json":{"offset":33604159,"length":793,"mode":420},"/node_modules/hyper-svc/node_modules/bare-http1/index.js":{"offset":33604952,"length":2188,"mode":420},"/node_modules/hyper-svc/node_modules/bare-http1/lib/agent.js":{"offset":33607140,"length":4498,"mode":420},"/node_modules/hyper-svc/node_modules/bare-http1/lib/client-connection.js":{"offset":33611638,"length":3663,"mode":420},"/node_modules/hyper-svc/node_modules/bare-http1/lib/client-request.js":{"offset":33615301,"length":3286,"mode":420},"/node_modules/hyper-svc/node_modules/bare-http1/lib/constants.js":{"offset":33618587,"length":2016,"mode":420},"/node_modules/hyper-svc/node_modules/bare-http1/lib/errors.js":{"offset":33620603,"length":634,"mode":420},"/node_modules/hyper-svc/node_modules/bare-http1/lib/incoming-message.js":{"offset":33621237,"length":1568,"mode":420},"/node_modules/hyper-svc/node_modules/bare-http1/lib/outgoing-message.js":{"offset":33622805,"length":1291,"mode":420},"/node_modules/hyper-svc/node_modules/bare-http1/lib/server-connection.js":{"offset":33624096,"length":4041,"mode":420},"/node_modules/hyper-svc/node_modules/bare-http1/lib/server-response.js":{"offset":33628137,"length":3183,"mode":420},"/node_modules/hyper-svc/node_modules/bare-http1/lib/server.js":{"offset":33631320,"length":977,"mode":420},"/node_modules/hyper-svc/node_modules/bare-http1/package.json":{"offset":33632297,"length":1510,"mode":420},"/node_modules/hyper-svc/node_modules/bare-inspect/binding.js":{"offset":33633807,"length":33,"mode":420},"/node_modules/hyper-svc/node_modules/bare-inspect/index.js":{"offset":33633840,"length":23856,"mode":420},"/node_modules/hyper-svc/node_modules/bare-inspect/package.json":{"offset":33657696,"length":1041,"mode":420},"/node_modules/hyper-svc/node_modules/bare-net/index.js":{"offset":33658737,"length":6868,"mode":420},"/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-dns/binding.js":{"offset":33665605,"length":33,"mode":420},"/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-dns/index.js":{"offset":33665638,"length":860,"mode":420},"/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-dns/package.json":{"offset":33666498,"length":772,"mode":420},"/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/binding.js":{"offset":33667270,"length":33,"mode":420},"/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/index.js":{"offset":33667303,"length":10947,"mode":420},"/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/lib/constants.js":{"offset":33678250,"length":188,"mode":420},"/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/lib/errors.js":{"offset":33678438,"length":668,"mode":420},"/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/package.json":{"offset":33679106,"length":962,"mode":420},"/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/binding.js":{"offset":33680068,"length":33,"mode":420},"/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/index.js":{"offset":33680101,"length":12710,"mode":420},"/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/lib/constants.js":{"offset":33692811,"length":167,"mode":420},"/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/lib/errors.js":{"offset":33692978,"length":799,"mode":420},"/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/lib/ip.js":{"offset":33693777,"length":2179,"mode":420},"/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/package.json":{"offset":33695956,"length":959,"mode":420},"/node_modules/hyper-svc/node_modules/bare-net/package.json":{"offset":33696915,"length":793,"mode":420},"/node_modules/hyper-svc/node_modules/bare-os/binding.js":{"offset":33697708,"length":33,"mode":420},"/node_modules/hyper-svc/node_modules/bare-os/index.js":{"offset":33697741,"length":3224,"mode":420},"/node_modules/hyper-svc/node_modules/bare-os/lib/constants.js":{"offset":33700965,"length":143,"mode":420},"/node_modules/hyper-svc/node_modules/bare-os/lib/errors.js":{"offset":33701108,"length":453,"mode":420},"/node_modules/hyper-svc/node_modules/bare-os/package.json":{"offset":33701561,"length":1257,"mode":420},"/node_modules/hyper-svc/node_modules/bare-path/index.js":{"offset":33702818,"length":306,"mode":420},"/node_modules/hyper-svc/node_modules/bare-path/lib/constants.js":{"offset":33703124,"length":247,"mode":420},"/node_modules/hyper-svc/node_modules/bare-path/lib/posix.js":{"offset":33703371,"length":5991,"mode":420},"/node_modules/hyper-svc/node_modules/bare-path/lib/shared.js":{"offset":33709362,"length":1888,"mode":420},"/node_modules/hyper-svc/node_modules/bare-path/lib/win32.js":{"offset":33711250,"length":13427,"mode":420},"/node_modules/hyper-svc/node_modules/bare-path/package.json":{"offset":33724677,"length":796,"mode":420},"/node_modules/hyper-svc/node_modules/bare-pipe/binding.js":{"offset":33725473,"length":33,"mode":420},"/node_modules/hyper-svc/node_modules/bare-pipe/index.js":{"offset":33725506,"length":10769,"mode":420},"/node_modules/hyper-svc/node_modules/bare-pipe/lib/constants.js":{"offset":33736275,"length":208,"mode":420},"/node_modules/hyper-svc/node_modules/bare-pipe/lib/errors.js":{"offset":33736483,"length":599,"mode":420},"/node_modules/hyper-svc/node_modules/bare-pipe/package.json":{"offset":33737082,"length":1256,"mode":420},"/node_modules/hyper-svc/node_modules/bare-process/index.js":{"offset":33738338,"length":2689,"mode":420},"/node_modules/hyper-svc/node_modules/bare-process/package.json":{"offset":33741027,"length":1255,"mode":420},"/node_modules/hyper-svc/node_modules/bare-signals/binding.js":{"offset":33742282,"length":33,"mode":420},"/node_modules/hyper-svc/node_modules/bare-signals/index.js":{"offset":33742315,"length":1517,"mode":420},"/node_modules/hyper-svc/node_modules/bare-signals/lib/emitter.js":{"offset":33743832,"length":1278,"mode":420},"/node_modules/hyper-svc/node_modules/bare-signals/lib/errors.js":{"offset":33745110,"length":479,"mode":420},"/node_modules/hyper-svc/node_modules/bare-signals/package.json":{"offset":33745589,"length":1112,"mode":420},"/node_modules/hyper-svc/node_modules/bare-stdio/binding.js":{"offset":33746701,"length":33,"mode":420},"/node_modules/hyper-svc/node_modules/bare-stdio/index.js":{"offset":33746734,"length":1525,"mode":420},"/node_modules/hyper-svc/node_modules/bare-stdio/package.json":{"offset":33748259,"length":1319,"mode":420},"/node_modules/hyper-svc/node_modules/bare-stream/index.js":{"offset":33749578,"length":10913,"mode":420},"/node_modules/hyper-svc/node_modules/bare-stream/package.json":{"offset":33760491,"length":1655,"mode":420},"/node_modules/hyper-svc/node_modules/bare-stream/web.js":{"offset":33762146,"length":13980,"mode":420},"/node_modules/hyper-svc/node_modules/bare-tcp/binding.js":{"offset":33776126,"length":33,"mode":420},"/node_modules/hyper-svc/node_modules/bare-tcp/index.js":{"offset":33776159,"length":15054,"mode":420},"/node_modules/hyper-svc/node_modules/bare-tcp/lib/constants.js":{"offset":33791213,"length":167,"mode":420},"/node_modules/hyper-svc/node_modules/bare-tcp/lib/errors.js":{"offset":33791380,"length":711,"mode":420},"/node_modules/hyper-svc/node_modules/bare-tcp/lib/ip.js":{"offset":33792091,"length":2204,"mode":420},"/node_modules/hyper-svc/node_modules/bare-tcp/package.json":{"offset":33794295,"length":1243,"mode":420},"/node_modules/hyper-svc/node_modules/bare-tty/binding.js":{"offset":33795538,"length":33,"mode":420},"/node_modules/hyper-svc/node_modules/bare-tty/index.js":{"offset":33795571,"length":4469,"mode":420},"/node_modules/hyper-svc/node_modules/bare-tty/lib/constants.js":{"offset":33800040,"length":442,"mode":420},"/node_modules/hyper-svc/node_modules/bare-tty/package.json":{"offset":33800482,"length":1097,"mode":420},"/node_modules/hyper-svc/node_modules/bare-type/binding.js":{"offset":33801579,"length":33,"mode":420},"/node_modules/hyper-svc/node_modules/bare-type/index.js":{"offset":33801612,"length":4566,"mode":420},"/node_modules/hyper-svc/node_modules/bare-type/package.json":{"offset":33806178,"length":938,"mode":420},"/node_modules/hyper-svc/node_modules/bare-url/binding.js":{"offset":33807116,"length":33,"mode":420},"/node_modules/hyper-svc/node_modules/bare-url/index.js":{"offset":33807149,"length":9308,"mode":420},"/node_modules/hyper-svc/node_modules/bare-url/lib/errors.js":{"offset":33816457,"length":778,"mode":420},"/node_modules/hyper-svc/node_modules/bare-url/lib/url-search-params.js":{"offset":33817235,"length":4331,"mode":420},"/node_modules/hyper-svc/node_modules/bare-url/package.json":{"offset":33821566,"length":1219,"mode":420},"/node_modules/hyper-svc/node_modules/bits-to-bytes/index.js":{"offset":33822785,"length":3083,"mode":420},"/node_modules/hyper-svc/node_modules/bits-to-bytes/package.json":{"offset":33825868,"length":708,"mode":420},"/node_modules/hyper-svc/node_modules/blind-relay/index.js":{"offset":33826576,"length":13256,"mode":420},"/node_modules/hyper-svc/node_modules/blind-relay/lib/errors.js":{"offset":33839832,"length":1036,"mode":420},"/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/endian.js":{"offset":33840868,"length":105,"mode":420},"/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/index.js":{"offset":33840973,"length":24454,"mode":420},"/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/lexint.js":{"offset":33865427,"length":2851,"mode":420},"/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/package.json":{"offset":33868278,"length":786,"mode":420},"/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/raw.js":{"offset":33869064,"length":4093,"mode":420},"/node_modules/hyper-svc/node_modules/blind-relay/package.json":{"offset":33873157,"length":1232,"mode":420},"/node_modules/hyper-svc/node_modules/bogon/index.js":{"offset":33874389,"length":4052,"mode":420},"/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/endian.js":{"offset":33878441,"length":105,"mode":420},"/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/index.js":{"offset":33878546,"length":24454,"mode":420},"/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/lexint.js":{"offset":33903000,"length":2851,"mode":420},"/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/package.json":{"offset":33905851,"length":786,"mode":420},"/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/raw.js":{"offset":33906637,"length":4093,"mode":420},"/node_modules/hyper-svc/node_modules/bogon/package.json":{"offset":33910730,"length":657,"mode":420},"/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/index.js":{"offset":33911387,"length":1963,"mode":420},"/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/endian.js":{"offset":33913350,"length":105,"mode":420},"/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/index.js":{"offset":33913455,"length":24454,"mode":420},"/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/lexint.js":{"offset":33937909,"length":2851,"mode":420},"/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/package.json":{"offset":33940760,"length":786,"mode":420},"/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/raw.js":{"offset":33941546,"length":4093,"mode":420},"/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/package.json":{"offset":33945639,"length":827,"mode":420},"/node_modules/hyper-svc/node_modules/compact-encoding-net/index.js":{"offset":33946466,"length":4109,"mode":420},"/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/endian.js":{"offset":33950575,"length":105,"mode":420},"/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/index.js":{"offset":33950680,"length":24454,"mode":420},"/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/lexint.js":{"offset":33975134,"length":2851,"mode":420},"/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/package.json":{"offset":33977985,"length":786,"mode":420},"/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/raw.js":{"offset":33978771,"length":4093,"mode":420},"/node_modules/hyper-svc/node_modules/compact-encoding-net/package.json":{"offset":33982864,"length":734,"mode":420},"/node_modules/hyper-svc/node_modules/compact-encoding/endian.js":{"offset":33983598,"length":105,"mode":420},"/node_modules/hyper-svc/node_modules/compact-encoding/index.js":{"offset":33983703,"length":26135,"mode":420},"/node_modules/hyper-svc/node_modules/compact-encoding/lexint.js":{"offset":34009838,"length":2851,"mode":420},"/node_modules/hyper-svc/node_modules/compact-encoding/package.json":{"offset":34012689,"length":866,"mode":420},"/node_modules/hyper-svc/node_modules/compact-encoding/raw.js":{"offset":34013555,"length":3977,"mode":420},"/node_modules/hyper-svc/node_modules/dht-rpc/index.js":{"offset":34017532,"length":29079,"mode":420},"/node_modules/hyper-svc/node_modules/dht-rpc/lib/commands.js":{"offset":34046611,"length":107,"mode":420},"/node_modules/hyper-svc/node_modules/dht-rpc/lib/errors.js":{"offset":34046718,"length":719,"mode":420},"/node_modules/hyper-svc/node_modules/dht-rpc/lib/health.js":{"offset":34047437,"length":2998,"mode":420},"/node_modules/hyper-svc/node_modules/dht-rpc/lib/io.js":{"offset":34050435,"length":16605,"mode":420},"/node_modules/hyper-svc/node_modules/dht-rpc/lib/peer.js":{"offset":34067040,"length":631,"mode":420},"/node_modules/hyper-svc/node_modules/dht-rpc/lib/query.js":{"offset":34067671,"length":9899,"mode":420},"/node_modules/hyper-svc/node_modules/dht-rpc/lib/session.js":{"offset":34077570,"length":1103,"mode":420},"/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/endian.js":{"offset":34078673,"length":105,"mode":420},"/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/index.js":{"offset":34078778,"length":24454,"mode":420},"/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/lexint.js":{"offset":34103232,"length":2851,"mode":420},"/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/package.json":{"offset":34106083,"length":786,"mode":420},"/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/raw.js":{"offset":34106869,"length":4093,"mode":420},"/node_modules/hyper-svc/node_modules/dht-rpc/package.json":{"offset":34110962,"length":1397,"mode":420},"/node_modules/hyper-svc/node_modules/events-universal/bare.js":{"offset":34112359,"length":40,"mode":420},"/node_modules/hyper-svc/node_modules/events-universal/package.json":{"offset":34112399,"length":908,"mode":420},"/node_modules/hyper-svc/node_modules/fast-fifo/fixed-size.js":{"offset":34113307,"length":875,"mode":420},"/node_modules/hyper-svc/node_modules/fast-fifo/index.js":{"offset":34114182,"length":972,"mode":420},"/node_modules/hyper-svc/node_modules/fast-fifo/package.json":{"offset":34115154,"length":682,"mode":420},"/node_modules/hyper-svc/node_modules/hypercore-crypto/index.js":{"offset":34115836,"length":5040,"mode":420},"/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/endian.js":{"offset":34120876,"length":105,"mode":420},"/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/index.js":{"offset":34120981,"length":24454,"mode":420},"/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/lexint.js":{"offset":34145435,"length":2851,"mode":420},"/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/package.json":{"offset":34148286,"length":786,"mode":420},"/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/raw.js":{"offset":34149072,"length":4093,"mode":420},"/node_modules/hyper-svc/node_modules/hypercore-crypto/package.json":{"offset":34153165,"length":771,"mode":420},"/node_modules/hyper-svc/node_modules/hypercore-id-encoding/index.js":{"offset":34153936,"length":923,"mode":420},"/node_modules/hyper-svc/node_modules/hypercore-id-encoding/package.json":{"offset":34154859,"length":799,"mode":420},"/node_modules/hyper-svc/node_modules/hyperdht-address/index.js":{"offset":34155658,"length":357,"mode":420},"/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/endian.js":{"offset":34156015,"length":105,"mode":420},"/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/index.js":{"offset":34156120,"length":24454,"mode":420},"/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/lexint.js":{"offset":34180574,"length":2851,"mode":420},"/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/package.json":{"offset":34183425,"length":786,"mode":420},"/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/raw.js":{"offset":34184211,"length":4093,"mode":420},"/node_modules/hyper-svc/node_modules/hyperdht-address/package.json":{"offset":34188304,"length":1047,"mode":420},"/node_modules/hyper-svc/node_modules/hyperdht-address/spec/hyperschema/index.js":{"offset":34189351,"length":2106,"mode":420},"/node_modules/hyper-svc/node_modules/hyperdht/index.js":{"offset":34191457,"length":16611,"mode":420},"/node_modules/hyper-svc/node_modules/hyperdht/lib/announcer.js":{"offset":34208068,"length":7533,"mode":420},"/node_modules/hyper-svc/node_modules/hyperdht/lib/connect.js":{"offset":34215601,"length":24788,"mode":420},"/node_modules/hyper-svc/node_modules/hyperdht/lib/connection-pool.js":{"offset":34240389,"length":3050,"mode":420},"/node_modules/hyper-svc/node_modules/hyperdht/lib/constants.js":{"offset":34243439,"length":1276,"mode":420},"/node_modules/hyper-svc/node_modules/hyperdht/lib/crypto.js":{"offset":34244715,"length":632,"mode":420},"/node_modules/hyper-svc/node_modules/hyperdht/lib/encode.js":{"offset":34245347,"length":446,"mode":420},"/node_modules/hyper-svc/node_modules/hyperdht/lib/errors.js":{"offset":34245793,"length":3712,"mode":420},"/node_modules/hyper-svc/node_modules/hyperdht/lib/holepuncher.js":{"offset":34249505,"length":10003,"mode":420},"/node_modules/hyper-svc/node_modules/hyperdht/lib/messages.js":{"offset":34259508,"length":11789,"mode":420},"/node_modules/hyper-svc/node_modules/hyperdht/lib/nat.js":{"offset":34271297,"length":4714,"mode":420},"/node_modules/hyper-svc/node_modules/hyperdht/lib/noise-wrap.js":{"offset":34276011,"length":1669,"mode":420},"/node_modules/hyper-svc/node_modules/hyperdht/lib/persistent.js":{"offset":34277680,"length":8361,"mode":420},"/node_modules/hyper-svc/node_modules/hyperdht/lib/raw-stream-set.js":{"offset":34286041,"length":1511,"mode":420},"/node_modules/hyper-svc/node_modules/hyperdht/lib/router.js":{"offset":34287552,"length":6978,"mode":420},"/node_modules/hyper-svc/node_modules/hyperdht/lib/secure-payload.js":{"offset":34294530,"length":1491,"mode":420},"/node_modules/hyper-svc/node_modules/hyperdht/lib/semaphore.js":{"offset":34296021,"length":1577,"mode":420},"/node_modules/hyper-svc/node_modules/hyperdht/lib/server.js":{"offset":34297598,"length":21300,"mode":420},"/node_modules/hyper-svc/node_modules/hyperdht/lib/sleeper.js":{"offset":34318898,"length":690,"mode":420},"/node_modules/hyper-svc/node_modules/hyperdht/lib/socket-pool.js":{"offset":34319588,"length":4343,"mode":420},"/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/endian.js":{"offset":34323931,"length":105,"mode":420},"/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/index.js":{"offset":34324036,"length":24454,"mode":420},"/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/lexint.js":{"offset":34348490,"length":2851,"mode":420},"/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/package.json":{"offset":34351341,"length":786,"mode":420},"/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/raw.js":{"offset":34352127,"length":4093,"mode":420},"/node_modules/hyper-svc/node_modules/hyperdht/package.json":{"offset":34356220,"length":2007,"mode":420},"/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/endian.js":{"offset":34358227,"length":105,"mode":420},"/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/index.js":{"offset":34358332,"length":24454,"mode":420},"/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/lexint.js":{"offset":34382786,"length":2851,"mode":420},"/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/package.json":{"offset":34385637,"length":786,"mode":420},"/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/raw.js":{"offset":34386423,"length":4093,"mode":420},"/node_modules/hyper-svc/node_modules/hyperschema/package.json":{"offset":34390516,"length":1556,"mode":420},"/node_modules/hyper-svc/node_modules/hyperschema/runtime.cjs":{"offset":34392072,"length":54,"mode":420},"/node_modules/hyper-svc/node_modules/hyperswarm/index.js":{"offset":34392126,"length":18589,"mode":420},"/node_modules/hyper-svc/node_modules/hyperswarm/lib/bulk-timer.js":{"offset":34410715,"length":728,"mode":420},"/node_modules/hyper-svc/node_modules/hyperswarm/lib/connection-set.js":{"offset":34411443,"length":823,"mode":420},"/node_modules/hyper-svc/node_modules/hyperswarm/lib/peer-discovery.js":{"offset":34412266,"length":9296,"mode":420},"/node_modules/hyper-svc/node_modules/hyperswarm/lib/peer-info.js":{"offset":34421562,"length":2688,"mode":420},"/node_modules/hyper-svc/node_modules/hyperswarm/lib/retry-timer.js":{"offset":34424250,"length":1889,"mode":420},"/node_modules/hyper-svc/node_modules/hyperswarm/package.json":{"offset":34426139,"length":1515,"mode":420},"/node_modules/hyper-svc/node_modules/kademlia-routing-table/index.js":{"offset":34427654,"length":4145,"mode":420},"/node_modules/hyper-svc/node_modules/kademlia-routing-table/package.json":{"offset":34431799,"length":967,"mode":420},"/node_modules/hyper-svc/node_modules/nanoassert/index.js":{"offset":34432766,"length":438,"mode":420},"/node_modules/hyper-svc/node_modules/nanoassert/package.json":{"offset":34433204,"length":647,"mode":420},"/node_modules/hyper-svc/node_modules/nat-sampler/index.js":{"offset":34433851,"length":1550,"mode":420},"/node_modules/hyper-svc/node_modules/nat-sampler/package.json":{"offset":34435401,"length":608,"mode":420},"/node_modules/hyper-svc/node_modules/noise-curve-ed/index.js":{"offset":34436009,"length":1642,"mode":420},"/node_modules/hyper-svc/node_modules/noise-curve-ed/package.json":{"offset":34437651,"length":808,"mode":420},"/node_modules/hyper-svc/node_modules/noise-handshake/cipher.js":{"offset":34438459,"length":2817,"mode":420},"/node_modules/hyper-svc/node_modules/noise-handshake/dh.js":{"offset":34441276,"length":1439,"mode":420},"/node_modules/hyper-svc/node_modules/noise-handshake/hkdf.js":{"offset":34442715,"length":1092,"mode":420},"/node_modules/hyper-svc/node_modules/noise-handshake/hmac.js":{"offset":34443807,"length":1273,"mode":420},"/node_modules/hyper-svc/node_modules/noise-handshake/noise.js":{"offset":34445080,"length":6437,"mode":420},"/node_modules/hyper-svc/node_modules/noise-handshake/package.json":{"offset":34451517,"length":638,"mode":420},"/node_modules/hyper-svc/node_modules/noise-handshake/symmetric-state.js":{"offset":34452155,"length":2206,"mode":420},"/node_modules/hyper-svc/node_modules/protomux/index.js":{"offset":34454361,"length":19741,"mode":420},"/node_modules/hyper-svc/node_modules/protomux/package.json":{"offset":34474102,"length":1059,"mode":420},"/node_modules/hyper-svc/node_modules/queue-tick/package.json":{"offset":34475161,"length":669,"mode":420},"/node_modules/hyper-svc/node_modules/queue-tick/process-next-tick.js":{"offset":34475830,"length":160,"mode":420},"/node_modules/hyper-svc/node_modules/queue-tick/queue-microtask.js":{"offset":34475990,"length":108,"mode":420},"/node_modules/hyper-svc/node_modules/ready-resource/index.js":{"offset":34476098,"length":1091,"mode":420},"/node_modules/hyper-svc/node_modules/ready-resource/package.json":{"offset":34477189,"length":812,"mode":420},"/node_modules/hyper-svc/node_modules/record-cache/index.js":{"offset":34478001,"length":3668,"mode":420},"/node_modules/hyper-svc/node_modules/record-cache/package.json":{"offset":34481669,"length":612,"mode":420},"/node_modules/hyper-svc/node_modules/require-addon/lib/bare.js":{"offset":34482281,"length":45,"mode":420},"/node_modules/hyper-svc/node_modules/require-addon/package.json":{"offset":34482326,"length":1449,"mode":420},"/node_modules/hyper-svc/node_modules/safety-catch/index.js":{"offset":34483775,"length":543,"mode":420},"/node_modules/hyper-svc/node_modules/safety-catch/package.json":{"offset":34484318,"length":547,"mode":420},"/node_modules/hyper-svc/node_modules/shuffled-priority-queue/index.js":{"offset":34484865,"length":2607,"mode":420},"/node_modules/hyper-svc/node_modules/shuffled-priority-queue/package.json":{"offset":34487472,"length":691,"mode":420},"/node_modules/hyper-svc/node_modules/signal-promise/index.js":{"offset":34488163,"length":1252,"mode":420},"/node_modules/hyper-svc/node_modules/signal-promise/package.json":{"offset":34489415,"length":503,"mode":420},"/node_modules/hyper-svc/node_modules/sodium-native/binding.js":{"offset":34489918,"length":89,"mode":420},"/node_modules/hyper-svc/node_modules/sodium-native/index.js":{"offset":34490007,"length":107894,"mode":420},"/node_modules/hyper-svc/node_modules/sodium-native/package.json":{"offset":34597901,"length":1478,"mode":420},"/node_modules/hyper-svc/node_modules/sodium-secretstream/index.js":{"offset":34599379,"length":2257,"mode":420},"/node_modules/hyper-svc/node_modules/sodium-secretstream/package.json":{"offset":34601636,"length":657,"mode":420},"/node_modules/hyper-svc/node_modules/sodium-universal/index.js":{"offset":34602293,"length":42,"mode":420},"/node_modules/hyper-svc/node_modules/sodium-universal/package.json":{"offset":34602335,"length":1217,"mode":420},"/node_modules/hyper-svc/node_modules/streamx/index.js":{"offset":34603552,"length":33510,"mode":420},"/node_modules/hyper-svc/node_modules/streamx/package.json":{"offset":34637062,"length":912,"mode":420},"/node_modules/hyper-svc/node_modules/teex/index.js":{"offset":34637974,"length":1107,"mode":420},"/node_modules/hyper-svc/node_modules/teex/package.json":{"offset":34639081,"length":608,"mode":420},"/node_modules/hyper-svc/node_modules/text-decoder/index.js":{"offset":34639689,"length":1371,"mode":420},"/node_modules/hyper-svc/node_modules/text-decoder/lib/pass-through-decoder.js":{"offset":34641060,"length":269,"mode":420},"/node_modules/hyper-svc/node_modules/text-decoder/lib/utf8-decoder.js":{"offset":34641329,"length":4429,"mode":420},"/node_modules/hyper-svc/node_modules/text-decoder/package.json":{"offset":34645758,"length":990,"mode":420},"/node_modules/hyper-svc/node_modules/time-ordered-set/index.js":{"offset":34646748,"length":1444,"mode":420},"/node_modules/hyper-svc/node_modules/time-ordered-set/package.json":{"offset":34648192,"length":666,"mode":420},"/node_modules/hyper-svc/node_modules/timeout-refresh/browser.js":{"offset":34648858,"length":1098,"mode":420},"/node_modules/hyper-svc/node_modules/timeout-refresh/index.js":{"offset":34649956,"length":184,"mode":420},"/node_modules/hyper-svc/node_modules/timeout-refresh/node.js":{"offset":34650140,"length":928,"mode":420},"/node_modules/hyper-svc/node_modules/timeout-refresh/package.json":{"offset":34651068,"length":619,"mode":420},"/node_modules/hyper-svc/node_modules/udx-native/binding.js":{"offset":34651687,"length":90,"mode":420},"/node_modules/hyper-svc/node_modules/udx-native/lib/ip.js":{"offset":34651777,"length":2204,"mode":420},"/node_modules/hyper-svc/node_modules/udx-native/lib/network-interfaces.js":{"offset":34653981,"length":1341,"mode":420},"/node_modules/hyper-svc/node_modules/udx-native/lib/socket.js":{"offset":34655322,"length":7557,"mode":420},"/node_modules/hyper-svc/node_modules/udx-native/lib/stream.js":{"offset":34662879,"length":12706,"mode":420},"/node_modules/hyper-svc/node_modules/udx-native/lib/udx.js":{"offset":34675585,"length":2868,"mode":420},"/node_modules/hyper-svc/node_modules/udx-native/package.json":{"offset":34678453,"length":1615,"mode":420},"/node_modules/hyper-svc/node_modules/unordered-set/index.js":{"offset":34680068,"length":677,"mode":420},"/node_modules/hyper-svc/node_modules/unordered-set/package.json":{"offset":34680745,"length":654,"mode":420},"/node_modules/hyper-svc/node_modules/unslab/index.js":{"offset":34681399,"length":913,"mode":420},"/node_modules/hyper-svc/node_modules/unslab/package.json":{"offset":34682312,"length":613,"mode":420},"/node_modules/hyper-svc/node_modules/which-runtime/index.js":{"offset":34682925,"length":1231,"mode":420},"/node_modules/hyper-svc/node_modules/which-runtime/package.json":{"offset":34684156,"length":602,"mode":420},"/node_modules/hyper-svc/node_modules/xache/index.js":{"offset":34684758,"length":2378,"mode":420},"/node_modules/hyper-svc/node_modules/xache/package.json":{"offset":34687136,"length":584,"mode":420},"/node_modules/hyper-svc/node_modules/z32/index.js":{"offset":34687720,"length":2654,"mode":420},"/node_modules/hyper-svc/node_modules/z32/package.json":{"offset":34690374,"length":701,"mode":420},"/node_modules/hyper-svc/package.json":{"offset":34691075,"length":1873,"mode":420},"/node_modules/hypercore-crypto/index.js":{"offset":34692948,"length":5031,"mode":420},"/node_modules/hypercore-crypto/package.json":{"offset":34697979,"length":1007,"mode":420},"/node_modules/pgh-runtime/index.js":{"offset":34698986,"length":11375,"mode":420},"/node_modules/pgh-runtime/node_modules/bare-events/index.js":{"offset":34710361,"length":8307,"mode":420},"/node_modules/pgh-runtime/node_modules/bare-events/lib/errors.js":{"offset":34718668,"length":671,"mode":420},"/node_modules/pgh-runtime/node_modules/bare-events/package.json":{"offset":34719339,"length":1504,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/lib/tree.js":{"offset":34720843,"length":14077,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/b4a/index.js":{"offset":34734920,"length":4054,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/b4a/package.json":{"offset":34738974,"length":1245,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-ansi-escapes/index.js":{"offset":34740219,"length":2255,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-ansi-escapes/package.json":{"offset":34742474,"length":1178,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-assert/index.js":{"offset":34743652,"length":2192,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-assert/package.json":{"offset":34745844,"length":835,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-events/index.js":{"offset":34746679,"length":8307,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-events/lib/errors.js":{"offset":34754986,"length":671,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-events/package.json":{"offset":34755657,"length":1504,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-fs/binding.js":{"offset":34757161,"length":33,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-fs/index.js":{"offset":34757194,"length":58907,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-fs/lib/constants.js":{"offset":34816101,"length":1494,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-fs/lib/errors.js":{"offset":34817595,"length":1163,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-fs/package.json":{"offset":34818758,"length":1654,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-fs/promises.js":{"offset":34820412,"length":2401,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-inspect/binding.js":{"offset":34822813,"length":33,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-inspect/index.js":{"offset":34822846,"length":23856,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-inspect/package.json":{"offset":34846702,"length":1041,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-os/binding.js":{"offset":34847743,"length":33,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-os/index.js":{"offset":34847776,"length":3224,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-os/lib/constants.js":{"offset":34851000,"length":143,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-os/lib/errors.js":{"offset":34851143,"length":453,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-os/package.json":{"offset":34851596,"length":1257,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-path/index.js":{"offset":34852853,"length":287,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-path/lib/constants.js":{"offset":34853140,"length":247,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-path/lib/posix.js":{"offset":34853387,"length":6005,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-path/lib/shared.js":{"offset":34859392,"length":1926,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-path/lib/win32.js":{"offset":34861318,"length":13591,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-path/package.json":{"offset":34874909,"length":1036,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-stream/index.js":{"offset":34875945,"length":10904,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-stream/package.json":{"offset":34886849,"length":1676,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-stream/web.js":{"offset":34888525,"length":13980,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-type/binding.js":{"offset":34902505,"length":33,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-type/index.js":{"offset":34902538,"length":4566,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-type/package.json":{"offset":34907104,"length":938,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-url/binding.js":{"offset":34908042,"length":33,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-url/index.js":{"offset":34908075,"length":9449,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-url/lib/errors.js":{"offset":34917524,"length":778,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-url/lib/url-search-params.js":{"offset":34918302,"length":4331,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/bare-url/package.json":{"offset":34922633,"length":1219,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/compact-encoding/endian.js":{"offset":34923852,"length":105,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/compact-encoding/index.js":{"offset":34923957,"length":26135,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/compact-encoding/lexint.js":{"offset":34950092,"length":2851,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/compact-encoding/package.json":{"offset":34952943,"length":866,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/compact-encoding/raw.js":{"offset":34953809,"length":3977,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/events-universal/bare.js":{"offset":34957786,"length":40,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/events-universal/package.json":{"offset":34957826,"length":908,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/fast-fifo/fixed-size.js":{"offset":34958734,"length":875,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/fast-fifo/index.js":{"offset":34959609,"length":972,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/fast-fifo/package.json":{"offset":34960581,"length":682,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/hypercore-crypto/index.js":{"offset":34961263,"length":5031,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/hypercore-crypto/package.json":{"offset":34966294,"length":1007,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/require-addon/lib/bare.js":{"offset":34967301,"length":45,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/require-addon/package.json":{"offset":34967346,"length":1449,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/sodium-native/binding.js":{"offset":34968795,"length":89,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/sodium-native/index.js":{"offset":34968884,"length":107894,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/sodium-native/package.json":{"offset":35076778,"length":1478,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/sodium-universal/index.js":{"offset":35078256,"length":42,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/sodium-universal/package.json":{"offset":35078298,"length":1217,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/streamx/index.js":{"offset":35079515,"length":34248,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/streamx/lib/errors.js":{"offset":35113763,"length":1096,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/streamx/package.json":{"offset":35114859,"length":1225,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/teex/index.js":{"offset":35116084,"length":1107,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/teex/package.json":{"offset":35117191,"length":608,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/text-decoder/index.js":{"offset":35117799,"length":1371,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/text-decoder/lib/pass-through-decoder.js":{"offset":35119170,"length":269,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/text-decoder/lib/utf8-decoder.js":{"offset":35119439,"length":4429,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/text-decoder/package.json":{"offset":35123868,"length":990,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/which-runtime/index.js":{"offset":35124858,"length":1469,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/node_modules/which-runtime/package.json":{"offset":35126327,"length":863,"mode":420},"/node_modules/pgh-runtime/node_modules/hyper-overlay/package.json":{"offset":35127190,"length":2132,"mode":420},"/node_modules/pgh-runtime/package.json":{"offset":35129322,"length":683,"mode":420},"/node_modules/pgh/lib/network-fetcher.js":{"offset":35130005,"length":20230,"mode":420},"/node_modules/pgh/lib/release-registry.js":{"offset":35150235,"length":12849,"mode":420},"/node_modules/pgh/lib/resolve-release.js":{"offset":35163084,"length":12622,"mode":420},"/node_modules/pgh/node_modules/@hyperswarm/secret-stream/index.js":{"offset":35175706,"length":16722,"mode":420},"/node_modules/pgh/node_modules/@hyperswarm/secret-stream/lib/bridge.js":{"offset":35192428,"length":1273,"mode":420},"/node_modules/pgh/node_modules/@hyperswarm/secret-stream/lib/handshake.js":{"offset":35193701,"length":1950,"mode":420},"/node_modules/pgh/node_modules/@hyperswarm/secret-stream/package.json":{"offset":35195651,"length":1132,"mode":420},"/node_modules/pgh/node_modules/adaptive-timeout/index.js":{"offset":35196783,"length":2424,"mode":420},"/node_modules/pgh/node_modules/adaptive-timeout/package.json":{"offset":35199207,"length":972,"mode":420},"/node_modules/pgh/node_modules/autobase/encoding/legacy.js":{"offset":35200179,"length":8969,"mode":420},"/node_modules/pgh/node_modules/autobase/encoding/spec/autobase/index.js":{"offset":35209148,"length":18905,"mode":420},"/node_modules/pgh/node_modules/autobase/index.js":{"offset":35228053,"length":59358,"mode":420},"/node_modules/pgh/node_modules/autobase/lib/active-writers.js":{"offset":35287411,"length":736,"mode":420},"/node_modules/pgh/node_modules/autobase/lib/append-batch.js":{"offset":35288147,"length":1426,"mode":420},"/node_modules/pgh/node_modules/autobase/lib/apply-calls.js":{"offset":35289573,"length":2275,"mode":420},"/node_modules/pgh/node_modules/autobase/lib/apply-state.js":{"offset":35291848,"length":46121,"mode":420},"/node_modules/pgh/node_modules/autobase/lib/boot.js":{"offset":35337969,"length":4599,"mode":420},"/node_modules/pgh/node_modules/autobase/lib/caps.js":{"offset":35342568,"length":505,"mode":420},"/node_modules/pgh/node_modules/autobase/lib/clock.js":{"offset":35343073,"length":749,"mode":420},"/node_modules/pgh/node_modules/autobase/lib/consensus.js":{"offset":35343822,"length":11754,"mode":420},"/node_modules/pgh/node_modules/autobase/lib/encryption.js":{"offset":35355576,"length":9444,"mode":420},"/node_modules/pgh/node_modules/autobase/lib/fast-forward.js":{"offset":35365020,"length":5714,"mode":420},"/node_modules/pgh/node_modules/autobase/lib/fork.js":{"offset":35370734,"length":4148,"mode":420},"/node_modules/pgh/node_modules/autobase/lib/linearizer.js":{"offset":35374882,"length":9696,"mode":420},"/node_modules/pgh/node_modules/autobase/lib/local-state.js":{"offset":35384578,"length":2013,"mode":420},"/node_modules/pgh/node_modules/autobase/lib/messages.js":{"offset":35386591,"length":827,"mode":420},"/node_modules/pgh/node_modules/autobase/lib/node-buffer.js":{"offset":35387418,"length":1563,"mode":420},"/node_modules/pgh/node_modules/autobase/lib/store.js":{"offset":35388981,"length":14341,"mode":420},"/node_modules/pgh/node_modules/autobase/lib/system.js":{"offset":35403322,"length":20176,"mode":420},"/node_modules/pgh/node_modules/autobase/lib/timer.js":{"offset":35423498,"length":2937,"mode":420},"/node_modules/pgh/node_modules/autobase/lib/topolist.js":{"offset":35426435,"length":5108,"mode":420},"/node_modules/pgh/node_modules/autobase/lib/updates.js":{"offset":35431543,"length":1109,"mode":420},"/node_modules/pgh/node_modules/autobase/lib/values.js":{"offset":35432652,"length":1539,"mode":420},"/node_modules/pgh/node_modules/autobase/lib/wakeup.js":{"offset":35434191,"length":4034,"mode":420},"/node_modules/pgh/node_modules/autobase/lib/writer.js":{"offset":35438225,"length":8901,"mode":420},"/node_modules/pgh/node_modules/autobase/package.json":{"offset":35447126,"length":2327,"mode":420},"/node_modules/pgh/node_modules/b4a/index.js":{"offset":35449453,"length":4054,"mode":420},"/node_modules/pgh/node_modules/b4a/package.json":{"offset":35453507,"length":1245,"mode":420},"/node_modules/pgh/node_modules/bare-abort/binding.js":{"offset":35454752,"length":33,"mode":420},"/node_modules/pgh/node_modules/bare-abort/index.js":{"offset":35454785,"length":69,"mode":420},"/node_modules/pgh/node_modules/bare-abort/package.json":{"offset":35454854,"length":886,"mode":420},"/node_modules/pgh/node_modules/bare-ansi-escapes/index.js":{"offset":35455740,"length":2255,"mode":420},"/node_modules/pgh/node_modules/bare-ansi-escapes/package.json":{"offset":35457995,"length":1178,"mode":420},"/node_modules/pgh/node_modules/bare-assert/index.js":{"offset":35459173,"length":2192,"mode":420},"/node_modules/pgh/node_modules/bare-assert/package.json":{"offset":35461365,"length":835,"mode":420},"/node_modules/pgh/node_modules/bare-env/index.js":{"offset":35462200,"length":1023,"mode":420},"/node_modules/pgh/node_modules/bare-env/package.json":{"offset":35463223,"length":649,"mode":420},"/node_modules/pgh/node_modules/bare-events/index.js":{"offset":35463872,"length":8307,"mode":420},"/node_modules/pgh/node_modules/bare-events/lib/errors.js":{"offset":35472179,"length":671,"mode":420},"/node_modules/pgh/node_modules/bare-events/package.json":{"offset":35472850,"length":1504,"mode":420},"/node_modules/pgh/node_modules/bare-fs/binding.js":{"offset":35474354,"length":33,"mode":420},"/node_modules/pgh/node_modules/bare-fs/index.js":{"offset":35474387,"length":58907,"mode":420},"/node_modules/pgh/node_modules/bare-fs/lib/constants.js":{"offset":35533294,"length":1494,"mode":420},"/node_modules/pgh/node_modules/bare-fs/lib/errors.js":{"offset":35534788,"length":1163,"mode":420},"/node_modules/pgh/node_modules/bare-fs/package.json":{"offset":35535951,"length":1654,"mode":420},"/node_modules/pgh/node_modules/bare-fs/promises.js":{"offset":35537605,"length":2401,"mode":420},"/node_modules/pgh/node_modules/bare-hrtime/binding.js":{"offset":35540006,"length":33,"mode":420},"/node_modules/pgh/node_modules/bare-hrtime/index.js":{"offset":35540039,"length":319,"mode":420},"/node_modules/pgh/node_modules/bare-hrtime/package.json":{"offset":35540358,"length":905,"mode":420},"/node_modules/pgh/node_modules/bare-inspect/binding.js":{"offset":35541263,"length":33,"mode":420},"/node_modules/pgh/node_modules/bare-inspect/index.js":{"offset":35541296,"length":23856,"mode":420},"/node_modules/pgh/node_modules/bare-inspect/package.json":{"offset":35565152,"length":1041,"mode":420},"/node_modules/pgh/node_modules/bare-os/binding.js":{"offset":35566193,"length":33,"mode":420},"/node_modules/pgh/node_modules/bare-os/index.js":{"offset":35566226,"length":3224,"mode":420},"/node_modules/pgh/node_modules/bare-os/lib/constants.js":{"offset":35569450,"length":143,"mode":420},"/node_modules/pgh/node_modules/bare-os/lib/errors.js":{"offset":35569593,"length":453,"mode":420},"/node_modules/pgh/node_modules/bare-os/package.json":{"offset":35570046,"length":1257,"mode":420},"/node_modules/pgh/node_modules/bare-path/index.js":{"offset":35571303,"length":287,"mode":420},"/node_modules/pgh/node_modules/bare-path/lib/constants.js":{"offset":35571590,"length":247,"mode":420},"/node_modules/pgh/node_modules/bare-path/lib/posix.js":{"offset":35571837,"length":6005,"mode":420},"/node_modules/pgh/node_modules/bare-path/lib/shared.js":{"offset":35577842,"length":1926,"mode":420},"/node_modules/pgh/node_modules/bare-path/lib/win32.js":{"offset":35579768,"length":13591,"mode":420},"/node_modules/pgh/node_modules/bare-path/package.json":{"offset":35593359,"length":1036,"mode":420},"/node_modules/pgh/node_modules/bare-process/index.js":{"offset":35594395,"length":2689,"mode":420},"/node_modules/pgh/node_modules/bare-process/package.json":{"offset":35597084,"length":1255,"mode":420},"/node_modules/pgh/node_modules/bare-signals/binding.js":{"offset":35598339,"length":33,"mode":420},"/node_modules/pgh/node_modules/bare-signals/index.js":{"offset":35598372,"length":1517,"mode":420},"/node_modules/pgh/node_modules/bare-signals/lib/emitter.js":{"offset":35599889,"length":1278,"mode":420},"/node_modules/pgh/node_modules/bare-signals/lib/errors.js":{"offset":35601167,"length":479,"mode":420},"/node_modules/pgh/node_modules/bare-signals/package.json":{"offset":35601646,"length":1112,"mode":420},"/node_modules/pgh/node_modules/bare-stdio/binding.js":{"offset":35602758,"length":33,"mode":420},"/node_modules/pgh/node_modules/bare-stdio/index.js":{"offset":35602791,"length":1525,"mode":420},"/node_modules/pgh/node_modules/bare-stdio/node_modules/bare-pipe/binding.js":{"offset":35604316,"length":33,"mode":420},"/node_modules/pgh/node_modules/bare-stdio/node_modules/bare-pipe/index.js":{"offset":35604349,"length":14060,"mode":420},"/node_modules/pgh/node_modules/bare-stdio/node_modules/bare-pipe/lib/constants.js":{"offset":35618409,"length":352,"mode":420},"/node_modules/pgh/node_modules/bare-stdio/node_modules/bare-pipe/lib/errors.js":{"offset":35618761,"length":699,"mode":420},"/node_modules/pgh/node_modules/bare-stdio/node_modules/bare-pipe/package.json":{"offset":35619460,"length":1396,"mode":420},"/node_modules/pgh/node_modules/bare-stdio/package.json":{"offset":35620856,"length":1319,"mode":420},"/node_modules/pgh/node_modules/bare-stream/index.js":{"offset":35622175,"length":10913,"mode":420},"/node_modules/pgh/node_modules/bare-stream/package.json":{"offset":35633088,"length":1655,"mode":420},"/node_modules/pgh/node_modules/bare-stream/web.js":{"offset":35634743,"length":13980,"mode":420},"/node_modules/pgh/node_modules/bare-tty/binding.js":{"offset":35648723,"length":33,"mode":420},"/node_modules/pgh/node_modules/bare-tty/index.js":{"offset":35648756,"length":4469,"mode":420},"/node_modules/pgh/node_modules/bare-tty/lib/constants.js":{"offset":35653225,"length":442,"mode":420},"/node_modules/pgh/node_modules/bare-tty/package.json":{"offset":35653667,"length":1097,"mode":420},"/node_modules/pgh/node_modules/bare-type/binding.js":{"offset":35654764,"length":33,"mode":420},"/node_modules/pgh/node_modules/bare-type/index.js":{"offset":35654797,"length":4566,"mode":420},"/node_modules/pgh/node_modules/bare-type/package.json":{"offset":35659363,"length":938,"mode":420},"/node_modules/pgh/node_modules/bare-url/binding.js":{"offset":35660301,"length":33,"mode":420},"/node_modules/pgh/node_modules/bare-url/index.js":{"offset":35660334,"length":9449,"mode":420},"/node_modules/pgh/node_modules/bare-url/lib/errors.js":{"offset":35669783,"length":778,"mode":420},"/node_modules/pgh/node_modules/bare-url/lib/url-search-params.js":{"offset":35670561,"length":4331,"mode":420},"/node_modules/pgh/node_modules/bare-url/package.json":{"offset":35674892,"length":1219,"mode":420},"/node_modules/pgh/node_modules/big-sparse-array/index.js":{"offset":35676111,"length":2471,"mode":420},"/node_modules/pgh/node_modules/big-sparse-array/package.json":{"offset":35678582,"length":636,"mode":420},"/node_modules/pgh/node_modules/bits-to-bytes/index.js":{"offset":35679218,"length":3083,"mode":420},"/node_modules/pgh/node_modules/bits-to-bytes/package.json":{"offset":35682301,"length":708,"mode":420},"/node_modules/pgh/node_modules/blind-relay/index.js":{"offset":35683009,"length":13411,"mode":420},"/node_modules/pgh/node_modules/blind-relay/lib/errors.js":{"offset":35696420,"length":1036,"mode":420},"/node_modules/pgh/node_modules/blind-relay/package.json":{"offset":35697456,"length":1231,"mode":420},"/node_modules/pgh/node_modules/bogon/index.js":{"offset":35698687,"length":4004,"mode":420},"/node_modules/pgh/node_modules/bogon/package.json":{"offset":35702691,"length":656,"mode":420},"/node_modules/pgh/node_modules/codecs/index.js":{"offset":35703347,"length":2416,"mode":420},"/node_modules/pgh/node_modules/codecs/package.json":{"offset":35705763,"length":655,"mode":420},"/node_modules/pgh/node_modules/compact-encoding-bitfield/index.js":{"offset":35706418,"length":1967,"mode":420},"/node_modules/pgh/node_modules/compact-encoding-bitfield/package.json":{"offset":35708385,"length":1109,"mode":420},"/node_modules/pgh/node_modules/compact-encoding/endian.js":{"offset":35709494,"length":105,"mode":420},"/node_modules/pgh/node_modules/compact-encoding/index.js":{"offset":35709599,"length":26135,"mode":420},"/node_modules/pgh/node_modules/compact-encoding/lexint.js":{"offset":35735734,"length":2851,"mode":420},"/node_modules/pgh/node_modules/compact-encoding/package.json":{"offset":35738585,"length":866,"mode":420},"/node_modules/pgh/node_modules/compact-encoding/raw.js":{"offset":35739451,"length":3977,"mode":420},"/node_modules/pgh/node_modules/core-coupler/index.js":{"offset":35743428,"length":2243,"mode":420},"/node_modules/pgh/node_modules/core-coupler/package.json":{"offset":35745671,"length":599,"mode":420},"/node_modules/pgh/node_modules/corestore/index.js":{"offset":35746270,"length":19823,"mode":420},"/node_modules/pgh/node_modules/corestore/lib/audit.js":{"offset":35766093,"length":475,"mode":420},"/node_modules/pgh/node_modules/corestore/lib/notify.js":{"offset":35766568,"length":630,"mode":420},"/node_modules/pgh/node_modules/corestore/package.json":{"offset":35767198,"length":1350,"mode":420},"/node_modules/pgh/node_modules/debounceify/index.js":{"offset":35768548,"length":585,"mode":420},"/node_modules/pgh/node_modules/debounceify/package.json":{"offset":35769133,"length":567,"mode":420},"/node_modules/pgh/node_modules/device-file/index.js":{"offset":35769700,"length":6394,"mode":420},"/node_modules/pgh/node_modules/device-file/package.json":{"offset":35776094,"length":1190,"mode":420},"/node_modules/pgh/node_modules/dht-rpc/index.js":{"offset":35777284,"length":29079,"mode":420},"/node_modules/pgh/node_modules/dht-rpc/lib/commands.js":{"offset":35806363,"length":107,"mode":420},"/node_modules/pgh/node_modules/dht-rpc/lib/errors.js":{"offset":35806470,"length":719,"mode":420},"/node_modules/pgh/node_modules/dht-rpc/lib/health.js":{"offset":35807189,"length":2998,"mode":420},"/node_modules/pgh/node_modules/dht-rpc/lib/io.js":{"offset":35810187,"length":16605,"mode":420},"/node_modules/pgh/node_modules/dht-rpc/lib/peer.js":{"offset":35826792,"length":583,"mode":420},"/node_modules/pgh/node_modules/dht-rpc/lib/query.js":{"offset":35827375,"length":9899,"mode":420},"/node_modules/pgh/node_modules/dht-rpc/lib/session.js":{"offset":35837274,"length":1103,"mode":420},"/node_modules/pgh/node_modules/dht-rpc/package.json":{"offset":35838377,"length":1396,"mode":420},"/node_modules/pgh/node_modules/encryption-encoding/index.js":{"offset":35839773,"length":378,"mode":420},"/node_modules/pgh/node_modules/encryption-encoding/package.json":{"offset":35840151,"length":1234,"mode":420},"/node_modules/pgh/node_modules/encryption-encoding/spec/hyperschema/index.js":{"offset":35841385,"length":1749,"mode":420},"/node_modules/pgh/node_modules/events-universal/bare.js":{"offset":35843134,"length":40,"mode":420},"/node_modules/pgh/node_modules/events-universal/package.json":{"offset":35843174,"length":908,"mode":420},"/node_modules/pgh/node_modules/fast-fifo/fixed-size.js":{"offset":35844082,"length":875,"mode":420},"/node_modules/pgh/node_modules/fast-fifo/index.js":{"offset":35844957,"length":972,"mode":420},"/node_modules/pgh/node_modules/fast-fifo/package.json":{"offset":35845929,"length":682,"mode":420},"/node_modules/pgh/node_modules/fd-lock/index.js":{"offset":35846611,"length":1661,"mode":420},"/node_modules/pgh/node_modules/fd-lock/package.json":{"offset":35848272,"length":1099,"mode":420},"/node_modules/pgh/node_modules/flat-tree/index.js":{"offset":35849371,"length":8164,"mode":420},"/node_modules/pgh/node_modules/flat-tree/package.json":{"offset":35857535,"length":631,"mode":420},"/node_modules/pgh/node_modules/fs-native-extensions/binding.js":{"offset":35858166,"length":90,"mode":420},"/node_modules/pgh/node_modules/fs-native-extensions/index.js":{"offset":35858256,"length":7239,"mode":420},"/node_modules/pgh/node_modules/fs-native-extensions/package.json":{"offset":35865495,"length":1790,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/lib/chunk-scheduler.js":{"offset":35867285,"length":18133,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/lib/chunker.js":{"offset":35885418,"length":14180,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/lib/file-index.js":{"offset":35899598,"length":20487,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/lib/messages.js":{"offset":35920085,"length":15242,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/lib/protocol.js":{"offset":35935327,"length":50117,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/lib/transfer.js":{"offset":35985444,"length":33515,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/lib/tree.js":{"offset":36018959,"length":14077,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/b4a/index.js":{"offset":36033036,"length":4054,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/b4a/package.json":{"offset":36037090,"length":1245,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-ansi-escapes/index.js":{"offset":36038335,"length":2255,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-ansi-escapes/package.json":{"offset":36040590,"length":1178,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-assert/index.js":{"offset":36041768,"length":2192,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-assert/package.json":{"offset":36043960,"length":835,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-events/index.js":{"offset":36044795,"length":8307,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-events/lib/errors.js":{"offset":36053102,"length":671,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-events/package.json":{"offset":36053773,"length":1504,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-fs/binding.js":{"offset":36055277,"length":33,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-fs/index.js":{"offset":36055310,"length":58907,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-fs/lib/constants.js":{"offset":36114217,"length":1494,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-fs/lib/errors.js":{"offset":36115711,"length":1163,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-fs/package.json":{"offset":36116874,"length":1654,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-fs/promises.js":{"offset":36118528,"length":2401,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-inspect/binding.js":{"offset":36120929,"length":33,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-inspect/index.js":{"offset":36120962,"length":23856,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-inspect/package.json":{"offset":36144818,"length":1041,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-os/binding.js":{"offset":36145859,"length":33,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-os/index.js":{"offset":36145892,"length":3224,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-os/lib/constants.js":{"offset":36149116,"length":143,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-os/lib/errors.js":{"offset":36149259,"length":453,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-os/package.json":{"offset":36149712,"length":1257,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-path/index.js":{"offset":36150969,"length":287,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-path/lib/constants.js":{"offset":36151256,"length":247,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-path/lib/posix.js":{"offset":36151503,"length":6005,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-path/lib/shared.js":{"offset":36157508,"length":1926,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-path/lib/win32.js":{"offset":36159434,"length":13591,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-path/package.json":{"offset":36173025,"length":1036,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-stream/index.js":{"offset":36174061,"length":10904,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-stream/package.json":{"offset":36184965,"length":1676,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-stream/web.js":{"offset":36186641,"length":13980,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-type/binding.js":{"offset":36200621,"length":33,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-type/index.js":{"offset":36200654,"length":4566,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-type/package.json":{"offset":36205220,"length":938,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-url/binding.js":{"offset":36206158,"length":33,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-url/index.js":{"offset":36206191,"length":9449,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-url/lib/errors.js":{"offset":36215640,"length":778,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-url/lib/url-search-params.js":{"offset":36216418,"length":4331,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/bare-url/package.json":{"offset":36220749,"length":1219,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/codecs/index.js":{"offset":36221968,"length":2416,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/codecs/package.json":{"offset":36224384,"length":655,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/compact-encoding/endian.js":{"offset":36225039,"length":105,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/compact-encoding/index.js":{"offset":36225144,"length":26135,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/compact-encoding/lexint.js":{"offset":36251279,"length":2851,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/compact-encoding/package.json":{"offset":36254130,"length":866,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/compact-encoding/raw.js":{"offset":36254996,"length":3977,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/debounceify/index.js":{"offset":36258973,"length":585,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/debounceify/package.json":{"offset":36259558,"length":567,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/events-universal/bare.js":{"offset":36260125,"length":40,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/events-universal/package.json":{"offset":36260165,"length":908,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/fast-fifo/fixed-size.js":{"offset":36261073,"length":875,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/fast-fifo/index.js":{"offset":36261948,"length":972,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/fast-fifo/package.json":{"offset":36262920,"length":682,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/hyperbee/index.js":{"offset":36263602,"length":46445,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/hyperbee/iterators/diff.js":{"offset":36310047,"length":5358,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/hyperbee/iterators/history.js":{"offset":36315405,"length":1631,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/hyperbee/iterators/local.js":{"offset":36317036,"length":1170,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/hyperbee/iterators/range.js":{"offset":36318206,"length":5869,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/hyperbee/lib/extension.js":{"offset":36324075,"length":3488,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/hyperbee/lib/messages.js":{"offset":36327563,"length":28162,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/hyperbee/package.json":{"offset":36355725,"length":1585,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/hypercore-crypto/index.js":{"offset":36357310,"length":5031,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/hypercore-crypto/package.json":{"offset":36362341,"length":1007,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/hypercore-errors/index.js":{"offset":36363348,"length":4896,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/hypercore-errors/package.json":{"offset":36368244,"length":688,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/hypercore-id-encoding/index.js":{"offset":36368932,"length":923,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/hypercore-id-encoding/package.json":{"offset":36369855,"length":799,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/mutexify/index.js":{"offset":36370654,"length":536,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/mutexify/package.json":{"offset":36371190,"length":679,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/mutexify/promise.js":{"offset":36371869,"length":324,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/protocol-buffers-encodings/index.js":{"offset":36372193,"length":6489,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/protocol-buffers-encodings/package.json":{"offset":36378682,"length":719,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/queue-tick/package.json":{"offset":36379401,"length":669,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/queue-tick/process-next-tick.js":{"offset":36380070,"length":160,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/queue-tick/queue-microtask.js":{"offset":36380230,"length":108,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/rache/index.js":{"offset":36380338,"length":2463,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/rache/package.json":{"offset":36382801,"length":602,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/ready-resource/index.js":{"offset":36383403,"length":1091,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/ready-resource/package.json":{"offset":36384494,"length":812,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/require-addon/lib/bare.js":{"offset":36385306,"length":45,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/require-addon/package.json":{"offset":36385351,"length":1449,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/resolve-reject-promise/index.js":{"offset":36386800,"length":443,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/resolve-reject-promise/package.json":{"offset":36387243,"length":581,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/safety-catch/index.js":{"offset":36387824,"length":543,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/safety-catch/package.json":{"offset":36388367,"length":547,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/signed-varint/index.js":{"offset":36388914,"length":435,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/signed-varint/package.json":{"offset":36389349,"length":523,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/sodium-native/binding.js":{"offset":36389872,"length":89,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/sodium-native/index.js":{"offset":36389961,"length":107894,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/sodium-native/package.json":{"offset":36497855,"length":1478,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/sodium-universal/index.js":{"offset":36499333,"length":42,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/sodium-universal/package.json":{"offset":36499375,"length":1217,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/streamx/index.js":{"offset":36500592,"length":34248,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/streamx/lib/errors.js":{"offset":36534840,"length":1096,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/streamx/package.json":{"offset":36535936,"length":1225,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/teex/index.js":{"offset":36537161,"length":1107,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/teex/package.json":{"offset":36538268,"length":608,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/text-decoder/index.js":{"offset":36538876,"length":1371,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/text-decoder/lib/pass-through-decoder.js":{"offset":36540247,"length":269,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/text-decoder/lib/utf8-decoder.js":{"offset":36540516,"length":4429,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/text-decoder/package.json":{"offset":36544945,"length":990,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/unslab/index.js":{"offset":36545935,"length":913,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/unslab/package.json":{"offset":36546848,"length":613,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/varint/decode.js":{"offset":36547461,"length":508,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/varint/encode.js":{"offset":36547969,"length":452,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/varint/index.js":{"offset":36548421,"length":134,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/varint/length.js":{"offset":36548555,"length":471,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/varint/package.json":{"offset":36549026,"length":511,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/which-runtime/index.js":{"offset":36549537,"length":1469,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/which-runtime/package.json":{"offset":36551006,"length":863,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/z32/index.js":{"offset":36551869,"length":2654,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/node_modules/z32/package.json":{"offset":36554523,"length":701,"mode":420},"/node_modules/pgh/node_modules/hyper-overlay/package.json":{"offset":36555224,"length":2132,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/index.js":{"offset":36557356,"length":424,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/lib/client.js":{"offset":36557780,"length":14860,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/lib/frame.js":{"offset":36572640,"length":1862,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/lib/service.js":{"offset":36574502,"length":11770,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/lib/transports/http.js":{"offset":36586272,"length":7998,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/lib/transports/swarm-rpc.js":{"offset":36594270,"length":4427,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/lib/transports/swarm.js":{"offset":36598697,"length":8308,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/lib/transports/uds.js":{"offset":36607005,"length":8779,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/lib/uds-backend.js":{"offset":36615784,"length":1568,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/index.js":{"offset":36617352,"length":16722,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/lib/bridge.js":{"offset":36634074,"length":1273,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/lib/handshake.js":{"offset":36635347,"length":1950,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/@hyperswarm/secret-stream/package.json":{"offset":36637297,"length":1132,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/adaptive-timeout/index.js":{"offset":36638429,"length":2424,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/adaptive-timeout/package.json":{"offset":36640853,"length":972,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/index.js":{"offset":36641825,"length":4054,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/b4a/package.json":{"offset":36645879,"length":1245,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-abort/binding.js":{"offset":36647124,"length":33,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-abort/index.js":{"offset":36647157,"length":69,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-abort/package.json":{"offset":36647226,"length":886,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-ansi-escapes/index.js":{"offset":36648112,"length":2255,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-ansi-escapes/package.json":{"offset":36650367,"length":1178,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-assert/index.js":{"offset":36651545,"length":2192,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-assert/package.json":{"offset":36653737,"length":835,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-dns/binding.js":{"offset":36654572,"length":33,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-dns/index.js":{"offset":36654605,"length":1345,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-dns/package.json":{"offset":36655950,"length":968,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-env/index.js":{"offset":36656918,"length":1023,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-env/package.json":{"offset":36657941,"length":649,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-events/index.js":{"offset":36658590,"length":8033,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-events/lib/errors.js":{"offset":36666623,"length":671,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-events/package.json":{"offset":36667294,"length":1399,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-fs/binding.js":{"offset":36668693,"length":33,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-fs/index.js":{"offset":36668726,"length":58907,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-fs/lib/constants.js":{"offset":36727633,"length":1494,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-fs/lib/errors.js":{"offset":36729127,"length":1163,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-fs/package.json":{"offset":36730290,"length":1654,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-fs/promises.js":{"offset":36731944,"length":2401,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-hrtime/binding.js":{"offset":36734345,"length":33,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-hrtime/index.js":{"offset":36734378,"length":319,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-hrtime/package.json":{"offset":36734697,"length":905,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http-parser/index.js":{"offset":36735602,"length":17480,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http-parser/lib/errors.js":{"offset":36753082,"length":845,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http-parser/package.json":{"offset":36753927,"length":793,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http1/index.js":{"offset":36754720,"length":2188,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http1/lib/agent.js":{"offset":36756908,"length":4498,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http1/lib/client-connection.js":{"offset":36761406,"length":3663,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http1/lib/client-request.js":{"offset":36765069,"length":3286,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http1/lib/constants.js":{"offset":36768355,"length":2016,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http1/lib/errors.js":{"offset":36770371,"length":634,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http1/lib/incoming-message.js":{"offset":36771005,"length":1568,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http1/lib/outgoing-message.js":{"offset":36772573,"length":1291,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http1/lib/server-connection.js":{"offset":36773864,"length":4041,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http1/lib/server-response.js":{"offset":36777905,"length":3183,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http1/lib/server.js":{"offset":36781088,"length":977,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-http1/package.json":{"offset":36782065,"length":1510,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-inspect/binding.js":{"offset":36783575,"length":33,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-inspect/index.js":{"offset":36783608,"length":23856,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-inspect/package.json":{"offset":36807464,"length":1041,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-net/index.js":{"offset":36808505,"length":6868,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-dns/binding.js":{"offset":36815373,"length":33,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-dns/index.js":{"offset":36815406,"length":860,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-dns/package.json":{"offset":36816266,"length":772,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/binding.js":{"offset":36817038,"length":33,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/index.js":{"offset":36817071,"length":10947,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/lib/constants.js":{"offset":36828018,"length":188,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/lib/errors.js":{"offset":36828206,"length":668,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-pipe/package.json":{"offset":36828874,"length":962,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/binding.js":{"offset":36829836,"length":33,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/index.js":{"offset":36829869,"length":12710,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/lib/constants.js":{"offset":36842579,"length":167,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/lib/errors.js":{"offset":36842746,"length":799,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/lib/ip.js":{"offset":36843545,"length":2179,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-net/node_modules/bare-tcp/package.json":{"offset":36845724,"length":959,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-net/package.json":{"offset":36846683,"length":793,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-os/binding.js":{"offset":36847476,"length":33,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-os/index.js":{"offset":36847509,"length":3224,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-os/lib/constants.js":{"offset":36850733,"length":143,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-os/lib/errors.js":{"offset":36850876,"length":453,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-os/package.json":{"offset":36851329,"length":1257,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-path/index.js":{"offset":36852586,"length":306,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-path/lib/constants.js":{"offset":36852892,"length":247,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-path/lib/posix.js":{"offset":36853139,"length":5991,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-path/lib/shared.js":{"offset":36859130,"length":1888,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-path/lib/win32.js":{"offset":36861018,"length":13427,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-path/package.json":{"offset":36874445,"length":796,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-pipe/binding.js":{"offset":36875241,"length":33,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-pipe/index.js":{"offset":36875274,"length":10769,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-pipe/lib/constants.js":{"offset":36886043,"length":208,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-pipe/lib/errors.js":{"offset":36886251,"length":599,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-pipe/package.json":{"offset":36886850,"length":1256,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-process/index.js":{"offset":36888106,"length":2689,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-process/package.json":{"offset":36890795,"length":1255,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-signals/binding.js":{"offset":36892050,"length":33,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-signals/index.js":{"offset":36892083,"length":1517,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-signals/lib/emitter.js":{"offset":36893600,"length":1278,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-signals/lib/errors.js":{"offset":36894878,"length":479,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-signals/package.json":{"offset":36895357,"length":1112,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-stdio/binding.js":{"offset":36896469,"length":33,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-stdio/index.js":{"offset":36896502,"length":1525,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-stdio/package.json":{"offset":36898027,"length":1319,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-stream/index.js":{"offset":36899346,"length":10913,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-stream/package.json":{"offset":36910259,"length":1655,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-stream/web.js":{"offset":36911914,"length":13980,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-tcp/binding.js":{"offset":36925894,"length":33,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-tcp/index.js":{"offset":36925927,"length":15054,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-tcp/lib/constants.js":{"offset":36940981,"length":167,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-tcp/lib/errors.js":{"offset":36941148,"length":711,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-tcp/lib/ip.js":{"offset":36941859,"length":2204,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-tcp/package.json":{"offset":36944063,"length":1243,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-tty/binding.js":{"offset":36945306,"length":33,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-tty/index.js":{"offset":36945339,"length":4469,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-tty/lib/constants.js":{"offset":36949808,"length":442,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-tty/package.json":{"offset":36950250,"length":1097,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-type/binding.js":{"offset":36951347,"length":33,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-type/index.js":{"offset":36951380,"length":4566,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-type/package.json":{"offset":36955946,"length":938,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-url/binding.js":{"offset":36956884,"length":33,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-url/index.js":{"offset":36956917,"length":9308,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-url/lib/errors.js":{"offset":36966225,"length":778,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-url/lib/url-search-params.js":{"offset":36967003,"length":4331,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bare-url/package.json":{"offset":36971334,"length":1219,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bits-to-bytes/index.js":{"offset":36972553,"length":3083,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bits-to-bytes/package.json":{"offset":36975636,"length":708,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/blind-relay/index.js":{"offset":36976344,"length":13256,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/blind-relay/lib/errors.js":{"offset":36989600,"length":1036,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/endian.js":{"offset":36990636,"length":105,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/index.js":{"offset":36990741,"length":24454,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/lexint.js":{"offset":37015195,"length":2851,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/package.json":{"offset":37018046,"length":786,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/blind-relay/node_modules/compact-encoding/raw.js":{"offset":37018832,"length":4093,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/blind-relay/package.json":{"offset":37022925,"length":1232,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bogon/index.js":{"offset":37024157,"length":4052,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/endian.js":{"offset":37028209,"length":105,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/index.js":{"offset":37028314,"length":24454,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/lexint.js":{"offset":37052768,"length":2851,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/package.json":{"offset":37055619,"length":786,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bogon/node_modules/compact-encoding/raw.js":{"offset":37056405,"length":4093,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/bogon/package.json":{"offset":37060498,"length":657,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/index.js":{"offset":37061155,"length":1963,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/endian.js":{"offset":37063118,"length":105,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/index.js":{"offset":37063223,"length":24454,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/lexint.js":{"offset":37087677,"length":2851,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/package.json":{"offset":37090528,"length":786,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/node_modules/compact-encoding/raw.js":{"offset":37091314,"length":4093,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding-bitfield/package.json":{"offset":37095407,"length":827,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding-net/index.js":{"offset":37096234,"length":4109,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/endian.js":{"offset":37100343,"length":105,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/index.js":{"offset":37100448,"length":24454,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/lexint.js":{"offset":37124902,"length":2851,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/package.json":{"offset":37127753,"length":786,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding-net/node_modules/compact-encoding/raw.js":{"offset":37128539,"length":4093,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding-net/package.json":{"offset":37132632,"length":734,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding/endian.js":{"offset":37133366,"length":105,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding/index.js":{"offset":37133471,"length":26135,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding/lexint.js":{"offset":37159606,"length":2851,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding/package.json":{"offset":37162457,"length":866,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/compact-encoding/raw.js":{"offset":37163323,"length":3977,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/dht-rpc/index.js":{"offset":37167300,"length":29079,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/dht-rpc/lib/commands.js":{"offset":37196379,"length":107,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/dht-rpc/lib/errors.js":{"offset":37196486,"length":719,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/dht-rpc/lib/health.js":{"offset":37197205,"length":2998,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/dht-rpc/lib/io.js":{"offset":37200203,"length":16605,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/dht-rpc/lib/peer.js":{"offset":37216808,"length":631,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/dht-rpc/lib/query.js":{"offset":37217439,"length":9899,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/dht-rpc/lib/session.js":{"offset":37227338,"length":1103,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/endian.js":{"offset":37228441,"length":105,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/index.js":{"offset":37228546,"length":24454,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/lexint.js":{"offset":37253000,"length":2851,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/package.json":{"offset":37255851,"length":786,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/dht-rpc/node_modules/compact-encoding/raw.js":{"offset":37256637,"length":4093,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/dht-rpc/package.json":{"offset":37260730,"length":1397,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/events-universal/bare.js":{"offset":37262127,"length":40,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/events-universal/package.json":{"offset":37262167,"length":908,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/fast-fifo/fixed-size.js":{"offset":37263075,"length":875,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/fast-fifo/index.js":{"offset":37263950,"length":972,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/fast-fifo/package.json":{"offset":37264922,"length":682,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hypercore-crypto/index.js":{"offset":37265604,"length":5040,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/endian.js":{"offset":37270644,"length":105,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/index.js":{"offset":37270749,"length":24454,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/lexint.js":{"offset":37295203,"length":2851,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/package.json":{"offset":37298054,"length":786,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hypercore-crypto/node_modules/compact-encoding/raw.js":{"offset":37298840,"length":4093,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hypercore-crypto/package.json":{"offset":37302933,"length":771,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hypercore-id-encoding/index.js":{"offset":37303704,"length":923,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hypercore-id-encoding/package.json":{"offset":37304627,"length":799,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht-address/index.js":{"offset":37305426,"length":357,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/endian.js":{"offset":37305783,"length":105,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/index.js":{"offset":37305888,"length":24454,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/lexint.js":{"offset":37330342,"length":2851,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/package.json":{"offset":37333193,"length":786,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht-address/node_modules/compact-encoding/raw.js":{"offset":37333979,"length":4093,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht-address/package.json":{"offset":37338072,"length":1047,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht-address/spec/hyperschema/index.js":{"offset":37339119,"length":2106,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/index.js":{"offset":37341225,"length":16611,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/announcer.js":{"offset":37357836,"length":7533,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/connect.js":{"offset":37365369,"length":24788,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/connection-pool.js":{"offset":37390157,"length":3050,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/constants.js":{"offset":37393207,"length":1276,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/crypto.js":{"offset":37394483,"length":632,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/encode.js":{"offset":37395115,"length":446,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/errors.js":{"offset":37395561,"length":3712,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/holepuncher.js":{"offset":37399273,"length":10003,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/messages.js":{"offset":37409276,"length":11789,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/nat.js":{"offset":37421065,"length":4714,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/noise-wrap.js":{"offset":37425779,"length":1669,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/persistent.js":{"offset":37427448,"length":8361,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/raw-stream-set.js":{"offset":37435809,"length":1511,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/router.js":{"offset":37437320,"length":6978,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/secure-payload.js":{"offset":37444298,"length":1491,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/semaphore.js":{"offset":37445789,"length":1577,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/server.js":{"offset":37447366,"length":21300,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/sleeper.js":{"offset":37468666,"length":690,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/lib/socket-pool.js":{"offset":37469356,"length":4343,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/endian.js":{"offset":37473699,"length":105,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/index.js":{"offset":37473804,"length":24454,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/lexint.js":{"offset":37498258,"length":2851,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/package.json":{"offset":37501109,"length":786,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/node_modules/compact-encoding/raw.js":{"offset":37501895,"length":4093,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperdht/package.json":{"offset":37505988,"length":2007,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/endian.js":{"offset":37507995,"length":105,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/index.js":{"offset":37508100,"length":24454,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/lexint.js":{"offset":37532554,"length":2851,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/package.json":{"offset":37535405,"length":786,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperschema/node_modules/compact-encoding/raw.js":{"offset":37536191,"length":4093,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperschema/package.json":{"offset":37540284,"length":1556,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperschema/runtime.cjs":{"offset":37541840,"length":54,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperswarm/index.js":{"offset":37541894,"length":18589,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperswarm/lib/bulk-timer.js":{"offset":37560483,"length":728,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperswarm/lib/connection-set.js":{"offset":37561211,"length":823,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperswarm/lib/peer-discovery.js":{"offset":37562034,"length":9296,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperswarm/lib/peer-info.js":{"offset":37571330,"length":2688,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperswarm/lib/retry-timer.js":{"offset":37574018,"length":1889,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/hyperswarm/package.json":{"offset":37575907,"length":1515,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/kademlia-routing-table/index.js":{"offset":37577422,"length":4145,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/kademlia-routing-table/package.json":{"offset":37581567,"length":967,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/nanoassert/index.js":{"offset":37582534,"length":438,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/nanoassert/package.json":{"offset":37582972,"length":647,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/nat-sampler/index.js":{"offset":37583619,"length":1550,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/nat-sampler/package.json":{"offset":37585169,"length":608,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/noise-curve-ed/index.js":{"offset":37585777,"length":1642,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/noise-curve-ed/package.json":{"offset":37587419,"length":808,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/noise-handshake/cipher.js":{"offset":37588227,"length":2817,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/noise-handshake/dh.js":{"offset":37591044,"length":1439,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/noise-handshake/hkdf.js":{"offset":37592483,"length":1092,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/noise-handshake/hmac.js":{"offset":37593575,"length":1273,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/noise-handshake/noise.js":{"offset":37594848,"length":6437,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/noise-handshake/package.json":{"offset":37601285,"length":638,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/noise-handshake/symmetric-state.js":{"offset":37601923,"length":2206,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/protomux/index.js":{"offset":37604129,"length":19741,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/protomux/package.json":{"offset":37623870,"length":1059,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/queue-tick/package.json":{"offset":37624929,"length":669,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/queue-tick/process-next-tick.js":{"offset":37625598,"length":160,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/queue-tick/queue-microtask.js":{"offset":37625758,"length":108,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/ready-resource/index.js":{"offset":37625866,"length":1091,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/ready-resource/package.json":{"offset":37626957,"length":812,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/record-cache/index.js":{"offset":37627769,"length":3668,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/record-cache/package.json":{"offset":37631437,"length":612,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/require-addon/lib/bare.js":{"offset":37632049,"length":45,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/require-addon/package.json":{"offset":37632094,"length":1449,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/safety-catch/index.js":{"offset":37633543,"length":543,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/safety-catch/package.json":{"offset":37634086,"length":547,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/shuffled-priority-queue/index.js":{"offset":37634633,"length":2607,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/shuffled-priority-queue/package.json":{"offset":37637240,"length":691,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/signal-promise/index.js":{"offset":37637931,"length":1252,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/signal-promise/package.json":{"offset":37639183,"length":503,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/sodium-native/binding.js":{"offset":37639686,"length":89,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/sodium-native/index.js":{"offset":37639775,"length":107894,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/sodium-native/package.json":{"offset":37747669,"length":1478,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/sodium-secretstream/index.js":{"offset":37749147,"length":2257,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/sodium-secretstream/package.json":{"offset":37751404,"length":657,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/sodium-universal/index.js":{"offset":37752061,"length":42,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/sodium-universal/package.json":{"offset":37752103,"length":1217,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/streamx/index.js":{"offset":37753320,"length":33510,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/streamx/package.json":{"offset":37786830,"length":912,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/teex/index.js":{"offset":37787742,"length":1107,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/teex/package.json":{"offset":37788849,"length":608,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/text-decoder/index.js":{"offset":37789457,"length":1371,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/text-decoder/lib/pass-through-decoder.js":{"offset":37790828,"length":269,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/text-decoder/lib/utf8-decoder.js":{"offset":37791097,"length":4429,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/text-decoder/package.json":{"offset":37795526,"length":990,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/time-ordered-set/index.js":{"offset":37796516,"length":1444,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/time-ordered-set/package.json":{"offset":37797960,"length":666,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/timeout-refresh/browser.js":{"offset":37798626,"length":1098,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/timeout-refresh/index.js":{"offset":37799724,"length":184,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/timeout-refresh/node.js":{"offset":37799908,"length":928,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/timeout-refresh/package.json":{"offset":37800836,"length":619,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/udx-native/binding.js":{"offset":37801455,"length":90,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/udx-native/lib/ip.js":{"offset":37801545,"length":2204,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/udx-native/lib/network-interfaces.js":{"offset":37803749,"length":1341,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/udx-native/lib/socket.js":{"offset":37805090,"length":7557,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/udx-native/lib/stream.js":{"offset":37812647,"length":12706,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/udx-native/lib/udx.js":{"offset":37825353,"length":2868,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/udx-native/package.json":{"offset":37828221,"length":1615,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/unordered-set/index.js":{"offset":37829836,"length":677,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/unordered-set/package.json":{"offset":37830513,"length":654,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/unslab/index.js":{"offset":37831167,"length":913,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/unslab/package.json":{"offset":37832080,"length":613,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/which-runtime/index.js":{"offset":37832693,"length":1231,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/which-runtime/package.json":{"offset":37833924,"length":602,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/xache/index.js":{"offset":37834526,"length":2378,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/xache/package.json":{"offset":37836904,"length":584,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/z32/index.js":{"offset":37837488,"length":2654,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/node_modules/z32/package.json":{"offset":37840142,"length":701,"mode":420},"/node_modules/pgh/node_modules/hyper-svc/package.json":{"offset":37840843,"length":1873,"mode":420},"/node_modules/pgh/node_modules/hyperbee/index.js":{"offset":37842716,"length":46445,"mode":420},"/node_modules/pgh/node_modules/hyperbee/iterators/diff.js":{"offset":37889161,"length":5358,"mode":420},"/node_modules/pgh/node_modules/hyperbee/iterators/history.js":{"offset":37894519,"length":1631,"mode":420},"/node_modules/pgh/node_modules/hyperbee/iterators/local.js":{"offset":37896150,"length":1170,"mode":420},"/node_modules/pgh/node_modules/hyperbee/iterators/range.js":{"offset":37897320,"length":5869,"mode":420},"/node_modules/pgh/node_modules/hyperbee/lib/extension.js":{"offset":37903189,"length":3488,"mode":420},"/node_modules/pgh/node_modules/hyperbee/lib/messages.js":{"offset":37906677,"length":28162,"mode":420},"/node_modules/pgh/node_modules/hyperbee/package.json":{"offset":37934839,"length":1585,"mode":420},"/node_modules/pgh/node_modules/hypercore-crypto/index.js":{"offset":37936424,"length":5031,"mode":420},"/node_modules/pgh/node_modules/hypercore-crypto/package.json":{"offset":37941455,"length":1007,"mode":420},"/node_modules/pgh/node_modules/hypercore-errors/index.js":{"offset":37942462,"length":4896,"mode":420},"/node_modules/pgh/node_modules/hypercore-errors/package.json":{"offset":37947358,"length":688,"mode":420},"/node_modules/pgh/node_modules/hypercore-id-encoding/index.js":{"offset":37948046,"length":923,"mode":420},"/node_modules/pgh/node_modules/hypercore-id-encoding/package.json":{"offset":37948969,"length":799,"mode":420},"/node_modules/pgh/node_modules/hypercore-storage/encoding/external.js":{"offset":37949768,"length":264,"mode":420},"/node_modules/pgh/node_modules/hypercore-storage/encoding/spec/hyperschema/index.js":{"offset":37950032,"length":16796,"mode":420},"/node_modules/pgh/node_modules/hypercore-storage/index.js":{"offset":37966828,"length":32609,"mode":420},"/node_modules/pgh/node_modules/hypercore-storage/lib/block-dependency-stream.js":{"offset":37999437,"length":2557,"mode":420},"/node_modules/pgh/node_modules/hypercore-storage/lib/close-error-stream.js":{"offset":38001994,"length":276,"mode":420},"/node_modules/pgh/node_modules/hypercore-storage/lib/keys.js":{"offset":38002270,"length":8751,"mode":420},"/node_modules/pgh/node_modules/hypercore-storage/lib/streams.js":{"offset":38011021,"length":5686,"mode":420},"/node_modules/pgh/node_modules/hypercore-storage/lib/tx.js":{"offset":38016707,"length":10227,"mode":420},"/node_modules/pgh/node_modules/hypercore-storage/lib/view.js":{"offset":38026934,"length":8379,"mode":420},"/node_modules/pgh/node_modules/hypercore-storage/migrations/0/index.js":{"offset":38035313,"length":20125,"mode":420},"/node_modules/pgh/node_modules/hypercore-storage/migrations/0/messages.js":{"offset":38055438,"length":26402,"mode":420},"/node_modules/pgh/node_modules/hypercore-storage/migrations/1/index.js":{"offset":38081840,"length":1181,"mode":420},"/node_modules/pgh/node_modules/hypercore-storage/package.json":{"offset":38083021,"length":1804,"mode":420},"/node_modules/pgh/node_modules/hypercore/index.js":{"offset":38084825,"length":40191,"mode":420},"/node_modules/pgh/node_modules/hypercore/lib/audit.js":{"offset":38125016,"length":3834,"mode":420},"/node_modules/pgh/node_modules/hypercore/lib/bit-interlude.js":{"offset":38128850,"length":4257,"mode":420},"/node_modules/pgh/node_modules/hypercore/lib/bitfield.js":{"offset":38133107,"length":12115,"mode":420},"/node_modules/pgh/node_modules/hypercore/lib/caps.js":{"offset":38145222,"length":1537,"mode":420},"/node_modules/pgh/node_modules/hypercore/lib/compat.js":{"offset":38146759,"length":477,"mode":420},"/node_modules/pgh/node_modules/hypercore/lib/copy-prologue.js":{"offset":38147236,"length":5999,"mode":420},"/node_modules/pgh/node_modules/hypercore/lib/core.js":{"offset":38153235,"length":28356,"mode":420},"/node_modules/pgh/node_modules/hypercore/lib/default-encryption.js":{"offset":38181591,"length":3453,"mode":420},"/node_modules/pgh/node_modules/hypercore/lib/download.js":{"offset":38185044,"length":1278,"mode":420},"/node_modules/pgh/node_modules/hypercore/lib/feature-flags.js":{"offset":38186322,"length":38,"mode":420},"/node_modules/pgh/node_modules/hypercore/lib/fully-remote-proof.js":{"offset":38186360,"length":3470,"mode":420},"/node_modules/pgh/node_modules/hypercore/lib/hotswap-queue.js":{"offset":38189830,"length":1498,"mode":420},"/node_modules/pgh/node_modules/hypercore/lib/info.js":{"offset":38191328,"length":1517,"mode":420},"/node_modules/pgh/node_modules/hypercore/lib/inspect.js":{"offset":38192845,"length":1983,"mode":420},"/node_modules/pgh/node_modules/hypercore/lib/mark-bitfield.js":{"offset":38194828,"length":2589,"mode":420},"/node_modules/pgh/node_modules/hypercore/lib/merkle-tree.js":{"offset":38197417,"length":34353,"mode":420},"/node_modules/pgh/node_modules/hypercore/lib/messages.js":{"offset":38231770,"length":28313,"mode":420},"/node_modules/pgh/node_modules/hypercore/lib/multisig.js":{"offset":38260083,"length":2851,"mode":420},"/node_modules/pgh/node_modules/hypercore/lib/mutex.js":{"offset":38262934,"length":1028,"mode":420},"/node_modules/pgh/node_modules/hypercore/lib/receiver-queue.js":{"offset":38263962,"length":1413,"mode":420},"/node_modules/pgh/node_modules/hypercore/lib/remote-bitfield.js":{"offset":38265375,"length":8124,"mode":420},"/node_modules/pgh/node_modules/hypercore/lib/replicator.js":{"offset":38273499,"length":87688,"mode":420},"/node_modules/pgh/node_modules/hypercore/lib/session-state.js":{"offset":38361187,"length":36078,"mode":420},"/node_modules/pgh/node_modules/hypercore/lib/streams.js":{"offset":38397265,"length":3034,"mode":420},"/node_modules/pgh/node_modules/hypercore/lib/verifier.js":{"offset":38400299,"length":9926,"mode":420},"/node_modules/pgh/node_modules/hypercore/lib/wants.js":{"offset":38410225,"length":7204,"mode":420},"/node_modules/pgh/node_modules/hypercore/package.json":{"offset":38417429,"length":2196,"mode":420},"/node_modules/pgh/node_modules/hyperdht-address/index.js":{"offset":38419625,"length":357,"mode":420},"/node_modules/pgh/node_modules/hyperdht-address/package.json":{"offset":38419982,"length":1046,"mode":420},"/node_modules/pgh/node_modules/hyperdht-address/spec/hyperschema/index.js":{"offset":38421028,"length":2106,"mode":420},"/node_modules/pgh/node_modules/hyperdht/index.js":{"offset":38423134,"length":16611,"mode":420},"/node_modules/pgh/node_modules/hyperdht/lib/announcer.js":{"offset":38439745,"length":7533,"mode":420},"/node_modules/pgh/node_modules/hyperdht/lib/connect.js":{"offset":38447278,"length":24788,"mode":420},"/node_modules/pgh/node_modules/hyperdht/lib/connection-pool.js":{"offset":38472066,"length":3050,"mode":420},"/node_modules/pgh/node_modules/hyperdht/lib/constants.js":{"offset":38475116,"length":1276,"mode":420},"/node_modules/pgh/node_modules/hyperdht/lib/crypto.js":{"offset":38476392,"length":632,"mode":420},"/node_modules/pgh/node_modules/hyperdht/lib/encode.js":{"offset":38477024,"length":446,"mode":420},"/node_modules/pgh/node_modules/hyperdht/lib/errors.js":{"offset":38477470,"length":3712,"mode":420},"/node_modules/pgh/node_modules/hyperdht/lib/holepuncher.js":{"offset":38481182,"length":10003,"mode":420},"/node_modules/pgh/node_modules/hyperdht/lib/messages.js":{"offset":38491185,"length":12057,"mode":420},"/node_modules/pgh/node_modules/hyperdht/lib/nat.js":{"offset":38503242,"length":4714,"mode":420},"/node_modules/pgh/node_modules/hyperdht/lib/noise-wrap.js":{"offset":38507956,"length":1669,"mode":420},"/node_modules/pgh/node_modules/hyperdht/lib/persistent.js":{"offset":38509625,"length":8361,"mode":420},"/node_modules/pgh/node_modules/hyperdht/lib/raw-stream-set.js":{"offset":38517986,"length":1511,"mode":420},"/node_modules/pgh/node_modules/hyperdht/lib/router.js":{"offset":38519497,"length":6978,"mode":420},"/node_modules/pgh/node_modules/hyperdht/lib/secure-payload.js":{"offset":38526475,"length":1491,"mode":420},"/node_modules/pgh/node_modules/hyperdht/lib/semaphore.js":{"offset":38527966,"length":1577,"mode":420},"/node_modules/pgh/node_modules/hyperdht/lib/server.js":{"offset":38529543,"length":21300,"mode":420},"/node_modules/pgh/node_modules/hyperdht/lib/sleeper.js":{"offset":38550843,"length":690,"mode":420},"/node_modules/pgh/node_modules/hyperdht/lib/socket-pool.js":{"offset":38551533,"length":4343,"mode":420},"/node_modules/pgh/node_modules/hyperdht/package.json":{"offset":38555876,"length":2007,"mode":420},"/node_modules/pgh/node_modules/hyperschema/package.json":{"offset":38557883,"length":1555,"mode":420},"/node_modules/pgh/node_modules/hyperschema/runtime.cjs":{"offset":38559438,"length":54,"mode":420},"/node_modules/pgh/node_modules/hyperswarm/index.js":{"offset":38559492,"length":18589,"mode":420},"/node_modules/pgh/node_modules/hyperswarm/lib/bulk-timer.js":{"offset":38578081,"length":728,"mode":420},"/node_modules/pgh/node_modules/hyperswarm/lib/connection-set.js":{"offset":38578809,"length":823,"mode":420},"/node_modules/pgh/node_modules/hyperswarm/lib/peer-discovery.js":{"offset":38579632,"length":9296,"mode":420},"/node_modules/pgh/node_modules/hyperswarm/lib/peer-info.js":{"offset":38588928,"length":2688,"mode":420},"/node_modules/pgh/node_modules/hyperswarm/lib/retry-timer.js":{"offset":38591616,"length":1889,"mode":420},"/node_modules/pgh/node_modules/hyperswarm/package.json":{"offset":38593505,"length":1515,"mode":420},"/node_modules/pgh/node_modules/index-encoder/index.js":{"offset":38595020,"length":10596,"mode":420},"/node_modules/pgh/node_modules/index-encoder/package.json":{"offset":38605616,"length":928,"mode":420},"/node_modules/pgh/node_modules/is-options/index.js":{"offset":38606544,"length":140,"mode":420},"/node_modules/pgh/node_modules/is-options/package.json":{"offset":38606684,"length":605,"mode":420},"/node_modules/pgh/node_modules/kademlia-routing-table/index.js":{"offset":38607289,"length":4145,"mode":420},"/node_modules/pgh/node_modules/kademlia-routing-table/package.json":{"offset":38611434,"length":967,"mode":420},"/node_modules/pgh/node_modules/mutexify/index.js":{"offset":38612401,"length":536,"mode":420},"/node_modules/pgh/node_modules/mutexify/package.json":{"offset":38612937,"length":679,"mode":420},"/node_modules/pgh/node_modules/mutexify/promise.js":{"offset":38613616,"length":324,"mode":420},"/node_modules/pgh/node_modules/nanoassert/index.js":{"offset":38613940,"length":438,"mode":420},"/node_modules/pgh/node_modules/nanoassert/package.json":{"offset":38614378,"length":647,"mode":420},"/node_modules/pgh/node_modules/nat-sampler/index.js":{"offset":38615025,"length":1550,"mode":420},"/node_modules/pgh/node_modules/nat-sampler/package.json":{"offset":38616575,"length":608,"mode":420},"/node_modules/pgh/node_modules/noise-curve-ed/index.js":{"offset":38617183,"length":1642,"mode":420},"/node_modules/pgh/node_modules/noise-curve-ed/package.json":{"offset":38618825,"length":808,"mode":420},"/node_modules/pgh/node_modules/noise-handshake/cipher.js":{"offset":38619633,"length":2817,"mode":420},"/node_modules/pgh/node_modules/noise-handshake/dh.js":{"offset":38622450,"length":1439,"mode":420},"/node_modules/pgh/node_modules/noise-handshake/hkdf.js":{"offset":38623889,"length":1092,"mode":420},"/node_modules/pgh/node_modules/noise-handshake/hmac.js":{"offset":38624981,"length":1273,"mode":420},"/node_modules/pgh/node_modules/noise-handshake/noise.js":{"offset":38626254,"length":6437,"mode":420},"/node_modules/pgh/node_modules/noise-handshake/package.json":{"offset":38632691,"length":638,"mode":420},"/node_modules/pgh/node_modules/noise-handshake/symmetric-state.js":{"offset":38633329,"length":2206,"mode":420},"/node_modules/pgh/node_modules/protocol-buffers-encodings/index.js":{"offset":38635535,"length":6489,"mode":420},"/node_modules/pgh/node_modules/protocol-buffers-encodings/package.json":{"offset":38642024,"length":719,"mode":420},"/node_modules/pgh/node_modules/protomux-wakeup/index.js":{"offset":38642743,"length":16824,"mode":420},"/node_modules/pgh/node_modules/protomux-wakeup/package.json":{"offset":38659567,"length":972,"mode":420},"/node_modules/pgh/node_modules/protomux-wakeup/spec/hyperschema/index.js":{"offset":38660539,"length":3335,"mode":420},"/node_modules/pgh/node_modules/protomux/index.js":{"offset":38663874,"length":19741,"mode":420},"/node_modules/pgh/node_modules/protomux/package.json":{"offset":38683615,"length":1059,"mode":420},"/node_modules/pgh/node_modules/queue-tick/package.json":{"offset":38684674,"length":669,"mode":420},"/node_modules/pgh/node_modules/queue-tick/process-next-tick.js":{"offset":38685343,"length":160,"mode":420},"/node_modules/pgh/node_modules/queue-tick/queue-microtask.js":{"offset":38685503,"length":108,"mode":420},"/node_modules/pgh/node_modules/quickbit-native/binding.js":{"offset":38685611,"length":90,"mode":420},"/node_modules/pgh/node_modules/quickbit-native/index.js":{"offset":38685701,"length":4683,"mode":420},"/node_modules/pgh/node_modules/quickbit-native/package.json":{"offset":38690384,"length":1104,"mode":420},"/node_modules/pgh/node_modules/quickbit-universal/fallback.js":{"offset":38691488,"length":10204,"mode":420},"/node_modules/pgh/node_modules/quickbit-universal/index.js":{"offset":38701692,"length":442,"mode":420},"/node_modules/pgh/node_modules/quickbit-universal/package.json":{"offset":38702134,"length":908,"mode":420},"/node_modules/pgh/node_modules/rache/index.js":{"offset":38703042,"length":2463,"mode":420},"/node_modules/pgh/node_modules/rache/package.json":{"offset":38705505,"length":602,"mode":420},"/node_modules/pgh/node_modules/random-array-iterator/index.js":{"offset":38706107,"length":1001,"mode":420},"/node_modules/pgh/node_modules/random-array-iterator/package.json":{"offset":38707108,"length":700,"mode":420},"/node_modules/pgh/node_modules/ready-resource/index.js":{"offset":38707808,"length":1091,"mode":420},"/node_modules/pgh/node_modules/ready-resource/package.json":{"offset":38708899,"length":812,"mode":420},"/node_modules/pgh/node_modules/record-cache/index.js":{"offset":38709711,"length":3668,"mode":420},"/node_modules/pgh/node_modules/record-cache/package.json":{"offset":38713379,"length":612,"mode":420},"/node_modules/pgh/node_modules/refcounter/index.js":{"offset":38713991,"length":611,"mode":420},"/node_modules/pgh/node_modules/refcounter/package.json":{"offset":38714602,"length":451,"mode":420},"/node_modules/pgh/node_modules/require-addon/lib/bare.js":{"offset":38715053,"length":45,"mode":420},"/node_modules/pgh/node_modules/require-addon/package.json":{"offset":38715098,"length":1449,"mode":420},"/node_modules/pgh/node_modules/resolve-reject-promise/index.js":{"offset":38716547,"length":443,"mode":420},"/node_modules/pgh/node_modules/resolve-reject-promise/package.json":{"offset":38716990,"length":581,"mode":420},"/node_modules/pgh/node_modules/resource-on-exit/index.js":{"offset":38717571,"length":361,"mode":420},"/node_modules/pgh/node_modules/resource-on-exit/package.json":{"offset":38717932,"length":496,"mode":420},"/node_modules/pgh/node_modules/rocksdb-native/binding.js":{"offset":38718428,"length":90,"mode":420},"/node_modules/pgh/node_modules/rocksdb-native/index.js":{"offset":38718518,"length":4758,"mode":420},"/node_modules/pgh/node_modules/rocksdb-native/lib/batch.js":{"offset":38723276,"length":9605,"mode":420},"/node_modules/pgh/node_modules/rocksdb-native/lib/column-family.js":{"offset":38732881,"length":2930,"mode":420},"/node_modules/pgh/node_modules/rocksdb-native/lib/constants.js":{"offset":38735811,"length":399,"mode":420},"/node_modules/pgh/node_modules/rocksdb-native/lib/filter-policy.js":{"offset":38736210,"length":437,"mode":420},"/node_modules/pgh/node_modules/rocksdb-native/lib/iterator.js":{"offset":38736647,"length":4311,"mode":420},"/node_modules/pgh/node_modules/rocksdb-native/lib/snapshot.js":{"offset":38740958,"length":503,"mode":420},"/node_modules/pgh/node_modules/rocksdb-native/lib/state.js":{"offset":38741461,"length":10338,"mode":420},"/node_modules/pgh/node_modules/rocksdb-native/package.json":{"offset":38751799,"length":1863,"mode":420},"/node_modules/pgh/node_modules/safety-catch/index.js":{"offset":38753662,"length":543,"mode":420},"/node_modules/pgh/node_modules/safety-catch/package.json":{"offset":38754205,"length":547,"mode":420},"/node_modules/pgh/node_modules/scope-lock/index.js":{"offset":38754752,"length":1821,"mode":420},"/node_modules/pgh/node_modules/scope-lock/package.json":{"offset":38756573,"length":611,"mode":420},"/node_modules/pgh/node_modules/shuffled-priority-queue/index.js":{"offset":38757184,"length":2607,"mode":420},"/node_modules/pgh/node_modules/shuffled-priority-queue/package.json":{"offset":38759791,"length":691,"mode":420},"/node_modules/pgh/node_modules/signal-promise/index.js":{"offset":38760482,"length":1252,"mode":420},"/node_modules/pgh/node_modules/signal-promise/package.json":{"offset":38761734,"length":503,"mode":420},"/node_modules/pgh/node_modules/signed-varint/index.js":{"offset":38762237,"length":435,"mode":420},"/node_modules/pgh/node_modules/signed-varint/package.json":{"offset":38762672,"length":523,"mode":420},"/node_modules/pgh/node_modules/simdle-native/binding.js":{"offset":38763195,"length":90,"mode":420},"/node_modules/pgh/node_modules/simdle-native/index.js":{"offset":38763285,"length":3474,"mode":420},"/node_modules/pgh/node_modules/simdle-native/package.json":{"offset":38766759,"length":1115,"mode":420},"/node_modules/pgh/node_modules/simdle-universal/fallback.js":{"offset":38767874,"length":5137,"mode":420},"/node_modules/pgh/node_modules/simdle-universal/index.js":{"offset":38773011,"length":103,"mode":420},"/node_modules/pgh/node_modules/simdle-universal/package.json":{"offset":38773114,"length":879,"mode":420},"/node_modules/pgh/node_modules/simdle-universal/scalar.js":{"offset":38773993,"length":469,"mode":420},"/node_modules/pgh/node_modules/sodium-native/binding.js":{"offset":38774462,"length":89,"mode":420},"/node_modules/pgh/node_modules/sodium-native/index.js":{"offset":38774551,"length":107894,"mode":420},"/node_modules/pgh/node_modules/sodium-native/package.json":{"offset":38882445,"length":1478,"mode":420},"/node_modules/pgh/node_modules/sodium-secretstream/index.js":{"offset":38883923,"length":2257,"mode":420},"/node_modules/pgh/node_modules/sodium-secretstream/package.json":{"offset":38886180,"length":657,"mode":420},"/node_modules/pgh/node_modules/sodium-universal/index.js":{"offset":38886837,"length":42,"mode":420},"/node_modules/pgh/node_modules/sodium-universal/package.json":{"offset":38886879,"length":1217,"mode":420},"/node_modules/pgh/node_modules/streamx/index.js":{"offset":38888096,"length":34248,"mode":420},"/node_modules/pgh/node_modules/streamx/lib/errors.js":{"offset":38922344,"length":1096,"mode":420},"/node_modules/pgh/node_modules/streamx/package.json":{"offset":38923440,"length":1080,"mode":420},"/node_modules/pgh/node_modules/sub-encoder/index.js":{"offset":38924520,"length":1968,"mode":420},"/node_modules/pgh/node_modules/sub-encoder/package.json":{"offset":38926488,"length":908,"mode":420},"/node_modules/pgh/node_modules/teex/index.js":{"offset":38927396,"length":1107,"mode":420},"/node_modules/pgh/node_modules/teex/package.json":{"offset":38928503,"length":608,"mode":420},"/node_modules/pgh/node_modules/text-decoder/index.js":{"offset":38929111,"length":1371,"mode":420},"/node_modules/pgh/node_modules/text-decoder/lib/pass-through-decoder.js":{"offset":38930482,"length":269,"mode":420},"/node_modules/pgh/node_modules/text-decoder/lib/utf8-decoder.js":{"offset":38930751,"length":4429,"mode":420},"/node_modules/pgh/node_modules/text-decoder/package.json":{"offset":38935180,"length":990,"mode":420},"/node_modules/pgh/node_modules/time-ordered-set/index.js":{"offset":38936170,"length":1444,"mode":420},"/node_modules/pgh/node_modules/time-ordered-set/package.json":{"offset":38937614,"length":666,"mode":420},"/node_modules/pgh/node_modules/timeout-refresh/browser.js":{"offset":38938280,"length":1098,"mode":420},"/node_modules/pgh/node_modules/timeout-refresh/index.js":{"offset":38939378,"length":184,"mode":420},"/node_modules/pgh/node_modules/timeout-refresh/node.js":{"offset":38939562,"length":928,"mode":420},"/node_modules/pgh/node_modules/timeout-refresh/package.json":{"offset":38940490,"length":619,"mode":420},"/node_modules/pgh/node_modules/tiny-buffer-map/index.js":{"offset":38941109,"length":936,"mode":420},"/node_modules/pgh/node_modules/tiny-buffer-map/package.json":{"offset":38942045,"length":650,"mode":420},"/node_modules/pgh/node_modules/udx-native/binding.js":{"offset":38942695,"length":90,"mode":420},"/node_modules/pgh/node_modules/udx-native/lib/ip.js":{"offset":38942785,"length":2204,"mode":420},"/node_modules/pgh/node_modules/udx-native/lib/network-interfaces.js":{"offset":38944989,"length":1341,"mode":420},"/node_modules/pgh/node_modules/udx-native/lib/socket.js":{"offset":38946330,"length":7557,"mode":420},"/node_modules/pgh/node_modules/udx-native/lib/stream.js":{"offset":38953887,"length":13050,"mode":420},"/node_modules/pgh/node_modules/udx-native/lib/udx.js":{"offset":38966937,"length":2868,"mode":420},"/node_modules/pgh/node_modules/udx-native/package.json":{"offset":38969805,"length":1665,"mode":420},"/node_modules/pgh/node_modules/unordered-set/index.js":{"offset":38971470,"length":677,"mode":420},"/node_modules/pgh/node_modules/unordered-set/package.json":{"offset":38972147,"length":654,"mode":420},"/node_modules/pgh/node_modules/unslab/index.js":{"offset":38972801,"length":913,"mode":420},"/node_modules/pgh/node_modules/unslab/package.json":{"offset":38973714,"length":613,"mode":420},"/node_modules/pgh/node_modules/varint/decode.js":{"offset":38974327,"length":508,"mode":420},"/node_modules/pgh/node_modules/varint/encode.js":{"offset":38974835,"length":452,"mode":420},"/node_modules/pgh/node_modules/varint/index.js":{"offset":38975287,"length":134,"mode":420},"/node_modules/pgh/node_modules/varint/length.js":{"offset":38975421,"length":471,"mode":420},"/node_modules/pgh/node_modules/varint/package.json":{"offset":38975892,"length":511,"mode":420},"/node_modules/pgh/node_modules/which-runtime/index.js":{"offset":38976403,"length":1469,"mode":420},"/node_modules/pgh/node_modules/which-runtime/package.json":{"offset":38977872,"length":863,"mode":420},"/node_modules/pgh/node_modules/xache/index.js":{"offset":38978735,"length":2378,"mode":420},"/node_modules/pgh/node_modules/xache/package.json":{"offset":38981113,"length":584,"mode":420},"/node_modules/pgh/node_modules/z32/index.js":{"offset":38981697,"length":2654,"mode":420},"/node_modules/pgh/node_modules/z32/package.json":{"offset":38984351,"length":701,"mode":420},"/node_modules/pgh/package.json":{"offset":38985052,"length":4099,"mode":420},"/node_modules/require-addon/lib/bare.js":{"offset":38989151,"length":45,"mode":420},"/node_modules/require-addon/package.json":{"offset":38989196,"length":1449,"mode":420},"/node_modules/sodium-native/binding.js":{"offset":38990645,"length":89,"mode":420},"/node_modules/sodium-native/index.js":{"offset":38990734,"length":107894,"mode":420},"/node_modules/sodium-native/package.json":{"offset":39098628,"length":1478,"mode":420},"/node_modules/sodium-universal/index.js":{"offset":39100106,"length":42,"mode":420},"/node_modules/sodium-universal/package.json":{"offset":39100148,"length":1217,"mode":420},"/node_modules/streamx/index.js":{"offset":39101365,"length":34248,"mode":420},"/node_modules/streamx/lib/errors.js":{"offset":39135613,"length":1096,"mode":420},"/node_modules/streamx/package.json":{"offset":39136709,"length":1225,"mode":420},"/node_modules/teex/index.js":{"offset":39137934,"length":1107,"mode":420},"/node_modules/teex/package.json":{"offset":39139041,"length":608,"mode":420},"/node_modules/text-decoder/index.js":{"offset":39139649,"length":1371,"mode":420},"/node_modules/text-decoder/lib/pass-through-decoder.js":{"offset":39141020,"length":269,"mode":420},"/node_modules/text-decoder/lib/utf8-decoder.js":{"offset":39141289,"length":4429,"mode":420},"/node_modules/text-decoder/package.json":{"offset":39145718,"length":990,"mode":420},"/node_modules/which-runtime/index.js":{"offset":39146708,"length":1469,"mode":420},"/node_modules/which-runtime/package.json":{"offset":39148177,"length":863,"mode":420},"/package.json":{"offset":39149040,"length":3020,"mode":420}}}
// MOVED: the ceremony now lives in hyper-proto-peer/lib/adopt.js.
//
// It belongs beside coowner.js — the ceremony it drives — because ANY node holding the DID must be able
// to mint an invite for the next device, not just the phone. Keet's `addDevice` is available to every
// active member and confers nothing on the adder; ours should be too.
//
// The phone keeps importing from here so lib/node.js and test/adopt.test.mjs are unchanged.
export { mintAdoptInvite, joinAdoptInvite } from 'hyper-proto-peer/lib/adopt.js'
// Which bundle this boot runs — the staged one, or the APK's.
//
// ⛔ ITS OWN MODULE, WITH NO IMPORTS, because it is needed on BOTH sides of the bridge and they share no
// filesystem API. The decision is made in React Native (RNFS) before the worklet starts; the staging that
// feeds it happens inside the worklet (bare-fs). lib/ota.js imports bare-fs at module top level, so
// importing it from the RN side would break the app on load — a mistake worth naming, because the split
// is not tidiness, it is the only reason this can be called where it has to be called.
//
// Pure and dependency-free, like lib/ipc-client.js and lib/lifecycle.js, and testable without a handset —
// which is the only place the consequences of getting this wrong actually show up.

/**
 * @param {{current: ?{treeHash: string, file: string, builtAt: ?number}, pending: ?{treeHash: string},
 *          failed: string[], assetBuiltAt: ?number}} state
 * @returns {{use:'staged'|'asset', hash:?string, file:?string, markPending:boolean, condemn:?string, reason:string}}
 *
 * ⛔ A STAGED BUNDLE NOTHING RUNS IS NOT AN UPDATE, and running one blindly is how a phone gets bricked.
 * There is no adb on a user's handset and no UI left if the node cannot boot, so the only safe shape is a
 * watchdog: record the intent BEFORE starting, clear it once the node reports ready, and treat a marker
 * that survived a boot as proof that bundle does not work.
 *
 * The failure this exists to prevent is the retry loop — a bad bundle chosen again on every boot, dying
 * identically each time, with no way in from outside.
 */
export function chooseBundle ({ current = null, pending = null, failed = [], assetBuiltAt = null } = {}) {
  const asset = (reason, condemn = null) => ({ use: 'asset', hash: null, file: null, markPending: false, condemn, reason })

  // A pending marker means the LAST boot started a bundle and never reached ready. Condemn whatever it
  // names — which is not necessarily what is staged now, so it is read from the marker, not from current.
  const condemn = pending && pending.treeHash ? pending.treeHash : null
  const dead = new Set([...(Array.isArray(failed) ? failed : []), ...(condemn ? [condemn] : [])])

  if (!current || !current.treeHash || !current.file) return asset('nothing staged', condemn)
  // A newer bundle still gets its chance: refusing every staged bundle after one bad build would make the
  // phone permanently un-updatable by a single bad release, and the fix for a bad release is the next one.
  if (dead.has(current.treeHash)) return asset('staged bundle previously failed to boot', condemn)

  // ⛔ AN APK INSTALL MUST SUPERSEDE AN OLDER STAGED BUNDLE. Staged used to win unconditionally, and tree
  // hashes carry no ordering — so installing a newer APK left the phone running the JS staged before it,
  // until the next OTA pass happened to catch up. Observed twice on a handset while shipping today: the
  // new shell booted, the new bundle sat in assets, and the old staged one ran anyway.
  //
  // Build times are the only comparable thing the two sides share: the CI stamps the APK's bundle
  // (`worklet.bundle.built`) and lib/ota.js records the release's build time in the staged marker. Both
  // absent means an older shell or an older staged marker, and the historic behaviour (staged wins) is
  // kept — never guess an ordering out of nothing.
  const staged = Number(current.builtAt) || 0
  const shipped = Number(assetBuiltAt) || 0
  if (shipped && staged && shipped > staged) {
    return asset('the app was updated more recently than the staged bundle', condemn)
  }
  // ⛔ AND AN UNDATED STAGED BUNDLE LOSES TO A STAMPED APK TOO.
  //
  // Requiring BOTH times made a whole class of staged bundles permanently unbeatable: the HTTPS fetcher's
  // getLatestRelease returned { name, version, treeHash } and no builtAt, so every bundle it ever staged
  // has a marker with no build time. `staged` is 0, the clause above cannot fire, and the phone keeps
  // running that JS through every future APK install.
  //
  // It is not hypothetical and the symptom is the worst kind — the install succeeds, the version looks
  // right, and the code does not run. Four APKs were installed on a handset on 2026-08-25, each carrying
  // fixes, and none took effect: a bundle staged from 0.1.6 won every boot. Most of an evening went into
  // diagnosing "my changes are not on the phone".
  //
  // An APK install is a PHYSICAL, DELIBERATE act by someone holding the device. A staged bundle that
  // cannot say when it was built cannot be shown to be newer than that, so the tie goes to the APK.
  // A staged bundle that CAN say, and is newer, still wins — OTA has to keep working, and that is the
  // case immediately above.
  if (shipped && !staged) {
    return asset('the staged bundle carries no build time; an installed APK is the more recent evidence', condemn)
  }

  return {
    use: 'staged',
    hash: current.treeHash,
    file: current.file,
    markPending: true,
    condemn,
    reason: 'staged bundle available'
  }
}
// The client for favela-web's HTTP API — the ONE place that knows the URL shape and how the session
// is carried.
//
// ⛔ NO SCREEN MAY CALL fetch(favelaUrl + …) DIRECTLY. The moment two components build their own
// request the session handling has two definitions, and the one that forgets the cookie degrades
// SILENTLY: favela-web answers 200 with viewerDid null, so the posts render un-liked, un-reposted and
// unmuted, and nothing anywhere says why. That is the same "two definitions drift apart" failure the
// IPC client exists to prevent (see lib/ipc-client.js), one layer out.
//
// The session is a cookie because favela-web is a web server and the browser client is its first
// consumer. There is no cookie jar here, so we set the header explicitly — bare-fetch and RN's fetch
// differ on jar behaviour and relying on either would be a silent per-platform difference.

const DEFAULT_TIMEOUT = 30_000

export class FavelaApi {
  /**
   * @param {object}   opts
   * @param {string}   opts.baseUrl     e.g. http://127.0.0.1:4041
   * @param {string?}  opts.session     favela_session token, or null for anonymous
   * @param {Function} [opts.fetchImpl] defaults to globalThis.fetch
   * @param {number}   [opts.timeout]
   */
  constructor ({ baseUrl, session = null, fetchImpl = null, timeout = DEFAULT_TIMEOUT } = {}) {
    if (!baseUrl) throw new Error('FavelaApi requires baseUrl')
    this.baseUrl = String(baseUrl).replace(/\/+$/, '')
    this.session = session
    this._fetch = fetchImpl || (typeof globalThis.fetch === 'function' ? globalThis.fetch.bind(globalThis) : null)
    if (!this._fetch) throw new Error('FavelaApi: no fetch available')
    this._timeout = timeout
  }

  /** True when requests carry a viewer. A screen that renders viewer-dependent UI should check this. */
  get authenticated () { return !!this.session }

  url (path, params) {
    const qs = params
      ? Object.entries(params)
        .filter(([, v]) => v !== undefined && v !== null && v !== '')
        .map(([k, v]) => encodeURIComponent(k) + '=' + encodeURIComponent(String(v)))
        .join('&')
      : ''
    return this.baseUrl + path + (qs ? '?' + qs : '')
  }

  async get (path, params) {
    const headers = {}
    // Explicit, not jar-dependent — see the header note above.
    if (this.session) headers.cookie = 'favela_session=' + this.session
    const res = await this._fetch(this.url(path, params), { headers })
    let body = null
    try { body = await res.json() } catch { /* non-JSON error page — fall through to status */ }
    if (!res.ok) {
      // Name the ROUTE. "HTTP 400" alone sends the reader to the wrong screen.
      throw new Error('favela-web ' + path + ' → ' + res.status + (body && body.error ? ': ' + body.error : ''))
    }
    return body
  }

  // The write half. Same session rule as `get` — and the same reason it lives here rather than at the
  // call site: a POST that forgets the cookie does not fail, it gets a 401 with an `error` body, and the
  // caller that hand-rolled it is the one least likely to check.
  async post (path, body) {
    const headers = { 'content-type': 'application/json' }
    if (this.session) headers.cookie = 'favela_session=' + this.session
    const res = await this._fetch(this.url(path), { method: 'POST', headers, body: JSON.stringify(body || {}) })
    let out = null
    try { out = await res.json() } catch { /* non-JSON error page — fall through to status */ }
    if (!res.ok) throw new Error('favela-web ' + path + ' → ' + res.status + (out && out.error ? ': ' + out.error : ''))
    return out
  }

  // Typed wrappers. Thin on purpose — they exist so a screen never types a path, not to add logic.
  timeline ({ limit = 30 } = {}) { return this.get('/api/timeline', { limit }) }
  author ({ did, limit = 30 } = {}) { return this.get('/api/author', { did, limit }) }
  profile ({ did } = {}) { return this.get('/api/profile', { did }) }
  thread ({ uri, depth, parentHeight } = {}) { return this.get('/api/thread', { uri, depth, parentHeight }) }
  replies ({ uri, limit = 50 } = {}) { return this.get('/api/replies', { uri, limit }) }
  search ({ q, kind = 'posts', limit = 25 } = {}) { return this.get('/api/search', { q, kind, limit }) }
  follows ({ did } = {}) { return this.get('/api/follows', { did }) }
  followers ({ did } = {}) { return this.get('/api/followers', { did }) }
  // hydrate=1 — profiles included, so a list of PEOPLE is one request rather than N+1. The bare-list
  // form above stays for callers that only need DIDs and would discard the hydration.
  people ({ did, kind = 'follows', limit = 200 } = {}) {
    return this.get(kind === 'followers' ? '/api/followers' : '/api/follows', { did, limit, hydrate: 1 })
  }
  tagFeed ({ tag, limit = 30 } = {}) { return this.get('/api/feed', { tag, limit }) }

  // Subscribe to a DID: favela-web resolves its verifyKey, joins its topic and follows the freshest
  // VERIFIED co-owner's firehose. Idempotent — addPeer returns the existing peer for a DID already read.
  //
  // ⛔ THIS IS THE ONLY WAY THE PHONE SHOULD INDEX ANYONE. The worklet used to keep its own appview and
  // fold records into it straight off local disk, which skipped every check this route performs and fed
  // an index no screen reads. A DID favela-web hosts takes addPeer's coHosted branch and baselines from
  // the shared store rather than the network, so `track` is right for our own DIDs too.
  track ({ did, wait } = {}) { return this.post('/api/track', { did, ...(wait ? { wait } : {}) }) }

  // Follow/unfollow — a TOGGLE, and favela-web owns both halves: it reads the existing follow rkey, asks
  // hpp to write or delete the record, and updates its own index. Nothing here decides anything.
  follow ({ did } = {}) { return this.post('/api/follow', { did }) }
}

/** Build an API client from the worklet's `status`, or null if favela-web is not up. */
export function apiFromStatus (status, fetchImpl = null) {
  if (!status || !status.favelaUrl) return null
  return new FavelaApi({ baseUrl: status.favelaUrl, session: status.favelaSession || null, fetchImpl })
}
// Accepting a bridge's invite, FROM THE PHONE — using the vault mint already sealed.
//
// The ceremony needs the recovery key, and a PLC update must be signed by a current rotation key, which
// for a swarm identity is exactly one: the root recovery key. mint seals that under a passphrase at
// creation time precisely so it can be used again later without anyone re-typing 24 words. This is the
// "later".
//
// ⛔ THE PASSPHRASE IS THE ONLY THING THAT CROSSES THE BRIDGE. The page collects it; the worklet opens
// the vault, derives the key, signs and submits. The mnemonic never reaches React Native, never reaches
// the WebView, and never reaches a log line. Same rule as mint, for the same reason.
//
// ⛔ PREVIEW FIRST, ALWAYS. A PLC append is permanent and public, so the handler previews unless told to
// submit — the shape hosting-cli.js established and the one a web UI needs, because a confirm screen is
// only honest if the thing it describes is the thing that will happen.

import path from 'bare-path'

export { attachHosting, detachHosting } from 'atproto-identity/lib/hosting.js'
export { describeChange, resolveSigner, hostingAttach, hostingDetach, hostingShow } from 'hyper-proto-peer/lib/hosting-cli.js'

/**
 * Where mint sealed this identity's recovery vault.
 *
 * Pure, and separate from the handler, because "can this phone accept an invite at all?" is answerable
 * without opening anything — a UI needs to know whether to offer the control before it asks for a
 * passphrase, and offering a control that cannot work is the bug this whole evening kept producing.
 *
 * Named by the DID's own suffix rather than a single vault.json: one device may hold several identities,
 * and a shared filename silently means "the last one minted".
 */
export function vaultPathFor (hppDir, did) {
  if (!hppDir || !did) throw new Error('vaultPathFor: hppDir and did required')
  const suffix = String(did).split(':').pop()
  if (!suffix) throw new Error('vaultPathFor: malformed did ' + did)
  return path.join(hppDir, 'recovery', suffix + '.vault.json')
}
// Creating an identity lives in hyper-proto-peer/lib/mint.js, beside coowner.js — the ceremony it is
// the counterpart of. ANY node should be able to mint, not just the phone: a desktop favela on a fresh
// install has exactly the same problem, and #54 §7's whole point is that this belongs where every
// device gets it rather than in one shell.
//
// The phone imports from here so lib/node.js reads the same as it does for adopt.
export { mintIdentity, submitMintedGenesis } from 'hyper-proto-peer/lib/mint.js'
// favela-android worklet — a FULL favela node, headless, speaking IPC to a React Native UI.
//
// ⛔ THIS IS NOT favela-web WITH THE HTML REMOVED. favela-web binds an HTTP port because a browser needs
// one. React Native does not: bare-kit already provides an IPC channel between the worklet thread and
// the app. Keeping an HTTP server here would mean binding a socket, serialising objects to HTML, and
// parsing them back — to avoid using the channel that is already open. So: no port, no render.js, no
// static assets. Objects cross the boundary.
//
// What IS reused from favela-web, unchanged: the appview (index + every query), repo-sync, communities,
// hosted-dids, and the whole atproto/holepunch stack. The appview was always render-agnostic —
// getTimeline/_hydrate return plain objects and nothing in the index knows HTML exists — which is why
// this is a re-render rather than a rewrite. See spec/architecture.md §1.
//
// ⛔ THE WORKLET OWNS ALL STATE. RN holds no atproto knowledge: no CAR parsing, no MST, no signing. If
// the UI ever needs atproto-repo, the boundary has been drawn in the wrong place. Every mutation goes
// through here, so the signing key never leaves the thread that owns it.
import 'favela-web/lib/bare-globals.js'
import process from 'bare-process'
import fs from 'bare-fs'
import path from 'bare-path'
import b4a from 'b4a'
import { createUtf8Decoder } from './utf8.js'
import { rosterEnv } from './roster.js'
import { parseShell, shellState, SHELL_FILE, STATE_FILE } from './shell-handoff.js'

const IPC = typeof BareKit !== 'undefined' ? BareKit.IPC : null

// Line-delimited JSON over the bare-kit pipe. Deliberately dumb: a request carries an `id`, the reply
// echoes it. Anything richer (streaming, backpressure) can be added when a screen actually needs it —
// inventing it now would be designing against imagined requirements.
function send (obj) {
  if (!IPC) { console.log(JSON.stringify(obj)); return }
  try { IPC.write(Buffer.from(JSON.stringify(obj) + '\n')) } catch { /* UI gone; node keeps running */ }
}
// ⛔ ALSO TO THE SYSTEM LOG. These lines are the only account of what the node did at boot — whether hpp
// came up, why it didn't, which DIDs loaded. Sending them ONLY over IPC meant they existed for the two
// seconds they were on the startup screen and nowhere else: unreadable by adb, ungrepable after the
// fact, and gone entirely if the UI was not watching yet. A boot log that cannot be read after boot is
// not a log. bare-kit routes console.* to logcat under the `bare` identifier.
const log = (msg, extra = {}) => {
  const line = Object.keys(extra).length ? msg + ' ' + JSON.stringify(extra) : msg
  try { console.log('[favela] ' + line) } catch {}
  send({ t: 'log', msg, ...extra })
}

// Android hands the app-private dir in as argv (there is no $HOME and no env on a phone — this replaces
// favela's FAVELA_STORE_ROOT convention entirely).
const storage = Bare.argv[Bare.argv.length - 1]

const dirs = {
  root: storage,
  hpp: path.join(storage, 'hpp'),
  favela: path.join(storage, 'favela'),
  overlay: path.join(storage, 'hpp', 'atproto-repo')
}

// What the native shell handed us for THIS boot: which bundle it started, whether it can service the
// settings page's update buttons, and the OS's DNS servers. Read once, here, because prepareEnv turns
// two of the three into env that favela-web freezes at import (see below).
//
// Absent on an old shell — every field then reads as "unknown", which is the honest answer and disables
// exactly the features that depend on it. See lib/shell-handoff.js for why this is a file, not argv.
const shell = (() => {
  try { return parseShell(fs.readFileSync(path.join(storage, SHELL_FILE), 'utf8')) } catch { return parseShell(null) }
})()

// ⛔ ENV BEFORE ANY IMPORT THAT READS IT. favela-web's libs capture process.env at module top level, so
// their config freezes on first import. Everything below is therefore assigned here and every favela
// import in boot() is DYNAMIC.
function prepareEnv () {
  for (const d of Object.values(dirs)) fs.mkdirSync(d, { recursive: true })
  process.env.HOME = storage
  process.env.FAVELA_STORE_ROOT = dirs.favela
  process.env.ATPROTO_OVERLAY_ROOT = dirs.overlay
  process.env.PEER_CONFIG = path.join(dirs.hpp, 'config.json')
  // A phone is storage-constrained and killed constantly; bound the inbound lens by default.
  process.env.FAVELA_RETENTION_BUDGET = process.env.FAVELA_RETENTION_BUDGET || String(64 * 1024 * 1024)
  // ⛔ ANDROID HAS NO /etc/resolv.conf. favela-web finds no nameserver there and turns DNS TXT handle
  // verification OFF — which on a handset means every custom-domain handle renders handle.invalid,
  // measured 2026-08-24. netd owns resolution on Android and `getprop net.dns1` has been empty since
  // Android 8, so the only source is ConnectivityManager, which only the native side can ask. It does,
  // and passes the answer through shell.json. This is the OS's own resolver for the active network —
  // not a third-party one, which favela-web deliberately refuses to default to.
  if (shell.dns.length) process.env.FAVELA_NAMESERVERS = shell.dns.join(',')
  // Where the settings page reads the update state from. Set unconditionally so the file's ABSENCE (a
  // node that never wrote one) and an `ota:false` inside it are distinguishable.
  process.env.FAVELA_SHELL_STATE = path.join(storage, STATE_FILE)
}

// Env-overridable so the suite can bind an ephemeral port. Hardcoding it meant test/ipc.test.mjs —
// which boots this file for real — died with EADDRINUSE whenever a favela-web was already running on
// this machine, i.e. on any developer box that had actually deployed one. The phone always gets 4041.
const FAVELA_PORT = Number(process.env.FAVELA_PORT) || 4041
// No `appview` here any more — favela-web owns the one index on this node. See the note where the
// worklet's second one used to be built.
const state = { hpp: null, ready: false, favelaUrl: null, favelaSession: null }
// The OTA runtime handle and the last time a check completed. Module-scoped because the IPC surface
// needs both long after boot() has returned.
let ota = null
let _lastCheck = null

// BOOT TIMING. "The app takes a very long time to start" has been a standing complaint with no number
// attached, and every guess about the cause (bundle size? swarm join? replication?) is unfalsifiable
// without one. Each stage logs its own duration and the cumulative total, so the next boot on a real
// handset says where the time actually goes instead of inviting another guess.
//
// Deliberately measured with Date.now() deltas around the stages that ALREADY log — no new checkpoints
// invented, so the timings line up with the existing narrative in the log.
let _bootT0 = 0
let _stageT = 0
function stage (name, extra = {}) {
  const now = Date.now()
  const ms = _stageT ? now - _stageT : 0
  _stageT = now
  log('boot stage: ' + name, { ms, totalMs: now - _bootT0, ...extra })
}

async function boot () {
  _bootT0 = _stageT = Date.now()
  prepareEnv()
  log('booting', { storage })

  // ---- the node's own identity + repo. This is what makes it a FULL node rather than a reader. ----
  const cfgPath = process.env.PEER_CONFIG
  if (fs.existsSync(cfgPath)) {
    try {
      const { bootMultiDevice } = await import('hyper-proto-peer/lib/device-node.js')
      // ⛔ hpp's OWN LOADER, not JSON.parse. The config's `members` roster has three on-disk shapes —
      // [{key,role}], an array of hex strings, or a "hex,hex" comma-string — and only the first is
      // understood downstream: projectMembers reads `m.key`, so plain strings yield undefined, are
      // skipped, and the roster arrives EMPTY. loadConfig normalises all three (config.js
      // normalizeMembers), which is why every node that boots through it works and this app did not:
      // hand-parsing made it the one reader that skipped the rule. The room then refused to project,
      // logging "empty roster would wipe 3 existing member(s)" every 30s while the config listed three.
      //
      // loadConfig reads PEER_CONFIG, which is set above, and also applies the PEER_* env overrides —
      // none of which are set on a handset, so this is the same file, correctly shaped.
      // ── REPAIR BEFORE LOAD: an identity minted by 0.1.6 has no storeBackend ──────────────────
      // Those DIDs boot on the legacy inline substrate and cannot post — the appview refuses to
      // materialise their record bytes ("refusing to CREATE bytes for a roster DID"). 0.3.121 fixed the
      // mint; it does nothing for an identity that already exists, and that identity is a permanently
      // registered did:plc with a sealed recovery vault, so wiping storage to change one field is not an
      // option. lib/repair-store-backend.js decides which entries may move (minted HERE, never joined);
      // hyper-proto-peer's marker-guarded migrateInline does the actual, tested conversion at boot.
      //
      // Written back to the RAW file, not through loadConfig: loadConfig normalises and overlays env, so
      // persisting its output would write derived values back as if they were the operator's.
      try {
        const { repairStoreBackend } = await import('./repair-store-backend.js')
        const raw = JSON.parse(fs.readFileSync(cfgPath, 'utf8'))
        const { changed } = repairStoreBackend(raw)
        if (changed.length) {
          // Keep the previous file. This is the one write that touches an identity's config, and the old
          // copy is the fastest way back if the migration below turns out to be wrong for this repo.
          try { fs.copyFileSync(cfgPath, cfgPath + '.bak.' + Math.floor(Date.now() / 1000)) } catch {}
          fs.writeFileSync(cfgPath, JSON.stringify(raw, null, 2) + '\n')
          log('repaired storeBackend — these identities were minted before 0.3.121 and could not post', { dids: changed })
        }
      } catch (e) {
        // Loud, not fatal: a node that boots read-only is better than a node that does not boot.
        log('storeBackend repair skipped', { error: (e && e.message) || String(e) })
      }

      const { loadConfig } = await import('hyper-proto-peer/lib/config.js')
      const cfg = loadConfig()
      // deviceMnemonic is DEVICE-scoped: `coowner-join` mints it at config ROOT so a phone can generate
      // its key before it knows which DID it is joining, and the `dids` entry it writes carries none.
      // Not passing it is why a phone that had genuinely completed the ceremony served ZERO DIDs
      // (hyper-social #40 §3). hyper-proto-peer 0.3.110+ applies the same precedence coowner-join uses.
      state.cfgDids = cfg.dids || [] // handles live in the CONFIG, not on the booted node — keep them
      // SAY WHAT THIS DEVICE IS. The device public key is the ONE value another machine needs in order to
      // admit this phone (`coowner-invite --device <hex>` puts it in the DID's roster, which is what
      // StateBaseV3 checks before it will admit a writer). It was written nowhere: not logged, not in any
      // read RPC, and unreadable from adb on a release-signed app — so a phone that holds a DID but is
      // absent from its roster could not even NAME itself to the machine able to fix that. Whole evening,
      // 2026-08-11.
      //
      // Same mnemonic precedence coowner-join uses (per-DID key first, config root second): printing the
      // key from the wrong source would send the next person round the same loop with a hex string that
      // admits nothing. Best-effort — a phone that cannot derive this still boots and reads.
      try {
        const { deviceKeetKeyPair } = await import('atproto-identity/lib/device-chain.js')
        for (const d of (cfg.dids || [])) {
          const mn = d.deviceMnemonic || cfg.deviceMnemonic
          if (!mn) continue
          const kp = await deviceKeetKeyPair(mn)
          log('device public key for ' + d.did, { devicePublicKey: b4a.toString(kp.publicKey, 'hex') })
        }
      } catch (e) { log('could not derive the device public key', { error: (e && e.message) || String(e) }) }
      state.hpp = await bootMultiDevice({ storage: dirs.hpp, dids: cfg.dids || [], deviceMnemonic: cfg.deviceMnemonic || null })
      // (A roster "repair" lived here briefly — it read the config's members, found them non-empty, and
      // correctly did nothing, because the empty roster was never the config's: it was the SHAPE being
      // dropped on the way in, which loadConfig above now prevents. Removed rather than left dormant.)
      // ⛔ REPORT WHAT BOOTED, NOT WHAT WAS CONFIGURED. This line used to print the CONFIG's DID count,
      // so it said "signing enabled {dids:1}" while zero nodes had come up — the compose button renders
      // on `signing`, so the app looked paired and an hour went into diagnosing an empty appview when
      // there was no node at all. A count that cannot express the failure is worse than no line.
      const up = (state.hpp && state.hpp.nodes.length) || 0
      const configured = (cfg.dids || []).length
      if (up === 0 && configured > 0) log('hpp booted NO DIDs — read-only despite ' + configured + ' configured', { dids: 0, configured })
      else log('hpp up — signing enabled', { dids: up, configured })
      stage('hpp up')
    } catch (e) {
      // A node that cannot sign still reads; a node that cannot boot is useless. Degrade, loudly.
      try { console.error('[favela] hpp boot FAILED — read-only:', (e && e.stack) || String(e)) } catch {}
      log('hpp boot FAILED — read-only', { error: (e && e.message) || String(e) })
    }
  } else {
    // Deliberately NOT minting a DID here, and that has not changed now that `mint` exists — it is a
    // REQUEST handler, driven by someone tapping through a screen that says what it costs. Joining an
    // existing identity and creating a new one are both user decisions with real consequences
    // (spec/architecture.md §6.3), and a boot path must not choose silently between them.
    //
    // What HAS changed is that both are now reachable from the device: the intro modal offers pairing
    // and creation, and either can be declined (hyper-social #54 §8).
    log('no identity yet — read-only until paired or created (see spec §6.3)')
  }

  // ---- there is ONE index on this phone, and favela-web owns it ----
  //
  // ⛔ WHAT USED TO BE HERE, AND WHY IT WAS WRONG. The worklet built its OWN `Appview` on its OWN
  // Corestore (<storage>/favela/index) and fed it by folding hpp's records straight off local disk
  // (`indexPeer({_noRepo:true})`) on every StateBase advance. The premise was that a co-owner does not
  // need favela-web's ingest loop because the records are already here. Both halves of that failed:
  //
  //   1. NOBODY READ IT. Every screen reads favela-web's index (see the compose handler's note — this
  //      file already recorded the same discovery once, for optimistic writes). So the fold logged a
  //      healthy "indexed … statebase-update" on every advance while updating an index with no readers.
  //   2. IT SKIPPED THE VERIFICATION. atproto's sync spec is explicit that "receiving services are
  //      responsible for validating message structure and verifying authenticity" — verify the commit
  //      signature against current identity data, check the message against the signed commit in the
  //      blocks CAR. Reading records off disk does none of that. Defensible for a DID we sign for;
  //      wrong for anyone else, and this path made no distinction.
  //
  // It also opened a SECOND OverlayRepoStore over hpp's private record directory, in the same process
  // where favela-web already has one. Each instance keeps its own in-memory oid→disk map, rebuilt only
  // from its own ready() seed (atproto-store invariant #5) — the shape behind the 75-hour wj62
  // byte-resolution outage. One process, one reader.
  //
  // favela-web already implements exactly the split this needs (bin/favela-web.js:577-616): a DID it
  // co-hosts baselines from the shared store and tails from the current end — no refetch of what is on
  // disk — and everyone else backfills from a VERIFIED firehose front, failover-aware, applying each
  // #commit incrementally instead of re-folding every record. It just needed to be told who to watch,
  // which is what FAVELA_ROSTER below does.

  // ── PORT, NOT REIMPLEMENT ────────────────────────────────────────────────────────────────────────
  // favela-web is a bare app (runtime "bare", bare-http1) and it holds the appview and every social
  // query; hpp holds identity/repo/blobs and exposes no timeline, thread, profile or search at all. So
  // the client logic has to run HERE, and hand-writing a second, thinner set of queries beside it — one
  // bespoke IPC verb per feature — is what produced a crippled cousin built from the same parts.
  //
  // Bring up the REAL favela-web in-process, bound to loopback, and let the UI call its routes. Its own
  // store root, deliberately: it constructs its own Corestore, and pointing it at the one our appview
  // already holds would collide on the lock.
  //
  // Non-fatal: if it fails the app still runs on the existing surface, and the failure is REPORTED
  // rather than leaving the UI to guess why every screen is empty.
  try {
    process.env.FAVELA_PORT = String(FAVELA_PORT)
    process.env.FAVELA_HOST = '127.0.0.1'
    process.env.FAVELA_STORE_ROOT = path.join(dirs.root, 'favela-web')
    process.env.FAVELA_SOCK = path.join(dirs.root, 'favela-web', 'svc.sock')
    // THE WRITE PATH. favela-web refuses writes unless it can NAME the hpp it writes to, and it was
    // never told — so the embedded server logged "writes are DISABLED" and every compose/like/follow
    // through it failed, while reads worked fine and hid it. The hpp is in THIS process with its control
    // socket already open, so name that: local IPC, no DHT, and the DID key never leaves the handset
    // (which is why FAVELA_CONTROL_KEY, the REMOTE-hpp transport, must stay unset here).
    //
    // The path comes from hpp itself (bootSwarmDevice's `uds`) rather than being rebuilt from its private
    // <storage>/dids/<roomId>/ layout — see the note on that field in device-node.js.
    const ctlSock = state.hpp && state.hpp.nodes && state.hpp.nodes[0] && state.hpp.nodes[0].uds
    if (ctlSock) process.env.FAVELA_HPP_SOCK = ctlSock
    else log('hpp exposed no control socket — favela-web will refuse writes (reads unaffected)')
    // THE READ PATH, and it was never told either. favela-web SUBSCRIBES to its roster: per DID it
    // resolves a verifyKey, joins the topic, and tails the freshest verified co-owner's firehose,
    // applying each #commit incrementally (bin/favela-web.js:565-687). It reads FAVELA_ROSTER at module
    // top level, so this must be set BEFORE the import below — and it never was. The phone therefore
    // booted with `joined 0 DID topic(s)` and an index that could only contain what was already in it:
    // records authored on another co-owner of our OWN DID reached the overlay store (pointers converged,
    // bytes fetched) and never reached the index every screen reads. Measured 2026-08-18 — three posts,
    // 404 on the handset two and a half hours and two boots later, with nothing in any log to say so.
    //
    // Hosted DIDs are in the roster because we INDEX them, not because we sign for them — the signing set
    // is the one control socket above. addPeer's coHosted branch baselines a hosted DID from the shared
    // store and tails from the current end, so this costs no refetch of what is already on disk.
    const roster = rosterEnv({ hosted: hostedDids(), tracked: readTracked() })
    if (roster) process.env.FAVELA_ROSTER = roster
    log('favela-web roster', { dids: roster ? roster.split(',').length : 0 })
    stage('favela-web starting')
    fs.mkdirSync(process.env.FAVELA_STORE_ROOT, { recursive: true })
    await import('favela-web/bin/favela-web.js')
    state.favelaUrl = 'http://127.0.0.1:' + FAVELA_PORT
    // Prove it SERVES, do not just assume the import worked: fetch its own status over loopback.
    try {
      const fetchImpl = (await import('bare-fetch')).default
      const res = await fetchImpl(state.favelaUrl + '/status')
      log('favela-web in-process', { url: state.favelaUrl, status: res.status })
      stage('favela-web serving')

      // SIGN IN to our own favela-web. Without this every UI fetch is ANONYMOUS: viewerOf(req) returns
      // null, so liked/reposted state and per-viewer mutes silently vanish from every row and every
      // write route 401s. The failure mode is invisible — posts just render un-liked — which is exactly
      // the kind of quiet degradation this port exists to remove, so it is logged either way.
      //
      // Non-fatal: a phone that cannot sign in still reads (anonymously). Reporting beats guessing.
      await signInToFavela()
      stage('signed in')
    } catch (e) { log('favela-web started but did not answer /status', { error: e.message }) }
  } catch (e) {
    state.favelaUrl = null
    log('favela-web could NOT start in-process — UI stays on the legacy surface', { error: e.message })
  }

  // Re-subscribe to what the user chose, now that favela-web is up to receive it.
  //
  // ⛔ ORDER IS THE WHOLE POINT. This used to run BEFORE favela-web started, because it fed the worklet's
  // own index and had nothing to wait for. It now goes through favela-web, so it must come after — and
  // after sign-in, because /api/track requires a viewer.
  //
  // FAVELA_ROSTER already carried the tracked DIDs into favela-web's boot, so this is not how they get
  // subscribed; it is how we find out whether each one is REACHABLE and say so. Both loops are
  // non-blocking: a community nobody is serving right now must not hold up the app.
  if (state.favelaUrl) {
    handlers.syncFollows({}).then(
      (r) => { if (r && r.queued) log('syncing ' + r.queued + ' followed account(s)', { following: r.following }) },
      (e) => log('could not read follows yet', { error: (e && e.message) || String(e) })
    )
    for (const did of readTracked()) {
      handlers.viewDid({ did, track: false }).then(
        (r) => log('viewing ' + did.slice(0, 20) + '…', { rev: r.rev }),
        (e) => log('cannot view ' + did.slice(0, 20) + '… yet', { error: e.message })
      )
    }
  }

  state.ready = true
  send({ t: 'ready' })

  // ⛔ BEFORE THE OTA ATTEMPT, NOT AFTER IT. The settings section is gated on this file existing, and it
  // carries the RESTART button — which is also the fix for a stale session and for a node that has
  // wedged. Writing it only on a successful startOta would withdraw the recovery control from exactly
  // the builds that most need it (pgh-runtime is deferred in the pack and may not be there at all).
  writeUpdateState()

  // OTA for this bundle. Deferred in the pack (--defer pgh-runtime) and dynamically imported, so a
  // build without it still runs: an update path that can break the node is worse than no update path.
  //
  // ⛔ THE HANDLE IS KEPT NOW. It used to be dropped on the floor, which is why there was no way to ask
  // for a check: pgh-runtime's `checkNow()` is public and was simply unreachable from here.
  //
  // And `currentTreeHash` is finally passed. Without it pgh-runtime's "nothing to do if we already run
  // this tree" test can never fire, so every boot logged `downloading … / staged … — active on next
  // start` naming the bundle it was already running. No bytes moved (installTree short-circuits on
  // hasTree), but that log is what a whole evening's wrong conclusion was read off.
  try {
    const { startOta } = await import('./ota.js')
    ota = await startOta({ storage: dirs.root, say: (m) => log(m), currentTreeHash: shell.bundle })
    writeUpdateState()
  } catch (e) {
    log('ota unavailable (non-fatal)', { error: (e && e.message) || String(e) })
  }
}

// The settings page's three fields, on disk where favela-web can render them SERVER-side. Kept as a file
// rather than an IPC reply because the page is HTML from favela-web, not React Native — a reply channel
// would mean a second source of truth for the same three fields.
//
// Never throws: this is a status file. A node that cannot write it still runs, and the page then shows
// what it last knew.
function writeUpdateState (checkedAt = _lastCheck) {
  try {
    let staged = null
    try { staged = (JSON.parse(fs.readFileSync(path.join(storage, 'bundles', 'current.json'), 'utf8')) || {}).treeHash } catch {}
    fs.writeFileSync(process.env.FAVELA_SHELL_STATE, JSON.stringify(shellState({ shell, staged, checkedAt })))
  } catch { /* status only */ }
}

// ---- the IPC surface (spec §3) ---------------------------------------------------------------------
// ── talking to our own favela-web ─────────────────────────────────────────────────────────────────
//
// Same client the screens use (lib/favela-api.js), for the same reason its header gives: the moment a
// second caller builds its own request, session handling has two definitions and the one that forgets
// the cookie degrades SILENTLY — favela-web answers 200 with viewerDid null.
//
// ⛔ THIS REPLACED A SECOND P2P STACK. Viewing a foreign DID used to construct favela-web's `P2PSource`
// HERE, in the worklet: its own storage, its own Hyperswarm, its own topic joins — a third subscriber
// beside favela-web's swarm and hpp's, in one process, doing what favela-web's addPeer already does with
// failover-aware front selection and an incremental #commit tail. `/api/track` is that same work, done
// once, by the component that owns the index.
let _api = null
async function api () {
  if (!state.favelaUrl) throw new Error('favela-web is not up on this node')
  const fetchImpl = (await import('bare-fetch')).default
  // Rebuilt when the session changes: the token is captured at construction, and a client still holding
  // a pre-sign-in null would read anonymously forever.
  if (!_api || _api.session !== state.favelaSession) {
    const { FavelaApi } = await import('./favela-api.js')
    _api = new FavelaApi({ baseUrl: state.favelaUrl, session: state.favelaSession, fetchImpl })
  }
  return _api
}

const TRACKED = () => path.join(dirs.root, 'tracked-dids.json')
function readTracked () { try { return JSON.parse(fs.readFileSync(TRACKED(), 'utf8')) } catch { return [] } }
// EVERY hosted DID, not nodes[0]. A handset can house two accounts — reads are already multi-DID (one
// index, DID-keyed, `viewerDid` per query), so half-subscribing the second one would show up as a
// timeline quietly missing a person rather than as an error. (Writes are still single-DID: one control
// socket, see favela-web/lib/writer.js:283. Roster membership carries no authority.)
function hostedDids () { return ((state.hpp && state.hpp.nodes) || []).map((n) => n && n.did).filter(Boolean) }
function writeTracked (list) { try { fs.writeFileSync(TRACKED(), JSON.stringify(list, null, 2) + '\n') } catch {} }

// SIGN IN to our own favela-web. Without this every UI fetch is ANONYMOUS: viewerOf(req) returns null,
// so liked/reposted state and per-viewer mutes silently vanish from every row and every write route 401s.
// The failure mode is invisible — posts just render un-liked — so it is logged either way.
//
// ⛔ CALLABLE AGAIN, not just at boot. favela-web's session store is an in-memory Map, so it is emptied
// by every restart of that process while this side still holds the old token. The WebView then hits
// /auth/handoff, gets "unknown or expired token", and RENDERS THE REFUSAL — a recoverable condition
// presented as a dead end, with force-stopping the app as the only way out. Nothing about the
// credentials changed: this side can mint a fresh session whenever asked, and now does.
//
// Non-fatal by design: a phone that cannot sign in still reads, anonymously. Reporting beats guessing.
async function signInToFavela () {
  const entry = state.hpp && state.hpp.nodes && state.hpp.nodes[0]
  if (!entry) {
    log('no DID yet — favela-web stays anonymous until this device is paired')
    return { ok: false, reason: 'no DID' }
  }
  try {
    const fetchImpl = (await import('bare-fetch')).default
    const { loadOrCreateSubKey, establishSession, sessionNodeOf } = await import('./session.js')
    // hpp hands back a WRAPPER, not the SwarmDevice — see sessionNodeOf. Passing `entry` straight
    // through is what made every boot sign-in fail with "an hpp node with delegate() required".
    const node = sessionNodeOf(entry)
    if (!node) throw new Error('hpp entry exposes no delegate() — cannot sign in')
    const key = loadOrCreateSubKey(path.join(dirs.root, 'ui-subkey.json'), fs, path.dirname)
    if (key.created) log('minted a UI sub-key for this device (delegated by our own DID)')
    const s = await establishSession({
      favelaUrl: state.favelaUrl, node, privHex: key.privHex, pubHex: key.pubHex, fetchImpl
    })
    state.favelaSession = s.token
    log('signed in to favela-web', { did: s.did.slice(0, 20) + '…', handle: s.handle })
    return { ok: true, token: s.token }
  } catch (e) {
    state.favelaSession = null
    log('favela-web sign-in FAILED — the UI will read anonymously (no liked/reposted state, no writes)', { error: e.message })
    return { ok: false, reason: e.message }
  }
}

const handlers = {
  // Mint a FRESH favela-web session and hand back the token.
  //
  // Exists because favela-web's session store is in memory: when that process restarts, this side's
  // token is instantly unknown and /auth/handoff answers 403. The WebView used to render that refusal
  // and stop, which reads as "signed out" and is only escapable by force-stopping the app. It is a
  // recoverable condition — nothing about the credentials changed — so the UI now asks for a new
  // session instead of dead-ending. See App.jsx's onHttpError.
  async resession () {
    const r = await signInToFavela()
    return { ok: !!r.ok, favelaSession: state.favelaSession, favelaUrl: state.favelaUrl, reason: r.reason || null }
  },

  // ── app updates ──────────────────────────────────────────────────────────────────────────────────
  // What is running, what is staged, when we last looked. The same three fields the settings page reads
  // from disk; this verb exists for the shell and the suite, which have no HTML to read.
  async updateStatus () {
    let staged = null
    try { staged = (JSON.parse(fs.readFileSync(path.join(storage, 'bundles', 'current.json'), 'utf8')) || {}).treeHash } catch {}
    return { ...shellState({ shell, staged, checkedAt: _lastCheck }), available: !!ota }
  },

  // Ask NOW instead of waiting up to six hours.
  //
  // ⛔ IT STILL DOES NOT APPLY ANYTHING. Staging and applying are separate on purpose (applying to a
  // running node means swapping code under itself), so this downloads and stages; the restart that runs
  // it belongs to the shell, which owns the runtime. Saying "updated" here would be the same false
  // report the OTA log used to make.
  async checkForUpdate () {
    if (!ota || typeof ota.checkNow !== 'function') return { ok: false, reason: 'ota unavailable in this build' }
    try {
      await ota.checkNow()
      _lastCheck = new Date().toISOString()
      writeUpdateState()
      return { ok: true, ...(await handlers.updateStatus()) }
    } catch (e) {
      // A failed check is a network fact, not a broken node — report it and leave the state alone.
      return { ok: false, reason: (e && e.message) || String(e) }
    }
  },
  async status () {
    // favelaSession is the session COOKIE VALUE, handed to the UI so its fetches can carry
    // `Cookie: favela_session=…`. HttpOnly is a browser protection against document-script access; there
    // is no document here, and the UI shares this process's trust boundary — the worklet already holds
    // the DID signing key, which is strictly more sensitive than a 30-day session token.
    //
    // Null means the UI is anonymous, and it must SAY so rather than render as if signed in: no
    // liked/reposted state, no per-viewer mutes, and every write will 401.
    return {
      ready: state.ready,
      signing: !!state.hpp,
      storage: dirs.root,
      favelaUrl: state.favelaUrl,
      favelaSession: state.favelaSession
    }
  },
  // HOME IS WHO YOU FOLLOW, not what happens to be indexed. Unscoped, getTimeline returns everything in
  // the local index — and this node indexes only the DIDs it hosts, so "the timeline" was your own posts
  // read back to you. Two separate causes, and scoping alone fixes neither: there also has to BE content
  // from other people, which is what syncFollows below is for.
  //
  //   scope 'following' (default) — you + everyone you follow + anything you track (communities)
  //   scope 'all'                 — every author in the local index, unfiltered (what it used to do)
  //   scope '<did>'               — one account/community

  // Pull the repos of accounts you follow but do not host, so the scoped timeline has something in it.
  // Bounded and non-blocking on purpose: this is a phone, each one is a topic join plus a verify, and a
  // home feed must not wait on the slowest peer. Already-tracked DIDs are skipped (viewDid tracks them).
  async syncFollows ({ viewer = null, max = 10 } = {}) {
    const me = viewerDid(viewer)
    if (!me) return { synced: 0 }
    const hosted = new Set(((state.hpp && state.hpp.nodes) || []).map((n) => n.did))
    const tracked = new Set(readTracked())
    // The graph lives in favela-web's index, which is now the only one. `.catch(() => [])` is kept
    // deliberately: a favela-web that is not up yet must degrade to "nothing to sync", not throw on boot.
    const following = (await api().then((a) => a.follows({ did: me })).then((r) => (r && r.dids) || []).catch(() => [])) || []
    const todo = following.filter((d) => !hosted.has(d) && !tracked.has(d)).slice(0, max)
    for (const did of todo) {
      handlers.viewDid({ did }).then(
        (r) => log('followed ' + did.slice(0, 20) + '… indexed', { rev: r.rev }),
        (e) => log('cannot reach ' + did.slice(0, 20) + '… yet', { error: e.message })
      )
    }
    return { queued: todo.length, following: following.length }
  },
  // The pairing ceremony runs IN THE WORKLET, never in the UI. lib/adopt.js touches keys, proofs and the
  // blind-pairing tunnel; a React Native component must not. The screen collects an invite and shows
  // progress — that is the whole of its involvement.
  async adopt ({ inviteHex, did = null } = {}) {
    // ONE STRING. The device mints its key from a mnemonic (which needs no identity), sends the public
    // half up the tunnel, and learns the DID from the bundle that comes back. `did` is accepted only as
    // an ASSERTION of which identity you expect — omitted, it is learned. Proven in
    // hyper-proto-peer/test/coowner-join-didless + this repo's adopt e2e.
    if (!inviteHex) throw new Error('adopt requires { inviteHex }')
    const { joinAdoptInvite } = await import('./adopt.js')
    const r = await joinAdoptInvite({
      did,
      inviteHex,
      configFile: process.env.PEER_CONFIG,
      onStep: (msg, extra) => log('adopt: ' + msg, extra)
    })
    // Deliberately NOT rebooting hpp here. The config is written; the node picks the DID up on next
    // start. A pairing call that also restarts the node is two operations, and the failure modes of the
    // second would surface as failures of the first.
    return { paired: true, devicePublicKey: r.devicePublicKey, entry: r.entry, restartRequired: true }
  },

  // CREATING an identity — the other half of the intro modal. Pairing copies an identity that already
  // exists; a phone that has never been paired has nothing to copy, so without this a fresh device could
  // never become a full node at all. That step used to exist only as bin/hpp-onboard.js on a server with
  // a hyperident and a shell, which a handset has neither of (hyper-social #54 §8).
  //
  // Runs IN THE WORKLET for the same reason adopt does: it touches keys and the recovery secret, and a
  // React Native component must not. The screen collects a passphrase, shows the words once, and asks
  // for confirmation — that is the whole of its involvement.
  async mint ({ passphrase = null, submit = true } = {}) {
    // ⛔ REFUSE IF THIS DEVICE ALREADY SIGNS. mintIdentity guards the config too, but this catches the
    // case earlier and with a message about what the user can see: a booted node. Minting is cheap to
    // repeat and impossible to undo, so both guards stay.
    if (state.hpp && state.hpp.nodes && state.hpp.nodes.length) {
      throw new Error('this device already has an identity — refusing to mint another')
    }
    // The passphrase is the ONLY thing protecting the recovery vault. The blob is designed to be
    // replicated, so it will land on disks we do not control; it is safe there only because it is
    // useless without something in a person's head (#54 §6). A short one makes the Argon2id cost the
    // sole defence, which is not what it is for.
    const pass = typeof passphrase === 'string' ? passphrase : ''
    if (pass.length < 8) throw new Error('mint requires a passphrase of at least 8 characters — it is the only thing protecting your recovery vault')

    const { mintIdentity, submitMintedGenesis } = await import('./mint.js')
    const r = await mintIdentity({
      configFile: process.env.PEER_CONFIG,
      onStep: (msg, extra) => log('mint: ' + msg, extra)
    })

    // ── SEAL BEFORE ANYTHING CAN FAIL ────────────────────────────────────────────────────────────
    // The root mnemonic exists in memory exactly once, here. Sealing it comes before the network call
    // so that a directory that is unreachable cannot cost the user their recovery secret — the identity
    // is already usable P2P at this point, and submission is retryable.
    let sealed = false
    let sealError = null
    try {
      const { sealVault } = await import('atproto-identity/lib/vault.js')
      const envelope = sealVault({ secret: r.rootMnemonic, passphrase: pass, did: r.did })
      const dir = path.join(dirs.hpp, 'recovery')
      fs.mkdirSync(dir, { recursive: true })
      // Named by the DID's own suffix: one device may later hold several identities, and a single
      // vault.json would silently mean "the last one minted".
      fs.writeFileSync(path.join(dir, r.did.split(':').pop() + '.vault.json'), JSON.stringify(envelope, null, 2) + '\n')
      sealed = true
      log('mint: recovery vault sealed', { did: r.did })
    } catch (e) {
      // Loud, and NOT fatal: the identity exists and the words are about to be shown. A user who writes
      // them down has lost nothing. Swallowing this would be the real failure.
      sealError = (e && e.message) || String(e)
      log('mint: could not seal the recovery vault — WRITE THE WORDS DOWN', { error: sealError })
    }

    // ── THE IRREVERSIBLE PART, LAST AND ON ITS OWN ───────────────────────────────────────────────
    // A PLC genesis is a permanent, public append to a global log. It is last so that everything
    // recoverable has already succeeded, and its failure is REPORTED rather than thrown: the identity
    // is real and works P2P without it, and the op re-derives from the mnemonic for a later retry.
    let submitted = false
    let submitError = null
    if (submit) {
      try {
        await submitMintedGenesis({ did: r.did, signedOp: r.signedOp, onStep: (msg) => log('mint: ' + msg) })
        submitted = true
      } catch (e) {
        submitError = (e && e.message) || String(e)
        log('mint: genesis NOT registered — the identity still works P2P', { error: submitError })
      }
    }

    // Deliberately NOT rebooting hpp here, for the reason adopt gives: two operations in one call means
    // the second one's failures surface as the first one's.
    return {
      did: r.did,
      // SHOWN ONCE. The only copy the user will ever see; the vault holds the other.
      mnemonic: r.rootMnemonic,
      devicePublicKey: r.devicePublicKey,
      sealed,
      sealError,
      submitted,
      submitError,
      restartRequired: true
    }
  },

  // ACCEPTING A BRIDGE'S INVITE — the other end of the split mint created.
  //
  // mint produces a P2P-only identity: no handle, no PDS, nobody's permission required. Being FRONTED by
  // a membrane is what an invite grants, and accepting one is a PLC update adding a handle and a service
  // endpoint. It must be signed by a current rotation key — the root recovery key — which mint sealed
  // into the vault under a passphrase for exactly this moment.
  //
  // ⛔ THE PASSPHRASE IS ALL THAT CROSSES THE BRIDGE. The page collects it; this opens the vault, derives
  // the key, signs and submits. The mnemonic never reaches React Native, the WebView, or a log line.
  //
  // ⛔ PREVIEWS UNLESS TOLD OTHERWISE. A PLC append is permanent and public. The caller asks twice: once
  // to see the exact change, once to make it. A confirm screen is only honest if what it describes is
  // what will happen, so both calls go through the same code path.
  async hostingAttach ({ handle = null, pdsUrl = null, passphrase = null, submit = false, plcUrl = null } = {}) {
    const did = (state.cfgDids && state.cfgDids[0] && state.cfgDids[0].did) || null
    if (!did) throw new Error('this device has no identity to host — pair or create one first')
    if (!handle) throw new Error('hosting requires the handle the invite grants')
    if (!pdsUrl) throw new Error('hosting requires the service endpoint the invite grants')
    if (!passphrase) throw new Error('hosting requires your vault passphrase — it is what unlocks the recovery key')

    const { vaultPathFor, resolveSigner, hostingAttach: run } = await import('./hosting.js')
    const vaultPath = vaultPathFor(dirs.hpp, did)
    let envelope = null
    try { envelope = JSON.parse(fs.readFileSync(vaultPath, 'utf8')) } catch {
      // A phone that PAIRED rather than minted has no vault: the recovery key stayed with whoever created
      // the identity. Saying so is the whole answer — there is no fallback that would be correct.
      throw new Error('no recovery vault on this device — this identity was not created here, so its recovery key is on the device that made it')
    }

    // Fails identically for a wrong passphrase, a tampered blob and the wrong identity, deliberately.
    const signer = resolveSigner({ vault: envelope, passphrase, did })
    log('hosting: vault unlocked', { did, submit })

    const r = await run({ did, handle, pdsUrl, signer, plcUrl, submit })
    if (r.submitted) log('hosting: PLC updated — this identity now names a handle and a PDS', { did, handle, pdsUrl })
    return {
      did,
      submitted: r.submitted,
      preview: r.preview,
      // ⛔ SAY WHAT IS STILL MISSING. Naming a PDS does not make the bridge serve you: fronting is the
      // operator's half and cannot be done from here. A screen that reported success and left the user
      // wondering why nothing federated would be the same lie as "installed" meaning "running".
      operatorStepRemaining: r.submitted
        ? 'the bridge operator must add ' + did + ' to frontedDids before it will front this identity'
        : null
    }
  },

  // View a DID this node does not host: join its topic over P2P, verify its head, index it into the
  // SAME appview the hosted DIDs use. After this it is an ordinary account everywhere downstream —
  // author feed, thread, search — with no special case. Tracked so it survives a restart.
  async viewDid ({ did, track = true, timeout = 45000 } = {}) {
    if (!did || !did.startsWith('did:')) throw new Error('viewDid requires { did }')
    // ONE ROUTE FOR BOTH CASES, because favela-web already distinguishes them better than this did.
    // /api/track is HOSTED-FIRST: a DID hpp holds is baselined from the shared store on disk rather than
    // chased over the network — which is the same correction made here once before, when tapping our own
    // identity reported "nobody is serving it right now" while its posts were on screen. A DID we do not
    // hold gets a verified front, and the route waits for one so an unreachable DID SAYS so.
    const a = await api()
    const r = await a.track({ did, wait: timeout })
    if (track) {
      const list = readTracked()
      if (!list.includes(did)) { list.push(did); writeTracked(list) }
    }
    // `rev` is the front's head where there is one; a hosted DID has no front and reports null, exactly
    // as the local branch did before.
    return { did, indexed: r && r.indexed != null ? r.indexed : null, rev: (r && r.rev) || null, local: !!(r && r.hosted) }
  },

  async trackedDids () {
    const tracked = readTracked()
    // Hydrate what we know, so the caller renders names rather than DIDs. A tracked DID with no profile
    // yet is normal (indexed but no app.bsky.actor.profile record) and must not read as an error.
    const out = []
    for (const did of tracked) {
      // GET /api/profile resolves the handle too, raced against a deadline — so a row is a render rather
      // than a DID the UI then has to look up. `held:false` (we hold no profile record) reads the same as
      // a failed request here, which is correct: both mean "no name to show", and neither is an error.
      let p = null
      try { p = await (await api()).profile({ did }) } catch {}
      out.push({ did, handle: (p && p.handle) || null, displayName: (p && p.displayName) || null, avatar: (p && p.avatar) || null })
    }
    return { dids: out }
  },

  async untrackDid ({ did } = {}) {
    writeTracked(readTracked().filter((d) => d !== did))
    return { did, tracked: false }
  },

  // People, hydrated. `follows`/`followers` returned bare DID strings, which a UI can only render as
  // hex — the reason there is no way to browse anyone. Same queries, with the profile attached.

  // ── identities ────────────────────────────────────────────────────────────────────────────────────
  // Every DID this node hosts, not just the first. The daemon has always been multi-DID — a user's own
  // identity plus each co-owned community (loser-club, ashatron's) — but the UI resolved everything
  // through nodes[0], so the others were unreachable: no feed, no switcher, and `thread`/`search`/`blob`
  // silently meant "DID #0". A client that hosts four identities and can address one is not multi-DID.
  //
  // `handle` comes from the CONFIG, not the node: bootSwarmDevice does not retain it. `signing` reports
  // whether this node can actually author for that DID, which is the difference between an identity you
  // can post as and one you can only read — and the UI must not offer a compose box for the latter.
  async hostedDids () {
    const nodes = (state.hpp && state.hpp.nodes) || []
    const byDid = new Map((state.cfgDids || []).map((d) => [d.did, d]))
    return {
      primary: nodes.length ? nodes[0].did : null,
      dids: nodes.map((n, i) => {
        const cfg = byDid.get(n.did) || {}
        return {
          did: n.did,
          handle: cfg.handle || null,
          primary: i === 0,
          // writable = the StateBase admitted us; without it this identity reads but cannot author.
          signing: !!(n.sb && n.sb.base && n.sb.base.writable)
        }
      })
    }
  },

  // ── media ─────────────────────────────────────────────────────────────────────────────────────────
  // Blob bytes for the UI. The UI cannot reach the store itself — it lives across the worklet boundary,
  // and there is no local HTTP origin on a phone the way favela-web has one — so bytes cross the same
  // line-delimited JSON wire as everything else, base64'd, and the component renders a data: URI.
  //
  // Resolution order matches favela-web's getBlob exactly (lib/blob-serve.js + lib/render.js are
  // imported, not re-implemented, so a ref form that works on the web works here):
  //   1. the SHARED content-addressed overlay file — <overlay>/<roomKey16(did)>/blobs/<cid>. This is the
  //      one copy hpp already wrote, and it covers ANY did whose bytes this node holds, not just ours.
  //   2. this node's own blob store — pointers + the legacy dual-read, for our own pre-migration blobs.
  //
  // `ref` is passed through verbatim from the record so the tolerant parsing ({$link} / {'/'} / CID /
  // string) has ONE definition, in favela-web, rather than a second one in a React component.
  //
  // SIZE-CAPPED. A base64 payload rides in a single JSON line, and a phone should not try to move a
  // video that way — the cap fails loudly with the real size instead of stalling the channel. Video
  // needs a streaming transport (and range support) and is deliberately not solved here.
  async blob ({ did = null, ref = null, cid = null, maxBytes = 8 * 1024 * 1024 } = {}) {
    const { blobCid } = await import('favela-web/lib/render.js')
    const { blobPath, sniffMime, isSafeCid } = await import('favela-web/lib/blob-serve.js')
    const id = cid || blobCid(ref)
    if (!id || !isSafeCid(id)) throw new Error('blob requires { cid } or a record { ref }')
    const owner = did || viewerDid()
    if (!owner) throw new Error('blob requires { did } (no local identity to default to)')

    let bytes = null
    try { bytes = fs.readFileSync(blobPath(dirs.overlay, owner, id)) } catch { /* fall through to the store */ }
    if (!bytes) {
      const node = state.hpp && state.hpp.nodes && state.hpp.nodes[0]
      const store = node && node.blobs
      if (store) { try { const got = await store.get(String(id)); if (got && got.bytes) bytes = got.bytes } catch { /* not ours */ } }
    }
    // A MISSING blob is a normal answer, not an error: the pointer replicates before the bytes do, and
    // some blobs are genuinely lost (the dual-read migration dropped wj62's avatar). The UI shows a
    // placeholder for `found:false` and an error only for a real failure — those must not look alike.
    if (!bytes) return { found: false, cid: id }
    if (bytes.length > maxBytes) return { found: false, cid: id, tooLarge: true, size: bytes.length }
    return { found: true, cid: id, size: bytes.length, mimeType: sniffMime(bytes), base64: b4a.toString(bytes, 'base64') }
  },

  async collections () {
    // The #33 ledger — useful on a phone for the same reason it is on a server: an unclassified lexicon
    // arriving should be visible, not silent.
    // favela-web already exposes this on its control surface (`svc.handle('collections')`) — the ledger
    // is a property of the index, and the index is favela-web's. Over its UDS rather than HTTP because
    // that is where the verb lives; a diagnostic does not deserve a new public route.
    //
    // ⚠ THE SHAPE CHANGED, and nothing consumes it: this returned `{ ledger: [...] }` from the worklet's
    // own index; it now passes favela-web's payload through — `{ ok, tracked, ignored, unknown }`, which
    // is strictly more (it says which lexicons are deliberately ignored and whether we have ever seen
    // one, not just which are unclassified). No screen reads this verb today; a future one should read
    // `unknown`.
    const { Client } = await import('hyper-svc')
    const sock = process.env.FAVELA_SOCK
    if (!sock) throw new Error('favela-web control socket unknown')
    const c = await Client.connectUds(sock)
    try { return await c.call('collections', {}) } finally { try { await c.close() } catch {} }
  },

  // ── the ported read surface ────────────────────────────────────────────────────────────────────────
  // favela-web's pages, as ops. Each is a thin wrapper on the appview the phone ALREADY runs — the index
  // and every query are shared verbatim, so a screen here answers the same question the web page does
  // from the same code. `viewerDid` is this node's own DID so viewer state (liked/reposted/muted) is
  // hydrated before anything crosses IPC, which is what keeps a row a render rather than a lookup.
  async compose ({ text, replyTo = null, quoteOf = null, lang = null, scope = 'public' } = {}) {
    const w = await writer()
    const langs = /^[a-z]{2}(-[A-Za-z0-9]{2,8})?$/.test(String(lang || '')) ? [String(lang)] : ['en']
    const r = await w.post(String(text || ''), { scope, langs, reply: replyTo, quote: quoteOf })
    const uri = 'at://' + viewerDid() + '/' + r.collection + '/' + r.rkey
    // No optimistic index write. Every screen now reads favela-web's index, so writing into the
    // worklet's own appview updated something nobody reads — a no-op that still looked like it worked.
    // favela-web picks the record up itself: it holds hpp's overlay (ATPROTO_OVERLAY_ROOT) and follows
    // the DID's firehose, and it indexes a local write promptly — observed on tabertron, where a post
    // appeared in /api/timeline immediately after the write and left it immediately on delete.
    return { ...r, uri }
  },
  async deletePost ({ rkey, collection = 'app.bsky.feed.post' } = {}) {
    if (!rkey) throw new Error('deletePost requires { rkey }')
    const w = await writer()
    await w.putRecord(collection, rkey, null, { action: 'delete' })
    // Same as compose: the optimistic delete updated an index no screen reads. favela-web drops it
    // from its own on the firehose round-trip.
    return { ok: true, rkey, collection }
  },
  // Follow is a TOGGLE and needs no strongRef — its subject is a plain DID, unlike a like or a repost
  // whose subject is a strongRef (uri AND cid) and must fail closed when the bytes are not held.
  async follow ({ did } = {}) {
    if (!did || !String(did).startsWith('did:')) throw new Error('follow requires { did }')
    const me = viewerDid()
    // ⛔ REFUSE HERE, NOT DOWNSTREAM. Every write op on a node with no identity must say the same thing —
    // "pair it" — rather than surfacing whatever the layer below happened to notice first. Delegating
    // straight to favela-web returned its 403 "this instance is read-only", which is true of favela-web
    // and useless to someone holding an unpaired phone. Same wording as writer(), deliberately.
    if (!me) throw new Error('this node has no identity yet — pair it before writing')
    if (did === me) throw new Error('cannot follow yourself')
    // ⛔ THE TOGGLE IS NOT OURS TO REIMPLEMENT. This read the existing rkey out of the worklet's index,
    // asked hpp to write, then wrote back into that same index — a second follow implementation racing
    // favela-web's, with its own idea of what "already following" means. /api/follow does all three
    // steps against the one index, and its writer.state() check refuses a write whose signed-in viewer
    // is not the DID this hpp signs for — a guard the local path never had.
    const r = await (await api()).follow({ did })
    return { following: !!(r && r.following) }
  },
  // invite — mint an adopt invite for ANOTHER device. Symmetric by design: keet's `addDevice` is
  // available to every active member and confers nothing on the adder, and coownerInvite no longer
  // claims the genesis, so a phone can pair the next device exactly as a desktop can.
  //
  // ⚠ APPROVAL IS THE BUTTON PRESS. mintAdoptInvite takes an `approve` callback because the bundle
  // carries the shared signing key and coownerInvite MUTATES the config — so it must never fire
  // speculatively. Here the user has already tapped "invite a device" behind a screen that says what it
  // grants, which is the same posture favela-web's `pair` command takes when it auto-delegates.
  async invite () {
    const me = viewerDid()
    if (!me) throw new Error('this node has no identity yet — pair it before inviting')
    const { mintAdoptInvite } = await import('./adopt.js')
    const src = await mintAdoptInvite({ did: me, approve: () => true, configFile: process.env.PEER_CONFIG })
    // The tunnel stays open for ONE pairing session. Await the peer in the background so the op can
    // return the code immediately — the UI shows progress from these log lines.
    src.waitForPeer()
      .then((r) => log(r ? 'invite: device joined' : 'invite: refused', r ? { devicePublicKey: r.devicePublicKey } : {}))
      .catch((e) => log('invite: failed', { error: (e && e.message) || String(e) }))
      .then(() => { try { src.close() } catch {} })
    return { inviteHex: src.inviteHex, did: me }
  },

  async devices () {
    const w = await writer()
    return { devices: await w.listDevices() }
  },
  async revokeDevice ({ subKey, restore = false } = {}) {
    if (!subKey) throw new Error('revokeDevice requires { subKey }')
    const w = await writer()
    await w.revokeDevice(subKey, { restore })
    return { ok: true, subKey, restored: !!restore }
  }
}

// This node's own DID — the first hosted one. Used as viewerDid for every query so viewer state is
// hydrated server-side (well, worklet-side), and as the author of every write.
// The DID a read is answered AS. Defaults to this node's own (the first hosted DID), but every read op
// accepts `viewer` so a client acting as one of the OTHER identities this node hosts — a co-owned
// community — gets ITS viewer state (liked/reposted/muted) rather than the primary's.
//
// VALIDATED against the hosted set, never trusted: an arbitrary DID from the UI would silently hydrate
// viewer state for an identity this node cannot act as, which reads as "my like vanished" rather than
// as the rejection it is.
function viewerDid (override = null) {
  if (!state.hpp || !state.hpp.nodes || !state.hpp.nodes.length) return null
  if (override) {
    const hit = state.hpp.nodes.find((n) => n.did === override)
    if (!hit) throw new Error('this node does not host ' + override)
    return hit.did
  }
  return state.hpp.nodes[0].did
}

// A TID rkey. Same generator the rest of the stack uses, imported lazily so a read-only node (no hpp)
// never pulls it in.
let _tid = null
function tid () {
  if (!_tid) throw new Error('tid unavailable — node not booted')
  return _tid()
}

// favela-web's Writer, wired to the IN-PROCESS device instead of a UDS socket. Built once, lazily: a
// node with no DID has nothing to write with, and asking for one should say so rather than crash a read.
let _writer = null
async function writer () {
  if (_writer) return _writer
  const node = state.hpp && state.hpp.nodes && state.hpp.nodes[0]
  if (!node) throw new Error('this node has no identity yet — pair it before writing')
  const { Writer } = await import('favela-web/lib/writer.js')
  if (!_tid) _tid = (await import('atproto-store/lib/tid.js')).tidNow
  _writer = new Writer({ device: node.device, blobs: node.blobs })
  return _writer
}

async function onRequest (req) {
  const { id, op, params } = req
  if (!state.ready && op !== 'status') return send({ id, error: 'not ready' })
  const fn = handlers[op]
  if (!fn) return send({ id, error: 'unknown op: ' + op })
  try {
    send({ id, result: await fn(params || {}) })
  } catch (e) {
    send({ id, error: (e && e.message) || String(e) })
  }
}

// ⛔ `IPC.on('data')`, NOT `IPC.read(cb)`. BareKit.IPC is a streamx Duplex: `read()` takes no callback
// and returns the next chunk (or null) synchronously. The previous pump passed a callback that streamx
// simply ignored, so it fired once, read nothing, and never re-armed — the worklet consumed ZERO inbound
// bytes for its whole life. It still booted and still sent its own log lines, so it looked alive while
// every request from the UI went unanswered and every screen hung after `ready`.
//
// The decoder is stateful for the same reason it is on the RN side: chunk boundaries are not character
// boundaries (lib/utf8.js).
if (IPC) {
  let buf = ''
  const decode = createUtf8Decoder()
  IPC.on('data', (data) => {
    buf += decode(data)
    let i
    while ((i = buf.indexOf('\n')) >= 0) {
      const line = buf.slice(0, i); buf = buf.slice(i + 1)
      if (!line.trim()) continue
      try { onRequest(JSON.parse(line)) } catch { send({ error: 'bad request json' }) }
    }
  })
}

boot().catch((e) => send({ t: 'fatal', error: (e && e.stack) || String(e) }))
// android-ota — keep the JS current on a phone, so the APK only has to change when native code does.
//
// THE SPLIT THIS EXISTS TO CREATE. An APK carries two very different things: ~77 MB of native libraries
// that change rarely (bare-kit + our addons), and a worklet bundle that changes constantly. Today proved
// the cost of not having this: a favela-web fix reached the handset only by rebuilding a 153 MB APK
// (150s of CI) and sideloading it, because favela-android vendors favela-web at build time.
//
// ⛔ WHAT WAS HERE BEFORE HAD NEVER RUN. pgh-runtime was `--defer`red out of the bundle and absent from
// dependencies, so `startOta`'s dynamic import always failed and this file returned null after logging
// "updates disabled". The code underneath was free to be wrong, and was: `getTree` returned
// `{entries: []}` for every hash, and pgh-runtime's installTree hashes the entries it is handed and
// rejects the tree unless they reproduce the root hash — a guard that exists so a peer cannot answer "I
// don't have it" with an empty directory. So it could not have downloaded a bundle even with the
// dependency present. It also took `versions[versions.length - 1]` as "newest", and this forge lists
// newest FIRST, so it would have pinned a phone to the oldest build on the server and called it current.
//
// ⛔ THE TWO "RELEASE" SYSTEMS ARE NOT INTERCHANGEABLE:
//   - pgh-sidecar's ReleaseRegistry: an Autobase of METADATA. Replicates P2P, never produces a file.
//   - pear-git-v3's ReleaseManager: real files on disk, served over HTTPS at
//     /git/releases/<repo>/<version>/<file>. This is the one that can hand a phone bytes.
// A phone needs BYTES, so this targets the second.
//
// ⚠ Artifacts are per-daemon. 7rnx.net/git is load-balanced and a release built on one backend is not
// automatically complete on the other (measured 2026-08-18: a 153 MB APK never reached the second
// backend while its build.log and manifest did). So `base` must point at a backend that actually holds
// the bytes, and every fetch is hash-verified rather than trusted because of where it came from.
import fs from 'bare-fs'
import path from 'bare-path'
import crypto from 'hypercore-crypto'
import { computeTreeHash, KIND_FILE } from 'hyper-overlay/tree'

const DEFAULT_BASE = 'https://7rnx.net/git'
const DEFAULT_REPO = 'favela-android'
// The publisher's release registry — the hex in every hyper-fleeky app's `pgh.upgrade`
// (hyper-proto-peer, atproto-bridge, hypernote, favela-web, pgh-sidecar all carry this exact value).
//
// ⛔ A CONSTANT, AND DELIBERATELY NOT A LIST. This is a publisher IDENTITY, not a set of hosts: the
// serving topic comes from the resolved release's own serverKey, so adding, moving or rotating a backend
// changes nothing here. A hand-maintained list of hosts would be the frontedDids anti-pattern
// (hyper-social #54 §8) on the one component that cannot be fixed remotely.
const DEFAULT_REGISTRY = '1dd36bdfa9cb7f7d84adbd07f017e7200f7f90a3a546cd0761fac2a1f8a13e86'
const DEFAULT_INTERVAL = 6 * 60 * 60 * 1000 // 6h — a phone is not a server; do not poll it awake
const BUNDLE_NAME = 'worklet.bundle'

const hashOf = (bytes) => crypto.data(Buffer.from(bytes)).toString('hex')

// The running bundle's hash, if the environment happens to say. Guarded because `process` is a shim in
// the worklet and absent everywhere else; an OTA client is not the place to discover that.
function envBundleHash () {
  try { return (typeof process !== 'undefined' && process.env) ? process.env.FAVELA_BUNDLE_HASH : null } catch { return null }
}

/**
 * The one-file tree for a bundle: what CI publishes as tree.json and what the phone verifies against.
 *
 * Deliberately built with hyper-overlay's own encoder rather than by hand — pgh-runtime verifies with
 * `computeTreeHash`, so producing the hash any other way would be a second definition of the format that
 * agrees until it doesn't.
 */
export function treeFor (bytes, name = BUNDLE_NAME) {
  const contentHash = hashOf(bytes)
  const entries = [{ kind: KIND_FILE, exec: 0, name, childHash: contentHash }]
  return { entries, treeHash: computeTreeHash(entries), contentHash, size: bytes.length }
}

/**
 * Newest release by BUILD TIME, not by position in the list.
 *
 * The old code took the last element and commented "newest last by publish order". `pgh deploy log`
 * returns newest FIRST, so that read the oldest build on the server. Ordering the caller cannot see is
 * not a contract; the timestamp is.
 */
export function pickNewest (versions) {
  const list = (Array.isArray(versions) ? versions : []).filter(Boolean)
  if (!list.length) return null
  return list.reduce((a, b) => ((Number(b.builtAt) || 0) > (Number(a.builtAt) || 0) ? b : a))
}

/**
 * A pgh-runtime fetcher over the forge's HTTPS release routes.
 *
 * Shape required by pgh-runtime: { getLatestRelease(name), getTree(hash), getContent(hash) }.
 */
export function bundleFetcher ({ base = DEFAULT_BASE, repo = DEFAULT_REPO, doFetch }) {
  // treeHash -> { version, entries }, and contentHash -> { version, name }. Populated when a tree.json is
  // read, because installTree asks for a tree and then for content BY HASH, with no version in hand.
  const trees = new Map()
  const contents = new Map()

  const releaseUrl = (version, file) => `${base}/releases/${repo}/${version}/${file}`

  async function readTree (version) {
    const res = await doFetch(releaseUrl(version, 'tree.json'))
    if (!res || res.ok === false) throw new Error(`no tree.json for ${version}`)
    const body = await res.json()
    const entries = (body && body.entries) || []
    // Trust the ENTRIES, not the advertised hash: recompute it. installTree checks this too, but a
    // fetcher that propagated a hash it never verified would hand the guard its own answer.
    const treeHash = computeTreeHash(entries)
    trees.set(treeHash, { version, entries })
    for (const e of entries) contents.set(e.childHash, { version, name: e.name })
    return { treeHash, entries }
  }

  // Named, because getTree's fallback calls back into getLatestRelease — one discovery path, not two.
  const api = {
    // ⛔ `release-index`, NOT `list-repo-releases`. The latter is behind the anonymous-RPC gate (pear-git
    // org #12: the whole /rpc/ surface was world-callable until it became opt-in), so a phone — anonymous
    // by construction — gets 403 forever. Measured on the handset: the check SUCCEEDS having found
    // nothing, prints no error, and is indistinguishable from being up to date.
    //
    // release-index is already in ANONYMOUS_METHODS, and for the same use: "Release discovery for a
    // ReleasePuller… The handler filters its response by repoAccess for anonymous callers, so a private
    // repo's versions and hashes stay hidden." A phone updating itself is a puller. Opening a second
    // method would have been inventing a path around one that already exists.
    async getLatestRelease (name) {
      const res = await doFetch(`${base}/rpc/release-index`, {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: '{}'
      })
      if (!res || res.ok === false) return null
      const body = await res.json()
      // hyper-svc wraps HTTP /rpc/ responses in { result }. The old code read body.versions and would
      // have found undefined even if the gate had let it through.
      const index = (body && body.result) || body || {}

      // Group this repo's files by version. The index carries every artifact, so it can answer the
      // question that matters: which versions are actually COMPLETE?
      const byVersion = new Map()
      for (const f of index.files || []) {
        if (!f || f.repo !== repo || !f.version) continue
        if (!byVersion.has(f.version)) byVersion.set(f.version, { version: f.version, builtAt: 0, names: new Set() })
        const v = byVersion.get(f.version)
        v.names.add(String(f.path || '').split('/').pop())
        if (Number(f.mtimeMs) > v.builtAt) v.builtAt = Number(f.mtimeMs)
      }

      // ⛔ SKIP INCOMPLETE RELEASES. Artifacts replicate per-file between forge backends and partial
      // arrivals are real — measured 2026-08-18: master-5d6d7e4 served build.log, manifest.json and the
      // APK while tree.json and worklet.bundle never arrived. Taking "newest" blindly would pin the phone
      // to a version it can never install, and retry it forever. Newest COMPLETE is the honest rule.
      const complete = [...byVersion.values()].filter((v) => v.names.has('tree.json') && v.names.has(BUNDLE_NAME))
      const newest = pickNewest(complete)
      if (!newest) return null

      // A release with no readable tree is not an error worth crashing a boot over.
      let tree
      try { tree = await readTree(newest.version) } catch { return null }
      return { name, version: newest.version, treeHash: tree.treeHash }
    },

    // ⛔ FETCH, DO NOT JUDGE. This returns whatever the release declares and lets installTree's
    // computeTreeHash guard accept or reject it. An earlier cut gated here too and had to be pulled: a
    // fetcher that verifies is a SECOND definition of the check, and the two agree right up until they
    // do not — and it made the fetcher order-dependent, answering only for a tree getLatestRelease had
    // pre-warmed. One guard, in the layer that owns it.
    async getTree (rootHash) {
      const hit = trees.get(rootHash)
      if (hit) return { entries: hit.entries, size: hit.entries.length }
      // Not seen yet — the caller went straight to installTree. Read the newest release's tree and hand
      // it over; if it is not the one asked for, installTree says so in the words an operator needs.
      // Same discovery path as getLatestRelease — the gated route would 403 here too.
      const latest = await api.getLatestRelease(repo)
      if (!latest) throw new Error('no complete release for ' + repo)
      const again = trees.get(latest.treeHash)
      if (!again) throw new Error('no tree for ' + latest.version)
      return { entries: again.entries, size: again.entries.length }
    },

    async getContent (contentHash) {
      const where = contents.get(contentHash)
      if (!where) throw new Error('unknown content ' + String(contentHash).slice(0, 12) + '…')
      const res = await doFetch(releaseUrl(where.version, where.name))
      if (!res || res.ok === false) throw new Error('fetch failed: ' + where.name)
      const bytes = new Uint8Array(await res.arrayBuffer())
      // ⛔ THE ONLY THING PROTECTING THIS PHONE. Releases are unsigned (`signed: false` in every publish)
      // and the forge is load-balanced HTTPS, so "it downloaded" says nothing about WHAT downloaded. The
      // bundle becomes the code that holds the DID signing key. Verify, or do not install.
      const got = hashOf(bytes)
      if (got !== contentHash) {
        throw new Error(`content hash mismatch for ${where.name}: expected ${contentHash.slice(0, 12)}…, got ${got.slice(0, 12)}…`)
      }
      return bytes
    }
  }

  return api
}

/**
 * Store-only: write the bundle, and let the NEXT start pick it up.
 *
 * Applying a new bundle to a running node would mean swapping the code under itself. A phone restarts
 * constantly anyway, so "active on next start" costs nothing and avoids a class of live-reload bugs.
 *
 * ⛔ NO MATERIALIZER. pgh's node materializer HARDLINKS, and SELinux denies `link` device-wide on
 * Android — which is what made a 269-dep closure balloon to ~5.7 GB on celltron. One file, written
 * directly, is the whole of what a bundle needs.
 */
export function bundleStore ({ dir }) {
  const markerPath = (treeHash) => path.join(dir, treeHash + '.json')
  // The release currently being installed. pgh-runtime's installTree does not pass the release down to
  // the store, but it emits `updating` with it immediately beforehand — so the caller notes it here and
  // materialize can stamp the staged marker with a comparable build time. Without that the shell has no
  // way to tell a staged bundle from the one inside a freshly installed APK.
  let pendingRelease = null
  const readMarker = (treeHash) => {
    try { return JSON.parse(fs.readFileSync(markerPath(treeHash), 'utf8')) } catch { return null }
  }

  return {
    init () { fs.mkdirSync(dir, { recursive: true }) },

    /** Told by startOta from the `updating` event, just before installTree runs. */
    noteRelease (r) { pendingRelease = r || null },

    /**
     * ⛔ THE BYTES, NOT JUST THE MARKER. A marker written before the file it names is the same bug the
     * forge has been living with all week — an index advertising a release whose artifact never arrived.
     * So the marker is written LAST and this checks the file too.
     */
    hasTree (treeHash) {
      const m = readMarker(treeHash)
      if (!m || !m.file) return false
      try { return fs.statSync(path.join(dir, m.file)).size > 0 } catch { return false }
    },

    /** Where the staged bundle for this tree lives, or null. */
    pathFor (treeHash) {
      const m = readMarker(treeHash)
      return m && m.file ? path.join(dir, m.file) : null
    },

    async materialize (rootHash, entries, { fetchContent } = {}) {
      // ⛔ RECORD A BUILD TIME, WHATEVER THE RELEASE CALLS IT. chooseBundle compares this against the
      // APK's stamp, and a staged bundle with no time is one an APK install cannot supersede — the
      // failure that left a handset running 0.1.6's JS through four installs on 2026-08-25.
      //
      // The two release shapes name it differently and neither is wrong: a forge release carries
      // `builtAt`, the pgh ReleaseRegistry carries an ISO `publishedAt`. Reading only one is how the
      // swarm fetcher would have inherited the very bug it was written to replace.
      const builtAt = (pendingRelease && (
        (Number(pendingRelease.builtAt) || 0) ||
        (Date.parse(pendingRelease.publishedAt || '') || 0)
      )) || null
      this.init()
      // ⛔ BY NAME, NEVER BY POSITION. This used to write EVERY file entry and keep whichever landed
      // last. That was safe only while a tree had exactly one entry, and the ci.yaml note said what
      // happens otherwise: "a two-entry tree stages a 154 MB APK as the worklet bundle. The OTA client
      // on a handset is exactly what cannot be fixed remotely."
      //
      // It stopped being hypothetical when CI started publishing to the release registry: `pgh publish`
      // requires a package.json, so the published tree is { package.json, worklet.bundle } and the winner
      // depended on an ordering nothing here controls or asserts. Selecting by name also stops the phone
      // downloading content it will discard — the old loop fetched every entry before dropping all but one.
      const want = (entries || []).find((e) => e && e.kind === KIND_FILE && e.name === BUNDLE_NAME)
      if (!want) {
        const names = (entries || []).filter((e) => e && e.kind === KIND_FILE).map((e) => e.name)
        throw new Error('tree contains no ' + BUNDLE_NAME + ' to stage (files: ' + (names.join(', ') || 'none') + ')')
      }
      const bytes = await fetchContent(want.childHash)
      // Write to .part and rename: a phone is killed constantly, and a truncated bundle that hasTree
      // then trusted would be a node that cannot boot with no way to say why.
      const dest = path.join(dir, want.childHash + '.bundle')
      const part = dest + '.part'
      fs.writeFileSync(part, Buffer.from(bytes))
      fs.renameSync(part, dest)
      const file = want.childHash + '.bundle'
      // `builtAt` is what lets the SHELL compare a staged bundle with the one inside the APK. Without it
      // an APK install loses to whatever was staged before it — chooseBundle prefers staged, and tree
      // hashes carry no ordering, so a phone kept running the older JS until the next OTA pass caught up.
      fs.writeFileSync(markerPath(rootHash), JSON.stringify({ treeHash: rootHash, file, builtAt }, null, 2) + '\n')
      // current.json is how the REACT NATIVE side learns what is staged: it runs before the worklet and
      // cannot read this store's code (bare-fs), only its files. Written last, after the bytes and the
      // marker, so it never advertises something that is not fully on disk.
      fs.writeFileSync(path.join(dir, 'current.json'), JSON.stringify({ treeHash: rootHash, file, builtAt }, null, 2) + '\n')
    }
  }
}

// The boot-time choice lives in its own dependency-free module so the React Native side can import
// it too (this file imports bare-fs, which does not exist there). Re-exported for callers inside the
// worklet, so there is one name for it.
export { chooseBundle } from './choose-bundle.js'

/**
 * THE FETCHER EVERY OTHER hyper-fleeky APP USES — Hyperswarm + hyper-overlay. No HTTPS, no backend.
 *
 * ⛔ WHAT THIS REPLACES, AND WHY IT WAS WRONG. The HTTPS fetcher spoke to https://7rnx.net/git — a
 * LOAD-BALANCED pair of forge daemons — for discovery, tree AND content. pgh-runtime never asked for
 * that: it is transport-agnostic and REQUIRES an injected fetcher, and pgh has shipped the Hyperswarm
 * implementation the whole time. favela-android was the only app not using it, so hyper-overlay was
 * reduced to a hashing library here while every other app used it as the transport it is.
 *
 * The cost was not theoretical. A release lands on the backend that BUILT it and replicates to the other
 * asynchronously; the phone asks the load balancer and gets whichever. Measured 2026-08-25: 0.1.6
 * replicated in ~15s, 0.1.7 had NOT replicated after 600s — the phone correctly reported no update and
 * was stuck. Measured 2026-08-18: a 153 MB APK never reached the second backend at all.
 *
 * TWO PIECES, both already exported by pgh:
 *   makeGetLatestRelease({ registryKeyHex })  replicates the PUBLISHER's registry over Hyperswarm —
 *                                            resolve-release.js path 2, written for exactly this case
 *                                            ("every standalone install"), which a handset is.
 *   NetworkFetcher({ topic: serverKey })      tree + content over hyper-overlay's protocol.
 *
 * MEASURED end-to-end against the real published release before this shipped: resolve 13.2s cold,
 * getTree 26ms, and the 38,135,946-byte worklet bundle in 8.4s.
 *
 * ⛔ RESOLVE ONCE. The 13s is registry replication from cold and it dominates everything else; fetches
 * after it are milliseconds. A phone that re-resolved per wake would pay it every time, so the topic is
 * learned once per boot — the same thing pgh's own runtime-factory does. A publisher that moves to a new
 * serverKey is a restart, not a case worth carrying state for.
 *
 * ANDROID: `preferSidecar: false`. resolve-release tries a pgh-sidecar UDS first because on a normal
 * machine both paths open the same registry corestore and a direct open loses an fd-lock race. A handset
 * has no sidecar and never will, so the probe is pure latency — and SELinux makes pathname sockets their
 * own hazard here.
 */
export async function swarmFetcher ({ registryKeyHex = DEFAULT_REGISTRY, repo = DEFAULT_REPO, timeout = 120000, destDir = null, swarm = null } = {}) {
  const { makeGetLatestRelease } = await import('pgh/resolve-release')
  const { NetworkFetcher } = await import('pgh/network-fetcher')

  const getLatestRelease = makeGetLatestRelease({ registryKeyHex, preferSidecar: false })
  const latest = await getLatestRelease(repo)
  if (!latest || !latest.serverKey) throw new Error('no published release with a serverKey for ' + repo)

  const fetcher = new NetworkFetcher({ topic: latest.serverKey, timeout, destDir, swarm })
  // NetworkFetcher's own getLatestRelease reads a LOCAL registry, which a phone does not have. Its header
  // calls the replacement a follow-on; the follow-on is the resolver above, and this is the same
  // substitution runtime-factory makes for the same reason.
  fetcher.getLatestRelease = getLatestRelease
  await fetcher.ready()
  return { fetcher, latest }
}

/**
 * Start the bundle updater. Returns { stop() } or null when OTA is unavailable.
 *
 * Never throws: the caller boots a node either way.
 */
export async function startOta ({ storage, say = () => {}, repo = DEFAULT_REPO, interval = DEFAULT_INTERVAL, currentTreeHash = null, registryKeyHex = DEFAULT_REGISTRY, swarm = null, fetcher: injectedFetcher = null } = {}) {
  let PghRuntime = null
  try {
    ;({ PghRuntime } = await import('pgh-runtime'))
  } catch {
    say('ota: pgh-runtime not bundled — updates disabled (add the dep to enable)')
    return null
  }

  const dir = path.join(storage, 'bundles')
  const store = bundleStore({ dir })
  store.init()

  // THE FETCHER IS INJECTED, exactly as pgh-runtime injects one into PghRuntime — one transport seam, in
  // the layer that owns it. Production passes nothing and gets the swarm; tests pass a double and can
  // exercise the store/runtime wiring without a DHT, which is the coverage that caught the two-week
  // "OTA never ran" bug and must not be lost with the transport.
  //
  // ⛔ NO HTTPS FALLBACK, DELIBERATELY. A fallback means the phone silently keeps using the load-balanced
  // path whenever the swarm is slow — which is precisely when the swarm is the thing to debug, and
  // precisely the failure HTTPS already has. Two transports is also two sets of failure modes on the one
  // component that cannot be fixed remotely. If this cannot reach a peer, OTA is off for that boot and
  // says so; a sideloaded APK stays the recovery route, as it already is for every native change.
  let fetcher = injectedFetcher
  if (!fetcher) {
    try {
      ;({ fetcher } = await swarmFetcher({ registryKeyHex, repo, destDir: path.join(dir, '.fetch'), swarm }))
    } catch (err) {
      say('ota: no swarm fetcher — updates disabled this boot (' + ((err && err.message) || err) + ')')
      return null
    }
  }

  const runtime = new PghRuntime({
    name: repo,
    // ⛔ NOT `process.env.X` BARE. `process` is not a Bare global — it exists in the worklet only because
    // lib/node.js imports favela-web's bare-globals shim before anything else. So this line worked on the
    // phone and threw ReferenceError everywhere else, including the first test that ever called startOta.
    // A library used from three environments must not read a global it did not import.
    currentTreeHash: currentTreeHash || envBundleHash() || null,
    fetcher,
    store,
    interval
  })

  runtime.on('updating', (r) => { store.noteRelease(r); say('ota: downloading ' + (r && r.version)) })
  runtime.on('updated', (i) => say('ota: staged ' + i.newTreeHash + ' — active on next start'))
  runtime.on('error', (e) => say('ota: ' + ((e && e.message) || e)))

  await runtime.start()
  say('ota: watching ' + repo + ' over the swarm every ' + Math.round(interval / 3600000) + 'h')
  // ⛔ `checkNow` IS EXPOSED. The 6-hour timer is a poll on a phone that is awake for seconds at a time,
  // so the interval is almost never when the user is actually looking — the one moment a check is worth
  // making is when they ask. pgh-runtime already has the public method (checkNow, index.js:107); this
  // just stops throwing the handle away, which is the whole reason the app had no update control.
  // ⛔ CLOSE THE SWARM WE OPENED. stop() used to stop only the poll loop, leaving NetworkFetcher's
  // Hyperswarm node and corestore open for the life of the process. On a server that is untidy; on a
  // phone it is a DHT node and a set of sockets held awake by something the user has switched off. It is
  // the same shape as the hyper-svc UDS leak that reached ~205k sockets and ~14 GB on stortron — a
  // handle nobody closed because the thing that created it was not the thing that owned it.
  //
  // Caught empirically: the real end-to-end probe finished staging in 23.5s and then never exited, and
  // `timeout` killed it at 600s (EXIT=124). A stop() that leaves the process alive is not a stop.
  //
  // OWNERSHIP: only close what we created. An injected fetcher belongs to the caller — a test owns its
  // double's lifecycle, and closing someone else's handle is how you get a use-after-close in the suite
  // that was meant to be catching this.
  const ownsFetcher = !injectedFetcher
  return {
    stop: async () => {
      try { if (runtime.stop) await runtime.stop() } catch { /* stopping must not throw on the way out */ }
      if (ownsFetcher && fetcher && typeof fetcher.close === 'function') {
        try { await fetcher.close() } catch { /* same */ }
      }
    },
    store,
    checkNow: () => runtime.checkNow()
  }
}
// Which config entries may be moved onto the current record backend — and, more importantly, which may not.
//
// favela-android 0.1.6 minted identities without `storeBackend`. bootSwarmDevice defaults that to null,
// and only `storeBackend === 'overlay'` constructs the OverlayRepoStore, so those DIDs boot on the legacy
// inline substrate: they author commits, and the appview refuses to materialise their record bytes.
// Posting is silently broken (observed on a handset 2026-08-25 with did:plc:zl5loetx46p6xusgc47h3mia).
//
// hyper-proto-peer 0.3.121 fixed the mint. It does nothing for an identity already created — and that
// identity is not disposable: it is a real did:plc, permanently registered in a global append-only log,
// with a recovery vault sealed under a passphrase. On a release-signed app its config is app-private, so
// there is no way to edit it from outside either. Wiping app storage would destroy the identity, the
// vault and the node's storage in order to change one field. The repair belongs in the app.
//
// ── THIS FILE IS NOT THE MIGRATION ───────────────────────────────────────────────────────────────
// Flipping a POPULATED legacy DID to 'overlay' is a genuine hazard, and hyper-proto-peer documents it as
// the e2jev case (hyper-social#16 P1): under PointerSubstrate its inline records read as an EMPTY set, so
// the first sign() would materialize an empty MST root and publish a delete-every-record commit. The
// anti-wipe guard does not catch it, because that guard looks for record FILES and a legacy DID has none.
//
// What makes the flip safe is already written and already tested: device-node.js runs migrateInline at
// boot for exactly this shape — marker-guarded by a durable __inline_migrated__ so it fires once, and its
// fromInline branch writes the file FROM the inline copy before publishing the pointer, refusing any key
// whose oid would change. Its suite proves the dangerous arm directly ("sign() REFUSED — no
// delete-every-record commit was published", then "after migration the set reads NON-empty") and proves
// it is safe to re-run (5/5, 28/28).
//
// So the only decision left is WHICH entries are allowed into that path, and that is all this file does.
//
// ── THE DISCRIMINATOR IS forceCreator, AND IT IS THE WHOLE POINT ─────────────────────────────────
// mint writes `forceCreator: true` and no `joiner`. coownerJoin writes `joiner: true` and DELETES
// forceCreator. So "this node created this identity" is expressible from the config alone, and a
// co-owned identity this phone merely JOINED is never touched: its records may already be pointer-shaped
// on the origin, its backend is the origin's decision, and a handset must not be able to migrate someone
// else's production repo as a side effect of booting.
//
// An ABSENT field means "never decided" — that is the 0.1.6 bug. An entry that says 'legacy' has decided,
// and is left alone. Silence and a choice are different things.

const OVERLAY = 'overlay'

/**
 * Move minted-here entries with no declared backend onto the current one, in place.
 *
 * Mutates `cfg`. Returns the DIDs changed so the caller can persist ONLY when something did — a repair
 * that rewrote the config on every boot would be a write to storage we care about, for nothing.
 *
 * Never throws: it runs before the node exists and must not be why a phone fails to start.
 *
 * @param {object|null} cfg  the raw hpp config ({ dids: [...] })
 * @returns {{ changed: string[] }}
 */
export function repairStoreBackend (cfg) {
  const changed = []
  const dids = cfg && Array.isArray(cfg.dids) ? cfg.dids : []
  for (const entry of dids) {
    if (!entry || typeof entry !== 'object') continue
    // Already answered — either correctly, or deliberately otherwise.
    if (entry.storeBackend) continue
    // Not ours to decide. `joiner` alone is the co-owner case; BOTH flags is an entry we did not write,
    // and guessing at an incoherent config is how a repair becomes an incident.
    if (entry.joiner) continue
    if (entry.forceCreator !== true) continue
    entry.storeBackend = OVERLAY
    if (entry.did) changed.push(entry.did)
  }
  return { changed }
}
// Which DIDs this node SUBSCRIBES to — the value favela-web reads as FAVELA_ROSTER.
//
// ⛔ ROSTER ≠ SIGNING SET. The roster is what this node INDEXES: it joins each DID's topic, resolves its
// verifyKey, and follows the freshest verified co-owner's firehose (favela-web/bin/favela-web.js:565-687).
// Every entry is read-only and independently verified. What this node can SIGN for is a different, much
// smaller thing — one hpp control socket (favela-web/lib/writer.js:283, "favela's write path is
// single-DID (the UDS socket picks the device)"). Our own hosted DIDs appear here because we index them,
// NOT because we hold their keys, and nothing downstream may read authority out of roster membership.
//
// ⛔ WHY THIS EXISTS AT ALL. favela-web captures the roster at module top level, so it is frozen at
// import. The phone never set it, so the in-process favela-web joined zero topics and its index — the one
// every screen reads — could only ever contain what was already in it. See test/roster.test.mjs, whose
// first test replicates favela-web's parser verbatim against the value we used to hand it.
//
// Pure and IO-free on purpose: the phone's boot is expensive to stand up, and the part worth testing is
// this decision, not the boot.

// A DID we are willing to turn into a topic join and a verifyKey resolution.
//
// The comma exclusion is load-bearing rather than cosmetic: the env format is comma-separated, so a DID
// carrying a comma would arrive at favela-web as TWO entries, each garbage. Whitespace is excluded for
// the same reason the parser trims — an entry that only survives trimming is an entry we should not have
// emitted. `did:` alone, or any method with no identifier, is not a DID and must not reach
// resolveVerifyKey, where it would cost a network round-trip to learn what a regex already knows.
const DID = /^did:[a-z][a-z0-9]*:[A-Za-z0-9._%:-]+$/

function usable (v) {
  return typeof v === 'string' && DID.test(v)
}

/**
 * The subscription set, in the order favela-web will open it.
 *
 * Hosted first, deliberately: `addPeer()` runs in roster order, and `apProjected()` asks about
 * `ROSTER[0]` specifically (bin/favela-web.js:351-352) — so a tracked stranger sorting ahead of our own
 * DID would quietly change which actor the ActivityPub side reports on.
 *
 * ALL hosted DIDs, not the first: reads are already multi-DID (one appview, DID-keyed, `viewerDid` per
 * query), so a phone housing two accounts is a read-path reality today. Taking `nodes[0]` here would
 * half-subscribe the second account — visible as a timeline that is simply missing one person's posts,
 * with nothing in the log to say so.
 *
 * @param {object}   opts
 * @param {string[]} [opts.hosted]    DIDs whose repos this node co-owns (hpp nodes)
 * @param {string[]} [opts.tracked]   DIDs explicitly tracked by the user (tracked-dids.json)
 * @param {string[]} [opts.following] DIDs the viewer follows, from the index
 * @returns {string[]} deduped, ordered, every entry safe to hand to favela-web
 */
export function rosterFor ({ hosted = [], tracked = [], following = [] } = {}) {
  const out = []
  const seen = new Set()
  for (const list of [hosted, tracked, following]) {
    if (!Array.isArray(list)) continue
    for (const did of list) {
      if (!usable(did) || seen.has(did)) continue
      seen.add(did)
      out.push(did)
    }
  }
  return out
}

/**
 * The same set as the env string favela-web parses.
 *
 * Empty means empty: `String(undefined)` is the literal 'undefined', which favela-web would happily take
 * for a DID and then fail to resolve, so a node with nothing to subscribe to must produce '' — the same
 * silence as before, rather than one fabricated peer.
 */
export function rosterEnv (opts) {
  return rosterFor(opts).join(',')
}
// The phone's session with its OWN in-process favela-web.
//
// WHY THIS EXISTS. favela-web derives the viewer from a session cookie (`viewerOf(req)` →
// `favela_session`). Anonymous requests get `viewerDid: null`, which silently costs:
//   - `liked` / `reposted` state on every post
//   - per-viewer mutes and blocks in withMod
//   - every write route (compose, like, repost, follow, delete) — all 401
// The phone's legacy IPC verbs passed viewerDid explicitly, so porting a screen to HTTP without a
// session would quietly degrade it: posts would just render un-liked and nobody would be told.
//
// WHY THE PHONE CAN SELF-AUTHENTICATE. The browser flow needs a pairing ceremony because the browser
// holds no DID key. The phone is not a browser: its worklet RUNS hpp and holds the DID's signing key,
// so it can mint its own delegation locally (SwarmDevice.delegate). No invite, no tunnel, no paste.
//
// THE PROOF (atproto-identity/lib/web-auth.js):
//   sig        = signAssertion({ challenge, exp }, subPriv)                    — sub-key signs the challenge
//   delegation = signAssertion({ iss: did, sub: subKeyHex, iat, exp }, didKey) — hpp vouches for the sub-key
// favela-web re-verifies the delegation against the DID's PLC-published #atproto key on EVERY login —
// there is no TOFU — and separately checks the sub-key has not been revoked in the device registry.
//
// The sub-key is a real, listable, revocable device: `delegate` calls addDevice, so this phone shows up
// in `pgh`/favela device lists and can be revoked like any other. That is deliberate — a session that
// cannot be revoked is not a device.
//
// IO is injected (fetch, fs, the hpp node) so this is testable without a handset, an emulator, or Metro.

import { signAssertion } from 'atproto-identity/lib/auth.js'
// keyFromPrivate (not generateAtprotoKey) — it produces the 33-byte COMPRESSED pubkey delegate()
// requires without generating anything, so the curve choice stays in atproto-identity.
//
// ⛔ generateAtprotoKey() is NOT bare-safe: it calls @noble's randomSecretKey, which requires
// `crypto.getRandomValues` — absent under Bare. atproto-identity's own auth.js avoids this the same way,
// taking randomness from hypercore-crypto (bare-native via sodium). Randomness here does likewise.
import { keyFromPrivate } from 'atproto-identity/lib/atproto-identity.js'
import { randomBytes } from 'hypercore-crypto'

const toHex = (b) => Array.from(b).map((x) => x.toString(16).padStart(2, '0')).join('')
const fromHex = (h) => { const b = new Uint8Array(h.length >> 1); for (let i = 0; i < b.length; i++) b[i] = parseInt(h.substr(i * 2, 2), 16); return b }

// How long the challenge assertion is valid. Short: it is consumed immediately by the login that
// follows, and favela-web burns the challenge single-use anyway. A long exp here buys nothing and
// widens the window if the proof ever leaks.
const SIG_TTL_SEC = 120

/**
 * A fresh secp256k1 sub-keypair, bare-safe.
 *
 * Randomness comes from hypercore-crypto (sodium), not @noble's randomSecretKey — see the import note.
 * A raw 32 random bytes is not automatically a valid secp256k1 scalar (it must be non-zero and below the
 * curve order), so retry rather than assume: the odds of a reject are ~2^-128, but "never happens" and
 * "cannot happen" are different, and the failure would be a key that cannot sign.
 */
export function mintSubKey () {
  for (let i = 0; i < 8; i++) {
    try { return keyFromPrivate(Uint8Array.from(randomBytes(32))) } catch { /* invalid scalar — draw again */ }
  }
  throw new Error('mintSubKey: could not derive a valid secp256k1 key in 8 attempts')
}

/**
 * Load the persisted UI sub-keypair, or mint one on first run.
 *
 * The key is the phone's IDENTITY AS A DEVICE, not a cache — regenerating it orphans the delegation
 * recorded in the device registry and leaves a dead entry behind, so it must persist across restarts.
 *
 * @param {string} file            path to the JSON keyfile
 * @param {object} fs              { readFileSync, writeFileSync, mkdirSync }
 * @param {(p:string)=>string} dirnameOf
 * @returns {{ privHex: string, pubHex: string, created: boolean }}
 */
export function loadOrCreateSubKey (file, fs, dirnameOf) {
  try {
    const parsed = JSON.parse(fs.readFileSync(file, 'utf8'))
    if (parsed && /^[0-9a-f]{64}$/i.test(parsed.priv) && /^[0-9a-f]{66}$/i.test(parsed.pub)) {
      return { privHex: parsed.priv.toLowerCase(), pubHex: parsed.pub.toLowerCase(), created: false }
    }
    // A malformed keyfile is NOT a reason to mint silently over it — that would orphan the delegation
    // the old key holds. Fail loudly; recovery is a human decision (revoke the old device, then delete).
    throw new Error('sub-key file exists but is malformed: ' + file)
  } catch (e) {
    if (e && e.message && e.message.startsWith('sub-key file exists')) throw e
    // Genuinely absent → first run.
  }
  const kp = mintSubKey()
  const rec = { priv: toHex(kp.privateKey), pub: toHex(kp.publicKey), createdAt: new Date().toISOString() }
  try { fs.mkdirSync(dirnameOf(file), { recursive: true }) } catch {}
  fs.writeFileSync(file, JSON.stringify(rec, null, 2))
  return { privHex: rec.priv, pubHex: rec.pub, created: true }
}

/**
 * Sign a favela-web challenge with the sub-key.
 * verifyChallengeSig checks `payload.challenge === challenge`, so that field is the contract.
 */
export function signChallenge (challenge, privHex, nowSec = Math.floor(Date.now() / 1000)) {
  if (!challenge) throw new Error('signChallenge: challenge required')
  return signAssertion({ challenge, iat: nowSec, exp: nowSec + SIG_TTL_SEC }, fromHex(privHex))
}

/** Pull the session token out of a Set-Cookie header. Returns null if absent. */
export function tokenFromSetCookie (setCookie) {
  if (!setCookie) return null
  const raw = Array.isArray(setCookie) ? setCookie.join('; ') : String(setCookie)
  const m = raw.match(/(?:^|[;,\s])favela_session=([^;,\s]+)/)
  return m ? m[1] : null
}

/**
 * Pick the SwarmDevice out of whatever hpp handed us.
 *
 * ⛔ THE SHAPE IS NOT WHAT IT LOOKS LIKE. `bootMultiDevice().nodes[i]` is NOT a SwarmDevice — it is the
 * WRAPPER `bootSwarmDevice` returns: `{ device, sb, did, self, blobs, control, membrane, overlay, … }`
 * (hyper-proto-peer/lib/device-node.js:595). `delegate()` lives on the SwarmDevice INSIDE it
 * (swarm-device.js:699). The wrapper DOES carry `.did`, which is exactly why this survived review and
 * every test: it reads like a node right up until the delegate() guard rejects it — on a handset, at
 * boot, with the UI silently downgraded to anonymous reads.
 *
 * Accept either shape, and refuse rather than guess when neither has delegate().
 */
export function sessionNodeOf (entry) {
  if (!entry) return null
  if (typeof entry.delegate === 'function') return entry                                   // already a SwarmDevice
  if (entry.device && typeof entry.device.delegate === 'function') return entry.device      // hpp's wrapper
  return null
}

/**
 * Establish a session against the in-process favela-web.
 *
 * @param {object}   opts
 * @param {string}   opts.favelaUrl   e.g. http://127.0.0.1:4041
 * @param {object}   opts.node        an hpp SwarmDevice (must expose .did and .delegate)
 * @param {string}   opts.privHex     sub-key private key
 * @param {string}   opts.pubHex      sub-key compressed public key
 * @param {Function} opts.fetchImpl   fetch(url, init)
 * @param {string}   [opts.label]     device label recorded in the registry
 * @returns {Promise<{ token: string, did: string, handle: string|null }>}
 */
export async function establishSession ({ favelaUrl, node, privHex, pubHex, fetchImpl, label = 'favela-android' } = {}) {
  if (!favelaUrl) throw new Error('establishSession: favelaUrl required')
  if (!node || typeof node.delegate !== 'function') throw new Error('establishSession: an hpp node with delegate() required')
  if (!privHex || !pubHex) throw new Error('establishSession: sub-keypair required')
  if (typeof fetchImpl !== 'function') throw new Error('establishSession: fetchImpl required')

  // 1. Mint (or re-mint) the delegation. Idempotent by design: delegate() re-signs and re-records the
  //    SAME sub-key, so running this every boot is safe and self-heals a registry entry that never
  //    landed (addDevice is fire-and-forget precisely because it can block on an unconverged writer).
  const del = await node.delegate({ subKey: pubHex, label })
  if (!del || !del.delegation) throw new Error('establishSession: hpp returned no delegation')

  // 2. Fresh single-use challenge.
  const cRes = await fetchImpl(favelaUrl + '/api/auth/challenge')
  if (!cRes.ok) throw new Error('challenge failed: HTTP ' + cRes.status)
  const { challenge } = await cRes.json()
  if (!challenge) throw new Error('challenge failed: no challenge in response')

  // 3. Prove live control of the sub-key, and present hpp's delegation for it.
  const proof = { did: node.did, subKey: pubHex, challenge, sig: signChallenge(challenge, privHex), delegation: del.delegation }
  const lRes = await fetchImpl(favelaUrl + '/api/auth/login', {
    method: 'POST',
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify(proof)
  })
  const body = await lRes.json().catch(() => ({}))
  if (!lRes.ok) throw new Error('login rejected (HTTP ' + lRes.status + '): ' + (body.error || 'unknown'))

  // 4. The cookie is the session. HttpOnly is irrelevant here — we read the header directly rather
  //    than from a document, because there is no document.
  const getHeader = (name) => (lRes.headers && typeof lRes.headers.get === 'function' ? lRes.headers.get(name) : null)
  const token = tokenFromSetCookie(getHeader('set-cookie'))
  if (!token) throw new Error('login succeeded but no favela_session cookie was returned')

  return { token, did: body.did || node.did, handle: body.handle || null }
}
// What the native shell tells the node at boot, and what the node tells the settings page back.
//
// ⛔ WHY A FILE AND NOT argv. The obvious way to hand the running bundle's hash to the worklet is a
// second argv element. It is a trap: the SHELL (the APK) and the BUNDLE (arrives by OTA) version
// independently, and lib/node.js reads storage as `Bare.argv[argv.length - 1]`. A new shell passing
// `[storage, hash]` to an OLD bundle would hand it the hash as its storage path — a node booting into
// an empty directory, which is the worst failure this app has. A file is additive in both directions:
// an old bundle never reads it, a new bundle finds it missing and says so.
//
// Two files, two directions, both tiny:
//
//   <storage>/shell.json      shell → node.  { ota, pair, bundle, dns }
//   <storage>/app-update.json node → page.   { ota, pair, running, staged, checkedAt }
//
// Nothing here does I/O: the callers own that (RNFS on one side, bare-fs on the other), which is what
// makes both shapes testable with no handset.

export const SHELL_FILE = 'shell.json'
export const STATE_FILE = 'app-update.json'

const isHash = (v) => typeof v === 'string' && /^[0-9a-f]{16,128}$/i.test(v)

// Addresses only — this list becomes FAVELA_NAMESERVERS and is handed to connect(). A hostname would
// need a resolver to resolve, which is the thing we are obtaining, and `8.8.8.8:53` is a connect() to a
// host that does not exist. A character-class test admits both, so the families are parsed apart.
//
// ⚠ Deliberately duplicated from favela-web's lib/dns-txt.js rather than imported: this module is also
// loaded by the React Native side, which does not bundle favela-web, and a cross-package import here
// would make the app shell depend on the worklet's dependency graph to open a settings screen.
function isIpv4 (s) {
  const parts = s.split('.')
  return parts.length === 4 && parts.every((o) => /^\d{1,3}$/.test(o) && Number(o) <= 255)
}
function isIpv6 (s) {
  if (!s.includes(':')) return false
  if ((s.match(/::/g) || []).length > 1) return false
  const parts = s.split(':')
  if (parts.length > 8) return false
  return parts.every((p, i) => {
    if (p === '') return true
    if (i === parts.length - 1 && p.includes('.')) return isIpv4(p)
    return /^[0-9a-fA-F]{1,4}$/.test(p)
  })
}
const isAddr = (v) => typeof v === 'string' && v.length > 0 && v.length <= 45 && (isIpv4(v) || isIpv6(v))

/**
 * Read what the shell said. Tolerant by construction: every field is optional and a malformed file is
 * the same as no file, because a node that refuses to boot over its own handoff blob is unrecoverable
 * from a user's phone.
 *
 * `ota` is a CAPABILITY CLAIM, not a preference: it means "this shell has a message handler that can
 * service check/restart". The settings page renders its buttons only when it is true, so an old shell
 * running a new bundle shows no controls rather than dead ones.
 */
export function parseShell (text) {
  let raw = null
  try { raw = typeof text === 'string' ? JSON.parse(text) : text } catch { raw = null }
  if (!raw || typeof raw !== 'object') return { ota: false, pair: false, bundle: null, dns: [] }
  return {
    ota: raw.ota === true,
    // A SEPARATE capability from `ota`, deliberately. The page arrives by OTA and this shell by APK, so
    // "can service update buttons" and "can open the pairing screen" are answered by whatever shell is
    // actually running — a page must never render a control the shell beneath it cannot honour.
    pair: raw.pair === true,
    bundle: isHash(raw.bundle) ? String(raw.bundle) : null,
    dns: Array.isArray(raw.dns) ? raw.dns.filter(isAddr).map(String) : []
  }
}

/** The shell's side of the same shape. Written before every worklet start, never appended to. */
export function encodeShell ({ ota = false, pair = false, bundle = null, dns = [] } = {}) {
  return JSON.stringify({
    ota: ota === true,
    pair: pair === true,
    bundle: isHash(bundle) ? String(bundle) : null,
    dns: Array.isArray(dns) ? dns.filter(isAddr).map(String) : []
  })
}

/**
 * What the settings page renders.
 *
 * ⛔ `running` COMES FROM THE SHELL, not from the OTA store. The store knows what is STAGED; only the
 * side that chose a file and started the runtime knows what is EXECUTING. Deriving "running" from
 * current.json is how the OTA log came to announce it had staged the bundle it was already running.
 *
 * `checkedAt` is an ISO string because favela-web's relTime() parses one.
 */
export function shellState ({ shell = null, staged = null, checkedAt = null } = {}) {
  const s = shell || { ota: false, pair: false, bundle: null }
  return {
    ota: s.ota === true,
    pair: s.pair === true,
    running: isHash(s.bundle) ? String(s.bundle) : null,
    staged: isHash(staged) ? String(staged) : null,
    checkedAt: typeof checkedAt === 'string' && checkedAt ? checkedAt : null
  }
}

/**
 * A message from the settings page, arriving through the WebView bridge.
 *
 * The page is served by our own loopback server and the WebView refuses off-origin navigation, but this
 * still parses UNTRUSTED input: it is a string from a web page reaching a function that can restart the
 * node, and one that opens a ceremony granting a signing key. So it is an allow-list of three named
 * verbs and nothing else — no pass-through of an op name to a handler map, which is how a bridge like
 * this turns into a remote-call surface.
 */
export function parseShellMessage (data) {
  let raw = null
  try { raw = typeof data === 'string' ? JSON.parse(data) : data } catch { return null }
  if (!raw || typeof raw !== 'object' || raw.t !== 'app-update') return null
  if (raw.op === 'check' || raw.op === 'restart' || raw.op === 'pair') return { op: raw.op }
  return null
}
// UTF-8 ↔ bytes, dependency-free.
//
// ⛔ WHY THIS EXISTS AT ALL. react-native-bare-kit's IPC is a byte stream on both sides and does NOT
// convert: `_read` pushes `new Uint8Array(data)` (index.js:59) and `_write` reads `.buffer` /
// `.byteOffset` / `.byteLength` off whatever it is given (index.js:65). So:
//
//   - `data.toString()` on a read chunk is Array.prototype.toString — it yields "123,34,116,..." (the
//     byte VALUES, comma-separated), not text. This silently fed garbage to the message parser and is
//     what made a fully-booted node look like "worklet did not become ready in 120000ms".
//   - writing a string writes nothing coherent, because a string has no `.buffer`.
//
// ⛔ NOT `b4a` and NOT `Buffer`. b4a's react-native entry does `require('react-native-b4a')` inside a
// try/catch, and Metro resolves statically — an unresolvable require fails the BUILD, catch or no
// catch. `Buffer` is not a React Native global. TextDecoder is not guaranteed present either. Hence
// hand-rolled, and hence testable off-device (test/utf8.test.mjs).

/**
 * Encode a string to UTF-8 bytes.
 */
export function encodeUtf8 (str) {
  const out = []
  for (let i = 0; i < str.length; i++) {
    let c = str.charCodeAt(i)
    // Surrogate pair → one code point.
    if (c >= 0xd800 && c <= 0xdbff && i + 1 < str.length) {
      const next = str.charCodeAt(i + 1)
      if (next >= 0xdc00 && next <= 0xdfff) {
        c = 0x10000 + ((c - 0xd800) << 10) + (next - 0xdc00)
        i++
      }
    }
    if (c < 0x80) out.push(c)
    else if (c < 0x800) out.push(0xc0 | (c >> 6), 0x80 | (c & 0x3f))
    else if (c < 0x10000) out.push(0xe0 | (c >> 12), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f))
    else {
      out.push(0xf0 | (c >> 18), 0x80 | ((c >> 12) & 0x3f), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f))
    }
  }
  return new Uint8Array(out)
}

/**
 * Decode COMPLETE UTF-8 bytes to a string. For a whole buffer that is known not to end mid-character
 * (a facet slice, a config file) — a stream needs createUtf8Decoder below instead.
 */
export function decodeUtf8 (bytes) {
  const d = createUtf8Decoder()
  return d(bytes)
}

/**
 * A STATEFUL decoder, because this decodes a STREAM.
 *
 * IPC chunk boundaries are not character boundaries any more than they are message boundaries: a
 * multi-byte character can straddle two reads. A stateless per-chunk decode would corrupt exactly those
 * characters (the node's own log lines contain an em dash, so this is not hypothetical). Incomplete
 * trailing sequences are therefore held back until their remaining bytes arrive.
 *
 * Returns a function: (Uint8Array) => string.
 */
export function createUtf8Decoder () {
  let pending = new Uint8Array(0)

  return function decode (chunk) {
    let bytes = chunk
    if (pending.length > 0) {
      bytes = new Uint8Array(pending.length + chunk.length)
      bytes.set(pending, 0)
      bytes.set(chunk, pending.length)
      pending = new Uint8Array(0)
    }

    // Find the start of a trailing incomplete sequence, if any, and hold it back.
    let end = bytes.length
    for (let i = bytes.length - 1; i >= 0 && i >= bytes.length - 3; i--) {
      const b = bytes[i]
      if ((b & 0xc0) === 0x80) continue          // continuation byte — keep walking back
      const need = b < 0x80 ? 1 : b < 0xe0 ? 2 : b < 0xf0 ? 3 : 4
      if (i + need > bytes.length) end = i       // sequence is cut off by the chunk boundary
      break
    }
    if (end < bytes.length) {
      pending = bytes.slice(end)
      bytes = bytes.subarray(0, end)
    }

    let str = ''
    for (let i = 0; i < bytes.length;) {
      const b = bytes[i]
      let c
      if (b < 0x80) { c = b; i += 1 } else if (b < 0xe0) {
        c = ((b & 0x1f) << 6) | (bytes[i + 1] & 0x3f); i += 2
      } else if (b < 0xf0) {
        c = ((b & 0x0f) << 12) | ((bytes[i + 1] & 0x3f) << 6) | (bytes[i + 2] & 0x3f); i += 3
      } else {
        c = ((b & 0x07) << 18) | ((bytes[i + 1] & 0x3f) << 12) | ((bytes[i + 2] & 0x3f) << 6) |
            (bytes[i + 3] & 0x3f)
        i += 4
      }
      if (c > 0xffff) {
        c -= 0x10000
        str += String.fromCharCode(0xd800 + (c >> 10), 0xdc00 + (c & 0x3ff))
      } else {
        str += String.fromCharCode(c)
      }
    }
    return str
  }
}
// Seed-anchored atproto identity — the secp256k1 / did:plc half.
//
// One BIP39 mnemonic anchors both worlds:
//   mnemonic -> Ed25519  (keet-identity-key)  -> Hypercore log signing   [NEXT increment]
//   mnemonic -> secp256k1 (this module)        -> did:plc + atproto commits
//
// This module owns the atproto side: deterministic secp256k1 derivation, did:key
// encoding, and building/signing a did:plc genesis operation — entirely offline.
// It never submits to the PLC directory (the op-log is permanent; don't churn).

import { mnemonicToSeedSync } from '@scure/bip39'
import { HDKey } from '@scure/bip32'
import { secp256k1 } from '@noble/curves/secp256k1'
import { sha256 } from '@noble/hashes/sha2'
import { base64url } from 'multiformats/bases/base64'
import { encodeDidKey, CURVE_SECP256K1 } from './did-key.js'
import { encodeOp, unsignedOp, didForCreateOp, opCid } from './did-plc.js'

// Our fixed derivation path. No BIP44 coin type is registered for atproto, so this
// is a project convention — the *mnemonic* is the recovery anchor; the path is fixed
// by this constant so the same phrase always yields the same atproto key.
export const ATPROTO_SIGNING_PATH = "m/44'/0'/0'/0/0"
// A SEPARATE derivation for the swarm's ROOT recovery/rotation key — held only by the root, NEVER
// distributed to devices. Distinct account index ('1') so a device that holds the signing key
// cannot derive this. See atproto-base-REVOCATION.md §4-5.
export const ATPROTO_RECOVERY_PATH = "m/44'/0'/1'/0/0"

// raw base64url (no multibase prefix, no padding) — atproto's sig encoding.
function sigToBase64url (bytes) {
  return base64url.encode(bytes).slice(1) // drop multibase 'u'
}
export function base64urlToBytes (str) {
  return base64url.decode('u' + str)
}

// mnemonic -> deterministic secp256k1 keypair for atproto signing.
export function deriveAtprotoKey (mnemonic, path = ATPROTO_SIGNING_PATH) {
  const seed = mnemonicToSeedSync(mnemonic)
  const node = HDKey.fromMasterSeed(seed).derive(path)
  if (!node.privateKey) throw new Error('derivation produced no private key')
  return keyFromPrivate(node.privateKey)
}

// raw 32-byte secp256k1 private key -> { privateKey, publicKey, didKey }.
export function keyFromPrivate (privateKey) {
  const publicKey = secp256k1.getPublicKey(privateKey, true) // 33-byte compressed
  return { privateKey, publicKey, didKey: encodeDidKey(CURVE_SECP256K1, publicKey) }
}

// A fresh random atproto signing keypair (server-minted accounts with no seed anchor).
export function generateAtprotoKey () {
  return keyFromPrivate(secp256k1.utils.randomPrivateKey())
}

// ECDSA sign the sha256 of DAG-CBOR(unsignedOp), low-S, compact -> base64url.
export function signOp (unsigned, privateKey) {
  const hash = sha256(encodeOp(unsigned))
  const sig = secp256k1.sign(hash, privateKey, { lowS: true })
  return sigToBase64url(sig.toCompactRawBytes())
}

// verify a signature string against an unsigned op + did:key-encoded pubkey bytes.
export function verifyOp (unsigned, sigB64url, publicKey) {
  const hash = sha256(encodeOp(unsigned))
  return secp256k1.verify(base64urlToBytes(sigB64url), hash, publicKey, { lowS: true })
}

// Build an UNSIGNED did:plc genesis op. rotationKey defaults to the signing key
// (single-key setup); pass a distinct rotation didKey for key-separation.
// A HANDLE AND A PDS ARE OPTIONAL, and omitting both is the P2P-only genesis (hyper-social #54 §8):
// an identity that names nobody's infrastructure. Creating a did:plc and joining someone's service are
// different decisions, and requiring both at once is what made minting undecidable — you could not have
// an identity without first answering "whose server are you on?". Accepting an invite from
// atproto-bridge or ap-bridge is a LATER PLC UPDATE op that adds the domain handle and the endpoint, so
// creation stays free and joining stays reversible.
//
// ⛔ THEY USED TO BE UNCONDITIONAL, and the two failure modes were not equally survivable. A missing
// pdsUrl put the VALUE `undefined` in the op and dag-cbor refused to encode it — loud, and safe. A
// missing handle produced the STRING 'at://undefined', which encodes perfectly and would have been
// appended to a global, permanent, public log. The silent one is the one this guards.
//
// The directory requires neither: checkGenesisOp (lib/plc-directory.js) asks only for a plc_operation
// with prev:null, rotationKeys, a verificationMethods.atproto and a self-signature.
export function buildGenesisOp ({ signingDidKey, rotationDidKeys, handle = null, pdsUrl = null, labelDidKey = null, feedGenEndpoint = null, labelerEndpoint = null }) {
  const verificationMethods = { atproto: signingDidKey }
  const services = {}
  if (pdsUrl) services.atproto_pds = { type: 'AtprotoPersonalDataServer', endpoint: pdsUrl }
  // Lens-export service entries (a self-custody feed-generator + labeler — e.g. a favela community DID).
  // The PLC op's `services`/`verificationMethods` KEYS become DID-doc fragments: services.bsky_fg → the
  // #bsky_fg service, verificationMethods.atproto_label → the #atproto_label VM. Endpoints point at where
  // the getFeedSkeleton / queryLabels+subscribeLabels XRPC is served (the membrane). #atproto_label
  // defaults to the #atproto signing key (labels co-signed by the shared key) unless a distinct key is given.
  if (feedGenEndpoint) services.bsky_fg = { type: 'BskyFeedGenerator', endpoint: feedGenEndpoint }
  if (labelerEndpoint) {
    services.atproto_labeler = { type: 'AtprotoLabeler', endpoint: labelerEndpoint }
    verificationMethods.atproto_label = labelDidKey || signingDidKey
  } else if (labelDidKey) {
    verificationMethods.atproto_label = labelDidKey
  }
  return {
    type: 'plc_operation',
    rotationKeys: rotationDidKeys && rotationDidKeys.length ? rotationDidKeys : [signingDidKey],
    verificationMethods,
    // Empty, not absent: an identity with no handle claims no alias. The domain handle arrives with the
    // invite, as an update op — it is not a thing you are born with.
    alsoKnownAs: handle ? [`at://${handle}`] : [],
    services,
    prev: null
  }
}

// key { privateKey, publicKey, didKey } -> signed genesis op + did:plc.
export function identityFromKey (key, { handle, pdsUrl }) {
  const unsigned = buildGenesisOp({ signingDidKey: key.didKey, handle, pdsUrl })
  const sig = signOp(unsigned, key.privateKey)
  const signedOp = { ...unsigned, sig }
  const did = didForCreateOp(signedOp)
  return { did, didKey: key.didKey, publicKey: key.publicKey, privateKey: key.privateKey, signedOp }
}

// Full offline flow: mnemonic -> signed genesis op + did:plc.
export function createAtprotoIdentity (mnemonic, { handle, pdsUrl, path = ATPROTO_SIGNING_PATH }) {
  return identityFromKey(deriveAtprotoKey(mnemonic, path), { handle, pdsUrl })
}

// Same, but from a raw private key (server-minted / bring-your-own accounts).
export function createAtprotoIdentityFromKey (privateKey, { handle, pdsUrl }) {
  return identityFromKey(keyFromPrivate(privateKey), { handle, pdsUrl })
}

// The atproto-base SWARM identity: ONE did:plc whose #atproto signing key is SHARED among N
// attested devices, but whose ROTATION authority is a SEPARATE root recovery key that is NEVER
// distributed to devices. Devices sign commits (verificationMethods.atproto = shared signing key)
// but have ZERO PLC authority — only the root (recovery key) can rotate/revoke. Revocation = the
// root rotates the shared signing key via a PLC update; a device holds only the old signing key,
// not the root, so it cannot self-recover. Contrast createAtprotoIdentity (rotationKeys =
// [signingKey], no separation — a device could rotate the DID). The genesis is signed by the
// recovery key (a genesis must be signed by one of its own rotationKeys). See
// atproto-base-REVOCATION.md §5. Returns { did, signedOp, signingKey, recoveryKey } — `signingKey`
// is distributed to attested devices; `recoveryKey` STAYS WITH THE ROOT.
export function createSwarmIdentity (mnemonic, { handle, pdsUrl, feedGenEndpoint = null, labelerEndpoint = null, labelDidKey = null } = {}) {
  const signingKey = deriveAtprotoKey(mnemonic, ATPROTO_SIGNING_PATH)
  const recoveryKey = deriveAtprotoKey(mnemonic, ATPROTO_RECOVERY_PATH)
  const unsigned = buildGenesisOp({ signingDidKey: signingKey.didKey, rotationDidKeys: [recoveryKey.didKey], handle, pdsUrl, feedGenEndpoint, labelerEndpoint, labelDidKey })
  const sig = signOp(unsigned, recoveryKey.privateKey)
  const signedOp = { ...unsigned, sig }
  const did = didForCreateOp(signedOp)
  return { did, signedOp, signingKey, recoveryKey, didKey: signingKey.didKey }
}

// ── Post-genesis PLC operations (device attestation = rotation, NOT genesis) ──
//
// A did:plc is fixed at genesis; you evolve it with UPDATE operations that chain via
// `prev` (the CID of the previous signed op) and are signed by one of the CURRENT
// rotationKeys. This is how a device signing key is attested AFTER genesis without
// changing the DID — the atproto-correct model (see DESIGN.md §4a). The genesis stays
// deterministic (root-derived signing key → reproducible DID); the device key arrives
// as a rotation of verificationMethods.atproto.

// Build an UNSIGNED update op. `prevSignedOp` is the previous op in the log (its CID
// becomes `prev`). The remaining fields are the FULL new operation state — carry
// forward what you're not changing (a PLC op replaces the whole doc state, it is not a
// patch). This module never submits to the PLC directory; it only builds/signs offline.
export function buildUpdateOp ({ prevSignedOp, rotationDidKeys, verificationMethods, alsoKnownAs, services }) {
  if (!prevSignedOp) throw new Error('buildUpdateOp: prevSignedOp required')
  return {
    type: 'plc_operation',
    rotationKeys: rotationDidKeys,
    verificationMethods,
    alsoKnownAs,
    services,
    prev: opCid(prevSignedOp)
  }
}

// Attest a device by ROTATING verificationMethods.atproto to the device's did:key,
// carrying every other field forward from `prevSignedOp`, signed by a rotation key
// (the root — `signerPrivateKey` must correspond to one of prevSignedOp.rotationKeys).
// The DID is UNCHANGED. Returns the signed update op ready to submit to the PLC log.
export function rotateVerificationMethod ({ prevSignedOp, newAtprotoDidKey, signerPrivateKey }) {
  const unsigned = buildUpdateOp({
    prevSignedOp,
    rotationDidKeys: prevSignedOp.rotationKeys,
    verificationMethods: { ...prevSignedOp.verificationMethods, atproto: newAtprotoDidKey },
    alsoKnownAs: prevSignedOp.alsoKnownAs,
    services: prevSignedOp.services
  })
  const sig = signOp(unsigned, signerPrivateKey)
  return { ...unsigned, sig }
}

// Full self-custody onboarding — the atproto-correct device-attested model. A DETERMINISTIC,
// root-derived genesis pins the DID (reproducible from rootMnemonic+handle+pdsUrl), then a
// POST-genesis rotation attests a per-device signing key. The DID is f(root,handle,pds) — NOT
// f(device key) — so it reproduces across runs and can span multiple devices. The root key
// signs the genesis + the rotation and is then discarded (the user keeps it via hyperident);
// the peer holds ONLY the device key. This supersedes buildAttestedIdentity, which baked the
// device key INTO the genesis (making did:plc = f(device key) — non-reproducible, single-device).
// Pass a device secp256k1 privateKey to pin it; otherwise a fresh device key is minted.
export function selfCustodyIdentity ({ rootMnemonic, rootKey, handle, pdsUrl, deviceKey, path = ATPROTO_SIGNING_PATH }) {
  const genesis = rootKey
    ? createAtprotoIdentityFromKey(rootKey, { handle, pdsUrl })
    : createAtprotoIdentity(rootMnemonic, { handle, pdsUrl, path })
  const device = deviceKey ? keyFromPrivate(deviceKey) : generateAtprotoKey()
  const rotationOp = rotateVerificationMethod({
    prevSignedOp: genesis.signedOp,
    newAtprotoDidKey: device.didKey,
    signerPrivateKey: genesis.privateKey // the root — a rotationKey of the genesis
  })
  return {
    did: genesis.did, // = f(root, handle, pds) — reproducible, device-independent
    genesisOp: genesis.signedOp, // vm = root-derived key, signed by root, prev:null
    rotationOp, // vm → device key, signed by root, prev = cid(genesis)
    deviceKey: device, // { privateKey, publicKey, didKey } — the peer holds THIS
    rootDidKey: genesis.didKey, // the root (rotation / recovery) key's did:key
    rootPublicKey: genesis.publicKey,
    rotationKeys: genesis.signedOp.rotationKeys
  }
}

export { unsignedOp, didForCreateOp, opCid }
// PDS auth primitives — password hashing + HS256 session tokens. Pure and bare-safe:
// scrypt/hmac/sha256 are @noble/hashes (pure JS, no crypto global), randomness comes from
// hypercore-crypto (bare-native via sodium). No I/O — the caller owns storage + clock.
//
// This is the ONLY auth the bsky-facing HTTP membrane needs: a client calls createSession
// with {identifier,password}, gets an opaque accessJwt, and presents it as `Authorization:
// Bearer` on writes. The PDS verifies the HMAC + expiry and reads `sub` (the repo DID).
// Standard atproto shape, so any @atproto/api client works unchanged.

import { scrypt } from '@noble/hashes/scrypt'
import { hmac } from '@noble/hashes/hmac'
import { sha256 } from '@noble/hashes/sha2'
import { secp256k1 } from '@noble/curves/secp256k1'
import { randomBytes } from 'hypercore-crypto'

const enc = new TextEncoder()
const dec = new TextDecoder()

// scrypt work factor — ~16 MiB, interactive-login appropriate. Embedded in the stored
// string so the params can evolve without breaking existing hashes.
const SCRYPT = { N: 16384, r: 8, p: 1, dkLen: 32 }

// ---- base64url (JWT segments) — base64 is universally supported (node + bare-buffer);
// the +/ -> -_ transform makes it url-safe without needing 'base64url' encoder support. ----
export function b64url (bytes) {
  return Buffer.from(bytes).toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
}
export function b64urlToBytes (str) {
  let s = str.replace(/-/g, '+').replace(/_/g, '/')
  while (s.length % 4) s += '='
  return new Uint8Array(Buffer.from(s, 'base64'))
}

function hex (bytes) { return Buffer.from(bytes).toString('hex') }
function fromHex (str) { return new Uint8Array(Buffer.from(str, 'hex')) }

// Constant-time equality — never leak match progress via early return.
export function timingSafeEqual (a, b) {
  if (a.length !== b.length) return false
  let d = 0
  for (let i = 0; i < a.length; i++) d |= a[i] ^ b[i]
  return d === 0
}

// ---- passwords ----
// Stored form: `scrypt$<N>$<r>$<p>$<saltHex>$<hashHex>`.
export function hashPassword (password, { salt } = {}) {
  const s = salt || randomBytes(16)
  const h = scrypt(enc.encode(password), s, SCRYPT)
  return `scrypt$${SCRYPT.N}$${SCRYPT.r}$${SCRYPT.p}$${hex(s)}$${hex(h)}`
}

export function verifyPassword (password, stored) {
  if (typeof stored !== 'string' || !stored.startsWith('scrypt$')) return false
  const parts = stored.split('$')
  if (parts.length !== 6) return false
  const N = parseInt(parts[1], 10)
  const r = parseInt(parts[2], 10)
  const p = parseInt(parts[3], 10)
  const salt = fromHex(parts[4])
  const expect = fromHex(parts[5])
  const got = scrypt(enc.encode(password), salt, { N, r, p, dkLen: expect.length })
  return timingSafeEqual(got, expect)
}

// ---- HS256 JWTs ----
function segment (obj) { return b64url(enc.encode(JSON.stringify(obj))) }

export function signJwt (payload, secret) {
  const head = segment({ alg: 'HS256', typ: 'JWT' })
  const body = segment(payload)
  const signingInput = `${head}.${body}`
  const sig = hmac(sha256, secret, enc.encode(signingInput))
  return `${signingInput}.${b64url(sig)}`
}

// Verify signature + expiry (nowSec = current time in epoch seconds). Throws a typed
// Error ({ status, error }) on any failure so the membrane can map it to an XRPC error.
export function verifyJwt (token, secret, { nowSec } = {}) {
  const parts = typeof token === 'string' ? token.split('.') : []
  if (parts.length !== 3) throw authError(401, 'AuthMissing', 'malformed token')
  const signingInput = `${parts[0]}.${parts[1]}`
  const expected = hmac(sha256, secret, enc.encode(signingInput))
  const got = b64urlToBytes(parts[2])
  if (!timingSafeEqual(got, expected)) throw authError(401, 'InvalidToken', 'bad signature')
  let payload
  try { payload = JSON.parse(dec.decode(b64urlToBytes(parts[1]))) } catch { throw authError(401, 'InvalidToken', 'bad payload') }
  const now = nowSec != null ? nowSec : Math.floor(Date.now() / 1000)
  if (payload.exp != null && now >= payload.exp) throw authError(401, 'ExpiredToken', 'token expired')
  return payload
}

// ---- ES256K signed assertions — the key-native login (also atproto's service-auth
// shape). A caller proves control of an account's atproto signing key by signing a
// short-lived assertion; the PDS verifies against the key already published in the DID,
// so NO secret is stored. This is the P2P trust root (key possession) brought to the
// HTTP edge — the same key that signs the repo's commits. ----
export function signAssertion (payload, privKey) {
  const head = segment({ alg: 'ES256K', typ: 'JWT' })
  const body = segment(payload)
  const signingInput = `${head}.${body}`
  const sig = secp256k1.sign(sha256(enc.encode(signingInput)), privKey, { lowS: true }).toCompactRawBytes()
  return `${signingInput}.${b64url(sig)}`
}

// Verify signature + expiry against a compressed secp256k1 public key. Throws typed.
export function verifyAssertion (token, pubKeyCompressed, { nowSec } = {}) {
  const parts = typeof token === 'string' ? token.split('.') : []
  if (parts.length !== 3) throw authError(401, 'AuthMissing', 'malformed assertion')
  const signingInput = `${parts[0]}.${parts[1]}`
  let okSig = false
  try { okSig = secp256k1.verify(b64urlToBytes(parts[2]), sha256(enc.encode(signingInput)), pubKeyCompressed, { lowS: true }) } catch { okSig = false }
  if (!okSig) throw authError(401, 'InvalidToken', 'bad assertion signature')
  let payload
  try { payload = JSON.parse(dec.decode(b64urlToBytes(parts[1]))) } catch { throw authError(401, 'InvalidToken', 'bad assertion payload') }
  const now = nowSec != null ? nowSec : Math.floor(Date.now() / 1000)
  if (payload.exp != null && now >= payload.exp) throw authError(401, 'ExpiredToken', 'assertion expired')
  return payload
}

// Decode a JWT/assertion segment (header or claims) WITHOUT verifying — used to read the
// issuer before we know which key to verify against. null on malformed input.
export function decodeSegment (seg) {
  try { return JSON.parse(dec.decode(b64urlToBytes(seg))) } catch { return null }
}

export function parseBearer (authHeader) {
  if (typeof authHeader !== 'string') return null
  const m = authHeader.match(/^Bearer\s+(.+)$/i)
  return m ? m[1].trim() : null
}

export function authError (status, error, message) {
  const e = new Error(message || error)
  e.status = status
  e.error = error
  return e
}

export const ACCESS_SCOPE = 'com.atproto.access'
export const REFRESH_SCOPE = 'com.atproto.refresh'
// keet-identity-key device chain — the P2P-verifiable half of device attestation.
//
// Runs in PARALLEL to the atproto PLC authority (device-attestation.js). atproto's
// rotationKeys/PLC-op-log carry the FEDERATION-visible authority (secp256k1); this keet
// chain carries the authority OUR P2P world verifies (Ed25519). Both anchor on the same
// root identity and vouch for the same device.
//
// Shape (from keet-identity-key): a proof is `{ identity, epoch, chain: [{publicKey,
// signature}], data? }`. `bootstrap` attests a device pubkey under the root identity;
// `attestData` lets the (leaf) device sign arbitrary data — here, the atproto DID — so a
// verifier learns "root → device → this device vouches for did:plc:…". `verify` walks the
// chain back to the identity and checks the data signature.

import IdentityKey from 'keet-identity-key'
import b4a from 'b4a'

// The device's keet-world Ed25519 keypair (derived from the device seed) — distinct from
// its secp256k1 atproto signing key. This is the device's identity in the keet chain.
export async function deviceKeetKeyPair (mnemonic, seed) {
  const idk = await IdentityKey.from({ mnemonic, seed })
  return idk.identityKeyPair // { publicKey, secretKey }
}

// The root identity's Ed25519 public key — the anchor every chain must resolve to.
export async function rootIdentityPublicKey (mnemonic, seed) {
  const idk = await IdentityKey.from({ mnemonic, seed })
  return b4a.from(idk.identityPublicKey)
}

// Root identity attests a device's Ed25519 public key → an encoded proof chain.
export async function attestDeviceChain ({ rootMnemonic, rootSeed, devicePublicKey }) {
  return IdentityKey.bootstrap({ mnemonic: rootMnemonic, seed: rootSeed }, devicePublicKey)
}

// An ALREADY-ATTESTED device attests ANOTHER device, extending the chain: root → parent → child.
// keet's attestDevice signs { epoch, identity, device } with the PARENT's keypair and pushes
// { publicKey, signature } onto the parent's chain, so the result still resolves to the same root
// identity and the same epoch — a chained device passes the identical admission gate and the identical
// minimum-epoch receipt check as a root-attested one.
//
// WHY THIS MATTERS OPERATIONALLY: admitting a new device to a room needs a proof anchored at the room's
// root identity, and attestDeviceChain above needs the ROOT MNEMONIC — which is deliberately not stored
// on any node (config.js: a device "must never hold" it). Read alone, that makes adding a co-owner
// impossible without recovering a secret nobody kept. It is not: an existing attested device already has
// everything required to vouch for the next one. Only the root's PUBLIC key is needed to verify.
//
// parentKeyPair: the attesting device's Ed25519 identity keypair (deviceKeetKeyPair of its mnemonic).
// parentProof: that device's own proof (root-attested, or itself chained — chains nest).
export function attestDeviceViaDevice ({ parentKeyPair, parentProof, devicePublicKey }) {
  if (!parentKeyPair || !parentProof || !devicePublicKey) throw new Error('attestDeviceViaDevice: parentKeyPair, parentProof, devicePublicKey required')
  // Pass the proof as BYTES: keet decodes a fresh copy, so the caller's proof is never mutated by the
  // chain.push inside attestDevice (it would otherwise grow the parent's own proof on every call).
  const proof = b4a.isBuffer(parentProof) ? parentProof : b4a.from(parentProof)
  return IdentityKey.attestDevice(b4a.from(devicePublicKey), parentKeyPair, proof)
}

// The attested (leaf) device vouches for the atproto DID by signing it as attested data,
// extending the proof with `proof.data`. Result: root → device → vouches-for(did).
export function attestAtprotoBinding ({ deviceKeyPair, did, proof }) {
  return IdentityKey.attestData(b4a.from(did), deviceKeyPair, proof)
}

// Verify the full binding: the chain resolves to the root identity AND the device vouched
// for exactly this DID. Returns { receipt, identityPublicKey, devicePublicKey } or null.
export function verifyAtprotoBinding ({ proof, did, expectedIdentity, expectedDevice }) {
  return IdentityKey.verify(proof, b4a.from(did), { expectedIdentity, expectedDevice })
}
// did:key encoding/decoding for the two curves atproto accepts.
//
//   did:key:z<base58btc( <multicodec-varint> ++ <compressed-pubkey> )>
//
// Multicodec key-type prefixes (unsigned-varint):
//   secp256k1-pub = 0xe7   -> varint [0xe7, 0x01]   -> did:key:zQ3s...
//   p256-pub      = 0x1200 -> varint [0x80, 0x24]   -> did:key:zDna...
//
// The pubkey is the 33-byte SEC1 compressed point (0x02/0x03 ++ x). This matches
// @atproto/crypto's formatDidKey. Validated by the P-256 golden round-trip test.

import { base58btc } from 'multiformats/bases/base58'

export const CURVE_SECP256K1 = 'secp256k1'
export const CURVE_P256 = 'p256'

const MULTICODEC = {
  [CURVE_SECP256K1]: 0xe7,
  [CURVE_P256]: 0x1200
}
const BY_CODE = { 0xe7: CURVE_SECP256K1, 0x1200: CURVE_P256 }

function varintEncode (n) {
  const out = []
  while (n >= 0x80) { out.push((n & 0x7f) | 0x80); n >>>= 7 }
  out.push(n)
  return Uint8Array.from(out)
}

function varintDecode (bytes) {
  let n = 0, shift = 0, i = 0
  for (;;) {
    const b = bytes[i++]
    n |= (b & 0x7f) << shift
    if ((b & 0x80) === 0) break
    shift += 7
  }
  return { code: n >>> 0, length: i }
}

// compressed pubkey bytes (33) -> did:key string
export function encodeDidKey (curve, compressedPubkey) {
  const code = MULTICODEC[curve]
  if (code === undefined) throw new Error(`unsupported curve: ${curve}`)
  const prefix = varintEncode(code)
  const bytes = new Uint8Array(prefix.length + compressedPubkey.length)
  bytes.set(prefix, 0)
  bytes.set(compressedPubkey, prefix.length)
  return `did:key:${base58btc.encode(bytes)}` // base58btc.encode already prepends 'z'
}

// did:key string -> { curve, pubkey (compressed bytes) }
export function decodeDidKey (didKey) {
  if (!didKey.startsWith('did:key:')) throw new Error('not a did:key')
  const mb = didKey.slice('did:key:'.length)
  const bytes = base58btc.decode(mb) // expects leading 'z'
  const { code, length } = varintDecode(bytes)
  const curve = BY_CODE[code]
  if (!curve) throw new Error(`unknown multicodec 0x${code.toString(16)}`)
  return { curve, pubkey: bytes.slice(length) }
}
// did:plc computation — byte-exact.
//
// A did:plc is derived from its *genesis* operation:
//   did = "did:plc:" + base32( sha256( dag-cbor(signedGenesisOp) ) ).slice(0, 24)
//
// The hash is over the SIGNED op (the `sig` field is included). DAG-CBOR gives a
// canonical byte layout (sorted map keys, definite lengths), so the DID is a pure
// function of the op. base32 here is RFC-4648 lowercase, NO padding, and NO
// multibase prefix (did-method-plc uses raw base32, not multiformats' 'b'-prefixed
// multibase form) — see the golden-vector test.
//
// Reference: https://github.com/did-method-plc/did-method-plc (didForCreateOp)

import * as dagCbor from '@ipld/dag-cbor'
import { sha256 } from '@noble/hashes/sha2'
import { base32 } from 'multiformats/bases/base32'
import { CID } from 'multiformats/cid'
import * as Digest from 'multiformats/hashes/digest'

// multiformats' base32.encode returns a multibase string prefixed with 'b'.
// did:plc uses the raw base32 alphabet output, so strip the leading multibase char.
function rawBase32 (bytes) {
  const multibase = base32.encode(bytes) // 'b' + <rfc4648-lower-nopad>
  return multibase.slice(1)
}

// Canonical DAG-CBOR bytes for an operation object.
export function encodeOp (op) {
  return dagCbor.encode(op)
}

// Compute the did:plc for a signed genesis operation.
export function didForCreateOp (signedOp, truncate = 24) {
  const bytes = encodeOp(signedOp)
  const hash = sha256(bytes)
  const b32 = rawBase32(hash)
  return `did:plc:${b32.slice(0, truncate)}`
}

// The unsigned operation is everything except `sig`. did:plc signs the DAG-CBOR of
// the unsigned op; the signature is then attached and the DID hashes the signed form.
export function unsignedOp (op) {
  const { sig, ...rest } = op // eslint-disable-line no-unused-vars
  return rest
}

// The CID of a SIGNED operation — CIDv1, dag-cbor codec (0x71), sha2-256 multihash
// (0x12), rendered as a base32 string. This is the value the NEXT operation carries in
// its `prev` field to chain the PLC op-log (genesis has `prev: null`). Same encoding as
// atproto-repo/lib/cid.js cidForBytesSync, over DAG-CBOR(signedOp). Reference: the
// did-method-plc CID = CID.create(1, 0x71, sha256(cborEncode(op))).
export function opCid (signedOp) {
  const bytes = encodeOp(signedOp)
  const digest = Digest.create(0x12, sha256(bytes))
  return CID.createV1(dagCbor.code, digest).toString()
}
// Attaching an identity to hosting, and detaching it again — the holder's half of the invite ceremony.
//
// ── WHY THIS IS A SEPARATE ACT FROM CREATING AN IDENTITY ─────────────────────────────────────────
// buildGenesisOp makes handle and pdsUrl optional, so an identity can be minted P2P-only: it names
// nobody's infrastructure and needs nobody's permission to exist (hyper-social #54 §8). What is scarce
// is not identity, it is somebody's servers. So being fronted by a membrane (pds.7rnx.net) or a
// fediverse bridge (ap.7rnx.net) is gated by an invite, and accepting one is THIS: a later PLC update
// adding a domain handle and a service endpoint.
//
// The ordering is forced rather than chosen. An update op must chain onto a genesis already in the log
// (checkUpdateOp wants prev == the head CID), so genesis is submitted at creation and the invite extends
// it. That is what keeps creation genuinely free and joining genuinely reversible.
//
// ── ⛔ THE OPERATOR CANNOT DO THIS FOR YOU ───────────────────────────────────────────────────────
// A PLC update must be signed by a CURRENT rotation key, and createSwarmIdentity puts exactly one there:
// the root recovery key, which never leaves its owner (device-node.js: a device receives the signing key
// and NEVER the root, "so it can't derive the recovery key or self-recover"). An operator can grant
// infrastructure and can add a DID to the bridge's fronted set, but cannot alter someone's identity
// document. The ceremony is two-sided by construction, not by policy — which is the property that makes
// "our infrastructure" a service rather than custody.
//
// ── SHAPE, FOR THE UI THAT WILL DRIVE IT ─────────────────────────────────────────────────────────
// These are OFFLINE and PURE: they take the current head op and return a signed op. Nothing here
// resolves, submits, or talks to a network — PlcDirectory.submitUpdate does that, and it is deliberately
// somebody else's call, because it is the irreversible half.
//
// So an atproto-bridge web UI splits cleanly: the UI issues the invite and knows the handle + endpoint;
// the HOLDER (a phone unlocking its vault, or an operator with the mnemonic) calls these and submits.
// Neither side can complete the ceremony alone.
//
// A PLC op REPLACES the whole document state — it is not a patch — so every field not being changed must
// be carried forward explicitly. Dropping one silently removes a key or a service.

import { buildUpdateOp, signOp, keyFromPrivate } from './atproto-identity.js'

const PDS_SERVICE = 'atproto_pds'
const PDS_TYPE = 'AtprotoPersonalDataServer'

const aka = (handle) => 'at://' + String(handle).replace(/^at:\/\//, '')

/**
 * Refuse locally what the directory would refuse remotely.
 *
 * Signing with a key that is not a current rotation key produces an op the directory rejects, and
 * finding that out by submitting is a wasted round trip against a permanent public log — and a
 * confusing one, because the rejection names a CID, not the mistake. The likely wrong key is the
 * #atproto signing key, which a device legitimately holds and which has zero PLC authority.
 */
function assertRotationSigner (prevSignedOp, signerPrivateKey) {
  const rot = (prevSignedOp && prevSignedOp.rotationKeys) || []
  let didKey = null
  try { didKey = keyFromPrivate(signerPrivateKey).didKey } catch { didKey = null }
  if (!didKey || !rot.includes(didKey)) {
    throw new Error(
      'hosting: signer is not a current rotation key of this identity — a PLC update must be signed by ' +
      'the recovery key, not the #atproto signing key'
    )
  }
}

/** Sign an unsigned op, after checking the signer may. */
function finish (prevSignedOp, unsigned, signerPrivateKey) {
  assertRotationSigner(prevSignedOp, signerPrivateKey)
  return { ...unsigned, sig: signOp(unsigned, signerPrivateKey) }
}

/**
 * Accept hosting: claim `handle` and name `pdsUrl` as this identity's PDS.
 *
 * Also the MOVE operation — pointing at a different host is one op, not a detach plus an attach, because
 * two ops would leave the identity briefly homeless in a log that never forgets.
 *
 * @param {object}  opts
 * @param {object}  opts.prevSignedOp      the current head op (genesis, or the last update)
 * @param {string}  opts.handle            e.g. 'flaky.7rnx.net'
 * @param {string}  opts.pdsUrl            e.g. 'https://pds.7rnx.net'
 * @param {Uint8Array} opts.signerPrivateKey  a CURRENT rotation key — the root recovery key
 * @returns {object} a signed plc_operation, ready for PlcDirectory.submitUpdate
 */
export function attachHosting ({ prevSignedOp, handle, pdsUrl, signerPrivateKey } = {}) {
  if (!prevSignedOp) throw new Error('attachHosting: prevSignedOp required')
  if (!handle) throw new Error('attachHosting: handle required')
  if (!pdsUrl) throw new Error('attachHosting: pdsUrl required')

  const prevServices = prevSignedOp.services || {}
  const prevAka = prevSignedOp.alsoKnownAs || []
  const wantAka = [aka(handle)]

  // ⛔ REFUSE A NO-OP. Every accepted op is a permanent, public append to a global log. Re-running an
  // invite that already succeeded must not add a second identical entry to someone's history — and a
  // web UI WILL re-run it, because a user who does not see a change presses the button again.
  const already = prevServices[PDS_SERVICE] &&
    prevServices[PDS_SERVICE].endpoint === pdsUrl &&
    prevAka.length === 1 && prevAka[0] === wantAka[0]
  if (already) {
    throw new Error('attachHosting: this identity is already hosted at ' + pdsUrl + ' as ' + handle + ' — nothing to append')
  }

  // The handle REPLACES rather than accumulates: atproto treats the first alias as the identity's handle,
  // and an identity that silently kept every host it ever tried would advertise handles that no longer
  // resolve. Other services are carried forward — a community DID's feed generator and labeler are not
  // this operation's business.
  const unsigned = buildUpdateOp({
    prevSignedOp,
    rotationDidKeys: prevSignedOp.rotationKeys,
    verificationMethods: prevSignedOp.verificationMethods,
    alsoKnownAs: wantAka,
    services: { ...prevServices, [PDS_SERVICE]: { type: PDS_TYPE, endpoint: pdsUrl } }
  })
  return finish(prevSignedOp, unsigned, signerPrivateKey)
}

/**
 * Leave hosting: release the handle and stop naming a PDS, returning the identity to P2P-only.
 *
 * This is what makes accepting an invite reversible, and it is why the invite gates INFRASTRUCTURE
 * rather than existence: leaving costs the identity nothing it was born with. The DID, its keys and its
 * repo are untouched — only the document's claims about where to reach it change.
 *
 * ⚠ Reversible is not retroactive. Content already replicated to a membrane or a relay has been read,
 * and detaching does not unsay it. This changes where the network is TOLD to look, nothing more.
 */
export function detachHosting ({ prevSignedOp, signerPrivateKey } = {}) {
  if (!prevSignedOp) throw new Error('detachHosting: prevSignedOp required')

  const services = { ...(prevSignedOp.services || {}) }
  const hadPds = !!services[PDS_SERVICE]
  delete services[PDS_SERVICE]
  const hadAka = (prevSignedOp.alsoKnownAs || []).length > 0
  if (!hadPds && !hadAka) {
    throw new Error('detachHosting: this identity is already P2P-only — nothing to append')
  }

  const unsigned = buildUpdateOp({
    prevSignedOp,
    rotationDidKeys: prevSignedOp.rotationKeys,
    verificationMethods: prevSignedOp.verificationMethods,
    alsoKnownAs: [],
    services
  })
  return finish(prevSignedOp, unsigned, signerPrivateKey)
}
// vault.js — the recovery secret, encrypted so it can be replicated.
//
// WHAT THIS IS FOR. Creating an identity phone-first means minting a did:plc, and whoever holds its
// recovery material can rotate its keys for ever. That secret has to reach the owner's other devices
// somehow, and every obvious channel is worse than this one: retyping 24 words on a handset invites
// transcription errors, a screenshot lands in a cloud photo library, and shipping it in plaintext to
// "attested devices" makes device attestation exactly as strong as the root key it is meant to protect.
//
// ⛔ THE PASSPHRASE IS NEVER STORED, ANYWHERE. That is the whole security argument: the sealed blob is
// designed to be replicated over the same P2P substrate as everything else, so it WILL end up on disks
// we do not control and in the hands of anyone who later joins the identity. It is safe there only
// because it is useless without something that lives in a person's head. If a future change writes the
// passphrase to disk to "make unlock smoother", this file stops being a vault and becomes a very
// elaborate copy of the mnemonic.
//
// ⛔ SEALING IS NOT REVOCATION. A device that once unlocked this vault knows the secret and will keep
// knowing it after you remove the device — see app/Pair.jsx in favela-android, which says the same thing
// about the signing key: removing a device stops it being ADMITTED, it cannot make it forget. The only
// thing that devalues a leaked recovery secret is ROTATING the identity's keys on the PLC log (see
// plc-directory.js rotateVerificationMethodOnChain). This module is how a NEW secret reaches the
// remaining devices; it is not what makes an old one harmless.
//
// ⛔ BOUND TO THE DID. The DID goes in as AEAD additional data, so a blob sealed for one identity cannot
// be silently served in place of another's. A vault that opens under the wrong identity is a vault that
// can be swapped.
//
// Argon2id via sodium-native, XChaCha20-Poly1305 for the seal. Both parameters and salt travel INSIDE
// the envelope: a phone and a workstation have very different tolerances for a KDF, and cost is a thing
// we will want to raise later without stranding blobs sealed today.
import sodium from 'sodium-native'
import b4a from 'b4a'

export const VAULT_VERSION = 1

// Interactive memory (64 MiB) with moderate ops. A handset is the constrained case and this has to run
// there without the OS killing the app; the ops cost carries the weight instead. Recorded per-envelope,
// so raising either later leaves old blobs openable.
const DEFAULT_OPSLIMIT = sodium.crypto_pwhash_OPSLIMIT_MODERATE
const DEFAULT_MEMLIMIT = sodium.crypto_pwhash_MEMLIMIT_INTERACTIVE

const b64 = (buf) => b4a.toString(buf, 'base64')
const unb64 = (s) => b4a.from(s, 'base64')

function deriveKey (passphrase, salt, opslimit, memlimit) {
  const key = b4a.alloc(sodium.crypto_aead_xchacha20poly1305_ietf_KEYBYTES)
  // ⛔ NOT a plain hash. A passphrase people can remember is low-entropy by definition, so the only
  // thing standing between a replicated blob and an offline guessing attack is the KDF's cost. Argon2id
  // is memory-hard, which is what makes that cost real on a GPU too.
  sodium.crypto_pwhash(
    key,
    b4a.from(String(passphrase), 'utf8'),
    salt,
    opslimit,
    memlimit,
    sodium.crypto_pwhash_ALG_ARGON2ID13
  )
  return key
}

/**
 * Seal a recovery secret for one identity.
 *
 * @param {{secret: string, passphrase: string, did: string, opslimit?: number, memlimit?: number}} opts
 * @returns {object} a JSON-safe envelope, safe to replicate
 */
export function sealVault ({ secret, passphrase, did, opslimit = DEFAULT_OPSLIMIT, memlimit = DEFAULT_MEMLIMIT } = {}) {
  if (typeof secret !== 'string' || !secret) throw new Error('secret required')
  // A vault with no passphrase is a file with extra steps, and would be worse than none: it would LOOK
  // encrypted to everyone downstream, including to whoever decides where to replicate it.
  if (typeof passphrase !== 'string' || !passphrase) throw new Error('passphrase required')
  if (typeof did !== 'string' || !did.startsWith('did:')) throw new Error('did required')

  const salt = b4a.alloc(sodium.crypto_pwhash_SALTBYTES)
  sodium.randombytes_buf(salt)
  const nonce = b4a.alloc(sodium.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES)
  sodium.randombytes_buf(nonce)

  const key = deriveKey(passphrase, salt, opslimit, memlimit)
  const message = b4a.from(secret, 'utf8')
  const ct = b4a.alloc(message.length + sodium.crypto_aead_xchacha20poly1305_ietf_ABYTES)
  sodium.crypto_aead_xchacha20poly1305_ietf_encrypt(ct, message, b4a.from(did, 'utf8'), null, nonce, key)
  sodium.sodium_memzero(key)
  sodium.sodium_memzero(message)

  return {
    v: VAULT_VERSION,
    did,
    kdf: { alg: 'argon2id13', opslimit, memlimit, salt: b64(salt) },
    aead: 'xchacha20poly1305-ietf',
    nonce: b64(nonce),
    ct: b64(ct)
  }
}

/**
 * Open a sealed vault. Throws on a wrong passphrase, a tampered blob, or the wrong identity — all three
 * are the same AEAD failure and are deliberately NOT distinguished in the message: telling a caller
 * which one failed tells an attacker which half they got right.
 */
export function openVault ({ envelope, passphrase, did } = {}) {
  const e = envelope
  if (!e || typeof e !== 'object') throw new Error('envelope required')
  if (e.v !== VAULT_VERSION) throw new Error('unsupported vault version: ' + e.v)
  if (e.aead !== 'xchacha20poly1305-ietf') throw new Error('unsupported aead: ' + e.aead)
  if (!e.kdf || e.kdf.alg !== 'argon2id13') throw new Error('unsupported kdf: ' + (e.kdf && e.kdf.alg))
  if (typeof passphrase !== 'string' || !passphrase) throw new Error('passphrase required')

  // The caller says which identity it BELIEVES this vault is for, and the AEAD refuses if it disagrees.
  // Defaulting to the envelope's own `did` would let a swapped blob authenticate itself.
  const forDid = typeof did === 'string' && did ? did : e.did
  if (typeof forDid !== 'string' || !forDid.startsWith('did:')) throw new Error('did required')

  const salt = unb64(e.kdf.salt)
  const nonce = unb64(e.nonce)
  const ct = unb64(e.ct)
  if (salt.length !== sodium.crypto_pwhash_SALTBYTES) throw new Error('malformed vault: salt')
  if (nonce.length !== sodium.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES) throw new Error('malformed vault: nonce')
  if (ct.length < sodium.crypto_aead_xchacha20poly1305_ietf_ABYTES) throw new Error('malformed vault: ciphertext')

  const key = deriveKey(passphrase, salt, e.kdf.opslimit, e.kdf.memlimit)
  const out = b4a.alloc(ct.length - sodium.crypto_aead_xchacha20poly1305_ietf_ABYTES)
  try {
    sodium.crypto_aead_xchacha20poly1305_ietf_decrypt(out, null, ct, b4a.from(forDid, 'utf8'), nonce, key)
  } catch {
    throw new Error('could not open the vault')
  } finally {
    sodium.sodium_memzero(key)
  }
  const secret = b4a.toString(out, 'utf8')
  sodium.sodium_memzero(out)
  return secret
}

/**
 * Re-seal an already-open secret under a new passphrase.
 *
 * Separate from sealVault so the caller cannot accidentally change WHICH identity a vault is for while
 * changing its passphrase — the did is carried over, not re-supplied.
 */
export function rekeyVault ({ envelope, passphrase, newPassphrase, did, ...rest } = {}) {
  const secret = openVault({ envelope, passphrase, did })
  return sealVault({ secret, passphrase: newPassphrase, did: (typeof did === 'string' && did) ? did : envelope.did, ...rest })
}
{
  "name": "@ipld/dag-cbor",
  "version": "9.2.7",
  "description": "JS implementation of DAG-CBOR",
  "author": "Rod <rod@vagg.org> (http://r.va.gg/)",
  "license": "Apache-2.0 OR MIT",
  "homepage": "https://github.com/ipld/js-dag-cbor#readme",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/ipld/js-dag-cbor.git"
  },
  "bugs": {
    "url": "https://github.com/ipld/js-dag-cbor/issues"
  },
  "publishConfig": {
    "access": "public",
    "provenance": true
  },
  "keywords": [
    "ipfs",
    "ipld",
    "multiformats"
  ],
  "type": "module",
  "types": "./dist/src/index.d.ts",
  "typesVersions": {
    "*": {
      "*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ],
      "src/*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ]
    }
  },
  "files": [
    "src",
    "dist",
    "!dist/test",
    "!**/*.tsbuildinfo"
  ],
  "exports": {
    ".": {
      "types": "./dist/src/index.d.ts",
      "import": "./src/index.js",
      "module-sync": "./src/index.js"
    }
  },
  "release": {
    "branches": [
      "master"
    ],
    "plugins": [
      [
        "@semantic-release/commit-analyzer",
        {
          "preset": "conventionalcommits",
          "releaseRules": [
            {
              "breaking": true,
              "release": "major"
            },
            {
              "revert": true,
              "release": "patch"
            },
            {
              "type": "feat",
              "release": "minor"
            },
            {
              "type": "fix",
              "release": "patch"
            },
            {
              "type": "docs",
              "release": "patch"
            },
            {
              "type": "test",
              "release": "patch"
            },
            {
              "type": "deps",
              "release": "patch"
            },
            {
              "scope": "no-release",
              "release": false
            }
          ]
        }
      ],
      [
        "@semantic-release/release-notes-generator",
        {
          "preset": "conventionalcommits",
          "presetConfig": {
            "types": [
              {
                "type": "feat",
                "section": "Features"
              },
              {
                "type": "fix",
                "section": "Bug Fixes"
              },
              {
                "type": "chore",
                "section": "Trivial Changes"
              },
              {
                "type": "docs",
                "section": "Documentation"
              },
              {
                "type": "deps",
                "section": "Dependencies"
              },
              {
                "type": "test",
                "section": "Tests"
              }
            ]
          }
        }
      ],
      "@semantic-release/changelog",
      "@semantic-release/npm",
      "@semantic-release/github",
      [
        "@semantic-release/git",
        {
          "assets": [
            "CHANGELOG.md",
            "package.json"
          ]
        }
      ]
    ]
  },
  "scripts": {
    "clean": "aegir clean",
    "lint": "aegir lint",
    "build": "aegir build",
    "release": "aegir release",
    "test": "npm run lint && aegir test",
    "test:ts": "npm run test --prefix test/ts-use",
    "test:node": "aegir test -t node --cov",
    "test:chrome": "aegir test -t browser --cov",
    "test:chrome-webworker": "aegir test -t webworker",
    "test:firefox": "aegir test -t browser -- --browser firefox",
    "test:firefox-webworker": "aegir test -t webworker -- --browser firefox",
    "test:electron-main": "aegir test -t electron-main",
    "dep-check": "aegir dep-check"
  },
  "dependencies": {
    "cborg": "^5.0.1",
    "multiformats": "^13.1.0"
  },
  "devDependencies": {
    "@ipld/garbage": "^6.0.0",
    "aegir": "^48.0.1"
  }
}
import * as cborg from 'cborg'
import { CID } from 'multiformats/cid'

// https://github.com/ipfs/go-ipfs/issues/3570#issuecomment-273931692
const CID_CBOR_TAG = 42

/**
 * @template T
 * @typedef {import('multiformats/codecs/interface').ByteView<T>} ByteView
 */

/**
 * @template T
 * @typedef {import('multiformats/codecs/interface').ArrayBufferView<T>} ArrayBufferView
 */

/**
 * @template T
 * @param {ByteView<T> | ArrayBufferView<T>} buf
 * @returns {ByteView<T>}
 */
export function toByteView (buf) {
  if (buf instanceof ArrayBuffer) {
    return new Uint8Array(buf, 0, buf.byteLength)
  }

  return buf
}

/**
 * cidEncoder will receive all Objects during encode, it needs to filter out
 * anything that's not a CID and return `null` for that so it's encoded as
 * normal.
 *
 * @param {any} obj
 * @returns {cborg.Token[]|null}
 */
function cidEncoder (obj) {
  if (obj.asCID !== obj && obj['/'] !== obj.bytes) {
    return null // any other kind of object
  }
  const cid = CID.asCID(obj)
  /* c8 ignore next 4 */
  // very unlikely case, and it'll probably throw a recursion error in cborg
  if (!cid) {
    return null
  }
  const bytes = new Uint8Array(cid.bytes.byteLength + 1)
  bytes.set(cid.bytes, 1) // prefix is 0x00, for historical reasons
  return [
    new cborg.Token(cborg.Type.tag, CID_CBOR_TAG),
    new cborg.Token(cborg.Type.bytes, bytes)
  ]
}

// eslint-disable-next-line jsdoc/require-returns-check
/**
 * Intercept all `undefined` values from an object walk and reject the entire
 * object if we find one.
 *
 * @returns {null}
 */
function undefinedEncoder () {
  throw new Error('`undefined` is not supported by the IPLD Data Model and cannot be encoded')
}

/**
 * Intercept all `number` values from an object walk and reject the entire
 * object if we find something that doesn't fit the IPLD data model (NaN &
 * Infinity).
 *
 * @param {number} num
 * @returns {null}
 */
function numberEncoder (num) {
  if (Number.isNaN(num)) {
    throw new Error('`NaN` is not supported by the IPLD Data Model and cannot be encoded')
  }
  if (num === Infinity || num === -Infinity) {
    throw new Error('`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded')
  }
  return null
}

/**
 * @param {Map<any, any>} map
 * @returns {null}
 */
function mapEncoder (map) {
  for (const key of map.keys()) {
    if (typeof key !== 'string' || key.length === 0) {
      throw new Error('Non-string Map keys are not supported by the IPLD Data Model and cannot be encoded')
    }
  }
  return null
}

const _encodeOptions = {
  float64: true,
  typeEncoders: {
    Map: mapEncoder,
    Object: cidEncoder,
    undefined: undefinedEncoder,
    number: numberEncoder
  }
}

export const encodeOptions = {
  ..._encodeOptions,
  typeEncoders: {
    ..._encodeOptions.typeEncoders
  }
}

/**
 * @param {import('cborg').TagDecodeControl} decode
 * @returns {CID}
 */
function cidDecoder (decode) {
  const bytes = /** @type {Uint8Array} */ (decode())
  if (bytes[0] !== 0) {
    throw new Error('Invalid CID for CBOR tag 42; expected leading 0x00')
  }
  return CID.decode(bytes.subarray(1)) // ignore leading 0x00
}

const _decodeOptions = {
  allowIndefinite: false,
  coerceUndefinedToNull: true,
  allowNaN: false,
  allowInfinity: false,
  allowBigInt: true, // this will lead to BigInt for ints outside of
  // safe-integer range, which may surprise users
  strict: true,
  useMaps: false,
  rejectDuplicateMapKeys: true,
  /** @type {{ [tagNumber: number]: import('cborg').TagDecoder }} */
  tags: { [CID_CBOR_TAG]: cidDecoder }
}

export const decodeOptions = {
  ..._decodeOptions,
  tags: { ..._decodeOptions.tags }
}

export const name = 'dag-cbor'
export const code = 0x71

/**
 * @template T
 * @param {T} node
 * @returns {ByteView<T>}
 */
export const encode = (node) => cborg.encode(node, _encodeOptions)

/**
 * @template T
 * @param {ByteView<T> | ArrayBufferView<T>} data
 * @returns {T}
 */
export const decode = (data) => cborg.decode(toByteView(data), _decodeOptions)
/**
 * Utilities for short weierstrass curves, combined with noble-hashes.
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { weierstrass } from "./abstract/weierstrass.js";
/** connects noble-curves to noble-hashes */
export function getHash(hash) {
    return { hash };
}
/** @deprecated use new `weierstrass()` and `ecdsa()` methods */
export function createCurve(curveDef, defHash) {
    const create = (hash) => weierstrass({ ...curveDef, hash: hash });
    return { ...create(defHash), create };
}
//# sourceMappingURL=_shortw_utils.js.map/**
 * Methods for elliptic curve multiplication by scalars.
 * Contains wNAF, pippenger.
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { bitLen, bitMask, validateObject } from "../utils.js";
import { Field, FpInvertBatch, nLength, validateField } from "./modular.js";
const _0n = BigInt(0);
const _1n = BigInt(1);
export function negateCt(condition, item) {
    const neg = item.negate();
    return condition ? neg : item;
}
/**
 * Takes a bunch of Projective Points but executes only one
 * inversion on all of them. Inversion is very slow operation,
 * so this improves performance massively.
 * Optimization: converts a list of projective points to a list of identical points with Z=1.
 */
export function normalizeZ(c, points) {
    const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
    return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
}
function validateW(W, bits) {
    if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
        throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);
}
function calcWOpts(W, scalarBits) {
    validateW(W, scalarBits);
    const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero
    const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero
    const maxNumber = 2 ** W; // W=8 256
    const mask = bitMask(W); // W=8 255 == mask 0b11111111
    const shiftBy = BigInt(W); // W=8 8
    return { windows, windowSize, mask, maxNumber, shiftBy };
}
function calcOffsets(n, window, wOpts) {
    const { windowSize, mask, maxNumber, shiftBy } = wOpts;
    let wbits = Number(n & mask); // extract W bits.
    let nextN = n >> shiftBy; // shift number by W bits.
    // What actually happens here:
    // const highestBit = Number(mask ^ (mask >> 1n));
    // let wbits2 = wbits - 1; // skip zero
    // if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);
    // split if bits > max: +224 => 256-32
    if (wbits > windowSize) {
        // we skip zero, which means instead of `>= size-1`, we do `> size`
        wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.
        nextN += _1n; // +256 (carry)
    }
    const offsetStart = window * windowSize;
    const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero
    const isZero = wbits === 0; // is current window slice a 0?
    const isNeg = wbits < 0; // is current window slice negative?
    const isNegF = window % 2 !== 0; // fake random statement for noise
    const offsetF = offsetStart; // fake offset for noise
    return { nextN, offset, isZero, isNeg, isNegF, offsetF };
}
function validateMSMPoints(points, c) {
    if (!Array.isArray(points))
        throw new Error('array expected');
    points.forEach((p, i) => {
        if (!(p instanceof c))
            throw new Error('invalid point at index ' + i);
    });
}
function validateMSMScalars(scalars, field) {
    if (!Array.isArray(scalars))
        throw new Error('array of scalars expected');
    scalars.forEach((s, i) => {
        if (!field.isValid(s))
            throw new Error('invalid scalar at index ' + i);
    });
}
// Since points in different groups cannot be equal (different object constructor),
// we can have single place to store precomputes.
// Allows to make points frozen / immutable.
const pointPrecomputes = new WeakMap();
const pointWindowSizes = new WeakMap();
function getW(P) {
    // To disable precomputes:
    // return 1;
    return pointWindowSizes.get(P) || 1;
}
function assert0(n) {
    if (n !== _0n)
        throw new Error('invalid wNAF');
}
/**
 * Elliptic curve multiplication of Point by scalar. Fragile.
 * Table generation takes **30MB of ram and 10ms on high-end CPU**,
 * but may take much longer on slow devices. Actual generation will happen on
 * first call of `multiply()`. By default, `BASE` point is precomputed.
 *
 * Scalars should always be less than curve order: this should be checked inside of a curve itself.
 * Creates precomputation tables for fast multiplication:
 * - private scalar is split by fixed size windows of W bits
 * - every window point is collected from window's table & added to accumulator
 * - since windows are different, same point inside tables won't be accessed more than once per calc
 * - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)
 * - +1 window is neccessary for wNAF
 * - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication
 *
 * @todo Research returning 2d JS array of windows, instead of a single window.
 * This would allow windows to be in different memory locations
 */
export class wNAF {
    // Parametrized with a given Point class (not individual point)
    constructor(Point, bits) {
        this.BASE = Point.BASE;
        this.ZERO = Point.ZERO;
        this.Fn = Point.Fn;
        this.bits = bits;
    }
    // non-const time multiplication ladder
    _unsafeLadder(elm, n, p = this.ZERO) {
        let d = elm;
        while (n > _0n) {
            if (n & _1n)
                p = p.add(d);
            d = d.double();
            n >>= _1n;
        }
        return p;
    }
    /**
     * Creates a wNAF precomputation window. Used for caching.
     * Default window size is set by `utils.precompute()` and is equal to 8.
     * Number of precomputed points depends on the curve size:
     * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
     * - 𝑊 is the window size
     * - 𝑛 is the bitlength of the curve order.
     * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
     * @param point Point instance
     * @param W window size
     * @returns precomputed point tables flattened to a single array
     */
    precomputeWindow(point, W) {
        const { windows, windowSize } = calcWOpts(W, this.bits);
        const points = [];
        let p = point;
        let base = p;
        for (let window = 0; window < windows; window++) {
            base = p;
            points.push(base);
            // i=1, bc we skip 0
            for (let i = 1; i < windowSize; i++) {
                base = base.add(p);
                points.push(base);
            }
            p = base.double();
        }
        return points;
    }
    /**
     * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
     * More compact implementation:
     * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
     * @returns real and fake (for const-time) points
     */
    wNAF(W, precomputes, n) {
        // Scalar should be smaller than field order
        if (!this.Fn.isValid(n))
            throw new Error('invalid scalar');
        // Accumulators
        let p = this.ZERO;
        let f = this.BASE;
        // This code was first written with assumption that 'f' and 'p' will never be infinity point:
        // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,
        // there is negate now: it is possible that negated element from low value
        // would be the same as high element, which will create carry into next window.
        // It's not obvious how this can fail, but still worth investigating later.
        const wo = calcWOpts(W, this.bits);
        for (let window = 0; window < wo.windows; window++) {
            // (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise
            const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
            n = nextN;
            if (isZero) {
                // bits are 0: add garbage to fake point
                // Important part for const-time getPublicKey: add random "noise" point to f.
                f = f.add(negateCt(isNegF, precomputes[offsetF]));
            }
            else {
                // bits are 1: add to result point
                p = p.add(negateCt(isNeg, precomputes[offset]));
            }
        }
        assert0(n);
        // Return both real and fake points: JIT won't eliminate f.
        // At this point there is a way to F be infinity-point even if p is not,
        // which makes it less const-time: around 1 bigint multiply.
        return { p, f };
    }
    /**
     * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
     * @param acc accumulator point to add result of multiplication
     * @returns point
     */
    wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
        const wo = calcWOpts(W, this.bits);
        for (let window = 0; window < wo.windows; window++) {
            if (n === _0n)
                break; // Early-exit, skip 0 value
            const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
            n = nextN;
            if (isZero) {
                // Window bits are 0: skip processing.
                // Move to next window.
                continue;
            }
            else {
                const item = precomputes[offset];
                acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM
            }
        }
        assert0(n);
        return acc;
    }
    getPrecomputes(W, point, transform) {
        // Calculate precomputes on a first run, reuse them after
        let comp = pointPrecomputes.get(point);
        if (!comp) {
            comp = this.precomputeWindow(point, W);
            if (W !== 1) {
                // Doing transform outside of if brings 15% perf hit
                if (typeof transform === 'function')
                    comp = transform(comp);
                pointPrecomputes.set(point, comp);
            }
        }
        return comp;
    }
    cached(point, scalar, transform) {
        const W = getW(point);
        return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
    }
    unsafe(point, scalar, transform, prev) {
        const W = getW(point);
        if (W === 1)
            return this._unsafeLadder(point, scalar, prev); // For W=1 ladder is ~x2 faster
        return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
    }
    // We calculate precomputes for elliptic curve point multiplication
    // using windowed method. This specifies window size and
    // stores precomputed values. Usually only base point would be precomputed.
    createCache(P, W) {
        validateW(W, this.bits);
        pointWindowSizes.set(P, W);
        pointPrecomputes.delete(P);
    }
    hasCache(elm) {
        return getW(elm) !== 1;
    }
}
/**
 * Endomorphism-specific multiplication for Koblitz curves.
 * Cost: 128 dbl, 0-256 adds.
 */
export function mulEndoUnsafe(Point, point, k1, k2) {
    let acc = point;
    let p1 = Point.ZERO;
    let p2 = Point.ZERO;
    while (k1 > _0n || k2 > _0n) {
        if (k1 & _1n)
            p1 = p1.add(acc);
        if (k2 & _1n)
            p2 = p2.add(acc);
        acc = acc.double();
        k1 >>= _1n;
        k2 >>= _1n;
    }
    return { p1, p2 };
}
/**
 * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).
 * 30x faster vs naive addition on L=4096, 10x faster than precomputes.
 * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.
 * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.
 * @param c Curve Point constructor
 * @param fieldN field over CURVE.N - important that it's not over CURVE.P
 * @param points array of L curve points
 * @param scalars array of L scalars (aka secret keys / bigints)
 */
export function pippenger(c, fieldN, points, scalars) {
    // If we split scalars by some window (let's say 8 bits), every chunk will only
    // take 256 buckets even if there are 4096 scalars, also re-uses double.
    // TODO:
    // - https://eprint.iacr.org/2024/750.pdf
    // - https://tches.iacr.org/index.php/TCHES/article/view/10287
    // 0 is accepted in scalars
    validateMSMPoints(points, c);
    validateMSMScalars(scalars, fieldN);
    const plength = points.length;
    const slength = scalars.length;
    if (plength !== slength)
        throw new Error('arrays of points and scalars must have equal length');
    // if (plength === 0) throw new Error('array must be of length >= 2');
    const zero = c.ZERO;
    const wbits = bitLen(BigInt(plength));
    let windowSize = 1; // bits
    if (wbits > 12)
        windowSize = wbits - 3;
    else if (wbits > 4)
        windowSize = wbits - 2;
    else if (wbits > 0)
        windowSize = 2;
    const MASK = bitMask(windowSize);
    const buckets = new Array(Number(MASK) + 1).fill(zero); // +1 for zero array
    const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;
    let sum = zero;
    for (let i = lastBits; i >= 0; i -= windowSize) {
        buckets.fill(zero);
        for (let j = 0; j < slength; j++) {
            const scalar = scalars[j];
            const wbits = Number((scalar >> BigInt(i)) & MASK);
            buckets[wbits] = buckets[wbits].add(points[j]);
        }
        let resI = zero; // not using this will do small speed-up, but will lose ct
        // Skip first bucket, because it is zero
        for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {
            sumI = sumI.add(buckets[j]);
            resI = resI.add(sumI);
        }
        sum = sum.add(resI);
        if (i !== 0)
            for (let j = 0; j < windowSize; j++)
                sum = sum.double();
    }
    return sum;
}
/**
 * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).
 * @param c Curve Point constructor
 * @param fieldN field over CURVE.N - important that it's not over CURVE.P
 * @param points array of L curve points
 * @returns function which multiplies points with scaars
 */
export function precomputeMSMUnsafe(c, fieldN, points, windowSize) {
    /**
     * Performance Analysis of Window-based Precomputation
     *
     * Base Case (256-bit scalar, 8-bit window):
     * - Standard precomputation requires:
     *   - 31 additions per scalar × 256 scalars = 7,936 ops
     *   - Plus 255 summary additions = 8,191 total ops
     *   Note: Summary additions can be optimized via accumulator
     *
     * Chunked Precomputation Analysis:
     * - Using 32 chunks requires:
     *   - 255 additions per chunk
     *   - 256 doublings
     *   - Total: (255 × 32) + 256 = 8,416 ops
     *
     * Memory Usage Comparison:
     * Window Size | Standard Points | Chunked Points
     * ------------|-----------------|---------------
     *     4-bit   |     520         |      15
     *     8-bit   |    4,224        |     255
     *    10-bit   |   13,824        |   1,023
     *    16-bit   |  557,056        |  65,535
     *
     * Key Advantages:
     * 1. Enables larger window sizes due to reduced memory overhead
     * 2. More efficient for smaller scalar counts:
     *    - 16 chunks: (16 × 255) + 256 = 4,336 ops
     *    - ~2x faster than standard 8,191 ops
     *
     * Limitations:
     * - Not suitable for plain precomputes (requires 256 constant doublings)
     * - Performance degrades with larger scalar counts:
     *   - Optimal for ~256 scalars
     *   - Less efficient for 4096+ scalars (Pippenger preferred)
     */
    validateW(windowSize, fieldN.BITS);
    validateMSMPoints(points, c);
    const zero = c.ZERO;
    const tableSize = 2 ** windowSize - 1; // table size (without zero)
    const chunks = Math.ceil(fieldN.BITS / windowSize); // chunks of item
    const MASK = bitMask(windowSize);
    const tables = points.map((p) => {
        const res = [];
        for (let i = 0, acc = p; i < tableSize; i++) {
            res.push(acc);
            acc = acc.add(p);
        }
        return res;
    });
    return (scalars) => {
        validateMSMScalars(scalars, fieldN);
        if (scalars.length > points.length)
            throw new Error('array of scalars must be smaller than array of points');
        let res = zero;
        for (let i = 0; i < chunks; i++) {
            // No need to double if accumulator is still zero.
            if (res !== zero)
                for (let j = 0; j < windowSize; j++)
                    res = res.double();
            const shiftBy = BigInt(chunks * windowSize - (i + 1) * windowSize);
            for (let j = 0; j < scalars.length; j++) {
                const n = scalars[j];
                const curr = Number((n >> shiftBy) & MASK);
                if (!curr)
                    continue; // skip zero scalars chunks
                res = res.add(tables[j][curr - 1]);
            }
        }
        return res;
    };
}
// TODO: remove
/** @deprecated */
export function validateBasic(curve) {
    validateField(curve.Fp);
    validateObject(curve, {
        n: 'bigint',
        h: 'bigint',
        Gx: 'field',
        Gy: 'field',
    }, {
        nBitLength: 'isSafeInteger',
        nByteLength: 'isSafeInteger',
    });
    // Set defaults
    return Object.freeze({
        ...nLength(curve.n, curve.nBitLength),
        ...curve,
        ...{ p: curve.Fp.ORDER },
    });
}
function createField(order, field, isLE) {
    if (field) {
        if (field.ORDER !== order)
            throw new Error('Field.ORDER must match order: Fp == p, Fn == n');
        validateField(field);
        return field;
    }
    else {
        return Field(order, { isLE });
    }
}
/** Validates CURVE opts and creates fields */
export function _createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
    if (FpFnLE === undefined)
        FpFnLE = type === 'edwards';
    if (!CURVE || typeof CURVE !== 'object')
        throw new Error(`expected valid ${type} CURVE object`);
    for (const p of ['p', 'n', 'h']) {
        const val = CURVE[p];
        if (!(typeof val === 'bigint' && val > _0n))
            throw new Error(`CURVE.${p} must be positive bigint`);
    }
    const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);
    const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
    const _b = type === 'weierstrass' ? 'b' : 'd';
    const params = ['Gx', 'Gy', 'a', _b];
    for (const p of params) {
        // @ts-ignore
        if (!Fp.isValid(CURVE[p]))
            throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
    }
    CURVE = Object.freeze(Object.assign({}, CURVE));
    return { CURVE, Fp, Fn };
}
//# sourceMappingURL=curve.js.mapimport { _validateObject, abytes, bytesToNumberBE, concatBytes, isBytes, isHash, utf8ToBytes, } from "../utils.js";
import { FpInvertBatch, mod } from "./modular.js";
// Octet Stream to Integer. "spec" implementation of os2ip is 2.5x slower vs bytesToNumberBE.
const os2ip = bytesToNumberBE;
// Integer to Octet Stream (numberToBytesBE)
function i2osp(value, length) {
    anum(value);
    anum(length);
    if (value < 0 || value >= 1 << (8 * length))
        throw new Error('invalid I2OSP input: ' + value);
    const res = Array.from({ length }).fill(0);
    for (let i = length - 1; i >= 0; i--) {
        res[i] = value & 0xff;
        value >>>= 8;
    }
    return new Uint8Array(res);
}
function strxor(a, b) {
    const arr = new Uint8Array(a.length);
    for (let i = 0; i < a.length; i++) {
        arr[i] = a[i] ^ b[i];
    }
    return arr;
}
function anum(item) {
    if (!Number.isSafeInteger(item))
        throw new Error('number expected');
}
function normDST(DST) {
    if (!isBytes(DST) && typeof DST !== 'string')
        throw new Error('DST must be Uint8Array or string');
    return typeof DST === 'string' ? utf8ToBytes(DST) : DST;
}
/**
 * Produces a uniformly random byte string using a cryptographic hash function H that outputs b bits.
 * [RFC 9380 5.3.1](https://www.rfc-editor.org/rfc/rfc9380#section-5.3.1).
 */
export function expand_message_xmd(msg, DST, lenInBytes, H) {
    abytes(msg);
    anum(lenInBytes);
    DST = normDST(DST);
    // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3
    if (DST.length > 255)
        DST = H(concatBytes(utf8ToBytes('H2C-OVERSIZE-DST-'), DST));
    const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H;
    const ell = Math.ceil(lenInBytes / b_in_bytes);
    if (lenInBytes > 65535 || ell > 255)
        throw new Error('expand_message_xmd: invalid lenInBytes');
    const DST_prime = concatBytes(DST, i2osp(DST.length, 1));
    const Z_pad = i2osp(0, r_in_bytes);
    const l_i_b_str = i2osp(lenInBytes, 2); // len_in_bytes_str
    const b = new Array(ell);
    const b_0 = H(concatBytes(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));
    b[0] = H(concatBytes(b_0, i2osp(1, 1), DST_prime));
    for (let i = 1; i <= ell; i++) {
        const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime];
        b[i] = H(concatBytes(...args));
    }
    const pseudo_random_bytes = concatBytes(...b);
    return pseudo_random_bytes.slice(0, lenInBytes);
}
/**
 * Produces a uniformly random byte string using an extendable-output function (XOF) H.
 * 1. The collision resistance of H MUST be at least k bits.
 * 2. H MUST be an XOF that has been proved indifferentiable from
 *    a random oracle under a reasonable cryptographic assumption.
 * [RFC 9380 5.3.2](https://www.rfc-editor.org/rfc/rfc9380#section-5.3.2).
 */
export function expand_message_xof(msg, DST, lenInBytes, k, H) {
    abytes(msg);
    anum(lenInBytes);
    DST = normDST(DST);
    // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3
    // DST = H('H2C-OVERSIZE-DST-' || a_very_long_DST, Math.ceil((lenInBytes * k) / 8));
    if (DST.length > 255) {
        const dkLen = Math.ceil((2 * k) / 8);
        DST = H.create({ dkLen }).update(utf8ToBytes('H2C-OVERSIZE-DST-')).update(DST).digest();
    }
    if (lenInBytes > 65535 || DST.length > 255)
        throw new Error('expand_message_xof: invalid lenInBytes');
    return (H.create({ dkLen: lenInBytes })
        .update(msg)
        .update(i2osp(lenInBytes, 2))
        // 2. DST_prime = DST || I2OSP(len(DST), 1)
        .update(DST)
        .update(i2osp(DST.length, 1))
        .digest());
}
/**
 * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F.
 * [RFC 9380 5.2](https://www.rfc-editor.org/rfc/rfc9380#section-5.2).
 * @param msg a byte string containing the message to hash
 * @param count the number of elements of F to output
 * @param options `{DST: string, p: bigint, m: number, k: number, expand: 'xmd' | 'xof', hash: H}`, see above
 * @returns [u_0, ..., u_(count - 1)], a list of field elements.
 */
export function hash_to_field(msg, count, options) {
    _validateObject(options, {
        p: 'bigint',
        m: 'number',
        k: 'number',
        hash: 'function',
    });
    const { p, k, m, hash, expand, DST } = options;
    if (!isHash(options.hash))
        throw new Error('expected valid hash');
    abytes(msg);
    anum(count);
    const log2p = p.toString(2).length;
    const L = Math.ceil((log2p + k) / 8); // section 5.1 of ietf draft link above
    const len_in_bytes = count * m * L;
    let prb; // pseudo_random_bytes
    if (expand === 'xmd') {
        prb = expand_message_xmd(msg, DST, len_in_bytes, hash);
    }
    else if (expand === 'xof') {
        prb = expand_message_xof(msg, DST, len_in_bytes, k, hash);
    }
    else if (expand === '_internal_pass') {
        // for internal tests only
        prb = msg;
    }
    else {
        throw new Error('expand must be "xmd" or "xof"');
    }
    const u = new Array(count);
    for (let i = 0; i < count; i++) {
        const e = new Array(m);
        for (let j = 0; j < m; j++) {
            const elm_offset = L * (j + i * m);
            const tv = prb.subarray(elm_offset, elm_offset + L);
            e[j] = mod(os2ip(tv), p);
        }
        u[i] = e;
    }
    return u;
}
export function isogenyMap(field, map) {
    // Make same order as in spec
    const coeff = map.map((i) => Array.from(i).reverse());
    return (x, y) => {
        const [xn, xd, yn, yd] = coeff.map((val) => val.reduce((acc, i) => field.add(field.mul(acc, x), i)));
        // 6.6.3
        // Exceptional cases of iso_map are inputs that cause the denominator of
        // either rational function to evaluate to zero; such cases MUST return
        // the identity point on E.
        const [xd_inv, yd_inv] = FpInvertBatch(field, [xd, yd], true);
        x = field.mul(xn, xd_inv); // xNum / xDen
        y = field.mul(y, field.mul(yn, yd_inv)); // y * (yNum / yDev)
        return { x, y };
    };
}
export const _DST_scalar = utf8ToBytes('HashToScalar-');
/** Creates hash-to-curve methods from EC Point and mapToCurve function. See {@link H2CHasher}. */
export function createHasher(Point, mapToCurve, defaults) {
    if (typeof mapToCurve !== 'function')
        throw new Error('mapToCurve() must be defined');
    function map(num) {
        return Point.fromAffine(mapToCurve(num));
    }
    function clear(initial) {
        const P = initial.clearCofactor();
        if (P.equals(Point.ZERO))
            return Point.ZERO; // zero will throw in assert
        P.assertValidity();
        return P;
    }
    return {
        defaults,
        hashToCurve(msg, options) {
            const opts = Object.assign({}, defaults, options);
            const u = hash_to_field(msg, 2, opts);
            const u0 = map(u[0]);
            const u1 = map(u[1]);
            return clear(u0.add(u1));
        },
        encodeToCurve(msg, options) {
            const optsDst = defaults.encodeDST ? { DST: defaults.encodeDST } : {};
            const opts = Object.assign({}, defaults, optsDst, options);
            const u = hash_to_field(msg, 1, opts);
            const u0 = map(u[0]);
            return clear(u0);
        },
        /** See {@link H2CHasher} */
        mapToCurve(scalars) {
            if (!Array.isArray(scalars))
                throw new Error('expected array of bigints');
            for (const i of scalars)
                if (typeof i !== 'bigint')
                    throw new Error('expected array of bigints');
            return clear(map(scalars));
        },
        // hash_to_scalar can produce 0: https://www.rfc-editor.org/errata/eid8393
        // RFC 9380, draft-irtf-cfrg-bbs-signatures-08
        hashToScalar(msg, options) {
            // @ts-ignore
            const N = Point.Fn.ORDER;
            const opts = Object.assign({}, defaults, { p: N, m: 1, DST: _DST_scalar }, options);
            return hash_to_field(msg, 1, opts)[0][0];
        },
    };
}
//# sourceMappingURL=hash-to-curve.js.map/**
 * Utils for modular division and fields.
 * Field over 11 is a finite (Galois) field is integer number operations `mod 11`.
 * There is no division: it is replaced by modular multiplicative inverse.
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { _validateObject, anumber, bitMask, bytesToNumberBE, bytesToNumberLE, ensureBytes, numberToBytesBE, numberToBytesLE, } from "../utils.js";
// prettier-ignore
const _0n = BigInt(0), _1n = BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3);
// prettier-ignore
const _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5), _7n = /* @__PURE__ */ BigInt(7);
// prettier-ignore
const _8n = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9), _16n = /* @__PURE__ */ BigInt(16);
// Calculates a modulo b
export function mod(a, b) {
    const result = a % b;
    return result >= _0n ? result : b + result;
}
/**
 * Efficiently raise num to power and do modular division.
 * Unsafe in some contexts: uses ladder, so can expose bigint bits.
 * @example
 * pow(2n, 6n, 11n) // 64n % 11n == 9n
 */
export function pow(num, power, modulo) {
    return FpPow(Field(modulo), num, power);
}
/** Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)` */
export function pow2(x, power, modulo) {
    let res = x;
    while (power-- > _0n) {
        res *= res;
        res %= modulo;
    }
    return res;
}
/**
 * Inverses number over modulo.
 * Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).
 */
export function invert(number, modulo) {
    if (number === _0n)
        throw new Error('invert: expected non-zero number');
    if (modulo <= _0n)
        throw new Error('invert: expected positive modulus, got ' + modulo);
    // Fermat's little theorem "CT-like" version inv(n) = n^(m-2) mod m is 30x slower.
    let a = mod(number, modulo);
    let b = modulo;
    // prettier-ignore
    let x = _0n, y = _1n, u = _1n, v = _0n;
    while (a !== _0n) {
        // JIT applies optimization if those two lines follow each other
        const q = b / a;
        const r = b % a;
        const m = x - u * q;
        const n = y - v * q;
        // prettier-ignore
        b = a, a = r, x = u, y = v, u = m, v = n;
    }
    const gcd = b;
    if (gcd !== _1n)
        throw new Error('invert: does not exist');
    return mod(x, modulo);
}
function assertIsSquare(Fp, root, n) {
    if (!Fp.eql(Fp.sqr(root), n))
        throw new Error('Cannot find square root');
}
// Not all roots are possible! Example which will throw:
// const NUM =
// n = 72057594037927816n;
// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));
function sqrt3mod4(Fp, n) {
    const p1div4 = (Fp.ORDER + _1n) / _4n;
    const root = Fp.pow(n, p1div4);
    assertIsSquare(Fp, root, n);
    return root;
}
function sqrt5mod8(Fp, n) {
    const p5div8 = (Fp.ORDER - _5n) / _8n;
    const n2 = Fp.mul(n, _2n);
    const v = Fp.pow(n2, p5div8);
    const nv = Fp.mul(n, v);
    const i = Fp.mul(Fp.mul(nv, _2n), v);
    const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
    assertIsSquare(Fp, root, n);
    return root;
}
// Based on RFC9380, Kong algorithm
// prettier-ignore
function sqrt9mod16(P) {
    const Fp_ = Field(P);
    const tn = tonelliShanks(P);
    const c1 = tn(Fp_, Fp_.neg(Fp_.ONE)); //  1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F
    const c2 = tn(Fp_, c1); //  2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F
    const c3 = tn(Fp_, Fp_.neg(c1)); //  3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F
    const c4 = (P + _7n) / _16n; //  4. c4 = (q + 7) / 16        # Integer arithmetic
    return (Fp, n) => {
        let tv1 = Fp.pow(n, c4); //  1. tv1 = x^c4
        let tv2 = Fp.mul(tv1, c1); //  2. tv2 = c1 * tv1
        const tv3 = Fp.mul(tv1, c2); //  3. tv3 = c2 * tv1
        const tv4 = Fp.mul(tv1, c3); //  4. tv4 = c3 * tv1
        const e1 = Fp.eql(Fp.sqr(tv2), n); //  5.  e1 = (tv2^2) == x
        const e2 = Fp.eql(Fp.sqr(tv3), n); //  6.  e2 = (tv3^2) == x
        tv1 = Fp.cmov(tv1, tv2, e1); //  7. tv1 = CMOV(tv1, tv2, e1)  # Select tv2 if (tv2^2) == x
        tv2 = Fp.cmov(tv4, tv3, e2); //  8. tv2 = CMOV(tv4, tv3, e2)  # Select tv3 if (tv3^2) == x
        const e3 = Fp.eql(Fp.sqr(tv2), n); //  9.  e3 = (tv2^2) == x
        const root = Fp.cmov(tv1, tv2, e3); // 10.  z = CMOV(tv1, tv2, e3)   # Select sqrt from tv1 & tv2
        assertIsSquare(Fp, root, n);
        return root;
    };
}
/**
 * Tonelli-Shanks square root search algorithm.
 * 1. https://eprint.iacr.org/2012/685.pdf (page 12)
 * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks
 * @param P field order
 * @returns function that takes field Fp (created from P) and number n
 */
export function tonelliShanks(P) {
    // Initialization (precomputation).
    // Caching initialization could boost perf by 7%.
    if (P < _3n)
        throw new Error('sqrt is not defined for small field');
    // Factor P - 1 = Q * 2^S, where Q is odd
    let Q = P - _1n;
    let S = 0;
    while (Q % _2n === _0n) {
        Q /= _2n;
        S++;
    }
    // Find the first quadratic non-residue Z >= 2
    let Z = _2n;
    const _Fp = Field(P);
    while (FpLegendre(_Fp, Z) === 1) {
        // Basic primality test for P. After x iterations, chance of
        // not finding quadratic non-residue is 2^x, so 2^1000.
        if (Z++ > 1000)
            throw new Error('Cannot find square root: probably non-prime P');
    }
    // Fast-path; usually done before Z, but we do "primality test".
    if (S === 1)
        return sqrt3mod4;
    // Slow-path
    // TODO: test on Fp2 and others
    let cc = _Fp.pow(Z, Q); // c = z^Q
    const Q1div2 = (Q + _1n) / _2n;
    return function tonelliSlow(Fp, n) {
        if (Fp.is0(n))
            return n;
        // Check if n is a quadratic residue using Legendre symbol
        if (FpLegendre(Fp, n) !== 1)
            throw new Error('Cannot find square root');
        // Initialize variables for the main loop
        let M = S;
        let c = Fp.mul(Fp.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp
        let t = Fp.pow(n, Q); // t = n^Q, first guess at the fudge factor
        let R = Fp.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root
        // Main loop
        // while t != 1
        while (!Fp.eql(t, Fp.ONE)) {
            if (Fp.is0(t))
                return Fp.ZERO; // if t=0 return R=0
            let i = 1;
            // Find the smallest i >= 1 such that t^(2^i) ≡ 1 (mod P)
            let t_tmp = Fp.sqr(t); // t^(2^1)
            while (!Fp.eql(t_tmp, Fp.ONE)) {
                i++;
                t_tmp = Fp.sqr(t_tmp); // t^(2^2)...
                if (i === M)
                    throw new Error('Cannot find square root');
            }
            // Calculate the exponent for b: 2^(M - i - 1)
            const exponent = _1n << BigInt(M - i - 1); // bigint is important
            const b = Fp.pow(c, exponent); // b = 2^(M - i - 1)
            // Update variables
            M = i;
            c = Fp.sqr(b); // c = b^2
            t = Fp.mul(t, c); // t = (t * b^2)
            R = Fp.mul(R, b); // R = R*b
        }
        return R;
    };
}
/**
 * Square root for a finite field. Will try optimized versions first:
 *
 * 1. P ≡ 3 (mod 4)
 * 2. P ≡ 5 (mod 8)
 * 3. P ≡ 9 (mod 16)
 * 4. Tonelli-Shanks algorithm
 *
 * Different algorithms can give different roots, it is up to user to decide which one they want.
 * For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).
 */
export function FpSqrt(P) {
    // P ≡ 3 (mod 4) => √n = n^((P+1)/4)
    if (P % _4n === _3n)
        return sqrt3mod4;
    // P ≡ 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf
    if (P % _8n === _5n)
        return sqrt5mod8;
    // P ≡ 9 (mod 16) => Kong algorithm, page 11 of https://eprint.iacr.org/2012/685.pdf (algorithm 4)
    if (P % _16n === _9n)
        return sqrt9mod16(P);
    // Tonelli-Shanks algorithm
    return tonelliShanks(P);
}
// Little-endian check for first LE bit (last BE bit);
export const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n;
// prettier-ignore
const FIELD_FIELDS = [
    'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',
    'eql', 'add', 'sub', 'mul', 'pow', 'div',
    'addN', 'subN', 'mulN', 'sqrN'
];
export function validateField(field) {
    const initial = {
        ORDER: 'bigint',
        MASK: 'bigint',
        BYTES: 'number',
        BITS: 'number',
    };
    const opts = FIELD_FIELDS.reduce((map, val) => {
        map[val] = 'function';
        return map;
    }, initial);
    _validateObject(field, opts);
    // const max = 16384;
    // if (field.BYTES < 1 || field.BYTES > max) throw new Error('invalid field');
    // if (field.BITS < 1 || field.BITS > 8 * max) throw new Error('invalid field');
    return field;
}
// Generic field functions
/**
 * Same as `pow` but for Fp: non-constant-time.
 * Unsafe in some contexts: uses ladder, so can expose bigint bits.
 */
export function FpPow(Fp, num, power) {
    if (power < _0n)
        throw new Error('invalid exponent, negatives unsupported');
    if (power === _0n)
        return Fp.ONE;
    if (power === _1n)
        return num;
    let p = Fp.ONE;
    let d = num;
    while (power > _0n) {
        if (power & _1n)
            p = Fp.mul(p, d);
        d = Fp.sqr(d);
        power >>= _1n;
    }
    return p;
}
/**
 * Efficiently invert an array of Field elements.
 * Exception-free. Will return `undefined` for 0 elements.
 * @param passZero map 0 to 0 (instead of undefined)
 */
export function FpInvertBatch(Fp, nums, passZero = false) {
    const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : undefined);
    // Walk from first to last, multiply them by each other MOD p
    const multipliedAcc = nums.reduce((acc, num, i) => {
        if (Fp.is0(num))
            return acc;
        inverted[i] = acc;
        return Fp.mul(acc, num);
    }, Fp.ONE);
    // Invert last element
    const invertedAcc = Fp.inv(multipliedAcc);
    // Walk from last to first, multiply them by inverted each other MOD p
    nums.reduceRight((acc, num, i) => {
        if (Fp.is0(num))
            return acc;
        inverted[i] = Fp.mul(acc, inverted[i]);
        return Fp.mul(acc, num);
    }, invertedAcc);
    return inverted;
}
// TODO: remove
export function FpDiv(Fp, lhs, rhs) {
    return Fp.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, Fp.ORDER) : Fp.inv(rhs));
}
/**
 * Legendre symbol.
 * Legendre constant is used to calculate Legendre symbol (a | p)
 * which denotes the value of a^((p-1)/2) (mod p).
 *
 * * (a | p) ≡ 1    if a is a square (mod p), quadratic residue
 * * (a | p) ≡ -1   if a is not a square (mod p), quadratic non residue
 * * (a | p) ≡ 0    if a ≡ 0 (mod p)
 */
export function FpLegendre(Fp, n) {
    // We can use 3rd argument as optional cache of this value
    // but seems unneeded for now. The operation is very fast.
    const p1mod2 = (Fp.ORDER - _1n) / _2n;
    const powered = Fp.pow(n, p1mod2);
    const yes = Fp.eql(powered, Fp.ONE);
    const zero = Fp.eql(powered, Fp.ZERO);
    const no = Fp.eql(powered, Fp.neg(Fp.ONE));
    if (!yes && !zero && !no)
        throw new Error('invalid Legendre symbol result');
    return yes ? 1 : zero ? 0 : -1;
}
// This function returns True whenever the value x is a square in the field F.
export function FpIsSquare(Fp, n) {
    const l = FpLegendre(Fp, n);
    return l === 1;
}
// CURVE.n lengths
export function nLength(n, nBitLength) {
    // Bit size, byte size of CURVE.n
    if (nBitLength !== undefined)
        anumber(nBitLength);
    const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;
    const nByteLength = Math.ceil(_nBitLength / 8);
    return { nBitLength: _nBitLength, nByteLength };
}
/**
 * Creates a finite field. Major performance optimizations:
 * * 1. Denormalized operations like mulN instead of mul.
 * * 2. Identical object shape: never add or remove keys.
 * * 3. `Object.freeze`.
 * Fragile: always run a benchmark on a change.
 * Security note: operations don't check 'isValid' for all elements for performance reasons,
 * it is caller responsibility to check this.
 * This is low-level code, please make sure you know what you're doing.
 *
 * Note about field properties:
 * * CHARACTERISTIC p = prime number, number of elements in main subgroup.
 * * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.
 *
 * @param ORDER field order, probably prime, or could be composite
 * @param bitLen how many bits the field consumes
 * @param isLE (default: false) if encoding / decoding should be in little-endian
 * @param redef optional faster redefinitions of sqrt and other methods
 */
export function Field(ORDER, bitLenOrOpts, // TODO: use opts only in v2?
isLE = false, opts = {}) {
    if (ORDER <= _0n)
        throw new Error('invalid field: expected ORDER > 0, got ' + ORDER);
    let _nbitLength = undefined;
    let _sqrt = undefined;
    let modFromBytes = false;
    let allowedLengths = undefined;
    if (typeof bitLenOrOpts === 'object' && bitLenOrOpts != null) {
        if (opts.sqrt || isLE)
            throw new Error('cannot specify opts in two arguments');
        const _opts = bitLenOrOpts;
        if (_opts.BITS)
            _nbitLength = _opts.BITS;
        if (_opts.sqrt)
            _sqrt = _opts.sqrt;
        if (typeof _opts.isLE === 'boolean')
            isLE = _opts.isLE;
        if (typeof _opts.modFromBytes === 'boolean')
            modFromBytes = _opts.modFromBytes;
        allowedLengths = _opts.allowedLengths;
    }
    else {
        if (typeof bitLenOrOpts === 'number')
            _nbitLength = bitLenOrOpts;
        if (opts.sqrt)
            _sqrt = opts.sqrt;
    }
    const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, _nbitLength);
    if (BYTES > 2048)
        throw new Error('invalid field: expected ORDER of <= 2048 bytes');
    let sqrtP; // cached sqrtP
    const f = Object.freeze({
        ORDER,
        isLE,
        BITS,
        BYTES,
        MASK: bitMask(BITS),
        ZERO: _0n,
        ONE: _1n,
        allowedLengths: allowedLengths,
        create: (num) => mod(num, ORDER),
        isValid: (num) => {
            if (typeof num !== 'bigint')
                throw new Error('invalid field element: expected bigint, got ' + typeof num);
            return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible
        },
        is0: (num) => num === _0n,
        // is valid and invertible
        isValidNot0: (num) => !f.is0(num) && f.isValid(num),
        isOdd: (num) => (num & _1n) === _1n,
        neg: (num) => mod(-num, ORDER),
        eql: (lhs, rhs) => lhs === rhs,
        sqr: (num) => mod(num * num, ORDER),
        add: (lhs, rhs) => mod(lhs + rhs, ORDER),
        sub: (lhs, rhs) => mod(lhs - rhs, ORDER),
        mul: (lhs, rhs) => mod(lhs * rhs, ORDER),
        pow: (num, power) => FpPow(f, num, power),
        div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),
        // Same as above, but doesn't normalize
        sqrN: (num) => num * num,
        addN: (lhs, rhs) => lhs + rhs,
        subN: (lhs, rhs) => lhs - rhs,
        mulN: (lhs, rhs) => lhs * rhs,
        inv: (num) => invert(num, ORDER),
        sqrt: _sqrt ||
            ((n) => {
                if (!sqrtP)
                    sqrtP = FpSqrt(ORDER);
                return sqrtP(f, n);
            }),
        toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),
        fromBytes: (bytes, skipValidation = true) => {
            if (allowedLengths) {
                if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
                    throw new Error('Field.fromBytes: expected ' + allowedLengths + ' bytes, got ' + bytes.length);
                }
                const padded = new Uint8Array(BYTES);
                // isLE add 0 to right, !isLE to the left.
                padded.set(bytes, isLE ? 0 : padded.length - bytes.length);
                bytes = padded;
            }
            if (bytes.length !== BYTES)
                throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);
            let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
            if (modFromBytes)
                scalar = mod(scalar, ORDER);
            if (!skipValidation)
                if (!f.isValid(scalar))
                    throw new Error('invalid field element: outside of range 0..ORDER');
            // NOTE: we don't validate scalar here, please use isValid. This done such way because some
            // protocol may allow non-reduced scalar that reduced later or changed some other way.
            return scalar;
        },
        // TODO: we don't need it here, move out to separate fn
        invertBatch: (lst) => FpInvertBatch(f, lst),
        // We can't move this out because Fp6, Fp12 implement it
        // and it's unclear what to return in there.
        cmov: (a, b, c) => (c ? b : a),
    });
    return Object.freeze(f);
}
// Generic random scalar, we can do same for other fields if via Fp2.mul(Fp2.ONE, Fp2.random)?
// This allows unsafe methods like ignore bias or zero. These unsafe, but often used in different protocols (if deterministic RNG).
// which mean we cannot force this via opts.
// Not sure what to do with randomBytes, we can accept it inside opts if wanted.
// Probably need to export getMinHashLength somewhere?
// random(bytes?: Uint8Array, unsafeAllowZero = false, unsafeAllowBias = false) {
//   const LEN = !unsafeAllowBias ? getMinHashLength(ORDER) : BYTES;
//   if (bytes === undefined) bytes = randomBytes(LEN); // _opts.randomBytes?
//   const num = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
//   // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0
//   const reduced = unsafeAllowZero ? mod(num, ORDER) : mod(num, ORDER - _1n) + _1n;
//   return reduced;
// },
export function FpSqrtOdd(Fp, elm) {
    if (!Fp.isOdd)
        throw new Error("Field doesn't have isOdd");
    const root = Fp.sqrt(elm);
    return Fp.isOdd(root) ? root : Fp.neg(root);
}
export function FpSqrtEven(Fp, elm) {
    if (!Fp.isOdd)
        throw new Error("Field doesn't have isOdd");
    const root = Fp.sqrt(elm);
    return Fp.isOdd(root) ? Fp.neg(root) : root;
}
/**
 * "Constant-time" private key generation utility.
 * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field).
 * Which makes it slightly more biased, less secure.
 * @deprecated use `mapKeyToField` instead
 */
export function hashToPrivateScalar(hash, groupOrder, isLE = false) {
    hash = ensureBytes('privateHash', hash);
    const hashLen = hash.length;
    const minLen = nLength(groupOrder).nByteLength + 8;
    if (minLen < 24 || hashLen < minLen || hashLen > 1024)
        throw new Error('hashToPrivateScalar: expected ' + minLen + '-1024 bytes of input, got ' + hashLen);
    const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash);
    return mod(num, groupOrder - _1n) + _1n;
}
/**
 * Returns total number of bytes consumed by the field element.
 * For example, 32 bytes for usual 256-bit weierstrass curve.
 * @param fieldOrder number of field elements, usually CURVE.n
 * @returns byte length of field
 */
export function getFieldBytesLength(fieldOrder) {
    if (typeof fieldOrder !== 'bigint')
        throw new Error('field order must be bigint');
    const bitLength = fieldOrder.toString(2).length;
    return Math.ceil(bitLength / 8);
}
/**
 * Returns minimal amount of bytes that can be safely reduced
 * by field order.
 * Should be 2^-128 for 128-bit curve such as P256.
 * @param fieldOrder number of field elements, usually CURVE.n
 * @returns byte length of target hash
 */
export function getMinHashLength(fieldOrder) {
    const length = getFieldBytesLength(fieldOrder);
    return length + Math.ceil(length / 2);
}
/**
 * "Constant-time" private key generation utility.
 * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF
 * and convert them into private scalar, with the modulo bias being negligible.
 * Needs at least 48 bytes of input for 32-byte private key.
 * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/
 * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final
 * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5
 * @param hash hash output from SHA3 or a similar function
 * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)
 * @param isLE interpret hash bytes as LE num
 * @returns valid private scalar
 */
export function mapHashToField(key, fieldOrder, isLE = false) {
    const len = key.length;
    const fieldLen = getFieldBytesLength(fieldOrder);
    const minLen = getMinHashLength(fieldOrder);
    // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.
    if (len < 16 || len < minLen || len > 1024)
        throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);
    const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);
    // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0
    const reduced = mod(num, fieldOrder - _1n) + _1n;
    return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
}
//# sourceMappingURL=modular.js.map/**
 * Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.
 *
 * ### Design rationale for types
 *
 * * Interaction between classes from different curves should fail:
 *   `k256.Point.BASE.add(p256.Point.BASE)`
 * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime
 * * Different calls of `curve()` would return different classes -
 *   `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,
 *   it won't affect others
 *
 * TypeScript can't infer types for classes created inside a function. Classes is one instance
 * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create
 * unique type for every function call.
 *
 * We can use generic types via some param, like curve opts, but that would:
 *     1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)
 *     which is hard to debug.
 *     2. Params can be generic and we can't enforce them to be constant value:
 *     if somebody creates curve from non-constant params,
 *     it would be allowed to interact with other curves with non-constant params
 *
 * @todo https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { hmac as nobleHmac } from '@noble/hashes/hmac.js';
import { ahash } from '@noble/hashes/utils';
import { _validateObject, _abool2 as abool, _abytes2 as abytes, aInRange, bitLen, bitMask, bytesToHex, bytesToNumberBE, concatBytes, createHmacDrbg, ensureBytes, hexToBytes, inRange, isBytes, memoized, numberToHexUnpadded, randomBytes as randomBytesWeb, } from "../utils.js";
import { _createCurveFields, mulEndoUnsafe, negateCt, normalizeZ, pippenger, wNAF, } from "./curve.js";
import { Field, FpInvertBatch, getMinHashLength, mapHashToField, nLength, validateField, } from "./modular.js";
// We construct basis in such way that den is always positive and equals n, but num sign depends on basis (not on secret value)
const divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n) / den;
/**
 * Splits scalar for GLV endomorphism.
 */
export function _splitEndoScalar(k, basis, n) {
    // Split scalar into two such that part is ~half bits: `abs(part) < sqrt(N)`
    // Since part can be negative, we need to do this on point.
    // TODO: verifyScalar function which consumes lambda
    const [[a1, b1], [a2, b2]] = basis;
    const c1 = divNearest(b2 * k, n);
    const c2 = divNearest(-b1 * k, n);
    // |k1|/|k2| is < sqrt(N), but can be negative.
    // If we do `k1 mod N`, we'll get big scalar (`> sqrt(N)`): so, we do cheaper negation instead.
    let k1 = k - c1 * a1 - c2 * a2;
    let k2 = -c1 * b1 - c2 * b2;
    const k1neg = k1 < _0n;
    const k2neg = k2 < _0n;
    if (k1neg)
        k1 = -k1;
    if (k2neg)
        k2 = -k2;
    // Double check that resulting scalar less than half bits of N: otherwise wNAF will fail.
    // This should only happen on wrong basises. Also, math inside is too complex and I don't trust it.
    const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n; // Half bits of N
    if (k1 < _0n || k1 >= MAX_NUM || k2 < _0n || k2 >= MAX_NUM) {
        throw new Error('splitScalar (endomorphism): failed, k=' + k);
    }
    return { k1neg, k1, k2neg, k2 };
}
function validateSigFormat(format) {
    if (!['compact', 'recovered', 'der'].includes(format))
        throw new Error('Signature format must be "compact", "recovered", or "der"');
    return format;
}
function validateSigOpts(opts, def) {
    const optsn = {};
    for (let optName of Object.keys(def)) {
        // @ts-ignore
        optsn[optName] = opts[optName] === undefined ? def[optName] : opts[optName];
    }
    abool(optsn.lowS, 'lowS');
    abool(optsn.prehash, 'prehash');
    if (optsn.format !== undefined)
        validateSigFormat(optsn.format);
    return optsn;
}
export class DERErr extends Error {
    constructor(m = '') {
        super(m);
    }
}
/**
 * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:
 *
 *     [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]
 *
 * Docs: https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/, https://luca.ntop.org/Teaching/Appunti/asn1.html
 */
export const DER = {
    // asn.1 DER encoding utils
    Err: DERErr,
    // Basic building block is TLV (Tag-Length-Value)
    _tlv: {
        encode: (tag, data) => {
            const { Err: E } = DER;
            if (tag < 0 || tag > 256)
                throw new E('tlv.encode: wrong tag');
            if (data.length & 1)
                throw new E('tlv.encode: unpadded data');
            const dataLen = data.length / 2;
            const len = numberToHexUnpadded(dataLen);
            if ((len.length / 2) & 128)
                throw new E('tlv.encode: long form length too big');
            // length of length with long form flag
            const lenLen = dataLen > 127 ? numberToHexUnpadded((len.length / 2) | 128) : '';
            const t = numberToHexUnpadded(tag);
            return t + lenLen + len + data;
        },
        // v - value, l - left bytes (unparsed)
        decode(tag, data) {
            const { Err: E } = DER;
            let pos = 0;
            if (tag < 0 || tag > 256)
                throw new E('tlv.encode: wrong tag');
            if (data.length < 2 || data[pos++] !== tag)
                throw new E('tlv.decode: wrong tlv');
            const first = data[pos++];
            const isLong = !!(first & 128); // First bit of first length byte is flag for short/long form
            let length = 0;
            if (!isLong)
                length = first;
            else {
                // Long form: [longFlag(1bit), lengthLength(7bit), length (BE)]
                const lenLen = first & 127;
                if (!lenLen)
                    throw new E('tlv.decode(long): indefinite length not supported');
                if (lenLen > 4)
                    throw new E('tlv.decode(long): byte length is too big'); // this will overflow u32 in js
                const lengthBytes = data.subarray(pos, pos + lenLen);
                if (lengthBytes.length !== lenLen)
                    throw new E('tlv.decode: length bytes not complete');
                if (lengthBytes[0] === 0)
                    throw new E('tlv.decode(long): zero leftmost byte');
                for (const b of lengthBytes)
                    length = (length << 8) | b;
                pos += lenLen;
                if (length < 128)
                    throw new E('tlv.decode(long): not minimal encoding');
            }
            const v = data.subarray(pos, pos + length);
            if (v.length !== length)
                throw new E('tlv.decode: wrong value length');
            return { v, l: data.subarray(pos + length) };
        },
    },
    // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
    // since we always use positive integers here. It must always be empty:
    // - add zero byte if exists
    // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
    _int: {
        encode(num) {
            const { Err: E } = DER;
            if (num < _0n)
                throw new E('integer: negative integers are not allowed');
            let hex = numberToHexUnpadded(num);
            // Pad with zero byte if negative flag is present
            if (Number.parseInt(hex[0], 16) & 0b1000)
                hex = '00' + hex;
            if (hex.length & 1)
                throw new E('unexpected DER parsing assertion: unpadded hex');
            return hex;
        },
        decode(data) {
            const { Err: E } = DER;
            if (data[0] & 128)
                throw new E('invalid signature integer: negative');
            if (data[0] === 0x00 && !(data[1] & 128))
                throw new E('invalid signature integer: unnecessary leading zero');
            return bytesToNumberBE(data);
        },
    },
    toSig(hex) {
        // parse DER signature
        const { Err: E, _int: int, _tlv: tlv } = DER;
        const data = ensureBytes('signature', hex);
        const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);
        if (seqLeftBytes.length)
            throw new E('invalid signature: left bytes after parsing');
        const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);
        const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);
        if (sLeftBytes.length)
            throw new E('invalid signature: left bytes after parsing');
        return { r: int.decode(rBytes), s: int.decode(sBytes) };
    },
    hexFromSig(sig) {
        const { _tlv: tlv, _int: int } = DER;
        const rs = tlv.encode(0x02, int.encode(sig.r));
        const ss = tlv.encode(0x02, int.encode(sig.s));
        const seq = rs + ss;
        return tlv.encode(0x30, seq);
    },
};
// Be friendly to bad ECMAScript parsers by not using bigint literals
// prettier-ignore
const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4);
export function _normFnElement(Fn, key) {
    const { BYTES: expected } = Fn;
    let num;
    if (typeof key === 'bigint') {
        num = key;
    }
    else {
        let bytes = ensureBytes('private key', key);
        try {
            num = Fn.fromBytes(bytes);
        }
        catch (error) {
            throw new Error(`invalid private key: expected ui8a of size ${expected}, got ${typeof key}`);
        }
    }
    if (!Fn.isValidNot0(num))
        throw new Error('invalid private key: out of range [1..N-1]');
    return num;
}
/**
 * Creates weierstrass Point constructor, based on specified curve options.
 *
 * @example
```js
const opts = {
  p: BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff'),
  n: BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551'),
  h: BigInt(1),
  a: BigInt('0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc'),
  b: BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b'),
  Gx: BigInt('0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296'),
  Gy: BigInt('0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5'),
};
const p256_Point = weierstrass(opts);
```
 */
export function weierstrassN(params, extraOpts = {}) {
    const validated = _createCurveFields('weierstrass', params, extraOpts);
    const { Fp, Fn } = validated;
    let CURVE = validated.CURVE;
    const { h: cofactor, n: CURVE_ORDER } = CURVE;
    _validateObject(extraOpts, {}, {
        allowInfinityPoint: 'boolean',
        clearCofactor: 'function',
        isTorsionFree: 'function',
        fromBytes: 'function',
        toBytes: 'function',
        endo: 'object',
        wrapPrivateKey: 'boolean',
    });
    const { endo } = extraOpts;
    if (endo) {
        // validateObject(endo, { beta: 'bigint', splitScalar: 'function' });
        if (!Fp.is0(CURVE.a) || typeof endo.beta !== 'bigint' || !Array.isArray(endo.basises)) {
            throw new Error('invalid endo: expected "beta": bigint and "basises": array');
        }
    }
    const lengths = getWLengths(Fp, Fn);
    function assertCompressionIsSupported() {
        if (!Fp.isOdd)
            throw new Error('compression is not supported: Field does not have .isOdd()');
    }
    // Implements IEEE P1363 point encoding
    function pointToBytes(_c, point, isCompressed) {
        const { x, y } = point.toAffine();
        const bx = Fp.toBytes(x);
        abool(isCompressed, 'isCompressed');
        if (isCompressed) {
            assertCompressionIsSupported();
            const hasEvenY = !Fp.isOdd(y);
            return concatBytes(pprefix(hasEvenY), bx);
        }
        else {
            return concatBytes(Uint8Array.of(0x04), bx, Fp.toBytes(y));
        }
    }
    function pointFromBytes(bytes) {
        abytes(bytes, undefined, 'Point');
        const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths; // e.g. for 32-byte: 33, 65
        const length = bytes.length;
        const head = bytes[0];
        const tail = bytes.subarray(1);
        // No actual validation is done here: use .assertValidity()
        if (length === comp && (head === 0x02 || head === 0x03)) {
            const x = Fp.fromBytes(tail);
            if (!Fp.isValid(x))
                throw new Error('bad point: is not on curve, wrong x');
            const y2 = weierstrassEquation(x); // y² = x³ + ax + b
            let y;
            try {
                y = Fp.sqrt(y2); // y = y² ^ (p+1)/4
            }
            catch (sqrtError) {
                const err = sqrtError instanceof Error ? ': ' + sqrtError.message : '';
                throw new Error('bad point: is not on curve, sqrt error' + err);
            }
            assertCompressionIsSupported();
            const isYOdd = Fp.isOdd(y); // (y & _1n) === _1n;
            const isHeadOdd = (head & 1) === 1; // ECDSA-specific
            if (isHeadOdd !== isYOdd)
                y = Fp.neg(y);
            return { x, y };
        }
        else if (length === uncomp && head === 0x04) {
            // TODO: more checks
            const L = Fp.BYTES;
            const x = Fp.fromBytes(tail.subarray(0, L));
            const y = Fp.fromBytes(tail.subarray(L, L * 2));
            if (!isValidXY(x, y))
                throw new Error('bad point: is not on curve');
            return { x, y };
        }
        else {
            throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);
        }
    }
    const encodePoint = extraOpts.toBytes || pointToBytes;
    const decodePoint = extraOpts.fromBytes || pointFromBytes;
    function weierstrassEquation(x) {
        const x2 = Fp.sqr(x); // x * x
        const x3 = Fp.mul(x2, x); // x² * x
        return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b); // x³ + a * x + b
    }
    // TODO: move top-level
    /** Checks whether equation holds for given x, y: y² == x³ + ax + b */
    function isValidXY(x, y) {
        const left = Fp.sqr(y); // y²
        const right = weierstrassEquation(x); // x³ + ax + b
        return Fp.eql(left, right);
    }
    // Validate whether the passed curve params are valid.
    // Test 1: equation y² = x³ + ax + b should work for generator point.
    if (!isValidXY(CURVE.Gx, CURVE.Gy))
        throw new Error('bad curve params: generator point');
    // Test 2: discriminant Δ part should be non-zero: 4a³ + 27b² != 0.
    // Guarantees curve is genus-1, smooth (non-singular).
    const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n), _4n);
    const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));
    if (Fp.is0(Fp.add(_4a3, _27b2)))
        throw new Error('bad curve params: a or b');
    /** Asserts coordinate is valid: 0 <= n < Fp.ORDER. */
    function acoord(title, n, banZero = false) {
        if (!Fp.isValid(n) || (banZero && Fp.is0(n)))
            throw new Error(`bad point coordinate ${title}`);
        return n;
    }
    function aprjpoint(other) {
        if (!(other instanceof Point))
            throw new Error('ProjectivePoint expected');
    }
    function splitEndoScalarN(k) {
        if (!endo || !endo.basises)
            throw new Error('no endo');
        return _splitEndoScalar(k, endo.basises, Fn.ORDER);
    }
    // Memoized toAffine / validity check. They are heavy. Points are immutable.
    // Converts Projective point to affine (x, y) coordinates.
    // Can accept precomputed Z^-1 - for example, from invertBatch.
    // (X, Y, Z) ∋ (x=X/Z, y=Y/Z)
    const toAffineMemo = memoized((p, iz) => {
        const { X, Y, Z } = p;
        // Fast-path for normalized points
        if (Fp.eql(Z, Fp.ONE))
            return { x: X, y: Y };
        const is0 = p.is0();
        // If invZ was 0, we return zero point. However we still want to execute
        // all operations, so we replace invZ with a random number, 1.
        if (iz == null)
            iz = is0 ? Fp.ONE : Fp.inv(Z);
        const x = Fp.mul(X, iz);
        const y = Fp.mul(Y, iz);
        const zz = Fp.mul(Z, iz);
        if (is0)
            return { x: Fp.ZERO, y: Fp.ZERO };
        if (!Fp.eql(zz, Fp.ONE))
            throw new Error('invZ was invalid');
        return { x, y };
    });
    // NOTE: on exception this will crash 'cached' and no value will be set.
    // Otherwise true will be return
    const assertValidMemo = memoized((p) => {
        if (p.is0()) {
            // (0, 1, 0) aka ZERO is invalid in most contexts.
            // In BLS, ZERO can be serialized, so we allow it.
            // (0, 0, 0) is invalid representation of ZERO.
            if (extraOpts.allowInfinityPoint && !Fp.is0(p.Y))
                return;
            throw new Error('bad point: ZERO');
        }
        // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`
        const { x, y } = p.toAffine();
        if (!Fp.isValid(x) || !Fp.isValid(y))
            throw new Error('bad point: x or y not field elements');
        if (!isValidXY(x, y))
            throw new Error('bad point: equation left != right');
        if (!p.isTorsionFree())
            throw new Error('bad point: not in prime-order subgroup');
        return true;
    });
    function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) {
        k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);
        k1p = negateCt(k1neg, k1p);
        k2p = negateCt(k2neg, k2p);
        return k1p.add(k2p);
    }
    /**
     * Projective Point works in 3d / projective (homogeneous) coordinates:(X, Y, Z) ∋ (x=X/Z, y=Y/Z).
     * Default Point works in 2d / affine coordinates: (x, y).
     * We're doing calculations in projective, because its operations don't require costly inversion.
     */
    class Point {
        /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
        constructor(X, Y, Z) {
            this.X = acoord('x', X);
            this.Y = acoord('y', Y, true);
            this.Z = acoord('z', Z);
            Object.freeze(this);
        }
        static CURVE() {
            return CURVE;
        }
        /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
        static fromAffine(p) {
            const { x, y } = p || {};
            if (!p || !Fp.isValid(x) || !Fp.isValid(y))
                throw new Error('invalid affine point');
            if (p instanceof Point)
                throw new Error('projective point not allowed');
            // (0, 0) would've produced (0, 0, 1) - instead, we need (0, 1, 0)
            if (Fp.is0(x) && Fp.is0(y))
                return Point.ZERO;
            return new Point(x, y, Fp.ONE);
        }
        static fromBytes(bytes) {
            const P = Point.fromAffine(decodePoint(abytes(bytes, undefined, 'point')));
            P.assertValidity();
            return P;
        }
        static fromHex(hex) {
            return Point.fromBytes(ensureBytes('pointHex', hex));
        }
        get x() {
            return this.toAffine().x;
        }
        get y() {
            return this.toAffine().y;
        }
        /**
         *
         * @param windowSize
         * @param isLazy true will defer table computation until the first multiplication
         * @returns
         */
        precompute(windowSize = 8, isLazy = true) {
            wnaf.createCache(this, windowSize);
            if (!isLazy)
                this.multiply(_3n); // random number
            return this;
        }
        // TODO: return `this`
        /** A point on curve is valid if it conforms to equation. */
        assertValidity() {
            assertValidMemo(this);
        }
        hasEvenY() {
            const { y } = this.toAffine();
            if (!Fp.isOdd)
                throw new Error("Field doesn't support isOdd");
            return !Fp.isOdd(y);
        }
        /** Compare one point to another. */
        equals(other) {
            aprjpoint(other);
            const { X: X1, Y: Y1, Z: Z1 } = this;
            const { X: X2, Y: Y2, Z: Z2 } = other;
            const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
            const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
            return U1 && U2;
        }
        /** Flips point to one corresponding to (x, -y) in Affine coordinates. */
        negate() {
            return new Point(this.X, Fp.neg(this.Y), this.Z);
        }
        // Renes-Costello-Batina exception-free doubling formula.
        // There is 30% faster Jacobian formula, but it is not complete.
        // https://eprint.iacr.org/2015/1060, algorithm 3
        // Cost: 8M + 3S + 3*a + 2*b3 + 15add.
        double() {
            const { a, b } = CURVE;
            const b3 = Fp.mul(b, _3n);
            const { X: X1, Y: Y1, Z: Z1 } = this;
            let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore
            let t0 = Fp.mul(X1, X1); // step 1
            let t1 = Fp.mul(Y1, Y1);
            let t2 = Fp.mul(Z1, Z1);
            let t3 = Fp.mul(X1, Y1);
            t3 = Fp.add(t3, t3); // step 5
            Z3 = Fp.mul(X1, Z1);
            Z3 = Fp.add(Z3, Z3);
            X3 = Fp.mul(a, Z3);
            Y3 = Fp.mul(b3, t2);
            Y3 = Fp.add(X3, Y3); // step 10
            X3 = Fp.sub(t1, Y3);
            Y3 = Fp.add(t1, Y3);
            Y3 = Fp.mul(X3, Y3);
            X3 = Fp.mul(t3, X3);
            Z3 = Fp.mul(b3, Z3); // step 15
            t2 = Fp.mul(a, t2);
            t3 = Fp.sub(t0, t2);
            t3 = Fp.mul(a, t3);
            t3 = Fp.add(t3, Z3);
            Z3 = Fp.add(t0, t0); // step 20
            t0 = Fp.add(Z3, t0);
            t0 = Fp.add(t0, t2);
            t0 = Fp.mul(t0, t3);
            Y3 = Fp.add(Y3, t0);
            t2 = Fp.mul(Y1, Z1); // step 25
            t2 = Fp.add(t2, t2);
            t0 = Fp.mul(t2, t3);
            X3 = Fp.sub(X3, t0);
            Z3 = Fp.mul(t2, t1);
            Z3 = Fp.add(Z3, Z3); // step 30
            Z3 = Fp.add(Z3, Z3);
            return new Point(X3, Y3, Z3);
        }
        // Renes-Costello-Batina exception-free addition formula.
        // There is 30% faster Jacobian formula, but it is not complete.
        // https://eprint.iacr.org/2015/1060, algorithm 1
        // Cost: 12M + 0S + 3*a + 3*b3 + 23add.
        add(other) {
            aprjpoint(other);
            const { X: X1, Y: Y1, Z: Z1 } = this;
            const { X: X2, Y: Y2, Z: Z2 } = other;
            let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore
            const a = CURVE.a;
            const b3 = Fp.mul(CURVE.b, _3n);
            let t0 = Fp.mul(X1, X2); // step 1
            let t1 = Fp.mul(Y1, Y2);
            let t2 = Fp.mul(Z1, Z2);
            let t3 = Fp.add(X1, Y1);
            let t4 = Fp.add(X2, Y2); // step 5
            t3 = Fp.mul(t3, t4);
            t4 = Fp.add(t0, t1);
            t3 = Fp.sub(t3, t4);
            t4 = Fp.add(X1, Z1);
            let t5 = Fp.add(X2, Z2); // step 10
            t4 = Fp.mul(t4, t5);
            t5 = Fp.add(t0, t2);
            t4 = Fp.sub(t4, t5);
            t5 = Fp.add(Y1, Z1);
            X3 = Fp.add(Y2, Z2); // step 15
            t5 = Fp.mul(t5, X3);
            X3 = Fp.add(t1, t2);
            t5 = Fp.sub(t5, X3);
            Z3 = Fp.mul(a, t4);
            X3 = Fp.mul(b3, t2); // step 20
            Z3 = Fp.add(X3, Z3);
            X3 = Fp.sub(t1, Z3);
            Z3 = Fp.add(t1, Z3);
            Y3 = Fp.mul(X3, Z3);
            t1 = Fp.add(t0, t0); // step 25
            t1 = Fp.add(t1, t0);
            t2 = Fp.mul(a, t2);
            t4 = Fp.mul(b3, t4);
            t1 = Fp.add(t1, t2);
            t2 = Fp.sub(t0, t2); // step 30
            t2 = Fp.mul(a, t2);
            t4 = Fp.add(t4, t2);
            t0 = Fp.mul(t1, t4);
            Y3 = Fp.add(Y3, t0);
            t0 = Fp.mul(t5, t4); // step 35
            X3 = Fp.mul(t3, X3);
            X3 = Fp.sub(X3, t0);
            t0 = Fp.mul(t3, t1);
            Z3 = Fp.mul(t5, Z3);
            Z3 = Fp.add(Z3, t0); // step 40
            return new Point(X3, Y3, Z3);
        }
        subtract(other) {
            return this.add(other.negate());
        }
        is0() {
            return this.equals(Point.ZERO);
        }
        /**
         * Constant time multiplication.
         * Uses wNAF method. Windowed method may be 10% faster,
         * but takes 2x longer to generate and consumes 2x memory.
         * Uses precomputes when available.
         * Uses endomorphism for Koblitz curves.
         * @param scalar by which the point would be multiplied
         * @returns New point
         */
        multiply(scalar) {
            const { endo } = extraOpts;
            if (!Fn.isValidNot0(scalar))
                throw new Error('invalid scalar: out of range'); // 0 is invalid
            let point, fake; // Fake point is used to const-time mult
            const mul = (n) => wnaf.cached(this, n, (p) => normalizeZ(Point, p));
            /** See docs for {@link EndomorphismOpts} */
            if (endo) {
                const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);
                const { p: k1p, f: k1f } = mul(k1);
                const { p: k2p, f: k2f } = mul(k2);
                fake = k1f.add(k2f);
                point = finishEndo(endo.beta, k1p, k2p, k1neg, k2neg);
            }
            else {
                const { p, f } = mul(scalar);
                point = p;
                fake = f;
            }
            // Normalize `z` for both points, but return only real one
            return normalizeZ(Point, [point, fake])[0];
        }
        /**
         * Non-constant-time multiplication. Uses double-and-add algorithm.
         * It's faster, but should only be used when you don't care about
         * an exposed secret key e.g. sig verification, which works over *public* keys.
         */
        multiplyUnsafe(sc) {
            const { endo } = extraOpts;
            const p = this;
            if (!Fn.isValid(sc))
                throw new Error('invalid scalar: out of range'); // 0 is valid
            if (sc === _0n || p.is0())
                return Point.ZERO;
            if (sc === _1n)
                return p; // fast-path
            if (wnaf.hasCache(this))
                return this.multiply(sc);
            if (endo) {
                const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);
                const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2); // 30% faster vs wnaf.unsafe
                return finishEndo(endo.beta, p1, p2, k1neg, k2neg);
            }
            else {
                return wnaf.unsafe(p, sc);
            }
        }
        multiplyAndAddUnsafe(Q, a, b) {
            const sum = this.multiplyUnsafe(a).add(Q.multiplyUnsafe(b));
            return sum.is0() ? undefined : sum;
        }
        /**
         * Converts Projective point to affine (x, y) coordinates.
         * @param invertedZ Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch
         */
        toAffine(invertedZ) {
            return toAffineMemo(this, invertedZ);
        }
        /**
         * Checks whether Point is free of torsion elements (is in prime subgroup).
         * Always torsion-free for cofactor=1 curves.
         */
        isTorsionFree() {
            const { isTorsionFree } = extraOpts;
            if (cofactor === _1n)
                return true;
            if (isTorsionFree)
                return isTorsionFree(Point, this);
            return wnaf.unsafe(this, CURVE_ORDER).is0();
        }
        clearCofactor() {
            const { clearCofactor } = extraOpts;
            if (cofactor === _1n)
                return this; // Fast-path
            if (clearCofactor)
                return clearCofactor(Point, this);
            return this.multiplyUnsafe(cofactor);
        }
        isSmallOrder() {
            // can we use this.clearCofactor()?
            return this.multiplyUnsafe(cofactor).is0();
        }
        toBytes(isCompressed = true) {
            abool(isCompressed, 'isCompressed');
            this.assertValidity();
            return encodePoint(Point, this, isCompressed);
        }
        toHex(isCompressed = true) {
            return bytesToHex(this.toBytes(isCompressed));
        }
        toString() {
            return `<Point ${this.is0() ? 'ZERO' : this.toHex()}>`;
        }
        // TODO: remove
        get px() {
            return this.X;
        }
        get py() {
            return this.X;
        }
        get pz() {
            return this.Z;
        }
        toRawBytes(isCompressed = true) {
            return this.toBytes(isCompressed);
        }
        _setWindowSize(windowSize) {
            this.precompute(windowSize);
        }
        static normalizeZ(points) {
            return normalizeZ(Point, points);
        }
        static msm(points, scalars) {
            return pippenger(Point, Fn, points, scalars);
        }
        static fromPrivateKey(privateKey) {
            return Point.BASE.multiply(_normFnElement(Fn, privateKey));
        }
    }
    // base / generator point
    Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
    // zero / infinity / identity point
    Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); // 0, 1, 0
    // math field
    Point.Fp = Fp;
    // scalar field
    Point.Fn = Fn;
    const bits = Fn.BITS;
    const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);
    Point.BASE.precompute(8); // Enable precomputes. Slows down first publicKey computation by 20ms.
    return Point;
}
// Points start with byte 0x02 when y is even; otherwise 0x03
function pprefix(hasEvenY) {
    return Uint8Array.of(hasEvenY ? 0x02 : 0x03);
}
/**
 * Implementation of the Shallue and van de Woestijne method for any weierstrass curve.
 * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular.
 * b = True and y = sqrt(u / v) if (u / v) is square in F, and
 * b = False and y = sqrt(Z * (u / v)) otherwise.
 * @param Fp
 * @param Z
 * @returns
 */
export function SWUFpSqrtRatio(Fp, Z) {
    // Generic implementation
    const q = Fp.ORDER;
    let l = _0n;
    for (let o = q - _1n; o % _2n === _0n; o /= _2n)
        l += _1n;
    const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1.
    // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<.
    // 2n ** c1 == 2n << (c1-1)
    const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n);
    const _2n_pow_c1 = _2n_pow_c1_1 * _2n;
    const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1)  # Integer arithmetic
    const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2            # Integer arithmetic
    const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1                # Integer arithmetic
    const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1)                  # Integer arithmetic
    const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2
    const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2)
    let sqrtRatio = (u, v) => {
        let tv1 = c6; // 1. tv1 = c6
        let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4
        let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2
        tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v
        let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3
        tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3
        tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2
        tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v
        tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u
        let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2
        tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5
        let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1
        tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7
        tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1
        tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR)
        tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR)
        // 17. for i in (c1, c1 - 1, ..., 2):
        for (let i = c1; i > _1n; i--) {
            let tv5 = i - _2n; // 18.    tv5 = i - 2
            tv5 = _2n << (tv5 - _1n); // 19.    tv5 = 2^tv5
            let tvv5 = Fp.pow(tv4, tv5); // 20.    tv5 = tv4^tv5
            const e1 = Fp.eql(tvv5, Fp.ONE); // 21.    e1 = tv5 == 1
            tv2 = Fp.mul(tv3, tv1); // 22.    tv2 = tv3 * tv1
            tv1 = Fp.mul(tv1, tv1); // 23.    tv1 = tv1 * tv1
            tvv5 = Fp.mul(tv4, tv1); // 24.    tv5 = tv4 * tv1
            tv3 = Fp.cmov(tv2, tv3, e1); // 25.    tv3 = CMOV(tv2, tv3, e1)
            tv4 = Fp.cmov(tvv5, tv4, e1); // 26.    tv4 = CMOV(tv5, tv4, e1)
        }
        return { isValid: isQR, value: tv3 };
    };
    if (Fp.ORDER % _4n === _3n) {
        // sqrt_ratio_3mod4(u, v)
        const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4     # Integer arithmetic
        const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z)
        sqrtRatio = (u, v) => {
            let tv1 = Fp.sqr(v); // 1. tv1 = v^2
            const tv2 = Fp.mul(u, v); // 2. tv2 = u * v
            tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2
            let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1
            y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2
            const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2
            const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v
            const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u
            let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR)
            return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2
        };
    }
    // No curves uses that
    // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8
    return sqrtRatio;
}
/**
 * Simplified Shallue-van de Woestijne-Ulas Method
 * https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2
 */
export function mapToCurveSimpleSWU(Fp, opts) {
    validateField(Fp);
    const { A, B, Z } = opts;
    if (!Fp.isValid(A) || !Fp.isValid(B) || !Fp.isValid(Z))
        throw new Error('mapToCurveSimpleSWU: invalid opts');
    const sqrtRatio = SWUFpSqrtRatio(Fp, Z);
    if (!Fp.isOdd)
        throw new Error('Field does not have .isOdd()');
    // Input: u, an element of F.
    // Output: (x, y), a point on E.
    return (u) => {
        // prettier-ignore
        let tv1, tv2, tv3, tv4, tv5, tv6, x, y;
        tv1 = Fp.sqr(u); // 1.  tv1 = u^2
        tv1 = Fp.mul(tv1, Z); // 2.  tv1 = Z * tv1
        tv2 = Fp.sqr(tv1); // 3.  tv2 = tv1^2
        tv2 = Fp.add(tv2, tv1); // 4.  tv2 = tv2 + tv1
        tv3 = Fp.add(tv2, Fp.ONE); // 5.  tv3 = tv2 + 1
        tv3 = Fp.mul(tv3, B); // 6.  tv3 = B * tv3
        tv4 = Fp.cmov(Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7.  tv4 = CMOV(Z, -tv2, tv2 != 0)
        tv4 = Fp.mul(tv4, A); // 8.  tv4 = A * tv4
        tv2 = Fp.sqr(tv3); // 9.  tv2 = tv3^2
        tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2
        tv5 = Fp.mul(tv6, A); // 11. tv5 = A * tv6
        tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5
        tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3
        tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4
        tv5 = Fp.mul(tv6, B); // 15. tv5 = B * tv6
        tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5
        x = Fp.mul(tv1, tv3); // 17.   x = tv1 * tv3
        const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6)
        y = Fp.mul(tv1, u); // 19.   y = tv1 * u  -> Z * u^3 * y1
        y = Fp.mul(y, value); // 20.   y = y * y1
        x = Fp.cmov(x, tv3, isValid); // 21.   x = CMOV(x, tv3, is_gx1_square)
        y = Fp.cmov(y, value, isValid); // 22.   y = CMOV(y, y1, is_gx1_square)
        const e1 = Fp.isOdd(u) === Fp.isOdd(y); // 23.  e1 = sgn0(u) == sgn0(y)
        y = Fp.cmov(Fp.neg(y), y, e1); // 24.   y = CMOV(-y, y, e1)
        const tv4_inv = FpInvertBatch(Fp, [tv4], true)[0];
        x = Fp.mul(x, tv4_inv); // 25.   x = x / tv4
        return { x, y };
    };
}
function getWLengths(Fp, Fn) {
    return {
        secretKey: Fn.BYTES,
        publicKey: 1 + Fp.BYTES,
        publicKeyUncompressed: 1 + 2 * Fp.BYTES,
        publicKeyHasPrefix: true,
        signature: 2 * Fn.BYTES,
    };
}
/**
 * Sometimes users only need getPublicKey, getSharedSecret, and secret key handling.
 * This helper ensures no signature functionality is present. Less code, smaller bundle size.
 */
export function ecdh(Point, ecdhOpts = {}) {
    const { Fn } = Point;
    const randomBytes_ = ecdhOpts.randomBytes || randomBytesWeb;
    const lengths = Object.assign(getWLengths(Point.Fp, Fn), { seed: getMinHashLength(Fn.ORDER) });
    function isValidSecretKey(secretKey) {
        try {
            return !!_normFnElement(Fn, secretKey);
        }
        catch (error) {
            return false;
        }
    }
    function isValidPublicKey(publicKey, isCompressed) {
        const { publicKey: comp, publicKeyUncompressed } = lengths;
        try {
            const l = publicKey.length;
            if (isCompressed === true && l !== comp)
                return false;
            if (isCompressed === false && l !== publicKeyUncompressed)
                return false;
            return !!Point.fromBytes(publicKey);
        }
        catch (error) {
            return false;
        }
    }
    /**
     * Produces cryptographically secure secret key from random of size
     * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.
     */
    function randomSecretKey(seed = randomBytes_(lengths.seed)) {
        return mapHashToField(abytes(seed, lengths.seed, 'seed'), Fn.ORDER);
    }
    /**
     * Computes public key for a secret key. Checks for validity of the secret key.
     * @param isCompressed whether to return compact (default), or full key
     * @returns Public key, full when isCompressed=false; short when isCompressed=true
     */
    function getPublicKey(secretKey, isCompressed = true) {
        return Point.BASE.multiply(_normFnElement(Fn, secretKey)).toBytes(isCompressed);
    }
    function keygen(seed) {
        const secretKey = randomSecretKey(seed);
        return { secretKey, publicKey: getPublicKey(secretKey) };
    }
    /**
     * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.
     */
    function isProbPub(item) {
        if (typeof item === 'bigint')
            return false;
        if (item instanceof Point)
            return true;
        const { secretKey, publicKey, publicKeyUncompressed } = lengths;
        if (Fn.allowedLengths || secretKey === publicKey)
            return undefined;
        const l = ensureBytes('key', item).length;
        return l === publicKey || l === publicKeyUncompressed;
    }
    /**
     * ECDH (Elliptic Curve Diffie Hellman).
     * Computes shared public key from secret key A and public key B.
     * Checks: 1) secret key validity 2) shared key is on-curve.
     * Does NOT hash the result.
     * @param isCompressed whether to return compact (default), or full key
     * @returns shared public key
     */
    function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {
        if (isProbPub(secretKeyA) === true)
            throw new Error('first arg must be private key');
        if (isProbPub(publicKeyB) === false)
            throw new Error('second arg must be public key');
        const s = _normFnElement(Fn, secretKeyA);
        const b = Point.fromHex(publicKeyB); // checks for being on-curve
        return b.multiply(s).toBytes(isCompressed);
    }
    const utils = {
        isValidSecretKey,
        isValidPublicKey,
        randomSecretKey,
        // TODO: remove
        isValidPrivateKey: isValidSecretKey,
        randomPrivateKey: randomSecretKey,
        normPrivateKeyToScalar: (key) => _normFnElement(Fn, key),
        precompute(windowSize = 8, point = Point.BASE) {
            return point.precompute(windowSize, false);
        },
    };
    return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point, utils, lengths });
}
/**
 * Creates ECDSA signing interface for given elliptic curve `Point` and `hash` function.
 * We need `hash` for 2 features:
 * 1. Message prehash-ing. NOT used if `sign` / `verify` are called with `prehash: false`
 * 2. k generation in `sign`, using HMAC-drbg(hash)
 *
 * ECDSAOpts are only rarely needed.
 *
 * @example
 * ```js
 * const p256_Point = weierstrass(...);
 * const p256_sha256 = ecdsa(p256_Point, sha256);
 * const p256_sha224 = ecdsa(p256_Point, sha224);
 * const p256_sha224_r = ecdsa(p256_Point, sha224, { randomBytes: (length) => { ... } });
 * ```
 */
export function ecdsa(Point, hash, ecdsaOpts = {}) {
    ahash(hash);
    _validateObject(ecdsaOpts, {}, {
        hmac: 'function',
        lowS: 'boolean',
        randomBytes: 'function',
        bits2int: 'function',
        bits2int_modN: 'function',
    });
    const randomBytes = ecdsaOpts.randomBytes || randomBytesWeb;
    const hmac = ecdsaOpts.hmac ||
        ((key, ...msgs) => nobleHmac(hash, key, concatBytes(...msgs)));
    const { Fp, Fn } = Point;
    const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;
    const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);
    const defaultSigOpts = {
        prehash: false,
        lowS: typeof ecdsaOpts.lowS === 'boolean' ? ecdsaOpts.lowS : false,
        format: undefined, //'compact' as ECDSASigFormat,
        extraEntropy: false,
    };
    const defaultSigOpts_format = 'compact';
    function isBiggerThanHalfOrder(number) {
        const HALF = CURVE_ORDER >> _1n;
        return number > HALF;
    }
    function validateRS(title, num) {
        if (!Fn.isValidNot0(num))
            throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);
        return num;
    }
    function validateSigLength(bytes, format) {
        validateSigFormat(format);
        const size = lengths.signature;
        const sizer = format === 'compact' ? size : format === 'recovered' ? size + 1 : undefined;
        return abytes(bytes, sizer, `${format} signature`);
    }
    /**
     * ECDSA signature with its (r, s) properties. Supports compact, recovered & DER representations.
     */
    class Signature {
        constructor(r, s, recovery) {
            this.r = validateRS('r', r); // r in [1..N-1];
            this.s = validateRS('s', s); // s in [1..N-1];
            if (recovery != null)
                this.recovery = recovery;
            Object.freeze(this);
        }
        static fromBytes(bytes, format = defaultSigOpts_format) {
            validateSigLength(bytes, format);
            let recid;
            if (format === 'der') {
                const { r, s } = DER.toSig(abytes(bytes));
                return new Signature(r, s);
            }
            if (format === 'recovered') {
                recid = bytes[0];
                format = 'compact';
                bytes = bytes.subarray(1);
            }
            const L = Fn.BYTES;
            const r = bytes.subarray(0, L);
            const s = bytes.subarray(L, L * 2);
            return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);
        }
        static fromHex(hex, format) {
            return this.fromBytes(hexToBytes(hex), format);
        }
        addRecoveryBit(recovery) {
            return new Signature(this.r, this.s, recovery);
        }
        recoverPublicKey(messageHash) {
            const FIELD_ORDER = Fp.ORDER;
            const { r, s, recovery: rec } = this;
            if (rec == null || ![0, 1, 2, 3].includes(rec))
                throw new Error('recovery id invalid');
            // ECDSA recovery is hard for cofactor > 1 curves.
            // In sign, `r = q.x mod n`, and here we recover q.x from r.
            // While recovering q.x >= n, we need to add r+n for cofactor=1 curves.
            // However, for cofactor>1, r+n may not get q.x:
            // r+n*i would need to be done instead where i is unknown.
            // To easily get i, we either need to:
            // a. increase amount of valid recid values (4, 5...); OR
            // b. prohibit non-prime-order signatures (recid > 1).
            const hasCofactor = CURVE_ORDER * _2n < FIELD_ORDER;
            if (hasCofactor && rec > 1)
                throw new Error('recovery id is ambiguous for h>1 curve');
            const radj = rec === 2 || rec === 3 ? r + CURVE_ORDER : r;
            if (!Fp.isValid(radj))
                throw new Error('recovery id 2 or 3 invalid');
            const x = Fp.toBytes(radj);
            const R = Point.fromBytes(concatBytes(pprefix((rec & 1) === 0), x));
            const ir = Fn.inv(radj); // r^-1
            const h = bits2int_modN(ensureBytes('msgHash', messageHash)); // Truncate hash
            const u1 = Fn.create(-h * ir); // -hr^-1
            const u2 = Fn.create(s * ir); // sr^-1
            // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1). unsafe is fine: there is no private data.
            const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));
            if (Q.is0())
                throw new Error('point at infinify');
            Q.assertValidity();
            return Q;
        }
        // Signatures should be low-s, to prevent malleability.
        hasHighS() {
            return isBiggerThanHalfOrder(this.s);
        }
        toBytes(format = defaultSigOpts_format) {
            validateSigFormat(format);
            if (format === 'der')
                return hexToBytes(DER.hexFromSig(this));
            const r = Fn.toBytes(this.r);
            const s = Fn.toBytes(this.s);
            if (format === 'recovered') {
                if (this.recovery == null)
                    throw new Error('recovery bit must be present');
                return concatBytes(Uint8Array.of(this.recovery), r, s);
            }
            return concatBytes(r, s);
        }
        toHex(format) {
            return bytesToHex(this.toBytes(format));
        }
        // TODO: remove
        assertValidity() { }
        static fromCompact(hex) {
            return Signature.fromBytes(ensureBytes('sig', hex), 'compact');
        }
        static fromDER(hex) {
            return Signature.fromBytes(ensureBytes('sig', hex), 'der');
        }
        normalizeS() {
            return this.hasHighS() ? new Signature(this.r, Fn.neg(this.s), this.recovery) : this;
        }
        toDERRawBytes() {
            return this.toBytes('der');
        }
        toDERHex() {
            return bytesToHex(this.toBytes('der'));
        }
        toCompactRawBytes() {
            return this.toBytes('compact');
        }
        toCompactHex() {
            return bytesToHex(this.toBytes('compact'));
        }
    }
    // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.
    // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.
    // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.
    // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors
    const bits2int = ecdsaOpts.bits2int ||
        function bits2int_def(bytes) {
            // Our custom check "just in case", for protection against DoS
            if (bytes.length > 8192)
                throw new Error('input is too large');
            // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)
            // for some cases, since bytes.length * 8 is not actual bitLength.
            const num = bytesToNumberBE(bytes); // check for == u8 done here
            const delta = bytes.length * 8 - fnBits; // truncate to nBitLength leftmost bits
            return delta > 0 ? num >> BigInt(delta) : num;
        };
    const bits2int_modN = ecdsaOpts.bits2int_modN ||
        function bits2int_modN_def(bytes) {
            return Fn.create(bits2int(bytes)); // can't use bytesToNumberBE here
        };
    // Pads output with zero as per spec
    const ORDER_MASK = bitMask(fnBits);
    /** Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. */
    function int2octets(num) {
        // IMPORTANT: the check ensures working for case `Fn.BYTES != Fn.BITS * 8`
        aInRange('num < 2^' + fnBits, num, _0n, ORDER_MASK);
        return Fn.toBytes(num);
    }
    function validateMsgAndHash(message, prehash) {
        abytes(message, undefined, 'message');
        return prehash ? abytes(hash(message), undefined, 'prehashed message') : message;
    }
    /**
     * Steps A, D of RFC6979 3.2.
     * Creates RFC6979 seed; converts msg/privKey to numbers.
     * Used only in sign, not in verify.
     *
     * Warning: we cannot assume here that message has same amount of bytes as curve order,
     * this will be invalid at least for P521. Also it can be bigger for P224 + SHA256.
     */
    function prepSig(message, privateKey, opts) {
        if (['recovered', 'canonical'].some((k) => k in opts))
            throw new Error('sign() legacy options not supported');
        const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);
        message = validateMsgAndHash(message, prehash); // RFC6979 3.2 A: h1 = H(m)
        // We can't later call bits2octets, since nested bits2int is broken for curves
        // with fnBits % 8 !== 0. Because of that, we unwrap it here as int2octets call.
        // const bits2octets = (bits) => int2octets(bits2int_modN(bits))
        const h1int = bits2int_modN(message);
        const d = _normFnElement(Fn, privateKey); // validate secret key, convert to bigint
        const seedArgs = [int2octets(d), int2octets(h1int)];
        // extraEntropy. RFC6979 3.6: additional k' (optional).
        if (extraEntropy != null && extraEntropy !== false) {
            // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')
            // gen random bytes OR pass as-is
            const e = extraEntropy === true ? randomBytes(lengths.secretKey) : extraEntropy;
            seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes
        }
        const seed = concatBytes(...seedArgs); // Step D of RFC6979 3.2
        const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash!
        // Converts signature params into point w r/s, checks result for validity.
        // To transform k => Signature:
        // q = k⋅G
        // r = q.x mod n
        // s = k^-1(m + rd) mod n
        // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to
        // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:
        // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT
        function k2sig(kBytes) {
            // RFC 6979 Section 3.2, step 3: k = bits2int(T)
            // Important: all mod() calls here must be done over N
            const k = bits2int(kBytes); // mod n, not mod p
            if (!Fn.isValidNot0(k))
                return; // Valid scalars (including k) must be in 1..N-1
            const ik = Fn.inv(k); // k^-1 mod n
            const q = Point.BASE.multiply(k).toAffine(); // q = k⋅G
            const r = Fn.create(q.x); // r = q.x mod n
            if (r === _0n)
                return;
            const s = Fn.create(ik * Fn.create(m + r * d)); // Not using blinding here, see comment above
            if (s === _0n)
                return;
            let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n)
            let normS = s;
            if (lowS && isBiggerThanHalfOrder(s)) {
                normS = Fn.neg(s); // if lowS was passed, ensure s is always
                recovery ^= 1; // // in the bottom half of N
            }
            return new Signature(r, normS, recovery); // use normS, not s
        }
        return { seed, k2sig };
    }
    /**
     * Signs message hash with a secret key.
     *
     * ```
     * sign(m, d) where
     *   k = rfc6979_hmac_drbg(m, d)
     *   (x, y) = G × k
     *   r = x mod n
     *   s = (m + dr) / k mod n
     * ```
     */
    function sign(message, secretKey, opts = {}) {
        message = ensureBytes('message', message);
        const { seed, k2sig } = prepSig(message, secretKey, opts); // Steps A, D of RFC6979 3.2.
        const drbg = createHmacDrbg(hash.outputLen, Fn.BYTES, hmac);
        const sig = drbg(seed, k2sig); // Steps B, C, D, E, F, G
        return sig;
    }
    function tryParsingSig(sg) {
        // Try to deduce format
        let sig = undefined;
        const isHex = typeof sg === 'string' || isBytes(sg);
        const isObj = !isHex &&
            sg !== null &&
            typeof sg === 'object' &&
            typeof sg.r === 'bigint' &&
            typeof sg.s === 'bigint';
        if (!isHex && !isObj)
            throw new Error('invalid signature, expected Uint8Array, hex string or Signature instance');
        if (isObj) {
            sig = new Signature(sg.r, sg.s);
        }
        else if (isHex) {
            try {
                sig = Signature.fromBytes(ensureBytes('sig', sg), 'der');
            }
            catch (derError) {
                if (!(derError instanceof DER.Err))
                    throw derError;
            }
            if (!sig) {
                try {
                    sig = Signature.fromBytes(ensureBytes('sig', sg), 'compact');
                }
                catch (error) {
                    return false;
                }
            }
        }
        if (!sig)
            return false;
        return sig;
    }
    /**
     * Verifies a signature against message and public key.
     * Rejects lowS signatures by default: see {@link ECDSAVerifyOpts}.
     * Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:
     *
     * ```
     * verify(r, s, h, P) where
     *   u1 = hs^-1 mod n
     *   u2 = rs^-1 mod n
     *   R = u1⋅G + u2⋅P
     *   mod(R.x, n) == r
     * ```
     */
    function verify(signature, message, publicKey, opts = {}) {
        const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);
        publicKey = ensureBytes('publicKey', publicKey);
        message = validateMsgAndHash(ensureBytes('message', message), prehash);
        if ('strict' in opts)
            throw new Error('options.strict was renamed to lowS');
        const sig = format === undefined
            ? tryParsingSig(signature)
            : Signature.fromBytes(ensureBytes('sig', signature), format);
        if (sig === false)
            return false;
        try {
            const P = Point.fromBytes(publicKey);
            if (lowS && sig.hasHighS())
                return false;
            const { r, s } = sig;
            const h = bits2int_modN(message); // mod n, not mod p
            const is = Fn.inv(s); // s^-1 mod n
            const u1 = Fn.create(h * is); // u1 = hs^-1 mod n
            const u2 = Fn.create(r * is); // u2 = rs^-1 mod n
            const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2)); // u1⋅G + u2⋅P
            if (R.is0())
                return false;
            const v = Fn.create(R.x); // v = r.x mod n
            return v === r;
        }
        catch (e) {
            return false;
        }
    }
    function recoverPublicKey(signature, message, opts = {}) {
        const { prehash } = validateSigOpts(opts, defaultSigOpts);
        message = validateMsgAndHash(message, prehash);
        return Signature.fromBytes(signature, 'recovered').recoverPublicKey(message).toBytes();
    }
    return Object.freeze({
        keygen,
        getPublicKey,
        getSharedSecret,
        utils,
        lengths,
        Point,
        sign,
        verify,
        recoverPublicKey,
        Signature,
        hash,
    });
}
/** @deprecated use `weierstrass` in newer releases */
export function weierstrassPoints(c) {
    const { CURVE, curveOpts } = _weierstrass_legacy_opts_to_new(c);
    const Point = weierstrassN(CURVE, curveOpts);
    return _weierstrass_new_output_to_legacy(c, Point);
}
function _weierstrass_legacy_opts_to_new(c) {
    const CURVE = {
        a: c.a,
        b: c.b,
        p: c.Fp.ORDER,
        n: c.n,
        h: c.h,
        Gx: c.Gx,
        Gy: c.Gy,
    };
    const Fp = c.Fp;
    let allowedLengths = c.allowedPrivateKeyLengths
        ? Array.from(new Set(c.allowedPrivateKeyLengths.map((l) => Math.ceil(l / 2))))
        : undefined;
    const Fn = Field(CURVE.n, {
        BITS: c.nBitLength,
        allowedLengths: allowedLengths,
        modFromBytes: c.wrapPrivateKey,
    });
    const curveOpts = {
        Fp,
        Fn,
        allowInfinityPoint: c.allowInfinityPoint,
        endo: c.endo,
        isTorsionFree: c.isTorsionFree,
        clearCofactor: c.clearCofactor,
        fromBytes: c.fromBytes,
        toBytes: c.toBytes,
    };
    return { CURVE, curveOpts };
}
function _ecdsa_legacy_opts_to_new(c) {
    const { CURVE, curveOpts } = _weierstrass_legacy_opts_to_new(c);
    const ecdsaOpts = {
        hmac: c.hmac,
        randomBytes: c.randomBytes,
        lowS: c.lowS,
        bits2int: c.bits2int,
        bits2int_modN: c.bits2int_modN,
    };
    return { CURVE, curveOpts, hash: c.hash, ecdsaOpts };
}
export function _legacyHelperEquat(Fp, a, b) {
    /**
     * y² = x³ + ax + b: Short weierstrass curve formula. Takes x, returns y².
     * @returns y²
     */
    function weierstrassEquation(x) {
        const x2 = Fp.sqr(x); // x * x
        const x3 = Fp.mul(x2, x); // x² * x
        return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x³ + a * x + b
    }
    return weierstrassEquation;
}
function _weierstrass_new_output_to_legacy(c, Point) {
    const { Fp, Fn } = Point;
    function isWithinCurveOrder(num) {
        return inRange(num, _1n, Fn.ORDER);
    }
    const weierstrassEquation = _legacyHelperEquat(Fp, c.a, c.b);
    return Object.assign({}, {
        CURVE: c,
        Point: Point,
        ProjectivePoint: Point,
        normPrivateKeyToScalar: (key) => _normFnElement(Fn, key),
        weierstrassEquation,
        isWithinCurveOrder,
    });
}
function _ecdsa_new_output_to_legacy(c, _ecdsa) {
    const Point = _ecdsa.Point;
    return Object.assign({}, _ecdsa, {
        ProjectivePoint: Point,
        CURVE: Object.assign({}, c, nLength(Point.Fn.ORDER, Point.Fn.BITS)),
    });
}
// _ecdsa_legacy
export function weierstrass(c) {
    const { CURVE, curveOpts, hash, ecdsaOpts } = _ecdsa_legacy_opts_to_new(c);
    const Point = weierstrassN(CURVE, curveOpts);
    const signs = ecdsa(Point, hash, ecdsaOpts);
    return _ecdsa_new_output_to_legacy(c, signs);
}
//# sourceMappingURL=weierstrass.js.map{
  "type": "module",
  "sideEffects": false
}
/**
 * SECG secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).
 *
 * Belongs to Koblitz curves: it has efficiently-computable GLV endomorphism ψ,
 * check out {@link EndomorphismOpts}. Seems to be rigid (not backdoored).
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { sha256 } from '@noble/hashes/sha2.js';
import { randomBytes } from '@noble/hashes/utils.js';
import { createCurve } from "./_shortw_utils.js";
import { createHasher, isogenyMap, } from "./abstract/hash-to-curve.js";
import { Field, mapHashToField, mod, pow2 } from "./abstract/modular.js";
import { _normFnElement, mapToCurveSimpleSWU, } from "./abstract/weierstrass.js";
import { bytesToNumberBE, concatBytes, ensureBytes, inRange, numberToBytesBE, utf8ToBytes, } from "./utils.js";
// Seems like generator was produced from some seed:
// `Point.BASE.multiply(Point.Fn.inv(2n, N)).toAffine().x`
// // gives short x 0x3b78ce563f89a0ed9414f5aa28ad0d96d6795f9c63n
const secp256k1_CURVE = {
    p: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'),
    n: BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'),
    h: BigInt(1),
    a: BigInt(0),
    b: BigInt(7),
    Gx: BigInt('0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'),
    Gy: BigInt('0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8'),
};
const secp256k1_ENDO = {
    beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),
    basises: [
        [BigInt('0x3086d221a7d46bcde86c90e49284eb15'), -BigInt('0xe4437ed6010e88286f547fa90abfe4c3')],
        [BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'), BigInt('0x3086d221a7d46bcde86c90e49284eb15')],
    ],
};
const _0n = /* @__PURE__ */ BigInt(0);
const _1n = /* @__PURE__ */ BigInt(1);
const _2n = /* @__PURE__ */ BigInt(2);
/**
 * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.
 * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]
 */
function sqrtMod(y) {
    const P = secp256k1_CURVE.p;
    // prettier-ignore
    const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
    // prettier-ignore
    const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
    const b2 = (y * y * y) % P; // x^3, 11
    const b3 = (b2 * b2 * y) % P; // x^7
    const b6 = (pow2(b3, _3n, P) * b3) % P;
    const b9 = (pow2(b6, _3n, P) * b3) % P;
    const b11 = (pow2(b9, _2n, P) * b2) % P;
    const b22 = (pow2(b11, _11n, P) * b11) % P;
    const b44 = (pow2(b22, _22n, P) * b22) % P;
    const b88 = (pow2(b44, _44n, P) * b44) % P;
    const b176 = (pow2(b88, _88n, P) * b88) % P;
    const b220 = (pow2(b176, _44n, P) * b44) % P;
    const b223 = (pow2(b220, _3n, P) * b3) % P;
    const t1 = (pow2(b223, _23n, P) * b22) % P;
    const t2 = (pow2(t1, _6n, P) * b2) % P;
    const root = pow2(t2, _2n, P);
    if (!Fpk1.eql(Fpk1.sqr(root), y))
        throw new Error('Cannot find square root');
    return root;
}
const Fpk1 = Field(secp256k1_CURVE.p, { sqrt: sqrtMod });
/**
 * secp256k1 curve, ECDSA and ECDH methods.
 *
 * Field: `2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n`
 *
 * @example
 * ```js
 * import { secp256k1 } from '@noble/curves/secp256k1';
 * const { secretKey, publicKey } = secp256k1.keygen();
 * const msg = new TextEncoder().encode('hello');
 * const sig = secp256k1.sign(msg, secretKey);
 * const isValid = secp256k1.verify(sig, msg, publicKey) === true;
 * ```
 */
export const secp256k1 = createCurve({ ...secp256k1_CURVE, Fp: Fpk1, lowS: true, endo: secp256k1_ENDO }, sha256);
// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.
// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki
/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */
const TAGGED_HASH_PREFIXES = {};
function taggedHash(tag, ...messages) {
    let tagP = TAGGED_HASH_PREFIXES[tag];
    if (tagP === undefined) {
        const tagH = sha256(utf8ToBytes(tag));
        tagP = concatBytes(tagH, tagH);
        TAGGED_HASH_PREFIXES[tag] = tagP;
    }
    return sha256(concatBytes(tagP, ...messages));
}
// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03
const pointToBytes = (point) => point.toBytes(true).slice(1);
const Pointk1 = /* @__PURE__ */ (() => secp256k1.Point)();
const hasEven = (y) => y % _2n === _0n;
// Calculate point, scalar and bytes
function schnorrGetExtPubKey(priv) {
    const { Fn, BASE } = Pointk1;
    const d_ = _normFnElement(Fn, priv);
    const p = BASE.multiply(d_); // P = d'⋅G; 0 < d' < n check is done inside
    const scalar = hasEven(p.y) ? d_ : Fn.neg(d_);
    return { scalar, bytes: pointToBytes(p) };
}
/**
 * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.
 * @returns valid point checked for being on-curve
 */
function lift_x(x) {
    const Fp = Fpk1;
    if (!Fp.isValidNot0(x))
        throw new Error('invalid x: Fail if x ≥ p');
    const xx = Fp.create(x * x);
    const c = Fp.create(xx * x + BigInt(7)); // Let c = x³ + 7 mod p.
    let y = Fp.sqrt(c); // Let y = c^(p+1)/4 mod p. Same as sqrt().
    // Return the unique point P such that x(P) = x and
    // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.
    if (!hasEven(y))
        y = Fp.neg(y);
    const p = Pointk1.fromAffine({ x, y });
    p.assertValidity();
    return p;
}
const num = bytesToNumberBE;
/**
 * Create tagged hash, convert it to bigint, reduce modulo-n.
 */
function challenge(...args) {
    return Pointk1.Fn.create(num(taggedHash('BIP0340/challenge', ...args)));
}
/**
 * Schnorr public key is just `x` coordinate of Point as per BIP340.
 */
function schnorrGetPublicKey(secretKey) {
    return schnorrGetExtPubKey(secretKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G)
}
/**
 * Creates Schnorr signature as per BIP340. Verifies itself before returning anything.
 * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous.
 */
function schnorrSign(message, secretKey, auxRand = randomBytes(32)) {
    const { Fn } = Pointk1;
    const m = ensureBytes('message', message);
    const { bytes: px, scalar: d } = schnorrGetExtPubKey(secretKey); // checks for isWithinCurveOrder
    const a = ensureBytes('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array
    const t = Fn.toBytes(d ^ num(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a)
    const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m)
    // Let k' = int(rand) mod n. Fail if k' = 0. Let R = k'⋅G
    const { bytes: rx, scalar: k } = schnorrGetExtPubKey(rand);
    const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.
    const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n).
    sig.set(rx, 0);
    sig.set(Fn.toBytes(Fn.create(k + e * d)), 32);
    // If Verify(bytes(P), m, sig) (see below) returns failure, abort
    if (!schnorrVerify(sig, m, px))
        throw new Error('sign: Invalid signature produced');
    return sig;
}
/**
 * Verifies Schnorr signature.
 * Will swallow errors & return false except for initial type validation of arguments.
 */
function schnorrVerify(signature, message, publicKey) {
    const { Fn, BASE } = Pointk1;
    const sig = ensureBytes('signature', signature, 64);
    const m = ensureBytes('message', message);
    const pub = ensureBytes('publicKey', publicKey, 32);
    try {
        const P = lift_x(num(pub)); // P = lift_x(int(pk)); fail if that fails
        const r = num(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r ≥ p.
        if (!inRange(r, _1n, secp256k1_CURVE.p))
            return false;
        const s = num(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n.
        if (!inRange(s, _1n, secp256k1_CURVE.n))
            return false;
        // int(challenge(bytes(r)||bytes(P)||m))%n
        const e = challenge(Fn.toBytes(r), pointToBytes(P), m);
        // R = s⋅G - e⋅P, where -eP == (n-e)P
        const R = BASE.multiplyUnsafe(s).add(P.multiplyUnsafe(Fn.neg(e)));
        const { x, y } = R.toAffine();
        // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r.
        if (R.is0() || !hasEven(y) || x !== r)
            return false;
        return true;
    }
    catch (error) {
        return false;
    }
}
/**
 * Schnorr signatures over secp256k1.
 * https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki
 * @example
 * ```js
 * import { schnorr } from '@noble/curves/secp256k1';
 * const { secretKey, publicKey } = schnorr.keygen();
 * // const publicKey = schnorr.getPublicKey(secretKey);
 * const msg = new TextEncoder().encode('hello');
 * const sig = schnorr.sign(msg, secretKey);
 * const isValid = schnorr.verify(sig, msg, publicKey);
 * ```
 */
export const schnorr = /* @__PURE__ */ (() => {
    const size = 32;
    const seedLength = 48;
    const randomSecretKey = (seed = randomBytes(seedLength)) => {
        return mapHashToField(seed, secp256k1_CURVE.n);
    };
    // TODO: remove
    secp256k1.utils.randomSecretKey;
    function keygen(seed) {
        const secretKey = randomSecretKey(seed);
        return { secretKey, publicKey: schnorrGetPublicKey(secretKey) };
    }
    return {
        keygen,
        getPublicKey: schnorrGetPublicKey,
        sign: schnorrSign,
        verify: schnorrVerify,
        Point: Pointk1,
        utils: {
            randomSecretKey: randomSecretKey,
            randomPrivateKey: randomSecretKey,
            taggedHash,
            // TODO: remove
            lift_x,
            pointToBytes,
            numberToBytesBE,
            bytesToNumberBE,
            mod,
        },
        lengths: {
            secretKey: size,
            publicKey: size,
            publicKeyHasPrefix: false,
            signature: size * 2,
            seed: seedLength,
        },
    };
})();
const isoMap = /* @__PURE__ */ (() => isogenyMap(Fpk1, [
    // xNum
    [
        '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7',
        '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581',
        '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262',
        '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c',
    ],
    // xDen
    [
        '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b',
        '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14',
        '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1
    ],
    // yNum
    [
        '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c',
        '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3',
        '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931',
        '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84',
    ],
    // yDen
    [
        '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b',
        '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573',
        '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f',
        '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1
    ],
].map((i) => i.map((j) => BigInt(j)))))();
const mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fpk1, {
    A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),
    B: BigInt('1771'),
    Z: Fpk1.create(BigInt('-11')),
}))();
/** Hashing / encoding to secp256k1 points / field. RFC 9380 methods. */
export const secp256k1_hasher = /* @__PURE__ */ (() => createHasher(secp256k1.Point, (scalars) => {
    const { x, y } = mapSWU(Fpk1.create(scalars[0]));
    return isoMap(x, y);
}, {
    DST: 'secp256k1_XMD:SHA-256_SSWU_RO_',
    encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_',
    p: Fpk1.ORDER,
    m: 1,
    k: 128,
    expand: 'xmd',
    hash: sha256,
}))();
/** @deprecated use `import { secp256k1_hasher } from '@noble/curves/secp256k1.js';` */
export const hashToCurve = /* @__PURE__ */ (() => secp256k1_hasher.hashToCurve)();
/** @deprecated use `import { secp256k1_hasher } from '@noble/curves/secp256k1.js';` */
export const encodeToCurve = /* @__PURE__ */ (() => secp256k1_hasher.encodeToCurve)();
//# sourceMappingURL=secp256k1.js.map/**
 * Hex, bytes and number utilities.
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { abytes as abytes_, bytesToHex as bytesToHex_, concatBytes as concatBytes_, hexToBytes as hexToBytes_, isBytes as isBytes_, } from '@noble/hashes/utils.js';
export { abytes, anumber, bytesToHex, bytesToUtf8, concatBytes, hexToBytes, isBytes, randomBytes, utf8ToBytes, } from '@noble/hashes/utils.js';
const _0n = /* @__PURE__ */ BigInt(0);
const _1n = /* @__PURE__ */ BigInt(1);
export function abool(title, value) {
    if (typeof value !== 'boolean')
        throw new Error(title + ' boolean expected, got ' + value);
}
// tmp name until v2
export function _abool2(value, title = '') {
    if (typeof value !== 'boolean') {
        const prefix = title && `"${title}"`;
        throw new Error(prefix + 'expected boolean, got type=' + typeof value);
    }
    return value;
}
// tmp name until v2
/** Asserts something is Uint8Array. */
export function _abytes2(value, length, title = '') {
    const bytes = isBytes_(value);
    const len = value?.length;
    const needsLen = length !== undefined;
    if (!bytes || (needsLen && len !== length)) {
        const prefix = title && `"${title}" `;
        const ofLen = needsLen ? ` of length ${length}` : '';
        const got = bytes ? `length=${len}` : `type=${typeof value}`;
        throw new Error(prefix + 'expected Uint8Array' + ofLen + ', got ' + got);
    }
    return value;
}
// Used in weierstrass, der
export function numberToHexUnpadded(num) {
    const hex = num.toString(16);
    return hex.length & 1 ? '0' + hex : hex;
}
export function hexToNumber(hex) {
    if (typeof hex !== 'string')
        throw new Error('hex string expected, got ' + typeof hex);
    return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian
}
// BE: Big Endian, LE: Little Endian
export function bytesToNumberBE(bytes) {
    return hexToNumber(bytesToHex_(bytes));
}
export function bytesToNumberLE(bytes) {
    abytes_(bytes);
    return hexToNumber(bytesToHex_(Uint8Array.from(bytes).reverse()));
}
export function numberToBytesBE(n, len) {
    return hexToBytes_(n.toString(16).padStart(len * 2, '0'));
}
export function numberToBytesLE(n, len) {
    return numberToBytesBE(n, len).reverse();
}
// Unpadded, rarely used
export function numberToVarBytesBE(n) {
    return hexToBytes_(numberToHexUnpadded(n));
}
/**
 * Takes hex string or Uint8Array, converts to Uint8Array.
 * Validates output length.
 * Will throw error for other types.
 * @param title descriptive title for an error e.g. 'secret key'
 * @param hex hex string or Uint8Array
 * @param expectedLength optional, will compare to result array's length
 * @returns
 */
export function ensureBytes(title, hex, expectedLength) {
    let res;
    if (typeof hex === 'string') {
        try {
            res = hexToBytes_(hex);
        }
        catch (e) {
            throw new Error(title + ' must be hex string or Uint8Array, cause: ' + e);
        }
    }
    else if (isBytes_(hex)) {
        // Uint8Array.from() instead of hash.slice() because node.js Buffer
        // is instance of Uint8Array, and its slice() creates **mutable** copy
        res = Uint8Array.from(hex);
    }
    else {
        throw new Error(title + ' must be hex string or Uint8Array');
    }
    const len = res.length;
    if (typeof expectedLength === 'number' && len !== expectedLength)
        throw new Error(title + ' of length ' + expectedLength + ' expected, got ' + len);
    return res;
}
// Compares 2 u8a-s in kinda constant time
export function equalBytes(a, b) {
    if (a.length !== b.length)
        return false;
    let diff = 0;
    for (let i = 0; i < a.length; i++)
        diff |= a[i] ^ b[i];
    return diff === 0;
}
/**
 * Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,
 * and Buffer#slice creates mutable copy. Never use Buffers!
 */
export function copyBytes(bytes) {
    return Uint8Array.from(bytes);
}
/**
 * Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols
 * Should be safe to use for things expected to be ASCII.
 * Returns exact same result as utf8ToBytes for ASCII or throws.
 */
export function asciiToBytes(ascii) {
    return Uint8Array.from(ascii, (c, i) => {
        const charCode = c.charCodeAt(0);
        if (c.length !== 1 || charCode > 127) {
            throw new Error(`string contains non-ASCII character "${ascii[i]}" with code ${charCode} at position ${i}`);
        }
        return charCode;
    });
}
/**
 * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
 */
// export const utf8ToBytes: typeof utf8ToBytes_ = utf8ToBytes_;
/**
 * Converts bytes to string using UTF8 encoding.
 * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'
 */
// export const bytesToUtf8: typeof bytesToUtf8_ = bytesToUtf8_;
// Is positive bigint
const isPosBig = (n) => typeof n === 'bigint' && _0n <= n;
export function inRange(n, min, max) {
    return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
}
/**
 * Asserts min <= n < max. NOTE: It's < max and not <= max.
 * @example
 * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)
 */
export function aInRange(title, n, min, max) {
    // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?
    // consider P=256n, min=0n, max=P
    // - a for min=0 would require -1:          `inRange('x', x, -1n, P)`
    // - b would commonly require subtraction:  `inRange('x', x, 0n, P - 1n)`
    // - our way is the cleanest:               `inRange('x', x, 0n, P)
    if (!inRange(n, min, max))
        throw new Error('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);
}
// Bit operations
/**
 * Calculates amount of bits in a bigint.
 * Same as `n.toString(2).length`
 * TODO: merge with nLength in modular
 */
export function bitLen(n) {
    let len;
    for (len = 0; n > _0n; n >>= _1n, len += 1)
        ;
    return len;
}
/**
 * Gets single bit at position.
 * NOTE: first bit position is 0 (same as arrays)
 * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`
 */
export function bitGet(n, pos) {
    return (n >> BigInt(pos)) & _1n;
}
/**
 * Sets single bit at position.
 */
export function bitSet(n, pos, value) {
    return n | ((value ? _1n : _0n) << BigInt(pos));
}
/**
 * Calculate mask for N bits. Not using ** operator with bigints because of old engines.
 * Same as BigInt(`0b${Array(i).fill('1').join('')}`)
 */
export const bitMask = (n) => (_1n << BigInt(n)) - _1n;
/**
 * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
 * @returns function that will call DRBG until 2nd arg returns something meaningful
 * @example
 *   const drbg = createHmacDRBG<Key>(32, 32, hmac);
 *   drbg(seed, bytesToKey); // bytesToKey must return Key or undefined
 */
export function createHmacDrbg(hashLen, qByteLen, hmacFn) {
    if (typeof hashLen !== 'number' || hashLen < 2)
        throw new Error('hashLen must be a number');
    if (typeof qByteLen !== 'number' || qByteLen < 2)
        throw new Error('qByteLen must be a number');
    if (typeof hmacFn !== 'function')
        throw new Error('hmacFn must be a function');
    // Step B, Step C: set hashLen to 8*ceil(hlen/8)
    const u8n = (len) => new Uint8Array(len); // creates Uint8Array
    const u8of = (byte) => Uint8Array.of(byte); // another shortcut
    let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
    let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same
    let i = 0; // Iterations counter, will throw when over 1000
    const reset = () => {
        v.fill(1);
        k.fill(0);
        i = 0;
    };
    const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)
    const reseed = (seed = u8n(0)) => {
        // HMAC-DRBG reseed() function. Steps D-G
        k = h(u8of(0x00), seed); // k = hmac(k || v || 0x00 || seed)
        v = h(); // v = hmac(k || v)
        if (seed.length === 0)
            return;
        k = h(u8of(0x01), seed); // k = hmac(k || v || 0x01 || seed)
        v = h(); // v = hmac(k || v)
    };
    const gen = () => {
        // HMAC-DRBG generate() function
        if (i++ >= 1000)
            throw new Error('drbg: tried 1000 values');
        let len = 0;
        const out = [];
        while (len < qByteLen) {
            v = h();
            const sl = v.slice();
            out.push(sl);
            len += v.length;
        }
        return concatBytes_(...out);
    };
    const genUntil = (seed, pred) => {
        reset();
        reseed(seed); // Steps D-G
        let res = undefined; // Step H: grind until k is in [1..n-1]
        while (!(res = pred(gen())))
            reseed();
        reset();
        return res;
    };
    return genUntil;
}
// Validating curves and fields
const validatorFns = {
    bigint: (val) => typeof val === 'bigint',
    function: (val) => typeof val === 'function',
    boolean: (val) => typeof val === 'boolean',
    string: (val) => typeof val === 'string',
    stringOrUint8Array: (val) => typeof val === 'string' || isBytes_(val),
    isSafeInteger: (val) => Number.isSafeInteger(val),
    array: (val) => Array.isArray(val),
    field: (val, object) => object.Fp.isValid(val),
    hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),
};
// type Record<K extends string | number | symbol, T> = { [P in K]: T; }
export function validateObject(object, validators, optValidators = {}) {
    const checkField = (fieldName, type, isOptional) => {
        const checkVal = validatorFns[type];
        if (typeof checkVal !== 'function')
            throw new Error('invalid validator function');
        const val = object[fieldName];
        if (isOptional && val === undefined)
            return;
        if (!checkVal(val, object)) {
            throw new Error('param ' + String(fieldName) + ' is invalid. Expected ' + type + ', got ' + val);
        }
    };
    for (const [fieldName, type] of Object.entries(validators))
        checkField(fieldName, type, false);
    for (const [fieldName, type] of Object.entries(optValidators))
        checkField(fieldName, type, true);
    return object;
}
// validate type tests
// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };
// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!
// // Should fail type-check
// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });
// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });
// const z3 = validateObject(o, { test: 'boolean', z: 'bug' });
// const z4 = validateObject(o, { a: 'boolean', z: 'bug' });
export function isHash(val) {
    return typeof val === 'function' && Number.isSafeInteger(val.outputLen);
}
export function _validateObject(object, fields, optFields = {}) {
    if (!object || typeof object !== 'object')
        throw new Error('expected valid options object');
    function checkField(fieldName, expectedType, isOpt) {
        const val = object[fieldName];
        if (isOpt && val === undefined)
            return;
        const current = typeof val;
        if (current !== expectedType || val === null)
            throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
    }
    Object.entries(fields).forEach(([k, v]) => checkField(k, v, false));
    Object.entries(optFields).forEach(([k, v]) => checkField(k, v, true));
}
/**
 * throws not implemented error
 */
export const notImplemented = () => {
    throw new Error('not implemented');
};
/**
 * Memoizes (caches) computation result.
 * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.
 */
export function memoized(fn) {
    const map = new WeakMap();
    return (arg, ...args) => {
        const val = map.get(arg);
        if (val !== undefined)
            return val;
        const computed = fn(arg, ...args);
        map.set(arg, computed);
        return computed;
    };
}
//# sourceMappingURL=utils.js.map/**
 * Internal Merkle-Damgard hash utils.
 * @module
 */
import { Hash, abytes, aexists, aoutput, clean, createView, toBytes } from "./utils.js";
/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */
export function setBigUint64(view, byteOffset, value, isLE) {
    if (typeof view.setBigUint64 === 'function')
        return view.setBigUint64(byteOffset, value, isLE);
    const _32n = BigInt(32);
    const _u32_max = BigInt(0xffffffff);
    const wh = Number((value >> _32n) & _u32_max);
    const wl = Number(value & _u32_max);
    const h = isLE ? 4 : 0;
    const l = isLE ? 0 : 4;
    view.setUint32(byteOffset + h, wh, isLE);
    view.setUint32(byteOffset + l, wl, isLE);
}
/** Choice: a ? b : c */
export function Chi(a, b, c) {
    return (a & b) ^ (~a & c);
}
/** Majority function, true if any two inputs is true. */
export function Maj(a, b, c) {
    return (a & b) ^ (a & c) ^ (b & c);
}
/**
 * Merkle-Damgard hash construction base class.
 * Could be used to create MD5, RIPEMD, SHA1, SHA2.
 */
export class HashMD extends Hash {
    constructor(blockLen, outputLen, padOffset, isLE) {
        super();
        this.finished = false;
        this.length = 0;
        this.pos = 0;
        this.destroyed = false;
        this.blockLen = blockLen;
        this.outputLen = outputLen;
        this.padOffset = padOffset;
        this.isLE = isLE;
        this.buffer = new Uint8Array(blockLen);
        this.view = createView(this.buffer);
    }
    update(data) {
        aexists(this);
        data = toBytes(data);
        abytes(data);
        const { view, buffer, blockLen } = this;
        const len = data.length;
        for (let pos = 0; pos < len;) {
            const take = Math.min(blockLen - this.pos, len - pos);
            // Fast path: we have at least one block in input, cast it to view and process
            if (take === blockLen) {
                const dataView = createView(data);
                for (; blockLen <= len - pos; pos += blockLen)
                    this.process(dataView, pos);
                continue;
            }
            buffer.set(data.subarray(pos, pos + take), this.pos);
            this.pos += take;
            pos += take;
            if (this.pos === blockLen) {
                this.process(view, 0);
                this.pos = 0;
            }
        }
        this.length += data.length;
        this.roundClean();
        return this;
    }
    digestInto(out) {
        aexists(this);
        aoutput(out, this);
        this.finished = true;
        // Padding
        // We can avoid allocation of buffer for padding completely if it
        // was previously not allocated here. But it won't change performance.
        const { buffer, view, blockLen, isLE } = this;
        let { pos } = this;
        // append the bit '1' to the message
        buffer[pos++] = 0b10000000;
        clean(this.buffer.subarray(pos));
        // we have less than padOffset left in buffer, so we cannot put length in
        // current block, need process it and pad again
        if (this.padOffset > blockLen - pos) {
            this.process(view, 0);
            pos = 0;
        }
        // Pad until full block byte with zeros
        for (let i = pos; i < blockLen; i++)
            buffer[i] = 0;
        // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that
        // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.
        // So we just write lowest 64 bits of that value.
        setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
        this.process(view, 0);
        const oview = createView(out);
        const len = this.outputLen;
        // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT
        if (len % 4)
            throw new Error('_sha2: outputLen should be aligned to 32bit');
        const outLen = len / 4;
        const state = this.get();
        if (outLen > state.length)
            throw new Error('_sha2: outputLen bigger than state');
        for (let i = 0; i < outLen; i++)
            oview.setUint32(4 * i, state[i], isLE);
    }
    digest() {
        const { buffer, outputLen } = this;
        this.digestInto(buffer);
        const res = buffer.slice(0, outputLen);
        this.destroy();
        return res;
    }
    _cloneInto(to) {
        to || (to = new this.constructor());
        to.set(...this.get());
        const { blockLen, buffer, length, finished, destroyed, pos } = this;
        to.destroyed = destroyed;
        to.finished = finished;
        to.length = length;
        to.pos = pos;
        if (length % blockLen)
            to.buffer.set(buffer);
        return to;
    }
    clone() {
        return this._cloneInto();
    }
}
/**
 * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.
 * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.
 */
/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */
export const SHA256_IV = /* @__PURE__ */ Uint32Array.from([
    0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
]);
/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */
export const SHA224_IV = /* @__PURE__ */ Uint32Array.from([
    0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,
]);
/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */
export const SHA384_IV = /* @__PURE__ */ Uint32Array.from([
    0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,
    0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,
]);
/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */
export const SHA512_IV = /* @__PURE__ */ Uint32Array.from([
    0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,
    0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,
]);
//# sourceMappingURL=_md.js.map/**
 * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.
 * @todo re-check https://issues.chromium.org/issues/42212588
 * @module
 */
const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
const _32n = /* @__PURE__ */ BigInt(32);
function fromBig(n, le = false) {
    if (le)
        return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };
    return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
}
function split(lst, le = false) {
    const len = lst.length;
    let Ah = new Uint32Array(len);
    let Al = new Uint32Array(len);
    for (let i = 0; i < len; i++) {
        const { h, l } = fromBig(lst[i], le);
        [Ah[i], Al[i]] = [h, l];
    }
    return [Ah, Al];
}
const toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);
// for Shift in [0, 32)
const shrSH = (h, _l, s) => h >>> s;
const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
// Right rotate for Shift in [1, 32)
const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));
const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
// Right rotate for Shift in (32, 64), NOTE: 32 is special case.
const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));
const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));
// Right rotate for shift===32 (just swaps l&h)
const rotr32H = (_h, l) => l;
const rotr32L = (h, _l) => h;
// Left rotate for Shift in [1, 32)
const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));
const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));
// Left rotate for Shift in (32, 64), NOTE: 32 is special case.
const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));
const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));
// JS uses 32-bit signed integers for bitwise operations which means we cannot
// simple take carry out of low bit sum by shift, we need to use division.
function add(Ah, Al, Bh, Bl) {
    const l = (Al >>> 0) + (Bl >>> 0);
    return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };
}
// Addition with more than 2 elements
const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;
const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;
const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;
// prettier-ignore
export { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig };
// prettier-ignore
const u64 = {
    fromBig, split, toBig,
    shrSH, shrSL,
    rotrSH, rotrSL, rotrBH, rotrBL,
    rotr32H, rotr32L,
    rotlSH, rotlSL, rotlBH, rotlBL,
    add, add3L, add3H, add4L, add4H, add5H, add5L,
};
export default u64;
//# sourceMappingURL=_u64.js.mapexport const crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;
//# sourceMappingURL=crypto.js.map/**
 * HMAC: RFC2104 message authentication code.
 * @module
 */
import { abytes, aexists, ahash, clean, Hash, toBytes } from "./utils.js";
export class HMAC extends Hash {
    constructor(hash, _key) {
        super();
        this.finished = false;
        this.destroyed = false;
        ahash(hash);
        const key = toBytes(_key);
        this.iHash = hash.create();
        if (typeof this.iHash.update !== 'function')
            throw new Error('Expected instance of class which extends utils.Hash');
        this.blockLen = this.iHash.blockLen;
        this.outputLen = this.iHash.outputLen;
        const blockLen = this.blockLen;
        const pad = new Uint8Array(blockLen);
        // blockLen can be bigger than outputLen
        pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
        for (let i = 0; i < pad.length; i++)
            pad[i] ^= 0x36;
        this.iHash.update(pad);
        // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone
        this.oHash = hash.create();
        // Undo internal XOR && apply outer XOR
        for (let i = 0; i < pad.length; i++)
            pad[i] ^= 0x36 ^ 0x5c;
        this.oHash.update(pad);
        clean(pad);
    }
    update(buf) {
        aexists(this);
        this.iHash.update(buf);
        return this;
    }
    digestInto(out) {
        aexists(this);
        abytes(out, this.outputLen);
        this.finished = true;
        this.iHash.digestInto(out);
        this.oHash.update(out);
        this.oHash.digestInto(out);
        this.destroy();
    }
    digest() {
        const out = new Uint8Array(this.oHash.outputLen);
        this.digestInto(out);
        return out;
    }
    _cloneInto(to) {
        // Create new instance without calling constructor since key already in state and we don't know it.
        to || (to = Object.create(Object.getPrototypeOf(this), {}));
        const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
        to = to;
        to.finished = finished;
        to.destroyed = destroyed;
        to.blockLen = blockLen;
        to.outputLen = outputLen;
        to.oHash = oHash._cloneInto(to.oHash);
        to.iHash = iHash._cloneInto(to.iHash);
        return to;
    }
    clone() {
        return this._cloneInto();
    }
    destroy() {
        this.destroyed = true;
        this.oHash.destroy();
        this.iHash.destroy();
    }
}
/**
 * HMAC: RFC2104 message authentication code.
 * @param hash - function that would be used e.g. sha256
 * @param key - message key
 * @param message - message data
 * @example
 * import { hmac } from '@noble/hashes/hmac';
 * import { sha256 } from '@noble/hashes/sha2';
 * const mac1 = hmac(sha256, 'key', 'message');
 */
export const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
hmac.create = (hash, key) => new HMAC(hash, key);
//# sourceMappingURL=hmac.js.map/**

SHA1 (RFC 3174), MD5 (RFC 1321) and RIPEMD160 (RFC 2286) legacy, weak hash functions.
Don't use them in a new protocol. What "weak" means:

- Collisions can be made with 2^18 effort in MD5, 2^60 in SHA1, 2^80 in RIPEMD160.
- No practical pre-image attacks (only theoretical, 2^123.4)
- HMAC seems kinda ok: https://datatracker.ietf.org/doc/html/rfc6151
 * @module
 */
import { Chi, HashMD, Maj } from "./_md.js";
import { clean, createHasher, rotl } from "./utils.js";
/** Initial SHA1 state */
const SHA1_IV = /* @__PURE__ */ Uint32Array.from([
    0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0,
]);
// Reusable temporary buffer
const SHA1_W = /* @__PURE__ */ new Uint32Array(80);
/** SHA1 legacy hash class. */
export class SHA1 extends HashMD {
    constructor() {
        super(64, 20, 8, false);
        this.A = SHA1_IV[0] | 0;
        this.B = SHA1_IV[1] | 0;
        this.C = SHA1_IV[2] | 0;
        this.D = SHA1_IV[3] | 0;
        this.E = SHA1_IV[4] | 0;
    }
    get() {
        const { A, B, C, D, E } = this;
        return [A, B, C, D, E];
    }
    set(A, B, C, D, E) {
        this.A = A | 0;
        this.B = B | 0;
        this.C = C | 0;
        this.D = D | 0;
        this.E = E | 0;
    }
    process(view, offset) {
        for (let i = 0; i < 16; i++, offset += 4)
            SHA1_W[i] = view.getUint32(offset, false);
        for (let i = 16; i < 80; i++)
            SHA1_W[i] = rotl(SHA1_W[i - 3] ^ SHA1_W[i - 8] ^ SHA1_W[i - 14] ^ SHA1_W[i - 16], 1);
        // Compression function main loop, 80 rounds
        let { A, B, C, D, E } = this;
        for (let i = 0; i < 80; i++) {
            let F, K;
            if (i < 20) {
                F = Chi(B, C, D);
                K = 0x5a827999;
            }
            else if (i < 40) {
                F = B ^ C ^ D;
                K = 0x6ed9eba1;
            }
            else if (i < 60) {
                F = Maj(B, C, D);
                K = 0x8f1bbcdc;
            }
            else {
                F = B ^ C ^ D;
                K = 0xca62c1d6;
            }
            const T = (rotl(A, 5) + F + E + K + SHA1_W[i]) | 0;
            E = D;
            D = C;
            C = rotl(B, 30);
            B = A;
            A = T;
        }
        // Add the compressed chunk to the current hash value
        A = (A + this.A) | 0;
        B = (B + this.B) | 0;
        C = (C + this.C) | 0;
        D = (D + this.D) | 0;
        E = (E + this.E) | 0;
        this.set(A, B, C, D, E);
    }
    roundClean() {
        clean(SHA1_W);
    }
    destroy() {
        this.set(0, 0, 0, 0, 0);
        clean(this.buffer);
    }
}
/** SHA1 (RFC 3174) legacy hash function. It was cryptographically broken. */
export const sha1 = /* @__PURE__ */ createHasher(() => new SHA1());
/** Per-round constants */
const p32 = /* @__PURE__ */ Math.pow(2, 32);
const K = /* @__PURE__ */ Array.from({ length: 64 }, (_, i) => Math.floor(p32 * Math.abs(Math.sin(i + 1))));
/** md5 initial state: same as sha1, but 4 u32 instead of 5. */
const MD5_IV = /* @__PURE__ */ SHA1_IV.slice(0, 4);
// Reusable temporary buffer
const MD5_W = /* @__PURE__ */ new Uint32Array(16);
/** MD5 legacy hash class. */
export class MD5 extends HashMD {
    constructor() {
        super(64, 16, 8, true);
        this.A = MD5_IV[0] | 0;
        this.B = MD5_IV[1] | 0;
        this.C = MD5_IV[2] | 0;
        this.D = MD5_IV[3] | 0;
    }
    get() {
        const { A, B, C, D } = this;
        return [A, B, C, D];
    }
    set(A, B, C, D) {
        this.A = A | 0;
        this.B = B | 0;
        this.C = C | 0;
        this.D = D | 0;
    }
    process(view, offset) {
        for (let i = 0; i < 16; i++, offset += 4)
            MD5_W[i] = view.getUint32(offset, true);
        // Compression function main loop, 64 rounds
        let { A, B, C, D } = this;
        for (let i = 0; i < 64; i++) {
            let F, g, s;
            if (i < 16) {
                F = Chi(B, C, D);
                g = i;
                s = [7, 12, 17, 22];
            }
            else if (i < 32) {
                F = Chi(D, B, C);
                g = (5 * i + 1) % 16;
                s = [5, 9, 14, 20];
            }
            else if (i < 48) {
                F = B ^ C ^ D;
                g = (3 * i + 5) % 16;
                s = [4, 11, 16, 23];
            }
            else {
                F = C ^ (B | ~D);
                g = (7 * i) % 16;
                s = [6, 10, 15, 21];
            }
            F = F + A + K[i] + MD5_W[g];
            A = D;
            D = C;
            C = B;
            B = B + rotl(F, s[i % 4]);
        }
        // Add the compressed chunk to the current hash value
        A = (A + this.A) | 0;
        B = (B + this.B) | 0;
        C = (C + this.C) | 0;
        D = (D + this.D) | 0;
        this.set(A, B, C, D);
    }
    roundClean() {
        clean(MD5_W);
    }
    destroy() {
        this.set(0, 0, 0, 0);
        clean(this.buffer);
    }
}
/**
 * MD5 (RFC 1321) legacy hash function. It was cryptographically broken.
 * MD5 architecture is similar to SHA1, with some differences:
 * - Reduced output length: 16 bytes (128 bit) instead of 20
 * - 64 rounds, instead of 80
 * - Little-endian: could be faster, but will require more code
 * - Non-linear index selection: huge speed-up for unroll
 * - Per round constants: more memory accesses, additional speed-up for unroll
 */
export const md5 = /* @__PURE__ */ createHasher(() => new MD5());
// RIPEMD-160
const Rho160 = /* @__PURE__ */ Uint8Array.from([
    7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
]);
const Id160 = /* @__PURE__ */ (() => Uint8Array.from(new Array(16).fill(0).map((_, i) => i)))();
const Pi160 = /* @__PURE__ */ (() => Id160.map((i) => (9 * i + 5) % 16))();
const idxLR = /* @__PURE__ */ (() => {
    const L = [Id160];
    const R = [Pi160];
    const res = [L, R];
    for (let i = 0; i < 4; i++)
        for (let j of res)
            j.push(j[i].map((k) => Rho160[k]));
    return res;
})();
const idxL = /* @__PURE__ */ (() => idxLR[0])();
const idxR = /* @__PURE__ */ (() => idxLR[1])();
// const [idxL, idxR] = idxLR;
const shifts160 = /* @__PURE__ */ [
    [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8],
    [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7],
    [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9],
    [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6],
    [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5],
].map((i) => Uint8Array.from(i));
const shiftsL160 = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts160[i][j]));
const shiftsR160 = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts160[i][j]));
const Kl160 = /* @__PURE__ */ Uint32Array.from([
    0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e,
]);
const Kr160 = /* @__PURE__ */ Uint32Array.from([
    0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000,
]);
// It's called f() in spec.
function ripemd_f(group, x, y, z) {
    if (group === 0)
        return x ^ y ^ z;
    if (group === 1)
        return (x & y) | (~x & z);
    if (group === 2)
        return (x | ~y) ^ z;
    if (group === 3)
        return (x & z) | (y & ~z);
    return x ^ (y | ~z);
}
// Reusable temporary buffer
const BUF_160 = /* @__PURE__ */ new Uint32Array(16);
export class RIPEMD160 extends HashMD {
    constructor() {
        super(64, 20, 8, true);
        this.h0 = 0x67452301 | 0;
        this.h1 = 0xefcdab89 | 0;
        this.h2 = 0x98badcfe | 0;
        this.h3 = 0x10325476 | 0;
        this.h4 = 0xc3d2e1f0 | 0;
    }
    get() {
        const { h0, h1, h2, h3, h4 } = this;
        return [h0, h1, h2, h3, h4];
    }
    set(h0, h1, h2, h3, h4) {
        this.h0 = h0 | 0;
        this.h1 = h1 | 0;
        this.h2 = h2 | 0;
        this.h3 = h3 | 0;
        this.h4 = h4 | 0;
    }
    process(view, offset) {
        for (let i = 0; i < 16; i++, offset += 4)
            BUF_160[i] = view.getUint32(offset, true);
        // prettier-ignore
        let al = this.h0 | 0, ar = al, bl = this.h1 | 0, br = bl, cl = this.h2 | 0, cr = cl, dl = this.h3 | 0, dr = dl, el = this.h4 | 0, er = el;
        // Instead of iterating 0 to 80, we split it into 5 groups
        // And use the groups in constants, functions, etc. Much simpler
        for (let group = 0; group < 5; group++) {
            const rGroup = 4 - group;
            const hbl = Kl160[group], hbr = Kr160[group]; // prettier-ignore
            const rl = idxL[group], rr = idxR[group]; // prettier-ignore
            const sl = shiftsL160[group], sr = shiftsR160[group]; // prettier-ignore
            for (let i = 0; i < 16; i++) {
                const tl = (rotl(al + ripemd_f(group, bl, cl, dl) + BUF_160[rl[i]] + hbl, sl[i]) + el) | 0;
                al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore
            }
            // 2 loops are 10% faster
            for (let i = 0; i < 16; i++) {
                const tr = (rotl(ar + ripemd_f(rGroup, br, cr, dr) + BUF_160[rr[i]] + hbr, sr[i]) + er) | 0;
                ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr; // prettier-ignore
            }
        }
        // Add the compressed chunk to the current hash value
        this.set((this.h1 + cl + dr) | 0, (this.h2 + dl + er) | 0, (this.h3 + el + ar) | 0, (this.h4 + al + br) | 0, (this.h0 + bl + cr) | 0);
    }
    roundClean() {
        clean(BUF_160);
    }
    destroy() {
        this.destroyed = true;
        clean(this.buffer);
        this.set(0, 0, 0, 0, 0);
    }
}
/**
 * RIPEMD-160 - a legacy hash function from 1990s.
 * * https://homes.esat.kuleuven.be/~bosselae/ripemd160.html
 * * https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf
 */
export const ripemd160 = /* @__PURE__ */ createHasher(() => new RIPEMD160());
//# sourceMappingURL=legacy.js.map{
  "type": "module",
  "sideEffects": false,
  "browser": {
    "node:crypto": false
  },
  "node": {
    "./crypto": "./esm/cryptoNode.js"
  }
}
/**
 * PBKDF (RFC 2898). Can be used to create a key from password and salt.
 * @module
 */
import { hmac } from "./hmac.js";
// prettier-ignore
import { ahash, anumber, asyncLoop, checkOpts, clean, createView, Hash, kdfInputToBytes } from "./utils.js";
// Common prologue and epilogue for sync/async functions
function pbkdf2Init(hash, _password, _salt, _opts) {
    ahash(hash);
    const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts);
    const { c, dkLen, asyncTick } = opts;
    anumber(c);
    anumber(dkLen);
    anumber(asyncTick);
    if (c < 1)
        throw new Error('iterations (c) should be >= 1');
    const password = kdfInputToBytes(_password);
    const salt = kdfInputToBytes(_salt);
    // DK = PBKDF2(PRF, Password, Salt, c, dkLen);
    const DK = new Uint8Array(dkLen);
    // U1 = PRF(Password, Salt + INT_32_BE(i))
    const PRF = hmac.create(hash, password);
    const PRFSalt = PRF._cloneInto().update(salt);
    return { c, dkLen, asyncTick, DK, PRF, PRFSalt };
}
function pbkdf2Output(PRF, PRFSalt, DK, prfW, u) {
    PRF.destroy();
    PRFSalt.destroy();
    if (prfW)
        prfW.destroy();
    clean(u);
    return DK;
}
/**
 * PBKDF2-HMAC: RFC 2898 key derivation function
 * @param hash - hash function that would be used e.g. sha256
 * @param password - password from which a derived key is generated
 * @param salt - cryptographic salt
 * @param opts - {c, dkLen} where c is work factor and dkLen is output message size
 * @example
 * const key = pbkdf2(sha256, 'password', 'salt', { dkLen: 32, c: Math.pow(2, 18) });
 */
export function pbkdf2(hash, password, salt, opts) {
    const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);
    let prfW; // Working copy
    const arr = new Uint8Array(4);
    const view = createView(arr);
    const u = new Uint8Array(PRF.outputLen);
    // DK = T1 + T2 + ⋯ + Tdklen/hlen
    for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {
        // Ti = F(Password, Salt, c, i)
        const Ti = DK.subarray(pos, pos + PRF.outputLen);
        view.setInt32(0, ti, false);
        // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc
        // U1 = PRF(Password, Salt + INT_32_BE(i))
        (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);
        Ti.set(u.subarray(0, Ti.length));
        for (let ui = 1; ui < c; ui++) {
            // Uc = PRF(Password, Uc−1)
            PRF._cloneInto(prfW).update(u).digestInto(u);
            for (let i = 0; i < Ti.length; i++)
                Ti[i] ^= u[i];
        }
    }
    return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);
}
/**
 * PBKDF2-HMAC: RFC 2898 key derivation function. Async version.
 * @example
 * await pbkdf2Async(sha256, 'password', 'salt', { dkLen: 32, c: 500_000 });
 */
export async function pbkdf2Async(hash, password, salt, opts) {
    const { c, dkLen, asyncTick, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);
    let prfW; // Working copy
    const arr = new Uint8Array(4);
    const view = createView(arr);
    const u = new Uint8Array(PRF.outputLen);
    // DK = T1 + T2 + ⋯ + Tdklen/hlen
    for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {
        // Ti = F(Password, Salt, c, i)
        const Ti = DK.subarray(pos, pos + PRF.outputLen);
        view.setInt32(0, ti, false);
        // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc
        // U1 = PRF(Password, Salt + INT_32_BE(i))
        (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);
        Ti.set(u.subarray(0, Ti.length));
        await asyncLoop(c - 1, asyncTick, () => {
            // Uc = PRF(Password, Uc−1)
            PRF._cloneInto(prfW).update(u).digestInto(u);
            for (let i = 0; i < Ti.length; i++)
                Ti[i] ^= u[i];
        });
    }
    return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);
}
//# sourceMappingURL=pbkdf2.js.map/**
 * RFC 7914 Scrypt KDF. Can be used to create a key from password and salt.
 * @module
 */
import { pbkdf2 } from "./pbkdf2.js";
import { sha256 } from "./sha2.js";
// prettier-ignore
import { anumber, asyncLoop, checkOpts, clean, rotl, swap32IfBE, u32 } from "./utils.js";
// The main Scrypt loop: uses Salsa extensively.
// Six versions of the function were tried, this is the fastest one.
// prettier-ignore
function XorAndSalsa(prev, pi, input, ii, out, oi) {
    // Based on https://cr.yp.to/salsa20.html
    // Xor blocks
    let y00 = prev[pi++] ^ input[ii++], y01 = prev[pi++] ^ input[ii++];
    let y02 = prev[pi++] ^ input[ii++], y03 = prev[pi++] ^ input[ii++];
    let y04 = prev[pi++] ^ input[ii++], y05 = prev[pi++] ^ input[ii++];
    let y06 = prev[pi++] ^ input[ii++], y07 = prev[pi++] ^ input[ii++];
    let y08 = prev[pi++] ^ input[ii++], y09 = prev[pi++] ^ input[ii++];
    let y10 = prev[pi++] ^ input[ii++], y11 = prev[pi++] ^ input[ii++];
    let y12 = prev[pi++] ^ input[ii++], y13 = prev[pi++] ^ input[ii++];
    let y14 = prev[pi++] ^ input[ii++], y15 = prev[pi++] ^ input[ii++];
    // Save state to temporary variables (salsa)
    let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15;
    // Main loop (salsa)
    for (let i = 0; i < 8; i += 2) {
        x04 ^= rotl(x00 + x12 | 0, 7);
        x08 ^= rotl(x04 + x00 | 0, 9);
        x12 ^= rotl(x08 + x04 | 0, 13);
        x00 ^= rotl(x12 + x08 | 0, 18);
        x09 ^= rotl(x05 + x01 | 0, 7);
        x13 ^= rotl(x09 + x05 | 0, 9);
        x01 ^= rotl(x13 + x09 | 0, 13);
        x05 ^= rotl(x01 + x13 | 0, 18);
        x14 ^= rotl(x10 + x06 | 0, 7);
        x02 ^= rotl(x14 + x10 | 0, 9);
        x06 ^= rotl(x02 + x14 | 0, 13);
        x10 ^= rotl(x06 + x02 | 0, 18);
        x03 ^= rotl(x15 + x11 | 0, 7);
        x07 ^= rotl(x03 + x15 | 0, 9);
        x11 ^= rotl(x07 + x03 | 0, 13);
        x15 ^= rotl(x11 + x07 | 0, 18);
        x01 ^= rotl(x00 + x03 | 0, 7);
        x02 ^= rotl(x01 + x00 | 0, 9);
        x03 ^= rotl(x02 + x01 | 0, 13);
        x00 ^= rotl(x03 + x02 | 0, 18);
        x06 ^= rotl(x05 + x04 | 0, 7);
        x07 ^= rotl(x06 + x05 | 0, 9);
        x04 ^= rotl(x07 + x06 | 0, 13);
        x05 ^= rotl(x04 + x07 | 0, 18);
        x11 ^= rotl(x10 + x09 | 0, 7);
        x08 ^= rotl(x11 + x10 | 0, 9);
        x09 ^= rotl(x08 + x11 | 0, 13);
        x10 ^= rotl(x09 + x08 | 0, 18);
        x12 ^= rotl(x15 + x14 | 0, 7);
        x13 ^= rotl(x12 + x15 | 0, 9);
        x14 ^= rotl(x13 + x12 | 0, 13);
        x15 ^= rotl(x14 + x13 | 0, 18);
    }
    // Write output (salsa)
    out[oi++] = (y00 + x00) | 0;
    out[oi++] = (y01 + x01) | 0;
    out[oi++] = (y02 + x02) | 0;
    out[oi++] = (y03 + x03) | 0;
    out[oi++] = (y04 + x04) | 0;
    out[oi++] = (y05 + x05) | 0;
    out[oi++] = (y06 + x06) | 0;
    out[oi++] = (y07 + x07) | 0;
    out[oi++] = (y08 + x08) | 0;
    out[oi++] = (y09 + x09) | 0;
    out[oi++] = (y10 + x10) | 0;
    out[oi++] = (y11 + x11) | 0;
    out[oi++] = (y12 + x12) | 0;
    out[oi++] = (y13 + x13) | 0;
    out[oi++] = (y14 + x14) | 0;
    out[oi++] = (y15 + x15) | 0;
}
function BlockMix(input, ii, out, oi, r) {
    // The block B is r 128-byte chunks (which is equivalent of 2r 64-byte chunks)
    let head = oi + 0;
    let tail = oi + 16 * r;
    for (let i = 0; i < 16; i++)
        out[tail + i] = input[ii + (2 * r - 1) * 16 + i]; // X ← B[2r−1]
    for (let i = 0; i < r; i++, head += 16, ii += 16) {
        // We write odd & even Yi at same time. Even: 0bXXXXX0 Odd:  0bXXXXX1
        XorAndSalsa(out, tail, input, ii, out, head); // head[i] = Salsa(blockIn[2*i] ^ tail[i-1])
        if (i > 0)
            tail += 16; // First iteration overwrites tmp value in tail
        XorAndSalsa(out, head, input, (ii += 16), out, tail); // tail[i] = Salsa(blockIn[2*i+1] ^ head[i])
    }
}
// Common prologue and epilogue for sync/async functions
function scryptInit(password, salt, _opts) {
    // Maxmem - 1GB+1KB by default
    const opts = checkOpts({
        dkLen: 32,
        asyncTick: 10,
        maxmem: 1024 ** 3 + 1024,
    }, _opts);
    const { N, r, p, dkLen, asyncTick, maxmem, onProgress } = opts;
    anumber(N);
    anumber(r);
    anumber(p);
    anumber(dkLen);
    anumber(asyncTick);
    anumber(maxmem);
    if (onProgress !== undefined && typeof onProgress !== 'function')
        throw new Error('progressCb should be function');
    const blockSize = 128 * r;
    const blockSize32 = blockSize / 4;
    // Max N is 2^32 (Integrify is 32-bit). Real limit is 2^22: JS engines Uint8Array limit is 4GB in 2024.
    // Spec check `N >= 2^(blockSize / 8)` is not done for compat with popular libs,
    // which used incorrect r: 1, p: 8. Also, the check seems to be a spec error:
    // https://www.rfc-editor.org/errata_search.php?rfc=7914
    const pow32 = Math.pow(2, 32);
    if (N <= 1 || (N & (N - 1)) !== 0 || N > pow32) {
        throw new Error('Scrypt: N must be larger than 1, a power of 2, and less than 2^32');
    }
    if (p < 0 || p > ((pow32 - 1) * 32) / blockSize) {
        throw new Error('Scrypt: p must be a positive integer less than or equal to ((2^32 - 1) * 32) / (128 * r)');
    }
    if (dkLen < 0 || dkLen > (pow32 - 1) * 32) {
        throw new Error('Scrypt: dkLen should be positive integer less than or equal to (2^32 - 1) * 32');
    }
    const memUsed = blockSize * (N + p);
    if (memUsed > maxmem) {
        throw new Error('Scrypt: memused is bigger than maxMem. Expected 128 * r * (N + p) > maxmem of ' + maxmem);
    }
    // [B0...Bp−1] ← PBKDF2HMAC-SHA256(Passphrase, Salt, 1, blockSize*ParallelizationFactor)
    // Since it has only one iteration there is no reason to use async variant
    const B = pbkdf2(sha256, password, salt, { c: 1, dkLen: blockSize * p });
    const B32 = u32(B);
    // Re-used between parallel iterations. Array(iterations) of B
    const V = u32(new Uint8Array(blockSize * N));
    const tmp = u32(new Uint8Array(blockSize));
    let blockMixCb = () => { };
    if (onProgress) {
        const totalBlockMix = 2 * N * p;
        // Invoke callback if progress changes from 10.01 to 10.02
        // Allows to draw smooth progress bar on up to 8K screen
        const callbackPer = Math.max(Math.floor(totalBlockMix / 10000), 1);
        let blockMixCnt = 0;
        blockMixCb = () => {
            blockMixCnt++;
            if (onProgress && (!(blockMixCnt % callbackPer) || blockMixCnt === totalBlockMix))
                onProgress(blockMixCnt / totalBlockMix);
        };
    }
    return { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick };
}
function scryptOutput(password, dkLen, B, V, tmp) {
    const res = pbkdf2(sha256, password, B, { c: 1, dkLen });
    clean(B, V, tmp);
    return res;
}
/**
 * Scrypt KDF from RFC 7914.
 * @param password - pass
 * @param salt - salt
 * @param opts - parameters
 * - `N` is cpu/mem work factor (power of 2 e.g. 2**18)
 * - `r` is block size (8 is common), fine-tunes sequential memory read size and performance
 * - `p` is parallelization factor (1 is common)
 * - `dkLen` is output key length in bytes e.g. 32.
 * - `asyncTick` - (default: 10) max time in ms for which async function can block execution
 * - `maxmem` - (default: `1024 ** 3 + 1024` aka 1GB+1KB). A limit that the app could use for scrypt
 * - `onProgress` - callback function that would be executed for progress report
 * @returns Derived key
 * @example
 * scrypt('password', 'salt', { N: 2**18, r: 8, p: 1, dkLen: 32 });
 */
export function scrypt(password, salt, opts) {
    const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb } = scryptInit(password, salt, opts);
    swap32IfBE(B32);
    for (let pi = 0; pi < p; pi++) {
        const Pi = blockSize32 * pi;
        for (let i = 0; i < blockSize32; i++)
            V[i] = B32[Pi + i]; // V[0] = B[i]
        for (let i = 0, pos = 0; i < N - 1; i++) {
            BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]);
            blockMixCb();
        }
        BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element
        blockMixCb();
        for (let i = 0; i < N; i++) {
            // First u32 of the last 64-byte block (u32 is LE)
            const j = B32[Pi + blockSize32 - 16] % N; // j = Integrify(X) % iterations
            for (let k = 0; k < blockSize32; k++)
                tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; // tmp = B ^ V[j]
            BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j])
            blockMixCb();
        }
    }
    swap32IfBE(B32);
    return scryptOutput(password, dkLen, B, V, tmp);
}
/**
 * Scrypt KDF from RFC 7914. Async version.
 * @example
 * await scryptAsync('password', 'salt', { N: 2**18, r: 8, p: 1, dkLen: 32 });
 */
export async function scryptAsync(password, salt, opts) {
    const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick } = scryptInit(password, salt, opts);
    swap32IfBE(B32);
    for (let pi = 0; pi < p; pi++) {
        const Pi = blockSize32 * pi;
        for (let i = 0; i < blockSize32; i++)
            V[i] = B32[Pi + i]; // V[0] = B[i]
        let pos = 0;
        await asyncLoop(N - 1, asyncTick, () => {
            BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]);
            blockMixCb();
        });
        BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element
        blockMixCb();
        await asyncLoop(N, asyncTick, () => {
            // First u32 of the last 64-byte block (u32 is LE)
            const j = B32[Pi + blockSize32 - 16] % N; // j = Integrify(X) % iterations
            for (let k = 0; k < blockSize32; k++)
                tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; // tmp = B ^ V[j]
            BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j])
            blockMixCb();
        });
    }
    swap32IfBE(B32);
    return scryptOutput(password, dkLen, B, V, tmp);
}
//# sourceMappingURL=scrypt.js.map/**
 * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.
 * SHA256 is the fastest hash implementable in JS, even faster than Blake3.
 * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and
 * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).
 * @module
 */
import { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from "./_md.js";
import * as u64 from "./_u64.js";
import { clean, createHasher, rotr } from "./utils.js";
/**
 * Round constants:
 * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)
 */
// prettier-ignore
const SHA256_K = /* @__PURE__ */ Uint32Array.from([
    0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
    0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
    0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
    0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
    0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
    0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
    0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
    0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
]);
/** Reusable temporary buffer. "W" comes straight from spec. */
const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
export class SHA256 extends HashMD {
    constructor(outputLen = 32) {
        super(64, outputLen, 8, false);
        // We cannot use array here since array allows indexing by variable
        // which means optimizer/compiler cannot use registers.
        this.A = SHA256_IV[0] | 0;
        this.B = SHA256_IV[1] | 0;
        this.C = SHA256_IV[2] | 0;
        this.D = SHA256_IV[3] | 0;
        this.E = SHA256_IV[4] | 0;
        this.F = SHA256_IV[5] | 0;
        this.G = SHA256_IV[6] | 0;
        this.H = SHA256_IV[7] | 0;
    }
    get() {
        const { A, B, C, D, E, F, G, H } = this;
        return [A, B, C, D, E, F, G, H];
    }
    // prettier-ignore
    set(A, B, C, D, E, F, G, H) {
        this.A = A | 0;
        this.B = B | 0;
        this.C = C | 0;
        this.D = D | 0;
        this.E = E | 0;
        this.F = F | 0;
        this.G = G | 0;
        this.H = H | 0;
    }
    process(view, offset) {
        // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array
        for (let i = 0; i < 16; i++, offset += 4)
            SHA256_W[i] = view.getUint32(offset, false);
        for (let i = 16; i < 64; i++) {
            const W15 = SHA256_W[i - 15];
            const W2 = SHA256_W[i - 2];
            const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);
            const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);
            SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;
        }
        // Compression function main loop, 64 rounds
        let { A, B, C, D, E, F, G, H } = this;
        for (let i = 0; i < 64; i++) {
            const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
            const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
            const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
            const T2 = (sigma0 + Maj(A, B, C)) | 0;
            H = G;
            G = F;
            F = E;
            E = (D + T1) | 0;
            D = C;
            C = B;
            B = A;
            A = (T1 + T2) | 0;
        }
        // Add the compressed chunk to the current hash value
        A = (A + this.A) | 0;
        B = (B + this.B) | 0;
        C = (C + this.C) | 0;
        D = (D + this.D) | 0;
        E = (E + this.E) | 0;
        F = (F + this.F) | 0;
        G = (G + this.G) | 0;
        H = (H + this.H) | 0;
        this.set(A, B, C, D, E, F, G, H);
    }
    roundClean() {
        clean(SHA256_W);
    }
    destroy() {
        this.set(0, 0, 0, 0, 0, 0, 0, 0);
        clean(this.buffer);
    }
}
export class SHA224 extends SHA256 {
    constructor() {
        super(28);
        this.A = SHA224_IV[0] | 0;
        this.B = SHA224_IV[1] | 0;
        this.C = SHA224_IV[2] | 0;
        this.D = SHA224_IV[3] | 0;
        this.E = SHA224_IV[4] | 0;
        this.F = SHA224_IV[5] | 0;
        this.G = SHA224_IV[6] | 0;
        this.H = SHA224_IV[7] | 0;
    }
}
// SHA2-512 is slower than sha256 in js because u64 operations are slow.
// Round contants
// First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409
// prettier-ignore
const K512 = /* @__PURE__ */ (() => u64.split([
    '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',
    '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',
    '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',
    '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',
    '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',
    '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',
    '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',
    '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',
    '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',
    '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',
    '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',
    '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',
    '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',
    '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',
    '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',
    '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',
    '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',
    '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',
    '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',
    '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'
].map(n => BigInt(n))))();
const SHA512_Kh = /* @__PURE__ */ (() => K512[0])();
const SHA512_Kl = /* @__PURE__ */ (() => K512[1])();
// Reusable temporary buffers
const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
export class SHA512 extends HashMD {
    constructor(outputLen = 64) {
        super(128, outputLen, 16, false);
        // We cannot use array here since array allows indexing by variable
        // which means optimizer/compiler cannot use registers.
        // h -- high 32 bits, l -- low 32 bits
        this.Ah = SHA512_IV[0] | 0;
        this.Al = SHA512_IV[1] | 0;
        this.Bh = SHA512_IV[2] | 0;
        this.Bl = SHA512_IV[3] | 0;
        this.Ch = SHA512_IV[4] | 0;
        this.Cl = SHA512_IV[5] | 0;
        this.Dh = SHA512_IV[6] | 0;
        this.Dl = SHA512_IV[7] | 0;
        this.Eh = SHA512_IV[8] | 0;
        this.El = SHA512_IV[9] | 0;
        this.Fh = SHA512_IV[10] | 0;
        this.Fl = SHA512_IV[11] | 0;
        this.Gh = SHA512_IV[12] | 0;
        this.Gl = SHA512_IV[13] | 0;
        this.Hh = SHA512_IV[14] | 0;
        this.Hl = SHA512_IV[15] | 0;
    }
    // prettier-ignore
    get() {
        const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
        return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
    }
    // prettier-ignore
    set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
        this.Ah = Ah | 0;
        this.Al = Al | 0;
        this.Bh = Bh | 0;
        this.Bl = Bl | 0;
        this.Ch = Ch | 0;
        this.Cl = Cl | 0;
        this.Dh = Dh | 0;
        this.Dl = Dl | 0;
        this.Eh = Eh | 0;
        this.El = El | 0;
        this.Fh = Fh | 0;
        this.Fl = Fl | 0;
        this.Gh = Gh | 0;
        this.Gl = Gl | 0;
        this.Hh = Hh | 0;
        this.Hl = Hl | 0;
    }
    process(view, offset) {
        // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array
        for (let i = 0; i < 16; i++, offset += 4) {
            SHA512_W_H[i] = view.getUint32(offset);
            SHA512_W_L[i] = view.getUint32((offset += 4));
        }
        for (let i = 16; i < 80; i++) {
            // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)
            const W15h = SHA512_W_H[i - 15] | 0;
            const W15l = SHA512_W_L[i - 15] | 0;
            const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);
            const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);
            // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)
            const W2h = SHA512_W_H[i - 2] | 0;
            const W2l = SHA512_W_L[i - 2] | 0;
            const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);
            const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);
            // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];
            const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
            const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
            SHA512_W_H[i] = SUMh | 0;
            SHA512_W_L[i] = SUMl | 0;
        }
        let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
        // Compression function main loop, 80 rounds
        for (let i = 0; i < 80; i++) {
            // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)
            const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);
            const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);
            //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
            const CHIh = (Eh & Fh) ^ (~Eh & Gh);
            const CHIl = (El & Fl) ^ (~El & Gl);
            // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]
            // prettier-ignore
            const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
            const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
            const T1l = T1ll | 0;
            // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)
            const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);
            const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);
            const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);
            const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);
            Hh = Gh | 0;
            Hl = Gl | 0;
            Gh = Fh | 0;
            Gl = Fl | 0;
            Fh = Eh | 0;
            Fl = El | 0;
            ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
            Dh = Ch | 0;
            Dl = Cl | 0;
            Ch = Bh | 0;
            Cl = Bl | 0;
            Bh = Ah | 0;
            Bl = Al | 0;
            const All = u64.add3L(T1l, sigma0l, MAJl);
            Ah = u64.add3H(All, T1h, sigma0h, MAJh);
            Al = All | 0;
        }
        // Add the compressed chunk to the current hash value
        ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
        ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
        ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
        ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
        ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
        ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
        ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
        ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
        this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
    }
    roundClean() {
        clean(SHA512_W_H, SHA512_W_L);
    }
    destroy() {
        clean(this.buffer);
        this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
    }
}
export class SHA384 extends SHA512 {
    constructor() {
        super(48);
        this.Ah = SHA384_IV[0] | 0;
        this.Al = SHA384_IV[1] | 0;
        this.Bh = SHA384_IV[2] | 0;
        this.Bl = SHA384_IV[3] | 0;
        this.Ch = SHA384_IV[4] | 0;
        this.Cl = SHA384_IV[5] | 0;
        this.Dh = SHA384_IV[6] | 0;
        this.Dl = SHA384_IV[7] | 0;
        this.Eh = SHA384_IV[8] | 0;
        this.El = SHA384_IV[9] | 0;
        this.Fh = SHA384_IV[10] | 0;
        this.Fl = SHA384_IV[11] | 0;
        this.Gh = SHA384_IV[12] | 0;
        this.Gl = SHA384_IV[13] | 0;
        this.Hh = SHA384_IV[14] | 0;
        this.Hl = SHA384_IV[15] | 0;
    }
}
/**
 * Truncated SHA512/256 and SHA512/224.
 * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as "intermediary" IV of SHA512/t.
 * Then t hashes string to produce result IV.
 * See `test/misc/sha2-gen-iv.js`.
 */
/** SHA512/224 IV */
const T224_IV = /* @__PURE__ */ Uint32Array.from([
    0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,
    0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,
]);
/** SHA512/256 IV */
const T256_IV = /* @__PURE__ */ Uint32Array.from([
    0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,
    0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,
]);
export class SHA512_224 extends SHA512 {
    constructor() {
        super(28);
        this.Ah = T224_IV[0] | 0;
        this.Al = T224_IV[1] | 0;
        this.Bh = T224_IV[2] | 0;
        this.Bl = T224_IV[3] | 0;
        this.Ch = T224_IV[4] | 0;
        this.Cl = T224_IV[5] | 0;
        this.Dh = T224_IV[6] | 0;
        this.Dl = T224_IV[7] | 0;
        this.Eh = T224_IV[8] | 0;
        this.El = T224_IV[9] | 0;
        this.Fh = T224_IV[10] | 0;
        this.Fl = T224_IV[11] | 0;
        this.Gh = T224_IV[12] | 0;
        this.Gl = T224_IV[13] | 0;
        this.Hh = T224_IV[14] | 0;
        this.Hl = T224_IV[15] | 0;
    }
}
export class SHA512_256 extends SHA512 {
    constructor() {
        super(32);
        this.Ah = T256_IV[0] | 0;
        this.Al = T256_IV[1] | 0;
        this.Bh = T256_IV[2] | 0;
        this.Bl = T256_IV[3] | 0;
        this.Ch = T256_IV[4] | 0;
        this.Cl = T256_IV[5] | 0;
        this.Dh = T256_IV[6] | 0;
        this.Dl = T256_IV[7] | 0;
        this.Eh = T256_IV[8] | 0;
        this.El = T256_IV[9] | 0;
        this.Fh = T256_IV[10] | 0;
        this.Fl = T256_IV[11] | 0;
        this.Gh = T256_IV[12] | 0;
        this.Gl = T256_IV[13] | 0;
        this.Hh = T256_IV[14] | 0;
        this.Hl = T256_IV[15] | 0;
    }
}
/**
 * SHA2-256 hash function from RFC 4634.
 *
 * It is the fastest JS hash, even faster than Blake3.
 * To break sha256 using birthday attack, attackers need to try 2^128 hashes.
 * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
 */
export const sha256 = /* @__PURE__ */ createHasher(() => new SHA256());
/** SHA2-224 hash function from RFC 4634 */
export const sha224 = /* @__PURE__ */ createHasher(() => new SHA224());
/** SHA2-512 hash function from RFC 4634. */
export const sha512 = /* @__PURE__ */ createHasher(() => new SHA512());
/** SHA2-384 hash function from RFC 4634. */
export const sha384 = /* @__PURE__ */ createHasher(() => new SHA384());
/**
 * SHA2-512/256 "truncated" hash function, with improved resistance to length extension attacks.
 * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).
 */
export const sha512_256 = /* @__PURE__ */ createHasher(() => new SHA512_256());
/**
 * SHA2-512/224 "truncated" hash function, with improved resistance to length extension attacks.
 * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).
 */
export const sha512_224 = /* @__PURE__ */ createHasher(() => new SHA512_224());
//# sourceMappingURL=sha2.js.map/**
 * Utilities for hex, bytes, CSPRNG.
 * @module
 */
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
// node.js versions earlier than v19 don't declare it in global scope.
// For node.js, package.json#exports field mapping rewrites import
// from `crypto` to `cryptoNode`, which imports native module.
// Makes the utils un-importable in browsers without a bundler.
// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.
import { crypto } from '@noble/hashes/crypto';
/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */
export function isBytes(a) {
    return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
}
/** Asserts something is positive integer. */
export function anumber(n) {
    if (!Number.isSafeInteger(n) || n < 0)
        throw new Error('positive integer expected, got ' + n);
}
/** Asserts something is Uint8Array. */
export function abytes(b, ...lengths) {
    if (!isBytes(b))
        throw new Error('Uint8Array expected');
    if (lengths.length > 0 && !lengths.includes(b.length))
        throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);
}
/** Asserts something is hash */
export function ahash(h) {
    if (typeof h !== 'function' || typeof h.create !== 'function')
        throw new Error('Hash should be wrapped by utils.createHasher');
    anumber(h.outputLen);
    anumber(h.blockLen);
}
/** Asserts a hash instance has not been destroyed / finished */
export function aexists(instance, checkFinished = true) {
    if (instance.destroyed)
        throw new Error('Hash instance has been destroyed');
    if (checkFinished && instance.finished)
        throw new Error('Hash#digest() has already been called');
}
/** Asserts output is properly-sized byte array */
export function aoutput(out, instance) {
    abytes(out);
    const min = instance.outputLen;
    if (out.length < min) {
        throw new Error('digestInto() expects output buffer of length at least ' + min);
    }
}
/** Cast u8 / u16 / u32 to u8. */
export function u8(arr) {
    return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
}
/** Cast u8 / u16 / u32 to u32. */
export function u32(arr) {
    return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
}
/** Zeroize a byte array. Warning: JS provides no guarantees. */
export function clean(...arrays) {
    for (let i = 0; i < arrays.length; i++) {
        arrays[i].fill(0);
    }
}
/** Create DataView of an array for easy byte-level manipulation. */
export function createView(arr) {
    return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
}
/** The rotate right (circular right shift) operation for uint32 */
export function rotr(word, shift) {
    return (word << (32 - shift)) | (word >>> shift);
}
/** The rotate left (circular left shift) operation for uint32 */
export function rotl(word, shift) {
    return (word << shift) | ((word >>> (32 - shift)) >>> 0);
}
/** Is current platform little-endian? Most are. Big-Endian platform: IBM */
export const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();
/** The byte swap operation for uint32 */
export function byteSwap(word) {
    return (((word << 24) & 0xff000000) |
        ((word << 8) & 0xff0000) |
        ((word >>> 8) & 0xff00) |
        ((word >>> 24) & 0xff));
}
/** Conditionally byte swap if on a big-endian platform */
export const swap8IfBE = isLE
    ? (n) => n
    : (n) => byteSwap(n);
/** @deprecated */
export const byteSwapIfBE = swap8IfBE;
/** In place byte swap for Uint32Array */
export function byteSwap32(arr) {
    for (let i = 0; i < arr.length; i++) {
        arr[i] = byteSwap(arr[i]);
    }
    return arr;
}
export const swap32IfBE = isLE
    ? (u) => u
    : byteSwap32;
// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex
const hasHexBuiltin = /* @__PURE__ */ (() => 
// @ts-ignore
typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();
// Array where index 0xf0 (240) is mapped to string 'f0'
const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
/**
 * Convert byte array to hex string. Uses built-in function, when available.
 * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
 */
export function bytesToHex(bytes) {
    abytes(bytes);
    // @ts-ignore
    if (hasHexBuiltin)
        return bytes.toHex();
    // pre-caching improves the speed 6x
    let hex = '';
    for (let i = 0; i < bytes.length; i++) {
        hex += hexes[bytes[i]];
    }
    return hex;
}
// We use optimized technique to convert hex string to byte array
const asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
function asciiToBase16(ch) {
    if (ch >= asciis._0 && ch <= asciis._9)
        return ch - asciis._0; // '2' => 50-48
    if (ch >= asciis.A && ch <= asciis.F)
        return ch - (asciis.A - 10); // 'B' => 66-(65-10)
    if (ch >= asciis.a && ch <= asciis.f)
        return ch - (asciis.a - 10); // 'b' => 98-(97-10)
    return;
}
/**
 * Convert hex string to byte array. Uses built-in function, when available.
 * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
 */
export function hexToBytes(hex) {
    if (typeof hex !== 'string')
        throw new Error('hex string expected, got ' + typeof hex);
    // @ts-ignore
    if (hasHexBuiltin)
        return Uint8Array.fromHex(hex);
    const hl = hex.length;
    const al = hl / 2;
    if (hl % 2)
        throw new Error('hex string expected, got unpadded hex of length ' + hl);
    const array = new Uint8Array(al);
    for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
        const n1 = asciiToBase16(hex.charCodeAt(hi));
        const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
        if (n1 === undefined || n2 === undefined) {
            const char = hex[hi] + hex[hi + 1];
            throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
        }
        array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163
    }
    return array;
}
/**
 * There is no setImmediate in browser and setTimeout is slow.
 * Call of async fn will return Promise, which will be fullfiled only on
 * next scheduler queue processing step and this is exactly what we need.
 */
export const nextTick = async () => { };
/** Returns control to thread each 'tick' ms to avoid blocking. */
export async function asyncLoop(iters, tick, cb) {
    let ts = Date.now();
    for (let i = 0; i < iters; i++) {
        cb(i);
        // Date.now() is not monotonic, so in case if clock goes backwards we return return control too
        const diff = Date.now() - ts;
        if (diff >= 0 && diff < tick)
            continue;
        await nextTick();
        ts += diff;
    }
}
/**
 * Converts string to bytes using UTF8 encoding.
 * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])
 */
export function utf8ToBytes(str) {
    if (typeof str !== 'string')
        throw new Error('string expected');
    return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
}
/**
 * Converts bytes to string using UTF8 encoding.
 * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'
 */
export function bytesToUtf8(bytes) {
    return new TextDecoder().decode(bytes);
}
/**
 * Normalizes (non-hex) string or Uint8Array to Uint8Array.
 * Warning: when Uint8Array is passed, it would NOT get copied.
 * Keep in mind for future mutable operations.
 */
export function toBytes(data) {
    if (typeof data === 'string')
        data = utf8ToBytes(data);
    abytes(data);
    return data;
}
/**
 * Helper for KDFs: consumes uint8array or string.
 * When string is passed, does utf8 decoding, using TextDecoder.
 */
export function kdfInputToBytes(data) {
    if (typeof data === 'string')
        data = utf8ToBytes(data);
    abytes(data);
    return data;
}
/** Copies several Uint8Arrays into one. */
export function concatBytes(...arrays) {
    let sum = 0;
    for (let i = 0; i < arrays.length; i++) {
        const a = arrays[i];
        abytes(a);
        sum += a.length;
    }
    const res = new Uint8Array(sum);
    for (let i = 0, pad = 0; i < arrays.length; i++) {
        const a = arrays[i];
        res.set(a, pad);
        pad += a.length;
    }
    return res;
}
export function checkOpts(defaults, opts) {
    if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')
        throw new Error('options should be object or undefined');
    const merged = Object.assign(defaults, opts);
    return merged;
}
/** For runtime check if class implements interface */
export class Hash {
}
/** Wraps hash function, creating an interface on top of it */
export function createHasher(hashCons) {
    const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
    const tmp = hashCons();
    hashC.outputLen = tmp.outputLen;
    hashC.blockLen = tmp.blockLen;
    hashC.create = () => hashCons();
    return hashC;
}
export function createOptHasher(hashCons) {
    const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();
    const tmp = hashCons({});
    hashC.outputLen = tmp.outputLen;
    hashC.blockLen = tmp.blockLen;
    hashC.create = (opts) => hashCons(opts);
    return hashC;
}
export function createXOFer(hashCons) {
    const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();
    const tmp = hashCons({});
    hashC.outputLen = tmp.outputLen;
    hashC.blockLen = tmp.blockLen;
    hashC.create = (opts) => hashCons(opts);
    return hashC;
}
export const wrapConstructor = createHasher;
export const wrapConstructorWithOpts = createOptHasher;
export const wrapXOFConstructorWithOpts = createXOFer;
/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */
export function randomBytes(bytesLength = 32) {
    if (crypto && typeof crypto.getRandomValues === 'function') {
        return crypto.getRandomValues(new Uint8Array(bytesLength));
    }
    // Legacy Node.js compatibility
    if (crypto && typeof crypto.randomBytes === 'function') {
        return Uint8Array.from(crypto.randomBytes(bytesLength));
    }
    throw new Error('crypto.getRandomValues must be defined');
}
//# sourceMappingURL=utils.js.map/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */
function isBytes(a) {
    return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
}
/** Asserts something is Uint8Array. */
function abytes(b, ...lengths) {
    if (!isBytes(b))
        throw new Error('Uint8Array expected');
    if (lengths.length > 0 && !lengths.includes(b.length))
        throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);
}
function isArrayOf(isString, arr) {
    if (!Array.isArray(arr))
        return false;
    if (arr.length === 0)
        return true;
    if (isString) {
        return arr.every((item) => typeof item === 'string');
    }
    else {
        return arr.every((item) => Number.isSafeInteger(item));
    }
}
// no abytes: seems to have 10% slowdown. Why?!
function afn(input) {
    if (typeof input !== 'function')
        throw new Error('function expected');
    return true;
}
function astr(label, input) {
    if (typeof input !== 'string')
        throw new Error(`${label}: string expected`);
    return true;
}
function anumber(n) {
    if (!Number.isSafeInteger(n))
        throw new Error(`invalid integer: ${n}`);
}
function aArr(input) {
    if (!Array.isArray(input))
        throw new Error('array expected');
}
function astrArr(label, input) {
    if (!isArrayOf(true, input))
        throw new Error(`${label}: array of strings expected`);
}
function anumArr(label, input) {
    if (!isArrayOf(false, input))
        throw new Error(`${label}: array of numbers expected`);
}
/**
 * @__NO_SIDE_EFFECTS__
 */
function chain(...args) {
    const id = (a) => a;
    // Wrap call in closure so JIT can inline calls
    const wrap = (a, b) => (c) => a(b(c));
    // Construct chain of args[-1].encode(args[-2].encode([...]))
    const encode = args.map((x) => x.encode).reduceRight(wrap, id);
    // Construct chain of args[0].decode(args[1].decode(...))
    const decode = args.map((x) => x.decode).reduce(wrap, id);
    return { encode, decode };
}
/**
 * Encodes integer radix representation to array of strings using alphabet and back.
 * Could also be array of strings.
 * @__NO_SIDE_EFFECTS__
 */
function alphabet(letters) {
    // mapping 1 to "b"
    const lettersA = typeof letters === 'string' ? letters.split('') : letters;
    const len = lettersA.length;
    astrArr('alphabet', lettersA);
    // mapping "b" to 1
    const indexes = new Map(lettersA.map((l, i) => [l, i]));
    return {
        encode: (digits) => {
            aArr(digits);
            return digits.map((i) => {
                if (!Number.isSafeInteger(i) || i < 0 || i >= len)
                    throw new Error(`alphabet.encode: digit index outside alphabet "${i}". Allowed: ${letters}`);
                return lettersA[i];
            });
        },
        decode: (input) => {
            aArr(input);
            return input.map((letter) => {
                astr('alphabet.decode', letter);
                const i = indexes.get(letter);
                if (i === undefined)
                    throw new Error(`Unknown letter: "${letter}". Allowed: ${letters}`);
                return i;
            });
        },
    };
}
/**
 * @__NO_SIDE_EFFECTS__
 */
function join(separator = '') {
    astr('join', separator);
    return {
        encode: (from) => {
            astrArr('join.decode', from);
            return from.join(separator);
        },
        decode: (to) => {
            astr('join.decode', to);
            return to.split(separator);
        },
    };
}
/**
 * Pad strings array so it has integer number of bits
 * @__NO_SIDE_EFFECTS__
 */
function padding(bits, chr = '=') {
    anumber(bits);
    astr('padding', chr);
    return {
        encode(data) {
            astrArr('padding.encode', data);
            while ((data.length * bits) % 8)
                data.push(chr);
            return data;
        },
        decode(input) {
            astrArr('padding.decode', input);
            let end = input.length;
            if ((end * bits) % 8)
                throw new Error('padding: invalid, string should have whole number of bytes');
            for (; end > 0 && input[end - 1] === chr; end--) {
                const last = end - 1;
                const byte = last * bits;
                if (byte % 8 === 0)
                    throw new Error('padding: invalid, string has too much padding');
            }
            return input.slice(0, end);
        },
    };
}
/**
 * @__NO_SIDE_EFFECTS__
 */
function normalize(fn) {
    afn(fn);
    return { encode: (from) => from, decode: (to) => fn(to) };
}
/**
 * Slow: O(n^2) time complexity
 */
function convertRadix(data, from, to) {
    // base 1 is impossible
    if (from < 2)
        throw new Error(`convertRadix: invalid from=${from}, base cannot be less than 2`);
    if (to < 2)
        throw new Error(`convertRadix: invalid to=${to}, base cannot be less than 2`);
    aArr(data);
    if (!data.length)
        return [];
    let pos = 0;
    const res = [];
    const digits = Array.from(data, (d) => {
        anumber(d);
        if (d < 0 || d >= from)
            throw new Error(`invalid integer: ${d}`);
        return d;
    });
    const dlen = digits.length;
    while (true) {
        let carry = 0;
        let done = true;
        for (let i = pos; i < dlen; i++) {
            const digit = digits[i];
            const fromCarry = from * carry;
            const digitBase = fromCarry + digit;
            if (!Number.isSafeInteger(digitBase) ||
                fromCarry / from !== carry ||
                digitBase - digit !== fromCarry) {
                throw new Error('convertRadix: carry overflow');
            }
            const div = digitBase / to;
            carry = digitBase % to;
            const rounded = Math.floor(div);
            digits[i] = rounded;
            if (!Number.isSafeInteger(rounded) || rounded * to + carry !== digitBase)
                throw new Error('convertRadix: carry overflow');
            if (!done)
                continue;
            else if (!rounded)
                pos = i;
            else
                done = false;
        }
        res.push(carry);
        if (done)
            break;
    }
    for (let i = 0; i < data.length - 1 && data[i] === 0; i++)
        res.push(0);
    return res.reverse();
}
const gcd = (a, b) => (b === 0 ? a : gcd(b, a % b));
const radix2carry = /* @__NO_SIDE_EFFECTS__ */ (from, to) => from + (to - gcd(from, to));
const powers = /* @__PURE__ */ (() => {
    let res = [];
    for (let i = 0; i < 40; i++)
        res.push(2 ** i);
    return res;
})();
/**
 * Implemented with numbers, because BigInt is 5x slower
 */
function convertRadix2(data, from, to, padding) {
    aArr(data);
    if (from <= 0 || from > 32)
        throw new Error(`convertRadix2: wrong from=${from}`);
    if (to <= 0 || to > 32)
        throw new Error(`convertRadix2: wrong to=${to}`);
    if (radix2carry(from, to) > 32) {
        throw new Error(`convertRadix2: carry overflow from=${from} to=${to} carryBits=${radix2carry(from, to)}`);
    }
    let carry = 0;
    let pos = 0; // bitwise position in current element
    const max = powers[from];
    const mask = powers[to] - 1;
    const res = [];
    for (const n of data) {
        anumber(n);
        if (n >= max)
            throw new Error(`convertRadix2: invalid data word=${n} from=${from}`);
        carry = (carry << from) | n;
        if (pos + from > 32)
            throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from}`);
        pos += from;
        for (; pos >= to; pos -= to)
            res.push(((carry >> (pos - to)) & mask) >>> 0);
        const pow = powers[pos];
        if (pow === undefined)
            throw new Error('invalid carry');
        carry &= pow - 1; // clean carry, otherwise it will cause overflow
    }
    carry = (carry << (to - pos)) & mask;
    if (!padding && pos >= from)
        throw new Error('Excess padding');
    if (!padding && carry > 0)
        throw new Error(`Non-zero padding: ${carry}`);
    if (padding && pos > 0)
        res.push(carry >>> 0);
    return res;
}
/**
 * @__NO_SIDE_EFFECTS__
 */
function radix(num) {
    anumber(num);
    const _256 = 2 ** 8;
    return {
        encode: (bytes) => {
            if (!isBytes(bytes))
                throw new Error('radix.encode input should be Uint8Array');
            return convertRadix(Array.from(bytes), _256, num);
        },
        decode: (digits) => {
            anumArr('radix.decode', digits);
            return Uint8Array.from(convertRadix(digits, num, _256));
        },
    };
}
/**
 * If both bases are power of same number (like `2**8 <-> 2**64`),
 * there is a linear algorithm. For now we have implementation for power-of-two bases only.
 * @__NO_SIDE_EFFECTS__
 */
function radix2(bits, revPadding = false) {
    anumber(bits);
    if (bits <= 0 || bits > 32)
        throw new Error('radix2: bits should be in (0..32]');
    if (radix2carry(8, bits) > 32 || radix2carry(bits, 8) > 32)
        throw new Error('radix2: carry overflow');
    return {
        encode: (bytes) => {
            if (!isBytes(bytes))
                throw new Error('radix2.encode input should be Uint8Array');
            return convertRadix2(Array.from(bytes), 8, bits, !revPadding);
        },
        decode: (digits) => {
            anumArr('radix2.decode', digits);
            return Uint8Array.from(convertRadix2(digits, bits, 8, revPadding));
        },
    };
}
function unsafeWrapper(fn) {
    afn(fn);
    return function (...args) {
        try {
            return fn.apply(null, args);
        }
        catch (e) { }
    };
}
function checksum(len, fn) {
    anumber(len);
    afn(fn);
    return {
        encode(data) {
            if (!isBytes(data))
                throw new Error('checksum.encode: input should be Uint8Array');
            const sum = fn(data).slice(0, len);
            const res = new Uint8Array(data.length + len);
            res.set(data);
            res.set(sum, data.length);
            return res;
        },
        decode(data) {
            if (!isBytes(data))
                throw new Error('checksum.decode: input should be Uint8Array');
            const payload = data.slice(0, -len);
            const oldChecksum = data.slice(-len);
            const newChecksum = fn(payload).slice(0, len);
            for (let i = 0; i < len; i++)
                if (newChecksum[i] !== oldChecksum[i])
                    throw new Error('Invalid checksum');
            return payload;
        },
    };
}
// prettier-ignore
export const utils = {
    alphabet, chain, checksum, convertRadix, convertRadix2, radix, radix2, join, padding,
};
// RFC 4648 aka RFC 3548
// ---------------------
/**
 * base16 encoding from RFC 4648.
 * @example
 * ```js
 * base16.encode(Uint8Array.from([0x12, 0xab]));
 * // => '12AB'
 * ```
 */
export const base16 = chain(radix2(4), alphabet('0123456789ABCDEF'), join(''));
/**
 * base32 encoding from RFC 4648. Has padding.
 * Use `base32nopad` for unpadded version.
 * Also check out `base32hex`, `base32hexnopad`, `base32crockford`.
 * @example
 * ```js
 * base32.encode(Uint8Array.from([0x12, 0xab]));
 * // => 'CKVQ===='
 * base32.decode('CKVQ====');
 * // => Uint8Array.from([0x12, 0xab])
 * ```
 */
export const base32 = chain(radix2(5), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'), padding(5), join(''));
/**
 * base32 encoding from RFC 4648. No padding.
 * Use `base32` for padded version.
 * Also check out `base32hex`, `base32hexnopad`, `base32crockford`.
 * @example
 * ```js
 * base32nopad.encode(Uint8Array.from([0x12, 0xab]));
 * // => 'CKVQ'
 * base32nopad.decode('CKVQ');
 * // => Uint8Array.from([0x12, 0xab])
 * ```
 */
export const base32nopad = chain(radix2(5), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'), join(''));
/**
 * base32 encoding from RFC 4648. Padded. Compared to ordinary `base32`, slightly different alphabet.
 * Use `base32hexnopad` for unpadded version.
 * @example
 * ```js
 * base32hex.encode(Uint8Array.from([0x12, 0xab]));
 * // => '2ALG===='
 * base32hex.decode('2ALG====');
 * // => Uint8Array.from([0x12, 0xab])
 * ```
 */
export const base32hex = chain(radix2(5), alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'), padding(5), join(''));
/**
 * base32 encoding from RFC 4648. No padding. Compared to ordinary `base32`, slightly different alphabet.
 * Use `base32hex` for padded version.
 * @example
 * ```js
 * base32hexnopad.encode(Uint8Array.from([0x12, 0xab]));
 * // => '2ALG'
 * base32hexnopad.decode('2ALG');
 * // => Uint8Array.from([0x12, 0xab])
 * ```
 */
export const base32hexnopad = chain(radix2(5), alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'), join(''));
/**
 * base32 encoding from RFC 4648. Doug Crockford's version.
 * https://www.crockford.com/base32.html
 * @example
 * ```js
 * base32crockford.encode(Uint8Array.from([0x12, 0xab]));
 * // => '2ANG'
 * base32crockford.decode('2ANG');
 * // => Uint8Array.from([0x12, 0xab])
 * ```
 */
export const base32crockford = chain(radix2(5), alphabet('0123456789ABCDEFGHJKMNPQRSTVWXYZ'), join(''), normalize((s) => s.toUpperCase().replace(/O/g, '0').replace(/[IL]/g, '1')));
// Built-in base64 conversion https://caniuse.com/mdn-javascript_builtins_uint8array_frombase64
// prettier-ignore
const hasBase64Builtin = /* @__PURE__ */ (() => typeof Uint8Array.from([]).toBase64 === 'function' &&
    typeof Uint8Array.fromBase64 === 'function')();
const decodeBase64Builtin = (s, isUrl) => {
    astr('base64', s);
    const re = isUrl ? /^[A-Za-z0-9=_-]+$/ : /^[A-Za-z0-9=+/]+$/;
    const alphabet = isUrl ? 'base64url' : 'base64';
    if (s.length > 0 && !re.test(s))
        throw new Error('invalid base64');
    return Uint8Array.fromBase64(s, { alphabet, lastChunkHandling: 'strict' });
};
/**
 * base64 from RFC 4648. Padded.
 * Use `base64nopad` for unpadded version.
 * Also check out `base64url`, `base64urlnopad`.
 * Falls back to built-in function, when available.
 * @example
 * ```js
 * base64.encode(Uint8Array.from([0x12, 0xab]));
 * // => 'Eqs='
 * base64.decode('Eqs=');
 * // => Uint8Array.from([0x12, 0xab])
 * ```
 */
// prettier-ignore
export const base64 = hasBase64Builtin ? {
    encode(b) { abytes(b); return b.toBase64(); },
    decode(s) { return decodeBase64Builtin(s, false); },
} : chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'), padding(6), join(''));
/**
 * base64 from RFC 4648. No padding.
 * Use `base64` for padded version.
 * @example
 * ```js
 * base64nopad.encode(Uint8Array.from([0x12, 0xab]));
 * // => 'Eqs'
 * base64nopad.decode('Eqs');
 * // => Uint8Array.from([0x12, 0xab])
 * ```
 */
export const base64nopad = chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'), join(''));
/**
 * base64 from RFC 4648, using URL-safe alphabet. Padded.
 * Use `base64urlnopad` for unpadded version.
 * Falls back to built-in function, when available.
 * @example
 * ```js
 * base64url.encode(Uint8Array.from([0x12, 0xab]));
 * // => 'Eqs='
 * base64url.decode('Eqs=');
 * // => Uint8Array.from([0x12, 0xab])
 * ```
 */
// prettier-ignore
export const base64url = hasBase64Builtin ? {
    encode(b) { abytes(b); return b.toBase64({ alphabet: 'base64url' }); },
    decode(s) { return decodeBase64Builtin(s, true); },
} : chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'), padding(6), join(''));
/**
 * base64 from RFC 4648, using URL-safe alphabet. No padding.
 * Use `base64url` for padded version.
 * @example
 * ```js
 * base64urlnopad.encode(Uint8Array.from([0x12, 0xab]));
 * // => 'Eqs'
 * base64urlnopad.decode('Eqs');
 * // => Uint8Array.from([0x12, 0xab])
 * ```
 */
export const base64urlnopad = chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'), join(''));
// base58 code
// -----------
const genBase58 = /* @__NO_SIDE_EFFECTS__ */ (abc) => chain(radix(58), alphabet(abc), join(''));
/**
 * base58: base64 without ambigous characters +, /, 0, O, I, l.
 * Quadratic (O(n^2)) - so, can't be used on large inputs.
 * @example
 * ```js
 * base58.decode('01abcdef');
 * // => '3UhJW'
 * ```
 */
export const base58 = genBase58('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz');
/**
 * base58: flickr version. Check out `base58`.
 */
export const base58flickr = genBase58('123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ');
/**
 * base58: XRP version. Check out `base58`.
 */
export const base58xrp = genBase58('rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz');
// Data len (index) -> encoded block len
const XMR_BLOCK_LEN = [0, 2, 3, 5, 6, 7, 9, 10, 11];
/**
 * base58: XMR version. Check out `base58`.
 * Done in 8-byte blocks (which equals 11 chars in decoding). Last (non-full) block padded with '1' to size in XMR_BLOCK_LEN.
 * Block encoding significantly reduces quadratic complexity of base58.
 */
export const base58xmr = {
    encode(data) {
        let res = '';
        for (let i = 0; i < data.length; i += 8) {
            const block = data.subarray(i, i + 8);
            res += base58.encode(block).padStart(XMR_BLOCK_LEN[block.length], '1');
        }
        return res;
    },
    decode(str) {
        let res = [];
        for (let i = 0; i < str.length; i += 11) {
            const slice = str.slice(i, i + 11);
            const blockLen = XMR_BLOCK_LEN.indexOf(slice.length);
            const block = base58.decode(slice);
            for (let j = 0; j < block.length - blockLen; j++) {
                if (block[j] !== 0)
                    throw new Error('base58xmr: wrong padding');
            }
            res = res.concat(Array.from(block.slice(block.length - blockLen)));
        }
        return Uint8Array.from(res);
    },
};
/**
 * Method, which creates base58check encoder.
 * Requires function, calculating sha256.
 */
export const createBase58check = (sha256) => chain(checksum(4, (data) => sha256(sha256(data))), base58);
/**
 * Use `createBase58check` instead.
 * @deprecated
 */
export const base58check = createBase58check;
const BECH_ALPHABET = chain(alphabet('qpzry9x8gf2tvdw0s3jn54khce6mua7l'), join(''));
const POLYMOD_GENERATORS = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];
function bech32Polymod(pre) {
    const b = pre >> 25;
    let chk = (pre & 0x1ffffff) << 5;
    for (let i = 0; i < POLYMOD_GENERATORS.length; i++) {
        if (((b >> i) & 1) === 1)
            chk ^= POLYMOD_GENERATORS[i];
    }
    return chk;
}
function bechChecksum(prefix, words, encodingConst = 1) {
    const len = prefix.length;
    let chk = 1;
    for (let i = 0; i < len; i++) {
        const c = prefix.charCodeAt(i);
        if (c < 33 || c > 126)
            throw new Error(`Invalid prefix (${prefix})`);
        chk = bech32Polymod(chk) ^ (c >> 5);
    }
    chk = bech32Polymod(chk);
    for (let i = 0; i < len; i++)
        chk = bech32Polymod(chk) ^ (prefix.charCodeAt(i) & 0x1f);
    for (let v of words)
        chk = bech32Polymod(chk) ^ v;
    for (let i = 0; i < 6; i++)
        chk = bech32Polymod(chk);
    chk ^= encodingConst;
    return BECH_ALPHABET.encode(convertRadix2([chk % powers[30]], 30, 5, false));
}
/**
 * @__NO_SIDE_EFFECTS__
 */
function genBech32(encoding) {
    const ENCODING_CONST = encoding === 'bech32' ? 1 : 0x2bc830a3;
    const _words = radix2(5);
    const fromWords = _words.decode;
    const toWords = _words.encode;
    const fromWordsUnsafe = unsafeWrapper(fromWords);
    function encode(prefix, words, limit = 90) {
        astr('bech32.encode prefix', prefix);
        if (isBytes(words))
            words = Array.from(words);
        anumArr('bech32.encode', words);
        const plen = prefix.length;
        if (plen === 0)
            throw new TypeError(`Invalid prefix length ${plen}`);
        const actualLength = plen + 7 + words.length;
        if (limit !== false && actualLength > limit)
            throw new TypeError(`Length ${actualLength} exceeds limit ${limit}`);
        const lowered = prefix.toLowerCase();
        const sum = bechChecksum(lowered, words, ENCODING_CONST);
        return `${lowered}1${BECH_ALPHABET.encode(words)}${sum}`;
    }
    function decode(str, limit = 90) {
        astr('bech32.decode input', str);
        const slen = str.length;
        if (slen < 8 || (limit !== false && slen > limit))
            throw new TypeError(`invalid string length: ${slen} (${str}). Expected (8..${limit})`);
        // don't allow mixed case
        const lowered = str.toLowerCase();
        if (str !== lowered && str !== str.toUpperCase())
            throw new Error(`String must be lowercase or uppercase`);
        const sepIndex = lowered.lastIndexOf('1');
        if (sepIndex === 0 || sepIndex === -1)
            throw new Error(`Letter "1" must be present between prefix and data only`);
        const prefix = lowered.slice(0, sepIndex);
        const data = lowered.slice(sepIndex + 1);
        if (data.length < 6)
            throw new Error('Data must be at least 6 characters long');
        const words = BECH_ALPHABET.decode(data).slice(0, -6);
        const sum = bechChecksum(prefix, words, ENCODING_CONST);
        if (!data.endsWith(sum))
            throw new Error(`Invalid checksum in ${str}: expected "${sum}"`);
        return { prefix, words };
    }
    const decodeUnsafe = unsafeWrapper(decode);
    function decodeToBytes(str) {
        const { prefix, words } = decode(str, false);
        return { prefix, words, bytes: fromWords(words) };
    }
    function encodeFromBytes(prefix, bytes) {
        return encode(prefix, toWords(bytes));
    }
    return {
        encode,
        decode,
        encodeFromBytes,
        decodeToBytes,
        decodeUnsafe,
        fromWords,
        fromWordsUnsafe,
        toWords,
    };
}
/**
 * bech32 from BIP 173. Operates on words.
 * For high-level, check out scure-btc-signer:
 * https://github.com/paulmillr/scure-btc-signer.
 */
export const bech32 = genBech32('bech32');
/**
 * bech32m from BIP 350. Operates on words.
 * It was to mitigate `bech32` weaknesses.
 * For high-level, check out scure-btc-signer:
 * https://github.com/paulmillr/scure-btc-signer.
 */
export const bech32m = genBech32('bech32m');
/**
 * UTF-8-to-byte decoder. Uses built-in TextDecoder / TextEncoder.
 * @example
 * ```js
 * const b = utf8.decode("hey"); // => new Uint8Array([ 104, 101, 121 ])
 * const str = utf8.encode(b); // "hey"
 * ```
 */
export const utf8 = {
    encode: (data) => new TextDecoder().decode(data),
    decode: (str) => new TextEncoder().encode(str),
};
// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex
// prettier-ignore
const hasHexBuiltin = /* @__PURE__ */ (() => typeof Uint8Array.from([]).toHex === 'function' &&
    typeof Uint8Array.fromHex === 'function')();
// prettier-ignore
const hexBuiltin = {
    encode(data) { abytes(data); return data.toHex(); },
    decode(s) { astr('hex', s); return Uint8Array.fromHex(s); },
};
/**
 * hex string decoder. Uses built-in function, when available.
 * @example
 * ```js
 * const b = hex.decode("0102ff"); // => new Uint8Array([ 1, 2, 255 ])
 * const str = hex.encode(b); // "0102ff"
 * ```
 */
export const hex = hasHexBuiltin
    ? hexBuiltin
    : chain(radix2(4), alphabet('0123456789abcdef'), join(''), normalize((s) => {
        if (typeof s !== 'string' || s.length % 2 !== 0)
            throw new TypeError(`hex.decode: expected string, got ${typeof s} with length ${s.length}`);
        return s.toLowerCase();
    }));
// prettier-ignore
const CODERS = {
    utf8, hex, base16, base32, base64, base64url, base58, base58xmr
};
const coderTypeError = 'Invalid encoding type. Available types: utf8, hex, base16, base32, base64, base64url, base58, base58xmr';
/** @deprecated */
export const bytesToString = (type, bytes) => {
    if (typeof type !== 'string' || !CODERS.hasOwnProperty(type))
        throw new TypeError(coderTypeError);
    if (!isBytes(bytes))
        throw new TypeError('bytesToString() expects Uint8Array');
    return CODERS[type].encode(bytes);
};
/** @deprecated */
export const str = bytesToString; // as in python, but for bytes only
/** @deprecated */
export const stringToBytes = (type, str) => {
    if (!CODERS.hasOwnProperty(type))
        throw new TypeError(coderTypeError);
    if (typeof str !== 'string')
        throw new TypeError('stringToBytes() expects string');
    return CODERS[type].decode(str);
};
/** @deprecated */
export const bytes = stringToBytes;
//# sourceMappingURL=index.js.map{ "type": "module", "sideEffects": false }
/**
 * @module BIP32 hierarchical deterministic (HD) wallets over secp256k1.
 * @example
 * ```js
 * import { HDKey } from "@scure/bip32";
 * const hdkey1 = HDKey.fromMasterSeed(seed);
 * const hdkey2 = HDKey.fromExtendedKey(base58key);
 * const hdkey3 = HDKey.fromJSON({ xpriv: string });
 *
 * // props
 * [hdkey1.depth, hdkey1.index, hdkey1.chainCode];
 * console.log(hdkey2.privateKey, hdkey2.publicKey);
 * console.log(hdkey3.derive("m/0/2147483647'/1"));
 * const sig = hdkey3.sign(hash);
 * hdkey3.verify(hash, sig);
 * ```
 */
/*! scure-bip32 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) */
import { mod } from '@noble/curves/abstract/modular';
import { secp256k1 as secp } from '@noble/curves/secp256k1';
import { hmac } from '@noble/hashes/hmac';
import { ripemd160 } from '@noble/hashes/legacy';
import { sha256, sha512 } from '@noble/hashes/sha2';
import { abytes, bytesToHex, concatBytes, createView, hexToBytes, utf8ToBytes, } from '@noble/hashes/utils';
import { createBase58check } from '@scure/base';
const Point = secp.ProjectivePoint;
const base58check = createBase58check(sha256);
function bytesToNumber(bytes) {
    abytes(bytes);
    const h = bytes.length === 0 ? '0' : bytesToHex(bytes);
    return BigInt('0x' + h);
}
function numberToBytes(num) {
    if (typeof num !== 'bigint')
        throw new Error('bigint expected');
    return hexToBytes(num.toString(16).padStart(64, '0'));
}
const MASTER_SECRET = utf8ToBytes('Bitcoin seed');
// Bitcoin hardcoded by default
const BITCOIN_VERSIONS = { private: 0x0488ade4, public: 0x0488b21e };
export const HARDENED_OFFSET = 0x80000000;
const hash160 = (data) => ripemd160(sha256(data));
const fromU32 = (data) => createView(data).getUint32(0, false);
const toU32 = (n) => {
    if (!Number.isSafeInteger(n) || n < 0 || n > 2 ** 32 - 1) {
        throw new Error('invalid number, should be from 0 to 2**32-1, got ' + n);
    }
    const buf = new Uint8Array(4);
    createView(buf).setUint32(0, n, false);
    return buf;
};
export class HDKey {
    get fingerprint() {
        if (!this.pubHash) {
            throw new Error('No publicKey set!');
        }
        return fromU32(this.pubHash);
    }
    get identifier() {
        return this.pubHash;
    }
    get pubKeyHash() {
        return this.pubHash;
    }
    get privateKey() {
        return this.privKeyBytes || null;
    }
    get publicKey() {
        return this.pubKey || null;
    }
    get privateExtendedKey() {
        const priv = this.privateKey;
        if (!priv) {
            throw new Error('No private key');
        }
        return base58check.encode(this.serialize(this.versions.private, concatBytes(new Uint8Array([0]), priv)));
    }
    get publicExtendedKey() {
        if (!this.pubKey) {
            throw new Error('No public key');
        }
        return base58check.encode(this.serialize(this.versions.public, this.pubKey));
    }
    static fromMasterSeed(seed, versions = BITCOIN_VERSIONS) {
        abytes(seed);
        if (8 * seed.length < 128 || 8 * seed.length > 512) {
            throw new Error('HDKey: seed length must be between 128 and 512 bits; 256 bits is advised, got ' +
                seed.length);
        }
        const I = hmac(sha512, MASTER_SECRET, seed);
        return new HDKey({
            versions,
            chainCode: I.slice(32),
            privateKey: I.slice(0, 32),
        });
    }
    static fromExtendedKey(base58key, versions = BITCOIN_VERSIONS) {
        // => version(4) || depth(1) || fingerprint(4) || index(4) || chain(32) || key(33)
        const keyBuffer = base58check.decode(base58key);
        const keyView = createView(keyBuffer);
        const version = keyView.getUint32(0, false);
        const opt = {
            versions,
            depth: keyBuffer[4],
            parentFingerprint: keyView.getUint32(5, false),
            index: keyView.getUint32(9, false),
            chainCode: keyBuffer.slice(13, 45),
        };
        const key = keyBuffer.slice(45);
        const isPriv = key[0] === 0;
        if (version !== versions[isPriv ? 'private' : 'public']) {
            throw new Error('Version mismatch');
        }
        if (isPriv) {
            return new HDKey({ ...opt, privateKey: key.slice(1) });
        }
        else {
            return new HDKey({ ...opt, publicKey: key });
        }
    }
    static fromJSON(json) {
        return HDKey.fromExtendedKey(json.xpriv);
    }
    constructor(opt) {
        this.depth = 0;
        this.index = 0;
        this.chainCode = null;
        this.parentFingerprint = 0;
        if (!opt || typeof opt !== 'object') {
            throw new Error('HDKey.constructor must not be called directly');
        }
        this.versions = opt.versions || BITCOIN_VERSIONS;
        this.depth = opt.depth || 0;
        this.chainCode = opt.chainCode || null;
        this.index = opt.index || 0;
        this.parentFingerprint = opt.parentFingerprint || 0;
        if (!this.depth) {
            if (this.parentFingerprint || this.index) {
                throw new Error('HDKey: zero depth with non-zero index/parent fingerprint');
            }
        }
        if (opt.publicKey && opt.privateKey) {
            throw new Error('HDKey: publicKey and privateKey at same time.');
        }
        if (opt.privateKey) {
            if (!secp.utils.isValidPrivateKey(opt.privateKey)) {
                throw new Error('Invalid private key');
            }
            this.privKey =
                typeof opt.privateKey === 'bigint' ? opt.privateKey : bytesToNumber(opt.privateKey);
            this.privKeyBytes = numberToBytes(this.privKey);
            this.pubKey = secp.getPublicKey(opt.privateKey, true);
        }
        else if (opt.publicKey) {
            this.pubKey = Point.fromHex(opt.publicKey).toRawBytes(true); // force compressed point
        }
        else {
            throw new Error('HDKey: no public or private key provided');
        }
        this.pubHash = hash160(this.pubKey);
    }
    derive(path) {
        if (!/^[mM]'?/.test(path)) {
            throw new Error('Path must start with "m" or "M"');
        }
        if (/^[mM]'?$/.test(path)) {
            return this;
        }
        const parts = path.replace(/^[mM]'?\//, '').split('/');
        // tslint:disable-next-line
        let child = this;
        for (const c of parts) {
            const m = /^(\d+)('?)$/.exec(c);
            const m1 = m && m[1];
            if (!m || m.length !== 3 || typeof m1 !== 'string')
                throw new Error('invalid child index: ' + c);
            let idx = +m1;
            if (!Number.isSafeInteger(idx) || idx >= HARDENED_OFFSET) {
                throw new Error('Invalid index');
            }
            // hardened key
            if (m[2] === "'") {
                idx += HARDENED_OFFSET;
            }
            child = child.deriveChild(idx);
        }
        return child;
    }
    deriveChild(index) {
        if (!this.pubKey || !this.chainCode) {
            throw new Error('No publicKey or chainCode set');
        }
        let data = toU32(index);
        if (index >= HARDENED_OFFSET) {
            // Hardened
            const priv = this.privateKey;
            if (!priv) {
                throw new Error('Could not derive hardened child key');
            }
            // Hardened child: 0x00 || ser256(kpar) || ser32(index)
            data = concatBytes(new Uint8Array([0]), priv, data);
        }
        else {
            // Normal child: serP(point(kpar)) || ser32(index)
            data = concatBytes(this.pubKey, data);
        }
        const I = hmac(sha512, this.chainCode, data);
        const childTweak = bytesToNumber(I.slice(0, 32));
        const chainCode = I.slice(32);
        if (!secp.utils.isValidPrivateKey(childTweak)) {
            throw new Error('Tweak bigger than curve order');
        }
        const opt = {
            versions: this.versions,
            chainCode,
            depth: this.depth + 1,
            parentFingerprint: this.fingerprint,
            index,
        };
        try {
            // Private parent key -> private child key
            if (this.privateKey) {
                const added = mod(this.privKey + childTweak, secp.CURVE.n);
                if (!secp.utils.isValidPrivateKey(added)) {
                    throw new Error('The tweak was out of range or the resulted private key is invalid');
                }
                opt.privateKey = added;
            }
            else {
                const added = Point.fromHex(this.pubKey).add(Point.fromPrivateKey(childTweak));
                // Cryptographically impossible: hmac-sha512 preimage would need to be found
                if (added.equals(Point.ZERO)) {
                    throw new Error('The tweak was equal to negative P, which made the result key invalid');
                }
                opt.publicKey = added.toRawBytes(true);
            }
            return new HDKey(opt);
        }
        catch (err) {
            return this.deriveChild(index + 1);
        }
    }
    sign(hash) {
        if (!this.privateKey) {
            throw new Error('No privateKey set!');
        }
        abytes(hash, 32);
        return secp.sign(hash, this.privKey).toCompactRawBytes();
    }
    verify(hash, signature) {
        abytes(hash, 32);
        abytes(signature, 64);
        if (!this.publicKey) {
            throw new Error('No publicKey set!');
        }
        let sig;
        try {
            sig = secp.Signature.fromCompact(signature);
        }
        catch (error) {
            return false;
        }
        return secp.verify(sig, hash, this.publicKey);
    }
    wipePrivateData() {
        this.privKey = undefined;
        if (this.privKeyBytes) {
            this.privKeyBytes.fill(0);
            this.privKeyBytes = undefined;
        }
        return this;
    }
    toJSON() {
        return {
            xpriv: this.privateExtendedKey,
            xpub: this.publicExtendedKey,
        };
    }
    serialize(version, key) {
        if (!this.chainCode) {
            throw new Error('No chainCode set');
        }
        abytes(key, 33);
        // version(4) || depth(1) || fingerprint(4) || index(4) || chain(32) || key(33)
        return concatBytes(toU32(version), new Uint8Array([this.depth]), toU32(this.parentFingerprint), toU32(this.index), this.chainCode, key);
    }
}
//# sourceMappingURL=index.js.map{
  "type": "module",
  "sideEffects": false
}/**
 * Audited & minimal JS implementation of
 * [BIP39 mnemonic phrases](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki).
 * @module
 * @example
```js
import * as bip39 from '@scure/bip39';
import { wordlist } from '@scure/bip39/wordlists/english';
const mn = bip39.generateMnemonic(wordlist);
console.log(mn);
const ent = bip39.mnemonicToEntropy(mn, wordlist)
bip39.entropyToMnemonic(ent, wordlist);
bip39.validateMnemonic(mn, wordlist);
await bip39.mnemonicToSeed(mn, 'password');
bip39.mnemonicToSeedSync(mn, 'password');

// Wordlists
import { wordlist as czech } from '@scure/bip39/wordlists/czech';
import { wordlist as english } from '@scure/bip39/wordlists/english';
import { wordlist as french } from '@scure/bip39/wordlists/french';
import { wordlist as italian } from '@scure/bip39/wordlists/italian';
import { wordlist as japanese } from '@scure/bip39/wordlists/japanese';
import { wordlist as korean } from '@scure/bip39/wordlists/korean';
import { wordlist as portuguese } from '@scure/bip39/wordlists/portuguese';
import { wordlist as simplifiedChinese } from '@scure/bip39/wordlists/simplified-chinese';
import { wordlist as spanish } from '@scure/bip39/wordlists/spanish';
import { wordlist as traditionalChinese } from '@scure/bip39/wordlists/traditional-chinese';
```
 */
/*! scure-bip39 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) */
import { pbkdf2, pbkdf2Async } from '@noble/hashes/pbkdf2';
import { sha256, sha512 } from '@noble/hashes/sha2';
import { abytes, anumber, randomBytes } from '@noble/hashes/utils';
import { utils as baseUtils } from '@scure/base';
// Japanese wordlist
const isJapanese = (wordlist) => wordlist[0] === '\u3042\u3044\u3053\u304f\u3057\u3093';
// Normalization replaces equivalent sequences of characters
// so that any two texts that are equivalent will be reduced
// to the same sequence of code points, called the normal form of the original text.
// https://tonsky.me/blog/unicode/#why-is-a----
function nfkd(str) {
    if (typeof str !== 'string')
        throw new TypeError('invalid mnemonic type: ' + typeof str);
    return str.normalize('NFKD');
}
function normalize(str) {
    const norm = nfkd(str);
    const words = norm.split(' ');
    if (![12, 15, 18, 21, 24].includes(words.length))
        throw new Error('Invalid mnemonic');
    return { nfkd: norm, words };
}
function aentropy(ent) {
    abytes(ent, 16, 20, 24, 28, 32);
}
/**
 * Generate x random words. Uses Cryptographically-Secure Random Number Generator.
 * @param wordlist imported wordlist for specific language
 * @param strength mnemonic strength 128-256 bits
 * @example
 * generateMnemonic(wordlist, 128)
 * // 'legal winner thank year wave sausage worth useful legal winner thank yellow'
 */
export function generateMnemonic(wordlist, strength = 128) {
    anumber(strength);
    if (strength % 32 !== 0 || strength > 256)
        throw new TypeError('Invalid entropy');
    return entropyToMnemonic(randomBytes(strength / 8), wordlist);
}
const calcChecksum = (entropy) => {
    // Checksum is ent.length/4 bits long
    const bitsLeft = 8 - entropy.length / 4;
    // Zero rightmost "bitsLeft" bits in byte
    // For example: bitsLeft=4 val=10111101 -> 10110000
    return new Uint8Array([(sha256(entropy)[0] >> bitsLeft) << bitsLeft]);
};
function getCoder(wordlist) {
    if (!Array.isArray(wordlist) || wordlist.length !== 2048 || typeof wordlist[0] !== 'string')
        throw new Error('Wordlist: expected array of 2048 strings');
    wordlist.forEach((i) => {
        if (typeof i !== 'string')
            throw new Error('wordlist: non-string element: ' + i);
    });
    return baseUtils.chain(baseUtils.checksum(1, calcChecksum), baseUtils.radix2(11, true), baseUtils.alphabet(wordlist));
}
/**
 * Reversible: Converts mnemonic string to raw entropy in form of byte array.
 * @param mnemonic 12-24 words
 * @param wordlist imported wordlist for specific language
 * @example
 * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';
 * mnemonicToEntropy(mnem, wordlist)
 * // Produces
 * new Uint8Array([
 *   0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f,
 *   0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f
 * ])
 */
export function mnemonicToEntropy(mnemonic, wordlist) {
    const { words } = normalize(mnemonic);
    const entropy = getCoder(wordlist).decode(words);
    aentropy(entropy);
    return entropy;
}
/**
 * Reversible: Converts raw entropy in form of byte array to mnemonic string.
 * @param entropy byte array
 * @param wordlist imported wordlist for specific language
 * @returns 12-24 words
 * @example
 * const ent = new Uint8Array([
 *   0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f,
 *   0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f
 * ]);
 * entropyToMnemonic(ent, wordlist);
 * // 'legal winner thank year wave sausage worth useful legal winner thank yellow'
 */
export function entropyToMnemonic(entropy, wordlist) {
    aentropy(entropy);
    const words = getCoder(wordlist).encode(entropy);
    return words.join(isJapanese(wordlist) ? '\u3000' : ' ');
}
/**
 * Validates mnemonic for being 12-24 words contained in `wordlist`.
 */
export function validateMnemonic(mnemonic, wordlist) {
    try {
        mnemonicToEntropy(mnemonic, wordlist);
    }
    catch (e) {
        return false;
    }
    return true;
}
const psalt = (passphrase) => nfkd('mnemonic' + passphrase);
/**
 * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password.
 * @param mnemonic 12-24 words
 * @param passphrase string that will additionally protect the key
 * @returns 64 bytes of key data
 * @example
 * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';
 * await mnemonicToSeed(mnem, 'password');
 * // new Uint8Array([...64 bytes])
 */
export function mnemonicToSeed(mnemonic, passphrase = '') {
    return pbkdf2Async(sha512, normalize(mnemonic).nfkd, psalt(passphrase), { c: 2048, dkLen: 64 });
}
/**
 * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password.
 * @param mnemonic 12-24 words
 * @param passphrase string that will additionally protect the key
 * @returns 64 bytes of key data
 * @example
 * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';
 * mnemonicToSeedSync(mnem, 'password');
 * // new Uint8Array([...64 bytes])
 */
export function mnemonicToSeedSync(mnemonic, passphrase = '') {
    return pbkdf2(sha512, normalize(mnemonic).nfkd, psalt(passphrase), { c: 2048, dkLen: 64 });
}
{
  "type": "module"
}function isBuffer(value) {
  return Buffer.isBuffer(value) || value instanceof Uint8Array
}

function isEncoding(encoding) {
  return Buffer.isEncoding(encoding)
}

function alloc(size, fill, encoding) {
  return Buffer.alloc(size, fill, encoding)
}

function allocUnsafe(size) {
  return Buffer.allocUnsafe(size)
}

function allocUnsafeSlow(size) {
  return Buffer.allocUnsafeSlow(size)
}

function byteLength(string, encoding) {
  return Buffer.byteLength(string, encoding)
}

function compare(a, b) {
  return Buffer.compare(a, b)
}

function concat(buffers, totalLength) {
  return Buffer.concat(buffers, totalLength)
}

function copy(source, target, targetStart, start, end) {
  return toBuffer(source).copy(target, targetStart, start, end)
}

function equals(a, b) {
  return toBuffer(a).equals(b)
}

function fill(buffer, value, offset, end, encoding) {
  return toBuffer(buffer).fill(value, offset, end, encoding)
}

function from(value, encodingOrOffset, length) {
  return Buffer.from(value, encodingOrOffset, length)
}

function includes(buffer, value, byteOffset, encoding) {
  return toBuffer(buffer).includes(value, byteOffset, encoding)
}

function indexOf(buffer, value, byfeOffset, encoding) {
  return toBuffer(buffer).indexOf(value, byfeOffset, encoding)
}

function lastIndexOf(buffer, value, byteOffset, encoding) {
  return toBuffer(buffer).lastIndexOf(value, byteOffset, encoding)
}

function swap16(buffer) {
  return toBuffer(buffer).swap16()
}

function swap32(buffer) {
  return toBuffer(buffer).swap32()
}

function swap64(buffer) {
  return toBuffer(buffer).swap64()
}

function toBuffer(buffer) {
  if (Buffer.isBuffer(buffer)) return buffer
  return Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

function toString(buffer, encoding, start, end) {
  return toBuffer(buffer).toString(encoding, start, end)
}

function write(buffer, string, offset, length, encoding) {
  return toBuffer(buffer).write(string, offset, length, encoding)
}

function readDoubleBE(buffer, offset) {
  return toBuffer(buffer).readDoubleBE(offset)
}

function readDoubleLE(buffer, offset) {
  return toBuffer(buffer).readDoubleLE(offset)
}

function readFloatBE(buffer, offset) {
  return toBuffer(buffer).readFloatBE(offset)
}

function readFloatLE(buffer, offset) {
  return toBuffer(buffer).readFloatLE(offset)
}

function readInt32BE(buffer, offset) {
  return toBuffer(buffer).readInt32BE(offset)
}

function readInt32LE(buffer, offset) {
  return toBuffer(buffer).readInt32LE(offset)
}

function readUInt32BE(buffer, offset) {
  return toBuffer(buffer).readUInt32BE(offset)
}

function readUInt32LE(buffer, offset) {
  return toBuffer(buffer).readUInt32LE(offset)
}

function writeDoubleBE(buffer, value, offset) {
  return toBuffer(buffer).writeDoubleBE(value, offset)
}

function writeDoubleLE(buffer, value, offset) {
  return toBuffer(buffer).writeDoubleLE(value, offset)
}

function writeFloatBE(buffer, value, offset) {
  return toBuffer(buffer).writeFloatBE(value, offset)
}

function writeFloatLE(buffer, value, offset) {
  return toBuffer(buffer).writeFloatLE(value, offset)
}

function writeInt32BE(buffer, value, offset) {
  return toBuffer(buffer).writeInt32BE(value, offset)
}

function writeInt32LE(buffer, value, offset) {
  return toBuffer(buffer).writeInt32LE(value, offset)
}

function writeUInt32BE(buffer, value, offset) {
  return toBuffer(buffer).writeUInt32BE(value, offset)
}

function writeUInt32LE(buffer, value, offset) {
  return toBuffer(buffer).writeUInt32LE(value, offset)
}

module.exports = {
  isBuffer,
  isEncoding,
  alloc,
  allocUnsafe,
  allocUnsafeSlow,
  byteLength,
  compare,
  concat,
  copy,
  equals,
  fill,
  from,
  includes,
  indexOf,
  lastIndexOf,
  swap16,
  swap32,
  swap64,
  toBuffer,
  toString,
  write,
  readDoubleBE,
  readDoubleLE,
  readFloatBE,
  readFloatLE,
  readInt32BE,
  readInt32LE,
  readUInt32BE,
  readUInt32LE,
  writeDoubleBE,
  writeDoubleLE,
  writeFloatBE,
  writeFloatLE,
  writeInt32BE,
  writeInt32LE,
  writeUInt32BE,
  writeUInt32LE
}
{
  "name": "b4a",
  "version": "1.8.1",
  "description": "Bridging the gap between buffers and typed arrays",
  "exports": {
    "./package": "./package.json",
    ".": {
      "react-native": "./react-native.js",
      "browser": "./browser.js",
      "default": "./index.js"
    }
  },
  "files": [
    "browser.js",
    "index.js",
    "react-native.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:bare && npm run test:node",
    "test:bare": "brittle-bare --coverage test.mjs",
    "test:node": "brittle-node --coverage test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/b4a.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/b4a/issues"
  },
  "homepage": "https://github.com/holepunchto/b4a#readme",
  "devDependencies": {
    "brittle": "^3.5.2",
    "lunte": "^1.7.0",
    "nanobench": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "react-native-b4a": "*"
  },
  "peerDependenciesMeta": {
    "react-native-b4a": {
      "optional": true
    }
  }
}
const ESC = '\x1b'
const CSI = ESC + '['
const SGR = (n) => CSI + n + 'm'

exports.constants = {
  ESC,
  CSI,
  SGR
}

// https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_(Control_Sequence_Introducer)_sequences

exports.cursorHide = CSI + '?25l'
exports.cursorShow = CSI + '?25h'

exports.cursorUp = function cursorUp(n = 1) {
  return CSI + n + 'A'
}

exports.cursorDown = function cursorDown(n = 1) {
  return CSI + n + 'B'
}

exports.cursorForward = function cursorForward(n = 1) {
  return CSI + n + 'C'
}

exports.cursorBack = function cursorBack(n = 1) {
  return CSI + n + 'D'
}

exports.cursorNextLine = function cursorNextLine(n = 1) {
  return CSI + n + 'E'
}

exports.cursorPreviousLine = function cursorPreviousLine(n = 1) {
  return CSI + n + 'F'
}

exports.cursorPosition = function cursorPosition(column, row = 0) {
  if (row === 0) return CSI + (column + 1) + 'G'

  return CSI + (row + 1) + ';' + (column + 1) + 'H'
}

exports.eraseDisplayEnd = CSI + 'J'
exports.eraseDisplayStart = CSI + '1J'
exports.eraseDisplay = CSI + '2J'
exports.eraseLineEnd = CSI + 'K'
exports.eraseLineStart = CSI + '1K'
exports.eraseLine = CSI + '2K'

exports.scrollUp = function scrollUp(n = 1) {
  return CSI + n + 'S'
}

exports.scrollDown = function scrollDown(n = 1) {
  return CSI + n + 'T'
}

// https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_(Select_Graphic_Rendition)_parameters

exports.modifierReset = SGR(0)
exports.modifierBold = SGR(1)
exports.modifierDim = SGR(2)
exports.modifierItalic = SGR(3)
exports.modifierUnderline = SGR(4)
exports.modifierNormal = SGR(22)
exports.modifierNotItalic = SGR(23)
exports.modifierNotUnderline = SGR(24)

// https://en.wikipedia.org/wiki/ANSI_escape_code#Colors

exports.colorBlack = SGR(30)
exports.colorRed = SGR(31)
exports.colorGreen = SGR(32)
exports.colorYellow = SGR(33)
exports.colorBlue = SGR(34)
exports.colorMagenta = SGR(35)
exports.colorCyan = SGR(36)
exports.colorWhite = SGR(37)
exports.colorDefault = SGR(39)
exports.colorBrightBlack = SGR(90)
exports.colorBrightRed = SGR(91)
exports.colorBrightGreen = SGR(92)
exports.colorBrightYellow = SGR(93)
exports.colorBrightBlue = SGR(94)
exports.colorBrightMagenta = SGR(95)
exports.colorBrightCyan = SGR(96)
exports.colorBrightWhite = SGR(97)
{
  "name": "bare-ansi-escapes",
  "version": "2.2.3",
  "description": "Parse and produce ANSI escape sequences",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./key-decoder": {
      "types": "./key-decoder.d.ts",
      "default": "./key-decoder.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "key-decoder.js",
    "key-decoder.d.ts"
  ],
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-ansi-escapes.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-ansi-escapes/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-ansi-escapes#readme",
  "dependencies": {
    "bare-stream": "^2.6.5"
  },
  "devDependencies": {
    "bare-buffer": "^3.0.2",
    "brittle": "^3.3.2",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  },
  "peerDependencies": {
    "bare-buffer": "*"
  },
  "peerDependenciesMeta": {
    "bare-buffer": {
      "optional": true
    }
  }
}
const inspect = require('bare-inspect')

class AssertionError extends Error {
  constructor(opts = {}) {
    let { message = null, actual, expected, operator } = opts

    if (message === null) {
      message = `${inspect(actual)} ${operator} ${inspect(expected)}`
    }

    super(message)

    this.actual = actual
    this.expected = expected
    this.operator = operator
  }

  get name() {
    return 'AssertionError'
  }

  get code() {
    'ASSERTION'
  }
}

function assertFail(opts, fn) {
  if (opts.message instanceof Error) throw opts.message

  const err = new AssertionError(opts)

  if (Error.captureStackTrace) Error.captureStackTrace(err, fn)

  throw err
}

module.exports = exports = function assert(actual, message) {
  if (actual) return

  assertFail({ message, actual, expected: true, operator: '==' }, assert)
}

exports.AssertionError = AssertionError

exports.fail = function fail(message) {
  if (message === undefined) message = 'Failed'

  assertFail({ message, operator: 'fail' }, fail)
}

exports.ok = function ok(actual, message) {
  if (actual) return

  assertFail({ message, actual, expected: true, operator: '==' }, ok)
}

exports.notOk = function ok(actual, message) {
  if (!actual) return

  assertFail({ message, actual, expected: false, operator: '==' }, ok)
}

exports.equal = function equal(actual, expected, message) {
  if (actual == expected || (actual !== actual && expected !== expected)) {
    return
  }

  assertFail({ message, actual, expected, operator: '==' }, equal)
}

exports.notEqual = function notEqual(actual, expected, message) {
  if (actual != expected && (actual === actual || expected === expected)) {
    return
  }

  assertFail({ message, actual, expected, operator: '!=' }, notEqual)
}

exports.strictEqual = function strictEqual(actual, expected, message) {
  if (Object.is(actual, expected)) return

  assertFail(
    { message, actual, expected, operator: 'strictEqual' },
    strictEqual
  )
}

exports.notStrictEqual = function notStrictEqual(actual, expected, message) {
  if (!Object.is(actual, expected)) return

  assertFail(
    { message, actual, expected, operator: 'notStrictEqual' },
    notStrictEqual
  )
}
{
  "name": "bare-assert",
  "version": "1.2.0",
  "description": "Assertion library for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts"
  ],
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-assert.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-assert/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-assert#readme",
  "dependencies": {
    "bare-inspect": "^3.1.2"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  }
}
module.exports = require.addon()
const ansiEscapes = require('bare-ansi-escapes')
const getType = require('bare-type')
const binding = require('./binding')

const PLAIN_KEY = /^[a-zA-Z_][a-zA-Z_0-9]*$/

const defaultDepth = 2
const defaultBreakLength = 80
const defaultMaxArrayLength = 40

module.exports = exports = function inspect(value, opts = {}) {
  const {
    colors = false,
    depth = defaultDepth,
    breakLength = defaultBreakLength,
    stylize = defaultStylize(colors)
  } = opts

  const references = new InspectRefMap()

  const tree = inspectValue(value, 0, {
    colors,
    depth,
    breakLength,
    stylize,
    references
  })

  return tree.toString()
}

exports.styles = {
  bigint: ansiEscapes.colorYellow,
  boolean: ansiEscapes.colorYellow,
  date: ansiEscapes.colorMagenta,
  module: ansiEscapes.modifierUnderline,
  name: ansiEscapes.modifierReset,
  null: ansiEscapes.modifierBold,
  number: ansiEscapes.colorYellow,
  regexp: ansiEscapes.colorRed,
  special: ansiEscapes.colorCyan,
  string: ansiEscapes.colorGreen,
  symbol: ansiEscapes.colorGreen,
  undefined: ansiEscapes.colorBrightBlack
}

const styles = exports.styles

function defaultStylize(colors) {
  return function stylize(value, style) {
    const color = colors && styles[style]

    if (color) return color + value + ansiEscapes.modifierReset

    return value
  }
}

class InspectRefMap {
  constructor() {
    this.refs = new WeakMap()
    this.ids = new WeakMap()
    this.nextId = 1
  }

  has(object) {
    return this.refs.has(object)
  }

  get(object) {
    return this.refs.get(object) || null
  }

  set(object, ref) {
    this.refs.set(object, ref)
  }

  id(object) {
    let id = this.ids.get(object)
    if (id) return id

    id = this.nextId++
    this.ids.set(object, id)

    return id
  }
}

class InspectNode {
  constructor(depth, length, opts) {
    const { breakLength = defaultBreakLength, breakAlways = false } = opts

    this.depth = depth
    this.length = length
    this.breakLength = breakLength
    this.breakAlways = breakAlways
  }

  pad(n, string) {
    return string.padStart(n, ' ')
  }

  indent(n, string) {
    return '  '.repeat(n) + string
  }
}

class InspectRef extends InspectNode {
  constructor(depth, opts) {
    super(depth, '[circular *]'.length, opts)

    this.refs = opts.references
    this.count = 0
    this.circular = false
    this.color = opts.colors && styles.special
  }

  get id() {
    return this.refs.id(this)
  }

  increment() {
    return ++this.count
  }

  decrement() {
    return --this.count
  }

  toString(opts = {}) {
    const { offset = 0, pad = 0, indent = 0 } = opts

    let value = this.pad(pad, '[circular *' + this.id + ']')

    if (this.color) value = this.color + value + ansiEscapes.modifierReset

    return offset ? value : this.indent(indent, value)
  }
}

class InspectLeaf extends InspectNode {
  constructor(value, color, depth, opts) {
    const length = value.length

    if (value.includes('\n')) {
      value = value.replaceAll('\n', '\n' + '  '.repeat(depth))

      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.value = value
    this.color = opts.colors && color
  }

  toString(opts = {}) {
    const { offset = 0, pad = 0, indent = 0 } = opts

    let value = this.pad(pad, this.value)

    if (this.color) value = this.color + value + ansiEscapes.modifierReset

    return offset ? value : this.indent(indent, value)
  }
}

class InspectPair extends InspectNode {
  constructor(delim, left, right, depth, opts) {
    const length = left.length + delim.length + right.length

    if (left.breakAlways || right.breakAlways) {
      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.delim = delim
    this.left = left
    this.right = right
  }

  toString(opts = {}) {
    const { indent = 0 } = opts

    return this.indent(
      indent,
      this.left +
        this.delim +
        this.right.toString({
          indent,
          offset: this.left.length + this.delim.length
        })
    )
  }
}

class InspectSuspension extends InspectNode {
  constructor(overflow, depth, opts) {
    const label = `... ${overflow} more`

    super(depth, label.length, opts)

    this.label = label
  }

  toString(opts = {}) {
    const { indent = 0 } = opts

    return this.indent(indent, this.label)
  }
}

class InspectSequence extends InspectNode {
  constructor(header, footer, delim, values, ref, depth, opts) {
    const { tabulate = false } = opts

    const length =
      (ref.circular ? '<ref *>'.length + 1 : 0) +
      header.length +
      values.reduce(
        (length, value, i) =>
          length + value.length + (i === 0 ? 0 : delim.length),
        0
      ) +
      footer.length

    if (values.some((value) => value.breakAlways)) {
      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.header = header
    this.footer = footer
    this.delim = delim
    this.values = values
    this.ref = ref
    this.tabulate = tabulate
  }

  toString(opts = {}) {
    const { offset = 0, indent = 0 } = opts

    const split =
      this.breakAlways ||
      (this.values.length &&
        (offset + this.length > this.breakLength ||
          indent * 2 + this.length > this.breakLength))

    let header = this.header

    if (this.ref.circular) {
      header = '<ref *' + this.ref.id + '> ' + header
    }

    if (this.values.length === 0) {
      header = header.trimEnd()
    }

    if (offset === 0) {
      header = this.indent(indent, header)
    }

    if (split) {
      header = header.trimEnd() + '\n'
    }

    let string = header

    let columns = 1
    let pad = 0

    if (this.tabulate) {
      const widest = this.values.reduce(
        (length, value) =>
          value.breakAlways ? length : Math.max(length, value.length),
        0
      )

      if (widest) {
        columns = Math.max(
          columns,
          Math.floor(
            (this.breakLength - indent * 2) / (widest + this.delim.length)
          )
        )

        if (columns > 1) pad = widest
      }
    }

    for (let i = 0, n = this.values.length, offset = 0; i < n; i++) {
      const value = this.values[i]

      if (split) {
        let part

        if (i % columns === 0 || value.breakAlways) {
          part = value.toString({ indent: indent + 1, pad })
        } else {
          part = value.toString({ pad })
        }

        string += part

        if (i < n - 1) {
          if (i % columns === columns - 1 || this.values[i + 1].breakAlways) {
            string += this.delim.trimEnd() + '\n'
          } else {
            string += this.delim
          }
        }
      } else {
        if (i > 0) string += this.delim

        string += value.toString({ offset })

        offset += value.length
      }
    }

    let footer = this.footer

    if (this.values.length === 0) {
      footer = footer.trimStart()
    }

    if (split) {
      string += '\n' + this.indent(indent, footer.trimStart())
    } else {
      string += footer
    }

    return string
  }
}

function inspectValue(value, depth, opts) {
  const type = getType(value)

  if (type.isUndefined()) return inspectUndefined(depth, opts)
  if (type.isNull()) return inspectNull(depth, opts)
  if (type.isBoolean()) return inspectBoolean(value, depth, opts)
  if (type.isNumber()) return inspectNumber(value, depth, opts)
  if (type.isBigInt()) return inspectBigInt(value, depth, opts)
  if (type.isString()) return inspectString(value, depth, opts)
  if (type.isSymbol()) return inspectSymbol(value, depth, opts)
  if (type.isObject()) return inspectObject(type, value, depth, opts)
  if (type.isFunction()) return inspectFunction(type, value, depth, opts)
  if (type.isExternal()) return inspectExternal(value, opts, opts)
}

function inspectUndefined(depth, opts) {
  return new InspectLeaf('undefined', styles.undefined, depth, opts)
}

function inspectNull(depth, opts) {
  return new InspectLeaf('null', styles.null, depth, opts)
}

function inspectBoolean(value, depth, opts) {
  return new InspectLeaf(value.toString(), styles.boolean, depth, opts)
}

function inspectNumber(value, depth, opts) {
  let string

  if (Object.is(value, -0)) {
    string = '-0'
  } else {
    string = value.toString(10)
  }

  return new InspectLeaf(string, styles.number, depth, opts)
}

function inspectBigInt(value, depth, opts) {
  return new InspectLeaf(value.toString(10) + 'n', styles.bigint, depth, opts)
}

const STRING_ESCAPES =
  /[\ud800-\udbff][\udc00-\udfff]|[\u0000-\u001f'\\\ud800-\udfff]/g

function inspectString(value, depth, opts) {
  // https://tc39.es/ecma262/multipage/structured-data.html#sec-quotejsonstring
  const string = value.replace(STRING_ESCAPES, (match) => {
    if (match.length === 2) return match

    switch (match) {
      case "'":
        return "\\'"
      case '\\':
        return '\\\\'
      case '\b':
        return '\\b'
      case '\t':
        return '\\t'
      case '\n':
        return '\\n'
      case '\f':
        return '\\f'
      case '\r':
        return '\\r'
      default:
        return '\\u' + match.charCodeAt(0).toString(16).padStart(4, '0')
    }
  })

  return new InspectLeaf("'" + string + "'", styles.string, depth, opts)
}

function inspectSymbol(value, depth, opts) {
  return new InspectLeaf(value.toString(), styles.symbol, depth, opts)
}

function inspectKey(value, depth, opts) {
  if (PLAIN_KEY.test(value)) {
    return new InspectLeaf(value, null, depth, opts)
  } else {
    return inspectValue(value, depth, opts)
  }
}

function inspectObject(type, object, depth, opts) {
  const refs = opts.references

  let ref = refs.get(object)
  if (ref === null) {
    ref = new InspectRef(depth, opts)
    refs.set(object, ref)
  } else if (ref.count) {
    ref.circular = true
    return ref
  }

  const maxDepth = typeof opts.depth === 'number' ? opts.depth : Infinity

  if (maxDepth < depth) {
    const constructor = object.constructor

    return new InspectLeaf(
      '[' +
        (constructor && constructor.name ? constructor.name : 'Object') +
        ']',
      styles.special,
      depth,
      opts
    )
  }

  const inspect =
    object[Symbol.for('bare.inspect')] ||
    object[Symbol.for('nodejs.util.inspect.custom')]

  if (typeof inspect === 'function') {
    const value = inspect.call(
      object,
      typeof opts.depth === 'number' ? opts.depth - depth : null,
      {
        colors: opts.colors,
        breakLength: opts.breakLength,
        stylize: opts.stylize
      },
      exports
    )

    if (typeof value === 'object' && value !== null) {
      refs.set(value, ref)
    }

    if (typeof value !== 'string') {
      return inspectValue(value, depth, opts)
    }

    return new InspectLeaf(value, null, depth, opts)
  }

  if (type.isArray()) return inspectArray(object, ref, depth, opts)
  if (type.isDate()) return inspectDate(object, ref, depth, opts)
  if (type.isRegExp()) return inspectRegExp(object, ref, depth, opts)
  if (type.isError()) return inspectError(object, ref, depth, opts)
  if (type.isPromise()) return inspectPromise(object, ref, depth, opts)
  if (type.isMap()) return inspectMap(object, ref, depth, opts)
  if (type.isSet()) return inspectSet(object, ref, depth, opts)
  if (type.isWeakMap()) return inspectWeakMap(object, ref, depth, opts)
  if (type.isWeakSet()) return inspectWeakSet(object, ref, depth, opts)
  if (type.isWeakRef()) return inspectWeakRef(object, ref, depth, opts)
  if (type.isArrayBuffer()) return inspectArrayBuffer(object, ref, depth, opts)
  if (type.isSharedArrayBuffer())
    return inspectSharedArrayBuffer(object, ref, depth, opts)
  if (type.isTypedArray()) return inspectTypedArray(object, ref, depth, opts)
  if (type.isDataView()) return inspectDataView(object, ref, depth, opts)

  ref.increment()

  const values = []

  for (const key in object) {
    if (key === 'constructor') continue

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(object[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  let header = '{ '

  const tag = object[Symbol.toStringTag]

  if (tag) header = '[' + tag + '] ' + header

  if (object.constructor) {
    const name = object.constructor.name

    if (name && name !== 'Object') {
      header = object.constructor.name + ' ' + header
    }
  }

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectArray(array, ref, depth, opts) {
  const { maxArrayLength = defaultMaxArrayLength } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxArrayLength, 0)

  for (let i = 0, n = array.length; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(array.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(inspectValue(array[i], depth + 1, opts))
  }

  for (const key of binding.getOwnNonIndexPropertyNames(array)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(array[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  let header = '[ '

  if (array.constructor.name !== 'Array') {
    header = array.constructor.name + '(' + array.length + ') ' + header
  }

  return new InspectSequence(header, ' ]', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectDate(date, ref, depth, opts) {
  return new InspectLeaf(date.toISOString(), styles.date, depth, opts)
}

function inspectRegExp(regExp, ref, depth, opts) {
  return new InspectLeaf(regExp.toString(), styles.regexp, depth, opts)
}

function inspectError(error, ref, depth, opts) {
  let header

  if ('stack' in error) {
    header = error.stack

    if (depth > 0) {
      header = header.replaceAll('\n', '\n' + '  '.repeat(depth))
    }
  } else {
    header = error.toString()
  }

  const builtins = ['cause']

  if (error.name === 'AggregateError') {
    builtins.push('errors')
  } else if (error.name === 'SuppressedError') {
    builtins.push('error', 'suppressed')
  }

  const values = []

  for (const key of builtins) {
    if (key in error === false) continue

    values.push(
      new InspectPair(
        ': ',
        new InspectLeaf('[' + key + ']', null, depth + 1, opts),
        inspectValue(error[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key in error) {
    if (key === 'constructor' || builtins.includes(key)) continue

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(error[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  if (values.length === 0) return new InspectLeaf(header, null, depth, opts)

  return new InspectSequence(
    header + ' {',
    ' }',
    ', ',
    values,
    ref,
    depth,
    opts
  )
}

function inspectPromise(promise, ref, depth, opts) {
  ref.increment()

  const state = binding.getPromiseState(promise)

  const values = []

  switch (state) {
    case 0: // Pending
      values.push(new InspectLeaf('<pending>', styles.special, depth, opts))
      break

    case 1: // Fulfilled
      values.push(inspectValue(binding.getPromiseResult(promise), depth, opts))
      break

    case 2: // Rejected
      values.push(
        new InspectLeaf('<rejected>', styles.special, depth, opts),
        inspectValue(binding.getPromiseResult(promise), depth, opts)
      )
  }

  ref.decrement()

  const header = promise.constructor.name + ' { '

  return new InspectSequence(header, ' }', ' ', values, ref, depth, opts)
}

function inspectMap(map, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxMapLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = maxMapLength

  for (const entry of map) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(map.size - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )
      break
    }

    values.push(
      new InspectPair(
        ' => ',
        inspectValue(entry[0], depth + 1, opts),
        inspectValue(entry[1], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key in map) {
    if (key === 'constructor') continue

    const value = inspectValue(map[key], depth + 1, opts)

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        value,
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = map.constructor.name + '(' + map.size + ') { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectSet(set, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxSetLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = maxSetLength

  for (const entry of set) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(set.size - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )
      break
    }

    values.push(inspectValue(entry, depth + 1, opts))
  }

  for (const key in set) {
    if (key === 'constructor') continue

    const value = inspectValue(set[key], depth + 1, opts)

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        value,
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = set.constructor.name + '(' + set.size + ') { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectWeakMap(weakMap, ref, depth, opts) {
  const header = weakMap.constructor.name + ' { '

  return new InspectSequence(
    header,
    ' }',
    ' ',
    [new InspectLeaf('<items unknown>', styles.special, depth + 1, opts)],
    ref,
    depth,
    opts
  )
}

function inspectWeakSet(weakSet, ref, depth, opts) {
  const header = weakSet.constructor.name + ' { '

  return new InspectSequence(
    header,
    ' }',
    ' ',
    [new InspectLeaf('<items unknown>', styles.special, depth + 1, opts)],
    ref,
    depth,
    opts
  )
}

function inspectWeakRef(weakRef, ref, depth, opts) {
  const target = weakRef.deref()

  let value

  if (target === undefined) {
    value = new InspectLeaf('<cleared>', styles.special, depth + 1, opts)
  } else {
    value = inspectValue(target, depth + 1, opts)
  }

  const header = weakRef.constructor.name + ' { '

  return new InspectSequence(header, ' }', ' ', [value], ref, depth, opts)
}

function inspectArrayBuffer(arrayBuffer, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(arrayBuffer[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = arrayBuffer.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectSharedArrayBuffer(sharedArrayBuffer, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(sharedArrayBuffer[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = sharedArrayBuffer.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectTypedArray(typedArray, ref, depth, opts) {
  if (Buffer.isBuffer(typedArray)) {
    return inspectBuffer(typedArray, ref, depth, opts)
  }

  const {
    maxArrayLength = defaultMaxArrayLength,
    maxTypedArrayLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxTypedArrayLength, 0)

  for (let i = 0, n = typedArray.length; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(typedArray.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(inspectValue(typedArray[i], depth + 1, opts))
  }

  for (const key of binding.getOwnNonIndexPropertyNames(typedArray)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(typedArray[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = typedArray.constructor.name + '(' + typedArray.length + ') [ '

  return new InspectSequence(header, ' ]', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectBuffer(buffer, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxBufferLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxBufferLength, 0)

  for (let i = 0, n = buffer.byteLength; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(buffer.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(
      new InspectLeaf(
        buffer[i].toString(16).padStart(2, '0'),
        null,
        depth + 1,
        opts
      )
    )
  }

  for (const key of binding.getOwnNonIndexPropertyNames(buffer)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(buffer[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  return new InspectSequence('<Buffer ', '>', ' ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectDataView(dataView, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength', 'byteOffset', 'buffer']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(dataView[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key of binding.getOwnNonIndexPropertyNames(dataView)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(dataView[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = dataView.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectFunction(type, fn, depth, opts) {
  if (fn.toString().startsWith('class')) return inspectClass(fn, depth, opts)

  let tag = 'function'

  if (type.isGeneratorFunction()) tag = 'generator ' + tag
  if (type.isAsyncFunction()) tag = 'async ' + tag

  return new InspectLeaf(
    '[' + tag + ' ' + (fn.name ? fn.name : '(anonymous)') + ']',
    styles.special,
    depth,
    opts
  )
}

function inspectClass(ctor, depth, opts) {
  return new InspectLeaf(
    '[class ' + (ctor.name ? ctor.name : '(anonymous)') + ']',
    styles.special,
    depth,
    opts
  )
}

function inspectExternal(external, depth, opts) {
  return new InspectLeaf(
    '[external 0x' + binding.getExternal(external).toString(16) + ']',
    styles.special,
    depth,
    opts
  )
}
{
  "name": "bare-inspect",
  "version": "3.1.4",
  "description": "Inspect objects as strings for debugging",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-inspect.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-inspect/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-inspect#readme",
  "engines": {
    "bare": ">=1.18.0"
  },
  "dependencies": {
    "bare-ansi-escapes": "^2.1.0",
    "bare-type": "^1.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
module.exports = require.addon()
const binding = require('./binding')

const t = binding.constants

class Type {
  constructor(type) {
    this._type = type
  }

  isUndefined() {
    return this._type === t.UNDEFINED
  }

  isNull() {
    return this._type === t.NULL
  }

  isBoolean() {
    return this._type === t.BOOLEAN
  }

  isNumber() {
    return (this._type & 0xff) === t.NUMBER
  }

  isInt32() {
    return (this._type & (0xff | t.INT32)) === (t.NUMBER | t.INT32)
  }

  isUint32() {
    return (this._type & (0xff | t.UINT32)) === (t.NUMBER | t.UINT32)
  }

  isString() {
    return this._type === t.STRING
  }

  isSymbol() {
    return this._type === t.SYMBOL
  }

  isObject() {
    return (this._type & 0xff) === t.OBJECT
  }

  isArray() {
    return this._type === (t.OBJECT | t.ARRAY)
  }

  isArguments() {
    return this._type === (t.OBJECT | t.ARGUMENTS)
  }

  isDate() {
    return this._type === (t.OBJECT | t.DATE)
  }

  isRegExp() {
    return this._type === (t.OBJECT | t.REGEXP)
  }

  isError() {
    return this._type === (t.OBJECT | t.ERROR)
  }

  isPromise() {
    return this._type === (t.OBJECT | t.PROMISE)
  }

  isProxy() {
    return this._type === (t.OBJECT | t.PROXY)
  }

  isGenerator() {
    return this._type === (t.OBJECT | t.GENERATOR)
  }

  isMap() {
    return this._type === (t.OBJECT | t.MAP)
  }

  isSet() {
    return this._type === (t.OBJECT | t.SET)
  }

  isWeakMap() {
    return this._type === (t.OBJECT | t.WEAK_MAP)
  }

  isWeakSet() {
    return this._type === (t.OBJECT | t.WEAK_SET)
  }

  isWeakRef() {
    return this._type === (t.OBJECT | t.WEAK_REF)
  }

  isArrayBuffer() {
    return this._type === (t.OBJECT | t.ARRAYBUFFER)
  }

  isSharedArrayBuffer() {
    return this._type === (t.OBJECT | t.SHAREDARRAYBUFFER)
  }

  isTypedArray() {
    return (this._type & 0xffff) === (t.OBJECT | t.TYPEDARRAY)
  }

  isInt8Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT8ARRAY)
  }

  isUint8Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT8ARRAY)
  }

  isUint8ClampedArray() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT8CLAMPEDARRAY)
  }

  isInt16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT16ARRAY)
  }

  isUint16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT16ARRAY)
  }

  isInt32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT32ARRAY)
  }

  isUint32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT32ARRAY)
  }

  isFloat16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT16ARRAY)
  }

  isFloat32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT32ARRAY)
  }

  isFloat64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT64ARRAY)
  }

  isBigInt64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.BIGINT64ARRAY)
  }

  isBigUint64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.BIGUINT64ARRAY)
  }

  isDataView() {
    return this._type === (t.OBJECT | t.DATAVIEW)
  }

  isModuleNamespace() {
    return this._type === (t.OBJECT | t.MODULE_NAMESPACE)
  }

  isFunction() {
    return (this._type & 0xff) === t.FUNCTION
  }

  isAsyncFunction() {
    return (
      (this._type & (0xff | t.ASYNC_FUNCTION)) ===
      (t.FUNCTION | t.ASYNC_FUNCTION)
    )
  }

  isGeneratorFunction() {
    return (
      (this._type & (0xff | t.GENERATOR_FUNCTION)) ===
      (t.FUNCTION | t.GENERATOR_FUNCTION)
    )
  }

  isExternal() {
    return this._type === t.EXTERNAL
  }

  isBigInt() {
    return this._type === t.BIGINT
  }
}

module.exports = exports = function type(value) {
  switch (typeof value) {
    case 'undefined':
      return new Type(t.UNDEFINED)
    case 'boolean':
      return new Type(t.BOOLEAN)
    case 'number':
      return new Type(
        Number.isSafeInteger(value) ? binding.type(value) : t.NUMBER
      )
    case 'string':
      return new Type(t.STRING)
    case 'symbol':
      return new Type(t.SYMBOL)
    case 'object':
      return new Type(value === null ? t.NULL : binding.type(value))
    case 'function':
      return new Type(binding.type(value))
    case 'bigint':
      return new Type(t.BIGINT)
  }
}

exports.createTag = function createTag(...components) {
  const tag = new Uint32Array(4)
  for (let i = 0; i < 4; i++) tag[i] = components[i] || 0
  return tag
}

exports.addTag = function addTag(object, tag) {
  binding.addTag(object, tag)
}

exports.checkTag = function checkTag(object, tag) {
  return binding.checkTag(object, tag)
}
{
  "name": "bare-type",
  "version": "1.1.0",
  "description": "Cross-realm type predicates for Bare",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-type.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-type/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-type#readme",
  "engines": {
    "bare": ">=1.2.0"
  },
  "devDependencies": {
    "brittle": "^3.4.0",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
const sodium = require('sodium-universal')
const b4a = require('b4a')
const assert = require('nanoassert')
const { detectLanguage, loadWordlist } = require('./wordlist')

module.exports = {
  generateEntropy,
  generateMnemonic,
  normalizeMnemonic,
  validateMnemonic,
  mnemonicToEntropy,
  mnemonicToSeed,
  entropyToMnemonic
}

function generateMnemonic ({ entropy = generateEntropy(), language = 'english' } = {}) {
  const wordlist = loadWordlist(language)
  const extended = computeCheckSum(entropy)

  const words = []

  for (const index of uint11Reader(extended)) {
    words.push(wordlist[index])
  }

  const delimiter = language === 'japanese' ? '\u3000' : ' '

  return words.join(delimiter).trim()
}

function entropyToMnemonic (entropy, { language = 'english' } = {}) {
  return generateMnemonic({ entropy, language })
}

function mnemonicToEntropy (mnemonic) {
  const words = mnemonic.replace(/\u3000/g, ' ').trim().split(' ')
  const language = detectLanguage(words)

  if (!language) {
    throw new Error('Language not recognised')
  }

  if (words.length % 3 !== 0) {
    throw new Error('Invalid length')
  }

  const wordlist = loadWordlist(language)

  const indexes = []
  for (const word of words) {
    const index = wordlist.indexOf(word)
    if (index === -1) {
      throw new Error('Bad word')
    }

    indexes.push(index)
  }

  const bits = words.length * 11
  const len = (bits * 32 / 33) >> 3

  const extended = b4a.alloc(Math.ceil(bits / 8))
  const entropy = extended.subarray(0, len)

  uint11Writer(extended, indexes)

  if (!b4a.equals(extended, computeCheckSum(entropy))) {
    throw new Error('Invalid checksum')
  }

  return entropy
}

function normalizeMnemonic (mnemonic) {
  return mnemonic.trim().replace(/\u3000/, ' ').split(/\s+/).map(c => c.toLowerCase()).join(' ')
}

async function mnemonicToSeed (mnemonic, passphrase = '') {
  mnemonic = normalizeMnemonic(mnemonic)

  if (!validateMnemonic(mnemonic)) {
    throw new Error('Invalid mnemonic')
  }

  const input = b4a.from(mnemonic)
  const salt = b4a.from('mnemonic' + passphrase)

  const output = b4a.alloc(64)

  await sodium.extension_pbkdf2_sha512_async(
    output,
    input,
    salt,
    2048,
    64
  )

  return output
}

function validateMnemonic (mnemonic) {
  try {
    mnemonicToEntropy(mnemonic)
  } catch (e) {
    return false
  }
  return true
}

function sha256 (data, output = b4a.alloc(32)) {
  sodium.crypto_hash_sha256(output, data)
  return output
}

function computeCheckSum (seed) {
  assert((seed.byteLength & 4) === 0, 'seed must be a multiple of 4 bytes')

  const len = seed.byteLength
  const cklen = len >> 2 // cksum bits
  const total = len + Math.ceil(cklen / 8)

  const output = b4a.alloc(len + 32)
  output.set(seed)

  const entropy = output.subarray(0, len)
  const cksum = output.subarray(len)

  sha256(entropy, cksum)

  // only append cklen bits
  output[total - 1] &= (0xff ^ (0xff >> cklen))

  return output.subarray(0, total)
}

function generateEntropy (length = 32) {
  const seed = b4a.alloc(length)
  sodium.randombytes_buf(seed)

  return seed
}

function * uint11Reader (state) {
  yield * uintReader(state, 11)
}

function uint11Writer (buf, uints) {
  return uintWriter(buf, uints, 11)
}

function * uintReader (buffer, width) {
  const MASK = (2 << (width - 1)) - 1

  let pos = 0
  let value = 0

  while (true) {
    const offset = pos >> 3 // byte offset

    if (offset >= buffer.byteLength) {
      return value & MASK
    }

    const height = width - (pos % width)
    const leftover = (offset + 1) * 8 - pos

    value += shift(buffer[offset], height - leftover)

    pos += Math.min(height, leftover)
    if (pos % width) continue

    yield value & MASK

    value = 0
  }
}

function uintWriter (buffer, uints, width) {
  let pos = 0

  while (true) {
    const offset = pos >> 3 // byte offset

    const i = Math.floor(pos / width)
    if (i >= uints.length) break

    if (offset >= buffer.length) {
      throw new Error('Failed to encode uints')
    }

    const rem = 8 - pos % 8
    const height = (i + 1) * width - pos

    const value = shift(uints[i], rem - height)

    buffer[offset] += mask(value, rem)

    pos += Math.min(rem, height)
  }

  return buffer
}

// when n is positive, shift left n bits
// when n is negative, shift right -n bits
function shift (val, n) {
  if (n === 0) return val
  if (n > 0) return val << n

  return val >> (-1 * n)
}

function mask (val, bits) {
  if (bits < 32) return val & ((1 << bits) - 1)
  return val % (2 ** bits)
}
{
  "name": "bip39-mnemonic",
  "version": "2.5.0",
  "description": "BIP39 mnemonic for key derivation schemes",
  "main": "index.js",
  "scripts": {
    "generate-wordlist": "node scripts/generate-wordlist.js",
    "test": "standard && brittle test/*.js"
  },
  "author": "Holepunch Inc",
  "license": "Apache-2.0",
  "devDependencies": {
    "brittle": "^3.4.0",
    "standard": "^17.1.0"
  },
  "dependencies": {
    "b4a": "^1.6.6",
    "nanoassert": "^2.0.0",
    "sodium-universal": "^5.0.1"
  },
  "files": [
    "index.js",
    "wordlist"
  ],
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bip39.git"
  },
  "bugs": {
    "url": "https://github.com/holepunchto/bip39/issues"
  },
  "homepage": "https://github.com/holepunchto/bip39#readme"
}
["的","一","是","在","不","了","有","和","人","这","中","大","为","上","个","国","我","以","要","他","时","来","用","们","生","到","作","地","于","出","就","分","对","成","会","可","主","发","年","动","同","工","也","能","下","过","子","说","产","种","面","而","方","后","多","定","行","学","法","所","民","得","经","十","三","之","进","着","等","部","度","家","电","力","里","如","水","化","高","自","二","理","起","小","物","现","实","加","量","都","两","体","制","机","当","使","点","从","业","本","去","把","性","好","应","开","它","合","还","因","由","其","些","然","前","外","天","政","四","日","那","社","义","事","平","形","相","全","表","间","样","与","关","各","重","新","线","内","数","正","心","反","你","明","看","原","又","么","利","比","或","但","质","气","第","向","道","命","此","变","条","只","没","结","解","问","意","建","月","公","无","系","军","很","情","者","最","立","代","想","已","通","并","提","直","题","党","程","展","五","果","料","象","员","革","位","入","常","文","总","次","品","式","活","设","及","管","特","件","长","求","老","头","基","资","边","流","路","级","少","图","山","统","接","知","较","将","组","见","计","别","她","手","角","期","根","论","运","农","指","几","九","区","强","放","决","西","被","干","做","必","战","先","回","则","任","取","据","处","队","南","给","色","光","门","即","保","治","北","造","百","规","热","领","七","海","口","东","导","器","压","志","世","金","增","争","济","阶","油","思","术","极","交","受","联","什","认","六","共","权","收","证","改","清","美","再","采","转","更","单","风","切","打","白","教","速","花","带","安","场","身","车","例","真","务","具","万","每","目","至","达","走","积","示","议","声","报","斗","完","类","八","离","华","名","确","才","科","张","信","马","节","话","米","整","空","元","况","今","集","温","传","土","许","步","群","广","石","记","需","段","研","界","拉","林","律","叫","且","究","观","越","织","装","影","算","低","持","音","众","书","布","复","容","儿","须","际","商","非","验","连","断","深","难","近","矿","千","周","委","素","技","备","半","办","青","省","列","习","响","约","支","般","史","感","劳","便","团","往","酸","历","市","克","何","除","消","构","府","称","太","准","精","值","号","率","族","维","划","选","标","写","存","候","毛","亲","快","效","斯","院","查","江","型","眼","王","按","格","养","易","置","派","层","片","始","却","专","状","育","厂","京","识","适","属","圆","包","火","住","调","满","县","局","照","参","红","细","引","听","该","铁","价","严","首","底","液","官","德","随","病","苏","失","尔","死","讲","配","女","黄","推","显","谈","罪","神","艺","呢","席","含","企","望","密","批","营","项","防","举","球","英","氧","势","告","李","台","落","木","帮","轮","破","亚","师","围","注","远","字","材","排","供","河","态","封","另","施","减","树","溶","怎","止","案","言","士","均","武","固","叶","鱼","波","视","仅","费","紧","爱","左","章","早","朝","害","续","轻","服","试","食","充","兵","源","判","护","司","足","某","练","差","致","板","田","降","黑","犯","负","击","范","继","兴","似","余","坚","曲","输","修","故","城","夫","够","送","笔","船","占","右","财","吃","富","春","职","觉","汉","画","功","巴","跟","虽","杂","飞","检","吸","助","升","阳","互","初","创","抗","考","投","坏","策","古","径","换","未","跑","留","钢","曾","端","责","站","简","述","钱","副","尽","帝","射","草","冲","承","独","令","限","阿","宣","环","双","请","超","微","让","控","州","良","轴","找","否","纪","益","依","优","顶","础","载","倒","房","突","坐","粉","敌","略","客","袁","冷","胜","绝","析","块","剂","测","丝","协","诉","念","陈","仍","罗","盐","友","洋","错","苦","夜","刑","移","频","逐","靠","混","母","短","皮","终","聚","汽","村","云","哪","既","距","卫","停","烈","央","察","烧","迅","境","若","印","洲","刻","括","激","孔","搞","甚","室","待","核","校","散","侵","吧","甲","游","久","菜","味","旧","模","湖","货","损","预","阻","毫","普","稳","乙","妈","植","息","扩","银","语","挥","酒","守","拿","序","纸","医","缺","雨","吗","针","刘","啊","急","唱","误","训","愿","审","附","获","茶","鲜","粮","斤","孩","脱","硫","肥","善","龙","演","父","渐","血","欢","械","掌","歌","沙","刚","攻","谓","盾","讨","晚","粒","乱","燃","矛","乎","杀","药","宁","鲁","贵","钟","煤","读","班","伯","香","介","迫","句","丰","培","握","兰","担","弦","蛋","沉","假","穿","执","答","乐","谁","顺","烟","缩","征","脸","喜","松","脚","困","异","免","背","星","福","买","染","井","概","慢","怕","磁","倍","祖","皇","促","静","补","评","翻","肉","践","尼","衣","宽","扬","棉","希","伤","操","垂","秋","宜","氢","套","督","振","架","亮","末","宪","庆","编","牛","触","映","雷","销","诗","座","居","抓","裂","胞","呼","娘","景","威","绿","晶","厚","盟","衡","鸡","孙","延","危","胶","屋","乡","临","陆","顾","掉","呀","灯","岁","措","束","耐","剧","玉","赵","跳","哥","季","课","凯","胡","额","款","绍","卷","齐","伟","蒸","殖","永","宗","苗","川","炉","岩","弱","零","杨","奏","沿","露","杆","探","滑","镇","饭","浓","航","怀","赶","库","夺","伊","灵","税","途","灭","赛","归","召","鼓","播","盘","裁","险","康","唯","录","菌","纯","借","糖","盖","横","符","私","努","堂","域","枪","润","幅","哈","竟","熟","虫","泽","脑","壤","碳","欧","遍","侧","寨","敢","彻","虑","斜","薄","庭","纳","弹","饲","伸","折","麦","湿","暗","荷","瓦","塞","床","筑","恶","户","访","塔","奇","透","梁","刀","旋","迹","卡","氯","遇","份","毒","泥","退","洗","摆","灰","彩","卖","耗","夏","择","忙","铜","献","硬","予","繁","圈","雪","函","亦","抽","篇","阵","阴","丁","尺","追","堆","雄","迎","泛","爸","楼","避","谋","吨","野","猪","旗","累","偏","典","馆","索","秦","脂","潮","爷","豆","忽","托","惊","塑","遗","愈","朱","替","纤","粗","倾","尚","痛","楚","谢","奋","购","磨","君","池","旁","碎","骨","监","捕","弟","暴","割","贯","殊","释","词","亡","壁","顿","宝","午","尘","闻","揭","炮","残","冬","桥","妇","警","综","招","吴","付","浮","遭","徐","您","摇","谷","赞","箱","隔","订","男","吹","园","纷","唐","败","宋","玻","巨","耕","坦","荣","闭","湾","键","凡","驻","锅","救","恩","剥","凝","碱","齿","截","炼","麻","纺","禁","废","盛","版","缓","净","睛","昌","婚","涉","筒","嘴","插","岸","朗","庄","街","藏","姑","贸","腐","奴","啦","惯","乘","伙","恢","匀","纱","扎","辩","耳","彪","臣","亿","璃","抵","脉","秀","萨","俄","网","舞","店","喷","纵","寸","汗","挂","洪","贺","闪","柬","爆","烯","津","稻","墙","软","勇","像","滚","厘","蒙","芳","肯","坡","柱","荡","腿","仪","旅","尾","轧","冰","贡","登","黎","削","钻","勒","逃","障","氨","郭","峰","币","港","伏","轨","亩","毕","擦","莫","刺","浪","秘","援","株","健","售","股","岛","甘","泡","睡","童","铸","汤","阀","休","汇","舍","牧","绕","炸","哲","磷","绩","朋","淡","尖","启","陷","柴","呈","徒","颜","泪","稍","忘","泵","蓝","拖","洞","授","镜","辛","壮","锋","贫","虚","弯","摩","泰","幼","廷","尊","窗","纲","弄","隶","疑","氏","宫","姐","震","瑞","怪","尤","琴","循","描","膜","违","夹","腰","缘","珠","穷","森","枝","竹","沟","催","绳","忆","邦","剩","幸","浆","栏","拥","牙","贮","礼","滤","钠","纹","罢","拍","咱","喊","袖","埃","勤","罚","焦","潜","伍","墨","欲","缝","姓","刊","饱","仿","奖","铝","鬼","丽","跨","默","挖","链","扫","喝","袋","炭","污","幕","诸","弧","励","梅","奶","洁","灾","舟","鉴","苯","讼","抱","毁","懂","寒","智","埔","寄","届","跃","渡","挑","丹","艰","贝","碰","拔","爹","戴","码","梦","芽","熔","赤","渔","哭","敬","颗","奔","铅","仲","虎","稀","妹","乏","珍","申","桌","遵","允","隆","螺","仓","魏","锐","晓","氮","兼","隐","碍","赫","拨","忠","肃","缸","牵","抢","博","巧","壳","兄","杜","讯","诚","碧","祥","柯","页","巡","矩","悲","灌","龄","伦","票","寻","桂","铺","圣","恐","恰","郑","趣","抬","荒","腾","贴","柔","滴","猛","阔","辆","妻","填","撤","储","签","闹","扰","紫","砂","递","戏","吊","陶","伐","喂","疗","瓶","婆","抚","臂","摸","忍","虾","蜡","邻","胸","巩","挤","偶","弃","槽","劲","乳","邓","吉","仁","烂","砖","租","乌","舰","伴","瓜","浅","丙","暂","燥","橡","柳","迷","暖","牌","秧","胆","详","簧","踏","瓷","谱","呆","宾","糊","洛","辉","愤","竞","隙","怒","粘","乃","绪","肩","籍","敏","涂","熙","皆","侦","悬","掘","享","纠","醒","狂","锁","淀","恨","牲","霸","爬","赏","逆","玩","陵","祝","秒","浙","貌","役","彼","悉","鸭","趋","凤","晨","畜","辈","秩","卵","署","梯","炎","滩","棋","驱","筛","峡","冒","啥","寿","译","浸","泉","帽","迟","硅","疆","贷","漏","稿","冠","嫩","胁","芯","牢","叛","蚀","奥","鸣","岭","羊","凭","串","塘","绘","酵","融","盆","锡","庙","筹","冻","辅","摄","袭","筋","拒","僚","旱","钾","鸟","漆","沈","眉","疏","添","棒","穗","硝","韩","逼","扭","侨","凉","挺","碗","栽","炒","杯","患","馏","劝","豪","辽","勃","鸿","旦","吏","拜","狗","埋","辊","掩","饮","搬","骂","辞","勾","扣","估","蒋","绒","雾","丈","朵","姆","拟","宇","辑","陕","雕","偿","蓄","崇","剪","倡","厅","咬","驶","薯","刷","斥","番","赋","奉","佛","浇","漫","曼","扇","钙","桃","扶","仔","返","俗","亏","腔","鞋","棱","覆","框","悄","叔","撞","骗","勘","旺","沸","孤","吐","孟","渠","屈","疾","妙","惜","仰","狠","胀","谐","抛","霉","桑","岗","嘛","衰","盗","渗","脏","赖","涌","甜","曹","阅","肌","哩","厉","烃","纬","毅","昨","伪","症","煮","叹","钉","搭","茎","笼","酷","偷","弓","锥","恒","杰","坑","鼻","翼","纶","叙","狱","逮","罐","络","棚","抑","膨","蔬","寺","骤","穆","冶","枯","册","尸","凸","绅","坯","牺","焰","轰","欣","晋","瘦","御","锭","锦","丧","旬","锻","垄","搜","扑","邀","亭","酯","迈","舒","脆","酶","闲","忧","酚","顽","羽","涨","卸","仗","陪","辟","惩","杭","姚","肚","捉","飘","漂","昆","欺","吾","郎","烷","汁","呵","饰","萧","雅","邮","迁","燕","撒","姻","赴","宴","烦","债","帐","斑","铃","旨","醇","董","饼","雏","姿","拌","傅","腹","妥","揉","贤","拆","歪","葡","胺","丢","浩","徽","昂","垫","挡","览","贪","慰","缴","汪","慌","冯","诺","姜","谊","凶","劣","诬","耀","昏","躺","盈","骑","乔","溪","丛","卢","抹","闷","咨","刮","驾","缆","悟","摘","铒","掷","颇","幻","柄","惠","惨","佳","仇","腊","窝","涤","剑","瞧","堡","泼","葱","罩","霍","捞","胎","苍","滨","俩","捅","湘","砍","霞","邵","萄","疯","淮","遂","熊","粪","烘","宿","档","戈","驳","嫂","裕","徙","箭","捐","肠","撑","晒","辨","殿","莲","摊","搅","酱","屏","疫","哀","蔡","堵","沫","皱","畅","叠","阁","莱","敲","辖","钩","痕","坝","巷","饿","祸","丘","玄","溜","曰","逻","彭","尝","卿","妨","艇","吞","韦","怨","矮","歇"]["的","一","是","在","不","了","有","和","人","這","中","大","為","上","個","國","我","以","要","他","時","來","用","們","生","到","作","地","於","出","就","分","對","成","會","可","主","發","年","動","同","工","也","能","下","過","子","說","產","種","面","而","方","後","多","定","行","學","法","所","民","得","經","十","三","之","進","著","等","部","度","家","電","力","裡","如","水","化","高","自","二","理","起","小","物","現","實","加","量","都","兩","體","制","機","當","使","點","從","業","本","去","把","性","好","應","開","它","合","還","因","由","其","些","然","前","外","天","政","四","日","那","社","義","事","平","形","相","全","表","間","樣","與","關","各","重","新","線","內","數","正","心","反","你","明","看","原","又","麼","利","比","或","但","質","氣","第","向","道","命","此","變","條","只","沒","結","解","問","意","建","月","公","無","系","軍","很","情","者","最","立","代","想","已","通","並","提","直","題","黨","程","展","五","果","料","象","員","革","位","入","常","文","總","次","品","式","活","設","及","管","特","件","長","求","老","頭","基","資","邊","流","路","級","少","圖","山","統","接","知","較","將","組","見","計","別","她","手","角","期","根","論","運","農","指","幾","九","區","強","放","決","西","被","幹","做","必","戰","先","回","則","任","取","據","處","隊","南","給","色","光","門","即","保","治","北","造","百","規","熱","領","七","海","口","東","導","器","壓","志","世","金","增","爭","濟","階","油","思","術","極","交","受","聯","什","認","六","共","權","收","證","改","清","美","再","採","轉","更","單","風","切","打","白","教","速","花","帶","安","場","身","車","例","真","務","具","萬","每","目","至","達","走","積","示","議","聲","報","鬥","完","類","八","離","華","名","確","才","科","張","信","馬","節","話","米","整","空","元","況","今","集","溫","傳","土","許","步","群","廣","石","記","需","段","研","界","拉","林","律","叫","且","究","觀","越","織","裝","影","算","低","持","音","眾","書","布","复","容","兒","須","際","商","非","驗","連","斷","深","難","近","礦","千","週","委","素","技","備","半","辦","青","省","列","習","響","約","支","般","史","感","勞","便","團","往","酸","歷","市","克","何","除","消","構","府","稱","太","準","精","值","號","率","族","維","劃","選","標","寫","存","候","毛","親","快","效","斯","院","查","江","型","眼","王","按","格","養","易","置","派","層","片","始","卻","專","狀","育","廠","京","識","適","屬","圓","包","火","住","調","滿","縣","局","照","參","紅","細","引","聽","該","鐵","價","嚴","首","底","液","官","德","隨","病","蘇","失","爾","死","講","配","女","黃","推","顯","談","罪","神","藝","呢","席","含","企","望","密","批","營","項","防","舉","球","英","氧","勢","告","李","台","落","木","幫","輪","破","亞","師","圍","注","遠","字","材","排","供","河","態","封","另","施","減","樹","溶","怎","止","案","言","士","均","武","固","葉","魚","波","視","僅","費","緊","愛","左","章","早","朝","害","續","輕","服","試","食","充","兵","源","判","護","司","足","某","練","差","致","板","田","降","黑","犯","負","擊","范","繼","興","似","餘","堅","曲","輸","修","故","城","夫","夠","送","筆","船","佔","右","財","吃","富","春","職","覺","漢","畫","功","巴","跟","雖","雜","飛","檢","吸","助","昇","陽","互","初","創","抗","考","投","壞","策","古","徑","換","未","跑","留","鋼","曾","端","責","站","簡","述","錢","副","盡","帝","射","草","衝","承","獨","令","限","阿","宣","環","雙","請","超","微","讓","控","州","良","軸","找","否","紀","益","依","優","頂","礎","載","倒","房","突","坐","粉","敵","略","客","袁","冷","勝","絕","析","塊","劑","測","絲","協","訴","念","陳","仍","羅","鹽","友","洋","錯","苦","夜","刑","移","頻","逐","靠","混","母","短","皮","終","聚","汽","村","雲","哪","既","距","衛","停","烈","央","察","燒","迅","境","若","印","洲","刻","括","激","孔","搞","甚","室","待","核","校","散","侵","吧","甲","遊","久","菜","味","舊","模","湖","貨","損","預","阻","毫","普","穩","乙","媽","植","息","擴","銀","語","揮","酒","守","拿","序","紙","醫","缺","雨","嗎","針","劉","啊","急","唱","誤","訓","願","審","附","獲","茶","鮮","糧","斤","孩","脫","硫","肥","善","龍","演","父","漸","血","歡","械","掌","歌","沙","剛","攻","謂","盾","討","晚","粒","亂","燃","矛","乎","殺","藥","寧","魯","貴","鐘","煤","讀","班","伯","香","介","迫","句","豐","培","握","蘭","擔","弦","蛋","沉","假","穿","執","答","樂","誰","順","煙","縮","徵","臉","喜","松","腳","困","異","免","背","星","福","買","染","井","概","慢","怕","磁","倍","祖","皇","促","靜","補","評","翻","肉","踐","尼","衣","寬","揚","棉","希","傷","操","垂","秋","宜","氫","套","督","振","架","亮","末","憲","慶","編","牛","觸","映","雷","銷","詩","座","居","抓","裂","胞","呼","娘","景","威","綠","晶","厚","盟","衡","雞","孫","延","危","膠","屋","鄉","臨","陸","顧","掉","呀","燈","歲","措","束","耐","劇","玉","趙","跳","哥","季","課","凱","胡","額","款","紹","卷","齊","偉","蒸","殖","永","宗","苗","川","爐","岩","弱","零","楊","奏","沿","露","桿","探","滑","鎮","飯","濃","航","懷","趕","庫","奪","伊","靈","稅","途","滅","賽","歸","召","鼓","播","盤","裁","險","康","唯","錄","菌","純","借","糖","蓋","橫","符","私","努","堂","域","槍","潤","幅","哈","竟","熟","蟲","澤","腦","壤","碳","歐","遍","側","寨","敢","徹","慮","斜","薄","庭","納","彈","飼","伸","折","麥","濕","暗","荷","瓦","塞","床","築","惡","戶","訪","塔","奇","透","梁","刀","旋","跡","卡","氯","遇","份","毒","泥","退","洗","擺","灰","彩","賣","耗","夏","擇","忙","銅","獻","硬","予","繁","圈","雪","函","亦","抽","篇","陣","陰","丁","尺","追","堆","雄","迎","泛","爸","樓","避","謀","噸","野","豬","旗","累","偏","典","館","索","秦","脂","潮","爺","豆","忽","托","驚","塑","遺","愈","朱","替","纖","粗","傾","尚","痛","楚","謝","奮","購","磨","君","池","旁","碎","骨","監","捕","弟","暴","割","貫","殊","釋","詞","亡","壁","頓","寶","午","塵","聞","揭","炮","殘","冬","橋","婦","警","綜","招","吳","付","浮","遭","徐","您","搖","谷","贊","箱","隔","訂","男","吹","園","紛","唐","敗","宋","玻","巨","耕","坦","榮","閉","灣","鍵","凡","駐","鍋","救","恩","剝","凝","鹼","齒","截","煉","麻","紡","禁","廢","盛","版","緩","淨","睛","昌","婚","涉","筒","嘴","插","岸","朗","莊","街","藏","姑","貿","腐","奴","啦","慣","乘","夥","恢","勻","紗","扎","辯","耳","彪","臣","億","璃","抵","脈","秀","薩","俄","網","舞","店","噴","縱","寸","汗","掛","洪","賀","閃","柬","爆","烯","津","稻","牆","軟","勇","像","滾","厘","蒙","芳","肯","坡","柱","盪","腿","儀","旅","尾","軋","冰","貢","登","黎","削","鑽","勒","逃","障","氨","郭","峰","幣","港","伏","軌","畝","畢","擦","莫","刺","浪","秘","援","株","健","售","股","島","甘","泡","睡","童","鑄","湯","閥","休","匯","舍","牧","繞","炸","哲","磷","績","朋","淡","尖","啟","陷","柴","呈","徒","顏","淚","稍","忘","泵","藍","拖","洞","授","鏡","辛","壯","鋒","貧","虛","彎","摩","泰","幼","廷","尊","窗","綱","弄","隸","疑","氏","宮","姐","震","瑞","怪","尤","琴","循","描","膜","違","夾","腰","緣","珠","窮","森","枝","竹","溝","催","繩","憶","邦","剩","幸","漿","欄","擁","牙","貯","禮","濾","鈉","紋","罷","拍","咱","喊","袖","埃","勤","罰","焦","潛","伍","墨","欲","縫","姓","刊","飽","仿","獎","鋁","鬼","麗","跨","默","挖","鏈","掃","喝","袋","炭","污","幕","諸","弧","勵","梅","奶","潔","災","舟","鑑","苯","訟","抱","毀","懂","寒","智","埔","寄","屆","躍","渡","挑","丹","艱","貝","碰","拔","爹","戴","碼","夢","芽","熔","赤","漁","哭","敬","顆","奔","鉛","仲","虎","稀","妹","乏","珍","申","桌","遵","允","隆","螺","倉","魏","銳","曉","氮","兼","隱","礙","赫","撥","忠","肅","缸","牽","搶","博","巧","殼","兄","杜","訊","誠","碧","祥","柯","頁","巡","矩","悲","灌","齡","倫","票","尋","桂","鋪","聖","恐","恰","鄭","趣","抬","荒","騰","貼","柔","滴","猛","闊","輛","妻","填","撤","儲","簽","鬧","擾","紫","砂","遞","戲","吊","陶","伐","餵","療","瓶","婆","撫","臂","摸","忍","蝦","蠟","鄰","胸","鞏","擠","偶","棄","槽","勁","乳","鄧","吉","仁","爛","磚","租","烏","艦","伴","瓜","淺","丙","暫","燥","橡","柳","迷","暖","牌","秧","膽","詳","簧","踏","瓷","譜","呆","賓","糊","洛","輝","憤","競","隙","怒","粘","乃","緒","肩","籍","敏","塗","熙","皆","偵","懸","掘","享","糾","醒","狂","鎖","淀","恨","牲","霸","爬","賞","逆","玩","陵","祝","秒","浙","貌","役","彼","悉","鴨","趨","鳳","晨","畜","輩","秩","卵","署","梯","炎","灘","棋","驅","篩","峽","冒","啥","壽","譯","浸","泉","帽","遲","矽","疆","貸","漏","稿","冠","嫩","脅","芯","牢","叛","蝕","奧","鳴","嶺","羊","憑","串","塘","繪","酵","融","盆","錫","廟","籌","凍","輔","攝","襲","筋","拒","僚","旱","鉀","鳥","漆","沈","眉","疏","添","棒","穗","硝","韓","逼","扭","僑","涼","挺","碗","栽","炒","杯","患","餾","勸","豪","遼","勃","鴻","旦","吏","拜","狗","埋","輥","掩","飲","搬","罵","辭","勾","扣","估","蔣","絨","霧","丈","朵","姆","擬","宇","輯","陝","雕","償","蓄","崇","剪","倡","廳","咬","駛","薯","刷","斥","番","賦","奉","佛","澆","漫","曼","扇","鈣","桃","扶","仔","返","俗","虧","腔","鞋","棱","覆","框","悄","叔","撞","騙","勘","旺","沸","孤","吐","孟","渠","屈","疾","妙","惜","仰","狠","脹","諧","拋","黴","桑","崗","嘛","衰","盜","滲","臟","賴","湧","甜","曹","閱","肌","哩","厲","烴","緯","毅","昨","偽","症","煮","嘆","釘","搭","莖","籠","酷","偷","弓","錐","恆","傑","坑","鼻","翼","綸","敘","獄","逮","罐","絡","棚","抑","膨","蔬","寺","驟","穆","冶","枯","冊","屍","凸","紳","坯","犧","焰","轟","欣","晉","瘦","禦","錠","錦","喪","旬","鍛","壟","搜","撲","邀","亭","酯","邁","舒","脆","酶","閒","憂","酚","頑","羽","漲","卸","仗","陪","闢","懲","杭","姚","肚","捉","飄","漂","昆","欺","吾","郎","烷","汁","呵","飾","蕭","雅","郵","遷","燕","撒","姻","赴","宴","煩","債","帳","斑","鈴","旨","醇","董","餅","雛","姿","拌","傅","腹","妥","揉","賢","拆","歪","葡","胺","丟","浩","徽","昂","墊","擋","覽","貪","慰","繳","汪","慌","馮","諾","姜","誼","兇","劣","誣","耀","昏","躺","盈","騎","喬","溪","叢","盧","抹","悶","諮","刮","駕","纜","悟","摘","鉺","擲","頗","幻","柄","惠","慘","佳","仇","臘","窩","滌","劍","瞧","堡","潑","蔥","罩","霍","撈","胎","蒼","濱","倆","捅","湘","砍","霞","邵","萄","瘋","淮","遂","熊","糞","烘","宿","檔","戈","駁","嫂","裕","徙","箭","捐","腸","撐","曬","辨","殿","蓮","攤","攪","醬","屏","疫","哀","蔡","堵","沫","皺","暢","疊","閣","萊","敲","轄","鉤","痕","壩","巷","餓","禍","丘","玄","溜","曰","邏","彭","嘗","卿","妨","艇","吞","韋","怨","矮","歇"]["abdikace","abeceda","adresa","agrese","akce","aktovka","alej","alkohol","amputace","ananas","andulka","anekdota","anketa","antika","anulovat","archa","arogance","asfalt","asistent","aspirace","astma","astronom","atlas","atletika","atol","autobus","azyl","babka","bachor","bacil","baculka","badatel","bageta","bagr","bahno","bakterie","balada","baletka","balkon","balonek","balvan","balza","bambus","bankomat","barbar","baret","barman","baroko","barva","baterka","batoh","bavlna","bazalka","bazilika","bazuka","bedna","beran","beseda","bestie","beton","bezinka","bezmoc","beztak","bicykl","bidlo","biftek","bikiny","bilance","biograf","biolog","bitva","bizon","blahobyt","blatouch","blecha","bledule","blesk","blikat","blizna","blokovat","bloudit","blud","bobek","bobr","bodlina","bodnout","bohatost","bojkot","bojovat","bokorys","bolest","borec","borovice","bota","boubel","bouchat","bouda","boule","bourat","boxer","bradavka","brambora","branka","bratr","brepta","briketa","brko","brloh","bronz","broskev","brunetka","brusinka","brzda","brzy","bublina","bubnovat","buchta","buditel","budka","budova","bufet","bujarost","bukvice","buldok","bulva","bunda","bunkr","burza","butik","buvol","buzola","bydlet","bylina","bytovka","bzukot","capart","carevna","cedr","cedule","cejch","cejn","cela","celer","celkem","celnice","cenina","cennost","cenovka","centrum","cenzor","cestopis","cetka","chalupa","chapadlo","charita","chata","chechtat","chemie","chichot","chirurg","chlad","chleba","chlubit","chmel","chmura","chobot","chochol","chodba","cholera","chomout","chopit","choroba","chov","chrapot","chrlit","chrt","chrup","chtivost","chudina","chutnat","chvat","chvilka","chvost","chyba","chystat","chytit","cibule","cigareta","cihelna","cihla","cinkot","cirkus","cisterna","citace","citrus","cizinec","cizost","clona","cokoliv","couvat","ctitel","ctnost","cudnost","cuketa","cukr","cupot","cvaknout","cval","cvik","cvrkot","cyklista","daleko","dareba","datel","datum","dcera","debata","dechovka","decibel","deficit","deflace","dekl","dekret","demokrat","deprese","derby","deska","detektiv","dikobraz","diktovat","dioda","diplom","disk","displej","divadlo","divoch","dlaha","dlouho","dluhopis","dnes","dobro","dobytek","docent","dochutit","dodnes","dohled","dohoda","dohra","dojem","dojnice","doklad","dokola","doktor","dokument","dolar","doleva","dolina","doma","dominant","domluvit","domov","donutit","dopad","dopis","doplnit","doposud","doprovod","dopustit","dorazit","dorost","dort","dosah","doslov","dostatek","dosud","dosyta","dotaz","dotek","dotknout","doufat","doutnat","dovozce","dozadu","doznat","dozorce","drahota","drak","dramatik","dravec","draze","drdol","drobnost","drogerie","drozd","drsnost","drtit","drzost","duben","duchovno","dudek","duha","duhovka","dusit","dusno","dutost","dvojice","dvorec","dynamit","ekolog","ekonomie","elektron","elipsa","email","emise","emoce","empatie","epizoda","epocha","epopej","epos","esej","esence","eskorta","eskymo","etiketa","euforie","evoluce","exekuce","exkurze","expedice","exploze","export","extrakt","facka","fajfka","fakulta","fanatik","fantazie","farmacie","favorit","fazole","federace","fejeton","fenka","fialka","figurant","filozof","filtr","finance","finta","fixace","fjord","flanel","flirt","flotila","fond","fosfor","fotbal","fotka","foton","frakce","freska","fronta","fukar","funkce","fyzika","galeje","garant","genetika","geolog","gilotina","glazura","glejt","golem","golfista","gotika","graf","gramofon","granule","grep","gril","grog","groteska","guma","hadice","hadr","hala","halenka","hanba","hanopis","harfa","harpuna","havran","hebkost","hejkal","hejno","hejtman","hektar","helma","hematom","herec","herna","heslo","hezky","historik","hladovka","hlasivky","hlava","hledat","hlen","hlodavec","hloh","hloupost","hltat","hlubina","hluchota","hmat","hmota","hmyz","hnis","hnojivo","hnout","hoblina","hoboj","hoch","hodiny","hodlat","hodnota","hodovat","hojnost","hokej","holinka","holka","holub","homole","honitba","honorace","horal","horda","horizont","horko","horlivec","hormon","hornina","horoskop","horstvo","hospoda","hostina","hotovost","houba","houf","houpat","houska","hovor","hradba","hranice","hravost","hrazda","hrbolek","hrdina","hrdlo","hrdost","hrnek","hrobka","hromada","hrot","hrouda","hrozen","hrstka","hrubost","hryzat","hubenost","hubnout","hudba","hukot","humr","husita","hustota","hvozd","hybnost","hydrant","hygiena","hymna","hysterik","idylka","ihned","ikona","iluze","imunita","infekce","inflace","inkaso","inovace","inspekce","internet","invalida","investor","inzerce","ironie","jablko","jachta","jahoda","jakmile","jakost","jalovec","jantar","jarmark","jaro","jasan","jasno","jatka","javor","jazyk","jedinec","jedle","jednatel","jehlan","jekot","jelen","jelito","jemnost","jenom","jepice","jeseter","jevit","jezdec","jezero","jinak","jindy","jinoch","jiskra","jistota","jitrnice","jizva","jmenovat","jogurt","jurta","kabaret","kabel","kabinet","kachna","kadet","kadidlo","kahan","kajak","kajuta","kakao","kaktus","kalamita","kalhoty","kalibr","kalnost","kamera","kamkoliv","kamna","kanibal","kanoe","kantor","kapalina","kapela","kapitola","kapka","kaple","kapota","kapr","kapusta","kapybara","karamel","karotka","karton","kasa","katalog","katedra","kauce","kauza","kavalec","kazajka","kazeta","kazivost","kdekoliv","kdesi","kedluben","kemp","keramika","kino","klacek","kladivo","klam","klapot","klasika","klaun","klec","klenba","klepat","klesnout","klid","klima","klisna","klobouk","klokan","klopa","kloub","klubovna","klusat","kluzkost","kmen","kmitat","kmotr","kniha","knot","koalice","koberec","kobka","kobliha","kobyla","kocour","kohout","kojenec","kokos","koktejl","kolaps","koleda","kolize","kolo","komando","kometa","komik","komnata","komora","kompas","komunita","konat","koncept","kondice","konec","konfese","kongres","konina","konkurs","kontakt","konzerva","kopanec","kopie","kopnout","koprovka","korbel","korektor","kormidlo","koroptev","korpus","koruna","koryto","korzet","kosatec","kostka","kotel","kotleta","kotoul","koukat","koupelna","kousek","kouzlo","kovboj","koza","kozoroh","krabice","krach","krajina","kralovat","krasopis","kravata","kredit","krejcar","kresba","kreveta","kriket","kritik","krize","krkavec","krmelec","krmivo","krocan","krok","kronika","kropit","kroupa","krovka","krtek","kruhadlo","krupice","krutost","krvinka","krychle","krypta","krystal","kryt","kudlanka","kufr","kujnost","kukla","kulajda","kulich","kulka","kulomet","kultura","kuna","kupodivu","kurt","kurzor","kutil","kvalita","kvasinka","kvestor","kynolog","kyselina","kytara","kytice","kytka","kytovec","kyvadlo","labrador","lachtan","ladnost","laik","lakomec","lamela","lampa","lanovka","lasice","laso","lastura","latinka","lavina","lebka","leckdy","leden","lednice","ledovka","ledvina","legenda","legie","legrace","lehce","lehkost","lehnout","lektvar","lenochod","lentilka","lepenka","lepidlo","letadlo","letec","letmo","letokruh","levhart","levitace","levobok","libra","lichotka","lidojed","lidskost","lihovina","lijavec","lilek","limetka","linie","linka","linoleum","listopad","litina","litovat","lobista","lodivod","logika","logoped","lokalita","loket","lomcovat","lopata","lopuch","lord","losos","lotr","loudal","louh","louka","louskat","lovec","lstivost","lucerna","lucifer","lump","lusk","lustrace","lvice","lyra","lyrika","lysina","madam","madlo","magistr","mahagon","majetek","majitel","majorita","makak","makovice","makrela","malba","malina","malovat","malvice","maminka","mandle","manko","marnost","masakr","maskot","masopust","matice","matrika","maturita","mazanec","mazivo","mazlit","mazurka","mdloba","mechanik","meditace","medovina","melasa","meloun","mentolka","metla","metoda","metr","mezera","migrace","mihnout","mihule","mikina","mikrofon","milenec","milimetr","milost","mimika","mincovna","minibar","minomet","minulost","miska","mistr","mixovat","mladost","mlha","mlhovina","mlok","mlsat","mluvit","mnich","mnohem","mobil","mocnost","modelka","modlitba","mohyla","mokro","molekula","momentka","monarcha","monokl","monstrum","montovat","monzun","mosaz","moskyt","most","motivace","motorka","motyka","moucha","moudrost","mozaika","mozek","mozol","mramor","mravenec","mrkev","mrtvola","mrzet","mrzutost","mstitel","mudrc","muflon","mulat","mumie","munice","muset","mutace","muzeum","muzikant","myslivec","mzda","nabourat","nachytat","nadace","nadbytek","nadhoz","nadobro","nadpis","nahlas","nahnat","nahodile","nahradit","naivita","najednou","najisto","najmout","naklonit","nakonec","nakrmit","nalevo","namazat","namluvit","nanometr","naoko","naopak","naostro","napadat","napevno","naplnit","napnout","naposled","naprosto","narodit","naruby","narychlo","nasadit","nasekat","naslepo","nastat","natolik","navenek","navrch","navzdory","nazvat","nebe","nechat","necky","nedaleko","nedbat","neduh","negace","nehet","nehoda","nejen","nejprve","neklid","nelibost","nemilost","nemoc","neochota","neonka","nepokoj","nerost","nerv","nesmysl","nesoulad","netvor","neuron","nevina","nezvykle","nicota","nijak","nikam","nikdy","nikl","nikterak","nitro","nocleh","nohavice","nominace","nora","norek","nositel","nosnost","nouze","noviny","novota","nozdra","nuda","nudle","nuget","nutit","nutnost","nutrie","nymfa","obal","obarvit","obava","obdiv","obec","obehnat","obejmout","obezita","obhajoba","obilnice","objasnit","objekt","obklopit","oblast","oblek","obliba","obloha","obluda","obnos","obohatit","obojek","obout","obrazec","obrna","obruba","obrys","obsah","obsluha","obstarat","obuv","obvaz","obvinit","obvod","obvykle","obyvatel","obzor","ocas","ocel","ocenit","ochladit","ochota","ochrana","ocitnout","odboj","odbyt","odchod","odcizit","odebrat","odeslat","odevzdat","odezva","odhadce","odhodit","odjet","odjinud","odkaz","odkoupit","odliv","odluka","odmlka","odolnost","odpad","odpis","odplout","odpor","odpustit","odpykat","odrazka","odsoudit","odstup","odsun","odtok","odtud","odvaha","odveta","odvolat","odvracet","odznak","ofina","ofsajd","ohlas","ohnisko","ohrada","ohrozit","ohryzek","okap","okenice","oklika","okno","okouzlit","okovy","okrasa","okres","okrsek","okruh","okupant","okurka","okusit","olejnina","olizovat","omak","omeleta","omezit","omladina","omlouvat","omluva","omyl","onehdy","opakovat","opasek","operace","opice","opilost","opisovat","opora","opozice","opravdu","oproti","orbital","orchestr","orgie","orlice","orloj","ortel","osada","oschnout","osika","osivo","oslava","oslepit","oslnit","oslovit","osnova","osoba","osolit","ospalec","osten","ostraha","ostuda","ostych","osvojit","oteplit","otisk","otop","otrhat","otrlost","otrok","otruby","otvor","ovanout","ovar","oves","ovlivnit","ovoce","oxid","ozdoba","pachatel","pacient","padouch","pahorek","pakt","palanda","palec","palivo","paluba","pamflet","pamlsek","panenka","panika","panna","panovat","panstvo","pantofle","paprika","parketa","parodie","parta","paruka","paryba","paseka","pasivita","pastelka","patent","patrona","pavouk","pazneht","pazourek","pecka","pedagog","pejsek","peklo","peloton","penalta","pendrek","penze","periskop","pero","pestrost","petarda","petice","petrolej","pevnina","pexeso","pianista","piha","pijavice","pikle","piknik","pilina","pilnost","pilulka","pinzeta","pipeta","pisatel","pistole","pitevna","pivnice","pivovar","placenta","plakat","plamen","planeta","plastika","platit","plavidlo","plaz","plech","plemeno","plenta","ples","pletivo","plevel","plivat","plnit","plno","plocha","plodina","plomba","plout","pluk","plyn","pobavit","pobyt","pochod","pocit","poctivec","podat","podcenit","podepsat","podhled","podivit","podklad","podmanit","podnik","podoba","podpora","podraz","podstata","podvod","podzim","poezie","pohanka","pohnutka","pohovor","pohroma","pohyb","pointa","pojistka","pojmout","pokazit","pokles","pokoj","pokrok","pokuta","pokyn","poledne","polibek","polknout","poloha","polynom","pomalu","pominout","pomlka","pomoc","pomsta","pomyslet","ponechat","ponorka","ponurost","popadat","popel","popisek","poplach","poprosit","popsat","popud","poradce","porce","porod","porucha","poryv","posadit","posed","posila","poskok","poslanec","posoudit","pospolu","postava","posudek","posyp","potah","potkan","potlesk","potomek","potrava","potupa","potvora","poukaz","pouto","pouzdro","povaha","povidla","povlak","povoz","povrch","povstat","povyk","povzdech","pozdrav","pozemek","poznatek","pozor","pozvat","pracovat","prahory","praktika","prales","praotec","praporek","prase","pravda","princip","prkno","probudit","procento","prodej","profese","prohra","projekt","prolomit","promile","pronikat","propad","prorok","prosba","proton","proutek","provaz","prskavka","prsten","prudkost","prut","prvek","prvohory","psanec","psovod","pstruh","ptactvo","puberta","puch","pudl","pukavec","puklina","pukrle","pult","pumpa","punc","pupen","pusa","pusinka","pustina","putovat","putyka","pyramida","pysk","pytel","racek","rachot","radiace","radnice","radon","raft","ragby","raketa","rakovina","rameno","rampouch","rande","rarach","rarita","rasovna","rastr","ratolest","razance","razidlo","reagovat","reakce","recept","redaktor","referent","reflex","rejnok","reklama","rekord","rekrut","rektor","reputace","revize","revma","revolver","rezerva","riskovat","riziko","robotika","rodokmen","rohovka","rokle","rokoko","romaneto","ropovod","ropucha","rorejs","rosol","rostlina","rotmistr","rotoped","rotunda","roubenka","roucho","roup","roura","rovina","rovnice","rozbor","rozchod","rozdat","rozeznat","rozhodce","rozinka","rozjezd","rozkaz","rozloha","rozmar","rozpad","rozruch","rozsah","roztok","rozum","rozvod","rubrika","ruchadlo","rukavice","rukopis","ryba","rybolov","rychlost","rydlo","rypadlo","rytina","ryzost","sadista","sahat","sako","samec","samizdat","samota","sanitka","sardinka","sasanka","satelit","sazba","sazenice","sbor","schovat","sebranka","secese","sedadlo","sediment","sedlo","sehnat","sejmout","sekera","sekta","sekunda","sekvoje","semeno","seno","servis","sesadit","seshora","seskok","seslat","sestra","sesuv","sesypat","setba","setina","setkat","setnout","setrvat","sever","seznam","shoda","shrnout","sifon","silnice","sirka","sirotek","sirup","situace","skafandr","skalisko","skanzen","skaut","skeptik","skica","skladba","sklenice","sklo","skluz","skoba","skokan","skoro","skripta","skrz","skupina","skvost","skvrna","slabika","sladidlo","slanina","slast","slavnost","sledovat","slepec","sleva","slezina","slib","slina","sliznice","slon","sloupek","slovo","sluch","sluha","slunce","slupka","slza","smaragd","smetana","smilstvo","smlouva","smog","smrad","smrk","smrtka","smutek","smysl","snad","snaha","snob","sobota","socha","sodovka","sokol","sopka","sotva","souboj","soucit","soudce","souhlas","soulad","soumrak","souprava","soused","soutok","souviset","spalovna","spasitel","spis","splav","spodek","spojenec","spolu","sponzor","spornost","spousta","sprcha","spustit","sranda","sraz","srdce","srna","srnec","srovnat","srpen","srst","srub","stanice","starosta","statika","stavba","stehno","stezka","stodola","stolek","stopa","storno","stoupat","strach","stres","strhnout","strom","struna","studna","stupnice","stvol","styk","subjekt","subtropy","suchar","sudost","sukno","sundat","sunout","surikata","surovina","svah","svalstvo","svetr","svatba","svazek","svisle","svitek","svoboda","svodidlo","svorka","svrab","sykavka","sykot","synek","synovec","sypat","sypkost","syrovost","sysel","sytost","tabletka","tabule","tahoun","tajemno","tajfun","tajga","tajit","tajnost","taktika","tamhle","tampon","tancovat","tanec","tanker","tapeta","tavenina","tazatel","technika","tehdy","tekutina","telefon","temnota","tendence","tenista","tenor","teplota","tepna","teprve","terapie","termoska","textil","ticho","tiskopis","titulek","tkadlec","tkanina","tlapka","tleskat","tlukot","tlupa","tmel","toaleta","topinka","topol","torzo","touha","toulec","tradice","traktor","tramp","trasa","traverza","trefit","trest","trezor","trhavina","trhlina","trochu","trojice","troska","trouba","trpce","trpitel","trpkost","trubec","truchlit","truhlice","trus","trvat","tudy","tuhnout","tuhost","tundra","turista","turnaj","tuzemsko","tvaroh","tvorba","tvrdost","tvrz","tygr","tykev","ubohost","uboze","ubrat","ubrousek","ubrus","ubytovna","ucho","uctivost","udivit","uhradit","ujednat","ujistit","ujmout","ukazatel","uklidnit","uklonit","ukotvit","ukrojit","ulice","ulita","ulovit","umyvadlo","unavit","uniforma","uniknout","upadnout","uplatnit","uplynout","upoutat","upravit","uran","urazit","usednout","usilovat","usmrtit","usnadnit","usnout","usoudit","ustlat","ustrnout","utahovat","utkat","utlumit","utonout","utopenec","utrousit","uvalit","uvolnit","uvozovka","uzdravit","uzel","uzenina","uzlina","uznat","vagon","valcha","valoun","vana","vandal","vanilka","varan","varhany","varovat","vcelku","vchod","vdova","vedro","vegetace","vejce","velbloud","veletrh","velitel","velmoc","velryba","venkov","veranda","verze","veselka","veskrze","vesnice","vespodu","vesta","veterina","veverka","vibrace","vichr","videohra","vidina","vidle","vila","vinice","viset","vitalita","vize","vizitka","vjezd","vklad","vkus","vlajka","vlak","vlasec","vlevo","vlhkost","vliv","vlnovka","vloupat","vnucovat","vnuk","voda","vodivost","vodoznak","vodstvo","vojensky","vojna","vojsko","volant","volba","volit","volno","voskovka","vozidlo","vozovna","vpravo","vrabec","vracet","vrah","vrata","vrba","vrcholek","vrhat","vrstva","vrtule","vsadit","vstoupit","vstup","vtip","vybavit","vybrat","vychovat","vydat","vydra","vyfotit","vyhledat","vyhnout","vyhodit","vyhradit","vyhubit","vyjasnit","vyjet","vyjmout","vyklopit","vykonat","vylekat","vymazat","vymezit","vymizet","vymyslet","vynechat","vynikat","vynutit","vypadat","vyplatit","vypravit","vypustit","vyrazit","vyrovnat","vyrvat","vyslovit","vysoko","vystavit","vysunout","vysypat","vytasit","vytesat","vytratit","vyvinout","vyvolat","vyvrhel","vyzdobit","vyznat","vzadu","vzbudit","vzchopit","vzdor","vzduch","vzdychat","vzestup","vzhledem","vzkaz","vzlykat","vznik","vzorek","vzpoura","vztah","vztek","xylofon","zabrat","zabydlet","zachovat","zadarmo","zadusit","zafoukat","zahltit","zahodit","zahrada","zahynout","zajatec","zajet","zajistit","zaklepat","zakoupit","zalepit","zamezit","zamotat","zamyslet","zanechat","zanikat","zaplatit","zapojit","zapsat","zarazit","zastavit","zasunout","zatajit","zatemnit","zatknout","zaujmout","zavalit","zavelet","zavinit","zavolat","zavrtat","zazvonit","zbavit","zbrusu","zbudovat","zbytek","zdaleka","zdarma","zdatnost","zdivo","zdobit","zdroj","zdvih","zdymadlo","zelenina","zeman","zemina","zeptat","zezadu","zezdola","zhatit","zhltnout","zhluboka","zhotovit","zhruba","zima","zimnice","zjemnit","zklamat","zkoumat","zkratka","zkumavka","zlato","zlehka","zloba","zlom","zlost","zlozvyk","zmapovat","zmar","zmatek","zmije","zmizet","zmocnit","zmodrat","zmrzlina","zmutovat","znak","znalost","znamenat","znovu","zobrazit","zotavit","zoubek","zoufale","zplodit","zpomalit","zprava","zprostit","zprudka","zprvu","zrada","zranit","zrcadlo","zrnitost","zrno","zrovna","zrychlit","zrzavost","zticha","ztratit","zubovina","zubr","zvednout","zvenku","zvesela","zvon","zvrat","zvukovod","zvyk"]["abandon","ability","able","about","above","absent","absorb","abstract","absurd","abuse","access","accident","account","accuse","achieve","acid","acoustic","acquire","across","act","action","actor","actress","actual","adapt","add","addict","address","adjust","admit","adult","advance","advice","aerobic","affair","afford","afraid","again","age","agent","agree","ahead","aim","air","airport","aisle","alarm","album","alcohol","alert","alien","all","alley","allow","almost","alone","alpha","already","also","alter","always","amateur","amazing","among","amount","amused","analyst","anchor","ancient","anger","angle","angry","animal","ankle","announce","annual","another","answer","antenna","antique","anxiety","any","apart","apology","appear","apple","approve","april","arch","arctic","area","arena","argue","arm","armed","armor","army","around","arrange","arrest","arrive","arrow","art","artefact","artist","artwork","ask","aspect","assault","asset","assist","assume","asthma","athlete","atom","attack","attend","attitude","attract","auction","audit","august","aunt","author","auto","autumn","average","avocado","avoid","awake","aware","away","awesome","awful","awkward","axis","baby","bachelor","bacon","badge","bag","balance","balcony","ball","bamboo","banana","banner","bar","barely","bargain","barrel","base","basic","basket","battle","beach","bean","beauty","because","become","beef","before","begin","behave","behind","believe","below","belt","bench","benefit","best","betray","better","between","beyond","bicycle","bid","bike","bind","biology","bird","birth","bitter","black","blade","blame","blanket","blast","bleak","bless","blind","blood","blossom","blouse","blue","blur","blush","board","boat","body","boil","bomb","bone","bonus","book","boost","border","boring","borrow","boss","bottom","bounce","box","boy","bracket","brain","brand","brass","brave","bread","breeze","brick","bridge","brief","bright","bring","brisk","broccoli","broken","bronze","broom","brother","brown","brush","bubble","buddy","budget","buffalo","build","bulb","bulk","bullet","bundle","bunker","burden","burger","burst","bus","business","busy","butter","buyer","buzz","cabbage","cabin","cable","cactus","cage","cake","call","calm","camera","camp","can","canal","cancel","candy","cannon","canoe","canvas","canyon","capable","capital","captain","car","carbon","card","cargo","carpet","carry","cart","case","cash","casino","castle","casual","cat","catalog","catch","category","cattle","caught","cause","caution","cave","ceiling","celery","cement","census","century","cereal","certain","chair","chalk","champion","change","chaos","chapter","charge","chase","chat","cheap","check","cheese","chef","cherry","chest","chicken","chief","child","chimney","choice","choose","chronic","chuckle","chunk","churn","cigar","cinnamon","circle","citizen","city","civil","claim","clap","clarify","claw","clay","clean","clerk","clever","click","client","cliff","climb","clinic","clip","clock","clog","close","cloth","cloud","clown","club","clump","cluster","clutch","coach","coast","coconut","code","coffee","coil","coin","collect","color","column","combine","come","comfort","comic","common","company","concert","conduct","confirm","congress","connect","consider","control","convince","cook","cool","copper","copy","coral","core","corn","correct","cost","cotton","couch","country","couple","course","cousin","cover","coyote","crack","cradle","craft","cram","crane","crash","crater","crawl","crazy","cream","credit","creek","crew","cricket","crime","crisp","critic","crop","cross","crouch","crowd","crucial","cruel","cruise","crumble","crunch","crush","cry","crystal","cube","culture","cup","cupboard","curious","current","curtain","curve","cushion","custom","cute","cycle","dad","damage","damp","dance","danger","daring","dash","daughter","dawn","day","deal","debate","debris","decade","december","decide","decline","decorate","decrease","deer","defense","define","defy","degree","delay","deliver","demand","demise","denial","dentist","deny","depart","depend","deposit","depth","deputy","derive","describe","desert","design","desk","despair","destroy","detail","detect","develop","device","devote","diagram","dial","diamond","diary","dice","diesel","diet","differ","digital","dignity","dilemma","dinner","dinosaur","direct","dirt","disagree","discover","disease","dish","dismiss","disorder","display","distance","divert","divide","divorce","dizzy","doctor","document","dog","doll","dolphin","domain","donate","donkey","donor","door","dose","double","dove","draft","dragon","drama","drastic","draw","dream","dress","drift","drill","drink","drip","drive","drop","drum","dry","duck","dumb","dune","during","dust","dutch","duty","dwarf","dynamic","eager","eagle","early","earn","earth","easily","east","easy","echo","ecology","economy","edge","edit","educate","effort","egg","eight","either","elbow","elder","electric","elegant","element","elephant","elevator","elite","else","embark","embody","embrace","emerge","emotion","employ","empower","empty","enable","enact","end","endless","endorse","enemy","energy","enforce","engage","engine","enhance","enjoy","enlist","enough","enrich","enroll","ensure","enter","entire","entry","envelope","episode","equal","equip","era","erase","erode","erosion","error","erupt","escape","essay","essence","estate","eternal","ethics","evidence","evil","evoke","evolve","exact","example","excess","exchange","excite","exclude","excuse","execute","exercise","exhaust","exhibit","exile","exist","exit","exotic","expand","expect","expire","explain","expose","express","extend","extra","eye","eyebrow","fabric","face","faculty","fade","faint","faith","fall","false","fame","family","famous","fan","fancy","fantasy","farm","fashion","fat","fatal","father","fatigue","fault","favorite","feature","february","federal","fee","feed","feel","female","fence","festival","fetch","fever","few","fiber","fiction","field","figure","file","film","filter","final","find","fine","finger","finish","fire","firm","first","fiscal","fish","fit","fitness","fix","flag","flame","flash","flat","flavor","flee","flight","flip","float","flock","floor","flower","fluid","flush","fly","foam","focus","fog","foil","fold","follow","food","foot","force","forest","forget","fork","fortune","forum","forward","fossil","foster","found","fox","fragile","frame","frequent","fresh","friend","fringe","frog","front","frost","frown","frozen","fruit","fuel","fun","funny","furnace","fury","future","gadget","gain","galaxy","gallery","game","gap","garage","garbage","garden","garlic","garment","gas","gasp","gate","gather","gauge","gaze","general","genius","genre","gentle","genuine","gesture","ghost","giant","gift","giggle","ginger","giraffe","girl","give","glad","glance","glare","glass","glide","glimpse","globe","gloom","glory","glove","glow","glue","goat","goddess","gold","good","goose","gorilla","gospel","gossip","govern","gown","grab","grace","grain","grant","grape","grass","gravity","great","green","grid","grief","grit","grocery","group","grow","grunt","guard","guess","guide","guilt","guitar","gun","gym","habit","hair","half","hammer","hamster","hand","happy","harbor","hard","harsh","harvest","hat","have","hawk","hazard","head","health","heart","heavy","hedgehog","height","hello","helmet","help","hen","hero","hidden","high","hill","hint","hip","hire","history","hobby","hockey","hold","hole","holiday","hollow","home","honey","hood","hope","horn","horror","horse","hospital","host","hotel","hour","hover","hub","huge","human","humble","humor","hundred","hungry","hunt","hurdle","hurry","hurt","husband","hybrid","ice","icon","idea","identify","idle","ignore","ill","illegal","illness","image","imitate","immense","immune","impact","impose","improve","impulse","inch","include","income","increase","index","indicate","indoor","industry","infant","inflict","inform","inhale","inherit","initial","inject","injury","inmate","inner","innocent","input","inquiry","insane","insect","inside","inspire","install","intact","interest","into","invest","invite","involve","iron","island","isolate","issue","item","ivory","jacket","jaguar","jar","jazz","jealous","jeans","jelly","jewel","job","join","joke","journey","joy","judge","juice","jump","jungle","junior","junk","just","kangaroo","keen","keep","ketchup","key","kick","kid","kidney","kind","kingdom","kiss","kit","kitchen","kite","kitten","kiwi","knee","knife","knock","know","lab","label","labor","ladder","lady","lake","lamp","language","laptop","large","later","latin","laugh","laundry","lava","law","lawn","lawsuit","layer","lazy","leader","leaf","learn","leave","lecture","left","leg","legal","legend","leisure","lemon","lend","length","lens","leopard","lesson","letter","level","liar","liberty","library","license","life","lift","light","like","limb","limit","link","lion","liquid","list","little","live","lizard","load","loan","lobster","local","lock","logic","lonely","long","loop","lottery","loud","lounge","love","loyal","lucky","luggage","lumber","lunar","lunch","luxury","lyrics","machine","mad","magic","magnet","maid","mail","main","major","make","mammal","man","manage","mandate","mango","mansion","manual","maple","marble","march","margin","marine","market","marriage","mask","mass","master","match","material","math","matrix","matter","maximum","maze","meadow","mean","measure","meat","mechanic","medal","media","melody","melt","member","memory","mention","menu","mercy","merge","merit","merry","mesh","message","metal","method","middle","midnight","milk","million","mimic","mind","minimum","minor","minute","miracle","mirror","misery","miss","mistake","mix","mixed","mixture","mobile","model","modify","mom","moment","monitor","monkey","monster","month","moon","moral","more","morning","mosquito","mother","motion","motor","mountain","mouse","move","movie","much","muffin","mule","multiply","muscle","museum","mushroom","music","must","mutual","myself","mystery","myth","naive","name","napkin","narrow","nasty","nation","nature","near","neck","need","negative","neglect","neither","nephew","nerve","nest","net","network","neutral","never","news","next","nice","night","noble","noise","nominee","noodle","normal","north","nose","notable","note","nothing","notice","novel","now","nuclear","number","nurse","nut","oak","obey","object","oblige","obscure","observe","obtain","obvious","occur","ocean","october","odor","off","offer","office","often","oil","okay","old","olive","olympic","omit","once","one","onion","online","only","open","opera","opinion","oppose","option","orange","orbit","orchard","order","ordinary","organ","orient","original","orphan","ostrich","other","outdoor","outer","output","outside","oval","oven","over","own","owner","oxygen","oyster","ozone","pact","paddle","page","pair","palace","palm","panda","panel","panic","panther","paper","parade","parent","park","parrot","party","pass","patch","path","patient","patrol","pattern","pause","pave","payment","peace","peanut","pear","peasant","pelican","pen","penalty","pencil","people","pepper","perfect","permit","person","pet","phone","photo","phrase","physical","piano","picnic","picture","piece","pig","pigeon","pill","pilot","pink","pioneer","pipe","pistol","pitch","pizza","place","planet","plastic","plate","play","please","pledge","pluck","plug","plunge","poem","poet","point","polar","pole","police","pond","pony","pool","popular","portion","position","possible","post","potato","pottery","poverty","powder","power","practice","praise","predict","prefer","prepare","present","pretty","prevent","price","pride","primary","print","priority","prison","private","prize","problem","process","produce","profit","program","project","promote","proof","property","prosper","protect","proud","provide","public","pudding","pull","pulp","pulse","pumpkin","punch","pupil","puppy","purchase","purity","purpose","purse","push","put","puzzle","pyramid","quality","quantum","quarter","question","quick","quit","quiz","quote","rabbit","raccoon","race","rack","radar","radio","rail","rain","raise","rally","ramp","ranch","random","range","rapid","rare","rate","rather","raven","raw","razor","ready","real","reason","rebel","rebuild","recall","receive","recipe","record","recycle","reduce","reflect","reform","refuse","region","regret","regular","reject","relax","release","relief","rely","remain","remember","remind","remove","render","renew","rent","reopen","repair","repeat","replace","report","require","rescue","resemble","resist","resource","response","result","retire","retreat","return","reunion","reveal","review","reward","rhythm","rib","ribbon","rice","rich","ride","ridge","rifle","right","rigid","ring","riot","ripple","risk","ritual","rival","river","road","roast","robot","robust","rocket","romance","roof","rookie","room","rose","rotate","rough","round","route","royal","rubber","rude","rug","rule","run","runway","rural","sad","saddle","sadness","safe","sail","salad","salmon","salon","salt","salute","same","sample","sand","satisfy","satoshi","sauce","sausage","save","say","scale","scan","scare","scatter","scene","scheme","school","science","scissors","scorpion","scout","scrap","screen","script","scrub","sea","search","season","seat","second","secret","section","security","seed","seek","segment","select","sell","seminar","senior","sense","sentence","series","service","session","settle","setup","seven","shadow","shaft","shallow","share","shed","shell","sheriff","shield","shift","shine","ship","shiver","shock","shoe","shoot","shop","short","shoulder","shove","shrimp","shrug","shuffle","shy","sibling","sick","side","siege","sight","sign","silent","silk","silly","silver","similar","simple","since","sing","siren","sister","situate","six","size","skate","sketch","ski","skill","skin","skirt","skull","slab","slam","sleep","slender","slice","slide","slight","slim","slogan","slot","slow","slush","small","smart","smile","smoke","smooth","snack","snake","snap","sniff","snow","soap","soccer","social","sock","soda","soft","solar","soldier","solid","solution","solve","someone","song","soon","sorry","sort","soul","sound","soup","source","south","space","spare","spatial","spawn","speak","special","speed","spell","spend","sphere","spice","spider","spike","spin","spirit","split","spoil","sponsor","spoon","sport","spot","spray","spread","spring","spy","square","squeeze","squirrel","stable","stadium","staff","stage","stairs","stamp","stand","start","state","stay","steak","steel","stem","step","stereo","stick","still","sting","stock","stomach","stone","stool","story","stove","strategy","street","strike","strong","struggle","student","stuff","stumble","style","subject","submit","subway","success","such","sudden","suffer","sugar","suggest","suit","summer","sun","sunny","sunset","super","supply","supreme","sure","surface","surge","surprise","surround","survey","suspect","sustain","swallow","swamp","swap","swarm","swear","sweet","swift","swim","swing","switch","sword","symbol","symptom","syrup","system","table","tackle","tag","tail","talent","talk","tank","tape","target","task","taste","tattoo","taxi","teach","team","tell","ten","tenant","tennis","tent","term","test","text","thank","that","theme","then","theory","there","they","thing","this","thought","three","thrive","throw","thumb","thunder","ticket","tide","tiger","tilt","timber","time","tiny","tip","tired","tissue","title","toast","tobacco","today","toddler","toe","together","toilet","token","tomato","tomorrow","tone","tongue","tonight","tool","tooth","top","topic","topple","torch","tornado","tortoise","toss","total","tourist","toward","tower","town","toy","track","trade","traffic","tragic","train","transfer","trap","trash","travel","tray","treat","tree","trend","trial","tribe","trick","trigger","trim","trip","trophy","trouble","truck","true","truly","trumpet","trust","truth","try","tube","tuition","tumble","tuna","tunnel","turkey","turn","turtle","twelve","twenty","twice","twin","twist","two","type","typical","ugly","umbrella","unable","unaware","uncle","uncover","under","undo","unfair","unfold","unhappy","uniform","unique","unit","universe","unknown","unlock","until","unusual","unveil","update","upgrade","uphold","upon","upper","upset","urban","urge","usage","use","used","useful","useless","usual","utility","vacant","vacuum","vague","valid","valley","valve","van","vanish","vapor","various","vast","vault","vehicle","velvet","vendor","venture","venue","verb","verify","version","very","vessel","veteran","viable","vibrant","vicious","victory","video","view","village","vintage","violin","virtual","virus","visa","visit","visual","vital","vivid","vocal","voice","void","volcano","volume","vote","voyage","wage","wagon","wait","walk","wall","walnut","want","warfare","warm","warrior","wash","wasp","waste","water","wave","way","wealth","weapon","wear","weasel","weather","web","wedding","weekend","weird","welcome","west","wet","whale","what","wheat","wheel","when","where","whip","whisper","wide","width","wife","wild","will","win","window","wine","wing","wink","winner","winter","wire","wisdom","wise","wish","witness","wolf","woman","wonder","wood","wool","word","work","world","worry","worth","wrap","wreck","wrestle","wrist","write","wrong","yard","year","yellow","you","young","youth","zebra","zero","zone","zoo"]["abaisser","abandon","abdiquer","abeille","abolir","aborder","aboutir","aboyer","abrasif","abreuver","abriter","abroger","abrupt","absence","absolu","absurde","abusif","abyssal","académie","acajou","acarien","accabler","accepter","acclamer","accolade","accroche","accuser","acerbe","achat","acheter","aciduler","acier","acompte","acquérir","acronyme","acteur","actif","actuel","adepte","adéquat","adhésif","adjectif","adjuger","admettre","admirer","adopter","adorer","adoucir","adresse","adroit","adulte","adverbe","aérer","aéronef","affaire","affecter","affiche","affreux","affubler","agacer","agencer","agile","agiter","agrafer","agréable","agrume","aider","aiguille","ailier","aimable","aisance","ajouter","ajuster","alarmer","alchimie","alerte","algèbre","algue","aliéner","aliment","alléger","alliage","allouer","allumer","alourdir","alpaga","altesse","alvéole","amateur","ambigu","ambre","aménager","amertume","amidon","amiral","amorcer","amour","amovible","amphibie","ampleur","amusant","analyse","anaphore","anarchie","anatomie","ancien","anéantir","angle","angoisse","anguleux","animal","annexer","annonce","annuel","anodin","anomalie","anonyme","anormal","antenne","antidote","anxieux","apaiser","apéritif","aplanir","apologie","appareil","appeler","apporter","appuyer","aquarium","aqueduc","arbitre","arbuste","ardeur","ardoise","argent","arlequin","armature","armement","armoire","armure","arpenter","arracher","arriver","arroser","arsenic","artériel","article","aspect","asphalte","aspirer","assaut","asservir","assiette","associer","assurer","asticot","astre","astuce","atelier","atome","atrium","atroce","attaque","attentif","attirer","attraper","aubaine","auberge","audace","audible","augurer","aurore","automne","autruche","avaler","avancer","avarice","avenir","averse","aveugle","aviateur","avide","avion","aviser","avoine","avouer","avril","axial","axiome","badge","bafouer","bagage","baguette","baignade","balancer","balcon","baleine","balisage","bambin","bancaire","bandage","banlieue","bannière","banquier","barbier","baril","baron","barque","barrage","bassin","bastion","bataille","bateau","batterie","baudrier","bavarder","belette","bélier","belote","bénéfice","berceau","berger","berline","bermuda","besace","besogne","bétail","beurre","biberon","bicycle","bidule","bijou","bilan","bilingue","billard","binaire","biologie","biopsie","biotype","biscuit","bison","bistouri","bitume","bizarre","blafard","blague","blanchir","blessant","blinder","blond","bloquer","blouson","bobard","bobine","boire","boiser","bolide","bonbon","bondir","bonheur","bonifier","bonus","bordure","borne","botte","boucle","boueux","bougie","boulon","bouquin","bourse","boussole","boutique","boxeur","branche","brasier","brave","brebis","brèche","breuvage","bricoler","brigade","brillant","brioche","brique","brochure","broder","bronzer","brousse","broyeur","brume","brusque","brutal","bruyant","buffle","buisson","bulletin","bureau","burin","bustier","butiner","butoir","buvable","buvette","cabanon","cabine","cachette","cadeau","cadre","caféine","caillou","caisson","calculer","calepin","calibre","calmer","calomnie","calvaire","camarade","caméra","camion","campagne","canal","caneton","canon","cantine","canular","capable","caporal","caprice","capsule","capter","capuche","carabine","carbone","caresser","caribou","carnage","carotte","carreau","carton","cascade","casier","casque","cassure","causer","caution","cavalier","caverne","caviar","cédille","ceinture","céleste","cellule","cendrier","censurer","central","cercle","cérébral","cerise","cerner","cerveau","cesser","chagrin","chaise","chaleur","chambre","chance","chapitre","charbon","chasseur","chaton","chausson","chavirer","chemise","chenille","chéquier","chercher","cheval","chien","chiffre","chignon","chimère","chiot","chlorure","chocolat","choisir","chose","chouette","chrome","chute","cigare","cigogne","cimenter","cinéma","cintrer","circuler","cirer","cirque","citerne","citoyen","citron","civil","clairon","clameur","claquer","classe","clavier","client","cligner","climat","clivage","cloche","clonage","cloporte","cobalt","cobra","cocasse","cocotier","coder","codifier","coffre","cogner","cohésion","coiffer","coincer","colère","colibri","colline","colmater","colonel","combat","comédie","commande","compact","concert","conduire","confier","congeler","connoter","consonne","contact","convexe","copain","copie","corail","corbeau","cordage","corniche","corpus","correct","cortège","cosmique","costume","coton","coude","coupure","courage","couteau","couvrir","coyote","crabe","crainte","cravate","crayon","créature","créditer","crémeux","creuser","crevette","cribler","crier","cristal","critère","croire","croquer","crotale","crucial","cruel","crypter","cubique","cueillir","cuillère","cuisine","cuivre","culminer","cultiver","cumuler","cupide","curatif","curseur","cyanure","cycle","cylindre","cynique","daigner","damier","danger","danseur","dauphin","débattre","débiter","déborder","débrider","débutant","décaler","décembre","déchirer","décider","déclarer","décorer","décrire","décupler","dédale","déductif","déesse","défensif","défiler","défrayer","dégager","dégivrer","déglutir","dégrafer","déjeuner","délice","déloger","demander","demeurer","démolir","dénicher","dénouer","dentelle","dénuder","départ","dépenser","déphaser","déplacer","déposer","déranger","dérober","désastre","descente","désert","désigner","désobéir","dessiner","destrier","détacher","détester","détourer","détresse","devancer","devenir","deviner","devoir","diable","dialogue","diamant","dicter","différer","digérer","digital","digne","diluer","dimanche","diminuer","dioxyde","directif","diriger","discuter","disposer","dissiper","distance","divertir","diviser","docile","docteur","dogme","doigt","domaine","domicile","dompter","donateur","donjon","donner","dopamine","dortoir","dorure","dosage","doseur","dossier","dotation","douanier","double","douceur","douter","doyen","dragon","draper","dresser","dribbler","droiture","duperie","duplexe","durable","durcir","dynastie","éblouir","écarter","écharpe","échelle","éclairer","éclipse","éclore","écluse","école","économie","écorce","écouter","écraser","écrémer","écrivain","écrou","écume","écureuil","édifier","éduquer","effacer","effectif","effigie","effort","effrayer","effusion","égaliser","égarer","éjecter","élaborer","élargir","électron","élégant","éléphant","élève","éligible","élitisme","éloge","élucider","éluder","emballer","embellir","embryon","émeraude","émission","emmener","émotion","émouvoir","empereur","employer","emporter","emprise","émulsion","encadrer","enchère","enclave","encoche","endiguer","endosser","endroit","enduire","énergie","enfance","enfermer","enfouir","engager","engin","englober","énigme","enjamber","enjeu","enlever","ennemi","ennuyeux","enrichir","enrobage","enseigne","entasser","entendre","entier","entourer","entraver","énumérer","envahir","enviable","envoyer","enzyme","éolien","épaissir","épargne","épatant","épaule","épicerie","épidémie","épier","épilogue","épine","épisode","épitaphe","époque","épreuve","éprouver","épuisant","équerre","équipe","ériger","érosion","erreur","éruption","escalier","espadon","espèce","espiègle","espoir","esprit","esquiver","essayer","essence","essieu","essorer","estime","estomac","estrade","étagère","étaler","étanche","étatique","éteindre","étendoir","éternel","éthanol","éthique","ethnie","étirer","étoffer","étoile","étonnant","étourdir","étrange","étroit","étude","euphorie","évaluer","évasion","éventail","évidence","éviter","évolutif","évoquer","exact","exagérer","exaucer","exceller","excitant","exclusif","excuse","exécuter","exemple","exercer","exhaler","exhorter","exigence","exiler","exister","exotique","expédier","explorer","exposer","exprimer","exquis","extensif","extraire","exulter","fable","fabuleux","facette","facile","facture","faiblir","falaise","fameux","famille","farceur","farfelu","farine","farouche","fasciner","fatal","fatigue","faucon","fautif","faveur","favori","fébrile","féconder","fédérer","félin","femme","fémur","fendoir","féodal","fermer","féroce","ferveur","festival","feuille","feutre","février","fiasco","ficeler","fictif","fidèle","figure","filature","filetage","filière","filleul","filmer","filou","filtrer","financer","finir","fiole","firme","fissure","fixer","flairer","flamme","flasque","flatteur","fléau","flèche","fleur","flexion","flocon","flore","fluctuer","fluide","fluvial","folie","fonderie","fongible","fontaine","forcer","forgeron","formuler","fortune","fossile","foudre","fougère","fouiller","foulure","fourmi","fragile","fraise","franchir","frapper","frayeur","frégate","freiner","frelon","frémir","frénésie","frère","friable","friction","frisson","frivole","froid","fromage","frontal","frotter","fruit","fugitif","fuite","fureur","furieux","furtif","fusion","futur","gagner","galaxie","galerie","gambader","garantir","gardien","garnir","garrigue","gazelle","gazon","géant","gélatine","gélule","gendarme","général","génie","genou","gentil","géologie","géomètre","géranium","germe","gestuel","geyser","gibier","gicler","girafe","givre","glace","glaive","glisser","globe","gloire","glorieux","golfeur","gomme","gonfler","gorge","gorille","goudron","gouffre","goulot","goupille","gourmand","goutte","graduel","graffiti","graine","grand","grappin","gratuit","gravir","grenat","griffure","griller","grimper","grogner","gronder","grotte","groupe","gruger","grutier","gruyère","guépard","guerrier","guide","guimauve","guitare","gustatif","gymnaste","gyrostat","habitude","hachoir","halte","hameau","hangar","hanneton","haricot","harmonie","harpon","hasard","hélium","hématome","herbe","hérisson","hermine","héron","hésiter","heureux","hiberner","hibou","hilarant","histoire","hiver","homard","hommage","homogène","honneur","honorer","honteux","horde","horizon","horloge","hormone","horrible","houleux","housse","hublot","huileux","humain","humble","humide","humour","hurler","hydromel","hygiène","hymne","hypnose","idylle","ignorer","iguane","illicite","illusion","image","imbiber","imiter","immense","immobile","immuable","impact","impérial","implorer","imposer","imprimer","imputer","incarner","incendie","incident","incliner","incolore","indexer","indice","inductif","inédit","ineptie","inexact","infini","infliger","informer","infusion","ingérer","inhaler","inhiber","injecter","injure","innocent","inoculer","inonder","inscrire","insecte","insigne","insolite","inspirer","instinct","insulter","intact","intense","intime","intrigue","intuitif","inutile","invasion","inventer","inviter","invoquer","ironique","irradier","irréel","irriter","isoler","ivoire","ivresse","jaguar","jaillir","jambe","janvier","jardin","jauger","jaune","javelot","jetable","jeton","jeudi","jeunesse","joindre","joncher","jongler","joueur","jouissif","journal","jovial","joyau","joyeux","jubiler","jugement","junior","jupon","juriste","justice","juteux","juvénile","kayak","kimono","kiosque","label","labial","labourer","lacérer","lactose","lagune","laine","laisser","laitier","lambeau","lamelle","lampe","lanceur","langage","lanterne","lapin","largeur","larme","laurier","lavabo","lavoir","lecture","légal","léger","légume","lessive","lettre","levier","lexique","lézard","liasse","libérer","libre","licence","licorne","liège","lièvre","ligature","ligoter","ligue","limer","limite","limonade","limpide","linéaire","lingot","lionceau","liquide","lisière","lister","lithium","litige","littoral","livreur","logique","lointain","loisir","lombric","loterie","louer","lourd","loutre","louve","loyal","lubie","lucide","lucratif","lueur","lugubre","luisant","lumière","lunaire","lundi","luron","lutter","luxueux","machine","magasin","magenta","magique","maigre","maillon","maintien","mairie","maison","majorer","malaxer","maléfice","malheur","malice","mallette","mammouth","mandater","maniable","manquant","manteau","manuel","marathon","marbre","marchand","mardi","maritime","marqueur","marron","marteler","mascotte","massif","matériel","matière","matraque","maudire","maussade","mauve","maximal","méchant","méconnu","médaille","médecin","méditer","méduse","meilleur","mélange","mélodie","membre","mémoire","menacer","mener","menhir","mensonge","mentor","mercredi","mérite","merle","messager","mesure","métal","météore","méthode","métier","meuble","miauler","microbe","miette","mignon","migrer","milieu","million","mimique","mince","minéral","minimal","minorer","minute","miracle","miroiter","missile","mixte","mobile","moderne","moelleux","mondial","moniteur","monnaie","monotone","monstre","montagne","monument","moqueur","morceau","morsure","mortier","moteur","motif","mouche","moufle","moulin","mousson","mouton","mouvant","multiple","munition","muraille","murène","murmure","muscle","muséum","musicien","mutation","muter","mutuel","myriade","myrtille","mystère","mythique","nageur","nappe","narquois","narrer","natation","nation","nature","naufrage","nautique","navire","nébuleux","nectar","néfaste","négation","négliger","négocier","neige","nerveux","nettoyer","neurone","neutron","neveu","niche","nickel","nitrate","niveau","noble","nocif","nocturne","noirceur","noisette","nomade","nombreux","nommer","normatif","notable","notifier","notoire","nourrir","nouveau","novateur","novembre","novice","nuage","nuancer","nuire","nuisible","numéro","nuptial","nuque","nutritif","obéir","objectif","obliger","obscur","observer","obstacle","obtenir","obturer","occasion","occuper","océan","octobre","octroyer","octupler","oculaire","odeur","odorant","offenser","officier","offrir","ogive","oiseau","oisillon","olfactif","olivier","ombrage","omettre","onctueux","onduler","onéreux","onirique","opale","opaque","opérer","opinion","opportun","opprimer","opter","optique","orageux","orange","orbite","ordonner","oreille","organe","orgueil","orifice","ornement","orque","ortie","osciller","osmose","ossature","otarie","ouragan","ourson","outil","outrager","ouvrage","ovation","oxyde","oxygène","ozone","paisible","palace","palmarès","palourde","palper","panache","panda","pangolin","paniquer","panneau","panorama","pantalon","papaye","papier","papoter","papyrus","paradoxe","parcelle","paresse","parfumer","parler","parole","parrain","parsemer","partager","parure","parvenir","passion","pastèque","paternel","patience","patron","pavillon","pavoiser","payer","paysage","peigne","peintre","pelage","pélican","pelle","pelouse","peluche","pendule","pénétrer","pénible","pensif","pénurie","pépite","péplum","perdrix","perforer","période","permuter","perplexe","persil","perte","peser","pétale","petit","pétrir","peuple","pharaon","phobie","phoque","photon","phrase","physique","piano","pictural","pièce","pierre","pieuvre","pilote","pinceau","pipette","piquer","pirogue","piscine","piston","pivoter","pixel","pizza","placard","plafond","plaisir","planer","plaque","plastron","plateau","pleurer","plexus","pliage","plomb","plonger","pluie","plumage","pochette","poésie","poète","pointe","poirier","poisson","poivre","polaire","policier","pollen","polygone","pommade","pompier","ponctuel","pondérer","poney","portique","position","posséder","posture","potager","poteau","potion","pouce","poulain","poumon","pourpre","poussin","pouvoir","prairie","pratique","précieux","prédire","préfixe","prélude","prénom","présence","prétexte","prévoir","primitif","prince","prison","priver","problème","procéder","prodige","profond","progrès","proie","projeter","prologue","promener","propre","prospère","protéger","prouesse","proverbe","prudence","pruneau","psychose","public","puceron","puiser","pulpe","pulsar","punaise","punitif","pupitre","purifier","puzzle","pyramide","quasar","querelle","question","quiétude","quitter","quotient","racine","raconter","radieux","ragondin","raideur","raisin","ralentir","rallonge","ramasser","rapide","rasage","ratisser","ravager","ravin","rayonner","réactif","réagir","réaliser","réanimer","recevoir","réciter","réclamer","récolter","recruter","reculer","recycler","rédiger","redouter","refaire","réflexe","réformer","refrain","refuge","régalien","région","réglage","régulier","réitérer","rejeter","rejouer","relatif","relever","relief","remarque","remède","remise","remonter","remplir","remuer","renard","renfort","renifler","renoncer","rentrer","renvoi","replier","reporter","reprise","reptile","requin","réserve","résineux","résoudre","respect","rester","résultat","rétablir","retenir","réticule","retomber","retracer","réunion","réussir","revanche","revivre","révolte","révulsif","richesse","rideau","rieur","rigide","rigoler","rincer","riposter","risible","risque","rituel","rival","rivière","rocheux","romance","rompre","ronce","rondin","roseau","rosier","rotatif","rotor","rotule","rouge","rouille","rouleau","routine","royaume","ruban","rubis","ruche","ruelle","rugueux","ruiner","ruisseau","ruser","rustique","rythme","sabler","saboter","sabre","sacoche","safari","sagesse","saisir","salade","salive","salon","saluer","samedi","sanction","sanglier","sarcasme","sardine","saturer","saugrenu","saumon","sauter","sauvage","savant","savonner","scalpel","scandale","scélérat","scénario","sceptre","schéma","science","scinder","score","scrutin","sculpter","séance","sécable","sécher","secouer","sécréter","sédatif","séduire","seigneur","séjour","sélectif","semaine","sembler","semence","séminal","sénateur","sensible","sentence","séparer","séquence","serein","sergent","sérieux","serrure","sérum","service","sésame","sévir","sevrage","sextuple","sidéral","siècle","siéger","siffler","sigle","signal","silence","silicium","simple","sincère","sinistre","siphon","sirop","sismique","situer","skier","social","socle","sodium","soigneux","soldat","soleil","solitude","soluble","sombre","sommeil","somnoler","sonde","songeur","sonnette","sonore","sorcier","sortir","sosie","sottise","soucieux","soudure","souffle","soulever","soupape","source","soutirer","souvenir","spacieux","spatial","spécial","sphère","spiral","stable","station","sternum","stimulus","stipuler","strict","studieux","stupeur","styliste","sublime","substrat","subtil","subvenir","succès","sucre","suffixe","suggérer","suiveur","sulfate","superbe","supplier","surface","suricate","surmener","surprise","sursaut","survie","suspect","syllabe","symbole","symétrie","synapse","syntaxe","système","tabac","tablier","tactile","tailler","talent","talisman","talonner","tambour","tamiser","tangible","tapis","taquiner","tarder","tarif","tartine","tasse","tatami","tatouage","taupe","taureau","taxer","témoin","temporel","tenaille","tendre","teneur","tenir","tension","terminer","terne","terrible","tétine","texte","thème","théorie","thérapie","thorax","tibia","tiède","timide","tirelire","tiroir","tissu","titane","titre","tituber","toboggan","tolérant","tomate","tonique","tonneau","toponyme","torche","tordre","tornade","torpille","torrent","torse","tortue","totem","toucher","tournage","tousser","toxine","traction","trafic","tragique","trahir","train","trancher","travail","trèfle","tremper","trésor","treuil","triage","tribunal","tricoter","trilogie","triomphe","tripler","triturer","trivial","trombone","tronc","tropical","troupeau","tuile","tulipe","tumulte","tunnel","turbine","tuteur","tutoyer","tuyau","tympan","typhon","typique","tyran","ubuesque","ultime","ultrason","unanime","unifier","union","unique","unitaire","univers","uranium","urbain","urticant","usage","usine","usuel","usure","utile","utopie","vacarme","vaccin","vagabond","vague","vaillant","vaincre","vaisseau","valable","valise","vallon","valve","vampire","vanille","vapeur","varier","vaseux","vassal","vaste","vecteur","vedette","végétal","véhicule","veinard","véloce","vendredi","vénérer","venger","venimeux","ventouse","verdure","vérin","vernir","verrou","verser","vertu","veston","vétéran","vétuste","vexant","vexer","viaduc","viande","victoire","vidange","vidéo","vignette","vigueur","vilain","village","vinaigre","violon","vipère","virement","virtuose","virus","visage","viseur","vision","visqueux","visuel","vital","vitesse","viticole","vitrine","vivace","vivipare","vocation","voguer","voile","voisin","voiture","volaille","volcan","voltiger","volume","vorace","vortex","voter","vouloir","voyage","voyelle","wagon","xénon","yacht","zèbre","zénith","zeste","zoologie"]// note all JSON files in this folder are generated with npm run generate-wordlist
const lookup = require('./lookup.json')

module.exports = {
  loadWordlist,
  detectLanguage
}

function loadWordlist (language) {
  switch (language) {
    case 'chinese_simplified': return require('./chinese_simplified.json')
    case 'chinese_traditional': return require('./chinese_traditional.json')
    case 'czech': return require('./czech.json')
    case 'english': return require('./english.json')
    case 'french': return require('./french.json')
    case 'italian': return require('./italian.json')
    case 'japanese': return require('./japanese.json')
    case 'korean': return require('./korean.json')
    case 'portuguese': return require('./portuguese.json')
    case 'russian': return require('./russian.json')
    case 'spanish': return require('./spanish.json')
    case 'turkish': return require('./turkish.json')
  }

  throw new Error('Unknown language: ' + language)
}

function detectLanguage (words) {
  let candidate = null

  for (const word of words) {
    const languages = lookup[word]
    if (!languages) return null

    if (languages.length === 1) return languages[0]

    if (!candidate) {
      candidate = languages
      continue
    }

    const intersect = candidate.filter(l => languages.includes(l))
    if (intersect.length === 1) return intersect[0]
  }

  return candidate[0]
}
["abaco","abbaglio","abbinato","abete","abisso","abolire","abrasivo","abrogato","accadere","accenno","accusato","acetone","achille","acido","acqua","acre","acrilico","acrobata","acuto","adagio","addebito","addome","adeguato","aderire","adipe","adottare","adulare","affabile","affetto","affisso","affranto","aforisma","afoso","africano","agave","agente","agevole","aggancio","agire","agitare","agonismo","agricolo","agrumeto","aguzzo","alabarda","alato","albatro","alberato","albo","albume","alce","alcolico","alettone","alfa","algebra","aliante","alibi","alimento","allagato","allegro","allievo","allodola","allusivo","almeno","alogeno","alpaca","alpestre","altalena","alterno","alticcio","altrove","alunno","alveolo","alzare","amalgama","amanita","amarena","ambito","ambrato","ameba","america","ametista","amico","ammasso","ammenda","ammirare","ammonito","amore","ampio","ampliare","amuleto","anacardo","anagrafe","analista","anarchia","anatra","anca","ancella","ancora","andare","andrea","anello","angelo","angolare","angusto","anima","annegare","annidato","anno","annuncio","anonimo","anticipo","anzi","apatico","apertura","apode","apparire","appetito","appoggio","approdo","appunto","aprile","arabica","arachide","aragosta","araldica","arancio","aratura","arazzo","arbitro","archivio","ardito","arenile","argento","argine","arguto","aria","armonia","arnese","arredato","arringa","arrosto","arsenico","arso","artefice","arzillo","asciutto","ascolto","asepsi","asettico","asfalto","asino","asola","aspirato","aspro","assaggio","asse","assoluto","assurdo","asta","astenuto","astice","astratto","atavico","ateismo","atomico","atono","attesa","attivare","attorno","attrito","attuale","ausilio","austria","autista","autonomo","autunno","avanzato","avere","avvenire","avviso","avvolgere","azione","azoto","azzimo","azzurro","babele","baccano","bacino","baco","badessa","badilata","bagnato","baita","balcone","baldo","balena","ballata","balzano","bambino","bandire","baraonda","barbaro","barca","baritono","barlume","barocco","basilico","basso","batosta","battuto","baule","bava","bavosa","becco","beffa","belgio","belva","benda","benevole","benigno","benzina","bere","berlina","beta","bibita","bici","bidone","bifido","biga","bilancia","bimbo","binocolo","biologo","bipede","bipolare","birbante","birra","biscotto","bisesto","bisnonno","bisonte","bisturi","bizzarro","blando","blatta","bollito","bonifico","bordo","bosco","botanico","bottino","bozzolo","braccio","bradipo","brama","branca","bravura","bretella","brevetto","brezza","briglia","brillante","brindare","broccolo","brodo","bronzina","brullo","bruno","bubbone","buca","budino","buffone","buio","bulbo","buono","burlone","burrasca","bussola","busta","cadetto","caduco","calamaro","calcolo","calesse","calibro","calmo","caloria","cambusa","camerata","camicia","cammino","camola","campale","canapa","candela","cane","canino","canotto","cantina","capace","capello","capitolo","capogiro","cappero","capra","capsula","carapace","carcassa","cardo","carisma","carovana","carretto","cartolina","casaccio","cascata","caserma","caso","cassone","castello","casuale","catasta","catena","catrame","cauto","cavillo","cedibile","cedrata","cefalo","celebre","cellulare","cena","cenone","centesimo","ceramica","cercare","certo","cerume","cervello","cesoia","cespo","ceto","chela","chiaro","chicca","chiedere","chimera","china","chirurgo","chitarra","ciao","ciclismo","cifrare","cigno","cilindro","ciottolo","circa","cirrosi","citrico","cittadino","ciuffo","civetta","civile","classico","clinica","cloro","cocco","codardo","codice","coerente","cognome","collare","colmato","colore","colposo","coltivato","colza","coma","cometa","commando","comodo","computer","comune","conciso","condurre","conferma","congelare","coniuge","connesso","conoscere","consumo","continuo","convegno","coperto","copione","coppia","copricapo","corazza","cordata","coricato","cornice","corolla","corpo","corredo","corsia","cortese","cosmico","costante","cottura","covato","cratere","cravatta","creato","credere","cremoso","crescita","creta","criceto","crinale","crisi","critico","croce","cronaca","crostata","cruciale","crusca","cucire","cuculo","cugino","cullato","cupola","curatore","cursore","curvo","cuscino","custode","dado","daino","dalmata","damerino","daniela","dannoso","danzare","datato","davanti","davvero","debutto","decennio","deciso","declino","decollo","decreto","dedicato","definito","deforme","degno","delegare","delfino","delirio","delta","demenza","denotato","dentro","deposito","derapata","derivare","deroga","descritto","deserto","desiderio","desumere","detersivo","devoto","diametro","dicembre","diedro","difeso","diffuso","digerire","digitale","diluvio","dinamico","dinnanzi","dipinto","diploma","dipolo","diradare","dire","dirotto","dirupo","disagio","discreto","disfare","disgelo","disposto","distanza","disumano","dito","divano","divelto","dividere","divorato","doblone","docente","doganale","dogma","dolce","domato","domenica","dominare","dondolo","dono","dormire","dote","dottore","dovuto","dozzina","drago","druido","dubbio","dubitare","ducale","duna","duomo","duplice","duraturo","ebano","eccesso","ecco","eclissi","economia","edera","edicola","edile","editoria","educare","egemonia","egli","egoismo","egregio","elaborato","elargire","elegante","elencato","eletto","elevare","elfico","elica","elmo","elsa","eluso","emanato","emblema","emesso","emiro","emotivo","emozione","empirico","emulo","endemico","enduro","energia","enfasi","enoteca","entrare","enzima","epatite","epilogo","episodio","epocale","eppure","equatore","erario","erba","erboso","erede","eremita","erigere","ermetico","eroe","erosivo","errante","esagono","esame","esanime","esaudire","esca","esempio","esercito","esibito","esigente","esistere","esito","esofago","esortato","esoso","espanso","espresso","essenza","esso","esteso","estimare","estonia","estroso","esultare","etilico","etnico","etrusco","etto","euclideo","europa","evaso","evidenza","evitato","evoluto","evviva","fabbrica","faccenda","fachiro","falco","famiglia","fanale","fanfara","fango","fantasma","fare","farfalla","farinoso","farmaco","fascia","fastoso","fasullo","faticare","fato","favoloso","febbre","fecola","fede","fegato","felpa","feltro","femmina","fendere","fenomeno","fermento","ferro","fertile","fessura","festivo","fetta","feudo","fiaba","fiducia","fifa","figurato","filo","finanza","finestra","finire","fiore","fiscale","fisico","fiume","flacone","flamenco","flebo","flemma","florido","fluente","fluoro","fobico","focaccia","focoso","foderato","foglio","folata","folclore","folgore","fondente","fonetico","fonia","fontana","forbito","forchetta","foresta","formica","fornaio","foro","fortezza","forzare","fosfato","fosso","fracasso","frana","frassino","fratello","freccetta","frenata","fresco","frigo","frollino","fronde","frugale","frutta","fucilata","fucsia","fuggente","fulmine","fulvo","fumante","fumetto","fumoso","fune","funzione","fuoco","furbo","furgone","furore","fuso","futile","gabbiano","gaffe","galateo","gallina","galoppo","gambero","gamma","garanzia","garbo","garofano","garzone","gasdotto","gasolio","gastrico","gatto","gaudio","gazebo","gazzella","geco","gelatina","gelso","gemello","gemmato","gene","genitore","gennaio","genotipo","gergo","ghepardo","ghiaccio","ghisa","giallo","gilda","ginepro","giocare","gioiello","giorno","giove","girato","girone","gittata","giudizio","giurato","giusto","globulo","glutine","gnomo","gobba","golf","gomito","gommone","gonfio","gonna","governo","gracile","grado","grafico","grammo","grande","grattare","gravoso","grazia","greca","gregge","grifone","grigio","grinza","grotta","gruppo","guadagno","guaio","guanto","guardare","gufo","guidare","ibernato","icona","identico","idillio","idolo","idra","idrico","idrogeno","igiene","ignaro","ignorato","ilare","illeso","illogico","illudere","imballo","imbevuto","imbocco","imbuto","immane","immerso","immolato","impacco","impeto","impiego","importo","impronta","inalare","inarcare","inattivo","incanto","incendio","inchino","incisivo","incluso","incontro","incrocio","incubo","indagine","india","indole","inedito","infatti","infilare","inflitto","ingaggio","ingegno","inglese","ingordo","ingrosso","innesco","inodore","inoltrare","inondato","insano","insetto","insieme","insonnia","insulina","intasato","intero","intonaco","intuito","inumidire","invalido","invece","invito","iperbole","ipnotico","ipotesi","ippica","iride","irlanda","ironico","irrigato","irrorare","isolato","isotopo","isterico","istituto","istrice","italia","iterare","labbro","labirinto","lacca","lacerato","lacrima","lacuna","laddove","lago","lampo","lancetta","lanterna","lardoso","larga","laringe","lastra","latenza","latino","lattuga","lavagna","lavoro","legale","leggero","lembo","lentezza","lenza","leone","lepre","lesivo","lessato","lesto","letterale","leva","levigato","libero","lido","lievito","lilla","limatura","limitare","limpido","lineare","lingua","liquido","lira","lirica","lisca","lite","litigio","livrea","locanda","lode","logica","lombare","londra","longevo","loquace","lorenzo","loto","lotteria","luce","lucidato","lumaca","luminoso","lungo","lupo","luppolo","lusinga","lusso","lutto","macabro","macchina","macero","macinato","madama","magico","maglia","magnete","magro","maiolica","malafede","malgrado","malinteso","malsano","malto","malumore","mana","mancia","mandorla","mangiare","manifesto","mannaro","manovra","mansarda","mantide","manubrio","mappa","maratona","marcire","maretta","marmo","marsupio","maschera","massaia","mastino","materasso","matricola","mattone","maturo","mazurca","meandro","meccanico","mecenate","medesimo","meditare","mega","melassa","melis","melodia","meninge","meno","mensola","mercurio","merenda","merlo","meschino","mese","messere","mestolo","metallo","metodo","mettere","miagolare","mica","micelio","michele","microbo","midollo","miele","migliore","milano","milite","mimosa","minerale","mini","minore","mirino","mirtillo","miscela","missiva","misto","misurare","mitezza","mitigare","mitra","mittente","mnemonico","modello","modifica","modulo","mogano","mogio","mole","molosso","monastero","monco","mondina","monetario","monile","monotono","monsone","montato","monviso","mora","mordere","morsicato","mostro","motivato","motosega","motto","movenza","movimento","mozzo","mucca","mucosa","muffa","mughetto","mugnaio","mulatto","mulinello","multiplo","mummia","munto","muovere","murale","musa","muscolo","musica","mutevole","muto","nababbo","nafta","nanometro","narciso","narice","narrato","nascere","nastrare","naturale","nautica","naviglio","nebulosa","necrosi","negativo","negozio","nemmeno","neofita","neretto","nervo","nessuno","nettuno","neutrale","neve","nevrotico","nicchia","ninfa","nitido","nobile","nocivo","nodo","nome","nomina","nordico","normale","norvegese","nostrano","notare","notizia","notturno","novella","nucleo","nulla","numero","nuovo","nutrire","nuvola","nuziale","oasi","obbedire","obbligo","obelisco","oblio","obolo","obsoleto","occasione","occhio","occidente","occorrere","occultare","ocra","oculato","odierno","odorare","offerta","offrire","offuscato","oggetto","oggi","ognuno","olandese","olfatto","oliato","oliva","ologramma","oltre","omaggio","ombelico","ombra","omega","omissione","ondoso","onere","onice","onnivoro","onorevole","onta","operato","opinione","opposto","oracolo","orafo","ordine","orecchino","orefice","orfano","organico","origine","orizzonte","orma","ormeggio","ornativo","orologio","orrendo","orribile","ortensia","ortica","orzata","orzo","osare","oscurare","osmosi","ospedale","ospite","ossa","ossidare","ostacolo","oste","otite","otre","ottagono","ottimo","ottobre","ovale","ovest","ovino","oviparo","ovocito","ovunque","ovviare","ozio","pacchetto","pace","pacifico","padella","padrone","paese","paga","pagina","palazzina","palesare","pallido","palo","palude","pandoro","pannello","paolo","paonazzo","paprica","parabola","parcella","parere","pargolo","pari","parlato","parola","partire","parvenza","parziale","passivo","pasticca","patacca","patologia","pattume","pavone","peccato","pedalare","pedonale","peggio","peloso","penare","pendice","penisola","pennuto","penombra","pensare","pentola","pepe","pepita","perbene","percorso","perdonato","perforare","pergamena","periodo","permesso","perno","perplesso","persuaso","pertugio","pervaso","pesatore","pesista","peso","pestifero","petalo","pettine","petulante","pezzo","piacere","pianta","piattino","piccino","picozza","piega","pietra","piffero","pigiama","pigolio","pigro","pila","pilifero","pillola","pilota","pimpante","pineta","pinna","pinolo","pioggia","piombo","piramide","piretico","pirite","pirolisi","pitone","pizzico","placebo","planare","plasma","platano","plenario","pochezza","poderoso","podismo","poesia","poggiare","polenta","poligono","pollice","polmonite","polpetta","polso","poltrona","polvere","pomice","pomodoro","ponte","popoloso","porfido","poroso","porpora","porre","portata","posa","positivo","possesso","postulato","potassio","potere","pranzo","prassi","pratica","precluso","predica","prefisso","pregiato","prelievo","premere","prenotare","preparato","presenza","pretesto","prevalso","prima","principe","privato","problema","procura","produrre","profumo","progetto","prolunga","promessa","pronome","proposta","proroga","proteso","prova","prudente","prugna","prurito","psiche","pubblico","pudica","pugilato","pugno","pulce","pulito","pulsante","puntare","pupazzo","pupilla","puro","quadro","qualcosa","quasi","querela","quota","raccolto","raddoppio","radicale","radunato","raffica","ragazzo","ragione","ragno","ramarro","ramingo","ramo","randagio","rantolare","rapato","rapina","rappreso","rasatura","raschiato","rasente","rassegna","rastrello","rata","ravveduto","reale","recepire","recinto","recluta","recondito","recupero","reddito","redimere","regalato","registro","regola","regresso","relazione","remare","remoto","renna","replica","reprimere","reputare","resa","residente","responso","restauro","rete","retina","retorica","rettifica","revocato","riassunto","ribadire","ribelle","ribrezzo","ricarica","ricco","ricevere","riciclato","ricordo","ricreduto","ridicolo","ridurre","rifasare","riflesso","riforma","rifugio","rigare","rigettato","righello","rilassato","rilevato","rimanere","rimbalzo","rimedio","rimorchio","rinascita","rincaro","rinforzo","rinnovo","rinomato","rinsavito","rintocco","rinuncia","rinvenire","riparato","ripetuto","ripieno","riportare","ripresa","ripulire","risata","rischio","riserva","risibile","riso","rispetto","ristoro","risultato","risvolto","ritardo","ritegno","ritmico","ritrovo","riunione","riva","riverso","rivincita","rivolto","rizoma","roba","robotico","robusto","roccia","roco","rodaggio","rodere","roditore","rogito","rollio","romantico","rompere","ronzio","rosolare","rospo","rotante","rotondo","rotula","rovescio","rubizzo","rubrica","ruga","rullino","rumine","rumoroso","ruolo","rupe","russare","rustico","sabato","sabbiare","sabotato","sagoma","salasso","saldatura","salgemma","salivare","salmone","salone","saltare","saluto","salvo","sapere","sapido","saporito","saraceno","sarcasmo","sarto","sassoso","satellite","satira","satollo","saturno","savana","savio","saziato","sbadiglio","sbalzo","sbancato","sbarra","sbattere","sbavare","sbendare","sbirciare","sbloccato","sbocciato","sbrinare","sbruffone","sbuffare","scabroso","scadenza","scala","scambiare","scandalo","scapola","scarso","scatenare","scavato","scelto","scenico","scettro","scheda","schiena","sciarpa","scienza","scindere","scippo","sciroppo","scivolo","sclerare","scodella","scolpito","scomparto","sconforto","scoprire","scorta","scossone","scozzese","scriba","scrollare","scrutinio","scuderia","scultore","scuola","scuro","scusare","sdebitare","sdoganare","seccatura","secondo","sedano","seggiola","segnalato","segregato","seguito","selciato","selettivo","sella","selvaggio","semaforo","sembrare","seme","seminato","sempre","senso","sentire","sepolto","sequenza","serata","serbato","sereno","serio","serpente","serraglio","servire","sestina","setola","settimana","sfacelo","sfaldare","sfamato","sfarzoso","sfaticato","sfera","sfida","sfilato","sfinge","sfocato","sfoderare","sfogo","sfoltire","sforzato","sfratto","sfruttato","sfuggito","sfumare","sfuso","sgabello","sgarbato","sgonfiare","sgorbio","sgrassato","sguardo","sibilo","siccome","sierra","sigla","signore","silenzio","sillaba","simbolo","simpatico","simulato","sinfonia","singolo","sinistro","sino","sintesi","sinusoide","sipario","sisma","sistole","situato","slitta","slogatura","sloveno","smarrito","smemorato","smentito","smeraldo","smilzo","smontare","smottato","smussato","snellire","snervato","snodo","sobbalzo","sobrio","soccorso","sociale","sodale","soffitto","sogno","soldato","solenne","solido","sollazzo","solo","solubile","solvente","somatico","somma","sonda","sonetto","sonnifero","sopire","soppeso","sopra","sorgere","sorpasso","sorriso","sorso","sorteggio","sorvolato","sospiro","sosta","sottile","spada","spalla","spargere","spatola","spavento","spazzola","specie","spedire","spegnere","spelatura","speranza","spessore","spettrale","spezzato","spia","spigoloso","spillato","spinoso","spirale","splendido","sportivo","sposo","spranga","sprecare","spronato","spruzzo","spuntino","squillo","sradicare","srotolato","stabile","stacco","staffa","stagnare","stampato","stantio","starnuto","stasera","statuto","stelo","steppa","sterzo","stiletto","stima","stirpe","stivale","stizzoso","stonato","storico","strappo","stregato","stridulo","strozzare","strutto","stuccare","stufo","stupendo","subentro","succoso","sudore","suggerito","sugo","sultano","suonare","superbo","supporto","surgelato","surrogato","sussurro","sutura","svagare","svedese","sveglio","svelare","svenuto","svezia","sviluppo","svista","svizzera","svolta","svuotare","tabacco","tabulato","tacciare","taciturno","tale","talismano","tampone","tannino","tara","tardivo","targato","tariffa","tarpare","tartaruga","tasto","tattico","taverna","tavolata","tazza","teca","tecnico","telefono","temerario","tempo","temuto","tendone","tenero","tensione","tentacolo","teorema","terme","terrazzo","terzetto","tesi","tesserato","testato","tetro","tettoia","tifare","tigella","timbro","tinto","tipico","tipografo","tiraggio","tiro","titanio","titolo","titubante","tizio","tizzone","toccare","tollerare","tolto","tombola","tomo","tonfo","tonsilla","topazio","topologia","toppa","torba","tornare","torrone","tortora","toscano","tossire","tostatura","totano","trabocco","trachea","trafila","tragedia","tralcio","tramonto","transito","trapano","trarre","trasloco","trattato","trave","treccia","tremolio","trespolo","tributo","tricheco","trifoglio","trillo","trincea","trio","tristezza","triturato","trivella","tromba","trono","troppo","trottola","trovare","truccato","tubatura","tuffato","tulipano","tumulto","tunisia","turbare","turchino","tuta","tutela","ubicato","uccello","uccisore","udire","uditivo","uffa","ufficio","uguale","ulisse","ultimato","umano","umile","umorismo","uncinetto","ungere","ungherese","unicorno","unificato","unisono","unitario","unte","uovo","upupa","uragano","urgenza","urlo","usanza","usato","uscito","usignolo","usuraio","utensile","utilizzo","utopia","vacante","vaccinato","vagabondo","vagliato","valanga","valgo","valico","valletta","valoroso","valutare","valvola","vampata","vangare","vanitoso","vano","vantaggio","vanvera","vapore","varano","varcato","variante","vasca","vedetta","vedova","veduto","vegetale","veicolo","velcro","velina","velluto","veloce","venato","vendemmia","vento","verace","verbale","vergogna","verifica","vero","verruca","verticale","vescica","vessillo","vestale","veterano","vetrina","vetusto","viandante","vibrante","vicenda","vichingo","vicinanza","vidimare","vigilia","vigneto","vigore","vile","villano","vimini","vincitore","viola","vipera","virgola","virologo","virulento","viscoso","visione","vispo","vissuto","visura","vita","vitello","vittima","vivanda","vivido","viziare","voce","voga","volatile","volere","volpe","voragine","vulcano","zampogna","zanna","zappato","zattera","zavorra","zefiro","zelante","zelo","zenzero","zerbino","zibetto","zinco","zircone","zitto","zolla","zotico","zucchero","zufolo","zulu","zuppa"]["あいこくしん","あいさつ","あいだ","あおぞら","あかちゃん","あきる","あけがた","あける","あこがれる","あさい","あさひ","あしあと","あじわう","あずかる","あずき","あそぶ","あたえる","あたためる","あたりまえ","あたる","あつい","あつかう","あっしゅく","あつまり","あつめる","あてな","あてはまる","あひる","あぶら","あぶる","あふれる","あまい","あまど","あまやかす","あまり","あみもの","あめりか","あやまる","あゆむ","あらいぐま","あらし","あらすじ","あらためる","あらゆる","あらわす","ありがとう","あわせる","あわてる","あんい","あんがい","あんこ","あんぜん","あんてい","あんない","あんまり","いいだす","いおん","いがい","いがく","いきおい","いきなり","いきもの","いきる","いくじ","いくぶん","いけばな","いけん","いこう","いこく","いこつ","いさましい","いさん","いしき","いじゅう","いじょう","いじわる","いずみ","いずれ","いせい","いせえび","いせかい","いせき","いぜん","いそうろう","いそがしい","いだい","いだく","いたずら","いたみ","いたりあ","いちおう","いちじ","いちど","いちば","いちぶ","いちりゅう","いつか","いっしゅん","いっせい","いっそう","いったん","いっち","いってい","いっぽう","いてざ","いてん","いどう","いとこ","いない","いなか","いねむり","いのち","いのる","いはつ","いばる","いはん","いびき","いひん","いふく","いへん","いほう","いみん","いもうと","いもたれ","いもり","いやがる","いやす","いよかん","いよく","いらい","いらすと","いりぐち","いりょう","いれい","いれもの","いれる","いろえんぴつ","いわい","いわう","いわかん","いわば","いわゆる","いんげんまめ","いんさつ","いんしょう","いんよう","うえき","うえる","うおざ","うがい","うかぶ","うかべる","うきわ","うくらいな","うくれれ","うけたまわる","うけつけ","うけとる","うけもつ","うける","うごかす","うごく","うこん","うさぎ","うしなう","うしろがみ","うすい","うすぎ","うすぐらい","うすめる","うせつ","うちあわせ","うちがわ","うちき","うちゅう","うっかり","うつくしい","うったえる","うつる","うどん","うなぎ","うなじ","うなずく","うなる","うねる","うのう","うぶげ","うぶごえ","うまれる","うめる","うもう","うやまう","うよく","うらがえす","うらぐち","うらない","うりあげ","うりきれ","うるさい","うれしい","うれゆき","うれる","うろこ","うわき","うわさ","うんこう","うんちん","うんてん","うんどう","えいえん","えいが","えいきょう","えいご","えいせい","えいぶん","えいよう","えいわ","えおり","えがお","えがく","えきたい","えくせる","えしゃく","えすて","えつらん","えのぐ","えほうまき","えほん","えまき","えもじ","えもの","えらい","えらぶ","えりあ","えんえん","えんかい","えんぎ","えんげき","えんしゅう","えんぜつ","えんそく","えんちょう","えんとつ","おいかける","おいこす","おいしい","おいつく","おうえん","おうさま","おうじ","おうせつ","おうたい","おうふく","おうべい","おうよう","おえる","おおい","おおう","おおどおり","おおや","おおよそ","おかえり","おかず","おがむ","おかわり","おぎなう","おきる","おくさま","おくじょう","おくりがな","おくる","おくれる","おこす","おこなう","おこる","おさえる","おさない","おさめる","おしいれ","おしえる","おじぎ","おじさん","おしゃれ","おそらく","おそわる","おたがい","おたく","おだやか","おちつく","おっと","おつり","おでかけ","おとしもの","おとなしい","おどり","おどろかす","おばさん","おまいり","おめでとう","おもいで","おもう","おもたい","おもちゃ","おやつ","おやゆび","およぼす","おらんだ","おろす","おんがく","おんけい","おんしゃ","おんせん","おんだん","おんちゅう","おんどけい","かあつ","かいが","がいき","がいけん","がいこう","かいさつ","かいしゃ","かいすいよく","かいぜん","かいぞうど","かいつう","かいてん","かいとう","かいふく","がいへき","かいほう","かいよう","がいらい","かいわ","かえる","かおり","かかえる","かがく","かがし","かがみ","かくご","かくとく","かざる","がぞう","かたい","かたち","がちょう","がっきゅう","がっこう","がっさん","がっしょう","かなざわし","かのう","がはく","かぶか","かほう","かほご","かまう","かまぼこ","かめれおん","かゆい","かようび","からい","かるい","かろう","かわく","かわら","がんか","かんけい","かんこう","かんしゃ","かんそう","かんたん","かんち","がんばる","きあい","きあつ","きいろ","ぎいん","きうい","きうん","きえる","きおう","きおく","きおち","きおん","きかい","きかく","きかんしゃ","ききて","きくばり","きくらげ","きけんせい","きこう","きこえる","きこく","きさい","きさく","きさま","きさらぎ","ぎじかがく","ぎしき","ぎじたいけん","ぎじにってい","ぎじゅつしゃ","きすう","きせい","きせき","きせつ","きそう","きぞく","きぞん","きたえる","きちょう","きつえん","ぎっちり","きつつき","きつね","きてい","きどう","きどく","きない","きなが","きなこ","きぬごし","きねん","きのう","きのした","きはく","きびしい","きひん","きふく","きぶん","きぼう","きほん","きまる","きみつ","きむずかしい","きめる","きもだめし","きもち","きもの","きゃく","きやく","ぎゅうにく","きよう","きょうりゅう","きらい","きらく","きりん","きれい","きれつ","きろく","ぎろん","きわめる","ぎんいろ","きんかくじ","きんじょ","きんようび","ぐあい","くいず","くうかん","くうき","くうぐん","くうこう","ぐうせい","くうそう","ぐうたら","くうふく","くうぼ","くかん","くきょう","くげん","ぐこう","くさい","くさき","くさばな","くさる","くしゃみ","くしょう","くすのき","くすりゆび","くせげ","くせん","ぐたいてき","くださる","くたびれる","くちこみ","くちさき","くつした","ぐっすり","くつろぐ","くとうてん","くどく","くなん","くねくね","くのう","くふう","くみあわせ","くみたてる","くめる","くやくしょ","くらす","くらべる","くるま","くれる","くろう","くわしい","ぐんかん","ぐんしょく","ぐんたい","ぐんて","けあな","けいかく","けいけん","けいこ","けいさつ","げいじゅつ","けいたい","げいのうじん","けいれき","けいろ","けおとす","けおりもの","げきか","げきげん","げきだん","げきちん","げきとつ","げきは","げきやく","げこう","げこくじょう","げざい","けさき","げざん","けしき","けしごむ","けしょう","げすと","けたば","けちゃっぷ","けちらす","けつあつ","けつい","けつえき","けっこん","けつじょ","けっせき","けってい","けつまつ","げつようび","げつれい","けつろん","げどく","けとばす","けとる","けなげ","けなす","けなみ","けぬき","げねつ","けねん","けはい","げひん","けぶかい","げぼく","けまり","けみかる","けむし","けむり","けもの","けらい","けろけろ","けわしい","けんい","けんえつ","けんお","けんか","げんき","けんげん","けんこう","けんさく","けんしゅう","けんすう","げんそう","けんちく","けんてい","けんとう","けんない","けんにん","げんぶつ","けんま","けんみん","けんめい","けんらん","けんり","こあくま","こいぬ","こいびと","ごうい","こうえん","こうおん","こうかん","ごうきゅう","ごうけい","こうこう","こうさい","こうじ","こうすい","ごうせい","こうそく","こうたい","こうちゃ","こうつう","こうてい","こうどう","こうない","こうはい","ごうほう","ごうまん","こうもく","こうりつ","こえる","こおり","ごかい","ごがつ","ごかん","こくご","こくさい","こくとう","こくない","こくはく","こぐま","こけい","こける","ここのか","こころ","こさめ","こしつ","こすう","こせい","こせき","こぜん","こそだて","こたい","こたえる","こたつ","こちょう","こっか","こつこつ","こつばん","こつぶ","こてい","こてん","ことがら","ことし","ことば","ことり","こなごな","こねこね","このまま","このみ","このよ","ごはん","こひつじ","こふう","こふん","こぼれる","ごまあぶら","こまかい","ごますり","こまつな","こまる","こむぎこ","こもじ","こもち","こもの","こもん","こやく","こやま","こゆう","こゆび","こよい","こよう","こりる","これくしょん","ころっけ","こわもて","こわれる","こんいん","こんかい","こんき","こんしゅう","こんすい","こんだて","こんとん","こんなん","こんびに","こんぽん","こんまけ","こんや","こんれい","こんわく","ざいえき","さいかい","さいきん","ざいげん","ざいこ","さいしょ","さいせい","ざいたく","ざいちゅう","さいてき","ざいりょう","さうな","さかいし","さがす","さかな","さかみち","さがる","さぎょう","さくし","さくひん","さくら","さこく","さこつ","さずかる","ざせき","さたん","さつえい","ざつおん","ざっか","ざつがく","さっきょく","ざっし","さつじん","ざっそう","さつたば","さつまいも","さてい","さといも","さとう","さとおや","さとし","さとる","さのう","さばく","さびしい","さべつ","さほう","さほど","さます","さみしい","さみだれ","さむけ","さめる","さやえんどう","さゆう","さよう","さよく","さらだ","ざるそば","さわやか","さわる","さんいん","さんか","さんきゃく","さんこう","さんさい","ざんしょ","さんすう","さんせい","さんそ","さんち","さんま","さんみ","さんらん","しあい","しあげ","しあさって","しあわせ","しいく","しいん","しうち","しえい","しおけ","しかい","しかく","じかん","しごと","しすう","じだい","したうけ","したぎ","したて","したみ","しちょう","しちりん","しっかり","しつじ","しつもん","してい","してき","してつ","じてん","じどう","しなぎれ","しなもの","しなん","しねま","しねん","しのぐ","しのぶ","しはい","しばかり","しはつ","しはらい","しはん","しひょう","しふく","じぶん","しへい","しほう","しほん","しまう","しまる","しみん","しむける","じむしょ","しめい","しめる","しもん","しゃいん","しゃうん","しゃおん","じゃがいも","しやくしょ","しゃくほう","しゃけん","しゃこ","しゃざい","しゃしん","しゃせん","しゃそう","しゃたい","しゃちょう","しゃっきん","じゃま","しゃりん","しゃれい","じゆう","じゅうしょ","しゅくはく","じゅしん","しゅっせき","しゅみ","しゅらば","じゅんばん","しょうかい","しょくたく","しょっけん","しょどう","しょもつ","しらせる","しらべる","しんか","しんこう","じんじゃ","しんせいじ","しんちく","しんりん","すあげ","すあし","すあな","ずあん","すいえい","すいか","すいとう","ずいぶん","すいようび","すうがく","すうじつ","すうせん","すおどり","すきま","すくう","すくない","すける","すごい","すこし","ずさん","すずしい","すすむ","すすめる","すっかり","ずっしり","ずっと","すてき","すてる","すねる","すのこ","すはだ","すばらしい","ずひょう","ずぶぬれ","すぶり","すふれ","すべて","すべる","ずほう","すぼん","すまい","すめし","すもう","すやき","すらすら","するめ","すれちがう","すろっと","すわる","すんぜん","すんぽう","せあぶら","せいかつ","せいげん","せいじ","せいよう","せおう","せかいかん","せきにん","せきむ","せきゆ","せきらんうん","せけん","せこう","せすじ","せたい","せたけ","せっかく","せっきゃく","ぜっく","せっけん","せっこつ","せっさたくま","せつぞく","せつだん","せつでん","せっぱん","せつび","せつぶん","せつめい","せつりつ","せなか","せのび","せはば","せびろ","せぼね","せまい","せまる","せめる","せもたれ","せりふ","ぜんあく","せんい","せんえい","せんか","せんきょ","せんく","せんげん","ぜんご","せんさい","せんしゅ","せんすい","せんせい","せんぞ","せんたく","せんちょう","せんてい","せんとう","せんぬき","せんねん","せんぱい","ぜんぶ","ぜんぽう","せんむ","せんめんじょ","せんもん","せんやく","せんゆう","せんよう","ぜんら","ぜんりゃく","せんれい","せんろ","そあく","そいとげる","そいね","そうがんきょう","そうき","そうご","そうしん","そうだん","そうなん","そうび","そうめん","そうり","そえもの","そえん","そがい","そげき","そこう","そこそこ","そざい","そしな","そせい","そせん","そそぐ","そだてる","そつう","そつえん","そっかん","そつぎょう","そっけつ","そっこう","そっせん","そっと","そとがわ","そとづら","そなえる","そなた","そふぼ","そぼく","そぼろ","そまつ","そまる","そむく","そむりえ","そめる","そもそも","そよかぜ","そらまめ","そろう","そんかい","そんけい","そんざい","そんしつ","そんぞく","そんちょう","ぞんび","ぞんぶん","そんみん","たあい","たいいん","たいうん","たいえき","たいおう","だいがく","たいき","たいぐう","たいけん","たいこ","たいざい","だいじょうぶ","だいすき","たいせつ","たいそう","だいたい","たいちょう","たいてい","だいどころ","たいない","たいねつ","たいのう","たいはん","だいひょう","たいふう","たいへん","たいほ","たいまつばな","たいみんぐ","たいむ","たいめん","たいやき","たいよう","たいら","たいりょく","たいる","たいわん","たうえ","たえる","たおす","たおる","たおれる","たかい","たかね","たきび","たくさん","たこく","たこやき","たさい","たしざん","だじゃれ","たすける","たずさわる","たそがれ","たたかう","たたく","ただしい","たたみ","たちばな","だっかい","だっきゃく","だっこ","だっしゅつ","だったい","たてる","たとえる","たなばた","たにん","たぬき","たのしみ","たはつ","たぶん","たべる","たぼう","たまご","たまる","だむる","ためいき","ためす","ためる","たもつ","たやすい","たよる","たらす","たりきほんがん","たりょう","たりる","たると","たれる","たれんと","たろっと","たわむれる","だんあつ","たんい","たんおん","たんか","たんき","たんけん","たんご","たんさん","たんじょうび","だんせい","たんそく","たんたい","だんち","たんてい","たんとう","だんな","たんにん","だんねつ","たんのう","たんぴん","だんぼう","たんまつ","たんめい","だんれつ","だんろ","だんわ","ちあい","ちあん","ちいき","ちいさい","ちえん","ちかい","ちから","ちきゅう","ちきん","ちけいず","ちけん","ちこく","ちさい","ちしき","ちしりょう","ちせい","ちそう","ちたい","ちたん","ちちおや","ちつじょ","ちてき","ちてん","ちぬき","ちぬり","ちのう","ちひょう","ちへいせん","ちほう","ちまた","ちみつ","ちみどろ","ちめいど","ちゃんこなべ","ちゅうい","ちゆりょく","ちょうし","ちょさくけん","ちらし","ちらみ","ちりがみ","ちりょう","ちるど","ちわわ","ちんたい","ちんもく","ついか","ついたち","つうか","つうじょう","つうはん","つうわ","つかう","つかれる","つくね","つくる","つけね","つける","つごう","つたえる","つづく","つつじ","つつむ","つとめる","つながる","つなみ","つねづね","つのる","つぶす","つまらない","つまる","つみき","つめたい","つもり","つもる","つよい","つるぼ","つるみく","つわもの","つわり","てあし","てあて","てあみ","ていおん","ていか","ていき","ていけい","ていこく","ていさつ","ていし","ていせい","ていたい","ていど","ていねい","ていひょう","ていへん","ていぼう","てうち","ておくれ","てきとう","てくび","でこぼこ","てさぎょう","てさげ","てすり","てそう","てちがい","てちょう","てつがく","てつづき","でっぱ","てつぼう","てつや","でぬかえ","てぬき","てぬぐい","てのひら","てはい","てぶくろ","てふだ","てほどき","てほん","てまえ","てまきずし","てみじか","てみやげ","てらす","てれび","てわけ","てわたし","でんあつ","てんいん","てんかい","てんき","てんぐ","てんけん","てんごく","てんさい","てんし","てんすう","でんち","てんてき","てんとう","てんない","てんぷら","てんぼうだい","てんめつ","てんらんかい","でんりょく","でんわ","どあい","といれ","どうかん","とうきゅう","どうぐ","とうし","とうむぎ","とおい","とおか","とおく","とおす","とおる","とかい","とかす","ときおり","ときどき","とくい","とくしゅう","とくてん","とくに","とくべつ","とけい","とける","とこや","とさか","としょかん","とそう","とたん","とちゅう","とっきゅう","とっくん","とつぜん","とつにゅう","とどける","ととのえる","とない","となえる","となり","とのさま","とばす","どぶがわ","とほう","とまる","とめる","ともだち","ともる","どようび","とらえる","とんかつ","どんぶり","ないかく","ないこう","ないしょ","ないす","ないせん","ないそう","なおす","ながい","なくす","なげる","なこうど","なさけ","なたでここ","なっとう","なつやすみ","ななおし","なにごと","なにもの","なにわ","なのか","なふだ","なまいき","なまえ","なまみ","なみだ","なめらか","なめる","なやむ","ならう","ならび","ならぶ","なれる","なわとび","なわばり","にあう","にいがた","にうけ","におい","にかい","にがて","にきび","にくしみ","にくまん","にげる","にさんかたんそ","にしき","にせもの","にちじょう","にちようび","にっか","にっき","にっけい","にっこう","にっさん","にっしょく","にっすう","にっせき","にってい","になう","にほん","にまめ","にもつ","にやり","にゅういん","にりんしゃ","にわとり","にんい","にんか","にんき","にんげん","にんしき","にんずう","にんそう","にんたい","にんち","にんてい","にんにく","にんぷ","にんまり","にんむ","にんめい","にんよう","ぬいくぎ","ぬかす","ぬぐいとる","ぬぐう","ぬくもり","ぬすむ","ぬまえび","ぬめり","ぬらす","ぬんちゃく","ねあげ","ねいき","ねいる","ねいろ","ねぐせ","ねくたい","ねくら","ねこぜ","ねこむ","ねさげ","ねすごす","ねそべる","ねだん","ねつい","ねっしん","ねつぞう","ねったいぎょ","ねぶそく","ねふだ","ねぼう","ねほりはほり","ねまき","ねまわし","ねみみ","ねむい","ねむたい","ねもと","ねらう","ねわざ","ねんいり","ねんおし","ねんかん","ねんきん","ねんぐ","ねんざ","ねんし","ねんちゃく","ねんど","ねんぴ","ねんぶつ","ねんまつ","ねんりょう","ねんれい","のいず","のおづま","のがす","のきなみ","のこぎり","のこす","のこる","のせる","のぞく","のぞむ","のたまう","のちほど","のっく","のばす","のはら","のべる","のぼる","のみもの","のやま","のらいぬ","のらねこ","のりもの","のりゆき","のれん","のんき","ばあい","はあく","ばあさん","ばいか","ばいく","はいけん","はいご","はいしん","はいすい","はいせん","はいそう","はいち","ばいばい","はいれつ","はえる","はおる","はかい","ばかり","はかる","はくしゅ","はけん","はこぶ","はさみ","はさん","はしご","ばしょ","はしる","はせる","ぱそこん","はそん","はたん","はちみつ","はつおん","はっかく","はづき","はっきり","はっくつ","はっけん","はっこう","はっさん","はっしん","はったつ","はっちゅう","はってん","はっぴょう","はっぽう","はなす","はなび","はにかむ","はぶらし","はみがき","はむかう","はめつ","はやい","はやし","はらう","はろうぃん","はわい","はんい","はんえい","はんおん","はんかく","はんきょう","ばんぐみ","はんこ","はんしゃ","はんすう","はんだん","ぱんち","ぱんつ","はんてい","はんとし","はんのう","はんぱ","はんぶん","はんぺん","はんぼうき","はんめい","はんらん","はんろん","ひいき","ひうん","ひえる","ひかく","ひかり","ひかる","ひかん","ひくい","ひけつ","ひこうき","ひこく","ひさい","ひさしぶり","ひさん","びじゅつかん","ひしょ","ひそか","ひそむ","ひたむき","ひだり","ひたる","ひつぎ","ひっこし","ひっし","ひつじゅひん","ひっす","ひつぜん","ぴったり","ぴっちり","ひつよう","ひてい","ひとごみ","ひなまつり","ひなん","ひねる","ひはん","ひびく","ひひょう","ひほう","ひまわり","ひまん","ひみつ","ひめい","ひめじし","ひやけ","ひやす","ひよう","びょうき","ひらがな","ひらく","ひりつ","ひりょう","ひるま","ひるやすみ","ひれい","ひろい","ひろう","ひろき","ひろゆき","ひんかく","ひんけつ","ひんこん","ひんしゅ","ひんそう","ぴんち","ひんぱん","びんぼう","ふあん","ふいうち","ふうけい","ふうせん","ぷうたろう","ふうとう","ふうふ","ふえる","ふおん","ふかい","ふきん","ふくざつ","ふくぶくろ","ふこう","ふさい","ふしぎ","ふじみ","ふすま","ふせい","ふせぐ","ふそく","ぶたにく","ふたん","ふちょう","ふつう","ふつか","ふっかつ","ふっき","ふっこく","ぶどう","ふとる","ふとん","ふのう","ふはい","ふひょう","ふへん","ふまん","ふみん","ふめつ","ふめん","ふよう","ふりこ","ふりる","ふるい","ふんいき","ぶんがく","ぶんぐ","ふんしつ","ぶんせき","ふんそう","ぶんぽう","へいあん","へいおん","へいがい","へいき","へいげん","へいこう","へいさ","へいしゃ","へいせつ","へいそ","へいたく","へいてん","へいねつ","へいわ","へきが","へこむ","べにいろ","べにしょうが","へらす","へんかん","べんきょう","べんごし","へんさい","へんたい","べんり","ほあん","ほいく","ぼうぎょ","ほうこく","ほうそう","ほうほう","ほうもん","ほうりつ","ほえる","ほおん","ほかん","ほきょう","ぼきん","ほくろ","ほけつ","ほけん","ほこう","ほこる","ほしい","ほしつ","ほしゅ","ほしょう","ほせい","ほそい","ほそく","ほたて","ほたる","ぽちぶくろ","ほっきょく","ほっさ","ほったん","ほとんど","ほめる","ほんい","ほんき","ほんけ","ほんしつ","ほんやく","まいにち","まかい","まかせる","まがる","まける","まこと","まさつ","まじめ","ますく","まぜる","まつり","まとめ","まなぶ","まぬけ","まねく","まほう","まもる","まゆげ","まよう","まろやか","まわす","まわり","まわる","まんが","まんきつ","まんぞく","まんなか","みいら","みうち","みえる","みがく","みかた","みかん","みけん","みこん","みじかい","みすい","みすえる","みせる","みっか","みつかる","みつける","みてい","みとめる","みなと","みなみかさい","みねらる","みのう","みのがす","みほん","みもと","みやげ","みらい","みりょく","みわく","みんか","みんぞく","むいか","むえき","むえん","むかい","むかう","むかえ","むかし","むぎちゃ","むける","むげん","むさぼる","むしあつい","むしば","むじゅん","むしろ","むすう","むすこ","むすぶ","むすめ","むせる","むせん","むちゅう","むなしい","むのう","むやみ","むよう","むらさき","むりょう","むろん","めいあん","めいうん","めいえん","めいかく","めいきょく","めいさい","めいし","めいそう","めいぶつ","めいれい","めいわく","めぐまれる","めざす","めした","めずらしい","めだつ","めまい","めやす","めんきょ","めんせき","めんどう","もうしあげる","もうどうけん","もえる","もくし","もくてき","もくようび","もちろん","もどる","もらう","もんく","もんだい","やおや","やける","やさい","やさしい","やすい","やすたろう","やすみ","やせる","やそう","やたい","やちん","やっと","やっぱり","やぶる","やめる","ややこしい","やよい","やわらかい","ゆうき","ゆうびんきょく","ゆうべ","ゆうめい","ゆけつ","ゆしゅつ","ゆせん","ゆそう","ゆたか","ゆちゃく","ゆでる","ゆにゅう","ゆびわ","ゆらい","ゆれる","ようい","ようか","ようきゅう","ようじ","ようす","ようちえん","よかぜ","よかん","よきん","よくせい","よくぼう","よけい","よごれる","よさん","よしゅう","よそう","よそく","よっか","よてい","よどがわく","よねつ","よやく","よゆう","よろこぶ","よろしい","らいう","らくがき","らくご","らくさつ","らくだ","らしんばん","らせん","らぞく","らたい","らっか","られつ","りえき","りかい","りきさく","りきせつ","りくぐん","りくつ","りけん","りこう","りせい","りそう","りそく","りてん","りねん","りゆう","りゅうがく","りよう","りょうり","りょかん","りょくちゃ","りょこう","りりく","りれき","りろん","りんご","るいけい","るいさい","るいじ","るいせき","るすばん","るりがわら","れいかん","れいぎ","れいせい","れいぞうこ","れいとう","れいぼう","れきし","れきだい","れんあい","れんけい","れんこん","れんさい","れんしゅう","れんぞく","れんらく","ろうか","ろうご","ろうじん","ろうそく","ろくが","ろこつ","ろじうら","ろしゅつ","ろせん","ろてん","ろめん","ろれつ","ろんぎ","ろんぱ","ろんぶん","ろんり","わかす","わかめ","わかやま","わかれる","わしつ","わじまし","わすれもの","わらう","われる"]["가격","가끔","가난","가능","가득","가르침","가뭄","가방","가상","가슴","가운데","가을","가이드","가입","가장","가정","가족","가죽","각오","각자","간격","간부","간섭","간장","간접","간판","갈등","갈비","갈색","갈증","감각","감기","감소","감수성","감자","감정","갑자기","강남","강당","강도","강력히","강변","강북","강사","강수량","강아지","강원도","강의","강제","강조","같이","개구리","개나리","개방","개별","개선","개성","개인","객관적","거실","거액","거울","거짓","거품","걱정","건강","건물","건설","건조","건축","걸음","검사","검토","게시판","게임","겨울","견해","결과","결국","결론","결석","결승","결심","결정","결혼","경계","경고","경기","경력","경복궁","경비","경상도","경영","경우","경쟁","경제","경주","경찰","경치","경향","경험","계곡","계단","계란","계산","계속","계약","계절","계층","계획","고객","고구려","고궁","고급","고등학생","고무신","고민","고양이","고장","고전","고집","고춧가루","고통","고향","곡식","골목","골짜기","골프","공간","공개","공격","공군","공급","공기","공동","공무원","공부","공사","공식","공업","공연","공원","공장","공짜","공책","공통","공포","공항","공휴일","과목","과일","과장","과정","과학","관객","관계","관광","관념","관람","관련","관리","관습","관심","관점","관찰","광경","광고","광장","광주","괴로움","굉장히","교과서","교문","교복","교실","교양","교육","교장","교직","교통","교환","교훈","구경","구름","구멍","구별","구분","구석","구성","구속","구역","구입","구청","구체적","국가","국기","국내","국립","국물","국민","국수","국어","국왕","국적","국제","국회","군대","군사","군인","궁극적","권리","권위","권투","귀국","귀신","규정","규칙","균형","그날","그냥","그늘","그러나","그룹","그릇","그림","그제서야","그토록","극복","극히","근거","근교","근래","근로","근무","근본","근원","근육","근처","글씨","글자","금강산","금고","금년","금메달","금액","금연","금요일","금지","긍정적","기간","기관","기념","기능","기독교","기둥","기록","기름","기법","기본","기분","기쁨","기숙사","기술","기억","기업","기온","기운","기원","기적","기준","기침","기혼","기획","긴급","긴장","길이","김밥","김치","김포공항","깍두기","깜빡","깨달음","깨소금","껍질","꼭대기","꽃잎","나들이","나란히","나머지","나물","나침반","나흘","낙엽","난방","날개","날씨","날짜","남녀","남대문","남매","남산","남자","남편","남학생","낭비","낱말","내년","내용","내일","냄비","냄새","냇물","냉동","냉면","냉방","냉장고","넥타이","넷째","노동","노란색","노력","노인","녹음","녹차","녹화","논리","논문","논쟁","놀이","농구","농담","농민","농부","농업","농장","농촌","높이","눈동자","눈물","눈썹","뉴욕","느낌","늑대","능동적","능력","다방","다양성","다음","다이어트","다행","단계","단골","단독","단맛","단순","단어","단위","단점","단체","단추","단편","단풍","달걀","달러","달력","달리","닭고기","담당","담배","담요","담임","답변","답장","당근","당분간","당연히","당장","대규모","대낮","대단히","대답","대도시","대략","대량","대륙","대문","대부분","대신","대응","대장","대전","대접","대중","대책","대출","대충","대통령","대학","대한민국","대합실","대형","덩어리","데이트","도대체","도덕","도둑","도망","도서관","도심","도움","도입","도자기","도저히","도전","도중","도착","독감","독립","독서","독일","독창적","동화책","뒷모습","뒷산","딸아이","마누라","마늘","마당","마라톤","마련","마무리","마사지","마약","마요네즈","마을","마음","마이크","마중","마지막","마찬가지","마찰","마흔","막걸리","막내","막상","만남","만두","만세","만약","만일","만점","만족","만화","많이","말기","말씀","말투","맘대로","망원경","매년","매달","매력","매번","매스컴","매일","매장","맥주","먹이","먼저","먼지","멀리","메일","며느리","며칠","면담","멸치","명단","명령","명예","명의","명절","명칭","명함","모금","모니터","모델","모든","모범","모습","모양","모임","모조리","모집","모퉁이","목걸이","목록","목사","목소리","목숨","목적","목표","몰래","몸매","몸무게","몸살","몸속","몸짓","몸통","몹시","무관심","무궁화","무더위","무덤","무릎","무슨","무엇","무역","무용","무조건","무지개","무척","문구","문득","문법","문서","문제","문학","문화","물가","물건","물결","물고기","물론","물리학","물음","물질","물체","미국","미디어","미사일","미술","미역","미용실","미움","미인","미팅","미혼","민간","민족","민주","믿음","밀가루","밀리미터","밑바닥","바가지","바구니","바나나","바늘","바닥","바닷가","바람","바이러스","바탕","박물관","박사","박수","반대","반드시","반말","반발","반성","반응","반장","반죽","반지","반찬","받침","발가락","발걸음","발견","발달","발레","발목","발바닥","발생","발음","발자국","발전","발톱","발표","밤하늘","밥그릇","밥맛","밥상","밥솥","방금","방면","방문","방바닥","방법","방송","방식","방안","방울","방지","방학","방해","방향","배경","배꼽","배달","배드민턴","백두산","백색","백성","백인","백제","백화점","버릇","버섯","버튼","번개","번역","번지","번호","벌금","벌레","벌써","범위","범인","범죄","법률","법원","법적","법칙","베이징","벨트","변경","변동","변명","변신","변호사","변화","별도","별명","별일","병실","병아리","병원","보관","보너스","보라색","보람","보름","보상","보안","보자기","보장","보전","보존","보통","보편적","보험","복도","복사","복숭아","복습","볶음","본격적","본래","본부","본사","본성","본인","본질","볼펜","봉사","봉지","봉투","부근","부끄러움","부담","부동산","부문","부분","부산","부상","부엌","부인","부작용","부장","부정","부족","부지런히","부친","부탁","부품","부회장","북부","북한","분노","분량","분리","분명","분석","분야","분위기","분필","분홍색","불고기","불과","불교","불꽃","불만","불법","불빛","불안","불이익","불행","브랜드","비극","비난","비닐","비둘기","비디오","비로소","비만","비명","비밀","비바람","비빔밥","비상","비용","비율","비중","비타민","비판","빌딩","빗물","빗방울","빗줄기","빛깔","빨간색","빨래","빨리","사건","사계절","사나이","사냥","사람","사랑","사립","사모님","사물","사방","사상","사생활","사설","사슴","사실","사업","사용","사월","사장","사전","사진","사촌","사춘기","사탕","사투리","사흘","산길","산부인과","산업","산책","살림","살인","살짝","삼계탕","삼국","삼십","삼월","삼촌","상관","상금","상대","상류","상반기","상상","상식","상업","상인","상자","상점","상처","상추","상태","상표","상품","상황","새벽","색깔","색연필","생각","생명","생물","생방송","생산","생선","생신","생일","생활","서랍","서른","서명","서민","서비스","서양","서울","서적","서점","서쪽","서클","석사","석유","선거","선물","선배","선생","선수","선원","선장","선전","선택","선풍기","설거지","설날","설렁탕","설명","설문","설사","설악산","설치","설탕","섭씨","성공","성당","성명","성별","성인","성장","성적","성질","성함","세금","세미나","세상","세월","세종대왕","세탁","센터","센티미터","셋째","소규모","소극적","소금","소나기","소년","소득","소망","소문","소설","소속","소아과","소용","소원","소음","소중히","소지품","소질","소풍","소형","속담","속도","속옷","손가락","손길","손녀","손님","손등","손목","손뼉","손실","손질","손톱","손해","솔직히","솜씨","송아지","송이","송편","쇠고기","쇼핑","수건","수년","수단","수돗물","수동적","수면","수명","수박","수상","수석","수술","수시로","수업","수염","수영","수입","수준","수집","수출","수컷","수필","수학","수험생","수화기","숙녀","숙소","숙제","순간","순서","순수","순식간","순위","숟가락","술병","술집","숫자","스님","스물","스스로","스승","스웨터","스위치","스케이트","스튜디오","스트레스","스포츠","슬쩍","슬픔","습관","습기","승객","승리","승부","승용차","승진","시각","시간","시골","시금치","시나리오","시댁","시리즈","시멘트","시민","시부모","시선","시설","시스템","시아버지","시어머니","시월","시인","시일","시작","시장","시절","시점","시중","시즌","시집","시청","시합","시험","식구","식기","식당","식량","식료품","식물","식빵","식사","식생활","식초","식탁","식품","신고","신규","신념","신문","신발","신비","신사","신세","신용","신제품","신청","신체","신화","실감","실내","실력","실례","실망","실수","실습","실시","실장","실정","실질적","실천","실체","실컷","실태","실패","실험","실현","심리","심부름","심사","심장","심정","심판","쌍둥이","씨름","씨앗","아가씨","아나운서","아드님","아들","아쉬움","아스팔트","아시아","아울러","아저씨","아줌마","아직","아침","아파트","아프리카","아픔","아홉","아흔","악기","악몽","악수","안개","안경","안과","안내","안녕","안동","안방","안부","안주","알루미늄","알코올","암시","암컷","압력","앞날","앞문","애인","애정","액수","앨범","야간","야단","야옹","약간","약국","약속","약수","약점","약품","약혼녀","양념","양력","양말","양배추","양주","양파","어둠","어려움","어른","어젯밤","어쨌든","어쩌다가","어쩐지","언니","언덕","언론","언어","얼굴","얼른","얼음","얼핏","엄마","업무","업종","업체","엉덩이","엉망","엉터리","엊그제","에너지","에어컨","엔진","여건","여고생","여관","여군","여권","여대생","여덟","여동생","여든","여론","여름","여섯","여성","여왕","여인","여전히","여직원","여학생","여행","역사","역시","역할","연결","연구","연극","연기","연락","연설","연세","연속","연습","연애","연예인","연인","연장","연주","연출","연필","연합","연휴","열기","열매","열쇠","열심히","열정","열차","열흘","염려","엽서","영국","영남","영상","영양","영역","영웅","영원히","영하","영향","영혼","영화","옆구리","옆방","옆집","예감","예금","예방","예산","예상","예선","예술","예습","예식장","예약","예전","예절","예정","예컨대","옛날","오늘","오락","오랫동안","오렌지","오로지","오른발","오븐","오십","오염","오월","오전","오직","오징어","오페라","오피스텔","오히려","옥상","옥수수","온갖","온라인","온몸","온종일","온통","올가을","올림픽","올해","옷차림","와이셔츠","와인","완성","완전","왕비","왕자","왜냐하면","왠지","외갓집","외국","외로움","외삼촌","외출","외침","외할머니","왼발","왼손","왼쪽","요금","요일","요즘","요청","용기","용서","용어","우산","우선","우승","우연히","우정","우체국","우편","운동","운명","운반","운전","운행","울산","울음","움직임","웃어른","웃음","워낙","원고","원래","원서","원숭이","원인","원장","원피스","월급","월드컵","월세","월요일","웨이터","위반","위법","위성","위원","위험","위협","윗사람","유난히","유럽","유명","유물","유산","유적","유치원","유학","유행","유형","육군","육상","육십","육체","은행","음력","음료","음반","음성","음식","음악","음주","의견","의논","의문","의복","의식","의심","의외로","의욕","의원","의학","이것","이곳","이념","이놈","이달","이대로","이동","이렇게","이력서","이론적","이름","이민","이발소","이별","이불","이빨","이상","이성","이슬","이야기","이용","이웃","이월","이윽고","이익","이전","이중","이튿날","이틀","이혼","인간","인격","인공","인구","인근","인기","인도","인류","인물","인생","인쇄","인연","인원","인재","인종","인천","인체","인터넷","인하","인형","일곱","일기","일단","일대","일등","일반","일본","일부","일상","일생","일손","일요일","일월","일정","일종","일주일","일찍","일체","일치","일행","일회용","임금","임무","입대","입력","입맛","입사","입술","입시","입원","입장","입학","자가용","자격","자극","자동","자랑","자부심","자식","자신","자연","자원","자율","자전거","자정","자존심","자판","작가","작년","작성","작업","작용","작은딸","작품","잔디","잔뜩","잔치","잘못","잠깐","잠수함","잠시","잠옷","잠자리","잡지","장관","장군","장기간","장래","장례","장르","장마","장면","장모","장미","장비","장사","장소","장식","장애인","장인","장점","장차","장학금","재능","재빨리","재산","재생","재작년","재정","재채기","재판","재학","재활용","저것","저고리","저곳","저녁","저런","저렇게","저번","저울","저절로","저축","적극","적당히","적성","적용","적응","전개","전공","전기","전달","전라도","전망","전문","전반","전부","전세","전시","전용","전자","전쟁","전주","전철","전체","전통","전혀","전후","절대","절망","절반","절약","절차","점검","점수","점심","점원","점점","점차","접근","접시","접촉","젓가락","정거장","정도","정류장","정리","정말","정면","정문","정반대","정보","정부","정비","정상","정성","정오","정원","정장","정지","정치","정확히","제공","제과점","제대로","제목","제발","제법","제삿날","제안","제일","제작","제주도","제출","제품","제한","조각","조건","조금","조깅","조명","조미료","조상","조선","조용히","조절","조정","조직","존댓말","존재","졸업","졸음","종교","종로","종류","종소리","종업원","종종","종합","좌석","죄인","주관적","주름","주말","주머니","주먹","주문","주민","주방","주변","주식","주인","주일","주장","주전자","주택","준비","줄거리","줄기","줄무늬","중간","중계방송","중국","중년","중단","중독","중반","중부","중세","중소기업","중순","중앙","중요","중학교","즉석","즉시","즐거움","증가","증거","증권","증상","증세","지각","지갑","지경","지극히","지금","지급","지능","지름길","지리산","지방","지붕","지식","지역","지우개","지원","지적","지점","지진","지출","직선","직업","직원","직장","진급","진동","진로","진료","진리","진짜","진찰","진출","진통","진행","질문","질병","질서","짐작","집단","집안","집중","짜증","찌꺼기","차남","차라리","차량","차림","차별","차선","차츰","착각","찬물","찬성","참가","참기름","참새","참석","참여","참외","참조","찻잔","창가","창고","창구","창문","창밖","창작","창조","채널","채점","책가방","책방","책상","책임","챔피언","처벌","처음","천국","천둥","천장","천재","천천히","철도","철저히","철학","첫날","첫째","청년","청바지","청소","청춘","체계","체력","체온","체육","체중","체험","초등학생","초반","초밥","초상화","초순","초여름","초원","초저녁","초점","초청","초콜릿","촛불","총각","총리","총장","촬영","최근","최상","최선","최신","최악","최종","추석","추억","추진","추천","추측","축구","축소","축제","축하","출근","출발","출산","출신","출연","출입","출장","출판","충격","충고","충돌","충분히","충청도","취업","취직","취향","치약","친구","친척","칠십","칠월","칠판","침대","침묵","침실","칫솔","칭찬","카메라","카운터","칼국수","캐릭터","캠퍼스","캠페인","커튼","컨디션","컬러","컴퓨터","코끼리","코미디","콘서트","콜라","콤플렉스","콩나물","쾌감","쿠데타","크림","큰길","큰딸","큰소리","큰아들","큰어머니","큰일","큰절","클래식","클럽","킬로","타입","타자기","탁구","탁자","탄생","태권도","태양","태풍","택시","탤런트","터널","터미널","테니스","테스트","테이블","텔레비전","토론","토마토","토요일","통계","통과","통로","통신","통역","통일","통장","통제","통증","통합","통화","퇴근","퇴원","퇴직금","튀김","트럭","특급","특별","특성","특수","특징","특히","튼튼히","티셔츠","파란색","파일","파출소","판결","판단","판매","판사","팔십","팔월","팝송","패션","팩스","팩시밀리","팬티","퍼센트","페인트","편견","편의","편지","편히","평가","평균","평생","평소","평양","평일","평화","포스터","포인트","포장","포함","표면","표정","표준","표현","품목","품질","풍경","풍속","풍습","프랑스","프린터","플라스틱","피곤","피망","피아노","필름","필수","필요","필자","필통","핑계","하느님","하늘","하드웨어","하룻밤","하반기","하숙집","하순","하여튼","하지만","하천","하품","하필","학과","학교","학급","학기","학년","학력","학번","학부모","학비","학생","학술","학습","학용품","학원","학위","학자","학점","한계","한글","한꺼번에","한낮","한눈","한동안","한때","한라산","한마디","한문","한번","한복","한식","한여름","한쪽","할머니","할아버지","할인","함께","함부로","합격","합리적","항공","항구","항상","항의","해결","해군","해답","해당","해물","해석","해설","해수욕장","해안","핵심","핸드백","햄버거","햇볕","햇살","행동","행복","행사","행운","행위","향기","향상","향수","허락","허용","헬기","현관","현금","현대","현상","현실","현장","현재","현지","혈액","협력","형부","형사","형수","형식","형제","형태","형편","혜택","호기심","호남","호랑이","호박","호텔","호흡","혹시","홀로","홈페이지","홍보","홍수","홍차","화면","화분","화살","화요일","화장","화학","확보","확인","확장","확정","환갑","환경","환영","환율","환자","활기","활동","활발히","활용","활짝","회견","회관","회복","회색","회원","회장","회전","횟수","횡단보도","효율적","후반","후춧가루","훈련","훨씬","휴식","휴일","흉내","흐름","흑백","흑인","흔적","흔히","흥미","흥분","희곡","희망","희생","흰색","힘껏"]{"的":["chinese_simplified","chinese_traditional"],"一":["chinese_simplified","chinese_traditional"],"是":["chinese_simplified","chinese_traditional"],"在":["chinese_simplified","chinese_traditional"],"不":["chinese_simplified","chinese_traditional"],"了":["chinese_simplified","chinese_traditional"],"有":["chinese_simplified","chinese_traditional"],"和":["chinese_simplified","chinese_traditional"],"人":["chinese_simplified","chinese_traditional"],"这":["chinese_simplified"],"中":["chinese_simplified","chinese_traditional"],"大":["chinese_simplified","chinese_traditional"],"为":["chinese_simplified"],"上":["chinese_simplified","chinese_traditional"],"个":["chinese_simplified"],"国":["chinese_simplified"],"我":["chinese_simplified","chinese_traditional"],"以":["chinese_simplified","chinese_traditional"],"要":["chinese_simplified","chinese_traditional"],"他":["chinese_simplified","chinese_traditional"],"时":["chinese_simplified"],"来":["chinese_simplified"],"用":["chinese_simplified","chinese_traditional"],"们":["chinese_simplified"],"生":["chinese_simplified","chinese_traditional"],"到":["chinese_simplified","chinese_traditional"],"作":["chinese_simplified","chinese_traditional"],"地":["chinese_simplified","chinese_traditional"],"于":["chinese_simplified"],"出":["chinese_simplified","chinese_traditional"],"就":["chinese_simplified","chinese_traditional"],"分":["chinese_simplified","chinese_traditional"],"对":["chinese_simplified"],"成":["chinese_simplified","chinese_traditional"],"会":["chinese_simplified"],"可":["chinese_simplified","chinese_traditional"],"主":["chinese_simplified","chinese_traditional"],"发":["chinese_simplified"],"年":["chinese_simplified","chinese_traditional"],"动":["chinese_simplified"],"同":["chinese_simplified","chinese_traditional"],"工":["chinese_simplified","chinese_traditional"],"也":["chinese_simplified","chinese_traditional"],"能":["chinese_simplified","chinese_traditional"],"下":["chinese_simplified","chinese_traditional"],"过":["chinese_simplified"],"子":["chinese_simplified","chinese_traditional"],"说":["chinese_simplified"],"产":["chinese_simplified"],"种":["chinese_simplified"],"面":["chinese_simplified","chinese_traditional"],"而":["chinese_simplified","chinese_traditional"],"方":["chinese_simplified","chinese_traditional"],"后":["chinese_simplified"],"多":["chinese_simplified","chinese_traditional"],"定":["chinese_simplified","chinese_traditional"],"行":["chinese_simplified","chinese_traditional"],"学":["chinese_simplified"],"法":["chinese_simplified","chinese_traditional"],"所":["chinese_simplified","chinese_traditional"],"民":["chinese_simplified","chinese_traditional"],"得":["chinese_simplified","chinese_traditional"],"经":["chinese_simplified"],"十":["chinese_simplified","chinese_traditional"],"三":["chinese_simplified","chinese_traditional"],"之":["chinese_simplified","chinese_traditional"],"进":["chinese_simplified"],"着":["chinese_simplified"],"等":["chinese_simplified","chinese_traditional"],"部":["chinese_simplified","chinese_traditional"],"度":["chinese_simplified","chinese_traditional"],"家":["chinese_simplified","chinese_traditional"],"电":["chinese_simplified"],"力":["chinese_simplified","chinese_traditional"],"里":["chinese_simplified"],"如":["chinese_simplified","chinese_traditional"],"水":["chinese_simplified","chinese_traditional"],"化":["chinese_simplified","chinese_traditional"],"高":["chinese_simplified","chinese_traditional"],"自":["chinese_simplified","chinese_traditional"],"二":["chinese_simplified","chinese_traditional"],"理":["chinese_simplified","chinese_traditional"],"起":["chinese_simplified","chinese_traditional"],"小":["chinese_simplified","chinese_traditional"],"物":["chinese_simplified","chinese_traditional"],"现":["chinese_simplified"],"实":["chinese_simplified"],"加":["chinese_simplified","chinese_traditional"],"量":["chinese_simplified","chinese_traditional"],"都":["chinese_simplified","chinese_traditional"],"两":["chinese_simplified"],"体":["chinese_simplified"],"制":["chinese_simplified","chinese_traditional"],"机":["chinese_simplified"],"当":["chinese_simplified"],"使":["chinese_simplified","chinese_traditional"],"点":["chinese_simplified"],"从":["chinese_simplified"],"业":["chinese_simplified"],"本":["chinese_simplified","chinese_traditional"],"去":["chinese_simplified","chinese_traditional"],"把":["chinese_simplified","chinese_traditional"],"性":["chinese_simplified","chinese_traditional"],"好":["chinese_simplified","chinese_traditional"],"应":["chinese_simplified"],"开":["chinese_simplified"],"它":["chinese_simplified","chinese_traditional"],"合":["chinese_simplified","chinese_traditional"],"还":["chinese_simplified"],"因":["chinese_simplified","chinese_traditional"],"由":["chinese_simplified","chinese_traditional"],"其":["chinese_simplified","chinese_traditional"],"些":["chinese_simplified","chinese_traditional"],"然":["chinese_simplified","chinese_traditional"],"前":["chinese_simplified","chinese_traditional"],"外":["chinese_simplified","chinese_traditional"],"天":["chinese_simplified","chinese_traditional"],"政":["chinese_simplified","chinese_traditional"],"四":["chinese_simplified","chinese_traditional"],"日":["chinese_simplified","chinese_traditional"],"那":["chinese_simplified","chinese_traditional"],"社":["chinese_simplified","chinese_traditional"],"义":["chinese_simplified"],"事":["chinese_simplified","chinese_traditional"],"平":["chinese_simplified","chinese_traditional"],"形":["chinese_simplified","chinese_traditional"],"相":["chinese_simplified","chinese_traditional"],"全":["chinese_simplified","chinese_traditional"],"表":["chinese_simplified","chinese_traditional"],"间":["chinese_simplified"],"样":["chinese_simplified"],"与":["chinese_simplified"],"关":["chinese_simplified"],"各":["chinese_simplified","chinese_traditional"],"重":["chinese_simplified","chinese_traditional"],"新":["chinese_simplified","chinese_traditional"],"线":["chinese_simplified"],"内":["chinese_simplified"],"数":["chinese_simplified"],"正":["chinese_simplified","chinese_traditional"],"心":["chinese_simplified","chinese_traditional"],"反":["chinese_simplified","chinese_traditional"],"你":["chinese_simplified","chinese_traditional"],"明":["chinese_simplified","chinese_traditional"],"看":["chinese_simplified","chinese_traditional"],"原":["chinese_simplified","chinese_traditional"],"又":["chinese_simplified","chinese_traditional"],"么":["chinese_simplified"],"利":["chinese_simplified","chinese_traditional"],"比":["chinese_simplified","chinese_traditional"],"或":["chinese_simplified","chinese_traditional"],"但":["chinese_simplified","chinese_traditional"],"质":["chinese_simplified"],"气":["chinese_simplified"],"第":["chinese_simplified","chinese_traditional"],"向":["chinese_simplified","chinese_traditional"],"道":["chinese_simplified","chinese_traditional"],"命":["chinese_simplified","chinese_traditional"],"此":["chinese_simplified","chinese_traditional"],"变":["chinese_simplified"],"条":["chinese_simplified"],"只":["chinese_simplified","chinese_traditional"],"没":["chinese_simplified"],"结":["chinese_simplified"],"解":["chinese_simplified","chinese_traditional"],"问":["chinese_simplified"],"意":["chinese_simplified","chinese_traditional"],"建":["chinese_simplified","chinese_traditional"],"月":["chinese_simplified","chinese_traditional"],"公":["chinese_simplified","chinese_traditional"],"无":["chinese_simplified"],"系":["chinese_simplified","chinese_traditional"],"军":["chinese_simplified"],"很":["chinese_simplified","chinese_traditional"],"情":["chinese_simplified","chinese_traditional"],"者":["chinese_simplified","chinese_traditional"],"最":["chinese_simplified","chinese_traditional"],"立":["chinese_simplified","chinese_traditional"],"代":["chinese_simplified","chinese_traditional"],"想":["chinese_simplified","chinese_traditional"],"已":["chinese_simplified","chinese_traditional"],"通":["chinese_simplified","chinese_traditional"],"并":["chinese_simplified"],"提":["chinese_simplified","chinese_traditional"],"直":["chinese_simplified","chinese_traditional"],"题":["chinese_simplified"],"党":["chinese_simplified"],"程":["chinese_simplified","chinese_traditional"],"展":["chinese_simplified","chinese_traditional"],"五":["chinese_simplified","chinese_traditional"],"果":["chinese_simplified","chinese_traditional"],"料":["chinese_simplified","chinese_traditional"],"象":["chinese_simplified","chinese_traditional"],"员":["chinese_simplified"],"革":["chinese_simplified","chinese_traditional"],"位":["chinese_simplified","chinese_traditional"],"入":["chinese_simplified","chinese_traditional"],"常":["chinese_simplified","chinese_traditional"],"文":["chinese_simplified","chinese_traditional"],"总":["chinese_simplified"],"次":["chinese_simplified","chinese_traditional"],"品":["chinese_simplified","chinese_traditional"],"式":["chinese_simplified","chinese_traditional"],"活":["chinese_simplified","chinese_traditional"],"设":["chinese_simplified"],"及":["chinese_simplified","chinese_traditional"],"管":["chinese_simplified","chinese_traditional"],"特":["chinese_simplified","chinese_traditional"],"件":["chinese_simplified","chinese_traditional"],"长":["chinese_simplified"],"求":["chinese_simplified","chinese_traditional"],"老":["chinese_simplified","chinese_traditional"],"头":["chinese_simplified"],"基":["chinese_simplified","chinese_traditional"],"资":["chinese_simplified"],"边":["chinese_simplified"],"流":["chinese_simplified","chinese_traditional"],"路":["chinese_simplified","chinese_traditional"],"级":["chinese_simplified"],"少":["chinese_simplified","chinese_traditional"],"图":["chinese_simplified"],"山":["chinese_simplified","chinese_traditional"],"统":["chinese_simplified"],"接":["chinese_simplified","chinese_traditional"],"知":["chinese_simplified","chinese_traditional"],"较":["chinese_simplified"],"将":["chinese_simplified"],"组":["chinese_simplified"],"见":["chinese_simplified"],"计":["chinese_simplified"],"别":["chinese_simplified"],"她":["chinese_simplified","chinese_traditional"],"手":["chinese_simplified","chinese_traditional"],"角":["chinese_simplified","chinese_traditional"],"期":["chinese_simplified","chinese_traditional"],"根":["chinese_simplified","chinese_traditional"],"论":["chinese_simplified"],"运":["chinese_simplified"],"农":["chinese_simplified"],"指":["chinese_simplified","chinese_traditional"],"几":["chinese_simplified"],"九":["chinese_simplified","chinese_traditional"],"区":["chinese_simplified"],"强":["chinese_simplified"],"放":["chinese_simplified","chinese_traditional"],"决":["chinese_simplified"],"西":["chinese_simplified","chinese_traditional"],"被":["chinese_simplified","chinese_traditional"],"干":["chinese_simplified"],"做":["chinese_simplified","chinese_traditional"],"必":["chinese_simplified","chinese_traditional"],"战":["chinese_simplified"],"先":["chinese_simplified","chinese_traditional"],"回":["chinese_simplified","chinese_traditional"],"则":["chinese_simplified"],"任":["chinese_simplified","chinese_traditional"],"取":["chinese_simplified","chinese_traditional"],"据":["chinese_simplified"],"处":["chinese_simplified"],"队":["chinese_simplified"],"南":["chinese_simplified","chinese_traditional"],"给":["chinese_simplified"],"色":["chinese_simplified","chinese_traditional"],"光":["chinese_simplified","chinese_traditional"],"门":["chinese_simplified"],"即":["chinese_simplified","chinese_traditional"],"保":["chinese_simplified","chinese_traditional"],"治":["chinese_simplified","chinese_traditional"],"北":["chinese_simplified","chinese_traditional"],"造":["chinese_simplified","chinese_traditional"],"百":["chinese_simplified","chinese_traditional"],"规":["chinese_simplified"],"热":["chinese_simplified"],"领":["chinese_simplified"],"七":["chinese_simplified","chinese_traditional"],"海":["chinese_simplified","chinese_traditional"],"口":["chinese_simplified","chinese_traditional"],"东":["chinese_simplified"],"导":["chinese_simplified"],"器":["chinese_simplified","chinese_traditional"],"压":["chinese_simplified"],"志":["chinese_simplified","chinese_traditional"],"世":["chinese_simplified","chinese_traditional"],"金":["chinese_simplified","chinese_traditional"],"增":["chinese_simplified","chinese_traditional"],"争":["chinese_simplified"],"济":["chinese_simplified"],"阶":["chinese_simplified"],"油":["chinese_simplified","chinese_traditional"],"思":["chinese_simplified","chinese_traditional"],"术":["chinese_simplified"],"极":["chinese_simplified"],"交":["chinese_simplified","chinese_traditional"],"受":["chinese_simplified","chinese_traditional"],"联":["chinese_simplified"],"什":["chinese_simplified","chinese_traditional"],"认":["chinese_simplified"],"六":["chinese_simplified","chinese_traditional"],"共":["chinese_simplified","chinese_traditional"],"权":["chinese_simplified"],"收":["chinese_simplified","chinese_traditional"],"证":["chinese_simplified"],"改":["chinese_simplified","chinese_traditional"],"清":["chinese_simplified","chinese_traditional"],"美":["chinese_simplified","chinese_traditional"],"再":["chinese_simplified","chinese_traditional"],"采":["chinese_simplified"],"转":["chinese_simplified"],"更":["chinese_simplified","chinese_traditional"],"单":["chinese_simplified"],"风":["chinese_simplified"],"切":["chinese_simplified","chinese_traditional"],"打":["chinese_simplified","chinese_traditional"],"白":["chinese_simplified","chinese_traditional"],"教":["chinese_simplified","chinese_traditional"],"速":["chinese_simplified","chinese_traditional"],"花":["chinese_simplified","chinese_traditional"],"带":["chinese_simplified"],"安":["chinese_simplified","chinese_traditional"],"场":["chinese_simplified"],"身":["chinese_simplified","chinese_traditional"],"车":["chinese_simplified"],"例":["chinese_simplified","chinese_traditional"],"真":["chinese_simplified","chinese_traditional"],"务":["chinese_simplified"],"具":["chinese_simplified","chinese_traditional"],"万":["chinese_simplified"],"每":["chinese_simplified","chinese_traditional"],"目":["chinese_simplified","chinese_traditional"],"至":["chinese_simplified","chinese_traditional"],"达":["chinese_simplified"],"走":["chinese_simplified","chinese_traditional"],"积":["chinese_simplified"],"示":["chinese_simplified","chinese_traditional"],"议":["chinese_simplified"],"声":["chinese_simplified"],"报":["chinese_simplified"],"斗":["chinese_simplified"],"完":["chinese_simplified","chinese_traditional"],"类":["chinese_simplified"],"八":["chinese_simplified","chinese_traditional"],"离":["chinese_simplified"],"华":["chinese_simplified"],"名":["chinese_simplified","chinese_traditional"],"确":["chinese_simplified"],"才":["chinese_simplified","chinese_traditional"],"科":["chinese_simplified","chinese_traditional"],"张":["chinese_simplified"],"信":["chinese_simplified","chinese_traditional"],"马":["chinese_simplified"],"节":["chinese_simplified"],"话":["chinese_simplified"],"米":["chinese_simplified","chinese_traditional"],"整":["chinese_simplified","chinese_traditional"],"空":["chinese_simplified","chinese_traditional"],"元":["chinese_simplified","chinese_traditional"],"况":["chinese_simplified"],"今":["chinese_simplified","chinese_traditional"],"集":["chinese_simplified","chinese_traditional"],"温":["chinese_simplified"],"传":["chinese_simplified"],"土":["chinese_simplified","chinese_traditional"],"许":["chinese_simplified"],"步":["chinese_simplified","chinese_traditional"],"群":["chinese_simplified","chinese_traditional"],"广":["chinese_simplified"],"石":["chinese_simplified","chinese_traditional"],"记":["chinese_simplified"],"需":["chinese_simplified","chinese_traditional"],"段":["chinese_simplified","chinese_traditional"],"研":["chinese_simplified","chinese_traditional"],"界":["chinese_simplified","chinese_traditional"],"拉":["chinese_simplified","chinese_traditional"],"林":["chinese_simplified","chinese_traditional"],"律":["chinese_simplified","chinese_traditional"],"叫":["chinese_simplified","chinese_traditional"],"且":["chinese_simplified","chinese_traditional"],"究":["chinese_simplified","chinese_traditional"],"观":["chinese_simplified"],"越":["chinese_simplified","chinese_traditional"],"织":["chinese_simplified"],"装":["chinese_simplified"],"影":["chinese_simplified","chinese_traditional"],"算":["chinese_simplified","chinese_traditional"],"低":["chinese_simplified","chinese_traditional"],"持":["chinese_simplified","chinese_traditional"],"音":["chinese_simplified","chinese_traditional"],"众":["chinese_simplified"],"书":["chinese_simplified"],"布":["chinese_simplified","chinese_traditional"],"复":["chinese_simplified","chinese_traditional"],"容":["chinese_simplified","chinese_traditional"],"儿":["chinese_simplified"],"须":["chinese_simplified"],"际":["chinese_simplified"],"商":["chinese_simplified","chinese_traditional"],"非":["chinese_simplified","chinese_traditional"],"验":["chinese_simplified"],"连":["chinese_simplified"],"断":["chinese_simplified"],"深":["chinese_simplified","chinese_traditional"],"难":["chinese_simplified"],"近":["chinese_simplified","chinese_traditional"],"矿":["chinese_simplified"],"千":["chinese_simplified","chinese_traditional"],"周":["chinese_simplified"],"委":["chinese_simplified","chinese_traditional"],"素":["chinese_simplified","chinese_traditional"],"技":["chinese_simplified","chinese_traditional"],"备":["chinese_simplified"],"半":["chinese_simplified","chinese_traditional"],"办":["chinese_simplified"],"青":["chinese_simplified","chinese_traditional"],"省":["chinese_simplified","chinese_traditional"],"列":["chinese_simplified","chinese_traditional"],"习":["chinese_simplified"],"响":["chinese_simplified"],"约":["chinese_simplified"],"支":["chinese_simplified","chinese_traditional"],"般":["chinese_simplified","chinese_traditional"],"史":["chinese_simplified","chinese_traditional"],"感":["chinese_simplified","chinese_traditional"],"劳":["chinese_simplified"],"便":["chinese_simplified","chinese_traditional"],"团":["chinese_simplified"],"往":["chinese_simplified","chinese_traditional"],"酸":["chinese_simplified","chinese_traditional"],"历":["chinese_simplified"],"市":["chinese_simplified","chinese_traditional"],"克":["chinese_simplified","chinese_traditional"],"何":["chinese_simplified","chinese_traditional"],"除":["chinese_simplified","chinese_traditional"],"消":["chinese_simplified","chinese_traditional"],"构":["chinese_simplified"],"府":["chinese_simplified","chinese_traditional"],"称":["chinese_simplified"],"太":["chinese_simplified","chinese_traditional"],"准":["chinese_simplified"],"精":["chinese_simplified","chinese_traditional"],"值":["chinese_simplified","chinese_traditional"],"号":["chinese_simplified"],"率":["chinese_simplified","chinese_traditional"],"族":["chinese_simplified","chinese_traditional"],"维":["chinese_simplified"],"划":["chinese_simplified"],"选":["chinese_simplified"],"标":["chinese_simplified"],"写":["chinese_simplified"],"存":["chinese_simplified","chinese_traditional"],"候":["chinese_simplified","chinese_traditional"],"毛":["chinese_simplified","chinese_traditional"],"亲":["chinese_simplified"],"快":["chinese_simplified","chinese_traditional"],"效":["chinese_simplified","chinese_traditional"],"斯":["chinese_simplified","chinese_traditional"],"院":["chinese_simplified","chinese_traditional"],"查":["chinese_simplified","chinese_traditional"],"江":["chinese_simplified","chinese_traditional"],"型":["chinese_simplified","chinese_traditional"],"眼":["chinese_simplified","chinese_traditional"],"王":["chinese_simplified","chinese_traditional"],"按":["chinese_simplified","chinese_traditional"],"格":["chinese_simplified","chinese_traditional"],"养":["chinese_simplified"],"易":["chinese_simplified","chinese_traditional"],"置":["chinese_simplified","chinese_traditional"],"派":["chinese_simplified","chinese_traditional"],"层":["chinese_simplified"],"片":["chinese_simplified","chinese_traditional"],"始":["chinese_simplified","chinese_traditional"],"却":["chinese_simplified"],"专":["chinese_simplified"],"状":["chinese_simplified"],"育":["chinese_simplified","chinese_traditional"],"厂":["chinese_simplified"],"京":["chinese_simplified","chinese_traditional"],"识":["chinese_simplified"],"适":["chinese_simplified"],"属":["chinese_simplified"],"圆":["chinese_simplified"],"包":["chinese_simplified","chinese_traditional"],"火":["chinese_simplified","chinese_traditional"],"住":["chinese_simplified","chinese_traditional"],"调":["chinese_simplified"],"满":["chinese_simplified"],"县":["chinese_simplified"],"局":["chinese_simplified","chinese_traditional"],"照":["chinese_simplified","chinese_traditional"],"参":["chinese_simplified"],"红":["chinese_simplified"],"细":["chinese_simplified"],"引":["chinese_simplified","chinese_traditional"],"听":["chinese_simplified"],"该":["chinese_simplified"],"铁":["chinese_simplified"],"价":["chinese_simplified"],"严":["chinese_simplified"],"首":["chinese_simplified","chinese_traditional"],"底":["chinese_simplified","chinese_traditional"],"液":["chinese_simplified","chinese_traditional"],"官":["chinese_simplified","chinese_traditional"],"德":["chinese_simplified","chinese_traditional"],"随":["chinese_simplified"],"病":["chinese_simplified","chinese_traditional"],"苏":["chinese_simplified"],"失":["chinese_simplified","chinese_traditional"],"尔":["chinese_simplified"],"死":["chinese_simplified","chinese_traditional"],"讲":["chinese_simplified"],"配":["chinese_simplified","chinese_traditional"],"女":["chinese_simplified","chinese_traditional"],"黄":["chinese_simplified"],"推":["chinese_simplified","chinese_traditional"],"显":["chinese_simplified"],"谈":["chinese_simplified"],"罪":["chinese_simplified","chinese_traditional"],"神":["chinese_simplified","chinese_traditional"],"艺":["chinese_simplified"],"呢":["chinese_simplified","chinese_traditional"],"席":["chinese_simplified","chinese_traditional"],"含":["chinese_simplified","chinese_traditional"],"企":["chinese_simplified","chinese_traditional"],"望":["chinese_simplified","chinese_traditional"],"密":["chinese_simplified","chinese_traditional"],"批":["chinese_simplified","chinese_traditional"],"营":["chinese_simplified"],"项":["chinese_simplified"],"防":["chinese_simplified","chinese_traditional"],"举":["chinese_simplified"],"球":["chinese_simplified","chinese_traditional"],"英":["chinese_simplified","chinese_traditional"],"氧":["chinese_simplified","chinese_traditional"],"势":["chinese_simplified"],"告":["chinese_simplified","chinese_traditional"],"李":["chinese_simplified","chinese_traditional"],"台":["chinese_simplified","chinese_traditional"],"落":["chinese_simplified","chinese_traditional"],"木":["chinese_simplified","chinese_traditional"],"帮":["chinese_simplified"],"轮":["chinese_simplified"],"破":["chinese_simplified","chinese_traditional"],"亚":["chinese_simplified"],"师":["chinese_simplified"],"围":["chinese_simplified"],"注":["chinese_simplified","chinese_traditional"],"远":["chinese_simplified"],"字":["chinese_simplified","chinese_traditional"],"材":["chinese_simplified","chinese_traditional"],"排":["chinese_simplified","chinese_traditional"],"供":["chinese_simplified","chinese_traditional"],"河":["chinese_simplified","chinese_traditional"],"态":["chinese_simplified"],"封":["chinese_simplified","chinese_traditional"],"另":["chinese_simplified","chinese_traditional"],"施":["chinese_simplified","chinese_traditional"],"减":["chinese_simplified"],"树":["chinese_simplified"],"溶":["chinese_simplified","chinese_traditional"],"怎":["chinese_simplified","chinese_traditional"],"止":["chinese_simplified","chinese_traditional"],"案":["chinese_simplified","chinese_traditional"],"言":["chinese_simplified","chinese_traditional"],"士":["chinese_simplified","chinese_traditional"],"均":["chinese_simplified","chinese_traditional"],"武":["chinese_simplified","chinese_traditional"],"固":["chinese_simplified","chinese_traditional"],"叶":["chinese_simplified"],"鱼":["chinese_simplified"],"波":["chinese_simplified","chinese_traditional"],"视":["chinese_simplified"],"仅":["chinese_simplified"],"费":["chinese_simplified"],"紧":["chinese_simplified"],"爱":["chinese_simplified"],"左":["chinese_simplified","chinese_traditional"],"章":["chinese_simplified","chinese_traditional"],"早":["chinese_simplified","chinese_traditional"],"朝":["chinese_simplified","chinese_traditional"],"害":["chinese_simplified","chinese_traditional"],"续":["chinese_simplified"],"轻":["chinese_simplified"],"服":["chinese_simplified","chinese_traditional"],"试":["chinese_simplified"],"食":["chinese_simplified","chinese_traditional"],"充":["chinese_simplified","chinese_traditional"],"兵":["chinese_simplified","chinese_traditional"],"源":["chinese_simplified","chinese_traditional"],"判":["chinese_simplified","chinese_traditional"],"护":["chinese_simplified"],"司":["chinese_simplified","chinese_traditional"],"足":["chinese_simplified","chinese_traditional"],"某":["chinese_simplified","chinese_traditional"],"练":["chinese_simplified"],"差":["chinese_simplified","chinese_traditional"],"致":["chinese_simplified","chinese_traditional"],"板":["chinese_simplified","chinese_traditional"],"田":["chinese_simplified","chinese_traditional"],"降":["chinese_simplified","chinese_traditional"],"黑":["chinese_simplified","chinese_traditional"],"犯":["chinese_simplified","chinese_traditional"],"负":["chinese_simplified"],"击":["chinese_simplified"],"范":["chinese_simplified","chinese_traditional"],"继":["chinese_simplified"],"兴":["chinese_simplified"],"似":["chinese_simplified","chinese_traditional"],"余":["chinese_simplified"],"坚":["chinese_simplified"],"曲":["chinese_simplified","chinese_traditional"],"输":["chinese_simplified"],"修":["chinese_simplified","chinese_traditional"],"故":["chinese_simplified","chinese_traditional"],"城":["chinese_simplified","chinese_traditional"],"夫":["chinese_simplified","chinese_traditional"],"够":["chinese_simplified"],"送":["chinese_simplified","chinese_traditional"],"笔":["chinese_simplified"],"船":["chinese_simplified","chinese_traditional"],"占":["chinese_simplified"],"右":["chinese_simplified","chinese_traditional"],"财":["chinese_simplified"],"吃":["chinese_simplified","chinese_traditional"],"富":["chinese_simplified","chinese_traditional"],"春":["chinese_simplified","chinese_traditional"],"职":["chinese_simplified"],"觉":["chinese_simplified"],"汉":["chinese_simplified"],"画":["chinese_simplified"],"功":["chinese_simplified","chinese_traditional"],"巴":["chinese_simplified","chinese_traditional"],"跟":["chinese_simplified","chinese_traditional"],"虽":["chinese_simplified"],"杂":["chinese_simplified"],"飞":["chinese_simplified"],"检":["chinese_simplified"],"吸":["chinese_simplified","chinese_traditional"],"助":["chinese_simplified","chinese_traditional"],"升":["chinese_simplified"],"阳":["chinese_simplified"],"互":["chinese_simplified","chinese_traditional"],"初":["chinese_simplified","chinese_traditional"],"创":["chinese_simplified"],"抗":["chinese_simplified","chinese_traditional"],"考":["chinese_simplified","chinese_traditional"],"投":["chinese_simplified","chinese_traditional"],"坏":["chinese_simplified"],"策":["chinese_simplified","chinese_traditional"],"古":["chinese_simplified","chinese_traditional"],"径":["chinese_simplified"],"换":["chinese_simplified"],"未":["chinese_simplified","chinese_traditional"],"跑":["chinese_simplified","chinese_traditional"],"留":["chinese_simplified","chinese_traditional"],"钢":["chinese_simplified"],"曾":["chinese_simplified","chinese_traditional"],"端":["chinese_simplified","chinese_traditional"],"责":["chinese_simplified"],"站":["chinese_simplified","chinese_traditional"],"简":["chinese_simplified"],"述":["chinese_simplified","chinese_traditional"],"钱":["chinese_simplified"],"副":["chinese_simplified","chinese_traditional"],"尽":["chinese_simplified"],"帝":["chinese_simplified","chinese_traditional"],"射":["chinese_simplified","chinese_traditional"],"草":["chinese_simplified","chinese_traditional"],"冲":["chinese_simplified"],"承":["chinese_simplified","chinese_traditional"],"独":["chinese_simplified"],"令":["chinese_simplified","chinese_traditional"],"限":["chinese_simplified","chinese_traditional"],"阿":["chinese_simplified","chinese_traditional"],"宣":["chinese_simplified","chinese_traditional"],"环":["chinese_simplified"],"双":["chinese_simplified"],"请":["chinese_simplified"],"超":["chinese_simplified","chinese_traditional"],"微":["chinese_simplified","chinese_traditional"],"让":["chinese_simplified"],"控":["chinese_simplified","chinese_traditional"],"州":["chinese_simplified","chinese_traditional"],"良":["chinese_simplified","chinese_traditional"],"轴":["chinese_simplified"],"找":["chinese_simplified","chinese_traditional"],"否":["chinese_simplified","chinese_traditional"],"纪":["chinese_simplified"],"益":["chinese_simplified","chinese_traditional"],"依":["chinese_simplified","chinese_traditional"],"优":["chinese_simplified"],"顶":["chinese_simplified"],"础":["chinese_simplified"],"载":["chinese_simplified"],"倒":["chinese_simplified","chinese_traditional"],"房":["chinese_simplified","chinese_traditional"],"突":["chinese_simplified","chinese_traditional"],"坐":["chinese_simplified","chinese_traditional"],"粉":["chinese_simplified","chinese_traditional"],"敌":["chinese_simplified"],"略":["chinese_simplified","chinese_traditional"],"客":["chinese_simplified","chinese_traditional"],"袁":["chinese_simplified","chinese_traditional"],"冷":["chinese_simplified","chinese_traditional"],"胜":["chinese_simplified"],"绝":["chinese_simplified"],"析":["chinese_simplified","chinese_traditional"],"块":["chinese_simplified"],"剂":["chinese_simplified"],"测":["chinese_simplified"],"丝":["chinese_simplified"],"协":["chinese_simplified"],"诉":["chinese_simplified"],"念":["chinese_simplified","chinese_traditional"],"陈":["chinese_simplified"],"仍":["chinese_simplified","chinese_traditional"],"罗":["chinese_simplified"],"盐":["chinese_simplified"],"友":["chinese_simplified","chinese_traditional"],"洋":["chinese_simplified","chinese_traditional"],"错":["chinese_simplified"],"苦":["chinese_simplified","chinese_traditional"],"夜":["chinese_simplified","chinese_traditional"],"刑":["chinese_simplified","chinese_traditional"],"移":["chinese_simplified","chinese_traditional"],"频":["chinese_simplified"],"逐":["chinese_simplified","chinese_traditional"],"靠":["chinese_simplified","chinese_traditional"],"混":["chinese_simplified","chinese_traditional"],"母":["chinese_simplified","chinese_traditional"],"短":["chinese_simplified","chinese_traditional"],"皮":["chinese_simplified","chinese_traditional"],"终":["chinese_simplified"],"聚":["chinese_simplified","chinese_traditional"],"汽":["chinese_simplified","chinese_traditional"],"村":["chinese_simplified","chinese_traditional"],"云":["chinese_simplified"],"哪":["chinese_simplified","chinese_traditional"],"既":["chinese_simplified","chinese_traditional"],"距":["chinese_simplified","chinese_traditional"],"卫":["chinese_simplified"],"停":["chinese_simplified","chinese_traditional"],"烈":["chinese_simplified","chinese_traditional"],"央":["chinese_simplified","chinese_traditional"],"察":["chinese_simplified","chinese_traditional"],"烧":["chinese_simplified"],"迅":["chinese_simplified","chinese_traditional"],"境":["chinese_simplified","chinese_traditional"],"若":["chinese_simplified","chinese_traditional"],"印":["chinese_simplified","chinese_traditional"],"洲":["chinese_simplified","chinese_traditional"],"刻":["chinese_simplified","chinese_traditional"],"括":["chinese_simplified","chinese_traditional"],"激":["chinese_simplified","chinese_traditional"],"孔":["chinese_simplified","chinese_traditional"],"搞":["chinese_simplified","chinese_traditional"],"甚":["chinese_simplified","chinese_traditional"],"室":["chinese_simplified","chinese_traditional"],"待":["chinese_simplified","chinese_traditional"],"核":["chinese_simplified","chinese_traditional"],"校":["chinese_simplified","chinese_traditional"],"散":["chinese_simplified","chinese_traditional"],"侵":["chinese_simplified","chinese_traditional"],"吧":["chinese_simplified","chinese_traditional"],"甲":["chinese_simplified","chinese_traditional"],"游":["chinese_simplified"],"久":["chinese_simplified","chinese_traditional"],"菜":["chinese_simplified","chinese_traditional"],"味":["chinese_simplified","chinese_traditional"],"旧":["chinese_simplified"],"模":["chinese_simplified","chinese_traditional"],"湖":["chinese_simplified","chinese_traditional"],"货":["chinese_simplified"],"损":["chinese_simplified"],"预":["chinese_simplified"],"阻":["chinese_simplified","chinese_traditional"],"毫":["chinese_simplified","chinese_traditional"],"普":["chinese_simplified","chinese_traditional"],"稳":["chinese_simplified"],"乙":["chinese_simplified","chinese_traditional"],"妈":["chinese_simplified"],"植":["chinese_simplified","chinese_traditional"],"息":["chinese_simplified","chinese_traditional"],"扩":["chinese_simplified"],"银":["chinese_simplified"],"语":["chinese_simplified"],"挥":["chinese_simplified"],"酒":["chinese_simplified","chinese_traditional"],"守":["chinese_simplified","chinese_traditional"],"拿":["chinese_simplified","chinese_traditional"],"序":["chinese_simplified","chinese_traditional"],"纸":["chinese_simplified"],"医":["chinese_simplified"],"缺":["chinese_simplified","chinese_traditional"],"雨":["chinese_simplified","chinese_traditional"],"吗":["chinese_simplified"],"针":["chinese_simplified"],"刘":["chinese_simplified"],"啊":["chinese_simplified","chinese_traditional"],"急":["chinese_simplified","chinese_traditional"],"唱":["chinese_simplified","chinese_traditional"],"误":["chinese_simplified"],"训":["chinese_simplified"],"愿":["chinese_simplified"],"审":["chinese_simplified"],"附":["chinese_simplified","chinese_traditional"],"获":["chinese_simplified"],"茶":["chinese_simplified","chinese_traditional"],"鲜":["chinese_simplified"],"粮":["chinese_simplified"],"斤":["chinese_simplified","chinese_traditional"],"孩":["chinese_simplified","chinese_traditional"],"脱":["chinese_simplified"],"硫":["chinese_simplified","chinese_traditional"],"肥":["chinese_simplified","chinese_traditional"],"善":["chinese_simplified","chinese_traditional"],"龙":["chinese_simplified"],"演":["chinese_simplified","chinese_traditional"],"父":["chinese_simplified","chinese_traditional"],"渐":["chinese_simplified"],"血":["chinese_simplified","chinese_traditional"],"欢":["chinese_simplified"],"械":["chinese_simplified","chinese_traditional"],"掌":["chinese_simplified","chinese_traditional"],"歌":["chinese_simplified","chinese_traditional"],"沙":["chinese_simplified","chinese_traditional"],"刚":["chinese_simplified"],"攻":["chinese_simplified","chinese_traditional"],"谓":["chinese_simplified"],"盾":["chinese_simplified","chinese_traditional"],"讨":["chinese_simplified"],"晚":["chinese_simplified","chinese_traditional"],"粒":["chinese_simplified","chinese_traditional"],"乱":["chinese_simplified"],"燃":["chinese_simplified","chinese_traditional"],"矛":["chinese_simplified","chinese_traditional"],"乎":["chinese_simplified","chinese_traditional"],"杀":["chinese_simplified"],"药":["chinese_simplified"],"宁":["chinese_simplified"],"鲁":["chinese_simplified"],"贵":["chinese_simplified"],"钟":["chinese_simplified"],"煤":["chinese_simplified","chinese_traditional"],"读":["chinese_simplified"],"班":["chinese_simplified","chinese_traditional"],"伯":["chinese_simplified","chinese_traditional"],"香":["chinese_simplified","chinese_traditional"],"介":["chinese_simplified","chinese_traditional"],"迫":["chinese_simplified","chinese_traditional"],"句":["chinese_simplified","chinese_traditional"],"丰":["chinese_simplified"],"培":["chinese_simplified","chinese_traditional"],"握":["chinese_simplified","chinese_traditional"],"兰":["chinese_simplified"],"担":["chinese_simplified"],"弦":["chinese_simplified","chinese_traditional"],"蛋":["chinese_simplified","chinese_traditional"],"沉":["chinese_simplified","chinese_traditional"],"假":["chinese_simplified","chinese_traditional"],"穿":["chinese_simplified","chinese_traditional"],"执":["chinese_simplified"],"答":["chinese_simplified","chinese_traditional"],"乐":["chinese_simplified"],"谁":["chinese_simplified"],"顺":["chinese_simplified"],"烟":["chinese_simplified"],"缩":["chinese_simplified"],"征":["chinese_simplified"],"脸":["chinese_simplified"],"喜":["chinese_simplified","chinese_traditional"],"松":["chinese_simplified","chinese_traditional"],"脚":["chinese_simplified"],"困":["chinese_simplified","chinese_traditional"],"异":["chinese_simplified"],"免":["chinese_simplified","chinese_traditional"],"背":["chinese_simplified","chinese_traditional"],"星":["chinese_simplified","chinese_traditional"],"福":["chinese_simplified","chinese_traditional"],"买":["chinese_simplified"],"染":["chinese_simplified","chinese_traditional"],"井":["chinese_simplified","chinese_traditional"],"概":["chinese_simplified","chinese_traditional"],"慢":["chinese_simplified","chinese_traditional"],"怕":["chinese_simplified","chinese_traditional"],"磁":["chinese_simplified","chinese_traditional"],"倍":["chinese_simplified","chinese_traditional"],"祖":["chinese_simplified","chinese_traditional"],"皇":["chinese_simplified","chinese_traditional"],"促":["chinese_simplified","chinese_traditional"],"静":["chinese_simplified"],"补":["chinese_simplified"],"评":["chinese_simplified"],"翻":["chinese_simplified","chinese_traditional"],"肉":["chinese_simplified","chinese_traditional"],"践":["chinese_simplified"],"尼":["chinese_simplified","chinese_traditional"],"衣":["chinese_simplified","chinese_traditional"],"宽":["chinese_simplified"],"扬":["chinese_simplified"],"棉":["chinese_simplified","chinese_traditional"],"希":["chinese_simplified","chinese_traditional"],"伤":["chinese_simplified"],"操":["chinese_simplified","chinese_traditional"],"垂":["chinese_simplified","chinese_traditional"],"秋":["chinese_simplified","chinese_traditional"],"宜":["chinese_simplified","chinese_traditional"],"氢":["chinese_simplified"],"套":["chinese_simplified","chinese_traditional"],"督":["chinese_simplified","chinese_traditional"],"振":["chinese_simplified","chinese_traditional"],"架":["chinese_simplified","chinese_traditional"],"亮":["chinese_simplified","chinese_traditional"],"末":["chinese_simplified","chinese_traditional"],"宪":["chinese_simplified"],"庆":["chinese_simplified"],"编":["chinese_simplified"],"牛":["chinese_simplified","chinese_traditional"],"触":["chinese_simplified"],"映":["chinese_simplified","chinese_traditional"],"雷":["chinese_simplified","chinese_traditional"],"销":["chinese_simplified"],"诗":["chinese_simplified"],"座":["chinese_simplified","chinese_traditional"],"居":["chinese_simplified","chinese_traditional"],"抓":["chinese_simplified","chinese_traditional"],"裂":["chinese_simplified","chinese_traditional"],"胞":["chinese_simplified","chinese_traditional"],"呼":["chinese_simplified","chinese_traditional"],"娘":["chinese_simplified","chinese_traditional"],"景":["chinese_simplified","chinese_traditional"],"威":["chinese_simplified","chinese_traditional"],"绿":["chinese_simplified"],"晶":["chinese_simplified","chinese_traditional"],"厚":["chinese_simplified","chinese_traditional"],"盟":["chinese_simplified","chinese_traditional"],"衡":["chinese_simplified","chinese_traditional"],"鸡":["chinese_simplified"],"孙":["chinese_simplified"],"延":["chinese_simplified","chinese_traditional"],"危":["chinese_simplified","chinese_traditional"],"胶":["chinese_simplified"],"屋":["chinese_simplified","chinese_traditional"],"乡":["chinese_simplified"],"临":["chinese_simplified"],"陆":["chinese_simplified"],"顾":["chinese_simplified"],"掉":["chinese_simplified","chinese_traditional"],"呀":["chinese_simplified","chinese_traditional"],"灯":["chinese_simplified"],"岁":["chinese_simplified"],"措":["chinese_simplified","chinese_traditional"],"束":["chinese_simplified","chinese_traditional"],"耐":["chinese_simplified","chinese_traditional"],"剧":["chinese_simplified"],"玉":["chinese_simplified","chinese_traditional"],"赵":["chinese_simplified"],"跳":["chinese_simplified","chinese_traditional"],"哥":["chinese_simplified","chinese_traditional"],"季":["chinese_simplified","chinese_traditional"],"课":["chinese_simplified"],"凯":["chinese_simplified"],"胡":["chinese_simplified","chinese_traditional"],"额":["chinese_simplified"],"款":["chinese_simplified","chinese_traditional"],"绍":["chinese_simplified"],"卷":["chinese_simplified","chinese_traditional"],"齐":["chinese_simplified"],"伟":["chinese_simplified"],"蒸":["chinese_simplified","chinese_traditional"],"殖":["chinese_simplified","chinese_traditional"],"永":["chinese_simplified","chinese_traditional"],"宗":["chinese_simplified","chinese_traditional"],"苗":["chinese_simplified","chinese_traditional"],"川":["chinese_simplified","chinese_traditional"],"炉":["chinese_simplified"],"岩":["chinese_simplified","chinese_traditional"],"弱":["chinese_simplified","chinese_traditional"],"零":["chinese_simplified","chinese_traditional"],"杨":["chinese_simplified"],"奏":["chinese_simplified","chinese_traditional"],"沿":["chinese_simplified","chinese_traditional"],"露":["chinese_simplified","chinese_traditional"],"杆":["chinese_simplified"],"探":["chinese_simplified","chinese_traditional"],"滑":["chinese_simplified","chinese_traditional"],"镇":["chinese_simplified"],"饭":["chinese_simplified"],"浓":["chinese_simplified"],"航":["chinese_simplified","chinese_traditional"],"怀":["chinese_simplified"],"赶":["chinese_simplified"],"库":["chinese_simplified"],"夺":["chinese_simplified"],"伊":["chinese_simplified","chinese_traditional"],"灵":["chinese_simplified"],"税":["chinese_simplified"],"途":["chinese_simplified","chinese_traditional"],"灭":["chinese_simplified"],"赛":["chinese_simplified"],"归":["chinese_simplified"],"召":["chinese_simplified","chinese_traditional"],"鼓":["chinese_simplified","chinese_traditional"],"播":["chinese_simplified","chinese_traditional"],"盘":["chinese_simplified"],"裁":["chinese_simplified","chinese_traditional"],"险":["chinese_simplified"],"康":["chinese_simplified","chinese_traditional"],"唯":["chinese_simplified","chinese_traditional"],"录":["chinese_simplified"],"菌":["chinese_simplified","chinese_traditional"],"纯":["chinese_simplified"],"借":["chinese_simplified","chinese_traditional"],"糖":["chinese_simplified","chinese_traditional"],"盖":["chinese_simplified"],"横":["chinese_simplified"],"符":["chinese_simplified","chinese_traditional"],"私":["chinese_simplified","chinese_traditional"],"努":["chinese_simplified","chinese_traditional"],"堂":["chinese_simplified","chinese_traditional"],"域":["chinese_simplified","chinese_traditional"],"枪":["chinese_simplified"],"润":["chinese_simplified"],"幅":["chinese_simplified","chinese_traditional"],"哈":["chinese_simplified","chinese_traditional"],"竟":["chinese_simplified","chinese_traditional"],"熟":["chinese_simplified","chinese_traditional"],"虫":["chinese_simplified"],"泽":["chinese_simplified"],"脑":["chinese_simplified"],"壤":["chinese_simplified","chinese_traditional"],"碳":["chinese_simplified","chinese_traditional"],"欧":["chinese_simplified"],"遍":["chinese_simplified","chinese_traditional"],"侧":["chinese_simplified"],"寨":["chinese_simplified","chinese_traditional"],"敢":["chinese_simplified","chinese_traditional"],"彻":["chinese_simplified"],"虑":["chinese_simplified"],"斜":["chinese_simplified","chinese_traditional"],"薄":["chinese_simplified","chinese_traditional"],"庭":["chinese_simplified","chinese_traditional"],"纳":["chinese_simplified"],"弹":["chinese_simplified"],"饲":["chinese_simplified"],"伸":["chinese_simplified","chinese_traditional"],"折":["chinese_simplified","chinese_traditional"],"麦":["chinese_simplified"],"湿":["chinese_simplified"],"暗":["chinese_simplified","chinese_traditional"],"荷":["chinese_simplified","chinese_traditional"],"瓦":["chinese_simplified","chinese_traditional"],"塞":["chinese_simplified","chinese_traditional"],"床":["chinese_simplified","chinese_traditional"],"筑":["chinese_simplified"],"恶":["chinese_simplified"],"户":["chinese_simplified"],"访":["chinese_simplified"],"塔":["chinese_simplified","chinese_traditional"],"奇":["chinese_simplified","chinese_traditional"],"透":["chinese_simplified","chinese_traditional"],"梁":["chinese_simplified","chinese_traditional"],"刀":["chinese_simplified","chinese_traditional"],"旋":["chinese_simplified","chinese_traditional"],"迹":["chinese_simplified"],"卡":["chinese_simplified","chinese_traditional"],"氯":["chinese_simplified","chinese_traditional"],"遇":["chinese_simplified","chinese_traditional"],"份":["chinese_simplified","chinese_traditional"],"毒":["chinese_simplified","chinese_traditional"],"泥":["chinese_simplified","chinese_traditional"],"退":["chinese_simplified","chinese_traditional"],"洗":["chinese_simplified","chinese_traditional"],"摆":["chinese_simplified"],"灰":["chinese_simplified","chinese_traditional"],"彩":["chinese_simplified","chinese_traditional"],"卖":["chinese_simplified"],"耗":["chinese_simplified","chinese_traditional"],"夏":["chinese_simplified","chinese_traditional"],"择":["chinese_simplified"],"忙":["chinese_simplified","chinese_traditional"],"铜":["chinese_simplified"],"献":["chinese_simplified"],"硬":["chinese_simplified","chinese_traditional"],"予":["chinese_simplified","chinese_traditional"],"繁":["chinese_simplified","chinese_traditional"],"圈":["chinese_simplified","chinese_traditional"],"雪":["chinese_simplified","chinese_traditional"],"函":["chinese_simplified","chinese_traditional"],"亦":["chinese_simplified","chinese_traditional"],"抽":["chinese_simplified","chinese_traditional"],"篇":["chinese_simplified","chinese_traditional"],"阵":["chinese_simplified"],"阴":["chinese_simplified"],"丁":["chinese_simplified","chinese_traditional"],"尺":["chinese_simplified","chinese_traditional"],"追":["chinese_simplified","chinese_traditional"],"堆":["chinese_simplified","chinese_traditional"],"雄":["chinese_simplified","chinese_traditional"],"迎":["chinese_simplified","chinese_traditional"],"泛":["chinese_simplified","chinese_traditional"],"爸":["chinese_simplified","chinese_traditional"],"楼":["chinese_simplified"],"避":["chinese_simplified","chinese_traditional"],"谋":["chinese_simplified"],"吨":["chinese_simplified"],"野":["chinese_simplified","chinese_traditional"],"猪":["chinese_simplified"],"旗":["chinese_simplified","chinese_traditional"],"累":["chinese_simplified","chinese_traditional"],"偏":["chinese_simplified","chinese_traditional"],"典":["chinese_simplified","chinese_traditional"],"馆":["chinese_simplified"],"索":["chinese_simplified","chinese_traditional"],"秦":["chinese_simplified","chinese_traditional"],"脂":["chinese_simplified","chinese_traditional"],"潮":["chinese_simplified","chinese_traditional"],"爷":["chinese_simplified"],"豆":["chinese_simplified","chinese_traditional"],"忽":["chinese_simplified","chinese_traditional"],"托":["chinese_simplified","chinese_traditional"],"惊":["chinese_simplified"],"塑":["chinese_simplified","chinese_traditional"],"遗":["chinese_simplified"],"愈":["chinese_simplified","chinese_traditional"],"朱":["chinese_simplified","chinese_traditional"],"替":["chinese_simplified","chinese_traditional"],"纤":["chinese_simplified"],"粗":["chinese_simplified","chinese_traditional"],"倾":["chinese_simplified"],"尚":["chinese_simplified","chinese_traditional"],"痛":["chinese_simplified","chinese_traditional"],"楚":["chinese_simplified","chinese_traditional"],"谢":["chinese_simplified"],"奋":["chinese_simplified"],"购":["chinese_simplified"],"磨":["chinese_simplified","chinese_traditional"],"君":["chinese_simplified","chinese_traditional"],"池":["chinese_simplified","chinese_traditional"],"旁":["chinese_simplified","chinese_traditional"],"碎":["chinese_simplified","chinese_traditional"],"骨":["chinese_simplified","chinese_traditional"],"监":["chinese_simplified"],"捕":["chinese_simplified","chinese_traditional"],"弟":["chinese_simplified","chinese_traditional"],"暴":["chinese_simplified","chinese_traditional"],"割":["chinese_simplified","chinese_traditional"],"贯":["chinese_simplified"],"殊":["chinese_simplified","chinese_traditional"],"释":["chinese_simplified"],"词":["chinese_simplified"],"亡":["chinese_simplified","chinese_traditional"],"壁":["chinese_simplified","chinese_traditional"],"顿":["chinese_simplified"],"宝":["chinese_simplified"],"午":["chinese_simplified","chinese_traditional"],"尘":["chinese_simplified"],"闻":["chinese_simplified"],"揭":["chinese_simplified","chinese_traditional"],"炮":["chinese_simplified","chinese_traditional"],"残":["chinese_simplified"],"冬":["chinese_simplified","chinese_traditional"],"桥":["chinese_simplified"],"妇":["chinese_simplified"],"警":["chinese_simplified","chinese_traditional"],"综":["chinese_simplified"],"招":["chinese_simplified","chinese_traditional"],"吴":["chinese_simplified"],"付":["chinese_simplified","chinese_traditional"],"浮":["chinese_simplified","chinese_traditional"],"遭":["chinese_simplified","chinese_traditional"],"徐":["chinese_simplified","chinese_traditional"],"您":["chinese_simplified","chinese_traditional"],"摇":["chinese_simplified"],"谷":["chinese_simplified","chinese_traditional"],"赞":["chinese_simplified"],"箱":["chinese_simplified","chinese_traditional"],"隔":["chinese_simplified","chinese_traditional"],"订":["chinese_simplified"],"男":["chinese_simplified","chinese_traditional"],"吹":["chinese_simplified","chinese_traditional"],"园":["chinese_simplified"],"纷":["chinese_simplified"],"唐":["chinese_simplified","chinese_traditional"],"败":["chinese_simplified"],"宋":["chinese_simplified","chinese_traditional"],"玻":["chinese_simplified","chinese_traditional"],"巨":["chinese_simplified","chinese_traditional"],"耕":["chinese_simplified","chinese_traditional"],"坦":["chinese_simplified","chinese_traditional"],"荣":["chinese_simplified"],"闭":["chinese_simplified"],"湾":["chinese_simplified"],"键":["chinese_simplified"],"凡":["chinese_simplified","chinese_traditional"],"驻":["chinese_simplified"],"锅":["chinese_simplified"],"救":["chinese_simplified","chinese_traditional"],"恩":["chinese_simplified","chinese_traditional"],"剥":["chinese_simplified"],"凝":["chinese_simplified","chinese_traditional"],"碱":["chinese_simplified"],"齿":["chinese_simplified"],"截":["chinese_simplified","chinese_traditional"],"炼":["chinese_simplified"],"麻":["chinese_simplified","chinese_traditional"],"纺":["chinese_simplified"],"禁":["chinese_simplified","chinese_traditional"],"废":["chinese_simplified"],"盛":["chinese_simplified","chinese_traditional"],"版":["chinese_simplified","chinese_traditional"],"缓":["chinese_simplified"],"净":["chinese_simplified"],"睛":["chinese_simplified","chinese_traditional"],"昌":["chinese_simplified","chinese_traditional"],"婚":["chinese_simplified","chinese_traditional"],"涉":["chinese_simplified","chinese_traditional"],"筒":["chinese_simplified","chinese_traditional"],"嘴":["chinese_simplified","chinese_traditional"],"插":["chinese_simplified","chinese_traditional"],"岸":["chinese_simplified","chinese_traditional"],"朗":["chinese_simplified","chinese_traditional"],"庄":["chinese_simplified"],"街":["chinese_simplified","chinese_traditional"],"藏":["chinese_simplified","chinese_traditional"],"姑":["chinese_simplified","chinese_traditional"],"贸":["chinese_simplified"],"腐":["chinese_simplified","chinese_traditional"],"奴":["chinese_simplified","chinese_traditional"],"啦":["chinese_simplified","chinese_traditional"],"惯":["chinese_simplified"],"乘":["chinese_simplified","chinese_traditional"],"伙":["chinese_simplified"],"恢":["chinese_simplified","chinese_traditional"],"匀":["chinese_simplified"],"纱":["chinese_simplified"],"扎":["chinese_simplified","chinese_traditional"],"辩":["chinese_simplified"],"耳":["chinese_simplified","chinese_traditional"],"彪":["chinese_simplified","chinese_traditional"],"臣":["chinese_simplified","chinese_traditional"],"亿":["chinese_simplified"],"璃":["chinese_simplified","chinese_traditional"],"抵":["chinese_simplified","chinese_traditional"],"脉":["chinese_simplified"],"秀":["chinese_simplified","chinese_traditional"],"萨":["chinese_simplified"],"俄":["chinese_simplified","chinese_traditional"],"网":["chinese_simplified"],"舞":["chinese_simplified","chinese_traditional"],"店":["chinese_simplified","chinese_traditional"],"喷":["chinese_simplified"],"纵":["chinese_simplified"],"寸":["chinese_simplified","chinese_traditional"],"汗":["chinese_simplified","chinese_traditional"],"挂":["chinese_simplified"],"洪":["chinese_simplified","chinese_traditional"],"贺":["chinese_simplified"],"闪":["chinese_simplified"],"柬":["chinese_simplified","chinese_traditional"],"爆":["chinese_simplified","chinese_traditional"],"烯":["chinese_simplified","chinese_traditional"],"津":["chinese_simplified","chinese_traditional"],"稻":["chinese_simplified","chinese_traditional"],"墙":["chinese_simplified"],"软":["chinese_simplified"],"勇":["chinese_simplified","chinese_traditional"],"像":["chinese_simplified","chinese_traditional"],"滚":["chinese_simplified"],"厘":["chinese_simplified","chinese_traditional"],"蒙":["chinese_simplified","chinese_traditional"],"芳":["chinese_simplified","chinese_traditional"],"肯":["chinese_simplified","chinese_traditional"],"坡":["chinese_simplified","chinese_traditional"],"柱":["chinese_simplified","chinese_traditional"],"荡":["chinese_simplified"],"腿":["chinese_simplified","chinese_traditional"],"仪":["chinese_simplified"],"旅":["chinese_simplified","chinese_traditional"],"尾":["chinese_simplified","chinese_traditional"],"轧":["chinese_simplified"],"冰":["chinese_simplified","chinese_traditional"],"贡":["chinese_simplified"],"登":["chinese_simplified","chinese_traditional"],"黎":["chinese_simplified","chinese_traditional"],"削":["chinese_simplified","chinese_traditional"],"钻":["chinese_simplified"],"勒":["chinese_simplified","chinese_traditional"],"逃":["chinese_simplified","chinese_traditional"],"障":["chinese_simplified","chinese_traditional"],"氨":["chinese_simplified","chinese_traditional"],"郭":["chinese_simplified","chinese_traditional"],"峰":["chinese_simplified","chinese_traditional"],"币":["chinese_simplified"],"港":["chinese_simplified","chinese_traditional"],"伏":["chinese_simplified","chinese_traditional"],"轨":["chinese_simplified"],"亩":["chinese_simplified"],"毕":["chinese_simplified"],"擦":["chinese_simplified","chinese_traditional"],"莫":["chinese_simplified","chinese_traditional"],"刺":["chinese_simplified","chinese_traditional"],"浪":["chinese_simplified","chinese_traditional"],"秘":["chinese_simplified","chinese_traditional"],"援":["chinese_simplified","chinese_traditional"],"株":["chinese_simplified","chinese_traditional"],"健":["chinese_simplified","chinese_traditional"],"售":["chinese_simplified","chinese_traditional"],"股":["chinese_simplified","chinese_traditional"],"岛":["chinese_simplified"],"甘":["chinese_simplified","chinese_traditional"],"泡":["chinese_simplified","chinese_traditional"],"睡":["chinese_simplified","chinese_traditional"],"童":["chinese_simplified","chinese_traditional"],"铸":["chinese_simplified"],"汤":["chinese_simplified"],"阀":["chinese_simplified"],"休":["chinese_simplified","chinese_traditional"],"汇":["chinese_simplified"],"舍":["chinese_simplified","chinese_traditional"],"牧":["chinese_simplified","chinese_traditional"],"绕":["chinese_simplified"],"炸":["chinese_simplified","chinese_traditional"],"哲":["chinese_simplified","chinese_traditional"],"磷":["chinese_simplified","chinese_traditional"],"绩":["chinese_simplified"],"朋":["chinese_simplified","chinese_traditional"],"淡":["chinese_simplified","chinese_traditional"],"尖":["chinese_simplified","chinese_traditional"],"启":["chinese_simplified"],"陷":["chinese_simplified","chinese_traditional"],"柴":["chinese_simplified","chinese_traditional"],"呈":["chinese_simplified","chinese_traditional"],"徒":["chinese_simplified","chinese_traditional"],"颜":["chinese_simplified"],"泪":["chinese_simplified"],"稍":["chinese_simplified","chinese_traditional"],"忘":["chinese_simplified","chinese_traditional"],"泵":["chinese_simplified","chinese_traditional"],"蓝":["chinese_simplified"],"拖":["chinese_simplified","chinese_traditional"],"洞":["chinese_simplified","chinese_traditional"],"授":["chinese_simplified","chinese_traditional"],"镜":["chinese_simplified"],"辛":["chinese_simplified","chinese_traditional"],"壮":["chinese_simplified"],"锋":["chinese_simplified"],"贫":["chinese_simplified"],"虚":["chinese_simplified"],"弯":["chinese_simplified"],"摩":["chinese_simplified","chinese_traditional"],"泰":["chinese_simplified","chinese_traditional"],"幼":["chinese_simplified","chinese_traditional"],"廷":["chinese_simplified","chinese_traditional"],"尊":["chinese_simplified","chinese_traditional"],"窗":["chinese_simplified","chinese_traditional"],"纲":["chinese_simplified"],"弄":["chinese_simplified","chinese_traditional"],"隶":["chinese_simplified"],"疑":["chinese_simplified","chinese_traditional"],"氏":["chinese_simplified","chinese_traditional"],"宫":["chinese_simplified"],"姐":["chinese_simplified","chinese_traditional"],"震":["chinese_simplified","chinese_traditional"],"瑞":["chinese_simplified","chinese_traditional"],"怪":["chinese_simplified","chinese_traditional"],"尤":["chinese_simplified","chinese_traditional"],"琴":["chinese_simplified","chinese_traditional"],"循":["chinese_simplified","chinese_traditional"],"描":["chinese_simplified","chinese_traditional"],"膜":["chinese_simplified","chinese_traditional"],"违":["chinese_simplified"],"夹":["chinese_simplified"],"腰":["chinese_simplified","chinese_traditional"],"缘":["chinese_simplified"],"珠":["chinese_simplified","chinese_traditional"],"穷":["chinese_simplified"],"森":["chinese_simplified","chinese_traditional"],"枝":["chinese_simplified","chinese_traditional"],"竹":["chinese_simplified","chinese_traditional"],"沟":["chinese_simplified"],"催":["chinese_simplified","chinese_traditional"],"绳":["chinese_simplified"],"忆":["chinese_simplified"],"邦":["chinese_simplified","chinese_traditional"],"剩":["chinese_simplified","chinese_traditional"],"幸":["chinese_simplified","chinese_traditional"],"浆":["chinese_simplified"],"栏":["chinese_simplified"],"拥":["chinese_simplified"],"牙":["chinese_simplified","chinese_traditional"],"贮":["chinese_simplified"],"礼":["chinese_simplified"],"滤":["chinese_simplified"],"钠":["chinese_simplified"],"纹":["chinese_simplified"],"罢":["chinese_simplified"],"拍":["chinese_simplified","chinese_traditional"],"咱":["chinese_simplified","chinese_traditional"],"喊":["chinese_simplified","chinese_traditional"],"袖":["chinese_simplified","chinese_traditional"],"埃":["chinese_simplified","chinese_traditional"],"勤":["chinese_simplified","chinese_traditional"],"罚":["chinese_simplified"],"焦":["chinese_simplified","chinese_traditional"],"潜":["chinese_simplified"],"伍":["chinese_simplified","chinese_traditional"],"墨":["chinese_simplified","chinese_traditional"],"欲":["chinese_simplified","chinese_traditional"],"缝":["chinese_simplified"],"姓":["chinese_simplified","chinese_traditional"],"刊":["chinese_simplified","chinese_traditional"],"饱":["chinese_simplified"],"仿":["chinese_simplified","chinese_traditional"],"奖":["chinese_simplified"],"铝":["chinese_simplified"],"鬼":["chinese_simplified","chinese_traditional"],"丽":["chinese_simplified"],"跨":["chinese_simplified","chinese_traditional"],"默":["chinese_simplified","chinese_traditional"],"挖":["chinese_simplified","chinese_traditional"],"链":["chinese_simplified"],"扫":["chinese_simplified"],"喝":["chinese_simplified","chinese_traditional"],"袋":["chinese_simplified","chinese_traditional"],"炭":["chinese_simplified","chinese_traditional"],"污":["chinese_simplified","chinese_traditional"],"幕":["chinese_simplified","chinese_traditional"],"诸":["chinese_simplified"],"弧":["chinese_simplified","chinese_traditional"],"励":["chinese_simplified"],"梅":["chinese_simplified","chinese_traditional"],"奶":["chinese_simplified","chinese_traditional"],"洁":["chinese_simplified"],"灾":["chinese_simplified"],"舟":["chinese_simplified","chinese_traditional"],"鉴":["chinese_simplified"],"苯":["chinese_simplified","chinese_traditional"],"讼":["chinese_simplified"],"抱":["chinese_simplified","chinese_traditional"],"毁":["chinese_simplified"],"懂":["chinese_simplified","chinese_traditional"],"寒":["chinese_simplified","chinese_traditional"],"智":["chinese_simplified","chinese_traditional"],"埔":["chinese_simplified","chinese_traditional"],"寄":["chinese_simplified","chinese_traditional"],"届":["chinese_simplified"],"跃":["chinese_simplified"],"渡":["chinese_simplified","chinese_traditional"],"挑":["chinese_simplified","chinese_traditional"],"丹":["chinese_simplified","chinese_traditional"],"艰":["chinese_simplified"],"贝":["chinese_simplified"],"碰":["chinese_simplified","chinese_traditional"],"拔":["chinese_simplified","chinese_traditional"],"爹":["chinese_simplified","chinese_traditional"],"戴":["chinese_simplified","chinese_traditional"],"码":["chinese_simplified"],"梦":["chinese_simplified"],"芽":["chinese_simplified","chinese_traditional"],"熔":["chinese_simplified","chinese_traditional"],"赤":["chinese_simplified","chinese_traditional"],"渔":["chinese_simplified"],"哭":["chinese_simplified","chinese_traditional"],"敬":["chinese_simplified","chinese_traditional"],"颗":["chinese_simplified"],"奔":["chinese_simplified","chinese_traditional"],"铅":["chinese_simplified"],"仲":["chinese_simplified","chinese_traditional"],"虎":["chinese_simplified","chinese_traditional"],"稀":["chinese_simplified","chinese_traditional"],"妹":["chinese_simplified","chinese_traditional"],"乏":["chinese_simplified","chinese_traditional"],"珍":["chinese_simplified","chinese_traditional"],"申":["chinese_simplified","chinese_traditional"],"桌":["chinese_simplified","chinese_traditional"],"遵":["chinese_simplified","chinese_traditional"],"允":["chinese_simplified","chinese_traditional"],"隆":["chinese_simplified","chinese_traditional"],"螺":["chinese_simplified","chinese_traditional"],"仓":["chinese_simplified"],"魏":["chinese_simplified","chinese_traditional"],"锐":["chinese_simplified"],"晓":["chinese_simplified"],"氮":["chinese_simplified","chinese_traditional"],"兼":["chinese_simplified","chinese_traditional"],"隐":["chinese_simplified"],"碍":["chinese_simplified"],"赫":["chinese_simplified","chinese_traditional"],"拨":["chinese_simplified"],"忠":["chinese_simplified","chinese_traditional"],"肃":["chinese_simplified"],"缸":["chinese_simplified","chinese_traditional"],"牵":["chinese_simplified"],"抢":["chinese_simplified"],"博":["chinese_simplified","chinese_traditional"],"巧":["chinese_simplified","chinese_traditional"],"壳":["chinese_simplified"],"兄":["chinese_simplified","chinese_traditional"],"杜":["chinese_simplified","chinese_traditional"],"讯":["chinese_simplified"],"诚":["chinese_simplified"],"碧":["chinese_simplified","chinese_traditional"],"祥":["chinese_simplified","chinese_traditional"],"柯":["chinese_simplified","chinese_traditional"],"页":["chinese_simplified"],"巡":["chinese_simplified","chinese_traditional"],"矩":["chinese_simplified","chinese_traditional"],"悲":["chinese_simplified","chinese_traditional"],"灌":["chinese_simplified","chinese_traditional"],"龄":["chinese_simplified"],"伦":["chinese_simplified"],"票":["chinese_simplified","chinese_traditional"],"寻":["chinese_simplified"],"桂":["chinese_simplified","chinese_traditional"],"铺":["chinese_simplified"],"圣":["chinese_simplified"],"恐":["chinese_simplified","chinese_traditional"],"恰":["chinese_simplified","chinese_traditional"],"郑":["chinese_simplified"],"趣":["chinese_simplified","chinese_traditional"],"抬":["chinese_simplified","chinese_traditional"],"荒":["chinese_simplified","chinese_traditional"],"腾":["chinese_simplified"],"贴":["chinese_simplified"],"柔":["chinese_simplified","chinese_traditional"],"滴":["chinese_simplified","chinese_traditional"],"猛":["chinese_simplified","chinese_traditional"],"阔":["chinese_simplified"],"辆":["chinese_simplified"],"妻":["chinese_simplified","chinese_traditional"],"填":["chinese_simplified","chinese_traditional"],"撤":["chinese_simplified","chinese_traditional"],"储":["chinese_simplified"],"签":["chinese_simplified"],"闹":["chinese_simplified"],"扰":["chinese_simplified"],"紫":["chinese_simplified","chinese_traditional"],"砂":["chinese_simplified","chinese_traditional"],"递":["chinese_simplified"],"戏":["chinese_simplified"],"吊":["chinese_simplified","chinese_traditional"],"陶":["chinese_simplified","chinese_traditional"],"伐":["chinese_simplified","chinese_traditional"],"喂":["chinese_simplified"],"疗":["chinese_simplified"],"瓶":["chinese_simplified","chinese_traditional"],"婆":["chinese_simplified","chinese_traditional"],"抚":["chinese_simplified"],"臂":["chinese_simplified","chinese_traditional"],"摸":["chinese_simplified","chinese_traditional"],"忍":["chinese_simplified","chinese_traditional"],"虾":["chinese_simplified"],"蜡":["chinese_simplified"],"邻":["chinese_simplified"],"胸":["chinese_simplified","chinese_traditional"],"巩":["chinese_simplified"],"挤":["chinese_simplified"],"偶":["chinese_simplified","chinese_traditional"],"弃":["chinese_simplified"],"槽":["chinese_simplified","chinese_traditional"],"劲":["chinese_simplified"],"乳":["chinese_simplified","chinese_traditional"],"邓":["chinese_simplified"],"吉":["chinese_simplified","chinese_traditional"],"仁":["chinese_simplified","chinese_traditional"],"烂":["chinese_simplified"],"砖":["chinese_simplified"],"租":["chinese_simplified","chinese_traditional"],"乌":["chinese_simplified"],"舰":["chinese_simplified"],"伴":["chinese_simplified","chinese_traditional"],"瓜":["chinese_simplified","chinese_traditional"],"浅":["chinese_simplified"],"丙":["chinese_simplified","chinese_traditional"],"暂":["chinese_simplified"],"燥":["chinese_simplified","chinese_traditional"],"橡":["chinese_simplified","chinese_traditional"],"柳":["chinese_simplified","chinese_traditional"],"迷":["chinese_simplified","chinese_traditional"],"暖":["chinese_simplified","chinese_traditional"],"牌":["chinese_simplified","chinese_traditional"],"秧":["chinese_simplified","chinese_traditional"],"胆":["chinese_simplified"],"详":["chinese_simplified"],"簧":["chinese_simplified","chinese_traditional"],"踏":["chinese_simplified","chinese_traditional"],"瓷":["chinese_simplified","chinese_traditional"],"谱":["chinese_simplified"],"呆":["chinese_simplified","chinese_traditional"],"宾":["chinese_simplified"],"糊":["chinese_simplified","chinese_traditional"],"洛":["chinese_simplified","chinese_traditional"],"辉":["chinese_simplified"],"愤":["chinese_simplified"],"竞":["chinese_simplified"],"隙":["chinese_simplified","chinese_traditional"],"怒":["chinese_simplified","chinese_traditional"],"粘":["chinese_simplified","chinese_traditional"],"乃":["chinese_simplified","chinese_traditional"],"绪":["chinese_simplified"],"肩":["chinese_simplified","chinese_traditional"],"籍":["chinese_simplified","chinese_traditional"],"敏":["chinese_simplified","chinese_traditional"],"涂":["chinese_simplified"],"熙":["chinese_simplified","chinese_traditional"],"皆":["chinese_simplified","chinese_traditional"],"侦":["chinese_simplified"],"悬":["chinese_simplified"],"掘":["chinese_simplified","chinese_traditional"],"享":["chinese_simplified","chinese_traditional"],"纠":["chinese_simplified"],"醒":["chinese_simplified","chinese_traditional"],"狂":["chinese_simplified","chinese_traditional"],"锁":["chinese_simplified"],"淀":["chinese_simplified","chinese_traditional"],"恨":["chinese_simplified","chinese_traditional"],"牲":["chinese_simplified","chinese_traditional"],"霸":["chinese_simplified","chinese_traditional"],"爬":["chinese_simplified","chinese_traditional"],"赏":["chinese_simplified"],"逆":["chinese_simplified","chinese_traditional"],"玩":["chinese_simplified","chinese_traditional"],"陵":["chinese_simplified","chinese_traditional"],"祝":["chinese_simplified","chinese_traditional"],"秒":["chinese_simplified","chinese_traditional"],"浙":["chinese_simplified","chinese_traditional"],"貌":["chinese_simplified","chinese_traditional"],"役":["chinese_simplified","chinese_traditional"],"彼":["chinese_simplified","chinese_traditional"],"悉":["chinese_simplified","chinese_traditional"],"鸭":["chinese_simplified"],"趋":["chinese_simplified"],"凤":["chinese_simplified"],"晨":["chinese_simplified","chinese_traditional"],"畜":["chinese_simplified","chinese_traditional"],"辈":["chinese_simplified"],"秩":["chinese_simplified","chinese_traditional"],"卵":["chinese_simplified","chinese_traditional"],"署":["chinese_simplified","chinese_traditional"],"梯":["chinese_simplified","chinese_traditional"],"炎":["chinese_simplified","chinese_traditional"],"滩":["chinese_simplified"],"棋":["chinese_simplified","chinese_traditional"],"驱":["chinese_simplified"],"筛":["chinese_simplified"],"峡":["chinese_simplified"],"冒":["chinese_simplified","chinese_traditional"],"啥":["chinese_simplified","chinese_traditional"],"寿":["chinese_simplified"],"译":["chinese_simplified"],"浸":["chinese_simplified","chinese_traditional"],"泉":["chinese_simplified","chinese_traditional"],"帽":["chinese_simplified","chinese_traditional"],"迟":["chinese_simplified"],"硅":["chinese_simplified"],"疆":["chinese_simplified","chinese_traditional"],"贷":["chinese_simplified"],"漏":["chinese_simplified","chinese_traditional"],"稿":["chinese_simplified","chinese_traditional"],"冠":["chinese_simplified","chinese_traditional"],"嫩":["chinese_simplified","chinese_traditional"],"胁":["chinese_simplified"],"芯":["chinese_simplified","chinese_traditional"],"牢":["chinese_simplified","chinese_traditional"],"叛":["chinese_simplified","chinese_traditional"],"蚀":["chinese_simplified"],"奥":["chinese_simplified"],"鸣":["chinese_simplified"],"岭":["chinese_simplified"],"羊":["chinese_simplified","chinese_traditional"],"凭":["chinese_simplified"],"串":["chinese_simplified","chinese_traditional"],"塘":["chinese_simplified","chinese_traditional"],"绘":["chinese_simplified"],"酵":["chinese_simplified","chinese_traditional"],"融":["chinese_simplified","chinese_traditional"],"盆":["chinese_simplified","chinese_traditional"],"锡":["chinese_simplified"],"庙":["chinese_simplified"],"筹":["chinese_simplified"],"冻":["chinese_simplified"],"辅":["chinese_simplified"],"摄":["chinese_simplified"],"袭":["chinese_simplified"],"筋":["chinese_simplified","chinese_traditional"],"拒":["chinese_simplified","chinese_traditional"],"僚":["chinese_simplified","chinese_traditional"],"旱":["chinese_simplified","chinese_traditional"],"钾":["chinese_simplified"],"鸟":["chinese_simplified"],"漆":["chinese_simplified","chinese_traditional"],"沈":["chinese_simplified","chinese_traditional"],"眉":["chinese_simplified","chinese_traditional"],"疏":["chinese_simplified","chinese_traditional"],"添":["chinese_simplified","chinese_traditional"],"棒":["chinese_simplified","chinese_traditional"],"穗":["chinese_simplified","chinese_traditional"],"硝":["chinese_simplified","chinese_traditional"],"韩":["chinese_simplified"],"逼":["chinese_simplified","chinese_traditional"],"扭":["chinese_simplified","chinese_traditional"],"侨":["chinese_simplified"],"凉":["chinese_simplified"],"挺":["chinese_simplified","chinese_traditional"],"碗":["chinese_simplified","chinese_traditional"],"栽":["chinese_simplified","chinese_traditional"],"炒":["chinese_simplified","chinese_traditional"],"杯":["chinese_simplified","chinese_traditional"],"患":["chinese_simplified","chinese_traditional"],"馏":["chinese_simplified"],"劝":["chinese_simplified"],"豪":["chinese_simplified","chinese_traditional"],"辽":["chinese_simplified"],"勃":["chinese_simplified","chinese_traditional"],"鸿":["chinese_simplified"],"旦":["chinese_simplified","chinese_traditional"],"吏":["chinese_simplified","chinese_traditional"],"拜":["chinese_simplified","chinese_traditional"],"狗":["chinese_simplified","chinese_traditional"],"埋":["chinese_simplified","chinese_traditional"],"辊":["chinese_simplified"],"掩":["chinese_simplified","chinese_traditional"],"饮":["chinese_simplified"],"搬":["chinese_simplified","chinese_traditional"],"骂":["chinese_simplified"],"辞":["chinese_simplified"],"勾":["chinese_simplified","chinese_traditional"],"扣":["chinese_simplified","chinese_traditional"],"估":["chinese_simplified","chinese_traditional"],"蒋":["chinese_simplified"],"绒":["chinese_simplified"],"雾":["chinese_simplified"],"丈":["chinese_simplified","chinese_traditional"],"朵":["chinese_simplified","chinese_traditional"],"姆":["chinese_simplified","chinese_traditional"],"拟":["chinese_simplified"],"宇":["chinese_simplified","chinese_traditional"],"辑":["chinese_simplified"],"陕":["chinese_simplified"],"雕":["chinese_simplified","chinese_traditional"],"偿":["chinese_simplified"],"蓄":["chinese_simplified","chinese_traditional"],"崇":["chinese_simplified","chinese_traditional"],"剪":["chinese_simplified","chinese_traditional"],"倡":["chinese_simplified","chinese_traditional"],"厅":["chinese_simplified"],"咬":["chinese_simplified","chinese_traditional"],"驶":["chinese_simplified"],"薯":["chinese_simplified","chinese_traditional"],"刷":["chinese_simplified","chinese_traditional"],"斥":["chinese_simplified","chinese_traditional"],"番":["chinese_simplified","chinese_traditional"],"赋":["chinese_simplified"],"奉":["chinese_simplified","chinese_traditional"],"佛":["chinese_simplified","chinese_traditional"],"浇":["chinese_simplified"],"漫":["chinese_simplified","chinese_traditional"],"曼":["chinese_simplified","chinese_traditional"],"扇":["chinese_simplified","chinese_traditional"],"钙":["chinese_simplified"],"桃":["chinese_simplified","chinese_traditional"],"扶":["chinese_simplified","chinese_traditional"],"仔":["chinese_simplified","chinese_traditional"],"返":["chinese_simplified","chinese_traditional"],"俗":["chinese_simplified","chinese_traditional"],"亏":["chinese_simplified"],"腔":["chinese_simplified","chinese_traditional"],"鞋":["chinese_simplified","chinese_traditional"],"棱":["chinese_simplified","chinese_traditional"],"覆":["chinese_simplified","chinese_traditional"],"框":["chinese_simplified","chinese_traditional"],"悄":["chinese_simplified","chinese_traditional"],"叔":["chinese_simplified","chinese_traditional"],"撞":["chinese_simplified","chinese_traditional"],"骗":["chinese_simplified"],"勘":["chinese_simplified","chinese_traditional"],"旺":["chinese_simplified","chinese_traditional"],"沸":["chinese_simplified","chinese_traditional"],"孤":["chinese_simplified","chinese_traditional"],"吐":["chinese_simplified","chinese_traditional"],"孟":["chinese_simplified","chinese_traditional"],"渠":["chinese_simplified","chinese_traditional"],"屈":["chinese_simplified","chinese_traditional"],"疾":["chinese_simplified","chinese_traditional"],"妙":["chinese_simplified","chinese_traditional"],"惜":["chinese_simplified","chinese_traditional"],"仰":["chinese_simplified","chinese_traditional"],"狠":["chinese_simplified","chinese_traditional"],"胀":["chinese_simplified"],"谐":["chinese_simplified"],"抛":["chinese_simplified"],"霉":["chinese_simplified"],"桑":["chinese_simplified","chinese_traditional"],"岗":["chinese_simplified"],"嘛":["chinese_simplified","chinese_traditional"],"衰":["chinese_simplified","chinese_traditional"],"盗":["chinese_simplified"],"渗":["chinese_simplified"],"脏":["chinese_simplified"],"赖":["chinese_simplified"],"涌":["chinese_simplified"],"甜":["chinese_simplified","chinese_traditional"],"曹":["chinese_simplified","chinese_traditional"],"阅":["chinese_simplified"],"肌":["chinese_simplified","chinese_traditional"],"哩":["chinese_simplified","chinese_traditional"],"厉":["chinese_simplified"],"烃":["chinese_simplified"],"纬":["chinese_simplified"],"毅":["chinese_simplified","chinese_traditional"],"昨":["chinese_simplified","chinese_traditional"],"伪":["chinese_simplified"],"症":["chinese_simplified","chinese_traditional"],"煮":["chinese_simplified","chinese_traditional"],"叹":["chinese_simplified"],"钉":["chinese_simplified"],"搭":["chinese_simplified","chinese_traditional"],"茎":["chinese_simplified"],"笼":["chinese_simplified"],"酷":["chinese_simplified","chinese_traditional"],"偷":["chinese_simplified","chinese_traditional"],"弓":["chinese_simplified","chinese_traditional"],"锥":["chinese_simplified"],"恒":["chinese_simplified"],"杰":["chinese_simplified"],"坑":["chinese_simplified","chinese_traditional"],"鼻":["chinese_simplified","chinese_traditional"],"翼":["chinese_simplified","chinese_traditional"],"纶":["chinese_simplified"],"叙":["chinese_simplified"],"狱":["chinese_simplified"],"逮":["chinese_simplified","chinese_traditional"],"罐":["chinese_simplified","chinese_traditional"],"络":["chinese_simplified"],"棚":["chinese_simplified","chinese_traditional"],"抑":["chinese_simplified","chinese_traditional"],"膨":["chinese_simplified","chinese_traditional"],"蔬":["chinese_simplified","chinese_traditional"],"寺":["chinese_simplified","chinese_traditional"],"骤":["chinese_simplified"],"穆":["chinese_simplified","chinese_traditional"],"冶":["chinese_simplified","chinese_traditional"],"枯":["chinese_simplified","chinese_traditional"],"册":["chinese_simplified"],"尸":["chinese_simplified"],"凸":["chinese_simplified","chinese_traditional"],"绅":["chinese_simplified"],"坯":["chinese_simplified","chinese_traditional"],"牺":["chinese_simplified"],"焰":["chinese_simplified","chinese_traditional"],"轰":["chinese_simplified"],"欣":["chinese_simplified","chinese_traditional"],"晋":["chinese_simplified"],"瘦":["chinese_simplified","chinese_traditional"],"御":["chinese_simplified"],"锭":["chinese_simplified"],"锦":["chinese_simplified"],"丧":["chinese_simplified"],"旬":["chinese_simplified","chinese_traditional"],"锻":["chinese_simplified"],"垄":["chinese_simplified"],"搜":["chinese_simplified","chinese_traditional"],"扑":["chinese_simplified"],"邀":["chinese_simplified","chinese_traditional"],"亭":["chinese_simplified","chinese_traditional"],"酯":["chinese_simplified","chinese_traditional"],"迈":["chinese_simplified"],"舒":["chinese_simplified","chinese_traditional"],"脆":["chinese_simplified","chinese_traditional"],"酶":["chinese_simplified","chinese_traditional"],"闲":["chinese_simplified"],"忧":["chinese_simplified"],"酚":["chinese_simplified","chinese_traditional"],"顽":["chinese_simplified"],"羽":["chinese_simplified","chinese_traditional"],"涨":["chinese_simplified"],"卸":["chinese_simplified","chinese_traditional"],"仗":["chinese_simplified","chinese_traditional"],"陪":["chinese_simplified","chinese_traditional"],"辟":["chinese_simplified"],"惩":["chinese_simplified"],"杭":["chinese_simplified","chinese_traditional"],"姚":["chinese_simplified","chinese_traditional"],"肚":["chinese_simplified","chinese_traditional"],"捉":["chinese_simplified","chinese_traditional"],"飘":["chinese_simplified"],"漂":["chinese_simplified","chinese_traditional"],"昆":["chinese_simplified","chinese_traditional"],"欺":["chinese_simplified","chinese_traditional"],"吾":["chinese_simplified","chinese_traditional"],"郎":["chinese_simplified","chinese_traditional"],"烷":["chinese_simplified","chinese_traditional"],"汁":["chinese_simplified","chinese_traditional"],"呵":["chinese_simplified","chinese_traditional"],"饰":["chinese_simplified"],"萧":["chinese_simplified"],"雅":["chinese_simplified","chinese_traditional"],"邮":["chinese_simplified"],"迁":["chinese_simplified"],"燕":["chinese_simplified","chinese_traditional"],"撒":["chinese_simplified","chinese_traditional"],"姻":["chinese_simplified","chinese_traditional"],"赴":["chinese_simplified","chinese_traditional"],"宴":["chinese_simplified","chinese_traditional"],"烦":["chinese_simplified"],"债":["chinese_simplified"],"帐":["chinese_simplified"],"斑":["chinese_simplified","chinese_traditional"],"铃":["chinese_simplified"],"旨":["chinese_simplified","chinese_traditional"],"醇":["chinese_simplified","chinese_traditional"],"董":["chinese_simplified","chinese_traditional"],"饼":["chinese_simplified"],"雏":["chinese_simplified"],"姿":["chinese_simplified","chinese_traditional"],"拌":["chinese_simplified","chinese_traditional"],"傅":["chinese_simplified","chinese_traditional"],"腹":["chinese_simplified","chinese_traditional"],"妥":["chinese_simplified","chinese_traditional"],"揉":["chinese_simplified","chinese_traditional"],"贤":["chinese_simplified"],"拆":["chinese_simplified","chinese_traditional"],"歪":["chinese_simplified","chinese_traditional"],"葡":["chinese_simplified","chinese_traditional"],"胺":["chinese_simplified","chinese_traditional"],"丢":["chinese_simplified"],"浩":["chinese_simplified","chinese_traditional"],"徽":["chinese_simplified","chinese_traditional"],"昂":["chinese_simplified","chinese_traditional"],"垫":["chinese_simplified"],"挡":["chinese_simplified"],"览":["chinese_simplified"],"贪":["chinese_simplified"],"慰":["chinese_simplified","chinese_traditional"],"缴":["chinese_simplified"],"汪":["chinese_simplified","chinese_traditional"],"慌":["chinese_simplified","chinese_traditional"],"冯":["chinese_simplified"],"诺":["chinese_simplified"],"姜":["chinese_simplified","chinese_traditional"],"谊":["chinese_simplified"],"凶":["chinese_simplified"],"劣":["chinese_simplified","chinese_traditional"],"诬":["chinese_simplified"],"耀":["chinese_simplified","chinese_traditional"],"昏":["chinese_simplified","chinese_traditional"],"躺":["chinese_simplified","chinese_traditional"],"盈":["chinese_simplified","chinese_traditional"],"骑":["chinese_simplified"],"乔":["chinese_simplified"],"溪":["chinese_simplified","chinese_traditional"],"丛":["chinese_simplified"],"卢":["chinese_simplified"],"抹":["chinese_simplified","chinese_traditional"],"闷":["chinese_simplified"],"咨":["chinese_simplified"],"刮":["chinese_simplified","chinese_traditional"],"驾":["chinese_simplified"],"缆":["chinese_simplified"],"悟":["chinese_simplified","chinese_traditional"],"摘":["chinese_simplified","chinese_traditional"],"铒":["chinese_simplified"],"掷":["chinese_simplified"],"颇":["chinese_simplified"],"幻":["chinese_simplified","chinese_traditional"],"柄":["chinese_simplified","chinese_traditional"],"惠":["chinese_simplified","chinese_traditional"],"惨":["chinese_simplified"],"佳":["chinese_simplified","chinese_traditional"],"仇":["chinese_simplified","chinese_traditional"],"腊":["chinese_simplified"],"窝":["chinese_simplified"],"涤":["chinese_simplified"],"剑":["chinese_simplified"],"瞧":["chinese_simplified","chinese_traditional"],"堡":["chinese_simplified","chinese_traditional"],"泼":["chinese_simplified"],"葱":["chinese_simplified"],"罩":["chinese_simplified","chinese_traditional"],"霍":["chinese_simplified","chinese_traditional"],"捞":["chinese_simplified"],"胎":["chinese_simplified","chinese_traditional"],"苍":["chinese_simplified"],"滨":["chinese_simplified"],"俩":["chinese_simplified"],"捅":["chinese_simplified","chinese_traditional"],"湘":["chinese_simplified","chinese_traditional"],"砍":["chinese_simplified","chinese_traditional"],"霞":["chinese_simplified","chinese_traditional"],"邵":["chinese_simplified","chinese_traditional"],"萄":["chinese_simplified","chinese_traditional"],"疯":["chinese_simplified"],"淮":["chinese_simplified","chinese_traditional"],"遂":["chinese_simplified","chinese_traditional"],"熊":["chinese_simplified","chinese_traditional"],"粪":["chinese_simplified"],"烘":["chinese_simplified","chinese_traditional"],"宿":["chinese_simplified","chinese_traditional"],"档":["chinese_simplified"],"戈":["chinese_simplified","chinese_traditional"],"驳":["chinese_simplified"],"嫂":["chinese_simplified","chinese_traditional"],"裕":["chinese_simplified","chinese_traditional"],"徙":["chinese_simplified","chinese_traditional"],"箭":["chinese_simplified","chinese_traditional"],"捐":["chinese_simplified","chinese_traditional"],"肠":["chinese_simplified"],"撑":["chinese_simplified"],"晒":["chinese_simplified"],"辨":["chinese_simplified","chinese_traditional"],"殿":["chinese_simplified","chinese_traditional"],"莲":["chinese_simplified"],"摊":["chinese_simplified"],"搅":["chinese_simplified"],"酱":["chinese_simplified"],"屏":["chinese_simplified","chinese_traditional"],"疫":["chinese_simplified","chinese_traditional"],"哀":["chinese_simplified","chinese_traditional"],"蔡":["chinese_simplified","chinese_traditional"],"堵":["chinese_simplified","chinese_traditional"],"沫":["chinese_simplified","chinese_traditional"],"皱":["chinese_simplified"],"畅":["chinese_simplified"],"叠":["chinese_simplified"],"阁":["chinese_simplified"],"莱":["chinese_simplified"],"敲":["chinese_simplified","chinese_traditional"],"辖":["chinese_simplified"],"钩":["chinese_simplified"],"痕":["chinese_simplified","chinese_traditional"],"坝":["chinese_simplified"],"巷":["chinese_simplified","chinese_traditional"],"饿":["chinese_simplified"],"祸":["chinese_simplified"],"丘":["chinese_simplified","chinese_traditional"],"玄":["chinese_simplified","chinese_traditional"],"溜":["chinese_simplified","chinese_traditional"],"曰":["chinese_simplified","chinese_traditional"],"逻":["chinese_simplified"],"彭":["chinese_simplified","chinese_traditional"],"尝":["chinese_simplified"],"卿":["chinese_simplified","chinese_traditional"],"妨":["chinese_simplified","chinese_traditional"],"艇":["chinese_simplified","chinese_traditional"],"吞":["chinese_simplified","chinese_traditional"],"韦":["chinese_simplified"],"怨":["chinese_simplified","chinese_traditional"],"矮":["chinese_simplified","chinese_traditional"],"歇":["chinese_simplified","chinese_traditional"],"這":["chinese_traditional"],"為":["chinese_traditional"],"個":["chinese_traditional"],"國":["chinese_traditional"],"時":["chinese_traditional"],"來":["chinese_traditional"],"們":["chinese_traditional"],"於":["chinese_traditional"],"對":["chinese_traditional"],"會":["chinese_traditional"],"發":["chinese_traditional"],"動":["chinese_traditional"],"過":["chinese_traditional"],"說":["chinese_traditional"],"產":["chinese_traditional"],"種":["chinese_traditional"],"後":["chinese_traditional"],"學":["chinese_traditional"],"經":["chinese_traditional"],"進":["chinese_traditional"],"著":["chinese_traditional"],"電":["chinese_traditional"],"裡":["chinese_traditional"],"現":["chinese_traditional"],"實":["chinese_traditional"],"兩":["chinese_traditional"],"體":["chinese_traditional"],"機":["chinese_traditional"],"當":["chinese_traditional"],"點":["chinese_traditional"],"從":["chinese_traditional"],"業":["chinese_traditional"],"應":["chinese_traditional"],"開":["chinese_traditional"],"還":["chinese_traditional"],"義":["chinese_traditional"],"間":["chinese_traditional"],"樣":["chinese_traditional"],"與":["chinese_traditional"],"關":["chinese_traditional"],"線":["chinese_traditional"],"內":["chinese_traditional"],"數":["chinese_traditional"],"麼":["chinese_traditional"],"質":["chinese_traditional"],"氣":["chinese_traditional"],"變":["chinese_traditional"],"條":["chinese_traditional"],"沒":["chinese_traditional"],"結":["chinese_traditional"],"問":["chinese_traditional"],"無":["chinese_traditional"],"軍":["chinese_traditional"],"並":["chinese_traditional"],"題":["chinese_traditional"],"黨":["chinese_traditional"],"員":["chinese_traditional"],"總":["chinese_traditional"],"設":["chinese_traditional"],"長":["chinese_traditional"],"頭":["chinese_traditional"],"資":["chinese_traditional"],"邊":["chinese_traditional"],"級":["chinese_traditional"],"圖":["chinese_traditional"],"統":["chinese_traditional"],"較":["chinese_traditional"],"將":["chinese_traditional"],"組":["chinese_traditional"],"見":["chinese_traditional"],"計":["chinese_traditional"],"別":["chinese_traditional"],"論":["chinese_traditional"],"運":["chinese_traditional"],"農":["chinese_traditional"],"幾":["chinese_traditional"],"區":["chinese_traditional"],"強":["chinese_traditional"],"決":["chinese_traditional"],"幹":["chinese_traditional"],"戰":["chinese_traditional"],"則":["chinese_traditional"],"據":["chinese_traditional"],"處":["chinese_traditional"],"隊":["chinese_traditional"],"給":["chinese_traditional"],"門":["chinese_traditional"],"規":["chinese_traditional"],"熱":["chinese_traditional"],"領":["chinese_traditional"],"東":["chinese_traditional"],"導":["chinese_traditional"],"壓":["chinese_traditional"],"爭":["chinese_traditional"],"濟":["chinese_traditional"],"階":["chinese_traditional"],"術":["chinese_traditional"],"極":["chinese_traditional"],"聯":["chinese_traditional"],"認":["chinese_traditional"],"權":["chinese_traditional"],"證":["chinese_traditional"],"採":["chinese_traditional"],"轉":["chinese_traditional"],"單":["chinese_traditional"],"風":["chinese_traditional"],"帶":["chinese_traditional"],"場":["chinese_traditional"],"車":["chinese_traditional"],"務":["chinese_traditional"],"萬":["chinese_traditional"],"達":["chinese_traditional"],"積":["chinese_traditional"],"議":["chinese_traditional"],"聲":["chinese_traditional"],"報":["chinese_traditional"],"鬥":["chinese_traditional"],"類":["chinese_traditional"],"離":["chinese_traditional"],"華":["chinese_traditional"],"確":["chinese_traditional"],"張":["chinese_traditional"],"馬":["chinese_traditional"],"節":["chinese_traditional"],"話":["chinese_traditional"],"況":["chinese_traditional"],"溫":["chinese_traditional"],"傳":["chinese_traditional"],"許":["chinese_traditional"],"廣":["chinese_traditional"],"記":["chinese_traditional"],"觀":["chinese_traditional"],"織":["chinese_traditional"],"裝":["chinese_traditional"],"眾":["chinese_traditional"],"書":["chinese_traditional"],"兒":["chinese_traditional"],"須":["chinese_traditional"],"際":["chinese_traditional"],"驗":["chinese_traditional"],"連":["chinese_traditional"],"斷":["chinese_traditional"],"難":["chinese_traditional"],"礦":["chinese_traditional"],"週":["chinese_traditional"],"備":["chinese_traditional"],"辦":["chinese_traditional"],"習":["chinese_traditional"],"響":["chinese_traditional"],"約":["chinese_traditional"],"勞":["chinese_traditional"],"團":["chinese_traditional"],"歷":["chinese_traditional"],"構":["chinese_traditional"],"稱":["chinese_traditional"],"準":["chinese_traditional"],"號":["chinese_traditional"],"維":["chinese_traditional"],"劃":["chinese_traditional"],"選":["chinese_traditional"],"標":["chinese_traditional"],"寫":["chinese_traditional"],"親":["chinese_traditional"],"養":["chinese_traditional"],"層":["chinese_traditional"],"卻":["chinese_traditional"],"專":["chinese_traditional"],"狀":["chinese_traditional"],"廠":["chinese_traditional"],"識":["chinese_traditional"],"適":["chinese_traditional"],"屬":["chinese_traditional"],"圓":["chinese_traditional"],"調":["chinese_traditional"],"滿":["chinese_traditional"],"縣":["chinese_traditional"],"參":["chinese_traditional"],"紅":["chinese_traditional"],"細":["chinese_traditional"],"聽":["chinese_traditional"],"該":["chinese_traditional"],"鐵":["chinese_traditional"],"價":["chinese_traditional"],"嚴":["chinese_traditional"],"隨":["chinese_traditional"],"蘇":["chinese_traditional"],"爾":["chinese_traditional"],"講":["chinese_traditional"],"黃":["chinese_traditional"],"顯":["chinese_traditional"],"談":["chinese_traditional"],"藝":["chinese_traditional"],"營":["chinese_traditional"],"項":["chinese_traditional"],"舉":["chinese_traditional"],"勢":["chinese_traditional"],"幫":["chinese_traditional"],"輪":["chinese_traditional"],"亞":["chinese_traditional"],"師":["chinese_traditional"],"圍":["chinese_traditional"],"遠":["chinese_traditional"],"態":["chinese_traditional"],"減":["chinese_traditional"],"樹":["chinese_traditional"],"葉":["chinese_traditional"],"魚":["chinese_traditional"],"視":["chinese_traditional"],"僅":["chinese_traditional"],"費":["chinese_traditional"],"緊":["chinese_traditional"],"愛":["chinese_traditional"],"續":["chinese_traditional"],"輕":["chinese_traditional"],"試":["chinese_traditional"],"護":["chinese_traditional"],"練":["chinese_traditional"],"負":["chinese_traditional"],"擊":["chinese_traditional"],"繼":["chinese_traditional"],"興":["chinese_traditional"],"餘":["chinese_traditional"],"堅":["chinese_traditional"],"輸":["chinese_traditional"],"夠":["chinese_traditional"],"筆":["chinese_traditional"],"佔":["chinese_traditional"],"財":["chinese_traditional"],"職":["chinese_traditional"],"覺":["chinese_traditional"],"漢":["chinese_traditional"],"畫":["chinese_traditional"],"雖":["chinese_traditional"],"雜":["chinese_traditional"],"飛":["chinese_traditional"],"檢":["chinese_traditional"],"昇":["chinese_traditional"],"陽":["chinese_traditional"],"創":["chinese_traditional"],"壞":["chinese_traditional"],"徑":["chinese_traditional"],"換":["chinese_traditional"],"鋼":["chinese_traditional"],"責":["chinese_traditional"],"簡":["chinese_traditional"],"錢":["chinese_traditional"],"盡":["chinese_traditional"],"衝":["chinese_traditional"],"獨":["chinese_traditional"],"環":["chinese_traditional"],"雙":["chinese_traditional"],"請":["chinese_traditional"],"讓":["chinese_traditional"],"軸":["chinese_traditional"],"紀":["chinese_traditional"],"優":["chinese_traditional"],"頂":["chinese_traditional"],"礎":["chinese_traditional"],"載":["chinese_traditional"],"敵":["chinese_traditional"],"勝":["chinese_traditional"],"絕":["chinese_traditional"],"塊":["chinese_traditional"],"劑":["chinese_traditional"],"測":["chinese_traditional"],"絲":["chinese_traditional"],"協":["chinese_traditional"],"訴":["chinese_traditional"],"陳":["chinese_traditional"],"羅":["chinese_traditional"],"鹽":["chinese_traditional"],"錯":["chinese_traditional"],"頻":["chinese_traditional"],"終":["chinese_traditional"],"雲":["chinese_traditional"],"衛":["chinese_traditional"],"燒":["chinese_traditional"],"遊":["chinese_traditional"],"舊":["chinese_traditional"],"貨":["chinese_traditional"],"損":["chinese_traditional"],"預":["chinese_traditional"],"穩":["chinese_traditional"],"媽":["chinese_traditional"],"擴":["chinese_traditional"],"銀":["chinese_traditional"],"語":["chinese_traditional"],"揮":["chinese_traditional"],"紙":["chinese_traditional"],"醫":["chinese_traditional"],"嗎":["chinese_traditional"],"針":["chinese_traditional"],"劉":["chinese_traditional"],"誤":["chinese_traditional"],"訓":["chinese_traditional"],"願":["chinese_traditional"],"審":["chinese_traditional"],"獲":["chinese_traditional"],"鮮":["chinese_traditional"],"糧":["chinese_traditional"],"脫":["chinese_traditional"],"龍":["chinese_traditional"],"漸":["chinese_traditional"],"歡":["chinese_traditional"],"剛":["chinese_traditional"],"謂":["chinese_traditional"],"討":["chinese_traditional"],"亂":["chinese_traditional"],"殺":["chinese_traditional"],"藥":["chinese_traditional"],"寧":["chinese_traditional"],"魯":["chinese_traditional"],"貴":["chinese_traditional"],"鐘":["chinese_traditional"],"讀":["chinese_traditional"],"豐":["chinese_traditional"],"蘭":["chinese_traditional"],"擔":["chinese_traditional"],"執":["chinese_traditional"],"樂":["chinese_traditional"],"誰":["chinese_traditional"],"順":["chinese_traditional"],"煙":["chinese_traditional"],"縮":["chinese_traditional"],"徵":["chinese_traditional"],"臉":["chinese_traditional"],"腳":["chinese_traditional"],"異":["chinese_traditional"],"買":["chinese_traditional"],"靜":["chinese_traditional"],"補":["chinese_traditional"],"評":["chinese_traditional"],"踐":["chinese_traditional"],"寬":["chinese_traditional"],"揚":["chinese_traditional"],"傷":["chinese_traditional"],"氫":["chinese_traditional"],"憲":["chinese_traditional"],"慶":["chinese_traditional"],"編":["chinese_traditional"],"觸":["chinese_traditional"],"銷":["chinese_traditional"],"詩":["chinese_traditional"],"綠":["chinese_traditional"],"雞":["chinese_traditional"],"孫":["chinese_traditional"],"膠":["chinese_traditional"],"鄉":["chinese_traditional"],"臨":["chinese_traditional"],"陸":["chinese_traditional"],"顧":["chinese_traditional"],"燈":["chinese_traditional"],"歲":["chinese_traditional"],"劇":["chinese_traditional"],"趙":["chinese_traditional"],"課":["chinese_traditional"],"凱":["chinese_traditional"],"額":["chinese_traditional"],"紹":["chinese_traditional"],"齊":["chinese_traditional"],"偉":["chinese_traditional"],"爐":["chinese_traditional"],"楊":["chinese_traditional"],"桿":["chinese_traditional"],"鎮":["chinese_traditional"],"飯":["chinese_traditional"],"濃":["chinese_traditional"],"懷":["chinese_traditional"],"趕":["chinese_traditional"],"庫":["chinese_traditional"],"奪":["chinese_traditional"],"靈":["chinese_traditional"],"稅":["chinese_traditional"],"滅":["chinese_traditional"],"賽":["chinese_traditional"],"歸":["chinese_traditional"],"盤":["chinese_traditional"],"險":["chinese_traditional"],"錄":["chinese_traditional"],"純":["chinese_traditional"],"蓋":["chinese_traditional"],"橫":["chinese_traditional"],"槍":["chinese_traditional"],"潤":["chinese_traditional"],"蟲":["chinese_traditional"],"澤":["chinese_traditional"],"腦":["chinese_traditional"],"歐":["chinese_traditional"],"側":["chinese_traditional"],"徹":["chinese_traditional"],"慮":["chinese_traditional"],"納":["chinese_traditional"],"彈":["chinese_traditional"],"飼":["chinese_traditional"],"麥":["chinese_traditional"],"濕":["chinese_traditional"],"築":["chinese_traditional"],"惡":["chinese_traditional"],"戶":["chinese_traditional"],"訪":["chinese_traditional"],"跡":["chinese_traditional"],"擺":["chinese_traditional"],"賣":["chinese_traditional"],"擇":["chinese_traditional"],"銅":["chinese_traditional"],"獻":["chinese_traditional"],"陣":["chinese_traditional"],"陰":["chinese_traditional"],"樓":["chinese_traditional"],"謀":["chinese_traditional"],"噸":["chinese_traditional"],"豬":["chinese_traditional"],"館":["chinese_traditional"],"爺":["chinese_traditional"],"驚":["chinese_traditional"],"遺":["chinese_traditional"],"纖":["chinese_traditional"],"傾":["chinese_traditional"],"謝":["chinese_traditional"],"奮":["chinese_traditional"],"購":["chinese_traditional"],"監":["chinese_traditional"],"貫":["chinese_traditional"],"釋":["chinese_traditional"],"詞":["chinese_traditional"],"頓":["chinese_traditional"],"寶":["chinese_traditional"],"塵":["chinese_traditional"],"聞":["chinese_traditional"],"殘":["chinese_traditional"],"橋":["chinese_traditional"],"婦":["chinese_traditional"],"綜":["chinese_traditional"],"吳":["chinese_traditional"],"搖":["chinese_traditional"],"贊":["chinese_traditional"],"訂":["chinese_traditional"],"園":["chinese_traditional"],"紛":["chinese_traditional"],"敗":["chinese_traditional"],"榮":["chinese_traditional"],"閉":["chinese_traditional"],"灣":["chinese_traditional"],"鍵":["chinese_traditional"],"駐":["chinese_traditional"],"鍋":["chinese_traditional"],"剝":["chinese_traditional"],"鹼":["chinese_traditional"],"齒":["chinese_traditional"],"煉":["chinese_traditional"],"紡":["chinese_traditional"],"廢":["chinese_traditional"],"緩":["chinese_traditional"],"淨":["chinese_traditional"],"莊":["chinese_traditional"],"貿":["chinese_traditional"],"慣":["chinese_traditional"],"夥":["chinese_traditional"],"勻":["chinese_traditional"],"紗":["chinese_traditional"],"辯":["chinese_traditional"],"億":["chinese_traditional"],"脈":["chinese_traditional"],"薩":["chinese_traditional"],"網":["chinese_traditional"],"噴":["chinese_traditional"],"縱":["chinese_traditional"],"掛":["chinese_traditional"],"賀":["chinese_traditional"],"閃":["chinese_traditional"],"牆":["chinese_traditional"],"軟":["chinese_traditional"],"滾":["chinese_traditional"],"盪":["chinese_traditional"],"儀":["chinese_traditional"],"軋":["chinese_traditional"],"貢":["chinese_traditional"],"鑽":["chinese_traditional"],"幣":["chinese_traditional"],"軌":["chinese_traditional"],"畝":["chinese_traditional"],"畢":["chinese_traditional"],"島":["chinese_traditional"],"鑄":["chinese_traditional"],"湯":["chinese_traditional"],"閥":["chinese_traditional"],"匯":["chinese_traditional"],"繞":["chinese_traditional"],"績":["chinese_traditional"],"啟":["chinese_traditional"],"顏":["chinese_traditional"],"淚":["chinese_traditional"],"藍":["chinese_traditional"],"鏡":["chinese_traditional"],"壯":["chinese_traditional"],"鋒":["chinese_traditional"],"貧":["chinese_traditional"],"虛":["chinese_traditional"],"彎":["chinese_traditional"],"綱":["chinese_traditional"],"隸":["chinese_traditional"],"宮":["chinese_traditional"],"違":["chinese_traditional"],"夾":["chinese_traditional"],"緣":["chinese_traditional"],"窮":["chinese_traditional"],"溝":["chinese_traditional"],"繩":["chinese_traditional"],"憶":["chinese_traditional"],"漿":["chinese_traditional"],"欄":["chinese_traditional"],"擁":["chinese_traditional"],"貯":["chinese_traditional"],"禮":["chinese_traditional"],"濾":["chinese_traditional"],"鈉":["chinese_traditional"],"紋":["chinese_traditional"],"罷":["chinese_traditional"],"罰":["chinese_traditional"],"潛":["chinese_traditional"],"縫":["chinese_traditional"],"飽":["chinese_traditional"],"獎":["chinese_traditional"],"鋁":["chinese_traditional"],"麗":["chinese_traditional"],"鏈":["chinese_traditional"],"掃":["chinese_traditional"],"諸":["chinese_traditional"],"勵":["chinese_traditional"],"潔":["chinese_traditional"],"災":["chinese_traditional"],"鑑":["chinese_traditional"],"訟":["chinese_traditional"],"毀":["chinese_traditional"],"屆":["chinese_traditional"],"躍":["chinese_traditional"],"艱":["chinese_traditional"],"貝":["chinese_traditional"],"碼":["chinese_traditional"],"夢":["chinese_traditional"],"漁":["chinese_traditional"],"顆":["chinese_traditional"],"鉛":["chinese_traditional"],"倉":["chinese_traditional"],"銳":["chinese_traditional"],"曉":["chinese_traditional"],"隱":["chinese_traditional"],"礙":["chinese_traditional"],"撥":["chinese_traditional"],"肅":["chinese_traditional"],"牽":["chinese_traditional"],"搶":["chinese_traditional"],"殼":["chinese_traditional"],"訊":["chinese_traditional"],"誠":["chinese_traditional"],"頁":["chinese_traditional"],"齡":["chinese_traditional"],"倫":["chinese_traditional"],"尋":["chinese_traditional"],"鋪":["chinese_traditional"],"聖":["chinese_traditional"],"鄭":["chinese_traditional"],"騰":["chinese_traditional"],"貼":["chinese_traditional"],"闊":["chinese_traditional"],"輛":["chinese_traditional"],"儲":["chinese_traditional"],"簽":["chinese_traditional"],"鬧":["chinese_traditional"],"擾":["chinese_traditional"],"遞":["chinese_traditional"],"戲":["chinese_traditional"],"餵":["chinese_traditional"],"療":["chinese_traditional"],"撫":["chinese_traditional"],"蝦":["chinese_traditional"],"蠟":["chinese_traditional"],"鄰":["chinese_traditional"],"鞏":["chinese_traditional"],"擠":["chinese_traditional"],"棄":["chinese_traditional"],"勁":["chinese_traditional"],"鄧":["chinese_traditional"],"爛":["chinese_traditional"],"磚":["chinese_traditional"],"烏":["chinese_traditional"],"艦":["chinese_traditional"],"淺":["chinese_traditional"],"暫":["chinese_traditional"],"膽":["chinese_traditional"],"詳":["chinese_traditional"],"譜":["chinese_traditional"],"賓":["chinese_traditional"],"輝":["chinese_traditional"],"憤":["chinese_traditional"],"競":["chinese_traditional"],"緒":["chinese_traditional"],"塗":["chinese_traditional"],"偵":["chinese_traditional"],"懸":["chinese_traditional"],"糾":["chinese_traditional"],"鎖":["chinese_traditional"],"賞":["chinese_traditional"],"鴨":["chinese_traditional"],"趨":["chinese_traditional"],"鳳":["chinese_traditional"],"輩":["chinese_traditional"],"灘":["chinese_traditional"],"驅":["chinese_traditional"],"篩":["chinese_traditional"],"峽":["chinese_traditional"],"壽":["chinese_traditional"],"譯":["chinese_traditional"],"遲":["chinese_traditional"],"矽":["chinese_traditional"],"貸":["chinese_traditional"],"脅":["chinese_traditional"],"蝕":["chinese_traditional"],"奧":["chinese_traditional"],"鳴":["chinese_traditional"],"嶺":["chinese_traditional"],"憑":["chinese_traditional"],"繪":["chinese_traditional"],"錫":["chinese_traditional"],"廟":["chinese_traditional"],"籌":["chinese_traditional"],"凍":["chinese_traditional"],"輔":["chinese_traditional"],"攝":["chinese_traditional"],"襲":["chinese_traditional"],"鉀":["chinese_traditional"],"鳥":["chinese_traditional"],"韓":["chinese_traditional"],"僑":["chinese_traditional"],"涼":["chinese_traditional"],"餾":["chinese_traditional"],"勸":["chinese_traditional"],"遼":["chinese_traditional"],"鴻":["chinese_traditional"],"輥":["chinese_traditional"],"飲":["chinese_traditional"],"罵":["chinese_traditional"],"辭":["chinese_traditional"],"蔣":["chinese_traditional"],"絨":["chinese_traditional"],"霧":["chinese_traditional"],"擬":["chinese_traditional"],"輯":["chinese_traditional"],"陝":["chinese_traditional"],"償":["chinese_traditional"],"廳":["chinese_traditional"],"駛":["chinese_traditional"],"賦":["chinese_traditional"],"澆":["chinese_traditional"],"鈣":["chinese_traditional"],"虧":["chinese_traditional"],"騙":["chinese_traditional"],"脹":["chinese_traditional"],"諧":["chinese_traditional"],"拋":["chinese_traditional"],"黴":["chinese_traditional"],"崗":["chinese_traditional"],"盜":["chinese_traditional"],"滲":["chinese_traditional"],"臟":["chinese_traditional"],"賴":["chinese_traditional"],"湧":["chinese_traditional"],"閱":["chinese_traditional"],"厲":["chinese_traditional"],"烴":["chinese_traditional"],"緯":["chinese_traditional"],"偽":["chinese_traditional"],"嘆":["chinese_traditional"],"釘":["chinese_traditional"],"莖":["chinese_traditional"],"籠":["chinese_traditional"],"錐":["chinese_traditional"],"恆":["chinese_traditional"],"傑":["chinese_traditional"],"綸":["chinese_traditional"],"敘":["chinese_traditional"],"獄":["chinese_traditional"],"絡":["chinese_traditional"],"驟":["chinese_traditional"],"冊":["chinese_traditional"],"屍":["chinese_traditional"],"紳":["chinese_traditional"],"犧":["chinese_traditional"],"轟":["chinese_traditional"],"晉":["chinese_traditional"],"禦":["chinese_traditional"],"錠":["chinese_traditional"],"錦":["chinese_traditional"],"喪":["chinese_traditional"],"鍛":["chinese_traditional"],"壟":["chinese_traditional"],"撲":["chinese_traditional"],"邁":["chinese_traditional"],"閒":["chinese_traditional"],"憂":["chinese_traditional"],"頑":["chinese_traditional"],"漲":["chinese_traditional"],"闢":["chinese_traditional"],"懲":["chinese_traditional"],"飄":["chinese_traditional"],"飾":["chinese_traditional"],"蕭":["chinese_traditional"],"郵":["chinese_traditional"],"遷":["chinese_traditional"],"煩":["chinese_traditional"],"債":["chinese_traditional"],"帳":["chinese_traditional"],"鈴":["chinese_traditional"],"餅":["chinese_traditional"],"雛":["chinese_traditional"],"賢":["chinese_traditional"],"丟":["chinese_traditional"],"墊":["chinese_traditional"],"擋":["chinese_traditional"],"覽":["chinese_traditional"],"貪":["chinese_traditional"],"繳":["chinese_traditional"],"馮":["chinese_traditional"],"諾":["chinese_traditional"],"誼":["chinese_traditional"],"兇":["chinese_traditional"],"誣":["chinese_traditional"],"騎":["chinese_traditional"],"喬":["chinese_traditional"],"叢":["chinese_traditional"],"盧":["chinese_traditional"],"悶":["chinese_traditional"],"諮":["chinese_traditional"],"駕":["chinese_traditional"],"纜":["chinese_traditional"],"鉺":["chinese_traditional"],"擲":["chinese_traditional"],"頗":["chinese_traditional"],"慘":["chinese_traditional"],"臘":["chinese_traditional"],"窩":["chinese_traditional"],"滌":["chinese_traditional"],"劍":["chinese_traditional"],"潑":["chinese_traditional"],"蔥":["chinese_traditional"],"撈":["chinese_traditional"],"蒼":["chinese_traditional"],"濱":["chinese_traditional"],"倆":["chinese_traditional"],"瘋":["chinese_traditional"],"糞":["chinese_traditional"],"檔":["chinese_traditional"],"駁":["chinese_traditional"],"腸":["chinese_traditional"],"撐":["chinese_traditional"],"曬":["chinese_traditional"],"蓮":["chinese_traditional"],"攤":["chinese_traditional"],"攪":["chinese_traditional"],"醬":["chinese_traditional"],"皺":["chinese_traditional"],"暢":["chinese_traditional"],"疊":["chinese_traditional"],"閣":["chinese_traditional"],"萊":["chinese_traditional"],"轄":["chinese_traditional"],"鉤":["chinese_traditional"],"壩":["chinese_traditional"],"餓":["chinese_traditional"],"禍":["chinese_traditional"],"邏":["chinese_traditional"],"嘗":["chinese_traditional"],"韋":["chinese_traditional"],"abdikace":["czech"],"abeceda":["czech"],"adresa":["czech"],"agrese":["czech"],"akce":["czech"],"aktovka":["czech"],"alej":["czech"],"alkohol":["czech"],"amputace":["czech"],"ananas":["czech"],"andulka":["czech"],"anekdota":["czech"],"anketa":["czech"],"antika":["czech"],"anulovat":["czech"],"archa":["czech"],"arogance":["czech"],"asfalt":["czech","turkish"],"asistent":["czech"],"aspirace":["czech"],"astma":["czech"],"astronom":["czech"],"atlas":["czech"],"atletika":["czech"],"atol":["czech"],"autobus":["czech"],"azyl":["czech"],"babka":["czech"],"bachor":["czech"],"bacil":["czech"],"baculka":["czech"],"badatel":["czech"],"bageta":["czech"],"bagr":["czech"],"bahno":["czech"],"bakterie":["czech"],"balada":["czech"],"baletka":["czech"],"balkon":["czech"],"balonek":["czech"],"balvan":["czech"],"balza":["czech"],"bambus":["czech"],"bankomat":["czech"],"barbar":["czech"],"baret":["czech"],"barman":["czech"],"baroko":["czech"],"barva":["czech"],"baterka":["czech"],"batoh":["czech"],"bavlna":["czech"],"bazalka":["czech"],"bazilika":["czech"],"bazuka":["czech"],"bedna":["czech"],"beran":["czech"],"beseda":["czech"],"bestie":["czech"],"beton":["czech","turkish"],"bezinka":["czech"],"bezmoc":["czech"],"beztak":["czech"],"bicykl":["czech"],"bidlo":["czech"],"biftek":["czech","turkish"],"bikiny":["czech"],"bilance":["czech"],"biograf":["czech"],"biolog":["czech"],"bitva":["czech"],"bizon":["czech"],"blahobyt":["czech"],"blatouch":["czech"],"blecha":["czech"],"bledule":["czech"],"blesk":["czech"],"blikat":["czech"],"blizna":["czech"],"blokovat":["czech"],"bloudit":["czech"],"blud":["czech"],"bobek":["czech"],"bobr":["czech"],"bodlina":["czech"],"bodnout":["czech"],"bohatost":["czech"],"bojkot":["czech"],"bojovat":["czech"],"bokorys":["czech"],"bolest":["czech"],"borec":["czech"],"borovice":["czech"],"bota":["czech"],"boubel":["czech"],"bouchat":["czech"],"bouda":["czech"],"boule":["czech"],"bourat":["czech"],"boxer":["czech"],"bradavka":["czech"],"brambora":["czech"],"branka":["czech"],"bratr":["czech"],"brepta":["czech"],"briketa":["czech"],"brko":["czech"],"brloh":["czech"],"bronz":["czech"],"broskev":["czech"],"brunetka":["czech"],"brusinka":["czech"],"brzda":["czech"],"brzy":["czech"],"bublina":["czech"],"bubnovat":["czech"],"buchta":["czech"],"buditel":["czech"],"budka":["czech"],"budova":["czech"],"bufet":["czech"],"bujarost":["czech"],"bukvice":["czech"],"buldok":["czech"],"bulva":["czech"],"bunda":["czech"],"bunkr":["czech"],"burza":["czech"],"butik":["czech","turkish"],"buvol":["czech"],"buzola":["czech"],"bydlet":["czech"],"bylina":["czech"],"bytovka":["czech"],"bzukot":["czech"],"capart":["czech"],"carevna":["czech"],"cedr":["czech"],"cedule":["czech"],"cejch":["czech"],"cejn":["czech"],"cela":["czech"],"celer":["czech"],"celkem":["czech"],"celnice":["czech"],"cenina":["czech"],"cennost":["czech"],"cenovka":["czech"],"centrum":["czech"],"cenzor":["czech"],"cestopis":["czech"],"cetka":["czech"],"chalupa":["czech"],"chapadlo":["czech"],"charita":["czech"],"chata":["czech"],"chechtat":["czech"],"chemie":["czech"],"chichot":["czech"],"chirurg":["czech"],"chlad":["czech"],"chleba":["czech"],"chlubit":["czech"],"chmel":["czech"],"chmura":["czech"],"chobot":["czech"],"chochol":["czech"],"chodba":["czech"],"cholera":["czech"],"chomout":["czech"],"chopit":["czech"],"choroba":["czech"],"chov":["czech"],"chrapot":["czech"],"chrlit":["czech"],"chrt":["czech"],"chrup":["czech"],"chtivost":["czech"],"chudina":["czech"],"chutnat":["czech"],"chvat":["czech"],"chvilka":["czech"],"chvost":["czech"],"chyba":["czech"],"chystat":["czech"],"chytit":["czech"],"cibule":["czech"],"cigareta":["czech"],"cihelna":["czech"],"cihla":["czech"],"cinkot":["czech"],"cirkus":["czech"],"cisterna":["czech"],"citace":["czech"],"citrus":["czech"],"cizinec":["czech"],"cizost":["czech"],"clona":["czech"],"cokoliv":["czech"],"couvat":["czech"],"ctitel":["czech"],"ctnost":["czech"],"cudnost":["czech"],"cuketa":["czech"],"cukr":["czech"],"cupot":["czech"],"cvaknout":["czech"],"cval":["czech"],"cvik":["czech"],"cvrkot":["czech"],"cyklista":["czech"],"daleko":["czech"],"dareba":["czech"],"datel":["czech"],"datum":["czech"],"dcera":["czech"],"debata":["czech"],"dechovka":["czech"],"decibel":["czech"],"deficit":["czech"],"deflace":["czech"],"dekl":["czech"],"dekret":["czech"],"demokrat":["czech"],"deprese":["czech"],"derby":["czech"],"deska":["czech"],"detektiv":["czech"],"dikobraz":["czech"],"diktovat":["czech"],"dioda":["czech"],"diplom":["czech"],"disk":["czech","turkish"],"displej":["czech"],"divadlo":["czech"],"divoch":["czech"],"dlaha":["czech"],"dlouho":["czech"],"dluhopis":["czech"],"dnes":["czech"],"dobro":["czech"],"dobytek":["czech"],"docent":["czech"],"dochutit":["czech"],"dodnes":["czech"],"dohled":["czech"],"dohoda":["czech"],"dohra":["czech"],"dojem":["czech"],"dojnice":["czech"],"doklad":["czech"],"dokola":["czech"],"doktor":["czech","turkish"],"dokument":["czech"],"dolar":["czech"],"doleva":["czech"],"dolina":["czech"],"doma":["czech"],"dominant":["czech"],"domluvit":["czech"],"domov":["czech"],"donutit":["czech"],"dopad":["czech"],"dopis":["czech"],"doplnit":["czech"],"doposud":["czech"],"doprovod":["czech"],"dopustit":["czech"],"dorazit":["czech"],"dorost":["czech"],"dort":["czech"],"dosah":["czech"],"doslov":["czech"],"dostatek":["czech"],"dosud":["czech"],"dosyta":["czech"],"dotaz":["czech"],"dotek":["czech"],"dotknout":["czech"],"doufat":["czech"],"doutnat":["czech"],"dovozce":["czech"],"dozadu":["czech"],"doznat":["czech"],"dozorce":["czech"],"drahota":["czech"],"drak":["czech"],"dramatik":["czech"],"dravec":["czech"],"draze":["czech"],"drdol":["czech"],"drobnost":["czech"],"drogerie":["czech"],"drozd":["czech"],"drsnost":["czech"],"drtit":["czech"],"drzost":["czech"],"duben":["czech"],"duchovno":["czech"],"dudek":["czech"],"duha":["czech"],"duhovka":["czech"],"dusit":["czech"],"dusno":["czech"],"dutost":["czech"],"dvojice":["czech"],"dvorec":["czech"],"dynamit":["czech"],"ekolog":["czech"],"ekonomie":["czech"],"elektron":["czech"],"elipsa":["czech"],"email":["czech"],"emise":["czech"],"emoce":["czech"],"empatie":["czech"],"epizoda":["czech"],"epocha":["czech"],"epopej":["czech"],"epos":["czech"],"esej":["czech"],"esence":["czech"],"eskorta":["czech"],"eskymo":["czech"],"etiketa":["czech"],"euforie":["czech"],"evoluce":["czech"],"exekuce":["czech"],"exkurze":["czech"],"expedice":["czech"],"exploze":["czech"],"export":["czech"],"extrakt":["czech"],"facka":["czech"],"fajfka":["czech"],"fakulta":["czech"],"fanatik":["czech","turkish"],"fantazie":["czech"],"farmacie":["czech"],"favorit":["czech"],"fazole":["czech"],"federace":["czech"],"fejeton":["czech"],"fenka":["czech"],"fialka":["czech"],"figurant":["czech"],"filozof":["czech"],"filtr":["czech"],"finance":["czech"],"finta":["czech"],"fixace":["czech"],"fjord":["czech"],"flanel":["czech"],"flirt":["czech"],"flotila":["czech"],"fond":["czech"],"fosfor":["czech"],"fotbal":["czech"],"fotka":["czech"],"foton":["czech"],"frakce":["czech"],"freska":["czech"],"fronta":["czech"],"fukar":["czech"],"funkce":["czech"],"fyzika":["czech"],"galeje":["czech"],"garant":["czech"],"genetika":["czech"],"geolog":["czech"],"gilotina":["czech"],"glazura":["czech"],"glejt":["czech"],"golem":["czech"],"golfista":["czech"],"gotika":["czech"],"graf":["czech"],"gramofon":["czech"],"granule":["czech"],"grep":["czech"],"gril":["czech"],"grog":["czech"],"groteska":["czech"],"guma":["czech"],"hadice":["czech"],"hadr":["czech"],"hala":["czech"],"halenka":["czech"],"hanba":["czech"],"hanopis":["czech"],"harfa":["czech"],"harpuna":["czech"],"havran":["czech"],"hebkost":["czech"],"hejkal":["czech"],"hejno":["czech"],"hejtman":["czech"],"hektar":["czech","turkish"],"helma":["czech"],"hematom":["czech"],"herec":["czech"],"herna":["czech"],"heslo":["czech"],"hezky":["czech"],"historik":["czech"],"hladovka":["czech"],"hlasivky":["czech"],"hlava":["czech"],"hledat":["czech"],"hlen":["czech"],"hlodavec":["czech"],"hloh":["czech"],"hloupost":["czech"],"hltat":["czech"],"hlubina":["czech"],"hluchota":["czech"],"hmat":["czech"],"hmota":["czech"],"hmyz":["czech"],"hnis":["czech"],"hnojivo":["czech"],"hnout":["czech"],"hoblina":["czech"],"hoboj":["czech"],"hoch":["czech"],"hodiny":["czech"],"hodlat":["czech"],"hodnota":["czech"],"hodovat":["czech"],"hojnost":["czech"],"hokej":["czech"],"holinka":["czech"],"holka":["czech"],"holub":["czech"],"homole":["czech"],"honitba":["czech"],"honorace":["czech"],"horal":["czech"],"horda":["czech"],"horizont":["czech"],"horko":["czech"],"horlivec":["czech"],"hormon":["czech","turkish"],"hornina":["czech"],"horoskop":["czech"],"horstvo":["czech"],"hospoda":["czech"],"hostina":["czech"],"hotovost":["czech"],"houba":["czech"],"houf":["czech"],"houpat":["czech"],"houska":["czech"],"hovor":["czech"],"hradba":["czech"],"hranice":["czech"],"hravost":["czech"],"hrazda":["czech"],"hrbolek":["czech"],"hrdina":["czech"],"hrdlo":["czech"],"hrdost":["czech"],"hrnek":["czech"],"hrobka":["czech"],"hromada":["czech"],"hrot":["czech"],"hrouda":["czech"],"hrozen":["czech"],"hrstka":["czech"],"hrubost":["czech"],"hryzat":["czech"],"hubenost":["czech"],"hubnout":["czech"],"hudba":["czech"],"hukot":["czech"],"humr":["czech"],"husita":["czech"],"hustota":["czech"],"hvozd":["czech"],"hybnost":["czech"],"hydrant":["czech"],"hygiena":["czech"],"hymna":["czech"],"hysterik":["czech"],"idylka":["czech"],"ihned":["czech"],"ikona":["czech"],"iluze":["czech"],"imunita":["czech"],"infekce":["czech"],"inflace":["czech"],"inkaso":["czech"],"inovace":["czech"],"inspekce":["czech"],"internet":["czech"],"invalida":["czech"],"investor":["czech"],"inzerce":["czech"],"ironie":["czech"],"jablko":["czech"],"jachta":["czech"],"jahoda":["czech"],"jakmile":["czech"],"jakost":["czech"],"jalovec":["czech"],"jantar":["czech"],"jarmark":["czech"],"jaro":["czech"],"jasan":["czech"],"jasno":["czech"],"jatka":["czech"],"javor":["czech"],"jazyk":["czech"],"jedinec":["czech"],"jedle":["czech"],"jednatel":["czech"],"jehlan":["czech"],"jekot":["czech"],"jelen":["czech"],"jelito":["czech"],"jemnost":["czech"],"jenom":["czech"],"jepice":["czech"],"jeseter":["czech"],"jevit":["czech"],"jezdec":["czech"],"jezero":["czech"],"jinak":["czech"],"jindy":["czech"],"jinoch":["czech"],"jiskra":["czech"],"jistota":["czech"],"jitrnice":["czech"],"jizva":["czech"],"jmenovat":["czech"],"jogurt":["czech"],"jurta":["czech"],"kabaret":["czech"],"kabel":["czech"],"kabinet":["czech"],"kachna":["czech"],"kadet":["czech"],"kadidlo":["czech"],"kahan":["czech"],"kajak":["czech"],"kajuta":["czech"],"kakao":["czech"],"kaktus":["czech"],"kalamita":["czech"],"kalhoty":["czech"],"kalibr":["czech"],"kalnost":["czech"],"kamera":["czech"],"kamkoliv":["czech"],"kamna":["czech"],"kanibal":["czech"],"kanoe":["czech"],"kantor":["czech"],"kapalina":["czech"],"kapela":["czech"],"kapitola":["czech"],"kapka":["czech"],"kaple":["czech"],"kapota":["czech"],"kapr":["czech"],"kapusta":["czech"],"kapybara":["czech"],"karamel":["czech"],"karotka":["czech"],"karton":["czech"],"kasa":["czech"],"katalog":["czech"],"katedra":["czech"],"kauce":["czech"],"kauza":["czech"],"kavalec":["czech"],"kazajka":["czech"],"kazeta":["czech"],"kazivost":["czech"],"kdekoliv":["czech"],"kdesi":["czech"],"kedluben":["czech"],"kemp":["czech"],"keramika":["czech"],"kino":["czech"],"klacek":["czech"],"kladivo":["czech"],"klam":["czech"],"klapot":["czech"],"klasika":["czech"],"klaun":["czech"],"klec":["czech"],"klenba":["czech"],"klepat":["czech"],"klesnout":["czech"],"klid":["czech"],"klima":["czech"],"klisna":["czech"],"klobouk":["czech"],"klokan":["czech"],"klopa":["czech"],"kloub":["czech"],"klubovna":["czech"],"klusat":["czech"],"kluzkost":["czech"],"kmen":["czech"],"kmitat":["czech"],"kmotr":["czech"],"kniha":["czech"],"knot":["czech"],"koalice":["czech"],"koberec":["czech"],"kobka":["czech"],"kobliha":["czech"],"kobyla":["czech"],"kocour":["czech"],"kohout":["czech"],"kojenec":["czech"],"kokos":["czech"],"koktejl":["czech"],"kolaps":["czech"],"koleda":["czech"],"kolize":["czech"],"kolo":["czech"],"komando":["czech"],"kometa":["czech"],"komik":["czech"],"komnata":["czech"],"komora":["czech"],"kompas":["czech"],"komunita":["czech"],"konat":["czech"],"koncept":["czech"],"kondice":["czech"],"konec":["czech"],"konfese":["czech"],"kongres":["czech"],"konina":["czech"],"konkurs":["czech"],"kontakt":["czech"],"konzerva":["czech"],"kopanec":["czech"],"kopie":["czech"],"kopnout":["czech"],"koprovka":["czech"],"korbel":["czech"],"korektor":["czech"],"kormidlo":["czech"],"koroptev":["czech"],"korpus":["czech"],"koruna":["czech"],"koryto":["czech"],"korzet":["czech"],"kosatec":["czech"],"kostka":["czech"],"kotel":["czech"],"kotleta":["czech"],"kotoul":["czech"],"koukat":["czech"],"koupelna":["czech"],"kousek":["czech"],"kouzlo":["czech"],"kovboj":["czech"],"koza":["czech"],"kozoroh":["czech"],"krabice":["czech"],"krach":["czech"],"krajina":["czech"],"kralovat":["czech"],"krasopis":["czech"],"kravata":["czech"],"kredit":["czech"],"krejcar":["czech"],"kresba":["czech"],"kreveta":["czech"],"kriket":["czech"],"kritik":["czech"],"krize":["czech"],"krkavec":["czech"],"krmelec":["czech"],"krmivo":["czech"],"krocan":["czech"],"krok":["czech"],"kronika":["czech"],"kropit":["czech"],"kroupa":["czech"],"krovka":["czech"],"krtek":["czech"],"kruhadlo":["czech"],"krupice":["czech"],"krutost":["czech"],"krvinka":["czech"],"krychle":["czech"],"krypta":["czech"],"krystal":["czech"],"kryt":["czech"],"kudlanka":["czech"],"kufr":["czech"],"kujnost":["czech"],"kukla":["czech"],"kulajda":["czech"],"kulich":["czech"],"kulka":["czech"],"kulomet":["czech"],"kultura":["czech"],"kuna":["czech"],"kupodivu":["czech"],"kurt":["czech"],"kurzor":["czech"],"kutil":["czech"],"kvalita":["czech"],"kvasinka":["czech"],"kvestor":["czech"],"kynolog":["czech"],"kyselina":["czech"],"kytara":["czech"],"kytice":["czech"],"kytka":["czech"],"kytovec":["czech"],"kyvadlo":["czech"],"labrador":["czech"],"lachtan":["czech"],"ladnost":["czech"],"laik":["czech"],"lakomec":["czech"],"lamela":["czech"],"lampa":["czech"],"lanovka":["czech"],"lasice":["czech"],"laso":["czech"],"lastura":["czech"],"latinka":["czech"],"lavina":["czech"],"lebka":["czech"],"leckdy":["czech"],"leden":["czech"],"lednice":["czech"],"ledovka":["czech"],"ledvina":["czech"],"legenda":["czech"],"legie":["czech"],"legrace":["czech"],"lehce":["czech"],"lehkost":["czech"],"lehnout":["czech"],"lektvar":["czech"],"lenochod":["czech"],"lentilka":["czech"],"lepenka":["czech"],"lepidlo":["czech"],"letadlo":["czech"],"letec":["czech"],"letmo":["czech"],"letokruh":["czech"],"levhart":["czech"],"levitace":["czech"],"levobok":["czech"],"libra":["czech"],"lichotka":["czech"],"lidojed":["czech"],"lidskost":["czech"],"lihovina":["czech"],"lijavec":["czech"],"lilek":["czech"],"limetka":["czech"],"linie":["czech"],"linka":["czech"],"linoleum":["czech"],"listopad":["czech"],"litina":["czech"],"litovat":["czech"],"lobista":["czech"],"lodivod":["czech"],"logika":["czech"],"logoped":["czech"],"lokalita":["czech"],"loket":["czech"],"lomcovat":["czech"],"lopata":["czech"],"lopuch":["czech"],"lord":["czech"],"losos":["czech"],"lotr":["czech"],"loudal":["czech"],"louh":["czech"],"louka":["czech"],"louskat":["czech"],"lovec":["czech"],"lstivost":["czech"],"lucerna":["czech"],"lucifer":["czech"],"lump":["czech"],"lusk":["czech"],"lustrace":["czech"],"lvice":["czech"],"lyra":["czech"],"lyrika":["czech"],"lysina":["czech"],"madam":["czech"],"madlo":["czech"],"magistr":["czech"],"mahagon":["czech"],"majetek":["czech"],"majitel":["czech"],"majorita":["czech"],"makak":["czech"],"makovice":["czech"],"makrela":["czech"],"malba":["czech"],"malina":["czech"],"malovat":["czech"],"malvice":["czech"],"maminka":["czech"],"mandle":["czech"],"manko":["czech"],"marnost":["czech"],"masakr":["czech"],"maskot":["czech"],"masopust":["czech"],"matice":["czech"],"matrika":["czech"],"maturita":["czech"],"mazanec":["czech"],"mazivo":["czech"],"mazlit":["czech"],"mazurka":["czech"],"mdloba":["czech"],"mechanik":["czech"],"meditace":["czech"],"medovina":["czech"],"melasa":["czech"],"meloun":["czech"],"mentolka":["czech"],"metla":["czech"],"metoda":["czech"],"metr":["czech"],"mezera":["czech"],"migrace":["czech"],"mihnout":["czech"],"mihule":["czech"],"mikina":["czech"],"mikrofon":["czech","turkish"],"milenec":["czech"],"milimetr":["czech"],"milost":["czech"],"mimika":["czech"],"mincovna":["czech"],"minibar":["czech"],"minomet":["czech"],"minulost":["czech"],"miska":["czech"],"mistr":["czech"],"mixovat":["czech"],"mladost":["czech"],"mlha":["czech"],"mlhovina":["czech"],"mlok":["czech"],"mlsat":["czech"],"mluvit":["czech"],"mnich":["czech"],"mnohem":["czech"],"mobil":["czech"],"mocnost":["czech"],"modelka":["czech"],"modlitba":["czech"],"mohyla":["czech"],"mokro":["czech"],"molekula":["czech"],"momentka":["czech"],"monarcha":["czech"],"monokl":["czech"],"monstrum":["czech"],"montovat":["czech"],"monzun":["czech"],"mosaz":["czech"],"moskyt":["czech"],"most":["czech"],"motivace":["czech"],"motorka":["czech"],"motyka":["czech"],"moucha":["czech"],"moudrost":["czech"],"mozaika":["czech"],"mozek":["czech"],"mozol":["czech"],"mramor":["czech"],"mravenec":["czech"],"mrkev":["czech"],"mrtvola":["czech"],"mrzet":["czech"],"mrzutost":["czech"],"mstitel":["czech"],"mudrc":["czech"],"muflon":["czech"],"mulat":["czech"],"mumie":["czech"],"munice":["czech"],"muset":["czech"],"mutace":["czech"],"muzeum":["czech"],"muzikant":["czech"],"myslivec":["czech"],"mzda":["czech"],"nabourat":["czech"],"nachytat":["czech"],"nadace":["czech"],"nadbytek":["czech"],"nadhoz":["czech"],"nadobro":["czech"],"nadpis":["czech"],"nahlas":["czech"],"nahnat":["czech"],"nahodile":["czech"],"nahradit":["czech"],"naivita":["czech"],"najednou":["czech"],"najisto":["czech"],"najmout":["czech"],"naklonit":["czech"],"nakonec":["czech"],"nakrmit":["czech"],"nalevo":["czech"],"namazat":["czech"],"namluvit":["czech"],"nanometr":["czech"],"naoko":["czech"],"naopak":["czech"],"naostro":["czech"],"napadat":["czech"],"napevno":["czech"],"naplnit":["czech"],"napnout":["czech"],"naposled":["czech"],"naprosto":["czech"],"narodit":["czech"],"naruby":["czech"],"narychlo":["czech"],"nasadit":["czech"],"nasekat":["czech"],"naslepo":["czech"],"nastat":["czech"],"natolik":["czech"],"navenek":["czech"],"navrch":["czech"],"navzdory":["czech"],"nazvat":["czech"],"nebe":["czech"],"nechat":["czech"],"necky":["czech"],"nedaleko":["czech"],"nedbat":["czech"],"neduh":["czech"],"negace":["czech"],"nehet":["czech"],"nehoda":["czech"],"nejen":["czech"],"nejprve":["czech"],"neklid":["czech"],"nelibost":["czech"],"nemilost":["czech"],"nemoc":["czech"],"neochota":["czech"],"neonka":["czech"],"nepokoj":["czech"],"nerost":["czech"],"nerv":["czech"],"nesmysl":["czech"],"nesoulad":["czech"],"netvor":["czech"],"neuron":["czech"],"nevina":["czech"],"nezvykle":["czech"],"nicota":["czech"],"nijak":["czech"],"nikam":["czech"],"nikdy":["czech"],"nikl":["czech"],"nikterak":["czech"],"nitro":["czech"],"nocleh":["czech"],"nohavice":["czech"],"nominace":["czech"],"nora":["czech"],"norek":["czech"],"nositel":["czech"],"nosnost":["czech"],"nouze":["czech"],"noviny":["czech"],"novota":["czech"],"nozdra":["czech"],"nuda":["czech"],"nudle":["czech"],"nuget":["czech"],"nutit":["czech"],"nutnost":["czech"],"nutrie":["czech"],"nymfa":["czech"],"obal":["czech"],"obarvit":["czech"],"obava":["czech"],"obdiv":["czech"],"obec":["czech"],"obehnat":["czech"],"obejmout":["czech"],"obezita":["czech"],"obhajoba":["czech"],"obilnice":["czech"],"objasnit":["czech"],"objekt":["czech"],"obklopit":["czech"],"oblast":["czech"],"oblek":["czech"],"obliba":["czech"],"obloha":["czech"],"obluda":["czech"],"obnos":["czech"],"obohatit":["czech"],"obojek":["czech"],"obout":["czech"],"obrazec":["czech"],"obrna":["czech"],"obruba":["czech"],"obrys":["czech"],"obsah":["czech"],"obsluha":["czech"],"obstarat":["czech"],"obuv":["czech"],"obvaz":["czech"],"obvinit":["czech"],"obvod":["czech"],"obvykle":["czech"],"obyvatel":["czech"],"obzor":["czech"],"ocas":["czech"],"ocel":["czech"],"ocenit":["czech"],"ochladit":["czech"],"ochota":["czech"],"ochrana":["czech"],"ocitnout":["czech"],"odboj":["czech"],"odbyt":["czech"],"odchod":["czech"],"odcizit":["czech"],"odebrat":["czech"],"odeslat":["czech"],"odevzdat":["czech"],"odezva":["czech"],"odhadce":["czech"],"odhodit":["czech"],"odjet":["czech"],"odjinud":["czech"],"odkaz":["czech"],"odkoupit":["czech"],"odliv":["czech"],"odluka":["czech"],"odmlka":["czech"],"odolnost":["czech"],"odpad":["czech"],"odpis":["czech"],"odplout":["czech"],"odpor":["czech"],"odpustit":["czech"],"odpykat":["czech"],"odrazka":["czech"],"odsoudit":["czech"],"odstup":["czech"],"odsun":["czech"],"odtok":["czech"],"odtud":["czech"],"odvaha":["czech"],"odveta":["czech"],"odvolat":["czech"],"odvracet":["czech"],"odznak":["czech"],"ofina":["czech"],"ofsajd":["czech"],"ohlas":["czech"],"ohnisko":["czech"],"ohrada":["czech"],"ohrozit":["czech"],"ohryzek":["czech"],"okap":["czech"],"okenice":["czech"],"oklika":["czech"],"okno":["czech"],"okouzlit":["czech"],"okovy":["czech"],"okrasa":["czech"],"okres":["czech"],"okrsek":["czech"],"okruh":["czech"],"okupant":["czech"],"okurka":["czech"],"okusit":["czech"],"olejnina":["czech"],"olizovat":["czech"],"omak":["czech"],"omeleta":["czech"],"omezit":["czech"],"omladina":["czech"],"omlouvat":["czech"],"omluva":["czech"],"omyl":["czech"],"onehdy":["czech"],"opakovat":["czech"],"opasek":["czech"],"operace":["czech"],"opice":["czech"],"opilost":["czech"],"opisovat":["czech"],"opora":["czech"],"opozice":["czech"],"opravdu":["czech"],"oproti":["czech"],"orbital":["czech"],"orchestr":["czech"],"orgie":["czech"],"orlice":["czech"],"orloj":["czech"],"ortel":["czech"],"osada":["czech"],"oschnout":["czech"],"osika":["czech"],"osivo":["czech"],"oslava":["czech"],"oslepit":["czech"],"oslnit":["czech"],"oslovit":["czech"],"osnova":["czech"],"osoba":["czech"],"osolit":["czech"],"ospalec":["czech"],"osten":["czech"],"ostraha":["czech"],"ostuda":["czech"],"ostych":["czech"],"osvojit":["czech"],"oteplit":["czech"],"otisk":["czech"],"otop":["czech"],"otrhat":["czech"],"otrlost":["czech"],"otrok":["czech"],"otruby":["czech"],"otvor":["czech"],"ovanout":["czech"],"ovar":["czech"],"oves":["czech"],"ovlivnit":["czech"],"ovoce":["czech"],"oxid":["czech"],"ozdoba":["czech"],"pachatel":["czech"],"pacient":["czech"],"padouch":["czech"],"pahorek":["czech"],"pakt":["czech"],"palanda":["czech"],"palec":["czech"],"palivo":["czech"],"paluba":["czech"],"pamflet":["czech"],"pamlsek":["czech"],"panenka":["czech"],"panika":["czech"],"panna":["czech"],"panovat":["czech"],"panstvo":["czech"],"pantofle":["czech"],"paprika":["czech"],"parketa":["czech"],"parodie":["czech"],"parta":["czech"],"paruka":["czech"],"paryba":["czech"],"paseka":["czech"],"pasivita":["czech"],"pastelka":["czech"],"patent":["czech"],"patrona":["czech"],"pavouk":["czech"],"pazneht":["czech"],"pazourek":["czech"],"pecka":["czech"],"pedagog":["czech"],"pejsek":["czech"],"peklo":["czech"],"peloton":["czech"],"penalta":["czech"],"pendrek":["czech"],"penze":["czech"],"periskop":["czech"],"pero":["czech"],"pestrost":["czech"],"petarda":["czech"],"petice":["czech"],"petrolej":["czech"],"pevnina":["czech"],"pexeso":["czech"],"pianista":["czech"],"piha":["czech"],"pijavice":["czech"],"pikle":["czech"],"piknik":["czech","turkish"],"pilina":["czech"],"pilnost":["czech"],"pilulka":["czech"],"pinzeta":["czech"],"pipeta":["czech"],"pisatel":["czech"],"pistole":["czech"],"pitevna":["czech"],"pivnice":["czech"],"pivovar":["czech"],"placenta":["czech"],"plakat":["czech"],"plamen":["czech"],"planeta":["czech"],"plastika":["czech"],"platit":["czech"],"plavidlo":["czech"],"plaz":["czech"],"plech":["czech"],"plemeno":["czech"],"plenta":["czech"],"ples":["czech"],"pletivo":["czech"],"plevel":["czech"],"plivat":["czech"],"plnit":["czech"],"plno":["czech"],"plocha":["czech"],"plodina":["czech"],"plomba":["czech"],"plout":["czech"],"pluk":["czech"],"plyn":["czech"],"pobavit":["czech"],"pobyt":["czech"],"pochod":["czech"],"pocit":["czech"],"poctivec":["czech"],"podat":["czech"],"podcenit":["czech"],"podepsat":["czech"],"podhled":["czech"],"podivit":["czech"],"podklad":["czech"],"podmanit":["czech"],"podnik":["czech"],"podoba":["czech"],"podpora":["czech"],"podraz":["czech"],"podstata":["czech"],"podvod":["czech"],"podzim":["czech"],"poezie":["czech"],"pohanka":["czech"],"pohnutka":["czech"],"pohovor":["czech"],"pohroma":["czech"],"pohyb":["czech"],"pointa":["czech"],"pojistka":["czech"],"pojmout":["czech"],"pokazit":["czech"],"pokles":["czech"],"pokoj":["czech"],"pokrok":["czech"],"pokuta":["czech"],"pokyn":["czech"],"poledne":["czech"],"polibek":["czech"],"polknout":["czech"],"poloha":["czech"],"polynom":["czech"],"pomalu":["czech"],"pominout":["czech"],"pomlka":["czech"],"pomoc":["czech"],"pomsta":["czech"],"pomyslet":["czech"],"ponechat":["czech"],"ponorka":["czech"],"ponurost":["czech"],"popadat":["czech"],"popel":["czech"],"popisek":["czech"],"poplach":["czech"],"poprosit":["czech"],"popsat":["czech"],"popud":["czech"],"poradce":["czech"],"porce":["czech"],"porod":["czech"],"porucha":["czech"],"poryv":["czech"],"posadit":["czech"],"posed":["czech"],"posila":["czech"],"poskok":["czech"],"poslanec":["czech"],"posoudit":["czech"],"pospolu":["czech"],"postava":["czech"],"posudek":["czech"],"posyp":["czech"],"potah":["czech"],"potkan":["czech"],"potlesk":["czech"],"potomek":["czech"],"potrava":["czech"],"potupa":["czech"],"potvora":["czech"],"poukaz":["czech"],"pouto":["czech"],"pouzdro":["czech"],"povaha":["czech"],"povidla":["czech"],"povlak":["czech"],"povoz":["czech"],"povrch":["czech"],"povstat":["czech"],"povyk":["czech"],"povzdech":["czech"],"pozdrav":["czech"],"pozemek":["czech"],"poznatek":["czech"],"pozor":["czech"],"pozvat":["czech"],"pracovat":["czech"],"prahory":["czech"],"praktika":["czech"],"prales":["czech"],"praotec":["czech"],"praporek":["czech"],"prase":["czech"],"pravda":["czech"],"princip":["czech"],"prkno":["czech"],"probudit":["czech"],"procento":["czech"],"prodej":["czech"],"profese":["czech"],"prohra":["czech"],"projekt":["czech"],"prolomit":["czech"],"promile":["czech"],"pronikat":["czech"],"propad":["czech"],"prorok":["czech"],"prosba":["czech"],"proton":["czech"],"proutek":["czech"],"provaz":["czech"],"prskavka":["czech"],"prsten":["czech"],"prudkost":["czech"],"prut":["czech"],"prvek":["czech"],"prvohory":["czech"],"psanec":["czech"],"psovod":["czech"],"pstruh":["czech"],"ptactvo":["czech"],"puberta":["czech"],"puch":["czech"],"pudl":["czech"],"pukavec":["czech"],"puklina":["czech"],"pukrle":["czech"],"pult":["czech"],"pumpa":["czech"],"punc":["czech"],"pupen":["czech"],"pusa":["czech"],"pusinka":["czech"],"pustina":["czech"],"putovat":["czech"],"putyka":["czech"],"pyramida":["czech"],"pysk":["czech"],"pytel":["czech"],"racek":["czech"],"rachot":["czech"],"radiace":["czech"],"radnice":["czech"],"radon":["czech"],"raft":["czech"],"ragby":["czech"],"raketa":["czech"],"rakovina":["czech"],"rameno":["czech"],"rampouch":["czech"],"rande":["czech"],"rarach":["czech"],"rarita":["czech"],"rasovna":["czech"],"rastr":["czech"],"ratolest":["czech"],"razance":["czech"],"razidlo":["czech"],"reagovat":["czech"],"reakce":["czech"],"recept":["czech"],"redaktor":["czech"],"referent":["czech"],"reflex":["czech"],"rejnok":["czech"],"reklama":["czech"],"rekord":["czech"],"rekrut":["czech"],"rektor":["czech"],"reputace":["czech"],"revize":["czech","turkish"],"revma":["czech"],"revolver":["czech"],"rezerva":["czech"],"riskovat":["czech"],"riziko":["czech"],"robotika":["czech"],"rodokmen":["czech"],"rohovka":["czech"],"rokle":["czech"],"rokoko":["czech"],"romaneto":["czech"],"ropovod":["czech"],"ropucha":["czech"],"rorejs":["czech"],"rosol":["czech"],"rostlina":["czech"],"rotmistr":["czech"],"rotoped":["czech"],"rotunda":["czech"],"roubenka":["czech"],"roucho":["czech"],"roup":["czech"],"roura":["czech"],"rovina":["czech"],"rovnice":["czech"],"rozbor":["czech"],"rozchod":["czech"],"rozdat":["czech"],"rozeznat":["czech"],"rozhodce":["czech"],"rozinka":["czech"],"rozjezd":["czech"],"rozkaz":["czech"],"rozloha":["czech"],"rozmar":["czech"],"rozpad":["czech"],"rozruch":["czech"],"rozsah":["czech"],"roztok":["czech"],"rozum":["czech"],"rozvod":["czech"],"rubrika":["czech"],"ruchadlo":["czech"],"rukavice":["czech"],"rukopis":["czech"],"ryba":["czech"],"rybolov":["czech"],"rychlost":["czech"],"rydlo":["czech"],"rypadlo":["czech"],"rytina":["czech"],"ryzost":["czech"],"sadista":["czech"],"sahat":["czech"],"sako":["czech"],"samec":["czech"],"samizdat":["czech"],"samota":["czech"],"sanitka":["czech"],"sardinka":["czech"],"sasanka":["czech"],"satelit":["czech"],"sazba":["czech"],"sazenice":["czech"],"sbor":["czech"],"schovat":["czech"],"sebranka":["czech"],"secese":["czech"],"sedadlo":["czech"],"sediment":["czech"],"sedlo":["czech"],"sehnat":["czech"],"sejmout":["czech"],"sekera":["czech"],"sekta":["czech"],"sekunda":["czech"],"sekvoje":["czech"],"semeno":["czech"],"seno":["czech"],"servis":["czech","turkish"],"sesadit":["czech"],"seshora":["czech"],"seskok":["czech"],"seslat":["czech"],"sestra":["czech"],"sesuv":["czech"],"sesypat":["czech"],"setba":["czech"],"setina":["czech"],"setkat":["czech"],"setnout":["czech"],"setrvat":["czech"],"sever":["czech"],"seznam":["czech"],"shoda":["czech"],"shrnout":["czech"],"sifon":["czech"],"silnice":["czech"],"sirka":["czech"],"sirotek":["czech"],"sirup":["czech"],"situace":["czech"],"skafandr":["czech"],"skalisko":["czech"],"skanzen":["czech"],"skaut":["czech"],"skeptik":["czech"],"skica":["czech"],"skladba":["czech"],"sklenice":["czech"],"sklo":["czech"],"skluz":["czech"],"skoba":["czech"],"skokan":["czech"],"skoro":["czech"],"skripta":["czech"],"skrz":["czech"],"skupina":["czech"],"skvost":["czech"],"skvrna":["czech"],"slabika":["czech"],"sladidlo":["czech"],"slanina":["czech"],"slast":["czech"],"slavnost":["czech"],"sledovat":["czech"],"slepec":["czech"],"sleva":["czech"],"slezina":["czech"],"slib":["czech"],"slina":["czech"],"sliznice":["czech"],"slon":["czech"],"sloupek":["czech"],"slovo":["czech"],"sluch":["czech"],"sluha":["czech"],"slunce":["czech"],"slupka":["czech"],"slza":["czech"],"smaragd":["czech"],"smetana":["czech"],"smilstvo":["czech"],"smlouva":["czech"],"smog":["czech"],"smrad":["czech"],"smrk":["czech"],"smrtka":["czech"],"smutek":["czech"],"smysl":["czech"],"snad":["czech"],"snaha":["czech"],"snob":["czech"],"sobota":["czech"],"socha":["czech"],"sodovka":["czech"],"sokol":["czech"],"sopka":["czech"],"sotva":["czech"],"souboj":["czech"],"soucit":["czech"],"soudce":["czech"],"souhlas":["czech"],"soulad":["czech"],"soumrak":["czech"],"souprava":["czech"],"soused":["czech"],"soutok":["czech"],"souviset":["czech"],"spalovna":["czech"],"spasitel":["czech"],"spis":["czech"],"splav":["czech"],"spodek":["czech"],"spojenec":["czech"],"spolu":["czech"],"sponzor":["czech"],"spornost":["czech"],"spousta":["czech"],"sprcha":["czech"],"spustit":["czech"],"sranda":["czech"],"sraz":["czech"],"srdce":["czech"],"srna":["czech"],"srnec":["czech"],"srovnat":["czech"],"srpen":["czech"],"srst":["czech"],"srub":["czech"],"stanice":["czech"],"starosta":["czech"],"statika":["czech"],"stavba":["czech"],"stehno":["czech"],"stezka":["czech"],"stodola":["czech"],"stolek":["czech"],"stopa":["czech"],"storno":["czech"],"stoupat":["czech"],"strach":["czech"],"stres":["czech"],"strhnout":["czech"],"strom":["czech"],"struna":["czech"],"studna":["czech"],"stupnice":["czech"],"stvol":["czech"],"styk":["czech"],"subjekt":["czech"],"subtropy":["czech"],"suchar":["czech"],"sudost":["czech"],"sukno":["czech"],"sundat":["czech"],"sunout":["czech"],"surikata":["czech"],"surovina":["czech"],"svah":["czech"],"svalstvo":["czech"],"svetr":["czech"],"svatba":["czech"],"svazek":["czech"],"svisle":["czech"],"svitek":["czech"],"svoboda":["czech"],"svodidlo":["czech"],"svorka":["czech"],"svrab":["czech"],"sykavka":["czech"],"sykot":["czech"],"synek":["czech"],"synovec":["czech"],"sypat":["czech"],"sypkost":["czech"],"syrovost":["czech"],"sysel":["czech"],"sytost":["czech"],"tabletka":["czech"],"tabule":["czech"],"tahoun":["czech"],"tajemno":["czech"],"tajfun":["czech"],"tajga":["czech"],"tajit":["czech"],"tajnost":["czech"],"taktika":["czech"],"tamhle":["czech"],"tampon":["czech","turkish"],"tancovat":["czech"],"tanec":["czech"],"tanker":["czech"],"tapeta":["czech"],"tavenina":["czech"],"tazatel":["czech"],"technika":["czech"],"tehdy":["czech"],"tekutina":["czech"],"telefon":["czech"],"temnota":["czech"],"tendence":["czech"],"tenista":["czech"],"tenor":["czech"],"teplota":["czech"],"tepna":["czech"],"teprve":["czech"],"terapie":["czech"],"termoska":["czech"],"textil":["czech"],"ticho":["czech"],"tiskopis":["czech"],"titulek":["czech"],"tkadlec":["czech"],"tkanina":["czech"],"tlapka":["czech"],"tleskat":["czech"],"tlukot":["czech"],"tlupa":["czech"],"tmel":["czech"],"toaleta":["czech"],"topinka":["czech"],"topol":["czech"],"torzo":["czech"],"touha":["czech"],"toulec":["czech"],"tradice":["czech"],"traktor":["czech"],"tramp":["czech"],"trasa":["czech"],"traverza":["czech"],"trefit":["czech"],"trest":["czech"],"trezor":["czech"],"trhavina":["czech"],"trhlina":["czech"],"trochu":["czech"],"trojice":["czech"],"troska":["czech"],"trouba":["czech"],"trpce":["czech"],"trpitel":["czech"],"trpkost":["czech"],"trubec":["czech"],"truchlit":["czech"],"truhlice":["czech"],"trus":["czech"],"trvat":["czech"],"tudy":["czech"],"tuhnout":["czech"],"tuhost":["czech"],"tundra":["czech"],"turista":["czech"],"turnaj":["czech"],"tuzemsko":["czech"],"tvaroh":["czech"],"tvorba":["czech"],"tvrdost":["czech"],"tvrz":["czech"],"tygr":["czech"],"tykev":["czech"],"ubohost":["czech"],"uboze":["czech"],"ubrat":["czech"],"ubrousek":["czech"],"ubrus":["czech"],"ubytovna":["czech"],"ucho":["czech"],"uctivost":["czech"],"udivit":["czech"],"uhradit":["czech"],"ujednat":["czech"],"ujistit":["czech"],"ujmout":["czech"],"ukazatel":["czech"],"uklidnit":["czech"],"uklonit":["czech"],"ukotvit":["czech"],"ukrojit":["czech"],"ulice":["czech"],"ulita":["czech"],"ulovit":["czech"],"umyvadlo":["czech"],"unavit":["czech"],"uniforma":["czech"],"uniknout":["czech"],"upadnout":["czech"],"uplatnit":["czech"],"uplynout":["czech"],"upoutat":["czech"],"upravit":["czech"],"uran":["czech"],"urazit":["czech"],"usednout":["czech"],"usilovat":["czech"],"usmrtit":["czech"],"usnadnit":["czech"],"usnout":["czech"],"usoudit":["czech"],"ustlat":["czech"],"ustrnout":["czech"],"utahovat":["czech"],"utkat":["czech"],"utlumit":["czech"],"utonout":["czech"],"utopenec":["czech"],"utrousit":["czech"],"uvalit":["czech"],"uvolnit":["czech"],"uvozovka":["czech"],"uzdravit":["czech"],"uzel":["czech"],"uzenina":["czech"],"uzlina":["czech"],"uznat":["czech"],"vagon":["czech","turkish"],"valcha":["czech"],"valoun":["czech"],"vana":["czech"],"vandal":["czech"],"vanilka":["czech"],"varan":["czech"],"varhany":["czech"],"varovat":["czech"],"vcelku":["czech"],"vchod":["czech"],"vdova":["czech"],"vedro":["czech"],"vegetace":["czech"],"vejce":["czech"],"velbloud":["czech"],"veletrh":["czech"],"velitel":["czech"],"velmoc":["czech"],"velryba":["czech"],"venkov":["czech"],"veranda":["czech"],"verze":["czech"],"veselka":["czech"],"veskrze":["czech"],"vesnice":["czech"],"vespodu":["czech"],"vesta":["czech"],"veterina":["czech"],"veverka":["czech"],"vibrace":["czech"],"vichr":["czech"],"videohra":["czech"],"vidina":["czech"],"vidle":["czech"],"vila":["czech"],"vinice":["czech"],"viset":["czech"],"vitalita":["czech"],"vize":["czech"],"vizitka":["czech"],"vjezd":["czech"],"vklad":["czech"],"vkus":["czech"],"vlajka":["czech"],"vlak":["czech"],"vlasec":["czech"],"vlevo":["czech"],"vlhkost":["czech"],"vliv":["czech"],"vlnovka":["czech"],"vloupat":["czech"],"vnucovat":["czech"],"vnuk":["czech"],"voda":["czech"],"vodivost":["czech"],"vodoznak":["czech"],"vodstvo":["czech"],"vojensky":["czech"],"vojna":["czech"],"vojsko":["czech"],"volant":["czech"],"volba":["czech"],"volit":["czech"],"volno":["czech"],"voskovka":["czech"],"vozidlo":["czech"],"vozovna":["czech"],"vpravo":["czech"],"vrabec":["czech"],"vracet":["czech"],"vrah":["czech"],"vrata":["czech"],"vrba":["czech"],"vrcholek":["czech"],"vrhat":["czech"],"vrstva":["czech"],"vrtule":["czech"],"vsadit":["czech"],"vstoupit":["czech"],"vstup":["czech"],"vtip":["czech"],"vybavit":["czech"],"vybrat":["czech"],"vychovat":["czech"],"vydat":["czech"],"vydra":["czech"],"vyfotit":["czech"],"vyhledat":["czech"],"vyhnout":["czech"],"vyhodit":["czech"],"vyhradit":["czech"],"vyhubit":["czech"],"vyjasnit":["czech"],"vyjet":["czech"],"vyjmout":["czech"],"vyklopit":["czech"],"vykonat":["czech"],"vylekat":["czech"],"vymazat":["czech"],"vymezit":["czech"],"vymizet":["czech"],"vymyslet":["czech"],"vynechat":["czech"],"vynikat":["czech"],"vynutit":["czech"],"vypadat":["czech"],"vyplatit":["czech"],"vypravit":["czech"],"vypustit":["czech"],"vyrazit":["czech"],"vyrovnat":["czech"],"vyrvat":["czech"],"vyslovit":["czech"],"vysoko":["czech"],"vystavit":["czech"],"vysunout":["czech"],"vysypat":["czech"],"vytasit":["czech"],"vytesat":["czech"],"vytratit":["czech"],"vyvinout":["czech"],"vyvolat":["czech"],"vyvrhel":["czech"],"vyzdobit":["czech"],"vyznat":["czech"],"vzadu":["czech"],"vzbudit":["czech"],"vzchopit":["czech"],"vzdor":["czech"],"vzduch":["czech"],"vzdychat":["czech"],"vzestup":["czech"],"vzhledem":["czech"],"vzkaz":["czech"],"vzlykat":["czech"],"vznik":["czech"],"vzorek":["czech"],"vzpoura":["czech"],"vztah":["czech"],"vztek":["czech"],"xylofon":["czech"],"zabrat":["czech"],"zabydlet":["czech"],"zachovat":["czech"],"zadarmo":["czech"],"zadusit":["czech"],"zafoukat":["czech"],"zahltit":["czech"],"zahodit":["czech"],"zahrada":["czech"],"zahynout":["czech"],"zajatec":["czech"],"zajet":["czech"],"zajistit":["czech"],"zaklepat":["czech"],"zakoupit":["czech"],"zalepit":["czech"],"zamezit":["czech"],"zamotat":["czech"],"zamyslet":["czech"],"zanechat":["czech"],"zanikat":["czech"],"zaplatit":["czech"],"zapojit":["czech"],"zapsat":["czech"],"zarazit":["czech"],"zastavit":["czech"],"zasunout":["czech"],"zatajit":["czech"],"zatemnit":["czech"],"zatknout":["czech"],"zaujmout":["czech"],"zavalit":["czech"],"zavelet":["czech"],"zavinit":["czech"],"zavolat":["czech"],"zavrtat":["czech"],"zazvonit":["czech"],"zbavit":["czech"],"zbrusu":["czech"],"zbudovat":["czech"],"zbytek":["czech"],"zdaleka":["czech"],"zdarma":["czech"],"zdatnost":["czech"],"zdivo":["czech"],"zdobit":["czech"],"zdroj":["czech"],"zdvih":["czech"],"zdymadlo":["czech"],"zelenina":["czech"],"zeman":["czech"],"zemina":["czech"],"zeptat":["czech"],"zezadu":["czech"],"zezdola":["czech"],"zhatit":["czech"],"zhltnout":["czech"],"zhluboka":["czech"],"zhotovit":["czech"],"zhruba":["czech"],"zima":["czech"],"zimnice":["czech"],"zjemnit":["czech"],"zklamat":["czech"],"zkoumat":["czech"],"zkratka":["czech"],"zkumavka":["czech"],"zlato":["czech"],"zlehka":["czech"],"zloba":["czech"],"zlom":["czech"],"zlost":["czech"],"zlozvyk":["czech"],"zmapovat":["czech"],"zmar":["czech"],"zmatek":["czech"],"zmije":["czech"],"zmizet":["czech"],"zmocnit":["czech"],"zmodrat":["czech"],"zmrzlina":["czech"],"zmutovat":["czech"],"znak":["czech"],"znalost":["czech"],"znamenat":["czech"],"znovu":["czech"],"zobrazit":["czech"],"zotavit":["czech"],"zoubek":["czech"],"zoufale":["czech"],"zplodit":["czech"],"zpomalit":["czech"],"zprava":["czech"],"zprostit":["czech"],"zprudka":["czech"],"zprvu":["czech"],"zrada":["czech"],"zranit":["czech"],"zrcadlo":["czech"],"zrnitost":["czech"],"zrno":["czech"],"zrovna":["czech"],"zrychlit":["czech"],"zrzavost":["czech"],"zticha":["czech"],"ztratit":["czech"],"zubovina":["czech"],"zubr":["czech"],"zvednout":["czech"],"zvenku":["czech"],"zvesela":["czech"],"zvon":["czech"],"zvrat":["czech"],"zvukovod":["czech"],"zvyk":["czech"],"abandon":["english","french"],"ability":["english"],"able":["english"],"about":["english"],"above":["english"],"absent":["english"],"absorb":["english"],"abstract":["english"],"absurd":["english"],"abuse":["english"],"access":["english"],"accident":["english"],"account":["english"],"accuse":["english"],"achieve":["english"],"acid":["english"],"acoustic":["english"],"acquire":["english"],"across":["english"],"act":["english"],"action":["english"],"actor":["english"],"actress":["english"],"actual":["english"],"adapt":["english"],"add":["english"],"addict":["english"],"address":["english"],"adjust":["english"],"admit":["english"],"adult":["english"],"advance":["english"],"advice":["english"],"aerobic":["english"],"affair":["english"],"afford":["english"],"afraid":["english"],"again":["english"],"age":["english"],"agent":["english"],"agree":["english"],"ahead":["english"],"aim":["english"],"air":["english"],"airport":["english"],"aisle":["english"],"alarm":["english"],"album":["english"],"alcohol":["english"],"alert":["english"],"alien":["english"],"all":["english"],"alley":["english"],"allow":["english"],"almost":["english"],"alone":["english"],"alpha":["english"],"already":["english"],"also":["english"],"alter":["english"],"always":["english"],"amateur":["english","french"],"amazing":["english"],"among":["english"],"amount":["english"],"amused":["english"],"analyst":["english"],"anchor":["english"],"ancient":["english"],"anger":["english"],"angle":["english","french"],"angry":["english"],"animal":["english","french"],"ankle":["english"],"announce":["english"],"annual":["english"],"another":["english"],"answer":["english"],"antenna":["english"],"antique":["english"],"anxiety":["english"],"any":["english"],"apart":["english"],"apology":["english"],"appear":["english"],"apple":["english"],"approve":["english"],"april":["english"],"arch":["english"],"arctic":["english"],"area":["english"],"arena":["english","turkish"],"argue":["english"],"arm":["english"],"armed":["english"],"armor":["english"],"army":["english"],"around":["english"],"arrange":["english"],"arrest":["english"],"arrive":["english"],"arrow":["english"],"art":["english"],"artefact":["english"],"artist":["english","turkish"],"artwork":["english"],"ask":["english"],"aspect":["english","french"],"assault":["english"],"asset":["english"],"assist":["english"],"assume":["english"],"asthma":["english"],"athlete":["english"],"atom":["english","turkish"],"attack":["english"],"attend":["english"],"attitude":["english"],"attract":["english"],"auction":["english"],"audit":["english"],"august":["english"],"aunt":["english"],"author":["english"],"auto":["english"],"autumn":["english"],"average":["english"],"avocado":["english"],"avoid":["english"],"awake":["english"],"aware":["english"],"away":["english"],"awesome":["english"],"awful":["english"],"awkward":["english"],"axis":["english"],"baby":["english"],"bachelor":["english"],"bacon":["english"],"badge":["english","french"],"bag":["english"],"balance":["english"],"balcony":["english"],"ball":["english"],"bamboo":["english"],"banana":["english"],"banner":["english"],"bar":["english"],"barely":["english"],"bargain":["english"],"barrel":["english"],"base":["english"],"basic":["english"],"basket":["english"],"battle":["english"],"beach":["english"],"bean":["english"],"beauty":["english"],"because":["english"],"become":["english"],"beef":["english"],"before":["english"],"begin":["english"],"behave":["english"],"behind":["english"],"believe":["english"],"below":["english"],"belt":["english"],"bench":["english"],"benefit":["english"],"best":["english"],"betray":["english"],"better":["english"],"between":["english"],"beyond":["english"],"bicycle":["english","french"],"bid":["english"],"bike":["english"],"bind":["english"],"biology":["english"],"bird":["english"],"birth":["english"],"bitter":["english"],"black":["english"],"blade":["english"],"blame":["english"],"blanket":["english"],"blast":["english"],"bleak":["english"],"bless":["english"],"blind":["english"],"blood":["english"],"blossom":["english"],"blouse":["english"],"blue":["english"],"blur":["english"],"blush":["english"],"board":["english"],"boat":["english"],"body":["english"],"boil":["english"],"bomb":["english"],"bone":["english"],"bonus":["english","french"],"book":["english"],"boost":["english"],"border":["english"],"boring":["english"],"borrow":["english"],"boss":["english"],"bottom":["english"],"bounce":["english"],"box":["english"],"boy":["english"],"bracket":["english"],"brain":["english"],"brand":["english"],"brass":["english"],"brave":["english","french"],"bread":["english"],"breeze":["english"],"brick":["english"],"bridge":["english"],"brief":["english"],"bright":["english"],"bring":["english"],"brisk":["english"],"broccoli":["english"],"broken":["english"],"bronze":["english"],"broom":["english"],"brother":["english"],"brown":["english"],"brush":["english"],"bubble":["english"],"buddy":["english"],"budget":["english"],"buffalo":["english"],"build":["english"],"bulb":["english"],"bulk":["english"],"bullet":["english"],"bundle":["english"],"bunker":["english"],"burden":["english"],"burger":["english"],"burst":["english"],"bus":["english"],"business":["english"],"busy":["english"],"butter":["english"],"buyer":["english"],"buzz":["english"],"cabbage":["english"],"cabin":["english"],"cable":["english"],"cactus":["english"],"cage":["english"],"cake":["english"],"call":["english"],"calm":["english"],"camera":["english"],"camp":["english"],"can":["english"],"canal":["english","french"],"cancel":["english"],"candy":["english"],"cannon":["english"],"canoe":["english"],"canvas":["english"],"canyon":["english"],"capable":["english","french"],"capital":["english"],"captain":["english"],"car":["english"],"carbon":["english"],"card":["english"],"cargo":["english"],"carpet":["english"],"carry":["english"],"cart":["english"],"case":["english"],"cash":["english"],"casino":["english"],"castle":["english"],"casual":["english"],"cat":["english"],"catalog":["english"],"catch":["english"],"category":["english"],"cattle":["english"],"caught":["english"],"cause":["english"],"caution":["english","french"],"cave":["english"],"ceiling":["english"],"celery":["english"],"cement":["english"],"census":["english"],"century":["english"],"cereal":["english"],"certain":["english"],"chair":["english"],"chalk":["english"],"champion":["english"],"change":["english"],"chaos":["english"],"chapter":["english"],"charge":["english"],"chase":["english"],"chat":["english"],"cheap":["english"],"check":["english"],"cheese":["english"],"chef":["english"],"cherry":["english"],"chest":["english"],"chicken":["english"],"chief":["english"],"child":["english"],"chimney":["english"],"choice":["english"],"choose":["english"],"chronic":["english"],"chuckle":["english"],"chunk":["english"],"churn":["english"],"cigar":["english"],"cinnamon":["english"],"circle":["english"],"citizen":["english"],"city":["english"],"civil":["english","french"],"claim":["english"],"clap":["english"],"clarify":["english"],"claw":["english"],"clay":["english"],"clean":["english"],"clerk":["english"],"clever":["english"],"click":["english"],"client":["english","french"],"cliff":["english"],"climb":["english"],"clinic":["english"],"clip":["english"],"clock":["english"],"clog":["english"],"close":["english"],"cloth":["english"],"cloud":["english"],"clown":["english"],"club":["english"],"clump":["english"],"cluster":["english"],"clutch":["english"],"coach":["english"],"coast":["english"],"coconut":["english"],"code":["english"],"coffee":["english"],"coil":["english"],"coin":["english"],"collect":["english"],"color":["english"],"column":["english"],"combine":["english"],"come":["english"],"comfort":["english"],"comic":["english"],"common":["english"],"company":["english"],"concert":["english","french"],"conduct":["english"],"confirm":["english"],"congress":["english"],"connect":["english"],"consider":["english"],"control":["english"],"convince":["english"],"cook":["english"],"cool":["english"],"copper":["english"],"copy":["english"],"coral":["english"],"core":["english"],"corn":["english"],"correct":["english","french"],"cost":["english"],"cotton":["english"],"couch":["english"],"country":["english"],"couple":["english"],"course":["english"],"cousin":["english"],"cover":["english"],"coyote":["english","french"],"crack":["english"],"cradle":["english"],"craft":["english"],"cram":["english"],"crane":["english"],"crash":["english"],"crater":["english"],"crawl":["english"],"crazy":["english"],"cream":["english"],"credit":["english"],"creek":["english"],"crew":["english"],"cricket":["english"],"crime":["english"],"crisp":["english"],"critic":["english"],"crop":["english"],"cross":["english"],"crouch":["english"],"crowd":["english"],"crucial":["english","french"],"cruel":["english","french"],"cruise":["english"],"crumble":["english"],"crunch":["english"],"crush":["english"],"cry":["english"],"crystal":["english"],"cube":["english"],"culture":["english"],"cup":["english"],"cupboard":["english"],"curious":["english"],"current":["english"],"curtain":["english"],"curve":["english"],"cushion":["english"],"custom":["english"],"cute":["english"],"cycle":["english","french"],"dad":["english"],"damage":["english"],"damp":["english"],"dance":["english"],"danger":["english","french"],"daring":["english"],"dash":["english"],"daughter":["english"],"dawn":["english"],"day":["english"],"deal":["english"],"debate":["english"],"debris":["english"],"decade":["english"],"december":["english"],"decide":["english"],"decline":["english"],"decorate":["english"],"decrease":["english"],"deer":["english"],"defense":["english"],"define":["english"],"defy":["english"],"degree":["english"],"delay":["english"],"deliver":["english"],"demand":["english"],"demise":["english"],"denial":["english"],"dentist":["english"],"deny":["english"],"depart":["english"],"depend":["english"],"deposit":["english"],"depth":["english"],"deputy":["english"],"derive":["english"],"describe":["english"],"desert":["english"],"design":["english"],"desk":["english"],"despair":["english"],"destroy":["english"],"detail":["english"],"detect":["english"],"develop":["english"],"device":["english"],"devote":["english"],"diagram":["english"],"dial":["english"],"diamond":["english"],"diary":["english"],"dice":["english"],"diesel":["english"],"diet":["english"],"differ":["english"],"digital":["english","french"],"dignity":["english"],"dilemma":["english"],"dinner":["english"],"dinosaur":["english"],"direct":["english"],"dirt":["english"],"disagree":["english"],"discover":["english"],"disease":["english"],"dish":["english"],"dismiss":["english"],"disorder":["english"],"display":["english"],"distance":["english","french"],"divert":["english"],"divide":["english"],"divorce":["english"],"dizzy":["english"],"doctor":["english"],"document":["english"],"dog":["english"],"doll":["english"],"dolphin":["english"],"domain":["english"],"donate":["english"],"donkey":["english"],"donor":["english"],"door":["english"],"dose":["english"],"double":["english","french"],"dove":["english"],"draft":["english"],"dragon":["english","french"],"drama":["english"],"drastic":["english"],"draw":["english"],"dream":["english"],"dress":["english"],"drift":["english"],"drill":["english"],"drink":["english"],"drip":["english"],"drive":["english"],"drop":["english"],"drum":["english"],"dry":["english"],"duck":["english"],"dumb":["english"],"dune":["english"],"during":["english"],"dust":["english"],"dutch":["english"],"duty":["english"],"dwarf":["english"],"dynamic":["english"],"eager":["english"],"eagle":["english"],"early":["english"],"earn":["english"],"earth":["english"],"easily":["english"],"east":["english"],"easy":["english"],"echo":["english"],"ecology":["english"],"economy":["english"],"edge":["english"],"edit":["english"],"educate":["english"],"effort":["english","french"],"egg":["english"],"eight":["english"],"either":["english"],"elbow":["english"],"elder":["english"],"electric":["english"],"elegant":["english"],"element":["english"],"elephant":["english"],"elevator":["english"],"elite":["english"],"else":["english"],"embark":["english"],"embody":["english"],"embrace":["english"],"emerge":["english"],"emotion":["english"],"employ":["english"],"empower":["english"],"empty":["english"],"enable":["english"],"enact":["english"],"end":["english"],"endless":["english"],"endorse":["english"],"enemy":["english"],"energy":["english"],"enforce":["english"],"engage":["english"],"engine":["english"],"enhance":["english"],"enjoy":["english"],"enlist":["english"],"enough":["english"],"enrich":["english"],"enroll":["english"],"ensure":["english"],"enter":["english"],"entire":["english"],"entry":["english"],"envelope":["english"],"episode":["english"],"equal":["english"],"equip":["english"],"era":["english"],"erase":["english"],"erode":["english"],"erosion":["english"],"error":["english"],"erupt":["english"],"escape":["english"],"essay":["english"],"essence":["english","french"],"estate":["english"],"eternal":["english"],"ethics":["english"],"evidence":["english"],"evil":["english"],"evoke":["english"],"evolve":["english"],"exact":["english","french"],"example":["english"],"excess":["english"],"exchange":["english"],"excite":["english"],"exclude":["english"],"excuse":["english","french"],"execute":["english"],"exercise":["english"],"exhaust":["english"],"exhibit":["english"],"exile":["english"],"exist":["english"],"exit":["english"],"exotic":["english"],"expand":["english"],"expect":["english"],"expire":["english"],"explain":["english"],"expose":["english"],"express":["english"],"extend":["english"],"extra":["english"],"eye":["english"],"eyebrow":["english"],"fabric":["english"],"face":["english"],"faculty":["english"],"fade":["english"],"faint":["english"],"faith":["english"],"fall":["english"],"false":["english"],"fame":["english"],"family":["english"],"famous":["english"],"fan":["english"],"fancy":["english"],"fantasy":["english"],"farm":["english"],"fashion":["english"],"fat":["english"],"fatal":["english","french"],"father":["english"],"fatigue":["english","french"],"fault":["english"],"favorite":["english"],"feature":["english"],"february":["english"],"federal":["english","turkish"],"fee":["english"],"feed":["english"],"feel":["english"],"female":["english"],"fence":["english"],"festival":["english","french","turkish"],"fetch":["english"],"fever":["english"],"few":["english"],"fiber":["english"],"fiction":["english"],"field":["english"],"figure":["english","french"],"file":["english"],"film":["english"],"filter":["english"],"final":["english"],"find":["english"],"fine":["english"],"finger":["english"],"finish":["english"],"fire":["english"],"firm":["english"],"first":["english"],"fiscal":["english"],"fish":["english"],"fit":["english"],"fitness":["english"],"fix":["english"],"flag":["english"],"flame":["english"],"flash":["english"],"flat":["english"],"flavor":["english"],"flee":["english"],"flight":["english"],"flip":["english"],"float":["english"],"flock":["english"],"floor":["english"],"flower":["english"],"fluid":["english"],"flush":["english"],"fly":["english"],"foam":["english"],"focus":["english"],"fog":["english"],"foil":["english"],"fold":["english"],"follow":["english"],"food":["english"],"foot":["english"],"force":["english"],"forest":["english"],"forget":["english"],"fork":["english"],"fortune":["english","french"],"forum":["english"],"forward":["english"],"fossil":["english"],"foster":["english"],"found":["english"],"fox":["english"],"fragile":["english","french"],"frame":["english"],"frequent":["english"],"fresh":["english"],"friend":["english"],"fringe":["english"],"frog":["english"],"front":["english"],"frost":["english"],"frown":["english"],"frozen":["english"],"fruit":["english","french"],"fuel":["english"],"fun":["english"],"funny":["english"],"furnace":["english"],"fury":["english"],"future":["english"],"gadget":["english"],"gain":["english"],"galaxy":["english"],"gallery":["english"],"game":["english"],"gap":["english"],"garage":["english"],"garbage":["english"],"garden":["english"],"garlic":["english"],"garment":["english"],"gas":["english"],"gasp":["english"],"gate":["english"],"gather":["english"],"gauge":["english"],"gaze":["english"],"general":["english"],"genius":["english"],"genre":["english"],"gentle":["english"],"genuine":["english"],"gesture":["english"],"ghost":["english"],"giant":["english"],"gift":["english"],"giggle":["english"],"ginger":["english"],"giraffe":["english"],"girl":["english"],"give":["english"],"glad":["english"],"glance":["english"],"glare":["english"],"glass":["english"],"glide":["english"],"glimpse":["english"],"globe":["english","french"],"gloom":["english"],"glory":["english"],"glove":["english"],"glow":["english"],"glue":["english"],"goat":["english"],"goddess":["english"],"gold":["english"],"good":["english"],"goose":["english"],"gorilla":["english"],"gospel":["english"],"gossip":["english"],"govern":["english"],"gown":["english"],"grab":["english"],"grace":["english"],"grain":["english"],"grant":["english"],"grape":["english"],"grass":["english"],"gravity":["english"],"great":["english"],"green":["english"],"grid":["english"],"grief":["english"],"grit":["english"],"grocery":["english"],"group":["english"],"grow":["english"],"grunt":["english"],"guard":["english"],"guess":["english"],"guide":["english","french"],"guilt":["english"],"guitar":["english"],"gun":["english"],"gym":["english"],"habit":["english"],"hair":["english"],"half":["english"],"hammer":["english"],"hamster":["english"],"hand":["english"],"happy":["english"],"harbor":["english"],"hard":["english"],"harsh":["english"],"harvest":["english"],"hat":["english"],"have":["english"],"hawk":["english"],"hazard":["english"],"head":["english"],"health":["english"],"heart":["english"],"heavy":["english"],"hedgehog":["english"],"height":["english"],"hello":["english"],"helmet":["english"],"help":["english"],"hen":["english"],"hero":["english"],"hidden":["english"],"high":["english"],"hill":["english"],"hint":["english"],"hip":["english"],"hire":["english"],"history":["english"],"hobby":["english"],"hockey":["english"],"hold":["english"],"hole":["english"],"holiday":["english"],"hollow":["english"],"home":["english"],"honey":["english"],"hood":["english"],"hope":["english"],"horn":["english"],"horror":["english"],"horse":["english"],"hospital":["english"],"host":["english"],"hotel":["english"],"hour":["english"],"hover":["english"],"hub":["english"],"huge":["english"],"human":["english"],"humble":["english","french"],"humor":["english"],"hundred":["english"],"hungry":["english"],"hunt":["english"],"hurdle":["english"],"hurry":["english"],"hurt":["english"],"husband":["english"],"hybrid":["english"],"ice":["english"],"icon":["english"],"idea":["english"],"identify":["english"],"idle":["english"],"ignore":["english"],"ill":["english"],"illegal":["english"],"illness":["english"],"image":["english","french"],"imitate":["english"],"immense":["english","french"],"immune":["english"],"impact":["english","french"],"impose":["english"],"improve":["english"],"impulse":["english"],"inch":["english"],"include":["english"],"income":["english"],"increase":["english"],"index":["english"],"indicate":["english"],"indoor":["english"],"industry":["english"],"infant":["english"],"inflict":["english"],"inform":["english"],"inhale":["english"],"inherit":["english"],"initial":["english"],"inject":["english"],"injury":["english"],"inmate":["english"],"inner":["english"],"innocent":["english","french"],"input":["english"],"inquiry":["english"],"insane":["english"],"insect":["english"],"inside":["english"],"inspire":["english"],"install":["english"],"intact":["english","french"],"interest":["english"],"into":["english"],"invest":["english"],"invite":["english"],"involve":["english"],"iron":["english"],"island":["english"],"isolate":["english"],"issue":["english"],"item":["english"],"ivory":["english"],"jacket":["english"],"jaguar":["english","french"],"jar":["english"],"jazz":["english"],"jealous":["english"],"jeans":["english"],"jelly":["english"],"jewel":["english"],"job":["english"],"join":["english"],"joke":["english"],"journey":["english"],"joy":["english"],"judge":["english"],"juice":["english"],"jump":["english"],"jungle":["english"],"junior":["english","french"],"junk":["english"],"just":["english"],"kangaroo":["english"],"keen":["english"],"keep":["english"],"ketchup":["english"],"key":["english"],"kick":["english"],"kid":["english"],"kidney":["english"],"kind":["english"],"kingdom":["english"],"kiss":["english"],"kit":["english"],"kitchen":["english"],"kite":["english"],"kitten":["english"],"kiwi":["english"],"knee":["english"],"knife":["english"],"knock":["english"],"know":["english"],"lab":["english"],"label":["english","french"],"labor":["english"],"ladder":["english"],"lady":["english"],"lake":["english"],"lamp":["english"],"language":["english"],"laptop":["english"],"large":["english"],"later":["english"],"latin":["english"],"laugh":["english"],"laundry":["english"],"lava":["english"],"law":["english"],"lawn":["english"],"lawsuit":["english"],"layer":["english"],"lazy":["english"],"leader":["english"],"leaf":["english"],"learn":["english"],"leave":["english"],"lecture":["english","french"],"left":["english"],"leg":["english"],"legal":["english"],"legend":["english"],"leisure":["english"],"lemon":["english"],"lend":["english"],"length":["english"],"lens":["english"],"leopard":["english"],"lesson":["english"],"letter":["english"],"level":["english"],"liar":["english"],"liberty":["english"],"library":["english"],"license":["english"],"life":["english"],"lift":["english"],"light":["english"],"like":["english"],"limb":["english"],"limit":["english"],"link":["english"],"lion":["english"],"liquid":["english"],"list":["english"],"little":["english"],"live":["english"],"lizard":["english"],"load":["english"],"loan":["english"],"lobster":["english"],"local":["english"],"lock":["english"],"logic":["english"],"lonely":["english"],"long":["english"],"loop":["english"],"lottery":["english"],"loud":["english"],"lounge":["english"],"love":["english"],"loyal":["english","french"],"lucky":["english"],"luggage":["english"],"lumber":["english"],"lunar":["english"],"lunch":["english"],"luxury":["english"],"lyrics":["english"],"machine":["english","french"],"mad":["english"],"magic":["english"],"magnet":["english"],"maid":["english"],"mail":["english"],"main":["english"],"major":["english"],"make":["english"],"mammal":["english"],"man":["english"],"manage":["english"],"mandate":["english"],"mango":["english"],"mansion":["english"],"manual":["english"],"maple":["english"],"marble":["english"],"march":["english"],"margin":["english"],"marine":["english"],"market":["english","turkish"],"marriage":["english"],"mask":["english"],"mass":["english"],"master":["english"],"match":["english"],"material":["english"],"math":["english"],"matrix":["english"],"matter":["english"],"maximum":["english"],"maze":["english"],"meadow":["english"],"mean":["english"],"measure":["english"],"meat":["english"],"mechanic":["english"],"medal":["english"],"media":["english"],"melody":["english"],"melt":["english"],"member":["english"],"memory":["english"],"mention":["english"],"menu":["english"],"mercy":["english"],"merge":["english"],"merit":["english"],"merry":["english"],"mesh":["english"],"message":["english"],"metal":["english"],"method":["english"],"middle":["english"],"midnight":["english"],"milk":["english"],"million":["english","french"],"mimic":["english"],"mind":["english"],"minimum":["english"],"minor":["english"],"minute":["english","french"],"miracle":["english","french"],"mirror":["english"],"misery":["english"],"miss":["english"],"mistake":["english"],"mix":["english"],"mixed":["english"],"mixture":["english"],"mobile":["english","french"],"model":["english","turkish"],"modify":["english"],"mom":["english"],"moment":["english"],"monitor":["english"],"monkey":["english"],"monster":["english"],"month":["english"],"moon":["english"],"moral":["english"],"more":["english"],"morning":["english"],"mosquito":["english"],"mother":["english"],"motion":["english"],"motor":["english","turkish"],"mountain":["english"],"mouse":["english"],"move":["english"],"movie":["english"],"much":["english"],"muffin":["english"],"mule":["english"],"multiply":["english"],"muscle":["english","french"],"museum":["english"],"mushroom":["english"],"music":["english"],"must":["english"],"mutual":["english"],"myself":["english"],"mystery":["english"],"myth":["english"],"naive":["english"],"name":["english"],"napkin":["english"],"narrow":["english"],"nasty":["english"],"nation":["english","french"],"nature":["english","french"],"near":["english"],"neck":["english"],"need":["english"],"negative":["english"],"neglect":["english"],"neither":["english"],"nephew":["english"],"nerve":["english"],"nest":["english"],"net":["english"],"network":["english"],"neutral":["english"],"never":["english"],"news":["english"],"next":["english"],"nice":["english"],"night":["english"],"noble":["english","french"],"noise":["english"],"nominee":["english"],"noodle":["english"],"normal":["english","turkish"],"north":["english"],"nose":["english"],"notable":["english","french"],"note":["english"],"nothing":["english"],"notice":["english"],"novel":["english"],"now":["english"],"nuclear":["english"],"number":["english"],"nurse":["english"],"nut":["english"],"oak":["english"],"obey":["english"],"object":["english"],"oblige":["english"],"obscure":["english"],"observe":["english"],"obtain":["english"],"obvious":["english"],"occur":["english"],"ocean":["english"],"october":["english"],"odor":["english"],"off":["english"],"offer":["english"],"office":["english"],"often":["english"],"oil":["english"],"okay":["english"],"old":["english"],"olive":["english"],"olympic":["english"],"omit":["english"],"once":["english"],"one":["english"],"onion":["english"],"online":["english"],"only":["english"],"open":["english"],"opera":["english","turkish"],"opinion":["english","french"],"oppose":["english"],"option":["english"],"orange":["english","french"],"orbit":["english"],"orchard":["english"],"order":["english"],"ordinary":["english"],"organ":["english"],"orient":["english"],"original":["english"],"orphan":["english"],"ostrich":["english"],"other":["english"],"outdoor":["english"],"outer":["english"],"output":["english"],"outside":["english"],"oval":["english"],"oven":["english"],"over":["english"],"own":["english"],"owner":["english"],"oxygen":["english"],"oyster":["english"],"ozone":["english","french"],"pact":["english"],"paddle":["english"],"page":["english"],"pair":["english"],"palace":["english","french"],"palm":["english"],"panda":["english","french","turkish"],"panel":["english","turkish"],"panic":["english"],"panther":["english"],"paper":["english"],"parade":["english"],"parent":["english"],"park":["english"],"parrot":["english"],"party":["english"],"pass":["english"],"patch":["english"],"path":["english"],"patient":["english"],"patrol":["english"],"pattern":["english"],"pause":["english"],"pave":["english"],"payment":["english"],"peace":["english"],"peanut":["english"],"pear":["english"],"peasant":["english"],"pelican":["english"],"pen":["english"],"penalty":["english"],"pencil":["english"],"people":["english"],"pepper":["english"],"perfect":["english"],"permit":["english"],"person":["english"],"pet":["english"],"phone":["english"],"photo":["english"],"phrase":["english","french"],"physical":["english"],"piano":["english","french"],"picnic":["english"],"picture":["english"],"piece":["english"],"pig":["english"],"pigeon":["english"],"pill":["english"],"pilot":["english","turkish"],"pink":["english"],"pioneer":["english"],"pipe":["english"],"pistol":["english"],"pitch":["english"],"pizza":["english","french"],"place":["english"],"planet":["english"],"plastic":["english"],"plate":["english"],"play":["english"],"please":["english"],"pledge":["english"],"pluck":["english"],"plug":["english"],"plunge":["english"],"poem":["english"],"poet":["english"],"point":["english"],"polar":["english"],"pole":["english"],"police":["english"],"pond":["english"],"pony":["english"],"pool":["english"],"popular":["english"],"portion":["english"],"position":["english","french"],"possible":["english"],"post":["english"],"potato":["english"],"pottery":["english"],"poverty":["english"],"powder":["english"],"power":["english"],"practice":["english"],"praise":["english"],"predict":["english"],"prefer":["english"],"prepare":["english"],"present":["english"],"pretty":["english"],"prevent":["english"],"price":["english"],"pride":["english"],"primary":["english"],"print":["english"],"priority":["english"],"prison":["english","french"],"private":["english"],"prize":["english"],"problem":["english","turkish"],"process":["english"],"produce":["english"],"profit":["english"],"program":["english","turkish"],"project":["english"],"promote":["english"],"proof":["english"],"property":["english"],"prosper":["english"],"protect":["english"],"proud":["english"],"provide":["english"],"public":["english","french"],"pudding":["english"],"pull":["english"],"pulp":["english"],"pulse":["english"],"pumpkin":["english"],"punch":["english"],"pupil":["english"],"puppy":["english"],"purchase":["english"],"purity":["english"],"purpose":["english"],"purse":["english"],"push":["english"],"put":["english"],"puzzle":["english","french"],"pyramid":["english"],"quality":["english"],"quantum":["english"],"quarter":["english"],"question":["english","french"],"quick":["english"],"quit":["english"],"quiz":["english"],"quote":["english"],"rabbit":["english"],"raccoon":["english"],"race":["english"],"rack":["english"],"radar":["english","turkish"],"radio":["english"],"rail":["english"],"rain":["english"],"raise":["english"],"rally":["english"],"ramp":["english"],"ranch":["english"],"random":["english"],"range":["english"],"rapid":["english"],"rare":["english"],"rate":["english"],"rather":["english"],"raven":["english"],"raw":["english"],"razor":["english"],"ready":["english"],"real":["english"],"reason":["english"],"rebel":["english"],"rebuild":["english"],"recall":["english"],"receive":["english"],"recipe":["english"],"record":["english"],"recycle":["english"],"reduce":["english"],"reflect":["english"],"reform":["english","turkish"],"refuse":["english"],"region":["english"],"regret":["english"],"regular":["english"],"reject":["english"],"relax":["english"],"release":["english"],"relief":["english","french"],"rely":["english"],"remain":["english"],"remember":["english"],"remind":["english"],"remove":["english"],"render":["english"],"renew":["english"],"rent":["english"],"reopen":["english"],"repair":["english"],"repeat":["english"],"replace":["english"],"report":["english"],"require":["english"],"rescue":["english"],"resemble":["english"],"resist":["english"],"resource":["english"],"response":["english"],"result":["english"],"retire":["english"],"retreat":["english"],"return":["english"],"reunion":["english"],"reveal":["english"],"review":["english"],"reward":["english"],"rhythm":["english"],"rib":["english"],"ribbon":["english"],"rice":["english"],"rich":["english"],"ride":["english"],"ridge":["english"],"rifle":["english"],"right":["english"],"rigid":["english"],"ring":["english"],"riot":["english"],"ripple":["english"],"risk":["english"],"ritual":["english"],"rival":["english","french"],"river":["english"],"road":["english"],"roast":["english"],"robot":["english","turkish"],"robust":["english"],"rocket":["english"],"romance":["english","french"],"roof":["english"],"rookie":["english"],"room":["english"],"rose":["english"],"rotate":["english"],"rough":["english"],"round":["english"],"route":["english"],"royal":["english"],"rubber":["english"],"rude":["english"],"rug":["english"],"rule":["english"],"run":["english"],"runway":["english"],"rural":["english"],"sad":["english"],"saddle":["english"],"sadness":["english"],"safe":["english"],"sail":["english"],"salad":["english"],"salmon":["english"],"salon":["english","french","turkish"],"salt":["english"],"salute":["english"],"same":["english"],"sample":["english"],"sand":["english"],"satisfy":["english"],"satoshi":["english"],"sauce":["english"],"sausage":["english"],"save":["english"],"say":["english"],"scale":["english"],"scan":["english"],"scare":["english"],"scatter":["english"],"scene":["english"],"scheme":["english"],"school":["english"],"science":["english","french"],"scissors":["english"],"scorpion":["english"],"scout":["english"],"scrap":["english"],"screen":["english"],"script":["english"],"scrub":["english"],"sea":["english"],"search":["english"],"season":["english"],"seat":["english"],"second":["english"],"secret":["english"],"section":["english"],"security":["english"],"seed":["english"],"seek":["english"],"segment":["english"],"select":["english"],"sell":["english"],"seminar":["english"],"senior":["english"],"sense":["english"],"sentence":["english","french"],"series":["english"],"service":["english","french"],"session":["english"],"settle":["english"],"setup":["english"],"seven":["english"],"shadow":["english"],"shaft":["english"],"shallow":["english"],"share":["english"],"shed":["english"],"shell":["english"],"sheriff":["english"],"shield":["english"],"shift":["english"],"shine":["english"],"ship":["english"],"shiver":["english"],"shock":["english"],"shoe":["english"],"shoot":["english"],"shop":["english"],"short":["english"],"shoulder":["english"],"shove":["english"],"shrimp":["english"],"shrug":["english"],"shuffle":["english"],"shy":["english"],"sibling":["english"],"sick":["english"],"side":["english"],"siege":["english"],"sight":["english"],"sign":["english"],"silent":["english"],"silk":["english"],"silly":["english"],"silver":["english"],"similar":["english"],"simple":["english","french"],"since":["english"],"sing":["english"],"siren":["english"],"sister":["english"],"situate":["english"],"six":["english"],"size":["english"],"skate":["english"],"sketch":["english"],"ski":["english"],"skill":["english"],"skin":["english"],"skirt":["english"],"skull":["english"],"slab":["english"],"slam":["english"],"sleep":["english"],"slender":["english"],"slice":["english"],"slide":["english"],"slight":["english"],"slim":["english"],"slogan":["english","turkish"],"slot":["english"],"slow":["english"],"slush":["english"],"small":["english"],"smart":["english"],"smile":["english"],"smoke":["english"],"smooth":["english"],"snack":["english"],"snake":["english"],"snap":["english"],"sniff":["english"],"snow":["english"],"soap":["english"],"soccer":["english"],"social":["english","french"],"sock":["english"],"soda":["english"],"soft":["english"],"solar":["english"],"soldier":["english"],"solid":["english"],"solution":["english"],"solve":["english"],"someone":["english"],"song":["english"],"soon":["english"],"sorry":["english"],"sort":["english"],"soul":["english"],"sound":["english"],"soup":["english"],"source":["english","french"],"south":["english"],"space":["english"],"spare":["english"],"spatial":["english","french"],"spawn":["english"],"speak":["english"],"special":["english"],"speed":["english"],"spell":["english"],"spend":["english"],"sphere":["english"],"spice":["english"],"spider":["english"],"spike":["english"],"spin":["english"],"spirit":["english"],"split":["english"],"spoil":["english"],"sponsor":["english","turkish"],"spoon":["english"],"sport":["english"],"spot":["english"],"spray":["english"],"spread":["english"],"spring":["english"],"spy":["english"],"square":["english"],"squeeze":["english"],"squirrel":["english"],"stable":["english","french"],"stadium":["english"],"staff":["english"],"stage":["english"],"stairs":["english"],"stamp":["english"],"stand":["english"],"start":["english"],"state":["english"],"stay":["english"],"steak":["english"],"steel":["english"],"stem":["english"],"step":["english"],"stereo":["english"],"stick":["english"],"still":["english"],"sting":["english"],"stock":["english"],"stomach":["english"],"stone":["english"],"stool":["english"],"story":["english"],"stove":["english"],"strategy":["english"],"street":["english"],"strike":["english"],"strong":["english"],"struggle":["english"],"student":["english"],"stuff":["english"],"stumble":["english"],"style":["english"],"subject":["english"],"submit":["english"],"subway":["english"],"success":["english"],"such":["english"],"sudden":["english"],"suffer":["english"],"sugar":["english"],"suggest":["english"],"suit":["english"],"summer":["english"],"sun":["english"],"sunny":["english"],"sunset":["english"],"super":["english"],"supply":["english"],"supreme":["english"],"sure":["english"],"surface":["english","french"],"surge":["english"],"surprise":["english","french"],"surround":["english"],"survey":["english"],"suspect":["english","french"],"sustain":["english"],"swallow":["english"],"swamp":["english"],"swap":["english"],"swarm":["english"],"swear":["english"],"sweet":["english"],"swift":["english"],"swim":["english"],"swing":["english"],"switch":["english"],"sword":["english"],"symbol":["english"],"symptom":["english"],"syrup":["english"],"system":["english"],"table":["english"],"tackle":["english"],"tag":["english"],"tail":["english"],"talent":["english","french"],"talk":["english"],"tank":["english"],"tape":["english"],"target":["english"],"task":["english"],"taste":["english"],"tattoo":["english"],"taxi":["english"],"teach":["english"],"team":["english"],"tell":["english"],"ten":["english"],"tenant":["english"],"tennis":["english"],"tent":["english"],"term":["english"],"test":["english"],"text":["english"],"thank":["english"],"that":["english"],"theme":["english"],"then":["english"],"theory":["english"],"there":["english"],"they":["english"],"thing":["english"],"this":["english"],"thought":["english"],"three":["english"],"thrive":["english"],"throw":["english"],"thumb":["english"],"thunder":["english"],"ticket":["english"],"tide":["english"],"tiger":["english"],"tilt":["english"],"timber":["english"],"time":["english"],"tiny":["english"],"tip":["english"],"tired":["english"],"tissue":["english"],"title":["english"],"toast":["english"],"tobacco":["english"],"today":["english"],"toddler":["english"],"toe":["english"],"together":["english"],"toilet":["english"],"token":["english"],"tomato":["english"],"tomorrow":["english"],"tone":["english"],"tongue":["english"],"tonight":["english"],"tool":["english"],"tooth":["english"],"top":["english"],"topic":["english"],"topple":["english"],"torch":["english"],"tornado":["english"],"tortoise":["english"],"toss":["english"],"total":["english"],"tourist":["english"],"toward":["english"],"tower":["english"],"town":["english"],"toy":["english"],"track":["english"],"trade":["english"],"traffic":["english"],"tragic":["english"],"train":["english","french"],"transfer":["english","turkish"],"trap":["english"],"trash":["english"],"travel":["english"],"tray":["english"],"treat":["english"],"tree":["english"],"trend":["english"],"trial":["english"],"tribe":["english"],"trick":["english"],"trigger":["english"],"trim":["english"],"trip":["english"],"trophy":["english"],"trouble":["english"],"truck":["english"],"true":["english"],"truly":["english"],"trumpet":["english"],"trust":["english"],"truth":["english"],"try":["english"],"tube":["english"],"tuition":["english"],"tumble":["english"],"tuna":["english"],"tunnel":["english","french"],"turkey":["english"],"turn":["english"],"turtle":["english"],"twelve":["english"],"twenty":["english"],"twice":["english"],"twin":["english"],"twist":["english"],"two":["english"],"type":["english"],"typical":["english"],"ugly":["english"],"umbrella":["english"],"unable":["english"],"unaware":["english"],"uncle":["english"],"uncover":["english"],"under":["english"],"undo":["english"],"unfair":["english"],"unfold":["english"],"unhappy":["english"],"uniform":["english"],"unique":["english","french"],"unit":["english"],"universe":["english"],"unknown":["english"],"unlock":["english"],"until":["english"],"unusual":["english"],"unveil":["english"],"update":["english"],"upgrade":["english"],"uphold":["english"],"upon":["english"],"upper":["english"],"upset":["english"],"urban":["english"],"urge":["english"],"usage":["english","french"],"use":["english"],"used":["english"],"useful":["english"],"useless":["english"],"usual":["english"],"utility":["english"],"vacant":["english"],"vacuum":["english"],"vague":["english","french"],"valid":["english"],"valley":["english"],"valve":["english","french"],"van":["english"],"vanish":["english"],"vapor":["english"],"various":["english"],"vast":["english"],"vault":["english"],"vehicle":["english"],"velvet":["english"],"vendor":["english"],"venture":["english"],"venue":["english"],"verb":["english"],"verify":["english"],"version":["english"],"very":["english"],"vessel":["english"],"veteran":["english"],"viable":["english"],"vibrant":["english"],"vicious":["english"],"victory":["english"],"video":["english"],"view":["english"],"village":["english","french"],"vintage":["english"],"violin":["english"],"virtual":["english"],"virus":["english","french"],"visa":["english"],"visit":["english"],"visual":["english"],"vital":["english","french"],"vivid":["english"],"vocal":["english"],"voice":["english"],"void":["english"],"volcano":["english"],"volume":["english","french"],"vote":["english"],"voyage":["english","french"],"wage":["english"],"wagon":["english","french"],"wait":["english"],"walk":["english"],"wall":["english"],"walnut":["english"],"want":["english"],"warfare":["english"],"warm":["english"],"warrior":["english"],"wash":["english"],"wasp":["english"],"waste":["english"],"water":["english"],"wave":["english"],"way":["english"],"wealth":["english"],"weapon":["english"],"wear":["english"],"weasel":["english"],"weather":["english"],"web":["english"],"wedding":["english"],"weekend":["english"],"weird":["english"],"welcome":["english"],"west":["english"],"wet":["english"],"whale":["english"],"what":["english"],"wheat":["english"],"wheel":["english"],"when":["english"],"where":["english"],"whip":["english"],"whisper":["english"],"wide":["english"],"width":["english"],"wife":["english"],"wild":["english"],"will":["english"],"win":["english"],"window":["english"],"wine":["english"],"wing":["english"],"wink":["english"],"winner":["english"],"winter":["english"],"wire":["english"],"wisdom":["english"],"wise":["english"],"wish":["english"],"witness":["english"],"wolf":["english"],"woman":["english"],"wonder":["english"],"wood":["english"],"wool":["english"],"word":["english"],"work":["english"],"world":["english"],"worry":["english"],"worth":["english"],"wrap":["english"],"wreck":["english"],"wrestle":["english"],"wrist":["english"],"write":["english"],"wrong":["english"],"yard":["english"],"year":["english"],"yellow":["english"],"you":["english"],"young":["english"],"youth":["english"],"zebra":["english"],"zero":["english"],"zone":["english"],"zoo":["english"],"abaisser":["french"],"abdiquer":["french"],"abeille":["french"],"abolir":["french"],"aborder":["french"],"aboutir":["french"],"aboyer":["french"],"abrasif":["french"],"abreuver":["french"],"abriter":["french"],"abroger":["french"],"abrupt":["french"],"absence":["french"],"absolu":["french"],"absurde":["french"],"abusif":["french"],"abyssal":["french"],"académie":["french"],"acajou":["french"],"acarien":["french"],"accabler":["french"],"accepter":["french"],"acclamer":["french"],"accolade":["french"],"accroche":["french"],"accuser":["french"],"acerbe":["french"],"achat":["french"],"acheter":["french"],"aciduler":["french"],"acier":["french"],"acompte":["french"],"acquérir":["french"],"acronyme":["french"],"acteur":["french"],"actif":["french"],"actuel":["french"],"adepte":["french"],"adéquat":["french"],"adhésif":["french"],"adjectif":["french"],"adjuger":["french"],"admettre":["french"],"admirer":["french"],"adopter":["french"],"adorer":["french"],"adoucir":["french"],"adresse":["french"],"adroit":["french"],"adulte":["french"],"adverbe":["french"],"aérer":["french"],"aéronef":["french"],"affaire":["french"],"affecter":["french"],"affiche":["french"],"affreux":["french"],"affubler":["french"],"agacer":["french"],"agencer":["french"],"agile":["french"],"agiter":["french"],"agrafer":["french"],"agréable":["french"],"agrume":["french"],"aider":["french"],"aiguille":["french"],"ailier":["french"],"aimable":["french"],"aisance":["french"],"ajouter":["french"],"ajuster":["french"],"alarmer":["french"],"alchimie":["french"],"alerte":["french"],"algèbre":["french"],"algue":["french"],"aliéner":["french"],"aliment":["french"],"alléger":["french"],"alliage":["french"],"allouer":["french"],"allumer":["french"],"alourdir":["french"],"alpaga":["french"],"altesse":["french"],"alvéole":["french"],"ambigu":["french"],"ambre":["french"],"aménager":["french"],"amertume":["french"],"amidon":["french"],"amiral":["french"],"amorcer":["french"],"amour":["french"],"amovible":["french"],"amphibie":["french"],"ampleur":["french"],"amusant":["french"],"analyse":["french"],"anaphore":["french"],"anarchie":["french"],"anatomie":["french"],"ancien":["french"],"anéantir":["french"],"angoisse":["french"],"anguleux":["french"],"annexer":["french"],"annonce":["french"],"annuel":["french"],"anodin":["french"],"anomalie":["french"],"anonyme":["french"],"anormal":["french"],"antenne":["french"],"antidote":["french"],"anxieux":["french"],"apaiser":["french"],"apéritif":["french"],"aplanir":["french"],"apologie":["french"],"appareil":["french"],"appeler":["french"],"apporter":["french"],"appuyer":["french"],"aquarium":["french"],"aqueduc":["french"],"arbitre":["french"],"arbuste":["french"],"ardeur":["french"],"ardoise":["french"],"argent":["french"],"arlequin":["french"],"armature":["french"],"armement":["french"],"armoire":["french"],"armure":["french"],"arpenter":["french"],"arracher":["french"],"arriver":["french"],"arroser":["french"],"arsenic":["french"],"artériel":["french"],"article":["french"],"asphalte":["french"],"aspirer":["french"],"assaut":["french"],"asservir":["french"],"assiette":["french"],"associer":["french"],"assurer":["french"],"asticot":["french"],"astre":["french"],"astuce":["french"],"atelier":["french"],"atome":["french"],"atrium":["french"],"atroce":["french"],"attaque":["french"],"attentif":["french"],"attirer":["french"],"attraper":["french"],"aubaine":["french"],"auberge":["french"],"audace":["french"],"audible":["french"],"augurer":["french"],"aurore":["french"],"automne":["french"],"autruche":["french"],"avaler":["french"],"avancer":["french"],"avarice":["french"],"avenir":["french"],"averse":["french"],"aveugle":["french"],"aviateur":["french"],"avide":["french"],"avion":["french"],"aviser":["french"],"avoine":["french"],"avouer":["french"],"avril":["french"],"axial":["french"],"axiome":["french"],"bafouer":["french"],"bagage":["french"],"baguette":["french"],"baignade":["french"],"balancer":["french"],"balcon":["french"],"baleine":["french"],"balisage":["french"],"bambin":["french"],"bancaire":["french"],"bandage":["french"],"banlieue":["french"],"bannière":["french"],"banquier":["french"],"barbier":["french"],"baril":["french"],"baron":["french"],"barque":["french"],"barrage":["french"],"bassin":["french"],"bastion":["french"],"bataille":["french"],"bateau":["french"],"batterie":["french"],"baudrier":["french"],"bavarder":["french"],"belette":["french"],"bélier":["french"],"belote":["french"],"bénéfice":["french"],"berceau":["french"],"berger":["french"],"berline":["french"],"bermuda":["french","turkish"],"besace":["french"],"besogne":["french"],"bétail":["french"],"beurre":["french"],"biberon":["french"],"bidule":["french"],"bijou":["french"],"bilan":["french"],"bilingue":["french"],"billard":["french"],"binaire":["french"],"biologie":["french"],"biopsie":["french"],"biotype":["french"],"biscuit":["french"],"bison":["french"],"bistouri":["french"],"bitume":["french"],"bizarre":["french"],"blafard":["french"],"blague":["french"],"blanchir":["french"],"blessant":["french"],"blinder":["french"],"blond":["french"],"bloquer":["french"],"blouson":["french"],"bobard":["french"],"bobine":["french"],"boire":["french"],"boiser":["french"],"bolide":["french"],"bonbon":["french"],"bondir":["french"],"bonheur":["french"],"bonifier":["french"],"bordure":["french"],"borne":["french"],"botte":["french"],"boucle":["french"],"boueux":["french"],"bougie":["french"],"boulon":["french"],"bouquin":["french"],"bourse":["french"],"boussole":["french"],"boutique":["french"],"boxeur":["french"],"branche":["french"],"brasier":["french"],"brebis":["french"],"brèche":["french"],"breuvage":["french"],"bricoler":["french"],"brigade":["french"],"brillant":["french"],"brioche":["french"],"brique":["french"],"brochure":["french"],"broder":["french"],"bronzer":["french"],"brousse":["french"],"broyeur":["french"],"brume":["french"],"brusque":["french"],"brutal":["french"],"bruyant":["french"],"buffle":["french"],"buisson":["french"],"bulletin":["french"],"bureau":["french"],"burin":["french"],"bustier":["french"],"butiner":["french"],"butoir":["french"],"buvable":["french"],"buvette":["french"],"cabanon":["french"],"cabine":["french"],"cachette":["french"],"cadeau":["french"],"cadre":["french"],"caféine":["french"],"caillou":["french"],"caisson":["french"],"calculer":["french"],"calepin":["french"],"calibre":["french"],"calmer":["french"],"calomnie":["french"],"calvaire":["french"],"camarade":["french"],"caméra":["french"],"camion":["french"],"campagne":["french"],"caneton":["french"],"canon":["french"],"cantine":["french"],"canular":["french"],"caporal":["french"],"caprice":["french"],"capsule":["french"],"capter":["french"],"capuche":["french"],"carabine":["french"],"carbone":["french"],"caresser":["french"],"caribou":["french"],"carnage":["french"],"carotte":["french"],"carreau":["french"],"carton":["french"],"cascade":["french"],"casier":["french"],"casque":["french"],"cassure":["french"],"causer":["french"],"cavalier":["french"],"caverne":["french"],"caviar":["french"],"cédille":["french"],"ceinture":["french"],"céleste":["french"],"cellule":["french"],"cendrier":["french"],"censurer":["french"],"central":["french"],"cercle":["french"],"cérébral":["french"],"cerise":["french"],"cerner":["french"],"cerveau":["french"],"cesser":["french"],"chagrin":["french"],"chaise":["french"],"chaleur":["french"],"chambre":["french"],"chance":["french"],"chapitre":["french"],"charbon":["french"],"chasseur":["french"],"chaton":["french"],"chausson":["french"],"chavirer":["french"],"chemise":["french"],"chenille":["french"],"chéquier":["french"],"chercher":["french"],"cheval":["french"],"chien":["french"],"chiffre":["french"],"chignon":["french"],"chimère":["french"],"chiot":["french"],"chlorure":["french"],"chocolat":["french"],"choisir":["french"],"chose":["french"],"chouette":["french"],"chrome":["french"],"chute":["french"],"cigare":["french"],"cigogne":["french"],"cimenter":["french"],"cinéma":["french"],"cintrer":["french"],"circuler":["french"],"cirer":["french"],"cirque":["french"],"citerne":["french"],"citoyen":["french"],"citron":["french"],"clairon":["french"],"clameur":["french"],"claquer":["french"],"classe":["french"],"clavier":["french"],"cligner":["french"],"climat":["french"],"clivage":["french"],"cloche":["french"],"clonage":["french"],"cloporte":["french"],"cobalt":["french"],"cobra":["french"],"cocasse":["french"],"cocotier":["french"],"coder":["french"],"codifier":["french"],"coffre":["french"],"cogner":["french"],"cohésion":["french"],"coiffer":["french"],"coincer":["french"],"colère":["french"],"colibri":["french"],"colline":["french"],"colmater":["french"],"colonel":["french"],"combat":["french"],"comédie":["french"],"commande":["french"],"compact":["french"],"conduire":["french"],"confier":["french"],"congeler":["french"],"connoter":["french"],"consonne":["french"],"contact":["french"],"convexe":["french"],"copain":["french"],"copie":["french"],"corail":["french"],"corbeau":["french"],"cordage":["french"],"corniche":["french"],"corpus":["french"],"cortège":["french"],"cosmique":["french"],"costume":["french"],"coton":["french"],"coude":["french"],"coupure":["french"],"courage":["french"],"couteau":["french"],"couvrir":["french"],"crabe":["french"],"crainte":["french"],"cravate":["french"],"crayon":["french"],"créature":["french"],"créditer":["french"],"crémeux":["french"],"creuser":["french"],"crevette":["french"],"cribler":["french"],"crier":["french"],"cristal":["french"],"critère":["french"],"croire":["french"],"croquer":["french"],"crotale":["french"],"crypter":["french"],"cubique":["french"],"cueillir":["french"],"cuillère":["french"],"cuisine":["french"],"cuivre":["french"],"culminer":["french"],"cultiver":["french"],"cumuler":["french"],"cupide":["french"],"curatif":["french"],"curseur":["french"],"cyanure":["french"],"cylindre":["french"],"cynique":["french"],"daigner":["french"],"damier":["french"],"danseur":["french"],"dauphin":["french"],"débattre":["french"],"débiter":["french"],"déborder":["french"],"débrider":["french"],"débutant":["french"],"décaler":["french"],"décembre":["french"],"déchirer":["french"],"décider":["french"],"déclarer":["french"],"décorer":["french"],"décrire":["french"],"décupler":["french"],"dédale":["french"],"déductif":["french"],"déesse":["french"],"défensif":["french"],"défiler":["french"],"défrayer":["french"],"dégager":["french"],"dégivrer":["french"],"déglutir":["french"],"dégrafer":["french"],"déjeuner":["french"],"délice":["french"],"déloger":["french"],"demander":["french"],"demeurer":["french"],"démolir":["french"],"dénicher":["french"],"dénouer":["french"],"dentelle":["french"],"dénuder":["french"],"départ":["french"],"dépenser":["french"],"déphaser":["french"],"déplacer":["french"],"déposer":["french"],"déranger":["french"],"dérober":["french"],"désastre":["french"],"descente":["french"],"désert":["french"],"désigner":["french"],"désobéir":["french"],"dessiner":["french"],"destrier":["french"],"détacher":["french"],"détester":["french"],"détourer":["french"],"détresse":["french"],"devancer":["french"],"devenir":["french"],"deviner":["french"],"devoir":["french"],"diable":["french"],"dialogue":["french"],"diamant":["french"],"dicter":["french"],"différer":["french"],"digérer":["french"],"digne":["french"],"diluer":["french"],"dimanche":["french"],"diminuer":["french"],"dioxyde":["french"],"directif":["french"],"diriger":["french"],"discuter":["french"],"disposer":["french"],"dissiper":["french"],"divertir":["french"],"diviser":["french"],"docile":["french"],"docteur":["french"],"dogme":["french"],"doigt":["french"],"domaine":["french"],"domicile":["french"],"dompter":["french"],"donateur":["french"],"donjon":["french"],"donner":["french"],"dopamine":["french"],"dortoir":["french"],"dorure":["french"],"dosage":["french"],"doseur":["french"],"dossier":["french"],"dotation":["french"],"douanier":["french"],"douceur":["french"],"douter":["french"],"doyen":["french"],"draper":["french"],"dresser":["french"],"dribbler":["french"],"droiture":["french"],"duperie":["french"],"duplexe":["french"],"durable":["french"],"durcir":["french"],"dynastie":["french"],"éblouir":["french"],"écarter":["french"],"écharpe":["french"],"échelle":["french"],"éclairer":["french"],"éclipse":["french"],"éclore":["french"],"écluse":["french"],"école":["french"],"économie":["french"],"écorce":["french"],"écouter":["french"],"écraser":["french"],"écrémer":["french"],"écrivain":["french"],"écrou":["french"],"écume":["french"],"écureuil":["french"],"édifier":["french"],"éduquer":["french"],"effacer":["french"],"effectif":["french"],"effigie":["french"],"effrayer":["french"],"effusion":["french"],"égaliser":["french"],"égarer":["french"],"éjecter":["french"],"élaborer":["french"],"élargir":["french"],"électron":["french"],"élégant":["french"],"éléphant":["french"],"élève":["french"],"éligible":["french"],"élitisme":["french"],"éloge":["french"],"élucider":["french"],"éluder":["french"],"emballer":["french"],"embellir":["french"],"embryon":["french"],"émeraude":["french"],"émission":["french"],"emmener":["french"],"émotion":["french"],"émouvoir":["french"],"empereur":["french"],"employer":["french"],"emporter":["french"],"emprise":["french"],"émulsion":["french"],"encadrer":["french"],"enchère":["french"],"enclave":["french"],"encoche":["french"],"endiguer":["french"],"endosser":["french"],"endroit":["french"],"enduire":["french"],"énergie":["french"],"enfance":["french"],"enfermer":["french"],"enfouir":["french"],"engager":["french"],"engin":["french","turkish"],"englober":["french"],"énigme":["french"],"enjamber":["french"],"enjeu":["french"],"enlever":["french"],"ennemi":["french"],"ennuyeux":["french"],"enrichir":["french"],"enrobage":["french"],"enseigne":["french"],"entasser":["french"],"entendre":["french"],"entier":["french"],"entourer":["french"],"entraver":["french"],"énumérer":["french"],"envahir":["french"],"enviable":["french"],"envoyer":["french"],"enzyme":["french"],"éolien":["french"],"épaissir":["french"],"épargne":["french"],"épatant":["french"],"épaule":["french"],"épicerie":["french"],"épidémie":["french"],"épier":["french"],"épilogue":["french"],"épine":["french"],"épisode":["french"],"épitaphe":["french"],"époque":["french"],"épreuve":["french"],"éprouver":["french"],"épuisant":["french"],"équerre":["french"],"équipe":["french"],"ériger":["french"],"érosion":["french"],"erreur":["french"],"éruption":["french"],"escalier":["french"],"espadon":["french"],"espèce":["french"],"espiègle":["french"],"espoir":["french"],"esprit":["french"],"esquiver":["french"],"essayer":["french"],"essieu":["french"],"essorer":["french"],"estime":["french"],"estomac":["french"],"estrade":["french"],"étagère":["french"],"étaler":["french"],"étanche":["french"],"étatique":["french"],"éteindre":["french"],"étendoir":["french"],"éternel":["french"],"éthanol":["french"],"éthique":["french"],"ethnie":["french"],"étirer":["french"],"étoffer":["french"],"étoile":["french"],"étonnant":["french"],"étourdir":["french"],"étrange":["french"],"étroit":["french"],"étude":["french"],"euphorie":["french"],"évaluer":["french"],"évasion":["french"],"éventail":["french"],"évidence":["french"],"éviter":["french"],"évolutif":["french"],"évoquer":["french"],"exagérer":["french"],"exaucer":["french"],"exceller":["french"],"excitant":["french"],"exclusif":["french"],"exécuter":["french"],"exemple":["french"],"exercer":["french"],"exhaler":["french"],"exhorter":["french"],"exigence":["french"],"exiler":["french"],"exister":["french"],"exotique":["french"],"expédier":["french"],"explorer":["french"],"exposer":["french"],"exprimer":["french"],"exquis":["french"],"extensif":["french"],"extraire":["french"],"exulter":["french"],"fable":["french"],"fabuleux":["french"],"facette":["french"],"facile":["french"],"facture":["french"],"faiblir":["french"],"falaise":["french"],"fameux":["french"],"famille":["french"],"farceur":["french"],"farfelu":["french"],"farine":["french"],"farouche":["french"],"fasciner":["french"],"faucon":["french"],"fautif":["french"],"faveur":["french"],"favori":["french","turkish"],"fébrile":["french"],"féconder":["french"],"fédérer":["french"],"félin":["french"],"femme":["french"],"fémur":["french"],"fendoir":["french"],"féodal":["french"],"fermer":["french"],"féroce":["french"],"ferveur":["french"],"feuille":["french"],"feutre":["french"],"février":["french"],"fiasco":["french"],"ficeler":["french"],"fictif":["french"],"fidèle":["french"],"filature":["french"],"filetage":["french"],"filière":["french"],"filleul":["french"],"filmer":["french"],"filou":["french"],"filtrer":["french"],"financer":["french"],"finir":["french"],"fiole":["french"],"firme":["french"],"fissure":["french"],"fixer":["french"],"flairer":["french"],"flamme":["french"],"flasque":["french"],"flatteur":["french"],"fléau":["french"],"flèche":["french"],"fleur":["french"],"flexion":["french"],"flocon":["french"],"flore":["french"],"fluctuer":["french"],"fluide":["french"],"fluvial":["french"],"folie":["french"],"fonderie":["french"],"fongible":["french"],"fontaine":["french"],"forcer":["french"],"forgeron":["french"],"formuler":["french"],"fossile":["french"],"foudre":["french"],"fougère":["french"],"fouiller":["french"],"foulure":["french"],"fourmi":["french"],"fraise":["french"],"franchir":["french"],"frapper":["french"],"frayeur":["french"],"frégate":["french"],"freiner":["french"],"frelon":["french"],"frémir":["french"],"frénésie":["french"],"frère":["french"],"friable":["french"],"friction":["french"],"frisson":["french"],"frivole":["french"],"froid":["french"],"fromage":["french"],"frontal":["french"],"frotter":["french"],"fugitif":["french"],"fuite":["french"],"fureur":["french"],"furieux":["french"],"furtif":["french"],"fusion":["french"],"futur":["french"],"gagner":["french"],"galaxie":["french"],"galerie":["french"],"gambader":["french"],"garantir":["french"],"gardien":["french"],"garnir":["french"],"garrigue":["french"],"gazelle":["french"],"gazon":["french"],"géant":["french"],"gélatine":["french"],"gélule":["french"],"gendarme":["french"],"général":["french"],"génie":["french"],"genou":["french"],"gentil":["french"],"géologie":["french"],"géomètre":["french"],"géranium":["french"],"germe":["french"],"gestuel":["french"],"geyser":["french"],"gibier":["french"],"gicler":["french"],"girafe":["french"],"givre":["french"],"glace":["french"],"glaive":["french"],"glisser":["french"],"gloire":["french"],"glorieux":["french"],"golfeur":["french"],"gomme":["french"],"gonfler":["french"],"gorge":["french"],"gorille":["french"],"goudron":["french"],"gouffre":["french"],"goulot":["french"],"goupille":["french"],"gourmand":["french"],"goutte":["french"],"graduel":["french"],"graffiti":["french"],"graine":["french"],"grand":["french"],"grappin":["french"],"gratuit":["french"],"gravir":["french"],"grenat":["french"],"griffure":["french"],"griller":["french"],"grimper":["french"],"grogner":["french"],"gronder":["french"],"grotte":["french"],"groupe":["french"],"gruger":["french"],"grutier":["french"],"gruyère":["french"],"guépard":["french"],"guerrier":["french"],"guimauve":["french"],"guitare":["french"],"gustatif":["french"],"gymnaste":["french"],"gyrostat":["french"],"habitude":["french"],"hachoir":["french"],"halte":["french"],"hameau":["french"],"hangar":["french","turkish"],"hanneton":["french"],"haricot":["french"],"harmonie":["french"],"harpon":["french"],"hasard":["french"],"hélium":["french"],"hématome":["french"],"herbe":["french"],"hérisson":["french"],"hermine":["french"],"héron":["french"],"hésiter":["french"],"heureux":["french"],"hiberner":["french"],"hibou":["french"],"hilarant":["french"],"histoire":["french"],"hiver":["french"],"homard":["french"],"hommage":["french"],"homogène":["french"],"honneur":["french"],"honorer":["french"],"honteux":["french"],"horde":["french"],"horizon":["french"],"horloge":["french"],"hormone":["french"],"horrible":["french"],"houleux":["french"],"housse":["french"],"hublot":["french"],"huileux":["french"],"humain":["french"],"humide":["french"],"humour":["french"],"hurler":["french"],"hydromel":["french"],"hygiène":["french"],"hymne":["french"],"hypnose":["french"],"idylle":["french"],"ignorer":["french"],"iguane":["french"],"illicite":["french"],"illusion":["french"],"imbiber":["french"],"imiter":["french"],"immobile":["french"],"immuable":["french"],"impérial":["french"],"implorer":["french"],"imposer":["french"],"imprimer":["french"],"imputer":["french"],"incarner":["french"],"incendie":["french"],"incident":["french"],"incliner":["french"],"incolore":["french"],"indexer":["french"],"indice":["french"],"inductif":["french"],"inédit":["french"],"ineptie":["french"],"inexact":["french"],"infini":["french"],"infliger":["french"],"informer":["french"],"infusion":["french"],"ingérer":["french"],"inhaler":["french"],"inhiber":["french"],"injecter":["french"],"injure":["french"],"inoculer":["french"],"inonder":["french"],"inscrire":["french"],"insecte":["french"],"insigne":["french"],"insolite":["french"],"inspirer":["french"],"instinct":["french"],"insulter":["french"],"intense":["french"],"intime":["french"],"intrigue":["french"],"intuitif":["french"],"inutile":["french"],"invasion":["french"],"inventer":["french"],"inviter":["french"],"invoquer":["french"],"ironique":["french"],"irradier":["french"],"irréel":["french"],"irriter":["french"],"isoler":["french"],"ivoire":["french"],"ivresse":["french"],"jaillir":["french"],"jambe":["french"],"janvier":["french"],"jardin":["french"],"jauger":["french"],"jaune":["french"],"javelot":["french"],"jetable":["french"],"jeton":["french"],"jeudi":["french"],"jeunesse":["french"],"joindre":["french"],"joncher":["french"],"jongler":["french"],"joueur":["french"],"jouissif":["french"],"journal":["french"],"jovial":["french"],"joyau":["french"],"joyeux":["french"],"jubiler":["french"],"jugement":["french"],"jupon":["french"],"juriste":["french"],"justice":["french"],"juteux":["french"],"juvénile":["french"],"kayak":["french"],"kimono":["french"],"kiosque":["french"],"labial":["french"],"labourer":["french"],"lacérer":["french"],"lactose":["french"],"lagune":["french"],"laine":["french"],"laisser":["french"],"laitier":["french"],"lambeau":["french"],"lamelle":["french"],"lampe":["french"],"lanceur":["french"],"langage":["french"],"lanterne":["french"],"lapin":["french"],"largeur":["french"],"larme":["french"],"laurier":["french"],"lavabo":["french"],"lavoir":["french"],"légal":["french"],"léger":["french"],"légume":["french"],"lessive":["french"],"lettre":["french"],"levier":["french"],"lexique":["french"],"lézard":["french"],"liasse":["french"],"libérer":["french"],"libre":["french"],"licence":["french"],"licorne":["french"],"liège":["french"],"lièvre":["french"],"ligature":["french"],"ligoter":["french"],"ligue":["french"],"limer":["french"],"limite":["french"],"limonade":["french"],"limpide":["french"],"linéaire":["french"],"lingot":["french"],"lionceau":["french"],"liquide":["french"],"lisière":["french"],"lister":["french"],"lithium":["french"],"litige":["french"],"littoral":["french"],"livreur":["french"],"logique":["french"],"lointain":["french"],"loisir":["french"],"lombric":["french"],"loterie":["french"],"louer":["french"],"lourd":["french"],"loutre":["french"],"louve":["french"],"lubie":["french"],"lucide":["french"],"lucratif":["french"],"lueur":["french"],"lugubre":["french"],"luisant":["french"],"lumière":["french"],"lunaire":["french"],"lundi":["french"],"luron":["french"],"lutter":["french"],"luxueux":["french"],"magasin":["french"],"magenta":["french"],"magique":["french"],"maigre":["french"],"maillon":["french"],"maintien":["french"],"mairie":["french"],"maison":["french"],"majorer":["french"],"malaxer":["french"],"maléfice":["french"],"malheur":["french"],"malice":["french"],"mallette":["french"],"mammouth":["french"],"mandater":["french"],"maniable":["french"],"manquant":["french"],"manteau":["french"],"manuel":["french"],"marathon":["french"],"marbre":["french"],"marchand":["french"],"mardi":["french"],"maritime":["french"],"marqueur":["french"],"marron":["french"],"marteler":["french"],"mascotte":["french"],"massif":["french"],"matériel":["french"],"matière":["french"],"matraque":["french"],"maudire":["french"],"maussade":["french"],"mauve":["french"],"maximal":["french"],"méchant":["french"],"méconnu":["french"],"médaille":["french"],"médecin":["french"],"méditer":["french"],"méduse":["french"],"meilleur":["french"],"mélange":["french"],"mélodie":["french"],"membre":["french"],"mémoire":["french"],"menacer":["french"],"mener":["french"],"menhir":["french"],"mensonge":["french"],"mentor":["french"],"mercredi":["french"],"mérite":["french"],"merle":["french"],"messager":["french"],"mesure":["french"],"métal":["french"],"météore":["french"],"méthode":["french"],"métier":["french"],"meuble":["french"],"miauler":["french"],"microbe":["french"],"miette":["french"],"mignon":["french"],"migrer":["french"],"milieu":["french"],"mimique":["french"],"mince":["french"],"minéral":["french"],"minimal":["french"],"minorer":["french"],"miroiter":["french"],"missile":["french"],"mixte":["french"],"moderne":["french"],"moelleux":["french"],"mondial":["french"],"moniteur":["french"],"monnaie":["french"],"monotone":["french"],"monstre":["french"],"montagne":["french"],"monument":["french"],"moqueur":["french"],"morceau":["french"],"morsure":["french"],"mortier":["french"],"moteur":["french"],"motif":["french"],"mouche":["french"],"moufle":["french"],"moulin":["french"],"mousson":["french"],"mouton":["french"],"mouvant":["french"],"multiple":["french"],"munition":["french"],"muraille":["french"],"murène":["french"],"murmure":["french"],"muséum":["french"],"musicien":["french"],"mutation":["french"],"muter":["french"],"mutuel":["french"],"myriade":["french"],"myrtille":["french"],"mystère":["french"],"mythique":["french"],"nageur":["french"],"nappe":["french"],"narquois":["french"],"narrer":["french"],"natation":["french"],"naufrage":["french"],"nautique":["french"],"navire":["french"],"nébuleux":["french"],"nectar":["french"],"néfaste":["french"],"négation":["french"],"négliger":["french"],"négocier":["french"],"neige":["french"],"nerveux":["french"],"nettoyer":["french"],"neurone":["french"],"neutron":["french"],"neveu":["french"],"niche":["french"],"nickel":["french"],"nitrate":["french"],"niveau":["french"],"nocif":["french"],"nocturne":["french"],"noirceur":["french"],"noisette":["french"],"nomade":["french"],"nombreux":["french"],"nommer":["french"],"normatif":["french"],"notifier":["french"],"notoire":["french"],"nourrir":["french"],"nouveau":["french"],"novateur":["french"],"novembre":["french"],"novice":["french"],"nuage":["french"],"nuancer":["french"],"nuire":["french"],"nuisible":["french"],"numéro":["french"],"nuptial":["french"],"nuque":["french"],"nutritif":["french"],"obéir":["french"],"objectif":["french"],"obliger":["french"],"obscur":["french"],"observer":["french"],"obstacle":["french"],"obtenir":["french"],"obturer":["french"],"occasion":["french"],"occuper":["french"],"océan":["french"],"octobre":["french"],"octroyer":["french"],"octupler":["french"],"oculaire":["french"],"odeur":["french"],"odorant":["french"],"offenser":["french"],"officier":["french"],"offrir":["french"],"ogive":["french"],"oiseau":["french"],"oisillon":["french"],"olfactif":["french"],"olivier":["french"],"ombrage":["french"],"omettre":["french"],"onctueux":["french"],"onduler":["french"],"onéreux":["french"],"onirique":["french"],"opale":["french"],"opaque":["french"],"opérer":["french"],"opportun":["french"],"opprimer":["french"],"opter":["french"],"optique":["french"],"orageux":["french"],"orbite":["french"],"ordonner":["french"],"oreille":["french"],"organe":["french"],"orgueil":["french"],"orifice":["french"],"ornement":["french"],"orque":["french"],"ortie":["french"],"osciller":["french"],"osmose":["french"],"ossature":["french"],"otarie":["french"],"ouragan":["french"],"ourson":["french"],"outil":["french"],"outrager":["french"],"ouvrage":["french"],"ovation":["french"],"oxyde":["french"],"oxygène":["french"],"paisible":["french"],"palmarès":["french"],"palourde":["french"],"palper":["french"],"panache":["french"],"pangolin":["french"],"paniquer":["french"],"panneau":["french"],"panorama":["french"],"pantalon":["french"],"papaye":["french"],"papier":["french"],"papoter":["french"],"papyrus":["french"],"paradoxe":["french"],"parcelle":["french"],"paresse":["french"],"parfumer":["french"],"parler":["french"],"parole":["french"],"parrain":["french"],"parsemer":["french"],"partager":["french"],"parure":["french"],"parvenir":["french"],"passion":["french"],"pastèque":["french"],"paternel":["french"],"patience":["french"],"patron":["french","turkish"],"pavillon":["french"],"pavoiser":["french"],"payer":["french"],"paysage":["french"],"peigne":["french"],"peintre":["french"],"pelage":["french"],"pélican":["french"],"pelle":["french"],"pelouse":["french"],"peluche":["french"],"pendule":["french"],"pénétrer":["french"],"pénible":["french"],"pensif":["french"],"pénurie":["french"],"pépite":["french"],"péplum":["french"],"perdrix":["french"],"perforer":["french"],"période":["french"],"permuter":["french"],"perplexe":["french"],"persil":["french"],"perte":["french"],"peser":["french"],"pétale":["french"],"petit":["french"],"pétrir":["french"],"peuple":["french"],"pharaon":["french"],"phobie":["french"],"phoque":["french"],"photon":["french"],"physique":["french"],"pictural":["french"],"pièce":["french"],"pierre":["french"],"pieuvre":["french"],"pilote":["french"],"pinceau":["french"],"pipette":["french"],"piquer":["french"],"pirogue":["french"],"piscine":["french"],"piston":["french"],"pivoter":["french"],"pixel":["french"],"placard":["french"],"plafond":["french"],"plaisir":["french"],"planer":["french"],"plaque":["french"],"plastron":["french"],"plateau":["french"],"pleurer":["french"],"plexus":["french"],"pliage":["french"],"plomb":["french"],"plonger":["french"],"pluie":["french"],"plumage":["french"],"pochette":["french"],"poésie":["french"],"poète":["french"],"pointe":["french"],"poirier":["french"],"poisson":["french"],"poivre":["french"],"polaire":["french"],"policier":["french"],"pollen":["french"],"polygone":["french"],"pommade":["french"],"pompier":["french"],"ponctuel":["french"],"pondérer":["french"],"poney":["french"],"portique":["french"],"posséder":["french"],"posture":["french"],"potager":["french"],"poteau":["french"],"potion":["french"],"pouce":["french"],"poulain":["french"],"poumon":["french"],"pourpre":["french"],"poussin":["french"],"pouvoir":["french"],"prairie":["french"],"pratique":["french"],"précieux":["french"],"prédire":["french"],"préfixe":["french"],"prélude":["french"],"prénom":["french"],"présence":["french"],"prétexte":["french"],"prévoir":["french"],"primitif":["french"],"prince":["french"],"priver":["french"],"problème":["french"],"procéder":["french"],"prodige":["french"],"profond":["french"],"progrès":["french"],"proie":["french"],"projeter":["french"],"prologue":["french"],"promener":["french"],"propre":["french"],"prospère":["french"],"protéger":["french"],"prouesse":["french"],"proverbe":["french"],"prudence":["french"],"pruneau":["french"],"psychose":["french"],"puceron":["french"],"puiser":["french"],"pulpe":["french"],"pulsar":["french"],"punaise":["french"],"punitif":["french"],"pupitre":["french"],"purifier":["french"],"pyramide":["french"],"quasar":["french"],"querelle":["french"],"quiétude":["french"],"quitter":["french"],"quotient":["french"],"racine":["french"],"raconter":["french"],"radieux":["french"],"ragondin":["french"],"raideur":["french"],"raisin":["french"],"ralentir":["french"],"rallonge":["french"],"ramasser":["french"],"rapide":["french"],"rasage":["french"],"ratisser":["french"],"ravager":["french"],"ravin":["french"],"rayonner":["french"],"réactif":["french"],"réagir":["french"],"réaliser":["french"],"réanimer":["french"],"recevoir":["french"],"réciter":["french"],"réclamer":["french"],"récolter":["french"],"recruter":["french"],"reculer":["french"],"recycler":["french"],"rédiger":["french"],"redouter":["french"],"refaire":["french"],"réflexe":["french"],"réformer":["french"],"refrain":["french"],"refuge":["french"],"régalien":["french"],"région":["french"],"réglage":["french"],"régulier":["french"],"réitérer":["french"],"rejeter":["french"],"rejouer":["french"],"relatif":["french"],"relever":["french"],"remarque":["french"],"remède":["french"],"remise":["french"],"remonter":["french"],"remplir":["french"],"remuer":["french"],"renard":["french"],"renfort":["french"],"renifler":["french"],"renoncer":["french"],"rentrer":["french"],"renvoi":["french"],"replier":["french"],"reporter":["french"],"reprise":["french"],"reptile":["french"],"requin":["french"],"réserve":["french"],"résineux":["french"],"résoudre":["french"],"respect":["french"],"rester":["french"],"résultat":["french"],"rétablir":["french"],"retenir":["french"],"réticule":["french"],"retomber":["french"],"retracer":["french"],"réunion":["french"],"réussir":["french"],"revanche":["french"],"revivre":["french"],"révolte":["french"],"révulsif":["french"],"richesse":["french"],"rideau":["french"],"rieur":["french"],"rigide":["french"],"rigoler":["french"],"rincer":["french"],"riposter":["french"],"risible":["french"],"risque":["french"],"rituel":["french"],"rivière":["french"],"rocheux":["french"],"rompre":["french"],"ronce":["french"],"rondin":["french"],"roseau":["french"],"rosier":["french"],"rotatif":["french"],"rotor":["french"],"rotule":["french"],"rouge":["french"],"rouille":["french"],"rouleau":["french"],"routine":["french"],"royaume":["french"],"ruban":["french"],"rubis":["french"],"ruche":["french"],"ruelle":["french"],"rugueux":["french"],"ruiner":["french"],"ruisseau":["french"],"ruser":["french"],"rustique":["french"],"rythme":["french"],"sabler":["french"],"saboter":["french"],"sabre":["french"],"sacoche":["french"],"safari":["french"],"sagesse":["french"],"saisir":["french"],"salade":["french"],"salive":["french"],"saluer":["french"],"samedi":["french"],"sanction":["french"],"sanglier":["french"],"sarcasme":["french"],"sardine":["french"],"saturer":["french"],"saugrenu":["french"],"saumon":["french"],"sauter":["french"],"sauvage":["french"],"savant":["french"],"savonner":["french"],"scalpel":["french"],"scandale":["french"],"scélérat":["french"],"scénario":["french"],"sceptre":["french"],"schéma":["french"],"scinder":["french"],"score":["french"],"scrutin":["french"],"sculpter":["french"],"séance":["french"],"sécable":["french"],"sécher":["french"],"secouer":["french"],"sécréter":["french"],"sédatif":["french"],"séduire":["french"],"seigneur":["french"],"séjour":["french"],"sélectif":["french"],"semaine":["french"],"sembler":["french"],"semence":["french"],"séminal":["french"],"sénateur":["french"],"sensible":["french"],"séparer":["french"],"séquence":["french"],"serein":["french"],"sergent":["french"],"sérieux":["french"],"serrure":["french"],"sérum":["french"],"sésame":["french"],"sévir":["french"],"sevrage":["french"],"sextuple":["french"],"sidéral":["french"],"siècle":["french"],"siéger":["french"],"siffler":["french"],"sigle":["french"],"signal":["french"],"silence":["french"],"silicium":["french"],"sincère":["french"],"sinistre":["french"],"siphon":["french"],"sirop":["french"],"sismique":["french"],"situer":["french"],"skier":["french"],"socle":["french"],"sodium":["french"],"soigneux":["french"],"soldat":["french"],"soleil":["french"],"solitude":["french"],"soluble":["french"],"sombre":["french"],"sommeil":["french"],"somnoler":["french"],"sonde":["french"],"songeur":["french"],"sonnette":["french"],"sonore":["french"],"sorcier":["french"],"sortir":["french"],"sosie":["french"],"sottise":["french"],"soucieux":["french"],"soudure":["french"],"souffle":["french"],"soulever":["french"],"soupape":["french"],"soutirer":["french"],"souvenir":["french"],"spacieux":["french"],"spécial":["french"],"sphère":["french"],"spiral":["french","turkish"],"station":["french"],"sternum":["french"],"stimulus":["french"],"stipuler":["french"],"strict":["french"],"studieux":["french"],"stupeur":["french"],"styliste":["french"],"sublime":["french"],"substrat":["french"],"subtil":["french"],"subvenir":["french"],"succès":["french"],"sucre":["french"],"suffixe":["french"],"suggérer":["french"],"suiveur":["french"],"sulfate":["french"],"superbe":["french"],"supplier":["french"],"suricate":["french"],"surmener":["french"],"sursaut":["french"],"survie":["french"],"syllabe":["french"],"symbole":["french"],"symétrie":["french"],"synapse":["french"],"syntaxe":["french"],"système":["french"],"tabac":["french"],"tablier":["french"],"tactile":["french"],"tailler":["french"],"talisman":["french"],"talonner":["french"],"tambour":["french"],"tamiser":["french"],"tangible":["french"],"tapis":["french"],"taquiner":["french"],"tarder":["french"],"tarif":["french"],"tartine":["french"],"tasse":["french"],"tatami":["french"],"tatouage":["french"],"taupe":["french"],"taureau":["french"],"taxer":["french"],"témoin":["french"],"temporel":["french"],"tenaille":["french"],"tendre":["french"],"teneur":["french"],"tenir":["french"],"tension":["french"],"terminer":["french"],"terne":["french"],"terrible":["french"],"tétine":["french"],"texte":["french"],"thème":["french"],"théorie":["french"],"thérapie":["french"],"thorax":["french"],"tibia":["french"],"tiède":["french"],"timide":["french"],"tirelire":["french"],"tiroir":["french"],"tissu":["french"],"titane":["french"],"titre":["french"],"tituber":["french"],"toboggan":["french"],"tolérant":["french"],"tomate":["french"],"tonique":["french"],"tonneau":["french"],"toponyme":["french"],"torche":["french"],"tordre":["french"],"tornade":["french"],"torpille":["french"],"torrent":["french"],"torse":["french"],"tortue":["french"],"totem":["french"],"toucher":["french"],"tournage":["french"],"tousser":["french"],"toxine":["french"],"traction":["french"],"trafic":["french"],"tragique":["french"],"trahir":["french"],"trancher":["french"],"travail":["french"],"trèfle":["french"],"tremper":["french"],"trésor":["french"],"treuil":["french"],"triage":["french"],"tribunal":["french"],"tricoter":["french"],"trilogie":["french"],"triomphe":["french"],"tripler":["french"],"triturer":["french"],"trivial":["french"],"trombone":["french"],"tronc":["french"],"tropical":["french"],"troupeau":["french"],"tuile":["french"],"tulipe":["french"],"tumulte":["french"],"turbine":["french"],"tuteur":["french"],"tutoyer":["french"],"tuyau":["french"],"tympan":["french"],"typhon":["french"],"typique":["french"],"tyran":["french"],"ubuesque":["french"],"ultime":["french"],"ultrason":["french"],"unanime":["french"],"unifier":["french"],"union":["french"],"unitaire":["french"],"univers":["french"],"uranium":["french"],"urbain":["french"],"urticant":["french"],"usine":["french"],"usuel":["french"],"usure":["french"],"utile":["french"],"utopie":["french"],"vacarme":["french"],"vaccin":["french"],"vagabond":["french"],"vaillant":["french"],"vaincre":["french"],"vaisseau":["french"],"valable":["french"],"valise":["french"],"vallon":["french"],"vampire":["french"],"vanille":["french"],"vapeur":["french"],"varier":["french"],"vaseux":["french"],"vassal":["french"],"vaste":["french"],"vecteur":["french"],"vedette":["french"],"végétal":["french"],"véhicule":["french"],"veinard":["french"],"véloce":["french"],"vendredi":["french"],"vénérer":["french"],"venger":["french"],"venimeux":["french"],"ventouse":["french"],"verdure":["french"],"vérin":["french"],"vernir":["french"],"verrou":["french"],"verser":["french"],"vertu":["french"],"veston":["french"],"vétéran":["french"],"vétuste":["french"],"vexant":["french"],"vexer":["french"],"viaduc":["french"],"viande":["french"],"victoire":["french"],"vidange":["french"],"vidéo":["french"],"vignette":["french"],"vigueur":["french"],"vilain":["french"],"vinaigre":["french"],"violon":["french"],"vipère":["french"],"virement":["french"],"virtuose":["french"],"visage":["french"],"viseur":["french"],"vision":["french"],"visqueux":["french"],"visuel":["french"],"vitesse":["french"],"viticole":["french"],"vitrine":["french"],"vivace":["french"],"vivipare":["french"],"vocation":["french"],"voguer":["french"],"voile":["french"],"voisin":["french"],"voiture":["french"],"volaille":["french"],"volcan":["french"],"voltiger":["french"],"vorace":["french"],"vortex":["french"],"voter":["french"],"vouloir":["french"],"voyelle":["french"],"xénon":["french"],"yacht":["french"],"zèbre":["french"],"zénith":["french"],"zeste":["french"],"zoologie":["french"],"abaco":["italian"],"abbaglio":["italian"],"abbinato":["italian"],"abete":["italian"],"abisso":["italian"],"abolire":["italian"],"abrasivo":["italian"],"abrogato":["italian"],"accadere":["italian"],"accenno":["italian"],"accusato":["italian"],"acetone":["italian"],"achille":["italian"],"acido":["italian"],"acqua":["italian"],"acre":["italian"],"acrilico":["italian"],"acrobata":["italian"],"acuto":["italian"],"adagio":["italian"],"addebito":["italian"],"addome":["italian"],"adeguato":["italian"],"aderire":["italian"],"adipe":["italian"],"adottare":["italian"],"adulare":["italian"],"affabile":["italian"],"affetto":["italian"],"affisso":["italian"],"affranto":["italian"],"aforisma":["italian"],"afoso":["italian"],"africano":["italian"],"agave":["italian"],"agente":["italian"],"agevole":["italian"],"aggancio":["italian"],"agire":["italian"],"agitare":["italian"],"agonismo":["italian"],"agricolo":["italian"],"agrumeto":["italian"],"aguzzo":["italian"],"alabarda":["italian"],"alato":["italian"],"albatro":["italian"],"alberato":["italian"],"albo":["italian"],"albume":["italian"],"alce":["italian"],"alcolico":["italian"],"alettone":["italian"],"alfa":["italian"],"algebra":["italian"],"aliante":["italian"],"alibi":["italian"],"alimento":["italian"],"allagato":["italian"],"allegro":["italian"],"allievo":["italian"],"allodola":["italian"],"allusivo":["italian"],"almeno":["italian"],"alogeno":["italian"],"alpaca":["italian"],"alpestre":["italian"],"altalena":["italian"],"alterno":["italian"],"alticcio":["italian"],"altrove":["italian"],"alunno":["italian"],"alveolo":["italian"],"alzare":["italian"],"amalgama":["italian"],"amanita":["italian"],"amarena":["italian"],"ambito":["italian"],"ambrato":["italian"],"ameba":["italian"],"america":["italian"],"ametista":["italian"],"amico":["italian"],"ammasso":["italian"],"ammenda":["italian"],"ammirare":["italian"],"ammonito":["italian"],"amore":["italian"],"ampio":["italian"],"ampliare":["italian"],"amuleto":["italian"],"anacardo":["italian"],"anagrafe":["italian"],"analista":["italian"],"anarchia":["italian"],"anatra":["italian"],"anca":["italian"],"ancella":["italian"],"ancora":["italian"],"andare":["italian"],"andrea":["italian"],"anello":["italian"],"angelo":["italian"],"angolare":["italian"],"angusto":["italian"],"anima":["italian"],"annegare":["italian"],"annidato":["italian"],"anno":["italian"],"annuncio":["italian"],"anonimo":["italian"],"anticipo":["italian"],"anzi":["italian"],"apatico":["italian"],"apertura":["italian"],"apode":["italian"],"apparire":["italian"],"appetito":["italian"],"appoggio":["italian"],"approdo":["italian"],"appunto":["italian"],"aprile":["italian"],"arabica":["italian"],"arachide":["italian"],"aragosta":["italian"],"araldica":["italian"],"arancio":["italian"],"aratura":["italian"],"arazzo":["italian"],"arbitro":["italian"],"archivio":["italian"],"ardito":["italian"],"arenile":["italian"],"argento":["italian"],"argine":["italian"],"arguto":["italian"],"aria":["italian"],"armonia":["italian"],"arnese":["italian"],"arredato":["italian"],"arringa":["italian"],"arrosto":["italian"],"arsenico":["italian"],"arso":["italian"],"artefice":["italian"],"arzillo":["italian"],"asciutto":["italian"],"ascolto":["italian"],"asepsi":["italian"],"asettico":["italian"],"asfalto":["italian"],"asino":["italian"],"asola":["italian"],"aspirato":["italian"],"aspro":["italian"],"assaggio":["italian"],"asse":["italian"],"assoluto":["italian"],"assurdo":["italian"],"asta":["italian"],"astenuto":["italian"],"astice":["italian"],"astratto":["italian"],"atavico":["italian"],"ateismo":["italian"],"atomico":["italian"],"atono":["italian"],"attesa":["italian"],"attivare":["italian"],"attorno":["italian"],"attrito":["italian"],"attuale":["italian"],"ausilio":["italian"],"austria":["italian"],"autista":["italian"],"autonomo":["italian"],"autunno":["italian"],"avanzato":["italian"],"avere":["italian"],"avvenire":["italian"],"avviso":["italian"],"avvolgere":["italian"],"azione":["italian"],"azoto":["italian"],"azzimo":["italian"],"azzurro":["italian"],"babele":["italian"],"baccano":["italian"],"bacino":["italian"],"baco":["italian"],"badessa":["italian"],"badilata":["italian"],"bagnato":["italian"],"baita":["italian"],"balcone":["italian"],"baldo":["italian"],"balena":["italian"],"ballata":["italian"],"balzano":["italian"],"bambino":["italian"],"bandire":["italian"],"baraonda":["italian"],"barbaro":["italian"],"barca":["italian"],"baritono":["italian"],"barlume":["italian"],"barocco":["italian"],"basilico":["italian"],"basso":["italian"],"batosta":["italian"],"battuto":["italian"],"baule":["italian"],"bava":["italian"],"bavosa":["italian"],"becco":["italian"],"beffa":["italian"],"belgio":["italian"],"belva":["italian"],"benda":["italian"],"benevole":["italian"],"benigno":["italian"],"benzina":["italian"],"bere":["italian"],"berlina":["italian"],"beta":["italian"],"bibita":["italian"],"bici":["italian"],"bidone":["italian"],"bifido":["italian"],"biga":["italian"],"bilancia":["italian"],"bimbo":["italian"],"binocolo":["italian"],"biologo":["italian"],"bipede":["italian"],"bipolare":["italian"],"birbante":["italian"],"birra":["italian"],"biscotto":["italian"],"bisesto":["italian"],"bisnonno":["italian"],"bisonte":["italian"],"bisturi":["italian"],"bizzarro":["italian"],"blando":["italian"],"blatta":["italian"],"bollito":["italian"],"bonifico":["italian"],"bordo":["italian"],"bosco":["italian"],"botanico":["italian"],"bottino":["italian"],"bozzolo":["italian"],"braccio":["italian"],"bradipo":["italian"],"brama":["italian"],"branca":["italian"],"bravura":["italian"],"bretella":["italian"],"brevetto":["italian"],"brezza":["italian"],"briglia":["italian"],"brillante":["italian"],"brindare":["italian"],"broccolo":["italian"],"brodo":["italian"],"bronzina":["italian"],"brullo":["italian"],"bruno":["italian"],"bubbone":["italian"],"buca":["italian"],"budino":["italian"],"buffone":["italian"],"buio":["italian"],"bulbo":["italian"],"buono":["italian"],"burlone":["italian"],"burrasca":["italian"],"bussola":["italian"],"busta":["italian"],"cadetto":["italian"],"caduco":["italian"],"calamaro":["italian"],"calcolo":["italian"],"calesse":["italian"],"calibro":["italian"],"calmo":["italian"],"caloria":["italian"],"cambusa":["italian"],"camerata":["italian"],"camicia":["italian"],"cammino":["italian"],"camola":["italian"],"campale":["italian"],"canapa":["italian"],"candela":["italian"],"cane":["italian"],"canino":["italian"],"canotto":["italian"],"cantina":["italian"],"capace":["italian"],"capello":["italian"],"capitolo":["italian"],"capogiro":["italian"],"cappero":["italian"],"capra":["italian"],"capsula":["italian"],"carapace":["italian"],"carcassa":["italian"],"cardo":["italian"],"carisma":["italian"],"carovana":["italian"],"carretto":["italian"],"cartolina":["italian"],"casaccio":["italian"],"cascata":["italian"],"caserma":["italian"],"caso":["italian"],"cassone":["italian"],"castello":["italian"],"casuale":["italian"],"catasta":["italian"],"catena":["italian"],"catrame":["italian"],"cauto":["italian"],"cavillo":["italian"],"cedibile":["italian"],"cedrata":["italian"],"cefalo":["italian"],"celebre":["italian"],"cellulare":["italian"],"cena":["italian"],"cenone":["italian"],"centesimo":["italian"],"ceramica":["italian"],"cercare":["italian"],"certo":["italian"],"cerume":["italian"],"cervello":["italian"],"cesoia":["italian"],"cespo":["italian"],"ceto":["italian"],"chela":["italian"],"chiaro":["italian"],"chicca":["italian"],"chiedere":["italian"],"chimera":["italian"],"china":["italian"],"chirurgo":["italian"],"chitarra":["italian"],"ciao":["italian"],"ciclismo":["italian"],"cifrare":["italian"],"cigno":["italian"],"cilindro":["italian"],"ciottolo":["italian"],"circa":["italian"],"cirrosi":["italian"],"citrico":["italian"],"cittadino":["italian"],"ciuffo":["italian"],"civetta":["italian"],"civile":["italian"],"classico":["italian"],"clinica":["italian"],"cloro":["italian"],"cocco":["italian"],"codardo":["italian"],"codice":["italian"],"coerente":["italian"],"cognome":["italian"],"collare":["italian"],"colmato":["italian"],"colore":["italian"],"colposo":["italian"],"coltivato":["italian"],"colza":["italian"],"coma":["italian"],"cometa":["italian"],"commando":["italian"],"comodo":["italian"],"computer":["italian"],"comune":["italian"],"conciso":["italian"],"condurre":["italian"],"conferma":["italian"],"congelare":["italian"],"coniuge":["italian"],"connesso":["italian"],"conoscere":["italian"],"consumo":["italian"],"continuo":["italian"],"convegno":["italian"],"coperto":["italian"],"copione":["italian"],"coppia":["italian"],"copricapo":["italian"],"corazza":["italian"],"cordata":["italian"],"coricato":["italian"],"cornice":["italian"],"corolla":["italian"],"corpo":["italian"],"corredo":["italian"],"corsia":["italian"],"cortese":["italian"],"cosmico":["italian"],"costante":["italian"],"cottura":["italian"],"covato":["italian"],"cratere":["italian"],"cravatta":["italian"],"creato":["italian"],"credere":["italian"],"cremoso":["italian"],"crescita":["italian"],"creta":["italian"],"criceto":["italian"],"crinale":["italian"],"crisi":["italian"],"critico":["italian"],"croce":["italian"],"cronaca":["italian"],"crostata":["italian"],"cruciale":["italian"],"crusca":["italian"],"cucire":["italian"],"cuculo":["italian"],"cugino":["italian"],"cullato":["italian"],"cupola":["italian"],"curatore":["italian"],"cursore":["italian"],"curvo":["italian"],"cuscino":["italian"],"custode":["italian"],"dado":["italian"],"daino":["italian"],"dalmata":["italian"],"damerino":["italian"],"daniela":["italian"],"dannoso":["italian"],"danzare":["italian"],"datato":["italian"],"davanti":["italian"],"davvero":["italian"],"debutto":["italian"],"decennio":["italian"],"deciso":["italian"],"declino":["italian"],"decollo":["italian"],"decreto":["italian"],"dedicato":["italian"],"definito":["italian"],"deforme":["italian"],"degno":["italian"],"delegare":["italian"],"delfino":["italian"],"delirio":["italian"],"delta":["italian"],"demenza":["italian"],"denotato":["italian"],"dentro":["italian"],"deposito":["italian"],"derapata":["italian"],"derivare":["italian"],"deroga":["italian"],"descritto":["italian"],"deserto":["italian"],"desiderio":["italian"],"desumere":["italian"],"detersivo":["italian"],"devoto":["italian"],"diametro":["italian"],"dicembre":["italian"],"diedro":["italian"],"difeso":["italian"],"diffuso":["italian"],"digerire":["italian"],"digitale":["italian"],"diluvio":["italian"],"dinamico":["italian"],"dinnanzi":["italian"],"dipinto":["italian"],"diploma":["italian"],"dipolo":["italian"],"diradare":["italian"],"dire":["italian"],"dirotto":["italian"],"dirupo":["italian"],"disagio":["italian"],"discreto":["italian"],"disfare":["italian"],"disgelo":["italian"],"disposto":["italian"],"distanza":["italian"],"disumano":["italian"],"dito":["italian"],"divano":["italian"],"divelto":["italian"],"dividere":["italian"],"divorato":["italian"],"doblone":["italian"],"docente":["italian"],"doganale":["italian"],"dogma":["italian"],"dolce":["italian"],"domato":["italian"],"domenica":["italian"],"dominare":["italian"],"dondolo":["italian"],"dono":["italian"],"dormire":["italian"],"dote":["italian"],"dottore":["italian"],"dovuto":["italian"],"dozzina":["italian"],"drago":["italian"],"druido":["italian"],"dubbio":["italian"],"dubitare":["italian"],"ducale":["italian"],"duna":["italian"],"duomo":["italian"],"duplice":["italian"],"duraturo":["italian"],"ebano":["italian"],"eccesso":["italian"],"ecco":["italian"],"eclissi":["italian"],"economia":["italian"],"edera":["italian"],"edicola":["italian"],"edile":["italian"],"editoria":["italian"],"educare":["italian"],"egemonia":["italian"],"egli":["italian"],"egoismo":["italian"],"egregio":["italian"],"elaborato":["italian"],"elargire":["italian"],"elegante":["italian"],"elencato":["italian"],"eletto":["italian"],"elevare":["italian"],"elfico":["italian"],"elica":["italian"],"elmo":["italian"],"elsa":["italian"],"eluso":["italian"],"emanato":["italian"],"emblema":["italian"],"emesso":["italian"],"emiro":["italian"],"emotivo":["italian"],"emozione":["italian"],"empirico":["italian"],"emulo":["italian"],"endemico":["italian"],"enduro":["italian"],"energia":["italian"],"enfasi":["italian"],"enoteca":["italian"],"entrare":["italian"],"enzima":["italian"],"epatite":["italian"],"epilogo":["italian"],"episodio":["italian"],"epocale":["italian"],"eppure":["italian"],"equatore":["italian"],"erario":["italian"],"erba":["italian"],"erboso":["italian"],"erede":["italian"],"eremita":["italian"],"erigere":["italian"],"ermetico":["italian"],"eroe":["italian"],"erosivo":["italian"],"errante":["italian"],"esagono":["italian"],"esame":["italian"],"esanime":["italian"],"esaudire":["italian"],"esca":["italian"],"esempio":["italian"],"esercito":["italian"],"esibito":["italian"],"esigente":["italian"],"esistere":["italian"],"esito":["italian"],"esofago":["italian"],"esortato":["italian"],"esoso":["italian"],"espanso":["italian"],"espresso":["italian"],"essenza":["italian"],"esso":["italian"],"esteso":["italian"],"estimare":["italian"],"estonia":["italian"],"estroso":["italian"],"esultare":["italian"],"etilico":["italian"],"etnico":["italian"],"etrusco":["italian"],"etto":["italian"],"euclideo":["italian"],"europa":["italian"],"evaso":["italian"],"evidenza":["italian"],"evitato":["italian"],"evoluto":["italian"],"evviva":["italian"],"fabbrica":["italian"],"faccenda":["italian"],"fachiro":["italian"],"falco":["italian"],"famiglia":["italian"],"fanale":["italian"],"fanfara":["italian"],"fango":["italian"],"fantasma":["italian"],"fare":["italian"],"farfalla":["italian"],"farinoso":["italian"],"farmaco":["italian"],"fascia":["italian"],"fastoso":["italian"],"fasullo":["italian"],"faticare":["italian"],"fato":["italian"],"favoloso":["italian"],"febbre":["italian"],"fecola":["italian"],"fede":["italian"],"fegato":["italian"],"felpa":["italian"],"feltro":["italian"],"femmina":["italian"],"fendere":["italian"],"fenomeno":["italian"],"fermento":["italian"],"ferro":["italian"],"fertile":["italian"],"fessura":["italian"],"festivo":["italian"],"fetta":["italian"],"feudo":["italian"],"fiaba":["italian"],"fiducia":["italian"],"fifa":["italian"],"figurato":["italian"],"filo":["italian","turkish"],"finanza":["italian"],"finestra":["italian"],"finire":["italian"],"fiore":["italian"],"fiscale":["italian"],"fisico":["italian"],"fiume":["italian"],"flacone":["italian"],"flamenco":["italian"],"flebo":["italian"],"flemma":["italian"],"florido":["italian"],"fluente":["italian"],"fluoro":["italian"],"fobico":["italian"],"focaccia":["italian"],"focoso":["italian"],"foderato":["italian"],"foglio":["italian"],"folata":["italian"],"folclore":["italian"],"folgore":["italian"],"fondente":["italian"],"fonetico":["italian"],"fonia":["italian"],"fontana":["italian"],"forbito":["italian"],"forchetta":["italian"],"foresta":["italian"],"formica":["italian"],"fornaio":["italian"],"foro":["italian"],"fortezza":["italian"],"forzare":["italian"],"fosfato":["italian"],"fosso":["italian"],"fracasso":["italian"],"frana":["italian"],"frassino":["italian"],"fratello":["italian"],"freccetta":["italian"],"frenata":["italian"],"fresco":["italian"],"frigo":["italian"],"frollino":["italian"],"fronde":["italian"],"frugale":["italian"],"frutta":["italian"],"fucilata":["italian"],"fucsia":["italian"],"fuggente":["italian"],"fulmine":["italian"],"fulvo":["italian"],"fumante":["italian"],"fumetto":["italian"],"fumoso":["italian"],"fune":["italian"],"funzione":["italian"],"fuoco":["italian"],"furbo":["italian"],"furgone":["italian"],"furore":["italian"],"fuso":["italian"],"futile":["italian"],"gabbiano":["italian"],"gaffe":["italian"],"galateo":["italian"],"gallina":["italian"],"galoppo":["italian"],"gambero":["italian"],"gamma":["italian"],"garanzia":["italian"],"garbo":["italian"],"garofano":["italian"],"garzone":["italian"],"gasdotto":["italian"],"gasolio":["italian"],"gastrico":["italian"],"gatto":["italian"],"gaudio":["italian"],"gazebo":["italian"],"gazzella":["italian"],"geco":["italian"],"gelatina":["italian"],"gelso":["italian"],"gemello":["italian"],"gemmato":["italian"],"gene":["italian"],"genitore":["italian"],"gennaio":["italian"],"genotipo":["italian"],"gergo":["italian"],"ghepardo":["italian"],"ghiaccio":["italian"],"ghisa":["italian"],"giallo":["italian"],"gilda":["italian"],"ginepro":["italian"],"giocare":["italian"],"gioiello":["italian"],"giorno":["italian"],"giove":["italian"],"girato":["italian"],"girone":["italian"],"gittata":["italian"],"giudizio":["italian"],"giurato":["italian"],"giusto":["italian"],"globulo":["italian"],"glutine":["italian"],"gnomo":["italian"],"gobba":["italian"],"golf":["italian"],"gomito":["italian"],"gommone":["italian"],"gonfio":["italian"],"gonna":["italian"],"governo":["italian"],"gracile":["italian"],"grado":["italian"],"grafico":["italian"],"grammo":["italian"],"grande":["italian"],"grattare":["italian"],"gravoso":["italian"],"grazia":["italian"],"greca":["italian"],"gregge":["italian"],"grifone":["italian"],"grigio":["italian"],"grinza":["italian"],"grotta":["italian"],"gruppo":["italian"],"guadagno":["italian"],"guaio":["italian"],"guanto":["italian"],"guardare":["italian"],"gufo":["italian"],"guidare":["italian"],"ibernato":["italian"],"icona":["italian"],"identico":["italian"],"idillio":["italian"],"idolo":["italian"],"idra":["italian"],"idrico":["italian"],"idrogeno":["italian"],"igiene":["italian"],"ignaro":["italian"],"ignorato":["italian"],"ilare":["italian"],"illeso":["italian"],"illogico":["italian"],"illudere":["italian"],"imballo":["italian"],"imbevuto":["italian"],"imbocco":["italian"],"imbuto":["italian"],"immane":["italian"],"immerso":["italian"],"immolato":["italian"],"impacco":["italian"],"impeto":["italian"],"impiego":["italian"],"importo":["italian"],"impronta":["italian"],"inalare":["italian"],"inarcare":["italian"],"inattivo":["italian"],"incanto":["italian"],"incendio":["italian"],"inchino":["italian"],"incisivo":["italian"],"incluso":["italian"],"incontro":["italian"],"incrocio":["italian"],"incubo":["italian"],"indagine":["italian"],"india":["italian"],"indole":["italian"],"inedito":["italian"],"infatti":["italian"],"infilare":["italian"],"inflitto":["italian"],"ingaggio":["italian"],"ingegno":["italian"],"inglese":["italian"],"ingordo":["italian"],"ingrosso":["italian"],"innesco":["italian"],"inodore":["italian"],"inoltrare":["italian"],"inondato":["italian"],"insano":["italian"],"insetto":["italian"],"insieme":["italian"],"insonnia":["italian"],"insulina":["italian"],"intasato":["italian"],"intero":["italian"],"intonaco":["italian"],"intuito":["italian"],"inumidire":["italian"],"invalido":["italian"],"invece":["italian"],"invito":["italian"],"iperbole":["italian"],"ipnotico":["italian"],"ipotesi":["italian"],"ippica":["italian"],"iride":["italian"],"irlanda":["italian"],"ironico":["italian"],"irrigato":["italian"],"irrorare":["italian"],"isolato":["italian"],"isotopo":["italian"],"isterico":["italian"],"istituto":["italian"],"istrice":["italian"],"italia":["italian"],"iterare":["italian"],"labbro":["italian"],"labirinto":["italian"],"lacca":["italian"],"lacerato":["italian"],"lacrima":["italian"],"lacuna":["italian"],"laddove":["italian"],"lago":["italian"],"lampo":["italian"],"lancetta":["italian"],"lanterna":["italian"],"lardoso":["italian"],"larga":["italian"],"laringe":["italian"],"lastra":["italian"],"latenza":["italian"],"latino":["italian"],"lattuga":["italian"],"lavagna":["italian"],"lavoro":["italian"],"legale":["italian"],"leggero":["italian"],"lembo":["italian"],"lentezza":["italian"],"lenza":["italian"],"leone":["italian"],"lepre":["italian"],"lesivo":["italian"],"lessato":["italian"],"lesto":["italian"],"letterale":["italian"],"leva":["italian"],"levigato":["italian"],"libero":["italian"],"lido":["italian"],"lievito":["italian"],"lilla":["italian"],"limatura":["italian"],"limitare":["italian"],"limpido":["italian"],"lineare":["italian"],"lingua":["italian"],"liquido":["italian"],"lira":["italian"],"lirica":["italian"],"lisca":["italian"],"lite":["italian"],"litigio":["italian"],"livrea":["italian"],"locanda":["italian"],"lode":["italian"],"logica":["italian"],"lombare":["italian"],"londra":["italian"],"longevo":["italian"],"loquace":["italian"],"lorenzo":["italian"],"loto":["italian"],"lotteria":["italian"],"luce":["italian"],"lucidato":["italian"],"lumaca":["italian"],"luminoso":["italian"],"lungo":["italian"],"lupo":["italian"],"luppolo":["italian"],"lusinga":["italian"],"lusso":["italian"],"lutto":["italian"],"macabro":["italian"],"macchina":["italian"],"macero":["italian"],"macinato":["italian"],"madama":["italian"],"magico":["italian"],"maglia":["italian"],"magnete":["italian"],"magro":["italian"],"maiolica":["italian"],"malafede":["italian"],"malgrado":["italian"],"malinteso":["italian"],"malsano":["italian"],"malto":["italian"],"malumore":["italian"],"mana":["italian"],"mancia":["italian"],"mandorla":["italian"],"mangiare":["italian"],"manifesto":["italian"],"mannaro":["italian"],"manovra":["italian"],"mansarda":["italian"],"mantide":["italian"],"manubrio":["italian"],"mappa":["italian"],"maratona":["italian"],"marcire":["italian"],"maretta":["italian"],"marmo":["italian"],"marsupio":["italian"],"maschera":["italian"],"massaia":["italian"],"mastino":["italian"],"materasso":["italian"],"matricola":["italian"],"mattone":["italian"],"maturo":["italian"],"mazurca":["italian"],"meandro":["italian"],"meccanico":["italian"],"mecenate":["italian"],"medesimo":["italian"],"meditare":["italian"],"mega":["italian"],"melassa":["italian"],"melis":["italian"],"melodia":["italian"],"meninge":["italian"],"meno":["italian"],"mensola":["italian"],"mercurio":["italian"],"merenda":["italian"],"merlo":["italian"],"meschino":["italian"],"mese":["italian"],"messere":["italian"],"mestolo":["italian"],"metallo":["italian"],"metodo":["italian"],"mettere":["italian"],"miagolare":["italian"],"mica":["italian"],"micelio":["italian"],"michele":["italian"],"microbo":["italian"],"midollo":["italian"],"miele":["italian"],"migliore":["italian"],"milano":["italian"],"milite":["italian"],"mimosa":["italian"],"minerale":["italian"],"mini":["italian"],"minore":["italian"],"mirino":["italian"],"mirtillo":["italian"],"miscela":["italian"],"missiva":["italian"],"misto":["italian"],"misurare":["italian"],"mitezza":["italian"],"mitigare":["italian"],"mitra":["italian"],"mittente":["italian"],"mnemonico":["italian"],"modello":["italian"],"modifica":["italian"],"modulo":["italian"],"mogano":["italian"],"mogio":["italian"],"mole":["italian"],"molosso":["italian"],"monastero":["italian"],"monco":["italian"],"mondina":["italian"],"monetario":["italian"],"monile":["italian"],"monotono":["italian"],"monsone":["italian"],"montato":["italian"],"monviso":["italian"],"mora":["italian"],"mordere":["italian"],"morsicato":["italian"],"mostro":["italian"],"motivato":["italian"],"motosega":["italian"],"motto":["italian"],"movenza":["italian"],"movimento":["italian"],"mozzo":["italian"],"mucca":["italian"],"mucosa":["italian"],"muffa":["italian"],"mughetto":["italian"],"mugnaio":["italian"],"mulatto":["italian"],"mulinello":["italian"],"multiplo":["italian"],"mummia":["italian"],"munto":["italian"],"muovere":["italian"],"murale":["italian"],"musa":["italian"],"muscolo":["italian"],"musica":["italian"],"mutevole":["italian"],"muto":["italian"],"nababbo":["italian"],"nafta":["italian"],"nanometro":["italian"],"narciso":["italian"],"narice":["italian"],"narrato":["italian"],"nascere":["italian"],"nastrare":["italian"],"naturale":["italian"],"nautica":["italian"],"naviglio":["italian"],"nebulosa":["italian"],"necrosi":["italian"],"negativo":["italian"],"negozio":["italian"],"nemmeno":["italian"],"neofita":["italian"],"neretto":["italian"],"nervo":["italian"],"nessuno":["italian"],"nettuno":["italian"],"neutrale":["italian"],"neve":["italian"],"nevrotico":["italian"],"nicchia":["italian"],"ninfa":["italian"],"nitido":["italian"],"nobile":["italian"],"nocivo":["italian"],"nodo":["italian"],"nome":["italian"],"nomina":["italian"],"nordico":["italian"],"normale":["italian"],"norvegese":["italian"],"nostrano":["italian"],"notare":["italian"],"notizia":["italian"],"notturno":["italian"],"novella":["italian"],"nucleo":["italian"],"nulla":["italian"],"numero":["italian"],"nuovo":["italian"],"nutrire":["italian"],"nuvola":["italian"],"nuziale":["italian"],"oasi":["italian"],"obbedire":["italian"],"obbligo":["italian"],"obelisco":["italian"],"oblio":["italian"],"obolo":["italian"],"obsoleto":["italian"],"occasione":["italian"],"occhio":["italian"],"occidente":["italian"],"occorrere":["italian"],"occultare":["italian"],"ocra":["italian"],"oculato":["italian"],"odierno":["italian"],"odorare":["italian"],"offerta":["italian"],"offrire":["italian"],"offuscato":["italian"],"oggetto":["italian"],"oggi":["italian"],"ognuno":["italian"],"olandese":["italian"],"olfatto":["italian"],"oliato":["italian"],"oliva":["italian"],"ologramma":["italian"],"oltre":["italian"],"omaggio":["italian"],"ombelico":["italian"],"ombra":["italian"],"omega":["italian"],"omissione":["italian"],"ondoso":["italian"],"onere":["italian"],"onice":["italian"],"onnivoro":["italian"],"onorevole":["italian"],"onta":["italian"],"operato":["italian"],"opinione":["italian"],"opposto":["italian"],"oracolo":["italian"],"orafo":["italian"],"ordine":["italian"],"orecchino":["italian"],"orefice":["italian"],"orfano":["italian"],"organico":["italian"],"origine":["italian"],"orizzonte":["italian"],"orma":["italian"],"ormeggio":["italian"],"ornativo":["italian"],"orologio":["italian"],"orrendo":["italian"],"orribile":["italian"],"ortensia":["italian"],"ortica":["italian"],"orzata":["italian"],"orzo":["italian"],"osare":["italian"],"oscurare":["italian"],"osmosi":["italian"],"ospedale":["italian"],"ospite":["italian"],"ossa":["italian"],"ossidare":["italian"],"ostacolo":["italian"],"oste":["italian"],"otite":["italian"],"otre":["italian"],"ottagono":["italian"],"ottimo":["italian"],"ottobre":["italian"],"ovale":["italian"],"ovest":["italian"],"ovino":["italian"],"oviparo":["italian"],"ovocito":["italian"],"ovunque":["italian"],"ovviare":["italian"],"ozio":["italian"],"pacchetto":["italian"],"pace":["italian"],"pacifico":["italian"],"padella":["italian"],"padrone":["italian"],"paese":["italian"],"paga":["italian"],"pagina":["italian"],"palazzina":["italian"],"palesare":["italian"],"pallido":["italian"],"palo":["italian"],"palude":["italian"],"pandoro":["italian"],"pannello":["italian"],"paolo":["italian"],"paonazzo":["italian"],"paprica":["italian"],"parabola":["italian"],"parcella":["italian"],"parere":["italian"],"pargolo":["italian"],"pari":["italian"],"parlato":["italian"],"parola":["italian"],"partire":["italian"],"parvenza":["italian"],"parziale":["italian"],"passivo":["italian"],"pasticca":["italian"],"patacca":["italian"],"patologia":["italian"],"pattume":["italian"],"pavone":["italian"],"peccato":["italian"],"pedalare":["italian"],"pedonale":["italian"],"peggio":["italian"],"peloso":["italian"],"penare":["italian"],"pendice":["italian"],"penisola":["italian"],"pennuto":["italian"],"penombra":["italian"],"pensare":["italian"],"pentola":["italian"],"pepe":["italian"],"pepita":["italian"],"perbene":["italian"],"percorso":["italian"],"perdonato":["italian"],"perforare":["italian"],"pergamena":["italian"],"periodo":["italian"],"permesso":["italian"],"perno":["italian"],"perplesso":["italian"],"persuaso":["italian"],"pertugio":["italian"],"pervaso":["italian"],"pesatore":["italian"],"pesista":["italian"],"peso":["italian"],"pestifero":["italian"],"petalo":["italian"],"pettine":["italian"],"petulante":["italian"],"pezzo":["italian"],"piacere":["italian"],"pianta":["italian"],"piattino":["italian"],"piccino":["italian"],"picozza":["italian"],"piega":["italian"],"pietra":["italian"],"piffero":["italian"],"pigiama":["italian"],"pigolio":["italian"],"pigro":["italian"],"pila":["italian"],"pilifero":["italian"],"pillola":["italian"],"pilota":["italian"],"pimpante":["italian"],"pineta":["italian"],"pinna":["italian"],"pinolo":["italian"],"pioggia":["italian"],"piombo":["italian"],"piramide":["italian"],"piretico":["italian"],"pirite":["italian"],"pirolisi":["italian"],"pitone":["italian"],"pizzico":["italian"],"placebo":["italian"],"planare":["italian"],"plasma":["italian"],"platano":["italian"],"plenario":["italian"],"pochezza":["italian"],"poderoso":["italian"],"podismo":["italian"],"poesia":["italian"],"poggiare":["italian"],"polenta":["italian"],"poligono":["italian"],"pollice":["italian"],"polmonite":["italian"],"polpetta":["italian"],"polso":["italian"],"poltrona":["italian"],"polvere":["italian"],"pomice":["italian"],"pomodoro":["italian"],"ponte":["italian"],"popoloso":["italian"],"porfido":["italian"],"poroso":["italian"],"porpora":["italian"],"porre":["italian"],"portata":["italian"],"posa":["italian","turkish"],"positivo":["italian"],"possesso":["italian"],"postulato":["italian"],"potassio":["italian"],"potere":["italian"],"pranzo":["italian"],"prassi":["italian"],"pratica":["italian"],"precluso":["italian"],"predica":["italian"],"prefisso":["italian"],"pregiato":["italian"],"prelievo":["italian"],"premere":["italian"],"prenotare":["italian"],"preparato":["italian"],"presenza":["italian"],"pretesto":["italian"],"prevalso":["italian"],"prima":["italian"],"principe":["italian"],"privato":["italian"],"problema":["italian"],"procura":["italian"],"produrre":["italian"],"profumo":["italian"],"progetto":["italian"],"prolunga":["italian"],"promessa":["italian"],"pronome":["italian"],"proposta":["italian"],"proroga":["italian"],"proteso":["italian"],"prova":["italian","turkish"],"prudente":["italian"],"prugna":["italian"],"prurito":["italian"],"psiche":["italian"],"pubblico":["italian"],"pudica":["italian"],"pugilato":["italian"],"pugno":["italian"],"pulce":["italian"],"pulito":["italian"],"pulsante":["italian"],"puntare":["italian"],"pupazzo":["italian"],"pupilla":["italian"],"puro":["italian"],"quadro":["italian"],"qualcosa":["italian"],"quasi":["italian"],"querela":["italian"],"quota":["italian"],"raccolto":["italian"],"raddoppio":["italian"],"radicale":["italian"],"radunato":["italian"],"raffica":["italian"],"ragazzo":["italian"],"ragione":["italian"],"ragno":["italian"],"ramarro":["italian"],"ramingo":["italian"],"ramo":["italian"],"randagio":["italian"],"rantolare":["italian"],"rapato":["italian"],"rapina":["italian"],"rappreso":["italian"],"rasatura":["italian"],"raschiato":["italian"],"rasente":["italian"],"rassegna":["italian"],"rastrello":["italian"],"rata":["italian"],"ravveduto":["italian"],"reale":["italian"],"recepire":["italian"],"recinto":["italian"],"recluta":["italian"],"recondito":["italian"],"recupero":["italian"],"reddito":["italian"],"redimere":["italian"],"regalato":["italian"],"registro":["italian"],"regola":["italian"],"regresso":["italian"],"relazione":["italian"],"remare":["italian"],"remoto":["italian"],"renna":["italian"],"replica":["italian"],"reprimere":["italian"],"reputare":["italian"],"resa":["italian"],"residente":["italian"],"responso":["italian"],"restauro":["italian"],"rete":["italian"],"retina":["italian"],"retorica":["italian"],"rettifica":["italian"],"revocato":["italian"],"riassunto":["italian"],"ribadire":["italian"],"ribelle":["italian"],"ribrezzo":["italian"],"ricarica":["italian"],"ricco":["italian"],"ricevere":["italian"],"riciclato":["italian"],"ricordo":["italian"],"ricreduto":["italian"],"ridicolo":["italian"],"ridurre":["italian"],"rifasare":["italian"],"riflesso":["italian"],"riforma":["italian"],"rifugio":["italian"],"rigare":["italian"],"rigettato":["italian"],"righello":["italian"],"rilassato":["italian"],"rilevato":["italian"],"rimanere":["italian"],"rimbalzo":["italian"],"rimedio":["italian"],"rimorchio":["italian"],"rinascita":["italian"],"rincaro":["italian"],"rinforzo":["italian"],"rinnovo":["italian"],"rinomato":["italian"],"rinsavito":["italian"],"rintocco":["italian"],"rinuncia":["italian"],"rinvenire":["italian"],"riparato":["italian"],"ripetuto":["italian"],"ripieno":["italian"],"riportare":["italian"],"ripresa":["italian"],"ripulire":["italian"],"risata":["italian"],"rischio":["italian"],"riserva":["italian"],"risibile":["italian"],"riso":["italian"],"rispetto":["italian"],"ristoro":["italian"],"risultato":["italian"],"risvolto":["italian"],"ritardo":["italian"],"ritegno":["italian"],"ritmico":["italian"],"ritrovo":["italian"],"riunione":["italian"],"riva":["italian"],"riverso":["italian"],"rivincita":["italian"],"rivolto":["italian"],"rizoma":["italian"],"roba":["italian"],"robotico":["italian"],"robusto":["italian"],"roccia":["italian"],"roco":["italian"],"rodaggio":["italian"],"rodere":["italian"],"roditore":["italian"],"rogito":["italian"],"rollio":["italian"],"romantico":["italian"],"rompere":["italian"],"ronzio":["italian"],"rosolare":["italian"],"rospo":["italian"],"rotante":["italian"],"rotondo":["italian"],"rotula":["italian"],"rovescio":["italian"],"rubizzo":["italian"],"rubrica":["italian"],"ruga":["italian"],"rullino":["italian"],"rumine":["italian"],"rumoroso":["italian"],"ruolo":["italian"],"rupe":["italian"],"russare":["italian"],"rustico":["italian"],"sabato":["italian"],"sabbiare":["italian"],"sabotato":["italian"],"sagoma":["italian"],"salasso":["italian"],"saldatura":["italian"],"salgemma":["italian"],"salivare":["italian"],"salmone":["italian"],"salone":["italian"],"saltare":["italian"],"saluto":["italian"],"salvo":["italian"],"sapere":["italian"],"sapido":["italian"],"saporito":["italian"],"saraceno":["italian"],"sarcasmo":["italian"],"sarto":["italian"],"sassoso":["italian"],"satellite":["italian"],"satira":["italian"],"satollo":["italian"],"saturno":["italian"],"savana":["italian"],"savio":["italian"],"saziato":["italian"],"sbadiglio":["italian"],"sbalzo":["italian"],"sbancato":["italian"],"sbarra":["italian"],"sbattere":["italian"],"sbavare":["italian"],"sbendare":["italian"],"sbirciare":["italian"],"sbloccato":["italian"],"sbocciato":["italian"],"sbrinare":["italian"],"sbruffone":["italian"],"sbuffare":["italian"],"scabroso":["italian"],"scadenza":["italian"],"scala":["italian"],"scambiare":["italian"],"scandalo":["italian"],"scapola":["italian"],"scarso":["italian"],"scatenare":["italian"],"scavato":["italian"],"scelto":["italian"],"scenico":["italian"],"scettro":["italian"],"scheda":["italian"],"schiena":["italian"],"sciarpa":["italian"],"scienza":["italian"],"scindere":["italian"],"scippo":["italian"],"sciroppo":["italian"],"scivolo":["italian"],"sclerare":["italian"],"scodella":["italian"],"scolpito":["italian"],"scomparto":["italian"],"sconforto":["italian"],"scoprire":["italian"],"scorta":["italian"],"scossone":["italian"],"scozzese":["italian"],"scriba":["italian"],"scrollare":["italian"],"scrutinio":["italian"],"scuderia":["italian"],"scultore":["italian"],"scuola":["italian"],"scuro":["italian"],"scusare":["italian"],"sdebitare":["italian"],"sdoganare":["italian"],"seccatura":["italian"],"secondo":["italian"],"sedano":["italian"],"seggiola":["italian"],"segnalato":["italian"],"segregato":["italian"],"seguito":["italian"],"selciato":["italian"],"selettivo":["italian"],"sella":["italian"],"selvaggio":["italian"],"semaforo":["italian"],"sembrare":["italian"],"seme":["italian"],"seminato":["italian"],"sempre":["italian"],"senso":["italian"],"sentire":["italian"],"sepolto":["italian"],"sequenza":["italian"],"serata":["italian"],"serbato":["italian"],"sereno":["italian"],"serio":["italian"],"serpente":["italian"],"serraglio":["italian"],"servire":["italian"],"sestina":["italian"],"setola":["italian"],"settimana":["italian"],"sfacelo":["italian"],"sfaldare":["italian"],"sfamato":["italian"],"sfarzoso":["italian"],"sfaticato":["italian"],"sfera":["italian"],"sfida":["italian"],"sfilato":["italian"],"sfinge":["italian"],"sfocato":["italian"],"sfoderare":["italian"],"sfogo":["italian"],"sfoltire":["italian"],"sforzato":["italian"],"sfratto":["italian"],"sfruttato":["italian"],"sfuggito":["italian"],"sfumare":["italian"],"sfuso":["italian"],"sgabello":["italian"],"sgarbato":["italian"],"sgonfiare":["italian"],"sgorbio":["italian"],"sgrassato":["italian"],"sguardo":["italian"],"sibilo":["italian"],"siccome":["italian"],"sierra":["italian"],"sigla":["italian"],"signore":["italian"],"silenzio":["italian"],"sillaba":["italian"],"simbolo":["italian"],"simpatico":["italian"],"simulato":["italian"],"sinfonia":["italian"],"singolo":["italian"],"sinistro":["italian"],"sino":["italian"],"sintesi":["italian"],"sinusoide":["italian"],"sipario":["italian"],"sisma":["italian"],"sistole":["italian"],"situato":["italian"],"slitta":["italian"],"slogatura":["italian"],"sloveno":["italian"],"smarrito":["italian"],"smemorato":["italian"],"smentito":["italian"],"smeraldo":["italian"],"smilzo":["italian"],"smontare":["italian"],"smottato":["italian"],"smussato":["italian"],"snellire":["italian"],"snervato":["italian"],"snodo":["italian"],"sobbalzo":["italian"],"sobrio":["italian"],"soccorso":["italian"],"sociale":["italian"],"sodale":["italian"],"soffitto":["italian"],"sogno":["italian"],"soldato":["italian"],"solenne":["italian"],"solido":["italian"],"sollazzo":["italian"],"solo":["italian"],"solubile":["italian"],"solvente":["italian"],"somatico":["italian"],"somma":["italian"],"sonda":["italian"],"sonetto":["italian"],"sonnifero":["italian"],"sopire":["italian"],"soppeso":["italian"],"sopra":["italian"],"sorgere":["italian"],"sorpasso":["italian"],"sorriso":["italian"],"sorso":["italian"],"sorteggio":["italian"],"sorvolato":["italian"],"sospiro":["italian"],"sosta":["italian"],"sottile":["italian"],"spada":["italian"],"spalla":["italian"],"spargere":["italian"],"spatola":["italian"],"spavento":["italian"],"spazzola":["italian"],"specie":["italian"],"spedire":["italian"],"spegnere":["italian"],"spelatura":["italian"],"speranza":["italian"],"spessore":["italian"],"spettrale":["italian"],"spezzato":["italian"],"spia":["italian"],"spigoloso":["italian"],"spillato":["italian"],"spinoso":["italian"],"spirale":["italian"],"splendido":["italian"],"sportivo":["italian"],"sposo":["italian"],"spranga":["italian"],"sprecare":["italian"],"spronato":["italian"],"spruzzo":["italian"],"spuntino":["italian"],"squillo":["italian"],"sradicare":["italian"],"srotolato":["italian"],"stabile":["italian"],"stacco":["italian"],"staffa":["italian"],"stagnare":["italian"],"stampato":["italian"],"stantio":["italian"],"starnuto":["italian"],"stasera":["italian"],"statuto":["italian"],"stelo":["italian"],"steppa":["italian"],"sterzo":["italian"],"stiletto":["italian"],"stima":["italian"],"stirpe":["italian"],"stivale":["italian"],"stizzoso":["italian"],"stonato":["italian"],"storico":["italian"],"strappo":["italian"],"stregato":["italian"],"stridulo":["italian"],"strozzare":["italian"],"strutto":["italian"],"stuccare":["italian"],"stufo":["italian"],"stupendo":["italian"],"subentro":["italian"],"succoso":["italian"],"sudore":["italian"],"suggerito":["italian"],"sugo":["italian"],"sultano":["italian"],"suonare":["italian"],"superbo":["italian"],"supporto":["italian"],"surgelato":["italian"],"surrogato":["italian"],"sussurro":["italian"],"sutura":["italian"],"svagare":["italian"],"svedese":["italian"],"sveglio":["italian"],"svelare":["italian"],"svenuto":["italian"],"svezia":["italian"],"sviluppo":["italian"],"svista":["italian"],"svizzera":["italian"],"svolta":["italian"],"svuotare":["italian"],"tabacco":["italian"],"tabulato":["italian"],"tacciare":["italian"],"taciturno":["italian"],"tale":["italian"],"talismano":["italian"],"tampone":["italian"],"tannino":["italian"],"tara":["italian"],"tardivo":["italian"],"targato":["italian"],"tariffa":["italian"],"tarpare":["italian"],"tartaruga":["italian"],"tasto":["italian"],"tattico":["italian"],"taverna":["italian"],"tavolata":["italian"],"tazza":["italian"],"teca":["italian"],"tecnico":["italian"],"telefono":["italian"],"temerario":["italian"],"tempo":["italian","turkish"],"temuto":["italian"],"tendone":["italian"],"tenero":["italian"],"tensione":["italian"],"tentacolo":["italian"],"teorema":["italian"],"terme":["italian"],"terrazzo":["italian"],"terzetto":["italian"],"tesi":["italian"],"tesserato":["italian"],"testato":["italian"],"tetro":["italian"],"tettoia":["italian"],"tifare":["italian"],"tigella":["italian"],"timbro":["italian"],"tinto":["italian"],"tipico":["italian"],"tipografo":["italian"],"tiraggio":["italian"],"tiro":["italian"],"titanio":["italian"],"titolo":["italian"],"titubante":["italian"],"tizio":["italian"],"tizzone":["italian"],"toccare":["italian"],"tollerare":["italian"],"tolto":["italian"],"tombola":["italian"],"tomo":["italian"],"tonfo":["italian"],"tonsilla":["italian"],"topazio":["italian"],"topologia":["italian"],"toppa":["italian"],"torba":["italian"],"tornare":["italian"],"torrone":["italian"],"tortora":["italian"],"toscano":["italian"],"tossire":["italian"],"tostatura":["italian"],"totano":["italian"],"trabocco":["italian"],"trachea":["italian"],"trafila":["italian"],"tragedia":["italian"],"tralcio":["italian"],"tramonto":["italian"],"transito":["italian"],"trapano":["italian"],"trarre":["italian"],"trasloco":["italian"],"trattato":["italian"],"trave":["italian"],"treccia":["italian"],"tremolio":["italian"],"trespolo":["italian"],"tributo":["italian"],"tricheco":["italian"],"trifoglio":["italian"],"trillo":["italian"],"trincea":["italian"],"trio":["italian"],"tristezza":["italian"],"triturato":["italian"],"trivella":["italian"],"tromba":["italian"],"trono":["italian"],"troppo":["italian"],"trottola":["italian"],"trovare":["italian"],"truccato":["italian"],"tubatura":["italian"],"tuffato":["italian"],"tulipano":["italian"],"tumulto":["italian"],"tunisia":["italian"],"turbare":["italian"],"turchino":["italian"],"tuta":["italian"],"tutela":["italian"],"ubicato":["italian"],"uccello":["italian"],"uccisore":["italian"],"udire":["italian"],"uditivo":["italian"],"uffa":["italian"],"ufficio":["italian"],"uguale":["italian"],"ulisse":["italian"],"ultimato":["italian"],"umano":["italian"],"umile":["italian"],"umorismo":["italian"],"uncinetto":["italian"],"ungere":["italian"],"ungherese":["italian"],"unicorno":["italian"],"unificato":["italian"],"unisono":["italian"],"unitario":["italian"],"unte":["italian"],"uovo":["italian"],"upupa":["italian"],"uragano":["italian"],"urgenza":["italian"],"urlo":["italian"],"usanza":["italian"],"usato":["italian"],"uscito":["italian"],"usignolo":["italian"],"usuraio":["italian"],"utensile":["italian"],"utilizzo":["italian"],"utopia":["italian"],"vacante":["italian"],"vaccinato":["italian"],"vagabondo":["italian"],"vagliato":["italian"],"valanga":["italian"],"valgo":["italian"],"valico":["italian"],"valletta":["italian"],"valoroso":["italian"],"valutare":["italian"],"valvola":["italian"],"vampata":["italian"],"vangare":["italian"],"vanitoso":["italian"],"vano":["italian"],"vantaggio":["italian"],"vanvera":["italian"],"vapore":["italian"],"varano":["italian"],"varcato":["italian"],"variante":["italian"],"vasca":["italian"],"vedetta":["italian"],"vedova":["italian"],"veduto":["italian"],"vegetale":["italian"],"veicolo":["italian"],"velcro":["italian"],"velina":["italian"],"velluto":["italian"],"veloce":["italian"],"venato":["italian"],"vendemmia":["italian"],"vento":["italian"],"verace":["italian"],"verbale":["italian"],"vergogna":["italian"],"verifica":["italian"],"vero":["italian"],"verruca":["italian"],"verticale":["italian"],"vescica":["italian"],"vessillo":["italian"],"vestale":["italian"],"veterano":["italian"],"vetrina":["italian"],"vetusto":["italian"],"viandante":["italian"],"vibrante":["italian"],"vicenda":["italian"],"vichingo":["italian"],"vicinanza":["italian"],"vidimare":["italian"],"vigilia":["italian"],"vigneto":["italian"],"vigore":["italian"],"vile":["italian"],"villano":["italian"],"vimini":["italian"],"vincitore":["italian"],"viola":["italian"],"vipera":["italian"],"virgola":["italian"],"virologo":["italian"],"virulento":["italian"],"viscoso":["italian"],"visione":["italian"],"vispo":["italian"],"vissuto":["italian"],"visura":["italian"],"vita":["italian"],"vitello":["italian"],"vittima":["italian"],"vivanda":["italian"],"vivido":["italian"],"viziare":["italian"],"voce":["italian"],"voga":["italian"],"volatile":["italian"],"volere":["italian"],"volpe":["italian"],"voragine":["italian"],"vulcano":["italian"],"zampogna":["italian"],"zanna":["italian"],"zappato":["italian"],"zattera":["italian"],"zavorra":["italian"],"zefiro":["italian"],"zelante":["italian"],"zelo":["italian"],"zenzero":["italian"],"zerbino":["italian"],"zibetto":["italian"],"zinco":["italian"],"zircone":["italian"],"zitto":["italian"],"zolla":["italian"],"zotico":["italian"],"zucchero":["italian"],"zufolo":["italian"],"zulu":["italian"],"zuppa":["italian"],"あいこくしん":["japanese"],"あいさつ":["japanese"],"あいだ":["japanese"],"あおぞら":["japanese"],"あかちゃん":["japanese"],"あきる":["japanese"],"あけがた":["japanese"],"あける":["japanese"],"あこがれる":["japanese"],"あさい":["japanese"],"あさひ":["japanese"],"あしあと":["japanese"],"あじわう":["japanese"],"あずかる":["japanese"],"あずき":["japanese"],"あそぶ":["japanese"],"あたえる":["japanese"],"あたためる":["japanese"],"あたりまえ":["japanese"],"あたる":["japanese"],"あつい":["japanese"],"あつかう":["japanese"],"あっしゅく":["japanese"],"あつまり":["japanese"],"あつめる":["japanese"],"あてな":["japanese"],"あてはまる":["japanese"],"あひる":["japanese"],"あぶら":["japanese"],"あぶる":["japanese"],"あふれる":["japanese"],"あまい":["japanese"],"あまど":["japanese"],"あまやかす":["japanese"],"あまり":["japanese"],"あみもの":["japanese"],"あめりか":["japanese"],"あやまる":["japanese"],"あゆむ":["japanese"],"あらいぐま":["japanese"],"あらし":["japanese"],"あらすじ":["japanese"],"あらためる":["japanese"],"あらゆる":["japanese"],"あらわす":["japanese"],"ありがとう":["japanese"],"あわせる":["japanese"],"あわてる":["japanese"],"あんい":["japanese"],"あんがい":["japanese"],"あんこ":["japanese"],"あんぜん":["japanese"],"あんてい":["japanese"],"あんない":["japanese"],"あんまり":["japanese"],"いいだす":["japanese"],"いおん":["japanese"],"いがい":["japanese"],"いがく":["japanese"],"いきおい":["japanese"],"いきなり":["japanese"],"いきもの":["japanese"],"いきる":["japanese"],"いくじ":["japanese"],"いくぶん":["japanese"],"いけばな":["japanese"],"いけん":["japanese"],"いこう":["japanese"],"いこく":["japanese"],"いこつ":["japanese"],"いさましい":["japanese"],"いさん":["japanese"],"いしき":["japanese"],"いじゅう":["japanese"],"いじょう":["japanese"],"いじわる":["japanese"],"いずみ":["japanese"],"いずれ":["japanese"],"いせい":["japanese"],"いせえび":["japanese"],"いせかい":["japanese"],"いせき":["japanese"],"いぜん":["japanese"],"いそうろう":["japanese"],"いそがしい":["japanese"],"いだい":["japanese"],"いだく":["japanese"],"いたずら":["japanese"],"いたみ":["japanese"],"いたりあ":["japanese"],"いちおう":["japanese"],"いちじ":["japanese"],"いちど":["japanese"],"いちば":["japanese"],"いちぶ":["japanese"],"いちりゅう":["japanese"],"いつか":["japanese"],"いっしゅん":["japanese"],"いっせい":["japanese"],"いっそう":["japanese"],"いったん":["japanese"],"いっち":["japanese"],"いってい":["japanese"],"いっぽう":["japanese"],"いてざ":["japanese"],"いてん":["japanese"],"いどう":["japanese"],"いとこ":["japanese"],"いない":["japanese"],"いなか":["japanese"],"いねむり":["japanese"],"いのち":["japanese"],"いのる":["japanese"],"いはつ":["japanese"],"いばる":["japanese"],"いはん":["japanese"],"いびき":["japanese"],"いひん":["japanese"],"いふく":["japanese"],"いへん":["japanese"],"いほう":["japanese"],"いみん":["japanese"],"いもうと":["japanese"],"いもたれ":["japanese"],"いもり":["japanese"],"いやがる":["japanese"],"いやす":["japanese"],"いよかん":["japanese"],"いよく":["japanese"],"いらい":["japanese"],"いらすと":["japanese"],"いりぐち":["japanese"],"いりょう":["japanese"],"いれい":["japanese"],"いれもの":["japanese"],"いれる":["japanese"],"いろえんぴつ":["japanese"],"いわい":["japanese"],"いわう":["japanese"],"いわかん":["japanese"],"いわば":["japanese"],"いわゆる":["japanese"],"いんげんまめ":["japanese"],"いんさつ":["japanese"],"いんしょう":["japanese"],"いんよう":["japanese"],"うえき":["japanese"],"うえる":["japanese"],"うおざ":["japanese"],"うがい":["japanese"],"うかぶ":["japanese"],"うかべる":["japanese"],"うきわ":["japanese"],"うくらいな":["japanese"],"うくれれ":["japanese"],"うけたまわる":["japanese"],"うけつけ":["japanese"],"うけとる":["japanese"],"うけもつ":["japanese"],"うける":["japanese"],"うごかす":["japanese"],"うごく":["japanese"],"うこん":["japanese"],"うさぎ":["japanese"],"うしなう":["japanese"],"うしろがみ":["japanese"],"うすい":["japanese"],"うすぎ":["japanese"],"うすぐらい":["japanese"],"うすめる":["japanese"],"うせつ":["japanese"],"うちあわせ":["japanese"],"うちがわ":["japanese"],"うちき":["japanese"],"うちゅう":["japanese"],"うっかり":["japanese"],"うつくしい":["japanese"],"うったえる":["japanese"],"うつる":["japanese"],"うどん":["japanese"],"うなぎ":["japanese"],"うなじ":["japanese"],"うなずく":["japanese"],"うなる":["japanese"],"うねる":["japanese"],"うのう":["japanese"],"うぶげ":["japanese"],"うぶごえ":["japanese"],"うまれる":["japanese"],"うめる":["japanese"],"うもう":["japanese"],"うやまう":["japanese"],"うよく":["japanese"],"うらがえす":["japanese"],"うらぐち":["japanese"],"うらない":["japanese"],"うりあげ":["japanese"],"うりきれ":["japanese"],"うるさい":["japanese"],"うれしい":["japanese"],"うれゆき":["japanese"],"うれる":["japanese"],"うろこ":["japanese"],"うわき":["japanese"],"うわさ":["japanese"],"うんこう":["japanese"],"うんちん":["japanese"],"うんてん":["japanese"],"うんどう":["japanese"],"えいえん":["japanese"],"えいが":["japanese"],"えいきょう":["japanese"],"えいご":["japanese"],"えいせい":["japanese"],"えいぶん":["japanese"],"えいよう":["japanese"],"えいわ":["japanese"],"えおり":["japanese"],"えがお":["japanese"],"えがく":["japanese"],"えきたい":["japanese"],"えくせる":["japanese"],"えしゃく":["japanese"],"えすて":["japanese"],"えつらん":["japanese"],"えのぐ":["japanese"],"えほうまき":["japanese"],"えほん":["japanese"],"えまき":["japanese"],"えもじ":["japanese"],"えもの":["japanese"],"えらい":["japanese"],"えらぶ":["japanese"],"えりあ":["japanese"],"えんえん":["japanese"],"えんかい":["japanese"],"えんぎ":["japanese"],"えんげき":["japanese"],"えんしゅう":["japanese"],"えんぜつ":["japanese"],"えんそく":["japanese"],"えんちょう":["japanese"],"えんとつ":["japanese"],"おいかける":["japanese"],"おいこす":["japanese"],"おいしい":["japanese"],"おいつく":["japanese"],"おうえん":["japanese"],"おうさま":["japanese"],"おうじ":["japanese"],"おうせつ":["japanese"],"おうたい":["japanese"],"おうふく":["japanese"],"おうべい":["japanese"],"おうよう":["japanese"],"おえる":["japanese"],"おおい":["japanese"],"おおう":["japanese"],"おおどおり":["japanese"],"おおや":["japanese"],"おおよそ":["japanese"],"おかえり":["japanese"],"おかず":["japanese"],"おがむ":["japanese"],"おかわり":["japanese"],"おぎなう":["japanese"],"おきる":["japanese"],"おくさま":["japanese"],"おくじょう":["japanese"],"おくりがな":["japanese"],"おくる":["japanese"],"おくれる":["japanese"],"おこす":["japanese"],"おこなう":["japanese"],"おこる":["japanese"],"おさえる":["japanese"],"おさない":["japanese"],"おさめる":["japanese"],"おしいれ":["japanese"],"おしえる":["japanese"],"おじぎ":["japanese"],"おじさん":["japanese"],"おしゃれ":["japanese"],"おそらく":["japanese"],"おそわる":["japanese"],"おたがい":["japanese"],"おたく":["japanese"],"おだやか":["japanese"],"おちつく":["japanese"],"おっと":["japanese"],"おつり":["japanese"],"おでかけ":["japanese"],"おとしもの":["japanese"],"おとなしい":["japanese"],"おどり":["japanese"],"おどろかす":["japanese"],"おばさん":["japanese"],"おまいり":["japanese"],"おめでとう":["japanese"],"おもいで":["japanese"],"おもう":["japanese"],"おもたい":["japanese"],"おもちゃ":["japanese"],"おやつ":["japanese"],"おやゆび":["japanese"],"およぼす":["japanese"],"おらんだ":["japanese"],"おろす":["japanese"],"おんがく":["japanese"],"おんけい":["japanese"],"おんしゃ":["japanese"],"おんせん":["japanese"],"おんだん":["japanese"],"おんちゅう":["japanese"],"おんどけい":["japanese"],"かあつ":["japanese"],"かいが":["japanese"],"がいき":["japanese"],"がいけん":["japanese"],"がいこう":["japanese"],"かいさつ":["japanese"],"かいしゃ":["japanese"],"かいすいよく":["japanese"],"かいぜん":["japanese"],"かいぞうど":["japanese"],"かいつう":["japanese"],"かいてん":["japanese"],"かいとう":["japanese"],"かいふく":["japanese"],"がいへき":["japanese"],"かいほう":["japanese"],"かいよう":["japanese"],"がいらい":["japanese"],"かいわ":["japanese"],"かえる":["japanese"],"かおり":["japanese"],"かかえる":["japanese"],"かがく":["japanese"],"かがし":["japanese"],"かがみ":["japanese"],"かくご":["japanese"],"かくとく":["japanese"],"かざる":["japanese"],"がぞう":["japanese"],"かたい":["japanese"],"かたち":["japanese"],"がちょう":["japanese"],"がっきゅう":["japanese"],"がっこう":["japanese"],"がっさん":["japanese"],"がっしょう":["japanese"],"かなざわし":["japanese"],"かのう":["japanese"],"がはく":["japanese"],"かぶか":["japanese"],"かほう":["japanese"],"かほご":["japanese"],"かまう":["japanese"],"かまぼこ":["japanese"],"かめれおん":["japanese"],"かゆい":["japanese"],"かようび":["japanese"],"からい":["japanese"],"かるい":["japanese"],"かろう":["japanese"],"かわく":["japanese"],"かわら":["japanese"],"がんか":["japanese"],"かんけい":["japanese"],"かんこう":["japanese"],"かんしゃ":["japanese"],"かんそう":["japanese"],"かんたん":["japanese"],"かんち":["japanese"],"がんばる":["japanese"],"きあい":["japanese"],"きあつ":["japanese"],"きいろ":["japanese"],"ぎいん":["japanese"],"きうい":["japanese"],"きうん":["japanese"],"きえる":["japanese"],"きおう":["japanese"],"きおく":["japanese"],"きおち":["japanese"],"きおん":["japanese"],"きかい":["japanese"],"きかく":["japanese"],"きかんしゃ":["japanese"],"ききて":["japanese"],"きくばり":["japanese"],"きくらげ":["japanese"],"きけんせい":["japanese"],"きこう":["japanese"],"きこえる":["japanese"],"きこく":["japanese"],"きさい":["japanese"],"きさく":["japanese"],"きさま":["japanese"],"きさらぎ":["japanese"],"ぎじかがく":["japanese"],"ぎしき":["japanese"],"ぎじたいけん":["japanese"],"ぎじにってい":["japanese"],"ぎじゅつしゃ":["japanese"],"きすう":["japanese"],"きせい":["japanese"],"きせき":["japanese"],"きせつ":["japanese"],"きそう":["japanese"],"きぞく":["japanese"],"きぞん":["japanese"],"きたえる":["japanese"],"きちょう":["japanese"],"きつえん":["japanese"],"ぎっちり":["japanese"],"きつつき":["japanese"],"きつね":["japanese"],"きてい":["japanese"],"きどう":["japanese"],"きどく":["japanese"],"きない":["japanese"],"きなが":["japanese"],"きなこ":["japanese"],"きぬごし":["japanese"],"きねん":["japanese"],"きのう":["japanese"],"きのした":["japanese"],"きはく":["japanese"],"きびしい":["japanese"],"きひん":["japanese"],"きふく":["japanese"],"きぶん":["japanese"],"きぼう":["japanese"],"きほん":["japanese"],"きまる":["japanese"],"きみつ":["japanese"],"きむずかしい":["japanese"],"きめる":["japanese"],"きもだめし":["japanese"],"きもち":["japanese"],"きもの":["japanese"],"きゃく":["japanese"],"きやく":["japanese"],"ぎゅうにく":["japanese"],"きよう":["japanese"],"きょうりゅう":["japanese"],"きらい":["japanese"],"きらく":["japanese"],"きりん":["japanese"],"きれい":["japanese"],"きれつ":["japanese"],"きろく":["japanese"],"ぎろん":["japanese"],"きわめる":["japanese"],"ぎんいろ":["japanese"],"きんかくじ":["japanese"],"きんじょ":["japanese"],"きんようび":["japanese"],"ぐあい":["japanese"],"くいず":["japanese"],"くうかん":["japanese"],"くうき":["japanese"],"くうぐん":["japanese"],"くうこう":["japanese"],"ぐうせい":["japanese"],"くうそう":["japanese"],"ぐうたら":["japanese"],"くうふく":["japanese"],"くうぼ":["japanese"],"くかん":["japanese"],"くきょう":["japanese"],"くげん":["japanese"],"ぐこう":["japanese"],"くさい":["japanese"],"くさき":["japanese"],"くさばな":["japanese"],"くさる":["japanese"],"くしゃみ":["japanese"],"くしょう":["japanese"],"くすのき":["japanese"],"くすりゆび":["japanese"],"くせげ":["japanese"],"くせん":["japanese"],"ぐたいてき":["japanese"],"くださる":["japanese"],"くたびれる":["japanese"],"くちこみ":["japanese"],"くちさき":["japanese"],"くつした":["japanese"],"ぐっすり":["japanese"],"くつろぐ":["japanese"],"くとうてん":["japanese"],"くどく":["japanese"],"くなん":["japanese"],"くねくね":["japanese"],"くのう":["japanese"],"くふう":["japanese"],"くみあわせ":["japanese"],"くみたてる":["japanese"],"くめる":["japanese"],"くやくしょ":["japanese"],"くらす":["japanese"],"くらべる":["japanese"],"くるま":["japanese"],"くれる":["japanese"],"くろう":["japanese"],"くわしい":["japanese"],"ぐんかん":["japanese"],"ぐんしょく":["japanese"],"ぐんたい":["japanese"],"ぐんて":["japanese"],"けあな":["japanese"],"けいかく":["japanese"],"けいけん":["japanese"],"けいこ":["japanese"],"けいさつ":["japanese"],"げいじゅつ":["japanese"],"けいたい":["japanese"],"げいのうじん":["japanese"],"けいれき":["japanese"],"けいろ":["japanese"],"けおとす":["japanese"],"けおりもの":["japanese"],"げきか":["japanese"],"げきげん":["japanese"],"げきだん":["japanese"],"げきちん":["japanese"],"げきとつ":["japanese"],"げきは":["japanese"],"げきやく":["japanese"],"げこう":["japanese"],"げこくじょう":["japanese"],"げざい":["japanese"],"けさき":["japanese"],"げざん":["japanese"],"けしき":["japanese"],"けしごむ":["japanese"],"けしょう":["japanese"],"げすと":["japanese"],"けたば":["japanese"],"けちゃっぷ":["japanese"],"けちらす":["japanese"],"けつあつ":["japanese"],"けつい":["japanese"],"けつえき":["japanese"],"けっこん":["japanese"],"けつじょ":["japanese"],"けっせき":["japanese"],"けってい":["japanese"],"けつまつ":["japanese"],"げつようび":["japanese"],"げつれい":["japanese"],"けつろん":["japanese"],"げどく":["japanese"],"けとばす":["japanese"],"けとる":["japanese"],"けなげ":["japanese"],"けなす":["japanese"],"けなみ":["japanese"],"けぬき":["japanese"],"げねつ":["japanese"],"けねん":["japanese"],"けはい":["japanese"],"げひん":["japanese"],"けぶかい":["japanese"],"げぼく":["japanese"],"けまり":["japanese"],"けみかる":["japanese"],"けむし":["japanese"],"けむり":["japanese"],"けもの":["japanese"],"けらい":["japanese"],"けろけろ":["japanese"],"けわしい":["japanese"],"けんい":["japanese"],"けんえつ":["japanese"],"けんお":["japanese"],"けんか":["japanese"],"げんき":["japanese"],"けんげん":["japanese"],"けんこう":["japanese"],"けんさく":["japanese"],"けんしゅう":["japanese"],"けんすう":["japanese"],"げんそう":["japanese"],"けんちく":["japanese"],"けんてい":["japanese"],"けんとう":["japanese"],"けんない":["japanese"],"けんにん":["japanese"],"げんぶつ":["japanese"],"けんま":["japanese"],"けんみん":["japanese"],"けんめい":["japanese"],"けんらん":["japanese"],"けんり":["japanese"],"こあくま":["japanese"],"こいぬ":["japanese"],"こいびと":["japanese"],"ごうい":["japanese"],"こうえん":["japanese"],"こうおん":["japanese"],"こうかん":["japanese"],"ごうきゅう":["japanese"],"ごうけい":["japanese"],"こうこう":["japanese"],"こうさい":["japanese"],"こうじ":["japanese"],"こうすい":["japanese"],"ごうせい":["japanese"],"こうそく":["japanese"],"こうたい":["japanese"],"こうちゃ":["japanese"],"こうつう":["japanese"],"こうてい":["japanese"],"こうどう":["japanese"],"こうない":["japanese"],"こうはい":["japanese"],"ごうほう":["japanese"],"ごうまん":["japanese"],"こうもく":["japanese"],"こうりつ":["japanese"],"こえる":["japanese"],"こおり":["japanese"],"ごかい":["japanese"],"ごがつ":["japanese"],"ごかん":["japanese"],"こくご":["japanese"],"こくさい":["japanese"],"こくとう":["japanese"],"こくない":["japanese"],"こくはく":["japanese"],"こぐま":["japanese"],"こけい":["japanese"],"こける":["japanese"],"ここのか":["japanese"],"こころ":["japanese"],"こさめ":["japanese"],"こしつ":["japanese"],"こすう":["japanese"],"こせい":["japanese"],"こせき":["japanese"],"こぜん":["japanese"],"こそだて":["japanese"],"こたい":["japanese"],"こたえる":["japanese"],"こたつ":["japanese"],"こちょう":["japanese"],"こっか":["japanese"],"こつこつ":["japanese"],"こつばん":["japanese"],"こつぶ":["japanese"],"こてい":["japanese"],"こてん":["japanese"],"ことがら":["japanese"],"ことし":["japanese"],"ことば":["japanese"],"ことり":["japanese"],"こなごな":["japanese"],"こねこね":["japanese"],"このまま":["japanese"],"このみ":["japanese"],"このよ":["japanese"],"ごはん":["japanese"],"こひつじ":["japanese"],"こふう":["japanese"],"こふん":["japanese"],"こぼれる":["japanese"],"ごまあぶら":["japanese"],"こまかい":["japanese"],"ごますり":["japanese"],"こまつな":["japanese"],"こまる":["japanese"],"こむぎこ":["japanese"],"こもじ":["japanese"],"こもち":["japanese"],"こもの":["japanese"],"こもん":["japanese"],"こやく":["japanese"],"こやま":["japanese"],"こゆう":["japanese"],"こゆび":["japanese"],"こよい":["japanese"],"こよう":["japanese"],"こりる":["japanese"],"これくしょん":["japanese"],"ころっけ":["japanese"],"こわもて":["japanese"],"こわれる":["japanese"],"こんいん":["japanese"],"こんかい":["japanese"],"こんき":["japanese"],"こんしゅう":["japanese"],"こんすい":["japanese"],"こんだて":["japanese"],"こんとん":["japanese"],"こんなん":["japanese"],"こんびに":["japanese"],"こんぽん":["japanese"],"こんまけ":["japanese"],"こんや":["japanese"],"こんれい":["japanese"],"こんわく":["japanese"],"ざいえき":["japanese"],"さいかい":["japanese"],"さいきん":["japanese"],"ざいげん":["japanese"],"ざいこ":["japanese"],"さいしょ":["japanese"],"さいせい":["japanese"],"ざいたく":["japanese"],"ざいちゅう":["japanese"],"さいてき":["japanese"],"ざいりょう":["japanese"],"さうな":["japanese"],"さかいし":["japanese"],"さがす":["japanese"],"さかな":["japanese"],"さかみち":["japanese"],"さがる":["japanese"],"さぎょう":["japanese"],"さくし":["japanese"],"さくひん":["japanese"],"さくら":["japanese"],"さこく":["japanese"],"さこつ":["japanese"],"さずかる":["japanese"],"ざせき":["japanese"],"さたん":["japanese"],"さつえい":["japanese"],"ざつおん":["japanese"],"ざっか":["japanese"],"ざつがく":["japanese"],"さっきょく":["japanese"],"ざっし":["japanese"],"さつじん":["japanese"],"ざっそう":["japanese"],"さつたば":["japanese"],"さつまいも":["japanese"],"さてい":["japanese"],"さといも":["japanese"],"さとう":["japanese"],"さとおや":["japanese"],"さとし":["japanese"],"さとる":["japanese"],"さのう":["japanese"],"さばく":["japanese"],"さびしい":["japanese"],"さべつ":["japanese"],"さほう":["japanese"],"さほど":["japanese"],"さます":["japanese"],"さみしい":["japanese"],"さみだれ":["japanese"],"さむけ":["japanese"],"さめる":["japanese"],"さやえんどう":["japanese"],"さゆう":["japanese"],"さよう":["japanese"],"さよく":["japanese"],"さらだ":["japanese"],"ざるそば":["japanese"],"さわやか":["japanese"],"さわる":["japanese"],"さんいん":["japanese"],"さんか":["japanese"],"さんきゃく":["japanese"],"さんこう":["japanese"],"さんさい":["japanese"],"ざんしょ":["japanese"],"さんすう":["japanese"],"さんせい":["japanese"],"さんそ":["japanese"],"さんち":["japanese"],"さんま":["japanese"],"さんみ":["japanese"],"さんらん":["japanese"],"しあい":["japanese"],"しあげ":["japanese"],"しあさって":["japanese"],"しあわせ":["japanese"],"しいく":["japanese"],"しいん":["japanese"],"しうち":["japanese"],"しえい":["japanese"],"しおけ":["japanese"],"しかい":["japanese"],"しかく":["japanese"],"じかん":["japanese"],"しごと":["japanese"],"しすう":["japanese"],"じだい":["japanese"],"したうけ":["japanese"],"したぎ":["japanese"],"したて":["japanese"],"したみ":["japanese"],"しちょう":["japanese"],"しちりん":["japanese"],"しっかり":["japanese"],"しつじ":["japanese"],"しつもん":["japanese"],"してい":["japanese"],"してき":["japanese"],"してつ":["japanese"],"じてん":["japanese"],"じどう":["japanese"],"しなぎれ":["japanese"],"しなもの":["japanese"],"しなん":["japanese"],"しねま":["japanese"],"しねん":["japanese"],"しのぐ":["japanese"],"しのぶ":["japanese"],"しはい":["japanese"],"しばかり":["japanese"],"しはつ":["japanese"],"しはらい":["japanese"],"しはん":["japanese"],"しひょう":["japanese"],"しふく":["japanese"],"じぶん":["japanese"],"しへい":["japanese"],"しほう":["japanese"],"しほん":["japanese"],"しまう":["japanese"],"しまる":["japanese"],"しみん":["japanese"],"しむける":["japanese"],"じむしょ":["japanese"],"しめい":["japanese"],"しめる":["japanese"],"しもん":["japanese"],"しゃいん":["japanese"],"しゃうん":["japanese"],"しゃおん":["japanese"],"じゃがいも":["japanese"],"しやくしょ":["japanese"],"しゃくほう":["japanese"],"しゃけん":["japanese"],"しゃこ":["japanese"],"しゃざい":["japanese"],"しゃしん":["japanese"],"しゃせん":["japanese"],"しゃそう":["japanese"],"しゃたい":["japanese"],"しゃちょう":["japanese"],"しゃっきん":["japanese"],"じゃま":["japanese"],"しゃりん":["japanese"],"しゃれい":["japanese"],"じゆう":["japanese"],"じゅうしょ":["japanese"],"しゅくはく":["japanese"],"じゅしん":["japanese"],"しゅっせき":["japanese"],"しゅみ":["japanese"],"しゅらば":["japanese"],"じゅんばん":["japanese"],"しょうかい":["japanese"],"しょくたく":["japanese"],"しょっけん":["japanese"],"しょどう":["japanese"],"しょもつ":["japanese"],"しらせる":["japanese"],"しらべる":["japanese"],"しんか":["japanese"],"しんこう":["japanese"],"じんじゃ":["japanese"],"しんせいじ":["japanese"],"しんちく":["japanese"],"しんりん":["japanese"],"すあげ":["japanese"],"すあし":["japanese"],"すあな":["japanese"],"ずあん":["japanese"],"すいえい":["japanese"],"すいか":["japanese"],"すいとう":["japanese"],"ずいぶん":["japanese"],"すいようび":["japanese"],"すうがく":["japanese"],"すうじつ":["japanese"],"すうせん":["japanese"],"すおどり":["japanese"],"すきま":["japanese"],"すくう":["japanese"],"すくない":["japanese"],"すける":["japanese"],"すごい":["japanese"],"すこし":["japanese"],"ずさん":["japanese"],"すずしい":["japanese"],"すすむ":["japanese"],"すすめる":["japanese"],"すっかり":["japanese"],"ずっしり":["japanese"],"ずっと":["japanese"],"すてき":["japanese"],"すてる":["japanese"],"すねる":["japanese"],"すのこ":["japanese"],"すはだ":["japanese"],"すばらしい":["japanese"],"ずひょう":["japanese"],"ずぶぬれ":["japanese"],"すぶり":["japanese"],"すふれ":["japanese"],"すべて":["japanese"],"すべる":["japanese"],"ずほう":["japanese"],"すぼん":["japanese"],"すまい":["japanese"],"すめし":["japanese"],"すもう":["japanese"],"すやき":["japanese"],"すらすら":["japanese"],"するめ":["japanese"],"すれちがう":["japanese"],"すろっと":["japanese"],"すわる":["japanese"],"すんぜん":["japanese"],"すんぽう":["japanese"],"せあぶら":["japanese"],"せいかつ":["japanese"],"せいげん":["japanese"],"せいじ":["japanese"],"せいよう":["japanese"],"せおう":["japanese"],"せかいかん":["japanese"],"せきにん":["japanese"],"せきむ":["japanese"],"せきゆ":["japanese"],"せきらんうん":["japanese"],"せけん":["japanese"],"せこう":["japanese"],"せすじ":["japanese"],"せたい":["japanese"],"せたけ":["japanese"],"せっかく":["japanese"],"せっきゃく":["japanese"],"ぜっく":["japanese"],"せっけん":["japanese"],"せっこつ":["japanese"],"せっさたくま":["japanese"],"せつぞく":["japanese"],"せつだん":["japanese"],"せつでん":["japanese"],"せっぱん":["japanese"],"せつび":["japanese"],"せつぶん":["japanese"],"せつめい":["japanese"],"せつりつ":["japanese"],"せなか":["japanese"],"せのび":["japanese"],"せはば":["japanese"],"せびろ":["japanese"],"せぼね":["japanese"],"せまい":["japanese"],"せまる":["japanese"],"せめる":["japanese"],"せもたれ":["japanese"],"せりふ":["japanese"],"ぜんあく":["japanese"],"せんい":["japanese"],"せんえい":["japanese"],"せんか":["japanese"],"せんきょ":["japanese"],"せんく":["japanese"],"せんげん":["japanese"],"ぜんご":["japanese"],"せんさい":["japanese"],"せんしゅ":["japanese"],"せんすい":["japanese"],"せんせい":["japanese"],"せんぞ":["japanese"],"せんたく":["japanese"],"せんちょう":["japanese"],"せんてい":["japanese"],"せんとう":["japanese"],"せんぬき":["japanese"],"せんねん":["japanese"],"せんぱい":["japanese"],"ぜんぶ":["japanese"],"ぜんぽう":["japanese"],"せんむ":["japanese"],"せんめんじょ":["japanese"],"せんもん":["japanese"],"せんやく":["japanese"],"せんゆう":["japanese"],"せんよう":["japanese"],"ぜんら":["japanese"],"ぜんりゃく":["japanese"],"せんれい":["japanese"],"せんろ":["japanese"],"そあく":["japanese"],"そいとげる":["japanese"],"そいね":["japanese"],"そうがんきょう":["japanese"],"そうき":["japanese"],"そうご":["japanese"],"そうしん":["japanese"],"そうだん":["japanese"],"そうなん":["japanese"],"そうび":["japanese"],"そうめん":["japanese"],"そうり":["japanese"],"そえもの":["japanese"],"そえん":["japanese"],"そがい":["japanese"],"そげき":["japanese"],"そこう":["japanese"],"そこそこ":["japanese"],"そざい":["japanese"],"そしな":["japanese"],"そせい":["japanese"],"そせん":["japanese"],"そそぐ":["japanese"],"そだてる":["japanese"],"そつう":["japanese"],"そつえん":["japanese"],"そっかん":["japanese"],"そつぎょう":["japanese"],"そっけつ":["japanese"],"そっこう":["japanese"],"そっせん":["japanese"],"そっと":["japanese"],"そとがわ":["japanese"],"そとづら":["japanese"],"そなえる":["japanese"],"そなた":["japanese"],"そふぼ":["japanese"],"そぼく":["japanese"],"そぼろ":["japanese"],"そまつ":["japanese"],"そまる":["japanese"],"そむく":["japanese"],"そむりえ":["japanese"],"そめる":["japanese"],"そもそも":["japanese"],"そよかぜ":["japanese"],"そらまめ":["japanese"],"そろう":["japanese"],"そんかい":["japanese"],"そんけい":["japanese"],"そんざい":["japanese"],"そんしつ":["japanese"],"そんぞく":["japanese"],"そんちょう":["japanese"],"ぞんび":["japanese"],"ぞんぶん":["japanese"],"そんみん":["japanese"],"たあい":["japanese"],"たいいん":["japanese"],"たいうん":["japanese"],"たいえき":["japanese"],"たいおう":["japanese"],"だいがく":["japanese"],"たいき":["japanese"],"たいぐう":["japanese"],"たいけん":["japanese"],"たいこ":["japanese"],"たいざい":["japanese"],"だいじょうぶ":["japanese"],"だいすき":["japanese"],"たいせつ":["japanese"],"たいそう":["japanese"],"だいたい":["japanese"],"たいちょう":["japanese"],"たいてい":["japanese"],"だいどころ":["japanese"],"たいない":["japanese"],"たいねつ":["japanese"],"たいのう":["japanese"],"たいはん":["japanese"],"だいひょう":["japanese"],"たいふう":["japanese"],"たいへん":["japanese"],"たいほ":["japanese"],"たいまつばな":["japanese"],"たいみんぐ":["japanese"],"たいむ":["japanese"],"たいめん":["japanese"],"たいやき":["japanese"],"たいよう":["japanese"],"たいら":["japanese"],"たいりょく":["japanese"],"たいる":["japanese"],"たいわん":["japanese"],"たうえ":["japanese"],"たえる":["japanese"],"たおす":["japanese"],"たおる":["japanese"],"たおれる":["japanese"],"たかい":["japanese"],"たかね":["japanese"],"たきび":["japanese"],"たくさん":["japanese"],"たこく":["japanese"],"たこやき":["japanese"],"たさい":["japanese"],"たしざん":["japanese"],"だじゃれ":["japanese"],"たすける":["japanese"],"たずさわる":["japanese"],"たそがれ":["japanese"],"たたかう":["japanese"],"たたく":["japanese"],"ただしい":["japanese"],"たたみ":["japanese"],"たちばな":["japanese"],"だっかい":["japanese"],"だっきゃく":["japanese"],"だっこ":["japanese"],"だっしゅつ":["japanese"],"だったい":["japanese"],"たてる":["japanese"],"たとえる":["japanese"],"たなばた":["japanese"],"たにん":["japanese"],"たぬき":["japanese"],"たのしみ":["japanese"],"たはつ":["japanese"],"たぶん":["japanese"],"たべる":["japanese"],"たぼう":["japanese"],"たまご":["japanese"],"たまる":["japanese"],"だむる":["japanese"],"ためいき":["japanese"],"ためす":["japanese"],"ためる":["japanese"],"たもつ":["japanese"],"たやすい":["japanese"],"たよる":["japanese"],"たらす":["japanese"],"たりきほんがん":["japanese"],"たりょう":["japanese"],"たりる":["japanese"],"たると":["japanese"],"たれる":["japanese"],"たれんと":["japanese"],"たろっと":["japanese"],"たわむれる":["japanese"],"だんあつ":["japanese"],"たんい":["japanese"],"たんおん":["japanese"],"たんか":["japanese"],"たんき":["japanese"],"たんけん":["japanese"],"たんご":["japanese"],"たんさん":["japanese"],"たんじょうび":["japanese"],"だんせい":["japanese"],"たんそく":["japanese"],"たんたい":["japanese"],"だんち":["japanese"],"たんてい":["japanese"],"たんとう":["japanese"],"だんな":["japanese"],"たんにん":["japanese"],"だんねつ":["japanese"],"たんのう":["japanese"],"たんぴん":["japanese"],"だんぼう":["japanese"],"たんまつ":["japanese"],"たんめい":["japanese"],"だんれつ":["japanese"],"だんろ":["japanese"],"だんわ":["japanese"],"ちあい":["japanese"],"ちあん":["japanese"],"ちいき":["japanese"],"ちいさい":["japanese"],"ちえん":["japanese"],"ちかい":["japanese"],"ちから":["japanese"],"ちきゅう":["japanese"],"ちきん":["japanese"],"ちけいず":["japanese"],"ちけん":["japanese"],"ちこく":["japanese"],"ちさい":["japanese"],"ちしき":["japanese"],"ちしりょう":["japanese"],"ちせい":["japanese"],"ちそう":["japanese"],"ちたい":["japanese"],"ちたん":["japanese"],"ちちおや":["japanese"],"ちつじょ":["japanese"],"ちてき":["japanese"],"ちてん":["japanese"],"ちぬき":["japanese"],"ちぬり":["japanese"],"ちのう":["japanese"],"ちひょう":["japanese"],"ちへいせん":["japanese"],"ちほう":["japanese"],"ちまた":["japanese"],"ちみつ":["japanese"],"ちみどろ":["japanese"],"ちめいど":["japanese"],"ちゃんこなべ":["japanese"],"ちゅうい":["japanese"],"ちゆりょく":["japanese"],"ちょうし":["japanese"],"ちょさくけん":["japanese"],"ちらし":["japanese"],"ちらみ":["japanese"],"ちりがみ":["japanese"],"ちりょう":["japanese"],"ちるど":["japanese"],"ちわわ":["japanese"],"ちんたい":["japanese"],"ちんもく":["japanese"],"ついか":["japanese"],"ついたち":["japanese"],"つうか":["japanese"],"つうじょう":["japanese"],"つうはん":["japanese"],"つうわ":["japanese"],"つかう":["japanese"],"つかれる":["japanese"],"つくね":["japanese"],"つくる":["japanese"],"つけね":["japanese"],"つける":["japanese"],"つごう":["japanese"],"つたえる":["japanese"],"つづく":["japanese"],"つつじ":["japanese"],"つつむ":["japanese"],"つとめる":["japanese"],"つながる":["japanese"],"つなみ":["japanese"],"つねづね":["japanese"],"つのる":["japanese"],"つぶす":["japanese"],"つまらない":["japanese"],"つまる":["japanese"],"つみき":["japanese"],"つめたい":["japanese"],"つもり":["japanese"],"つもる":["japanese"],"つよい":["japanese"],"つるぼ":["japanese"],"つるみく":["japanese"],"つわもの":["japanese"],"つわり":["japanese"],"てあし":["japanese"],"てあて":["japanese"],"てあみ":["japanese"],"ていおん":["japanese"],"ていか":["japanese"],"ていき":["japanese"],"ていけい":["japanese"],"ていこく":["japanese"],"ていさつ":["japanese"],"ていし":["japanese"],"ていせい":["japanese"],"ていたい":["japanese"],"ていど":["japanese"],"ていねい":["japanese"],"ていひょう":["japanese"],"ていへん":["japanese"],"ていぼう":["japanese"],"てうち":["japanese"],"ておくれ":["japanese"],"てきとう":["japanese"],"てくび":["japanese"],"でこぼこ":["japanese"],"てさぎょう":["japanese"],"てさげ":["japanese"],"てすり":["japanese"],"てそう":["japanese"],"てちがい":["japanese"],"てちょう":["japanese"],"てつがく":["japanese"],"てつづき":["japanese"],"でっぱ":["japanese"],"てつぼう":["japanese"],"てつや":["japanese"],"でぬかえ":["japanese"],"てぬき":["japanese"],"てぬぐい":["japanese"],"てのひら":["japanese"],"てはい":["japanese"],"てぶくろ":["japanese"],"てふだ":["japanese"],"てほどき":["japanese"],"てほん":["japanese"],"てまえ":["japanese"],"てまきずし":["japanese"],"てみじか":["japanese"],"てみやげ":["japanese"],"てらす":["japanese"],"てれび":["japanese"],"てわけ":["japanese"],"てわたし":["japanese"],"でんあつ":["japanese"],"てんいん":["japanese"],"てんかい":["japanese"],"てんき":["japanese"],"てんぐ":["japanese"],"てんけん":["japanese"],"てんごく":["japanese"],"てんさい":["japanese"],"てんし":["japanese"],"てんすう":["japanese"],"でんち":["japanese"],"てんてき":["japanese"],"てんとう":["japanese"],"てんない":["japanese"],"てんぷら":["japanese"],"てんぼうだい":["japanese"],"てんめつ":["japanese"],"てんらんかい":["japanese"],"でんりょく":["japanese"],"でんわ":["japanese"],"どあい":["japanese"],"といれ":["japanese"],"どうかん":["japanese"],"とうきゅう":["japanese"],"どうぐ":["japanese"],"とうし":["japanese"],"とうむぎ":["japanese"],"とおい":["japanese"],"とおか":["japanese"],"とおく":["japanese"],"とおす":["japanese"],"とおる":["japanese"],"とかい":["japanese"],"とかす":["japanese"],"ときおり":["japanese"],"ときどき":["japanese"],"とくい":["japanese"],"とくしゅう":["japanese"],"とくてん":["japanese"],"とくに":["japanese"],"とくべつ":["japanese"],"とけい":["japanese"],"とける":["japanese"],"とこや":["japanese"],"とさか":["japanese"],"としょかん":["japanese"],"とそう":["japanese"],"とたん":["japanese"],"とちゅう":["japanese"],"とっきゅう":["japanese"],"とっくん":["japanese"],"とつぜん":["japanese"],"とつにゅう":["japanese"],"とどける":["japanese"],"ととのえる":["japanese"],"とない":["japanese"],"となえる":["japanese"],"となり":["japanese"],"とのさま":["japanese"],"とばす":["japanese"],"どぶがわ":["japanese"],"とほう":["japanese"],"とまる":["japanese"],"とめる":["japanese"],"ともだち":["japanese"],"ともる":["japanese"],"どようび":["japanese"],"とらえる":["japanese"],"とんかつ":["japanese"],"どんぶり":["japanese"],"ないかく":["japanese"],"ないこう":["japanese"],"ないしょ":["japanese"],"ないす":["japanese"],"ないせん":["japanese"],"ないそう":["japanese"],"なおす":["japanese"],"ながい":["japanese"],"なくす":["japanese"],"なげる":["japanese"],"なこうど":["japanese"],"なさけ":["japanese"],"なたでここ":["japanese"],"なっとう":["japanese"],"なつやすみ":["japanese"],"ななおし":["japanese"],"なにごと":["japanese"],"なにもの":["japanese"],"なにわ":["japanese"],"なのか":["japanese"],"なふだ":["japanese"],"なまいき":["japanese"],"なまえ":["japanese"],"なまみ":["japanese"],"なみだ":["japanese"],"なめらか":["japanese"],"なめる":["japanese"],"なやむ":["japanese"],"ならう":["japanese"],"ならび":["japanese"],"ならぶ":["japanese"],"なれる":["japanese"],"なわとび":["japanese"],"なわばり":["japanese"],"にあう":["japanese"],"にいがた":["japanese"],"にうけ":["japanese"],"におい":["japanese"],"にかい":["japanese"],"にがて":["japanese"],"にきび":["japanese"],"にくしみ":["japanese"],"にくまん":["japanese"],"にげる":["japanese"],"にさんかたんそ":["japanese"],"にしき":["japanese"],"にせもの":["japanese"],"にちじょう":["japanese"],"にちようび":["japanese"],"にっか":["japanese"],"にっき":["japanese"],"にっけい":["japanese"],"にっこう":["japanese"],"にっさん":["japanese"],"にっしょく":["japanese"],"にっすう":["japanese"],"にっせき":["japanese"],"にってい":["japanese"],"になう":["japanese"],"にほん":["japanese"],"にまめ":["japanese"],"にもつ":["japanese"],"にやり":["japanese"],"にゅういん":["japanese"],"にりんしゃ":["japanese"],"にわとり":["japanese"],"にんい":["japanese"],"にんか":["japanese"],"にんき":["japanese"],"にんげん":["japanese"],"にんしき":["japanese"],"にんずう":["japanese"],"にんそう":["japanese"],"にんたい":["japanese"],"にんち":["japanese"],"にんてい":["japanese"],"にんにく":["japanese"],"にんぷ":["japanese"],"にんまり":["japanese"],"にんむ":["japanese"],"にんめい":["japanese"],"にんよう":["japanese"],"ぬいくぎ":["japanese"],"ぬかす":["japanese"],"ぬぐいとる":["japanese"],"ぬぐう":["japanese"],"ぬくもり":["japanese"],"ぬすむ":["japanese"],"ぬまえび":["japanese"],"ぬめり":["japanese"],"ぬらす":["japanese"],"ぬんちゃく":["japanese"],"ねあげ":["japanese"],"ねいき":["japanese"],"ねいる":["japanese"],"ねいろ":["japanese"],"ねぐせ":["japanese"],"ねくたい":["japanese"],"ねくら":["japanese"],"ねこぜ":["japanese"],"ねこむ":["japanese"],"ねさげ":["japanese"],"ねすごす":["japanese"],"ねそべる":["japanese"],"ねだん":["japanese"],"ねつい":["japanese"],"ねっしん":["japanese"],"ねつぞう":["japanese"],"ねったいぎょ":["japanese"],"ねぶそく":["japanese"],"ねふだ":["japanese"],"ねぼう":["japanese"],"ねほりはほり":["japanese"],"ねまき":["japanese"],"ねまわし":["japanese"],"ねみみ":["japanese"],"ねむい":["japanese"],"ねむたい":["japanese"],"ねもと":["japanese"],"ねらう":["japanese"],"ねわざ":["japanese"],"ねんいり":["japanese"],"ねんおし":["japanese"],"ねんかん":["japanese"],"ねんきん":["japanese"],"ねんぐ":["japanese"],"ねんざ":["japanese"],"ねんし":["japanese"],"ねんちゃく":["japanese"],"ねんど":["japanese"],"ねんぴ":["japanese"],"ねんぶつ":["japanese"],"ねんまつ":["japanese"],"ねんりょう":["japanese"],"ねんれい":["japanese"],"のいず":["japanese"],"のおづま":["japanese"],"のがす":["japanese"],"のきなみ":["japanese"],"のこぎり":["japanese"],"のこす":["japanese"],"のこる":["japanese"],"のせる":["japanese"],"のぞく":["japanese"],"のぞむ":["japanese"],"のたまう":["japanese"],"のちほど":["japanese"],"のっく":["japanese"],"のばす":["japanese"],"のはら":["japanese"],"のべる":["japanese"],"のぼる":["japanese"],"のみもの":["japanese"],"のやま":["japanese"],"のらいぬ":["japanese"],"のらねこ":["japanese"],"のりもの":["japanese"],"のりゆき":["japanese"],"のれん":["japanese"],"のんき":["japanese"],"ばあい":["japanese"],"はあく":["japanese"],"ばあさん":["japanese"],"ばいか":["japanese"],"ばいく":["japanese"],"はいけん":["japanese"],"はいご":["japanese"],"はいしん":["japanese"],"はいすい":["japanese"],"はいせん":["japanese"],"はいそう":["japanese"],"はいち":["japanese"],"ばいばい":["japanese"],"はいれつ":["japanese"],"はえる":["japanese"],"はおる":["japanese"],"はかい":["japanese"],"ばかり":["japanese"],"はかる":["japanese"],"はくしゅ":["japanese"],"はけん":["japanese"],"はこぶ":["japanese"],"はさみ":["japanese"],"はさん":["japanese"],"はしご":["japanese"],"ばしょ":["japanese"],"はしる":["japanese"],"はせる":["japanese"],"ぱそこん":["japanese"],"はそん":["japanese"],"はたん":["japanese"],"はちみつ":["japanese"],"はつおん":["japanese"],"はっかく":["japanese"],"はづき":["japanese"],"はっきり":["japanese"],"はっくつ":["japanese"],"はっけん":["japanese"],"はっこう":["japanese"],"はっさん":["japanese"],"はっしん":["japanese"],"はったつ":["japanese"],"はっちゅう":["japanese"],"はってん":["japanese"],"はっぴょう":["japanese"],"はっぽう":["japanese"],"はなす":["japanese"],"はなび":["japanese"],"はにかむ":["japanese"],"はぶらし":["japanese"],"はみがき":["japanese"],"はむかう":["japanese"],"はめつ":["japanese"],"はやい":["japanese"],"はやし":["japanese"],"はらう":["japanese"],"はろうぃん":["japanese"],"はわい":["japanese"],"はんい":["japanese"],"はんえい":["japanese"],"はんおん":["japanese"],"はんかく":["japanese"],"はんきょう":["japanese"],"ばんぐみ":["japanese"],"はんこ":["japanese"],"はんしゃ":["japanese"],"はんすう":["japanese"],"はんだん":["japanese"],"ぱんち":["japanese"],"ぱんつ":["japanese"],"はんてい":["japanese"],"はんとし":["japanese"],"はんのう":["japanese"],"はんぱ":["japanese"],"はんぶん":["japanese"],"はんぺん":["japanese"],"はんぼうき":["japanese"],"はんめい":["japanese"],"はんらん":["japanese"],"はんろん":["japanese"],"ひいき":["japanese"],"ひうん":["japanese"],"ひえる":["japanese"],"ひかく":["japanese"],"ひかり":["japanese"],"ひかる":["japanese"],"ひかん":["japanese"],"ひくい":["japanese"],"ひけつ":["japanese"],"ひこうき":["japanese"],"ひこく":["japanese"],"ひさい":["japanese"],"ひさしぶり":["japanese"],"ひさん":["japanese"],"びじゅつかん":["japanese"],"ひしょ":["japanese"],"ひそか":["japanese"],"ひそむ":["japanese"],"ひたむき":["japanese"],"ひだり":["japanese"],"ひたる":["japanese"],"ひつぎ":["japanese"],"ひっこし":["japanese"],"ひっし":["japanese"],"ひつじゅひん":["japanese"],"ひっす":["japanese"],"ひつぜん":["japanese"],"ぴったり":["japanese"],"ぴっちり":["japanese"],"ひつよう":["japanese"],"ひてい":["japanese"],"ひとごみ":["japanese"],"ひなまつり":["japanese"],"ひなん":["japanese"],"ひねる":["japanese"],"ひはん":["japanese"],"ひびく":["japanese"],"ひひょう":["japanese"],"ひほう":["japanese"],"ひまわり":["japanese"],"ひまん":["japanese"],"ひみつ":["japanese"],"ひめい":["japanese"],"ひめじし":["japanese"],"ひやけ":["japanese"],"ひやす":["japanese"],"ひよう":["japanese"],"びょうき":["japanese"],"ひらがな":["japanese"],"ひらく":["japanese"],"ひりつ":["japanese"],"ひりょう":["japanese"],"ひるま":["japanese"],"ひるやすみ":["japanese"],"ひれい":["japanese"],"ひろい":["japanese"],"ひろう":["japanese"],"ひろき":["japanese"],"ひろゆき":["japanese"],"ひんかく":["japanese"],"ひんけつ":["japanese"],"ひんこん":["japanese"],"ひんしゅ":["japanese"],"ひんそう":["japanese"],"ぴんち":["japanese"],"ひんぱん":["japanese"],"びんぼう":["japanese"],"ふあん":["japanese"],"ふいうち":["japanese"],"ふうけい":["japanese"],"ふうせん":["japanese"],"ぷうたろう":["japanese"],"ふうとう":["japanese"],"ふうふ":["japanese"],"ふえる":["japanese"],"ふおん":["japanese"],"ふかい":["japanese"],"ふきん":["japanese"],"ふくざつ":["japanese"],"ふくぶくろ":["japanese"],"ふこう":["japanese"],"ふさい":["japanese"],"ふしぎ":["japanese"],"ふじみ":["japanese"],"ふすま":["japanese"],"ふせい":["japanese"],"ふせぐ":["japanese"],"ふそく":["japanese"],"ぶたにく":["japanese"],"ふたん":["japanese"],"ふちょう":["japanese"],"ふつう":["japanese"],"ふつか":["japanese"],"ふっかつ":["japanese"],"ふっき":["japanese"],"ふっこく":["japanese"],"ぶどう":["japanese"],"ふとる":["japanese"],"ふとん":["japanese"],"ふのう":["japanese"],"ふはい":["japanese"],"ふひょう":["japanese"],"ふへん":["japanese"],"ふまん":["japanese"],"ふみん":["japanese"],"ふめつ":["japanese"],"ふめん":["japanese"],"ふよう":["japanese"],"ふりこ":["japanese"],"ふりる":["japanese"],"ふるい":["japanese"],"ふんいき":["japanese"],"ぶんがく":["japanese"],"ぶんぐ":["japanese"],"ふんしつ":["japanese"],"ぶんせき":["japanese"],"ふんそう":["japanese"],"ぶんぽう":["japanese"],"へいあん":["japanese"],"へいおん":["japanese"],"へいがい":["japanese"],"へいき":["japanese"],"へいげん":["japanese"],"へいこう":["japanese"],"へいさ":["japanese"],"へいしゃ":["japanese"],"へいせつ":["japanese"],"へいそ":["japanese"],"へいたく":["japanese"],"へいてん":["japanese"],"へいねつ":["japanese"],"へいわ":["japanese"],"へきが":["japanese"],"へこむ":["japanese"],"べにいろ":["japanese"],"べにしょうが":["japanese"],"へらす":["japanese"],"へんかん":["japanese"],"べんきょう":["japanese"],"べんごし":["japanese"],"へんさい":["japanese"],"へんたい":["japanese"],"べんり":["japanese"],"ほあん":["japanese"],"ほいく":["japanese"],"ぼうぎょ":["japanese"],"ほうこく":["japanese"],"ほうそう":["japanese"],"ほうほう":["japanese"],"ほうもん":["japanese"],"ほうりつ":["japanese"],"ほえる":["japanese"],"ほおん":["japanese"],"ほかん":["japanese"],"ほきょう":["japanese"],"ぼきん":["japanese"],"ほくろ":["japanese"],"ほけつ":["japanese"],"ほけん":["japanese"],"ほこう":["japanese"],"ほこる":["japanese"],"ほしい":["japanese"],"ほしつ":["japanese"],"ほしゅ":["japanese"],"ほしょう":["japanese"],"ほせい":["japanese"],"ほそい":["japanese"],"ほそく":["japanese"],"ほたて":["japanese"],"ほたる":["japanese"],"ぽちぶくろ":["japanese"],"ほっきょく":["japanese"],"ほっさ":["japanese"],"ほったん":["japanese"],"ほとんど":["japanese"],"ほめる":["japanese"],"ほんい":["japanese"],"ほんき":["japanese"],"ほんけ":["japanese"],"ほんしつ":["japanese"],"ほんやく":["japanese"],"まいにち":["japanese"],"まかい":["japanese"],"まかせる":["japanese"],"まがる":["japanese"],"まける":["japanese"],"まこと":["japanese"],"まさつ":["japanese"],"まじめ":["japanese"],"ますく":["japanese"],"まぜる":["japanese"],"まつり":["japanese"],"まとめ":["japanese"],"まなぶ":["japanese"],"まぬけ":["japanese"],"まねく":["japanese"],"まほう":["japanese"],"まもる":["japanese"],"まゆげ":["japanese"],"まよう":["japanese"],"まろやか":["japanese"],"まわす":["japanese"],"まわり":["japanese"],"まわる":["japanese"],"まんが":["japanese"],"まんきつ":["japanese"],"まんぞく":["japanese"],"まんなか":["japanese"],"みいら":["japanese"],"みうち":["japanese"],"みえる":["japanese"],"みがく":["japanese"],"みかた":["japanese"],"みかん":["japanese"],"みけん":["japanese"],"みこん":["japanese"],"みじかい":["japanese"],"みすい":["japanese"],"みすえる":["japanese"],"みせる":["japanese"],"みっか":["japanese"],"みつかる":["japanese"],"みつける":["japanese"],"みてい":["japanese"],"みとめる":["japanese"],"みなと":["japanese"],"みなみかさい":["japanese"],"みねらる":["japanese"],"みのう":["japanese"],"みのがす":["japanese"],"みほん":["japanese"],"みもと":["japanese"],"みやげ":["japanese"],"みらい":["japanese"],"みりょく":["japanese"],"みわく":["japanese"],"みんか":["japanese"],"みんぞく":["japanese"],"むいか":["japanese"],"むえき":["japanese"],"むえん":["japanese"],"むかい":["japanese"],"むかう":["japanese"],"むかえ":["japanese"],"むかし":["japanese"],"むぎちゃ":["japanese"],"むける":["japanese"],"むげん":["japanese"],"むさぼる":["japanese"],"むしあつい":["japanese"],"むしば":["japanese"],"むじゅん":["japanese"],"むしろ":["japanese"],"むすう":["japanese"],"むすこ":["japanese"],"むすぶ":["japanese"],"むすめ":["japanese"],"むせる":["japanese"],"むせん":["japanese"],"むちゅう":["japanese"],"むなしい":["japanese"],"むのう":["japanese"],"むやみ":["japanese"],"むよう":["japanese"],"むらさき":["japanese"],"むりょう":["japanese"],"むろん":["japanese"],"めいあん":["japanese"],"めいうん":["japanese"],"めいえん":["japanese"],"めいかく":["japanese"],"めいきょく":["japanese"],"めいさい":["japanese"],"めいし":["japanese"],"めいそう":["japanese"],"めいぶつ":["japanese"],"めいれい":["japanese"],"めいわく":["japanese"],"めぐまれる":["japanese"],"めざす":["japanese"],"めした":["japanese"],"めずらしい":["japanese"],"めだつ":["japanese"],"めまい":["japanese"],"めやす":["japanese"],"めんきょ":["japanese"],"めんせき":["japanese"],"めんどう":["japanese"],"もうしあげる":["japanese"],"もうどうけん":["japanese"],"もえる":["japanese"],"もくし":["japanese"],"もくてき":["japanese"],"もくようび":["japanese"],"もちろん":["japanese"],"もどる":["japanese"],"もらう":["japanese"],"もんく":["japanese"],"もんだい":["japanese"],"やおや":["japanese"],"やける":["japanese"],"やさい":["japanese"],"やさしい":["japanese"],"やすい":["japanese"],"やすたろう":["japanese"],"やすみ":["japanese"],"やせる":["japanese"],"やそう":["japanese"],"やたい":["japanese"],"やちん":["japanese"],"やっと":["japanese"],"やっぱり":["japanese"],"やぶる":["japanese"],"やめる":["japanese"],"ややこしい":["japanese"],"やよい":["japanese"],"やわらかい":["japanese"],"ゆうき":["japanese"],"ゆうびんきょく":["japanese"],"ゆうべ":["japanese"],"ゆうめい":["japanese"],"ゆけつ":["japanese"],"ゆしゅつ":["japanese"],"ゆせん":["japanese"],"ゆそう":["japanese"],"ゆたか":["japanese"],"ゆちゃく":["japanese"],"ゆでる":["japanese"],"ゆにゅう":["japanese"],"ゆびわ":["japanese"],"ゆらい":["japanese"],"ゆれる":["japanese"],"ようい":["japanese"],"ようか":["japanese"],"ようきゅう":["japanese"],"ようじ":["japanese"],"ようす":["japanese"],"ようちえん":["japanese"],"よかぜ":["japanese"],"よかん":["japanese"],"よきん":["japanese"],"よくせい":["japanese"],"よくぼう":["japanese"],"よけい":["japanese"],"よごれる":["japanese"],"よさん":["japanese"],"よしゅう":["japanese"],"よそう":["japanese"],"よそく":["japanese"],"よっか":["japanese"],"よてい":["japanese"],"よどがわく":["japanese"],"よねつ":["japanese"],"よやく":["japanese"],"よゆう":["japanese"],"よろこぶ":["japanese"],"よろしい":["japanese"],"らいう":["japanese"],"らくがき":["japanese"],"らくご":["japanese"],"らくさつ":["japanese"],"らくだ":["japanese"],"らしんばん":["japanese"],"らせん":["japanese"],"らぞく":["japanese"],"らたい":["japanese"],"らっか":["japanese"],"られつ":["japanese"],"りえき":["japanese"],"りかい":["japanese"],"りきさく":["japanese"],"りきせつ":["japanese"],"りくぐん":["japanese"],"りくつ":["japanese"],"りけん":["japanese"],"りこう":["japanese"],"りせい":["japanese"],"りそう":["japanese"],"りそく":["japanese"],"りてん":["japanese"],"りねん":["japanese"],"りゆう":["japanese"],"りゅうがく":["japanese"],"りよう":["japanese"],"りょうり":["japanese"],"りょかん":["japanese"],"りょくちゃ":["japanese"],"りょこう":["japanese"],"りりく":["japanese"],"りれき":["japanese"],"りろん":["japanese"],"りんご":["japanese"],"るいけい":["japanese"],"るいさい":["japanese"],"るいじ":["japanese"],"るいせき":["japanese"],"るすばん":["japanese"],"るりがわら":["japanese"],"れいかん":["japanese"],"れいぎ":["japanese"],"れいせい":["japanese"],"れいぞうこ":["japanese"],"れいとう":["japanese"],"れいぼう":["japanese"],"れきし":["japanese"],"れきだい":["japanese"],"れんあい":["japanese"],"れんけい":["japanese"],"れんこん":["japanese"],"れんさい":["japanese"],"れんしゅう":["japanese"],"れんぞく":["japanese"],"れんらく":["japanese"],"ろうか":["japanese"],"ろうご":["japanese"],"ろうじん":["japanese"],"ろうそく":["japanese"],"ろくが":["japanese"],"ろこつ":["japanese"],"ろじうら":["japanese"],"ろしゅつ":["japanese"],"ろせん":["japanese"],"ろてん":["japanese"],"ろめん":["japanese"],"ろれつ":["japanese"],"ろんぎ":["japanese"],"ろんぱ":["japanese"],"ろんぶん":["japanese"],"ろんり":["japanese"],"わかす":["japanese"],"わかめ":["japanese"],"わかやま":["japanese"],"わかれる":["japanese"],"わしつ":["japanese"],"わじまし":["japanese"],"わすれもの":["japanese"],"わらう":["japanese"],"われる":["japanese"],"가격":["korean"],"가끔":["korean"],"가난":["korean"],"가능":["korean"],"가득":["korean"],"가르침":["korean"],"가뭄":["korean"],"가방":["korean"],"가상":["korean"],"가슴":["korean"],"가운데":["korean"],"가을":["korean"],"가이드":["korean"],"가입":["korean"],"가장":["korean"],"가정":["korean"],"가족":["korean"],"가죽":["korean"],"각오":["korean"],"각자":["korean"],"간격":["korean"],"간부":["korean"],"간섭":["korean"],"간장":["korean"],"간접":["korean"],"간판":["korean"],"갈등":["korean"],"갈비":["korean"],"갈색":["korean"],"갈증":["korean"],"감각":["korean"],"감기":["korean"],"감소":["korean"],"감수성":["korean"],"감자":["korean"],"감정":["korean"],"갑자기":["korean"],"강남":["korean"],"강당":["korean"],"강도":["korean"],"강력히":["korean"],"강변":["korean"],"강북":["korean"],"강사":["korean"],"강수량":["korean"],"강아지":["korean"],"강원도":["korean"],"강의":["korean"],"강제":["korean"],"강조":["korean"],"같이":["korean"],"개구리":["korean"],"개나리":["korean"],"개방":["korean"],"개별":["korean"],"개선":["korean"],"개성":["korean"],"개인":["korean"],"객관적":["korean"],"거실":["korean"],"거액":["korean"],"거울":["korean"],"거짓":["korean"],"거품":["korean"],"걱정":["korean"],"건강":["korean"],"건물":["korean"],"건설":["korean"],"건조":["korean"],"건축":["korean"],"걸음":["korean"],"검사":["korean"],"검토":["korean"],"게시판":["korean"],"게임":["korean"],"겨울":["korean"],"견해":["korean"],"결과":["korean"],"결국":["korean"],"결론":["korean"],"결석":["korean"],"결승":["korean"],"결심":["korean"],"결정":["korean"],"결혼":["korean"],"경계":["korean"],"경고":["korean"],"경기":["korean"],"경력":["korean"],"경복궁":["korean"],"경비":["korean"],"경상도":["korean"],"경영":["korean"],"경우":["korean"],"경쟁":["korean"],"경제":["korean"],"경주":["korean"],"경찰":["korean"],"경치":["korean"],"경향":["korean"],"경험":["korean"],"계곡":["korean"],"계단":["korean"],"계란":["korean"],"계산":["korean"],"계속":["korean"],"계약":["korean"],"계절":["korean"],"계층":["korean"],"계획":["korean"],"고객":["korean"],"고구려":["korean"],"고궁":["korean"],"고급":["korean"],"고등학생":["korean"],"고무신":["korean"],"고민":["korean"],"고양이":["korean"],"고장":["korean"],"고전":["korean"],"고집":["korean"],"고춧가루":["korean"],"고통":["korean"],"고향":["korean"],"곡식":["korean"],"골목":["korean"],"골짜기":["korean"],"골프":["korean"],"공간":["korean"],"공개":["korean"],"공격":["korean"],"공군":["korean"],"공급":["korean"],"공기":["korean"],"공동":["korean"],"공무원":["korean"],"공부":["korean"],"공사":["korean"],"공식":["korean"],"공업":["korean"],"공연":["korean"],"공원":["korean"],"공장":["korean"],"공짜":["korean"],"공책":["korean"],"공통":["korean"],"공포":["korean"],"공항":["korean"],"공휴일":["korean"],"과목":["korean"],"과일":["korean"],"과장":["korean"],"과정":["korean"],"과학":["korean"],"관객":["korean"],"관계":["korean"],"관광":["korean"],"관념":["korean"],"관람":["korean"],"관련":["korean"],"관리":["korean"],"관습":["korean"],"관심":["korean"],"관점":["korean"],"관찰":["korean"],"광경":["korean"],"광고":["korean"],"광장":["korean"],"광주":["korean"],"괴로움":["korean"],"굉장히":["korean"],"교과서":["korean"],"교문":["korean"],"교복":["korean"],"교실":["korean"],"교양":["korean"],"교육":["korean"],"교장":["korean"],"교직":["korean"],"교통":["korean"],"교환":["korean"],"교훈":["korean"],"구경":["korean"],"구름":["korean"],"구멍":["korean"],"구별":["korean"],"구분":["korean"],"구석":["korean"],"구성":["korean"],"구속":["korean"],"구역":["korean"],"구입":["korean"],"구청":["korean"],"구체적":["korean"],"국가":["korean"],"국기":["korean"],"국내":["korean"],"국립":["korean"],"국물":["korean"],"국민":["korean"],"국수":["korean"],"국어":["korean"],"국왕":["korean"],"국적":["korean"],"국제":["korean"],"국회":["korean"],"군대":["korean"],"군사":["korean"],"군인":["korean"],"궁극적":["korean"],"권리":["korean"],"권위":["korean"],"권투":["korean"],"귀국":["korean"],"귀신":["korean"],"규정":["korean"],"규칙":["korean"],"균형":["korean"],"그날":["korean"],"그냥":["korean"],"그늘":["korean"],"그러나":["korean"],"그룹":["korean"],"그릇":["korean"],"그림":["korean"],"그제서야":["korean"],"그토록":["korean"],"극복":["korean"],"극히":["korean"],"근거":["korean"],"근교":["korean"],"근래":["korean"],"근로":["korean"],"근무":["korean"],"근본":["korean"],"근원":["korean"],"근육":["korean"],"근처":["korean"],"글씨":["korean"],"글자":["korean"],"금강산":["korean"],"금고":["korean"],"금년":["korean"],"금메달":["korean"],"금액":["korean"],"금연":["korean"],"금요일":["korean"],"금지":["korean"],"긍정적":["korean"],"기간":["korean"],"기관":["korean"],"기념":["korean"],"기능":["korean"],"기독교":["korean"],"기둥":["korean"],"기록":["korean"],"기름":["korean"],"기법":["korean"],"기본":["korean"],"기분":["korean"],"기쁨":["korean"],"기숙사":["korean"],"기술":["korean"],"기억":["korean"],"기업":["korean"],"기온":["korean"],"기운":["korean"],"기원":["korean"],"기적":["korean"],"기준":["korean"],"기침":["korean"],"기혼":["korean"],"기획":["korean"],"긴급":["korean"],"긴장":["korean"],"길이":["korean"],"김밥":["korean"],"김치":["korean"],"김포공항":["korean"],"깍두기":["korean"],"깜빡":["korean"],"깨달음":["korean"],"깨소금":["korean"],"껍질":["korean"],"꼭대기":["korean"],"꽃잎":["korean"],"나들이":["korean"],"나란히":["korean"],"나머지":["korean"],"나물":["korean"],"나침반":["korean"],"나흘":["korean"],"낙엽":["korean"],"난방":["korean"],"날개":["korean"],"날씨":["korean"],"날짜":["korean"],"남녀":["korean"],"남대문":["korean"],"남매":["korean"],"남산":["korean"],"남자":["korean"],"남편":["korean"],"남학생":["korean"],"낭비":["korean"],"낱말":["korean"],"내년":["korean"],"내용":["korean"],"내일":["korean"],"냄비":["korean"],"냄새":["korean"],"냇물":["korean"],"냉동":["korean"],"냉면":["korean"],"냉방":["korean"],"냉장고":["korean"],"넥타이":["korean"],"넷째":["korean"],"노동":["korean"],"노란색":["korean"],"노력":["korean"],"노인":["korean"],"녹음":["korean"],"녹차":["korean"],"녹화":["korean"],"논리":["korean"],"논문":["korean"],"논쟁":["korean"],"놀이":["korean"],"농구":["korean"],"농담":["korean"],"농민":["korean"],"농부":["korean"],"농업":["korean"],"농장":["korean"],"농촌":["korean"],"높이":["korean"],"눈동자":["korean"],"눈물":["korean"],"눈썹":["korean"],"뉴욕":["korean"],"느낌":["korean"],"늑대":["korean"],"능동적":["korean"],"능력":["korean"],"다방":["korean"],"다양성":["korean"],"다음":["korean"],"다이어트":["korean"],"다행":["korean"],"단계":["korean"],"단골":["korean"],"단독":["korean"],"단맛":["korean"],"단순":["korean"],"단어":["korean"],"단위":["korean"],"단점":["korean"],"단체":["korean"],"단추":["korean"],"단편":["korean"],"단풍":["korean"],"달걀":["korean"],"달러":["korean"],"달력":["korean"],"달리":["korean"],"닭고기":["korean"],"담당":["korean"],"담배":["korean"],"담요":["korean"],"담임":["korean"],"답변":["korean"],"답장":["korean"],"당근":["korean"],"당분간":["korean"],"당연히":["korean"],"당장":["korean"],"대규모":["korean"],"대낮":["korean"],"대단히":["korean"],"대답":["korean"],"대도시":["korean"],"대략":["korean"],"대량":["korean"],"대륙":["korean"],"대문":["korean"],"대부분":["korean"],"대신":["korean"],"대응":["korean"],"대장":["korean"],"대전":["korean"],"대접":["korean"],"대중":["korean"],"대책":["korean"],"대출":["korean"],"대충":["korean"],"대통령":["korean"],"대학":["korean"],"대한민국":["korean"],"대합실":["korean"],"대형":["korean"],"덩어리":["korean"],"데이트":["korean"],"도대체":["korean"],"도덕":["korean"],"도둑":["korean"],"도망":["korean"],"도서관":["korean"],"도심":["korean"],"도움":["korean"],"도입":["korean"],"도자기":["korean"],"도저히":["korean"],"도전":["korean"],"도중":["korean"],"도착":["korean"],"독감":["korean"],"독립":["korean"],"독서":["korean"],"독일":["korean"],"독창적":["korean"],"동화책":["korean"],"뒷모습":["korean"],"뒷산":["korean"],"딸아이":["korean"],"마누라":["korean"],"마늘":["korean"],"마당":["korean"],"마라톤":["korean"],"마련":["korean"],"마무리":["korean"],"마사지":["korean"],"마약":["korean"],"마요네즈":["korean"],"마을":["korean"],"마음":["korean"],"마이크":["korean"],"마중":["korean"],"마지막":["korean"],"마찬가지":["korean"],"마찰":["korean"],"마흔":["korean"],"막걸리":["korean"],"막내":["korean"],"막상":["korean"],"만남":["korean"],"만두":["korean"],"만세":["korean"],"만약":["korean"],"만일":["korean"],"만점":["korean"],"만족":["korean"],"만화":["korean"],"많이":["korean"],"말기":["korean"],"말씀":["korean"],"말투":["korean"],"맘대로":["korean"],"망원경":["korean"],"매년":["korean"],"매달":["korean"],"매력":["korean"],"매번":["korean"],"매스컴":["korean"],"매일":["korean"],"매장":["korean"],"맥주":["korean"],"먹이":["korean"],"먼저":["korean"],"먼지":["korean"],"멀리":["korean"],"메일":["korean"],"며느리":["korean"],"며칠":["korean"],"면담":["korean"],"멸치":["korean"],"명단":["korean"],"명령":["korean"],"명예":["korean"],"명의":["korean"],"명절":["korean"],"명칭":["korean"],"명함":["korean"],"모금":["korean"],"모니터":["korean"],"모델":["korean"],"모든":["korean"],"모범":["korean"],"모습":["korean"],"모양":["korean"],"모임":["korean"],"모조리":["korean"],"모집":["korean"],"모퉁이":["korean"],"목걸이":["korean"],"목록":["korean"],"목사":["korean"],"목소리":["korean"],"목숨":["korean"],"목적":["korean"],"목표":["korean"],"몰래":["korean"],"몸매":["korean"],"몸무게":["korean"],"몸살":["korean"],"몸속":["korean"],"몸짓":["korean"],"몸통":["korean"],"몹시":["korean"],"무관심":["korean"],"무궁화":["korean"],"무더위":["korean"],"무덤":["korean"],"무릎":["korean"],"무슨":["korean"],"무엇":["korean"],"무역":["korean"],"무용":["korean"],"무조건":["korean"],"무지개":["korean"],"무척":["korean"],"문구":["korean"],"문득":["korean"],"문법":["korean"],"문서":["korean"],"문제":["korean"],"문학":["korean"],"문화":["korean"],"물가":["korean"],"물건":["korean"],"물결":["korean"],"물고기":["korean"],"물론":["korean"],"물리학":["korean"],"물음":["korean"],"물질":["korean"],"물체":["korean"],"미국":["korean"],"미디어":["korean"],"미사일":["korean"],"미술":["korean"],"미역":["korean"],"미용실":["korean"],"미움":["korean"],"미인":["korean"],"미팅":["korean"],"미혼":["korean"],"민간":["korean"],"민족":["korean"],"민주":["korean"],"믿음":["korean"],"밀가루":["korean"],"밀리미터":["korean"],"밑바닥":["korean"],"바가지":["korean"],"바구니":["korean"],"바나나":["korean"],"바늘":["korean"],"바닥":["korean"],"바닷가":["korean"],"바람":["korean"],"바이러스":["korean"],"바탕":["korean"],"박물관":["korean"],"박사":["korean"],"박수":["korean"],"반대":["korean"],"반드시":["korean"],"반말":["korean"],"반발":["korean"],"반성":["korean"],"반응":["korean"],"반장":["korean"],"반죽":["korean"],"반지":["korean"],"반찬":["korean"],"받침":["korean"],"발가락":["korean"],"발걸음":["korean"],"발견":["korean"],"발달":["korean"],"발레":["korean"],"발목":["korean"],"발바닥":["korean"],"발생":["korean"],"발음":["korean"],"발자국":["korean"],"발전":["korean"],"발톱":["korean"],"발표":["korean"],"밤하늘":["korean"],"밥그릇":["korean"],"밥맛":["korean"],"밥상":["korean"],"밥솥":["korean"],"방금":["korean"],"방면":["korean"],"방문":["korean"],"방바닥":["korean"],"방법":["korean"],"방송":["korean"],"방식":["korean"],"방안":["korean"],"방울":["korean"],"방지":["korean"],"방학":["korean"],"방해":["korean"],"방향":["korean"],"배경":["korean"],"배꼽":["korean"],"배달":["korean"],"배드민턴":["korean"],"백두산":["korean"],"백색":["korean"],"백성":["korean"],"백인":["korean"],"백제":["korean"],"백화점":["korean"],"버릇":["korean"],"버섯":["korean"],"버튼":["korean"],"번개":["korean"],"번역":["korean"],"번지":["korean"],"번호":["korean"],"벌금":["korean"],"벌레":["korean"],"벌써":["korean"],"범위":["korean"],"범인":["korean"],"범죄":["korean"],"법률":["korean"],"법원":["korean"],"법적":["korean"],"법칙":["korean"],"베이징":["korean"],"벨트":["korean"],"변경":["korean"],"변동":["korean"],"변명":["korean"],"변신":["korean"],"변호사":["korean"],"변화":["korean"],"별도":["korean"],"별명":["korean"],"별일":["korean"],"병실":["korean"],"병아리":["korean"],"병원":["korean"],"보관":["korean"],"보너스":["korean"],"보라색":["korean"],"보람":["korean"],"보름":["korean"],"보상":["korean"],"보안":["korean"],"보자기":["korean"],"보장":["korean"],"보전":["korean"],"보존":["korean"],"보통":["korean"],"보편적":["korean"],"보험":["korean"],"복도":["korean"],"복사":["korean"],"복숭아":["korean"],"복습":["korean"],"볶음":["korean"],"본격적":["korean"],"본래":["korean"],"본부":["korean"],"본사":["korean"],"본성":["korean"],"본인":["korean"],"본질":["korean"],"볼펜":["korean"],"봉사":["korean"],"봉지":["korean"],"봉투":["korean"],"부근":["korean"],"부끄러움":["korean"],"부담":["korean"],"부동산":["korean"],"부문":["korean"],"부분":["korean"],"부산":["korean"],"부상":["korean"],"부엌":["korean"],"부인":["korean"],"부작용":["korean"],"부장":["korean"],"부정":["korean"],"부족":["korean"],"부지런히":["korean"],"부친":["korean"],"부탁":["korean"],"부품":["korean"],"부회장":["korean"],"북부":["korean"],"북한":["korean"],"분노":["korean"],"분량":["korean"],"분리":["korean"],"분명":["korean"],"분석":["korean"],"분야":["korean"],"분위기":["korean"],"분필":["korean"],"분홍색":["korean"],"불고기":["korean"],"불과":["korean"],"불교":["korean"],"불꽃":["korean"],"불만":["korean"],"불법":["korean"],"불빛":["korean"],"불안":["korean"],"불이익":["korean"],"불행":["korean"],"브랜드":["korean"],"비극":["korean"],"비난":["korean"],"비닐":["korean"],"비둘기":["korean"],"비디오":["korean"],"비로소":["korean"],"비만":["korean"],"비명":["korean"],"비밀":["korean"],"비바람":["korean"],"비빔밥":["korean"],"비상":["korean"],"비용":["korean"],"비율":["korean"],"비중":["korean"],"비타민":["korean"],"비판":["korean"],"빌딩":["korean"],"빗물":["korean"],"빗방울":["korean"],"빗줄기":["korean"],"빛깔":["korean"],"빨간색":["korean"],"빨래":["korean"],"빨리":["korean"],"사건":["korean"],"사계절":["korean"],"사나이":["korean"],"사냥":["korean"],"사람":["korean"],"사랑":["korean"],"사립":["korean"],"사모님":["korean"],"사물":["korean"],"사방":["korean"],"사상":["korean"],"사생활":["korean"],"사설":["korean"],"사슴":["korean"],"사실":["korean"],"사업":["korean"],"사용":["korean"],"사월":["korean"],"사장":["korean"],"사전":["korean"],"사진":["korean"],"사촌":["korean"],"사춘기":["korean"],"사탕":["korean"],"사투리":["korean"],"사흘":["korean"],"산길":["korean"],"산부인과":["korean"],"산업":["korean"],"산책":["korean"],"살림":["korean"],"살인":["korean"],"살짝":["korean"],"삼계탕":["korean"],"삼국":["korean"],"삼십":["korean"],"삼월":["korean"],"삼촌":["korean"],"상관":["korean"],"상금":["korean"],"상대":["korean"],"상류":["korean"],"상반기":["korean"],"상상":["korean"],"상식":["korean"],"상업":["korean"],"상인":["korean"],"상자":["korean"],"상점":["korean"],"상처":["korean"],"상추":["korean"],"상태":["korean"],"상표":["korean"],"상품":["korean"],"상황":["korean"],"새벽":["korean"],"색깔":["korean"],"색연필":["korean"],"생각":["korean"],"생명":["korean"],"생물":["korean"],"생방송":["korean"],"생산":["korean"],"생선":["korean"],"생신":["korean"],"생일":["korean"],"생활":["korean"],"서랍":["korean"],"서른":["korean"],"서명":["korean"],"서민":["korean"],"서비스":["korean"],"서양":["korean"],"서울":["korean"],"서적":["korean"],"서점":["korean"],"서쪽":["korean"],"서클":["korean"],"석사":["korean"],"석유":["korean"],"선거":["korean"],"선물":["korean"],"선배":["korean"],"선생":["korean"],"선수":["korean"],"선원":["korean"],"선장":["korean"],"선전":["korean"],"선택":["korean"],"선풍기":["korean"],"설거지":["korean"],"설날":["korean"],"설렁탕":["korean"],"설명":["korean"],"설문":["korean"],"설사":["korean"],"설악산":["korean"],"설치":["korean"],"설탕":["korean"],"섭씨":["korean"],"성공":["korean"],"성당":["korean"],"성명":["korean"],"성별":["korean"],"성인":["korean"],"성장":["korean"],"성적":["korean"],"성질":["korean"],"성함":["korean"],"세금":["korean"],"세미나":["korean"],"세상":["korean"],"세월":["korean"],"세종대왕":["korean"],"세탁":["korean"],"센터":["korean"],"센티미터":["korean"],"셋째":["korean"],"소규모":["korean"],"소극적":["korean"],"소금":["korean"],"소나기":["korean"],"소년":["korean"],"소득":["korean"],"소망":["korean"],"소문":["korean"],"소설":["korean"],"소속":["korean"],"소아과":["korean"],"소용":["korean"],"소원":["korean"],"소음":["korean"],"소중히":["korean"],"소지품":["korean"],"소질":["korean"],"소풍":["korean"],"소형":["korean"],"속담":["korean"],"속도":["korean"],"속옷":["korean"],"손가락":["korean"],"손길":["korean"],"손녀":["korean"],"손님":["korean"],"손등":["korean"],"손목":["korean"],"손뼉":["korean"],"손실":["korean"],"손질":["korean"],"손톱":["korean"],"손해":["korean"],"솔직히":["korean"],"솜씨":["korean"],"송아지":["korean"],"송이":["korean"],"송편":["korean"],"쇠고기":["korean"],"쇼핑":["korean"],"수건":["korean"],"수년":["korean"],"수단":["korean"],"수돗물":["korean"],"수동적":["korean"],"수면":["korean"],"수명":["korean"],"수박":["korean"],"수상":["korean"],"수석":["korean"],"수술":["korean"],"수시로":["korean"],"수업":["korean"],"수염":["korean"],"수영":["korean"],"수입":["korean"],"수준":["korean"],"수집":["korean"],"수출":["korean"],"수컷":["korean"],"수필":["korean"],"수학":["korean"],"수험생":["korean"],"수화기":["korean"],"숙녀":["korean"],"숙소":["korean"],"숙제":["korean"],"순간":["korean"],"순서":["korean"],"순수":["korean"],"순식간":["korean"],"순위":["korean"],"숟가락":["korean"],"술병":["korean"],"술집":["korean"],"숫자":["korean"],"스님":["korean"],"스물":["korean"],"스스로":["korean"],"스승":["korean"],"스웨터":["korean"],"스위치":["korean"],"스케이트":["korean"],"스튜디오":["korean"],"스트레스":["korean"],"스포츠":["korean"],"슬쩍":["korean"],"슬픔":["korean"],"습관":["korean"],"습기":["korean"],"승객":["korean"],"승리":["korean"],"승부":["korean"],"승용차":["korean"],"승진":["korean"],"시각":["korean"],"시간":["korean"],"시골":["korean"],"시금치":["korean"],"시나리오":["korean"],"시댁":["korean"],"시리즈":["korean"],"시멘트":["korean"],"시민":["korean"],"시부모":["korean"],"시선":["korean"],"시설":["korean"],"시스템":["korean"],"시아버지":["korean"],"시어머니":["korean"],"시월":["korean"],"시인":["korean"],"시일":["korean"],"시작":["korean"],"시장":["korean"],"시절":["korean"],"시점":["korean"],"시중":["korean"],"시즌":["korean"],"시집":["korean"],"시청":["korean"],"시합":["korean"],"시험":["korean"],"식구":["korean"],"식기":["korean"],"식당":["korean"],"식량":["korean"],"식료품":["korean"],"식물":["korean"],"식빵":["korean"],"식사":["korean"],"식생활":["korean"],"식초":["korean"],"식탁":["korean"],"식품":["korean"],"신고":["korean"],"신규":["korean"],"신념":["korean"],"신문":["korean"],"신발":["korean"],"신비":["korean"],"신사":["korean"],"신세":["korean"],"신용":["korean"],"신제품":["korean"],"신청":["korean"],"신체":["korean"],"신화":["korean"],"실감":["korean"],"실내":["korean"],"실력":["korean"],"실례":["korean"],"실망":["korean"],"실수":["korean"],"실습":["korean"],"실시":["korean"],"실장":["korean"],"실정":["korean"],"실질적":["korean"],"실천":["korean"],"실체":["korean"],"실컷":["korean"],"실태":["korean"],"실패":["korean"],"실험":["korean"],"실현":["korean"],"심리":["korean"],"심부름":["korean"],"심사":["korean"],"심장":["korean"],"심정":["korean"],"심판":["korean"],"쌍둥이":["korean"],"씨름":["korean"],"씨앗":["korean"],"아가씨":["korean"],"아나운서":["korean"],"아드님":["korean"],"아들":["korean"],"아쉬움":["korean"],"아스팔트":["korean"],"아시아":["korean"],"아울러":["korean"],"아저씨":["korean"],"아줌마":["korean"],"아직":["korean"],"아침":["korean"],"아파트":["korean"],"아프리카":["korean"],"아픔":["korean"],"아홉":["korean"],"아흔":["korean"],"악기":["korean"],"악몽":["korean"],"악수":["korean"],"안개":["korean"],"안경":["korean"],"안과":["korean"],"안내":["korean"],"안녕":["korean"],"안동":["korean"],"안방":["korean"],"안부":["korean"],"안주":["korean"],"알루미늄":["korean"],"알코올":["korean"],"암시":["korean"],"암컷":["korean"],"압력":["korean"],"앞날":["korean"],"앞문":["korean"],"애인":["korean"],"애정":["korean"],"액수":["korean"],"앨범":["korean"],"야간":["korean"],"야단":["korean"],"야옹":["korean"],"약간":["korean"],"약국":["korean"],"약속":["korean"],"약수":["korean"],"약점":["korean"],"약품":["korean"],"약혼녀":["korean"],"양념":["korean"],"양력":["korean"],"양말":["korean"],"양배추":["korean"],"양주":["korean"],"양파":["korean"],"어둠":["korean"],"어려움":["korean"],"어른":["korean"],"어젯밤":["korean"],"어쨌든":["korean"],"어쩌다가":["korean"],"어쩐지":["korean"],"언니":["korean"],"언덕":["korean"],"언론":["korean"],"언어":["korean"],"얼굴":["korean"],"얼른":["korean"],"얼음":["korean"],"얼핏":["korean"],"엄마":["korean"],"업무":["korean"],"업종":["korean"],"업체":["korean"],"엉덩이":["korean"],"엉망":["korean"],"엉터리":["korean"],"엊그제":["korean"],"에너지":["korean"],"에어컨":["korean"],"엔진":["korean"],"여건":["korean"],"여고생":["korean"],"여관":["korean"],"여군":["korean"],"여권":["korean"],"여대생":["korean"],"여덟":["korean"],"여동생":["korean"],"여든":["korean"],"여론":["korean"],"여름":["korean"],"여섯":["korean"],"여성":["korean"],"여왕":["korean"],"여인":["korean"],"여전히":["korean"],"여직원":["korean"],"여학생":["korean"],"여행":["korean"],"역사":["korean"],"역시":["korean"],"역할":["korean"],"연결":["korean"],"연구":["korean"],"연극":["korean"],"연기":["korean"],"연락":["korean"],"연설":["korean"],"연세":["korean"],"연속":["korean"],"연습":["korean"],"연애":["korean"],"연예인":["korean"],"연인":["korean"],"연장":["korean"],"연주":["korean"],"연출":["korean"],"연필":["korean"],"연합":["korean"],"연휴":["korean"],"열기":["korean"],"열매":["korean"],"열쇠":["korean"],"열심히":["korean"],"열정":["korean"],"열차":["korean"],"열흘":["korean"],"염려":["korean"],"엽서":["korean"],"영국":["korean"],"영남":["korean"],"영상":["korean"],"영양":["korean"],"영역":["korean"],"영웅":["korean"],"영원히":["korean"],"영하":["korean"],"영향":["korean"],"영혼":["korean"],"영화":["korean"],"옆구리":["korean"],"옆방":["korean"],"옆집":["korean"],"예감":["korean"],"예금":["korean"],"예방":["korean"],"예산":["korean"],"예상":["korean"],"예선":["korean"],"예술":["korean"],"예습":["korean"],"예식장":["korean"],"예약":["korean"],"예전":["korean"],"예절":["korean"],"예정":["korean"],"예컨대":["korean"],"옛날":["korean"],"오늘":["korean"],"오락":["korean"],"오랫동안":["korean"],"오렌지":["korean"],"오로지":["korean"],"오른발":["korean"],"오븐":["korean"],"오십":["korean"],"오염":["korean"],"오월":["korean"],"오전":["korean"],"오직":["korean"],"오징어":["korean"],"오페라":["korean"],"오피스텔":["korean"],"오히려":["korean"],"옥상":["korean"],"옥수수":["korean"],"온갖":["korean"],"온라인":["korean"],"온몸":["korean"],"온종일":["korean"],"온통":["korean"],"올가을":["korean"],"올림픽":["korean"],"올해":["korean"],"옷차림":["korean"],"와이셔츠":["korean"],"와인":["korean"],"완성":["korean"],"완전":["korean"],"왕비":["korean"],"왕자":["korean"],"왜냐하면":["korean"],"왠지":["korean"],"외갓집":["korean"],"외국":["korean"],"외로움":["korean"],"외삼촌":["korean"],"외출":["korean"],"외침":["korean"],"외할머니":["korean"],"왼발":["korean"],"왼손":["korean"],"왼쪽":["korean"],"요금":["korean"],"요일":["korean"],"요즘":["korean"],"요청":["korean"],"용기":["korean"],"용서":["korean"],"용어":["korean"],"우산":["korean"],"우선":["korean"],"우승":["korean"],"우연히":["korean"],"우정":["korean"],"우체국":["korean"],"우편":["korean"],"운동":["korean"],"운명":["korean"],"운반":["korean"],"운전":["korean"],"운행":["korean"],"울산":["korean"],"울음":["korean"],"움직임":["korean"],"웃어른":["korean"],"웃음":["korean"],"워낙":["korean"],"원고":["korean"],"원래":["korean"],"원서":["korean"],"원숭이":["korean"],"원인":["korean"],"원장":["korean"],"원피스":["korean"],"월급":["korean"],"월드컵":["korean"],"월세":["korean"],"월요일":["korean"],"웨이터":["korean"],"위반":["korean"],"위법":["korean"],"위성":["korean"],"위원":["korean"],"위험":["korean"],"위협":["korean"],"윗사람":["korean"],"유난히":["korean"],"유럽":["korean"],"유명":["korean"],"유물":["korean"],"유산":["korean"],"유적":["korean"],"유치원":["korean"],"유학":["korean"],"유행":["korean"],"유형":["korean"],"육군":["korean"],"육상":["korean"],"육십":["korean"],"육체":["korean"],"은행":["korean"],"음력":["korean"],"음료":["korean"],"음반":["korean"],"음성":["korean"],"음식":["korean"],"음악":["korean"],"음주":["korean"],"의견":["korean"],"의논":["korean"],"의문":["korean"],"의복":["korean"],"의식":["korean"],"의심":["korean"],"의외로":["korean"],"의욕":["korean"],"의원":["korean"],"의학":["korean"],"이것":["korean"],"이곳":["korean"],"이념":["korean"],"이놈":["korean"],"이달":["korean"],"이대로":["korean"],"이동":["korean"],"이렇게":["korean"],"이력서":["korean"],"이론적":["korean"],"이름":["korean"],"이민":["korean"],"이발소":["korean"],"이별":["korean"],"이불":["korean"],"이빨":["korean"],"이상":["korean"],"이성":["korean"],"이슬":["korean"],"이야기":["korean"],"이용":["korean"],"이웃":["korean"],"이월":["korean"],"이윽고":["korean"],"이익":["korean"],"이전":["korean"],"이중":["korean"],"이튿날":["korean"],"이틀":["korean"],"이혼":["korean"],"인간":["korean"],"인격":["korean"],"인공":["korean"],"인구":["korean"],"인근":["korean"],"인기":["korean"],"인도":["korean"],"인류":["korean"],"인물":["korean"],"인생":["korean"],"인쇄":["korean"],"인연":["korean"],"인원":["korean"],"인재":["korean"],"인종":["korean"],"인천":["korean"],"인체":["korean"],"인터넷":["korean"],"인하":["korean"],"인형":["korean"],"일곱":["korean"],"일기":["korean"],"일단":["korean"],"일대":["korean"],"일등":["korean"],"일반":["korean"],"일본":["korean"],"일부":["korean"],"일상":["korean"],"일생":["korean"],"일손":["korean"],"일요일":["korean"],"일월":["korean"],"일정":["korean"],"일종":["korean"],"일주일":["korean"],"일찍":["korean"],"일체":["korean"],"일치":["korean"],"일행":["korean"],"일회용":["korean"],"임금":["korean"],"임무":["korean"],"입대":["korean"],"입력":["korean"],"입맛":["korean"],"입사":["korean"],"입술":["korean"],"입시":["korean"],"입원":["korean"],"입장":["korean"],"입학":["korean"],"자가용":["korean"],"자격":["korean"],"자극":["korean"],"자동":["korean"],"자랑":["korean"],"자부심":["korean"],"자식":["korean"],"자신":["korean"],"자연":["korean"],"자원":["korean"],"자율":["korean"],"자전거":["korean"],"자정":["korean"],"자존심":["korean"],"자판":["korean"],"작가":["korean"],"작년":["korean"],"작성":["korean"],"작업":["korean"],"작용":["korean"],"작은딸":["korean"],"작품":["korean"],"잔디":["korean"],"잔뜩":["korean"],"잔치":["korean"],"잘못":["korean"],"잠깐":["korean"],"잠수함":["korean"],"잠시":["korean"],"잠옷":["korean"],"잠자리":["korean"],"잡지":["korean"],"장관":["korean"],"장군":["korean"],"장기간":["korean"],"장래":["korean"],"장례":["korean"],"장르":["korean"],"장마":["korean"],"장면":["korean"],"장모":["korean"],"장미":["korean"],"장비":["korean"],"장사":["korean"],"장소":["korean"],"장식":["korean"],"장애인":["korean"],"장인":["korean"],"장점":["korean"],"장차":["korean"],"장학금":["korean"],"재능":["korean"],"재빨리":["korean"],"재산":["korean"],"재생":["korean"],"재작년":["korean"],"재정":["korean"],"재채기":["korean"],"재판":["korean"],"재학":["korean"],"재활용":["korean"],"저것":["korean"],"저고리":["korean"],"저곳":["korean"],"저녁":["korean"],"저런":["korean"],"저렇게":["korean"],"저번":["korean"],"저울":["korean"],"저절로":["korean"],"저축":["korean"],"적극":["korean"],"적당히":["korean"],"적성":["korean"],"적용":["korean"],"적응":["korean"],"전개":["korean"],"전공":["korean"],"전기":["korean"],"전달":["korean"],"전라도":["korean"],"전망":["korean"],"전문":["korean"],"전반":["korean"],"전부":["korean"],"전세":["korean"],"전시":["korean"],"전용":["korean"],"전자":["korean"],"전쟁":["korean"],"전주":["korean"],"전철":["korean"],"전체":["korean"],"전통":["korean"],"전혀":["korean"],"전후":["korean"],"절대":["korean"],"절망":["korean"],"절반":["korean"],"절약":["korean"],"절차":["korean"],"점검":["korean"],"점수":["korean"],"점심":["korean"],"점원":["korean"],"점점":["korean"],"점차":["korean"],"접근":["korean"],"접시":["korean"],"접촉":["korean"],"젓가락":["korean"],"정거장":["korean"],"정도":["korean"],"정류장":["korean"],"정리":["korean"],"정말":["korean"],"정면":["korean"],"정문":["korean"],"정반대":["korean"],"정보":["korean"],"정부":["korean"],"정비":["korean"],"정상":["korean"],"정성":["korean"],"정오":["korean"],"정원":["korean"],"정장":["korean"],"정지":["korean"],"정치":["korean"],"정확히":["korean"],"제공":["korean"],"제과점":["korean"],"제대로":["korean"],"제목":["korean"],"제발":["korean"],"제법":["korean"],"제삿날":["korean"],"제안":["korean"],"제일":["korean"],"제작":["korean"],"제주도":["korean"],"제출":["korean"],"제품":["korean"],"제한":["korean"],"조각":["korean"],"조건":["korean"],"조금":["korean"],"조깅":["korean"],"조명":["korean"],"조미료":["korean"],"조상":["korean"],"조선":["korean"],"조용히":["korean"],"조절":["korean"],"조정":["korean"],"조직":["korean"],"존댓말":["korean"],"존재":["korean"],"졸업":["korean"],"졸음":["korean"],"종교":["korean"],"종로":["korean"],"종류":["korean"],"종소리":["korean"],"종업원":["korean"],"종종":["korean"],"종합":["korean"],"좌석":["korean"],"죄인":["korean"],"주관적":["korean"],"주름":["korean"],"주말":["korean"],"주머니":["korean"],"주먹":["korean"],"주문":["korean"],"주민":["korean"],"주방":["korean"],"주변":["korean"],"주식":["korean"],"주인":["korean"],"주일":["korean"],"주장":["korean"],"주전자":["korean"],"주택":["korean"],"준비":["korean"],"줄거리":["korean"],"줄기":["korean"],"줄무늬":["korean"],"중간":["korean"],"중계방송":["korean"],"중국":["korean"],"중년":["korean"],"중단":["korean"],"중독":["korean"],"중반":["korean"],"중부":["korean"],"중세":["korean"],"중소기업":["korean"],"중순":["korean"],"중앙":["korean"],"중요":["korean"],"중학교":["korean"],"즉석":["korean"],"즉시":["korean"],"즐거움":["korean"],"증가":["korean"],"증거":["korean"],"증권":["korean"],"증상":["korean"],"증세":["korean"],"지각":["korean"],"지갑":["korean"],"지경":["korean"],"지극히":["korean"],"지금":["korean"],"지급":["korean"],"지능":["korean"],"지름길":["korean"],"지리산":["korean"],"지방":["korean"],"지붕":["korean"],"지식":["korean"],"지역":["korean"],"지우개":["korean"],"지원":["korean"],"지적":["korean"],"지점":["korean"],"지진":["korean"],"지출":["korean"],"직선":["korean"],"직업":["korean"],"직원":["korean"],"직장":["korean"],"진급":["korean"],"진동":["korean"],"진로":["korean"],"진료":["korean"],"진리":["korean"],"진짜":["korean"],"진찰":["korean"],"진출":["korean"],"진통":["korean"],"진행":["korean"],"질문":["korean"],"질병":["korean"],"질서":["korean"],"짐작":["korean"],"집단":["korean"],"집안":["korean"],"집중":["korean"],"짜증":["korean"],"찌꺼기":["korean"],"차남":["korean"],"차라리":["korean"],"차량":["korean"],"차림":["korean"],"차별":["korean"],"차선":["korean"],"차츰":["korean"],"착각":["korean"],"찬물":["korean"],"찬성":["korean"],"참가":["korean"],"참기름":["korean"],"참새":["korean"],"참석":["korean"],"참여":["korean"],"참외":["korean"],"참조":["korean"],"찻잔":["korean"],"창가":["korean"],"창고":["korean"],"창구":["korean"],"창문":["korean"],"창밖":["korean"],"창작":["korean"],"창조":["korean"],"채널":["korean"],"채점":["korean"],"책가방":["korean"],"책방":["korean"],"책상":["korean"],"책임":["korean"],"챔피언":["korean"],"처벌":["korean"],"처음":["korean"],"천국":["korean"],"천둥":["korean"],"천장":["korean"],"천재":["korean"],"천천히":["korean"],"철도":["korean"],"철저히":["korean"],"철학":["korean"],"첫날":["korean"],"첫째":["korean"],"청년":["korean"],"청바지":["korean"],"청소":["korean"],"청춘":["korean"],"체계":["korean"],"체력":["korean"],"체온":["korean"],"체육":["korean"],"체중":["korean"],"체험":["korean"],"초등학생":["korean"],"초반":["korean"],"초밥":["korean"],"초상화":["korean"],"초순":["korean"],"초여름":["korean"],"초원":["korean"],"초저녁":["korean"],"초점":["korean"],"초청":["korean"],"초콜릿":["korean"],"촛불":["korean"],"총각":["korean"],"총리":["korean"],"총장":["korean"],"촬영":["korean"],"최근":["korean"],"최상":["korean"],"최선":["korean"],"최신":["korean"],"최악":["korean"],"최종":["korean"],"추석":["korean"],"추억":["korean"],"추진":["korean"],"추천":["korean"],"추측":["korean"],"축구":["korean"],"축소":["korean"],"축제":["korean"],"축하":["korean"],"출근":["korean"],"출발":["korean"],"출산":["korean"],"출신":["korean"],"출연":["korean"],"출입":["korean"],"출장":["korean"],"출판":["korean"],"충격":["korean"],"충고":["korean"],"충돌":["korean"],"충분히":["korean"],"충청도":["korean"],"취업":["korean"],"취직":["korean"],"취향":["korean"],"치약":["korean"],"친구":["korean"],"친척":["korean"],"칠십":["korean"],"칠월":["korean"],"칠판":["korean"],"침대":["korean"],"침묵":["korean"],"침실":["korean"],"칫솔":["korean"],"칭찬":["korean"],"카메라":["korean"],"카운터":["korean"],"칼국수":["korean"],"캐릭터":["korean"],"캠퍼스":["korean"],"캠페인":["korean"],"커튼":["korean"],"컨디션":["korean"],"컬러":["korean"],"컴퓨터":["korean"],"코끼리":["korean"],"코미디":["korean"],"콘서트":["korean"],"콜라":["korean"],"콤플렉스":["korean"],"콩나물":["korean"],"쾌감":["korean"],"쿠데타":["korean"],"크림":["korean"],"큰길":["korean"],"큰딸":["korean"],"큰소리":["korean"],"큰아들":["korean"],"큰어머니":["korean"],"큰일":["korean"],"큰절":["korean"],"클래식":["korean"],"클럽":["korean"],"킬로":["korean"],"타입":["korean"],"타자기":["korean"],"탁구":["korean"],"탁자":["korean"],"탄생":["korean"],"태권도":["korean"],"태양":["korean"],"태풍":["korean"],"택시":["korean"],"탤런트":["korean"],"터널":["korean"],"터미널":["korean"],"테니스":["korean"],"테스트":["korean"],"테이블":["korean"],"텔레비전":["korean"],"토론":["korean"],"토마토":["korean"],"토요일":["korean"],"통계":["korean"],"통과":["korean"],"통로":["korean"],"통신":["korean"],"통역":["korean"],"통일":["korean"],"통장":["korean"],"통제":["korean"],"통증":["korean"],"통합":["korean"],"통화":["korean"],"퇴근":["korean"],"퇴원":["korean"],"퇴직금":["korean"],"튀김":["korean"],"트럭":["korean"],"특급":["korean"],"특별":["korean"],"특성":["korean"],"특수":["korean"],"특징":["korean"],"특히":["korean"],"튼튼히":["korean"],"티셔츠":["korean"],"파란색":["korean"],"파일":["korean"],"파출소":["korean"],"판결":["korean"],"판단":["korean"],"판매":["korean"],"판사":["korean"],"팔십":["korean"],"팔월":["korean"],"팝송":["korean"],"패션":["korean"],"팩스":["korean"],"팩시밀리":["korean"],"팬티":["korean"],"퍼센트":["korean"],"페인트":["korean"],"편견":["korean"],"편의":["korean"],"편지":["korean"],"편히":["korean"],"평가":["korean"],"평균":["korean"],"평생":["korean"],"평소":["korean"],"평양":["korean"],"평일":["korean"],"평화":["korean"],"포스터":["korean"],"포인트":["korean"],"포장":["korean"],"포함":["korean"],"표면":["korean"],"표정":["korean"],"표준":["korean"],"표현":["korean"],"품목":["korean"],"품질":["korean"],"풍경":["korean"],"풍속":["korean"],"풍습":["korean"],"프랑스":["korean"],"프린터":["korean"],"플라스틱":["korean"],"피곤":["korean"],"피망":["korean"],"피아노":["korean"],"필름":["korean"],"필수":["korean"],"필요":["korean"],"필자":["korean"],"필통":["korean"],"핑계":["korean"],"하느님":["korean"],"하늘":["korean"],"하드웨어":["korean"],"하룻밤":["korean"],"하반기":["korean"],"하숙집":["korean"],"하순":["korean"],"하여튼":["korean"],"하지만":["korean"],"하천":["korean"],"하품":["korean"],"하필":["korean"],"학과":["korean"],"학교":["korean"],"학급":["korean"],"학기":["korean"],"학년":["korean"],"학력":["korean"],"학번":["korean"],"학부모":["korean"],"학비":["korean"],"학생":["korean"],"학술":["korean"],"학습":["korean"],"학용품":["korean"],"학원":["korean"],"학위":["korean"],"학자":["korean"],"학점":["korean"],"한계":["korean"],"한글":["korean"],"한꺼번에":["korean"],"한낮":["korean"],"한눈":["korean"],"한동안":["korean"],"한때":["korean"],"한라산":["korean"],"한마디":["korean"],"한문":["korean"],"한번":["korean"],"한복":["korean"],"한식":["korean"],"한여름":["korean"],"한쪽":["korean"],"할머니":["korean"],"할아버지":["korean"],"할인":["korean"],"함께":["korean"],"함부로":["korean"],"합격":["korean"],"합리적":["korean"],"항공":["korean"],"항구":["korean"],"항상":["korean"],"항의":["korean"],"해결":["korean"],"해군":["korean"],"해답":["korean"],"해당":["korean"],"해물":["korean"],"해석":["korean"],"해설":["korean"],"해수욕장":["korean"],"해안":["korean"],"핵심":["korean"],"핸드백":["korean"],"햄버거":["korean"],"햇볕":["korean"],"햇살":["korean"],"행동":["korean"],"행복":["korean"],"행사":["korean"],"행운":["korean"],"행위":["korean"],"향기":["korean"],"향상":["korean"],"향수":["korean"],"허락":["korean"],"허용":["korean"],"헬기":["korean"],"현관":["korean"],"현금":["korean"],"현대":["korean"],"현상":["korean"],"현실":["korean"],"현장":["korean"],"현재":["korean"],"현지":["korean"],"혈액":["korean"],"협력":["korean"],"형부":["korean"],"형사":["korean"],"형수":["korean"],"형식":["korean"],"형제":["korean"],"형태":["korean"],"형편":["korean"],"혜택":["korean"],"호기심":["korean"],"호남":["korean"],"호랑이":["korean"],"호박":["korean"],"호텔":["korean"],"호흡":["korean"],"혹시":["korean"],"홀로":["korean"],"홈페이지":["korean"],"홍보":["korean"],"홍수":["korean"],"홍차":["korean"],"화면":["korean"],"화분":["korean"],"화살":["korean"],"화요일":["korean"],"화장":["korean"],"화학":["korean"],"확보":["korean"],"확인":["korean"],"확장":["korean"],"확정":["korean"],"환갑":["korean"],"환경":["korean"],"환영":["korean"],"환율":["korean"],"환자":["korean"],"활기":["korean"],"활동":["korean"],"활발히":["korean"],"활용":["korean"],"활짝":["korean"],"회견":["korean"],"회관":["korean"],"회복":["korean"],"회색":["korean"],"회원":["korean"],"회장":["korean"],"회전":["korean"],"횟수":["korean"],"횡단보도":["korean"],"효율적":["korean"],"후반":["korean"],"후춧가루":["korean"],"훈련":["korean"],"훨씬":["korean"],"휴식":["korean"],"휴일":["korean"],"흉내":["korean"],"흐름":["korean"],"흑백":["korean"],"흑인":["korean"],"흔적":["korean"],"흔히":["korean"],"흥미":["korean"],"흥분":["korean"],"희곡":["korean"],"희망":["korean"],"희생":["korean"],"흰색":["korean"],"힘껏":["korean"],"abacate":["portuguese"],"abaixo":["portuguese"],"abalar":["portuguese"],"abater":["portuguese"],"abduzir":["portuguese"],"abelha":["portuguese"],"aberto":["portuguese"],"abismo":["portuguese"],"abotoar":["portuguese"],"abranger":["portuguese"],"abreviar":["portuguese"],"abrigar":["portuguese"],"abrupto":["portuguese"],"absinto":["portuguese"],"absoluto":["portuguese"],"absurdo":["portuguese"],"abutre":["portuguese"],"acabado":["portuguese"],"acalmar":["portuguese"],"acampar":["portuguese"],"acanhar":["portuguese"],"acaso":["portuguese"],"aceitar":["portuguese"],"acelerar":["portuguese"],"acenar":["portuguese"],"acervo":["portuguese"],"acessar":["portuguese"],"acetona":["portuguese"],"achatar":["portuguese"],"acidez":["portuguese"],"acima":["portuguese"],"acionado":["portuguese"],"acirrar":["portuguese"],"aclamar":["portuguese"],"aclive":["portuguese"],"acolhida":["portuguese"],"acomodar":["portuguese"],"acoplar":["portuguese"],"acordar":["portuguese"],"acumular":["portuguese"],"acusador":["portuguese"],"adaptar":["portuguese"],"adega":["portuguese"],"adentro":["portuguese"],"adepto":["portuguese"],"adequar":["portuguese"],"aderente":["portuguese"],"adesivo":["portuguese"],"adeus":["portuguese"],"adiante":["portuguese"],"aditivo":["portuguese"],"adjetivo":["portuguese"],"adjunto":["portuguese"],"admirar":["portuguese"],"adorar":["portuguese"],"adquirir":["portuguese"],"adubo":["portuguese"],"adverso":["portuguese"],"advogado":["portuguese"],"aeronave":["portuguese"],"afastar":["portuguese"],"aferir":["portuguese"],"afetivo":["portuguese"],"afinador":["portuguese"],"afivelar":["portuguese"],"aflito":["portuguese"],"afluente":["portuguese"],"afrontar":["portuguese"],"agachar":["portuguese"],"agarrar":["portuguese"],"agasalho":["portuguese"],"agenciar":["portuguese"],"agilizar":["portuguese"],"agiota":["portuguese"],"agitado":["portuguese"],"agora":["portuguese"],"agradar":["portuguese"],"agreste":["portuguese"],"agrupar":["portuguese"],"aguardar":["portuguese"],"agulha":["portuguese"],"ajoelhar":["portuguese"],"ajudar":["portuguese"],"ajustar":["portuguese"],"alameda":["portuguese"],"alarme":["portuguese"],"alastrar":["portuguese"],"alavanca":["portuguese"],"albergue":["portuguese"],"albino":["portuguese"],"alcatra":["portuguese"],"aldeia":["portuguese"],"alecrim":["portuguese"],"alegria":["portuguese"],"alertar":["portuguese"],"alface":["portuguese"],"alfinete":["portuguese"],"algum":["portuguese"],"alheio":["portuguese"],"aliar":["portuguese"],"alicate":["portuguese"],"alienar":["portuguese"],"alinhar":["portuguese"],"aliviar":["portuguese"],"almofada":["portuguese"],"alocar":["portuguese"],"alpiste":["portuguese"],"alterar":["portuguese"],"altitude":["portuguese"],"alucinar":["portuguese"],"alugar":["portuguese"],"aluno":["portuguese"],"alusivo":["portuguese"],"alvo":["portuguese"],"amaciar":["portuguese"],"amador":["portuguese"],"amarelo":["portuguese"],"amassar":["portuguese"],"ambas":["portuguese"],"ambiente":["portuguese"],"ameixa":["portuguese"],"amenizar":["portuguese"],"amido":["portuguese"],"amistoso":["portuguese"],"amizade":["portuguese"],"amolador":["portuguese"],"amontoar":["portuguese"],"amoroso":["portuguese"],"amostra":["portuguese"],"amparar":["portuguese"],"ampliar":["portuguese"],"ampola":["portuguese"],"anagrama":["portuguese"],"analisar":["portuguese"],"anarquia":["portuguese"],"anatomia":["portuguese"],"andaime":["portuguese"],"anel":["portuguese"],"anexo":["portuguese"],"angular":["portuguese"],"animar":["portuguese"],"anjo":["portuguese"],"anomalia":["portuguese"],"anotado":["portuguese"],"ansioso":["portuguese"],"anterior":["portuguese"],"anuidade":["portuguese"],"anunciar":["portuguese"],"anzol":["portuguese"],"apagador":["portuguese"],"apalpar":["portuguese"],"apanhado":["portuguese"],"apego":["portuguese"],"apelido":["portuguese"],"apertada":["portuguese"],"apesar":["portuguese"],"apetite":["portuguese"],"apito":["portuguese"],"aplauso":["portuguese"],"aplicada":["portuguese"],"apoio":["portuguese"],"apontar":["portuguese"],"aposta":["portuguese"],"aprendiz":["portuguese"],"aprovar":["portuguese"],"aquecer":["portuguese"],"arame":["portuguese"],"aranha":["portuguese"],"arara":["portuguese"],"arcada":["portuguese"],"ardente":["portuguese"],"areia":["portuguese"],"arejar":["portuguese"],"arenito":["portuguese"],"aresta":["portuguese"],"argiloso":["portuguese"],"argola":["portuguese"],"arma":["portuguese"],"arquivo":["portuguese"],"arraial":["portuguese"],"arrebate":["portuguese"],"arriscar":["portuguese"],"arroba":["portuguese"],"arrumar":["portuguese"],"arsenal":["portuguese"],"arterial":["portuguese"],"artigo":["portuguese"],"arvoredo":["portuguese"],"asfaltar":["portuguese"],"asilado":["portuguese"],"aspirar":["portuguese"],"assador":["portuguese"],"assinar":["portuguese"],"assoalho":["portuguese"],"assunto":["portuguese"],"astral":["portuguese"],"atacado":["portuguese"],"atadura":["portuguese"],"atalho":["portuguese"],"atarefar":["portuguese"],"atear":["portuguese"],"atender":["portuguese"],"aterro":["portuguese"],"ateu":["portuguese"],"atingir":["portuguese"],"atirador":["portuguese"],"ativo":["portuguese"],"atoleiro":["portuguese"],"atracar":["portuguese"],"atrevido":["portuguese"],"atriz":["portuguese"],"atual":["portuguese"],"atum":["portuguese"],"auditor":["portuguese"],"aumentar":["portuguese"],"aura":["portuguese"],"aurora":["portuguese"],"autismo":["portuguese"],"autoria":["portuguese"],"autuar":["portuguese"],"avaliar":["portuguese"],"avante":["portuguese"],"avaria":["portuguese"],"avental":["portuguese"],"avesso":["portuguese"],"aviador":["portuguese"],"avisar":["portuguese"],"avulso":["portuguese"],"axila":["portuguese"],"azarar":["portuguese"],"azedo":["portuguese"],"azeite":["portuguese"],"azulejo":["portuguese"],"babar":["portuguese"],"babosa":["portuguese"],"bacalhau":["portuguese"],"bacharel":["portuguese"],"bacia":["portuguese"],"bagagem":["portuguese"],"baiano":["portuguese"],"bailar":["portuguese"],"baioneta":["portuguese"],"bairro":["portuguese"],"baixista":["portuguese"],"bajular":["portuguese"],"baleia":["portuguese"],"baliza":["portuguese"],"balsa":["portuguese"],"banal":["portuguese"],"bandeira":["portuguese"],"banho":["portuguese"],"banir":["portuguese"],"banquete":["portuguese"],"barato":["portuguese"],"barbado":["portuguese"],"baronesa":["portuguese"],"barraca":["portuguese"],"barulho":["portuguese"],"baseado":["portuguese"],"bastante":["portuguese"],"batata":["portuguese"],"batedor":["portuguese"],"batida":["portuguese"],"batom":["portuguese"],"batucar":["portuguese"],"baunilha":["portuguese"],"beber":["portuguese"],"beijo":["portuguese"],"beirada":["portuguese"],"beisebol":["portuguese"],"beldade":["portuguese"],"beleza":["portuguese"],"belga":["portuguese"],"beliscar":["portuguese"],"bendito":["portuguese"],"bengala":["portuguese"],"benzer":["portuguese","turkish"],"berimbau":["portuguese"],"berlinda":["portuguese"],"berro":["portuguese"],"besouro":["portuguese"],"bexiga":["portuguese"],"bezerro":["portuguese"],"bico":["portuguese"],"bicudo":["portuguese"],"bienal":["portuguese"],"bifocal":["portuguese"],"bifurcar":["portuguese"],"bigorna":["portuguese"],"bilhete":["portuguese"],"bimestre":["portuguese"],"bimotor":["portuguese"],"biologia":["portuguese"],"biombo":["portuguese"],"biosfera":["portuguese"],"bipolar":["portuguese"],"birrento":["portuguese"],"biscoito":["portuguese"],"bisneto":["portuguese"],"bispo":["portuguese"],"bissexto":["portuguese"],"bitola":["portuguese"],"bizarro":["portuguese"],"blindado":["portuguese"],"bloco":["portuguese"],"bloquear":["portuguese"],"boato":["portuguese"],"bobagem":["portuguese"],"bocado":["portuguese"],"bocejo":["portuguese"],"bochecha":["portuguese"],"boicotar":["portuguese"],"bolada":["portuguese"],"boletim":["portuguese"],"bolha":["portuguese"],"bolo":["portuguese"],"bombeiro":["portuguese"],"bonde":["portuguese"],"boneco":["portuguese"],"bonita":["portuguese"],"borbulha":["portuguese"],"borda":["portuguese"],"boreal":["portuguese"],"borracha":["portuguese"],"bovino":["portuguese"],"boxeador":["portuguese"],"branco":["portuguese"],"brasa":["portuguese"],"braveza":["portuguese"],"breu":["portuguese"],"briga":["portuguese"],"brilho":["portuguese"],"brincar":["portuguese"],"broa":["portuguese"],"brochura":["portuguese"],"bronzear":["portuguese"],"broto":["portuguese"],"bruxo":["portuguese"],"bucha":["portuguese"],"budismo":["portuguese"],"bufar":["portuguese"],"bule":["portuguese"],"buraco":["portuguese"],"busca":["portuguese"],"busto":["portuguese"],"buzina":["portuguese"],"cabana":["portuguese"],"cabelo":["portuguese"],"cabide":["portuguese"],"cabo":["portuguese"],"cabrito":["portuguese"],"cacau":["portuguese"],"cacetada":["portuguese"],"cachorro":["portuguese"],"cacique":["portuguese"],"cadastro":["portuguese"],"cadeado":["portuguese"],"cafezal":["portuguese"],"caiaque":["portuguese"],"caipira":["portuguese"],"caixote":["portuguese"],"cajado":["portuguese"],"caju":["portuguese"],"calafrio":["portuguese"],"calcular":["portuguese"],"caldeira":["portuguese"],"calibrar":["portuguese"],"calmante":["portuguese"],"calota":["portuguese"],"camada":["portuguese"],"cambista":["portuguese"],"camisa":["portuguese"],"camomila":["portuguese"],"campanha":["portuguese"],"camuflar":["portuguese"],"canavial":["portuguese"],"cancelar":["portuguese"],"caneta":["portuguese"],"canguru":["portuguese"],"canhoto":["portuguese"],"canivete":["portuguese"],"canoa":["portuguese"],"cansado":["portuguese"],"cantar":["portuguese"],"canudo":["portuguese"],"capacho":["portuguese"],"capela":["portuguese"],"capinar":["portuguese"],"capotar":["portuguese"],"capricho":["portuguese"],"captador":["portuguese"],"capuz":["portuguese"],"caracol":["portuguese"],"carbono":["portuguese"],"cardeal":["portuguese"],"careca":["portuguese"],"carimbar":["portuguese"],"carneiro":["portuguese"],"carpete":["portuguese"],"carreira":["portuguese"],"cartaz":["portuguese"],"carvalho":["portuguese"],"casaco":["portuguese"],"casca":["portuguese"],"casebre":["portuguese"],"castelo":["portuguese"],"casulo":["portuguese"],"catarata":["portuguese"],"cativar":["portuguese"],"caule":["portuguese"],"causador":["portuguese"],"cautelar":["portuguese"],"cavalo":["portuguese"],"caverna":["portuguese"],"cebola":["portuguese"],"cedilha":["portuguese"],"cegonha":["portuguese"],"celebrar":["portuguese"],"celular":["portuguese"],"cenoura":["portuguese"],"censo":["portuguese"],"centeio":["portuguese"],"cercar":["portuguese"],"cerrado":["portuguese"],"certeiro":["portuguese"],"cerveja":["portuguese"],"cetim":["portuguese"],"cevada":["portuguese"],"chacota":["portuguese"],"chaleira":["portuguese"],"chamado":["portuguese"],"chapada":["portuguese"],"charme":["portuguese"],"chatice":["portuguese"],"chave":["portuguese"],"chefe":["portuguese"],"chegada":["portuguese"],"cheiro":["portuguese"],"cheque":["portuguese"],"chicote":["portuguese"],"chifre":["portuguese"],"chinelo":["portuguese"],"chocalho":["portuguese"],"chover":["portuguese"],"chumbo":["portuguese"],"chutar":["portuguese"],"chuva":["portuguese"],"cicatriz":["portuguese"],"ciclone":["portuguese"],"cidade":["portuguese"],"cidreira":["portuguese"],"ciente":["portuguese"],"cigana":["portuguese"],"cimento":["portuguese"],"cinto":["portuguese"],"cinza":["portuguese"],"ciranda":["portuguese"],"circuito":["portuguese"],"cirurgia":["portuguese"],"citar":["portuguese"],"clareza":["portuguese"],"clero":["portuguese"],"clicar":["portuguese"],"clone":["portuguese"],"clube":["portuguese"],"coado":["portuguese"],"coagir":["portuguese"],"cobaia":["portuguese"],"cobertor":["portuguese"],"cobrar":["portuguese"],"cocada":["portuguese"],"coelho":["portuguese"],"coentro":["portuguese"],"coeso":["portuguese"],"cogumelo":["portuguese"],"coibir":["portuguese"],"coifa":["portuguese"],"coiote":["portuguese"],"colar":["portuguese"],"coleira":["portuguese"],"colher":["portuguese"],"colidir":["portuguese"],"colmeia":["portuguese"],"colono":["portuguese"],"coluna":["portuguese"],"comando":["portuguese"],"combinar":["portuguese"],"comentar":["portuguese"],"comitiva":["portuguese"],"comover":["portuguese"],"complexo":["portuguese"],"comum":["portuguese"],"concha":["portuguese"],"condor":["portuguese"],"conectar":["portuguese"],"confuso":["portuguese"],"congelar":["portuguese"],"conhecer":["portuguese"],"conjugar":["portuguese"],"consumir":["portuguese"],"contrato":["portuguese"],"convite":["portuguese"],"cooperar":["portuguese"],"copeiro":["portuguese"],"copiador":["portuguese"],"copo":["portuguese"],"coquetel":["portuguese"],"coragem":["portuguese"],"cordial":["portuguese"],"corneta":["portuguese"],"coronha":["portuguese"],"corporal":["portuguese"],"correio":["portuguese"],"cortejo":["portuguese"],"coruja":["portuguese"],"corvo":["portuguese"],"cosseno":["portuguese"],"costela":["portuguese"],"cotonete":["portuguese"],"couro":["portuguese"],"couve":["portuguese"],"covil":["portuguese"],"cozinha":["portuguese"],"cratera":["portuguese"],"cravo":["portuguese"],"creche":["portuguese"],"credor":["portuguese"],"creme":["portuguese"],"crer":["portuguese"],"crespo":["portuguese"],"criada":["portuguese"],"criminal":["portuguese"],"crioulo":["portuguese"],"crise":["portuguese"],"criticar":["portuguese"],"crosta":["portuguese"],"crua":["portuguese"],"cruzeiro":["portuguese"],"cubano":["portuguese"],"cueca":["portuguese"],"cuidado":["portuguese"],"cujo":["portuguese"],"culatra":["portuguese"],"culminar":["portuguese"],"culpar":["portuguese"],"cultura":["portuguese"],"cumprir":["portuguese"],"cunhado":["portuguese"],"cupido":["portuguese"],"curativo":["portuguese"],"curral":["portuguese"],"cursar":["portuguese"],"curto":["portuguese"],"cuspir":["portuguese"],"custear":["portuguese"],"cutelo":["portuguese"],"damasco":["portuguese"],"datar":["portuguese"],"debater":["portuguese"],"debitar":["portuguese"],"deboche":["portuguese"],"debulhar":["portuguese"],"decalque":["portuguese"],"decimal":["portuguese"],"declive":["portuguese"],"decote":["portuguese"],"decretar":["portuguese"],"dedal":["portuguese"],"dedicado":["portuguese"],"deduzir":["portuguese"],"defesa":["portuguese"],"defumar":["portuguese"],"degelo":["portuguese"],"degrau":["portuguese"],"degustar":["portuguese"],"deitado":["portuguese"],"deixar":["portuguese"],"delator":["portuguese"],"delegado":["portuguese"],"delinear":["portuguese"],"delonga":["portuguese"],"demanda":["portuguese"],"demitir":["portuguese"],"demolido":["portuguese"],"dentista":["portuguese"],"depenado":["portuguese"],"depilar":["portuguese"],"depois":["portuguese"],"depressa":["portuguese"],"depurar":["portuguese"],"deriva":["portuguese"],"derramar":["portuguese"],"desafio":["portuguese"],"desbotar":["portuguese"],"descanso":["portuguese"],"desenho":["portuguese"],"desfiado":["portuguese"],"desgaste":["portuguese"],"desigual":["portuguese"],"deslize":["portuguese"],"desmamar":["portuguese"],"desova":["portuguese"],"despesa":["portuguese"],"destaque":["portuguese"],"desviar":["portuguese"],"detalhar":["portuguese"],"detentor":["portuguese"],"detonar":["portuguese"],"detrito":["portuguese"],"deusa":["portuguese"],"dever":["portuguese"],"devido":["portuguese"],"devotado":["portuguese"],"dezena":["portuguese"],"diagrama":["portuguese"],"dialeto":["portuguese"],"didata":["portuguese"],"difuso":["portuguese"],"digitar":["portuguese"],"dilatado":["portuguese"],"diluente":["portuguese"],"diminuir":["portuguese"],"dinastia":["portuguese"],"dinheiro":["portuguese"],"diocese":["portuguese"],"direto":["portuguese"],"discreta":["portuguese"],"disfarce":["portuguese"],"disparo":["portuguese"],"disquete":["portuguese"],"dissipar":["portuguese"],"distante":["portuguese"],"ditador":["portuguese"],"diurno":["portuguese"],"diverso":["portuguese"],"divisor":["portuguese"],"divulgar":["portuguese"],"dizer":["portuguese"],"dobrador":["portuguese"],"dolorido":["portuguese"],"domador":["portuguese"],"dominado":["portuguese"],"donativo":["portuguese"],"donzela":["portuguese"],"dormente":["portuguese"],"dorsal":["portuguese"],"dosagem":["portuguese"],"dourado":["portuguese"],"doutor":["portuguese"],"drenagem":["portuguese"],"drible":["portuguese"],"drogaria":["portuguese"],"duelar":["portuguese"],"duende":["portuguese"],"dueto":["portuguese"],"duplo":["portuguese"],"duquesa":["portuguese"],"durante":["portuguese"],"duvidoso":["portuguese"],"eclodir":["portuguese"],"ecoar":["portuguese"],"ecologia":["portuguese"],"edificar":["portuguese"],"edital":["portuguese"],"educado":["portuguese"],"efeito":["portuguese"],"efetivar":["portuguese"],"ejetar":["portuguese"],"elaborar":["portuguese"],"eleger":["portuguese"],"eleitor":["portuguese"],"elenco":["portuguese"],"elevador":["portuguese"],"eliminar":["portuguese"],"elogiar":["portuguese"],"embargo":["portuguese"],"embolado":["portuguese"],"embrulho":["portuguese"],"embutido":["portuguese"],"emenda":["portuguese"],"emergir":["portuguese"],"emissor":["portuguese"],"empatia":["portuguese"],"empenho":["portuguese"],"empinado":["portuguese"],"empolgar":["portuguese"],"emprego":["portuguese"],"empurrar":["portuguese"],"emulador":["portuguese"],"encaixe":["portuguese"],"encenado":["portuguese"],"enchente":["portuguese"],"encontro":["portuguese"],"endeusar":["portuguese"],"endossar":["portuguese"],"enfaixar":["portuguese"],"enfeite":["portuguese"],"enfim":["portuguese"],"engajado":["portuguese"],"engenho":["portuguese"],"englobar":["portuguese"],"engomado":["portuguese"],"engraxar":["portuguese"],"enguia":["portuguese"],"enjoar":["portuguese"],"enlatar":["portuguese"],"enquanto":["portuguese"],"enraizar":["portuguese"],"enrolado":["portuguese"],"enrugar":["portuguese"],"ensaio":["portuguese"],"enseada":["portuguese"],"ensino":["portuguese"],"ensopado":["portuguese"],"entanto":["portuguese"],"enteado":["portuguese"],"entidade":["portuguese"],"entortar":["portuguese"],"entrada":["portuguese"],"entulho":["portuguese"],"envergar":["portuguese"],"enviado":["portuguese"],"envolver":["portuguese"],"enxame":["portuguese"],"enxerto":["portuguese"],"enxofre":["portuguese"],"enxuto":["portuguese"],"epiderme":["portuguese"],"equipar":["portuguese"],"ereto":["portuguese"],"erguido":["portuguese"],"errata":["portuguese"],"erva":["portuguese"],"ervilha":["portuguese"],"esbanjar":["portuguese"],"esbelto":["portuguese"],"escama":["portuguese"],"escola":["portuguese"],"escrita":["portuguese"],"escuta":["portuguese"],"esfinge":["portuguese"],"esfolar":["portuguese"],"esfregar":["portuguese"],"esfumado":["portuguese"],"esgrima":["portuguese"],"esmalte":["portuguese"],"espanto":["portuguese"],"espelho":["portuguese"],"espiga":["portuguese"],"esponja":["portuguese"],"espreita":["portuguese"],"espumar":["portuguese"],"esquerda":["portuguese"],"estaca":["portuguese"],"esteira":["portuguese"],"esticar":["portuguese"],"estofado":["portuguese"],"estrela":["portuguese"],"estudo":["portuguese"],"esvaziar":["portuguese"],"etanol":["portuguese"],"etiqueta":["portuguese"],"euforia":["portuguese"],"europeu":["portuguese"],"evacuar":["portuguese"],"evaporar":["portuguese"],"evasivo":["portuguese"],"eventual":["portuguese"],"evidente":["portuguese"],"evoluir":["portuguese"],"exagero":["portuguese"],"exalar":["portuguese"],"examinar":["portuguese"],"exato":["portuguese"],"exausto":["portuguese"],"excesso":["portuguese"],"excitar":["portuguese"],"exclamar":["portuguese"],"executar":["portuguese"],"exemplo":["portuguese"],"exibir":["portuguese"],"exigente":["portuguese"],"exonerar":["portuguese"],"expandir":["portuguese"],"expelir":["portuguese"],"expirar":["portuguese"],"explanar":["portuguese"],"exposto":["portuguese"],"expresso":["portuguese"],"expulsar":["portuguese"],"externo":["portuguese"],"extinto":["portuguese"],"extrato":["portuguese"],"fabricar":["portuguese"],"fabuloso":["portuguese"],"faceta":["portuguese"],"facial":["portuguese"],"fada":["portuguese"],"fadiga":["portuguese"],"faixa":["portuguese"],"falar":["portuguese"],"falta":["portuguese"],"familiar":["portuguese"],"fandango":["portuguese"],"fanfarra":["portuguese"],"fantoche":["portuguese"],"fardado":["portuguese"],"farelo":["portuguese"],"farinha":["portuguese"],"farofa":["portuguese"],"farpa":["portuguese"],"fartura":["portuguese"],"fatia":["portuguese"],"fator":["portuguese"],"favorita":["portuguese"],"faxina":["portuguese"],"fazenda":["portuguese"],"fechado":["portuguese"],"feijoada":["portuguese"],"feirante":["portuguese"],"felino":["portuguese"],"feminino":["portuguese"],"fenda":["portuguese"],"feno":["portuguese"],"fera":["portuguese"],"feriado":["portuguese"],"ferrugem":["portuguese"],"ferver":["portuguese"],"festejar":["portuguese"],"fetal":["portuguese"],"feudal":["portuguese"],"fiapo":["portuguese"],"fibrose":["portuguese"],"ficar":["portuguese"],"ficheiro":["portuguese"],"figurado":["portuguese"],"fileira":["portuguese"],"filho":["portuguese"],"filme":["portuguese"],"filtrar":["portuguese"],"firmeza":["portuguese"],"fisgada":["portuguese"],"fissura":["portuguese"],"fita":["portuguese"],"fivela":["portuguese"],"fixador":["portuguese"],"fixo":["portuguese"],"flacidez":["portuguese"],"flamingo":["portuguese"],"flanela":["portuguese"],"flechada":["portuguese"],"flora":["portuguese"],"flutuar":["portuguese"],"fluxo":["portuguese"],"focal":["portuguese"],"focinho":["portuguese"],"fofocar":["portuguese"],"fogo":["portuguese"],"foguete":["portuguese"],"foice":["portuguese"],"folgado":["portuguese"],"folheto":["portuguese"],"forjar":["portuguese"],"formiga":["portuguese"],"forno":["portuguese"],"forte":["portuguese"],"fosco":["portuguese"],"fossa":["portuguese"],"fragata":["portuguese"],"fralda":["portuguese"],"frango":["portuguese"],"frasco":["portuguese"],"fraterno":["portuguese"],"freira":["portuguese"],"frente":["portuguese"],"fretar":["portuguese"],"frieza":["portuguese"],"friso":["portuguese"],"fritura":["portuguese"],"fronha":["portuguese"],"frustrar":["portuguese"],"fruteira":["portuguese"],"fugir":["portuguese"],"fulano":["portuguese"],"fuligem":["portuguese"],"fundar":["portuguese"],"fungo":["portuguese"],"funil":["portuguese"],"furador":["portuguese"],"furioso":["portuguese"],"futebol":["portuguese"],"gabarito":["portuguese"],"gabinete":["portuguese"],"gado":["portuguese"],"gaiato":["portuguese"],"gaiola":["portuguese"],"gaivota":["portuguese"],"galega":["portuguese"],"galho":["portuguese"],"galinha":["portuguese"],"galocha":["portuguese"],"ganhar":["portuguese"],"garagem":["portuguese"],"garfo":["portuguese"],"gargalo":["portuguese"],"garimpo":["portuguese"],"garoupa":["portuguese"],"garrafa":["portuguese"],"gasoduto":["portuguese"],"gasto":["portuguese"],"gata":["portuguese"],"gatilho":["portuguese"],"gaveta":["portuguese"],"gazela":["portuguese"],"gelado":["portuguese"],"geleia":["portuguese"],"gelo":["portuguese"],"gemada":["portuguese"],"gemer":["portuguese"],"gemido":["portuguese"],"generoso":["portuguese"],"gengiva":["portuguese"],"genial":["portuguese"],"genoma":["portuguese"],"genro":["portuguese"],"geologia":["portuguese"],"gerador":["portuguese"],"germinar":["portuguese"],"gesso":["portuguese"],"gestor":["portuguese"],"ginasta":["portuguese"],"gincana":["portuguese"],"gingado":["portuguese"],"girafa":["portuguese"],"girino":["portuguese"],"glacial":["portuguese"],"glicose":["portuguese"],"global":["portuguese"],"glorioso":["portuguese"],"goela":["portuguese"],"goiaba":["portuguese"],"golfe":["portuguese"],"golpear":["portuguese"],"gordura":["portuguese"],"gorjeta":["portuguese"],"gorro":["portuguese"],"gostoso":["portuguese"],"goteira":["portuguese"],"governar":["portuguese"],"gracejo":["portuguese"],"gradual":["portuguese"],"grafite":["portuguese"],"gralha":["portuguese"],"grampo":["portuguese"],"granada":["portuguese"],"gratuito":["portuguese"],"graveto":["portuguese"],"graxa":["portuguese"],"grego":["portuguese"],"grelhar":["portuguese"],"greve":["portuguese"],"grilo":["portuguese"],"grisalho":["portuguese"],"gritaria":["portuguese"],"grosso":["portuguese"],"grotesco":["portuguese"],"grudado":["portuguese"],"grunhido":["portuguese"],"gruta":["portuguese"],"guache":["portuguese"],"guarani":["portuguese"],"guaxinim":["portuguese"],"guerrear":["portuguese"],"guiar":["portuguese"],"guincho":["portuguese"],"guisado":["portuguese"],"gula":["portuguese"],"guloso":["portuguese"],"guru":["portuguese"],"habitar":["portuguese"],"harmonia":["portuguese"],"haste":["portuguese"],"haver":["portuguese"],"hectare":["portuguese"],"herdar":["portuguese"],"heresia":["portuguese"],"hesitar":["portuguese"],"hiato":["portuguese"],"hibernar":["portuguese"],"hidratar":["portuguese"],"hiena":["portuguese"],"hino":["portuguese"],"hipismo":["portuguese"],"hipnose":["portuguese"],"hipoteca":["portuguese"],"hoje":["portuguese"],"holofote":["portuguese"],"homem":["portuguese"],"honesto":["portuguese"],"honrado":["portuguese"],"hormonal":["portuguese"],"hospedar":["portuguese"],"humorado":["portuguese"],"iate":["portuguese"],"ideia":["portuguese"],"idoso":["portuguese"],"ignorado":["portuguese"],"igreja":["portuguese"],"iguana":["portuguese"],"ileso":["portuguese"],"ilha":["portuguese"],"iludido":["portuguese"],"iluminar":["portuguese"],"ilustrar":["portuguese"],"imagem":["portuguese"],"imediato":["portuguese"],"imenso":["portuguese"],"imersivo":["portuguese"],"iminente":["portuguese"],"imitador":["portuguese"],"imortal":["portuguese"],"impacto":["portuguese"],"impedir":["portuguese"],"implante":["portuguese"],"impor":["portuguese"],"imprensa":["portuguese"],"impune":["portuguese"],"imunizar":["portuguese"],"inalador":["portuguese"],"inapto":["portuguese"],"inativo":["portuguese"],"incenso":["portuguese"],"inchar":["portuguese"],"incidir":["portuguese"],"incluir":["portuguese"],"incolor":["portuguese"],"indeciso":["portuguese"],"indireto":["portuguese"],"indutor":["portuguese"],"ineficaz":["portuguese"],"inerente":["portuguese"],"infantil":["portuguese"],"infestar":["portuguese"],"infinito":["portuguese"],"inflamar":["portuguese"],"informal":["portuguese"],"infrator":["portuguese"],"ingerir":["portuguese"],"inibido":["portuguese"],"inicial":["portuguese"],"inimigo":["portuguese"],"injetar":["portuguese"],"inocente":["portuguese"],"inodoro":["portuguese"],"inovador":["portuguese"],"inox":["portuguese"],"inquieto":["portuguese"],"inscrito":["portuguese"],"inseto":["portuguese"],"insistir":["portuguese"],"inspetor":["portuguese"],"instalar":["portuguese"],"insulto":["portuguese"],"intacto":["portuguese"],"integral":["portuguese"],"intimar":["portuguese"],"intocado":["portuguese"],"intriga":["portuguese"],"invasor":["portuguese"],"inverno":["portuguese"],"invicto":["portuguese"],"invocar":["portuguese"],"iogurte":["portuguese"],"iraniano":["portuguese"],"ironizar":["portuguese"],"irreal":["portuguese"],"irritado":["portuguese"],"isca":["portuguese"],"isento":["portuguese"],"isolado":["portuguese"],"isqueiro":["portuguese"],"italiano":["portuguese"],"janeiro":["portuguese"],"jangada":["portuguese"],"janta":["portuguese"],"jararaca":["portuguese"],"jardim":["portuguese"],"jarro":["portuguese"],"jasmim":["portuguese"],"jato":["portuguese"],"javali":["portuguese"],"jazida":["portuguese"],"jejum":["portuguese"],"joaninha":["portuguese"],"joelhada":["portuguese"],"jogador":["portuguese"],"joia":["portuguese"],"jornal":["portuguese"],"jorrar":["portuguese"],"jovem":["portuguese"],"juba":["portuguese"],"judeu":["portuguese"],"judoca":["portuguese"],"juiz":["portuguese"],"julgador":["portuguese"],"julho":["portuguese"],"jurado":["portuguese"],"jurista":["portuguese"],"juro":["portuguese"],"justa":["portuguese"],"labareda":["portuguese"],"laboral":["portuguese"],"lacre":["portuguese"],"lactante":["portuguese"],"ladrilho":["portuguese"],"lagarta":["portuguese"],"lagoa":["portuguese"],"laje":["portuguese"],"lamber":["portuguese"],"lamentar":["portuguese"],"laminar":["portuguese"],"lampejo":["portuguese"],"lanche":["portuguese"],"lapidar":["portuguese"],"lapso":["portuguese"],"laranja":["portuguese"],"lareira":["portuguese"],"largura":["portuguese"],"lasanha":["portuguese"],"lastro":["portuguese"],"lateral":["portuguese"],"latido":["portuguese"],"lavanda":["portuguese"],"lavoura":["portuguese"],"lavrador":["portuguese"],"laxante":["portuguese"],"lazer":["portuguese"],"lealdade":["portuguese"],"lebre":["portuguese"],"legado":["portuguese"],"legendar":["portuguese"],"legista":["portuguese"],"leigo":["portuguese"],"leiloar":["portuguese"],"leitura":["portuguese"],"lembrete":["portuguese"],"leme":["portuguese"],"lenhador":["portuguese"],"lentilha":["portuguese"],"leoa":["portuguese"],"lesma":["portuguese"],"leste":["portuguese"],"letivo":["portuguese"],"letreiro":["portuguese"],"levar":["portuguese"],"leveza":["portuguese"],"levitar":["portuguese"],"liberal":["portuguese"],"libido":["portuguese"],"liderar":["portuguese"],"ligar":["portuguese"],"ligeiro":["portuguese"],"limitar":["portuguese"],"limoeiro":["portuguese"],"limpador":["portuguese"],"linda":["portuguese"],"linear":["portuguese"],"linhagem":["portuguese"],"liquidez":["portuguese"],"listagem":["portuguese"],"lisura":["portuguese"],"litoral":["portuguese"],"livro":["portuguese"],"lixa":["portuguese"],"lixeira":["portuguese"],"locador":["portuguese"],"locutor":["portuguese"],"lojista":["portuguese"],"lombo":["portuguese"],"lona":["portuguese"],"longe":["portuguese"],"lontra":["portuguese"],"lorde":["portuguese"],"lotado":["portuguese"],"loteria":["portuguese"],"loucura":["portuguese"],"lousa":["portuguese"],"louvar":["portuguese"],"luar":["portuguese"],"lucidez":["portuguese"],"lucro":["portuguese"],"luneta":["portuguese"],"lustre":["portuguese"],"lutador":["portuguese"],"luva":["portuguese"],"macaco":["portuguese"],"macete":["portuguese"],"machado":["portuguese"],"macio":["portuguese"],"madeira":["portuguese"],"madrinha":["portuguese"],"magnata":["portuguese"],"magreza":["portuguese"],"maior":["portuguese"],"mais":["portuguese"],"malandro":["portuguese"],"malha":["portuguese"],"malote":["portuguese"],"maluco":["portuguese"],"mamilo":["portuguese"],"mamoeiro":["portuguese"],"mamute":["portuguese"],"manada":["portuguese"],"mancha":["portuguese"],"mandato":["portuguese"],"manequim":["portuguese"],"manhoso":["portuguese"],"manivela":["portuguese"],"manobrar":["portuguese"],"mansa":["portuguese"],"manter":["portuguese"],"manusear":["portuguese"],"mapeado":["portuguese"],"maquinar":["portuguese"],"marcador":["portuguese"],"maresia":["portuguese"],"marfim":["portuguese"],"margem":["portuguese"],"marinho":["portuguese"],"marmita":["portuguese"],"maroto":["portuguese"],"marquise":["portuguese"],"marreco":["portuguese"],"martelo":["portuguese"],"marujo":["portuguese"],"mascote":["portuguese"],"masmorra":["portuguese"],"massagem":["portuguese"],"mastigar":["portuguese"],"matagal":["portuguese"],"materno":["portuguese"],"matinal":["portuguese"],"matutar":["portuguese"],"maxilar":["portuguese"],"medalha":["portuguese"],"medida":["portuguese"],"medusa":["portuguese"],"megafone":["portuguese"],"meiga":["portuguese"],"melancia":["portuguese"],"melhor":["portuguese"],"membro":["portuguese"],"memorial":["portuguese"],"menino":["portuguese"],"menos":["portuguese"],"mensagem":["portuguese"],"mental":["portuguese"],"merecer":["portuguese"],"mergulho":["portuguese"],"mesada":["portuguese"],"mesclar":["portuguese"],"mesmo":["portuguese"],"mesquita":["portuguese"],"mestre":["portuguese"],"metade":["portuguese"],"meteoro":["portuguese"],"metragem":["portuguese"],"mexer":["portuguese"],"mexicano":["portuguese"],"micro":["portuguese"],"migalha":["portuguese"],"migrar":["portuguese"],"milagre":["portuguese"],"milenar":["portuguese"],"milhar":["portuguese"],"mimado":["portuguese"],"minerar":["portuguese"],"minhoca":["portuguese"],"ministro":["portuguese"],"minoria":["portuguese"],"miolo":["portuguese"],"mirante":["portuguese"],"mirtilo":["portuguese"],"misturar":["portuguese"],"mocidade":["portuguese"],"moderno":["portuguese"],"modular":["portuguese"],"moeda":["portuguese"],"moer":["portuguese"],"moinho":["portuguese"],"moita":["portuguese"],"moldura":["portuguese"],"moleza":["portuguese"],"molho":["portuguese"],"molinete":["portuguese"],"molusco":["portuguese"],"montanha":["portuguese"],"moqueca":["portuguese"],"morango":["portuguese"],"morcego":["portuguese"],"mordomo":["portuguese"],"morena":["portuguese"],"mosaico":["portuguese"],"mosquete":["portuguese"],"mostarda":["portuguese"],"motel":["portuguese"],"motim":["portuguese"],"moto":["portuguese"],"motriz":["portuguese"],"muda":["portuguese"],"muito":["portuguese"],"mulata":["portuguese"],"mulher":["portuguese"],"multar":["portuguese"],"mundial":["portuguese"],"munido":["portuguese"],"muralha":["portuguese"],"murcho":["portuguese"],"muscular":["portuguese"],"museu":["portuguese"],"musical":["portuguese"],"nacional":["portuguese"],"nadador":["portuguese"],"naja":["portuguese"],"namoro":["portuguese"],"narina":["portuguese"],"narrado":["portuguese"],"nascer":["portuguese"],"nativa":["portuguese"],"natureza":["portuguese"],"navalha":["portuguese"],"navegar":["portuguese"],"navio":["portuguese"],"neblina":["portuguese"],"nebuloso":["portuguese"],"negativa":["portuguese"],"negociar":["portuguese"],"negrito":["portuguese"],"nervoso":["portuguese"],"neta":["portuguese"],"neural":["portuguese"],"nevasca":["portuguese"],"nevoeiro":["portuguese"],"ninar":["portuguese"],"ninho":["portuguese"],"nitidez":["portuguese"],"nivelar":["portuguese"],"nobreza":["portuguese"],"noite":["portuguese"],"noiva":["portuguese"],"nomear":["portuguese"],"nominal":["portuguese"],"nordeste":["portuguese"],"nortear":["portuguese"],"notar":["portuguese"],"noticiar":["portuguese"],"noturno":["portuguese"],"novelo":["portuguese"],"novilho":["portuguese"],"novo":["portuguese"],"nublado":["portuguese"],"nudez":["portuguese"],"numeral":["portuguese"],"nupcial":["portuguese"],"nutrir":["portuguese"],"nuvem":["portuguese"],"obcecado":["portuguese"],"obedecer":["portuguese"],"objetivo":["portuguese"],"obrigado":["portuguese"],"obscuro":["portuguese"],"obstetra":["portuguese"],"obter":["portuguese"],"obturar":["portuguese"],"ocidente":["portuguese"],"ocioso":["portuguese"],"ocorrer":["portuguese"],"oculista":["portuguese"],"ocupado":["portuguese"],"ofegante":["portuguese"],"ofensiva":["portuguese"],"oferenda":["portuguese"],"oficina":["portuguese"],"ofuscado":["portuguese"],"ogiva":["portuguese"],"olaria":["portuguese"],"oleoso":["portuguese"],"olhar":["portuguese"],"oliveira":["portuguese"],"ombro":["portuguese"],"omelete":["portuguese"],"omisso":["portuguese"],"omitir":["portuguese"],"ondulado":["portuguese"],"oneroso":["portuguese"],"ontem":["portuguese"],"opcional":["portuguese"],"operador":["portuguese"],"oponente":["portuguese"],"oportuno":["portuguese"],"oposto":["portuguese"],"orar":["portuguese"],"orbitar":["portuguese"],"ordem":["portuguese"],"ordinal":["portuguese"],"orfanato":["portuguese"],"orgasmo":["portuguese"],"orgulho":["portuguese"],"oriental":["portuguese"],"origem":["portuguese"],"oriundo":["portuguese"],"orla":["portuguese"],"ortodoxo":["portuguese"],"orvalho":["portuguese"],"oscilar":["portuguese"],"ossada":["portuguese"],"osso":["portuguese"],"ostentar":["portuguese"],"otimismo":["portuguese"],"ousadia":["portuguese"],"outono":["portuguese"],"outubro":["portuguese"],"ouvido":["portuguese"],"ovelha":["portuguese"],"ovular":["portuguese"],"oxidar":["portuguese"],"oxigenar":["portuguese"],"pacato":["portuguese"],"paciente":["portuguese"],"pacote":["portuguese"],"pactuar":["portuguese"],"padaria":["portuguese"],"padrinho":["portuguese"],"pagar":["portuguese"],"pagode":["portuguese"],"painel":["portuguese"],"pairar":["portuguese"],"paisagem":["portuguese"],"palavra":["portuguese"],"palestra":["portuguese"],"palheta":["portuguese"],"palito":["portuguese"],"palmada":["portuguese"],"palpitar":["portuguese"],"pancada":["portuguese"],"panela":["portuguese"],"panfleto":["portuguese"],"panqueca":["portuguese"],"pantanal":["portuguese"],"papagaio":["portuguese"],"papelada":["portuguese"],"papiro":["portuguese"],"parafina":["portuguese"],"parcial":["portuguese"],"pardal":["portuguese"],"parede":["portuguese"],"partida":["portuguese"],"pasmo":["portuguese"],"passado":["portuguese"],"pastel":["portuguese"],"patamar":["portuguese"],"patente":["portuguese"],"patinar":["portuguese"],"patrono":["portuguese"],"paulada":["portuguese"],"pausar":["portuguese"],"peculiar":["portuguese"],"pedalar":["portuguese"],"pedestre":["portuguese"],"pediatra":["portuguese"],"pedra":["portuguese"],"pegada":["portuguese"],"peitoral":["portuguese"],"peixe":["portuguese"],"pele":["portuguese"],"pelicano":["portuguese"],"penca":["portuguese"],"pendurar":["portuguese"],"peneira":["portuguese"],"penhasco":["portuguese"],"pensador":["portuguese"],"pente":["portuguese"],"perceber":["portuguese"],"perfeito":["portuguese"],"pergunta":["portuguese"],"perito":["portuguese"],"permitir":["portuguese"],"perna":["portuguese"],"perplexo":["portuguese"],"persiana":["portuguese"],"pertence":["portuguese"],"peruca":["portuguese"],"pescado":["portuguese"],"pesquisa":["portuguese"],"pessoa":["portuguese"],"petiscar":["portuguese"],"piada":["portuguese"],"picado":["portuguese"],"piedade":["portuguese"],"pigmento":["portuguese"],"pilastra":["portuguese"],"pilhado":["portuguese"],"pilotar":["portuguese"],"pimenta":["portuguese"],"pincel":["portuguese"],"pinguim":["portuguese"],"pinha":["portuguese"],"pinote":["portuguese"],"pintar":["portuguese"],"pioneiro":["portuguese"],"pipoca":["portuguese"],"piquete":["portuguese"],"piranha":["portuguese"],"pires":["portuguese"],"pirueta":["portuguese"],"piscar":["portuguese"],"pistola":["portuguese"],"pitanga":["portuguese"],"pivete":["portuguese"],"planta":["portuguese"],"plaqueta":["portuguese"],"platina":["portuguese"],"plebeu":["portuguese"],"plumagem":["portuguese"],"pluvial":["portuguese"],"pneu":["portuguese"],"poda":["portuguese"],"poeira":["portuguese"],"poetisa":["portuguese"],"polegada":["portuguese"],"policiar":["portuguese"],"poluente":["portuguese"],"polvilho":["portuguese"],"pomar":["portuguese"],"pomba":["portuguese"],"ponderar":["portuguese"],"pontaria":["portuguese"],"populoso":["portuguese"],"porta":["portuguese"],"possuir":["portuguese"],"postal":["portuguese"],"pote":["portuguese"],"poupar":["portuguese"],"pouso":["portuguese"],"povoar":["portuguese"],"praia":["portuguese"],"prancha":["portuguese"],"prato":["portuguese"],"praxe":["portuguese"],"prece":["portuguese"],"predador":["portuguese"],"prefeito":["portuguese"],"premiar":["portuguese"],"prensar":["portuguese"],"preparar":["portuguese"],"presilha":["portuguese"],"pretexto":["portuguese"],"prevenir":["portuguese"],"prezar":["portuguese"],"primata":["portuguese"],"princesa":["portuguese"],"prisma":["portuguese"],"privado":["portuguese"],"processo":["portuguese"],"produto":["portuguese"],"profeta":["portuguese"],"proibido":["portuguese"],"projeto":["portuguese"],"prometer":["portuguese"],"propagar":["portuguese"],"prosa":["portuguese"],"protetor":["portuguese"],"provador":["portuguese"],"publicar":["portuguese"],"pudim":["portuguese"],"pular":["portuguese"],"pulmonar":["portuguese"],"pulseira":["portuguese"],"punhal":["portuguese"],"punir":["portuguese"],"pupilo":["portuguese"],"pureza":["portuguese"],"puxador":["portuguese"],"quadra":["portuguese"],"quantia":["portuguese"],"quarto":["portuguese"],"quase":["portuguese"],"quebrar":["portuguese"],"queda":["portuguese"],"queijo":["portuguese"],"quente":["portuguese"],"querido":["portuguese"],"quimono":["portuguese"],"quina":["portuguese"],"quiosque":["portuguese"],"rabanada":["portuguese"],"rabisco":["portuguese"],"rachar":["portuguese"],"racionar":["portuguese"],"radial":["portuguese"],"raiar":["portuguese"],"rainha":["portuguese"],"raio":["portuguese"],"raiva":["portuguese"],"rajada":["portuguese"],"ralado":["portuguese"],"ramal":["portuguese"],"ranger":["portuguese"],"ranhura":["portuguese"],"rapadura":["portuguese"],"rapel":["portuguese"],"rapidez":["portuguese"],"raposa":["portuguese"],"raquete":["portuguese"],"raridade":["portuguese"],"rasante":["portuguese"],"rascunho":["portuguese"],"rasgar":["portuguese"],"raspador":["portuguese"],"rasteira":["portuguese"],"rasurar":["portuguese"],"ratazana":["portuguese"],"ratoeira":["portuguese"],"realeza":["portuguese"],"reanimar":["portuguese"],"reaver":["portuguese"],"rebaixar":["portuguese"],"rebelde":["portuguese"],"rebolar":["portuguese"],"recado":["portuguese"],"recente":["portuguese"],"recheio":["portuguese"],"recibo":["portuguese"],"recordar":["portuguese"],"recrutar":["portuguese"],"recuar":["portuguese"],"rede":["portuguese"],"redimir":["portuguese"],"redonda":["portuguese"],"reduzida":["portuguese"],"reenvio":["portuguese"],"refinar":["portuguese"],"refletir":["portuguese"],"refogar":["portuguese"],"refresco":["portuguese"],"refugiar":["portuguese"],"regalia":["portuguese"],"regime":["portuguese"],"regra":["portuguese"],"reinado":["portuguese"],"reitor":["portuguese"],"rejeitar":["portuguese"],"relativo":["portuguese"],"remador":["portuguese"],"remendo":["portuguese"],"remorso":["portuguese"],"renovado":["portuguese"],"reparo":["portuguese"],"repelir":["portuguese"],"repleto":["portuguese"],"repolho":["portuguese"],"represa":["portuguese"],"repudiar":["portuguese"],"requerer":["portuguese"],"resenha":["portuguese"],"resfriar":["portuguese"],"resgatar":["portuguese"],"residir":["portuguese"],"resolver":["portuguese"],"respeito":["portuguese"],"ressaca":["portuguese"],"restante":["portuguese"],"resumir":["portuguese"],"retalho":["portuguese"],"reter":["portuguese"],"retirar":["portuguese"],"retomada":["portuguese"],"retratar":["portuguese"],"revelar":["portuguese"],"revisor":["portuguese"],"revolta":["portuguese"],"riacho":["portuguese"],"rica":["portuguese"],"rigidez":["portuguese"],"rigoroso":["portuguese"],"rimar":["portuguese"],"ringue":["portuguese"],"risada":["portuguese"],"risco":["portuguese"],"risonho":["portuguese"],"robalo":["portuguese"],"rochedo":["portuguese"],"rodada":["portuguese"],"rodeio":["portuguese"],"rodovia":["portuguese"],"roedor":["portuguese"],"roleta":["portuguese"],"romano":["portuguese"],"roncar":["portuguese"],"rosado":["portuguese"],"roseira":["portuguese"],"rosto":["portuguese"],"rota":["portuguese","turkish"],"roteiro":["portuguese"],"rotina":["portuguese"],"rotular":["portuguese"],"rouco":["portuguese"],"roupa":["portuguese"],"roxo":["portuguese"],"rubro":["portuguese"],"rugido":["portuguese"],"rugoso":["portuguese"],"ruivo":["portuguese"],"rumo":["portuguese"],"rupestre":["portuguese"],"russo":["portuguese"],"sabor":["portuguese"],"saciar":["portuguese"],"sacola":["portuguese"],"sacudir":["portuguese"],"sadio":["portuguese"],"safira":["portuguese"],"saga":["portuguese"],"sagrada":["portuguese"],"saibro":["portuguese"],"salada":["portuguese"],"saleiro":["portuguese"],"salgado":["portuguese"],"saliva":["portuguese"],"salpicar":["portuguese"],"salsicha":["portuguese"],"saltar":["portuguese"],"salvador":["portuguese"],"sambar":["portuguese"],"samurai":["portuguese"],"sanar":["portuguese"],"sanfona":["portuguese"],"sangue":["portuguese"],"sanidade":["portuguese"],"sapato":["portuguese"],"sarda":["portuguese"],"sargento":["portuguese"],"sarjeta":["portuguese"],"saturar":["portuguese"],"saudade":["portuguese"],"saxofone":["portuguese"],"sazonal":["portuguese"],"secar":["portuguese"],"secular":["portuguese"],"seda":["portuguese","turkish"],"sedento":["portuguese"],"sediado":["portuguese"],"sedoso":["portuguese"],"sedutor":["portuguese"],"segmento":["portuguese"],"segredo":["portuguese"],"segundo":["portuguese"],"seiva":["portuguese"],"seleto":["portuguese"],"selvagem":["portuguese"],"semanal":["portuguese"],"semente":["portuguese"],"senador":["portuguese"],"senhor":["portuguese"],"sensual":["portuguese"],"sentado":["portuguese"],"separado":["portuguese"],"sereia":["portuguese"],"seringa":["portuguese"],"serra":["portuguese"],"servo":["portuguese"],"setembro":["portuguese"],"setor":["portuguese"],"sigilo":["portuguese"],"silhueta":["portuguese"],"silicone":["portuguese"],"simetria":["portuguese"],"simpatia":["portuguese"],"simular":["portuguese"],"sinal":["portuguese"],"sincero":["portuguese"],"singular":["portuguese"],"sinopse":["portuguese"],"sintonia":["portuguese"],"sirene":["portuguese"],"siri":["portuguese"],"situado":["portuguese"],"soberano":["portuguese"],"sobra":["portuguese"],"socorro":["portuguese"],"sogro":["portuguese"],"soja":["portuguese"],"solda":["portuguese"],"soletrar":["portuguese"],"solteiro":["portuguese"],"sombrio":["portuguese"],"sonata":["portuguese"],"sondar":["portuguese"],"sonegar":["portuguese"],"sonhador":["portuguese"],"sono":["portuguese"],"soprano":["portuguese"],"soquete":["portuguese"],"sorrir":["portuguese"],"sorteio":["portuguese"],"sossego":["portuguese"],"sotaque":["portuguese"],"soterrar":["portuguese"],"sovado":["portuguese"],"sozinho":["portuguese"],"suavizar":["portuguese"],"subida":["portuguese"],"submerso":["portuguese"],"subsolo":["portuguese"],"subtrair":["portuguese"],"sucata":["portuguese"],"sucesso":["portuguese"],"suco":["portuguese"],"sudeste":["portuguese"],"sufixo":["portuguese"],"sugador":["portuguese"],"sugerir":["portuguese"],"sujeito":["portuguese"],"sulfato":["portuguese"],"sumir":["portuguese"],"suor":["portuguese"],"superior":["portuguese"],"suplicar":["portuguese"],"suposto":["portuguese"],"suprimir":["portuguese"],"surdina":["portuguese"],"surfista":["portuguese"],"surpresa":["portuguese"],"surreal":["portuguese"],"surtir":["portuguese"],"suspiro":["portuguese"],"sustento":["portuguese"],"tabela":["portuguese","turkish"],"tablete":["portuguese"],"tabuada":["portuguese"],"tacho":["portuguese"],"tagarela":["portuguese"],"talher":["portuguese"],"talo":["portuguese"],"talvez":["portuguese"],"tamanho":["portuguese"],"tamborim":["portuguese"],"tampa":["portuguese"],"tangente":["portuguese"],"tanto":["portuguese"],"tapar":["portuguese"],"tapioca":["portuguese"],"tardio":["portuguese"],"tarefa":["portuguese"],"tarja":["portuguese"],"tarraxa":["portuguese"],"tatuagem":["portuguese"],"taurino":["portuguese"],"taxativo":["portuguese"],"taxista":["portuguese"],"teatral":["portuguese"],"tecer":["portuguese"],"tecido":["portuguese"],"teclado":["portuguese"],"tedioso":["portuguese"],"teia":["portuguese"],"teimar":["portuguese"],"telefone":["portuguese"],"telhado":["portuguese"],"tempero":["portuguese"],"tenente":["portuguese"],"tensor":["portuguese"],"tentar":["portuguese"],"termal":["portuguese"],"terno":["portuguese"],"terreno":["portuguese"],"tese":["portuguese"],"tesoura":["portuguese"],"testado":["portuguese"],"teto":["portuguese"],"textura":["portuguese"],"texugo":["portuguese"],"tiara":["portuguese"],"tigela":["portuguese"],"tijolo":["portuguese"],"timbrar":["portuguese"],"timidez":["portuguese"],"tingido":["portuguese"],"tinteiro":["portuguese"],"tiragem":["portuguese"],"titular":["portuguese"],"toalha":["portuguese"],"tocha":["portuguese"],"tolerar":["portuguese"],"tolice":["portuguese"],"tomada":["portuguese"],"tomilho":["portuguese"],"tonel":["portuguese"],"tontura":["portuguese"],"topete":["portuguese"],"tora":["portuguese"],"torcido":["portuguese"],"torneio":["portuguese"],"torque":["portuguese"],"torrada":["portuguese"],"torto":["portuguese"],"tostar":["portuguese"],"touca":["portuguese"],"toupeira":["portuguese"],"toxina":["portuguese"],"trabalho":["portuguese"],"tracejar":["portuguese"],"tradutor":["portuguese"],"trafegar":["portuguese"],"trajeto":["portuguese"],"trama":["portuguese"],"trancar":["portuguese"],"trapo":["portuguese"],"traseiro":["portuguese"],"tratador":["portuguese"],"travar":["portuguese"],"treino":["portuguese"],"tremer":["portuguese"],"trepidar":["portuguese"],"trevo":["portuguese"],"triagem":["portuguese"],"tribo":["portuguese"],"triciclo":["portuguese"],"tridente":["portuguese"],"trilogia":["portuguese"],"trindade":["portuguese"],"triplo":["portuguese"],"triturar":["portuguese"],"triunfal":["portuguese"],"trocar":["portuguese"],"trombeta":["portuguese"],"trova":["portuguese"],"trunfo":["portuguese"],"truque":["portuguese"],"tubular":["portuguese"],"tucano":["portuguese"],"tudo":["portuguese"],"tulipa":["portuguese"],"tupi":["portuguese"],"turbo":["portuguese"],"turma":["portuguese"],"turquesa":["portuguese"],"tutelar":["portuguese"],"tutorial":["portuguese"],"uivar":["portuguese"],"umbigo":["portuguese"],"unha":["portuguese"],"unidade":["portuguese"],"uniforme":["portuguese"],"urologia":["portuguese"],"urso":["portuguese"],"urtiga":["portuguese"],"urubu":["portuguese"],"usado":["portuguese"],"usina":["portuguese"],"usufruir":["portuguese"],"vacina":["portuguese"],"vadiar":["portuguese"],"vagaroso":["portuguese"],"vaidoso":["portuguese"],"vala":["portuguese"],"valente":["portuguese"],"validade":["portuguese"],"valores":["portuguese"],"vantagem":["portuguese"],"vaqueiro":["portuguese"],"varanda":["portuguese"],"vareta":["portuguese"],"varrer":["portuguese"],"vascular":["portuguese"],"vasilha":["portuguese"],"vassoura":["portuguese"],"vazar":["portuguese"],"vazio":["portuguese"],"veado":["portuguese"],"vedar":["portuguese"],"vegetar":["portuguese"],"veicular":["portuguese"],"veleiro":["portuguese"],"velhice":["portuguese"],"veludo":["portuguese"],"vencedor":["portuguese"],"vendaval":["portuguese"],"venerar":["portuguese"],"ventre":["portuguese"],"verbal":["portuguese"],"verdade":["portuguese"],"vereador":["portuguese"],"vergonha":["portuguese"],"vermelho":["portuguese"],"verniz":["portuguese"],"versar":["portuguese"],"vertente":["portuguese"],"vespa":["portuguese"],"vestido":["portuguese"],"vetorial":["portuguese"],"viaduto":["portuguese"],"viagem":["portuguese"],"viajar":["portuguese"],"viatura":["portuguese"],"vibrador":["portuguese"],"videira":["portuguese"],"vidraria":["portuguese"],"viela":["portuguese"],"viga":["portuguese"],"vigente":["portuguese"],"vigiar":["portuguese"],"vigorar":["portuguese"],"vilarejo":["portuguese"],"vinco":["portuguese"],"vinheta":["portuguese"],"vinil":["portuguese"],"violeta":["portuguese"],"virada":["portuguese"],"virtude":["portuguese"],"visitar":["portuguese"],"visto":["portuguese"],"vitral":["portuguese"],"viveiro":["portuguese"],"vizinho":["portuguese"],"voador":["portuguese"],"voar":["portuguese"],"vogal":["portuguese"],"volante":["portuguese"],"voleibol":["portuguese"],"voltagem":["portuguese"],"volumoso":["portuguese"],"vontade":["portuguese"],"vulto":["portuguese"],"vuvuzela":["portuguese"],"xadrez":["portuguese"],"xarope":["portuguese"],"xeque":["portuguese"],"xeretar":["portuguese"],"xerife":["portuguese"],"xingar":["portuguese"],"zangado":["portuguese"],"zarpar":["portuguese"],"zebu":["portuguese"],"zelador":["portuguese"],"zombar":["portuguese"],"zoologia":["portuguese"],"zumbido":["portuguese"],"абзац":["russian"],"абонент":["russian"],"абсурд":["russian"],"авангард":["russian"],"авария":["russian"],"август":["russian"],"авиация":["russian"],"автор":["russian"],"агент":["russian"],"агитация":["russian"],"агрегат":["russian"],"адвокат":["russian"],"адмирал":["russian"],"адрес":["russian"],"азарт":["russian"],"азот":["russian"],"академия":["russian"],"аквариум":["russian"],"аксиома":["russian"],"акула":["russian"],"акцент":["russian"],"акция":["russian"],"аллея":["russian"],"алмаз":["russian"],"алтарь":["russian"],"альбом":["russian"],"альянс":["russian"],"амбиция":["russian"],"анализ":["russian"],"анекдот":["russian"],"анкета":["russian"],"ансамбль":["russian"],"антенна":["russian"],"апельсин":["russian"],"аппарат":["russian"],"аппетит":["russian"],"апрель":["russian"],"аптека":["russian"],"арбуз":["russian"],"аргумент":["russian"],"аренда":["russian"],"арест":["russian"],"армия":["russian"],"аромат":["russian"],"арсенал":["russian"],"артерия":["russian"],"артист":["russian"],"архив":["russian"],"аспирант":["russian"],"асфальт":["russian"],"атака":["russian"],"атомный":["russian"],"атрибут":["russian"],"аукцион":["russian"],"афиша":["russian"],"аэропорт":["russian"],"бабочка":["russian"],"бабушка":["russian"],"багаж":["russian"],"база":["russian"],"бактерия":["russian"],"баланс":["russian"],"балерина":["russian"],"балкон":["russian"],"бандит":["russian"],"банк":["russian"],"барабан":["russian"],"барон":["russian"],"барышня":["russian"],"барьер":["russian"],"бассейн":["russian"],"батарея":["russian"],"башмак":["russian"],"башня":["russian"],"бедный":["russian"],"беженец":["russian"],"бездна":["russian"],"белка":["russian"],"белый":["russian"],"бензин":["russian"],"берег":["russian"],"беседа":["russian"],"бешеный":["russian"],"билет":["russian"],"бинокль":["russian"],"биржа":["russian"],"битва":["russian"],"благо":["russian"],"блеск":["russian"],"близкий":["russian"],"блин":["russian"],"блок":["russian"],"блюдо":["russian"],"богатый":["russian"],"бодрый":["russian"],"боец":["russian"],"бокал":["russian"],"боковой":["russian"],"бокс":["russian"],"более":["russian"],"болото":["russian"],"болтать":["russian"],"большой":["russian"],"бомба":["russian"],"борт":["russian"],"борьба":["russian"],"босой":["russian"],"ботинок":["russian"],"бояться":["russian"],"брак":["russian"],"брать":["russian"],"бревно":["russian"],"бред":["russian"],"бригада":["russian"],"бродяга":["russian"],"броня":["russian"],"бросить":["russian"],"брызги":["russian"],"брюки":["russian"],"брюхо":["russian"],"бугор":["russian"],"будка":["russian"],"будни":["russian"],"будущее":["russian"],"буква":["russian"],"букет":["russian"],"бульвар":["russian"],"бумага":["russian"],"бунт":["russian"],"бурный":["russian"],"буря":["russian"],"бутылка":["russian"],"бухта":["russian"],"бывший":["russian"],"быстро":["russian"],"бытовой":["russian"],"быть":["russian"],"бюджет":["russian"],"бюро":["russian"],"бюст":["russian"],"вагон":["russian"],"важный":["russian"],"вакцина":["russian"],"валенок":["russian"],"вальс":["russian"],"валюта":["russian"],"ванная":["russian"],"варенье":["russian"],"вариант":["russian"],"вблизи":["russian"],"вверх":["russian"],"вводить":["russian"],"вдали":["russian"],"вдвое":["russian"],"вдова":["russian"],"вдоль":["russian"],"вдруг":["russian"],"ведро":["russian"],"ведущий":["russian"],"ведьма":["russian"],"вежливо":["russian"],"везде":["russian"],"веко":["russian"],"вексель":["russian"],"велеть":["russian"],"великий":["russian"],"венец":["russian"],"веник":["russian"],"веранда":["russian"],"верблюд":["russian"],"верить":["russian"],"верный":["russian"],"версия":["russian"],"вертеть":["russian"],"верхний":["russian"],"вершина":["russian"],"весело":["russian"],"весна":["russian"],"весомый":["russian"],"вести":["russian"],"весь":["russian"],"ветеран":["russian"],"ветхий":["russian"],"вечер":["russian"],"вечно":["russian"],"вешалка":["russian"],"вещество":["russian"],"взамен":["russian"],"взгляд":["russian"],"вздох":["russian"],"взнос":["russian"],"взойти":["russian"],"взор":["russian"],"взрыв":["russian"],"взять":["russian"],"видеть":["russian"],"видимо":["russian"],"визг":["russian"],"визит":["russian"],"вилка":["russian"],"вина":["russian"],"вирус":["russian"],"висок":["russian"],"витамин":["russian"],"витрина":["russian"],"вихрь":["russian"],"вишня":["russian"],"вкус":["russian"],"влага":["russian"],"владелец":["russian"],"власть":["russian"],"влево":["russian"],"влияние":["russian"],"вложить":["russian"],"вместе":["russian"],"внешний":["russian"],"вникать":["russian"],"внимание":["russian"],"вновь":["russian"],"внук":["russian"],"внутри":["russian"],"внучка":["russian"],"внушать":["russian"],"вовлечь":["russian"],"вовремя":["russian"],"вовсю":["russian"],"вода":["russian"],"водород":["russian"],"водяной":["russian"],"воевать":["russian"],"возврат":["russian"],"возглас":["russian"],"воздух":["russian"],"возить":["russian"],"возле":["russian"],"возня":["russian"],"возраст":["russian"],"война":["russian"],"войско":["russian"],"вокзал":["russian"],"волос":["russian"],"волчий":["russian"],"вольный":["russian"],"воля":["russian"],"вообще":["russian"],"вопль":["russian"],"вопрос":["russian"],"ворота":["russian"],"восемь":["russian"],"восток":["russian"],"вплоть":["russian"],"вполне":["russian"],"вправе":["russian"],"впредь":["russian"],"впрочем":["russian"],"врач":["russian"],"вредный":["russian"],"время":["russian"],"вручить":["russian"],"всадник":["russian"],"всегда":["russian"],"вскоре":["russian"],"вскрыть":["russian"],"всплеск":["russian"],"вспышка":["russian"],"встреча":["russian"],"всюду":["russian"],"всякий":["russian"],"второй":["russian"],"вход":["russian"],"вчера":["russian"],"выбор":["russian"],"вывод":["russian"],"выгнать":["russian"],"выдать":["russian"],"выехать":["russian"],"вызов":["russian"],"выйти":["russian"],"выкуп":["russian"],"вылезти":["russian"],"вымыть":["russian"],"выпасть":["russian"],"выпить":["russian"],"выплата":["russian"],"выпуск":["russian"],"вырасти":["russian"],"выручка":["russian"],"выслать":["russian"],"высокий":["russian"],"выставка":["russian"],"вышка":["russian"],"вязать":["russian"],"вялый":["russian"],"газета":["russian"],"газовый":["russian"],"галерея":["russian"],"галстук":["russian"],"гамма":["russian"],"гарантия":["russian"],"гармония":["russian"],"гарнизон":["russian"],"гастроли":["russian"],"гвардия":["russian"],"гвоздь":["russian"],"гектар":["russian"],"генерал":["russian"],"гений":["russian"],"геном":["russian"],"геолог":["russian"],"герб":["russian"],"герой":["russian"],"гибкий":["russian"],"гигант":["russian"],"гимн":["russian"],"гипотеза":["russian"],"гитара":["russian"],"главный":["russian"],"глагол":["russian"],"гладить":["russian"],"глаз":["russian"],"глина":["russian"],"глоток":["russian"],"глубокий":["russian"],"глупый":["russian"],"глухой":["russian"],"глыба":["russian"],"глядеть":["russian"],"гнев":["russian"],"гнездо":["russian"],"гнилой":["russian"],"годовой":["russian"],"голова":["russian"],"голубой":["russian"],"голый":["russian"],"гонорар":["russian"],"гордость":["russian"],"горизонт":["russian"],"горло":["russian"],"горный":["russian"],"город":["russian"],"горшок":["russian"],"горький":["russian"],"горючее":["russian"],"горячий":["russian"],"готовый":["russian"],"градус":["russian"],"грамм":["russian"],"граница":["russian"],"граф":["russian"],"гребень":["russian"],"гриб":["russian"],"гримаса":["russian"],"грозить":["russian"],"грохот":["russian"],"грош":["russian"],"грубый":["russian"],"грудь":["russian"],"груз":["russian"],"грунт":["russian"],"группа":["russian"],"груша":["russian"],"грязный":["russian"],"губа":["russian"],"гудок":["russian"],"гулкий":["russian"],"гулять":["russian"],"гусеница":["russian"],"густо":["russian"],"гусь":["russian"],"давление":["russian"],"давно":["russian"],"даже":["russian"],"дальний":["russian"],"данный":["russian"],"дарить":["russian"],"датчик":["russian"],"дать":["russian"],"дача":["russian"],"двадцать":["russian"],"дважды":["russian"],"дверь":["russian"],"двигать":["russian"],"движение":["russian"],"двойной":["russian"],"двор":["russian"],"дебют":["russian"],"девятый":["russian"],"дежурный":["russian"],"действие":["russian"],"декабрь":["russian"],"деление":["russian"],"дело":["russian"],"дельфин":["russian"],"день":["russian"],"дерево":["russian"],"держать":["russian"],"дерзкий":["russian"],"десять":["russian"],"деталь":["russian"],"детский":["russian"],"дефект":["russian"],"дефицит":["russian"],"деятель":["russian"],"джаз":["russian"],"джинсы":["russian"],"джунгли":["russian"],"диагноз":["russian"],"диалог":["russian"],"диапазон":["russian"],"диван":["russian"],"дивизия":["russian"],"дивный":["russian"],"диета":["russian"],"дизайн":["russian"],"дикарь":["russian"],"дилер":["russian"],"динамика":["russian"],"диплом":["russian"],"директор":["russian"],"дитя":["russian"],"длинный":["russian"],"дневник":["russian"],"добрый":["russian"],"добыча":["russian"],"доверие":["russian"],"догадка":["russian"],"догнать":["russian"],"дождь":["russian"],"доклад":["russian"],"доктор":["russian"],"документ":["russian"],"долго":["russian"],"должен":["russian"],"долина":["russian"],"донос":["russian"],"дорога":["russian"],"досада":["russian"],"доска":["russian"],"достать":["russian"],"досуг":["russian"],"доход":["russian"],"доцент":["russian"],"дощатый":["russian"],"драка":["russian"],"древний":["russian"],"дремать":["russian"],"дробный":["russian"],"дрова":["russian"],"дрожать":["russian"],"другой":["russian"],"дружба":["russian"],"дубовый":["russian"],"дуга":["russian"],"думать":["russian"],"дурной":["russian"],"духи":["russian"],"душный":["russian"],"дуэль":["russian"],"дуэт":["russian"],"дыра":["russian"],"дыхание":["russian"],"дюжина":["russian"],"дядя":["russian"],"едва":["russian"],"единый":["russian"],"ерунда":["russian"],"если":["russian"],"ехать":["russian"],"жадный":["russian"],"жажда":["russian"],"жалеть":["russian"],"жалоба":["russian"],"жанр":["russian"],"жареный":["russian"],"жаркий":["russian"],"жгучий":["russian"],"жевать":["russian"],"желание":["russian"],"желудок":["russian"],"жена":["russian"],"женщина":["russian"],"жертва":["russian"],"жест":["russian"],"жидкость":["russian"],"житель":["russian"],"жить":["russian"],"жрец":["russian"],"жулик":["russian"],"журнал":["russian"],"жуткий":["russian"],"забрать":["russian"],"забыть":["russian"],"завести":["russian"],"завод":["russian"],"завтра":["russian"],"загадка":["russian"],"загнать":["russian"],"заговор":["russian"],"задача":["russian"],"задеть":["russian"],"задний":["russian"],"задолго":["russian"],"заехать":["russian"],"заказ":["russian"],"закон":["russian"],"закрыть":["russian"],"закуска":["russian"],"залезть":["russian"],"залить":["russian"],"залп":["russian"],"замок":["russian"],"замуж":["russian"],"замысел":["russian"],"занавес":["russian"],"заново":["russian"],"занять":["russian"],"заодно":["russian"],"запись":["russian"],"запрос":["russian"],"запуск":["russian"],"запястье":["russian"],"заранее":["russian"],"заросль":["russian"],"зарплата":["russian"],"заря":["russian"],"засада":["russian"],"заслуга":["russian"],"заснуть":["russian"],"застать":["russian"],"затвор":["russian"],"затеять":["russian"],"затрата":["russian"],"затылок":["russian"],"захват":["russian"],"зачем":["russian"],"защита":["russian"],"заявить":["russian"],"заяц":["russian"],"звезда":["russian"],"звено":["russian"],"звонить":["russian"],"здесь":["russian"],"зелень":["russian"],"земля":["russian"],"зеркало":["russian"],"зерно":["russian"],"зима":["russian"],"злой":["russian"],"змея":["russian"],"знамя":["russian"],"знание":["russian"],"значит":["russian"],"золотой":["russian"],"зона":["russian"],"зонтик":["russian"],"зоопарк":["russian"],"зрачок":["russian"],"зрение":["russian"],"зритель":["russian"],"зубной":["russian"],"зубр":["russian"],"игла":["russian"],"идеал":["russian"],"идеолог":["russian"],"идея":["russian"],"идол":["russian"],"идти":["russian"],"изба":["russian"],"избить":["russian"],"избрать":["russian"],"избыток":["russian"],"извлечь":["russian"],"извне":["russian"],"изгиб":["russian"],"изгнать":["russian"],"издание":["russian"],"изделие":["russian"],"изнутри":["russian"],"изобилие":["russian"],"изоляция":["russian"],"изредка":["russian"],"изрядно":["russian"],"изучение":["russian"],"изъять":["russian"],"изящный":["russian"],"икона":["russian"],"икра":["russian"],"иллюзия":["russian"],"именно":["russian"],"иметь":["russian"],"имидж":["russian"],"империя":["russian"],"импульс":["russian"],"иначе":["russian"],"инвалид":["russian"],"индекс":["russian"],"индивид":["russian"],"инерция":["russian"],"инженер":["russian"],"иногда":["russian"],"иной":["russian"],"институт":["russian"],"интерес":["russian"],"интрига":["russian"],"интуиция":["russian"],"инфаркт":["russian"],"инцидент":["russian"],"ирония":["russian"],"искать":["russian"],"испуг":["russian"],"история":["russian"],"итог":["russian"],"июнь":["russian"],"кабель":["russian"],"кабинет":["russian"],"каблук":["russian"],"кавалер":["russian"],"кадр":["russian"],"каждый":["russian"],"кажется":["russian"],"казино":["russian"],"калитка":["russian"],"камень":["russian"],"камин":["russian"],"канал":["russian"],"кандидат":["russian"],"каникулы":["russian"],"канон":["russian"],"капитан":["russian"],"капля":["russian"],"капот":["russian"],"капуста":["russian"],"карандаш":["russian"],"карета":["russian"],"каркас":["russian"],"карман":["russian"],"картина":["russian"],"карьера":["russian"],"каска":["russian"],"кассета":["russian"],"кастрюля":["russian"],"каталог":["russian"],"катер":["russian"],"каток":["russian"],"катушка":["russian"],"кафедра":["russian"],"качество":["russian"],"каша":["russian"],"кашлять":["russian"],"каюта":["russian"],"квадрат":["russian"],"квартира":["russian"],"квота":["russian"],"кепка":["russian"],"кивнуть":["russian"],"километр":["russian"],"кино":["russian"],"киоск":["russian"],"кипяток":["russian"],"кирпич":["russian"],"кислота":["russian"],"кисть":["russian"],"клавиша":["russian"],"клапан":["russian"],"класс":["russian"],"клей":["russian"],"клетка":["russian"],"клиент":["russian"],"климат":["russian"],"клиника":["russian"],"кличка":["russian"],"клоун":["russian"],"клочок":["russian"],"клуб":["russian"],"клумба":["russian"],"ключ":["russian"],"книга":["russian"],"кнопка":["russian"],"кнут":["russian"],"княгиня":["russian"],"князь":["russian"],"кобура":["russian"],"когда":["russian"],"кодекс":["russian"],"кожа":["russian"],"коктейль":["russian"],"колено":["russian"],"коллега":["russian"],"колонна":["russian"],"колпак":["russian"],"кольцо":["russian"],"колючий":["russian"],"коляска":["russian"],"команда":["russian"],"комедия":["russian"],"комиссия":["russian"],"коммуна":["russian"],"комната":["russian"],"комок":["russian"],"компания":["russian"],"комфорт":["russian"],"конвейер":["russian"],"конгресс":["russian"],"конечно":["russian"],"конкурс":["russian"],"контроль":["russian"],"концерт":["russian"],"конь":["russian"],"конюшня":["russian"],"копать":["russian"],"копейка":["russian"],"копыто":["russian"],"корабль":["russian"],"корень":["russian"],"корзина":["russian"],"коридор":["russian"],"кормить":["russian"],"корпус":["russian"],"космос":["russian"],"костюм":["russian"],"косяк":["russian"],"котел":["russian"],"котлета":["russian"],"который":["russian"],"коттедж":["russian"],"кофе":["russian"],"кофта":["russian"],"кошка":["russian"],"кража":["russian"],"край":["russian"],"красный":["russian"],"краткий":["russian"],"кредит":["russian"],"крем":["russian"],"крепкий":["russian"],"кресло":["russian"],"кривой":["russian"],"кризис":["russian"],"кристалл":["russian"],"критерий":["russian"],"кричать":["russian"],"кровь":["russian"],"крокодил":["russian"],"кролик":["russian"],"кроме":["russian"],"крона":["russian"],"круг":["russian"],"кружка":["russian"],"крупный":["russian"],"крутой":["russian"],"крушение":["russian"],"крыло":["russian"],"крыша":["russian"],"крючок":["russian"],"кстати":["russian"],"кубик":["russian"],"куда":["russian"],"кузов":["russian"],"кукла":["russian"],"кулак":["russian"],"кулиса":["russian"],"культура":["russian"],"кумир":["russian"],"купе":["russian"],"купить":["russian"],"купол":["russian"],"купюра":["russian"],"курица":["russian"],"курорт":["russian"],"курс":["russian"],"куртка":["russian"],"кусок":["russian"],"куст":["russian"],"кухня":["russian"],"кушать":["russian"],"лабиринт":["russian"],"лавка":["russian"],"лагерь":["russian"],"ладно":["russian"],"ладонь":["russian"],"лапа":["russian"],"лауреат":["russian"],"лгать":["russian"],"лебедь":["russian"],"левый":["russian"],"легенда":["russian"],"легкий":["russian"],"ледяной":["russian"],"лежать":["russian"],"лезвие":["russian"],"лезть":["russian"],"лекция":["russian"],"ленивый":["russian"],"лента":["russian"],"лепесток":["russian"],"лесной":["russian"],"лестница":["russian"],"лететь":["russian"],"лето":["russian"],"лечить":["russian"],"лига":["russian"],"лидер":["russian"],"лиловый":["russian"],"лимон":["russian"],"линия":["russian"],"липкий":["russian"],"лист":["russian"],"литр":["russian"],"лихой":["russian"],"лицо":["russian"],"лишить":["russian"],"лишний":["russian"],"ловить":["russian"],"логика":["russian"],"лодка":["russian"],"ложь":["russian"],"лозунг":["russian"],"локоть":["russian"],"лопата":["russian"],"лошадь":["russian"],"лукавый":["russian"],"луна":["russian"],"лучший":["russian"],"лысый":["russian"],"льгота":["russian"],"любить":["russian"],"любой":["russian"],"людской":["russian"],"люстра":["russian"],"лютый":["russian"],"лягушка":["russian"],"магазин":["russian"],"магия":["russian"],"майор":["russian"],"майский":["russian"],"максимум":["russian"],"макушка":["russian"],"мало":["russian"],"мальчик":["russian"],"мама":["russian"],"манера":["russian"],"марка":["russian"],"март":["russian"],"маршрут":["russian"],"масса":["russian"],"мастер":["russian"],"масштаб":["russian"],"материал":["russian"],"матч":["russian"],"махать":["russian"],"машина":["russian"],"маяк":["russian"],"мебель":["russian"],"медаль":["russian"],"медведь":["russian"],"медицина":["russian"],"медь":["russian"],"между":["russian"],"мелкий":["russian"],"мелочь":["russian"],"мемуары":["russian"],"меньше":["russian"],"меню":["russian"],"менять":["russian"],"мера":["russian"],"мерцать":["russian"],"место":["russian"],"месяц":["russian"],"металл":["russian"],"метод":["russian"],"метр":["russian"],"механизм":["russian"],"меховой":["russian"],"мечтать":["russian"],"мешать":["russian"],"мешок":["russian"],"миграция":["russian"],"микрофон":["russian"],"милиция":["russian"],"миллион":["russian"],"милость":["russian"],"миля":["russian"],"мимо":["russian"],"минерал":["russian"],"министр":["russian"],"минута":["russian"],"мирный":["russian"],"миска":["russian"],"миссия":["russian"],"митинг":["russian"],"мишень":["russian"],"младший":["russian"],"мнение":["russian"],"мнимый":["russian"],"много":["russian"],"могучий":["russian"],"модель":["russian"],"может":["russian"],"мозг":["russian"],"мокрый":["russian"],"молекула":["russian"],"молния":["russian"],"молодой":["russian"],"молчать":["russian"],"момент":["russian"],"монета":["russian"],"монитор":["russian"],"монолог":["russian"],"монстр":["russian"],"монтаж":["russian"],"мораль":["russian"],"море":["russian"],"морковь":["russian"],"мороз":["russian"],"морщина":["russian"],"мостовая":["russian"],"мотать":["russian"],"мотив":["russian"],"мотор":["russian"],"мохнатый":["russian"],"мрамор":["russian"],"мрачный":["russian"],"мстить":["russian"],"мудрый":["russian"],"мужество":["russian"],"мужчина":["russian"],"музей":["russian"],"музыка":["russian"],"мундир":["russian"],"муравей":["russian"],"мусор":["russian"],"муха":["russian"],"мчаться":["russian"],"мысль":["russian"],"мыться":["russian"],"мышца":["russian"],"мышь":["russian"],"мюзикл":["russian"],"мягкий":["russian"],"мясо":["russian"],"набор":["russian"],"навык":["russian"],"наглый":["russian"],"нагрузка":["russian"],"надежда":["russian"],"надзор":["russian"],"надо":["russian"],"наедине":["russian"],"назад":["russian"],"название":["russian"],"назло":["russian"],"наивный":["russian"],"найти":["russian"],"наконец":["russian"],"налево":["russian"],"наличие":["russian"],"налог":["russian"],"намерен":["russian"],"нанести":["russian"],"напасть":["russian"],"например":["russian"],"народ":["russian"],"наследие":["russian"],"натура":["russian"],"наука":["russian"],"наутро":["russian"],"начать":["russian"],"небо":["russian"],"неважно":["russian"],"невеста":["russian"],"негодяй":["russian"],"недавно":["russian"],"неделя":["russian"],"недолго":["russian"],"недра":["russian"],"недуг":["russian"],"нежный":["russian"],"незачем":["russian"],"некто":["russian"],"нелепый":["russian"],"неловко":["russian"],"нельзя":["russian"],"немало":["russian"],"немой":["russian"],"неплохо":["russian"],"нервный":["russian"],"нередко":["russian"],"нестись":["russian"],"неудача":["russian"],"неужели":["russian"],"нефть":["russian"],"неясный":["russian"],"нигде":["russian"],"низкий":["russian"],"никакой":["russian"],"никогда":["russian"],"никуда":["russian"],"ничто":["russian"],"ничуть":["russian"],"ниша":["russian"],"нищий":["russian"],"новость":["russian"],"новый":["russian"],"нога":["russian"],"ноготь":["russian"],"ножницы":["russian"],"ноздря":["russian"],"номер":["russian"],"носить":["russian"],"носок":["russian"],"ночь":["russian"],"ноябрь":["russian"],"нрав":["russian"],"нуль":["russian"],"нынче":["russian"],"нырять":["russian"],"нюанс":["russian"],"няня":["russian"],"обаяние":["russian"],"обед":["russian"],"обезьяна":["russian"],"обещать":["russian"],"обжечь":["russian"],"обзор":["russian"],"обилие":["russian"],"обитать":["russian"],"область":["russian"],"облик":["russian"],"обложка":["russian"],"обмен":["russian"],"обморок":["russian"],"обожать":["russian"],"обои":["russian"],"оболочка":["russian"],"оборона":["russian"],"обочина":["russian"],"образ":["russian"],"обрести":["russian"],"обрыв":["russian"],"обувь":["russian"],"обучение":["russian"],"обход":["russian"],"общество":["russian"],"общий":["russian"],"объект":["russian"],"обыск":["russian"],"обычно":["russian"],"обязать":["russian"],"овощи":["russian"],"овраг":["russian"],"овца":["russian"],"оговорка":["russian"],"ограда":["russian"],"огурец":["russian"],"одежда":["russian"],"одеяло":["russian"],"один":["russian"],"однако":["russian"],"одолеть":["russian"],"ожидать":["russian"],"озеро":["russian"],"океан":["russian"],"окно":["russian"],"около":["russian"],"окоп":["russian"],"окраина":["russian"],"октябрь":["russian"],"опасный":["russian"],"опека":["russian"],"операция":["russian"],"описание":["russian"],"оплата":["russian"],"опора":["russian"],"оппонент":["russian"],"оптимизм":["russian"],"оптовый":["russian"],"опухоль":["russian"],"опыт":["russian"],"оратор":["russian"],"орбита":["russian"],"орган":["russian"],"орден":["russian"],"орел":["russian"],"оригинал":["russian"],"ориентир":["russian"],"оркестр":["russian"],"оружие":["russian"],"осенний":["russian"],"осколок":["russian"],"осмотр":["russian"],"остров":["russian"],"отбор":["russian"],"отбыть":["russian"],"отвлечь":["russian"],"отдать":["russian"],"отдел":["russian"],"отдых":["russian"],"отель":["russian"],"отец":["russian"],"отзыв":["russian"],"отказ":["russian"],"отклик":["russian"],"открыть":["russian"],"откуда":["russian"],"отличие":["russian"],"отныне":["russian"],"отойти":["russian"],"отпуск":["russian"],"отрасль":["russian"],"отросток":["russian"],"отрывок":["russian"],"отряд":["russian"],"отсек":["russian"],"отставка":["russian"],"отсюда":["russian"],"оттенок":["russian"],"оттого":["russian"],"отчего":["russian"],"отъезд":["russian"],"офис":["russian"],"офицер":["russian"],"охота":["russian"],"охрана":["russian"],"оценка":["russian"],"очаг":["russian"],"очень":["russian"],"очередь":["russian"],"очищать":["russian"],"ошибка":["russian"],"ощущение":["russian"],"павильон":["russian"],"падать":["russian"],"пазуха":["russian"],"пакет":["russian"],"палата":["russian"],"палец":["russian"],"палуба":["russian"],"пальто":["russian"],"память":["russian"],"панель":["russian"],"паника":["russian"],"пара":["russian"],"парень":["russian"],"пароход":["russian"],"партия":["russian"],"парус":["russian"],"паспорт":["russian"],"пассажир":["russian"],"пастух":["russian"],"патент":["russian"],"патрон":["russian"],"пауза":["russian"],"паук":["russian"],"паутина":["russian"],"пафос":["russian"],"пахнуть":["russian"],"пациент":["russian"],"пачка":["russian"],"певец":["russian"],"педагог":["russian"],"пейзаж":["russian"],"пенсия":["russian"],"пепел":["russian"],"первый":["russian"],"перед":["russian"],"период":["russian"],"перо":["russian"],"перрон":["russian"],"персонаж":["russian"],"перчатка":["russian"],"песня":["russian"],"песок":["russian"],"петля":["russian"],"петрушка":["russian"],"петух":["russian"],"пехота":["russian"],"печать":["russian"],"печень":["russian"],"пешком":["russian"],"пещера":["russian"],"пианист":["russian"],"пиджак":["russian"],"пилот":["russian"],"пионер":["russian"],"пирамида":["russian"],"пирожок":["russian"],"письмо":["russian"],"пища":["russian"],"плавание":["russian"],"плакать":["russian"],"пламя":["russian"],"план":["russian"],"пласт":["russian"],"платить":["russian"],"пленный":["russian"],"плечо":["russian"],"плита":["russian"],"плод":["russian"],"плоский":["russian"],"плотный":["russian"],"плохой":["russian"],"площадь":["russian"],"плыть":["russian"],"плюс":["russian"],"пляж":["russian"],"плясать":["russian"],"победа":["russian"],"повар":["russian"],"повод":["russian"],"повсюду":["russian"],"повязка":["russian"],"погода":["russian"],"погреб":["russian"],"подбор":["russian"],"подвиг":["russian"],"подделка":["russian"],"поджать":["russian"],"поднос":["russian"],"подпись":["russian"],"подруга":["russian"],"подход":["russian"],"подчас":["russian"],"подъезд":["russian"],"поединок":["russian"],"поезд":["russian"],"поесть":["russian"],"поехать":["russian"],"пожалуй":["russian"],"пожилой":["russian"],"позади":["russian"],"позвать":["russian"],"поздний":["russian"],"позиция":["russian"],"позор":["russian"],"поиск":["russian"],"поймать":["russian"],"пойти":["russian"],"поклон":["russian"],"покой":["russian"],"покрыть":["russian"],"полдень":["russian"],"полезный":["russian"],"ползти":["russian"],"полк":["russian"],"полный":["russian"],"половина":["russian"],"полтора":["russian"],"польза":["russian"],"поляна":["russian"],"помидор":["russian"],"помнить":["russian"],"помощь":["russian"],"попасть":["russian"],"поперек":["russian"],"поплыть":["russian"],"пополам":["russian"],"поправка":["russian"],"попугай":["russian"],"попытка":["russian"],"порог":["russian"],"портрет":["russian"],"порция":["russian"],"порыв":["russian"],"порядок":["russian"],"после":["russian"],"посол":["russian"],"посреди":["russian"],"постель":["russian"],"посуда":["russian"],"потом":["russian"],"похвала":["russian"],"похожий":["russian"],"поцелуй":["russian"],"почва":["russian"],"почему":["russian"],"пошлина":["russian"],"поэма":["russian"],"поэтому":["russian"],"право":["russian"],"праздник":["russian"],"практика":["russian"],"прах":["russian"],"преграда":["russian"],"предмет":["russian"],"прежде":["russian"],"прелесть":["russian"],"премия":["russian"],"препарат":["russian"],"пресса":["russian"],"прибыть":["russian"],"прижать":["russian"],"прийти":["russian"],"приказ":["russian"],"прилавок":["russian"],"пример":["russian"],"принять":["russian"],"природа":["russian"],"притом":["russian"],"прихожая":["russian"],"прицел":["russian"],"причина":["russian"],"приют":["russian"],"прогноз":["russian"],"продукт":["russian"],"проект":["russian"],"прожить":["russian"],"прокат":["russian"],"промысел":["russian"],"пропуск":["russian"],"просто":["russian"],"против":["russian"],"профиль":["russian"],"процесс":["russian"],"прочий":["russian"],"прошлый":["russian"],"прощать":["russian"],"пружина":["russian"],"прут":["russian"],"прыжок":["russian"],"прямой":["russian"],"птица":["russian"],"публика":["russian"],"пугать":["russian"],"пуговица":["russian"],"пузырь":["russian"],"пульт":["russian"],"пуля":["russian"],"пункт":["russian"],"пускать":["russian"],"пустой":["russian"],"путь":["russian"],"пухлый":["russian"],"пучок":["russian"],"пушистый":["russian"],"пушка":["russian"],"пчела":["russian"],"пшеница":["russian"],"пылать":["russian"],"пыль":["russian"],"пышный":["russian"],"пьеса":["russian"],"пятка":["russian"],"пятно":["russian"],"пятый":["russian"],"пятьсот":["russian"],"работа":["russian"],"равнина":["russian"],"ради":["russian"],"радость":["russian"],"радуга":["russian"],"разбить":["russian"],"развитие":["russian"],"разговор":["russian"],"раздел":["russian"],"различие":["russian"],"размер":["russian"],"разный":["russian"],"разрыв":["russian"],"разум":["russian"],"район":["russian"],"ракета":["russian"],"раковина":["russian"],"рамка":["russian"],"рано":["russian"],"рапорт":["russian"],"распад":["russian"],"рассказ":["russian"],"расти":["russian"],"расход":["russian"],"расцвет":["russian"],"рация":["russian"],"рвануть":["russian"],"рваться":["russian"],"реакция":["russian"],"ребро":["russian"],"реветь":["russian"],"редактор":["russian"],"редкий":["russian"],"реестр":["russian"],"режим":["russian"],"резать":["russian"],"резерв":["russian"],"резина":["russian"],"резко":["russian"],"резной":["russian"],"рейс":["russian"],"реклама":["russian"],"рекорд":["russian"],"религия":["russian"],"рельс":["russian"],"ремень":["russian"],"ремонт":["russian"],"реплика":["russian"],"репортаж":["russian"],"ресница":["russian"],"ресторан":["russian"],"реформа":["russian"],"рецепт":["russian"],"речь":["russian"],"решение":["russian"],"ржавый":["russian"],"риск":["russian"],"рисунок":["russian"],"ритуал":["russian"],"рифма":["russian"],"робко":["russian"],"робот":["russian"],"ровесник":["russian"],"ровно":["russian"],"родной":["russian"],"рождение":["russian"],"роза":["russian"],"розовый":["russian"],"розыск":["russian"],"роль":["russian"],"роман":["russian"],"роскошь":["russian"],"роспись":["russian"],"рост":["russian"],"рубашка":["russian"],"рубеж":["russian"],"рубить":["russian"],"рубрика":["russian"],"рудник":["russian"],"рука":["russian"],"рукопись":["russian"],"румяный":["russian"],"русло":["russian"],"рухнуть":["russian"],"ручей":["russian"],"ручной":["russian"],"рыба":["russian"],"рыжий":["russian"],"рынок":["russian"],"рыхлый":["russian"],"рыцарь":["russian"],"рычаг":["russian"],"рюкзак":["russian"],"рядом":["russian"],"садовый":["russian"],"сажать":["russian"],"салон":["russian"],"салфетка":["russian"],"салют":["russian"],"самец":["russian"],"самовар":["russian"],"самый":["russian"],"сани":["russian"],"санкция":["russian"],"сапог":["russian"],"сарай":["russian"],"сатира":["russian"],"сахар":["russian"],"сбить":["russian"],"сбоку":["russian"],"сборная":["russian"],"сбыт":["russian"],"свадьба":["russian"],"свалка":["russian"],"сварить":["russian"],"свежий":["russian"],"сверху":["russian"],"свет":["russian"],"свеча":["russian"],"свинья":["russian"],"свист":["russian"],"свитер":["russian"],"свобода":["russian"],"сводка":["russian"],"свой":["russian"],"свыше":["russian"],"связь":["russian"],"сдаться":["russian"],"сделать":["russian"],"сегмент":["russian"],"сегодня":["russian"],"седло":["russian"],"седой":["russian"],"седьмой":["russian"],"сезон":["russian"],"сейф":["russian"],"сейчас":["russian"],"секрет":["russian"],"сектор":["russian"],"секунда":["russian"],"семинар":["russian"],"семья":["russian"],"сенатор":["russian"],"сено":["russian"],"сенсация":["russian"],"сентябрь":["russian"],"сервис":["russian"],"сердце":["russian"],"середина":["russian"],"сержант":["russian"],"серия":["russian"],"серый":["russian"],"сессия":["russian"],"сесть":["russian"],"сетевой":["russian"],"сжатый":["russian"],"сжечь":["russian"],"сзади":["russian"],"сигнал":["russian"],"сиденье":["russian"],"сила":["russian"],"силуэт":["russian"],"сильный":["russian"],"символ":["russian"],"симпатия":["russian"],"симфония":["russian"],"синий":["russian"],"синтез":["russian"],"синяк":["russian"],"сирень":["russian"],"система":["russian"],"ситуация":["russian"],"сияние":["russian"],"сказать":["russian"],"скала":["russian"],"скамейка":["russian"],"скандал":["russian"],"скатерть":["russian"],"скачок":["russian"],"скважина":["russian"],"сквер":["russian"],"сквозь":["russian"],"скелет":["russian"],"скидка":["russian"],"склад":["russian"],"сколько":["russian"],"скорый":["russian"],"скосить":["russian"],"скот":["russian"],"скрипка":["russian"],"скудный":["russian"],"скука":["russian"],"слабый":["russian"],"слава":["russian"],"сладкий":["russian"],"слегка":["russian"],"след":["russian"],"слеза":["russian"],"слепой":["russian"],"слесарь":["russian"],"слишком":["russian"],"слово":["russian"],"слог":["russian"],"сложный":["russian"],"сломать":["russian"],"служба":["russian"],"слух":["russian"],"случай":["russian"],"слышать":["russian"],"слюна":["russian"],"смежный":["russian"],"смелый":["russian"],"сменить":["russian"],"смесь":["russian"],"сметана":["russian"],"смех":["russian"],"смола":["russian"],"смуглый":["russian"],"смутный":["russian"],"смущать":["russian"],"смысл":["russian"],"снайпер":["russian"],"снаряд":["russian"],"сначала":["russian"],"снег":["russian"],"снизу":["russian"],"сниться":["russian"],"сно��а":["russian"],"снять":["russian"],"собака":["russian"],"соблазн":["russian"],"собрание":["russian"],"событие":["russian"],"совесть":["russian"],"совсем":["russian"],"согласие":["russian"],"создать":["russian"],"сознание":["russian"],"созреть":["russian"],"сойтись":["russian"],"сокол":["russian"],"солдат":["russian"],"соленый":["russian"],"солнце":["russian"],"солома":["russian"],"сомнение":["russian"],"сонный":["russian"],"соперник":["russian"],"соратник":["russian"],"сорвать":["russian"],"сосед":["russian"],"сосиска":["russian"],"состав":["russian"],"сотня":["russian"],"соус":["russian"],"союз":["russian"],"спад":["russian"],"спальня":["russian"],"спасти":["russian"],"спектр":["russian"],"сперва":["russian"],"спешить":["russian"],"спина":["russian"],"спирт":["russian"],"список":["russian"],"спичка":["russian"],"сплав":["russian"],"спонсор":["russian"],"спор":["russian"],"способ":["russian"],"справка":["russian"],"спустя":["russian"],"спутник":["russian"],"сразу":["russian"],"средство":["russian"],"срок":["russian"],"срыв":["russian"],"ссора":["russian"],"ссылка":["russian"],"ставить":["russian"],"стадия":["russian"],"стакан":["russian"],"станция":["russian"],"старый":["russian"],"стая":["russian"],"стебель":["russian"],"стекло":["russian"],"стена":["russian"],"степень":["russian"],"стереть":["russian"],"стиль":["russian"],"стимул":["russian"],"стирать":["russian"],"стихи":["russian"],"стоить":["russian"],"стойка":["russian"],"стол":["russian"],"стонать":["russian"],"стопа":["russian"],"сторона":["russian"],"стоянка":["russian"],"страна":["russian"],"стричь":["russian"],"строгий":["russian"],"струя":["russian"],"студент":["russian"],"стук":["russian"],"ступня":["russian"],"стыдно":["russian"],"суббота":["russian"],"субъект":["russian"],"сувенир":["russian"],"сугроб":["russian"],"сугубо":["russian"],"судить":["russian"],"судно":["russian"],"судьба":["russian"],"суета":["russian"],"суметь":["russian"],"сумма":["russian"],"сумрак":["russian"],"сундук":["russian"],"супруг":["russian"],"суровый":["russian"],"сутки":["russian"],"сухой":["russian"],"суша":["russian"],"существо":["russian"],"сфера":["russian"],"схема":["russian"],"схожий":["russian"],"сценарий":["russian"],"счастье":["russian"],"считать":["russian"],"съезд":["russian"],"сыграть":["russian"],"сырой":["russian"],"сытый":["russian"],"сыщик":["russian"],"сюда":["russian"],"сюжет":["russian"],"сюрприз":["russian"],"тайна":["russian"],"также":["russian"],"такой":["russian"],"такси":["russian"],"тактика":["russian"],"талия":["russian"],"таможня":["russian"],"танец":["russian"],"таракан":["russian"],"тарелка":["russian"],"тариф":["russian"],"тащить":["russian"],"таять":["russian"],"тварь":["russian"],"театр":["russian"],"тезис":["russian"],"текст":["russian"],"текущий":["russian"],"телефон":["russian"],"тема":["russian"],"темнота":["russian"],"теневой":["russian"],"теннис":["russian"],"теория":["russian"],"теперь":["russian"],"тепло":["russian"],"терапия":["russian"],"терзать":["russian"],"термин":["russian"],"терпеть":["russian"],"терраса":["russian"],"терять":["russian"],"тесный":["russian"],"тетрадь":["russian"],"техника":["russian"],"течение":["russian"],"тигр":["russian"],"типовой":["russian"],"тираж":["russian"],"титул":["russian"],"тихий":["russian"],"ткань":["russian"],"товарищ":["russian"],"тоже":["russian"],"толпа":["russian"],"толстый":["russian"],"толчок":["russian"],"толщина":["russian"],"только":["russian"],"тонкий":["russian"],"тонна":["russian"],"топить":["russian"],"топор":["russian"],"торговля":["russian"],"тормоз":["russian"],"торчать":["russian"],"тотчас":["russian"],"точка":["russian"],"точно":["russian"],"тощий":["russian"],"трава":["russian"],"традиция":["russian"],"трактор":["russian"],"трамвай":["russian"],"траншея":["russian"],"трасса":["russian"],"тревога":["russian"],"трезвый":["russian"],"тренер":["russian"],"трепет":["russian"],"треск":["russian"],"третий":["russian"],"трещина":["russian"],"трибуна":["russian"],"тридцать":["russian"],"триста":["russian"],"триумф":["russian"],"трогать":["russian"],"тройка":["russian"],"тронуть":["russian"],"тропа":["russian"],"тротуар":["russian"],"трубка":["russian"],"труд":["russian"],"трюк":["russian"],"тряпка":["russian"],"туго":["russian"],"туловище":["russian"],"туман":["russian"],"тумбочка":["russian"],"тундра":["russian"],"тупик":["russian"],"турист":["russian"],"турнир":["russian"],"тусклый":["russian"],"туфля":["russian"],"туча":["russian"],"тысяча":["russian"],"тяга":["russian"],"тяжело":["russian"],"убежать":["russian"],"убогий":["russian"],"уборка":["russian"],"уважение":["russian"],"увезти":["russian"],"уволить":["russian"],"угадать":["russian"],"угол":["russian"],"угощать":["russian"],"угроза":["russian"],"угрюмый":["russian"],"удар":["russian"],"удачный":["russian"],"уделять":["russian"],"удивить":["russian"],"удобный":["russian"],"удочка":["russian"],"уезжать":["russian"],"ужин":["russian"],"узел":["russian"],"узкий":["russian"],"уйти":["russian"],"указание":["russian"],"уклон":["russian"],"украсть":["russian"],"укусить":["russian"],"улетать":["russian"],"улица":["russian"],"улыбка":["russian"],"умело":["russian"],"умение":["russian"],"умный":["russian"],"умолять":["russian"],"унести":["russian"],"унижать":["russian"],"унылый":["russian"],"упаковка":["russian"],"упасть":["russian"],"упорно":["russian"],"упрек":["russian"],"урна":["russian"],"уровень":["russian"],"урожай":["russian"],"уронить":["russian"],"усадьба":["russian"],"усатый":["russian"],"усвоить":["russian"],"усилие":["russian"],"условие":["russian"],"услуга":["russian"],"усмешка":["russian"],"успеть":["russian"],"устав":["russian"],"устоять":["russian"],"утечка":["russian"],"утешать":["russian"],"утро":["russian"],"уцелеть":["russian"],"участие":["russian"],"ученик":["russian"],"учесть":["russian"],"ущелье":["russian"],"ущерб":["russian"],"уютный":["russian"],"фабрика":["russian"],"фаворит":["russian"],"факел":["russian"],"факт":["russian"],"фамилия":["russian"],"фантазия":["russian"],"фасад":["russian"],"февраль":["russian"],"феномен":["russian"],"фермер":["russian"],"фигура":["russian"],"физика":["russian"],"филиал":["russian"],"философ":["russian"],"фильм":["russian"],"финал":["russian"],"флаг":["russian"],"флот":["russian"],"фойе":["russian"],"фокус":["russian"],"фонарь":["russian"],"фонд":["russian"],"фонтан":["russian"],"форма":["russian"],"форум":["russian"],"фото":["russian"],"фрагмент":["russian"],"фраза":["russian"],"фракция":["russian"],"фронт":["russian"],"фрукт":["russian"],"функция":["russian"],"фуражка":["russian"],"футбол":["russian"],"футляр":["russian"],"халат":["russian"],"хаос":["russian"],"характер":["russian"],"хата":["russian"],"хвалить":["russian"],"хватать":["russian"],"хвойный":["russian"],"хвост":["russian"],"химия":["russian"],"хирург":["russian"],"хитрый":["russian"],"хищник":["russian"],"хлеб":["russian"],"хлынуть":["russian"],"хмурый":["russian"],"ходить":["russian"],"хозяин":["russian"],"хоккей":["russian"],"холм":["russian"],"холст":["russian"],"хорошо":["russian"],"хотеть":["russian"],"храбрый":["russian"],"храм":["russian"],"хранить":["russian"],"хребет":["russian"],"хрен":["russian"],"хрипло":["russian"],"хроника":["russian"],"хрупкий":["russian"],"художник":["russian"],"худший":["russian"],"хулиган":["russian"],"хутор":["russian"],"царь":["russian"],"цветок":["russian"],"целевой":["russian"],"целиком":["russian"],"целое":["russian"],"цель":["russian"],"цензура":["russian"],"ценить":["russian"],"центр":["russian"],"цепной":["russian"],"цикл":["russian"],"цилиндр":["russian"],"цирк":["russian"],"цитата":["russian"],"цифра":["russian"],"чайник":["russian"],"часы":["russian"],"чашка":["russian"],"человек":["russian"],"челюсть":["russian"],"чемодан":["russian"],"чемпион":["russian"],"чепуха":["russian"],"червь":["russian"],"чердак":["russian"],"через":["russian"],"чернила":["russian"],"черта":["russian"],"чеснок":["russian"],"честно":["russian"],"четверть":["russian"],"четыре":["russian"],"число":["russian"],"чистый":["russian"],"читатель":["russian"],"чтение":["russian"],"чтобы":["russian"],"чувство":["russian"],"чудак":["russian"],"чудный":["russian"],"чудо":["russian"],"чужой":["russian"],"чулок":["russian"],"чума":["russian"],"чушь":["russian"],"чуять":["russian"],"шагать":["russian"],"шанс":["russian"],"шапка":["russian"],"шарик":["russian"],"шарф":["russian"],"шахматы":["russian"],"шашлык":["russian"],"шедевр":["russian"],"шептать":["russian"],"шерсть":["russian"],"шестой":["russian"],"шинель":["russian"],"ширина":["russian"],"шишка":["russian"],"шкаф":["russian"],"школа":["russian"],"шкура":["russian"],"шланг":["russian"],"шлем":["russian"],"шнур":["russian"],"шоколад":["russian"],"шорох":["russian"],"шоссе":["russian"],"шпион":["russian"],"шприц":["russian"],"штаб":["russian"],"штамм":["russian"],"штаны":["russian"],"штатный":["russian"],"штора":["russian"],"штраф":["russian"],"штурм":["russian"],"штык":["russian"],"шумно":["russian"],"шуршать":["russian"],"шутить":["russian"],"шутка":["russian"],"щедрый":["russian"],"щека":["russian"],"щенок":["russian"],"экзамен":["russian"],"экипаж":["russian"],"экономия":["russian"],"экран":["russian"],"эксперт":["russian"],"элемент":["russian"],"элитный":["russian"],"эмоция":["russian"],"энергия":["russian"],"эпизод":["russian"],"эпоха":["russian"],"эскиз":["russian"],"эстрада":["russian"],"этап":["russian"],"этика":["russian"],"этот":["russian"],"эфир":["russian"],"эффект":["russian"],"эшелон":["russian"],"юбилей":["russian"],"юбка":["russian"],"южный":["russian"],"юмор":["russian"],"юность":["russian"],"юрист":["russian"],"юстиция":["russian"],"яблоко":["russian"],"явление":["russian"],"ягода":["russian"],"ядро":["russian"],"язык":["russian"],"яйцо":["russian"],"якобы":["russian"],"якорь":["russian"],"январь":["russian"],"яркий":["russian"],"ярмарка":["russian"],"ярость":["russian"],"ясный":["russian"],"яхта":["russian"],"ячейка":["russian"],"ящик":["russian"],"ábaco":["spanish"],"abdomen":["spanish"],"abeja":["spanish"],"abierto":["spanish"],"abogado":["spanish"],"abono":["spanish"],"aborto":["spanish"],"abrazo":["spanish"],"abrir":["spanish"],"abuelo":["spanish"],"abuso":["spanish"],"acabar":["spanish"],"academia":["spanish"],"acceso":["spanish"],"acción":["spanish"],"aceite":["spanish"],"acelga":["spanish"],"acento":["spanish"],"aceptar":["spanish"],"ácido":["spanish"],"aclarar":["spanish"],"acné":["spanish"],"acoger":["spanish"],"acoso":["spanish"],"activo":["spanish"],"acto":["spanish"],"actriz":["spanish"],"actuar":["spanish"],"acudir":["spanish"],"acuerdo":["spanish"],"acusar":["spanish"],"adicto":["spanish"],"admitir":["spanish"],"adoptar":["spanish"],"adorno":["spanish"],"aduana":["spanish"],"adulto":["spanish"],"aéreo":["spanish"],"afectar":["spanish"],"afición":["spanish"],"afinar":["spanish"],"afirmar":["spanish"],"ágil":["spanish"],"agitar":["spanish"],"agonía":["spanish"],"agosto":["spanish"],"agotar":["spanish"],"agregar":["spanish"],"agrio":["spanish"],"agua":["spanish"],"agudo":["spanish"],"águila":["spanish"],"aguja":["spanish"],"ahogo":["spanish"],"ahorro":["spanish"],"aire":["spanish"],"aislar":["spanish"],"ajedrez":["spanish"],"ajeno":["spanish"],"ajuste":["spanish"],"alacrán":["spanish"],"alambre":["spanish"],"alarma":["spanish"],"alba":["spanish"],"álbum":["spanish"],"alcalde":["spanish"],"aldea":["spanish"],"alegre":["spanish"],"alejar":["spanish"],"alerta":["spanish"],"aleta":["spanish"],"alfiler":["spanish"],"alga":["spanish"],"algodón":["spanish"],"aliado":["spanish"],"aliento":["spanish"],"alivio":["spanish"],"alma":["spanish"],"almeja":["spanish"],"almíbar":["spanish"],"altar":["spanish"],"alteza":["spanish"],"altivo":["spanish"],"alto":["spanish"],"altura":["spanish"],"alumno":["spanish"],"alzar":["spanish"],"amable":["spanish"],"amante":["spanish"],"amapola":["spanish"],"amargo":["spanish"],"amasar":["spanish"],"ámbar":["spanish"],"ámbito":["spanish"],"ameno":["spanish"],"amigo":["spanish","turkish"],"amistad":["spanish"],"amor":["spanish"],"amparo":["spanish"],"amplio":["spanish"],"ancho":["spanish"],"anciano":["spanish"],"ancla":["spanish"],"andar":["spanish"],"andén":["spanish"],"anemia":["spanish"],"ángulo":["spanish"],"anillo":["spanish"],"ánimo":["spanish"],"anís":["spanish"],"anotar":["spanish"],"antena":["spanish"],"antiguo":["spanish"],"antojo":["spanish"],"anual":["spanish"],"anular":["spanish"],"anuncio":["spanish"],"añadir":["spanish"],"añejo":["spanish"],"año":["spanish"],"apagar":["spanish"],"aparato":["spanish"],"apetito":["spanish"],"apio":["spanish"],"aplicar":["spanish"],"apodo":["spanish"],"aporte":["spanish"],"apoyo":["spanish"],"aprender":["spanish"],"aprobar":["spanish"],"apuesta":["spanish"],"apuro":["spanish"],"arado":["spanish"],"araña":["spanish"],"arar":["spanish"],"árbitro":["spanish"],"árbol":["spanish"],"arbusto":["spanish"],"archivo":["spanish"],"arco":["spanish"],"arder":["spanish"],"ardilla":["spanish"],"arduo":["spanish"],"área":["spanish"],"árido":["spanish"],"aries":["spanish"],"armonía":["spanish"],"arnés":["spanish"],"aroma":["spanish","turkish"],"arpa":["spanish"],"arpón":["spanish"],"arreglo":["spanish"],"arroz":["spanish"],"arruga":["spanish"],"arte":["spanish"],"artista":["spanish"],"asa":["spanish"],"asado":["spanish"],"asalto":["spanish"],"ascenso":["spanish"],"asegurar":["spanish"],"aseo":["spanish"],"asesor":["spanish"],"asiento":["spanish"],"asilo":["spanish"],"asistir":["spanish"],"asno":["spanish"],"asombro":["spanish"],"áspero":["spanish"],"astilla":["spanish"],"astro":["spanish"],"astuto":["spanish"],"asumir":["spanish"],"asunto":["spanish"],"atajo":["spanish"],"ataque":["spanish"],"atar":["spanish"],"atento":["spanish"],"ateo":["spanish"],"ático":["spanish"],"atleta":["spanish"],"átomo":["spanish"],"atraer":["spanish"],"atroz":["spanish"],"atún":["spanish"],"audaz":["spanish"],"audio":["spanish"],"auge":["spanish"],"aula":["spanish"],"aumento":["spanish"],"ausente":["spanish"],"autor":["spanish"],"aval":["spanish"],"avance":["spanish"],"avaro":["spanish"],"ave":["spanish"],"avellana":["spanish"],"avena":["spanish"],"avestruz":["spanish"],"avión":["spanish"],"aviso":["spanish"],"ayer":["spanish"],"ayuda":["spanish"],"ayuno":["spanish"],"azafrán":["spanish"],"azar":["spanish"],"azote":["spanish"],"azúcar":["spanish"],"azufre":["spanish"],"azul":["spanish"],"baba":["spanish"],"babor":["spanish"],"bache":["spanish"],"bahía":["spanish"],"baile":["spanish"],"bajar":["spanish"],"balanza":["spanish"],"balcón":["spanish"],"balde":["spanish"],"bambú":["spanish"],"banco":["spanish"],"banda":["spanish"],"baño":["spanish"],"barba":["spanish"],"barco":["spanish"],"barniz":["spanish"],"barro":["spanish"],"báscula":["spanish"],"bastón":["spanish"],"basura":["spanish"],"batalla":["spanish"],"batería":["spanish"],"batir":["spanish"],"batuta":["spanish"],"baúl":["spanish"],"bazar":["spanish"],"bebé":["spanish"],"bebida":["spanish"],"bello":["spanish"],"besar":["spanish"],"beso":["spanish"],"bestia":["spanish"],"bicho":["spanish"],"bien":["spanish"],"bingo":["spanish"],"blanco":["spanish"],"bloque":["spanish"],"blusa":["spanish"],"boa":["spanish"],"bobina":["spanish"],"bobo":["spanish"],"boca":["spanish"],"bocina":["spanish"],"boda":["spanish"],"bodega":["spanish"],"boina":["spanish"],"bola":["spanish"],"bolero":["spanish","turkish"],"bolsa":["spanish"],"bomba":["spanish"],"bondad":["spanish"],"bonito":["spanish"],"bono":["spanish"],"bonsái":["spanish"],"borde":["spanish"],"borrar":["spanish"],"bosque":["spanish"],"bote":["spanish"],"botín":["spanish"],"bóveda":["spanish"],"bozal":["spanish"],"bravo":["spanish"],"brazo":["spanish"],"brecha":["spanish"],"breve":["spanish"],"brillo":["spanish"],"brinco":["spanish"],"brisa":["spanish"],"broca":["spanish"],"broma":["spanish"],"bronce":["spanish"],"brote":["spanish"],"bruja":["spanish"],"brusco":["spanish"],"bruto":["spanish"],"buceo":["spanish"],"bucle":["spanish"],"bueno":["spanish"],"buey":["spanish"],"bufanda":["spanish"],"bufón":["spanish"],"búho":["spanish"],"buitre":["spanish"],"bulto":["spanish"],"burbuja":["spanish"],"burla":["spanish"],"burro":["spanish"],"buscar":["spanish"],"butaca":["spanish"],"buzón":["spanish"],"caballo":["spanish"],"cabeza":["spanish"],"cabina":["spanish"],"cabra":["spanish"],"cacao":["spanish"],"cadáver":["spanish"],"cadena":["spanish"],"caer":["spanish"],"café":["spanish"],"caída":["spanish"],"caimán":["spanish"],"caja":["spanish"],"cajón":["spanish"],"cal":["spanish"],"calamar":["spanish"],"calcio":["spanish"],"caldo":["spanish"],"calidad":["spanish"],"calle":["spanish"],"calma":["spanish"],"calor":["spanish"],"calvo":["spanish"],"cama":["spanish"],"cambio":["spanish"],"camello":["spanish"],"camino":["spanish"],"campo":["spanish"],"cáncer":["spanish"],"candil":["spanish"],"canela":["spanish"],"canguro":["spanish"],"canica":["spanish"],"canto":["spanish"],"caña":["spanish"],"cañón":["spanish"],"caoba":["spanish"],"caos":["spanish"],"capaz":["spanish"],"capitán":["spanish"],"capote":["spanish"],"captar":["spanish"],"capucha":["spanish"],"cara":["spanish"],"carbón":["spanish"],"cárcel":["spanish"],"careta":["spanish"],"carga":["spanish"],"cariño":["spanish"],"carne":["spanish"],"carpeta":["spanish"],"carro":["spanish"],"carta":["spanish"],"casa":["spanish"],"casco":["spanish"],"casero":["spanish"],"caspa":["spanish"],"castor":["spanish"],"catorce":["spanish"],"catre":["spanish"],"caudal":["spanish"],"causa":["spanish"],"cazo":["spanish"],"cebolla":["spanish"],"ceder":["spanish"],"cedro":["spanish"],"celda":["spanish"],"célebre":["spanish"],"celoso":["spanish"],"célula":["spanish"],"cemento":["spanish"],"ceniza":["spanish"],"centro":["spanish"],"cerca":["spanish"],"cerdo":["spanish"],"cereza":["spanish"],"cero":["spanish"],"cerrar":["spanish"],"certeza":["spanish"],"césped":["spanish"],"cetro":["spanish"],"chacal":["spanish"],"chaleco":["spanish"],"champú":["spanish"],"chancla":["spanish"],"chapa":["spanish"],"charla":["spanish"],"chico":["spanish"],"chiste":["spanish"],"chivo":["spanish"],"choque":["spanish"],"choza":["spanish"],"chuleta":["spanish"],"chupar":["spanish"],"ciclón":["spanish"],"ciego":["spanish"],"cielo":["spanish"],"cien":["spanish"],"cierto":["spanish"],"cifra":["spanish"],"cigarro":["spanish"],"cima":["spanish"],"cinco":["spanish"],"cine":["spanish"],"cinta":["spanish"],"ciprés":["spanish"],"circo":["spanish"],"ciruela":["spanish"],"cisne":["spanish"],"cita":["spanish"],"ciudad":["spanish"],"clamor":["spanish"],"clan":["spanish"],"claro":["spanish"],"clase":["spanish"],"clave":["spanish"],"cliente":["spanish"],"clima":["spanish"],"clínica":["spanish"],"cobre":["spanish"],"cocción":["spanish"],"cochino":["spanish"],"cocina":["spanish"],"coco":["spanish"],"código":["spanish"],"codo":["spanish"],"cofre":["spanish"],"coger":["spanish"],"cohete":["spanish"],"cojín":["spanish"],"cojo":["spanish"],"cola":["spanish"],"colcha":["spanish"],"colegio":["spanish"],"colgar":["spanish"],"colina":["spanish"],"collar":["spanish"],"colmo":["spanish"],"columna":["spanish"],"combate":["spanish"],"comer":["spanish"],"comida":["spanish"],"cómodo":["spanish"],"compra":["spanish"],"conde":["spanish"],"conejo":["spanish"],"conga":["spanish"],"conocer":["spanish"],"consejo":["spanish"],"contar":["spanish"],"copa":["spanish"],"copia":["spanish"],"corazón":["spanish"],"corbata":["spanish"],"corcho":["spanish"],"cordón":["spanish"],"corona":["spanish"],"correr":["spanish"],"coser":["spanish"],"cosmos":["spanish"],"costa":["spanish"],"cráneo":["spanish"],"cráter":["spanish"],"crear":["spanish"],"crecer":["spanish"],"creído":["spanish"],"crema":["spanish"],"cría":["spanish"],"crimen":["spanish"],"cripta":["spanish"],"crisis":["spanish"],"cromo":["spanish"],"crónica":["spanish"],"croqueta":["spanish"],"crudo":["spanish"],"cruz":["spanish"],"cuadro":["spanish"],"cuarto":["spanish"],"cuatro":["spanish"],"cubo":["spanish"],"cubrir":["spanish"],"cuchara":["spanish"],"cuello":["spanish"],"cuento":["spanish"],"cuerda":["spanish"],"cuesta":["spanish"],"cueva":["spanish"],"cuidar":["spanish"],"culebra":["spanish"],"culpa":["spanish"],"culto":["spanish"],"cumbre":["spanish"],"cumplir":["spanish"],"cuna":["spanish"],"cuneta":["spanish"],"cuota":["spanish"],"cupón":["spanish"],"cúpula":["spanish"],"curar":["spanish"],"curioso":["spanish"],"curso":["spanish"],"curva":["spanish"],"cutis":["spanish"],"dama":["spanish"],"danza":["spanish"],"dar":["spanish"],"dardo":["spanish"],"dátil":["spanish"],"deber":["spanish"],"débil":["spanish"],"década":["spanish"],"decir":["spanish"],"dedo":["spanish"],"defensa":["spanish"],"definir":["spanish"],"dejar":["spanish"],"delfín":["spanish"],"delgado":["spanish"],"delito":["spanish"],"demora":["spanish"],"denso":["spanish"],"dental":["spanish"],"deporte":["spanish"],"derecho":["spanish"],"derrota":["spanish"],"desayuno":["spanish"],"deseo":["spanish"],"desfile":["spanish"],"desnudo":["spanish"],"destino":["spanish"],"desvío":["spanish"],"detalle":["spanish"],"detener":["spanish"],"deuda":["spanish"],"día":["spanish"],"diablo":["spanish"],"diadema":["spanish"],"diamante":["spanish"],"diana":["spanish"],"diario":["spanish"],"dibujo":["spanish"],"dictar":["spanish"],"diente":["spanish"],"dieta":["spanish"],"diez":["spanish"],"difícil":["spanish"],"digno":["spanish"],"dilema":["spanish"],"diluir":["spanish"],"dinero":["spanish"],"directo":["spanish"],"dirigir":["spanish"],"disco":["spanish"],"diseño":["spanish"],"disfraz":["spanish"],"diva":["spanish"],"divino":["spanish"],"doble":["spanish"],"doce":["spanish"],"dolor":["spanish"],"domingo":["spanish"],"don":["spanish"],"donar":["spanish"],"dorado":["spanish"],"dormir":["spanish"],"dorso":["spanish"],"dos":["spanish"],"dosis":["spanish"],"dragón":["spanish"],"droga":["spanish"],"ducha":["spanish"],"duda":["spanish"],"duelo":["spanish"],"dueño":["spanish"],"dulce":["spanish"],"dúo":["spanish"],"duque":["spanish"],"durar":["spanish"],"dureza":["spanish"],"duro":["spanish"],"ébano":["spanish"],"ebrio":["spanish"],"echar":["spanish"],"eco":["spanish"],"ecuador":["spanish"],"edad":["spanish"],"edición":["spanish"],"edificio":["spanish"],"editor":["spanish"],"educar":["spanish"],"efecto":["spanish"],"eficaz":["spanish"],"eje":["spanish"],"ejemplo":["spanish"],"elefante":["spanish"],"elegir":["spanish"],"elemento":["spanish"],"elevar":["spanish"],"elipse":["spanish"],"élite":["spanish"],"elixir":["spanish"],"elogio":["spanish"],"eludir":["spanish"],"embudo":["spanish"],"emitir":["spanish"],"emoción":["spanish"],"empate":["spanish"],"empeño":["spanish"],"empleo":["spanish"],"empresa":["spanish"],"enano":["spanish"],"encargo":["spanish"],"enchufe":["spanish"],"encía":["spanish"],"enemigo":["spanish"],"enero":["spanish"],"enfado":["spanish"],"enfermo":["spanish"],"engaño":["spanish"],"enigma":["spanish"],"enlace":["spanish"],"enorme":["spanish"],"enredo":["spanish"],"ensayo":["spanish"],"enseñar":["spanish"],"entero":["spanish"],"entrar":["spanish"],"envase":["spanish"],"envío":["spanish"],"época":["spanish"],"equipo":["spanish"],"erizo":["spanish"],"escala":["spanish"],"escena":["spanish"],"escolar":["spanish"],"escribir":["spanish"],"escudo":["spanish"],"esencia":["spanish"],"esfera":["spanish"],"esfuerzo":["spanish"],"espada":["spanish"],"espejo":["spanish"],"espía":["spanish"],"esposa":["spanish"],"espuma":["spanish"],"esquí":["spanish"],"estar":["spanish"],"este":["spanish"],"estilo":["spanish"],"estufa":["spanish"],"etapa":["spanish"],"eterno":["spanish"],"ética":["spanish"],"etnia":["spanish"],"evadir":["spanish"],"evaluar":["spanish"],"evento":["spanish"],"evitar":["spanish"],"exacto":["spanish"],"examen":["spanish"],"exceso":["spanish"],"excusa":["spanish"],"exento":["spanish"],"exigir":["spanish"],"exilio":["spanish"],"existir":["spanish"],"éxito":["spanish"],"experto":["spanish"],"explicar":["spanish"],"exponer":["spanish"],"extremo":["spanish"],"fábrica":["spanish"],"fábula":["spanish"],"fachada":["spanish"],"fácil":["spanish"],"factor":["spanish"],"faena":["spanish"],"faja":["spanish"],"falda":["spanish"],"fallo":["spanish"],"falso":["spanish"],"faltar":["spanish"],"fama":["spanish"],"familia":["spanish"],"famoso":["spanish"],"faraón":["spanish"],"farmacia":["spanish"],"farol":["spanish"],"farsa":["spanish"],"fase":["spanish"],"fatiga":["spanish"],"fauna":["spanish","turkish"],"favor":["spanish"],"fax":["spanish"],"febrero":["spanish"],"fecha":["spanish"],"feliz":["spanish"],"feo":["spanish"],"feria":["spanish"],"feroz":["spanish"],"fértil":["spanish"],"fervor":["spanish"],"festín":["spanish"],"fiable":["spanish"],"fianza":["spanish"],"fiar":["spanish"],"fibra":["spanish"],"ficción":["spanish"],"ficha":["spanish"],"fideo":["spanish"],"fiebre":["spanish"],"fiel":["spanish"],"fiera":["spanish"],"fiesta":["spanish"],"figura":["spanish"],"fijar":["spanish"],"fijo":["spanish"],"fila":["spanish"],"filete":["spanish"],"filial":["spanish"],"filtro":["spanish"],"fin":["spanish"],"finca":["spanish"],"fingir":["spanish"],"finito":["spanish"],"firma":["spanish"],"flaco":["spanish"],"flauta":["spanish"],"flecha":["spanish"],"flor":["spanish"],"flota":["spanish"],"fluir":["spanish"],"flujo":["spanish"],"flúor":["spanish"],"fobia":["spanish"],"foca":["spanish"],"fogata":["spanish"],"fogón":["spanish"],"folio":["spanish"],"folleto":["spanish"],"fondo":["spanish"],"forma":["spanish"],"forro":["spanish"],"fortuna":["spanish"],"forzar":["spanish"],"fosa":["spanish"],"foto":["spanish"],"fracaso":["spanish"],"frágil":["spanish"],"franja":["spanish"],"frase":["spanish"],"fraude":["spanish"],"freír":["spanish"],"freno":["spanish"],"fresa":["spanish"],"frío":["spanish"],"frito":["spanish"],"fruta":["spanish"],"fuego":["spanish"],"fuente":["spanish"],"fuerza":["spanish"],"fuga":["spanish"],"fumar":["spanish"],"función":["spanish"],"funda":["spanish"],"furgón":["spanish"],"furia":["spanish"],"fusil":["spanish"],"fútbol":["spanish"],"futuro":["spanish"],"gacela":["spanish"],"gafas":["spanish"],"gaita":["spanish"],"gajo":["spanish"],"gala":["spanish"],"galería":["spanish"],"gallo":["spanish"],"gamba":["spanish"],"ganar":["spanish"],"gancho":["spanish"],"ganga":["spanish"],"ganso":["spanish"],"garaje":["spanish"],"garza":["spanish"],"gasolina":["spanish"],"gastar":["spanish"],"gato":["spanish"],"gavilán":["spanish"],"gemelo":["spanish"],"gemir":["spanish"],"gen":["spanish"],"género":["spanish"],"genio":["spanish"],"gente":["spanish"],"geranio":["spanish"],"gerente":["spanish"],"germen":["spanish"],"gesto":["spanish"],"gigante":["spanish"],"gimnasio":["spanish"],"girar":["spanish"],"giro":["spanish"],"glaciar":["spanish"],"globo":["spanish"],"gloria":["spanish"],"gol":["spanish"],"golfo":["spanish"],"goloso":["spanish"],"golpe":["spanish"],"goma":["spanish"],"gordo":["spanish"],"gorila":["spanish"],"gorra":["spanish"],"gota":["spanish"],"goteo":["spanish"],"gozar":["spanish"],"grada":["spanish"],"gráfico":["spanish"],"grano":["spanish"],"grasa":["spanish"],"gratis":["spanish"],"grave":["spanish"],"grieta":["spanish"],"grillo":["spanish"],"gripe":["spanish"],"gris":["spanish"],"grito":["spanish"],"grosor":["spanish"],"grúa":["spanish"],"grueso":["spanish"],"grumo":["spanish"],"grupo":["spanish"],"guante":["spanish"],"guapo":["spanish"],"guardia":["spanish"],"guerra":["spanish"],"guía":["spanish"],"guiño":["spanish"],"guion":["spanish"],"guiso":["spanish"],"guitarra":["spanish"],"gusano":["spanish"],"gustar":["spanish"],"haber":["spanish","turkish"],"hábil":["spanish"],"hablar":["spanish"],"hacer":["spanish"],"hacha":["spanish"],"hada":["spanish"],"hallar":["spanish"],"hamaca":["spanish"],"harina":["spanish"],"haz":["spanish"],"hazaña":["spanish"],"hebilla":["spanish"],"hebra":["spanish"],"hecho":["spanish"],"helado":["spanish"],"helio":["spanish"],"hembra":["spanish"],"herir":["spanish"],"hermano":["spanish"],"héroe":["spanish"],"hervir":["spanish"],"hielo":["spanish"],"hierro":["spanish"],"hígado":["spanish"],"higiene":["spanish"],"hijo":["spanish"],"himno":["spanish"],"historia":["spanish"],"hocico":["spanish"],"hogar":["spanish"],"hoguera":["spanish"],"hoja":["spanish"],"hombre":["spanish"],"hongo":["spanish"],"honor":["spanish"],"honra":["spanish"],"hora":["spanish"],"hormiga":["spanish"],"horno":["spanish"],"hostil":["spanish"],"hoyo":["spanish"],"hueco":["spanish"],"huelga":["spanish"],"huerta":["spanish"],"hueso":["spanish"],"huevo":["spanish"],"huida":["spanish"],"huir":["spanish"],"humano":["spanish"],"húmedo":["spanish"],"humilde":["spanish"],"humo":["spanish"],"hundir":["spanish"],"huracán":["spanish"],"hurto":["spanish"],"icono":["spanish"],"ideal":["spanish"],"idioma":["spanish"],"ídolo":["spanish"],"iglesia":["spanish"],"iglú":["spanish"],"igual":["spanish"],"ilegal":["spanish"],"ilusión":["spanish"],"imagen":["spanish"],"imán":["spanish"],"imitar":["spanish"],"impar":["spanish"],"imperio":["spanish"],"imponer":["spanish"],"impulso":["spanish"],"incapaz":["spanish"],"índice":["spanish"],"inerte":["spanish"],"infiel":["spanish"],"informe":["spanish"],"ingenio":["spanish"],"inicio":["spanish"],"inmenso":["spanish"],"inmune":["spanish"],"innato":["spanish"],"insecto":["spanish"],"instante":["spanish"],"interés":["spanish"],"íntimo":["spanish"],"intuir":["spanish"],"inútil":["spanish"],"invierno":["spanish"],"ira":["spanish"],"iris":["spanish"],"ironía":["spanish"],"isla":["spanish"],"islote":["spanish"],"jabalí":["spanish"],"jabón":["spanish"],"jamón":["spanish"],"jarabe":["spanish"],"jardín":["spanish"],"jarra":["spanish"],"jaula":["spanish"],"jazmín":["spanish"],"jefe":["spanish"],"jeringa":["spanish"],"jinete":["spanish"],"jornada":["spanish"],"joroba":["spanish"],"joven":["spanish"],"joya":["spanish"],"juerga":["spanish"],"jueves":["spanish"],"juez":["spanish"],"jugador":["spanish"],"jugo":["spanish"],"juguete":["spanish"],"juicio":["spanish"],"junco":["spanish"],"jungla":["spanish"],"junio":["spanish"],"juntar":["spanish"],"júpiter":["spanish"],"jurar":["spanish"],"justo":["spanish"],"juvenil":["spanish"],"juzgar":["spanish"],"kilo":["spanish"],"koala":["spanish"],"labio":["spanish"],"lacio":["spanish"],"lacra":["spanish"],"lado":["spanish"],"ladrón":["spanish"],"lagarto":["spanish"],"lágrima":["spanish"],"laguna":["spanish"],"laico":["spanish"],"lamer":["spanish"],"lámina":["spanish"],"lámpara":["spanish"],"lana":["spanish"],"lancha":["spanish"],"langosta":["spanish"],"lanza":["spanish"],"lápiz":["spanish"],"largo":["spanish"],"larva":["spanish"],"lástima":["spanish"],"lata":["spanish"],"látex":["spanish"],"latir":["spanish"],"laurel":["spanish"],"lavar":["spanish"],"lazo":["spanish"],"leal":["spanish"],"lección":["spanish"],"leche":["spanish"],"lector":["spanish"],"leer":["spanish"],"legión":["spanish"],"legumbre":["spanish"],"lejano":["spanish"],"lengua":["spanish"],"lento":["spanish"],"leña":["spanish"],"león":["spanish"],"leopardo":["spanish"],"lesión":["spanish"],"letal":["spanish"],"letra":["spanish"],"leve":["spanish"],"leyenda":["spanish"],"libertad":["spanish"],"libro":["spanish"],"licor":["spanish"],"líder":["spanish"],"lidiar":["spanish"],"lienzo":["spanish"],"liga":["spanish"],"ligero":["spanish"],"lima":["spanish"],"límite":["spanish"],"limón":["spanish"],"limpio":["spanish"],"lince":["spanish"],"lindo":["spanish"],"línea":["spanish"],"lingote":["spanish"],"lino":["spanish"],"linterna":["spanish"],"líquido":["spanish"],"liso":["spanish"],"lista":["spanish"],"litera":["spanish"],"litio":["spanish"],"litro":["spanish"],"llaga":["spanish"],"llama":["spanish"],"llanto":["spanish"],"llave":["spanish"],"llegar":["spanish"],"llenar":["spanish"],"llevar":["spanish"],"llorar":["spanish"],"llover":["spanish"],"lluvia":["spanish"],"lobo":["spanish"],"loción":["spanish"],"loco":["spanish"],"locura":["spanish"],"lógica":["spanish"],"logro":["spanish"],"lombriz":["spanish"],"lomo":["spanish"],"lonja":["spanish"],"lote":["spanish"],"lucha":["spanish"],"lucir":["spanish"],"lugar":["spanish"],"lujo":["spanish"],"luna":["spanish"],"lunes":["spanish"],"lupa":["spanish"],"lustro":["spanish"],"luto":["spanish"],"luz":["spanish"],"maceta":["spanish"],"macho":["spanish"],"madera":["spanish"],"madre":["spanish"],"maduro":["spanish"],"maestro":["spanish"],"mafia":["spanish"],"magia":["spanish"],"mago":["spanish"],"maíz":["spanish"],"maldad":["spanish"],"maleta":["spanish"],"malla":["spanish"],"malo":["spanish"],"mamá":["spanish"],"mambo":["spanish"],"mamut":["spanish"],"manco":["spanish"],"mando":["spanish"],"manejar":["spanish"],"manga":["spanish"],"maniquí":["spanish"],"manjar":["spanish"],"mano":["spanish"],"manso":["spanish"],"manta":["spanish"],"mañana":["spanish"],"mapa":["spanish"],"máquina":["spanish"],"mar":["spanish"],"marco":["spanish"],"marea":["spanish"],"marfil":["spanish"],"margen":["spanish"],"marido":["spanish"],"mármol":["spanish"],"marrón":["spanish"],"martes":["spanish"],"marzo":["spanish"],"masa":["spanish"],"máscara":["spanish"],"masivo":["spanish"],"matar":["spanish"],"materia":["spanish"],"matiz":["spanish"],"matriz":["spanish"],"máximo":["spanish"],"mayor":["spanish"],"mazorca":["spanish"],"mecha":["spanish"],"medalla":["spanish"],"medio":["spanish"],"médula":["spanish"],"mejilla":["spanish"],"mejor":["spanish"],"melena":["spanish"],"melón":["spanish"],"memoria":["spanish"],"menor":["spanish"],"mensaje":["spanish"],"mente":["spanish"],"menú":["spanish"],"mercado":["spanish"],"merengue":["spanish"],"mérito":["spanish"],"mes":["spanish"],"mesón":["spanish"],"meta":["spanish"],"meter":["spanish"],"método":["spanish"],"metro":["spanish"],"mezcla":["spanish"],"miedo":["spanish"],"miel":["spanish"],"miembro":["spanish"],"miga":["spanish"],"mil":["spanish"],"milagro":["spanish"],"militar":["spanish"],"millón":["spanish"],"mimo":["spanish"],"mina":["spanish"],"minero":["spanish"],"mínimo":["spanish"],"minuto":["spanish"],"miope":["spanish"],"mirar":["spanish"],"misa":["spanish"],"miseria":["spanish"],"misil":["spanish"],"mismo":["spanish"],"mitad":["spanish"],"mito":["spanish"],"mochila":["spanish"],"moción":["spanish"],"moda":["spanish"],"modelo":["spanish"],"moho":["spanish"],"mojar":["spanish"],"molde":["spanish"],"moler":["spanish"],"molino":["spanish"],"momento":["spanish"],"momia":["spanish"],"monarca":["spanish"],"moneda":["spanish"],"monja":["spanish"],"monto":["spanish"],"moño":["spanish"],"morada":["spanish"],"morder":["spanish"],"moreno":["spanish"],"morir":["spanish"],"morro":["spanish"],"morsa":["spanish"],"mortal":["spanish"],"mosca":["spanish"],"mostrar":["spanish"],"motivo":["spanish"],"mover":["spanish"],"móvil":["spanish"],"mozo":["spanish"],"mucho":["spanish"],"mudar":["spanish"],"mueble":["spanish"],"muela":["spanish"],"muerte":["spanish"],"muestra":["spanish"],"mugre":["spanish"],"mujer":["spanish"],"mula":["spanish"],"muleta":["spanish"],"multa":["spanish"],"mundo":["spanish"],"muñeca":["spanish"],"mural":["spanish"],"muro":["spanish"],"músculo":["spanish"],"museo":["spanish"],"musgo":["spanish"],"música":["spanish"],"muslo":["spanish"],"nácar":["spanish"],"nación":["spanish"],"nadar":["spanish"],"naipe":["spanish"],"naranja":["spanish"],"nariz":["spanish"],"narrar":["spanish"],"nasal":["spanish"],"natal":["spanish"],"nativo":["spanish"],"natural":["spanish"],"náusea":["spanish"],"naval":["spanish"],"nave":["spanish"],"navidad":["spanish"],"necio":["spanish"],"néctar":["spanish"],"negar":["spanish"],"negocio":["spanish"],"negro":["spanish"],"neón":["spanish"],"nervio":["spanish"],"neto":["spanish"],"neutro":["spanish"],"nevar":["spanish"],"nevera":["spanish"],"nicho":["spanish"],"nido":["spanish"],"niebla":["spanish"],"nieto":["spanish"],"niñez":["spanish"],"niño":["spanish"],"nítido":["spanish"],"nivel":["spanish"],"nobleza":["spanish"],"noche":["spanish"],"nómina":["spanish"],"noria":["spanish"],"norma":["spanish"],"norte":["spanish"],"nota":["spanish"],"noticia":["spanish"],"novato":["spanish"],"novela":["spanish"],"novio":["spanish"],"nube":["spanish"],"nuca":["spanish"],"núcleo":["spanish"],"nudillo":["spanish"],"nudo":["spanish"],"nuera":["spanish"],"nueve":["spanish"],"nuez":["spanish"],"nulo":["spanish"],"número":["spanish"],"nutria":["spanish"],"oasis":["spanish"],"obeso":["spanish"],"obispo":["spanish"],"objeto":["spanish"],"obra":["spanish"],"obrero":["spanish"],"observar":["spanish"],"obtener":["spanish"],"obvio":["spanish"],"oca":["spanish"],"ocaso":["spanish"],"océano":["spanish"],"ochenta":["spanish"],"ocho":["spanish"],"ocio":["spanish"],"ocre":["spanish"],"octavo":["spanish"],"octubre":["spanish"],"oculto":["spanish"],"ocupar":["spanish"],"ocurrir":["spanish"],"odiar":["spanish"],"odio":["spanish"],"odisea":["spanish"],"oeste":["spanish"],"ofensa":["spanish"],"oferta":["spanish"],"oficio":["spanish"],"ofrecer":["spanish"],"ogro":["spanish"],"oído":["spanish"],"oír":["spanish"],"ojo":["spanish"],"ola":["spanish"],"oleada":["spanish"],"olfato":["spanish"],"olivo":["spanish"],"olla":["spanish"],"olmo":["spanish"],"olor":["spanish"],"olvido":["spanish"],"ombligo":["spanish"],"onda":["spanish"],"onza":["spanish"],"opaco":["spanish"],"opción":["spanish"],"ópera":["spanish"],"opinar":["spanish"],"oponer":["spanish"],"optar":["spanish"],"óptica":["spanish"],"opuesto":["spanish"],"oración":["spanish"],"orador":["spanish"],"oral":["spanish","turkish"],"órbita":["spanish"],"orca":["spanish"],"orden":["spanish"],"oreja":["spanish"],"órgano":["spanish"],"orgía":["spanish"],"orgullo":["spanish"],"oriente":["spanish"],"origen":["spanish"],"orilla":["spanish"],"oro":["spanish"],"orquesta":["spanish"],"oruga":["spanish"],"osadía":["spanish"],"oscuro":["spanish"],"osezno":["spanish"],"oso":["spanish"],"ostra":["spanish"],"otoño":["spanish"],"otro":["spanish"],"oveja":["spanish"],"óvulo":["spanish"],"óxido":["spanish"],"oxígeno":["spanish"],"oyente":["spanish"],"ozono":["spanish"],"pacto":["spanish"],"padre":["spanish"],"paella":["spanish"],"página":["spanish"],"pago":["spanish"],"país":["spanish"],"pájaro":["spanish"],"palabra":["spanish"],"palco":["spanish"],"paleta":["spanish"],"pálido":["spanish"],"palma":["spanish"],"paloma":["spanish"],"palpar":["spanish"],"pan":["spanish"],"panal":["spanish"],"pánico":["spanish"],"pantera":["spanish"],"pañuelo":["spanish"],"papá":["spanish"],"papel":["spanish"],"papilla":["spanish"],"paquete":["spanish"],"parar":["spanish"],"parcela":["spanish"],"pared":["spanish"],"parir":["spanish"],"paro":["spanish"],"párpado":["spanish"],"parque":["spanish"],"párrafo":["spanish"],"parte":["spanish"],"pasar":["spanish"],"paseo":["spanish"],"pasión":["spanish"],"paso":["spanish"],"pasta":["spanish"],"pata":["spanish"],"patio":["spanish"],"patria":["spanish"],"pausa":["spanish"],"pauta":["spanish"],"pavo":["spanish"],"payaso":["spanish"],"peatón":["spanish"],"pecado":["spanish"],"pecera":["spanish"],"pecho":["spanish"],"pedal":["spanish","turkish"],"pedir":["spanish"],"pegar":["spanish"],"peine":["spanish"],"pelar":["spanish"],"peldaño":["spanish"],"pelea":["spanish"],"peligro":["spanish"],"pellejo":["spanish"],"pelo":["spanish"],"peluca":["spanish"],"pena":["spanish","turkish"],"pensar":["spanish"],"peñón":["spanish"],"peón":["spanish"],"peor":["spanish"],"pepino":["spanish"],"pequeño":["spanish"],"pera":["spanish"],"percha":["spanish"],"perder":["spanish"],"pereza":["spanish"],"perfil":["spanish"],"perico":["spanish"],"perla":["spanish"],"permiso":["spanish"],"perro":["spanish"],"persona":["spanish"],"pesa":["spanish"],"pesca":["spanish"],"pésimo":["spanish"],"pestaña":["spanish"],"pétalo":["spanish"],"petróleo":["spanish"],"pez":["spanish"],"pezuña":["spanish"],"picar":["spanish"],"pichón":["spanish"],"pie":["spanish"],"piedra":["spanish"],"pierna":["spanish"],"pieza":["spanish"],"pijama":["spanish"],"pilar":["spanish"],"piloto":["spanish"],"pimienta":["spanish"],"pino":["spanish"],"pintor":["spanish"],"pinza":["spanish"],"piña":["spanish"],"piojo":["spanish"],"pipa":["spanish"],"pirata":["spanish"],"pisar":["spanish"],"piscina":["spanish"],"piso":["spanish"],"pista":["spanish"],"pitón":["spanish"],"pizca":["spanish"],"placa":["spanish"],"plan":["spanish"],"plata":["spanish"],"playa":["spanish"],"plaza":["spanish"],"pleito":["spanish"],"pleno":["spanish"],"plomo":["spanish"],"pluma":["spanish"],"plural":["spanish"],"pobre":["spanish"],"poco":["spanish"],"poder":["spanish"],"podio":["spanish"],"poema":["spanish"],"poesía":["spanish"],"poeta":["spanish"],"polen":["spanish","turkish"],"policía":["spanish"],"pollo":["spanish"],"polvo":["spanish"],"pomada":["spanish"],"pomelo":["spanish"],"pomo":["spanish"],"pompa":["spanish","turkish"],"poner":["spanish"],"porción":["spanish"],"portal":["spanish"],"posada":["spanish"],"poseer":["spanish"],"posible":["spanish"],"poste":["spanish"],"potencia":["spanish"],"potro":["spanish"],"pozo":["spanish"],"prado":["spanish"],"precoz":["spanish"],"pregunta":["spanish"],"premio":["spanish"],"prensa":["spanish"],"preso":["spanish"],"previo":["spanish"],"primo":["spanish"],"príncipe":["spanish"],"prisión":["spanish"],"privar":["spanish"],"proa":["spanish"],"probar":["spanish"],"proceso":["spanish"],"producto":["spanish"],"proeza":["spanish"],"profesor":["spanish"],"programa":["spanish"],"prole":["spanish"],"promesa":["spanish"],"pronto":["spanish"],"propio":["spanish"],"próximo":["spanish"],"prueba":["spanish"],"público":["spanish"],"puchero":["spanish"],"pudor":["spanish"],"pueblo":["spanish"],"puerta":["spanish"],"puesto":["spanish"],"pulga":["spanish"],"pulir":["spanish"],"pulmón":["spanish"],"pulpo":["spanish"],"pulso":["spanish"],"puma":["spanish"],"punto":["spanish"],"puñal":["spanish"],"puño":["spanish"],"pupa":["spanish"],"pupila":["spanish"],"puré":["spanish"],"quedar":["spanish"],"queja":["spanish"],"quemar":["spanish"],"querer":["spanish"],"queso":["spanish"],"quieto":["spanish"],"química":["spanish"],"quince":["spanish"],"quitar":["spanish"],"rábano":["spanish"],"rabia":["spanish"],"rabo":["spanish"],"ración":["spanish"],"radical":["spanish"],"raíz":["spanish"],"rama":["spanish"],"rampa":["spanish","turkish"],"rancho":["spanish"],"rango":["spanish"],"rapaz":["spanish"],"rápido":["spanish"],"rapto":["spanish"],"rasgo":["spanish"],"raspa":["spanish"],"rato":["spanish"],"rayo":["spanish"],"raza":["spanish"],"razón":["spanish"],"reacción":["spanish"],"realidad":["spanish"],"rebaño":["spanish"],"rebote":["spanish"],"recaer":["spanish"],"receta":["spanish"],"rechazo":["spanish"],"recoger":["spanish"],"recreo":["spanish"],"recto":["spanish"],"recurso":["spanish"],"red":["spanish"],"redondo":["spanish"],"reducir":["spanish"],"reflejo":["spanish"],"reforma":["spanish"],"refrán":["spanish"],"refugio":["spanish"],"regalo":["spanish"],"regir":["spanish"],"regla":["spanish"],"regreso":["spanish"],"rehén":["spanish"],"reino":["spanish"],"reír":["spanish"],"reja":["spanish"],"relato":["spanish"],"relevo":["spanish"],"relieve":["spanish"],"relleno":["spanish"],"reloj":["spanish"],"remar":["spanish"],"remedio":["spanish"],"remo":["spanish"],"rencor":["spanish"],"rendir":["spanish"],"renta":["spanish"],"reparto":["spanish"],"repetir":["spanish"],"reposo":["spanish"],"reptil":["spanish"],"res":["spanish"],"rescate":["spanish"],"resina":["spanish"],"respeto":["spanish"],"resto":["spanish"],"resumen":["spanish"],"retiro":["spanish"],"retorno":["spanish"],"retrato":["spanish"],"reunir":["spanish"],"revés":["spanish"],"revista":["spanish"],"rey":["spanish"],"rezar":["spanish"],"rico":["spanish"],"riego":["spanish"],"rienda":["spanish"],"riesgo":["spanish"],"rifa":["spanish"],"rígido":["spanish"],"rigor":["spanish"],"rincón":["spanish"],"riñón":["spanish"],"río":["spanish"],"riqueza":["spanish"],"risa":["spanish"],"ritmo":["spanish"],"rito":["spanish"],"rizo":["spanish"],"roble":["spanish"],"roce":["spanish"],"rociar":["spanish"],"rodar":["spanish"],"rodeo":["spanish"],"rodilla":["spanish"],"roer":["spanish"],"rojizo":["spanish"],"rojo":["spanish"],"romero":["spanish"],"romper":["spanish"],"ron":["spanish"],"ronco":["spanish"],"ronda":["spanish"],"ropa":["spanish"],"ropero":["spanish"],"rosa":["spanish"],"rosca":["spanish"],"rostro":["spanish"],"rotar":["spanish"],"rubí":["spanish"],"rubor":["spanish"],"rudo":["spanish"],"rueda":["spanish"],"rugir":["spanish"],"ruido":["spanish"],"ruina":["spanish"],"ruleta":["spanish"],"rulo":["spanish","turkish"],"rumbo":["spanish"],"rumor":["spanish"],"ruptura":["spanish"],"ruta":["spanish"],"rutina":["spanish"],"sábado":["spanish"],"saber":["spanish"],"sabio":["spanish"],"sable":["spanish"],"sacar":["spanish"],"sagaz":["spanish"],"sagrado":["spanish"],"sala":["spanish"],"saldo":["spanish"],"salero":["spanish"],"salir":["spanish"],"salmón":["spanish"],"salón":["spanish"],"salsa":["spanish"],"salto":["spanish"],"salud":["spanish"],"salvar":["spanish"],"samba":["spanish"],"sanción":["spanish"],"sandía":["spanish"],"sanear":["spanish"],"sangre":["spanish"],"sanidad":["spanish"],"sano":["spanish"],"santo":["spanish"],"sapo":["spanish"],"saque":["spanish"],"sardina":["spanish"],"sartén":["spanish"],"sastre":["spanish"],"satán":["spanish"],"sauna":["spanish"],"saxofón":["spanish"],"sección":["spanish"],"seco":["spanish"],"secreto":["spanish"],"secta":["spanish"],"sed":["spanish"],"seguir":["spanish"],"seis":["spanish"],"sello":["spanish"],"selva":["spanish"],"semana":["spanish"],"semilla":["spanish"],"senda":["spanish"],"sensor":["spanish"],"señal":["spanish"],"señor":["spanish"],"separar":["spanish"],"sepia":["spanish"],"sequía":["spanish"],"ser":["spanish"],"serie":["spanish"],"sermón":["spanish"],"servir":["spanish"],"sesenta":["spanish"],"sesión":["spanish"],"seta":["spanish"],"setenta":["spanish"],"severo":["spanish"],"sexo":["spanish"],"sexto":["spanish"],"sidra":["spanish"],"siesta":["spanish"],"siete":["spanish"],"siglo":["spanish"],"signo":["spanish"],"sílaba":["spanish"],"silbar":["spanish"],"silencio":["spanish"],"silla":["spanish"],"símbolo":["spanish"],"simio":["spanish"],"sirena":["spanish"],"sistema":["spanish"],"sitio":["spanish"],"situar":["spanish"],"sobre":["spanish"],"socio":["spanish"],"sodio":["spanish"],"sol":["spanish"],"solapa":["spanish"],"soldado":["spanish"],"soledad":["spanish"],"sólido":["spanish"],"soltar":["spanish"],"solución":["spanish"],"sombra":["spanish"],"sondeo":["spanish"],"sonido":["spanish"],"sonoro":["spanish"],"sonrisa":["spanish"],"sopa":["spanish"],"soplar":["spanish"],"soporte":["spanish"],"sordo":["spanish"],"sorpresa":["spanish"],"sorteo":["spanish"],"sostén":["spanish"],"sótano":["spanish"],"suave":["spanish"],"subir":["spanish"],"suceso":["spanish"],"sudor":["spanish"],"suegra":["spanish"],"suelo":["spanish"],"sueño":["spanish"],"suerte":["spanish"],"sufrir":["spanish"],"sujeto":["spanish"],"sultán":["spanish"],"sumar":["spanish"],"superar":["spanish"],"suplir":["spanish"],"suponer":["spanish"],"supremo":["spanish"],"sur":["spanish"],"surco":["spanish"],"sureño":["spanish"],"surgir":["spanish"],"susto":["spanish"],"sutil":["spanish"],"tabaco":["spanish"],"tabique":["spanish"],"tabla":["spanish"],"tabú":["spanish"],"taco":["spanish"],"tacto":["spanish"],"tajo":["spanish"],"talar":["spanish"],"talco":["spanish"],"talento":["spanish"],"talla":["spanish"],"talón":["spanish"],"tamaño":["spanish"],"tambor":["spanish"],"tango":["spanish"],"tanque":["spanish"],"tapa":["spanish"],"tapete":["spanish"],"tapia":["spanish"],"tapón":["spanish"],"taquilla":["spanish"],"tarde":["spanish"],"tarea":["spanish"],"tarifa":["spanish"],"tarjeta":["spanish"],"tarot":["spanish"],"tarro":["spanish"],"tarta":["spanish"],"tatuaje":["spanish"],"tauro":["spanish"],"taza":["spanish"],"tazón":["spanish"],"teatro":["spanish"],"techo":["spanish"],"tecla":["spanish"],"técnica":["spanish"],"tejado":["spanish"],"tejer":["spanish"],"tejido":["spanish"],"tela":["spanish"],"teléfono":["spanish"],"tema":["spanish"],"temor":["spanish"],"templo":["spanish"],"tenaz":["spanish"],"tender":["spanish"],"tener":["spanish"],"tenis":["spanish"],"tenso":["spanish"],"teoría":["spanish"],"terapia":["spanish"],"terco":["spanish"],"término":["spanish"],"ternura":["spanish"],"terror":["spanish"],"tesis":["spanish"],"tesoro":["spanish"],"testigo":["spanish"],"tetera":["spanish"],"texto":["spanish"],"tez":["spanish"],"tibio":["spanish"],"tiburón":["spanish"],"tiempo":["spanish"],"tienda":["spanish"],"tierra":["spanish"],"tieso":["spanish"],"tigre":["spanish"],"tijera":["spanish"],"tilde":["spanish"],"timbre":["spanish"],"tímido":["spanish"],"timo":["spanish"],"tinta":["spanish"],"tío":["spanish"],"típico":["spanish"],"tipo":["spanish"],"tira":["spanish"],"tirón":["spanish"],"titán":["spanish"],"títere":["spanish"],"título":["spanish"],"tiza":["spanish"],"toalla":["spanish"],"tobillo":["spanish"],"tocar":["spanish"],"tocino":["spanish"],"todo":["spanish"],"toga":["spanish"],"toldo":["spanish"],"tomar":["spanish","turkish"],"tono":["spanish"],"tonto":["spanish"],"topar":["spanish"],"tope":["spanish"],"toque":["spanish"],"tórax":["spanish"],"torero":["spanish"],"tormenta":["spanish"],"torneo":["spanish"],"toro":["spanish"],"torpedo":["spanish"],"torre":["spanish"],"torso":["spanish"],"tortuga":["spanish"],"tos":["spanish"],"tosco":["spanish"],"toser":["spanish"],"tóxico":["spanish"],"trabajo":["spanish"],"tractor":["spanish"],"traer":["spanish"],"tráfico":["spanish"],"trago":["spanish"],"traje":["spanish"],"tramo":["spanish"],"trance":["spanish"],"trato":["spanish"],"trauma":["spanish"],"trazar":["spanish"],"trébol":["spanish"],"tregua":["spanish"],"treinta":["spanish"],"tren":["spanish"],"trepar":["spanish"],"tres":["spanish"],"tribu":["spanish"],"trigo":["spanish"],"tripa":["spanish"],"triste":["spanish"],"triunfo":["spanish"],"trofeo":["spanish"],"trompa":["spanish"],"tronco":["spanish"],"tropa":["spanish"],"trote":["spanish"],"trozo":["spanish"],"truco":["spanish"],"trueno":["spanish"],"trufa":["spanish"],"tubería":["spanish"],"tubo":["spanish"],"tuerto":["spanish"],"tumba":["spanish"],"tumor":["spanish"],"túnel":["spanish"],"túnica":["spanish"],"turbina":["spanish"],"turismo":["spanish"],"turno":["spanish"],"tutor":["spanish"],"ubicar":["spanish"],"úlcera":["spanish"],"umbral":["spanish"],"unidad":["spanish"],"unir":["spanish"],"universo":["spanish"],"uno":["spanish"],"untar":["spanish"],"uña":["spanish"],"urbano":["spanish"],"urbe":["spanish"],"urgente":["spanish"],"urna":["spanish"],"usar":["spanish"],"usuario":["spanish"],"útil":["spanish"],"utopía":["spanish"],"uva":["spanish"],"vaca":["spanish"],"vacío":["spanish"],"vacuna":["spanish"],"vagar":["spanish"],"vago":["spanish"],"vaina":["spanish"],"vajilla":["spanish"],"vale":["spanish"],"válido":["spanish"],"valle":["spanish"],"valor":["spanish"],"válvula":["spanish"],"vampiro":["spanish"],"vara":["spanish"],"variar":["spanish"],"varón":["spanish"],"vaso":["spanish"],"vecino":["spanish"],"vector":["spanish"],"vehículo":["spanish"],"veinte":["spanish"],"vejez":["spanish"],"vela":["spanish"],"velero":["spanish"],"veloz":["spanish"],"vena":["spanish"],"vencer":["spanish"],"venda":["spanish"],"veneno":["spanish"],"vengar":["spanish"],"venir":["spanish"],"venta":["spanish"],"venus":["spanish"],"ver":["spanish"],"verano":["spanish"],"verbo":["spanish"],"verde":["spanish"],"vereda":["spanish"],"verja":["spanish"],"verso":["spanish"],"verter":["spanish"],"vía":["spanish"],"viaje":["spanish"],"vibrar":["spanish"],"vicio":["spanish"],"víctima":["spanish"],"vida":["spanish"],"vídeo":["spanish"],"vidrio":["spanish"],"viejo":["spanish"],"viernes":["spanish"],"vigor":["spanish"],"vil":["spanish"],"villa":["spanish"],"vinagre":["spanish"],"vino":["spanish"],"viñedo":["spanish"],"violín":["spanish"],"viral":["spanish"],"virgo":["spanish"],"virtud":["spanish"],"visor":["spanish"],"víspera":["spanish"],"vista":["spanish"],"vitamina":["spanish"],"viudo":["spanish"],"vivaz":["spanish"],"vivero":["spanish"],"vivir":["spanish"],"vivo":["spanish"],"volcán":["spanish"],"volumen":["spanish"],"volver":["spanish"],"voraz":["spanish"],"votar":["spanish"],"voto":["spanish"],"voz":["spanish"],"vuelo":["spanish"],"vulgar":["spanish"],"yacer":["spanish"],"yate":["spanish"],"yegua":["spanish"],"yema":["spanish"],"yerno":["spanish"],"yeso":["spanish"],"yodo":["spanish"],"yoga":["spanish"],"yogur":["spanish"],"zafiro":["spanish"],"zanja":["spanish"],"zapato":["spanish"],"zarza":["spanish"],"zona":["spanish"],"zorro":["spanish"],"zumo":["spanish"],"zurdo":["spanish"],"abajur":["turkish"],"abaküs":["turkish"],"abartı":["turkish"],"abdal":["turkish"],"abdest":["turkish"],"abiye":["turkish"],"abluka":["turkish"],"abone":["turkish"],"absorbe":["turkish"],"absürt":["turkish"],"acayip":["turkish"],"acele":["turkish"],"acemi":["turkish"],"açıkgöz":["turkish"],"adalet":["turkish"],"adam":["turkish"],"adezyon":["turkish"],"adisyon":["turkish"],"adliye":["turkish"],"adres":["turkish"],"afacan":["turkish"],"afili":["turkish"],"afiş":["turkish"],"afiyet":["turkish"],"aforizm":["turkish"],"afra":["turkish"],"ağaç":["turkish"],"ağır":["turkish"],"ahbap":["turkish"],"ahkam":["turkish"],"ahlak":["turkish"],"ahtapot":["turkish"],"aidat":["turkish"],"aile":["turkish"],"ajan":["turkish"],"akademi":["turkish"],"akarsu":["turkish"],"akbaş":["turkish"],"akciğer":["turkish"],"akdeniz":["turkish"],"akıbet":["turkish"],"akıl":["turkish"],"akıntı":["turkish"],"akide":["turkish"],"akrep":["turkish"],"akrobasi":["turkish"],"aksiyon":["turkish"],"akşam":["turkish"],"aktif":["turkish"],"aktör":["turkish"],"aktris":["turkish"],"akustik":["turkish"],"alaca":["turkish"],"albüm":["turkish"],"alçak":["turkish"],"aldanma":["turkish"],"aleni":["turkish"],"alet":["turkish"],"alfabe":["turkish"],"algılama":["turkish"],"alıngan":["turkish"],"alkış":["turkish"],"alkol":["turkish"],"alpay":["turkish"],"alperen":["turkish"],"altın":["turkish"],"altüst":["turkish"],"altyapı":["turkish"],"alyuvar":["turkish"],"amade":["turkish"],"amatör":["turkish"],"amazon":["turkish"],"ambalaj":["turkish"],"amblem":["turkish"],"ambulans":["turkish"],"amca":["turkish"],"amel":["turkish"],"amir":["turkish"],"amiyane":["turkish"],"amorti":["turkish"],"ampul":["turkish"],"anadolu":["turkish"],"anahtar":["turkish"],"anakonda":["turkish"],"anaokul":["turkish"],"anapara":["turkish"],"anarşi":["turkish"],"anatomi":["turkish"],"anayasa":["turkish"],"anekdot":["turkish"],"anestezi":["turkish"],"angaje":["turkish"],"anka":["turkish"],"anket":["turkish"],"anlamlı":["turkish"],"anne":["turkish"],"anomali":["turkish"],"anonim":["turkish"],"anten":["turkish"],"antlaşma":["turkish"],"apse":["turkish"],"araba":["turkish"],"aracı":["turkish"],"araf":["turkish"],"arbede":["turkish"],"arda":["turkish"],"arefe":["turkish"],"argo":["turkish"],"argüman":["turkish"],"arkadaş":["turkish"],"armoni":["turkish"],"arsa":["turkish"],"arsız":["turkish"],"artı":["turkish"],"aruz":["turkish"],"asansör":["turkish"],"asayiş":["turkish"],"asgari":["turkish"],"asil":["turkish"],"asker":["turkish"],"askı":["turkish"],"aslan":["turkish"],"asosyal":["turkish"],"astsubay":["turkish"],"asya":["turkish"],"aşçı":["turkish"],"aşırı":["turkish"],"aşure":["turkish"],"atabey":["turkish"],"ataman":["turkish"],"ateş":["turkish"],"atmaca":["turkish"],"atmosfer":["turkish"],"atölye":["turkish"],"avcı":["turkish"],"avdet":["turkish"],"avize":["turkish"],"avlu":["turkish"],"avokado":["turkish"],"avrupa":["turkish"],"avukat":["turkish"],"ayaz":["turkish"],"ayçiçeği":["turkish"],"aydın":["turkish"],"aygıt":["turkish"],"ayna":["turkish"],"ayran":["turkish"],"ayrıntı":["turkish"],"azim":["turkish"],"baca":["turkish"],"bagaj":["turkish"],"bağlantı":["turkish"],"bahadır":["turkish"],"bahçe":["turkish"],"baki":["turkish"],"bakkal":["turkish"],"baklava":["turkish"],"bakteri":["turkish"],"balçık":["turkish"],"balina":["turkish"],"balo":["turkish"],"balta":["turkish"],"bant":["turkish"],"banyo":["turkish"],"bardak":["turkish"],"barış":["turkish"],"başbuğ":["turkish"],"başıboş":["turkish"],"başkan":["turkish"],"başlık":["turkish"],"bavul":["turkish"],"bayındır":["turkish"],"baykuş":["turkish"],"bazlama":["turkish"],"bedel":["turkish"],"begüm":["turkish"],"bekçi":["turkish"],"bekle":["turkish"],"belge":["turkish"],"belki":["turkish"],"bencil":["turkish"],"benek":["turkish"],"bengi":["turkish"],"berjer":["turkish"],"berk":["turkish"],"berrak":["turkish"],"beşik":["turkish"],"beyin":["turkish"],"beyoğlu":["turkish"],"bıçak":["turkish"],"biberiye":["turkish"],"bidon":["turkish"],"bihaber":["turkish"],"bikini":["turkish"],"bilezik":["turkish"],"bilinç":["turkish"],"bilye":["turkish"],"bina":["turkish"],"binbaşı":["turkish"],"binyıl":["turkish"],"bisiklet":["turkish"],"bisküvi":["turkish"],"bitki":["turkish"],"bizzat":["turkish"],"bodrum":["turkish"],"boğaz":["turkish"],"bohça":["turkish"],"boncuk":["turkish"],"bonfile":["turkish"],"borsa":["turkish"],"boru":["turkish"],"bostan":["turkish"],"boşboğaz":["turkish"],"botanik":["turkish"],"boya":["turkish"],"boykot":["turkish"],"boynuz":["turkish"],"bozgun":["turkish"],"bozkır":["turkish"],"bölüm":["turkish"],"börek":["turkish"],"buçuk":["turkish"],"bugün":["turkish"],"buğday":["turkish"],"buhar":["turkish"],"buhran":["turkish"],"bulvar":["turkish"],"buram":["turkish"],"burçak":["turkish"],"burs":["turkish"],"burun":["turkish"],"buzdağı":["turkish"],"buzkıran":["turkish"],"bücür":["turkish"],"büfe":["turkish"],"bülten":["turkish"],"bütçe":["turkish"],"bütün":["turkish"],"büyük":["turkish"],"cacık":["turkish"],"cadı":["turkish"],"cahil":["turkish"],"cambaz":["turkish"],"canhıraş":["turkish"],"casus":["turkish"],"cazibe":["turkish"],"cehalet":["turkish"],"cehennem":["turkish"],"ceket":["turkish"],"cemre":["turkish"],"cenin":["turkish"],"cennet":["turkish"],"cepken":["turkish"],"cerrah":["turkish"],"cesur":["turkish"],"cetvel":["turkish"],"cevher":["turkish"],"ceylan":["turkish"],"cılız":["turkish"],"cıva":["turkish"],"cilt":["turkish"],"cisim":["turkish"],"ciyak":["turkish"],"coğrafya":["turkish"],"cömert":["turkish"],"cumba":["turkish"],"cüzdan":["turkish"],"çabucak":["turkish"],"çadır":["turkish"],"çağdaş":["turkish"],"çağlayan":["turkish"],"çağrı":["turkish"],"çakmak":["turkish"],"çalışkan":["turkish"],"çamaşır":["turkish"],"çapa":["turkish"],"çaput":["turkish"],"çarık":["turkish"],"çarpan":["turkish"],"çarşaf":["turkish"],"çayhane":["turkish"],"çekirdek":["turkish"],"çelebi":["turkish"],"çember":["turkish"],"çenet":["turkish"],"çengel":["turkish"],"çerçeve":["turkish"],"çerez":["turkish"],"çeşit":["turkish"],"çeşme":["turkish"],"çete":["turkish"],"çevre":["turkish"],"çeyiz":["turkish"],"çeyrek":["turkish"],"çığır":["turkish"],"çılgın":["turkish"],"çıngırak":["turkish"],"çift":["turkish"],"çiğdem":["turkish"],"çikolata":["turkish"],"çilek":["turkish"],"çimen":["turkish"],"çivi":["turkish"],"çoban":["turkish"],"çocuk":["turkish"],"çokgen":["turkish"],"çomak":["turkish"],"çorba":["turkish"],"çözelti":["turkish"],"çubuk":["turkish"],"çukur":["turkish"],"çuval":["turkish"],"çürük":["turkish"],"dağbaşı":["turkish"],"dağılım":["turkish"],"daktilo":["turkish"],"daldırış":["turkish"],"dalga":["turkish"],"dalkavuk":["turkish"],"damak":["turkish"],"damıtma":["turkish"],"damla":["turkish"],"dana":["turkish"],"dandik":["turkish"],"danışman":["turkish"],"daniska":["turkish"],"dantel":["turkish"],"dargeçit":["turkish"],"darphane":["turkish"],"davet":["turkish"],"dayı":["turkish"],"defter":["turkish"],"değer":["turkish"],"değirmen":["turkish"],"dehşet":["turkish"],"delgeç":["turkish"],"demir":["turkish"],"deneyim":["turkish"],"denge":["turkish"],"depo":["turkish"],"deprem":["turkish"],"derdest":["turkish"],"dere":["turkish"],"derhal":["turkish"],"derman":["turkish"],"dernek":["turkish"],"derviş":["turkish"],"desen":["turkish"],"destan":["turkish"],"dışarı":["turkish"],"dışbükey":["turkish"],"dijital":["turkish"],"dikbaşlı":["turkish"],"dilekçe":["turkish"],"dimağ":["turkish"],"dinamik":["turkish"],"dindar":["turkish"],"dinleme":["turkish"],"dinozor":["turkish"],"dipçik":["turkish"],"dipnot":["turkish"],"direniş":["turkish"],"dirsek":["turkish"],"disiplin":["turkish"],"divriği":["turkish"],"dizüstü":["turkish"],"dobra":["turkish"],"dodurga":["turkish"],"doğalgaz":["turkish"],"doküman":["turkish"],"dolap":["turkish"],"donanım":["turkish"],"dondurma":["turkish"],"donör":["turkish"],"doruk":["turkish"],"dosdoğru":["turkish"],"dost":["turkish"],"dosya":["turkish"],"dozer":["turkish"],"döküm":["turkish"],"dönence":["turkish"],"dörtyol":["turkish"],"dövme":["turkish"],"dram":["turkish"],"dublaj":["turkish"],"durum":["turkish"],"duvak":["turkish"],"duyarga":["turkish"],"duyma":["turkish"],"duyuru":["turkish"],"düğme":["turkish"],"düğüm":["turkish"],"dükkan":["turkish"],"dünür":["turkish"],"düpedüz":["turkish"],"dürbün":["turkish"],"düşünür":["turkish"],"düzayak":["turkish"],"düzeltme":["turkish"],"ebeveyn":["turkish"],"ebru":["turkish"],"ecel":["turkish"],"ecnebi":["turkish"],"ecza":["turkish"],"edat":["turkish"],"edilgen":["turkish"],"efendi":["turkish"],"efor":["turkish"],"efsane":["turkish"],"egemen":["turkish"],"egzersiz":["turkish"],"eğrelti":["turkish"],"ekarte":["turkish"],"ekip":["turkish"],"eklem":["turkish"],"ekmek":["turkish"],"ekol":["turkish"],"ekonomi":["turkish"],"ekose":["turkish"],"ekran":["turkish"],"ekvator":["turkish"],"elaman":["turkish"],"elastik":["turkish"],"elbet":["turkish"],"elbise":["turkish"],"elçi":["turkish"],"eldiven":["turkish"],"elebaşı":["turkish"],"eleştiri":["turkish"],"elma":["turkish"],"eloğlu":["turkish"],"elveda":["turkish"],"emare":["turkish"],"emekçi":["turkish"],"emisyon":["turkish"],"emniyet":["turkish"],"empati":["turkish"],"emsal":["turkish"],"emzik":["turkish"],"endüstri":["turkish"],"enerji":["turkish"],"engebe":["turkish"],"enişte":["turkish"],"enkaz":["turkish"],"entari":["turkish"],"entegre":["turkish"],"entrika":["turkish"],"enzim":["turkish"],"erdem":["turkish"],"ergen":["turkish"],"erguvan":["turkish"],"erkek":["turkish"],"erozyon":["turkish"],"ertesi":["turkish"],"erzak":["turkish"],"esaret":["turkish"],"esenlik":["turkish"],"eser":["turkish"],"eski":["turkish"],"esnek":["turkish"],"eşarp":["turkish"],"eşofman":["turkish"],"eşraf":["turkish"],"eşya":["turkish"],"eşzaman":["turkish"],"etik":["turkish"],"etken":["turkish"],"etkinlik":["turkish"],"etüt":["turkish"],"evet":["turkish"],"evire":["turkish"],"evrak":["turkish"],"evrim":["turkish"],"eyalet":["turkish"],"eyvah":["turkish"],"ezber":["turkish"],"fabrika":["turkish"],"fanus":["turkish"],"fason":["turkish"],"fasulye":["turkish"],"fatih":["turkish"],"fatura":["turkish"],"fayans":["turkish"],"fayton":["turkish"],"fazıl":["turkish"],"fazilet":["turkish"],"felsefe":["turkish"],"fener":["turkish"],"feribot":["turkish"],"fersah":["turkish"],"fesih":["turkish"],"feveran":["turkish"],"feza":["turkish"],"fıçı":["turkish"],"fıldır":["turkish"],"fındık":["turkish"],"fırça":["turkish"],"fırsat":["turkish"],"fırtına":["turkish"],"fıtık":["turkish"],"fidan":["turkish"],"fidye":["turkish"],"figür":["turkish"],"fihrist":["turkish"],"fikir":["turkish"],"fildişi":["turkish"],"filtre":["turkish"],"fincan":["turkish"],"firuze":["turkish"],"fitil":["turkish"],"fiyaka":["turkish"],"fizik":["turkish"],"flaş":["turkish"],"flüt":["turkish"],"fosil":["turkish"],"fren":["turkish"],"fukara":["turkish"],"futbol":["turkish"],"garabet":["turkish"],"gariban":["turkish"],"garnitür":["turkish"],"gazi":["turkish"],"gece":["turkish"],"gedik":["turkish"],"gelenek":["turkish"],"gelin":["turkish"],"gemi":["turkish"],"genç":["turkish"],"geniş":["turkish"],"geometri":["turkish"],"gerçek":["turkish"],"gevrek":["turkish"],"gezegen":["turkish"],"gezgin":["turkish"],"geziyolu":["turkish"],"gıcık":["turkish"],"gıda":["turkish"],"gıybet":["turkish"],"girdap":["turkish"],"girişim":["turkish"],"gitar":["turkish"],"giyecek":["turkish"],"giysi":["turkish"],"gizem":["turkish"],"gofret":["turkish"],"goril":["turkish"],"göbek":["turkish"],"göçebe":["turkish"],"göğüs":["turkish"],"gökdelen":["turkish"],"gökmen":["turkish"],"gökyüzü":["turkish"],"gölge":["turkish"],"gömlek":["turkish"],"gönül":["turkish"],"görenek":["turkish"],"görkemli":["turkish"],"görsel":["turkish"],"gösteri":["turkish"],"gövde":["turkish"],"gözaltı":["turkish"],"gözcü":["turkish"],"gözdağı":["turkish"],"gözleme":["turkish"],"gözyaşı":["turkish"],"grup":["turkish"],"gurbet":["turkish"],"gusül":["turkish"],"gübre":["turkish"],"güfte":["turkish"],"gümüş":["turkish"],"günaydın":["turkish"],"güncel":["turkish"],"gündüz":["turkish"],"güneş":["turkish"],"günyüzü":["turkish"],"gürbüz":["turkish"],"güvercin":["turkish"],"güzel":["turkish"],"hacamat":["turkish"],"hacim":["turkish"],"hademe":["turkish"],"hafız":["turkish"],"hafriyat":["turkish"],"hafta":["turkish"],"hakan":["turkish"],"hakem":["turkish"],"hakikat":["turkish"],"haksever":["turkish"],"halı":["turkish"],"hançer":["turkish"],"hane":["turkish"],"hapis":["turkish"],"hapşırık":["turkish"],"harf":["turkish"],"haseki":["turkish"],"hasret":["turkish"],"hatun":["turkish"],"havuç":["turkish"],"haylaz":["turkish"],"haysiyet":["turkish"],"hayvan":["turkish"],"hedef":["turkish"],"hemen":["turkish"],"hemfikir":["turkish"],"hendek":["turkish"],"hepsi":["turkish"],"hergele":["turkish"],"herhangi":["turkish"],"hesap":["turkish"],"heyecan":["turkish"],"heykel":["turkish"],"hezimet":["turkish"],"hıçkırık":["turkish"],"hızölçer":["turkish"],"hicviye":["turkish"],"hikaye":["turkish"],"hikmet":["turkish"],"hile":["turkish"],"hisse":["turkish"],"hobi":["turkish"],"hoca":["turkish"],"horlama":["turkish"],"hoşbeş":["turkish"],"hoşgörü":["turkish"],"hoyrat":["turkish"],"hörgüç":["turkish"],"höyük":["turkish"],"hudut":["turkish"],"hukuk":["turkish"],"hunhar":["turkish"],"hurda":["turkish"],"huysuz":["turkish"],"huzur":["turkish"],"hücum":["turkish"],"hükümet":["turkish"],"hünkar":["turkish"],"hüviyet":["turkish"],"ırmak":["turkish"],"ısıölçer":["turkish"],"ısıtıcı":["turkish"],"ıspanak":["turkish"],"ısrar":["turkish"],"ışıldak":["turkish"],"ızdırap":["turkish"],"ızgara":["turkish"],"ibadet":["turkish"],"icat":["turkish"],"içbükey":["turkish"],"içecek":["turkish"],"içgüdü":["turkish"],"içsel":["turkish"],"idman":["turkish"],"iftihar":["turkish"],"iğne":["turkish"],"ihanet":["turkish"],"ihbar":["turkish"],"ihdas":["turkish"],"ihmal":["turkish"],"ihracat":["turkish"],"ihsan":["turkish"],"ikilem":["turkish"],"ikindi":["turkish"],"ikircik":["turkish"],"iklim":["turkish"],"iksir":["turkish"],"iktibas":["turkish"],"ilaç":["turkish"],"ilçe":["turkish"],"ileri":["turkish"],"iletişim":["turkish"],"ilgi":["turkish"],"ilhak":["turkish"],"ilkbahar":["turkish"],"ilkokul":["turkish"],"ilmek":["turkish"],"imkan":["turkish"],"imleç":["turkish"],"imsak":["turkish"],"imtihan":["turkish"],"imza":["turkish"],"ince":["turkish"],"inkar":["turkish"],"inşa":["turkish"],"ipek":["turkish"],"ipucu":["turkish"],"irade":["turkish"],"irfan":["turkish"],"irmik":["turkish"],"isabet":["turkish"],"iskele":["turkish"],"israf":["turkish"],"isyan":["turkish"],"işçi":["turkish"],"işgal":["turkish"],"işgüzar":["turkish"],"işlem":["turkish"],"itibar":["turkish"],"itiraf":["turkish"],"ivedi":["turkish"],"ivme":["turkish"],"iyileşme":["turkish"],"iyimser":["turkish"],"izbandut":["turkish"],"izci":["turkish"],"izdiham":["turkish"],"izin":["turkish"],"jakoben":["turkish"],"jandarma":["turkish"],"jargon":["turkish"],"kabadayı":["turkish"],"kablo":["turkish"],"kabus":["turkish"],"kaçamak":["turkish"],"kadeh":["turkish"],"kadın":["turkish"],"kadraj":["turkish"],"kafa":["turkish"],"kafkas":["turkish"],"kağıt":["turkish"],"kağnı":["turkish"],"kahkaha":["turkish"],"kahraman":["turkish"],"kahvaltı":["turkish"],"kakül":["turkish"],"kaldırım":["turkish"],"kale":["turkish"],"kalibre":["turkish"],"kalkan":["turkish"],"kalpak":["turkish"],"kamış":["turkish"],"kamyon":["turkish"],"kanat":["turkish"],"kandaş":["turkish"],"kanepe":["turkish"],"kanser":["turkish"],"kanun":["turkish"],"kaos":["turkish"],"kapı":["turkish"],"kaplıca":["turkish"],"kaptan":["turkish"],"karanlık":["turkish"],"kardeş":["turkish"],"karga":["turkish"],"karınca":["turkish"],"karmaşa":["turkish"],"karşıt":["turkish"],"kasırga":["turkish"],"kask":["turkish"],"kasvet":["turkish"],"katkı":["turkish"],"katman":["turkish"],"kavram":["turkish"],"kaygan":["turkish"],"kaynakça":["turkish"],"kayyum":["turkish"],"kedi":["turkish"],"kehanet":["turkish"],"kekik":["turkish"],"kelebek":["turkish"],"kenar":["turkish"],"kerkenez":["turkish"],"kerpiç":["turkish"],"kesirli":["turkish"],"kesmece":["turkish"],"kestane":["turkish"],"keşkek":["turkish"],"ketçap":["turkish"],"keyfiyet":["turkish"],"kıble":["turkish"],"kıdemli":["turkish"],"kılavuz":["turkish"],"kılçık":["turkish"],"kılıf":["turkish"],"kıraç":["turkish"],"kırmızı":["turkish"],"kırsal":["turkish"],"kısayol":["turkish"],"kısım":["turkish"],"kıskanç":["turkish"],"kısmet":["turkish"],"kışla":["turkish"],"kıvanç":["turkish"],"kıvılcım":["turkish"],"kıvrık":["turkish"],"kıyafet":["turkish"],"kıymetli":["turkish"],"kızak":["turkish"],"kızılcık":["turkish"],"kibar":["turkish"],"kinaye":["turkish"],"kira":["turkish"],"kiremit":["turkish"],"kirli":["turkish"],"kirpik":["turkish"],"kişisel":["turkish"],"kitap":["turkish"],"koçbaşı":["turkish"],"kodaman":["turkish"],"koğuş":["turkish"],"kokteyl":["turkish"],"kolaycı":["turkish"],"kolbastı":["turkish"],"kolonya":["turkish"],"koltuk":["turkish"],"kolye":["turkish"],"kombine":["turkish"],"komedyen":["turkish"],"komiser":["turkish"],"komposto":["turkish"],"komşu":["turkish"],"komuta":["turkish"],"konak":["turkish"],"konfor":["turkish"],"koni":["turkish"],"konsül":["turkish"],"kopya":["turkish"],"korkusuz":["turkish"],"korna":["turkish"],"korse":["turkish"],"korunak":["turkish"],"korvet":["turkish"],"kostüm":["turkish"],"koşul":["turkish"],"koyu":["turkish"],"kozmik":["turkish"],"köfte":["turkish"],"kökensel":["turkish"],"köprücük":["turkish"],"köpük":["turkish"],"kördüğüm":["turkish"],"körfez":["turkish"],"köstebek":["turkish"],"köşegen":["turkish"],"kötü":["turkish"],"kravat":["turkish"],"kriter":["turkish"],"kuantum":["turkish"],"kudurma":["turkish"],"kuluçka":["turkish"],"kulübe":["turkish"],"kumanya":["turkish"],"kumbara":["turkish"],"kumlu":["turkish"],"kumpir":["turkish"],"kumral":["turkish"],"kundura":["turkish"],"kupa":["turkish"],"kupkuru":["turkish"],"kuramsal":["turkish"],"kurbağa":["turkish"],"kurdele":["turkish"],"kurgu":["turkish"],"kurmay":["turkish"],"kurşun":["turkish"],"kurtuluş":["turkish"],"kurultay":["turkish"],"kurye":["turkish"],"kusursuz":["turkish"],"kuşak":["turkish"],"kuşbaşı":["turkish"],"kuşkulu":["turkish"],"kutlama":["turkish"],"kutsal":["turkish"],"kutup":["turkish"],"kuver":["turkish"],"kuyruk":["turkish"],"kuzey":["turkish"],"kuzgun":["turkish"],"küçük":["turkish"],"külçe":["turkish"],"külfet":["turkish"],"külliye":["turkish"],"kültürel":["turkish"],"kümes":["turkish"],"künefe":["turkish"],"küresel":["turkish"],"kütle":["turkish"],"lahana":["turkish"],"lahmacun":["turkish"],"lamba":["turkish"],"lansman":["turkish"],"lavaş":["turkish"],"layık":["turkish"],"leğen":["turkish"],"levent":["turkish"],"leziz":["turkish"],"lezzet":["turkish"],"lider":["turkish"],"likide":["turkish"],"liman":["turkish"],"liste":["turkish"],"litre":["turkish"],"liyakat":["turkish"],"lodos":["turkish"],"lokanta":["turkish"],"lokman":["turkish"],"lokum":["turkish"],"lunapark":["turkish"],"lütfen":["turkish"],"lüzum":["turkish"],"nokta":["turkish"],"mabet":["turkish"],"macera":["turkish"],"macun":["turkish"],"madalya":["turkish"],"madde":["turkish"],"madem":["turkish"],"mağara":["turkish"],"mağdur":["turkish"],"mağfiret":["turkish"],"mağlup":["turkish"],"mahalle":["turkish"],"mahcup":["turkish"],"mahir":["turkish"],"mahkeme":["turkish"],"mahlas":["turkish"],"mahrum":["turkish"],"mahsul":["turkish"],"makas":["turkish"],"makbuz":["turkish"],"makine":["turkish"],"makro":["turkish"],"maksat":["turkish"],"makul":["turkish"],"maliye":["turkish"],"manav":["turkish"],"mangal":["turkish"],"manidar":["turkish"],"manken":["turkish"],"mantık":["turkish"],"manzara":["turkish"],"mareşal":["turkish"],"margarin":["turkish"],"marifet":["turkish"],"marmelat":["turkish"],"masaüstü":["turkish"],"masmavi":["turkish"],"masraf":["turkish"],"masum":["turkish"],"matah":["turkish"],"materyal":["turkish"],"matrak":["turkish"],"maval":["turkish"],"mavra":["turkish"],"maydanoz":["turkish"],"mayhoş":["turkish"],"maytap":["turkish"],"mazbata":["turkish"],"mazeret":["turkish"],"mazlum":["turkish"],"mazot":["turkish"],"mazur":["turkish"],"meblağ":["turkish"],"mebus":["turkish"],"mecaz":["turkish"],"mecbur":["turkish"],"meclis":["turkish"],"mecmua":["turkish"],"mecnun":["turkish"],"meçhul":["turkish"],"medeni":["turkish"],"mehtap":["turkish"],"mekanik":["turkish"],"melodi":["turkish"],"meltem":["turkish"],"memur":["turkish"],"mendil":["turkish"],"menekşe":["turkish"],"menteşe":["turkish"],"meraklı":["turkish"],"mercek":["turkish"],"merdiven":["turkish"],"merhaba":["turkish"],"merinos":["turkish"],"merkez":["turkish"],"mermi":["turkish"],"mert":["turkish"],"mesafe":["turkish"],"mesele":["turkish"],"mesken":["turkish"],"meslek":["turkish"],"meşale":["turkish"],"meşgul":["turkish"],"meşhur":["turkish"],"metafor":["turkish"],"metin":["turkish"],"metre":["turkish"],"mevcut":["turkish"],"mevkidaş":["turkish"],"meydan":["turkish"],"meyil":["turkish"],"meyve":["turkish"],"meziyet":["turkish"],"mezun":["turkish"],"mıknatıs":["turkish"],"mısra":["turkish"],"mızıka":["turkish"],"miğfer":["turkish"],"mihrak":["turkish"],"miktar":["turkish"],"milat":["turkish"],"milli":["turkish"],"mimar":["turkish"],"minare":["turkish"],"mineral":["turkish"],"minik":["turkish"],"minyon":["turkish"],"mirliva":["turkish"],"misafir":["turkish"],"miskin":["turkish"],"miting":["turkish"],"miyop":["turkish"],"mizah":["turkish"],"mobilya":["turkish"],"monitör":["turkish"],"morötesi":["turkish"],"motive":["turkish"],"mozaik":["turkish"],"muavin":["turkish"],"mucize":["turkish"],"muhafız":["turkish"],"muhteşem":["turkish"],"mukayese":["turkish"],"mumya":["turkish"],"musluk":["turkish"],"muşamba":["turkish"],"mutabık":["turkish"],"mutfak":["turkish"],"mutlu":["turkish"],"muzaffer":["turkish"],"muzdarip":["turkish"],"mübarek":["turkish"],"mücadele":["turkish"],"müdür":["turkish"],"müfredat":["turkish"],"müftü":["turkish"],"mühendis":["turkish"],"mühim":["turkish"],"mühlet":["turkish"],"mükemmel":["turkish"],"mülk":["turkish"],"mümkün":["turkish"],"mümtaz":["turkish"],"müsrif":["turkish"],"müstesna":["turkish"],"müşahit":["turkish"],"müşteri":["turkish"],"mütercim":["turkish"],"müthiş":["turkish"],"müze":["turkish"],"müzik":["turkish"],"nabız":["turkish"],"nadas":["turkish"],"nadir":["turkish"],"nahoş":["turkish"],"nakarat":["turkish"],"nakış":["turkish"],"nalbur":["turkish"],"namlu":["turkish"],"namus":["turkish"],"nankör":["turkish"],"nargile":["turkish"],"narkoz":["turkish"],"nasıl":["turkish"],"nasip":["turkish"],"naylon":["turkish"],"nazar":["turkish"],"nazım":["turkish"],"nazik":["turkish"],"neden":["turkish"],"nefes":["turkish"],"negatif":["turkish"],"neon":["turkish"],"neptün":["turkish"],"nerede":["turkish"],"nesil":["turkish"],"nesnel":["turkish"],"neşeli":["turkish"],"netice":["turkish"],"nevresim":["turkish"],"neyse":["turkish"],"neyzen":["turkish"],"nezaket":["turkish"],"nezih":["turkish"],"nezle":["turkish"],"nicel":["turkish"],"nilüfer":["turkish"],"nimet":["turkish"],"nisan":["turkish"],"nispet":["turkish"],"nitekim":["turkish"],"nizam":["turkish"],"nohut":["turkish"],"noksan":["turkish"],"nostalji":["turkish"],"noter":["turkish"],"nöbet":["turkish"],"numara":["turkish"],"numune":["turkish"],"nutuk":["turkish"],"nüfus":["turkish"],"obabaşı":["turkish"],"obez":["turkish"],"obje":["turkish"],"ocak":["turkish"],"odun":["turkish"],"ofansif":["turkish"],"ofis":["turkish"],"oğlak":["turkish"],"oğuz":["turkish"],"okçu":["turkish"],"oklava":["turkish"],"oksijen":["turkish"],"okul":["turkish"],"okumuş":["turkish"],"okutman":["turkish"],"okuyucu":["turkish"],"okyanus":["turkish"],"olağan":["turkish"],"olanak":["turkish"],"olası":["turkish"],"olay":["turkish"],"olgun":["turkish"],"olimpik":["turkish"],"olumlu":["turkish"],"omlet":["turkish"],"omurga":["turkish"],"onarım":["turkish"],"onursal":["turkish"],"optik":["turkish"],"orantı":["turkish"],"ordu":["turkish"],"organik":["turkish"],"orijin":["turkish"],"orkide":["turkish"],"orman":["turkish"],"orta":["turkish"],"oruç":["turkish"],"otağ":["turkish"],"otantik":["turkish"],"otel":["turkish"],"otoban":["turkish"],"otogar":["turkish"],"otomobil":["turkish"],"otonom":["turkish"],"otopark":["turkish"],"otorite":["turkish"],"otoyol":["turkish"],"oturum":["turkish"],"oyuk":["turkish"],"oyuncak":["turkish"],"ozan":["turkish"],"ödeme":["turkish"],"ödenek":["turkish"],"ödev":["turkish"],"ödül":["turkish"],"ödünç":["turkish"],"öfke":["turkish"],"öğlen":["turkish"],"öğrenci":["turkish"],"öğün":["turkish"],"öğütücü":["turkish"],"öksürük":["turkish"],"ölçme":["turkish"],"ölçü":["turkish"],"ölümsüz":["turkish"],"ömür":["turkish"],"önayak":["turkish"],"öncü":["turkish"],"önder":["turkish"],"önem":["turkish"],"önerge":["turkish"],"öngörü":["turkish"],"önlük":["turkish"],"önsezi":["turkish"],"öpücük":["turkish"],"ördek":["turkish"],"örgü":["turkish"],"örtbas":["turkish"],"örtme":["turkish"],"örtü":["turkish"],"örümcek":["turkish"],"örüntü":["turkish"],"öteberi":["turkish"],"öteki":["turkish"],"övünç":["turkish"],"öykü":["turkish"],"öyleyse":["turkish"],"özçekim":["turkish"],"özdeyiş":["turkish"],"özel":["turkish"],"özenti":["turkish"],"özerk":["turkish"],"özgürlük":["turkish"],"özlem":["turkish"],"özlü":["turkish"],"özne":["turkish"],"özsever":["turkish"],"özümseme":["turkish"],"özür":["turkish"],"özveri":["turkish"],"pabuç":["turkish"],"padişah":["turkish"],"palamut":["turkish"],"palmiye":["turkish"],"palto":["turkish"],"palyaço":["turkish"],"pamuk":["turkish"],"panayır":["turkish"],"pancar":["turkish"],"panik":["turkish"],"panjur":["turkish"],"pankart":["turkish"],"pano":["turkish"],"pansuman":["turkish"],"pantolon":["turkish"],"panzehir":["turkish"],"papatya":["turkish"],"papyon":["turkish"],"paraşüt":["turkish"],"parça":["turkish"],"pardösü":["turkish"],"parfüm":["turkish"],"parıltı":["turkish"],"parkur":["turkish"],"parmak":["turkish"],"parodi":["turkish"],"parsel":["turkish"],"partner":["turkish"],"pasaport":["turkish"],"pasif":["turkish"],"paskalya":["turkish"],"pastırma":["turkish"],"paşa":["turkish"],"patates":["turkish"],"paten":["turkish"],"patika":["turkish"],"patlıcan":["turkish"],"patolog":["turkish"],"payanda":["turkish"],"paydaş":["turkish"],"payidar":["turkish"],"paylaşma":["turkish"],"paytak":["turkish"],"peçete":["turkish"],"peder":["turkish"],"pehlivan":["turkish"],"pekala":["turkish"],"pekmez":["turkish"],"pelerin":["turkish"],"pelikan":["turkish"],"pelüş":["turkish"],"pembe":["turkish"],"pencere":["turkish"],"pense":["turkish"],"perçin":["turkish"],"perde":["turkish"],"pergel":["turkish"],"perişan":["turkish"],"peron":["turkish"],"personel":["turkish"],"perşembe":["turkish"],"peruk":["turkish"],"pervane":["turkish"],"pespaye":["turkish"],"pestil":["turkish"],"peşin":["turkish"],"petek":["turkish"],"petrol":["turkish"],"petunya":["turkish"],"peynir":["turkish"],"peyzaj":["turkish"],"pınar":["turkish"],"pırasa":["turkish"],"pırlanta":["turkish"],"pide":["turkish"],"pikap":["turkish"],"pilav":["turkish"],"piliç":["turkish"],"pipet":["turkish"],"pipo":["turkish"],"piramit":["turkish"],"pirinç":["turkish"],"pirzola":["turkish"],"pist":["turkish"],"pişik":["turkish"],"pişman":["turkish"],"piyasa":["turkish"],"piyes":["turkish"],"plaj":["turkish"],"plaket":["turkish"],"planlama":["turkish"],"platform":["turkish"],"plazma":["turkish"],"podyum":["turkish"],"poğaça":["turkish"],"polat":["turkish"],"politika":["turkish"],"popüler":["turkish"],"porselen":["turkish"],"portakal":["turkish"],"poster":["turkish"],"poşet":["turkish"],"poyraz":["turkish"],"pozitif":["turkish"],"pranga":["turkish"],"pratik":["turkish"],"prenses":["turkish"],"prim":["turkish"],"profil":["turkish"],"proje":["turkish"],"protokol":["turkish"],"puan":["turkish"],"pudra":["turkish"],"pusula":["turkish"],"püre":["turkish"],"pürüz":["turkish"],"püstül":["turkish"],"püsür":["turkish"],"racon":["turkish"],"radikal":["turkish"],"radyo":["turkish"],"rafadan":["turkish"],"rafine":["turkish"],"rağbet":["turkish"],"rahat":["turkish"],"rahle":["turkish"],"rakam":["turkish"],"raket":["turkish"],"rakip":["turkish"],"rakun":["turkish"],"ralli":["turkish"],"randevu":["turkish"],"ranza":["turkish"],"rapor":["turkish"],"rastgele":["turkish"],"rasyonel":["turkish"],"razı":["turkish"],"realite":["turkish"],"reçine":["turkish"],"refah":["turkish"],"referans":["turkish"],"refik":["turkish"],"rehber":["turkish"],"rehin":["turkish"],"reis":["turkish"],"rekabet":["turkish"],"reklam":["turkish"],"rekor":["turkish"],"rektör":["turkish"],"renk":["turkish"],"resim":["turkish"],"resmen":["turkish"],"restoran":["turkish"],"retorik":["turkish"],"revaç":["turkish"],"reyon":["turkish"],"rezalet":["turkish"],"rezerv":["turkish"],"rezil":["turkish"],"rıhtım":["turkish"],"rıza":["turkish"],"ritim":["turkish"],"ritüel":["turkish"],"rivayet":["turkish"],"roman":["turkish"],"rozet":["turkish"],"röportaj":["turkish"],"rötar":["turkish"],"ruble":["turkish"],"ruhban":["turkish"],"ruhsat":["turkish"],"rulet":["turkish"],"runik":["turkish"],"rutin":["turkish"],"rutubet":["turkish"],"rüşvet":["turkish"],"rütbe":["turkish"],"rüya":["turkish"],"rüzgar":["turkish"],"sabah":["turkish"],"sabıka":["turkish"],"sabit":["turkish"],"sabun":["turkish"],"saçma":["turkish"],"sade":["turkish"],"sadık":["turkish"],"safahat":["turkish"],"safdil":["turkish"],"safkan":["turkish"],"sağanak":["turkish"],"sağduyu":["turkish"],"sağlam":["turkish"],"saha":["turkish"],"sahiden":["turkish"],"sahne":["turkish"],"sakal":["turkish"],"sakız":["turkish"],"sakin":["turkish"],"saklama":["turkish"],"saksağan":["turkish"],"salamura":["turkish"],"salça":["turkish"],"salgı":["turkish"],"salınım":["turkish"],"salkım":["turkish"],"saltanat":["turkish"],"sanatçı":["turkish"],"sancak":["turkish"],"sandalye":["turkish"],"saniye":["turkish"],"saplantı":["turkish"],"sapsız":["turkish"],"saray":["turkish"],"sarışın":["turkish"],"sarkık":["turkish"],"sarmaşık":["turkish"],"satır":["turkish"],"savaşım":["turkish"],"savunma":["turkish"],"saydam":["turkish"],"sayfa":["turkish"],"saygın":["turkish"],"sayısal":["turkish"],"sebep":["turkish"],"seçenek":["turkish"],"seçim":["turkish"],"seçkin":["turkish"],"seçmen":["turkish"],"sedir":["turkish"],"sedye":["turkish"],"sefer":["turkish"],"sehpa":["turkish"],"sekizgen":["turkish"],"selektör":["turkish"],"selvi":["turkish"],"semavi":["turkish"],"sembol":["turkish"],"seminer":["turkish"],"senaryo":["turkish"],"sendika":["turkish"],"senkron":["turkish"],"sensör":["turkish"],"sentez":["turkish"],"sepet":["turkish"],"seramik":["turkish"],"serbest":["turkish"],"serdar":["turkish"],"seremoni":["turkish"],"sergi":["turkish"],"serhat":["turkish"],"serin":["turkish"],"sermaye":["turkish"],"serpuş":["turkish"],"sersem":["turkish"],"serüven":["turkish"],"sesli":["turkish"],"sesteş":["turkish"],"sevap":["turkish"],"seviye":["turkish"],"seyahat":["turkish"],"seyirci":["turkish"],"sezon":["turkish"],"sıcak":["turkish"],"sıfat":["turkish"],"sıhhi":["turkish"],"sınanma":["turkish"],"sınır":["turkish"],"sıradan":["turkish"],"sırdaş":["turkish"],"sırma":["turkish"],"sırtüstü":["turkish"],"sızgıt":["turkish"],"siftah":["turkish"],"sigorta":["turkish"],"sihirbaz":["turkish"],"silah":["turkish"],"silecek":["turkish"],"silindir":["turkish"],"simetri":["turkish"],"simge":["turkish"],"simit":["turkish"],"sincap":["turkish"],"sindirim":["turkish"],"sinema":["turkish"],"sinirli":["turkish"],"sipariş":["turkish"],"sirke":["turkish"],"siroz":["turkish"],"sistem":["turkish"],"sivilce":["turkish"],"siyasi":["turkish"],"soba":["turkish"],"sofra":["turkish"],"soğuk":["turkish"],"sohbet":["turkish"],"sokak":["turkish"],"solfej":["turkish"],"solunum":["turkish"],"somut":["turkish"],"sonbahar":["turkish"],"sonraki":["turkish"],"sonsuz":["turkish"],"sorunsuz":["turkish"],"sosyete":["turkish"],"soyağacı":["turkish"],"soydaş":["turkish"],"soygun":["turkish"],"soytarı":["turkish"],"söğüş":["turkish"],"sömürge":["turkish"],"sönük":["turkish"],"söylem":["turkish"],"sözcük":["turkish"],"sözde":["turkish"],"spatula":["turkish"],"spektrum":["turkish"],"spiker":["turkish"],"sporcu":["turkish"],"sprey":["turkish"],"stabil":["turkish"],"statü":["turkish"],"stok":["turkish"],"stopaj":["turkish"],"strateji":["turkish"],"subay":["turkish"],"sucuk":["turkish"],"suçüstü":["turkish"],"suhulet":["turkish"],"sulama":["turkish"],"sungur":["turkish"],"sunucu":["turkish"],"surat":["turkish"],"susam":["turkish"],"suskun":["turkish"],"sükse":["turkish"],"sükut":["turkish"],"sülale":["turkish"],"sünger":["turkish"],"süpürge":["turkish"],"sürahi":["turkish"],"süreç":["turkish"],"sürgün":["turkish"],"sürüm":["turkish"],"süsleme":["turkish"],"sütanne":["turkish"],"sütlaç":["turkish"],"sütun":["turkish"],"süvari":["turkish"],"şahane":["turkish"],"şahbaz":["turkish"],"şahit":["turkish"],"şahsiyet":["turkish"],"şakıma":["turkish"],"şaklaban":["turkish"],"şakrak":["turkish"],"şamar":["turkish"],"şampiyon":["turkish"],"şanslı":["turkish"],"şantiye":["turkish"],"şapka":["turkish"],"şarkıcı":["turkish"],"şartname":["turkish"],"şaşırma":["turkish"],"şaşkın":["turkish"],"şatafat":["turkish"],"şayet":["turkish"],"şebeke":["turkish"],"şefkat":["turkish"],"şeftali":["turkish"],"şehir":["turkish"],"şehvet":["turkish"],"şeker":["turkish"],"şekil":["turkish"],"şelale":["turkish"],"şema":["turkish"],"şemsiye":["turkish"],"şerbet":["turkish"],"şeref":["turkish"],"şerit":["turkish"],"şımarık":["turkish"],"şıpıdık":["turkish"],"şifre":["turkish"],"şimdi":["turkish"],"şimşek":["turkish"],"şipşak":["turkish"],"şirin":["turkish"],"şişe":["turkish"],"şişirme":["turkish"],"şofben":["turkish"],"şöhret":["turkish"],"şölen":["turkish"],"şüphe":["turkish"],"tabaka":["turkish"],"tabure":["turkish"],"tadilat":["turkish"],"taharet":["turkish"],"tahıl":["turkish"],"tahkim":["turkish"],"tahlil":["turkish"],"tahmin":["turkish"],"tahrifat":["turkish"],"tahsilat":["turkish"],"tahta":["turkish"],"taklit":["turkish"],"takoz":["turkish"],"taksici":["turkish"],"taktik":["turkish"],"takvim":["turkish"],"talebe":["turkish"],"talip":["turkish"],"tamamen":["turkish"],"tamirci":["turkish"],"tamtakır":["turkish"],"tandır":["turkish"],"tanecik":["turkish"],"tanıtım":["turkish"],"tanrı":["turkish"],"tansiyon":["turkish"],"tapan":["turkish"],"tapınak":["turkish"],"taptaze":["turkish"],"tapu":["turkish"],"tarafgir":["turkish"],"tarhana":["turkish"],"tarım":["turkish"],"tarih":["turkish"],"tarla":["turkish"],"tartak":["turkish"],"tarumar":["turkish"],"tasarım":["turkish"],"tasdik":["turkish"],"taslak":["turkish"],"tastamam":["turkish"],"taşeron":["turkish"],"taşınmaz":["turkish"],"taşra":["turkish"],"tatava":["turkish"],"tatbikat":["turkish"],"tatil":["turkish"],"tatlı":["turkish"],"tavsiye":["turkish"],"tavşan":["turkish"],"tavuk":["turkish"],"taze":["turkish"],"taziye":["turkish"],"tazminat":["turkish"],"tebeşir":["turkish"],"tebrik":["turkish"],"tecrübe":["turkish"],"teçhizat":["turkish"],"tedarik":["turkish"],"tedbir":["turkish"],"teftiş":["turkish"],"teğet":["turkish"],"teğmen":["turkish"],"tehdit":["turkish"],"tehlike":["turkish"],"tekdüze":["turkish"],"tekerlek":["turkish"],"tekme":["turkish"],"teknik":["turkish"],"tekrar":["turkish"],"telef":["turkish"],"telsiz":["turkish"],"telve":["turkish"],"temas":["turkish"],"tembel":["turkish"],"temiz":["turkish"],"temkin":["turkish"],"temsilci":["turkish"],"tendon":["turkish"],"teneke":["turkish"],"tenha":["turkish"],"tenkit":["turkish"],"tepegöz":["turkish"],"tepki":["turkish"],"terazi":["turkish"],"terbiye":["turkish"],"tercih":["turkish"],"tereyağı":["turkish"],"terfi":["turkish"],"terim":["turkish"],"terminal":["turkish"],"tersane":["turkish"],"tertip":["turkish"],"tesadüf":["turkish"],"tescil":["turkish"],"tesir":["turkish"],"teslimat":["turkish"],"tespit":["turkish"],"testere":["turkish"],"teşekkür":["turkish"],"teşhir":["turkish"],"teşrif":["turkish"],"teşvik":["turkish"],"teyze":["turkish"],"tezahür":["turkish"],"tezgah":["turkish"],"tıbbi":["turkish"],"tıkaç":["turkish"],"tıkışık":["turkish"],"tıknaz":["turkish"],"tılsım":["turkish"],"tıpkı":["turkish"],"tıraş":["turkish"],"tırışka":["turkish"],"tırmanış":["turkish"],"tırnak":["turkish"],"tırpan":["turkish"],"tıslama":["turkish"],"ticaret":["turkish"],"tilki":["turkish"],"tiryaki":["turkish"],"titreşim":["turkish"],"tohum":["turkish"],"tokat":["turkish"],"tolere":["turkish"],"tombak":["turkish"],"tomurcuk":["turkish"],"topaç":["turkish"],"toplum":["turkish"],"toprak":["turkish"],"toptan":["turkish"],"toraman":["turkish"],"torpido":["turkish"],"tortu":["turkish"],"tosbağa":["turkish"],"toynak":["turkish"],"tören":["turkish"],"trafik":["turkish"],"trajedi":["turkish"],"tramvay":["turkish"],"tribün":["turkish"],"triko":["turkish"],"tugay":["turkish"],"tuğla":["turkish"],"tuğrul":["turkish"],"tuhaf":["turkish"],"tulumba":["turkish"],"tunç":["turkish"],"turan":["turkish"],"turkuaz":["turkish"],"turnusol":["turkish"],"turşu":["turkish"],"turuncu":["turkish"],"tutanak":["turkish"],"tutkal":["turkish"],"tutsak":["turkish"],"tutum":["turkish"],"tuyuğ":["turkish"],"tuzlu":["turkish"],"tüccar":["turkish"],"tüfek":["turkish"],"tükenmez":["turkish"],"tülbent":["turkish"],"tümleç":["turkish"],"tünel":["turkish"],"türbin":["turkish"],"türev":["turkish"],"türk":["turkish"],"tüzük":["turkish"],"ucube":["turkish"],"ucuz":["turkish"],"uçak":["turkish"],"uçurtma":["turkish"],"ufuk":["turkish"],"uğrak":["turkish"],"uğur":["turkish"],"ukala":["turkish"],"ulaşım":["turkish"],"ulema":["turkish"],"ulus":["turkish"],"ulvi":["turkish"],"umursama":["turkish"],"umut":["turkish"],"unutkan":["turkish"],"uslu":["turkish"],"ustabaşı":["turkish"],"ustura":["turkish"],"usul":["turkish"],"utangaç":["turkish"],"uyanık":["turkish"],"uyarı":["turkish"],"uydu":["turkish"],"uygar":["turkish"],"uygulama":["turkish"],"uykusuz":["turkish"],"uysal":["turkish"],"uyuşma":["turkish"],"uzantı":["turkish"],"uzay":["turkish"],"uzgören":["turkish"],"uzlaşma":["turkish"],"uzman":["turkish"],"uzun":["turkish"],"ücra":["turkish"],"ücret":["turkish"],"üçbudak":["turkish"],"üçgen":["turkish"],"üçkağıt":["turkish"],"üçleme":["turkish"],"üfürük":["turkish"],"ülke":["turkish"],"ümit":["turkish"],"üniforma":["turkish"],"ünite":["turkish"],"ünlem":["turkish"],"üretken":["turkish"],"ürün":["turkish"],"üslup":["turkish"],"üstel":["turkish"],"üstün":["turkish"],"üşengeç":["turkish"],"üşüme":["turkish"],"ütopya":["turkish"],"üvey":["turkish"],"üzengi":["turkish"],"üzgün":["turkish"],"üzüm":["turkish"],"vaka":["turkish"],"vakfiye":["turkish"],"vakıf":["turkish"],"vakit":["turkish"],"vakum":["turkish"],"vapur":["turkish"],"varil":["turkish"],"varlık":["turkish"],"varsayım":["turkish"],"varyemez":["turkish"],"vasıta":["turkish"],"vasiyet":["turkish"],"vatandaş":["turkish"],"vazife":["turkish"],"vazo":["turkish"],"veciz":["turkish"],"vefa":["turkish"],"vehim":["turkish"],"veliaht":["turkish"],"veresiye":["turkish"],"verimli":["turkish"],"verkaç":["turkish"],"vernik":["turkish"],"vertigo":["turkish"],"vesait":["turkish"],"vesika":["turkish"],"vestiyer":["turkish"],"veznedar":["turkish"],"vicdan":["turkish"],"vilayet":["turkish"],"virane":["turkish"],"virgül":["turkish"],"vişne":["turkish"],"vites":["turkish"],"vokal":["turkish"],"volkan":["turkish"],"vurma":["turkish"],"vurucu":["turkish"],"vücut":["turkish"],"yabancı":["turkish"],"yabgu":["turkish"],"yağış":["turkish"],"yağlı":["turkish"],"yağmur":["turkish"],"yakamoz":["turkish"],"yakın":["turkish"],"yaklaşık":["turkish"],"yalçın":["turkish"],"yalıtım":["turkish"],"yaman":["turkish"],"yanardağ":["turkish"],"yangın":["turkish"],"yanıt":["turkish"],"yankı":["turkish"],"yanlış":["turkish"],"yansıma":["turkish"],"yapay":["turkish"],"yapboz":["turkish"],"yapımcı":["turkish"],"yaprak":["turkish"],"yaratık":["turkish"],"yarbay":["turkish"],"yardım":["turkish"],"yargıç":["turkish"],"yarıçap":["turkish"],"yasemin":["turkish"],"yastık":["turkish"],"yaşam":["turkish"],"yatak":["turkish"],"yatırım":["turkish"],"yavru":["turkish"],"yaygara":["turkish"],"yayıncı":["turkish"],"yayla":["turkish"],"yazılım":["turkish"],"yekpare":["turkish"],"yekvücut":["turkish"],"yelkovan":["turkish"],"yelpaze":["turkish"],"yemek":["turkish"],"yemiş":["turkish"],"yengeç":["turkish"],"yeniçeri":["turkish"],"yeraltı":["turkish"],"yerküre":["turkish"],"yerleşke":["turkish"],"yeryüzü":["turkish"],"yeşil":["turkish"],"yetenek":["turkish"],"yetkili":["turkish"],"yığınak":["turkish"],"yıkama":["turkish"],"yılbaşı":["turkish"],"yıldırım":["turkish"],"yılkı":["turkish"],"yılmaz":["turkish"],"yırtıcı":["turkish"],"yiğit":["turkish"],"yoğurt":["turkish"],"yokuş":["turkish"],"yolcu":["turkish"],"yoldaş":["turkish"],"yolgeçen":["turkish"],"yolkesen":["turkish"],"yolüstü":["turkish"],"yordam":["turkish"],"yorgan":["turkish"],"yorumcu":["turkish"],"yosun":["turkish"],"yöndeş":["turkish"],"yönetim":["turkish"],"yönlü":["turkish"],"yöntem":["turkish"],"yöresel":["turkish"],"yörünge":["turkish"],"yufka":["turkish"],"yukarı":["turkish"],"yumruk":["turkish"],"yumurta":["turkish"],"yuvarlak":["turkish"],"yücelme":["turkish"],"yükçeker":["turkish"],"yüklem":["turkish"],"yüksek":["turkish"],"yürek":["turkish"],"yürütme":["turkish"],"yüzde":["turkish"],"yüzeysel":["turkish"],"yüzgeç":["turkish"],"yüzüstü":["turkish"],"yüzyıl":["turkish"],"zabıta":["turkish"],"zafer":["turkish"],"zahmet":["turkish"],"zambak":["turkish"],"zaptiye":["turkish"],"zarafet":["turkish"],"zaruret":["turkish"],"zeka":["turkish"],"zekice":["turkish"],"zemberek":["turkish"],"zemin":["turkish"],"zencefil":["turkish"],"zeplin":["turkish"],"zeytin":["turkish"],"zıbın":["turkish"],"zılgıt":["turkish"],"zımbırtı":["turkish"],"zımpara":["turkish"],"zıpkın":["turkish"],"zigon":["turkish"],"zihinsel":["turkish"],"zihniyet":["turkish"],"zincir":["turkish"],"zindan":["turkish"],"zirzop":["turkish"],"ziyaret":["turkish"],"ziynet":["turkish"],"zoraki":["turkish"],"zorlu":["turkish"],"zorunlu":["turkish"],"züğürt":["turkish"],"zümre":["turkish"]}["abacate","abaixo","abalar","abater","abduzir","abelha","aberto","abismo","abotoar","abranger","abreviar","abrigar","abrupto","absinto","absoluto","absurdo","abutre","acabado","acalmar","acampar","acanhar","acaso","aceitar","acelerar","acenar","acervo","acessar","acetona","achatar","acidez","acima","acionado","acirrar","aclamar","aclive","acolhida","acomodar","acoplar","acordar","acumular","acusador","adaptar","adega","adentro","adepto","adequar","aderente","adesivo","adeus","adiante","aditivo","adjetivo","adjunto","admirar","adorar","adquirir","adubo","adverso","advogado","aeronave","afastar","aferir","afetivo","afinador","afivelar","aflito","afluente","afrontar","agachar","agarrar","agasalho","agenciar","agilizar","agiota","agitado","agora","agradar","agreste","agrupar","aguardar","agulha","ajoelhar","ajudar","ajustar","alameda","alarme","alastrar","alavanca","albergue","albino","alcatra","aldeia","alecrim","alegria","alertar","alface","alfinete","algum","alheio","aliar","alicate","alienar","alinhar","aliviar","almofada","alocar","alpiste","alterar","altitude","alucinar","alugar","aluno","alusivo","alvo","amaciar","amador","amarelo","amassar","ambas","ambiente","ameixa","amenizar","amido","amistoso","amizade","amolador","amontoar","amoroso","amostra","amparar","ampliar","ampola","anagrama","analisar","anarquia","anatomia","andaime","anel","anexo","angular","animar","anjo","anomalia","anotado","ansioso","anterior","anuidade","anunciar","anzol","apagador","apalpar","apanhado","apego","apelido","apertada","apesar","apetite","apito","aplauso","aplicada","apoio","apontar","aposta","aprendiz","aprovar","aquecer","arame","aranha","arara","arcada","ardente","areia","arejar","arenito","aresta","argiloso","argola","arma","arquivo","arraial","arrebate","arriscar","arroba","arrumar","arsenal","arterial","artigo","arvoredo","asfaltar","asilado","aspirar","assador","assinar","assoalho","assunto","astral","atacado","atadura","atalho","atarefar","atear","atender","aterro","ateu","atingir","atirador","ativo","atoleiro","atracar","atrevido","atriz","atual","atum","auditor","aumentar","aura","aurora","autismo","autoria","autuar","avaliar","avante","avaria","avental","avesso","aviador","avisar","avulso","axila","azarar","azedo","azeite","azulejo","babar","babosa","bacalhau","bacharel","bacia","bagagem","baiano","bailar","baioneta","bairro","baixista","bajular","baleia","baliza","balsa","banal","bandeira","banho","banir","banquete","barato","barbado","baronesa","barraca","barulho","baseado","bastante","batata","batedor","batida","batom","batucar","baunilha","beber","beijo","beirada","beisebol","beldade","beleza","belga","beliscar","bendito","bengala","benzer","berimbau","berlinda","berro","besouro","bexiga","bezerro","bico","bicudo","bienal","bifocal","bifurcar","bigorna","bilhete","bimestre","bimotor","biologia","biombo","biosfera","bipolar","birrento","biscoito","bisneto","bispo","bissexto","bitola","bizarro","blindado","bloco","bloquear","boato","bobagem","bocado","bocejo","bochecha","boicotar","bolada","boletim","bolha","bolo","bombeiro","bonde","boneco","bonita","borbulha","borda","boreal","borracha","bovino","boxeador","branco","brasa","braveza","breu","briga","brilho","brincar","broa","brochura","bronzear","broto","bruxo","bucha","budismo","bufar","bule","buraco","busca","busto","buzina","cabana","cabelo","cabide","cabo","cabrito","cacau","cacetada","cachorro","cacique","cadastro","cadeado","cafezal","caiaque","caipira","caixote","cajado","caju","calafrio","calcular","caldeira","calibrar","calmante","calota","camada","cambista","camisa","camomila","campanha","camuflar","canavial","cancelar","caneta","canguru","canhoto","canivete","canoa","cansado","cantar","canudo","capacho","capela","capinar","capotar","capricho","captador","capuz","caracol","carbono","cardeal","careca","carimbar","carneiro","carpete","carreira","cartaz","carvalho","casaco","casca","casebre","castelo","casulo","catarata","cativar","caule","causador","cautelar","cavalo","caverna","cebola","cedilha","cegonha","celebrar","celular","cenoura","censo","centeio","cercar","cerrado","certeiro","cerveja","cetim","cevada","chacota","chaleira","chamado","chapada","charme","chatice","chave","chefe","chegada","cheiro","cheque","chicote","chifre","chinelo","chocalho","chover","chumbo","chutar","chuva","cicatriz","ciclone","cidade","cidreira","ciente","cigana","cimento","cinto","cinza","ciranda","circuito","cirurgia","citar","clareza","clero","clicar","clone","clube","coado","coagir","cobaia","cobertor","cobrar","cocada","coelho","coentro","coeso","cogumelo","coibir","coifa","coiote","colar","coleira","colher","colidir","colmeia","colono","coluna","comando","combinar","comentar","comitiva","comover","complexo","comum","concha","condor","conectar","confuso","congelar","conhecer","conjugar","consumir","contrato","convite","cooperar","copeiro","copiador","copo","coquetel","coragem","cordial","corneta","coronha","corporal","correio","cortejo","coruja","corvo","cosseno","costela","cotonete","couro","couve","covil","cozinha","cratera","cravo","creche","credor","creme","crer","crespo","criada","criminal","crioulo","crise","criticar","crosta","crua","cruzeiro","cubano","cueca","cuidado","cujo","culatra","culminar","culpar","cultura","cumprir","cunhado","cupido","curativo","curral","cursar","curto","cuspir","custear","cutelo","damasco","datar","debater","debitar","deboche","debulhar","decalque","decimal","declive","decote","decretar","dedal","dedicado","deduzir","defesa","defumar","degelo","degrau","degustar","deitado","deixar","delator","delegado","delinear","delonga","demanda","demitir","demolido","dentista","depenado","depilar","depois","depressa","depurar","deriva","derramar","desafio","desbotar","descanso","desenho","desfiado","desgaste","desigual","deslize","desmamar","desova","despesa","destaque","desviar","detalhar","detentor","detonar","detrito","deusa","dever","devido","devotado","dezena","diagrama","dialeto","didata","difuso","digitar","dilatado","diluente","diminuir","dinastia","dinheiro","diocese","direto","discreta","disfarce","disparo","disquete","dissipar","distante","ditador","diurno","diverso","divisor","divulgar","dizer","dobrador","dolorido","domador","dominado","donativo","donzela","dormente","dorsal","dosagem","dourado","doutor","drenagem","drible","drogaria","duelar","duende","dueto","duplo","duquesa","durante","duvidoso","eclodir","ecoar","ecologia","edificar","edital","educado","efeito","efetivar","ejetar","elaborar","eleger","eleitor","elenco","elevador","eliminar","elogiar","embargo","embolado","embrulho","embutido","emenda","emergir","emissor","empatia","empenho","empinado","empolgar","emprego","empurrar","emulador","encaixe","encenado","enchente","encontro","endeusar","endossar","enfaixar","enfeite","enfim","engajado","engenho","englobar","engomado","engraxar","enguia","enjoar","enlatar","enquanto","enraizar","enrolado","enrugar","ensaio","enseada","ensino","ensopado","entanto","enteado","entidade","entortar","entrada","entulho","envergar","enviado","envolver","enxame","enxerto","enxofre","enxuto","epiderme","equipar","ereto","erguido","errata","erva","ervilha","esbanjar","esbelto","escama","escola","escrita","escuta","esfinge","esfolar","esfregar","esfumado","esgrima","esmalte","espanto","espelho","espiga","esponja","espreita","espumar","esquerda","estaca","esteira","esticar","estofado","estrela","estudo","esvaziar","etanol","etiqueta","euforia","europeu","evacuar","evaporar","evasivo","eventual","evidente","evoluir","exagero","exalar","examinar","exato","exausto","excesso","excitar","exclamar","executar","exemplo","exibir","exigente","exonerar","expandir","expelir","expirar","explanar","exposto","expresso","expulsar","externo","extinto","extrato","fabricar","fabuloso","faceta","facial","fada","fadiga","faixa","falar","falta","familiar","fandango","fanfarra","fantoche","fardado","farelo","farinha","farofa","farpa","fartura","fatia","fator","favorita","faxina","fazenda","fechado","feijoada","feirante","felino","feminino","fenda","feno","fera","feriado","ferrugem","ferver","festejar","fetal","feudal","fiapo","fibrose","ficar","ficheiro","figurado","fileira","filho","filme","filtrar","firmeza","fisgada","fissura","fita","fivela","fixador","fixo","flacidez","flamingo","flanela","flechada","flora","flutuar","fluxo","focal","focinho","fofocar","fogo","foguete","foice","folgado","folheto","forjar","formiga","forno","forte","fosco","fossa","fragata","fralda","frango","frasco","fraterno","freira","frente","fretar","frieza","friso","fritura","fronha","frustrar","fruteira","fugir","fulano","fuligem","fundar","fungo","funil","furador","furioso","futebol","gabarito","gabinete","gado","gaiato","gaiola","gaivota","galega","galho","galinha","galocha","ganhar","garagem","garfo","gargalo","garimpo","garoupa","garrafa","gasoduto","gasto","gata","gatilho","gaveta","gazela","gelado","geleia","gelo","gemada","gemer","gemido","generoso","gengiva","genial","genoma","genro","geologia","gerador","germinar","gesso","gestor","ginasta","gincana","gingado","girafa","girino","glacial","glicose","global","glorioso","goela","goiaba","golfe","golpear","gordura","gorjeta","gorro","gostoso","goteira","governar","gracejo","gradual","grafite","gralha","grampo","granada","gratuito","graveto","graxa","grego","grelhar","greve","grilo","grisalho","gritaria","grosso","grotesco","grudado","grunhido","gruta","guache","guarani","guaxinim","guerrear","guiar","guincho","guisado","gula","guloso","guru","habitar","harmonia","haste","haver","hectare","herdar","heresia","hesitar","hiato","hibernar","hidratar","hiena","hino","hipismo","hipnose","hipoteca","hoje","holofote","homem","honesto","honrado","hormonal","hospedar","humorado","iate","ideia","idoso","ignorado","igreja","iguana","ileso","ilha","iludido","iluminar","ilustrar","imagem","imediato","imenso","imersivo","iminente","imitador","imortal","impacto","impedir","implante","impor","imprensa","impune","imunizar","inalador","inapto","inativo","incenso","inchar","incidir","incluir","incolor","indeciso","indireto","indutor","ineficaz","inerente","infantil","infestar","infinito","inflamar","informal","infrator","ingerir","inibido","inicial","inimigo","injetar","inocente","inodoro","inovador","inox","inquieto","inscrito","inseto","insistir","inspetor","instalar","insulto","intacto","integral","intimar","intocado","intriga","invasor","inverno","invicto","invocar","iogurte","iraniano","ironizar","irreal","irritado","isca","isento","isolado","isqueiro","italiano","janeiro","jangada","janta","jararaca","jardim","jarro","jasmim","jato","javali","jazida","jejum","joaninha","joelhada","jogador","joia","jornal","jorrar","jovem","juba","judeu","judoca","juiz","julgador","julho","jurado","jurista","juro","justa","labareda","laboral","lacre","lactante","ladrilho","lagarta","lagoa","laje","lamber","lamentar","laminar","lampejo","lanche","lapidar","lapso","laranja","lareira","largura","lasanha","lastro","lateral","latido","lavanda","lavoura","lavrador","laxante","lazer","lealdade","lebre","legado","legendar","legista","leigo","leiloar","leitura","lembrete","leme","lenhador","lentilha","leoa","lesma","leste","letivo","letreiro","levar","leveza","levitar","liberal","libido","liderar","ligar","ligeiro","limitar","limoeiro","limpador","linda","linear","linhagem","liquidez","listagem","lisura","litoral","livro","lixa","lixeira","locador","locutor","lojista","lombo","lona","longe","lontra","lorde","lotado","loteria","loucura","lousa","louvar","luar","lucidez","lucro","luneta","lustre","lutador","luva","macaco","macete","machado","macio","madeira","madrinha","magnata","magreza","maior","mais","malandro","malha","malote","maluco","mamilo","mamoeiro","mamute","manada","mancha","mandato","manequim","manhoso","manivela","manobrar","mansa","manter","manusear","mapeado","maquinar","marcador","maresia","marfim","margem","marinho","marmita","maroto","marquise","marreco","martelo","marujo","mascote","masmorra","massagem","mastigar","matagal","materno","matinal","matutar","maxilar","medalha","medida","medusa","megafone","meiga","melancia","melhor","membro","memorial","menino","menos","mensagem","mental","merecer","mergulho","mesada","mesclar","mesmo","mesquita","mestre","metade","meteoro","metragem","mexer","mexicano","micro","migalha","migrar","milagre","milenar","milhar","mimado","minerar","minhoca","ministro","minoria","miolo","mirante","mirtilo","misturar","mocidade","moderno","modular","moeda","moer","moinho","moita","moldura","moleza","molho","molinete","molusco","montanha","moqueca","morango","morcego","mordomo","morena","mosaico","mosquete","mostarda","motel","motim","moto","motriz","muda","muito","mulata","mulher","multar","mundial","munido","muralha","murcho","muscular","museu","musical","nacional","nadador","naja","namoro","narina","narrado","nascer","nativa","natureza","navalha","navegar","navio","neblina","nebuloso","negativa","negociar","negrito","nervoso","neta","neural","nevasca","nevoeiro","ninar","ninho","nitidez","nivelar","nobreza","noite","noiva","nomear","nominal","nordeste","nortear","notar","noticiar","noturno","novelo","novilho","novo","nublado","nudez","numeral","nupcial","nutrir","nuvem","obcecado","obedecer","objetivo","obrigado","obscuro","obstetra","obter","obturar","ocidente","ocioso","ocorrer","oculista","ocupado","ofegante","ofensiva","oferenda","oficina","ofuscado","ogiva","olaria","oleoso","olhar","oliveira","ombro","omelete","omisso","omitir","ondulado","oneroso","ontem","opcional","operador","oponente","oportuno","oposto","orar","orbitar","ordem","ordinal","orfanato","orgasmo","orgulho","oriental","origem","oriundo","orla","ortodoxo","orvalho","oscilar","ossada","osso","ostentar","otimismo","ousadia","outono","outubro","ouvido","ovelha","ovular","oxidar","oxigenar","pacato","paciente","pacote","pactuar","padaria","padrinho","pagar","pagode","painel","pairar","paisagem","palavra","palestra","palheta","palito","palmada","palpitar","pancada","panela","panfleto","panqueca","pantanal","papagaio","papelada","papiro","parafina","parcial","pardal","parede","partida","pasmo","passado","pastel","patamar","patente","patinar","patrono","paulada","pausar","peculiar","pedalar","pedestre","pediatra","pedra","pegada","peitoral","peixe","pele","pelicano","penca","pendurar","peneira","penhasco","pensador","pente","perceber","perfeito","pergunta","perito","permitir","perna","perplexo","persiana","pertence","peruca","pescado","pesquisa","pessoa","petiscar","piada","picado","piedade","pigmento","pilastra","pilhado","pilotar","pimenta","pincel","pinguim","pinha","pinote","pintar","pioneiro","pipoca","piquete","piranha","pires","pirueta","piscar","pistola","pitanga","pivete","planta","plaqueta","platina","plebeu","plumagem","pluvial","pneu","poda","poeira","poetisa","polegada","policiar","poluente","polvilho","pomar","pomba","ponderar","pontaria","populoso","porta","possuir","postal","pote","poupar","pouso","povoar","praia","prancha","prato","praxe","prece","predador","prefeito","premiar","prensar","preparar","presilha","pretexto","prevenir","prezar","primata","princesa","prisma","privado","processo","produto","profeta","proibido","projeto","prometer","propagar","prosa","protetor","provador","publicar","pudim","pular","pulmonar","pulseira","punhal","punir","pupilo","pureza","puxador","quadra","quantia","quarto","quase","quebrar","queda","queijo","quente","querido","quimono","quina","quiosque","rabanada","rabisco","rachar","racionar","radial","raiar","rainha","raio","raiva","rajada","ralado","ramal","ranger","ranhura","rapadura","rapel","rapidez","raposa","raquete","raridade","rasante","rascunho","rasgar","raspador","rasteira","rasurar","ratazana","ratoeira","realeza","reanimar","reaver","rebaixar","rebelde","rebolar","recado","recente","recheio","recibo","recordar","recrutar","recuar","rede","redimir","redonda","reduzida","reenvio","refinar","refletir","refogar","refresco","refugiar","regalia","regime","regra","reinado","reitor","rejeitar","relativo","remador","remendo","remorso","renovado","reparo","repelir","repleto","repolho","represa","repudiar","requerer","resenha","resfriar","resgatar","residir","resolver","respeito","ressaca","restante","resumir","retalho","reter","retirar","retomada","retratar","revelar","revisor","revolta","riacho","rica","rigidez","rigoroso","rimar","ringue","risada","risco","risonho","robalo","rochedo","rodada","rodeio","rodovia","roedor","roleta","romano","roncar","rosado","roseira","rosto","rota","roteiro","rotina","rotular","rouco","roupa","roxo","rubro","rugido","rugoso","ruivo","rumo","rupestre","russo","sabor","saciar","sacola","sacudir","sadio","safira","saga","sagrada","saibro","salada","saleiro","salgado","saliva","salpicar","salsicha","saltar","salvador","sambar","samurai","sanar","sanfona","sangue","sanidade","sapato","sarda","sargento","sarjeta","saturar","saudade","saxofone","sazonal","secar","secular","seda","sedento","sediado","sedoso","sedutor","segmento","segredo","segundo","seiva","seleto","selvagem","semanal","semente","senador","senhor","sensual","sentado","separado","sereia","seringa","serra","servo","setembro","setor","sigilo","silhueta","silicone","simetria","simpatia","simular","sinal","sincero","singular","sinopse","sintonia","sirene","siri","situado","soberano","sobra","socorro","sogro","soja","solda","soletrar","solteiro","sombrio","sonata","sondar","sonegar","sonhador","sono","soprano","soquete","sorrir","sorteio","sossego","sotaque","soterrar","sovado","sozinho","suavizar","subida","submerso","subsolo","subtrair","sucata","sucesso","suco","sudeste","sufixo","sugador","sugerir","sujeito","sulfato","sumir","suor","superior","suplicar","suposto","suprimir","surdina","surfista","surpresa","surreal","surtir","suspiro","sustento","tabela","tablete","tabuada","tacho","tagarela","talher","talo","talvez","tamanho","tamborim","tampa","tangente","tanto","tapar","tapioca","tardio","tarefa","tarja","tarraxa","tatuagem","taurino","taxativo","taxista","teatral","tecer","tecido","teclado","tedioso","teia","teimar","telefone","telhado","tempero","tenente","tensor","tentar","termal","terno","terreno","tese","tesoura","testado","teto","textura","texugo","tiara","tigela","tijolo","timbrar","timidez","tingido","tinteiro","tiragem","titular","toalha","tocha","tolerar","tolice","tomada","tomilho","tonel","tontura","topete","tora","torcido","torneio","torque","torrada","torto","tostar","touca","toupeira","toxina","trabalho","tracejar","tradutor","trafegar","trajeto","trama","trancar","trapo","traseiro","tratador","travar","treino","tremer","trepidar","trevo","triagem","tribo","triciclo","tridente","trilogia","trindade","triplo","triturar","triunfal","trocar","trombeta","trova","trunfo","truque","tubular","tucano","tudo","tulipa","tupi","turbo","turma","turquesa","tutelar","tutorial","uivar","umbigo","unha","unidade","uniforme","urologia","urso","urtiga","urubu","usado","usina","usufruir","vacina","vadiar","vagaroso","vaidoso","vala","valente","validade","valores","vantagem","vaqueiro","varanda","vareta","varrer","vascular","vasilha","vassoura","vazar","vazio","veado","vedar","vegetar","veicular","veleiro","velhice","veludo","vencedor","vendaval","venerar","ventre","verbal","verdade","vereador","vergonha","vermelho","verniz","versar","vertente","vespa","vestido","vetorial","viaduto","viagem","viajar","viatura","vibrador","videira","vidraria","viela","viga","vigente","vigiar","vigorar","vilarejo","vinco","vinheta","vinil","violeta","virada","virtude","visitar","visto","vitral","viveiro","vizinho","voador","voar","vogal","volante","voleibol","voltagem","volumoso","vontade","vulto","vuvuzela","xadrez","xarope","xeque","xeretar","xerife","xingar","zangado","zarpar","zebu","zelador","zombar","zoologia","zumbido"]["абзац","абонент","абсурд","авангард","авария","август","авиация","автор","агент","агитация","агрегат","адвокат","адмирал","адрес","азарт","азот","академия","аквариум","аксиома","акула","акцент","акция","аллея","алмаз","алтарь","альбом","альянс","амбиция","анализ","анекдот","анкета","ансамбль","антенна","апельсин","аппарат","аппетит","апрель","аптека","арбуз","аргумент","аренда","арест","армия","аромат","арсенал","артерия","артист","архив","аспирант","асфальт","атака","атомный","атрибут","аукцион","афиша","аэропорт","бабочка","бабушка","багаж","база","бактерия","баланс","балерина","балкон","бандит","банк","барабан","барон","барышня","барьер","бассейн","батарея","башмак","башня","бедный","беженец","бездна","белка","белый","бензин","берег","беседа","бешеный","билет","бинокль","биржа","битва","благо","блеск","близкий","блин","блок","блюдо","богатый","бодрый","боец","бокал","боковой","бокс","более","болото","болтать","большой","бомба","борт","борьба","босой","ботинок","бояться","брак","брать","бревно","бред","бригада","бродяга","броня","бросить","брызги","брюки","брюхо","бугор","будка","будни","будущее","буква","букет","бульвар","бумага","бунт","бурный","буря","бутылка","бухта","бывший","быстро","бытовой","быть","бюджет","бюро","бюст","вагон","важный","вакцина","валенок","вальс","валюта","ванная","варенье","вариант","вблизи","вверх","вводить","вдали","вдвое","вдова","вдоль","вдруг","ведро","ведущий","ведьма","вежливо","везде","веко","вексель","велеть","великий","венец","веник","веранда","верблюд","верить","верный","версия","вертеть","верхний","вершина","весело","весна","весомый","вести","весь","ветеран","ветхий","вечер","вечно","вешалка","вещество","взамен","взгляд","вздох","взнос","взойти","взор","взрыв","взять","видеть","видимо","визг","визит","вилка","вина","вирус","висок","витамин","витрина","вихрь","вишня","вкус","влага","владелец","власть","влево","влияние","вложить","вместе","внешний","вникать","внимание","вновь","внук","внутри","внучка","внушать","вовлечь","вовремя","вовсю","вода","водород","водяной","воевать","возврат","возглас","воздух","возить","возле","возня","возраст","война","войско","вокзал","волос","волчий","вольный","воля","вообще","вопль","вопрос","ворота","восемь","восток","вплоть","вполне","вправе","впредь","впрочем","врач","вредный","время","вручить","всадник","всегда","вскоре","вскрыть","всплеск","вспышка","встреча","всюду","всякий","второй","вход","вчера","выбор","вывод","выгнать","выдать","выехать","вызов","выйти","выкуп","вылезти","вымыть","выпасть","выпить","выплата","выпуск","вырасти","выручка","выслать","высокий","выставка","вышка","вязать","вялый","газета","газовый","галерея","галстук","гамма","гарантия","гармония","гарнизон","гастроли","гвардия","гвоздь","гектар","генерал","гений","геном","геолог","герб","герой","гибкий","гигант","гимн","гипотеза","гитара","главный","глагол","гладить","глаз","глина","глоток","глубокий","глупый","глухой","глыба","глядеть","гнев","гнездо","гнилой","годовой","голова","голубой","голый","гонорар","гордость","горизонт","горло","горный","город","горшок","горький","горючее","горячий","готовый","градус","грамм","граница","граф","гребень","гриб","гримаса","грозить","грохот","грош","грубый","грудь","груз","грунт","группа","груша","грязный","губа","гудок","гулкий","гулять","гусеница","густо","гусь","давление","давно","даже","дальний","данный","дарить","датчик","дать","дача","двадцать","дважды","дверь","двигать","движение","двойной","двор","дебют","девятый","дежурный","действие","декабрь","деление","дело","дельфин","день","дерево","держать","дерзкий","десять","деталь","детский","дефект","дефицит","деятель","джаз","джинсы","джунгли","диагноз","диалог","диапазон","диван","дивизия","дивный","диета","дизайн","дикарь","дилер","динамика","диплом","директор","дитя","длинный","дневник","добрый","добыча","доверие","догадка","догнать","дождь","доклад","доктор","документ","долго","должен","долина","донос","дорога","досада","доска","достать","досуг","доход","доцент","дощатый","драка","древний","дремать","дробный","дрова","дрожать","другой","дружба","дубовый","дуга","думать","дурной","духи","душный","дуэль","дуэт","дыра","дыхание","дюжина","дядя","едва","единый","ерунда","если","ехать","жадный","жажда","жалеть","жалоба","жанр","жареный","жаркий","жгучий","жевать","желание","желудок","жена","женщина","жертва","жест","жидкость","житель","жить","жрец","жулик","журнал","жуткий","забрать","забыть","завести","завод","завтра","загадка","загнать","заговор","задача","задеть","задний","задолго","заехать","заказ","закон","закрыть","закуска","залезть","залить","залп","замок","замуж","замысел","занавес","заново","занять","заодно","запись","запрос","запуск","запястье","заранее","заросль","зарплата","заря","засада","заслуга","заснуть","застать","затвор","затеять","затрата","затылок","захват","зачем","защита","заявить","заяц","звезда","звено","звонить","здесь","зелень","земля","зеркало","зерно","зима","злой","змея","знамя","знание","значит","золотой","зона","зонтик","зоопарк","зрачок","зрение","зритель","зубной","зубр","игла","идеал","идеолог","идея","идол","идти","изба","избить","избрать","избыток","извлечь","извне","изгиб","изгнать","издание","изделие","изнутри","изобилие","изоляция","изредка","изрядно","изучение","изъять","изящный","икона","икра","иллюзия","именно","иметь","имидж","империя","импульс","иначе","инвалид","индекс","индивид","инерция","инженер","иногда","иной","институт","интерес","интрига","интуиция","инфаркт","инцидент","ирония","искать","испуг","история","итог","июнь","кабель","кабинет","каблук","кавалер","кадр","каждый","кажется","казино","калитка","камень","камин","канал","кандидат","каникулы","канон","капитан","капля","капот","капуста","карандаш","карета","каркас","карман","картина","карьера","каска","кассета","кастрюля","каталог","катер","каток","катушка","кафедра","качество","каша","кашлять","каюта","квадрат","квартира","квота","кепка","кивнуть","километр","кино","киоск","кипяток","кирпич","кислота","кисть","клавиша","клапан","класс","клей","клетка","клиент","климат","клиника","кличка","клоун","клочок","клуб","клумба","ключ","книга","кнопка","кнут","княгиня","князь","кобура","когда","кодекс","кожа","коктейль","колено","коллега","колонна","колпак","кольцо","колючий","коляска","команда","комедия","комиссия","коммуна","комната","комок","компания","комфорт","конвейер","конгресс","конечно","конкурс","контроль","концерт","конь","конюшня","копать","копейка","копыто","корабль","корень","корзина","коридор","кормить","корпус","космос","костюм","косяк","котел","котлета","который","коттедж","кофе","кофта","кошка","кража","край","красный","краткий","кредит","крем","крепкий","кресло","кривой","кризис","кристалл","критерий","кричать","кровь","крокодил","кролик","кроме","крона","круг","кружка","крупный","крутой","крушение","крыло","крыша","крючок","кстати","кубик","куда","кузов","кукла","кулак","кулиса","культура","кумир","купе","купить","купол","купюра","курица","курорт","курс","куртка","кусок","куст","кухня","кушать","лабиринт","лавка","лагерь","ладно","ладонь","лапа","лауреат","лгать","лебедь","левый","легенда","легкий","ледяной","лежать","лезвие","лезть","лекция","ленивый","лента","лепесток","лесной","лестница","лететь","лето","лечить","лига","лидер","лиловый","лимон","линия","липкий","лист","литр","лихой","лицо","лишить","лишний","ловить","логика","лодка","ложь","лозунг","локоть","лопата","лошадь","лукавый","луна","лучший","лысый","льгота","любить","любой","людской","люстра","лютый","лягушка","магазин","магия","майор","майский","максимум","макушка","мало","мальчик","мама","манера","марка","март","маршрут","масса","мастер","масштаб","материал","матч","махать","машина","маяк","мебель","медаль","медведь","медицина","медь","между","мелкий","мелочь","мемуары","меньше","меню","менять","мера","мерцать","место","месяц","металл","метод","метр","механизм","меховой","мечтать","мешать","мешок","миграция","микрофон","милиция","миллион","милость","миля","мимо","минерал","министр","минута","мирный","миска","миссия","митинг","мишень","младший","мнение","мнимый","много","могучий","модель","может","мозг","мокрый","молекула","молния","молодой","молчать","момент","монета","монитор","монолог","монстр","монтаж","мораль","море","морковь","мороз","морщина","мостовая","мотать","мотив","мотор","мохнатый","мрамор","мрачный","мстить","мудрый","мужество","мужчина","музей","музыка","мундир","муравей","мусор","муха","мчаться","мысль","мыться","мышца","мышь","мюзикл","мягкий","мясо","набор","навык","наглый","нагрузка","надежда","надзор","надо","наедине","назад","название","назло","наивный","найти","наконец","налево","наличие","налог","намерен","нанести","напасть","например","народ","наследие","натура","наука","наутро","начать","небо","неважно","невеста","негодяй","недавно","неделя","недолго","недра","недуг","нежный","незачем","некто","нелепый","неловко","нельзя","немало","немой","неплохо","нервный","нередко","нестись","неудача","неужели","нефть","неясный","нигде","низкий","никакой","никогда","никуда","ничто","ничуть","ниша","нищий","новость","новый","нога","ноготь","ножницы","ноздря","номер","носить","носок","ночь","ноябрь","нрав","нуль","нынче","нырять","нюанс","няня","обаяние","обед","обезьяна","обещать","обжечь","обзор","обилие","обитать","область","облик","обложка","обмен","обморок","обожать","обои","оболочка","оборона","обочина","образ","обрести","обрыв","обувь","обучение","обход","общество","общий","объект","обыск","обычно","обязать","овощи","овраг","овца","оговорка","ограда","огурец","одежда","одеяло","один","однако","одолеть","ожидать","озеро","океан","окно","около","окоп","окраина","октябрь","опасный","опека","операция","описание","оплата","опора","оппонент","оптимизм","оптовый","опухоль","опыт","оратор","орбита","орган","орден","орел","оригинал","ориентир","оркестр","оружие","осенний","осколок","осмотр","остров","отбор","отбыть","отвлечь","отдать","отдел","отдых","отель","отец","отзыв","отказ","отклик","открыть","откуда","отличие","отныне","отойти","отпуск","отрасль","отросток","отрывок","отряд","отсек","отставка","отсюда","оттенок","оттого","отчего","отъезд","офис","офицер","охота","охрана","оценка","очаг","очень","очередь","очищать","ошибка","ощущение","павильон","падать","пазуха","пакет","палата","палец","палуба","пальто","память","панель","паника","пара","парень","пароход","партия","парус","паспорт","пассажир","пастух","патент","патрон","пауза","паук","паутина","пафос","пахнуть","пациент","пачка","певец","педагог","пейзаж","пенсия","пепел","первый","перед","период","перо","перрон","персонаж","перчатка","песня","песок","петля","петрушка","петух","пехота","печать","печень","пешком","пещера","пианист","пиджак","пилот","пионер","пирамида","пирожок","письмо","пища","плавание","плакать","пламя","план","пласт","платить","пленный","плечо","плита","плод","плоский","плотный","плохой","площадь","плыть","плюс","пляж","плясать","победа","повар","повод","повсюду","повязка","погода","погреб","подбор","подвиг","подделка","поджать","поднос","подпись","подруга","подход","подчас","подъезд","поединок","поезд","поесть","поехать","пожалуй","пожилой","позади","позвать","поздний","позиция","позор","поиск","поймать","пойти","поклон","покой","покрыть","полдень","полезный","ползти","полк","полный","половина","полтора","польза","поляна","помидор","помнить","помощь","попасть","поперек","поплыть","пополам","поправка","попугай","попытка","порог","портрет","порция","порыв","порядок","после","посол","посреди","постель","посуда","потом","похвала","похожий","поцелуй","почва","почему","пошлина","поэма","поэтому","право","праздник","практика","прах","преграда","предмет","прежде","прелесть","премия","препарат","пресса","прибыть","прижать","прийти","приказ","прилавок","пример","принять","природа","притом","прихожая","прицел","причина","приют","прогноз","продукт","проект","прожить","прокат","промысел","пропуск","просто","против","профиль","процесс","прочий","прошлый","прощать","пружина","прут","прыжок","прямой","птица","публика","пугать","пуговица","пузырь","пульт","пуля","пункт","пускать","пустой","путь","пухлый","пучок","пушистый","пушка","пчела","пшеница","пылать","пыль","пышный","пьеса","пятка","пятно","пятый","пятьсот","работа","равнина","ради","радость","радуга","разбить","развитие","разговор","раздел","различие","размер","разный","разрыв","разум","район","ракета","раковина","рамка","рано","рапорт","распад","рассказ","расти","расход","расцвет","рация","рвануть","рваться","реакция","ребро","реветь","редактор","редкий","реестр","режим","резать","резерв","резина","резко","резной","рейс","реклама","рекорд","религия","рельс","ремень","ремонт","реплика","репортаж","ресница","ресторан","реформа","рецепт","речь","решение","ржавый","риск","рисунок","ритуал","рифма","робко","робот","ровесник","ровно","родной","рождение","роза","розовый","розыск","роль","роман","роскошь","роспись","рост","рубашка","рубеж","рубить","рубрика","рудник","рука","рукопись","румяный","русло","рухнуть","ручей","ручной","рыба","рыжий","рынок","рыхлый","рыцарь","рычаг","рюкзак","рядом","садовый","сажать","салон","салфетка","салют","самец","самовар","самый","сани","санкция","сапог","сарай","сатира","сахар","сбить","сбоку","сборная","сбыт","свадьба","свалка","сварить","свежий","сверху","свет","свеча","свинья","свист","свитер","свобода","сводка","свой","свыше","связь","сдаться","сделать","сегмент","сегодня","седло","седой","седьмой","сезон","сейф","сейчас","секрет","сектор","секунда","семинар","семья","сенатор","сено","сенсация","сентябрь","сервис","сердце","середина","сержант","серия","серый","сессия","сесть","сетевой","сжатый","сжечь","сзади","сигнал","сиденье","сила","силуэт","сильный","символ","симпатия","симфония","синий","синтез","синяк","сирень","система","ситуация","сияние","сказать","скала","скамейка","скандал","скатерть","скачок","скважина","сквер","сквозь","скелет","скидка","склад","сколько","скорый","скосить","скот","скрипка","скудный","скука","слабый","слава","сладкий","слегка","след","слеза","слепой","слесарь","слишком","слово","слог","сложный","сломать","служба","слух","случай","слышать","слюна","смежный","смелый","сменить","смесь","сметана","смех","смола","смуглый","смутный","смущать","смысл","снайпер","снаряд","сначала","снег","снизу","сниться","сно��а","снять","собака","соблазн","собрание","событие","совесть","совсем","согласие","создать","сознание","созреть","сойтись","сокол","солдат","соленый","солнце","солома","сомнение","сонный","соперник","соратник","сорвать","сосед","сосиска","состав","сотня","соус","союз","спад","спальня","спасти","спектр","сперва","спешить","спина","спирт","список","спичка","сплав","спонсор","спор","способ","справка","спустя","спутник","сразу","средство","срок","срыв","ссора","ссылка","ставить","стадия","стакан","станция","старый","стая","стебель","стекло","стена","степень","стереть","стиль","стимул","стирать","стихи","стоить","стойка","стол","стонать","стопа","сторона","стоянка","страна","стричь","строгий","струя","студент","стук","ступня","стыдно","суббота","субъект","сувенир","сугроб","сугубо","судить","судно","судьба","суета","суметь","сумма","сумрак","сундук","супруг","суровый","сутки","сухой","суша","существо","сфера","схема","схожий","сценарий","счастье","считать","съезд","сыграть","сырой","сытый","сыщик","сюда","сюжет","сюрприз","тайна","также","такой","такси","тактика","талия","таможня","танец","таракан","тарелка","тариф","тащить","таять","тварь","театр","тезис","текст","текущий","телефон","тема","темнота","теневой","теннис","теория","теперь","тепло","терапия","терзать","термин","терпеть","терраса","терять","тесный","тетрадь","техника","течение","тигр","типовой","тираж","титул","тихий","ткань","товарищ","тоже","толпа","толстый","толчок","толщина","только","тонкий","тонна","топить","топор","торговля","тормоз","торчать","тотчас","точка","точно","тощий","трава","традиция","трактор","трамвай","траншея","трасса","тревога","трезвый","тренер","трепет","треск","третий","трещина","трибуна","тридцать","триста","триумф","трогать","тройка","тронуть","тропа","тротуар","трубка","труд","трюк","тряпка","туго","туловище","туман","тумбочка","тундра","тупик","турист","турнир","тусклый","туфля","туча","тысяча","тяга","тяжело","убежать","убогий","уборка","уважение","увезти","уволить","угадать","угол","угощать","угроза","угрюмый","удар","удачный","уделять","удивить","удобный","удочка","уезжать","ужин","узел","узкий","уйти","указание","уклон","украсть","укусить","улетать","улица","улыбка","умело","умение","умный","умолять","унести","унижать","унылый","упаковка","упасть","упорно","упрек","урна","уровень","урожай","уронить","усадьба","усатый","усвоить","усилие","условие","услуга","усмешка","успеть","устав","устоять","утечка","утешать","утро","уцелеть","участие","ученик","учесть","ущелье","ущерб","уютный","фабрика","фаворит","факел","факт","фамилия","фантазия","фасад","февраль","феномен","фермер","фигура","физика","филиал","философ","фильм","финал","флаг","флот","фойе","фокус","фонарь","фонд","фонтан","форма","форум","фото","фрагмент","фраза","фракция","фронт","фрукт","функция","фуражка","футбол","футляр","халат","хаос","характер","хата","хвалить","хватать","хвойный","хвост","химия","хирург","хитрый","хищник","хлеб","хлынуть","хмурый","ходить","хозяин","хоккей","холм","холст","хорошо","хотеть","храбрый","храм","хранить","хребет","хрен","хрипло","хроника","хрупкий","художник","худший","хулиган","хутор","царь","цветок","целевой","целиком","целое","цель","цензура","ценить","центр","цепной","цикл","цилиндр","цирк","цитата","цифра","чайник","часы","чашка","человек","челюсть","чемодан","чемпион","чепуха","червь","чердак","через","чернила","черта","чеснок","честно","четверть","четыре","число","чистый","читатель","чтение","чтобы","чувство","чудак","чудный","чудо","чужой","чулок","чума","чушь","чуять","шагать","шанс","шапка","шарик","шарф","шахматы","шашлык","шедевр","шептать","шерсть","шестой","шинель","ширина","шишка","шкаф","школа","шкура","шланг","шлем","шнур","шоколад","шорох","шоссе","шпион","шприц","штаб","штамм","штаны","штатный","штора","штраф","штурм","штык","шумно","шуршать","шутить","шутка","щедрый","щека","щенок","экзамен","экипаж","экономия","экран","эксперт","элемент","элитный","эмоция","энергия","эпизод","эпоха","эскиз","эстрада","этап","этика","этот","эфир","эффект","эшелон","юбилей","юбка","южный","юмор","юность","юрист","юстиция","яблоко","явление","ягода","ядро","язык","яйцо","якобы","якорь","январь","яркий","ярмарка","ярость","ясный","яхта","ячейка","ящик"]["ábaco","abdomen","abeja","abierto","abogado","abono","aborto","abrazo","abrir","abuelo","abuso","acabar","academia","acceso","acción","aceite","acelga","acento","aceptar","ácido","aclarar","acné","acoger","acoso","activo","acto","actriz","actuar","acudir","acuerdo","acusar","adicto","admitir","adoptar","adorno","aduana","adulto","aéreo","afectar","afición","afinar","afirmar","ágil","agitar","agonía","agosto","agotar","agregar","agrio","agua","agudo","águila","aguja","ahogo","ahorro","aire","aislar","ajedrez","ajeno","ajuste","alacrán","alambre","alarma","alba","álbum","alcalde","aldea","alegre","alejar","alerta","aleta","alfiler","alga","algodón","aliado","aliento","alivio","alma","almeja","almíbar","altar","alteza","altivo","alto","altura","alumno","alzar","amable","amante","amapola","amargo","amasar","ámbar","ámbito","ameno","amigo","amistad","amor","amparo","amplio","ancho","anciano","ancla","andar","andén","anemia","ángulo","anillo","ánimo","anís","anotar","antena","antiguo","antojo","anual","anular","anuncio","añadir","añejo","año","apagar","aparato","apetito","apio","aplicar","apodo","aporte","apoyo","aprender","aprobar","apuesta","apuro","arado","araña","arar","árbitro","árbol","arbusto","archivo","arco","arder","ardilla","arduo","área","árido","aries","armonía","arnés","aroma","arpa","arpón","arreglo","arroz","arruga","arte","artista","asa","asado","asalto","ascenso","asegurar","aseo","asesor","asiento","asilo","asistir","asno","asombro","áspero","astilla","astro","astuto","asumir","asunto","atajo","ataque","atar","atento","ateo","ático","atleta","átomo","atraer","atroz","atún","audaz","audio","auge","aula","aumento","ausente","autor","aval","avance","avaro","ave","avellana","avena","avestruz","avión","aviso","ayer","ayuda","ayuno","azafrán","azar","azote","azúcar","azufre","azul","baba","babor","bache","bahía","baile","bajar","balanza","balcón","balde","bambú","banco","banda","baño","barba","barco","barniz","barro","báscula","bastón","basura","batalla","batería","batir","batuta","baúl","bazar","bebé","bebida","bello","besar","beso","bestia","bicho","bien","bingo","blanco","bloque","blusa","boa","bobina","bobo","boca","bocina","boda","bodega","boina","bola","bolero","bolsa","bomba","bondad","bonito","bono","bonsái","borde","borrar","bosque","bote","botín","bóveda","bozal","bravo","brazo","brecha","breve","brillo","brinco","brisa","broca","broma","bronce","brote","bruja","brusco","bruto","buceo","bucle","bueno","buey","bufanda","bufón","búho","buitre","bulto","burbuja","burla","burro","buscar","butaca","buzón","caballo","cabeza","cabina","cabra","cacao","cadáver","cadena","caer","café","caída","caimán","caja","cajón","cal","calamar","calcio","caldo","calidad","calle","calma","calor","calvo","cama","cambio","camello","camino","campo","cáncer","candil","canela","canguro","canica","canto","caña","cañón","caoba","caos","capaz","capitán","capote","captar","capucha","cara","carbón","cárcel","careta","carga","cariño","carne","carpeta","carro","carta","casa","casco","casero","caspa","castor","catorce","catre","caudal","causa","cazo","cebolla","ceder","cedro","celda","célebre","celoso","célula","cemento","ceniza","centro","cerca","cerdo","cereza","cero","cerrar","certeza","césped","cetro","chacal","chaleco","champú","chancla","chapa","charla","chico","chiste","chivo","choque","choza","chuleta","chupar","ciclón","ciego","cielo","cien","cierto","cifra","cigarro","cima","cinco","cine","cinta","ciprés","circo","ciruela","cisne","cita","ciudad","clamor","clan","claro","clase","clave","cliente","clima","clínica","cobre","cocción","cochino","cocina","coco","código","codo","cofre","coger","cohete","cojín","cojo","cola","colcha","colegio","colgar","colina","collar","colmo","columna","combate","comer","comida","cómodo","compra","conde","conejo","conga","conocer","consejo","contar","copa","copia","corazón","corbata","corcho","cordón","corona","correr","coser","cosmos","costa","cráneo","cráter","crear","crecer","creído","crema","cría","crimen","cripta","crisis","cromo","crónica","croqueta","crudo","cruz","cuadro","cuarto","cuatro","cubo","cubrir","cuchara","cuello","cuento","cuerda","cuesta","cueva","cuidar","culebra","culpa","culto","cumbre","cumplir","cuna","cuneta","cuota","cupón","cúpula","curar","curioso","curso","curva","cutis","dama","danza","dar","dardo","dátil","deber","débil","década","decir","dedo","defensa","definir","dejar","delfín","delgado","delito","demora","denso","dental","deporte","derecho","derrota","desayuno","deseo","desfile","desnudo","destino","desvío","detalle","detener","deuda","día","diablo","diadema","diamante","diana","diario","dibujo","dictar","diente","dieta","diez","difícil","digno","dilema","diluir","dinero","directo","dirigir","disco","diseño","disfraz","diva","divino","doble","doce","dolor","domingo","don","donar","dorado","dormir","dorso","dos","dosis","dragón","droga","ducha","duda","duelo","dueño","dulce","dúo","duque","durar","dureza","duro","ébano","ebrio","echar","eco","ecuador","edad","edición","edificio","editor","educar","efecto","eficaz","eje","ejemplo","elefante","elegir","elemento","elevar","elipse","élite","elixir","elogio","eludir","embudo","emitir","emoción","empate","empeño","empleo","empresa","enano","encargo","enchufe","encía","enemigo","enero","enfado","enfermo","engaño","enigma","enlace","enorme","enredo","ensayo","enseñar","entero","entrar","envase","envío","época","equipo","erizo","escala","escena","escolar","escribir","escudo","esencia","esfera","esfuerzo","espada","espejo","espía","esposa","espuma","esquí","estar","este","estilo","estufa","etapa","eterno","ética","etnia","evadir","evaluar","evento","evitar","exacto","examen","exceso","excusa","exento","exigir","exilio","existir","éxito","experto","explicar","exponer","extremo","fábrica","fábula","fachada","fácil","factor","faena","faja","falda","fallo","falso","faltar","fama","familia","famoso","faraón","farmacia","farol","farsa","fase","fatiga","fauna","favor","fax","febrero","fecha","feliz","feo","feria","feroz","fértil","fervor","festín","fiable","fianza","fiar","fibra","ficción","ficha","fideo","fiebre","fiel","fiera","fiesta","figura","fijar","fijo","fila","filete","filial","filtro","fin","finca","fingir","finito","firma","flaco","flauta","flecha","flor","flota","fluir","flujo","flúor","fobia","foca","fogata","fogón","folio","folleto","fondo","forma","forro","fortuna","forzar","fosa","foto","fracaso","frágil","franja","frase","fraude","freír","freno","fresa","frío","frito","fruta","fuego","fuente","fuerza","fuga","fumar","función","funda","furgón","furia","fusil","fútbol","futuro","gacela","gafas","gaita","gajo","gala","galería","gallo","gamba","ganar","gancho","ganga","ganso","garaje","garza","gasolina","gastar","gato","gavilán","gemelo","gemir","gen","género","genio","gente","geranio","gerente","germen","gesto","gigante","gimnasio","girar","giro","glaciar","globo","gloria","gol","golfo","goloso","golpe","goma","gordo","gorila","gorra","gota","goteo","gozar","grada","gráfico","grano","grasa","gratis","grave","grieta","grillo","gripe","gris","grito","grosor","grúa","grueso","grumo","grupo","guante","guapo","guardia","guerra","guía","guiño","guion","guiso","guitarra","gusano","gustar","haber","hábil","hablar","hacer","hacha","hada","hallar","hamaca","harina","haz","hazaña","hebilla","hebra","hecho","helado","helio","hembra","herir","hermano","héroe","hervir","hielo","hierro","hígado","higiene","hijo","himno","historia","hocico","hogar","hoguera","hoja","hombre","hongo","honor","honra","hora","hormiga","horno","hostil","hoyo","hueco","huelga","huerta","hueso","huevo","huida","huir","humano","húmedo","humilde","humo","hundir","huracán","hurto","icono","ideal","idioma","ídolo","iglesia","iglú","igual","ilegal","ilusión","imagen","imán","imitar","impar","imperio","imponer","impulso","incapaz","índice","inerte","infiel","informe","ingenio","inicio","inmenso","inmune","innato","insecto","instante","interés","íntimo","intuir","inútil","invierno","ira","iris","ironía","isla","islote","jabalí","jabón","jamón","jarabe","jardín","jarra","jaula","jazmín","jefe","jeringa","jinete","jornada","joroba","joven","joya","juerga","jueves","juez","jugador","jugo","juguete","juicio","junco","jungla","junio","juntar","júpiter","jurar","justo","juvenil","juzgar","kilo","koala","labio","lacio","lacra","lado","ladrón","lagarto","lágrima","laguna","laico","lamer","lámina","lámpara","lana","lancha","langosta","lanza","lápiz","largo","larva","lástima","lata","látex","latir","laurel","lavar","lazo","leal","lección","leche","lector","leer","legión","legumbre","lejano","lengua","lento","leña","león","leopardo","lesión","letal","letra","leve","leyenda","libertad","libro","licor","líder","lidiar","lienzo","liga","ligero","lima","límite","limón","limpio","lince","lindo","línea","lingote","lino","linterna","líquido","liso","lista","litera","litio","litro","llaga","llama","llanto","llave","llegar","llenar","llevar","llorar","llover","lluvia","lobo","loción","loco","locura","lógica","logro","lombriz","lomo","lonja","lote","lucha","lucir","lugar","lujo","luna","lunes","lupa","lustro","luto","luz","maceta","macho","madera","madre","maduro","maestro","mafia","magia","mago","maíz","maldad","maleta","malla","malo","mamá","mambo","mamut","manco","mando","manejar","manga","maniquí","manjar","mano","manso","manta","mañana","mapa","máquina","mar","marco","marea","marfil","margen","marido","mármol","marrón","martes","marzo","masa","máscara","masivo","matar","materia","matiz","matriz","máximo","mayor","mazorca","mecha","medalla","medio","médula","mejilla","mejor","melena","melón","memoria","menor","mensaje","mente","menú","mercado","merengue","mérito","mes","mesón","meta","meter","método","metro","mezcla","miedo","miel","miembro","miga","mil","milagro","militar","millón","mimo","mina","minero","mínimo","minuto","miope","mirar","misa","miseria","misil","mismo","mitad","mito","mochila","moción","moda","modelo","moho","mojar","molde","moler","molino","momento","momia","monarca","moneda","monja","monto","moño","morada","morder","moreno","morir","morro","morsa","mortal","mosca","mostrar","motivo","mover","móvil","mozo","mucho","mudar","mueble","muela","muerte","muestra","mugre","mujer","mula","muleta","multa","mundo","muñeca","mural","muro","músculo","museo","musgo","música","muslo","nácar","nación","nadar","naipe","naranja","nariz","narrar","nasal","natal","nativo","natural","náusea","naval","nave","navidad","necio","néctar","negar","negocio","negro","neón","nervio","neto","neutro","nevar","nevera","nicho","nido","niebla","nieto","niñez","niño","nítido","nivel","nobleza","noche","nómina","noria","norma","norte","nota","noticia","novato","novela","novio","nube","nuca","núcleo","nudillo","nudo","nuera","nueve","nuez","nulo","número","nutria","oasis","obeso","obispo","objeto","obra","obrero","observar","obtener","obvio","oca","ocaso","océano","ochenta","ocho","ocio","ocre","octavo","octubre","oculto","ocupar","ocurrir","odiar","odio","odisea","oeste","ofensa","oferta","oficio","ofrecer","ogro","oído","oír","ojo","ola","oleada","olfato","olivo","olla","olmo","olor","olvido","ombligo","onda","onza","opaco","opción","ópera","opinar","oponer","optar","óptica","opuesto","oración","orador","oral","órbita","orca","orden","oreja","órgano","orgía","orgullo","oriente","origen","orilla","oro","orquesta","oruga","osadía","oscuro","osezno","oso","ostra","otoño","otro","oveja","óvulo","óxido","oxígeno","oyente","ozono","pacto","padre","paella","página","pago","país","pájaro","palabra","palco","paleta","pálido","palma","paloma","palpar","pan","panal","pánico","pantera","pañuelo","papá","papel","papilla","paquete","parar","parcela","pared","parir","paro","párpado","parque","párrafo","parte","pasar","paseo","pasión","paso","pasta","pata","patio","patria","pausa","pauta","pavo","payaso","peatón","pecado","pecera","pecho","pedal","pedir","pegar","peine","pelar","peldaño","pelea","peligro","pellejo","pelo","peluca","pena","pensar","peñón","peón","peor","pepino","pequeño","pera","percha","perder","pereza","perfil","perico","perla","permiso","perro","persona","pesa","pesca","pésimo","pestaña","pétalo","petróleo","pez","pezuña","picar","pichón","pie","piedra","pierna","pieza","pijama","pilar","piloto","pimienta","pino","pintor","pinza","piña","piojo","pipa","pirata","pisar","piscina","piso","pista","pitón","pizca","placa","plan","plata","playa","plaza","pleito","pleno","plomo","pluma","plural","pobre","poco","poder","podio","poema","poesía","poeta","polen","policía","pollo","polvo","pomada","pomelo","pomo","pompa","poner","porción","portal","posada","poseer","posible","poste","potencia","potro","pozo","prado","precoz","pregunta","premio","prensa","preso","previo","primo","príncipe","prisión","privar","proa","probar","proceso","producto","proeza","profesor","programa","prole","promesa","pronto","propio","próximo","prueba","público","puchero","pudor","pueblo","puerta","puesto","pulga","pulir","pulmón","pulpo","pulso","puma","punto","puñal","puño","pupa","pupila","puré","quedar","queja","quemar","querer","queso","quieto","química","quince","quitar","rábano","rabia","rabo","ración","radical","raíz","rama","rampa","rancho","rango","rapaz","rápido","rapto","rasgo","raspa","rato","rayo","raza","razón","reacción","realidad","rebaño","rebote","recaer","receta","rechazo","recoger","recreo","recto","recurso","red","redondo","reducir","reflejo","reforma","refrán","refugio","regalo","regir","regla","regreso","rehén","reino","reír","reja","relato","relevo","relieve","relleno","reloj","remar","remedio","remo","rencor","rendir","renta","reparto","repetir","reposo","reptil","res","rescate","resina","respeto","resto","resumen","retiro","retorno","retrato","reunir","revés","revista","rey","rezar","rico","riego","rienda","riesgo","rifa","rígido","rigor","rincón","riñón","río","riqueza","risa","ritmo","rito","rizo","roble","roce","rociar","rodar","rodeo","rodilla","roer","rojizo","rojo","romero","romper","ron","ronco","ronda","ropa","ropero","rosa","rosca","rostro","rotar","rubí","rubor","rudo","rueda","rugir","ruido","ruina","ruleta","rulo","rumbo","rumor","ruptura","ruta","rutina","sábado","saber","sabio","sable","sacar","sagaz","sagrado","sala","saldo","salero","salir","salmón","salón","salsa","salto","salud","salvar","samba","sanción","sandía","sanear","sangre","sanidad","sano","santo","sapo","saque","sardina","sartén","sastre","satán","sauna","saxofón","sección","seco","secreto","secta","sed","seguir","seis","sello","selva","semana","semilla","senda","sensor","señal","señor","separar","sepia","sequía","ser","serie","sermón","servir","sesenta","sesión","seta","setenta","severo","sexo","sexto","sidra","siesta","siete","siglo","signo","sílaba","silbar","silencio","silla","símbolo","simio","sirena","sistema","sitio","situar","sobre","socio","sodio","sol","solapa","soldado","soledad","sólido","soltar","solución","sombra","sondeo","sonido","sonoro","sonrisa","sopa","soplar","soporte","sordo","sorpresa","sorteo","sostén","sótano","suave","subir","suceso","sudor","suegra","suelo","sueño","suerte","sufrir","sujeto","sultán","sumar","superar","suplir","suponer","supremo","sur","surco","sureño","surgir","susto","sutil","tabaco","tabique","tabla","tabú","taco","tacto","tajo","talar","talco","talento","talla","talón","tamaño","tambor","tango","tanque","tapa","tapete","tapia","tapón","taquilla","tarde","tarea","tarifa","tarjeta","tarot","tarro","tarta","tatuaje","tauro","taza","tazón","teatro","techo","tecla","técnica","tejado","tejer","tejido","tela","teléfono","tema","temor","templo","tenaz","tender","tener","tenis","tenso","teoría","terapia","terco","término","ternura","terror","tesis","tesoro","testigo","tetera","texto","tez","tibio","tiburón","tiempo","tienda","tierra","tieso","tigre","tijera","tilde","timbre","tímido","timo","tinta","tío","típico","tipo","tira","tirón","titán","títere","título","tiza","toalla","tobillo","tocar","tocino","todo","toga","toldo","tomar","tono","tonto","topar","tope","toque","tórax","torero","tormenta","torneo","toro","torpedo","torre","torso","tortuga","tos","tosco","toser","tóxico","trabajo","tractor","traer","tráfico","trago","traje","tramo","trance","trato","trauma","trazar","trébol","tregua","treinta","tren","trepar","tres","tribu","trigo","tripa","triste","triunfo","trofeo","trompa","tronco","tropa","trote","trozo","truco","trueno","trufa","tubería","tubo","tuerto","tumba","tumor","túnel","túnica","turbina","turismo","turno","tutor","ubicar","úlcera","umbral","unidad","unir","universo","uno","untar","uña","urbano","urbe","urgente","urna","usar","usuario","útil","utopía","uva","vaca","vacío","vacuna","vagar","vago","vaina","vajilla","vale","válido","valle","valor","válvula","vampiro","vara","variar","varón","vaso","vecino","vector","vehículo","veinte","vejez","vela","velero","veloz","vena","vencer","venda","veneno","vengar","venir","venta","venus","ver","verano","verbo","verde","vereda","verja","verso","verter","vía","viaje","vibrar","vicio","víctima","vida","vídeo","vidrio","viejo","viernes","vigor","vil","villa","vinagre","vino","viñedo","violín","viral","virgo","virtud","visor","víspera","vista","vitamina","viudo","vivaz","vivero","vivir","vivo","volcán","volumen","volver","voraz","votar","voto","voz","vuelo","vulgar","yacer","yate","yegua","yema","yerno","yeso","yodo","yoga","yogur","zafiro","zanja","zapato","zarza","zona","zorro","zumo","zurdo"]["abajur","abaküs","abartı","abdal","abdest","abiye","abluka","abone","absorbe","absürt","acayip","acele","acemi","açıkgöz","adalet","adam","adezyon","adisyon","adliye","adres","afacan","afili","afiş","afiyet","aforizm","afra","ağaç","ağır","ahbap","ahkam","ahlak","ahtapot","aidat","aile","ajan","akademi","akarsu","akbaş","akciğer","akdeniz","akıbet","akıl","akıntı","akide","akrep","akrobasi","aksiyon","akşam","aktif","aktör","aktris","akustik","alaca","albüm","alçak","aldanma","aleni","alet","alfabe","algılama","alıngan","alkış","alkol","alpay","alperen","altın","altüst","altyapı","alyuvar","amade","amatör","amazon","ambalaj","amblem","ambulans","amca","amel","amigo","amir","amiyane","amorti","ampul","anadolu","anahtar","anakonda","anaokul","anapara","anarşi","anatomi","anayasa","anekdot","anestezi","angaje","anka","anket","anlamlı","anne","anomali","anonim","anten","antlaşma","apse","araba","aracı","araf","arbede","arda","arefe","arena","argo","argüman","arkadaş","armoni","aroma","arsa","arsız","artı","artist","aruz","asansör","asayiş","asfalt","asgari","asil","asker","askı","aslan","asosyal","astsubay","asya","aşçı","aşırı","aşure","atabey","ataman","ateş","atmaca","atmosfer","atom","atölye","avcı","avdet","avize","avlu","avokado","avrupa","avukat","ayaz","ayçiçeği","aydın","aygıt","ayna","ayran","ayrıntı","azim","baca","bagaj","bağlantı","bahadır","bahçe","baki","bakkal","baklava","bakteri","balçık","balina","balo","balta","bant","banyo","bardak","barış","başbuğ","başıboş","başkan","başlık","bavul","bayındır","baykuş","bazlama","bedel","begüm","bekçi","bekle","belge","belki","bencil","benek","bengi","benzer","berjer","berk","bermuda","berrak","beşik","beton","beyin","beyoğlu","bıçak","biberiye","bidon","biftek","bihaber","bikini","bilezik","bilinç","bilye","bina","binbaşı","binyıl","bisiklet","bisküvi","bitki","bizzat","bodrum","boğaz","bohça","bolero","boncuk","bonfile","borsa","boru","bostan","boşboğaz","botanik","boya","boykot","boynuz","bozgun","bozkır","bölüm","börek","buçuk","bugün","buğday","buhar","buhran","bulvar","buram","burçak","burs","burun","butik","buzdağı","buzkıran","bücür","büfe","bülten","bütçe","bütün","büyük","cacık","cadı","cahil","cambaz","canhıraş","casus","cazibe","cehalet","cehennem","ceket","cemre","cenin","cennet","cepken","cerrah","cesur","cetvel","cevher","ceylan","cılız","cıva","cilt","cisim","ciyak","coğrafya","cömert","cumba","cüzdan","çabucak","çadır","çağdaş","çağlayan","çağrı","çakmak","çalışkan","çamaşır","çapa","çaput","çarık","çarpan","çarşaf","çayhane","çekirdek","çelebi","çember","çenet","çengel","çerçeve","çerez","çeşit","çeşme","çete","çevre","çeyiz","çeyrek","çığır","çılgın","çıngırak","çift","çiğdem","çikolata","çilek","çimen","çivi","çoban","çocuk","çokgen","çomak","çorba","çözelti","çubuk","çukur","çuval","çürük","dağbaşı","dağılım","daktilo","daldırış","dalga","dalkavuk","damak","damıtma","damla","dana","dandik","danışman","daniska","dantel","dargeçit","darphane","davet","dayı","defter","değer","değirmen","dehşet","delgeç","demir","deneyim","denge","depo","deprem","derdest","dere","derhal","derman","dernek","derviş","desen","destan","dışarı","dışbükey","dijital","dikbaşlı","dilekçe","dimağ","dinamik","dindar","dinleme","dinozor","dipçik","dipnot","direniş","dirsek","disiplin","disk","divriği","dizüstü","dobra","dodurga","doğalgaz","doktor","doküman","dolap","donanım","dondurma","donör","doruk","dosdoğru","dost","dosya","dozer","döküm","dönence","dörtyol","dövme","dram","dublaj","durum","duvak","duyarga","duyma","duyuru","düğme","düğüm","dükkan","dünür","düpedüz","dürbün","düşünür","düzayak","düzeltme","ebeveyn","ebru","ecel","ecnebi","ecza","edat","edilgen","efendi","efor","efsane","egemen","egzersiz","eğrelti","ekarte","ekip","eklem","ekmek","ekol","ekonomi","ekose","ekran","ekvator","elaman","elastik","elbet","elbise","elçi","eldiven","elebaşı","eleştiri","elma","eloğlu","elveda","emare","emekçi","emisyon","emniyet","empati","emsal","emzik","endüstri","enerji","engebe","engin","enişte","enkaz","entari","entegre","entrika","enzim","erdem","ergen","erguvan","erkek","erozyon","ertesi","erzak","esaret","esenlik","eser","eski","esnek","eşarp","eşofman","eşraf","eşya","eşzaman","etik","etken","etkinlik","etüt","evet","evire","evrak","evrim","eyalet","eyvah","ezber","fabrika","fanatik","fanus","fason","fasulye","fatih","fatura","fauna","favori","fayans","fayton","fazıl","fazilet","federal","felsefe","fener","feribot","fersah","fesih","festival","feveran","feza","fıçı","fıldır","fındık","fırça","fırsat","fırtına","fıtık","fidan","fidye","figür","fihrist","fikir","fildişi","filo","filtre","fincan","firuze","fitil","fiyaka","fizik","flaş","flüt","fosil","fren","fukara","futbol","garabet","gariban","garnitür","gazi","gece","gedik","gelenek","gelin","gemi","genç","geniş","geometri","gerçek","gevrek","gezegen","gezgin","geziyolu","gıcık","gıda","gıybet","girdap","girişim","gitar","giyecek","giysi","gizem","gofret","goril","göbek","göçebe","göğüs","gökdelen","gökmen","gökyüzü","gölge","gömlek","gönül","görenek","görkemli","görsel","gösteri","gövde","gözaltı","gözcü","gözdağı","gözleme","gözyaşı","grup","gurbet","gusül","gübre","güfte","gümüş","günaydın","güncel","gündüz","güneş","günyüzü","gürbüz","güvercin","güzel","haber","hacamat","hacim","hademe","hafız","hafriyat","hafta","hakan","hakem","hakikat","haksever","halı","hançer","hane","hangar","hapis","hapşırık","harf","haseki","hasret","hatun","havuç","haylaz","haysiyet","hayvan","hedef","hektar","hemen","hemfikir","hendek","hepsi","hergele","herhangi","hesap","heyecan","heykel","hezimet","hıçkırık","hızölçer","hicviye","hikaye","hikmet","hile","hisse","hobi","hoca","horlama","hormon","hoşbeş","hoşgörü","hoyrat","hörgüç","höyük","hudut","hukuk","hunhar","hurda","huysuz","huzur","hücum","hükümet","hünkar","hüviyet","ırmak","ısıölçer","ısıtıcı","ıspanak","ısrar","ışıldak","ızdırap","ızgara","ibadet","icat","içbükey","içecek","içgüdü","içsel","idman","iftihar","iğne","ihanet","ihbar","ihdas","ihmal","ihracat","ihsan","ikilem","ikindi","ikircik","iklim","iksir","iktibas","ilaç","ilçe","ileri","iletişim","ilgi","ilhak","ilkbahar","ilkokul","ilmek","imkan","imleç","imsak","imtihan","imza","ince","inkar","inşa","ipek","ipucu","irade","irfan","irmik","isabet","iskele","israf","isyan","işçi","işgal","işgüzar","işlem","itibar","itiraf","ivedi","ivme","iyileşme","iyimser","izbandut","izci","izdiham","izin","jakoben","jandarma","jargon","kabadayı","kablo","kabus","kaçamak","kadeh","kadın","kadraj","kafa","kafkas","kağıt","kağnı","kahkaha","kahraman","kahvaltı","kakül","kaldırım","kale","kalibre","kalkan","kalpak","kamış","kamyon","kanat","kandaş","kanepe","kanser","kanun","kaos","kapı","kaplıca","kaptan","karanlık","kardeş","karga","karınca","karmaşa","karşıt","kasırga","kask","kasvet","katkı","katman","kavram","kaygan","kaynakça","kayyum","kedi","kehanet","kekik","kelebek","kenar","kerkenez","kerpiç","kesirli","kesmece","kestane","keşkek","ketçap","keyfiyet","kıble","kıdemli","kılavuz","kılçık","kılıf","kıraç","kırmızı","kırsal","kısayol","kısım","kıskanç","kısmet","kışla","kıvanç","kıvılcım","kıvrık","kıyafet","kıymetli","kızak","kızılcık","kibar","kinaye","kira","kiremit","kirli","kirpik","kişisel","kitap","koçbaşı","kodaman","koğuş","kokteyl","kolaycı","kolbastı","kolonya","koltuk","kolye","kombine","komedyen","komiser","komposto","komşu","komuta","konak","konfor","koni","konsül","kopya","korkusuz","korna","korse","korunak","korvet","kostüm","koşul","koyu","kozmik","köfte","kökensel","köprücük","köpük","kördüğüm","körfez","köstebek","köşegen","kötü","kravat","kriter","kuantum","kudurma","kuluçka","kulübe","kumanya","kumbara","kumlu","kumpir","kumral","kundura","kupa","kupkuru","kuramsal","kurbağa","kurdele","kurgu","kurmay","kurşun","kurtuluş","kurultay","kurye","kusursuz","kuşak","kuşbaşı","kuşkulu","kutlama","kutsal","kutup","kuver","kuyruk","kuzey","kuzgun","küçük","külçe","külfet","külliye","kültürel","kümes","künefe","küresel","kütle","lahana","lahmacun","lamba","lansman","lavaş","layık","leğen","levent","leziz","lezzet","lider","likide","liman","liste","litre","liyakat","lodos","lokanta","lokman","lokum","lunapark","lütfen","lüzum","nokta","mabet","macera","macun","madalya","madde","madem","mağara","mağdur","mağfiret","mağlup","mahalle","mahcup","mahir","mahkeme","mahlas","mahrum","mahsul","makas","makbuz","makine","makro","maksat","makul","maliye","manav","mangal","manidar","manken","mantık","manzara","mareşal","margarin","marifet","market","marmelat","masaüstü","masmavi","masraf","masum","matah","materyal","matrak","maval","mavra","maydanoz","mayhoş","maytap","mazbata","mazeret","mazlum","mazot","mazur","meblağ","mebus","mecaz","mecbur","meclis","mecmua","mecnun","meçhul","medeni","mehtap","mekanik","melodi","meltem","memur","mendil","menekşe","menteşe","meraklı","mercek","merdiven","merhaba","merinos","merkez","mermi","mert","mesafe","mesele","mesken","meslek","meşale","meşgul","meşhur","metafor","metin","metre","mevcut","mevkidaş","meydan","meyil","meyve","meziyet","mezun","mıknatıs","mısra","mızıka","miğfer","mihrak","mikrofon","miktar","milat","milli","mimar","minare","mineral","minik","minyon","mirliva","misafir","miskin","miting","miyop","mizah","mobilya","model","monitör","morötesi","motive","motor","mozaik","muavin","mucize","muhafız","muhteşem","mukayese","mumya","musluk","muşamba","mutabık","mutfak","mutlu","muzaffer","muzdarip","mübarek","mücadele","müdür","müfredat","müftü","mühendis","mühim","mühlet","mükemmel","mülk","mümkün","mümtaz","müsrif","müstesna","müşahit","müşteri","mütercim","müthiş","müze","müzik","nabız","nadas","nadir","nahoş","nakarat","nakış","nalbur","namlu","namus","nankör","nargile","narkoz","nasıl","nasip","naylon","nazar","nazım","nazik","neden","nefes","negatif","neon","neptün","nerede","nesil","nesnel","neşeli","netice","nevresim","neyse","neyzen","nezaket","nezih","nezle","nicel","nilüfer","nimet","nisan","nispet","nitekim","nizam","nohut","noksan","normal","nostalji","noter","nöbet","numara","numune","nutuk","nüfus","obabaşı","obez","obje","ocak","odun","ofansif","ofis","oğlak","oğuz","okçu","oklava","oksijen","okul","okumuş","okutman","okuyucu","okyanus","olağan","olanak","olası","olay","olgun","olimpik","olumlu","omlet","omurga","onarım","onursal","opera","optik","oral","orantı","ordu","organik","orijin","orkide","orman","orta","oruç","otağ","otantik","otel","otoban","otogar","otomobil","otonom","otopark","otorite","otoyol","oturum","oyuk","oyuncak","ozan","ödeme","ödenek","ödev","ödül","ödünç","öfke","öğlen","öğrenci","öğün","öğütücü","öksürük","ölçme","ölçü","ölümsüz","ömür","önayak","öncü","önder","önem","önerge","öngörü","önlük","önsezi","öpücük","ördek","örgü","örtbas","örtme","örtü","örümcek","örüntü","öteberi","öteki","övünç","öykü","öyleyse","özçekim","özdeyiş","özel","özenti","özerk","özgürlük","özlem","özlü","özne","özsever","özümseme","özür","özveri","pabuç","padişah","palamut","palmiye","palto","palyaço","pamuk","panayır","pancar","panda","panel","panik","panjur","pankart","pano","pansuman","pantolon","panzehir","papatya","papyon","paraşüt","parça","pardösü","parfüm","parıltı","parkur","parmak","parodi","parsel","partner","pasaport","pasif","paskalya","pastırma","paşa","patates","paten","patika","patlıcan","patolog","patron","payanda","paydaş","payidar","paylaşma","paytak","peçete","pedal","peder","pehlivan","pekala","pekmez","pelerin","pelikan","pelüş","pembe","pena","pencere","pense","perçin","perde","pergel","perişan","peron","personel","perşembe","peruk","pervane","pespaye","pestil","peşin","petek","petrol","petunya","peynir","peyzaj","pınar","pırasa","pırlanta","pide","pikap","piknik","pilav","piliç","pilot","pipet","pipo","piramit","pirinç","pirzola","pist","pişik","pişman","piyasa","piyes","plaj","plaket","planlama","platform","plazma","podyum","poğaça","polat","polen","politika","pompa","popüler","porselen","portakal","posa","poster","poşet","poyraz","pozitif","pranga","pratik","prenses","prim","problem","profil","program","proje","protokol","prova","puan","pudra","pusula","püre","pürüz","püstül","püsür","racon","radar","radikal","radyo","rafadan","rafine","rağbet","rahat","rahle","rakam","raket","rakip","rakun","ralli","rampa","randevu","ranza","rapor","rastgele","rasyonel","razı","realite","reçine","refah","referans","refik","reform","rehber","rehin","reis","rekabet","reklam","rekor","rektör","renk","resim","resmen","restoran","retorik","revaç","revize","reyon","rezalet","rezerv","rezil","rıhtım","rıza","ritim","ritüel","rivayet","robot","roman","rota","rozet","röportaj","rötar","ruble","ruhban","ruhsat","rulet","rulo","runik","rutin","rutubet","rüşvet","rütbe","rüya","rüzgar","sabah","sabıka","sabit","sabun","saçma","sade","sadık","safahat","safdil","safkan","sağanak","sağduyu","sağlam","saha","sahiden","sahne","sakal","sakız","sakin","saklama","saksağan","salamura","salça","salgı","salınım","salkım","salon","saltanat","sanatçı","sancak","sandalye","saniye","saplantı","sapsız","saray","sarışın","sarkık","sarmaşık","satır","savaşım","savunma","saydam","sayfa","saygın","sayısal","sebep","seçenek","seçim","seçkin","seçmen","seda","sedir","sedye","sefer","sehpa","sekizgen","selektör","selvi","semavi","sembol","seminer","senaryo","sendika","senkron","sensör","sentez","sepet","seramik","serbest","serdar","seremoni","sergi","serhat","serin","sermaye","serpuş","sersem","serüven","servis","sesli","sesteş","sevap","seviye","seyahat","seyirci","sezon","sıcak","sıfat","sıhhi","sınanma","sınır","sıradan","sırdaş","sırma","sırtüstü","sızgıt","siftah","sigorta","sihirbaz","silah","silecek","silindir","simetri","simge","simit","sincap","sindirim","sinema","sinirli","sipariş","sirke","siroz","sistem","sivilce","siyasi","slogan","soba","sofra","soğuk","sohbet","sokak","solfej","solunum","somut","sonbahar","sonraki","sonsuz","sorunsuz","sosyete","soyağacı","soydaş","soygun","soytarı","söğüş","sömürge","sönük","söylem","sözcük","sözde","spatula","spektrum","spiker","spiral","sponsor","sporcu","sprey","stabil","statü","stok","stopaj","strateji","subay","sucuk","suçüstü","suhulet","sulama","sungur","sunucu","surat","susam","suskun","sükse","sükut","sülale","sünger","süpürge","sürahi","süreç","sürgün","sürüm","süsleme","sütanne","sütlaç","sütun","süvari","şahane","şahbaz","şahit","şahsiyet","şakıma","şaklaban","şakrak","şamar","şampiyon","şanslı","şantiye","şapka","şarkıcı","şartname","şaşırma","şaşkın","şatafat","şayet","şebeke","şefkat","şeftali","şehir","şehvet","şeker","şekil","şelale","şema","şemsiye","şerbet","şeref","şerit","şımarık","şıpıdık","şifre","şimdi","şimşek","şipşak","şirin","şişe","şişirme","şofben","şöhret","şölen","şüphe","tabaka","tabela","tabure","tadilat","taharet","tahıl","tahkim","tahlil","tahmin","tahrifat","tahsilat","tahta","taklit","takoz","taksici","taktik","takvim","talebe","talip","tamamen","tamirci","tampon","tamtakır","tandır","tanecik","tanıtım","tanrı","tansiyon","tapan","tapınak","taptaze","tapu","tarafgir","tarhana","tarım","tarih","tarla","tartak","tarumar","tasarım","tasdik","taslak","tastamam","taşeron","taşınmaz","taşra","tatava","tatbikat","tatil","tatlı","tavsiye","tavşan","tavuk","taze","taziye","tazminat","tebeşir","tebrik","tecrübe","teçhizat","tedarik","tedbir","teftiş","teğet","teğmen","tehdit","tehlike","tekdüze","tekerlek","tekme","teknik","tekrar","telef","telsiz","telve","temas","tembel","temiz","temkin","tempo","temsilci","tendon","teneke","tenha","tenkit","tepegöz","tepki","terazi","terbiye","tercih","tereyağı","terfi","terim","terminal","tersane","tertip","tesadüf","tescil","tesir","teslimat","tespit","testere","teşekkür","teşhir","teşrif","teşvik","teyze","tezahür","tezgah","tıbbi","tıkaç","tıkışık","tıknaz","tılsım","tıpkı","tıraş","tırışka","tırmanış","tırnak","tırpan","tıslama","ticaret","tilki","tiryaki","titreşim","tohum","tokat","tolere","tomar","tombak","tomurcuk","topaç","toplum","toprak","toptan","toraman","torpido","tortu","tosbağa","toynak","tören","trafik","trajedi","tramvay","transfer","tribün","triko","tugay","tuğla","tuğrul","tuhaf","tulumba","tunç","turan","turkuaz","turnusol","turşu","turuncu","tutanak","tutkal","tutsak","tutum","tuyuğ","tuzlu","tüccar","tüfek","tükenmez","tülbent","tümleç","tünel","türbin","türev","türk","tüzük","ucube","ucuz","uçak","uçurtma","ufuk","uğrak","uğur","ukala","ulaşım","ulema","ulus","ulvi","umursama","umut","unutkan","uslu","ustabaşı","ustura","usul","utangaç","uyanık","uyarı","uydu","uygar","uygulama","uykusuz","uysal","uyuşma","uzantı","uzay","uzgören","uzlaşma","uzman","uzun","ücra","ücret","üçbudak","üçgen","üçkağıt","üçleme","üfürük","ülke","ümit","üniforma","ünite","ünlem","üretken","ürün","üslup","üstel","üstün","üşengeç","üşüme","ütopya","üvey","üzengi","üzgün","üzüm","vagon","vaka","vakfiye","vakıf","vakit","vakum","vapur","varil","varlık","varsayım","varyemez","vasıta","vasiyet","vatandaş","vazife","vazo","veciz","vefa","vehim","veliaht","veresiye","verimli","verkaç","vernik","vertigo","vesait","vesika","vestiyer","veznedar","vicdan","vilayet","virane","virgül","vişne","vites","vokal","volkan","vurma","vurucu","vücut","yabancı","yabgu","yağış","yağlı","yağmur","yakamoz","yakın","yaklaşık","yalçın","yalıtım","yaman","yanardağ","yangın","yanıt","yankı","yanlış","yansıma","yapay","yapboz","yapımcı","yaprak","yaratık","yarbay","yardım","yargıç","yarıçap","yasemin","yastık","yaşam","yatak","yatırım","yavru","yaygara","yayıncı","yayla","yazılım","yekpare","yekvücut","yelkovan","yelpaze","yemek","yemiş","yengeç","yeniçeri","yeraltı","yerküre","yerleşke","yeryüzü","yeşil","yetenek","yetkili","yığınak","yıkama","yılbaşı","yıldırım","yılkı","yılmaz","yırtıcı","yiğit","yoğurt","yokuş","yolcu","yoldaş","yolgeçen","yolkesen","yolüstü","yordam","yorgan","yorumcu","yosun","yöndeş","yönetim","yönlü","yöntem","yöresel","yörünge","yufka","yukarı","yumruk","yumurta","yuvarlak","yücelme","yükçeker","yüklem","yüksek","yürek","yürütme","yüzde","yüzeysel","yüzgeç","yüzüstü","yüzyıl","zabıta","zafer","zahmet","zambak","zaptiye","zarafet","zaruret","zeka","zekice","zemberek","zemin","zencefil","zeplin","zeytin","zıbın","zılgıt","zımbırtı","zımpara","zıpkın","zigon","zihinsel","zihniyet","zincir","zindan","zirzop","ziyaret","ziynet","zoraki","zorlu","zorunlu","züğürt","zümre"]import { encode, encodeInto, objectToTokens, rfc8949EncodeOptions } from './lib/encode.js'
import { decode, decodeFirst, Tokeniser, tokensToObject } from './lib/decode.js'
import { Tagged } from './lib/tagged.js'
import { Token, Type } from './lib/token.js'

/**
 * Export the types that were present in the original manual cborg.d.ts
 * @typedef {import('./interface.js').TagDecodeControl} TagDecodeControl
 * @typedef {import('./interface.js').TagDecoder} TagDecoder
 * There was originally just `TypeEncoder` so don't break types by renaming or not exporting
 * @typedef {import('./interface.js').OptionalTypeEncoder} TypeEncoder
 * @typedef {import('./interface.js').DecodeOptions} DecodeOptions
 * @typedef {import('./interface.js').EncodeOptions} EncodeOptions
 */

export {
  decode,
  decodeFirst,
  Tokeniser as Tokenizer,
  tokensToObject,
  encode,
  encodeInto,
  objectToTokens,
  rfc8949EncodeOptions,
  Tagged,
  Token,
  Type
}
/* globals BigInt */

import { Token, Type } from './token.js'
import { decodeErrPrefix, assertEnoughData } from './common.js'

export const uintBoundaries = [24, 256, 65536, 4294967296, BigInt('18446744073709551616')]

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number}
 */
export function readUint8 (data, offset, options) {
  assertEnoughData(data, offset, 1)
  const value = data[offset]
  if (options.strict === true && value < uintBoundaries[0]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  return value
}

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number}
 */
export function readUint16 (data, offset, options) {
  assertEnoughData(data, offset, 2)
  const value = (data[offset] << 8) | data[offset + 1]
  if (options.strict === true && value < uintBoundaries[1]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  return value
}

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number}
 */
export function readUint32 (data, offset, options) {
  assertEnoughData(data, offset, 4)
  const value = (data[offset] * 16777216 /* 2 ** 24 */) + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]
  if (options.strict === true && value < uintBoundaries[2]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  return value
}

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number|bigint}
 */
export function readUint64 (data, offset, options) {
  // assume BigInt, convert back to Number if within safe range
  assertEnoughData(data, offset, 8)
  const hi = (data[offset] * 16777216 /* 2 ** 24 */) + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]
  const lo = (data[offset + 4] * 16777216 /* 2 ** 24 */) + (data[offset + 5] << 16) + (data[offset + 6] << 8) + data[offset + 7]
  const value = (BigInt(hi) << BigInt(32)) + BigInt(lo)
  if (options.strict === true && value < uintBoundaries[3]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  if (value <= Number.MAX_SAFE_INTEGER) {
    return Number(value)
  }
  if (options.allowBigInt === true) {
    return value
  }
  throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`)
}

/* not required thanks to quick[] list
const oneByteTokens = new Array(24).fill(0).map((v, i) => new Token(Type.uint, i, 1))
export function decodeUintCompact (data, pos, minor, options) {
  return oneByteTokens[minor]
}
*/

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint8 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint8(data, pos + 1, options), 2)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint16 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint16(data, pos + 1, options), 3)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint32 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint32(data, pos + 1, options), 5)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint64 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint64(data, pos + 1, options), 9)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeUint (writer, token) {
  return encodeUintValue(writer, 0, token.value)
}

/**
 * @param {ByteWriter} writer
 * @param {number} major
 * @param {number|bigint} uint
 */
export function encodeUintValue (writer, major, uint) {
  if (uint < uintBoundaries[0]) {
    const nuint = Number(uint)
    // pack into one byte, minor=0, additional=value
    writer.push([major | nuint])
  } else if (uint < uintBoundaries[1]) {
    const nuint = Number(uint)
    // pack into two byte, minor=0, additional=24
    writer.push([major | 24, nuint])
  } else if (uint < uintBoundaries[2]) {
    const nuint = Number(uint)
    // pack into three byte, minor=0, additional=25
    writer.push([major | 25, nuint >>> 8, nuint & 0xff])
  } else if (uint < uintBoundaries[3]) {
    const nuint = Number(uint)
    // pack into five byte, minor=0, additional=26
    writer.push([major | 26, (nuint >>> 24) & 0xff, (nuint >>> 16) & 0xff, (nuint >>> 8) & 0xff, nuint & 0xff])
  } else {
    const buint = BigInt(uint)
    if (buint < uintBoundaries[4]) {
      // pack into nine byte, minor=0, additional=27
      const set = [major | 27, 0, 0, 0, 0, 0, 0, 0]
      // simulate bitwise above 32 bits
      let lo = Number(buint & BigInt(0xffffffff))
      let hi = Number(buint >> BigInt(32) & BigInt(0xffffffff))
      set[8] = lo & 0xff
      lo = lo >> 8
      set[7] = lo & 0xff
      lo = lo >> 8
      set[6] = lo & 0xff
      lo = lo >> 8
      set[5] = lo & 0xff
      set[4] = hi & 0xff
      hi = hi >> 8
      set[3] = hi & 0xff
      hi = hi >> 8
      set[2] = hi & 0xff
      hi = hi >> 8
      set[1] = hi & 0xff
      writer.push(set)
    } else {
      throw new Error(`${decodeErrPrefix} encountered BigInt larger than allowable range`)
    }
  }
}

/**
 * @param {Token} token
 * @returns {number}
 */
encodeUint.encodedSize = function encodedSize (token) {
  return encodeUintValue.encodedSize(token.value)
}

/**
 * @param {number} uint
 * @returns {number}
 */
encodeUintValue.encodedSize = function encodedSize (uint) {
  if (uint < uintBoundaries[0]) {
    return 1
  }
  if (uint < uintBoundaries[1]) {
    return 2
  }
  if (uint < uintBoundaries[2]) {
    return 3
  }
  if (uint < uintBoundaries[3]) {
    return 5
  }
  return 9
}

/**
 * @param {Token} tok1
 * @param {Token} tok2
 * @returns {number}
 */
encodeUint.compareTokens = function compareTokens (tok1, tok2) {
  return tok1.value < tok2.value ? -1 : tok1.value > tok2.value ? 1 : 0
}
/* eslint-env es2020 */

import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import { decodeErrPrefix } from './common.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint8 (data, pos, _minor, options) {
  return new Token(Type.negint, -1 - uint.readUint8(data, pos + 1, options), 2)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint16 (data, pos, _minor, options) {
  return new Token(Type.negint, -1 - uint.readUint16(data, pos + 1, options), 3)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint32 (data, pos, _minor, options) {
  return new Token(Type.negint, -1 - uint.readUint32(data, pos + 1, options), 5)
}

const neg1b = BigInt(-1)
const pos1b = BigInt(1)

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint64 (data, pos, _minor, options) {
  const int = uint.readUint64(data, pos + 1, options)
  if (typeof int !== 'bigint') {
    const value = -1 - int
    if (value >= Number.MIN_SAFE_INTEGER) {
      return new Token(Type.negint, value, 9)
    }
  }
  if (options.allowBigInt !== true) {
    throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`)
  }
  return new Token(Type.negint, neg1b - BigInt(int), 9)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeNegint (writer, token) {
  const negint = token.value
  const unsigned = (typeof negint === 'bigint' ? (negint * neg1b - pos1b) : (negint * -1 - 1))
  uint.encodeUintValue(writer, token.type.majorEncoded, unsigned)
}

/**
 * @param {Token} token
 * @returns {number}
 */
encodeNegint.encodedSize = function encodedSize (token) {
  const negint = token.value
  const unsigned = (typeof negint === 'bigint' ? (negint * neg1b - pos1b) : (negint * -1 - 1))
  // handled by quickEncode, we shouldn't get here but it's included for completeness
  if (unsigned < uint.uintBoundaries[0]) {
    return 1
  }
  if (unsigned < uint.uintBoundaries[1]) {
    return 2
  }
  if (unsigned < uint.uintBoundaries[2]) {
    return 3
  }
  if (unsigned < uint.uintBoundaries[3]) {
    return 5
  }
  return 9
}

/**
 * @param {Token} tok1
 * @param {Token} tok2
 * @returns {number}
 */
encodeNegint.compareTokens = function compareTokens (tok1, tok2) {
  // opposite of the uint comparison since we store the uint version in bytes
  return tok1.value < tok2.value ? 1 : tok1.value > tok2.value ? -1 : 0
}
import { Token, Type } from './token.js'
import { assertEnoughData, decodeErrPrefix } from './common.js'
import * as uint from './0uint.js'
import { compare, fromString } from './byte-utils.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} prefix
 * @param {number} length
 * @returns {Token}
 */
function toToken (data, pos, prefix, length) {
  assertEnoughData(data, pos, prefix + length)
  const buf = data.slice(pos + prefix, pos + prefix + length)
  return new Token(Type.bytes, buf, prefix + length)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeBytesCompact (data, pos, minor, _options) {
  return toToken(data, pos, 1, minor)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer bytes lengths not supported`)
  }
  return toToken(data, pos, 9, l)
}

/**
 * `encodedBytes` allows for caching when we do a byte version of a string
 * for key sorting purposes
 * @param {Token} token
 * @returns {Uint8Array}
 */
function tokenBytes (token) {
  if (token.encodedBytes === undefined) {
    token.encodedBytes = Type.equals(token.type, Type.string) ? fromString(token.value) : token.value
  }
  // @ts-ignore c'mon
  return token.encodedBytes
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeBytes (writer, token) {
  const bytes = tokenBytes(token)
  uint.encodeUintValue(writer, token.type.majorEncoded, bytes.length)
  writer.push(bytes)
}

/**
 * @param {Token} token
 * @returns {number}
 */
encodeBytes.encodedSize = function encodedSize (token) {
  const bytes = tokenBytes(token)
  return uint.encodeUintValue.encodedSize(bytes.length) + bytes.length
}

/**
 * @param {Token} tok1
 * @param {Token} tok2
 * @returns {number}
 */
encodeBytes.compareTokens = function compareTokens (tok1, tok2) {
  return compareBytes(tokenBytes(tok1), tokenBytes(tok2))
}

/**
 * @param {Uint8Array} b1
 * @param {Uint8Array} b2
 * @returns {number}
 */
export function compareBytes (b1, b2) {
  return b1.length < b2.length ? -1 : b1.length > b2.length ? 1 : compare(b1, b2)
}
import { Token, Type } from './token.js'
import { assertEnoughData, decodeErrPrefix } from './common.js'
import * as uint from './0uint.js'
import { encodeBytes } from './2bytes.js'

const textDecoder = new TextDecoder()

// Threshold for ASCII fast-path vs TextDecoder. Short ASCII strings (common for
// map keys) are faster to decode with a simple loop than TextDecoder overhead.
const ASCII_THRESHOLD = 32

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * Decode UTF-8 bytes to string. For short ASCII strings (common case for map keys),
 * a simple loop is faster than TextDecoder.
 * @param {Uint8Array} bytes
 * @param {number} start
 * @param {number} end
 * @returns {string}
 */
function toStr (bytes, start, end) {
  const len = end - start
  if (len < ASCII_THRESHOLD) {
    let str = ''
    for (let i = start; i < end; i++) {
      const c = bytes[i]
      if (c & 0x80) { // non-ASCII, fall back to TextDecoder
        return textDecoder.decode(bytes.subarray(start, end))
      }
      str += String.fromCharCode(c)
    }
    return str
  }
  return textDecoder.decode(bytes.subarray(start, end))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} prefix
 * @param {number} length
 * @param {DecodeOptions} options
 * @returns {Token}
 */
function toToken (data, pos, prefix, length, options) {
  const totLength = prefix + length
  assertEnoughData(data, pos, totLength)
  const tok = new Token(Type.string, toStr(data, pos + prefix, pos + totLength), totLength)
  if (options.retainStringBytes === true) {
    tok.byteValue = data.slice(pos + prefix, pos + totLength)
  }
  return tok
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeStringCompact (data, pos, minor, options) {
  return toToken(data, pos, 1, minor, options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options), options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options), options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options), options)
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer string lengths not supported`)
  }
  return toToken(data, pos, 9, l, options)
}

export const encodeString = encodeBytes
import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import { decodeErrPrefix } from './common.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} prefix
 * @param {number} length
 * @returns {Token}
 */
function toToken (_data, _pos, prefix, length) {
  return new Token(Type.array, length, prefix)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeArrayCompact (data, pos, minor, _options) {
  return toToken(data, pos, 1, minor)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer array lengths not supported`)
  }
  return toToken(data, pos, 9, l)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArrayIndefinite (data, pos, _minor, options) {
  if (options.allowIndefinite === false) {
    throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)
  }
  return toToken(data, pos, 1, Infinity)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeArray (writer, token) {
  uint.encodeUintValue(writer, Type.array.majorEncoded, token.value)
}

// using an array as a map key, are you sure about this? we can only sort
// by map length here, it's up to the encoder to decide to look deeper
encodeArray.compareTokens = uint.encodeUint.compareTokens

/**
 * @param {Token} token
 * @returns {number}
 */
encodeArray.encodedSize = function encodedSize (token) {
  return uint.encodeUintValue.encodedSize(token.value)
}
import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import { decodeErrPrefix } from './common.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} prefix
 * @param {number} length
 * @returns {Token}
 */
function toToken (_data, _pos, prefix, length) {
  return new Token(Type.map, length, prefix)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeMapCompact (data, pos, minor, _options) {
  return toToken(data, pos, 1, minor)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer map lengths not supported`)
  }
  return toToken(data, pos, 9, l)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMapIndefinite (data, pos, _minor, options) {
  if (options.allowIndefinite === false) {
    throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)
  }
  return toToken(data, pos, 1, Infinity)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeMap (writer, token) {
  uint.encodeUintValue(writer, Type.map.majorEncoded, token.value)
}

// using a map as a map key, are you sure about this? we can only sort
// by map length here, it's up to the encoder to decide to look deeper
encodeMap.compareTokens = uint.encodeUint.compareTokens

/**
 * @param {Token} token
 * @returns {number}
 */
encodeMap.encodedSize = function encodedSize (token) {
  return uint.encodeUintValue.encodedSize(token.value)
}
import { Token, Type } from './token.js'
import * as uint from './0uint.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeTagCompact (_data, _pos, minor, _options) {
  return new Token(Type.tag, minor, 1)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag8 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint8(data, pos + 1, options), 2)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag16 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint16(data, pos + 1, options), 3)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag32 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint32(data, pos + 1, options), 5)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag64 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint64(data, pos + 1, options), 9)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeTag (writer, token) {
  uint.encodeUintValue(writer, Type.tag.majorEncoded, token.value)
}

encodeTag.compareTokens = uint.encodeUint.compareTokens

/**
 * @param {Token} token
 * @returns {number}
 */
encodeTag.encodedSize = function encodedSize (token) {
  return uint.encodeUintValue.encodedSize(token.value)
}
// TODO: shift some of the bytes logic to bytes-utils so we can use Buffer
// where possible

import { Token, Type } from './token.js'
import { decodeErrPrefix } from './common.js'
import { encodeUint } from './0uint.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 * @typedef {import('../interface.js').EncodeOptions} EncodeOptions
 */

export const MINOR_FALSE = 20
export const MINOR_TRUE = 21
export const MINOR_NULL = 22
export const MINOR_UNDEFINED = 23

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUndefined (_data, _pos, _minor, options) {
  if (options.allowUndefined === false) {
    throw new Error(`${decodeErrPrefix} undefined values are not supported`)
  } else if (options.coerceUndefinedToNull === true) {
    return new Token(Type.null, null, 1)
  }
  return new Token(Type.undefined, undefined, 1)
}

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBreak (_data, _pos, _minor, options) {
  if (options.allowIndefinite === false) {
    throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)
  }
  return new Token(Type.break, undefined, 1)
}

/**
 * @param {number} value
 * @param {number} bytes
 * @param {DecodeOptions} options
 * @returns {Token}
 */
function createToken (value, bytes, options) {
  if (options) {
    if (options.allowNaN === false && Number.isNaN(value)) {
      throw new Error(`${decodeErrPrefix} NaN values are not supported`)
    }
    if (options.allowInfinity === false && (value === Infinity || value === -Infinity)) {
      throw new Error(`${decodeErrPrefix} Infinity values are not supported`)
    }
  }
  return new Token(Type.float, value, bytes)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeFloat16 (data, pos, _minor, options) {
  return createToken(readFloat16(data, pos + 1), 3, options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeFloat32 (data, pos, _minor, options) {
  return createToken(readFloat32(data, pos + 1), 5, options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeFloat64 (data, pos, _minor, options) {
  return createToken(readFloat64(data, pos + 1), 9, options)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 * @param {EncodeOptions} options
 */
export function encodeFloat (writer, token, options) {
  const float = token.value

  if (float === false) {
    writer.push([Type.float.majorEncoded | MINOR_FALSE])
  } else if (float === true) {
    writer.push([Type.float.majorEncoded | MINOR_TRUE])
  } else if (float === null) {
    writer.push([Type.float.majorEncoded | MINOR_NULL])
  } else if (float === undefined) {
    writer.push([Type.float.majorEncoded | MINOR_UNDEFINED])
  } else {
    let decoded
    let success = false
    if (!options || options.float64 !== true) {
      encodeFloat16(float)
      decoded = readFloat16(ui8a, 1)
      if (float === decoded || Number.isNaN(float)) {
        ui8a[0] = 0xf9
        writer.push(ui8a.slice(0, 3))
        success = true
      } else {
        encodeFloat32(float)
        decoded = readFloat32(ui8a, 1)
        if (float === decoded) {
          ui8a[0] = 0xfa
          writer.push(ui8a.slice(0, 5))
          success = true
        }
      }
    }
    if (!success) {
      encodeFloat64(float)
      decoded = readFloat64(ui8a, 1)
      ui8a[0] = 0xfb
      writer.push(ui8a.slice(0, 9))
    }
  }
}

/**
 * @param {Token} token
 * @param {EncodeOptions} options
 * @returns {number}
 */
encodeFloat.encodedSize = function encodedSize (token, options) {
  const float = token.value

  if (float === false || float === true || float === null || float === undefined) {
    return 1
  }

  if (!options || options.float64 !== true) {
    encodeFloat16(float)
    let decoded = readFloat16(ui8a, 1)
    if (float === decoded || Number.isNaN(float)) {
      return 3
    }
    encodeFloat32(float)
    decoded = readFloat32(ui8a, 1)
    if (float === decoded) {
      return 5
    }
  }
  return 9
}

const buffer = new ArrayBuffer(9)
const dataView = new DataView(buffer, 1)
const ui8a = new Uint8Array(buffer, 0)

/**
 * @param {number} inp
 */
function encodeFloat16 (inp) {
  if (inp === Infinity) {
    dataView.setUint16(0, 0x7c00, false)
  } else if (inp === -Infinity) {
    dataView.setUint16(0, 0xfc00, false)
  } else if (Number.isNaN(inp)) {
    dataView.setUint16(0, 0x7e00, false)
  } else {
    dataView.setFloat32(0, inp)
    const valu32 = dataView.getUint32(0)
    const exponent = (valu32 & 0x7f800000) >> 23
    const mantissa = valu32 & 0x7fffff

    if (exponent === 0xff) {
      // too big, Infinity, but this should be hard (impossible?) to trigger
      dataView.setUint16(0, 0x7c00, false)
    } else if (exponent === 0x00) {
      // 0.0, -0.0 and subnormals, shouldn't be possible to get here because 0.0 should be counted as an int
      // Use valu32 for sign bit since bitwise ops on floats lose -0 sign
      dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | (mantissa >> 13), false)
    } else { // standard numbers
      // chunks of logic here borrowed from https://github.com/PJK/libcbor/blob/c78f437182533e3efa8d963ff4b945bb635c2284/src/cbor/encoding.c#L127
      const logicalExponent = exponent - 127
      // Now we know that 2^exponent <= 0 logically
      if (logicalExponent < -24) {
        /* No unambiguous representation exists, this float is not a half float
          and is too small to be represented using a half, round off to zero.
          Consistent with the reference implementation. */
        // should be difficult (impossible?) to get here in JS
        dataView.setUint16(0, 0)
      } else if (logicalExponent < -14) {
        /* Offset the remaining decimal places by shifting the significand, the
          value is lost. This is an implementation decision that works around the
          absence of standard half-float in the language. */
        dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | /* sign bit */ (1 << (24 + logicalExponent)), false)
      } else {
        dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | ((logicalExponent + 15) << 10) | (mantissa >> 13), false)
      }
    }
  }
}

/**
 * @param {Uint8Array} ui8a
 * @param {number} pos
 * @returns {number}
 */
function readFloat16 (ui8a, pos) {
  if (ui8a.length - pos < 2) {
    throw new Error(`${decodeErrPrefix} not enough data for float16`)
  }

  const half = (ui8a[pos] << 8) + ui8a[pos + 1]
  if (half === 0x7c00) {
    return Infinity
  }
  if (half === 0xfc00) {
    return -Infinity
  }
  if (half === 0x7e00) {
    return NaN
  }
  const exp = (half >> 10) & 0x1f
  const mant = half & 0x3ff
  let val
  if (exp === 0) {
    val = mant * (2 ** -24)
  } else if (exp !== 31) {
    val = (mant + 1024) * (2 ** (exp - 25))
  } else {
    // may not be possible to get here
    val = mant === 0 ? Infinity : NaN
  }
  return (half & 0x8000) ? -val : val
}

/**
 * @param {number} inp
 */
function encodeFloat32 (inp) {
  dataView.setFloat32(0, inp, false)
}

/**
 * @param {Uint8Array} ui8a
 * @param {number} pos
 * @returns {number}
 */
function readFloat32 (ui8a, pos) {
  if (ui8a.length - pos < 4) {
    throw new Error(`${decodeErrPrefix} not enough data for float32`)
  }
  const offset = (ui8a.byteOffset || 0) + pos
  return new DataView(ui8a.buffer, offset, 4).getFloat32(0, false)
}

/**
 * @param {number} inp
 */
function encodeFloat64 (inp) {
  dataView.setFloat64(0, inp, false)
}

/**
 * @param {Uint8Array} ui8a
 * @param {number} pos
 * @returns {number}
 */
function readFloat64 (ui8a, pos) {
  if (ui8a.length - pos < 8) {
    throw new Error(`${decodeErrPrefix} not enough data for float64`)
  }
  const offset = (ui8a.byteOffset || 0) + pos
  return new DataView(ui8a.buffer, offset, 8).getFloat64(0, false)
}

/**
 * @param {Token} _tok1
 * @param {Token} _tok2
 * @returns {number}
 */
encodeFloat.compareTokens = encodeUint.compareTokens
/*
encodeFloat.compareTokens = function compareTokens (_tok1, _tok2) {
  return _tok1
  throw new Error(`${encodeErrPrefix} cannot use floats as map keys`)
}
*/
/**
 * Bl is a list of byte chunks, similar to https://github.com/rvagg/bl but for
 * writing rather than reading.
 * A Bl object accepts set() operations for individual bytes and copyTo() for
 * inserting byte arrays. These write operations don't automatically increment
 * the internal cursor so its "length" won't be changed. Instead, increment()
 * must be called to extend its length to cover the inserted data.
 * The toBytes() call will convert all internal memory to a single Uint8Array of
 * the correct length, truncating any data that is stored but hasn't been
 * included by an increment().
 * get() can retrieve a single byte.
 * All operations (except toBytes()) take an "offset" argument that will perform
 * the write at the offset _from the current cursor_. For most operations this
 * will be `0` to write at the current cursor position but it can be ahead of
 * the current cursor. Negative offsets probably work but are untested.
 */

// TODO: ipjs doesn't support this, only for test files: https://github.com/mikeal/ipjs/blob/master/src/package/testFile.js#L39
import { alloc, concat, slice } from './byte-utils.js'

// the ts-ignores in this file are almost all for the `Uint8Array|number[]` duality that exists
// for perf reasons. Consider better approaches to this or removing it entirely, it is quite
// risky because of some assumptions about small chunks === number[] and everything else === Uint8Array.

const defaultChunkSize = 256

export class Bl {
  /**
   * @param {number} [chunkSize]
   */
  constructor (chunkSize = defaultChunkSize) {
    this.chunkSize = chunkSize
    /** @type {number} */
    this.cursor = 0
    /** @type {number} */
    this.maxCursor = -1
    /** @type {(Uint8Array|number[])[]} */
    this.chunks = []
    // keep the first chunk around if we can to save allocations for future encodes
    /** @type {Uint8Array|number[]|null} */
    this._initReuseChunk = null
  }

  reset () {
    this.cursor = 0
    this.maxCursor = -1
    if (this.chunks.length) {
      this.chunks = []
    }
    if (this._initReuseChunk !== null) {
      this.chunks.push(this._initReuseChunk)
      this.maxCursor = this._initReuseChunk.length - 1
    }
  }

  /**
   * @param {Uint8Array|number[]} bytes
   */
  push (bytes) {
    let topChunk = this.chunks[this.chunks.length - 1]
    const newMax = this.cursor + bytes.length
    if (newMax <= this.maxCursor + 1) {
      // we have at least one chunk and we can fit these bytes into that chunk
      const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1
      // @ts-ignore
      topChunk.set(bytes, chunkPos)
    } else {
      // can't fit it in
      if (topChunk) {
        // trip the last chunk to `cursor` if we need to
        const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1
        if (chunkPos < topChunk.length) {
          // @ts-ignore
          this.chunks[this.chunks.length - 1] = topChunk.subarray(0, chunkPos)
          this.maxCursor = this.cursor - 1
        }
      }
      if (bytes.length < 64 && bytes.length < this.chunkSize) {
        // make a new chunk and copy the new one into it
        topChunk = alloc(this.chunkSize)
        this.chunks.push(topChunk)
        this.maxCursor += topChunk.length
        if (this._initReuseChunk === null) {
          this._initReuseChunk = topChunk
        }
        // @ts-ignore
        topChunk.set(bytes, 0)
      } else {
        // push the new bytes in as its own chunk
        this.chunks.push(bytes)
        this.maxCursor += bytes.length
      }
    }
    this.cursor += bytes.length
  }

  /**
   * @param {boolean} [reset]
   * @returns {Uint8Array}
   */
  toBytes (reset = false) {
    let byts
    if (this.chunks.length === 1) {
      const chunk = this.chunks[0]
      if (reset && this.cursor > chunk.length / 2) {
        // @ts-ignore
        byts = this.cursor === chunk.length ? chunk : chunk.subarray(0, this.cursor)
        this._initReuseChunk = null
        this.chunks = []
      } else {
        // @ts-ignore
        byts = slice(chunk, 0, this.cursor)
      }
    } else {
      // @ts-ignore
      byts = concat(this.chunks, this.cursor)
    }
    if (reset) {
      this.reset()
    }
    return byts
  }
}

/**
 * U8Bl is a buffer list that writes directly to a user-provided Uint8Array.
 * It provides the same interface as Bl but writes to a fixed destination.
 */
export class U8Bl {
  /**
   * @param {Uint8Array} dest
   */
  constructor (dest) {
    this.dest = dest
    /** @type {number} */
    this.cursor = 0
    // chunks is for interface compatibility with Bl - encode.js checks chunks.length
    // as a sanity check for pre-calculated sizes. For U8Bl this is always [dest].
    /** @type {Uint8Array[]} */
    this.chunks = [dest]
  }

  reset () {
    this.cursor = 0
  }

  /**
   * @param {Uint8Array|number[]} bytes
   */
  push (bytes) {
    if (this.cursor + bytes.length > this.dest.length) {
      throw new Error('write out of bounds, destination buffer is too small')
    }
    this.dest.set(bytes, this.cursor)
    this.cursor += bytes.length
  }

  /**
   * @param {boolean} [reset]
   * @returns {Uint8Array}
   */
  toBytes (reset = false) {
    const byts = this.dest.subarray(0, this.cursor)
    if (reset) {
      this.reset()
    }
    return byts
  }
}
// Use Uint8Array directly in the browser, use Buffer in Node.js but don't
// speak its name directly to avoid bundlers pulling in the `Buffer` polyfill

// @ts-ignore
export const useBuffer = globalThis.process &&
  // @ts-ignore
  !globalThis.process.browser &&
  // @ts-ignore
  globalThis.Buffer &&
  // @ts-ignore
  typeof globalThis.Buffer.isBuffer === 'function'

const textEncoder = new TextEncoder()

/**
 * @param {Uint8Array} buf
 * @returns {boolean}
 */
function isBuffer (buf) {
  // @ts-ignore
  return useBuffer && globalThis.Buffer.isBuffer(buf)
}

/**
 * @param {Uint8Array|number[]} buf
 * @returns {Uint8Array}
 */
export function asU8A (buf) {
  if (!(buf instanceof Uint8Array)) {
    return Uint8Array.from(buf)
  }
  return isBuffer(buf) ? new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength) : buf
}

// Threshold for manual UTF-8 encoding vs native methods.
// Node.js Buffer.from: crossover ~24 chars
// Browser TextEncoder: crossover ~200 chars
const FROM_STRING_THRESHOLD_BUFFER = 24
const FROM_STRING_THRESHOLD_TEXTENCODER = 200

export const fromString = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {string} string
     */
    (string) => {
      return string.length >= FROM_STRING_THRESHOLD_BUFFER
        ? // eslint-disable-line operator-linebreak
      // @ts-ignore
        globalThis.Buffer.from(string)
        : utf8ToBytes(string)
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {string} string
     */
    (string) => {
      return string.length >= FROM_STRING_THRESHOLD_TEXTENCODER ? textEncoder.encode(string) : utf8ToBytes(string)
    }

/**
 * Buffer variant not fast enough for what we need
 * @param {number[]} arr
 * @returns {Uint8Array}
 */
export const fromArray = (arr) => {
  return Uint8Array.from(arr)
}

export const slice = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} bytes
     * @param {number} start
     * @param {number} end
     */
    // Buffer.slice() returns a view, not a copy, so we need special handling
    (bytes, start, end) => {
      if (isBuffer(bytes)) {
        return new Uint8Array(bytes.subarray(start, end))
      }
      return bytes.slice(start, end)
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} bytes
     * @param {number} start
     * @param {number} end
     */
    (bytes, start, end) => {
      return bytes.slice(start, end)
    }

export const concat = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array[]} chunks
     * @param {number} length
     * @returns {Uint8Array}
     */
    (chunks, length) => {
      // might get a stray plain Array here
      chunks = chunks.map((c) => c instanceof Uint8Array
        ? c
        : // eslint-disable-line operator-linebreak
        // @ts-ignore
        globalThis.Buffer.from(c))
      // @ts-ignore
      return asU8A(globalThis.Buffer.concat(chunks, length))
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array[]} chunks
     * @param {number} length
     * @returns {Uint8Array}
     */
    (chunks, length) => {
      const out = new Uint8Array(length)
      let off = 0
      for (let b of chunks) {
        if (off + b.length > out.length) {
          // final chunk that's bigger than we need
          b = b.subarray(0, out.length - off)
        }
        out.set(b, off)
        off += b.length
      }
      return out
    }

export const alloc = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {number} size
     * @returns {Uint8Array}
     */
    (size) => {
      // we always write over the contents we expose so this should be safe
      // @ts-ignore
      return globalThis.Buffer.allocUnsafe(size)
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {number} size
     * @returns {Uint8Array}
     */
    (size) => {
      return new Uint8Array(size)
    }

export const toHex = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} d
     * @returns {string}
     */
    (d) => {
      if (typeof d === 'string') {
        return d
      }
      // @ts-ignore
      return globalThis.Buffer.from(toBytes(d)).toString('hex')
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} d
     * @returns {string}
     */
    (d) => {
      if (typeof d === 'string') {
        return d
      }
      // @ts-ignore not smart enough to figure this out
      return Array.prototype.reduce.call(toBytes(d), (p, c) => `${p}${c.toString(16).padStart(2, '0')}`, '')
    }

export const fromHex = useBuffer
  ? // eslint-disable-line operator-linebreak
  /**
   * @param {string|Uint8Array} hex
   * @returns {Uint8Array}
   */
    (hex) => {
      if (hex instanceof Uint8Array) {
        return hex
      }
      // @ts-ignore
      return globalThis.Buffer.from(hex, 'hex')
    }
  : // eslint-disable-line operator-linebreak
  /**
   * @param {string|Uint8Array} hex
   * @returns {Uint8Array}
   */
    (hex) => {
      if (hex instanceof Uint8Array) {
        return hex
      }
      if (!hex.length) {
        return new Uint8Array(0)
      }
      return new Uint8Array(hex.split('')
        .map((/** @type {string} */ c, /** @type {number} */ i, /** @type {string[]} */ d) => i % 2 === 0 ? `0x${c}${d[i + 1]}` : '')
        .filter(Boolean)
        .map((/** @type {string} */ e) => parseInt(e, 16)))
    }

/**
 * @param {Uint8Array|ArrayBuffer|ArrayBufferView} obj
 * @returns {Uint8Array}
 */
function toBytes (obj) {
  if (obj instanceof Uint8Array && obj.constructor.name === 'Uint8Array') {
    return obj
  }
  if (obj instanceof ArrayBuffer) {
    return new Uint8Array(obj)
  }
  if (ArrayBuffer.isView(obj)) {
    return new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength)
  }
  throw new Error('Unknown type, must be binary type')
}

/**
 * @param {Uint8Array} b1
 * @param {Uint8Array} b2
 * @returns {number}
 */
export function compare (b1, b2) {
  if (isBuffer(b1) && isBuffer(b2)) {
    // probably not possible to get here in the current API
    // @ts-ignore Buffer
    return b1.compare(b2)
  }
  for (let i = 0; i < b1.length; i++) {
    if (b1[i] === b2[i]) {
      continue
    }
    return b1[i] < b2[i] ? -1 : 1
  }
  return 0
}

// The below code is taken from https://github.com/google/closure-library/blob/8598d87242af59aac233270742c8984e2b2bdbe0/closure/goog/crypt/crypt.js#L117-L143
// Licensed Apache-2.0.

/**
 * @param {string} str
 * @returns {number[]}
 */
function utf8ToBytes (str) {
  const out = []
  let p = 0
  for (let i = 0; i < str.length; i++) {
    let c = str.charCodeAt(i)
    if (c < 128) {
      out[p++] = c
    } else if (c < 2048) {
      out[p++] = (c >> 6) | 192
      out[p++] = (c & 63) | 128
    } else if (
      ((c & 0xFC00) === 0xD800) && (i + 1) < str.length &&
      ((str.charCodeAt(i + 1) & 0xFC00) === 0xDC00)) {
      // Surrogate Pair
      c = 0x10000 + ((c & 0x03FF) << 10) + (str.charCodeAt(++i) & 0x03FF)
      out[p++] = (c >> 18) | 240
      out[p++] = ((c >> 12) & 63) | 128
      out[p++] = ((c >> 6) & 63) | 128
      out[p++] = (c & 63) | 128
    } else {
      if ((c >= 0xD800) && (c <= 0xDFFF)) {
        c = 0xFFFD // Unpaired Surrogate
      }
      out[p++] = (c >> 12) | 224
      out[p++] = ((c >> 6) & 63) | 128
      out[p++] = (c & 63) | 128
    }
  }
  return out
}

// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
const MAX_ARGUMENTS_LENGTH = 0x1000

/**
 * @param {number[]} codePoints
 * @returns {string}
 */
export function decodeCodePointsArray (codePoints) {
  const len = codePoints.length
  if (len <= MAX_ARGUMENTS_LENGTH) {
    return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  }
  // Decode in chunks to avoid "call stack size exceeded".
  let res = ''
  let i = 0
  while (i < len) {
    res += String.fromCharCode.apply(
      String,
      codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
    )
  }
  return res
}
const decodeErrPrefix = 'CBOR decode error:'
const encodeErrPrefix = 'CBOR encode error:'

const uintMinorPrefixBytes = []
uintMinorPrefixBytes[23] = 1
uintMinorPrefixBytes[24] = 2
uintMinorPrefixBytes[25] = 3
uintMinorPrefixBytes[26] = 5
uintMinorPrefixBytes[27] = 9

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} need
 */
function assertEnoughData (data, pos, need) {
  if (data.length - pos < need) {
    throw new Error(`${decodeErrPrefix} not enough data for type`)
  }
}

export {
  decodeErrPrefix,
  encodeErrPrefix,
  uintMinorPrefixBytes,
  assertEnoughData
}
import { decodeErrPrefix } from './common.js'
import { Type } from './token.js'
import { jump, quick } from './jump.js'
import { asU8A } from './byte-utils.js'

/**
 * @typedef {import('./token.js').Token} Token
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 * @typedef {import('../interface.js').DecodeTokenizer} DecodeTokenizer
 * @typedef {import('../interface.js').TagDecodeControl} TagDecodeControl
 */

const defaultDecodeOptions = {
  strict: false,
  allowIndefinite: true,
  allowUndefined: true,
  allowBigInt: true
}

/**
 * @implements {DecodeTokenizer}
 */
class Tokeniser {
  /**
   * @param {Uint8Array} data
   * @param {DecodeOptions} options
   */
  constructor (data, options = {}) {
    this._pos = 0
    this.data = data
    this.options = options
  }

  pos () {
    return this._pos
  }

  done () {
    return this._pos >= this.data.length
  }

  next () {
    const byt = this.data[this._pos]
    let token = quick[byt]
    if (token === undefined) {
      const decoder = jump[byt]
      // if we're here then there's something wrong with our jump or quick lists!
      if (!decoder) {
        throw new Error(`${decodeErrPrefix} no decoder for major type ${byt >>> 5} (byte 0x${byt.toString(16).padStart(2, '0')})`)
      }
      const minor = byt & 31
      token = decoder(this.data, this._pos, minor, this.options)
    }
    // @ts-ignore we get to assume encodedLength is set (crossing fingers slightly)
    this._pos += token.encodedLength
    return token
  }
}

const DONE = Symbol.for('DONE')
const BREAK = Symbol.for('BREAK')

/**
 * @param {Token} token
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {any|BREAK|DONE}
 */
function tokenToArray (token, tokeniser, options) {
  const arr = []
  for (let i = 0; i < token.value; i++) {
    const value = tokensToObject(tokeniser, options)
    if (value === BREAK) {
      if (token.value === Infinity) {
        // normal end to indefinite length array
        break
      }
      throw new Error(`${decodeErrPrefix} got unexpected break to lengthed array`)
    }
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} found array but not enough entries (got ${i}, expected ${token.value})`)
    }
    arr[i] = value
  }
  return arr
}

/**
 * @param {Token} token
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {any|BREAK|DONE}
 */
function tokenToMap (token, tokeniser, options) {
  const useMaps = options.useMaps === true
  const rejectDuplicateMapKeys = options.rejectDuplicateMapKeys === true
  const obj = useMaps ? undefined : {}
  const m = useMaps ? new Map() : undefined
  for (let i = 0; i < token.value; i++) {
    const key = tokensToObject(tokeniser, options)
    if (key === BREAK) {
      if (token.value === Infinity) {
        // normal end to indefinite length map
        break
      }
      throw new Error(`${decodeErrPrefix} got unexpected break to lengthed map`)
    }
    if (key === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no key], expected ${token.value})`)
    }
    if (!useMaps && typeof key !== 'string') {
      throw new Error(`${decodeErrPrefix} non-string keys not supported (got ${typeof key})`)
    }
    if (rejectDuplicateMapKeys) {
      // @ts-ignore
      if ((useMaps && m.has(key)) || (!useMaps && Object.hasOwn(obj, key))) {
        throw new Error(`${decodeErrPrefix} found repeat map key "${key}"`)
      }
    }
    const value = tokensToObject(tokeniser, options)
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no value], expected ${token.value})`)
    }
    if (useMaps) {
      // @ts-ignore TODO reconsider this .. maybe needs to be strict about key types
      m.set(key, value)
    } else {
      // @ts-ignore TODO reconsider this .. maybe needs to be strict about key types
      obj[key] = value
    }
  }
  // @ts-ignore c'mon man
  return useMaps ? m : obj
}

/**
 * Generator that yields [key, value] entries from a CBOR map token.
 * Used by tag decoders that need to preserve key types (e.g., Tag 259 Map).
 * @param {Token} token - The map token
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {Generator<[any, any], void, unknown>}
 */
function * tokenToMapEntries (token, tokeniser, options) {
  for (let i = 0; i < token.value; i++) {
    const key = tokensToObject(tokeniser, options)
    if (key === BREAK) {
      if (token.value === Infinity) {
        // normal end to indefinite length map
        break
      }
      throw new Error(`${decodeErrPrefix} got unexpected break to lengthed map`)
    }
    if (key === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no key], expected ${token.value})`)
    }
    const value = tokensToObject(tokeniser, options)
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no value], expected ${token.value})`)
    }
    yield [key, value]
  }
}

/**
 * Creates a TagDecodeControl object for tag decoders.
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {TagDecodeControl}
 */
function createTagDecodeControl (tokeniser, options) {
  let called = false

  /**
   * @type {TagDecodeControl}
   */
  const decode = function () {
    if (called) {
      throw new Error(`${decodeErrPrefix} tag decode() may only be called once`)
    }
    called = true
    const value = tokensToObject(tokeniser, options)
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} tag content missing`)
    }
    if (value === BREAK) {
      throw new Error(`${decodeErrPrefix} got unexpected break in tag content`)
    }
    return value
  }

  decode.entries = function () {
    if (called) {
      throw new Error(`${decodeErrPrefix} tag decode() may only be called once`)
    }
    called = true

    // Get the next token and ensure it's a map
    const token = tokeniser.next()
    if (!Type.equals(token.type, Type.map)) {
      throw new Error(`${decodeErrPrefix} entries() requires map content, got ${token.type.name}`)
    }

    // Collect all entries into an array (ensures full content consumption)
    const entries = []
    for (const entry of tokenToMapEntries(token, tokeniser, options)) {
      entries.push(entry)
    }
    return entries
  }

  // For internal tracking
  Object.defineProperty(decode, '_called', {
    get () { return called },
    enumerable: false
  })

  return decode
}

/**
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {any|BREAK|DONE}
 */
function tokensToObject (tokeniser, options) {
  // should we support array as an argument?
  // check for tokenIter[Symbol.iterator] and replace tokenIter with what that returns?
  if (tokeniser.done()) {
    return DONE
  }

  const token = tokeniser.next()

  if (Type.equals(token.type, Type.break)) {
    return BREAK
  }

  if (token.type.terminal) {
    return token.value
  }

  if (Type.equals(token.type, Type.array)) {
    return tokenToArray(token, tokeniser, options)
  }

  if (Type.equals(token.type, Type.map)) {
    return tokenToMap(token, tokeniser, options)
  }

  if (Type.equals(token.type, Type.tag)) {
    if (options.tags && typeof options.tags[token.value] === 'function') {
      const decodeControl = createTagDecodeControl(tokeniser, options)
      const result = options.tags[token.value](decodeControl)
      if (!decodeControl._called) {
        throw new Error(`${decodeErrPrefix} tag decoder must call decode() or entries()`)
      }
      return result
    }
    throw new Error(`${decodeErrPrefix} tag not supported (${token.value})`)
  }
  throw new Error('unsupported')
}

/**
 * @param {Uint8Array} data
 * @param {DecodeOptions} [options]
 * @returns {[any, Uint8Array]}
 */
function decodeFirst (data, options) {
  if (!(data instanceof Uint8Array)) {
    throw new Error(`${decodeErrPrefix} data to decode must be a Uint8Array`)
  }
  options = Object.assign({}, defaultDecodeOptions, options)
  // Convert Buffer to plain Uint8Array for faster slicing in decode path
  const u8aData = asU8A(data)
  const tokeniser = options.tokenizer || new Tokeniser(u8aData, options)
  const decoded = tokensToObject(tokeniser, options)
  if (decoded === DONE) {
    throw new Error(`${decodeErrPrefix} did not find any content to decode`)
  }
  if (decoded === BREAK) {
    throw new Error(`${decodeErrPrefix} got unexpected break`)
  }
  return [decoded, data.subarray(tokeniser.pos())]
}

/**
 * @param {Uint8Array} data
 * @param {DecodeOptions} [options]
 * @returns {any}
 */
function decode (data, options) {
  const [decoded, remainder] = decodeFirst(data, options)
  if (remainder.length > 0) {
    throw new Error(`${decodeErrPrefix} too many terminals, data makes no sense`)
  }
  return decoded
}

export { Tokeniser, tokensToObject, decode, decodeFirst }
import { is } from './is.js'
import { Token, Type } from './token.js'
import { Bl, U8Bl } from './bl.js'
import { encodeErrPrefix } from './common.js'
import { quickEncodeToken } from './jump.js'
import { asU8A, compare, fromString } from './byte-utils.js'

import { encodeUint, encodeUintValue } from './0uint.js'
import { encodeNegint } from './1negint.js'
import { encodeBytes } from './2bytes.js'
import { encodeString } from './3string.js'
import { encodeArray } from './4array.js'
import { encodeMap } from './5map.js'
import { encodeTag } from './6tag.js'
import { encodeFloat, MINOR_FALSE, MINOR_TRUE, MINOR_NULL, MINOR_UNDEFINED } from './7float.js'

/**
 * @typedef {import('../interface.js').EncodeOptions} EncodeOptions
 * @typedef {import('../interface.js').OptionalTypeEncoder} OptionalTypeEncoder
 * @typedef {import('../interface.js').Reference} Reference
 * @typedef {import('../interface.js').StrictTypeEncoder} StrictTypeEncoder
 * @typedef {import('../interface.js').TokenTypeEncoder} TokenTypeEncoder
 * @typedef {import('../interface.js').TokenOrNestedTokens} TokenOrNestedTokens
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 */

/** @type {EncodeOptions} */
const defaultEncodeOptions = {
  float64: false,
  mapSorter,
  quickEncodeToken
}

/** @type {EncodeOptions} */
export const rfc8949EncodeOptions = Object.freeze({
  mapSorter: rfc8949MapSorter,
  quickEncodeToken
})

/** @returns {TokenTypeEncoder[]} */
export function makeCborEncoders () {
  const encoders = []
  encoders[Type.uint.major] = encodeUint
  encoders[Type.negint.major] = encodeNegint
  encoders[Type.bytes.major] = encodeBytes
  encoders[Type.string.major] = encodeString
  encoders[Type.array.major] = encodeArray
  encoders[Type.map.major] = encodeMap
  encoders[Type.tag.major] = encodeTag
  encoders[Type.float.major] = encodeFloat
  return encoders
}

const cborEncoders = makeCborEncoders()

const defaultWriter = new Bl()

/** @implements {Reference} */
class Ref {
  /**
   * @param {object|any[]} obj
   * @param {Reference|undefined} parent
   */
  constructor (obj, parent) {
    this.obj = obj
    this.parent = parent
  }

  /**
   * @param {object|any[]} obj
   * @returns {boolean}
   */
  includes (obj) {
    /** @type {Reference|undefined} */
    let p = this
    do {
      if (p.obj === obj) {
        return true
      }
    } while (p = p.parent) // eslint-disable-line
    return false
  }

  /**
   * @param {Reference|undefined} stack
   * @param {object|any[]} obj
   * @returns {Reference}
   */
  static createCheck (stack, obj) {
    if (stack && stack.includes(obj)) {
      throw new Error(`${encodeErrPrefix} object contains circular references`)
    }
    return new Ref(obj, stack)
  }
}

const simpleTokens = {
  null: new Token(Type.null, null),
  undefined: new Token(Type.undefined, undefined),
  true: new Token(Type.true, true),
  false: new Token(Type.false, false),
  emptyArray: new Token(Type.array, 0),
  emptyMap: new Token(Type.map, 0)
}

/** @type {{[typeName: string]: StrictTypeEncoder}} */
const typeEncoders = {
  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  number (obj, _typ, _options, _refStack) {
    if (!Number.isInteger(obj) || !Number.isSafeInteger(obj)) {
      return new Token(Type.float, obj)
    } else if (obj >= 0) {
      return new Token(Type.uint, obj)
    } else {
      return new Token(Type.negint, obj)
    }
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  bigint (obj, _typ, _options, _refStack) {
    if (obj >= BigInt(0)) {
      return new Token(Type.uint, obj)
    } else {
      return new Token(Type.negint, obj)
    }
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  Uint8Array (obj, _typ, _options, _refStack) {
    return new Token(Type.bytes, obj)
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  string (obj, _typ, _options, _refStack) {
    return new Token(Type.string, obj)
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  boolean (obj, _typ, _options, _refStack) {
    return obj ? simpleTokens.true : simpleTokens.false
  },

  /**
   * @param {any} _obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  null (_obj, _typ, _options, _refStack) {
    return simpleTokens.null
  },

  /**
   * @param {any} _obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  undefined (_obj, _typ, _options, _refStack) {
    return simpleTokens.undefined
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  ArrayBuffer (obj, _typ, _options, _refStack) {
    return new Token(Type.bytes, new Uint8Array(obj))
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  DataView (obj, _typ, _options, _refStack) {
    return new Token(Type.bytes, new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength))
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} options
   * @param {Reference} [refStack]
   * @returns {TokenOrNestedTokens}
   */
  Array (obj, _typ, options, refStack) {
    if (!obj.length) {
      if (options.addBreakTokens === true) {
        return [simpleTokens.emptyArray, new Token(Type.break)]
      }
      return simpleTokens.emptyArray
    }
    refStack = Ref.createCheck(refStack, obj)
    const entries = []
    let i = 0
    for (const e of obj) {
      entries[i++] = objectToTokens(e, options, refStack)
    }
    if (options.addBreakTokens) {
      return [new Token(Type.array, obj.length), entries, new Token(Type.break)]
    }
    return [new Token(Type.array, obj.length), entries]
  },

  /**
   * @param {any} obj
   * @param {string} typ
   * @param {EncodeOptions} options
   * @param {Reference} [refStack]
   * @returns {TokenOrNestedTokens}
   */
  Object (obj, typ, options, refStack) {
    // could be an Object or a Map
    const isMap = typ !== 'Object'
    // it's slightly quicker to use Object.keys() than Object.entries()
    const keys = isMap ? obj.keys() : Object.keys(obj)
    const maxLength = isMap ? obj.size : keys.length

    /** @type {undefined | [TokenOrNestedTokens, TokenOrNestedTokens][]} */
    let entries

    if (maxLength) {
      // Pre-allocate the array with the expected size
      entries = new Array(maxLength)
      refStack = Ref.createCheck(refStack, obj)
      const skipUndefined = !isMap && options.ignoreUndefinedProperties

      let i = 0
      for (const key of keys) {
        const value = isMap ? obj.get(key) : obj[key]
        if (skipUndefined && value === undefined) {
          continue
        }
        entries[i++] = [
          objectToTokens(key, options, refStack),
          objectToTokens(value, options, refStack)
        ]
      }

      // Truncate only if properties were skipped
      if (i < maxLength) {
        entries.length = i
      }
    }

    if (!entries?.length) {
      if (options.addBreakTokens === true) {
        return [simpleTokens.emptyMap, new Token(Type.break)]
      }
      return simpleTokens.emptyMap
    }

    sortMapEntries(entries, options)
    if (options.addBreakTokens) {
      return [new Token(Type.map, entries.length), entries, new Token(Type.break)]
    }
    return [new Token(Type.map, entries.length), entries]
  },

  /**
   * Encode a `Tagged` wrapper as a CBOR tag header followed by the encoded
   * form of the wrapped value. The value is recursively tokenised through
   * `objectToTokens()` so any registered `typeEncoders` apply to it.
   *
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} options
   * @param {Reference} [refStack]
   * @returns {TokenOrNestedTokens}
   */
  Tagged (obj, _typ, options, refStack) {
    return [
      new Token(Type.tag, obj.tag),
      objectToTokens(obj.value, options, refStack)
    ]
  }
}

typeEncoders.Map = typeEncoders.Object
typeEncoders.Buffer = typeEncoders.Uint8Array
for (const typ of 'Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64'.split(' ')) {
  typeEncoders[`${typ}Array`] = typeEncoders.DataView
}

/**
 * @param {any} obj
 * @param {EncodeOptions} [options]
 * @param {Reference} [refStack]
 * @returns {TokenOrNestedTokens}
 */
function objectToTokens (obj, options = {}, refStack) {
  const typ = is(obj)
  const customTypeEncoder = (options && options.typeEncoders && /** @type {OptionalTypeEncoder} */ options.typeEncoders[typ]) || typeEncoders[typ]
  if (typeof customTypeEncoder === 'function') {
    const tokens = customTypeEncoder(obj, typ, options, refStack)
    if (tokens != null) {
      return tokens
    }
  }
  const typeEncoder = typeEncoders[typ]
  if (!typeEncoder) {
    throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`)
  }
  return typeEncoder(obj, typ, options, refStack)
}

/*
CBOR key sorting is a mess.

The canonicalisation recommendation from https://tools.ietf.org/html/rfc7049#section-3.9
includes the wording:

> The keys in every map must be sorted lowest value to highest.
> Sorting is performed on the bytes of the representation of the key
> data items without paying attention to the 3/5 bit splitting for
> major types.
> ...
>  *  If two keys have different lengths, the shorter one sorts
      earlier;
>  *  If two keys have the same length, the one with the lower value
      in (byte-wise) lexical order sorts earlier.

1. It is not clear what "bytes of the representation of the key" means: is it
   the CBOR representation, or the binary representation of the object itself?
   Consider the int and uint difference here.
2. It is not clear what "without paying attention to" means: do we include it
   and compare on that? Or do we omit the special prefix byte, (mostly) treating
   the key in its plain binary representation form.

The FIDO 2.0: Client To Authenticator Protocol spec takes the original CBOR
wording and clarifies it according to their understanding.
https://fidoalliance.org/specs/fido-v2.0-rd-20170927/fido-client-to-authenticator-protocol-v2.0-rd-20170927.html#message-encoding

> The keys in every map must be sorted lowest value to highest. Sorting is
> performed on the bytes of the representation of the key data items without
> paying attention to the 3/5 bit splitting for major types. The sorting rules
> are:
>  * If the major types are different, the one with the lower value in numerical
>    order sorts earlier.
>  * If two keys have different lengths, the shorter one sorts earlier;
>  * If two keys have the same length, the one with the lower value in
>    (byte-wise) lexical order sorts earlier.

Some other implementations, such as borc, do a full encode then do a
length-first, byte-wise-second comparison:
https://github.com/dignifiedquire/borc/blob/b6bae8b0bcde7c3976b0f0f0957208095c392a36/src/encoder.js#L358
https://github.com/dignifiedquire/borc/blob/b6bae8b0bcde7c3976b0f0f0957208095c392a36/src/utils.js#L143-L151

This has the benefit of being able to easily handle arbitrary keys, including
complex types (maps and arrays).

We'll opt for the FIDO approach, since it affords some efficies since we don't
need a full encode of each key to determine order and can defer to the types
to determine how to most efficiently order their values (i.e. int and uint
ordering can be done on the numbers, no need for byte-wise, for example).

Recommendation: stick to single key types or you'll get into trouble, and prefer
string keys because it's much simpler that way.
*/

/**
 * @param {TokenOrNestedTokens[]} entries
 * @param {EncodeOptions} options
 */
function sortMapEntries (entries, options) {
  if (options.mapSorter) {
    entries.sort(options.mapSorter)
  }
}

/**
 * @param {(Token|Token[])[]} e1
 * @param {(Token|Token[])[]} e2
 * @returns {number}
 */
function mapSorter (e1, e2) {
  // the key position ([0]) could have a single token or an array
  // almost always it'll be a single token but complex key might get involved
  const keyToken1 = Array.isArray(e1[0]) ? e1[0][0] : e1[0]
  const keyToken2 = Array.isArray(e2[0]) ? e2[0][0] : e2[0]

  // different key types
  if (keyToken1.type !== keyToken2.type) {
    return keyToken1.type.compare(keyToken2.type)
  }

  const major = keyToken1.type.major
  // TODO: handle case where cmp === 0 but there are more keyToken e. complex type)
  const tcmp = cborEncoders[major].compareTokens(keyToken1, keyToken2)
  if (tcmp === 0) {
    // duplicate key or complex type where the first token matched,
    // i.e. a map or array and we're only comparing the opening token
    console.warn('WARNING: complex key types used, CBOR key sorting guarantees are gone')
  }
  return tcmp
}

/**
 * @typedef {Token & { _keyBytes?: Uint8Array }} TokenEx
 *
 * @param {(Token|Token[])[]} e1
 * @param {(Token|Token[])[]} e2
 * @returns {number}
 */
function rfc8949MapSorter (e1, e2) {
  if (e1[0] instanceof Token && e2[0] instanceof Token) {
    const t1 = /** @type {TokenEx} */ (e1[0])
    const t2 = /** @type {TokenEx} */ (e2[0])

    if (!t1._keyBytes) {
      t1._keyBytes = encodeRfc8949(t1.value)
    }

    if (!t2._keyBytes) {
      t2._keyBytes = encodeRfc8949(t2.value)
    }

    return compare(t1._keyBytes, t2._keyBytes)
  }

  throw new Error('rfc8949MapSorter: complex key types are not supported yet')
}

/**
 * @param {any} data
 * @returns {Uint8Array}
 */
function encodeRfc8949 (data) {
  return encodeCustom(data, cborEncoders, rfc8949EncodeOptions)
}

/**
 * @param {ByteWriter} writer
 * @param {TokenOrNestedTokens} tokens
 * @param {TokenTypeEncoder[]} encoders
 * @param {EncodeOptions} options
 */
function tokensToEncoded (writer, tokens, encoders, options) {
  if (Array.isArray(tokens)) {
    for (const token of tokens) {
      tokensToEncoded(writer, token, encoders, options)
    }
  } else {
    encoders[tokens.type.major](writer, tokens, options)
  }
}

// CBOR major type prefixes, cached from Type for hot path performance
const MAJOR_UINT = Type.uint.majorEncoded
const MAJOR_NEGINT = Type.negint.majorEncoded
const MAJOR_BYTES = Type.bytes.majorEncoded
const MAJOR_STRING = Type.string.majorEncoded
const MAJOR_ARRAY = Type.array.majorEncoded

// Simple value bytes (CBOR major type 7 + minor value)
const SIMPLE_FALSE = Type.float.majorEncoded | MINOR_FALSE
const SIMPLE_TRUE = Type.float.majorEncoded | MINOR_TRUE
const SIMPLE_NULL = Type.float.majorEncoded | MINOR_NULL
const SIMPLE_UNDEFINED = Type.float.majorEncoded | MINOR_UNDEFINED

const neg1b = BigInt(-1)
const pos1b = BigInt(1)

/**
 * Check if direct encoding can be used for the given options.
 * Direct encoding bypasses token creation for most values.
 * @param {EncodeOptions} options
 * @returns {boolean}
 */
function canDirectEncode (options) {
  // Cannot use direct encode with addBreakTokens (needs special break token handling).
  // Direct encode checks typeEncoders per-value, falling back to tokens as needed.
  // Maps fall back to token-based encoding for efficient key sorting.
  return options.addBreakTokens !== true
}

/**
 * Direct encode a value to the writer, bypassing token creation for most types.
 * Falls back to token-based encoding for custom type encoders.
 * @param {ByteWriter} writer
 * @param {any} data
 * @param {EncodeOptions} options
 * @param {Reference|undefined} refStack
 */
function directEncode (writer, data, options, refStack) {
  const typ = is(data)

  // Check for custom encoder for THIS specific type
  const customEncoder = options.typeEncoders && options.typeEncoders[typ]
  if (customEncoder) {
    const tokens = customEncoder(data, typ, options, refStack)
    if (tokens != null) {
      // Custom encoder returned tokens, serialize immediately
      tokensToEncoded(writer, tokens, cborEncoders, options)
      return
    }
    // Custom encoder returned null, fall through to default handling
  }

  // Direct encode based on type
  switch (typ) {
    case 'null':
      writer.push([SIMPLE_NULL])
      return

    case 'undefined':
      writer.push([SIMPLE_UNDEFINED])
      return

    case 'boolean':
      writer.push([data ? SIMPLE_TRUE : SIMPLE_FALSE])
      return

    case 'number':
      if (!Number.isInteger(data) || !Number.isSafeInteger(data)) {
        // Float, use token encoder for complex float encoding
        encodeFloat(writer, new Token(Type.float, data), options)
      } else if (data >= 0) {
        encodeUintValue(writer, MAJOR_UINT, data)
      } else {
        // Negative integer
        encodeUintValue(writer, MAJOR_NEGINT, data * -1 - 1)
      }
      return

    case 'bigint':
      if (data >= BigInt(0)) {
        encodeUintValue(writer, MAJOR_UINT, data)
      } else {
        encodeUintValue(writer, MAJOR_NEGINT, data * neg1b - pos1b)
      }
      return

    case 'string': {
      const bytes = fromString(data)
      encodeUintValue(writer, MAJOR_STRING, bytes.length)
      writer.push(bytes)
      return
    }

    case 'Uint8Array':
      encodeUintValue(writer, MAJOR_BYTES, data.length)
      writer.push(data)
      return

    case 'Array':
      if (!data.length) {
        writer.push([MAJOR_ARRAY]) // Empty array: 0x80
        return
      }
      refStack = Ref.createCheck(refStack, data)
      encodeUintValue(writer, MAJOR_ARRAY, data.length)
      for (const elem of data) {
        directEncode(writer, elem, options, refStack)
      }
      return

    case 'Object':
    case 'Map':
      // Maps require key sorting, use token-based encoding for efficiency
      // (pre-encoding all keys for sorting is expensive)
      {
        const tokens = typeEncoders.Object(data, typ, options, refStack)
        tokensToEncoded(writer, tokens, cborEncoders, options)
      }
      return

    default:
    // Fall back to token-based encoding for other types (DataView, TypedArrays, etc.)
    {
      const typeEncoder = typeEncoders[typ]
      if (!typeEncoder) {
        throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`)
      }
      const tokens = typeEncoder(data, typ, options, refStack)
      tokensToEncoded(writer, tokens, cborEncoders, options)
    }
  }
}

/**
 * @param {any} data
 * @param {TokenTypeEncoder[]} encoders
 * @param {EncodeOptions} options
 * @param {Uint8Array} [destination]
 * @returns {Uint8Array}
 */
function encodeCustom (data, encoders, options, destination) {
  // arg ordering is different to encodeInto for backward compatibility
  const hasDest = destination instanceof Uint8Array
  let writeTo = hasDest ? new U8Bl(destination) : defaultWriter

  const tokens = objectToTokens(data, options)
  if (!Array.isArray(tokens) && options.quickEncodeToken) {
    const quickBytes = options.quickEncodeToken(tokens)
    if (quickBytes) {
      if (hasDest) {
        // Copy quick bytes into destination buffer
        writeTo.push(quickBytes)
        return writeTo.toBytes()
      }
      return quickBytes
    }
    const encoder = encoders[tokens.type.major]
    if (encoder.encodedSize) {
      const size = encoder.encodedSize(tokens, options)
      if (!hasDest) {
        writeTo = new Bl(size)
      }
      encoder(writeTo, tokens, options)
      // this would be a problem with encodedSize() functions
      if (writeTo.chunks.length !== 1) {
        throw new Error(`Unexpected error: pre-calculated length for ${tokens} was wrong`)
      }
      return hasDest ? writeTo.toBytes() : asU8A(writeTo.chunks[0])
    }
  }
  writeTo.reset()
  tokensToEncoded(writeTo, tokens, encoders, options)
  return writeTo.toBytes(true)
}

/**
 * @param {any} data
 * @param {EncodeOptions} [options]
 * @returns {Uint8Array}
 */
function encode (data, options) {
  options = Object.assign({}, defaultEncodeOptions, options)

  // Use direct encode path when possible
  if (canDirectEncode(options)) {
    defaultWriter.reset()
    directEncode(defaultWriter, data, options, undefined)
    return defaultWriter.toBytes(true)
  }

  return encodeCustom(data, cborEncoders, options)
}

/**
 * @param {any} data
 * @param {Uint8Array} destination
 * @param {EncodeOptions} [options]
 * @returns {{ written: number }}
 */
function encodeInto (data, destination, options) {
  options = Object.assign({}, defaultEncodeOptions, options)

  // Use direct encode path when possible
  if (canDirectEncode(options)) {
    const writer = new U8Bl(destination)
    directEncode(writer, data, options, undefined)
    return { written: writer.toBytes().length }
  }

  const result = encodeCustom(data, cborEncoders, options, destination)
  return { written: result.length }
}

export { objectToTokens, encode, encodeCustom, encodeInto, Ref }
// This is an unfortunate replacement for @sindresorhus/is that we need to
// re-implement for performance purposes. In particular the is.observable()
// check is expensive, and unnecessary for our purposes. The values returned
// are compatible with @sindresorhus/is, however.

// Types that reach getObjectType() - excludes types with fast-paths above:
// primitives (typeof), Array (isArray), Uint8Array (instanceof), plain Object (constructor)
const objectTypeNames = [
  'Object', // for Object.create(null) and other non-plain objects
  'RegExp',
  'Date',
  'Error',
  'Map',
  'Set',
  'WeakMap',
  'WeakSet',
  'ArrayBuffer',
  'SharedArrayBuffer',
  'DataView',
  'Promise',
  'URL',
  'HTMLElement',
  'Int8Array',
  'Uint8ClampedArray',
  'Int16Array',
  'Uint16Array',
  'Int32Array',
  'Uint32Array',
  'Float32Array',
  'Float64Array',
  'BigInt64Array',
  'BigUint64Array',
  'Tagged'
]

/**
 * @param {any} value
 * @returns {string}
 */
export function is (value) {
  if (value === null) {
    return 'null'
  }
  if (value === undefined) {
    return 'undefined'
  }
  if (value === true || value === false) {
    return 'boolean'
  }
  const typeOf = typeof value
  if (typeOf === 'string' || typeOf === 'number' || typeOf === 'bigint' || typeOf === 'symbol') {
    return typeOf
  }
  if (typeOf === 'function') {
    return 'Function'
  }
  if (Array.isArray(value)) {
    return 'Array'
  }
  // Also catches Node.js Buffer which extends Uint8Array
  if (value instanceof Uint8Array) {
    return 'Uint8Array'
  }
  // Fast path for plain objects (most common case after primitives/arrays/bytes)
  if (value.constructor === Object) {
    return 'Object'
  }
  const objectType = getObjectType(value)
  if (objectType) {
    return objectType
  }
  return 'Object'
}

/**
 * @param {any} value
 * @returns {string|undefined}
 */
function getObjectType (value) {
  const objectTypeName = Object.prototype.toString.call(value).slice(8, -1)
  if (objectTypeNames.includes(objectTypeName)) {
    return objectTypeName
  }
  return undefined
}
import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import * as negint from './1negint.js'
import * as bytes from './2bytes.js'
import * as string from './3string.js'
import * as array from './4array.js'
import * as map from './5map.js'
import * as tag from './6tag.js'
import * as float from './7float.js'
import { decodeErrPrefix } from './common.js'
import { fromArray } from './byte-utils.js'

/**
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 */
function invalidMinor (data, pos, minor) {
  throw new Error(`${decodeErrPrefix} encountered invalid minor (${minor}) for major ${data[pos] >>> 5}`)
}

/**
 * @param {string} msg
 * @returns {()=>any}
 */
function errorer (msg) {
  return () => { throw new Error(`${decodeErrPrefix} ${msg}`) }
}

/** @type {((data:Uint8Array, pos:number, minor:number, options?:DecodeOptions) => any)[]} */
export const jump = []

// unsigned integer, 0x00..0x17 (0..23)
for (let i = 0; i <= 0x17; i++) {
  jump[i] = invalidMinor // uint.decodeUintCompact, handled by quick[]
}
jump[0x18] = uint.decodeUint8 // unsigned integer, one-byte uint8_t follows
jump[0x19] = uint.decodeUint16 // unsigned integer, two-byte uint16_t follows
jump[0x1a] = uint.decodeUint32 // unsigned integer, four-byte uint32_t follows
jump[0x1b] = uint.decodeUint64 // unsigned integer, eight-byte uint64_t follows
jump[0x1c] = invalidMinor
jump[0x1d] = invalidMinor
jump[0x1e] = invalidMinor
jump[0x1f] = invalidMinor
// negative integer, -1-0x00..-1-0x17 (-1..-24)
for (let i = 0x20; i <= 0x37; i++) {
  jump[i] = invalidMinor // negintDecode, handled by quick[]
}
jump[0x38] = negint.decodeNegint8 // negative integer, -1-n one-byte uint8_t for n follows
jump[0x39] = negint.decodeNegint16 // negative integer, -1-n two-byte uint16_t for n follows
jump[0x3a] = negint.decodeNegint32 // negative integer, -1-n four-byte uint32_t for follows
jump[0x3b] = negint.decodeNegint64 // negative integer, -1-n eight-byte uint64_t for follows
jump[0x3c] = invalidMinor
jump[0x3d] = invalidMinor
jump[0x3e] = invalidMinor
jump[0x3f] = invalidMinor
// byte string, 0x00..0x17 bytes follow
for (let i = 0x40; i <= 0x57; i++) {
  jump[i] = bytes.decodeBytesCompact
}
jump[0x58] = bytes.decodeBytes8 // byte string, one-byte uint8_t for n, and then n bytes follow
jump[0x59] = bytes.decodeBytes16 // byte string, two-byte uint16_t for n, and then n bytes follow
jump[0x5a] = bytes.decodeBytes32 // byte string, four-byte uint32_t for n, and then n bytes follow
jump[0x5b] = bytes.decodeBytes64 // byte string, eight-byte uint64_t for n, and then n bytes follow
jump[0x5c] = invalidMinor
jump[0x5d] = invalidMinor
jump[0x5e] = invalidMinor
jump[0x5f] = errorer('indefinite length bytes/strings are not supported') // byte string, byte strings follow, terminated by "break"
// UTF-8 string 0x00..0x17 bytes follow
for (let i = 0x60; i <= 0x77; i++) {
  jump[i] = string.decodeStringCompact
}
jump[0x78] = string.decodeString8 // UTF-8 string, one-byte uint8_t for n, and then n bytes follow
jump[0x79] = string.decodeString16 // UTF-8 string, two-byte uint16_t for n, and then n bytes follow
jump[0x7a] = string.decodeString32 // UTF-8 string, four-byte uint32_t for n, and then n bytes follow
jump[0x7b] = string.decodeString64 // UTF-8 string, eight-byte uint64_t for n, and then n bytes follow
jump[0x7c] = invalidMinor
jump[0x7d] = invalidMinor
jump[0x7e] = invalidMinor
jump[0x7f] = errorer('indefinite length bytes/strings are not supported') // UTF-8 strings follow, terminated by "break"
// array, 0x00..0x17 data items follow
for (let i = 0x80; i <= 0x97; i++) {
  jump[i] = array.decodeArrayCompact
}
jump[0x98] = array.decodeArray8 // array, one-byte uint8_t for n, and then n data items follow
jump[0x99] = array.decodeArray16 // array, two-byte uint16_t for n, and then n data items follow
jump[0x9a] = array.decodeArray32 // array, four-byte uint32_t for n, and then n data items follow
jump[0x9b] = array.decodeArray64 // array, eight-byte uint64_t for n, and then n data items follow
jump[0x9c] = invalidMinor
jump[0x9d] = invalidMinor
jump[0x9e] = invalidMinor
jump[0x9f] = array.decodeArrayIndefinite // array, data items follow, terminated by "break"
// map, 0x00..0x17 pairs of data items follow
for (let i = 0xa0; i <= 0xb7; i++) {
  jump[i] = map.decodeMapCompact
}
jump[0xb8] = map.decodeMap8 // map, one-byte uint8_t for n, and then n pairs of data items follow
jump[0xb9] = map.decodeMap16 // map, two-byte uint16_t for n, and then n pairs of data items follow
jump[0xba] = map.decodeMap32 // map, four-byte uint32_t for n, and then n pairs of data items follow
jump[0xbb] = map.decodeMap64 // map, eight-byte uint64_t for n, and then n pairs of data items follow
jump[0xbc] = invalidMinor
jump[0xbd] = invalidMinor
jump[0xbe] = invalidMinor
jump[0xbf] = map.decodeMapIndefinite // map, pairs of data items follow, terminated by "break"
// tags
for (let i = 0xc0; i <= 0xd7; i++) {
  jump[i] = tag.decodeTagCompact
}
jump[0xd8] = tag.decodeTag8
jump[0xd9] = tag.decodeTag16
jump[0xda] = tag.decodeTag32
jump[0xdb] = tag.decodeTag64
jump[0xdc] = invalidMinor
jump[0xdd] = invalidMinor
jump[0xde] = invalidMinor
jump[0xdf] = invalidMinor
// 0xe0..0xf3 simple values, unsupported
for (let i = 0xe0; i <= 0xf3; i++) {
  jump[i] = errorer('simple values are not supported')
}
jump[0xf4] = invalidMinor // false, handled by quick[]
jump[0xf5] = invalidMinor // true, handled by quick[]
jump[0xf6] = invalidMinor // null, handled by quick[]
jump[0xf7] = float.decodeUndefined // undefined
jump[0xf8] = errorer('simple values are not supported') // simple value, one byte follows, unsupported
jump[0xf9] = float.decodeFloat16 // half-precision float (two-byte IEEE 754)
jump[0xfa] = float.decodeFloat32 // single-precision float (four-byte IEEE 754)
jump[0xfb] = float.decodeFloat64 // double-precision float (eight-byte IEEE 754)
jump[0xfc] = invalidMinor
jump[0xfd] = invalidMinor
jump[0xfe] = invalidMinor
jump[0xff] = float.decodeBreak // "break" stop code

/** @type {Token[]} */
export const quick = []
// ints <24
for (let i = 0; i < 24; i++) {
  quick[i] = new Token(Type.uint, i, 1)
}
// negints >= -24
for (let i = -1; i >= -24; i--) {
  quick[31 - i] = new Token(Type.negint, i, 1)
}
// empty bytes
quick[0x40] = new Token(Type.bytes, new Uint8Array(0), 1)
// empty string
quick[0x60] = new Token(Type.string, '', 1)
// empty list
quick[0x80] = new Token(Type.array, 0, 1)
// empty map
quick[0xa0] = new Token(Type.map, 0, 1)
// false
quick[0xf4] = new Token(Type.false, false, 1)
// true
quick[0xf5] = new Token(Type.true, true, 1)
// null
quick[0xf6] = new Token(Type.null, null, 1)

/**
 * @param {Token} token
 * @returns {Uint8Array|undefined}
 */
export function quickEncodeToken (token) {
  switch (token.type) {
    case Type.false:
      return fromArray([0xf4])
    case Type.true:
      return fromArray([0xf5])
    case Type.null:
      return fromArray([0xf6])
    case Type.bytes:
      if (!token.value.length) {
        return fromArray([0x40])
      }
      return
    case Type.string:
      if (token.value === '') {
        return fromArray([0x60])
      }
      return
    case Type.array:
      if (token.value === 0) {
        return fromArray([0x80])
      }
      // shouldn't be possible if this were called when there was only one token
      return
    case Type.map:
      if (token.value === 0) {
        return fromArray([0xa0])
      }
      // shouldn't be possible if this were called when there was only one token
      return
    case Type.uint:
      if (token.value < 24) {
        return fromArray([Number(token.value)])
      }
      return
    case Type.negint:
      if (token.value >= -24) {
        return fromArray([31 - Number(token.value)])
      }
  }
}
/**
 * @typedef {import('../interface.js').TagDecodeControl} TagDecodeControl
 * @typedef {(decode: TagDecodeControl) => Tagged} TaggedTagDecoder
 */

/**
 * A wrapper class for representing a CBOR tag with an arbitrary nested value.
 *
 * `Tagged` is a symmetric primitive: it can be passed to `encode()` to emit
 * a CBOR tag header followed by the encoded form of `value`, and it can be
 * returned from a tag decoder (via `Tagged.decoder(tag)` or `Tagged.preserve()`)
 * to round-trip a tag through decode without losing the tag number.
 *
 * Use `Tagged` for one-off tag handling where defining a dedicated
 * `typeEncoders` entry and tag decoder pair would be heavyweight, e.g. when
 * wrapping a structure in a single application-specific tag (COSE, dCBOR
 * envelopes, etc.).
 *
 * For systematic mapping of a JS type to a tag (e.g. CID -> tag 42), prefer
 * a dedicated `typeEncoders` entry instead.
 */
export class Tagged {
  /**
   * @param {number} tag - CBOR tag number, a non-negative integer
   * @param {any} value - The value to be tagged; encoded recursively
   */
  constructor (tag, value) {
    if (typeof tag !== 'number' || !Number.isInteger(tag) || tag < 0) {
      throw new TypeError('Tagged: tag must be a non-negative integer')
    }
    this.tag = tag
    this.value = value
  }

  /**
   * Build a tag decoder for use in `decode()`'s `tags` option that returns the
   * decoded content wrapped in a `Tagged` instance, preserving the tag number
   * for the caller to inspect.
   *
   * @param {number} tag - The CBOR tag number this decoder will be registered for
   * @returns {TaggedTagDecoder}
   *
   * @example
   * import { decode, Tagged } from 'cborg'
   * const value = decode(bytes, { tags: { 16: Tagged.decoder(16) } })
   * // value instanceof Tagged; value.tag === 16
   */
  static decoder (tag) {
    return (decode) => new Tagged(tag, decode())
  }

  /**
   * Build a `tags` option for `decode()` that wraps each listed tag number in
   * a `Tagged` instance, preserving those tags through decode without
   * registering a dedicated decoder per tag.
   *
   * @param {...number} tagNumbers - One or more CBOR tag numbers to preserve
   * @returns {{[tagNumber: number]: TaggedTagDecoder}}
   *
   * @example
   * import { decode, Tagged } from 'cborg'
   * const value = decode(bytes, { tags: Tagged.preserve(16, 96) })
   */
  static preserve (...tagNumbers) {
    /** @type {{[tagNumber: number]: TaggedTagDecoder}} */
    const tags = {}
    for (const tag of tagNumbers) {
      tags[tag] = Tagged.decoder(tag)
    }
    return tags
  }
}

// Symbol.toStringTag so the internal `is()` type detection returns 'Tagged'
// for instances, allowing the default Tagged typeEncoder to match.
Object.defineProperty(Tagged.prototype, Symbol.toStringTag, {
  value: 'Tagged'
})
class Type {
  /**
   * @param {number} major
   * @param {string} name
   * @param {boolean} terminal
   */
  constructor (major, name, terminal) {
    this.major = major
    this.majorEncoded = major << 5
    this.name = name
    this.terminal = terminal
  }

  toString () {
    return `Type[${this.major}].${this.name}`
  }

  /**
   * @param {Type} typ
   * @returns {number}
   */
  compare (typ) {
    return this.major < typ.major ? -1 : this.major > typ.major ? 1 : 0
  }

  /**
   * Check equality between two Type instances. Safe to use across different
   * copies of the Type class (e.g., when bundlers duplicate the module).
   * (major, name) uniquely identifies a Type; terminal is implied by these.
   * @param {Type} a
   * @param {Type} b
   * @returns {boolean}
   */
  static equals (a, b) {
    return a === b || (a.major === b.major && a.name === b.name)
  }
}

// convert to static fields when better supported
Type.uint = new Type(0, 'uint', true)
Type.negint = new Type(1, 'negint', true)
Type.bytes = new Type(2, 'bytes', true)
Type.string = new Type(3, 'string', true)
Type.array = new Type(4, 'array', false)
Type.map = new Type(5, 'map', false)
Type.tag = new Type(6, 'tag', false) // terminal?
Type.float = new Type(7, 'float', true)
Type.false = new Type(7, 'false', true)
Type.true = new Type(7, 'true', true)
Type.null = new Type(7, 'null', true)
Type.undefined = new Type(7, 'undefined', true)
Type.break = new Type(7, 'break', true)
// Type.indefiniteLength = new Type(0, 'indefiniteLength', true)

class Token {
  /**
   * @param {Type} type
   * @param {any} [value]
   * @param {number} [encodedLength]
   */
  constructor (type, value, encodedLength) {
    this.type = type
    this.value = value
    this.encodedLength = encodedLength
    /** @type {Uint8Array|undefined} */
    this.encodedBytes = undefined
    /** @type {Uint8Array|undefined} */
    this.byteValue = undefined
  }

  toString () {
    return `Token[${this.type}].${this.value}`
  }
}

export { Type, Token }
{
  "name": "cborg",
  "version": "5.1.6",
  "description": "Fast CBOR with a focus on strictness",
  "main": "cborg.js",
  "type": "module",
  "bin": {
    "cborg": "lib/bin.js"
  },
  "scripts": {
    "lint": "standard *.js lib/*.js test/*.js",
    "build": "npm run build:types",
    "build:types": "tsc --build",
    "prepublishOnly": "npm run build",
    "test:node": "mocha test/test-*.js",
    "test:node-bin": "mocha test/node-test-bin.js",
    "test:browser": "polendina --cleanup test/test-*.js",
    "test": "npm run lint && npm run build && npm run test:node && npm run test:node-bin && npm run test:browser",
    "test:ci": "npm run test"
  },
  "repository": {
    "type": "git",
    "url": "git@github.com:rvagg/cborg.git"
  },
  "keywords": [
    "cbor"
  ],
  "author": "Rod <rod@vagg.org> (http://r.va.gg/)",
  "license": "Apache-2.0",
  "devDependencies": {
    "@semantic-release/changelog": "^6.0.3",
    "@semantic-release/commit-analyzer": "^13.0.1",
    "@semantic-release/git": "^10.0.1",
    "@semantic-release/github": "^12.0.6",
    "@semantic-release/npm": "^13.1.5",
    "@semantic-release/release-notes-generator": "^14.1.0",
    "@types/chai": "^5.2.3",
    "@types/mocha": "^10.0.10",
    "@types/node": "^26.0.1",
    "chai": "^6.2.2",
    "conventional-changelog-conventionalcommits": "^10.0.0",
    "ipld-garbage": "^5.0.0",
    "mocha": "^11.7.5",
    "polendina": "^3.2.20",
    "semantic-release": "^25.0.3",
    "standard": "^17.1.2",
    "typescript": "^6.0.2"
  },
  "exports": {
    ".": {
      "import": "./cborg.js",
      "types": "./types/cborg.d.ts"
    },
    "./length": {
      "import": "./lib/length.js",
      "types": "./types/lib/length.d.ts"
    },
    "./taglib": {
      "import": "./lib/taglib.js",
      "types": "./types/lib/taglib.d.ts"
    },
    "./json": {
      "import": "./lib/json/json.js",
      "types": "./types/lib/json/json.d.ts"
    },
    "./extended": {
      "import": "./lib/extended/extended.js",
      "types": "./types/lib/extended/extended.d.ts"
    },
    "./interface": {
      "types": "./types/interface.d.ts"
    }
  },
  "types": "cborg.d.ts",
  "typesVersions": {
    "*": {
      "json": [
        "types/lib/json/json.d.ts"
      ],
      "length": [
        "types/lib/length.d.ts"
      ],
      "*": [
        "types/*"
      ],
      "types/*": [
        "types/*"
      ]
    }
  },
  "release": {
    "branches": [
      "master"
    ],
    "plugins": [
      [
        "@semantic-release/commit-analyzer",
        {
          "preset": "conventionalcommits",
          "releaseRules": [
            {
              "breaking": true,
              "release": "major"
            },
            {
              "revert": true,
              "release": "patch"
            },
            {
              "type": "feat",
              "release": "minor"
            },
            {
              "type": "fix",
              "release": "patch"
            },
            {
              "type": "chore",
              "release": "patch"
            },
            {
              "type": "docs",
              "release": "patch"
            },
            {
              "type": "test",
              "release": "patch"
            },
            {
              "scope": "no-release",
              "release": false
            }
          ]
        }
      ],
      [
        "@semantic-release/release-notes-generator",
        {
          "preset": "conventionalcommits",
          "presetConfig": {
            "types": [
              {
                "type": "feat",
                "section": "Features"
              },
              {
                "type": "fix",
                "section": "Bug Fixes"
              },
              {
                "type": "chore",
                "section": "Trivial Changes"
              },
              {
                "type": "docs",
                "section": "Trivial Changes"
              },
              {
                "type": "test",
                "section": "Tests"
              }
            ]
          }
        }
      ],
      "@semantic-release/changelog",
      "@semantic-release/npm",
      "@semantic-release/github",
      "@semantic-release/git"
    ]
  }
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const b4a = require('b4a')

// https://en.wikipedia.org/wiki/Merkle_tree#Second_preimage_attack
const LEAF_TYPE = b4a.from([0])
const PARENT_TYPE = b4a.from([1])
const ROOT_TYPE = b4a.from([2])

const HYPERCORE = b4a.from('hypercore')

exports.keyPair = function (seed) {
  // key pairs might stay around for a while, so better not to use a default slab to avoid retaining it completely
  const slab = b4a.allocUnsafeSlow(
    sodium.crypto_sign_PUBLICKEYBYTES + sodium.crypto_sign_SECRETKEYBYTES
  )
  const publicKey = slab.subarray(0, sodium.crypto_sign_PUBLICKEYBYTES)
  const secretKey = slab.subarray(sodium.crypto_sign_PUBLICKEYBYTES)

  if (seed) sodium.crypto_sign_seed_keypair(publicKey, secretKey, seed)
  else sodium.crypto_sign_keypair(publicKey, secretKey)

  return {
    publicKey,
    secretKey
  }
}

exports.validateKeyPair = function (keyPair) {
  const pk = b4a.allocUnsafe(sodium.crypto_sign_PUBLICKEYBYTES)
  sodium.crypto_sign_ed25519_sk_to_pk(pk, keyPair.secretKey)
  return b4a.equals(pk, keyPair.publicKey)
}

exports.sign = function (message, secretKey) {
  // Dedicated slab for the signature, to avoid retaining unneeded mem and for security
  const signature = b4a.allocUnsafeSlow(sodium.crypto_sign_BYTES)
  sodium.crypto_sign_detached(signature, message, secretKey)
  return signature
}

exports.verify = function (message, signature, publicKey) {
  if (signature.byteLength !== sodium.crypto_sign_BYTES) return false
  if (publicKey.byteLength !== sodium.crypto_sign_PUBLICKEYBYTES) return false
  return sodium.crypto_sign_verify_detached(signature, message, publicKey)
}

exports.encrypt = function (message, publicKey) {
  const ciphertext = b4a.alloc(message.byteLength + sodium.crypto_box_SEALBYTES)
  sodium.crypto_box_seal(ciphertext, message, publicKey)
  return ciphertext
}

exports.decrypt = function (ciphertext, keyPair) {
  if (ciphertext.byteLength < sodium.crypto_box_SEALBYTES) return null

  const plaintext = b4a.alloc(ciphertext.byteLength - sodium.crypto_box_SEALBYTES)

  if (!sodium.crypto_box_seal_open(plaintext, ciphertext, keyPair.publicKey, keyPair.secretKey)) {
    return null
  }

  return plaintext
}

exports.encryptionKeyPair = function (seed) {
  const publicKey = b4a.alloc(sodium.crypto_box_PUBLICKEYBYTES)
  const secretKey = b4a.alloc(sodium.crypto_box_SECRETKEYBYTES)

  if (seed) {
    sodium.crypto_box_seed_keypair(publicKey, secretKey, seed)
  } else {
    sodium.crypto_box_keypair(publicKey, secretKey)
  }

  return {
    publicKey,
    secretKey
  }
}

exports.data = function (data) {
  const out = b4a.allocUnsafe(32)

  sodium.crypto_generichash_batch(out, [LEAF_TYPE, c.encode(c.uint64, data.byteLength), data])

  return out
}

exports.parent = function (a, b) {
  if (a.index > b.index) {
    const tmp = a
    a = b
    b = tmp
  }

  const out = b4a.allocUnsafe(32)

  sodium.crypto_generichash_batch(out, [
    PARENT_TYPE,
    c.encode(c.uint64, a.size + b.size),
    a.hash,
    b.hash
  ])

  return out
}

exports.tree = function (roots, out) {
  const buffers = new Array(3 * roots.length + 1)
  let j = 0

  buffers[j++] = ROOT_TYPE

  for (let i = 0; i < roots.length; i++) {
    const r = roots[i]
    buffers[j++] = r.hash
    buffers[j++] = c.encode(c.uint64, r.index)
    buffers[j++] = c.encode(c.uint64, r.size)
  }

  if (!out) out = b4a.allocUnsafe(32)
  sodium.crypto_generichash_batch(out, buffers)
  return out
}

exports.hash = function (data, out) {
  if (!out) out = b4a.allocUnsafe(32)
  if (!Array.isArray(data)) data = [data]

  sodium.crypto_generichash_batch(out, data)

  return out
}

exports.randomBytes = function (n) {
  const buf = b4a.allocUnsafe(n)
  sodium.randombytes_buf(buf)
  return buf
}

exports.discoveryKey = function (key) {
  if (!key || key.byteLength !== 32) throw new Error('Must pass a 32 byte buffer')
  // Discovery keys might stay around for a while, so better not to use slab memory (for better gc)
  const digest = b4a.allocUnsafeSlow(32)
  sodium.crypto_generichash(digest, HYPERCORE, key)
  return digest
}

if (sodium.sodium_free) {
  exports.free = function (secureBuf) {
    if (secureBuf.secure) sodium.sodium_free(secureBuf)
  }
} else {
  exports.free = function () {}
}

exports.namespace = function (name, count) {
  const ids = typeof count === 'number' ? range(count) : count

  // Namespaces are long-lived, so better to use a dedicated slab
  const buf = b4a.allocUnsafeSlow(32 * ids.length)

  const list = new Array(ids.length)

  // ns is ephemeral, so default slab
  const ns = b4a.allocUnsafe(33)
  sodium.crypto_generichash(ns.subarray(0, 32), typeof name === 'string' ? b4a.from(name) : name)

  for (let i = 0; i < list.length; i++) {
    list[i] = buf.subarray(32 * i, 32 * i + 32)
    ns[32] = ids[i]
    sodium.crypto_generichash(list[i], ns)
  }

  return list
}

function range(count) {
  const arr = new Array(count)
  for (let i = 0; i < count; i++) arr[i] = i
  return arr
}
{
  "name": "hypercore-crypto",
  "version": "3.7.0",
  "description": "The crypto primitives used in hypercore, extracted into a separate module",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.6.6",
    "compact-encoding": "^3.0.0",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "brittle": "^3.5.0",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/hypercore-crypto.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/hypercore-crypto/issues"
  },
  "homepage": "https://github.com/mafintosh/hypercore-crypto"
}
const c = require('compact-encoding')
const b4a = require('b4a')

const KeyChain = require('./lib/keychain')
const { sign, verify, hash } = require('./lib/crypto')

const {
  ProofEncoding,
  AttestedData,
  AttestedDevice,
  ReceiptEncoding
} = require('./lib/encoding')

const PROOF_VERSION = 1
const KEET_TYPE = 5338

const NS_PROFILE_DISC_ENC = hash(b4a.from('profile discovery'))

module.exports = class IdentityKey {
  constructor (keyChain) {
    this.keyChain = keyChain

    this.identityKeyPair = this.keyChain.get(identityKeyPath(0))
    this.profileDiscoveryKeyPair = this.keyChain.get(discoveryCorePath(0))
  }

  static generateMnemonic () {
    return KeyChain.generateMnemonic()
  }

  static deriveSeed (mnemonic) {
    return KeyChain.deriveSeed(mnemonic)
  }

  get identityPublicKey () {
    return this.identityKeyPair.publicKey
  }

  get profileDiscoveryPublicKey () {
    return this.profileDiscoveryKeyPair.publicKey
  }

  getProfileDiscoveryEncryptionKey () {
    return this.keyChain.getSymmetricKey(encryptionKeyPath(NS_PROFILE_DISC_ENC))
  }

  getEncryptionKey (profileKey) {
    return this.keyChain.getSymmetricKey(encryptionKeyPath(profileKey))
  }

  bootstrap (device) {
    return IdentityKey.bootstrap({ identity: this.identityKeyPair }, device)
  }

  clear () {
    this.keyChain.clear()
    this.identityKeyPair.secretKey.fill(0)
    this.profileDiscoveryKeyPair.secretKey.fill(0)
  }

  static async bootstrap ({ identity, seed, mnemonic }, device) {
    if (!identity) {
      const identityPath = identityKeyPath(0) // accountIndex unused for now
      identity = await KeyChain.from({ seed, mnemonic }, identityPath)
    }

    const proof = {
      version: PROOF_VERSION,
      epoch: Date.now(),
      identity: identity.publicKey,
      chain: []
    }

    return IdentityKey.attestDevice(device, identity, proof)
  }

  static attestDevice (publicKey, parent, proof) {
    if (!proof) return IdentityKey.bootstrap({ identity: parent }, publicKey)

    if (b4a.isBuffer(proof)) {
      proof = c.decode(ProofEncoding, proof)
    }

    if (proof.version === 0) {
      throw new Error('Version 0 proofs are not supported')
    }

    const signable = c.encode(AttestedDevice, {
      epoch: proof.epoch,
      identity: proof.identity,
      device: publicKey
    })

    const signature = sign(signable, parent)

    proof.chain.push({ publicKey, signature })

    return c.encode(ProofEncoding, proof)
  }

  static attestData (attestedData, keyPair, proof) {
    if (attestedData === null) throw new Error('Data is not attestable')

    if (b4a.isBuffer(proof)) {
      proof = c.decode(ProofEncoding, proof)
    }

    if (proof && proof.version === 0) {
      throw new Error('Version 0 proofs are not supported')
    }

    if (!proof) {
      proof = {
        version: PROOF_VERSION,
        epoch: Date.now(),
        identity: keyPair.publicKey,
        chain: []
      }
    }

    const signable = c.encode(AttestedData, {
      epoch: proof.epoch,
      identity: proof.identity,
      data: hash(attestedData)
    })

    proof.data = { signature: sign(signable, keyPair) }

    return c.encode(ProofEncoding, proof)
  }

  static async from ({ seed, mnemonic }) {
    const keyChain = await KeyChain.from({ seed, mnemonic })

    return new IdentityKey(keyChain)
  }

  static verify (proof, attestedData, opts = {}) {
    if (b4a.isBuffer(proof)) {
      proof = c.decode(ProofEncoding, proof)
    }

    if (!validateProof(proof, attestedData, opts)) {
      return null
    }

    const { epoch, identity, chain } = proof

    const candidate = getLastKey(chain) || identity

    if (opts.expectedDevice) {
      if (!b4a.equals(candidate, opts.expectedDevice)) return null
    }

    let parent = identity

    // verify chain
    for (let i = 0; i < chain.length; i++) {
      const { publicKey, signature } = chain[i]

      const signable = c.encode(AttestedDevice, {
        epoch,
        identity,
        device: publicKey
      })

      if (!verify(signable, signature, parent)) {
        return null
      }

      parent = publicKey
    }

    if (proof.data) {
      const signable = c.encode(AttestedData, {
        epoch,
        identity,
        data: hash(attestedData)
      })

      if (!verify(signable, proof.data.signature, parent)) {
        return null
      }
    }

    const receipt = c.encode(ReceiptEncoding, { epoch })

    return {
      receipt,
      identityPublicKey: identity,
      devicePublicKey: candidate
    }
  }
}

function validateProof (proof, attestedData, opts = {}) {
  // version 0 is ignored
  if (proof.version === 0) return false

  // validate version
  if (proof.version > PROOF_VERSION) return false

  // verify epoch
  if (opts.receipt) {
    const { epoch } = c.decode(ReceiptEncoding, opts.receipt)
    if (proof.epoch < epoch) return false
  }

  // verify identity
  if (opts.expectedIdentity) {
    if (!b4a.equals(proof.identity, opts.expectedIdentity)) return false
  }

  return validateAttestedData(proof.data, attestedData)
}

function validateAttestedData (data, attestedData) {
  if (!data && attestedData) return false
  return true
}

function getLastKey (chain) {
  if (!chain.length) return null

  const last = chain[chain.length - 1]
  return last.publicKey
}

// slip48 derivations:
// https://github.com/satoshilabs/slips/blob/master/slip-0048.md

function keyPath (accountIndex, index) {
  // https://github.com/bitcoin/bips/blob/master/bip-0043.mediawiki
  const purpose = 48 // SLIP-48 wallet
  const role = 0 // owner

  return [purpose, KEET_TYPE, role, accountIndex, index]
}

// identityKey -> m/48'/keet'/0'/0'

function identityKeyPath (accountIndex) {
  return keyPath(accountIndex, 0)
}

// identityKey -> m/48'/keet'/0'/1'

function discoveryCorePath (accountIndex) {
  return keyPath(accountIndex, 1)
}

// slip21 derivations
// https://github.com/satoshilabs/slips/blob/master/slip-0021.md

function symmetricPath (...path) {
  const purpose = 'SLIP-0021' // SLIP-21 wallet
  const namespace = 'keet-identity-key' // keet

  return [purpose, namespace, ...path]
}

// encryptionKey  -> m/SLIP-10/keet-identity-key/account/"encryption key"

function encryptionKeyPath (profileKey) {
  return symmetricPath(b4a.toString(profileKey, 'hex'), 'encryption key')
}
const sodium = require('sodium-universal')
const b4a = require('b4a')

module.exports = {
  sign,
  verify,
  hash: blake2b
}

function sign (signable, keyPair) {
  const signature = b4a.alloc(sodium.crypto_sign_BYTES)
  sodium.crypto_sign_detached(signature, signable, keyPair.secretKey)

  return signature
}

function verify (signable, signature, publicKey) {
  return sodium.crypto_sign_verify_detached(signature, signable, publicKey)
}

function blake2b (data, output = b4a.alloc(32)) {
  sodium.crypto_generichash(output, data)
  return output
}
const c = require('compact-encoding')

const ATTESTED_DEVICE = 0
const ATTESTED_DATA = 1

const Epoch = {
  preencode (state, e) {
    c.uint64.preencode(state, Math.floor(e / 1000))
  },
  encode (state, e) {
    c.uint64.encode(state, Math.floor(e / 1000))
  },
  decode (state) {
    return c.uint64.decode(state) * 1000
  }
}

const AttestedDevice = {
  preencode (state, a) {
    c.uint8.preencode(state, ATTESTED_DEVICE)
    Epoch.preencode(state, a.epoch)
    c.fixed32.preencode(state, a.identity)
    c.fixed32.preencode(state, a.device)
  },
  encode (state, a) {
    c.uint8.encode(state, ATTESTED_DEVICE)
    Epoch.encode(state, a.epoch)
    c.fixed32.encode(state, a.identity)
    c.fixed32.encode(state, a.device)
  },
  decode (state) {
    throw new Error('Signed data should only be encoded')
  }
}

const AttestedData = {
  preencode (state, a) {
    c.uint8.preencode(state, ATTESTED_DATA)
    Epoch.preencode(state, a.epoch)
    c.fixed32.preencode(state, a.identity)
    c.fixed32.preencode(state, a.data)
  },
  encode (state, a) {
    c.uint8.encode(state, ATTESTED_DATA)
    Epoch.encode(state, a.epoch)
    c.fixed32.encode(state, a.identity)
    c.fixed32.encode(state, a.data)
  },
  decode (state) {
    throw new Error('Signed data should only be encoded')
  }
}

const DeviceAttestation = {
  preencode (state, a) {
    c.fixed32.preencode(state, a.publicKey)
    c.fixed64.preencode(state, a.signature)
  },
  encode (state, a) {
    c.fixed32.encode(state, a.publicKey)
    c.fixed64.encode(state, a.signature)
  },
  decode (state) {
    return {
      publicKey: c.fixed32.decode(state),
      signature: c.fixed64.decode(state)
    }
  }
}

const DeviceAttestationArray = c.array(DeviceAttestation)

const DataAttestation = {
  preencode (state, a) {
    c.fixed64.preencode(state, a.signature)
  },
  encode (state, a) {
    c.fixed64.encode(state, a.signature)
  },
  decode (state) {
    return {
      signature: c.fixed64.decode(state)
    }
  }
}

const ProofEncoding = {
  preencode (state, proof) {
    c.uint.preencode(state, proof.version)
    Epoch.preencode(state, proof.epoch)
    c.fixed32.preencode(state, proof.identity)
    DeviceAttestationArray.preencode(state, proof.chain)

    let flags = 0
    if (proof.data) flags |= 1
    c.uint.preencode(state, flags)

    if (proof.data) DataAttestation.preencode(state, proof.data)
  },
  encode (state, proof) {
    c.uint.encode(state, proof.version)
    Epoch.encode(state, proof.epoch)
    c.fixed32.encode(state, proof.identity)
    DeviceAttestationArray.encode(state, proof.chain)

    let flags = 0
    if (proof.data) flags |= 1
    c.uint.encode(state, flags)

    if (proof.data) DataAttestation.encode(state, proof.data)
  },
  decode (state) {
    const version = c.uint.decode(state)

    // ignore v0 proofs
    if (version === 0) {
      return {
        version: 0,
        epoch: 0,
        identity: null,
        chain: [],
        data: null
      }
    }

    const epoch = Epoch.decode(state)
    const identity = c.fixed32.decode(state)
    const chain = DeviceAttestationArray.decode(state)

    const flags = c.uint.decode(state)
    const data = flags & 1 ? DataAttestation.decode(state) : null

    return {
      version,
      epoch,
      identity,
      chain,
      data
    }
  }
}

const ReceiptEncoding = {
  preencode (state, receipt) {
    Epoch.preencode(state, receipt.epoch)
  },
  encode (state, receipt) {
    Epoch.encode(state, receipt.epoch)
  },
  decode (state) {
    return {
      epoch: Epoch.decode(state)
    }
  }
}

module.exports = {
  ATTESTED_DEVICE,
  ATTESTED_DATA,
  AttestedDevice,
  AttestedData,
  ProofEncoding,
  ReceiptEncoding
}
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const assert = require('nanoassert')
const b4a = require('b4a')
const { HMAC } = require('sodium-hmac')
const bip39 = require('bip39-mnemonic')

const { sign } = require('./crypto')

const MASTER_CHAIN_CODE = b4a.from('ed25519 seed')
const MASTER_SYMMETRIC_CODE = b4a.from('Symmetric key seed')

const HARDENED_OFFSET = 0x80000000

class KeyChain {
  constructor (seed) {
    this.seed = seed

    this._buffer = b4a.alloc(64)

    this.chainKey = this._buffer.subarray(0, 32)
    this.chainCode = this._buffer.subarray(32)

    this.publicKey = b4a.alloc(sodium.crypto_sign_PUBLICKEYBYTES)
    this.secretKey = b4a.alloc(sodium.crypto_sign_SECRETKEYBYTES)

    this._initialise()
  }

  static generateMnemonic () {
    return bip39.generateMnemonic()
  }

  static deriveSeed (mnemonic) {
    return bip39.mnemonicToSeed(mnemonic)
  }

  static async from ({ mnemonic, seed }, path) {
    assert(mnemonic || seed, 'No mnemonic or seed was passed.')

    if (!seed) seed = await KeyChain.deriveSeed(mnemonic)

    const key = new KeyChain(seed)

    if (!path) return key

    return key.get(path)
  }

  getSymmetricKey (path) {
    const buffer = b4a.alloc(64)

    const chainKey = buffer.subarray(0, 32)
    const key = buffer.subarray(32)

    HMAC.sha512(this.seed, MASTER_SYMMETRIC_CODE, buffer)

    for (const step of path) {
      const label = b4a.alloc(step.length + 1)
      b4a.write(label, step, 1, 'utf8')

      HMAC.sha512(label, chainKey, buffer)
    }

    return key
  }

  get isKeychain () {
    return true
  }

  _initialise () {
    HMAC.sha512(this.seed, MASTER_CHAIN_CODE, this._buffer)
    sodium.crypto_sign_seed_keypair(this.publicKey, this.secretKey, this.chainKey)
  }

  clear () {
    this.secretKey.fill(0)
    this.chainKey.fill(0)
    this.chainCode.fill(0)
  }

  get (path) {
    return this.derive(path)
  }

  sign (signable) {
    return sign(signable, this)
  }

  derive (path) {
    const buffer = b4a.from(this._buffer)

    const chainKey = buffer.subarray(0, 32)
    const chainCode = buffer.subarray(32)

    for (const step of path) {
      const index = ensureHardened(step) // hardened indices are >= 2^31
      HMAC.sha512(encodeDerivationData(chainKey, index), chainCode, buffer)
    }

    return createKeyPair(chainKey)
  }
}

module.exports = KeyChain

function createKeyPair (seed) {
  if (!seed) throw new Error('No seed provided')

  const publicKey = b4a.alloc(sodium.crypto_sign_PUBLICKEYBYTES)
  const secretKey = b4a.alloc(sodium.crypto_sign_SECRETKEYBYTES)

  sodium.crypto_sign_seed_keypair(publicKey, secretKey, seed)

  return {
    publicKey,
    secretKey
  }
}

function encodeDerivationData (key, step) {
  const state = { buffer: b4a.alloc(37), start: 0, end: 37 }

  c.uint8.encode(state, 0)
  c.fixed32.encode(state, key)
  state.buffer.writeUInt32BE(step, state.start)

  state.buffer[33] |= 0x80

  return state.buffer
}

function ensureHardened (n) {
  if (n >= HARDENED_OFFSET) return n
  return n + HARDENED_OFFSET
}
{
  "name": "keet-identity-key",
  "version": "3.2.0",
  "description": "Hierarchical Deterministic Keys for Keet Identities",
  "main": "index.js",
  "scripts": {
    "test": "standard && brittle test/*.js"
  },
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "devDependencies": {
    "brittle": "^3.3.2",
    "hypercore-crypto": "^3.4.0",
    "standard": "^17.1.0"
  },
  "dependencies": {
    "b4a": "^1.6.4",
    "bip39-mnemonic": "^2.2.0",
    "compact-encoding": "^3.0.0",
    "nanoassert": "^2.0.0",
    "sodium-hmac": "^2.0.1",
    "sodium-universal": "^5.0.1"
  },
  "files": [
    "lib/*"
  ],
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/keet-identity-key.git"
  },
  "bugs": {
    "url": "https://github.com/holepunchto/keet-identity-key/issues"
  },
  "homepage": "https://github.com/holepunchto/keet-identity-key#readme"
}
import { coerce } from '../bytes.js';
import basex from '../vendor/base-x.js';
/**
 * Class represents both BaseEncoder and MultibaseEncoder meaning it
 * can be used to encode to multibase or base encode without multibase
 * prefix.
 */
class Encoder {
    name;
    prefix;
    baseEncode;
    constructor(name, prefix, baseEncode) {
        this.name = name;
        this.prefix = prefix;
        this.baseEncode = baseEncode;
    }
    encode(bytes) {
        if (bytes instanceof Uint8Array) {
            return `${this.prefix}${this.baseEncode(bytes)}`;
        }
        else {
            throw Error('Unknown type, must be binary type');
        }
    }
}
/**
 * Class represents both BaseDecoder and MultibaseDecoder so it could be used
 * to decode multibases (with matching prefix) or just base decode strings
 * with corresponding base encoding.
 */
class Decoder {
    name;
    prefix;
    baseDecode;
    prefixCodePoint;
    constructor(name, prefix, baseDecode) {
        this.name = name;
        this.prefix = prefix;
        const prefixCodePoint = prefix.codePointAt(0);
        /* c8 ignore next 3 */
        if (prefixCodePoint === undefined) {
            throw new Error('Invalid prefix character');
        }
        this.prefixCodePoint = prefixCodePoint;
        this.baseDecode = baseDecode;
    }
    decode(text) {
        if (typeof text === 'string') {
            if (text.codePointAt(0) !== this.prefixCodePoint) {
                throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);
            }
            return this.baseDecode(text.slice(this.prefix.length));
        }
        else {
            throw Error('Can only multibase decode strings');
        }
    }
    or(decoder) {
        return or(this, decoder);
    }
}
class ComposedDecoder {
    decoders;
    constructor(decoders) {
        this.decoders = decoders;
    }
    or(decoder) {
        return or(this, decoder);
    }
    decode(input) {
        const prefix = input[0];
        const decoder = this.decoders[prefix];
        if (decoder != null) {
            return decoder.decode(input);
        }
        else {
            throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);
        }
    }
}
export function or(left, right) {
    return new ComposedDecoder({
        ...(left.decoders ?? { [left.prefix]: left }),
        ...(right.decoders ?? { [right.prefix]: right })
    });
}
export class Codec {
    name;
    prefix;
    baseEncode;
    baseDecode;
    encoder;
    decoder;
    constructor(name, prefix, baseEncode, baseDecode) {
        this.name = name;
        this.prefix = prefix;
        this.baseEncode = baseEncode;
        this.baseDecode = baseDecode;
        this.encoder = new Encoder(name, prefix, baseEncode);
        this.decoder = new Decoder(name, prefix, baseDecode);
    }
    encode(input) {
        return this.encoder.encode(input);
    }
    decode(input) {
        return this.decoder.decode(input);
    }
}
export function from({ name, prefix, encode, decode }) {
    return new Codec(name, prefix, encode, decode);
}
export function baseX({ name, prefix, alphabet }) {
    const { encode, decode } = basex(alphabet, name);
    return from({
        prefix,
        name,
        encode,
        decode: (text) => coerce(decode(text))
    });
}
function decode(string, alphabetIdx, bitsPerChar, name) {
    // Count the padding bytes:
    let end = string.length;
    while (string[end - 1] === '=') {
        --end;
    }
    // Allocate the output:
    const out = new Uint8Array((end * bitsPerChar / 8) | 0);
    // Parse the data:
    let bits = 0; // Number of bits currently in the buffer
    let buffer = 0; // Bits waiting to be written out, MSB first
    let written = 0; // Next byte to write
    for (let i = 0; i < end; ++i) {
        // Read one character from the string:
        const value = alphabetIdx[string[i]];
        if (value === undefined) {
            throw new SyntaxError(`Non-${name} character`);
        }
        // Append the bits to the buffer:
        buffer = (buffer << bitsPerChar) | value;
        bits += bitsPerChar;
        // Write out some bits if the buffer has a byte's worth:
        if (bits >= 8) {
            bits -= 8;
            out[written++] = 0xff & (buffer >> bits);
        }
    }
    // Verify that we have received just enough bits:
    if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {
        throw new SyntaxError('Unexpected end of data');
    }
    return out;
}
function encode(data, alphabet, bitsPerChar) {
    const pad = alphabet[alphabet.length - 1] === '=';
    const mask = (1 << bitsPerChar) - 1;
    let out = '';
    let bits = 0; // Number of bits currently in the buffer
    let buffer = 0; // Bits waiting to be written out, MSB first
    for (let i = 0; i < data.length; ++i) {
        // Slurp data into the buffer:
        buffer = (buffer << 8) | data[i];
        bits += 8;
        // Write out as much as we can:
        while (bits > bitsPerChar) {
            bits -= bitsPerChar;
            out += alphabet[mask & (buffer >> bits)];
        }
    }
    // Partial character:
    if (bits !== 0) {
        out += alphabet[mask & (buffer << (bitsPerChar - bits))];
    }
    // Add padding characters until we hit a byte boundary:
    if (pad) {
        while (((out.length * bitsPerChar) & 7) !== 0) {
            out += '=';
        }
    }
    return out;
}
function createAlphabetIdx(alphabet) {
    // Build the character lookup table:
    const alphabetIdx = {};
    for (let i = 0; i < alphabet.length; ++i) {
        alphabetIdx[alphabet[i]] = i;
    }
    return alphabetIdx;
}
/**
 * RFC4648 Factory
 */
export function rfc4648({ name, prefix, bitsPerChar, alphabet }) {
    const alphabetIdx = createAlphabetIdx(alphabet);
    return from({
        prefix,
        name,
        encode(input) {
            return encode(input, alphabet, bitsPerChar);
        },
        decode(input) {
            return decode(input, alphabetIdx, bitsPerChar, name);
        }
    });
}
//# sourceMappingURL=base.js.mapimport { rfc4648 } from './base.js';
export const base32 = rfc4648({
    prefix: 'b',
    name: 'base32',
    alphabet: 'abcdefghijklmnopqrstuvwxyz234567',
    bitsPerChar: 5
});
export const base32upper = rfc4648({
    prefix: 'B',
    name: 'base32upper',
    alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',
    bitsPerChar: 5
});
export const base32pad = rfc4648({
    prefix: 'c',
    name: 'base32pad',
    alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',
    bitsPerChar: 5
});
export const base32padupper = rfc4648({
    prefix: 'C',
    name: 'base32padupper',
    alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',
    bitsPerChar: 5
});
export const base32hex = rfc4648({
    prefix: 'v',
    name: 'base32hex',
    alphabet: '0123456789abcdefghijklmnopqrstuv',
    bitsPerChar: 5
});
export const base32hexupper = rfc4648({
    prefix: 'V',
    name: 'base32hexupper',
    alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',
    bitsPerChar: 5
});
export const base32hexpad = rfc4648({
    prefix: 't',
    name: 'base32hexpad',
    alphabet: '0123456789abcdefghijklmnopqrstuv=',
    bitsPerChar: 5
});
export const base32hexpadupper = rfc4648({
    prefix: 'T',
    name: 'base32hexpadupper',
    alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',
    bitsPerChar: 5
});
export const base32z = rfc4648({
    prefix: 'h',
    name: 'base32z',
    alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',
    bitsPerChar: 5
});
//# sourceMappingURL=base32.js.mapimport { baseX } from './base.js';
export const base36 = baseX({
    prefix: 'k',
    name: 'base36',
    alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'
});
export const base36upper = baseX({
    prefix: 'K',
    name: 'base36upper',
    alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
});
//# sourceMappingURL=base36.js.mapimport { baseX } from './base.js';
export const base58btc = baseX({
    name: 'base58btc',
    prefix: 'z',
    alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
});
export const base58flickr = baseX({
    name: 'base58flickr',
    prefix: 'Z',
    alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'
});
//# sourceMappingURL=base58.js.mapimport { rfc4648 } from './base.js';
export const base64 = rfc4648({
    prefix: 'm',
    name: 'base64',
    alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',
    bitsPerChar: 6
});
export const base64pad = rfc4648({
    prefix: 'M',
    name: 'base64pad',
    alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',
    bitsPerChar: 6
});
export const base64url = rfc4648({
    prefix: 'u',
    name: 'base64url',
    alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',
    bitsPerChar: 6
});
export const base64urlpad = rfc4648({
    prefix: 'U',
    name: 'base64urlpad',
    alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',
    bitsPerChar: 6
});
//# sourceMappingURL=base64.js.mapexport const empty = new Uint8Array(0);
export function toHex(d) {
    return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '');
}
export function fromHex(hex) {
    const hexes = hex.match(/../g);
    return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty;
}
export function equals(aa, bb) {
    if (aa === bb) {
        return true;
    }
    if (aa.byteLength !== bb.byteLength) {
        return false;
    }
    for (let ii = 0; ii < aa.byteLength; ii++) {
        if (aa[ii] !== bb[ii]) {
            return false;
        }
    }
    return true;
}
export function coerce(o) {
    if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') {
        return o;
    }
    if (o instanceof ArrayBuffer) {
        return new Uint8Array(o);
    }
    if (ArrayBuffer.isView(o)) {
        return new Uint8Array(o.buffer, o.byteOffset, o.byteLength);
    }
    throw new Error('Unknown type, must be binary type');
}
export function isBinary(o) {
    return o instanceof ArrayBuffer || ArrayBuffer.isView(o);
}
export function fromString(str) {
    return new TextEncoder().encode(str);
}
export function toString(b) {
    return new TextDecoder().decode(b);
}
//# sourceMappingURL=bytes.js.mapimport { base32 } from './bases/base32.js';
import { base36 } from './bases/base36.js';
import { base58btc } from './bases/base58.js';
import { coerce } from './bytes.js';
import * as Digest from './hashes/digest.js';
import * as varint from './varint.js';
// This way TS will also expose all the types from module
export * from './link/interface.js';
export function format(link, base) {
    const { bytes, version } = link;
    switch (version) {
        case 0:
            return toStringV0(bytes, baseCache(link), base ?? base58btc.encoder);
        default:
            return toStringV1(bytes, baseCache(link), (base ?? base32.encoder));
    }
}
export function toJSON(link) {
    return {
        '/': format(link)
    };
}
export function fromJSON(json) {
    return CID.parse(json['/']);
}
const cache = new WeakMap();
function baseCache(cid) {
    const baseCache = cache.get(cid);
    if (baseCache == null) {
        const baseCache = new Map();
        cache.set(cid, baseCache);
        return baseCache;
    }
    return baseCache;
}
export class CID {
    code;
    version;
    multihash;
    bytes;
    '/';
    /**
     * @param version - Version of the CID
     * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
     * @param multihash - (Multi)hash of the of the content.
     */
    constructor(version, code, multihash, bytes) {
        this.code = code;
        this.version = version;
        this.multihash = multihash;
        this.bytes = bytes;
        // flag to serializers that this is a CID and
        // should be treated specially
        this['/'] = bytes;
    }
    /**
     * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`
     * please either use `CID.asCID(cid)` or switch to new signalling mechanism
     *
     * @deprecated
     */
    get asCID() {
        return this;
    }
    // ArrayBufferView
    get byteOffset() {
        return this.bytes.byteOffset;
    }
    // ArrayBufferView
    get byteLength() {
        return this.bytes.byteLength;
    }
    toV0() {
        switch (this.version) {
            case 0: {
                return this;
            }
            case 1: {
                const { code, multihash } = this;
                if (code !== DAG_PB_CODE) {
                    throw new Error('Cannot convert a non dag-pb CID to CIDv0');
                }
                // sha2-256
                if (multihash.code !== SHA_256_CODE) {
                    throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0');
                }
                return (CID.createV0(multihash));
            }
            default: {
                throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);
            }
        }
    }
    toV1() {
        switch (this.version) {
            case 0: {
                const { code, digest } = this.multihash;
                const multihash = Digest.create(code, digest);
                return (CID.createV1(this.code, multihash));
            }
            case 1: {
                return this;
            }
            default: {
                throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);
            }
        }
    }
    equals(other) {
        return CID.equals(this, other);
    }
    static equals(self, other) {
        const unknown = other;
        return (unknown != null &&
            self.code === unknown.code &&
            self.version === unknown.version &&
            Digest.equals(self.multihash, unknown.multihash));
    }
    toString(base) {
        return format(this, base);
    }
    toJSON() {
        return { '/': format(this) };
    }
    link() {
        return this;
    }
    [Symbol.toStringTag] = 'CID';
    // Legacy
    [Symbol.for('nodejs.util.inspect.custom')]() {
        return `CID(${this.toString()})`;
    }
    /**
     * Takes any input `value` and returns a `CID` instance if it was
     * a `CID` otherwise returns `null`. If `value` is instanceof `CID`
     * it will return value back. If `value` is not instance of this CID
     * class, but is compatible CID it will return new instance of this
     * `CID` class. Otherwise returns null.
     *
     * This allows two different incompatible versions of CID library to
     * co-exist and interop as long as binary interface is compatible.
     */
    static asCID(input) {
        if (input == null) {
            return null;
        }
        const value = input;
        if (value instanceof CID) {
            // If value is instance of CID then we're all set.
            return value;
        }
        else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {
            // If value isn't instance of this CID class but `this.asCID === this` or
            // `value['/'] === value.bytes` is true it is CID instance coming from a
            // different implementation (diff version or duplicate). In that case we
            // rebase it to this `CID` implementation so caller is guaranteed to get
            // instance with expected API.
            const { version, code, multihash, bytes } = value;
            return new CID(version, code, multihash, bytes ?? encodeCID(version, code, multihash.bytes));
        }
        else if (value[cidSymbol] === true) {
            // If value is a CID from older implementation that used to be tagged via
            // symbol we still rebase it to the this `CID` implementation by
            // delegating that to a constructor.
            const { version, multihash, code } = value;
            const digest = Digest.decode(multihash);
            return CID.create(version, code, digest);
        }
        else {
            // Otherwise value is not a CID (or an incompatible version of it) in
            // which case we return `null`.
            return null;
        }
    }
    /**
     * @param version - Version of the CID
     * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
     * @param digest - (Multi)hash of the of the content.
     */
    static create(version, code, digest) {
        if (typeof code !== 'number') {
            throw new Error('String codecs are no longer supported');
        }
        if (!(digest.bytes instanceof Uint8Array)) {
            throw new Error('Invalid digest');
        }
        switch (version) {
            case 0: {
                if (code !== DAG_PB_CODE) {
                    throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);
                }
                else {
                    return new CID(version, code, digest, digest.bytes);
                }
            }
            case 1: {
                const bytes = encodeCID(version, code, digest.bytes);
                return new CID(version, code, digest, bytes);
            }
            default: {
                throw new Error('Invalid version');
            }
        }
    }
    /**
     * Simplified version of `create` for CIDv0.
     */
    static createV0(digest) {
        return CID.create(0, DAG_PB_CODE, digest);
    }
    /**
     * Simplified version of `create` for CIDv1.
     *
     * @param code - Content encoding format code.
     * @param digest - Multihash of the content.
     */
    static createV1(code, digest) {
        return CID.create(1, code, digest);
    }
    /**
     * Decoded a CID from its binary representation. The byte array must contain
     * only the CID with no additional bytes.
     *
     * An error will be thrown if the bytes provided do not contain a valid
     * binary representation of a CID.
     */
    static decode(bytes) {
        const [cid, remainder] = CID.decodeFirst(bytes);
        if (remainder.length !== 0) {
            throw new Error('Incorrect length');
        }
        return cid;
    }
    /**
     * Decoded a CID from its binary representation at the beginning of a byte
     * array.
     *
     * Returns an array with the first element containing the CID and the second
     * element containing the remainder of the original byte array. The remainder
     * will be a zero-length byte array if the provided bytes only contained a
     * binary CID representation.
     */
    static decodeFirst(bytes) {
        const specs = CID.inspectBytes(bytes);
        const prefixSize = specs.size - specs.multihashSize;
        const multihashBytes = coerce(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));
        if (multihashBytes.byteLength !== specs.multihashSize) {
            throw new Error('Incorrect length');
        }
        const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);
        const digest = new Digest.Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);
        const cid = specs.version === 0
            ? CID.createV0(digest)
            : CID.createV1(specs.codec, digest);
        return [cid, bytes.subarray(specs.size)];
    }
    /**
     * Inspect the initial bytes of a CID to determine its properties.
     *
     * Involves decoding up to 4 varints. Typically this will require only 4 to 6
     * bytes but for larger multicodec code values and larger multihash digest
     * lengths these varints can be quite large. It is recommended that at least
     * 10 bytes be made available in the `initialBytes` argument for a complete
     * inspection.
     */
    static inspectBytes(initialBytes) {
        let offset = 0;
        const next = () => {
            const [i, length] = varint.decode(initialBytes.subarray(offset));
            offset += length;
            return i;
        };
        let version = next();
        let codec = DAG_PB_CODE;
        if (version === 18) {
            // CIDv0
            version = 0;
            offset = 0;
        }
        else {
            codec = next();
        }
        if (version !== 0 && version !== 1) {
            throw new RangeError(`Invalid CID version ${version}`);
        }
        const prefixSize = offset;
        const multihashCode = next(); // multihash code
        const digestSize = next(); // multihash length
        const size = offset + digestSize;
        const multihashSize = size - prefixSize;
        return { version, codec, multihashCode, digestSize, multihashSize, size };
    }
    /**
     * Takes cid in a string representation and creates an instance. If `base`
     * decoder is not provided will use a default from the configuration. It will
     * throw an error if encoding of the CID is not compatible with supplied (or
     * a default decoder).
     */
    static parse(source, base) {
        const [prefix, bytes] = parseCIDtoBytes(source, base);
        const cid = CID.decode(bytes);
        if (cid.version === 0 && source[0] !== 'Q') {
            throw Error('Version 0 CID string must not include multibase prefix');
        }
        // Cache string representation to avoid computing it on `this.toString()`
        baseCache(cid).set(prefix, source);
        return cid;
    }
}
function parseCIDtoBytes(source, base) {
    switch (source[0]) {
        // CIDv0 is parsed differently
        case 'Q': {
            const decoder = base ?? base58btc;
            return [
                base58btc.prefix,
                decoder.decode(`${base58btc.prefix}${source}`)
            ];
        }
        case base58btc.prefix: {
            const decoder = base ?? base58btc;
            return [base58btc.prefix, decoder.decode(source)];
        }
        case base32.prefix: {
            const decoder = base ?? base32;
            return [base32.prefix, decoder.decode(source)];
        }
        case base36.prefix: {
            const decoder = base ?? base36;
            return [base36.prefix, decoder.decode(source)];
        }
        default: {
            if (base == null) {
                throw Error('To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided');
            }
            return [source[0], base.decode(source)];
        }
    }
}
function toStringV0(bytes, cache, base) {
    const { prefix } = base;
    if (prefix !== base58btc.prefix) {
        throw Error(`Cannot string encode V0 in ${base.name} encoding`);
    }
    const cid = cache.get(prefix);
    if (cid == null) {
        const cid = base.encode(bytes).slice(1);
        cache.set(prefix, cid);
        return cid;
    }
    else {
        return cid;
    }
}
function toStringV1(bytes, cache, base) {
    const { prefix } = base;
    const cid = cache.get(prefix);
    if (cid == null) {
        const cid = base.encode(bytes);
        cache.set(prefix, cid);
        return cid;
    }
    else {
        return cid;
    }
}
const DAG_PB_CODE = 0x70;
const SHA_256_CODE = 0x12;
function encodeCID(version, code, multihash) {
    const codeOffset = varint.encodingLength(version);
    const hashOffset = codeOffset + varint.encodingLength(code);
    const bytes = new Uint8Array(hashOffset + multihash.byteLength);
    varint.encodeTo(version, bytes, 0);
    varint.encodeTo(code, bytes, codeOffset);
    bytes.set(multihash, hashOffset);
    return bytes;
}
const cidSymbol = Symbol.for('@ipld/js-cid/CID');
//# sourceMappingURL=cid.js.mapimport { coerce, equals as equalBytes } from '../bytes.js';
import * as varint from '../varint.js';
/**
 * Creates a multihash digest.
 */
export function create(code, digest) {
    const size = digest.byteLength;
    const sizeOffset = varint.encodingLength(code);
    const digestOffset = sizeOffset + varint.encodingLength(size);
    const bytes = new Uint8Array(digestOffset + size);
    varint.encodeTo(code, bytes, 0);
    varint.encodeTo(size, bytes, sizeOffset);
    bytes.set(digest, digestOffset);
    return new Digest(code, size, digest, bytes);
}
/**
 * Turns bytes representation of multihash digest into an instance.
 */
export function decode(multihash) {
    const bytes = coerce(multihash);
    const [code, sizeOffset] = varint.decode(bytes);
    const [size, digestOffset] = varint.decode(bytes.subarray(sizeOffset));
    const digest = bytes.subarray(sizeOffset + digestOffset);
    if (digest.byteLength !== size) {
        throw new Error('Incorrect length');
    }
    return new Digest(code, size, digest, bytes);
}
export function equals(a, b) {
    if (a === b) {
        return true;
    }
    else {
        const data = b;
        return (a.code === data.code &&
            a.size === data.size &&
            data.bytes instanceof Uint8Array &&
            equalBytes(a.bytes, data.bytes));
    }
}
/**
 * Represents a multihash digest which carries information about the
 * hashing algorithm and an actual hash digest.
 */
export class Digest {
    code;
    size;
    digest;
    bytes;
    /**
     * Creates a multihash digest.
     */
    constructor(code, size, digest, bytes) {
        this.code = code;
        this.size = size;
        this.digest = digest;
        this.bytes = bytes;
    }
}
/**
 * Used to check that the passed multihash has the passed code
 */
export function hasCode(digest, code) {
    return digest.code === code;
}
//# sourceMappingURL=digest.js.mapexport {};
//# sourceMappingURL=interface.js.mapimport varint from './vendor/varint.js';
export function decode(data, offset = 0) {
    const code = varint.decode(data, offset);
    return [code, varint.decode.bytes];
}
export function encodeTo(int, target, offset = 0) {
    varint.encode(int, target, offset);
    return target;
}
export function encodingLength(int) {
    return varint.encodingLength(int);
}
//# sourceMappingURL=varint.js.map/* eslint-disable */
// base-x encoding / decoding
// Copyright (c) 2018 base-x contributors
// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)
// Distributed under the MIT software license, see the accompanying
// file LICENSE or http://www.opensource.org/licenses/mit-license.php.
/**
 * @param {string} ALPHABET
 * @param {any} name
 */
function base(ALPHABET, name) {
    if (ALPHABET.length >= 255) {
        throw new TypeError('Alphabet too long');
    }
    var BASE_MAP = new Uint8Array(256);
    for (var j = 0; j < BASE_MAP.length; j++) {
        BASE_MAP[j] = 255;
    }
    for (var i = 0; i < ALPHABET.length; i++) {
        var x = ALPHABET.charAt(i);
        var xc = x.charCodeAt(0);
        if (BASE_MAP[xc] !== 255) {
            throw new TypeError(x + ' is ambiguous');
        }
        BASE_MAP[xc] = i;
    }
    var BASE = ALPHABET.length;
    var LEADER = ALPHABET.charAt(0);
    var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up
    var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up
    /**
     * @param {any[] | Iterable<number>} source
     */
    function encode(source) {
        // @ts-ignore
        if (source instanceof Uint8Array)
            ;
        else if (ArrayBuffer.isView(source)) {
            source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
        }
        else if (Array.isArray(source)) {
            source = Uint8Array.from(source);
        }
        if (!(source instanceof Uint8Array)) {
            throw new TypeError('Expected Uint8Array');
        }
        if (source.length === 0) {
            return '';
        }
        // Skip & count leading zeroes.
        var zeroes = 0;
        var length = 0;
        var pbegin = 0;
        var pend = source.length;
        while (pbegin !== pend && source[pbegin] === 0) {
            pbegin++;
            zeroes++;
        }
        // Allocate enough space in big-endian base58 representation.
        var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;
        var b58 = new Uint8Array(size);
        // Process the bytes.
        while (pbegin !== pend) {
            var carry = source[pbegin];
            // Apply "b58 = b58 * 256 + ch".
            var i = 0;
            for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {
                carry += (256 * b58[it1]) >>> 0;
                b58[it1] = (carry % BASE) >>> 0;
                carry = (carry / BASE) >>> 0;
            }
            if (carry !== 0) {
                throw new Error('Non-zero carry');
            }
            length = i;
            pbegin++;
        }
        // Skip leading zeroes in base58 result.
        var it2 = size - length;
        while (it2 !== size && b58[it2] === 0) {
            it2++;
        }
        // Translate the result into a string.
        var str = LEADER.repeat(zeroes);
        for (; it2 < size; ++it2) {
            str += ALPHABET.charAt(b58[it2]);
        }
        return str;
    }
    /**
     * @param {string | string[]} source
     */
    function decodeUnsafe(source) {
        if (typeof source !== 'string') {
            throw new TypeError('Expected String');
        }
        if (source.length === 0) {
            return new Uint8Array();
        }
        var psz = 0;
        // Skip leading spaces.
        if (source[psz] === ' ') {
            return;
        }
        // Skip and count leading '1's.
        var zeroes = 0;
        var length = 0;
        while (source[psz] === LEADER) {
            zeroes++;
            psz++;
        }
        // Allocate enough space in big-endian base256 representation.
        var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.
        var b256 = new Uint8Array(size);
        // Process the characters.
        while (source[psz]) {
            // Decode character
            var carry = BASE_MAP[source.charCodeAt(psz)];
            // Invalid character
            if (carry === 255) {
                return;
            }
            var i = 0;
            for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {
                carry += (BASE * b256[it3]) >>> 0;
                b256[it3] = (carry % 256) >>> 0;
                carry = (carry / 256) >>> 0;
            }
            if (carry !== 0) {
                throw new Error('Non-zero carry');
            }
            length = i;
            psz++;
        }
        // Skip trailing spaces.
        if (source[psz] === ' ') {
            return;
        }
        // Skip leading zeroes in b256.
        var it4 = size - length;
        while (it4 !== size && b256[it4] === 0) {
            it4++;
        }
        var vch = new Uint8Array(zeroes + (size - it4));
        var j = zeroes;
        while (it4 !== size) {
            vch[j++] = b256[it4++];
        }
        return vch;
    }
    /**
     * @param {string | string[]} string
     */
    function decode(string) {
        var buffer = decodeUnsafe(string);
        if (buffer) {
            return buffer;
        }
        throw new Error(`Non-${name} character`);
    }
    return {
        encode: encode,
        decodeUnsafe: decodeUnsafe,
        decode: decode
    };
}
var src = base;
var _brrp__multiformats_scope_baseX = src;
export default _brrp__multiformats_scope_baseX;
//# sourceMappingURL=base-x.js.map/* eslint-disable */
var encode_1 = encode;
var MSB = 0x80, REST = 0x7F, MSBALL = ~REST, INT = Math.pow(2, 31);
/**
 * @param {number} num
 * @param {number[]} out
 * @param {number} offset
 */
function encode(num, out, offset) {
    out = out || [];
    offset = offset || 0;
    var oldOffset = offset;
    while (num >= INT) {
        out[offset++] = (num & 0xFF) | MSB;
        num /= 128;
    }
    while (num & MSBALL) {
        out[offset++] = (num & 0xFF) | MSB;
        num >>>= 7;
    }
    out[offset] = num | 0;
    // @ts-ignore
    encode.bytes = offset - oldOffset + 1;
    return out;
}
var decode = read;
var MSB$1 = 0x80, REST$1 = 0x7F;
/**
 * @param {string | any[]} buf
 * @param {number} offset
 */
function read(buf, offset) {
    var res = 0, offset = offset || 0, shift = 0, counter = offset, b, l = buf.length;
    do {
        if (counter >= l) {
            // @ts-ignore
            read.bytes = 0;
            throw new RangeError('Could not decode varint');
        }
        b = buf[counter++];
        res += shift < 28
            ? (b & REST$1) << shift
            : (b & REST$1) * Math.pow(2, shift);
        shift += 7;
    } while (b >= MSB$1);
    // @ts-ignore
    read.bytes = counter - offset;
    return res;
}
var N1 = Math.pow(2, 7);
var N2 = Math.pow(2, 14);
var N3 = Math.pow(2, 21);
var N4 = Math.pow(2, 28);
var N5 = Math.pow(2, 35);
var N6 = Math.pow(2, 42);
var N7 = Math.pow(2, 49);
var N8 = Math.pow(2, 56);
var N9 = Math.pow(2, 63);
var length = function (/** @type {number} */ value) {
    return (value < N1 ? 1
        : value < N2 ? 2
            : value < N3 ? 3
                : value < N4 ? 4
                    : value < N5 ? 5
                        : value < N6 ? 6
                            : value < N7 ? 7
                                : value < N8 ? 8
                                    : value < N9 ? 9
                                        : 10);
};
var varint = {
    encode: encode_1,
    decode: decode,
    encodingLength: length
};
var _brrp_varint = varint;
export default _brrp_varint;
//# sourceMappingURL=varint.js.map{
  "name": "multiformats",
  "version": "13.4.2",
  "description": "Interface for multihash, multicodec, multibase and CID",
  "author": "Mikeal Rogers <mikeal.rogers@gmail.com> (https://www.mikealrogers.com/)",
  "license": "Apache-2.0 OR MIT",
  "homepage": "https://github.com/multiformats/js-multiformats#readme",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/multiformats/js-multiformats.git"
  },
  "bugs": {
    "url": "https://github.com/multiformats/js-multiformats/issues"
  },
  "publishConfig": {
    "access": "public",
    "provenance": true
  },
  "keywords": [
    "ipfs",
    "ipld",
    "multiformats"
  ],
  "type": "module",
  "types": "./dist/src/index.d.ts",
  "typesVersions": {
    "*": {
      "*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ],
      "src/*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ]
    }
  },
  "files": [
    "src",
    "dist",
    "!dist/test",
    "!**/*.tsbuildinfo"
  ],
  "exports": {
    ".": {
      "types": "./dist/src/index.d.ts",
      "import": "./dist/src/index.js"
    },
    "./bases/base10": {
      "types": "./dist/src/bases/base10.d.ts",
      "import": "./dist/src/bases/base10.js"
    },
    "./bases/base16": {
      "types": "./dist/src/bases/base16.d.ts",
      "import": "./dist/src/bases/base16.js"
    },
    "./bases/base2": {
      "types": "./dist/src/bases/base2.d.ts",
      "import": "./dist/src/bases/base2.js"
    },
    "./bases/base256emoji": {
      "types": "./dist/src/bases/base256emoji.d.ts",
      "import": "./dist/src/bases/base256emoji.js"
    },
    "./bases/base32": {
      "types": "./dist/src/bases/base32.d.ts",
      "import": "./dist/src/bases/base32.js"
    },
    "./bases/base36": {
      "types": "./dist/src/bases/base36.d.ts",
      "import": "./dist/src/bases/base36.js"
    },
    "./bases/base58": {
      "types": "./dist/src/bases/base58.d.ts",
      "import": "./dist/src/bases/base58.js"
    },
    "./bases/base64": {
      "types": "./dist/src/bases/base64.d.ts",
      "import": "./dist/src/bases/base64.js"
    },
    "./bases/base8": {
      "types": "./dist/src/bases/base8.d.ts",
      "import": "./dist/src/bases/base8.js"
    },
    "./bases/identity": {
      "types": "./dist/src/bases/identity.d.ts",
      "import": "./dist/src/bases/identity.js"
    },
    "./bases/interface": {
      "types": "./dist/src/bases/interface.d.ts",
      "import": "./dist/src/bases/interface.js"
    },
    "./basics": {
      "types": "./dist/src/basics.d.ts",
      "import": "./dist/src/basics.js"
    },
    "./block": {
      "types": "./dist/src/block.d.ts",
      "import": "./dist/src/block.js"
    },
    "./block/interface": {
      "types": "./dist/src/block/interface.d.ts",
      "import": "./dist/src/block/interface.js"
    },
    "./bytes": {
      "types": "./dist/src/bytes.d.ts",
      "import": "./dist/src/bytes.js"
    },
    "./cid": {
      "types": "./dist/src/cid.d.ts",
      "import": "./dist/src/cid.js"
    },
    "./codecs/interface": {
      "types": "./dist/src/codecs/interface.d.ts",
      "import": "./dist/src/codecs/interface.js"
    },
    "./codecs/json": {
      "types": "./dist/src/codecs/json.d.ts",
      "import": "./dist/src/codecs/json.js"
    },
    "./codecs/raw": {
      "types": "./dist/src/codecs/raw.d.ts",
      "import": "./dist/src/codecs/raw.js"
    },
    "./hashes/digest": {
      "types": "./dist/src/hashes/digest.d.ts",
      "import": "./dist/src/hashes/digest.js"
    },
    "./hashes/hasher": {
      "types": "./dist/src/hashes/hasher.d.ts",
      "import": "./dist/src/hashes/hasher.js"
    },
    "./hashes/identity": {
      "types": "./dist/src/hashes/identity.d.ts",
      "import": "./dist/src/hashes/identity.js"
    },
    "./hashes/interface": {
      "types": "./dist/src/hashes/interface.d.ts",
      "import": "./dist/src/hashes/interface.js"
    },
    "./hashes/sha1": {
      "types": "./dist/types/src/hashes/sha1.d.ts",
      "browser": "./dist/src/hashes/sha1-browser.js",
      "import": "./dist/src/hashes/sha1.js"
    },
    "./hashes/sha2": {
      "types": "./dist/src/hashes/sha2.d.ts",
      "browser": "./dist/src/hashes/sha2-browser.js",
      "import": "./dist/src/hashes/sha2.js"
    },
    "./interface": {
      "types": "./dist/src/interface.d.ts",
      "import": "./dist/src/interface.js"
    },
    "./link": {
      "types": "./dist/src/link.d.ts",
      "import": "./dist/src/link.js"
    },
    "./link/interface": {
      "types": "./dist/src/link/interface.d.ts",
      "import": "./dist/src/link/interface.js"
    },
    "./traversal": {
      "types": "./dist/src/traversal.d.ts",
      "import": "./dist/src/traversal.js"
    }
  },
  "eslintConfig": {
    "extends": "ipfs",
    "parserOptions": {
      "project": true,
      "sourceType": "module"
    }
  },
  "release": {
    "branches": [
      "master"
    ],
    "plugins": [
      [
        "@semantic-release/commit-analyzer",
        {
          "preset": "conventionalcommits",
          "releaseRules": [
            {
              "breaking": true,
              "release": "major"
            },
            {
              "revert": true,
              "release": "patch"
            },
            {
              "type": "feat",
              "release": "minor"
            },
            {
              "type": "fix",
              "release": "patch"
            },
            {
              "type": "docs",
              "release": "patch"
            },
            {
              "type": "test",
              "release": "patch"
            },
            {
              "type": "deps",
              "release": "patch"
            },
            {
              "scope": "no-release",
              "release": false
            }
          ]
        }
      ],
      [
        "@semantic-release/release-notes-generator",
        {
          "preset": "conventionalcommits",
          "presetConfig": {
            "types": [
              {
                "type": "feat",
                "section": "Features"
              },
              {
                "type": "fix",
                "section": "Bug Fixes"
              },
              {
                "type": "chore",
                "section": "Trivial Changes"
              },
              {
                "type": "docs",
                "section": "Documentation"
              },
              {
                "type": "deps",
                "section": "Dependencies"
              },
              {
                "type": "test",
                "section": "Tests"
              }
            ]
          }
        }
      ],
      "@semantic-release/changelog",
      "@semantic-release/npm",
      "@semantic-release/github",
      [
        "@semantic-release/git",
        {
          "assets": [
            "CHANGELOG.md",
            "package.json"
          ]
        }
      ]
    ]
  },
  "scripts": {
    "clean": "aegir clean",
    "lint": "aegir lint",
    "build": "aegir build",
    "release": "aegir release",
    "docs": "aegir docs",
    "test": "npm run lint && npm run test:node && npm run test:chrome",
    "test:node": "aegir test -t node --cov",
    "test:chrome": "aegir test -t browser --cov",
    "test:chrome-webworker": "aegir test -t webworker",
    "test:firefox": "aegir test -t browser -- --browser firefox",
    "test:firefox-webworker": "aegir test -t webworker -- --browser firefox",
    "test:electron-main": "aegir test -t electron-main"
  },
  "devDependencies": {
    "@stablelib/sha256": "^2.0.0",
    "@stablelib/sha512": "^2.0.0",
    "@types/node": "^25.0.0",
    "aegir": "^47.0.7",
    "buffer": "^6.0.3",
    "cids": "^1.1.9",
    "crypto-hash": "^4.0.0"
  },
  "aegir": {
    "test": {
      "target": [
        "node",
        "browser"
      ]
    }
  },
  "browser": {
    "./hashes/sha1": "./dist/src/hashes/sha1-browser.js",
    "./dist/src/hashes/sha1.js": "./dist/src/hashes/sha1-browser.js",
    "./hashes/sha2": "./dist/src/hashes/sha2-browser.js",
    "./dist/src/hashes/sha2.js": "./dist/src/hashes/sha2-browser.js"
  }
}
module.exports = assert

class AssertionError extends Error {}
AssertionError.prototype.name = 'AssertionError'

/**
 * Minimal assert function
 * @param  {any} t Value to check if falsy
 * @param  {string=} m Optional assertion error message
 * @throws {AssertionError}
 */
function assert (t, m) {
  if (!t) {
    var err = new AssertionError(m)
    if (Error.captureStackTrace) Error.captureStackTrace(err, assert)
    throw err
  }
}
{
  "name": "nanoassert",
  "version": "2.0.0",
  "description": "Nanoscale assertion module",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "tape": "^4.9.1"
  },
  "scripts": {
    "test": "tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/emilbayes/nanoassert.git"
  },
  "keywords": [
    "assert",
    "unassert",
    "power-assert",
    "tiny",
    "nano",
    "pico"
  ],
  "author": "Emil Bay <github@tixz.dk>",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/emilbayes/nanoassert/issues"
  },
  "homepage": "https://github.com/emilbayes/nanoassert#readme"
}
module.exports = require.addon.bind(require)
{
  "name": "require-addon",
  "version": "1.2.0",
  "description": "Import native addons across JavaScript runtimes",
  "exports": {
    "./package": "./package.json",
    ".": {
      "bare": "./lib/bare.js",
      "node": "./lib/node.js",
      "default": "./lib/default.js"
    }
  },
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    },
    "url": {
      "bare": "bare-url",
      "default": "url"
    }
  },
  "files": [
    "lib"
  ],
  "scripts": {
    "test": "npm run lint && npm run test:bare && npm run test:node",
    "test:bare": "bare test.js",
    "test:node": "node test.js",
    "lint": "prettier --check .",
    "format": "prettier --write ."
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/require-addon.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/require-addon/issues"
  },
  "homepage": "https://github.com/holepunchto/require-addon#readme",
  "engines": {
    "bare": ">=1.10.0"
  },
  "dependencies": {
    "bare-addon-resolve": "^1.3.0"
  },
  "devDependencies": {
    "bare-bundle": "^1.8.1",
    "bare-bundle-evaluate": "^1.1.0",
    "bare-fs": "^4.0.0",
    "bare-path": "^3.0.0",
    "bare-url": "^2.1.0",
    "brittle": "^3.7.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
const sodium = require('sodium-universal')

module.exports = {
  init: sodium.crypto_hash_sha256_init,
  update: sodium.crypto_hash_sha256_update,
  final: sodium.crypto_hash_sha256_final,
  BYTES: sodium.crypto_hash_sha256_BYTES,
  STATEBYTES: sodium.crypto_hash_sha256_STATEBYTES
}
const sodium = require('sodium-universal')

module.exports = {
  init: sodium.crypto_hash_sha512_init,
  update: sodium.crypto_hash_sha512_update,
  final: sodium.crypto_hash_sha512_final,
  BYTES: sodium.crypto_hash_sha512_BYTES,
  STATEBYTES: sodium.crypto_hash_sha512_STATEBYTES
}
const b4a = require('b4a')

const sha256 = require('./hash/sha256')
const sha512 = require('./hash/sha512')

class HMAC {
  constructor (hash, key) {
    this.hash = hash
    this.length = hash.BYTES

    this._blocksize = 2 * hash.BYTES

    this._initialised = false

    this.state = b4a.alloc(hash.STATEBYTES)
    this.pad = b4a.alloc(this._blocksize)

    if (key) this.init(key)
  }

  init (key) {
    if (this._initialised) {
      throw new Error('Already initialised, call final first')
    }

    if (key.length > this._blocksize) {
      this.hash.init(this.state)
      this.hash.update(this.state, key)
      this.hash.final(this.state, this.pad.subarray(0, this.length))
    } else {
      this.pad.set(key)
    }

    bufferByteXor(this.pad, 0x36)

    this.hash.init(this.state)
    this.hash.update(this.state, this.pad)

    bufferByteXor(this.pad, 0x5c ^ 0x36)

    this._initialised = true

    return this
  }

  update (data) {
    if (!this._initialised) {
      throw new Error('First initialise with a key')
    }

    this.hash.update(this.state, data)
    return this
  }

  final (output = b4a.alloc(this.length)) {
    if (!this._initialised) {
      throw new Error('First initialise with a key')
    }

    const out = output.byteLength === this.length
      ? output
      : output.subarray(0, this.hash.BYTES)

    this.hash.final(this.state, out)

    this.hash.init(this.state)
    this.hash.update(this.state, this.pad)
    this.hash.update(this.state, out)
    this.hash.final(this.state, out)

    this.pad.fill(0)
    this.state.fill(0)

    this._initialised = false

    return out
  }

  static sha256 (data, key, output) {
    const hmac = new HMAC(sha256, key)
    return hmac.update(data).final(output)
  }

  static sha512 (data, key, output) {
    const hmac = new HMAC(sha512, key)
    return hmac.update(data).final(output)
  }
}

module.exports = {
  HMAC,
  sha256,
  sha512
}

function bufferByteXor (output, byte) {
  for (let i = 0; i < output.byteLength; i++) {
    output[i] ^= byte
  }

  return output
}
{
  "name": "sodium-hmac",
  "version": "2.1.0",
  "description": "HMAC utility",
  "main": "index.js",
  "scripts": {
    "test": "standard && brittle test/*.js"
  },
  "author": "",
  "license": "Apache-2.0",
  "dependencies": {
    "b4a": "^1.6.6",
    "sodium-universal": "^5.0.1"
  },
  "devDependencies": {
    "brittle": "^3.4.0",
    "standard": "^17.1.0"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sodium-hmac.git"
  },
  "files": [
    "index.js",
    "hash/*"
  ],
  "bugs": {
    "url": "https://github.com/holepunchto/sodium-hmac/issues"
  },
  "homepage": "https://github.com/holepunchto/sodium-hmac#readme"
}
require.addon = require('require-addon')
module.exports = require.addon('.', __filename)
const assert = require('assert')
const binding = require('./binding')
const { isNode } = require('which-runtime')

const OPTIONAL = Buffer.from(new ArrayBuffer(0))

module.exports = exports = { ...binding }

// memory

exports.sodium_memzero = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  binding.sodium_memzero(buf)
}

exports.sodium_mlock = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  const res = binding.sodium_mlock(buf)

  if (res !== 0) throw new Error('memory lock failed')
}

exports.sodium_munlock = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  const res = binding.sodium_munlock(buf)

  if (res !== 0) throw new Error('memory unlock failed')
}

exports.sodium_malloc = function (size) {
  assert(size >= 0, 'invalid size')

  const buf = Buffer.from(binding.sodium_malloc(size))
  buf.secure = true
  return buf
}

exports.sodium_free = function (buf) {
  if (!buf || !buf.secure) return

  binding.sodium_free(buf.buffer)
}

exports.sodium_mprotect_noaccess = function (buf) {
  const res = binding.sodium_mprotect_noaccess(buf.buffer)

  if (res !== 0) throw new Error('failed to lock buffer')
}

exports.sodium_mprotect_readonly = function (buf) {
  const res = binding.sodium_mprotect_readonly(buf.buffer)

  if (res !== 0) throw new Error('failed to unlock buffer')
}

exports.sodium_mprotect_readwrite = function (buf) {
  const res = binding.sodium_mprotect_readwrite(buf.buffer)

  if (res !== 0) throw new Error('failed to unlock buffer')
}

// crypto_randombytes

exports.randombytes_buf = function (buffer) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')

  binding.randombytes_buf(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

exports.randombytes_buf_deterministic = function (buffer, seed) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    seed.byteLength === binding.randombytes_SEEDBYTES,
    "seed must be 'randombytes_SEEDBYTES' bytes"
  )

  binding.randombytes_buf_deterministic(
    buffer.buffer,
    buffer.byteOffset,
    buffer.byteLength,

    seed.buffer,
    seed.byteOffset,
    seed.byteLength
  )
}

// sodium_helpers

exports.sodium_memcmp = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  return binding.sodium_memcmp(a, b)
}

exports.sodium_add = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  binding.sodium_add(a, b)
}

exports.sodium_sub = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  binding.sodium_sub(a, b)
}

exports.sodium_compare = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  return binding.sodium_compare(a, b)
}

exports.sodium_is_zero = function (buffer, length) {
  if (length === undefined) length = buffer.byteLength

  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(length >= 0 && length <= buffer.byteLength, 'invalid length')

  return binding.sodium_is_zero(buffer, length)
}

exports.sodium_pad = function (buffer, unpaddedBuflen, blockSize) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(unpaddedBuflen <= buffer.byteLength, 'unpadded length cannot exceed buffer length')
  assert(blockSize <= buffer.byteLength, 'block size cannot exceed buffer length')
  assert(blockSize >= 1, 'block size must be at least 1 byte')
  assert(
    buffer.byteLength >= unpaddedBuflen + (blockSize - (unpaddedBuflen % blockSize)),
    'buf not long enough'
  )

  return binding.sodium_pad(buffer, unpaddedBuflen, blockSize)
}

exports.sodium_unpad = function (buffer, paddedBuflen, blockSize) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(paddedBuflen <= buffer.byteLength, 'unpadded length cannot exceed buffer length')
  assert(blockSize <= buffer.byteLength, 'block size cannot exceed buffer length')
  assert(blockSize >= 1, 'block size must be at least 1 byte')

  return binding.sodium_unpad(buffer, paddedBuflen, blockSize)
}

// crypto_sign

exports.crypto_sign_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )
  assert(
    seed.byteLength === binding.crypto_sign_SEEDBYTES,
    "seed must be 'crypto_sign_SEEDBYTES' bytes"
  )

  const res = binding.crypto_sign_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign = function (sm, m, sk) {
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sm.byteLength === binding.crypto_sign_BYTES + m.byteLength,
    "sm must be 'm.byteLength + crypto_sign_BYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign(sm, m, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_open = function (m, sm, pk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sm.byteLength >= binding.crypto_sign_BYTES,
    "sm must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    m.byteLength === sm.byteLength - binding.crypto_sign_BYTES,
    "m must be 'sm.byteLength - crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_open(m, sm, pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_open = function (m, sm, pk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sm.byteLength >= binding.crypto_sign_BYTES,
    "sm must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    m.byteLength === sm.byteLength - binding.crypto_sign_BYTES,
    "m must be 'sm.byteLength - crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  return binding.crypto_sign_open(m, sm, pk)
}

exports.crypto_sign_detached = function (sig, m, sk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(sig.byteLength === binding.crypto_sign_BYTES, "sig must be 'crypto_sign_BYTES' bytes")
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_detached(sig, m, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_verify_detached = function (sig, m, pk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sig.byteLength >= binding.crypto_sign_BYTES,
    "sig must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  return binding.crypto_sign_verify_detached(
    sig.buffer,
    sig.byteOffset,
    sig.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    pk.buffer,
    pk.byteOffset,
    pk.byteLength
  )
}

exports.crypto_sign_ed25519_sk_to_pk = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_sk_to_pk(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_ed25519_pk_to_curve25519 = function (x25519pk, ed25519pk) {
  assert(ArrayBuffer.isView(x25519pk), 'x25519pk must be a typed array')
  assert(ArrayBuffer.isView(ed25519pk), 'ed25519pk must be a typed array')
  assert(
    x25519pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "x25519pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    ed25519pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "ed25519pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_pk_to_curve25519(x25519pk, ed25519pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_ed25519_sk_to_curve25519 = function (x25519sk, ed25519sk) {
  assert(ArrayBuffer.isView(x25519sk), 'x25519sk must be a typed array')
  assert(ArrayBuffer.isView(ed25519sk), 'ed25519sk must be a typed array')
  assert(
    x25519sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "x25519sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const edLen = ed25519sk.byteLength

  assert(
    edLen === binding.crypto_sign_SECRETKEYBYTES || edLen === binding.crypto_box_SECRETKEYBYTES,
    "ed25519sk must be 'crypto_sign_SECRETKEYBYTES' or 'crypto_sign_SECRETKEYBYTES - crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_sk_to_curve25519(x25519sk, ed25519sk)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_box

exports.crypto_box_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    seed.byteLength === binding.crypto_box_SEEDBYTES,
    "seed must be 'crypto_box_SEEDBYTES' bytes"
  )

  const res = binding.crypto_box_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_easy = function (c, m, n, pk, sk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength === m.byteLength + exports.crypto_box_MACBYTES,
    "c must be 'm.byteLength + crypto_box_MACBYTES' bytes"
  )
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_easy(c, m, n, pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_detached = function (c, mac, m, n, pk, sk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(mac.byteLength === exports.crypto_box_MACBYTES, "mac must be 'crypto_box_MACBYTES' bytes")
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_detached(c, mac, m, n, pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_open_easy = function (m, c, n, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength >= exports.crypto_box_MACBYTES,
    "c must be at least 'crypto_box_MACBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - exports.crypto_box_MACBYTES,
    "m must be 'c.byteLength - crypto_box_MACBYTES' bytes"
  )
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_open_easy(m, c, n, pk, sk)
}

exports.crypto_box_open_detached = function (m, c, mac, n, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(mac.byteLength === exports.crypto_box_MACBYTES, "mac must be 'crypto_box_MACBYTES' bytes")
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_open_detached(m, c, mac, n, pk, sk)
}

exports.crypto_box_seal = function (c, m, pk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    c.byteLength === m.byteLength + exports.crypto_box_SEALBYTES,
    "c must be 'm.byteLength + crypto_box_SEALBYTES' bytes"
  )
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_box_seal(c, m, pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_seal_open = function (m, c, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength >= exports.crypto_box_SEALBYTES,
    "c must be at least 'crypto_box_SEALBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - exports.crypto_box_SEALBYTES,
    "m must be 'c.byteLength - crypto_box_SEALBYTES' bytes"
  )
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_seal_open(
    m.buffer,
    m.byteOffset,
    m.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    pk.buffer,
    pk.byteOffset,
    pk.byteLength,

    sk.buffer,
    sk.byteOffset,
    sk.byteLength
  )
}

// crypto_secretbox

exports.crypto_secretbox_easy = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_secretbox_MACBYTES,
    "c must be 'm.byteLength + crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretbox_easy(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretbox_open_easy = function (m, c, n, k) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    c.byteLength >= binding.crypto_secretbox_MACBYTES,
    "c must be at least 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - binding.crypto_secretbox_MACBYTES,
    "m must be 'c.byteLength - crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  return binding.crypto_secretbox_open_easy(m, c, n, k)
}

exports.crypto_secretbox_detached = function (c, mac, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    mac.byteLength === binding.crypto_secretbox_MACBYTES,
    "mac must be 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretbox_detached(c, mac, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretbox_open_detached = function (m, c, mac, n, k) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(
    mac.byteLength === binding.crypto_secretbox_MACBYTES,
    "mac must be 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  return binding.crypto_secretbox_open_detached(m, c, mac, n, k)
}

// crypto_generichash

exports.crypto_generichash = function (output, input, key) {
  if (!key) key = OPTIONAL

  assert(ArrayBuffer.isView(output), 'output must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    output.byteLength >= binding.crypto_generichash_BYTES_MIN &&
      output.byteLength <= binding.crypto_generichash_BYTES_MAX,
    'output must be between crypto_generichash_BYTES_MIN and crypto_generichash_BYTES_MAX bytes'
  )

  if (key !== OPTIONAL) {
    assert(ArrayBuffer.isView(key), 'key must be a typed array')
    assert(
      key.byteLength >= binding.crypto_generichash_KEYBYTES_MIN &&
        key.byteLength <= binding.crypto_generichash_KEYBYTES_MAX,
      'key must be between crypto_generichash_KEYBYTES_MIN and crypto_generichash_KEYBYTES_MAX bytes'
    )
  }

  const res = binding.crypto_generichash(
    output.buffer,
    output.byteOffset,
    output.byteLength,

    input.buffer,
    input.byteOffset,
    input.byteLength,

    key.buffer,
    key.byteOffset,
    key.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_batch = function (output, batch, key) {
  assert(ArrayBuffer.isView(output), 'output must be a typed array')

  if (isNode || batch.length < 4) {
    const res = binding.crypto_generichash_batch(output, batch, !!key, key || OPTIONAL)
    if (res !== 0) throw new Error('status: ' + res)
  } else {
    const state = Buffer.alloc(binding.crypto_generichash_STATEBYTES)

    exports.crypto_generichash_init(state, key, output.byteLength)

    for (const buf of batch) {
      exports.crypto_generichash_update(state, buf)
    }

    exports.crypto_generichash_final(state, output)
  }
}

exports.crypto_generichash_keygen = function (key) {
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(
    key.byteLength === binding.crypto_generichash_KEYBYTES,
    "key must be 'crypto_generichash_KEYBYTES' bytes"
  )

  const res = binding.crypto_generichash_keygen(key.buffer, key.byteOffset, key.byteLength)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_init = function (state, key, outputLength) {
  if (!key) key = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_init(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    key.buffer,
    key.byteOffset,
    key.byteLength,

    outputLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_update(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    input.buffer,
    input.byteOffset,
    input.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_final = function (state, output) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(output), 'output must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_final(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    output.buffer,
    output.byteOffset,
    output.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

// secretstream

exports.crypto_secretstream_xchacha20poly1305_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  binding.crypto_secretstream_xchacha20poly1305_keygen(k.buffer, k.byteOffset, k.byteLength)
}

exports.crypto_secretstream_xchacha20poly1305_init_push = function (state, header, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(header), 'header must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    header.byteLength === binding.crypto_secretstream_xchacha20poly1305_HEADERBYTES,
    "header must be 'crypto_secretstream_xchacha20poly1305_HEADERBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_init_push(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    header.buffer,
    header.byteOffset,
    header.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretstream_xchacha20poly1305_init_pull = function (state, header, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(header), 'header must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    header.byteLength === binding.crypto_secretstream_xchacha20poly1305_HEADERBYTES,
    "header must be 'crypto_secretstream_xchacha20poly1305_HEADERBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_init_pull(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    header.buffer,
    header.byteOffset,
    header.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretstream_xchacha20poly1305_push = function (state, c, m, ad, tag) {
  if (!ad) ad = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    c.byteLength === m.byteLength + binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "c must be 'm.byteLength + crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_push(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    ad.buffer,
    ad.byteOffset,
    ad.byteLength,

    tag
  )

  if (res < 0) throw new Error('push failed')

  return res
}

exports.crypto_secretstream_xchacha20poly1305_pull = function (state, m, tag, c, ad) {
  if (!ad) ad = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(tag), 'tag must be a typed array')
  assert(tag.byteLength === 1, 'tag must be 1 byte')

  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    c.byteLength >= binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "c must be at least 'crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "m must be 'c.byteLength - crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_pull(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    tag.buffer,
    tag.byteOffset,
    tag.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    ad.buffer,
    ad.byteOffset,
    ad.byteLength
  )

  if (res < 0) throw new Error('pull failed')

  return res
}

exports.crypto_secretstream_xchacha20poly1305_rekey = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )

  binding.crypto_secretstream_xchacha20poly1305_rekey(
    state.buffer,
    state.byteOffset,
    state.byteLength
  )
}

// crypto_stream

exports.crypto_stream = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xor(
    c.buffer,
    c.byteOffset,
    c.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    n.buffer,
    n.byteOffset,
    n.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_auth

exports.crypto_auth = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(out.byteLength === binding.crypto_auth_BYTES, "out must be 'crypto_auth_BYTES' bytes")
  assert(k.byteLength === binding.crypto_auth_KEYBYTES, "k must be 'crypto_auth_KEYBYTES' bytes")

  const res = binding.crypto_auth(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_auth_verify = function (h, input, k) {
  assert(ArrayBuffer.isView(h), 'h must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(h.byteLength === binding.crypto_auth_BYTES, "h must be 'crypto_auth_BYTES' bytes")
  assert(k.byteLength === binding.crypto_auth_KEYBYTES, "k must be 'crypto_auth_KEYBYTES' bytes")

  return binding.crypto_auth_verify(h, input, k)
}

// crypto_onetimeauth

exports.crypto_onetimeauth = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    out.byteLength === binding.crypto_onetimeauth_BYTES,
    "out must be 'crypto_onetimeauth_BYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_init = function (state, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_init(state, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )
  assert(
    out.byteLength === binding.crypto_onetimeauth_BYTES,
    "out must be 'crypto_onetimeauth_BYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_verify = function (h, input, k) {
  assert(ArrayBuffer.isView(h), 'h must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    h.byteLength === binding.crypto_onetimeauth_BYTES,
    "h must be 'crypto_onetimeauth_BYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  return binding.crypto_onetimeauth_verify(h, input, k)
}

// crypto_pwhash

exports.crypto_pwhash = function (out, passwd, salt, opslimit, memlimit, alg) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_BYTES_MIN,
    "out must be at least 'crypto_pwhash_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_BYTES_MAX,
    "out must be at most 'crypto_pwhash_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_SALTBYTES,
    "salt must be 'crypto_pwhash_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )
  assert(alg >= 1 && alg <= 2, 'alg must be either Argon2i 1.3 or Argon2id 1.3')

  const res = binding.crypto_pwhash(out, passwd, salt, opslimit, memlimit, alg)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_async = function (
  out,
  passwd,
  salt,
  opslimit,
  memlimit,
  alg,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_BYTES_MIN,
    "out must be at least 'crypto_pwhash_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_BYTES_MAX,
    "out must be at most 'crypto_pwhash_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_SALTBYTES,
    "salt must be 'crypto_pwhash_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )
  assert(alg >= 1 && alg <= 2, 'alg must be either Argon2i 1.3 or Argon2id 1.3')

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    opslimit,
    memlimit,
    alg,

    done
  )

  return promise
}

exports.crypto_pwhash_str = function (out, passwd, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_STRBYTES,
    "out must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(typeof opslimit === 'number', 'opslimit must be a number')
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(typeof memlimit === 'number', 'memlimit must be a number')
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_str(out, passwd, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_str_async = function (out, passwd, opslimit, memlimit, callback = undefined) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_STRBYTES,
    "out must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(typeof opslimit === 'number', 'opslimit must be a number')
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(typeof memlimit === 'number', 'memlimit must be a number')
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_str_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_str_verify = function (str, passwd) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )

  return binding.crypto_pwhash_str_verify(str, passwd)
}

exports.crypto_pwhash_str_verify_async = function (str, passwd, callback = undefined) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  const [done, promise] = checkStatus(callback, true)

  binding.crypto_pwhash_str_verify_async(
    str.buffer,
    str.byteOffset,
    str.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    done
  )

  return promise
}

exports.crypto_pwhash_str_needs_rehash = function (str, opslimit, memlimit) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  return binding.crypto_pwhash_str_needs_rehash(str, opslimit, memlimit)
}

exports.crypto_pwhash_scryptsalsa208sha256 = function (out, passwd, salt, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MIN,
    "out must be at least 'crypto_pwhash_scryptsalsa208sha256_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MAX,
    "out must be at most 'crypto_pwhash_scryptsalsa208sha256_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_SALTBYTES,
    "salt must be 'crypto_pwhash_scryptsalsa208sha256_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_scryptsalsa208sha256(out, passwd, salt, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_scryptsalsa208sha256_async = function (
  out,
  passwd,
  salt,
  opslimit,
  memlimit,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MIN,
    "out must be at least 'crypto_pwhash_scryptsalsa208sha256_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MAX,
    "out must be at most 'crypto_pwhash_scryptsalsa208sha256_BYTES_MAX' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    salt.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_SALTBYTES,
    "salt must be 'crypto_pwhash_scryptsalsa208sha256_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_scryptsalsa208sha256_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str_async = function (
  out,
  passwd,
  opslimit,
  memlimit,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "out must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_scryptsalsa208sha256_str_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str = function (out, passwd, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "out must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_scryptsalsa208sha256_str(out, passwd, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_scryptsalsa208sha256_str_verify_async = function (
  str,
  passwd,
  callback = undefined
) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  const [done, promise] = checkStatus(callback, true)

  binding.crypto_pwhash_scryptsalsa208sha256_str_verify_async(
    str.buffer,
    str.byteOffset,
    str.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str_verify = function (str, passwd) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  return binding.crypto_pwhash_scryptsalsa208sha256_str_verify(str, passwd)
}

exports.crypto_pwhash_scryptsalsa208sha256_str_needs_rehash = function (str, opslimit, memlimit) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  return binding.crypto_pwhash_scryptsalsa208sha256_str_needs_rehash(str, opslimit, memlimit)
}

// crypto_kx

exports.crypto_kx_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "pk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "sk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    pk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "pk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "sk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    seed.byteLength === binding.crypto_kx_SEEDBYTES,
    "seed must be 'crypto_kx_SEEDBYTES' bytes"
  )

  const res = binding.crypto_kx_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_client_session_keys = function (rx, tx, clientPk, clientSk, serverPk) {
  if (!rx) rx = undefined
  if (!tx) tx = undefined

  assert(rx || tx, 'at least one session key must be specified')

  if (rx) {
    assert(ArrayBuffer.isView(rx), 'rx must be a typed array')
    assert(
      rx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "rx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  if (tx) {
    assert(ArrayBuffer.isView(tx), 'tx must be a typed array')
    assert(
      tx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "tx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  assert(ArrayBuffer.isView(clientPk), 'clientPk must be a typed array')
  assert(ArrayBuffer.isView(clientSk), 'clientSk must be a typed array')
  assert(ArrayBuffer.isView(serverPk), 'serverPk must be a typed array')
  assert(
    clientPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "clientPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    clientSk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "clientSk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    serverPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "serverPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_client_session_keys(rx, tx, clientPk, clientSk, serverPk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_server_session_keys = function (rx, tx, serverPk, serverSk, clientPk) {
  if (!rx) rx = undefined
  if (!tx) tx = undefined

  assert(rx || tx, 'at least one session key must be specified')

  if (rx) {
    assert(ArrayBuffer.isView(rx), 'rx must be a typed array')
    assert(
      rx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "rx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  if (tx) {
    assert(ArrayBuffer.isView(tx), 'tx must be a typed array')
    assert(
      tx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "tx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  assert(ArrayBuffer.isView(serverPk), 'serverPk must be a typed array')
  assert(ArrayBuffer.isView(serverSk), 'serverSk must be a typed array')
  assert(ArrayBuffer.isView(clientPk), 'clientPk must be a typed array')
  assert(
    serverPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "serverPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    serverSk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "serverSk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    clientPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "clientPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_server_session_keys(rx, tx, serverPk, serverSk, clientPk)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_scalarmult

exports.crypto_scalarmult_base = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_BYTES,
    "q must be 'crypto_scalarmult_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_SCALARBYTES,
    "n must be 'crypto_scalarmult_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_base(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_BYTES,
    "q must be 'crypto_scalarmult_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_SCALARBYTES,
    "n must be 'crypto_scalarmult_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_BYTES,
    "p must be 'crypto_scalarmult_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_base = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_base(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519 = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "p must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_is_valid_point = function (p) {
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )

  return binding.crypto_core_ed25519_is_valid_point(p)
}

exports.crypto_core_ed25519_from_uniform = function (p, r) {
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_UNIFORMBYTES,
    "r must be 'crypto_core_ed25519_UNIFORMBYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_from_uniform(p, r)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_base_noclamp = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_base_noclamp(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_noclamp = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "p must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_noclamp(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_core

exports.crypto_core_ed25519_add = function (r, p, q) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_BYTES,
    "r must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_core_ed25519_BYTES,
    "q must be 'crypto_core_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_add(r, p, q)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_sub = function (r, p, q) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_BYTES,
    "r must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_core_ed25519_BYTES,
    "q must be 'crypto_core_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_sub(r, p, q)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_scalar_random = function (r) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "r must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_random(r)
}

exports.crypto_core_ed25519_scalar_reduce = function (r, s) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "r must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_NONREDUCEDSCALARBYTES,
    "s must be 'crypto_core_ed25519_NONREDUCEDSCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_reduce(r, s)
}

exports.crypto_core_ed25519_scalar_invert = function (recip, s) {
  assert(ArrayBuffer.isView(recip), 'recip must be a typed array')
  assert(
    recip.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "recip must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_invert(recip, s)
}

exports.crypto_core_ed25519_scalar_negate = function (neg, s) {
  assert(ArrayBuffer.isView(neg), 'neg must be a typed array')
  assert(
    neg.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "neg must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_negate(neg, s)
}

exports.crypto_core_ed25519_scalar_complement = function (comp, s) {
  assert(ArrayBuffer.isView(comp), 'comp must be a typed array')
  assert(
    comp.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "comp must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_complement(comp, s)
}

exports.crypto_core_ed25519_scalar_add = function (z, x, y) {
  assert(ArrayBuffer.isView(z), 'z must be a typed array')
  assert(
    z.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "z must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(x), 'x must be a typed array')
  assert(
    x.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "x must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(y), 'y must be a typed array')
  assert(
    y.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "y must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_add(z, x, y)
}

exports.crypto_core_ed25519_scalar_sub = function (z, x, y) {
  assert(ArrayBuffer.isView(z), 'z must be a typed array')
  assert(
    z.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "z must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(x), 'x must be a typed array')
  assert(
    x.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "x must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(y), 'y must be a typed array')
  assert(
    y.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "y must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_sub(z, x, y)
}

// crypto_shorthash

exports.crypto_shorthash = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_shorthash_BYTES,
    "out must be 'crypto_shorthash_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_shorthash_KEYBYTES,
    "k must be 'crypto_shorthash_KEYBYTES' bytes"
  )

  const res = binding.crypto_shorthash(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_kdf

exports.crypto_kdf_keygen = function (key) {
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(key.byteLength === binding.crypto_kdf_KEYBYTES, "key must be 'crypto_kdf_KEYBYTES' bytes")

  binding.crypto_kdf_keygen(key)
}

exports.crypto_kdf_derive_from_key = function (subkey, subkeyId, ctx, key) {
  assert(ArrayBuffer.isView(subkey), 'subkey must be a typed array')
  assert(
    subkey.byteLength >= binding.crypto_kdf_BYTES_MIN,
    "subkey must be at least 'crypto_kdf_BYTES_MIN' bytes"
  )
  assert(
    subkey.byteLength <= binding.crypto_kdf_BYTES_MAX,
    "subkey must be at most 'crypto_kdf_BYTES_MAX' bytes"
  )
  assert(ArrayBuffer.isView(ctx), 'ctx must be a typed array')
  assert(
    ctx.byteLength === binding.crypto_kdf_CONTEXTBYTES,
    "ctx must be 'crypto_kdf_CONTEXTBYTES' bytes"
  )
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(key.byteLength === binding.crypto_kdf_KEYBYTES, "key must be 'crypto_kdf_KEYBYTES' bytes")

  const res = binding.crypto_kdf_derive_from_key(subkey, subkeyId, ctx, key)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_hash

exports.crypto_hash = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(out.byteLength === binding.crypto_hash_BYTES, "out must be 'crypto_hash_BYTES' bytes")

  const res = binding.crypto_hash(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256 = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha256_BYTES,
    "out must be 'crypto_hash_sha256_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha256(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_init = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_init(state)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha256_BYTES,
    "out must be 'crypto_hash_sha256_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512 = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha512_BYTES,
    "out must be 'crypto_hash_sha512_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha512(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_init = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_init(state)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha512_BYTES,
    "out must be 'crypto_hash_sha512_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_aead

exports.crypto_aead_xchacha20poly1305_ietf_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  binding.crypto_aead_xchacha20poly1305_ietf_keygen(k)
}

exports.crypto_aead_xchacha20poly1305_ietf_encrypt = function (c, m, ad, nsec, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "c must be 'm.byteLength + crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(c.byteLength <= 0xffffffff, 'c.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_encrypt(c, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_decrypt = function (m, nsec, c, ad, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "m must be 'c.byteLength - crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(m.byteLength <= 0xffffffff, 'm.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_decrypt(m, c, ad, npub, k)

  if (res < 0) throw new Error('could not verify data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_encrypt_detached = function (
  c,
  mac,
  m,
  ad,
  nsec,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_encrypt_detached(c, mac, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_decrypt_detached = function (
  m,
  nsec,
  c,
  mac,
  ad,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_decrypt_detached(m, c, mac, ad, npub, k)

  if (res !== 0) throw new Error('could not verify data')
}

exports.crypto_aead_chacha20poly1305_ietf_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  binding.crypto_aead_chacha20poly1305_ietf_keygen(k)
}

exports.crypto_aead_chacha20poly1305_ietf_encrypt = function (c, m, ad, nsec, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "c must be 'm.byteLength + crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(c.byteLength <= 0xffffffff, 'c.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_encrypt(c, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_decrypt = function (m, nsec, c, ad, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "m must be 'c.byteLength - crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(m.byteLength <= 0xffffffff, 'm.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_decrypt(m, c, ad, npub, k)

  if (res < 0) throw new Error('could not verify data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_encrypt_detached = function (
  c,
  mac,
  m,
  ad,
  nsec,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_encrypt_detached(c, mac, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_decrypt_detached = function (
  m,
  nsec,
  c,
  mac,
  ad,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_decrypt_detached(m, c, mac, ad, npub, k)

  if (res !== 0) throw new Error('could not verify data')
}

// crypto_stream

exports.crypto_stream_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  binding.crypto_stream_xor_wrap_init(state, n, k)
}

exports.crypto_stream_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_xor_wrap_update(state, c, m)
}

exports.crypto_stream_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_xor_wrap_final(state)
}

exports.crypto_stream_chacha20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  binding.crypto_stream_chacha20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_chacha20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_chacha20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_chacha20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_chacha20_xor_wrap_final(state)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  binding.crypto_stream_chacha20_ietf_xor_wrap_init(state, n, k)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_chacha20_ietf_xor_wrap_update(state, c, m)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_chacha20_ietf_xor_wrap_final(state)
}

exports.crypto_stream_xchacha20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  binding.crypto_stream_xchacha20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_xchacha20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_xchacha20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_xchacha20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_xchacha20_xor_wrap_final(state)
}

exports.crypto_stream_salsa20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  binding.crypto_stream_salsa20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_salsa20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_salsa20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_salsa20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_salsa20_xor_wrap_final(state)
}

// experimental

exports.extension_tweak_ed25519_base = function (n, p, ns) {
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.extension_tweak_ed25519_BYTES,
    "p must be 'extension_tweak_ed25519_BYTES' bytes"
  )

  binding.extension_tweak_ed25519_base(n, p, ns)
}

exports.extension_tweak_ed25519_sign_detached = function (sig, m, scalar, pk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(sig.byteLength === binding.crypto_sign_BYTES, "sig must be 'crypto_sign_BYTES' bytes")
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  if (pk) {
    assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
    assert(
      pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
      "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
    )
  }

  const res = binding.extension_tweak_ed25519_sign_detached(sig, m, scalar, pk)

  if (res !== 0) throw new Error('failed to compute signature')
}

exports.extension_tweak_ed25519_sk_to_scalar = function (n, sk) {
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  binding.extension_tweak_ed25519_sk_to_scalar(n, sk)
}

exports.extension_tweak_ed25519_scalar = function (scalarOut, scalar, ns) {
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_scalar(scalarOut, scalar, ns)
}

exports.extension_tweak_ed25519_pk = function (tpk, pk, ns) {
  assert(ArrayBuffer.isView(tpk), 'tpk must be a typed array')
  assert(
    tpk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "tpk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_pk(tpk, pk, ns)

  if (res !== 0) throw new Error('failed to tweak public key')
}

exports.extension_tweak_ed25519_keypair = function (pk, scalarOut, scalarIn, ns) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.extension_tweak_ed25519_BYTES,
    "pk must be 'extension_tweak_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarIn), 'scalarIn must be a typed array')
  assert(
    scalarIn.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarIn must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_keypair(pk, scalarOut, scalarIn, ns)
}

exports.extension_tweak_ed25519_scalar_add = function (scalarOut, scalar, n) {
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_scalar_add(scalarOut, scalar, n)
}

exports.extension_tweak_ed25519_pk_add = function (tpk, pk, p) {
  assert(ArrayBuffer.isView(tpk), 'tpk must be a typed array')
  assert(
    tpk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "tpk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "p must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_pk_add(tpk, pk, p)

  if (res !== 0) throw new Error('failed to add tweak to public key')
}

exports.extension_tweak_ed25519_keypair_add = function (pk, scalarOut, scalarIn, tweak) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.extension_tweak_ed25519_BYTES,
    "pk must be 'extension_tweak_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarIn), 'scalarIn must be a typed array')
  assert(
    scalarIn.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarIn must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(tweak), 'tweak must be a typed array')
  assert(
    tweak.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "tweak must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_keypair_add(pk, scalarOut, scalarIn, tweak)

  if (res !== 0) throw new Error('failed to add tweak to keypair')
}

exports.extension_pbkdf2_sha512_async = function (out, passwd, salt, iter, outlen, callback) {
  assert(
    iter >= binding.extension_pbkdf2_sha512_ITERATIONS_MIN,
    "iter must be at least 'extension_pbkdf2_sha512_ITERATIONS_MIN'"
  )
  assert(
    outlen <= binding.extension_pbkdf2_sha512_BYTES_MAX,
    "outlen must be at most 'extension_pbkdf2_sha512_BYTES_MAX'"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(out.byteLength >= outlen, "out must be at least 'outlen' bytes")
  assert(out.byteLength > 0, 'out must not be empty')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(salt.byteLength > 0, 'salt must not be empty')

  const [done, promise] = checkStatus(callback)

  binding.extension_pbkdf2_sha512_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    iter,
    outlen,

    done
  )

  return promise
}

exports.extension_pbkdf2_sha512 = function (out, passwd, salt, iter, outlen) {
  assert(
    iter >= binding.extension_pbkdf2_sha512_ITERATIONS_MIN,
    "iter must be at least 'extension_pbkdf2_sha512_ITERATIONS_MIN'"
  )
  assert(
    outlen <= binding.extension_pbkdf2_sha512_BYTES_MAX,
    "outlen must be at most 'extension_pbkdf2_sha512_BYTES_MAX'"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(out.byteLength >= outlen, "out must be at least 'outlen' bytes")
  assert(out.byteLength > 0, 'out must not be empty')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(salt.byteLength > 0, 'salt must not be empty')

  const res = binding.extension_pbkdf2_sha512(out, passwd, salt, iter, outlen)

  if (res !== 0) throw new Error('failed to add tweak to public key')
}

function checkStatus(callback, booleanResult = false) {
  let done, promise

  if (typeof callback === 'function') {
    done = function (status) {
      if (booleanResult) callback(null, status === 0)
      else if (status === 0) callback(null)
      else callback(new Error('status: ' + status))
    }
  } else {
    promise = new Promise(function (resolve, reject) {
      done = function (status) {
        if (booleanResult) resolve(status === 0)
        else if (status === 0) resolve()
        else reject(new Error('status: ' + status))
      }
    })
  }

  return [done, promise]
}
{
  "name": "sodium-native",
  "version": "5.1.0",
  "description": "Low level bindings for libsodium",
  "main": "index.js",
  "files": [
    "index.js",
    "binding.cc",
    "binding.js",
    "extensions",
    "prebuilds",
    "CMakeLists.txt"
  ],
  "imports": {
    "assert": {
      "bare": "bare-assert",
      "node": "assert"
    }
  },
  "addon": true,
  "dependencies": {
    "bare-assert": "^1.2.0",
    "require-addon": "^1.1.0",
    "which-runtime": "^1.2.1"
  },
  "devDependencies": {
    "bare-compat-napi": "^1.3.5",
    "brittle": "^3.16.2",
    "cmake-bare": "^1.6.1",
    "cmake-fetch": "^1.4.3",
    "cmake-napi": "^1.2.1",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "test": "prettier . --check && npm run test:node && npm run test:bare",
    "test:node": "node test/all.js",
    "test:bare": "bare test/all.js"
  },
  "standard": {
    "ignore": [
      "/test/fixtures/*.js"
    ]
  },
  "engines": {
    "bare": ">=1.16.0"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sodium-native.git"
  },
  "contributors": [
    "Emil Bay <github@tixz.dk> (http://bayes.dk)",
    "Mathias Buus <mathiasbuus@gmail.com> (https://mafinto.sh)",
    "Christophe Diederichs <chm-diederichs@hyperdivision.dk>"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/sodium-native/issues"
  },
  "homepage": "https://github.com/holepunchto/sodium-native"
}
module.exports = require('sodium-native')
{
  "name": "sodium-universal",
  "version": "5.0.1",
  "description": "Universal wrapper for sodium-javascript and sodium-native working in Node.js and the Browser",
  "main": "index.js",
  "dependencies": {
    "sodium-native": "^5.0.1"
  },
  "peerDependencies": {
    "sodium-javascript": "~0.8.0"
  },
  "peerDependenciesMeta": {
    "sodium-javascript": {
      "optional": true
    }
  },
  "scripts": {
    "prepublish": "./build-scripts/generate.js"
  },
  "browser": {
    "sodium-native": "sodium-javascript"
  },
  "browserify": {
    "transform": [
      "./build-scripts/transform.js"
    ]
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sodium-universal.git"
  },
  "keywords": [
    "libsodium",
    "sodium",
    "sodium-native",
    "sodium-javascript",
    "browserify"
  ],
  "contributors": [
    "Emil Bay <github@tixz.dk> (http://bayes.dk)",
    "Mathias Buus <mathiasbuus@gmail.com> (https://mafinto.sh)",
    "Christophe Diederichs <chm-diederichs@hyperdivision.dk>"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/sodium-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/sodium-universal#readme"
}
const { runtime, platform, arch, version } =
  typeof Bare !== 'undefined'
    ? {
        runtime: 'bare',
        platform: global.Bare.platform,
        arch: global.Bare.arch,
        version: global.Bare.version
      }
    : typeof process !== 'undefined'
      ? {
          runtime: 'node',
          platform: global.process.platform,
          arch: global.process.arch,
          version: global.process.version
        }
      : typeof Window !== 'undefined'
        ? { runtime: 'browser', platform: 'unknown', arch: 'unknown', version: 'unknown' }
        : { runtime: 'unknown', platform: 'unknown', arch: 'unknown', version: 'unknown' }

exports.runtime = runtime
exports.version = version
exports.platform = platform
exports.arch = arch
exports.isBare = runtime === 'bare'
exports.isBareKit = exports.isBare && typeof BareKit !== 'undefined'
exports.isPear = typeof Pear !== 'undefined'
exports.isNode = runtime === 'node'
exports.isBrowser = runtime === 'browser'
exports.isWindows = platform === 'win32'
exports.isLinux = platform === 'linux'
exports.isMac = platform === 'darwin'
exports.isIOS = platform === 'ios' || platform === 'ios-simulator'
exports.isAndroid = platform === 'android'
exports.isElectron = typeof process !== 'undefined' && !!global.process.versions?.electron
exports.isElectronRenderer = exports.isElectron && global.process.type === 'renderer'
exports.isElectronWorker = exports.isElectron && global.process.type === 'worker'
{
  "name": "which-runtime",
  "version": "1.4.0",
  "description": "Detect if you are in Bare or Node and which os etc",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte .",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/which-runtime.git"
  },
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/which-runtime/issues"
  },
  "homepage": "https://github.com/holepunchto/which-runtime",
  "devDependencies": {
    "brittle": "^3.0.0",
    "lunte": "^1.4.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
{
  "name": "atproto-identity",
  "version": "0.0.4",
  "description": "Seed-anchored atproto identity: one BIP39 mnemonic -> Ed25519 (Hypercore) + secp256k1 (did:plc). Offline did:plc genesis + verification.",
  "type": "module",
  "main": "lib/atproto-identity.js",
  "scripts": {
    "test": "brittle-node test/*.test.js && node test/labels.test.mjs",
    "postinstall": "node scripts/bare-deps.mjs"
  },
  "dependencies": {
    "@ipld/dag-cbor": "^9.2.1",
    "@noble/curves": "^1.6.0",
    "@noble/hashes": "^1.5.0",
    "@scure/bip32": "^1.5.0",
    "@scure/bip39": "^1.4.0",
    "b4a": "^1.6.7",
    "hypercore-crypto": "^3.0.0",
    "keet-identity-key": "^3.2.0",
    "multiformats": "^13.3.0",
    "sodium-native": "^5.1.0"
  },
  "devDependencies": {
    "brittle": "^4.0.2"
  }
}
// atproto TID — the 13-char, lexicographically-sortable timestamp id used for `rev`
// (and default rkeys). value = (unixMicros << 10) | clockId(10 bits), top bit 0,
// encoded in the sortable base32 alphabet. Monotonic within a process.

const S32 = '234567abcdefghijklmnopqrstuvwxyz' // atproto sortable base32

function s32encode (n) {
  let s = ''
  for (let i = 0; i < 13; i++) { s = S32[Number(n % 32n)] + s; n /= 32n }
  return s
}

let _last = 0n

// clock() returns micros; injectable for deterministic tests.
export function tidNow (clockId = 0, clock = () => BigInt(Date.now()) * 1000n) {
  let micros = clock()
  const val = (micros << 10n) | (BigInt(clockId) & 0x3ffn)
  const t = val > _last ? val : _last + 1n // strictly monotonic
  _last = t
  return s32encode(t)
}

export function isValidTid (s) {
  return typeof s === 'string' && s.length === 13 && [...s].every(c => S32.includes(c))
}

// The micros component of a TID (drops the 10-bit clock id).
export function tidMicros (tid) {
  let n = 0n
  for (const ch of String(tid)) n = (n << 5n) | BigInt(S32.indexOf(ch))
  return n >> 10n
}

// The DETERMINISTIC next rev after `prevRev` — a pure function of the previous rev, never the
// wall clock. This is what makes the atproto chain indexer-agnostic: two co-owners continuing
// from the SAME head over the SAME finalized record set produce byte-identical commits (RFC6979
// signing is deterministic), so concurrent signers are idempotent rather than forking. Mirrors
// atproto-base/lib/rev.js byte-for-byte (clockId 0) so both implementations agree exactly.
export function nextRev (prevRev) {
  return s32encode((tidMicros(prevRev) + 1n) << 10n)
}
{
  "name": "atproto-store",
  "version": "0.0.25",
  "description": "Holepunch-native atproto repo store — records in a classic Hyperbee (collection/rkey -> DAG-CBOR). The P2P home; the atproto-repo module is the bridge serializer over it.",
  "type": "module",
  "main": "lib/repo-store.js",
  "scripts": {
    "test": "brittle-node test/*.test.js"
  },
  "dependencies": {
    "atproto-repo": "file:../atproto-repo",
    "@ipld/dag-cbor": "^9.2.1",
    "b4a": "^1.6.0",
    "corestore": "^7.4.0",
    "hyperbee": "^2.20.0",
    "random-access-memory": "^6.2.0",
    "bare-fs": "^4.7.3",
    "bare-path": "^3.0.1"
  },
  "devDependencies": {
    "brittle": "^4.0.2"
  },
  "imports": {
    "#node:fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "#node:path": {
      "bare": "bare-path",
      "default": "path"
    }
  },
  "overrides": {
    "rocksdb-native": "3.17.2",
    "hypercore-storage": "3.2.0"
  }
}
function isBuffer(value) {
  return Buffer.isBuffer(value) || value instanceof Uint8Array
}

function isEncoding(encoding) {
  return Buffer.isEncoding(encoding)
}

function alloc(size, fill, encoding) {
  return Buffer.alloc(size, fill, encoding)
}

function allocUnsafe(size) {
  return Buffer.allocUnsafe(size)
}

function allocUnsafeSlow(size) {
  return Buffer.allocUnsafeSlow(size)
}

function byteLength(string, encoding) {
  return Buffer.byteLength(string, encoding)
}

function compare(a, b) {
  return Buffer.compare(a, b)
}

function concat(buffers, totalLength) {
  return Buffer.concat(buffers, totalLength)
}

function copy(source, target, targetStart, start, end) {
  return toBuffer(source).copy(target, targetStart, start, end)
}

function equals(a, b) {
  return toBuffer(a).equals(b)
}

function fill(buffer, value, offset, end, encoding) {
  return toBuffer(buffer).fill(value, offset, end, encoding)
}

function from(value, encodingOrOffset, length) {
  return Buffer.from(value, encodingOrOffset, length)
}

function includes(buffer, value, byteOffset, encoding) {
  return toBuffer(buffer).includes(value, byteOffset, encoding)
}

function indexOf(buffer, value, byfeOffset, encoding) {
  return toBuffer(buffer).indexOf(value, byfeOffset, encoding)
}

function lastIndexOf(buffer, value, byteOffset, encoding) {
  return toBuffer(buffer).lastIndexOf(value, byteOffset, encoding)
}

function swap16(buffer) {
  return toBuffer(buffer).swap16()
}

function swap32(buffer) {
  return toBuffer(buffer).swap32()
}

function swap64(buffer) {
  return toBuffer(buffer).swap64()
}

function toBuffer(buffer) {
  if (Buffer.isBuffer(buffer)) return buffer
  return Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

function toString(buffer, encoding, start, end) {
  return toBuffer(buffer).toString(encoding, start, end)
}

function write(buffer, string, offset, length, encoding) {
  return toBuffer(buffer).write(string, offset, length, encoding)
}

function readDoubleBE(buffer, offset) {
  return toBuffer(buffer).readDoubleBE(offset)
}

function readDoubleLE(buffer, offset) {
  return toBuffer(buffer).readDoubleLE(offset)
}

function readFloatBE(buffer, offset) {
  return toBuffer(buffer).readFloatBE(offset)
}

function readFloatLE(buffer, offset) {
  return toBuffer(buffer).readFloatLE(offset)
}

function readInt32BE(buffer, offset) {
  return toBuffer(buffer).readInt32BE(offset)
}

function readInt32LE(buffer, offset) {
  return toBuffer(buffer).readInt32LE(offset)
}

function readUInt32BE(buffer, offset) {
  return toBuffer(buffer).readUInt32BE(offset)
}

function readUInt32LE(buffer, offset) {
  return toBuffer(buffer).readUInt32LE(offset)
}

function writeDoubleBE(buffer, value, offset) {
  return toBuffer(buffer).writeDoubleBE(value, offset)
}

function writeDoubleLE(buffer, value, offset) {
  return toBuffer(buffer).writeDoubleLE(value, offset)
}

function writeFloatBE(buffer, value, offset) {
  return toBuffer(buffer).writeFloatBE(value, offset)
}

function writeFloatLE(buffer, value, offset) {
  return toBuffer(buffer).writeFloatLE(value, offset)
}

function writeInt32BE(buffer, value, offset) {
  return toBuffer(buffer).writeInt32BE(value, offset)
}

function writeInt32LE(buffer, value, offset) {
  return toBuffer(buffer).writeInt32LE(value, offset)
}

function writeUInt32BE(buffer, value, offset) {
  return toBuffer(buffer).writeUInt32BE(value, offset)
}

function writeUInt32LE(buffer, value, offset) {
  return toBuffer(buffer).writeUInt32LE(value, offset)
}

module.exports = {
  isBuffer,
  isEncoding,
  alloc,
  allocUnsafe,
  allocUnsafeSlow,
  byteLength,
  compare,
  concat,
  copy,
  equals,
  fill,
  from,
  includes,
  indexOf,
  lastIndexOf,
  swap16,
  swap32,
  swap64,
  toBuffer,
  toString,
  write,
  readDoubleBE,
  readDoubleLE,
  readFloatBE,
  readFloatLE,
  readInt32BE,
  readInt32LE,
  readUInt32BE,
  readUInt32LE,
  writeDoubleBE,
  writeDoubleLE,
  writeFloatBE,
  writeFloatLE,
  writeInt32BE,
  writeInt32LE,
  writeUInt32BE,
  writeUInt32LE
}
{
  "name": "b4a",
  "version": "1.8.1",
  "description": "Bridging the gap between buffers and typed arrays",
  "exports": {
    "./package": "./package.json",
    ".": {
      "react-native": "./react-native.js",
      "browser": "./browser.js",
      "default": "./index.js"
    }
  },
  "files": [
    "browser.js",
    "index.js",
    "react-native.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:bare && npm run test:node",
    "test:bare": "brittle-bare --coverage test.mjs",
    "test:node": "brittle-node --coverage test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/b4a.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/b4a/issues"
  },
  "homepage": "https://github.com/holepunchto/b4a#readme",
  "devDependencies": {
    "brittle": "^3.5.2",
    "lunte": "^1.7.0",
    "nanobench": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "react-native-b4a": "*"
  },
  "peerDependenciesMeta": {
    "react-native-b4a": {
      "optional": true
    }
  }
}
module.exports = require.addon()
const binding = require('./binding')

module.exports = binding.abort
{
  "name": "bare-abort",
  "version": "2.0.13",
  "description": "Cause abnormal program termination and generate a crash report",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-abort.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-abort/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-abort#readme",
  "devDependencies": {
    "cmake-bare": "^1.1.7",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  }
}
const ESC = '\x1b'
const CSI = ESC + '['
const SGR = (n) => CSI + n + 'm'

exports.constants = {
  ESC,
  CSI,
  SGR
}

// https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_(Control_Sequence_Introducer)_sequences

exports.cursorHide = CSI + '?25l'
exports.cursorShow = CSI + '?25h'

exports.cursorUp = function cursorUp(n = 1) {
  return CSI + n + 'A'
}

exports.cursorDown = function cursorDown(n = 1) {
  return CSI + n + 'B'
}

exports.cursorForward = function cursorForward(n = 1) {
  return CSI + n + 'C'
}

exports.cursorBack = function cursorBack(n = 1) {
  return CSI + n + 'D'
}

exports.cursorNextLine = function cursorNextLine(n = 1) {
  return CSI + n + 'E'
}

exports.cursorPreviousLine = function cursorPreviousLine(n = 1) {
  return CSI + n + 'F'
}

exports.cursorPosition = function cursorPosition(column, row = 0) {
  if (row === 0) return CSI + (column + 1) + 'G'

  return CSI + (row + 1) + ';' + (column + 1) + 'H'
}

exports.eraseDisplayEnd = CSI + 'J'
exports.eraseDisplayStart = CSI + '1J'
exports.eraseDisplay = CSI + '2J'
exports.eraseLineEnd = CSI + 'K'
exports.eraseLineStart = CSI + '1K'
exports.eraseLine = CSI + '2K'

exports.scrollUp = function scrollUp(n = 1) {
  return CSI + n + 'S'
}

exports.scrollDown = function scrollDown(n = 1) {
  return CSI + n + 'T'
}

// https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_(Select_Graphic_Rendition)_parameters

exports.modifierReset = SGR(0)
exports.modifierBold = SGR(1)
exports.modifierDim = SGR(2)
exports.modifierItalic = SGR(3)
exports.modifierUnderline = SGR(4)
exports.modifierNormal = SGR(22)
exports.modifierNotItalic = SGR(23)
exports.modifierNotUnderline = SGR(24)

// https://en.wikipedia.org/wiki/ANSI_escape_code#Colors

exports.colorBlack = SGR(30)
exports.colorRed = SGR(31)
exports.colorGreen = SGR(32)
exports.colorYellow = SGR(33)
exports.colorBlue = SGR(34)
exports.colorMagenta = SGR(35)
exports.colorCyan = SGR(36)
exports.colorWhite = SGR(37)
exports.colorDefault = SGR(39)
exports.colorBrightBlack = SGR(90)
exports.colorBrightRed = SGR(91)
exports.colorBrightGreen = SGR(92)
exports.colorBrightYellow = SGR(93)
exports.colorBrightBlue = SGR(94)
exports.colorBrightMagenta = SGR(95)
exports.colorBrightCyan = SGR(96)
exports.colorBrightWhite = SGR(97)
{
  "name": "bare-ansi-escapes",
  "version": "2.2.3",
  "description": "Parse and produce ANSI escape sequences",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./key-decoder": {
      "types": "./key-decoder.d.ts",
      "default": "./key-decoder.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "key-decoder.js",
    "key-decoder.d.ts"
  ],
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-ansi-escapes.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-ansi-escapes/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-ansi-escapes#readme",
  "dependencies": {
    "bare-stream": "^2.6.5"
  },
  "devDependencies": {
    "bare-buffer": "^3.0.2",
    "brittle": "^3.3.2",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  },
  "peerDependencies": {
    "bare-buffer": "*"
  },
  "peerDependenciesMeta": {
    "bare-buffer": {
      "optional": true
    }
  }
}
const inspect = require('bare-inspect')

class AssertionError extends Error {
  constructor(opts = {}) {
    let { message = null, actual, expected, operator } = opts

    if (message === null) {
      message = `${inspect(actual)} ${operator} ${inspect(expected)}`
    }

    super(message)

    this.actual = actual
    this.expected = expected
    this.operator = operator
  }

  get name() {
    return 'AssertionError'
  }

  get code() {
    'ASSERTION'
  }
}

function assertFail(opts, fn) {
  if (opts.message instanceof Error) throw opts.message

  const err = new AssertionError(opts)

  if (Error.captureStackTrace) Error.captureStackTrace(err, fn)

  throw err
}

module.exports = exports = function assert(actual, message) {
  if (actual) return

  assertFail({ message, actual, expected: true, operator: '==' }, assert)
}

exports.AssertionError = AssertionError

exports.fail = function fail(message) {
  if (message === undefined) message = 'Failed'

  assertFail({ message, operator: 'fail' }, fail)
}

exports.ok = function ok(actual, message) {
  if (actual) return

  assertFail({ message, actual, expected: true, operator: '==' }, ok)
}

exports.notOk = function ok(actual, message) {
  if (!actual) return

  assertFail({ message, actual, expected: false, operator: '==' }, ok)
}

exports.equal = function equal(actual, expected, message) {
  if (actual == expected || (actual !== actual && expected !== expected)) {
    return
  }

  assertFail({ message, actual, expected, operator: '==' }, equal)
}

exports.notEqual = function notEqual(actual, expected, message) {
  if (actual != expected && (actual === actual || expected === expected)) {
    return
  }

  assertFail({ message, actual, expected, operator: '!=' }, notEqual)
}

exports.strictEqual = function strictEqual(actual, expected, message) {
  if (Object.is(actual, expected)) return

  assertFail(
    { message, actual, expected, operator: 'strictEqual' },
    strictEqual
  )
}

exports.notStrictEqual = function notStrictEqual(actual, expected, message) {
  if (!Object.is(actual, expected)) return

  assertFail(
    { message, actual, expected, operator: 'notStrictEqual' },
    notStrictEqual
  )
}
{
  "name": "bare-assert",
  "version": "1.2.0",
  "description": "Assertion library for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts"
  ],
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-assert.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-assert/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-assert#readme",
  "dependencies": {
    "bare-inspect": "^3.1.2"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  }
}
module.exports = require.addon()
const constants = require('./lib/constants')
const ascii = require('./lib/ascii')
const base64 = require('./lib/base64')
const base64url = require('./lib/base64url')
const hex = require('./lib/hex')
const utf8 = require('./lib/utf8')
const utf16le = require('./lib/utf16le')
const latin1 = require('./lib/latin1')
const binding = require('./binding')

const kind = Symbol.for('bare.buffer.kind')

let poolSize = 0

module.exports = exports = class Buffer extends Uint8Array {
  static get [kind]() {
    return 0 // Compatibility version
  }

  static get poolSize() {
    return poolSize
  }

  static set poolSize(value) {
    poolSize = Math.max(0, value)
  }

  constructor(arrayBuffer, offset, length, opts = {}) {
    if (typeof arrayBuffer === 'number') {
      opts = offset || {}

      const { uninitialized = false } = opts

      offset = 0
      length = arrayBuffer

      if (length > constants.MAX_LENGTH) {
        throw new RangeError(`Buffer length must be at most ${constants.MAX_LENGTH}`)
      }

      arrayBuffer = uninitialized ? binding.allocUnsafe(length) : binding.alloc(length)
    } else {
      if (length > constants.MAX_LENGTH) {
        throw new RangeError(`Buffer length must be at most ${constants.MAX_LENGTH}`)
      }

      if (typeof offset === 'object' && offset !== null) {
        opts = offset
        offset = 0
        length = arrayBuffer.byteLength
      } else if (typeof length === 'length' && length !== null) {
        opts = length
        length = arrayBuffer.byteLength - offset
      }
    }

    super(arrayBuffer, offset, length)
  }

  get [kind]() {
    return Buffer[kind]
  }

  copy(target, targetStart = 0, sourceStart = 0, sourceEnd = this.byteLength) {
    let source = this

    if (targetStart < 0) targetStart = 0
    if (targetStart >= target.byteLength) return 0

    const targetLength = target.byteLength - targetStart

    if (sourceStart < 0) sourceStart = 0
    if (sourceStart >= source.byteLength) return 0

    if (sourceEnd <= sourceStart) return 0
    if (sourceEnd > source.byteLength) sourceEnd = source.byteLength

    if (sourceEnd - sourceStart > targetLength) {
      sourceEnd = sourceStart + targetLength
    }

    const sourceLength = sourceEnd - sourceStart

    if (source === target) {
      target.copyWithin(targetStart, sourceStart, sourceEnd)
    } else {
      if (sourceStart !== 0 || sourceEnd !== source.byteLength) {
        source = source.subarray(sourceStart, sourceEnd)
      }

      target.set(source, targetStart)
    }

    return sourceLength
  }

  equals(target) {
    const source = this

    if (source === target) return true
    if (source.byteLength !== target.byteLength) return false

    return (
      binding.compare(
        source.buffer,
        source.byteOffset,
        source.byteLength,
        target.buffer,
        target.byteOffset,
        target.byteLength
      ) === 0
    )
  }

  compare(
    target,
    targetStart = 0,
    targetEnd = target.byteLength,
    sourceStart = 0,
    sourceEnd = this.byteLength
  ) {
    let source = this

    if (source === target) return 0

    if (arguments.length > 1) {
      if (targetStart < 0) targetStart = 0
      if (targetStart > target.byteLength) targetStart = target.byteLength

      if (targetEnd < targetStart) targetEnd = targetStart
      if (targetEnd > target.byteLength) targetEnd = target.byteLength

      if (sourceStart < 0) sourceStart = 0
      if (sourceStart > source.byteLength) sourceStart = source.byteLength

      if (sourceEnd < sourceStart) sourceEnd = sourceStart
      if (sourceEnd > source.byteLength) sourceEnd = source.byteLength

      if (sourceStart !== 0 || sourceEnd !== source.byteLength) {
        source = source.subarray(sourceStart, sourceEnd)
      }

      if (targetStart !== 0 || targetEnd !== target.byteLength) {
        target = target.subarray(targetStart, targetEnd)
      }
    }

    return binding.compare(
      source.buffer,
      source.byteOffset,
      source.byteLength,
      target.buffer,
      target.byteOffset,
      target.byteLength
    )
  }

  fill(value, offset = 0, end = this.byteLength, encoding = 'utf8') {
    if (typeof value === 'string') {
      if (typeof offset === 'string') {
        // fill(string, encoding)
        encoding = offset
        offset = 0
        end = this.byteLength
      } else if (typeof end === 'string') {
        // fill(string, offset, encoding)
        encoding = end
        end = this.byteLength
      }
    } else if (typeof value === 'number') {
      value = value & 0xff
    } else if (typeof value === 'boolean') {
      value = +value
    }

    if (offset < 0) offset = 0
    if (offset >= this.byteLength) return this

    if (end <= offset) return this
    if (end > this.byteLength) end = this.byteLength

    if (typeof value === 'number') return super.fill(value, offset, end)

    if (typeof value === 'string') value = exports.from(value, encoding)

    const length = value.byteLength

    for (let i = 0, n = end - offset; i < n; ++i) {
      this[i + offset] = value[i % length]
    }

    return this
  }

  includes(value, offset, encoding) {
    return this.indexOf(value, offset, encoding) !== -1
  }

  indexOf(value, offset = 0, encoding) {
    if (typeof value === 'boolean') value = +value

    if (typeof value === 'number') {
      return super.indexOf(value & 0xff, offset)
    }

    return bidirectionalIndexOf(this, value, offset, encoding, true /* first */)
  }

  lastIndexOf(value, offset = this.byteLength - 1, encoding) {
    if (typeof value === 'boolean') value = +value

    if (typeof value === 'number') {
      return super.lastIndexOf(value & 0xff, offset)
    }

    return bidirectionalIndexOf(this, value, offset, encoding, false /* last */)
  }

  swap16() {
    const length = this.byteLength

    if (length % 2 !== 0) {
      throw new RangeError('Buffer size must be a multiple of 16-bits')
    }

    for (let i = 0; i < length; i += 2) swap(this, i, i + 1)

    return this
  }

  swap32() {
    const length = this.byteLength

    if (length % 4 !== 0) {
      throw new RangeError('Buffer size must be a multiple of 32-bits')
    }

    for (let i = 0; i < length; i += 4) {
      swap(this, i, i + 3)
      swap(this, i + 1, i + 2)
    }

    return this
  }

  swap64() {
    const length = this.byteLength

    if (length % 8 !== 0) {
      throw new RangeError('Buffer size must be a multiple of 64-bits')
    }

    for (let i = 0; i < length; i += 8) {
      swap(this, i, i + 7)
      swap(this, i + 1, i + 6)
      swap(this, i + 2, i + 5)
      swap(this, i + 3, i + 4)
    }

    return this
  }

  toString(encoding = 'utf8', start = 0, end = this.byteLength) {
    // toString()
    if (arguments.length === 0) return utf8.toString(this)

    // toString(encoding)
    if (arguments.length === 1) return codecFor(encoding).toString(this)

    if (start < 0) start = 0
    if (start >= this.byteLength) return ''

    if (end <= start) return ''
    if (end > this.byteLength) end = this.byteLength

    let buffer = this

    if (start !== 0 || end !== this.byteLength) {
      buffer = buffer.subarray(start, end)
    }

    return codecFor(encoding).toString(buffer)
  }

  toJSON() {
    return Array.from(this)
  }

  write(string, offset = 0, length = this.byteLength - offset, encoding = 'utf8') {
    // write(string)
    if (arguments.length === 1) return utf8.write(this, string)

    if (typeof offset === 'string') {
      // write(string, encoding)
      encoding = offset
      offset = 0
      length = this.byteLength
    } else if (typeof length === 'string') {
      // write(string, offset, encoding)
      encoding = length
      length = this.byteLength - offset
    }

    length = Math.min(length, exports.byteLength(string, encoding))

    let start = offset
    if (start < 0) start = 0
    if (start >= this.byteLength) return 0

    let end = offset + length
    if (end <= start) return 0
    if (end > this.byteLength) end = this.byteLength

    let buffer = this

    if (start !== 0 || end !== this.byteLength) {
      buffer = buffer.subarray(start, end)
    }

    return codecFor(encoding).write(buffer, string)
  }

  readBigInt64BE(offset = 0) {
    return viewOf(this).getBigInt64(offset, false)
  }
  readBigInt64LE(offset = 0) {
    return viewOf(this).getBigInt64(offset, true)
  }

  readBigUint64BE(offset = 0) {
    return viewOf(this).getBigUint64(offset, false)
  }
  readBigUint64LE(offset = 0) {
    return viewOf(this).getBigUint64(offset, true)
  }

  readDoubleBE(offset = 0) {
    return viewOf(this).getFloat64(offset, false)
  }
  readDoubleLE(offset = 0) {
    return viewOf(this).getFloat64(offset, true)
  }

  readFloatBE(offset = 0) {
    return viewOf(this).getFloat32(offset, false)
  }
  readFloatLE(offset = 0) {
    return viewOf(this).getFloat32(offset, true)
  }

  readInt8(offset = 0) {
    return viewOf(this).getInt8(offset)
  }

  readInt16BE(offset = 0) {
    return viewOf(this).getInt16(offset, false)
  }
  readInt16LE(offset = 0) {
    return viewOf(this).getInt16(offset, true)
  }

  readInt32BE(offset = 0) {
    return viewOf(this).getInt32(offset, false)
  }
  readInt32LE(offset = 0) {
    return viewOf(this).getInt32(offset, true)
  }

  readIntBE(offset, byteLength) {
    if (byteLength === 6) return readInt48BE(viewOf(this), offset)
    if (byteLength === 5) return readInt40BE(viewOf(this), offset)
    if (byteLength === 3) return readInt24BE(viewOf(this), offset)
    if (byteLength === 4) return this.readInt32BE(offset)
    if (byteLength === 2) return this.readInt16BE(offset)
    if (byteLength === 1) return this.readInt8(offset)
    throw new RangeError(`Byte length must be between 1 and 6`)
  }

  readIntLE(offset, byteLength) {
    if (byteLength === 6) return readInt48LE(viewOf(this), offset)
    if (byteLength === 5) return readInt40LE(viewOf(this), offset)
    if (byteLength === 3) return readInt24LE(viewOf(this), offset)
    if (byteLength === 4) return this.readInt32LE(offset)
    if (byteLength === 2) return this.readInt16LE(offset)
    if (byteLength === 1) return this.readInt8(offset)
    throw new RangeError(`Byte length must be between 1 and 6`)
  }

  readUint8(offset = 0) {
    return viewOf(this).getUint8(offset)
  }

  readUint16BE(offset = 0) {
    return viewOf(this).getUint16(offset, false)
  }
  readUint16LE(offset = 0) {
    return viewOf(this).getUint16(offset, true)
  }

  readUint32BE(offset = 0) {
    return viewOf(this).getUint32(offset, false)
  }
  readUint32LE(offset = 0) {
    return viewOf(this).getUint32(offset, true)
  }

  readUintBE(offset, byteLength) {
    if (byteLength === 6) return readUint48BE(viewOf(this), offset)
    if (byteLength === 5) return readUint40BE(viewOf(this), offset)
    if (byteLength === 3) return readUint24BE(viewOf(this), offset)
    if (byteLength === 4) return this.readUint32BE(offset)
    if (byteLength === 2) return this.readUint16BE(offset)
    if (byteLength === 1) return this.readUint8(offset)
    throw new RangeError(`Byte length must be between 1 and 6`)
  }

  readUintLE(offset, byteLength) {
    if (byteLength === 6) return readUint48LE(viewOf(this), offset)
    if (byteLength === 5) return readUint40LE(viewOf(this), offset)
    if (byteLength === 3) return readUint24LE(viewOf(this), offset)
    if (byteLength === 4) return this.readUint32LE(offset)
    if (byteLength === 2) return this.readUint16LE(offset)
    if (byteLength === 1) return this.readUint8(offset)
    throw new RangeError(`Byte length must be between 1 and 6`)
  }

  readBigUInt64BE(...args) {
    return this.readBigUint64BE(...args)
  }
  readBigUInt64LE(...args) {
    return this.readBigUint64LE(...args)
  }

  readUInt8(...args) {
    return this.readUint8(...args)
  }

  readUInt16BE(...args) {
    return this.readUint16BE(...args)
  }
  readUInt16LE(...args) {
    return this.readUint16LE(...args)
  }

  readUInt32BE(...args) {
    return this.readUint32BE(...args)
  }
  readUInt32LE(...args) {
    return this.readUint32LE(...args)
  }

  readUIntBE(...args) {
    return this.readUintBE(...args)
  }
  readUIntLE(...args) {
    return this.readUintLE(...args)
  }

  writeBigInt64BE(value, offset = 0) {
    viewOf(this).setBigInt64(offset, value, false)
    return offset + 8
  }
  writeBigInt64LE(value, offset = 0) {
    viewOf(this).setBigInt64(offset, value, true)
    return offset + 8
  }

  writeBigUint64BE(value, offset = 0) {
    viewOf(this).setBigUint64(offset, value, false)
    return offset + 8
  }
  writeBigUint64LE(value, offset = 0) {
    viewOf(this).setBigUint64(offset, value, true)
    return offset + 8
  }

  writeDoubleBE(value, offset = 0) {
    viewOf(this).setFloat64(offset, value, false)
    return offset + 8
  }
  writeDoubleLE(value, offset = 0) {
    viewOf(this).setFloat64(offset, value, true)
    return offset + 8
  }

  writeFloatBE(value, offset = 0) {
    viewOf(this).setFloat32(offset, value, false)
    return offset + 4
  }
  writeFloatLE(value, offset = 0) {
    viewOf(this).setFloat32(offset, value, true)
    return offset + 4
  }

  writeInt8(value, offset = 0) {
    viewOf(this).setInt8(offset, value)
    return offset + 1
  }

  writeInt16BE(value, offset = 0) {
    viewOf(this).setInt16(offset, value, false)
    return offset + 2
  }
  writeInt16LE(value, offset = 0) {
    viewOf(this).setInt16(offset, value, true)
    return offset + 2
  }

  writeInt32BE(value, offset = 0) {
    viewOf(this).setInt32(offset, value, false)
    return offset + 4
  }
  writeInt32LE(value, offset = 0) {
    viewOf(this).setInt32(offset, value, true)
    return offset + 4
  }

  writeIntBE(value, offset, byteLength) {
    if (byteLength === 6) return writeInt48BE(value, viewOf(this), offset)
    if (byteLength === 5) return writeInt40BE(value, viewOf(this), offset)
    if (byteLength === 3) return writeInt24BE(value, viewOf(this), offset)
    if (byteLength === 4) return this.writeInt32BE(value, offset)
    if (byteLength === 2) return this.writeInt16BE(value, offset)
    if (byteLength === 1) return this.writeInt8(value, offset)
    throw new RangeError(`Byte length must be between 1 and 6`)
  }

  writeIntLE(value, offset, byteLength) {
    if (byteLength === 6) return writeInt48LE(value, viewOf(this), offset)
    if (byteLength === 5) return writeInt40LE(value, viewOf(this), offset)
    if (byteLength === 3) return writeInt24LE(value, viewOf(this), offset)
    if (byteLength === 4) return this.writeInt32LE(value, offset)
    if (byteLength === 2) return this.writeInt16LE(value, offset)
    if (byteLength === 1) return this.writeInt8(value, offset)
    throw new RangeError(`Byte length must be between 1 and 6`)
  }

  writeUint8(value, offset = 0) {
    viewOf(this).setUint8(offset, value, true)
    return offset + 1
  }

  writeUint16BE(value, offset = 0) {
    viewOf(this).setUint16(offset, value, false)
    return offset + 2
  }
  writeUint16LE(value, offset = 0) {
    viewOf(this).setUint16(offset, value, true)
    return offset + 2
  }

  writeUint32LE(value, offset = 0) {
    viewOf(this).setUint32(offset, value, true)
    return offset + 4
  }
  writeUint32BE(value, offset = 0) {
    viewOf(this).setUint32(offset, value, false)
    return offset + 4
  }

  writeUintBE(value, offset, byteLength) {
    if (byteLength === 6) return writeUint48BE(value, viewOf(this), offset)
    if (byteLength === 5) return writeUint40BE(value, viewOf(this), offset)
    if (byteLength === 3) return writeUint24BE(value, viewOf(this), offset)
    if (byteLength === 4) return this.writeUint32BE(value, offset)
    if (byteLength === 2) return this.writeUint16BE(value, offset)
    if (byteLength === 1) return this.writeUint8(value, offset)
    throw new RangeError(`Byte length must be between 1 and 6`)
  }

  writeUintLE(value, offset, byteLength) {
    if (byteLength === 6) return writeUint48LE(value, viewOf(this), offset)
    if (byteLength === 5) return writeUint40LE(value, viewOf(this), offset)
    if (byteLength === 3) return writeUint24LE(value, viewOf(this), offset)
    if (byteLength === 4) return this.writeUint32LE(value, offset)
    if (byteLength === 2) return this.writeUint16LE(value, offset)
    if (byteLength === 1) return this.writeUint8(value, offset)
    throw new RangeError(`Byte length must be between 1 and 6`)
  }

  writeBigUInt64BE(...args) {
    return this.writeBigUint64BE(...args)
  }
  writeBigUInt64LE(...args) {
    return this.writeBigUint64LE(...args)
  }

  writeUInt8(...args) {
    return this.writeUint8(...args)
  }

  writeUInt16BE(...args) {
    return this.writeUint16BE(...args)
  }
  writeUInt16LE(...args) {
    return this.writeUint16LE(...args)
  }

  writeUInt32BE(...args) {
    return this.writeUint32BE(...args)
  }
  writeUInt32LE(...args) {
    return this.writeUint32LE(...args)
  }

  writeUIntBE(...args) {
    return this.writeUintBE(...args)
  }
  writeUIntLE(...args) {
    return this.writeUintLE(...args)
  }
}

const Buffer = exports

exports.Buffer = Buffer // For Node.js compatibility

exports.constants = constants

const codecs = Object.create(null)

codecs.ascii = ascii
codecs.base64 = base64
codecs.base64url = base64url
codecs.hex = hex
codecs.utf8 = codecs['utf-8'] = utf8
codecs.utf16le = codecs.ucs2 = codecs['utf-16le'] = codecs['ucs-2'] = utf16le
codecs.latin1 = codecs.binary = latin1

function codecFor(encoding = 'utf8') {
  if (encoding in codecs) return codecs[encoding]

  encoding = encoding.toLowerCase()

  if (encoding in codecs) return codecs[encoding]

  throw new Error(`Unknown encoding '${encoding}'`)
}

const views = new WeakMap()

function viewOf(buffer) {
  let view = views.get(buffer)
  if (view === undefined) {
    view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength)
    views.set(buffer, view)
  }
  return view
}

exports.isBuffer = function isBuffer(value) {
  if (value instanceof Buffer) return true

  return typeof value === 'object' && value !== null && value[kind] === Buffer[kind]
}

exports.isEncoding = function isEncoding(encoding) {
  try {
    codecFor(encoding)
    return true
  } catch {
    return false
  }
}

exports.isASCII = function isASCII(buffer) {
  return ascii.validate(buffer)
}

// for Node.js compatibily
exports.isAscii = exports.isASCII

exports.isUTF8 = function isUTF8(buffer) {
  return utf8.validate(buffer)
}

// for Node.js compatibility
exports.isUtf8 = exports.isUTF8

exports.alloc = function alloc(size, fill, encoding) {
  const buffer = new Buffer(size)
  if (fill !== undefined) buffer.fill(fill, 0, buffer.byteLength, encoding)
  return buffer
}

exports.allocUnsafe = function allocUnsafe(size) {
  return new Buffer(size, { uninitialized: true })
}

exports.allocUnsafeSlow = function allocUnsafeSlow(size) {
  return exports.allocUnsafe(size)
}

exports.byteLength = function byteLength(string, encoding) {
  if (typeof string === 'string') {
    return codecFor(encoding).byteLength(string)
  }

  return string.byteLength
}

exports.compare = function compare(a, b) {
  return binding.compare(a.buffer, a.byteOffset, a.byteLength, b.buffer, b.byteOffset, b.byteLength)
}

exports.concat = function concat(buffers, length) {
  if (length === undefined) {
    length = buffers.reduce((length, buffer) => length + buffer.byteLength, 0)
  }

  const result = new Buffer(length)

  for (let i = 0, n = buffers.length, offset = 0; i < n; i++) {
    const buffer = buffers[i]

    if (offset + buffer.byteLength > result.byteLength) {
      result.set(buffer.subarray(0, result.byteLength - offset), offset)
      return result
    }

    result.set(buffer, offset)
    offset += buffer.byteLength
  }

  return result
}

exports.coerce = function coerce(buffer) {
  if (exports.isBuffer(buffer)) return buffer
  return new Buffer(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

exports.copyBytesFrom = function copyBytesFrom(view, offset = 0, length = view.length - offset) {
  if (offset + length > view.length) {
    throw new RangeError('View length is out of range')
  }

  if (offset !== 0 || length !== view.length) {
    view = view.subarray(offset, offset + length)
  }

  return new Buffer(view.buffer.slice(view.byteOffset, view.byteOffset + view.byteLength))
}

exports.from = function from(value, encodingOrOffset, length) {
  // from(string, encoding)
  if (typeof value === 'string') return fromString(value, encodingOrOffset)

  // from(array)
  if (Array.isArray(value)) return fromArray(value)

  // from(buffer)
  if (ArrayBuffer.isView(value)) return fromBuffer(value)

  // from(arrayBuffer[, offset[, length]])
  return fromArrayBuffer(value, encodingOrOffset, length)
}

function fromString(string, encoding) {
  const codec = codecFor(encoding)
  const buffer = new Buffer(codec.byteLength(string))
  codec.write(buffer, string)
  return buffer
}

function fromArray(array) {
  const buffer = new Buffer(array.length)
  buffer.set(array)
  return buffer
}

function fromBuffer(buffer) {
  const copy = new Buffer(buffer.byteLength)
  copy.set(buffer)
  return copy
}

function fromArrayBuffer(arrayBuffer, offset, length) {
  return new Buffer(arrayBuffer, offset, length)
}

function bidirectionalIndexOf(buffer, value, offset, encoding, first) {
  if (buffer.byteLength === 0) return -1

  if (typeof offset === 'string') {
    encoding = offset
    offset = 0
  } else if (offset === undefined) {
    offset = first ? 0 : buffer.byteLength - 1
  } else if (offset < 0) {
    offset += buffer.byteLength
  }

  if (offset >= buffer.byteLength) {
    if (first) return -1
    else offset = buffer.byteLength - 1
  } else if (offset < 0) {
    if (first) offset = 0
    else return -1
  }

  if (typeof value === 'string') value = exports.from(value, encoding)

  if (value.byteLength === 0) return -1

  if (first) {
    let foundIndex = -1

    for (let i = offset; i < buffer.byteLength; i++) {
      if (buffer[i] === value[foundIndex === -1 ? 0 : i - foundIndex]) {
        if (foundIndex === -1) foundIndex = i
        if (i - foundIndex + 1 === value.byteLength) return foundIndex
      } else {
        if (foundIndex !== -1) i -= i - foundIndex
        foundIndex = -1
      }
    }
  } else {
    if (offset + value.byteLength > buffer.byteLength) {
      offset = buffer.byteLength - value.byteLength
    }

    for (let i = offset; i >= 0; i--) {
      let found = true

      for (let j = 0; j < value.byteLength; j++) {
        if (buffer[i + j] !== value[j]) {
          found = false
          break
        }
      }

      if (found) return i
    }
  }

  return -1
}

function swap(buffer, n, m) {
  const i = buffer[n]
  buffer[n] = buffer[m]
  buffer[m] = i
}

exports.atob = function atob(data) {
  return Buffer.from(data, 'base64').toString('latin1')
}

exports.btoa = function btoa(data) {
  if (typeof data !== 'string') data = String(data)

  return Buffer.from(data, 'latin1').toString('base64')
}

exports.transcode = function transcode(buffer, from, to) {
  return Buffer.from(buffer.toString(from), to)
}

function readInt48BE(view, offset) {
  const hi = view.getUint16(offset, false)
  const lo = view.getUint32(offset + 2, false)
  let value = lo + hi * 0x100000000
  if (hi & 0x8000) value -= 0x1000000000000
  return value
}

function readInt48LE(view, offset) {
  const lo = view.getUint32(offset, true)
  const hi = view.getUint16(offset + 4, true)
  let value = lo + hi * 0x100000000
  if (hi & 0x8000) value -= 0x1000000000000
  return value
}

function readInt40BE(view, offset) {
  const hi = view.getUint8(offset)
  const lo = view.getUint32(offset + 1, false)
  let value = lo + hi * 0x100000000
  if (hi & 0x80) value -= 0x10000000000
  return value
}

function readInt40LE(view, offset) {
  const lo = view.getUint32(offset, true)
  const hi = view.getUint8(offset + 4)
  let value = lo + hi * 0x100000000
  if (hi & 0x80) value -= 0x10000000000
  return value
}

function readInt24BE(view, offset) {
  const value =
    (view.getUint8(offset) << 16) | (view.getUint8(offset + 1) << 8) | view.getUint8(offset + 2)
  return value & 0x800000 ? value - 0x1000000 : value
}

function readInt24LE(view, offset) {
  const value =
    view.getUint8(offset) | (view.getUint8(offset + 1) << 8) | (view.getUint8(offset + 2) << 16)
  return value & 0x800000 ? value - 0x1000000 : value
}

function readUint48BE(view, offset) {
  const hi = view.getUint16(offset, false)
  const lo = view.getUint32(offset + 2, false)
  return lo + hi * 0x100000000
}

function readUint48LE(view, offset) {
  const lo = view.getUint32(offset, true)
  const hi = view.getUint16(offset + 4, true)
  return lo + hi * 0x100000000
}

function readUint40BE(view, offset) {
  const hi = view.getUint8(offset)
  const lo = view.getUint32(offset + 1, false)
  return lo + hi * 0x100000000
}

function readUint40LE(view, offset) {
  const lo = view.getUint32(offset, true)
  const hi = view.getUint8(offset + 4)
  return lo + hi * 0x100000000
}

function readUint24BE(view, offset) {
  return (
    (view.getUint8(offset) << 16) | (view.getUint8(offset + 1) << 8) | view.getUint8(offset + 2)
  )
}

function readUint24LE(view, offset) {
  return (
    view.getUint8(offset) | (view.getUint8(offset + 1) << 8) | (view.getUint8(offset + 2) << 16)
  )
}

function writeInt48BE(value, view, offset) {
  if (value < 0) value += 0x1000000000000
  const hi = Math.floor(value / 0x100000000)
  const lo = value >>> 0
  view.setUint16(offset, hi, false)
  view.setUint32(offset + 2, lo, false)
  return offset + 6
}

function writeInt48LE(value, view, offset) {
  if (value < 0) value += 0x1000000000000
  const hi = Math.floor(value / 0x100000000)
  const lo = value >>> 0
  view.setUint32(offset, lo, true)
  view.setUint16(offset + 4, hi, true)
  return offset + 6
}

function writeInt40BE(value, view, offset) {
  if (value < 0) value += 0x10000000000
  const hi = Math.floor(value / 0x100000000)
  const lo = value >>> 0
  view.setUint8(offset, hi)
  view.setUint32(offset + 1, lo, false)
  return offset + 5
}

function writeInt40LE(value, view, offset) {
  if (value < 0) value += 0x10000000000
  const hi = Math.floor(value / 0x100000000)
  const lo = value >>> 0
  view.setUint32(offset, lo, true)
  view.setUint8(offset + 4, hi)
  return offset + 5
}

function writeInt24BE(value, view, offset) {
  if (value < 0) value += 0x1000000
  view.setUint8(offset, (value >> 16) & 0xff)
  view.setUint8(offset + 1, (value >> 8) & 0xff)
  view.setUint8(offset + 2, value & 0xff)
  return offset + 3
}

function writeInt24LE(value, view, offset) {
  if (value < 0) value += 0x1000000
  view.setUint8(offset, value & 0xff)
  view.setUint8(offset + 1, (value >> 8) & 0xff)
  view.setUint8(offset + 2, (value >> 16) & 0xff)
  return offset + 3
}

function writeUint48BE(value, view, offset) {
  const hi = Math.floor(value / 0x100000000)
  const lo = value >>> 0
  view.setUint16(offset, hi, false)
  view.setUint32(offset + 2, lo, false)
  return offset + 6
}

function writeUint48LE(value, view, offset) {
  const hi = Math.floor(value / 0x100000000)
  const lo = value >>> 0
  view.setUint32(offset, lo, true)
  view.setUint16(offset + 4, hi, true)
  return offset + 6
}

function writeUint40BE(value, view, offset) {
  const hi = Math.floor(value / 0x100000000)
  const lo = value >>> 0
  view.setUint8(offset, hi)
  view.setUint32(offset + 1, lo, false)
  return offset + 5
}

function writeUint40LE(value, view, offset) {
  const hi = Math.floor(value / 0x100000000)
  const lo = value >>> 0
  view.setUint32(offset, lo, true)
  view.setUint8(offset + 4, hi)
  return offset + 5
}

function writeUint24BE(value, view, offset) {
  view.setUint8(offset, (value >> 16) & 0xff)
  view.setUint8(offset + 1, (value >> 8) & 0xff)
  view.setUint8(offset + 2, value & 0xff)
  return offset + 3
}

function writeUint24LE(value, view, offset) {
  view.setUint8(offset, value & 0xff)
  view.setUint8(offset + 1, (value >> 8) & 0xff)
  view.setUint8(offset + 2, (value >> 16) & 0xff)
  return offset + 3
}
const binding = require('../binding')

exports.byteLength = function byteLength(string) {
  return string.length
}

exports.toString = function toString(buffer) {
  const len = buffer.byteLength

  let result = ''

  for (let i = 0; i < len; i++) {
    result += String.fromCharCode(buffer[i] & 0x7f)
  }

  return result
}

exports.write = function write(buffer, string) {
  const len = buffer.byteLength

  for (let i = 0; i < len; i++) {
    buffer[i] = string.charCodeAt(i)
  }

  return len
}

exports.validate = function validate(buffer) {
  return binding.validateAscii(buffer.buffer, buffer.byteLength)
}
const binding = require('../binding')

exports.byteLength = function byteLength(string) {
  let len = string.length

  if (string.charCodeAt(len - 1) === 0x3d) len--
  if (len > 1 && string.charCodeAt(len - 1) === 0x3d) len--

  return (len * 3) >>> 2
}

exports.toString = function toString(buffer) {
  return binding.toStringBase64(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

exports.write = function write(buffer, string) {
  return binding.writeBase64(buffer.buffer, buffer.byteOffset, buffer.byteLength, string)
}
const binding = require('../binding')

exports.byteLength = function byteLength(string) {
  let len = string.length

  if (string.charCodeAt(len - 1) === 0x3d) len--
  if (len > 1 && string.charCodeAt(len - 1) === 0x3d) len--

  return (len * 3) >>> 2
}

exports.toString = function toString(buffer) {
  return binding.toStringBase64URL(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

exports.write = function write(buffer, string) {
  return binding.writeBase64(buffer.buffer, buffer.byteOffset, buffer.byteLength, string)
}
const binding = require('../binding')

module.exports = binding.constants
const binding = require('../binding')

exports.byteLength = function byteLength(string) {
  return string.length >>> 1
}

exports.toString = function toString(buffer) {
  return binding.toStringHex(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

exports.write = function write(buffer, string) {
  return binding.writeHex(buffer.buffer, buffer.byteOffset, buffer.byteLength, string)
}
const binding = require('../binding')

exports.byteLength = function byteLength(string) {
  return string.length
}

exports.toString = function toString(buffer) {
  return binding.toStringLatin1(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

exports.write = function write(buffer, string) {
  return binding.writeLatin1(buffer.buffer, buffer.byteOffset, buffer.byteLength, string)
}
const binding = require('../binding')

exports.byteLength = function byteLength(string) {
  return string.length * 2
}

exports.toString = function toString(buffer) {
  return binding.toStringUTF16LE(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

exports.write = function write(buffer, string) {
  return binding.writeUTF16LE(buffer.buffer, buffer.byteOffset, buffer.byteLength, string)
}
const binding = require('../binding')

exports.byteLength = function byteLength(string) {
  return binding.byteLengthUTF8(string)
}

exports.toString = function toString(buffer) {
  return binding.toStringUTF8(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

exports.write = function write(buffer, string) {
  return binding.writeUTF8(buffer.buffer, buffer.byteOffset, buffer.byteLength, string)
}

exports.validate = function validate(buffer) {
  return binding.validateUTF8(buffer.buffer, buffer.byteLength)
}
{
  "name": "bare-buffer",
  "version": "3.6.2",
  "description": "Native buffers for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    },
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "global.js",
    "global.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-buffer.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-buffer/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-buffer#readme",
  "engines": {
    "bare": ">=1.20.0"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "cmake-bare": "^1.1.6",
    "cmake-fetch": "^1.0.0",
    "lunte": "^1.8.0",
    "prettier": "^3.3.3",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = require.addon()
const binding = require('./binding')
const constants = require('./lib/constants')
const errors = require('./lib/errors')
const DNSResolver = require('./lib/resolver')

exports.Resolver = DNSResolver

function onlookup(err, addresses) {
  const req = this

  if (err) return req.cb(err, null, 0)

  const { address, family } = addresses[0]

  return req.cb(null, address, family)
}

function onlookupall(err, addresses) {
  const req = this

  if (err) return req.cb(err, null)

  return req.cb(null, addresses)
}

exports.lookup = function lookup(hostname, opts = {}, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  let { family = 0, all = false } = opts

  if (typeof family === 'string') {
    switch (family) {
      case 'IPv4':
        family = 4
        break
      case 'IPv6':
        family = 6
        break
      default:
        family = 0
    }
  }

  const req = {
    cb,
    handle: null
  }

  req.handle = binding.lookup(hostname, family || 0, all, req, all ? onlookupall : onlookup)
}

exports.getServers = function getServers() {
  return DNSResolver.global.getServers()
}

exports.setServers = function setServers(servers) {
  return DNSResolver.global.setServers(servers)
}

exports.setLocalAddress = function setLocalAddress(ipv4, ipv6) {
  return DNSResolver.global.setLocalAddress(ipv4, ipv6)
}

exports.cancel = function cancel() {
  return DNSResolver.global.cancel()
}

exports.resolve = function resolve(hostname, rrtype, cb) {
  return DNSResolver.global.resolve(hostname, rrtype, cb)
}

exports.resolve4 = function resolve4(hostname, opts, cb) {
  return DNSResolver.global.resolve4(hostname, opts, cb)
}

exports.resolve6 = function resolve6(hostname, opts, cb) {
  return DNSResolver.global.resolve6(hostname, opts, cb)
}

exports.resolveAny = function resolveAny(hostname, cb) {
  return DNSResolver.global.resolveAny(hostname, cb)
}

exports.resolveCaa = function resolveCaa(hostname, cb) {
  return DNSResolver.global.resolveCaa(hostname, cb)
}

exports.resolveCname = function resolveCname(hostname, cb) {
  return DNSResolver.global.resolveCname(hostname, cb)
}

exports.resolveMx = function resolveMx(hostname, cb) {
  return DNSResolver.global.resolveMx(hostname, cb)
}

exports.resolveNaptr = function resolveNaptr(hostname, cb) {
  return DNSResolver.global.resolveNaptr(hostname, cb)
}

exports.resolveNs = function resolveNs(hostname, cb) {
  return DNSResolver.global.resolveNs(hostname, cb)
}

exports.resolvePtr = function resolvePtr(hostname, cb) {
  return DNSResolver.global.resolvePtr(hostname, cb)
}

exports.resolveSoa = function resolveSoa(hostname, cb) {
  return DNSResolver.global.resolveSoa(hostname, cb)
}

exports.resolveSrv = function resolveSrv(hostname, cb) {
  return DNSResolver.global.resolveSrv(hostname, cb)
}

exports.resolveTlsa = function resolveTlsa(hostname, cb) {
  return DNSResolver.global.resolveTlsa(hostname, cb)
}

exports.resolveTxt = function resolveTxt(hostname, cb) {
  return DNSResolver.global.resolveTxt(hostname, cb)
}

exports.reverse = function reverse(ip, cb) {
  return DNSResolver.global.reverse(ip, cb)
}

exports.constants = constants
exports.errors = errors
exports.promises = require('./lib/promises')
// Resource record types, as understood by the underlying resolver.
exports.type = {
  A: 1,
  NS: 2,
  CNAME: 5,
  SOA: 6,
  PTR: 12,
  HINFO: 13,
  MX: 15,
  TXT: 16,
  SIG: 24,
  AAAA: 28,
  SRV: 33,
  NAPTR: 35,
  OPT: 41,
  TLSA: 52,
  SVCB: 64,
  HTTPS: 65,
  ANY: 255,
  URI: 256,
  CAA: 257
}

// Resolver status codes, indexed to match the values reported by the binding.
exports.status = {
  SUCCESS: 0,
  ENODATA: 1,
  EFORMERR: 2,
  ESERVFAIL: 3,
  ENOTFOUND: 4,
  ENOTIMP: 5,
  EREFUSED: 6,
  EBADQUERY: 7,
  EBADNAME: 8,
  EBADFAMILY: 9,
  EBADRESP: 10,
  ECONNREFUSED: 11,
  ETIMEOUT: 12,
  EOF: 13,
  EFILE: 14,
  ENOMEM: 15,
  EDESTRUCTION: 16,
  EBADSTR: 17,
  EBADFLAGS: 18,
  ENONAME: 19,
  EBADHINTS: 20,
  ENOTINITIALIZED: 21,
  ELOADIPHLPAPI: 22,
  EADDRGETNETWORKPARAMS: 23,
  ECANCELLED: 24,
  ESERVICE: 25,
  ENOSERVER: 26
}
const constants = require('./constants')

// The status codes indexed by their value, for turning the status a query
// reports into the code its error carries.
const codes = []

for (const [name, value] of Object.entries(constants.status)) {
  codes[value] = name
}

module.exports = class DNSError extends Error {
  constructor(msg, fn = DNSError, code = fn.name) {
    super(`${code}: ${msg}`)

    this.code = code

    if (Error.captureStackTrace) Error.captureStackTrace(this, fn)
  }

  get name() {
    return 'DNSError'
  }

  static RESOLVER_DESTROYED(msg = 'Resolver is destroyed') {
    return new DNSError(msg, DNSError.RESOLVER_DESTROYED)
  }

  static UNKNOWN_RECORD_TYPE(msg = 'Unknown resource record type') {
    return new DNSError(msg, DNSError.UNKNOWN_RECORD_TYPE)
  }

  static INVALID_IP_ADDRESS(msg = 'Invalid IP address') {
    return new DNSError(msg, DNSError.INVALID_IP_ADDRESS)
  }

  static query(status, syscall, hostname = null) {
    const code = codes[status] || 'UNKNOWN'

    const err = new DNSError(
      `${syscall}` + (hostname === null ? '' : ` ${hostname}`),
      DNSError.query,
      code
    )

    err.syscall = syscall

    if (hostname !== null) err.hostname = hostname

    return err
  }
}
const constants = require('./constants')
const errors = require('./errors')
const DNSResolver = require('./resolver')

class DNSPromiseResolver {
  constructor(opts) {
    this._resolver = new DNSResolver(opts)
  }

  getServers() {
    return this._resolver.getServers()
  }

  setServers(servers) {
    return this._resolver.setServers(servers)
  }

  setLocalAddress(ipv4, ipv6) {
    return this._resolver.setLocalAddress(ipv4, ipv6)
  }

  cancel() {
    return this._resolver.cancel()
  }

  destroy() {
    return this._resolver.destroy()
  }

  resolve(hostname, rrtype) {
    return promisify(this._resolver, 'resolve', hostname, rrtype)
  }

  resolve4(hostname, opts) {
    return promisify(this._resolver, 'resolve4', hostname, opts)
  }

  resolve6(hostname, opts) {
    return promisify(this._resolver, 'resolve6', hostname, opts)
  }

  resolveAny(hostname) {
    return promisify(this._resolver, 'resolveAny', hostname)
  }

  resolveCaa(hostname) {
    return promisify(this._resolver, 'resolveCaa', hostname)
  }

  resolveCname(hostname) {
    return promisify(this._resolver, 'resolveCname', hostname)
  }

  resolveMx(hostname) {
    return promisify(this._resolver, 'resolveMx', hostname)
  }

  resolveNaptr(hostname) {
    return promisify(this._resolver, 'resolveNaptr', hostname)
  }

  resolveNs(hostname) {
    return promisify(this._resolver, 'resolveNs', hostname)
  }

  resolvePtr(hostname) {
    return promisify(this._resolver, 'resolvePtr', hostname)
  }

  resolveSoa(hostname) {
    return promisify(this._resolver, 'resolveSoa', hostname)
  }

  resolveSrv(hostname) {
    return promisify(this._resolver, 'resolveSrv', hostname)
  }

  resolveTlsa(hostname) {
    return promisify(this._resolver, 'resolveTlsa', hostname)
  }

  resolveTxt(hostname) {
    return promisify(this._resolver, 'resolveTxt', hostname)
  }

  reverse(ip) {
    return promisify(this._resolver, 'reverse', ip)
  }

  static global = new this()
}

function promisify(resolver, method, ...args) {
  return new Promise((resolve, reject) => {
    resolver[method](...args, (err, result) => {
      if (err) reject(err)
      else resolve(result)
    })
  })
}

exports.Resolver = DNSPromiseResolver

exports.lookup = function lookup(hostname, opts = {}) {
  const dns = require('../')

  return new Promise((resolve, reject) => {
    if (opts && opts.all) {
      dns.lookup(hostname, opts, (err, addresses) => {
        if (err) reject(err)
        else resolve(addresses)
      })
    } else {
      dns.lookup(hostname, opts, (err, address, family) => {
        if (err) reject(err)
        else resolve({ address, family })
      })
    }
  })
}

exports.getServers = function getServers() {
  return DNSPromiseResolver.global.getServers()
}

exports.setServers = function setServers(servers) {
  return DNSPromiseResolver.global.setServers(servers)
}

exports.setLocalAddress = function setLocalAddress(ipv4, ipv6) {
  return DNSPromiseResolver.global.setLocalAddress(ipv4, ipv6)
}

exports.cancel = function cancel() {
  return DNSPromiseResolver.global.cancel()
}

exports.resolve = function resolve(hostname, rrtype) {
  return DNSPromiseResolver.global.resolve(hostname, rrtype)
}

exports.resolve4 = function resolve4(hostname, opts) {
  return DNSPromiseResolver.global.resolve4(hostname, opts)
}

exports.resolve6 = function resolve6(hostname, opts) {
  return DNSPromiseResolver.global.resolve6(hostname, opts)
}

exports.resolveAny = function resolveAny(hostname) {
  return DNSPromiseResolver.global.resolveAny(hostname)
}

exports.resolveCaa = function resolveCaa(hostname) {
  return DNSPromiseResolver.global.resolveCaa(hostname)
}

exports.resolveCname = function resolveCname(hostname) {
  return DNSPromiseResolver.global.resolveCname(hostname)
}

exports.resolveMx = function resolveMx(hostname) {
  return DNSPromiseResolver.global.resolveMx(hostname)
}

exports.resolveNaptr = function resolveNaptr(hostname) {
  return DNSPromiseResolver.global.resolveNaptr(hostname)
}

exports.resolveNs = function resolveNs(hostname) {
  return DNSPromiseResolver.global.resolveNs(hostname)
}

exports.resolvePtr = function resolvePtr(hostname) {
  return DNSPromiseResolver.global.resolvePtr(hostname)
}

exports.resolveSoa = function resolveSoa(hostname) {
  return DNSPromiseResolver.global.resolveSoa(hostname)
}

exports.resolveSrv = function resolveSrv(hostname) {
  return DNSPromiseResolver.global.resolveSrv(hostname)
}

exports.resolveTlsa = function resolveTlsa(hostname) {
  return DNSPromiseResolver.global.resolveTlsa(hostname)
}

exports.resolveTxt = function resolveTxt(hostname) {
  return DNSPromiseResolver.global.resolveTxt(hostname)
}

exports.reverse = function reverse(ip) {
  return DNSPromiseResolver.global.reverse(ip)
}

exports.constants = constants
exports.errors = errors
// Shapes a parsed DNS record into the result each `resolve*()` method returns.
// The binding hands back every field a record type carries, named as the
// resolver names it.

function answers(record, type) {
  const result = []

  for (const rr of record.answers) {
    if (rr.type === type) result.push(rr)
  }

  return result
}

function string(value) {
  return value === null ? '' : Buffer.from(value).toString()
}

function buffer(value) {
  return value === null ? Buffer.alloc(0) : Buffer.from(value)
}

// Each shape returns `null` when the answer section holds no record of the
// requested type, which the caller reports as `ENODATA`.
function list(type, fn) {
  return (record) => {
    const rrs = answers(record, type)

    return rrs.length === 0 ? null : rrs.map(fn)
  }
}

const address = (rr) => rr.addr
const addressWithTTL = (rr) => ({ address: rr.addr, ttl: rr.ttl })

exports.a = (ttl) => list('A', ttl ? addressWithTTL : address)
exports.aaaa = (ttl) => list('AAAA', ttl ? addressWithTTL : address)

exports.cname = list('CNAME', (rr) => rr.cname)
exports.ns = list('NS', (rr) => rr.nsdname)
exports.ptr = list('PTR', (rr) => rr.dname)
exports.txt = list('TXT', (rr) => rr.data)

exports.mx = list('MX', (rr) => ({
  priority: rr.preference,
  exchange: rr.exchange
}))

exports.srv = list('SRV', (rr) => ({
  priority: rr.priority,
  weight: rr.weight,
  port: rr.port,
  name: rr.target
}))

exports.naptr = list('NAPTR', (rr) => ({
  flags: rr.flags,
  service: rr.services,
  regexp: rr.regexp,
  replacement: rr.replacement,
  order: rr.order,
  preference: rr.preference
}))

exports.caa = list('CAA', (rr) => ({
  critical: rr.critical,
  [rr.tag]: string(rr.value)
}))

exports.tlsa = list('TLSA', (rr) => ({
  certUsage: rr.cert_usage,
  selector: rr.selector,
  match: rr.match,
  data: buffer(rr.data)
}))

// Unlike every other type, a start of authority resolves to a single record
// rather than a list.
exports.soa = (record) => {
  const rrs = answers(record, 'SOA')

  return rrs.length === 0 ? null : soa(rrs[0])
}

function soa(rr) {
  return {
    nsname: rr.mname,
    hostmaster: rr.rname,
    serial: rr.serial,
    refresh: rr.refresh,
    retry: rr.retry,
    expire: rr.expire,
    minttl: rr.minimum
  }
}

// A wildcard query may come back with a mix of record types, each tagged with
// its type so that the caller can tell them apart.
exports.any = (record) => {
  const result = []

  for (const rr of record.answers) {
    switch (rr.type) {
      case 'A':
        result.push({ type: 'A', address: rr.addr, ttl: rr.ttl })
        break
      case 'AAAA':
        result.push({ type: 'AAAA', address: rr.addr, ttl: rr.ttl })
        break
      case 'CNAME':
        result.push({ type: 'CNAME', value: rr.cname })
        break
      case 'NS':
        result.push({ type: 'NS', value: rr.nsdname })
        break
      case 'PTR':
        result.push({ type: 'PTR', value: rr.dname })
        break
      case 'TXT':
        result.push({ type: 'TXT', entries: rr.data })
        break
      case 'MX':
        result.push({ type: 'MX', priority: rr.preference, exchange: rr.exchange })
        break
      case 'SRV':
        result.push({
          type: 'SRV',
          priority: rr.priority,
          weight: rr.weight,
          port: rr.port,
          name: rr.target
        })
        break
      case 'NAPTR':
        result.push({
          type: 'NAPTR',
          flags: rr.flags,
          service: rr.services,
          regexp: rr.regexp,
          replacement: rr.replacement,
          order: rr.order,
          preference: rr.preference
        })
        break
      case 'SOA':
        result.push({ type: 'SOA', ...soa(rr) })
        break
    }
  }

  return result
}
const binding = require('../binding')
const constants = require('./constants')
const errors = require('./errors')
const records = require('./records')

const { type, status } = constants

module.exports = class DNSResolver {
  constructor(opts = {}) {
    const { servers = null, localAddress = null } = opts

    this._handle = binding.initResolver()

    if (servers !== null) this.setServers(servers)

    if (localAddress !== null) {
      this.setLocalAddress(localAddress.ipv4, localAddress.ipv6)
    }
  }

  getServers() {
    if (this._handle === null) throw errors.RESOLVER_DESTROYED()

    const servers = binding.getServers(this._handle)

    return servers === '' ? [] : servers.split(',')
  }

  setServers(servers) {
    if (this._handle === null) throw errors.RESOLVER_DESTROYED()

    binding.setServers(this._handle, servers.join(','))
  }

  setLocalAddress(ipv4 = null, ipv6 = null) {
    if (this._handle === null) throw errors.RESOLVER_DESTROYED()

    binding.setLocalAddress(this._handle, ipv4, ipv6)
  }

  // Aborts every query outstanding on this resolver. Each pending callback is
  // invoked with `ECANCELLED`, releasing the loop.
  cancel() {
    if (this._handle === null) return

    binding.cancel(this._handle)
  }

  // Cancels every query outstanding on this resolver, so that none is left
  // without an answer, and releases the resources it holds.
  destroy() {
    if (this._handle === null) return

    binding.destroyResolver(this._handle)
    this._handle = null
  }

  resolve(hostname, rrtype = 'A', cb = noop) {
    if (typeof rrtype === 'function') {
      cb = rrtype
      rrtype = 'A'
    }

    switch (rrtype) {
      case 'A':
        return this.resolve4(hostname, cb)
      case 'AAAA':
        return this.resolve6(hostname, cb)
      case 'ANY':
        return this.resolveAny(hostname, cb)
      case 'CAA':
        return this.resolveCaa(hostname, cb)
      case 'CNAME':
        return this.resolveCname(hostname, cb)
      case 'MX':
        return this.resolveMx(hostname, cb)
      case 'NAPTR':
        return this.resolveNaptr(hostname, cb)
      case 'NS':
        return this.resolveNs(hostname, cb)
      case 'PTR':
        return this.resolvePtr(hostname, cb)
      case 'SOA':
        return this.resolveSoa(hostname, cb)
      case 'SRV':
        return this.resolveSrv(hostname, cb)
      case 'TLSA':
        return this.resolveTlsa(hostname, cb)
      case 'TXT':
        return this.resolveTxt(hostname, cb)
      default:
        throw errors.UNKNOWN_RECORD_TYPE(`Unknown resource record type '${rrtype}'`)
    }
  }

  resolve4(hostname, opts = {}, cb = noop) {
    if (typeof opts === 'function') {
      cb = opts
      opts = {}
    }

    const { ttl = false } = opts

    this._query(hostname, type.A, 'queryA', records.a(ttl), cb)
  }

  resolve6(hostname, opts = {}, cb = noop) {
    if (typeof opts === 'function') {
      cb = opts
      opts = {}
    }

    const { ttl = false } = opts

    this._query(hostname, type.AAAA, 'queryAaaa', records.aaaa(ttl), cb)
  }

  resolveAny(hostname, cb = noop) {
    this._query(hostname, type.ANY, 'queryAny', records.any, cb)
  }

  resolveCaa(hostname, cb = noop) {
    this._query(hostname, type.CAA, 'queryCaa', records.caa, cb)
  }

  resolveCname(hostname, cb = noop) {
    this._query(hostname, type.CNAME, 'queryCname', records.cname, cb)
  }

  resolveMx(hostname, cb = noop) {
    this._query(hostname, type.MX, 'queryMx', records.mx, cb)
  }

  resolveNaptr(hostname, cb = noop) {
    this._query(hostname, type.NAPTR, 'queryNaptr', records.naptr, cb)
  }

  resolveNs(hostname, cb = noop) {
    this._query(hostname, type.NS, 'queryNs', records.ns, cb)
  }

  resolvePtr(hostname, cb = noop) {
    this._query(hostname, type.PTR, 'queryPtr', records.ptr, cb)
  }

  resolveSoa(hostname, cb = noop) {
    this._query(hostname, type.SOA, 'querySoa', records.soa, cb)
  }

  resolveSrv(hostname, cb = noop) {
    this._query(hostname, type.SRV, 'querySrv', records.srv, cb)
  }

  resolveTlsa(hostname, cb = noop) {
    this._query(hostname, type.TLSA, 'queryTlsa', records.tlsa, cb)
  }

  resolveTxt(hostname, cb = noop) {
    this._query(hostname, type.TXT, 'queryTxt', records.txt, cb)
  }

  // Resolves a pointer record, which is a plain query against the reverse zone
  // for the address. Unlike Node.js, the hosts file is not consulted first, so
  // an address that is only named there does not resolve.
  reverse(ip, cb = noop) {
    let name

    try {
      name = binding.addrToPtr(ip)
    } catch {
      throw errors.INVALID_IP_ADDRESS(`Invalid IP address '${ip}'`)
    }

    this._query(name, type.PTR, 'getHostByAddr', records.ptr, cb, ip)
  }

  _query(name, rrtype, syscall, shape, cb, hostname = name) {
    if (this._handle === null) throw errors.RESOLVER_DESTROYED()

    const req = { hostname, syscall, shape, cb }

    binding.query(this._handle, name, rrtype, req, onquery)
  }

  static global = new this()
}

// The binding hands over an answer on a turn of the loop of its own, including
// one it served from its cache, so a callback never runs before the call that
// issued it.
function onquery(code, record) {
  const req = this

  if (code !== status.SUCCESS) {
    return req.cb(errors.query(code, req.syscall, req.hostname), null)
  }

  const result = req.shape(record)

  if (result === null) {
    return req.cb(errors.query(status.ENODATA, req.syscall, req.hostname), null)
  }

  req.cb(null, result)
}

function noop() {}
{
  "name": "bare-dns",
  "version": "2.2.0",
  "description": "Domain name resolution for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./promises": {
      "types": "./lib/promises.d.ts",
      "default": "./lib/promises.js"
    },
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    },
    "./errors": {
      "types": "./lib/errors.d.ts",
      "default": "./lib/errors.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-dns.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-dns/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-dns",
  "engines": {
    "bare": ">=1.7.0"
  },
  "devDependencies": {
    "bare-buffer": "^3.0.2",
    "bare-dgram": "^1.0.1",
    "brittle": "^3.3.2",
    "cmake-bare": "^1.1.6",
    "cmake-fetch": "^1.3.0",
    "lunte": "^1.8.4",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "bare-buffer": "*"
  },
  "peerDependenciesMeta": {
    "bare-buffer": {
      "optional": true
    }
  }
}
const os = require('bare-os')

module.exports = new Proxy(Object.create(null), {
  ownKeys(target) {
    return os.getEnvKeys()
  },

  get(target, property) {
    if (typeof property !== 'string') return

    return os.getEnv(property)
  },

  has(target, property) {
    if (typeof property !== 'string') return false

    return os.hasEnv(property)
  },

  set(target, property, value) {
    if (typeof property !== 'string') return

    const type = typeof value

    if (type !== 'string' && type !== 'number' && type !== 'boolean') {
      throw new Error('Environment variable must be of type string, number, or boolean')
    }

    value = String(value)

    os.setEnv(property, value)

    return true
  },

  deleteProperty(target, property) {
    if (typeof property !== 'string') return

    os.unsetEnv(property)
  },

  getOwnPropertyDescriptor(target, property) {
    return {
      value: this.get(target, property),
      enumerable: true,
      configurable: true,
      writable: true
    }
  }
})
{
  "name": "bare-env",
  "version": "3.0.1",
  "description": "Environment variable support for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-env.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-env/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-env#readme",
  "dependencies": {
    "bare-os": "^3.0.1"
  },
  "devDependencies": {
    "brittle": "^3.2.1",
    "lunte": "^1.8.3",
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
const errors = require('./lib/errors')

class EventListener {
  constructor() {
    this.list = []
    this.count = 0
  }

  append(ctx, name, fn, once) {
    this.count++
    ctx.emit('newListener', name, fn) // Emit BEFORE adding
    this.list.push([fn, once])
  }

  prepend(ctx, name, fn, once) {
    this.count++
    ctx.emit('newListener', name, fn) // Emit BEFORE adding
    this.list.unshift([fn, once])
  }

  remove(ctx, name, fn) {
    for (let i = 0, n = this.list.length; i < n; i++) {
      const l = this.list[i]

      if (l[0] === fn) {
        this.list.splice(i, 1)

        if (this.count === 1) delete ctx._events[name]

        ctx.emit('removeListener', name, fn) // Emit AFTER removing

        this.count--
        return
      }
    }
  }

  removeAll(ctx, name) {
    const list = [...this.list]
    this.list = []

    if (this.count === list.length) delete ctx._events[name]

    for (let i = list.length - 1; i >= 0; i--) {
      ctx.emit('removeListener', name, list[i][0]) // Emit AFTER removing
    }

    this.count -= list.length
  }

  emit(ctx, name, ...args) {
    const list = [...this.list]

    for (let i = 0, n = list.length; i < n; i++) {
      const l = list[i]

      if (l[1] === true) this.remove(ctx, name, l[0])

      Reflect.apply(l[0], ctx, args)
    }

    return list.length > 0
  }
}

function appendListener(ctx, name, fn, once) {
  if (ctx._events === undefined) ctx._events = Object.create(null)
  const e = ctx._events[name] || (ctx._events[name] = new EventListener())
  e.append(ctx, name, fn, once)
  return ctx
}

function prependListener(ctx, name, fn, once) {
  if (ctx._events === undefined) ctx._events = Object.create(null)
  const e = ctx._events[name] || (ctx._events[name] = new EventListener())
  e.prepend(ctx, name, fn, once)
  return ctx
}

function removeListener(ctx, name, fn) {
  if (ctx._events === undefined) return ctx
  const e = ctx._events[name]
  if (e !== undefined) e.remove(ctx, name, fn)
  return ctx
}

function throwUnhandledError(...args) {
  let err

  if (args.length > 0) err = args[0]

  if (err instanceof Error === false) err = errors.UNHANDLED_ERROR(err)

  if (Error.captureStackTrace) {
    Error.captureStackTrace(err, exports.prototype.emit)
  }

  queueMicrotask(() => {
    throw err
  })
}

module.exports = exports = class EventEmitter {
  constructor() {
    this._events = Object.create(null)
  }

  addListener(name, fn) {
    return appendListener(this, name, fn, false)
  }

  addOnceListener(name, fn) {
    return appendListener(this, name, fn, true)
  }

  prependListener(name, fn) {
    return prependListener(this, name, fn, false)
  }

  prependOnceListener(name, fn) {
    return prependListener(this, name, fn, true)
  }

  removeListener(name, fn) {
    return removeListener(this, name, fn)
  }

  on(name, fn) {
    return appendListener(this, name, fn, false)
  }

  once(name, fn) {
    return appendListener(this, name, fn, true)
  }

  off(name, fn) {
    return removeListener(this, name, fn)
  }

  emit(name, ...args) {
    if (name === 'error' && this._events !== undefined && this._events.error === undefined) {
      throwUnhandledError(...args)
    }

    if (this._events === undefined) return false
    const e = this._events[name]
    return e === undefined ? false : e.emit(this, name, ...args)
  }

  listeners(name) {
    if (this._events === undefined) return []
    const e = this._events[name]
    return e === undefined ? [] : [...e.list]
  }

  rawListeners(name) {
    if (this._events === undefined) return []
    const e = this._events[name]
    return e === undefined ? [] : e.list.map((l) => l[0])
  }

  eventNames() {
    if (this._events === undefined) return []
    return Reflect.ownKeys(this._events)
  }

  listenerCount(name) {
    if (this._events === undefined) return 0
    const e = this._events[name]
    return e === undefined ? 0 : e.list.length
  }

  getMaxListeners() {
    return EventEmitter.defaultMaxListeners
  }

  setMaxListeners(n) {}

  removeAllListeners(name) {
    if (arguments.length === 0) {
      for (const key of Reflect.ownKeys(this._events)) {
        if (key === 'removeListener') continue
        this.removeAllListeners(key)
      }
      this.removeAllListeners('removeListener')
    } else {
      const e = this._events[name]
      if (e !== undefined) e.removeAll(this, name)
    }
    return this
  }
}

exports.EventEmitter = exports

exports.errors = errors

exports.defaultMaxListeners = 10

exports.on = function on(emitter, name, opts = {}) {
  const { signal } = opts

  if (signal && signal.aborted) {
    throw errors.OPERATION_ABORTED(signal.reason)
  }

  let error = null
  let done = false

  const events = []
  const promises = []

  if (name !== 'error') emitter.on('error', onerror)

  if (signal) signal.addEventListener('abort', onabort)

  emitter.on(name, onevent)

  return {
    next() {
      if (events.length) {
        return Promise.resolve({ value: events.shift(), done: false })
      }

      if (error) {
        const err = error

        error = null

        return Promise.reject(err)
      }

      if (done) return onclose()

      return new Promise((resolve, reject) => promises.push({ resolve, reject }))
    },

    return() {
      return onclose()
    },

    throw(err) {
      return onerror(err)
    },

    [Symbol.asyncIterator]() {
      return this
    }
  }

  function onevent(...args) {
    if (promises.length) {
      promises.shift().resolve({ value: args, done: false })
    } else {
      events.push(args)
    }
  }

  function onerror(err) {
    emitter.off(name, onevent).off('error', onerror)

    if (promises.length) {
      promises.shift().reject(err)
    } else {
      error = err
    }

    return Promise.resolve({ done: true })
  }

  function onabort() {
    signal.removeEventListener('abort', onabort)

    onerror(errors.OPERATION_ABORTED(signal.reason))
  }

  function onclose() {
    emitter.off(name, onevent)

    if (name !== 'error') emitter.off('error', onerror)

    if (signal) signal.removeEventListener('abort', onabort)

    done = true

    if (promises.length) promises.shift().resolve({ done: true })

    return Promise.resolve({ done: true })
  }
}

exports.once = function once(emitter, name, opts = {}) {
  const { signal } = opts

  if (signal && signal.aborted) {
    return Promise.reject(errors.OPERATION_ABORTED(signal.reason))
  }

  return new Promise((resolve, reject) => {
    if (name !== 'error') emitter.on('error', onerror)

    if (signal) signal.addEventListener('abort', onabort)

    emitter.once(name, onevent)

    function onevent(...args) {
      if (name !== 'error') emitter.off('error', onerror)

      if (signal) signal.removeEventListener('abort', onabort)

      resolve(args)
    }

    function onerror(err) {
      emitter.off(name, onevent)

      if (name !== 'error') emitter.off('error', onerror)

      reject(err)
    }

    function onabort() {
      signal.removeEventListener('abort', onabort)

      onerror(errors.OPERATION_ABORTED(signal.reason))
    }
  })
}

exports.forward = function forward(from, to, names, opts = {}) {
  if (typeof names === 'string') names = [names]

  const { emit = to.emit.bind(to) } = opts

  const listeners = names.map(
    (name) =>
      function onevent(...args) {
        emit(name, ...args)
      }
  )

  to.on('newListener', (name) => {
    const i = names.indexOf(name)

    if (i !== -1 && to.listenerCount(name) === 0) {
      from.on(name, listeners[i])
    }
  }).on('removeListener', (name) => {
    const i = names.indexOf(name)

    if (i !== -1 && to.listenerCount(name) === 0) {
      from.off(name, listeners[i])
    }
  })
}

exports.listenerCount = function listenerCount(emitter, name) {
  return emitter.listenerCount(name)
}

exports.getMaxListeners = function getMaxListeners(emitter) {
  if (typeof emitter.getMaxListeners === 'function') {
    return emitter.getMaxListeners()
  }

  return exports.defaultMaxListeners
}

exports.setMaxListeners = function setMaxListeners(n, ...emitters) {
  if (emitters.length === 0) exports.defaultMaxListeners = n
  else {
    for (const emitter of emitters) {
      if (typeof emitter.setMaxListeners === 'function') {
        emitter.setMaxListeners(n)
      }
    }
  }
}
module.exports = class EventEmitterError extends Error {
  constructor(msg, code, fn = EventEmitterError, opts) {
    super(`${code}: ${msg}`, opts)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'EventEmitterError'
  }

  static OPERATION_ABORTED(cause, msg = 'Operation aborted') {
    return new EventEmitterError(msg, 'OPERATION_ABORTED', EventEmitterError.OPERATION_ABORTED, {
      cause
    })
  }

  static UNHANDLED_ERROR(cause, msg = 'Unhandled error') {
    return new EventEmitterError(msg, 'UNHANDLED_ERROR', EventEmitterError.UNHANDLED_ERROR, {
      cause
    })
  }
}
{
  "name": "bare-events",
  "version": "2.9.1",
  "description": "Event emitters for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    },
    "./web": {
      "types": "./web.d.ts",
      "default": "./web.js"
    },
    "./errors": "./lib/errors.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "global.js",
    "global.d.ts",
    "web.js",
    "web.d.ts",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:bare && npm run test:node",
    "test:bare": "brittle-bare --coverage test.js",
    "test:node": "brittle-node --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-events.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-events/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-events#readme",
  "devDependencies": {
    "bare-abort-controller": "^1.0.0",
    "brittle": "^3.3.2",
    "lunte": "^1.8.0",
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^2.0.0",
    "uncaughts": "^1.1.1"
  },
  "peerDependencies": {
    "bare-abort-controller": "*"
  },
  "peerDependenciesMeta": {
    "bare-abort-controller": {
      "optional": true
    }
  }
}
const http = require('bare-http1')
const https = require('bare-https')
const { ReadableStream } = require('bare-stream/web')
const Request = require('./lib/request')
const Response = require('./lib/response')
const ResponseStream = require('./lib/response-stream')
const Headers = require('./lib/headers')
const errors = require('./lib/errors')

// https://fetch.spec.whatwg.org/#dom-global-fetch
module.exports = exports = function fetch(input, init = {}) {
  let resolve
  let reject

  const promise = new Promise((res, rej) => {
    resolve = res
    reject = rej
  })

  const response = new Response()

  process(input)

  return promise

  async function process(input, origin = null) {
    let request
    try {
      request = new Request(input, init)
    } catch (err) {
      return reject(err)
    }

    if (request.signal) {
      if (request.signal.aborted) return abort(reject, request, response)

      request.signal.addEventListener('abort', (event) => abort(reject, request, response))
    }

    if (response._urls.length > 20) {
      return reject(errors.TOO_MANY_REDIRECTS('Redirect count exceeded'))
    }

    if (origin && !isSameOrigin(request._url, origin)) {
      request.headers.delete('authorization')
    }

    let protocol

    if (request._url.protocol === 'http:') {
      protocol = http
    } else if (request._url.protocol === 'https:') {
      protocol = https
    } else {
      return reject(errors.UNKNOWN_PROTOCOL(`Unknown protocol '${request._url.protocol}'`))
    }

    response._urls.push(request._url)

    if (!request._headers.has('user-agent')) {
      request._headers.set('user-agent', `Bare/${Bare.version.substring(1)}`)
    }

    if (!request._headers.has('content-type') && request._type) {
      request._headers.set('content-type', request._type)
    }

    const agent = request._agent || protocol.globalAgent

    while (agent.suspended) await agent.resumed

    const req = protocol.request(
      request._url,
      {
        agent,
        method: request._method,
        headers: Object.fromEntries(request._headers)
      },
      (res) => {
        req.off('close', onclose)

        if (request.signal && request.signal.aborted) {
          res.resume()

          return abort(reject, request, response)
        }

        if (res.headers.location && isRedirectStatus(res.statusCode)) {
          res.resume()

          let url
          try {
            url = new URL(res.headers.location, request._url)
          } catch (err) {
            return reject(errors.INVALID_URL('Invalid URL', err))
          }

          return process(url, request._url)
        }

        response._body = new ReadableStream(new ResponseStream(res))
        response._status = res.statusCode
        response._statusText = res.statusMessage

        for (const [name, value] of Object.entries(res.headers)) {
          response._headers.set(name, value)
        }

        resolve(response)
      }
    )

    req.on('error', onerror).on('close', onclose)

    try {
      if (request._body) {
        for await (const data of request._body) req.write(data)
      }

      req.end()
    } catch (err) {
      req.destroy(err)
    }

    function onerror(err) {
      req.off('close', onclose)

      reject(errors.NETWORK_ERROR('Network error', err))
    }

    function onclose() {
      onerror(http.errors.CONNECTION_LOST())
    }
  }
}

exports.Request = Request
exports.Response = Response
exports.Headers = Headers

// https://fetch.spec.whatwg.org/#redirect-status
function isRedirectStatus(status) {
  return status === 301 || status === 302 || status === 303 || status === 307 || status === 308
}

// https://html.spec.whatwg.org/multipage/browsers.html#same-origin
function isSameOrigin(a, b) {
  return a.protocol === b.protocol && a.host === b.host
}

// https://fetch.spec.whatwg.org/#abort-fetch
function abort(reject, req, res) {
  const { reason } = req.signal

  if (req._body !== null) req._body.cancel(reason)
  if (res._body !== null) res._body.cancel(reason)

  reject(reason)
}
const { ReadableStream, isReadableStream, isReadableStreamDisturbed } = require('bare-stream/web')
const { isURLSearchParams } = require('bare-url')
const { FormData, File, isFormData, isBlob } = require('bare-form-data')
const Headers = require('./headers')
const errors = require('./errors')

const empty = Buffer.from(new ArrayBuffer(0))

// https://fetch.spec.whatwg.org/#body-mixin
module.exports = exports = class Body {
  constructor(body = null, type = null) {
    if (isReadableStream(body)) {
      if (isReadableStreamDisturbed(body) || body.locked) {
        throw errors.BODY_UNUSABLE('Body has already been consumed')
      }
    } else {
      if (typeof body === 'string') body = Buffer.from(body)
      else if (isFormData(body)) body = FormData.toBlob(body)
      else if (isURLSearchParams(body)) {
        body = body.toString()
        type = 'application/x-www-form-urlencoded;charset=UTF-8'
      }

      if (isBlob(body)) {
        type = body.type || null
        body = body.stream()
      } else if (body !== null) {
        if (ArrayBuffer.isView(body)) {
          body = Buffer.from(body.buffer, body.byteOffset, body.byteLength)
        } else {
          body = Buffer.from(body)
        }

        body = new ReadableStream({
          start(controller) {
            controller.enqueue(body)
            controller.close()
          }
        })
      }
    }

    this._type = type
    this._body = body
  }

  // https://fetch.spec.whatwg.org/#dom-body-body
  get body() {
    return this._body
  }

  // https://fetch.spec.whatwg.org/#dom-body-bodyused
  get bodyUsed() {
    return this._body !== null && isReadableStreamDisturbed(this._body)
  }

  async buffer() {
    if (this._body === null) return empty

    if (Body.isUnusable(this)) {
      throw errors.BODY_UNUSABLE('Body has already been consumed')
    }

    const chunks = []
    let length = 0

    for await (const chunk of this._body) {
      chunks.push(chunk)
      length += chunk.byteLength
    }

    const result = Buffer.from(new ArrayBuffer(length))
    let offset = 0

    for (const chunk of chunks) {
      result.set(chunk, offset)
      offset += chunk.byteLength
    }

    return result
  }

  // https://fetch.spec.whatwg.org/#dom-body-bytes
  async bytes() {
    return this.buffer()
  }

  // https://fetch.spec.whatwg.org/#dom-body-arraybuffer
  async arrayBuffer() {
    return (await this.buffer()).buffer
  }

  // https://fetch.spec.whatwg.org/#dom-body-text
  async text() {
    return (await this.buffer()).toString()
  }

  // https://fetch.spec.whatwg.org/#dom-body-json
  async json() {
    return JSON.parse(await this.text())
  }

  // https://fetch.spec.whatwg.org/#dom-body-formdata
  async formData() {
    const mimeType = getMIMEType(this)

    // 1.
    if (mimeType !== null && mimeType.type === 'multipart' && mimeType.subtype === 'form-data') {
      const body = await this.text()
      const boundary = mimeType.parameters.get('boundary')

      if (boundary === undefined) {
        throw errors.INVALID_FORM_DATA('Missing boundary parameter')
      }

      return parseMultipart(body, boundary)
    }

    // 2.
    if (
      mimeType !== null &&
      mimeType.type === 'application' &&
      mimeType.subtype === 'x-www-form-urlencoded'
    ) {
      const body = await this.text()
      const formData = new FormData()

      for (const [name, value] of new URLSearchParams(body)) {
        formData.append(name, value)
      }

      return formData
    }

    // 3.
    throw errors.INVALID_FORM_DATA('Could not parse content as form data')
  }
}

// https://fetch.spec.whatwg.org/#body-unusable
exports.isUnusable = function isUsable(body) {
  return body._body !== null && (isReadableStreamDisturbed(body._body) || body._body.locked)
}

// https://fetch.spec.whatwg.org/#concept-body-clone
exports.clone = function clone(body) {
  if (body._body === null) return null

  const [out1, out2] = body._body.tee()

  body._body = out1

  return out2
}

// https://fetch.spec.whatwg.org/#concept-body-mime-type
function getMIMEType(body) {
  const headers = body._headers

  if (headers === undefined) return null

  return Headers.extractMIMEType(headers)
}

// https://www.rfc-editor.org/rfc/rfc7578
// https://www.rfc-editor.org/rfc/rfc2046#section-5.1
function parseMultipart(input, boundary) {
  const formData = new FormData()

  const delimiter = `\r\n--${boundary}`
  const close = `\r\n--${boundary}--`

  let start = input.indexOf(`--${boundary}`)
  if (start === -1) return formData

  start += `--${boundary}`.length

  while (true) {
    if (input.startsWith('--', start)) break
    if (input.startsWith('\r\n', start)) start += 2

    let end = input.indexOf(delimiter, start)
    if (end === -1) end = input.indexOf(close, start)
    if (end === -1) break

    const part = input.slice(start, end)

    const headerEnd = part.indexOf('\r\n\r\n')
    if (headerEnd === -1) {
      start = end + delimiter.length
      continue
    }

    const headerSection = part.slice(0, headerEnd)
    const body = part.slice(headerEnd + 4)

    const contentDisposition = { name: null, filename: null }
    let contentType = null

    for (const line of headerSection.split('\r\n')) {
      const colon = line.indexOf(':')
      if (colon === -1) continue

      const name = line.slice(0, colon).trim().toLowerCase()
      const value = line.slice(colon + 1).trim()

      if (name === 'content-disposition') {
        contentDisposition.name = getParameter(value, 'name')
        contentDisposition.filename = getParameter(value, 'filename')
      } else if (name === 'content-type') {
        contentType = value
      }
    }

    if (contentDisposition.name === null) {
      start = end + delimiter.length
      continue
    }

    if (contentDisposition.filename !== null) {
      const file = new File([body], contentDisposition.filename, {
        type: contentType || 'application/octet-stream'
      })

      formData.append(contentDisposition.name, file)
    } else {
      formData.append(contentDisposition.name, body)
    }

    start = end + delimiter.length
  }

  return formData
}

function getParameter(header, name) {
  const pattern = new RegExp(`${name}="([^"]*)"|${name}=([^;\\s]*)`, 'i')

  const match = header.match(pattern)
  if (match === null) return null

  return match[1] !== undefined ? match[1] : match[2]
}
module.exports = class FetchError extends Error {
  constructor(msg, fn = FetchError, code = fn.name, opts = {}) {
    if (typeof code === 'object' && code !== null) {
      opts = code
      code = fn.name
    }

    super(`${code}: ${msg}`, opts)

    this.code = code

    if (Error.captureStackTrace) Error.captureStackTrace(this, fn)
  }

  get name() {
    return 'FetchError'
  }

  static INVALID_URL(msg, cause) {
    return new FetchError(msg, FetchError.INVALID_URL, { cause })
  }

  static NETWORK_ERROR(msg, cause) {
    return new FetchError(msg, FetchError.NETWORK_ERROR, { cause })
  }

  static TOO_MANY_REDIRECTS(msg) {
    return new FetchError(msg, FetchError.TOO_MANY_REDIRECTS)
  }

  static UNKNOWN_PROTOCOL(msg) {
    return new FetchError(msg, FetchError.UNKNOWN_PROTOCOL)
  }

  static BODY_UNUSABLE(msg) {
    return new FetchError(msg, FetchError.BODY_UNUSABLE)
  }

  static INVALID_FORM_DATA(msg) {
    return new FetchError(msg, FetchError.INVALID_FORM_DATA)
  }

  static INVALID_HEADER_NAME(msg) {
    return new FetchError(msg, FetchError.INVALID_HEADER_NAME)
  }

  static INVALID_HEADER_VALUE(msg) {
    return new FetchError(msg, FetchError.INVALID_HEADER_VALUE)
  }
}
const MIME = require('bare-mime')

const errors = require('./errors')

const NUL = 0x00
const LF = 0x0a
const CR = 0x0d

// https://www.rfc-editor.org/rfc/rfc9110.html#section-5.6.2
const TOKEN_BYTES = Buffer.from([
  // 0x00-0x1f (control characters) + 0x20 (space)
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  // 0x21-0x41: ! " # $ % & ' ( ) * + , - . / 0-9 : ; < = > ? @ A
  1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1,
  // 0x42-0x62: B-Z [ \ ] ^ _ ` a b
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1,
  // 0x63-0x7f: c-z { | } ~ DEL
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0
])

function isTokenByte(b) {
  return b < TOKEN_BYTES.length && TOKEN_BYTES[b] === 1
}

function isFieldByte(b) {
  return b !== NUL && b !== LF && b !== CR
}

// https://fetch.spec.whatwg.org/#header-name
function validateName(name) {
  if (name.length === 0) {
    throw errors.INVALID_HEADER_NAME(`Header name must not be empty`)
  }

  for (let i = 0, n = name.length; i < n; i++) {
    if (!isTokenByte(name.charCodeAt(i))) {
      throw errors.INVALID_HEADER_NAME(`Invalid header name '${name}'`)
    }
  }
}

// https://fetch.spec.whatwg.org/#header-value
function validateValue(name, value) {
  for (let i = 0, n = value.length; i < n; i++) {
    if (!isFieldByte(value.charCodeAt(i))) {
      throw errors.INVALID_HEADER_VALUE(`Invalid header value for '${name}'`)
    }
  }
}

// https://fetch.spec.whatwg.org/#headers-class
module.exports = exports = class Headers {
  // https://fetch.spec.whatwg.org/#dom-headers
  constructor(init) {
    this._headers = new Map()

    if (init) {
      for (const [key, value] of typeof init[Symbol.iterator] === 'function'
        ? init
        : Object.entries(init)) {
        this.append(key, value)
      }
    }
  }

  // https://fetch.spec.whatwg.org/#dom-headers-append
  append(name, value) {
    value = value.trim()

    validateName(name)
    validateValue(name, value)

    name = name.toLowerCase()

    let list = this._headers.get(name)

    if (list === undefined) {
      list = []
      this._headers.set(name, list)
    }

    list.push(value)
  }

  // https://fetch.spec.whatwg.org/#dom-headers-delete
  delete(name) {
    name = name.toLowerCase()

    this._headers.delete(name)
  }

  // https://fetch.spec.whatwg.org/#dom-headers-get
  get(name) {
    name = name.toLowerCase()

    const list = this._headers.get(name)

    if (list === undefined) return null

    return list.join(', ')
  }

  // https://fetch.spec.whatwg.org/#dom-headers-has
  has(name) {
    name = name.toLowerCase()

    return this._headers.has(name)
  }

  // https://fetch.spec.whatwg.org/#dom-headers-set
  set(name, value) {
    value = value.trim()

    validateName(name)
    validateValue(name, value)

    name = name.toLowerCase()

    this._headers.set(name, [value])
  }

  // https://webidl.spec.whatwg.org/#idl-iterable
  entries() {
    return this[Symbol.iterator]()
  }

  // https://webidl.spec.whatwg.org/#idl-iterable
  *keys() {
    for (const [name] of this) {
      yield name
    }
  }

  // https://webidl.spec.whatwg.org/#idl-iterable
  *values() {
    for (const [, value] of this) {
      yield value
    }
  }

  // https://webidl.spec.whatwg.org/#idl-iterable
  forEach(callback, thisArg) {
    for (const [name, value] of this) {
      callback.call(thisArg, value, name, this)
    }
  }

  *[Symbol.iterator]() {
    const names = [...this._headers.keys()].sort()

    for (const name of names) {
      yield [name, this.get(name)]
    }
  }
}

// https://fetch.spec.whatwg.org/#concept-header-extract-mime-type
exports.extractMIMEType = function extractMIMEType(headers) {
  // 1.
  const contentType = headers.get('content-type')

  // 2.
  if (contentType === null) return null

  // 3.
  const values = getDecodeSplit(contentType)

  // 4.
  let mimeType = null

  // 5.
  for (const value of values) {
    const parsed = MIME.parse(value)

    if (parsed !== null) {
      mimeType = parsed
    }
  }

  // 6.
  return mimeType
}

// https://fetch.spec.whatwg.org/#concept-header-list-get-decode-split
function getDecodeSplit(value) {
  const values = []
  let current = ''
  let position = 0

  while (position < value.length) {
    if (value[position] === '"') {
      current += value[position++]

      while (position < value.length) {
        if (value[position] === '\\' && position + 1 < value.length) {
          current += value[position++]
          current += value[position++]
        } else if (value[position] === '"') {
          current += value[position++]
          break
        } else {
          current += value[position++]
        }
      }
    } else if (value[position] === ',') {
      values.push(current.trim())
      current = ''
      position++
    } else {
      current += value[position++]
    }
  }

  values.push(current.trim())

  return values
}
const { isURL } = require('bare-url')
const Body = require('./body')
const Headers = require('./headers')
const errors = require('./errors')

// https://fetch.spec.whatwg.org/#request-class
module.exports = class Request extends Body {
  // https://fetch.spec.whatwg.org/#dom-request
  constructor(input, init = {}) {
    let url
    try {
      if (isURL(input)) {
        url = input
        input = {}
      } else if (typeof input === 'string') {
        url = new URL(input)
        input = {}
      } else {
        url = new URL(input.url)
      }
    } catch (err) {
      throw errors.INVALID_URL('Invalid URL', err)
    }

    const {
      body = input.body || null,
      method = input.method || 'GET',
      headers = input.headers,
      signal = null,
      agent = input.agent || null
    } = init

    super(body)

    this._url = url
    this._method = /^(delete|get|head|options|post|put)$/i.test(method)
      ? method.toUpperCase()
      : method
    this._headers = new Headers(headers)
    this._signal = signal
    this._agent = agent
  }

  // https://fetch.spec.whatwg.org/#dom-request-url
  get url() {
    return this._url.href
  }

  // https://fetch.spec.whatwg.org/#dom-request-method
  get method() {
    return this._method
  }

  // https://fetch.spec.whatwg.org/#dom-request-headers
  get headers() {
    return this._headers
  }

  // https://fetch.spec.whatwg.org/#dom-request-signal
  get signal() {
    return this._signal
  }

  // https://fetch.spec.whatwg.org/#dom-request-clone
  clone() {
    if (Body.isUnusable(this)) throw errors.BODY_UNUSABLE('Body has already been consumed')

    return new Request(this, { body: Body.clone(this) })
  }
}
const { Readable } = require('bare-stream')
const { Gunzip, Deflate } = require('bare-zlib')

module.exports = class ResponseStream extends Readable {
  constructor(response) {
    super()

    this._response = response
    this._response.socket.unref()

    const encoding = response.headers['content-encoding']

    switch (encoding) {
      case 'gzip':
        this._decoder = new Gunzip()
        break
      case 'deflate':
        this._decoder = new Deflate()
        break
      default:
        this._decoder = null
    }
  }

  _open(cb) {
    if (this._response.socket) this._response.socket.ref()

    const stream = this._decoder ? this._response.pipe(this._decoder) : this._response

    stream
      .on('data', this._ondata.bind(this))
      .on('end', this._onend.bind(this))
      .on('error', this._onerror.bind(this))

    cb(null)
  }

  _read() {
    this._response.resume()
  }

  _predestroy() {
    this._response.destroy()
  }

  _ondata(data) {
    if (this.push(data) === false) {
      this._response.pause()
    }
  }

  _onend() {
    this.push(null)
  }

  _onerror(err) {
    this.destroy(err)
  }
}
const Body = require('./body')
const Headers = require('./headers')
const errors = require('./errors')

// https://fetch.spec.whatwg.org/#response-class
module.exports = class Response extends Body {
  // https://fetch.spec.whatwg.org/#dom-response
  constructor(body = null, init = {}) {
    const { status = 200, statusText = '', headers } = init

    super(body)

    this._urls = []
    this._status = status
    this._statusText = statusText
    this._headers = new Headers(headers)
  }

  // https://fetch.spec.whatwg.org/#dom-response-url
  get url() {
    return this._urls.length === 0 ? null : this._urls[this._urls.length - 1].href
  }

  // https://fetch.spec.whatwg.org/#dom-response-redirected
  get redirected() {
    return this._urls.length > 1
  }

  // https://fetch.spec.whatwg.org/#dom-response-status
  get status() {
    return this._status
  }

  // https://fetch.spec.whatwg.org/#dom-response-ok
  get ok() {
    return this._status >= 200 && this._status <= 299
  }

  // https://fetch.spec.whatwg.org/#dom-response-statustext
  get statusText() {
    return this._statusText
  }

  // https://fetch.spec.whatwg.org/#dom-response-headers
  get headers() {
    return this._headers
  }

  // https://fetch.spec.whatwg.org/#dom-response-clone
  clone() {
    if (Body.isUnusable(this)) throw errors.BODY_UNUSABLE('Body has already been consumed')

    return new Response(Body.clone(this), this)
  }
}
{
  "name": "bare-fetch",
  "version": "3.0.1",
  "description": "WHATWG Fetch implementation for Bare",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    },
    "./errors": {
      "types": "./lib/errors.d.ts",
      "default": "./lib/errors.js"
    },
    "./body": {
      "types": "./lib/body.d.ts",
      "default": "./lib/body.js"
    },
    "./request": {
      "types": "./lib/request.d.ts",
      "default": "./lib/request.js"
    },
    "./response": {
      "types": "./lib/response.d.ts",
      "default": "./lib/response.js"
    },
    "./headers": {
      "types": "./lib/headers.d.ts",
      "default": "./lib/headers.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "global.js",
    "global.d.ts",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-fetch.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-fetch/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-fetch#readme",
  "dependencies": {
    "bare-form-data": "^1.2.0",
    "bare-http1": "^4.5.2",
    "bare-https": "^3.0.0",
    "bare-mime": "^1.0.0",
    "bare-stream": "^2.9.1",
    "bare-url": "^2.4.0",
    "bare-zlib": "^1.3.0"
  },
  "devDependencies": {
    "bare-abort-controller": "^1.0.1",
    "bare-buffer": "^3.0.2",
    "brittle": "^3.3.0",
    "listen-async": "^1.0.0",
    "lunte": "^1.6.0",
    "prettier": "^3.3.3",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "bare-abort-controller": "*",
    "bare-buffer": "*"
  },
  "peerDependenciesMeta": {
    "bare-abort-controller": {
      "optional": true
    },
    "bare-buffer": {
      "optional": true
    }
  }
}
const { ReadableStream } = require('bare-stream/web')
const { isBuffer } = require('bare-buffer')
const errors = require('./lib/errors')

class FormData {
  constructor() {
    this._entries = []
  }

  append(name, value, filename) {
    if (typeof value !== 'string') {
      if (!isFile(value) || filename) {
        value = new File([value], filename || 'blob', { type: value.type })
      }
    }

    this._entries.push([name, value])
  }

  delete(name) {
    this._entries = this._entries.filter((entry) => entry[0] !== name)
  }

  get(name) {
    const entry = this._entries.find((entry) => entry[0] === name)

    return entry ? entry[1] : null
  }

  getAll(name) {
    const entries = []

    for (const entry of this._entries) {
      if (entry[0] === name) entries.push(entry[1])
    }

    return entries
  }

  has(name) {
    return this._entries.findIndex((entry) => entry[0] === name) !== -1
  }

  set(name, value, filename) {
    this.delete(name)
    this.append(name, value, filename)
  }

  [Symbol.iterator]() {
    return this._entries[Symbol.iterator]()
  }

  [Symbol.for('bare.inspect')]() {
    return {
      __proto__: { constructor: FormData },

      entries: this._entries
    }
  }
}

module.exports = exports = FormData

exports.FormData = FormData

function isFormData(value) {
  return value instanceof FormData
}

exports.isFormData = isFormData

class Blob {
  // https://w3c.github.io/FileAPI/#dom-blob-blob
  constructor(parts, options = {}) {
    const { type = '' } = options

    this._bytes = processBlobParts(parts)
    this._type = type
  }

  // https://w3c.github.io/FileAPI/#dfn-size
  get size() {
    return this._bytes.byteLength
  }

  // https://w3c.github.io/FileAPI/#dfn-type
  get type() {
    return this._type
  }

  // https://w3c.github.io/FileAPI/#stream-method-algo
  stream() {
    const bytes = this._bytes

    return new ReadableStream({
      start(controller) {
        controller.enqueue(bytes)
        controller.close()
      }
    })
  }

  async buffer() {
    return Buffer.from(this._bytes)
  }

  // https://w3c.github.io/FileAPI/#bytes-method-algo
  async bytes() {
    return this.buffer()
  }

  // https://w3c.github.io/FileAPI/#arraybuffer-method-algo
  async arrayBuffer() {
    const buffer = new ArrayBuffer(this._bytes.byteLength)
    new Uint8Array(buffer).set(this._bytes)
    return buffer
  }

  // https://w3c.github.io/FileAPI/#text-method-algo
  async text() {
    return this._bytes.toString()
  }

  [Symbol.for('bare.inspect')]() {
    return {
      __proto__: { constructor: Blob },

      size: this.size,
      type: this.type
    }
  }
}

exports.Blob = Blob

function isBlob(value) {
  return value instanceof Blob
}

exports.isBlob = Blob.isBlob = isBlob

class File extends Blob {
  // https://w3c.github.io/FileAPI/#dom-file-file
  constructor(parts, name, options = {}) {
    const { lastModified = Date.now() } = options

    super(parts, options)

    this._name = name
    this._lastModified = lastModified
  }

  // https://w3c.github.io/FileAPI/#dfn-name
  get name() {
    return this._name
  }

  // https://w3c.github.io/FileAPI/#dfn-lastModified
  get lastModified() {
    return this._lastModified
  }

  [Symbol.for('bare.inspect')]() {
    return {
      __proto__: { constructor: File },

      size: this.size,
      type: this.type,
      name: this.name,
      lastModified: this.lastModified
    }
  }
}

exports.File = File

function isFile(value) {
  return value instanceof File
}

exports.isFile = File.isFile = isFile

// https://w3c.github.io/FileAPI/#process-blob-parts
function processBlobParts(parts) {
  const chunks = []

  for (const part of parts) {
    if (typeof part === 'string') {
      const buffer = Buffer.from(part)
      if (parts.length === 1) return buffer
      chunks.push(buffer)
    } else if (isBlob(part)) {
      chunks.push(part._bytes)
    } else if (isBuffer(part)) {
      chunks.push(part)
    } else if (ArrayBuffer.isView(part)) {
      chunks.push(Buffer.from(part.buffer, part.byteOffset, part.byteLength))
    } else {
      chunks.push(Buffer.from(part))
    }
  }

  return Buffer.concat(chunks)
}

function toBlob(formData, mimeType = 'multipart/form-data') {
  switch (mimeType) {
    case 'multipart/form-data':
      return toMultipartBlob(formData)
    default:
      throw errors.INVALID_MIME_TYPE(`Invalid MIME type '${mimeType}'`)
  }
}

exports.toBlob = toBlob

function escape(value) {
  return value.replace(/\n/g, '%0A').replace(/\r/g, '%0D').replace(/"/g, '%22')
}

function normalizeLinefeeds(value) {
  return value.replace(/\r?\n|\r/g, '\r\n')
}

const linefeed = Buffer.from('\r\n')

// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#multipart/form-data-encoding-algorithm
function toMultipartBlob(formData) {
  const boundary = Math.random().toString(16).slice(2, 18).padStart(16, '0')

  const prefix = `--${boundary}\r\nContent-Disposition: form-data`

  const parts = []

  for (const [name, value] of formData) {
    if (typeof value === 'string') {
      const chunk = Buffer.from(
        prefix +
          `; name="${escape(normalizeLinefeeds(name))}"` +
          `\r\n\r\n${normalizeLinefeeds(value)}\r\n`
      )

      parts.push(chunk)
    } else {
      const chunk = Buffer.from(
        prefix +
          `; name="${escape(normalizeLinefeeds(name))}"` +
          `; filename="${escape(value.name)}"` +
          `\r\nContent-Type: ${value.type || 'application/octet-stream'}\r\n\r\n`
      )

      parts.push(chunk, value, linefeed)
    }
  }

  parts.push(Buffer.from(`--${boundary}--\r\n`))

  return new Blob(parts, {
    type: 'multipart/form-data; boundary=' + boundary
  })
}
module.exports = class FormDataError extends Error {
  constructor(msg, code, fn = FormDataError) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'FormDataError'
  }

  static INVALID_MIME_TYPE(msg) {
    return new FormDataError(msg, 'INVALID_MIME_TYPE', FormDataError.INVALID_MIME_TYPE)
  }
}
{
  "name": "bare-form-data",
  "version": "1.2.2",
  "description": "Form data support for Bare",
  "exports": {
    "./package": "./package.json",
    ".": "./index.js",
    "./global": "./global.js",
    "./errors": "./lib/errors.js"
  },
  "files": [
    "index.js",
    "global.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-form-data.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-form-data/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-form-data#readme",
  "dependencies": {
    "bare-buffer": "^3.6.0",
    "bare-stream": "^2.6.5"
  },
  "devDependencies": {
    "brittle": "^3.3.0",
    "lunte": "^1.7.0",
    "prettier": "^3.3.3",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = require.addon()
const FIFO = require('fast-fifo')
const EventEmitter = require('bare-events')
const path = require('bare-path')
const { isURL, fileURLToPath } = require('bare-url')
const { Readable, Writable } = require('bare-stream')
const binding = require('./binding')
const constants = require('./lib/constants')
const FileError = require('./lib/errors')

const isWindows = Bare.platform === 'win32'

exports.constants = constants

class FileRequest {
  static borrow() {
    if (this._free.length > 0) return this._free.pop()
    return new FileRequest()
  }

  static return(req) {
    if (this._free.length < 32) this._free.push(req.reset())
    else req.destroy()
  }

  constructor() {
    this._reset()
    this._handle = binding.requestInit(this, this._onresult)
  }

  get handle() {
    return this._handle
  }

  retain(value) {
    this._retain = value // Tie the lifetime of `value` to the lifetime of `this`
  }

  reset() {
    if (this._handle === null) return this

    binding.requestReset(this._handle)

    this._reset()

    return this
  }

  destroy() {
    if (this._handle === null) return this

    binding.requestDestroy(this._handle)

    this._reset()
    this._handle = null

    return this
  }

  then(resolve, reject) {
    return this._promise.then(resolve, reject)
  }

  return() {
    if (this._handle === null) return this

    FileRequest.return(this)

    return this
  }

  _reset() {
    this._promise = new Promise((resolve, reject) => {
      this._resolve = resolve
      this._reject = reject
    })
    this._retain = null
  }

  _onresult(err, status) {
    if (err) this._reject(err)
    else this._resolve(status)
  }
}

FileRequest._free = []

function ok(result, cb) {
  if (typeof result === 'function') {
    cb = result
    result = undefined
  }

  if (cb) cb(null, result)
  else return result
}

function fail(err, cb) {
  if (cb) cb(err)
  else throw err
}

function done(err, result, cb) {
  if (typeof result === 'function') {
    cb = result
    result = undefined
  }

  if (err) fail(err, cb)
  else return ok(result, cb)
}

async function open(filepath, flags = 'r', mode = 0o666, cb) {
  if (typeof flags === 'function') {
    cb = flags
    flags = 'r'
    mode = 0o666
  } else if (typeof mode === 'function') {
    cb = mode
    mode = 0o666
  }

  if (typeof flags === 'string') flags = toFlags(flags)
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let fd
  let err = null
  try {
    binding.open(req.handle, filepath, flags, mode)

    fd = await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'open',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, fd, cb)
}

function openSync(filepath, flags = 'r', mode = 0o666) {
  if (typeof flags === 'string') flags = toFlags(flags)
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    return binding.openSync(req.handle, filepath, flags, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'open',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function close(fd, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.close(req.handle, fd)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'close', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function closeSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.closeSync(req.handle, fd)
  } catch (e) {
    throw new FileError(e.message, { operation: 'close', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function access(filepath, mode = constants.F_OK, cb) {
  if (typeof mode === 'function') {
    cb = mode
    mode = constants.F_OK
  }

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.access(req.handle, filepath, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'access',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function accessSync(filepath, mode = constants.F_OK) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.accessSync(req.handle, filepath, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'access',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function exists(filepath, cb) {
  let ok = true
  try {
    await access(filepath)
  } catch {
    ok = false
  }

  return done(null, ok, cb)
}

function existsSync(filepath) {
  try {
    accessSync(filepath)
  } catch {
    return false
  }

  return true
}

async function read(fd, buffer, offset = 0, len = buffer.byteLength - offset, pos = -1, cb) {
  if (typeof offset === 'function') {
    cb = offset
    offset = 0
    len = buffer.byteLength
    pos = -1
  } else if (typeof len === 'function') {
    cb = len
    len = buffer.byteLength - offset
    pos = -1
  } else if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.read(req.handle, fd, buffer, offset, len, pos)

    req.retain(buffer)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'read', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function readSync(fd, buffer, offset = 0, len = buffer.byteLength - offset, pos = -1) {
  const req = FileRequest.borrow()

  try {
    return binding.readSync(req.handle, fd, buffer, offset, len, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'read', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function readv(fd, buffers, pos = -1, cb) {
  if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.readv(req.handle, fd, buffers, pos)

    req.retain(buffers)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'readv', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function readvSync(fd, buffers, pos = -1) {
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  try {
    return binding.readvSync(req.handle, fd, buffers, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'readv', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function write(fd, data, offset, len, pos = -1, cb) {
  if (typeof data === 'string') {
    let encoding = len
    cb = pos
    pos = offset

    if (typeof pos === 'function') {
      cb = pos
      pos = -1
      encoding = 'utf8'
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = 'utf8'
    }

    if (typeof pos === 'string') {
      encoding = pos
      pos = -1
    }

    data = Buffer.from(data, encoding)
    offset = 0
    len = data.byteLength
  } else if (typeof offset === 'function') {
    cb = offset
    offset = 0
    len = data.byteLength
    pos = -1
  } else if (typeof len === 'function') {
    cb = len
    len = data.byteLength - offset
    pos = -1
  } else if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof offset !== 'number') offset = 0
  if (typeof len !== 'number') len = data.byteLength - offset
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.write(req.handle, fd, data, offset, len, pos)

    req.retain(data)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'write', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function writeSync(fd, data, offset, len, pos = -1) {
  if (typeof data === 'string') {
    let encoding = len
    pos = offset

    if (typeof pos === 'string') {
      encoding = pos
      pos = -1
    }

    data = Buffer.from(data, encoding)
    offset = 0
    len = data.byteLength
  }

  if (typeof offset !== 'number') offset = 0
  if (typeof len !== 'number') len = data.byteLength - offset
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  try {
    return binding.writeSync(req.handle, fd, data, offset, len, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'write', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function writev(fd, buffers, pos = -1, cb) {
  if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.writev(req.handle, fd, buffers, pos)

    req.retain(buffers)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'writev', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function writevSync(fd, buffers, pos = -1) {
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  try {
    return binding.writevSync(req.handle, fd, buffers, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'writev', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function stat(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.stat(req.handle, filepath)

    await req

    st = new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'stat', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function statSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.statSync(req.handle, filepath)

    return new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'stat', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function lstat(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.lstat(req.handle, filepath)

    await req

    st = new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'lstat', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function lstatSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.lstatSync(req.handle, filepath)

    return new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'lstat', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function fstat(fd, cb) {
  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.fstat(req.handle, fd)

    await req

    st = new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'fstat', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function fstatSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.fstatSync(req.handle, fd)

    return new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'fstat', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function statfs(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.statfs(req.handle, filepath)

    await req

    st = new StatFs(...binding.requestResultStatfs(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'statfs', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function statfsSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.statfsSync(req.handle, filepath)

    return new StatFs(...binding.requestResultStatfs(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'statfs', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function ftruncate(fd, len = 0, cb) {
  if (typeof len === 'function') {
    cb = len
    len = 0
  }

  if (typeof len !== 'number') len = 0

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.ftruncate(req.handle, fd, len)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'ftruncate', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function ftruncateSync(fd, len = 0) {
  if (typeof len !== 'number') len = 0

  const req = FileRequest.borrow()

  try {
    binding.ftruncateSync(req.handle, fd, len)
  } catch (e) {
    throw new FileError(e.message, { operation: 'ftruncate', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function truncate(filepath, len, cb) {
  let fd = -1
  let err

  try {
    fd = await open(filepath, 'r+')

    await ftruncate(fd, len)
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) await close(fd)
  }

  return done(err, cb)
}

function truncateSync(filepath, len) {
  let fd = -1
  let err

  try {
    fd = openSync(filepath, 'r+')

    ftruncateSync(fd, len)
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) closeSync(fd)
  }
}

async function chmod(filepath, mode, cb) {
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.chmod(req.handle, filepath, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'chmod',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function chmodSync(filepath, mode) {
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.chmodSync(req.handle, filepath, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'chmod',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function fchmod(fd, mode, cb) {
  if (typeof mode === 'string') mode = toMode(mode)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fchmod(req.handle, fd, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fchmod', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fchmodSync(fd, mode) {
  if (typeof mode === 'string') mode = toMode(mode)

  const req = FileRequest.borrow()

  try {
    binding.fchmodSync(req.handle, fd, mode)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fchmod', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function chown(filepath, uid, gid, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.chown(req.handle, filepath, uid, gid)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'chown', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function chownSync(filepath, uid, gid) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.chownSync(req.handle, filepath, uid, gid)
  } catch (e) {
    throw new FileError(e.message, { operation: 'chownSync', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function lchown(filepath, uid, gid, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.lchown(req.handle, filepath, uid, gid)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'lchown', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function lchownSync(filepath, uid, gid) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.lchownSync(req.handle, filepath, uid, gid)
  } catch (e) {
    throw new FileError(e.message, { operation: 'lchownSync', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function fchown(fd, uid, gid, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fchown(req.handle, fd, uid, gid)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fchown', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fchownSync(fd, uid, gid) {
  const req = FileRequest.borrow()

  try {
    binding.fchownSync(req.handle, fd, uid, gid)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fchownSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function utimes(filepath, atime, mtime, cb) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.utimes(req.handle, filepath, atime, mtime)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'utimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function utimesSync(filepath, atime, mtime) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.utimesSync(req.handle, filepath, atime, mtime)
  } catch (e) {
    throw new FileError(e.message, { operation: 'utimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function lutimes(filepath, atime, mtime, cb) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.lutimes(req.handle, filepath, atime, mtime)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'lutimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function lutimesSync(filepath, atime, mtime) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.lutimesSync(req.handle, filepath, atime, mtime)
  } catch (e) {
    throw new FileError(e.message, { operation: 'lutimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function futimes(fd, atime, mtime, cb) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.futimes(req.handle, fd, atime, mtime)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'futimes', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function futimesSync(fd, atime, mtime) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  const req = FileRequest.borrow()

  try {
    binding.futimesSync(req.handle, fd, atime, mtime)
  } catch (e) {
    throw new FileError(e.message, { operation: 'futimesSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function link(src, dst, cb) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.link(req.handle, src, dst)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'link', code: e.code, path: src, destination: dst })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function linkSync(src, dst) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  try {
    binding.linkSync(req.handle, src, dst)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'linkSync',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }
}

async function mkdir(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = { mode: 0o777 }
  }

  if (typeof opts === 'number') opts = { mode: opts }
  else if (!opts) opts = {}

  const mode = typeof opts.mode === 'number' ? opts.mode : 0o777

  filepath = toNamespacedPath(filepath)

  if (opts.recursive) {
    let err = null
    try {
      try {
        await mkdir(filepath, { mode })
      } catch (err) {
        if (err.code !== 'ENOENT') {
          if (!(await stat(filepath)).isDirectory()) throw err
        } else {
          while (filepath.endsWith(path.sep)) filepath = filepath.slice(0, -1)
          const i = filepath.lastIndexOf(path.sep)
          if (i <= 0) throw err

          await mkdir(filepath.slice(0, i), { mode, recursive: true })

          try {
            await mkdir(filepath, { mode })
          } catch (err) {
            if (!(await stat(filepath)).isDirectory()) throw err
          }
        }
      }
    } catch (e) {
      err = e
    }

    return done(err, cb)
  }

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.mkdir(req.handle, filepath, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'mkdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function mkdirSync(filepath, opts) {
  if (typeof opts === 'number') opts = { mode: opts }
  else if (!opts) opts = {}

  const mode = typeof opts.mode === 'number' ? opts.mode : 0o777

  filepath = toNamespacedPath(filepath)

  if (opts.recursive) {
    try {
      mkdirSync(filepath, { mode })
    } catch (err) {
      if (err.code !== 'ENOENT') {
        if (!statSync(filepath).isDirectory()) throw err
      } else {
        while (filepath.endsWith(path.sep)) filepath = filepath.slice(0, -1)
        const i = filepath.lastIndexOf(path.sep)
        if (i <= 0) throw err

        mkdirSync(filepath.slice(0, i), { mode, recursive: true })

        try {
          mkdirSync(filepath, { mode })
        } catch (err) {
          if (!statSync(filepath).isDirectory()) throw err
        }
      }
    }

    return
  }

  const req = FileRequest.borrow()

  try {
    binding.mkdirSync(req.handle, filepath, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'mkdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function mkdtemp(prefix, cb) {
  prefix = toNamespacedPath(prefix)

  const req = FileRequest.borrow()

  let res
  let err = null
  try {
    binding.mkdtemp(req.handle, prefix + 'XXXXXX')

    await req

    res = binding.requestResultPath(req.handle)
  } catch (e) {
    err = new FileError(e.message, { operation: 'mkdtemp', code: e.code, path: prefix })
  } finally {
    req.return()
  }

  return done(err, res, cb)
}

function mkdtempSync(prefix) {
  prefix = toNamespacedPath(prefix)

  const req = FileRequest.borrow()

  try {
    binding.mkdtempSync(req.handle, prefix + 'XXXXXX')

    return binding.requestResultPath(req.handle)
  } catch (e) {
    throw new FileError(e.message, { operation: 'mkdtempSync', code: e.code, path: prefix })
  } finally {
    req.return()
  }
}

async function rmdir(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.rmdir(req.handle, filepath)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'rmdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function rmdirSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.rmdirSync(req.handle, filepath)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'rmdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function rm(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  let err = null
  try {
    const st = await lstat(filepath)

    if (st.isDirectory()) {
      if (opts.recursive) {
        try {
          await rmdir(filepath)
        } catch (err) {
          if (err.code !== 'ENOTEMPTY') throw err

          const files = await readdir(filepath)

          for (const file of files) {
            await rm(filepath + path.sep + file, opts)
          }

          await rmdir(filepath)
        }
      } else {
        throw new FileError('is a directory', {
          operation: 'rm',
          code: 'EISDIR',
          path: filepath
        })
      }
    } else {
      await unlink(filepath)
    }
  } catch (e) {
    if (e.code !== 'ENOENT' || !opts.force) err = e
  }

  return done(err, cb)
}

function rmSync(filepath, opts) {
  if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  try {
    const st = lstatSync(filepath)

    if (st.isDirectory()) {
      if (opts.recursive) {
        try {
          rmdirSync(filepath)
        } catch (err) {
          if (err.code !== 'ENOTEMPTY') throw err

          const files = readdirSync(filepath)

          for (const file of files) {
            rmSync(filepath + path.sep + file, opts)
          }

          rmdirSync(filepath)
        }
      } else {
        throw new FileError('is a directory', {
          operation: 'rm',
          code: 'EISDIR',
          path: filepath
        })
      }
    } else {
      unlinkSync(filepath)
    }
  } catch (err) {
    if (err.code !== 'ENOENT' || !opts.force) throw err
  }
}

async function unlink(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.unlink(req.handle, filepath)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'unlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function unlinkSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.unlinkSync(req.handle, filepath)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'unlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function rename(src, dst, cb) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.rename(req.handle, src, dst)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'rename',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function renameSync(src, dst) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  try {
    binding.renameSync(req.handle, src, dst)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'rename',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }
}

async function copyFile(src, dst, mode = 0, cb) {
  if (typeof mode === 'function') {
    cb = mode
    mode = 0
  }

  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.copyfile(req.handle, src, dst, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'copyfile',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function copyFileSync(src, dst, mode = 0) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  try {
    binding.copyfileSync(req.handle, src, dst, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'copyfile',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }
}

async function cp(src, dst, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (!opts) opts = {}

  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  let err = null
  try {
    const st = await lstat(src)

    if (st.isDirectory()) {
      if (opts.recursive !== true) {
        throw new FileError('is a directory', { operation: 'cp', code: 'EISDIR', path: src })
      }

      try {
        await lstat(dst)
      } catch (e) {
        if (e.code !== 'ENOENT') throw e

        await mkdir(dst, { mode: st.mode, recursive: true })
      }

      const dir = await opendir(src)
      for await (const { name } of dir) {
        await cp(path.join(src, name), path.join(dst, name), opts)
      }
    } else if (st.isFile()) {
      await copyFile(src, dst)
      await chmod(dst, st.mode)
    }
  } catch (e) {
    err = e
  }

  return done(err, cb)
}

function cpSync(src, dst, opts = {}) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const st = lstatSync(src)

  if (st.isDirectory()) {
    if (opts.recursive !== true) {
      throw new FileError('is a directory', { operation: 'cp', code: 'EISDIR', path: src })
    }

    try {
      lstatSync(dst)
    } catch (e) {
      if (e.code !== 'ENOENT') throw e

      mkdirSync(dst, { mode: st.mode, recursive: true })
    }

    const dir = opendirSync(src)
    for (const { name } of dir) {
      cpSync(path.join(src, name), path.join(dst, name), opts)
    }
  } else if (st.isFile()) {
    copyFileSync(src, dst)
    chmodSync(dst, st.mode)
  }
}

async function realpath(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let res
  let err = null
  try {
    binding.realpath(req.handle, filepath)

    await req

    res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'realpath',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, res, cb)
}

function realpathSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.realpathSync(req.handle, filepath)

    let res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)

    return res
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'realpath',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function readlink(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let res
  let err = null
  try {
    binding.readlink(req.handle, filepath)

    await req

    res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'readlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, res, cb)
}

function readlinkSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.readlinkSync(req.handle, filepath)

    let res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)

    return res
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'readlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function fsync(fd, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fsync(req.handle, fd)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fsync', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fsyncSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.fsyncSync(req.handle, fd)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fsyncSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function fdatasync(fd, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fdatasync(req.handle, fd)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fdatasync', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fdatasyncSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.fdatasyncSync(req.handle, fd)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fdatasyncSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

function normalizeSymlinkTarget(target, type, filepath) {
  if (isWindows) {
    if (type === constants.UV_FS_SYMLINK_JUNCTION) target = path.resolve(filepath, '..', target)

    if (path.isAbsolute(target)) return path.toNamespacedPath(target)

    return target.replace(/\//g, path.sep)
  }

  return target
}

async function symlink(target, filepath, type, cb) {
  if (typeof type === 'function') {
    cb = type
    type = null
  }

  filepath = toNamespacedPath(filepath)

  if (typeof type === 'string') {
    switch (type) {
      case 'dir':
        type = constants.UV_FS_SYMLINK_DIR
        break
      case 'junction':
        type = constants.UV_FS_SYMLINK_JUNCTION
        break
      case 'file':
      default:
        type = 0
        break
    }
  } else if (typeof type !== 'number') {
    if (isWindows) {
      target = path.resolve(filepath, '..', target)

      try {
        type = (await stat(target)).isDirectory()
          ? constants.UV_FS_SYMLINK_DIR
          : constants.UV_FS_SYMLINK_JUNCTION
      } catch {
        type = 0
      }
    } else {
      type = 0
    }
  }

  target = normalizeSymlinkTarget(target, type, filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.symlink(req.handle, target, filepath, type)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'symlink',
      code: e.code,
      path: target,
      destination: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function symlinkSync(target, filepath, type) {
  filepath = toNamespacedPath(filepath)

  if (typeof type === 'string') {
    switch (type) {
      case 'dir':
        type = constants.UV_FS_SYMLINK_DIR
        break
      case 'junction':
        type = constants.UV_FS_SYMLINK_JUNCTION
        break
      case 'file':
      default:
        type = 0
        break
    }
  } else if (typeof type !== 'number') {
    if (isWindows) {
      target = path.resolve(filepath, '..', target)

      try {
        type = statSync(target).isDirectory()
          ? constants.UV_FS_SYMLINK_DIR
          : constants.UV_FS_SYMLINK_JUNCTION
      } catch {
        type = 0
      }
    } else {
      type = 0
    }
  }

  target = normalizeSymlinkTarget(target, type, filepath)

  const req = FileRequest.borrow()

  try {
    binding.symlinkSync(req.handle, target, filepath, type)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'symlink',
      code: e.code,
      path: target,
      destination: filepath
    })
  } finally {
    req.return()
  }
}

async function opendir(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let dir
  let err = null
  try {
    binding.opendir(req.handle, filepath)

    await req

    dir = new Dir(filepath, binding.requestResultDir(req.handle), opts)
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'opendir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, dir, cb)
}

function opendirSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.opendirSync(req.handle, filepath)

    return new Dir(filepath, binding.requestResultDir(req.handle), opts)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'opendir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function readdir(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { withFileTypes = false, recursive = false } = opts

  filepath = toNamespacedPath(filepath)

  const queue = [filepath]
  let result = []
  let err = null
  try {
    while (queue.length !== 0) {
      const dir = await opendir(queue.pop())

      for await (const entry of dir) {
        const entryPath = path.join(entry.parentPath, entry.name)

        if (withFileTypes) {
          result.push(entry)
        } else {
          result.push(path.relative(filepath, entryPath))
        }

        if (recursive && entry.isDirectory()) queue.push(entryPath)
      }
    }
  } catch (e) {
    result = []
    err = e
  }

  return done(err, result, cb)
}

function readdirSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { withFileTypes = false, recursive = false } = opts

  filepath = toNamespacedPath(filepath)

  const queue = [filepath]
  const result = []

  while (queue.length !== 0) {
    const dir = opendirSync(queue.pop(), opts)

    for (const entry of dir) {
      const entryPath = path.join(entry.parentPath, entry.name)

      if (withFileTypes) {
        result.push(entry)
      } else {
        result.push(path.relative(filepath, entryPath))
      }

      if (recursive && entry.isDirectory()) queue.push(entryPath)
    }
  }

  return result
}

async function readFile(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'buffer' } = opts

  let fd = -1
  let buffer = null
  let err = null
  try {
    fd = await open(filepath, opts.flag || 'r')

    const st = await fstat(fd)

    let len = 0

    if (st.size === 0) {
      const buffers = []

      while (true) {
        buffer = Buffer.allocUnsafe(8192)
        const r = await read(fd, buffer)
        len += r
        if (r === 0) break
        buffers.push(buffer.subarray(0, r))
      }

      buffer = Buffer.concat(buffers)
    } else {
      buffer = Buffer.allocUnsafe(st.size)

      while (true) {
        const r = await read(fd, len ? buffer.subarray(len) : buffer)
        len += r
        if (r === 0 || len === buffer.byteLength) break
      }

      if (len !== buffer.byteLength) buffer = buffer.subarray(0, len)
    }

    if (encoding !== 'buffer') buffer = buffer.toString(encoding)
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) await close(fd)
  }

  return done(err, buffer, cb)
}

function readFileSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'buffer' } = opts

  let fd = -1
  try {
    fd = openSync(filepath, opts.flag || 'r')

    const st = fstatSync(fd)

    let buffer
    let len = 0

    if (st.size === 0) {
      const buffers = []

      while (true) {
        buffer = Buffer.allocUnsafe(8192)
        const r = readSync(fd, buffer)
        len += r
        if (r === 0) break
        buffers.push(buffer.subarray(0, r))
      }

      buffer = Buffer.concat(buffers)
    } else {
      buffer = Buffer.allocUnsafe(st.size)

      while (true) {
        const r = readSync(fd, len ? buffer.subarray(len) : buffer)
        len += r
        if (r === 0 || len === buffer.byteLength) break
      }

      if (len !== buffer.byteLength) buffer = buffer.subarray(0, len)
    }

    if (encoding !== 'buffer') buffer = buffer.toString(encoding)

    return buffer
  } finally {
    if (fd !== -1) closeSync(fd)
  }
}

async function writeFile(filepath, data, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (typeof data === 'string') data = Buffer.from(data, opts.encoding)

  let fd = -1
  let len = 0
  let err = null
  try {
    fd = await open(filepath, opts.flag || 'w', opts.mode || 0o666)

    while (true) {
      len += await write(fd, len ? data.subarray(len) : data)
      if (len === data.byteLength) break
    }
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) await close(fd)
  }

  return done(err, len, cb)
}

function writeFileSync(filepath, data, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (typeof data === 'string') data = Buffer.from(data, opts.encoding)

  let fd = -1
  try {
    fd = openSync(filepath, opts.flag || 'w', opts.mode || 0o666)

    let len = 0

    while (true) {
      len += writeSync(fd, len ? data.subarray(len) : data)
      if (len === data.byteLength) break
    }
  } finally {
    if (fd !== -1) closeSync(fd)
  }
}

function appendFile(filepath, data, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (!opts.flag) opts = { ...opts, flag: 'a' }

  return writeFile(filepath, data, opts, cb)
}

function appendFileSync(filepath, data, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (!opts.flag) opts = { ...opts, flag: 'a' }

  return writeFileSync(filepath, data, opts)
}

function watch(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  return new Watcher(filepath, opts, cb)
}

class Stats {
  constructor(
    dev,
    mode,
    nlink,
    uid,
    gid,
    rdev,
    blksize,
    ino,
    size,
    blocks,
    atimeMs,
    mtimeMs,
    ctimeMs,
    birthtimeMs
  ) {
    this.dev = dev
    this.mode = mode
    this.nlink = nlink
    this.uid = uid
    this.gid = gid
    this.rdev = rdev
    this.blksize = blksize
    this.ino = ino
    this.size = size
    this.blocks = blocks
    this.atimeMs = atimeMs
    this.mtimeMs = mtimeMs
    this.ctimeMs = ctimeMs
    this.birthtimeMs = birthtimeMs
    this.atime = new Date(atimeMs)
    this.mtime = new Date(mtimeMs)
    this.ctime = new Date(ctimeMs)
    this.birthtime = new Date(birthtimeMs)
  }

  isDirectory() {
    return (this.mode & constants.S_IFMT) === constants.S_IFDIR
  }

  isFile() {
    return (this.mode & constants.S_IFMT) === constants.S_IFREG
  }

  isBlockDevice() {
    return (this.mode & constants.S_IFMT) === constants.S_IFBLK
  }

  isCharacterDevice() {
    return (this.mode & constants.S_IFMT) === constants.S_IFCHR
  }

  isFIFO() {
    return (this.mode & constants.S_IFMT) === constants.S_IFIFO
  }

  isSymbolicLink() {
    return (this.mode & constants.S_IFMT) === constants.S_IFLNK
  }

  isSocket() {
    return (this.mode & constants.S_IFMT) === constants.S_IFSOCK
  }
}

class StatFs {
  constructor(type, bsize, blocks, bfree, bavail, files, ffree) {
    this.type = type
    this.bsize = bsize
    this.blocks = blocks
    this.bfree = bfree
    this.bavail = bavail
    this.files = files
    this.ffree = ffree
  }
}

class Dir {
  constructor(path, handle, opts = {}) {
    const { encoding = 'utf8', bufferSize = 32 } = opts

    this.path = path

    this._encoding = encoding
    this._capacity = bufferSize
    this._buffer = new FIFO()
    this._ended = false
    this._handle = handle
  }

  async read(cb) {
    if (this._buffer.length) return ok(this._buffer.shift(), cb)
    if (this._ended) return ok(null, cb)

    const req = FileRequest.borrow()

    let entries
    let err = null
    try {
      req.retain(binding.readdir(req.handle, this._handle, this._capacity))

      await req

      entries = binding.requestResultDirents(req.handle)
    } catch (e) {
      err = new FileError(e.message, {
        operation: 'readdir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    if (err) return fail(err, cb)

    if (entries.length === 0) {
      this._ended = true

      return ok(null, cb)
    }

    for (const entry of entries) {
      let name = Buffer.from(entry.name)

      if (this._encoding !== 'buffer') name = name.toString(this._encoding)

      this._buffer.push(new Dirent(this.path, name, entry.type))
    }

    return ok(this._buffer.shift(), cb)
  }

  readSync() {
    if (this._buffer.length) return this._buffer.shift()
    if (this._ended) return null

    const req = FileRequest.borrow()

    let entries
    try {
      req.retain(binding.readdirSync(req.handle, this._handle, this._capacity))

      entries = binding.requestResultDirents(req.handle)
    } catch (e) {
      throw new FileError(e.message, {
        operation: 'readdir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    if (entries.length === 0) {
      this._ended = true

      return null
    }

    for (const entry of entries) {
      let name = Buffer.from(entry.name)

      if (this._encoding !== 'buffer') name = name.toString(this._encoding)

      this._buffer.push(new Dirent(this.path, name, entry.type))
    }

    return this._buffer.shift()
  }

  async close(cb) {
    const req = FileRequest.borrow()

    let err = null
    try {
      binding.closedir(req.handle, this._handle)

      await req
    } catch (e) {
      err = new FileError(e.message, {
        operation: 'closedir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    this._handle = null

    return done(err, cb)
  }

  closeSync() {
    const req = FileRequest.borrow()

    try {
      binding.closedirSync(req.handle, this._handle)
    } catch (e) {
      throw new FileError(e.message, {
        operation: 'closedir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    this._handle = null
  }

  [Symbol.dispose]() {
    this.closeSync()
  }

  async [Symbol.asyncDispose]() {
    await this.close()
  }

  *[Symbol.iterator]() {
    while (true) {
      const entry = this.readSync()
      if (entry === null) break
      yield entry
    }

    this.closeSync()
  }

  async *[Symbol.asyncIterator]() {
    while (true) {
      const entry = await this.read()
      if (entry === null) break
      yield entry
    }

    await this.close()
  }
}

class Dirent {
  constructor(parentPath, name, type) {
    this.parentPath = parentPath
    this.name = name
    this.type = type
  }

  isFile() {
    return this.type === constants.UV_DIRENT_FILE
  }

  isDirectory() {
    return this.type === constants.UV_DIRENT_DIR
  }

  isSymbolicLink() {
    return this.type === constants.UV_DIRENT_LINK
  }

  isFIFO() {
    return this.type === constants.UV_DIRENT_FIFO
  }

  isSocket() {
    return this.type === constants.UV_DIRENT_SOCKET
  }

  isCharacterDevice() {
    return this.type === constants.UV_DIRENT_CHAR
  }

  isBlockDevice() {
    return this.type === constants.UV_DIRENT_BLOCK
  }
}

class FileReadStream extends Readable {
  constructor(path, opts = {}) {
    const { eagerOpen = true } = opts

    super({ eagerOpen, ...opts })

    this.path = path
    this.fd = typeof opts.fd === 'number' ? opts.fd : -1
    this.flags = opts.flags || 'r'
    this.mode = opts.mode || 0o666

    this._offset = opts.start || 0
    this._missing = 0

    if (opts.length) {
      this._missing = opts.length
    } else if (typeof opts.end === 'number') {
      this._missing = opts.end - this._offset + 1
    } else {
      this._missing = -1
    }
  }

  async _open(cb) {
    let err

    if (this.fd === -1) {
      err = null
      try {
        this.fd = await open(this.path, this.flags, this.mode)
      } catch (e) {
        err = e
      }

      if (err) return cb(err)
    }

    let st
    err = null
    try {
      st = await fstat(this.fd)
    } catch (e) {
      err = e
    }

    if (err) return cb(err)

    if (this._missing === -1) this._missing = st.size

    if (st.size < this._offset) {
      this._offset = st.size
      this._missing = 0
    } else if (st.size < this._offset + this._missing) {
      this._missing = st.size - this._offset
    }

    cb(null)
  }

  async _read(size) {
    if (this._missing <= 0) return this.push(null)

    const data = Buffer.allocUnsafe(Math.min(this._missing, size))

    let len
    let err = null
    try {
      len = await read(this.fd, data, 0, data.byteLength, this._offset)
    } catch (e) {
      err = e
    }

    if (err) return this.destroy(err)

    if (len === 0) return this.push(null)

    if (this._missing < len) len = this._missing

    this._missing -= len
    this._offset += len

    this.push(data.subarray(0, len))
  }

  async _destroy(err, cb) {
    if (this.fd === -1) return cb(err)

    try {
      await close(this.fd)
    } catch (e) {
      err = err || e
    }

    cb(err)
  }
}

class FileWriteStream extends Writable {
  constructor(path, opts = {}) {
    const { eagerOpen = true } = opts

    super({ eagerOpen, ...opts })

    this.path = path
    this.fd = typeof opts.fd === 'number' ? opts.fd : -1
    this.flags = opts.flags || 'w'
    this.mode = opts.mode || 0o666
  }

  async _open(cb) {
    if (this.fd !== -1) return cb(null)

    let err = null
    try {
      this.fd = await open(this.path, this.flags, this.mode)
    } catch (e) {
      err = e
    }

    cb(err)
  }

  async _writev(batch, cb) {
    let err = null
    try {
      await writev(
        this.fd,
        batch.map(({ chunk }) => chunk)
      )
    } catch (e) {
      err = e
    }

    cb(err)
  }

  async _destroy(err, cb) {
    if (this.fd === -1) return cb(err)

    try {
      await close(this.fd)
    } catch (e) {
      err = err || e
    }

    cb(err)
  }
}

class Watcher extends EventEmitter {
  constructor(path, opts, onchange) {
    if (typeof opts === 'function') {
      onchange = opts
      opts = {}
    }

    if (!opts) opts = {}

    const { persistent = true, recursive = false, encoding = 'utf8' } = opts

    super()

    this._closed = false
    this._encoding = encoding
    this._handle = binding.watcherInit(path, recursive, this, this._onevent, this._onclose)

    if (!persistent) this.unref()

    if (onchange) this.on('change', onchange)
  }

  close() {
    if (this._closed) return
    this._closed = true

    binding.watcherClose(this._handle)
  }

  ref() {
    if (this._handle) binding.watcherRef(this._handle)
    return this
  }

  unref() {
    if (this._handle) binding.watcherUnref(this._handle)
    return this
  }

  [Symbol.asyncIterator]() {
    const buffer = []
    let done = false
    let error = null
    let next = null

    this.on('change', (eventType, filename) => {
      if (next) {
        next.resolve({ done: false, value: { eventType, filename } })
        next = null
      } else {
        buffer.push({ eventType, filename })
      }
    })
      .on('error', (err) => {
        done = true
        error = err

        if (next) {
          next.reject(error)
          next = null
        }
      })
      .on('close', () => {
        done = true

        if (next) {
          next.resolve({ done })
          next = null
        }
      })

    return {
      next: () =>
        new Promise((resolve, reject) => {
          if (error) return reject(error)

          if (buffer.length) return resolve({ done: false, value: buffer.shift() })

          if (done) return resolve({ done })

          next = { resolve, reject }
        })
    }
  }

  _onevent(err, events, filename) {
    if (err) {
      this.close()
      this.emit('error', err)
    } else {
      const path =
        this._encoding === 'buffer'
          ? Buffer.from(filename)
          : Buffer.from(filename).toString(this._encoding)

      if (events & binding.UV_RENAME) {
        this.emit('change', 'rename', path)
      }

      if (events & binding.UV_CHANGE) {
        this.emit('change', 'change', path)
      }
    }
  }

  _onclose() {
    this._handle = null

    this.emit('close')
  }
}

exports.access = access
exports.appendFile = appendFile
exports.chmod = chmod
exports.chown = chown
exports.close = close
exports.copyFile = copyFile
exports.cp = cp
exports.exists = exists
exports.fchmod = fchmod
exports.fchown = fchown
exports.fdatasync = fdatasync
exports.fstat = fstat
exports.fsync = fsync
exports.ftruncate = ftruncate
exports.futimes = futimes
exports.lchown = lchown
exports.lutimes = lutimes
exports.link = link
exports.lstat = lstat
exports.mkdir = mkdir
exports.mkdtemp = mkdtemp
exports.open = open
exports.opendir = opendir
exports.read = read
exports.readFile = readFile
exports.readdir = readdir
exports.readlink = readlink
exports.readv = readv
exports.realpath = realpath
exports.rename = rename
exports.rm = rm
exports.rmdir = rmdir
exports.stat = stat
exports.statfs = statfs
exports.symlink = symlink
exports.truncate = truncate
exports.unlink = unlink
exports.utimes = utimes
exports.watch = watch
exports.write = write
exports.writeFile = writeFile
exports.writev = writev

exports.accessSync = accessSync
exports.appendFileSync = appendFileSync
exports.chmodSync = chmodSync
exports.chownSync = chownSync
exports.closeSync = closeSync
exports.copyFileSync = copyFileSync
exports.cpSync = cpSync
exports.existsSync = existsSync
exports.fchmodSync = fchmodSync
exports.fchownSync = fchownSync
exports.fdatasyncSync = fdatasyncSync
exports.fstatSync = fstatSync
exports.fsyncSync = fsyncSync
exports.ftruncateSync = ftruncateSync
exports.futimesSync = futimesSync
exports.lchownSync = lchownSync
exports.lutimesSync = lutimesSync
exports.linkSync = linkSync
exports.lstatSync = lstatSync
exports.mkdirSync = mkdirSync
exports.mkdtempSync = mkdtempSync
exports.openSync = openSync
exports.opendirSync = opendirSync
exports.readFileSync = readFileSync
exports.readSync = readSync
exports.readdirSync = readdirSync
exports.readlinkSync = readlinkSync
exports.readvSync = readvSync
exports.realpathSync = realpathSync
exports.renameSync = renameSync
exports.rmSync = rmSync
exports.rmdirSync = rmdirSync
exports.statSync = statSync
exports.statfsSync = statfsSync
exports.symlinkSync = symlinkSync
exports.truncateSync = truncateSync
exports.unlinkSync = unlinkSync
exports.utimesSync = utimesSync
exports.writeFileSync = writeFileSync
exports.writeSync = writeSync
exports.writevSync = writevSync

exports.promises = require('./promises')

exports.Stats = Stats
exports.StatFs = StatFs
exports.Dir = Dir
exports.Dirent = Dirent
exports.Watcher = Watcher

exports.ReadStream = FileReadStream

exports.createReadStream = function createReadStream(path, opts) {
  return new FileReadStream(path, opts)
}

exports.WriteStream = FileWriteStream

exports.createWriteStream = function createWriteStream(path, opts) {
  return new FileWriteStream(path, opts)
}

function toNamespacedPath(filepath) {
  if (typeof filepath !== 'string') {
    if (isURL(filepath)) filepath = fileURLToPath(filepath)
    else filepath = filepath.toString()
  }

  return path.toNamespacedPath(filepath)
}

function toFlags(flags) {
  switch (flags) {
    case 'r':
      return constants.O_RDONLY
    case 'rs': // Fall through.
    case 'sr':
      return constants.O_RDONLY | constants.O_SYNC
    case 'r+':
      return constants.O_RDWR
    case 'rs+': // Fall through.
    case 'sr+':
      return constants.O_RDWR | constants.O_SYNC

    case 'w':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_WRONLY
    case 'wx': // Fall through.
    case 'xw':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_WRONLY | constants.O_EXCL

    case 'w+':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_RDWR
    case 'wx+': // Fall through.
    case 'xw+':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_RDWR | constants.O_EXCL

    case 'a':
      return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY
    case 'ax': // Fall through.
    case 'xa':
      return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY | constants.O_EXCL
    case 'as': // Fall through.
    case 'sa':
      return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY | constants.O_SYNC

    case 'a+':
      return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR
    case 'ax+': // Fall through.
    case 'xa+':
      return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR | constants.O_EXCL
    case 'as+': // Fall through.
    case 'sa+':
      return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR | constants.O_SYNC
    default:
      return 0
  }
}

function toMode(mode) {
  return parseInt(mode, 8)
}
const binding = require('../binding')

module.exports = {
  O_RDWR: binding.O_RDWR,
  O_RDONLY: binding.O_RDONLY,
  O_WRONLY: binding.O_WRONLY,
  O_CREAT: binding.O_CREAT,
  O_TRUNC: binding.O_TRUNC,
  O_APPEND: binding.O_APPEND,

  F_OK: binding.F_OK || 0,
  R_OK: binding.R_OK || 0,
  W_OK: binding.W_OK || 0,
  X_OK: binding.X_OK || 0,

  S_IFMT: binding.S_IFMT,
  S_IFREG: binding.S_IFREG,
  S_IFDIR: binding.S_IFDIR,
  S_IFCHR: binding.S_IFCHR,
  S_IFLNK: binding.S_IFLNK,
  S_IFBLK: binding.S_IFBLK || 0,
  S_IFIFO: binding.S_IFIFO || 0,
  S_IFSOCK: binding.S_IFSOCK || 0,

  S_IRUSR: binding.S_IRUSR || 0,
  S_IWUSR: binding.S_IWUSR || 0,
  S_IXUSR: binding.S_IXUSR || 0,
  S_IRGRP: binding.S_IRGRP || 0,
  S_IWGRP: binding.S_IWGRP || 0,
  S_IXGRP: binding.S_IXGRP || 0,
  S_IROTH: binding.S_IROTH || 0,
  S_IWOTH: binding.S_IWOTH || 0,
  S_IXOTH: binding.S_IXOTH || 0,

  UV_DIRENT_UNKNOWN: binding.UV_DIRENT_UNKNOWN,
  UV_DIRENT_FILE: binding.UV_DIRENT_FILE,
  UV_DIRENT_DIR: binding.UV_DIRENT_DIR,
  UV_DIRENT_LINK: binding.UV_DIRENT_LINK,
  UV_DIRENT_FIFO: binding.UV_DIRENT_FIFO,
  UV_DIRENT_SOCKET: binding.UV_DIRENT_SOCKET,
  UV_DIRENT_CHAR: binding.UV_DIRENT_CHAR,
  UV_DIRENT_BLOCK: binding.UV_DIRENT_BLOCK,

  COPYFILE_EXCL: binding.UV_FS_COPYFILE_EXCL,
  COPYFILE_FICLONE: binding.UV_FS_COPYFILE_FICLONE,
  COPYFILE_FICLONE_FORCE: binding.UV_FS_COPYFILE_FICLONE_FORCE,
  UV_FS_SYMLINK_DIR: binding.UV_FS_SYMLINK_DIR,
  UV_FS_SYMLINK_JUNCTION: binding.UV_FS_SYMLINK_JUNCTION
}
const binding = require('../binding')

module.exports = class FileError extends Error {
  constructor(msg, opts = {}) {
    const { code, operation = null, path = null, destination = null, fd = -1 } = opts

    if (operation !== null) msg += describe(operation, opts)

    super(`${code}: ${msg}`)

    this.code = code

    if (operation !== null) this.operation = operation
    if (path !== null) this.path = path
    if (destination !== null) this.destination = destination
    if (fd !== -1) this.fd = fd
  }

  get name() {
    return 'FileError'
  }

  // For Node.js compatibility
  get errno() {
    return binding.errnos[this.code]
  }

  // For Node.js compatibility
  get syscall() {
    return this.operation
  }

  // For Node.js compatibility
  get dest() {
    return this.destination
  }
}

function describe(operation, opts) {
  const { path = null, destination = null, fd = -1 } = opts

  let result = `, ${operation}`

  if (path !== null) {
    result += ` ${JSON.stringify(path)}`

    if (destination !== null) {
      result += ` -> ${JSON.stringify(destination)}`
    }
  } else if (fd !== -1) {
    result += ` ${fd}`
  }

  return result
}
{
  "name": "bare-fs",
  "version": "4.7.4",
  "description": "Native file system operations for Bare",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./promises": {
      "types": "./promises.d.ts",
      "default": "./promises.js"
    },
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "promises.js",
    "promises.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-fs.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-fs/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-fs#readme",
  "engines": {
    "bare": ">=1.16.0"
  },
  "dependencies": {
    "bare-events": "^2.5.4",
    "bare-path": "^3.0.0",
    "bare-stream": "^2.6.4",
    "bare-url": "^2.2.2",
    "fast-fifo": "^1.3.2"
  },
  "devDependencies": {
    "bare-buffer": "^3.0.2",
    "bare-crypto": "^1.11.2",
    "brittle": "^3.1.1",
    "cmake-bare": "^1.1.7",
    "lunte": "^1.6.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "bare-buffer": "*"
  },
  "peerDependenciesMeta": {
    "bare-buffer": {
      "optional": true
    }
  }
}
const EventEmitter = require('bare-events')
const fs = require('.')

class FileHandle extends EventEmitter {
  constructor(fd) {
    super()

    this.fd = fd
  }

  async close() {
    await fs.close(this.fd)

    this.fd = -1
    this.emit('close')
  }

  async read(buffer, ...args) {
    return {
      bytesRead: await fs.read(this.fd, buffer, ...args),
      buffer
    }
  }

  async readv(buffers, ...args) {
    return {
      bytesRead: await fs.readv(this.fd, buffers, ...args),
      buffers
    }
  }

  async write(buffer, ...args) {
    return {
      bytesWritten: await fs.write(this.fd, buffer, ...args),
      buffer
    }
  }

  async writev(buffers, ...args) {
    return {
      bytesWritten: await fs.writev(this.fd, buffers, ...args),
      buffers
    }
  }

  async stat() {
    return fs.fstat(this.fd)
  }

  async chmod(mode) {
    await fs.fchmod(this.fd, mode)
  }

  async chown(uid, gid) {
    await fs.fchown(this.fd, uid, gid)
  }

  async datasync() {
    return fs.fdatasync(this.fd)
  }

  async sync() {
    return fs.fsync(this.fd)
  }

  async truncate(len) {
    await fs.ftruncate(this.fd, len)
  }

  async utimes(atime, mtime) {
    await fs.futimes(this.fd, atime, mtime)
  }

  createReadStream(opts) {
    return fs.createReadStream(null, { ...opts, fd: this.fd })
  }

  createWriteStream(opts) {
    return fs.createWriteStream(null, { ...opts, fd: this.fd })
  }

  async [Symbol.asyncDispose]() {
    await this.close()
  }
}

exports.open = async function open(filepath, flags, mode) {
  return new FileHandle(await fs.open(filepath, flags, mode))
}

exports.access = fs.access
exports.appendFile = fs.appendFile
exports.chmod = fs.chmod
exports.chown = fs.chown
exports.constants = fs.constants
exports.copyFile = fs.copyFile
exports.cp = fs.cp
exports.lchown = fs.lchown
exports.lutimes = fs.lutimes
exports.link = fs.link
exports.lstat = fs.lstat
exports.mkdir = fs.mkdir
exports.mkdtemp = fs.mkdtemp
exports.opendir = fs.opendir
exports.readFile = fs.readFile
exports.readdir = fs.readdir
exports.readlink = fs.readlink
exports.realpath = fs.realpath
exports.rename = fs.rename
exports.rm = fs.rm
exports.rmdir = fs.rmdir
exports.stat = fs.stat
exports.statfs = fs.statfs
exports.truncate = fs.truncate
exports.symlink = fs.symlink
exports.unlink = fs.unlink
exports.utimes = fs.utimes
exports.watch = fs.watch
exports.writeFile = fs.writeFile
module.exports = require.addon()
const binding = require('./binding')

module.exports = exports = function hrtime(past) {
  let now = binding.hrtime()

  if (past) now -= BigInt(past[0]) * 1000000000n + BigInt(past[1])

  return [Number(now / 1000000000n), Number(now % 1000000000n)]
}

exports.bigint = function hrtime() {
  return binding.hrtime()
}
{
  "name": "bare-hrtime",
  "version": "2.1.1",
  "description": "High-resolution timers for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-hrtime.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-hrtime/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-hrtime#readme",
  "devDependencies": {
    "brittle": "^3.2.1",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  }
}
const errors = require('./lib/errors')

const constants = {
  REQUEST: 1,
  RESPONSE: 2,
  DATA: 3,
  END: 4
}

const TAB = 0x09
const LF = 0x0a
const CR = 0x0d
const SP = 0x20
const ZERO = 0x30
const NINE = 0x39
const UPPER_A = 0x41
const UPPER_F = 0x46
const UPPER_Z = 0x5a
const LOWER_A = 0x61
const LOWER_F = 0x66
const COLON = 0x3a

const MAX_CHUNK_SIZE_LENGTH = 16

// Header states
const FIRST_TOKEN = 0
const REQUEST_URL = 1
const REQUEST_VERSION = 2
const STATUS_CODE = 3
const STATUS_REASON = 4
const FIRST_LINE_LF = 5
const HEADER_START = 6
const HEADER_NAME = 7
const HEADER_VALUE_WS = 8
const HEADER_VALUE = 9
const HEADER_LINE_LF = 10
const HEADER_END_LF = 11

// Body states
const BODY = 12
const CHUNK_SIZE = 13
const CHUNK_SIZE_LF = 14
const CHUNK_DATA = 15
const CHUNK_EXTENSION = 16

// Trailing states
const LAST_CHUNK_LF = 17
const TRAILER_CR = 18
const TRAILER_LF = 19

module.exports = exports = class HTTPParser {
  constructor(opts = {}) {
    const { maxHeaderSize = 16384, maxHeadersCount = 2000 } = opts

    this._maxHeaderSize = maxHeaderSize
    this._maxHeadersCount = maxHeadersCount
    this._state = FIRST_TOKEN
    this._buffer = []
    this._bufferIndex = 0
    this._byteIndex = 0
    this._buffered = 0
    this._accumulator = []

    this._isResponse = false
    this._method = ''
    this._url = ''
    this._version = ''
    this._code = 0
    this._reason = ''

    this._headerName = ''
    this._headers = Object.create(null)
    this._headerCount = 0
    this._headerSize = 0

    this._remaining = 0
  }

  *push(data, encoding) {
    if (typeof data === 'string') data = Buffer.from(data, encoding)

    this._buffer.push(data)
    this._buffered += data.byteLength

    yield* this._parse()

    this._compact()
  }

  end() {
    const buffers = this._buffer
    const bufferIndex = this._bufferIndex
    const byteIndex = this._byteIndex

    this._buffer = []
    this._bufferIndex = 0
    this._byteIndex = 0
    this._buffered = 0

    if (bufferIndex >= buffers.length) return Buffer.alloc(0)

    buffers[bufferIndex] = buffers[bufferIndex].subarray(byteIndex)

    const remaining = buffers.slice(bufferIndex)

    if (remaining.length === 0) return Buffer.alloc(0)
    if (remaining.length === 1) return remaining[0]

    return Buffer.concat(remaining)
  }

  _compact() {
    if (this._bufferIndex > 0) {
      this._buffer = this._buffer.slice(this._bufferIndex)
      this._bufferIndex = 0
    }

    if (this._byteIndex > 0 && this._buffer.length > 0) {
      this._buffer[0] = this._buffer[0].subarray(this._byteIndex)
      this._byteIndex = 0
    }
  }

  _consume(n) {
    this._buffered -= n

    const current = this._buffer[this._bufferIndex]

    if (this._byteIndex + n <= current.byteLength) {
      const slice = current.subarray(this._byteIndex, this._byteIndex + n)

      this._byteIndex += n

      if (this._byteIndex >= current.byteLength) {
        this._bufferIndex++
        this._byteIndex = 0
      }

      return slice
    }

    const result = Buffer.allocUnsafe(n)

    let written = 0

    while (written < n) {
      const buffer = this._buffer[this._bufferIndex]
      const available = buffer.byteLength - this._byteIndex
      const take = Math.min(available, n - written)

      buffer.copy(result, written, this._byteIndex, this._byteIndex + take)

      written += take

      this._byteIndex += take

      if (this._byteIndex >= buffer.byteLength) {
        this._bufferIndex++
        this._byteIndex = 0
      }
    }

    return result
  }

  _buildString() {
    const string = String.fromCharCode.apply(null, this._accumulator)

    this._accumulator = []

    return string
  }

  _checkHeaderSize() {
    if (++this._headerSize > this._maxHeaderSize) {
      throw errors.INVALID_MESSAGE('Header exceeds limit of ' + this._maxHeaderSize + ' bytes')
    }
  }

  _storeHeader(name, value) {
    let end = value.length

    while (end > 0 && (value.charCodeAt(end - 1) === SP || value.charCodeAt(end - 1) === TAB)) {
      end--
    }

    if (end < value.length) value = value.substring(0, end)

    this._headerCount++

    if (this._headerCount > this._maxHeadersCount) {
      throw errors.INVALID_MESSAGE('Header count exceeds limit of ' + this._maxHeadersCount)
    }

    switch (name) {
      case '__proto__':
      case 'constructor':
      case 'prototype':
        throw errors.INVALID_HEADER("Unsafe header name '" + name + "'")

      case 'host':
      case 'content-length':
      case 'transfer-encoding':
        if (name in this._headers) {
          throw errors.INVALID_HEADER("Duplicate header '" + name + "'")
        }

        this._headers[name] = value
        break

      default: {
        const delimiter = name === 'cookie' ? '; ' : ', '

        if (name in this._headers) {
          this._headers[name] += delimiter + value
        } else {
          this._headers[name] = value
        }
      }
    }
  }

  *_parse() {
    while (true) {
      if (this._state === BODY) {
        if (this._buffered === 0) return

        const available = Math.min(this._buffered, this._remaining)
        const data = this._consume(available)

        this._remaining -= available

        const ended = this._remaining === 0

        if (ended) this._state = FIRST_TOKEN

        yield { type: constants.DATA, data }

        if (ended) yield { type: constants.END }

        continue
      }

      if (this._state === CHUNK_DATA) {
        if (this._buffered < this._remaining) return

        const consumed = this._consume(this._remaining)

        if (consumed[this._remaining - 2] !== CR || consumed[this._remaining - 1] !== LF) {
          throw errors.INVALID_MESSAGE('Expected CRLF after chunk data')
        }

        const data = consumed.subarray(0, this._remaining - 2)

        this._remaining = 0
        this._state = CHUNK_SIZE

        yield { type: constants.DATA, data }

        continue
      }

      if (this._buffered === 0) return

      const byte = this._buffer[this._bufferIndex][this._byteIndex++]

      this._buffered--

      if (this._byteIndex >= this._buffer[this._bufferIndex].byteLength) {
        this._bufferIndex++
        this._byteIndex = 0
      }

      switch (this._state) {
        case FIRST_TOKEN: {
          this._checkHeaderSize()

          if (byte === SP) {
            const token = this._buildString()

            if (token.length === 0) throw errors.INVALID_MESSAGE()

            this._isResponse = token.startsWith('HTTP/')

            if (this._isResponse) {
              if (token !== 'HTTP/1.0' && token !== 'HTTP/1.1') {
                throw errors.INVALID_MESSAGE()
              }

              this._version = token
              this._state = STATUS_CODE
            } else {
              this._method = token
              this._state = REQUEST_URL
            }
          } else if (byte === CR) {
            throw errors.INVALID_MESSAGE()
          } else if (isTokenByte(byte)) {
            this._accumulator.push(byte)
          } else if (
            byte === 0x2f &&
            this._accumulator.length === 4 &&
            this._accumulator[0] === 0x48 &&
            this._accumulator[1] === 0x54 &&
            this._accumulator[2] === 0x54 &&
            this._accumulator[3] === 0x50
          ) {
            this._accumulator.push(byte)
          } else {
            throw errors.INVALID_MESSAGE()
          }

          break
        }

        case REQUEST_URL: {
          this._checkHeaderSize()

          if (byte === SP) {
            this._url = this._buildString()

            if (this._url.length === 0) throw errors.INVALID_MESSAGE()

            this._state = REQUEST_VERSION
          } else if (byte === CR) {
            throw errors.INVALID_MESSAGE()
          } else if (byte >= 0x21 && byte !== 0x7f) {
            this._accumulator.push(byte)
          } else {
            throw errors.INVALID_MESSAGE()
          }

          break
        }

        case REQUEST_VERSION: {
          this._checkHeaderSize()

          if (byte === CR) {
            this._version = this._buildString()

            if (this._version !== 'HTTP/1.0' && this._version !== 'HTTP/1.1') {
              throw errors.INVALID_MESSAGE()
            }

            this._state = FIRST_LINE_LF
          } else if (byte >= 0x21 && byte !== 0x7f) {
            this._accumulator.push(byte)
          } else {
            throw errors.INVALID_MESSAGE()
          }

          break
        }

        case STATUS_CODE: {
          this._checkHeaderSize()

          if (byte === SP) {
            if (this._accumulator.length === 0) throw errors.INVALID_MESSAGE()

            let code = 0

            for (let i = 0, n = this._accumulator.length; i < n; i++) {
              code = code * 10 + this._accumulator[i]
            }

            this._accumulator = []

            if (code < 100 || code > 999) throw errors.INVALID_MESSAGE()

            this._code = code
            this._state = STATUS_REASON
          } else if (byte >= ZERO && byte <= NINE) {
            this._accumulator.push(byte - ZERO)
          } else {
            throw errors.INVALID_MESSAGE()
          }

          break
        }

        case STATUS_REASON: {
          this._checkHeaderSize()

          if (byte === CR) {
            this._reason = this._buildString()
            this._state = FIRST_LINE_LF
          } else if (isFieldByte(byte)) {
            this._accumulator.push(byte)
          } else {
            throw errors.INVALID_MESSAGE()
          }

          break
        }

        case FIRST_LINE_LF: {
          if (byte !== LF) throw errors.INVALID_MESSAGE()

          this._headers = Object.create(null)
          this._headerCount = 0
          this._state = HEADER_START

          break
        }

        case HEADER_START: {
          this._checkHeaderSize()

          if (byte === CR) {
            this._state = HEADER_END_LF
          } else if (byte !== COLON && isTokenByte(byte)) {
            this._accumulator.push(byte >= UPPER_A && byte <= UPPER_Z ? byte + 0x20 : byte)
            this._state = HEADER_NAME
          } else {
            throw errors.INVALID_HEADER()
          }

          break
        }

        case HEADER_NAME: {
          this._checkHeaderSize()

          if (byte === COLON) {
            this._headerName = this._buildString()
            this._state = HEADER_VALUE_WS
          } else if (byte !== COLON && isTokenByte(byte)) {
            this._accumulator.push(byte >= UPPER_A && byte <= UPPER_Z ? byte + 0x20 : byte)
          } else {
            throw errors.INVALID_HEADER()
          }

          break
        }

        case HEADER_VALUE_WS: {
          this._checkHeaderSize()

          if (byte === SP || byte === TAB) break

          if (byte === CR) {
            this._storeHeader(this._headerName, '')
            this._headerName = ''
            this._state = HEADER_LINE_LF

            break
          }

          if (!isFieldByte(byte)) throw errors.INVALID_HEADER()

          this._accumulator.push(byte)
          this._state = HEADER_VALUE

          break
        }

        case HEADER_VALUE: {
          this._checkHeaderSize()

          if (byte === CR) {
            this._storeHeader(this._headerName, this._buildString())
            this._headerName = ''
            this._state = HEADER_LINE_LF
          } else if (isFieldByte(byte)) {
            this._accumulator.push(byte)
          } else {
            throw errors.INVALID_HEADER()
          }

          break
        }

        case HEADER_LINE_LF: {
          if (byte !== LF) throw errors.INVALID_HEADER()

          this._state = HEADER_START

          break
        }

        case HEADER_END_LF: {
          if (byte !== LF) throw errors.INVALID_MESSAGE()

          const headers = { ...this._headers }

          if (this._isResponse) {
            yield {
              type: constants.RESPONSE,
              version: this._version,
              code: this._code,
              reason: this._reason,
              headers
            }
          } else {
            if (this._version === 'HTTP/1.1' && !('host' in headers)) {
              throw errors.INVALID_HEADER("Header 'Host' is missing")
            }

            yield {
              type: constants.REQUEST,
              version: this._version,
              method: this._method,
              url: this._url,
              headers
            }
          }

          const transferEncoding = headers['transfer-encoding']
          const contentLength = headers['content-length']

          if (transferEncoding) {
            const encodings = transferEncoding.split(',')

            let chunkedCount = 0

            for (let i = 0, n = encodings.length; i < n; i++) {
              if (encodings[i].trim().toLowerCase() === 'chunked') chunkedCount++
            }

            const lastEncoding = encodings[encodings.length - 1].trim().toLowerCase()

            if (lastEncoding !== 'chunked') {
              throw errors.INVALID_MESSAGE("'Transfer-Encoding' must end with 'chunked'")
            }

            if (chunkedCount > 1) {
              throw errors.INVALID_MESSAGE(
                "'chunked' must not appear more than once in 'Transfer-Encoding'"
              )
            }

            if (contentLength) {
              throw errors.INVALID_MESSAGE(
                "Conflicting 'Content-Length' and 'Transfer-Encoding' headers"
              )
            }

            this._state = CHUNK_SIZE
            this._headerSize = 0

            continue
          }

          if (contentLength) {
            if (contentLength.length === 0) throw errors.INVALID_CONTENT_LENGTH()

            let length = 0

            for (let i = 0, n = contentLength.length; i < n; i++) {
              const c = contentLength.charCodeAt(i)

              if (c < ZERO || c > NINE) throw errors.INVALID_CONTENT_LENGTH()

              length = length * 10 + (c - ZERO)
            }

            if (!Number.isSafeInteger(length) || length < 0) {
              throw errors.INVALID_CONTENT_LENGTH()
            }

            if (length === 0) {
              this._state = FIRST_TOKEN
              this._headerSize = 0

              yield { type: constants.END }
            } else {
              this._state = BODY
              this._remaining = length
              this._headerSize = 0
            }
          } else {
            this._state = FIRST_TOKEN
            this._headerSize = 0

            yield { type: constants.END }
          }

          break
        }

        case CHUNK_SIZE: {
          if (byte === CR || byte === 0x3b) {
            if (this._accumulator.length === 0) throw errors.INVALID_CHUNK_LENGTH()

            let length = 0

            for (let i = 0, n = this._accumulator.length; i < n; i++) {
              length = length * 16 + this._accumulator[i]
            }

            this._accumulator = []

            if (!Number.isSafeInteger(length)) throw errors.INVALID_CHUNK_LENGTH()

            if (byte === 0x3b) {
              this._remaining = length
              this._state = CHUNK_EXTENSION
            } else if (length === 0) {
              this._state = LAST_CHUNK_LF
            } else {
              this._remaining = length + 2
              this._state = CHUNK_SIZE_LF
            }
          } else if (isHex(byte)) {
            if (this._accumulator.length >= MAX_CHUNK_SIZE_LENGTH) {
              throw errors.INVALID_CHUNK_LENGTH()
            }

            this._accumulator.push(hexValue(byte))
          } else {
            throw errors.INVALID_CHUNK_LENGTH()
          }

          break
        }

        case CHUNK_EXTENSION: {
          this._checkHeaderSize()

          if (byte === CR) {
            if (this._remaining === 0) {
              this._state = LAST_CHUNK_LF
            } else {
              this._remaining += 2
              this._state = CHUNK_SIZE_LF
            }
          } else if (!isFieldByte(byte)) {
            throw errors.INVALID_CHUNK_LENGTH()
          }

          break
        }

        case CHUNK_SIZE_LF: {
          if (byte !== LF) throw errors.INVALID_CHUNK_LENGTH()

          this._state = CHUNK_DATA

          break
        }

        case LAST_CHUNK_LF: {
          if (byte !== LF) throw errors.INVALID_CHUNK_LENGTH()

          this._state = TRAILER_CR

          break
        }

        case TRAILER_CR: {
          if (byte !== CR) throw errors.INVALID_MESSAGE()

          this._state = TRAILER_LF

          break
        }

        case TRAILER_LF: {
          if (byte !== LF) throw errors.INVALID_MESSAGE()

          this._state = FIRST_TOKEN
          this._headerSize = 0

          yield { type: constants.END }

          break
        }

        default:
          throw errors.INVALID_MESSAGE()
      }
    }
  }
}

exports.constants = constants

const TOKEN_BYTES = Buffer.from([
  // 0x00-0x1f (control characters) + 0x20 (space)
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  // 0x21-0x41: ! " # $ % & ' ( ) * + , - . / 0-9 : ; < = > ? @ A
  1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1,
  // 0x42-0x62: B-Z [ \ ] ^ _ ` a b
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1,
  // 0x63-0x7f: c-z { | } ~ DEL
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0
])

function isTokenByte(b) {
  return TOKEN_BYTES[b] === 1
}

function isFieldByte(b) {
  return b === TAB || (b >= 0x20 && b <= 0x7e)
}

function isHex(b) {
  return (
    (b >= ZERO && b <= NINE) || (b >= UPPER_A && b <= UPPER_F) || (b >= LOWER_A && b <= LOWER_F)
  )
}

function hexValue(b) {
  if (b >= ZERO && b <= NINE) return b - ZERO
  if (b >= UPPER_A && b <= UPPER_F) return b - UPPER_A + 10
  return b - LOWER_A + 10
}
module.exports = class HTTPParserError extends Error {
  constructor(msg, fn = HTTPParserError, code = fn.name) {
    super(`${code}: ${msg}`)

    this.code = code

    if (Error.captureStackTrace) Error.captureStackTrace(this, fn)
  }

  get name() {
    return 'HTTPParserError'
  }

  static INVALID_MESSAGE(msg = 'Invalid HTTP message') {
    return new HTTPParserError(msg, HTTPParserError.INVALID_MESSAGE)
  }

  static INVALID_HEADER(msg = 'Invalid HTTP header') {
    return new HTTPParserError(msg, HTTPParserError.INVALID_HEADER)
  }

  static INVALID_CONTENT_LENGTH(msg = 'Invalid HTTP Content-Length') {
    return new HTTPParserError(msg, HTTPParserError.INVALID_CONTENT_LENGTH)
  }

  static INVALID_CHUNK_LENGTH(msg = 'Invalid HTTP chunk length') {
    return new HTTPParserError(msg, HTTPParserError.INVALID_CHUNK_LENGTH)
  }
}
{
  "name": "bare-http-parser",
  "version": "1.1.5",
  "description": "Streaming HTTP request and response parser for Bare",
  "exports": {
    "./package": "./package.json",
    ".": "./index.js",
    "./errors": "./lib/errors.js"
  },
  "files": [
    "index.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-http-parser.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-http-parser/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-http-parser#readme",
  "devDependencies": {
    "brittle": "^3.3.0",
    "lunte": "^1.8.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  }
}
exports.IncomingMessage = require('./lib/incoming-message')
exports.OutgoingMessage = require('./lib/outgoing-message')

exports.Agent = require('./lib/agent')
exports.globalAgent = exports.Agent.global

exports.Server = require('./lib/server')
exports.ServerResponse = require('./lib/server-response')
exports.ServerConnection = require('./lib/server-connection')

exports.ClientRequest = require('./lib/client-request')
exports.ClientConnection = require('./lib/client-connection')

exports.constants = require('./lib/constants')
exports.errors = require('./lib/errors')

exports.METHODS = Object.values(exports.constants.method) // For Node.js compatibility
exports.STATUS_CODES = exports.constants.status // For Node.js compatibility

exports.createServer = function createServer(opts, onrequest) {
  return new exports.Server(opts, onrequest)
}

exports.request = function request(url, opts, onresponse) {
  if (typeof opts === 'function') {
    onresponse = opts
    opts = {}
  }

  if (typeof url === 'string') url = new URL(url)

  if (isURL(url)) {
    opts = opts ? { ...url, ...opts } : { ...url }

    opts.host = url.hostname
    opts.path = url.pathname + url.search
    opts.port = url.port ? parseInt(url.port, 10) : defaultPort(url)
  } else {
    opts = url ? { ...url } : {}

    // For Node.js compatibility
    opts.host = opts.hostname || opts.host
    opts.port = typeof opts.port === 'string' ? parseInt(opts.port, 10) : opts.port
  }

  return new exports.ClientRequest(opts, onresponse)
}

exports.get = function get(url, opts, onresponse) {
  const req = exports.request(url, opts, onresponse)
  req.end()
  return req
}

// https://url.spec.whatwg.org/#default-port
function defaultPort(url) {
  switch (url.protocol) {
    case 'ftp:':
      return 21
    case 'http:':
    case 'ws:':
      return 80
    case 'https:':
    case 'wss:':
      return 443
  }

  return null
}

// https://url.spec.whatwg.org/#api
function isURL(url) {
  return (
    url !== null &&
    typeof url === 'object' &&
    typeof url.protocol === 'string' &&
    typeof url.hostname === 'string' &&
    typeof url.pathname === 'string' &&
    typeof url.search === 'string'
  )
}
const EventEmitter = require('bare-events')
const tcp = require('bare-tcp')
const HTTPClientConnection = require('./client-connection')
const errors = require('./errors')

class HTTPSocketSet {
  constructor() {
    this._sockets = new Map()
    this._size = 0
  }

  get size() {
    return this._size
  }

  add(name, socket) {
    const sockets = this._sockets.get(name)

    this._size++

    if (sockets === undefined) this._sockets.set(name, [socket])
    else sockets.push(socket)
  }

  pop(name) {
    const sockets = this._sockets.get(name)
    if (sockets === undefined || sockets.length === 0) return null

    this._size--

    const last = sockets.pop()

    if (sockets.length === 0) this._sockets.delete(name)

    return last
  }

  delete(name, socket) {
    const sockets = this._sockets.get(name)
    if (sockets === undefined) return

    const i = sockets.indexOf(socket)
    if (i === -1) return

    this._size--

    const last = sockets.pop()
    if (last !== socket) sockets[i] = last

    if (sockets.length === 0) this._sockets.delete(name)
  }

  *sockets() {
    for (const sockets of this._sockets.values()) {
      yield* sockets
    }
  }

  *[Symbol.iterator]() {
    for (const [name, sockets] of this._sockets) {
      for (const socket of sockets) yield [name, socket]
    }
  }
}

class HTTPAgent extends EventEmitter {
  constructor(opts = {}) {
    super()

    const { keepAlive = false, keepAliveMsecs = 1000, defaultPort = 80 } = opts

    this._suspended = false
    this._resuming = null

    this._sockets = new HTTPSocketSet()
    this._freeSockets = new HTTPSocketSet()

    this._keepAlive = typeof keepAlive === 'number' ? keepAlive : keepAlive ? keepAliveMsecs : -1
    this._defaultPort = defaultPort

    this._opts = { ...opts }
  }

  get suspended() {
    return this._suspended
  }

  get resumed() {
    return this._resuming ? this._resuming.promise : null
  }

  get sockets() {
    return this._sockets.sockets()
  }

  get freeSockets() {
    return this._freeSockets.sockets()
  }

  get defaultPort() {
    return this._defaultPort
  }

  createConnection(opts) {
    if (this._suspended) throw errors.AGENT_SUSPENDED()

    return tcp.createConnection(opts)
  }

  reuseSocket(socket, req) {
    socket.ref()
  }

  keepSocketAlive(socket) {
    if (this._keepAlive === -1) return false

    socket.setKeepAlive(true, this._keepAlive)
    socket.unref()

    return true
  }

  getName(opts) {
    return `${opts.host}:${opts.port}`
  }

  addRequest(req, opts) {
    opts = { ...opts, ...this._opts }

    const name = this.getName(opts)

    let socket = this._freeSockets.pop(name)

    if (socket) this.reuseSocket(socket, req)
    else {
      const agent = this

      socket = this.createConnection(opts)

      socket
        .on('error', noop) // someone needs to handle it
        .on('free', onfree)
        .on('end', onremove)
        .on('finish', onremove)
        .on('close', onremove)
        .on('timeout', ontimeout)

      function onfree() {
        if (socket.destroyed) return

        if (agent.keepSocketAlive(socket)) {
          agent._freeSockets.add(name, socket)
        } else {
          socket.end()
        }

        agent.emit('free', socket)
      }

      function onremove() {
        socket.off('free', onfree)

        agent._sockets.delete(name, socket)
        agent._freeSockets.delete(name, socket)

        if (agent._sockets.size === 0) HTTPAgent._agents.delete(agent)
      }

      function ontimeout() {
        socket.destroy()

        agent._freeSockets.delete(name, socket)
      }
    }

    if (this._sockets.size === 0) HTTPAgent._agents.add(this)

    this._sockets.add(name, socket)

    req._socket = socket

    const connection = HTTPClientConnection.from(socket, opts)

    connection._req = req
  }

  suspend() {
    if (this._suspended) return

    this._resuming = Promise.withResolvers()
    this._suspended = true

    this.destroy()
  }

  resume() {
    if (this._resuming === null) return

    this._resuming.resolve()
    this._resuming = null
    this._suspended = false
  }

  destroy() {
    for (const socket of this._sockets.sockets()) socket.destroy()
  }

  static _agents = new Set()

  static _onidle() {
    for (const agent of this._agents) {
      agent.destroy()
    }
  }
}

HTTPAgent.global = new HTTPAgent({ keepAlive: 1000, timeout: 5000 })

module.exports = HTTPAgent

Bare.on('idle', HTTPAgent._onidle.bind(HTTPAgent))

function noop() {}
const HTTPParser = require('bare-http-parser')
const HTTPIncomingMessage = require('./incoming-message')
const errors = require('./errors')

const {
  constants: { RESPONSE, DATA, END }
} = HTTPParser

const EMPTY = Buffer.alloc(0)

module.exports = class HTTPClientConnection {
  static _connections = new WeakMap()

  static for(socket) {
    return this._connections.get(socket) || null
  }

  static from(socket, opts) {
    return this.for(socket) || new this(socket, opts)
  }

  constructor(socket, opts = {}) {
    const { IncomingMessage = HTTPIncomingMessage } = opts

    this._socket = socket

    this._req = null
    this._res = null

    this._IncomingMessage = IncomingMessage

    this._parser = new HTTPParser()
    this._idle = true

    this._onerror = this._onerror.bind(this)
    this._onclose = this._onclose.bind(this)
    this._onend = this._onend.bind(this)
    this._ondata = this._ondata.bind(this)
    this._ondrain = this._ondrain.bind(this)
    this._ontimeout = this._ontimeout.bind(this)

    socket
      .on('error', this._onerror)
      .on('close', this._onclose)
      .on('end', this._onend)
      .on('data', this._ondata)
      .on('drain', this._ondrain)
      .on('timeout', this._ontimeout)

    HTTPClientConnection._connections.set(socket, this)
  }

  get socket() {
    return this._socket
  }

  get req() {
    return this._req
  }

  get res() {
    return this._res
  }

  get idle() {
    return this._idle
  }

  _onerror(err) {
    if (this._req) this._req.destroy(err)
  }

  _onclose() {
    if (this._req) this._req.destroy()
  }

  _onend() {
    if (this._req) this._req.destroy(errors.CONNECTION_LOST())
  }

  _ondata(data) {
    this._idle = false

    try {
      for (const op of this._parser.push(data)) {
        switch (op.type) {
          case RESPONSE:
            this._req.on('close', () => {
              this._req = null
            })

            this._res = new this._IncomingMessage(this._socket, {
              headers: op.headers,
              statusCode: op.code,
              statusMessage: op.reason
            })

            this._res.on('close', () => {
              this._res = null
              this._idle = true

              this._socket.emit('free')
            })

            if (op.headers.connection && op.headers.connection.toLowerCase() === 'upgrade') {
              return this._onupgrade(this._parser.end())
            }

            this._req.emit('response', this._res)
            break

          case DATA:
            this._res.push(op.data)
            break

          case END:
            if (this._res) {
              this._res._socket = null
              this._res.push(null)
            }

            if (this._req) {
              this._req._socket = null
              this._req.destroy()
            }
            break
        }
      }
    } catch (err) {
      this._socket.destroy(err)
    }
  }

  _onupgrade(data) {
    this._detach()

    const res = this._res
    const req = this._req

    res._upgrade = req._upgrade = true

    const upgraded = req.emit('upgrade', res, this._socket, data || EMPTY)

    res.push(null)
    req.destroy()

    if (!upgraded) this._socket.destroy()
  }

  _ontimeout() {
    if (this._req) this._req.emit('timeout')
  }

  _ondrain() {
    if (this._req) this._req._continueWrite()
  }

  _detach() {
    this._socket
      .off('error', this._onerror)
      .off('close', this._onclose)
      .off('end', this._onend)
      .off('data', this._ondata)
      .off('drain', this._ondrain)
      .off('timeout', this._ontimeout)

    HTTPClientConnection._connections.delete(this._socket)
  }
}
const HTTPAgent = require('./agent')
const HTTPOutgoingMessage = require('./outgoing-message')
const validate = require('./validate')

const CHUNK_DELIMITER = Buffer.from('\r\n')
const CHUNK_TERMINATOR = Buffer.from('0\r\n\r\n')

module.exports = class HTTPClientRequest extends HTTPOutgoingMessage {
  constructor(opts = {}, onresponse = null) {
    if (typeof opts === 'function') {
      onresponse = opts
      opts = {}
    }

    opts = opts ? { ...opts } : {}

    const agent = opts.agent === false ? new HTTPAgent() : opts.agent || HTTPAgent.global
    const method = opts.method || 'GET'
    const path = opts.path || '/'
    const defaultPort = opts.defaultPort || (agent && agent.defaultPort) || 80
    const host = (opts.host = opts.host || 'localhost')
    const port = (opts.port = opts.port || defaultPort)
    const headers = { host: hostHeader(host, port, defaultPort), ...opts.headers }

    validate.validateMethod(method)
    validate.validatePath(path)

    for (const name of Object.keys(headers)) {
      const n = name.toLowerCase()

      validate.validateHeaderName(n)
      validate.validateHeaderValue(n, headers[name])
    }

    super()

    agent.addRequest(this, opts)

    this._headers = headers
    this._method = method
    this._path = path

    this._chunked = method !== 'GET' && method !== 'HEAD'

    this._pendingWrite = null
    this._pendingFinal = null

    if (onresponse) this.once('response', onresponse)
  }

  get method() {
    return this._method
  }

  get path() {
    return this._path
  }

  // For Node.js compatibility
  abort() {
    return this.destroy()
  }

  _header() {
    validate.validateMethod(this._method)
    validate.validatePath(this._path)

    let h = `${this._method} ${this._path} HTTP/1.1\r\n`

    let upgrade = false

    for (const name of Object.keys(this._headers)) {
      const n = name.toLowerCase()
      const v = this._headers[name]

      validate.validateHeaderName(n)
      validate.validateHeaderValue(n, v)

      if (n === 'content-length') this._chunked = false
      if (n === 'connection' && v && v.toLowerCase() === 'upgrade') upgrade = true

      h += `${httpCase(n)}: ${v}\r\n`
    }

    if (upgrade) this._chunked = false

    if (this._chunked) h += 'Transfer-Encoding: chunked\r\n'

    h += '\r\n'

    return h
  }

  _write(data, encoding, cb) {
    if (this._headersSent === false) this.flushHeaders()

    if (this._chunked) {
      this._socket.write(Buffer.from(data.byteLength.toString(16)))
      this._socket.write(CHUNK_DELIMITER)
    }

    let flushed = this._socket.write(data)

    if (this._chunked) flushed = this._socket.write(CHUNK_DELIMITER)

    if (flushed) cb(null)
    else this._pendingWrite = cb
  }

  _final(cb) {
    if (this._headersSent === false) this.flushHeaders()

    if (this._chunked) this._socket.write(CHUNK_TERMINATOR)

    this._pendingFinal = cb
  }

  _predestroy() {
    super._predestroy()

    this._continueWrite()
    this._continueFinal()
  }

  _continueWrite() {
    if (this._pendingWrite === null) return
    const cb = this._pendingWrite
    this._pendingWrite = null
    cb(null)
  }

  _continueFinal() {
    if (this._pendingFinal === null) return
    const cb = this._pendingFinal
    this._pendingFinal = null
    cb(null)
  }
}

function httpCase(n) {
  let s = ''
  for (const part of n.split('-')) {
    s += (s ? '-' : '') + part.slice(0, 1).toUpperCase() + part.slice(1)
  }
  return s
}

function hostHeader(host, port, defaultPort) {
  const i = host.indexOf(':')

  if (i !== -1 && host.includes(':', i + 1) && host.charCodeAt(0) !== 91 /* [ */) {
    host = `[${host}]`
  }

  if (port && +port !== defaultPort) {
    host += ':' + port
  }

  return host
}
module.exports = {
  method: {
    GET: 'GET',
    HEAD: 'HEAD',
    POST: 'POST',
    PUT: 'PUT',
    DELETE: 'DELETE',
    CONNECT: 'CONNECT',
    OPTIONS: 'OPTIONS',
    TRACE: 'TRACE',
    PATCH: 'PATCH'
  },
  status: {
    100: 'Continue',
    101: 'Switching Protocols',
    102: 'Processing',
    103: 'Early Hints',
    200: 'OK',
    201: 'Created',
    202: 'Accepted',
    203: 'Non-Authoritative Information',
    204: 'No Content',
    205: 'Reset Content',
    206: 'Partial Content',
    207: 'Multi-Status',
    208: 'Already Reported',
    226: 'IM Used',
    300: 'Multiple Choices',
    301: 'Moved Permanently',
    302: 'Found',
    303: 'See Other',
    304: 'Not Modified',
    305: 'Use Proxy',
    307: 'Temporary Redirect',
    308: 'Permanent Redirect',
    400: 'Bad Request',
    401: 'Unauthorized',
    402: 'Payment Required',
    403: 'Forbidden',
    404: 'Not Found',
    405: 'Method Not Allowed',
    406: 'Not Acceptable',
    407: 'Proxy Authentication Required',
    408: 'Request Timeout',
    409: 'Conflict',
    410: 'Gone',
    411: 'Length Required',
    412: 'Precondition Failed',
    413: 'Payload Too Large',
    414: 'URI Too Long',
    415: 'Unsupported Media Type',
    416: 'Range Not Satisfiable',
    417: 'Expectation Failed',
    418: "I'm a Teapot",
    421: 'Misdirected Request',
    422: 'Unprocessable Entity',
    423: 'Locked',
    424: 'Failed Dependency',
    425: 'Too Early',
    426: 'Upgrade Required',
    428: 'Precondition Required',
    429: 'Too Many Requests',
    431: 'Request Header Fields Too Large',
    451: 'Unavailable For Legal Reasons',
    500: 'Internal Server Error',
    501: 'Not Implemented',
    502: 'Bad Gateway',
    503: 'Service Unavailable',
    504: 'Gateway Timeout',
    505: 'HTTP Version Not Supported',
    506: 'Variant Also Negotiates',
    507: 'Insufficient Storage',
    508: 'Loop Detected',
    509: 'Bandwidth Limit Exceeded',
    510: 'Not Extended',
    511: 'Network Authentication Required'
  }
}
module.exports = class HTTPError extends Error {
  constructor(msg, fn = HTTPError, code = fn.name) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'HTTPError'
  }

  static NOT_IMPLEMENTED(msg = 'Method not implemented') {
    return new HTTPError(msg, HTTPError.NOT_IMPLEMENTED)
  }

  static CONNECTION_LOST(msg = 'Socket hung up') {
    return new HTTPError(msg, HTTPError.CONNECTION_LOST)
  }

  static AGENT_SUSPENDED(msg = 'Agent is suspended') {
    return new HTTPError(msg, HTTPError.AGENT_SUSPENDED)
  }

  static INVALID_HEADER_NAME(msg = 'Invalid header name') {
    return new HTTPError(msg, HTTPError.INVALID_HEADER_NAME)
  }

  static INVALID_HEADER_VALUE(msg = 'Invalid header value') {
    return new HTTPError(msg, HTTPError.INVALID_HEADER_VALUE)
  }
}
const { Readable } = require('bare-stream')

module.exports = class HTTPIncomingMessage extends Readable {
  constructor(socket = null, opts = {}) {
    super()

    this._socket = socket
    this._upgrade = false
    this._headers = opts.headers || {}

    // Server options
    this._method = opts.method || ''
    this._url = opts.url || ''

    // Client options
    this._statusCode = opts.statusCode || 0
    this._statusMessage = opts.statusMessage || ''
  }

  get socket() {
    return this._socket
  }

  get upgrade() {
    return this._upgrade
  }

  get headers() {
    return this._headers
  }

  set headers(value) {
    this._headers = value
  }

  get method() {
    return this._method
  }

  set method(value) {
    this._method = value
  }

  get url() {
    return this._url
  }

  set url(value) {
    this._url = value
  }

  get statusCode() {
    return this._statusCode
  }

  set statusCode(value) {
    this._statusCode = value
  }

  get statusMessage() {
    return this._statusMessage
  }

  set statusMessage(value) {
    this._statusMessage = value
  }

  get httpVersion() {
    return '1.1'
  }

  getHeader(name) {
    return this._headers[name.toLowerCase()]
  }

  getHeaders() {
    return { ...this._headers }
  }

  hasHeader(name) {
    return name.toLowerCase() in this._headers
  }

  setTimeout(ms, ontimeout) {
    if (ontimeout) this.once('timeout', ontimeout)

    this._socket.setTimeout(ms)

    return this
  }

  _predestroy() {
    if (this._upgrade === false && this._socket !== null) this._socket.destroy()
  }
}
const { Writable } = require('bare-stream')
const errors = require('./errors')
const validate = require('./validate')

module.exports = class HTTPOutgoingMessage extends Writable {
  constructor(socket = null) {
    super()

    this._socket = socket
    this._upgrade = false
    this._headersSent = false
    this._headers = {}
  }

  get socket() {
    return this._socket
  }

  get upgrade() {
    return this._upgrade
  }

  get headersSent() {
    return this._headersSent
  }

  get headers() {
    return this._headers
  }

  set headers(value) {
    if (value) {
      for (const name of Object.keys(value)) {
        const n = name.toLowerCase()

        validate.validateHeaderName(n)
        validate.validateHeaderValue(n, value[name])
      }
    }

    this._headers = value
  }

  getHeader(name) {
    return this._headers[name.toLowerCase()]
  }

  getHeaders() {
    return { ...this._headers }
  }

  hasHeader(name) {
    return name.toLowerCase() in this._headers
  }

  setHeader(name, value) {
    const n = name.toLowerCase()

    validate.validateHeaderName(n)
    validate.validateHeaderValue(n, value)

    this._headers[n] = value
  }

  flushHeaders() {
    if (this._headersSent === true || this._socket === null) return

    this._socket.write(Buffer.from(this._header()))
    this._headersSent = true
  }

  setTimeout(ms, ontimeout) {
    if (ontimeout) this.once('timeout', ontimeout)

    this._socket.setTimeout(ms)

    return this
  }

  _header() {
    throw errors.NOT_IMPLEMENTED()
  }

  _predestroy() {
    if (this._upgrade === false && this._socket !== null) this._socket.destroy()
  }
}
const { isEnded, isFinished, getStreamError } = require('bare-stream')
const HTTPParser = require('bare-http-parser')
const HTTPIncomingMessage = require('./incoming-message')
const HTTPServerResponse = require('./server-response')

const {
  constants: { REQUEST, DATA, END }
} = HTTPParser

const EMPTY = Buffer.alloc(0)

module.exports = class HTTPServerConnection {
  static _connections = new WeakMap()

  static for(socket) {
    return this._connections.get(socket) || null
  }

  constructor(server, socket, opts = {}) {
    const { IncomingMessage = HTTPIncomingMessage, ServerResponse = HTTPServerResponse } = opts

    this._server = server
    this._socket = socket

    this._req = null
    this._res = null

    this._IncomingMessage = IncomingMessage
    this._ServerResponse = ServerResponse

    this._parser = new HTTPParser()
    this._idle = true

    this._onclose = this._onclose.bind(this)
    this._ondata = this._ondata.bind(this)
    this._ondrain = this._ondrain.bind(this)
    this._ontimeout = this._ontimeout.bind(this)

    socket
      .on('error', noop)
      .on('close', this._onclose)
      .on('data', this._ondata)
      .on('drain', this._ondrain)
      .on('timeout', this._ontimeout)

    HTTPServerConnection._connections.set(socket, this)

    if (this._server.timeout) socket.setTimeout(this._server.timeout)
  }

  get server() {
    return this._server
  }

  get socket() {
    return this._socket
  }

  get req() {
    return this._req
  }

  get res() {
    return this._res
  }

  get idle() {
    return this._idle
  }

  _onclose() {
    if (this._req && !isEnded(this._req)) this._req.destroy()
    if (this._res && !isFinished(this._res)) this._res.destroy()

    const err = getStreamError(this._socket)
    if (err) this._socket.destroy(err)
  }

  _ondata(data) {
    this._idle = false

    try {
      for (const op of this._parser.push(data)) {
        switch (op.type) {
          case REQUEST:
            this._req = new this._IncomingMessage(this._socket, {
              headers: op.headers,
              method: op.method,
              url: op.url
            })

            this._req.on('close', () => {
              this._req = null

              this._idle = true

              if (this._server.closing) this._socket.destroy()
            })

            // Eagerly open the request stream
            this._req.resume()
            this._req.pause()

            if (op.headers.connection && op.headers.connection.toLowerCase() === 'upgrade') {
              return this._onupgrade(this._parser.end())
            }

            this._res = new this._ServerResponse(this._socket, this._req)

            this._res.on('close', () => {
              this._res = null
            })

            this._server.emit('request', this._req, this._res)
            break

          case DATA:
            this._req.push(op.data)
            break

          case END:
            if (this._req) {
              this._req._socket = null
              this._req.push(null)
            }
            break
        }
      }
    } catch (err) {
      this._socket.destroy(err)
    }
  }

  _onupgrade(data) {
    this._detach()

    const req = this._req

    req._upgrade = true

    const upgraded = this._server.emit('upgrade', req, this._socket, data || EMPTY)

    req.push(null)

    if (!upgraded) this._socket.destroy()
  }

  _ontimeout() {
    const reqTimeout = this._req && this._req.emit('timeout')
    const resTimeout = this._res && this._res.emit('timeout')
    const serverTimeout = this._server.emit('timeout', this._socket)

    if (!reqTimeout && !resTimeout && !serverTimeout) this._socket.destroy()
  }

  _ondrain() {
    if (this._res) this._res._continueWrite()
  }

  _detach() {
    this._socket
      .off('error', noop)
      .off('close', this._onclose)
      .off('data', this._ondata)
      .off('drain', this._ondrain)
      .off('timeout', this._ontimeout)

    HTTPServerConnection._connections.delete(this._socket)
  }
}

function noop() {}
const { isFinishing } = require('bare-stream')
const HTTPOutgoingMessage = require('./outgoing-message')
const constants = require('./constants')
const validate = require('./validate')

const CHUNK_DELIMITER = Buffer.from('\r\n')
const CHUNK_TERMINATOR = Buffer.from('0\r\n\r\n')

module.exports = class HTTPServerResponse extends HTTPOutgoingMessage {
  constructor(socket, req) {
    super(socket)

    this._req = req

    this._statusCode = 200
    this._statusMessage = null

    this._chunked = true
    this._close = req.headers.connection === 'close'
    this._onlyHeaders = req.method === 'HEAD'

    this._pendingWrite = null
  }

  get req() {
    return this._req
  }

  get statusCode() {
    return this._statusCode
  }

  set statusCode(value) {
    this._statusCode = value
  }

  get statusMessage() {
    return this._statusMessage
  }

  set statusMessage(value) {
    validate.validateStatusMessage(value)

    this._statusMessage = value
  }

  writeHead(statusCode, statusMessage = null, headers = {}) {
    if (typeof statusMessage === 'object' && statusMessage !== null) {
      headers = statusMessage
      statusMessage = null
    }

    if (statusMessage !== null) validate.validateStatusMessage(statusMessage)

    if (headers) {
      for (const name of Object.keys(headers)) {
        const n = name.toLowerCase()

        validate.validateHeaderName(n)
        validate.validateHeaderValue(n, headers[name])
      }
    }

    this._statusCode = statusCode
    this._statusMessage = statusMessage || null

    if (headers) this._headers = { ...this._headers, ...headers }
  }

  _header() {
    const statusMessage =
      this._statusMessage === null ? constants.status[this._statusCode] : this._statusMessage

    validate.validateStatusMessage(statusMessage)

    let h = 'HTTP/1.1 ' + this._statusCode + ' ' + statusMessage + '\r\n'

    for (const name of Object.keys(this._headers)) {
      const n = name.toLowerCase()
      const v = this._headers[name]

      validate.validateHeaderName(n)
      validate.validateHeaderValue(n, v)

      if (n === 'content-length') this._chunked = false
      if (n === 'connection' && v && v.toLowerCase() === 'close') this._close = true

      h += httpCase(n) + ': ' + v + '\r\n'
    }

    if (this._chunked) h += 'Transfer-Encoding: chunked\r\n'

    h += '\r\n'

    return h
  }

  _write(data, encoding, cb) {
    if (this._headersSent === false) {
      if (isFinishing(this)) {
        this.setHeader(
          'Content-Length',
          (data.byteLength + this._writableState.buffered).toString()
        )
      }

      this.flushHeaders()
    }

    if (this._onlyHeaders === true) return cb(null)

    if (this._chunked) {
      this._socket.write(Buffer.from(data.byteLength.toString(16)))
      this._socket.write(CHUNK_DELIMITER)
    }

    let flushed = this._socket.write(data)

    if (this._chunked) flushed = this._socket.write(CHUNK_DELIMITER)

    if (flushed) cb(null)
    else this._pendingWrite = cb
  }

  _final(cb) {
    if (this._headersSent === false) {
      this.setHeader('Content-Length', '0')
      this.flushHeaders()
    }

    if (this._chunked && this._onlyHeaders === false) this._socket.write(CHUNK_TERMINATOR)

    if (this._close) this._socket.end()

    cb(null)
  }

  _predestroy() {
    super._predestroy()

    this._req.destroy()

    this._continueWrite()
  }

  _continueWrite() {
    if (this._pendingWrite === null) return
    const cb = this._pendingWrite
    this._pendingWrite = null
    cb(null)
  }
}

function httpCase(n) {
  let s = ''
  for (const part of n.split('-')) {
    s += (s ? '-' : '') + part.slice(0, 1).toUpperCase() + part.slice(1)
  }
  return s
}
const TCPServer = require('bare-tcp').Server
const HTTPServerConnection = require('./server-connection')

module.exports = class HTTPServer extends TCPServer {
  constructor(opts = {}, onrequest) {
    if (typeof opts === 'function') {
      onrequest = opts
      opts = {}
    }

    super({ allowHalfOpen: false })

    this._timeout = 0

    this.on('connection', (socket) => {
      new HTTPServerConnection(this, socket, opts)
    })

    if (onrequest) this.on('request', onrequest)
  }

  get timeout() {
    return this._timeout || undefined // For Node.js compatibility
  }

  setTimeout(ms = 0, ontimeout) {
    if (ontimeout) this.on('timeout', ontimeout)

    this._timeout = ms

    return this
  }

  close(onclose) {
    super.close(onclose)

    for (const socket of this.connections) {
      const connection = HTTPServerConnection.for(socket)

      if (connection === null || connection.idle) {
        socket.destroy()
      }
    }

    return this
  }
}
const errors = require('./errors')

// RFC 7230 token = 1*tchar
const TOKEN_RE = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/

// Reject characters that would terminate or split the current line
const VALUE_INVALID_RE = /[\r\n\0]/

// Reject control chars and whitespace in the request-target
const PATH_INVALID_RE = /[\r\n\0\s]/

exports.validateHeaderName = function (name) {
  if (typeof name !== 'string' || !TOKEN_RE.test(name)) {
    throw errors.INVALID_HEADER_NAME(`Invalid header name: ${JSON.stringify(name)}`)
  }
}

exports.validateHeaderValue = function (name, value) {
  if (value === undefined || value === null) return
  if (VALUE_INVALID_RE.test(String(value))) {
    throw errors.INVALID_HEADER_VALUE(
      `Invalid character in header value for ${JSON.stringify(name)}`
    )
  }
}

exports.validateStatusMessage = function (value) {
  if (value === undefined || value === null) return
  if (VALUE_INVALID_RE.test(String(value))) {
    throw errors.INVALID_HEADER_VALUE('Invalid character in status message')
  }
}

exports.validatePath = function (value) {
  if (typeof value !== 'string' || value.length === 0 || PATH_INVALID_RE.test(value)) {
    throw errors.INVALID_HEADER_VALUE(`Invalid character in request path: ${JSON.stringify(value)}`)
  }
}

exports.validateMethod = function (value) {
  if (typeof value !== 'string' || !TOKEN_RE.test(value)) {
    throw errors.INVALID_HEADER_NAME(`Invalid HTTP method: ${JSON.stringify(value)}`)
  }
}
{
  "name": "bare-http1",
  "version": "4.5.7",
  "description": "Native HTTP/1 library for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    },
    "./errors": {
      "types": "./lib/errors.d.ts",
      "default": "./lib/errors.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-http1.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-http1/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-http1#readme",
  "dependencies": {
    "bare-events": "^2.6.0",
    "bare-http-parser": "^1.1.1",
    "bare-stream": "^2.10.0",
    "bare-tcp": "^2.2.0"
  },
  "devDependencies": {
    "bare-buffer": "^3.0.2",
    "bare-url": "^2.1.3",
    "brittle": "^3.3.0",
    "lunte": "^1.6.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "bare-buffer": "*",
    "bare-url": "*"
  },
  "peerDependenciesMeta": {
    "bare-buffer": {
      "optional": true
    },
    "bare-url": {
      "optional": true
    }
  }
}
exports.Agent = require('./lib/agent')
exports.globalAgent = exports.Agent.global

exports.Server = require('./lib/server')

exports.ClientRequest = require('./lib/client-request')

exports.createServer = function createServer(opts, onrequest) {
  return new exports.Server(opts, onrequest)
}

exports.request = function request(url, opts, onresponse) {
  if (typeof opts === 'function') {
    onresponse = opts
    opts = {}
  }

  if (typeof url === 'string') url = new URL(url)

  if (isURL(url)) {
    opts = opts ? { ...url, ...opts } : { ...url }

    opts.host = url.hostname
    opts.path = url.pathname + url.search
    opts.port = url.port ? parseInt(url.port, 10) : defaultPort(url)
  } else {
    opts = url ? { ...url } : {}

    // For Node.js compatibility
    opts.host = opts.hostname || opts.host
    opts.port = typeof opts.port === 'string' ? parseInt(opts.port, 10) : opts.port
  }

  return new exports.ClientRequest(opts, onresponse)
}

// https://url.spec.whatwg.org/#default-port
function defaultPort(url) {
  switch (url.protocol) {
    case 'ftp:':
      return 21
    case 'http:':
    case 'ws:':
      return 80
    case 'https:':
    case 'wss:':
      return 443
  }

  return null
}

// https://url.spec.whatwg.org/#api
function isURL(url) {
  return (
    url !== null &&
    typeof url === 'object' &&
    typeof url.protocol === 'string' &&
    typeof url.hostname === 'string' &&
    typeof url.pathname === 'string' &&
    typeof url.search === 'string'
  )
}
const HTTPAgent = require('bare-http1').Agent
const HTTPSSocket = require('./socket')

class HTTPSAgent extends HTTPAgent {
  constructor(opts = {}) {
    super({ defaultPort: 443, ...opts })
  }

  createConnection(opts) {
    return new HTTPSSocket(super.createConnection(opts), opts)
  }
}

HTTPSAgent.global = new HTTPSAgent({ keepAlive: 1000, timeout: 5000 })

module.exports = HTTPSAgent
const HTTPClientRequest = require('bare-http1').ClientRequest
const HTTPSAgent = require('./agent')

module.exports = class HTTPSClientRequest extends HTTPClientRequest {
  constructor(opts = {}, onresponse = null) {
    if (typeof opts === 'function') {
      onresponse = opts
      opts = {}
    }

    opts = opts ? { ...opts } : {}

    opts.agent = opts.agent === false ? new HTTPSAgent() : opts.agent || HTTPSAgent.global

    super(opts, onresponse)
  }
}
const TCPServer = require('bare-tcp').Server
const HTTPServerConnection = require('bare-http1').ServerConnection
const HTTPSSocket = require('./socket')

module.exports = class HTTPSServer extends TCPServer {
  constructor(opts = {}, onrequest) {
    if (typeof opts === 'function') {
      onrequest = opts
      opts = {}
    }

    super({ allowHalfOpen: false })

    this._timeout = 0

    this.on('connection', (socket) => {
      new HTTPServerConnection(this, new HTTPSSocket(socket, { ...opts, isServer: true }), opts)
    })

    if (onrequest) this.on('request', onrequest)
  }

  get timeout() {
    return this._timeout || undefined // For Node.js compatibility
  }

  setTimeout(ms = 0, ontimeout) {
    if (ontimeout) this.on('timeout', ontimeout)

    this._timeout = ms

    return this
  }

  close(onclose) {
    super.close(onclose)

    for (const socket of this.connections) {
      const connection = HTTPServerConnection.for(socket)

      if (connection === null || connection.idle) {
        socket.destroy()
      }
    }

    return this
  }
}
const TLSSocket = require('bare-tls').Socket

module.exports = class HTTPSSocket extends TLSSocket {
  setKeepAlive(...args) {
    this.socket.setKeepAlive(...args)

    return this
  }

  setNoDelay(...args) {
    this.socket.setNoDelay(...args)

    return this
  }

  setTimeout(...args) {
    this.socket.setTimeout(...args)

    return this
  }

  ref() {
    this.socket.ref()

    return this
  }

  unref() {
    this.socket.unref()

    return this
  }
}
{
  "name": "bare-https",
  "version": "3.0.0",
  "description": "HTTPS library for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-https.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-https/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-https#readme",
  "dependencies": {
    "bare-http1": "^4.4.0",
    "bare-tcp": "^2.2.0",
    "bare-tls": "^3.0.0"
  },
  "devDependencies": {
    "bare-fs": "^4.0.0",
    "brittle": "^3.3.0",
    "lunte": "^1.7.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = require.addon()
const ansiEscapes = require('bare-ansi-escapes')
const getType = require('bare-type')
const binding = require('./binding')

const PLAIN_KEY = /^[a-zA-Z_][a-zA-Z_0-9]*$/

const defaultDepth = 2
const defaultBreakLength = 80
const defaultMaxArrayLength = 40

module.exports = exports = function inspect(value, opts = {}) {
  const {
    colors = false,
    depth = defaultDepth,
    breakLength = defaultBreakLength,
    stylize = defaultStylize(colors)
  } = opts

  const references = new InspectRefMap()

  const tree = inspectValue(value, 0, {
    colors,
    depth,
    breakLength,
    stylize,
    references
  })

  return tree.toString()
}

exports.styles = {
  bigint: ansiEscapes.colorYellow,
  boolean: ansiEscapes.colorYellow,
  date: ansiEscapes.colorMagenta,
  module: ansiEscapes.modifierUnderline,
  name: ansiEscapes.modifierReset,
  null: ansiEscapes.modifierBold,
  number: ansiEscapes.colorYellow,
  regexp: ansiEscapes.colorRed,
  special: ansiEscapes.colorCyan,
  string: ansiEscapes.colorGreen,
  symbol: ansiEscapes.colorGreen,
  undefined: ansiEscapes.colorBrightBlack
}

const styles = exports.styles

function defaultStylize(colors) {
  return function stylize(value, style) {
    const color = colors && styles[style]

    if (color) return color + value + ansiEscapes.modifierReset

    return value
  }
}

class InspectRefMap {
  constructor() {
    this.refs = new WeakMap()
    this.ids = new WeakMap()
    this.nextId = 1
  }

  has(object) {
    return this.refs.has(object)
  }

  get(object) {
    return this.refs.get(object) || null
  }

  set(object, ref) {
    this.refs.set(object, ref)
  }

  id(object) {
    let id = this.ids.get(object)
    if (id) return id

    id = this.nextId++
    this.ids.set(object, id)

    return id
  }
}

class InspectNode {
  constructor(depth, length, opts) {
    const { breakLength = defaultBreakLength, breakAlways = false } = opts

    this.depth = depth
    this.length = length
    this.breakLength = breakLength
    this.breakAlways = breakAlways
  }

  pad(n, string) {
    return string.padStart(n, ' ')
  }

  indent(n, string) {
    return '  '.repeat(n) + string
  }
}

class InspectRef extends InspectNode {
  constructor(depth, opts) {
    super(depth, '[circular *]'.length, opts)

    this.refs = opts.references
    this.count = 0
    this.circular = false
    this.color = opts.colors && styles.special
  }

  get id() {
    return this.refs.id(this)
  }

  increment() {
    return ++this.count
  }

  decrement() {
    return --this.count
  }

  toString(opts = {}) {
    const { offset = 0, pad = 0, indent = 0 } = opts

    let value = this.pad(pad, '[circular *' + this.id + ']')

    if (this.color) value = this.color + value + ansiEscapes.modifierReset

    return offset ? value : this.indent(indent, value)
  }
}

class InspectLeaf extends InspectNode {
  constructor(value, color, depth, opts) {
    const length = value.length

    if (value.includes('\n')) {
      value = value.replaceAll('\n', '\n' + '  '.repeat(depth))

      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.value = value
    this.color = opts.colors && color
  }

  toString(opts = {}) {
    const { offset = 0, pad = 0, indent = 0 } = opts

    let value = this.pad(pad, this.value)

    if (this.color) value = this.color + value + ansiEscapes.modifierReset

    return offset ? value : this.indent(indent, value)
  }
}

class InspectPair extends InspectNode {
  constructor(delim, left, right, depth, opts) {
    const length = left.length + delim.length + right.length

    if (left.breakAlways || right.breakAlways) {
      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.delim = delim
    this.left = left
    this.right = right
  }

  toString(opts = {}) {
    const { indent = 0 } = opts

    return this.indent(
      indent,
      this.left +
        this.delim +
        this.right.toString({
          indent,
          offset: this.left.length + this.delim.length
        })
    )
  }
}

class InspectSuspension extends InspectNode {
  constructor(overflow, depth, opts) {
    const label = `... ${overflow} more`

    super(depth, label.length, opts)

    this.label = label
  }

  toString(opts = {}) {
    const { indent = 0 } = opts

    return this.indent(indent, this.label)
  }
}

class InspectSequence extends InspectNode {
  constructor(header, footer, delim, values, ref, depth, opts) {
    const { tabulate = false } = opts

    const length =
      (ref.circular ? '<ref *>'.length + 1 : 0) +
      header.length +
      values.reduce(
        (length, value, i) =>
          length + value.length + (i === 0 ? 0 : delim.length),
        0
      ) +
      footer.length

    if (values.some((value) => value.breakAlways)) {
      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.header = header
    this.footer = footer
    this.delim = delim
    this.values = values
    this.ref = ref
    this.tabulate = tabulate
  }

  toString(opts = {}) {
    const { offset = 0, indent = 0 } = opts

    const split =
      this.breakAlways ||
      (this.values.length &&
        (offset + this.length > this.breakLength ||
          indent * 2 + this.length > this.breakLength))

    let header = this.header

    if (this.ref.circular) {
      header = '<ref *' + this.ref.id + '> ' + header
    }

    if (this.values.length === 0) {
      header = header.trimEnd()
    }

    if (offset === 0) {
      header = this.indent(indent, header)
    }

    if (split) {
      header = header.trimEnd() + '\n'
    }

    let string = header

    let columns = 1
    let pad = 0

    if (this.tabulate) {
      const widest = this.values.reduce(
        (length, value) =>
          value.breakAlways ? length : Math.max(length, value.length),
        0
      )

      if (widest) {
        columns = Math.max(
          columns,
          Math.floor(
            (this.breakLength - indent * 2) / (widest + this.delim.length)
          )
        )

        if (columns > 1) pad = widest
      }
    }

    for (let i = 0, n = this.values.length, offset = 0; i < n; i++) {
      const value = this.values[i]

      if (split) {
        let part

        if (i % columns === 0 || value.breakAlways) {
          part = value.toString({ indent: indent + 1, pad })
        } else {
          part = value.toString({ pad })
        }

        string += part

        if (i < n - 1) {
          if (i % columns === columns - 1 || this.values[i + 1].breakAlways) {
            string += this.delim.trimEnd() + '\n'
          } else {
            string += this.delim
          }
        }
      } else {
        if (i > 0) string += this.delim

        string += value.toString({ offset })

        offset += value.length
      }
    }

    let footer = this.footer

    if (this.values.length === 0) {
      footer = footer.trimStart()
    }

    if (split) {
      string += '\n' + this.indent(indent, footer.trimStart())
    } else {
      string += footer
    }

    return string
  }
}

function inspectValue(value, depth, opts) {
  const type = getType(value)

  if (type.isUndefined()) return inspectUndefined(depth, opts)
  if (type.isNull()) return inspectNull(depth, opts)
  if (type.isBoolean()) return inspectBoolean(value, depth, opts)
  if (type.isNumber()) return inspectNumber(value, depth, opts)
  if (type.isBigInt()) return inspectBigInt(value, depth, opts)
  if (type.isString()) return inspectString(value, depth, opts)
  if (type.isSymbol()) return inspectSymbol(value, depth, opts)
  if (type.isObject()) return inspectObject(type, value, depth, opts)
  if (type.isFunction()) return inspectFunction(type, value, depth, opts)
  if (type.isExternal()) return inspectExternal(value, opts, opts)
}

function inspectUndefined(depth, opts) {
  return new InspectLeaf('undefined', styles.undefined, depth, opts)
}

function inspectNull(depth, opts) {
  return new InspectLeaf('null', styles.null, depth, opts)
}

function inspectBoolean(value, depth, opts) {
  return new InspectLeaf(value.toString(), styles.boolean, depth, opts)
}

function inspectNumber(value, depth, opts) {
  let string

  if (Object.is(value, -0)) {
    string = '-0'
  } else {
    string = value.toString(10)
  }

  return new InspectLeaf(string, styles.number, depth, opts)
}

function inspectBigInt(value, depth, opts) {
  return new InspectLeaf(value.toString(10) + 'n', styles.bigint, depth, opts)
}

const STRING_ESCAPES =
  /[\ud800-\udbff][\udc00-\udfff]|[\u0000-\u001f'\\\ud800-\udfff]/g

function inspectString(value, depth, opts) {
  // https://tc39.es/ecma262/multipage/structured-data.html#sec-quotejsonstring
  const string = value.replace(STRING_ESCAPES, (match) => {
    if (match.length === 2) return match

    switch (match) {
      case "'":
        return "\\'"
      case '\\':
        return '\\\\'
      case '\b':
        return '\\b'
      case '\t':
        return '\\t'
      case '\n':
        return '\\n'
      case '\f':
        return '\\f'
      case '\r':
        return '\\r'
      default:
        return '\\u' + match.charCodeAt(0).toString(16).padStart(4, '0')
    }
  })

  return new InspectLeaf("'" + string + "'", styles.string, depth, opts)
}

function inspectSymbol(value, depth, opts) {
  return new InspectLeaf(value.toString(), styles.symbol, depth, opts)
}

function inspectKey(value, depth, opts) {
  if (PLAIN_KEY.test(value)) {
    return new InspectLeaf(value, null, depth, opts)
  } else {
    return inspectValue(value, depth, opts)
  }
}

function inspectObject(type, object, depth, opts) {
  const refs = opts.references

  let ref = refs.get(object)
  if (ref === null) {
    ref = new InspectRef(depth, opts)
    refs.set(object, ref)
  } else if (ref.count) {
    ref.circular = true
    return ref
  }

  const maxDepth = typeof opts.depth === 'number' ? opts.depth : Infinity

  if (maxDepth < depth) {
    const constructor = object.constructor

    return new InspectLeaf(
      '[' +
        (constructor && constructor.name ? constructor.name : 'Object') +
        ']',
      styles.special,
      depth,
      opts
    )
  }

  const inspect =
    object[Symbol.for('bare.inspect')] ||
    object[Symbol.for('nodejs.util.inspect.custom')]

  if (typeof inspect === 'function') {
    const value = inspect.call(
      object,
      typeof opts.depth === 'number' ? opts.depth - depth : null,
      {
        colors: opts.colors,
        breakLength: opts.breakLength,
        stylize: opts.stylize
      },
      exports
    )

    if (typeof value === 'object' && value !== null) {
      refs.set(value, ref)
    }

    if (typeof value !== 'string') {
      return inspectValue(value, depth, opts)
    }

    return new InspectLeaf(value, null, depth, opts)
  }

  if (type.isArray()) return inspectArray(object, ref, depth, opts)
  if (type.isDate()) return inspectDate(object, ref, depth, opts)
  if (type.isRegExp()) return inspectRegExp(object, ref, depth, opts)
  if (type.isError()) return inspectError(object, ref, depth, opts)
  if (type.isPromise()) return inspectPromise(object, ref, depth, opts)
  if (type.isMap()) return inspectMap(object, ref, depth, opts)
  if (type.isSet()) return inspectSet(object, ref, depth, opts)
  if (type.isWeakMap()) return inspectWeakMap(object, ref, depth, opts)
  if (type.isWeakSet()) return inspectWeakSet(object, ref, depth, opts)
  if (type.isWeakRef()) return inspectWeakRef(object, ref, depth, opts)
  if (type.isArrayBuffer()) return inspectArrayBuffer(object, ref, depth, opts)
  if (type.isSharedArrayBuffer())
    return inspectSharedArrayBuffer(object, ref, depth, opts)
  if (type.isTypedArray()) return inspectTypedArray(object, ref, depth, opts)
  if (type.isDataView()) return inspectDataView(object, ref, depth, opts)

  ref.increment()

  const values = []

  for (const key in object) {
    if (key === 'constructor') continue

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(object[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  let header = '{ '

  const tag = object[Symbol.toStringTag]

  if (tag) header = '[' + tag + '] ' + header

  if (object.constructor) {
    const name = object.constructor.name

    if (name && name !== 'Object') {
      header = object.constructor.name + ' ' + header
    }
  }

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectArray(array, ref, depth, opts) {
  const { maxArrayLength = defaultMaxArrayLength } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxArrayLength, 0)

  for (let i = 0, n = array.length; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(array.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(inspectValue(array[i], depth + 1, opts))
  }

  for (const key of binding.getOwnNonIndexPropertyNames(array)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(array[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  let header = '[ '

  if (array.constructor.name !== 'Array') {
    header = array.constructor.name + '(' + array.length + ') ' + header
  }

  return new InspectSequence(header, ' ]', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectDate(date, ref, depth, opts) {
  return new InspectLeaf(date.toISOString(), styles.date, depth, opts)
}

function inspectRegExp(regExp, ref, depth, opts) {
  return new InspectLeaf(regExp.toString(), styles.regexp, depth, opts)
}

function inspectError(error, ref, depth, opts) {
  let header

  if ('stack' in error) {
    header = error.stack

    if (depth > 0) {
      header = header.replaceAll('\n', '\n' + '  '.repeat(depth))
    }
  } else {
    header = error.toString()
  }

  const builtins = ['cause']

  if (error.name === 'AggregateError') {
    builtins.push('errors')
  } else if (error.name === 'SuppressedError') {
    builtins.push('error', 'suppressed')
  }

  const values = []

  for (const key of builtins) {
    if (key in error === false) continue

    values.push(
      new InspectPair(
        ': ',
        new InspectLeaf('[' + key + ']', null, depth + 1, opts),
        inspectValue(error[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key in error) {
    if (key === 'constructor' || builtins.includes(key)) continue

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(error[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  if (values.length === 0) return new InspectLeaf(header, null, depth, opts)

  return new InspectSequence(
    header + ' {',
    ' }',
    ', ',
    values,
    ref,
    depth,
    opts
  )
}

function inspectPromise(promise, ref, depth, opts) {
  ref.increment()

  const state = binding.getPromiseState(promise)

  const values = []

  switch (state) {
    case 0: // Pending
      values.push(new InspectLeaf('<pending>', styles.special, depth, opts))
      break

    case 1: // Fulfilled
      values.push(inspectValue(binding.getPromiseResult(promise), depth, opts))
      break

    case 2: // Rejected
      values.push(
        new InspectLeaf('<rejected>', styles.special, depth, opts),
        inspectValue(binding.getPromiseResult(promise), depth, opts)
      )
  }

  ref.decrement()

  const header = promise.constructor.name + ' { '

  return new InspectSequence(header, ' }', ' ', values, ref, depth, opts)
}

function inspectMap(map, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxMapLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = maxMapLength

  for (const entry of map) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(map.size - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )
      break
    }

    values.push(
      new InspectPair(
        ' => ',
        inspectValue(entry[0], depth + 1, opts),
        inspectValue(entry[1], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key in map) {
    if (key === 'constructor') continue

    const value = inspectValue(map[key], depth + 1, opts)

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        value,
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = map.constructor.name + '(' + map.size + ') { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectSet(set, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxSetLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = maxSetLength

  for (const entry of set) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(set.size - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )
      break
    }

    values.push(inspectValue(entry, depth + 1, opts))
  }

  for (const key in set) {
    if (key === 'constructor') continue

    const value = inspectValue(set[key], depth + 1, opts)

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        value,
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = set.constructor.name + '(' + set.size + ') { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectWeakMap(weakMap, ref, depth, opts) {
  const header = weakMap.constructor.name + ' { '

  return new InspectSequence(
    header,
    ' }',
    ' ',
    [new InspectLeaf('<items unknown>', styles.special, depth + 1, opts)],
    ref,
    depth,
    opts
  )
}

function inspectWeakSet(weakSet, ref, depth, opts) {
  const header = weakSet.constructor.name + ' { '

  return new InspectSequence(
    header,
    ' }',
    ' ',
    [new InspectLeaf('<items unknown>', styles.special, depth + 1, opts)],
    ref,
    depth,
    opts
  )
}

function inspectWeakRef(weakRef, ref, depth, opts) {
  const target = weakRef.deref()

  let value

  if (target === undefined) {
    value = new InspectLeaf('<cleared>', styles.special, depth + 1, opts)
  } else {
    value = inspectValue(target, depth + 1, opts)
  }

  const header = weakRef.constructor.name + ' { '

  return new InspectSequence(header, ' }', ' ', [value], ref, depth, opts)
}

function inspectArrayBuffer(arrayBuffer, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(arrayBuffer[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = arrayBuffer.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectSharedArrayBuffer(sharedArrayBuffer, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(sharedArrayBuffer[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = sharedArrayBuffer.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectTypedArray(typedArray, ref, depth, opts) {
  if (Buffer.isBuffer(typedArray)) {
    return inspectBuffer(typedArray, ref, depth, opts)
  }

  const {
    maxArrayLength = defaultMaxArrayLength,
    maxTypedArrayLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxTypedArrayLength, 0)

  for (let i = 0, n = typedArray.length; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(typedArray.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(inspectValue(typedArray[i], depth + 1, opts))
  }

  for (const key of binding.getOwnNonIndexPropertyNames(typedArray)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(typedArray[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = typedArray.constructor.name + '(' + typedArray.length + ') [ '

  return new InspectSequence(header, ' ]', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectBuffer(buffer, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxBufferLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxBufferLength, 0)

  for (let i = 0, n = buffer.byteLength; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(buffer.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(
      new InspectLeaf(
        buffer[i].toString(16).padStart(2, '0'),
        null,
        depth + 1,
        opts
      )
    )
  }

  for (const key of binding.getOwnNonIndexPropertyNames(buffer)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(buffer[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  return new InspectSequence('<Buffer ', '>', ' ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectDataView(dataView, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength', 'byteOffset', 'buffer']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(dataView[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key of binding.getOwnNonIndexPropertyNames(dataView)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(dataView[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = dataView.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectFunction(type, fn, depth, opts) {
  if (fn.toString().startsWith('class')) return inspectClass(fn, depth, opts)

  let tag = 'function'

  if (type.isGeneratorFunction()) tag = 'generator ' + tag
  if (type.isAsyncFunction()) tag = 'async ' + tag

  return new InspectLeaf(
    '[' + tag + ' ' + (fn.name ? fn.name : '(anonymous)') + ']',
    styles.special,
    depth,
    opts
  )
}

function inspectClass(ctor, depth, opts) {
  return new InspectLeaf(
    '[class ' + (ctor.name ? ctor.name : '(anonymous)') + ']',
    styles.special,
    depth,
    opts
  )
}

function inspectExternal(external, depth, opts) {
  return new InspectLeaf(
    '[external 0x' + binding.getExternal(external).toString(16) + ']',
    styles.special,
    depth,
    opts
  )
}
{
  "name": "bare-inspect",
  "version": "3.1.4",
  "description": "Inspect objects as strings for debugging",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-inspect.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-inspect/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-inspect#readme",
  "engines": {
    "bare": ">=1.18.0"
  },
  "dependencies": {
    "bare-ansi-escapes": "^2.1.0",
    "bare-type": "^1.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
class MIME {
  constructor(type, subtype, parameters = new Map()) {
    this._type = type
    this._subtype = subtype
    this._parameters = parameters
  }

  // https://mimesniff.spec.whatwg.org/#type
  get type() {
    return this._type
  }

  // https://mimesniff.spec.whatwg.org/#subtype
  get subtype() {
    return this._subtype
  }

  // https://mimesniff.spec.whatwg.org/#parameters
  get parameters() {
    return this._parameters
  }
}

module.exports = exports = MIME

// https://mimesniff.spec.whatwg.org/#parse-a-mime-type
exports.parse = function parse(input) {
  // 1.
  input = input.replace(httpWhitespaceLeadingAndTrailing, '')

  // 2.
  let position = 0

  // 3.
  let type = ''

  while (position < input.length && input[position] !== '/') {
    type += input[position++]
  }

  // 4.
  if (type === '' || !isHTTPTokenCodePoints(type)) return null

  // 5.
  if (position >= input.length) return null

  // 6.
  position++

  // 7.
  let subtype = ''

  while (position < input.length && input[position] !== ';') {
    subtype += input[position++]
  }

  // 8.
  subtype = subtype.replace(httpWhitespaceTrailing, '')

  // 9.
  if (subtype === '' || !isHTTPTokenCodePoints(subtype)) return null

  // 10.
  const mimeType = new MIME(type.toLowerCase(), subtype.toLowerCase())

  // 11.
  while (position < input.length) {
    // 11.1.
    position++

    // 11.2.
    while (position < input.length && httpWhitespace.test(input[position])) {
      position++
    }

    // 11.3.
    let parameterName = ''

    while (position < input.length && input[position] !== ';' && input[position] !== '=') {
      parameterName += input[position++]
    }

    // 11.4.
    parameterName = parameterName.toLowerCase()

    // 11.5.
    if (position < input.length && input[position] === ';') continue

    // 11.6.
    if (position >= input.length) break

    // 11.7.
    position++

    // 11.8.
    let parameterValue

    // 11.9.
    if (position < input.length && input[position] === '"') {
      // 11.9.1.
      parameterValue = collectHTTPQuotedString(input, position)
      position = parameterValue.position
      parameterValue = parameterValue.value

      // 11.9.2.
      while (position < input.length && input[position] !== ';') {
        position++
      }
    } else {
      // 11.10.
      parameterValue = ''

      while (position < input.length && input[position] !== ';') {
        parameterValue += input[position++]
      }

      // 11.10.1.
      parameterValue = parameterValue.replace(httpWhitespaceTrailing, '')

      // 11.10.2.
      if (parameterValue === '') continue
    }

    // 11.11.
    if (
      parameterName !== '' &&
      isHTTPTokenCodePoints(parameterName) &&
      isHTTPQuotedStringTokenCodePoints(parameterValue) &&
      !mimeType._parameters.has(parameterName)
    ) {
      mimeType._parameters.set(parameterName, parameterValue)
    }
  }

  // 12.
  return mimeType
}

// https://fetch.spec.whatwg.org/#http-whitespace
const httpWhitespace = /[\t\n\r ]/
const httpWhitespaceLeadingAndTrailing = /^[\t\n\r ]+|[\t\n\r ]+$/g
const httpWhitespaceTrailing = /[\t\n\r ]+$/

// https://mimesniff.spec.whatwg.org/#http-token-code-point
const httpTokenCodePoints = /^[!#$%&'*+\-.^_`|~A-Za-z0-9]+$/

// https://mimesniff.spec.whatwg.org/#http-quoted-string-token-code-point
const httpQuotedStringTokenCodePoints = /^[\t\x20-\x7e\x80-\xff]*$/

function isHTTPTokenCodePoints(s) {
  return httpTokenCodePoints.test(s)
}

function isHTTPQuotedStringTokenCodePoints(s) {
  return httpQuotedStringTokenCodePoints.test(s)
}

// https://fetch.spec.whatwg.org/#collect-an-http-quoted-string
function collectHTTPQuotedString(input, position) {
  let value = ''

  position++

  while (true) {
    while (position < input.length && input[position] !== '"' && input[position] !== '\\') {
      value += input[position++]
    }

    if (position >= input.length) break

    const quoteOrBackslash = input[position++]

    if (quoteOrBackslash === '\\') {
      if (position >= input.length) {
        value += '\\'
        break
      }
      value += input[position++]
    } else {
      break
    }
  }

  return { value, position }
}
{
  "name": "bare-mime",
  "version": "1.0.0",
  "description": "MIME type parsing for Bare",
  "exports": {
    "./package": "./package.json",
    ".": "./index.js"
  },
  "files": [
    "index.js"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-mime.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-mime/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-mime#readme",
  "devDependencies": {
    "brittle": "^3.3.0",
    "lunte": "^1.6.0",
    "prettier": "^3.3.3",
    "prettier-config-holepunch": "^2.0.0"
  }
}
const EventEmitter = require('bare-events')
const { Duplex } = require('bare-stream')
const tcp = require('bare-tcp')
const pipe = require('bare-pipe')
const constants = require('./lib/constants')
const errors = require('./lib/errors')

const defaultReadBufferSize = 65536

exports.Socket = class NetSocket extends Duplex {
  constructor(opts = {}) {
    const {
      readBufferSize = defaultReadBufferSize,
      allowHalfOpen = false,
      eagerOpen = false
    } = opts

    super({ eagerOpen, allowHalfOpen })

    this._type = 0
    this._state = 0
    this._socket = null

    this._opts = { readBufferSize, allowHalfOpen, eagerOpen }

    this._pendingOpen = null
    this._pendingWrite = null
    this._pendingFinal = null
    this._pendingDestroy = null
  }

  get connecting() {
    return this._socket !== null && this._socket.connecting
  }

  get pending() {
    return this._socket === null || this._socket.pending
  }

  get timeout() {
    return this._socket === null ? undefined : this._socket.timeout
  }

  get readyState() {
    return this._socket === null ? 'opening' : this._socket.readyState
  }

  get localAddress() {
    return this._socket === null ? undefined : this._socket.localAddress
  }

  get localPort() {
    return this._socket === null ? undefined : this._socket.localPort
  }

  get localFamily() {
    return this._socket === null ? undefined : this._socket.localFamily
  }

  get remoteAddress() {
    return this._socket === null ? undefined : this._socket.remoteAddress
  }

  get remotePort() {
    return this._socket === null ? undefined : this._socket.remotePort
  }

  get remoteFamily() {
    return this._socket === null ? undefined : this._socket.remoteFamily
  }

  connect(...args) {
    let opts = {}
    let onconnect

    if (typeof args[0] === 'string') {
      // connect(path[, onconnect])
      opts.path = args[0]
      onconnect = args[1]
    } else if (typeof args[0] === 'number') {
      // connect(port[, host][, onconnect])
      opts.port = args[0]

      if (typeof args[1] === 'function') {
        onconnect = args[1]
      } else {
        opts.host = args[1]
        onconnect = args[2]
      }
    } else {
      // connect(opts[, onconnect])
      opts = args[0] || {}
      onconnect = args[1]
    }

    opts = { ...opts, ...this._opts }

    if (opts.path) {
      this._attach(constants.type.IPC, pipe.createConnection(opts))
    } else {
      this._attach(constants.type.TCP, tcp.createConnection(opts))
    }

    if (onconnect) this.once('connect', onconnect)

    return this
  }

  setKeepAlive(...args) {
    if (this._socket !== null) this._socket.setKeepAlive(...args)
    return this
  }

  setNoDelay(...args) {
    if (this._socket !== null) this._socket.setNoDelay(...args)
    return this
  }

  setTimeout(...args) {
    if (this._socket !== null) this._socket.setTimeout(...args)
    return this
  }

  ref() {
    this._state &= ~constants.state.UNREFED
    if (this._socket !== null) this._socket.ref()
    return this
  }

  unref() {
    this._state |= constants.state.UNREFED
    if (this._socket !== null) this._socket.unref()
    return this
  }

  _attach(type, socket) {
    this._type = type
    this._socket = socket

    this._socket
      .on('connect', this._onconnect.bind(this))
      .on('timeout', this._ontimeout.bind(this))
      .on('error', this._onerror.bind(this))
      .on('data', this._ondata.bind(this))
      .on('end', this._onend.bind(this))
      .on('finish', this._onfinish.bind(this))
      .on('drain', this._ondrain.bind(this))
      .on('close', this._onclose.bind(this))

    if (this._state & constants.state.UNREFED) this._socket.unref()

    this._continueOpen()

    return this
  }

  _open(cb) {
    if (this._socket !== null) return cb(null)
    this._pendingOpen = cb
  }

  _write(data, encoding, cb) {
    if (this._socket.write(data)) return cb(null)
    this._pendingWrite = cb
  }

  _final(cb) {
    this._socket.end()
    this._pendingFinal = cb
  }

  _destroy(err, cb) {
    if (this._socket === null || this._socket.destroyed) return cb(null)

    this._socket.destroy(err)
    this._pendingDestroy = cb
  }

  _onconnect() {
    this.emit('connect')
  }

  _ontimeout() {
    this.emit('timeout')
  }

  _onerror(err) {
    this.destroy(err)
  }

  _ondata(data) {
    this.push(data)
  }

  _onend() {
    this.push(null)
  }

  _onfinish() {
    this._continueFinal()
  }

  _ondrain() {
    this._continueWrite()
  }

  _onclose() {
    this._continueWrite()
    this._continueFinal()

    if (this._pendingDestroy) this._continueDestroy()
    else this.destroy()
  }

  _continueOpen() {
    if (this._pendingOpen === null) return
    const cb = this._pendingOpen
    this._pendingOpen = null
    cb(null)
  }

  _continueWrite() {
    if (this._pendingWrite === null) return
    const cb = this._pendingWrite
    this._pendingWrite = null
    cb(null)
  }

  _continueFinal() {
    if (this._pendingFinal === null) return
    const cb = this._pendingFinal
    this._pendingFinal = null
    cb(null)
  }

  _continueDestroy() {
    if (this._pendingDestroy === null) return
    const cb = this._pendingDestroy
    this._pendingDestroy = null
    cb(null)
  }
}

exports.Server = class NetServer extends EventEmitter {
  constructor(opts = {}, onconnection) {
    if (typeof opts === 'function') {
      onconnection = opts
      opts = {}
    }

    super()

    const {
      readBufferSize = defaultReadBufferSize,
      allowHalfOpen = false,
      pauseOnConnect = false
    } = opts

    this._type = 0
    this._state = 0
    this._server = null

    this._opts = { readBufferSize, allowHalfOpen, pauseOnConnect }

    if (onconnection) this.on('connection', onconnection)
  }

  get listening() {
    return (this._state & constants.state.BOUND) !== 0
  }

  address() {
    return this._server === null ? null : this._server.address()
  }

  listen(...args) {
    if (this._state & constants.state.BINDING || this._state & constants.state.BOUND) {
      throw errors.SERVER_ALREADY_LISTENING('Server is already listening')
    }

    let opts = {}
    let onlistening

    if (typeof args[0] === 'string') {
      // listen(path[, backlog][, onlistening])
      opts.path = args[0]

      if (typeof args[1] === 'function') {
        onlistening = args[1]
      } else {
        opts.backlog = args[1]
        onlistening = args[2]
      }
    } else {
      // listen([port[, host[, backlog]]][, onlistening])
      if (typeof args[0] === 'function') {
        onlistening = args[0]
      } else {
        opts.port = args[0]

        if (typeof args[1] === 'function') {
          onlistening = args[1]
        } else {
          opts.host = args[1]

          if (typeof args[2] === 'function') {
            onlistening = args[2]
          } else {
            opts.backlog = args[2]
            onlistening = args[3]
          }
        }
      }
    }

    opts = { ...opts, ...this._opts }

    this._state |= constants.state.BINDING

    if (opts.path) {
      this._attach(constants.type.IPC, pipe.createServer(opts))
    } else {
      this._attach(constants.type.TCP, tcp.createServer(opts))
    }

    this._server.listen(opts)

    if (onlistening) this.once('listening', onlistening)

    return this
  }

  close(onclose) {
    if (onclose) this.once('close', onclose)
    this._server.close()
    return this
  }

  ref() {
    this._state &= ~constants.state.UNREFED
    if (this._server !== null) this._server.ref()
    return this
  }

  unref() {
    this._state |= constants.state.UNREFED
    if (this._server !== null) this._server.unref()
    return this
  }

  _attach(type, server) {
    this._type = type
    this._server = server

    this._server
      .on('listening', this._onlistening.bind(this))
      .on('connection', this._onconnection.bind(this))
      .on('error', this._onerror.bind(this))
      .on('close', this._onclose.bind(this))

    if (this._state & constants.state.UNREFED) this._server.unref()

    return this
  }

  _onlistening() {
    this._state |= constants.state.BOUND
    this._state &= ~constants.state.BINDING

    this.emit('listening')
  }

  _onconnection(socket) {
    this.emit('connection', new exports.Socket(this._opts)._attach(this._type, socket))
  }

  _onerror(err) {
    this._state &= ~constants.state.BINDING

    this.emit('error', err)
  }

  _onclose() {
    this._state &= ~constants.state.BINDING
    this._state &= ~constants.state.BOUND

    this.emit('close')
  }
}

exports.constants = constants
exports.errors = errors

exports.isIP = tcp.isIP
exports.isIPv4 = tcp.isIPv4
exports.isIPv6 = tcp.isIPv6

exports.createConnection = function createConnection(...args) {
  let opts = {}
  let onconnect

  if (typeof args[0] === 'string') {
    // createConnection(path[, onconnect])
    opts.path = args[0]
    onconnect = args[1]
  } else if (typeof args[0] === 'number') {
    // createConnection(port[, host][, onconnect])
    opts.port = args[0]

    if (typeof args[1] === 'function') {
      onconnect = args[1]
    } else {
      opts.host = args[1]
      onconnect = args[2]
    }
  } else {
    // createConnection(opts[, onconnect])
    opts = args[0] || {}
    onconnect = args[1]
  }

  return new exports.Socket(opts).connect(opts, onconnect)
}

// For Node.js compatibility
exports.connect = exports.createConnection

exports.createServer = function createServer(opts, onconnection) {
  return new exports.Server(opts, onconnection)
}
module.exports = {
  type: {
    TCP: 1,
    IPC: 2
  },
  state: {
    UNREFED: 0x1,
    BINDING: 0x2,
    BOUND: 0x4
  }
}
module.exports = class NetError extends Error {
  constructor(msg, fn = NetError, code = fn.name) {
    super(`${code}: ${msg}`)

    this.code = code

    if (Error.captureStackTrace) Error.captureStackTrace(this, fn)
  }

  get name() {
    return 'NetError'
  }

  static SERVER_ALREADY_LISTENING(msg) {
    return new NetError(msg, NetError.SERVER_ALREADY_LISTENING)
  }
}
{
  "name": "bare-net",
  "version": "2.3.3",
  "description": "TCP and IPC servers and clients for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    },
    "./errors": {
      "types": "./lib/errors.d.ts",
      "default": "./lib/errors.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-net.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-net/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-net#readme",
  "dependencies": {
    "bare-events": "^2.2.2",
    "bare-pipe": "^4.0.0",
    "bare-stream": "^2.0.0",
    "bare-tcp": "^2.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.0",
    "lunte": "^1.8.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = require.addon()
const binding = require('./binding')
const errors = require('./lib/errors')
const constants = require('./lib/constants')

exports.constants = constants
exports.errors = errors

exports.EOL = binding.platform === 'win32' ? '\r\n' : '\n'

exports.devNull = binding.platform === 'win32' ? '\\\\.\\nul' : '/dev/null'

exports.platform = function platform() {
  return binding.platform
}

exports.arch = function arch() {
  return binding.arch
}

exports.type = function type() {
  return binding.type()
}

exports.version = function version() {
  return binding.version()
}

exports.release = function release() {
  return binding.release()
}

exports.machine = function machine() {
  return binding.machine()
}

exports.execPath = function execPath() {
  return binding.execPath()
}

exports.pid = function pid() {
  return binding.pid()
}

exports.ppid = function ppid() {
  return binding.ppid()
}

exports.cwd = function cwd() {
  return binding.cwd()
}

exports.chdir = function chdir(dir) {
  validateString(dir, 'Directory')

  binding.chdir(dir)
}

exports.tmpdir = function tmpdir() {
  return binding.tmpdir()
}

exports.homedir = function homedir() {
  return binding.homedir()
}

exports.hostname = function hostname() {
  return binding.hostname()
}

exports.userInfo = function userInfo(uid) {
  if (uid !== undefined) validateInteger(uid, 'User ID')

  return binding.userInfo(uid)
}

exports.groupInfo = function groupInfo(gid) {
  if (gid !== undefined) validateInteger(gid, 'Group ID')

  return binding.groupInfo(gid)
}

exports.networkInterfaces = function networkInterfaces() {
  const result = {}

  for (const entry of binding.networkInterfaces()) {
    const { name, ...properties } = entry

    if (result[name]) result[name].push(properties)
    else result[name] = [properties]
  }

  return result
}

exports.kill = function kill(pid, signal = constants.signals.SIGTERM) {
  validateInteger(pid, 'Process ID')

  if (typeof signal === 'string') {
    if (signal in constants.signals === false) {
      throw errors.UNKNOWN_SIGNAL('Unknown signal: ' + signal)
    }

    signal = constants.signals[signal]
  } else {
    validateInteger(signal, 'Signal')
  }

  binding.kill(pid, signal)
}

exports.endianness = function endianness() {
  return binding.isLittleEndian ? 'LE' : 'BE'
}

exports.availableParallelism = function availableParallelism() {
  return binding.availableParallelism()
}

exports.cpuUsage = function cpuUsage(previous) {
  const current = binding.cpuUsage()

  if (previous) {
    return {
      user: current.user - previous.user,
      system: current.system - previous.system
    }
  }

  return current
}

exports.threadCpuUsage = function threadCpuUsage(previous) {
  const current = binding.threadCpuUsage()

  if (previous) {
    return {
      user: current.user - previous.user,
      system: current.system - previous.system
    }
  }

  return current
}

exports.resourceUsage = function resourceUsage() {
  return binding.resourceUsage()
}

exports.memoryUsage = function memoryUsage() {
  return binding.memoryUsage()
}

exports.freemem = function freemem() {
  return binding.freemem()
}

exports.totalmem = function totalmem() {
  return binding.totalmem()
}

exports.availableMemory = function availableMemory() {
  return binding.availableMemory()
}

exports.constrainedMemory = function constrainedMemory() {
  return binding.constrainedMemory()
}

exports.uptime = function uptime() {
  return binding.uptime()
}

exports.loadavg = function loadavg() {
  return binding.loadavg()
}

exports.cpus = function cpus() {
  return binding.cpus()
}

exports.getProcessTitle = function getProcessTitle() {
  return binding.getProcessTitle()
}

exports.setProcessTitle = function setProcessTitle(title) {
  if (typeof title !== 'string') title = title.toString()

  if (title.length >= 256) {
    throw errors.TITLE_OVERFLOW('Process title is too long')
  }

  binding.setProcessTitle(title)
}

exports.getPriority = function getPriority(pid = 0) {
  validateInteger(pid, 'Process ID')

  return binding.getPriority(pid)
}

exports.setPriority = function setPriority(pid, priority) {
  if (priority === undefined) {
    priority = pid
    pid = 0
  }

  validateInteger(pid, 'Process ID')
  validateInteger(priority, 'Priority')

  binding.setPriority(pid, priority)
}

exports.getEnvKeys = function getEnvKeys() {
  return binding.getEnvKeys()
}

exports.getEnv = function getEnv(name) {
  validateString(name, 'Name')

  return binding.getEnv(name)
}

exports.hasEnv = function hasEnv(name) {
  validateString(name, 'Name')

  return binding.hasEnv(name)
}

exports.setEnv = function setEnv(name, value) {
  validateString(name, 'Name')
  validateString(value, 'Value')

  binding.setEnv(name, value)
}

exports.unsetEnv = function unsetEnv(name) {
  validateString(name, 'Name')

  binding.unsetEnv(name)
}

function validateString(value, name) {
  if (typeof value !== 'string') {
    throw new TypeError(`${name} must be a string. Received type ${typeof value} (${value})`)
  }
}

function validateInteger(value, name) {
  if (!Number.isInteger(value)) {
    throw new TypeError(`${name} must be an integer. Received type ${typeof value} (${value})`)
  }
}
const binding = require('../binding')

module.exports = {
  signals: binding.signals,
  errnos: binding.errnos,
  priority: binding.priority
}
module.exports = class OSError extends Error {
  constructor(msg, fn = OSError, code = fn.name) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'OSError'
  }

  static UNKNOWN_SIGNAL(msg) {
    return new OSError(msg, OSError.UNKNOWN_SIGNAL)
  }

  static TITLE_OVERFLOW(msg) {
    return new OSError(msg, OSError.TITLE_OVERFLOW)
  }
}
{
  "name": "bare-os",
  "version": "3.9.3",
  "description": "Operating system utilities for Bare",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    },
    "./errors": {
      "types": "./lib/errors.d.ts",
      "default": "./lib/errors.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-os.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-os/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-os#readme",
  "engines": {
    "bare": ">=1.14.0"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "cmake-bare": "^1.1.6",
    "lunte": "^1.6.0",
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = require.addon()
// This export SHOULD NOT be shortened in any way as having the full
// `module.exports = require(...)` statement is crucial for synthesizing
// ESM exports.

if (Bare.platform === 'win32') {
  module.exports = require('./lib/win32')
} else {
  module.exports = require('./lib/posix')
}
module.exports = {
  CHAR_UPPERCASE_A: 0x41,
  CHAR_LOWERCASE_A: 0x61,
  CHAR_UPPERCASE_Z: 0x5a,
  CHAR_LOWERCASE_Z: 0x7a,
  CHAR_DOT: 0x2e,
  CHAR_FORWARD_SLASH: 0x2f,
  CHAR_BACKWARD_SLASH: 0x5c,
  CHAR_COLON: 0x3a,
  CHAR_QUESTION_MARK: 0x3f
}
const binding = require('../binding')

const { normalizeString, validateString } = require('./shared')
const { CHAR_DOT, CHAR_FORWARD_SLASH } = require('./constants')

function isPosixPathSeparator(code) {
  return code === CHAR_FORWARD_SLASH
}

exports.win32 = require('./win32')
exports.posix = exports

exports.sep = '/'
exports.delimiter = ':'

exports.resolve = function resolve(...args) {
  let resolvedPath = ''
  let resolvedAbsolute = false

  for (let i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) {
    const path = i >= 0 ? args[i] : binding.cwd()

    if (i >= 0) validateString(path, `paths[${i}]`)

    if (path.length === 0) {
      continue
    }

    resolvedPath = `${path}/${resolvedPath}`
    resolvedAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH
  }

  resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute, '/', isPosixPathSeparator)

  if (resolvedAbsolute) {
    return `/${resolvedPath}`
  }

  return resolvedPath.length > 0 ? resolvedPath : '.'
}

exports.normalize = function normalize(path) {
  validateString(path, 'path')

  if (path.length === 0) return '.'

  const isAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH
  const trailingSeparator = path.charCodeAt(path.length - 1) === CHAR_FORWARD_SLASH

  path = normalizeString(path, !isAbsolute, '/', isPosixPathSeparator)

  if (path.length === 0) {
    if (isAbsolute) return '/'
    return trailingSeparator ? './' : '.'
  }

  if (trailingSeparator) path += '/'

  return isAbsolute ? `/${path}` : path
}

exports.isAbsolute = function isAbsolute(path) {
  validateString(path, 'path')

  return path.length > 0 && path.charCodeAt(0) === CHAR_FORWARD_SLASH
}

exports.join = function join(...args) {
  if (args.length === 0) return '.'
  let joined
  for (let i = 0; i < args.length; ++i) {
    const arg = args[i]
    validateString(arg, 'path')
    if (arg.length > 0) {
      if (joined === undefined) joined = arg
      else joined += `/${arg}`
    }
  }
  if (joined === undefined) return '.'
  return exports.normalize(joined)
}

exports.relative = function relative(from, to) {
  validateString(from, 'from')
  validateString(to, 'to')

  if (from === to) return ''

  from = exports.resolve(from)
  to = exports.resolve(to)

  if (from === to) return ''

  const fromStart = 1
  const fromEnd = from.length
  const fromLen = fromEnd - fromStart
  const toStart = 1
  const toLen = to.length - toStart

  const length = fromLen < toLen ? fromLen : toLen
  let lastCommonSep = -1
  let i = 0
  for (; i < length; i++) {
    const fromCode = from.charCodeAt(fromStart + i)
    if (fromCode !== to.charCodeAt(toStart + i)) {
      break
    } else if (fromCode === CHAR_FORWARD_SLASH) {
      lastCommonSep = i
    }
  }
  if (i === length) {
    if (toLen > length) {
      if (to.charCodeAt(toStart + i) === CHAR_FORWARD_SLASH) {
        return to.substring(toStart + i + 1)
      }
      if (i === 0) {
        return to.substring(toStart + i)
      }
    } else if (fromLen > length) {
      if (from.charCodeAt(fromStart + i) === CHAR_FORWARD_SLASH) {
        lastCommonSep = i
      } else if (i === 0) {
        lastCommonSep = 0
      }
    }
  }

  let out = ''
  for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
    if (i === fromEnd || from.charCodeAt(i) === CHAR_FORWARD_SLASH) {
      out += out.length === 0 ? '..' : '/..'
    }
  }

  return `${out}${to.substring(toStart + lastCommonSep)}`
}

exports.toNamespacedPath = function toNamespacedPath(path) {
  return path
}

exports.dirname = function dirname(path) {
  validateString(path, 'path')

  if (path.length === 0) return '.'
  const hasRoot = path.charCodeAt(0) === CHAR_FORWARD_SLASH
  let end = -1
  let matchedSlash = true
  for (let i = path.length - 1; i >= 1; --i) {
    if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) {
      if (!matchedSlash) {
        end = i
        break
      }
    } else {
      matchedSlash = false
    }
  }

  if (end === -1) return hasRoot ? '/' : '.'
  if (hasRoot && end === 1) return '//'
  return path.substring(0, end)
}

exports.basename = function basename(path, suffix) {
  if (suffix !== undefined) validateString(suffix, 'suffix')
  validateString(path, 'path')

  let start = 0
  let end = -1
  let matchedSlash = true

  if (suffix !== undefined && suffix.length > 0 && suffix.length <= path.length) {
    if (suffix === path) {
      return ''
    }
    let extIdx = suffix.length - 1
    let firstNonSlashEnd = -1
    for (let i = path.length - 1; i >= 0; --i) {
      const code = path.charCodeAt(i)
      if (code === CHAR_FORWARD_SLASH) {
        if (!matchedSlash) {
          start = i + 1
          break
        }
      } else {
        if (firstNonSlashEnd === -1) {
          matchedSlash = false
          firstNonSlashEnd = i + 1
        }
        if (extIdx >= 0) {
          if (code === suffix.charCodeAt(extIdx)) {
            if (--extIdx === -1) {
              end = i
            }
          } else {
            extIdx = -1
            end = firstNonSlashEnd
          }
        }
      }
    }

    if (start === end) end = firstNonSlashEnd
    else if (end === -1) end = path.length
    return path.substring(start, end)
  }

  for (let i = path.length - 1; i >= 0; --i) {
    if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) {
      if (!matchedSlash) {
        start = i + 1
        break
      }
    } else if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
  }

  if (end === -1) return ''
  return path.substring(start, end)
}

exports.extname = function extname(path) {
  validateString(path, 'path')

  let startDot = -1
  let startPart = 0
  let end = -1
  let matchedSlash = true
  let preDotState = 0
  for (let i = path.length - 1; i >= 0; --i) {
    const code = path.charCodeAt(i)
    if (code === CHAR_FORWARD_SLASH) {
      if (!matchedSlash) {
        startPart = i + 1
        break
      }
      continue
    }
    if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
    if (code === CHAR_DOT) {
      if (startDot === -1) startDot = i
      else if (preDotState !== 1) preDotState = 1
    } else if (startDot !== -1) {
      preDotState = -1
    }
  }

  if (
    startDot === -1 ||
    end === -1 ||
    preDotState === 0 ||
    (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1)
  ) {
    return ''
  }
  return path.substring(startDot, end)
}
const { CHAR_DOT, CHAR_FORWARD_SLASH } = require('./constants')

exports.validateString = function validateString(value, name) {
  if (typeof value !== 'string') {
    throw new TypeError(
      `The "${name}" argument must be of type string. Received type ${typeof value}`
    )
  }
}

exports.normalizeString = function normalizeString(
  path,
  allowAboveRoot,
  separator,
  isPathSeparator
) {
  let res = ''
  let lastSegmentLength = 0
  let lastSlash = -1
  let dots = 0
  let code = 0
  for (let i = 0; i <= path.length; ++i) {
    if (i < path.length) {
      code = path.charCodeAt(i)
    } else if (isPathSeparator(code)) {
      break
    } else {
      code = CHAR_FORWARD_SLASH
    }

    if (isPathSeparator(code)) {
      if (lastSlash === i - 1 || dots === 1);
      else if (dots === 2) {
        if (
          res.length < 2 ||
          lastSegmentLength !== 2 ||
          res.charCodeAt(res.length - 1) !== CHAR_DOT ||
          res.charCodeAt(res.length - 2) !== CHAR_DOT
        ) {
          if (res.length > 2) {
            const lastSlashIndex = res.lastIndexOf(separator)
            if (lastSlashIndex === -1) {
              res = ''
              lastSegmentLength = 0
            } else {
              res = res.substring(0, lastSlashIndex)
              lastSegmentLength = res.length - 1 - res.lastIndexOf(separator)
            }
            lastSlash = i
            dots = 0
            continue
          } else if (res.length !== 0) {
            res = ''
            lastSegmentLength = 0
            lastSlash = i
            dots = 0
            continue
          }
        }
        if (allowAboveRoot) {
          res += res.length > 0 ? `${separator}..` : '..'
          lastSegmentLength = 2
        }
      } else {
        if (res.length > 0) {
          res += `${separator}${path.substring(lastSlash + 1, i)}`
        } else {
          res = path.substring(lastSlash + 1, i)
        }
        lastSegmentLength = i - lastSlash - 1
      }
      lastSlash = i
      dots = 0
    } else if (code === CHAR_DOT && dots !== -1) {
      ++dots
    } else {
      dots = -1
    }
  }
  return res
}
const binding = require('../binding')

const { normalizeString, validateString } = require('./shared')
const {
  CHAR_UPPERCASE_A,
  CHAR_LOWERCASE_A,
  CHAR_UPPERCASE_Z,
  CHAR_LOWERCASE_Z,
  CHAR_DOT,
  CHAR_FORWARD_SLASH,
  CHAR_BACKWARD_SLASH,
  CHAR_COLON,
  CHAR_QUESTION_MARK
} = require('./constants')

function isWindowsPathSeparator(code) {
  return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH
}

function isWindowsDeviceRoot(code) {
  return (
    (code >= CHAR_UPPERCASE_A && code <= CHAR_UPPERCASE_Z) ||
    (code >= CHAR_LOWERCASE_A && code <= CHAR_LOWERCASE_Z)
  )
}

exports.posix = require('./posix')
exports.win32 = exports

exports.sep = '\\'
exports.delimiter = ';'

exports.resolve = function resolve(...args) {
  let resolvedDevice = ''
  let resolvedTail = ''
  let resolvedAbsolute = false

  for (let i = args.length - 1; i >= -1; i--) {
    let path
    if (i >= 0) {
      path = args[i]

      validateString(path, `paths[${i}]`)

      if (path.length === 0) continue
    } else if (resolvedDevice.length === 0) {
      path = binding.cwd()
    } else {
      path = binding.cwd(resolvedDevice)

      if (
        path === undefined ||
        (path.substring(0, 2).toLowerCase() !== resolvedDevice.toLowerCase() &&
          path.charCodeAt(2) === CHAR_BACKWARD_SLASH)
      ) {
        path = `${resolvedDevice}\\`
      }
    }

    const len = path.length
    let rootEnd = 0
    let device = ''
    let isAbsolute = false
    const code = path.charCodeAt(0)

    if (len === 1) {
      if (isWindowsPathSeparator(code)) {
        rootEnd = 1
        isAbsolute = true
      }
    } else if (isWindowsPathSeparator(code)) {
      isAbsolute = true

      if (isWindowsPathSeparator(path.charCodeAt(1))) {
        let j = 2
        let last = j
        while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
          j++
        }
        if (j < len && j !== last) {
          const firstPart = path.substring(last, j)
          last = j
          while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
            j++
          }
          if (j < len && j !== last) {
            last = j
            while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
              j++
            }
            if (j === len || j !== last) {
              device = `\\\\${firstPart}\\${path.substring(last, j)}`
              rootEnd = j
            }
          }
        }
      } else {
        rootEnd = 1
      }
    } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
      device = path.substring(0, 2)
      rootEnd = 2
      if (len > 2 && isWindowsPathSeparator(path.charCodeAt(2))) {
        isAbsolute = true
        rootEnd = 3
      }
    }

    if (device.length > 0) {
      if (resolvedDevice.length > 0) {
        if (device.toLowerCase() !== resolvedDevice.toLowerCase()) {
          continue
        }
      } else {
        resolvedDevice = device
      }
    }

    if (resolvedAbsolute) {
      if (resolvedDevice.length > 0) {
        break
      }
    } else {
      resolvedTail = `${path.substring(rootEnd)}\\${resolvedTail}`
      resolvedAbsolute = isAbsolute
      if (isAbsolute && resolvedDevice.length > 0) {
        break
      }
    }
  }

  resolvedTail = normalizeString(resolvedTail, !resolvedAbsolute, '\\', isWindowsPathSeparator)

  return resolvedAbsolute
    ? `${resolvedDevice}\\${resolvedTail}`
    : `${resolvedDevice}${resolvedTail}` || '.'
}

exports.normalize = function normalize(path) {
  validateString(path, 'path')

  const len = path.length
  if (len === 0) return '.'
  let rootEnd = 0
  let device
  let isAbsolute = false
  const code = path.charCodeAt(0)

  if (len === 1) {
    return code === CHAR_FORWARD_SLASH ? '\\' : path
  }

  if (isWindowsPathSeparator(code)) {
    isAbsolute = true

    if (isWindowsPathSeparator(path.charCodeAt(1))) {
      let j = 2
      let last = j
      while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
        j++
      }
      if (j < len && j !== last) {
        const firstPart = path.substring(last, j)
        last = j
        while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
          j++
        }
        if (j < len && j !== last) {
          last = j
          while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
            j++
          }
          if (j === len) {
            return `\\\\${firstPart}\\${path.substring(last)}\\`
          }
          if (j !== last) {
            device = `\\\\${firstPart}\\${path.substring(last, j)}`
            rootEnd = j
          }
        }
      }
    } else {
      rootEnd = 1
    }
  } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
    device = path.substring(0, 2)
    rootEnd = 2
    if (len > 2 && isWindowsPathSeparator(path.charCodeAt(2))) {
      isAbsolute = true
      rootEnd = 3
    }
  }

  let tail =
    rootEnd < len
      ? normalizeString(path.substring(rootEnd), !isAbsolute, '\\', isWindowsPathSeparator)
      : ''
  if (tail.length === 0 && !isAbsolute) {
    tail = '.'
  }
  if (tail.length > 0 && isWindowsPathSeparator(path.charCodeAt(len - 1))) {
    tail += '\\'
  }
  if (device === undefined) {
    return isAbsolute ? `\\${tail}` : tail
  }
  return isAbsolute ? `${device}\\${tail}` : `${device}${tail}`
}

exports.isAbsolute = function isAbsolute(path) {
  validateString(path, 'path')

  const len = path.length
  if (len === 0) return false

  const code = path.charCodeAt(0)

  return (
    isWindowsPathSeparator(code) ||
    (len > 2 &&
      isWindowsDeviceRoot(code) &&
      path.charCodeAt(1) === CHAR_COLON &&
      isWindowsPathSeparator(path.charCodeAt(2)))
  )
}

exports.join = function join(...args) {
  if (args.length === 0) return '.'

  let joined
  let firstPart
  for (let i = 0; i < args.length; ++i) {
    const arg = args[i]
    validateString(arg, 'path')
    if (arg.length > 0) {
      if (joined === undefined) joined = firstPart = arg
      else joined += `\\${arg}`
    }
  }

  if (joined === undefined) return '.'

  let needsReplace = true
  let slashCount = 0
  if (isWindowsPathSeparator(firstPart.charCodeAt(0))) {
    ++slashCount
    const firstLen = firstPart.length
    if (firstLen > 1 && isWindowsPathSeparator(firstPart.charCodeAt(1))) {
      ++slashCount
      if (firstLen > 2) {
        if (isWindowsPathSeparator(firstPart.charCodeAt(2))) {
          ++slashCount
        } else {
          needsReplace = false
        }
      }
    }
  }
  if (needsReplace) {
    while (slashCount < joined.length && isWindowsPathSeparator(joined.charCodeAt(slashCount))) {
      slashCount++
    }

    if (slashCount >= 2) {
      joined = `\\${joined.substring(slashCount)}`
    }
  }

  return exports.normalize(joined)
}

exports.relative = function relative(from, to) {
  validateString(from, 'from')
  validateString(to, 'to')

  if (from === to) return ''

  const fromOrig = exports.resolve(from)
  const toOrig = exports.resolve(to)

  if (fromOrig === toOrig) return ''

  from = fromOrig.toLowerCase()
  to = toOrig.toLowerCase()

  if (from === to) return ''

  let fromStart = 0
  while (fromStart < from.length && from.charCodeAt(fromStart) === CHAR_BACKWARD_SLASH) {
    fromStart++
  }
  let fromEnd = from.length
  while (fromEnd - 1 > fromStart && from.charCodeAt(fromEnd - 1) === CHAR_BACKWARD_SLASH) {
    fromEnd--
  }
  const fromLen = fromEnd - fromStart

  let toStart = 0
  while (toStart < to.length && to.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) {
    toStart++
  }
  let toEnd = to.length
  while (toEnd - 1 > toStart && to.charCodeAt(toEnd - 1) === CHAR_BACKWARD_SLASH) {
    toEnd--
  }
  const toLen = toEnd - toStart

  const length = fromLen < toLen ? fromLen : toLen
  let lastCommonSep = -1
  let i = 0
  for (; i < length; i++) {
    const fromCode = from.charCodeAt(fromStart + i)
    if (fromCode !== to.charCodeAt(toStart + i)) {
      break
    } else if (fromCode === CHAR_BACKWARD_SLASH) {
      lastCommonSep = i
    }
  }

  if (i !== length) {
    if (lastCommonSep === -1) return toOrig
  } else {
    if (toLen > length) {
      if (to.charCodeAt(toStart + i) === CHAR_BACKWARD_SLASH) {
        return toOrig.substring(toStart + i + 1)
      }
      if (i === 2) {
        return toOrig.substring(toStart + i)
      }
    }
    if (fromLen > length) {
      if (from.charCodeAt(fromStart + i) === CHAR_BACKWARD_SLASH) {
        lastCommonSep = i
      } else if (i === 2) {
        lastCommonSep = 3
      }
    }
    if (lastCommonSep === -1) lastCommonSep = 0
  }

  let out = ''
  for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
    if (i === fromEnd || from.charCodeAt(i) === CHAR_BACKWARD_SLASH) {
      out += out.length === 0 ? '..' : '\\..'
    }
  }

  toStart += lastCommonSep

  if (out.length > 0) {
    return `${out}${toOrig.substring(toStart, toEnd)}`
  }
  if (toOrig.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) {
    ++toStart
  }
  return toOrig.substring(toStart, toEnd)
}

exports.toNamespacedPath = function toNamespacedPath(path) {
  if (typeof path !== 'string' || path.length === 0) return path

  const resolvedPath = exports.resolve(path)

  if (resolvedPath.length <= 2) return path

  if (resolvedPath.charCodeAt(0) === CHAR_BACKWARD_SLASH) {
    if (resolvedPath.charCodeAt(1) === CHAR_BACKWARD_SLASH) {
      const code = resolvedPath.charCodeAt(2)
      if (code !== CHAR_QUESTION_MARK && code !== CHAR_DOT) {
        return `\\\\?\\UNC\\${resolvedPath.substring(2)}`
      }
    }
  } else if (
    isWindowsDeviceRoot(resolvedPath.charCodeAt(0)) &&
    resolvedPath.charCodeAt(1) === CHAR_COLON &&
    resolvedPath.charCodeAt(2) === CHAR_BACKWARD_SLASH
  ) {
    return `\\\\?\\${resolvedPath}`
  }

  return path
}

exports.dirname = function dirname(path) {
  validateString(path, 'path')

  const len = path.length
  if (len === 0) return '.'
  let rootEnd = -1
  let offset = 0
  const code = path.charCodeAt(0)

  if (len === 1) {
    return isWindowsPathSeparator(code) ? path : '.'
  }

  if (isWindowsPathSeparator(code)) {
    rootEnd = offset = 1

    if (isWindowsPathSeparator(path.charCodeAt(1))) {
      let j = 2
      let last = j
      while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
        j++
      }
      if (j < len && j !== last) {
        last = j
        while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
          j++
        }
        if (j < len && j !== last) {
          last = j
          while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
            j++
          }
          if (j === len) {
            return path
          }
          if (j !== last) {
            rootEnd = offset = j + 1
          }
        }
      }
    }
  } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
    rootEnd = len > 2 && isWindowsPathSeparator(path.charCodeAt(2)) ? 3 : 2
    offset = rootEnd
  }

  let end = -1
  let matchedSlash = true
  for (let i = len - 1; i >= offset; --i) {
    if (isWindowsPathSeparator(path.charCodeAt(i))) {
      if (!matchedSlash) {
        end = i
        break
      }
    } else {
      matchedSlash = false
    }
  }

  if (end === -1) {
    if (rootEnd === -1) return '.'

    end = rootEnd
  }
  return path.substring(0, end)
}

exports.basename = function basename(path, suffix) {
  if (suffix !== undefined) validateString(suffix, 'suffix')
  validateString(path, 'path')

  let start = 0
  let end = -1
  let matchedSlash = true

  if (
    path.length >= 2 &&
    isWindowsDeviceRoot(path.charCodeAt(0)) &&
    path.charCodeAt(1) === CHAR_COLON
  ) {
    start = 2
  }

  if (suffix !== undefined && suffix.length > 0 && suffix.length <= path.length) {
    if (suffix === path) return ''
    let extIdx = suffix.length - 1
    let firstNonSlashEnd = -1
    for (let i = path.length - 1; i >= start; --i) {
      const code = path.charCodeAt(i)
      if (isWindowsPathSeparator(code)) {
        if (!matchedSlash) {
          start = i + 1
          break
        }
      } else {
        if (firstNonSlashEnd === -1) {
          matchedSlash = false
          firstNonSlashEnd = i + 1
        }
        if (extIdx >= 0) {
          if (code === suffix.charCodeAt(extIdx)) {
            if (--extIdx === -1) {
              end = i
            }
          } else {
            extIdx = -1
            end = firstNonSlashEnd
          }
        }
      }
    }

    if (start === end) end = firstNonSlashEnd
    else if (end === -1) end = path.length
    return path.substring(start, end)
  }
  for (let i = path.length - 1; i >= start; --i) {
    if (isWindowsPathSeparator(path.charCodeAt(i))) {
      if (!matchedSlash) {
        start = i + 1
        break
      }
    } else if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
  }

  if (end === -1) return ''
  return path.substring(start, end)
}

exports.extname = function extname(path) {
  validateString(path, 'path')

  let start = 0
  let startDot = -1
  let startPart = 0
  let end = -1
  let matchedSlash = true
  let preDotState = 0

  if (
    path.length >= 2 &&
    path.charCodeAt(1) === CHAR_COLON &&
    isWindowsDeviceRoot(path.charCodeAt(0))
  ) {
    start = startPart = 2
  }

  for (let i = path.length - 1; i >= start; --i) {
    const code = path.charCodeAt(i)
    if (isWindowsPathSeparator(code)) {
      if (!matchedSlash) {
        startPart = i + 1
        break
      }
      continue
    }
    if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
    if (code === CHAR_DOT) {
      if (startDot === -1) startDot = i
      else if (preDotState !== 1) preDotState = 1
    } else if (startDot !== -1) {
      preDotState = -1
    }
  }

  if (
    startDot === -1 ||
    end === -1 ||
    preDotState === 0 ||
    (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1)
  ) {
    return ''
  }
  return path.substring(startDot, end)
}
{
  "name": "bare-path",
  "version": "3.1.1",
  "description": "Path manipulation library for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./posix": "./lib/posix.js",
    "./win32": "./lib/win32.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds",
    "NOTICE"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-path.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-path/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-path#readme",
  "devDependencies": {
    "brittle": "^3.3.2",
    "cmake-bare": "^1.1.6",
    "lunte": "^1.8.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = require.addon()
const EventEmitter = require('bare-events')
const { Duplex } = require('bare-stream')
const binding = require('./binding')
const constants = require('./lib/constants')
const errors = require('./lib/errors')

const defaultReadBufferSize = 65536
const empty = Buffer.alloc(0)

const ipcHandle = Symbol.for('bare.ipc.handle')
const ipcAccept = Symbol.for('bare.ipc.accept')

module.exports = exports = class Pipe extends Duplex {
  constructor(path, opts = {}) {
    if (typeof path === 'object' && path !== null) {
      opts = path
      path = null
    }

    const {
      readBufferSize = defaultReadBufferSize,
      allowHalfOpen = true,
      eagerOpen = true,
      ipc = false
    } = opts

    super({ eagerOpen })

    this._state = 0

    this._allowHalfOpen = allowHalfOpen
    this._ipc = ipc

    this._fd = -1
    this._path = null

    this._pendingOpen = null
    this._pendingWrite = null
    this._pendingWriteBatch = null
    this._pendingWriteSegments = null
    this._pendingWriteIdx = 0
    this._pendingFinal = null
    this._pendingDestroy = null

    this._handleQueue = []
    this._handleQueueSize = 0

    this._buffer = Buffer.alloc(readBufferSize)

    this._handle = binding.init(
      this._buffer,
      ipc,
      this,
      noop,
      this._onconnect,
      this._onwrite,
      this._onfinal,
      this._onread,
      this._onhandle,
      this._onclose
    )

    if (typeof path === 'number') {
      this.open(path)
    } else if (typeof path === 'string') {
      this.connect(path)
    }
  }

  get connecting() {
    return (this._state & constants.state.CONNECTING) !== 0
  }

  get pending() {
    return (this._state & constants.state.CONNECTED) === 0
  }

  get readyState() {
    if (this._state & constants.state.READABLE && this._state & constants.state.WRITABLE) {
      return 'open'
    }

    if (this._state & constants.state.READABLE) {
      return 'readOnly'
    }

    if (this._state & constants.state.WRITABLE) {
      return 'writeOnly'
    }

    return 'opening'
  }

  get [ipcHandle]() {
    return this._handle
  }

  open(fd, opts = {}, onconnect) {
    if (typeof opts === 'function') {
      onconnect = opts
      opts = {}
    }

    if (typeof fd === 'object' && fd !== null) {
      opts = fd || {}
      fd = opts.fd
    }

    try {
      const status = binding.open(this._handle, fd)

      this._state |= constants.state.CONNECTED
      this._fd = fd

      if (status & binding.READABLE) {
        this._state |= constants.state.READABLE
      } else {
        this.push(null)
      }

      if (status & binding.WRITABLE) {
        this._state |= constants.state.WRITABLE
      } else {
        this.end()
      }

      if (onconnect) this.once('connect', onconnect)

      queueMicrotask(() => this.emit('connect'))
    } catch (err) {
      queueMicrotask(() => {
        if (this._pendingOpen) this._pendingOpen(err)
        else this.destroy(err)
      })
    }

    return this
  }

  connect(path, opts = {}, onconnect) {
    if (this._state & constants.state.CONNECTING || this._state & constants.state.CONNECTED) {
      throw errors.PIPE_ALREADY_CONNECTED('Pipe is already connected')
    }

    this._state |= constants.state.CONNECTING

    if (typeof opts === 'function') {
      onconnect = opts
      opts = {}
    }

    if (typeof path === 'object' && path !== null) {
      opts = path || {}
      path = opts.path
    }

    try {
      binding.connect(this._handle, path)

      this._path = path

      if (onconnect) this.once('connect', onconnect)
    } catch (err) {
      this._state &= ~constants.state.CONNECTING

      queueMicrotask(() => {
        if (this._pendingOpen) this._pendingOpen(err)
        else this.destroy(err)
      })
    }

    return this
  }

  write(chunk, encoding, handle, cb) {
    if (typeof encoding === 'function') {
      cb = encoding
      encoding = undefined
      handle = null
    } else if (typeof encoding === 'object' && encoding !== null) {
      if (typeof handle === 'function') cb = handle
      handle = encoding
      encoding = undefined
    } else if (typeof handle === 'function') {
      cb = handle
      handle = null
    }

    if (handle) this._handleQueueSize++

    this._handleQueue.push(handle || null)

    if (encoding) return super.write(chunk, encoding, cb)

    return super.write(chunk, cb)
  }

  accept(target) {
    const handle = target[ipcHandle]

    if (handle === undefined) {
      throw errors.INVALID_IPC_TARGET('Target does not implement the IPC handle protocol')
    }

    binding.accept(this._handle, handle)

    if (typeof target[ipcAccept] === 'function') target[ipcAccept]()

    return target
  }

  ref() {
    binding.ref(this._handle)

    return this
  }

  unref() {
    binding.unref(this._handle)

    return this
  }

  [ipcAccept]() {
    this._onaccept()
  }

  _open(cb) {
    if (this._state & constants.state.CONNECTED) return cb(null)

    this._pendingOpen = cb
  }

  _read() {
    if ((this._state & constants.state.READING) === 0) {
      this._state |= constants.state.READING

      binding.resume(this._handle)
    }
  }

  _writev(batch, cb) {
    this._pendingWrite = cb
    this._pendingWriteBatch = batch

    if (this._handleQueueSize === 0) {
      this._handleQueue = []
      this._pendingWriteSegments = null

      try {
        binding.writev(
          this._handle,
          batch.map(({ chunk }) => chunk),
          null
        )
      } catch (err) {
        this._continueWrite(err)
      }
      return
    }

    const handles = this._handleQueue.splice(0, batch.length)

    // Fill any holes in the batch for messages that don't carry a handle. Each
    // message that does carry a handle decrements the handle queue size.
    for (let i = 0; i < batch.length; i++) {
      if (handles[i] === undefined) handles[i] = null
      else if (handles[i] !== null) this._handleQueueSize--
    }

    const segments = []

    let i = 0
    while (i < batch.length) {
      if (handles[i] !== null) {
        segments.push({ chunks: [batch[i]], handle: handles[i] })
        i++
      } else {
        const start = i
        while (i < batch.length && handles[i] === null) i++
        segments.push({ chunks: batch.slice(start, i), handle: null })
      }
    }

    this._pendingWriteSegments = segments
    this._pendingWriteIdx = 0

    this._writeNextSegment()
  }

  _writeNextSegment() {
    const segment = this._pendingWriteSegments[this._pendingWriteIdx]

    const chunks = []
    for (let i = 0; i < segment.chunks.length; i++) {
      chunks.push(segment.chunks[i].chunk)
    }

    let sendHandle = null
    if (segment.handle !== null) sendHandle = segment.handle[ipcHandle]

    try {
      binding.writev(this._handle, chunks, sendHandle)
    } catch (err) {
      this._continueWrite(err)
    }
  }

  _final(cb) {
    if (this._state & constants.state.READABLE && this._state & constants.state.WRITABLE) {
      this._pendingFinal = cb

      binding.end(this._handle)
    } else {
      cb(null)
    }
  }

  _predestroy() {
    if (this._state & constants.state.CLOSING) return
    this._state |= constants.state.CLOSING

    binding.close(this._handle)
  }

  _destroy(err, cb) {
    if (this._state & constants.state.CLOSING) return cb(err)
    this._state |= constants.state.CLOSING

    this._pendingDestroy = cb

    binding.close(this._handle)
  }

  _continueOpen(err) {
    if (this._pendingOpen === null) return
    const cb = this._pendingOpen
    this._pendingOpen = null
    cb(err)
  }

  _continueWrite(err) {
    if (this._pendingWrite === null) return

    if (this._pendingWriteSegments === null) {
      const cb = this._pendingWrite
      this._pendingWrite = null
      this._pendingWriteBatch = null
      cb(err)
      return
    }

    this._pendingWriteIdx++

    if (err === null && this._pendingWriteIdx < this._pendingWriteSegments.length) {
      this._writeNextSegment()
      return
    }

    const cb = this._pendingWrite
    this._pendingWrite = null
    this._pendingWriteBatch = null
    this._pendingWriteSegments = null
    this._pendingWriteIdx = 0
    cb(err)
  }

  _continueFinal(err) {
    if (this._pendingFinal === null) return
    const cb = this._pendingFinal
    this._pendingFinal = null
    cb(err)
  }

  _continueDestroy() {
    if (this._pendingDestroy === null) return
    const cb = this._pendingDestroy
    this._pendingDestroy = null
    cb(null)
  }

  _onconnect(err) {
    if (err) {
      this._state &= ~constants.state.CONNECTING

      if (this._pendingOpen) this._continueOpen(err)
      else this.destroy(err)
      return
    }

    this._state |= constants.state.CONNECTED | constants.state.READABLE | constants.state.WRITABLE
    this._state &= ~constants.state.CONNECTING
    this._continueOpen()

    this.emit('connect')
  }

  _onaccept() {
    this._state |= constants.state.CONNECTED | constants.state.READABLE | constants.state.WRITABLE
    this._continueOpen()
  }

  _onread(err, read) {
    if (err) {
      this.destroy(err)
      return
    }

    if (read === 0) {
      this.push(null)
      if (this._allowHalfOpen === false) this.end()
      return
    }

    const copy = Buffer.allocUnsafe(read)
    copy.set(this._buffer.subarray(0, read))

    if (this.push(copy) === false && this.destroying === false) {
      this._state &= ~constants.state.READING

      binding.pause(this._handle)
    }
  }

  _onhandle(type) {
    this.emit('handle', type)
  }

  _onwrite(err) {
    this._continueWrite(err)
  }

  _onfinal(err) {
    this._continueFinal(err === null || err.code === 'ENOTCONN' ? null : err)
  }

  _onclose() {
    this._continueDestroy()
  }

  _onspawn(readable, writable) {
    this._state |= constants.state.CONNECTED

    if (readable) {
      this._state |= constants.state.READABLE
    } else {
      this.push(null)
    }

    if (writable) {
      this._state |= constants.state.WRITABLE
    } else {
      this.end()
    }

    this._continueOpen()
  }
}

exports.Pipe = exports

exports.pipe = function pipe() {
  return binding.pipe()
}

exports.Server = class PipeServer extends EventEmitter {
  constructor(opts = {}, onconnection) {
    if (typeof opts === 'function') {
      onconnection = opts
      opts = {}
    }

    super()

    const {
      readBufferSize = defaultReadBufferSize,
      allowHalfOpen = true,
      pauseOnConnect = false,
      ipc = false
    } = opts

    this._state = 0

    this._readBufferSize = readBufferSize
    this._allowHalfOpen = allowHalfOpen
    this._pauseOnConnect = pauseOnConnect
    this._ipc = ipc

    this._path = null
    this._connections = new Set()

    this._error = null
    this._handle = null

    if (onconnection) this.on('connection', onconnection)
  }

  get listening() {
    return (this._state & constants.state.BOUND) !== 0
  }

  address() {
    if ((this._state & constants.state.BOUND) === 0) {
      return null
    }

    return this._path
  }

  listen(path, backlog = 511, opts = {}, onlistening) {
    if (this._state & constants.state.BINDING || this._state & constants.state.BOUND) {
      throw errors.SERVER_ALREADY_LISTENING('Server is already listening')
    }

    if (this._state & constants.state.CLOSING) {
      throw errors.SERVER_IS_CLOSED('Server is closed')
    }

    this._state |= constants.state.BINDING

    if (typeof backlog === 'function') {
      onlistening = backlog
      backlog = 511
    } else if (typeof opts === 'function') {
      onlistening = opts
      opts = {}
    }

    if (typeof path === 'object' && path !== null) {
      opts = path || {}
      path = opts.path
      backlog = opts.backlog || 511
    }

    this._handle = binding.init(
      empty,
      this._ipc,
      this,
      this._onconnection,
      noop,
      noop,
      noop,
      noop,
      noop,
      this._onclose
    )

    if (this._state & constants.state.UNREFED) binding.unref(this._handle)

    try {
      binding.bind(this._handle, path, backlog)

      this._path = path
      this._state |= constants.state.BOUND
      this._state &= ~constants.state.BINDING

      if (onlistening) this.once('listening', onlistening)

      queueMicrotask(() => this.emit('listening'))
    } catch (err) {
      this._error = err

      binding.close(this._handle)
    }

    return this
  }

  close(onclose) {
    if (onclose) this.once('close', onclose)

    if (this._state & constants.state.CLOSING) return
    this._state |= constants.state.CLOSING

    this._closeMaybe()

    return this
  }

  ref() {
    this._state &= ~constants.state.UNREFED

    if (this._handle !== null) binding.ref(this._handle)

    return this
  }

  unref() {
    this._state |= constants.state.UNREFED

    if (this._handle !== null) binding.unref(this._handle)

    return this
  }

  _closeMaybe() {
    if (this._state & constants.state.CLOSING && this._connections.size === 0) {
      if (this._handle !== null) binding.close(this._handle)
      else queueMicrotask(() => this.emit('close'))
    }
  }

  _onconnection(err) {
    if (err) {
      this.emit('error', err)
      return
    }

    if (this._state & constants.state.CLOSING) return

    const pipe = new exports.Pipe({
      readBufferSize: this._readBufferSize,
      allowHalfOpen: this._allowHalfOpen,
      eagerOpen: !this._pauseOnConnect,
      ipc: this._ipc
    })

    try {
      binding.accept(this._handle, pipe._handle)

      pipe._path = this._path
      pipe._onaccept()

      this._connections.add(pipe)

      pipe.on('close', () => {
        this._connections.delete(pipe)
        this._closeMaybe()
      })

      this.emit('connection', pipe)
    } catch (err) {
      pipe.destroy()

      throw err
    }
  }

  _onclose() {
    const err = this._error

    this._state &= ~constants.state.BINDING
    this._state &= ~constants.state.BOUND
    this._error = null
    this._handle = null

    if (err) this.emit('error', err)
    else this.emit('close')
  }
}

exports.constants = constants
exports.errors = errors

exports.createConnection = function createConnection(path, opts, onconnect) {
  if (typeof opts === 'function') {
    onconnect = opts
    opts = {}
  }

  if (typeof path === 'object' && path !== null) {
    opts = path || {}
    path = opts.path
  }

  return new exports.Pipe(opts).connect(path, opts, onconnect)
}

exports.createServer = function createServer(opts, onconnection) {
  return new exports.Server(opts, onconnection)
}

function noop() {}
const binding = require('../binding')

module.exports = {
  state: {
    CONNECTING: 0x1,
    CONNECTED: 0x2,
    BINDING: 0x4,
    BOUND: 0x8,
    READING: 0x10,
    CLOSING: 0x20,
    READABLE: 0x40,
    WRITABLE: 0x80,
    UNREFED: 0x100
  },
  handle: {
    NAMED_PIPE: binding.UV_NAMED_PIPE,
    TCP: binding.UV_TCP,
    UDP: binding.UV_UDP
  }
}
module.exports = class PipeError extends Error {
  constructor(msg, fn = PipeError, code = fn.name) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'PipeError'
  }

  static PIPE_ALREADY_CONNECTED(msg) {
    return new PipeError(msg, PipeError.PIPE_ALREADY_CONNECTED)
  }

  static SERVER_ALREADY_LISTENING(msg) {
    return new PipeError(msg, PipeError.SERVER_ALREADY_LISTENING)
  }

  static SERVER_IS_CLOSED(msg) {
    return new PipeError(msg, PipeError.SERVER_IS_CLOSED)
  }

  static INVALID_IPC_TARGET(msg) {
    return new PipeError(msg, PipeError.INVALID_IPC_TARGET)
  }
}
{
  "name": "bare-pipe",
  "version": "4.2.3",
  "description": "Native I/O pipes for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    },
    "./errors": {
      "types": "./lib/errors.d.ts",
      "default": "./lib/errors.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-pipe.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-pipe/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-pipe#readme",
  "engines": {
    "bare": ">=1.16.0"
  },
  "dependencies": {
    "bare-events": "^2.0.0",
    "bare-stream": "^2.0.0"
  },
  "devDependencies": {
    "bare-path": "^3.0.0",
    "bare-tcp": "^2.4.1",
    "brittle": "^3.2.1",
    "cmake-bare": "^1.1.6",
    "lunte": "^1.8.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  }
}
{
  "name": "bare-posix",
  "version": "1.0.1",
  "description": "POSIX-specific bindings for Bare",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "android": "./unsupported.js",
      "win32": "./unsupported.js",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "unsupported.js",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-posix.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-posix/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-posix#readme",
  "devDependencies": {
    "brittle": "^3.19.1",
    "cmake-bare": "^1.7.7",
    "lunte": "^1.6.0",
    "prettier": "^3.8.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
exports.getgid = function getgid() {
  return -1
}

exports.setgid = function setgid() {
  throw new Error('Platform not supported')
}

exports.getegid = function getegid() {
  return -1
}

exports.setegid = function setgid() {
  throw new Error('Platform not supported')
}

exports.getuid = function getuid() {
  return -1
}

exports.setuid = function setgid() {
  throw new Error('Platform not supported')
}

exports.geteuid = function geteuid() {
  return -1
}

exports.seteuid = function setgid() {
  throw new Error('Platform not supported')
}

exports.getgroups = function getgroups() {
  return []
}

exports.getgrnam = function getgrnam() {
  return null
}

exports.getpwnam = function getpwnam() {
  return null
}
const abort = require('bare-abort')
const EventEmitter = require('bare-events')
const Signal = require('bare-signals')
const os = require('bare-os')
const env = require('bare-env')
const hrtime = require('bare-hrtime')
const stdio = require('bare-stdio')
const posix = require('bare-posix')

class Process extends EventEmitter {
  constructor() {
    super()

    this._startTime = hrtime.bigint()

    EventEmitter.forward(Bare, this, [
      'uncaughtException',
      'unhandledRejection',
      'beforeExit',
      'exit',
      'suspend',
      'wakeup',
      'idle',
      'resume'
    ])

    const signals = new Signal.Emitter()

    signals.unref()

    EventEmitter.forward(signals, this, Object.keys(os.constants.signals))
  }

  get stdin() {
    return stdio.in
  }

  get stdout() {
    return stdio.out
  }

  get stderr() {
    return stdio.err
  }

  get platform() {
    return os.platform()
  }

  get arch() {
    return os.arch()
  }

  get title() {
    return os.getProcessTitle()
  }

  set title(title) {
    os.setProcessTitle(title)
  }

  get pid() {
    return os.pid()
  }

  get ppid() {
    return os.ppid()
  }

  get argv() {
    return Bare.argv
  }

  get execArgv() {
    return []
  }

  get execPath() {
    return os.execPath()
  }

  get exitCode() {
    return Bare.exitCode
  }

  set exitCode(code) {
    Bare.exitCode = code
  }

  get version() {
    return Bare.version
  }

  get versions() {
    return Bare.versions
  }

  get env() {
    return env
  }

  get hrtime() {
    return hrtime
  }

  abort() {
    abort()
  }

  exit(code) {
    Bare.exit(code)
  }

  suspend() {
    Bare.suspend()
  }

  resume() {
    Bare.resume()
  }

  cwd() {
    return os.cwd()
  }

  chdir(directory) {
    os.chdir(directory)
  }

  kill(pid, signal) {
    os.kill(pid, signal)
  }

  uptime() {
    return Number(hrtime.bigint() - this._startTime) / 1e9
  }

  cpuUsage(previous) {
    return os.cpuUsage(previous)
  }

  threadCpuUsage(previous) {
    return os.threadCpuUsage(previous)
  }

  resourceUsage() {
    return os.resourceUsage()
  }

  availableMemory() {
    return os.availableMemory()
  }

  constrainedMemory() {
    return os.constrainedMemory()
  }

  memoryUsage() {
    return os.memoryUsage()
  }

  getgid() {
    return posix.getgid()
  }

  setgid(id) {
    return posix.setgid(id)
  }

  getegid() {
    return posix.getegid()
  }

  setegid(id) {
    return posix.setegid(id)
  }

  getuid() {
    return posix.getuid()
  }

  setuid(id) {
    return posix.setuid(id)
  }

  geteuid() {
    return posix.geteuid()
  }

  seteuid(id) {
    return posix.seteuid(id)
  }

  getgroups() {
    return posix.getgroups()
  }

  nextTick(cb, ...args) {
    queueMicrotask(cb.bind(null, ...args))
  }

  [Symbol.for('bare.inspect')]() {
    return {
      __proto__: { constructor: Process },

      platform: this.platform,
      arch: this.arch,
      title: this.title,
      pid: this.pid,
      ppid: this.ppid,
      argv: this.argv,
      execPath: this.execPath,
      exitCode: this.exitCode,
      version: this.version,
      versions: this.versions,
      env: this.env
    }
  }
}

module.exports = new Process()
{
  "name": "bare-process",
  "version": "4.5.1",
  "description": "Node.js-compatible process control for Bare",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "global.js",
    "global.d.ts"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-process.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-process/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-process#readme",
  "dependencies": {
    "bare-abort": "^2.0.13",
    "bare-env": "^3.0.0",
    "bare-events": "^2.3.1",
    "bare-hrtime": "^2.0.0",
    "bare-os": "^3.7.1",
    "bare-posix": "^1.0.1",
    "bare-signals": "^5.0.0",
    "bare-stdio": "^1.0.1"
  },
  "devDependencies": {
    "brittle": "^3.2.1",
    "lunte": "^1.6.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = require.addon()
const EventEmitter = require('bare-events')
const binding = require('./binding')
const errors = require('./lib/errors')

const signals = binding.signals

module.exports = exports = class Signal extends EventEmitter {
  constructor(signum) {
    super()

    if (typeof signum === 'string') {
      if (signum in signals === false) {
        throw errors.UNKNOWN_SIGNAL(`Unknown signal '${signum}'`)
      }

      signum = signals[signum]
    }

    this._signum = signum
    this._closing = null
    this._handle = binding.init(this, this._onsignal, this._onclose)
  }

  start() {
    if (this._closing) throw errors.SIGNAL_CLOSED('Signal is closed')
    binding.start(this._handle, this._signum)
    return this
  }

  stop() {
    if (this._closing) return this
    binding.stop(this._handle)
    return this
  }

  ref() {
    if (this._closing) return this
    binding.ref(this._handle)
    return this
  }

  unref() {
    if (this._closing) return this
    binding.unref(this._handle)
    return this
  }

  close() {
    if (this._closing) return this._closing
    this._closing = EventEmitter.once(this, 'close')

    binding.close(this._handle)

    return this._closing
  }

  _onsignal() {
    this.emit('signal', this._signum)
  }

  _onclose() {
    this._handle = null

    this.emit('close')
  }
}

exports.Emitter = require('./lib/emitter')

exports.constants = signals
exports.errors = errors
const EventEmitter = require('bare-events')
const Signal = require('..')

module.exports = class SignalEmitter extends EventEmitter {
  constructor() {
    super()

    this._signals = new Map()
    this._unrefed = false

    this.on('newListener', this._onnewlistener).on('removeListener', this._onremovelistener)
  }

  ref() {
    this._unrefed = false
    for (const signal of this._signals.values()) signal.ref()
    return this
  }

  unref() {
    this._unrefed = true
    for (const signal of this._signals.values()) signal.unref()
    return this
  }

  _onnewlistener(name) {
    if (name === 'newListener' || name === 'removeListener') return

    if (this.listenerCount(name) === 0) {
      const signal = new Signal(name)

      signal.on('signal', this._onsignal.bind(this, name)).start()

      if (this._unrefed) signal.unref()

      this._signals.set(name, signal)
    }
  }

  _onremovelistener(name) {
    if (name === 'newListener' || name === 'removeListener') return

    if (this.listenerCount(name) === 0) {
      const signal = this._signals.get(name)

      if (this._unrefed) signal.ref()

      signal.close()

      this._signals.delete(name)
    }
  }

  _onsignal(name) {
    this.emit(name, name, Signal.constants[name])
  }
}
module.exports = class SignalError extends Error {
  constructor(msg, fn = SignalError, code = fn.name) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'SignalError'
  }

  static UNKNOWN_SIGNAL(msg) {
    return new SignalError(msg, SignalError.UNKNOWN_SIGNAL)
  }

  static SIGNAL_CLOSED(msg) {
    return new SignalError(msg, SignalError.SIGNAL_CLOSED)
  }
}
{
  "name": "bare-signals",
  "version": "5.0.0",
  "description": "Native signal handling for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./errors": "./lib/errors.js",
    "./emitter": "./lib/emitter.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-signals.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-signals/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-signals#readme",
  "engines": {
    "bare": ">=1.7.0"
  },
  "dependencies": {
    "bare-events": "^2.5.3"
  },
  "devDependencies": {
    "bare-os": "^3.3.1",
    "brittle": "^3.2.1",
    "cmake-bare": "^1.1.6",
    "lunte": "^1.8.3",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = require.addon()
const fs = require('bare-fs')
const tty = require('bare-tty')
const Pipe = require('bare-pipe')
const binding = require('./binding')

const { TTY, NAMED_PIPE } = binding

class IO {
  constructor() {
    this._in = null
    this._out = null
    this._err = null
  }

  get in() {
    if (this._in === null) {
      switch (binding.guessType(0)) {
        case TTY:
          this._in = new tty.ReadStream(0)
          break
        case NAMED_PIPE:
          this._in = new Pipe(0, { eagerOpen: false })
          break
        default:
          this._in = fs.createReadStream(null, { fd: 0, eagerOpen: false })
      }
    }

    return this._in
  }

  get out() {
    if (this._out === null) {
      switch (binding.guessType(1)) {
        case TTY:
          this._out = new tty.WriteStream(1)
          break
        case NAMED_PIPE:
          this._out = new Pipe(1, { eagerOpen: false })
          this._out.unref()
          break
        default:
          this._out = fs.createWriteStream(null, { fd: 1, eagerOpen: false })
      }
    }

    return this._out
  }

  get err() {
    if (this._err === null) {
      switch (binding.guessType(2)) {
        case TTY:
          this._err = new tty.WriteStream(2)
          break
        case NAMED_PIPE:
          this._err = new Pipe(2, { eagerOpen: false })
          this._err.unref()
          break
        default:
          this._err = fs.createWriteStream(null, { fd: 2, eagerOpen: false })
      }
    }

    return this._err
  }
}

module.exports = new IO()
{
  "name": "bare-stdio",
  "version": "1.0.3",
  "description": "Standard input/output streams for Bare",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-stdio.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-stdio/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-stdio#readme",
  "dependencies": {
    "bare-fs": "^4.5.2",
    "bare-pipe": "^4.1.5",
    "bare-tty": "^5.0.3"
  },
  "devDependencies": {
    "bare-os": "^3.6.2",
    "bare-path": "^3.0.0",
    "bare-subprocess": "^6.0.0",
    "brittle": "^3.19.1",
    "cmake-bare": "^1.7.7",
    "lunte": "^1.4.0",
    "prettier": "^3.8.1",
    "prettier-config-holepunch": "^2.0.0",
    "tt-native": "^1.1.1"
  }
}
const b4a = require('b4a')
const stream = require('streamx')
const { ReadableStream, WritableStream } = require('./web')

const defaultEncoding = 'utf8'

module.exports = exports = stream.Stream

exports.pipeline = stream.pipeline

exports.isStream = stream.isStream
exports.isEnding = stream.isEnding
exports.isEnded = stream.isEnded
exports.isFinishing = stream.isFinishing
exports.isFinished = stream.isFinished
exports.isDisturbed = stream.isDisturbed

exports.isErrored = function isErrored(stream) {
  return exports.getStreamError(stream) !== null
}

exports.isReadable = function isReadable(stream) {
  return stream.readable && !stream.destroying && !exports.isEnded(stream)
}

exports.isWritable = function isWritable(stream) {
  return stream.writable && !stream.destroying && !exports.isFinishing(stream)
}

exports.getStreamError = stream.getStreamError

exports.addAbortSignal = function addAbortSignal(signal, stream) {
  function onAbort() {
    stream.destroy(signal.reason)
  }

  if (signal.aborted) onAbort()
  else signal.addEventListener('abort', onAbort)

  return stream
}

exports.Stream = exports

exports.Readable = class Readable extends stream.Readable {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthReadable: null,
      map: null,
      mapReadable: null
    })

    if (this._construct) this._open = this._construct

    if (this._read !== stream.Readable.prototype._read) {
      this._read = read.bind(this, this._read)
    }

    if (this._destroy !== stream.Stream.prototype._destroy) {
      this._destroy = destroy.bind(this, this._destroy)
    }
  }

  get closed() {
    return !exports.isReadable(this)
  }

  get errored() {
    return stream.getStreamError(this)
  }

  push(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    return super.push(chunk)
  }

  unshift(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    super.unshift(chunk)
  }

  static fromWeb(readableStream, opts = {}) {
    const stream = readableStream._stream

    if (opts.encoding) stream.setEncoding(opts.encoding)
    if (opts.signal) exports.addAbortSignal(opts.signal, stream)

    return stream
  }

  static toWeb(readable, opts = {}) {
    return new ReadableStream(readable, opts.strategy)
  }

  async [Symbol.asyncDispose]() {
    if (!this.destroyed) this.destroy()

    await new Promise((resolve) => exports.finished(this, resolve))
  }
}

exports.Writable = class Writable extends stream.Writable {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthWritable,
      map: null,
      mapWritable: null
    })

    if (this._construct) this._open = this._construct

    if (this._write !== stream.Writable.prototype._write) {
      this._write = write.bind(this, this._write)
    }

    if (this._destroy !== stream.Stream.prototype._destroy) {
      this._destroy = destroy.bind(this, this._destroy)
    }
  }

  get closed() {
    return !exports.isWritable(this)
  }

  get errored() {
    return stream.getStreamError(this)
  }

  write(chunk, encoding, cb) {
    if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result = super.write({ chunk, encoding })

    if (cb) stream.Writable.drained(this).then(() => cb(null), cb)

    return result
  }

  end(chunk, encoding, cb) {
    if (typeof chunk === 'function') {
      cb = chunk
      chunk = null
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    } else {
      encoding = 'buffer'
    }

    const result =
      chunk !== undefined && chunk !== null ? super.end({ chunk, encoding }) : super.end()

    if (cb) this.once('finish', () => cb(null))

    return result
  }

  static fromWeb(writableStream, opts = {}) {
    const stream = writableStream._stream

    if (opts.signal) exports.addAbortSignal(opts.signal, stream)

    return stream
  }

  static toWeb(writable) {
    return new WritableStream(writable)
  }

  async [Symbol.asyncDispose]() {
    if (!this.destroyed) this.destroy()

    await new Promise((resolve) => exports.finished(this, resolve))
  }
}

exports.Duplex = class Duplex extends stream.Duplex {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthReadable: null,
      byteLengthWritable,
      map: null,
      mapReadable: null,
      mapWritable: null
    })

    if (this._construct) this._open = this._construct

    if (this._read !== stream.Readable.prototype._read) {
      this._read = read.bind(this, this._read)
    }

    if (this._write !== stream.Duplex.prototype._write) {
      this._write = write.bind(this, this._write)
    }

    if (this._destroy !== stream.Stream.prototype._destroy) {
      this._destroy = destroy.bind(this, this._destroy)
    }
  }

  push(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    return super.push(chunk)
  }

  unshift(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    super.unshift(chunk)
  }

  write(chunk, encoding, cb) {
    if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result = super.write({ chunk, encoding })

    if (cb) stream.Writable.drained(this).then(() => cb(null), cb)

    return result
  }

  end(chunk, encoding, cb) {
    if (typeof chunk === 'function') {
      cb = chunk
      chunk = null
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result =
      chunk !== undefined && chunk !== null ? super.end({ chunk, encoding }) : super.end()

    if (cb) this.once('finish', () => cb(null))

    return result
  }

  static fromWeb({ readable: readableStream, writable: writableStream }, opts) {
    const readable = exports.Readable.fromWeb(readableStream, opts)
    const writable = exports.Writable.fromWeb(writableStream, opts)

    const duplex = new exports.Duplex({
      write(data, encoding, cb) {
        writable.write(data, encoding, cb)
      }
    })

    readable
      .on('data', (data) => duplex.push(data))
      .on('end', () => duplex.push(null))
      .on('error', (err) => duplex.destroy(err))

    writable.on('finish', () => duplex.end()).on('error', (err) => duplex.destroy(err))

    return duplex
  }

  static toWeb(duplex) {
    const readableStream = exports.Readable.toWeb(duplex)
    const writableStream = exports.Writable.toWeb(duplex)

    return { readable: readableStream, writable: writableStream }
  }
}

class DuplexSide extends exports.Duplex {
  constructor(opts) {
    super(opts)

    this._otherSide = null
    this._cb = null
  }

  _read() {
    const cb = this._cb
    if (!cb) return

    this._cb = null
    cb()
  }

  _write(chunk, encoding, cb) {
    this._otherSide.push(chunk, encoding)
    this._otherSide._cb = cb
  }

  _final(cb) {
    this._otherSide.on('end', cb)
    this._otherSide.push(null)
  }
}

exports.duplexPair = function duplexPair(opts) {
  const sideA = new DuplexSide(opts)
  const sideB = new DuplexSide(opts)

  sideA._otherSide = sideB
  sideB._otherSide = sideA

  return [sideA, sideB]
}

exports.Transform = class Transform extends stream.Transform {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthReadable: null,
      byteLengthWritable,
      map: null,
      mapReadable: null,
      mapWritable: null
    })

    if (this._transform !== stream.Transform.prototype._transform) {
      this._transform = transform.bind(this, this._transform)
    } else {
      this._transform = passthrough
    }
  }

  push(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    return super.push(chunk)
  }

  unshift(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    super.unshift(chunk)
  }

  write(chunk, encoding, cb) {
    if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result = super.write({ chunk, encoding })

    if (cb) stream.Writable.drained(this).then(() => cb(null), cb)

    return result
  }

  end(chunk, encoding, cb) {
    if (typeof chunk === 'function') {
      cb = chunk
      chunk = null
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result =
      chunk !== undefined && chunk !== null ? super.end({ chunk, encoding }) : super.end()

    if (cb) this.once('finish', () => cb(null))

    return result
  }
}

exports.PassThrough = class PassThrough extends exports.Transform {}

exports.finished = function finished(stream, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (!opts) opts = {}

  const { cleanup = false } = opts

  const done = () => {
    cb(exports.getStreamError(stream, { all: true }))

    if (cleanup) detach()
  }

  const detach = () => {
    stream.off('close', done)
    stream.off('error', noop)
  }

  if (stream.destroyed) {
    done()
  } else {
    stream.on('close', done)
    stream.on('error', noop)
  }

  return detach
}

function read(read, cb) {
  read.call(this, 65536)

  cb(null)
}

function write(write, data, cb) {
  write.call(this, data.chunk, data.encoding, cb)
}

function transform(transform, data, cb) {
  transform.call(this, data.chunk, data.encoding, cb)
}

function destroy(destroy, cb) {
  destroy.call(this, exports.getStreamError(this), cb)
}

function passthrough(data, cb) {
  cb(null, data.chunk)
}

function byteLengthWritable(data) {
  return data.chunk.byteLength
}

function noop() {}
{
  "name": "bare-stream",
  "version": "2.13.3",
  "description": "Streaming data for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./promises": "./promises.js",
    "./web": {
      "types": "./web.d.ts",
      "default": "./web.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "promises.js",
    "web.js",
    "web.d.ts",
    "global.js",
    "global.d.ts"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-stream.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-stream/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-stream#readme",
  "dependencies": {
    "b4a": "^1.8.1",
    "streamx": "^2.25.0",
    "teex": "^1.0.1"
  },
  "devDependencies": {
    "bare-abort-controller": "^1.1.0",
    "bare-buffer": "^3.0.0",
    "bare-events": "^2.5.4",
    "brittle": "^3.5.2",
    "lunte": "^1.6.0",
    "prettier": "^3.3.3",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "bare-abort-controller": "*",
    "bare-buffer": "*",
    "bare-events": "*"
  },
  "peerDependenciesMeta": {
    "bare-abort-controller": {
      "optional": true
    },
    "bare-buffer": {
      "optional": true
    },
    "bare-events": {
      "optional": true
    }
  }
}
const { Readable, Writable, Transform, getStreamError, isStreamx, isDisturbed } = require('streamx')
const tee = require('teex')

const readableKind = Symbol.for('bare.stream.readable.kind')
const writableKind = Symbol.for('bare.stream.writable.kind')
const transformKind = Symbol.for('bare.stream.transform.kind')

// https://streams.spec.whatwg.org/#readablestreamdefaultreader
exports.ReadableStreamDefaultReader = class ReadableStreamDefaultReader {
  constructor(stream) {
    this._stream = stream
    this._stream._stream.once('close', onclose).once('error', onerror)

    const closed = Promise.withResolvers()

    // Avoid unhandled exceptions
    closed.promise.catch(noop)

    this._closed = closed

    function onclose() {
      closed.resolve()
    }

    function onerror(err) {
      closed.reject(err)
    }
  }

  get closed() {
    return this._closed.promise
  }

  read() {
    const stream = this._stream._stream

    return new Promise((resolve, reject) => {
      const err = getStreamError(stream)

      if (err) return reject(err)

      if (stream.destroyed) {
        return resolve({ value: undefined, done: true })
      }

      const value = stream.read()

      if (value !== null) {
        return resolve({ value, done: false })
      }

      stream.once('readable', onreadable).once('close', onclose).once('error', onerror)

      function onreadable() {
        const value = stream.read()

        ondone(null, value === null ? { value: undefined, done: true } : { value, done: false })
      }

      function onclose() {
        ondone(null, { value: undefined, done: true })
      }

      function onerror(err) {
        ondone(err, null)
      }

      function ondone(err, value) {
        stream.off('readable', onreadable).off('close', onclose).off('error', onerror)

        if (err) reject(err)
        else resolve(value)
      }
    })
  }

  releaseLock() {
    this._closed.reject(new TypeError('Reader was released'))
    this._stream._releaseLock()
    this._stream = null
  }

  cancel(reason = new TypeError('Stream was cancelled')) {
    const stream = this._stream._stream

    if (stream.destroyed) return Promise.resolve()

    return new Promise((resolve) =>
      stream.once('close', resolve).once('error', noop).destroy(reason)
    )
  }
}

// https://streams.spec.whatwg.org/#readablestreamdefaultcontroller
exports.ReadableStreamDefaultController = class ReadableStreamDefaultController {
  constructor(stream) {
    this._stream = stream
  }

  get desiredSize() {
    const stream = this._stream._stream

    return stream._readableState.highWaterMark - stream._readableState.buffered
  }

  enqueue(data) {
    this._stream._stream.push(data)
  }

  close() {
    this._stream._stream.push(null)
  }

  error(err) {
    this._stream._stream.destroy(err)
  }
}

// https://streams.spec.whatwg.org/#readablestream
class ReadableStream {
  static get [readableKind]() {
    return 0 // Compatibility version
  }

  static from(iterable) {
    return new ReadableStream(Readable.from(iterable))
  }

  constructor(underlyingSource = {}, queuingStrategy) {
    if (isStreamx(underlyingSource)) {
      this._stream = underlyingSource
    } else {
      if (queuingStrategy === undefined) {
        queuingStrategy = new exports.CountQueuingStrategy()
      }

      const { start, pull, cancel } = underlyingSource
      const { highWaterMark = 1, size = defaultSize } = queuingStrategy

      this._stream = new Readable({ highWaterMark, byteLength: size })

      const controller = new exports.ReadableStreamDefaultController(this)

      try {
        let starting = Promise.resolve()

        if (start) starting = forwardError(start.call(this, controller), controller)

        if (pull) {
          this._stream._read = this._read.bind(this, starting, pull.bind(this, controller))
        }

        if (cancel) {
          this._stream.once('error', cancel.bind(this))
        }
      } catch (err) {
        controller.error(err)
      }
    }

    this._reader = null
  }

  get [readableKind]() {
    return ReadableStream[readableKind]
  }

  get locked() {
    return this._reader !== null
  }

  getReader() {
    if (this.locked) throw new TypeError('Stream is locked')

    this._reader = new exports.ReadableStreamDefaultReader(this)

    return this._reader
  }

  cancel(reason = new TypeError('Stream was cancelled')) {
    const stream = this._stream

    if (stream.destroyed) return Promise.resolve()

    if (this.locked) return Promise.reject(new TypeError('Stream is locked'))

    return new Promise((resolve) =>
      stream.once('close', resolve).once('error', noop).destroy(reason)
    )
  }

  tee() {
    const [a, b] = tee(this._stream)

    return [new ReadableStream(a), new ReadableStream(b)]
  }

  pipeTo(destination) {
    return new Promise((resolve, reject) =>
      this._stream.pipe(destination._stream, (err) => {
        err ? reject(err) : resolve()
      })
    )
  }

  [Symbol.asyncIterator]() {
    return this._stream[Symbol.asyncIterator]()
  }

  _releaseLock() {
    this._reader = null
  }

  async _read(starting, pull, cb) {
    await starting

    let err = null
    try {
      await pull()
    } catch (e) {
      err = e
    }
    cb(err)
  }
}

function defaultSize() {
  return 1
}

exports.ReadableStream = ReadableStream

// https://streams.spec.whatwg.org/#countqueuingstrategy
exports.CountQueuingStrategy = class CountQueuingStrategy {
  constructor(opts = {}) {
    const { highWaterMark = 1 } = opts

    this.highWaterMark = highWaterMark
  }

  size(chunk) {
    return 1
  }
}

// https://streams.spec.whatwg.org/#bytelengthqueuingstrategy
exports.ByteLengthQueuingStrategy = class ByteLengthQueuingStrategy {
  constructor(opts = {}) {
    const { highWaterMark = 16384 } = opts

    this.highWaterMark = highWaterMark
  }

  size(chunk) {
    return chunk.byteLength
  }
}

exports.isReadableStream = function isReadableStream(value) {
  if (value instanceof ReadableStream) return true

  return (
    typeof value === 'object' &&
    value !== null &&
    value[readableKind] === ReadableStream[readableKind]
  )
}

// https://streams.spec.whatwg.org/#readablestream-errored
exports.isReadableStreamErrored = function isReadableStreamErrored(stream) {
  return getStreamError(stream._stream) !== null
}

// https://streams.spec.whatwg.org/#is-readable-stream-disturbed
exports.isReadableStreamDisturbed = function isReadableStreamDisturbed(stream) {
  return isDisturbed(stream._stream)
}

// https://streams.spec.whatwg.org/#writablestreamdefaultwriter
exports.WritableStreamDefaultWriter = class WritableStreamDefaultWriter {
  constructor(stream) {
    this._stream = stream
    this._stream._stream.once('close', onclose).once('error', onerror)

    const closed = Promise.withResolvers()

    // Avoid unhandled exceptions
    closed.promise.catch(noop)

    this._closed = closed

    function onclose() {
      closed.resolve()
    }

    function onerror(err) {
      closed.reject(err)
    }
  }

  get desiredSize() {
    const stream = this._stream._stream

    return stream._writableState.highWaterMark - stream._writableState.buffered
  }

  get closed() {
    return this._closed.promise
  }

  get ready() {
    const stream = this._stream._stream

    if (getStreamError(stream)) return Promise.reject()

    return Writable.drained(stream).then()
  }

  async write(chunk) {
    const stream = this._stream._stream

    let err = getStreamError(stream)
    if (err) return Promise.reject(err)

    stream.write(chunk)

    await Writable.drained(stream)

    err = getStreamError(stream)
    if (err) return Promise.reject(err)
  }

  releaseLock() {
    this._closed.reject(new TypeError('Writer was released'))
    this._stream._releaseLock()
    this._stream = null
  }

  close() {
    const stream = this._stream._stream

    if (stream.destroyed) return Promise.resolve()

    return new Promise((resolve) => stream.once('close', resolve).end())
  }

  abort(reason = new TypeError('Stream was aborted')) {
    const stream = this._stream._stream

    if (stream.destroyed) return Promise.resolve()

    return new Promise((resolve) => stream.once('close', resolve).destroy(reason))
  }
}

// https://streams.spec.whatwg.org/#writablestreamdefaultcontroller
exports.WritableStreamDefaultController = class WritableStreamDefaultController {
  constructor(stream) {
    this._stream = stream
  }

  error(err) {
    this._stream._stream.destroy(err)
  }
}

// https://streams.spec.whatwg.org/#writablestream
class WritableStream {
  static get [writableKind]() {
    return 0 // Compatibility version
  }

  constructor(underlyingSink = {}, queuingStrategy = {}) {
    if (isStreamx(underlyingSink)) {
      this._stream = underlyingSink
    } else {
      if (queuingStrategy === undefined) {
        queuingStrategy = new exports.CountQueuingStrategy()
      }

      const { start, write, close, abort } = underlyingSink
      const { highWaterMark = 1, size = defaultSize } = queuingStrategy

      this._stream = new Writable({ highWaterMark, byteLength: size })

      const controller = new exports.WritableStreamDefaultController(this)

      this._controller = controller

      try {
        let starting = Promise.resolve()

        if (start) starting = forwardError(start.call(this, controller), controller)

        if (write) {
          this._stream._write = this._write.bind(this, starting, write.bind(this))
        }

        if (close) {
          this._stream._destroy = this._destroy.bind(this, close.call(this))
        }

        if (abort) {
          this._stream.once('error', abort.bind(this))
        }
      } catch (err) {
        controller.error(err)
      }
    }

    this._writer = null
  }

  get [writableKind]() {
    return WritableStream[writableKind]
  }

  get locked() {
    return this._writer !== null
  }

  getWriter() {
    if (this.locked) throw new TypeError('Stream is locked')

    this._writer = new exports.WritableStreamDefaultWriter(this)

    return this._writer
  }

  abort(reason = new TypeError('Stream was aborted')) {
    if (this._stream.destroyed) return Promise.resolve()

    if (this.locked) return Promise.reject(new TypeError('Stream is locked'))

    return new Promise((resolve) => this._stream.once('close', resolve).destroy(reason))
  }

  close() {
    if (this._stream.destroyed) return Promise.resolve()

    if (this.locked) return Promise.reject(new TypeError('Stream is locked'))

    return new Promise((resolve) => this._stream.once('close', resolve).end())
  }

  _releaseLock() {
    this._writer = null
  }

  async _write(starting, write, data, cb) {
    await starting

    let err = null
    try {
      await write(data, this._controller)
    } catch (e) {
      err = e
    }
    cb(err)
  }

  async _destroy(closing, cb) {
    let err = null
    try {
      await closing
    } catch (e) {
      err = e
    }
    cb(err)
  }
}

exports.WritableStream = WritableStream

exports.isWritableStream = function isWritableStream(value) {
  if (value instanceof WritableStream) return true

  return (
    typeof value === 'object' &&
    value !== null &&
    value[writableKind] === WritableStream[writableKind]
  )
}

// https://streams.spec.whatwg.org/#transformstreamdefaultcontroller
exports.TransformStreamDefaultController = class TransformStreamDefaultController {
  constructor(stream) {
    this._stream = stream
  }

  get desiredSize() {
    const stream = this._stream._stream

    return stream._readableState.highWaterMark - stream._readableState.buffered
  }

  enqueue(data) {
    this._stream._stream.push(data)
  }

  error(err) {
    this._stream._stream.destroy(err)
  }

  terminate() {
    const stream = this._stream._stream

    stream.push(null)
    stream.destroy(new TypeError('Stream has been terminated'))
  }
}

// https://streams.spec.whatwg.org/#transformstream
class TransformStream {
  static get [transformKind]() {
    return 0 // Compatibility version
  }

  constructor(transformer = {}, writableStrategy = {}, readableStrategy = {}) {
    if (isStreamx(transformer)) {
      this._stream = transformer
    } else {
      const { start, transform, flush } = transformer

      this._stream = new Transform({ ...writableStrategy, ...readableStrategy })

      const controller = new exports.TransformStreamDefaultController(this)

      this._controller = controller

      try {
        let starting = Promise.resolve()

        if (start) starting = forwardError(start.call(this, controller), controller)

        if (transform) {
          this._stream._transform = this._transform.bind(this, starting, transform.bind(this))
        }

        if (flush) {
          this._stream._flush = this._flush.bind(this, flush.call(this, this._controller))
        }
      } catch (err) {
        controller.error(err)
      }
    }

    this._writable = new WritableStream(this._stream)
    this._readable = new ReadableStream(this._stream)
  }

  get [transformKind]() {
    return TransformStream[transformKind]
  }

  get writable() {
    return this._writable
  }

  get readable() {
    return this._readable
  }

  async _transform(starting, transform, data, cb) {
    await starting

    let err = null
    try {
      await transform(data, this._controller)
    } catch (e) {
      err = e
    }
    cb(err)
  }

  async _flush(flush, cb) {
    let err = null
    try {
      await flush
    } catch (e) {
      err = e
    }
    cb(err)
  }
}

exports.TransformStream = TransformStream

exports.isTransformStream = function isTransformStream(value) {
  if (value instanceof TransformStream) return true

  return (
    typeof value === 'object' &&
    value !== null &&
    value[transformKind] === TransformStream[transformKind]
  )
}

async function forwardError(promise, controller) {
  try {
    await promise
  } catch (err) {
    controller.error(err)
  }
}

function noop() {}
module.exports = require.addon()
const EventEmitter = require('bare-events')
const { Duplex } = require('bare-stream')
const dns = require('bare-dns')
const binding = require('./binding')
const constants = require('./lib/constants')
const errors = require('./lib/errors')
const ip = require('./lib/ip')

const defaultReadBufferSize = 65536
const empty = Buffer.alloc(0)

const ipcHandle = Symbol.for('bare.ipc.handle')
const ipcAccept = Symbol.for('bare.ipc.accept')

exports.Socket = class TCPSocket extends Duplex {
  constructor(opts = {}) {
    const { readBufferSize = defaultReadBufferSize, allowHalfOpen = true, eagerOpen = true } = opts

    super({ eagerOpen })

    this._state = 0

    this._allowHalfOpen = allowHalfOpen

    this._keepAlive = 0
    this._keepAliveInitialDelay = 0
    this._noDelay = 0

    this._localAddress = null
    this._remoteAddress = null

    this._pendingOpen = null
    this._pendingWrite = null
    this._pendingWriteBatch = null
    this._pendingFinal = null
    this._pendingDestroy = null

    this._timer = null
    this._timeout = 0

    this._buffer = Buffer.alloc(readBufferSize)

    this._addresses = null
    this._errors = null

    this._handle = binding.init(
      this._buffer,
      this,
      noop,
      this._onconnect,
      this._onreset,
      this._onread,
      this._onwrite,
      this._onfinal,
      this._onclose
    )
  }

  get connecting() {
    return (this._state & constants.state.CONNECTING) !== 0
  }

  get pending() {
    return (this._state & constants.state.CONNECTED) === 0
  }

  get timeout() {
    return this._timeout || undefined // For Node.js compatibility
  }

  get readyState() {
    if (this._state & constants.state.CONNECTED) {
      return 'open'
    }

    return 'opening'
  }

  get localAddress() {
    if (this._localAddress) return this._localAddress.address
  }

  get localFamily() {
    if (this._localAddress) return `IPv${this._localAddress.family}`
  }

  get localPort() {
    if (this._localAddress) return this._localAddress.port
  }

  get remoteAddress() {
    if (this._remoteAddress) return this._remoteAddress.address
  }

  get remoteFamily() {
    if (this._remoteAddress) return `IPv${this._remoteAddress.family}`
  }

  get remotePort() {
    if (this._remoteAddress) return this._remoteAddress.port
  }

  get [ipcHandle]() {
    return this._handle
  }

  connect(port, host = 'localhost', opts = {}, onconnect) {
    if (this._state & constants.state.CONNECTING || this._state & constants.state.CONNECTED) {
      throw errors.SOCKET_ALREADY_CONNECTED('Socket is already connected')
    }

    if (typeof host === 'function') {
      onconnect = host
      host = 'localhost'
    } else if (typeof opts === 'function') {
      onconnect = opts
      opts = {}
    }

    let family = 0

    if (typeof port === 'object' && port !== null) {
      opts = port || {}
      port = opts.port || 0
      host = opts.host || 'localhost'
      family = opts.family || 0
    }

    if (!host) host = 'localhost'

    validatePort(port)

    this._state |= constants.state.CONNECTING

    const {
      lookup = dns.lookup,
      hints,
      keepAlive = false,
      keepAliveInitialDelay = 0,
      noDelay = false,
      timeout
    } = opts

    const type = ip.isIP(host)

    if (type === 0) {
      lookup(host, { all: true, family, hints }, (err, addresses) => {
        if (this._state & constants.state.CLOSING) return

        this._state &= ~constants.state.CONNECTING

        if (err || addresses.length === 0) {
          if (!err) {
            err = new Error(`No address found for host "${host}"`)
            err.code = 'ENOTFOUND'
          }

          this.emit('lookup', err, null, 0, host)

          if (this._pendingOpen) this._continueOpen(err)
          else this.destroy(err)
          return
        }

        for (const { address, family } of addresses) {
          this.emit('lookup', null, address, family, host)
        }

        const [{ address, family }, ...rest] = addresses

        if (rest.length > 0) {
          this._addresses = rest.map(({ address, family }) => [
            port,
            address,
            { ...opts, family },
            onconnect
          ])

          this._errors = []
        }

        this.connect(port, address, { ...opts, family }, onconnect)
      })

      return this
    }

    family = type

    try {
      binding.connect(this._handle, port, host, family)

      if (keepAlive) {
        this._keepAlive = keepAlive
        this._keepAliveInitialDelay = keepAliveInitialDelay
      }
      if (noDelay) this._noDelay = noDelay
      if (timeout) this.setTimeout(timeout)

      if (onconnect) this.once('connect', onconnect)
    } catch (err) {
      this._state &= ~constants.state.CONNECTING

      queueMicrotask(() => {
        if (this._pendingOpen) this._pendingOpen(err)
        else this.destroy(err)
      })
    }

    return this
  }

  open(fd, opts = {}, onconnect) {
    if (typeof opts === 'function') {
      onconnect = opts
      opts = {}
    }

    if (typeof fd === 'object' && fd !== null) {
      opts = fd
      fd = opts.fd
    }

    try {
      binding.open(this._handle, fd)

      this._state |= constants.state.CONNECTED

      if (onconnect) this.once('connect', onconnect)

      queueMicrotask(() => this.emit('connect'))
    } catch (err) {
      queueMicrotask(() => {
        if (this._pendingOpen) this._pendingOpen(err)
        else this.destroy(err)
      })
    }

    return this
  }

  setKeepAlive(enable = false, delay = 0) {
    if (typeof enable === 'number') {
      delay = enable
      enable = false
    }

    delay = Math.floor(delay / 1000)

    if (delay === 0) enable = false

    binding.keepalive(this._handle, enable, delay)

    return this
  }

  setNoDelay(enable = true) {
    binding.nodelay(this._handle, enable)

    return this
  }

  setTimeout(ms, ontimeout) {
    if (ms === 0) {
      clearTimeout(this._timer)

      this._timer = null
    } else {
      if (ontimeout) this.once('timeout', ontimeout)

      this._timer = setTimeout(() => this.emit('timeout'), ms)
      this._timer.unref()
    }

    this._timeout = ms

    return this
  }

  ref() {
    binding.ref(this._handle)

    return this
  }

  unref() {
    binding.unref(this._handle)

    return this
  }

  [ipcAccept]() {
    this._onaccept()
  }

  _open(cb) {
    if (this._state & constants.state.CONNECTED) return cb(null)

    this._pendingOpen = cb
  }

  _read() {
    if ((this._state & constants.state.READING) === 0) {
      this._state |= constants.state.READING

      binding.resume(this._handle)
    }
  }

  _writev(batch, cb) {
    this._pendingWrite = cb
    this._pendingWriteBatch = batch

    try {
      binding.writev(
        this._handle,
        batch.map(({ chunk }) => chunk)
      )
    } catch (err) {
      this._continueWrite(err)
    }
  }

  _final(cb) {
    this._pendingFinal = cb

    binding.end(this._handle)
  }

  _predestroy() {
    if (this._state & constants.state.CLOSING) return
    this._state |= constants.state.CLOSING

    binding.close(this._handle)
  }

  _destroy(err, cb) {
    if (this._state & constants.state.CLOSING) return cb(err)
    this._state |= constants.state.CLOSING

    this._pendingDestroy = cb

    binding.close(this._handle)
  }

  _continueOpen(err) {
    if (this._pendingOpen === null) return
    const cb = this._pendingOpen
    this._pendingOpen = null
    cb(err)
  }

  _continueWrite(err) {
    if (this._pendingWrite === null) return
    const cb = this._pendingWrite
    this._pendingWrite = null
    this._pendingWriteBatch = null
    cb(err)
  }

  _continueFinal(err) {
    if (this._pendingFinal === null) return
    const cb = this._pendingFinal
    this._pendingFinal = null
    cb(err)
  }

  _continueDestroy() {
    if (this._pendingDestroy === null) return
    const cb = this._pendingDestroy
    this._pendingDestroy = null
    cb(null)
  }

  _reset() {
    this._state = 0

    this._localAddress = null
    this._remoteAddress = null

    binding.reset(this._handle)
  }

  _updateAddresses() {
    try {
      this._localAddress = binding.address(this._handle, true)
    } catch {
      this._localAddress = null
    }

    try {
      this._remoteAddress = binding.address(this._handle, false)
    } catch {
      this._remoteAddress = null
    }
  }

  _onconnect(err) {
    if (err) {
      if (this._addresses !== null) {
        this._errors.push(err)

        if (this._addresses.length > 0) return this._reset()

        err = this._errors.length === 1 ? this._errors[0] : new AggregateError(this._errors)
      }

      this._state &= ~constants.state.CONNECTING

      if (this._pendingOpen) this._continueOpen(err)
      else this.destroy(err)
      return
    }

    if (this._keepAlive) this.setKeepAlive(this._keepAlive, this._keepAliveInitialDelay)
    if (this._noDelay) this.setNoDelay()

    this._updateAddresses()

    this._state |= constants.state.CONNECTED
    this._state &= ~constants.state.CONNECTING
    this._continueOpen()

    this.emit('connect')
  }

  _onaccept() {
    this._updateAddresses()

    this._state |= constants.state.CONNECTED
    this._continueOpen()
  }

  _onreset(err) {
    if (err) {
      this._errors.push(err)
      this.destroy(this._errors.length === 1 ? this._errors[0] : new AggregateError(this._errors))
      return
    }

    this.connect(...this._addresses.shift())
  }

  _onread(err, read) {
    if (this._timer) this._timer.refresh()

    if (err) {
      this.destroy(err)
      return
    }

    if (read === 0) {
      this.push(null)
      if (this._allowHalfOpen === false) this.end()
      return
    }

    const copy = Buffer.allocUnsafe(read)
    copy.set(this._buffer.subarray(0, read))

    if (this.push(copy) === false && this.destroying === false) {
      this._state &= ~constants.state.READING

      binding.pause(this._handle)
    }
  }

  _onwrite(err) {
    if (this._timer) this._timer.refresh()

    this._continueWrite(err)
  }

  _onfinal(err) {
    this._continueFinal(err)
  }

  _onclose() {
    clearTimeout(this._timer)

    this._continueOpen()
    this._continueDestroy()
  }
}

exports.Server = class TCPServer extends EventEmitter {
  constructor(opts = {}, onconnection) {
    if (typeof opts === 'function') {
      onconnection = opts
      opts = {}
    }

    super()

    const {
      readBufferSize = defaultReadBufferSize,
      allowHalfOpen = true,
      keepAlive = false,
      keepAliveInitialDelay = 0,
      noDelay = false,
      pauseOnConnect = false,
      maxConnections = Infinity
    } = opts

    this._state = 0

    this._readBufferSize = readBufferSize
    this._allowHalfOpen = allowHalfOpen
    this._keepAlive = keepAlive
    this._keepAliveInitialDelay = keepAliveInitialDelay
    this._noDelay = noDelay
    this._pauseOnConnect = pauseOnConnect
    this._maxConnections = maxConnections

    this._address = null
    this._connections = new Set()

    this._error = null
    this._handle = null

    if (onconnection) this.on('connection', onconnection)
  }

  get listening() {
    return (this._state & constants.state.BOUND) !== 0
  }

  get closing() {
    return (this._state & constants.state.CLOSING) !== 0
  }

  get connections() {
    return this._connections
  }

  get maxConnections() {
    return this._maxConnections
  }

  set maxConnections(value) {
    this._maxConnections = value
  }

  address() {
    if ((this._state & constants.state.BOUND) === 0) return null

    const { address, family, port } = this._address

    return { address, family: `IPv${family}`, port }
  }

  listen(port = 0, host = 'localhost', backlog = 511, opts = {}, onlistening) {
    if (this._state & constants.state.BINDING || this._state & constants.state.BOUND) {
      throw errors.SERVER_ALREADY_LISTENING('Server is already listening')
    }

    if (this._state & constants.state.CLOSING) {
      throw errors.SERVER_IS_CLOSED('Server is closed')
    }

    if (typeof port === 'function') {
      onlistening = port
      port = 0
    } else if (typeof host === 'function') {
      onlistening = host
      host = 'localhost'
    } else if (typeof backlog === 'function') {
      onlistening = backlog
      backlog = 511
    } else if (typeof opts === 'function') {
      onlistening = opts
      opts = {}
    }

    let family = 0

    if (typeof port === 'object' && port !== null) {
      opts = port || {}
      port = opts.port || 0
      host = opts.host || 'localhost'
      family = opts.family || 0
      backlog = opts.backlog || 511
    }

    if (!host) host = 'localhost'
    if (!backlog) backlog = 511

    validatePort(port)

    this._state |= constants.state.BINDING

    const { lookup = dns.lookup, hints } = opts

    const type = ip.isIP(host)

    if (type === 0) {
      lookup(host, { family, hints }, (err, address, family) => {
        if (this._state & constants.state.CLOSING) return

        this.emit('lookup', err, address, family, host)

        this._state &= ~constants.state.BINDING

        if (err) return this.emit('error', err)

        this.listen(port, address, backlog, { ...opts, family }, onlistening)
      })

      return this
    }

    family = type

    this._handle = binding.init(
      empty,
      this,
      this._onconnection,
      noop,
      noop,
      noop,
      noop,
      noop,
      this._onclose
    )

    if (this._state & constants.state.UNREFED) binding.unref(this._handle)

    try {
      binding.bind(this._handle, port, host, backlog, family)

      this._address = binding.address(this._handle, true)

      this._state |= constants.state.BOUND
      this._state &= ~constants.state.BINDING

      if (onlistening) this.once('listening', onlistening)

      queueMicrotask(() => this.emit('listening'))
    } catch (err) {
      this._error = err

      binding.close(this._handle)
    }

    return this
  }

  close(onclose) {
    if (onclose) this.once('close', onclose)

    if (this._state & constants.state.CLOSING) return this
    this._state |= constants.state.CLOSING

    this._closeMaybe()

    return this
  }

  ref() {
    this._state &= ~constants.state.UNREFED

    if (this._handle !== null) binding.ref(this._handle)

    return this
  }

  unref() {
    this._state |= constants.state.UNREFED

    if (this._handle !== null) binding.unref(this._handle)

    return this
  }

  _closeMaybe() {
    if (this._state & constants.state.CLOSING && this._connections.size === 0) {
      if (this._handle !== null) binding.close(this._handle)
      else queueMicrotask(() => this.emit('close'))
    }
  }

  _onconnection(err) {
    if (err) {
      this.emit('error', err)
      return
    }

    if (this._state & constants.state.CLOSING) return

    const overLimit = this._connections.size >= this._maxConnections

    const socket = new exports.Socket({
      readBufferSize: overLimit ? 0 : this._readBufferSize,
      allowHalfOpen: this._allowHalfOpen,
      eagerOpen: !this._pauseOnConnect
    })

    try {
      binding.accept(this._handle, socket._handle)

      socket._onaccept()

      if (overLimit) {
        const info = {
          localAddress: socket.localAddress,
          localPort: socket.localPort,
          localFamily: socket.localFamily,
          remoteAddress: socket.remoteAddress,
          remotePort: socket.remotePort,
          remoteFamily: socket.remoteFamily
        }

        socket.destroy()

        this.emit('drop', info)
        return
      }

      this._connections.add(socket)

      if (this._keepAlive) socket.setKeepAlive(this._keepAlive, this._keepAliveInitialDelay)
      if (this._noDelay) socket.setNoDelay()

      socket.on('close', () => {
        this._connections.delete(socket)
        this._closeMaybe()
      })

      this.emit('connection', socket)
    } catch (err) {
      socket.destroy()

      this.emit('error', err)
    }
  }

  _onclose() {
    const err = this._error

    this._state &= ~constants.state.BINDING
    this._state &= ~constants.state.BOUND
    this._error = null
    this._handle = null
    this._address = null

    if (err) this.emit('error', err)
    else this.emit('close')
  }
}

exports.constants = constants
exports.errors = errors

exports.isIP = ip.isIP
exports.isIPv4 = ip.isIPv4
exports.isIPv6 = ip.isIPv6

exports.createConnection = function createConnection(port, host, opts, onconnect) {
  if (typeof host === 'function') {
    onconnect = host
    host = 'localhost'
  } else if (typeof opts === 'function') {
    onconnect = opts
    opts = {}
  }

  if (typeof port === 'object' && port !== null) {
    opts = port || {}
    port = opts.port || 0
    host = opts.host || 'localhost'
  }

  return new exports.Socket(opts).connect(port, host, opts, onconnect)
}

// For Node.js compatibility
exports.connect = exports.createConnection

exports.createServer = function createServer(opts, onconnection) {
  return new exports.Server(opts, onconnection)
}

exports.socketpair = function socketpair() {
  return binding.socketpair()
}

function validatePort(port) {
  if (typeof port !== 'number') {
    throw errors.INVALID_PORT(`Port must be a number, got ${typeof port}`)
  }

  if (!Number.isInteger(port) || port < 0 || port > 0xffff) {
    throw errors.INVALID_PORT(`Port must be an integer between 0 and 65535, got ${port}`)
  }
}

function noop() {}
module.exports = {
  state: {
    CONNECTING: 0x1,
    CONNECTED: 0x2,
    BINDING: 0x4,
    BOUND: 0x8,
    READING: 0x10,
    CLOSING: 0x20,
    UNREFED: 0x40
  }
}
module.exports = class TCPError extends Error {
  constructor(msg, fn = TCPError, code = fn.name) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'TCPError'
  }

  static SOCKET_ALREADY_CONNECTED(msg) {
    return new TCPError(msg, TCPError.SOCKET_ALREADY_CONNECTED)
  }

  static SERVER_ALREADY_LISTENING(msg) {
    return new TCPError(msg, TCPError.SERVER_ALREADY_LISTENING)
  }

  static SERVER_IS_CLOSED(msg) {
    return new TCPError(msg, TCPError.SERVER_IS_CLOSED)
  }

  static INVALID_HOST(msg = 'Unrecognizable host format') {
    return new TCPError(msg, TCPError.INVALID_HOST)
  }

  static INVALID_PORT(msg) {
    return new TCPError(msg, TCPError.INVALID_PORT)
  }
}
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

const v4Seg = '(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])'
const v4Str = `(${v4Seg}[.]){3}${v4Seg}`
const IPv4Pattern = new RegExp(`^${v4Str}$`)

const v6Seg = '(?:[0-9a-fA-F]{1,4})'
const IPv6Pattern = new RegExp(
  '^(' +
    `(?:${v6Seg}:){7}(?:${v6Seg}|:)|` +
    `(?:${v6Seg}:){6}(?:${v4Str}|:${v6Seg}|:)|` +
    `(?:${v6Seg}:){5}(?::${v4Str}|(:${v6Seg}){1,2}|:)|` +
    `(?:${v6Seg}:){4}(?:(:${v6Seg}){0,1}:${v4Str}|(:${v6Seg}){1,3}|:)|` +
    `(?:${v6Seg}:){3}(?:(:${v6Seg}){0,2}:${v4Str}|(:${v6Seg}){1,4}|:)|` +
    `(?:${v6Seg}:){2}(?:(:${v6Seg}){0,3}:${v4Str}|(:${v6Seg}){1,5}|:)|` +
    `(?:${v6Seg}:){1}(?:(:${v6Seg}){0,4}:${v4Str}|(:${v6Seg}){1,6}|:)|` +
    `(?::((?::${v6Seg}){0,5}:${v4Str}|(?::${v6Seg}){1,7}|:))` +
    ')(%[0-9a-zA-Z-.:]{1,})?$'
)

const isIPv4 = (exports.isIPv4 = function isIPv4(host) {
  return IPv4Pattern.test(host)
})

const isIPv6 = (exports.isIPv6 = function isIPv6(host) {
  return IPv6Pattern.test(host)
})

exports.isIP = function isIP(host) {
  if (isIPv4(host)) return 4
  if (isIPv6(host)) return 6
  return 0
}
{
  "name": "bare-tcp",
  "version": "2.5.4",
  "description": "Native TCP sockets for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./constants": "./lib/constants.js",
    "./errors": "./lib/errors.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-tcp.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-tcp/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-tcp#readme",
  "engines": {
    "bare": ">=1.16.0"
  },
  "dependencies": {
    "bare-dns": "^2.0.4",
    "bare-events": "^2.5.4",
    "bare-stream": "^2.6.4"
  },
  "devDependencies": {
    "bare-pipe": "^4.1.5",
    "brittle": "^3.5.0",
    "cmake-bare": "^1.1.6",
    "lunte": "^1.6.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "bare-pipe": "*"
  },
  "peerDependenciesMeta": {
    "bare-pipe": {
      "optional": true
    }
  }
}
module.exports = require.addon()
const { Duplex, Writable } = require('bare-stream')
const binding = require('./binding')
const constants = require('./lib/constants')
const errors = require('./lib/errors')

const defaultReadBufferSize = 65536

const context = binding.context()

exports.Socket = class TLSSocket extends Duplex {
  constructor(socket, opts = {}) {
    const {
      isServer = false,
      cert = null,
      key = null,
      host = null,
      rejectUnauthorized = true,
      ca = null,
      alpnProtocols = null,
      eagerOpen = true,
      allowHalfOpen = true,
      readBufferSize = defaultReadBufferSize
    } = opts

    if (!isServer && rejectUnauthorized && !host) {
      throw new TypeError("'host' is required for client sockets when 'rejectUnauthorized' is true")
    }

    super({ eagerOpen })

    this._state = 0

    this._socket = socket
    this._allowHalfOpen = allowHalfOpen

    this._pendingOpen = null
    this._pendingWrite = null
    this._pendingDestroy = null

    this._reading = Buffer.alloc(readBufferSize)
    this._buffer = []
    this._buffered = 0

    this._ondata = this._ondata.bind(this)
    this._ondrain = this._ondrain.bind(this)
    this._onend = this._onend.bind(this)
    this._onclose = this._onclose.bind(this)
    this._onerror = this._onerror.bind(this)

    socket.on('close', this._onclose).on('error', this._onerror)

    let alpn = null

    if (alpnProtocols && alpnProtocols.length > 0) {
      const parts = []

      for (const protocol of alpnProtocols) {
        const encoded = Buffer.from(protocol)

        if (encoded.byteLength === 0 || encoded.byteLength > 255) {
          throw new RangeError('ALPN protocol name must be 1-255 bytes')
        }

        parts.push(Buffer.of(encoded.byteLength), encoded)
      }

      alpn = Buffer.concat(parts)
    }

    try {
      this._handle = binding.init(
        context,
        isServer,
        cert,
        key,
        host,
        rejectUnauthorized,
        ca,
        alpn,
        this,
        this._onread,
        this._onwrite
      )
    } catch (err) {
      this._handle = null

      this.destroy(err)
    }
  }

  get socket() {
    return this._socket
  }

  get encrypted() {
    return true
  }

  get alpnProtocol() {
    return this._handle ? binding.alpnProtocol(this._handle) : null
  }

  _onconnect() {
    this._state |= constants.state.CONNECTED

    this.emit('connect')

    const cb = this._pendingOpen
    this._pendingOpen = null
    cb(null)
  }

  _ondata(data) {
    this._buffer.push(data)
    this._buffered += data.byteLength

    while (this._buffered > 0) {
      if (this._state & constants.state.CONNECTED) {
        let read
        try {
          read = binding.read(this._handle, this._reading)
        } catch (err) {
          return this.destroy(errors.from(err))
        }

        if (read < 0) break

        if (read === 0) {
          this.push(null)
          if (this._allowHalfOpen === false) this.end()
          return
        }

        const copy = Buffer.allocUnsafe(read)
        copy.set(this._reading.subarray(0, read))

        this.push(copy)
      } else {
        try {
          if (binding.handshake(this._handle)) this._onconnect()
          else break
        } catch (err) {
          err = errors.from(err)

          // Defer so any alert the handshake wrote to the underlying socket
          // gets a chance to flush before we tear it down.
          queueMicrotask(() => {
            if (this._pendingOpen) {
              const cb = this._pendingOpen
              this._pendingOpen = null
              cb(err)
            } else {
              this.destroy(err)
            }
          })
          return
        }
      }
    }
  }

  _ondrain() {
    if (this._pendingWrite === null) return
    const cb = this._pendingWrite
    this._pendingWrite = null
    cb(null)
  }

  _onend() {
    this.push(null)
  }

  _onclose() {
    this._socket.off('close', this._onclose).off('error', this._onerror)

    if (this._pendingDestroy) {
      const cb = this._pendingDestroy
      this._pendingDestroy = null
      cb()
    }
  }

  _onerror(err) {
    if (this._pendingOpen) {
      const cb = this._pendingOpen
      this._pendingOpen = null
      cb(err)
    } else if (this._pendingDestroy) {
      const cb = this._pendingDestroy
      this._pendingDestroy = null
      cb(err)
    } else {
      this.destroy(err)
    }
  }

  _onread(data) {
    if (this._buffered < data.byteLength) return 0

    let offset = 0
    let remaining = data.byteLength

    while (remaining > 0) {
      const chunk = this._buffer[0]

      if (chunk.byteLength <= remaining) {
        data.set(chunk, offset)

        offset += chunk.byteLength
        remaining -= chunk.byteLength

        this._buffer.shift()
      } else {
        data.set(chunk.subarray(0, remaining), offset)

        this._buffer[0] = chunk.subarray(remaining)

        remaining = 0
      }
    }

    this._buffered -= data.byteLength

    return data.byteLength
  }

  _onwrite(data) {
    this._socket.write(Buffer.from(data.slice()))

    return data.byteLength
  }

  _attach() {
    if (this._state & constants.state.ATTACHED) return
    this._state |= constants.state.ATTACHED

    this._socket.on('data', this._ondata).on('drain', this._ondrain).on('end', this._onend)
  }

  _detach() {
    if (!(this._state & constants.state.ATTACHED)) return
    this._state &= ~constants.state.ATTACHED

    this._socket.off('data', this._ondata).off('drain', this._ondrain).off('end', this._onend)
  }

  _open(cb) {
    this._pendingOpen = cb
    this._attach()

    try {
      if (binding.handshake(this._handle)) this._onconnect()
    } catch (err) {
      this._pendingOpen = null

      cb(errors.from(err))
    }
  }

  _write(data, encoding, cb) {
    try {
      binding.write(this._handle, data)

      if (Writable.isBackpressured(this._socket)) {
        this._pendingWrite = cb
      } else {
        cb(null)
      }
    } catch (err) {
      this._pendingWrite = null

      cb(errors.from(err))
    }
  }

  _final(cb) {
    try {
      binding.shutdown(this._handle)

      cb(null)
    } catch (err) {
      cb(err)
    }

    this._socket.end()
  }

  _predestroy() {
    if (this._handle) {
      this._detach()

      binding.destroy(this._handle)
      this._handle = null
    }

    this._socket.destroy()
  }

  _destroy(err, cb) {
    if (this._handle) {
      this._detach()

      binding.destroy(this._handle)
      this._handle = null
    }

    if (err) this._socket.destroy()

    if (this._socket.destroyed) cb(err)
    else this._pendingDestroy = cb
  }
}

exports.TLSSocket = exports.Socket // For Node.js compatibility

exports.constants = constants
exports.errors = errors

const net = require('./net')

exports.createConnection = net.createConnection
exports.createServer = net.createServer

// For Node.js compatibility
exports.connect = exports.createConnection
module.exports = {
  state: {
    CONNECTED: 0x1,
    ATTACHED: 0x2
  }
}
module.exports = class TLSError extends Error {
  constructor(msg, code, fn = TLSError) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'TLSError'
  }

  static from(err) {
    return new TLSError(err.message, err.code, TLSError.from)
  }
}
const EventEmitter = require('bare-events')
const net = require('bare-net')
const tls = require('bare-tls')

class TLSNetSocket extends tls.Socket {
  ref() {
    this.socket.ref()
  }

  unref() {
    this.socket.unref()
  }
}

class TLSNetServer extends EventEmitter {
  constructor(opts = {}, onconnection) {
    if (typeof opts === 'function') {
      onconnection = opts
      opts = {}
    }

    const {
      cert = null,
      key = null,
      host = null,
      rejectUnauthorized = true,
      ca = null,
      alpnProtocols = null,
      eagerOpen = true,
      allowHalfOpen = true
    } = opts

    super()

    this._opts = {
      cert,
      key,
      host,
      rejectUnauthorized,
      ca,
      alpnProtocols,
      eagerOpen,
      allowHalfOpen
    }

    this._server = net.createServer(opts)
    this._server
      .on('listening', this._onlistening.bind(this))
      .on('connection', this._onconnection.bind(this))
      .on('error', this._onerror.bind(this))
      .on('close', this._onclose.bind(this))

    if (onconnection) this.on('connection', onconnection)
  }

  get listening() {
    return this._server.listening
  }

  address() {
    return this._server.address()
  }

  listen(...args) {
    this._server.listen(...args)
    return this
  }

  close(onclose) {
    if (onclose) this.once('close', onclose)
    this._server.close()
  }

  ref() {
    this._server.ref()
  }

  unref() {
    this._server.unref()
  }

  _onlistening() {
    this.emit('listening')
  }

  _onconnection(socket) {
    this.emit('connection', new TLSNetSocket(socket, { ...this._opts, isServer: true }))
  }

  _onerror(err) {
    this.emit('error', err)
  }

  _onclose() {
    this.emit('close')
  }
}

exports.createConnection = function createConnection(...args) {
  let opts = {}
  let onconnect

  if (typeof args[0] === 'string') {
    // createConnection(path[, onconnect])
    opts.path = args[0]
    onconnect = args[1]
  } else if (typeof args[0] === 'number') {
    // createConnection(port[, host][, onconnect])
    opts.port = args[0]

    if (typeof args[1] === 'function') {
      onconnect = args[1]
    } else {
      opts.host = args[1]
      onconnect = args[2]
    }
  } else {
    // createConnection(opts[, onconnect])
    opts = args[0] || {}
    onconnect = args[1]
  }

  if (!opts.host && !opts.path) opts.host = 'localhost'

  return new TLSNetSocket(net.createConnection(opts, onconnect), opts)
}

exports.createServer = function createServer(opts, onconnection) {
  return new TLSNetServer(opts, onconnection)
}
{
  "name": "bare-tls",
  "version": "3.1.8",
  "description": "Transport Layer Security (TLS) streams for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    },
    "./errors": {
      "types": "./lib/errors.d.ts",
      "default": "./lib/errors.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "net.js",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-tls.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-tls/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-tls#readme",
  "engines": {
    "bare": ">=1.7.0"
  },
  "dependencies": {
    "bare-net": "^2.0.1",
    "bare-stream": "^2.6.4"
  },
  "devDependencies": {
    "bare-events": "^2.6.0",
    "bare-fs": "^4.0.2",
    "brittle": "^3.1.1",
    "cmake-bare": "^1.1.6",
    "cmake-fetch": "^1.0.0",
    "lunte": "^1.6.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = require.addon()
const { Readable, Writable } = require('bare-stream')
const Signal = require('bare-signals')
const binding = require('./binding')
const constants = require('./lib/constants')

const defaultReadBufferSize = 65536
const empty = Buffer.alloc(0)

exports.ReadStream = class TTYReadStream extends Readable {
  constructor(fd, opts = {}) {
    super()

    const { readBufferSize = defaultReadBufferSize, allowHalfOpen = true } = opts

    this._fd = fd
    this._state = 0
    this._allowHalfOpen = allowHalfOpen
    this._buffer = Buffer.alloc(readBufferSize)

    this._pendingDestroy = null

    this._handle = binding.init(fd, this._buffer, this, noop, this._onread, this._onclose)
  }

  get fd() {
    return this._fd
  }

  get isTTY() {
    return true
  }

  setMode(mode) {
    binding.setMode(this._handle, mode)
    return this
  }

  setRawMode(enabled) {
    return this.setMode(enabled ? constants.mode.RAW : constants.mode.NORMAL)
  }

  _read() {
    if ((this._state & constants.state.READING) === 0) {
      this._state |= constants.state.READING

      binding.resume(this._handle)
    }
  }

  _predestroy() {
    if (this._state & constants.state.CLOSING) return
    this._state |= constants.state.CLOSING

    binding.close(this._handle)
  }

  _destroy(err, cb) {
    if (this._state & constants.state.CLOSING) return cb(err)
    this._state |= constants.state.CLOSING

    this._pendingDestroy = cb

    binding.close(this._handle)
  }

  _continueDestroy() {
    if (this._pendingDestroy === null) return
    const cb = this._pendingDestroy
    this._pendingDestroy = null
    cb(null)
  }

  _onread(err, read) {
    if (err) {
      this.destroy(err)
      return
    }

    if (read === 0) {
      this.push(null)
      if (this._allowHalfOpen === false) this.end()
      return
    }

    const copy = Buffer.allocUnsafe(read)
    copy.set(this._buffer.subarray(0, read))

    if (this.push(copy) === false && this.destroying === false) {
      this._state &= ~constants.state.READING

      binding.pause(this._handle)
    }
  }

  _onclose() {
    this._handle = null

    this._continueDestroy()
  }
}

exports.WriteStream = class TTYWriteStream extends Writable {
  constructor(fd, opts = {}) {
    super()

    this._fd = fd
    this._state = 0
    this._size = null

    this._pendingWrite = null
    this._pendingWriteBatch = null
    this._pendingDestroy = null

    this._handle = binding.init(fd, empty, this, this._onwrite, noop, this._onclose)

    this._size = this.getWindowSize()

    if (TTYWriteStream._streams.size === 0) TTYWriteStream._resize.start()

    TTYWriteStream._streams.add(this)
  }

  get fd() {
    return this._fd
  }

  get isTTY() {
    return true
  }

  get columns() {
    return this._size[0]
  }

  get rows() {
    return this._size[1]
  }

  getWindowSize() {
    return binding.getWindowSize(this._handle)
  }

  _writev(batch, cb) {
    this._pendingWrite = cb
    this._pendingWriteBatch = batch

    try {
      binding.writev(
        this._handle,
        batch.map(({ chunk }) => chunk)
      )
    } catch (err) {
      this._continueWrite(err)
    }
  }

  _predestroy() {
    if (this._state & constants.state.CLOSING) return
    this._state |= constants.state.CLOSING

    binding.close(this._handle)

    TTYWriteStream._streams.delete(this)

    if (TTYWriteStream._streams.size === 0) TTYWriteStream._resize.stop()
  }

  _destroy(err, cb) {
    if (this._state & constants.state.CLOSING) return cb(err)
    this._state |= constants.state.CLOSING

    this._pendingDestroy = cb

    binding.close(this._handle)

    TTYWriteStream._streams.delete(this)

    if (TTYWriteStream._streams.size === 0) TTYWriteStream._resize.stop()
  }

  _continueWrite(err) {
    if (this._pendingWrite === null) return
    const cb = this._pendingWrite
    this._pendingWrite = null
    this._pendingWriteBatch = null
    cb(err)
  }

  _continueDestroy() {
    if (this._pendingDestroy === null) return
    const cb = this._pendingDestroy
    this._pendingDestroy = null
    cb(null)
  }

  _onwrite(err) {
    this._continueWrite(err)
  }

  _onclose() {
    this._handle = null

    this._continueDestroy()
  }

  _onresize() {
    this._size = this.getWindowSize()

    this.emit('resize')
  }

  static _streams = new Set()

  static _resize = new Signal('SIGWINCH')
}

exports.constants = constants

exports.isTTY = binding.isTTY

exports.isatty = exports.isTTY // For Node.js compatibility

exports.WriteStream._resize
  .on('signal', () => {
    for (const stream of exports.WriteStream._streams) {
      stream._onresize()
    }
  })
  .unref()

function noop() {}
const binding = require('../binding')

module.exports = exports = {
  mode: {
    NORMAL: binding.MODE_NORMAL,
    RAW: binding.MODE_RAW,
    IO: binding.MODE_IO || 0
  },

  state: {
    READING: 0x1,
    CLOSING: 0x2
  }
}

/** @deprecated Use `mode.NORMAL` */
exports.MODE_NORMAL = exports.mode.NORMAL
/** @deprecated Use `mode.RAW` */
exports.MODE_RAW = exports.mode.RAW
/** @deprecated Use `mode.IO` */
exports.MODE_IO = exports.mode.IO
{
  "name": "bare-tty",
  "version": "5.1.2",
  "description": "Native TTY streams for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./constants": "./lib/constants.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-tty.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-tty/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-tty#readme",
  "engines": {
    "bare": ">=1.16.0"
  },
  "dependencies": {
    "bare-events": "^2.2.0",
    "bare-signals": "^5.0.0",
    "bare-stream": "^2.0.0"
  },
  "devDependencies": {
    "brittle": "^3.2.1",
    "cmake-bare": "^1.1.6",
    "lunte": "^1.8.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = require.addon()
const binding = require('./binding')

const t = binding.constants

class Type {
  constructor(type) {
    this._type = type
  }

  isUndefined() {
    return this._type === t.UNDEFINED
  }

  isNull() {
    return this._type === t.NULL
  }

  isBoolean() {
    return this._type === t.BOOLEAN
  }

  isNumber() {
    return (this._type & 0xff) === t.NUMBER
  }

  isInt32() {
    return (this._type & (0xff | t.INT32)) === (t.NUMBER | t.INT32)
  }

  isUint32() {
    return (this._type & (0xff | t.UINT32)) === (t.NUMBER | t.UINT32)
  }

  isString() {
    return this._type === t.STRING
  }

  isSymbol() {
    return this._type === t.SYMBOL
  }

  isObject() {
    return (this._type & 0xff) === t.OBJECT
  }

  isArray() {
    return this._type === (t.OBJECT | t.ARRAY)
  }

  isArguments() {
    return this._type === (t.OBJECT | t.ARGUMENTS)
  }

  isDate() {
    return this._type === (t.OBJECT | t.DATE)
  }

  isRegExp() {
    return this._type === (t.OBJECT | t.REGEXP)
  }

  isError() {
    return this._type === (t.OBJECT | t.ERROR)
  }

  isPromise() {
    return this._type === (t.OBJECT | t.PROMISE)
  }

  isProxy() {
    return this._type === (t.OBJECT | t.PROXY)
  }

  isGenerator() {
    return this._type === (t.OBJECT | t.GENERATOR)
  }

  isMap() {
    return this._type === (t.OBJECT | t.MAP)
  }

  isSet() {
    return this._type === (t.OBJECT | t.SET)
  }

  isWeakMap() {
    return this._type === (t.OBJECT | t.WEAK_MAP)
  }

  isWeakSet() {
    return this._type === (t.OBJECT | t.WEAK_SET)
  }

  isWeakRef() {
    return this._type === (t.OBJECT | t.WEAK_REF)
  }

  isArrayBuffer() {
    return this._type === (t.OBJECT | t.ARRAYBUFFER)
  }

  isSharedArrayBuffer() {
    return this._type === (t.OBJECT | t.SHAREDARRAYBUFFER)
  }

  isTypedArray() {
    return (this._type & 0xffff) === (t.OBJECT | t.TYPEDARRAY)
  }

  isInt8Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT8ARRAY)
  }

  isUint8Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT8ARRAY)
  }

  isUint8ClampedArray() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT8CLAMPEDARRAY)
  }

  isInt16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT16ARRAY)
  }

  isUint16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT16ARRAY)
  }

  isInt32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT32ARRAY)
  }

  isUint32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT32ARRAY)
  }

  isFloat16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT16ARRAY)
  }

  isFloat32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT32ARRAY)
  }

  isFloat64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT64ARRAY)
  }

  isBigInt64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.BIGINT64ARRAY)
  }

  isBigUint64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.BIGUINT64ARRAY)
  }

  isDataView() {
    return this._type === (t.OBJECT | t.DATAVIEW)
  }

  isModuleNamespace() {
    return this._type === (t.OBJECT | t.MODULE_NAMESPACE)
  }

  isFunction() {
    return (this._type & 0xff) === t.FUNCTION
  }

  isAsyncFunction() {
    return (
      (this._type & (0xff | t.ASYNC_FUNCTION)) ===
      (t.FUNCTION | t.ASYNC_FUNCTION)
    )
  }

  isGeneratorFunction() {
    return (
      (this._type & (0xff | t.GENERATOR_FUNCTION)) ===
      (t.FUNCTION | t.GENERATOR_FUNCTION)
    )
  }

  isExternal() {
    return this._type === t.EXTERNAL
  }

  isBigInt() {
    return this._type === t.BIGINT
  }
}

module.exports = exports = function type(value) {
  switch (typeof value) {
    case 'undefined':
      return new Type(t.UNDEFINED)
    case 'boolean':
      return new Type(t.BOOLEAN)
    case 'number':
      return new Type(
        Number.isSafeInteger(value) ? binding.type(value) : t.NUMBER
      )
    case 'string':
      return new Type(t.STRING)
    case 'symbol':
      return new Type(t.SYMBOL)
    case 'object':
      return new Type(value === null ? t.NULL : binding.type(value))
    case 'function':
      return new Type(binding.type(value))
    case 'bigint':
      return new Type(t.BIGINT)
  }
}

exports.createTag = function createTag(...components) {
  const tag = new Uint32Array(4)
  for (let i = 0; i < 4; i++) tag[i] = components[i] || 0
  return tag
}

exports.addTag = function addTag(object, tag) {
  binding.addTag(object, tag)
}

exports.checkTag = function checkTag(object, tag) {
  return binding.checkTag(object, tag)
}
{
  "name": "bare-type",
  "version": "1.1.0",
  "description": "Cross-realm type predicates for Bare",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-type.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-type/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-type#readme",
  "engines": {
    "bare": ">=1.2.0"
  },
  "devDependencies": {
    "brittle": "^3.4.0",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
module.exports = require.addon()
const path = require('bare-path')
const binding = require('./binding')
const errors = require('./lib/errors')
const URLSearchParams = require('./lib/url-search-params')

const kind = Symbol.for('bare.url.kind')

const isWindows = Bare.platform === 'win32'

class URL {
  static get [kind]() {
    return 0 // Compatibility version
  }

  constructor(input, base, opts = {}) {
    if (arguments.length === 0) throw errors.INVALID_URL()

    input = String(input)

    if (base !== undefined) base = String(base)

    this._components = new Uint32Array(8)

    this._parse(input, base, opts.throw !== false)

    if (this._href) this._params = new URLSearchParams(this.search, this)
  }

  get [kind]() {
    return URL[kind]
  }

  // https://url.spec.whatwg.org/#dom-url-href

  get href() {
    return this._href
  }

  set href(value) {
    this._update(value)

    this._params._parse(this.search)
  }

  // https://url.spec.whatwg.org/#dom-url-protocol

  get protocol() {
    return this._slice(0, this._components[0]) + ':'
  }

  set protocol(value) {
    this._update(this._replace(value.replace(/:+$/, ''), 0, this._components[0]))
  }

  // https://url.spec.whatwg.org/#dom-url-username

  get username() {
    return this._slice(this._components[0] + 3 /* :// */, this._components[1])
  }

  set username(value) {
    if (cannotHaveCredentialsOrPort(this)) {
      return
    }

    if (this.username === '') value += '@'

    this._update(this._replace(value, this._components[0] + 3 /* :// */, this._components[1]))
  }

  // https://url.spec.whatwg.org/#dom-url-password

  get password() {
    return this._href.slice(this._components[1] + 1 /* : */, this._components[2] - 1 /* @ */)
  }

  set password(value) {
    if (cannotHaveCredentialsOrPort(this)) {
      return
    }

    let start = this._components[1] + 1 /* : */
    let end = this._components[2] - 1 /* @ */

    if (this.password === '') {
      value = ':' + value
      start--
    }

    if (this.username === '') {
      value += '@'
      end++
    }

    this._update(this._replace(value, start, end))
  }

  // https://url.spec.whatwg.org/#dom-url-host

  get host() {
    return this._slice(this._components[2], this._components[5])
  }

  set host(value) {
    if (hasOpaquePath(this)) {
      return
    }

    this._update(
      this._replace(value, this._components[2], this._components[value.includes(':') ? 5 : 3])
    )
  }

  // https://url.spec.whatwg.org/#dom-url-hostname

  get hostname() {
    return this._slice(this._components[2], this._components[3])
  }

  set hostname(value) {
    if (hasOpaquePath(this)) {
      return
    }

    this._update(this._replace(value, this._components[2], this._components[3]))
  }

  // https://url.spec.whatwg.org/#dom-url-port

  get port() {
    return this._slice(this._components[3] + 1 /* : */, this._components[5])
  }

  set port(value) {
    if (cannotHaveCredentialsOrPort(this)) {
      return
    }

    let start = this._components[3] + 1 /* : */

    if (this.port === '') {
      value = ':' + value
      start--
    }

    this._update(this._replace(value, start, this._components[5]))
  }

  // https://url.spec.whatwg.org/#dom-url-pathname

  get pathname() {
    return this._slice(this._components[5], this._components[6] - 1 /* ? */)
  }

  set pathname(value) {
    if (hasOpaquePath(this)) {
      return
    }

    if (value[0] !== '/' && value[0] !== '\\') {
      value = '/' + value
    }

    this._update(this._replace(value, this._components[5], this._components[6] - 1 /* ? */))
  }

  // https://url.spec.whatwg.org/#dom-url-search

  get search() {
    return this._slice(this._components[6] - 1 /* ? */, this._components[7] - 1 /* # */)
  }

  set search(value) {
    if (value && value[0] !== '?') value = '?' + value

    this._update(
      this._replace(value, this._components[6] - 1 /* ? */, this._components[7] - 1 /* # */)
    )

    this._params._parse(this.search)
  }

  // https://url.spec.whatwg.org/#dom-url-searchparams

  get searchParams() {
    return this._params
  }

  // https://url.spec.whatwg.org/#dom-url-hash

  get hash() {
    return this._slice(this._components[7] - 1 /* # */)
  }

  set hash(value) {
    if (value && value[0] !== '#') value = '#' + value

    this._update(this._replace(value, this._components[7] - 1 /* # */))
  }

  toString() {
    return this._href
  }

  toJSON() {
    return this._href
  }

  [Symbol.for('bare.inspect')]() {
    return {
      __proto__: { constructor: URL },

      href: this.href,
      protocol: this.protocol,
      username: this.username,
      password: this.password,
      host: this.host,
      hostname: this.hostname,
      port: this.port,
      pathname: this.pathname,
      search: this.search,
      searchParams: this.searchParams,
      hash: this.hash
    }
  }

  _slice(start, end = this._href.length) {
    return this._href.slice(start, end)
  }

  _replace(replacement, start, end = this._href.length) {
    return this._slice(0, start) + replacement + this._slice(end)
  }

  _parse(input, base, shouldThrow) {
    try {
      this._href = binding.parse(
        String(input),
        base ? String(base) : null,
        this._components,
        shouldThrow
      )
    } catch (err) {
      if (err instanceof TypeError) throw err

      throw errors.INVALID_URL(`Invalid URL '${input}'`, input)
    }
  }

  _update(input) {
    try {
      this._parse(input, null, true)
    } catch (err) {
      if (err instanceof TypeError) throw err
    }
  }
}

module.exports = exports = URL

// https://url.spec.whatwg.org/#url-opaque-path
function hasOpaquePath(url) {
  return url.pathname[0] !== '/'
}

// https://url.spec.whatwg.org/#cannot-have-a-username-password-port
function cannotHaveCredentialsOrPort(url) {
  return url.hostname === '' || url.protocol === 'file:'
}

exports.URL = URL
exports.URLSearchParams = URLSearchParams

exports.errors = errors

exports.isURL = function isURL(value) {
  if (value instanceof URL) return true

  return typeof value === 'object' && value !== null && value[kind] === URL[kind]
}

exports.isURLSearchParams = URLSearchParams.isURLSearchParams

// https://url.spec.whatwg.org/#dom-url-parse
exports.parse = function parse(input, base) {
  const url = new URL(input, base, { throw: false })
  return url._href ? url : null
}

// https://url.spec.whatwg.org/#dom-url-canparse
exports.canParse = function canParse(input, base) {
  return binding.canParse(String(input), base ? String(base) : null)
}

exports.fileURLToPath = function fileURLToPath(url) {
  if (typeof url === 'string') {
    url = new URL(url)
  }

  if (url.protocol !== 'file:') {
    throw errors.INVALID_URL_SCHEME('The URL must use the file: protocol')
  }

  if (isWindows) {
    if (/%2f|%5c/i.test(url.pathname)) {
      throw errors.INVALID_FILE_URL_PATH(
        'The file: URL path must not include encoded \\ or / characters'
      )
    }
  } else {
    if (url.hostname) {
      throw errors.INVALID_FILE_URL_HOST("The file: URL host must be 'localhost' or empty")
    }

    if (/%2f/i.test(url.pathname)) {
      throw errors.INVALID_FILE_URL_PATH('The file: URL path must not include encoded / characters')
    }
  }

  if (/%00/i.test(url.pathname)) {
    throw errors.INVALID_FILE_URL_PATH('The file: URL path must not include encoded NUL characters')
  }

  const pathname = path.normalize(decodeURIComponent(url.pathname))

  if (isWindows) {
    if (url.hostname) return '\\\\' + url.hostname + pathname

    const letter = pathname.charCodeAt(1) | 0x20

    if (letter < 0x61 /* a */ || letter > 0x7a /* z */ || pathname.charCodeAt(2) !== 0x3a /* : */) {
      throw errors.INVALID_FILE_URL_PATH('The file: URL path must be absolute')
    }

    return pathname.slice(1)
  }

  return pathname
}

exports.pathToFileURL = function pathToFileURL(pathname) {
  let resolved = path.resolve(pathname)

  if (pathname[pathname.length - 1] === '/') {
    resolved += '/'
  } else if (isWindows && pathname[pathname.length - 1] === '\\') {
    resolved += '\\'
  }

  resolved = resolved
    .replaceAll('%', '%25') // Must be first
    .replaceAll('#', '%23')
    .replaceAll('?', '%3f')
    .replaceAll('\n', '%0a')
    .replaceAll('\r', '%0d')
    .replaceAll('\t', '%09')

  if (!isWindows) {
    resolved = resolved.replaceAll('\\', '%5c')
  }

  return new URL('file:' + resolved)
}

exports.format = function format(parts) {
  const { protocol, auth, host, hostname, port, pathname, search, query, hash, slashes } = parts

  let result = ''

  if (typeof protocol === 'string') {
    result += protocol

    if (protocol[protocol.length - 1] !== ':') {
      result += ':'
    }

    if (slashes === true || /https?|ftp|gopher|file/.test(protocol)) {
      result += '//'
    }
  }

  if (typeof auth === 'string') {
    if (host || hostname) result += auth + '@'
  }

  if (typeof host === 'string') result += host
  else {
    result += hostname

    if (port) result += ':' + port
  }

  if (typeof pathname === 'string' && pathname !== '') {
    if (pathname[0] !== '/') result += '/'
    result += pathname
  }

  if (typeof search === 'string') {
    if (search[0] !== '?') result += '?'
    result += search
  } else if (typeof query === 'object' && query !== null) {
    result += '?' + new URLSearchParams(query)
  }

  if (typeof hash === 'string') {
    if (hash[0] !== '#') result += '#'
    result += hash
  }

  return result
}
module.exports = class URLError extends Error {
  constructor(msg, fn = URLError, code = fn.name) {
    super(`${code}: ${msg}`)

    this.code = code

    if (Error.captureStackTrace) Error.captureStackTrace(this, fn)
  }

  get name() {
    return 'URLError'
  }

  static INVALID_URL(msg, input) {
    const err = new URLError(msg, URLError.INVALID_URL)

    err.input = input

    return err
  }

  static INVALID_URL_SCHEME(msg = 'Invalid URL') {
    return new URLError(msg, URLError.INVALID_URL_SCHEME)
  }

  static INVALID_FILE_URL_HOST(msg = 'Invalid file: URL host') {
    return new URLError(msg, URLError.INVALID_FILE_URL_HOST)
  }

  static INVALID_FILE_URL_PATH(msg = 'Invalid file: URL path') {
    return new URLError(msg, URLError.INVALID_FILE_URL_PATH)
  }
}
const binding = require('../binding')

const kind = Symbol.for('bare.url.search-params.kind')

class URLSearchParams {
  static _urls = new WeakMap()

  static get [kind]() {
    return 0 // Compatibility version
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-urlsearchparams
  constructor(init, url = null) {
    this._params = new Map()

    if (url) URLSearchParams._urls.set(this, url)

    if (typeof init === 'string') {
      this._parse(init)
    } else if (init) {
      for (const [name, value] of typeof init[Symbol.iterator] === 'function'
        ? init
        : Object.entries(init)) {
        this.append(name, value)
      }
    }
  }

  get [kind]() {
    return URLSearchParams[kind]
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-size
  get size() {
    let size = 0

    for (const values of this._params.values()) size += values.length

    return size
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-append
  append(name, value = null) {
    if (value === null) return

    let list = this._params.get(name)

    if (list === undefined) {
      list = []
      this._params.set(name, list)
    }

    list.push(value)

    this._update()
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-delete
  delete(name, value = null) {
    if (value === null) this._params.delete(name)
    else {
      let list = this._params.get(name)

      if (list === undefined) return

      list = list.filter((found) => found !== value)

      if (list.length === 0) this._params.delete(name)
      else this._params.set(name, list)
    }

    this._update()
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-get
  get(name) {
    const list = this._params.get(name)

    if (list === undefined) return null

    return list[0]
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-getall
  getAll(name) {
    const list = this._params.get(name)

    if (list === undefined) return []

    return Array.from(list)
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-has
  has(name, value = null) {
    const list = this._params.get(name)

    if (list === undefined) return false

    if (value === null) return true

    return list.includes(value)
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-set
  set(name, value = null) {
    if (value === null) this._params.delete(name)
    else this._params.set(name, [value])

    this._update()
  }

  toString() {
    return this._serialize()
  }

  toJSON() {
    return [...this]
  }

  *[Symbol.iterator]() {
    for (const [name, values] of this._params) {
      for (const value of values) yield [name, value]
    }
  }

  [Symbol.for('bare.inspect')]() {
    const object = {
      __proto__: { constructor: URLSearchParams }
    }

    for (const [name, values] of this._params) {
      if (values.length === 1) object[name] = values[0]
      else object[name] = values
    }

    return object
  }

  // https://url.spec.whatwg.org/#concept-urlsearchparams-update
  _update() {
    const url = URLSearchParams._urls.get(this)

    if (url === undefined) return

    url.search = this._serialize()
  }

  // https://url.spec.whatwg.org/#concept-urlencoded-parser
  _parse(input) {
    if (input[0] === '?') input = input.substring(1)

    this._params = new Map()

    for (let sequence of input.split('&')) {
      if (sequence.length === 0) continue

      sequence = sequence.replace(/\+/g, ' ')

      let i = sequence.indexOf('=')
      if (i === -1) i = sequence.length

      const name = decodeURIComponent(sequence.substring(0, i))
      const value = decodeURIComponent(sequence.substring(i + 1, sequence.length))

      let list = this._params.get(name)

      if (list === undefined) {
        list = []
        this._params.set(name, list)
      }

      list.push(value)
    }
  }

  // https://url.spec.whatwg.org/#concept-urlencoded-serializer
  _serialize() {
    const pairs = []

    for (const [name, values] of this._params) {
      for (const value of values) pairs.push(String(name), String(value))
    }

    return binding.serializeSearchParams(pairs)
  }
}

module.exports = exports = URLSearchParams

exports.isURLSearchParams = function isURLSearchParams(value) {
  if (value instanceof URLSearchParams) return true

  return typeof value === 'object' && value !== null && value[kind] === URLSearchParams[kind]
}
{
  "name": "bare-url",
  "version": "2.5.1",
  "description": "WHATWG URL implementation for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "global.js",
    "global.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-url.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-url/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-url",
  "dependencies": {
    "bare-path": "^3.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "cmake-bare": "^1.8.1",
    "cmake-fetch": "^1.0.0",
    "lunte": "^1.6.0",
    "prettier": "^3.3.3",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = require.addon()
const { Transform, Writable } = require('bare-stream')
const binding = require('./binding')
const constants = require('./lib/constants')
const errors = require('./lib/errors')

exports.constants = constants
exports.errors = errors

const MAX_OUTPUT_LENGTH = (Buffer.constants && Buffer.constants.MAX_LENGTH) || 0x100000000

class ZlibState {
  constructor(mode, opts = {}) {
    const {
      flush = constants.Z_NO_FLUSH,
      finishFlush = constants.Z_FINISH,
      chunkSize = constants.Z_DEFAULT_CHUNK,
      level = constants.Z_DEFAULT_LEVEL,
      windowBits = constants.Z_DEFAULT_WINDOWBITS,
      memLevel = constants.Z_DEFAULT_MEMLEVEL,
      strategy = constants.Z_DEFAULT_STRATEGY,
      maxOutputLength = MAX_OUTPUT_LENGTH
    } = opts

    this._mode = mode

    this._flushMode = flush
    this._finishFlushMode = finishFlush
    this._allocations = []

    this._maxOutputLength = maxOutputLength
    this._outputLength = 0

    this._buffer = Buffer.allocUnsafe(chunkSize)

    this._handle = binding.init(
      this._mode,
      this._buffer,
      level,
      windowBits,
      memLevel,
      strategy,
      this,
      this._onalloc,
      this._onfree
    )
  }

  _onalloc(size) {
    const buffer = Buffer.allocUnsafe(size)

    const view = new Uint32Array(buffer.buffer, buffer.byteOffset, buffer.byteLength / 4)

    view[0] = this._allocations.push(view) - 1

    return buffer
  }

  _onfree(id) {
    const last = this._allocations.pop()

    if (last[0] !== id) {
      this._allocations[(last[0] = id)] = last
    }
  }

  reset() {
    this._outputLength = 0

    binding.reset(this._handle)
  }

  *transform(data) {
    binding.load(this._handle, data)

    let available
    do {
      try {
        available = binding.transform(this._handle, this._flushMode)
      } catch (err) {
        throw errors[err.code](err.message)
      }

      const read = this._buffer.length - available

      if (read) {
        this._outputLength += read

        if (this._outputLength > this._maxOutputLength) {
          throw errors.LIMIT_EXCEEDED(
            `Output length exceeded maxOutputLength of ${this._maxOutputLength} bytes`
          )
        }

        const copy = Buffer.allocUnsafe(read)
        copy.set(this._buffer.subarray(0, read))

        yield copy
      }
    } while (available === 0)
  }

  *flush() {
    let available
    do {
      try {
        available = binding.transform(this._handle, this._finishFlushMode)
      } catch (err) {
        throw errors[err.code](err.message)
      }

      const read = this._buffer.length - available

      if (read) {
        this._outputLength += read

        if (this._outputLength > this._maxOutputLength) {
          throw errors.LIMIT_EXCEEDED(
            `Output length exceeded maxOutputLength of ${this._maxOutputLength} bytes`
          )
        }

        const copy = Buffer.allocUnsafe(read)
        copy.set(this._buffer.subarray(0, read))

        yield copy
      }
    } while (available === 0)

    try {
      binding.end(this._handle)
    } catch (err) {
      throw errors[err.code](err.message)
    }

    this._handle = null
  }
}

class ZlibStream extends Transform {
  constructor(mode, opts = {}) {
    const { flush, ...streamOpts } = opts

    super(streamOpts)

    this._state = new ZlibState(mode, opts)
  }

  async flush(mode = constants.Z_FULL_FLUSH, cb) {
    if (typeof mode === 'function') {
      cb = mode
      mode = constants.Z_FULL_FLUSH
    }

    const previousMode = this._state._flushMode

    this._state._flushMode = mode

    await Writable.drained(this)

    this._state._flushMode = previousMode

    if (cb) cb(null) // For Node.js compatibility
  }

  reset() {
    if (this._state === null) {
      throw errors.STREAM_CLOSED('Stream has already closed')
    }

    this._state.reset()
  }

  _transform(data, encoding, cb) {
    let err = null

    try {
      for (const chunk of this._state.transform(data)) {
        this.push(chunk)
      }
    } catch (e) {
      err = e
    }

    cb(err)
  }

  _flush(cb) {
    let err = null

    try {
      for (const chunk of this._state.flush()) {
        this.push(chunk)
      }
    } catch (e) {
      err = e
    }

    this._state = null

    cb(err)
  }
}

function readAsBuffer(stream, buffer, cb) {
  const chunks = []

  stream.on('data', ondata).on('end', onend).on('error', onerror).end(buffer)

  function ondata(chunk) {
    chunks.push(chunk)
  }

  function onend() {
    cb(null, chunks.length === 1 ? chunks[0] : Buffer.concat(chunks))
  }

  function onerror(err) {
    stream.off('end', onend)
    cb(err)
  }
}

function transformToBuffer(mode, buffer, opts) {
  if (typeof buffer === 'string') buffer = Buffer.from(buffer)

  const state = new ZlibState(mode, opts)
  const chunks = []

  for (const chunk of state.transform(buffer)) {
    chunks.push(chunk)
  }

  for (const chunk of state.flush()) {
    chunks.push(chunk)
  }

  return chunks.length === 1 ? chunks[0] : Buffer.concat(chunks)
}

exports.Deflate = class ZlibDeflateStream extends ZlibStream {
  constructor(opts) {
    super(binding.DEFLATE, opts)
  }
}

exports.createDeflate = function createDeflate(opts) {
  return new exports.Deflate(opts)
}

exports.deflate = function deflate(buffer, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  readAsBuffer(new exports.Deflate(opts), buffer, cb)
}

exports.deflateSync = function deflateSync(buffer, opts) {
  return transformToBuffer(binding.DEFLATE, buffer, opts)
}

exports.Inflate = class ZlibInflateStream extends ZlibStream {
  constructor(opts) {
    super(binding.INFLATE, opts)
  }
}

exports.createInflate = function createInflate(opts) {
  return new exports.Inflate(opts)
}

exports.inflate = function inflate(buffer, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  readAsBuffer(new exports.Inflate(opts), buffer, cb)
}

exports.inflateSync = function inflateSync(buffer, opts) {
  return transformToBuffer(binding.INFLATE, buffer, opts)
}

exports.DeflateRaw = class ZlibDeflateRawStream extends ZlibStream {
  constructor(opts) {
    super(binding.DEFLATE_RAW, opts)
  }
}

exports.createDeflateRaw = function createDeflateRaw(opts) {
  return new exports.DeflateRaw(opts)
}

exports.deflateRaw = function deflateRaw(buffer, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  readAsBuffer(new exports.DeflateRaw(opts), buffer, cb)
}

exports.deflateRawSync = function deflateRawSync(buffer, opts) {
  return transformToBuffer(binding.DEFLATE_RAW, buffer, opts)
}

exports.InflateRaw = class ZlibInflateRawStream extends ZlibStream {
  constructor(opts) {
    super(binding.INFLATE_RAW, opts)
  }
}

exports.createInflateRaw = function createInflateRaw(opts) {
  return new exports.InflateRaw(opts)
}

exports.inflateRaw = function inflateRaw(buffer, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  readAsBuffer(new exports.InflateRaw(opts), buffer, cb)
}

exports.inflateRawSync = function inflateRawSync(buffer, opts) {
  return transformToBuffer(binding.INFLATE_RAW, buffer, opts)
}

exports.Gzip = class ZlibGzipStream extends ZlibStream {
  constructor(opts) {
    super(binding.GZIP, opts)
  }
}

exports.createGzip = function createGzip(opts) {
  return new exports.Gzip(opts)
}

exports.gzip = function gzip(buffer, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  readAsBuffer(new exports.Gzip(opts), buffer, cb)
}

exports.gzipSync = function gzipSync(buffer, opts) {
  return transformToBuffer(binding.GZIP, buffer, opts)
}

exports.Gunzip = class ZlibGunzipStream extends ZlibStream {
  constructor(opts) {
    super(binding.GUNZIP, opts)
  }
}

exports.createGunzip = function createGunzip(opts) {
  return new exports.Gunzip(opts)
}

exports.gunzip = function gunzip(buffer, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  readAsBuffer(new exports.Gunzip(opts), buffer, cb)
}

exports.gunzipSync = function gunzipSync(buffer, opts) {
  return transformToBuffer(binding.GUNZIP, buffer, opts)
}
const binding = require('../binding')

module.exports = binding.constants
module.exports = class ZlibError extends Error {
  constructor(msg, code, fn = ZlibError) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'ZlibError'
  }

  static STREAM_CLOSED(msg) {
    return new ZlibError(msg, 'STREAM_CLOSED', ZlibError.STREAM_CLOSED)
  }

  static STREAM_ERROR(msg) {
    return new ZlibError(msg, 'STREAM_ERROR', ZlibError.STREAM_ERROR)
  }

  static DATA_ERROR(msg) {
    return new ZlibError(msg, 'DATA_ERROR', ZlibError.DATA_ERROR)
  }

  static MEM_ERROR(msg) {
    return new ZlibError(msg, 'MEM_ERROR', ZlibError.MEM_ERROR)
  }

  static BUF_ERROR(msg) {
    return new ZlibError(msg, 'BUF_ERROR', ZlibError.BUF_ERROR)
  }

  static VERSION_ERROR(msg) {
    return new ZlibError(msg, 'VERSION_ERROR', ZlibError.VERSION_ERROR)
  }

  static UNKNOWN_ERROR(msg) {
    return new ZlibError(msg, 'UNKNOWN_ERROR', ZlibError.UNKNOWN_ERROR)
  }

  static LIMIT_EXCEEDED(msg) {
    return new ZlibError(msg, 'LIMIT_EXCEEDED', ZlibError.LIMIT_EXCEEDED)
  }
}
{
  "name": "bare-zlib",
  "version": "1.4.1",
  "description": "Stream-based zlib bindings for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    },
    "./errors": {
      "types": "./lib/errors.d.ts",
      "default": "./lib/errors.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-zlib.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-zlib/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-zlib",
  "dependencies": {
    "bare-stream": "^2.0.0"
  },
  "devDependencies": {
    "bare-fs": "^3.0.0",
    "brittle": "^3.5.0",
    "cmake-bare": "^1.1.7",
    "cmake-fetch": "^1.0.0",
    "lunte": "^1.6.0",
    "prettier": "^3.5.3",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "bare-buffer": "*"
  },
  "peerDependenciesMeta": {
    "bare-buffer": {
      "optional": true
    }
  }
}
const { EventEmitter } = require('events')
const sodium = require('sodium-universal')
const crypto = require('hypercore-crypto')
const b4a = require('b4a')
const c = require('compact-encoding')

const {
  Invite,
  ResponsePayload,
  InviteRequest,
  InviteResponse,
  InviteData,
  InviteReceipt,
  PersistedRequest,
  AuthData
} = require('./lib/messages')

const {
  PAIRING_REJECTED,
  INVITE_USED,
  INVITE_EXPIRED
} = require('./lib/errors')

const [
  NS_SIGNATURE,
  NS_TOKEN,
  NS_INVITE_ID,
  NS_REQUEST_ID,
  NS_SESSION,
  NS_SESSION_KEY,
  NS_ENCRYPT,
  NS_NONCE
] = crypto.namespace('blind-pairing', 8)

class CandidateRequest extends EventEmitter {
  constructor(invite, userData, opts = {}) {
    super()

    if (b4a.isBuffer(invite)) {
      invite = c.decode(Invite, invite)
    }

    this.discoveryKey = invite.discoveryKey
    this.seed = invite.seed

    this.keyPair = crypto.keyPair(this.seed)
    this.inviteId = deriveInviteId(this.keyPair.publicKey)
    this.userData = userData

    this.token = deriveToken(this.keyPair.publicKey, userData)
    this.session = opts.session || createSessionToken(this.token)
    this.id = deriveRequestId(this.session)

    this.payload = createAuth(this.userData, this.keyPair, this.session)

    this._encoded = null

    // set in reply
    this.auth = null
  }

  static from(buf) {
    const info = c.decode(PersistedRequest, buf)
    const { seed, discoveryKey, userData } = info
    const request = new CandidateRequest({ discoveryKey, seed }, userData)

    // clear completed request
    if (info.key) {
      request.key = info.key
      request.token = null
      request.payload = null
    }

    return request
  }

  handleResponse(payload) {
    if (b4a.isBuffer(payload)) {
      payload = this._decodeResponse(payload)
    }

    try {
      this._openResponse(payload)
    } catch (err) {
      this.emit('rejected', err)
      return null
    }

    this._onAccept()

    return this.auth
  }

  _openResponse(payload) {
    try {
      const response = openReply(
        payload,
        this.payload.session,
        this.keyPair.publicKey
      )
      this.response = c.decode(ResponsePayload, response)
    } catch (e) {
      throw new Error('Could not decrypt reply.')
    }

    const { status, key, encryptionKey, additional } = this.response

    if (status !== 0) {
      switch (status) {
        case 1:
          throw PAIRING_REJECTED()

        case 2:
          throw INVITE_USED()

        case 3:
          throw INVITE_EXPIRED()
      }
    }

    if (b4a.compare(crypto.discoveryKey(key), this.discoveryKey)) {
      throw new Error('Invite response does not match discoveryKey')
    }

    if (
      additional &&
      !crypto.verify(
        additional.data,
        additional.signature,
        this.keyPair.publicKey
      )
    ) {
      throw new Error('Additional data failed verification')
    }

    this.auth = {
      key,
      encryptionKey,
      data: additional ? additional.data : null
    }
  }

  _onAccept() {
    this.emit('accepted', this.auth)
    this.destroy()
  }

  _decodeResponse(buf) {
    try {
      const { payload } = c.decode(InviteResponse, buf)
      return payload
    } catch {
      throw new Error('Could not decode response.')
    }
  }

  destroy() {
    this.token = null
    this.payload = null

    this.emit('destroyed')
  }

  encode() {
    if (!this._encoded) this._encoded = c.encode(InviteRequest, this)
    return this._encoded
  }
}

class MemberRequest {
  constructor(inviteId, requestData) {
    this.inviteId = inviteId
    this.requestData = requestData

    this._opened = false
    this._confirmed = false
    this._denied = false

    // set by transport
    this.discoveryKey = null

    // set in open
    this.publicKey = null
    this.userData = null
    this.session = null
    this.id = null
    this.receipt = null

    // set in confirm/respond
    this._payload = null
    this.response = null
  }

  static from(req) {
    if (b4a.isBuffer(req)) {
      return MemberRequest.from(c.decode(InviteRequest, req))
    }

    return new MemberRequest(req.inviteId, req.payload)
  }

  confirm({ key, encryptionKey, additional }) {
    if (this._confirmed || this._denied || !this._opened) return
    this._confirmed = true

    const payload = c.encode(ResponsePayload, {
      status: 0,
      key,
      encryptionKey,
      additional
    })
    this._payload = createReply(payload, this.session, this.publicKey)

    this._respond()
  }

  deny({ status = 1 } = {}) {
    if (this._confirmed || this._denied) return
    this._denied = true

    if (!status) return

    const payload = c.encode(ResponsePayload, {
      status,
      key: null,
      encryptionKey: null,
      additional: null
    })
    this._payload = createReply(payload, this.session, this.publicKey)

    this._respond()
  }

  respond() {
    return {
      id: this.id,
      payload: this._payload
    }
  }

  _respond() {
    this.response = c.encode(InviteResponse, this.respond())
  }

  open(publicKey) {
    if (this._opened && b4a.equals(this.publicKey, publicKey))
      return this.userData

    try {
      this.receipt = openAuth(this.requestData, publicKey)
      const { userData, session } = c.decode(InviteReceipt, this.receipt)

      this.userData = userData
      this.session = session
      this.token = deriveToken(publicKey, userData)
      this.id = deriveRequestId(this.session)
    } catch (e) {
      throw new Error('Failed to open invite with provided key')
    }

    this.publicKey = publicKey
    this._opened = true

    return this.userData
  }
}

module.exports.CandidateRequest = CandidateRequest
module.exports.MemberRequest = MemberRequest
module.exports.createInvite = createInvite
module.exports.decodeInvite = decodeInvite
module.exports.verifyReceipt = verifyReceipt
module.exports.createReceipt = createReceipt
module.exports.Invite = Invite

function createReceipt(invite, userData) {
  const req = new CandidateRequest(invite, userData) // yolo, refactor
  const receipt = openAuth(req.payload, req.keyPair.publicKey)
  return { id: deriveInviteId(req.keyPair.publicKey), receipt }
}

function verifyReceipt(receipt, publicKey) {
  if (b4a.isBuffer(receipt)) {
    receipt = c.decode(InviteReceipt, receipt)
  }

  const { session, signature, userData } = receipt
  const signData = c.encode(AuthData, { userData, session })

  if (!verifySignature(signData, signature, publicKey)) return null

  return userData
}

function deriveInviteId(publicKey) {
  return crypto.hash([NS_INVITE_ID, publicKey])
}

function deriveKey(publicKey) {
  const out = b4a.allocUnsafe(
    sodium.crypto_aead_xchacha20poly1305_ietf_KEYBYTES
  )
  return crypto.hash([NS_ENCRYPT, publicKey], out)
}

function deriveNonce(publicKey, sessionToken) {
  const out = b4a.allocUnsafe(
    sodium.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES
  )
  return crypto.hash([NS_NONCE, publicKey, sessionToken], out)
}

function deriveToken(publicKey, userData) {
  return crypto.hash([NS_TOKEN, publicKey, userData])
}

function createSessionToken(token) {
  return crypto.hash([NS_SESSION, token])
}

function deriveRequestId(sessionToken) {
  return crypto.hash([NS_REQUEST_ID, sessionToken])
}

function createInvite(key, opts = {}) {
  const {
    discoveryKey = crypto.discoveryKey(key),
    expires = 0,
    seed = crypto.randomBytes(32),
    sensitive = false,
    data,
    testInvitation = false,
    additionalNodes
  } = opts

  const keyPair = crypto.keyPair(seed)
  const additional = data
    ? {
        data,
        signature: crypto.sign(data, keyPair.secretKey)
      }
    : null

  return {
    id: deriveInviteId(keyPair.publicKey),
    invite: c.encode(Invite, {
      seed,
      discoveryKey,
      expires,
      sensitive,
      testInvitation,
      additionalNodes
    }),
    seed,
    publicKey: keyPair.publicKey,
    additional,
    discoveryKey,
    expires,
    sensitive,
    testInvitation
  }
}

function decodeInvite(invite) {
  const data = c.decode(Invite, invite)
  return {
    id: deriveInviteId(crypto.keyPair(data.seed).publicKey),
    ...data
  }
}

function encrypt(data, nonce, secretKey) {
  const output = b4a.allocUnsafe(
    data.byteLength + sodium.crypto_aead_xchacha20poly1305_ietf_ABYTES
  )
  sodium.crypto_aead_xchacha20poly1305_ietf_encrypt(
    output,
    data,
    nonce,
    null,
    nonce,
    secretKey
  )
  return output
}

function decrypt(data, nonce, secretKey) {
  const output = b4a.allocUnsafe(
    data.byteLength - sodium.crypto_aead_xchacha20poly1305_ietf_ABYTES
  )
  sodium.crypto_aead_xchacha20poly1305_ietf_decrypt(
    output,
    null,
    data,
    nonce,
    nonce,
    secretKey
  )
  return output
}

function createAuth(userData, invitationKeyPair, session) {
  const secret = deriveKey(invitationKeyPair.publicKey)

  const nonce = deriveNonce(invitationKeyPair.publicKey, session)
  const signData = c.encode(AuthData, { userData, session })
  const signature = createSignature(signData, invitationKeyPair.secretKey)

  const inviteData = c.encode(InviteData, { userData, signature })
  const data = encrypt(inviteData, nonce, secret)

  return {
    session,
    data
  }
}

function openAuth(payload, invitationKey) {
  const secret = deriveKey(invitationKey)

  const { session, data } = payload

  const nonce = deriveNonce(invitationKey, session)

  let plaintext
  try {
    plaintext = decrypt(data, nonce, secret)
  } catch {
    // todo stronger check
    throw new Error('Decryption failed.')
  }

  const { userData, signature } = c.decode(InviteData, plaintext)
  const receipt = { session, signature, userData }

  if (!verifyReceipt(receipt, invitationKey)) {
    throw new Error('Invalid reply')
  }

  return c.encode(InviteReceipt, { session, signature, userData })
}

function createReply(payload, sessionToken, invitationKey) {
  const sessionKey = crypto.hash([NS_SESSION_KEY, invitationKey, sessionToken])
  const secret = deriveKey(sessionKey)
  const nonce = deriveNonce(sessionKey, sessionToken)

  return encrypt(payload, nonce, secret)
}

function openReply(data, sessionToken, invitationKey) {
  const sessionKey = crypto.hash([NS_SESSION_KEY, invitationKey, sessionToken])
  const secret = deriveKey(sessionKey)
  const nonce = deriveNonce(sessionKey, sessionToken)

  return decrypt(data, nonce, secret)
}

function createSignature(data, secretKey) {
  const signature = b4a.allocUnsafe(sodium.crypto_sign_BYTES)
  const namespaced = b4a.allocUnsafe(32 + data.byteLength)

  namespaced.set(NS_SIGNATURE, 0)
  namespaced.set(data, 32)

  sodium.crypto_sign_detached(signature, namespaced, secretKey)

  return signature
}

function verifySignature(data, signature, publicKey) {
  const namespaced = b4a.allocUnsafe(32 + data.byteLength)

  namespaced.set(NS_SIGNATURE, 0)
  namespaced.set(data, 32)

  return sodium.crypto_sign_verify_detached(signature, namespaced, publicKey)
}
module.exports = class PairingError extends Error {
  constructor(msg, code, fn = PairingError) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'PairingError'
  }

  static PAIRING_REJECTED(msg = 'Pairing was rejected') {
    return new PairingError(
      msg,
      'PAIRING_REJECTED',
      PairingError.PAIRING_REJECTED
    )
  }

  static INVITE_USED(msg = 'Invite has been used') {
    return new PairingError(msg, 'INVITE_USED', PairingError.INVITE_USED)
  }

  static INVITE_EXPIRED(msg = 'Invite has expireds') {
    return new PairingError(msg, 'INVITE_EXPIRED', PairingError.INVITE_EXPIRED)
  }
}
const { isBogon } = require('bogon')
const c = require('compact-encoding')

const DHTNodes = c.array(c.ipv4Address)

const Invite = {
  preencode(state, i) {
    state.end++ // version
    state.end++ // flags
    c.fixed32.preencode(state, i.seed)
    if (i.discoveryKey) c.fixed32.preencode(state, i.discoveryKey)
    if (i.expires) c.uint32.preencode(state, Math.floor(i.expires / 1000)) // store as secs
    if (i.additionalNodes && Array.isArray(i.additionalNodes))
      DHTNodes.preencode(
        state,
        i.additionalNodes.filter((node) => !isBogon(node.host))
      )
  },
  encode(state, i) {
    c.uint.encode(state, 1) // version
    c.uint.encode(
      state,
      (i.discoveryKey ? 1 : 0) |
        (i.expires ? 2 : 0) |
        (i.sensitive ? 4 : 0) |
        (i.testInvitation ? 8 : 0) |
        (i.additionalNodes && Array.isArray(i.additionalNodes) ? 16 : 0)
    )
    c.fixed32.encode(state, i.seed)
    if (i.discoveryKey) c.fixed32.encode(state, i.discoveryKey)
    if (i.expires) c.uint32.encode(state, Math.floor(i.expires / 1000))
    if (i.additionalNodes && Array.isArray(i.additionalNodes))
      DHTNodes.encode(
        state,
        i.additionalNodes.filter((node) => !isBogon(node.host))
      )
  },
  decode(state) {
    const version = c.uint.decode(state)
    if (version !== 1) {
      throw new Error('Unknown invite version')
    }

    const flags = c.uint.decode(state)

    return {
      seed: c.fixed32.decode(state),
      discoveryKey: flags & 1 ? c.fixed32.decode(state) : null,
      expires: flags & 2 ? c.uint32.decode(state) * 1000 : 0,
      sensitive: (flags & 4) !== 0,
      testInvitation: (flags & 8) !== 0,
      additionalNodes: flags & 16 ? DHTNodes.decode(state) : null
    }
  }
}

const RequestPayload = {
  preencode(state, p) {
    c.optionalBuffer.preencode(state, p.session)
    c.optionalBuffer.preencode(state, p.data)
  },
  encode(state, p) {
    c.optionalBuffer.encode(state, p.session)
    c.optionalBuffer.encode(state, p.data)
  },
  decode(state) {
    return {
      session: c.optionalBuffer.decode(state),
      data: c.optionalBuffer.decode(state)
    }
  }
}

const ResponseStatus = c.uint

const AdditionalData = {
  preencode(state, m) {
    c.optionalBuffer.preencode(state, m.data)
    c.fixed64.preencode(state, m.signature)
  },
  encode(state, m) {
    c.optionalBuffer.encode(state, m.data)
    c.fixed64.encode(state, m.signature)
  },
  decode(state) {
    return {
      data: c.optionalBuffer.decode(state),
      signature: c.fixed64.decode(state)
    }
  }
}

const ResponsePayload = {
  preencode(state, p) {
    ResponseStatus.preencode(state, p.status)
    if (p.status !== 0) return

    let flags = 0
    if (p.encryptionKey) flags |= 1
    if (p.additional) flags |= 2
    c.uint.preencode(state, flags) // flags

    c.fixed32.preencode(state, p.key)
    if (p.encryptionKey) c.fixed32.preencode(state, p.encryptionKey)
    if (p.additional) AdditionalData.preencode(state, p.additional)
  },
  encode(state, p) {
    ResponseStatus.encode(state, p.status)
    if (p.status !== 0) return

    let flags = 0
    if (p.encryptionKey) flags |= 1
    if (p.additional) flags |= 2
    c.uint.encode(state, flags)

    c.fixed32.encode(state, p.key)
    if (p.encryptionKey) c.fixed32.encode(state, p.encryptionKey)
    if (p.additional) AdditionalData.encode(state, p.additional)
  },
  decode(state) {
    const status = ResponseStatus.decode(state)

    if (status !== 0) {
      return {
        status,
        key: null,
        encryptionKey: null,
        additional: null
      }
    }

    const flags = c.uint.decode(state)
    const key = c.fixed32.decode(state)
    const encryptionKey = (flags & 1) !== 0 ? c.fixed32.decode(state) : null
    const additional = (flags & 2) !== 0 ? AdditionalData.decode(state) : null

    return {
      status: 0,
      key,
      encryptionKey,
      additional
    }
  }
}

const InviteRequest = {
  preencode(state, i) {
    c.fixed32.preencode(state, i.inviteId)
    RequestPayload.preencode(state, i.payload)
  },
  encode(state, i) {
    c.fixed32.encode(state, i.inviteId)
    RequestPayload.encode(state, i.payload)
  },
  decode(state) {
    return {
      inviteId: c.fixed32.decode(state),
      payload: RequestPayload.decode(state)
    }
  }
}

const InviteResponse = {
  preencode(state, i) {
    c.fixed32.preencode(state, i.id)
    c.optionalBuffer.preencode(state, i.payload)
  },
  encode(state, i) {
    c.fixed32.encode(state, i.id)
    c.optionalBuffer.encode(state, i.payload)
  },
  decode(state) {
    return {
      id: c.fixed32.decode(state),
      payload: c.optionalBuffer.decode(state)
    }
  }
}

const InviteData = {
  preencode(state, i) {
    c.fixed64.preencode(state, i.signature)
    c.optionalBuffer.preencode(state, i.userData)
  },
  encode(state, i) {
    c.fixed64.encode(state, i.signature)
    c.optionalBuffer.encode(state, i.userData)
  },
  decode(state) {
    return {
      signature: c.fixed64.decode(state),
      userData: c.optionalBuffer.decode(state)
    }
  }
}

const InviteReceipt = {
  preencode(state, i) {
    c.fixed32.preencode(state, i.session)
    c.fixed64.preencode(state, i.signature)
    c.optionalBuffer.preencode(state, i.userData)
  },
  encode(state, i) {
    c.fixed32.encode(state, i.session)
    c.fixed64.encode(state, i.signature)
    c.optionalBuffer.encode(state, i.userData)
  },
  decode(state) {
    return {
      session: c.fixed32.decode(state),
      signature: c.fixed64.decode(state),
      userData: c.optionalBuffer.decode(state)
    }
  }
}

const AuthData = {
  preencode(state, i) {
    c.optionalBuffer.preencode(state, i.session)
    c.optionalBuffer.preencode(state, i.userData)
  },
  encode(state, i) {
    c.optionalBuffer.encode(state, i.session)
    c.optionalBuffer.encode(state, i.userData)
  },
  decode(state) {
    return {
      session: c.optionalBuffer.decode(state),
      userData: c.optionalBuffer.decode(state)
    }
  }
}

module.exports = {
  Invite,
  ResponsePayload,
  InviteRequest,
  InviteResponse,
  InviteData,
  InviteReceipt,
  AuthData
}
{
  "name": "blind-pairing-core",
  "version": "2.10.1",
  "description": "Core blind pairing module",
  "main": "index.js",
  "files": [
    "index.js",
    "lib/**.js"
  ],
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test/*.js"
  },
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/blind-pairing-core.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/blind-pairing-core/issues"
  },
  "homepage": "https://github.com/holepunchto/blind-pairing-core#readme",
  "dependencies": {
    "b4a": "^1.6.4",
    "bare-events": "^2.5.0",
    "bogon": "^1.1.0",
    "compact-encoding": "^3.0.0",
    "hypercore-crypto": "^3.4.0",
    "sodium-universal": "^5.0.1",
    "tiny-buffer-map": "^1.1.1"
  },
  "devDependencies": {
    "brittle": "^3.2.1",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  }
}
// https://ipinfo.io/bogon

const b4a = require('b4a')
const c = require('compact-encoding')

module.exports = exports = function isBogon (ip) {
  return isBogonIP(ensureBuffer(ip))
}

exports.isBogon = exports

exports.isPrivate = function isPrivate (ip) {
  return isPrivateIP(ensureBuffer(ip))
}

exports.isReserved = function isReserved (ip) {
  return isReservedIP(ensureBuffer(ip))
}

function isBogonIP (ip) {
  return isPrivateIP(ip) || isReservedIP(ip)
}

function isPrivateIP (ip) {
  return ip.byteLength === 4 ? isPrivateIPv4(ip) : false // IPv6 has no private IPs
}

function isPrivateIPv4 (ip) {
  return (
    // 10.0.0.0/8  Private-use networks
    (ip[0] === 10) ||
    // 100.64.0.0/10 Carrier-grade NAT
    (ip[0] === 100 && ip[1] >= 64 && ip[1] <= 127) ||
    // 127.0.0.0/8 Loopback + Name collision occurrence (127.0.53.53)
    (ip[0] === 127) ||
    // 169.254.0.0/16  Link local
    (ip[0] === 169 && ip[1] === 254) ||
    // 172.16.0.0/12 Private-use networks
    (ip[0] === 172 && ip[1] >= 16 && ip[1] <= 31) ||
    // 192.168.0.0/16  Private-use networks
    (ip[0] === 192 && ip[1] === 168)
  )
}

function isReservedIP (ip) {
  return ip.byteLength === 4 ? isReservedIPv4(ip) : isReservedIPv6(ip)
}

function isReservedIPv4 (ip) {
  return (
    // 0.0.0.0/8 "This" network
    (ip[0] === 0) ||
    // 192.0.0.0/24  IETF protocol assignments
    (ip[0] === 192 && ip[1] === 0 && ip[2] === 0) ||
    // 192.0.2.0/24  TEST-NET-1
    (ip[0] === 192 && ip[1] === 0 && ip[2] === 2) ||
    // 198.18.0.0/15 Network interconnect device benchmark testing
    (ip[0] === 198 && ip[1] >= 18 && ip[1] <= 19) ||
    // 198.51.100.0/24 TEST-NET-2
    (ip[0] === 198 && ip[1] === 51 && ip[2] === 100) ||
    // 203.0.113.0/24  TEST-NET-3
    (ip[0] === 203 && ip[1] === 0 && ip[2] === 113) ||
    // 224.0.0.0/4 Multicast
    (ip[0] >= 224 && ip[0] <= 239) ||
    // 240.0.0.0/4 Reserved for future use
    (ip[0] >= 240) ||
    // 255.255.255.255/32
    (ip[0] === 255 && ip[1] === 255 && ip[2] === 255 && ip[3] === 255)
  )
}

function isReservedIPv6 (ip) {
  return (
    // ::/128 Node-scope unicast unspecified address
    // ::1/128 Node-scope unicast loopback address
    (
      ip[0] === 0 && ip[1] === 0 && ip[2] === 0 && ip[3] === 0 && ip[4] === 0 &&
      ip[5] === 0 && ip[6] === 0 && ip[7] === 0 && ip[8] === 0 && ip[9] === 0 &&
      ip[10] === 0 && ip[11] === 0 && ip[12] === 0 && ip[13] === 0 && ip[14] === 0 &&
      ip[15] <= 1
    ) ||
    // ::ffff:0:0/96 IPv4-mapped addresses
    // ::/96 IPv4-compatible addresses
    (
      ip[0] === 0 && ip[1] === 0 && ip[2] === 0 && ip[3] === 0 && ip[4] === 0 &&
      ip[5] === 0 && ip[6] === 0 && ip[7] === 0 && ip[8] === 0 && ip[9] === 0 &&
      (ip[10] === 0 || ip[10] === 0xff) &&
      (ip[11] === 0 || ip[11] === 0xff)
    ) ||
    // 100::/64 Remotely triggered black hole addresses
    (ip[0] === 0x01 && ip[1] === 0 && ip[2] === 0 && ip[3] === 0 && ip[4] === 0 && ip[5] === 0 && ip[6] === 0 && ip[7] === 0) ||
    // 2001:10::/28 Overlay routable cryptographic hash identifiers (ORCHID)
    (ip[0] === 0x20 && ip[1] === 0x01 && ip[2] === 0 && ip[3] >= 0x10 && ip[3] <= 0x1f) ||
    // 2001:20::/28 Overlay routable cryptographic hash identifiers version 2 (ORCHIDv2)
    (ip[0] === 0x20 && ip[1] === 0x01 && ip[2] === 0 && ip[3] >= 0x20 && ip[3] <= 0x2f) ||
    // 2001:db8::/32 Documentation prefix
    (ip[0] === 0x20 && ip[1] === 0x01 && ip[2] === 0x0d && ip[3] === 0xb8) ||
    // fc00::/7 Unique local addresses (ULA)
    (ip[0] >= 0xfc && ip[0] <= 0xfd) ||
    // fe80::/10 Link-local unicast
    (ip[0] === 0xfe && ip[1] >= 0x80 && ip[1] <= 0xbf) ||
    // ff00::/8 Multicast
    (ip[0] === 0xff)
  )
}

const state = c.state(0, 0, b4a.allocUnsafe(1 /* family */ + 16))

function ensureBuffer (ip) {
  if (b4a.isBuffer(ip)) return ip

  c.ip.preencode(state, ip)
  c.ip.encode(state, ip)

  const buffer = state.buffer.subarray(1 /* family */, state.end)

  state.start = 0
  state.end = 0

  return buffer
}
{
  "name": "bogon",
  "version": "1.3.0",
  "description": "Check if an IP is a bogon",
  "main": "index.js",
  "scripts": {
    "test": "standard && brittle test.mjs"
  },
  "dependencies": {
    "compact-encoding": "^3.0.0",
    "compact-encoding-net": "^1.2.0"
  },
  "devDependencies": {
    "brittle": "^3.0.4",
    "nanobench": "^2.1.1",
    "standard": "^17.0.0"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/bogon.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/bogon/issues"
  },
  "homepage": "https://github.com/mafintosh/bogon"
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
module.exports = require('bare-events')
{
  "name": "events-universal",
  "version": "1.0.1",
  "description": "Universal wrapper for the Node.js events module",
  "exports": {
    "./package": "./package.json",
    ".": {
      "bare": "./bare.js",
      "react-native": "./react-native.js",
      "default": "./default.js"
    }
  },
  "files": [
    "index.js",
    "default.js",
    "bare.js",
    "react-native.js"
  ],
  "scripts": {
    "test": "prettier . --check"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/events-universal.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/events-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/events-universal#readme",
  "dependencies": {
    "bare-events": "^2.7.0"
  },
  "devDependencies": {
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^1.0.0"
  }
}
module.exports = class FixedFIFO {
  constructor (hwm) {
    if (!(hwm > 0) || ((hwm - 1) & hwm) !== 0) throw new Error('Max size for a FixedFIFO should be a power of two')
    this.buffer = new Array(hwm)
    this.mask = hwm - 1
    this.top = 0
    this.btm = 0
    this.next = null
  }

  clear () {
    this.top = this.btm = 0
    this.next = null
    this.buffer.fill(undefined)
  }

  push (data) {
    if (this.buffer[this.top] !== undefined) return false
    this.buffer[this.top] = data
    this.top = (this.top + 1) & this.mask
    return true
  }

  shift () {
    const last = this.buffer[this.btm]
    if (last === undefined) return undefined
    this.buffer[this.btm] = undefined
    this.btm = (this.btm + 1) & this.mask
    return last
  }

  peek () {
    return this.buffer[this.btm]
  }

  isEmpty () {
    return this.buffer[this.btm] === undefined
  }
}
const FixedFIFO = require('./fixed-size')

module.exports = class FastFIFO {
  constructor (hwm) {
    this.hwm = hwm || 16
    this.head = new FixedFIFO(this.hwm)
    this.tail = this.head
    this.length = 0
  }

  clear () {
    this.head = this.tail
    this.head.clear()
    this.length = 0
  }

  push (val) {
    this.length++
    if (!this.head.push(val)) {
      const prev = this.head
      this.head = prev.next = new FixedFIFO(2 * this.head.buffer.length)
      this.head.push(val)
    }
  }

  shift () {
    if (this.length !== 0) this.length--
    const val = this.tail.shift()
    if (val === undefined && this.tail.next) {
      const next = this.tail.next
      this.tail.next = null
      this.tail = next
      return this.tail.shift()
    }

    return val
  }

  peek () {
    const val = this.tail.peek()
    if (val === undefined && this.tail.next) return this.tail.next.peek()
    return val
  }

  isEmpty () {
    return this.length === 0
  }
}
{
  "name": "fast-fifo",
  "version": "1.3.2",
  "description": "A fast fifo implementation similar to the one powering nextTick in Node.js core",
  "main": "index.js",
  "files": [
    "./index.js",
    "./fixed-size.js"
  ],
  "dependencies": {},
  "devDependencies": {
    "standard": "^17.1.0",
    "brittle": "^3.3.2"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/fast-fifo.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/fast-fifo/issues"
  },
  "homepage": "https://github.com/mafintosh/fast-fifo"
}
// favela SSR gateway — a Bare backend that reads a roster of DIDs over P2P (atproto-did-peer), folds
// them into the appview index, and SERVES the views SERVER-RENDERED (no-JS HTML at real URLs) plus the
// JSON APIs as progressive enhancement. This is the "P2P-less window" (DESIGN §2.6/§4.1): a browser
// with a URL reads the community — no install, no JS, SEO-able, RSS/Atom for free. atcute is NOT in
// the backend (it serves HTML/JSON — atcute is UI-side per §4.1). Run: `bare bin/favela-web.js`.
//
// Currently single-viewer (the node operator's configured roster/labelers/mutes). The per-viewer DID
// session layer (browser sub-key attested to the DID + profile-entered StateBase community links) is
// the next increment — the render layer already takes a `viewer`.
import '../lib/bare-globals.js'
import http from 'bare-http1'
// Every outbound HTTP call in this daemon goes through the BOUNDED fetch, never bare-fetch directly.
// A raw bare-fetch to an HTTPS host that accepts TCP and then goes silent holds its socket for ever
// (bare-tls does not forward 'timeout' up to the wrapper bare-https puts around the socket, so the
// agent's own reaper cannot fire). That is what put 47,191 sockets and 24.3 GB into this process and
// OOM-killed stortron twice, on 2026-08-27 and 2026-08-29. See lib/bounded-fetch.js for the full
// mechanism and test/bounded-fetch.test.mjs for the drill that proves both the leak and the fix.
import { createBoundedFetch } from '../lib/bounded-fetch.js'
const bareFetch = createBoundedFetch({
  onTimeout: ({ url, ms }) => console.error(JSON.stringify({ msg: 'fetch deadline exceeded — socket reaped', url, ms }))
})
import { readFile, writeFile, mkdir, rename } from 'bare-fs/promises'
import fs from 'bare-fs'
import Hyperswarm from 'hyperswarm'
import Corestore from 'corestore'
import { DidPeer, DidPeerRouter } from 'atproto-did-peer'
import { openCorestore } from 'atproto-store/lib/corestore.js'
import { OverlayRepoStore } from 'atproto-store/lib/overlay-repo-store.js'
import { roomKey16, blobPath, sniffMime, isSafeCid } from '../lib/blob-serve.js'
import { verifyBlobCid } from '../lib/blob-refs.js'
import { VERSION } from '../lib/version.js'
import { parseHostedDids, createIsForeign, isIgnoredCollection, IGNORED_COLLECTIONS } from '../lib/hosted-dids.js'
import { join } from 'bare-path'
import { discoveryTopic } from 'atproto-identity/lib/discovery.js'
import { decodeFrame } from 'atproto-store/lib/firehose.js'
import { Appview, INGEST_VERSION, threadPostList } from '../lib/appview.js'
import { parseLenses, lensesEnabled, lensEnv, parseLensPref, LENS_PREF_FILE } from '../lib/lenses.js'
import { createLensReader, extractThreadReplies, extractThreadParents } from '../lib/lens-import.js'
import { frontsDiag } from '../lib/fronts-diag.js'
import { fromApItem, fromReply, mergeNotifications } from '../lib/notifications.js'
import { createApInbox } from '../lib/ap-inbox.js'
import { tidNow } from 'atproto-store/lib/tid.js' // rkey minting for like/follow records
import { strongRef, parseAtUri } from '../lib/strongref.js'
import { resolveVerifyKey } from '../lib/plc.js'
import net from 'bare-net'
import { PlcDirectory } from 'atproto-identity/lib/plc-directory.js'
import { createHandleResolver } from '../lib/handles.js'
import { createTcpResolveTxt, chooseNameservers } from '../lib/dns-txt.js'
import { createFollowerLens } from '../lib/followers.js'
import { createApFollowers } from '../lib/ap-followers.js'
import { createConstellationClient } from '../lib/constellation.js'
import { Writer, writeTransportConfigured } from '../lib/writer.js'
import { SCOPE_COLLECTION, DEFAULT_SCOPE, POST_COLLECTIONS } from '../lib/scopes.js'
import { createMuteStore } from '../lib/mutes.js'
import { createBookmarkStore } from '../lib/bookmarks.js'
import { listRecord, listitemRecord, ownLists, membersOf, memberRkey, listUri as mkListUri, subscriptionRkey, missingMembers, LIST_COLLECTION, LISTITEM_COLLECTION, PURPOSES, CURATE } from '../lib/lists.js'
import { gateRecord, choiceOf, describe as describeGate, canReply, mentionsOf, listUriOf, GATE_CHOICES } from '../lib/threadgate.js'
import { postgateRecord, quoteChoiceOf, canQuote, describeQuoteGate, QUOTE_CHOICES } from '../lib/postgate.js'
import { parseListUri, resolveRoster } from '../lib/roster.js'
import { LabelStore, postModeration } from '../lib/labels.js'
import { readLabelFeed, Labeler } from '../lib/labeler.js'
import { LabelerExport } from '../lib/labeler-export.js'
import { LabelFirehose } from '../lib/label-firehose.js'
import { decodeLabel } from 'atproto-identity/lib/labels.js'
import crypto from 'hypercore-crypto'
import bareWs from 'bare-ws'
import { timelinePage, profilePage, tagPage, renderAtom, esc } from '../lib/render.js'
import { FavelaAuth, handoffDecision } from '../lib/auth.js'
import { extractToken, extractIdentity, requireIdentity, requireRepoOwner, requireMember } from '../lib/check.js'
import { makeIsMember, siteVisibility, isPublicPath, PUBLIC, MEMBERS } from '../lib/gate-policy.js'
// Membership on top of repo ownership is OPT-IN per node. Default OFF on purpose: turning it on
// without the operator's DID on a roster would refuse their OWN posts — a self-inflicted outage
// shipped as a security fix. Flip it once the roster is confirmed.
const REQUIRE_MEMBERSHIP = String(process.env.FAVELA_REQUIRE_MEMBERSHIP || '').trim() === '1'
import { joinPairInvite, createPairInvite } from '../lib/pairing.js'

// Live device-invite tunnels, did -> { inviteHex, state, done, src }. In memory because a blind-pairing
// tunnel is a live swarm connection that must outlive the HTTP request that minted it; a restart drops
// any pending invite, which is correct — an invite nobody is holding open is not an invite.
const deviceInvites = new Map()
import { serveStatic } from '../lib/static.js'
import { loginPage, settingsPage, postPage, statusPage, searchPage, bookmarksPage, notificationsPage, listsPage, listPage, followListPage, editPage } from '../lib/render.js'
import bareOs from 'bare-os'
// Which box am I looking at? /status is read over ssh or a tunnel as often as locally, and a status page
// that does not name its host is how you diagnose the wrong machine.
const HOSTNAME = (() => { try { return bareOs.hostname() } catch { return null } })()
import { Communities } from '../lib/communities.js'
import { FeedGenerator, slugRkey } from '../lib/feedgen.js'
import { CommunityRooms, CommunityDiscovery, FeedRegistries } from 'favela-community'
import { makeFeedReactor } from '../lib/feed-reactor.js'
import b4a from 'b4a'

// CLI subcommands: `favela-web pair | devices | revoke` — run + exit BEFORE booting the server daemon.
// Lets a user manage pairing/devices with a clean verb instead of `bare bin/favela-pair.js`. (No args →
// fall through to the server, unchanged.)
{
  const sub = process.argv[2]
  const { CLI_COMMANDS, runCli } = await import('../lib/cli.js')
  if (sub && CLI_COMMANDS.includes(sub)) {
    await runCli(process.argv.slice(2))
    process.exit(0)
  }
}

const PORT = Number(process.env.FAVELA_PORT || 4041)
// bare-http1's listen(port) defaults to 127.0.0.1 (unlike Node) — bind FAVELA_HOST so a remote membrane
// (the atproto-bridge proxy, possibly on another VPN host) can reach the lens-export XRPC. Default local.
const HOST = process.env.FAVELA_HOST || '127.0.0.1'
const EXTERNAL_URL = (process.env.FAVELA_EXTERNAL_URL || `http://localhost:${PORT}`).replace(/\/$/, '')

// Where a no-JS form POST returns to. ONLY a same-site absolute path is honoured — an attacker-supplied
// `return` would otherwise turn every like button into an open redirect.
function safeReturn (v) {
  const s = String(v == null ? '' : v)
  return /^\/[^\/\\]/.test(s) ? s : '/'
}

// Live browser-pairing invites, keyed by DID — see POST /api/devices/pair. Each entry owns a Hyperswarm,
// so it MUST be closed; `close()` drains protomux before destroy (pairing.js) so the delegation frame
// reaches the joining browser rather than being cut off mid-flight.
const PAIR_TTL_MS = 5 * 60 * 1000
const pendingPairs = new Map()
async function closePendingPair (did) {
  const p = pendingPairs.get(did)
  if (!p) return
  pendingPairs.delete(did)
  clearTimeout(p.timer)
  try { await p.source.close() } catch {}
}
// Write target: the LOCAL hpp device favela relays posts to (favela stays keyless; hpp signs).
// ⛔ NO DEFAULT. This used to fall back to wj62's live control key, which meant ANY favela-web started
// without config — a test, a spike, a second instance, the copy now running inside favela-android's
// worklet — wrote into production wj62 over the swarm. That is the exact failure lib/writer.js records
// from 2026-08-09 (a post landed in wj62 from a test run), one layer up and fleet-wide.
//
// Unset now means writes are REFUSED, not redirected. An instance that cannot name the node it writes
// to has no business guessing. Deployments set FAVELA_CONTROL_KEY explicitly (see package.json
// pgh.defaults.env); favela-android does not set it at all, because its writes go through the worklet's
// in-process Writer({device}) and must never leave the handset.
const WRITE_CONTROL = process.env.FAVELA_CONTROL_KEY || null
const WRITE_SEED = process.env.FAVELA_WRITER_SEED || 'wj62-swarm-test-writer-2026-07-05'
// Roster source. FAVELA_LIST (an app.bsky.graph.list AT-URI) resolves the member DIDs over P2P from the
// list owner's repo; else FAVELA_ROSTER (comma-separated DIDs); else the fleet default. verifyKeys are
// resolved from PLC per DID (no hardcoding).
// Remote AppViews this node may READ (lens import). Default is none: an unconfigured favela reaches out
// to nobody and behaves exactly as before. Opt in with FAVELA_BRIDGE_URL (one lens named 'bsky', read
// THROUGH our own bridge so no bsky URL or credential lands in this config) or FAVELA_LENSES.
// Malformed entries are reported and skipped rather than fatal — a typo in one lens must not stop the
// daemon booting, but it must not vanish silently either.
// The stored preference (settings page) layered over env. `let`, not `const`, because saving in the UI
// rebuilds these in place — a setting that needs a daemon restart to take effect is a config file with
// extra steps, and on a server nobody is going to restart for it.
function readLensPref () {
  try { return JSON.parse(fs.readFileSync(STORE(LENS_PREF_FILE), 'utf8')) } catch { return null }
}
let LENS_PREF = readLensPref()
let { lenses: LENSES, errors: LENS_ERRORS } = parseLenses(lensEnv(process.env, LENS_PREF))
for (const e of LENS_ERRORS) console.error(JSON.stringify({ msg: 'lens config problem — entry ignored', error: e }))
let LENSES_ON = lensesEnabled(LENSES)
// One reader for the process: it owns the cache, the single-flight coalescing, the per-lens circuit
// breaker and the concurrency cap, so those are properties of THIS NODE rather than of how many people
// happen to open a thread at once.
let lensReader = LENSES_ON ? createLensReader({ doFetch: bareFetch }) : null
console.log(JSON.stringify({ msg: 'lens import', enabled: LENSES_ON, lenses: LENSES.map((l) => l.name) }))

const LIST = (process.env.FAVELA_LIST || '').trim()
// ⛔ NO FLEET DEFAULT. This used to fall back to the author's own DIDs, so a stranger who installed
// favela-web silently indexed SOMEONE ELSE'S timeline and nothing errored to say so. Unconfigured
// means EMPTY — the node indexes nothing until told whose repos it serves. Same rule the write
// transport already follows (lib/writer.js: an instance that cannot name its hpp must not guess).
const ROSTER = (process.env.FAVELA_ROSTER || '').split(',').map((s) => s.trim()).filter(Boolean)
// Optional verifyKey overrides (FAVELA_VERIFYKEYS="did=hex,did=hex") for DIDs not resolvable via the
// PLC directory — local/offline/test peers, or a roster owner whose DID isn't PLC-published. Members
// still resolve via PLC unless overridden.
const VERIFY_OVERRIDES = new Map(
  (process.env.FAVELA_VERIFYKEYS || '').split(',').map((s) => s.trim()).filter(Boolean)
    .map((p) => { const i = p.indexOf('='); return i > 0 ? [p.slice(0, i), p.slice(i + 1)] : null }).filter(Boolean)
)
// Trusted labelers (moderation, OPT-IN): FAVELA_LABELERS = "feedKeyHex=didKey,feedKeyHex=didKey".
// favela replicates each labeler's signed feed, verifies + stores its labels, and applies them at render.
const LABELERS = (process.env.FAVELA_LABELERS || '').split(',').map((s) => s.trim()).filter(Boolean)
  .map((p) => { const i = p.indexOf('='); return i > 0 ? { feedKey: p.slice(0, i), didKey: p.slice(i + 1) } : null }).filter(Boolean)
// Render policy: label val -> hide|warn|inform|ignore. FAVELA_LABEL_POLICY = "nsfw=warn,spam=hide".
// (System vals !hide/!warn are always honored regardless of policy.)
const LABEL_POLICY = Object.fromEntries((process.env.FAVELA_LABEL_POLICY || '').split(',').map((s) => s.trim()).filter(Boolean)
  .map((p) => { const i = p.indexOf('='); return i > 0 ? [p.slice(0, i), p.slice(i + 1)] : null }).filter(Boolean))
// Moderation lists (viewer-side MUTE, OPT-IN): FAVELA_MODLISTS = "at://owner/app.bsky.graph.list/rkey,…".
// A modlist is an app.bsky.graph.list (purpose=modlist) — same records as a roster; favela reads its
// members and MUTES them (their posts collapse at render). Owners not on PLC use FAVELA_VERIFYKEYS.
const MODLISTS = (process.env.FAVELA_MODLISTS || '').split(',').map((s) => s.trim()).filter(Boolean)
// Co-owned communities (DESIGN §3.5): FAVELA_COMMUNITY_ROOMS = "id=roomKeyHex,id=roomKeyHex". Each is a
// plaintext hyper-rooms autobase room favela reads KEYLESSLY (by public bootstrapKey) for its member roster.
// A signed-in viewer's timeline scopes to the union of member DIDs of the community rooms they belong to.
const COMMUNITY_ROOMS = (process.env.FAVELA_COMMUNITY_ROOMS || '').split(',').map((s) => s.trim()).filter(Boolean)
  .map((p) => { const i = p.indexOf('='); return i > 0 ? { id: p.slice(0, i), roomKey: p.slice(i + 1) } : null }).filter(Boolean)
  .filter((c) => /^[0-9a-fA-F]{64}$/.test(c.roomKey))
// Discoverable communities by NAME (no hex): FAVELA_COMMUNITY_NAMES = "cat lovers,pets". Each is resolved
// to its roomKey over the DHT at boot (CommunityDiscovery) and then treated exactly like a configured room.
const COMMUNITY_NAMES = (process.env.FAVELA_COMMUNITY_NAMES || '').split(',').map((s) => s.trim()).filter(Boolean)
// Feed registries (community-ux.md §95): FAVELA_FEED_REGISTRY = "regKeyHex,regKeyHex". Each is a keyless,
// watched FeedRegistry — the durable P2P allow-set of feeds. favela-web REACTS to its entries (add-feed →
// serve getFeedSkeleton; remove-feed → stop) with NO restart and NO per-community env. This SUPERSEDES the
// static FAVELA_COMMUNITY_* config: a feed published into the registry is picked up live. Roster-first —
// entries with a roomKey (community feeds, curation from the room) are served; light feeds (no room) are
// logged + skipped for now.
const FEED_REGISTRIES = (process.env.FAVELA_FEED_REGISTRY || '').split(',').map((s) => s.trim()).filter(Boolean)
  .filter((k) => /^[0-9a-fA-F]{64}$/.test(k))
// Lens export (DESIGN §3.6): project communities into bsky-subscribable custom feeds via getFeedSkeleton.
// FAVELA_FEEDGEN_HOSTNAME = the public HTTPS host serving the XRPC endpoints (e.g. favela.7rnx.net) →
// serviceDid = did:web:<host>. FAVELA_PUBLISHER_DID = the DID whose repo holds the feed-generator records
// (the account the publish ceremony writes to). Both set → the feed-generator surfaces come online.
const FEEDGEN_HOSTNAME = (process.env.FAVELA_FEEDGEN_HOSTNAME || '').trim().replace(/^https?:\/\//, '').replace(/\/$/, '')
const PUBLISHER_DID = (process.env.FAVELA_PUBLISHER_DID || '').trim()
// Labeler export (DESIGN §3.6, moderation): FAVELA_LABELER_SEED enables favela's own atproto labeler,
// sharing the did:web identity (FAVELA_FEEDGEN_HOSTNAME) — its signing key is published as #atproto_label
// and its labels are served over com.atproto.label.queryLabels. FAVELA_LABELER_VALUES declares the vals.
const LABELER_SEED = (process.env.FAVELA_LABELER_SEED || '').trim()
const LABELER_VALUES = (process.env.FAVELA_LABELER_VALUES || 'spam,!hide,!warn').split(',').map((s) => s.trim()).filter(Boolean)
const SERVICE_DID = FEEDGEN_HOSTNAME ? 'did:web:' + FEEDGEN_HOSTNAME : null

// STABLE store dirs. Previously each was `'data/web-…-' + Date.now()`, which minted a FRESH Corestore set
// every boot and ABANDONED the prior set (measured: multiple GB of orphaned stores across restarts) AND
// forced a full P2P re-replication + appview re-index on every restart/OTA/crash. Reuse one dir per store so
// a restart RESUMES from the persisted cache. The appview is a rebuildable cache — a corrupt dir can be wiped.
const STORE = (name) => (process.env.FAVELA_STORE_ROOT || 'data') + '/' + name
const swarm = new Hyperswarm()
// ONE Corestore, NAMESPACED — not one Corestore per concern. Each Corestore is a separate RocksDB
// instance, and in practice an ACTIVE instance here costs ~75 MB of ALLOCATED blocks for a few hundred
// KB of live content, so opening four multiplied that by four. Measured end-to-end on ashatron: three
// separate stores = 225 MB actual; this one namespaced store = 75 MB.
//
// ⚠ Do NOT read that as an intrinsic per-store floor — it is not, and an earlier version of this comment
// wrongly asserted a formula (write_buffer_size * 1.1). Measured on ashatron
// (corestore 7.11.0 / hypercore-storage 3.2.0 / rocksdb-native 3.17.2):
//     fresh store, ready() only         -> apparent 70K, actual 100K (WAL size=842  allocated=4096)
//     ready() + one 5-byte append       -> apparent 75K, actual 104K (WAL size=5178 allocated=8192)
// So a new store is ~100 KB. What is real but NOT yet explained: some active stores carry a WAL with
// size=65K yet allocated=71M (allocated >> live, which only happens via preallocation), and the same
// logical store measures 4.4 MB on tabertron vs 75 MB on ashatron. Filesystem-dependent, under
// investigation — do not encode a formula here until the trigger is actually identified.
// The justification for consolidating is the 225M -> 75M measurement above, not any formula.
//
// Namespacing is safe for these three because none owns a PUBLISHED derived key (all verified):
//   did  — replicated DID/firehose cores + consumed labeler feeds, fetched BY KEY, and a by-key get is
//          namespace-independent, so nothing re-derives
//   idx  — appview index + label cache, both rebuildable: indexPeer() re-folds from the shared
//          content-addressed overlay store on LOCAL disk (no network); the cache re-fills from feeds
//   comm — CommunityRoom / FeedRegistry replicas opened by BOOTSTRAP key; favela is a keyless READER
//          (never .append/addWriter) so there is no autobase writer identity to lose
// The labeler store stays SEPARATE on purpose — see the note where it is constructed.
//
// ⚠ One-time cost, deliberately accepted: these namespaces derive DIFFERENT keys than the old
// per-dir stores, so the index rebuilds once on first boot and web-did/web-idx/web-comm are left
// orphaned on disk (untouched, so reverting this line restores them). NOT the every-boot churn the
// note above fixed — that was a new dir per boot; this is one rebuild, from local disk.
//
// Root via openCorestore (atproto-store's Corestore class): its guard is `storage instanceof Corestore`,
// which fails across duplicated corestore module copies, and namespaces of this root share that class.
const store = openCorestore(STORE('web'))
const didStore = store.namespace('did')
const indexStore = store.namespace('idx')
// SHARED record byte store (content-addressed files, ONE copy per machine). ATPROTO_OVERLAY_ROOT points at
// the SAME location hpp uses (e.g. ~/.config/hyper-proto-peer/data/atproto-repo) so co-located hpp+favela-web
// share the EXACT files — identical layout (roomKey16 = hash('atproto-base/v1/room-key' ‖ did)), byte-exact
// DAG-CBOR (idempotent for records hpp already wrote). Falls back to a favela-local dir when run standalone.
// The appview index (web-idx) now holds only POINTERS; the record bytes are never duplicated into it.
// handle -> DID, for @mention facets at compose time. A mention carries a DID, so an unresolvable handle
// gets NO facet and stays plain text (facets.js refuses to guess) — mentioning the wrong account sends a
// stranger a notification. HTTPS .well-known only: measured, *.bsky.social resolves this way and NOT via
// the DNS TXT path, so the DNS mechanism would silently answer for almost nobody. Cached per process;
// short timeout, because composing must not block on someone else's webserver.
const _handleDids = new Map()
async function resolveHandle (handle) {
  const h = String(handle || '').toLowerCase()
  if (!/^[a-z0-9][a-z0-9.-]*\.[a-z]{2,}$/.test(h)) return null
  if (_handleDids.has(h)) return _handleDids.get(h)
  let did = null
  try {
    const res = await fetch(`https://${h}/.well-known/atproto-did`, { headers: { accept: 'text/plain' }, timeout: 4000 })
    if (res && res.ok) {
      const body = (await res.text()).trim()
      if (/^did:[a-z]+:[a-zA-Z0-9._:%-]+$/.test(body)) did = body
    }
  } catch { did = null }
  _handleDids.set(h, did)
  return did
}

const OVERLAY_ROOT = process.env.ATPROTO_OVERLAY_ROOT || STORE('atproto-repo')
const _recordStores = new Map()
async function getRecordStore (did) {
  if (!_recordStores.has(did)) _recordStores.set(did, await new OverlayRepoStore(join(OVERLAY_ROOT, roomKey16(did)), { did }).ready())
  return _recordStores.get(did)
}
// Handle resolution for bylines. The handle is NOT in the profile record — atproto keeps it in the DID
// document (alsoKnownAs) — and alsoKnownAs is a CLAIM by the DID, not proof, so the resolver verifies it
// bidirectionally before anything renders it. Both mechanisms are wired: /.well-known/atproto-did
// carries both handles we serve (measured), DNS TXT is the spec's alternative. Unverified ->
// 'handle.invalid', so a DID claiming someone else's handle can never render as that person.
//
// ⛔ NOT bare-dns. `bare_dns_resolve_txt` hands c-ares a pointer into a JS arraybuffer that nothing
// references, so any GC during a query frees it and the callback faults — a SIGSEGV, uncatchable from
// JS, which took the public backend down 819 times in a week. The addon is statically linked into the
// bare runtime, so it cannot be fixed by patching a dependency. See lib/dns-txt.js.
//
// This is NOT an optional path. Measured 2026-08-24: every custom-domain handle sampled — pfrazee.com,
// dholms.xyz, jay.bsky.team, bsky.app — verifies ONLY over DNS TXT, because their /.well-known is a
// redirect, a 404 or nothing. Hosted subdomains (*.bsky.social, our own *.7rnx.net) are the reverse.
// Without TXT, most of the interesting identities on the network render handle.invalid.
//
// Same resolver as before: whatever /etc/resolv.conf points at, which is what c-ares defaulted to. No
// third-party DoH, because handle verification is the last place to hand a stranger the list of every
// identity we look up.
//
// FAVELA_NAMESERVERS is for the one environment that HAS a resolver and no file naming it: Android,
// where netd owns resolution, there is no /etc/resolv.conf, and `net.dns1` has been empty since Android
// 8 (confirmed on a handset 2026-08-24). The embedder passes the OS's own servers for the active network
// — favela-android reads them from ConnectivityManager — so this is still the network's resolver, it
// just arrives by a different route, and the objection above to third-party resolvers is untouched.
//
// Without it the phone logs "verification is OFF" and every custom-domain handle renders
// handle.invalid, which by the measurement above is most of the interesting identities on the network.
// An unusable env value falls through to the file rather than shadowing it: exporting the variable
// wrong must not silently turn verification off on a server.
const { servers: nameservers, source: nsSource } = chooseNameservers({
  envValue: process.env.FAVELA_NAMESERVERS,
  resolvConf: (() => { try { return fs.readFileSync('/etc/resolv.conf', 'utf8') } catch { return null } })()
})
if (nameservers.length === 0) {
  console.log('[favela] no nameserver (FAVELA_NAMESERVERS unset, none in /etc/resolv.conf) — DNS TXT handle verification is OFF')
} else {
  console.log('[favela] DNS TXT handle verification via ' + nameservers.length + ' nameserver(s) from ' + nsSource)
}
const handleResolver = createHandleResolver({
  plc: new PlcDirectory({ fetchImpl: bareFetch }),
  doFetch: bareFetch,
  // null disables the DNS path rather than pointing it at nothing.
  resolveTxt: nameservers.length
    ? createTcpResolveTxt({ connect: (opts) => net.createConnection(opts), servers: nameservers })
    : null
})
// isForeign gates whether the appview may CREATE record bytes: for a DID THE LOCAL HPP HOSTS, hpp is the
// authority and the sole author of those bytes, so an absent file means "not materialised here yet", not
// "ours to write". Same predicate the retention path uses (below) — one definition of "ours", not two
// that can drift.
//
// ⛔ This was `!ROSTER.includes(did)` until 0.3.37, and roster membership is NOT hosting. On a node that
// rosters a DID it does not co-host (ashatron rosters wj62 but hpp there serves only e2jev) every record
// was refused as "hpp owns these" while no local hpp would ever author them — its appview froze on
// 2026-07-31 and stayed frozen through two restarts. See lib/hosted-dids.js.
const HPP_CONFIG = process.env.PEER_CONFIG || join(process.env.HOME || '', '.config/hyper-proto-peer/config.json')
let HOSTED_DIDS = null
try { HOSTED_DIDS = parseHostedDids(fs.readFileSync(HPP_CONFIG, 'utf8')) } catch { HOSTED_DIDS = null }
// Unknown (no config / unreadable / malformed) falls back to ROSTER — the pre-0.3.37 behaviour. Roster ⊇
// hosted, so the fallback can only refuse MORE writes, never permit one the old code refused.
const isForeignDid = createIsForeign({ hosted: HOSTED_DIDS, roster: ROSTER })
console.log(JSON.stringify({
  msg: 'byte-authorship scope',
  source: HOSTED_DIDS ? 'local hpp config' : 'ROSTER (hpp config unreadable — conservative fallback)',
  hosted: HOSTED_DIDS || ROSTER,
  roster: ROSTER,
  weMayAuthorFor: ROSTER.filter(isForeignDid)
}))
const av = await new Appview(indexStore, { getRecordStore, handleResolver, isForeign: isForeignDid }).ready()

// spec/convergence.md §8 Q4, answered: BOTH a boot warning and a `diff` line, plus its own verb.
//
// The three surfaces answer three different questions and none substitutes for another. `diff` reports
// what the AUTHORITY holds right now, and only for the DIDs you ask about. This reports what has already
// ARRIVED here across every DID, from the persisted ledger — so a collection that stopped appearing
// upstream is still visible, and so an operator who never runs `diff` still learns. Boot is the moment
// they are guaranteed to read output at all.
//
// Warns only for UNKNOWN. Ignored-by-policy is a decision on file; announcing it every boot would train
// the reader to skip the block, which is how a real warning gets missed.
try {
  const unknown = await av.unknownCollections()
  if (unknown.length) {
    console.warn(JSON.stringify({
      msg: 'UNKNOWN collections have been ingested and no view indexes them',
      collections: unknown.map((u) => ({ collection: u.collection, count: u.count, firstSeen: u.firstSeen, lastSeen: u.lastSeen, dids: u.dids })),
      action: 'favela-web collections   — then classify each in lib/hosted-dids.js (spec/convergence.md §2.1)'
    }))
  }
} catch { /* a diagnostic must never block boot */ }

// Network-wide followers (§7.6 Tier C). Independent of the inbound lens on purpose: this is a READ-ONLY
// reference query — no store, no retention, nothing to clobber — so it stays on even when FAVELA_SPACEDUST
// is off. Shares the handle resolver so follower names are bidirectionally verified, not claimed.
// The ActivityPub side of the same identity. ap-bridge already serves a standard AP followers
// collection over HTTP, and its actor document declares which DID it is (`alsoKnownAs`) — so no new
// storage or transport is needed to READ it, only the URL. OFF unless FAVELA_AP_BRIDGE is set, and
// fails soft: if it is unreachable the follower page still renders its atproto followers.
const apFollowers = createApFollowers({
  base: (process.env.FAVELA_AP_BRIDGE || '').trim() || null,
  doFetch: bareFetch
})
if (apFollowers.enabled) console.log(JSON.stringify({ msg: 'ap followers: reading', base: process.env.FAVELA_AP_BRIDGE.trim() }))

// The rkeys ap-bridge has actually projected — the OBSERVED half of the reach badges (lib/reach.js).
// One outbox fetch per request, cached 60s inside the reader, and null (not empty) when the AP side
// is unconfigured or unreachable so "not projected" and "could not ask" never render alike.
//
// Scoped to the PRIMARY roster DID: ap-bridge fronts one actor, and its outbox only ever describes
// that DID. Asking about anyone else's posts would be a category error, not a miss.
async function apProjected () {
  if (!apFollowers.enabled || !ROSTER.length) return null
  try { return await apFollowers.projectedRkeys(ROSTER[0]) } catch { return null }
}

// The fediverse half of notifications. Local socket only — ap-bridge is single-instance and holds
// other people's messages to us, so it is not a public endpoint. Returns null when this node cannot
// ask, which the page renders as "cannot see them" rather than "none".
const apInbox = createApInbox({
  home: process.env.HOME || '',
  exists: (p) => { try { return fs.existsSync(p) } catch { return false } },
  connect: async (p) => { const { Client } = await import('hyper-svc'); return Client.connectUds(p) }
})

const followerLens = createFollowerLens({
  constellation: createConstellationClient({
    doFetch: bareFetch,
    ...(process.env.FAVELA_CONSTELLATION ? { endpoint: process.env.FAVELA_CONSTELLATION.trim() } : {})
  }),
  handles: handleResolver
})

// ── inbound lens (DESIGN §7.6) — OPT-IN, default OFF ────────────────────────────────────────────
// Subscribes to spacedust for links that touch OUR roster, fetches each linking record from its
// author's PDS, VERIFIES it against the DID document's key, and retains the content-bearing ones.
// Off unless FAVELA_SPACEDUST is set: an always-on subscription to a third-party service is not
// something a node should inherit by upgrading. `1`/`true` uses the public instance; any other value
// is treated as the endpoint URL.
//
// Reuses getRecordStore, so a retained foreign record lands in the SAME per-DID OverlayRepoStore layout
// hpp uses — files, not cores. The retention index gets its own namespace so it can never collide with
// the appview's; per §7.5 it is bookkeeping only (skip-test + eviction order), so losing it costs a
// re-fetch, never correctness. The retained records are Tier-B cache: the authoritative copy lives in
// the author's PDS and is re-fetchable, which is why eviction is always safe.
const SPACEDUST = (process.env.FAVELA_SPACEDUST || '').trim()
const RETENTION_BUDGET = Number(process.env.FAVELA_RETENTION_BUDGET || 0) || null
// How many of our OWN recent posts to ask Constellation about per roster DID. Bounds the sweep.
const BACKFILL_POSTS = Number(process.env.FAVELA_BACKFILL_POSTS || 50)
let inbound = null
if (SPACEDUST) {
  const { createInboundLens } = await import('../lib/inbound.js')
  const { createBeeIndex } = await import('../lib/retention.js')
  const { createBareSocket } = await import('../lib/spacedust-socket.js')
  const Hyperbee = (await import('hyperbee')).default
  const retentionBee = new Hyperbee(store.namespace('retention').get({ name: 'retention' }), {
    keyEncoding: 'utf-8',
    valueEncoding: 'json'
  })
  await retentionBee.ready()
  const isFlag = SPACEDUST === '1' || SPACEDUST.toLowerCase() === 'true'
  inbound = createInboundLens({
    roster: ROSTER,
    openStore: getRecordStore,
    appview: av,
    index: createBeeIndex(retentionBee),
    doFetch: bareFetch,
    createSocket: createBareSocket,
    // OUR OWN record at-uris — what Constellation is asked about. NOT our DIDs: its `subject` is an
    // EXACT target, so a DID matches nothing for reply/quote sources and returns a silent zero that
    // looks exactly like a quiet roster (measured live 2026-07-30). Spacedust is not symmetric here —
    // its subject_did axis DOES extract DIDs from at-uris, so the live filter above is correctly
    // keyed by roster DID.
    //
    // Bounded to the most recent BACKFILL_POSTS per roster DID: a full-history sweep is exactly the
    // unbounded crawl §7.6 warns about, and recent posts are where inbound replies actually land.
    // Known inefficiency: getAuthorFeed HYDRATES (a record read + profile + three counts per post)
    // when all we want is the uri. Bounded and infrequent (cold start + roster change), so it is
    // accepted for now rather than reaching into the private _author index.
    listSubjectUris: async (dids) => {
      const uris = []
      for (const did of dids) {
        try {
          // getAuthorFeed returns { posts, cursor } — NOT a bare array. Iterating the object throws,
          // and a swallowing catch turns that into a silent zero (it did, live, for a full retry cycle).
          const { posts } = await av.getAuthorFeed(did, { limit: BACKFILL_POSTS })
          for (const p of posts || []) if (p && p.uri) uris.push(p.uri)
        } catch (err) {
          // One unreadable author must not abort the sweep — but never swallow it. A silent skip here
          // is indistinguishable from "nobody has replied to us", which is the whole failure mode.
          console.log(JSON.stringify({ msg: 'inbound', event: 'subject-uris-failed', did, error: (err && err.message) || String(err) }))
        }
      }
      return uris
    },
    // ⛔ NEVER retain into a repo hpp AUTHORS. Constellation reports ANY record linking to our subjects
    // — including our OWN replies to our own posts — and writing those back over hpp's canonical files
    // re-encoded them, dropped `langs`, and wedged the forward-only sign gate (2026-07-31: two wj62
    // replies never federated). The set hpp signs for on this node is what its OWN config hosts — not
    // the roster, which also names DIDs other nodes host (see lib/hosted-dids.js). Same function object
    // as the appview gate above, so the two can never drift.
    isForeign: isForeignDid,
    budgetBytes: RETENTION_BUDGET,
    ...(isFlag ? {} : { endpoint: SPACEDUST }),
    ...(process.env.FAVELA_CONSTELLATION ? { constellationEndpoint: process.env.FAVELA_CONSTELLATION.trim() } : {}),
    onEvent: (event, detail) => {
      // Drops, refusals and truncations are invisible unless the daemon says so — §7.6's whole posture.
      if (event === 'retained' || event === 'evicted') return // too chatty for steady state
      console.log(JSON.stringify({ msg: 'inbound', event, ...detail }))
    }
  })
  // ⛔ NOT AWAITED. This is the inbound lens: it subscribes to a remote index and backfills over HTTP.
  // Awaiting it made a LOCAL, P2P-FIRST node refuse to serve until a REMOTE WEB SERVICE answered — and
  // on 2026-08-24 that is exactly what happened. The bridge saturated, this fetch had no deadline
  // (bare-fetch silently drops `timeout`: its Request destructures only body/method/headers/signal/
  // agent, verified in node_modules/bare-fetch/lib/request.js), and the daemon hung in boot forever
  // while every P2P capability it owns was already available. Both backends did it simultaneously,
  // which left the proxy with no healthy node, which kept the fetch from ever completing — a deadlock
  // that could only be broken by restarting Apache.
  //
  // A phone, tabertron and ashatron are P2P nodes. Nothing on the web side may gate them serving.
  // The lens is an ENHANCEMENT: it fills in replies from outside this node's window. Without it the
  // timeline still renders, so it starts in the background and reports failure instead of blocking.
  //
  // Deliberately not "bounded with a timeout" either. A deadline would have turned a permanent hang
  // into a slow boot, when the correct answer is that a P2P node's readiness does not depend on this
  // at all.
  inbound.start().then(
    () => console.log(JSON.stringify({ msg: 'inbound lens', enabled: true, subjects: ROSTER.length, budgetBytes: RETENTION_BUDGET })),
    (e) => console.error(JSON.stringify({ msg: 'inbound lens FAILED to start — serving anyway, replies from outside this node will be missing', error: (e && e.message) || String(e) }))
  )
} else {
  console.log(JSON.stringify({ msg: 'inbound lens', enabled: false }))
}
// ONE announce-channel per connection, dispatched to DidPeers by DID (the multi-DID fix — a per-peer
// attach() would collide on the single ANNOUNCE_PROTOCOL channel and only the first-added DID would
// ever learn its cores). The router owns corestore replication + the shared channel.
// Give the router the SWARM (not just manual onconnection): this arms the canonical _refreshFronts loop —
// the pull-refresh staleness-ceiling that update({wait:true})s a replicated firehose core which saw no
// 'append' and re-picks the FRESHEST co-owner front. Without it a co-owned DID's tail silently follows a
// stalled front while another advances (the bridge stays current precisely because it wires this). The
// router owns the 'connection' handler when given the swarm, so we no longer add our own.
// rpc:true arms ONE protomux-rpc per connection, which is what lets a front RELAY a request to the peer
// that actually holds the data. Needed for getBlob: favela serves blobs from the SHARED overlay files,
// which only works for a DID whose bytes are co-located on this box. Every other DID 404'd — measured:
// wj62 had its 1 avatar blob locally and served, while e2jev (blobs on ashatron, in the LEGACY Hyperbee
// store that never replicates) returned BlobNotFound for every image. The bridge has always handled this
// by relaying get-blob to the holder; favela had no fallback at all. Read-only use — favela holds no key.
const router = new DidPeerRouter(didStore, { swarm, rpc: true })
const peers = []
const byDid = new Map()

const delay = (ms) => new Promise((r) => setTimeout(r, ms))

// Ask the peer that HOLDS a blob for its bytes, when they are not in our shared overlay dir. This is the
// same relay the keyless bridge performs (DidPeer.getBlob -> the holder's hpp `get-blob` RPC), and it is
// the only way to serve a DID whose blobs are not co-located — e.g. one still on the LEGACY Hyperbee blob
// store, which never replicates, so no amount of waiting would bring the bytes here.
//
// STRICTLY BOUNDED: this runs inside an HTTP request, so every step is capped and every failure returns
// null (the caller then 404s as before). A front with no RPC channel, an unreachable holder, or a holder
// that simply lacks the blob must degrade to "not found", never hang the page. Returns bytes or null.
// Every failure here USED to collapse into `return null`, so a 404 could not be told apart from "no
// front", "front with no RPC channel", "holder timed out" or "holder does not have it" — four faults
// with four different fixes. That cost a round trip on e2jev: the relay returned in 9ms (so it bailed on
// a guard rather than trying) and nothing said which. Same mistake as the byte-resolution message that
// asserted a content fault for a transport fault (hyper-social #14, lesson 2), reproduced immediately
// after quoting it. Each guard now names itself.
//
// The dedup key includes the DID's front/RPC topology, not just the reason — a line keyed on the reason
// alone is emitted once and then indistinguishable from a live failure, which is the trap #14 recorded
// for _logFetchMiss. Keyed this way it re-emits the moment connectivity changes.
// Keep a blob we had to fetch, so the next reader is served from disk and this node becomes a source.
//
// Writes into the SAME shared content-addressed dir hpp uses (blob-serve.js keeps that derivation in
// one place), so a co-located hpp sees the file too rather than a second copy appearing beside it.
//
// .part then rename: a reader hitting the path mid-write must never get a truncated image, and a
// truncated file under a content-addressed name would be served as fact forever. Same reason
// favela-android stages its OTA bundle that way.
//
// The CALLER verifies the bytes against the cid first. This function must never be handed unverified
// bytes — the filename is the hash, so writing the wrong body poisons the name permanently.
async function retainBlob (did, cid, bytes) {
  const dest = blobPath(OVERLAY_ROOT, did, cid)
  const dir = dest.slice(0, dest.lastIndexOf('/'))
  await mkdir(dir, { recursive: true })
  const part = dest + '.part'
  await writeFile(part, bytes)
  await rename(part, dest)
  console.log(JSON.stringify({ msg: 'blob retained from relay — this node can now serve it', did, cid: String(cid).slice(0, 20), bytes: bytes.length }))
}

const _relayMiss = new Set()
function relayFronts (did) {
  try {
    const d = router.diagnose()
    const mine = (d.fronts || []).filter((f) => f.did === did)
    return { fronts: mine.length, withRpc: mine.filter((f) => f.rpcConnected).length, live: mine.filter((f) => f.live).length, keys: mine.map((f) => String(f.firehoseKey).slice(0, 12)) }
  } catch { return { fronts: null, withRpc: null, live: null, keys: [] } }
}
function logRelayMiss (did, cid, reason, extra = {}) {
  const t = relayFronts(did)
  const k = did + ':' + reason + ':' + t.fronts + ':' + t.withRpc + ':' + t.live
  if (_relayMiss.has(k)) return
  _relayMiss.add(k)
  try {
    console.error(JSON.stringify({
      msg: 'getBlob relay could not obtain the bytes — serving 404',
      did, cid: String(cid).slice(0, 20), reason, ...extra, ...t
    }))
  } catch {}
}

const RELAY_BLOB_MS = 8000
async function relayBlob (did, cid) {
  let front
  try {
    front = await Promise.race([
      router.front(did, { timeout: RELAY_BLOB_MS }),
      delay(RELAY_BLOB_MS).then(() => '__timeout__')
    ])
  } catch (e) {
    // router.front throws for a DID it does not front at all ("not a fronted DID") — a WIRING fault,
    // distinct from a holder that simply lacks the blob.
    logRelayMiss(did, cid, 'front-lookup-failed', { error: e.message })
    return null
  }
  if (front === '__timeout__') { logRelayMiss(did, cid, 'front-lookup-timeout', { ms: RELAY_BLOB_MS }); return null }
  if (!front) { logRelayMiss(did, cid, 'no-frontable-co-owner'); return null }
  if (!front.rpc) {
    // The suspected e2jev case: we replicate this DID's cores from a peer that SEEDS them rather than
    // holds its key (a keyless bridge/relay announces the same cores), so there is no get-blob responder
    // to ask. `withRpc` in the payload says whether ANY front for this DID has a channel.
    logRelayMiss(did, cid, 'front-has-no-rpc-channel', { rev: front.head ? front.head.rev : null })
    return null
  }
  let r
  try {
    r = await Promise.race([front.getBlob(cid), delay(RELAY_BLOB_MS).then(() => '__timeout__')])
  } catch (e) {
    logRelayMiss(did, cid, 'rpc-error', { error: e.message })
    return null
  }
  if (r === '__timeout__') { logRelayMiss(did, cid, 'rpc-timeout', { ms: RELAY_BLOB_MS }); return null }
  if (!r || !r.bytes) {
    // Reached a holder and it answered: it genuinely does not have this blob. A CONTENT fault, not a
    // transport one — the distinction that matters when deciding whether to chase wiring or bytes.
    logRelayMiss(did, cid, 'holder-does-not-have-it')
    return null
  }
  // The peer sends bytes hex-encoded in the c.json RPC value (serve-membrane's get-blob responder).
  return b4a.from(r.bytes, 'hex')
}
// Bare has no global AbortController; the firehose sequencer only needs a signal with { aborted,
// add/removeEventListener('abort') }, so supply a minimal one (used to cut over a firehose tail on failover).
function makeAbort () {
  const ls = new Set()
  const signal = { aborted: false, addEventListener: (_t, fn) => ls.add(fn), removeEventListener: (_t, fn) => ls.delete(fn) }
  return { signal, abort () { if (signal.aborted) return; signal.aborted = true; for (const fn of [...ls]) { try { fn() } catch {} } ls.clear() } }
}

// Open (once) a DidPeer for a DID: resolve its verifyKey, join its topic, and wire the hybrid ingest
// (snapshot baseline + incremental firehose tail). Deduped so the list owner and a member DID don't
// double-open the same cores. Returns the peer, or null if verifyKey resolution failed.
async function addPeer (did) {
  if (byDid.has(did)) return byDid.get(did)
  let verifyKey
  const override = VERIFY_OVERRIDES.get(did)
  if (override) { verifyKey = b4a.from(override, 'hex') } else {
    try { verifyKey = await resolveVerifyKey(did, { fetch: bareFetch }) } catch (e) { console.error('[favela] verifyKey resolve failed for', did, '-', e.message); return null }
  }
  // EVERY DID is noRepo: follow the firehose ONLY (verified head + tail) and NEVER replicate the repo core —
  // no duplicate copy. Records live once in the shared content-addressed OverlayRepoStore. coHosted decides
  // the BASELINE source: a DID whose records hpp already holds on this box (wj62/loser-club on tabertron)
  // reads them from the AUTHORITATIVE shared store (bypasses the membrane fork/desync); a non-co-hosted DID
  // rebuilds its repo from the FIREHOSE BACKFILL (subscribeRepos(0) — each #commit frame carries the bytes).
  // ⛔ CO-HOSTED MEANS hpp HOLDS IT, NOT "WE HAVE SOME RECORDS FOR IT". This was
  // `(await store.records()).length > 0`, which is SELF-FULFILLING — the gate below says so in its own
  // comment: our own putPost populates the shared store for ingested peers too. So the first time we
  // glanced at a DID it acquired records, became "co-hosted" for ever, and from then on every boot
  // tailed from the CURRENT END and could never fill a gap.
  //
  // Measured on a handset (hyper-social #53): ashatron viewed once in August, then frozen — posts 16
  // days stale and the PREVIOUS avatar rendering as current, because the profile record was inside the
  // hole. It reads as corruption rather than as a sync gap, which is the worst way for it to fail.
  //
  // hpp's config is the authority (the same source /api/track calls HOSTED-FIRST for the same reason).
  // A DID we actually host is authoritative on disk and rightly tails from the end; anything else
  // rebuilds from the firehose, which is the only copy that can close a gap.
  //
  // ⚠ Non-hosted DIDs therefore replay from seq 0 on each boot. That is idempotent (putPost/putProfile
  // dedup by content signature, so a replay re-reads without re-writing) but it re-reads frames every
  // launch. The real answer is a persisted per-DID fold cursor so a boot resumes instead of replaying;
  // until that exists, correct-and-costly beats cheap-and-frozen.
  const coHosted = (HOSTED_DIDS || []).includes(did)
  console.log(JSON.stringify({ msg: 'firehose-only (noRepo) DID', did, baseline: coHosted ? 'shared-store' : 'firehose-backfill' }))
  const peer = router.add(did, { verifyKey, noRepo: true, onError: (e) => console.error('[peer]', did, e.message) })
  byDid.set(did, peer); peers.push(peer)
  swarm.join(discoveryTopic(did), { client: true, server: true })
  // FAILOVER-AWARE ingest (noRepo, event-driven, no poll). A CO-OWNED DID can move to a DIFFERENT co-owner's
  // firehose core (a new firehoseKey) at any time; following one fixed core FREEZES the index at the failover
  // point (the loser-club stall — wj62/ashatron both froze at their July co-owner failovers). So resolve the
  // FRESHEST verified front (router.front → highest-rev co-owner), baseline + live-tail IT, and when the router
  // opens a fresher front, abort the tail and re-resolve + re-baseline (the new co-owner's firehose is a
  // distinct history). Baseline source per coHosted: the AUTHORITATIVE shared store (indexPeer, which for a
  // noRepo peer reads OverlayRepoStore — needs ATPROTO_OVERLAY_ROOT → hpp's dir) vs firehose backfill from 0.
  // #sync re-baselines within a front.
  ;(async () => {
    let lastKey = null
    while (byDid.has(did)) {
      let front
      try { front = await router.front(did, { timeout: 60000 }) } catch (e) { await delay(5000); continue }
      const fhKey = front._firehoseKey ? b4a.toString(front._firehoseKey, 'hex') : 'primary'
      if (fhKey !== lastKey) { console.log(JSON.stringify({ msg: 'ingest: following firehose front', did, front: fhKey.slice(0, 12) })); lastKey = fhKey }
      const ac = makeAbort()
      // Watch for a FRESHER front (a failover to another co-owner) → abort this tail so the loop re-resolves.
      const watch = setInterval(() => { try { const f = router._freshestFront(did); if (f && f !== front) ac.abort() } catch {} }, 5000)
      if (watch.unref) watch.unref()
      try {
        if (coHosted) { try { await av.indexPeer(front) } catch (e) { console.error('[favela] baseline index failed', did, '-', e.message) } }
        // Sync the replicated firehose core's length/backlog BEFORE reading it: a freshly-opened replica
        // reads length 0, and 'append' only fires for frames appended AFTER we connect — so without this the
        // tail sits idle on the peer's existing history (this is exactly what FleetRelay.addSource does).
        // Bounded so a slow/offline peer can't hang the loop; _refreshFronts keeps it fresh thereafter.
        if (front.seq && front.seq.core) { try { await Promise.race([front.seq.core.update({ wait: true }), delay(8000)]) } catch {} }
        // BACKFILL GATE. The coHosted fast path tails from the current end, which is right for a DID whose
        // records the shared store already holds authoritatively — but it is self-fulfilling, because our
        // own putPost populates that store for ingested peers too. So once this build indexes MORE than the
        // build that last folded this DID (INGEST_VERSION), replay from 0 regardless of coHosted. Idempotent:
        // putPost/putProfile are dedup-gated by content signature, so a replay re-reads without re-writing.
        const backfill = await av.needsBackfill(did).catch(() => true)
        const target = front.seq && front.seq.core ? front.seq.core.length : 0
        const from = (coHosted && !backfill) ? target : 0
        if (backfill) console.log(JSON.stringify({ msg: 'ingest: BACKFILL from seq 0 (this build indexes more than the last fold)', did, frames: target, ingestVersion: INGEST_VERSION }))
        // An empty firehose has nothing to replay — mark it done now or every boot re-announces a backfill.
        let marked = false
        if (backfill && target === 0) { await av.markBackfilled(did); marked = true }
        let seen = 0
        for await (const { bytes } of front.subscribeRepos(from, { signal: ac.signal })) {
          try {
            const d = decodeFrame(bytes)
            if (!d) continue
            if (d.t === '#commit') await av.applyCommit(did, await DidPeer.commitOps(d.body))
            else if (d.t === '#sync') await av.indexPeer(front) // re-baseline: chain discontinuity
          } catch (e) { console.error('[favela] ingest frame failed', did, '-', e.message) }
          // Mark ONLY once the replay has reached the length the front had when we started — not on
          // starting one. A crash mid-replay must leave the marker unset so the next boot retries.
          seen++
          if (backfill && !marked && seen >= target) {
            await av.markBackfilled(did)
            marked = true
            console.log(JSON.stringify({ msg: 'ingest: backfill complete', did, frames: seen, ingestVersion: INGEST_VERSION }))
          }
        }
      } catch (e) {
        if (!ac.signal.aborted) console.error('[favela] firehose loop', did, '-', e.message)
      } finally { clearInterval(watch) }
      await delay(1000) // brief backoff, then re-resolve the freshest front (failover cutover or reconnect)
    }
  })().catch((e) => console.error('[favela] ingest loop', did, '-', e.message))

  // CO-HOSTED reconciliation — EVENT-DRIVEN (no polling timer). The co-located hpp writes each new record as
  // a file into the SHARED store; that filesystem write IS the event. `fs.watch` the timeline collection dirs
  // and re-index when a record lands — so favela stays current from the AUTHORITATIVE local store even when
  // the firehose front's live tail is stalled on a lagging co-owner. Silent when idle (watch fires nothing);
  // a short coalescing delay collapses a burst of writes into one indexPeer (event-triggered, not periodic).
  // Non-co-hosted DIDs (no shared store) rely on the firehose backfill/tail above.
  if (coHosted) {
    const recDir = join(OVERLAY_ROOT, roomKey16(did), 'records')
    let coalesce = null
    const onChange = () => {
      if (coalesce) return
      coalesce = setTimeout(() => { coalesce = null; av.indexPeer(peer).catch((e) => console.error('[favela] re-index failed', did, '-', e.message)) }, 400)
      if (coalesce.unref) coalesce.unref()
    }
    for (const col of [SCOPE_COLLECTION.public, SCOPE_COLLECTION.local]) {
      try {
        const dir = join(recDir, col)
        fs.mkdirSync(dir, { recursive: true }) // ensure it exists before watching (fresh DID may lack it)
        const w = fs.watch(dir, onChange)
        if (w && w.on) w.on('error', () => {})
      } catch (e) { console.error('[favela] record-dir watch setup failed', did, col, '-', e.message) }
    }
  }
  return peer
}

// ── THE SUBSCRIPTION LIST, AND WHY IT IS NOT CONFIGURATION ───────────────────────────────────────────
// WHICH identities a node subscribes to was node-local: tabertron pinned FAVELA_ROSTER in apps.json
// while a handset derived its own from hosted + locally tracked DIDs. Same DID, two sources of truth,
// and they disagreed — ashatron was indexed on one and invisible on the other, which surfaced as a
// profile frozen two weeks in the past rather than as a missing subscription (hyper-social #53).
//
// A list is the fix that already exists: an app.bsky.graph.list in the owner's OWN repo, membership as
// listitems, resolved by lib/roster.js. It replicates with the identity, so every device hosting that
// DID converges on the same subscriptions with nothing configured anywhere.
//
// So look for one at a well-known rkey on the DID we host, when no FAVELA_LIST is set explicitly. No new
// substrate, no new env var to remember, and a second device inherits the roster by replication.
const SUBSCRIPTIONS_RKEY = 'subscriptions'
let listUri = LIST
if (!listUri) {
  const selfDid = (HOSTED_DIDS || [])[0] || null
  if (selfDid) {
    const candidate = `at://${selfDid}/${LIST_COLLECTION}/${SUBSCRIPTIONS_RKEY}`
    try {
      const store = await getRecordStore(selfDid)
      if (await store.get(LIST_COLLECTION, SUBSCRIPTIONS_RKEY)) {
        listUri = candidate
        console.log(JSON.stringify({ msg: 'roster: using the replicated subscriptions list', list: candidate }))
      }
    } catch (e) {
      console.error(JSON.stringify({ msg: 'roster: could not read the subscriptions list (env roster still in force)', error: e.message }))
    }
  }
}

// Resolve the roster: from a list (open the owner first to READ it, then use its member DIDs) or the
// env fallback. A list-resolve failure falls back to FAVELA_ROSTER rather than coming up empty.
let rosterDids = ROSTER
if (listUri) {
  try {
    const { owner } = parseListUri(listUri)
    const ownerPeer = await addPeer(owner)
    if (!ownerPeer) throw new Error('could not open the list owner peer')
    await ownerPeer.ready({ timeout: 60000 })
    const r = await resolveRoster(ownerPeer, listUri)
    // ⛔ HOSTED DIDs ARE NOT OPTIONAL. `rosterDids = r.members` alone would drop this node's OWN identity
    // out of the roster the moment a list resolves — it would stop indexing itself, which is invisible
    // until every one of your own posts is missing. Hosted FIRST, because addPeer runs in roster order
    // and apProjected() asks about ROSTER[0] specifically.
    rosterDids = [...(HOSTED_DIDS || []), ...r.members].filter((d, i, a) => a.indexOf(d) === i)
    console.log(`[favela] list "${r.name || listUri}" -> ${r.members.length} member(s), ${rosterDids.length} in roster with hosted`)
  } catch (e) { console.error('[favela] list resolve failed:', e.message, '- falling back to FAVELA_ROSTER'); rosterDids = ROSTER }
}
for (const did of rosterDids) await addPeer(did)
await swarm.flush()
console.log(`[favela] joined ${peers.length} DID topic(s); indexing over P2P...`)

// Moderation (opt-in): replicate each trusted labeler's signed feed and verify+store its labels. The
// labeler feed cores live on didStore, so the router's per-connection didStore.replicate already
// carries them once we join the feed's discoveryKey. Labels apply at render — posts are never deleted.
const labelStore = await new LabelStore(indexStore, { name: 'favela-labels' }).ready()
for (const { feedKey, didKey } of LABELERS) {
  try {
    const core = didStore.get({ key: b4a.from(feedKey, 'hex'), valueEncoding: 'binary' })
    await core.ready()
    swarm.join(core.discoveryKey, { client: true, server: true })
    readLabelFeed(core, didKey, labelStore, { onError: (e) => console.error('[labeler]', e.message) })
    console.log(`[favela] labeler subscribed: ${didKey.slice(0, 24)}… feed=${feedKey.slice(0, 12)}…`)
  } catch (e) { console.error('[favela] bad labeler', feedKey, '-', e.message) }
}
if (LABELERS.length) await swarm.flush()

// Moderation lists (opt-in mute): resolve each subscribed modlist's members over P2P (same list
// machinery as the roster) into a muted-author set. Their posts collapse at render.
const MUTED = new Set()
for (const listUri of MODLISTS) {
  try {
    const { owner } = parseListUri(listUri)
    const ownerPeer = await addPeer(owner)
    if (!ownerPeer) continue
    await ownerPeer.ready({ timeout: 60000 })
    const r = await resolveRoster(ownerPeer, listUri)
    for (const did of r.members) MUTED.add(did)
    console.log(`[favela] modlist "${r.name || listUri}" -> ${r.members.length} muted author(s)`)
  } catch (e) { console.error('[favela] modlist resolve failed:', listUri, '-', e.message) }
}

// Enrich a feed result with the two viewer-side moderation layers: labeler labels + modlist mute.
// Attaches { labels:[val], treatment, muted } per post; the render collapses hide/warn/muted.
const uriOf = (p) => `at://${p.did}/${(p.record && p.record.$type) || 'app.bsky.feed.post'}/${p.rkey}`
// Per-viewer mutes + block bookkeeping. NODE-LOCAL: a mute is private in atproto and must never become
// a record (see lib/mutes.js). Lives in the appview's own store, which is a rebuildable cache and is
// never replicated — the right home for something that must not leave this machine.
const muteStore = createMuteStore(av.bee.sub('mutes'))
// Private, node-local, per viewer — see lib/bookmarks.js for why this is deliberately NOT a record.
const bookmarkStore = createBookmarkStore(av.bee.sub('bookmarks'))

// `viewerDid` is now threaded in, because "muted" is a property of a READER, not of a post. The node-wide
// MODLIST set (an operator subscribing the whole node to a moderation list) is UNIONED with the viewer's
// own mutes rather than merged into storage — they are different facts with different owners.
//
// A BLOCKED account is hidden outright rather than collapsed: a mute says "not interested", a block says
// "not in my feed", and rendering a block as a revealable <details> would make the stronger action look
// weaker than the softer one.
async function withMod (result, viewerDid = null) {
  const mutedByViewer = viewerDid ? await muteStore.mutedBy(viewerDid) : new Set()
  // Blocks come from the INDEXED records now (any device, any peer), UNIONED with this node's own
  // bookkeeping. The union matters during the changeover: a block made here before 0.3.27 has local
  // bookkeeping and may not be re-indexed yet, and dropping it would silently unblock someone.
  const blocked = new Set()
  if (viewerDid) {
    for (const d of await av.blocking(viewerDid)) blocked.add(d)
    for (const d of await muteStore.blockedBy(viewerDid)) blocked.add(d)
  }
  if (blocked.size) result.posts = result.posts.filter((p) => !p || !blocked.has(p.did))
  for (const p of result.posts) {
    const mod = postModeration(await labelStore.getLabels(uriOf(p)), MUTED.has(p.did) || mutedByViewer.has(p.did), LABEL_POLICY)
    if (mod.labels.length) p.labels = mod.labels
    if (mod.treatment !== 'ignore') p.treatment = mod.treatment
    if (mod.muted) p.muted = true
  }
  return result
}

// Write path: relay posts to the local hpp device (keyless — hpp signs). The authoring peer's
// firehose 'append' listener re-indexes automatically, so a new post appears without a manual poke.
// Guarded behind a Proxy rather than a check in each of the ~12 write routes: a per-route check is one
// forgotten route away from the hazard coming back, and the routes are added to regularly. Every method
// call throws the same named error, so a refusal reads as a refusal instead of a stack trace about a
// null controlKey.
const _writer = new Writer({ controlKey: WRITE_CONTROL, writerSeed: WRITE_SEED })
// WHICH TRANSPORT — swarm (FAVELA_CONTROL_KEY, a REMOTE hpp) or local UDS (FAVELA_HPP_SOCK, an hpp on
// this box). The gate used to test the control key ALONE, so a CO-LOCATED instance was refused its own
// local device: favela-android embeds this server beside an hpp whose control socket is right there, and
// it still logged "writes are DISABLED" and refused every post. Reads were unaffected, which is why the
// phone looked like it was working. See writeTransportConfigured for why this reads the ENV and not the
// Writer — DEFAULT_SOCK must never open the gate by itself.
const WRITE_TRANSPORT = writeTransportConfigured(process.env)
if (!WRITE_TRANSPORT) {
  console.error(JSON.stringify({
    msg: 'no write transport configured — writes are DISABLED for this instance (reads are unaffected)',
    why: 'an instance that cannot name the hpp it writes to must not guess; there is no default',
    fix: 'set FAVELA_HPP_SOCK to a co-located hpp control socket, or FAVELA_CONTROL_KEY for a remote one'
  }))
} else {
  console.log(JSON.stringify({ msg: 'write transport', transport: WRITE_TRANSPORT, uds: WRITE_TRANSPORT === 'uds' ? process.env.FAVELA_HPP_SOCK : null }))
}
const writer = WRITE_TRANSPORT
  ? _writer
  : new Proxy({}, {
    get (_t, prop) {
      // Lifecycle, not writes — a caller must still be able to shut down cleanly. `then` must stay
      // undefined or an `await` on this object would treat it as a thenable and hang.
      if (prop === 'close' || prop === 'then') return undefined
      // REJECTED PROMISE, not a synchronous throw. The login path does
      // `await writer.isDeviceRevoked(k).catch(() => false)` — a sync throw escapes that .catch and
      // would break sign-in on exactly the instances that have writes disabled (the phone). Rejecting
      // preserves the documented fail-open: registry unreachable → treated as not-revoked.
      return () => Promise.reject(new Error('writes disabled: FAVELA_CONTROL_KEY is not set on this instance'))
    }
  })

// ── CONVERGE THE SUBSCRIPTION LIST ACROSS EVERY DEVICE OF THIS IDENTITY ──────────────────────────────
// Devices that host the same DID ARE the same identity, so they should agree on what it subscribes to
// without anyone configuring anything. This merges each node's local roster into the identity's own
// app.bsky.graph.list, which then replicates like any other record.
//
// ⛔ GROW-ONLY UNION, NEVER A REPLACE. The first cut wrote the list wholesale, which made "who booted
// first" decide everyone's roster — a handset won that race against tabertron on 2026-08-25 and its
// derived set became authoritative for the identity (#53). A union is order-independent instead: each
// node contributes only what the list lacks, so any interleaving converges on the same set and there is
// no winner.
//
// ⛔ DETERMINISTIC rkeys. A fresh TID per add means two devices contributing the same DID concurrently
// write TWO records for one membership. resolveRoster dedups by subject so it READS correctly, but the
// repo accumulates duplicates forever. Deriving the rkey from the subject makes the add itself
// idempotent: same membership, same record, second write is a no-op.
//
// ⛔ CONTRIBUTE ONCE PER NODE, then treat the list as authoritative. Grow-only and "re-merge my local
// set every boot" together mean an unsubscribe can never stick: delete a member on one device and the
// next device to boot re-adds it from its own stale local set. The marker below makes contribution a
// one-time act, so removals survive.
//
// Steady state is ZERO writes: nothing new to contribute, nothing written.
const SUBSCRIPTIONS_MARKER = STORE('subscriptions-merged')

// The hash behind the deterministic rkey (lib/lists.js explains why it must be deterministic).
const rkeyHash = (subject) => b4a.toString(crypto.data(b4a.from(subject)), 'hex')

if (!LIST && (HOSTED_DIDS || []).length) {
  const selfDid = HOSTED_DIDS[0]
  const uri = `at://${selfDid}/${LIST_COLLECTION}/${SUBSCRIPTIONS_RKEY}`
  ;(async () => {
    try {
      const st = await writer.state().catch(() => null)
      if (!st || st.did !== selfDid) return // this node does not sign for the identity — not ours to write

      // What this node knows, minus itself: hosted DIDs are subscribed by virtue of being hosted, and a
      // list entry for yourself says nothing.
      const local = ROSTER
      const contributed = fs.existsSync(SUBSCRIPTIONS_MARKER)
      const store = await getRecordStore(selfDid)
      const listRec = await store.get(LIST_COLLECTION, SUBSCRIPTIONS_RKEY)

      if (!listRec) {
        // Create-if-absent. A concurrent create from a sibling device is not an error: whoever loses the
        // race still proceeds to merge, and both arrive at the same list.
        try {
          await writer.putRecord(LIST_COLLECTION, SUBSCRIPTIONS_RKEY, {
            $type: LIST_COLLECTION,
            purpose: CURATE,
            name: 'subscriptions',
            description: 'Identities this account subscribes to. Shared by every device of this identity.',
            createdAt: new Date().toISOString()
          }, { action: 'create' })
        } catch (e) {
          console.log(JSON.stringify({ msg: 'subscriptions: list already created by another device, merging into it', error: e.message }))
        }
      }

      if (contributed) return // already gave this node's set to the list; the list is authoritative now

      // Union: add only what the list does not already have.
      // ⛔ store.list() is an ASYNC GENERATOR yielding { rkey, record } (overlay-repo-store.js:288) —
      // not an array and not the { records } wrapper the P2P peer returns. Awaiting it and testing
      // Array.isArray finds nothing, silently, and every node then re-contributes every boot.
      const already = new Set()
      for await (const { record } of store.list(LISTITEM_COLLECTION)) {
        if (record && record.list === uri && record.subject) already.add(record.subject)
      }
      const missing = missingMembers({ local, listed: [...already], selfDid })
      const createdAt = new Date().toISOString()
      for (const did of missing) {
        await writer.putRecord(LISTITEM_COLLECTION, subscriptionRkey(did, rkeyHash), {
          $type: LISTITEM_COLLECTION, subject: did, list: uri, createdAt
        }, { action: 'create' }).catch(() => {}) // deterministic rkey: a concurrent identical add is a no-op
        addPeer(did).catch(() => {})
      }
      try { fs.writeFileSync(SUBSCRIPTIONS_MARKER, createdAt) } catch {}
      if (missing.length) {
        console.log(JSON.stringify({ msg: 'subscriptions: merged this node\'s roster into the shared list', list: uri, added: missing.length }))
      }
    } catch (e) {
      console.error(JSON.stringify({ msg: 'subscriptions: merge failed (this node keeps its local roster)', error: e.message }))
    }
  })()
}

const readBody = (req) => new Promise((resolve) => { let b = ''; req.on('data', (d) => { b += d }); req.on('end', () => resolve(b)) })
// BINARY-safe body reader. readBody above concatenates onto a STRING, which mangles any byte that is
// not valid UTF-8 — fine for JSON/form posts, silently corrupting for an image. Blob uploads MUST use
// this one. Bounded: an unbounded upload buffered into a Bare daemon is a trivial DoS, and bsky rejects
// blobs over ~1 MB regardless, so refuse early rather than buffer-then-fail.
const MAX_BLOB_BYTES = 1024 * 1024
const readBodyBuffer = (req, max = MAX_BLOB_BYTES) => new Promise((resolve, reject) => {
  const chunks = []
  let n = 0
  req.on('data', (d) => {
    n += d.length
    if (n > max) { reject(Object.assign(new Error('image too large (max ' + Math.floor(max / 1024) + ' KB)'), { code: 'ETOOLARGE' })); try { req.destroy() } catch {}; return }
    chunks.push(b4a.from(d))
  })
  req.on('end', () => resolve(b4a.concat(chunks)))
  req.on('error', reject)
})
// The mime type comes from the BYTES, never the client's content-type header. The header is
// attacker-controlled and it is what ends up inside the SIGNED record, while getBlob serves by sniffing
// magic bytes — trusting the header would let the record disagree with what is actually served.
// Anything not identifiable as an image is refused outright rather than stored as octet-stream.
function imageMimeOrNull (bytes) {
  const m = sniffMime(bytes)
  return m.startsWith('image/') ? m : null
}

// ── DID auth (the pgv3 method via hyper-identity; favela stays keyless) ────────
// FavelaAuth verifies a login proof: the browser's secp256k1 sub-key signs the challenge, and the
// DID's #atproto key delegated that sub-key (verified against the DID's PLC-published key via plc.js +
// bare-fetch). All secp256k1/ES256K, atproto-native. Sessions are cookie tokens; favela holds no key.
const auth = new FavelaAuth({
  resolveVerifyKey: (did) => resolveVerifyKey(did, { fetch: bareFetch })
})
const NODE_CAN_WRITE = true // the node relay writer; per-viewer write authority lands later

// ── Co-owned communities (DESIGN §3.5): keyless read of hyper-rooms rooms → per-viewer scope ──
// favela-web opens each configured community room by its PUBLIC bootstrapKey (no key held) and reads the
// member roster. A signed-in viewer's timeline scopes to the union of member DIDs of the communities they
// belong to. The room's WRITE layer (mods' hpp) is separate (DESIGN step 3) — favela-web only reads.
const commStore = store.namespace('comm') // namespace of the ONE store — see the note at its creation
const communityRooms = new CommunityRooms(commStore, swarm)
const communities = new Communities({ communities: COMMUNITY_ROOMS, resolve: (c) => communityRooms.members(c.roomKey) })

// ── 5B policy: who participates, and who may LOOK ───────────────────────────────────────────────
// isMember reads the room roster favela already replicates; it fails closed (see gate-policy.js).
const isMember = makeIsMember(communities)
// A community closes its site with `set-meta visibility members` — an ordinary meta key, so no schema
// change. Cached: room meta replicates asynchronously and this is consulted per page render. Default
// (and every failure path) is PUBLIC, so a node that never sets it renders exactly as it does today.
let _visCache = { value: PUBLIC, exp: 0 }
const siteVisibilityOnce = async () => {
  if (Date.now() < _visCache.exp) return _visCache.value
  let value = PUBLIC
  try {
    const metas = await Promise.all(COMMUNITY_ROOMS.map((c) => communityRooms.meta(c.roomKey).catch(() => ({}))))
    value = siteVisibility(metas)
  } catch { value = PUBLIC }
  _visCache = { value, exp: Date.now() + 60000 }
  return value
}
// Lens export: one bsky custom feed per community, served from favela's own appview index. Online only when
// both feedgen envs are set; each community registers as a feed (rkey = slug of its id), and getFeedSkeleton
// reads the roster → the appview → bsky-only post URIs. registerFeed is idempotent (Map by rkey).
// Multi-tenant (phase 4): each community's OWN did:plc (bound in its room as meta:did) IS its feed-
// generator service; favela-web just serves getFeedSkeleton for all of them. A community is exported as a
// bsky feed IFF it has bound a DID. registerFeed reads that DID keylessly from the room (async).
const feedgen = new FeedGenerator({ hostname: FEEDGEN_HOSTNAME || null })
// Idempotent + quiet: meta:did replicates ASYNC (the room is opened keyless over the swarm), so it is
// usually NULL when this first runs at startup. Return false and retry on each room update (the watch below
// calls this too) — register exactly once, when meta:did actually arrives. No error spam on the not-yet case.
const registerFeed = async (c) => {
  try {
    const communityDid = await communityRooms.communityDid(c.roomKey)
    if (!communityDid) return false // meta:did not replicated yet — the room watch retries
    const rkey = slugRkey(c.id)
    if (feedgen.has(communityDid, rkey)) return true // already exported (idempotent)
    feedgen.addFeed({ communityDid, rkey, roomKey: c.roomKey, displayName: String(c.id), description: `favela community: ${c.id}` })
    console.log(`[favela] feed export: at://${communityDid}/app.bsky.feed.generator/${rkey} (community "${c.id}")`)
    return true
  } catch (e) { console.error('[favela] registerFeed failed:', c.id, '-', e.message); return false }
}

// ── labeler export: favela's own atproto labeler (shares the did:web identity) ──
// The signing key is derived deterministically from FAVELA_LABELER_SEED; labels are stamped with the
// service DID as `src` and served over queryLabels. Bsky resolves did:web → #atproto_label VM (this key)
// → verifies our label sigs. Production of labels (a mod writing via a co-authored LabelRoom) is the
// full-node integration; this exposes whatever the local Labeler feed holds.
let labeler = null
let labelerExport = null
// Module-scope so shutdown() can close it: it is the one store that is NOT a namespace of `store`.
let labelerStore = null
if (SERVICE_DID && LABELER_SEED) {
  // ⚠ DELIBERATELY ITS OWN Corestore — do NOT fold this into the namespaced `store` above.
  // This is the one core favela AUTHORS rather than replicates: Labeler does
  // `corestore.get({ name })`, a DERIVED key, and PUBLISHES it as `feedKey` — "consumers replicate the
  // feed BY KEY and VERIFY each label" (lib/labeler.js:2). Namespacing changes that derived key, which
  // would silently strand every existing subscriber and orphan the label history. Identity itself is
  // safe either way (the signing key is seed-derived: crypto.hash(LABELER_SEED) -> did:key, which is
  // what consumers verify against) — it is DISCOVERY that breaks, and only republishing the new key
  // would recover it. Consumed labeler feeds are different: those live on didStore, fetched by key.
  // The extra RocksDB floor (~75 MB) is the price of keeping "state we author" separable from "state we
  // replicate or derive". Folding it in is only safe once Labeler accepts an EXPLICIT keypair.
  labelerStore = new Corestore(STORE('web-labeler'))
  labeler = await new Labeler(labelerStore, { privateKey: crypto.hash(b4a.from(LABELER_SEED)), src: SERVICE_DID, name: 'favela-labeler' }).ready()
  const source = {
    labels: async () => {
      const core = labeler.core
      await core.ready()
      const out = []
      for (let i = 0; i < core.length; i++) { try { out.push(decodeLabel(await core.get(i))) } catch {} }
      return out
    }
  }
  labelerExport = new LabelerExport({ labelerDid: SERVICE_DID, signingDidKey: labeler.didKey, hostname: FEEDGEN_HOSTNAME, source, labelValues: LABELER_VALUES })
  console.log(`[favela] labeler export online: ${SERVICE_DID} (#atproto_labeler) values=[${LABELER_VALUES.join(',')}]`)
}
// The live-push firehose (com.atproto.label.subscribeLabels) over the labeler's feed core (phase 5).
const labelFirehose = labeler ? await new LabelFirehose(labeler.core).ready() : null

// The combined did:web document — one identity, whichever export surfaces are configured. The labeler
// adds a #atproto_label verificationMethod (its signing key) + a Multikey @context; the feedgen adds its
// service entry. Served at /.well-known/did.json whenever SERVICE_DID is set.
function buildDidDoc () {
  // favela-web's own did:web doc carries ONLY the (favela-owned, 3B) labeler — communities are their own
  // feed-generator + labeler services (did:plc), advertised via their OWN PLC docs, not here.
  const doc = { '@context': ['https://www.w3.org/ns/did/v1'], id: SERVICE_DID, service: [] }
  if (labelerExport) {
    doc['@context'].push('https://w3id.org/security/multikey/v1')
    doc.verificationMethod = [labelerExport.verificationMethod()]
    doc.service.push(labelerExport.service())
  }
  return doc
}
// Watch each community room's roster so members are indexed NOW (baseline) AND when they change LATER — with
// NO restart (DESIGN §7 roster watcher). On any roster change: addPeer new member DIDs (so their posts flow
// into the index) and invalidate the per-viewer scope cache for that community (so scopeFor re-resolves at
// once instead of waiting out the TTL). watch() opens the room (joining its discoveryKey) and fires an
// initial baseline, so this subsumes the old one-shot boot index. Best-effort + background so it never
// blocks the HTTP server; rooms replicate async, so each replicated membership op re-fires the watcher and
// the roster is eventually-consistent.
if (COMMUNITY_ROOMS.length || COMMUNITY_NAMES.length) {
  ;(async () => {
    try {
      // Resolve any human community NAMES to roomKeys over the DHT, then treat them like configured rooms.
      // A name not yet announced (owner offline) is skipped with a log — it resolves on a later boot.
      if (COMMUNITY_NAMES.length) {
        const disc = new CommunityDiscovery(swarm.dht)
        for (const name of COMMUNITY_NAMES) {
          try {
            const roomKey = await disc.resolve(name)
            if (!roomKey) { console.error('[favela] community name not found on the DHT (owner offline?):', name); continue }
            if (COMMUNITY_ROOMS.some((c) => c.roomKey === roomKey)) continue // already configured by key
            const c = { id: name, roomKey }
            communities.add(c)      // so scopeFor covers it
            COMMUNITY_ROOMS.push(c) // so the watch loop below covers it (feed registration happens there)
            console.log(`[favela] resolved community "${name}" → ${roomKey.slice(0, 12)}…`)
          } catch (e) { console.error('[favela] community name resolve failed:', name, '-', e.message) }
        }
      }
      for (const c of COMMUNITY_ROOMS) {
        await registerFeed(c) // try now; if meta:did hasn't replicated yet the watch (below) registers it
        await communityRooms.watch(c.roomKey, async (memberDids) => {
          await registerFeed(c) // meta:did replicates async — register the feed the moment it arrives (idempotent)
          communities.invalidate(c.id) // roster changed → drop this community's cached scope
          for (const did of memberDids) {
            if (byDid.has(did)) continue
            try { await addPeer(did) } catch (e) { console.error('[favela] community member index failed', did, '-', e.message) }
          }
        })
      }
      await swarm.flush()
      console.log(`[favela] watching ${COMMUNITY_ROOMS.length} community room(s) for roster changes`)
    } catch (e) { console.error('[favela] community watch setup failed:', e.message) }
  })()
}
// ── Feed registries (community-ux.md §120): REACT to the durable P2P feed list — no per-community env, no
// restart. favela-web watches each configured FeedRegistry (the keyless allow-set) and reconciles the feeds
// it serves to the registry's entries: add-feed → serve getFeedSkeleton + wire the roster into the index +
// viewer scope; remove-feed → stop serving. This SUPERSEDES the static FAVELA_COMMUNITY_* config — a feed
// published into the registry is picked up live. wireRoster mirrors the env path's roster watcher above.
if (FEED_REGISTRIES.length) {
  const feedRegistries = new FeedRegistries(commStore, swarm)
  const wireRoster = async (id, roomKey) => {
    const c = { id, roomKey }
    communities.add(c)                                                              // so scopeFor covers it
    if (!COMMUNITY_ROOMS.some((x) => x.roomKey === roomKey)) COMMUNITY_ROOMS.push(c) // so scopeOf activates
    await communityRooms.watch(roomKey, async (memberDids) => {
      communities.invalidate(id) // roster changed → drop this community's cached scope
      for (const did of memberDids) {
        if (byDid.has(did)) continue
        try { await addPeer(did) } catch (e) { console.error('[favela] registry member index failed', did, '-', e.message) }
      }
    })
  }
  const reconcile = makeFeedReactor({ feedgen, wireRoster, log: (m) => console.log(m) })
  ;(async () => {
    try {
      for (const regKey of FEED_REGISTRIES) {
        await feedRegistries.watch(regKey, (feeds) => reconcile(regKey, feeds))
        console.log(`[favela] watching feed registry ${regKey.slice(0, 12)}… for feed add/remove`)
      }
      await swarm.flush()
    } catch (e) { console.error('[favela] feed registry watch setup failed:', e.message) }
  })()
}

// A signed-in viewer's per-request author scope. null (anonymous / community-less / no rooms) → global.
const scopeOf = async (viewer) => (viewer && COMMUNITY_ROOMS.length ? await communities.scopeFor(viewer.did) : null)

const COOKIE = 'favela_session'
// ONE extraction path (lib/check.js, ported from pear-git-v3). This was a hand-rolled cookie regex
// here plus a second read in the logout branch — the shape that lets two callers disagree about who
// is signed in. extractToken also accepts `Authorization: Bearer`, so a non-browser client can
// authenticate without a cookie jar. The loopback /auth/handoff is unaffected: it takes its token
// from the query string, never from here.
const parseCookie = (req) => extractToken(req)
const viewerOf = (req) => extractIdentity(req, auth.sessions)

// WHICH repo does this node write to? Asked of the hpp, never assumed — and cached, because the write
// gate consults it on every mutating request and it is a property of the node, not of the request.
// Unresolved stays null so the gate DENIES: an instance with no write transport (the stortron lens)
// must refuse writes, not guess a target.
let _repoDid = null
const repoDidOnce = async () => {
  if (_repoDid) return _repoDid
  try { _repoDid = ((await writer.state()) || {}).did || null } catch { _repoDid = null }
  return _repoDid
}
const SESSION_COOKIE = (token) => `${COOKIE}=${token}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${30 * 24 * 3600}`
const CLEAR_COOKIE = `${COOKIE}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0`

// Write-gate tiers (see the gate itself, at the top of the request handler). Listed here so the
// classification of a route is one grep away, not buried mid-file.
//
// OPEN: no session required. The auth routes ESTABLISH one, so gating them on having one would be
// circular. /api/theme is here for a different reason: it writes NOTHING server-side — its only
// effect is a cookie in the caller's own browser — and it must work on a read-only lens instance,
// which is the first thing the gate below refuses. A reader who is not signed in still gets to
// choose dark.
const OPEN_POST = new Set(['/api/auth/login', '/api/auth/pair', '/api/auth/logout', '/api/auth/challenge', '/api/theme'])
// IDENTITY: self-scoped or node-local. /api/devices/* act on the caller's OWN delegated sub-keys;
// track/bookmark/mute mutate this node's local index and stores only — nothing is signed into a repo,
// so repo ownership is not the relevant question, but anonymity still is.
const IDENTITY_POST = new Set([
  '/api/devices/pair', '/api/devices/invite', '/api/devices/revoke',
  // /api/lens changes where THIS NODE reads from — node-local, nothing signed into a repo, so repo
  // ownership is not the question. It carries its own stricter check (viewer must be the identity this
  // node signs for), because repointing a node's reads is an operator act, not a viewer preference.
  '/api/lens',
  '/api/track', '/api/bookmark', '/api/mute'
])
// Everything else POSTed authors a record (or a blob) into the repo and falls through to the
// repo-owner check. Deliberately NOT enumerated: an unlisted route must fail closed.

// Theme is applied HERE rather than threaded through a dozen page functions, because it affects
// exactly one attribute on <html> and every HTML response already funnels through this helper. The
// value is stamped on `res` by the request handler below — the response object is per-request, so
// there is no shared state to race.
//
// Server-side, so the first paint is correct. A script that flips a class after load would flash the
// wrong theme on every navigation and would never run at all with scripting off.
const html = (res, status, body, extra) => {
  const t = res._theme
  const themed = (t === 'dark' || t === 'light') && typeof body === 'string'
    ? body.replace('<html lang="en">', `<html lang="en" data-theme="${t}">`)
    : body
  res.writeHead(status, { 'content-type': 'text/html; charset=utf-8', ...(extra || {}) })
  res.end(themed)
}
// system | light | dark. Absent or unrecognised means system, which is what everyone had before this
// existed, so an old cookie or a hand-edited one degrades to the previous behaviour rather than to a
// broken page.
const THEMES = new Set(['light', 'dark'])
function themeOf (req) {
  const raw = (req.headers && req.headers.cookie) || ''
  const m = raw.match(/(?:^|;\s*)favela_theme=([a-z]+)/)
  return m && THEMES.has(m[1]) ? m[1] : null
}
const json = (res, status, body, extra) => { res.writeHead(status, { 'content-type': 'application/json', ...(extra || {}) }); res.end(body) }
const xml = (res, status, body, type) => { res.writeHead(status, { 'content-type': type }); res.end(body) }
const redirect = (res, to, extra) => { res.writeHead(303, { location: to, ...(extra || {}) }); res.end() }
const server = http.createServer(async (req, res) => {
  try {
    const url = new URL(req.url, 'http://localhost')
    const path = url.pathname
    const viewer = viewerOf(req) // { did, subKey } from the session cookie/Bearer, or null (anonymous)
    res._theme = themeOf(req) // read once per request; html() applies it to whatever page is rendered

    // ── WRITE GATE — one choke point, default-deny ──────────────────────────────────────────────
    //
    // Every mutating route used to carry (or forget) its own `if (!viewer)`. /api/post forgot, and on
    // 2026-08-11 an anonymous request created a post in wj62; the images branch of that same handler
    // had the check, which is why inspection missed it. pgv3 puts its read gate at ONE point above
    // ~14 routes for exactly this reason: per-route checks are per-route chances to forget, and a
    // route added later defaults to open. Here the default is DENY — a new POST route is gated as a
    // repo write until someone deliberately lists it otherwise.
    //
    // Tiers, most open first:
    //   OPEN      — establish the session; requiring one would be circular.
    //   IDENTITY  — self-scoped: acts on the caller's own devices, or on state that never leaves
    //               this node. A live, non-revoked session is the whole requirement.
    //   (default) — AUTHORS A RECORD INTO THE REPO. Requires that the caller OWN that repo.
    //
    // ⛔ The repo owner check is the load-bearing one. `Writer` speaks to a single hpp control socket,
    // so a write authors as THAT DID whoever is signed in — and sign-in admits any DID that can prove
    // a delegation from its own #atproto key. Without this, any atproto account posts as wj62.
    if (req.method === 'POST' && !OPEN_POST.has(path)) {
      // ⛔ SAY "READ-ONLY" BEFORE ASKING AN HPP THAT ISN'T THERE. A lens instance (stortron) has no
      // write transport, so every hpp call throws — including the device-revocation check. Fail-closed
      // then surfaced as "this device has been revoked" to a signed-in user whose device was perfectly
      // fine. Reported live on favela.7rnx.net. The refusal is right; the reason was a fabrication.
      if (!writeTransportConfigured(process.env)) {
        console.log(JSON.stringify({ msg: 'write refused', path, viewer: viewer ? viewer.did : null, status: 403, reason: 'read-only instance' }))
        return json(res, 403, JSON.stringify({ error: 'this instance is read-only — it serves feeds and cannot author records' }))
      }
      const ctx = { identity: viewer }
      const isDeviceRevoked = (k) => writer.isDeviceRevoked(k)
      try {
        if (IDENTITY_POST.has(path)) await requireIdentity(ctx, { isDeviceRevoked, failOpen: false })
        else {
          await requireRepoOwner(ctx, { repoDid: await repoDidOnce(), isDeviceRevoked })
          if (REQUIRE_MEMBERSHIP) await requireMember(ctx, { isMember, isDeviceRevoked })
        }
      } catch (e) {
        const status = e.status || 403
        console.log(JSON.stringify({ msg: 'write refused', path, viewer: viewer ? viewer.did : null, status, reason: e.message }))
        return json(res, status, JSON.stringify({ error: e.message }))
      }
    }

    // ── READ GATE — a community may CLOSE its site (`set-meta visibility members`) ──────────────
    // INERT unless every configured community asks to close (gate-policy.siteVisibility defaults to
    // public), so a node that never sets the flag renders exactly as it does today. Exemptions live in
    // isPublicPath and are load-bearing: gate /login or /api/auth/* and a visitor can never STOP being
    // anonymous, turning "members only" into "nobody, ever". /xrpc stays open because bsky's AppView
    // reads the lens anonymously. POSTs are already covered by the write gate above.
    if (req.method === 'GET' && !viewer && !isPublicPath(path) && (await siteVisibilityOnce()) === MEMBERS) {
      return redirect(res, '/login')
    }

    // ── auth (the browser client drives these; favela verifies keylessly) ──
    if (path === '/api/auth/challenge') {
      return json(res, 200, JSON.stringify({ challenge: auth.mintChallenge() }))
    }
    // SESSION HANDOFF — for a UI rendered in an embedded WebView (favela-android). The worklet signs in
    // over this same loopback API and holds the token; the WebView has a separate cookie jar and no way
    // to be given one, so without this every page it renders is anonymous. Swaps a token the caller
    // already holds for the cookie form of the SAME session — see handoffDecision for why it refuses
    // unknown tokens, off-box callers and non-local `next` values.
    if (path === '/auth/handoff') {
      const d = handoffDecision({
        token: url.searchParams.get('token'),
        next: url.searchParams.get('next'),
        remoteAddress: req.socket && req.socket.remoteAddress,
        isValid: (t) => !!auth.get(t)
      })
      if (!d.ok) return html(res, 403, '<h1>handoff refused</h1><p>' + esc(d.reason || 'refused') + '</p>')
      return redirect(res, d.next, { 'set-cookie': SESSION_COOKIE(d.token) })
    }
    if (req.method === 'POST' && path === '/api/auth/login') {
      let proof
      try { proof = JSON.parse((await readBody(req)) || '{}') } catch { return json(res, 400, JSON.stringify({ error: 'bad json' })) }
      try {
        const s = await auth.login(proof) // verifies chain + PLC-anchors first bind; throws on any failure
        // REVOCATION GATE (Option 3): the delegation is cryptographically valid, but the DID may have
        // REVOKED this sub-key in the persistent device registry. Check via the local hpp. Fail-open if
        // the registry is unreachable — the delegation still holds; revocation is a best-effort second gate.
        if (proof.subKey && await writer.isDeviceRevoked(proof.subKey).catch(() => false)) {
          auth.revoke(s.token)
          return json(res, 403, JSON.stringify({ error: 'this device has been revoked' }))
        }
        return json(res, 200, JSON.stringify({ did: s.did, handle: s.handle }), { 'set-cookie': SESSION_COOKIE(s.token) })
      } catch (e) { return json(res, 401, JSON.stringify({ error: e.message })) }
    }
    // hpp-INITIATED pairing (the fix for the backwards flow): the browser pastes ONE hash-URL invite the
    // hpp minted; favela-web joins the blind-pairing tunnel, sends the browser's sub-key up, and gets the
    // delegation back — no manual delegation shuttle. The browser still signs the challenge (proves it holds
    // the sub-key secret); favela-web fetches the delegation via the invite, then runs the SAME auth.login.
    if (req.method === 'POST' && path === '/api/auth/pair') {
      let body
      try { body = JSON.parse((await readBody(req)) || '{}') } catch { return json(res, 400, JSON.stringify({ error: 'bad json' })) }
      const { invite, subKey, challenge, sig } = body
      if (!invite || !subKey || !challenge || !sig) return json(res, 400, JSON.stringify({ error: 'invite, subKey, challenge, sig required' }))
      try {
        const del = await joinPairInvite(String(invite).trim(), { subKey }) // { did, subKey, delegation, exp } from the hpp
        if (del.subKey && del.subKey.toLowerCase() !== String(subKey).toLowerCase()) return json(res, 401, JSON.stringify({ error: 'delegation is for a different sub-key' }))
        const s = await auth.login({ did: del.did, subKey, delegation: del.delegation, challenge, sig })
        // Revocation gate (Option 3) — a previously-revoked sub-key stays revoked until explicitly restored.
        if (await writer.isDeviceRevoked(subKey).catch(() => false)) {
          auth.revoke(s.token)
          return json(res, 403, JSON.stringify({ error: 'this device has been revoked — restore it or use a new browser identity' }))
        }
        // Return the delegation so the browser PERSISTS it (localStorage) and can re-sign-in silently
        // after a favela-web restart — no re-paste of the invite. (pgv3-parity persistence.)
        return json(res, 200, JSON.stringify({ did: s.did, handle: s.handle, delegation: del.delegation }), { 'set-cookie': SESSION_COOKIE(s.token) })
      } catch (e) { return json(res, 401, JSON.stringify({ error: e.message })) }
    }
    // Session identity for the browser client (cookie is HttpOnly → can't be read in JS). Always 200:
    // { did } when signed in, { did: null } when anonymous.
    if (path === '/api/auth/me') {
      return json(res, 200, JSON.stringify({ did: viewer ? viewer.did : null }))
    }
    if (path === '/logout' || (req.method === 'POST' && path === '/api/auth/logout')) {
      const t = parseCookie(req); if (t) auth.revoke(t)
      // no-JS GET → redirect home; client POST → 200 (it re-renders itself).
      if (req.method === 'POST') return json(res, 200, JSON.stringify({ ok: true }), { 'set-cookie': CLEAR_COOKIE })
      return redirect(res, '/', { 'set-cookie': CLEAR_COOKIE })
    }
    // Device management (Option 3): the signed-in DID-holder lists + revokes/restores the DID's delegated
    // browser sub-keys. Gated on a live session; the hpp additionally enforces its writer-allowlist. The
    // registry is persistent + replicated, so a revoke propagates to every device and every login check.
    // Mint a pairing invite from the WEB UI. `favela-web pair` has been able to do this since 0.2.15;
    // the browser could only ever CONSUME an invite (POST /api/auth/pair), so adding a second device
    // meant shell access to the box running favela-web. That is the wrong requirement for "sign in on my
    // phone" — this closes the loop: generate here, paste at /login there.
    //
    // The invite object is LONG-LIVED (it holds a blind-pairing member on a Hyperswarm and resolves only
    // when a browser joins), so it cannot live inside the request. It is parked per-DID and torn down on
    // whichever comes first: a successful pair, the TTL, or the DID minting a replacement. ONE live invite
    // per DID — minting again supersedes the previous one rather than accumulating swarms, which is both
    // the safer resource story and the more obvious semantics (the newest code is the one that works).
    if (req.method === 'POST' && path === '/api/devices/pair') {
      if (!viewer) return json(res, 401, JSON.stringify({ error: 'sign in first' }))
      let body; try { body = JSON.parse((await readBody(req)) || '{}') } catch { body = {} }
      const rawLabel = typeof body.label === 'string' ? body.label.trim() : ''
      const label = rawLabel ? rawLabel.slice(0, 64) : null
      await closePendingPair(viewer.did)
      try {
        // onSubkey fires when the far browser presents its sub-key: the DID delegates it via the hpp.
        // favela holds no key — the delegation is minted by the key-holder, exactly as the CLI does.
        const source = await createPairInvite({ onSubkey: (sk) => writer.delegate(sk, { label }) })
        const expiresAt = Date.now() + PAIR_TTL_MS
        const timer = setTimeout(() => { closePendingPair(viewer.did).catch(() => {}) }, PAIR_TTL_MS)
        if (typeof timer.unref === 'function') timer.unref()
        pendingPairs.set(viewer.did, { source, timer })
        // Resolve in the background and tear down either way — waitForPeer() rejects on timeout, and an
        // un-awaited rejection here would be an unhandled promise, not a leak we notice later.
        source.waitForPeer().then(
          () => closePendingPair(viewer.did).catch(() => {}),
          () => closePendingPair(viewer.did).catch(() => {})
        )
        return json(res, 200, JSON.stringify({
          inviteHex: source.inviteHex,
          loginUrl: EXTERNAL_URL + '/login#pair=' + source.inviteHex,
          expiresAt
        }))
      } catch (e) { return json(res, 502, JSON.stringify({ error: 'could not mint an invite: ' + e.message })) }
    }
    // ── DEVICE INVITE (a NODE, not a browser) ────────────────────────────────────────────────────────
    //
    // ⛔ NOT /api/devices/pair. That mints a DELEGATION for a browser: a sub-key the DID vouches for,
    // where every signature is still made by an hpp. This mints the CO-OWNER BUNDLE — the shared signing
    // key plus a chained attestation — which is what a device needs to become another peer on the DID's
    // swarm and sign its own commits offline (favela-android, or a second server).
    //
    // The two are trivially confusable and the confusion is SILENT: paste a browser invite into a node
    // and its 64-hex keet device key is rejected by delegate() (which wants 66-hex secp256k1), the source
    // never confirms, and the joiner waits out a five-minute timeout with no error. Hence a separate
    // route with its own wording.
    //
    // The tunnel must OUTLIVE the request, so the source is held in memory here and the page polls it.
    // One live invite per DID: minting a second would leave the first dangling with no way to close it.
    if (req.method === 'POST' && path === '/api/devices/invite') {
      if (!viewer) return json(res, 401, JSON.stringify({ error: 'sign in first' }))
      let body; try { body = JSON.parse((await readBody(req)) || '{}') } catch { body = {} }
      const did = body.did || viewer.did
      if (!did) return json(res, 400, JSON.stringify({ error: 'did required' }))
      const live = deviceInvites.get(did)
      if (live && !live.done) return json(res, 200, JSON.stringify({ inviteHex: live.inviteHex, state: live.state, reused: true }))
      try {
        const { mintAdoptInvite } = await import('hyper-proto-peer/lib/adopt.js')
        // Approval IS this request: it is owner-gated by the session, and coownerInvite mutates the
        // roster + hands over the signing key, so it must never fire speculatively.
        const src = await mintAdoptInvite({ did, approve: () => true })
        const rec = { inviteHex: src.inviteHex, state: 'waiting', done: false, src }
        deviceInvites.set(did, rec)
        src.waitForPeer()
          .then((r) => { rec.state = r ? ('joined: ' + String(r.devicePublicKey).slice(0, 16) + '…') : 'refused'; rec.done = true })
          .catch((e) => { rec.state = 'failed: ' + (e && e.message); rec.done = true })
          .then(() => { try { src.close() } catch {} })
        return json(res, 200, JSON.stringify({ inviteHex: rec.inviteHex, state: rec.state }))
      } catch (e) { return json(res, 502, JSON.stringify({ error: 'mint failed: ' + e.message })) }
    }
    if (path === '/api/devices/invite') {
      if (!viewer) return json(res, 401, JSON.stringify({ error: 'sign in first' }))
      const rec = deviceInvites.get(viewer.did)
      return json(res, 200, JSON.stringify(rec ? { inviteHex: rec.inviteHex, state: rec.state, done: rec.done } : { state: 'none' }))
    }
    if (path === '/api/devices') {
      if (!viewer) return json(res, 401, JSON.stringify({ error: 'sign in first' }))
      try { return json(res, 200, JSON.stringify({ devices: await writer.listDevices() })) }
      catch (e) { return json(res, 502, JSON.stringify({ error: 'device registry unreachable: ' + e.message })) }
    }
    if (req.method === 'POST' && path === '/api/devices/revoke') {
      if (!viewer) return json(res, 401, JSON.stringify({ error: 'sign in first' }))
      let body; try { body = JSON.parse((await readBody(req)) || '{}') } catch { return json(res, 400, JSON.stringify({ error: 'bad json' })) }
      if (!body.subKey) return json(res, 400, JSON.stringify({ error: 'subKey required' }))
      try { return json(res, 200, JSON.stringify(await writer.revokeDevice(body.subKey, { restore: !!body.restore }))) }
      catch (e) { return json(res, 502, JSON.stringify({ error: e.message })) }
    }
    // Settings — currently just the avatar. Reads the CURRENT profile record from the shared overlay
    // store (the same files hpp writes) so the page shows what is actually published, not a guess.
    if (path === '/settings') {
      let profile = null
      let did = viewer ? viewer.did : null
      if (viewer) {
        try {
          const st = await writer.state().catch(() => null)
          if (st && st.did) did = st.did // the DID this node actually signs for
          const store = await getRecordStore(did)
          profile = await store.get('app.bsky.actor.profile', 'self')
        } catch {}
      }
      // Devices are rendered SERVER-SIDE so the list is visible with JS off; only the actions
      // (pair / revoke) are progressive enhancement, matching how the avatar section already works.
      let devices = []
      if (viewer) { try { devices = await writer.listDevices() } catch { devices = [] } }
      // App updates, on a handset only. FAVELA_SHELL_STATE is set by favela-android's worklet and by
      // nothing else, so a server never renders the section — `appUpdateSection(null)` is ''. Read per
      // request rather than at boot: a check performed while this page is open must be visible on the
      // next render, and the file is four fields.
      let shell = null
      if (process.env.FAVELA_SHELL_STATE) {
        try { shell = JSON.parse(fs.readFileSync(process.env.FAVELA_SHELL_STATE, 'utf8')) } catch { shell = null }
      }
      // The lens control is shown only to the identity this node signs for — the same test /api/lens
      // itself enforces, so the page never offers a control the route will refuse.
      let isOperator = false
      if (viewer) { try { const st = await writer.state(); isOperator = !!(st && st.did && st.did === viewer.did) } catch {} }
      const lens = { enabled: LENSES_ON, lenses: LENSES.map((l) => ({ name: l.name, base: l.base })) }
      return html(res, 200, settingsPage({ viewer, profile, did, devices, theme: res._theme, shell, lens, isOperator }))
    }
    if (path === '/login') {
      // Sign-in UI: the client script (/static/login.js) generates the browser's secp256k1 sub-key,
      // drives pairing (paste the hpp-minted delegation) + the challenge→sign→session flow. favela
      // stays keyless — the sub-key secret never leaves the browser.
      return html(res, 200, loginPage({ viewer }))
    }
    // Browser-side client + vendored crypto (served from web/static/).
    if (path.startsWith('/static/')) {
      if (await serveStatic(path.slice('/static/'.length), res)) return
      return json(res, 404, JSON.stringify({ error: 'not found' }))
    }

    // com.atproto.sync.getBlob — serve a DID's blob (avatar/image) from the SHARED overlay files (slice 3b):
    // ONE physical copy, the same files hpp writes. Content-addressed → immutable-cacheable. Content-type
    // sniffed from the bytes (the mimeType lives in the record's blob ref, not the file).
    if (path === '/xrpc/com.atproto.sync.getBlob') {
      const bdid = url.searchParams.get('did'); const bcid = url.searchParams.get('cid')
      if (!bdid || !isSafeCid(bcid)) return json(res, 400, JSON.stringify({ error: 'InvalidRequest', message: 'did + cid required' }))
      let bytes = null
      try { bytes = await readFile(blobPath(OVERLAY_ROOT, bdid, bcid)) } catch { bytes = null }
      // A local miss used to be the END of it, which made this surface work only for a DID whose blob
      // bytes happen to be co-located on THIS box. Measured: wj62 served its avatar (1 blob present)
      // while every e2jev image 404'd — those bytes live on ashatron in the LEGACY Hyperbee blob store,
      // which never replicates, so waiting could never help. Fall back to asking the peer that HOLDS the
      // blob, exactly as the keyless bridge does (peer-front.getBlob -> hpp's get-blob RPC). Works for
      // both backends: the holder answers from its overlay files or its legacy store, whichever it has.
      if (!bytes) {
        const relayed = await relayBlob(bdid, bcid)
        // ⛔ VERIFY BEFORE SERVING, not just before storing. The CID *is* the hash, so a front that
        // returns the wrong body cannot pass — and this used to be served straight through, which made
        // any peer answering get-blob able to put arbitrary content under someone else's avatar.
        if (relayed && await verifyBlobCid(relayed, bcid)) {
          bytes = relayed
          // ★ RETAIN. Content-addressed bytes we already hold have no reason to be fetched twice, and a
          // node that keeps them becomes a SOURCE — which is the whole point of a content-addressed
          // store and the thing this surface was missing. Measured 2026-08-24: tabertron served two of
          // e2jev's blobs from disk while stortron 404'd the same CIDs, because a keyless reader had
          // exactly two routes — local file, or ask the holder — and no way to keep what it was given.
          // With this, the first request while a holder is up is the last one that needs it up.
          //
          // Best-effort: a failed write must never fail the response. We have the bytes; the reader
          // gets them either way.
          retainBlob(bdid, bcid, relayed).catch(() => {})
        } else if (relayed) {
          console.error(JSON.stringify({ msg: 'relayed blob failed content-address verification — refusing', did: bdid, cid: String(bcid).slice(0, 20) }))
        }
      }
      if (!bytes) return json(res, 404, JSON.stringify({ error: 'BlobNotFound' }))
      res.writeHead(200, { 'content-type': sniffMime(bytes), 'cache-control': 'public, max-age=31536000, immutable' })
      return res.end(bytes)
    }

    // ── lens export (DESIGN §3.6): did:web identity + feed generator + labeler, when configured ──
    // did:web resolution: bsky fetches this to find our feedgen/labeler service endpoints + signing key.
    if (SERVICE_DID && path === '/.well-known/did.json') {
      return json(res, 200, JSON.stringify(buildDidDoc()))
    }
    // com.atproto.label.queryLabels — the labeler pull surface (labels for uriPatterns/sources).
    if (labelerExport && path === '/xrpc/com.atproto.label.queryLabels') {
      const uriPatterns = url.searchParams.getAll('uriPatterns')
      const sources = url.searchParams.getAll('sources')
      const limit = Math.min(Number(url.searchParams.get('limit')) || 50, 250)
      const cursor = url.searchParams.get('cursor') || null
      const body = await labelerExport.queryLabels({ uriPatterns, sources: sources.length ? sources : null, limit, cursor })
      return json(res, 200, JSON.stringify(body))
    }
    if (feedgen) {
      if (path === '/xrpc/app.bsky.feed.describeFeedGenerator') {
        return json(res, 200, JSON.stringify(feedgen.describe(url.searchParams.get('did') || null)))
      }
      if (path === '/xrpc/app.bsky.feed.getFeedSkeleton') {
        let algo
        try { algo = feedgen.resolve(url.searchParams.get('feed')) } catch (e) { return json(res, e.status || 400, JSON.stringify({ error: e.error || 'InvalidRequest', message: e.message })) }
        const limit = Math.min(Number(url.searchParams.get('limit')) || 50, 100)
        const cursor = url.searchParams.get('cursor') || null
        const body = await feedgen.skeleton(algo, {
          rosterOf: (roomKey) => communityRooms.members(roomKey),
          curationOf: (roomKey) => communityRooms.curation(roomKey),
          getTimeline: (opts) => av.getTimeline(opts),
          getTagFeed: (tag, opts) => av.getTagFeed(tag, opts),
          limit,
          cursor
        })
        // A feed skeleton is DYNAMIC (new roster posts every minute). Tell bsky's AppView + any CDN/proxy
        // (there is an Apache reverse proxy in front of us) NEVER to cache it, so every getFeed re-poll
        // returns the current posts. Without this, an intermediary serves a stale skeleton and the feed
        // appears "stuck" days behind while the generator itself is current (atproto feeds are pull-only —
        // there is no push-new-posts signal, so this header is the freshness lever we control).
        return json(res, 200, JSON.stringify(body), { 'cache-control': 'no-store, no-cache, max-age=0, must-revalidate' })
      }
    }

    // Fill in bylines for authors this node holds NO profile record for — a bsky account whose posts
    // arrived through the inbound lens has a name and picture nowhere in our index, so it rendered as a
    // grey circle and a short DID while the SAME account showed correctly on its profile page (0.3.12
    // fixed the page and not the byline).
    //
    // Done HERE and not in the appview on purpose: the appview is the index layer and must not make
    // network calls during hydration. Bounded per page — distinct DIDs only, capped — and the lens reader
    // caches, single-flights and circuit-breaks, so a timeline of 50 posts by 3 foreign authors costs at
    // most 3 requests, and a repeat view costs none.
    //
    // Only displayName + avatar are taken. The HANDLE is deliberately NOT: a handle is an identity claim
    // and this codebase only ever renders one it has verified bidirectionally (see byline). A display
    // name is a label, not a claim of identity.
    const LENS_BYLINE_CAP = 12
    // Stamp the viewer's own bookmarks onto a result. One scan per render rather than a lookup per post.
    async function withBookmarks (result, viewerDid) {
      if (!viewerDid || !result || !Array.isArray(result.posts) || !result.posts.length) return result
      const saved = await bookmarkStore.uris(viewerDid)
      if (saved.size) for (const p of result.posts) { if (p && p.uri && saved.has(p.uri)) p.viewerBookmarked = true }
      return result
    }

    async function withLensBylines (result) {
      if (!lensReader || !LENSES.length || !result || !Array.isArray(result.posts) || !result.posts.length) return result
      const need = []
      const seen = new Set()
      for (const p of result.posts) {
        const a = p && p.author
        if (!a || !a.did || a.displayName || a.avatar || a.avatarUrl) continue
        if (seen.has(a.did)) continue
        seen.add(a.did)
        if (need.length < LENS_BYLINE_CAP) need.push(a.did)
      }
      // A QUOTED post carries its OWN author, so a quote of a bsky post shows a blank card author on every
      // surface at once. Same fill, same budget.
      for (const p of result.posts) {
        const qa = p && p.quoted && p.quoted.author
        if (!qa || !qa.did || qa.displayName || qa.avatar || qa.avatarUrl) continue
        if (seen.has(qa.did)) continue
        seen.add(qa.did)
        if (need.length < LENS_BYLINE_CAP) need.push(qa.did)
      }
      if (!need.length) return result
      const lens = LENSES[0]
      const found = new Map()
      await Promise.all(need.map(async (did) => {
        try {
          const body = await lensReader.get(lens, 'app.bsky.actor.getProfile', { actor: did })
          if (body && (body.displayName || body.avatar)) found.set(did, { displayName: body.displayName || null, avatarUrl: typeof body.avatar === 'string' ? body.avatar : null })
        } catch { /* a byline without a picture is not worth failing a page over */ }
      }))
      if (!found.size) return result
      const fill = (a) => {
        const hit = a && a.did ? found.get(a.did) : null
        if (!hit) return
        if (!a.displayName && hit.displayName) a.displayName = hit.displayName
        if (!a.avatarUrl && hit.avatarUrl) a.avatarUrl = hit.avatarUrl
      }
      for (const p of result.posts) {
        fill(p && p.author)
        fill(p && p.quoted && p.quoted.author)
      }
      return result
    }

    // ── SSR pages (no JS required) ─────────────────────────────
    if (path === '/') {
      // `cursor` is read straight off the query string so paging works with NO JS — the "older posts"
      // link is a plain <a>. Before this the cursor was computed on every request and discarded, so a
      // reader could never see past the newest 50 posts.
      const result = await withBookmarks(await withLensBylines(await withMod(await av.getTimeline({ limit: 50, cursor: url.searchParams.get('cursor') || null, authors: await scopeOf(viewer), viewerDid: viewer ? viewer.did : null }), viewer ? viewer.did : null)), viewer ? viewer.did : null)
      // ?quote=<at-uri> loads the composer with that post attached. Hydrated here so the composer can
      // PREVIEW what is being quoted — without it the form looks identical to a normal one and you cannot
      // tell what, or whether, you are quoting. Unresolvable → no preview and no hidden field, so the
      // post is never silently written as a plain one carrying a quote you thought you made.
      let quoting = null
      const qUri = url.searchParams.get('quote')
      if (qUri) {
        const qref = parseAtUri(qUri)
        if (qref) {
          try {
            const qrec = await (await getRecordStore(qref.did)).get(qref.collection, qref.rkey)
            if (qrec) {
              const qprof = await av.getProfile(qref.did)
              quoting = { uri: qUri, did: qref.did, who: (qprof && qprof.displayName) || null, text: qrec.text || '' }
            }
          } catch { quoting = null }
        }
      }
      // The composer can only offer #listRule if it knows your lists.
      let composerLists = []
      if (viewer) {
        try {
          const st6 = await writer.state()
          if (st6 && st6.did === viewer.did) {
            composerLists = (await ownLists(await getRecordStore(st6.did), st6.did)).map((l) => ({ uri: l.uri, name: (l.record && l.record.name) || l.rkey }))
          }
        } catch { composerLists = [] }
      }
      // Freshness qualifies everything on this page, so it is computed for the page the reader is ON —
      // not only for /status, which a reader never opens. In-memory router maps; no I/O.
      return html(res, 200, timelinePage({ result, viewer, canWrite: NODE_CAN_WRITE, quoting, composerLists, apRkeys: await apProjected(), freshness: frontsDiag(router) }))
    }
    // Following feed — the DIDs the viewer follows, handed to getTimeline's existing `authors` filter.
    // No new index: that filter already exists for community scoping.
    if (path === '/following') {
      if (!viewer) return html(res, 200, timelinePage({ result: { posts: [] }, viewer, active: 'following' }))
      const authors = await av.following(viewer.did)
      const result = authors.length
        ? await withBookmarks(await withLensBylines(await withMod(await av.getTimeline({ limit: 50, cursor: url.searchParams.get('cursor') || null, authors, viewerDid: viewer.did }), viewer.did)), viewer.did)
        : { posts: [] }
      return html(res, 200, timelinePage({ result, viewer, canWrite: NODE_CAN_WRITE, active: 'following', apRkeys: await apProjected(), freshness: frontsDiag(router), emptyMsg: authors.length ? 'nobody you follow has posted here yet' : 'you are not following anyone yet — open a profile to follow them' }))
    }
    // /profile/<did>/followers · /profile/<did>/following — the dedicated list.
    //
    // MUST precede the general /profile/ handler below, which slices the whole remainder as the DID and
    // would otherwise treat "<did>/followers" as a DID and render an empty stranger.
    //
    // Handle resolution is DEADLINE-BOUNDED and parallel, deliberately: the profile page learned this the
    // hard way — resolving serially hung it for >90s. A row whose handle does not resolve in time renders
    // as a short DID, which is the honest fallback, not an error.
    {
      const m = path.match(/^\/profile\/([^/]+)\/(followers|following)$/)
      if (m) {
        const did = decodeURIComponent(m[1])
        const kind = m[2]
        if (!did.startsWith('did:')) return html(res, 404, timelinePage({ result: { posts: [] }, viewer }))
        const all = kind === 'followers' ? await av.followers(did) : await av.following(did)
        // Offset cursor. The underlying read is a full key-range scan either way, so an opaque cursor
        // would buy nothing here beyond the appearance of one.
        const PAGE = 50
        const off = Math.max(0, parseInt(url.searchParams.get('cursor') || '0', 10) || 0)
        const slice = all.slice(off, off + PAGE)
        const deadline = delay(2500)
        const accounts = await Promise.all(slice.map(async (d) => {
          const prof = await av.getProfile(d).catch(() => null)
          let h = null
          try { h = await Promise.race([handleResolver.resolve(d), deadline.then(() => null)]) } catch {}
          return {
            did: d,
            displayName: (prof && prof.displayName) || null,
            handle: h && h.verified ? h.handle : null,
            verified: !!(h && h.verified),
            // No badge for our own indexed records — an unlabelled row means "we hold the follow", and
            // that default has to stay silent or the label stops carrying information. AP followers get
            // a source here once ap-bridge's follower state is readable (hyper-social #29).
            source: null
          }
        }))
        // The SAME identity's ActivityPub followers, appended and LABELLED. Only for the followers
        // tab — "following" is a record we author, and we do not author AP follows yet (that is #29
        // item 4's outbound half). Best-effort by construction: a failure here must not cost the page
        // its atproto followers, so it degrades to an empty list rather than throwing.
        let apRows = []
        if (kind === 'followers' && apFollowers.enabled && off === 0) {
          try { apRows = await apFollowers.followersOf(did) } catch { apRows = [] }
        }
        const subj = await av.getProfile(did).catch(() => null)
        return html(res, 200, followListPage({
          did,
          kind,
          accounts: accounts.concat(apRows),
          viewer,
          subjectName: (subj && subj.displayName) || null,
          cursor: (off + PAGE) < all.length ? String(off + PAGE) : null
        }))
      }
    }

    if (path.startsWith('/profile/')) {
      const did = decodeURIComponent(path.slice('/profile/'.length))
      if (!did) return html(res, 400, timelinePage({ result: { posts: [] }, viewer }))
      // Tab = an app.bsky.feed.getAuthorFeed filter value. The PAGE default is posts_no_replies (bsky's
      // Posts tab); the appview keeps the lexicon default. An unknown value degrades inside getAuthorFeed
      // rather than erroring, so a hand-edited query string cannot 500 a profile.
      const filter = url.searchParams.get('filter') || 'posts_no_replies'
      // ⛔ A PROFILE WE DO NOT SUBSCRIBE TO GOES STALE SILENTLY, AND LOOKS CURRENT. Nothing tails an
      // identity outside the roster, so an earlier one-shot view renders as a complete, plausible profile
      // that is simply months out of date — old posts, and the old avatar CID because the PROFILE RECORD
      // is old too. Measured on a handset (hyper-social #53): ashatron's posts 16 days behind and their
      // previous avatar shown as though it were current. That reads as corruption, not as "not
      // subscribed", which is the worst way for this to fail.
      //
      // So looking at someone refreshes them. addPeer is the same idempotent runtime path /api/track
      // uses — join the topic, resolve a verify key, start the ingest loop — and the loop then keeps the
      // profile current for as long as this node runs.
      //
      // ⚠ GATED TO THE NODE'S OWN OPERATOR. `viewer.did === the DID this node signs for` is the same test
      // /api/follow uses. Without it, any anonymous visitor to a public instance could make it join an
      // arbitrary topic per URL — a page view must not be a remote "make this node subscribe" button.
      // On a handset the operator is the only viewer there is, which is the case this fixes.
      //
      // Detached and non-fatal: the page must render at snapshot speed. An unreachable DID (every
      // bsky-hosted account) simply resolves no peer, and the render is unaffected.
      if (viewer && !(HOSTED_DIDS || []).includes(did) && !ROSTER.includes(did)) {
        try {
          const st = await writer.state().catch(() => null)
          if (st && st.did === viewer.did) {
            addPeer(did).then(
              (p) => { if (p) console.log(JSON.stringify({ msg: 'profile view: subscribed, ingest running', did })) },
              (e) => console.error(JSON.stringify({ msg: 'profile view: subscribe failed (page still rendered)', did, error: e.message }))
            )
          }
        } catch { /* the page is the product; a refresh attempt must never break it */ }
      }
      const result = await withLensBylines(await withMod(await av.getAuthorFeed(did, { limit: 50, cursor: url.searchParams.get('cursor') || null, viewerDid: viewer ? viewer.did : null, filter }), viewer ? viewer.did : null))
      // The profile header needs the SUBJECT's own profile — the same indexed record the per-post
      // hydration uses, just looked up by the DID being viewed rather than by each post's author.
      const profile = await av.getProfile(did)
      // A DID we hold no profile record for — typically a bsky account discovered through a backlink
      // (a network follower) — rendered as a short DID, a placeholder avatar and an empty feed. Honest,
      // and useless: it reads as a broken page rather than as "we don't hold this person".
      //
      // Ask a lens, and label it. Same rule the thread view's lens replies follow (DESIGN §7.6 Tier C —
      // REFERENCED, never retained): it is not written to any store, it is attributed to a NAMED foreign
      // source, and it carries no affordances, because acting on a profile we do not hold would be a lie.
      // Nothing here changes what we federate; it only stops the page pretending the person is nameless.
      let lensProfile = null
      if (!profile && lensReader && LENSES.length) {
        try {
          const lens = LENSES[0]
          const body = await lensReader.get(lens, 'app.bsky.actor.getProfile', { actor: did })
          if (body && (body.displayName || body.handle || body.avatar)) {
            lensProfile = {
              lens: lens.name,
              displayName: body.displayName || null,
              handle: body.handle || null,
              description: body.description || null,
              avatarUrl: typeof body.avatar === 'string' ? body.avatar : null,
              followersCount: Number.isFinite(body.followersCount) ? body.followersCount : null,
              followsCount: Number.isFinite(body.followsCount) ? body.followsCount : null,
              postsCount: Number.isFinite(body.postsCount) ? body.postsCount : null
            }
          }
        } catch { lensProfile = null }
      }
      const graph = {
        following: (await av.following(did)).length,
        followers: (await av.followers(did)).length,
        // Whether the VIEWER follows this profile, so the button renders the right verb.
        viewerFollows: viewer ? !!(await av.followRkey(viewer.did, did)) : false,
        isSelf: !!(viewer && viewer.did === did),
        canFollow: !!(viewer && viewer.did),
        // Network-wide followers (§7.6 Tier C — referenced, never retained). av.followers() above counts
        // only follows authored by DIDs THIS NODE INDEXES, so a bsky account following you is invisible
        // to it. Kept as a SEPARATE field, never merged into the local count: different denominators.
        // Read-only by construction — this path holds no store and cannot write.
        network: followerLens ? await followerLens.followersOf(did) : null,
        // Viewer-relative moderation state, so the profile can offer the right verb.
        viewerMuted: viewer ? await muteStore.isMuted(viewer.did, did) : false,
        viewerBlocked: viewer ? (!!(await av.blockRkeyFor(viewer.did, did)) || await muteStore.isBlocked(viewer.did, did)) : false,
        // The viewer's own lists, with whether THIS profile is already on each — so the control can show
        // a ✓ rather than making someone guess whether they already added them.
        viewerLists: await (async () => {
          if (!viewer) return []
          try {
            const st = await writer.state()
            if (!st || st.did !== viewer.did) return []
            const store = await getRecordStore(st.did)
            const ls = await ownLists(store, st.did)
            const out = []
            for (const l of ls) {
              out.push({ uri: l.uri, name: (l.record && l.record.name) || l.rkey, member: !!(await memberRkey(store, l.uri, did)) })
            }
            return out
          } catch { return [] }
        })()
      }
      // Their POSTS via the lens. Clicking a bsky account gave a name and an avatar (0.3.12) and then an
      // empty page — the profile of someone whose posts this node has never indexed is mostly a list of
      // their posts, so without this the page is a shell.
      //
      // Fetched only when we hold NOTHING of our own for them: a DID we index should render OUR records,
      // not a remote view of them. Shown as a NAMED foreign source with no affordances, same rule as the
      // thread view's lens replies — acting on a post we do not hold would be a lie.
      let lensPosts = null
      // ⛔ NOT GATED ON lensProfile. It used to be, and lensProfile is itself only fetched when we hold NO
      // profile record — so the moment a bsky account's profile arrived through a backlink, the header
      // rendered from our own data, lensProfile stayed null, and their posts were never asked for. The
      // page then looked legitimate and empty: a real name, a real avatar, "no posts from this author"
      // for someone who posts daily. Reported 2026-08-25.
      //
      // The real condition is the one this is for: we have nothing of our OWN to show for this DID. A DID
      // we index renders our records; anything else may be filled in from a named foreign source.
      const holdNothing = !(result && result.posts && result.posts.length)
      if (lensReader && LENSES.length && holdNothing) {
        try {
          const l = LENSES[0]
          // The tab maps to the same getAuthorFeed filter the lexicon defines, so Media stays Media.
          const body = await lensReader.get(l, 'app.bsky.feed.getAuthorFeed', { actor: did, limit: 30, filter })
          const feed = (body && Array.isArray(body.feed)) ? body.feed : []
          const posts = feed.map((f) => f && f.post).filter(Boolean).map((pp) => ({
            did: (pp.author && pp.author.did) || did,
            handle: (pp.author && pp.author.handle) || null,
            displayName: (pp.author && pp.author.displayName) || null,
            text: (pp.record && pp.record.text) || '',
            createdAt: (pp.record && pp.record.createdAt) || pp.indexedAt || null,
            replyCount: pp.replyCount || 0,
            // Image thumbs come from the LENS's CDN — we hold no blob for these.
            images: ((pp.embed && (pp.embed.images || (pp.embed.media && pp.embed.media.images))) || [])
              .map((im) => ({ thumb: typeof im.thumb === 'string' ? im.thumb : null, alt: im.alt || '' }))
              .filter((im) => im.thumb && /^https:\/\//i.test(im.thumb))
          }))
          if (posts.length) lensPosts = { name: l.name, posts }
        } catch { lensPosts = null }
      }
      return html(res, 200, profilePage({ did, result, viewer, profile, graph, filter, lensProfile, lensPosts, apRkeys: await apProjected() }))
    }
    // A single post on its own page — the target of every permalink. Served from the author feed rather
    // than a point lookup so the post arrives with the same moderation treatment (labels, mutes) the
    // timeline would have given it; a permalink that bypasses moderation would be a hole in it.
    if (path.startsWith('/post/')) {
      const rest = path.slice('/post/'.length).split('/')
      const did = decodeURIComponent(rest[0] || '')
      const rkey = decodeURIComponent(rest[1] || '')
      if (!did || !rkey) return html(res, 404, postPage({ post: null, viewer }))
      const viewerDid = viewer ? viewer.did : null
      // Point lookup + a thread in BOTH directions. This used to scan the author's last 100 posts and
      // match by rkey, which 404'd every permalink to an older post; getPost reads the (did, rkey) index
      // directly, so there is no horizon.
      const thread = await av.getPostThread(`at://${did}/app.bsky.feed.post/${rkey}`, { viewerDid })
      if (!thread) return html(res, 404, postPage({ post: null, viewer }))
      // Moderation still covers everything shown. withMod mutates each post in place, so passing the
      // FLAT list moderates the whole tree — the old code moderated only the post plus its DIRECT
      // replies, so a nested reply bypassed labels and mutes.
      // threadPostList flattens the TREE but yields the same objects, so filling a byline here propagates
      // back through the nested replies — the same property withMod relies on. Without this the thread
      // page kept the grey circles the timeline just lost (0.3.14): the identical bug, one surface over.
      await withLensBylines({ posts: threadPostList(thread) })
      await withMod({ posts: threadPostList(thread) }, viewer ? viewer.did : null)
      // LENS IMPORT. favela indexes the firehoses of the peers it ingests, which is a strictly narrower
      // window than a public AppView's: a bsky user replying to us was never in scope, so no amount of
      // local indexing surfaces them. Ask each configured lens for the same thread and render what it has
      // that we do not — ATTRIBUTED and separate, never merged into our tree.
      //
      // Fails soft by construction (the reader returns null on timeout, non-2xx, bad JSON or an open
      // breaker), so a slow or down AppView costs this page nothing but the rows it would have added.
      let lensReplies = []
      let lensAncestors = []
      if (lensReader) {
        const localUris = new Set(threadPostList(thread).map((p) => p.uri).filter(Boolean))
        const uri = thread.post.uri
        // Ask for ancestors ONLY when our own walk actually stopped at one we never indexed. Otherwise
        // parentHeight stays 0: a bigger response for a gap that does not exist is wasted on every thread
        // whose chain we already hold in full, and it would fragment the reader's cache by params.
        const gap = (thread.ancestors || []).some((a) => a && a.missing)
        const results = await Promise.all(LENSES.map(async (lens) => {
          const body = await lensReader.get(lens, 'app.bsky.feed.getPostThread', { uri, depth: 1, parentHeight: gap ? 10 : 0 })
          return {
            lens: lens.name,
            replies: extractThreadReplies(body, { exclude: localUris }),
            posts: gap ? extractThreadParents(body, { exclude: localUris }) : []
          }
        }))
        lensReplies = results.filter((r) => r.replies.length).map((r) => ({ lens: r.lens, replies: r.replies }))
        lensAncestors = results.filter((r) => r.posts.length).map((r) => ({ lens: r.lens, posts: r.posts }))
      }
      // The gate lives at the SAME rkey as the post, so it is directly addressable — no new index, no
      // INGEST_VERSION bump. Absent record = no gate = anyone may reply.
      let gateRec = null
      try { gateRec = await (await getRecordStore(thread.post.did)).get('app.bsky.feed.threadgate', thread.post.rkey) } catch { gateRec = null }
      // The postgate lives at the same rkey too — one more direct lookup, no index.
      let pgRec = null
      try { pgRec = await (await getRecordStore(thread.post.did)).get('app.bsky.feed.postgate', thread.post.rkey) } catch { pgRec = null }
      const gateChoice = choiceOf(gateRec)
      // #followingRule is "people the AUTHOR follows" — the direction matters, and reversing it would
      // gate exactly the wrong set of people.
      const authorFollowsViewer = (gateChoice === 'following' && viewer) ? !!(await av.followRkey(thread.post.did, viewer.did)) : false
      // #listRule — resolvable ONLY when the list is one this node already tracks (a community roster).
      // Otherwise membership stays null, which means "unknown", NOT "excluded": the reply box closes but
      // the notice says the membership could not be checked, rather than telling someone they were left
      // out of a list we never read.
      let listMembers = null
      let listUnknown = false
      if (gateChoice === 'list') {
        const lu = listUriOf(gateRec)
        const parsed = lu ? parseListUri(lu) : null
        try {
          // Resolvable only if we can reach the list OWNER as a peer — the same path the modlist
          // subscription uses. An arbitrary bsky list is not readable from here, and pretending
          // otherwise would be worse than saying so.
          const ownerPeer = parsed ? await addPeer(parsed.owner) : null
          if (ownerPeer) {
            await ownerPeer.ready({ timeout: 15000 })
            const r = await resolveRoster(ownerPeer, lu)
            if (r && Array.isArray(r.members)) listMembers = r.members
            else listUnknown = true
          } else listUnknown = true
        } catch { listUnknown = true }
      }
      const viewerCanReply = canReply({
        viewerDid: viewer ? viewer.did : null,
        authorDid: thread.post.did,
        record: gateRec,
        authorFollowsViewer,
        mentionedDids: mentionsOf(thread.post.record),
        listMembers
      })
      return html(res, 200, postPage({ post: thread.post, viewer, ancestors: thread.ancestors, replies: thread.replies, canWrite: NODE_CAN_WRITE, lensReplies, lensAncestors, lensesOn: LENSES_ON, quoteNote: describeQuoteGate(quoteChoiceOf(pgRec)),
        viewerCanQuote: canQuote({ viewerDid: viewer ? viewer.did : null, authorDid: thread.post.did, record: pgRec }),
        gateNote: describeGate(gateChoice) + (listUnknown ? ' — and this node cannot read that list, so it cannot check whether you are a member' : ''), viewerCanReply }))
    }
    // Search — this node's index, plus bsky via the lens, kept as SEPARATE sections (see searchPage).
    // A plain GET, so a search is a shareable URL and works with scripting off.
    // Lists — yours, and the members of one. Read straight from the record store: we know our own DID,
    // so both collections are directly addressable and no index is needed.
    if (path === '/lists' || path.startsWith('/lists/')) {
      if (!viewer) return html(res, 200, listsPage({ viewer: null }))
      const st = await writer.state().catch(() => null)
      const own = st && st.did === viewer.did
      const store = own ? await getRecordStore(st.did) : null
      const lists = store ? await ownLists(store, st.did) : []
      const rkey = path.startsWith('/lists/') ? decodeURIComponent(path.slice('/lists/'.length)) : null
      if (!rkey) return html(res, 200, listsPage({ viewer, lists, canWrite: own }))
      const one = lists.find((l) => l.rkey === rkey)
      if (!one) return html(res, 404, listsPage({ viewer, lists, canWrite: own, notFound: rkey }))
      const members = await membersOf(store, one.uri)
      // Names where we have them; a bare DID otherwise. A list of opaque DIDs is unusable.
      const hydrated = []
      for (const m of members) {
        const prof = await av.getProfile(m.subject)
        hydrated.push({ ...m, displayName: (prof && prof.displayName) || null })
      }
      return html(res, 200, listPage({ viewer, list: one, members: hydrated }))
    }

    // Notifications — the server renders the shell and nothing else. See web/static/notifications.js:
    // hpp requires a real user bearer to mint service auth (deliberately), and holding one here would
    // make favela-web a credential store, which is the thing it is built not to be.
    if (path === '/notifications') {
      // Answered from what this node already knows: the inbound lens folds replies touching our
      // content into the appview, and ap-bridge keeps what the fediverse sent. No credential.
      let items = []
      let apAvailable = null
      if (viewer) {
        const collected = []
        try {
          // Our own recent posts are the subjects anyone could have replied to. The reply index is
          // keyed by parent uri, so this is N cheap local range reads, not a network call.
          const own = await av.getAuthorFeed(viewer.did, { limit: 20, filter: 'posts_no_replies' })
          for (const post of (own && own.posts) || []) {
            if (!post || !post.uri) continue
            for (const r of await av.getReplies(post.uri, { limit: 20 })) {
              if (!r || r.did === viewer.did) continue // your own reply is not a notification
              collected.push({ ...fromReply(r, post.uri), authorDid: r.did })
            }
          }
        } catch (e) {
          console.error(JSON.stringify({ msg: 'notifications: atproto side failed', error: e.message }))
        }

        const apItems = await apInbox.list({ limit: 50 })
        apAvailable = apItems !== null // null means COULD NOT ASK, not "none"
        items = mergeNotifications({
          atproto: collected,
          activitypub: (apItems || []).map(fromApItem).filter(Boolean),
          viewerDid: viewer.did,
          limit: 50
        })
      }
      return html(res, 200, notificationsPage({ viewer, items, apAvailable, pds: EXTERNAL_URL || 'https://pds.7rnx.net' }))
    }

    // Bookmarks — the viewer's own saved posts. Nothing shared, nothing federated.
    if (path === '/bookmarks') {
      if (!viewer) return html(res, 200, bookmarksPage({ viewer: null }))
      const rows = await bookmarkStore.list(viewer.did, { limit: 50 })
      const posts = []
      let missing = 0
      for (const row of rows) {
        const ref = parseAtUri(row.uri)
        if (!ref) { missing++; continue }
        // A bookmark can outlive the post it points at — deleted by its author, or no longer held here.
        const p = await av.getPost(ref.did, ref.rkey)
        if (p) { p.viewerBookmarked = true; posts.push(p) } else missing++
      }
      const result = await withLensBylines(await withMod({ posts }, viewer.did))
      return html(res, 200, bookmarksPage({ result, viewer, missing }))
    }

    if (path === '/search') {
      const q = url.searchParams.get('q') || ''
      if (!q.trim()) return html(res, 200, searchPage({ q: '', viewer, canWrite: NODE_CAN_WRITE }))
      const local = await withLensBylines(await withMod(await av.searchPosts(q, { limit: 25, viewerDid: viewer ? viewer.did : null }), viewer ? viewer.did : null))
      const actors = await av.searchActors(q, { limit: 10 })
      // bsky's own search. Both endpoints are public — no auth, no session — so this needs none of the
      // service-auth chain that notifications are blocked on. Failure is soft: a lens that is down or
      // slow yields no remote section rather than an error page.
      let lens = null
      if (lensReader && LENSES.length) {
        const l = LENSES[0]
        try {
          const [pRes, aRes] = await Promise.all([
            lensReader.get(l, 'app.bsky.feed.searchPosts', { q, limit: 15 }).catch(() => null),
            lensReader.get(l, 'app.bsky.actor.searchActors', { q, limit: 8 }).catch(() => null)
          ])
          const posts = (pRes && Array.isArray(pRes.posts) ? pRes.posts : []).map((p) => ({
            did: (p.author && p.author.did) || '',
            handle: (p.author && p.author.handle) || null,
            displayName: (p.author && p.author.displayName) || null,
            text: (p.record && p.record.text) || '',
            createdAt: (p.record && p.record.createdAt) || null,
            replyCount: p.replyCount || 0
          }))
          const acts = (aRes && Array.isArray(aRes.actors) ? aRes.actors : []).map((a) => ({
            did: a.did, handle: a.handle || null, displayName: a.displayName || null, description: a.description || null
          }))
          if (posts.length || acts.length) lens = { name: l.name, posts, actors: acts }
          else lens = { name: l.name, posts: [], actors: [] }
        } catch { lens = null }
      }
      return html(res, 200, searchPage({ q, local, actors, lens, viewer, canWrite: NODE_CAN_WRITE }))
    }

    if (path.startsWith('/tag/')) {
      const tag = decodeURIComponent(path.slice('/tag/'.length))
      const result = await withLensBylines(await withMod(await av.getTagFeed(tag, { limit: 50, cursor: url.searchParams.get('cursor') || null, viewerDid: viewer ? viewer.did : null }), viewer ? viewer.did : null))
      return html(res, 200, tagPage({ tag, result, viewer }))
    }
    if (path === '/feed.xml') {
      const { posts } = await av.getTimeline({ limit: 50 })
      return xml(res, 200, renderAtom({ posts, selfUrl: EXTERNAL_URL + '/feed.xml' }), 'application/atom+xml; charset=utf-8')
    }

    // ── JSON APIs (programmatic / progressive enhancement) ─────
    if (path === '/api/timeline') {
      const limit = Math.min(Number(url.searchParams.get('limit')) || 30, 100)
      return json(res, 200, JSON.stringify(await withMod(await av.getTimeline({ limit, authors: await scopeOf(viewer) }))))
    }
    // Which co-owner's firehose are we following, and why? Read-only, no auth (it exposes no content —
    // only keys, revs and lengths that peers already announce to each other). Added because a frozen
    // ingest is invisible from every other surface: see lib/fronts-diag.js.
    // The operator page. Same data as /api/fronts + /api/lens, rendered for a human — a raw JSON blob is
    // what we already had, and it is not what gets looked at when something is quietly frozen.
    if (path === '/status') {
      return html(res, 200, statusPage({
        fronts: frontsDiag(router),
        lens: { enabled: LENSES_ON, lenses: LENSES, errors: LENS_ERRORS, stats: lensReader ? lensReader.stats() : null },
        host: HOSTNAME,
        viewer
      }))
    }
    if (path === '/api/fronts') {
      const want = url.searchParams.get('did')
      return json(res, 200, JSON.stringify(frontsDiag(router, want ? [want] : null), null, 2))
    }
    // Lens config + live reader counters (cache hits, failures, open breakers). The boot log said only
    // whether lenses were enabled; this says whether they are WORKING.
    //
    // ⛔ EXCLUDE POST, or this swallows it. This route carries no method check and sits ~250 lines ahead
    // of the POST handler that SETS the lens, so without the guard the setter is unreachable code that
    // returns diagnostics and looks like a successful save.
    if (path === '/api/lens' && req.method !== 'POST') {
      return json(res, 200, JSON.stringify({
        enabled: LENSES_ON,
        lenses: LENSES.map((l) => ({ name: l.name, base: l.base, proxy: l.proxy || null })),
        errors: LENS_ERRORS,
        stats: lensReader ? lensReader.stats() : null
      }, null, 2))
    }
    // Inbound-lens health. Everything §7.6 can silently drop — queue overflow, verify refusals,
    // re-encode refusals, budget evictions, backfill truncation — is countable here or it is invisible.
    if (path === '/api/inbound') {
      return json(res, 200, JSON.stringify(
        inbound ? { enabled: true, ...inbound.stats } : { enabled: false }, null, 2))
    }
    if (path === '/api/author') {
      const did = url.searchParams.get('did')
      if (!did) return json(res, 400, JSON.stringify({ error: 'did required' }))
      return json(res, 200, JSON.stringify(await withMod(await av.getAuthorFeed(did, { limit: 30 }))))
    }
    if (path === '/api/feed') {
      const tag = url.searchParams.get('tag')
      if (!tag) return json(res, 400, JSON.stringify({ error: 'tag required' }))
      const limit = Math.min(Number(url.searchParams.get('limit')) || 30, 100)
      return json(res, 200, JSON.stringify(await withMod(await av.getTagFeed(tag, { limit }))))
    }

    // ── the read surface, as JSON ──────────────────────────────
    // These answer the same questions the SSR pages already do, from the same appview methods. The pages
    // rendered them straight to HTML, so a non-browser client had nowhere to ask — and favela-android
    // hand-wrote each one as an IPC verb over its OWN second appview, which is how the phone ended up
    // with a duplicate index and a second definition of every query.
    //
    // The engine is shared; only the RENDERING differs per surface. So the query belongs here and the
    // markup does not. Web keeps using the SSR pages; mobile and desktop call these.
    // `viewer` here is the SESSION object, not a DID — every call below takes viewer.did, matching the
    // SSR routes. And withMod indexes `result.posts` unconditionally, so it must be handed a { posts }
    // shape; it mutates each post IN PLACE, which is what lets a flattened tree moderate the whole tree.
    if (path === '/api/thread') {
      const uri = url.searchParams.get('uri')
      if (!uri) return json(res, 400, JSON.stringify({ error: 'uri required' }))
      const viewerDid = viewer ? viewer.did : null
      const depth = Math.min(Number(url.searchParams.get('depth')) || 6, 40)
      const parentHeight = Math.min(Number(url.searchParams.get('parentHeight')) || 80, 200)
      const thread = await av.getPostThread(uri, { depth, parentHeight, viewerDid })
      if (!thread) return json(res, 404, JSON.stringify({ error: 'not found' }))
      // Flatten to moderate: threadPostList yields the SAME objects the tree holds, so labels/mutes
      // applied here propagate back through the nested replies. Moderating only the root plus its
      // direct replies let a nested reply bypass labels entirely (0.3.14, on the SSR page).
      await withMod({ posts: threadPostList(thread) }, viewerDid)
      return json(res, 200, JSON.stringify({ thread }))
    }
    if (path === '/api/replies') {
      const uri = url.searchParams.get('uri')
      if (!uri) return json(res, 400, JSON.stringify({ error: 'uri required' }))
      const viewerDid = viewer ? viewer.did : null
      const limit = Math.min(Number(url.searchParams.get('limit')) || 50, 200)
      const replies = await av.getReplies(uri, { limit, viewerDid })
      const moderated = await withMod({ posts: replies }, viewerDid)
      return json(res, 200, JSON.stringify({ replies: moderated.posts }))
    }
    if (path === '/api/search') {
      const q = url.searchParams.get('q')
      if (!q) return json(res, 400, JSON.stringify({ error: 'q required' }))
      const viewerDid = viewer ? viewer.did : null
      const kind = url.searchParams.get('kind') === 'actors' ? 'actors' : 'posts'
      const limit = Math.min(Number(url.searchParams.get('limit')) || 25, 100)
      // The two shapes differ AT THE SOURCE and must not be "tidied" into one: searchPosts already
      // returns { posts, cursor, truncated } — truncated matters, a scan-capped result is not an empty
      // one — while searchActors returns a bare array. Wrapping the first again yields {posts:{posts}}.
      if (kind === 'actors') {
        return json(res, 200, JSON.stringify({ actors: await av.searchActors(q, { limit }) }))
      }
      return json(res, 200, JSON.stringify(
        await withMod(await av.searchPosts(q, { limit, viewerDid }), viewerDid)
      ))
    }
    if (path === '/api/follows' || path === '/api/followers') {
      const did = url.searchParams.get('did') || (viewer ? viewer.did : null)
      if (!did) return json(res, 400, JSON.stringify({ error: 'did required' }))
      const dids = path === '/api/follows' ? await av.following(did) : await av.followers(did)
      if (url.searchParams.get('hydrate') !== '1') return json(res, 200, JSON.stringify({ dids }))
      // hydrate=1 — profiles included, so a client is not forced into N+1 requests to render a list of
      // people. Same shape as the /profile/<did>/(followers|following) page, and hydrated the same way:
      // profiles in PARALLEL, handles raced against a deadline. The profile page learned that serially
      // — it hung for >90s. A row whose handle misses the deadline renders as a short DID, which is the
      // honest fallback rather than an error.
      const limit = Math.min(Number(url.searchParams.get('limit')) || 200, 500)
      const slice = dids.slice(0, limit)
      const deadline = delay(2500)
      const people = await Promise.all(slice.map(async (d) => {
        const prof = await av.getProfile(d).catch(() => null)
        let handle = null
        try { handle = await Promise.race([handleResolver.resolve(d), deadline.then(() => null)]) } catch {}
        return {
          did: d,
          handle: handle || (prof && prof.handle) || null,
          displayName: (prof && prof.displayName) || null,
          avatar: (prof && prof.avatar) || null,
          description: (prof && prof.description) || null
        }
      }))
      return json(res, 200, JSON.stringify({ dids, people, count: dids.length }))
    }

    // ── blobs: avatar + post images ────────────────────────────
    // Raw-body upload (the browser POSTs the File directly; no multipart parser needed). Session-gated.
    // Returns the atproto blob REF ready to embed in a record — the shape the fleet's existing records
    // already use and that bsky demonstrably hydrates. favela stays keyless: the hpp stores the bytes.
    if (req.method === 'POST' && path === '/api/upload') {
      if (!viewer) return json(res, 401, JSON.stringify({ error: 'sign in first' }))
      let bytes
      try { bytes = await readBodyBuffer(req) } catch (e) { return json(res, e.code === 'ETOOLARGE' ? 413 : 400, JSON.stringify({ error: e.message })) }
      if (!bytes || !bytes.length) return json(res, 400, JSON.stringify({ error: 'empty body' }))
      const mime = imageMimeOrNull(bytes)
      if (!mime) return json(res, 415, JSON.stringify({ error: 'not a recognised image (png/jpeg/gif/webp)' }))
      try {
        const up = await writer.uploadBlob(bytes, mime)
        return json(res, 200, JSON.stringify({ blob: Writer.blobRef(up), cid: up.cid, mimeType: up.mimeType, size: up.size }))
      } catch (e) { return json(res, 502, JSON.stringify({ error: 'upload failed: ' + e.message })) }
    }
    // Set the signed-in DID's avatar. Uploads the blob, then UPDATES app.bsky.actor.profile/self —
    // reading the CURRENT record first so displayName/description (and any other field) survive. A
    // blind put would silently blank the rest of the profile.
    // Banner — the wide header image on a profile (app.bsky.actor.profile.banner). Identical shape to
    // /api/avatar: same size cap, same magic-byte sniff, same signs-for-this-DID guard. Kept as its own
    // route rather than a flag on the avatar one so a bug in either cannot overwrite the other's field.
    if (req.method === 'POST' && path === '/api/banner') {
      if (!viewer) return json(res, 401, JSON.stringify({ error: 'sign in first' }))
      let bytes
      try { bytes = await readBodyBuffer(req) } catch (e) { return json(res, e.code === 'ETOOLARGE' ? 413 : 400, JSON.stringify({ error: e.message })) }
      if (!bytes || !bytes.length) return json(res, 400, JSON.stringify({ error: 'empty body' }))
      const mime = imageMimeOrNull(bytes)
      if (!mime) return json(res, 415, JSON.stringify({ error: 'not a recognised image (png/jpeg/gif/webp)' }))
      try {
        const st = await writer.state()
        const deviceDid = st && st.did
        if (!deviceDid) return json(res, 502, JSON.stringify({ error: 'device did not report a DID' }))
        if (deviceDid !== viewer.did) return json(res, 403, JSON.stringify({ error: `this node signs for ${deviceDid}, not ${viewer.did} — banner not written` }))
        const up = await writer.uploadBlob(bytes, mime)
        const store = await getRecordStore(deviceDid)
        const current = (await store.get('app.bsky.actor.profile', 'self')) || { $type: 'app.bsky.actor.profile' }
        // Spread `current` FIRST so an existing avatar/displayName/description survives — a profile write
        // that drops the other fields is the lossy-overwrite shape that cost two records on 2026-07-31.
        const record = { ...current, $type: 'app.bsky.actor.profile', banner: Writer.blobRef(up) }
        await writer.putRecord('app.bsky.actor.profile', 'self', record, { action: 'update' })
        return json(res, 200, JSON.stringify({ ok: true, did: deviceDid, cid: up.cid, mimeType: up.mimeType, size: up.size }))
      } catch (e) { return json(res, 502, JSON.stringify({ error: 'banner update failed: ' + e.message })) }
    }

    if (req.method === 'POST' && path === '/api/avatar') {
      if (!viewer) return json(res, 401, JSON.stringify({ error: 'sign in first' }))
      let bytes
      try { bytes = await readBodyBuffer(req) } catch (e) { return json(res, e.code === 'ETOOLARGE' ? 413 : 400, JSON.stringify({ error: e.message })) }
      if (!bytes || !bytes.length) return json(res, 400, JSON.stringify({ error: 'empty body' }))
      const mime = imageMimeOrNull(bytes)
      if (!mime) return json(res, 415, JSON.stringify({ error: 'not a recognised image (png/jpeg/gif/webp)' }))
      try {
        // favela's write path is single-DID: the UDS socket picks the device, so the record lands in
        // whatever DID this hpp signs for. Refuse if that is not the viewer's own DID rather than write
        // a profile into someone else's repo.
        const st = await writer.state()
        const deviceDid = st && st.did
        if (!deviceDid) return json(res, 502, JSON.stringify({ error: 'device did not report a DID' }))
        if (deviceDid !== viewer.did) {
          return json(res, 403, JSON.stringify({ error: `this node signs for ${deviceDid}, not ${viewer.did} — avatar not written` }))
        }
        const up = await writer.uploadBlob(bytes, mime)
        const store = await getRecordStore(deviceDid)
        const current = (await store.get('app.bsky.actor.profile', 'self')) || { $type: 'app.bsky.actor.profile' }
        const record = { ...current, $type: 'app.bsky.actor.profile', avatar: Writer.blobRef(up) }
        await writer.putRecord('app.bsky.actor.profile', 'self', record, { action: 'update' })
        return json(res, 200, JSON.stringify({ ok: true, did: deviceDid, cid: up.cid, mimeType: up.mimeType, size: up.size, displayName: record.displayName || null }))
      } catch (e) { return json(res, 502, JSON.stringify({ error: 'avatar update failed: ' + e.message })) }
    }

    // Like / unlike a post. A TOGGLE, because that is what the UI affords — and unliking is a delete of
    // the viewer's OWN like record, whose rkey only their repo knows, so the appview is asked for it.
    // Plain-form friendly (redirects back) so it works with scripting off, like the composer.
    if (req.method === 'POST' && path === '/api/like') {
      const isForm = !(req.headers['content-type'] || '').includes('application/json')
      const raw = (await readBody(req)) || ''
      let uri, back
      try {
        if (isForm) { const q = new URLSearchParams(raw); uri = q.get('uri'); back = q.get('return') }
        else { const b = JSON.parse(raw || '{}'); uri = b.uri; back = b.return }
      } catch { uri = null }
      const home = safeReturn(back)
      const fail = (code, msg) => isForm ? redirect(res, home) : json(res, code, JSON.stringify({ error: msg }))
      if (!viewer) return fail(401, 'sign in first')
      if (typeof uri !== 'string' || !uri.startsWith('at://')) return fail(400, 'uri must be an at:// post uri')
      try {
        const st = await writer.state()
        const deviceDid = st && st.did
        if (!deviceDid) return fail(502, 'device did not report a DID')
        if (deviceDid !== viewer.did) return fail(403, `this node signs for ${deviceDid}, not ${viewer.did}`)
        const existing = await av.likeRkey(deviceDid, uri)
        if (existing) {
          await writer.putRecord('app.bsky.feed.like', existing, null, { action: 'delete' })
          await av.delLike({ did: deviceDid, rkey: existing })
        } else {
          // subject is a com.atproto.repo.strongRef — uri AND cid, both required. A uri-only subject
          // indexes fine here and is REJECTED by bsky's lexicon validation, so it federates as nothing
          // while the UI shows a like (shipped exactly that in 0.2.41). Refuse rather than write one.
          const ref = await strongRef(uri, getRecordStore)
          if (!ref) return fail(409, 'cannot like a post whose record bytes are not held locally — a like needs its cid')
          const rkey = tidNow()
          const record = { $type: 'app.bsky.feed.like', subject: ref, createdAt: new Date().toISOString() }
          await writer.putRecord('app.bsky.feed.like', rkey, record, { action: 'create' })
          await av.putLike({ did: deviceDid, rkey, record })
        }
        if (isForm) return redirect(res, home)
        return json(res, 200, JSON.stringify({ ok: true, liked: !existing, likeCount: await av.likeCount(uri) }))
      } catch (e) { return fail(502, 'like failed: ' + e.message) }
    }

    // Repost / unrepost. Same toggle + strongRef shape as /api/like — subject is a strongRef, so it
    // FAILS CLOSED rather than writing a uri-only ref that bsky would silently drop.
    if (req.method === 'POST' && path === '/api/repost') {
      const isForm = !(req.headers['content-type'] || '').includes('application/json')
      const raw = (await readBody(req)) || ''
      let uri, back
      try {
        if (isForm) { const q = new URLSearchParams(raw); uri = q.get('uri'); back = q.get('return') }
        else { const b = JSON.parse(raw || '{}'); uri = b.uri; back = b.return }
      } catch { uri = null }
      const home = safeReturn(back)
      const fail = (code, msg) => isForm ? redirect(res, home) : json(res, code, JSON.stringify({ error: msg }))
      if (!viewer) return fail(401, 'sign in first')
      if (typeof uri !== 'string' || !uri.startsWith('at://')) return fail(400, 'uri must be an at:// post uri')
      try {
        const st = await writer.state()
        const deviceDid = st && st.did
        if (!deviceDid) return fail(502, 'device did not report a DID')
        if (deviceDid !== viewer.did) return fail(403, `this node signs for ${deviceDid}, not ${viewer.did}`)
        const existing = await av.repostRkey(deviceDid, uri)
        if (existing) {
          await writer.putRecord('app.bsky.feed.repost', existing, null, { action: 'delete' })
          await av.delRepost({ did: deviceDid, rkey: existing })
        } else {
          const ref = await strongRef(uri, getRecordStore)
          if (!ref) return fail(409, 'cannot repost a post whose record bytes are not held locally — a repost needs its cid')
          const rkey = tidNow()
          const record = { $type: 'app.bsky.feed.repost', subject: ref, createdAt: new Date().toISOString() }
          await writer.putRecord('app.bsky.feed.repost', rkey, record, { action: 'create' })
          await av.putRepost({ did: deviceDid, rkey, record })
        }
        if (isForm) return redirect(res, home)
        return json(res, 200, JSON.stringify({ ok: true, reposted: !existing, repostCount: await av.repostCount(uri) }))
      } catch (e) { return fail(502, 'repost failed: ' + e.message) }
    }

    // Follow / unfollow a DID. Same toggle shape. A follow is what scopes the Following feed below.
    // ── the lens setting, from the settings page ─────────────────────────────────────────────────
    // Which remote AppView this node may read was reachable only by editing apps.json and restarting,
    // which makes it a deployment detail rather than a setting — and on a handset there is no apps.json
    // at all, so it could not be changed there by any means.
    //
    // ⛔ OPERATOR ONLY. This decides where this node sends the DIDs it looks up, so it is gated the same
    // way /api/follow is: the viewer must be the identity this node signs for. A signed-in guest on
    // somebody else's instance must not be able to repoint its reads.
    //
    // Applied IN PLACE. A setting that needs a daemon restart is a config file with extra steps.
    if (req.method === 'POST' && path === '/api/lens') {
      const isForm = !(req.headers['content-type'] || '').includes('application/json')
      const raw = (await readBody(req)) || ''
      let value, back
      try {
        if (isForm) { const q = new URLSearchParams(raw); value = q.get('bridgeUrl'); back = q.get('return') }
        else { const b = JSON.parse(raw || '{}'); value = b.bridgeUrl; back = b.return }
      } catch { value = null }
      const home = safeReturn(back) || '/settings'
      const fail = (code, msg) => isForm ? redirect(res, home) : json(res, code, JSON.stringify({ error: msg }))
      if (!viewer) return fail(401, 'sign in first')
      const st = await writer.state().catch(() => null)
      if (!st || !st.did || st.did !== viewer.did) return fail(403, 'only this node\'s own identity can change where it reads')
      const parsed = parseLensPref(value)
      if (parsed.error) return fail(400, parsed.error)
      try {
        fs.writeFileSync(STORE(LENS_PREF_FILE), JSON.stringify({ bridgeUrl: parsed.bridgeUrl }, null, 2) + '\n')
        LENS_PREF = { bridgeUrl: parsed.bridgeUrl }
        const next = parseLenses(lensEnv(process.env, LENS_PREF))
        for (const e of next.errors) console.error(JSON.stringify({ msg: 'lens config problem — entry ignored', error: e }))
        LENSES = next.lenses
        LENS_ERRORS = next.errors // or /api/lens keeps reporting the errors from boot
        LENSES_ON = lensesEnabled(LENSES)
        // Rebuilt rather than kept: the reader owns the cache, the circuit breaker and the concurrency
        // cap, and carrying those across a change of source would answer the new lens from the old one.
        lensReader = LENSES_ON ? createLensReader({ doFetch: bareFetch }) : null
        console.log(JSON.stringify({ msg: 'lens import reconfigured', enabled: LENSES_ON, lenses: LENSES.map((l) => l.name) }))
      } catch (e) { return fail(502, 'could not save: ' + e.message) }
      if (isForm) return redirect(res, home)
      return json(res, 200, JSON.stringify({ ok: true, enabled: LENSES_ON, lenses: LENSES.map((l) => l.name) }))
    }

    if (req.method === 'POST' && path === '/api/follow') {
      const isForm = !(req.headers['content-type'] || '').includes('application/json')
      const raw = (await readBody(req)) || ''
      let subject, back
      try {
        if (isForm) { const q = new URLSearchParams(raw); subject = q.get('did'); back = q.get('return') }
        else { const b = JSON.parse(raw || '{}'); subject = b.did; back = b.return }
      } catch { subject = null }
      const home = safeReturn(back)
      const fail = (code, msg) => isForm ? redirect(res, home) : json(res, code, JSON.stringify({ error: msg }))
      if (!viewer) return fail(401, 'sign in first')
      if (typeof subject !== 'string' || !subject.startsWith('did:')) return fail(400, 'did required')
      try {
        const st = await writer.state()
        const deviceDid = st && st.did
        if (!deviceDid) return fail(502, 'device did not report a DID')
        if (deviceDid !== viewer.did) return fail(403, `this node signs for ${deviceDid}, not ${viewer.did}`)
        // Following yourself is meaningless and would pollute your own Following feed with your own posts
        // twice over — refuse rather than write a record nothing can use.
        if (subject === deviceDid) return fail(400, 'cannot follow yourself')
        const existing = await av.followRkey(deviceDid, subject)
        if (existing) {
          await writer.putRecord('app.bsky.graph.follow', existing, null, { action: 'delete' })
          await av.delFollow({ did: deviceDid, rkey: existing })
        } else {
          const rkey = tidNow()
          const record = { $type: 'app.bsky.graph.follow', subject, createdAt: new Date().toISOString() }
          await writer.putRecord('app.bsky.graph.follow', rkey, record, { action: 'create' })
          await av.putFollow({ did: deviceDid, rkey, record })
          // ⛔ SUBSCRIBE NOW, NOT AT THE NEXT BOOT. A follow is the durable, replicating statement of
          // interest in an identity, and it used to change nothing until the node restarted: FAVELA_ROSTER
          // is captured at import, and favela-android's syncFollows runs only inside boot(). So following
          // someone left their posts absent — or worse, left an earlier one-shot view on screen, ageing
          // silently, which is how a handset came to show a two-week-old profile and its previous avatar
          // as though they were current (hyper-social #53).
          //
          // addPeer is the same runtime path /api/track uses: it joins the DID's topic, resolves a verify
          // key and starts the ingest loop. Idempotent, so a re-follow costs nothing.
          //
          // Detached and non-fatal ON PURPOSE. The follow RECORD is the durable half and it is already
          // written; making the response wait on a DHT rendezvous would turn a local write into a
          // network-latency operation, and an unreachable peer (every bsky-hosted account, which no peer
          // serves) would read as "follow failed" when the follow succeeded perfectly.
          addPeer(subject).then(
            (p) => { if (!p) console.log(JSON.stringify({ msg: 'follow: nobody serves this DID yet — the follow stands, ingest starts when someone does', did: subject })) },
            (e) => console.error(JSON.stringify({ msg: 'follow: subscribe failed (the follow itself is written)', did: subject, error: e.message }))
          )
        }
        if (isForm) return redirect(res, home)
        return json(res, 200, JSON.stringify({ ok: true, following: !existing }))
      } catch (e) { return fail(502, 'follow failed: ' + e.message) }
    }

    // Edit displayName / description. There was no way to set either: Settings did the avatar only, and
    // no hpp subcommand writes records — so every peer's display name was whatever it happened to be at
    // onboarding, and "change my name" meant editing a DAG-CBOR record by hand. Every atproto client has
    // this; favela did not.
    //
    // Accepts JSON *or* form-urlencoded so it works with scripting off (same dual shape as /api/post):
    // the no-JS path posts a plain <form> and gets a redirect back to /settings.
    // One person, as JSON. `FavelaApi.profile({did})` has called GET /api/profile since it was written and
    // this server only ever handled the POST — so the client has always 404'd here, silently, because
    // every in-tree caller happened to read profiles through a LIST route that hydrates them inline
    // (/api/follows?hydrate=1, /api/people). A phone asking about one tracked DID has no list to ride on.
    //
    // ⛔ `held` IS THE POINT. A DID we hold no profile record for is normal — a network follower
    // discovered through a backlink, or an account indexed before it ever wrote app.bsky.actor.profile —
    // and it must not render as "someone with no name". Absent and nameless are different facts, and the
    // caller can only tell them apart if we say which one this is.
    if (req.method === 'GET' && path === '/api/profile') {
      const did = url.searchParams.get('did')
      if (!did || !did.startsWith('did:')) return json(res, 400, JSON.stringify({ error: 'did required' }))
      const prof = await av.getProfile(did).catch(() => null)
      // Raced against a deadline, like every other handle hydration here: a handle that misses it renders
      // as a short DID, which is the honest fallback. The profile page learned this the slow way — it
      // resolved serially and hung for >90s.
      let h = null
      try { h = await Promise.race([handleResolver.resolve(did), delay(2500).then(() => null)]) } catch {}
      return json(res, 200, JSON.stringify({
        did,
        held: !!prof,
        displayName: (prof && prof.displayName) || null,
        description: (prof && prof.description) || null,
        avatar: (prof && prof.avatar) || null,
        handle: h && h.verified ? h.handle : null,
        verified: !!(h && h.verified)
      }))
    }
    if (req.method === 'POST' && path === '/api/profile') {
      const isForm = !(req.headers['content-type'] || '').includes('application/json')
      const fail = (code, msg) => isForm ? redirect(res, '/settings') : json(res, code, JSON.stringify({ error: msg }))
      if (!viewer) return fail(401, 'sign in first')
      const raw = (await readBody(req)) || ''
      let displayName, description
      try {
        if (isForm) { const q = new URLSearchParams(raw); displayName = q.get('displayName'); description = q.get('description') }
        else { const b = JSON.parse(raw || '{}'); displayName = b.displayName; description = b.description }
      } catch { return fail(400, 'bad body') }
      // atproto caps these in GRAPHEMES (app.bsky.actor.profile: displayName 64, description 256), which
      // is not string length — an emoji is one grapheme and several UTF-16 units. Rejecting on .length
      // would refuse legal values.
      const count = (v) => { try { return [...new Intl.Segmenter(undefined, { granularity: 'grapheme' }).segment(v)].length } catch { return [...String(v)].length } }
      if (displayName != null && count(String(displayName)) > 64) return fail(400, 'display name is over 64 characters')
      if (description != null && count(String(description)) > 256) return fail(400, 'bio is over 256 characters')
      try {
        // Same guard as /api/avatar: the UDS socket picks the device, so refuse rather than write a
        // profile into a DID this node does not sign for.
        const st = await writer.state()
        const deviceDid = st && st.did
        if (!deviceDid) return fail(502, 'device did not report a DID')
        if (deviceDid !== viewer.did) return fail(403, `this node signs for ${deviceDid}, not ${viewer.did} — profile not written`)
        const store = await getRecordStore(deviceDid)
        const current = (await store.get('app.bsky.actor.profile', 'self')) || { $type: 'app.bsky.actor.profile' }
        const record = { ...current, $type: 'app.bsky.actor.profile' }
        // An EMPTY field clears it: atproto models "unset" as the key being absent, not as an empty
        // string, and a stray "" would render as a blank name rather than falling back to the DID.
        for (const [k, v] of [['displayName', displayName], ['description', description]]) {
          if (v == null) continue
          const t = String(v).trim()
          if (t) record[k] = t; else delete record[k]
        }
        await writer.putRecord('app.bsky.actor.profile', 'self', record, { action: 'update' })
        if (isForm) return redirect(res, '/settings')
        return json(res, 200, JSON.stringify({ ok: true, did: deviceDid, displayName: record.displayName || null, description: record.description || null }))
      } catch (e) { return fail(502, 'profile update failed: ' + e.message) }
    }

    // Create a list. Two records make a list work (see lib/lists.js): this writes the `list` itself;
    // membership is separate `listitem` records.
    if (req.method === 'POST' && path === '/api/list') {
      const isForm = !(req.headers['content-type'] || '').includes('application/json')
      const raw = (await readBody(req)) || ''
      let name, purpose, description
      try {
        if (isForm) { const q = new URLSearchParams(raw); name = q.get('name'); purpose = q.get('purpose'); description = q.get('description') }
        else { const b = JSON.parse(raw || '{}'); name = b.name; purpose = b.purpose; description = b.description }
      } catch { name = null }
      const fail = (code, msg) => isForm ? redirect(res, '/lists') : json(res, code, JSON.stringify({ error: msg }))
      if (!viewer) return fail(401, 'sign in first')
      // PURPOSE is not a label: a modlist mutes or blocks everyone on it for anyone who subscribes, so it
      // must be chosen explicitly and never defaulted into.
      const rec = listRecord({ name, purpose: PURPOSES.includes(purpose) ? purpose : CURATE, description })
      if (!rec) return fail(400, 'a list needs a name')
      try {
        const st = await writer.state()
        if (!st || st.did !== viewer.did) return fail(403, 'this node does not sign for you')
        const rkey = tidNow()
        await writer.putRecord(LIST_COLLECTION, rkey, rec, { action: 'create' })
        if (isForm) return redirect(res, '/lists')
        return json(res, 200, JSON.stringify({ ok: true, uri: mkListUri(st.did, rkey), rkey }))
      } catch (e) { return fail(502, 'list create failed: ' + e.message) }
    }

    // Add or remove a member. A TOGGLE, because that is what the UI affords — and removing means deleting
    // THEIR listitem, so the rkey has to be found first.
    if (req.method === 'POST' && path === '/api/list-member') {
      const isForm = !(req.headers['content-type'] || '').includes('application/json')
      const raw = (await readBody(req)) || ''
      let list, subject, back
      try {
        if (isForm) { const q = new URLSearchParams(raw); list = q.get('list'); subject = q.get('subject'); back = q.get('return') }
        else { const b = JSON.parse(raw || '{}'); list = b.list; subject = b.subject; back = b.return }
      } catch { list = null }
      const home = safeReturn(back)
      const fail = (code, msg) => isForm ? redirect(res, home) : json(res, code, JSON.stringify({ error: msg }))
      if (!viewer) return fail(401, 'sign in first')
      if (typeof subject !== 'string' || !subject.startsWith('did:')) return fail(400, 'subject must be a did')
      try {
        const st = await writer.state()
        if (!st || st.did !== viewer.did) return fail(403, 'this node does not sign for you')
        // You may only edit YOUR OWN list: the uri must name your DID. Without this check the form could
        // be pointed at anyone's list uri.
        const ref = parseAtUri(list)
        if (!ref || ref.did !== st.did || ref.collection !== LIST_COLLECTION) return fail(403, 'not your list')
        const store = await getRecordStore(st.did)
        const existing = await memberRkey(store, list, subject)
        if (existing) {
          await writer.putRecord(LISTITEM_COLLECTION, existing, null, { action: 'delete' })
          if (isForm) return redirect(res, home)
          return json(res, 200, JSON.stringify({ ok: true, member: false }))
        }
        const rec = listitemRecord({ subject, list })
        if (!rec) return fail(400, 'bad subject or list')
        await writer.putRecord(LISTITEM_COLLECTION, tidNow(), rec, { action: 'create' })
        if (isForm) return redirect(res, home)
        return json(res, 200, JSON.stringify({ ok: true, member: true }))
      } catch (e) { return fail(502, 'list membership failed: ' + e.message) }
    }

    // TRACK — start reading a DID this node does not already read. See spec/did-tracking.md.
    //
    // Tracking is TWO things and only one of them is persistence:
    //   1. the ACTION — resolve the DID over P2P, wait for a verified head, start ingesting. That is
    //      what tells a user "nobody is serving this right now" instead of showing an empty screen
    //      forever, and a list entry cannot say it.
    //   2. the MEMORY — an app.bsky.graph.list entry, so the set survives a restart AND syncs to every
    //      other device, which a device-local file (favela-android's tracked-dids.json) cannot.
    //
    // The roster is resolved ONCE at boot, so adding a list entry alone would sit inert until restart —
    // hence this route does its own addPeer rather than relying on the roster being re-read.
    if (req.method === 'POST' && path === '/api/track') {
      const raw = (await readBody(req)) || ''
      let did, list, wait
      try { const b = JSON.parse(raw || '{}'); did = b.did; list = b.list; wait = b.wait } catch { did = null }
      if (!viewer) return json(res, 401, JSON.stringify({ error: 'sign in first' }))
      if (typeof did !== 'string' || !did.startsWith('did:')) return json(res, 400, JSON.stringify({ error: 'did required' }))
      const timeout = Math.min(Number(wait) || 45000, 120000)
      // HOSTED-FIRST. hpp's config `dids[]` is the authority, NOT roster membership — conflating the two
      // froze ashatron's appview for hours on 2026-08-06 (lib/hosted-dids.js). A DID we host is already
      // on disk; addPeer's coHosted branch baselines it from the shared store rather than the network.
      // HOSTED_DIDS is null when hpp's config is unreadable — a normal state for a favela-web with no
      // local hpp, not an error. Null means "we host nothing", which is the correct answer there.
      const hosted = (HOSTED_DIDS || []).includes(did)
      try {
        // Idempotent: addPeer returns the existing peer if we already read this DID.
        const peer = await addPeer(did)
        if (!peer) return json(res, 502, JSON.stringify({ error: 'could not resolve a verify key for ' + did }))
        // addPeer returns BEFORE the ingest loop has a front — it starts the loop detached. So wait for a
        // verified front here, which is the whole point of the route: an unreachable DID must say so.
        let front = null
        try { front = await router.front(did, { timeout }) } catch { front = null }
        if (!front) {
          return json(res, 503, JSON.stringify({
            error: 'no verified head for ' + did + ' — nobody is serving it right now',
            did,
            hosted,
            tracked: false
          }))
        }
        // Index once inline so the response reflects reality; the ingest loop also folds it continuously.
        let indexed = null
        try { const r = await av.indexPeer(front); indexed = r && r.indexed != null ? r.indexed : null } catch {}
        // MEMORY. Skipped with list:false — "look at this once" is a real thing to want, and it should
        // not silently edit a record that syncs to every other device.
        let tracked = false
        if (list !== false) {
          try {
            const st = await writer.state()
            if (st && st.did === viewer.did) {
              const target = typeof list === 'string' && list ? list : null
              if (target) {
                const ref = parseAtUri(target)
                if (!ref || ref.did !== st.did || ref.collection !== LIST_COLLECTION) {
                  return json(res, 403, JSON.stringify({ error: 'not your list' }))
                }
                const store = await getRecordStore(st.did)
                if (!(await memberRkey(store, target, did))) {
                  const rec = listitemRecord({ subject: did, list: target })
                  if (rec) { await writer.putRecord(LISTITEM_COLLECTION, tidNow(), rec, { action: 'create' }); tracked = true }
                } else tracked = true
              }
            }
          } catch (e) {
            // The DID is being read either way — membership is the durable half, not the working half.
            console.error(JSON.stringify({ msg: 'track: membership write failed (still ingesting)', did, error: e.message }))
          }
        }
        return json(res, 200, JSON.stringify({
          did,
          hosted,
          indexed,
          rev: (front.head && front.head.rev) || null,
          tracked
        }))
      } catch (e) {
        return json(res, 502, JSON.stringify({ error: 'track failed: ' + e.message }))
      }
    }

    // BOOKMARK — private, node-local, per viewer. Writes nothing to the repo and federates nothing.
    if (req.method === 'POST' && path === '/api/bookmark') {
      const isForm = !(req.headers['content-type'] || '').includes('application/json')
      const raw = (await readBody(req)) || ''
      let uri, back
      try {
        if (isForm) { const q = new URLSearchParams(raw); uri = q.get('uri'); back = q.get('return') }
        else { const b = JSON.parse(raw || '{}'); uri = b.uri; back = b.return }
      } catch { uri = null }
      const home = safeReturn(back)
      const fail = (code, msg) => isForm ? redirect(res, home) : json(res, code, JSON.stringify({ error: msg }))
      if (!viewer) return fail(401, 'sign in first')
      if (typeof uri !== 'string' || !uri.startsWith('at://')) return fail(400, 'uri must be an at:// post uri')
      const on = await bookmarkStore.has(viewer.did, uri)
      if (on) await bookmarkStore.remove(viewer.did, uri)
      else await bookmarkStore.add(viewer.did, uri)
      if (isForm) return redirect(res, home)
      return json(res, 200, JSON.stringify({ ok: true, bookmarked: !on }))
    }

    // MUTE — private and NODE-LOCAL. Never a record: in atproto a mute is server-side state, so writing
    // one to the repo would publish "alice muted bob" to the network permanently, in a signed record.
    // Nothing here touches hpp or the repo at all.
    // Theme preference. Writes nothing but a cookie — no repo, no index, no session. A plain form POST
    // with a redirect so it works with scripting off, which is the whole point: the no-JS path is the
    // one that has to carry this, because a script-flipped class cannot fix the first paint.
    //
    // NOT HttpOnly, deliberately, unlike the session cookie: this is a display preference, and leaving
    // it readable lets a future client-side control stay in sync without a round trip. It carries no
    // authority, so there is nothing to steal.
    if (req.method === 'POST' && path === '/api/theme') {
      const isForm = !(req.headers['content-type'] || '').includes('application/json')
      const raw = (await readBody(req)) || ''
      let choice, back
      try {
        if (isForm) { const q = new URLSearchParams(raw); choice = q.get('theme'); back = q.get('return') }
        else { const b = JSON.parse(raw || '{}'); choice = b.theme; back = b.return }
      } catch { choice = null }
      const home = safeReturn(back) || '/settings'
      // 'system' clears the cookie rather than storing a third value, so "follow the system" is the
      // ABSENCE of a preference — the same state as a reader who never touched this.
      const cookie = THEMES.has(choice)
        ? `favela_theme=${choice}; Path=/; SameSite=Lax; Max-Age=${365 * 24 * 3600}`
        : 'favela_theme=; Path=/; SameSite=Lax; Max-Age=0'
      return redirect(res, home, { 'set-cookie': cookie })
    }
    if (req.method === 'POST' && path === '/api/mute') {
      const isForm = !(req.headers['content-type'] || '').includes('application/json')
      const raw = (await readBody(req)) || ''
      let did, back
      try {
        if (isForm) { const q = new URLSearchParams(raw); did = q.get('did'); back = q.get('return') }
        else { const b = JSON.parse(raw || '{}'); did = b.did; back = b.return }
      } catch { did = null }
      const home = safeReturn(back)
      const fail = (code, msg) => isForm ? redirect(res, home) : json(res, code, JSON.stringify({ error: msg }))
      if (!viewer) return fail(401, 'sign in first')
      if (typeof did !== 'string' || !did.startsWith('did:')) return fail(400, 'did required')
      if (did === viewer.did) return fail(400, 'muting yourself is meaningless')
      const on = await muteStore.isMuted(viewer.did, did)
      if (on) await muteStore.unmute(viewer.did, did)
      else await muteStore.mute(viewer.did, did)
      if (isForm) return redirect(res, home)
      return json(res, 200, JSON.stringify({ ok: true, muted: !on }))
    }

    // BLOCK — PUBLIC. app.bsky.graph.block is a real record that federates by design; bsky renders blocks
    // as mutually visible. So this writes through hpp exactly like a follow, and remembers the rkey
    // locally so unblock can delete it without scanning the repo for a matching subject.
    //
    // ⚠ KNOWN LIMIT: the appview does not yet ingest app.bsky.graph.block (adding a collection to the
    // ingest filter means bumping INGEST_VERSION and re-indexing every DID). So a block made on ANOTHER
    // device is not reflected here until that lands. Stated rather than hidden — the record itself is
    // correct and federates; only this node's awareness of a remote block is missing.
    if (req.method === 'POST' && path === '/api/block') {
      const isForm = !(req.headers['content-type'] || '').includes('application/json')
      const raw = (await readBody(req)) || ''
      let did, back
      try {
        if (isForm) { const q = new URLSearchParams(raw); did = q.get('did'); back = q.get('return') }
        else { const b = JSON.parse(raw || '{}'); did = b.did; back = b.return }
      } catch { did = null }
      const home = safeReturn(back)
      const fail = (code, msg) => isForm ? redirect(res, home) : json(res, code, JSON.stringify({ error: msg }))
      if (!viewer) return fail(401, 'sign in first')
      if (typeof did !== 'string' || !did.startsWith('did:')) return fail(400, 'did required')
      if (did === viewer.did) return fail(400, 'blocking yourself is meaningless')
      try {
        const st = await writer.state()
        const deviceDid = st && st.did
        if (!deviceDid) return fail(502, 'device did not report a DID')
        if (deviceDid !== viewer.did) return fail(403, `this node signs for ${deviceDid}, not ${viewer.did}`)
        // Prefer the INDEXED rkey: a block made on another device has no local bookkeeping, and without
        // this an unblock would appear to work while the record stayed in the repo.
        const existing = (await av.blockRkeyFor(viewer.did, did)) || (await muteStore.blockRkey(viewer.did, did))
        if (existing) {
          await writer.putRecord('app.bsky.graph.block', existing, null, { action: 'delete' })
          await muteStore.unblock(viewer.did, did)
          if (isForm) return redirect(res, home)
          return json(res, 200, JSON.stringify({ ok: true, blocked: false }))
        }
        const rkey = tidNow()
        await writer.putRecord('app.bsky.graph.block', rkey, { $type: 'app.bsky.graph.block', subject: did, createdAt: new Date().toISOString() }, { action: 'create' })
        await muteStore.block(viewer.did, did, rkey)
        if (isForm) return redirect(res, home)
        return json(res, 200, JSON.stringify({ ok: true, blocked: true }))
      } catch (e) { return fail(502, 'block failed: ' + e.message) }
    }

    // Delete one of the VIEWER'S OWN posts. Irreversible: the record leaves the repo and the delete
    // federates, so anyone already holding it sees a tombstone rather than the post.
    //
    // OWNERSHIP IS ENFORCED HERE, not by hiding the button. The UI only renders the control on your own
    // posts, but a hidden control is not a permission check — the uri arrives from the client and the
    // only thing standing between it and someone else's repo is this comparison. Two gates: the uri's DID
    // must be the viewer's, AND this node must actually sign for that DID (the same pair every other
    // write path checks, because a node signing for someone else would make the first gate meaningless).
    // GET /edit/<did>/<rkey> — the prefilled edit form. Own posts only; the check is repeated on
    // POST because a GET guard is a UI affordance, not a permission.
    {
      const m = path.match(/^\/edit\/([^/]+)\/([^/]+)$/)
      if (m && req.method === 'GET') {
        const did = decodeURIComponent(m[1]); const rkey = decodeURIComponent(m[2])
        const back = safeReturn(url.searchParams.get('return'))
        if (!viewer) return redirect(res, '/login')
        if (did !== viewer.did) return html(res, 403, editPage({ post: null, viewer, returnTo: back, error: 'you can only edit your own posts' }))
        const post = await av.getPost(did, rkey).catch(() => null)
        return html(res, post ? 200 : 404, editPage({ post, viewer, returnTo: back }))
      }
    }

    // POST /api/edit — replace a post's text in place. Mirrors /api/delete's ownership checks
    // exactly; see spec/record-vocabulary.md §10.5 for why this is honest on P2P and AP and only
    // partial on bsky.
    if (req.method === 'POST' && path === '/api/edit') {
      const isForm = !(req.headers['content-type'] || '').includes('application/json')
      const raw = (await readBody(req)) || ''
      let uri, back, text
      try {
        if (isForm) { const q = new URLSearchParams(raw); uri = q.get('uri'); back = q.get('return'); text = q.get('text') }
        else { const b = JSON.parse(raw || '{}'); uri = b.uri; back = b.return; text = b.text }
      } catch { uri = null }
      const home = safeReturn(back)
      const ref = typeof uri === 'string' ? parseAtUri(uri) : null
      const fail = async (code, msg) => {
        if (!isForm) return json(res, code, JSON.stringify({ error: msg }))
        const post = ref ? await av.getPost(ref.did, ref.rkey).catch(() => null) : null
        return html(res, code, editPage({ post, viewer, returnTo: home, error: msg }))
      }
      if (!viewer) return fail(401, 'sign in first')
      if (!ref) return fail(400, 'uri must be an at:// post uri')
      if (ref.did !== viewer.did) return fail(403, 'you can only edit your own posts')
      if (!POST_COLLECTIONS.includes(ref.collection)) return fail(400, 'not a post collection')
      if (!text || !String(text).trim()) return fail(400, 'a post cannot be edited to nothing — delete it instead')
      try {
        const st = await writer.state()
        const deviceDid = st && st.did
        if (!deviceDid) return fail(502, 'device did not report a DID')
        if (deviceDid !== viewer.did) return fail(403, `this node signs for ${deviceDid}, not ${viewer.did}`)
        // The PRIOR record is what preserves createdAt, reply and embed — an edit that dropped them
        // would silently detach a thread or delete images (writer.editPost documents why).
        const prior = await av.getPost(ref.did, ref.rkey).catch(() => null)
        await writer.editPost(ref.collection, ref.rkey, String(text), {
          prior: prior && prior.record ? prior.record : null,
          resolveHandle
        })
        if (isForm) return redirect(res, home)
        return json(res, 200, JSON.stringify({ ok: true, edited: uri }))
      } catch (e) { return fail(502, 'edit failed: ' + e.message) }
    }

    if (req.method === 'POST' && path === '/api/delete') {
      const isForm = !(req.headers['content-type'] || '').includes('application/json')
      const raw = (await readBody(req)) || ''
      let uri, back
      try {
        if (isForm) { const q = new URLSearchParams(raw); uri = q.get('uri'); back = q.get('return') }
        else { const b = JSON.parse(raw || '{}'); uri = b.uri; back = b.return }
      } catch { uri = null }
      const home = safeReturn(back)
      const fail = (code, msg) => isForm ? redirect(res, home) : json(res, code, JSON.stringify({ error: msg }))
      if (!viewer) return fail(401, 'sign in first')
      const ref = typeof uri === 'string' ? parseAtUri(uri) : null
      if (!ref) return fail(400, 'uri must be an at:// post uri')
      if (ref.did !== viewer.did) return fail(403, 'you can only delete your own posts')
      if (!POST_COLLECTIONS.includes(ref.collection)) return fail(400, 'not a post collection')
      try {
        const st = await writer.state()
        const deviceDid = st && st.did
        if (!deviceDid) return fail(502, 'device did not report a DID')
        if (deviceDid !== viewer.did) return fail(403, `this node signs for ${deviceDid}, not ${viewer.did}`)
        await writer.putRecord(ref.collection, ref.rkey, null, { action: 'delete' })
        // Drop it from our own index immediately, so the page it redirects to does not still show it
        // while the firehose round-trip completes.
        try { await av.delPost({ did: deviceDid, rkey: ref.rkey }) } catch {}
        if (isForm) return redirect(res, home)
        return json(res, 200, JSON.stringify({ ok: true, deleted: uri }))
      } catch (e) { return fail(502, 'delete failed: ' + e.message) }
    }

    // ── write: JSON (client) OR form-urlencoded (no-JS <form>) ──
    if (req.method === 'POST' && path === '/api/post') {
      const ctype0 = req.headers['content-type'] || ''
      // ⛔ SIGN-IN GATE. This route had none: it authored as whatever DID the node signs for, so ANY
      // unauthenticated request that could reach the port posted as that identity. FAVELA_HOST defaults
      // to 0.0.0.0, so "could reach the port" is the whole network. Confirmed live on 2026-08-11 — an
      // anonymous curl created a post in wj62.
      //
      // The near-miss is instructive: the images branch below already refuses without a viewer ("sign in
      // to attach images"), so the gate was considered and applied to the ATTACHMENT rather than to the
      // post. Every other write route here checks `!viewer` first; this one is now consistent with them.
      //
      // Checked BEFORE the body is read — an unauthenticated caller should not get to hand us bytes.
      if (!viewer) {
        return ctype0.includes('application/json')
          ? json(res, 401, JSON.stringify({ error: 'sign in first' }))
          : redirect(res, '/')
      }
      const raw = (await readBody(req)) || ''
      const ctype = ctype0
      const isJson = ctype.includes('application/json')
      let text, scope, images, replyTo
      // `images` is JSON-only: it carries blob REFS returned by /api/upload, which the no-JS <form>
      // path has no way to produce. The form keeps working exactly as before (text + scope).
      // `replyTo` IS form-safe — the reply box is a plain form on the post page.
      // `quoteOf` is form-safe like replyTo: the quote composer is a plain form, so quoting works with
      // scripting off.
      let quoteOf, gate, lang, quoteGate
      if (isJson) { const b = JSON.parse(raw || '{}'); text = b.text; scope = b.scope; images = Array.isArray(b.images) ? b.images : null; replyTo = b.replyTo; quoteOf = b.quoteOf; gate = b.gate; lang = b.lang; quoteGate = b.quoteGate } else { const p = new URLSearchParams(raw); text = p.get('text'); scope = p.get('scope'); replyTo = p.get('replyTo'); quoteOf = p.get('quoteOf'); gate = p.get('gate'); lang = p.get('lang'); quoteGate = p.get('quoteGate') }
      const backTo = replyTo ? (parseAtUri(replyTo) ? `/post/${encodeURIComponent(parseAtUri(replyTo).did)}/${encodeURIComponent(parseAtUri(replyTo).rkey)}` : '/') : '/'
      if (!text) return isJson ? json(res, 400, JSON.stringify({ error: 'text required' })) : redirect(res, backTo)
      if (images && images.length && !viewer) return json(res, 401, JSON.stringify({ error: 'sign in to attach images' }))
      // A reply carries reply: { root, parent }, both strongRefs. `root` is the THREAD root: the parent's
      // own root when the parent is itself a reply, else the parent. Getting this wrong is what makes a
      // thread render as a flat list of orphans in every other client.
      let reply = null
      if (replyTo) {
        const ref = parseAtUri(replyTo)
        if (!ref) return isJson ? json(res, 400, JSON.stringify({ error: 'replyTo must be an at:// uri' })) : redirect(res, '/')
        const parent = await strongRef(replyTo, getRecordStore)
        if (!parent) return isJson ? json(res, 409, JSON.stringify({ error: 'cannot reply to a post whose record bytes are not held locally — a reply needs its cid' })) : redirect(res, backTo)
        let root = parent
        try {
          const prec = await (await getRecordStore(ref.did)).get(ref.collection, ref.rkey)
          const pr = prec && prec.reply && prec.reply.root
          if (pr && typeof pr.uri === 'string' && typeof pr.cid === 'string') root = { uri: pr.uri, cid: pr.cid }
        } catch {}
        reply = { root, parent }
      }
      // A quote embeds a strongRef — uri AND cid — so it FAILS CLOSED exactly like a like or a reply:
      // without the cid the record is lexicon-invalid and federates as nothing while looking fine here.
      let quote = null
      if (quoteOf) {
        if (!parseAtUri(quoteOf)) return isJson ? json(res, 400, JSON.stringify({ error: 'quoteOf must be an at:// uri' })) : redirect(res, '/')
        quote = await strongRef(quoteOf, getRecordStore)
        if (!quote) return isJson ? json(res, 409, JSON.stringify({ error: 'cannot quote a post whose record bytes are not held locally — a quote needs its cid' })) : redirect(res, backTo)
      }
      // LANGUAGE. `langs` was hardcoded ['en'], which is wrong for anyone who does not write in English
      // and is not cosmetic: bsky's custom-feed tuner runs a language detector on posts that omit langs
      // and DROPS what it does not read as the viewer's language, so a mis-declared language makes a post
      // vanish from feeds while looking fine everywhere else. A bad value is ignored rather than written.
      const langs = /^[a-z]{2}(-[A-Za-z0-9]{2,8})?$/.test(String(lang || '')) ? [String(lang)] : ['en']
      // SELF-THREAD. A line containing only --- splits the box into segments, each posted as a reply to
      // the one before. Chosen over N textareas because it works with scripting off and survives a
      // half-written draft being pasted around.
      //
      // The CHAIN is the whole correctness question: every segment after the first replies to its
      // PREDECESSOR (parent) while carrying the FIRST post as root. Getting root wrong is what makes a
      // thread render as a pile of orphans in every other client. Segments are posted in order and a
      // failure mid-way STOPS rather than continuing — a thread with a hole in it is worse than a short
      // one, and the segments already posted stay up.
      const segments = String(text).split(/\r?\n\s*---\s*(?:\r?\n|$)/).map((t) => t.trim()).filter(Boolean)
      if (!reply && segments.length > 1) {
        const posted = []
        let root = null
        let parent = null
        for (const seg of segments) {
          const r = await writer.post(seg, {
            scope: scope || DEFAULT_SCOPE,
            // Images and the quote ride the FIRST segment only — they belong to the thread's opening
            // post, and repeating them on every segment would post the same picture N times.
            images: posted.length ? null : images,
            quote: posted.length ? null : quote,
            reply: parent ? { root, parent } : null,
            resolveHandle,
            langs
          })
          const st3 = await writer.state()
          const uri = `at://${st3.did}/${r.collection}/${r.rkey}`
          const ref = await strongRef(uri, getRecordStore)
          if (!ref) break // cannot chain without a cid — stop cleanly rather than orphan the rest
          if (!root) root = ref
          parent = ref
          posted.push(r)
        }
        const first = posted[0]
        if (first && gate && GATE_CHOICES.includes(gate) && gate !== 'everyone') {
          try {
            const st4 = await writer.state()
            const rec = gateRecord({ postUri: `at://${st4.did}/${first.collection}/${first.rkey}`, choice: gate })
            if (rec) await writer.putRecord('app.bsky.feed.threadgate', first.rkey, rec, { action: 'create' })
          } catch { /* the thread itself is fine */ }
        }
        return isJson ? json(res, 200, JSON.stringify({ ok: true, posts: posted.length, first: first || null })) : redirect(res, backTo)
      }
      const out = await writer.post(text, { scope: scope || DEFAULT_SCOPE, images, reply, resolveHandle, quote, langs })
      // THREADGATE. A separate record whose rkey is IDENTICAL to the post's — that rkey is the entire
      // linkage, so it can only be written once the post has one. 'everyone' writes NOTHING: an
      // allow-everything gate would read as an empty allow, which means NOBODY (see lib/threadgate.js).
      // A gate on a REPLY is meaningless (it gates a thread root), so it is only written for top-level
      // posts. Failure here must never lose the post that already succeeded.
      if (gate && (GATE_CHOICES.includes(gate) || gate.startsWith('at://')) && gate !== 'everyone' && !reply) {
        try {
          const st2 = await writer.state()
          // A gate value that is an at:// uri means "members of THIS list" — #listRule, now authorable
          // because lists are. Only your OWN list: the uri must name your DID, or the form could gate a
          // thread on someone else's membership.
          let rec
          if (gate.startsWith('at://')) {
            const lref = parseAtUri(gate)
            rec = (lref && lref.did === st2.did && lref.collection === LIST_COLLECTION)
              ? { $type: 'app.bsky.feed.threadgate', post: `at://${st2.did}/${out.collection}/${out.rkey}`, allow: [{ $type: 'app.bsky.feed.threadgate#listRule', list: gate }], createdAt: new Date().toISOString() }
              : null
          } else {
            rec = gateRecord({ postUri: `at://${st2.did}/${out.collection}/${out.rkey}`, choice: gate })
          }
          if (rec) await writer.putRecord('app.bsky.feed.threadgate', out.rkey, rec, { action: 'create' })
        } catch (e) { console.error(JSON.stringify({ msg: 'threadgate write failed (post itself is fine)', error: e.message })) }
      }
      // POSTGATE — same rkey binding as the threadgate. 'anyone' writes nothing. Like a threadgate it
      // only makes sense on a top-level post, and a failure must never lose the post that succeeded.
      if (quoteGate === 'nobody' && QUOTE_CHOICES.includes(quoteGate) && !reply) {
        try {
          const st5 = await writer.state()
          const pg = postgateRecord({ postUri: `at://${st5.did}/${out.collection}/${out.rkey}`, choice: quoteGate })
          if (pg) await writer.putRecord('app.bsky.feed.postgate', out.rkey, pg, { action: 'create' })
        } catch (e) { console.error(JSON.stringify({ msg: 'postgate write failed (post itself is fine)', error: e.message })) }
      }
      // Index our own write immediately so it shows without waiting for the firehose round-trip.
      //
      // ⛔ THIS USED TO BE `if (reply)`. A reply appeared in its thread instantly and a top-level post did
      // not appear on the timeline at all until the firehose came back around — which reads as "my post
      // vanished", and on 2026-08-18 sent us looking for a sync bug that was this asymmetry.
      //
      // READ THE RECORD BACK rather than rebuilding it. The hand-built shape carried text/createdAt/reply
      // and dropped langs, embeds and facets, so an optimistic row rendered as a DEGRADED COPY of the post
      // that then changed under the reader when the real one landed — an image appearing seconds later, a
      // link becoming a link. The bytes hpp just signed are the truth; ask for them. The rebuild stays as
      // a fallback for the window where the write is durable but not yet readable.
      //
      // Safe to run twice: putPost is dedup-gated by content signature, so the firehose fold that follows
      // re-reads without re-writing.
      try {
        const wdid = (await writer.state()).did
        let rec = null
        try { rec = await (await getRecordStore(wdid)).get(out.collection, out.rkey) } catch {}
        await av.putPost({
          did: wdid,
          collection: out.collection,
          rkey: out.rkey,
          record: rec || { $type: out.collection, text, createdAt: new Date().toISOString(), langs, ...(reply ? { reply } : {}) }
        })
      } catch {}
      // ?posted=1 is the SUCCESS signal draft.js waits for. Clearing the draft on submit instead would
      // throw the text away in exactly the case draft recovery exists for — the write that failed.
      return isJson ? json(res, 200, JSON.stringify(out)) : redirect(res, backTo + (backTo.includes('?') ? '&' : '?') + 'posted=1')
    }

    json(res, 404, JSON.stringify({ error: 'not found' }))
  } catch (e) {
    // LOG IT, don't only answer it. This is the single catch-all for every route and it returned the
    // reason to the CALLER and nowhere else — so a client that discards the body (an embedded WebView
    // showing its own "HTTP 500" screen) leaves the operator with a 500 and no cause anywhere on the box.
    // Cost a real debugging session on favela-android 2026-08-11. With the stack, because `e.message`
    // alone cannot say WHICH of a route's several awaits threw.
    //
    // ⛔ `req.url`, NOT the parsed `url` — that is declared with const INSIDE the try above, so it is out
    // of scope here and naming it would throw a ReferenceError from inside the error handler.
    console.error(JSON.stringify({ msg: 'request failed', method: req.method, url: req.url, error: e.message, stack: e.stack }))
    json(res, 500, JSON.stringify({ error: e.message }))
  }
})

// ── com.atproto.label.subscribeLabels — WS firehose (phase 5), shares the HTTP server via 'upgrade' ──
// Only wired when a labeler is configured. bsky/Ozone (via the membrane proxy) subscribe with ?cursor=;
// LabelFirehose replays from there then live-tails. Any other upgrade path is rejected.
if (labelFirehose) {
  const wss = new bareWs.Server({ server })
  wss.on('connection', (ws, req) => {
    try {
      const u = new URL(req.url, 'http://localhost')
      if (u.pathname !== '/xrpc/com.atproto.label.subscribeLabels') { try { ws.destroy() } catch {} ; return }
      const cursor = Number(u.searchParams.get('cursor')) || 0
      const stop = labelFirehose.serve((bytes) => { try { ws.write(Buffer.from(bytes)) } catch {} }, { cursor })
      ws.on('close', stop)
      ws.on('error', () => { try { stop() } catch {} })
    } catch { try { ws.destroy() } catch {} }
  })
  console.log('[favela] subscribeLabels firehose online (WS)')
}

server.listen(PORT, HOST, () => console.log(`[favela] SSR gateway on ${EXTERNAL_URL} (bind ${HOST}:${PORT})`))

// ── Clean shutdown — CLOSE the corestores, don't just die ────────────────────────────────────────────
// favela-web had NO signal handler, so `pgh app stop` (SIGTERM, then SIGKILL after the grace period)
// killed it without ever calling close(). That STRANDS disk: RocksDB fallocate's each open WAL with
// FALLOC_FL_KEEP_SIZE at open — traced as a single `fallocate(fd, FALLOC_FL_KEEP_SIZE, 0, 73819750)`,
// i.e. write_buffer_size (64 MB) * 1.1 — and those blocks are released only by the `ftruncate(fd,
// <live size>)` that runs on a clean close. Measured: WHILE OPEN size=6192 allocated=73826304;
// AFTER CLOSE size=6192 allocated=8192. So an unclean exit leaves ~70 MB per store allocated
// indefinitely — exactly how the orphaned web-did dir ended up holding 70 MB with ZERO open fds.
//
// hpp already does this (index.js SIGINT/SIGTERM -> shutdown). Closing `store` covers the did/idx/comm
// namespaces (they are namespaces of it, not separate instances); labelerStore is separate by design
// and closed explicitly. Idempotent, and each close is time-boxed: a hung close must not block exit, or the
// supervisor SIGKILLs us and we are back to stranding blocks.
let shuttingDown = false
async function shutdown (signal, code = 0) {
  if (shuttingDown) return
  shuttingDown = true
  console.log(`[favela] ${signal} — closing stores (releases preallocated WAL blocks)`)
  const bounded = (p) => Promise.race([Promise.resolve(p).catch(() => {}), new Promise((r) => setTimeout(r, 4000))])
  try { server.close() } catch {}
  await bounded(swarm.destroy())
  await bounded(store.close())
  if (labelerStore) await bounded(labelerStore.close())
  console.log('[favela] shutdown complete')
  process.exit(code)
}
process.on('SIGTERM', () => { shutdown('SIGTERM') })
process.on('SIGINT', () => { shutdown('SIGINT') })

// ── OTA ──────────────────────────────────────────────────────────────────────────────────────────
// favela-web had NO control surface at all, so pgh-sidecar had no udsPath for it and could not push
// `release-ready`: autoupdate installed a new tree and the daemon kept serving the OLD code until
// someone ran stop/start by hand. That is the INSTALLED != RUNNING trap.
//
// A minimal hyper-svc Service on a UDS — status + release-ready, nothing else. This is a MANAGEMENT
// surface, not a second way into the app: it is a unix socket with no HTTP transport, so it is reachable
// only by something already on this machine as this user.
//
// ⚠ NOT pgh-runtime. It fetches ROOT trees without dep closures, which produces a broken install — the
// missing-dependency MODULE_NOT_FOUND that took the membrane down on 2026-07-31. The sidecar already
// does the full install correctly; our only job is to exit so the supervisor respawns onto it.
try {
  const { Service } = await import('hyper-svc')
  const { maintainSidecarRegistration } = await import('../lib/sidecar.js')
  const udsPath = process.env.FAVELA_SOCK || STORE('svc.sock')
  const svc = new Service({ name: 'favela-web', uds: udsPath })
  svc.handle('status', async () => ({ ok: true, dids: ROSTER, port: PORT }))
  // Operator HEALING, over the UDS rather than HTTP on purpose: this daemon binds 0.0.0.0, and a route
  // that triggers outbound fetches and writes records has no business being reachable from the network.
  // Same shape as hpp's `reindex-overlay` — repair the RUNNING daemon, no restart, owner-gated by the
  // socket's file permissions. It must run IN here because the daemon holds the index store's lock.
  //
  // DRY RUN unless params.write. Driven by `favela-web repair-bytes` (lib/cli.js).
  svc.handle('repair-bytes', async (ctx, params = {}) => {
    const { repairBytes } = await import('../lib/repair-bytes.js')
    const { createFetchRecord, createVerifyRecord, createIdentityResolver } = await import('../lib/record-fetch.js')
    const want = params && params.did ? [params.did] : ROSTER
    // Only ever repair DIDs this node does NOT host: where hpp is the authority those bytes are its job,
    // and racing it is the whole class of bug this repair exists downstream of.
    const dids = want.filter(isForeignDid)
    const skipped = want.filter((d) => !isForeignDid(d))
    const resolveIdentity = createIdentityResolver({ fetchImpl: bareFetch, plc: new PlcDirectory({ fetchImpl: bareFetch }) })
    const report = await repairBytes({
      dids,
      listRefs: (did) => av.indexedRefs(did),
      openStore: getRecordStore,
      fetchRecord: createFetchRecord({ doFetch: bareFetch, resolveIdentity }),
      verifyRecord: createVerifyRecord(),
      write: !!(params && params.write),
      limit: Number(params && params.limit) || 0,
      onEvent: (event, detail) => {
        if (event === 'written' || event === 'unverified' || event === 'reencode-differs') {
          console.log(JSON.stringify({ msg: 'repair-bytes', event, ...detail }))
        }
      }
    })
    return { ok: true, write: !!(params && params.write), dids, skippedHostedLocally: skipped, ...report }
  })
  // The convergence loop: head (are we behind?), diff (what exactly differs?), backfill (pull it).
  // Same UDS-only reasoning as repair-bytes above. All three share one resolver so the DID document is
  // fetched once per call, and all three refuse DIDs this node HOSTS — hpp is the authority there.
  const syncDeps = async () => {
    const rs = await import('../lib/repo-sync.js')
    const { createIdentityResolver } = await import('../lib/record-fetch.js')
    const resolveIdentity = createIdentityResolver({ fetchImpl: bareFetch, plc: new PlcDirectory({ fetchImpl: bareFetch }) })
    return { rs, resolveIdentity }
  }
  const targetDids = (params) => {
    const want = params && params.did ? [params.did] : ROSTER
    return { dids: want.filter(isForeignDid), skippedHostedLocally: want.filter((d) => !isForeignDid(d)) }
  }

  // The collection ledger (org #33). The THIRD of the three classes spec §2 defines, which no verb could
  // previously show: `diff` reports what the authority holds, this reports what has arrived HERE and what
  // we decided about it. Reads the daemon's own index, so it must run over the socket like the rest.
  //
  // The tracked + ignored halves are returned even when empty, because "we index these five, deliberately
  // skip these two, and have never classified these" is the whole answer — a bare list of unknowns would
  // leave the reader to work out what the other two classes even are.
  svc.handle('collections', async (ctx, params = {}) => {
    const ledger = await av.collectionLedger()
    const seen = new Map(ledger.map((e) => [e.collection, e]))
    return {
      ok: true,
      // The RAW ledger, alongside the curated classes below. The curation exists for a human reading a
      // diagnostic; a programmatic caller (favela-android's `collections` IPC verb) wants the entries
      // themselves, and synthesising them back out of `unknown` would be a subset masquerading as the
      // whole. Additive — nothing that reads the curated fields changes.
      ledger,
      tracked: [...Appview.TRACKED.entries()].map(([collection, meta]) => ({ collection, view: meta.view, bytes: !!meta.bytes })),
      ignored: [...IGNORED_COLLECTIONS.entries()].map(([collection, reason]) => ({
        collection,
        reason,
        // Whether this node has actually SEEN it, and how often. An ignore entry nothing ever matches is
        // worth knowing too — it may be describing a lexicon that no longer exists.
        seen: seen.has(collection) ? seen.get(collection).count : 0,
        lastSeen: seen.has(collection) ? seen.get(collection).lastSeen : null
      })),
      unknown: ledger.filter((e) => e.class === 'unknown')
    }
  })

  svc.handle('repo-head', async (ctx, params = {}) => {
    const { rs, resolveIdentity } = await syncDeps()
    const fetchHead = rs.createFetchHead({ doFetch: bareFetch, resolveIdentity })
    const { dids, skippedHostedLocally } = targetDids(params)
    const out = []
    for (const did of dids) {
      const remote = await fetchHead(did)
      // Our rev is the highest we have folded; the peer's head carries it (same field the relay-miss log
      // reads). Absent peer/head = we have never folded this DID at all, which is itself the answer.
      const front = byDid.get(did) || null
      const localRev = front && front.head ? (front.head.rev || null) : null
      out.push({
        did,
        remoteRev: remote ? remote.rev : null,
        localRev,
        active: remote ? remote.active : null,
        status: remote ? remote.status : null,
        behind: remote && remote.rev && localRev ? (localRev < remote.rev) : null,
        unreachable: remote ? null : 'could not read the authoritative head'
      })
    }
    return { ok: true, heads: out, skippedHostedLocally }
  })

  const runDiff = async (params, { rs, resolveIdentity }) => {
    const fetchRepo = rs.createFetchRepo({ doFetch: bareFetch, resolveIdentity })
    const { dids, skippedHostedLocally } = targetDids(params)
    const results = []
    for (const did of dids) {
      // No `since`: convergence needs the COMPLETE record set. `extraLocal` ("we hold it, the repo does
      // not") is only meaningful against the whole repo — against a diff, every record older than the
      // rev looks extra and the report cries wolf on every run. See lib/repo-sync.js.
      const got = await fetchRepo({ did })
      if (!got) { results.push({ did, unreachable: 'could not fetch the repo' }); continue }
      const remote = await rs.parseRepo({ did, carBytes: got.carBytes, pubkey: got.identity && got.identity.pubkey, partial: got.partial })
      if (!remote) { results.push({ did, unreachable: 'malformed repo CAR' }); continue }
      if (!remote.ok) { results.push({ did, refused: remote.reason }); continue }
      const d = await rs.diffRepo({
        did,
        remote,
        // Per-VIEW comparison: each tracked collection is checked against the view that owns it, not
        // against the post index (which is why "in sync" used to mean "posts are in sync").
        tracked: Appview.TRACKED,
        listRefsFor: (x, collection) => av.indexedRefsFor(x, collection),
        isIgnored: isIgnoredCollection,
        hasBytes: async (x, collection, rkey) => {
          try { const s = await getRecordStore(x); return (await s.getRaw(collection, rkey)) != null } catch { return false }
        }
      })
      // Referenced-blob convergence (spec §6). Local-only: the records are already in hand, so this
      // costs no extra fetch. Orphans are NOT covered — that needs listBlobs, which the membrane does
      // not implement.
      const { diffBlobs } = await import('../lib/blob-refs.js')
      const blobs = await diffBlobs({
        records: remote.records,
        hasBlob: async (cid) => { try { return isSafeCid(cid) && fs.existsSync(blobPath(OVERLAY_ROOT, did, cid)) } catch { return false } },
        // The authority's own inventory — the ONLY thing that can reveal an orphan. A membrane or peer
        // too old to answer returns null, and the report degrades to "orphans unchecked" rather than
        // claiming there are none.
        listAuthorityBlobs: async () => {
          const identity = got.identity
          if (!identity || !identity.pds) return null
          const out = []
          let cursor = null
          for (let page = 0; page < 20; page++) {
            let u = identity.pds + '/xrpc/com.atproto.sync.listBlobs?did=' + encodeURIComponent(did) + '&limit=1000'
            if (cursor) u += '&cursor=' + encodeURIComponent(cursor)
            const res = await bareFetch(u, { method: 'GET', headers: { accept: 'application/json' }, timeout: 30000 })
            if (!res || res.ok === false) return null
            const body = await res.json()
            if (!body || !Array.isArray(body.cids)) return null
            out.push(...body.cids)
            cursor = body.cursor || null
            if (!cursor) break
          }
          return { cids: out }
        }
      })
      results.push({ ...d, blobs, _remote: remote })
    }
    return { results, skippedHostedLocally }
  }

  svc.handle('repo-diff', async (ctx, params = {}) => {
    const deps = await syncDeps()
    const { results, skippedHostedLocally } = await runDiff(params, deps)
    // Strip the parsed repo — it carries every record's bytes and has no business crossing the socket.
    return { ok: true, skippedHostedLocally, dids: results.map(({ _remote, ...rest }) => rest) }
  })

  svc.handle('repo-backfill', async (ctx, params = {}) => {
    const deps = await syncDeps()
    const { results, skippedHostedLocally } = await runDiff(params, deps)
    const write = !!(params && params.write)
    const out = []
    for (const r of results) {
      if (!r._remote) { out.push(r); continue }
      const { _remote, ...diff } = r
      const applied = await deps.rs.applyBackfill({
        did: r.did,
        remote: _remote,
        diff,
        applyOps: (did, ops) => av.applyCommit(did, ops),
        putBytes: async (did, collection, rkey, value) => { const s = await getRecordStore(did); await s.put(collection, rkey, value) },
        write,
        limit: Number(params && params.limit) || 0,
        onEvent: (event, detail) => console.log(JSON.stringify({ msg: 'repo-backfill', event, did: r.did, ...detail }))
      })
      // Blobs are a separate axis from records: same "pull what is missing" intent, different transport
      // (getBlob, by CID). Verified by CONTENT ADDRESS — the CID is the hash, so a wrong body cannot be
      // written under the right name; we check it rather than trusting the server.
      let blobsApplied = null
      if (diff.blobs && diff.blobs.missing.length) {
        blobsApplied = { fetched: 0, unfetchable: 0, hashMismatch: 0, errors: 0 }
        if (write) {
          const identity = await deps.resolveIdentity(r.did)
          for (const b of diff.blobs.missing) {
            if (!identity || !isSafeCid(b.cid)) { blobsApplied.unfetchable++; continue }
            try {
              const url = identity.pds + '/xrpc/com.atproto.sync.getBlob?did=' + encodeURIComponent(r.did) + '&cid=' + encodeURIComponent(b.cid)
              const res = await bareFetch(url, { method: 'GET', timeout: 60000 })
              if (!res || res.ok === false) { blobsApplied.unfetchable++; continue }
              const bytes = new Uint8Array(await res.arrayBuffer())
              if (!bytes.length) { blobsApplied.unfetchable++; continue }
              const { verifyBlobCid } = await import('../lib/blob-refs.js')
              if (!(await verifyBlobCid(bytes, b.cid))) { blobsApplied.hashMismatch++; continue }
              const p = blobPath(OVERLAY_ROOT, r.did, b.cid)
              fs.mkdirSync(p.slice(0, p.lastIndexOf('/')), { recursive: true })
              fs.writeFileSync(p, bytes)
              blobsApplied.fetched++
              console.log(JSON.stringify({ msg: 'repo-backfill', event: 'blob-written', did: r.did, cid: b.cid, bytes: bytes.length }))
            } catch (e) { blobsApplied.errors++ }
          }
        }
      }
      out.push({ ...diff, applied, blobsApplied })
    }
    return { ok: true, write, skippedHostedLocally, dids: out }
  })

  svc.handle('release-ready', async (ctx, params = {}) => {
    const ver = (params && params.version) || '?'
    console.log(`[ota] release-ready ${ver} — sidecar installed; exiting 75 for supervisor respawn`)
    // Respond FIRST, then shut down cleanly; exit 75 is the supervisor's respawn signal.
    setImmediate(() => { shutdown('ota', 75).catch(() => process.exit(75)) })
    return { ok: true, willRespawn: true }
  })
  await svc.listen()
  // Report the RUNNING version, not null. This was null, so `pgh app status` could only ever show the
// version on DISK — which is exactly the number that lies when an app installs an update and does not
// restart. Now the process states its own.
maintainSidecarRegistration({ udsPath, name: process.env.PGH_APP_NAME || 'favela-web', runtime: 'bare', version: VERSION })
  console.log(`[favela] control surface on ${udsPath} — OTA respawn armed`)
} catch (e) {
  // Non-fatal by design: serving the timeline matters more than being remotely manageable.
  console.error('[favela] control surface unavailable (non-fatal):', (e && e.message) || e)
}
// ap-followers — read the ActivityPub side of a DID's follower graph.
//
// THE POINT. favela-web's follower list shows follows it has indexed from atproto. The same identity
// also has an ActivityPub actor (ap-bridge), and people follow THAT. Those followers were invisible
// here, so a page claiming to list "followers" was quietly listing only some of them.
//
// ★ THE BINDING IS THE ACTOR'S OWN CLAIM, NOT OUR CONFIG. We fetch the actor document and read
// `alsoKnownAs`; only if it names the DID being viewed do we attribute its followers to that profile.
// Configuring "actor X belongs to DID Y" by hand would let a typo attribute strangers' followers to
// someone, and would drift the moment the actor changed.
//
// ⚠ `alsoKnownAs` is a CLAIM, not proof — the same lesson handles taught us (a DID can assert any
// handle; only bidirectional verification settles it). The rigorous check is that the DID's own
// document points BACK at the actor. We do not do that here, and this is only safe because the actor
// URL is OUR OWN bridge, supplied by the operator via config — a trusted endpoint describing identities
// we already host. Do NOT reuse this to ingest a stranger's actor without adding the reverse check.
//
// FAILS SOFT, ALWAYS. This is an optional, additional source over a network hop to another host. If
// ap-bridge is down, slow, or returns nonsense, the follower page must still render its atproto
// followers. An enrichment that can break the page it enriches is worse than the gap it fills.

const DEFAULT_TIMEOUT = 2500
const CACHE_MS = 60_000

// "https://prsm.space/users/fleeky" -> "@fleeky@prsm.space" — the form a fediverse user recognises as
// their own address. Purely derived from the URL; we do not fetch each follower (a page of them would
// be a page of cross-host requests, and the address is the part that identifies them anyway).
export function actorHandle (uri) {
  try {
    const u = new URL(uri)
    const segs = u.pathname.split('/').filter(Boolean)
    const name = segs[segs.length - 1]
    if (!name) return null
    return `@${name}@${u.host}`
  } catch { return null }
}

function isHttps (s) {
  try { return new URL(s).protocol === 'https:' } catch { return false }
}

export function createApFollowers ({ base = null, doFetch = null, timeoutMs = DEFAULT_TIMEOUT, cacheMs = CACHE_MS } = {}) {
  const enabled = !!(base && doFetch)
  const cache = new Map() // key -> { at, value }

  const withDeadline = (p) => Promise.race([
    p,
    new Promise((resolve) => setTimeout(() => resolve(null), timeoutMs))
  ])

  async function getJson (url) {
    const hit = cache.get(url)
    if (hit && Date.now() - hit.at < cacheMs) return hit.value
    let value = null
    try {
      const res = await withDeadline(doFetch(url, { headers: { accept: 'application/activity+json' } }))
      if (res && res.ok) value = await res.json()
    } catch { value = null }
    cache.set(url, { at: Date.now(), value })
    return value
  }

  return {
    get enabled () { return enabled },

    // -> { did, actor, followersUrl } | null. The actor's self-description, including which DID it
    // claims to be. Cached, because every follower-page render would otherwise re-fetch it.
    async identity () {
      if (!enabled) return null
      const doc = await getJson(base.replace(/\/+$/, '') + '/ap/actor')
      if (!doc || typeof doc !== 'object') return null
      const aka = Array.isArray(doc.alsoKnownAs) ? doc.alsoKnownAs : (doc.alsoKnownAs ? [doc.alsoKnownAs] : [])
      const did = aka.find((v) => typeof v === 'string' && v.startsWith('did:')) || null
      if (!did) return null
      return { did, actor: doc.id || null, followersUrl: typeof doc.followers === 'string' ? doc.followers : null }
    },

    // The set of rkeys ap-bridge has actually PROJECTED, read from its outbox — the observed half of
    // the reach display (lib/reach.js). One fetch covers a whole page of posts.
    //
    // Returns null (not an empty Set) when the AP side is unconfigured or unreachable, because
    // "nothing projected" and "could not ask" must not render the same way. Object ids are
    // `<base>/ap/objects/<rkey>`, matching ap-bridge's objectIdFor().
    async projectedRkeys (did) {
      if (!enabled || !did) return null
      const id = await this.identity()
      if (!id || id.did !== did) return null
      const coll = await getJson(base.replace(/\/+$/, '') + '/ap/outbox')
      if (!coll || !Array.isArray(coll.orderedItems)) return null
      const set = new Set()
      for (const it of coll.orderedItems) {
        const uri = typeof it === 'string' ? it : (it && (typeof it.id === 'string' ? it.id : null))
        const m = uri && /\/ap\/objects\/([^/?#]+)$/.exec(uri)
        if (m) set.add(m[1])
      }
      return set
    },

    // Followers of `did`, or [] when this actor is not that DID. Returns rows shaped for the follower
    // list: no `did` (we hold no DID for a fediverse account), a `url` to their own profile, and a
    // `source` label so the page can say where the row came from rather than blending it in.
    async followersOf (did) {
      if (!enabled || !did) return []
      const id = await this.identity()
      // NOT our DID -> not our followers. Silently returning the wrong actor's followers would be the
      // worst possible failure here.
      if (!id || id.did !== did || !id.followersUrl) return []
      const coll = await getJson(id.followersUrl)
      const items = coll && Array.isArray(coll.orderedItems) ? coll.orderedItems : []
      const out = []
      for (const it of items) {
        // Items may be bare URI strings or embedded objects; take the id either way, and require https
        // so a malformed collection can never put a javascript: or http: URL into an href.
        const uri = typeof it === 'string' ? it : (it && typeof it.id === 'string' ? it.id : null)
        if (!uri || !isHttps(uri)) continue
        out.push({ did: null, url: uri, displayName: actorHandle(uri) || uri, handle: null, verified: false, source: 'fediverse' })
      }
      return out
    }
  }
}
// ap-inbox.js — read what the fediverse sent us, from ap-bridge's control socket.
//
// ap-bridge 0.0.6 keeps inbound replies, mentions, likes and boosts (before that it verified them,
// returned 202, and dropped them). They are NOT served over its public HTTP surface, deliberately:
// an AP inbox holds other people's messages to us, and publishing it would republish their content
// under our host. So this reads the control socket, which is local and privileged.
//
// ⛔ LOCAL ONLY, AND THAT IS THE HONEST LIMIT. ap-bridge is single-instance by construction — its RSA
// keypair, follower list and delivered-map are per-node state, and ap.7rnx.net is a static vhost to
// one backend. A favela-web on any other host cannot read this and must SAY so rather than render an
// empty list.
//
// ⛔ null MEANS "COULD NOT ASK". [] means "asked, nothing there". The existing AP reach reader draws
// exactly this distinction ("so 'not projected' and 'could not ask' never render alike") and the
// notifications page depends on it: a user with no replies and a user whose node cannot see the
// fediverse must not be shown the same page.

const DEFAULT_SOCK = '/.config/ap-bridge/svc.sock'

export function createApInbox ({ sockPath = null, connect = null, home = null, exists = null } = {}) {
  const path = sockPath || ((home || '') + DEFAULT_SOCK)

  return {
    get path () { return path },

    // Is there an ap-bridge on this machine at all? Checked before connecting so the common case
    // (no AP side here) costs nothing and logs nothing.
    available () {
      if (!exists) return true // no probe injected: let the connect attempt decide
      try { return !!exists(path) } catch { return false }
    },

    /**
     * @returns {Promise<Array|null>} items, or null when we could not ask.
     */
    async list ({ limit = 50 } = {}) {
      if (!this.available()) return null
      if (typeof connect !== 'function') return null
      let client = null
      try {
        client = await connect(path)
        const res = await client.call('notifications', { limit })
        const items = res && res.items
        return Array.isArray(items) ? items : null
      } catch {
        // Unreachable, wrong version (no `notifications` verb), or mid-restart. All the same answer:
        // we could not ask. Never throw — the notifications page must render its atproto half
        // regardless of whether the AP side is up.
        return null
      } finally {
        try { await client?.close?.() } catch {}
      }
    }
  }
}
// favela appview index — folds atproto posts into a LOCAL Hyperbee for query (timeline, author feed).
//
// FAVELA-LOCAL by design (§7.5): every peer derives its OWN view from the replicated firehoses; this
// index is a rebuildable CACHE, never replicated. Bare-native (hypercore/hyperbee, no shims).
//
// This is a per-peer atproto FEED GENERATOR: the "firehose" is each DID's FirehoseSequencer, the index
// is this Hyperbee, and getTimeline is the (locally-hydrated) getFeedSkeleton. It ingests two ways:
//   - indexPeer(peer): a SNAPSHOT reconcile from the current repo (listRecords). Catches adopted/
//     historical records that were imported in bulk (not as per-record firehose commits), and REMOVES
//     entries whose record is no longer present (delete-correctness for the baseline).
//   - applyCommit(did, body): INCREMENTAL per-commit ingest from a #commit frame — create/update ->
//     putPost (record read from the frame's own CAR, race-free), delete -> delPost. This is the live tail.
//
// Keys — ISO createdAt sorts lexicographically = chronologically; reverse:true = newest first:
//   timeline sub:  `${createdAt}\x00${did}\x00${rkey}` -> { did, rkey, record, createdAt }
//   author sub:    `${did}\x00${createdAt}\x00${rkey}` -> { did, rkey, record, createdAt }
//   ref sub:       `${did}\x00${rkey}`                 -> { createdAt }   (reverse lookup: lets delPost
//     reconstruct the createdAt-bearing timeline/author keys, and lets an UPDATE that moved createdAt
//     clear its stale keys — a delete op carries no record, so the createdAt must be remembered.)
import Hyperbee from 'hyperbee'
import { displayHandle } from './handles.js'
import crypto from 'hypercore-crypto'
import b4a from 'b4a'
import { POST_COLLECTIONS } from './scopes.js'
import { isIgnoredCollection } from './hosted-dids.js'
import { parseQuery, matches, score, postText, actorText } from './search.js'
import * as dagCbor from '@ipld/dag-cbor'

// Byte length our copy WOULD serialize to — used only to report a divergence from the canonical bytes,
// never to decide a write. Returns -1 if the record cannot be encoded, so the comparison simply reads as
// "differs" rather than throwing inside the ingest path.
function recEncodedLength (record) {
  try { return dagCbor.encode(record).length } catch { return -1 }
}

function deepEq (a, b) {
  if (a === b) return true
  if (a == null || b == null || typeof a !== typeof b) return false
  if (typeof a !== 'object') return false
  if (Array.isArray(a) !== Array.isArray(b)) return false
  if (Array.isArray(a)) return a.length === b.length && a.every((x, i) => deepEq(x, b[i]))
  const ka = Object.keys(a); const kb = Object.keys(b)
  return ka.length === kb.length && ka.every((k) => deepEq(a[k], b[k]))
}

// Is `ours` a strictly LOSSY version of `theirs` — every field we have, they have identically, and they
// carry at least one field we dropped? That is the exact shape of the 2026-07-30 outage: hpp's record
// carried `langs: ['en']`, ours was identical without it, and re-encoding ours over the canonical file
// invalidated the committed pointer.
//
// This is deliberately NARROW. A genuine EDIT changes a value, so it is not a subset and still writes —
// which matters, because for a peer whose records no local hpp holds we are the only writer, and an
// edited profile that never updates its bytes is its own bug (caught by appview-ingest/-dedup).
export function isLossySubset (ours, theirs) {
  if (!ours || !theirs || typeof ours !== 'object' || typeof theirs !== 'object') return false
  const ko = Object.keys(ours); const kt = Object.keys(theirs)
  if (kt.length <= ko.length) return false
  return ko.every((k) => k in theirs && deepEq(ours[k], theirs[k]))
}

// The atproto profile record. One per repo, rkey always 'self'.
// What this build knows how to index. BUMP THIS when the ingest filter widens, and every DID gets ONE
// firehose replay from seq 0 to pick up what the previous build discarded.
//
// This exists because the fast path is self-fulfilling. bin/favela-web.js decides `coHosted` by asking
// whether the local shared store already holds records for a DID — but favela's OWN putPost writes
// ingested records into that store, so the first ingest makes it non-empty and the DID is treated as
// co-hosted forever after, tailing from the current end and never replaying history. e2jev backfilled
// from 0 exactly once, while applyCommit still dropped profiles, and could never do it again: its
// profile commit sat in firehose history that nothing would re-read, and its profile record was absent
// from the local store, so the store-based baseline had nothing to fold either. A dead end reachable
// only by widening the filter, which is precisely when it matters.
//
//   1: post collections only
//   2: + app.bsky.actor.profile
//   3: + app.bsky.feed.like, app.bsky.graph.follow
//   4: + reply threading (post records' reply.parent indexed)
//   5: + app.bsky.feed.repost
//   6: + app.bsky.graph.block — a block is a PUBLIC record and federates, so a block made on ANOTHER
//      device (or by a peer) must be visible here. Until this it was tracked only in node-local
//      bookkeeping, so a block made elsewhere simply did not exist for this node.
export const INGEST_VERSION = 6

const PROFILE_COLLECTION = 'app.bsky.actor.profile'
const PROFILE_RKEY = 'self'
const LIKE_COLLECTION = 'app.bsky.feed.like'
const FOLLOW_COLLECTION = 'app.bsky.graph.follow'
const REPOST_COLLECTION = 'app.bsky.feed.repost'
const BLOCK_COLLECTION = 'app.bsky.graph.block'
const PROF_TTL_MS = 30 * 1000

const SEP = '\x00'

// The author-feed filters, verbatim from app.bsky.feed.getAuthorFeed's knownValues (verified against the
// lexicon 2026-07-30). Kept as the bsky set rather than a favela-specific one so the profile tabs mean
// the same thing they do elsewhere in atproto, and so a lens import can pass the value straight through.
export const AUTHOR_FILTERS = new Set([
  'posts_with_replies',      // default — everything
  'posts_no_replies',        // top-level only
  'posts_with_media',        // images or video
  'posts_and_author_threads',// top-level, plus replies to the author's OWN posts (self-threads)
  'posts_with_video'
])

// Which media an embed carries. Mirrors render.js's embedImages for the two shapes we actually write
// (app.bsky.embed.images, and the .media side of recordWithMedia), plus video for the video filter.
function embedMedia (record) {
  const e = record && record.embed
  if (!e) return { images: false, video: false }
  const m = (e.$type === 'app.bsky.embed.recordWithMedia' && e.media) ? e.media : e
  return {
    images: !!(m && m.$type === 'app.bsky.embed.images' && Array.isArray(m.images) && m.images.length),
    video: !!(m && m.$type === 'app.bsky.embed.video')
  }
}

// Every real post in a thread, flat, in render order. Moderation (withMod) works on a `.posts` array and
// mutates each entry in place, so flattening for it leaves the TREE carrying the moderated objects —
// labels/mutes apply to a reply nested four levels down exactly as they do on the timeline. `missing`
// ancestor markers are not posts and are skipped.
export function threadPostList (thread) {
  if (!thread || !thread.post) return []
  const out = [thread.post]
  for (const a of thread.ancestors || []) if (a && !a.missing) out.push(a)
  const walk = (nodes) => { for (const n of nodes || []) { if (n && n.post) { out.push(n.post); walk(n.replies) } } }
  walk(thread.replies)
  return out
}
const FLOOR = '0000-01-01T00:00:00.000Z' // sorts before any real ISO createdAt

// Normalize an author scope (Set | array | null) to a Set of DIDs, or null (= no filter / global view).
// An empty scope stays null rather than "match nothing": a signed-in viewer with zero known communities
// falls back to the global timeline instead of an empty page.
function normAuthors (authors) {
  if (!authors) return null
  const set = authors instanceof Set ? authors : new Set(authors)
  return set.size ? set : null
}

// Extract hashtags/topics from a post: the structured self-`tags` array + richtext #tag facets + the
// #hashtags users type in text. Normalized (lowercase, de-#, deduped). This is the topic-feed index —
// the atproto feed-generator "filter" (DESIGN §5 native local search) applied locally per-peer.
const TAG_RE = /(?:^|\s)#([\p{L}\p{N}_]+)/gu
function normTag (t) { const s = String(t || '').replace(/^#/, '').trim().toLowerCase(); return s || null }
export function extractTags (record) {
  if (!record) return []
  const out = new Set()
  if (Array.isArray(record.tags)) for (const t of record.tags) { const n = normTag(t); if (n) out.add(n) }
  if (Array.isArray(record.facets)) {
    for (const f of record.facets) {
      for (const feat of (f && Array.isArray(f.features) ? f.features : [])) {
        if (feat && feat.$type === 'app.bsky.richtext.facet#tag' && feat.tag) { const n = normTag(feat.tag); if (n) out.add(n) }
      }
    }
  }
  const text = typeof record.text === 'string' ? record.text : ''
  for (const m of text.matchAll(TAG_RE)) { const n = normTag(m[1]); if (n) out.add(n) }
  return [...out]
}

// Deterministic content signature of a record. indexPeer re-folds the FULL repo on every baseline/#sync,
// and Hyperbee sub-bees do NOT honor alwaysDuplicate:false (a re-put ALWAYS appends — verified), so putPost
// must skip the write entirely when the record is unchanged (sig match). That gate is what stops the index
// ballooning: without it, every reconnect re-appends every record's timeline/author/tags/ref entries.
function recSig (record) { return b4a.toString(crypto.data(b4a.from(JSON.stringify(record || null))), 'hex') }
function sameTags (a, b) {
  const x = Array.isArray(a) ? a : []
  const y = Array.isArray(b) ? b : []
  if (x.length !== y.length) return false
  for (let i = 0; i < x.length; i++) if (x[i] !== y[i]) return false
  return true
}

export class Appview {
  // corestore: a Corestore (favela's own copy — the index touches NO atproto-store cores, so there is
  // no cross-copy instanceof gotcha here). name: the index core's namespace.
  constructor (corestore, { name = 'favela-appview', getRecordStore = null, handleResolver = null, isForeign = () => true } = {}) {
    // Optional: resolves + bidirectionally VERIFIES a DID's handle for bylines (see _hydrate).
    this._handles = handleResolver
    // Is this DID one a local hpp owns (roster) or a foreign peer's? Gates whether we may CREATE record
    // bytes — see the guard in putPost. Defaults to "everything is foreign", which is the pre-existing
    // behaviour: a caller that does not know its roster keeps writing exactly as before.
    this._isForeign = typeof isForeign === 'function' ? isForeign : () => true
    this.bee = new Hyperbee(corestore.get({ name }), { keyEncoding: 'utf-8', valueEncoding: 'json' })
    this._timeline = this.bee.sub('timeline')
    this._author = this.bee.sub('author')
    this._tags = this.bee.sub('tags')
    this._ref = this.bee.sub('ref')
    // Profiles are indexed like posts because that is how atproto works: an AppView consumes the
    // firehose and indexes app.bsky.actor.profile alongside app.bsky.feed.post, then serves feeds with
    // the author ALREADY HYDRATED (app.bsky.feed.defs#postView carries a #profileViewBasic). Clients
    // never resolve authors themselves. Before this, profile commits arrived on the firehose and were
    // dropped by the POST_COLLECTIONS filter in applyCommit, so every node could render its OWN profile
    // and nobody else's — remote authors showed as a raw DID forever.
    this._profiles = this.bee.sub('profiles')
    // blocks: `<did>\x00<subject>` -> {…}; blockRkey: `<did>\x00<rkey>` -> {subject}, so a delete op
    // (which carries no record) can find what it removed — the same pair follows uses.
    this._blocks = this.bee.sub('blocks')
    this._blockRkey = this.bee.sub('blockrkey')
    // Per-DID bookkeeping: which INGEST_VERSION this DID's history has been folded at.
    this._meta = this.bee.sub('meta')
    // ---- the ingest-time collection ledger (spec/convergence.md §2, org #33) --------------------------
    //
    // applyCommit used to end with a bare `continue` for every collection it had no branch for, so a NEW
    // LEXICON appearing in a repo we follow vanished without a word. That is the same silence, in a fourth
    // costume, that let a node sit broken for five days under four green checks: the code was working
    // exactly as written, and what it discarded was never anybody's to see.
    //
    //   `<collection>` -> { collection, class: 'unknown'|'ignored', count, firstSeen, lastSeen, dids[], sample }
    //
    // Keyed by COLLECTION, not by record, so the ledger grows with distinct lexicons (two today) and never
    // with traffic — a repo pushing a million unknown records adds one key.
    //
    // PERSISTED, not in-memory, because the question outlives the process: an operator who restarts must
    // not thereby lose the fact that something unclassified has been arriving. Deletion story: this is part
    // of the appview index, which is a rebuildable local CACHE (see the header) — a rebuild re-derives the
    // ledger from re-ingest, and nothing here is replicated or authoritative for anyone else.
    this._collections = this.bee.sub('collections')
    // Log an unknown collection ONCE per process. Without this a repo carrying a lexicon we do not know
    // emits one warning per op forever, and a log that floods is read by nobody — which would reproduce
    // the very failure this closes.
    this._loggedUnknown = new Set()
    // Social graph. Both are keyed so that the natural read is a RANGE SCAN and every write is
    // idempotent — the same (liker, rkey) or (follower, subject) always lands on the same key.
    //
    // Deliberately NOT stored as counters. A counter is an increment, and increments are not idempotent
    // under replay: the INGEST_VERSION backfill re-reads a peer's whole firehose, so every like would be
    // counted again on every version bump. Counting keys in a range is O(n) per post instead of O(1), but
    // it is CORRECT under replay, which a counter is not without a separate dedup ledger.
    this._likes = this.bee.sub('likes')       // <subjectUri>\x00<likerDid>\x00<rkey> -> { did, rkey, subject }
    this._reposts = this.bee.sub('reposts')     // <subjectUri>\x00<did>\x00<rkey> -> { did, rkey, subject }
    this._repostedBy = this.bee.sub('repostedby') // <did>\x00<rkey> -> subjectUri (deletes carry only rkey)
    this._likedBy = this.bee.sub('likedby')   // <likerDid>\x00<rkey> -> subjectUri (for deletes, which carry only rkey)
    this._follows = this.bee.sub('follows')   // <followerDid>\x00<subjectDid> -> { did, subject, createdAt }
    this._followers = this.bee.sub('followers') // <subjectDid>\x00<followerDid> -> same (reverse index)
    this._followRkey = this.bee.sub('followrk')
    // Reply threading. A reply is an ordinary post whose record carries reply: { root, parent } as
    // strongRefs, so there is no new COLLECTION to ingest — only an extra index off the parent uri.
    // Keyed parent-first + createdAt so a thread reads as one forward-chron range scan.
    this._replies = this.bee.sub('replies')   // <parentUri>\x00<createdAt>\x00<did>\x00<rkey> -> pointer
    this._replyOf = this.bee.sub('replyof')   // <did>\x00<rkey> -> parentUri (deletes carry only rkey) // <followerDid>\x00<rkey> -> subjectDid (deletes carry only rkey)
    // A timeline is a handful of distinct authors repeated many times, and _hydrate runs per post.
    // Memoized briefly so a 50-post page is a few reads, not fifty.
    this._profCache = new Map()
    // getRecordStore(did) -> OverlayRepoStore: the SHARED content-addressed record byte store, ONE physical
    // copy per machine at ATPROTO_OVERLAY_ROOT/<roomKey16> — the SAME files hpp writes (identical layout +
    // byte-exact DAG-CBOR). The index below holds only POINTERS { did, collection, rkey, createdAt }; the
    // record BYTES live once in that store, never duplicated into this Hyperbee. Null => records unresolved.
    this._getRecordStore = getRecordStore
  }

  async ready () { await this.bee.ready(); return this }

  // Resolve a record's bytes from the shared store by (did, collection, rkey). null if no store / absent.
  async _resolveRecord (did, collection, rkey) {
    if (!this._getRecordStore) return null
    try { const s = await this._getRecordStore(did); return s ? await s.get(collection, rkey) : null } catch { return null }
  }

  // The post an embed.record / embed.recordWithMedia points at, as { did, rkey, record, author } — or null
  // when we do not hold it (a quote of a post outside this node's window is normal, and saying nothing is
  // better than rendering an empty box). Never recurses: the returned view carries no `quoted` of its own.
  async _resolveQuoted (record) {
    const e = record && record.embed
    if (!e) return null
    const ref = e.$type === 'app.bsky.embed.record'
      ? e.record
      : (e.$type === 'app.bsky.embed.recordWithMedia' && e.record ? (e.record.record || e.record) : null)
    const uri = ref && typeof ref.uri === 'string' ? ref.uri : null
    if (!uri) return null
    const parts = uri.replace(/^at:\/\//, '').split('/')
    if (parts.length !== 3 || !parts[0].startsWith('did:')) return null
    const [did, collection, rkey] = parts
    const rec = await this._resolveRecord(did, collection, rkey)
    if (!rec) return null
    const prof = await this.getProfile(did)
    const h = this._handles ? await this._handles.resolve(did) : null
    return {
      did,
      rkey,
      record: rec,
      author: {
        did,
        displayName: (prof && prof.displayName) || null,
        avatar: (prof && prof.avatar) || null,
        handle: displayHandle(h),
        handleVerified: !!(h && h.verified)
      }
    }
  }

  // SEARCH — a scan over the existing subs, not an inverted index. See lib/search.js for why that is an
  // honest trade at this corpus size and what to do when it stops being one. `scanCap` bounds the work so
  // a query can never walk an unbounded index: it is a COST ceiling, and hitting it is reported
  // (`truncated`) rather than silently returning a short list that looks complete.
  async searchPosts (q, { limit = 25, viewerDid = null, scanCap = 5000 } = {}) {
    const query = parseQuery(q)
    if (!query.terms.length && !query.phrases.length) return { posts: [], cursor: null, truncated: false }
    const hits = []
    let scanned = 0
    // Newest first, so an early exit keeps the most recent matches rather than an arbitrary slice.
    for await (const e of this._timeline.createReadStream({ reverse: true })) {
      if (++scanned > scanCap) break
      const v = e && e.value
      if (!v) continue
      const rec = await this._resolveRecord(v.did, v.collection || 'app.bsky.feed.post', v.rkey)
      if (!rec) continue
      const text = postText(rec)
      if (!matches(text, query)) continue
      hits.push({ v, s: score(text, query) })
      if (hits.length >= limit * 4) break // enough to rank meaningfully without scanning to the end
    }
    hits.sort((a, b) => b.s - a.s)
    const posts = []
    for (const h of hits.slice(0, limit)) {
      const p = await this._hydrate(h.v, viewerDid)
      if (p) posts.push(p)
    }
    return { posts, cursor: null, truncated: scanned > scanCap }
  }

  // People this node knows about, by display name, handle, DID or bio.
  async searchActors (q, { limit = 10 } = {}) {
    const query = parseQuery(q)
    if (!query.terms.length && !query.phrases.length) return []
    const hits = []
    try {
      for await (const e of this._profiles.createReadStream()) {
        const did = String(e.key)
        const prof = e.value || {}
        const text = actorText(did, prof)
        if (!matches(text, query)) continue
        hits.push({ did, profile: prof, s: score(text, query) })
      }
    } catch { /* an unreadable profile sub must not fail the whole search */ }
    hits.sort((a, b) => b.s - a.s)
    return hits.slice(0, limit)
  }

  // Hydrate a pointer { did, collection, rkey, createdAt } into { did, rkey, record, createdAt } for reads.
  async _hydrate (v, viewerDid = null) {
    const record = await this._resolveRecord(v.did, v.collection || 'app.bsky.feed.post', v.rkey)
    // Author rides the view, atproto-style — the render layer does no lookups of its own.
    const prof = await this.getProfile(v.did)
    // The HANDLE is not in the profile record — atproto keeps it in the DID document (alsoKnownAs), so
    // it needs resolution, and resolution alone is not enough: alsoKnownAs is a CLAIM by the DID. The
    // resolver verifies it bidirectionally and yields 'handle.invalid' when it does not check out, so an
    // impostor DID claiming someone else's handle can never render as that person. Optional: with no
    // resolver wired the byline falls back to a short DID rather than inventing a name.
    const h = this._handles ? await this._handles.resolve(v.did) : null
    const author = {
      did: v.did,
      displayName: (prof && prof.displayName) || null,
      avatar: (prof && prof.avatar) || null,
      handle: displayHandle(h),
      handleVerified: !!(h && h.verified)
    }
    const uri = `at://${v.did}/${v.collection || 'app.bsky.feed.post'}/${v.rkey}`
    const likeCount = await this.likeCount(uri)
    // Viewer state rides the view, as it does in atproto (postView carries a #viewerState). The render
    // layer must not have to ask "did I like this" per post.
    const viewerLiked = viewerDid ? await this.hasLiked(viewerDid, uri) : false
    const replyCount = await this.replyCount(uri)
    const repostCount = await this.repostCount(uri)
    const viewerReposted = viewerDid ? await this.hasReposted(viewerDid, uri) : false
    // A QUOTE POST embeds a strongRef, not the quoted content. Until this, embed.record was rendered as
    // NOTHING — a quote showed the commentary with the post it was about invisible, which reads as a
    // non-sequitur. Resolved here for the same reason `author` is: the render layer does no lookups.
    // One level only, deliberately — a quote of a quote of a quote would recurse a timeline into a tree.
    const quoted = await this._resolveQuoted(record)
    return { did: v.did, rkey: v.rkey, record, createdAt: v.createdAt, editedAt: v.editedAt || null, author, likeCount, replyCount, repostCount, uri, viewerLiked, viewerReposted, quoted }
  }

  _tlKey (createdAt, did, rkey) { return `${createdAt}${SEP}${did}${SEP}${rkey}` }
  _auKey (did, createdAt, rkey) { return `${did}${SEP}${createdAt}${SEP}${rkey}` }
  _tagKey (tag, createdAt, did, rkey) { return `${tag}${SEP}${createdAt}${SEP}${did}${SEP}${rkey}` }
  _refKey (did, rkey) { return `${did}${SEP}${rkey}` }

  // Every TRACKED collection, and whether this node stores its BYTES.
  //
  // ⛔ The bytes flag is not cosmetic. putLike/putRepost/putFollow/putBlock index a record without ever
  // writing it to the record store — only posts and the profile get bytes. A convergence check that
  // asked "do we have the bytes?" for a like would report a gap on every like this node has ever
  // indexed, which is worse than the blind spot it replaced. See spec/convergence.md §2.
  static get TRACKED () {
    const m = new Map()
    for (const c of POST_COLLECTIONS) m.set(c, { bytes: true, view: 'post' })
    m.set(PROFILE_COLLECTION, { bytes: true, view: 'profile' })
    m.set(LIKE_COLLECTION, { bytes: false, view: 'like' })
    m.set(REPOST_COLLECTION, { bytes: false, view: 'repost' })
    m.set(FOLLOW_COLLECTION, { bytes: false, view: 'follow' })
    m.set(BLOCK_COLLECTION, { bytes: false, view: 'block' })
    return m
  }

  // Refs this node has indexed for ONE collection, from the view that actually owns it.
  //
  // Each of the five non-post views keeps a `<did><SEP><rkey>` reverse index precisely so a record can be
  // located by its rkey (it is what del*() uses); walking that prefix is the same question convergence
  // asks. The profile is a single record per DID, keyed by did alone, so its rkey is always 'self'.
  async * indexedRefsFor (did, collection) {
    const meta = Appview.TRACKED.get(collection)
    if (!meta) return
    if (meta.view === 'post') {
      for await (const ref of this.indexedRefs(did)) if (ref.collection === collection) yield ref
      return
    }
    if (meta.view === 'profile') {
      const p = await this._profiles.get(did)
      if (p && p.value) yield { did, rkey: PROFILE_RKEY, collection }
      return
    }
    const bee = { like: this._likedBy, repost: this._repostedBy, follow: this._followRkey, block: this._blockRkey }[meta.view]
    if (!bee) return
    const lo = `${did}${SEP}`
    const hi = `${did}\x01`
    for await (const { key } of bee.createReadStream({ gte: lo, lt: hi })) {
      const i = key.indexOf(SEP)
      if (i < 0) continue
      yield { did, rkey: key.slice(i + 1), collection }
    }
  }

  // Every record this node has INDEXED for a DID, as { did, rkey, collection, createdAt }.
  //
  // Exposed because "indexed" and "has bytes" are separate states here — the create-gate above may
  // refuse byte authorship while still indexing — and lib/repair-bytes.js needs to walk the first set to
  // find the gap in the second. Reaching into `_ref` from a caller would couple it to the key encoding.
  async * indexedRefs (did) {
    const lo = `${did}${SEP}`
    const hi = `${did}\x01`
    for await (const { key, value } of this._ref.createReadStream({ gte: lo, lt: hi })) {
      const i = key.indexOf(SEP)
      if (i < 0) continue
      yield {
        did,
        rkey: key.slice(i + 1),
        collection: (value && value.collection) || null,
        createdAt: (value && value.createdAt) || null
      }
    }
  }

  // Index one post into both views. Idempotent by (did, rkey). If a prior index of the SAME (did, rkey)
  // used a different createdAt (an edit that moved the timestamp), its stale timeline/author keys are
  // removed first — otherwise the reverse-chron key would orphan.
  // `edited` is set ONLY by applyCommit, from the firehose op's action. It is deliberately NOT
  // inferred from "a prior entry exists": indexPeer re-puts every record on a snapshot reconcile, so
  // inferring would mark the whole repo edited on any re-index. An edit is a claim about history and
  // must come from the log that records history.
  //
  // Stored in the index (derived, rebuildable) rather than in the record — spec §10.5.2: atproto's
  // $orig/$hist pattern exists because atproto has no history, and this substrate has some.
  async putPost ({ did, collection = 'app.bsky.feed.post', rkey, record, edited = false }) {
    const createdAt = (record && record.createdAt) || FLOOR
    const tags = extractTags(record)
    const refKey = this._refKey(did, rkey)
    const prior = await this._ref.get(refKey)
    const priorVal = prior && prior.value
    // DEDUP GATE (the balloon fix): if this exact record is already indexed, skip the whole write. A blind
    // re-put would append dead blocks — Hyperbee subs don't dedup — and indexPeer re-folds the full repo on
    // every baseline/#sync, so an ungated re-index balloons the log on every reconnect.
    const sig = recSig(record)
    if (priorVal && priorVal.sig === sig) return
    // Record BYTES go to the SHARED content-addressed store (one copy per machine). The index holds only a
    // POINTER, never the record.
    //
    // NEVER LET A LOSSY COPY CLOBBER A RICHER ONE. This used to call put() unconditionally, on the
    // assumption that our re-encode is "byte-identical to hpp's, so writing an already-present record is
    // idempotent". It is not, and on 2026-07-30 that assumption froze wj62's repo for ~42h:
    //
    //   hpp wrote the record WITH langs (390 bytes) and published a pointer to that hash
    //   -> we re-encoded our decoded copy WITHOUT langs (380 bytes) over the same file
    //   -> the converged pointer now referenced bytes that existed on NO node
    //   -> the signer could not resolve them, so the head never advanced again, and two posts
    //      ("we workin", "moar torren") were never published anywhere.
    //
    // These files are shared with hpp (ATPROTO_OVERLAY_ROOT is its record dir) and hpp is the AUTHORITY:
    // its PointerSubstrate hashes the bytes it writes and commits that hash to the autobase. We write no
    // pointer, so we must never invalidate one — but we DO remain the only writer for a peer whose records
    // no local hpp holds, so a blanket "never overwrite" would freeze every ingested profile at its
    // first-seen version. Refusing only a LOSSY overwrite threads both.
    if (this._getRecordStore) {
      try {
        const s = await this._getRecordStore(did)
        if (s) {
          // getRaw returns { bytes, record } (or null) — NOT a buffer.
          const existing = await s.getRaw(collection, rkey)
          // ⛔ THE HOLE THE LOSSY GUARD BELOW COULD NOT SEE. isLossySubset can only compare against a file
          // that is ALREADY on this disk. When the file is absent it had nothing to compare, so it wrote
          // unconditionally — and "absent" is exactly the state hpp is in between publishing a pointer and
          // this node materialising the bytes. Our re-encode then lands first, hashes differently from the
          // pointer hpp already committed, and the signer can never resolve it: the head stops advancing and
          // NOTHING federates. That is the 2026-07-31 recurrence (392-byte pointer, 382-byte file, `langs`
          // dropped) — the same defect as 2026-07-30, through the one branch the fix did not cover.
          //
          // For a DID on our ROSTER, hpp is the AUTHORITY for these bytes and the only writer that may
          // create them. Absence means "not here YET", never "ours to author". For a foreign peer no local
          // hpp holds, we remain the only writer, so the original behaviour is preserved — which is what
          // keeps ingested profiles from freezing at their first-seen version.
          if (existing == null && !this._isForeign(did)) {
            console.error(JSON.stringify({
              msg: 'appview: refusing to CREATE bytes for a roster DID — hpp owns these and may already have published a pointer',
              did,
              collection,
              rkey,
              ourBytes: recEncodedLength(record)
            }))
          } else if (existing == null) await s.put(collection, rkey, record)
          else if (!isLossySubset(record, existing.record)) await s.put(collection, rkey, record)
          else {
            // Divergence is now LOUD. Silence here is what let a clobbered record sit undetected for two
            // days while every surface reported health. We keep the canonical bytes and say so, naming the
            // dropped fields — that is what identifies the write path that lost them.
            console.error(JSON.stringify({
              msg: 'appview: our copy is LOSSY vs canonical bytes — refusing to overwrite',
              did,
              collection,
              rkey,
              canonicalBytes: existing.bytes.length,
              ourBytes: recEncodedLength(record),
              droppedFields: Object.keys(existing.record).filter((k) => !(k in record))
            }))
          }
        }
      } catch {}
    }
    // The record changed (or is new). Clear the OLD keys only when createdAt or the tag set MOVED — those
    // define the key layout; if unchanged, the puts below overwrite in place (a text-only edit). Skipping
    // the del avoids a tombstone append (del always appends, regardless of alwaysDuplicate).
    if (priorVal && (priorVal.createdAt !== createdAt || !sameTags(priorVal.tags, tags))) await this._removeEntries(did, rkey, priorVal)
    // Once edited, ALWAYS edited: a later unrelated re-put (re-index, snapshot reconcile) must not
    // erase the fact. First edit wins the timestamp — it is "this has been edited", not "last edited".
    const editedAt = (priorVal && priorVal.editedAt) || (edited ? new Date().toISOString() : null)
    const val = { did, collection, rkey, createdAt } // POINTER only — record bytes live in the shared store
    if (editedAt) val.editedAt = editedAt
    await this._timeline.put(this._tlKey(createdAt, did, rkey), val)
    await this._author.put(this._auKey(did, createdAt, rkey), val)
    for (const tag of tags) await this._tags.put(this._tagKey(tag, createdAt, did, rkey), val)
    // Thread edge, when this post is a reply. parent.uri is what a thread hangs off; root is not indexed
    // because a thread view walks DOWN from a post, and bsky's own getPostThread does the same.
    const parentUri = record && record.reply && record.reply.parent && record.reply.parent.uri
    if (typeof parentUri === 'string' && parentUri.startsWith('at://')) {
      await this._replies.put(`${parentUri}${SEP}${createdAt}${SEP}${did}${SEP}${rkey}`, val)
      await this._replyOf.put(refKey, { parentUri, createdAt })
    }
    await this._ref.put(refKey, { createdAt, tags, sig, collection })
  }

  // Remove every index entry for a (did, rkey) given its stored ref { createdAt, tags }.
  async _removeEntries (did, rkey, ref) {
    const createdAt = ref.createdAt || FLOOR
    await this._timeline.del(this._tlKey(createdAt, did, rkey))
    await this._author.del(this._auKey(did, createdAt, rkey))
    // Drop the thread edge too, or a deleted reply leaves a phantom in its parent's thread.
    try {
      const r = await this._replyOf.get(this._refKey(did, rkey))
      if (r && r.value && r.value.parentUri) {
        await this._replies.del(`${r.value.parentUri}${SEP}${r.value.createdAt || createdAt}${SEP}${did}${SEP}${rkey}`)
        await this._replyOf.del(this._refKey(did, rkey))
      }
    } catch {}
    for (const tag of (Array.isArray(ref.tags) ? ref.tags : [])) await this._tags.del(this._tagKey(tag, createdAt, did, rkey))
  }

  // Remove a post from all views (timeline/author/tags). No-op if not indexed.
  async delPost ({ did, rkey }) {
    const refKey = this._refKey(did, rkey)
    const prior = await this._ref.get(refKey)
    if (!prior || !prior.value) return false
    const ref = prior.value
    if (this._getRecordStore && ref.collection) { try { const s = await this._getRecordStore(did); if (s) await s.del(ref.collection, rkey) } catch {} }
    await this._removeEntries(did, rkey, ref)
    await this._ref.del(refKey)
    return true
  }

  // Index a peer's profile record. Same two-layer shape as putPost: the record BYTES go to the shared
  // content-addressed overlay store (one physical copy per machine, byte-identical to hpp's, so this is
  // also how a remote profile ends up REPLICATED into hyper-overlay rather than living only on its home
  // node) and the index keeps a small projection for hydration. Dedup-gated by content signature for the
  // same reason putPost is: Hyperbee subs do not dedup, and a re-fold on every reconnect would balloon.
  //
  // `avatar` is stored as the RAW blob ref, not a cid string — normalizing it is the render layer's job
  // (it owns blobCid and the four shapes a ref arrives in), and the appview should not grow a second
  // copy of that knowledge.
  async putProfile ({ did, record }) {
    if (!did || !record) return false
    const sig = recSig(record)
    const prior = await this._profiles.get(did)
    if (prior && prior.value && prior.value.sig === sig) return false
    if (this._getRecordStore) { try { const s = await this._getRecordStore(did); if (s) await s.put(PROFILE_COLLECTION, PROFILE_RKEY, record) } catch {} }
    await this._profiles.put(did, {
      did,
      displayName: typeof record.displayName === 'string' ? record.displayName : null,
      description: typeof record.description === 'string' ? record.description : null,
      avatar: record.avatar || null,
      sig
    })
    this._profCache.delete(did)
    return true
  }

  async delProfile (did) {
    const prior = await this._profiles.get(did)
    if (!prior || !prior.value) return false
    if (this._getRecordStore) { try { const s = await this._getRecordStore(did); if (s) await s.del(PROFILE_COLLECTION, PROFILE_RKEY) } catch {} }
    await this._profiles.del(did)
    this._profCache.delete(did)
    return true
  }

  // The projected profile for a DID, or null. Memoized briefly (see _profCache).
  async getProfile (did) {
    if (!did) return null
    const now = Date.now()
    const hit = this._profCache.get(did)
    if (hit && now - hit.at < PROF_TTL_MS) return hit.value
    let value = null
    try { const r = await this._profiles.get(did); value = (r && r.value) || null } catch { value = null }
    if (this._profCache.size > 500) this._profCache.clear()
    this._profCache.set(did, { at: now, value })
    return value
  }

  // Replies to a post, forward-chron (a conversation reads oldest-first, unlike a timeline).
  async getReplies (uri, { limit = 50, viewerDid = null } = {}) {
    const out = []
    if (!uri) return out
    try {
      for await (const { value } of this._replies.createReadStream({ gte: `${uri}${SEP}`, lt: `${uri}\x01`, limit })) {
        if (value) out.push(await this._hydrate(value, viewerDid))
      }
    } catch {}
    return out
  }

  // Parse an at:// post URI into its parts. Returns null for anything that is not one, so a malformed
  // permalink is a 404 rather than a throw.
  _parseUri (uri) {
    if (typeof uri !== 'string' || !uri.startsWith('at://')) return null
    const rest = uri.slice('at://'.length)
    const i = rest.indexOf('/')
    if (i < 0) return null
    const did = rest.slice(0, i)
    const tail = rest.slice(i + 1)
    const j = tail.lastIndexOf('/')
    if (j < 0) return null
    const collection = tail.slice(0, j)
    const rkey = tail.slice(j + 1)
    if (!did || !collection || !rkey) return null
    return { did, collection, rkey }
  }

  // POINT lookup of one post. The permalink route used to find a post by scanning the author's last 100
  // and matching rkey, so ANY older post 404'd on its own permalink. `_ref` already maps
  // (did, rkey) -> { createdAt, collection }, which is the same answer in one get and has no horizon.
  async getPost (uri, { viewerDid = null } = {}) {
    const p = this._parseUri(uri)
    if (!p) return null
    const ref = await this._ref.get(this._refKey(p.did, p.rkey))
    if (!ref || !ref.value) return null
    return this._hydrate({ did: p.did, collection: ref.value.collection || p.collection, rkey: p.rkey, createdAt: ref.value.createdAt }, viewerDid)
  }

  // A thread in BOTH directions, mirroring app.bsky.feed.getPostThread and its two knobs: `depth` walks
  // DOWN (descendants), `parentHeight` walks UP (ancestors). Same defaults as the lexicon (6 / 80).
  //
  // NB the comment on the reply index used to say root is not indexed "because a thread view walks DOWN
  // from a post, and bsky's own getPostThread does the same". bsky walks BOTH — parentHeight is an
  // ancestor walk — so that premise was wrong. Ancestors are reachable anyway via `_replyOf` (child ->
  // parent) one hop at a time, which is what this does; indexing root would only buy an O(1) jump to the
  // top of a thread.
  //
  // An ancestor that is NOT in this node's window stops the walk and is reported as { missing, uri }
  // rather than dropped. "The rest of this thread is outside our firehose" is true and worth rendering,
  // and it is precisely the hole a lens import would later fill; truncating silently would instead look
  // like the thread simply started there.
  async getPostThread (uri, { depth = 6, parentHeight = 80, viewerDid = null, maxNodes = 200 } = {}) {
    const post = await this.getPost(uri, { viewerDid })
    if (!post) return null

    const ancestors = []
    const seen = new Set([uri])
    let cur = uri
    for (let i = 0; i < parentHeight; i++) {
      const p = this._parseUri(cur)
      if (!p) break
      const r = await this._replyOf.get(this._refKey(p.did, p.rkey))
      const parentUri = r && r.value && r.value.parentUri
      // `seen` guards a malformed cycle (a reply chain that points back into itself). Data we did not
      // author can be arbitrary, and a cycle here would hang the request forever.
      if (!parentUri || seen.has(parentUri)) break
      seen.add(parentUri)
      const parent = await this.getPost(parentUri, { viewerDid })
      if (!parent) { ancestors.unshift({ missing: true, uri: parentUri }); break }
      ancestors.unshift(parent)
      cur = parentUri
    }

    // Descendants. maxNodes bounds the TOTAL, not the per-level fan-out, so one very wide thread cannot
    // pin the event loop of a single-process SSR gateway.
    let nodes = 0
    const walk = async (parentUri, d) => {
      if (d >= depth || nodes >= maxNodes) return []
      const kids = await this.getReplies(parentUri, { viewerDid })
      const out = []
      for (const kid of kids) {
        if (nodes >= maxNodes) break
        nodes++
        out.push({ post: kid, replies: await walk(kid.uri, d + 1) })
      }
      return out
    }
    const replies = await walk(uri, 0)

    return { post, ancestors, replies, truncated: nodes >= maxNodes }
  }

  // Count only — the timeline wants a number, not the posts. Range scan, idempotent under replay for the
  // same reason likeCount is.
  async replyCount (uri) {
    if (!uri) return 0
    let n = 0
    try { for await (const _ of this._replies.createReadStream({ gte: `${uri}${SEP}`, lt: `${uri}\x01` })) n++ } catch { return 0 }
    return n
  }

  // ── social graph ────────────────────────────────────────────────────────────────────────────────
  // A like's subject is a strong ref { uri, cid }; the uri is the at:// of the liked post. A delete
  // commit carries only the rkey, so _likedBy maps (liker, rkey) -> subject to make removal possible.
  async putLike ({ did, rkey, record }) {
    const uri = record && record.subject && record.subject.uri
    if (!did || !rkey || typeof uri !== 'string' || !uri.startsWith('at://')) return false
    await this._likes.put(`${uri}${SEP}${did}${SEP}${rkey}`, { did, rkey, subject: uri, createdAt: (record && record.createdAt) || null })
    await this._likedBy.put(`${did}${SEP}${rkey}`, { subject: uri })
    return true
  }

  async delLike ({ did, rkey }) {
    const r = await this._likedBy.get(`${did}${SEP}${rkey}`)
    if (!r || !r.value || !r.value.subject) return false
    await this._likes.del(`${r.value.subject}${SEP}${did}${SEP}${rkey}`)
    await this._likedBy.del(`${did}${SEP}${rkey}`)
    return true
  }

  // How many distinct (liker, rkey) entries point at this post. Range scan — see the note on counters.
  async likeCount (uri) {
    if (!uri) return 0
    let n = 0
    try { for await (const _ of this._likes.createReadStream({ gte: `${uri}${SEP}`, lt: `${uri}\x01` })) n++ } catch { return 0 }
    return n
  }

  // The rkey of this DID's like of that post, or null. A toggle needs it: unliking is a DELETE of the
  // liker's OWN record, and only the liker's repo knows its rkey — it is not derivable from the subject.
  async likeRkey (did, uri) {
    if (!did || !uri) return null
    try {
      for await (const { value } of this._likes.createReadStream({ gte: `${uri}${SEP}${did}${SEP}`, lt: `${uri}${SEP}${did}\x01` })) {
        if (value && value.rkey) return value.rkey
      }
    } catch {}
    return null
  }

  // The rkey of this DID's follow of that subject, or null. Same reason as likeRkey.
  async followRkey (did, subject) {
    if (!did || !subject) return null
    try { const r = await this._follows.get(`${did}${SEP}${subject}`); return (r && r.value && r.value.rkey) || null } catch { return null }
  }

  // Did this DID like that post? Used to render the viewer's own like state.
  async hasLiked (did, uri) {
    if (!did || !uri) return false
    try {
      for await (const { value } of this._likes.createReadStream({ gte: `${uri}${SEP}${did}${SEP}`, lt: `${uri}${SEP}${did}\x01` })) { if (value) return true }
    } catch {}
    return false
  }

  // A repost's subject is the same strongRef shape a like uses, so this mirrors putLike exactly —
  // including storing keys rather than a counter, so a replay cannot inflate the count.
  async putRepost ({ did, rkey, record }) {
    const uri = record && record.subject && record.subject.uri
    if (!did || !rkey || typeof uri !== 'string' || !uri.startsWith('at://')) return false
    await this._reposts.put(`${uri}${SEP}${did}${SEP}${rkey}`, { did, rkey, subject: uri, createdAt: (record && record.createdAt) || null })
    await this._repostedBy.put(`${did}${SEP}${rkey}`, { subject: uri })
    return true
  }

  async delRepost ({ did, rkey }) {
    const r = await this._repostedBy.get(`${did}${SEP}${rkey}`)
    if (!r || !r.value || !r.value.subject) return false
    await this._reposts.del(`${r.value.subject}${SEP}${did}${SEP}${rkey}`)
    await this._repostedBy.del(`${did}${SEP}${rkey}`)
    return true
  }

  async repostCount (uri) {
    if (!uri) return 0
    let n = 0
    try { for await (const _ of this._reposts.createReadStream({ gte: `${uri}${SEP}`, lt: `${uri}\x01` })) n++ } catch { return 0 }
    return n
  }

  async hasReposted (did, uri) {
    if (!did || !uri) return false
    try { for await (const { value } of this._reposts.createReadStream({ gte: `${uri}${SEP}${did}${SEP}`, lt: `${uri}${SEP}${did}\x01` })) { if (value) return true } } catch {}
    return false
  }

  // Needed to UNrepost: the delete targets our own record, whose rkey only our repo knows.
  async repostRkey (did, uri) {
    if (!did || !uri) return null
    try {
      for await (const { value } of this._reposts.createReadStream({ gte: `${uri}${SEP}${did}${SEP}`, lt: `${uri}${SEP}${did}\x01` })) { if (value && value.rkey) return value.rkey }
    } catch {}
    return null
  }

  async putFollow ({ did, rkey, record }) {
    const subject = record && record.subject
    if (!did || !rkey || typeof subject !== 'string' || !subject.startsWith('did:')) return false
    const val = { did, subject, rkey, createdAt: (record && record.createdAt) || null }
    await this._follows.put(`${did}${SEP}${subject}`, val)
    await this._followers.put(`${subject}${SEP}${did}`, val)
    await this._followRkey.put(`${did}${SEP}${rkey}`, { subject })
    return true
  }

  async delFollow ({ did, rkey }) {
    const r = await this._followRkey.get(`${did}${SEP}${rkey}`)
    if (!r || !r.value || !r.value.subject) return false
    const subject = r.value.subject
    await this._follows.del(`${did}${SEP}${subject}`)
    await this._followers.del(`${subject}${SEP}${did}`)
    await this._followRkey.del(`${did}${SEP}${rkey}`)
    return true
  }

  // A BLOCK is public and federates by design (unlike a mute, which is private and node-local). Indexed
  // so a block made on another device — or by a peer — is visible here rather than only in this node's
  // own bookkeeping.
  async putBlock ({ did, rkey, record }) {
    const subject = record && record.subject
    if (!did || !rkey || typeof subject !== 'string' || !subject.startsWith('did:')) return false
    await this._blocks.put(`${did}${SEP}${subject}`, { did, subject, rkey, createdAt: (record && record.createdAt) || null })
    await this._blockRkey.put(`${did}${SEP}${rkey}`, { subject })
    return true
  }

  async delBlock ({ did, rkey }) {
    const r = await this._blockRkey.get(`${did}${SEP}${rkey}`)
    if (!r || !r.value || !r.value.subject) return false
    await this._blocks.del(`${did}${SEP}${r.value.subject}`)
    await this._blockRkey.del(`${did}${SEP}${rkey}`)
    return true
  }

  // Every DID this DID blocks, from ANY device — the point of indexing the record rather than trusting
  // local bookkeeping alone.
  async blocking (did) {
    const out = new Set()
    if (!did) return out
    try { for await (const { value } of this._blocks.createReadStream({ gte: `${did}${SEP}`, lt: `${did}\x01` })) if (value && value.subject) out.add(value.subject) } catch {}
    return out
  }

  // The rkey of the block record, so an unblock can delete the right one wherever it was created.
  async blockRkeyFor (did, subject) {
    if (!did || !subject) return null
    try { const r = await this._blocks.get(`${did}${SEP}${subject}`); return (r && r.value && r.value.rkey) || null } catch { return null }
  }

  // The DIDs this DID follows. This is the author set a Following feed scopes on — getTimeline already
  // takes `authors`, so a following feed is this list handed to the existing filter.
  async following (did) {
    const out = []
    if (!did) return out
    try { for await (const { value } of this._follows.createReadStream({ gte: `${did}${SEP}`, lt: `${did}\x01` })) if (value && value.subject) out.push(value.subject) } catch {}
    return out
  }

  async followers (did) {
    const out = []
    if (!did) return out
    try { for await (const { value } of this._followers.createReadStream({ gte: `${did}${SEP}`, lt: `${did}\x01` })) if (value && value.did) out.push(value.did) } catch {}
    return out
  }

  // ---- collection classification at ingest (spec/convergence.md §2, org #33) ------------------------
  //
  // The fallthrough of applyCommit, made EXPLICIT. Three outcomes, and the difference between them is the
  // whole point:
  //   TRACKED             — never reaches here; a view indexed it above.
  //   IGNORED-BY-POLICY   — a decision on file with a stated reason (lib/hosted-dids.js). Counted, not logged.
  //   UNKNOWN             — a lexicon nobody has classified. An operator event, logged once per collection.
  //
  // Returns the class so a caller can act on it; null for a malformed op.
  //
  // ⛔ NEVER THROWS. This sits in the live ingest path. A ledger write that failed must not cost us a
  // commit: a dropped counter is a worse report, a dropped commit is a data gap, and they are not close.
  async noteUnhandled (did, collection, rkey = null) {
    if (typeof collection !== 'string' || collection.length === 0) return null
    // A TRACKED collection reaching a fallthrough means a MALFORMED record (e.g. a profile at an rkey other
    // than `self`), not an unclassified lexicon. Recording it as UNKNOWN would send an operator to
    // hosted-dids.js to classify something already classified. Not this ledger's question.
    if (Appview.TRACKED.has(collection)) return 'tracked'
    const cls = isIgnoredCollection(collection) ? 'ignored' : 'unknown'
    if (cls === 'unknown' && !this._loggedUnknown.has(collection)) {
      this._loggedUnknown.add(collection)
      console.warn(JSON.stringify({
        msg: 'ingest: UNKNOWN collection — not tracked by any view and not on the ignore list',
        collection,
        did: did || null,
        rkey: rkey || null,
        action: 'classify it: add a view, or add it to IGNORED_COLLECTIONS in lib/hosted-dids.js with a reason (spec/convergence.md §2.1)'
      }))
    }
    try {
      const now = new Date().toISOString()
      const prior = await this._collections.get(collection)
      const v = (prior && prior.value) || null
      // Bounded: the entry records WHICH repos are sending this, but must not become a list of every DID
      // on a large fleet. Twenty is enough to recognise a pattern; the count carries the magnitude.
      const dids = new Set((v && Array.isArray(v.dids)) ? v.dids : [])
      if (did && dids.size < 20) dids.add(did)
      await this._collections.put(collection, {
        collection,
        class: cls,
        count: ((v && v.count) || 0) + 1,
        firstSeen: (v && v.firstSeen) || now,
        lastSeen: now,
        dids: [...dids],
        sample: (v && v.sample) || (rkey ? { did: did || null, rkey } : null)
      })
    } catch { /* diagnostics must never cost an ingest */ }
    return cls
  }

  // What has actually ARRIVED that no view indexes. Deliberately distinct from `diff`'s unknown count,
  // which is derived from the AUTHORITY's repo at one instant: this is the live firehose's own record, and
  // it survives a restart. A collection can appear here and not there (the authority deleted it since) or
  // there and not here (we have never been online for one of its commits), and both are worth knowing.
  // UNKNOWN sorts first — it is the class that should make someone look.
  async collectionLedger () {
    const out = []
    try {
      for await (const { value } of this._collections.createReadStream()) if (value && value.collection) out.push(value)
    } catch { return out }
    out.sort((a, b) => (a.class === b.class ? (b.count || 0) - (a.count || 0) : (a.class === 'unknown' ? -1 : 1)))
    return out
  }

  async unknownCollections () { return (await this.collectionLedger()).filter((e) => e.class === 'unknown') }

  // The INGEST_VERSION this DID's history has been folded at (0 = never recorded, i.e. pre-versioning).
  async ingestVersion (did) {
    try { const r = await this._meta.get('ingest:' + did); return (r && r.value && r.value.v) || 0 } catch { return 0 }
  }

  // True when this build indexes more than the build that last folded this DID's history — so its
  // firehose must be replayed from 0 once. Fails OPEN (true): a replay is idempotent thanks to the
  // recSig dedup gate, whereas wrongly skipping it leaves records permanently missing.
  async needsBackfill (did) {
    try { return (await this.ingestVersion(did)) < INGEST_VERSION } catch { return true }
  }

  // Record that this DID's history has been folded at the current version. Called only once the replay
  // has actually caught up, never on merely STARTING one — marking early would make a crash mid-replay
  // look like a completed backfill, which is the one outcome that is silently wrong forever.
  async markBackfilled (did, v = INGEST_VERSION) {
    try { await this._meta.put('ingest:' + did, { v, at: Date.now() }); return true } catch { return false }
  }

  // SNAPSHOT reconcile of one peer's current repo into the index (baseline). Folds every favela post
  // collection (public + local — see scopes.js) via listRecords, AND removes previously-indexed records
  // for this DID that are no longer present (delete-correctness a pure add-only fold can't do). Returns
  // the count of records indexed (present).
  async indexPeer (peer) {
    const did = peer.did
    const desired = new Map() // rkey -> { collection, record }
    // A noRepo peer (co-hosted DID) has NO repo core — its records live in the SHARED overlay store, which
    // is the authoritative view (bypasses membrane fork/desync). Source the baseline from there. Every other
    // peer keeps sourcing from its own repo core (listRecords) — unchanged. Discriminate on peer._noRepo so
    // the store-write of ordinary peers (for read-hydration) never becomes an aliased second source of truth.
    let fromStore = false
    if (peer._noRepo && this._getRecordStore) {
      try {
        const store = await this._getRecordStore(did)
        const recs = store ? await store.records() : []
        fromStore = true // authoritative: a noRepo peer has no repo core to fall back to
        for (const r of recs) {
          const i = r.key.indexOf('/')
          if (i <= 0) continue
          const collection = r.key.slice(0, i)
          if (POST_COLLECTIONS.includes(collection)) desired.set(r.key.slice(i + 1), { collection, record: r.record })
          else if (collection === PROFILE_COLLECTION && r.key.slice(i + 1) === PROFILE_RKEY) await this.putProfile({ did, record: r.record })
          else if (collection === LIKE_COLLECTION) await this.putLike({ did, rkey: r.key.slice(i + 1), record: r.record })
          else if (collection === REPOST_COLLECTION) await this.putRepost({ did, rkey: r.key.slice(i + 1), record: r.record })
          else if (collection === FOLLOW_COLLECTION) await this.putFollow({ did, rkey: r.key.slice(i + 1), record: r.record })
          else if (collection === BLOCK_COLLECTION) await this.putBlock({ did, rkey: r.key.slice(i + 1), record: r.record })
          // The SNAPSHOT path had the same silent tail as applyCommit's (org #33): this `else if` chain
          // simply ended, so a lexicon in the store that no branch matched was dropped without a word.
          // The other baseline path below cannot have this bug — it asks for named collections one at a
          // time and never enumerates — which also means it can never DISCOVER an unknown one. This branch
          // is the only place a snapshot sees the whole repo, so it is the only place that can report.
          else await this.noteUnhandled(did, collection, r.key.slice(i + 1))
        }
      } catch {}
    }
    if (!fromStore) {
      // ⛔ `peer.listRecords` RETURNS { records, cursor }, NOT AN ARRAY (atproto-did-peer 0.2.10, per the
      // lexicon). Every iteration below read the wrapper. This path is currently unreachable in
      // favela-web — bin/favela-web.js:539 makes EVERY DID noRepo, so `fromStore` is always taken — which
      // is the only reason it never threw. It is still wrong, and it is the branch a store-open failure
      // falls into, so the failure mode would have been a TypeError at exactly the moment the store was
      // already misbehaving. Normalised once here rather than at three call sites.
      const listOf = async (coll) => {
        const r = await peer.listRecords(coll)
        return Array.isArray(r) ? r : ((r && r.records) || [])
      }
      // Baseline the profile too — a peer that has not edited it since we connected emits no commit, so
      // the fold is the only place a first-time author's profile is picked up.
      try {
        for (const r of await listOf(PROFILE_COLLECTION)) {
          const rkey = String(r.uri || r.key || '').split('/').pop()
          if (rkey === PROFILE_RKEY && r.value) await this.putProfile({ did, record: r.value })
        }
      } catch {}
      for (const [coll, put] of [[LIKE_COLLECTION, 'putLike'], [FOLLOW_COLLECTION, 'putFollow'], [REPOST_COLLECTION, 'putRepost'], [BLOCK_COLLECTION, 'putBlock']]) {
        try {
          for (const r of await listOf(coll)) {
            const rkey = String(r.uri || r.key || '').split('/').pop()
            if (rkey && r.value) await this[put]({ did, rkey, record: r.value })
          }
        } catch {}
      }
      for (const collection of POST_COLLECTIONS) {
        for (const r of await listOf(collection)) { // [{ uri|key, cid, value }]
          const path = r.uri || r.key || ''
          const rkey = path.split('/').pop()
          if (rkey) desired.set(rkey, { collection, record: r.value })
        }
      }
    }
    // Remove stragglers: indexed rkeys for this DID that are no longer in the repo.
    const lo = `${did}${SEP}`
    const hi = `${did}\x01`
    const stale = []
    for await (const { key } of this._ref.createReadStream({ gte: lo, lt: hi })) {
      const i = key.indexOf(SEP)
      const rkey = i >= 0 ? key.slice(i + 1) : null
      if (rkey && !desired.has(rkey)) stale.push(rkey)
    }
    for (const rkey of stale) await this.delPost({ did, rkey })
    // Add / update present records.
    for (const [rkey, { collection, record }] of desired) await this.putPost({ did, collection, rkey, record })
    return desired.size
  }

  // INCREMENTAL ingest of normalized commit ops [{ action, collection, rkey, record? }] — decoded by
  // DidPeer.commitOps from a #commit frame (the record is read from the frame's own CAR, race-free).
  // create/update -> putPost, delete -> delPost, for favela post collections only. Returns ops applied.
  async applyCommit (did, ops) {
    if (!Array.isArray(ops)) return 0
    let n = 0
    for (const op of ops) {
      // Profile commits ride the SAME firehose as posts and used to be discarded here. The record is read
      // from the frame's own CAR, so indexing it needs no fetch — the bytes already arrived.
      if (op.collection === PROFILE_COLLECTION) {
        if (op.action === 'delete') { if (await this.delProfile(did)) n++ ; continue }
        if ((op.action === 'create' || op.action === 'update') && op.record) { if (await this.putProfile({ did, record: op.record })) n++ }
        continue
      }
      if (op.collection === LIKE_COLLECTION) {
        if (op.action === 'delete') { if (await this.delLike({ did, rkey: op.rkey })) n++ ; continue }
        if (op.record && await this.putLike({ did, rkey: op.rkey, record: op.record })) n++
        continue
      }
      if (op.collection === REPOST_COLLECTION) {
        if (op.action === 'delete') { if (await this.delRepost({ did, rkey: op.rkey })) n++ ; continue }
        if (op.record && await this.putRepost({ did, rkey: op.rkey, record: op.record })) n++
        continue
      }
      if (op.collection === FOLLOW_COLLECTION) {
        if (op.action === 'delete') { if (await this.delFollow({ did, rkey: op.rkey })) n++ ; continue }
        if (op.record && await this.putFollow({ did, rkey: op.rkey, record: op.record })) n++
        continue
      }
      if (op.collection === BLOCK_COLLECTION) {
        if (op.action === 'delete') { if (await this.delBlock({ did, rkey: op.rkey })) n++ ; continue }
        if (op.record && await this.putBlock({ did, rkey: op.rkey, record: op.record })) n++
        continue
      }
      // ⛔ NOT A BARE `continue` (org #33). Anything reaching here is either IGNORED-BY-POLICY or UNKNOWN,
      // and collapsing those two is exactly the mistake spec §2 exists to prevent: one is a decision, the
      // other is a lexicon nobody has looked at. Both are recorded; only the second warns.
      if (!POST_COLLECTIONS.includes(op.collection)) { await this.noteUnhandled(did, op.collection, op.rkey || null); continue }
      if (op.action === 'delete') { await this.delPost({ did, rkey: op.rkey }); n++; continue }
      if ((op.action === 'create' || op.action === 'update') && op.record) {
        // op.action comes off the #commit frame, so 'update' IS the firehose's own statement that
        // this rkey was edited — the prev chain, read rather than re-implemented (spec §10.5.2).
        await this.putPost({ did, collection: op.collection, rkey: op.rkey, record: op.record, edited: op.action === 'update' }); n++
      }
    }
    return n
  }

  // Reverse-chron timeline. cursor = the last key from a prior page (exclusive).
  // `authors` (optional Set|array of DIDs) scopes the timeline to those authors — this is the PER-VIEWER
  // view (DESIGN §7.5): a signed-in viewer sees the union of the member DIDs of the communities they
  // belong to, computed per-request by lib/communities.js. Omitted/empty → the global node timeline
  // (anonymous / unscoped). The filter is applied over the reverse-chron stream so paging still yields
  // `limit` matching posts; because the index only holds the node's rostered DIDs, this is naturally the
  // INTERSECTION of the viewer's communities with what this node serves.
  async getTimeline ({ limit = 30, cursor = null, authors = null, viewerDid = null } = {}) {
    const allow = normAuthors(authors)
    const posts = []
    let lastKey = null
    // When filtering we may scan past `limit` index entries to collect `limit` matches — keep streaming
    // until we have enough (or the stream ends), advancing the cursor to the last SCANNED key.
    const stream = this._timeline.createReadStream({ ...(cursor ? { lt: cursor } : {}), reverse: true, ...(allow ? {} : { limit }) })
    for await (const { key, value } of stream) {
      lastKey = key
      if (allow && !allow.has(value.did)) continue
      posts.push(await this._hydrate(value, viewerDid))
      if (posts.length >= limit) break
    }
    // More pages remain iff we filled this one (unfiltered: exactly limit; filtered: we broke on limit).
    return { posts, cursor: posts.length >= limit ? lastKey : null }
  }

  // Reverse-chron feed for one author. All of a DID's keys live in [`${did}\x00`, `${did}\x01`).
  // reverse pagination: keep the DID floor as gte, move the ceiling (lt) down to the last key seen.
  //
  // `filter` mirrors app.bsky.feed.getAuthorFeed's knownValues, so the profile tabs are the same split
  // bsky makes rather than one we invented: posts_with_replies (default), posts_no_replies,
  // posts_with_media, posts_and_author_threads, posts_with_video. An unknown value degrades to the
  // default instead of erroring — a filter is a view preference, not an assertion, and a bad query
  // string should not 500 a profile.
  //
  // Filtering happens OVER the reverse-chron stream (the timeline's pattern), so a page still yields
  // `limit` matches rather than "limit scanned, some discarded" — otherwise a reply-heavy profile shows
  // three posts under posts_no_replies and looks empty.
  async getAuthorFeed (did, { limit = 30, cursor = null, viewerDid = null, filter = 'posts_with_replies' } = {}) {
    const f = AUTHOR_FILTERS.has(filter) ? filter : 'posts_with_replies'
    const unfiltered = f === 'posts_with_replies'
    const needsRecord = f === 'posts_with_media' || f === 'posts_with_video'
    const gte = `${did}${SEP}`
    const lt = cursor || `${did}\x01`
    const posts = []
    let lastKey = null
    const stream = this._author.createReadStream({ gte, lt, reverse: true, ...(unfiltered ? { limit } : {}) })
    for await (const { key, value } of stream) {
      lastKey = key
      if (!unfiltered) {
        // Reply-ness is one cheap get off the child->parent index — decided BEFORE hydrating, since
        // hydration costs a record read plus profile and three counts per post.
        const r = await this._replyOf.get(this._refKey(value.did, value.rkey))
        const parentUri = r && r.value && r.value.parentUri
        if (f === 'posts_no_replies' && parentUri) continue
        if (f === 'posts_and_author_threads' && parentUri) {
          // A self-thread only. Replying to someone ELSE is a conversation, not the author's own thread.
          const p = this._parseUri(parentUri)
          if (!p || p.did !== did) continue
        }
        if (needsRecord) {
          const record = await this._resolveRecord(value.did, value.collection || 'app.bsky.feed.post', value.rkey)
          const m = embedMedia(record)
          if (f === 'posts_with_media' && !(m.images || m.video)) continue
          if (f === 'posts_with_video' && !m.video) continue
        }
      }
      posts.push(await this._hydrate(value, viewerDid))
      if (posts.length >= limit) break
    }
    return { posts, cursor: posts.length >= limit ? lastKey : null }
  }

  // Reverse-chron feed for one topic/hashtag (a custom feed = the atproto feed-generator "filter",
  // run locally). All of a tag's keys live in [`${tag}\x00`, `${tag}\x01`); pagination mirrors the
  // author feed (move the `lt` ceiling down to the last key seen).
  async getTagFeed (tag, { limit = 30, cursor = null, viewerDid = null } = {}) {
    const t = normTag(tag)
    if (!t) return { posts: [], cursor: null }
    const gte = `${t}${SEP}`
    const lt = cursor || `${t}\x01`
    const posts = []
    let lastKey = null
    for await (const { key, value } of this._tags.createReadStream({ gte, lt, reverse: true, limit })) {
      posts.push(await this._hydrate(value, viewerDid)); lastKey = key
    }
    return { posts, cursor: posts.length === limit ? lastKey : null }
  }

  async close () { await this.bee.close() }
}
// favela auth — DID web sign-in, atproto-native (the pgv3 method). Thin glue: the reusable crypto
// verify lives in atproto-identity (makeAtprotoWebVerify — secp256k1 sub-key delegated by the DID's
// #atproto key, PLC-anchored), the identity/registration in hyper-identity (AtprotoProvider). favela
// owns only the single-use challenge store + the session cookie. No keet, no anproto; favela is keyless.
//
// The DID is the identity anchor; each browser sub-key is a device delegated by the DID's #atproto key
// (the atproto analog of pgv3's root ← device chain). The delegation is re-verified every login, so
// there is no TOFU and no per-DID root bookkeeping.
import { AtprotoProvider } from 'hyper-identity/auth/providers/atproto'
import { makeAtprotoWebVerify } from 'atproto-identity/lib/web-auth.js'
import { SessionStore } from './sessions.js'
import crypto from 'hypercore-crypto'
import b4a from 'b4a'

const CHALLENGE_TTL_MS = 5 * 60 * 1000
const SESSION_TTL_MS = 30 * 24 * 60 * 60 * 1000

// Minimal DID registry satisfying AtprotoProvider (getIdentityByDid + registerIdentity). favela is a
// keyless VIEW; it doesn't need hyper-identity's full autobase IdentityRegistry.
export class DidRegistry {
  constructor () { this._byDid = new Map() }
  async getIdentityByDid (did) { return this._byDid.get(String(did)) || null }
  async registerIdentity (identity) {
    const did = (identity.credentials && identity.credentials.did) || identity.identityId
    this._byDid.set(String(did), identity)
    return identity
  }
}

export class FavelaAuth {
  // resolveVerifyKey(did) → the DID's #atproto compressed pubkey (favela wires plc.js over the PLC
  // directory). Required for the delegation check — without it (or on PLC-resolve failure) logins fail
  // closed.
  constructor ({ registry, resolveVerifyKey, now = () => Date.now(), sessions = null } = {}) {
    this._now = now
    this._challenges = new Map() // hex -> exp (single-use)
    // Sessions live in the ported pgv3 SessionStore (lib/sessions.js): sliding renewal so an ACTIVE
    // user is not logged out the moment the fixed window elapses, plus a sweeper so an abandoned
    // session does not sit in memory until the process dies. The bare Map this replaces had neither.
    this.sessions = sessions || new SessionStore({ ttl: SESSION_TTL_MS })
    this.registry = registry || new DidRegistry()
    const webVerify = resolveVerifyKey ? makeAtprotoWebVerify({ resolveVerifyKey }) : async () => false
    // The AtprotoProvider's injected verify: burn the single-use challenge FIRST (replay guard), then
    // run the atproto crypto verify (challenge sig by the sub-key + the DID's #atproto delegation).
    const verify = async (proof) => {
      if (!proof || !this._consume(proof.challenge)) return false
      return webVerify(proof)
    }
    this.provider = new AtprotoProvider(this.registry, { verify })
  }

  mintChallenge () {
    const c = b4a.toString(crypto.randomBytes(32), 'hex')
    this._challenges.set(c, this._now() + CHALLENGE_TTL_MS)
    return c
  }

  _consume (c) {
    const exp = this._challenges.get(c)
    if (exp == null || this._now() >= exp) { this._challenges.delete(c); return false }
    this._challenges.delete(c) // burn on use
    return true
  }

  // proof = { did, subKey(hex), challenge(hex), sig, delegation, handle?, didKey? }. Verifies +
  // registers via the provider, then mints a session. Throws (provider: 'Invalid atproto proof') on
  // any failure.
  async login (proof) {
    const result = await this.provider.authenticate({ proof })
    const token = this.sessions.create({ did: result.identityId, subKey: proof.subKey })
    return { token, did: result.identityId, handle: (result.credentials && result.credentials.handle) || null }
  }

  // Unchanged contract: { did, subKey } for a live session, null otherwise. The store applies the
  // sliding renewal on the way through.
  get (token) {
    const entry = this.sessions.get(token)
    return entry ? entry.identity : null
  }

  revoke (token) { return this.sessions.revoke(token) }

  /** Stop the session sweeper (tests, shutdown). Challenges are plain state and need no teardown. */
  close () { this.sessions.close() }
}

const LOOPBACK = new Set(['127.0.0.1', '::1', '::ffff:127.0.0.1'])

/**
 * Should a session-cookie handoff be performed for this request?
 *
 * WHY IT EXISTS: an embedded WebView (favela-android) has its own cookie jar, and the session is
 * established by the WORKLET over the loopback API — so the UI would render anonymously forever unless
 * the token it already holds can be turned into the cookie form of the same session.
 *
 * That grants nothing new — possession of the token IS the session — but it must not become either of
 * the two things it resembles:
 *   - an OPEN COOKIE-SETTER: an unknown or expired token sets nothing, so a crafted link cannot stamp
 *     an attacker-chosen value into a visitor's jar.
 *   - an OPEN REDIRECT: `next` is confined to a same-origin absolute path. A protocol-relative `//host`
 *     is a URL, not a path — exactly the case a naive "starts with /" check waves through.
 *
 * LOOPBACK ONLY. Fleet instances bind 0.0.0.0, and a token in a query string leaks through logs and
 * Referer in a way a cookie does not. Only the app hosting the server has business calling this, and an
 * unknown peer address is refused rather than assumed local.
 *
 * @returns {{ ok: boolean, token?: string, next: string, reason?: string }}
 */
export function handoffDecision ({ token, remoteAddress, isValid, next } = {}) {
  const to = (typeof next === 'string' && next.startsWith('/') && !next.startsWith('//')) ? next : '/'
  if (!LOOPBACK.has(String(remoteAddress || ''))) return { ok: false, next: to, reason: 'not loopback' }
  const t = String(token || '')
  if (!t || typeof isValid !== 'function' || !isValid(t)) return { ok: false, next: to, reason: 'unknown or expired token' }
  return { ok: true, token: t, next: to }
}

export { CHALLENGE_TTL_MS, SESSION_TTL_MS }
// Minimal web-global shims for Bare (adapted from hyper-proto-peer/lib/bare-globals.js).
// Bare omits TextEncoder/TextDecoder (used at module-load by deps like @noble/curves and by
// atcute's encoding paths). Buffer IS a Bare global, so we back them with it. Import FIRST.
// atcute's P2P handler REPLACES fetch, so we deliberately do NOT shim fetch — only what the
// lexicon/encoding + Response-handling paths need. No-op under Node.

import bareProcess from 'bare-process'
if (typeof globalThis.process === 'undefined') globalThis.process = bareProcess

if (typeof globalThis.TextEncoder === 'undefined') {
  globalThis.TextEncoder = class TextEncoder {
    get encoding () { return 'utf-8' }
    encode (input = '') { return new Uint8Array(Buffer.from(String(input), 'utf8')) }
    encodeInto (src, dest) {
      const bytes = this.encode(src)
      const n = Math.min(bytes.length, dest.length)
      dest.set(bytes.subarray(0, n))
      return { read: src.length, written: n }
    }
  }
}

if (typeof globalThis.TextDecoder === 'undefined') {
  globalThis.TextDecoder = class TextDecoder {
    get encoding () { return 'utf-8' }
    decode (input) {
      if (input == null) return ''
      const u8 = input instanceof Uint8Array ? input : new Uint8Array(input.buffer || input, input.byteOffset || 0, input.byteLength)
      return Buffer.from(u8).toString('utf8')
    }
  }
}
// Every blob a repo's records REFER to — spec/convergence.md §6.
//
// Records are not the whole repo. Blobs (images, avatars, banners, video) live OUTSIDE the MST and are
// addressed by CID from inside records, so a node can hold a byte-perfect, fully verified record set and
// still be unable to render a single image. Nothing checked this until now.
//
// ⛔ WHY A GENERIC WALK AND NOT A LIST OF PATHS. The obvious implementation reads the paths we know:
// profile.avatar, profile.banner, embed.images[].image, embed.video, embed.external.thumb,
// recordWithMedia.media.*. That list is wrong the day a lexicon adds a field, and wrong SILENTLY — a
// blob nobody enumerates is a blob nobody notices is missing, which is precisely the failure this is
// built to catch. So walk the decoded record and take anything shaped like a blob, wherever it sits.
//
// A blob ref is `{$type:'blob', ref:<cid>, mimeType, size}` in the current lexicon. The pre-lexicon
// "legacy blob" form is `{cid:'<string>', mimeType}` with no $type; wj62's repo predates the cutover in
// places, so both are taken. `ref` itself arrives in four shapes (multiformats CID, {$link}, {'/'} or a
// bare string) — blobCid() in render.js already normalises all four and is reused rather than reinvented.
import { blobCid } from './render.js'

// Depth cap: records are small and self-describing, but this walks UNTRUSTED decoded input. A cycle is
// impossible out of dag-cbor (no back-references) yet a deeply nested record should still cost bounded
// work rather than blowing the stack.
const MAX_DEPTH = 12

function pushRef (out, seen, node, where) {
  const cid = blobCid(node.ref !== undefined ? node.ref : node.cid)
  if (typeof cid !== 'string' || !cid) return
  if (seen.has(cid)) return // the same blob referenced twice is ONE blob
  seen.add(cid)
  out.push({
    cid,
    mimeType: typeof node.mimeType === 'string' ? node.mimeType : null,
    size: Number.isFinite(node.size) ? node.size : null,
    where // a breadcrumb, so a report can say WHICH field is missing its bytes
  })
}

function walk (node, out, seen, depth, where) {
  if (!node || depth > MAX_DEPTH) return
  if (Array.isArray(node)) {
    for (let i = 0; i < node.length; i++) walk(node[i], out, seen, depth + 1, `${where}[${i}]`)
    return
  }
  if (typeof node !== 'object') return
  // A multiformats CID is an object, but it is a LEAF — descending into its internals would yield
  // garbage fields, so stop here. It is only a blob when it sat under a `ref`/`cid` key, handled below.
  if (node.asCID === node) return

  const isBlob = node.$type === 'blob' ||
    (node.ref !== undefined && typeof node.mimeType === 'string') ||
    (typeof node.cid === 'string' && typeof node.mimeType === 'string' && node.$type === undefined)
  if (isBlob) { pushRef(out, seen, node, where); return }

  for (const k of Object.keys(node)) walk(node[k], out, seen, depth + 1, where ? `${where}.${k}` : k)
}

// One record -> [{ cid, mimeType, size, where }], deduped within the record.
export function collectBlobRefs (record) {
  const out = []
  walk(record, out, new Set(), 0, '')
  return out
}

// Every blob the whole repo refers to -> Map<cid, { cid, mimeType, size, refs:[{collection,rkey,where}] }>.
// Keyed by CID because blobs are content-addressed: the same image embedded in two posts is ONE blob,
// and reporting it twice would overstate a gap.
export function collectRepoBlobRefs (records) {
  const byCid = new Map()
  for (const r of records || []) {
    if (!r || !r.record) continue
    for (const b of collectBlobRefs(r.record)) {
      let e = byCid.get(b.cid)
      if (!e) { e = { cid: b.cid, mimeType: b.mimeType, size: b.size, refs: [] }; byCid.set(b.cid, e) }
      e.refs.push({ collection: r.collection, rkey: r.rkey, where: b.where })
    }
  }
  return byCid
}

// Which referenced blobs are absent locally. hasBlob(cid) -> boolean.
//
// This answers the REFERENCED question only. An ORPHAN — bytes uploaded and referenced by no record — is
// invisible to any walk of records, by construction, and needs com.atproto.sync.listBlobs, which the
// membrane does not implement (spec §6). That is the class that lost the 2026-07-03 image, so the gap is
// named in the result rather than left for the reader to infer from its absence.
// listAuthorityBlobs() -> { cids: [...] } | null   (com.atproto.sync.listBlobs, optional)
//
// Two questions, and they need different sources:
//   MISSING  — the records refer to it, we do not have the bytes.  (records, always available)
//   ORPHAN   — the authority HAS it, no record refers to it.       (needs the authority's inventory)
//
// An orphan is invisible to any walk of records by construction, which is exactly why the 2026-07-03
// image could be lost without any surface noticing. When no inventory is available the result says
// orphansChecked:false rather than reporting zero orphans — "we did not look" and "there are none" are
// different answers, and conflating them is the habit this whole spec exists to break.
export async function diffBlobs ({ records, hasBlob, listAuthorityBlobs = null }) {
  const byCid = collectRepoBlobRefs(records)
  const missing = []
  let present = 0
  for (const e of byCid.values()) {
    let here = false
    try { here = await hasBlob(e.cid) } catch { here = false }
    if (here) present++
    else missing.push(e)
  }

  let orphansChecked = false
  let orphans = []
  let inventory = null
  if (typeof listAuthorityBlobs === 'function') {
    let inv = null
    try { inv = await listAuthorityBlobs() } catch { inv = null }
    if (inv && Array.isArray(inv.cids)) {
      orphansChecked = true
      inventory = inv.cids.length
      orphans = inv.cids.filter((cid) => !byCid.has(cid)).map((cid) => ({ cid }))
    }
  }

  return {
    referenced: byCid.size,
    present,
    missing,
    inventory, // null when the authority could not be asked
    orphansChecked,
    orphans,
    orphanNote: orphansChecked
      ? 'orphans = blobs the authority holds that no record references'
      : 'orphan blobs (uploaded, referenced by no record) are NOT checked — needs com.atproto.sync.listBlobs (spec/convergence.md §6)'
  }
}

// ---- content-address verification -------------------------------------------------------------------
//
// ⛔ NEVER write fetched bytes under a CID without checking them. The CID *is* the hash (raw codec,
// sha-256), so verifying is free and refusing is absolute: a server that returns the wrong body cannot
// get it stored under the right name. This is the blob analogue of the record-side rule that bytes must
// re-encode to their own CID — the whole reason it is safe to fetch from our own membrane, or anyone.
//
// cidForBlobSync is atproto-repo's own raw-codec derivation (the same one atproto-store's
// OverlayBlobStore uses to name these files), so this cannot drift from how they were written.
export async function verifyBlobCid (bytes, cid) {
  if (!bytes || !bytes.length || typeof cid !== 'string' || !cid) return false
  try {
    const { cidForBlobSync } = await import('atproto-repo/lib/cid.js')
    return String(cidForBlobSync(bytes)) === cid
  } catch {
    return false // cannot verify -> do not write. Never "assume it is fine".
  }
}
// Serving blobs (and locating record dirs) from the SHARED content-addressed overlay store — favela-web
// slice 3b. These are the SAME files hpp writes via atproto-store's OverlayRepoStore/OverlayBlobStore, so a
// co-located tabertron (running BOTH hpp and favela-web) keeps ONE physical copy per DID, no data drift.
//
// The derivation here MUST match atproto-store exactly, or the two processes would write to separate dirs and
// the whole "one copy" invariant breaks. roomKey16(wj62) === '0d6d2249141a9549' matches hpp's on-disk dir.
import crypto from 'hypercore-crypto'
import b4a from 'b4a'

const ROOM_KEY_NS = b4a.from('atproto-base/v1/room-key')

// The 16-hex per-DID namespace dir shared by hpp and favela. Content lives under OVERLAY_ROOT/<roomKey16>/.
export function roomKey16 (did) {
  return b4a.toString(crypto.hash([ROOM_KEY_NS, b4a.from(did)]), 'hex').slice(0, 16)
}

// Absolute path of a DID's content-addressed blob file in the shared store: <root>/<roomKey16>/blobs/<cid>.
// Joined by hand (no bare-path) so this module stays runtime-agnostic — it runs under both bare (the daemon)
// and node (tests). cid MUST be pre-validated with isSafeCid; roomKey16/'blobs' are trusted segments.
export function blobPath (root, did, cid) {
  return `${root.replace(/\/+$/, '')}/${roomKey16(did)}/blobs/${cid}`
}

// atproto blobs are content-addressed and the mimeType lives in the record's blob ref (not the file), so we
// sniff the content-type from magic bytes for the getBlob response header. Default: application/octet-stream.
export function sniffMime (b) {
  if (b.length >= 3 && b[0] === 0xFF && b[1] === 0xD8 && b[2] === 0xFF) return 'image/jpeg'
  if (b.length >= 8 && b[0] === 0x89 && b[1] === 0x50 && b[2] === 0x4E && b[3] === 0x47) return 'image/png'
  if (b.length >= 4 && b[0] === 0x47 && b[1] === 0x49 && b[2] === 0x46 && b[3] === 0x38) return 'image/gif'
  if (b.length >= 12 && b[0] === 0x52 && b[1] === 0x49 && b[2] === 0x46 && b[3] === 0x46 && b[8] === 0x57 && b[9] === 0x45 && b[10] === 0x42 && b[11] === 0x50) return 'image/webp'
  return 'application/octet-stream'
}

// True iff a caller-supplied cid is safe to use as a path segment (no traversal, bounded length). getBlob MUST
// reject anything else — the cid comes straight off an untrusted query string.
export function isSafeCid (cid) {
  return typeof cid === 'string' && cid.length > 0 && cid.length <= 128 && !cid.includes('/') && !cid.includes('..')
}
// Bookmarks — private, node-local, per viewer.
//
// ⛔ NOT A RECORD, AND NOT FOR THE SAME REASON AS A MUTE. A mute is private because atproto defines it
// that way. A bookmark is private because there is no interoperable lexicon for one that we should be
// writing: inventing `net.favela.bookmark` in a user's public repo would publish their reading list to
// the network forever, in signed records, to solve a problem that is entirely local. If bsky's own
// bookmark lexicon stabilises this can be revisited — as a DELIBERATE choice to publish, not as a
// side-effect of how it was stored.
//
// So: same home as mutes (the appview's own store, a rebuildable cache that is never replicated), same
// per-viewer keying, and a remove is a real delete that leaves nothing behind.
//
// Keyed `<viewerDid>\x00<at-uri>`. The value carries `at` so the list can be shown newest-first — a
// bookmark list ordered by the POST's date would bury something you saved today under an old post you
// just found, which is the opposite of what the feature is for.

const SEP = '\x00'

export function createBookmarkStore (bee) {
  if (!bee) throw new Error('createBookmarkStore requires a Hyperbee (sub)')
  const key = (viewer, uri) => `${viewer}${SEP}${uri}`

  return {
    async add (viewer, uri) {
      if (!viewer || typeof uri !== 'string' || !uri.startsWith('at://')) return false
      await bee.put(key(viewer, uri), { at: Date.now() })
      return true
    },
    async remove (viewer, uri) {
      if (!viewer || !uri) return false
      try { await bee.del(key(viewer, uri)) } catch { return false }
      return true
    },
    async has (viewer, uri) {
      if (!viewer || !uri) return false
      try { const r = await bee.get(key(viewer, uri)); return !!(r && r.value) } catch { return false }
    },
    // Every bookmarked uri for this viewer as a Set — one scan per page render, so the read path does not
    // do a lookup per post.
    async uris (viewer) {
      const out = new Set()
      if (!viewer) return out
      const p = viewer + SEP
      try {
        for await (const e of bee.createReadStream({ gte: p, lt: p + '￿' })) {
          const uri = String(e.key).slice(p.length)
          if (uri) out.add(uri)
        }
      } catch { /* an unreadable index must not blank the page */ }
      return out
    },
    // Newest-SAVED first — see the header note on why this is not the post's own date.
    async list (viewer, { limit = 50 } = {}) {
      const rows = []
      if (!viewer) return rows
      const p = viewer + SEP
      try {
        for await (const e of bee.createReadStream({ gte: p, lt: p + '￿' })) {
          rows.push({ uri: String(e.key).slice(p.length), at: (e.value && e.value.at) || 0 })
        }
      } catch { /* same */ }
      rows.sort((a, b) => b.at - a.at)
      return rows.slice(0, limit)
    }
  }
}
// Bounded fetch — the fix for the 2026-08-30 stortron socket leak.
//
// WHY THIS EXISTS. favela-web reached 24.3 GB RSS holding 47,191 leaked sockets (46,857 of them
// outbound :443) and OOM-killed the box twice, because an HTTPS fetch to a host that accepts TCP but
// never completes the TLS handshake holds its socket FOR EVER. Three faults compound, and no one of
// them is sufficient to explain it:
//
//  1. bare-https WRAPS the raw socket — `HTTPSAgent.createConnection` returns
//     `new HTTPSSocket(super.createConnection(opts), opts)`. `HTTPAgent.addRequest` then attaches
//     `.on('timeout', () => socket.destroy())` to the WRAPPER, while bare-tcp arms `setTimeout` on the
//     INNER socket. bare-tls forwards data/drain/end/close/error upward but NOT 'timeout'. So on HTTPS
//     the agent's own reaper can never fire. Plain HTTP is unaffected — nothing wraps there.
//  2. bare-fetch silently drops `timeout`: its Request destructures only body/method/headers/signal/
//     agent. Every call site passing `timeout: 30000` was a no-op.
//  3. bare-fetch's `signal` rejects the promise but never destroys the socket — its abort() is
//     registered before the ClientRequest exists and only cancels bodies. And AbortController is not a
//     global in Bare (verified, v1.28.7), so reaching for one crashes the daemon outright.
//
// Measured against a blackhole listener (accept, never reply), 5 concurrent fetches:
//   stock agent  -> 5 client sockets still ESTABLISHED at t+20s, no promise settled, held for ever
//   this module  -> 0 client sockets at t+20s
//
// Hence two mechanisms, BOTH required:
//   - ReapingHTTPSAgent forwards the inner socket's 'timeout' up to the wrapper, which makes the
//     agent's EXISTING destroy path work as designed. This is what reclaims the fd and the memory.
//   - a promise deadline settles the caller, because destroying the socket underneath bare-fetch does
//     not reject its promise.
//
// On the timer: bare-tcp's timeout is an IDLE timeout (`_timer.refresh()` on both read and write), not
// an absolute one, so a slow-but-live transfer is never cut off. It is a liveness deadline on a foreign
// socket, not a poll — the failure it exists to catch is a counterparty that emits NOTHING, ever, and
// silence is only observable against a clock. That is why it is a timer and not an event subscription.
import http from 'bare-http1'
import https from 'bare-https'
import bareFetch from 'bare-fetch'

// Idle, not absolute. Generous enough that a slow upstream that is still talking survives; any host
// that goes silent is reaped this long after its last byte instead of never.
export const DEFAULT_SOCKET_IDLE_MS = 30000
// Whole-request ceiling, so a caller is never left pending for ever. Matches the most generous value
// already passed by an existing call site (bin/favela-web.js used timeout: 60000).
export const DEFAULT_DEADLINE_MS = 60000

class ReapingHTTPSAgent extends https.Agent {
  createConnection (opts) {
    const socket = super.createConnection(opts) // an HTTPSSocket wrapping a bare-tcp socket
    const inner = socket && socket.socket
    // The one line the whole leak turned on: let the wrapper hear its own socket time out, so
    // HTTPAgent.addRequest's ontimeout -> socket.destroy() can run.
    if (inner && typeof inner.on === 'function') {
      inner.on('timeout', () => socket.emit('timeout'))
    }
    return socket
  }
}

function protocolOf (input) {
  try {
    if (typeof input === 'string') return new URL(input).protocol
    if (input && input.url) return new URL(input.url).protocol
    if (input && input.protocol) return input.protocol
  } catch {}
  return null
}

export function createBoundedFetch (opts = {}) {
  const socketIdleMs = opts.socketIdleMs || DEFAULT_SOCKET_IDLE_MS
  const deadlineMs = opts.deadlineMs || DEFAULT_DEADLINE_MS
  const onTimeout = typeof opts.onTimeout === 'function' ? opts.onTimeout : null

  const httpsAgent = new ReapingHTTPSAgent({ keepAlive: 1000, timeout: socketIdleMs })
  const httpAgent = new http.Agent({ keepAlive: 1000, timeout: socketIdleMs })

  function boundedFetch (input, init = {}) {
    const proto = protocolOf(input)
    // Only override when we can tell — passing an https agent to an http URL would be worse than
    // leaving bare-fetch to choose its own global.
    const agent = init.agent || (proto === 'https:' ? httpsAgent : proto === 'http:' ? httpAgent : null)
    // Honour the `timeout` callers already pass and believe in; it has been inert until now.
    const ms = init.timeout || deadlineMs

    const request = bareFetch(input, agent ? { ...init, agent } : init)

    let timer = null
    const deadline = new Promise((resolve, reject) => {
      timer = setTimeout(() => {
        if (onTimeout) { try { onTimeout({ url: String(input), ms }) } catch {} }
        // The socket is already being reaped by the agent's idle timeout; this only frees the caller.
        reject(new Error(`fetch deadline exceeded after ${ms}ms: ${String(input)}`))
      }, ms)
      if (typeof timer.unref === 'function') timer.unref()
    })

    return Promise.race([request, deadline]).finally(() => { if (timer) clearTimeout(timer) })
  }

  // Exposed so the leak is OBSERVABLE rather than inferred: these are the only sockets this fetch owns,
  // and a growing count here is the signature that cost 24.3 GB before anyone could see it.
  boundedFetch.agents = { https: httpsAgent, http: httpAgent }
  boundedFetch.socketCount = () =>
    [...(httpsAgent.sockets || [])].length + [...(httpAgent.sockets || [])].length

  return boundedFetch
}

export default createBoundedFetch
// Auth checks and request middleware — PORTED from pear-git-v3 `lib/auth/check.js`.
//
// Two layers, same as pgv3:
//
//   1. extractIdentity(req, sessions) — reads the bearer token from `Authorization: Bearer <token>`
//      OR the `favela_session` cookie, resolves it against the SessionStore, returns the identity or
//      null. Never throws; the caller decides whether anonymous is acceptable.
//
//   2. requireIdentity(ctx) / requireMember(ctx) — handler-side guards that THROW an AuthError.
//      Having these as guards rather than as an inline `if (!viewer)` in every route is the actual
//      lesson from pgv3: its read gate sits at ONE choke point above ~14 routes precisely because
//      fourteen hand-written checks are fourteen chances to forget. favela already paid that bill —
//      /api/post had no gate until 2026-08-11, when an anonymous request posted as wj62, while the
//      images branch of the same handler DID check. A named guard makes the omission visible.
//
// WHAT WAS DELIBERATELY NOT PORTED, and why:
//
//   - The `transport === 'uds'` bypass. pgv3 trusts a local caller because holding the UDS socket is
//     itself proof of local access. favela-web serves HTTP only; inventing a "local is trusted" rule
//     here would be a bypass with nothing behind it. (favela's loopback handoff in lib/auth.js is a
//     different thing: it converts a token the caller ALREADY holds into cookie form, granting nothing.)
//
//   - `globalPermissions` / IdentityRegistry. pgv3 resolves a pubkey to a User record with global
//     perms. favela has no such registry, and it should not grow a server-side one: membership belongs
//     in the community room (`add-member` / `ban` ops, DID-rooted), which is replicated P2P and is the
//     same authority the feed's roster already reads. So `requireMember` takes an INJECTED policy
//     rather than assuming a store.
//
// AUTHENTICATION IS NOT AUTHORISATION. A valid session proves only "this browser holds a sub-key that
// the DID delegated". Any atproto DID can prove that about ITSELF, so a session alone must never imply
// the right to write — that is what `requireMember` is for, and why it fails CLOSED with no policy.

export const COOKIE_NAME = 'favela_session'

export class AuthError extends Error {
  constructor (message, status = 401) {
    super(message)
    this.name = 'AuthError'
    this.status = status
    this.code = 'EAUTH'
  }
}

/** Extract the bearer token from a request, header first, then cookie. */
export function extractToken (req) {
  if (!req || !req.headers) return null

  const auth = req.headers.authorization
  // Header before cookie: the cookie is what a browser attaches automatically, the header is what a
  // client sets deliberately. When both are present, honour the deliberate one.
  if (auth && auth.startsWith('Bearer ')) return auth.slice(7).trim() || null

  const cookieHeader = req.headers.cookie
  if (cookieHeader) {
    for (const part of cookieHeader.split(';')) {
      const idx = part.indexOf('=')
      if (idx === -1) continue
      if (part.slice(0, idx).trim() !== COOKIE_NAME) continue
      const raw = part.slice(idx + 1).trim()
      if (!raw) return null
      try { return decodeURIComponent(raw) } catch { return raw }
    }
  }

  return null
}

/**
 * Resolve the request's identity via the SessionStore. Sliding renewal is applied by the store.
 * @returns {{ did: string, subKey?: string } | null}
 */
export function extractIdentity (req, sessions) {
  const token = extractToken(req)
  if (!token || !sessions) return null
  const entry = sessions.get(token)
  return entry ? entry.identity : null
}

/**
 * Is this device revoked?
 *
 * pgv3's twin (isIdentityRevoked) exists because revocation lived in a SEPARATE view index — the
 * identity record's own flag always read false, so testing it silently missed every revocation. Here
 * the authoritative source is hpp's device registry, injected as `isDeviceRevoked(subKey)`.
 *
 * FAILURE POLICY is explicit, because the right answer differs by caller. pgv3 fails OPEN so that a
 * transient registry read cannot deny every caller at once, and that is right for reads. It is NOT
 * right for a write: there, an unreachable registry must not wave through a device that may have been
 * revoked. Hence `failOpen`, defaulting to pgv3's behaviour and flipped by the write guards.
 */
export const UNKNOWN = 'unknown'

export async function isRevoked ({ subKey, isDeviceRevoked, failOpen = true } = {}) {
  if (!subKey || typeof isDeviceRevoked !== 'function') return false
  try {
    return !!(await isDeviceRevoked(subKey))
  } catch {
    // ⛔ A CHECK THAT COULD NOT RUN IS NOT A POSITIVE REVOCATION. This returned `true` on the write
    // path, so a read-only instance — one with no hpp to ask — told a signed-in user "this device has
    // been revoked". Their device was fine; nobody could check. Reported live on favela.7rnx.net.
    // Fail-closed still DENIES; it must simply not assert something untrue about the user's device.
    return failOpen ? false : UNKNOWN
  }
}

/**
 * Require an authenticated, non-revoked identity. Does NOT imply any right to write.
 * For self-scoped reads (your own devices, your own bookmarks) this is the correct guard.
 */
export async function requireIdentity (ctx, opts = {}) {
  const identity = ctx && ctx.identity
  if (!identity || !identity.did) throw new AuthError('authentication required')
  const verdict = await isRevoked({ subKey: identity.subKey, ...opts })
  if (verdict === UNKNOWN) throw new AuthError('device status could not be verified', 403)
  if (verdict) throw new AuthError('this device has been revoked', 403)
}

/**
 * Require a member — favela's analog of pgv3's requireWriter.
 *
 * `isMember(did)` is injected: today nothing supplies it, and that is why this DENIES without one.
 * A guard whose unconfigured state is "allow" is not a guard; the whole reason this exists is that a
 * valid session proves identity and nothing else.
 *
 * Order matters: authentication → revocation → membership. Revocation outranks membership so that a
 * revoked device belonging to a member is still refused, and a membership lookup that THROWS denies
 * rather than admits (an unreachable room is not consent).
 */
export async function requireMember (ctx, opts = {}) {
  await requireIdentity(ctx, { ...opts, failOpen: opts.failOpen === undefined ? false : opts.failOpen })
  const { isMember } = opts
  if (typeof isMember !== 'function') {
    throw new AuthError('membership policy not configured', 403)
  }
  let member = false
  try {
    member = !!(await isMember(ctx.identity.did))
  } catch {
    throw new AuthError('membership could not be verified', 403)
  }
  if (!member) throw new AuthError('membership required', 403)
}

/**
 * Require that the caller OWNS the repo being written to.
 *
 * ⛔ THE HOLE THIS CLOSES. `Writer` connects to ONE hpp control socket — the primary DID's — so
 * `writer.post()` authors as THAT DID regardless of who is signed in. Meanwhile `auth.login()` admits
 * any DID that proves a delegation from its own #atproto key, and unknown DIDs are registered on
 * sight. Composed, those two facts mean any atproto account could sign in here and post as wj62.
 * A session proves WHO YOU ARE; it must never be mistaken for a right to write as SOMEONE ELSE.
 *
 * `repoDid` is the DID the writer is actually bound to — ask the hpp (`writer.state().did`), never
 * assume. An unknown target DENIES: not knowing whose history you are about to append to is the
 * worst possible moment to guess.
 *
 * This does not YET permit a co-owner to write to a community DID — that needs per-DID socket routing
 * (hpp already exposes a socket per DID). It is the safety property; routing is additive on top.
 */
export async function requireRepoOwner (ctx, opts = {}) {
  await requireIdentity(ctx, { ...opts, failOpen: opts.failOpen === undefined ? false : opts.failOpen })
  const repoDid = opts.repoDid
  if (!repoDid) throw new AuthError('cannot determine which repo this node writes to', 403)
  // Exact match. A DID is an opaque, case-sensitive identifier; near-misses are not owners.
  if (ctx.identity.did !== repoDid) {
    throw new AuthError('you may only write to your own repo', 403)
  }
}

/**
 * Non-throwing probe: may this caller write? For SSR — decide whether to RENDER the composer at all,
 * rather than rendering it and letting the POST fail. Mirrors pgv3's isAdmin(). Never throws.
 */
export async function mayWrite (ctx, opts = {}) {
  try {
    await requireMember(ctx, opts)
    return true
  } catch {
    return false
  }
}

export default { UNKNOWN, extractToken, extractIdentity, requireIdentity, requireMember, requireRepoOwner, mayWrite, isRevoked, AuthError, COOKIE_NAME }
// favela-web CLI subcommands — pairing + device management from the `favela-web` launcher, so a user
// runs a clean verb instead of the raw `bare bin/favela-pair.js` incantation:
//
//   favela-web pair [--label "my laptop"]      mint a BROWSER pairing invite (a delegation), print the link
//   favela-web invite <did>                     mint a DEVICE invite (co-owner bundle) — for a phone/node
//   favela-web devices                          list the DID's delegated browser sub-keys (+ revoked)
//   favela-web revoke <sub-key|prefix> [--restore]   revoke (or restore) a device — kills its sign-in
//   favela-web fronts [<did>] [--json]          which co-owner's firehose each DID follows, and why
//   favela-web lens [--json]                    lens-import config + live cache/breaker counters
//   favela-web status                           both of the above, plus the /status URL
//   favela-web conformance [--offline] [--json] what we hold vs what bsky indexes (READ-ONLY)
//   favela-web heal [--json]                    list every diagnostic and repair this node has
//   favela-web repair-strongrefs [--write]      add the missing cid to invalid strongRefs (DRY RUN default)
//   favela-web repair-bytes [<did>] [--limit N] [--write]
//                                               fetch + verify bytes we indexed but never stored (DRY RUN)
//   favela-web head [<did>] [--json]            our rev vs the authoritative repo head
//   favela-web diff [<did>] [--json]            exactly what we and the authority disagree on
//   favela-web backfill [<did>] [--limit N] [--write]
//                                               pull the authoritative repo and fill what is missing (DRY RUN)
//   favela-web collections [--json]             every collection by class: tracked / ignored / UNKNOWN
//
// All three talk to the LOCAL hpp control surface over the DEDICATED pairing writer identity (277037…,
// which is in the hpp writers allowlist) — NOT the server's poster (2c5499…) — so they never collide on
// the DHT with a running favela-web daemon. Dispatched from bin/favela-web.js BEFORE the server boots.
import process from 'bare-process'
import { join } from 'bare-path'
import { OverlayRepoStore } from 'atproto-store/lib/overlay-repo-store.js'
import { Writer } from './writer.js'
import { createPairInvite } from './pairing.js'
import { roomKey16 } from './blob-serve.js'
import { repairStrongRefs } from './repair-strongrefs.js'
import { checkConformance } from './conformance.js'

// ⛔ NO DEFAULT. This fell back to the author's LIVE wj62 hpp control key, so running this on a box
// with no local socket dialled production over the DHT — the accident lib/writer.js:56-62 already
// records ('a post landed in wj62 from a test run'). Unset now means unreachable, which is correct.
const CONTROL = (process.env.FAVELA_CONTROL_KEY || '').trim() || null
const CLI_SEED = process.env.FAVELA_PAIR_SEED || 'favela-pair-tabertron-2026-07-16' // dedicated, allowlisted (277037…)
const EXTERNAL = (process.env.FAVELA_EXTERNAL_URL || 'http://localhost:4041').replace(/\/$/, '')

export const CLI_COMMANDS = ['pair', 'invite', 'devices', 'revoke', 'fronts', 'lens', 'status', 'conformance', 'heal', 'head', 'diff', 'backfill', 'collections', 'repair-strongrefs', 'repair-bytes']

// `fronts` / `lens` / `status` read the RUNNING daemon over its local HTTP surface rather than building a
// router of their own. That is not a shortcut: the state worth inspecting (which front was chosen, what
// each offers, live cache and breaker counters) exists only inside the serving process. A second router
// would answer a different question — what a fresh client would pick right now — which is precisely NOT
// what you want when diagnosing a node that has been wrong for two days.
const LOCAL = (args) => flagVal(args, '--url') ||
  process.env.FAVELA_LOCAL_URL ||
  ('http://127.0.0.1:' + (process.env.FAVELA_PORT || '4041'))

async function getJson (args, path) {
  const base = LOCAL(args).replace(/\/$/, '')
  if (typeof globalThis.fetch !== 'function') await import('bare-fetch/global')
  try {
    const res = await fetch(base + path, { headers: { accept: 'application/json' } })
    if (!res.ok) { console.error('\n  ✗ ' + base + path + ' → HTTP ' + res.status + '\n'); process.exit(1) }
    return await res.json()
  } catch (e) {
    console.error('\n  ✗ cannot reach favela-web at ' + base + ' — is it running?  (pgh app status favela-web)')
    console.error('    ' + (e && e.message) + '\n')
    process.exit(1)
  }
}

async function frontsCmd (args) {
  const did = args.find((a) => a.startsWith('did:')) || null
  const d = await getJson(args, '/api/fronts' + (did ? '?did=' + encodeURIComponent(did) : ''))
  if (args.includes('--json')) { console.log(JSON.stringify(d, null, 2)); return }
  console.log('')
  for (const e of d.dids || []) {
    // The alarm condition, stated once per DID rather than left for the reader to compute from the table.
    const alarm = e.frontCount > 1 && (e.onHighestRev === false || (e.behindBy || 0) > 0)
    console.log('  ' + e.did)
    console.log('    following ' + (e.chosen || 'none') + '  ·  ' + e.frontCount + ' front(s)' +
      '  ·  highest-rev: ' + (e.onHighestRev ? 'yes' : 'no') +
      (e.behindBy ? '  ·  BEHIND BY ' + e.behindBy + ' frames' : ''))
    for (const f of e.fronts || []) {
      console.log('      ' + (f.chosen ? '→ ' : '  ') + (f.short || '') +
        '  rev=' + (f.rev || '—') +
        '  firehose=' + (f.firehoseLength == null ? '—' : f.firehoseLength) +
        '  live=' + (f.live ? 'y' : 'n') +
        '  verified=' + (f.verified ? 'y' : 'n'))
    }
    if (alarm) console.log('    ⚠ following a line that is not the freshest — the shape of a frozen index.')
    console.log('')
  }
  if (!(d.dids || []).length) console.log('  (no DIDs)\n')
}

async function lensCmd (args) {
  const d = await getJson(args, '/api/lens')
  if (args.includes('--json')) { console.log(JSON.stringify(d, null, 2)); return }
  console.log('\n  lens import: ' + (d.enabled ? 'ON' : 'OFF'))
  for (const l of d.lenses || []) console.log('    ' + l.name + ' → ' + l.base + (l.proxy ? '  (proxy ' + l.proxy + ')' : ''))
  for (const e of d.errors || []) console.log('    ⚠ ' + e)
  const s = d.stats
  if (s) {
    console.log('    hits=' + s.hits + ' misses=' + s.misses + ' fetches=' + s.fetches +
      ' failures=' + s.failures + ' timeouts=' + s.timeouts + ' coalesced=' + s.coalesced +
      ' short-circuited=' + s.shortCircuited + ' cache=' + s.cacheSize)
    if ((s.open || []).length) console.log('    ⚠ breaker OPEN for: ' + s.open.join(', '))
  }
  console.log('')
}

async function statusCmd (args) {
  await frontsCmd(args)
  await lensCmd(args)
  console.log('  web: ' + LOCAL(args).replace(/\/$/, '') + '/status\n')
}

const flagVal = (args, name) => { const i = args.indexOf(name); return i >= 0 ? args[i + 1] : null }
const hasFlag = (args, name) => args.includes(name)
const ymd = (ms) => { try { return new Date(ms).toISOString().slice(0, 10) } catch { return '?' } }

async function connect () {
  const w = new Writer({ controlKey: CONTROL, writerSeed: CLI_SEED })
  if (!(await w.ready({ timeout: 30000 }))) {
    console.error('\n  ✗ no hpp connection — is the local hpp running?  (pgh app status hyper-proto-peer)\n')
    try { await w.close() } catch {}
    process.exit(1)
  }
  return w
}

async function pairCmd (args) {
  const label = flagVal(args, '--label')
  const w = await connect()
  const source = await createPairInvite({ onSubkey: (sk) => w.delegate(sk, { label }) })
  console.log('\n  Pair a browser to this DID — open this on the device you want to sign in:\n')
  console.log('    ' + EXTERNAL + '/login#pair=' + source.inviteHex + '\n')
  console.log('  …or paste this invite into the login box:\n')
  console.log('    ' + source.inviteHex + '\n')
  console.log('  Waiting for your browser to pair (Ctrl-C to cancel)…\n')
  try {
    const r = await source.waitForPeer()
    console.log('  ✓ paired — signed in as ' + r.delegation.did + (label ? ' ("' + label + '")' : '') + '\n')
  } catch (e) { console.error('  ✗ ' + e.message + '\n') }
  try { await source.close() } catch {}
  try { await w.close() } catch {}
}

// ── invite — mint a DEVICE invite, not a browser one ────────────────────────────────────────────────
//
// ⛔ THIS IS NOT `pair`. `pair` delegates a BROWSER sub-key: the browser holds no key and every signature
// is still made by the hpp. A phone running favela-android is a NODE — it needs the co-owner bundle
// (shared signing key + chained attestation), because the room's secrets are DERIVED from that key and
// it cannot even open the DID's StateBase without it.
//
// The two are easy to confuse and the confusion is SILENT: paste a `pair` invite into the phone and
// delegate() rejects its 64-hex keet device key (it wants a 66-hex secp256k1 sub-key), the source never
// confirms, and the phone waits out its five-minute timeout with no error. Hence a separate verb.
//
// Runs against the LOCAL config, like the record-store commands above — the bundle carries a secret, so
// it is minted by the machine that already holds it.
async function inviteCmd (args) {
  const did = args.find((a) => a.startsWith('did:'))
  if (!did) { console.error('\n  usage: favela-web invite <did>   (the DID this machine already hosts)\n'); process.exit(1) }
  const { mintAdoptInvite } = await import('hyper-proto-peer/lib/adopt.js')
  const configFile = flagVal(args, '--config') || null
  let src
  try {
    // Approval IS the invocation: coownerInvite mutates the roster and the bundle carries the signing
    // key, so mintAdoptInvite refuses to fire without approve(). Running this, on the machine that holds
    // the DID, is that approval — same posture as `pair` auto-delegating.
    src = await mintAdoptInvite({ did, approve: () => true, configFile })
  } catch (e) { console.error('\n  ✗ ' + e.message + '\n'); process.exit(1) }

  console.log('\n  Device invite for ' + did + ' — paste this into the joining device:\n')
  console.log('    ' + src.inviteHex + '\n')
  console.log('  ⚠ It carries the SHARED SIGNING KEY. Single-use, and whoever reads it first can post as you.')
  console.log('  Keep this command running — it holds the tunnel open.\n')
  try {
    const r = await src.waitForPeer()
    if (r) console.log('  ✓ joined — device ' + String(r.devicePublicKey).slice(0, 16) + '…  roster now ' + (r.members ? r.members.length : '?') + ' device(s)\n')
    else console.log('  ✗ refused — nothing was written\n')
  } catch (e) { console.error('  ✗ ' + e.message + '\n') }
  try { await src.close() } catch {}
  console.log('  Restart this hpp and the joiner so both pick up the new roster.\n')
}

async function devicesCmd () {
  const w = await connect()
  const devices = await w.listDevices()
  if (!devices.length) console.log('\n  no browsers paired yet — run `favela-web pair`\n')
  else {
    console.log('\n  Delegated browser devices for this DID:\n')
    for (const d of devices) {
      console.log('    ' + d.subKey.slice(0, 20) + '…  ' + (d.revoked ? 'REVOKED' : 'active ') + '  ' + ymd(d.addedAt) + '  ' + (d.label || ''))
    }
    console.log('\n  revoke one with:  favela-web revoke <sub-key-prefix>\n')
  }
  try { await w.close() } catch {}
}

async function revokeCmd (args) {
  const restore = hasFlag(args, '--restore')
  const key = args.find((a) => !a.startsWith('--'))
  if (!key) { console.error('\n  usage: favela-web revoke <sub-key-or-prefix> [--restore]\n'); process.exit(1) }
  const w = await connect()
  const devices = await w.listDevices()
  const match = devices.find((d) => d.subKey === key.toLowerCase() || d.subKey.startsWith(key.toLowerCase()))
  if (!match) console.error('  (no match in the registry for "' + key + '" — sending the raw key)')
  const target = match ? match.subKey : key.toLowerCase()
  await w.revokeDevice(target, { restore })
  console.log('\n  ✓ ' + (restore ? 'restored' : 'revoked') + ' ' + target.slice(0, 20) + '…\n')
  try { await w.close() } catch {}
}

// ── repair + conformance ─────────────────────────────────────────────────────────────────────────
//
// WHY THESE ARE HERE AT ALL. `lib/repair-strongrefs.js` (0.3.3) and `lib/conformance.js` (0.3.4) both
// shipped as libraries with tests and NO WAY TO RUN THEM — the only caller was a test file. The repair
// module's own header says it: "A defect whose repair is un-runnable is not fixed." It then shipped
// un-runnable. #23 lesson 7 is the same sentence from the other direction. This closes both.
//
// The record SOURCE is the shared content-addressed byte store — the same `OverlayRepoStore` +
// `roomKey16(did)` construction bin/favela-web.js:217-220 uses, so the CLI reads the exact bytes hpp
// wrote rather than a re-encode. Re-encoding is what made a byte-exactness guard verify a fetch against
// itself and miss the divergence on disk (#23 root cause 3).
// ⚠ THE DAEMON'S ENV IS NOT THE CLI'S ENV. pgh sets ATPROTO_OVERLAY_ROOT from the install record's
// defaults.env when the SUPERVISOR spawns the daemon; a `favela-web <cmd>` typed at a shell inherits none
// of it. The first cut of this fell back to a favela-local path that does not exist, opened an empty
// store, and reported "checked 0 · 0 findings" — a health report produced by reading the wrong directory.
// A conformance tool that answers "all clean" when it read nothing is worse than absent, so the default
// now points at hpp's real record dir and an empty read is a LOUD failure (assertRead below).
const HPP_RECORDS = process.env.HOME + '/.config/hyper-proto-peer/data/atproto-repo'
const OVERLAY_ROOT = () => process.env.ATPROTO_OVERLAY_ROOT ||
  (process.env.FAVELA_STORE_ROOT ? join(process.env.FAVELA_STORE_ROOT, 'atproto-repo') : HPP_RECORDS)

// A zero read is nearly always the wrong root, not an empty repo. Say which path was read and stop, rather
// than returning a clean bill of health for a directory that may not even exist.
function assertRead (n, did) {
  if (n > 0) return
  console.error('\n  ✗ read 0 records for ' + did + '\n    root: ' + OVERLAY_ROOT() +
    '\n    That is almost certainly the wrong directory rather than an empty repo.' +
    '\n    Set ATPROTO_OVERLAY_ROOT to hpp\'s record dir and re-run:' +
    '\n      ATPROTO_OVERLAY_ROOT=' + HPP_RECORDS + ' favela-web <command>\n')
  process.exit(1)
}

function recordStoreOpener () {
  const root = OVERLAY_ROOT()
  const cache = new Map()
  return async (did) => {
    if (!cache.has(did)) cache.set(did, await new OverlayRepoStore(join(root, roomKey16(did)), { did }).ready())
    return cache.get(did)
  }
}

// `list()` is an async generator; both consumers want an array per collection.
async function collectRecords (store, collection) {
  const out = []
  try { for await (const r of store.list(collection)) out.push(r) } catch { /* absent collection dir */ }
  return out
}

// The DID to operate on: --did wins, else whatever the local hpp is primary for.
async function resolveDid (args, w) {
  const explicit = flagVal(args, '--did')
  if (explicit) return explicit
  try { const st = await w.state(); if (st && st.did) return st.did } catch { /* fall through */ }
  console.error('\n  ✗ could not determine the DID — pass --did did:plc:…\n')
  process.exit(1)
}

async function conformanceCmd (args) {
  const offline = hasFlag(args, '--offline')
  const w = await connect()
  const did = await resolveDid(args, w)
  const getStore = recordStoreOpener()
  let store
  try { store = await getStore(did) } catch (e) {
    console.error('\n  ✗ cannot open the record store at ' + OVERLAY_ROOT() + '\n    ' + e.message + '\n')
    try { await w.close() } catch {}
    process.exit(1)
  }
  if (!offline && typeof globalThis.fetch !== 'function') await import('bare-fetch/global')
  const r = await checkConformance({
    did,
    listRecords: (c) => collectRecords(store, c),
    // No doFetch => the offline STRUCTURAL layer only. That layer is deterministic and needs no network,
    // which is what makes it CI-able (#23 short-term item).
    doFetch: offline ? null : globalThis.fetch
  })
  if (hasFlag(args, '--json')) { console.log(JSON.stringify(r, null, 2)); try { await w.close() } catch {}; return }
  const s = r.summary || {}
  assertRead(s.checked || 0, did)
  console.log('\n  conformance · ' + did + (offline ? '  (structural only)' : ''))
  console.log('    checked ' + (s.checked != null ? s.checked : '?') + '  ·  structural findings ' +
    r.structural.length + '  ·  network findings ' + r.network.length + '\n')
  for (const f of r.structural) console.log('    ✗ STRUCTURAL  ' + f.collection + '/' + f.rkey + '  ' + f.code + (f.field ? ' [' + f.field + ']' : ''))
  for (const f of r.network) console.log('    ' + (f.state === 'missing' ? '✗ MISSING   ' : '· pending   ') + '  ' + f.collection + '/' + f.rkey)
  // An absence is a FINDING, not a verdict — the module is emphatic about this and the CLI must not
  // upgrade it to one. bsky's AppView is eventually consistent and its relay is non-archival.
  if (r.network.length) console.log('\n  note: `pending` is inside the grace window; `missing` is past it and worth investigating — neither is proof of corruption.')
  if (!r.structural.length && !r.network.length) console.log('    ✓ nothing to report')
  console.log('')
  try { await w.close() } catch {}
}

async function repairStrongRefsCmd (args) {
  const write = hasFlag(args, '--write')
  const w = await connect()
  const did = await resolveDid(args, w)
  const getStore = recordStoreOpener()
  let store
  try { store = await getStore(did) } catch (e) {
    console.error('\n  ✗ cannot open the record store at ' + OVERLAY_ROOT() + '\n    ' + e.message + '\n')
    try { await w.close() } catch {}
    process.exit(1)
  }
  const r = await repairStrongRefs({
    listRecords: (c) => collectRecords(store, c),
    getRecordStore: getStore,
    // ⛔ WRITES GO THROUGH hpp, NEVER store.put(). hpp is the AUTHORITY for these bytes: it hashes what
    // it writes and commits that hash to the autobase. A direct store.put() here would make this CLI a
    // SECOND WRITER into hpp's canonical record store — which is verbatim the 2026-07-31 clobber that
    // cost two records permanently (#23 root cause 2). putRecord goes over the hpp control surface, so
    // hpp does the encode, the hash and the pointer.
    applyWrite: (op) => w.putRecord(op.collection, op.rkey, op.record, { action: op.action || 'update' }),
    write
  })
  assertRead(r.checked || 0, did)
  console.log('\n  repair-strongrefs · ' + did + (write ? '' : '   (DRY RUN — pass --write to apply)'))
  console.log('    checked ' + r.checked + '  ·  broken ' + r.broken + '  ·  ' +
    (write ? 'repaired ' + r.repaired : 'would repair ' + r.entries.filter((e) => e.state === 'would-repair').length) +
    '  ·  unresolvable ' + r.unresolvable + '\n')
  for (const e of r.entries) {
    const mark = e.state === 'unresolvable' ? '✗ UNRESOLVABLE' : (e.state === 'repaired' ? '✓ repaired    ' : '· would repair')
    console.log('    ' + mark + '  ' + e.collection + '/' + e.rkey)
    for (const u of e.uris || []) console.log('        → ' + u)
  }
  if (!r.entries.length) console.log('    ✓ every strongRef already carries a cid')
  // Unresolvable is not a failure of the repair — it is the guard refusing to invent a cid. Say so, or
  // the next operator reads it as a bug and goes looking for one.
  if (r.unresolvable) console.log('\n  note: unresolvable = the subject bytes are not held here, so no cid can be proven.\n        The record is left INVALID rather than rewritten with a guessed cid.')
  console.log('')
  try { await w.close() } catch {}
}

// ---- healing ---------------------------------------------------------------------------------------
//
// Every repair in this app is registered HERE, so `favela-web heal` can list them and no healing verb
// can exist that an operator has to read the source to discover. That was the actual failure mode
// behind the 2026-08-06 audit: the capability to notice a byte gap existed, the capability to close it
// did not, and nothing in the CLI said so.
//
// The shared contract for every entry: READ-ONLY by default, `--write` to apply, and a report that
// distinguishes "nothing to do" from "could not". Diagnostics are listed too, because in practice you
// run them first and the split between "look" and "fix" is not where an operator's question sits.
export const HEALERS = [
  { name: 'backfill', kind: 'repair', writes: true, blurb: 'pull the authoritative repo (getRepo) and index/store whatever we are missing' },
  { name: 'repair-bytes', kind: 'repair', writes: true, blurb: 'fetch + verify record bytes this node indexed but never stored' },
  { name: 'repair-strongrefs', kind: 'repair', writes: true, blurb: 'add the missing cid to invalid strongRefs (writes go THROUGH hpp)' },
  { name: 'head', kind: 'check', writes: false, blurb: 'our rev vs the authoritative repo head — the cheap staleness check' },
  { name: 'diff', kind: 'check', writes: false, blurb: 'exactly what we and the authoritative repo disagree on' },
  { name: 'collections', kind: 'check', writes: false, blurb: 'every collection by class — tracked / ignored-by-policy / UNKNOWN (what we drop)' },
  { name: 'conformance', kind: 'check', writes: false, blurb: 'what we hold vs what bsky indexes (the OUTBOUND question)' },
  { name: 'fronts', kind: 'check', writes: false, blurb: "which co-owner's firehose each DID follows, and why" },
  { name: 'lens', kind: 'check', writes: false, blurb: 'lens-import config + live cache/breaker counters' }
]

// repair-bytes runs INSIDE the daemon (it holds the index store's lock) over the UDS control surface —
// never HTTP, because this daemon binds 0.0.0.0 and this writes.
async function repairBytesCmd (args) {
  const write = hasFlag(args, '--write')
  const did = args.find((a) => a.startsWith('did:')) || null
  const limit = Number(flagVal(args, '--limit')) || 0
  // ⛔ The default must be the daemon's REAL socket, not a relative `data/svc.sock`. The daemon gets
  // FAVELA_STORE_ROOT from its install record when the SUPERVISOR spawns it; a CLI call inherits none of
  // that, so a relative default resolves against the operator's cwd and never exists — the same class of
  // silent-wrong-path bug as the record root above, and it cost this command its first invocation.
  const sock = flagVal(args, '--sock') || process.env.FAVELA_SOCK ||
    (process.env.FAVELA_STORE_ROOT
      ? process.env.FAVELA_STORE_ROOT + '/svc.sock'
      : join(process.env.HOME || '', '.config/favela-web/data/svc.sock'))

  const { Client } = await import('hyper-svc')
  let client
  try {
    client = await Client.connectUds(sock)
  } catch (e) {
    console.error('\n  ✗ cannot reach the favela-web control surface at ' + sock)
    console.error('    ' + ((e && e.message) || e) + '\n    is it running?  (pgh app status favela-web)\n')
    process.exit(1)
  }
  let r
  try {
    // `call`, not `request` — hyper-svc's Client exposes call(op, params); see hpp's lib/diag.js, which
    // drives the same kind of control socket.
    r = await client.call('repair-bytes', { did, write, limit })
  } catch (e) {
    console.error('\n  ✗ repair-bytes failed: ' + ((e && e.message) || e) + '\n')
    process.exit(1)
  } finally {
    try { await client.close() } catch {}
  }

  if (args.includes('--json')) { console.log(JSON.stringify(r, null, 2)); return }
  console.log('\n  repair-bytes' + (write ? '' : '   (DRY RUN — pass --write to apply)'))
  console.log('    scanned ' + r.scanned + '  ·  have bytes ' + r.present + '  ·  MISSING ' + r.missing +
    (write ? '  ·  written ' + r.written : ''))
  if (write && (r.unfetchable || r.unverified || r.reencodeRefused || r.storeErrors)) {
    console.log('    unfetchable ' + r.unfetchable + '  ·  unverified ' + r.unverified +
      '  ·  re-encode refused ' + r.reencodeRefused + '  ·  store errors ' + r.storeErrors)
  }
  for (const p of r.samples || []) console.log('    · ' + p.collection + '/' + p.rkey)
  if (r.samples && r.missing > r.samples.length) console.log('    … and ' + (r.missing - r.samples.length) + ' more')
  // Say plainly which DIDs were NOT touched and why — an empty result on a node that hosts everything
  // reads like a broken command otherwise.
  if (r.skippedHostedLocally && r.skippedHostedLocally.length) {
    console.log('\n  not repaired (this node HOSTS them — hpp is the authority for their bytes):')
    for (const d of r.skippedHostedLocally) console.log('    · ' + d)
  }
  if (!r.missing) console.log('\n  ✓ every indexed record has its bytes')
  else if (!write) console.log('\n  run with --write to fetch and verify them from the DID\'s peers')
  if (write && r.unfetchable) {
    console.log('\n  note: unfetchable = no peer could produce those bytes (deleted upstream, or lost).')
    console.log('        They are reported rather than invented — nothing is written that cannot be proven.')
  }
  console.log('')
}

// Shared UDS call for the convergence verbs — same socket, same failure message, one place to fix.
async function daemonCall (args, op, params) {
  const sock = flagVal(args, '--sock') || process.env.FAVELA_SOCK ||
    (process.env.FAVELA_STORE_ROOT
      ? process.env.FAVELA_STORE_ROOT + '/svc.sock'
      : join(process.env.HOME || '', '.config/favela-web/data/svc.sock'))
  const { Client } = await import('hyper-svc')
  let client
  try {
    client = await Client.connectUds(sock)
  } catch (e) {
    console.error('\n  ✗ cannot reach the favela-web control surface at ' + sock)
    console.error('    ' + ((e && e.message) || e) + '\n    is it running?  (pgh app status favela-web)\n')
    process.exit(1)
  }
  try {
    return await client.call(op, params)
  } catch (e) {
    console.error('\n  ✗ ' + op + ' failed: ' + ((e && e.message) || e) + '\n')
    process.exit(1)
  } finally {
    try { await client.close() } catch {}
  }
}

const skippedNote = (r) => {
  if (!r.skippedHostedLocally || !r.skippedHostedLocally.length) return
  console.log('\n  not checked (this node HOSTS them — hpp is the authority for their repo):')
  for (const d of r.skippedHostedLocally) console.log('    · ' + d)
}

// head — the cheap staleness question. One call per DID, no CAR fetch.
async function headCmd (args) {
  const did = args.find((a) => a.startsWith('did:')) || null
  const r = await daemonCall(args, 'repo-head', { did })
  if (args.includes('--json')) { console.log(JSON.stringify(r, null, 2)); return }
  console.log('')
  for (const h of r.heads || []) {
    if (h.unreachable) { console.log('  ✗ ' + h.did + '  — ' + h.unreachable); continue }
    const mark = h.behind === true ? '⚠ BEHIND' : (h.behind === false ? '✓ current' : '? unknown')
    console.log('  ' + mark + '  ' + h.did)
    console.log('      authority rev ' + (h.remoteRev || '—') + '   ours ' + (h.localRev || 'NEVER FOLDED'))
    if (h.active === false) console.log('      ⚠ repo is not active (status: ' + (h.status || '?') + ')')
  }
  if (!(r.heads || []).length) console.log('  (no foreign DIDs to check)')
  skippedNote(r)
  console.log('\n  behind?  run `favela-web diff` to see exactly what differs.\n')
}

// diff — the question nothing answered before: what exactly do we and the authority disagree on.
async function diffCmd (args) {
  const did = args.find((a) => a.startsWith('did:')) || null
  const r = await daemonCall(args, 'repo-diff', { did })
  if (args.includes('--json')) { console.log(JSON.stringify(r, null, 2)); return }
  console.log('')
  for (const d of r.dids || []) {
    if (d.unreachable) { console.log('  ✗ ' + d.did + ' — ' + d.unreachable); continue }
    if (d.refused) { console.log('  ⛔ ' + d.did + ' — repo REFUSED: ' + d.refused + ' (nothing was believed)'); continue }
    console.log('  ' + (d.inSync ? '✓ in sync' : '⚠ DRIFTED') + '  ' + d.did + '   rev ' + (d.remoteRev || '—'))
    console.log('      authority holds ' + d.remoteRecords + ' record(s)')
    for (const [c, n] of Object.entries(d.perCollection || {})) {
      const mark = n.authority === n.indexed ? ' ' : '⚠'
      console.log('      ' + mark + ' ' + c.padEnd(28) + ' authority ' + n.authority + '  ·  indexed ' + n.indexed)
    }
    if (d.ignored) {
      const by = Object.entries(d.ignoredByCollection || {}).map(([c, n]) => c + ' ' + n).join(', ')
      console.log('      ignored by policy: ' + d.ignored + '  [' + by + ']   (see spec/convergence.md §2.1)')
    }
    // UNKNOWN is the one that should make someone look: a lexicon nobody has classified.
    if (d.unknown) {
      const by = Object.entries(d.unknownByCollection || {}).map(([c, n]) => c + ' ' + n).join(', ')
      console.log('      ⚠ UNKNOWN collection(s): ' + d.unknown + '  [' + by + ']')
      console.log('        Not tracked and not on the ignore list — classify it in lib/hosted-dids.js.')
      console.log('        `favela-web collections` shows what has already ARRIVED unclassified, across every DID.')
    }
    const show = (label, list) => {
      if (!list || !list.length) return
      console.log('      ' + label + ': ' + list.length)
      for (const x of list.slice(0, 10)) console.log('        · ' + x.collection + '/' + x.rkey)
      if (list.length > 10) console.log('        … and ' + (list.length - 10) + ' more')
    }
    if (d.blobs) {
      const b = d.blobs
      const mark = b.missing.length ? '⚠' : ' '
      console.log('      ' + mark + ' blobs (referenced)'.padEnd(30) + ' authority ' + b.referenced + '  ·  here ' + b.present)
      for (const m of b.missing.slice(0, 10)) {
        const r0 = (m.refs && m.refs[0]) || {}
        console.log('        · MISSING ' + m.cid + (r0.collection ? '  ← ' + r0.collection + '/' + r0.rkey + (r0.where ? ' (' + r0.where + ')' : '') : ''))
      }
      if (b.missing.length > 10) console.log('        … and ' + (b.missing.length - 10) + ' more')
      // Say what was NOT checked. An unqualified blob count would read as "blobs are fine".
      if (b.orphansChecked) {
        console.log('        inventory ' + b.inventory + '  ·  orphans ' + b.orphans.length +
          (b.orphans.length ? '  (held by the authority, referenced by no record)' : ''))
        for (const o of b.orphans.slice(0, 5)) console.log('          · ORPHAN ' + o.cid)
        if (b.orphans.length > 5) console.log('          … and ' + (b.orphans.length - 5) + ' more')
      } else {
        console.log('        note: orphan blobs NOT checked — the authority did not answer listBlobs (spec §6)')
      }
    }
    show('MISSING from our index', d.missingFromIndex)
    show('indexed but NO BYTES', d.indexedWithoutBytes)
    show('we hold, repo does not', d.extraLocal)
  }
  skippedNote(r)
  const drifted = (r.dids || []).some((d) => d.inSync === false)
  if (drifted) console.log('\n  run `favela-web backfill --write` to pull what is missing.')
  console.log('')
}

// backfill — pull it. getRepo, verified, then index what we never indexed and fill byte gaps.
async function backfillCmd (args) {
  const write = hasFlag(args, '--write')
  const did = args.find((a) => a.startsWith('did:')) || null
  const limit = Number(flagVal(args, '--limit')) || 0
  // `--since` is deliberately NOT offered. It was, and it worked only because the membrane accepted and
  // ignored the parameter; now that the membrane honours it (0.9.45) a diff CAR is unusable here — see
  // lib/repo-sync.js. Backfill always pulls the complete repo.
  const r = await daemonCall(args, 'repo-backfill', { did, write, limit })
  if (args.includes('--json')) { console.log(JSON.stringify(r, null, 2)); return }
  console.log('\n  backfill' + (write ? '' : '   (DRY RUN — pass --write to apply)'))
  for (const d of r.dids || []) {
    if (d.unreachable) { console.log('  ✗ ' + d.did + ' — ' + d.unreachable); continue }
    if (d.refused) { console.log('  ⛔ ' + d.did + ' — repo REFUSED: ' + d.refused); continue }
    const a = d.applied || {}
    console.log('    ' + d.did)
    // localIndexed was removed in 0.3.43 when diff went per-collection; sum the per-collection view
    // rather than printing `undefined` (which is what shipped, and reads as a bug in the data).
    const indexedHere = Object.values(d.perCollection || {}).reduce((a, n) => a + (n.indexed || 0), 0)
    console.log('      authority ' + d.remoteRecords + '  ·  indexed here ' + indexedHere +
      '  ·  missing ' + (d.missingFromIndex || []).length + '  ·  byteless ' + (d.indexedWithoutBytes || []).length)
    if (write) console.log('      → indexed ' + (a.indexed || 0) + '  ·  bytes written ' + (a.bytesWritten || 0) +
      (a.reencodeRefused ? '  ·  re-encode refused ' + a.reencodeRefused : '') +
      (a.errors ? '  ·  errors ' + a.errors : ''))
    if (d.blobs && d.blobs.missing.length) {
      const ba = d.blobsApplied
      console.log('      blobs missing ' + d.blobs.missing.length +
        (write && ba ? '  →  fetched ' + ba.fetched +
          (ba.unfetchable ? '  ·  unfetchable ' + ba.unfetchable : '') +
          (ba.hashMismatch ? '  ·  ⛔ hash mismatch ' + ba.hashMismatch : '') +
          (ba.errors ? '  ·  errors ' + ba.errors : '') : ''))
      if (write && ba && ba.hashMismatch) console.log('        ⛔ bytes that did not hash to their CID were REFUSED, not written.')
    }
    if (a.skippedExtraLocal) {
      console.log('      note: ' + a.skippedExtraLocal + ' record(s) we hold are NOT in the repo — reported, never deleted.')
      console.log('            This cannot tell a stale local copy from one the authority has not published.')
    }
  }
  skippedNote(r)
  if (!write) console.log('\n  nothing was written. Re-run with --write to apply.')
  console.log('')
}

// collections — the classification ledger (org #33, spec §2). What arrives here, and what we decided
// about it. The three classes are printed even when a class is empty: the shape of the answer is the
// answer, and a bare list of unknowns would not say what the alternative was.
async function collectionsCmd (args) {
  const r = await daemonCall(args, 'collections', {})
  if (args.includes('--json')) { console.log(JSON.stringify(r, null, 2)); return }
  console.log('\n  collections · what this node ingests, and what it does not\n')
  console.log('  TRACKED — a view indexes it, so convergence can compare it record-for-record')
  for (const t of r.tracked || []) {
    console.log('    ' + t.collection.padEnd(30) + 'view ' + String(t.view).padEnd(10) + (t.bytes ? 'bytes stored here' : 'index only (no bytes)'))
  }
  console.log('\n  IGNORED BY POLICY — a decision on file (lib/hosted-dids.js). Not a gap.')
  for (const g of r.ignored || []) {
    console.log('    ' + g.collection + '   seen ' + g.seen + (g.lastSeen ? '  · last ' + g.lastSeen : '  · never seen here'))
    console.log('        ' + g.reason)
  }
  if (!(r.ignored || []).length) console.log('    (none)')
  console.log('')
  if ((r.unknown || []).length) {
    // The one class that should make someone look. Named loudly, with what to do about it — an operator
    // who learns a lexicon arrived and not what to do next has been told half of something.
    console.log('  ⚠ UNKNOWN — arrived here, no view indexes it, and nobody has classified it')
    for (const u of r.unknown) {
      console.log('    ' + u.collection + '   ' + u.count + ' op(s)  ·  first ' + u.firstSeen + '  ·  last ' + u.lastSeen)
      for (const d of u.dids || []) console.log('        from ' + d)
      if (u.sample) console.log('        e.g. ' + u.collection + '/' + u.sample.rkey)
    }
    console.log('\n  Classify each one: add a view for it, or add it to IGNORED_COLLECTIONS in')
    console.log('  lib/hosted-dids.js WITH A REASON (spec/convergence.md §2.1). "We don\'t use it" is not')
    console.log('  a reason; "no surface consumes it, and here is what does" is.\n')
  } else {
    console.log('  ✓ no UNKNOWN collections — everything that has arrived is either tracked or on the ignore list\n')
  }
  // Say what this did NOT check, per §3. The ledger is what ARRIVED; it cannot speak for a lexicon the
  // authority holds that we have simply never been online for.
  console.log('  note: this is what has ARRIVED here. A collection the authority holds that we have never')
  console.log('        received will not appear — `favela-web diff` asks that question instead.\n')
}

function healCmd (args) {
  if (args.includes('--json')) { console.log(JSON.stringify(HEALERS, null, 2)); return }
  console.log('\n  favela-web healing commands\n')
  for (const kind of ['check', 'repair']) {
    console.log('  ' + (kind === 'check' ? 'DIAGNOSE (read-only)' : 'REPAIR (dry run unless --write)'))
    for (const h of HEALERS.filter((x) => x.kind === kind)) {
      console.log('    favela-web ' + h.name.padEnd(20) + h.blurb)
    }
    console.log('')
  }
  console.log('  Every repair is READ-ONLY until you pass --write, and none of them overwrites bytes')
  console.log('  that are already present — hpp is the authority for the DIDs this node hosts.\n')
}

export async function runCli (argv) {
  const [cmd, ...rest] = argv
  if (cmd === 'pair') return pairCmd(rest)
  if (cmd === 'invite') return inviteCmd(rest)
  if (cmd === 'devices') return devicesCmd()
  if (cmd === 'revoke') return revokeCmd(rest)
  if (cmd === 'fronts') return frontsCmd(rest)
  if (cmd === 'lens') return lensCmd(rest)
  if (cmd === 'status') return statusCmd(rest)
  if (cmd === 'conformance') return conformanceCmd(rest)
  if (cmd === 'repair-strongrefs') return repairStrongRefsCmd(rest)
  if (cmd === 'repair-bytes') return repairBytesCmd(rest)
  if (cmd === 'head') return headCmd(rest)
  if (cmd === 'diff') return diffCmd(rest)
  if (cmd === 'backfill') return backfillCmd(rest)
  if (cmd === 'collections') return collectionsCmd(rest)
  if (cmd === 'heal') return healCmd(rest)
  console.error('\n  favela-web ' + cmd + ': unknown command\n  commands: ' + CLI_COMMANDS.join(' | ') + '\n')
  process.exit(1)
}
// favela community registry — resolves a VIEWER (signed-in DID) to their per-viewer author scope: the
// union of member DIDs across the communities they belong to. That scope feeds Appview.getTimeline
// ({ authors }) so two viewers in different communities see different timelines (DESIGN §7.5 — the
// per-peer/per-viewer view). Anonymous or community-less viewers get the global node timeline.
//
// A community is just a ROSTER of member DIDs. The roster SOURCE is pluggable and injected (this module
// stays pure + unit-testable, no P2P): `resolve(community) -> Promise<string[] memberDIDs>`. The server
// wires the real source(s):
//   - a bsky list (app.bsky.graph.list, roster.js resolveRoster over a DidPeer) — the DISCOVERABLE /
//     public community. Already proven.
//   - a StateBaseV3 room (atproto-room, read-only __members__) — the INVITE-ONLY community. Same shape,
//     different resolver.
// Communities are node-configured descriptors; a viewer's membership is derived (the communities whose
// roster CONTAINS the viewer's DID). A viewer-declared "entry-links" model (the viewer points at the
// communities they joined, from their own repo) is a richer future variant — same scopeFor() seam.

const DEFAULT_TTL_MS = 5 * 60 * 1000

export class Communities {
  // communities: [{ id, ... }] opaque descriptors passed verbatim to resolve(). resolve(community) ->
  // Promise<string[]> member DIDs. ttlMs: roster cache TTL (rosters are P2P reads; caching avoids a
  // re-resolve per request). now: injectable clock (tests).
  constructor ({ communities = [], resolve, ttlMs = DEFAULT_TTL_MS, now = () => Date.now() } = {}) {
    if (typeof resolve !== 'function') throw new Error('Communities: resolve(community) => Promise<string[]> is required')
    this._communities = Array.isArray(communities) ? communities.slice() : []
    this._resolve = resolve
    this._ttlMs = ttlMs
    this._now = now
    this._cache = new Map() // id -> { members: Set, exp }
  }

  get communities () { return this._communities.slice() }

  add (community) { if (community && community.id != null) this._communities.push(community) }

  // Cached member Set for one community. On a resolve failure, returns the last-good cached roster if
  // present (stale-serve), else an empty Set — a flaky community never breaks the whole view.
  async rosterOf (community) {
    const id = String(community && community.id)
    const hit = this._cache.get(id)
    if (hit && this._now() < hit.exp) return hit.members
    try {
      const members = new Set((await this._resolve(community)) || [])
      this._cache.set(id, { members, exp: this._now() + this._ttlMs })
      return members
    } catch (e) {
      if (hit) return hit.members // stale-serve on failure
      this._cache.set(id, { members: new Set(), exp: this._now() + this._ttlMs })
      return new Set()
    }
  }

  // The per-viewer author scope: union of member DIDs across every community whose roster contains the
  // viewer's DID. Returns a Set, or null when the viewer belongs to no known community (→ caller falls
  // back to the global timeline). Rosters resolve concurrently.
  async scopeFor (viewerDid) {
    if (!viewerDid || !this._communities.length) return null
    const rosters = await Promise.all(this._communities.map((c) => this.rosterOf(c).then((m) => ({ c, m }))))
    const scope = new Set()
    let member = false
    for (const { m } of rosters) {
      if (!m.has(viewerDid)) continue
      member = true
      for (const did of m) scope.add(did)
    }
    return member && scope.size ? scope : null
  }

  // The communities a viewer belongs to (descriptors) — for UI / diagnostics.
  async communitiesFor (viewerDid) {
    if (!viewerDid) return []
    const rosters = await Promise.all(this._communities.map((c) => this.rosterOf(c).then((m) => ({ c, m }))))
    return rosters.filter(({ m }) => m.has(viewerDid)).map(({ c }) => c)
  }

  // Union of member DIDs across ALL configured communities — what the node should be indexing so that
  // per-viewer scopes have posts to filter. (The node still only serves DIDs it actually replicates.)
  async allMemberDids () {
    const rosters = await Promise.all(this._communities.map((c) => this.rosterOf(c)))
    const all = new Set()
    for (const m of rosters) for (const did of m) all.add(did)
    return all
  }

  invalidate (id) { if (id == null) this._cache.clear(); else this._cache.delete(String(id)) }
}

export default Communities
// conformance.js — does the network actually hold what we think we published?
//
// WHY THIS EXISTS. Both real interop defects found on 2026-07-31 were SILENT SUCCESSES: every local
// surface reported health while the network saw nothing.
//   - 4 of 6 likes carried a strongRef with no `cid`. Valid here, rejected by relay lexicon validation,
//     federated as nothing. Invisible for weeks.
//   - two records were re-encoded by a second writer, stopped hashing to their pointers, and silently
//     dropped out of the signed repo.
// Nothing compared WHAT WE HOLD against WHAT BSKY INDEXES, so nothing could see either. This does.
//
// TWO LAYERS, cheapest first:
//   1. STRUCTURAL (offline, deterministic) — is the record even valid atproto? This is where the
//      strongRef class lives, and it needs no network, so it can run on every deploy.
//   2. NETWORK (a real diff) — for each record we hold, does the network agree it exists? This is the
//      only layer that catches "we signed it and nobody indexed it".
//
// ⛔ ABSENCE FROM BSKY IS NOT PROOF OF A DEFECT. bsky's AppView is eventually consistent, its relay is
// non-archival, and a freshly-signed record legitimately takes time to appear. So a network miss is
// reported as `pending` when the record is recent and `missing` only past a grace window — and even then
// it is a FINDING, not a verdict. Reporting a propagation delay as corruption would be its own silent
// failure, in the opposite direction.
//
// PURE + INJECTED. `doFetch` and `now` are parameters; every check is testable with no network.

const APPVIEW = 'https://public.api.bsky.app'
// How long after createdAt a record may be absent from bsky before we call it missing rather than pending.
const GRACE_MS = 10 * 60 * 1000

// ── layer 1: structural ──────────────────────────────────────────────────────────────────────────

// Fields that MUST be a com.atproto.repo.strongRef ({uri, cid} — both required).
const STRONGREF_PATHS = {
  'app.bsky.feed.like': [['subject']],
  'app.bsky.feed.repost': [['subject']],
  'app.bsky.feed.post': [['reply', 'parent'], ['reply', 'root']]
}
const REQUIRED = {
  'app.bsky.feed.post': ['text', 'createdAt'],
  'app.bsky.feed.like': ['subject', 'createdAt'],
  'app.bsky.feed.repost': ['subject', 'createdAt'],
  'app.bsky.graph.follow': ['subject', 'createdAt']
}

const at = (o, p) => p.reduce((x, k) => (x == null ? x : x[k]), o)

// -> [{ code, field, detail }]. Empty means structurally valid as far as we can tell offline.
export function validateRecord (collection, record) {
  const out = []
  if (!record || typeof record !== 'object') return [{ code: 'not-an-object', field: null }]

  for (const f of REQUIRED[collection] || []) {
    if (record[f] === undefined || record[f] === null) out.push({ code: 'missing-required', field: f })
  }
  // The defect that federated 4 likes as nothing: uri present, cid absent.
  for (const path of STRONGREF_PATHS[collection] || []) {
    const ref = at(record, path)
    if (!ref || typeof ref !== 'object') continue
    const label = path.join('.')
    if (typeof ref.uri !== 'string') out.push({ code: 'strongref-no-uri', field: label })
    else if (!ref.cid) out.push({ code: 'strongref-no-cid', field: label, detail: ref.uri })
  }
  // A reply must carry BOTH sides; one alone is not a valid thread edge.
  if (collection === 'app.bsky.feed.post' && record.reply) {
    if (!record.reply.parent) out.push({ code: 'reply-no-parent', field: 'reply.parent' })
    if (!record.reply.root) out.push({ code: 'reply-no-root', field: 'reply.root' })
  }
  // langs is not required by lexicon, but a post without it is dropped by some custom feeds — a real
  // observed loss (bsky feed drops langs-less posts), so it is reported as a WARNING, not an error.
  if (collection === 'app.bsky.feed.post' && !Array.isArray(record.langs)) {
    out.push({ code: 'no-langs', field: 'langs', warning: true })
  }
  return out
}

// ── layer 2: the network diff ────────────────────────────────────────────────────────────────────

async function getJson (doFetch, url) {
  try {
    const res = await doFetch(url, { method: 'GET', headers: { accept: 'application/json' }, timeout: 10000 })
    if (!res || res.ok === false) return null
    return await res.json()
  } catch { return null }
}

// ⚠ GRACE IS KEYED ON createdAt, WHICH IS WRONG FOR A REPUBLISHED RECORD. A record REPAIRED today
// (repair-strongrefs rewrites it under its original rkey and createdAt) is freshly re-signed but reads
// as old, so it is classified `missing` while it is genuinely still propagating. Observed immediately:
// the 4 likes repaired on 2026-07-31 reported `missing` seconds after being rewritten. Pass
// `republishedAfter` (a timestamp) to treat anything re-signed since then as pending regardless of
// createdAt. Without it, read `missing` on a recently-repaired record as "check again later", not as a
// defect — the whole point of this file is to not report propagation as corruption.
const recent = (record, now, graceMs, republishedAfter = null) => {
  if (republishedAfter && now - republishedAfter < graceMs) return true
  const t = Date.parse((record && record.createdAt) || '')
  return Number.isFinite(t) && (now - t) < graceMs
}

// Does bsky's AppView hold this post? Absence is meaningful only outside the grace window.
export async function probePost (doFetch, did, rkey, record, { appview = APPVIEW, now = Date.now(), graceMs = GRACE_MS, republishedAfter = null } = {}) {
  const uri = `at://${did}/app.bsky.feed.post/${rkey}`
  const body = await getJson(doFetch, `${appview}/xrpc/app.bsky.feed.getPostThread?uri=${encodeURIComponent(uri)}&depth=0`)
  const found = !!(body && body.thread && body.thread.post)
  if (found) return { state: 'ok' }
  return { state: recent(record, now, graceMs, republishedAfter) ? 'pending' : 'missing', uri }
}

// Our follows, as bsky sees them. ONE call for the whole collection rather than one per record.
export async function networkFollows (doFetch, did, { appview = APPVIEW, limit = 100 } = {}) {
  const body = await getJson(doFetch, `${appview}/xrpc/app.bsky.graph.getFollows?actor=${encodeURIComponent(did)}&limit=${limit}`)
  if (!body || !Array.isArray(body.follows)) return null
  return new Set(body.follows.map((f) => f && f.did).filter(Boolean))
}

// Does bsky record US as having liked this subject? One call per SUBJECT, so likes are grouped first.
export async function likedBy (doFetch, subjectUri, did, { appview = APPVIEW, limit = 100 } = {}) {
  const body = await getJson(doFetch, `${appview}/xrpc/app.bsky.feed.getLikes?uri=${encodeURIComponent(subjectUri)}&limit=${limit}`)
  if (!body || !Array.isArray(body.likes)) return null
  return body.likes.some((l) => l && l.actor && l.actor.did === did)
}

// ── the check ────────────────────────────────────────────────────────────────────────────────────
//
// listRecords(collection) -> [{ rkey, record }]
// Returns { structural, network, summary } — findings, never a pass/fail verdict.
export async function checkConformance ({
  did,
  listRecords,
  doFetch = null, // omit to run the offline structural layer only
  collections = ['app.bsky.feed.post', 'app.bsky.feed.like', 'app.bsky.feed.repost', 'app.bsky.graph.follow'],
  appview = APPVIEW,
  now = Date.now(),
  graceMs = GRACE_MS,
  maxProbes = 40, // bound the network layer; a full repo is not worth probing every run
  republishedAfter = null, // ms timestamp: records re-signed since then count as pending (see `recent`)
  onEvent = null
} = {}) {
  if (!did) throw new Error('checkConformance requires did')
  if (typeof listRecords !== 'function') throw new Error('checkConformance requires listRecords')
  const emit = (e, d) => { if (onEvent) onEvent(e, d) }

  const structural = []
  const network = []
  const byCollection = {}
  let checked = 0

  for (const collection of collections) {
    let recs = []
    try { recs = (await listRecords(collection)) || [] } catch (err) { emit('list-failed', { collection, error: err.message }); continue }
    byCollection[collection] = recs.length
    for (const { rkey, record } of recs) {
      checked++
      for (const p of validateRecord(collection, record)) {
        structural.push({ collection, rkey, ...p })
      }
    }
  }

  if (doFetch) {
    // posts — bounded, newest-last so a big repo still checks the interesting tail
    const posts = (await listRecords('app.bsky.feed.post').catch(() => [])) || []
    for (const { rkey, record } of posts.slice(-maxProbes)) {
      const r = await probePost(doFetch, did, rkey, record, { appview, now, graceMs, republishedAfter })
      if (r.state !== 'ok') network.push({ collection: 'app.bsky.feed.post', rkey, ...r })
    }

    // follows — one call, set difference
    const follows = (await listRecords('app.bsky.graph.follow').catch(() => [])) || []
    if (follows.length) {
      const net = await networkFollows(doFetch, did, { appview })
      if (net === null) emit('probe-unavailable', { collection: 'app.bsky.graph.follow' })
      else {
        for (const { rkey, record } of follows) {
          const subject = typeof record.subject === 'string' ? record.subject : (record.subject && record.subject.did)
          if (!subject || net.has(subject)) continue
          network.push({ collection: 'app.bsky.graph.follow', rkey, state: recent(record, now, graceMs, republishedAfter) ? 'pending' : 'missing', subject })
        }
      }
    }

    // likes — grouped by subject so N likes on one post cost ONE call
    const likes = (await listRecords('app.bsky.feed.like').catch(() => [])) || []
    const bySubject = new Map()
    for (const { rkey, record } of likes) {
      const uri = record && record.subject && record.subject.uri
      if (!uri) continue // structural layer already reported it
      if (!bySubject.has(uri)) bySubject.set(uri, [])
      bySubject.get(uri).push({ rkey, record })
    }
    for (const [uri, group] of [...bySubject].slice(0, maxProbes)) {
      const seen = await likedBy(doFetch, uri, did, { appview })
      if (seen === null || seen) continue
      for (const { rkey, record } of group) {
        network.push({ collection: 'app.bsky.feed.like', rkey, state: recent(record, now, graceMs, republishedAfter) ? 'pending' : 'missing', subject: uri })
      }
    }
  }

  const errors = structural.filter((s) => !s.warning)
  const summary = {
    did,
    checked,
    byCollection,
    structuralErrors: errors.length,
    structuralWarnings: structural.length - errors.length,
    networkMissing: network.filter((n) => n.state === 'missing').length,
    networkPending: network.filter((n) => n.state === 'pending').length,
    networkChecked: !!doFetch
  }
  return { structural, network, summary }
}
// constellation.js — the HISTORICAL half of DESIGN §7.6's inbound arm.
//
// WHY BOTH. Spacedust is a live subscription with NO cursor: `/subscribe` replays nothing, so every
// reconnect leaves a gap of unknown size. Constellation is the backlink INDEX over the same data — it
// answers "what links to this subject?" for any point in the past. §7.6 pairs them deliberately: the
// subscription is the edge, the index is the floor. Neither is sufficient alone, which is why treating
// either as the whole answer is the mistake to avoid.
//
// SAME POINTER SHAPE, DIFFERENT SOURCE. Constellation returns `{did, collection, rkey}` — a locator,
// exactly like spacedust, and for the same reason: it indexes links, not content. This module maps its
// rows into the IDENTICAL pointer shape `link-drain.js` already consumes, so the drain neither knows nor
// cares which source a pointer came from. That is the unification — one pipeline, several pointer
// sources — rather than a second parallel path.
//
// TIER C IS ANSWERED HERE, NOT RETAINED. §7.6 says likes and reposts are countable, not content. That
// is only affordable because `getBacklinksCount` exists: a post with 50k likes costs ONE query rather
// than 50k retained records. `countBacklinks` is that call, and it is why the tiering works at all.
//
// FAILS SOFT. Every path returns null / an empty page rather than throwing. Backfill is best-effort by
// construction: a gap we fail to close is a gap that stays open, not a crashed drain.
//
// PURE + INJECTED. `doFetch` is a parameter, so pagination, the cursor walk and failure handling are
// testable with no network.

import { CONTENT_BEARING } from './spacedust.js'
import { pointerKey } from './link-drain.js'

export const DEFAULT_ENDPOINT = 'https://constellation.microcosm.blue'

// Their docs ask consumers to identify themselves in the user-agent.
export const USER_AGENT = 'favela-web (+https://github.com/favela)'

const MAX_LIMIT = 100 // lexicon-enforced ceiling on getBacklinks

// A Constellation row is `{did, collection, rkey}`. Everything else in a pointer is context we already
// hold from the query itself, so it is filled in rather than parsed.
//
// `rev` is deliberately null: Constellation does not report the revision that produced a link, so the
// drain's skip-test cannot short-circuit on it. shouldSkipRev() treats a null incoming rev as NEW, which
// is the safe direction — we re-fetch and let verification decide, rather than skipping on absent data.
export function rowToPointer (row, { subject, source }) {
  if (!row || typeof row.did !== 'string' || typeof row.collection !== 'string' || typeof row.rkey !== 'string') return null
  if (!row.did || !row.collection || !row.rkey) return null
  return {
    operation: 'create', // the index only holds live links; deletions are absences, not rows
    source,
    subject,
    did: row.did,
    collection: row.collection,
    rkey: row.rkey,
    rev: null,
    contentBearing: CONTENT_BEARING.has(source),
    origin: 'backfill'
  }
}

export function createConstellationClient ({ doFetch, endpoint = DEFAULT_ENDPOINT, timeoutMs = 10_000 } = {}) {
  if (typeof doFetch !== 'function') throw new Error('createConstellationClient requires doFetch')
  const base = String(endpoint).replace(/\/+$/, '')

  async function query (nsid, params) {
    const url = new URL(`${base}/xrpc/${nsid}`)
    for (const [k, v] of Object.entries(params)) {
      if (v === undefined || v === null) continue
      if (Array.isArray(v)) { for (const item of v) url.searchParams.append(k, item) } else url.searchParams.set(k, String(v))
    }
    try {
      const res = await doFetch(url.toString(), {
        method: 'GET',
        headers: { accept: 'application/json', 'User-Agent': USER_AGENT },
        timeout: timeoutMs
      })
      if (!res || res.ok === false) return null
      return await res.json()
    } catch {
      return null // network, timeout, malformed JSON — all "no answer", never a throw
    }
  }

  return {
    // One page of records linking to `subject` through `source` (a `<nsid>:<path>` spec).
    // Returns { total, pointers, cursor } — or null when the index gave no usable answer.
    async getBacklinks (subject, source, { did = null, limit = MAX_LIMIT, cursor = null } = {}) {
      if (!subject || !source) return null
      const body = await query('blue.microcosm.links.getBacklinks', {
        subject,
        source,
        did,
        limit: Math.min(Math.max(1, limit), MAX_LIMIT),
        cursor
      })
      if (!body || !Array.isArray(body.records)) return null
      const pointers = body.records.map((r) => rowToPointer(r, { subject, source })).filter((p) => p !== null)
      return {
        total: typeof body.total === 'number' ? body.total : pointers.length,
        pointers,
        cursor: typeof body.cursor === 'string' && body.cursor.length > 0 ? body.cursor : null
      }
    },

    // TIER C. The reason likes never need retaining — one query instead of N records.
    async countBacklinks (subject, source) {
      if (!subject || !source) return null
      const body = await query('blue.microcosm.links.getBacklinksCount', { subject, source })
      if (typeof body === 'number') return body
      if (body && typeof body.total === 'number') return body.total
      if (body && typeof body.count === 'number') return body.count
      return null
    },

    // Distinct DIDs linking to a subject — "which people you follow liked this", without the records.
    async getDistinctDids (subject, source, { limit = MAX_LIMIT, cursor = null } = {}) {
      if (!subject || !source) return null
      const body = await query('blue.microcosm.links.getDistinct', {
        subject,
        source,
        limit: Math.min(Math.max(1, limit), MAX_LIMIT),
        cursor
      })
      if (!body) return null
      const dids = Array.isArray(body.dids)
        ? body.dids
        : Array.isArray(body.records) ? body.records.map((r) => r && r.did).filter(Boolean) : null
      if (dids === null) return null
      return { dids, cursor: typeof body.cursor === 'string' && body.cursor.length > 0 ? body.cursor : null }
    },

    // Walk every page for one (subject, source), yielding pointers. `maxPages` bounds the walk so a
    // pathological subject — a viral post with a million backlinks — cannot turn a gap-fill into an
    // unbounded crawl. Hitting the bound is reported, never silent: §7.6's whole posture is that a
    // truncation you cannot see reads as completeness you do not have.
    async * walkBacklinks (subject, source, { maxPages = 10, limit = MAX_LIMIT, onTruncate = null } = {}) {
      let cursor = null
      for (let page = 0; page < maxPages; page++) {
        const res = await this.getBacklinks(subject, source, { limit, cursor })
        if (res === null) return
        for (const p of res.pointers) yield p
        if (res.cursor === null) return
        cursor = res.cursor
      }
      if (onTruncate) onTruncate({ subject, source, maxPages })
    },

    // Gap-fill after a reconnect: pull recent backlinks for our subjects across the content-bearing
    // sources and hand them to the same drain the live subscription feeds. Returns { offered, duplicates }
    // so a caller can log what a reconnect actually cost.
    //
    // ⚠ DEDUP IS REQUIRED HERE, not optional. One record legitimately links through SEVERAL sources — a
    // reply carries both reply.parent.uri and reply.root.uri — so a (subjects x sources) sweep offers the
    // same record once per matching source. Live pointers dedup themselves via the rev skip-test, but
    // backfilled ones carry rev:null (Constellation does not report it), so nothing downstream would
    // catch it: measured 3 fetches, 3 signature verifications and 3 writes for ONE record. Dedup by
    // record identity within the sweep.
    async backfillInto (enqueue, { subjects, sources, maxPages = 3, onTruncate = null }) {
      const seen = new Set()
      let offered = 0
      let duplicates = 0
      for (const subject of subjects || []) {
        for (const source of sources || []) {
          for await (const pointer of this.walkBacklinks(subject, source, { maxPages, onTruncate })) {
            const key = pointerKey(pointer)
            if (seen.has(key)) { duplicates++; continue }
            seen.add(key)
            enqueue(pointer)
            offered++
          }
        }
      }
      return { offered, duplicates }
    }
  }
}
// curators.js — the registry of curation FUNCTIONS favela-web runs to turn a community's mutable
// { curator, params } contract (favela-community's CommunityRoom.curation()) into a feed skeleton
// (architecture.md "Feeds are curation functions": in=firehose/index, out=[post URIs]).
//
// A curator is a PAGER: ({ limit, cursor }) => Promise<{ posts, cursor }> over the appview index. feedgen's
// skeleton() drives it — filtering each page to bsky posts + paginating until `limit` bsky entries. Curators
// only SELECT posts; they never sign or touch the bsky wire, so the whole layer is bsky-NEUTRAL (the output
// is always app.bsky.feed.post URIs). And the read is P2P-native: roster/curation come from a keyless
// community-room replica, posts from the local Hyperbee appview.
//
// Built-ins: roster (WHO — the room members' posts) + subject (a topic/tag feed). NOT-yet-built curators
// (rules, custom/sandboxed) fall back to ROSTER — the safe default that always yields a valid feed — until
// their implementation ships. Adding a curator = a case here; NO schema change (the room stores any curator
// string, so a community can name a future custom curator with no migration).

const EMPTY = () => Promise.resolve({ posts: [], cursor: null })

// roster: the community's members' posts, reverse-chron. params: none. Uses queries.getTimeline({ authors }).
// (This is favela-web's historical implicit behavior — the default.)
function rosterPager ({ roster, queries }) {
  if (!roster || !roster.size) return EMPTY
  return ({ limit, cursor }) => queries.getTimeline({ authors: roster, limit, cursor })
}

// subject: a TOPICAL feed — posts carrying params.tag across ALL indexed authors (a community can be about a
// subject, not only a member set). params: { tag }. Uses queries.getTagFeed(tag). Missing tag / no tag query
// → empty (a misconfigured subject feed degrades to empty, never throws).
function subjectPager ({ params, queries }) {
  const tag = params && params.tag
  if (!tag || typeof queries.getTagFeed !== 'function') return EMPTY
  return ({ limit, cursor }) => queries.getTagFeed(tag, { limit, cursor })
}

// The curators with a native implementation today (advertised so a config/UI can validate).
export const IMPLEMENTED_CURATORS = ['roster', 'subject']

// Resolve a { curator, params } contract to a pager. ctx = { roster: Set, queries: { getTimeline, getTagFeed } }.
// Unknown / not-yet-built curators degrade to roster (the safe default) rather than erroring the feed.
export function makeCurator (curation, ctx) {
  const curator = (curation && curation.curator) || 'roster'
  const params = (curation && curation.params) || {}
  switch (curator) {
    case 'subject': return subjectPager({ params, ...ctx })
    case 'roster': return rosterPager(ctx)
    default: return rosterPager(ctx) // rules + custom/sandboxed: not built yet → safe roster fallback
  }
}

export default { makeCurator, IMPLEMENTED_CURATORS }
// dns-txt.js — a minimal DNS TXT client, because bare-dns segfaults the process.
//
// WHY THIS EXISTS. atproto handles ARE domain names, and a handle is only displayable once it
// verifies BACK to the DID (see handles.js). There are two mechanisms and we try HTTPS well-known
// first, but measured 2026-08-24, every custom-domain handle sampled verifies ONLY by DNS TXT —
// pfrazee.com, dholms.xyz, jay.bsky.team and bsky.app all return did= over TXT while their
// /.well-known/atproto-did is a redirect, a 404 or nothing. Hosted subdomains (*.bsky.social, our own
// *.7rnx.net) are the reverse. So TXT is not a fallback for rare names; it is the primary mechanism
// for most of the interesting identities on the network, and without it they render handle.invalid.
//
// bare-dns cannot be used for it. `bare_dns_resolve_txt` hands c-ares a pointer into a JS arraybuffer
// that nothing references, so any GC during the query frees it and the callback faults:
//
//   #0 js_open_handle_scope  #1 bare_dns__on_resolve_txt  #2 ares_query_dnsrec_cb  ... #7 uv_run
//
// That is a SIGSEGV, not an exception — uncatchable, and it took the public backend down 819 times in
// a week. The addon is statically linked into the bare runtime, so it cannot be fixed by patching a
// dependency; it needs a runtime rebuild. Until then, this.
//
// DNS over TCP (RFC 7766), not UDP. Every resolver supports it including the systemd-resolved stub,
// it removes the 512-byte truncation dance entirely, and bare-net is already present — adding
// bare-dgram would mean adding another native addon, which is the class of thing that put us here.
//
// PURE + INJECTED, like handles.js: the codec below is plain Uint8Array work with no I/O so it runs
// under node in the test suite, and the transport takes `connect` as a parameter.

const TYPE_TXT = 16
const CLASS_IN = 1
const HEADER_LEN = 12
const MAX_NAME_LEN = 255
const MAX_LABEL_LEN = 63
// A compressed name could otherwise point at itself and spin forever. The bound is arbitrary but far
// above any legitimate chain.
const MAX_POINTER_JUMPS = 64

export const RCODE = { NOERROR: 0, FORMERR: 1, SERVFAIL: 2, NXDOMAIN: 3, NOTIMP: 4, REFUSED: 5 }

// `nameserver 127.0.0.53` lines, in file order. Everything else in resolv.conf is ignored: we only
// need somewhere to send the query, and options/search are the stub resolver's business.
export function parseResolvConf (text) {
  if (typeof text !== 'string') return []
  const out = []
  for (const raw of text.split('\n')) {
    const line = raw.trim()
    if (!line || line.startsWith('#') || line.startsWith(';')) continue
    const m = line.match(/^nameserver\s+(\S+)$/i)
    if (m) out.push(m[1])
  }
  return out
}

// ⛔ ANDROID HAS NO /etc/resolv.conf. netd owns resolution there and `getprop net.dns1` has been empty
// since Android 8, so the handset booted with `DNS TXT handle verification is OFF` — the bare-dns crash
// was fixed and the CAPABILITY never arrived: every custom-domain handle renders handle.invalid on the
// phone, which by our own measurement is most of the interesting identities on the network.
//
// Nothing about the resolver needed changing; it only ever needed somewhere to send the query. So the
// embedder may pass one in. On Android that is ConnectivityManager's own DNS list for the active
// network — the SAME resolver the OS uses, not a third party, which is why this is an env handoff and
// NOT a hardcoded 1.1.1.1: handle verification is the last place to hand a stranger the list of every
// identity we look up (see the note at the resolver's construction in bin/favela-web.js).
//
// Addresses only, no ports, no hostnames: this value is handed straight to connect(), and a hostname
// would need a resolver to resolve — which is the thing we are trying to obtain.
//
// ⛔ A CHARACTER-CLASS TEST IS NOT ENOUGH. `[0-9a-fA-F:.]+` admits `8.8.8.8:53`, because ':' has to be
// allowed for IPv6 — and a port smuggled into the host argument is a connect() to a host that does not
// exist. So the two families are parsed apart.
function isIpv4 (s) {
  const parts = s.split('.')
  return parts.length === 4 && parts.every((o) => /^\d{1,3}$/.test(o) && Number(o) <= 255)
}
function isIpv6 (s) {
  if (!s.includes(':')) return false
  if ((s.match(/::/g) || []).length > 1) return false
  const parts = s.split(':')
  if (parts.length > 8) return false
  return parts.every((p, i) => {
    if (p === '') return true // the '::' compression, and a leading/trailing colon of it
    if (i === parts.length - 1 && p.includes('.')) return isIpv4(p) // ::ffff:1.2.3.4
    return /^[0-9a-fA-F]{1,4}$/.test(p)
  })
}
const isAddress = (s) => typeof s === 'string' && s.length > 0 && s.length <= 45 && (isIpv4(s) || isIpv6(s))

export function parseNameserverList (value) {
  if (typeof value !== 'string') return []
  return value.split(/[,\s]+/).map((s) => s.trim()).filter(isAddress)
}

// Env first, resolv.conf second. Deliberately not "merge both": if an embedder has said which resolvers
// to use, silently appending the file's would send some queries somewhere it did not choose.
export function chooseNameservers ({ envValue = null, resolvConf = null } = {}) {
  const fromEnv = parseNameserverList(envValue)
  if (fromEnv.length) return { servers: fromEnv, source: 'env' }
  const fromFile = parseResolvConf(resolvConf)
  if (fromFile.length) return { servers: fromFile, source: 'resolv.conf' }
  return { servers: [], source: 'none' }
}

export function encodeQuery (name, id) {
  if (typeof name !== 'string' || !name) throw new Error('name required')
  const labels = name.replace(/\.$/, '').split('.')
  let qnameLen = 1 // the terminating root label
  for (const l of labels) {
    const bytes = utf8(l)
    if (bytes.length === 0) throw new Error('empty label in ' + name)
    if (bytes.length > MAX_LABEL_LEN) throw new Error('label too long in ' + name)
    qnameLen += 1 + bytes.length
  }
  if (qnameLen > MAX_NAME_LEN) throw new Error('name too long: ' + name)

  const buf = new Uint8Array(HEADER_LEN + qnameLen + 4)
  const view = new DataView(buf.buffer)

  view.setUint16(0, id & 0xffff)
  view.setUint16(2, 0x0100) // RD — we want the resolver to do the work
  view.setUint16(4, 1) // one question
  // ancount / nscount / arcount stay zero

  let o = HEADER_LEN
  for (const l of labels) {
    const bytes = utf8(l)
    buf[o++] = bytes.length
    buf.set(bytes, o)
    o += bytes.length
  }
  buf[o++] = 0

  view.setUint16(o, TYPE_TXT); o += 2
  view.setUint16(o, CLASS_IN)

  return buf
}

// -> { id, rcode, answers } where answers is an array per TXT record of its character-strings, which
// is the shape didFromTxt() already expects (it joins arrays before matching).
export function decodeResponse (buf, expectedId = null) {
  if (!(buf instanceof Uint8Array)) throw new Error('response must be a Uint8Array')
  if (buf.length < HEADER_LEN) throw new Error('response shorter than a DNS header')
  const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)

  const id = view.getUint16(0)
  // A response for a different query is not our answer. Cheap, and it is the only thing standing
  // between us and an off-path answer on a shared socket.
  if (expectedId !== null && id !== expectedId) throw new Error('response id mismatch')

  const flags = view.getUint16(2)
  const rcode = flags & 0x0f
  const qdcount = view.getUint16(4)
  const ancount = view.getUint16(6)

  let o = HEADER_LEN
  for (let i = 0; i < qdcount; i++) {
    o = skipName(buf, o)
    o += 4 // qtype + qclass
    if (o > buf.length) throw new Error('truncated question section')
  }

  const answers = []
  for (let i = 0; i < ancount; i++) {
    if (o >= buf.length) break
    o = skipName(buf, o)
    if (o + 10 > buf.length) throw new Error('truncated answer header')
    const type = view.getUint16(o); o += 2
    o += 2 // class
    o += 4 // ttl
    const rdlength = view.getUint16(o); o += 2
    if (o + rdlength > buf.length) throw new Error('rdlength past end of response')

    if (type === TYPE_TXT) {
      const chunks = []
      let p = o
      const end = o + rdlength
      while (p < end) {
        const len = buf[p++]
        if (p + len > end) throw new Error('TXT character-string past end of rdata')
        chunks.push(ascii(buf.subarray(p, p + len)))
        p += len
      }
      answers.push(chunks)
    }
    o += rdlength
  }

  return { id, rcode, answers }
}

// Names may be compressed as a pointer to an earlier offset. We never need the name itself here —
// only to step over it — so this resolves pointers just far enough to find where the name ends.
function skipName (buf, offset) {
  let o = offset
  let jumps = 0
  while (true) {
    if (o >= buf.length) throw new Error('name past end of response')
    const len = buf[o]
    if (len === 0) return o + 1
    if ((len & 0xc0) === 0xc0) {
      // A pointer is two bytes and the name ENDS there, whatever it points at.
      if (o + 2 > buf.length) throw new Error('truncated compression pointer')
      if (++jumps > MAX_POINTER_JUMPS) throw new Error('too many compression pointers')
      return o + 2
    }
    if ((len & 0xc0) !== 0) throw new Error('reserved label type')
    o += 1 + len
  }
}

function utf8 (s) {
  const out = []
  for (const ch of unescape(encodeURIComponent(s))) out.push(ch.charCodeAt(0))
  return Uint8Array.from(out)
}

function ascii (bytes) {
  let s = ''
  for (let i = 0; i < bytes.length; i++) s += String.fromCharCode(bytes[i])
  return s
}

// DNS over TCP frames each message with a two-byte big-endian length.
export function frame (msg) {
  const out = new Uint8Array(2 + msg.length)
  new DataView(out.buffer).setUint16(0, msg.length)
  out.set(msg, 2)
  return out
}

/**
 * Build the resolveTxt(name) -> string[][] that handles.js takes.
 *
 * `connect` is injected (bare-net's createConnection in the daemon, a fake in tests) so none of this
 * needs a socket to be tested.
 */
export function createTcpResolveTxt ({
  connect,
  servers = ['127.0.0.1'],
  port = 53,
  timeoutMs = 5000,
  nextId = () => Math.floor(Math.random() * 0xffff)
} = {}) {
  if (typeof connect !== 'function') throw new Error('createTcpResolveTxt requires connect')
  if (!Array.isArray(servers) || servers.length === 0) throw new Error('at least one server required')

  return function resolveTxt (name) {
    return new Promise((resolve, reject) => {
      const id = nextId()
      const query = frame(encodeQuery(name, id))

      const socket = connect({ host: servers[0], port })

      let settled = false
      let expected = -1
      let received = new Uint8Array(0)

      const finish = (err, value) => {
        if (settled) return
        settled = true
        clearTimeout(timer)
        try { socket.destroy() } catch {}
        err ? reject(err) : resolve(value)
      }

      // A resolver that accepts the connection and never answers would otherwise hang the caller
      // forever — which is the failure mode that made the bare-dns bug so expensive to notice.
      const timer = setTimeout(() => finish(new Error('DNS query timed out after ' + timeoutMs + 'ms')), timeoutMs)
      if (typeof timer.unref === 'function') timer.unref()

      socket.on('error', (err) => finish(err))
      socket.on('close', () => finish(new Error('DNS connection closed before a complete response')))

      socket.on('data', (chunk) => {
        const next = new Uint8Array(received.length + chunk.length)
        next.set(received, 0)
        next.set(chunk, received.length)
        received = next

        if (expected < 0) {
          if (received.length < 2) return
          expected = (received[0] << 8) | received[1]
        }
        if (received.length < 2 + expected) return

        try {
          const { rcode, answers } = decodeResponse(received.subarray(2, 2 + expected), id)
          // NXDOMAIN and an empty answer set are both "no record", which is a verdict, not a failure.
          if (rcode !== RCODE.NOERROR && rcode !== RCODE.NXDOMAIN) {
            return finish(new Error('DNS rcode ' + rcode))
          }
          finish(null, answers)
        } catch (err) {
          finish(err)
        }
      })

      socket.on('connect', () => socket.write(query))
    })
  }
}
// facets — turn compose-time text into app.bsky.richtext.facet[] for the record we write.
//
// THE GAP THIS CLOSES. `renderRichText` has always READ facets correctly, so we display everyone else's
// links, mentions and hashtags properly. We never WROTE any: writer.post() built {$type, text, createdAt}
// and nothing else. So every link, @mention and #tag posted from favela arrived as INERT PLAIN TEXT in
// bsky and every other client — unclickable, unsearchable, and a mention that notified nobody. Pure
// asymmetry: we consumed rich text and produced none.
//
// ⚠ BYTE OFFSETS, NOT STRING INDICES. A facet's index is a range into the UTF-8 ENCODING of `text`. JS
// string indices are UTF-16 code units, so any emoji or non-ASCII character before a link shifts the real
// byte offset and every facet after it lands on the wrong characters — which renders as garbled links
// rather than as an error. renderRichText documents the same trap on the read side; this is the write
// side of it. Every offset here goes through TextEncoder.
//
// ⚠ A MENTION NEEDS A DID, NOT A HANDLE. app.bsky.richtext.facet#mention carries `did`. A handle we cannot
// resolve gets NO facet — the text stays plain rather than shipping a mention pointing at a guess. Being
// unlinked is a papercut; mentioning the wrong account is a different person's notification.
//
// Pure + injected: `resolveHandle` is a parameter, so the whole detector is testable with no network.

const enc = new TextEncoder()
const byteLen = (s) => enc.encode(s).length

// Same conservative URL shape the renderer uses: stop before trailing punctuation so "see https://x.com."
// does not swallow the full stop. Kept deliberately in step with render.js's URL_RE — if the two disagree,
// text renders as a link locally and ships without a facet (or the reverse), which is exactly the class of
// silent divergence that costs days.
const URL_RE = /\bhttps?:\/\/[^\s<]+[^\s<.,:;!?)\]}'"]/g
// atproto handles are domain names. Require a dot and a 2+ char TLD so "@someone" (no domain) is not
// mistaken for a handle — bsky does the same, and an unresolvable bare word would be dropped anyway.
const MENTION_RE = /(^|[\s([])@([a-zA-Z0-9][a-zA-Z0-9-]*(?:\.[a-zA-Z0-9][a-zA-Z0-9-]*)+)/g
// Matches render.js TAG_RE: letters, numbers, underscore, unicode-aware.
const TAG_RE = /(^|[\s([])#([\p{L}\p{N}_]+)/gu

// All candidate ranges, as { start, end, type, value } in STRING indices. Sync + pure, so the hard part
// (what counts as a link) is testable on its own.
export function findCandidates (text) {
  const t = String(text == null ? '' : text)
  const out = []
  let m

  URL_RE.lastIndex = 0
  while ((m = URL_RE.exec(t)) !== null) out.push({ start: m.index, end: m.index + m[0].length, type: 'link', value: m[0] })

  MENTION_RE.lastIndex = 0
  while ((m = MENTION_RE.exec(t)) !== null) {
    const lead = m[1] ? m[1].length : 0
    const start = m.index + lead // the '@' itself, not the whitespace the regex ate
    out.push({ start, end: start + 1 + m[2].length, type: 'mention', value: m[2] })
  }

  TAG_RE.lastIndex = 0
  while ((m = TAG_RE.exec(t)) !== null) {
    const lead = m[1] ? m[1].length : 0
    const start = m.index + lead
    out.push({ start, end: start + 1 + m[2].length, type: 'tag', value: m[2] })
  }

  // Sort by position, then drop anything overlapping an earlier match. A '#tag' inside a URL's fragment is
  // the common case: the URL wins because it started first, and emitting both would produce interleaved
  // facets that no client can render.
  out.sort((a, b) => a.start - b.start || b.end - a.end)
  const kept = []
  let at = -1
  for (const c of out) {
    if (c.start < at) continue
    kept.push(c)
    at = c.end
  }
  return kept
}

// -> app.bsky.richtext.facet[], byte-indexed and sorted. `resolveHandle(handle) -> did|null` is optional;
// without it, mentions are simply not emitted (links and tags still are).
export async function detectFacets (text, { resolveHandle = null } = {}) {
  const t = String(text == null ? '' : text)
  const cands = findCandidates(t)
  if (!cands.length) return []

  const facets = []
  for (const c of cands) {
    // Offsets are computed from the ENCODED prefix, never from the string index.
    const byteStart = byteLen(t.slice(0, c.start))
    const byteEnd = byteStart + byteLen(t.slice(c.start, c.end))
    const index = { byteStart, byteEnd }

    if (c.type === 'link') {
      facets.push({ index, features: [{ $type: 'app.bsky.richtext.facet#link', uri: c.value }] })
      continue
    }
    if (c.type === 'tag') {
      facets.push({ index, features: [{ $type: 'app.bsky.richtext.facet#tag', tag: c.value }] })
      continue
    }
    // mention — only with a resolved DID, never on a guess.
    if (!resolveHandle) continue
    let did = null
    try { did = await resolveHandle(c.value) } catch { did = null }
    if (typeof did !== 'string' || !did.startsWith('did:')) continue
    facets.push({ index, features: [{ $type: 'app.bsky.richtext.facet#mention', did }] })
  }
  return facets
}
// The favela-web FEED REACTOR (community-ux.md §120): reconcile the feeds favela-web SERVES to the durable
// P2P FeedRegistry — with no per-community env and no restart. A FeedRegistry watch fires with the registry's
// FULL current entry list on every advance; reconcile(regKey, entries) makes the served set match:
//   - add-feed  → feedgen.addFeed (serve getFeedSkeleton) + wireRoster (index the roster, scope viewers)
//   - remove-feed (an entry that vanished) → feedgen.removeFeed, but ONLY once NO registry still lists it
//     (a feed can be listed in more than one allow-set registry; it stays served while any of them lists it).
// Roster-first: entries with a roomKey (community feeds — curation lives in the room) are served; light
// feeds (no room — curation in the entry) are reported to onLight and skipped for now.
//
// Pure + injected (feedgen, wireRoster, log stubs) so the reconcile is unit-testable without a live server.
// The registry entry shape is feed-schema.js: { did, rkey, name, curator, params, roomKey, handle, ... }.
export function makeFeedReactor ({ feedgen, wireRoster = async () => {}, log = () => {}, onLight = null } = {}) {
  if (!feedgen) throw new Error('makeFeedReactor requires a feedgen')
  const key = (did, rkey) => `${did}\x00${rkey}`
  const servedBy = new Map() // `${did}\x00${rkey}` -> Set<regKey> (served while ANY registry lists it)
  const wiredRooms = new Set() // roomKeys we've already wired a roster watch for (wire once; a live watch is
  // permanent + harmless even after a feed is de-listed, so we never un-wire — re-adding won't double-watch)

  async function reconcile (regKey, entries) {
    const desired = new Set()
    for (const e of entries || []) {
      if (!e || !e.did || !e.rkey) continue
      if (!e.roomKey) { if (onLight) onLight(e); else log(`[favela] light feed (no room) not served yet — roster-first: ${e.did} ${e.rkey}`); continue }
      const k = key(e.did, e.rkey)
      desired.add(k)
      // idempotent (Map.set): a re-fire with an unchanged entry is a no-op; a changed name/room updates it.
      feedgen.addFeed({ communityDid: e.did, rkey: e.rkey, roomKey: e.roomKey, displayName: e.name || e.rkey, description: `favela community: ${e.name || e.rkey}` })
      if (!servedBy.has(k)) servedBy.set(k, new Set())
      const regs = servedBy.get(k)
      if (!regs.has(regKey)) { regs.add(regKey); log(`[favela] registry feed: at://${e.did}/app.bsky.feed.generator/${e.rkey} (${e.name || e.rkey})`) }
      if (!wiredRooms.has(e.roomKey)) { wiredRooms.add(e.roomKey); await wireRoster(e.name || e.rkey, e.roomKey) }
    }
    // drop THIS registry's claim on feeds it no longer lists; stop SERVING only when no registry lists them.
    for (const [k, regs] of servedBy) {
      if (regs.has(regKey) && !desired.has(k)) {
        regs.delete(regKey)
        if (regs.size === 0) {
          const i = k.indexOf('\x00')
          const did = k.slice(0, i); const rkey = k.slice(i + 1)
          feedgen.removeFeed(did, rkey)
          servedBy.delete(k)
          log(`[favela] registry feed removed: at://${did}/app.bsky.feed.generator/${rkey}`)
        }
      }
    }
  }

  // introspection (tests / status): which (did,rkey) are currently served, and by which registries.
  reconcile.served = () => [...servedBy.keys()].map((k) => { const i = k.indexOf('\x00'); return { did: k.slice(0, i), rkey: k.slice(i + 1), registries: [...servedBy.get(k)] } })
  return reconcile
}

export default makeFeedReactor
// feedgen.js — favela's LENS EXPORT to bsky (DESIGN §3.6): a favela community projects into a
// bsky-subscribable custom feed via app.bsky.feed.getFeedSkeleton.
//
// A feed generator is STATELESS and hydration-free (atproto contract): it returns an ordered list of
// post at:// URIs ({ feed:[{post}], cursor }); the requesting AppView (bsky) hydrates text/author/counts.
// favela already holds exactly this — a community's skeleton is its members' posts in reverse-chron,
// straight out of the appview index (getTimeline({authors})). We return ONLY app.bsky.feed.post URIs —
// bsky can't hydrate net.favela.local.post (unknown lexicon), so local-only posts correctly stay local
// (DESIGN §3.6 caveat). The room itself is never bsky-legible; only its post-output projects.
//
// Three surfaces (the starter-kit shape, keyless-native):
//   GET /.well-known/did.json                        — did:web doc; BskyFeedGenerator service → our HTTPS
//   GET /xrpc/app.bsky.feed.describeFeedGenerator     — advertise every hosted community feed
//   GET /xrpc/app.bsky.feed.getFeedSkeleton?feed=…    — the skeleton for one community

import { makeCurator } from './curators.js'

const GENERATOR_COLLECTION = 'app.bsky.feed.generator'
const BSKY_POST = 'app.bsky.feed.post'

// Parse an at:// URI into { hostname, collection, rkey }. Returns null if malformed.
export function parseFeedUri (uri) {
  const m = /^at:\/\/([^/]+)\/([^/]+)\/([^/]+)$/.exec(String(uri || ''))
  return m ? { hostname: m[1], collection: m[2], rkey: m[3] } : null
}

// A member post's canonical bsky at:// URI (a skeleton entry).
export function postUri (did, rkey) { return `at://${did}/${BSKY_POST}/${rkey}` }

// Turn a community id/name into a valid atproto record key (rkey syntax = [A-Za-z0-9._~-], 1–512, not
// "."/".."). Used both when registering a feed and when publishing its generator record, so the two never
// drift. Deterministic: the same id always slugs to the same rkey.
export function slugRkey (id) {
  const s = String(id || '').toLowerCase().replace(/[^a-z0-9._~-]+/g, '-').replace(/^[-.]+|[-.]+$/g, '').slice(0, 64)
  return s || 'feed'
}

// Is this indexed post bsky-federated (vs favela-local)? Only these belong in a bsky-facing feed.
export function isBskyPost (p) { return !!(p && p.record && p.record.$type === BSKY_POST) }

// bsky post rkeys are TIDs (the app.bsky.feed.post lexicon declares key=tid). A non-TID rkey — e.g. a
// bootstrap placeholder like 'self.hello', or any malformed member record — is NOT a real post, and it
// POISONS a bsky feed: getFeed validates every skeleton URI's rkey as a TID and rejects the ENTIRE response
// (InvalidFeedResponse) on a single bad entry, so ONE stray record breaks the whole community feed. Emit
// only valid-TID post URIs. TID = 13 chars, base32-sortable (matches @atproto ensureValidTid exactly).
const TID_RE = /^[234567abcdefghij][234567abcdefghijklmnopqrstuvwxyz]{12}$/
export function isValidPostRkey (rkey) { return TID_RE.test(String(rkey || '')) }

export class FeedGenerator {
  // MULTI-TENANT (phase 4): favela-web serves getFeedSkeleton for MANY communities, each identified by its
  // OWN co-owned did:plc (the community DID IS its own feed-generator service — its PLC #bsky_fg points
  // here). So a feed is keyed by (communityDid, rkey); there is NO single service/publisher DID. hostname
  // is optional (only for a vestigial did:web fallback doc — communities self-advertise via their PLC docs).
  constructor ({ hostname = null } = {}) {
    this.hostname = hostname
    this._algos = new Map() // `${communityDid}\x00${rkey}` -> { communityDid, rkey, roomKey, displayName, description }
  }

  _key (communityDid, rkey) { return `${communityDid}\x00${rkey}` }

  // Register a hosted community feed. communityDid = the community's own DID (owns the feed record + is the
  // service). rkey = the generator record rkey (the community's feed short name). roomKey = the room to
  // read the roster from. Idempotent per (communityDid, rkey).
  addFeed ({ communityDid, rkey, roomKey, displayName = '', description = '' } = {}) {
    if (!communityDid || !rkey) throw new Error('addFeed requires communityDid + rkey')
    this._algos.set(this._key(communityDid, String(rkey)), { communityDid, rkey: String(rkey), roomKey: roomKey || null, displayName, description })
    return this
  }

  // Deregister a hosted feed (a remove-feed reaction from the FeedRegistry). Idempotent — removing an
  // unknown feed is a no-op. Returns true iff a feed was actually removed. In-memory only: the durable
  // feed record lives in the FeedRegistry (owned elsewhere); this just stops SERVING a de-listed feed.
  removeFeed (communityDid, rkey) { return this._algos.delete(this._key(communityDid, String(rkey))) }

  get feeds () { return [...this._algos.values()] }
  has (communityDid, rkey) { return this._algos.has(this._key(communityDid, String(rkey))) }
  feed (communityDid, rkey) { return this._algos.get(this._key(communityDid, String(rkey))) || null }

  // app.bsky.feed.describeFeedGenerator. Ambiguous at a multi-tenant front (many service DIDs, one
  // endpoint), so: given a communityDid, describe THAT community's feeds; without one, list every hosted
  // feed uri (a best-effort superset — describe is optional; the load-bearing path is getFeedSkeleton).
  describe (communityDid = null) {
    const feeds = communityDid ? this.feeds.filter((f) => f.communityDid === communityDid) : this.feeds
    const out = { feeds: feeds.map((f) => ({ uri: this.feedUri(f.communityDid, f.rkey) })) }
    if (communityDid) out.did = communityDid
    return out
  }

  // The at:// uri of a hosted feed — under the COMMUNITY DID (its own repo holds the record).
  feedUri (communityDid, rkey) { return `at://${communityDid}/${GENERATOR_COLLECTION}/${rkey}` }

  // Validate a getFeedSkeleton `feed` param (atproto contract). The uri's hostname is the community DID;
  // accept iff it's the generator collection and (communityDid, rkey) is a hosted feed. Returns the feed
  // entry, or throws UnsupportedAlgorithm ({ status:400, error:'UnsupportedAlgorithm' }).
  resolve (feedUri) {
    const parsed = parseFeedUri(feedUri)
    if (!parsed || parsed.collection !== GENERATOR_COLLECTION || !this.has(parsed.hostname, parsed.rkey)) {
      const e = new Error('Unsupported algorithm'); e.status = 400; e.error = 'UnsupportedAlgorithm'; throw e
    }
    return this.feed(parsed.hostname, parsed.rkey)
  }

  // Build the skeleton for one hosted community feed by running the community's CURATION CONTRACT
  // ({ curator, params }) over the appview (architecture.md "Feeds are curation functions"). Injected:
  //   rosterOf(roomKey)                     => member DIDs (array/Set)      — the roster substrate (WHO)
  //   curationOf(roomKey)                   => { curator, params }          — the curation contract (HOW)
  //   getTimeline({authors,limit,cursor})   => { posts, cursor }            — appview, author-scoped
  //   getTagFeed(tag,{limit,cursor})        => { posts, cursor }            — appview, tag-scoped
  // makeCurator resolves the contract to a PAGER; we page it, keeping ONLY bsky posts and over-fetching to
  // backfill locals dropped by isBskyPost, so a page still tends to yield `limit` bsky entries. curationOf
  // is OPTIONAL — omitted (or absent contract) => roster curation, favela-web's historical default, so
  // callers that don't pass it (and pre-curation rooms) behave exactly as before. bsky-neutral: the output
  // is always { feed:[{post}], cursor } of app.bsky.feed.post URIs.
  async skeleton (algo, { rosterOf, curationOf = null, getTimeline, getTagFeed = null, limit = 50, cursor = null } = {}) {
    const roster = new Set(await rosterOf(algo.roomKey))
    const curation = curationOf ? await curationOf(algo.roomKey) : { curator: 'roster', params: {} }
    const pager = makeCurator(curation, { roster, queries: { getTimeline, getTagFeed } })
    const feed = []
    let cur = cursor
    // Page through the curator's stream until we have `limit` bsky posts or it is exhausted.
    while (feed.length < limit) {
      const page = await pager({ limit, cursor: cur })
      for (const p of page.posts) { if (isBskyPost(p) && isValidPostRkey(p.rkey)) feed.push({ post: postUri(p.did, p.rkey) }) }
      cur = page.cursor
      if (!cur || !page.posts.length) break
    }
    // atproto: `cursor` is an OPTIONAL string — it must be a string or ABSENT, never JSON null. An exhausted
    // pager leaves `cur === null`; emitting `{cursor: null}` fails bsky's XRPC response-schema validation
    // (cursor is typed `string`) → the AppView rejects the ENTIRE feed with InvalidFeedResponse (a feed that
    // reads as "broken" on bsky). So OMIT the field when there is no next page: present string = more pages,
    // absent = end of feed. (This is the actual InvalidFeedResponse cause, distinct from the TID filter above.)
    const out = { feed: feed.slice(0, limit) }
    if (cur) out.cursor = cur
    return out
  }
}

export default FeedGenerator
// followers.js — who follows a DID, across the whole network. DESIGN §7.6 Tier C.
//
// WHY THIS IS NOT IN THE APPVIEW. `av.followers(did)` counts only follows authored by DIDs this node
// INDEXES — its roster. A bsky account following you is invisible to it, not because anything is broken
// but because we never replicate that account's repo. Asking the local index for a network-wide fact
// gets a window-local answer, which is exactly the mistake §7.6 exists to prevent.
//
// TIER C: REFERENCED, NEVER RETAINED. A follow is countable, not content — there is nothing to render
// from the record itself beyond "this DID follows that DID". So we answer from a backlink index on
// demand and store NOTHING. No fetch, no verify, no write. That matters twice over: it costs no disk,
// and (after 2026-07-31) a read-only path cannot corrupt hpp's canonical store.
//
// ⛔ NEVER BLEND THE COUNTS. bsky's follower number is network-wide; ours is window-local. A sum means
// nothing, and silently substituting one for the other is worse — it makes a partial view look total.
// The caller gets both, separately labelled, and the render layer must keep them apart. lens-import.js
// makes the same refusal for the same reason.
//
// HANDLES ARE VERIFIED, NOT CLAIMED. Each follower DID is resolved through the bidirectional handle
// resolver, so an impostor DID claiming someone's handle shows as handle.invalid rather than as them.
// A follower list is exactly the surface where impersonation would pay.
//
// PURE + INJECTED. constellation, handles and the clock are parameters — no network in tests.

const FOLLOW_SOURCE = 'app.bsky.graph.follow:subject'
const TTL_MS = 5 * 60 * 1000
const DEFAULT_RESOLVE = 24 // how many follower handles to resolve for display
const RESOLVE_CONCURRENCY = 8
const RESOLVE_DEADLINE_MS = 2500 // hard cap on the WHOLE resolution phase

export function createFollowerLens ({
  constellation, // createConstellationClient(...)
  handles = null, // createHandleResolver(...) — optional; without it, DIDs render unresolved
  ttlMs = TTL_MS,
  resolveLimit = DEFAULT_RESOLVE,
  // Handle resolution is NETWORK work (PLC + a well-known probe + possibly DNS) and it sits on the
  // render path. Serially, 24 followers with unreachable hosts took >90s and hung the profile page —
  // measured, not hypothetical. Bounded parallelism plus a hard deadline: whatever has not resolved
  // when the deadline fires renders as a DID, which is the same graceful degradation used elsewhere.
  concurrency = RESOLVE_CONCURRENCY,
  deadlineMs = RESOLVE_DEADLINE_MS,
  now = () => Date.now()
} = {}) {
  if (!constellation) throw new Error('createFollowerLens requires constellation')

  const cache = new Map()

  return {
    // -> { count, followers: [{ did, handle, verified }], shown, truncated } | null
    //
    // `count` is the NETWORK total from the index; `followers` is the resolved prefix we display.
    // `truncated` says plainly that the list is shorter than the count, so the UI never implies it is
    // showing everyone.
    async followersOf (did) {
      if (typeof did !== 'string' || !did.startsWith('did:')) return null
      const hit = cache.get(did)
      if (hit && hit.expires > now()) return hit.value

      let value = null
      try {
        const count = await constellation.countBacklinks(did, FOLLOW_SOURCE)
        const page = await constellation.getBacklinks(did, FOLLOW_SOURCE, { limit: resolveLimit })
        if (count !== null || page !== null) {
          // A follow record's AUTHOR is the follower; the subject is who they followed.
          const dids = page ? [...new Set(page.pointers.map((p) => p.did))] : []
          const resolved = new Map()
          if (handles && dids.length) {
            // Race the whole phase against a deadline; each worker also stops once it fires, so a slow
            // host delays one follower's NAME, never the page.
            let expired = false
            const timer = new Promise((r) => setTimeout(() => { expired = true; r() }, deadlineMs))
            const queue = dids.slice()
            const workers = Array.from({ length: Math.min(concurrency, queue.length) }, () => (async () => {
              while (queue.length && !expired) {
                const d = queue.shift()
                try { const h = await handles.resolve(d); if (h) resolved.set(d, h) } catch { /* renders as a DID */ }
              }
            })())
            await Promise.race([Promise.all(workers), timer])
          }
          const followers = dids.map((d) => {
            const h = resolved.get(d)
            return { did: d, handle: h && h.verified ? h.handle : null, verified: !!(h && h.verified) }
          })
          const total = count !== null ? count : followers.length
          value = { count: total, followers, shown: followers.length, truncated: followers.length < total }
        }
      } catch {
        value = null // fail soft — a follower list must never break a profile page
      }
      cache.set(did, { value, expires: now() + (value === null ? 60_000 : ttlMs) })
      return value
    },

    // Count only — cheap enough to call per profile render without the handle resolution.
    async countOf (did) {
      const r = await this.followersOf(did)
      return r ? r.count : null
    }
  }
}
// fronts-diag — which co-owner's firehose is this node actually following, and why?
//
// WHY THIS EXISTS. A co-owned DID is served by several co-owners, each with its own firehose core.
// DidPeerRouter picks one ("the freshest front") by ranking verified fronts on head.rev, preferring live
// ones, behind a continuity gate. When that choice is wrong the index FREEZES at the failover point while
// every other surface looks healthy: the peer is connected, the daemon is up, backfill reports success,
// and the profile page renders — it is simply missing everything appended since.
//
// That is not hypothetical. favela-web's own ingest loop carries the comment "wj62/ashatron both froze at
// their July co-owner failovers", and on 2026-07-30 ashatron was found ~42h stale on wj62 while both
// co-owners held 151 records. Diagnosing it from outside was impossible: nothing exposed which front was
// chosen, what rev each offered, or how long their firehoses were. Four restarts and a from-zero backfill
// all reported success and changed nothing.
//
// So this reports the INPUTS to the decision, not just its outcome. `chosen` alone would say what
// happened; rev/live/firehoseLength per front say WHY, and make "we are pinned to a short line" visible
// at a glance instead of inferable after an afternoon.
//
// READS ROUTER INTERNALS (_fronts, _byDid, _freshestFront, front._firehoseKey/head/seq). atproto-did-peer
// exposes no public accessor for them — its announce payloads carry firehoseLength but there is no
// status(). Same bargain hpp's conflict-diag made: hooking internals is worse than being handed an API,
// and better than a failure mode nobody can see. If this earns its keep, push it upstream.
//
// Defensive throughout: a half-open front, a peer mid-handshake or a shape change upstream must degrade
// to nulls, never throw. A diagnostic that can 500 the page it is meant to explain is worthless.

const hex = (b) => {
  try { return typeof b === 'string' ? b : (b ? Buffer.from(b).toString('hex') : null) } catch { return null }
}

export function frontsDiag (router, dids = null) {
  const at = new Date().toISOString()
  if (!router || !router._fronts) return { at, error: 'no router', dids: [] }

  const targets = Array.isArray(dids) && dids.length ? dids : [...router._fronts.keys()]
  const out = []

  for (const did of targets) {
    const set = router._fronts.get(did) || new Map()
    const live = (router._byDid && router._byDid.get(did)) || new Map()

    // The router's own answer, asked the same way the ingest loop asks it.
    let chosenKey = null
    try {
      const f = router._freshestFront(did)
      chosenKey = f && f._firehoseKey ? hex(f._firehoseKey) : null
    } catch { chosenKey = null }

    const fronts = []
    for (const [key, f] of set) {
      let firehoseLength = null
      try { firehoseLength = (f && f.seq && f.seq.core) ? f.seq.core.length : null } catch {}
      const rev = (f && f.head && f.head.rev) ? f.head.rev : null
      fronts.push({
        firehoseKey: key,
        short: typeof key === 'string' ? key.slice(0, 12) : null,
        // `live` is the router's own liveness map — a front can be known (announced) without a live
        // connection, and the ranking prefers live ones, so the distinction is load-bearing.
        live: live.has(key),
        // Only fronts with a verified head are ranked at all; an unverified one is invisible to the
        // choice, which is itself a reason a node can end up on an older front.
        verified: !!rev,
        rev,
        firehoseLength,
        chosen: chosenKey != null && key === chosenKey
      })
    }

    // Highest rev first — the order the ranking sees, so a chosen front that is NOT at the top is
    // immediately visible as the anomaly worth explaining (continuity gate, or not live).
    fronts.sort((a, b) => String(b.rev || '').localeCompare(String(a.rev || '')))

    const chosen = fronts.find((f) => f.chosen) || null
    const best = fronts.find((f) => f.verified) || null
    out.push({
      did,
      frontCount: fronts.length,
      chosen: chosen ? chosen.short : null,
      // The one-line answer an operator wants: are we on the highest-rev line, and is the line we are on
      // shorter than one we can see? Either being true is the freeze signature.
      onHighestRev: !!(chosen && best && chosen.firehoseKey === best.firehoseKey),
      behindBy: (chosen && best && Number.isFinite(chosen.firehoseLength) && Number.isFinite(best.firehoseLength))
        ? best.firehoseLength - chosen.firehoseLength
        : null,
      fronts
    })
  }

  return { at, dids: out }
}
// Gate policy — the two decisions 5B adds, kept PURE so they can be reasoned about without a swarm.
//
//   makeIsMember(communities) -> isMember(did)   WHO may participate
//   siteVisibility(metas)     -> 'public'|'members'   WHETHER an anonymous visitor sees the site
//
// Both read state that already exists: the community room's roster (`member:<did>`, via
// Communities.communitiesFor) and its meta (`set-meta {key,value}`, already in favela-community's
// schema — `visibility` is just another key, so this needs NO schema change and no migration).
//
// ⛔ These gate the BROWSER-FACING site only. `getFeedSkeleton` and the rest of the lens export stay
// public regardless: bsky's AppView calls them anonymously, so gating them on membership would
// silently break the community's bsky feed — the exact surface the community publishes ON PURPOSE.

export const PUBLIC = 'public'
export const MEMBERS = 'members'

/**
 * Build the `isMember(did)` policy `requireMember` takes.
 *
 * FAILS CLOSED. Communities.rosterOf already stale-serves a last-good roster and yields an empty Set
 * when a room cannot be read, so an unreachable room reports "not a member" rather than "everyone".
 * A resolver that throws outright is caught here to the same effect — an unreachable room is not
 * consent, and this is the one place where being wrong grants someone else's rights.
 */
export function makeIsMember (communities) {
  return async function isMember (did) {
    if (!did || !communities || typeof communities.communitiesFor !== 'function') return false
    try {
      const mine = await communities.communitiesFor(did)
      return Array.isArray(mine) && mine.length > 0
    } catch {
      return false
    }
  }
}

/**
 * Should the SSR site render for an anonymous visitor?
 *
 * DEFAULT IS PUBLIC, deliberately: this flag exists so a community can CLOSE its site, and a node
 * that never sets it must behave exactly as it does today. A flag that changed behaviour on arrival
 * would be an outage dressed as a feature.
 *
 * With several communities on one node, ONE public community keeps the site open — closing it would
 * hide content another community chose to publish. Per-community closure is the stricter rule and
 * wants per-community routing, which this node does not have yet.
 *
 * @param {Array<{visibility?: string}>} metas - each configured community's room meta
 */
export function siteVisibility (metas) {
  if (!Array.isArray(metas) || metas.length === 0) return PUBLIC
  const closed = (m) => String((m && m.visibility) || '').trim().toLowerCase() === MEMBERS
  // Every community must ASK to be closed. An unrecognised value is not a request to close.
  return metas.every(closed) ? MEMBERS : PUBLIC
}


// Paths that must stay reachable even when a community closes its site.
//
// ⛔ THIS LIST IS LOAD-BEARING. Close the site without it and you brick the way IN: a visitor who
// cannot reach /login or /api/auth/* can never stop being anonymous, so "members only" becomes
// "nobody, ever". The lens export is exempt for a different reason — bsky's AppView calls /xrpc
// ANONYMOUSLY, so gating it would silently break the very feed the community publishes on purpose.
const EXEMPT_PREFIXES = [
  '/xrpc/',        // lens export (getFeedSkeleton, describeFeedGenerator, queryLabels) — bsky reads these
  '/.well-known/', // did:web + atproto-did identity resolution
  '/api/auth/',    // challenge -> sign -> session
  '/static/',      // the assets /login itself needs
  '/auth/handoff'  // embedded-WebView session handoff (loopback-gated on its own)
]
const EXEMPT_EXACT = new Set(['/login', '/logout', '/favicon.ico', '/robots.txt'])

/** May an ANONYMOUS request reach this path even on a closed site? */
export function isPublicPath (path) {
  const p = String(path || '')
  if (EXEMPT_EXACT.has(p)) return true
  return EXEMPT_PREFIXES.some((pre) => p.startsWith(pre))
}

export default { makeIsMember, siteVisibility, isPublicPath, PUBLIC, MEMBERS }
// handles.js — resolve a DID to a DISPLAYABLE, VERIFIED handle.
//
// WHY THIS IS NOT JUST READING alsoKnownAs. A DID document's `alsoKnownAs` is a CLAIM MADE BY THE DID,
// not proof. Anyone can mint a did:plc whose document says `at://fleeky.bsky.social` and, if we rendered
// that, they would appear in the UI as that person. atproto's rule is BIDIRECTIONAL verification: the
// handle must independently resolve BACK to the same DID. Unverified handles must render as
// `handle.invalid` (the same convention Slingshot and @atproto/identity use), never as the bare claim.
//
// This matters more here than in a normal client: our inbound lens retains records authored by arbitrary
// foreign DIDs discovered through a third-party index. Impersonation is the obvious attack on a UI that
// shows names next to content, and displaying an unverified claim is exactly how it lands.
//
// TWO MECHANISMS, because atproto specifies either:
//   1. HTTPS  — GET https://<handle>/.well-known/atproto-did  -> the DID as plain text
//   2. DNS    — TXT _atproto.<handle>                          -> "did=<did>"
// MEASURED 2026-07-31: BOTH handles we actually serve verify over HTTPS — p2p.7rnx.net (self-hosted)
// and fleeky.bsky.social (bsky-hosted) each return their DID from the well-known path, and
// `dig TXT _atproto.fleeky.bsky.social` returns nothing. So HTTPS carries the load today. DNS is
// implemented anyway because the spec permits it and some self-hosted handles use only that — a handle
// we cannot verify renders as handle.invalid, so a missing mechanism costs real names, not just
// coverage.
//
// PURE + INJECTED. `doFetch`, `resolveTxt` and `now` are parameters, so both verification paths, the
// mismatch case and the cache are testable with no network and no DNS.

const TTL_MS = 30 * 60 * 1000 // handles change rarely; a rename is what this lags on
const NEG_TTL_MS = 5 * 60 * 1000

// `alsoKnownAs: ['at://fleeky.bsky.social']` -> 'fleeky.bsky.social'. Returns null for anything that is
// not an at:// handle URI (the field is a list of arbitrary URIs by spec).
export function claimedHandle (alsoKnownAs) {
  if (!Array.isArray(alsoKnownAs)) return null
  for (const aka of alsoKnownAs) {
    if (typeof aka !== 'string' || !aka.startsWith('at://')) continue
    const h = aka.slice(5).trim().toLowerCase()
    // A handle is a domain name. Reject anything with a path/query, or that is obviously not one.
    if (!h || h.includes('/') || h.includes('?') || !h.includes('.')) continue
    return h
  }
  return null
}

// A DNS TXT record set for _atproto.<handle> may contain several strings; the DID is the one shaped
// `did=...`. Chunked TXT values arrive as arrays and must be joined before matching.
export function didFromTxt (records) {
  if (!Array.isArray(records)) return null
  for (const r of records) {
    const s = Array.isArray(r) ? r.join('') : String(r)
    const m = s.trim().match(/^did=(did:[a-z0-9:._%-]+)$/i)
    if (m) return m[1]
  }
  return null
}

// What the UI should show, in preference order. Never the raw claim when unverified.
export function displayHandle (resolved) {
  if (!resolved || !resolved.handle) return null
  return resolved.verified ? resolved.handle : 'handle.invalid'
}

export function createHandleResolver ({
  plc, // PlcDirectory-like: getData(did) -> { alsoKnownAs, ... }
  doFetch, // for the .well-known probe
  resolveTxt = null, // async (name) -> string[]|string[][]; null disables the DNS path
  ttlMs = TTL_MS,
  now = () => Date.now()
} = {}) {
  if (!plc) throw new Error('createHandleResolver requires plc')
  if (typeof doFetch !== 'function') throw new Error('createHandleResolver requires doFetch')

  const cache = new Map()

  // Does `handle` independently resolve back to `did`? Either mechanism suffices.
  async function verifies (handle, did) {
    // 1. HTTPS well-known.
    try {
      const res = await doFetch(`https://${handle}/.well-known/atproto-did`, {
        method: 'GET',
        headers: { accept: 'text/plain' },
        timeout: 5000
      })
      if (res && res.ok !== false) {
        const txt = (await res.text()).trim()
        if (txt === did) return 'well-known'
      }
    } catch { /* fall through to DNS — an unreachable host is not a verdict */ }

    // 2. DNS TXT.
    if (typeof resolveTxt === 'function') {
      try {
        const recs = await resolveTxt(`_atproto.${handle}`)
        if (didFromTxt(recs) === did) return 'dns'
      } catch { /* no record / NXDOMAIN — not verified, not an error */ }
    }
    return null
  }

  return {
    // -> { did, handle, verified, via } | null. `handle` is the CLAIM; consult `verified` before
    // showing it, or use displayHandle() which enforces that for you.
    async resolve (did) {
      if (typeof did !== 'string' || !did.startsWith('did:')) return null
      const hit = cache.get(did)
      if (hit && hit.expires > now()) return hit.value

      let value = null
      try {
        const data = await plc.getData(did)
        const handle = claimedHandle(data && data.alsoKnownAs)
        if (handle) {
          const via = await verifies(handle, did)
          value = { did, handle, verified: via !== null, via }
        }
      } catch {
        value = null // network/404 — retry sooner than a success
      }
      cache.set(did, { value, expires: now() + (value === null ? NEG_TTL_MS : ttlMs) })
      return value
    },

    get size () { return cache.size }
  }
}

// bare-dns is callback-style; wrap it for the daemon. Kept here so the resolver itself stays runtime
// agnostic and node-testable (bare-dns pulls a native addon that cannot load under node).
export function bareResolveTxt (dns) {
  return (name) => new Promise((resolve, reject) => {
    dns.resolveTxt(name, (err, records) => (err ? reject(err) : resolve(records)))
  })
}
// Which DIDs does the LOCAL hpp actually host?
//
// ⛔ THE BUG THIS EXISTS TO CLOSE (2026-08-06). `isForeign` gates whether the appview may CREATE record
// bytes, and bin/favela-web.js supplied it as `(did) => !ROSTER.includes(did)`. But the guard in
// lib/appview.js means something narrower, and says so itself: "for a foreign peer NO LOCAL HPP HOLDS,
// we remain the only writer". Roster membership and local hosting are the same set on tabertron (hpp
// hosts wj62, and wj62 is on the roster) and DIFFERENT on ashatron (hpp hosts only e2jev, yet wj62 is
// on its roster). On ashatron every wj62 post was therefore refused — "hpp owns these" — while no local
// hpp would ever author them. Its appview froze at 2026-07-31T18:49, hours after the guard landed
// (d78f2e4), and neither restarting hpp nor favela-web could clear it: the refusal was working as coded.
//
// The authority for the answer is hpp's own config: `dids[]` is exactly the set it boots and serves
// (lib/config.js -> bootMultiDevice, and lib/diag.js reads the same array to decide what to probe).
// We take the DID strings and nothing else — the file also holds device mnemonics.
//
// No RPC and no boot ordering: a plain read of a file that is present whether or not hpp is up. When the
// answer is UNKNOWN (absent/unreadable/malformed) we return null and the caller falls back to the roster
// — the OLD behaviour, which is the conservative direction. Roster ⊇ hosted, so falling back can only
// refuse MORE writes, never permit one the previous version refused.

// Pure: parse hpp's config.json text -> the DIDs it hosts. null means "unknown", which is NOT the same
// as "hosts nothing" — the caller must distinguish, because empty would make every DID foreign and
// re-open the clobber the guard was built to stop.
export function parseHostedDids (text) {
  if (typeof text !== 'string' || text.length === 0) return null
  let cfg
  try { cfg = JSON.parse(text) } catch { return null }
  if (!cfg || !Array.isArray(cfg.dids)) return null
  const dids = cfg.dids
    .map((d) => (d && typeof d.did === 'string' ? d.did.trim() : null))
    .filter((d) => d && d.startsWith('did:'))
  // A `dids` array that parsed but named nothing usable is malformed, not an empty fleet.
  return dids.length ? dids : null
}

// The one definition of "ours", used by BOTH the appview create-gate and the retention scope so they
// cannot drift apart (bin/favela-web.js wired the same expression twice by hand before this).
//
// A DID is OURS only when the local hpp hosts it — that is the whole correction. Everything else is
// foreign, which is what licenses us to author its bytes, and what keeps an ingested repo from freezing
// at its first-seen version.
export function createIsForeign ({ hosted, roster = [] } = {}) {
  const known = Array.isArray(hosted) && hosted.length > 0
  const ours = new Set(known ? hosted : roster)
  return (did) => !ours.has(did)
}

// ---- IGNORED-BY-POLICY collections (spec/convergence.md §2.1) ---------------------------------------
//
// Collections we deliberately do not index. This is a DECISION list, not a dumping ground: each entry
// carries the reason, because "we don't use it" is not one. Anything not tracked and not here is
// UNKNOWN — a lexicon nobody has classified.
//
// Both classes are now reported rather than dropped, on BOTH sides of the question: `diff` classifies the
// authority's records (0.3.43), and the appview's ingest ledger records what actually arrives here
// (0.3.47, spec §2.2) — which is what `applyCommit`'s final bare `continue` discarded in silence.
export const IGNORED_COLLECTIONS = new Map([
  ['chat.bsky.actor.declaration',
    'DM policy (allowIncoming/allowGroupInvites) consumed by bsky\'s chat service, which we do not run. ' +
    'Referenced nowhere in this stack. The repo carries it and it still federates; we have no surface to render it.'],
  ['net.favela.test',
    'Our own debugging debris ("delete-tip-fix verification", 2026-07-24). Referenced nowhere. Retained ' +
    'in the repo because nothing here deletes from a repo.']
])

export const isIgnoredCollection = (c) => IGNORED_COLLECTIONS.has(c)
// inbound.js — DESIGN §7.6's inbound arm, assembled. One controller the daemon starts and stops.
//
// This is only composition: SpacedustClient (live edge) + Constellation (historical floor) + LinkDrain
// (tier routing) + retention hooks (fetch/verify/retain/evict). Every part is tested on its own; what
// this adds is the wiring, the roster binding, and the reconnect gap-fill.
//
// DEFAULT OFF. The daemon constructs this only when explicitly configured. An always-on subscription to
// a third-party service is not something a node should inherit by upgrading.
//
// THE ROSTER IS THE FILTER. `wantedSubjectDids` = the DIDs we serve, so spacedust sends only links that
// touch our own content — §7.6's "one hop from our records", enforced server-side rather than by
// discarding a firehose locally. Caps are 10k DIDs / 1k sources, far above a community.
//
// CONTENT-BEARING SOURCES ONLY. We deliberately do NOT subscribe to likes/reposts/follows. The drain
// would skip them anyway (Tier C), so subscribing would spend bandwidth to deliver events we discard.
// Counts come from Constellation on demand — that is the whole point of the tiering.
//
// RECONNECT MEANS BACKFILL. /subscribe has no cursor and replays nothing, so every reconnect leaves a
// gap. On each (re)connect we walk Constellation for OUR OWN RECORD at-uris (not our DIDs — see the
// asymmetry note on backfill()) and push those pointers into the same drain. Pointer shapes are
// identical, so they dedup against whatever the live stream already handled.

import { SpacedustClient, SOURCES, CONTENT_BEARING } from './spacedust.js'
import { LinkDrain } from './link-drain.js'
import { createConstellationClient } from './constellation.js'
import { createFetchRecord, createVerifyRecord, createIdentityResolver } from './record-fetch.js'
import { createRetentionHooks } from './retention.js'

// Only the sources that carry text. Derived from CONTENT_BEARING so the two can never drift.
export const DEFAULT_SOURCES = Object.values(SOURCES).filter((s) => CONTENT_BEARING.has(s))

export function createInboundLens ({
  roster = [], // DIDs we serve — the subject filter
  openStore, // async (did) -> OverlayRepoStore   (the daemon's getRecordStore)
  appview = null, // the Appview, for the index fold
  index, // retention index (bee-backed in production)
  doFetch, // bare-fetch
  createSocket, // from spacedust-socket.js
  listSubjectUris = null, // async (rosterDids) -> [at-uri]  OUR OWN records to ask Constellation about.
                          // Required for backfill: Constellation matches subjects EXACTLY, so DIDs
                          // match nothing. See the note on backfill() below.
  plc = null, // optional PlcDirectory override (tests)
  endpoint = undefined,
  constellationEndpoint = undefined,
  budgetBytes = null,
  sources = DEFAULT_SOURCES,
  backfillPages = 2,
  backfillRetryMs = 5000, // cold start: the appview is EMPTY until the P2P ingest lands (see start())
  backfillRetries = 6,
  onEvent = null
} = {}) {
  if (typeof openStore !== 'function') throw new Error('createInboundLens requires openStore')
  if (typeof doFetch !== 'function') throw new Error('createInboundLens requires doFetch')
  if (typeof createSocket !== 'function') throw new Error('createInboundLens requires createSocket')
  if (!index) throw new Error('createInboundLens requires an index')

  const emit = (ev, detail) => { if (onEvent) onEvent(ev, detail) }

  const resolveIdentity = createIdentityResolver({ fetchImpl: doFetch, plc })
  const retention = createRetentionHooks({ openStore, appview, index, budgetBytes, onEvent })
  const constellation = createConstellationClient({
    doFetch,
    ...(constellationEndpoint ? { endpoint: constellationEndpoint } : {})
  })

  let subjects = roster.slice()

  const client = new SpacedustClient(
    { subjectDids: subjects, sources },
    { createSocket, ...(endpoint ? { endpoint } : {}) }
  )

  const drain = new LinkDrain(client, {
    fetchRecord: createFetchRecord({ doFetch, resolveIdentity }),
    verifyRecord: createVerifyRecord({ onFailure: (reason, p) => emit('verify-failed', { reason, pointer: p }) }),
    retainRecord: retention.retainRecord,
    evictRecord: retention.evictRecord,
    knownRev: retention.knownRev
  })

  let backfills = 0
  let running = false
  let lastUris = 0 // how many of OUR at-uris the last sweep had to ask about
  let retryTimer = null
  let retriesLeft = backfillRetries

  // Push Constellation's historical pointers into the drain's queue. Uses the client's own enqueue path
  // so backfilled and live pointers share one bounded queue and one dedup surface.
  //
  // ⛔ SUBJECTS HERE ARE at-uris, NOT DIDs — the two services are NOT symmetric, measured live 2026-07-30.
  // Spacedust filters on `subject_did`, which its source documents as matching "both bare-DIDs and DIDs
  // extracted from at-uris", so the LIVE filter is correctly keyed by roster DID. Constellation's
  // `subject` is an EXACT target with no such extraction: a reply's reply.parent.uri is always
  // `at://did/collection/rkey` and never a bare DID, so querying subject=<our DID> against a
  // content-bearing source matches NOTHING, always. That returned 0 and looked exactly like a quiet
  // roster — the silent-zero failure this design keeps warning about.
  //
  // So backfill needs OUR OWN RECORD at-uris, which only the caller can enumerate (they come from the
  // appview). With no provider we do NOT fall back to DID queries — that is the bug, not a degraded
  // mode — we skip and say so.
  async function backfill () {
    if (subjects.length === 0) return 0
    if (typeof listSubjectUris !== 'function') {
      emit('backfill-skipped', { reason: 'no listSubjectUris provider — DID subjects match nothing in Constellation' })
      return 0
    }

    lastUris = 0
    let uris = []
    try {
      uris = (await listSubjectUris(subjects)) || []
    } catch (err) {
      emit('backfill-skipped', { reason: 'listSubjectUris failed', error: (err && err.message) || String(err) })
      return 0
    }
    lastUris = uris.length
    if (uris.length === 0) {
      emit('backfill', { offered: 0, duplicates: 0, uris: 0, note: 'no own records to ask about yet' })
      return 0
    }

    const { offered, duplicates } = await constellation.backfillInto(
      (pointer) => client.enqueue(pointer),
      { subjects: uris, sources, maxPages: backfillPages, onTruncate: (t) => emit('backfill-truncated', t) }
    )
    backfills++
    // `duplicates` is the cross-source collapse (one reply links via parent AND root). Reported because
    // a silently-deduped sweep and an empty sweep look identical from the outside.
    emit('backfill', { offered, duplicates, uris: uris.length })
    return offered
  }

  // COLD START IS A RACE, and losing it is silent. `inbound.start()` runs as soon as the daemon has an
  // Appview, but the P2P ingest that POPULATES that appview finishes later — observed live: the sweep
  // logged `uris: 0` and only then did `ingest: backfill complete` arrive. A one-shot backfill therefore
  // asks about nothing at boot and never asks again, which reads exactly like "nobody has replied to us".
  //
  // Retrying rather than hooking the ingest lifecycle keeps this decoupled and also covers the honest
  // second case: a roster DID that genuinely has no posts yet. Bounded, so a permanently-empty roster
  // costs a handful of no-op calls, not a poll forever.
  async function backfillWithRetry () {
    const offered = await backfill()
    if (running && lastUris === 0 && retriesLeft > 0) {
      retriesLeft--
      emit('backfill-retry', { retriesLeft, delayMs: backfillRetryMs, reason: 'no own records indexed yet' })
      retryTimer = setTimeout(() => {
        retryTimer = null
        backfillWithRetry().catch(() => {}) // fail soft — a retry must never take the daemon down
      }, backfillRetryMs)
    }
    return offered
  }

  return {
    get stats () {
      return {
        running,
        subjects: subjects.length,
        sources: sources.length,
        backfills,
        backfillUris: lastUris,
        backfillRetriesLeft: retriesLeft,
        socket: client.stats,
        drain: drain.stats,
        retention: retention.stats,
        pending: client.pending
      }
    },

    async start () {
      if (running) return this
      running = true
      client.start()
      drain.start()
      // Cold start is a gap by definition — everything that happened while we were down. Retries
      // because the appview is not populated yet at this point (see backfillWithRetry).
      await backfillWithRetry()
      emit('started', { subjects: subjects.length, sources })
      return this
    },

    // Roster changed: update the server-side filter WITHOUT reconnecting, then backfill the newcomers.
    async updateRoster (dids) {
      const next = (dids || []).filter(Boolean)
      const added = next.filter((d) => !subjects.includes(d))
      subjects = next
      client.updateFilter({ subjectDids: subjects })
      // A new member's HISTORY needs their own record at-uris, for the same reason cold start does —
      // `added` is a list of DIDs and would match nothing. Re-running the provider is the honest way to
      // pick them up; it returns the union for the current roster.
      if (added.length > 0) {
        retriesLeft = backfillRetries // a new member's posts may not be indexed yet either
        const offered = await backfillWithRetry()
        emit('roster-backfill', { added: added.length, offered })
      }
      emit('roster-updated', { subjects: subjects.length })
      return subjects.length
    },

    backfill,

    async stop () {
      running = false
      if (retryTimer !== null) { clearTimeout(retryTimer); retryTimer = null }
      client.close()
      await drain.stop()
      emit('stopped', {})
    }
  }
}
// label-firehose.js — com.atproto.label.subscribeLabels: the LIVE-PUSH surface bsky's AppView/Ozone
// ingests (lens export §3.6, moderation half; the push counterpart to lib/labeler-export.js's queryLabels).
//
// The atproto wire format (matches atproto-store/lib/firehose.js's subscribeRepos framing): each WS binary
// message = dag-cbor(header {t:'#labels', op:1}) ++ dag-cbor(body {seq, labels:[label…]}). Labels are the
// com.atproto.label.defs#label objects with `sig` as raw bytes (DAG-CBOR carries bytes natively — NOT the
// JSON { $bytes } form queryLabels uses). A subscriber connects with ?cursor=<lastSeq>; the server replays
// from there, then live-tails. seq is a 1-based monotonic index over the labeler's feed.
import * as dagCbor from '@ipld/dag-cbor'
import { decodeLabel } from 'atproto-identity/lib/labels.js'

const LABELS_HEADER = dagCbor.encode({ t: '#labels', op: 1 })
const ERROR_HEADER = dagCbor.encode({ op: -1 })

function concat (a, b) { const out = new Uint8Array(a.length + b.length); out.set(a, 0); out.set(b, a.length); return out }

// One subscribeLabels frame: header ++ dag-cbor({ seq, labels }). labels = signed label objects (sig bytes).
export function labelFrame (seq, labels) { return concat(LABELS_HEADER, dagCbor.encode({ seq, labels })) }

// An error frame ({ op:-1 } ++ { error, message }) — e.g. FutureCursor when the client's cursor is ahead.
export function errorFrame (error, message = '') { return concat(ERROR_HEADER, dagCbor.encode({ error, message })) }

// Decode a subscribeLabels frame (for tests / a consumer): → { t, body } or { op:-1, body } or null.
export function decodeLabelsFrame (bytes) {
  if (bytes.length >= LABELS_HEADER.length && Buffer.from(bytes.subarray(0, LABELS_HEADER.length)).equals(Buffer.from(LABELS_HEADER))) {
    return { t: '#labels', body: dagCbor.decode(bytes.subarray(LABELS_HEADER.length)) }
  }
  if (bytes.length >= ERROR_HEADER.length && Buffer.from(bytes.subarray(0, ERROR_HEADER.length)).equals(Buffer.from(ERROR_HEADER))) {
    return { op: -1, body: dagCbor.decode(bytes.subarray(ERROR_HEADER.length)) }
  }
  return null
}

export class LabelFirehose {
  // core: a hypercore of encoded labels (the labeler's feed — each block = dag-cbor(signed label)). Needs
  // { length, get(i), on/off('append'), ready }.
  constructor (core) { this.core = core }

  async ready () { if (this.core.ready) await this.core.ready(); return this }

  // Serve one subscriber. send(bytes) writes a binary WS message. cursor = the last seq the client holds
  // (0/absent → from the start). Replays [cursor, head) then live-tails on append. Runs are serialized +
  // coalesced (append during a replay re-runs after) so no frame is skipped/duplicated. If cursor is past
  // the head, sends a FutureCursor error frame first. Returns stop() to detach the append listener.
  serve (send, { cursor = 0 } = {}) {
    let closed = false
    let running = false
    let pending = false
    let i = Math.max(0, Number(cursor) || 0) // seq = i+1, so start index = cursor
    if (i > this.core.length) { try { send(errorFrame('FutureCursor', 'cursor is past the labeler head')) } catch {} ; i = this.core.length }
    const pump = async () => {
      if (running) { pending = true; return }
      running = true
      try {
        while (!closed && i < this.core.length) {
          const idx = i++
          try { send(labelFrame(idx + 1, [decodeLabel(await this.core.get(idx))])) } catch {}
        }
      } finally { running = false }
      if (!closed && pending) { pending = false; return pump() }
    }
    const onAppend = () => { pump().catch(() => {}) }
    this.core.on('append', onAppend)
    pump().catch(() => {})
    return () => { if (closed) return; closed = true; this.core.off('append', onAppend) }
  }
}

export default LabelFirehose
// labeler-export.js — favela's LENS EXPORT to bsky, moderation half (DESIGN §3.6): expose favela's own
// signed labels over the atproto labeler surfaces so bsky users can SUBSCRIBE to favela moderation.
//
// This is the EMITTER side (the inverse of lib/labeler.js's reader). favela produces com.atproto.label
// records (byte-exact: DAG-CBOR + secp256k1 low-S over the sig-less bytes, atproto-identity/lib/labels.js);
// this module projects them into the three bsky-legible surfaces:
//   1. did:web identity — a #atproto_label verificationMethod (the signing key, so bsky verifies our sigs)
//      + a #atproto_labeler service entry (where to reach queryLabels/subscribeLabels).
//   2. com.atproto.label.queryLabels — the HTTP pull surface: labels for a set of uriPatterns/sources.
//   3. app.bsky.labeler.service record — declares the labeler + its label values (the publish ceremony).
//
// The live-push surface (com.atproto.label.subscribeLabels, a WS firehose) is what bsky's AppView ingests
// for real-time labels; it needs a WS server (bare-ws) and is the remaining outward piece — see DESIGN.
// queryLabels + identity are enough to stand up + verify the labeler identity and pull labels.
import b4a from 'b4a'

// A signed label → its atproto JSON-XRPC representation. `sig` is CBOR bytes on the wire; in JSON it's the
// canonical { $bytes: base64 } form. undefined optional fields are omitted.
export function toWireLabel (label) {
  const w = { src: label.src, uri: label.uri, val: label.val, cts: label.cts }
  if (label.cid !== undefined) w.cid = label.cid
  if (label.neg !== undefined) w.neg = label.neg
  if (label.exp !== undefined) w.exp = label.exp
  if (label.ver !== undefined) w.ver = label.ver
  if (label.sig) w.sig = { $bytes: b4a.toString(b4a.isBuffer(label.sig) ? label.sig : b4a.from(label.sig), 'base64') }
  return w
}

// Match an AT-URI/DID subject against a queryLabels uriPattern. `*` is a suffix wildcard; a bare pattern
// matches exactly. `*` alone matches everything (atproto convention).
export function uriMatches (uri, pattern) {
  if (pattern === '*') return true
  if (pattern.endsWith('*')) return String(uri).startsWith(pattern.slice(0, -1))
  return uri === pattern
}

export class LabelerExport {
  // labelerDid: the DID stamped as `src` in labels AND the labeler's service DID (did:web:<host>). Bsky
  // verifies label sigs against this DID's #atproto_label key, so it MUST be the did:web we serve.
  // signingDidKey: the label signing key's did:key (its multibase becomes the VM publicKeyMultibase).
  // hostname: the public HTTPS host. source: { labels() => Promise<signedLabel[]> } — favela's produced
  // labels (e.g. adapted from a Labeler feed). labelValues: the vals this labeler emits (declared surface).
  constructor ({ labelerDid, signingDidKey, hostname, source, labelValues = [] } = {}) {
    if (!labelerDid || !signingDidKey || !hostname || !source) throw new Error('LabelerExport requires { labelerDid, signingDidKey, hostname, source }')
    this.labelerDid = labelerDid
    this.signingDidKey = signingDidKey
    this.hostname = hostname
    this._source = source
    this.labelValues = labelValues
  }

  // The #atproto_label verificationMethod for the did:web doc — bsky reads the signing key from here to
  // verify our label signatures. publicKeyMultibase = the did:key multibase (drop the `did:key:` prefix).
  verificationMethod () {
    return {
      id: this.labelerDid + '#atproto_label',
      type: 'Multikey',
      controller: this.labelerDid,
      publicKeyMultibase: this.signingDidKey.replace(/^did:key:/, '')
    }
  }

  // The #atproto_labeler service entry — where a consumer reaches queryLabels / subscribeLabels.
  service () {
    return { id: '#atproto_labeler', type: 'AtprotoLabeler', serviceEndpoint: `https://${this.hostname}` }
  }

  // com.atproto.label.queryLabels — labels for the given uriPatterns (required) filtered by sources
  // (optional; defaults to us). Returns { cursor, labels:[wireLabel] }. Cursor pagination is opaque and
  // index-based over the current source snapshot (a simple offset — fine for a pull surface).
  async queryLabels ({ uriPatterns = [], sources = null, limit = 50, cursor = null } = {}) {
    const patterns = (Array.isArray(uriPatterns) && uriPatterns.length) ? uriPatterns : ['*']
    // Default to OUR own labels (this is favela's labeler endpoint); an explicit `sources` overrides.
    const srcAllow = (Array.isArray(sources) && sources.length) ? new Set(sources) : new Set([this.labelerDid])
    const all = (await this._source.labels()) || []
    const matched = all.filter((l) =>
      srcAllow.has(l.src) && patterns.some((p) => uriMatches(l.uri, p))
    )
    const start = cursor ? Math.max(0, Number(cursor) || 0) : 0
    const page = matched.slice(start, start + limit)
    const next = (start + limit) < matched.length ? String(start + limit) : undefined
    return { ...(next !== undefined ? { cursor: next } : {}), labels: page.map(toWireLabel) }
  }

  // The app.bsky.labeler.service record body (rkey 'self') to publish into the labeler account's repo —
  // declares the labeler and the label values it emits. policies.labelValueDefinitions may add severity/
  // blur/locale definitions; omitted here → consumers use their own defaults for our vals.
  serviceRecord ({ createdAt, labelValueDefinitions = [] } = {}) {
    if (!createdAt) throw new Error('serviceRecord requires createdAt (ISO datetime, caller-supplied)')
    return {
      $type: 'app.bsky.labeler.service',
      policies: { labelValues: this.labelValues, ...(labelValueDefinitions.length ? { labelValueDefinitions } : {}) },
      createdAt
    }
  }
}

export default LabelerExport
// favela labeler feed — the single-authority labeler (DESIGN §8): a signed hypercore of
// com.atproto.label records on its own key. The producer SIGNS labels with its secp256k1 key;
// consumers replicate the feed by key and VERIFY each label against the labeler's did:key. Simpler
// than a repo (no MST/CAR/commit chain) — a label feed is just N independently-signed leaves.
//
// Multi-mod (co-authored labels) is a later variant — an autobase room + a signer lease (DESIGN §8),
// same as the peer's writer model. This is the single-mod first cut.
import { buildLabel, signLabel, verifyLabel, encodeLabel, decodeLabel } from 'atproto-identity/lib/labels.js'
import { keyFromPrivate } from 'atproto-identity/lib/atproto-identity.js'

export class Labeler {
  // corestore: for the feed core. privateKey: the labeler's raw secp256k1 signing key. src: the
  // labeler's DID published in each label (defaults to its did:key when no did:plc is minted).
  constructor (corestore, { privateKey, src, name = 'label-feed' } = {}) {
    this._key = keyFromPrivate(privateKey) // { privateKey, publicKey, didKey }
    this.src = src || this._key.didKey
    this.core = corestore.get({ name, valueEncoding: 'binary' })
  }

  async ready () { await this.core.ready(); return this }
  get feedKey () { return this.core.key } // share with consumers to replicate the feed
  get didKey () { return this._key.didKey } // share with consumers to verify signatures

  // Append a signed label. uri = subject (an AT-URI or account DID); val = label value; neg retracts a
  // prior (src,uri,val); cts defaults to now. Returns the signed label.
  async label (uri, val, { neg, cts } = {}) {
    const signed = signLabel(buildLabel({ src: this.src, uri, val, cts: cts || new Date().toISOString(), neg }), this._key.privateKey)
    await this.core.append(encodeLabel(signed))
    return signed
  }

  async close () { await this.core.close() }
}

// Consume a labeler feed: decode + VERIFY each label against `didKey` and addLabel the valid ones into
// the LabelStore. Downloads the whole feed then live-tails. `core` is a read replica opened by the
// labeler's feedKey (the caller replicates it over the swarm). Returns a stop() function.
export function readLabelFeed (core, didKey, store, { onError, onLabel } = {}) {
  let stopped = false
  ;(async () => {
    await core.ready()
    try { core.download({ start: 0, end: -1 }) } catch {}
    let i = 0
    while (!stopped) {
      if (i < core.length) {
        try {
          const label = decodeLabel(await core.get(i))
          if (verifyLabel(label, didKey)) { const changed = await store.addLabel(label); if (changed && onLabel) onLabel(label) }
        } catch (e) { if (onError) onError(e) }
        i++
        continue
      }
      await new Promise((resolve) => {
        const on = () => { core.off('append', on); resolve() }
        core.on('append', on)
        if (stopped) { core.off('append', on); resolve() }
      })
    }
  })().catch((e) => { if (onError) onError(e) })
  return () => { stopped = true }
}
// favela label consumption — index VERIFIED labels by subject, resolve the active set, and decide
// render treatment. Labels are moderation judgments from labelers favela TRUSTS; signature verification
// (verifyLabel vs the labeler's did:key) happens in the feed reader BEFORE addLabel — this store only
// holds already-trusted labels. Moderation is OPT-IN and applied AT RENDER (never destroys posts).
//
// State model (atproto): a label is keyed by (src, uri, val); retraction is NEGATION (`neg:true`), not
// deletion; the latest `cts` wins (LWW). getLabels returns the currently-active (non-negated) labels.
import Hyperbee from 'hyperbee'

const SEP = '\x00'
const RANK = { ignore: 0, inform: 1, warn: 2, hide: 3 }

export class LabelStore {
  constructor (corestore, { name = 'favela-labels' } = {}) {
    this.bee = new Hyperbee(corestore.get({ name }), { keyEncoding: 'utf-8', valueEncoding: 'json' })
  }

  async ready () { await this.bee.ready(); return this }
  _key (uri, src, val) { return `${uri}${SEP}${src}${SEP}${val}` }

  // Add an already-VERIFIED label. LWW by cts: apply only if strictly newer than the stored state for
  // (uri, src, val). A neg:true label is stored (it retracts the val at render). Returns true on change.
  async addLabel (label) {
    if (!label || !label.uri || !label.src || !label.val || !label.cts) return false
    const key = this._key(label.uri, label.src, label.val)
    const prior = await this.bee.get(key)
    if (prior && prior.value && String(prior.value.cts) >= String(label.cts)) return false // not newer
    await this.bee.put(key, { src: label.src, uri: label.uri, val: label.val, cts: label.cts, neg: !!label.neg })
    return true
  }

  // Active labels on a subject uri: the (src, val) whose latest state is NOT negated. Prefix-safe
  // (the \x00 separator + \x01 ceiling bound exactly this uri — a longer uri sharing the prefix is
  // excluded). Returns [{ src, val, cts }].
  async getLabels (uri) {
    const out = []
    for await (const { value } of this.bee.createReadStream({ gte: `${uri}${SEP}`, lt: `${uri}\x01` })) {
      if (value && !value.neg) out.push({ src: value.src, val: value.val, cts: value.cts })
    }
    return out
  }

  async close () { await this.bee.close() }
}

// Decide the strongest render treatment for a set of active labels, given a policy map
// (val -> 'hide'|'warn'|'inform'|'ignore'). atproto system values ('!hide'/'!warn') are ALWAYS honored;
// unknown custom values default to 'ignore' (shown normally) unless the policy opts in. Returns
// 'ignore' | 'inform' | 'warn' | 'hide'.
export function labelTreatment (labels, policy = {}) {
  let best = 'ignore'
  for (const l of labels) {
    let t = policy[l.val]
    if (!t) t = l.val === '!hide' ? 'hide' : l.val === '!warn' ? 'warn' : 'ignore'
    if ((RANK[t] || 0) > RANK[best]) best = t
  }
  return best
}

// Combined per-post moderation decision from the two viewer-side layers: labeler labels (applied per
// policy) and a modlist MUTE (the author is on a subscribed moderation list). Returns
// { treatment, muted, labels } — the client collapses a post when treatment is hide/warn OR muted.
// Both are opt-in and applied at render; neither deletes the post.
export function postModeration (labels, muted, policy = {}) {
  return { treatment: (labels && labels.length) ? labelTreatment(labels, policy) : 'ignore', muted: !!muted, labels: (labels || []).map((l) => l.val) }
}
// lens-import.js — read an atproto AppView over XRPC. The missing arm of DESIGN.md's lens model.
//
// DESIGN.md:226 calls the *view* a replaceable lens (appview / feed generator / labeler) and :246 defines
// lens EXPORT — favela communities projected out as bsky feeds. This is the symmetric arm: lens IMPORT,
// reading a remote AppView for data our own index cannot have.
//
// WHY IT IS NEEDED. favela's appview indexes the firehoses of peers it ingests, which is a strictly
// narrower window than a public AppView's. A bsky user replying to us, or the profile of anyone outside
// that window, is not "missing" — it was never in scope. No amount of local indexing surfaces it.
//
// WHAT THIS IS NOT. It does not merge remote data into local views. Two AppViews legitimately disagree —
// different visibility, different moderation, one may block a post another serves — and atproto assumes
// exactly ONE AppView per client session (the `atproto-proxy` header names it). Aggregating invents a
// consensus neither endorses. So this returns ATTRIBUTED data for a named lens and leaves presentation to
// the caller. Counts and labels in particular must not be silently blended: bsky's counts are
// network-wide while ours are window-local (different denominators), and labels are a moderation policy,
// which atproto models as per-labeler subscription rather than aggregation.
//
// FAILS SOFT, ALWAYS. Every path returns null rather than throwing. A lens is supplementary: a thread
// must render from local data whether or not a remote AppView answers. An import that can break a page is
// worse than one that is absent.
//
// PURE + INJECTED. `doFetch` and `now` are parameters, so the whole backpressure story is unit-testable
// without a network or a sleeping clock.

const DEFAULTS = {
  cacheTtlMs: 60_000,
  negativeTtlMs: 15_000,
  timeoutMs: 1500,
  maxConcurrent: 4,
  breakerThreshold: 3,
  breakerCooldownMs: 60_000,
  maxCacheEntries: 500
}

// Stable cache key. Params are sorted so {a,b} and {b,a} are one entry rather than two.
function keyOf (lensName, nsid, params) {
  const q = Object.keys(params || {}).sort().map((k) => `${k}=${String(params[k])}`).join('&')
  return `${lensName}|${nsid}|${q}`
}

// Pull the DIRECT replies out of an app.bsky.feed.getPostThread body, as plain attributed rows.
//
// A thread node is a union: #threadViewPost, #notFoundPost or #blockedPost. Only the first carries a
// post, and skipping the other two is not a detail — a blocked post is a moderation decision by THAT
// AppView, and rendering it as though we had the content would misrepresent their call as ours.
//
// Returns a normalized, RENDER-READY row rather than bsky's postView, so the presentation layer never has
// to know AppView shapes: { uri, cid, did, handle, displayName, avatar, text, createdAt, replyCount }.
// Nested descendants are deliberately dropped — one level is enough to say "there is more over there",
// and reproducing a remote AppView's whole tree inside ours starts to look like the merge this module
// exists to refuse.
export function extractThreadReplies (body, { exclude = null } = {}) {
  const replies = body && body.thread && Array.isArray(body.thread.replies) ? body.thread.replies : []
  const out = []
  for (const node of replies) {
    if (!node || typeof node !== 'object') continue
    const t = node.$type
    if (typeof t === 'string' && !t.endsWith('#threadViewPost')) continue // notFound / blocked
    const p = node.post
    if (!p || typeof p.uri !== 'string') continue
    // Anything this node already indexed is OURS to render, in our tree, with our affordances. Showing it
    // again under the lens would double it — this is de-duplication for display, NOT a merge of the two
    // views (no counts are combined, nothing is reconciled).
    if (exclude && exclude.has(p.uri)) continue
    const a = p.author || {}
    const rec = p.record || {}
    out.push({
      uri: p.uri,
      cid: typeof p.cid === 'string' ? p.cid : null,
      did: typeof a.did === 'string' ? a.did : null,
      handle: typeof a.handle === 'string' ? a.handle : null,
      displayName: typeof a.displayName === 'string' ? a.displayName : null,
      avatar: typeof a.avatar === 'string' ? a.avatar : null,
      text: typeof rec.text === 'string' ? rec.text : '',
      createdAt: typeof rec.createdAt === 'string' ? rec.createdAt : null,
      replyCount: Number.isFinite(p.replyCount) ? p.replyCount : 0
    })
  }
  return out
}

// Pull the ANCESTOR chain out of an app.bsky.feed.getPostThread body, oldest first.
//
// This is the other half of the window problem. getPostThread nests ancestors as `thread.parent`, and
// each parent may carry its own `.parent` — so the chain is a linked list walked upward, unlike replies
// which are an array. Our own walk stops at the first parent we never indexed and marks it { missing },
// which is exactly the gap this fills.
//
// Stops at a #notFoundPost or #blockedPost, and at anything malformed, rather than skipping over it: an
// ancestor chain with a hole in the middle is not a chain, and silently closing the gap would imply the
// remaining posts are consecutive when they are not. `maxDepth` bounds a hostile or looping response.
export function extractThreadParents (body, { exclude = null, maxDepth = 20 } = {}) {
  const out = []
  const seen = new Set()
  let node = body && body.thread ? body.thread.parent : null
  for (let i = 0; i < maxDepth && node && typeof node === 'object'; i++) {
    const t = node.$type
    if (typeof t === 'string' && !t.endsWith('#threadViewPost')) break
    const p = node.post
    if (!p || typeof p.uri !== 'string') break
    if (seen.has(p.uri)) break // a cycle in someone else's data must not hang our page
    seen.add(p.uri)
    if (!exclude || !exclude.has(p.uri)) {
      const a = p.author || {}
      const rec = p.record || {}
      out.push({
        uri: p.uri,
        cid: typeof p.cid === 'string' ? p.cid : null,
        did: typeof a.did === 'string' ? a.did : null,
        handle: typeof a.handle === 'string' ? a.handle : null,
        displayName: typeof a.displayName === 'string' ? a.displayName : null,
        avatar: typeof a.avatar === 'string' ? a.avatar : null,
        text: typeof rec.text === 'string' ? rec.text : '',
        createdAt: typeof rec.createdAt === 'string' ? rec.createdAt : null,
        replyCount: Number.isFinite(p.replyCount) ? p.replyCount : 0
      })
    }
    node = node.parent
  }
  // Walked upward, so reverse to render oldest-first — the order a reader scans a conversation.
  return out.reverse()
}

export function createLensReader (opts = {}) {
  const cfg = { ...DEFAULTS, ...opts }
  const doFetch = opts.doFetch
  const now = opts.now || (() => Date.now())
  if (typeof doFetch !== 'function') throw new Error('createLensReader requires doFetch(url, init)')

  const cache = new Map()      // key -> { at, ok, value }
  const inflight = new Map()   // key -> Promise (single-flight)
  const breakers = new Map()   // lensName -> { fails, openedAt }
  const stats = { hits: 0, misses: 0, fetches: 0, failures: 0, shortCircuited: 0, coalesced: 0, timeouts: 0 }

  let active = 0
  const waiters = []
  // A plain semaphore. Without it a burst of thread views opens one socket each; the cap makes the
  // outbound load a property of THIS process rather than of how many people happen to click at once.
  async function withSlot (fn) {
    if (active >= cfg.maxConcurrent) await new Promise((resolve) => waiters.push(resolve))
    active++
    try { return await fn() } finally {
      active--
      const next = waiters.shift()
      if (next) next()
    }
  }

  // Per-LENS, not per-key: the failure mode being defended against is "this AppView is down", and
  // per-key breakers would let a down lens be retried once per distinct thread forever.
  function breakerOpen (lensName) {
    const b = breakers.get(lensName)
    if (!b || b.fails < cfg.breakerThreshold) return false
    if (now() - b.openedAt >= cfg.breakerCooldownMs) { breakers.delete(lensName); return false }
    return true
  }

  function recordOutcome (lensName, ok) {
    if (ok) { breakers.delete(lensName); return }
    const b = breakers.get(lensName) || { fails: 0, openedAt: 0 }
    b.fails++
    if (b.fails >= cfg.breakerThreshold) b.openedAt = now()
    breakers.set(lensName, b)
  }

  function cacheGet (key) {
    const e = cache.get(key)
    if (!e) return undefined
    // Negatives expire FASTER than positives: a transiently unreachable lens should recover quickly,
    // but not be retried on every single page view in the meantime.
    const ttl = e.ok ? cfg.cacheTtlMs : cfg.negativeTtlMs
    if (now() - e.at >= ttl) { cache.delete(key); return undefined }
    return e
  }

  function cacheSet (key, ok, value) {
    if (cache.size >= cfg.maxCacheEntries) cache.clear()
    cache.set(key, { at: now(), ok, value })
  }

  // GET <lens.base>/xrpc/<nsid>?<params>. When `lens.proxy` is set it rides as the `atproto-proxy`
  // header — which is how the bridge (pds/lib/appview.js resolveAppView) is told WHICH AppView to
  // forward to. That makes one configured egress reach bsky, Blacksky, or anything else, and keeps
  // favela keyless: it never needs credentials for the AppView it is reading.
  function urlFor (lens, nsid, params) {
    const qs = Object.keys(params || {}).sort().map((k) => `${encodeURIComponent(k)}=${encodeURIComponent(params[k])}`).join('&')
    return `${String(lens.base).replace(/\/$/, '')}/xrpc/${nsid}${qs ? '?' + qs : ''}`
  }

  async function fetchOnce (lens, nsid, params) {
    const url = urlFor(lens, nsid, params)
    const headers = { accept: 'application/json' }
    if (lens.proxy) headers['atproto-proxy'] = lens.proxy
    let timer = null
    try {
      const timeout = new Promise((_, reject) => { timer = setTimeout(() => reject(new Error('lens timeout')), cfg.timeoutMs) })
      const res = await Promise.race([doFetch(url, { method: 'GET', headers }), timeout])
      if (!res || typeof res.status !== 'number' || res.status < 200 || res.status >= 300) return null
      // A body that is not JSON is a failure, not an empty result — an AppView that answers 200 with an
      // HTML error page must not be cached as a valid (empty) view.
      if (typeof res.json === 'function') return await res.json()
      if (typeof res.body === 'string') return JSON.parse(res.body)
      return res.body || null
    } catch (e) {
      if (String(e && e.message) === 'lens timeout') stats.timeouts++
      return null
    } finally { if (timer) clearTimeout(timer) }
  }

  // Read one XRPC method from one lens. Returns the decoded body, or null (never throws).
  async function get (lens, nsid, params = {}) {
    if (!lens || !lens.base || !lens.name || !nsid) return null
    const key = keyOf(lens.name, nsid, params)

    const cached = cacheGet(key)
    if (cached !== undefined) { stats.hits++; return cached.ok ? cached.value : null }
    stats.misses++

    if (breakerOpen(lens.name)) { stats.shortCircuited++; return null }

    // Single-flight: N concurrent viewers of the same thread share ONE request. Without this the cache
    // only helps AFTER the first response, so a cold popular thread still fans out.
    const pending = inflight.get(key)
    if (pending) { stats.coalesced++; return pending }

    const p = (async () => {
      stats.fetches++
      const value = await withSlot(() => fetchOnce(lens, nsid, params))
      const ok = value !== null && value !== undefined
      if (!ok) stats.failures++
      recordOutcome(lens.name, ok)
      cacheSet(key, ok, value)
      return ok ? value : null
    })().finally(() => inflight.delete(key))

    inflight.set(key, p)
    return p
  }

  return {
    get,
    stats: () => ({ ...stats, cacheSize: cache.size, inflight: inflight.size, open: [...breakers].filter(([, b]) => b.fails >= cfg.breakerThreshold).map(([n]) => n) }),
    // Test/ops affordance: forget everything for a lens (e.g. after reconfiguring it).
    reset (lensName = null) {
      if (!lensName) { cache.clear(); breakers.clear(); return }
      breakers.delete(lensName)
      for (const k of [...cache.keys()]) if (k.startsWith(lensName + '|')) cache.delete(k)
    }
  }
}
// lenses.js — which remote AppViews this node reads, if any.
//
// DEFAULT IS NONE. An unconfigured favela reads no remote AppView and behaves exactly as it does today:
// local-indexed data only. That is a deliberate default, not laziness — favela's premise is P2P-native
// with bsky as an optional export, so reaching out to a hosted AppView has to be something an operator
// opts INTO. The cost of opting out is that a thread's view is partial, which the UI must say out loud
// rather than leave implied (a thread with three unseen bsky replies looks identical to one with none).
//
// Three config forms. The first is the one a person can actually reach:
//
//   THE SETTINGS PAGE (lensPref below)
//     A node-level trust decision that only someone with shell access could change is not a setting, it
//     is a deployment detail. The stored preference wins over env so that changing it in the UI is not
//     silently overridden by whatever the process was started with, and clearing it falls back to env.
//
// The env forms remain, for provisioning a node before anyone opens it:
//
//   FAVELA_BRIDGE_URL=https://pds.example.net
//     Shorthand for the common case: one lens named 'bsky', reached THROUGH the bridge, which resolves
//     the `atproto-proxy` header to the real AppView. One variable, keyless, no bsky URL in our config.
//
//   FAVELA_LENSES=[{"name":"blacksky","base":"https://…","proxy":"did:web:…#bsky_appview"}]
//     Explicit list, for multiple lenses or a non-bsky AppView. `base` may be a bridge (with `proxy`) or
//     an AppView directly (without).
//
// NOT MERGED. Each lens stays a named, attributed source. atproto assumes one AppView per client session
// and two AppViews can legitimately disagree — different visibility, different moderation, one blocking
// what another serves. A registry of lenses is not a quorum; presentation must keep them distinguishable.

const BSKY_APPVIEW_PROXY = 'did:web:api.bsky.app#bsky_appview'

export function validBase (base) {
  const s = String(base || '')
  return /^https?:\/\/[^\s/]+/.test(s) ? s.replace(/\/$/, '') : null
}

// One lens entry, or null with a reason. Malformed entries are SKIPPED rather than fatal: a typo in one
// lens must not stop a daemon booting, and a silently-dropped lens is why `errors` is returned too.
function normalize (raw) {
  if (!raw || typeof raw !== 'object') return { error: 'not an object' }
  const name = typeof raw.name === 'string' ? raw.name.trim() : ''
  if (!name) return { error: 'missing name' }
  if (!/^[a-z0-9][a-z0-9._-]*$/i.test(name)) return { error: `invalid name "${name}"` }
  const base = validBase(raw.base)
  if (!base) return { error: `lens "${name}": base must be an http(s) url` }
  const proxy = typeof raw.proxy === 'string' && raw.proxy.trim() ? raw.proxy.trim() : null
  return { lens: { name, base, proxy } }
}

// Parse the lens registry from an env-like object. Returns { lenses, errors } — never throws.
export function parseLenses (env = {}) {
  const out = []
  const errors = []
  const seen = new Set()

  const add = (raw) => {
    const r = normalize(raw)
    if (r.error) { errors.push(r.error); return }
    // First definition of a name wins, so the explicit list can be reasoned about top-down and a
    // duplicate is reported rather than silently shadowing.
    if (seen.has(r.lens.name)) { errors.push(`duplicate lens "${r.lens.name}" ignored`); return }
    seen.add(r.lens.name)
    out.push(r.lens)
  }

  const raw = env.FAVELA_LENSES
  if (raw) {
    let parsed = null
    try { parsed = JSON.parse(raw) } catch { errors.push('FAVELA_LENSES is not valid JSON — ignored') }
    if (parsed !== null) {
      if (Array.isArray(parsed)) for (const e of parsed) add(e)
      else errors.push('FAVELA_LENSES must be a JSON array — ignored')
    }
  }

  // Shorthand last, so an explicit `bsky` entry in FAVELA_LENSES takes precedence over it.
  const bridge = validBase(env.FAVELA_BRIDGE_URL)
  if (bridge) add({ name: 'bsky', base: bridge, proxy: env.FAVELA_BSKY_APPVIEW || BSKY_APPVIEW_PROXY })
  else if (env.FAVELA_BRIDGE_URL) errors.push('FAVELA_BRIDGE_URL must be an http(s) url — ignored')

  return { lenses: out, errors }
}

// Is remote reading configured at all? The UI needs this to distinguish "no replies" from "we did not
// look" — the honesty requirement of the opted-out default.
export function lensesEnabled (lenses) {
  return Array.isArray(lenses) && lenses.length > 0
}

export function findLens (lenses, name) {
  return (Array.isArray(lenses) ? lenses : []).find((l) => l.name === name) || null
}


// ── the stored preference ────────────────────────────────────────────────────────────────────────────
// Node-LOCAL on purpose, unlike the subscription list, which is a property of the identity and belongs in
// its repo. Which remote AppView this node may read is a trust and privacy decision about THIS machine on
// THIS network: a phone on a hostile network can reasonably answer differently from a server, and a fresh
// install must start closed regardless of what any other device chose.
//
// Pure: the caller owns the file I/O, so the precedence rule is testable without a store.
export const LENS_PREF_FILE = 'lens-pref.json'

/**
 * Merge a stored preference into an env-like object, for parseLenses.
 *
 * Stored wins when set — otherwise saving in the UI would appear to do nothing on a node started with
 * FAVELA_BRIDGE_URL. An explicitly cleared preference ('') means "off", NOT "fall back to env", or the
 * UI could never turn off what env turned on.
 */
export function lensEnv (env = {}, pref = null) {
  if (!pref || typeof pref !== 'object' || pref.bridgeUrl === undefined) return env
  return { ...env, FAVELA_BRIDGE_URL: pref.bridgeUrl || '' }
}

/** Validate what the settings form submitted. Returns { bridgeUrl } or { error }. */
export function parseLensPref (raw) {
  const v = String(raw == null ? '' : raw).trim()
  if (!v) return { bridgeUrl: '' } // cleared — reading remotely is off
  const base = validBase(v)
  if (!base) return { error: 'that is not an http(s) url' }
  return { bridgeUrl: base }
}
// link-drain.js — consume Spacedust pointers and run DESIGN §7.6's retention pipeline.
//
// WHERE THIS SITS. `spacedust.js` owns the socket and does exactly one thing per message: parse and
// enqueue. This module owns everything after that — tier routing, dedup, fetch, verify, retain. The
// split exists because spacedust DROPS a subscriber that lags, so the socket handler must never do work.
//
// WHY NOT A THREAD (asked and answered 2026-07-30). `bare-thread` runs an entry point on a dedicated OS
// thread with its module graph bundled AHEAD OF TIME, in isolation — its API is join/suspend/wakeup/
// resume/terminate, with no message passing (that is `bare-channel`). The tail of this pipeline WRITES:
// OverlayRepoStore file handles plus the appview Hyperbee over a Corestore, and a Corestore holds an
// EXCLUSIVE RocksDB lock. Store handles are not transferable across threads — only serializable messages
// are — so putting the drain on a thread would need a second store opened over the same directory, which
// is precisely the lock conflict the stack already documents. The lag hazard is event-loop OCCUPANCY,
// not instruction count, so the fix is to YIELD, not to parallelise.
//
// THE THREAD SEAM, IF A PROFILE EVER JUSTIFIES ONE. Only `verifyRecord` is a candidate: it is pure
// (bytes in, boolean out), CPU-bound (signature + hash), and touches no store. It could move behind a
// `bare-channel` to a `bare-thread` worker without changing anything else here. Everything that touches
// a store must stay on this thread. Do not move it without a measurement — see the standing rule about
// unmeasured numbers.
//
// FAILS SOFT, ALWAYS. A pointer that cannot be fetched or verified is counted and dropped, never thrown.
// Losing one pointer is recoverable: §7.6 pairs the live subscription with Constellation precisely so a
// gap can be backfilled by (subject, source). Losing the drain loop is not recoverable.
//
// PURE + INJECTED. Every pipeline step is a parameter, so tier routing, dedup, the rev skip-test, the
// yield cadence and the failure accounting are all unit-testable with no network, no store and no clock.

const DEFAULTS = {
  concurrency: 4, // parallel fetch+verify; bounded so a burst cannot monopolise the loop
  batchSize: 16, // pointers handled between explicit yields
  idleMs: 250, // poll interval when the queue is empty
  maxRetained: null // optional cap; null = caller enforces the §7.6 byte budget
}

// Yield the macrotask queue. `await` on I/O already yields, but a run of cache hits or synchronous
// verifies would not — this guarantees the loop cannot be occupied for a whole batch.
function yieldToLoop () {
  return new Promise((resolve) => setTimeout(resolve, 0))
}

// Stable identity for a linking record. Dedup is by record, not by link, because the same record can
// legitimately produce several link events (a post links to reply.parent AND reply.root).
export function pointerKey (p) {
  return `${p.did}/${p.collection}/${p.rkey}`
}

// The backfilling guide's skip test: a pointer whose rev is not newer than what we already hold for that
// record is already-known state. Revs are TIDs — lexicographically sortable, so string compare is right.
// Unknown/absent revs are treated as NEW (fetch and let verification decide) rather than skipped, because
// skipping on missing data would silently lose writes.
export function shouldSkipRev (incomingRev, knownRev) {
  if (typeof incomingRev !== 'string' || typeof knownRev !== 'string') return false
  return incomingRev <= knownRev
}

export class LinkDrain {
  // `client` is a SpacedustClient (anything with .drain(n) and .pending).
  //
  // Pipeline hooks — all optional, all async, all fail-soft:
  //   fetchRecord({did, collection, rkey})  -> { bytes, cid } | null   (resolveMiniDoc -> getRecord)
  //   verifyRecord(record, pointer)         -> boolean                 (signature + MST; the thread seam)
  //   retainRecord(record, pointer)         -> void                    (OverlayRepoStore + appview index)
  //   evictRecord(pointer)                  -> void                    (a 'delete' link arrived)
  //   knownRev(pointer)                     -> string | null           (rev we already hold, for the skip)
  constructor (client, opts = {}) {
    this.client = client
    this.opts = { ...DEFAULTS, ...opts }

    this._fetchRecord = opts.fetchRecord || (async () => null)
    this._verifyRecord = opts.verifyRecord || (async () => true)
    this._retainRecord = opts.retainRecord || (async () => {})
    this._evictRecord = opts.evictRecord || (async () => {})
    this._knownRev = opts.knownRev || (async () => null)
    // ⛔ COUNT-BEARING LINKS ARE NO LONGER DROPPED. §7.6 put likes and reposts in Tier C because "a
    // post with 50k likes must not become 50k retained records" — true of the RECORD, and the record
    // is not what we want. A like's bytes carry nothing its pointer does not: $type is the
    // collection, subject.uri is our own post, and the only per-like facts are WHO and WHEN, both
    // already in the pointer Spacedust shipped for free. Measured: 50,000 of them encode to 0.50 MB.
    //
    // ⚠ STILL NEVER FETCHED OR VERIFIED. The pressure valve §7.6 was protecting is the round trip,
    // not the storage, and that stays shut — this sink is handed the pointer and nothing else.
    this._noteInteraction = opts.noteInteraction || null

    this._running = false
    this._loop = null

    this.stats = {
      seen: 0,
      skippedTierC: 0, // count-bearing (likes/reposts) — never FETCHED; noted as a tuple if a sink is set
      noted: 0, // count-bearing pointers handed to the interaction sink
      noteFailed: 0,
      skippedRev: 0, // already have this state
      deleted: 0,
      fetchFailed: 0,
      verifyFailed: 0,
      retained: 0,
      errored: 0
    }
  }

  start () {
    if (this._running) return this
    this._running = true
    this._loop = this._run()
    return this
  }

  async stop () {
    this._running = false
    if (this._loop !== null) {
      try {
        await this._loop
      } catch {
        // the loop never rejects, but do not let teardown throw
      }
      this._loop = null
    }
  }

  async _run () {
    while (this._running) {
      const batch = this.client.drain(this.opts.batchSize)
      if (batch.length === 0) {
        await new Promise((resolve) => setTimeout(resolve, this.opts.idleMs))
        continue
      }
      await this._handleBatch(batch)
      await yieldToLoop() // never hold the loop across batches
    }
  }

  // Bounded-concurrency pool. Deliberately simple: N workers pulling from one array beats a scheduler,
  // and the bound is what stops a burst from monopolising the event loop.
  async _handleBatch (batch) {
    const queue = batch.slice()
    const workers = []
    const width = Math.min(this.opts.concurrency, queue.length)
    for (let i = 0; i < width; i++) {
      workers.push((async () => {
        while (queue.length > 0) {
          const pointer = queue.shift()
          try {
            await this._handleOne(pointer)
          } catch {
            this.stats.errored++ // fail soft — one bad pointer must not stop the drain
          }
        }
      })())
    }
    await Promise.all(workers)
  }

  async _handleOne (pointer) {
    this.stats.seen++

    // TIER ROUTING (§7.6). Count-bearing links — likes, reposts, follows — are never retained. This is
    // the pressure valve: a post with 50k likes costs us nothing here, and "how many" is answered on
    // demand by Constellation's getBacklinksCount. Only content-bearing links proceed.
    if (!pointer.contentBearing) {
      this.stats.skippedTierC++
      // The tuple, if anyone is collecting them. Failure here must not disturb the drain: an
      // interaction we failed to note is one missing row, and losing the loop is losing everything.
      if (this._noteInteraction) {
        try { await this._noteInteraction(pointer); this.stats.noted++ } catch { this.stats.noteFailed++ }
      }
      return
    }

    if (pointer.operation === 'delete') {
      this.stats.deleted++
      await this._evictRecord(pointer)
      return
    }

    // Skip state we already hold.
    const known = await this._knownRev(pointer)
    if (shouldSkipRev(pointer.rev, known)) {
      this.stats.skippedRev++
      return
    }

    // FETCH from the authoritative PDS. Spacedust ships only a locator by design, so the bytes come from
    // the record's own repo — never from the index that told us about it.
    const record = await this._fetchRecord(pointer)
    if (!record) {
      this.stats.fetchFailed++
      return
    }

    // VERIFY before retaining. This is the whole agency claim — replicate signed data, verify locally,
    // rather than trusting a third-party index. An unverified record is not retained, full stop.
    // (This call is the thread seam described in the header.)
    const ok = await this._verifyRecord(record, pointer)
    if (!ok) {
      this.stats.verifyFailed++
      return
    }

    await this._retainRecord(record, pointer)
    this.stats.retained++
  }
}
// User lists — app.bsky.graph.list + app.bsky.graph.listitem.
//
// TWO RECORDS, and the relationship between them is the whole thing. A `list` is just a name and a
// purpose; membership lives in separate `listitem` records, each carrying `subject` (the member's DID)
// and `list` (the list's at:// uri). So a list of 500 people is 501 records, and removing someone means
// deleting THEIR listitem — not editing the list.
//
// That shape is why this needs no index for our OWN lists: we know our DID, so both collections are
// directly readable from the record store. Someone ELSE's list still needs the peer path
// (lib/roster.js resolveRoster), which is what threadgate #listRule already uses.
//
// PURPOSE IS LOAD-BEARING, not a label. `#curatelist` is a normal user list; `#modlist` is a moderation
// list, and subscribing to one MUTES OR BLOCKS everyone on it. Rendering a modlist as if it were a
// curation list, or letting one be created by accident, hands someone a footgun — so the purpose is
// explicit at creation and shown wherever a list is displayed.

export const LIST_COLLECTION = 'app.bsky.graph.list'
export const LISTITEM_COLLECTION = 'app.bsky.graph.listitem'
export const CURATE = 'app.bsky.graph.defs#curatelist'
export const MODLIST = 'app.bsky.graph.defs#modlist'
export const PURPOSES = [CURATE, MODLIST]

export function listRecord ({ name, purpose = CURATE, description = '', createdAt = new Date().toISOString() }) {
  const n = String(name || '').trim()
  if (!n) return null
  return {
    $type: LIST_COLLECTION,
    purpose: PURPOSES.includes(purpose) ? purpose : CURATE,
    name: n.slice(0, 64),
    ...(description ? { description: String(description).slice(0, 300) } : {}),
    createdAt
  }
}

export function listitemRecord ({ subject, list, createdAt = new Date().toISOString() }) {
  if (typeof subject !== 'string' || !subject.startsWith('did:')) return null
  if (typeof list !== 'string' || !list.startsWith('at://')) return null
  return { $type: LISTITEM_COLLECTION, subject, list, createdAt }
}

export function isModlist (record) {
  return !!(record && record.purpose === MODLIST)
}

export function describePurpose (record) {
  return isModlist(record)
    ? 'moderation list — subscribing to this mutes or blocks everyone on it'
    : 'curation list'
}

export const listUri = (did, rkey) => `at://${did}/${LIST_COLLECTION}/${rkey}`

// Our own lists, read straight from the record store. Returns [{ rkey, uri, record }].
export async function ownLists (store, did) {
  const out = []
  if (!store || !did) return out
  try {
    for await (const { rkey, record } of store.list(LIST_COLLECTION)) {
      if (record && record.$type === LIST_COLLECTION) out.push({ rkey, uri: listUri(did, rkey), record })
    }
  } catch { /* absent collection dir — no lists yet */ }
  out.sort((a, b) => String((a.record && a.record.name) || '').localeCompare(String((b.record && b.record.name) || '')))
  return out
}

// Members of one of OUR lists: every listitem whose `list` matches. Returns [{ rkey, subject }].
//
// This SCANS the listitem collection, because membership is not indexed by list — the same honest trade
// search makes. A few hundred listitems is nothing; a hundred thousand would want an index.
export async function membersOf (store, uri) {
  const out = []
  if (!store || !uri) return out
  try {
    for await (const { rkey, record } of store.list(LISTITEM_COLLECTION)) {
      if (record && record.list === uri && typeof record.subject === 'string') out.push({ rkey, subject: record.subject })
    }
  } catch { /* no listitems yet */ }
  return out
}

// The listitem rkey binding `subject` to `uri`, or null. Needed to REMOVE someone: the membership record
// is what gets deleted, and without its rkey you would have to scan for it every time.
export async function memberRkey (store, uri, subject) {
  for (const m of await membersOf(store, uri)) if (m.subject === subject) return m.rkey
  return null
}

// ── CONVERGING ONE IDENTITY'S SUBSCRIPTIONS ACROSS ITS DEVICES ───────────────────────────────────────
// Devices hosting the same DID are the same identity and should agree on what it subscribes to with
// nothing configured on any of them. Both helpers below exist so that decision is testable without a
// repo, a writer or a handset — the failure they prevent was only visible on a phone.

// The rkey binding a subject to the subscriptions list.
//
// ⛔ DETERMINISTIC, NOT A FRESH TID. Two devices contributing the same DID concurrently would otherwise
// write TWO records for one membership: reads dedup by subject so it looks fine, while the repo
// accumulates duplicates for ever. Same subject => same rkey => the second write is a no-op, which is
// what makes the merge idempotent rather than merely convergent-on-read.
//
// rkey charset is [A-Za-z0-9.:_~-], so hex — not base64url. Truncated: a collision across a handful of
// subscriptions is not a practical concern, and would only drop one add, which another device's merge
// re-contributes.
export function subscriptionRkey (subject, hash) {
  if (typeof subject !== 'string' || !subject) throw new Error('subject required')
  if (typeof hash !== 'function') throw new Error('hash function required')
  return 'sub' + String(hash(subject)).slice(0, 24)
}

// What THIS node still owes the shared list: its own roster, minus itself, minus what the list already
// has, deduped and order-stable.
//
// ⛔ UNION, NEVER REPLACE. Writing the list wholesale makes "who booted first" decide the identity's
// roster for every device — a handset won that race against a server on 2026-08-25 and its derived set
// became authoritative. A union is order-independent: any interleaving of devices converges on the same
// set, and there is no winner to be.
//
// Self is excluded because a hosted DID is subscribed by virtue of being hosted; listing yourself says
// nothing and would round-trip into the roster as a duplicate.
export function missingMembers ({ local = [], listed = [], selfDid = null } = {}) {
  const have = new Set(listed)
  const out = []
  const seen = new Set()
  for (const did of local) {
    if (typeof did !== 'string' || !did.startsWith('did:')) continue
    if (did === selfDid || have.has(did) || seen.has(did)) continue
    seen.add(did)
    out.push(did)
  }
  return out
}
// Per-viewer mutes and block bookkeeping.
//
// ⛔ THE DISTINCTION THAT MATTERS, AND GETTING IT WRONG IS A PRIVACY LEAK.
//
//   MUTE  is PRIVATE. In atproto a mute is not a record — bsky keeps it as server-side state behind
//         app.bsky.graph.muteActor. Nobody, including the muted account, can enumerate who muted them.
//         So a mute must NEVER be written to the repo: doing so would publish "alice muted bob" to the
//         whole network, permanently, in a signed record. It lives HERE, node-local, never federated.
//
//   BLOCK is PUBLIC. app.bsky.graph.block IS a record in your repo and it federates by design — bsky
//         renders blocks as mutually visible. The record is written by the caller through hpp; this
//         module only remembers its RKEY so the block can be undone, and which subjects are blocked so
//         the feed can hide them without a round-trip.
//
// Both are keyed by VIEWER, because "muted" is a property of a reader, not of a post. The node-wide
// MODLIST set in bin/favela-web.js is a different thing — an operator subscribing the whole node to a
// moderation list — and the two are unioned at read time rather than merged in storage.
//
// One Hyperbee sub, key `<kind>\x00<viewerDid>\x00<subjectDid>`. A tombstone is a real delete: an unmute
// should leave no trace, which is the whole point of it being private.

const SEP = '\x00'
const KINDS = new Set(['mute', 'block'])

export function createMuteStore (bee) {
  if (!bee) throw new Error('createMuteStore requires a Hyperbee (sub)')
  const key = (kind, viewer, subject) => `${kind}${SEP}${viewer}${SEP}${subject}`
  const prefix = (kind, viewer) => `${kind}${SEP}${viewer}${SEP}`

  async function set (kind, viewer, subject, value = {}) {
    if (!KINDS.has(kind) || !viewer || !subject) return false
    if (viewer === subject) return false // muting or blocking yourself is meaningless
    await bee.put(key(kind, viewer, subject), { at: Date.now(), ...value })
    return true
  }

  async function del (kind, viewer, subject) {
    if (!KINDS.has(kind) || !viewer || !subject) return false
    try { await bee.del(key(kind, viewer, subject)) } catch { return false }
    return true
  }

  async function get (kind, viewer, subject) {
    if (!KINDS.has(kind) || !viewer || !subject) return null
    try { const r = await bee.get(key(kind, viewer, subject)); return (r && r.value) || null } catch { return null }
  }

  // Every subject of `kind` for this viewer, as a Set. One scan per page render, so the read path does
  // not do a lookup per post — a 50-post timeline would otherwise be 50 gets.
  async function subjects (kind, viewer) {
    const out = new Set()
    if (!KINDS.has(kind) || !viewer) return out
    const p = prefix(kind, viewer)
    try {
      for await (const e of bee.createReadStream({ gte: p, lt: p + '￿' })) {
        const did = String(e.key).slice(p.length)
        if (did) out.add(did)
      }
    } catch { /* an unreadable index must not blank a timeline */ }
    return out
  }

  return {
    mute: (viewer, subject) => set('mute', viewer, subject),
    unmute: (viewer, subject) => del('mute', viewer, subject),
    isMuted: async (viewer, subject) => !!(await get('mute', viewer, subject)),
    mutedBy: (viewer) => subjects('mute', viewer),
    // The block RECORD is written through hpp by the caller; `rkey` is remembered so unblock can delete
    // it. Without the rkey an unblock would have to scan the repo for a matching subject.
    block: (viewer, subject, rkey) => set('block', viewer, subject, { rkey: rkey || null }),
    unblock: (viewer, subject) => del('block', viewer, subject),
    blockRkey: async (viewer, subject) => { const v = await get('block', viewer, subject); return (v && v.rkey) || null },
    isBlocked: async (viewer, subject) => !!(await get('block', viewer, subject)),
    blockedBy: (viewer) => subjects('block', viewer)
  }
}
// notifications.js — "did anyone reply to me", answered from what THIS NODE already knows.
//
// ⛔ WHAT THIS REPLACES. /notifications rendered a shell and asked the browser for a bsky APP
// PASSWORD, then fetched bsky's notification API client-side. Three things wrong with that: it needs
// a second credential for an account you already control here; it shows bsky's view rather than this
// node's; and it is blind to ActivityPub entirely. hyper-social #45 called it "an empty shell" and
// put "the 'did anyone reply to me' loop does not work" among the five gaps that decide whether
// favela is a product.
//
// The data was already here. On the atproto side the inbound lens folds replies, quotes and likes
// that touch our content into the appview (spacedust live, Constellation backfill), so `getReplies`
// answers "who replied to this" from a local index with no credential and no remote call. On the
// ActivityPub side ap-bridge now keeps what the fediverse sends (0.0.6) and exposes it over its
// control socket. This merges the two into one list.
//
// ⛔ ONE SURFACE, BOTH NETWORKS, ATTRIBUTED. #41's rule: inbound Create/Follow/Like/Announce from the
// fediverse must land in the SAME place as atproto interactions "or we ship two inboxes and a
// confused user". They are merged here — and each item keeps its `network`, because a reply from
// Mastodon and a reply from bsky are not interchangeable and a UI that pretends otherwise is lying
// about where a conversation is happening.

// A notification is normalised to one shape regardless of which network produced it, so rendering
// does not branch per source.
//   kind    reply | like | boost | mention
//   network atproto | activitypub
//   who     display string for the author (handle, or a short did/actor)
//   when    ISO timestamp for ordering and display
//   text    what they said, when the kind carries text
//   subject what of OURS it touches (uri/objectId), for linking back
//   url     where to read it in full, when the source gives one

const AP_KIND = { Create: 'reply', Update: 'reply', Like: 'like', Announce: 'boost' }

// A remote actor URI is long and mostly noise. `https://prsm.space/users/fleeky` -> `@fleeky@prsm.space`
// — the form a fediverse user recognises as their own name.
export function actorHandle (actorUri) {
  try {
    const u = new URL(String(actorUri))
    const name = u.pathname.split('/').filter(Boolean).pop()
    return name ? '@' + name + '@' + u.host : u.host
  } catch {
    return String(actorUri || '')
  }
}

// ⛔ HTML FROM A REMOTE SERVER IS NOT MARKUP WE TRUST. ap-bridge stores `content` verbatim, which is
// correct — it is not the store's job to decide how it renders. Here it becomes TEXT: tags stripped,
// entities left for the renderer to escape. A notification line is not a place to reproduce someone
// else's markup, and treating it as such is how a mention becomes a script tag.
export function htmlToText (html) {
  return String(html || '')
    .replace(/<br\s*\/?>/gi, ' ')
    .replace(/<\/p>/gi, ' ')
    .replace(/<[^>]*>/g, '')
    .replace(/\s+/g, ' ')
    .trim()
}

/** One ap-bridge inbound item -> a notification, or null if it is not one we can present. */
export function fromApItem (item) {
  if (!item || !item.type) return null
  const kind = AP_KIND[item.type]
  if (!kind) return null
  return {
    kind,
    network: 'activitypub',
    who: actorHandle(item.actor),
    when: item.published || (item.receivedAt ? new Date(item.receivedAt).toISOString() : null),
    text: kind === 'reply' ? htmlToText(item.content) : '',
    // For a reply this is OUR post it answers; for a like/boost it is OUR post they acted on.
    subject: item.inReplyTo || item.objectId || null,
    url: item.url || item.objectId || null,
    id: item.id || null
  }
}

/** One indexed atproto reply -> a notification. `post` is an appview-hydrated reply. */
export function fromReply (post, subjectUri) {
  if (!post) return null
  const rec = post.record || {}
  return {
    kind: 'reply',
    network: 'atproto',
    who: post.handle || post.author?.handle || shortDid(post.did),
    when: rec.createdAt || post.createdAt || null,
    text: typeof rec.text === 'string' ? rec.text : '',
    subject: subjectUri || null,
    url: post.uri || null,
    id: post.uri || null
  }
}

function shortDid (did) {
  const d = String(did || '')
  const id = d.startsWith('did:plc:') ? d.slice('did:plc:'.length) : d
  return id.length > 14 ? id.slice(0, 8) + '…' + id.slice(-4) : id
}

/**
 * Merge both networks into one list, newest first.
 *
 * ⛔ YOUR OWN ACTIVITY IS NOT A NOTIFICATION. Replies you wrote to your own thread are indexed
 * exactly like anyone else's, so without this filter the list fills with your own voice — which is
 * both useless and the fastest way to make a user stop opening the page.
 *
 * Deduped by id: the same reply can arrive from more than one source (a fediverse reply that also
 * federates back, a record seen via both spacedust paths).
 */
export function mergeNotifications ({ atproto = [], activitypub = [], viewerDid = null, viewerActors = [], limit = 50 } = {}) {
  const mine = new Set([viewerDid, ...viewerActors].filter(Boolean))
  const seen = new Set()
  const out = []

  for (const n of [...atproto, ...activitypub]) {
    if (!n) continue
    if (n.authorDid && mine.has(n.authorDid)) continue
    if (n.id && seen.has(n.id)) continue
    if (n.id) seen.add(n.id)
    out.push(n)
  }

  // Undated items sort last rather than being dropped: "we do not know when" is not "it did not
  // happen", and a notification with a missing timestamp is still a notification.
  out.sort((a, b) => String(b.when || '').localeCompare(String(a.when || '')))
  return out.slice(0, limit)
}
// MOVED: the implementation now lives in atproto-room/lib/pairing.js.
//
// WHY. Blind-pairing is not a favela-web concern — it is the transport every ceremony in this stack
// uses, and hyper-proto-peer needs it too so that ANY node holding a DID (a desktop, a phone) can mint
// an invite for the next device. That is keet's model: `addDevice` is available to any active member,
// and the adder gains nothing by performing it. While this module lived here, only trees that depend on
// favela-web could mint — which meant a phone could join but never invite.
//
// The module itself was always generic: hyperswarm, blind-pairing, hypercore-crypto, b4a. Nothing
// favela-shaped ever crossed it.
//
// This re-export keeps favela-web's existing importers (bin/favela-web.js, bin/favela-pair.js,
// lib/cli.js, test/pairing.test.mjs) working unchanged. New code should import from atproto-room.
export { createPairInvite, joinPairInvite } from 'atproto-room/lib/pairing.js'
// Resolve a DID's #atproto signing pubkey (the verifyKey) from the PLC directory.
// MODULE NOTE (feedback_ask-should-this-be-a-module): the bridge resolves the same (peer-router
// resolvePlcVerifyKey). Kept favela-local for now; fold into an atproto-identity PLC helper when the
// bridge migrates. `fetch` is injectable (bare-fetch under Bare, global fetch under Node).
import { decodeDidKey } from 'atproto-identity/lib/did-key.js'

export async function resolveVerifyKey (did, { fetch: doFetch = fetch, plcUrl = 'https://plc.directory' } = {}) {
  const res = await doFetch(`${plcUrl}/${did}`)
  if (!res.ok) throw new Error(`PLC ${res.status} for ${did}`)
  const doc = await res.json()
  const vm = (doc.verificationMethod || []).find((m) => m.id && m.id.endsWith('#atproto')) || (doc.verificationMethod || [])[0]
  if (!vm || !vm.publicKeyMultibase) throw new Error(`no #atproto verificationMethod for ${did}`)
  return decodeDidKey(`did:key:${vm.publicKeyMultibase}`).pubkey
}
// postgate — who may QUOTE a post (app.bsky.feed.postgate).
//
// Same rkey binding as a threadgate: the record's rkey is IDENTICAL to the post's, and `post` carries the
// post's at:// uri. So it needs no index either — given a post we know the rkey.
//
// ⚠ THE POLARITY IS INVERTED RELATIVE TO A THREADGATE, and that is the whole trap. A threadgate carries
// `allow` — a list of who MAY reply, where an empty array means nobody. A postgate carries
// `embeddingRules` — a list of RESTRICTIONS, where an empty array means NO restrictions, i.e. anyone may
// quote. So:
//
//   threadgate  allow: []          -> nobody may reply
//   postgate    embeddingRules: [] -> ANYONE may quote
//
// The two look alike and mean opposite things. Writing one with the other's polarity silently produces
// the reverse of what the author asked for, and nothing errors.
//
// There is one rule today, #disableRule: quoting off entirely. `detachedEmbeddingUris` is the other half
// of the lexicon — specific existing quotes the author has pulled down — and is preserved on read so a
// future writer does not clobber it.

export const QUOTE_CHOICES = ['anyone', 'nobody']

// A UI choice -> the record, or null for 'anyone'. Like a threadgate's 'everyone', 'anyone' writes NO
// RECORD rather than one with an empty rule list: the absent record and the empty list happen to mean the
// same thing here, but writing nothing is unambiguous and leaves no artefact to misread later.
export function postgateRecord ({ postUri, choice, detachedEmbeddingUris = [], createdAt = new Date().toISOString() }) {
  if (choice !== 'nobody') return null
  return {
    $type: 'app.bsky.feed.postgate',
    post: postUri,
    createdAt,
    detachedEmbeddingUris,
    embeddingRules: [{ $type: 'app.bsky.feed.postgate#disableRule' }]
  }
}

// The inverse, for rendering. An unrecognised rule reads as 'limited' — never guessed permissive, since
// assuming an unknown restriction is harmless is how a protected post ends up quotable.
export function quoteChoiceOf (record) {
  if (!record) return 'anyone'
  const rules = record.embeddingRules
  if (!Array.isArray(rules) || rules.length === 0) return 'anyone' // empty = NO restrictions
  const types = rules.map((r) => String((r && r.$type) || ''))
  if (types.some((t) => t.endsWith('#disableRule'))) return 'nobody'
  return 'limited'
}

// May `viewerDid` quote a post by `authorDid`? The author may always quote their own — that is how a
// self-thread of quotes works, and every client behaves that way.
export function canQuote ({ viewerDid, authorDid, record } = {}) {
  if (!viewerDid) return false
  if (viewerDid === authorDid) return true
  const c = quoteChoiceOf(record)
  if (c === 'anyone') return true
  // 'nobody' and 'limited' both fail closed for OUR writes: posting a quote the author asked to prevent
  // is worse than declining to offer the button.
  return false
}

export function describeQuoteGate (choice) {
  switch (choice) {
    case 'nobody': return 'the author turned off quotes for this post'
    case 'limited': return 'quoting this post is limited'
    default: return ''
  }
}

// Quotes the author has individually detached. Preserved on any rewrite so a later gate change does not
// silently re-attach something they pulled down.
export function detachedUris (record) {
  const d = record && record.detachedEmbeddingUris
  return Array.isArray(d) ? d.filter((u) => typeof u === 'string') : []
}
// reach — where a post actually went.
//
// THE GAP THIS FILLS. Every public post already reaches bsky AND the fediverse, from the same record
// bytes, automatically. Verified 2026-08-05: "need to package" (2026-08-05T13:38:23.294Z) is in
// app.bsky.feed.getAuthorFeed AND in ap.7rnx.net's outbox, same timestamp. But nothing in the client
// ever said so, so the one architecturally interesting fact about this project — one record, several
// networks, no copies — was invisible to the person using it.
//
// ★ OBSERVED vs ELIGIBLE — the distinction is the whole point, and collapsing it would be a lie.
//
//   fediverse  OBSERVED. ap-bridge's outbox is the actual list of what it projected. If an rkey is
//              there, it was published. One cheap fetch covers a whole page of posts.
//   bsky       ELIGIBLE, not observed. We know bsky's AppView indexes `app.bsky.*` lexicons and
//              ignores everything else, so the collection tells us whether the post was OFFERED.
//              Whether bsky actually indexed it needs a per-post API call — too expensive for a
//              timeline, and its absence would usually mean lag rather than rejection.
//   favela     always. We hold the record; that is what "we have it" means.
//
// So the UI must not render these three identically. "went to bsky" and "bsky has it" are different
// claims, and this codebase has repeatedly paid for surfaces that reported success they had not
// checked (#24, #26: "everything we control reports success").

import { scopeForCollection } from './scopes.js'

export const TIER = Object.freeze({
  FAVELA: 'favela',
  BSKY: 'bsky',
  FEDIVERSE: 'fediverse'
})

// -> [{ tier, state }] where state is 'observed' | 'eligible'.
//
// apRkeys is a Set of rkeys ap-bridge reports having projected, or null when the AP side is not
// configured/reachable. NULL IS NOT "NO" — it means unknown, and an unknown must not render as an
// absence. A post that really did federate showing "not on the fediverse" because one HTTP call
// failed is worse than showing nothing at all.
export function reachFor ({ collection, rkey, apRkeys = null } = {}) {
  const out = [{ tier: TIER.FAVELA, state: 'observed' }]
  if (!collection) return out

  // bsky indexes app.bsky.* and silently ignores unknown lexicons — that IS the local-only mechanism
  // (scopes.js), so the collection is exactly the signal for whether the post was offered to bsky.
  const isPublic = scopeForCollection(collection) === 'public'
  if (isPublic) out.push({ tier: TIER.BSKY, state: 'eligible' })

  // Only claim the fediverse when the outbox names it AND the post is in a collection ap-bridge
  // actually projects. Unknown stays silent.
  //
  // ⚠ THE COLLECTION GATE IS LOAD-BEARING, not belt-and-braces. ap-bridge's object ids are keyed by
  // RKEY ALONE (`objectIdFor({host, rkey})`), and an rkey is unique only WITHIN a collection. So a
  // local-only post sharing an rkey with a public one would match the outbox set and render as
  // "published to the fediverse" — announcing that we federated a post whose whole purpose was NOT
  // being federated. Caught by test/reach.test.mjs; it is the same cross-collection collision
  // documented in spec/record-vocabulary.md §3.1.
  if (isPublic && apKnown(apRkeys) && rkey && apRkeys.has(rkey)) {
    out.push({ tier: TIER.FEDIVERSE, state: 'observed' })
  }
  return out
}

// True when the AP side told us anything at all. The caller uses this to distinguish "no fediverse
// row because it wasn't projected" from "no fediverse row because we couldn't ask".
export function apKnown (apRkeys) { return apRkeys instanceof Set }
// record-fetch.js — the fetch + verify halves of DESIGN §7.6's pipeline.
//
// Spacedust/Constellation tell us a record EXISTS. This module gets its bytes and proves them. Those
// are deliberately different jobs from different sources: the index is a hint, the author's PDS is the
// authority, and the DID document is the root of trust.
//
// ⛔ THE VERIFICATION KEY NEVER COMES FROM AN INDEX. `blue.microcosm.identity.resolveMiniDoc` returns a
// convenient `{did, handle, pds, signing_key}` bundle, and it is tempting to use all four. Do not use
// its `signing_key`. If we verified against a key handed to us by the same class of service that told
// us the record exists, a compromised or hostile index could serve forged records that verify. The key
// MUST come from the DID document (PLC directory for did:plc). An index may accelerate the *endpoint*
// lookup — a wrong PDS just fails to serve, which is safe — but never the key.
//
// WHY sync.getRecord AND NOT repo.getRecord. `com.atproto.repo.getRecord` returns hydrated JSON: no
// commit, no signature, no MST proof, and not byte-exact, so nothing about it can be verified.
// `com.atproto.sync.getRecord` returns a CAR carrying the signed commit plus the MST blocks that prove
// the record's inclusion at its path. Only the second can back a retention decision.
//
// WHAT "VERIFIED" MEANS HERE — all four must hold:
//   1. the commit's `did` is the DID we asked about        (no cross-repo substitution)
//   2. the commit signature validates against the DID doc's atproto key
//   3. the record CID is provably at `<collection>/<rkey>` under the commit's MST root
//   4. the record bytes hash to that CID                   (bytes match their own address)
//
// FAILS SOFT. Every path returns null/false rather than throwing. An unfetchable or unverifiable record
// is simply not retained; §7.6 makes that recoverable (Constellation can re-offer the same pointer).
//
// PURE + INJECTED. `doFetch`, the resolver and the clock are parameters, so every branch is testable
// with no network.

import { readCar, getBlock, loadCommit } from 'atproto-repo/lib/repo.js'
import { verifyCommit } from 'atproto-repo/lib/commit.js'
import { cidForBytesSync } from 'atproto-repo/lib/cid.js'
import { nodeStoreFromBlocks, findRpathProof } from 'atproto-repo/lib/mst.js'
import { decodeDidKey, CURVE_SECP256K1 } from 'atproto-identity/lib/did-key.js'
import { PlcDirectory } from 'atproto-identity/lib/plc-directory.js'

const IDENTITY_TTL_MS = 15 * 60 * 1000 // DID docs change rarely; a rotation is the thing this misses

// The MST key for a record. atproto keys the tree by `<collection>/<rkey>` as UTF-8 bytes.
export function recordKey ({ collection, rkey }) {
  return `${collection}/${rkey}`
}

// A DID doc's atproto verification method is a did:key; resolveMiniDoc-style sources hand back the bare
// `publicKeyMultibase` body instead. Accept either, since they are the same string with/without prefix.
export function toDidKey (value) {
  if (typeof value !== 'string' || value.length === 0) return null
  return value.startsWith('did:key:') ? value : `did:key:${value}`
}

// Pull the atproto signing key + PDS endpoint out of a PLC `/data` response.
// Shape: { did, verificationMethods: { atproto }, services: { atproto_pds: { endpoint } } }
export function extractIdentity (data) {
  if (!data || typeof data !== 'object') return null
  const didKey = toDidKey(data.verificationMethods && data.verificationMethods.atproto)
  const svc = data.services && data.services.atproto_pds
  const pds = svc && typeof svc.endpoint === 'string' ? svc.endpoint.replace(/\/+$/, '') : null
  if (didKey === null || pds === null) return null

  let pubkey
  try {
    const decoded = decodeDidKey(didKey)
    // atproto permits secp256k1 and P-256; our verifyCommit is secp256k1-only. Reject rather than
    // silently mis-verify — a P-256 repo should surface as unsupported, not as "invalid signature".
    if (decoded.curve !== CURVE_SECP256K1) return null
    pubkey = decoded.pubkey
  } catch {
    return null
  }
  return { did: data.did, didKey, pubkey, pds }
}

// Authoritative identity resolution with a small TTL cache.
//
// did:plc only. did:web would need a `/.well-known/did.json` fetch — not wired, and returning null is
// the honest failure (records from did:web repos are simply not retained yet) rather than guessing.
export function createIdentityResolver ({ fetchImpl, plc = null, ttlMs = IDENTITY_TTL_MS, now = () => Date.now() } = {}) {
  const directory = plc || new PlcDirectory({ fetchImpl })
  const cache = new Map()

  return async function resolveIdentity (did) {
    if (typeof did !== 'string' || !did.startsWith('did:plc:')) return null

    const hit = cache.get(did)
    if (hit && hit.expires > now()) return hit.value

    let identity = null
    try {
      identity = extractIdentity(await directory.getData(did))
    } catch {
      identity = null // network/404/malformed — fail soft, retry on the next pointer
    }
    // Cache negatives too, briefly, so a dead DID cannot drive a fetch storm through the drain.
    cache.set(did, { value: identity, expires: now() + (identity === null ? 60_000 : ttlMs) })
    return identity
  }
}

// ---- fetchRecord ----------------------------------------------------------------------------------

// Build the drain's `fetchRecord` hook.
//   fetchRecord({ did, collection, rkey }) -> { car, commit, recordCid, bytes, value, identity } | null
//
// Returns the parsed CAR alongside the record so `verifyRecord` does not re-parse. Nothing here is
// trusted yet — this function only OBTAINS; verification is the next step and is not optional.
export function createFetchRecord ({ doFetch, resolveIdentity, timeoutMs = 10_000 } = {}) {
  if (typeof doFetch !== 'function') throw new Error('createFetchRecord requires doFetch')
  if (typeof resolveIdentity !== 'function') throw new Error('createFetchRecord requires resolveIdentity')

  return async function fetchRecord (pointer) {
    const identity = await resolveIdentity(pointer.did)
    if (identity === null) return null

    const url = `${identity.pds}/xrpc/com.atproto.sync.getRecord` +
      `?did=${encodeURIComponent(pointer.did)}` +
      `&collection=${encodeURIComponent(pointer.collection)}` +
      `&rkey=${encodeURIComponent(pointer.rkey)}`

    let carBytes
    try {
      const res = await doFetch(url, {
        method: 'GET',
        headers: { accept: 'application/vnd.ipld.car' },
        timeout: timeoutMs
      })
      if (!res || res.ok === false) return null
      const buf = await res.arrayBuffer()
      carBytes = new Uint8Array(buf)
    } catch {
      return null
    }
    if (!carBytes || carBytes.length === 0) return null

    try {
      const car = await readCar(carBytes)
      const commit = loadCommit(car)
      const ns = nodeStoreFromBlocks(car.blocks)
      // Targeted descent, NOT a full walk: a proof CAR contains only the covering path, so walking the
      // whole tree would throw on absent sibling blocks.
      const { value: recordCid } = findRpathProof(ns, commit.value.data, recordKey(pointer))
      if (!recordCid) return null // exclusion proof — the record is genuinely not in the repo

      const block = getBlock(car, recordCid)
      return {
        car,
        commit,
        recordCid,
        bytes: block.bytes,
        identity
      }
    } catch {
      return null // malformed CAR, missing block, not an MST node — all "cannot use this"
    }
  }
}

// ---- verifyRecord ---------------------------------------------------------------------------------

// Build the drain's `verifyRecord` hook. Pure: bytes + already-resolved identity in, boolean out. No
// store access and no I/O, which is exactly why this is the one step that could later move to a
// `bare-thread` worker behind `bare-channel` if a profile ever justifies it.
export function createVerifyRecord ({ onFailure = null } = {}) {
  return async function verifyRecord (record, pointer) {
    if (!record || !record.commit || !record.identity) return false
    const fail = (reason) => {
      if (onFailure) onFailure(reason, pointer)
      return false
    }

    const commit = record.commit.value

    // 1. The commit must be for the repo we asked about. Without this, a validly-signed commit from a
    //    DIFFERENT repo would satisfy every other check.
    if (commit.did !== pointer.did) return fail('did-mismatch')

    // 2. Signature over the commit, against the key from the DID DOCUMENT (never from an index).
    let sigOk = false
    try {
      sigOk = verifyCommit(commit, record.identity.pubkey)
    } catch {
      sigOk = false
    }
    if (!sigOk) return fail('bad-signature')

    // 3. Inclusion: the record CID must be provably at <collection>/<rkey> under the SIGNED commit's
    //    MST root. Re-derived here rather than trusting what fetch found, so verify stands alone.
    let provenCid = null
    try {
      const ns = nodeStoreFromBlocks(record.car.blocks)
      provenCid = findRpathProof(ns, commit.data, recordKey(pointer)).value
    } catch {
      return fail('proof-failed')
    }
    if (!provenCid || provenCid.toString() !== record.recordCid.toString()) return fail('not-in-repo')

    // 4. The bytes must hash to that CID — otherwise a correct proof could be paired with wrong bytes.
    let bytesOk = false
    try {
      bytesOk = cidForBytesSync(record.bytes).toString() === record.recordCid.toString()
    } catch {
      bytesOk = false
    }
    if (!bytesOk) return fail('cid-mismatch')

    // NOTE: we deliberately do NOT require commit.rev to equal pointer.rev. getRecord returns the
    // CURRENT commit, which is legitimately newer than the commit that created the link. The rev
    // skip-test in link-drain.js is about what we already hold, not about proof validity.
    return true
  }
}
// favela SSR render layer — pure view-model → HTML string. No DOM, no JS required to READ (the
// server renders posts, hashtags become real <a href="/tag/…"> links, and moderation collapse uses a
// native <details> so warn/hide reveal works with JS disabled). The same JSON APIs + client script
// remain as progressive enhancement (live 5s refresh), but a URL renders fully server-side — the
// "P2P-less window" (DESIGN §2.6/§4.1): no install, no JS, SEO-able, RSS/Atom for free (renderAtom).
//
// Pure + injected: takes plain view-models ({ posts, cursor }, a viewer descriptor) and returns
// strings. It touches no P2P/index state, so it is unit-testable in isolation.
import { SCOPE_COLLECTION } from './scopes.js'
import { VERSION } from './version.js'
import { reachFor } from './reach.js'
import { isSafeCid } from './blob-serve.js'

const LOCAL_NSID = SCOPE_COLLECTION.local
const TAG_RE = /(?:^|\s)#([\p{L}\p{N}_]+)/gu

export function esc (s) {
  return String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]))
}

// Normalize an atproto blob `ref` to its CID string, tolerating every form the ref can arrive in:
// a decoded `{$link}` (how wj62's records store it), a dag-json `{'/':cid}`, a multiformats CID
// instance, or a bare string. Returns null if none match.
export function blobCid (ref) {
  if (!ref) return null
  if (typeof ref === 'string') return ref
  if (ref.asCID === ref && typeof ref.toString === 'function') return ref.toString()
  if (typeof ref.$link === 'string') return ref.$link
  if (typeof ref['/'] === 'string') return ref['/']
  return null
}

// The favela getBlob URL for a DID's blob — served from the SHARED overlay files (slice 3b).
function blobUrl (did, cid) {
  return `/xrpc/com.atproto.sync.getBlob?did=${encodeURIComponent(did)}&cid=${encodeURIComponent(cid)}`
}

// The image list an embed carries, if any. Handles app.bsky.embed.images and the .media side of
// app.bsky.embed.recordWithMedia (a quote-post with attached images). Other embeds → no images.
function embedImages (embed) {
  if (!embed) return []
  if (embed.$type === 'app.bsky.embed.images' && Array.isArray(embed.images)) return embed.images
  if (embed.$type === 'app.bsky.embed.recordWithMedia' && embed.media && embed.media.$type === 'app.bsky.embed.images' && Array.isArray(embed.media.images)) return embed.media.images
  return []
}

// Render a post's image embeds to <img> tags pointing at favela's getBlob (the shared overlay bytes).
// alt text is escaped; a ref whose cid is missing/unsafe is skipped (never emitted as a src). Returns ''
// when there are no images. loading=lazy so a long timeline doesn't fetch every blob eagerly.
// A LINK CARD (app.bsky.embed.external). Self-contained in the record — title/description/uri, and a
// thumb blob — so unlike a quote it needs no resolution. Rendered as one anchor: the whole card is the
// link, which is what every other client does and what a reader expects.
//
// The uri is scheme-checked before it becomes an href (same rule renderRichText applies to link facets):
// a card is attacker-supplied content and javascript: must never survive into an attribute.
// app.bsky.embed.video — a blob, like an image. Rendered as a real <video controls> rather than a
// "this post has a video" placeholder: we already serve the bytes through getBlob, so there is nothing to
// gain by refusing to play them. preload=metadata so a timeline of videos does not pull megabytes.
export function renderVideo (p) {
  const e = p && p.record && p.record.embed
  const v = e && e.$type === 'app.bsky.embed.video' ? e
    : (e && e.$type === 'app.bsky.embed.recordWithMedia' && e.media && e.media.$type === 'app.bsky.embed.video' ? e.media : null)
  if (!v) return ''
  const cid = blobCid(v.video && v.video.ref)
  if (!cid || !isSafeCid(cid) || !p.did) return ''
  const alt = esc(v.alt || '')
  return `<div class="media"><video class="vid" controls preload="metadata" playsinline src="${esc(blobUrl(p.did, cid))}"${alt ? ` aria-label="${alt}"` : ''}></video></div>`
}

export function renderExternal (p) {
  const e = p && p.record && p.record.embed
  const ext = e && e.$type === 'app.bsky.embed.external' ? e.external
    : (e && e.$type === 'app.bsky.embed.recordWithMedia' && e.media && e.media.$type === 'app.bsky.embed.external' ? e.media.external : null)
  if (!ext || typeof ext.uri !== 'string' || !/^https?:\/\//i.test(ext.uri)) return ''
  let host = ''
  try { host = new URL(ext.uri).host.replace(/^www\./, '') } catch { host = '' }
  const cid = blobCid(ext.thumb && ext.thumb.ref)
  const thumb = (cid && isSafeCid(cid) && p.did)
    ? `<img class="cardimg" src="${esc(blobUrl(p.did, cid))}" alt="" loading="lazy">`
    : ''
  return `<a class="card" href="${esc(ext.uri)}" rel="noopener nofollow ugc" target="_blank">${thumb}<span class="cardtxt">${host ? `<span class="cardhost">${esc(host)}</span>` : ''}<span class="cardtitle">${esc(ext.title || ext.uri)}</span>${ext.description ? `<span class="carddesc">${esc(ext.description)}</span>` : ''}</span></a>`
}

// A QUOTE POST. `p.quoted` is attached by the appview (_resolveQuoted) — the record only embeds a
// strongRef, and before this it rendered as NOTHING: the commentary appeared with the post it was about
// invisible, which reads as a non-sequitur.
//
// Deliberately NOT renderPost: a quoted post gets no like/repost/reply controls of its own (acting on it
// belongs on its own page) and no nested quote, so a quote-of-a-quote cannot recurse a timeline into a
// tree. It IS a link to the quoted post, so the whole card navigates there.
//
// An unresolved quote says so rather than rendering an empty box — quoting a post outside this node's
// window is normal, and a blank card would read as a broken render instead of an honest gap.
export function renderQuote (p) {
  const e = p && p.record && p.record.embed
  const isQuote = e && (e.$type === 'app.bsky.embed.record' || e.$type === 'app.bsky.embed.recordWithMedia')
  if (!isQuote) return ''
  const q = p.quoted
  if (!q || !q.record) {
    const ref = e.$type === 'app.bsky.embed.record' ? e.record : (e.record && (e.record.record || e.record))
    const uri = ref && typeof ref.uri === 'string' ? ref.uri : ''
    return `<div class="quote missingq">quoted post is outside this node\'s window${uri ? `<br><code>${esc(uri)}</code>` : ''}</div>`
  }
  const a = q.author || {}
  const name = a.displayName || (a.handleVerified && a.handle ? '@' + a.handle : shortDid(q.did))
  const cid = a.avatarCid || blobCid(a.avatar && a.avatar.ref)
  const av = (cid && isSafeCid(cid))
    ? `<img class="pfp qpfp" src="${esc(blobUrl(q.did, cid))}" alt="" loading="lazy" width="20" height="20">`
    : (a.avatarUrl && /^https:\/\//i.test(a.avatarUrl)
        ? `<img class="pfp qpfp" src="${esc(a.avatarUrl)}" alt="" loading="lazy" width="20" height="20" referrerpolicy="no-referrer">`
        : '<span class="pfp qpfp none" aria-hidden="true"></span>')
  const when = q.record.createdAt ? `<time datetime="${esc(q.record.createdAt)}">${esc(relTime(q.record.createdAt))}</time>` : ''
  const text = renderRichText(q.record.text || '', q.record.facets)
  return `<a class="quote" href="${esc(postHref(q))}"><span class="qhead">${av}<span class="qname">${esc(name)}</span>${when}</span><span class="qtext">${text}</span></a>`
}

export function renderEmbed (p) {
  const imgs = embedImages(p && p.record && p.record.embed)
  if (!imgs.length) return ''
  const many = imgs.length > 1
  const tags = imgs.map((im) => {
    const cid = blobCid(im && im.image && im.image.ref)
    if (!cid || !isSafeCid(cid)) return ''
    const url = blobUrl(p.did, cid)
    const alt = esc((im && im.alt) || '')
    // Each image is a REAL LINK to its own full-size bytes. With no JS that opens the image — which is
    // what a reader wants and what the timeline could not do at all before. With JS, actions.js
    // intercepts it and shows the lightbox. It also has to be a link for another reason: the whole post
    // is a stretched anchor to its thread, so without an element of its own an image click would open
    // the thread instead of the picture. `.post .media a` is raised above that overlay in CSS.
    return `<a class="lb" href="${esc(url)}"${alt ? ` data-alt="${alt}"` : ''}><img src="${esc(url)}" alt="${alt}" loading="lazy"></a>`
  }).filter(Boolean).join('')
  return tags ? `<div class="media${many ? ' multi' : ''}">${tags}</div>` : ''
}

// "older posts" — the cursor was computed and thrown away on every page, so a reader could only ever see
// the newest 50 and there was no way to reach anything before that. A plain link with ?cursor=, so paging
// works with scripting off; `cursor` null means the stream ended and nothing renders.
export function moreLink (cursor, baseHref = '/') {
  if (!cursor) return ''
  const sep = baseHref.includes('?') ? '&' : '?'
  return `<a class="more" href="${esc(baseHref + sep + 'cursor=' + encodeURIComponent(cursor))}" rel="next">older posts →</a>`
}

// A bare URL in post text used to render as inert characters, which is a daily papercut — people post
// links constantly. Matched conservatively: stop before trailing punctuation so "see https://x.com." does
// not swallow the full stop, and never inside an existing tag (this runs on ESCAPED text, so there are no
// tags to be inside).
const URL_RE = /\bhttps?:\/\/[^\s<]+[^\s<.,:;!?)\]}'"]/g

function linkifyUrls (escaped) {
  return escaped.replace(URL_RE, (u) => `<a class="link" href="${u}" rel="noopener nofollow ugc" target="_blank">${u}</a>`)
}

// Escape text, then linkify #hashtags into real server-navigable /tag/<tag> links (no JS needed) and
// bare URLs into anchors. This is the FALLBACK path — see renderRichText for the authoritative one.
export function renderText (t) {
  return linkifyUrls(esc(t)).replace(TAG_RE, (m, tag) => {
    const lead = m.slice(0, m.length - tag.length - 1) // preserve the leading space/BOL the regex ate
    return `${lead}<a class="tag" href="/tag/${encodeURIComponent(tag.toLowerCase())}">#${esc(tag)}</a>`
  })
}

// atproto rich text is NOT the post text re-parsed — it is `record.facets`, byte ranges into the UTF-8
// encoding of `text` carrying links, mentions and tags. Re-deriving them with a regex is guesswork that
// disagrees with what the author actually published: a link whose display text differs from its target,
// a mention, or a tag the writer did not spell with a '#' are all invisible to a regex and all normal.
//
// Offsets are BYTE offsets, so slicing must go through the UTF-8 encoding — slicing the JS string would
// mis-cut anything past the first non-ASCII character, which is most of the world's text.
export function renderRichText (text, facets) {
  const t = String(text == null ? '' : text)
  if (!Array.isArray(facets) || !facets.length) return renderText(t)
  let bytes
  try { bytes = new TextEncoder().encode(t) } catch { return renderText(t) }
  const dec = new TextDecoder()
  const slice = (a, b) => { try { return dec.decode(bytes.slice(a, b)) } catch { return '' } }

  // Sort + drop anything overlapping or out of range: a malformed facet set must degrade to plain text,
  // never to interleaved tags.
  const ranges = facets
    .filter((f) => f && f.index && Number.isInteger(f.index.byteStart) && Number.isInteger(f.index.byteEnd))
    .filter((f) => f.index.byteStart >= 0 && f.index.byteEnd <= bytes.length && f.index.byteStart < f.index.byteEnd)
    .sort((a, b) => a.index.byteStart - b.index.byteStart)

  let out = ''
  let at = 0
  for (const f of ranges) {
    if (f.index.byteStart < at) continue // overlaps the previous facet — skip rather than nest
    out += linkifyUrls(esc(slice(at, f.index.byteStart)))
    const label = esc(slice(f.index.byteStart, f.index.byteEnd))
    const feat = (Array.isArray(f.features) ? f.features : [])[0] || {}
    const type = String(feat.$type || '')
    if (type.endsWith('#link') && typeof feat.uri === 'string' && /^https?:\/\//i.test(feat.uri)) {
      out += `<a class="link" href="${esc(feat.uri)}" rel="noopener nofollow ugc" target="_blank">${label}</a>`
    } else if (type.endsWith('#tag') && typeof feat.tag === 'string') {
      out += `<a class="tag" href="/tag/${encodeURIComponent(feat.tag.toLowerCase())}">${label}</a>`
    } else if (type.endsWith('#mention') && typeof feat.did === 'string') {
      out += `<a class="mention" href="/profile/${encodeURIComponent(feat.did)}">${label}</a>`
    } else {
      out += label // unknown feature: show the text, invent no link
    }
    at = f.index.byteEnd
  }
  return out + linkifyUrls(esc(slice(at, bytes.length)))
}

// A minimal at:// splitter for rendering links. Deliberately separate from lib/strongref.js's
// parseAtUri: that one exists to gate a WRITE and is strict about nsids; this only needs did + rkey to
// build a href, and render must stay free of store-facing imports.
function parseAtUriLite (uri) {
  const parts = String(uri || '').replace(/^at:\/\//, '').split('/')
  return parts.length === 3 && parts[0].startsWith('did:') ? { did: parts[0], rkey: parts[2] } : null
}

function uriOf (p) {
  return `at://${p.did}/${(p.record && p.record.$type) || 'app.bsky.feed.post'}/${p.rkey}`
}

// A post's own page. `uriOf` was computed and thrown away before this — there was no way to link to a
// single post, which also meant no way to SHARE one.
export function postHref (p) {
  return `/post/${encodeURIComponent(p.did)}/${encodeURIComponent(p.rkey)}`
}

// did:plc:wj62ebbusln6gxo5azo6ogzo -> wj62ebbu…ogzo. Enough to tell two authors apart at a glance
// without spending a line of the post on an opaque string.
export function shortDid (did) {
  const d = String(did || '')
  const id = d.startsWith('did:plc:') ? d.slice('did:plc:'.length) : d
  return id.length > 14 ? id.slice(0, 8) + '…' + id.slice(-4) : id
}

// "2h", "3d" — the form every reader scans for. The exact value stays available in the datetime
// attribute and the title, so nothing is lost by not printing an ISO timestamp on every row.
export function relTime (iso, now = Date.now()) {
  const t = Date.parse(iso)
  if (!Number.isFinite(t)) return String(iso || '')
  const secs = Math.round((now - t) / 1000)
  if (secs < 0) return 'just now'
  if (secs < 60) return secs + 's'
  const mins = Math.round(secs / 60); if (mins < 60) return mins + 'm'
  const hrs = Math.round(mins / 60); if (hrs < 24) return hrs + 'h'
  const days = Math.round(hrs / 24); if (days < 7) return days + 'd'
  const wks = Math.round(days / 7); if (wks < 5) return wks + 'w'
  const mos = Math.round(days / 30); if (mos < 12) return mos + 'mo'
  return Math.round(days / 365) + 'y'
}

// The author line: avatar + display name, degrading to a short DID. `author` is attached server-side
// (lib/bylines.js); when it is absent — cold cache, or a pure render test — this still produces a
// usable line rather than nothing.
export function byline (p) {
  const a = p.author || {}
  const did = p.did
  // displayName -> VERIFIED handle -> short DID. The handle is only ever shown when the resolver
  // verified it bidirectionally (it yields 'handle.invalid' otherwise), so a DID claiming someone
  // else's handle can never render as that person.
  const name = a.displayName || (a.handleVerified && a.handle ? '@' + a.handle : shortDid(did))
  // Show the handle alongside a displayName too — a name alone is not an identity, and this is how
  // you tell two accounts with the same display name apart.
  const sub = (a.handleVerified && a.handle && a.displayName) ? ` <span class="handle">@${esc(a.handle)}</span>` : ''
  const href = `/profile/${encodeURIComponent(did)}`
  // The DID is kept as the link title, not printed: it is the identity that matters for verification,
  // but it should cost a hover rather than a line.
  //
  // The avatar is NOT in here. It renders as its own column beside the post body (see .prow), which is
  // the layout every mainstream client uses and the one thing our timeline most obviously lacked.
  // avatarLink() below emits it; both point at the same profile.
  return `<a class="byline" href="${href}" title="${esc(did)}"><span class="name">${esc(name)}</span>${sub}</a>`
}

// The avatar column. A separate anchor to the same profile as the byline, so it is a real link and a
// comfortable target — but aria-hidden and out of the tab order, for the same reason .pstretch is: it
// adds a MOUSE target to a destination the byline already provides, it does not add a destination.
// A keyboard or screen-reader user should not walk to the same profile twice per post.
export function avatarLink (p) {
  const a = p.author || {}
  const did = p.did
  // The appview hands back the RAW blob ref (it deliberately does not duplicate blobCid's knowledge of
  // the four shapes a ref arrives in); accept either that or an already-extracted cid.
  const cid = a.avatarCid || blobCid(a.avatar && a.avatar.ref)
  // `avatarUrl` is a LENS-supplied absolute URL, used only when we hold no blob of our own — a bsky
  // author whose profile record this node has never indexed. The profile PAGE got this in 0.3.12; the
  // per-post avatar did not, so the same account had a picture on its profile and a grey circle in the
  // timeline. https only, and no-referrer so browsing here does not leak the page you are on.
  const av = (cid && isSafeCid(cid))
    ? `<img class="pfp" src="${esc(blobUrl(did, cid))}" alt="" loading="lazy" width="42" height="42">`
    : (a.avatarUrl && /^https:\/\//i.test(a.avatarUrl)
        ? `<img class="pfp" src="${esc(a.avatarUrl)}" alt="" loading="lazy" width="42" height="42" referrerpolicy="no-referrer">`
        : '<span class="pfp none" aria-hidden="true"></span>')
  return `<a class="pavatar" href="/profile/${encodeURIComponent(did)}" aria-hidden="true" tabindex="-1">${av}</a>`
}

// One post. did → a real /profile/<did> link; moderation (hide/warn/muted) collapses into a native
// <details> so it is revealable with NO JavaScript. `treatment`/`muted`/`labels` are attached by the
// server's moderation pass (withMod) — the render just honors them.
// ── reach ─────────────────────────────────────────────────────────────────────────────────────────
//
// Where a post actually went. Every public post already reaches bsky AND the fediverse from the same
// record bytes — verified on both surfaces 2026-08-05 — and nothing in the client ever said so, so
// the one architecturally interesting fact about this project was invisible to its user.
//
// ★ OBSERVED and ELIGIBLE render DIFFERENTLY, and that is the point.
//   `fediverse` is observed — ap-bridge's outbox names the rkey, so it was published.
//   `bsky` is eligible — the lexicon is one bsky indexes, so the post was OFFERED. Whether bsky
//   actually indexed it needs a per-post API call we do not make on a timeline.
// Rendering them alike would claim something we did not check, which is the exact habit that made
// #24 and #26 hard to diagnose ("everything we control reports success").
//
// `favela` is never badged: it is true of every post on the page, so it carries no information.
// Absence is silent too — no badge means not projected OR not asked, and inventing a "not on the
// fediverse" badge from a failed HTTP call would be worse than saying nothing.
const REACH_LABEL = {
  bsky: ['bsky', 'offered to bsky — this lexicon is one its AppView indexes'],
  fediverse: ['fediverse', 'published to the fediverse — ap-bridge\'s outbox lists this post']
}
export function renderReach (p) {
  if (!p || !Array.isArray(p.reach)) return ''
  return p.reach.map((r) => {
    const spec = REACH_LABEL[r && r.tier]
    if (!spec) return ''
    const weak = r.state === 'eligible' ? ' weak' : ''
    return `<span class="badge reach${weak}" title="${esc(spec[1])}">${esc(spec[0])}</span>`
  }).join('')
}

// Stamp reach onto a post list. Kept OUT of renderPost for the same reason as withViewer: whether we
// could reach ap-bridge is a property of the request, not of the post.
export function withReach (posts, apRkeys, fn = reachFor) {
  if (!Array.isArray(posts) || typeof fn !== 'function') return posts
  for (const p of posts) {
    if (!p) continue
    const collection = (p.record && p.record.$type) || p.collection || null
    p.reach = fn({ collection, rkey: p.rkey, apRkeys }).filter((r) => r.tier !== 'favela')
  }
  return posts
}

export function renderPost (p) {
  const local = (p.record && p.record.$type) === LOCAL_NSID
  const text = renderRichText((p.record && p.record.text) || '', p.record && p.record.facets)
  const labels = Array.isArray(p.labels) ? p.labels : []
  const lbls = labels.map((v) => `<span class="lbl">${esc(v)}</span>`).join('')
  const badges = (local ? '<span class="badge">local-only</span>' : '') + renderReach(p) + lbls
  // Author ABOVE the text (a reader needs to know who is speaking before they read it) and the
  // timestamp below as a permalink — the one affordance that lets a post be shared at all.
  // Timestamp sits ON the byline line, not below it. A reader asks who and when together, and splitting
  // them cost a whole row per post while leaving .meta a mixed bag of "when" and "act on this". It is
  // still the permalink — the one affordance that lets a post be shared at all.
  const stamp = `<a class="permalink" href="${postHref(p)}"><time datetime="${esc(p.createdAt)}" title="${esc(p.createdAt)}">${esc(relTime(p.createdAt))}</time></a>`
  const head = `<div class="phead">${byline(p)}${stamp}${badges}</div>`
  // Like count is shown only when non-zero: a row of "0" on every post is noise, and an absent count
  // reads correctly as "none" without spending pixels saying so.
  // Like is a plain form POST so it works with scripting off, and carries `return` so the redirect lands
  // back where you clicked. `canLike` gates rendering it at all — an anonymous viewer gets the count only.
  const uri = p.uri || uriOf(p)
  const likes = p.likeCount > 0 ? `<span class="likes" title="${p.likeCount} like${p.likeCount === 1 ? '' : 's'}">${p.likeCount}</span>` : ''
  const likeBtn = p.canLike
    ? `<form class="likef" method="POST" action="/api/like"><input type="hidden" name="uri" value="${esc(uri)}"><input type="hidden" name="return" value="${esc(p.returnTo || '/')}"><button class="likebtn${p.viewerLiked ? ' on' : ''}" aria-pressed="${p.viewerLiked ? 'true' : 'false'}" aria-label="${p.viewerLiked ? 'unlike this post' : 'like this post'}" title="${p.viewerLiked ? 'unlike' : 'like'}">${p.viewerLiked ? '♥' : '♡'}</button>${likes}</form>`
    : (likes ? `<span class="likef">♥ ${likes}</span>` : '')
  // Reply count links INTO the thread — it is the affordance for "there is more here", so it must be
  // clickable rather than decorative. Hidden at zero, like likes.
  // ALWAYS shown, count or not. Rendering it only when replyCount > 0 (as 0.2.43 did) means there is no
  // way to START a thread from a timeline — you can only join one that already exists. The icon is the
  // affordance; the number is incidental.
  const replyLabel = p.replyCount > 0 ? `${p.replyCount} repl${p.replyCount === 1 ? 'y' : 'ies'} — open thread` : 'reply to this post'
  const replies = `<a class="replyc" href="${postHref(p)}" aria-label="${esc(replyLabel)}" title="${esc(replyLabel)}"><span aria-hidden="true">↩${p.replyCount > 0 ? ' ' + p.replyCount : ''}</span></a>`
  // Quote — a plain link that opens the composer pre-loaded with this post, so quoting works with
  // scripting off. Only for a viewer who can write; an anonymous reader gets no dead control.
  // `quotable === false` is stamped by the post page from the postgate. Offering a control whose write
  // we would refuse is worse than not offering it.
  const quoteBtn = (p.canLike && p.quotable !== false) ? `<a class="qbtn" href="/?quote=${encodeURIComponent(uri)}" aria-label="quote this post"><span aria-hidden="true">❝</span></a>` : ''
  // Delete — YOUR OWN posts only, and `isOwn` is stamped by withViewer from the viewer's DID. The server
  // re-checks ownership regardless: a hidden control is not a permission check.
  //
  // Deletion is irreversible and federates, so it asks first — but the confirm is a native <details>,
  // not a JS confirm(), so it works with scripting off exactly like the moderation collapse does. One
  // click reveals the button; the destructive act is never the first click.
  // Bookmark — private, so it is deliberately quiet: no count, no shared state, just on or off. A plain
  // form, like every other control here.
  const bmBtn = p.canLike
    ? `<form class="bmf" method="POST" action="/api/bookmark"><input type="hidden" name="uri" value="${esc(uri)}"><input type="hidden" name="return" value="${esc(p.returnTo || '/')}"><button class="bmbtn${p.viewerBookmarked ? ' on' : ''}" aria-pressed="${p.viewerBookmarked ? 'true' : 'false'}" aria-label="${p.viewerBookmarked ? 'remove bookmark' : 'save this post'}" title="${p.viewerBookmarked ? 'remove bookmark' : 'bookmark'}">${p.viewerBookmarked ? '★' : '☆'}</button></form>`
    : ''
  // Report — only on someone ELSE's post (reporting your own is meaningless) and only for a viewer who
  // could act. Needs JS and a session, and says so rather than failing silently (web/static/report.js).
  const repBtn = (p.canLike && !p.isOwn)
    ? `<button class="reportbtn" type="button" data-uri="${esc(uri)}"${p.cid ? ` data-cid="${esc(p.cid)}"` : ''} aria-label="report this post" title="report">⚑</button>`
    : ''
  // Edit sits BEFORE delete and is a plain link, not a <details> confirm: editing is reversible
  // (edit again), deleting is not. Presenting them with equal weight would invite the wrong one.
  const editBtn = p.isOwn && !p.focusedEdit
    ? `<a class="editlink" href="/edit/${encodeURIComponent(p.did)}/${encodeURIComponent(p.rkey)}?return=${encodeURIComponent(p.returnTo || '/')}" aria-label="edit this post">✎</a>`
    : ''
  const delBtn = p.isOwn
    ? `<details class="delw"><summary aria-label="delete this post"><span aria-hidden="true">🗑</span></summary><form class="delf" method="POST" action="/api/delete"><input type="hidden" name="uri" value="${esc(uri)}"><input type="hidden" name="return" value="${esc(p.returnTo || '/')}"><button class="delbtn">really delete</button></form></details>`
    : ''
  // Repost mirrors like: a plain form toggle, count hidden at zero, anonymous sees the count only.
  const rpCount = p.repostCount > 0 ? `<span class="rps">${p.repostCount}</span>` : ''
  const repostBtn = p.canLike
    ? `<form class="rpf" method="POST" action="/api/repost"><input type="hidden" name="uri" value="${esc(uri)}"><input type="hidden" name="return" value="${esc(p.returnTo || '/')}"><button class="rpbtn${p.viewerReposted ? ' on' : ''}" aria-pressed="${p.viewerReposted ? 'true' : 'false'}" aria-label="${p.viewerReposted ? 'undo repost' : 'repost this post'}" title="${p.viewerReposted ? 'undo repost' : 'repost'}">⇄</button>${rpCount}</form>`
    : (rpCount ? `<span class="rpf">⇄ ${rpCount}</span>` : '')
  // A reply says so, and links to what it answers — otherwise it reads as a non-sequitur in a timeline.
  const parentUri = p.record && p.record.reply && p.record.reply.parent && p.record.reply.parent.uri
  const pref = parentUri ? parseAtUriLite(parentUri) : null
  const inReply = pref ? `<div class="inreply">↩ in reply to <a href="/post/${encodeURIComponent(pref.did)}/${encodeURIComponent(pref.rkey)}">${esc(shortDid(pref.did))}</a></div>` : ''
  // ★ "edited" is DERIVED, not a record field. The firehose op's action said `update`, and the index
  // recorded that at ingest (spec §10.5.2 — atproto's $orig/$hist pattern exists because atproto has
  // no history; this substrate has some). It sits next to the timestamp because that is where a
  // reader looks to ask "when", and an edit is an answer to that question.
  const editedMark = p.editedAt
    ? ` <span class="edited" title="edited ${esc(p.editedAt)} — the original time is kept">(edited)</span>`
    : ''
  // .meta is now purely the controls row: one job, so it can be spaced and sized as one.
  //
  // ★ PRIMARY THREE, then an overflow. This is forced by arithmetic, not taste: every control needs a
  // 44px target, and seven of them plus their counts do not fit the 366px a 390px phone leaves — the
  // row wrapped to two lines. Reply/repost/like are the ones bsky keeps visible, and they are the ones
  // that act on the post itself; quote, bookmark, report, edit and delete are about YOUR relationship
  // to it and can cost a tap. Native <details>, the same no-JS pattern the delete confirm already
  // uses, so the menu opens with scripting off.
  const secondary = quoteBtn + bmBtn + repBtn + editBtn + delBtn
  const more = secondary
    ? `<details class="morew"><summary aria-label="more actions" title="more actions"><span aria-hidden="true">\u22ef</span></summary><div class="moremenu">${secondary}</div></details>`
    : ''
  const meta = `<div class="meta">${replies}${repostBtn}${likeBtn}${more}${editedMark}</div>`
  // The WHOLE ENTRY opens the thread. Until now the only ways in were the timestamp and the ↩ icon —
  // two ~10px targets on a card as wide as the page — so the reply view, which is where a conversation
  // actually lives, was the hardest thing here to reach.
  //
  // Done as a "stretched link": ONE real <a> absolutely positioned over the card, with every genuinely
  // interactive descendant raised above it in CSS (see .pstretch in STYLE). Deliberately NOT a wrapping
  // anchor — a post contains anchors (byline, tags, mentions) and forms (like, repost), and an <a> may
  // legally contain neither. Deliberately NOT a JS click handler either: this is a real link, so
  // middle-click, ctrl-click, "copy link address" and no-JS reading all keep working.
  //
  // aria-hidden + tabindex="-1" because the timestamp permalink and the ↩ link already point HERE and
  // are already in the tab order. A third identical link would make a keyboard or screen-reader user
  // walk the same destination three times per post. The overlay adds a MOUSE target for a destination
  // that is already reachable — it does not add a destination.
  //
  // Suppressed on the focused post of a thread page (`p.focused`): a page linking to itself is a dead
  // click, and the overlay would sit on top of the one post the reader opened the page to read.
  const stretch = p.focused ? '' : `<a class="pstretch" href="${postHref(p)}" aria-hidden="true" tabindex="-1"></a>`
  // ★ TWO COLUMNS: avatar beside the content, not above it. This is the layout every mainstream client
  // uses and the largest single thing our timeline was missing — full-width text under a small avatar
  // reads as a log, not a feed.
  //
  // Done as an inner .prow rather than by making .post itself a grid, because .post is ALSO the
  // <details> element in the collapsed-moderation case; a grid there would lay the <summary> out as a
  // column. The row wraps only the body, so the summary keeps sitting above it untouched.
  //
  // .pbody carries min-width:0 in CSS — without it a long unbroken word in a post makes the text
  // column refuse to shrink and pushes the card wider than the screen.
  const row = `<div class="prow">${avatarLink(p)}<div class="pbody">${head}${inReply}<div class="text">${text}</div>${renderEmbed(p)}${renderVideo(p)}${renderExternal(p)}${renderQuote(p)}${meta}</div></div>`
  const body = `${stretch}${row}`
  const collapse = p.treatment === 'hide' || p.treatment === 'warn' || p.muted
  if (collapse) {
    const reason = p.muted ? '🔇 muted account' : (p.treatment === 'hide' ? `◼ hidden by a label (${esc(labels.join(', '))})` : `⚠ ${esc(labels.join(', '))}`)
    return `<details class="post collapsed"><summary>${reason}</summary>${body}</details>`
  }
  return `<article class="post">${body}</article>`
}

// Stamp the per-viewer affordances onto a post list. Kept OUT of renderPost so the render stays a pure
// function of its input: whether a like button appears is a property of the page, not of the post.
export function withViewer (posts, viewer, returnTo = '/') {
  if (!Array.isArray(posts)) return posts
  const canLike = !!(viewer && viewer.did)
  for (const p of posts) { if (p) { p.canLike = canLike; p.returnTo = returnTo; p.isOwn = !!(viewer && viewer.did && p.did === viewer.did) } }
  return posts
}

// An empty state must distinguish "nothing here" from "something is broken". Grey italic text did not:
// an empty timeline, a profile with no posts, and a failed index all rendered the same single line.
//
// `hint` is the second half — what to DO, when there is something. Deliberately optional: inventing an
// action for a state that has none ("no notifications yet — why not get some?") is worse than silence.
// `hintHtml` is for the rare hint carrying a link; every other path is escaped text.
export function emptyState (title, hint = '', hintHtml = '') {
  const h = hintHtml || (hint ? esc(hint) : '')
  // NOT `.empty` — that class is also carrying explanatory helper text all over the settings page, so
  // restyling it would turn eight paragraphs of prose into dashed empty-boxes. Distinct class instead.
  return `<div class="emptyst"><span class="empty-t">${esc(title)}</span>${h ? `<span class="empty-h">${h}</span>` : ''}</div>`
}

// Accepts a plain string (every existing caller) or { title, hint, hintHtml }. Keeping the string form
// working means this is additive — no caller has to change to keep rendering what it rendered before.
export function renderPosts (posts, empty = 'no posts yet') {
  if (posts && posts.length) return posts.map(renderPost).join('')
  if (empty && typeof empty === 'object') return emptyState(empty.title || 'nothing here', empty.hint, empty.hintHtml)
  return emptyState(String(empty))
}

// Accept EITHER shape: the { post, replies } tree getPostThread returns, or a flat array of posts (what
// the one-level reply list used to be). A caller that passes the old shape gets a one-level thread rather
// than silence — rendering nothing with no error is the worst failure mode there is, and it is exactly
// what happened here when the shape changed under a caller that had not been updated.
function asThreadNodes (replies) {
  if (!Array.isArray(replies)) return []
  return replies.map((r) => (r && r.post) ? r : (r ? { post: r, replies: [] } : null)).filter(Boolean)
}

// A reply TREE, not a list. Children are nested INSIDE their parent's element, so one CSS rule
// (`.tnode .tnode`) produces the accumulating indent and thread line — no depth arithmetic here, and no
// inline styles. Depth is already bounded by getPostThread, so this recursion is bounded too.
export function renderThread (replies, viewer, returnTo) {
  const nodes = asThreadNodes(replies)
  if (!nodes.length) return ''
  return nodes.map((n) => {
    const p = withViewer([n.post], viewer, returnTo)[0]
    return `<div class="tnode">${renderPost(p)}${renderThread(n.replies, viewer, returnTo)}</div>`
  }).join('')
}

// Count the whole subtree, so the heading says "8 replies" when six of them are nested rather than
// claiming 2 because only the direct children were counted.
export function countThread (replies) {
  let n = 0
  for (const node of asThreadNodes(replies)) n += 1 + countThread(node.replies)
  return n
}

// ── page shell ────────────────────────────────────────────────
const STYLE = `
body{font-family:system-ui,sans-serif;max-width:620px;margin:2rem auto;padding:0 1rem;color:var(--fg)}
a{color:var(--accent)}h1{font-size:var(--f4)}h1 small{color:var(--fg-faint);font-weight:400}
nav{margin:.4rem 0 1rem;display:flex;gap:1rem;font-size:var(--f1)}
.post{position:relative;border-bottom:1px solid var(--line);padding:.8rem 0}.post .text{white-space:pre-wrap}
/* The whole-entry link emitted by renderPost. It covers the card and sits UNDER everything, so the
   card is one big click target for "open this thread". */
.pstretch{position:absolute;inset:0;z-index:0}
/* With scripting on, POSTCLICK takes the overlay out of the hit test and handles the click itself, so
   that dragging across a post still SELECTS its text. Scripting off: this class is never added and the
   overlay above does the whole job. */
.js-postclick .pstretch{pointer-events:none}
/* …and everything genuinely interactive is lifted above it, keeping its own behaviour: the byline goes
   to a profile, a tag/mention/url in the text goes where it points, like/repost stay buttons, and a
   collapsed post's <summary> still toggles rather than navigating. Anything NOT listed here (the text
   itself, images, empty space, padding) falls through to the thread — which is the point. */
.post .byline,.post .pavatar,.post .phead .permalink,.post .inreply a,.post .text a,.post .meta a,.post .meta form,.post .media a,.post .quote,.post .card,.post .delw,details.post>summary{position:relative;z-index:1}
/* A click target with no hover state is invisible until you happen to click it. Kept faint: it must
   read as "this row is live", not as a selected state. */
.post:hover{background:var(--bg-soft)}
/* No hover where there is no link to follow: the focused post of a thread, and a collapsed post while
   it is still closed (its overlay lives inside the hidden content, so there is nothing to click yet). */
.focus .post:hover,details.post.collapsed:not([open]):hover{background:none}
.post .media{margin-top:.5rem}.post .media img{max-width:100%;height:auto;border-radius:.5rem;display:block;margin:.3rem 0;background:var(--bg-soft)}
details.post>summary{cursor:pointer;color:var(--fg-faint);font-style:italic;list-style:revert}
.meta{color:var(--fg-faint);font-size:var(--f0);margin-top:.35rem}.meta .did{color:var(--fg-faint)}
.controls{display:flex;gap:.5rem;align-items:center;margin-top:.4rem}.controls select,.controls button{font:inherit;padding:.3rem}
.badge{display:inline-block;font-size:var(--f0);font-weight:600;padding:.05rem .4rem;border-radius:.6rem;margin-left:.4rem;background:var(--badge-bg);color:var(--accent)}
.lbl{display:inline-block;font-size:var(--f0);font-weight:600;padding:.05rem .4rem;border-radius:.6rem;margin-left:.4rem;background:var(--danger-bg);color:var(--danger-text)}
.tag{text-decoration:none}.tag:hover{text-decoration:underline}
.viewhdr{margin:.6rem 0;font-weight:600}.empty{color:var(--fg-faint);font-style:italic}
.who{font-size:var(--f1);color:var(--fg-faint);margin-left:auto}
.phead{display:flex;align-items:center;gap:.5rem;flex-wrap:wrap;margin-bottom:.35rem}
.byline{display:flex;align-items:center;gap:.5rem;text-decoration:none;color:inherit;min-width:0}
.byline:hover .name{text-decoration:underline}
.byline .name{font-weight:600;font-size:var(--f2);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.pfp{width:42px;height:42px;border-radius:50%;object-fit:cover;background:var(--line);flex:none}
.pfp.none{display:inline-block;background:var(--line)}
.pfp.big{width:72px;height:72px}
.meta .permalink{color:var(--fg-faint);text-decoration:none}.meta .permalink:hover{text-decoration:underline}
.mention{text-decoration:none;font-weight:500}.mention:hover{text-decoration:underline}
.profhdr{display:flex;gap:.9rem;align-items:flex-start;margin:.6rem 0 1rem}
.profname{font-size:var(--f3);font-weight:700}
.profdid code{font-size:var(--f0);color:var(--fg-faint);word-break:break-all}
.profbio{margin:.4rem 0 0;white-space:pre-wrap}
.aturi code{font-size:var(--f0);word-break:break-all}
.replyc{color:var(--fg-faint);text-decoration:none}.replyc:hover{text-decoration:underline}
.rpf{display:inline;margin-left:.15rem}
.rpbtn{font:inherit;font-size:var(--f1);line-height:1;border:none;background:none;color:var(--fg-faint);cursor:pointer;padding:0 .15rem}
.rpbtn.on{color:var(--repost)}.rpbtn:hover{color:var(--repost)}
.rps{color:var(--fg-faint);font-size:var(--f0)}
.inreply{font-size:var(--f0);color:var(--fg-faint);margin-bottom:.25rem}
.replyf{margin:.8rem 0;padding:.6rem;border:1px solid var(--line);border-radius:.5rem}
.replyf textarea{width:100%;box-sizing:border-box;font:inherit;padding:.4rem;border:1px solid var(--line);border-radius:.3rem}
.replyf p{display:flex;align-items:center;gap:.5rem;margin:.4rem 0 0}
.replyf button{font:inherit;padding:.3rem .9rem;cursor:pointer}
.thread{margin-top:1rem;border-top:2px solid var(--line);padding-top:.5rem}
.thread h3{font-size:var(--f1);color:var(--fg-dim);margin:.3rem 0}
/* Nested replies: children live INSIDE the parent node, so this one rule gives the accumulating indent
   and the thread line at every depth. Capped padding keeps a deep chain from marching off-screen. */
.tnode .tnode{margin-left:.5rem;padding-left:.7rem;border-left:2px solid var(--line-soft)}
.focus{border-left:3px solid #444;padding-left:.6rem;margin:.4rem 0}
/* A lens is a NAMED FOREIGN source. Styled visibly apart from our own posts — a reader must never have
   to guess whether a reply is one this node holds or one it is relaying from someone else's AppView. */
.lens{margin-top:1rem;border-top:1px dashed var(--lens-line);padding-top:.5rem}
/* The ancestor fill sits ABOVE the focused post, so its rule belongs on the bottom edge — otherwise the
   section reads as separating itself from the post it precedes. */
.lensup{margin:.3rem 0 .6rem;border-top:0;border-bottom:1px dashed var(--lens-line);padding:0 0 .4rem}
.lens h3{font-size:var(--f1);color:var(--fg-dim);font-weight:600;margin:.3rem 0}
.lensname{color:var(--lens)}
.lpost{border-left:2px solid var(--lens-edge);padding:.3rem 0 .3rem .7rem;margin:.4rem 0}
.lwho{font-size:var(--f1);font-weight:600}
.lhandle{font-weight:400;color:var(--fg-faint)}
.ltext{white-space:pre-wrap;margin:.15rem 0}
.lensoff{font-size:var(--f0);margin-top:1rem}
.lensnote{font-size:var(--f0);color:var(--fg-dim);margin:.4rem 0 0}
.qbtn{color:var(--fg-faint);text-decoration:none}.qbtn:hover{color:var(--accent)}
.delw{display:inline}
.delw>summary{display:inline;list-style:none;cursor:pointer;color:var(--fg-faint)}
.delw>summary::-webkit-details-marker{display:none}
.delw>summary:hover{color:var(--danger)}
.delf{display:inline;margin-left:.3rem}
.delbtn{font:inherit;font-size:var(--f0);border:1px solid var(--danger);background:var(--danger);color:#fff;border-radius:999px;padding:.15rem .5rem;cursor:pointer}
.delbtn:hover{filter:brightness(1.1)}
.modrow{display:flex;align-items:center;gap:.6rem;margin-top:.5rem;font-size:var(--f1)}
.modf{display:inline}
.mutebtn{font:inherit;font-size:var(--f1);border:none;background:none;color:var(--fg-faint,#888);cursor:pointer;padding:.2rem 0;text-decoration:underline}
.mutebtn:hover{color:var(--fg,#111)}.mutebtn.on{color:var(--fg-dim,#666)}
.modw{display:inline}
.modw>summary{display:inline;list-style:none;cursor:pointer;color:var(--fg-faint,#888);text-decoration:underline}
.modw>summary::-webkit-details-marker{display:none}
.modw>summary:hover{color:var(--danger)}
.blockbtn{font:inherit;font-size:var(--f0);border:1px solid var(--danger);background:var(--danger);color:#fff;border-radius:999px;padding:.2rem .6rem;cursor:pointer;margin-left:.3rem}
.blockbtn.on{background:none;color:var(--danger)}
.navsearch{margin-left:auto}
.navsearch input{font:inherit;font-size:var(--f1);padding:.2rem .5rem;border:1px solid var(--line,#e5e5e5);border-radius:999px;background:var(--bg,#fff);color:inherit;width:8rem}
.navsearch input:focus{outline:2px solid var(--accent,#1a56db);outline-offset:1px;width:11rem}
.searchbox{display:flex;gap:.5rem;margin:.6rem 0 1rem}
.searchbox input{flex:1;font:inherit;padding:.45rem .7rem;border:1px solid var(--line,#e5e5e5);border-radius:999px;background:var(--bg,#fff);color:inherit}
.searchbox button{font:inherit;padding:.4rem 1rem;border:none;border-radius:999px;background:var(--accent,#1a56db);color:var(--bg);font-weight:600;cursor:pointer}
.actorrow{padding:.4rem 0;border-bottom:1px solid var(--line-soft,#f0f1f3)}
.gatenote{font-size:var(--f1);color:var(--fg-dim,#666);margin:.6rem 0 0}
.gateoff{font-size:var(--f1);margin:.6rem 0 0}
.draftnote{font-size:var(--f0);color:var(--fg-dim,#5c6672);margin:0 0 .3rem}
/* The composer control row. It was a single non-wrapping flex line, which was fine with ONE select and
   broke once scope/lang/quotes/replies were all added: the row overflowed its container and the image
   picker and post button ended up outside it. Four dropdowns is simply more than one line holds at 640px,
   and less on a phone — so it wraps, and every item is allowed to shrink. */
.controls{flex-wrap:wrap;gap:.4rem .7rem;row-gap:.5rem}
.controls label{display:inline-flex;align-items:center;gap:.3rem;min-width:0;font-size:var(--f1);color:var(--fg-dim,#5c6672)}
/* min-width:0 is the load-bearing half: a flex item defaults to min-width:auto, so a select refuses to
   shrink below its longest option and pushes its siblings out of the box instead of wrapping. */
.controls select,.controls button{min-width:0;max-width:100%;border:1px solid var(--line);border-radius:var(--r1);background:var(--bg);color:inherit}
/* The post button always ends the row, on whatever line it lands on. */
#post-btn{margin-left:auto;flex:none}
.cc{flex:none}
#img-controls{flex:none}
.composerhint{font-size:var(--f0);color:var(--fg-faint,#6b7480);margin:.4rem 0 0}
/* Which identity this form writes as. Above the textarea because it has to be read BEFORE typing, not
   discovered after posting; strong enough to be seen, quiet enough not to shout on every page. */
/* Staleness. Above everything, because it qualifies everything below it — but a notice, not an alarm:
   it is frequently true and correctly ignorable on a P2P node. */
.stale{font-size:var(--f1);background:var(--bg-soft);border:1px solid var(--line);border-left:3px solid var(--warn);border-radius:var(--r1);padding:.45rem .6rem;margin:0 0 var(--s3)}
.composerwho{font-size:var(--f0);color:var(--fg-faint,#6b7480);margin:0 0 .4rem}
.composerwho strong{color:var(--fg);font-weight:600}
@media(max-width:640px){
  /* On a phone the labels alone fill a line, so give the selects room and let each pair own its width. */
  .controls{gap:.35rem .5rem}
  .controls label{flex:1 1 45%}
  .controls select{flex:1 1 auto}
  #post-btn{margin-left:0;flex:1 1 100%}
}
.reportbtn{font:inherit;font-size:var(--f1);border:none;background:none;color:var(--fg-faint,#6b7480);cursor:pointer;padding:.3rem .35rem;margin:-.3rem -.1rem}
.reportbtn:hover{color:var(--danger)}
.reportbox{display:flex;flex-wrap:wrap;gap:.4rem;align-items:center;margin-top:.4rem;padding:.5rem;border:1px solid var(--line,#e5e5e5);border-radius:var(--r1,.375rem);font-size:var(--f1)}
.reportbox select,.reportbox input,.reportbox button{font:inherit;font-size:var(--f1);padding:.25rem .4rem}
.reportbox input{flex:1;min-width:8rem}
.lmedia{display:flex;gap:.4rem;flex-wrap:wrap;margin-top:.35rem}
.lthumb{width:110px;height:110px;object-fit:cover;border-radius:var(--r1,.375rem);background:var(--bg-soft,#f3f4f6)}
.listrow{display:flex;align-items:center;gap:.6rem;flex-wrap:wrap;padding:.6rem 0;border-bottom:1px solid var(--line,#e5e5e5);text-decoration:none;color:inherit}
.listrow:hover{background:var(--bg-soft,#f7f8fa)}
.listname{font-weight:600}
.listkind{font-size:var(--f0);color:var(--fg-faint,#6b7480);border:1px solid var(--line,#e5e5e5);border-radius:999px;padding:.05rem .5rem}
.listkind.mod{color:var(--danger);border-color:var(--danger)}
.listdesc{font-size:var(--f1);color:var(--fg-dim,#5c6672);width:100%}
.profbanner{margin:0 0 .6rem;border-radius:var(--r2,.625rem);overflow:hidden;background:var(--bg-soft,#f7f8fa)}
.profbanner img{display:block;width:100%;aspect-ratio:3/1;object-fit:cover}
.profbanner.small img{aspect-ratio:4/1}
.bmf{display:inline}
.bmbtn{font:inherit;font-size:var(--f1);line-height:1;border:none;background:none;color:var(--fg-faint);cursor:pointer;padding:.3rem .45rem;margin:-.3rem -.1rem;transition:transform .08s ease,color .12s ease;touch-action:manipulation}
.bmbtn:hover{color:var(--bookmark)}.bmbtn.on{color:var(--bookmark)}
.bmbtn:active{transform:scale(.88)}
.bmbtn:focus-visible{outline:2px solid var(--accent);outline-offset:2px;border-radius:.3rem}
/* a11y. A skip link is the difference between reaching the content and tabbing the whole nav on every
   page; it is visually hidden until focused, which is the one time it matters. */
.skip{position:absolute;left:-9999px;top:0;z-index:200;background:var(--accent,#1a56db);color:var(--bg);padding:.5rem .9rem;border-radius:0 0 .4rem 0}
.skip:focus{left:0}
main:focus{outline:none}
/* Visually hidden but ANNOUNCED — for labels that would be redundant on screen and essential aloud.
   Deliberately not display:none, which removes it from the accessibility tree entirely. */
.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap;border:0}
/* Every interactive element gets a visible focus ring, not just the ones styled by hand. */
a:focus-visible,button:focus-visible,input:focus-visible,textarea:focus-visible,select:focus-visible,summary:focus-visible{outline:2px solid var(--accent,#1a56db);outline-offset:2px;border-radius:.2rem}
.quote{display:block;border:1px solid var(--line,#e5e5e5);border-radius:var(--r2,.625rem);padding:.5rem .6rem;margin-top:.5rem;text-decoration:none;color:inherit}
.quote:hover{background:var(--bg-soft,#fafafa)}
.qhead{display:flex;align-items:center;gap:.35rem;font-size:var(--f1);color:var(--fg-dim,#666)}
.qname{font-weight:600;color:var(--fg,#111)}
.qpfp{width:20px;height:20px}
.qtext{display:block;margin-top:.25rem;white-space:pre-wrap;font-size:var(--f1)}
.missingq{color:var(--fg-faint,#888);font-style:italic;font-size:var(--f1)}
.card{display:flex;gap:.6rem;align-items:stretch;border:1px solid var(--line,#e5e5e5);border-radius:var(--r2,.625rem);overflow:hidden;margin-top:.5rem;text-decoration:none;color:inherit}
.card:hover{background:var(--bg-soft,#fafafa)}
.cardimg{width:88px;height:88px;object-fit:cover;flex:none}
.cardtxt{display:flex;flex-direction:column;justify-content:center;padding:.5rem .6rem;min-width:0}
.cardhost{font-size:var(--f0);color:var(--fg-faint,#888);text-transform:lowercase}
.cardtitle{font-weight:600;font-size:var(--f1);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.carddesc{font-size:var(--f1);color:var(--fg-dim,#666);display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}
.vid{width:100%;max-height:70vh;border-radius:var(--r2,.625rem);background:#000;display:block}
.qpreview{font-size:var(--f1);color:var(--fg-dim,#666);border-left:3px solid var(--accent,#1a56db);padding:.2rem .5rem;margin-bottom:.5rem}
.qptext{font-style:italic}
.qcancel{font-size:var(--f0)}
.stath{font-size:var(--f1);color:var(--fg-dim);margin:1rem 0 .3rem;text-transform:uppercase;letter-spacing:.03em}
.statblk{border:1px solid var(--line);border-radius:4px;padding:.5rem .6rem;margin:.4rem 0}
.statblk.alarm{border-color:var(--danger);background:var(--danger-bg)}
.statdid{font-size:var(--f0);color:var(--fg-dim)}
.statsum{font-size:var(--f1);margin:.2rem 0 .4rem}
.stattbl{border-collapse:collapse;font-size:var(--f0);width:100%}
.stattbl th{text-align:left;color:var(--fg-faint);font-weight:600;padding:.15rem .4rem .15rem 0}
.stattbl td{padding:.15rem .4rem .15rem 0;border-top:1px solid #f1f1f1}
.stattbl tr.chosen td{font-weight:600;background:#f8f9ff}
.alarmnote{color:var(--danger);font-size:var(--f1);margin:.4rem 0 0}
.ok{color:var(--ok)}.bad{color:var(--danger)}
.ptabs{display:flex;gap:.15rem;border-bottom:1px solid var(--line);margin:.6rem 0 .3rem;flex-wrap:wrap}
.ptab{padding:.35rem .7rem;font-size:var(--f1);color:var(--fg-dim);text-decoration:none;border-bottom:2px solid transparent}
.ptab:hover{color:var(--fg)}
.ptab.on{color:var(--fg);font-weight:600;border-bottom-color:#444}
.ancestor{opacity:.72}
.missing{font-size:var(--f0);border-left:2px dashed var(--line);padding-left:.6rem}
.likes{color:var(--fg-faint);font-size:var(--f0)}
.likef{display:inline;margin-left:.5rem}
.likebtn{font:inherit;font-size:var(--f1);line-height:1;border:none;background:none;color:var(--fg-faint);cursor:pointer;padding:0 .15rem}
.likebtn.on{color:var(--like)}.likebtn:hover{color:var(--like)}
/* Responsive controls. These used to be plain form POSTs that reloaded the whole page to toggle a heart —
   correct, and it felt broken. /static/actions.js now posts JSON and updates in place; this is the part
   that makes the press FEEL like it landed:
     - a tactile :active scale, so the click registers before the network does
     - a wider hit area (touch targets were ~14px; a thumb needs far more)
     - .failed briefly reddens a control whose write did NOT land, because the optimistic flip is rolled
       back and a silent revert is indistinguishable from never having clicked. */
.likebtn,.rpbtn,.followbtn{transition:transform .08s ease,color .12s ease,opacity .12s ease;touch-action:manipulation}
/* The hit area is stated, not inherited. It used to fall out of glyph size plus padding, which meant
   dropping the font from 14.4px to 14px silently took it to 23.59px — under WCAG 2.2 AA 2.5.8, which
   asks 24x24. A target size that moves when someone edits a font scale is not a target size.

   24px is the floor; Material asks 48dp and Apple 44pt. Getting there by PADDING would make the
   controls row 44px tall and push every post apart, so the target is expanded without expanding the
   box: a transparent ::after stretched past the button's bounds. That is what bsky does natively —
   PostControls sets an explicit hitSlop on every control — and this is the CSS equivalent. The inset
   is half the row gap horizontally, so neighbouring targets meet exactly and never overlap.

   First attempt grew the target with a transparent ::after, the way bsky's hitSlop does. Measured, it
   only half worked: it fixed height everywhere but could not fix width, because a fixed inset applied
   to a 6px-wide glyph still yields 22px (.qbtn measured 22x39, .replyc 36x39). And insets that DID
   reach 44 would have overlapped their neighbours, so the wrong control gets tapped.

   So the controls are real 44x44 boxes. Target equals box, which means neighbours cannot overlap by
   construction, and the row can use a small gap: 7 controls x 44 + 6 x 4 = 332px, inside the 366px a
   390px phone gives. */
.likebtn,.rpbtn,.bmbtn,.reportbtn,.replyc,.qbtn,.editlink,.delw>summary,.morew>summary{
  display:inline-flex;align-items:center;justify-content:center;
  min-width:44px;min-height:44px;box-sizing:border-box}
.likebtn,.rpbtn{padding:0;margin:0}
/* Overflow menu. A native <details>, like the delete confirm, so it opens with scripting off. The
   panel is absolutely positioned so opening it never reflows the timeline underneath — a menu that
   pushes every post below it down is how you lose your place in a feed. */
.morew{position:relative;display:inline-flex}
.morew>summary{list-style:none;cursor:pointer;color:var(--fg-faint);border-radius:999px}
.morew>summary::-webkit-details-marker{display:none}
.morew>summary:hover{color:var(--fg);background:var(--bg-soft)}
.morew[open]>summary{color:var(--fg);background:var(--bg-soft)}
.moremenu{position:absolute;right:0;top:100%;z-index:20;display:flex;align-items:center;gap:var(--s1);
  padding:var(--s1);background:var(--bg);border:1px solid var(--line);border-radius:var(--r2);
  box-shadow:0 4px 16px rgba(0,0,0,.12)}
/* The menu's own controls keep their 44px targets — an overflow is not an excuse for a smaller one. */
.moremenu>*{flex:none}
.likebtn:active,.rpbtn:active,.followbtn:active{transform:scale(.88)}
.likebtn[disabled],.rpbtn[disabled],.followbtn[disabled]{opacity:.55;cursor:default}
.likebtn.failed,.rpbtn.failed,.followbtn.failed{color:var(--danger);animation:shake .25s}
@keyframes shake{25%{transform:translateX(-2px)}75%{transform:translateX(2px)}}
/* Keyboard users get the same affordance the mouse does — these are real buttons, so make focus visible. */
.likebtn:focus-visible,.rpbtn:focus-visible,.followbtn:focus-visible,.replyc:focus-visible{outline:2px solid var(--accent);outline-offset:2px;border-radius:.3rem}
@media(prefers-reduced-motion:reduce){.likebtn,.rpbtn,.followbtn{transition:none}.likebtn.failed,.rpbtn.failed,.followbtn.failed{animation:none}}
.followf{margin:.5rem 0 0}
.followbtn{font:inherit;border:1px solid var(--accent);background:var(--accent);color:var(--bg);border-radius:.4rem;padding:.3rem .9rem;cursor:pointer}
.followbtn.on{background:none;color:var(--accent)}
.scopenote{color:var(--fg-faint);font-weight:400}
.profnet{margin:.3rem 0;font-size:var(--f1)}
.fol{display:inline-block;margin:.1rem .3rem .1rem 0;color:#356}
.folmore{color:var(--fg-faint)}
.profgraph{margin:.4rem 0 0;font-size:var(--f1);color:var(--fg-dim)}
.cc{font-size:var(--f0);color:var(--fg-faint);margin-left:auto}.cc.over{color:var(--danger-text);font-weight:600}
.proform label{font-size:var(--f1);color:var(--fg-dim)}
.proform input,.proform textarea{width:100%;box-sizing:border-box;font:inherit;padding:.4rem;border:1px solid var(--line);border-radius:.3rem}
.proform button{font:inherit;padding:.35rem .9rem;cursor:pointer}
.proform .cc{margin-left:0;display:inline-block;margin-top:.15rem}
.imgpick{display:inline-block;cursor:pointer;border:1px solid var(--line);border-radius:.3rem;padding:.25rem .6rem;font-size:var(--f1)}
.imgprev{display:flex;gap:.5rem;flex-wrap:wrap;margin-top:.5rem}
.imgprev .thumb{display:flex;flex-direction:column;gap:.2rem;width:140px}
.imgprev .thumb img{width:140px;height:100px;object-fit:cover;border-radius:.3rem;background:var(--bg-soft)}
.imgprev .thumb input,.imgprev .thumb button{font:inherit;font-size:var(--f0);padding:.2rem;width:100%;box-sizing:border-box}
.imgprev .thumb button{cursor:pointer}
/* The base layer's dark patch lived here: 5 lines hand-repainting body, a/.tag, .post, .post:hover,
   .controls, .badge, .lbl, .meta/.did/.who/.permalink, .pfp, .profdid and .cc. Every one of those now
   reads from a token, so the single :root override in the design pass below covers them and this block
   had nothing left to do. It existed only because those rules were written as literals. */

/* ── design pass ──────────────────────────────────────────────────────────────────────────────────
   Everything above grew rule-by-rule as features landed and had no shared scale: spacing was ad-hoc,
   type sizes were chosen per-component, and there was no token to change. This layer sits last (so it
   wins at equal specificity) and introduces the scale rather than restyling from scratch — the goal is a
   consistent rhythm, not a different look for its own sake. Colours stay in the same family. */
:root{
  /* --fg-faint is timestamps, handles, meta rows and card hosts — most of the secondary text in the
     app. It must clear WCAG AA 4.5:1 on --bg for small text. #8b95a1 measured 3.04:1 and failed; it
     had already been fixed once further up the sheet, and this block silently reverted it by being
     defined later and winning. Measured on white: #6b7480 = 4.74:1. Do not lighten without checking. */
  --fg:#111; --fg-dim:#5c6672; --fg-faint:#6b7480;
  --bg:#fff; --bg-soft:#f7f8fa; --line:#e6e8eb; --line-soft:#f0f1f3;
  --accent:#1a56db; --like:#e0245e; --repost:#17bf63;
  /* Paired with --accent and with a text input's background, so the theme block only has to restate
     tokens rather than restate rules. */
  --bg-input:#fff; --on-accent:#fff;
  /* Semantic colours. These existed only as literals, which is why the dark patch below had to
     hand-repaint every element that used one. Measured on --bg #fff: --danger-text 6.47:1 and --lens
     5.67:1 pass AA for text. Two were corrected on the way in rather than tokenising a known-failing
     value a second time — --ok was #2b8a3e (4.37:1, text, just under), --bookmark was #f59f00
     (2.13:1 as an icon, under even the 3:1 non-text bar). --warn is only ever a border, where 3:1
     applies and 3.25:1 clears it. */
  --danger:#c92a2a; --danger-text:#b91c1c; --danger-bg:#fde8e8;
  --warn:#b8860b; --ok:#2a833b; --bookmark:#c77800; --badge-bg:#e8f0fe;
  /* The lens family names a FOREIGN source — content this node relays but does not hold. Audit #45
     lists that distinction as load-bearing, so it stays a visible treatment, not a hint. */
  --lens:#3b5bdb; --lens-line:#cbd5e1; --lens-edge:#dbe4ff;
  --s1:.25rem; --s2:.5rem; --s3:.75rem; --s4:1rem; --s5:1.5rem; --s6:2rem;
  /* Radii and type land on whole pixels at a 16px root. The previous values (6/10px, and
     12.48/13.6/15.2/16.8/21.6px) were on no grid at all, which is what fractional rem buys you:
     sub-pixel text rendering and no two components agreeing. Read off bluesky-social/social-app's
     alf tokens, which are the closest thing to a reference for this kind of client — theirs are
     radius 2/4/8/12/16 and type 10/12/14/16/18/20/22/26/32/40. Ours is a subset that lands on it.
     Kept in rem, not px, so a reader who raises their browser font size still gets it. */
  --r1:.5rem; --r2:.75rem; --r3:1rem;                       /* 8 / 12 / 16 */
  --f0:.75rem; --f1:.875rem; --f2:1rem; --f3:1.125rem; --f4:1.375rem;   /* 12 / 14 / 16 / 18 / 22 */
}
body{font-family:ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;
  max-width:640px;margin:0 auto;padding:var(--s5) var(--s4) var(--s6);color:var(--fg);
  line-height:1.55;-webkit-font-smoothing:antialiased;font-size:var(--f2);background:var(--bg)}
h1{display:flex;align-items:center;gap:var(--s2);font-size:var(--f4);letter-spacing:-.01em;margin:0 0 var(--s3)}
h1 small{font-size:var(--f1)}
/* The search form is a fixed 8rem and a flex item defaults to min-width:auto, so on a nowrap row it
   cannot shrink and cannot drop — it just pushes the page wider than the viewport. Measured: at 360px
   (a mainstream Android portrait width) the document was 377px, overflowing by exactly the amount
   .navsearch could not give up. 390px was already fine, so this is narrow-phone only. Wrapping lets the
   form take its own line instead of widening the document; min-width:0 lets it shrink first and stay on
   line one where there is room. */
nav{gap:var(--s4);margin:0 0 var(--s5);padding-bottom:var(--s2);border-bottom:1px solid var(--line);font-size:var(--f1);flex-wrap:wrap}
.navsearch{min-width:0}
.navsearch input{max-width:100%}
header nav a{color:var(--fg-dim);text-decoration:none;padding:var(--s1) 0;border-bottom:2px solid transparent}
header nav a:hover{color:var(--fg)}
/* Scoped to the header: .bottomnav is also a <nav>, and this underline was reaching it by accident.
   The bar marks its own active item (colour + weight) rather than inheriting a rule meant for a
   horizontal text row. */
header nav a[aria-current=page]{color:var(--fg);font-weight:600;border-bottom-color:var(--fg)}
/* Posts read as rows in a stream, not as boxed cards — the hairline is the separator and the padding
   gives each one room to breathe. */
.post{padding:var(--s4) var(--s2);border-color:var(--line);border-radius:var(--r2)}
.post .text{font-size:var(--f2);line-height:1.6;overflow-wrap:anywhere}
.post .media{margin-top:var(--s3)}
.post .media img{border-radius:var(--r2);border:1px solid var(--line-soft)}
/* Two or more images share a row instead of stacking full-width down the page. */
.media.multi{display:grid;grid-template-columns:1fr 1fr;gap:var(--s2)}
.media.multi img{height:100%;object-fit:cover;aspect-ratio:1/1;margin:0}
.media a{display:block;line-height:0}
.phead{gap:var(--s2);margin-bottom:var(--s2)}
.byline .name{font-size:var(--f2)}
.handle{color:var(--fg-faint);font-weight:400;font-size:var(--f1)}
/* Controls row. Small gap on purpose: each control is its own 44x44 box, so the whitespace between
   them is padding INSIDE a target, not dead space between two small ones. */
.meta{display:flex;align-items:center;gap:var(--s1);flex-wrap:wrap;margin-top:var(--s2);font-size:var(--f0);color:var(--fg-faint)}
/* ── bottom navigation (phones) ────────────────────────────────────────────────────────────────────
   Read off bluesky-social/social-app BottomBarWeb.tsx + BottomBarStyles.tsx: fixed to the bottom,
   full width, hairline top rule, items at flex:1 with roughly 13px above and 4px below. Five
   destinations, icon over label.

   Phones only. bsky uses a left sidebar at desktop widths and our content column is 640px — a phone
   chrome pinned under it would just be wrong. Above 640px this does not render as a bar at all.

   The four destinations it shares with the top nav are hidden FROM that row under 640px, so a phone
   shows each place once; saved / lists / settings / RSS stay up there, which is why the top row is
   not simply hidden. */
.bottomnav{display:none}
@media(max-width:640px){
  .bottomnav{display:flex;position:fixed;left:0;right:0;bottom:0;z-index:50;
    background:var(--bg);border-top:1px solid var(--line);padding:0 var(--s2);
    /* Clears the home indicator on phones that have one. */
    padding-bottom:env(safe-area-inset-bottom,0)}
  .bnitem{flex:1;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:2px;
    padding:13px 0 4px;min-height:44px;text-decoration:none;color:var(--fg-faint);font-size:11px}
  .bnitem .nicon{display:block}
  .bnitem.on{color:var(--accent);font-weight:600}
  .bnitem:hover{color:var(--fg)}
  /* Shown in the bar instead — one destination, one place. */
  header nav a.navprimary{display:none}
}
/* ── appearance control ────────────────────────────────────────────────────────────────────────────
   A segmented row of submit buttons, one per state. Buttons rather than a select because the current
   value should be visible without opening anything, and 44px because this is a touch control like any
   other. */
.themesec{margin:0 0 var(--s5)}
.sech{font-size:var(--f2);margin:0 0 var(--s2)}
.themeform{display:flex;gap:0;border:1px solid var(--line);border-radius:999px;overflow:hidden;width:fit-content}
.themebtn{font:inherit;font-size:var(--f1);min-height:44px;padding:0 var(--s4);border:0;
  background:var(--bg);color:var(--fg-dim);cursor:pointer}
.themebtn+.themebtn{border-left:1px solid var(--line)}
.themebtn:hover{background:var(--bg-soft);color:var(--fg)}
.themebtn.on{background:var(--accent);color:var(--on-accent);font-weight:600}
.themenote{font-size:var(--f0);color:var(--fg-faint);margin:var(--s2) 0 0;max-width:44ch}
.vernote{font-size:var(--f0);color:var(--fg-faint);margin:var(--s5) 0 0}
.vernote code{font-size:var(--f0)}
/* ── composer ──────────────────────────────────────────────────────────────────────────────────────
   The composer was ~40% of the first screen on a phone, permanently expanded, with four gate selects
   competing with the timeline before a reader had seen a single post. The gates move behind a native
   <details> so the default is what people actually do — type, maybe attach, post.

   The post button and image picker stay OUTSIDE the disclosure deliberately: making someone open a
   twisty before they can post would trade one bad default for a worse one, and with scripting off
   there is no other way to submit. */
.copts{margin:var(--s2) 0 0}
.copts>summary{display:inline-flex;align-items:center;min-height:44px;cursor:pointer;list-style:none;
  font-size:var(--f0);color:var(--fg-dim);text-decoration:underline}
.copts>summary::-webkit-details-marker{display:none}
.copts>summary:hover{color:var(--fg)}
.copts[open]>summary{margin-bottom:var(--s1)}
/* The submit row. Post sits at the end on whatever line it lands on, as it did when it lived in
   .controls. */
.optshint{font-size:var(--f0);color:var(--fg-faint);margin:var(--s1) 0 0;flex-basis:100%}
.cbar{display:flex;align-items:center;gap:var(--s2);flex-wrap:wrap;margin-top:var(--s2)}
.cbar #post-btn{margin-left:auto;flex:none}
@media(max-width:640px){
  .cbar #post-btn{margin-left:0;flex:1 1 100%}
}
/* ── two-column post row ───────────────────────────────────────────────────────────────────────────
   Avatar column, then everything else. 42px and a 10px gutter, matching bsky's PostFeedItem
   (size={42}, gap: 10). Applied to an inner .prow rather than to .post, because .post doubles as the
   <details> element for collapsed moderation and a grid there would column-lay the <summary>. */
.prow{display:grid;grid-template-columns:42px 1fr;column-gap:10px;align-items:start}
/* Load-bearing. A grid item's min-width defaults to auto, so one long unbroken word (a URL, a DID)
   would refuse to shrink and push the whole card past the viewport instead of wrapping. */
.pbody{min-width:0}
.pavatar{display:block;line-height:0;text-decoration:none}
/* The avatar stays 42px on a phone too — bsky does not shrink it, and it is what anchors the row. */
/* The timestamp now rides the byline row. Muted and small: it answers "when", it is not a control. */
.phead .permalink{color:var(--fg-faint);font-size:var(--f0);text-decoration:none;white-space:nowrap}
.phead .permalink:hover{text-decoration:underline}
.inreply{color:var(--fg-faint);font-size:var(--f0)}
.composer{background:var(--bg-soft);border:1px solid var(--line);border-radius:var(--r3);padding:var(--s3);margin-bottom:var(--s5)}
.composer textarea{border:1px solid var(--line);border-radius:var(--r1);background:var(--bg);resize:vertical}
.composer textarea:focus{outline:2px solid var(--accent);outline-offset:-1px;border-color:transparent}
#post-btn{background:var(--accent);color:#fff;border:none;border-radius:999px;padding:.4rem 1.1rem;font-weight:600;cursor:pointer}
#post-btn:hover{filter:brightness(1.08)}
.viewhdr{font-size:var(--f1);color:var(--fg-dim)}
.empty{color:var(--fg-faint)}
/* "older posts" — a full-width target, because on a phone a small text link at the end of 50 posts is a
   miserable thing to hit. */
.more{display:block;text-align:center;margin:var(--s5) 0 0;padding:var(--s3);border:1px solid var(--line);
  border-radius:999px;color:var(--accent);text-decoration:none;font-weight:600;font-size:var(--f1)}
.more:hover{background:var(--bg-soft)}
/* Lightbox. Fixed overlay; the image is capped to the viewport so a tall picture never needs scrolling. */
.lbox{position:fixed;inset:0;z-index:100;background:rgba(0,0,0,.88);display:flex;flex-direction:column;
  align-items:center;justify-content:center;gap:var(--s3);padding:var(--s4);cursor:zoom-out}
.lbox img{max-width:100%;max-height:82vh;object-fit:contain;border-radius:var(--r1);cursor:default}
.lbalt{color:#e8eaed;font-size:var(--f1);max-width:60ch;text-align:center;margin:0}
.lbclose{position:absolute;top:var(--s3);right:var(--s3);width:2.25rem;height:2.25rem;border-radius:999px;
  border:none;background:rgba(255,255,255,.14);color:#fff;font-size:1rem;cursor:pointer}
.lbclose:hover{background:rgba(255,255,255,.26)}
.thread{border-color:var(--line)}
.focus{border-left-width:3px;border-color:var(--accent)}
/* Small screens: the page had desktop margins on a phone, wasting ~15% of a narrow viewport. */
@media(max-width:640px){
  /* Body stays --f2 (16px) here rather than stepping up to --f3. The step-up was added when the base
     was 15.2px and read small on a phone; now that the base IS 16px it would overshoot to 18px, which
     is larger than any mainstream client sets body text. The padding reduction below is the part that
     was actually buying the space. */
  /* The bottom bar is fixed and sits ON TOP of the page, so the last post needs room or it is
     unreachable behind it. This lives in the shorthand rather than as a separate padding-bottom:
     an earlier padding-bottom loses to this rule, which is exactly what happened first time —
     measured 32px where 64 was intended. env() clears the home indicator where there is one. */
  body{padding:var(--s4) var(--s3) calc(64px + env(safe-area-inset-bottom,0));font-size:var(--f2)}
  h1{flex-wrap:wrap}
  .who{margin-left:0;width:100%}
  .post{padding:var(--s4) 0;border-radius:0}
  .media.multi{gap:var(--s1)}
  .meta{gap:var(--s2)}
}
/* ── theme ─────────────────────────────────────────────────────────────────────────────────────────
   THREE states, not two: system (no attribute), explicit light, explicit dark.

   It cannot be prefers-color-scheme alone. Android's WebView does not report that query truthfully to
   page content unless the app opts in (setAlgorithmicDarkeningAllowed, or the deprecated
   setForceDark), and favela-android does neither — so the phone has ALWAYS been told "light" whatever
   the handset is set to. An explicit attribute does not consult the query at all, which is why the
   settings toggle and the Android bug are one fix.

   The attribute is written server-side from a cookie, so the first paint is already correct — a
   class flipped by script would flash white on every navigation.

   Only the token block is duplicated. The rules that used to live in here alongside it now read from
   --bg-input and --on-accent, so there is one place per theme rather than one place per component —
   the same reason the hand-written dark patch was deleted earlier. */
@media(prefers-color-scheme:dark){
  /* System dark, unless the reader explicitly chose light. */
  :root:not([data-theme="light"]){--fg:#e8eaed;--fg-dim:#9aa4b2;--fg-faint:#79838f;--bg:#111;--bg-soft:#191b1f;
  --line:#2b2f36;--line-soft:#23262b;--accent:#9ec5ff;
  --bg-input:#0e0f12;--on-accent:#0b0d10;
  /* Measured on --bg #111: danger-text 10.95:1, ok 10.84:1, bookmark 8.85:1, lens 9.47:1.
     --danger keeps its light value because it is a fixed button background that white sits on
     (5.46:1) rather than something read against the page. */
  --danger:#c92a2a;--danger-text:#f8b4b4;--danger-bg:#4a1e1e;
  --warn:#e3b341;--ok:#4ade80;--bookmark:#f59f00;--badge-bg:#1e3a5f;
  --lens:#a5b4fc;--lens-line:#3b4252;--lens-edge:#2d3a5f}
}
/* Explicit dark wins in BOTH directions: it must also override a light system preference. */
:root[data-theme="dark"]{--fg:#e8eaed;--fg-dim:#9aa4b2;--fg-faint:#79838f;--bg:#111;--bg-soft:#191b1f;
  --line:#2b2f36;--line-soft:#23262b;--accent:#9ec5ff;
  --bg-input:#0e0f12;--on-accent:#0b0d10;
  /* Measured on --bg #111: danger-text 10.95:1, ok 10.84:1, bookmark 8.85:1, lens 9.47:1.
     --danger keeps its light value because it is a fixed button background that white sits on
     (5.46:1) rather than something read against the page. */
  --danger:#c92a2a;--danger-text:#f8b4b4;--danger-bg:#4a1e1e;
  --warn:#e3b341;--ok:#4ade80;--bookmark:#f59f00;--badge-bg:#1e3a5f;
  --lens:#a5b4fc;--lens-line:#3b4252;--lens-edge:#2d3a5f}
.post .media img{border-color:var(--line)}
.composer textarea{background:var(--bg-input);color:var(--fg)}
#post-btn{background:var(--accent);color:var(--on-accent)}
.more:hover{background:var(--bg-soft)}

/* ── error surface ────────────────────────────────────────────────────────────────────────────────
   A failed write used to be a 1.2s flash plus a title attribute, which needs a hover — so on touch it did not
   exist, and no screen reader announced it. The control reverted correctly and said nothing, which
   reads as "my tap didn't register". See web/static/toast.js. JS-only by construction; nothing in the
   no-JS path renders or depends on it. */
/* edit — a plain link, lighter than the delete control it sits beside */
.edited{color:var(--fg-faint);font-size:var(--f0)}
.editlink{text-decoration:none;color:var(--fg-faint)}
.editlink:hover{color:var(--accent)}
.edith{font-size:var(--f3);margin:var(--s4) 0 var(--s2)}
.editform textarea{width:100%}
.editnote,.editreach{font-size:var(--f0);color:var(--fg-dim);margin:var(--s2) 0}
.editreach em{color:var(--fg-faint);font-style:normal}
.editerr{color:var(--like);font-size:var(--f1)}
.editcancel{margin-left:var(--s3);color:var(--fg-dim);font-size:var(--f1)}
.toasts{position:fixed;left:50%;transform:translateX(-50%);bottom:var(--s4);z-index:60;
  display:flex;flex-direction:column;gap:var(--s2);width:min(30rem,calc(100vw - var(--s5)));pointer-events:none}
.toast{pointer-events:auto;display:flex;align-items:flex-start;gap:var(--s3);
  padding:var(--s3) var(--s4);border-radius:var(--r2);font-size:var(--f1);line-height:1.45;
  border:1px solid var(--line);background:var(--bg);color:var(--fg);
  box-shadow:0 6px 24px rgba(0,0,0,.16)}
.toast-err{border-color:var(--like);border-left-width:3px}
.toast-x{margin-left:auto;flex:none;border:0;background:none;cursor:pointer;
  color:var(--fg-faint);font-size:var(--f1);line-height:1;padding:0 var(--s1)}
.toast-x:hover{color:var(--fg)}
@media(prefers-reduced-motion:no-preference){
  .toast{animation:toastin .18s ease-out}
  @keyframes toastin{from{opacity:0;transform:translateY(.4rem)}to{opacity:1;transform:none}}
}

/* ── empty states ─────────────────────────────────────────────────────────────────────────────────
   The .empty class was grey italic text and nothing else, so an empty timeline looked identical to a broken
   one. An empty state should say what is absent, and — where there IS one — what to do about it. */
.emptyst{color:var(--fg-dim);text-align:center;
  padding:var(--s6) var(--s4);border:1px dashed var(--line);border-radius:var(--r2);background:var(--bg-soft)}
.emptyst .empty-t{display:block;font-weight:600;color:var(--fg);font-size:var(--f2);margin-bottom:var(--s1)}
.emptyst .empty-h{display:block;font-size:var(--f1);color:var(--fg-faint)}
.emptyst .empty-h a{color:var(--accent)}

/* ── reach badges ─────────────────────────────────────────────────────────────────────────────────
   Where a post went. OBSERVED (fediverse — the outbox names it) is solid; ELIGIBLE (bsky — the
   lexicon is one it indexes, but we did not check that it landed) is outlined and dimmer. The visual
   weight difference IS the honesty: they are different claims.

   Demoted from a filled pill to a hairline underline: these appear on EVERY row, and as boxes they
   competed with the post text for attention on a surface where the post is the point. The claim they
   make is unchanged and so is the channel that encodes it — solid underline for observed, dashed for
   eligible — but it now sits at the weight of a timestamp rather than a button. A lens is deliberately
   left louder than this: relaying a whole section from a foreign source is a bigger claim than "this
   one post was also offered to bsky". */
.badge.reach{display:inline;border:0;border-bottom:1px solid var(--line);border-radius:0;
  background:none;color:var(--fg-dim);font-weight:400;font-size:var(--f0);
  padding:0;margin-left:var(--s2);letter-spacing:.01em}
.badge.reach.weak{color:var(--fg-faint);border-bottom-style:dashed}

/* ── follower / following list ────────────────────────────────────────────────────────────────────
   A row per account rather than the inline run of names the profile shows. */
.folist{list-style:none;padding:0;margin:var(--s4) 0}
.folist li{display:flex;align-items:center;gap:var(--s3);padding:var(--s3) var(--s2);border-bottom:1px solid var(--line-soft)}
.folist li:last-child{border-bottom:0}
.folist .fo-id{min-width:0;flex:1}
.folist .fo-name{display:block;font-weight:600;overflow-wrap:anywhere}
.folist .fo-sub{display:block;font-size:var(--f0);color:var(--fg-faint);overflow-wrap:anywhere}
.folist .fo-src{flex:none;font-size:var(--f0);color:var(--fg-faint);
  border:1px solid var(--line);border-radius:var(--r1);padding:0 var(--s2)}
.subtabs{display:flex;gap:var(--s4);margin:0 0 var(--s3);font-size:var(--f1)}
.subtabs a{color:var(--fg-dim);text-decoration:none;padding-bottom:var(--s1);border-bottom:2px solid transparent}
.subtabs a[aria-current=page]{color:var(--fg);font-weight:600;border-bottom-color:var(--fg)}
`

// The composer is a plain <form> that POSTs to /api/post (works with NO JS — the handler redirects
// back). scope select mirrors DESIGN §3 POSSE. Shown only when the viewer can write (a signed-in DID
// or the node's relay writer).
// The image picker is PROGRESSIVE ENHANCEMENT and starts hidden: attaching images needs JS (the bytes
// go to /api/upload, which returns blob refs that /api/post takes as JSON). With JS off the form is
// byte-for-byte the plain text+scope POST it always was — the no-JS path is not regressed.
// Post languages. Deliberately a SHORT list of common tags rather than every ISO code — a 180-entry
// select is not a usable control, and the field only has to be right, not exhaustive. `langs` is not
// cosmetic: bsky's custom-feed tuner language-detects posts that omit it and drops what it does not read
// as the viewer's language, so declaring the wrong one makes a post vanish from feeds while looking
// perfectly fine everywhere else (memory: bsky-custom-feed-lande-langs-drop).
const LANGS = [
  ['en', 'English'], ['es', 'Español'], ['pt', 'Português'], ['fr', 'Français'], ['de', 'Deutsch'],
  ['it', 'Italiano'], ['nl', 'Nederlands'], ['ja', '日本語'], ['ko', '한국어'], ['zh', '中文'],
  ['ru', 'Русский'], ['uk', 'Українська'], ['ar', 'العربية'], ['hi', 'हिन्दी'], ['tr', 'Türkçe'],
  ['pl', 'Polski'], ['sv', 'Svenska'], ['da', 'Dansk'], ['fi', 'Suomi'], ['cs', 'Čeština']
]

function composer (canWrite, quoting = null, lists = [], viewer = null) {
  if (!canWrite) return ''
  // ⛔ SAY WHICH IDENTITY THIS WRITES AS. A favela node hosts MANY DIDs — your own plus every co-owned
  // community — and this form named none of them, so "post" meant "post as whichever DID the session
  // happens to be bound to". On 2026-08-18 that sent a post intended for a community out as a personal
  // identity, to bsky, where it cannot be recalled. The page header's `whoami` is not this: it answers
  // "who is signed in" in the opposite corner, and with no handle resolved it prints 32 characters of
  // raw DID, which reads as decoration.
  //
  // Rendered only when the identity is actually KNOWN. `canWrite` is also true for the node's own relay
  // writer, where this page holds no DID — and a composer that says "posting as this node" when it has
  // not established that would be the same lie one step quieter.
  const who = viewer && viewer.did ? (viewer.handle || shortDid(viewer.did)) : null
  const whoLine = who ? `<p class="composerwho">posting as <strong>${esc(who)}</strong></p>` : ''
  // Quoting: a hidden quoteOf plus a PREVIEW of what is being quoted. Without the preview the composer
  // looks identical to a normal one and you cannot tell what (or whether) you are quoting.
  const q = quoting
    ? `<input type="hidden" name="quoteOf" value="${esc(quoting.uri)}">
<div class="qpreview">❝ quoting <strong>${esc(quoting.who || shortDid(quoting.did || ''))}</strong>${quoting.text ? `: <span class="qptext">${esc(String(quoting.text).slice(0, 140))}</span>` : ''} <a class="qcancel" href="/">cancel</a></div>`
    : ''
  return `<form class="composer" method="POST" action="/api/post">${whoLine}${q}
<label class="sr-only" for="composer-text">what do you want to post?</label><textarea id="composer-text" name="text" rows="2" placeholder="Say something…" style="width:100%;box-sizing:border-box;font:inherit;padding:.5rem" required></textarea>
<details class="copts"><summary>post options</summary><div class="controls"><label>scope <select name="scope">
<option value="public">public</option>
<option value="local">local only</option>
</select></label><label>lang <select name="lang">
${LANGS.map(([code, label]) => `<option value="${code}">${esc(label)}</option>`).join('')}
</select></label><label>quotes <select name="quoteGate">
<option value="anyone">anyone</option>
<option value="nobody">nobody</option>
</select></label><label>replies <select name="gate">
<option value="everyone">anyone</option>
<option value="following">people you follow</option>
<option value="mentioned">mentioned</option>
<option value="nobody">nobody</option>
${lists.map((l) => `<option value="${esc(l.uri)}">only: ${esc(l.name)}</option>`).join('')}
</select></label>
<p class="optshint">a line with only --- starts a new post in a thread</p></div></details>
<div class="cbar"><span id="img-controls" hidden><label class="imgpick">📎 image<input type="file" id="post-image" accept="image/*" multiple hidden></label></span><span id="charcount" class="cc" aria-live="polite"></span><button id="post-btn">post</button></div>
<p class="composerhint">public posts syndicate to bsky · local-only stays on favela</p>
<div id="img-preview" class="imgprev"></div></form>`
}

// Settings: the avatar. This exists because a lost avatar is otherwise unfixable — the blob bytes are
// gone from every node, so nothing can restore it except the owner re-uploading. Doing so also lands
// the first blob in the content-addressed OverlayBlobStore, so it migrates as a side effect.
// Appearance. Deliberately available SIGNED OUT as well: a theme is a property of the reader's eyes,
// not of an account, and the public instance serves mostly anonymous readers.
//
// Three states, and "system" is the ABSENCE of a preference rather than a third stored value — so a
// reader who never touches this is in exactly the state everyone was in before it existed.
//
// A plain form with a submit per option: no JS, one tap, and it works in the Android WebView, which is
// the case that prompted it. `return` sends you back where you were.
export function themeControl (theme = null, returnTo = '/settings') {
  const opts = [
    ['system', 'System', 'follow the device setting'],
    ['light', 'Light', ''],
    ['dark', 'Dark', '']
  ]
  const cur = (theme === 'light' || theme === 'dark') ? theme : 'system'
  const buttons = opts.map(([v, label, hint]) => {
    const on = v === cur
    return `<button class="themebtn${on ? ' on' : ''}" name="theme" value="${v}"${on ? ' aria-current="true"' : ''}${hint ? ` title="${esc(hint)}"` : ''}>${esc(label)}</button>`
  }).join('')
  return `<section class="themesec"><h2 class="sech">Appearance</h2>
<form class="themeform" method="POST" action="/api/theme"><input type="hidden" name="return" value="${esc(returnTo)}">${buttons}</form>
<p class="themenote">System follows your device. On Android the in-app browser does not report that setting, so choose Light or Dark there.</p></section>`
}

// The version of the RUNNING code. `pgh app status` reports the version on DISK, which an app that
// installed an update and never restarted will report while still serving the old one — so a number
// rendered by the process itself is the only one that answers "what am I actually looking at".
//
// Shown SIGNED OUT as well, and on the phone this is the only place a version appears at all: the
// handset has no `pgh app status`, and its worklet bundle arrives by OTA independently of any APK.
export function versionNote () {
  return `<p class="vernote">favela-web <code>${esc(VERSION)}</code></p>`
}

// App updates, on a handset only. Rendered ONLY when the native shell has said it can service these
// buttons (`shell.ota`), because the shell and the worklet bundle version INDEPENDENTLY — the bundle
// arrives by OTA, the shell only when an APK is installed — so a new bundle can find itself inside an
// old shell that has no message handler. Buttons that silently do nothing are worse than no buttons.
//
// ⛔ WHY THIS EXISTS AT ALL. Staging and applying are deliberately separate (applying to a running node
// means swapping code under itself), so an update discovered during boot N can only take effect at boot
// N+1 — and with a 6-hour poll and no way to restart the node, "up to date" is a thing the phone can
// only become by accident. Measured on a handset 2026-08-24: the device ran a bundle whose replacement
// had been staged for over half an hour with no user-reachable way to apply it.
//
// This does NOT make updates event-driven; the 6h poll is still the last polling loop in the stack and
// announce-over-swarm is still the real fix. It makes the existing design operable by the person holding
// the phone.
//
// Signed OUT as well, on purpose: a stale session is one of the states a restart repairs, and gating the
// repair on being signed in would put it behind the thing that is broken.
export function appUpdateSection (shell = null) {
  if (!shell || !shell.ota) return ''
  const short = (h) => (typeof h === 'string' && h.length > 12 ? h.slice(0, 12) + '…' : (h || ''))
  const running = shell.running ? `<code>${esc(short(shell.running))}</code>` : '<span class="empty">the bundle shipped in the app</span>'
  // "staged" is only news when it is NOT what is already running — otherwise it reads as a pending
  // update to someone who is already on it, which is the exact lie the OTA log used to tell.
  const pending = shell.staged && shell.staged !== shell.running
  const stagedRow = pending
    ? `<p class="otapend">An update is staged: <code>${esc(short(shell.staged))}</code> — restart the node to run it.</p>`
    : '<p class="empty">No update staged.</p>'
  const checked = shell.checkedAt ? `<p class="empty">last checked ${esc(relTime(shell.checkedAt))}</p>` : ''
  return `<section class="authbox otasec">
  <h3>App updates</h3>
  <p class="empty">running <span class="otarun">${running}</span></p>
  ${stagedRow}
  ${checked}
  <p><button class="devbtn" data-ota="check">check for updates</button>
     <button class="devbtn${pending ? ' otaprim' : ''}" data-ota="restart">restart the node</button></p>
  <p class="empty">Checking downloads in the background; nothing changes until the node restarts. A restart
     also re-signs this page in, which is the fix if it has started refusing you.</p>
<style>.otapend{margin:.3rem 0}.otaprim{border-color:#2563eb}.otarun code{font-size:.85rem}</style>
<script>
// One-way to the shell, deliberately: it acts and then reloads this page, so the state above is always
// SERVER-rendered from what the worklet actually knows. A reply channel would be a second source of
// truth for the same three fields.
document.querySelectorAll('[data-ota]').forEach(function (b) {
  b.addEventListener('click', function () {
    var bridge = window.ReactNativeWebView
    if (!bridge) return
    b.disabled = true
    b.textContent = b.dataset.ota === 'restart' ? 'restarting…' : 'checking…'
    bridge.postMessage(JSON.stringify({ t: 'app-update', op: b.dataset.ota }))
  })
})
</script>
</section>`
}

// Pairing, on a handset, from the page instead of an overlay.
//
// ⛔ WHAT THIS OPENS IS NOT A LOGIN. The ceremony hands this phone the DID's SHARED SIGNING KEY, after
// which it authors as that identity on its own, offline — and removing a device later stops it being
// ADMITTED but cannot un-know a key it already holds. The full warning lives on the native screen this
// button opens (app/Pair.jsx, where the wording is explicitly part of the security model), so this says
// enough to set expectations and does not paraphrase it into something softer.
//
// It lives here because it always should have: favela-android's own note says "the old UI reached
// pairing from settings for exactly this reason", and it only became a floating button when the native
// settings screen went away with the move to a WebView. On the handset that overlay sat on top of the
// bottom nav's Home item, so tapping Home opened the pairing screen — reported 2026-08-25.
//
// Gated on `shell.pair`, a SEPARATE capability from `shell.ota`: the page arrives by OTA and the shell
// by APK, so a page that lands on a shell which cannot service this must render nothing at all rather
// than a button that silently does nothing.
export function pairSection (shell = null) {
  if (!shell || !shell.pair) return ''
  return `<section class="authbox pairsec">
  <h3>Connect this phone</h3>
  <p class="empty">Paste an invite minted by a device that already holds your identity — favela's
     <em>Generate a device invite</em>, above or on your desktop. Use this when setting the phone up, or
     when it holds your identity but posts are being refused because it is not on the room's member list.</p>
  <p class="empty"><strong>It receives the key that signs your posts.</strong> From then on this phone can
     post as you, by itself. The next screen says so in full before anything happens.</p>
  <p><button class="devbtn" data-ota="pair">open the pairing screen</button></p>
<script>
document.querySelectorAll('[data-ota="pair"]').forEach(function (b) {
  b.addEventListener('click', function () {
    var bridge = window.ReactNativeWebView
    if (!bridge) return
    b.disabled = true
    bridge.postMessage(JSON.stringify({ t: 'app-update', op: 'pair' }))
  })
})
</script>
</section>`
}

// Where this node may read from, as a setting rather than a deployment detail.
//
// ⛔ THIS WAS ONLY REACHABLE BY EDITING apps.json AND RESTARTING — and on a handset there is no
// apps.json at all, so it could not be changed there by any means. The consequence was visible rather
// than theoretical: a bsky account's page rendered a real name and avatar and "no posts from this
// author", because reading their posts needs a lens and no node had one configured (hyper-social #53).
//
// Shown to the node's OWN identity only. Repointing where a node sends the DIDs it looks up is an
// operator act, not a viewer preference, and on a public instance a signed-in guest must not have it.
//
// A plain form: it works with scripting off, like themeControl and the profile form.
export function lensControl ({ lens = null, isOperator = false, returnTo = '/settings' } = {}) {
  if (!isOperator) return ''
  const on = !!(lens && lens.enabled)
  const current = (lens && lens.lenses && lens.lenses[0] && lens.lenses[0].base) || ''
  const names = (lens && lens.lenses ? lens.lenses : []).map((l) => l.name).filter(Boolean)
  const state = on
    ? `<p class="empty">Reading from <strong>${esc(names.join(', ') || 'a lens')}</strong> at <code>${esc(current)}</code>.</p>`
    : '<p class="empty">Off. Posts by people this node does not index \u2014 anyone on bsky \u2014 show as an empty profile.</p>'
  return `<section class="authbox lenssec">
  <h3>Remote reading</h3>
  <p class="empty">Point this at a bridge and profiles this node has never indexed can show their posts,
     clearly marked as coming from that source. Nothing is stored and nothing is federated \u2014 it fills
     in a page that would otherwise be blank. Leave it empty to read nothing remote, the default.</p>
  ${state}
  <form method="POST" action="/api/lens" class="rowform">
    <input type="hidden" name="return" value="${esc(returnTo)}">
    <p><label for="lens-url">bridge url</label><br>
      <input id="lens-url" name="bridgeUrl" type="url" inputmode="url" placeholder="https://pds.example.net"
             value="${esc(current)}" size="34"></p>
    <p><button type="submit">save</button>
       <span class="empty">applies immediately \u2014 no restart</span></p>
  </form>
</section>`
}

export function settingsPage ({ viewer = null, profile = null, did = null, devices = [], theme = null, shell = null, lens = null, isOperator = false } = {}) {
  if (!viewer) {
    // Appearance still renders here — it is not an account setting. So does App updates: a restart is
    // what repairs a session this page has forgotten, and hiding it behind sign-in hides it exactly when
    // it is needed.
    return page({ title: 'settings · favela', viewer, active: null, theme, body: '<div class="viewhdr">Settings <a href="/">← back</a></div>' + themeControl(theme) + versionNote() + appUpdateSection(shell) + pairSection(shell) + lensControl({ lens, isOperator }) + '<p class="empty">Sign in to manage your profile. <a href="/login">sign in →</a></p>' })
  }
  const cid = profile && profile.avatar && blobCid(profile.avatar.ref)
  const current = (cid && did && isSafeCid(cid))
    ? `<img class="avatar" src="${esc(blobUrl(did, cid))}" alt="current avatar">`
    : '<div class="avatar none" title="no avatar set">no avatar</div>'
  // Server-rendered so the list is readable with JS off. A revoked device is shown rather than hidden:
  // "no devices" and "one revoked device" are different facts, and the second is the one worth seeing.
  const ymd = (ms) => { try { return new Date(ms).toISOString().slice(0, 10) } catch { return '' } }
  const rows = devices.length
    ? devices.map((d) => `<li class="dev${d.revoked ? ' revoked' : ''}" data-subkey="${esc(d.subKey)}">
      <code>${esc(String(d.subKey).slice(0, 20))}…</code>
      <span class="devmeta">${d.revoked ? 'revoked' : 'active'}${d.addedAt ? ' · ' + esc(ymd(d.addedAt)) : ''}${d.label ? ' · ' + esc(d.label) : ''}</span>
      <button class="devbtn" data-action="${d.revoked ? 'restore' : 'revoke'}">${d.revoked ? 'restore' : 'revoke'}</button>
    </li>`).join('')
    : '<li class="empty">no browsers paired yet</li>'

  return page({
    title: 'settings · favela',
    viewer,
    active: null,
    theme,
    body: `<div class="viewhdr">Settings <a href="/">← back</a></div>
${themeControl(theme)}
${versionNote()}
${appUpdateSection(shell)}
${pairSection(shell)}
${lensControl({ lens, isOperator })}
<section class="authbox">
  <h3>Profile picture</h3>
  <p class="empty">Signed in as <strong>${esc(viewer.did)}</strong>${profile && profile.displayName ? ' · ' + esc(profile.displayName) : ''}</p>
  <div class="avatarrow">${current}
    <div>
      <p><label class="imgpick">choose an image<input type="file" id="avatar-file" accept="image/*" hidden></label></p>
      <p class="empty">PNG, JPEG, GIF or WebP · max 1&nbsp;MB. Your hpp stores it and signs the profile update; favela never holds your key.</p>
      <p id="avatar-status" aria-live="polite"></p>
    </div>
  </div>
</section>
<section class="authbox">
  <h3>Connect a device</h3>
  <p class="empty">
    For another <strong>node</strong> — a phone running favela-android, or a second machine. It receives
    the key that signs your posts, so from then on it posts as you on its own, offline, and replicates
    your repo directly. That is different from signing a browser in below, where the key never leaves
    this machine.
  </p>
  <p class="empty">
    <strong>⚠ Whoever reads this code before your device uses it can post as you.</strong> It is
    single-use and short-lived. Losing the device means rotating your identity key, which is permanent.
  </p>
  <form method="post" action="/api/devices/invite" class="rowform">
    <button type="submit">Generate a device invite</button>
  </form>
  <p id="device-invite" aria-live="polite"></p>
  <p class="empty">
    Paste the code into the device and keep this page open — the tunnel closes when the invite is used
    or expires. Do <em>not</em> use the browser sign-in code below for a node: it delegates a browser
    sub-key, and a node will silently wait until it times out.
  </p>
</section>
<section class="authbox">
  <h3>Banner</h3>
  <p class="empty">The wide image across the top of your profile. Same limits as the avatar: PNG, JPEG, GIF or WebP, max 1&nbsp;MB.</p>
  ${(profile && profile.banner && blobCid(profile.banner.ref) && isSafeCid(blobCid(profile.banner.ref)) && did)
    ? `<div class="profbanner small"><img src="${esc(blobUrl(did, blobCid(profile.banner.ref)))}" alt="current banner"></div>`
    : '<p class="empty">no banner set</p>'}
  <p><label class="imgpick">choose a banner<input type="file" id="banner-file" accept="image/*" hidden></label></p>
  <p id="banner-status" aria-live="polite"></p>
</section>
<section class="authbox">
  <h3>Name &amp; bio</h3>
  <p class="empty">This is what other peers see instead of your DID. A plain form — it works with JavaScript off.</p>
  <form method="POST" action="/api/profile" class="proform">
    <p><label for="pf-name">display name</label><br>
      <input id="pf-name" name="displayName" type="text" maxlength="640" value="${esc((profile && profile.displayName) || '')}" placeholder="${esc(shortDid(did || ''))}">
      <span id="pf-name-cc" class="cc"></span></p>
    <p><label for="pf-bio">bio</label><br>
      <textarea id="pf-bio" name="description" rows="3" maxlength="2560" placeholder="a sentence about you">${esc((profile && profile.description) || '')}</textarea>
      <span id="pf-bio-cc" class="cc"></span></p>
    <p><button type="submit">save</button> <span class="empty">your hpp signs the update — leaving a field empty clears it</span></p>
  </form>
</section>
<section class="authbox">
  <h3>Devices</h3>
  <p class="empty">Browsers allowed to sign in as this DID. Pairing is minted by your hpp — favela never holds your key.</p>
  <ul class="devlist">${rows}</ul>
  <p><label class="imgpick" for="pair-label">name this device</label>
     <input id="pair-label" type="text" placeholder="my phone" maxlength="64">
     <button id="pair-new" class="devbtn">generate join code</button></p>
  <div id="pair-out" hidden>
    <p class="empty">Open this on the device you want to sign in — or paste the code into its login box. One use, expires in 5 minutes.</p>
    <p><a id="pair-url" href="#" rel="noreferrer"></a></p>
    <p><code id="pair-code" class="paircode"></code> <button id="pair-copy" class="devbtn">copy</button></p>
  </div>
  <p id="dev-status" aria-live="polite"></p>
</section>`,
    clientScript: `<style>
.authbox{border:1px solid #e5e5e5;border-radius:.5rem;padding:1rem;margin:1rem 0}
.avatarrow{display:flex;gap:1rem;align-items:flex-start;flex-wrap:wrap}
.avatar{width:96px;height:96px;border-radius:50%;object-fit:cover;background:#f3f4f6}
.avatar.none{display:flex;align-items:center;justify-content:center;font-size:.75rem;color:#888;border:1px dashed #ccc}
.imgpick{display:inline-block;cursor:pointer;border:1px solid #ccc;border-radius:.3rem;padding:.35rem .7rem;font:inherit}
#avatar-status.ok{color:#15803d}#avatar-status.err{color:#b91c1c}
.devlist{list-style:none;padding:0;margin:.5rem 0}
.dev{display:flex;gap:.6rem;align-items:center;flex-wrap:wrap;padding:.4rem 0;border-bottom:1px solid #eee}
.dev.revoked code,.dev.revoked .devmeta{opacity:.55;text-decoration:line-through}
.devmeta{color:#666;font-size:.85rem}
.devbtn{font:inherit;border:1px solid #ccc;border-radius:.3rem;padding:.25rem .6rem;background:#fafafa;cursor:pointer}
.devbtn[disabled]{opacity:.5;cursor:default}
.paircode{word-break:break-all;font-size:.8rem;background:#f3f4f6;padding:.2rem .35rem;border-radius:.25rem}
#pair-label{font:inherit;padding:.3rem .4rem;border:1px solid #ccc;border-radius:.3rem}
#dev-status.ok{color:#15803d}#dev-status.err{color:#b91c1c}
@media(prefers-color-scheme:dark){.proform input,.proform textarea,.proform button{background:#222;color:#eee;border-color:#444}.proform label{color:#9ca3af}.dev{border-color:#333}.devbtn{background:#222;color:#eee;border-color:#444}.paircode{background:#1f2937}#pair-label{background:#222;color:#eee;border-color:#444}.devmeta{color:#9ca3af}#dev-status.ok{color:#4ade80}#dev-status.err{color:#f87171}.authbox{border-color:#333}.avatar{background:#1f2937}.imgpick{background:#222;color:#eee;border-color:#444}#avatar-status.ok{color:#4ade80}}
</style>
<script type="module" src="/static/settings.js"></script>`
  })
}

// The signed-in/anonymous indicator + sign-in/out link (the DID session layer wires these routes).
// Is what you are reading current? The one state this UI never had.
//
// ⛔ THIS NODE IS DESIGNED TO BE INTERMITTENTLY ONLINE (favela-web/spec/mobile-node.md §5) and every page
// rendered identically whether the index advanced a second ago or froze two days ago. The freeze
// signature is invisible by construction: peers connected, daemon up, backfill "successful", profile
// renders — just missing everything appended since. On 2026-08-18 the handset's node was dead for 68
// minutes behind a timeline that looked merely quiet.
//
// frontsDiag has computed the answer since the ashatron freeze; it was only ever rendered on /status,
// which a reader never opens. This is the one sentence a reader needs, on the page they are on.
//
// ⛔ NEVER CLAIMS CURRENCY. The freshest front we can SEE may not be the freshest that exists, so "up to
// date" is not a statement this node is entitled to make. Two things are sayable — "no peer is serving
// this right now" and "we are behind by N on the line we are on" — and everything else renders NOTHING.
// Silence here means "no reason to doubt", not "verified fresh"; a green tick would be the lie.
export function freshnessNote (diag) {
  if (!diag || !Array.isArray(diag.dids) || !diag.dids.length) return ''

  // No live front = nobody answered for this identity. This is the handset's case, and the reader's
  // question ("is this all there is?") has a real answer we were withholding.
  const dark = diag.dids.filter((d) => !((d && d.fronts) || []).some((f) => f && f.live))
  if (dark.length) {
    const n = dark.length
    const total = diag.dids.length
    return `<p class="stale">⚠ this view may be <strong>out of date</strong> — ${n} of ${total} ${n === 1 ? 'identity has' : 'identities have'} no live peer right now. <a href="/status">why</a></p>`
  }

  // On a line, but a shorter one than we can see: the freeze signature, in a reader's words. Stated as a
  // COUNT, because "syncing…" is what the old empty state said while nothing was happening.
  const behind = diag.dids.filter((d) => d && Number.isFinite(d.behindBy) && d.behindBy > 0)
  if (behind.length) {
    const worst = behind.reduce((a, b) => (b.behindBy > a.behindBy ? b : a))
    return `<p class="stale">⚠ <strong>behind</strong> by ${worst.behindBy} record${worst.behindBy === 1 ? '' : 's'} on ${esc(shortDid(worst.did))}. <a href="/status">why</a></p>`
  }

  return ''
}

function whoami (viewer) {
  if (viewer && viewer.did) return `<span class="who">${esc(viewer.handle || viewer.did)} · <a href="/logout">sign out</a></span>`
  return '<span class="who"><a href="/login">sign in</a></span>'
}

// Icons for the bottom bar. Inline SVG rather than Unicode glyphs: a nav drawn in ⌂ ⌕ ☰ is the single
// most reliable way to look unfinished, and these inherit currentColor so they theme for free. 24px to
// match the rest of the touch furniture. aria-hidden because each sits beside a real text label.
const ICON = {
  home: '<path d="M3 10.5 12 3l9 7.5"/><path d="M5 9.5V21h14V9.5"/>',
  search: '<circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/>',
  following: '<circle cx="9" cy="8" r="3.5"/><path d="M2.5 20a6.5 6.5 0 0 1 13 0"/><path d="M17 5.2a3.5 3.5 0 0 1 0 6.6"/><path d="M18.5 20a6.5 6.5 0 0 0-2.5-5.1"/>',
  bell: '<path d="M18 9a6 6 0 1 0-12 0c0 5-2 6-2 6h16s-2-1-2-6"/><path d="M10.5 20a2 2 0 0 0 3 0"/>',
  user: '<circle cx="12" cy="8" r="4"/><path d="M4 21a8 8 0 0 1 16 0"/>'
}
const icon = (k) => `<svg class="nicon" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${ICON[k]}</svg>`

// The phone bar. Five destinations, matching bsky's shape (home / search / a people feed /
// notifications / you) — read from their BottomBarWeb.tsx rather than recalled.
//
// Signed out, `following`, `notifications` and a profile do not exist, so it degrades to three rather
// than offering links to permanently empty pages. Each item is flex:1, so a target is a fifth of the
// screen wide — the same "make it unmissable" instinct as bsky's hitSlop on the post controls.
//
// The items here are HIDDEN from the top nav under 640px (see .navprimary in STYLE), so a phone shows
// each destination once. Everything that is not here — saved, lists, settings, RSS — stays in the top
// nav, which is why that row is not simply hidden on mobile.
function bottomNav (active, viewer = null) {
  const signedIn = !!(viewer && viewer.did)
  const item = (href, label, key, ic) =>
    `<a href="${href}" class="bnitem${active === key ? ' on' : ''}"${active === key ? ' aria-current="page"' : ''}>${icon(ic)}<span>${label}</span></a>`
  const items = [
    item('/', 'Home', 'timeline', 'home'),
    item('/search', 'Search', 'search', 'search'),
    signedIn ? item('/following', 'Following', 'following', 'following') : '',
    signedIn ? item('/notifications', 'Alerts', 'notifications', 'bell') : '',
    signedIn ? item(`/profile/${encodeURIComponent(viewer.did)}`, 'You', 'profile', 'user') : ''
  ].join('')
  return `<nav class="bottomnav" aria-label="primary">${items}</nav>`
}

function nav (active, viewer = null) {
  // `primary` marks the destinations the bottom bar also carries, so they can be hidden from this row
  // on a phone without hiding the row itself — the overflow lives here and must stay reachable.
  const item = (href, label, key, primary = false) => `<a href="${href}"${primary ? ' class="navprimary"' : ''}${active === key ? ' aria-current="page"' : ''}>${label}</a>`
  // Following is only meaningful signed in — an anonymous viewer has no follow graph, so offering the
  // link would lead to a permanently empty page.
  const following = viewer && viewer.did ? item('/following', 'following', 'following', true) : ''
  const bookmarks = viewer && viewer.did ? item('/bookmarks', 'saved', 'bookmarks') : ''
  const notifs = viewer && viewer.did ? item('/notifications', 'notifications', 'notifications', true) : ''
  const lists = viewer && viewer.did ? item('/lists', 'lists', 'lists') : ''
  // A plain GET form: search works with scripting off and the result is a shareable URL.
  const search = `<form class="navsearch" method="GET" action="/search" role="search"><input type="search" name="q" placeholder="search" aria-label="search"></form>`
  return `<nav>${item('/', 'timeline', 'timeline', true)}${following}${notifs}${bookmarks}${lists}${item('/search', 'search', 'search', true)}${item('/settings', 'settings', 'settings')}${item('/feed.xml', 'RSS', 'rss')}${search}</nav>`
}

// Progressive enhancement for the whole-entry link, and the one thing the pure-CSS version costs.
//
// .pstretch is a real anchor lying ON TOP of the card — that is what makes the card clickable with no
// JavaScript at all. But an anchor on top of text also swallows the drag that selects that text, and
// selecting a post's words is part of reading it. That would be a regression traded for the click.
//
// So when scripting IS available, the overlay is taken out of the hit test (pointer-events:none, via
// the js-postclick class this adds) and the same job is done by a handler that knows two things CSS
// cannot: whether the reader is currently selecting text, and whether they asked for a new tab. With
// scripting off, none of this runs and the pure-CSS overlay stands unchanged.
//
// Delegated on `document` rather than bound per-post, so it keeps working for posts swapped in by the
// live refresh without anything having to re-bind.
const POSTCLICK = `<script>
(function () {
  var d = document
  d.documentElement.className += ' js-postclick'
  var CONTROL = 'a,button,form,summary,input,textarea,select,label'
  function href (e) {
    if (!e.target || !e.target.closest) return null
    var post = e.target.closest('.post')
    if (!post) return null
    if (e.target.closest(CONTROL)) return null
    var link = post.querySelector(':scope > .pstretch')
    if (!link) return null
    var sel = d.getSelection && d.getSelection()
    if (sel && !sel.isCollapsed && post.contains(sel.anchorNode)) return null
    return link.getAttribute('href')
  }
  d.addEventListener('click', function (e) {
    if (e.button !== 0) return
    var h = href(e)
    if (!h) return
    if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) window.open(h, '_blank', 'noopener')
    else location.href = h
  })
  d.addEventListener('auxclick', function (e) {
    if (e.button !== 1) return
    var h = href(e)
    if (!h) return
    e.preventDefault()
    window.open(h, '_blank', 'noopener')
  })
})()
</script>`

// Full HTML document. `client` (optional) is the progressive-enhancement <script> src/inline appended
// before </body>; with it absent the page is fully functional server-rendered.
export function page ({ title = 'favela', heading, viewer = null, active = 'timeline', canWrite = false, body = '', clientScript = '', quoting = null, pds = 'https://pds.7rnx.net', composerLists = [], freshness = null, theme = null } = {}) {
  // Written server-side so the FIRST paint is already correct. A class flipped by script would flash
  // the wrong theme on every navigation, and with scripting off would never apply at all. Absent
  // attribute = follow the system, which is the default and the only state that existed before.
  const themeAttr = (theme === 'dark' || theme === 'light') ? ` data-theme="${theme}"` : ''
  return `<!doctype html><html lang="en"${themeAttr}><head><meta charset="utf-8">
<!-- viewport-fit=cover is what makes env(safe-area-inset-*) resolve to anything. Without it those
     insets are INERT — they compute to 0 — and .bottomnav's padding-bottom plus body's
     calc(64px + env(safe-area-inset-bottom)) were both written expecting them to work. On the handset
     the effect was a bottom bar floating ABOVE the gesture strip with page content sliding underneath
     it, because the WebView paints edge-to-edge while the layout viewport stops at the safe area.
     Observed on a moto g power, 2026-08-25. The rules were already correct; this is the token that
     switches them on. -->
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<title>${esc(title)}</title>
<link rel="alternate" type="application/atom+xml" title="favela timeline" href="/feed.xml">
<meta name="favela-pds" content="${esc(pds)}">
<style>${STYLE}</style></head><body>
<a class="skip" href="#main">skip to content</a>
<header>
<h1>${esc(heading || 'favela')} <small>· native P2P view</small>${whoami(viewer)}</h1>
${nav(active, viewer)}
</header>
<main id="main" tabindex="-1">
${freshnessNote(freshness)}
${composer(canWrite, quoting, composerLists, viewer)}
${body}
</main>
${bottomNav(active, viewer)}
${clientScript}
${POSTCLICK}
<script type="module" src="/static/actions.js"></script>
<script type="module" src="/static/draft.js"></script>
<script type="module" src="/static/report.js"></script>
</body></html>`
}

// ── whole-page views ──────────────────────────────────────────
export function timelinePage ({ result, viewer = null, canWrite = false, clientScript = '', active = 'timeline', emptyMsg = 'no posts yet (indexing…)', quoting = null, composerLists = [], apRkeys = null, freshness = null } = {}) {
  const base = active === 'following' ? '/following' : '/'
  const posts = withReach(withViewer(result && result.posts, viewer, base), apRkeys)
  return page({
    title: 'favela',
    viewer,
    active,
    canWrite,
    quoting,
    composerLists,
    freshness,
    body: renderPosts(posts, emptyMsg) + moreLink(result && result.cursor, base),
    // Composer image picker is progressive enhancement — only loaded when there is a composer to enhance.
    clientScript: clientScript || (canWrite ? '<script type="module" src="/static/compose.js"></script>' : '')
  })
}

// Profile tabs, each one an app.bsky.feed.getAuthorFeed filter value — the same split bsky makes, so a
// tab means the same thing here as anywhere else in atproto.
//
// `posts_with_video` is a valid filter and is deliberately NOT a tab: our composer only ever writes
// app.bsky.embed.images (writer.js), so a Videos tab would be permanently empty on this node. The filter
// stays reachable via ?filter= for records ingested from peers that do post video.
//
// Order and default follow the bsky app: Posts first, and Posts is what you land on. NOTE this CHANGES
// what a profile shows by default — this page used to list replies inline, and now they live behind the
// Replies tab. Deliberate, for parity; it is the one behaviour change in this feature.
//
// (The appview's own default stays the LEXICON default, posts_with_replies. Which tab a page opens on is
// a UI decision, so it lives here and is passed in, rather than being baked into the query layer.)
const PROFILE_TABS = [
  ['posts_no_replies', 'Posts', 'no posts from this author'],
  ['posts_with_replies', 'Replies', 'no posts or replies from this author'],
  ['posts_and_author_threads', 'Threads', 'no self-threads from this author'],
  ['posts_with_media', 'Media', 'no posts with images from this author']
]
const PROFILE_DEFAULT = 'posts_no_replies'


// Network-wide followers, from a backlink index (DESIGN §7.6 Tier C — referenced, never retained).
//
// ⛔ DELIBERATELY A SEPARATE LINE FROM THE LOCAL COUNT. Our number counts follows by DIDs this node
// indexes; this one counts the whole network. Different denominators, so a sum would be meaningless and
// silently replacing one with the other would make a partial view look total. They are labelled and kept
// apart — the same refusal lens-import makes for remote counts.
//
// Only VERIFIED handles are shown as names. An unverified follower renders as a short DID, because a
// follower list is exactly the surface where claiming someone else's handle would pay.
function netFollowers (net) {
  if (!net || !net.count) return ''
  const names = (net.followers || []).map((f) => {
    const label = f.verified && f.handle ? '@' + f.handle : shortDid(f.did)
    return `<a class="fol" href="/profile/${encodeURIComponent(f.did)}" title="${esc(f.did)}">${esc(label)}</a>`
  }).join(' ')
  const more = net.truncated ? `<span class="folmore"> +${net.count - net.shown} more</span>` : ''
  return `<p class="profnet"><strong>${net.count}</strong> follower${net.count === 1 ? '' : 's'}<span class="scopenote"> across the network</span>${names ? `<br>${names}${more}` : ''}</p>`
}

// Mute and block, offered together but deliberately NOT alike.
//
// MUTE is reversible, private, and nobody else ever learns of it — a quiet control, plain text, one
// click. BLOCK writes a PUBLIC record that federates, so it asks first via the same native <details>
// the delete confirm uses (no JS), and is styled as the heavier action. Presenting them identically
// would invite someone to publish a block when they meant to quietly mute.
//
// Both are plain forms; neither needs scripting. Hidden entirely on your own profile and when signed out.
// Add someone to one of YOUR lists, from their profile — the only place it makes sense. Shown only when
// you actually have lists; offering an empty picker would be a dead control.
function listPicker (did, graph) {
  const ls = (graph && graph.viewerLists) || []
  if (!ls.length) return ''
  const opts = ls.map((l) => `<option value="${esc(l.uri)}">${esc(l.name)}${l.member ? ' ✓' : ''}</option>`).join('')
  return `<form class="modf" method="POST" action="/api/list-member">
    <input type="hidden" name="subject" value="${esc(did)}">
    <input type="hidden" name="return" value="/profile/${encodeURIComponent(did)}">
    <select name="list" aria-label="list">${opts}</select>
    <button class="mutebtn">add / remove</button>
  </form>`
}

function modControls (did, graph) {
  if (!graph || !graph.canFollow || graph.isSelf) return ''
  const back = `/profile/${encodeURIComponent(did)}`
  const hidden = `<input type="hidden" name="did" value="${esc(did)}"><input type="hidden" name="return" value="${esc(back)}">`
  const mute = `<form class="modf" method="POST" action="/api/mute">${hidden}<button class="mutebtn${graph.viewerMuted ? ' on' : ''}">${graph.viewerMuted ? 'unmute' : 'mute'}</button></form>`
  const block = graph.viewerBlocked
    ? `<form class="modf" method="POST" action="/api/block">${hidden}<button class="blockbtn on">unblock</button></form>`
    : `<details class="modw"><summary>block</summary><form class="modf" method="POST" action="/api/block">${hidden}<button class="blockbtn">really block · this is public</button></form></details>`
  return `<div class="modrow">${mute}${block}${listPicker(did, graph)}</div>`
}

// A remote account's posts, via a lens. Same attribution rule as every other borrowed view: a NAMED
// source, escaped text, and NO like/reply/quote controls, because acting on a post we do not hold would
// be a lie. Media thumbs load from the lens's CDN — we hold no blob for these — with no-referrer so
// browsing here does not leak the page you are on.
function renderLensPosts (lp) {
  if (!lp || !lp.posts || !lp.posts.length) return ''
  const rows = lp.posts.map((r) => {
    const when = r.createdAt ? `<time datetime="${esc(r.createdAt)}">${esc(relTime(r.createdAt))}</time>` : ''
    const imgs = (r.images || []).map((im) => `<img class="lthumb" src="${esc(im.thumb)}" alt="${esc(im.alt || '')}" loading="lazy" referrerpolicy="no-referrer">`).join('')
    return `<article class="lpost">
      ${r.text ? `<div class="ltext">${esc(r.text)}</div>` : ''}
      ${imgs ? `<div class="lmedia">${imgs}</div>` : ''}
      <div class="meta">${when}${r.replyCount ? ` · ${r.replyCount} repl${r.replyCount === 1 ? 'y' : 'ies'} there` : ''}</div>
    </article>`
  }).join('')
  return `<section class="lens"><h3>${lp.posts.length} post${lp.posts.length === 1 ? '' : 's'} via <span class="lensname">${esc(lp.name)}</span> · not indexed by this node</h3>${rows}</section>`
}

// The profile's own base href, needed above the `base` const below (the counts render before it).
const base0 = (did) => `/profile/${encodeURIComponent(did)}`

export function profilePage ({ did, result, viewer = null, profile = null, graph = null, filter = PROFILE_DEFAULT, lensProfile = null, lensPosts = null, apRkeys = null } = {}) {
  // We hold no profile record for this DID (a bsky account reached via a backlink is the common case), so
  // a lens answered instead. Shown, but never passed off as ours: a named source, no follow/act
  // affordances beyond what the graph already allows, and the avatar loads from the LENS's CDN because we
  // hold no blob for them. §7.6 Tier C — referenced, never retained; nothing here is written to a store.
  const lp = !profile && lensProfile ? lensProfile : null
  const name = (profile && profile.displayName) || (lp && (lp.displayName || (lp.handle && '@' + lp.handle))) || shortDid(did)
  const cid = profile && (profile.avatarCid || blobCid(profile.avatar && profile.avatar.ref))
  const av = (cid && isSafeCid(cid))
    ? `<img class="pfp big" src="${esc(blobUrl(did, cid))}" alt="" width="72" height="72">`
    : (lp && lp.avatarUrl && /^https:\/\//i.test(lp.avatarUrl)
        ? `<img class="pfp big" src="${esc(lp.avatarUrl)}" alt="" width="72" height="72" loading="lazy" referrerpolicy="no-referrer">`
        : '<span class="pfp big none" aria-hidden="true"></span>')
  // The DID is shown in FULL here — unlike the timeline, this is the page where verifying exactly whose
  // account you are looking at is the point, so it is selectable text rather than a hover title.
  // The banner sits ABOVE the header row, full-bleed within the column. Absent → nothing renders, not an
  // empty grey band: a blank placeholder reads as a broken image rather than as "no banner set".
  const bcid = profile && blobCid(profile.banner && profile.banner.ref)
  const banner = (bcid && isSafeCid(bcid))
    ? `<div class="profbanner"><img src="${esc(blobUrl(did, bcid))}" alt="" loading="lazy"></div>`
    : ''
  const head = `${banner}<header class="profhdr">${av}
  <div><div class="profname">${esc(name)}</div>
  <div class="profdid"><code>${esc(did)}</code></div>
  ${profile && profile.description ? `<p class="profbio">${renderText(profile.description)}</p>` : ''}
  ${lp && lp.description ? `<p class="profbio">${esc(lp.description)}</p>` : ''}
  ${lp ? `<p class="lensnote">profile via <span class="lensname">${esc(lp.lens)}</span> · this node holds no records for this account${(lp.followersCount != null || lp.postsCount != null) ? `<br><span class="scopenote">${lp.followersCount != null ? lp.followersCount + ' followers' : ''}${(lp.followersCount != null && lp.postsCount != null) ? ' · ' : ''}${lp.postsCount != null ? lp.postsCount + ' posts' : ''} there</span>` : ''}</p>` : ''}
  ${(graph && (graph.following != null || graph.followers != null)) ? `<p class="profgraph"><a href="${base0(did)}/following"><strong>${graph.following || 0}</strong> following</a> · <a href="${base0(did)}/followers"><strong>${graph.followers || 0}</strong> follower${graph.followers === 1 ? '' : 's'}</a><span class="scopenote"> here</span></p>` : ''}
  ${netFollowers(graph && graph.network)}
  ${(graph && graph.canFollow && !graph.isSelf) ? `<form method="POST" action="/api/follow" class="followf"><input type="hidden" name="did" value="${esc(did)}"><input type="hidden" name="return" value="/profile/${encodeURIComponent(did)}"><button class="followbtn${graph.viewerFollows ? ' on' : ''}">${graph.viewerFollows ? 'following ✓' : 'follow'}</button></form>` : ''}
  ${modControls(did, graph)}</div></header>`
  const known = PROFILE_TABS.some(([v]) => v === filter) ? filter : PROFILE_DEFAULT
  const base = `/profile/${encodeURIComponent(did)}`
  // The active tab rides in the returnTo, so liking from Media comes back to Media, not to Posts.
  const hrefFor = (v) => v === PROFILE_DEFAULT ? base : `${base}?filter=${encodeURIComponent(v)}`
  const here = hrefFor(known)
  const empty = lp
    ? 'this node holds none of this account\'s posts — it knows them only by reference'
    : ((PROFILE_TABS.find(([v]) => v === known) || [])[2] || 'no posts from this author')
  const tabs = `<nav class="ptabs">${PROFILE_TABS.map(([v, label]) =>
    `<a class="ptab${v === known ? ' on' : ''}" href="${hrefFor(v)}">${esc(label)}</a>`).join('')}</nav>`
  return page({
    title: `${name} · favela`,
    heading: 'favela',
    viewer,
    active: null,
    body: `<div class="viewhdr"><a href="/">← all posts</a></div>${head}${tabs}` +
      renderPosts(withReach(withViewer(result && result.posts, viewer, here), apRkeys), lensPosts ? '' : empty) + moreLink(result && result.cursor, here) + renderLensPosts(lensPosts),
  })
}

// ── edit ──────────────────────────────────────────────────────────────────────────────────────────
//
// A plain form prefilled from the record, so editing works with scripting off like every other write
// here. Deliberately its own PAGE rather than an inline box: the composer at the top of the timeline
// is for new posts, and reusing it would make "am I writing or rewriting?" a matter of scroll
// position.
//
// ⚠ The reach notice is NOT decoration. atproto allows the edit and bsky's AppView ignores it, so the
// same post reads as edited via getRecord and stale via getPostThread. A user cannot be told "it did
// not sync", because partly it did — so we say exactly what is true per surface
// (spec/record-vocabulary.md §10.5.4).
export function editPage ({ post = null, viewer = null, returnTo = '/', error = null } = {}) {
  if (!post) {
    return page({ title: 'edit · favela', viewer, active: null,
      body: `<div class="viewhdr"><a href="${esc(returnTo)}">← back</a></div>` + emptyState('post not found', 'It may not have reached this node yet.') })
  }
  const rec = post.record || {}
  const uri = post.uri || ''
  const media = (rec.embed && (rec.embed.images || (rec.embed.media && rec.embed.media.images))) ? true : false
  return page({
    title: 'edit post · favela',
    heading: 'favela',
    viewer,
    active: null,
    body: `<div class="viewhdr"><a href="${esc(returnTo)}">← back</a></div>
<h2 class="edith">Edit post</h2>
${error ? `<p class="editerr" role="alert">${esc(error)}</p>` : ''}
<form class="composer editform" method="POST" action="/api/edit">
  <input type="hidden" name="uri" value="${esc(uri)}">
  <input type="hidden" name="return" value="${esc(returnTo)}">
  <textarea name="text" rows="5" maxlength="3000" aria-label="post text">${esc(rec.text || '')}</textarea>
  <p class="editnote">
    Editing the text only. The original time, thread and any attachments are kept.
    ${media ? '<br>Images are preserved and cannot be changed here.' : ''}
  </p>
  <p class="editreach">
    <strong>Where this edit lands:</strong>
    <span class="badge reach">favela</span> updated ·
    <span class="badge reach">fediverse</span> updated ·
    <span class="badge reach weak">bsky</span> <em>the record updates, but bsky&#39;s AppView ignores
    post edits — the old text keeps showing in threads there.</em>
  </p>
  <p><button type="submit">save changes</button>
     <a class="editcancel" href="${esc(returnTo)}">cancel</a></p>
</form>`
  })
}

// ── follower / following list ─────────────────────────────────────────────────────────────────────
//
// The profile shows counts and an inline run of names, which stops being usable past a handful and gives
// no way to page. This is the dedicated list.
//
// ★ `source` is why this page is shaped the way it is. Follows arrive from more than one place and the
// difference is NOT cosmetic: a follow we hold as a signed `app.bsky.graph.follow` record is a different
// epistemic thing from one a lens reported, and — once ap-bridge's follower state is readable — from a
// fediverse follow whose only proof is an HTTP Signature verified at receipt. Same list, labelled
// sources, never silently merged into one number. This mirrors the profile's existing choice to render
// local and network-wide counts as SEPARATE lines rather than summing them.
//
// Accounts: [{ did, displayName, handle, verified, source }]. `source` is a short label or null for ours.
export function followListPage ({ did, kind = 'followers', accounts = [], viewer = null, subjectName = null, cursor = null } = {}) {
  const who = subjectName || shortDid(did)
  const base = `/profile/${encodeURIComponent(did)}`
  const isFollowers = kind !== 'following'
  const tab = (k, label) => `<a href="${base}/${k}"${(isFollowers ? 'followers' : 'following') === k ? ' aria-current="page"' : ''}>${esc(label)}</a>`

  const rows = accounts.map((a) => {
    const label = a.displayName || (a.verified && a.handle ? '@' + a.handle : shortDid(a.did))
    const sub = (a.verified && a.handle && a.displayName) ? '@' + a.handle : (a.did || a.url || '')
    // The source badge is rendered ONLY when it is not our own signed record — an unlabelled row means
    // "we hold the record", and that default must stay silent or the label stops carrying information.
    const src = a.source ? `<span class="fo-src" title="where this follow is known from">${esc(a.source)}</span>` : ''
    // A row we hold a DID for links to OUR profile page. One we do not — a fediverse follower — links
    // OUT to their own server, marked external. Sending them to /profile/<nothing> would render an
    // empty stranger, and pretending we have a local page for an account we hold nothing of is the
    // same lie the lens rules already forbid (§7.6 Tier C: referenced, never retained).
    const href = a.did
      ? `/profile/${encodeURIComponent(a.did)}`
      : (typeof a.url === 'string' && /^https:\/\//i.test(a.url) ? a.url : null)
    const rel = a.did ? '' : ' rel="noopener nofollow external" target="_blank"'
    const inner = `<span class="fo-name">${esc(label)}</span><span class="fo-sub">${esc(sub)}</span>`
    const id = href ? `<a class="fo-id" href="${esc(href)}"${rel}>${inner}</a>` : `<span class="fo-id">${inner}</span>`
    return `<li>${id}${src}</li>`
  }).join('')

  const body = accounts.length
    ? `<ul class="folist">${rows}</ul>` + (cursor ? `<a class="more" href="${base}/${isFollowers ? 'followers' : 'following'}?cursor=${encodeURIComponent(cursor)}" rel="next">more →</a>` : '')
    : emptyState(
        isFollowers ? 'no followers here yet' : 'not following anyone yet',
        isFollowers
          ? 'This node only knows follows it has indexed — someone may follow this account elsewhere without it showing here.'
          : '')

  return page({
    title: `${who} · ${isFollowers ? 'followers' : 'following'} · favela`,
    heading: 'favela',
    viewer,
    active: null,
    body: `<div class="viewhdr"><a href="${base}">← ${esc(who)}</a></div>
<nav class="subtabs">${tab('followers', 'Followers')}${tab('following', 'Following')}</nav>${body}`
  })
}

// A single post on its own page — the target of every permalink. Also the natural home for a thread view
// when replies land; today it renders the one post plus its at:// URI, which is the identifier anything
// else in the atproto world needs to address it.
// A remote AppView's replies, rendered as a NAMED, SEPARATE source.
//
// Deliberately not our post component. Two reasons, both about not lying:
//   - No like/reply buttons. Acting on a remote post is not wired through this node, so an affordance
//     that silently does nothing is worse than its absence.
//   - Plain escaped text, not renderText. Our rich-text pass resolves facets against records we hold;
//     remote text is untrusted input from another service and gets escaped, full stop.
// Counts are shown per-post as the lens reported them and are never added to ours — bsky's numbers are
// network-wide, ours are window-local, and a sum of the two would mean nothing.
// One remote post row, shared by the reply and ancestor sections.
function lensRow (r) {
  const who = r.displayName || (r.handle ? '@' + r.handle : shortDid(r.did || ''))
  const when = r.createdAt ? `<time datetime="${esc(r.createdAt)}">${esc(relTime(r.createdAt))}</time>` : ''
  return `<article class="lpost">
    <div class="lwho">${esc(who)}${r.handle && r.displayName ? ` <span class="lhandle">@${esc(r.handle)}</span>` : ''}</div>
    <div class="ltext">${esc(r.text)}</div>
    <div class="meta">${when}${r.replyCount ? ` · ${r.replyCount} repl${r.replyCount === 1 ? 'y' : 'ies'} there` : ''}</div>
  </article>`
}

// The ancestors our own walk could not reach, rendered IN THE GAP where it stopped. Same attribution
// rule as replies: a named foreign source, no affordances, escaped text. The point is that the reader
// sees the conversation actually begins earlier and where it came from — not that our chain got longer.
function renderLensAncestors (groups) {
  if (!groups || !groups.length) return ''
  return groups.filter((g) => g.posts && g.posts.length).map((g) => `<section class="lens lensup">
  <h3>earlier in this thread, via <span class="lensname">${esc(g.lens)}</span> · not indexed by this node</h3>
  ${g.posts.map(lensRow).join('')}
</section>`).join('')
}

function renderLensReplies (groups) {
  if (!groups || !groups.length) return ''
  return groups.map((g) => `<section class="lens">
  <h3>${g.replies.length} repl${g.replies.length === 1 ? 'y' : 'ies'} via <span class="lensname">${esc(g.lens)}</span> · not indexed by this node</h3>
  ${g.replies.map(lensRow).join('')}
</section>`).join('')
}

export function postPage ({ post, viewer = null, replies = [], canWrite = false, ancestors = [], lensReplies = [], lensAncestors = [], lensesOn = false, gateNote = '', viewerCanReply = true, quoteNote = '', viewerCanQuote = true } = {}) {
  if (!post) {
    return page({ title: 'post not found · favela', viewer, active: null, body: '<div class="viewhdr">Post <a href="/">← all posts</a></div><p class="empty">no such post — it may not have reached this node yet.</p>' })
  }
  const who = (post.author && post.author.displayName) || shortDid(post.did)
  const backTo = postHref(post)
  // The ancestor chain, oldest first, above the focused post. A `missing` marker is an HONEST gap: the
  // parent exists somewhere in atproto but not in this node's window, and saying so beats rendering a
  // thread that appears to begin mid-conversation.
  // A lens fills the gap IN PLACE, where our own walk stopped — so the conversation reads in order
  // rather than having its beginning tacked on somewhere else. If no lens answered, the honest marker
  // stands. `filled` is what any lens actually returned for the gap.
  const filled = (lensAncestors || []).filter((g) => g.posts && g.posts.length)
  const above = (ancestors || []).map((a) => a && a.missing
    ? (filled.length
        ? renderLensAncestors(filled)
        : `<p class="empty missing">⤒ earlier replies are outside this node's window<br><code>${esc(a.uri || '')}</code></p>`)
    : (a ? `<div class="tnode ancestor">${renderPost(withViewer([a], viewer, backTo)[0])}</div>` : '')).join('')
  const replyTotal = countThread(replies)
  // This post IS this page — see the `stretch` note in renderPost. Its own whole-entry link would point
  // here, and would sit over the text the reader came for.
  const focused = withViewer([post], viewer, backTo)[0]
  focused.focused = true
  focused.quotable = viewerCanQuote
  return page({
    title: `${who} · favela`,
    viewer,
    active: null,
    body: `<div class="viewhdr">Thread <a href="/">← all posts</a></div>${above}<div class="focus">${renderPost(focused)}</div>
${gateNote ? `<p class="gatenote">🔒 ${esc(gateNote)}</p>` : ''}
${quoteNote ? `<p class="gatenote">❝ ${esc(quoteNote)}</p>` : ''}
${(viewer && canWrite && viewerCanReply) ? `<form class="replyf" method="POST" action="/api/post">
  <input type="hidden" name="replyTo" value="${esc(post.uri || uriOf(post))}">
  <textarea name="text" rows="2" placeholder="reply…" required></textarea>
  <p><span id="reply-cc" class="cc"></span><button>reply</button></p>
</form>` : (viewer && canWrite && !viewerCanReply
  // The box is GONE and the reason is stated. Silently removing it looks like a broken page, and a
  // threadgate is the author's choice — worth naming rather than hiding.
  ? `<p class="empty gateoff">The author limited who can reply to this thread, and this account is not included.</p>`
  : '')}
${replyTotal ? `<div class="thread"><h3>${replyTotal} repl${replyTotal === 1 ? 'y' : 'ies'}</h3>${renderThread(replies, viewer, backTo)}</div>` : ''}
${renderLensReplies(lensReplies)}
${lensesOn ? '' : `<p class="empty lensoff">This node reads no remote AppView, so replies from outside its own window are not shown here. A thread with unseen replies looks identical to one with none — that is why this line exists.</p>`}
<p class="empty aturi"><code>${esc(uriOf(post))}</code></p>`
  })
}

// The search page. TWO SOURCES, never merged.
//
// What this node holds is rendered as our own posts, with the ordinary affordances. What bsky returns is
// rendered as a NAMED foreign source with escaped text and no like/reply controls — the same rule the
// thread view's lens replies follow, and for the same reason: acting on a post we do not hold would be a
// lie, and blending remote hits into ours would make a partial index look total.
export function searchPage ({ q = '', local = null, actors = [], lens = null, viewer = null, canWrite = false } = {}) {
  const query = String(q || '')
  const box = `<form class="searchbox" method="GET" action="/search" role="search"><input type="search" name="q" value="${esc(query)}" placeholder="search posts and people" aria-label="search" autofocus><button>search</button></form>`
  if (!query.trim()) {
    return page({ title: 'search · favela', viewer, active: 'search', body: `<div class="viewhdr">Search</div>${box}<p class="empty">Search this node\'s posts and people — and bsky, shown separately.</p>` })
  }
  const people = actors.length
    ? `<h3 class="stath">people here</h3>` + actors.map((a) => {
        const name = (a.profile && a.profile.displayName) || shortDid(a.did)
        const cid = a.profile && blobCid(a.profile.avatar && a.profile.avatar.ref)
        const av = (cid && isSafeCid(cid))
          ? `<img class="pfp" src="${esc(blobUrl(a.did, cid))}" alt="" loading="lazy" width="36" height="36">`
          : '<span class="pfp none" aria-hidden="true"></span>'
        return `<a class="byline actorrow" href="/profile/${encodeURIComponent(a.did)}" title="${esc(a.did)}">${av}<span class="name">${esc(name)}</span></a>`
      }).join('')
    : ''
  const posts = (local && local.posts && local.posts.length)
    ? `<h3 class="stath">posts here</h3>` + renderPosts(withViewer(local.posts, viewer, `/search?q=${encodeURIComponent(query)}`))
    : ''
  // A scan cap is a COST ceiling, and hitting it means the answer is incomplete. Saying so beats
  // returning a short list that looks complete.
  const truncated = local && local.truncated
    ? '<p class="empty">…this node\'s index was only scanned to a bounded depth, so older matches may be missing.</p>'
    : ''
  const nothingLocal = !people && !posts ? '<p class="empty">nothing on this node matches</p>' : ''
  const remote = lens && lens.posts && lens.posts.length
    ? `<section class="lens"><h3>${lens.posts.length} post${lens.posts.length === 1 ? '' : 's'} via <span class="lensname">${esc(lens.name)}</span> · not indexed by this node</h3>${lens.posts.map(lensRow).join('')}</section>`
    : ''
  const remoteActors = lens && lens.actors && lens.actors.length
    ? `<section class="lens"><h3>${lens.actors.length} account${lens.actors.length === 1 ? '' : 's'} via <span class="lensname">${esc(lens.name)}</span></h3>${lens.actors.map((a) => `<article class="lpost"><div class="lwho">${esc(a.displayName || a.handle || a.did)}${a.handle ? ` <span class="lhandle">@${esc(a.handle)}</span>` : ''}</div>${a.description ? `<div class="ltext">${esc(String(a.description).slice(0, 160))}</div>` : ''}<div class="meta"><a href="/profile/${encodeURIComponent(a.did)}">open here</a></div></article>`).join('')}</section>`
    : ''
  const lensOff = !lens ? '<p class="empty lensoff">This node reads no remote AppView, so results are limited to what it holds.</p>' : ''
  return page({
    title: `${query} · search · favela`,
    viewer,
    active: 'search',
    canWrite,
    body: `<div class="viewhdr">Search</div>${box}${people}${posts}${truncated}${nothingLocal}${remoteActors}${remote}${lensOff}`
  })
}

// The bookmarks page. Private by construction — there is no shared state to render, so this is simply
// the viewer's own saved posts, newest-SAVED first (see lib/bookmarks.js on why not newest-posted).
export function bookmarksPage ({ result = null, viewer = null, missing = 0 } = {}) {
  if (!viewer) {
    return page({ title: 'bookmarks · favela', viewer, active: 'bookmarks', body: '<div class="viewhdr">Bookmarks</div><p class="empty">Sign in to save posts. <a href="/login">sign in →</a></p>' })
  }
  const posts = withViewer((result && result.posts) || [], viewer, '/bookmarks')
  // A bookmark can outlive the post it points at — deleted by its author, or simply not held here any
  // more. Saying how many could not be loaded beats silently returning a shorter list.
  const gone = missing
    ? `<p class="empty">${missing} bookmarked post${missing === 1 ? '' : 's'} could not be loaded — deleted, or outside this node's window.</p>`
    : ''
  return page({
    title: 'bookmarks · favela',
    viewer,
    active: 'bookmarks',
    body: `<div class="viewhdr">Bookmarks <span class="scopenote">· private to you, stored only on this node</span></div>` +
      renderPosts(posts, 'nothing saved yet — tap ☆ on a post') + gone
  })
}

// Notifications. The server renders ONLY this shell — every authenticated byte moves between the
// browser and the PDS (web/static/notifications.js explains why). favela-web holds no credential, which
// is the property that would be lost by doing this server-side.
//
// This is the ONE page that requires JavaScript, and it says so rather than appearing broken with
// scripting off. Notifications are inherently authenticated and per-viewer; there is no meaningful
// server-rendered version when the server deliberately holds nothing.
// One notification line. Kind decides the verb, network decides the badge — a reply from Mastodon
// and a reply from bsky are not interchangeable, and a UI that renders them identically is lying
// about where the conversation is happening.
function notifRow (n) {
  const verb = n.kind === 'reply' ? 'replied' : n.kind === 'like' ? 'liked' : n.kind === 'boost' ? 'boosted' : 'mentioned you'
  const net = n.network === 'activitypub' ? 'fediverse' : 'bsky'
  // n.text is already stripped of remote markup by notifications.js; esc() is the second line of
  // defence, not the first.
  const said = n.text ? `<div class="ntext">${esc(n.text.slice(0, 280))}</div>` : ''
  const when = n.when ? `<time datetime="${esc(n.when)}">${esc(relTime(n.when))}</time>` : '<span class="dim">unknown time</span>'
  const link = n.url ? `<a href="${esc(n.url)}" rel="noopener">open</a>` : ''
  return `<div class="notif"><div class="nhead"><strong>${esc(n.who || 'someone')}</strong> ${verb} <span class="netbadge">${net}</span> · ${when} ${link}</div>${said}</div>`
}

// ⛔ THIS PAGE USED TO ASK FOR A SECOND CREDENTIAL. It rendered a shell and a form for a bsky APP
// PASSWORD, then fetched bsky's notification API in the browser — for an account this node already
// controls, showing bsky's view rather than ours, and blind to ActivityPub entirely (#45: "the 'did
// anyone reply to me' loop does not work").
//
// Now the node answers from what it already knows: the inbound lens folds replies that touch our
// content into the appview, and ap-bridge keeps what the fediverse sends. No credential, works with
// JavaScript off.
//
// ⚠ `apAvailable === false` is NOT "no fediverse replies" — it is "this node cannot see them",
// because ap-bridge is single-instance and may live on another host. Saying so is the difference
// between an empty page that is true and one that is a lie.
export function notificationsPage ({ viewer = null, pds = 'https://pds.7rnx.net', items = [], apAvailable = null } = {}) {
  const list = items.length
    ? items.map(notifRow).join('')
    : '<p class="empty">Nothing yet — replies, likes and boosts that touch your posts appear here.</p>'
  const apNote = apAvailable === false
    ? '<p class="scopenote">⚠ The ActivityPub side is not readable from this node, so fediverse replies are not shown here. They are not missing — this node cannot see them.</p>'
    : ''
  const body = `<div class="viewhdr">Notifications <span class="scopenote">· from this node, no credential</span></div>
${apNote}
<div class="notiflist">${list}</div>
<details class="bskybox"><summary>also fetch bsky's own notifications in this browser</summary>
<noscript><p class="empty">Notifications need JavaScript. Everything else in favela works without it — this page is the exception, because the server holds no credential of yours and so cannot fetch them for you.</p></noscript>
<form id="notif-login" class="authbox" hidden>
  <p class="empty">Sign in with an <strong>app password</strong> — not your account password. It is used once to mint a session and is never stored; only the short-lived tokens are kept, in this browser.</p>
  <p><label for="notif-handle">handle</label><br><input id="notif-handle" type="text" autocomplete="username" placeholder="you.example.com" value="${esc((viewer && viewer.handle) || '')}"></p>
  <p><label for="notif-pass">app password</label><br><input id="notif-pass" type="password" autocomplete="current-password" placeholder="xxxx-xxxx-xxxx-xxxx"></p>
  <p><button type="submit">sign in</button></p>
</form>
<p id="notif-status" aria-live="polite" class="empty"></p>
<div id="notif-list"></div>
<p><button id="notif-signout" class="devbtn">forget this browser\'s notification session</button></p>
</details>`
  return page({
    title: 'notifications · favela',
    viewer,
    active: 'notifications',
    body,
    clientScript: `<meta name="favela-pds" content="${esc(pds)}">
<style>
.notif{display:flex;gap:.6rem;align-items:flex-start;padding:.7rem 0;border-bottom:1px solid var(--line,#e5e5e5)}
.notif.unread{background:var(--bg-soft,#f7f8fa);border-radius:var(--r1,.375rem);padding-left:.5rem;padding-right:.5rem}
.ntext{min-width:0;flex:1}
.nquote{color:var(--fg-dim,#5c6672);font-size:.9rem;margin-top:.2rem;white-space:pre-wrap;overflow-wrap:anywhere}
#notif-login input{width:100%;box-sizing:border-box;font:inherit;padding:.4rem;border:1px solid var(--line,#ccc);border-radius:.3rem}
#notif-login button{font:inherit;padding:.4rem 1rem;border:none;border-radius:999px;background:var(--accent,#1a56db);color:#fff;font-weight:600;cursor:pointer}
#notif-status.err{color:#c92a2a}#notif-status.ok{color:var(--fg-dim,#5c6672)}
</style>
<script type="module" src="/static/notifications.js"></script>`
  })
}

// Your lists. A list is TWO record types (see lib/lists.js) but one idea, so the page shows the list and
// its size, and the members live on their own page.
//
// PURPOSE IS SHOWN, always. A modlist mutes or blocks everyone on it for anyone who subscribes; rendering
// it identically to a curation list hands someone a footgun.
export function listsPage ({ viewer = null, lists = [], canWrite = false, notFound = null } = {}) {
  if (!viewer) {
    return page({ title: 'lists · favela', viewer, active: 'lists', body: '<div class="viewhdr">Lists</div><p class="empty">Sign in to make lists. <a href="/login">sign in →</a></p>' })
  }
  const rows = lists.length
    ? lists.map((l) => {
        const mod = l.record && l.record.purpose === 'app.bsky.graph.defs#modlist'
        return `<a class="listrow" href="/lists/${encodeURIComponent(l.rkey)}">
          <span class="listname">${esc((l.record && l.record.name) || l.rkey)}</span>
          <span class="listkind${mod ? ' mod' : ''}">${mod ? 'moderation list' : 'curation list'}</span>
          ${l.record && l.record.description ? `<span class="listdesc">${esc(l.record.description)}</span>` : ''}
        </a>`
      }).join('')
    : '<p class="empty">no lists yet</p>'
  const form = canWrite
    ? `<form class="authbox" method="POST" action="/api/list">
        <h3>New list</h3>
        <p><label for="list-name">name</label><br><input id="list-name" name="name" type="text" maxlength="64" required placeholder="people who post about boats"></p>
        <p><label for="list-desc">description</label><br><input id="list-desc" name="description" type="text" maxlength="300"></p>
        <p><label for="list-purpose">kind</label><br><select id="list-purpose" name="purpose">
          <option value="app.bsky.graph.defs#curatelist">curation list — just a group of people</option>
          <option value="app.bsky.graph.defs#modlist">moderation list — subscribers MUTE or BLOCK everyone on it</option>
        </select></p>
        <p><button type="submit">create list</button></p>
      </form>`
    : '<p class="empty">this node does not sign for you, so it cannot create lists</p>'
  const missing = notFound ? `<p class="empty">no list with that id</p>` : ''
  return page({ title: 'lists · favela', viewer, active: 'lists', body: `<div class="viewhdr">Lists</div>${missing}${rows}${form}` })
}

// One list and its members. Removing someone deletes THEIR listitem — the membership record is the thing
// that exists, so the control is per-member rather than an edit of the list.
export function listPage ({ viewer = null, list = null, members = [] } = {}) {
  if (!list) return page({ title: 'list · favela', viewer, active: 'lists', body: '<div class="viewhdr">List <a href="/lists">← lists</a></div><p class="empty">no such list</p>' })
  const rec = list.record || {}
  const mod = rec.purpose === 'app.bsky.graph.defs#modlist'
  const rows = members.length
    ? members.map((m) => `<div class="listrow">
        <a class="byline" href="/profile/${encodeURIComponent(m.subject)}" title="${esc(m.subject)}"><span class="name">${esc(m.displayName || shortDid(m.subject))}</span></a>
        <form class="modf" method="POST" action="/api/list-member">
          <input type="hidden" name="list" value="${esc(list.uri)}">
          <input type="hidden" name="subject" value="${esc(m.subject)}">
          <input type="hidden" name="return" value="/lists/${encodeURIComponent(list.rkey)}">
          <button class="mutebtn">remove</button>
        </form>
      </div>`).join('')
    : '<p class="empty">nobody on this list yet — add someone from their profile</p>'
  return page({
    title: `${(rec.name || 'list')} · favela`,
    viewer,
    active: 'lists',
    body: `<div class="viewhdr">${esc(rec.name || list.rkey)} <a href="/lists">← lists</a></div>
<p class="lensnote">${mod ? 'moderation list — subscribing to this mutes or blocks everyone on it' : 'curation list'}${rec.description ? ' · ' + esc(rec.description) : ''}</p>
<p class="empty aturi"><code>${esc(list.uri)}</code></p>
${rows}`
  })
}

// /status — the operator page. Everything here was previously either a boot-log line, a hand-built curl,
// or nothing at all. The ordering is deliberate: the ingest table first, because a frozen front is the
// failure that looks healthy from every other angle.
export function statusPage ({ fronts = null, lens = null, host = null, viewer = null } = {}) {
  const yn = (b) => b ? '<span class="ok">yes</span>' : '<span class="bad">no</span>'
  const didRows = ((fronts && fronts.dids) || []).map((d) => {
    // The alarm: chosen front is not the highest-rev line, or the line we are on is shorter than one we
    // can see. Either is the freeze signature.
    const alarm = d.frontCount > 1 && (d.onHighestRev === false || (d.behindBy || 0) > 0)
    const rows = (d.fronts || []).map((f) => `<tr class="${f.chosen ? 'chosen' : ''}">
      <td><code>${esc(f.short || '')}</code>${f.chosen ? ' ←' : ''}</td>
      <td>${esc(String(f.rev || '—'))}</td>
      <td>${f.firehoseLength == null ? '—' : f.firehoseLength}</td>
      <td>${yn(f.live)}</td><td>${yn(f.verified)}</td></tr>`).join('')
    return `<div class="statblk${alarm ? ' alarm' : ''}">
      <div class="statdid"><code>${esc(d.did)}</code></div>
      <div class="statsum">${d.frontCount} front${d.frontCount === 1 ? '' : 's'} ·
        following <code>${esc(d.chosen || 'none')}</code> ·
        highest-rev: ${yn(d.onHighestRev)}${d.behindBy ? ` · <strong>behind by ${d.behindBy} frames</strong>` : ''}</div>
      ${d.frontCount ? `<table class="stattbl"><tr><th>front</th><th>rev</th><th>firehose</th><th>live</th><th>verified</th></tr>${rows}</table>` : '<p class="empty">no fronts known</p>'}
      ${alarm ? '<p class="alarmnote">⚠ following a line that is not the freshest — this is the shape of a frozen index.</p>' : ''}
    </div>`
  }).join('')

  const s = lens && lens.stats
  const lensBlk = `<div class="statblk">
    <div class="statsum">lens import: ${lens && lens.enabled ? '<span class="ok">on</span>' : '<span class="bad">off</span>'}${(lens && lens.lenses && lens.lenses.length) ? ' · ' + lens.lenses.map((l) => `<code>${esc(l.name)}</code> → ${esc(l.base)}`).join(', ') : ''}</div>
    ${s ? `<table class="stattbl"><tr><th>hits</th><th>misses</th><th>fetches</th><th>failures</th><th>timeouts</th><th>coalesced</th><th>short-circuited</th><th>cache</th><th>breakers open</th></tr>
      <tr><td>${s.hits}</td><td>${s.misses}</td><td>${s.fetches}</td><td>${s.failures}</td><td>${s.timeouts}</td><td>${s.coalesced}</td><td>${s.shortCircuited}</td><td>${s.cacheSize}</td><td>${(s.open || []).length ? '<span class="bad">' + esc((s.open || []).join(', ')) + '</span>' : '0'}</td></tr></table>` : ''}
    ${(lens && lens.errors && lens.errors.length) ? `<p class="alarmnote">⚠ ${lens.errors.map(esc).join('<br>')}</p>` : ''}
  </div>`

  return page({
    title: 'status · favela',
    heading: 'favela',
    viewer,
    active: null,
    body: `<div class="viewhdr">Status${host ? ` · <code>${esc(host)}</code>` : ''} <a href="/">← all posts</a></div>
<h3 class="stath">ingest — which co-owner's firehose each DID follows</h3>${didRows || '<p class="empty">no DIDs</p>'}
<h3 class="stath">lens import</h3>${lensBlk}
<p class="empty">raw: <a href="/api/fronts">/api/fronts</a> · <a href="/api/lens">/api/lens</a></p>`
  })
}

export function tagPage ({ tag, result, viewer = null } = {}) {
  return page({
    title: `#${tag} · favela`,
    heading: 'favela',
    viewer,
    active: null,
    body: `<div class="viewhdr">#${esc(tag)} <a href="/">← all posts</a></div>` + renderPosts(withViewer(result && result.posts, viewer, `/tag/${encodeURIComponent(tag)}`), `no posts for #${esc(tag)}`) + moreLink(result && result.cursor, `/tag/${encodeURIComponent(tag)}`),
  })
}

// The DID sign-in page. Server-renders the scaffolding; the client script (/static/login.js) generates
// the browser's secp256k1 sub-key, drives pairing (paste the hpp-minted delegation) + the challenge→
// sign→session flow. favela is KEYLESS — the sub-key secret never leaves the browser and no key of the
// viewer's is ever held server-side. Model: the DID is the anchor, each browser sub-key is a delegated
// device (the atproto analog of pgv3's root ← device chain).
export function loginPage ({ viewer = null } = {}) {
  const body = `<div class="viewhdr">Sign in to favela <a href="/">← back</a></div>
<p class="empty">favela never holds your key. Your browser signs a challenge with a secp256k1 <em>sub-key</em> that your DID's <code>#atproto</code> key has delegated — the atproto-native sign-in (the pgv3 method). No key of yours is stored server-side.</p>
<p id="status" aria-live="polite"></p>

<section id="session-box" class="authbox" style="display:none">
  <p>Signed in as <strong id="session-who"></strong>.</p>
  <p><button id="logout-btn" type="button">sign out</button> <a href="/">go to timeline →</a></p>
</section>

<section id="signin-box" class="authbox" style="display:none">
  <p>This browser is paired to <strong id="paired-did"></strong>.</p>
  <p><button id="signin-btn" type="button">sign in</button> <button id="unpair-btn" type="button" class="ghost">unpair this browser</button></p>
</section>

<section id="pair-box" class="authbox" style="display:none">
  <h3>Pair this browser to your DID</h3>
  <ol class="pair-steps">
    <li>On the machine that holds your DID (your <strong>hpp</strong>), run <code>favela-pair</code>. It prints a one-time <strong>pairing invite</strong> (a hash URL).</li>
    <li>Paste the invite here. favela opens a peer-to-peer tunnel to your hpp, which delegates this browser's sub-key — favela never sees your key.</li>
  </ol>
  <form id="pair-form">
    <p><textarea id="pair-invite" rows="2" placeholder="pairing invite from favela-pair (a long hex string, or the …/login#pair=… link)" spellcheck="false" required></textarea></p>
    <p><button type="submit">pair &amp; sign in</button></p>
  </form>
  <p class="empty" style="margin-top:.5rem">This browser's sub-key: <code id="subkey" class="subkey"></code> <button id="copy-subkey" type="button" class="ghost">copy</button> <span style="opacity:.6">(the hpp delegates this over the tunnel — you don't need to copy it)</span></p>
</section>`
  return page({
    title: 'sign in · favela',
    viewer,
    active: null,
    body,
    clientScript: `<style>
.authbox{border:1px solid #e5e5e5;border-radius:.5rem;padding:1rem;margin:1rem 0}
.authbox h3{margin:.2rem 0 .6rem}
.pair-steps{padding-left:1.2rem}.pair-steps li{margin:.5rem 0}
.subkey{word-break:break-all;font-size:.8rem;background:#f3f4f6;padding:.15rem .35rem;border-radius:.3rem}
.authbox input,.authbox textarea{width:100%;box-sizing:border-box;font:inherit;padding:.4rem;border:1px solid #ccc;border-radius:.3rem}
.authbox button{font:inherit;padding:.35rem .8rem;cursor:pointer}
.authbox button.ghost{background:none;border:1px solid #ccc;border-radius:.3rem}
#status.ok{color:#15803d}#status.err{color:#b91c1c}
@media(prefers-color-scheme:dark){.authbox{border-color:#333}.subkey{background:#1f2937}.authbox input,.authbox textarea,.authbox button.ghost{background:#222;color:#eee;border-color:#444}#status.ok{color:#4ade80}}
</style>
<script type="module" src="/static/login.js"></script>`
  })
}

// ── Atom feed (RSS-family; free off the same timeline view-model) ──────────────
export function renderAtom ({ posts = [], selfUrl = 'http://localhost/feed.xml', title = 'favela — native P2P timeline', updated } = {}) {
  const upd = updated || (posts[0] && posts[0].createdAt) || '1970-01-01T00:00:00.000Z'
  const entries = posts.map((p) => {
    const uri = uriOf(p)
    const text = (p.record && p.record.text) || ''
    return `<entry>
  <id>${esc(uri)}</id>
  <title>${esc(text.slice(0, 80) || '(post)')}</title>
  <updated>${esc(p.createdAt)}</updated>
  <author><name>${esc(p.did)}</name></author>
  <content type="text">${esc(text)}</content>
</entry>`
  }).join('\n')
  return `<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
  <title>${esc(title)}</title>
  <link rel="self" href="${esc(selfUrl)}"/>
  <id>${esc(selfUrl)}</id>
  <updated>${esc(upd)}</updated>
${entries}
</feed>`
}
// repair-bytes — re-author record BYTES this node indexed but never stored.
//
// ⛔ THE STATE THIS EXISTS TO CLEAR. Until 0.3.37 the appview's create-gate asked the ROSTER instead of
// the local hpp (see lib/hosted-dids.js), so a node that rostered a DID it did not co-host refused to
// author every one of that DID's records. The refusal is by design — hpp may hold a pointer to bytes
// that differ from our re-encode — but on such a node NO local hpp would ever write them.
//
// The miss is PERMANENT without this, and that is the part worth understanding: the record was still
// INDEXED (appview-no-clobber pins that trade — "we refuse the byte authorship, not the indexing"), so
// on every later replay the dedup gate at appview.js:377 sees a matching `sig` and returns before the
// write is retried. The index says the post exists; the store has no bytes; _resolveRecord returns null;
// the post 404s forever. ashatron sat like this from 2026-07-31 to 2026-08-06.
//
// WHERE THE BYTES COME FROM. `com.atproto.sync.getRecord` — a CAR carrying the signed commit and the MST
// blocks proving the record's inclusion — NOT `repo.getRecord`, whose hydrated JSON cannot be verified.
// The four checks in lib/record-fetch.js (commit is for this DID, signature validates against the DID
// DOCUMENT's key, the CID is provably at <collection>/<rkey> under the commit root, and the bytes hash
// to that CID) mean the served bytes are canonical no matter WHO served them. That is what makes this
// safe to run against our own membrane, which fronts the peers that actually hold the repo.
//
// ⛔ AND THE RE-ENCODE IS STILL GUARDED. OverlayRepoStore.put() takes a DECODED record and re-encodes it,
// but what we verified was the ORIGINAL bytes. If decode->encode is not byte-identical we REFUSE, exactly
// as lib/retention.js does — writing bytes that no longer match their CID is the 2026-07-30 outage, and
// a repair that re-introduced it would be worse than the gap it closes.
//
// NEVER OVERWRITES. Only absences are filled. A record whose bytes are already here is left untouched,
// so this cannot clobber hpp's canonical files no matter how it is invoked.
//
// DRY RUN BY DEFAULT. `write: false` reports what it WOULD do and touches nothing.
import * as dagCbor from '@ipld/dag-cbor'
import b4a from 'b4a'

export function emptyReport () {
  return {
    scanned: 0, // index entries examined
    present: 0, // bytes already on disk — the healthy majority
    missing: 0, // indexed, no bytes: the defect's footprint
    written: 0, // bytes fetched, verified and stored
    unfetchable: 0, // no peer/PDS could produce them (deleted, or genuinely lost)
    unverified: 0, // served, but failed one of the four proofs — never written
    reencodeRefused: 0, // canonical bytes that do not survive decode->encode — never written
    storeErrors: 0,
    samples: [] // a bounded list of what is missing, so a dry run is actionable
  }
}

// listRefs(did) -> async iterable of { did, rkey, collection }
// openStore(did) -> OverlayRepoStore (ready)
// fetchRecord(pointer) -> { bytes, commit, identity, ... } | null   (lib/record-fetch.js)
// verifyRecord(fetched, pointer) -> boolean                          (lib/record-fetch.js)
export async function repairBytes ({
  dids = [],
  listRefs,
  openStore,
  fetchRecord,
  verifyRecord,
  write = false,
  limit = 0, // 0 = no cap; otherwise stop after this many REPAIR ATTEMPTS (dry run: after this many finds)
  sampleLimit = 25,
  onEvent = null
} = {}) {
  if (typeof listRefs !== 'function') throw new Error('repairBytes requires listRefs')
  if (typeof openStore !== 'function') throw new Error('repairBytes requires openStore')
  if (write && typeof fetchRecord !== 'function') throw new Error('repairBytes --write requires fetchRecord')
  if (write && typeof verifyRecord !== 'function') throw new Error('repairBytes --write requires verifyRecord')

  const report = emptyReport()
  const emit = (ev, detail) => { if (onEvent) onEvent(ev, detail) }
  let attempts = 0

  for (const did of dids) {
    let store
    try {
      store = await openStore(did)
    } catch (e) {
      report.storeErrors++
      emit('store-failed', { did, error: (e && e.message) || String(e) })
      continue
    }
    if (!store) { report.storeErrors++; emit('store-failed', { did, error: 'no store' }); continue }

    for await (const ref of listRefs(did)) {
      if (limit && attempts >= limit) return report
      const collection = ref && ref.collection
      const rkey = ref && ref.rkey
      // An index entry written before `collection` was recorded cannot be located in the store or asked
      // for over XRPC. Counted, not guessed at.
      if (!collection || !rkey) { report.scanned++; report.storeErrors++; continue }
      report.scanned++

      const pointer = { did, collection, rkey }
      let existing = null
      try {
        existing = await store.getRaw(collection, rkey)
      } catch (e) {
        report.storeErrors++
        emit('read-failed', { pointer, error: (e && e.message) || String(e) })
        continue
      }
      if (existing != null) { report.present++; continue }

      report.missing++
      if (report.samples.length < sampleLimit) report.samples.push(pointer)
      emit('missing', { pointer })
      attempts++
      if (!write) continue // dry run: counted and sampled, nothing touched

      const fetched = await fetchRecord(pointer)
      if (!fetched || !fetched.bytes) { report.unfetchable++; emit('unfetchable', { pointer }); continue }

      let ok = false
      try { ok = await verifyRecord(fetched, pointer) } catch { ok = false }
      if (!ok) { report.unverified++; emit('unverified', { pointer }); continue }

      // The guard from lib/retention.js, for the same reason: put() re-encodes, and we verified the
      // ORIGINAL bytes. If the round trip is not byte-identical the store would persist bytes that no
      // longer match the CID we just proved. Refuse, loudly.
      let value
      try {
        value = dagCbor.decode(fetched.bytes)
      } catch {
        report.reencodeRefused++
        emit('decode-failed', { pointer })
        continue
      }
      let reencoded
      try {
        reencoded = dagCbor.encode(value)
      } catch {
        report.reencodeRefused++
        emit('reencode-failed', { pointer })
        continue
      }
      if (!b4a.equals(b4a.from(reencoded), b4a.from(fetched.bytes))) {
        report.reencodeRefused++
        emit('reencode-differs', { pointer, verified: fetched.bytes.length, reencoded: reencoded.length })
        continue
      }

      try {
        await store.put(collection, rkey, value)
        report.written++
        emit('written', { pointer, bytes: fetched.bytes.length })
      } catch (e) {
        report.storeErrors++
        emit('write-failed', { pointer, error: (e && e.message) || String(e) })
      }
    }
  }

  return report
}
// repair-strongrefs — rewrite records whose strongRef is missing its `cid`.
//
// THE DEFECT. `app.bsky.feed.like.subject` (and repost, and a reply's parent/root) is a
// com.atproto.repo.strongRef: uri AND cid, both REQUIRED. A record written with `subject: { uri }`
// indexes perfectly in favela and FAILS LEXICON VALIDATION AT THE RELAY — it federates as nothing while
// every local surface reports success. favela-web 0.2.41 shipped exactly that; 0cce69a fixed the write
// path. But the fix is forward-only: records already written stay invalid forever, so the account keeps
// showing likes that no one else can see. Measured on wj62 2026-07-31: 4 of 6 likes invalid, all from a
// single 14-second burst on 2026-07-29.
//
// WHY A COMMAND. The same reason `hyper-proto-peer repair-pointers` exists: the fix was known and the
// only way to apply it was a hand-written script. A defect whose repair is un-runnable is not fixed.
//
// SAFETY. This is a CONTENT-PRESERVING rewrite, not a delete:
//   - The subject URI is UNCHANGED. Only the missing `cid` is added, resolved from the bytes we already
//     hold, asserted by hash (strongRef returns null rather than guessing).
//   - A record whose subject cannot be resolved is SKIPPED, never rewritten with a placeholder — an
//     invalid record is better than a confidently wrong one.
//   - Records that already carry a cid are untouched.
//   - DRY RUN by default; --write required.
//
// The rewrite reuses the SAME rkey, so it is an update of the existing record rather than a new like —
// no duplicate appears, and the subject's like count does not double-count.
import { strongRef, parseAtUri } from './strongref.js'

// Collections whose records carry a strongRef, and where that ref lives.
// A reply carries TWO (parent + root) and both must be valid.
export const STRONGREF_FIELDS = {
  'app.bsky.feed.like': [['subject']],
  'app.bsky.feed.repost': [['subject']],
  'app.bsky.feed.post': [['reply', 'parent'], ['reply', 'root']]
}

const at = (obj, path) => path.reduce((o, k) => (o == null ? o : o[k]), obj)

// Which refs in this record are missing a cid? Returns [{ path, uri }].
export function brokenRefs (collection, record) {
  const fields = STRONGREF_FIELDS[collection]
  if (!fields || !record) return []
  const out = []
  for (const path of fields) {
    const ref = at(record, path)
    if (!ref || typeof ref !== 'object') continue
    if (typeof ref.uri !== 'string' || !parseAtUri(ref.uri)) continue
    if (ref.cid) continue // already valid
    out.push({ path, uri: ref.uri })
  }
  return out
}

// Return a REPAIRED copy, or null when any broken ref could not be resolved. Never partially repairs:
// a record with one fixed ref and one still-missing is still invalid, so it is left alone and reported.
export async function repairRecord (collection, record, getRecordStore) {
  const broken = brokenRefs(collection, record)
  if (!broken.length) return null
  const next = JSON.parse(JSON.stringify(record))
  for (const { path, uri } of broken) {
    const ref = await strongRef(uri, getRecordStore)
    if (!ref || !ref.cid) return null // unresolvable — refuse rather than invent a cid
    const parent = path.slice(0, -1).reduce((o, k) => o[k], next)
    parent[path[path.length - 1]] = { uri: ref.uri, cid: ref.cid }
  }
  return next
}

// Scan a repo's records and repair every invalid strongRef.
//   listRecords(collection) -> [{ rkey, record }]
//   applyWrite({ action:'update'|'create', collection, rkey, record })
// Returns { checked, broken, repaired, unresolvable, entries[] }.
export async function repairStrongRefs ({ listRecords, applyWrite, getRecordStore, write = false, collections = Object.keys(STRONGREF_FIELDS), onEvent = null } = {}) {
  if (typeof listRecords !== 'function') throw new Error('repairStrongRefs requires listRecords')
  if (typeof getRecordStore !== 'function') throw new Error('repairStrongRefs requires getRecordStore')
  const emit = (e, d) => { if (onEvent) onEvent(e, d) }
  const stats = { checked: 0, broken: 0, repaired: 0, unresolvable: 0, entries: [] }

  for (const collection of collections) {
    let recs = []
    try { recs = (await listRecords(collection)) || [] } catch (err) { emit('list-failed', { collection, error: err.message }); continue }
    for (const { rkey, record } of recs) {
      stats.checked++
      const broken = brokenRefs(collection, record)
      if (!broken.length) continue
      stats.broken++
      const fixed = await repairRecord(collection, record, getRecordStore)
      if (!fixed) {
        stats.unresolvable++
        stats.entries.push({ collection, rkey, state: 'unresolvable', uris: broken.map((b) => b.uri) })
        emit('unresolvable', { collection, rkey, uris: broken.map((b) => b.uri) })
        continue
      }
      stats.entries.push({ collection, rkey, state: write ? 'repaired' : 'would-repair', uris: broken.map((b) => b.uri) })
      if (!write) continue
      try {
        // SAME rkey => an update, not a second like. A new rkey would double-count the subject.
        await applyWrite({ action: 'update', collection, rkey, record: fixed })
        stats.repaired++
        emit('repaired', { collection, rkey })
      } catch (err) {
        emit('write-failed', { collection, rkey, error: err.message })
      }
    }
  }
  return stats
}
// repo-sync — "does my copy match the authoritative repo, and pull what is missing".
//
// ⛔ THE QUESTION NOTHING ANSWERED. This node had `conformance` (do WE appear in bsky's appview?),
// `fronts` (whose firehose are we following?) and `diag` (are our cores conflicted?). All three reported
// health on 2026-08-05 while ashatron's copy of wj62 was five days stale, because none of them asks the
// INBOUND question. The drift was found by a hand audit, and then mis-diagnosed twice, purely because
// there was no verb for "compare me to the authority".
//
// THE THREE STATES, kept distinct because they have different causes and different repairs:
//   missingFromIndex     — the repo has it, we never indexed it        (ashatron's actual gap)
//   indexedWithoutBytes  — we indexed it, the bytes were refused/lost  (what repair-bytes fixes)
//   extraLocal           — we hold it, the repo does not               (a delete we never folded)
// Collapsing these into one number is how "140/140 have bytes" read as healthy on a node missing 26
// records outright.
//
// WHY getRepo AND NOT THE FIREHOSE. Boot already replays subscribeRepos(0) for a non-co-hosted DID and
// demonstrably did not recover these records. getRepo is one request carrying the signed commit and the
// whole MST: a single signature check covers every record, the set is complete by construction, and
// there is no cursor to be quietly parked at the wrong place. Measured 45,563 bytes for wj62.
//
// ⚠ `since` IS NOT USED HERE, DELIBERATELY. It used to be sent — and worked only because the membrane
// accepted and ignored it (measured 2026-08-06: byte-identical full CAR either way). Since atproto-bridge
// 0.9.45 the membrane HONOURS it and returns a genuine diff, which this node cannot apply: a partial CAR
// omits the unchanged MST nodes, so applying one needs a BLOCK store to union against and favela holds
// RECORDS. See createFetchRepo below for the full reasoning; it now refuses `since` loudly.
//
// TRUST. The verification key comes from the DID DOCUMENT, never from the host that served the CAR, for
// the reason record-fetch.js states: a key handed over by the same party as the data proves nothing.
import { readCar, loadCommit, listRecords, getBlock, verifyRepo } from 'atproto-repo/lib/repo.js'
import { verifyCommit } from 'atproto-repo/lib/commit.js'
import * as dagCbor from '@ipld/dag-cbor'
import b4a from 'b4a'

const splitKey = (key) => {
  const i = key.indexOf('/')
  return i > 0 ? { collection: key.slice(0, i), rkey: key.slice(i + 1) } : null
}

// ---- fetch ------------------------------------------------------------------------------------------

// Pull the authoritative repo CAR. Returns { carBytes, identity, partial } or null — fails soft like
// record-fetch.
//
// ⛔ FAVELA CANNOT CONSUME A PARTIAL CAR, AND MUST NOT ASK FOR ONE. As of atproto-bridge 0.9.45 the
// membrane HONOURS `since` and returns a real diff: the MST nodes that did not change are deliberately
// absent, so the tree cannot be walked from the root. Applying one requires a BLOCK store to union it
// with — and this node holds RECORDS, not blocks. There is nothing here to union against.
//
// Nor could a diff answer the question `diff` asks. `extraLocal` ("we hold it, the repo does not") is
// only meaningful against the COMPLETE record set; computed against a diff, every record older than
// `since` looks extra. Nothing would be deleted (spec §2 forbids it) but the report would cry wolf on
// every run, which is the failure mode that made the first per-view diff useless.
//
// So `since` is NOT sent. It was sent before — accepted and ignored by the membrane, which is why it
// appeared to work — and this is the silent regression the issue predicted, closed before it could
// happen rather than after. The parameter stays in the signature and is REFUSED loudly, because a
// caller that passes it is asking for something this cannot do and deserves to be told.
export function createFetchRepo ({ doFetch, resolveIdentity, timeoutMs = 60_000 } = {}) {
  if (typeof doFetch !== 'function') throw new Error('createFetchRepo requires doFetch')
  if (typeof resolveIdentity !== 'function') throw new Error('createFetchRepo requires resolveIdentity')
  return async function fetchRepo ({ did, since = null } = {}) {
    if (since) throw new Error('fetchRepo: `since` is not supported here — a partial CAR needs a block store to apply against, and this node holds records. See lib/repo-sync.js.')
    const identity = await resolveIdentity(did)
    if (identity === null) return null
    const url = `${identity.pds}/xrpc/com.atproto.sync.getRepo?did=${encodeURIComponent(did)}`
    try {
      const res = await doFetch(url, { method: 'GET', headers: { accept: 'application/vnd.ipld.car' }, timeout: timeoutMs })
      if (!res || res.ok === false) return null
      const buf = await res.arrayBuffer()
      const carBytes = new Uint8Array(buf)
      if (!carBytes.length) return null
      // Belt and braces: if a membrane ever hands us a partial CAR unasked, say so rather than letting
      // parseRepo report it as a malformed repo. The two are not the same problem and the fix differs.
      const partial = res.headers && typeof res.headers.get === 'function'
        ? res.headers.get('atproto-repo-partial') === 'true'
        : false
      return { carBytes, identity, partial }
    } catch {
      return null
    }
  }
}

// Head-only: the cheap staleness check. { rev, cid, active, status } or null.
export function createFetchHead ({ doFetch, resolveIdentity, timeoutMs = 20_000 } = {}) {
  if (typeof doFetch !== 'function') throw new Error('createFetchHead requires doFetch')
  if (typeof resolveIdentity !== 'function') throw new Error('createFetchHead requires resolveIdentity')
  return async function fetchHead (did) {
    const identity = await resolveIdentity(did)
    if (identity === null) return null
    const get = async (nsid, q) => {
      try {
        const res = await doFetch(`${identity.pds}/xrpc/${nsid}?${q}`, { method: 'GET', headers: { accept: 'application/json' }, timeout: timeoutMs })
        if (!res || res.ok === false) return null
        return await res.json()
      } catch { return null }
    }
    const q = `did=${encodeURIComponent(did)}`
    const [commit, status] = await Promise.all([
      get('com.atproto.sync.getLatestCommit', q),
      get('com.atproto.sync.getRepoStatus', q)
    ])
    if (!commit) return null
    return {
      pds: identity.pds,
      rev: commit.rev || null,
      cid: commit.cid || null,
      active: status ? status.active !== false : null,
      status: status ? (status.status || null) : null
    }
  }
}

// ---- parse + verify ---------------------------------------------------------------------------------

// Decode a repo CAR and prove it before a single byte is believed. Returns null when any proof fails —
// an unverifiable repo is not a repo, and silently degrading to "index what we got" is how a hostile or
// broken host would get to rewrite our copy.
export async function parseRepo ({ did, carBytes, pubkey, partial = false }) {
  // A PARTIAL CAR is not a broken one. Since atproto-bridge 0.9.45 a membrane can serve a genuine diff,
  // and its MST is incomplete BY DESIGN — so verifyRepo below would fail on a missing block and report
  // `malformed-repo`, sending whoever reads it hunting for corruption that is not there. Named as its own
  // refusal instead. We should never receive one (createFetchRepo does not ask), which is exactly why it
  // is worth catching: it would mean a membrane returned something nobody requested.
  if (partial) return { ok: false, reason: 'partial-car', rev: null }
  let car, commit
  try {
    car = await readCar(carBytes)
    commit = loadCommit(car)
  } catch {
    return null
  }
  const value = commit && commit.value
  if (!value) return null
  // 1. the commit is for the repo we asked about
  if (value.did !== did) return { ok: false, reason: 'did-mismatch', rev: value.rev || null }
  // 2. signed by the key from the DID DOCUMENT
  if (pubkey) {
    let sigOk = false
    try { sigOk = verifyCommit(value, pubkey) } catch { sigOk = false }
    if (!sigOk) return { ok: false, reason: 'bad-signature', rev: value.rev || null }
  }
  // 3. every block re-encodes to its own CID (the wholesale form of repair-bytes' round-trip guard)
  let fidelity
  try { fidelity = await verifyRepo(car) } catch (e) { return { ok: false, reason: 'malformed-repo', error: (e && e.message) || String(e) } }
  if (!fidelity.ok) return { ok: false, reason: 'block-cid-mismatch', mismatches: fidelity.mismatches.length }

  const records = []
  for (const r of listRecords(car)) {
    const parts = splitKey(r.key)
    if (!parts) continue
    let bytes = null
    try { bytes = getBlock(car, r.cid).bytes } catch { bytes = null }
    if (!bytes) continue
    records.push({ collection: parts.collection, rkey: parts.rkey, cid: String(r.cid), bytes, record: r.value })
  }
  return { ok: true, rev: value.rev || null, records, blocks: fidelity.blocks }
}

// ---- diff -------------------------------------------------------------------------------------------

// listRefs(did) -> async iterable { rkey, collection }; hasBytes(did, collection, rkey) -> boolean
//
// ⛔ COMPARE LIKE WITH LIKE. `listRefs` walks the appview's POST index, which by construction holds only
// POST_COLLECTIONS — likes, follows, reposts and the profile live in separate views it never yields. A
// first cut compared the FULL remote record set against that post-only index and so reported every like
// and follow as "missing from our index", permanently: applying them made no difference, because they
// were never going to appear in `_ref`. 19 of ashatron's 27 were this, and a diff that cries wolf on
// every run is worse than none.
//
// `tracksCollection` names what the local index can actually answer for. Everything else is counted and
// reported separately rather than silently dropped — "we cannot verify these here" is a real answer, and
// pretending they are missing or pretending they are fine are both worse.
// tracked        Map<collection, { bytes: boolean }> — the views that can answer, and whether this node
//                stores that collection's bytes at all (likes/follows/reposts/blocks: it does not)
// listRefsFor(did, collection) -> async iterable { rkey } from THAT collection's own view
// isIgnored(collection) -> deliberately not indexed, with a reason on file (spec §2.1)
export async function diffRepo ({ did, remote, tracked, listRefsFor, hasBytes, isIgnored = () => false }) {
  const trackedMap = tracked instanceof Map ? tracked : new Map(Object.entries(tracked || {}))
  const missingFromIndex = []
  const indexedWithoutBytes = []
  const extraLocal = []
  const perCollection = {}
  const ignoredByCollection = {}
  const unknownByCollection = {}

  // Group the authority's records by collection, and classify every one of them. A collection that is
  // neither tracked nor on the ignore list is UNKNOWN — a lexicon we have never classified, which
  // used to vanish through applyCommit's final `continue` without a word (spec §2).
  const remoteByCollection = new Map()
  for (const r of remote.records) {
    if (trackedMap.has(r.collection)) {
      if (!remoteByCollection.has(r.collection)) remoteByCollection.set(r.collection, new Map())
      remoteByCollection.get(r.collection).set(r.rkey, r)
    } else if (isIgnored(r.collection)) {
      ignoredByCollection[r.collection] = (ignoredByCollection[r.collection] || 0) + 1
    } else {
      unknownByCollection[r.collection] = (unknownByCollection[r.collection] || 0) + 1
    }
  }

  // Compare EVERY tracked collection, including ones the authority has none of — a collection we hold
  // records for and the repo does not is exactly the extraLocal case, and skipping empty remotes would
  // hide it.
  for (const [collection, meta] of trackedMap) {
    const remoteRk = remoteByCollection.get(collection) || new Map()
    const localRk = new Set()
    for await (const ref of listRefsFor(did, collection)) {
      if (!ref || !ref.rkey) continue
      localRk.add(ref.rkey)
      if (!remoteRk.has(ref.rkey)) { extraLocal.push({ collection, rkey: ref.rkey }); continue }
      // Only ask about bytes where this node is supposed to have them.
      if (meta && meta.bytes && !(await hasBytes(did, collection, ref.rkey))) {
        indexedWithoutBytes.push({ collection, rkey: ref.rkey })
      }
    }
    for (const rkey of remoteRk.keys()) if (!localRk.has(rkey)) missingFromIndex.push({ collection, rkey })
    if (remoteRk.size || localRk.size) perCollection[collection] = { authority: remoteRk.size, indexed: localRk.size }
  }

  const count = (o) => Object.values(o).reduce((a, b) => a + b, 0)
  return {
    did,
    remoteRev: remote.rev,
    remoteRecords: remote.records.length,
    perCollection,
    ignored: count(ignoredByCollection),
    ignoredByCollection,
    unknown: count(unknownByCollection),
    unknownByCollection,
    missingFromIndex,
    indexedWithoutBytes,
    extraLocal,
    inSync: missingFromIndex.length === 0 && indexedWithoutBytes.length === 0 && extraLocal.length === 0
  }
}

// ---- apply ------------------------------------------------------------------------------------------

// applyOps(did, ops)  -> index + author bytes through the appview's own gates (unindexed records)
// putBytes(did, collection, rkey, record) -> write bytes ONLY (already-indexed records, where the
//   appview's dedup gate would return before the write is retried)
//
// EXTRA-LOCAL RECORDS ARE NEVER DELETED HERE. A record we hold that the repo does not may be a genuine
// delete we failed to fold, or it may be a record the authority has not yet published — and this cannot
// tell the two apart. Deleting on that ambiguity is how the appview's straggler removal is suspected of
// having pruned the very records this exists to restore. Reported, never actioned.
export async function applyBackfill ({ did, remote, diff, applyOps, putBytes, write = false, limit = 0, onEvent = null }) {
  const emit = (ev, d) => { if (onEvent) onEvent(ev, d) }
  const byKey = new Map(remote.records.map((r) => [r.collection + '/' + r.rkey, r]))
  const report = { indexed: 0, bytesWritten: 0, reencodeRefused: 0, errors: 0, skippedExtraLocal: diff.extraLocal.length }
  let done = 0

  const guarded = (r) => {
    // Same guard as repair-bytes: the store re-encodes a decoded record, and what the commit signed was
    // the ORIGINAL bytes. If the round trip is not byte-identical, writing would persist bytes that no
    // longer match their CID.
    let value, re
    try { value = dagCbor.decode(r.bytes) } catch { return null }
    try { re = dagCbor.encode(value) } catch { return null }
    if (!b4a.equals(b4a.from(re), b4a.from(r.bytes))) return null
    return value
  }

  for (const item of diff.missingFromIndex) {
    if (limit && done >= limit) return report
    const r = byKey.get(item.collection + '/' + item.rkey)
    if (!r) continue
    const value = guarded(r)
    if (value == null) { report.reencodeRefused++; emit('reencode-refused', item); continue }
    done++
    if (!write) continue
    try {
      await applyOps(did, [{ action: 'create', collection: r.collection, rkey: r.rkey, record: value }])
      report.indexed++
      emit('indexed', item)
    } catch (e) { report.errors++; emit('index-failed', { ...item, error: (e && e.message) || String(e) }) }
  }

  for (const item of diff.indexedWithoutBytes) {
    if (limit && done >= limit) return report
    const r = byKey.get(item.collection + '/' + item.rkey)
    if (!r) continue
    const value = guarded(r)
    if (value == null) { report.reencodeRefused++; emit('reencode-refused', item); continue }
    done++
    if (!write) continue
    try {
      await putBytes(did, r.collection, r.rkey, value)
      report.bytesWritten++
      emit('bytes-written', item)
    } catch (e) { report.errors++; emit('write-failed', { ...item, error: (e && e.message) || String(e) }) }
  }

  return report
}
// retention.js — the last three hooks of DESIGN §7.6: retain, knownRev, evict. Plus the byte budget.
//
// WHAT THIS OWNS. Everything downstream of verification: writing a verified foreign record to disk,
// folding it into the appview so it renders, remembering enough to answer the skip-test, and enforcing
// the Tier-B budget by evicting least-recently-used records. §7.6 specifies all of this; until now none
// of it existed.
//
// FOREIGN RECORDS ARE FILES, NOT CORES. A retained bsky account costs a directory under an
// OverlayRepoStore, not a Hypercore (hyper-proto-peer/lib/device-node.js:221 uses the same store for
// its own repo). That is what makes "one hop from our records" affordable — 500 followed accounts are
// 500 directories, not 500 cores with RocksDB overhead each.
//
// THE RETENTION INDEX IS BOOKKEEPING, NOT AUTHORITY — and §7.5's invariant is the reason this is safe.
// It records { rev, size, lastSeen } per retained record and gates exactly two things: the skip-test and
// eviction order. Both are CACHE MANAGEMENT. It never gates a write, a signature, or a serve decision:
// lose the whole index and the system is still correct, merely slower (every pointer re-fetches, and
// eviction restarts from a clean slate). That is the test §7.5 demands, and this passes it.
//
// ⛔ BYTE-EXACTNESS IS GUARDED, NOT ASSUMED. OverlayRepoStore.put() takes a DECODED record and
// re-encodes it (`dagCbor.encode(record)`), but what we verified was the ORIGINAL bytes and their CID.
// DAG-CBOR is deterministic so a canonical record round-trips identically — but "should" is not a
// fidelity argument, and §13's whole point is that an encoding divergence federates as corruption
// rather than failing loudly. So we re-encode, re-CID, and REFUSE to retain on any mismatch. A record
// we cannot store byte-exactly is one we decline to hold, not one we quietly mangle.
//
// PURE + INJECTED. The store opener, the appview, the index and the clock are all parameters, so the
// tiering, the skip-test, the budget and the eviction order are testable with no Corestore and no disk.

import * as dagCbor from '@ipld/dag-cbor'
import { cidForBytesSync } from 'atproto-repo/lib/cid.js'
import { isLossySubset } from './appview.js'

// Index key for one retained foreign record.
export function retentionKey ({ did, collection, rkey }) {
  return `${did}/${collection}/${rkey}`
}

// An in-memory retention index. Production wraps a Hyperbee (see createBeeIndex below); this is the
// reference implementation and what the tests drive.
export function createMemoryIndex () {
  const m = new Map()
  return {
    async get (k) { return m.get(k) || null },
    async put (k, v) { m.set(k, v) },
    async del (k) { return m.delete(k) },
    async * entries () { for (const [k, v] of m) yield { key: k, value: v } },
    get size () { return m.size }
  }
}

// A Hyperbee-backed retention index. `bee` should be a sub() dedicated to retention so it never
// collides with the appview's own namespaces (Hyperbee subs do not dedup — see the
// reference_hyperbee-subs-no-alwaysduplicate note; alwaysDuplicate:false belongs on the ROOT bee).
export function createBeeIndex (bee) {
  return {
    async get (k) { const n = await bee.get(k); return n ? n.value : null },
    async put (k, v) { await bee.put(k, v) },
    async del (k) { await bee.del(k); return true },
    async * entries () { for await (const n of bee.createReadStream()) yield { key: n.key.toString(), value: n.value } }
  }
}

export function createRetentionHooks ({
  openStore, // async (did) -> OverlayRepoStore (ready)
  appview = null, // optional: something with applyCommit(did, ops)
  index, // a retention index (memory or bee)
  budgetBytes = null, // §7.6 Tier-B byte budget; null = unbounded (caller accepts the risk)
  // ⛔ Is this DID one hpp AUTHORS for? §7.6 scopes retention to FOREIGN records, and I did not enforce
  // that — so Constellation, which reports ANY record linking to our subjects INCLUDING our own replies
  // to our own posts, fed our own records back through this pipeline. They were re-encoded over hpp's
  // canonical files, dropped `langs`, and wedged the forward-only sign gate: two of wj62's replies never
  // federated. Default is "everything is foreign" so an unconfigured caller cannot silently clobber.
  isForeign = () => true,
  now = () => Date.now(),
  onEvent = null // (event, detail) -> void, for observability
} = {}) {
  if (typeof openStore !== 'function') throw new Error('createRetentionHooks requires openStore')
  if (!index) throw new Error('createRetentionHooks requires an index')

  const stats = { retained: 0, reencodeRefused: 0, lossyRefused: 0, skippedOwn: 0, evicted: 0, evictedForBudget: 0, bytes: 0, storeErrors: 0 }
  const emit = (ev, detail) => { if (onEvent) onEvent(ev, detail) }

  // Recompute the live byte total from the index. Cheap enough at Tier-B scale and avoids a counter
  // drifting out of sync with reality across restarts.
  async function totalBytes () {
    let sum = 0
    for await (const { value } of index.entries()) sum += (value && value.size) || 0
    return sum
  }

  // ---- knownRev -----------------------------------------------------------------------------------
  // Per-RECORD, deliberately not per-repo. Tier B is a partial cache: we hold some records of a foreign
  // repo, never all of them, so a repo-level head would claim a completeness we do not have.
  async function knownRev (pointer) {
    const entry = await index.get(retentionKey(pointer))
    return entry && typeof entry.rev === 'string' ? entry.rev : null
  }

  // ---- retainRecord -------------------------------------------------------------------------------
  async function retainRecord (record, pointer) {
    if (!record || !record.bytes) return false

    // NEVER write into a repo hpp authors. hpp is the authority for those records: PointerSubstrate
    // hashes the bytes IT writes and commits that hash to the autobase, so any differing re-encode by a
    // second writer invalidates a converged pointer and the signer can no longer resolve it.
    if (!isForeign(pointer.did)) {
      stats.skippedOwn++
      emit('skipped-own-did', { pointer })
      return false
    }

    // Decode once, then prove the round-trip before writing anything.
    let value
    try {
      value = dagCbor.decode(record.bytes)
    } catch {
      stats.reencodeRefused++
      emit('decode-failed', { pointer })
      return false
    }

    const reencoded = dagCbor.encode(value)
    if (cidForBytesSync(reencoded).toString() !== record.recordCid.toString()) {
      // The store would persist bytes that no longer match the CID we verified. Refuse loudly.
      stats.reencodeRefused++
      emit('reencode-mismatch', { pointer, cid: record.recordCid.toString() })
      return false
    }

    let store
    try {
      store = await openStore(pointer.did)
      // NO LOSSY OVERWRITE — the same rule appview.putPost adopted in 0.2.50, which this path bypassed.
      // The byte-exactness guard above only proves our re-encode matches the bytes we FETCHED; it says
      // nothing about what is already on disk, which is the only comparison that matters when another
      // writer owns the file. Refuse only a strict subset: a changed value or an added field still
      // writes (freezing at first-seen version is its own bug), dropping a field is refused.
      const existing = await store.getRaw(pointer.collection, pointer.rkey)
      if (existing != null && isLossySubset(value, existing.record)) {
        stats.lossyRefused++
        emit('lossy-refused', {
          pointer,
          oursBytes: reencoded.length,
          canonicalBytes: existing.bytes.length
        })
        return false
      }
      await store.put(pointer.collection, pointer.rkey, value)
    } catch (err) {
      stats.storeErrors++
      emit('store-failed', { pointer, error: (err && err.message) || String(err) })
      return false
    }

    // Fold into the appview so the record actually renders. Synthesised as a commit op because that is
    // the shape the existing ingest path already understands — no second indexing route.
    if (appview) {
      try {
        await appview.applyCommit(pointer.did, [{
          collection: pointer.collection,
          rkey: pointer.rkey,
          action: 'create',
          record: value
        }])
      } catch (err) {
        // The bytes are already safely on disk; a failed index fold is a render gap, not data loss, and
        // a re-index will heal it. Never unwind the write for it.
        emit('index-failed', { pointer, error: (err && err.message) || String(err) })
      }
    }

    const size = reencoded.length
    const prev = await index.get(retentionKey(pointer))
    await index.put(retentionKey(pointer), {
      did: pointer.did,
      collection: pointer.collection,
      rkey: pointer.rkey,
      // A backfilled pointer carries rev: null (Constellation does not report it). Keep any rev we
      // already had rather than downgrading to null, or the skip-test would forget known state.
      rev: pointer.rev || (prev && prev.rev) || null,
      size,
      retainedAt: prev ? prev.retainedAt : now(),
      lastSeen: now()
    })

    stats.retained++
    stats.bytes = await totalBytes()
    emit('retained', { pointer, size })

    if (budgetBytes !== null) await enforceBudget()
    return true
  }

  // ---- evictRecord --------------------------------------------------------------------------------
  // Always safe: the authoritative copy lives in the author's PDS and is re-fetchable. That asymmetry
  // is what makes §7.6 a budgeting problem rather than a correctness one.
  async function evictRecord (pointer) {
    const key = retentionKey(pointer)
    const entry = await index.get(key)

    try {
      const store = await openStore(pointer.did)
      await store.del(pointer.collection, pointer.rkey)
    } catch (err) {
      // Fall through: drop the index entry regardless, so a store that has already lost the file does
      // not leave a permanently un-evictable row inflating the budget.
      stats.storeErrors++
      emit('evict-store-failed', { pointer, error: (err && err.message) || String(err) })
    }

    if (appview) {
      try {
        await appview.applyCommit(pointer.did, [{
          collection: pointer.collection,
          rkey: pointer.rkey,
          action: 'delete'
        }])
      } catch (err) {
        emit('index-failed', { pointer, error: (err && err.message) || String(err) })
      }
    }

    await index.del(key)
    if (entry) {
      stats.evicted++
      stats.bytes = await totalBytes()
    }
    emit('evicted', { pointer })
    return true
  }

  // ---- the §7.6 byte budget -----------------------------------------------------------------------
  // LRU by lastSeen. Evicting past the budget cannot break correctness — a Tier-B miss degrades to a
  // lens-import fetch, which already fails soft — so this is allowed to be aggressive.
  async function enforceBudget () {
    if (budgetBytes === null) return 0
    let total = await totalBytes()
    if (total <= budgetBytes) return 0

    const all = []
    for await (const { value } of index.entries()) if (value) all.push(value)
    all.sort((a, b) => (a.lastSeen || 0) - (b.lastSeen || 0)) // oldest touch first

    let evicted = 0
    for (const entry of all) {
      if (total <= budgetBytes) break
      await evictRecord({ did: entry.did, collection: entry.collection, rkey: entry.rkey })
      total -= entry.size || 0
      evicted++
      stats.evictedForBudget++
    }
    if (evicted > 0) emit('budget-enforced', { evicted, budgetBytes, total })
    stats.bytes = total
    return evicted
  }

  // Mark a record as freshly used, so LRU reflects RENDER activity and not merely write order. The
  // caller should call this when a retained record is actually served.
  async function touch (pointer) {
    const key = retentionKey(pointer)
    const entry = await index.get(key)
    if (!entry) return false
    entry.lastSeen = now()
    await index.put(key, entry)
    return true
  }

  return { retainRecord, knownRev, evictRecord, enforceBudget, touch, totalBytes, stats }
}
// favela roster resolver — turn an atproto LIST into a set of member DIDs.
//
// A community roster is an `app.bsky.graph.list` record in the OWNER's repo; membership is one
// `app.bsky.graph.listitem` record per member (subject = member DID, list = the list's AT-URI). favela
// reads the owner's listitems over P2P (a DidPeer) and collects the subjects — the SAME read path it
// already uses for posts, just a different collection. No new substrate: a list is just records.
// Shapes verified against bluesky-social/atproto (list: name/purpose/createdAt + optional; listitem:
// subject:did / list:at-uri / createdAt).
//
// This is the roster analog of the post scope (scopes.js): an `app.bsky.graph.list` is bsky-visible;
// a favela-only community would use a `net.favela.*` list NSID with the SAME listitem semantics — the
// resolver is collection-parameterized so that variant is a one-line addition later.

export const LIST_COLLECTION = 'app.bsky.graph.list'
export const LISTITEM_COLLECTION = 'app.bsky.graph.listitem'

const LIST_URI_RE = /^at:\/\/([^/]+)\/app\.bsky\.graph\.list\/([^/]+)$/

// Parse an app.bsky.graph.list AT-URI -> { owner, rkey, uri }. Throws on a non-list URI.
export function parseListUri (uri) {
  const m = LIST_URI_RE.exec(String(uri || ''))
  if (!m) throw new Error(`not an app.bsky.graph.list AT-URI: ${uri}`)
  return { owner: m[1], rkey: m[2], uri: String(uri) }
}

// Resolve a roster from a list. `ownerPeer` = anything exposing getRecord(collection, rkey) and
// listRecords(collection) (a DidPeer) for the list OWNER. Returns { uri, owner, name, purpose, members }
// where members is the deduped list of subject DIDs. Only listitems whose `.list` equals THIS list URI
// count (an owner can host many lists in one repo); duplicate subjects are ignored (as the AppView does).
export async function resolveRoster (ownerPeer, listUri) {
  const { owner, rkey, uri } = parseListUri(listUri)
  const listRec = await ownerPeer.getRecord(LIST_COLLECTION, rkey)
  const meta = listRec && listRec.value ? listRec.value : null
  // ⛔ `listRecords` RETURNS { records, cursor }, NOT AN ARRAY (atproto-did-peer 0.2.10, per the
  // com.atproto.repo.listRecords lexicon). This read `for (const it of items)` against the wrapper and
  // threw `items is not iterable` — community rosters simply stopped resolving. Accept both shapes so a
  // caller passing an older peer, or a plain array in a test, still works.
  const listed = await ownerPeer.listRecords(LISTITEM_COLLECTION)
  const items = Array.isArray(listed) ? listed : ((listed && listed.records) || [])
  const members = []
  const seen = new Set()
  for (const it of items) {
    const rec = it && it.value ? it.value : null
    if (!rec || rec.list !== uri || !rec.subject) continue
    if (seen.has(rec.subject)) continue
    seen.add(rec.subject)
    members.push(rec.subject)
  }
  return { uri, owner, name: meta ? meta.name : null, purpose: meta ? meta.purpose : null, members }
}
// favela post SCOPES — the POSSE scope selector (DESIGN §3), the single source of truth shared by the
// Writer (what collection to sign into), the Appview (what collections to fold), and the web shell
// (the compose toggle). Keeping the scope->collection map in ONE place is what makes "local-only" a
// pure data decision instead of three stringly-typed constants drifting apart.
//
// The whole mechanism of step 1: a post's atproto `$type` MUST equal its collection NSID, and bsky's
// AppView only indexes `app.bsky.*` lexicons. So a record in `net.favela.local.post` is still signed by
// the hpp into the DID's repo and rides the firehose — but bsky silently ignores it (unknown lexicon),
// while favela folds it into the local timeline. No bridge change is needed; "local-only" falls out of
// which collection we write + which collections favela indexes.
//
// HONESTY (DESIGN §10.2): local-only means UNINDEXED BY BSKY, not UNREPLICATED. If the DID is fronted +
// crawled, the record BYTES still reach bsky's relay; they just never render there. It is "community,
// not secret" until encryption lands — surface that in the UI, never promise erasure.

// scope -> the atproto collection NSID (== the record `$type`) it writes into.
export const SCOPE_COLLECTION = {
  public: 'app.bsky.feed.post', // fronted to bsky by the bridge (POSSE syndicate arm)
  local: 'net.favela.local.post' // favela-only; bridge never projects it (not app.bsky.*)
}

export const DEFAULT_SCOPE = 'public'

// Every collection favela's appview folds into the timeline (both scopes render locally).
export const POST_COLLECTIONS = Object.values(SCOPE_COLLECTION)

// scope name -> collection NSID; throws on an unknown scope (fail loud, no silent public fallback).
export function collectionForScope (scope = DEFAULT_SCOPE) {
  const c = SCOPE_COLLECTION[scope]
  if (!c) throw new Error(`unknown scope '${scope}' (expected one of: ${Object.keys(SCOPE_COLLECTION).join(', ')})`)
  return c
}

// Reverse map: a record's collection/$type -> its scope name (for render badges). Unknown -> null.
export function scopeForCollection (collection) {
  for (const [scope, nsid] of Object.entries(SCOPE_COLLECTION)) if (nsid === collection) return scope
  return null
}
// search — matching and ranking, kept PURE so the behaviour is testable with no index and no network.
//
// ⚠ WHAT THIS IS NOT. There is no inverted index here. favela's appview holds a few thousand records at
// most, so search is a SCAN over the existing subs with these predicates applied. That is an honest
// trade at this size and a bad one at a hundred thousand records — when the scan gets slow the fix is a
// real term index, not a faster scan. Stated here so the next reader does not mistake "it works" for
// "it scales".
//
// Matching rules, chosen to behave the way people expect rather than the way a regex is easiest:
//   - case- and accent-insensitive, so "cafe" finds "Café"
//   - ALL terms must appear (AND, not OR) — an OR search over a small corpus returns everything
//   - a quoted "phrase" must appear contiguously
//   - terms match on a word BOUNDARY, so "art" does not match "start" — substring matching on short
//     terms is the single fastest way to make a search feel broken

// Strip diacritics and case. NFD splits a letter from its accent, then the combining marks are dropped.
export function fold (s) {
  return String(s == null ? '' : s).normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase()
}

// A query -> { terms: string[], phrases: string[] }. Quoted runs become phrases; the rest split on
// whitespace. Empty/garbage yields empty arrays rather than throwing, so a stray quote cannot 500 a page.
export function parseQuery (q) {
  const raw = String(q == null ? '' : q).trim()
  if (!raw) return { terms: [], phrases: [] }
  const phrases = []
  const rest = raw.replace(/"([^"]+)"/g, (_, p) => { phrases.push(fold(p).trim()); return ' ' })
  const terms = fold(rest).split(/\s+/).map((t) => t.trim()).filter(Boolean)
  return { terms, phrases: phrases.filter(Boolean) }
}

const boundary = (hay, needle) => {
  if (!needle) return false
  let i = hay.indexOf(needle)
  while (i !== -1) {
    const before = i === 0 || !/[\p{L}\p{N}]/u.test(hay[i - 1])
    if (before) return true // start-of-word is enough: "art" matches "artist", not "start"
    i = hay.indexOf(needle, i + 1)
  }
  return false
}

// Does `text` satisfy the query? ALL terms and ALL phrases must be present.
export function matches (text, { terms, phrases }) {
  if (!terms.length && !phrases.length) return false
  const hay = fold(text)
  for (const p of phrases) if (!hay.includes(p)) return false
  for (const t of terms) if (!boundary(hay, t)) return false
  return true
}

// A small relevance score, so an exact-ish hit outranks an incidental one. Deliberately simple: term
// frequency, with a bonus for a phrase hit and for matching near the start. Recency is applied by the
// caller (the index is already time-ordered), so this stays a pure function of the text.
export function score (text, { terms, phrases }) {
  const hay = fold(text)
  let s = 0
  for (const p of phrases) { if (hay.includes(p)) s += 5 + (hay.indexOf(p) === 0 ? 2 : 0) }
  for (const t of terms) {
    let i = hay.indexOf(t); let n = 0
    while (i !== -1) { n++; i = hay.indexOf(t, i + 1) }
    if (n) s += Math.min(n, 3) + (hay.indexOf(t) === 0 ? 1 : 0)
  }
  return s
}

// The text of a post that search should see: the post text plus any image ALT text. Alt is included on
// purpose — someone who wrote "a photo of the harbour at dusk" has described a post that the post text
// itself may not describe at all, and excluding it makes those posts unfindable.
export function postText (record) {
  if (!record) return ''
  const parts = [record.text || '']
  const e = record.embed
  const imgs = e && e.$type === 'app.bsky.embed.images' ? e.images
    : (e && e.$type === 'app.bsky.embed.recordWithMedia' && e.media && e.media.$type === 'app.bsky.embed.images' ? e.media.images : null)
  for (const im of imgs || []) if (im && im.alt) parts.push(im.alt)
  if (e && e.$type === 'app.bsky.embed.external' && e.external) parts.push(e.external.title || '', e.external.description || '')
  return parts.filter(Boolean).join(' ')
}

// The text an ACTOR is searchable by. The DID is included so pasting one finds the person, which is a
// real thing operators do; the handle and display name are the ordinary paths.
export function actorText (did, profile) {
  return [did || '', (profile && profile.displayName) || '', (profile && profile.handle) || '', (profile && profile.description) || ''].filter(Boolean).join(' ')
}
// In-memory session store with sliding renewal.
//
// PORTED from pear-git-v3 `lib/auth/sessions.js` (the flagship public-web p2p app). favela had the
// same need and a weaker answer: a bare `Map` inside FavelaAuth with a FIXED expiry, no renewal and
// no sweeper — so an abandoned session sat in memory until the process died, and an ACTIVE user was
// logged out the instant the fixed window elapsed.
//
// One deliberate difference from pgv3: it stores a bare `publicKey`; favela's identity is a PAIR —
// the DID (the account) and the browser sub-key delegated to it (the device) — so the payload is a
// whole identity object. Both are needed downstream: the DID for authorisation, the sub-key for the
// revocation check.
//
// NOT persisted across restarts, and that is correct rather than lazy: the browser keeps its sub-key
// AND its delegation in localStorage (`/api/auth/pair` returns the delegation for exactly this
// reason), so re-authentication after a restart is silent. Persisting bearer tokens would add a
// durable secret store to a process whose whole design point is that it holds no keys.

import crypto from 'hypercore-crypto'
import b4a from 'b4a'

// 30 days — favela's existing SESSION_TTL_MS. pgv3 uses 24h; keeping favela's value means this port
// changes session LIFETIME for nobody, only how it is renewed and reclaimed.
export const DEFAULT_TTL = 30 * 24 * 60 * 60 * 1000
export const DEFAULT_CLEANUP = 60 * 1000 // 1 min

export class SessionStore {
  constructor (opts = {}) {
    this._ttl = opts.ttl || DEFAULT_TTL
    this._sessions = new Map() // token → { identity, expiresAt }
    this._cleanupInterval = setInterval(() => this._cleanup(), opts.cleanupInterval || DEFAULT_CLEANUP)
    // Unref'd: a session sweeper must never be the reason a process stays alive.
    if (this._cleanupInterval.unref) this._cleanupInterval.unref()
  }

  /**
   * Mint a fresh session. Returns the bearer token (64-char hex).
   * @param {object} identity - e.g. { did, subKey }
   */
  create (identity) {
    const token = b4a.toString(crypto.randomBytes(32), 'hex')
    this._sessions.set(token, { identity, expiresAt: Date.now() + this._ttl })
    return token
  }

  /**
   * Look up a session. Slides the expiry forward on every hit, so an active user stays signed in and
   * only genuine IDLE time expires them.
   * @returns {{ identity: object, expiresAt: number } | null}
   */
  get (token) {
    if (!token) return null
    const entry = this._sessions.get(token)
    if (!entry) return null
    if (entry.expiresAt < Date.now()) {
      this._sessions.delete(token)
      return null
    }
    entry.expiresAt = Date.now() + this._ttl
    return entry
  }

  /** Revoke a session. True if it existed. */
  revoke (token) {
    if (!token) return false
    return this._sessions.delete(token)
  }

  /** Number of sessions held (including any not yet swept). */
  get size () {
    return this._sessions.size
  }

  /**
   * Diagnostics only. The token IS the credential, so the listing carries a short PREFIX — enough to
   * correlate with a log line, useless to replay — never the token itself.
   */
  list () {
    const now = Date.now()
    const out = []
    for (const [token, entry] of this._sessions) {
      if (entry.expiresAt < now) continue
      out.push({
        tokenPrefix: token.slice(0, 8),
        did: entry.identity && entry.identity.did ? entry.identity.did : null,
        expiresAt: entry.expiresAt
      })
    }
    return out
  }

  _cleanup () {
    const now = Date.now()
    for (const [token, entry] of this._sessions) {
      if (entry.expiresAt < now) this._sessions.delete(token)
    }
  }

  /** Stop the sweeper and drop every session. */
  close () {
    if (this._cleanupInterval) {
      clearInterval(this._cleanupInterval)
      this._cleanupInterval = null
    }
    this._sessions.clear()
  }
}

export default SessionStore
// pgh-sidecar registration — makes the daemon a first-class pgh app. Registering our UDS
// with the sidecar lets `app-lookup` resolve us (so `pgh app status atproto-bridge` and the
// readiness probe work) and survives the boot race (sidecar socket may appear after us).
// Mirrors pear-git-v3/lib/sidecar-wait.js + server.js registerWithSidecar.

// ⚠ BARE-NATIVE IMPORTS. Copied from atproto-bridge, which resolves `#node:*` through an "imports" map
// in its package.json — favela-web has none, so those specifiers throw PACKAGE_IMPORT_NOT_DEFINED. The
// failure is INVISIBLE because the caller treats a missing control surface as non-fatal, so the daemon
// boots normally and simply never registers. Exactly the same trap was hit in hyper-proto-peer 0.3.102.
import fs from 'bare-fs'
import path from 'bare-path'
import os from 'bare-os'
import process from 'bare-process'

export function sidecarSockPath () {
  return process.env.PGH_SIDECAR_SOCK || path.join(os.homedir(), '.pgh', 'svc.sock')
}

// Poll for the sidecar socket (it may be created after this daemon boots — the boot race).
export async function waitForSidecarSock ({ timeoutMs = 120000, intervalMs = 1000, shouldStop = () => false } = {}) {
  const sock = sidecarSockPath()
  const deadline = Date.now() + timeoutMs
  while (!fs.existsSync(sock)) {
    if (shouldStop()) return false
    if (Date.now() >= deadline) return false
    await new Promise((r) => setTimeout(r, intervalMs))
  }
  return true
}

// app-register (last-writer-wins, idempotent) our live UDS + pid with the sidecar.
export async function registerWithSidecar ({ udsPath, name, runtime = 'bare', version = null }) {
  const sidecarSock = sidecarSockPath()
  if (!fs.existsSync(sidecarSock)) return { registered: false, reason: 'sidecar not running' }
  const installName = name || process.env.PGH_APP_NAME || 'atproto-bridge'
  try {
    const { Client } = await import('hyper-svc')
    const c = await Client.connectUds(sidecarSock)
    await c.call('app-register', { name: installName, udsPath, pid: process.pid, runtime, version })
    await c.close()
    return { registered: true, name: installName }
  } catch (err) {
    return { registered: false, reason: err.message }
  }
}

// Register once the sidecar is up, then re-register on an interval (the sidecar keeps its
// registry in memory, so a sidecar restart silently drops us). Returns a stop() fn.
export function maintainSidecarRegistration ({ udsPath, name, runtime, version, intervalMs = 30000 } = {}) {
  let timer = null
  let stopped = false
  ;(async () => {
    const ready = await waitForSidecarSock({ shouldStop: () => stopped })
    if (stopped) return
    if (ready) await registerWithSidecar({ udsPath, name, runtime, version })
    timer = setInterval(() => { registerWithSidecar({ udsPath, name, runtime, version }) }, intervalMs)
    if (timer.unref) timer.unref()
  })()
  return () => { stopped = true; if (timer) clearInterval(timer) }
}
// spacedust-socket.js — the Bare-only half of the spacedust client.
//
// This file exists so `spacedust.js` can stay runtime-agnostic and unit-testable under plain Node.
// `bare-ws` transitively pulls native addons (bare-dns), so any module that imports it is Bare-only.
// Keeping that import here means the protocol logic — URL building, event parsing, filter framing,
// queue behaviour — is testable with `node`, and only the socket itself needs `bare`.
//
// bare-ws details that matter and were verified against its source:
//   - `new Socket(url)` accepts a URL string and derives host/path/port/secure from it, so `wss://`
//     with a query string works (lib/socket.js:18-21, :77 routes through bare-https).
//   - It auto-replies PONG with the ECHOED payload on PING (lib/socket.js:163-165), which is exactly
//     what spacedust's 30s keepalive verifies. Nothing to implement.
//   - It is a non-objectMode Duplex that pushes one Buffer per message (:195), so messages arrive as
//     'data' events — see the framing note in spacedust.js.

import bareWs from 'bare-ws'
import { USER_AGENT } from './spacedust.js'

// The production socket factory. Pass as `createSocket` to SpacedustClient.
export function createBareSocket (url) {
  return new bareWs.Socket(url, { headers: { 'User-Agent': USER_AGENT } })
}
// spacedust.js — live inbound link subscription. The transport for DESIGN §7.6's inbound arm.
//
// WHAT IT IS. Spacedust (microcosm.blue) watches the global firehose, extracts every LINK it sees, and
// re-emits them over a filtered WebSocket. We subscribe with our roster's DIDs as the subjects, so we
// receive exactly the interactions that touch our own content — replies, quotes, likes, follows — and
// nothing else. This is NOT the firehose: the filtering happens server-side, and the caps (10k subject
// DIDs, 1k sources) are far above what a community needs.
//
// WHAT IT IS NOT. It does not fetch, verify, or store anything. Spacedust deliberately ships only a
// LOCATOR — `{did, collection, rkey}` reconstructed from `source_record`, plus the subject it points at.
// Their own source says so ("include the record too? ... no, not for now"), and that is the right call:
// an unsigned record from a third-party index is not something we retain. This module emits pointers;
// §7.6's pipeline (resolveMiniDoc -> getRecord -> verify -> OverlayRepoStore) turns them into data.
//
// THE 21-SECOND BUFFER IS LOAD-BEARING — LEAVE IT ON. By default spacedust holds every link for 21s
// before emitting, so interactions that are undone almost immediately never reach us (~<1% of links are
// deleted within 21s). That is precisely what Tier B wants: we should never spend a fetch+verify+write
// on a reply that was deleted two seconds later. `instant: true` bypasses it and is for UIs that want
// noise, not for a retention pipeline.
//
// BACKPRESSURE IS THE REAL HAZARD, AND IT IS ARCHITECTURAL. Spacedust DROPS a subscriber that lags
// (`RecvError::Lagged` -> cancel). If we did fetch/verify/store work inside the socket handler we would
// block the Bare event loop and be disconnected — the same failure class as pgv3's `reconcileAll` and
// pgh-sidecar's `spawnSync`. So the handler does one thing: parse and enqueue. All work happens in a
// drain loop. If the queue fills we drop the OLDEST pointer and count it, because a dropped pointer is
// recoverable (Constellation can backfill the same link by subject+source) while a lag-disconnect loses
// the entire stream until reconnect. Trading a recoverable loss for an unrecoverable one is the whole
// point of the bound.
//
// PURE + INJECTED. `createSocket` and `now` are parameters, so the URL building, event parsing, filter
// framing and queue behaviour are all unit-testable with no network and no clock.
//
// NO RUNTIME-SPECIFIC IMPORTS HERE — deliberately. `bare-ws` pulls native addons (bare-dns) that cannot
// load under Node, so importing it at the top of this file would make the whole module Bare-only and the
// "pure + injected" claim above a fiction. The real socket factory lives in `spacedust-socket.js`;
// `createSocket` is therefore REQUIRED, and tests inject a fake.

export const DEFAULT_ENDPOINT = 'wss://spacedust.microcosm.blue/subscribe'

// They instrument by user-agent and ask consumers to identify themselves.
export const USER_AGENT = 'favela-web (+https://github.com/favela)'

// Link sources are `<collection NSID>:<record property path>` with NO leading dot — spacedust strips it
// (`link.path.strip_prefix('.')`). These are the inbound interactions Tier B/C care about.
//
// VERIFIED against live traffic 2026-07-31 via Constellation's link enumeration on a post with 426
// quotes: `.embed.record.uri` 376 + `.embed.record.record.uri` 50 = 426 exactly. BOTH quote paths are
// real — plain quote vs recordWithMedia — so subscribing to only the first silently missed ~12% of
// quotes. Reply paths confirmed the same way (.reply.parent.uri / .reply.root.uri).
export const SOURCES = {
  REPLY_PARENT: 'app.bsky.feed.post:reply.parent.uri',
  REPLY_ROOT: 'app.bsky.feed.post:reply.root.uri',
  QUOTE: 'app.bsky.feed.post:embed.record.uri',
  QUOTE_MEDIA: 'app.bsky.feed.post:embed.record.record.uri', // recordWithMedia — a DIFFERENT path
  LIKE: 'app.bsky.feed.like:subject.uri',
  REPOST: 'app.bsky.feed.repost:subject.uri',
  FOLLOW: 'app.bsky.graph.follow:subject'
}

// Content-bearing sources (Tier B — worth a fetch+verify+retain) vs count-bearing (Tier C — reference
// only, answered on demand by Constellation's getBacklinksCount). §7.6's pressure valve lives here: a
// post with 50k likes must not become 50k retained records.
export const CONTENT_BEARING = new Set([
  SOURCES.REPLY_PARENT, SOURCES.REPLY_ROOT, SOURCES.QUOTE, SOURCES.QUOTE_MEDIA
])

const DEFAULTS = {
  endpoint: DEFAULT_ENDPOINT,
  instant: false, // see the 21-second note above — do not flip this for a retention pipeline
  maxQueue: 1000,
  reconnectMinMs: 1000,
  reconnectMaxMs: 60_000
}

// Build the subscribe URL. Params are camelCase and REPEAT rather than comma-separating:
// `wantedSubjectDids=a&wantedSubjectDids=b`. Server-side caps are 50k subjects / 100 prefixes /
// 10k subject DIDs / 1k sources; we do not enforce them here (the server rejects, loudly).
export function buildSubscribeUrl (filter = {}, { endpoint = DEFAULT_ENDPOINT, instant = false } = {}) {
  const url = new URL(endpoint)
  const add = (name, values) => {
    for (const v of values || []) url.searchParams.append(name, v)
  }
  add('wantedSubjectDids', filter.subjectDids)
  add('wantedSubjects', filter.subjects)
  add('wantedSubjectPrefixes', filter.subjectPrefixes)
  add('wantedSources', filter.sources)
  if (instant) url.searchParams.set('instant', 'true')
  return url.toString()
}

// The runtime filter-update frame. Sent as a TEXT frame over the SAME socket — no reconnect, which is
// what lets a mutating roster stay live. Note the shape asymmetry: the envelope is snake_case-tagged
// (serde `tag="type", content="payload"`) while the payload is camelCase. It REPLACES the whole query
// (`*self = opts`), so always send the complete filter, never a delta.
export function optionsUpdateFrame (filter = {}) {
  return JSON.stringify({
    type: 'options_update',
    payload: {
      wantedSubjectDids: filter.subjectDids || [],
      wantedSubjects: filter.subjects || [],
      wantedSubjectPrefixes: filter.subjectPrefixes || [],
      wantedSources: filter.sources || []
    }
  })
}

// Split an at-uri into a record locator. Returns null on anything that is not `at://<did>/<nsid>/<rkey>`
// — a plain URL subject, or a bare DID, is legitimate and simply is not a record.
export function parseAtUri (uri) {
  if (typeof uri !== 'string' || !uri.startsWith('at://')) return null
  const parts = uri.slice(5).split('/')
  if (parts.length !== 3) return null
  const [did, collection, rkey] = parts
  if (!did || !collection || !rkey) return null
  return { did, collection, rkey }
}

// Parse one link event into a normalized POINTER. Returns null for anything unexpected rather than
// throwing — a malformed frame must never take down the subscription.
//
// Wire shape (spacedust/src/lib.rs ClientEvent/ClientLinkEvent):
//   { kind:"link", origin:"live"|"replay"|"backfill",
//     link:{ operation:"create"|"delete", source, source_record, source_rev, subject } }
export function parseLinkEvent (raw) {
  let body
  try {
    body = typeof raw === 'string' ? JSON.parse(raw) : JSON.parse(raw.toString())
  } catch {
    return null // see the framing note in the class below
  }
  if (!body || body.kind !== 'link' || !body.link) return null

  const l = body.link
  if (typeof l.source !== 'string' || typeof l.subject !== 'string') return null
  if (l.operation !== 'create' && l.operation !== 'delete') return null

  const source = parseAtUri(l.source_record)
  if (source === null) return null // the linking record must be addressable, or we cannot fetch it

  return {
    operation: l.operation,
    source: l.source, // the `<nsid>:<path>` spec, e.g. app.bsky.feed.like:subject.uri
    subject: l.subject, // what was linked TO (one of ours)
    // The linking record — this is the thing to fetch+verify+retain if content-bearing.
    did: source.did,
    collection: source.collection,
    rkey: source.rkey,
    // Repo revision of the commit that produced this link. The backfilling guide's skip test: if this
    // rev is <= the rev we already hold for this DID, we already have this state.
    rev: typeof l.source_rev === 'string' ? l.source_rev : null,
    contentBearing: CONTENT_BEARING.has(l.source),
    origin: body.origin || null
  }
}

// Exponential backoff with full jitter. Jitter matters: if the service restarts, every subscriber
// reconnecting on the same schedule is a thundering herd (DESIGN §7.5 makes the same point about ghost
// sweeps).
export function backoffDelay (attempt, { min, max }, random = Math.random) {
  const ceiling = Math.min(max, min * 2 ** Math.max(0, attempt - 1))
  return Math.floor(random() * ceiling)
}

// Does this filter narrow the stream BY SUBJECT? `sources` does not count: it defaults to every
// source, so a sources-only filter looks configured and narrows nothing. Without a subject axis the
// server sends the whole network (see buildSubscribeUrl — an empty array appends no param at all).
export function hasSubjectAxis (filter = {}) {
  return (filter.subjectDids || []).length > 0 ||
    (filter.subjects || []).length > 0 ||
    (filter.subjectPrefixes || []).length > 0
}

export class SpacedustClient {
  // FAIL CLOSED on an empty roster (hyper-social #47). 0.3.58 made the roster empty-by-default so an
  // unconfigured node would not silently index someone else's timeline — but this path turned the same
  // condition into a subscription to EVERYONE'S. Measured on ashatron: 98 retained posts from one
  // unrelated DID, zero from the roster. Unconfigured has to mean inert, not indiscriminate.
  //
  // `allowUnfiltered: true` preserves the URL builder's documented contract for a caller that really
  // does want the firehose — it just has to say so, rather than arrive there via an empty array.
  constructor (filter = {}, opts = {}) {
    this.opts = { ...DEFAULTS, ...opts }
    this._allowUnfiltered = !!opts.allowUnfiltered
    this.filter = {
      subjectDids: filter.subjectDids || [],
      subjects: filter.subjects || [],
      subjectPrefixes: filter.subjectPrefixes || [],
      sources: filter.sources || Object.values(SOURCES)
    }

    // REQUIRED — see the no-runtime-imports note above. Production wiring passes the factory from
    // `spacedust-socket.js`; tests pass a fake.
    if (typeof opts.createSocket !== 'function') {
      throw new Error('SpacedustClient requires opts.createSocket (see lib/spacedust-socket.js)')
    }
    this._createSocket = opts.createSocket
    this._now = opts.now || (() => Date.now())

    this._socket = null
    this._queue = []
    this._closed = false
    this._attempt = 0
    this._reconnectTimer = null

    // Observability — §7.6 budgets are meaningless if drops are silent.
    this.stats = { received: 0, parsed: 0, dropped: 0, unparseable: 0, connects: 0, disconnects: 0, refusedUnfiltered: 0 }
  }

  // Pointers waiting to be drained. The caller owns the drain loop, so it can do fetch/verify/retain at
  // whatever rate it can sustain WITHOUT ever blocking the socket.
  get pending () {
    return this._queue.length
  }

  start () {
    if (this._closed) throw new Error('client is closed')
    this._connect()
    return this
  }

  _connect () {
    // Refuse rather than widen. Guarded here, not in start(), so a RECONNECT cannot quietly restore an
    // unfiltered subscription after the roster was emptied at runtime.
    if (!hasSubjectAxis(this.filter) && !this._allowUnfiltered) {
      this.stats.refusedUnfiltered++
      console.error(JSON.stringify({
        msg: 'spacedust: refusing to subscribe with no subject filter',
        reason: 'an empty roster would subscribe to the ENTIRE network, not to nothing',
        fix: 'set FAVELA_ROSTER (or FAVELA_LIST), or pass allowUnfiltered:true to mean it'
      }))
      return
    }
    const url = buildSubscribeUrl(this.filter, this.opts)
    let socket
    try {
      socket = this._createSocket(url)
    } catch {
      return this._scheduleReconnect() // fail soft — a bad connect is a retry, not a crash
    }

    this._socket = socket
    this.stats.connects++

    // bare-ws auto-replies PONG with the echoed payload (lib/socket.js:163-165), which is exactly what
    // spacedust's 30s keepalive checks (it verifies the 8 random bytes come back). Nothing to do here.

    socket.on('data', (chunk) => this._onMessage(chunk))
    socket.on('error', () => this._onDisconnect())
    socket.on('close', () => this._onDisconnect())
    socket.on('end', () => this._onDisconnect())
  }

  // THE HOT PATH. Parse and enqueue. Nothing else. Any await here risks a lag-disconnect.
  //
  // Framing note: bare-ws is a non-objectMode Duplex that pushes one Buffer per WebSocket message
  // (lib/socket.js:195), and flowing-mode 'data' emits per push — so one chunk is one message. We do not
  // rely on that silently: an unparseable chunk is counted and dropped rather than throwing, and a lost
  // pointer is recoverable via Constellation backfill by (subject, source).
  _onMessage (chunk) {
    this.stats.received++
    const pointer = parseLinkEvent(chunk)
    if (pointer === null) {
      this.stats.unparseable++
      return
    }
    this.stats.parsed++
    this.enqueue(pointer)
  }

  // Enqueue an already-parsed pointer. PUBLIC because the live socket is not the only source: the
  // Constellation backfill pushes historical pointers through this same queue, so both share one bound,
  // one drain and one dedup surface rather than growing a second path.
  //
  // Bounded: drop the OLDEST. Losing one recoverable pointer beats being disconnected and losing the
  // stream — Constellation can re-offer a dropped pointer, nothing can re-offer a missed subscription.
  enqueue (pointer) {
    if (!pointer) return false
    if (this._queue.length >= this.opts.maxQueue) {
      this._queue.shift()
      this.stats.dropped++
    }
    this._queue.push({ ...pointer, receivedAt: this._now() })
    return true
  }

  // Drain up to `max` pointers. Returns them; the caller runs the §7.6 pipeline.
  drain (max = Infinity) {
    if (max >= this._queue.length) {
      const all = this._queue
      this._queue = []
      return all
    }
    return this._queue.splice(0, max)
  }

  // Change the filter WITHOUT reconnecting. Send the complete filter — the server replaces wholesale.
  // Falls back to a reconnect if the socket is not writable, so a roster change is never silently lost.
  updateFilter (filter = {}) {
    // The server REPLACES the whole query, so an empty update is the same unfiltered subscription
    // reached by a different door. Refuse WITHOUT mutating this.filter: the previous (narrower) query
    // stays in force, which is stale but bounded — never wider than what was already asked for.
    const next = { ...this.filter, ...filter }
    if (!hasSubjectAxis(next) && !this._allowUnfiltered) {
      this.stats.refusedUnfiltered++
      console.error(JSON.stringify({
        msg: 'spacedust: refusing a filter update that would remove every subject',
        reason: 'the server replaces the whole query — an empty one matches the ENTIRE network'
      }))
      return false
    }
    this.filter = next
    if (this._socket === null) return false
    try {
      this._socket.write(optionsUpdateFrame(this.filter))
      return true
    } catch {
      this._onDisconnect()
      return false
    }
  }

  _onDisconnect () {
    if (this._socket === null) return // already handled; close/end/error can all fire
    this._socket = null
    this.stats.disconnects++
    if (!this._closed) this._scheduleReconnect()
  }

  _scheduleReconnect () {
    if (this._closed || this._reconnectTimer !== null) return
    this._attempt++
    const delay = backoffDelay(this._attempt, {
      min: this.opts.reconnectMinMs,
      max: this.opts.reconnectMaxMs
    })
    this._reconnectTimer = setTimeout(() => {
      this._reconnectTimer = null
      if (!this._closed) this._connect()
    }, delay)
  }

  // NOTE for the caller: a reconnect leaves a GAP. Spacedust replays nothing — there is no cursor in the
  // subscribe contract. Gap-filling is Constellation's job (getBacklinks by subject+source, paginated),
  // which is why §7.6 pairs the live subscription with the historical index rather than treating either
  // as sufficient alone.
  close () {
    this._closed = true
    if (this._reconnectTimer !== null) {
      clearTimeout(this._reconnectTimer)
      this._reconnectTimer = null
    }
    const socket = this._socket
    this._socket = null
    if (socket !== null) {
      try {
        socket.end()
      } catch {
        // already gone
      }
    }
  }
}
// Static asset serving for favela's browser-side JS (the sign-in client + vendored crypto).
// Serves files from `web/static/` over `GET /static/<path>`. Bare-native (bare-fs/bare-path/bare-url).
//
// Adapted from pear-git-v3's lib/web/static.js: extension allowlist (not a per-file whitelist) +
// path-traversal guard, so a client can never read arbitrary files. Content-Length is intentionally
// NOT set — res.end(body) derives it; setting it explicitly makes bare-http1 emit a duplicate header
// its (stricter-than-node) parser rejects.
import { readFile } from 'bare-fs/promises'
import { fileURLToPath } from 'bare-url'
import { dirname, join, normalize } from 'bare-path'
import { STATIC_ASSETS } from '../web/static-assets.js'

const __dirname = dirname(fileURLToPath(import.meta.url))
const STATIC_DIR = join(__dirname, '..', 'web', 'static')

const ALLOWED_EXTENSIONS = new Set(['.js', '.css', '.json', '.map'])
const CONTENT_TYPES = {
  '.js': 'application/javascript; charset=utf-8',
  '.css': 'text/css; charset=utf-8',
  '.json': 'application/json'
}
function contentType (path) {
  const dot = path.lastIndexOf('.')
  if (dot < 0) return 'application/octet-stream'
  return CONTENT_TYPES[path.slice(dot)] || 'application/octet-stream'
}

// Serve a static file from web/static/. Returns true if handled, false if unknown/blocked (caller 404s).
// relPath is the path AFTER /static/, e.g. "vendor/noble-secp256k1.js".
export async function serveStatic (relPath, res) {
  if (!relPath || typeof relPath !== 'string') return false
  const clean = relPath.replace(/^\/+/, '')
  const normalized = normalize(clean)
  if (normalized.startsWith('..') || normalized.includes('/..')) return false
  if (normalized !== clean) return false
  const dot = normalized.lastIndexOf('.')
  const ext = dot >= 0 ? normalized.slice(dot) : ''
  if (!ALLOWED_EXTENSIONS.has(ext)) return false

  // ⛔ FILESYSTEM FIRST, BUNDLE SECOND. On a server web/static/ is a real directory and this read is the
  // whole story. Inside a bundle it is not: bare-pack packs the module GRAPH, these files are imported by
  // nothing, and readFile throws — which is exactly what favela-android has been doing since the WebView
  // pivot. Measured on the handset 2026-08-18: /static/compose.js and /static/actions.js both 404, so
  // image attach, like, repost, follow, drafts and reporting had NEVER worked there. The markup arrived
  // for free and the behaviour silently did not.
  //
  // The generated module is the copy that survives packing. Filesystem stays first so a server picks up
  // an edited file without regenerating, and test/static-assets.test.mjs fails if the two ever disagree.
  let body
  try { body = await readFile(join(STATIC_DIR, normalized)) } catch { body = null }
  if (body === null) {
    const src = STATIC_ASSETS[normalized]
    if (src === undefined) return false
    body = Buffer.from(src, 'utf8')
  }
  res.writeHead(200, { 'Content-Type': contentType(normalized), 'Cache-Control': 'no-cache, must-revalidate' })
  res.end(body)
  return true
}
// strongref.js — build a com.atproto.repo.strongRef { uri, cid } for a record we are referencing.
//
// WHY THIS EXISTS. A like written as `subject: { uri }` indexes perfectly in favela and is INVALID to
// bsky. app.bsky.feed.like.subject is a strongRef, where uri AND cid are both required, so a like missing
// the cid fails lexicon validation at the relay: it federates as nothing while the local UI shows it
// working. Shipped exactly that in 0.2.41 and only found it because the likes never appeared on bsky.
//
// The cid must be of the EXACT stored bytes, never a re-encode. OverlayRepoStore.getRaw's own comment
// says so ("The bridge CIDs the EXACT bytes (never a re-encode) — so these must be the same bytes `put`
// wrote"), and the store's determinism contract is that it writes dagCbor.encode(record) verbatim. A
// re-encode would usually match and would be a silent, occasional mismatch when it did not — the worst
// possible failure shape for a content address.
import { cidForBytesSync } from 'atproto-repo/lib/cid.js'

// at://<did>/<collection>/<rkey> -> { did, collection, rkey }, or null if it is not that shape.
// Deliberately strict: a malformed uri must not half-parse into a lookup against the wrong record.
export function parseAtUri (uri) {
  if (typeof uri !== 'string' || !uri.startsWith('at://')) return null
  const parts = uri.slice('at://'.length).split('/')
  if (parts.length !== 3) return null
  const [did, collection, rkey] = parts
  if (!did.startsWith('did:') || !collection.includes('.') || !rkey) return null
  return { did, collection, rkey }
}

// Resolve a strongRef for an at:// uri, or null when the record's bytes are not available locally.
//
// Returning null rather than a uri-only ref is the whole point: the caller must REFUSE to write the
// referencing record instead of writing an invalid one. A like that cannot be made valid should fail
// visibly, not federate as nothing.
export async function strongRef (uri, getRecordStore) {
  const ref = parseAtUri(uri)
  if (!ref || typeof getRecordStore !== 'function') return null
  try {
    const store = await getRecordStore(ref.did)
    if (!store || typeof store.getRaw !== 'function') return null
    const raw = await store.getRaw(ref.collection, ref.rkey)
    if (!raw || !raw.bytes) return null
    return { uri, cid: String(cidForBytesSync(raw.bytes)) }
  } catch {
    return null
  }
}
// threadgate — who may reply to a post (app.bsky.feed.threadgate).
//
// THE BINDING IS THE RKEY. A threadgate is a separate record whose rkey is IDENTICAL to the post's, and
// whose `post` field is the post's at:// uri. That is the whole linkage — there is no pointer from the
// post to its gate. It is also why favela needs no new index for this: given a post we already know the
// rkey, so the gate is directly addressable in the record store. (Indexing a new collection would mean
// an INGEST_VERSION bump and a re-index of every DID, for something we can simply look up.)
//
// THE EMPTY ARRAY IS MEANINGFUL, and it is the one thing here that is easy to get backwards:
//   allow ABSENT   -> anyone may reply (there is no gate)
//   allow: []      -> NOBODY may reply
// So a serializer that helpfully omits an empty array turns "nobody" into "everyone" — the exact inverse
// of what the author asked for. Every function here treats undefined and [] as different values.
//
// ⚠ WHAT WE CAN AND CANNOT ENFORCE. A threadgate is advisory metadata: enforcement lives in whoever
// accepts the reply. We honour it in OUR ui and refuse OUR writes, and bsky enforces it in its appview.
// Neither can stop a peer writing a reply record anyway — the gate is not a permission system, and
// presenting it as one would be a lie. The UI says "replies are limited", not "replies are impossible".

export const GATE_CHOICES = ['everyone', 'following', 'mentioned', 'nobody']

// A UI choice -> the `allow` value for the record. `everyone` returns undefined, meaning WRITE NO GATE
// AT ALL rather than a gate that allows everything: an empty-rule gate would read as "nobody".
export function allowFor (choice) {
  switch (choice) {
    case 'nobody': return []
    case 'following': return [{ $type: 'app.bsky.feed.threadgate#followingRule' }]
    case 'mentioned': return [{ $type: 'app.bsky.feed.threadgate#mentionRule' }]
    default: return undefined
  }
}

// The inverse, for rendering an existing gate. A gate whose rules we do not recognise is reported as
// 'limited' rather than guessed at — inventing a permissive reading of an unknown rule is how a gated
// thread ends up looking open.
export function choiceOf (record) {
  if (!record) return 'everyone'
  const allow = record.allow
  if (allow === undefined || allow === null) return 'everyone'
  if (!Array.isArray(allow)) return 'limited'
  if (allow.length === 0) return 'nobody'
  const types = allow.map((r) => String((r && r.$type) || ''))
  if (types.length === 1 && types[0].endsWith('#followingRule')) return 'following'
  if (types.length === 1 && types[0].endsWith('#mentionRule')) return 'mentioned'
  // #listRule — replies limited to members of a named list. Recognised as its own choice rather than
  // lumped into 'limited', because we CAN say which list, and because membership is resolvable when the
  // list is one this node already tracks.
  if (types.length === 1 && types[0].endsWith('#listRule')) return 'list'
  return 'limited'
}

// Human-readable, for the notice on a post.
export function describe (choice) {
  switch (choice) {
    case 'nobody': return 'replies are turned off'
    case 'following': return 'only people the author follows can reply'
    case 'mentioned': return 'only mentioned accounts can reply'
    case 'list': return 'only members of a list can reply'
    case 'limited': return 'replies are limited'
    default: return ''
  }
}

// May `viewerDid` reply, given the gate on a post by `authorDid`?
//
//   authorFollowsViewer — for #followingRule. NOTE the direction: the rule is "people the AUTHOR
//     follows", not "people who follow the author". Getting it backwards silently gates the wrong set.
//   mentionedDids       — the DIDs the post mentions, for #mentionRule.
//
// The author can always reply to their own thread, which is how every client behaves and what makes a
// self-thread possible under a restrictive gate.
export function canReply ({ viewerDid, authorDid, record, authorFollowsViewer = false, mentionedDids = [], listMembers = null } = {}) {
  if (!viewerDid) return false
  if (viewerDid === authorDid) return true
  const choice = choiceOf(record)
  switch (choice) {
    case 'everyone': return true
    case 'nobody': return false
    case 'following': return !!authorFollowsViewer
    case 'mentioned': return mentionedDids.includes(viewerDid)
    // A list gate is answerable ONLY if this node knows the list's membership. `listMembers === null`
    // means "we could not resolve it", which is NOT the same as "you are not a member" — so it fails
    // closed for our own writes, and the UI says the membership is unknown rather than implying refusal.
    case 'list': return Array.isArray(listMembers) ? listMembers.includes(viewerDid) : false
    // An unrecognised rule set is treated as CLOSED for our own writes. Refusing to post a reply that
    // may be rejected downstream is a papercut; writing one that the author asked to prevent is worse.
    default: return false
  }
}

// The list uri a #listRule gate names, or null. The caller needs it to attempt membership resolution.
export function listUriOf (record) {
  const allow = record && record.allow
  if (!Array.isArray(allow)) return null
  for (const r of allow) {
    if (r && String(r.$type || '').endsWith('#listRule') && typeof r.list === 'string') return r.list
  }
  return null
}

// The DIDs a post mentions, read from its richtext facets — the mention rule is defined against these.
export function mentionsOf (postRecord) {
  const out = []
  for (const f of (postRecord && postRecord.facets) || []) {
    for (const feat of (f && f.features) || []) {
      if (feat && String(feat.$type || '').endsWith('#mention') && typeof feat.did === 'string') out.push(feat.did)
    }
  }
  return out
}

// The record to write. rkey MUST be the post's rkey — the caller passes it, and this returns null for
// 'everyone' so the caller writes nothing at all.
export function gateRecord ({ postUri, choice, createdAt = new Date().toISOString() }) {
  const allow = allowFor(choice)
  if (allow === undefined) return null
  return { $type: 'app.bsky.feed.threadgate', post: postUri, allow, createdAt }
}
// The version of the CODE THAT IS RUNNING — not the version on disk.
//
// `pgh app status` reports the INSTALLED tree's package.json, which is true about the disk and can be
// false about the process: an app that installed an update and never restarted still reports the new
// number while serving the old one. That gap has bitten this fleet before. A version rendered by the
// running process is the only one that answers "what am I actually looking at".
//
// Imported statically from package.json so bare-pack pulls it into the module graph — the phone runs
// from worklet.bundle with no package.json on disk, and anything read via fs would be absent there.
// The `with { type: 'json' }` attribute is required by node (the test suite's runtime) and accepted by
// bare (the daemon's). The bare form alone throws ERR_IMPORT_ATTRIBUTE_MISSING under node; verified on
// both before choosing this.
import pkg from '../package.json' with { type: 'json' }

export const VERSION = (pkg && pkg.version) || 'unknown'
// favela Writer — relays a post (and device/pairing ops) to the hpp device, which signs it. favela is
// keyless: it never holds the DID signing key; the hpp does. Two transports, tried in order:
//
//   1. LOCAL UDS (preferred) — when favela-web is CO-LOCATED with the hpp (the normal case), it reaches
//      the device over the hpp's unix socket (hyper-svc): instant local IPC, NO DHT rendezvous, and
//      owner-gated by the filesystem so it needs NO swarm identity / writer-allowlist (no seed collision).
//   2. SWARM (fallback) — a REMOTE hpp: connect to the device control key over Hyperswarm with an
//      allowlisted writer keypair + ProtomuxRPC. (The original transport; kept for the remote case.)
//
// Both surfaces expose the SAME ops (apply-write / delegate / list-devices / revoke-device /
// is-device-revoked / get-state), so a single `_call(method, params)` routes over whichever is live.
import Hyperswarm from 'hyperswarm'
import crypto from 'hypercore-crypto'
import b4a from 'b4a'
import c from 'compact-encoding'
import ProtomuxRPC from 'protomux-rpc'
import { Client } from 'hyper-svc'
import { tidNow } from 'atproto-store/lib/tid.js'
import { collectionForScope, DEFAULT_SCOPE, SCOPE_COLLECTION } from './scopes.js'
import { detectFacets } from './facets.js'

const DEVICE_PROTOCOL = 'hyper-proto-peer/device/v1' // must match hpp serve-device (swarm surface)
const DEFAULT_SOCK = (process.env.HOME || '') + '/.config/hyper-proto-peer/data/control.sock'

/**
 * Which write transport, if any, this process has been EXPLICITLY configured with.
 *
 * The caller (bin/favela-web.js) refuses writes wholesale when this returns null, because an instance
 * that cannot name the node it writes to must not guess — the 2026-08-09 accident was a test run
 * reaching live wj62 through a default.
 *
 * ⛔ READ THE ENV, NOT THE Writer. The constructor below falls back to DEFAULT_SOCK when nothing is set,
 * so asking "does the writer have a uds" is always true and would silently hand writes to whatever hpp
 * owns the default socket — the very hazard the gate exists to prevent. Only an explicitly-set value counts.
 *
 * UDS outranks the swarm key: if a device is reachable on this box, taking a DHT round-trip to it is
 * strictly worse, and the co-located case (favela-android's embedded favela-web, a desktop hpp+web pair)
 * is the normal one.
 *
 * @returns {'uds'|'swarm'|null}
 */
export function writeTransportConfigured (env = {}) {
  if (String(env.FAVELA_HPP_SOCK || '').trim()) return 'uds'
  if (String(env.FAVELA_CONTROL_KEY || '').trim()) return 'swarm'
  return null
}

export class Writer {
  // controlKey/writerSeed: only needed for the SWARM fallback (remote hpp). uds: the local hpp socket
  // (defaults to the co-located hpp; FAVELA_HPP_SOCK overrides). Local UDS is tried first.
  constructor ({ controlKey, writerSeed, uds, device = null, blobs = null } = {}) {
    // IN-PROCESS TRANSPORT (favela-android). The phone runs the node in the SAME process — there is no
    // socket and no DHT to reach, the SwarmDevice object is right here. Every method on this class is
    // record-BUILDING (scope->collection, facets, embeds, langs, the grapheme cap) plus one `_call`, so
    // injecting the device lets the React Native port reuse this write path verbatim instead of
    // reimplementing the record shapes — which is how a uri-only strongRef shipped once already.
    //
    // ⛔ IT MUST ALSO FORECLOSE THE SOCKET. With a device injected there is deliberately NO uds and NO
    // swarm fallback: a `Writer({device})` that could still reach DEFAULT_SOCK is one forgotten stub away
    // from a test writing to production — which is exactly what happened on 2026-08-09 (a post landed in
    // wj62 from test/writer.test.mjs because the unknown option was ignored and ready() connected to the
    // live hpp). Being unable to reach a socket is the property, not a detail.
    this.device = device
    this.blobs = blobs
    this.uds = device ? null : (uds || process.env.FAVELA_HPP_SOCK || DEFAULT_SOCK)
    this.controlKey = controlKey ? String(controlKey).toLowerCase() : null
    this.writerSeed = writerSeed || null
    this._uds = null // hyper-svc Client (local)
    this._rpc = null // ProtomuxRPC (swarm fallback)
    this.swarm = null
  }

  _startSwarm () {
    if (this.swarm || !this.controlKey || !this.writerSeed) return
    this.swarm = new Hyperswarm({ keyPair: crypto.keyPair(crypto.hash(b4a.from(this.writerSeed))) })
    this.swarm.on('connection', (conn) => {
      if (b4a.toString(conn.remotePublicKey, 'hex') !== this.controlKey) { conn.destroy(); return }
      this._rpc = new ProtomuxRPC(conn, { protocol: DEVICE_PROTOCOL, valueEncoding: c.json })
      this._rpc.on('close', () => { if (this._rpc && this._rpc.closed) this._rpc = null })
    })
    this.swarm.join(b4a.from(this.controlKey, 'hex'), { client: true, server: false })
  }

  async ready ({ timeout = 20000 } = {}) {
    if (this.device) return true // in-process: nothing to connect to
    // 1. LOCAL UDS first — instant, no DHT. Client.connectUds throws fast if the socket is absent.
    if (this._uds && !this._uds.closed) return true
    if (this.uds) {
      try { this._uds = await Client.connectUds(this.uds); if (this._uds) return true } catch { this._uds = null }
    }
    // 2. SWARM fallback — remote hpp (or no local socket). Poll for the ProtomuxRPC channel.
    this._startSwarm()
    if (!this.swarm) return false // no swarm creds and no socket → unreachable
    const end = Date.now() + timeout
    while (Date.now() < end) { if (this._rpc && !this._rpc.closed) return true; await new Promise((r) => setTimeout(r, 100)) }
    return false
  }

  async _call (method, params) {
    if (this.device) return this._deviceCall(method, params || {})
    if (!(await this.ready())) throw new Error('Writer: no device connection (hpp up? local socket present? control key current?)')
    if (this._uds && !this._uds.closed) {
      // The cached UDS client goes STALE when the co-located hpp RESTARTS: bare-net half-open means the
      // socket dies but the Client's `.closed` never flips, so ready() keeps returning it and the call
      // HANGS forever (this wedged /api/post after every hpp restart). Time-box the call; on timeout/
      // error drop the client, reconnect ONCE, and retry — so an hpp restart self-heals per-request.
      try {
        return await this._udsCall(method, params)
      } catch (err) {
        try { await this._uds.close() } catch {}
        this._uds = null
        if (await this.ready()) { if (this._uds && !this._uds.closed) return await this._udsCall(method, params) }
        if (!this._rpc || this._rpc.closed) throw err // no swarm fallback → surface the original error
      }
    }
    return this._rpc.request(method, params || {}) // swarm: ProtomuxRPC.request
  }

  // The in-process dispatch: the SAME seven ops the UDS/swarm surfaces expose (serve-device-uds.js),
  // mapped straight onto the SwarmDevice. Bytes are NOT hex-encoded here — hex exists because the UDS
  // RPC value encoding is JSON; in-process the Buffer is handed over as-is.
  async _deviceCall (method, params) {
    const d = this.device
    switch (method) {
      case 'apply-write': return d.applyWrite(params)
      case 'get-state': return d.state()
      case 'delegate': return d.delegate(params)
      case 'list-devices': return { devices: await d.listDevices() }
      case 'revoke-device': return params.restore ? d.restoreDevice(params.subKey) : d.revokeDevice(params.subKey, { reason: params.reason || null })
      case 'is-device-revoked': return { revoked: await d.isDeviceRevoked(params.subKey) }
      case 'upload-blob': {
        if (!this.blobs) throw new Error('Writer: no blob store injected — cannot upload')
        const bytes = params.bytes && typeof params.bytes === 'string' ? b4a.from(params.bytes, 'hex') : params.bytes
        const r = await this.blobs.put(bytes, params.mimeType || 'application/octet-stream')
        return { cid: String(r.cid), mimeType: r.mimeType || params.mimeType, size: r.size }
      }
      default: throw new Error('Writer: unsupported in-process method ' + method)
    }
  }

  // A UDS call bounded by a timeout so a stale (post-hpp-restart) socket can't hang the caller
  // indefinitely. On timeout the underlying call promise is abandoned; the caller reconnects + retries.
  async _udsCall (method, params, ms = 10000) {
    let t = null
    try {
      return await Promise.race([
        this._uds.call(method, params || {}),
        new Promise((_, reject) => { t = setTimeout(() => reject(new Error('UDS call timed out (stale hpp socket?)')), ms) })
      ])
    } finally { if (t) clearTimeout(t) }
  }

  // Post a text record. `scope` selects the collection (POSSE): 'public' -> app.bsky.feed.post (fronted to
  // bsky) or 'local' -> net.favela.local.post (favela-only). Returns { rkey, scope, collection, ...sign }.
  // `images` = [{ blob, alt?, aspectRatio? }] where blob came from uploadBlob → Writer.blobRef.
  // Edit an existing post IN PLACE: same collection, same rkey, new CID.
  //
  // ★ atproto ALLOWS this — putRecord is lexicon-agnostic and the PDS accepts it — but bsky's AppView
  // deliberately ignores post updates, so getRecord reflects an edit and getPostThread does not
  // (atproto discussion #3038). The edit is real on the P2P side and on ActivityPub; on bsky it is
  // partial. See spec/record-vocabulary.md §10.5. Callers MUST NOT imply otherwise in the UI.
  //
  // What is PRESERVED from the original, deliberately:
  //   createdAt — an edit is not a new post. Rewriting it would reorder the timeline and lie about
  //               when the thing was said.
  //   reply / embed — editing text must not silently detach a thread or drop images.
  //   collection — an edit cannot change a post's REACH. Moving app.bsky.feed.post to
  //               net.favela.local.post would "unpublish" from bsky by writing a new record while
  //               the old one keeps federating: two records, one rkey, no way back.
  //
  // Facets are RE-DERIVED, never carried over: they are byte offsets into the OLD text and would
  // land on the wrong characters (or outside the string) once the text changes.
  async editPost (collection, rkey, text, { langs = null, resolveHandle = null, prior = null } = {}) {
    if (!collection || !rkey) throw new Error('editPost: collection and rkey required')
    const graphemes = [...String(text)].length
    if (graphemes > 300) throw new Error(`too long: ${graphemes} graphemes (bsky limit 300)`)
    const base = prior && typeof prior === 'object' ? prior : {}
    const record = {
      $type: collection,
      text: String(text),
      createdAt: base.createdAt || new Date().toISOString()
    }
    if (Array.isArray(langs) && langs.length) record.langs = langs
    else if (Array.isArray(base.langs) && base.langs.length) record.langs = base.langs
    if (base.reply) record.reply = base.reply
    if (base.embed) record.embed = base.embed
    try {
      const facets = await detectFacets(record.text, { resolveHandle })
      if (facets.length) record.facets = facets
    } catch { /* an edit without facets beats a failed edit */ }
    await this.putRecord(collection, rkey, record, { action: 'update' })
    return { collection, rkey, record }
  }

  async post (text, { scope = DEFAULT_SCOPE, langs = ['en'], images = null, reply = null, resolveHandle = null, quote = null } = {}) {
    const collection = collectionForScope(scope) // throws on an unknown scope (no silent public fallback)
    const graphemes = [...String(text)].length
    if (graphemes > 300) throw new Error(`too long: ${graphemes} graphemes (bsky limit 300)`)
    const rkey = tidNow()
    const record = { $type: collection, text, createdAt: new Date().toISOString() }
    // reply: { root, parent } — both com.atproto.repo.strongRef. Built by the caller (it needs the
    // appview to resolve cids); passed through verbatim so this stays a thin signer.
    if (reply && reply.root && reply.parent) record.reply = reply
    // Image embed — the shape decoded from wj62's existing working image post. Capped at 4, matching
    // app.bsky.embed.images' maxLength: bsky REJECTS a longer array outright, and a record the relay
    // refuses would federate as nothing while looking fine locally.
    const imageEmbed = (Array.isArray(images) && images.length)
      ? {
          $type: 'app.bsky.embed.images',
          images: images.slice(0, 4).map((im) => ({
            alt: String((im && im.alt) || ''),
            image: im.blob,
            ...(im && im.aspectRatio ? { aspectRatio: im.aspectRatio } : {})
          }))
        }
      : null
    // A QUOTE is a strongRef (uri AND cid) exactly like a like's subject, and the caller resolves it —
    // this stays a thin signer. Quote + images is `recordWithMedia`, which is the ONLY lexicon-valid way
    // to carry both: a record can hold one `embed`, so emitting two would silently drop one of them.
    if (quote && quote.uri && quote.cid) {
      record.embed = imageEmbed
        ? { $type: 'app.bsky.embed.recordWithMedia', record: { $type: 'app.bsky.embed.record', record: { uri: quote.uri, cid: quote.cid } }, media: imageEmbed }
        : { $type: 'app.bsky.embed.record', record: { uri: quote.uri, cid: quote.cid } }
    } else if (imageEmbed) {
      record.embed = imageEmbed
    }
    // Declare the post language. bsky.app's CUSTOM-FEED view applies FeedTuner.preferredLangOnly — a tuner it
    // does NOT apply to author feeds or the raw getFeed XRPC — which runs the `lande` language detector on any
    // post that omits `langs` and drops whatever it doesn't read as the viewer's content language. Short/
    // technical posts get misdetected ("test 2" -> French, "hello" -> Finnish, "stortron/origin" -> Dutch) and
    // silently vanish from the feed on bsky.app while still appearing everywhere else. A declared langs makes
    // getPostLanguage take the fast path (return the tag, never run lande), so the post always renders. Only
    // the bsky-fronted collection carries langs; net.favela.local.post has no such field.
    if (collection === SCOPE_COLLECTION.public && Array.isArray(langs) && langs.length) record.langs = langs
    // Rich-text facets. Until 0.3.11 we READ facets and wrote none, so every link, @mention and #tag
    // posted from favela shipped as inert plain text to bsky and every other client — the exact inverse
    // of what renderRichText does on the read side. Byte offsets, not string indices (see facets.js).
    // A mention resolves to a DID or is omitted: an unlinked handle is a papercut, a mention pointing at
    // the wrong account is someone else's notification. Failure here must never block the post itself.
    if (collection === SCOPE_COLLECTION.public) {
      try {
        const facets = await detectFacets(text, { resolveHandle })
        if (facets.length) record.facets = facets
      } catch { /* a post without facets beats no post */ }
    }
    const r = await this._call('apply-write', { action: 'create', collection, rkey, record })
    return { rkey, scope, collection, ...r }
  }

  // ── blobs (avatars + post images) ───────────────────────────────────────────────────────────────
  // Upload bytes to the hpp, which stores them content-addressed and returns the atproto blob CID.
  // favela stays keyless: it never signs — it hands the hpp bytes and the hpp owns storage. The UDS
  // surface is JSON, so the bytes travel as hex (matching serve-device-uds's b4a.from(bytes,'hex')).
  async uploadBlob (bytes, mimeType = 'application/octet-stream') {
    const buf = b4a.isBuffer(bytes) ? bytes : b4a.from(bytes)
    const r = await this._call('upload-blob', { bytes: b4a.toString(buf, 'hex'), mimeType })
    if (!r || !r.cid) throw new Error('upload-blob returned no cid')
    return { cid: r.cid, mimeType: r.mimeType || mimeType, size: r.size != null ? r.size : buf.length }
  }

  // The atproto blob REFERENCE embedded in a record. This shape is not a guess — it is exactly what
  // the fleet's existing records already hold on disk (verified by decoding wj62's live
  // app.bsky.actor.profile/self and its working image post): `ref` is a PLAIN object carrying $link,
  // not a CID instance. Records written in this shape federate to bsky today, so match it byte-for-byte
  // rather than "correcting" it — changing the encoding is a separate, riskier decision.
  static blobRef ({ cid, mimeType, size }) {
    return { $type: 'blob', ref: { $link: String(cid) }, mimeType, size }
  }

  // Write any record through the hpp (it signs). action 'create'|'update' are equivalent at the repo
  // layer (last-writer-wins on the key); 'delete' removes it.
  async putRecord (collection, rkey, record, { action = 'update' } = {}) {
    return this._call('apply-write', { action, collection, rkey, record })
  }

  // Delegate a browser sub-key to act as the DID (the hpp signs the delegation). Returns
  // { did, subKey, delegation, exp }. Used by the pairing mint (favela-pair / lib/cli.js).
  async delegate (subKey, { ttlSec, label } = {}) {
    return this._call('delegate', { subKey, ...(ttlSec ? { ttlSec } : {}), ...(label ? { label } : {}) })
  }

  // The device's own view of itself — used to confirm WHICH DID this hpp signs for before writing a
  // profile record. favela's write path is single-DID (the UDS socket picks the device), so a signed-in
  // viewer whose DID differs from the device's must not have their write silently land in someone
  // else's repo.
  async state () { return this._call('get-state', {}) }

  // Device registry (Option 3): list / revoke / query the DID's delegated browser sub-keys.
  async listDevices () { const r = await this._call('list-devices', {}); return (r && r.devices) || [] }
  async revokeDevice (subKey, { restore = false, reason = null } = {}) { return this._call('revoke-device', { subKey, restore, reason }) }
  async isDeviceRevoked (subKey) { const r = await this._call('is-device-revoked', { subKey }); return !!(r && r.revoked) }

  async close () {
    try { if (this._uds) await this._uds.close() } catch {}
    try { if (this.swarm) await this.swarm.destroy() } catch {}
  }
}
const { Pull, Push, HEADERBYTES, KEYBYTES, ABYTES } = require('sodium-secretstream')
const sodium = require('sodium-universal')
const crypto = require('hypercore-crypto')
const { Duplex, Writable, getStreamError } = require('streamx')
const b4a = require('b4a')
const Timeout = require('timeout-refresh')
const unslab = require('unslab')
const Bridge = require('./lib/bridge')
const Handshake = require('./lib/handshake')

const IDHEADERBYTES = HEADERBYTES + 32
const [NS_INITIATOR, NS_RESPONDER, NS_SEND] = crypto.namespace('hyperswarm/secret-stream', 3)
const MAX_ATOMIC_WRITE = 256 * 256 * 256 - 1

module.exports = class NoiseSecretStream extends Duplex {
  constructor(isInitiator, rawStream, opts = {}) {
    super({ mapWritable: toBuffer })

    if (typeof isInitiator !== 'boolean') {
      throw new Error('isInitiator should be a boolean')
    }

    this.noiseStream = this
    this.isInitiator = isInitiator
    this.rawStream = null

    this.publicKey = opts.publicKey || null
    this.remotePublicKey = opts.remotePublicKey || null
    this.handshakeHash = null
    this.connected = false
    this.keepAlive = opts.keepAlive || 0
    this.timeout = 0
    this.enableSend = opts.enableSend !== false

    // pointer for upstream to set data here if they want
    this.userData = null

    let openedDone = null
    this.opened = new Promise((resolve) => {
      openedDone = resolve
    })

    this.rawBytesWritten = 0
    this.rawBytesRead = 0

    // metadata used by 'hyperdht'
    this.relay = null
    this.puncher = null

    // unwrapped raw stream
    this._rawStream = null

    // handshake state
    this._handshake = null
    this._handshakePattern = opts.pattern || null
    this._handshakeDone = null

    // message parsing state
    this._state = 0
    this._len = 0
    this._tmp = 1
    this._message = null

    this._openedDone = openedDone
    this._startDone = null
    this._drainDone = null
    this._outgoingPlain = null
    this._outgoingWrapped = null
    this._utp = null
    this._setup = true
    this._ended = 2
    this._encrypt = null
    this._decrypt = null
    this._timeoutTimer = null
    this._keepAliveTimer = null
    this._sendState = null

    if (opts.autoStart !== false) this.start(rawStream, opts)

    // wiggle it to trigger open immediately (TODO add streamx option for this)
    this.resume()
    this.pause()
  }

  static keyPair(seed) {
    return Handshake.keyPair(seed)
  }

  static id(handshakeHash, isInitiator, id) {
    return streamId(handshakeHash, isInitiator, id)
  }

  setTimeout(ms) {
    if (!ms) ms = 0

    this._clearTimeout()
    this.timeout = ms

    if (!ms || this.rawStream === null) return

    this._timeoutTimer = Timeout.once(ms, destroyTimeout, this)
    this._timeoutTimer.unref()
  }

  setKeepAlive(ms) {
    if (!ms) ms = 0

    this._clearKeepAlive()

    this.keepAlive = ms

    if (!ms || this.rawStream === null) return

    this._keepAliveTimer = Timeout.on(ms, sendKeepAlive, this)
    this._keepAliveTimer.unref()
  }

  sendKeepAlive() {
    const empty = this.alloc(0)
    this.write(empty)
  }

  start(rawStream, opts = {}) {
    if (rawStream) {
      this.rawStream = rawStream
      this._rawStream = rawStream
      if (typeof this.rawStream.setContentSize === 'function') {
        this._utp = rawStream
      }
    } else {
      this.rawStream = new Bridge(this)
      this._rawStream = this.rawStream.reverse
    }

    this.rawStream.on('error', this._onrawerror.bind(this))
    this.rawStream.on('close', this._onrawclose.bind(this))

    this._startHandshake(opts.handshake, opts.keyPair || null)
    this._continueOpen(null)

    if (this.destroying) return

    if (opts.data) this._onrawdata(opts.data)
    if (opts.ended) this._onrawend()

    if (this.keepAlive > 0 && this._keepAliveTimer === null) {
      this.setKeepAlive(this.keepAlive)
    }

    if (this.timeout > 0 && this._timeoutTimer === null) {
      this.setTimeout(this.timeout)
    }
  }

  async flush() {
    if ((await this.opened) === false) return false
    if ((await Writable.drained(this)) === false) return false
    if (this.destroying) return false

    if (this.rawStream !== null && this.rawStream.flush) {
      return await this.rawStream.flush()
    }

    return true
  }

  _continueOpen(err) {
    if (err) this.destroy(err)
    if (this._startDone === null) return
    const done = this._startDone
    this._startDone = null
    this._open(done)
  }

  _onkeypairpromise(p) {
    const self = this
    const cont = this._continueOpen.bind(this)

    p.then(onkeypair, cont)

    function onkeypair(kp) {
      self._onkeypair(kp)
      cont(null)
    }
  }

  _onkeypair(keyPair) {
    const pattern = this._handshakePattern || 'XX'
    const remotePublicKey = this.remotePublicKey

    this._handshake = new Handshake(this.isInitiator, keyPair, remotePublicKey, pattern)
    this.publicKey = this._handshake.keyPair.publicKey
  }

  _startHandshake(handshake, keyPair) {
    if (handshake) {
      const { tx, rx, hash, publicKey, remotePublicKey } = handshake
      this._setupSecretStream(tx, rx, hash, publicKey, remotePublicKey)
      return
    }

    if (!keyPair) keyPair = Handshake.keyPair()

    if (typeof keyPair.then === 'function') {
      this._onkeypairpromise(keyPair)
    } else {
      this._onkeypair(keyPair)
    }
  }

  _onrawerror(err) {
    this.destroy(err)
  }

  _onrawclose() {
    if (this._ended !== 0) this.destroy()
  }

  _onrawdata(data) {
    let offset = 0

    if (this._timeoutTimer !== null) {
      this._timeoutTimer.refresh()
    }

    do {
      switch (this._state) {
        case 0: {
          while (this._tmp !== 0x1000000 && offset < data.byteLength) {
            const v = data[offset++]
            this._len += this._tmp * v
            this._tmp *= 256
          }

          if (this._tmp === 0x1000000) {
            this._tmp = 0
            this._state = 1
            const unprocessed = data.byteLength - offset
            if (unprocessed < this._len && this._utp !== null)
              this._utp.setContentSize(this._len - unprocessed)
          }

          break
        }

        case 1: {
          const missing = this._len - this._tmp
          const end = missing + offset

          if (this._message === null && end <= data.byteLength) {
            this._message = data.subarray(offset, end)
            offset += missing
            this._incoming()
            break
          }

          const unprocessed = data.byteLength - offset

          if (this._message === null) {
            this._message = b4a.allocUnsafe(this._len)
          }

          b4a.copy(data, this._message, this._tmp, offset)
          this._tmp += unprocessed

          if (end <= data.byteLength) {
            offset += missing
            this._incoming()
          } else {
            offset += unprocessed
          }

          break
        }
      }
    } while (offset < data.byteLength && !this.destroying)
  }

  _onrawend() {
    this._ended--
    this.push(null)
  }

  _onrawdrain() {
    const drain = this._drainDone
    if (drain === null) return
    this._drainDone = null
    drain()
  }

  _read(cb) {
    this.rawStream.resume()
    cb(null)
  }

  _incoming() {
    const message = this._message

    this._state = 0
    this._len = 0
    this._tmp = 1
    this._message = null

    if (this._setup === true) {
      if (this._handshake) {
        this._onhandshakert(this._handshake.recv(message))
      } else {
        if (message.byteLength !== IDHEADERBYTES) {
          this.destroy(new Error('Invalid header message received'))
          return
        }

        const remoteId = message.subarray(0, 32)
        const expectedId = streamId(this.handshakeHash, !this.isInitiator)
        const header = message.subarray(32)

        if (!b4a.equals(expectedId, remoteId)) {
          this.destroy(new Error('Invalid header received'))
          return
        }

        this._decrypt.init(header)
        this._setup = false // setup is now done
      }
      return
    }

    if (message.byteLength < ABYTES) {
      this.destroy(new Error('Invalid message received'))
      return
    }

    this.rawBytesRead += message.byteLength

    const plain = message.subarray(1, message.byteLength - ABYTES + 1)

    try {
      this._decrypt.next(message, plain)
    } catch (err) {
      this.destroy(err)
      return
    }

    // If keep alive is selective, eat the empty buffers (ie assume the other side has it enabled also)
    if (plain.byteLength === 0 && this.keepAlive !== 0) return

    if (this.push(plain) === false) {
      this.rawStream.pause()
    }
  }

  _onhandshakert(h) {
    if (this._handshakeDone === null) return

    if (h !== null) {
      if (h.data) this._rawStream.write(h.data)
      if (!h.tx) return
    }

    const done = this._handshakeDone
    const publicKey = this._handshake.keyPair.publicKey

    this._handshakeDone = null
    this._handshake = null

    if (h === null) return done(new Error('Noise handshake failed'))

    this._setupSecretStream(h.tx, h.rx, h.hash, publicKey, h.remotePublicKey)
    this._resolveOpened(true)
    done(null)
  }

  _setupSecretStream(tx, rx, handshakeHash, publicKey, remotePublicKey) {
    const buf = b4a.allocUnsafeSlow(3 + IDHEADERBYTES)
    writeUint24le(IDHEADERBYTES, buf)

    this._encrypt = new Push(unslab(tx.subarray(0, KEYBYTES)), undefined, buf.subarray(3 + 32))
    this._decrypt = new Pull(unslab(rx.subarray(0, KEYBYTES)))

    this.publicKey = publicKey
    this.remotePublicKey = remotePublicKey
    this.handshakeHash = handshakeHash

    const id = buf.subarray(3, 3 + 32)
    streamId(handshakeHash, this.isInitiator, id)

    // initialize secretbox state for unordered messages
    this._setupSecretSend(handshakeHash)

    this.emit('handshake')
    // if rawStream is a bridge, also emit it there
    if (this.rawStream !== this._rawStream) this.rawStream.emit('handshake')

    if (this.destroying) return

    this._rawStream.write(buf)
  }

  _setupSecretSend(handshakeHash) {
    this._sendState = b4a.allocUnsafeSlow(32 + 32 + 8 + 8)
    const encrypt = this._sendState.subarray(0, 32) // secrets
    const decrypt = this._sendState.subarray(32, 64)
    const counter = this._sendState.subarray(64, 72) // nonce
    const initial = this._sendState.subarray(72)

    const inputs = this.isInitiator
      ? [
          [NS_INITIATOR, NS_SEND],
          [NS_RESPONDER, NS_SEND]
        ]
      : [
          [NS_RESPONDER, NS_SEND],
          [NS_INITIATOR, NS_SEND]
        ]

    sodium.crypto_generichash_batch(encrypt, inputs[0], handshakeHash)
    sodium.crypto_generichash_batch(decrypt, inputs[1], handshakeHash)

    sodium.randombytes_buf(initial)
    counter.set(initial)
  }

  _open(cb) {
    // no autostart or no handshake yet
    if (this._rawStream === null || (this._handshake === null && this._encrypt === null)) {
      this._startDone = cb
      return
    }

    this._rawStream.on('data', this._onrawdata.bind(this))
    this._rawStream.on('end', this._onrawend.bind(this))
    this._rawStream.on('drain', this._onrawdrain.bind(this))

    if (this.enableSend) this._rawStream.on('message', this._onmessage.bind(this))

    if (this._encrypt !== null) {
      this._resolveOpened(true)
      return cb(null)
    }

    this._handshakeDone = cb

    if (this.isInitiator) this._onhandshakert(this._handshake.send())
  }

  _predestroy() {
    if (this.rawStream) {
      const error = getStreamError(this)
      this.rawStream.destroy(error)
    }

    if (this._startDone !== null) {
      const done = this._startDone
      this._startDone = null
      done(new Error('Stream destroyed'))
    }

    if (this._handshakeDone !== null) {
      const done = this._handshakeDone
      this._handshakeDone = null
      done(new Error('Stream destroyed'))
    }

    if (this._drainDone !== null) {
      const done = this._drainDone
      this._drainDone = null
      done(new Error('Stream destroyed'))
    }
  }

  _write(data, cb) {
    let wrapped = this._outgoingWrapped

    if (data !== this._outgoingPlain) {
      wrapped = b4a.allocUnsafe(data.byteLength + 3 + ABYTES)
      wrapped.set(data, 4)
    } else {
      this._outgoingWrapped = this._outgoingPlain = null
    }

    if (wrapped.byteLength - 3 > MAX_ATOMIC_WRITE) {
      return cb(
        new Error(
          'Message is too large for an atomic write. Max size is ' + MAX_ATOMIC_WRITE + ' bytes.'
        )
      )
    }
    this.rawBytesWritten += wrapped.byteLength

    writeUint24le(wrapped.byteLength - 3, wrapped)
    // offset 4 so we can do it in-place
    this._encrypt.next(wrapped.subarray(4, 4 + data.byteLength), wrapped.subarray(3))

    if (this._keepAliveTimer !== null) this._keepAliveTimer.refresh()

    if (this._rawStream.write(wrapped) === false) {
      this._drainDone = cb
    } else {
      cb(null)
    }
  }

  _final(cb) {
    this._clearKeepAlive()
    this._ended--
    this._rawStream.end()
    cb(null)
  }

  _resolveOpened(val) {
    if (this._openedDone === null) return
    const opened = this._openedDone
    this._openedDone = null
    opened(val)
    if (!val) return
    this.connected = true
    this.emit('connect')
  }

  _clearTimeout() {
    if (this._timeoutTimer === null) return
    this._timeoutTimer.destroy()
    this._timeoutTimer = null
    this.timeout = 0
  }

  _clearKeepAlive() {
    if (this._keepAliveTimer === null) return
    this._keepAliveTimer.destroy()
    this._keepAliveTimer = null
    this.keepAlive = 0
  }

  _destroy(cb) {
    this._clearKeepAlive()
    this._clearTimeout()
    this._resolveOpened(false)
    cb(null)
  }

  _boxMessage(buffer) {
    const MB = sodium.crypto_secretbox_MACBYTES // 16
    const NB = sodium.crypto_secretbox_NONCEBYTES // 24

    const counter = this._sendState.subarray(64, 72)
    sodium.sodium_increment(counter)
    if (b4a.equals(counter, this._sendState.subarray(72))) {
      this.destroy(new Error('udp send nonce exchausted'))
      return
    }

    const secret = this._sendState.subarray(0, 32)
    const envelope = b4a.allocUnsafe(8 + MB + buffer.byteLength)
    const nonce = envelope.subarray(0, NB)
    const ciphertext = envelope.subarray(8)

    b4a.fill(nonce, 0) // pad suffix
    nonce.set(counter)

    sodium.crypto_secretbox_easy(ciphertext, buffer, nonce, secret)
    return envelope
  }

  send(buffer) {
    if (!this._sendState) return
    if (!this.rawStream?.send) return // udx-stream expected

    const message = this._boxMessage(buffer)
    return this.rawStream.send(message)
  }

  trySend(buffer) {
    if (!this._sendState) return
    if (!this.rawStream?.trySend) return // udx-stream expected

    const message = this._boxMessage(buffer)
    this.rawStream.trySend(message)
  }

  _onmessage(buffer) {
    if (!this._sendState) return // messages before handshake are dropped

    const MB = sodium.crypto_secretbox_MACBYTES // 16
    const NB = sodium.crypto_secretbox_NONCEBYTES // 24

    if (buffer.byteLength < NB) return // Invalid message

    const nonce = b4a.allocUnsafe(NB)
    b4a.fill(nonce, 0)
    nonce.set(buffer.subarray(0, 8))

    const secret = this._sendState.subarray(32, 64)
    const ciphertext = buffer.subarray(8)
    const plain = buffer.subarray(8, buffer.byteLength - MB)

    if (ciphertext.byteLength < MB) return // invalid message

    const success = sodium.crypto_secretbox_open_easy(plain, ciphertext, nonce, secret)

    if (success) this.emit('message', plain)
  }

  alloc(len) {
    const buf = b4a.allocUnsafe(len + 3 + ABYTES)
    this._outgoingWrapped = buf
    this._outgoingPlain = buf.subarray(4, buf.byteLength - ABYTES + 1)
    return this._outgoingPlain
  }

  toJSON() {
    return {
      isInitiator: this.isInitiator,
      publicKey: this.publicKey && b4a.toString(this.publicKey, 'hex'),
      remotePublicKey: this.remotePublicKey && b4a.toString(this.remotePublicKey, 'hex'),
      connected: this.connected,
      destroying: this.destroying,
      destroyed: this.destroyed,
      rawStream: this.rawStream && this.rawStream.toJSON ? this.rawStream.toJSON() : null
    }
  }
}

function writeUint24le(n, buf) {
  buf[0] = n & 255
  buf[1] = (n >>> 8) & 255
  buf[2] = (n >>> 16) & 255
}

function streamId(handshakeHash, isInitiator, out = b4a.allocUnsafe(32)) {
  sodium.crypto_generichash(out, isInitiator ? NS_INITIATOR : NS_RESPONDER, handshakeHash)
  return out
}

function toBuffer(data) {
  return typeof data === 'string' ? b4a.from(data) : data
}

function destroyTimeout() {
  this.destroy(new Error('Stream timed out'))
}

function sendKeepAlive() {
  const empty = this.alloc(0)
  this.write(empty)
}
const { Duplex, Writable } = require('streamx')

class ReversePassThrough extends Duplex {
  constructor(s) {
    super()
    this._stream = s
    this._ondrain = null
  }

  _write(data, cb) {
    if (this._stream.push(data) === false) {
      this._stream._ondrain = cb
    } else {
      cb(null)
    }
  }

  _final(cb) {
    this._stream.push(null)
    cb(null)
  }

  _read(cb) {
    const ondrain = this._ondrain
    this._ondrain = null
    if (ondrain) ondrain()
    cb(null)
  }
}

module.exports = class Bridge extends Duplex {
  constructor(noiseStream) {
    super()

    this.noiseStream = noiseStream

    this._ondrain = null
    this.reverse = new ReversePassThrough(this)
  }

  get publicKey() {
    return this.noiseStream.publicKey
  }

  get remotePublicKey() {
    return this.noiseStream.remotePublicKey
  }

  get handshakeHash() {
    return this.noiseStream.handshakeHash
  }

  flush() {
    return Writable.drained(this)
  }

  _read(cb) {
    const ondrain = this._ondrain
    this._ondrain = null
    if (ondrain) ondrain()
    cb(null)
  }

  _write(data, cb) {
    if (this.reverse.push(data) === false) {
      this.reverse._ondrain = cb
    } else {
      cb(null)
    }
  }

  _final(cb) {
    this.reverse.push(null)
    cb(null)
  }
}
const sodium = require('sodium-universal')
const curve = require('noise-curve-ed')
const Noise = require('noise-handshake')
const b4a = require('b4a')

const EMPTY = b4a.alloc(0)

module.exports = class Handshake {
  constructor(isInitiator, keyPair, remotePublicKey, pattern) {
    this.isInitiator = isInitiator
    this.keyPair = keyPair
    this.noise = new Noise(pattern, isInitiator, keyPair, { curve })
    this.noise.initialise(EMPTY, remotePublicKey)
    this.destroyed = false
  }

  static keyPair(seed) {
    const publicKey = b4a.alloc(32)
    const secretKey = b4a.alloc(64)
    if (seed) sodium.crypto_sign_seed_keypair(publicKey, secretKey, seed)
    else sodium.crypto_sign_keypair(publicKey, secretKey)
    return { publicKey, secretKey }
  }

  recv(data) {
    try {
      this.noise.recv(data)
      if (this.noise.complete) return this._return(null)
      return this.send()
    } catch {
      this.destroy()
      return null
    }
  }

  // note that the data returned here is framed so we don't have to do an extra copy
  // when sending it...
  send() {
    try {
      const data = this.noise.send()
      const wrap = b4a.allocUnsafe(data.byteLength + 3)

      writeUint24le(data.byteLength, wrap)
      wrap.set(data, 3)

      return this._return(wrap)
    } catch {
      this.destroy()
      return null
    }
  }

  destroy() {
    if (this.destroyed) return
    this.destroyed = true
  }

  _return(data) {
    const tx = this.noise.complete ? b4a.toBuffer(this.noise.tx) : null
    const rx = this.noise.complete ? b4a.toBuffer(this.noise.rx) : null
    const hash = this.noise.complete ? b4a.toBuffer(this.noise.hash) : null
    const remotePublicKey = this.noise.complete ? b4a.toBuffer(this.noise.rs) : null

    return {
      data,
      remotePublicKey,
      hash,
      tx,
      rx
    }
  }
}

function writeUint24le(n, buf) {
  buf[0] = n & 255
  buf[1] = (n >>> 8) & 255
  buf[2] = (n >>> 16) & 255
}
{
  "name": "@hyperswarm/secret-stream",
  "version": "6.9.1",
  "description": "Secret stream backed by Noise and libsodium's secretstream",
  "main": "index.js",
  "files": [
    "index.js",
    "lib/**.js"
  ],
  "dependencies": {
    "b4a": "^1.1.0",
    "hypercore-crypto": "^3.3.1",
    "noise-curve-ed": "^2.0.1",
    "noise-handshake": "^4.0.0",
    "sodium-secretstream": "^1.1.0",
    "sodium-universal": "^5.0.0",
    "streamx": "^2.14.0",
    "timeout-refresh": "^2.0.0",
    "unslab": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "udx-native": "^1.13.2"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check .",
    "test": "brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/hyperswarm-secret-stream.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/hyperswarm-secret-stream/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperswarm-secret-stream"
}
{
  "name": "@ipld/dag-cbor",
  "version": "9.2.7",
  "description": "JS implementation of DAG-CBOR",
  "author": "Rod <rod@vagg.org> (http://r.va.gg/)",
  "license": "Apache-2.0 OR MIT",
  "homepage": "https://github.com/ipld/js-dag-cbor#readme",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/ipld/js-dag-cbor.git"
  },
  "bugs": {
    "url": "https://github.com/ipld/js-dag-cbor/issues"
  },
  "publishConfig": {
    "access": "public",
    "provenance": true
  },
  "keywords": [
    "ipfs",
    "ipld",
    "multiformats"
  ],
  "type": "module",
  "types": "./dist/src/index.d.ts",
  "typesVersions": {
    "*": {
      "*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ],
      "src/*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ]
    }
  },
  "files": [
    "src",
    "dist",
    "!dist/test",
    "!**/*.tsbuildinfo"
  ],
  "exports": {
    ".": {
      "types": "./dist/src/index.d.ts",
      "import": "./src/index.js",
      "module-sync": "./src/index.js"
    }
  },
  "release": {
    "branches": [
      "master"
    ],
    "plugins": [
      [
        "@semantic-release/commit-analyzer",
        {
          "preset": "conventionalcommits",
          "releaseRules": [
            {
              "breaking": true,
              "release": "major"
            },
            {
              "revert": true,
              "release": "patch"
            },
            {
              "type": "feat",
              "release": "minor"
            },
            {
              "type": "fix",
              "release": "patch"
            },
            {
              "type": "docs",
              "release": "patch"
            },
            {
              "type": "test",
              "release": "patch"
            },
            {
              "type": "deps",
              "release": "patch"
            },
            {
              "scope": "no-release",
              "release": false
            }
          ]
        }
      ],
      [
        "@semantic-release/release-notes-generator",
        {
          "preset": "conventionalcommits",
          "presetConfig": {
            "types": [
              {
                "type": "feat",
                "section": "Features"
              },
              {
                "type": "fix",
                "section": "Bug Fixes"
              },
              {
                "type": "chore",
                "section": "Trivial Changes"
              },
              {
                "type": "docs",
                "section": "Documentation"
              },
              {
                "type": "deps",
                "section": "Dependencies"
              },
              {
                "type": "test",
                "section": "Tests"
              }
            ]
          }
        }
      ],
      "@semantic-release/changelog",
      "@semantic-release/npm",
      "@semantic-release/github",
      [
        "@semantic-release/git",
        {
          "assets": [
            "CHANGELOG.md",
            "package.json"
          ]
        }
      ]
    ]
  },
  "scripts": {
    "clean": "aegir clean",
    "lint": "aegir lint",
    "build": "aegir build",
    "release": "aegir release",
    "test": "npm run lint && aegir test",
    "test:ts": "npm run test --prefix test/ts-use",
    "test:node": "aegir test -t node --cov",
    "test:chrome": "aegir test -t browser --cov",
    "test:chrome-webworker": "aegir test -t webworker",
    "test:firefox": "aegir test -t browser -- --browser firefox",
    "test:firefox-webworker": "aegir test -t webworker -- --browser firefox",
    "test:electron-main": "aegir test -t electron-main",
    "dep-check": "aegir dep-check"
  },
  "dependencies": {
    "cborg": "^5.0.1",
    "multiformats": "^13.1.0"
  },
  "devDependencies": {
    "@ipld/garbage": "^6.0.0",
    "aegir": "^48.0.1"
  }
}
import * as cborg from 'cborg'
import { CID } from 'multiformats/cid'

// https://github.com/ipfs/go-ipfs/issues/3570#issuecomment-273931692
const CID_CBOR_TAG = 42

/**
 * @template T
 * @typedef {import('multiformats/codecs/interface').ByteView<T>} ByteView
 */

/**
 * @template T
 * @typedef {import('multiformats/codecs/interface').ArrayBufferView<T>} ArrayBufferView
 */

/**
 * @template T
 * @param {ByteView<T> | ArrayBufferView<T>} buf
 * @returns {ByteView<T>}
 */
export function toByteView (buf) {
  if (buf instanceof ArrayBuffer) {
    return new Uint8Array(buf, 0, buf.byteLength)
  }

  return buf
}

/**
 * cidEncoder will receive all Objects during encode, it needs to filter out
 * anything that's not a CID and return `null` for that so it's encoded as
 * normal.
 *
 * @param {any} obj
 * @returns {cborg.Token[]|null}
 */
function cidEncoder (obj) {
  if (obj.asCID !== obj && obj['/'] !== obj.bytes) {
    return null // any other kind of object
  }
  const cid = CID.asCID(obj)
  /* c8 ignore next 4 */
  // very unlikely case, and it'll probably throw a recursion error in cborg
  if (!cid) {
    return null
  }
  const bytes = new Uint8Array(cid.bytes.byteLength + 1)
  bytes.set(cid.bytes, 1) // prefix is 0x00, for historical reasons
  return [
    new cborg.Token(cborg.Type.tag, CID_CBOR_TAG),
    new cborg.Token(cborg.Type.bytes, bytes)
  ]
}

// eslint-disable-next-line jsdoc/require-returns-check
/**
 * Intercept all `undefined` values from an object walk and reject the entire
 * object if we find one.
 *
 * @returns {null}
 */
function undefinedEncoder () {
  throw new Error('`undefined` is not supported by the IPLD Data Model and cannot be encoded')
}

/**
 * Intercept all `number` values from an object walk and reject the entire
 * object if we find something that doesn't fit the IPLD data model (NaN &
 * Infinity).
 *
 * @param {number} num
 * @returns {null}
 */
function numberEncoder (num) {
  if (Number.isNaN(num)) {
    throw new Error('`NaN` is not supported by the IPLD Data Model and cannot be encoded')
  }
  if (num === Infinity || num === -Infinity) {
    throw new Error('`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded')
  }
  return null
}

/**
 * @param {Map<any, any>} map
 * @returns {null}
 */
function mapEncoder (map) {
  for (const key of map.keys()) {
    if (typeof key !== 'string' || key.length === 0) {
      throw new Error('Non-string Map keys are not supported by the IPLD Data Model and cannot be encoded')
    }
  }
  return null
}

const _encodeOptions = {
  float64: true,
  typeEncoders: {
    Map: mapEncoder,
    Object: cidEncoder,
    undefined: undefinedEncoder,
    number: numberEncoder
  }
}

export const encodeOptions = {
  ..._encodeOptions,
  typeEncoders: {
    ..._encodeOptions.typeEncoders
  }
}

/**
 * @param {import('cborg').TagDecodeControl} decode
 * @returns {CID}
 */
function cidDecoder (decode) {
  const bytes = /** @type {Uint8Array} */ (decode())
  if (bytes[0] !== 0) {
    throw new Error('Invalid CID for CBOR tag 42; expected leading 0x00')
  }
  return CID.decode(bytes.subarray(1)) // ignore leading 0x00
}

const _decodeOptions = {
  allowIndefinite: false,
  coerceUndefinedToNull: true,
  allowNaN: false,
  allowInfinity: false,
  allowBigInt: true, // this will lead to BigInt for ints outside of
  // safe-integer range, which may surprise users
  strict: true,
  useMaps: false,
  rejectDuplicateMapKeys: true,
  /** @type {{ [tagNumber: number]: import('cborg').TagDecoder }} */
  tags: { [CID_CBOR_TAG]: cidDecoder }
}

export const decodeOptions = {
  ..._decodeOptions,
  tags: { ..._decodeOptions.tags }
}

export const name = 'dag-cbor'
export const code = 0x71

/**
 * @template T
 * @param {T} node
 * @returns {ByteView<T>}
 */
export const encode = (node) => cborg.encode(node, _encodeOptions)

/**
 * @template T
 * @param {ByteView<T> | ArrayBufferView<T>} data
 * @returns {T}
 */
export const decode = (data) => cborg.decode(toByteView(data), _decodeOptions)
const Cache = require('xache')

module.exports = class AdaptiveTimeout {
  constructor(opts = {}) {
    this._cache = new Cache({
      maxSize: opts.maxSize || 65536,
      maxAge: opts.maxAge || 10 * 60 * 1000 // 10 minutes
    })
    this._fallback = opts.fallback || AdaptiveTimeout.TimeoutExponential
    this._min = opts.min ?? 300
    this._max = opts.max || 4000
    this._jitter = opts.jitter ?? 256
  }

  // Default - aggressive ramp
  static TimeoutAggressive = [500, 750, 1000, 1500, 2000]

  // Linear - steady increase
  static TimeoutLinear = [500, 1000, 1500, 2000, 2500]

  // Exponential - slow start, rapid backoff
  static TimeoutExponential = [250, 500, 1000, 2000, 4000]

  // Gentle - conservative, patient
  static TimeoutGentle = [1000, 1250, 1500, 1750, 2000]

  // Fast - rapid fire retries
  static TimeoutFast = [200, 400, 600, 800, 1000]

  // U-shape - long, short, long
  static TimeoutUShape = [1500, 750, 500, 750, 1500]

  // Inverse U - short, long, short
  static TimeoutInverseU = [500, 1000, 1500, 1000, 500]

  // Sawtooth - alternating fast/slow
  static TimeoutSawtooth = [500, 1500, 500, 1500, 500]

  // Plateau - quick ramp then steady
  static TimeoutPlateau = [500, 1000, 2000, 2000, 2000]

  // Logarithmic - diminishing increases
  static TimeoutLogarithmic = [500, 1000, 1300, 1500, 1600]

  getValue(key) {
    return this._cache.get(key)
  }

  put(key, value) {
    let p = this._cache.get(key)

    if (!p) {
      p = { avg: value, variance: value >> 1 }
    } else {
      // blend 75% old + 25% new deviation
      p.variance += (Math.abs(p.avg - value) - p.variance) >> 2
      // blend 87.5% old + 12.5% new sample
      p.avg += (value - p.avg) >> 3
    }

    this._cache.set(key, p)

    return p
  }

  get(key, attempt = 1) {
    const p = this._cache.get(key)
    const jitter = (Math.random() * this._jitter) | 0

    if (p) {
      // known - use adaptive with linear backoff
      const base = p.avg + (p.variance << 1)
      const backoff = base * attempt
      return Math.min(Math.max(backoff + jitter, this._min), this._max)
    } else {
      // unknown - use aggressive fallback
      const base = this._fallback[Math.min(attempt - 1, this._fallback.length - 1)]
      return base + jitter
    }
  }

  has(key) {
    return this._cache.has(key)
  }

  delete(key) {
    return this._cache.delete(key)
  }

  clear() {
    this._cache.clear()
  }
}
{
  "name": "adaptive-timeout",
  "version": "1.0.1",
  "description": "adaptive-timeout",
  "main": "index.js",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    }
  },
  "files": [
    "package.json",
    "index.js",
    "index.d.ts"
  ],
  "devDependencies": {
    "brittle": "^3.19.0",
    "lunte": "^1.2.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && lunte && brittle-bare test/index.js",
    "lint": "lunte"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/adaptive-timeout.git"
  },
  "author": "Holepunch Inc",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/adaptive-timeout/issues"
  },
  "homepage": "https://github.com/holepunchto/adaptive-timeout",
  "dependencies": {
    "xache": "^1.2.1"
  }
}
export { DidPeer, DidPeerRouter, ANNOUNCE_PROTOCOL, RPC_PROTOCOL } from './lib/did-peer.js'
// DidPeer — the corrected, direction-free P2P primitive for an atproto DID's data (repo + firehose
// Hypercores), extracted from atproto-bridge as a shared module (audited vs keet + holepunch,
// 2026-07-13). A DID's data lives in a swarm keyed by discoveryTopic(did); every participant —
// signing device, availability relay/seedbox, read/HTTP bridge, favela client — is the SAME primitive.
// It is NOT a "front the origin by serverKey" client: it replicates the DID's cores from WHOEVER has
// them and serves the freshest commit that VERIFIES against the DID key.
//
// Corrections baked in (see atproto-bridge memory/feedback_p2p-no-directionality-event-driven):
//  - ANNOUNCE, don't DERIVE / get-coords-PULL: on connect a holder PUSHES {repoKey,firehoseKey,lengths}
//    over a protomux channel (one-mux-per-connection, keet model). No round-trip, no serverKey.
//  - EVENT-DRIVEN head reconciliation: the served head re-derives on the firehose core's 'append'
//    (fires on local append AND on replicated download) — never a data poll.
//  - Auth mandatory: the DID topic is unauthenticated in ANY discovery scheme; trust comes from
//    verifying the served repo's signed commit against the DID signing key (verifyKey).
//
// Transport-agnostic: the CONSUMER owns the swarm (joins discoveryTopic(did), and on each 'connection'
// calls didPeer.attach(conn)). The consumer also supplies verifyKey (resolve from the DID doc / PLC).

import b4a from 'b4a'
import c from 'compact-encoding'
import Protomux from 'protomux'
import ProtomuxRPC from 'protomux-rpc'
import { RepoStore } from 'atproto-store/lib/repo-store.js'
import { FirehoseSequencer } from 'atproto-store/lib/sequencer.js'
import { decodeCommitFrame, syncFrame } from 'atproto-store/lib/firehose.js'
import { repoDiffSince } from 'atproto-store/lib/repo-diff.js'
import { getRepoFromCommit, getRecord as rvGetRecord, listRecords as rvListRecords } from 'atproto-store/lib/read-view.js'
import { readCar, loadCommit, decodeBlock, listRecords as carListRecords } from 'atproto-repo/lib/repo.js'
import { verifyCommit, commitCid } from 'atproto-repo/lib/commit.js'

const ANNOUNCE_PROTOCOL = 'atproto/did-announce/v1'
// The peer's application RPC (write/session/blob relay). Opened by DidPeerRouter ONE-per-connection when
// `{ rpc: true }` — the freshest front borrows it. MUST match hyper-proto-peer's serve RPC protocol.
export const RPC_PROTOCOL = 'hyper-proto-peer/rpc/v1'
const toKey = (k) => (b4a.isBuffer(k) ? k : b4a.from(k, 'hex'))

// Reject a promise if it doesn't settle within ms (bounds the router's staleness nudge on a degraded link).
export function withTimeout (p, ms) {
  return new Promise((resolve, reject) => {
    const t = setTimeout(() => reject(new Error('rpc timeout')), ms)
    p.then((v) => { clearTimeout(t); resolve(v) }, (e) => { clearTimeout(t); reject(e) })
  })
}

export class DidPeer {
  // corestore: a Corestore (cores are global by key). did: the DID. verifyKey: its signing pubkey
  // (Uint8Array) — REQUIRED to accept a served head. onHead: (head) => void on every NEW verified
  // head. onError: optional (err) => void.
  constructor (corestore, { did, verifyKey, handle = null, onHead = null, onError = null, noRepo = false } = {}) {
    if (!corestore) throw new Error('DidPeer: corestore required')
    if (!did) throw new Error('DidPeer: did required')
    if (!verifyKey) throw new Error('DidPeer: verifyKey (DID signing pubkey) required — auth is mandatory')
    this.corestore = corestore
    this.did = did
    this.verifyKey = verifyKey
    this.handle = handle
    this._onHead = onHead
    this._onError = onError
    // noRepo: follow the firehose ONLY (verified head + tail ops) and DO NOT open/replicate the repo core.
    // Records come from elsewhere (the shared content-addressed OverlayRepoStore, co-located with the
    // producer). This is the "one copy" consumer: no duplicate repo-core replica. getRepo/getRecord/
    // listRecords return null/[]/throw (this.repo stays null) — the caller reads records from the store.
    this._noRepo = !!noRepo
    this.repo = null
    this.seq = null
    // Optional write/session/blob RPC to the peer (peer-signs-over-RPC). Set by DidPeerRouter from the
    // per-connection ProtomuxRPC when the router runs with `{ rpc: true }`. Null for a read-only consumer
    // (favela) — the keyless read surface below needs no RPC.
    //
    // A SET, not a slot. A front is keyed by firehoseKey, but the key HOLDER and every keyless SEEDER
    // announce the SAME core key, so a single slot was won by whoever announced last — and a seeder answers
    // `UNKNOWN_METHOD: Unknown method 'get-blob'` because it serves no application RPC at all. That is the
    // favela getBlob failure and e2jev's intermittent images. `rpc` stays a property (assignment still
    // works, and consumers still read it) but is now backed by the candidate list.
    this._rpcs = []
    this._repoKey = null
    this._firehoseKey = null
    this._channels = new Set()
    this.head = null
    this._opening = null
  }

  // Every _call below is reached from inside an HTTP request handler in atproto-bridge. Without a
  // deadline an hpp that is alive-but-wedged hangs that request forever — no 504, no log, nothing
  // to restart (hyper-social #47). protomux-rpc defaults timeout=-1 and only arms its timer when
  // timeout > 0, so the value MUST be passed explicitly; there is no useful transport default.
  //
  // 30s covers a P2P round trip with a wide margin while still bounding a wedge. Bulk transfers
  // (whole-CAR pull, blob upload) get their own budget at the call site — they are legitimately
  // slow, and clamping them to the interactive default would break large repos and uploads.
  static DEFAULT_RPC_TIMEOUT_MS = 30_000
  static BULK_RPC_TIMEOUT_MS = 120_000

  // ---- application RPC candidates ----
  // `rpc` reads as the preferred LIVE candidate and assigning to it adds one (or clears the set with null),
  // so every existing caller — `if (!this.rpc) throw`, `peer.rpc = entry.rpc`, `f.rpc && !f.rpc.closed` —
  // keeps working unchanged against a set.
  get rpc () { const live = this._liveRpcs(); return live.length ? live[0] : null }
  set rpc (v) { if (v) this.addRpc(v); else this._rpcs = [] }

  addRpc (rpc) { if (rpc && !this._rpcs.includes(rpc)) this._rpcs.push(rpc) }
  _liveRpcs () { this._rpcs = this._rpcs.filter((r) => r && !r.closed); return this._rpcs }

  // Try each candidate until one ANSWERS. Only a "wrong peer" / "dead link" failure moves on:
  //  - UNKNOWN_METHOD    the peer serves no such method (a seeder, not the holder) -> try the next
  //  - CHANNEL_CLOSED/DESTROYED  the link died -> try the next
  //  - TIMEOUT_EXCEEDED  ambiguous: retried for READS only, never for a write (a request that may have
  //                      been applied must not be replayed against another peer)
  // Anything else is the peer ANSWERING with a real error (REQUEST_ERROR: "blob not found",
  // "unauthorized"); surfacing that beats masking it behind a retry.
  async _call (method, params, { readOnly = false, timeoutMs = DidPeer.DEFAULT_RPC_TIMEOUT_MS } = {}) {
    const cands = this._liveRpcs()
    if (!cands.length) throw new Error('DidPeer: no write RPC (read-only front)')
    const nextOn = new Set(['UNKNOWN_METHOD', 'CHANNEL_CLOSED', 'CHANNEL_DESTROYED'])
    if (readOnly) nextOn.add('TIMEOUT_EXCEEDED')
    let last = null
    for (let i = 0; i < cands.length; i++) {
      const rpc = cands[i]
      try {
        // The deadline is DELEGATED to protomux-rpc, not raced locally: its _ontimeout also deletes
        // the pending entry from `_requests` (protomux-rpc/index.js:161-168). A Promise.race wrapper
        // would settle us and leak that entry for the life of the channel.
        const res = await rpc.request(method, params, { timeout: timeoutMs })
        // Sticky: the peer that answered goes to the front so later calls do not re-pay the failed hops.
        if (i > 0) { this._rpcs = [rpc, ...this._rpcs.filter((r) => r !== rpc)] }
        return res
      } catch (e) {
        last = e
        if (!nextOn.has(e && e.code)) throw e
      }
    }
    throw last
  }

  // This node HOLDS the cores (a signing device, a relay that already seeded, or a bootstrap). Open
  // them so we can serve + announce. Idempotent.
  async provide ({ repoKey, firehoseKey } = {}) { return this._openCores(repoKey, firehoseKey) }

  // Re-open a repo core for a front that went back to PROJECTING after a stateless spell. The router
  // drops the replica when a peer announces repoKey:null; without this the drop is ONE-WAY, so a peer
  // that resumes projecting stays repo-less for the life of the process — permanently on the slower
  // derive path. Observed: rolling projectRepoCore back to true did NOT heal the cached front.
  async adoptRepoKey (repoKey) {
    if (this._noRepo || this.repo || !repoKey) return false
    // CRITICAL: during the INITIAL _openCores, this.repo is null while the open is in flight. Without
    // this guard a second announce arriving mid-open races it and opens a COMPETING repo core for the
    // same front — which deterministically broke the co-owned freshest-by-rev test (the ahead co-owner
    // was never fronted). Only adopt for a front that is already established (seq open, nothing opening).
    if (this._opening || !this.seq) return false
    this._repoKey = toKey(repoKey)
    this.repo = await new RepoStore(this.corestore, { key: this._repoKey }).ready()
    try { this.repo.core.download({ start: 0, end: -1 }) } catch {}
    this._derived = null // the derive cache is now redundant; the core is authoritative
    this._derivedAt = null
    return true
  }

  async _openCores (repoKey, firehoseKey) {
    if (this.seq) return // firehose is opened in BOTH modes; the idempotency guard (repo may stay null under noRepo)
    if (this._opening) return this._opening
    this._opening = (async () => {
      // repoKey is OPTIONAL now. A peer running the stateless virtual device (serve-membrane
      // projectRepoCore:false) publishes no membrane-repo core at all — record bytes exist only as the
      // content-addressed files, and the repo is DERIVED on demand via the get-repo-car RPC (see
      // getRepo below). Requiring repoKey here is what previously made such a peer un-frontable.
      this._repoKey = repoKey ? toKey(repoKey) : null
      this._firehoseKey = toKey(firehoseKey)
      // noRepo: skip the repo core entirely — never opened, so corestore.replicate never syncs it (no replica).
      if (!this._noRepo && this._repoKey) this.repo = await new RepoStore(this.corestore, { key: this._repoKey }).ready()
      this.seq = await new FirehoseSequencer(this.corestore.get({ key: this._firehoseKey })).ready()
      // FULL seed so this node can serve the cores to others (download all + follow appends) — this is
      // the "each peer seeds" torrent behaviour; a read-only consumer that does NOT want to seed can
      // subclass/override, but seeding-by-default is the P2P-native contribution posture.
      // ONE live download range per core: end:-1 downloads all current blocks AND follows future appends
      // (verified), so a single call is sufficient. The prior form re-ran `core.download({0,-1})` inside a
      // `core.on('append', …)` listener — every append minted a NEW, never-destroyed [0,-1] RangeRequest and
      // added another append listener, an UNBOUNDED range/listener leak that a re-authoring or ballooning
      // producer turned into runaway replication churn (the ~100MB/s "never settles" amplifier).
      const seed = (core) => { try { core.download({ start: 0, end: -1 }) } catch {} }
      if (this.repo) seed(this.repo.core)
      seed(this.seq.core)
      // EVENT-DRIVEN: re-derive the served head on every firehose append (local or replicated), and
      // re-announce the new length to connected peers. No poll loop.
      this.seq.core.on('append', () => { this._reconcile(); this._announceAll() })
      await this._reconcile()
    })()
    try { await this._opening } finally { this._opening = null }
  }

  // Wire a swarm connection: replicate the corestore + open the announce channel. Symmetric — both
  // sides call attach(); whoever HOLDS the cores announces, whoever lacks them learns from the announce.
  attach (conn) {
    try { this.corestore.replicate(conn) } catch (e) { this._fail(e) }
    const mux = Protomux.from(conn)
    const chan = mux.createChannel({
      protocol: ANNOUNCE_PROTOCOL,
      onopen: () => { if (this.seq) this._announceTo(chan) }, // ANNOUNCE-PUSH on open
      onclose: () => this._channels.delete(chan)
    })
    if (!chan) return // already open on this mux
    chan._announce = chan.addMessage({
      encoding: c.json,
      onmessage: (a) => this.onAnnounce(a).catch((e) => this._fail(e))
    })
    chan.open()
    this._channels.add(chan)
    if (this.seq) this._announceTo(chan)
  }

  // Does this peer currently hold (and can serve/seed) the DID's cores?
  // We HOLD a DID once the firehose (the signed-commit trust anchor) is open. Previously this keyed
  // off the repo core, so a stateless peer — which publishes no repo core — read as holding nothing.
  get holds () { return !!this.seq }

  // Send this peer's announce over a protomux message (used by DidPeerRouter's shared per-connection
  // channel, where a single channel is multiplexed across many DIDs).
  announceVia (message) {
    if (!this.seq || !message) return
    try {
      message.send({
        did: this.did,
        repoKey: this._repoKey ? b4a.toString(this._repoKey, 'hex') : null,
        firehoseKey: b4a.toString(this._firehoseKey, 'hex'),
        repoLength: this.repo ? this.repo.core.length : null,
        firehoseLength: this.seq.core.length
      })
    } catch (e) { this._fail(e) }
  }

  _announceTo (chan) {
    if (!this.seq || !chan._announce) return
    try {
      chan._announce.send({
        did: this.did,
        repoKey: this._repoKey ? b4a.toString(this._repoKey, 'hex') : null,
        firehoseKey: b4a.toString(this._firehoseKey, 'hex'),
        repoLength: this.repo ? this.repo.core.length : null,
        firehoseLength: this.seq.core.length
      })
    } catch (e) { this._fail(e) }
  }

  _announceAll () { for (const chan of this._channels) this._announceTo(chan) }

  async onAnnounce (a) {
    // repoKey is OPTIONAL — a stateless peer announces { firehoseKey, repoKey: null }. The firehose is
    // the load-bearing half (it carries the SIGNED commits, i.e. the trust anchor); the repo is either
    // replicated, read from co-located files, or derived over RPC.
    if (!a || a.did !== this.did || !a.firehoseKey) return
    if (!this.seq) {
      await this._openCores(a.repoKey, a.firehoseKey)
      this._announceAll() // we can help seed now — tell peers we have them too (symmetric)
    }
    // The announce is a HINT (peer says its firehose is at length N). Replication pushes the blocks;
    // we react to the 'append' event to reconcile. One-shot update() nudges the fetch (event-triggered
    // on announce, NOT a poll loop).
    if (this.seq) this.seq.core.update().catch(() => {})
  }

  // The served head = the freshest signed commit that VERIFIES against the DID key. Re-derived on
  // firehose 'append'. Rejects an unverifiable head (can't be tricked into serving a forged repo).
  async _reconcile () {
    if (!this.seq || this.seq.core.length === 0) return
    try {
      const { body } = decodeCommitFrame(await this.seq.core.get(this.seq.core.length - 1))
      const signed = loadCommit(await readCar(body.blocks)).value
      if (!verifyCommit(signed, this.verifyKey)) return
      const rev = signed.rev
      if (this.head && this.head.rev === rev) return // no change
      this.head = { rev, cid: commitCid(signed).toString(), signed }
      if (this._onHead) this._onHead(this.head)
    } catch (e) { this._fail(e) }
  }

  _fail (e) { if (this._onError) this._onError(e) }

  // ---- keyless read surface (from the replicated repo/firehose; no signing) ----
  // Wait until a verified head exists (cores replicated + a commit that verifies against the DID key).
  async ready ({ timeout = 20000 } = {}) {
    if (this.head) return this.head
    const end = Date.now() + timeout
    while (Date.now() < end) {
      if (this.head) return this.head
      await new Promise((r) => setTimeout(r, 100))
    }
    return null
  }

  // com.atproto.sync.getRepo -> keyless signed CAR (records rebuilt from the replicated repo, signature
  // from the verified firehose commit; getRepoFromCommit guards data-root integrity).
  // `since` (com.atproto.sync.getRepo?since) — the PARTIAL CAR. Answered from the REPLICATED FIREHOSE,
  // which every front already holds in both modes (_openCores opens `seq` whether or not there is a repo
  // core), so this needs no RPC to the peer, no new storage and no change to hpp. Each #commit frame
  // carries the blocks that were new at that commit; the union over the frames newer than `since` is the
  // diff. See atproto-store/lib/repo-diff.js for the coverage proof and its refusals.
  //
  // The result ALWAYS declares what happened: `partial` and `sinceHonoured` are set explicitly, and a
  // refusal falls back to the full CAR with a `reason`. A caller must never have to infer from the bytes
  // which one it got — inferring is what "accepted and ignored" made everyone do.
  async getRepo (opts) {
    if (!this.head) throw new Error(`DidPeer: no verified head yet for ${this.did}`)
    const since = opts && typeof opts === 'object' ? (opts.since || null) : null
    if (since) {
      const diff = await this._repoDiffSince(since)
      if (diff) return diff
      // fall through to the full CAR, with the refusal reported by the caller
    }
    if (this.repo) {
      const full = await getRepoFromCommit(this.repo, this.head.signed)
      return { ...full, partial: false, sinceHonoured: since ? false : null, since, reason: since ? this._sinceRefusal : null }
    }
    // STATELESS PEER: no membrane-repo core to rebuild from, because the peer derives the CAR from its
    // record FILES instead of projecting them (serve-membrane projectRepoCore:false). Ask for it.
    //
    // The trust model does NOT relax. With a repo core we rebuild the MST locally and getRepoFromCommit
    // asserts it matches the verified commit; here the CAR arrives whole, so we re-establish the same
    // guarantee by verifying the commit INSIDE it against the DID key and refusing anything older than
    // the head we already verified off the firehose. A peer that serves a forged or rolled-back repo is
    // rejected exactly as before — we never serve bytes we have not authenticated.
    if (!this.rpc) throw new Error(`DidPeer: ${this.did} has no repo core and no RPC to derive one`)
    const r = await this._call('get-repo-car', {}, { readOnly: true, timeoutMs: DidPeer.BULK_RPC_TIMEOUT_MS })
    if (!r || !r.car) throw new Error(`DidPeer: ${this.did} served no CAR`)
    const carBytes = b4a.from(r.car, 'hex')
    const signed = loadCommit(await readCar(carBytes)).value
    if (!verifyCommit(signed, this.verifyKey)) throw new Error(`DidPeer: derived CAR commit does not verify for ${this.did}`)
    if (signed.rev < this.head.rev) throw new Error(`DidPeer: derived CAR is older than the verified head (${signed.rev} < ${this.head.rev})`)
    return { carBytes, commitCid: commitCid(signed), dataCid: signed.data, partial: false, sinceHonoured: since ? false : null, since, reason: since ? this._sinceRefusal : null }
  }

  // The partial CAR, or null when we cannot prove one is complete. Never throws: a coverage failure is a
  // normal answer here (the caller serves the full repo instead), not an error, and turning it into one
  // would take down a getRepo that has a perfectly good full answer available.
  //
  // We pass the head's CID — derived from the commit VERIFIED against the DID key — and let repo-diff
  // LOCATE those bytes in the firehose rather than handing them over. That is deliberately stricter: a
  // CAR rooted at a commit the firehose does not carry cannot be walked by anyone, so a head we cannot
  // find is a refusal instead of a block we synthesise. It also keeps a dag-cbor dependency out of this
  // package, which has none and is a symlinked sibling.
  async _repoDiffSince (since) {
    this._sinceRefusal = null
    if (!this.seq) { this._sinceRefusal = 'no firehose replicated for this DID'; return null }
    try {
      const r = await repoDiffSince({
        getFrame: (i) => this.seq.core.get(i),
        length: this.seq.core.length,
        since,
        headCommitCid: commitCid(this.head.signed),
        headRev: this.head.rev
      })
      if (!r || !r.ok) { this._sinceRefusal = (r && r.reason) || 'could not assemble a diff'; return null }
      return {
        carBytes: r.carBytes,
        commitCid: commitCid(this.head.signed),
        dataCid: this.head.signed.data,
        partial: true,
        sinceHonoured: true,
        since,
        fromRev: r.fromRev,
        toRev: r.toRev,
        empty: !!r.empty,
        blocks: r.blocks
      }
    } catch (e) {
      this._sinceRefusal = 'diff assembly failed: ' + ((e && e.message) || String(e))
      return null
    }
  }

  // The record set for a peer with NO repo core, derived from the CAR getRepo() already fetches and
  // VERIFIES. Cached against the head rev, so N reads at one head cost ONE derive and the cache
  // invalidates the moment a new commit lands — no staleness, no per-read CAR fetch.
  //
  // Without this, getRecord/listRecords/collections returned null/[] whenever this.repo was null. That
  // was tolerable when the only repo-less mode was noRepo (favela, which reads records from the shared
  // store instead), but it silently broke com.atproto.repo.getRecord the moment a peer went STATELESS —
  // observed in production as RecordNotFound for a profile that was present and correctly served by
  // getRepo. The trust story is unchanged: these read out of the same verified CAR.
  async _derivedRecords () {
    if (!this.head) return []
    // Derive ONLY when it can actually work. A front with no repo core and no RPC (one still mid-open,
    // or a plain seeder) previously returned an empty list from these readers; making it THROW instead
    // changed observable behaviour for every such caller — it broke the co-owned freshest-by-rev test,
    // where a poller reading a not-yet-open front started erroring instead of reporting "nothing yet".
    if (!this.rpc) return []
    if (this._derivedAt === this.head.rev && this._derived) return this._derived
    const { carBytes } = await this.getRepo()
    const car = await readCar(carBytes)
    // listRecords already yields the record CID (the MST value), so nothing is recomputed and no
    // dag-cbor dependency is pulled in here — the CAR is the single source for key, cid and value.
    this._derived = carListRecords(car).map((r) => ({ key: r.key, value: r.value, cid: r.cid.toString() }))
    this._derivedAt = this.head.rev
    return this._derived
  }

  // com.atproto.repo.getRecord
  async getRecord (collection, rkey) {
    if (this.repo) return rvGetRecord(this.repo, collection, rkey, { did: this.did })
    if (this._noRepo) return null // records live in the consumer's own store, by design
    const key = collection + '/' + rkey
    const hit = (await this._derivedRecords()).find((r) => r.key === key)
    return hit ? { uri: `at://${this.did}/${key}`, cid: hit.cid, value: hit.value } : null
  }

  // com.atproto.repo.listRecords
  // Returns { records, cursor } per the lexicon. `limit`/`reverse`/`cursor` were dropped on the floor
  // here as well as in read-view, so a caller's paging parameters never reached anything that honoured
  // them. Both derived and repo-backed paths now page identically — a client must not get different
  // semantics depending on which internal path answered.
  async listRecords (collection, { limit = 50, reverse = false, cursor = null } = {}) {
    if (this.repo) return rvListRecords(this.repo, collection, { did: this.did, limit, reverse, cursor })
    if (this._noRepo) return { records: [], cursor: undefined }
    const n = Math.min(100, Math.max(1, Number(limit) || 50))
    const prefix = collection + '/'
    const all = (await this._derivedRecords())
      .filter((r) => r.key.startsWith(prefix))
      .map((r) => ({ rkey: r.key.slice(prefix.length), uri: `at://${this.did}/${r.key}`, cid: r.cid, value: r.value }))
    if (reverse) all.reverse()
    let start = 0
    if (cursor) {
      const i = all.findIndex((r) => r.rkey === cursor)
      start = i >= 0 ? i + 1 : all.length
    }
    const page = all.slice(start, start + n)
    const more = start + page.length < all.length
    const last = page.length ? page[page.length - 1].rkey : null
    return { records: page.map(({ uri, cid, value }) => ({ uri, cid, value })), cursor: more && last ? last : undefined }
  }

  // com.atproto.sync.getLatestCommit -> { cid, rev } from the verified head (keyless).
  getLatestCommit () {
    if (!this.head) return null
    return { cid: this.head.cid, rev: this.head.rev }
  }

  // com.atproto.sync.subscribeRepos -> the peer's own signed firehose frames (cursor=0 backfills).
  subscribeRepos (cursor = 0, opts) {
    if (!this.seq) throw new Error(`DidPeer: cores not open for ${this.did}`)
    return this.seq.subscribe(cursor, opts)
  }

  // com.atproto.sync.getRepoStatus -> a fronted peer we replicate + verified is active.
  getRepoStatus () { return { did: this.did, active: true, status: 'active' } }

  // com.atproto.repo.describeRepo -> { handle, did, didDoc, collections, handleIsCorrect }. Keyless:
  // did/handle come from the announce, collections from the replicated repo, didDoc a best-effort PLC
  // fetch (null on failure). doFetch: (url, opts) -> { status, body:Buffer } (the server's wrapper shape).
  async describeRepo ({ doFetch } = {}) {
    const collections = await this.collections()
    let didDoc = null
    try {
      if (doFetch) {
        const r = await doFetch(`https://plc.directory/${this.did}`, { method: 'GET' })
        if (r && r.status === 200 && r.body) didDoc = JSON.parse(r.body.toString())
      }
    } catch {}
    return { handle: this.handle || null, did: this.did, didDoc, collections, handleIsCorrect: !!this.handle }
  }

  // ---- write / session / blob relay (peer-signs-over-RPC) — the PEER holds the key + applies + signs;
  // this consumer never holds a key. Requires the router to run with `{ rpc: true }` (this.rpc set). The
  // signed result flows back on the peer's firehose (which this DidPeer already replicates + reconciles).
  applyWrite (op) { return this._call('apply-write', op) }
  applyWrites (op) { return this._call('apply-writes', op) }
  createSession ({ identifier, password } = {}) { return this._call('create-session', { identifier, password }) }
  refreshSession (refreshJwt) { return this._call('refresh-session', { refreshJwt }) }
  getServiceAuth ({ aud, lxm, token } = {}) { return this._call('get-service-auth', { aud, lxm, token }, { readOnly: true }) }
  getPreferences ({ token } = {}) { return this._call('get-preferences', { token }, { readOnly: true }) }
  putPreferences ({ preferences, token } = {}) { return this._call('put-preferences', { preferences, token }) }
  getBlob (cid) { return this._call('get-blob', { cid }, { readOnly: true }) }

  // The peer's published blob inventory (com.atproto.sync.listBlobs). Read-only, same gate as getBlob.
  // Returns { cids, cursor }. A peer too old to answer replies not-supported rather than erroring, so a
  // mixed-version fleet degrades to "orphans unchecked" instead of failing the whole call.
  listBlobs ({ limit, cursor } = {}) { return this._call('list-blobs', { limit, cursor }, { readOnly: true }) }
  uploadBlob ({ bytes, mimeType, token } = {}) { return this._call('upload-blob', { bytes, mimeType, token }, { timeoutMs: DidPeer.BULK_RPC_TIMEOUT_MS }) }

  // Decode a #commit frame BODY (from firehose.decodeFrame) into normalized ops with the changed record
  // INLINE — read from the frame's OWN CAR (body.blocks) keyed by op.cid, so it is race-free (does NOT
  // depend on the repo core having caught up). Returns [{ action, collection, rkey, record? }]; delete
  // ops omit record; create/update carry the decoded record (null if the block was absent). This keeps
  // the atproto CAR codec in the P2P-read layer — consumers (favela) get plain ops, no atproto-repo dep.
  static async commitOps (body) {
    if (!body || !Array.isArray(body.ops)) return []
    const needsCar = body.ops.some(o => (o.action === 'create' || o.action === 'update') && o.cid)
    let car = null
    if (needsCar && body.blocks) { try { car = await readCar(body.blocks) } catch { car = null } }
    const out = []
    for (const op of body.ops) {
      const path = op.path || ''
      const i = path.indexOf('/')
      if (i <= 0) continue
      const collection = path.slice(0, i)
      const rkey = path.slice(i + 1)
      if (op.action === 'delete') { out.push({ action: 'delete', collection, rkey }); continue }
      if (op.action === 'create' || op.action === 'update') {
        let record = null
        if (op.cid && car) { try { record = decodeBlock(car, op.cid) } catch { record = null } }
        out.push({ action: op.action, collection, rkey, record })
      }
    }
    return out
  }

  // Distinct collection NSIDs present in the replicated repo (keys are "<collection>/<rkey>").
  async collections () {
    const set = new Set()
    const rows = this.repo ? await this.repo.records() : (this._noRepo ? [] : await this._derivedRecords())
    for (const r of rows) {
      const i = r.key.indexOf('/')
      if (i > 0) set.add(r.key.slice(0, i))
    }
    return [...set]
  }

  status () {
    return {
      did: this.did,
      hasCores: !!this.repo,
      repoLength: this.repo ? this.repo.core.length : 0,
      firehoseLength: this.seq ? this.seq.core.length : 0,
      head: this.head ? { rev: this.head.rev, cid: this.head.cid } : null,
      channels: this._channels.size
    }
  }

  async close () {
    for (const chan of this._channels) { try { chan.close() } catch {} }
    this._channels.clear()
    if (this.seq) { try { await this.seq.close() } catch {} }
    if (this.repo) { try { await this.repo.close() } catch {} }
  }
}

// Multi-DID, co-owned-aware router over ONE shared corestore + swarm — the CANONICAL consumer primitive
// (unifies atproto-bridge's PeerRouter/PeerFront + favela's earlier single-front DidPeerRouter, per
// EXTRACTION-PLAN Phase 1). Fixes the per-DidPeer attach() channel collision (Protomux allows one channel
// per (protocol,id) per mux) by opening ONE announce channel per connection and dispatching by DID.
//
// Beyond that, it absorbs PeerRouter's co-owned handling: a DID can have MANY self-custody holders (wj62 =
// notary + co-owner; each announces the SAME did with its OWN membrane core keys — distinct keys, identical
// deterministic content, differing only in replication lag). We track a SET of fronts per DID (one per
// firehoseKey) and serve reads from the FRESHEST by commit REV (not frame count — a lagging co-owner can
// out-FRAME a fresher one; the wj62 prod symptom). Optional layers, all off by default (favela's read-only
// posture is `new DidPeerRouter(store)`):
//   swarm    — router OWNS it: auto-wires onconnection + a pull-only refresh/failover timer. Omit to drive
//              onconnection() yourself and join topics yourself (favela / tests).
//   join     — (did)=>void topic-join fn (bridge passes `d=>swarm.join(discoveryTopic(d),{...})`); keeps
//              atproto-identity OUT of this module's runtime deps.
//   fronted  — DIDs to allow-list immediately (bridge). resolveVerifyKey — async (did)=>pubkey fallback.
//   relay    — FleetRelay: fold the FRESHEST co-owner's firehose per DID (single source) + failover + #sync.
//   rpc      — open ONE protomux-rpc per connection (the write/session/blob relay); the front borrows it.
//   handles/onHandles — persist handle->did resolution across restarts.
export class DidPeerRouter {
  constructor (corestore, {
    swarm = null, fronted = [], relay = null, resolveVerifyKey = null, rpc = false, join = null,
    refreshMs = 10000, refreshTimeoutMs = 5000, staleFrontMs = 300000, continuityScan = 500,
    handles = {}, onHandles = null
  } = {}) {
    this.corestore = corestore
    this.swarm = swarm
    this.relay = relay
    this._resolveVerifyKey = resolveVerifyKey
    this._useRpc = !!rpc
    this._join = join
    this._refreshMs = refreshMs
    this._refreshTimeoutMs = refreshTimeoutMs
    // Age-out ceiling: a front whose peer has not announced for this long is dropped — but ONLY while a
    // live, verified sibling remains to serve the DID (see _ageOutFronts). 0 disables age-out.
    this._staleFrontMs = staleFrontMs
    // How many frames back the continuity walk will look for the head we already serve. 0 disables the
    // continuity gate entirely (freshest-by-rev only — the pre-0.2.8 behaviour).
    this._continuityScan = continuityScan

    this._peers = new Map()          // did -> primary DidPeer (backward-compat add()/get())
    this._fronts = new Map()         // did -> Map<fhKeyHex, DidPeer> (co-owned multi-front)
    this._byDid = new Map()          // did -> Map<fhKeyHex, { coords, conns: Map<conn, rpc|null> }>
                                     // MANY peers announce one (did, firehoseKey): the holder + every seeder
    this._opts = new Map()           // did -> { verifyKey, handle, onHead, onError } from add()
    this._verifyKeys = new Map()     // did -> Promise<pubkey>
    this._fronted = new Set(fronted)
    this._opening = new Map()        // "did|fhKeyHex" -> in-flight open promise
    this._waiters = new Map()        // did -> Set<fn> woken when ANY co-owner of that did lands
    this._lastAppend = new Map()     // did -> ts of last firehose 'append' (event-driven liveness)
    this._lastLive = new Map()       // "did|fhKeyHex" -> ts of that co-owner's last announce (age-out input)
    this._denied = new Map()         // did -> Set<fhKeyHex> evicted by an operator; a re-announce must NOT resurrect
    this._servedHead = new Map()     // did -> { rev, cid, fhKeyHex } the head reads currently resolve to
    this._continuity = new Map()     // "candCid|servedCid" -> bool (does the candidate chain from what we serve?)
    this._forkRejected = new Map()   // "did|fhKeyHex" -> count of times this front was rejected as off-line
    this._relaySourceKey = new Map() // did -> firehoseKeyHex currently folded into the relay
    this._handleToDid = new Map(Object.entries(handles || {}))
    this._onHandles = onHandles
    this._channels = new Set()

    if (this.swarm) {
      this._onconnbound = (conn) => this.onconnection(conn)
      this.swarm.on('connection', this._onconnbound)
    }
    for (const did of this._fronted) this._joinDid(did)
    if (this._refreshMs > 0 && (this.swarm || this.relay)) {
      this._refreshTimer = setInterval(() => { this._refreshFronts().catch(() => {}) }, this._refreshMs)
      if (this._refreshTimer && this._refreshTimer.unref) this._refreshTimer.unref()
    }
  }

  get (did) { return this._peers.get(did) || null }
  peers () { return [...this._peers.values()] }
  isFronted (did) { return !!did && this._fronted.has(did) }
  list () { return [...this._fronted] }
  resolveHandle (handle) { return this._handleToDid.get(handle) || null }

  _isCared (did) { return this._fronted.has(did) || this._peers.has(did) || this._opts.has(did) }
  _joinDid (did) { if (this._join) { try { this._join(did) } catch {} } }
  _wake (did) { const ws = this._waiters.get(did); if (ws) { this._waiters.delete(did); for (const fn of ws) fn() } }

  _setHandle (handle, did) {
    if (!handle || !did || this._handleToDid.get(handle) === did) return
    this._handleToDid.set(handle, did)
    if (this._onHandles) { try { this._onHandles(Object.fromEntries(this._handleToDid)) } catch {} }
  }

  // Cached DID->verifyKey. Per-DID add({verifyKey}) wins; else the injected resolver (PLC).
  _verifyKey (did) {
    const o = this._opts.get(did) || {}
    if (o.verifyKey) return Promise.resolve(o.verifyKey)
    if (!this._verifyKeys.has(did)) {
      if (!this._resolveVerifyKey) return Promise.reject(new Error(`DidPeerRouter: no verifyKey for ${did} (pass add(did,{verifyKey}) or {resolveVerifyKey})`))
      this._verifyKeys.set(did, Promise.resolve(this._resolveVerifyKey(did)))
    }
    return this._verifyKeys.get(did)
  }

  // Register a DID. With a verifyKey (favela) it eagerly creates + returns the primary DidPeer (its cores
  // load from the announce); without one (bridge allow-set) it just allow-lists + returns `this` (chainable,
  // verifyKey resolved lazily at front time). Idempotent.
  add (did, opts = {}) {
    this._fronted.add(did)
    if (opts.verifyKey || opts.onHead || opts.onError || opts.handle || opts.noRepo) {
      this._opts.set(did, { ...(this._opts.get(did) || {}), ...opts })
    }
    this._joinDid(did)
    const existing = this._peers.get(did)
    if (existing) return existing
    const o = this._opts.get(did) || {}
    if (!o.verifyKey) return this // bridge allow-set add (verifyKey lazy); return value unused/chainable
    const p = new DidPeer(this.corestore, { did, verifyKey: o.verifyKey, handle: o.handle || null, onHead: o.onHead || null, onError: o.onError || null, noRepo: o.noRepo })
    this._peers.set(did, p)
    for (const chan of this._channels) p.announceVia(chan._announce) // (re-add) announce if already held
    return p
  }

  // Wire ONE swarm connection: replicate the corestore ONCE, open ONE announce channel (+ one write RPC
  // when `{ rpc: true }`), and route each received announce by DID -> (did, firehoseKey) tracking.
  onconnection (conn) {
    try { this.corestore.replicate(conn) } catch {}
    const mux = Protomux.from(conn)
    let rpc = null
    if (this._useRpc) {
      try { rpc = new ProtomuxRPC(conn, { protocol: RPC_PROTOCOL, valueEncoding: c.json }); rpc.on('error', () => {}) } catch {}
    }
    const chan = mux.createChannel({
      protocol: ANNOUNCE_PROTOCOL,
      onopen: () => this._announceHeld(chan),
      onclose: () => this._channels.delete(chan)
    })
    if (!chan) return // already open on this mux
    chan._announce = chan.addMessage({
      encoding: c.json,
      onmessage: (a) => { this._onAnnounce(a, rpc, conn).catch(() => {}) }
    })
    chan.open()
    this._channels.add(chan)
    this._announceHeld(chan)
    conn.on('close', () => this._onConnClose(conn))
  }

  // Learn a (did, firehoseKey) co-owner from a PUSHED announce; open its front (best-effort). A DIFFERENT
  // firehoseKey under the same DID is a DISTINCT co-owner (tracked, never evicting the other).
  async _onAnnounce (a, rpc, conn) {
    // repoKey is OPTIONAL — same contract as DidPeer.onAnnounce. A peer running the stateless virtual
    // device (serve-membrane projectRepoCore:false) publishes no membrane-repo core and announces
    // { firehoseKey, repoKey: null }; its repo is DERIVED over the get-repo-car RPC. Requiring repoKey
    // HERE silently dropped that announce before it ever reached the DidPeer, so the peer went live:false
    // and was never fronted — the fix in DidPeer.onAnnounce alone was not enough, because the router
    // gates first. The firehose key is the only thing genuinely required: it is the trust anchor.
    if (!a || !a.did || !a.firehoseKey) return
    const did = a.did
    const fhKeyHex = a.firehoseKey
    if (a.handle) this._setHandle(a.handle, did)
    if (!this._isCared(did)) return
    // An operator-EVICTED co-owner must stay evicted. Without this, dropFront({forget:true}) is undone by
    // the offender's very next announce (peers re-announce on connect AND on every append), which is the
    // difference between an eviction an operator can rely on and one that lasts milliseconds.
    if (this._isDenied(did, fhKeyHex)) return
    this._lastLive.set(did + '|' + fhKeyHex, Date.now())
    if (!this._byDid.has(did)) this._byDid.set(did, new Map())
    // MANY peers announce the SAME (did, firehoseKey): the key holder AND every keyless seeder. Keep them
    // ALL — a single {conn, rpc} slot was overwritten by whoever announced last, so the front's application
    // RPC could end up pointed at a seeder that answers UNKNOWN_METHOD for every method.
    const entries = this._byDid.get(did)
    if (!entries.has(fhKeyHex)) entries.set(fhKeyHex, { coords: a, conns: new Map() })
    const entry = entries.get(fhKeyHex)
    entry.coords = a
    entry.conns.set(conn, rpc || null)
    const existing = this._fronts.get(did) && this._fronts.get(did).get(fhKeyHex)
    if (existing) { // refresh write rpc + handle; nudge fetch (cores re-replicate via corestore regardless)
      if (this._useRpc && rpc) existing.addRpc(rpc)
      if (a.handle) existing.handle = a.handle
      // The peer went STATELESS while we still hold a repo-core replica (it used to project, now it
      // announces repoKey:null). That replica is frozen at whatever it last replicated, so once the head
      // advances getRepoFromCommit's data-root assertion fails — safe, but permanently broken. Drop it so
      // getRepo takes the derive-over-RPC path instead. The firehose (the trust anchor) is untouched.
      if (!a.repoKey && existing.repo) {
        const stale = existing.repo
        existing.repo = null
        existing._repoKey = null
        try { await stale.close() } catch {}
      } else if (a.repoKey && !existing.repo) {
        // ...and the reverse: the peer resumed projecting, so take the core back. Without this the drop
        // above is one-way and a rolled-back flip never heals.
        existing.adoptRepoKey(a.repoKey).catch(() => {})
      }
      if (existing.seq) existing.seq.core.update().catch(() => {})
      this._wake(did)
      return
    }
    this._wake(did)
    // Add THIS announcer's rpc once the front exists. An announce that arrives while the front is still
    // OPENING takes the dedup path (it awaits the in-flight promise), and that open captured only the
    // candidates present when it started — so without this the second announcer's rpc is silently dropped
    // and the candidate set stays stuck at one, which is the single-slot bug wearing a different hat.
    this._ensureFront(did, fhKeyHex)
      .then((f) => { if (f && this._useRpc && rpc) f.addRpc(rpc) })
      .catch(() => {})
  }

  // Open (once, dedup-guarded) the front for ONE co-owner (did, firehoseKey). Reuses the primary DidPeer
  // (from add()) for its FIRST co-owner; a co-owner with a different firehoseKey gets its own DidPeer.
  async _ensureFront (did, fhKeyHex) {
    if (this._isDenied(did, fhKeyHex)) return null // operator-evicted; re-front only after allowFront()
    const set = this._fronts.get(did)
    if (set && set.has(fhKeyHex)) return set.get(fhKeyHex)
    const openKey = did + '|' + fhKeyHex
    const inflight = this._opening.get(openKey)
    if (inflight) return inflight
    const entry = this._byDid.get(did) && this._byDid.get(did).get(fhKeyHex)
    if (!entry) return null
    const p = (async () => {
      const verifyKey = await this._verifyKey(did)
      const o = this._opts.get(did) || {}
      let peer = this._peers.get(did)
      // Reuse the primary only while it is UNBOUND. Test BINDING (_firehoseKey), not `holds`: `holds`
      // (=> !!seq) flips true only once _openCores COMPLETES, whereas _firehoseKey is assigned
      // synchronously inside provide(). A second co-owner announcing while the primary's FIRST provide()
      // was still in flight therefore read holds=false, reused the primary, and its provide() returned the
      // first co-owner's in-flight open — so _fronts held two keys ALIASING ONE DidPeer bound to one
      // co-owner. The co-owner SET silently collapsed to a single front, freshest-by-rev had nothing to
      // choose between, and which co-owner got served was a coin flip (co-owned.test.mjs flaked on exactly
      // that; diagnose() counted map ENTRIES so it still reported 2). There is no await between this check
      // and provide() below, so reading _firehoseKey here is race-free.
      if (peer && peer._firehoseKey) {
        const boundFh = b4a.toString(peer._firehoseKey, 'hex')
        if (boundFh !== fhKeyHex) peer = null // primary already bound to a different co-owner -> new front
      }
      if (!peer) peer = new DidPeer(this.corestore, { did, verifyKey, handle: entry.coords.handle || o.handle || null, onHead: o.onHead || null, onError: o.onError || null, noRepo: o.noRepo })
      if (entry.coords.handle) peer.handle = entry.coords.handle
      // EVERY peer announcing this (did, firehoseKey) is a candidate; _call tries them until one answers.
      if (this._useRpc) for (const r of entry.conns.values()) if (r) peer.addRpc(r)
      await peer.provide({ repoKey: entry.coords.repoKey, firehoseKey: entry.coords.firehoseKey })
      // Re-sync: more peers may have announced this same (did, firehoseKey) during the open above.
      if (this._useRpc) for (const r of entry.conns.values()) if (r) peer.addRpc(r)
      if (!this._fronts.has(did)) this._fronts.set(did, new Map())
      this._fronts.get(did).set(fhKeyHex, peer)
      if (!this._peers.has(did)) this._peers.set(did, peer) // first front becomes the primary (get())
      if (peer.seq && peer.seq.core && !peer._appendWired) {
        peer._appendWired = true
        this._lastAppend.set(did, Date.now())
        peer.seq.core.on('append', () => { this._lastAppend.set(did, Date.now()) })
      }
      if (peer.handle) this._setHandle(peer.handle, did)
      this._wake(did)
      this._pickRelaySource(did).catch(() => {})
      return peer
    })().catch(() => null)
    this._opening.set(openKey, p)
    try { return await p } finally { this._opening.delete(openKey) }
  }

  // The freshest VERIFIED front for a DID = the co-owner whose head has the highest REV (a head is only set
  // after its commit verifies against the DID key). Prefer a CURRENTLY-announced (live) front; fall back to
  // any verified front if none are announced (all co-owners momentarily disconnected). Revs are TID strings
  // (lexicographic == chronological). Never regresses to a lagging co-owner once a fresher one is open.
  _freshestFront (did) {
    const set = this._fronts.get(did)
    if (!set || !set.size) return null
    const live = this._byDid.get(did) || new Map()
    const scored = []
    for (const [fhKeyHex, f] of set) {
      if (!f || !f.head || !f.head.rev) continue // only verified fronts
      scored.push({ f, rev: f.head.rev, live: live.has(fhKeyHex) })
    }
    if (!scored.length) return null
    const pickMaxRev = (arr) => arr.reduce((b, x) => (!b || x.rev > b.rev ? x : b), null)
    const liveOnes = scored.filter((x) => x.live)
    const chosen = pickMaxRev(liveOnes) || pickMaxRev(scored)
    return chosen ? chosen.f : null
  }

  // ---- continuity ---------------------------------------------------------------------------------
  // freshest-by-rev alone trusts a rev with NO continuity check, so a FORKED line whose rev sorts higher
  // simply wins. That is how loser-club's public getLatestCommit served a rival 1-record head
  // (3mrnruepxss22) over the authoritative 139-record one (3mrfgnyiurk22) until the bridge was bounced: a
  // rev REGRESSION was guarded against, a higher rev on a DIFFERENT LINE was not.
  //
  // Real co-owners are not a different line. `atproto-store/lib/tid.js:nextRev` makes the chain a pure
  // function of the previous rev, so two co-owners continuing from the same head over the same finalized
  // record set produce BYTE-IDENTICAL commits — a lagging co-owner's firehose is a strict PREFIX of a
  // fresher one's. So "chains from the head we serve" is decidable: walk the candidate's own frames back
  // and look for the exact commit we are serving.
  //
  // Enforced only while the INCUMBENT IS STILL LIVE. A peer that legitimately rebuilds its cores (storage
  // repair, rebuild-did) goes away and comes back announcing new keys on a new line, and refusing that
  // would strand the DID on dead cores — the case test/peer-router.test.js 'REBUILDS its cores' covers.
  // Live incumbent + a rival line => fork, keep serving the incumbent. No incumbent (gone, or evicted by
  // an operator) => the new line is the only truth on offer, take it.
  async _chainsFromServed (front, served) {
    if (!front || !front.head) return false
    if (front.head.rev === served.rev) return front.head.cid === served.cid // same rev MUST be same commit
    if (front.head.rev < served.rev) return false                           // regression (pre-existing policy)
    const ck = front.head.cid + '|' + served.cid
    if (this._continuity.has(ck)) return this._continuity.get(ck)
    const verdict = await this._scanForServed(front, served) // 'same' | 'fork' | 'unknown'
    if (verdict !== 'unknown') this._continuity.set(ck, verdict === 'same') // never cache an inconclusive read
    return verdict === 'same'
  }

  // Walk the candidate's firehose backwards looking for the served commit. Bounded by continuityScan.
  // Reads are wait:false — a block we do not hold yet is INCONCLUSIVE, not evidence of a fork (the verdict
  // is left uncached so the next read re-decides once replication catches up).
  async _scanForServed (front, served) {
    const core = front.seq && front.seq.core
    if (!core || !core.length) return 'unknown'
    const limit = Math.min(core.length, this._continuityScan)
    for (let i = 1; i <= limit; i++) {
      let body = null
      try {
        const raw = await core.get(core.length - i, { wait: false })
        if (!raw) return 'unknown' // not replicated locally — cannot conclude
        const d = decodeCommitFrame(raw)
        body = d && d.body
      } catch { return 'unknown' }
      if (!body || !body.rev) continue // #sync/#identity/#account frames carry no commit
      if (body.rev === served.rev) return (body.commit && body.commit.toString() === served.cid) ? 'same' : 'fork'
      if (body.rev < served.rev) return 'fork' // walked PAST it without meeting it -> different line
    }
    return limit < core.length ? 'unknown' : 'fork' // exhausted the window vs exhausted the core
  }

  // The freshest front that also CHAINS from what we already serve. Returns the incumbent when every
  // fresher candidate is on a rival line. Records what it picks as the new incumbent.
  async _freshestChained (did) {
    const set = this._fronts.get(did)
    if (!set || !set.size) return null
    if (!this._continuityScan) return this._freshestFront(did) // gate disabled
    const live = this._byDid.get(did) || new Map()
    const scored = []
    for (const [fhKeyHex, f] of set) {
      if (!f || !f.head || !f.head.rev) continue
      scored.push({ fhKeyHex, f, rev: f.head.rev, live: live.has(fhKeyHex) })
    }
    if (!scored.length) return null
    const pool = scored.some((x) => x.live) ? scored.filter((x) => x.live) : scored
    pool.sort((a, b) => (a.rev < b.rev ? 1 : a.rev > b.rev ? -1 : 0)) // highest rev first
    const served = this._servedHead.get(did)
    const incumbentLive = !!(served && live.has(served.fhKeyHex) && set.has(served.fhKeyHex))
    for (const cand of pool) {
      if (served && incumbentLive && cand.fhKeyHex !== served.fhKeyHex) {
        if (!(await this._chainsFromServed(cand.f, served))) {
          const k = did + '|' + cand.fhKeyHex
          this._forkRejected.set(k, (this._forkRejected.get(k) || 0) + 1)
          continue
        }
      }
      this._servedHead.set(did, { rev: cand.rev, cid: cand.f.head.cid, fhKeyHex: cand.fhKeyHex })
      return cand.f
    }
    return (served && set.get(served.fhKeyHex)) || null // every rival was a fork: hold the line
  }

  // Get the FRESHEST verified front for a fronted DID: ensure fronts for every identified co-owner, then
  // return the highest-rev one that chains from what we serve. This is what every read
  // (getRepo/listRecords/…) resolves against — a lagging co-owner never freezes the served head.
  async front (did, { timeout } = {}) {
    if (!this._isCared(did)) throw new Error(`DidPeerRouter: ${did} is not a fronted DID`)
    this._joinDid(did)
    if (!this._byDid.has(did) || this._byDid.get(did).size === 0) {
      // Every co-owner is momentarily away. _freshestFront already documents a fallback to any VERIFIED
      // front for exactly this case, but it was unreachable from here: _waitForDid blocked first, so a read
      // during a blip stalled for the full timeout and then threw, even though a verified head was cached.
      // (It is also what makes age-out's "never drop the last front" worth anything.) Cores keep
      // replicating over the next connection, so the cached head is the freshest thing that exists.
      const cached = await this._freshestChained(did)
      if (cached) return cached
      await this._waitForDid(did, timeout || 20000)
    }
    const entries = this._byDid.get(did) || new Map()
    await Promise.all([...entries.keys()].map((fh) => this._ensureFront(did, fh).catch(() => null)))
    // A front is opened once provide() kicks off replication, but its head is only set once the firehose
    // commit REPLICATES + verifies (event-driven, on 'append'). For a single front() call (no retry — a
    // real getRepo request), wait for AT LEAST ONE co-owner to reach a verified head, then serve the
    // freshest among those ready. A slow co-owner never delays serving from a ready one (freshest-of-ready).
    let best = await this._freshestChained(did)
    if (!best) {
      const end = Date.now() + (timeout || 20000)
      while (!best && Date.now() < end) {
        await new Promise((r) => setTimeout(r, 100))
        best = await this._freshestChained(did)
      }
    }
    if (!best) throw new Error(`DidPeerRouter: no frontable co-owner for ${did}`)
    return best
  }

  // Resolve that AT LEAST ONE co-owner of a DID is identified — immediately if any is connected, else wait.
  _waitForDid (did, timeout) {
    const e = this._byDid.get(did)
    if (e && e.size > 0) return Promise.resolve(e)
    return new Promise((resolve, reject) => {
      const fn = () => {
        clearTimeout(timer)
        const e2 = this._byDid.get(did)
        e2 && e2.size > 0 ? resolve(e2) : reject(new Error(`DidPeerRouter: ${did} identified but entry missing`))
      }
      const timer = setTimeout(() => {
        const ws = this._waiters.get(did); if (ws) ws.delete(fn)
        reject(new Error(`DidPeerRouter: timeout finding ${did}`))
      }, timeout)
      if (!this._waiters.has(did)) this._waiters.set(did, new Set())
      this._waiters.get(did).add(fn)
    })
  }

  // A peer disconnected: drop its (did, firehoseKey) identified-connection entries so _onAnnounce re-runs
  // on reconnect. Do NOT close the cached front — its cores keep replicating over any remaining/next conn.
  // (Keeping it is right for a transient reconnect and WRONG forever: see _ageOutFronts + dropFront.)
  _onConnClose (conn) {
    for (const [did, entries] of this._byDid) {
      // Drop only THIS connection's candidate. A (did, firehoseKey) announced by several peers stays
      // identified while any of them is still connected — one seeder leaving must not un-identify the DID.
      for (const [fhKeyHex, entry] of entries) {
        entry.conns.delete(conn)
        if (entry.conns.size === 0) entries.delete(fhKeyHex)
      }
      if (entries.size === 0) this._byDid.delete(did)
    }
  }

  // ---- eviction ----------------------------------------------------------------------------------
  // A cached front used to live for the life of the PROCESS: _onConnClose deliberately keeps it, and
  // _ensureFront returns the existing entry on every later announce. So the only way to stop serving a
  // wrong head (a peer that stopped announcing, or one announcing a FORKED line) was to restart the
  // bridge — unacceptable for a production read surface. These are the surgical alternatives.

  _isDenied (did, fhKeyHex) { const s = this._denied.get(did); return !!(s && s.has(fhKeyHex)) }

  // Evict one co-owner's front (or every front of a DID with no firehoseKey). `forget: true` also
  // DENIES that firehose key, so the peer's next announce cannot resurrect it — required whenever the
  // reason for evicting is the content the front is serving, because the offender keeps announcing.
  // Never denies when dropping ALL of a DID's fronts implicitly (that is forgetDid's job, and denying a
  // whole DID would make it permanently unservable).
  async dropFront (did, { firehoseKey = null, forget = false } = {}) {
    const set = this._fronts.get(did)
    const targets = firehoseKey ? [firehoseKey] : (set ? [...set.keys()] : [])
    const dropped = []
    for (const fhKeyHex of targets) {
      const f = set && set.get(fhKeyHex)
      if (set) set.delete(fhKeyHex)
      const entries = this._byDid.get(did)
      if (entries) { entries.delete(fhKeyHex); if (entries.size === 0) this._byDid.delete(did) }
      this._lastLive.delete(did + '|' + fhKeyHex)
      if (forget && firehoseKey) {
        if (!this._denied.has(did)) this._denied.set(did, new Set())
        this._denied.get(did).add(fhKeyHex)
      }
      // Stop folding an evicted front into the aggregate relay before it can emit another frame.
      if (this._relaySourceKey.get(did) === fhKeyHex) {
        this._relaySourceKey.delete(did)
        if (this.relay) { try { this.relay.removeSource(fhKeyHex) } catch {} }
      }
      // Re-point the primary (get()/announce-held) at a surviving front before closing this one.
      if (this._peers.get(did) === f) {
        const survivor = set && set.size ? [...set.values()][0] : null
        if (survivor) this._peers.set(did, survivor); else this._peers.delete(did)
      }
      // If the evicted front was the INCUMBENT, clear it: the operator's drop is an explicit decision that
      // this line is wrong, so a surviving rival must be allowed to take over instead of being held off by
      // the continuity gate as a "fork" of the head we just threw away.
      const served = this._servedHead.get(did)
      if (served && served.fhKeyHex === fhKeyHex) this._servedHead.delete(did)
      this._forkRejected.delete(did + '|' + fhKeyHex)
      if (f) { dropped.push(fhKeyHex); try { await f.close() } catch {} }
    }
    if (set && set.size === 0) this._fronts.delete(did)
    // A surviving co-owner must take over the relay slot immediately, not at the next refresh tick.
    this._pickRelaySource(did).catch(() => {})
    return { did, dropped, forgotten: forget && firehoseKey ? [firehoseKey] : [] }
  }

  // Un-deny a previously forgotten front (omit firehoseKey to clear every denial for the DID) so the
  // peer's next announce re-fronts it. An eviction with no undo is an outage waiting to happen.
  allowFront (did, firehoseKey = null) {
    const s = this._denied.get(did)
    if (!s) return { did, allowed: [] }
    const allowed = firehoseKey ? (s.delete(firehoseKey) ? [firehoseKey] : []) : [...s]
    if (!firehoseKey) s.clear()
    if (s.size === 0) this._denied.delete(did)
    return { did, allowed }
  }

  // Forget EVERYTHING cached for a DID — every co-owner front, its identified connections and its
  // resolved verify key — so the next request re-fronts from scratch. The DID stays allow-listed (it must
  // still be servable) and nothing is denied: this is the "re-derive, don't restart" lever. To evict a
  // specific misbehaving co-owner and keep it out, use dropFront({ firehoseKey, forget: true }).
  async forgetDid (did) {
    const r = await this.dropFront(did)
    this._byDid.delete(did)
    this._verifyKeys.delete(did)
    this._lastAppend.delete(did)
    this._relaySourceKey.delete(did)
    this._servedHead.delete(did) // no incumbent => the continuity gate starts clean on the next front()
    return { did, dropped: r.dropped }
  }

  // Age out fronts whose peer has stopped announcing. Conservative by construction: a front is only
  // dropped while a LIVE, VERIFIED sibling remains to serve the DID, so age-out can never be the reason a
  // DID becomes unservable — the single-holder case (the overwhelmingly common one) is never touched.
  async _ageOutFronts (did) {
    if (!this._staleFrontMs) return []
    const set = this._fronts.get(did)
    if (!set || set.size < 2) return []
    const live = this._byDid.get(did) || new Map()
    const hasLiveVerified = [...set].some(([k, f]) => live.has(k) && f && f.head)
    if (!hasLiveVerified) return []
    const now = Date.now()
    const stale = [...set.keys()].filter((k) => !live.has(k) && now - (this._lastLive.get(did + '|' + k) || now) > this._staleFrontMs)
    const dropped = []
    for (const k of stale) {
      if (this._fronts.get(did) && this._fronts.get(did).size < 2) break // never drop the last front
      const r = await this.dropFront(did, { firehoseKey: k })
      dropped.push(...r.dropped)
    }
    return dropped
  }

  // Fold the FRESHEST co-owner's firehose into the aggregate relay (single source per DID — two co-owners
  // are the SAME frames under different sourceIds, so folding both duplicates every #commit). On a source
  // change (fresher co-owner won, or the folded one stalled) swap removeSource->addSource + emit #sync.
  async _pickRelaySource (did) {
    if (!this.relay) return
    // The relay must fold the SAME line the read surface serves — folding a fork's frames would publish it
    // to every downstream subscriber, which is worse than serving it on one read.
    const best = await this._freshestChained(did)
    if (!best || !best.seq || !best.seq.core) return
    const key = b4a.toString(best.seq.core.key, 'hex')
    if (this._relaySourceKey.get(did) === key) return
    const old = this._relaySourceKey.get(did)
    this._relaySourceKey.set(did, key)
    ;(async () => {
      if (old) { try { this.relay.removeSource(old) } catch {} }
      try { await this.relay.addSource(key, best.seq.core) } catch {}
      try { await this._emitSync(did, best) } catch {}
    })().catch(() => {})
  }

  async _emitSync (did, front) {
    if (!this.relay) return { did, emitted: false, reason: 'no relay' }
    const signed = front.head && front.head.signed
    if (!signed) return { did, emitted: false, reason: 'no commit' }
    const time = new Date().toISOString()
    const frameBytes = await syncFrame({ seq: 0, did, signedCommit: signed, time })
    const emitted = await this.relay.emit(`sync:${did}:${signed.rev}`, frameBytes)
    return { did, rev: signed.rev, emitted }
  }

  // Public control-plane trigger: force a #sync re-baseline for a fronted DID (from its freshest front).
  async emitSync (did) { const f = await this.front(did); return this._emitSync(did, f) }

  // Pull-only staleness ceiling + relay failover (owns-swarm/relay mode). NEVER destroys a connection —
  // cores live-follow via the standing download; this just nudges a front that saw no 'append' for a window
  // and re-picks the relay source if the folded co-owner stalled while another advanced.
  async _refreshFronts () {
    for (const did of [...this._fronts.keys()]) { // snapshot: _ageOutFronts mutates _fronts
      const set = this._fronts.get(did)
      if (!set) continue
      for (const [, f] of set) {
        if (!f || !f.seq || !f.seq.core) continue
        if (Date.now() - (this._lastAppend.get(did) || 0) < this._refreshMs) continue
        try { await withTimeout(f.seq.core.update({ wait: true }), this._refreshTimeoutMs) } catch {}
      }
      try { await this._ageOutFronts(did) } catch {}
      this._pickRelaySource(did).catch(() => {})
    }
  }

  diagnose () {
    const fronts = []
    const now = Date.now()
    for (const [did, set] of this._fronts) {
      for (const [fhKeyHex, f] of set) {
        const live = (this._byDid.get(did) || new Map()).has(fhKeyHex)
        fronts.push({
          did,
          handle: f.handle || null,
          repoKey: f._repoKey ? b4a.toString(f._repoKey, 'hex') : null,
          firehoseKey: fhKeyHex,
          firehoseLen: (f.seq && f.seq.core) ? f.seq.core.length : null,
          rev: f.head ? f.head.rev : null,
          rpcConnected: !!(f.rpc && !f.rpc.closed),
          relaySource: this._relaySourceKey.get(did) === fhKeyHex,
          live,
          // How long this co-owner has been silent, and whether age-out would take it — so an operator can
          // SEE an evictable front instead of inferring one.
          silentMs: live ? 0 : now - (this._lastLive.get(did + '|' + fhKeyHex) || now),
          // Is this the head reads resolve to, and has it been refused as a rival line? A front sitting at
          // a HIGHER rev than the served one with forkRejected > 0 is the loser-club signature.
          served: (this._servedHead.get(did) || {}).fhKeyHex === fhKeyHex,
          forkRejected: this._forkRejected.get(did + '|' + fhKeyHex) || 0
        })
      }
    }
    const denied = {}
    for (const [did, s] of this._denied) denied[did] = [...s]
    return {
      fronted: [...this._fronted],
      cachedFronts: fronts.length,
      // Distinct front OBJECTS. cachedFronts counts map entries, which is why an aliased set (one DidPeer
      // filed under N keys) read as healthy right up to 0.2.6.
      distinctFronts: new Set([].concat(...[...this._fronts.values()].map((s) => [...s.values()]))).size,
      fronts,
      denied,
      staleFrontMs: this._staleFrontMs,
      relay: this.relay ? { sources: this.relay.sourceCount ? this.relay.sourceCount() : null } : null
    }
  }

  // Announce every HELD DID on a channel (symmetric seeding: tell the peer which cores we can serve).
  _announceHeld (chan) {
    for (const p of this._peers.values()) { if (p && p.holds) p.announceVia(chan._announce) }
  }

  async close () {
    if (this._refreshTimer) { try { clearInterval(this._refreshTimer) } catch {} this._refreshTimer = null }
    if (this.swarm && this._onconnbound) { try { this.swarm.off('connection', this._onconnbound) } catch {} }
    for (const chan of this._channels) { try { chan.close() } catch {} }
    this._channels.clear()
    const closed = new Set()
    for (const set of this._fronts.values()) { for (const f of set.values()) { if (closed.has(f)) continue; closed.add(f); try { await f.close() } catch {} } }
    for (const p of this._peers.values()) { if (closed.has(p)) continue; closed.add(p); try { await p.close() } catch {} }
    this._fronts.clear(); this._peers.clear(); this._byDid.clear()
  }
}

export { ANNOUNCE_PROTOCOL }
// Minimal CAR v1 codec — bare-safe, dependency-light replacement for @ipld/car.
//
// CAR v1 is a trivial container: varint(headerLen) ++ dag-cbor({version:1, roots:[…]})
// then, per block, varint(len) ++ CIDbytes ++ blockBytes. We only need whole-buffer
// read/write (no streaming, no file I/O), so this is ~40 lines of pure JS over
// multiformats' CID (byte-exact with @ipld/car — verified by the repo tests + the
// @atproto/repo conformance reader). Drops @ipld/car (which imports `fs`/streams and
// won't load under Bare).
//
// ⚠️ LIMITATIONS vs @ipld/car (tracked in memory: bare-car-limitations). Fine for our
// current use (whole-buffer, CARv1, OUR-OWN trusted output); add the feature before the
// gate it guards:
//   - No streaming — whole CAR is buffered in memory. GATE: large repos (getRepo of a
//     big repo could be GBs). Add an async-iterator read/write path.
//   - No untrusted-input hardening — readCar trusts varints/lengths/CIDs. GATE: reading
//     UNTRUSTED CARs (com.atproto.repo.importRepo, ingress bridge). Add bounds/overflow/
//     truncation checks + duplicate-CID handling before then.
//   - CARv1 only (no CARv2/index). atproto is CARv1, so no gate today.
// Fully-featured path: grow this file at each gate, OR extract a standalone bare-native
// `bare-car` package (the holepunch ecosystem lacks one — a real contribution).

import { CID } from 'multiformats/cid'
import * as dagCbor from '@ipld/dag-cbor'

function varintEncode (n) {
  const out = []
  while (n >= 0x80) { out.push((n & 0x7f) | 0x80); n >>>= 7 }
  out.push(n)
  return Uint8Array.from(out)
}

function varintDecode (bytes, offset) {
  let n = 0; let shift = 0; let i = offset
  for (;;) {
    const b = bytes[i++]
    n |= (b & 0x7f) << shift
    if ((b & 0x80) === 0) break
    shift += 7
  }
  return [n >>> 0, i]
}

// Serialise { root, blocks } to CAR bytes. `blocks` is an iterable of { cid, bytes }.
export async function writeCar (rootCid, blocks) {
  const header = dagCbor.encode({ version: 1, roots: [rootCid] })
  const parts = [Buffer.from(varintEncode(header.length)), Buffer.from(header)]
  for (const { cid, bytes } of blocks) {
    const cidBytes = cid.bytes
    const body = new Uint8Array(cidBytes.length + bytes.length)
    body.set(cidBytes, 0)
    body.set(bytes, cidBytes.length)
    parts.push(Buffer.from(varintEncode(body.length)), Buffer.from(body))
  }
  return Buffer.concat(parts)
}

// Read a CAR into { roots, blocks } where blocks maps cid-string -> { cid, bytes }.
export async function readCar (carBytes) {
  const bytes = carBytes instanceof Uint8Array ? carBytes : new Uint8Array(carBytes)
  let [hlen, off] = varintDecode(bytes, 0)
  const header = dagCbor.decode(bytes.subarray(off, off + hlen))
  off += hlen
  const blocks = new Map()
  while (off < bytes.length) {
    const [blen, bodyStart] = varintDecode(bytes, off)
    const end = bodyStart + blen
    const [cid, rest] = CID.decodeFirst(bytes.subarray(bodyStart, end))
    blocks.set(cid.toString(), { cid, bytes: rest })
    off = end
  }
  return { roots: header.roots, blocks }
}
// atproto block CIDs — CIDv1, dag-cbor codec (0x71), sha2-256 multihash (0x12).
// Every block in a repo (commit, MST node, record) is content-addressed this way,
// so computeCid(dag-cbor(block)) IS the block's identity. This is the anchor for
// byte-exact fidelity: if our re-encoded bytes hash to the same CID the reference
// produced, our encoding is byte-identical.

import { CID } from 'multiformats/cid'
import * as Digest from 'multiformats/hashes/digest'
import { sha256 as nobleSha256 } from '@noble/hashes/sha2'
import * as dagCbor from '@ipld/dag-cbor'
import * as raw from 'multiformats/codecs/raw'

// raw block bytes -> CID. Uses noble's pure-JS sha256 (same as the sync path) rather
// than multiformats' `crypto.subtle` path — identical CID, and no WebCrypto dependency
// (so it loads + runs under Bare, which has no crypto.subtle).
export async function cidForBytes (bytes) {
  return cidForBytesSync(bytes)
}

// Synchronous variant — needed by the recursive MST build. Same result as
// cidForBytes (CIDv1 / dag-cbor 0x71 / sha2-256 0x12), just without the async
// WebCrypto digest.
export function cidForBytesSync (bytes) {
  const digest = Digest.create(0x12, nobleSha256(bytes)) // 0x12 = sha2-256 multihash code
  return CID.createV1(dagCbor.code, digest)
}

// BLOB CID — CIDv1, RAW codec (0x55), sha2-256. atproto blobs (images/avatars) are
// content-addressed with the raw codec (opaque bytes), NOT dag-cbor. This is the CID that
// goes in a blob ref ({$type:'blob', ref:{$link:<this>}, mimeType, size}) and the key
// com.atproto.sync.getBlob serves by.
export function cidForBlobSync (bytes) {
  const digest = Digest.create(0x12, nobleSha256(bytes))
  return CID.createV1(raw.code, digest)
}

// a JS value -> its canonical dag-cbor bytes + CID
export async function cidForValue (value) {
  const bytes = dagCbor.encode(value)
  return { bytes, cid: await cidForBytes(bytes) }
}
// atproto repo commit — sign + verify.
//
// A commit is { did, version: 3, data: <MST root CID>, rev, prev, sig }. The
// signature is ECDSA-secp256k1 (low-S) over sha256(dag-cbor(unsignedCommit)), stored
// as a raw 64-byte CBOR byte string (NOT base64url — that's the did:plc genesis).
// The relay validates this sig against the DID doc's verificationMethod.

import * as dagCbor from '@ipld/dag-cbor'
import { sha256 as nobleSha256 } from '@noble/hashes/sha2'
import { secp256k1 } from '@noble/curves/secp256k1'
import { cidForBytesSync } from './cid.js'

export const REPO_VERSION = 3

// The unsigned commit (everything the signature covers).
export function unsignedCommit ({ did, rev, data, prev = null }) {
  return { did, version: REPO_VERSION, data, rev, prev }
}

// Sign an unsigned commit -> signed commit with `sig` (64 raw bytes).
export function signCommit (unsigned, privateKey) {
  const hash = nobleSha256(dagCbor.encode(unsigned))
  const sig = secp256k1.sign(hash, privateKey, { lowS: true }).toCompactRawBytes()
  return { ...unsigned, sig }
}

export function commitCid (signedCommit) {
  return cidForBytesSync(dagCbor.encode(signedCommit))
}

// Verify a signed commit against a compressed secp256k1 pubkey (33 bytes).
export function verifyCommit (signedCommit, publicKey) {
  const { sig, ...unsigned } = signedCommit
  const hash = nobleSha256(dagCbor.encode(unsigned))
  return secp256k1.verify(sig, hash, publicKey, { lowS: true })
}
// atproto MST — WRITE path (slice 2).
//
// A faithful port of millipds's `atmst` (mst/node.py + node_wrangler.py) — the exact
// code that produced our golden CAR. Byte-exactness is verified two ways: rebuilding
// the golden repo's MST, and matching atmst's own root CIDs for a multi-height tree
// (build + delete oracles). See test/mst-write.test.js.
//
// Node shape (interleaved): subtrees[0], (keys[0],vals[0]), subtrees[1], … ,subtrees[n].
// key layer = leading-zero BITS of sha256(key), // 2 (fanout 4).

import * as dagCbor from '@ipld/dag-cbor'
import { sha256 as nobleSha256 } from '@noble/hashes/sha2'
import { cidForBytesSync } from './cid.js'

const cidEq = (a, b) => (a === null || b === null) ? a === b : a.equals(b)
const replaceAt = (arr, i, v) => { const c = arr.slice(); c[i] = v; return c }
const insertAt = (arr, i, v) => arr.slice(0, i).concat([v], arr.slice(i))
const removeAt = (arr, i) => arr.slice(0, i).concat(arr.slice(i + 1))

export function keyHeight (key) {
  const h = nobleSha256(Buffer.from(key, 'utf8')) // 32 bytes
  let zeros = 0
  for (const byte of h) {
    if (byte === 0) { zeros += 8; continue }
    zeros += Math.clz32(byte) - 24 // leading zero bits within this byte
    break
  }
  return zeros >> 1 // // 2
}

export class MSTNode {
  constructor (keys, vals, subtrees) {
    this.keys = keys // [string]
    this.vals = vals // [CID]
    this.subtrees = subtrees // [CID|null], length keys.length + 1
  }

  static empty () { return new MSTNode([], [], [null]) }

  isEmpty () { return this.keys.length === 0 && this.subtrees.length === 1 && this.subtrees[0] === null }

  serialise () {
    const e = []
    let prevKey = Buffer.alloc(0)
    for (let i = 0; i < this.keys.length; i++) {
      const keyBytes = Buffer.from(this.keys[i], 'utf8')
      const max = Math.min(prevKey.length, keyBytes.length)
      let p = 0
      while (p < max && prevKey[p] === keyBytes[p]) p++
      e.push({ k: keyBytes.subarray(p), p, t: this.subtrees[i + 1], v: this.vals[i] })
      prevKey = keyBytes
    }
    return dagCbor.encode({ e, l: this.subtrees[0] }) // dag-cbor canonicalises map key order
  }

  cid () { return cidForBytesSync(this.serialise()) }

  toOptional () { return this.isEmpty() ? null : this.cid() }

  gteIndex (key) { let i = 0; while (i < this.keys.length && key > this.keys[i]) i++; return i }

  height () {
    if (this.keys.length) return keyHeight(this.keys[0])
    if (this.subtrees[0] === null) return 0
    return null // indeterminate (empty intermediate node)
  }

  static deserialise (bytes) {
    const cbor = dagCbor.decode(bytes)
    const subtrees = [cbor.l]
    const keys = []
    const vals = []
    let prevKey = Buffer.alloc(0)
    for (const e of cbor.e) {
      const suffix = Buffer.from(e.k)
      const thisKey = Buffer.concat([prevKey.subarray(0, e.p), suffix])
      keys.push(thisKey.toString('utf8'))
      vals.push(e.v)
      subtrees.push(e.t)
      prevKey = thisKey
    }
    return new MSTNode(keys, vals, subtrees)
  }
}

// In-memory node store — maps CID string -> { cid, bytes }. get(null) returns the
// (stored) empty node, matching atmst NodeStore.get_node(None).
export class NodeStore {
  constructor () { this.blocks = new Map() }

  storedNode (node) {
    const bytes = node.serialise()
    const cid = cidForBytesSync(bytes)
    this.blocks.set(cid.toString(), { cid, bytes })
    return node
  }

  getNode (cid) {
    if (cid === null || cid === undefined) return this.storedNode(MSTNode.empty())
    const b = this.blocks.get(cid.toString())
    if (!b) throw new Error(`missing MST node ${cid}`)
    return MSTNode.deserialise(b.bytes)
  }
}

export class NodeWrangler {
  constructor (ns) { this.ns = ns }

  putRecord (rootCid, key, val) {
    const root = this.ns.getNode(rootCid)
    if (root.isEmpty()) return this._putHere(root, key, val).cid()
    return this._putRecursive(root, key, val, keyHeight(key), root.height()).cid()
  }

  delRecord (rootCid, key) {
    const root = this.ns.getNode(rootCid)
    const afterDel = this._deleteRecursive(root, key, keyHeight(key), root.height())
    return this.ns.getNode(this._squashTop(afterDel)).cid()
  }

  _putHere (node, key, val) {
    const i = node.gteIndex(key)
    if (i < node.keys.length && node.keys[i] === key) {
      if (cidEq(node.vals[i], val)) return node
      return this.ns.storedNode(new MSTNode(node.keys.slice(), replaceAt(node.vals, i, val), node.subtrees.slice()))
    }
    const [lsub, rsub] = this._splitOnKey(node.subtrees[i], key)
    return this.ns.storedNode(new MSTNode(
      insertAt(node.keys, i, key),
      insertAt(node.vals, i, val),
      node.subtrees.slice(0, i).concat([lsub, rsub], node.subtrees.slice(i + 1))
    ))
  }

  _putRecursive (node, key, val, keyH, treeH) {
    if (keyH > treeH) { // grow the tree upward
      return this.ns.storedNode(this._putRecursive(
        this.ns.storedNode(new MSTNode([], [], [node.cid()])),
        key, val, keyH, treeH + 1
      ))
    }
    if (keyH < treeH) { // descend
      const i = node.gteIndex(key)
      return this.ns.storedNode(new MSTNode(
        node.keys.slice(), node.vals.slice(),
        replaceAt(node.subtrees, i, this._putRecursive(this.ns.getNode(node.subtrees[i]), key, val, keyH, treeH - 1).cid())
      ))
    }
    return this._putHere(node, key, val) // keyH === treeH
  }

  _splitOnKey (nodeCid, key) {
    if (nodeCid === null || nodeCid === undefined) return [null, null]
    const node = this.ns.getNode(nodeCid)
    const i = node.gteIndex(key)
    const [lsub, rsub] = this._splitOnKey(node.subtrees[i], key)
    const left = this.ns.storedNode(new MSTNode(node.keys.slice(0, i), node.vals.slice(0, i), node.subtrees.slice(0, i).concat([lsub]))).toOptional()
    const right = this.ns.storedNode(new MSTNode(node.keys.slice(i), node.vals.slice(i), [rsub].concat(node.subtrees.slice(i + 1)))).toOptional()
    return [left, right]
  }

  _squashTop (nodeCid) {
    const node = this.ns.getNode(nodeCid)
    if (node.keys.length) return nodeCid
    if (node.subtrees[0] === null) return nodeCid
    return this._squashTop(node.subtrees[0])
  }

  _deleteRecursive (node, key, keyH, treeH) {
    if (keyH > treeH) return node.toOptional()
    let i = node.gteIndex(key)
    if (keyH < treeH) {
      if (node.subtrees[i] === null) return node.toOptional()
      return this.ns.storedNode(new MSTNode(
        node.keys.slice(), node.vals.slice(),
        replaceAt(node.subtrees, i, this._deleteRecursive(this.ns.getNode(node.subtrees[i]), key, keyH, treeH - 1))
      )).toOptional()
    }
    i = node.gteIndex(key)
    if (i === node.keys.length || node.keys[i] !== key) return node.toOptional()
    return this.ns.storedNode(new MSTNode(
      removeAt(node.keys, i), removeAt(node.vals, i),
      node.subtrees.slice(0, i).concat([this._merge(node.subtrees[i], node.subtrees[i + 1])], node.subtrees.slice(i + 2))
    )).toOptional()
  }

  _merge (leftCid, rightCid) {
    if (leftCid === null) return rightCid
    if (rightCid === null) return leftCid
    const left = this.ns.getNode(leftCid)
    const right = this.ns.getNode(rightCid)
    return this.ns.storedNode(new MSTNode(
      left.keys.concat(right.keys), left.vals.concat(right.vals),
      left.subtrees.slice(0, -1).concat([this._merge(left.subtrees[left.subtrees.length - 1], right.subtrees[0])], right.subtrees.slice(1))
    )).toOptional()
  }
}

// Build an MST from records [{ key, value: CID }] (any order). Returns
// { root: CID, ns: NodeStore }. ns.blocks holds every node created; use
// reachableBlocks(ns, root) for just the live set (CAR output).
export function buildMst (records) {
  const ns = new NodeStore()
  const w = new NodeWrangler(ns)
  let root = ns.storedNode(MSTNode.empty()).cid()
  for (const { key, value } of records) root = w.putRecord(root, key, value)
  return { root, ns, wrangler: w }
}

// BFS the live MST nodes reachable from root (for CAR block sets).
export function reachableBlocks (ns, rootCid) {
  const out = new Map()
  const stack = [rootCid]
  while (stack.length) {
    const cid = stack.pop()
    if (cid === null || cid === undefined) continue
    const key = cid.toString()
    if (out.has(key)) continue
    const b = ns.blocks.get(key)
    if (!b) throw new Error(`missing node ${key}`)
    out.set(key, b)
    const node = MSTNode.deserialise(b.bytes)
    for (const t of node.subtrees) if (t) stack.push(t)
  }
  return out
}

// ---- Firehose MST-inversion proof (slice 3b) ----
//
// A #commit's `blocks` CAR must be a MINIMAL, self-contained proof of the
// old→new transition — not the whole tree (that would trip a relay's `tooBig`).
// This ports millipds `repo_ops.py:apply_writes` step 2b + `atmst` proof.py:
//   blocks = created | deletion_proof_cids | inductive_proof_nodes  (+ new records)
// where `inductive_proof_nodes` = every MST node READ while replaying the ops
// backward from the new root, which must reproduce the old (prevData) root.
// The prior record CIDs travel in each op's `prev` (like millipds), so a cold
// relay can invert with no old-tree state of its own.

// A NodeStore overlay: writes land in an in-memory upper layer (NOT logged);
// reads that fall through to `lower` are recorded in `.gets`. Mirrors millipds's
// OverlayBlockStore(MemoryBlockStore, LoggingBlockStoreWrapper(bs)).
export class OverlayNodeStore {
  constructor (lower) { this.lower = lower; this.upper = new Map(); this.gets = new Set() }

  storedNode (node) {
    const bytes = node.serialise()
    const cid = cidForBytesSync(bytes)
    this.upper.set(cid.toString(), { cid, bytes })
    return node
  }

  getNode (cid) {
    if (cid === null || cid === undefined) return MSTNode.empty()
    const k = cid.toString()
    const u = this.upper.get(k)
    if (u) return MSTNode.deserialise(u.bytes)
    this.gets.add(k) // a read of a pre-existing node — part of the inductive proof
    return this.lower.getNode(cid)
  }
}

// Follow the search path for `key` from `rootCid`, collecting every node visited.
// Returns { value: CID|null, proof: Set<cidStr> }. value===null ⇒ exclusion proof;
// value!==null ⇒ inclusion proof. Port of atmst find_rpath_and_build_proof.
export function findRpathProof (ns, rootCid, key) {
  const proof = new Set()
  let cid = rootCid
  while (cid !== null && cid !== undefined) {
    const node = ns.getNode(cid)
    proof.add(cid.toString())
    const i = node.gteIndex(key)
    if (i < node.keys.length && node.keys[i] === key) return { value: node.vals[i], proof }
    cid = node.subtrees[i] // descend the subtree left of the first key >= target
  }
  return { value: null, proof }
}

// Build a NodeStore holding exactly the given blocks (cid-string -> { cid, bytes }).
export function nodeStoreFromBlocks (blocks) {
  const ns = new NodeStore()
  for (const [k, v] of blocks) ns.blocks.set(k, v)
  return ns
}

// Compute the minimal firehose block set for a single commit's ops.
//   oldRecords / newRecords : [{ key, value: CID }] — the record sets BEFORE/AFTER.
//   ops : [{ action:'create'|'update'|'delete', path, cid: CID|null, prev: CID|null }]
// Returns { blocks: Map<cidStr,{cid,bytes}>, dataCid, oldRoot } — MST nodes only
// (record + commit blocks are added by the caller). Throws if the backward replay
// does not reproduce the old root (i.e. the proof would be invalid).
export function firehoseProofBlocks ({ oldRecords, newRecords, ops }) {
  const oldB = buildMst(oldRecords)
  const newB = buildMst(newRecords)
  const oldRoot = oldB.root
  const newRoot = newB.root

  const oldSet = reachableBlocks(oldB.ns, oldRoot)
  const newSet = reachableBlocks(newB.ns, newRoot)

  // combined store holds every node of BOTH trees (proof reads span both)
  const combined = new NodeStore()
  for (const [k, v] of oldSet) combined.blocks.set(k, v)
  for (const [k, v] of newSet) combined.blocks.set(k, v)

  const proofCids = new Set()

  // created: new-tree nodes not present in the old tree
  for (const k of newSet.keys()) if (!oldSet.has(k)) proofCids.add(k)

  // deletion proofs: for each delete, the exclusion-proof path in the NEW tree
  for (const op of ops) {
    if (op.action !== 'delete') continue
    const { value, proof } = findRpathProof(combined, newRoot, op.path)
    if (value !== null) throw new Error(`delete proof: ${op.path} still present in new tree`)
    for (const c of proof) proofCids.add(c)
  }

  // inductive proof: replay ops backward from newRoot; every node read is required.
  const overlay = new OverlayNodeStore(combined)
  const w = new NodeWrangler(overlay)
  let inv = newRoot
  for (let i = ops.length - 1; i >= 0; i--) {
    const op = ops[i]
    if (op.action === 'create') {
      inv = w.delRecord(inv, op.path)
    } else { // update | delete → restore the prior value
      if (op.prev === null || op.prev === undefined) throw new Error(`inversion: ${op.action} ${op.path} missing prev`)
      inv = w.putRecord(inv, op.path, op.prev)
    }
  }
  if (!inv.equals(oldRoot)) throw new Error('inversion proof failed: backward replay did not reproduce prevData root')
  for (const k of overlay.gets) proofCids.add(k)

  const blocks = new Map()
  for (const k of proofCids) blocks.set(k, combined.blocks.get(k))
  return { blocks, dataCid: newRoot, oldRoot }
}
// atproto repo — READ path (slice 1).
//
// A repo is a CAR whose root is a signed commit; the commit's `data` CID points at
// the root of a Merkle Search Tree (MST) of records. This module reads a CAR, walks
// the MST, and — most importantly — VERIFIES byte-exact fidelity by re-encoding every
// block and checking its CID. Writing/mutating the MST is slice 2.

import * as dagCbor from '@ipld/dag-cbor'
import { cidForBytes, cidForBytesSync } from './cid.js'
import { buildMst, reachableBlocks } from './mst.js'
import { unsignedCommit, signCommit, commitCid } from './commit.js'
import { readCar, writeCar } from './car.js'

// CAR read/write moved to the bare-safe minimal codec in ./car.js (was @ipld/car).
export { readCar, writeCar }

export function getBlock (car, cid) {
  const b = car.blocks.get(cid.toString())
  if (!b) throw new Error(`missing block ${cid}`)
  return b
}

export function decodeBlock (car, cid) {
  return dagCbor.decode(getBlock(car, cid).bytes)
}

// The signed commit at the CAR root.
export function loadCommit (car) {
  if (car.roots.length !== 1) throw new Error(`expected 1 root, got ${car.roots.length}`)
  const commit = decodeBlock(car, car.roots[0])
  if (!commit || !commit.did || commit.data === undefined) throw new Error('root is not a commit')
  return { cid: car.roots[0], value: commit }
}

// Walk the MST in key order, yielding { key, value: recordCid }. MST node shape:
//   { l: CID|null, e: [ { p: int, k: bytes, v: CID, t: CID|null } ] }
// keys are prefix-compressed against the previous key in the SAME node.
export function * walkMst (car, rootCid, _prevKey = '') {
  const node = decodeBlock(car, rootCid)
  if (!node || !Array.isArray(node.e)) throw new Error(`not an MST node: ${rootCid}`)
  if (node.l) yield * walkMst(car, node.l)
  let prev = ''
  for (const e of node.e) {
    const suffix = Buffer.from(e.k).toString('utf8')
    const key = prev.slice(0, e.p) + suffix
    prev = key
    yield { key, value: e.v }
    if (e.t) yield * walkMst(car, e.t)
  }
}

// All records as { key, cid, value } in key order.
export function listRecords (car) {
  const commit = loadCommit(car)
  const out = []
  for (const { key, value } of walkMst(car, commit.value.data)) {
    out.push({ key, cid: value, value: decodeBlock(car, value) })
  }
  return out
}

// Byte-exact fidelity check: re-encode every block and confirm its CID is unchanged.
// Also confirms the commit's data CID and every MST value CID resolve to a present
// block. Returns { blocks, records, ok, mismatches }.
export async function verifyRepo (car) {
  const mismatches = []
  for (const [cidStr, { cid, bytes }] of car.blocks) {
    // re-encode: decode then canonical-encode; must reproduce the exact bytes + CID
    const reencoded = dagCbor.encode(dagCbor.decode(bytes))
    const sameBytes = Buffer.from(reencoded).equals(Buffer.from(bytes))
    const recomputed = await cidForBytes(reencoded)
    if (!sameBytes || !recomputed.equals(cid)) {
      mismatches.push({ cid: cidStr, sameBytes, recomputed: recomputed.toString() })
    }
  }
  const commit = loadCommit(car)
  getBlock(car, commit.value.data) // MST root must be present
  const records = listRecords(car)
  for (const r of records) getBlock(car, r.cid) // each record block present
  return { blocks: car.blocks.size, records: records.length, ok: mismatches.length === 0, mismatches }
}

// ---- WRITE path (slice 3) ----

// Originate a full atproto repo from records. Each record is
// { collection, rkey, record } (or { key, value }). Returns the CAR bytes plus the
// commit/data CIDs. `privateKey` is the atproto secp256k1 signing key.
export async function createRepo ({ records, did, rev, privateKey }) {
  const recordBlocks = new Map()
  const mstRecords = []
  for (const r of records) {
    const key = r.key !== undefined ? r.key : `${r.collection}/${r.rkey}`
    const value = r.record !== undefined ? r.record : r.value
    const bytes = dagCbor.encode(value)
    const cid = cidForBytesSync(bytes)
    recordBlocks.set(cid.toString(), { cid, bytes })
    mstRecords.push({ key, value: cid })
  }
  const { root: dataCid, ns } = buildMst(mstRecords)
  const mstBlocks = reachableBlocks(ns, dataCid)

  const signed = signCommit(unsignedCommit({ did, rev, data: dataCid }), privateKey)
  const cCid = commitCid(signed)
  const commitBytes = dagCbor.encode(signed)

  const blocks = [{ cid: cCid, bytes: commitBytes }, ...mstBlocks.values(), ...recordBlocks.values()]
  const carBytes = await writeCar(cCid, blocks)
  return { carBytes, commitCid: cCid, dataCid, signedCommit: signed }
}
{
  "name": "@ipld/dag-cbor",
  "version": "9.2.7",
  "description": "JS implementation of DAG-CBOR",
  "author": "Rod <rod@vagg.org> (http://r.va.gg/)",
  "license": "Apache-2.0 OR MIT",
  "homepage": "https://github.com/ipld/js-dag-cbor#readme",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/ipld/js-dag-cbor.git"
  },
  "bugs": {
    "url": "https://github.com/ipld/js-dag-cbor/issues"
  },
  "publishConfig": {
    "access": "public",
    "provenance": true
  },
  "keywords": [
    "ipfs",
    "ipld",
    "multiformats"
  ],
  "type": "module",
  "types": "./dist/src/index.d.ts",
  "typesVersions": {
    "*": {
      "*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ],
      "src/*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ]
    }
  },
  "files": [
    "src",
    "dist",
    "!dist/test",
    "!**/*.tsbuildinfo"
  ],
  "exports": {
    ".": {
      "types": "./dist/src/index.d.ts",
      "import": "./src/index.js",
      "module-sync": "./src/index.js"
    }
  },
  "release": {
    "branches": [
      "master"
    ],
    "plugins": [
      [
        "@semantic-release/commit-analyzer",
        {
          "preset": "conventionalcommits",
          "releaseRules": [
            {
              "breaking": true,
              "release": "major"
            },
            {
              "revert": true,
              "release": "patch"
            },
            {
              "type": "feat",
              "release": "minor"
            },
            {
              "type": "fix",
              "release": "patch"
            },
            {
              "type": "docs",
              "release": "patch"
            },
            {
              "type": "test",
              "release": "patch"
            },
            {
              "type": "deps",
              "release": "patch"
            },
            {
              "scope": "no-release",
              "release": false
            }
          ]
        }
      ],
      [
        "@semantic-release/release-notes-generator",
        {
          "preset": "conventionalcommits",
          "presetConfig": {
            "types": [
              {
                "type": "feat",
                "section": "Features"
              },
              {
                "type": "fix",
                "section": "Bug Fixes"
              },
              {
                "type": "chore",
                "section": "Trivial Changes"
              },
              {
                "type": "docs",
                "section": "Documentation"
              },
              {
                "type": "deps",
                "section": "Dependencies"
              },
              {
                "type": "test",
                "section": "Tests"
              }
            ]
          }
        }
      ],
      "@semantic-release/changelog",
      "@semantic-release/npm",
      "@semantic-release/github",
      [
        "@semantic-release/git",
        {
          "assets": [
            "CHANGELOG.md",
            "package.json"
          ]
        }
      ]
    ]
  },
  "scripts": {
    "clean": "aegir clean",
    "lint": "aegir lint",
    "build": "aegir build",
    "release": "aegir release",
    "test": "npm run lint && aegir test",
    "test:ts": "npm run test --prefix test/ts-use",
    "test:node": "aegir test -t node --cov",
    "test:chrome": "aegir test -t browser --cov",
    "test:chrome-webworker": "aegir test -t webworker",
    "test:firefox": "aegir test -t browser -- --browser firefox",
    "test:firefox-webworker": "aegir test -t webworker -- --browser firefox",
    "test:electron-main": "aegir test -t electron-main",
    "dep-check": "aegir dep-check"
  },
  "dependencies": {
    "cborg": "^5.0.1",
    "multiformats": "^13.1.0"
  },
  "devDependencies": {
    "@ipld/garbage": "^6.0.0",
    "aegir": "^48.0.1"
  }
}
import * as cborg from 'cborg'
import { CID } from 'multiformats/cid'

// https://github.com/ipfs/go-ipfs/issues/3570#issuecomment-273931692
const CID_CBOR_TAG = 42

/**
 * @template T
 * @typedef {import('multiformats/codecs/interface').ByteView<T>} ByteView
 */

/**
 * @template T
 * @typedef {import('multiformats/codecs/interface').ArrayBufferView<T>} ArrayBufferView
 */

/**
 * @template T
 * @param {ByteView<T> | ArrayBufferView<T>} buf
 * @returns {ByteView<T>}
 */
export function toByteView (buf) {
  if (buf instanceof ArrayBuffer) {
    return new Uint8Array(buf, 0, buf.byteLength)
  }

  return buf
}

/**
 * cidEncoder will receive all Objects during encode, it needs to filter out
 * anything that's not a CID and return `null` for that so it's encoded as
 * normal.
 *
 * @param {any} obj
 * @returns {cborg.Token[]|null}
 */
function cidEncoder (obj) {
  if (obj.asCID !== obj && obj['/'] !== obj.bytes) {
    return null // any other kind of object
  }
  const cid = CID.asCID(obj)
  /* c8 ignore next 4 */
  // very unlikely case, and it'll probably throw a recursion error in cborg
  if (!cid) {
    return null
  }
  const bytes = new Uint8Array(cid.bytes.byteLength + 1)
  bytes.set(cid.bytes, 1) // prefix is 0x00, for historical reasons
  return [
    new cborg.Token(cborg.Type.tag, CID_CBOR_TAG),
    new cborg.Token(cborg.Type.bytes, bytes)
  ]
}

// eslint-disable-next-line jsdoc/require-returns-check
/**
 * Intercept all `undefined` values from an object walk and reject the entire
 * object if we find one.
 *
 * @returns {null}
 */
function undefinedEncoder () {
  throw new Error('`undefined` is not supported by the IPLD Data Model and cannot be encoded')
}

/**
 * Intercept all `number` values from an object walk and reject the entire
 * object if we find something that doesn't fit the IPLD data model (NaN &
 * Infinity).
 *
 * @param {number} num
 * @returns {null}
 */
function numberEncoder (num) {
  if (Number.isNaN(num)) {
    throw new Error('`NaN` is not supported by the IPLD Data Model and cannot be encoded')
  }
  if (num === Infinity || num === -Infinity) {
    throw new Error('`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded')
  }
  return null
}

/**
 * @param {Map<any, any>} map
 * @returns {null}
 */
function mapEncoder (map) {
  for (const key of map.keys()) {
    if (typeof key !== 'string' || key.length === 0) {
      throw new Error('Non-string Map keys are not supported by the IPLD Data Model and cannot be encoded')
    }
  }
  return null
}

const _encodeOptions = {
  float64: true,
  typeEncoders: {
    Map: mapEncoder,
    Object: cidEncoder,
    undefined: undefinedEncoder,
    number: numberEncoder
  }
}

export const encodeOptions = {
  ..._encodeOptions,
  typeEncoders: {
    ..._encodeOptions.typeEncoders
  }
}

/**
 * @param {import('cborg').TagDecodeControl} decode
 * @returns {CID}
 */
function cidDecoder (decode) {
  const bytes = /** @type {Uint8Array} */ (decode())
  if (bytes[0] !== 0) {
    throw new Error('Invalid CID for CBOR tag 42; expected leading 0x00')
  }
  return CID.decode(bytes.subarray(1)) // ignore leading 0x00
}

const _decodeOptions = {
  allowIndefinite: false,
  coerceUndefinedToNull: true,
  allowNaN: false,
  allowInfinity: false,
  allowBigInt: true, // this will lead to BigInt for ints outside of
  // safe-integer range, which may surprise users
  strict: true,
  useMaps: false,
  rejectDuplicateMapKeys: true,
  /** @type {{ [tagNumber: number]: import('cborg').TagDecoder }} */
  tags: { [CID_CBOR_TAG]: cidDecoder }
}

export const decodeOptions = {
  ..._decodeOptions,
  tags: { ..._decodeOptions.tags }
}

export const name = 'dag-cbor'
export const code = 0x71

/**
 * @template T
 * @param {T} node
 * @returns {ByteView<T>}
 */
export const encode = (node) => cborg.encode(node, _encodeOptions)

/**
 * @template T
 * @param {ByteView<T> | ArrayBufferView<T>} data
 * @returns {T}
 */
export const decode = (data) => cborg.decode(toByteView(data), _decodeOptions)
/**
 * Utilities for short weierstrass curves, combined with noble-hashes.
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { weierstrass } from "./abstract/weierstrass.js";
/** connects noble-curves to noble-hashes */
export function getHash(hash) {
    return { hash };
}
/** @deprecated use new `weierstrass()` and `ecdsa()` methods */
export function createCurve(curveDef, defHash) {
    const create = (hash) => weierstrass({ ...curveDef, hash: hash });
    return { ...create(defHash), create };
}
//# sourceMappingURL=_shortw_utils.js.map/**
 * Methods for elliptic curve multiplication by scalars.
 * Contains wNAF, pippenger.
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { bitLen, bitMask, validateObject } from "../utils.js";
import { Field, FpInvertBatch, nLength, validateField } from "./modular.js";
const _0n = BigInt(0);
const _1n = BigInt(1);
export function negateCt(condition, item) {
    const neg = item.negate();
    return condition ? neg : item;
}
/**
 * Takes a bunch of Projective Points but executes only one
 * inversion on all of them. Inversion is very slow operation,
 * so this improves performance massively.
 * Optimization: converts a list of projective points to a list of identical points with Z=1.
 */
export function normalizeZ(c, points) {
    const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
    return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
}
function validateW(W, bits) {
    if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
        throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);
}
function calcWOpts(W, scalarBits) {
    validateW(W, scalarBits);
    const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero
    const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero
    const maxNumber = 2 ** W; // W=8 256
    const mask = bitMask(W); // W=8 255 == mask 0b11111111
    const shiftBy = BigInt(W); // W=8 8
    return { windows, windowSize, mask, maxNumber, shiftBy };
}
function calcOffsets(n, window, wOpts) {
    const { windowSize, mask, maxNumber, shiftBy } = wOpts;
    let wbits = Number(n & mask); // extract W bits.
    let nextN = n >> shiftBy; // shift number by W bits.
    // What actually happens here:
    // const highestBit = Number(mask ^ (mask >> 1n));
    // let wbits2 = wbits - 1; // skip zero
    // if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);
    // split if bits > max: +224 => 256-32
    if (wbits > windowSize) {
        // we skip zero, which means instead of `>= size-1`, we do `> size`
        wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.
        nextN += _1n; // +256 (carry)
    }
    const offsetStart = window * windowSize;
    const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero
    const isZero = wbits === 0; // is current window slice a 0?
    const isNeg = wbits < 0; // is current window slice negative?
    const isNegF = window % 2 !== 0; // fake random statement for noise
    const offsetF = offsetStart; // fake offset for noise
    return { nextN, offset, isZero, isNeg, isNegF, offsetF };
}
function validateMSMPoints(points, c) {
    if (!Array.isArray(points))
        throw new Error('array expected');
    points.forEach((p, i) => {
        if (!(p instanceof c))
            throw new Error('invalid point at index ' + i);
    });
}
function validateMSMScalars(scalars, field) {
    if (!Array.isArray(scalars))
        throw new Error('array of scalars expected');
    scalars.forEach((s, i) => {
        if (!field.isValid(s))
            throw new Error('invalid scalar at index ' + i);
    });
}
// Since points in different groups cannot be equal (different object constructor),
// we can have single place to store precomputes.
// Allows to make points frozen / immutable.
const pointPrecomputes = new WeakMap();
const pointWindowSizes = new WeakMap();
function getW(P) {
    // To disable precomputes:
    // return 1;
    return pointWindowSizes.get(P) || 1;
}
function assert0(n) {
    if (n !== _0n)
        throw new Error('invalid wNAF');
}
/**
 * Elliptic curve multiplication of Point by scalar. Fragile.
 * Table generation takes **30MB of ram and 10ms on high-end CPU**,
 * but may take much longer on slow devices. Actual generation will happen on
 * first call of `multiply()`. By default, `BASE` point is precomputed.
 *
 * Scalars should always be less than curve order: this should be checked inside of a curve itself.
 * Creates precomputation tables for fast multiplication:
 * - private scalar is split by fixed size windows of W bits
 * - every window point is collected from window's table & added to accumulator
 * - since windows are different, same point inside tables won't be accessed more than once per calc
 * - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)
 * - +1 window is neccessary for wNAF
 * - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication
 *
 * @todo Research returning 2d JS array of windows, instead of a single window.
 * This would allow windows to be in different memory locations
 */
export class wNAF {
    // Parametrized with a given Point class (not individual point)
    constructor(Point, bits) {
        this.BASE = Point.BASE;
        this.ZERO = Point.ZERO;
        this.Fn = Point.Fn;
        this.bits = bits;
    }
    // non-const time multiplication ladder
    _unsafeLadder(elm, n, p = this.ZERO) {
        let d = elm;
        while (n > _0n) {
            if (n & _1n)
                p = p.add(d);
            d = d.double();
            n >>= _1n;
        }
        return p;
    }
    /**
     * Creates a wNAF precomputation window. Used for caching.
     * Default window size is set by `utils.precompute()` and is equal to 8.
     * Number of precomputed points depends on the curve size:
     * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
     * - 𝑊 is the window size
     * - 𝑛 is the bitlength of the curve order.
     * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
     * @param point Point instance
     * @param W window size
     * @returns precomputed point tables flattened to a single array
     */
    precomputeWindow(point, W) {
        const { windows, windowSize } = calcWOpts(W, this.bits);
        const points = [];
        let p = point;
        let base = p;
        for (let window = 0; window < windows; window++) {
            base = p;
            points.push(base);
            // i=1, bc we skip 0
            for (let i = 1; i < windowSize; i++) {
                base = base.add(p);
                points.push(base);
            }
            p = base.double();
        }
        return points;
    }
    /**
     * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
     * More compact implementation:
     * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
     * @returns real and fake (for const-time) points
     */
    wNAF(W, precomputes, n) {
        // Scalar should be smaller than field order
        if (!this.Fn.isValid(n))
            throw new Error('invalid scalar');
        // Accumulators
        let p = this.ZERO;
        let f = this.BASE;
        // This code was first written with assumption that 'f' and 'p' will never be infinity point:
        // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,
        // there is negate now: it is possible that negated element from low value
        // would be the same as high element, which will create carry into next window.
        // It's not obvious how this can fail, but still worth investigating later.
        const wo = calcWOpts(W, this.bits);
        for (let window = 0; window < wo.windows; window++) {
            // (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise
            const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
            n = nextN;
            if (isZero) {
                // bits are 0: add garbage to fake point
                // Important part for const-time getPublicKey: add random "noise" point to f.
                f = f.add(negateCt(isNegF, precomputes[offsetF]));
            }
            else {
                // bits are 1: add to result point
                p = p.add(negateCt(isNeg, precomputes[offset]));
            }
        }
        assert0(n);
        // Return both real and fake points: JIT won't eliminate f.
        // At this point there is a way to F be infinity-point even if p is not,
        // which makes it less const-time: around 1 bigint multiply.
        return { p, f };
    }
    /**
     * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
     * @param acc accumulator point to add result of multiplication
     * @returns point
     */
    wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
        const wo = calcWOpts(W, this.bits);
        for (let window = 0; window < wo.windows; window++) {
            if (n === _0n)
                break; // Early-exit, skip 0 value
            const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
            n = nextN;
            if (isZero) {
                // Window bits are 0: skip processing.
                // Move to next window.
                continue;
            }
            else {
                const item = precomputes[offset];
                acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM
            }
        }
        assert0(n);
        return acc;
    }
    getPrecomputes(W, point, transform) {
        // Calculate precomputes on a first run, reuse them after
        let comp = pointPrecomputes.get(point);
        if (!comp) {
            comp = this.precomputeWindow(point, W);
            if (W !== 1) {
                // Doing transform outside of if brings 15% perf hit
                if (typeof transform === 'function')
                    comp = transform(comp);
                pointPrecomputes.set(point, comp);
            }
        }
        return comp;
    }
    cached(point, scalar, transform) {
        const W = getW(point);
        return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
    }
    unsafe(point, scalar, transform, prev) {
        const W = getW(point);
        if (W === 1)
            return this._unsafeLadder(point, scalar, prev); // For W=1 ladder is ~x2 faster
        return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
    }
    // We calculate precomputes for elliptic curve point multiplication
    // using windowed method. This specifies window size and
    // stores precomputed values. Usually only base point would be precomputed.
    createCache(P, W) {
        validateW(W, this.bits);
        pointWindowSizes.set(P, W);
        pointPrecomputes.delete(P);
    }
    hasCache(elm) {
        return getW(elm) !== 1;
    }
}
/**
 * Endomorphism-specific multiplication for Koblitz curves.
 * Cost: 128 dbl, 0-256 adds.
 */
export function mulEndoUnsafe(Point, point, k1, k2) {
    let acc = point;
    let p1 = Point.ZERO;
    let p2 = Point.ZERO;
    while (k1 > _0n || k2 > _0n) {
        if (k1 & _1n)
            p1 = p1.add(acc);
        if (k2 & _1n)
            p2 = p2.add(acc);
        acc = acc.double();
        k1 >>= _1n;
        k2 >>= _1n;
    }
    return { p1, p2 };
}
/**
 * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).
 * 30x faster vs naive addition on L=4096, 10x faster than precomputes.
 * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.
 * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.
 * @param c Curve Point constructor
 * @param fieldN field over CURVE.N - important that it's not over CURVE.P
 * @param points array of L curve points
 * @param scalars array of L scalars (aka secret keys / bigints)
 */
export function pippenger(c, fieldN, points, scalars) {
    // If we split scalars by some window (let's say 8 bits), every chunk will only
    // take 256 buckets even if there are 4096 scalars, also re-uses double.
    // TODO:
    // - https://eprint.iacr.org/2024/750.pdf
    // - https://tches.iacr.org/index.php/TCHES/article/view/10287
    // 0 is accepted in scalars
    validateMSMPoints(points, c);
    validateMSMScalars(scalars, fieldN);
    const plength = points.length;
    const slength = scalars.length;
    if (plength !== slength)
        throw new Error('arrays of points and scalars must have equal length');
    // if (plength === 0) throw new Error('array must be of length >= 2');
    const zero = c.ZERO;
    const wbits = bitLen(BigInt(plength));
    let windowSize = 1; // bits
    if (wbits > 12)
        windowSize = wbits - 3;
    else if (wbits > 4)
        windowSize = wbits - 2;
    else if (wbits > 0)
        windowSize = 2;
    const MASK = bitMask(windowSize);
    const buckets = new Array(Number(MASK) + 1).fill(zero); // +1 for zero array
    const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;
    let sum = zero;
    for (let i = lastBits; i >= 0; i -= windowSize) {
        buckets.fill(zero);
        for (let j = 0; j < slength; j++) {
            const scalar = scalars[j];
            const wbits = Number((scalar >> BigInt(i)) & MASK);
            buckets[wbits] = buckets[wbits].add(points[j]);
        }
        let resI = zero; // not using this will do small speed-up, but will lose ct
        // Skip first bucket, because it is zero
        for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {
            sumI = sumI.add(buckets[j]);
            resI = resI.add(sumI);
        }
        sum = sum.add(resI);
        if (i !== 0)
            for (let j = 0; j < windowSize; j++)
                sum = sum.double();
    }
    return sum;
}
/**
 * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).
 * @param c Curve Point constructor
 * @param fieldN field over CURVE.N - important that it's not over CURVE.P
 * @param points array of L curve points
 * @returns function which multiplies points with scaars
 */
export function precomputeMSMUnsafe(c, fieldN, points, windowSize) {
    /**
     * Performance Analysis of Window-based Precomputation
     *
     * Base Case (256-bit scalar, 8-bit window):
     * - Standard precomputation requires:
     *   - 31 additions per scalar × 256 scalars = 7,936 ops
     *   - Plus 255 summary additions = 8,191 total ops
     *   Note: Summary additions can be optimized via accumulator
     *
     * Chunked Precomputation Analysis:
     * - Using 32 chunks requires:
     *   - 255 additions per chunk
     *   - 256 doublings
     *   - Total: (255 × 32) + 256 = 8,416 ops
     *
     * Memory Usage Comparison:
     * Window Size | Standard Points | Chunked Points
     * ------------|-----------------|---------------
     *     4-bit   |     520         |      15
     *     8-bit   |    4,224        |     255
     *    10-bit   |   13,824        |   1,023
     *    16-bit   |  557,056        |  65,535
     *
     * Key Advantages:
     * 1. Enables larger window sizes due to reduced memory overhead
     * 2. More efficient for smaller scalar counts:
     *    - 16 chunks: (16 × 255) + 256 = 4,336 ops
     *    - ~2x faster than standard 8,191 ops
     *
     * Limitations:
     * - Not suitable for plain precomputes (requires 256 constant doublings)
     * - Performance degrades with larger scalar counts:
     *   - Optimal for ~256 scalars
     *   - Less efficient for 4096+ scalars (Pippenger preferred)
     */
    validateW(windowSize, fieldN.BITS);
    validateMSMPoints(points, c);
    const zero = c.ZERO;
    const tableSize = 2 ** windowSize - 1; // table size (without zero)
    const chunks = Math.ceil(fieldN.BITS / windowSize); // chunks of item
    const MASK = bitMask(windowSize);
    const tables = points.map((p) => {
        const res = [];
        for (let i = 0, acc = p; i < tableSize; i++) {
            res.push(acc);
            acc = acc.add(p);
        }
        return res;
    });
    return (scalars) => {
        validateMSMScalars(scalars, fieldN);
        if (scalars.length > points.length)
            throw new Error('array of scalars must be smaller than array of points');
        let res = zero;
        for (let i = 0; i < chunks; i++) {
            // No need to double if accumulator is still zero.
            if (res !== zero)
                for (let j = 0; j < windowSize; j++)
                    res = res.double();
            const shiftBy = BigInt(chunks * windowSize - (i + 1) * windowSize);
            for (let j = 0; j < scalars.length; j++) {
                const n = scalars[j];
                const curr = Number((n >> shiftBy) & MASK);
                if (!curr)
                    continue; // skip zero scalars chunks
                res = res.add(tables[j][curr - 1]);
            }
        }
        return res;
    };
}
// TODO: remove
/** @deprecated */
export function validateBasic(curve) {
    validateField(curve.Fp);
    validateObject(curve, {
        n: 'bigint',
        h: 'bigint',
        Gx: 'field',
        Gy: 'field',
    }, {
        nBitLength: 'isSafeInteger',
        nByteLength: 'isSafeInteger',
    });
    // Set defaults
    return Object.freeze({
        ...nLength(curve.n, curve.nBitLength),
        ...curve,
        ...{ p: curve.Fp.ORDER },
    });
}
function createField(order, field, isLE) {
    if (field) {
        if (field.ORDER !== order)
            throw new Error('Field.ORDER must match order: Fp == p, Fn == n');
        validateField(field);
        return field;
    }
    else {
        return Field(order, { isLE });
    }
}
/** Validates CURVE opts and creates fields */
export function _createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
    if (FpFnLE === undefined)
        FpFnLE = type === 'edwards';
    if (!CURVE || typeof CURVE !== 'object')
        throw new Error(`expected valid ${type} CURVE object`);
    for (const p of ['p', 'n', 'h']) {
        const val = CURVE[p];
        if (!(typeof val === 'bigint' && val > _0n))
            throw new Error(`CURVE.${p} must be positive bigint`);
    }
    const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);
    const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
    const _b = type === 'weierstrass' ? 'b' : 'd';
    const params = ['Gx', 'Gy', 'a', _b];
    for (const p of params) {
        // @ts-ignore
        if (!Fp.isValid(CURVE[p]))
            throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
    }
    CURVE = Object.freeze(Object.assign({}, CURVE));
    return { CURVE, Fp, Fn };
}
//# sourceMappingURL=curve.js.mapimport { _validateObject, abytes, bytesToNumberBE, concatBytes, isBytes, isHash, utf8ToBytes, } from "../utils.js";
import { FpInvertBatch, mod } from "./modular.js";
// Octet Stream to Integer. "spec" implementation of os2ip is 2.5x slower vs bytesToNumberBE.
const os2ip = bytesToNumberBE;
// Integer to Octet Stream (numberToBytesBE)
function i2osp(value, length) {
    anum(value);
    anum(length);
    if (value < 0 || value >= 1 << (8 * length))
        throw new Error('invalid I2OSP input: ' + value);
    const res = Array.from({ length }).fill(0);
    for (let i = length - 1; i >= 0; i--) {
        res[i] = value & 0xff;
        value >>>= 8;
    }
    return new Uint8Array(res);
}
function strxor(a, b) {
    const arr = new Uint8Array(a.length);
    for (let i = 0; i < a.length; i++) {
        arr[i] = a[i] ^ b[i];
    }
    return arr;
}
function anum(item) {
    if (!Number.isSafeInteger(item))
        throw new Error('number expected');
}
function normDST(DST) {
    if (!isBytes(DST) && typeof DST !== 'string')
        throw new Error('DST must be Uint8Array or string');
    return typeof DST === 'string' ? utf8ToBytes(DST) : DST;
}
/**
 * Produces a uniformly random byte string using a cryptographic hash function H that outputs b bits.
 * [RFC 9380 5.3.1](https://www.rfc-editor.org/rfc/rfc9380#section-5.3.1).
 */
export function expand_message_xmd(msg, DST, lenInBytes, H) {
    abytes(msg);
    anum(lenInBytes);
    DST = normDST(DST);
    // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3
    if (DST.length > 255)
        DST = H(concatBytes(utf8ToBytes('H2C-OVERSIZE-DST-'), DST));
    const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H;
    const ell = Math.ceil(lenInBytes / b_in_bytes);
    if (lenInBytes > 65535 || ell > 255)
        throw new Error('expand_message_xmd: invalid lenInBytes');
    const DST_prime = concatBytes(DST, i2osp(DST.length, 1));
    const Z_pad = i2osp(0, r_in_bytes);
    const l_i_b_str = i2osp(lenInBytes, 2); // len_in_bytes_str
    const b = new Array(ell);
    const b_0 = H(concatBytes(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));
    b[0] = H(concatBytes(b_0, i2osp(1, 1), DST_prime));
    for (let i = 1; i <= ell; i++) {
        const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime];
        b[i] = H(concatBytes(...args));
    }
    const pseudo_random_bytes = concatBytes(...b);
    return pseudo_random_bytes.slice(0, lenInBytes);
}
/**
 * Produces a uniformly random byte string using an extendable-output function (XOF) H.
 * 1. The collision resistance of H MUST be at least k bits.
 * 2. H MUST be an XOF that has been proved indifferentiable from
 *    a random oracle under a reasonable cryptographic assumption.
 * [RFC 9380 5.3.2](https://www.rfc-editor.org/rfc/rfc9380#section-5.3.2).
 */
export function expand_message_xof(msg, DST, lenInBytes, k, H) {
    abytes(msg);
    anum(lenInBytes);
    DST = normDST(DST);
    // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3
    // DST = H('H2C-OVERSIZE-DST-' || a_very_long_DST, Math.ceil((lenInBytes * k) / 8));
    if (DST.length > 255) {
        const dkLen = Math.ceil((2 * k) / 8);
        DST = H.create({ dkLen }).update(utf8ToBytes('H2C-OVERSIZE-DST-')).update(DST).digest();
    }
    if (lenInBytes > 65535 || DST.length > 255)
        throw new Error('expand_message_xof: invalid lenInBytes');
    return (H.create({ dkLen: lenInBytes })
        .update(msg)
        .update(i2osp(lenInBytes, 2))
        // 2. DST_prime = DST || I2OSP(len(DST), 1)
        .update(DST)
        .update(i2osp(DST.length, 1))
        .digest());
}
/**
 * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F.
 * [RFC 9380 5.2](https://www.rfc-editor.org/rfc/rfc9380#section-5.2).
 * @param msg a byte string containing the message to hash
 * @param count the number of elements of F to output
 * @param options `{DST: string, p: bigint, m: number, k: number, expand: 'xmd' | 'xof', hash: H}`, see above
 * @returns [u_0, ..., u_(count - 1)], a list of field elements.
 */
export function hash_to_field(msg, count, options) {
    _validateObject(options, {
        p: 'bigint',
        m: 'number',
        k: 'number',
        hash: 'function',
    });
    const { p, k, m, hash, expand, DST } = options;
    if (!isHash(options.hash))
        throw new Error('expected valid hash');
    abytes(msg);
    anum(count);
    const log2p = p.toString(2).length;
    const L = Math.ceil((log2p + k) / 8); // section 5.1 of ietf draft link above
    const len_in_bytes = count * m * L;
    let prb; // pseudo_random_bytes
    if (expand === 'xmd') {
        prb = expand_message_xmd(msg, DST, len_in_bytes, hash);
    }
    else if (expand === 'xof') {
        prb = expand_message_xof(msg, DST, len_in_bytes, k, hash);
    }
    else if (expand === '_internal_pass') {
        // for internal tests only
        prb = msg;
    }
    else {
        throw new Error('expand must be "xmd" or "xof"');
    }
    const u = new Array(count);
    for (let i = 0; i < count; i++) {
        const e = new Array(m);
        for (let j = 0; j < m; j++) {
            const elm_offset = L * (j + i * m);
            const tv = prb.subarray(elm_offset, elm_offset + L);
            e[j] = mod(os2ip(tv), p);
        }
        u[i] = e;
    }
    return u;
}
export function isogenyMap(field, map) {
    // Make same order as in spec
    const coeff = map.map((i) => Array.from(i).reverse());
    return (x, y) => {
        const [xn, xd, yn, yd] = coeff.map((val) => val.reduce((acc, i) => field.add(field.mul(acc, x), i)));
        // 6.6.3
        // Exceptional cases of iso_map are inputs that cause the denominator of
        // either rational function to evaluate to zero; such cases MUST return
        // the identity point on E.
        const [xd_inv, yd_inv] = FpInvertBatch(field, [xd, yd], true);
        x = field.mul(xn, xd_inv); // xNum / xDen
        y = field.mul(y, field.mul(yn, yd_inv)); // y * (yNum / yDev)
        return { x, y };
    };
}
export const _DST_scalar = utf8ToBytes('HashToScalar-');
/** Creates hash-to-curve methods from EC Point and mapToCurve function. See {@link H2CHasher}. */
export function createHasher(Point, mapToCurve, defaults) {
    if (typeof mapToCurve !== 'function')
        throw new Error('mapToCurve() must be defined');
    function map(num) {
        return Point.fromAffine(mapToCurve(num));
    }
    function clear(initial) {
        const P = initial.clearCofactor();
        if (P.equals(Point.ZERO))
            return Point.ZERO; // zero will throw in assert
        P.assertValidity();
        return P;
    }
    return {
        defaults,
        hashToCurve(msg, options) {
            const opts = Object.assign({}, defaults, options);
            const u = hash_to_field(msg, 2, opts);
            const u0 = map(u[0]);
            const u1 = map(u[1]);
            return clear(u0.add(u1));
        },
        encodeToCurve(msg, options) {
            const optsDst = defaults.encodeDST ? { DST: defaults.encodeDST } : {};
            const opts = Object.assign({}, defaults, optsDst, options);
            const u = hash_to_field(msg, 1, opts);
            const u0 = map(u[0]);
            return clear(u0);
        },
        /** See {@link H2CHasher} */
        mapToCurve(scalars) {
            if (!Array.isArray(scalars))
                throw new Error('expected array of bigints');
            for (const i of scalars)
                if (typeof i !== 'bigint')
                    throw new Error('expected array of bigints');
            return clear(map(scalars));
        },
        // hash_to_scalar can produce 0: https://www.rfc-editor.org/errata/eid8393
        // RFC 9380, draft-irtf-cfrg-bbs-signatures-08
        hashToScalar(msg, options) {
            // @ts-ignore
            const N = Point.Fn.ORDER;
            const opts = Object.assign({}, defaults, { p: N, m: 1, DST: _DST_scalar }, options);
            return hash_to_field(msg, 1, opts)[0][0];
        },
    };
}
//# sourceMappingURL=hash-to-curve.js.map/**
 * Utils for modular division and fields.
 * Field over 11 is a finite (Galois) field is integer number operations `mod 11`.
 * There is no division: it is replaced by modular multiplicative inverse.
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { _validateObject, anumber, bitMask, bytesToNumberBE, bytesToNumberLE, ensureBytes, numberToBytesBE, numberToBytesLE, } from "../utils.js";
// prettier-ignore
const _0n = BigInt(0), _1n = BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3);
// prettier-ignore
const _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5), _7n = /* @__PURE__ */ BigInt(7);
// prettier-ignore
const _8n = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9), _16n = /* @__PURE__ */ BigInt(16);
// Calculates a modulo b
export function mod(a, b) {
    const result = a % b;
    return result >= _0n ? result : b + result;
}
/**
 * Efficiently raise num to power and do modular division.
 * Unsafe in some contexts: uses ladder, so can expose bigint bits.
 * @example
 * pow(2n, 6n, 11n) // 64n % 11n == 9n
 */
export function pow(num, power, modulo) {
    return FpPow(Field(modulo), num, power);
}
/** Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)` */
export function pow2(x, power, modulo) {
    let res = x;
    while (power-- > _0n) {
        res *= res;
        res %= modulo;
    }
    return res;
}
/**
 * Inverses number over modulo.
 * Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).
 */
export function invert(number, modulo) {
    if (number === _0n)
        throw new Error('invert: expected non-zero number');
    if (modulo <= _0n)
        throw new Error('invert: expected positive modulus, got ' + modulo);
    // Fermat's little theorem "CT-like" version inv(n) = n^(m-2) mod m is 30x slower.
    let a = mod(number, modulo);
    let b = modulo;
    // prettier-ignore
    let x = _0n, y = _1n, u = _1n, v = _0n;
    while (a !== _0n) {
        // JIT applies optimization if those two lines follow each other
        const q = b / a;
        const r = b % a;
        const m = x - u * q;
        const n = y - v * q;
        // prettier-ignore
        b = a, a = r, x = u, y = v, u = m, v = n;
    }
    const gcd = b;
    if (gcd !== _1n)
        throw new Error('invert: does not exist');
    return mod(x, modulo);
}
function assertIsSquare(Fp, root, n) {
    if (!Fp.eql(Fp.sqr(root), n))
        throw new Error('Cannot find square root');
}
// Not all roots are possible! Example which will throw:
// const NUM =
// n = 72057594037927816n;
// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));
function sqrt3mod4(Fp, n) {
    const p1div4 = (Fp.ORDER + _1n) / _4n;
    const root = Fp.pow(n, p1div4);
    assertIsSquare(Fp, root, n);
    return root;
}
function sqrt5mod8(Fp, n) {
    const p5div8 = (Fp.ORDER - _5n) / _8n;
    const n2 = Fp.mul(n, _2n);
    const v = Fp.pow(n2, p5div8);
    const nv = Fp.mul(n, v);
    const i = Fp.mul(Fp.mul(nv, _2n), v);
    const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
    assertIsSquare(Fp, root, n);
    return root;
}
// Based on RFC9380, Kong algorithm
// prettier-ignore
function sqrt9mod16(P) {
    const Fp_ = Field(P);
    const tn = tonelliShanks(P);
    const c1 = tn(Fp_, Fp_.neg(Fp_.ONE)); //  1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F
    const c2 = tn(Fp_, c1); //  2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F
    const c3 = tn(Fp_, Fp_.neg(c1)); //  3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F
    const c4 = (P + _7n) / _16n; //  4. c4 = (q + 7) / 16        # Integer arithmetic
    return (Fp, n) => {
        let tv1 = Fp.pow(n, c4); //  1. tv1 = x^c4
        let tv2 = Fp.mul(tv1, c1); //  2. tv2 = c1 * tv1
        const tv3 = Fp.mul(tv1, c2); //  3. tv3 = c2 * tv1
        const tv4 = Fp.mul(tv1, c3); //  4. tv4 = c3 * tv1
        const e1 = Fp.eql(Fp.sqr(tv2), n); //  5.  e1 = (tv2^2) == x
        const e2 = Fp.eql(Fp.sqr(tv3), n); //  6.  e2 = (tv3^2) == x
        tv1 = Fp.cmov(tv1, tv2, e1); //  7. tv1 = CMOV(tv1, tv2, e1)  # Select tv2 if (tv2^2) == x
        tv2 = Fp.cmov(tv4, tv3, e2); //  8. tv2 = CMOV(tv4, tv3, e2)  # Select tv3 if (tv3^2) == x
        const e3 = Fp.eql(Fp.sqr(tv2), n); //  9.  e3 = (tv2^2) == x
        const root = Fp.cmov(tv1, tv2, e3); // 10.  z = CMOV(tv1, tv2, e3)   # Select sqrt from tv1 & tv2
        assertIsSquare(Fp, root, n);
        return root;
    };
}
/**
 * Tonelli-Shanks square root search algorithm.
 * 1. https://eprint.iacr.org/2012/685.pdf (page 12)
 * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks
 * @param P field order
 * @returns function that takes field Fp (created from P) and number n
 */
export function tonelliShanks(P) {
    // Initialization (precomputation).
    // Caching initialization could boost perf by 7%.
    if (P < _3n)
        throw new Error('sqrt is not defined for small field');
    // Factor P - 1 = Q * 2^S, where Q is odd
    let Q = P - _1n;
    let S = 0;
    while (Q % _2n === _0n) {
        Q /= _2n;
        S++;
    }
    // Find the first quadratic non-residue Z >= 2
    let Z = _2n;
    const _Fp = Field(P);
    while (FpLegendre(_Fp, Z) === 1) {
        // Basic primality test for P. After x iterations, chance of
        // not finding quadratic non-residue is 2^x, so 2^1000.
        if (Z++ > 1000)
            throw new Error('Cannot find square root: probably non-prime P');
    }
    // Fast-path; usually done before Z, but we do "primality test".
    if (S === 1)
        return sqrt3mod4;
    // Slow-path
    // TODO: test on Fp2 and others
    let cc = _Fp.pow(Z, Q); // c = z^Q
    const Q1div2 = (Q + _1n) / _2n;
    return function tonelliSlow(Fp, n) {
        if (Fp.is0(n))
            return n;
        // Check if n is a quadratic residue using Legendre symbol
        if (FpLegendre(Fp, n) !== 1)
            throw new Error('Cannot find square root');
        // Initialize variables for the main loop
        let M = S;
        let c = Fp.mul(Fp.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp
        let t = Fp.pow(n, Q); // t = n^Q, first guess at the fudge factor
        let R = Fp.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root
        // Main loop
        // while t != 1
        while (!Fp.eql(t, Fp.ONE)) {
            if (Fp.is0(t))
                return Fp.ZERO; // if t=0 return R=0
            let i = 1;
            // Find the smallest i >= 1 such that t^(2^i) ≡ 1 (mod P)
            let t_tmp = Fp.sqr(t); // t^(2^1)
            while (!Fp.eql(t_tmp, Fp.ONE)) {
                i++;
                t_tmp = Fp.sqr(t_tmp); // t^(2^2)...
                if (i === M)
                    throw new Error('Cannot find square root');
            }
            // Calculate the exponent for b: 2^(M - i - 1)
            const exponent = _1n << BigInt(M - i - 1); // bigint is important
            const b = Fp.pow(c, exponent); // b = 2^(M - i - 1)
            // Update variables
            M = i;
            c = Fp.sqr(b); // c = b^2
            t = Fp.mul(t, c); // t = (t * b^2)
            R = Fp.mul(R, b); // R = R*b
        }
        return R;
    };
}
/**
 * Square root for a finite field. Will try optimized versions first:
 *
 * 1. P ≡ 3 (mod 4)
 * 2. P ≡ 5 (mod 8)
 * 3. P ≡ 9 (mod 16)
 * 4. Tonelli-Shanks algorithm
 *
 * Different algorithms can give different roots, it is up to user to decide which one they want.
 * For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).
 */
export function FpSqrt(P) {
    // P ≡ 3 (mod 4) => √n = n^((P+1)/4)
    if (P % _4n === _3n)
        return sqrt3mod4;
    // P ≡ 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf
    if (P % _8n === _5n)
        return sqrt5mod8;
    // P ≡ 9 (mod 16) => Kong algorithm, page 11 of https://eprint.iacr.org/2012/685.pdf (algorithm 4)
    if (P % _16n === _9n)
        return sqrt9mod16(P);
    // Tonelli-Shanks algorithm
    return tonelliShanks(P);
}
// Little-endian check for first LE bit (last BE bit);
export const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n;
// prettier-ignore
const FIELD_FIELDS = [
    'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',
    'eql', 'add', 'sub', 'mul', 'pow', 'div',
    'addN', 'subN', 'mulN', 'sqrN'
];
export function validateField(field) {
    const initial = {
        ORDER: 'bigint',
        MASK: 'bigint',
        BYTES: 'number',
        BITS: 'number',
    };
    const opts = FIELD_FIELDS.reduce((map, val) => {
        map[val] = 'function';
        return map;
    }, initial);
    _validateObject(field, opts);
    // const max = 16384;
    // if (field.BYTES < 1 || field.BYTES > max) throw new Error('invalid field');
    // if (field.BITS < 1 || field.BITS > 8 * max) throw new Error('invalid field');
    return field;
}
// Generic field functions
/**
 * Same as `pow` but for Fp: non-constant-time.
 * Unsafe in some contexts: uses ladder, so can expose bigint bits.
 */
export function FpPow(Fp, num, power) {
    if (power < _0n)
        throw new Error('invalid exponent, negatives unsupported');
    if (power === _0n)
        return Fp.ONE;
    if (power === _1n)
        return num;
    let p = Fp.ONE;
    let d = num;
    while (power > _0n) {
        if (power & _1n)
            p = Fp.mul(p, d);
        d = Fp.sqr(d);
        power >>= _1n;
    }
    return p;
}
/**
 * Efficiently invert an array of Field elements.
 * Exception-free. Will return `undefined` for 0 elements.
 * @param passZero map 0 to 0 (instead of undefined)
 */
export function FpInvertBatch(Fp, nums, passZero = false) {
    const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : undefined);
    // Walk from first to last, multiply them by each other MOD p
    const multipliedAcc = nums.reduce((acc, num, i) => {
        if (Fp.is0(num))
            return acc;
        inverted[i] = acc;
        return Fp.mul(acc, num);
    }, Fp.ONE);
    // Invert last element
    const invertedAcc = Fp.inv(multipliedAcc);
    // Walk from last to first, multiply them by inverted each other MOD p
    nums.reduceRight((acc, num, i) => {
        if (Fp.is0(num))
            return acc;
        inverted[i] = Fp.mul(acc, inverted[i]);
        return Fp.mul(acc, num);
    }, invertedAcc);
    return inverted;
}
// TODO: remove
export function FpDiv(Fp, lhs, rhs) {
    return Fp.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, Fp.ORDER) : Fp.inv(rhs));
}
/**
 * Legendre symbol.
 * Legendre constant is used to calculate Legendre symbol (a | p)
 * which denotes the value of a^((p-1)/2) (mod p).
 *
 * * (a | p) ≡ 1    if a is a square (mod p), quadratic residue
 * * (a | p) ≡ -1   if a is not a square (mod p), quadratic non residue
 * * (a | p) ≡ 0    if a ≡ 0 (mod p)
 */
export function FpLegendre(Fp, n) {
    // We can use 3rd argument as optional cache of this value
    // but seems unneeded for now. The operation is very fast.
    const p1mod2 = (Fp.ORDER - _1n) / _2n;
    const powered = Fp.pow(n, p1mod2);
    const yes = Fp.eql(powered, Fp.ONE);
    const zero = Fp.eql(powered, Fp.ZERO);
    const no = Fp.eql(powered, Fp.neg(Fp.ONE));
    if (!yes && !zero && !no)
        throw new Error('invalid Legendre symbol result');
    return yes ? 1 : zero ? 0 : -1;
}
// This function returns True whenever the value x is a square in the field F.
export function FpIsSquare(Fp, n) {
    const l = FpLegendre(Fp, n);
    return l === 1;
}
// CURVE.n lengths
export function nLength(n, nBitLength) {
    // Bit size, byte size of CURVE.n
    if (nBitLength !== undefined)
        anumber(nBitLength);
    const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;
    const nByteLength = Math.ceil(_nBitLength / 8);
    return { nBitLength: _nBitLength, nByteLength };
}
/**
 * Creates a finite field. Major performance optimizations:
 * * 1. Denormalized operations like mulN instead of mul.
 * * 2. Identical object shape: never add or remove keys.
 * * 3. `Object.freeze`.
 * Fragile: always run a benchmark on a change.
 * Security note: operations don't check 'isValid' for all elements for performance reasons,
 * it is caller responsibility to check this.
 * This is low-level code, please make sure you know what you're doing.
 *
 * Note about field properties:
 * * CHARACTERISTIC p = prime number, number of elements in main subgroup.
 * * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.
 *
 * @param ORDER field order, probably prime, or could be composite
 * @param bitLen how many bits the field consumes
 * @param isLE (default: false) if encoding / decoding should be in little-endian
 * @param redef optional faster redefinitions of sqrt and other methods
 */
export function Field(ORDER, bitLenOrOpts, // TODO: use opts only in v2?
isLE = false, opts = {}) {
    if (ORDER <= _0n)
        throw new Error('invalid field: expected ORDER > 0, got ' + ORDER);
    let _nbitLength = undefined;
    let _sqrt = undefined;
    let modFromBytes = false;
    let allowedLengths = undefined;
    if (typeof bitLenOrOpts === 'object' && bitLenOrOpts != null) {
        if (opts.sqrt || isLE)
            throw new Error('cannot specify opts in two arguments');
        const _opts = bitLenOrOpts;
        if (_opts.BITS)
            _nbitLength = _opts.BITS;
        if (_opts.sqrt)
            _sqrt = _opts.sqrt;
        if (typeof _opts.isLE === 'boolean')
            isLE = _opts.isLE;
        if (typeof _opts.modFromBytes === 'boolean')
            modFromBytes = _opts.modFromBytes;
        allowedLengths = _opts.allowedLengths;
    }
    else {
        if (typeof bitLenOrOpts === 'number')
            _nbitLength = bitLenOrOpts;
        if (opts.sqrt)
            _sqrt = opts.sqrt;
    }
    const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, _nbitLength);
    if (BYTES > 2048)
        throw new Error('invalid field: expected ORDER of <= 2048 bytes');
    let sqrtP; // cached sqrtP
    const f = Object.freeze({
        ORDER,
        isLE,
        BITS,
        BYTES,
        MASK: bitMask(BITS),
        ZERO: _0n,
        ONE: _1n,
        allowedLengths: allowedLengths,
        create: (num) => mod(num, ORDER),
        isValid: (num) => {
            if (typeof num !== 'bigint')
                throw new Error('invalid field element: expected bigint, got ' + typeof num);
            return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible
        },
        is0: (num) => num === _0n,
        // is valid and invertible
        isValidNot0: (num) => !f.is0(num) && f.isValid(num),
        isOdd: (num) => (num & _1n) === _1n,
        neg: (num) => mod(-num, ORDER),
        eql: (lhs, rhs) => lhs === rhs,
        sqr: (num) => mod(num * num, ORDER),
        add: (lhs, rhs) => mod(lhs + rhs, ORDER),
        sub: (lhs, rhs) => mod(lhs - rhs, ORDER),
        mul: (lhs, rhs) => mod(lhs * rhs, ORDER),
        pow: (num, power) => FpPow(f, num, power),
        div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),
        // Same as above, but doesn't normalize
        sqrN: (num) => num * num,
        addN: (lhs, rhs) => lhs + rhs,
        subN: (lhs, rhs) => lhs - rhs,
        mulN: (lhs, rhs) => lhs * rhs,
        inv: (num) => invert(num, ORDER),
        sqrt: _sqrt ||
            ((n) => {
                if (!sqrtP)
                    sqrtP = FpSqrt(ORDER);
                return sqrtP(f, n);
            }),
        toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),
        fromBytes: (bytes, skipValidation = true) => {
            if (allowedLengths) {
                if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
                    throw new Error('Field.fromBytes: expected ' + allowedLengths + ' bytes, got ' + bytes.length);
                }
                const padded = new Uint8Array(BYTES);
                // isLE add 0 to right, !isLE to the left.
                padded.set(bytes, isLE ? 0 : padded.length - bytes.length);
                bytes = padded;
            }
            if (bytes.length !== BYTES)
                throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);
            let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
            if (modFromBytes)
                scalar = mod(scalar, ORDER);
            if (!skipValidation)
                if (!f.isValid(scalar))
                    throw new Error('invalid field element: outside of range 0..ORDER');
            // NOTE: we don't validate scalar here, please use isValid. This done such way because some
            // protocol may allow non-reduced scalar that reduced later or changed some other way.
            return scalar;
        },
        // TODO: we don't need it here, move out to separate fn
        invertBatch: (lst) => FpInvertBatch(f, lst),
        // We can't move this out because Fp6, Fp12 implement it
        // and it's unclear what to return in there.
        cmov: (a, b, c) => (c ? b : a),
    });
    return Object.freeze(f);
}
// Generic random scalar, we can do same for other fields if via Fp2.mul(Fp2.ONE, Fp2.random)?
// This allows unsafe methods like ignore bias or zero. These unsafe, but often used in different protocols (if deterministic RNG).
// which mean we cannot force this via opts.
// Not sure what to do with randomBytes, we can accept it inside opts if wanted.
// Probably need to export getMinHashLength somewhere?
// random(bytes?: Uint8Array, unsafeAllowZero = false, unsafeAllowBias = false) {
//   const LEN = !unsafeAllowBias ? getMinHashLength(ORDER) : BYTES;
//   if (bytes === undefined) bytes = randomBytes(LEN); // _opts.randomBytes?
//   const num = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
//   // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0
//   const reduced = unsafeAllowZero ? mod(num, ORDER) : mod(num, ORDER - _1n) + _1n;
//   return reduced;
// },
export function FpSqrtOdd(Fp, elm) {
    if (!Fp.isOdd)
        throw new Error("Field doesn't have isOdd");
    const root = Fp.sqrt(elm);
    return Fp.isOdd(root) ? root : Fp.neg(root);
}
export function FpSqrtEven(Fp, elm) {
    if (!Fp.isOdd)
        throw new Error("Field doesn't have isOdd");
    const root = Fp.sqrt(elm);
    return Fp.isOdd(root) ? Fp.neg(root) : root;
}
/**
 * "Constant-time" private key generation utility.
 * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field).
 * Which makes it slightly more biased, less secure.
 * @deprecated use `mapKeyToField` instead
 */
export function hashToPrivateScalar(hash, groupOrder, isLE = false) {
    hash = ensureBytes('privateHash', hash);
    const hashLen = hash.length;
    const minLen = nLength(groupOrder).nByteLength + 8;
    if (minLen < 24 || hashLen < minLen || hashLen > 1024)
        throw new Error('hashToPrivateScalar: expected ' + minLen + '-1024 bytes of input, got ' + hashLen);
    const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash);
    return mod(num, groupOrder - _1n) + _1n;
}
/**
 * Returns total number of bytes consumed by the field element.
 * For example, 32 bytes for usual 256-bit weierstrass curve.
 * @param fieldOrder number of field elements, usually CURVE.n
 * @returns byte length of field
 */
export function getFieldBytesLength(fieldOrder) {
    if (typeof fieldOrder !== 'bigint')
        throw new Error('field order must be bigint');
    const bitLength = fieldOrder.toString(2).length;
    return Math.ceil(bitLength / 8);
}
/**
 * Returns minimal amount of bytes that can be safely reduced
 * by field order.
 * Should be 2^-128 for 128-bit curve such as P256.
 * @param fieldOrder number of field elements, usually CURVE.n
 * @returns byte length of target hash
 */
export function getMinHashLength(fieldOrder) {
    const length = getFieldBytesLength(fieldOrder);
    return length + Math.ceil(length / 2);
}
/**
 * "Constant-time" private key generation utility.
 * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF
 * and convert them into private scalar, with the modulo bias being negligible.
 * Needs at least 48 bytes of input for 32-byte private key.
 * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/
 * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final
 * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5
 * @param hash hash output from SHA3 or a similar function
 * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)
 * @param isLE interpret hash bytes as LE num
 * @returns valid private scalar
 */
export function mapHashToField(key, fieldOrder, isLE = false) {
    const len = key.length;
    const fieldLen = getFieldBytesLength(fieldOrder);
    const minLen = getMinHashLength(fieldOrder);
    // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.
    if (len < 16 || len < minLen || len > 1024)
        throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);
    const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);
    // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0
    const reduced = mod(num, fieldOrder - _1n) + _1n;
    return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
}
//# sourceMappingURL=modular.js.map/**
 * Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.
 *
 * ### Design rationale for types
 *
 * * Interaction between classes from different curves should fail:
 *   `k256.Point.BASE.add(p256.Point.BASE)`
 * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime
 * * Different calls of `curve()` would return different classes -
 *   `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,
 *   it won't affect others
 *
 * TypeScript can't infer types for classes created inside a function. Classes is one instance
 * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create
 * unique type for every function call.
 *
 * We can use generic types via some param, like curve opts, but that would:
 *     1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)
 *     which is hard to debug.
 *     2. Params can be generic and we can't enforce them to be constant value:
 *     if somebody creates curve from non-constant params,
 *     it would be allowed to interact with other curves with non-constant params
 *
 * @todo https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { hmac as nobleHmac } from '@noble/hashes/hmac.js';
import { ahash } from '@noble/hashes/utils';
import { _validateObject, _abool2 as abool, _abytes2 as abytes, aInRange, bitLen, bitMask, bytesToHex, bytesToNumberBE, concatBytes, createHmacDrbg, ensureBytes, hexToBytes, inRange, isBytes, memoized, numberToHexUnpadded, randomBytes as randomBytesWeb, } from "../utils.js";
import { _createCurveFields, mulEndoUnsafe, negateCt, normalizeZ, pippenger, wNAF, } from "./curve.js";
import { Field, FpInvertBatch, getMinHashLength, mapHashToField, nLength, validateField, } from "./modular.js";
// We construct basis in such way that den is always positive and equals n, but num sign depends on basis (not on secret value)
const divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n) / den;
/**
 * Splits scalar for GLV endomorphism.
 */
export function _splitEndoScalar(k, basis, n) {
    // Split scalar into two such that part is ~half bits: `abs(part) < sqrt(N)`
    // Since part can be negative, we need to do this on point.
    // TODO: verifyScalar function which consumes lambda
    const [[a1, b1], [a2, b2]] = basis;
    const c1 = divNearest(b2 * k, n);
    const c2 = divNearest(-b1 * k, n);
    // |k1|/|k2| is < sqrt(N), but can be negative.
    // If we do `k1 mod N`, we'll get big scalar (`> sqrt(N)`): so, we do cheaper negation instead.
    let k1 = k - c1 * a1 - c2 * a2;
    let k2 = -c1 * b1 - c2 * b2;
    const k1neg = k1 < _0n;
    const k2neg = k2 < _0n;
    if (k1neg)
        k1 = -k1;
    if (k2neg)
        k2 = -k2;
    // Double check that resulting scalar less than half bits of N: otherwise wNAF will fail.
    // This should only happen on wrong basises. Also, math inside is too complex and I don't trust it.
    const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n; // Half bits of N
    if (k1 < _0n || k1 >= MAX_NUM || k2 < _0n || k2 >= MAX_NUM) {
        throw new Error('splitScalar (endomorphism): failed, k=' + k);
    }
    return { k1neg, k1, k2neg, k2 };
}
function validateSigFormat(format) {
    if (!['compact', 'recovered', 'der'].includes(format))
        throw new Error('Signature format must be "compact", "recovered", or "der"');
    return format;
}
function validateSigOpts(opts, def) {
    const optsn = {};
    for (let optName of Object.keys(def)) {
        // @ts-ignore
        optsn[optName] = opts[optName] === undefined ? def[optName] : opts[optName];
    }
    abool(optsn.lowS, 'lowS');
    abool(optsn.prehash, 'prehash');
    if (optsn.format !== undefined)
        validateSigFormat(optsn.format);
    return optsn;
}
export class DERErr extends Error {
    constructor(m = '') {
        super(m);
    }
}
/**
 * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:
 *
 *     [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]
 *
 * Docs: https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/, https://luca.ntop.org/Teaching/Appunti/asn1.html
 */
export const DER = {
    // asn.1 DER encoding utils
    Err: DERErr,
    // Basic building block is TLV (Tag-Length-Value)
    _tlv: {
        encode: (tag, data) => {
            const { Err: E } = DER;
            if (tag < 0 || tag > 256)
                throw new E('tlv.encode: wrong tag');
            if (data.length & 1)
                throw new E('tlv.encode: unpadded data');
            const dataLen = data.length / 2;
            const len = numberToHexUnpadded(dataLen);
            if ((len.length / 2) & 128)
                throw new E('tlv.encode: long form length too big');
            // length of length with long form flag
            const lenLen = dataLen > 127 ? numberToHexUnpadded((len.length / 2) | 128) : '';
            const t = numberToHexUnpadded(tag);
            return t + lenLen + len + data;
        },
        // v - value, l - left bytes (unparsed)
        decode(tag, data) {
            const { Err: E } = DER;
            let pos = 0;
            if (tag < 0 || tag > 256)
                throw new E('tlv.encode: wrong tag');
            if (data.length < 2 || data[pos++] !== tag)
                throw new E('tlv.decode: wrong tlv');
            const first = data[pos++];
            const isLong = !!(first & 128); // First bit of first length byte is flag for short/long form
            let length = 0;
            if (!isLong)
                length = first;
            else {
                // Long form: [longFlag(1bit), lengthLength(7bit), length (BE)]
                const lenLen = first & 127;
                if (!lenLen)
                    throw new E('tlv.decode(long): indefinite length not supported');
                if (lenLen > 4)
                    throw new E('tlv.decode(long): byte length is too big'); // this will overflow u32 in js
                const lengthBytes = data.subarray(pos, pos + lenLen);
                if (lengthBytes.length !== lenLen)
                    throw new E('tlv.decode: length bytes not complete');
                if (lengthBytes[0] === 0)
                    throw new E('tlv.decode(long): zero leftmost byte');
                for (const b of lengthBytes)
                    length = (length << 8) | b;
                pos += lenLen;
                if (length < 128)
                    throw new E('tlv.decode(long): not minimal encoding');
            }
            const v = data.subarray(pos, pos + length);
            if (v.length !== length)
                throw new E('tlv.decode: wrong value length');
            return { v, l: data.subarray(pos + length) };
        },
    },
    // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
    // since we always use positive integers here. It must always be empty:
    // - add zero byte if exists
    // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
    _int: {
        encode(num) {
            const { Err: E } = DER;
            if (num < _0n)
                throw new E('integer: negative integers are not allowed');
            let hex = numberToHexUnpadded(num);
            // Pad with zero byte if negative flag is present
            if (Number.parseInt(hex[0], 16) & 0b1000)
                hex = '00' + hex;
            if (hex.length & 1)
                throw new E('unexpected DER parsing assertion: unpadded hex');
            return hex;
        },
        decode(data) {
            const { Err: E } = DER;
            if (data[0] & 128)
                throw new E('invalid signature integer: negative');
            if (data[0] === 0x00 && !(data[1] & 128))
                throw new E('invalid signature integer: unnecessary leading zero');
            return bytesToNumberBE(data);
        },
    },
    toSig(hex) {
        // parse DER signature
        const { Err: E, _int: int, _tlv: tlv } = DER;
        const data = ensureBytes('signature', hex);
        const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);
        if (seqLeftBytes.length)
            throw new E('invalid signature: left bytes after parsing');
        const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);
        const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);
        if (sLeftBytes.length)
            throw new E('invalid signature: left bytes after parsing');
        return { r: int.decode(rBytes), s: int.decode(sBytes) };
    },
    hexFromSig(sig) {
        const { _tlv: tlv, _int: int } = DER;
        const rs = tlv.encode(0x02, int.encode(sig.r));
        const ss = tlv.encode(0x02, int.encode(sig.s));
        const seq = rs + ss;
        return tlv.encode(0x30, seq);
    },
};
// Be friendly to bad ECMAScript parsers by not using bigint literals
// prettier-ignore
const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4);
export function _normFnElement(Fn, key) {
    const { BYTES: expected } = Fn;
    let num;
    if (typeof key === 'bigint') {
        num = key;
    }
    else {
        let bytes = ensureBytes('private key', key);
        try {
            num = Fn.fromBytes(bytes);
        }
        catch (error) {
            throw new Error(`invalid private key: expected ui8a of size ${expected}, got ${typeof key}`);
        }
    }
    if (!Fn.isValidNot0(num))
        throw new Error('invalid private key: out of range [1..N-1]');
    return num;
}
/**
 * Creates weierstrass Point constructor, based on specified curve options.
 *
 * @example
```js
const opts = {
  p: BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff'),
  n: BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551'),
  h: BigInt(1),
  a: BigInt('0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc'),
  b: BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b'),
  Gx: BigInt('0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296'),
  Gy: BigInt('0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5'),
};
const p256_Point = weierstrass(opts);
```
 */
export function weierstrassN(params, extraOpts = {}) {
    const validated = _createCurveFields('weierstrass', params, extraOpts);
    const { Fp, Fn } = validated;
    let CURVE = validated.CURVE;
    const { h: cofactor, n: CURVE_ORDER } = CURVE;
    _validateObject(extraOpts, {}, {
        allowInfinityPoint: 'boolean',
        clearCofactor: 'function',
        isTorsionFree: 'function',
        fromBytes: 'function',
        toBytes: 'function',
        endo: 'object',
        wrapPrivateKey: 'boolean',
    });
    const { endo } = extraOpts;
    if (endo) {
        // validateObject(endo, { beta: 'bigint', splitScalar: 'function' });
        if (!Fp.is0(CURVE.a) || typeof endo.beta !== 'bigint' || !Array.isArray(endo.basises)) {
            throw new Error('invalid endo: expected "beta": bigint and "basises": array');
        }
    }
    const lengths = getWLengths(Fp, Fn);
    function assertCompressionIsSupported() {
        if (!Fp.isOdd)
            throw new Error('compression is not supported: Field does not have .isOdd()');
    }
    // Implements IEEE P1363 point encoding
    function pointToBytes(_c, point, isCompressed) {
        const { x, y } = point.toAffine();
        const bx = Fp.toBytes(x);
        abool(isCompressed, 'isCompressed');
        if (isCompressed) {
            assertCompressionIsSupported();
            const hasEvenY = !Fp.isOdd(y);
            return concatBytes(pprefix(hasEvenY), bx);
        }
        else {
            return concatBytes(Uint8Array.of(0x04), bx, Fp.toBytes(y));
        }
    }
    function pointFromBytes(bytes) {
        abytes(bytes, undefined, 'Point');
        const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths; // e.g. for 32-byte: 33, 65
        const length = bytes.length;
        const head = bytes[0];
        const tail = bytes.subarray(1);
        // No actual validation is done here: use .assertValidity()
        if (length === comp && (head === 0x02 || head === 0x03)) {
            const x = Fp.fromBytes(tail);
            if (!Fp.isValid(x))
                throw new Error('bad point: is not on curve, wrong x');
            const y2 = weierstrassEquation(x); // y² = x³ + ax + b
            let y;
            try {
                y = Fp.sqrt(y2); // y = y² ^ (p+1)/4
            }
            catch (sqrtError) {
                const err = sqrtError instanceof Error ? ': ' + sqrtError.message : '';
                throw new Error('bad point: is not on curve, sqrt error' + err);
            }
            assertCompressionIsSupported();
            const isYOdd = Fp.isOdd(y); // (y & _1n) === _1n;
            const isHeadOdd = (head & 1) === 1; // ECDSA-specific
            if (isHeadOdd !== isYOdd)
                y = Fp.neg(y);
            return { x, y };
        }
        else if (length === uncomp && head === 0x04) {
            // TODO: more checks
            const L = Fp.BYTES;
            const x = Fp.fromBytes(tail.subarray(0, L));
            const y = Fp.fromBytes(tail.subarray(L, L * 2));
            if (!isValidXY(x, y))
                throw new Error('bad point: is not on curve');
            return { x, y };
        }
        else {
            throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);
        }
    }
    const encodePoint = extraOpts.toBytes || pointToBytes;
    const decodePoint = extraOpts.fromBytes || pointFromBytes;
    function weierstrassEquation(x) {
        const x2 = Fp.sqr(x); // x * x
        const x3 = Fp.mul(x2, x); // x² * x
        return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b); // x³ + a * x + b
    }
    // TODO: move top-level
    /** Checks whether equation holds for given x, y: y² == x³ + ax + b */
    function isValidXY(x, y) {
        const left = Fp.sqr(y); // y²
        const right = weierstrassEquation(x); // x³ + ax + b
        return Fp.eql(left, right);
    }
    // Validate whether the passed curve params are valid.
    // Test 1: equation y² = x³ + ax + b should work for generator point.
    if (!isValidXY(CURVE.Gx, CURVE.Gy))
        throw new Error('bad curve params: generator point');
    // Test 2: discriminant Δ part should be non-zero: 4a³ + 27b² != 0.
    // Guarantees curve is genus-1, smooth (non-singular).
    const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n), _4n);
    const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));
    if (Fp.is0(Fp.add(_4a3, _27b2)))
        throw new Error('bad curve params: a or b');
    /** Asserts coordinate is valid: 0 <= n < Fp.ORDER. */
    function acoord(title, n, banZero = false) {
        if (!Fp.isValid(n) || (banZero && Fp.is0(n)))
            throw new Error(`bad point coordinate ${title}`);
        return n;
    }
    function aprjpoint(other) {
        if (!(other instanceof Point))
            throw new Error('ProjectivePoint expected');
    }
    function splitEndoScalarN(k) {
        if (!endo || !endo.basises)
            throw new Error('no endo');
        return _splitEndoScalar(k, endo.basises, Fn.ORDER);
    }
    // Memoized toAffine / validity check. They are heavy. Points are immutable.
    // Converts Projective point to affine (x, y) coordinates.
    // Can accept precomputed Z^-1 - for example, from invertBatch.
    // (X, Y, Z) ∋ (x=X/Z, y=Y/Z)
    const toAffineMemo = memoized((p, iz) => {
        const { X, Y, Z } = p;
        // Fast-path for normalized points
        if (Fp.eql(Z, Fp.ONE))
            return { x: X, y: Y };
        const is0 = p.is0();
        // If invZ was 0, we return zero point. However we still want to execute
        // all operations, so we replace invZ with a random number, 1.
        if (iz == null)
            iz = is0 ? Fp.ONE : Fp.inv(Z);
        const x = Fp.mul(X, iz);
        const y = Fp.mul(Y, iz);
        const zz = Fp.mul(Z, iz);
        if (is0)
            return { x: Fp.ZERO, y: Fp.ZERO };
        if (!Fp.eql(zz, Fp.ONE))
            throw new Error('invZ was invalid');
        return { x, y };
    });
    // NOTE: on exception this will crash 'cached' and no value will be set.
    // Otherwise true will be return
    const assertValidMemo = memoized((p) => {
        if (p.is0()) {
            // (0, 1, 0) aka ZERO is invalid in most contexts.
            // In BLS, ZERO can be serialized, so we allow it.
            // (0, 0, 0) is invalid representation of ZERO.
            if (extraOpts.allowInfinityPoint && !Fp.is0(p.Y))
                return;
            throw new Error('bad point: ZERO');
        }
        // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`
        const { x, y } = p.toAffine();
        if (!Fp.isValid(x) || !Fp.isValid(y))
            throw new Error('bad point: x or y not field elements');
        if (!isValidXY(x, y))
            throw new Error('bad point: equation left != right');
        if (!p.isTorsionFree())
            throw new Error('bad point: not in prime-order subgroup');
        return true;
    });
    function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) {
        k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);
        k1p = negateCt(k1neg, k1p);
        k2p = negateCt(k2neg, k2p);
        return k1p.add(k2p);
    }
    /**
     * Projective Point works in 3d / projective (homogeneous) coordinates:(X, Y, Z) ∋ (x=X/Z, y=Y/Z).
     * Default Point works in 2d / affine coordinates: (x, y).
     * We're doing calculations in projective, because its operations don't require costly inversion.
     */
    class Point {
        /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
        constructor(X, Y, Z) {
            this.X = acoord('x', X);
            this.Y = acoord('y', Y, true);
            this.Z = acoord('z', Z);
            Object.freeze(this);
        }
        static CURVE() {
            return CURVE;
        }
        /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
        static fromAffine(p) {
            const { x, y } = p || {};
            if (!p || !Fp.isValid(x) || !Fp.isValid(y))
                throw new Error('invalid affine point');
            if (p instanceof Point)
                throw new Error('projective point not allowed');
            // (0, 0) would've produced (0, 0, 1) - instead, we need (0, 1, 0)
            if (Fp.is0(x) && Fp.is0(y))
                return Point.ZERO;
            return new Point(x, y, Fp.ONE);
        }
        static fromBytes(bytes) {
            const P = Point.fromAffine(decodePoint(abytes(bytes, undefined, 'point')));
            P.assertValidity();
            return P;
        }
        static fromHex(hex) {
            return Point.fromBytes(ensureBytes('pointHex', hex));
        }
        get x() {
            return this.toAffine().x;
        }
        get y() {
            return this.toAffine().y;
        }
        /**
         *
         * @param windowSize
         * @param isLazy true will defer table computation until the first multiplication
         * @returns
         */
        precompute(windowSize = 8, isLazy = true) {
            wnaf.createCache(this, windowSize);
            if (!isLazy)
                this.multiply(_3n); // random number
            return this;
        }
        // TODO: return `this`
        /** A point on curve is valid if it conforms to equation. */
        assertValidity() {
            assertValidMemo(this);
        }
        hasEvenY() {
            const { y } = this.toAffine();
            if (!Fp.isOdd)
                throw new Error("Field doesn't support isOdd");
            return !Fp.isOdd(y);
        }
        /** Compare one point to another. */
        equals(other) {
            aprjpoint(other);
            const { X: X1, Y: Y1, Z: Z1 } = this;
            const { X: X2, Y: Y2, Z: Z2 } = other;
            const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
            const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
            return U1 && U2;
        }
        /** Flips point to one corresponding to (x, -y) in Affine coordinates. */
        negate() {
            return new Point(this.X, Fp.neg(this.Y), this.Z);
        }
        // Renes-Costello-Batina exception-free doubling formula.
        // There is 30% faster Jacobian formula, but it is not complete.
        // https://eprint.iacr.org/2015/1060, algorithm 3
        // Cost: 8M + 3S + 3*a + 2*b3 + 15add.
        double() {
            const { a, b } = CURVE;
            const b3 = Fp.mul(b, _3n);
            const { X: X1, Y: Y1, Z: Z1 } = this;
            let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore
            let t0 = Fp.mul(X1, X1); // step 1
            let t1 = Fp.mul(Y1, Y1);
            let t2 = Fp.mul(Z1, Z1);
            let t3 = Fp.mul(X1, Y1);
            t3 = Fp.add(t3, t3); // step 5
            Z3 = Fp.mul(X1, Z1);
            Z3 = Fp.add(Z3, Z3);
            X3 = Fp.mul(a, Z3);
            Y3 = Fp.mul(b3, t2);
            Y3 = Fp.add(X3, Y3); // step 10
            X3 = Fp.sub(t1, Y3);
            Y3 = Fp.add(t1, Y3);
            Y3 = Fp.mul(X3, Y3);
            X3 = Fp.mul(t3, X3);
            Z3 = Fp.mul(b3, Z3); // step 15
            t2 = Fp.mul(a, t2);
            t3 = Fp.sub(t0, t2);
            t3 = Fp.mul(a, t3);
            t3 = Fp.add(t3, Z3);
            Z3 = Fp.add(t0, t0); // step 20
            t0 = Fp.add(Z3, t0);
            t0 = Fp.add(t0, t2);
            t0 = Fp.mul(t0, t3);
            Y3 = Fp.add(Y3, t0);
            t2 = Fp.mul(Y1, Z1); // step 25
            t2 = Fp.add(t2, t2);
            t0 = Fp.mul(t2, t3);
            X3 = Fp.sub(X3, t0);
            Z3 = Fp.mul(t2, t1);
            Z3 = Fp.add(Z3, Z3); // step 30
            Z3 = Fp.add(Z3, Z3);
            return new Point(X3, Y3, Z3);
        }
        // Renes-Costello-Batina exception-free addition formula.
        // There is 30% faster Jacobian formula, but it is not complete.
        // https://eprint.iacr.org/2015/1060, algorithm 1
        // Cost: 12M + 0S + 3*a + 3*b3 + 23add.
        add(other) {
            aprjpoint(other);
            const { X: X1, Y: Y1, Z: Z1 } = this;
            const { X: X2, Y: Y2, Z: Z2 } = other;
            let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore
            const a = CURVE.a;
            const b3 = Fp.mul(CURVE.b, _3n);
            let t0 = Fp.mul(X1, X2); // step 1
            let t1 = Fp.mul(Y1, Y2);
            let t2 = Fp.mul(Z1, Z2);
            let t3 = Fp.add(X1, Y1);
            let t4 = Fp.add(X2, Y2); // step 5
            t3 = Fp.mul(t3, t4);
            t4 = Fp.add(t0, t1);
            t3 = Fp.sub(t3, t4);
            t4 = Fp.add(X1, Z1);
            let t5 = Fp.add(X2, Z2); // step 10
            t4 = Fp.mul(t4, t5);
            t5 = Fp.add(t0, t2);
            t4 = Fp.sub(t4, t5);
            t5 = Fp.add(Y1, Z1);
            X3 = Fp.add(Y2, Z2); // step 15
            t5 = Fp.mul(t5, X3);
            X3 = Fp.add(t1, t2);
            t5 = Fp.sub(t5, X3);
            Z3 = Fp.mul(a, t4);
            X3 = Fp.mul(b3, t2); // step 20
            Z3 = Fp.add(X3, Z3);
            X3 = Fp.sub(t1, Z3);
            Z3 = Fp.add(t1, Z3);
            Y3 = Fp.mul(X3, Z3);
            t1 = Fp.add(t0, t0); // step 25
            t1 = Fp.add(t1, t0);
            t2 = Fp.mul(a, t2);
            t4 = Fp.mul(b3, t4);
            t1 = Fp.add(t1, t2);
            t2 = Fp.sub(t0, t2); // step 30
            t2 = Fp.mul(a, t2);
            t4 = Fp.add(t4, t2);
            t0 = Fp.mul(t1, t4);
            Y3 = Fp.add(Y3, t0);
            t0 = Fp.mul(t5, t4); // step 35
            X3 = Fp.mul(t3, X3);
            X3 = Fp.sub(X3, t0);
            t0 = Fp.mul(t3, t1);
            Z3 = Fp.mul(t5, Z3);
            Z3 = Fp.add(Z3, t0); // step 40
            return new Point(X3, Y3, Z3);
        }
        subtract(other) {
            return this.add(other.negate());
        }
        is0() {
            return this.equals(Point.ZERO);
        }
        /**
         * Constant time multiplication.
         * Uses wNAF method. Windowed method may be 10% faster,
         * but takes 2x longer to generate and consumes 2x memory.
         * Uses precomputes when available.
         * Uses endomorphism for Koblitz curves.
         * @param scalar by which the point would be multiplied
         * @returns New point
         */
        multiply(scalar) {
            const { endo } = extraOpts;
            if (!Fn.isValidNot0(scalar))
                throw new Error('invalid scalar: out of range'); // 0 is invalid
            let point, fake; // Fake point is used to const-time mult
            const mul = (n) => wnaf.cached(this, n, (p) => normalizeZ(Point, p));
            /** See docs for {@link EndomorphismOpts} */
            if (endo) {
                const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);
                const { p: k1p, f: k1f } = mul(k1);
                const { p: k2p, f: k2f } = mul(k2);
                fake = k1f.add(k2f);
                point = finishEndo(endo.beta, k1p, k2p, k1neg, k2neg);
            }
            else {
                const { p, f } = mul(scalar);
                point = p;
                fake = f;
            }
            // Normalize `z` for both points, but return only real one
            return normalizeZ(Point, [point, fake])[0];
        }
        /**
         * Non-constant-time multiplication. Uses double-and-add algorithm.
         * It's faster, but should only be used when you don't care about
         * an exposed secret key e.g. sig verification, which works over *public* keys.
         */
        multiplyUnsafe(sc) {
            const { endo } = extraOpts;
            const p = this;
            if (!Fn.isValid(sc))
                throw new Error('invalid scalar: out of range'); // 0 is valid
            if (sc === _0n || p.is0())
                return Point.ZERO;
            if (sc === _1n)
                return p; // fast-path
            if (wnaf.hasCache(this))
                return this.multiply(sc);
            if (endo) {
                const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);
                const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2); // 30% faster vs wnaf.unsafe
                return finishEndo(endo.beta, p1, p2, k1neg, k2neg);
            }
            else {
                return wnaf.unsafe(p, sc);
            }
        }
        multiplyAndAddUnsafe(Q, a, b) {
            const sum = this.multiplyUnsafe(a).add(Q.multiplyUnsafe(b));
            return sum.is0() ? undefined : sum;
        }
        /**
         * Converts Projective point to affine (x, y) coordinates.
         * @param invertedZ Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch
         */
        toAffine(invertedZ) {
            return toAffineMemo(this, invertedZ);
        }
        /**
         * Checks whether Point is free of torsion elements (is in prime subgroup).
         * Always torsion-free for cofactor=1 curves.
         */
        isTorsionFree() {
            const { isTorsionFree } = extraOpts;
            if (cofactor === _1n)
                return true;
            if (isTorsionFree)
                return isTorsionFree(Point, this);
            return wnaf.unsafe(this, CURVE_ORDER).is0();
        }
        clearCofactor() {
            const { clearCofactor } = extraOpts;
            if (cofactor === _1n)
                return this; // Fast-path
            if (clearCofactor)
                return clearCofactor(Point, this);
            return this.multiplyUnsafe(cofactor);
        }
        isSmallOrder() {
            // can we use this.clearCofactor()?
            return this.multiplyUnsafe(cofactor).is0();
        }
        toBytes(isCompressed = true) {
            abool(isCompressed, 'isCompressed');
            this.assertValidity();
            return encodePoint(Point, this, isCompressed);
        }
        toHex(isCompressed = true) {
            return bytesToHex(this.toBytes(isCompressed));
        }
        toString() {
            return `<Point ${this.is0() ? 'ZERO' : this.toHex()}>`;
        }
        // TODO: remove
        get px() {
            return this.X;
        }
        get py() {
            return this.X;
        }
        get pz() {
            return this.Z;
        }
        toRawBytes(isCompressed = true) {
            return this.toBytes(isCompressed);
        }
        _setWindowSize(windowSize) {
            this.precompute(windowSize);
        }
        static normalizeZ(points) {
            return normalizeZ(Point, points);
        }
        static msm(points, scalars) {
            return pippenger(Point, Fn, points, scalars);
        }
        static fromPrivateKey(privateKey) {
            return Point.BASE.multiply(_normFnElement(Fn, privateKey));
        }
    }
    // base / generator point
    Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
    // zero / infinity / identity point
    Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); // 0, 1, 0
    // math field
    Point.Fp = Fp;
    // scalar field
    Point.Fn = Fn;
    const bits = Fn.BITS;
    const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);
    Point.BASE.precompute(8); // Enable precomputes. Slows down first publicKey computation by 20ms.
    return Point;
}
// Points start with byte 0x02 when y is even; otherwise 0x03
function pprefix(hasEvenY) {
    return Uint8Array.of(hasEvenY ? 0x02 : 0x03);
}
/**
 * Implementation of the Shallue and van de Woestijne method for any weierstrass curve.
 * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular.
 * b = True and y = sqrt(u / v) if (u / v) is square in F, and
 * b = False and y = sqrt(Z * (u / v)) otherwise.
 * @param Fp
 * @param Z
 * @returns
 */
export function SWUFpSqrtRatio(Fp, Z) {
    // Generic implementation
    const q = Fp.ORDER;
    let l = _0n;
    for (let o = q - _1n; o % _2n === _0n; o /= _2n)
        l += _1n;
    const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1.
    // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<.
    // 2n ** c1 == 2n << (c1-1)
    const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n);
    const _2n_pow_c1 = _2n_pow_c1_1 * _2n;
    const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1)  # Integer arithmetic
    const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2            # Integer arithmetic
    const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1                # Integer arithmetic
    const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1)                  # Integer arithmetic
    const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2
    const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2)
    let sqrtRatio = (u, v) => {
        let tv1 = c6; // 1. tv1 = c6
        let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4
        let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2
        tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v
        let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3
        tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3
        tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2
        tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v
        tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u
        let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2
        tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5
        let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1
        tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7
        tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1
        tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR)
        tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR)
        // 17. for i in (c1, c1 - 1, ..., 2):
        for (let i = c1; i > _1n; i--) {
            let tv5 = i - _2n; // 18.    tv5 = i - 2
            tv5 = _2n << (tv5 - _1n); // 19.    tv5 = 2^tv5
            let tvv5 = Fp.pow(tv4, tv5); // 20.    tv5 = tv4^tv5
            const e1 = Fp.eql(tvv5, Fp.ONE); // 21.    e1 = tv5 == 1
            tv2 = Fp.mul(tv3, tv1); // 22.    tv2 = tv3 * tv1
            tv1 = Fp.mul(tv1, tv1); // 23.    tv1 = tv1 * tv1
            tvv5 = Fp.mul(tv4, tv1); // 24.    tv5 = tv4 * tv1
            tv3 = Fp.cmov(tv2, tv3, e1); // 25.    tv3 = CMOV(tv2, tv3, e1)
            tv4 = Fp.cmov(tvv5, tv4, e1); // 26.    tv4 = CMOV(tv5, tv4, e1)
        }
        return { isValid: isQR, value: tv3 };
    };
    if (Fp.ORDER % _4n === _3n) {
        // sqrt_ratio_3mod4(u, v)
        const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4     # Integer arithmetic
        const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z)
        sqrtRatio = (u, v) => {
            let tv1 = Fp.sqr(v); // 1. tv1 = v^2
            const tv2 = Fp.mul(u, v); // 2. tv2 = u * v
            tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2
            let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1
            y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2
            const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2
            const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v
            const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u
            let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR)
            return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2
        };
    }
    // No curves uses that
    // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8
    return sqrtRatio;
}
/**
 * Simplified Shallue-van de Woestijne-Ulas Method
 * https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2
 */
export function mapToCurveSimpleSWU(Fp, opts) {
    validateField(Fp);
    const { A, B, Z } = opts;
    if (!Fp.isValid(A) || !Fp.isValid(B) || !Fp.isValid(Z))
        throw new Error('mapToCurveSimpleSWU: invalid opts');
    const sqrtRatio = SWUFpSqrtRatio(Fp, Z);
    if (!Fp.isOdd)
        throw new Error('Field does not have .isOdd()');
    // Input: u, an element of F.
    // Output: (x, y), a point on E.
    return (u) => {
        // prettier-ignore
        let tv1, tv2, tv3, tv4, tv5, tv6, x, y;
        tv1 = Fp.sqr(u); // 1.  tv1 = u^2
        tv1 = Fp.mul(tv1, Z); // 2.  tv1 = Z * tv1
        tv2 = Fp.sqr(tv1); // 3.  tv2 = tv1^2
        tv2 = Fp.add(tv2, tv1); // 4.  tv2 = tv2 + tv1
        tv3 = Fp.add(tv2, Fp.ONE); // 5.  tv3 = tv2 + 1
        tv3 = Fp.mul(tv3, B); // 6.  tv3 = B * tv3
        tv4 = Fp.cmov(Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7.  tv4 = CMOV(Z, -tv2, tv2 != 0)
        tv4 = Fp.mul(tv4, A); // 8.  tv4 = A * tv4
        tv2 = Fp.sqr(tv3); // 9.  tv2 = tv3^2
        tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2
        tv5 = Fp.mul(tv6, A); // 11. tv5 = A * tv6
        tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5
        tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3
        tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4
        tv5 = Fp.mul(tv6, B); // 15. tv5 = B * tv6
        tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5
        x = Fp.mul(tv1, tv3); // 17.   x = tv1 * tv3
        const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6)
        y = Fp.mul(tv1, u); // 19.   y = tv1 * u  -> Z * u^3 * y1
        y = Fp.mul(y, value); // 20.   y = y * y1
        x = Fp.cmov(x, tv3, isValid); // 21.   x = CMOV(x, tv3, is_gx1_square)
        y = Fp.cmov(y, value, isValid); // 22.   y = CMOV(y, y1, is_gx1_square)
        const e1 = Fp.isOdd(u) === Fp.isOdd(y); // 23.  e1 = sgn0(u) == sgn0(y)
        y = Fp.cmov(Fp.neg(y), y, e1); // 24.   y = CMOV(-y, y, e1)
        const tv4_inv = FpInvertBatch(Fp, [tv4], true)[0];
        x = Fp.mul(x, tv4_inv); // 25.   x = x / tv4
        return { x, y };
    };
}
function getWLengths(Fp, Fn) {
    return {
        secretKey: Fn.BYTES,
        publicKey: 1 + Fp.BYTES,
        publicKeyUncompressed: 1 + 2 * Fp.BYTES,
        publicKeyHasPrefix: true,
        signature: 2 * Fn.BYTES,
    };
}
/**
 * Sometimes users only need getPublicKey, getSharedSecret, and secret key handling.
 * This helper ensures no signature functionality is present. Less code, smaller bundle size.
 */
export function ecdh(Point, ecdhOpts = {}) {
    const { Fn } = Point;
    const randomBytes_ = ecdhOpts.randomBytes || randomBytesWeb;
    const lengths = Object.assign(getWLengths(Point.Fp, Fn), { seed: getMinHashLength(Fn.ORDER) });
    function isValidSecretKey(secretKey) {
        try {
            return !!_normFnElement(Fn, secretKey);
        }
        catch (error) {
            return false;
        }
    }
    function isValidPublicKey(publicKey, isCompressed) {
        const { publicKey: comp, publicKeyUncompressed } = lengths;
        try {
            const l = publicKey.length;
            if (isCompressed === true && l !== comp)
                return false;
            if (isCompressed === false && l !== publicKeyUncompressed)
                return false;
            return !!Point.fromBytes(publicKey);
        }
        catch (error) {
            return false;
        }
    }
    /**
     * Produces cryptographically secure secret key from random of size
     * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.
     */
    function randomSecretKey(seed = randomBytes_(lengths.seed)) {
        return mapHashToField(abytes(seed, lengths.seed, 'seed'), Fn.ORDER);
    }
    /**
     * Computes public key for a secret key. Checks for validity of the secret key.
     * @param isCompressed whether to return compact (default), or full key
     * @returns Public key, full when isCompressed=false; short when isCompressed=true
     */
    function getPublicKey(secretKey, isCompressed = true) {
        return Point.BASE.multiply(_normFnElement(Fn, secretKey)).toBytes(isCompressed);
    }
    function keygen(seed) {
        const secretKey = randomSecretKey(seed);
        return { secretKey, publicKey: getPublicKey(secretKey) };
    }
    /**
     * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.
     */
    function isProbPub(item) {
        if (typeof item === 'bigint')
            return false;
        if (item instanceof Point)
            return true;
        const { secretKey, publicKey, publicKeyUncompressed } = lengths;
        if (Fn.allowedLengths || secretKey === publicKey)
            return undefined;
        const l = ensureBytes('key', item).length;
        return l === publicKey || l === publicKeyUncompressed;
    }
    /**
     * ECDH (Elliptic Curve Diffie Hellman).
     * Computes shared public key from secret key A and public key B.
     * Checks: 1) secret key validity 2) shared key is on-curve.
     * Does NOT hash the result.
     * @param isCompressed whether to return compact (default), or full key
     * @returns shared public key
     */
    function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {
        if (isProbPub(secretKeyA) === true)
            throw new Error('first arg must be private key');
        if (isProbPub(publicKeyB) === false)
            throw new Error('second arg must be public key');
        const s = _normFnElement(Fn, secretKeyA);
        const b = Point.fromHex(publicKeyB); // checks for being on-curve
        return b.multiply(s).toBytes(isCompressed);
    }
    const utils = {
        isValidSecretKey,
        isValidPublicKey,
        randomSecretKey,
        // TODO: remove
        isValidPrivateKey: isValidSecretKey,
        randomPrivateKey: randomSecretKey,
        normPrivateKeyToScalar: (key) => _normFnElement(Fn, key),
        precompute(windowSize = 8, point = Point.BASE) {
            return point.precompute(windowSize, false);
        },
    };
    return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point, utils, lengths });
}
/**
 * Creates ECDSA signing interface for given elliptic curve `Point` and `hash` function.
 * We need `hash` for 2 features:
 * 1. Message prehash-ing. NOT used if `sign` / `verify` are called with `prehash: false`
 * 2. k generation in `sign`, using HMAC-drbg(hash)
 *
 * ECDSAOpts are only rarely needed.
 *
 * @example
 * ```js
 * const p256_Point = weierstrass(...);
 * const p256_sha256 = ecdsa(p256_Point, sha256);
 * const p256_sha224 = ecdsa(p256_Point, sha224);
 * const p256_sha224_r = ecdsa(p256_Point, sha224, { randomBytes: (length) => { ... } });
 * ```
 */
export function ecdsa(Point, hash, ecdsaOpts = {}) {
    ahash(hash);
    _validateObject(ecdsaOpts, {}, {
        hmac: 'function',
        lowS: 'boolean',
        randomBytes: 'function',
        bits2int: 'function',
        bits2int_modN: 'function',
    });
    const randomBytes = ecdsaOpts.randomBytes || randomBytesWeb;
    const hmac = ecdsaOpts.hmac ||
        ((key, ...msgs) => nobleHmac(hash, key, concatBytes(...msgs)));
    const { Fp, Fn } = Point;
    const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;
    const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);
    const defaultSigOpts = {
        prehash: false,
        lowS: typeof ecdsaOpts.lowS === 'boolean' ? ecdsaOpts.lowS : false,
        format: undefined, //'compact' as ECDSASigFormat,
        extraEntropy: false,
    };
    const defaultSigOpts_format = 'compact';
    function isBiggerThanHalfOrder(number) {
        const HALF = CURVE_ORDER >> _1n;
        return number > HALF;
    }
    function validateRS(title, num) {
        if (!Fn.isValidNot0(num))
            throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);
        return num;
    }
    function validateSigLength(bytes, format) {
        validateSigFormat(format);
        const size = lengths.signature;
        const sizer = format === 'compact' ? size : format === 'recovered' ? size + 1 : undefined;
        return abytes(bytes, sizer, `${format} signature`);
    }
    /**
     * ECDSA signature with its (r, s) properties. Supports compact, recovered & DER representations.
     */
    class Signature {
        constructor(r, s, recovery) {
            this.r = validateRS('r', r); // r in [1..N-1];
            this.s = validateRS('s', s); // s in [1..N-1];
            if (recovery != null)
                this.recovery = recovery;
            Object.freeze(this);
        }
        static fromBytes(bytes, format = defaultSigOpts_format) {
            validateSigLength(bytes, format);
            let recid;
            if (format === 'der') {
                const { r, s } = DER.toSig(abytes(bytes));
                return new Signature(r, s);
            }
            if (format === 'recovered') {
                recid = bytes[0];
                format = 'compact';
                bytes = bytes.subarray(1);
            }
            const L = Fn.BYTES;
            const r = bytes.subarray(0, L);
            const s = bytes.subarray(L, L * 2);
            return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);
        }
        static fromHex(hex, format) {
            return this.fromBytes(hexToBytes(hex), format);
        }
        addRecoveryBit(recovery) {
            return new Signature(this.r, this.s, recovery);
        }
        recoverPublicKey(messageHash) {
            const FIELD_ORDER = Fp.ORDER;
            const { r, s, recovery: rec } = this;
            if (rec == null || ![0, 1, 2, 3].includes(rec))
                throw new Error('recovery id invalid');
            // ECDSA recovery is hard for cofactor > 1 curves.
            // In sign, `r = q.x mod n`, and here we recover q.x from r.
            // While recovering q.x >= n, we need to add r+n for cofactor=1 curves.
            // However, for cofactor>1, r+n may not get q.x:
            // r+n*i would need to be done instead where i is unknown.
            // To easily get i, we either need to:
            // a. increase amount of valid recid values (4, 5...); OR
            // b. prohibit non-prime-order signatures (recid > 1).
            const hasCofactor = CURVE_ORDER * _2n < FIELD_ORDER;
            if (hasCofactor && rec > 1)
                throw new Error('recovery id is ambiguous for h>1 curve');
            const radj = rec === 2 || rec === 3 ? r + CURVE_ORDER : r;
            if (!Fp.isValid(radj))
                throw new Error('recovery id 2 or 3 invalid');
            const x = Fp.toBytes(radj);
            const R = Point.fromBytes(concatBytes(pprefix((rec & 1) === 0), x));
            const ir = Fn.inv(radj); // r^-1
            const h = bits2int_modN(ensureBytes('msgHash', messageHash)); // Truncate hash
            const u1 = Fn.create(-h * ir); // -hr^-1
            const u2 = Fn.create(s * ir); // sr^-1
            // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1). unsafe is fine: there is no private data.
            const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));
            if (Q.is0())
                throw new Error('point at infinify');
            Q.assertValidity();
            return Q;
        }
        // Signatures should be low-s, to prevent malleability.
        hasHighS() {
            return isBiggerThanHalfOrder(this.s);
        }
        toBytes(format = defaultSigOpts_format) {
            validateSigFormat(format);
            if (format === 'der')
                return hexToBytes(DER.hexFromSig(this));
            const r = Fn.toBytes(this.r);
            const s = Fn.toBytes(this.s);
            if (format === 'recovered') {
                if (this.recovery == null)
                    throw new Error('recovery bit must be present');
                return concatBytes(Uint8Array.of(this.recovery), r, s);
            }
            return concatBytes(r, s);
        }
        toHex(format) {
            return bytesToHex(this.toBytes(format));
        }
        // TODO: remove
        assertValidity() { }
        static fromCompact(hex) {
            return Signature.fromBytes(ensureBytes('sig', hex), 'compact');
        }
        static fromDER(hex) {
            return Signature.fromBytes(ensureBytes('sig', hex), 'der');
        }
        normalizeS() {
            return this.hasHighS() ? new Signature(this.r, Fn.neg(this.s), this.recovery) : this;
        }
        toDERRawBytes() {
            return this.toBytes('der');
        }
        toDERHex() {
            return bytesToHex(this.toBytes('der'));
        }
        toCompactRawBytes() {
            return this.toBytes('compact');
        }
        toCompactHex() {
            return bytesToHex(this.toBytes('compact'));
        }
    }
    // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.
    // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.
    // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.
    // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors
    const bits2int = ecdsaOpts.bits2int ||
        function bits2int_def(bytes) {
            // Our custom check "just in case", for protection against DoS
            if (bytes.length > 8192)
                throw new Error('input is too large');
            // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)
            // for some cases, since bytes.length * 8 is not actual bitLength.
            const num = bytesToNumberBE(bytes); // check for == u8 done here
            const delta = bytes.length * 8 - fnBits; // truncate to nBitLength leftmost bits
            return delta > 0 ? num >> BigInt(delta) : num;
        };
    const bits2int_modN = ecdsaOpts.bits2int_modN ||
        function bits2int_modN_def(bytes) {
            return Fn.create(bits2int(bytes)); // can't use bytesToNumberBE here
        };
    // Pads output with zero as per spec
    const ORDER_MASK = bitMask(fnBits);
    /** Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. */
    function int2octets(num) {
        // IMPORTANT: the check ensures working for case `Fn.BYTES != Fn.BITS * 8`
        aInRange('num < 2^' + fnBits, num, _0n, ORDER_MASK);
        return Fn.toBytes(num);
    }
    function validateMsgAndHash(message, prehash) {
        abytes(message, undefined, 'message');
        return prehash ? abytes(hash(message), undefined, 'prehashed message') : message;
    }
    /**
     * Steps A, D of RFC6979 3.2.
     * Creates RFC6979 seed; converts msg/privKey to numbers.
     * Used only in sign, not in verify.
     *
     * Warning: we cannot assume here that message has same amount of bytes as curve order,
     * this will be invalid at least for P521. Also it can be bigger for P224 + SHA256.
     */
    function prepSig(message, privateKey, opts) {
        if (['recovered', 'canonical'].some((k) => k in opts))
            throw new Error('sign() legacy options not supported');
        const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);
        message = validateMsgAndHash(message, prehash); // RFC6979 3.2 A: h1 = H(m)
        // We can't later call bits2octets, since nested bits2int is broken for curves
        // with fnBits % 8 !== 0. Because of that, we unwrap it here as int2octets call.
        // const bits2octets = (bits) => int2octets(bits2int_modN(bits))
        const h1int = bits2int_modN(message);
        const d = _normFnElement(Fn, privateKey); // validate secret key, convert to bigint
        const seedArgs = [int2octets(d), int2octets(h1int)];
        // extraEntropy. RFC6979 3.6: additional k' (optional).
        if (extraEntropy != null && extraEntropy !== false) {
            // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')
            // gen random bytes OR pass as-is
            const e = extraEntropy === true ? randomBytes(lengths.secretKey) : extraEntropy;
            seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes
        }
        const seed = concatBytes(...seedArgs); // Step D of RFC6979 3.2
        const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash!
        // Converts signature params into point w r/s, checks result for validity.
        // To transform k => Signature:
        // q = k⋅G
        // r = q.x mod n
        // s = k^-1(m + rd) mod n
        // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to
        // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:
        // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT
        function k2sig(kBytes) {
            // RFC 6979 Section 3.2, step 3: k = bits2int(T)
            // Important: all mod() calls here must be done over N
            const k = bits2int(kBytes); // mod n, not mod p
            if (!Fn.isValidNot0(k))
                return; // Valid scalars (including k) must be in 1..N-1
            const ik = Fn.inv(k); // k^-1 mod n
            const q = Point.BASE.multiply(k).toAffine(); // q = k⋅G
            const r = Fn.create(q.x); // r = q.x mod n
            if (r === _0n)
                return;
            const s = Fn.create(ik * Fn.create(m + r * d)); // Not using blinding here, see comment above
            if (s === _0n)
                return;
            let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n)
            let normS = s;
            if (lowS && isBiggerThanHalfOrder(s)) {
                normS = Fn.neg(s); // if lowS was passed, ensure s is always
                recovery ^= 1; // // in the bottom half of N
            }
            return new Signature(r, normS, recovery); // use normS, not s
        }
        return { seed, k2sig };
    }
    /**
     * Signs message hash with a secret key.
     *
     * ```
     * sign(m, d) where
     *   k = rfc6979_hmac_drbg(m, d)
     *   (x, y) = G × k
     *   r = x mod n
     *   s = (m + dr) / k mod n
     * ```
     */
    function sign(message, secretKey, opts = {}) {
        message = ensureBytes('message', message);
        const { seed, k2sig } = prepSig(message, secretKey, opts); // Steps A, D of RFC6979 3.2.
        const drbg = createHmacDrbg(hash.outputLen, Fn.BYTES, hmac);
        const sig = drbg(seed, k2sig); // Steps B, C, D, E, F, G
        return sig;
    }
    function tryParsingSig(sg) {
        // Try to deduce format
        let sig = undefined;
        const isHex = typeof sg === 'string' || isBytes(sg);
        const isObj = !isHex &&
            sg !== null &&
            typeof sg === 'object' &&
            typeof sg.r === 'bigint' &&
            typeof sg.s === 'bigint';
        if (!isHex && !isObj)
            throw new Error('invalid signature, expected Uint8Array, hex string or Signature instance');
        if (isObj) {
            sig = new Signature(sg.r, sg.s);
        }
        else if (isHex) {
            try {
                sig = Signature.fromBytes(ensureBytes('sig', sg), 'der');
            }
            catch (derError) {
                if (!(derError instanceof DER.Err))
                    throw derError;
            }
            if (!sig) {
                try {
                    sig = Signature.fromBytes(ensureBytes('sig', sg), 'compact');
                }
                catch (error) {
                    return false;
                }
            }
        }
        if (!sig)
            return false;
        return sig;
    }
    /**
     * Verifies a signature against message and public key.
     * Rejects lowS signatures by default: see {@link ECDSAVerifyOpts}.
     * Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:
     *
     * ```
     * verify(r, s, h, P) where
     *   u1 = hs^-1 mod n
     *   u2 = rs^-1 mod n
     *   R = u1⋅G + u2⋅P
     *   mod(R.x, n) == r
     * ```
     */
    function verify(signature, message, publicKey, opts = {}) {
        const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);
        publicKey = ensureBytes('publicKey', publicKey);
        message = validateMsgAndHash(ensureBytes('message', message), prehash);
        if ('strict' in opts)
            throw new Error('options.strict was renamed to lowS');
        const sig = format === undefined
            ? tryParsingSig(signature)
            : Signature.fromBytes(ensureBytes('sig', signature), format);
        if (sig === false)
            return false;
        try {
            const P = Point.fromBytes(publicKey);
            if (lowS && sig.hasHighS())
                return false;
            const { r, s } = sig;
            const h = bits2int_modN(message); // mod n, not mod p
            const is = Fn.inv(s); // s^-1 mod n
            const u1 = Fn.create(h * is); // u1 = hs^-1 mod n
            const u2 = Fn.create(r * is); // u2 = rs^-1 mod n
            const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2)); // u1⋅G + u2⋅P
            if (R.is0())
                return false;
            const v = Fn.create(R.x); // v = r.x mod n
            return v === r;
        }
        catch (e) {
            return false;
        }
    }
    function recoverPublicKey(signature, message, opts = {}) {
        const { prehash } = validateSigOpts(opts, defaultSigOpts);
        message = validateMsgAndHash(message, prehash);
        return Signature.fromBytes(signature, 'recovered').recoverPublicKey(message).toBytes();
    }
    return Object.freeze({
        keygen,
        getPublicKey,
        getSharedSecret,
        utils,
        lengths,
        Point,
        sign,
        verify,
        recoverPublicKey,
        Signature,
        hash,
    });
}
/** @deprecated use `weierstrass` in newer releases */
export function weierstrassPoints(c) {
    const { CURVE, curveOpts } = _weierstrass_legacy_opts_to_new(c);
    const Point = weierstrassN(CURVE, curveOpts);
    return _weierstrass_new_output_to_legacy(c, Point);
}
function _weierstrass_legacy_opts_to_new(c) {
    const CURVE = {
        a: c.a,
        b: c.b,
        p: c.Fp.ORDER,
        n: c.n,
        h: c.h,
        Gx: c.Gx,
        Gy: c.Gy,
    };
    const Fp = c.Fp;
    let allowedLengths = c.allowedPrivateKeyLengths
        ? Array.from(new Set(c.allowedPrivateKeyLengths.map((l) => Math.ceil(l / 2))))
        : undefined;
    const Fn = Field(CURVE.n, {
        BITS: c.nBitLength,
        allowedLengths: allowedLengths,
        modFromBytes: c.wrapPrivateKey,
    });
    const curveOpts = {
        Fp,
        Fn,
        allowInfinityPoint: c.allowInfinityPoint,
        endo: c.endo,
        isTorsionFree: c.isTorsionFree,
        clearCofactor: c.clearCofactor,
        fromBytes: c.fromBytes,
        toBytes: c.toBytes,
    };
    return { CURVE, curveOpts };
}
function _ecdsa_legacy_opts_to_new(c) {
    const { CURVE, curveOpts } = _weierstrass_legacy_opts_to_new(c);
    const ecdsaOpts = {
        hmac: c.hmac,
        randomBytes: c.randomBytes,
        lowS: c.lowS,
        bits2int: c.bits2int,
        bits2int_modN: c.bits2int_modN,
    };
    return { CURVE, curveOpts, hash: c.hash, ecdsaOpts };
}
export function _legacyHelperEquat(Fp, a, b) {
    /**
     * y² = x³ + ax + b: Short weierstrass curve formula. Takes x, returns y².
     * @returns y²
     */
    function weierstrassEquation(x) {
        const x2 = Fp.sqr(x); // x * x
        const x3 = Fp.mul(x2, x); // x² * x
        return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x³ + a * x + b
    }
    return weierstrassEquation;
}
function _weierstrass_new_output_to_legacy(c, Point) {
    const { Fp, Fn } = Point;
    function isWithinCurveOrder(num) {
        return inRange(num, _1n, Fn.ORDER);
    }
    const weierstrassEquation = _legacyHelperEquat(Fp, c.a, c.b);
    return Object.assign({}, {
        CURVE: c,
        Point: Point,
        ProjectivePoint: Point,
        normPrivateKeyToScalar: (key) => _normFnElement(Fn, key),
        weierstrassEquation,
        isWithinCurveOrder,
    });
}
function _ecdsa_new_output_to_legacy(c, _ecdsa) {
    const Point = _ecdsa.Point;
    return Object.assign({}, _ecdsa, {
        ProjectivePoint: Point,
        CURVE: Object.assign({}, c, nLength(Point.Fn.ORDER, Point.Fn.BITS)),
    });
}
// _ecdsa_legacy
export function weierstrass(c) {
    const { CURVE, curveOpts, hash, ecdsaOpts } = _ecdsa_legacy_opts_to_new(c);
    const Point = weierstrassN(CURVE, curveOpts);
    const signs = ecdsa(Point, hash, ecdsaOpts);
    return _ecdsa_new_output_to_legacy(c, signs);
}
//# sourceMappingURL=weierstrass.js.map{
  "type": "module",
  "sideEffects": false
}
/**
 * SECG secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).
 *
 * Belongs to Koblitz curves: it has efficiently-computable GLV endomorphism ψ,
 * check out {@link EndomorphismOpts}. Seems to be rigid (not backdoored).
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { sha256 } from '@noble/hashes/sha2.js';
import { randomBytes } from '@noble/hashes/utils.js';
import { createCurve } from "./_shortw_utils.js";
import { createHasher, isogenyMap, } from "./abstract/hash-to-curve.js";
import { Field, mapHashToField, mod, pow2 } from "./abstract/modular.js";
import { _normFnElement, mapToCurveSimpleSWU, } from "./abstract/weierstrass.js";
import { bytesToNumberBE, concatBytes, ensureBytes, inRange, numberToBytesBE, utf8ToBytes, } from "./utils.js";
// Seems like generator was produced from some seed:
// `Point.BASE.multiply(Point.Fn.inv(2n, N)).toAffine().x`
// // gives short x 0x3b78ce563f89a0ed9414f5aa28ad0d96d6795f9c63n
const secp256k1_CURVE = {
    p: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'),
    n: BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'),
    h: BigInt(1),
    a: BigInt(0),
    b: BigInt(7),
    Gx: BigInt('0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'),
    Gy: BigInt('0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8'),
};
const secp256k1_ENDO = {
    beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),
    basises: [
        [BigInt('0x3086d221a7d46bcde86c90e49284eb15'), -BigInt('0xe4437ed6010e88286f547fa90abfe4c3')],
        [BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'), BigInt('0x3086d221a7d46bcde86c90e49284eb15')],
    ],
};
const _0n = /* @__PURE__ */ BigInt(0);
const _1n = /* @__PURE__ */ BigInt(1);
const _2n = /* @__PURE__ */ BigInt(2);
/**
 * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.
 * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]
 */
function sqrtMod(y) {
    const P = secp256k1_CURVE.p;
    // prettier-ignore
    const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
    // prettier-ignore
    const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
    const b2 = (y * y * y) % P; // x^3, 11
    const b3 = (b2 * b2 * y) % P; // x^7
    const b6 = (pow2(b3, _3n, P) * b3) % P;
    const b9 = (pow2(b6, _3n, P) * b3) % P;
    const b11 = (pow2(b9, _2n, P) * b2) % P;
    const b22 = (pow2(b11, _11n, P) * b11) % P;
    const b44 = (pow2(b22, _22n, P) * b22) % P;
    const b88 = (pow2(b44, _44n, P) * b44) % P;
    const b176 = (pow2(b88, _88n, P) * b88) % P;
    const b220 = (pow2(b176, _44n, P) * b44) % P;
    const b223 = (pow2(b220, _3n, P) * b3) % P;
    const t1 = (pow2(b223, _23n, P) * b22) % P;
    const t2 = (pow2(t1, _6n, P) * b2) % P;
    const root = pow2(t2, _2n, P);
    if (!Fpk1.eql(Fpk1.sqr(root), y))
        throw new Error('Cannot find square root');
    return root;
}
const Fpk1 = Field(secp256k1_CURVE.p, { sqrt: sqrtMod });
/**
 * secp256k1 curve, ECDSA and ECDH methods.
 *
 * Field: `2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n`
 *
 * @example
 * ```js
 * import { secp256k1 } from '@noble/curves/secp256k1';
 * const { secretKey, publicKey } = secp256k1.keygen();
 * const msg = new TextEncoder().encode('hello');
 * const sig = secp256k1.sign(msg, secretKey);
 * const isValid = secp256k1.verify(sig, msg, publicKey) === true;
 * ```
 */
export const secp256k1 = createCurve({ ...secp256k1_CURVE, Fp: Fpk1, lowS: true, endo: secp256k1_ENDO }, sha256);
// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.
// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki
/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */
const TAGGED_HASH_PREFIXES = {};
function taggedHash(tag, ...messages) {
    let tagP = TAGGED_HASH_PREFIXES[tag];
    if (tagP === undefined) {
        const tagH = sha256(utf8ToBytes(tag));
        tagP = concatBytes(tagH, tagH);
        TAGGED_HASH_PREFIXES[tag] = tagP;
    }
    return sha256(concatBytes(tagP, ...messages));
}
// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03
const pointToBytes = (point) => point.toBytes(true).slice(1);
const Pointk1 = /* @__PURE__ */ (() => secp256k1.Point)();
const hasEven = (y) => y % _2n === _0n;
// Calculate point, scalar and bytes
function schnorrGetExtPubKey(priv) {
    const { Fn, BASE } = Pointk1;
    const d_ = _normFnElement(Fn, priv);
    const p = BASE.multiply(d_); // P = d'⋅G; 0 < d' < n check is done inside
    const scalar = hasEven(p.y) ? d_ : Fn.neg(d_);
    return { scalar, bytes: pointToBytes(p) };
}
/**
 * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.
 * @returns valid point checked for being on-curve
 */
function lift_x(x) {
    const Fp = Fpk1;
    if (!Fp.isValidNot0(x))
        throw new Error('invalid x: Fail if x ≥ p');
    const xx = Fp.create(x * x);
    const c = Fp.create(xx * x + BigInt(7)); // Let c = x³ + 7 mod p.
    let y = Fp.sqrt(c); // Let y = c^(p+1)/4 mod p. Same as sqrt().
    // Return the unique point P such that x(P) = x and
    // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.
    if (!hasEven(y))
        y = Fp.neg(y);
    const p = Pointk1.fromAffine({ x, y });
    p.assertValidity();
    return p;
}
const num = bytesToNumberBE;
/**
 * Create tagged hash, convert it to bigint, reduce modulo-n.
 */
function challenge(...args) {
    return Pointk1.Fn.create(num(taggedHash('BIP0340/challenge', ...args)));
}
/**
 * Schnorr public key is just `x` coordinate of Point as per BIP340.
 */
function schnorrGetPublicKey(secretKey) {
    return schnorrGetExtPubKey(secretKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G)
}
/**
 * Creates Schnorr signature as per BIP340. Verifies itself before returning anything.
 * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous.
 */
function schnorrSign(message, secretKey, auxRand = randomBytes(32)) {
    const { Fn } = Pointk1;
    const m = ensureBytes('message', message);
    const { bytes: px, scalar: d } = schnorrGetExtPubKey(secretKey); // checks for isWithinCurveOrder
    const a = ensureBytes('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array
    const t = Fn.toBytes(d ^ num(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a)
    const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m)
    // Let k' = int(rand) mod n. Fail if k' = 0. Let R = k'⋅G
    const { bytes: rx, scalar: k } = schnorrGetExtPubKey(rand);
    const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.
    const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n).
    sig.set(rx, 0);
    sig.set(Fn.toBytes(Fn.create(k + e * d)), 32);
    // If Verify(bytes(P), m, sig) (see below) returns failure, abort
    if (!schnorrVerify(sig, m, px))
        throw new Error('sign: Invalid signature produced');
    return sig;
}
/**
 * Verifies Schnorr signature.
 * Will swallow errors & return false except for initial type validation of arguments.
 */
function schnorrVerify(signature, message, publicKey) {
    const { Fn, BASE } = Pointk1;
    const sig = ensureBytes('signature', signature, 64);
    const m = ensureBytes('message', message);
    const pub = ensureBytes('publicKey', publicKey, 32);
    try {
        const P = lift_x(num(pub)); // P = lift_x(int(pk)); fail if that fails
        const r = num(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r ≥ p.
        if (!inRange(r, _1n, secp256k1_CURVE.p))
            return false;
        const s = num(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n.
        if (!inRange(s, _1n, secp256k1_CURVE.n))
            return false;
        // int(challenge(bytes(r)||bytes(P)||m))%n
        const e = challenge(Fn.toBytes(r), pointToBytes(P), m);
        // R = s⋅G - e⋅P, where -eP == (n-e)P
        const R = BASE.multiplyUnsafe(s).add(P.multiplyUnsafe(Fn.neg(e)));
        const { x, y } = R.toAffine();
        // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r.
        if (R.is0() || !hasEven(y) || x !== r)
            return false;
        return true;
    }
    catch (error) {
        return false;
    }
}
/**
 * Schnorr signatures over secp256k1.
 * https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki
 * @example
 * ```js
 * import { schnorr } from '@noble/curves/secp256k1';
 * const { secretKey, publicKey } = schnorr.keygen();
 * // const publicKey = schnorr.getPublicKey(secretKey);
 * const msg = new TextEncoder().encode('hello');
 * const sig = schnorr.sign(msg, secretKey);
 * const isValid = schnorr.verify(sig, msg, publicKey);
 * ```
 */
export const schnorr = /* @__PURE__ */ (() => {
    const size = 32;
    const seedLength = 48;
    const randomSecretKey = (seed = randomBytes(seedLength)) => {
        return mapHashToField(seed, secp256k1_CURVE.n);
    };
    // TODO: remove
    secp256k1.utils.randomSecretKey;
    function keygen(seed) {
        const secretKey = randomSecretKey(seed);
        return { secretKey, publicKey: schnorrGetPublicKey(secretKey) };
    }
    return {
        keygen,
        getPublicKey: schnorrGetPublicKey,
        sign: schnorrSign,
        verify: schnorrVerify,
        Point: Pointk1,
        utils: {
            randomSecretKey: randomSecretKey,
            randomPrivateKey: randomSecretKey,
            taggedHash,
            // TODO: remove
            lift_x,
            pointToBytes,
            numberToBytesBE,
            bytesToNumberBE,
            mod,
        },
        lengths: {
            secretKey: size,
            publicKey: size,
            publicKeyHasPrefix: false,
            signature: size * 2,
            seed: seedLength,
        },
    };
})();
const isoMap = /* @__PURE__ */ (() => isogenyMap(Fpk1, [
    // xNum
    [
        '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7',
        '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581',
        '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262',
        '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c',
    ],
    // xDen
    [
        '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b',
        '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14',
        '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1
    ],
    // yNum
    [
        '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c',
        '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3',
        '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931',
        '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84',
    ],
    // yDen
    [
        '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b',
        '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573',
        '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f',
        '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1
    ],
].map((i) => i.map((j) => BigInt(j)))))();
const mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fpk1, {
    A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),
    B: BigInt('1771'),
    Z: Fpk1.create(BigInt('-11')),
}))();
/** Hashing / encoding to secp256k1 points / field. RFC 9380 methods. */
export const secp256k1_hasher = /* @__PURE__ */ (() => createHasher(secp256k1.Point, (scalars) => {
    const { x, y } = mapSWU(Fpk1.create(scalars[0]));
    return isoMap(x, y);
}, {
    DST: 'secp256k1_XMD:SHA-256_SSWU_RO_',
    encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_',
    p: Fpk1.ORDER,
    m: 1,
    k: 128,
    expand: 'xmd',
    hash: sha256,
}))();
/** @deprecated use `import { secp256k1_hasher } from '@noble/curves/secp256k1.js';` */
export const hashToCurve = /* @__PURE__ */ (() => secp256k1_hasher.hashToCurve)();
/** @deprecated use `import { secp256k1_hasher } from '@noble/curves/secp256k1.js';` */
export const encodeToCurve = /* @__PURE__ */ (() => secp256k1_hasher.encodeToCurve)();
//# sourceMappingURL=secp256k1.js.map/**
 * Hex, bytes and number utilities.
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { abytes as abytes_, bytesToHex as bytesToHex_, concatBytes as concatBytes_, hexToBytes as hexToBytes_, isBytes as isBytes_, } from '@noble/hashes/utils.js';
export { abytes, anumber, bytesToHex, bytesToUtf8, concatBytes, hexToBytes, isBytes, randomBytes, utf8ToBytes, } from '@noble/hashes/utils.js';
const _0n = /* @__PURE__ */ BigInt(0);
const _1n = /* @__PURE__ */ BigInt(1);
export function abool(title, value) {
    if (typeof value !== 'boolean')
        throw new Error(title + ' boolean expected, got ' + value);
}
// tmp name until v2
export function _abool2(value, title = '') {
    if (typeof value !== 'boolean') {
        const prefix = title && `"${title}"`;
        throw new Error(prefix + 'expected boolean, got type=' + typeof value);
    }
    return value;
}
// tmp name until v2
/** Asserts something is Uint8Array. */
export function _abytes2(value, length, title = '') {
    const bytes = isBytes_(value);
    const len = value?.length;
    const needsLen = length !== undefined;
    if (!bytes || (needsLen && len !== length)) {
        const prefix = title && `"${title}" `;
        const ofLen = needsLen ? ` of length ${length}` : '';
        const got = bytes ? `length=${len}` : `type=${typeof value}`;
        throw new Error(prefix + 'expected Uint8Array' + ofLen + ', got ' + got);
    }
    return value;
}
// Used in weierstrass, der
export function numberToHexUnpadded(num) {
    const hex = num.toString(16);
    return hex.length & 1 ? '0' + hex : hex;
}
export function hexToNumber(hex) {
    if (typeof hex !== 'string')
        throw new Error('hex string expected, got ' + typeof hex);
    return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian
}
// BE: Big Endian, LE: Little Endian
export function bytesToNumberBE(bytes) {
    return hexToNumber(bytesToHex_(bytes));
}
export function bytesToNumberLE(bytes) {
    abytes_(bytes);
    return hexToNumber(bytesToHex_(Uint8Array.from(bytes).reverse()));
}
export function numberToBytesBE(n, len) {
    return hexToBytes_(n.toString(16).padStart(len * 2, '0'));
}
export function numberToBytesLE(n, len) {
    return numberToBytesBE(n, len).reverse();
}
// Unpadded, rarely used
export function numberToVarBytesBE(n) {
    return hexToBytes_(numberToHexUnpadded(n));
}
/**
 * Takes hex string or Uint8Array, converts to Uint8Array.
 * Validates output length.
 * Will throw error for other types.
 * @param title descriptive title for an error e.g. 'secret key'
 * @param hex hex string or Uint8Array
 * @param expectedLength optional, will compare to result array's length
 * @returns
 */
export function ensureBytes(title, hex, expectedLength) {
    let res;
    if (typeof hex === 'string') {
        try {
            res = hexToBytes_(hex);
        }
        catch (e) {
            throw new Error(title + ' must be hex string or Uint8Array, cause: ' + e);
        }
    }
    else if (isBytes_(hex)) {
        // Uint8Array.from() instead of hash.slice() because node.js Buffer
        // is instance of Uint8Array, and its slice() creates **mutable** copy
        res = Uint8Array.from(hex);
    }
    else {
        throw new Error(title + ' must be hex string or Uint8Array');
    }
    const len = res.length;
    if (typeof expectedLength === 'number' && len !== expectedLength)
        throw new Error(title + ' of length ' + expectedLength + ' expected, got ' + len);
    return res;
}
// Compares 2 u8a-s in kinda constant time
export function equalBytes(a, b) {
    if (a.length !== b.length)
        return false;
    let diff = 0;
    for (let i = 0; i < a.length; i++)
        diff |= a[i] ^ b[i];
    return diff === 0;
}
/**
 * Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,
 * and Buffer#slice creates mutable copy. Never use Buffers!
 */
export function copyBytes(bytes) {
    return Uint8Array.from(bytes);
}
/**
 * Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols
 * Should be safe to use for things expected to be ASCII.
 * Returns exact same result as utf8ToBytes for ASCII or throws.
 */
export function asciiToBytes(ascii) {
    return Uint8Array.from(ascii, (c, i) => {
        const charCode = c.charCodeAt(0);
        if (c.length !== 1 || charCode > 127) {
            throw new Error(`string contains non-ASCII character "${ascii[i]}" with code ${charCode} at position ${i}`);
        }
        return charCode;
    });
}
/**
 * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
 */
// export const utf8ToBytes: typeof utf8ToBytes_ = utf8ToBytes_;
/**
 * Converts bytes to string using UTF8 encoding.
 * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'
 */
// export const bytesToUtf8: typeof bytesToUtf8_ = bytesToUtf8_;
// Is positive bigint
const isPosBig = (n) => typeof n === 'bigint' && _0n <= n;
export function inRange(n, min, max) {
    return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
}
/**
 * Asserts min <= n < max. NOTE: It's < max and not <= max.
 * @example
 * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)
 */
export function aInRange(title, n, min, max) {
    // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?
    // consider P=256n, min=0n, max=P
    // - a for min=0 would require -1:          `inRange('x', x, -1n, P)`
    // - b would commonly require subtraction:  `inRange('x', x, 0n, P - 1n)`
    // - our way is the cleanest:               `inRange('x', x, 0n, P)
    if (!inRange(n, min, max))
        throw new Error('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);
}
// Bit operations
/**
 * Calculates amount of bits in a bigint.
 * Same as `n.toString(2).length`
 * TODO: merge with nLength in modular
 */
export function bitLen(n) {
    let len;
    for (len = 0; n > _0n; n >>= _1n, len += 1)
        ;
    return len;
}
/**
 * Gets single bit at position.
 * NOTE: first bit position is 0 (same as arrays)
 * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`
 */
export function bitGet(n, pos) {
    return (n >> BigInt(pos)) & _1n;
}
/**
 * Sets single bit at position.
 */
export function bitSet(n, pos, value) {
    return n | ((value ? _1n : _0n) << BigInt(pos));
}
/**
 * Calculate mask for N bits. Not using ** operator with bigints because of old engines.
 * Same as BigInt(`0b${Array(i).fill('1').join('')}`)
 */
export const bitMask = (n) => (_1n << BigInt(n)) - _1n;
/**
 * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
 * @returns function that will call DRBG until 2nd arg returns something meaningful
 * @example
 *   const drbg = createHmacDRBG<Key>(32, 32, hmac);
 *   drbg(seed, bytesToKey); // bytesToKey must return Key or undefined
 */
export function createHmacDrbg(hashLen, qByteLen, hmacFn) {
    if (typeof hashLen !== 'number' || hashLen < 2)
        throw new Error('hashLen must be a number');
    if (typeof qByteLen !== 'number' || qByteLen < 2)
        throw new Error('qByteLen must be a number');
    if (typeof hmacFn !== 'function')
        throw new Error('hmacFn must be a function');
    // Step B, Step C: set hashLen to 8*ceil(hlen/8)
    const u8n = (len) => new Uint8Array(len); // creates Uint8Array
    const u8of = (byte) => Uint8Array.of(byte); // another shortcut
    let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
    let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same
    let i = 0; // Iterations counter, will throw when over 1000
    const reset = () => {
        v.fill(1);
        k.fill(0);
        i = 0;
    };
    const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)
    const reseed = (seed = u8n(0)) => {
        // HMAC-DRBG reseed() function. Steps D-G
        k = h(u8of(0x00), seed); // k = hmac(k || v || 0x00 || seed)
        v = h(); // v = hmac(k || v)
        if (seed.length === 0)
            return;
        k = h(u8of(0x01), seed); // k = hmac(k || v || 0x01 || seed)
        v = h(); // v = hmac(k || v)
    };
    const gen = () => {
        // HMAC-DRBG generate() function
        if (i++ >= 1000)
            throw new Error('drbg: tried 1000 values');
        let len = 0;
        const out = [];
        while (len < qByteLen) {
            v = h();
            const sl = v.slice();
            out.push(sl);
            len += v.length;
        }
        return concatBytes_(...out);
    };
    const genUntil = (seed, pred) => {
        reset();
        reseed(seed); // Steps D-G
        let res = undefined; // Step H: grind until k is in [1..n-1]
        while (!(res = pred(gen())))
            reseed();
        reset();
        return res;
    };
    return genUntil;
}
// Validating curves and fields
const validatorFns = {
    bigint: (val) => typeof val === 'bigint',
    function: (val) => typeof val === 'function',
    boolean: (val) => typeof val === 'boolean',
    string: (val) => typeof val === 'string',
    stringOrUint8Array: (val) => typeof val === 'string' || isBytes_(val),
    isSafeInteger: (val) => Number.isSafeInteger(val),
    array: (val) => Array.isArray(val),
    field: (val, object) => object.Fp.isValid(val),
    hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),
};
// type Record<K extends string | number | symbol, T> = { [P in K]: T; }
export function validateObject(object, validators, optValidators = {}) {
    const checkField = (fieldName, type, isOptional) => {
        const checkVal = validatorFns[type];
        if (typeof checkVal !== 'function')
            throw new Error('invalid validator function');
        const val = object[fieldName];
        if (isOptional && val === undefined)
            return;
        if (!checkVal(val, object)) {
            throw new Error('param ' + String(fieldName) + ' is invalid. Expected ' + type + ', got ' + val);
        }
    };
    for (const [fieldName, type] of Object.entries(validators))
        checkField(fieldName, type, false);
    for (const [fieldName, type] of Object.entries(optValidators))
        checkField(fieldName, type, true);
    return object;
}
// validate type tests
// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };
// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!
// // Should fail type-check
// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });
// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });
// const z3 = validateObject(o, { test: 'boolean', z: 'bug' });
// const z4 = validateObject(o, { a: 'boolean', z: 'bug' });
export function isHash(val) {
    return typeof val === 'function' && Number.isSafeInteger(val.outputLen);
}
export function _validateObject(object, fields, optFields = {}) {
    if (!object || typeof object !== 'object')
        throw new Error('expected valid options object');
    function checkField(fieldName, expectedType, isOpt) {
        const val = object[fieldName];
        if (isOpt && val === undefined)
            return;
        const current = typeof val;
        if (current !== expectedType || val === null)
            throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
    }
    Object.entries(fields).forEach(([k, v]) => checkField(k, v, false));
    Object.entries(optFields).forEach(([k, v]) => checkField(k, v, true));
}
/**
 * throws not implemented error
 */
export const notImplemented = () => {
    throw new Error('not implemented');
};
/**
 * Memoizes (caches) computation result.
 * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.
 */
export function memoized(fn) {
    const map = new WeakMap();
    return (arg, ...args) => {
        const val = map.get(arg);
        if (val !== undefined)
            return val;
        const computed = fn(arg, ...args);
        map.set(arg, computed);
        return computed;
    };
}
//# sourceMappingURL=utils.js.map/**
 * Internal Merkle-Damgard hash utils.
 * @module
 */
import { Hash, abytes, aexists, aoutput, clean, createView, toBytes } from "./utils.js";
/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */
export function setBigUint64(view, byteOffset, value, isLE) {
    if (typeof view.setBigUint64 === 'function')
        return view.setBigUint64(byteOffset, value, isLE);
    const _32n = BigInt(32);
    const _u32_max = BigInt(0xffffffff);
    const wh = Number((value >> _32n) & _u32_max);
    const wl = Number(value & _u32_max);
    const h = isLE ? 4 : 0;
    const l = isLE ? 0 : 4;
    view.setUint32(byteOffset + h, wh, isLE);
    view.setUint32(byteOffset + l, wl, isLE);
}
/** Choice: a ? b : c */
export function Chi(a, b, c) {
    return (a & b) ^ (~a & c);
}
/** Majority function, true if any two inputs is true. */
export function Maj(a, b, c) {
    return (a & b) ^ (a & c) ^ (b & c);
}
/**
 * Merkle-Damgard hash construction base class.
 * Could be used to create MD5, RIPEMD, SHA1, SHA2.
 */
export class HashMD extends Hash {
    constructor(blockLen, outputLen, padOffset, isLE) {
        super();
        this.finished = false;
        this.length = 0;
        this.pos = 0;
        this.destroyed = false;
        this.blockLen = blockLen;
        this.outputLen = outputLen;
        this.padOffset = padOffset;
        this.isLE = isLE;
        this.buffer = new Uint8Array(blockLen);
        this.view = createView(this.buffer);
    }
    update(data) {
        aexists(this);
        data = toBytes(data);
        abytes(data);
        const { view, buffer, blockLen } = this;
        const len = data.length;
        for (let pos = 0; pos < len;) {
            const take = Math.min(blockLen - this.pos, len - pos);
            // Fast path: we have at least one block in input, cast it to view and process
            if (take === blockLen) {
                const dataView = createView(data);
                for (; blockLen <= len - pos; pos += blockLen)
                    this.process(dataView, pos);
                continue;
            }
            buffer.set(data.subarray(pos, pos + take), this.pos);
            this.pos += take;
            pos += take;
            if (this.pos === blockLen) {
                this.process(view, 0);
                this.pos = 0;
            }
        }
        this.length += data.length;
        this.roundClean();
        return this;
    }
    digestInto(out) {
        aexists(this);
        aoutput(out, this);
        this.finished = true;
        // Padding
        // We can avoid allocation of buffer for padding completely if it
        // was previously not allocated here. But it won't change performance.
        const { buffer, view, blockLen, isLE } = this;
        let { pos } = this;
        // append the bit '1' to the message
        buffer[pos++] = 0b10000000;
        clean(this.buffer.subarray(pos));
        // we have less than padOffset left in buffer, so we cannot put length in
        // current block, need process it and pad again
        if (this.padOffset > blockLen - pos) {
            this.process(view, 0);
            pos = 0;
        }
        // Pad until full block byte with zeros
        for (let i = pos; i < blockLen; i++)
            buffer[i] = 0;
        // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that
        // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.
        // So we just write lowest 64 bits of that value.
        setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
        this.process(view, 0);
        const oview = createView(out);
        const len = this.outputLen;
        // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT
        if (len % 4)
            throw new Error('_sha2: outputLen should be aligned to 32bit');
        const outLen = len / 4;
        const state = this.get();
        if (outLen > state.length)
            throw new Error('_sha2: outputLen bigger than state');
        for (let i = 0; i < outLen; i++)
            oview.setUint32(4 * i, state[i], isLE);
    }
    digest() {
        const { buffer, outputLen } = this;
        this.digestInto(buffer);
        const res = buffer.slice(0, outputLen);
        this.destroy();
        return res;
    }
    _cloneInto(to) {
        to || (to = new this.constructor());
        to.set(...this.get());
        const { blockLen, buffer, length, finished, destroyed, pos } = this;
        to.destroyed = destroyed;
        to.finished = finished;
        to.length = length;
        to.pos = pos;
        if (length % blockLen)
            to.buffer.set(buffer);
        return to;
    }
    clone() {
        return this._cloneInto();
    }
}
/**
 * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.
 * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.
 */
/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */
export const SHA256_IV = /* @__PURE__ */ Uint32Array.from([
    0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
]);
/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */
export const SHA224_IV = /* @__PURE__ */ Uint32Array.from([
    0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,
]);
/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */
export const SHA384_IV = /* @__PURE__ */ Uint32Array.from([
    0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,
    0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,
]);
/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */
export const SHA512_IV = /* @__PURE__ */ Uint32Array.from([
    0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,
    0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,
]);
//# sourceMappingURL=_md.js.map/**
 * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.
 * @todo re-check https://issues.chromium.org/issues/42212588
 * @module
 */
const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
const _32n = /* @__PURE__ */ BigInt(32);
function fromBig(n, le = false) {
    if (le)
        return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };
    return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
}
function split(lst, le = false) {
    const len = lst.length;
    let Ah = new Uint32Array(len);
    let Al = new Uint32Array(len);
    for (let i = 0; i < len; i++) {
        const { h, l } = fromBig(lst[i], le);
        [Ah[i], Al[i]] = [h, l];
    }
    return [Ah, Al];
}
const toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);
// for Shift in [0, 32)
const shrSH = (h, _l, s) => h >>> s;
const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
// Right rotate for Shift in [1, 32)
const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));
const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
// Right rotate for Shift in (32, 64), NOTE: 32 is special case.
const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));
const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));
// Right rotate for shift===32 (just swaps l&h)
const rotr32H = (_h, l) => l;
const rotr32L = (h, _l) => h;
// Left rotate for Shift in [1, 32)
const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));
const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));
// Left rotate for Shift in (32, 64), NOTE: 32 is special case.
const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));
const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));
// JS uses 32-bit signed integers for bitwise operations which means we cannot
// simple take carry out of low bit sum by shift, we need to use division.
function add(Ah, Al, Bh, Bl) {
    const l = (Al >>> 0) + (Bl >>> 0);
    return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };
}
// Addition with more than 2 elements
const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;
const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;
const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;
// prettier-ignore
export { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig };
// prettier-ignore
const u64 = {
    fromBig, split, toBig,
    shrSH, shrSL,
    rotrSH, rotrSL, rotrBH, rotrBL,
    rotr32H, rotr32L,
    rotlSH, rotlSL, rotlBH, rotlBL,
    add, add3L, add3H, add4L, add4H, add5H, add5L,
};
export default u64;
//# sourceMappingURL=_u64.js.mapexport const crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;
//# sourceMappingURL=crypto.js.map/**
 * HMAC: RFC2104 message authentication code.
 * @module
 */
import { abytes, aexists, ahash, clean, Hash, toBytes } from "./utils.js";
export class HMAC extends Hash {
    constructor(hash, _key) {
        super();
        this.finished = false;
        this.destroyed = false;
        ahash(hash);
        const key = toBytes(_key);
        this.iHash = hash.create();
        if (typeof this.iHash.update !== 'function')
            throw new Error('Expected instance of class which extends utils.Hash');
        this.blockLen = this.iHash.blockLen;
        this.outputLen = this.iHash.outputLen;
        const blockLen = this.blockLen;
        const pad = new Uint8Array(blockLen);
        // blockLen can be bigger than outputLen
        pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
        for (let i = 0; i < pad.length; i++)
            pad[i] ^= 0x36;
        this.iHash.update(pad);
        // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone
        this.oHash = hash.create();
        // Undo internal XOR && apply outer XOR
        for (let i = 0; i < pad.length; i++)
            pad[i] ^= 0x36 ^ 0x5c;
        this.oHash.update(pad);
        clean(pad);
    }
    update(buf) {
        aexists(this);
        this.iHash.update(buf);
        return this;
    }
    digestInto(out) {
        aexists(this);
        abytes(out, this.outputLen);
        this.finished = true;
        this.iHash.digestInto(out);
        this.oHash.update(out);
        this.oHash.digestInto(out);
        this.destroy();
    }
    digest() {
        const out = new Uint8Array(this.oHash.outputLen);
        this.digestInto(out);
        return out;
    }
    _cloneInto(to) {
        // Create new instance without calling constructor since key already in state and we don't know it.
        to || (to = Object.create(Object.getPrototypeOf(this), {}));
        const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
        to = to;
        to.finished = finished;
        to.destroyed = destroyed;
        to.blockLen = blockLen;
        to.outputLen = outputLen;
        to.oHash = oHash._cloneInto(to.oHash);
        to.iHash = iHash._cloneInto(to.iHash);
        return to;
    }
    clone() {
        return this._cloneInto();
    }
    destroy() {
        this.destroyed = true;
        this.oHash.destroy();
        this.iHash.destroy();
    }
}
/**
 * HMAC: RFC2104 message authentication code.
 * @param hash - function that would be used e.g. sha256
 * @param key - message key
 * @param message - message data
 * @example
 * import { hmac } from '@noble/hashes/hmac';
 * import { sha256 } from '@noble/hashes/sha2';
 * const mac1 = hmac(sha256, 'key', 'message');
 */
export const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
hmac.create = (hash, key) => new HMAC(hash, key);
//# sourceMappingURL=hmac.js.map{
  "type": "module",
  "sideEffects": false,
  "browser": {
    "node:crypto": false
  },
  "node": {
    "./crypto": "./esm/cryptoNode.js"
  }
}
/**
 * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.
 * SHA256 is the fastest hash implementable in JS, even faster than Blake3.
 * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and
 * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).
 * @module
 */
import { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from "./_md.js";
import * as u64 from "./_u64.js";
import { clean, createHasher, rotr } from "./utils.js";
/**
 * Round constants:
 * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)
 */
// prettier-ignore
const SHA256_K = /* @__PURE__ */ Uint32Array.from([
    0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
    0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
    0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
    0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
    0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
    0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
    0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
    0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
]);
/** Reusable temporary buffer. "W" comes straight from spec. */
const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
export class SHA256 extends HashMD {
    constructor(outputLen = 32) {
        super(64, outputLen, 8, false);
        // We cannot use array here since array allows indexing by variable
        // which means optimizer/compiler cannot use registers.
        this.A = SHA256_IV[0] | 0;
        this.B = SHA256_IV[1] | 0;
        this.C = SHA256_IV[2] | 0;
        this.D = SHA256_IV[3] | 0;
        this.E = SHA256_IV[4] | 0;
        this.F = SHA256_IV[5] | 0;
        this.G = SHA256_IV[6] | 0;
        this.H = SHA256_IV[7] | 0;
    }
    get() {
        const { A, B, C, D, E, F, G, H } = this;
        return [A, B, C, D, E, F, G, H];
    }
    // prettier-ignore
    set(A, B, C, D, E, F, G, H) {
        this.A = A | 0;
        this.B = B | 0;
        this.C = C | 0;
        this.D = D | 0;
        this.E = E | 0;
        this.F = F | 0;
        this.G = G | 0;
        this.H = H | 0;
    }
    process(view, offset) {
        // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array
        for (let i = 0; i < 16; i++, offset += 4)
            SHA256_W[i] = view.getUint32(offset, false);
        for (let i = 16; i < 64; i++) {
            const W15 = SHA256_W[i - 15];
            const W2 = SHA256_W[i - 2];
            const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);
            const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);
            SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;
        }
        // Compression function main loop, 64 rounds
        let { A, B, C, D, E, F, G, H } = this;
        for (let i = 0; i < 64; i++) {
            const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
            const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
            const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
            const T2 = (sigma0 + Maj(A, B, C)) | 0;
            H = G;
            G = F;
            F = E;
            E = (D + T1) | 0;
            D = C;
            C = B;
            B = A;
            A = (T1 + T2) | 0;
        }
        // Add the compressed chunk to the current hash value
        A = (A + this.A) | 0;
        B = (B + this.B) | 0;
        C = (C + this.C) | 0;
        D = (D + this.D) | 0;
        E = (E + this.E) | 0;
        F = (F + this.F) | 0;
        G = (G + this.G) | 0;
        H = (H + this.H) | 0;
        this.set(A, B, C, D, E, F, G, H);
    }
    roundClean() {
        clean(SHA256_W);
    }
    destroy() {
        this.set(0, 0, 0, 0, 0, 0, 0, 0);
        clean(this.buffer);
    }
}
export class SHA224 extends SHA256 {
    constructor() {
        super(28);
        this.A = SHA224_IV[0] | 0;
        this.B = SHA224_IV[1] | 0;
        this.C = SHA224_IV[2] | 0;
        this.D = SHA224_IV[3] | 0;
        this.E = SHA224_IV[4] | 0;
        this.F = SHA224_IV[5] | 0;
        this.G = SHA224_IV[6] | 0;
        this.H = SHA224_IV[7] | 0;
    }
}
// SHA2-512 is slower than sha256 in js because u64 operations are slow.
// Round contants
// First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409
// prettier-ignore
const K512 = /* @__PURE__ */ (() => u64.split([
    '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',
    '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',
    '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',
    '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',
    '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',
    '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',
    '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',
    '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',
    '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',
    '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',
    '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',
    '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',
    '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',
    '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',
    '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',
    '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',
    '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',
    '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',
    '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',
    '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'
].map(n => BigInt(n))))();
const SHA512_Kh = /* @__PURE__ */ (() => K512[0])();
const SHA512_Kl = /* @__PURE__ */ (() => K512[1])();
// Reusable temporary buffers
const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
export class SHA512 extends HashMD {
    constructor(outputLen = 64) {
        super(128, outputLen, 16, false);
        // We cannot use array here since array allows indexing by variable
        // which means optimizer/compiler cannot use registers.
        // h -- high 32 bits, l -- low 32 bits
        this.Ah = SHA512_IV[0] | 0;
        this.Al = SHA512_IV[1] | 0;
        this.Bh = SHA512_IV[2] | 0;
        this.Bl = SHA512_IV[3] | 0;
        this.Ch = SHA512_IV[4] | 0;
        this.Cl = SHA512_IV[5] | 0;
        this.Dh = SHA512_IV[6] | 0;
        this.Dl = SHA512_IV[7] | 0;
        this.Eh = SHA512_IV[8] | 0;
        this.El = SHA512_IV[9] | 0;
        this.Fh = SHA512_IV[10] | 0;
        this.Fl = SHA512_IV[11] | 0;
        this.Gh = SHA512_IV[12] | 0;
        this.Gl = SHA512_IV[13] | 0;
        this.Hh = SHA512_IV[14] | 0;
        this.Hl = SHA512_IV[15] | 0;
    }
    // prettier-ignore
    get() {
        const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
        return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
    }
    // prettier-ignore
    set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
        this.Ah = Ah | 0;
        this.Al = Al | 0;
        this.Bh = Bh | 0;
        this.Bl = Bl | 0;
        this.Ch = Ch | 0;
        this.Cl = Cl | 0;
        this.Dh = Dh | 0;
        this.Dl = Dl | 0;
        this.Eh = Eh | 0;
        this.El = El | 0;
        this.Fh = Fh | 0;
        this.Fl = Fl | 0;
        this.Gh = Gh | 0;
        this.Gl = Gl | 0;
        this.Hh = Hh | 0;
        this.Hl = Hl | 0;
    }
    process(view, offset) {
        // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array
        for (let i = 0; i < 16; i++, offset += 4) {
            SHA512_W_H[i] = view.getUint32(offset);
            SHA512_W_L[i] = view.getUint32((offset += 4));
        }
        for (let i = 16; i < 80; i++) {
            // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)
            const W15h = SHA512_W_H[i - 15] | 0;
            const W15l = SHA512_W_L[i - 15] | 0;
            const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);
            const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);
            // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)
            const W2h = SHA512_W_H[i - 2] | 0;
            const W2l = SHA512_W_L[i - 2] | 0;
            const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);
            const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);
            // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];
            const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
            const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
            SHA512_W_H[i] = SUMh | 0;
            SHA512_W_L[i] = SUMl | 0;
        }
        let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
        // Compression function main loop, 80 rounds
        for (let i = 0; i < 80; i++) {
            // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)
            const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);
            const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);
            //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
            const CHIh = (Eh & Fh) ^ (~Eh & Gh);
            const CHIl = (El & Fl) ^ (~El & Gl);
            // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]
            // prettier-ignore
            const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
            const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
            const T1l = T1ll | 0;
            // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)
            const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);
            const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);
            const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);
            const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);
            Hh = Gh | 0;
            Hl = Gl | 0;
            Gh = Fh | 0;
            Gl = Fl | 0;
            Fh = Eh | 0;
            Fl = El | 0;
            ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
            Dh = Ch | 0;
            Dl = Cl | 0;
            Ch = Bh | 0;
            Cl = Bl | 0;
            Bh = Ah | 0;
            Bl = Al | 0;
            const All = u64.add3L(T1l, sigma0l, MAJl);
            Ah = u64.add3H(All, T1h, sigma0h, MAJh);
            Al = All | 0;
        }
        // Add the compressed chunk to the current hash value
        ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
        ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
        ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
        ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
        ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
        ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
        ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
        ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
        this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
    }
    roundClean() {
        clean(SHA512_W_H, SHA512_W_L);
    }
    destroy() {
        clean(this.buffer);
        this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
    }
}
export class SHA384 extends SHA512 {
    constructor() {
        super(48);
        this.Ah = SHA384_IV[0] | 0;
        this.Al = SHA384_IV[1] | 0;
        this.Bh = SHA384_IV[2] | 0;
        this.Bl = SHA384_IV[3] | 0;
        this.Ch = SHA384_IV[4] | 0;
        this.Cl = SHA384_IV[5] | 0;
        this.Dh = SHA384_IV[6] | 0;
        this.Dl = SHA384_IV[7] | 0;
        this.Eh = SHA384_IV[8] | 0;
        this.El = SHA384_IV[9] | 0;
        this.Fh = SHA384_IV[10] | 0;
        this.Fl = SHA384_IV[11] | 0;
        this.Gh = SHA384_IV[12] | 0;
        this.Gl = SHA384_IV[13] | 0;
        this.Hh = SHA384_IV[14] | 0;
        this.Hl = SHA384_IV[15] | 0;
    }
}
/**
 * Truncated SHA512/256 and SHA512/224.
 * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as "intermediary" IV of SHA512/t.
 * Then t hashes string to produce result IV.
 * See `test/misc/sha2-gen-iv.js`.
 */
/** SHA512/224 IV */
const T224_IV = /* @__PURE__ */ Uint32Array.from([
    0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,
    0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,
]);
/** SHA512/256 IV */
const T256_IV = /* @__PURE__ */ Uint32Array.from([
    0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,
    0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,
]);
export class SHA512_224 extends SHA512 {
    constructor() {
        super(28);
        this.Ah = T224_IV[0] | 0;
        this.Al = T224_IV[1] | 0;
        this.Bh = T224_IV[2] | 0;
        this.Bl = T224_IV[3] | 0;
        this.Ch = T224_IV[4] | 0;
        this.Cl = T224_IV[5] | 0;
        this.Dh = T224_IV[6] | 0;
        this.Dl = T224_IV[7] | 0;
        this.Eh = T224_IV[8] | 0;
        this.El = T224_IV[9] | 0;
        this.Fh = T224_IV[10] | 0;
        this.Fl = T224_IV[11] | 0;
        this.Gh = T224_IV[12] | 0;
        this.Gl = T224_IV[13] | 0;
        this.Hh = T224_IV[14] | 0;
        this.Hl = T224_IV[15] | 0;
    }
}
export class SHA512_256 extends SHA512 {
    constructor() {
        super(32);
        this.Ah = T256_IV[0] | 0;
        this.Al = T256_IV[1] | 0;
        this.Bh = T256_IV[2] | 0;
        this.Bl = T256_IV[3] | 0;
        this.Ch = T256_IV[4] | 0;
        this.Cl = T256_IV[5] | 0;
        this.Dh = T256_IV[6] | 0;
        this.Dl = T256_IV[7] | 0;
        this.Eh = T256_IV[8] | 0;
        this.El = T256_IV[9] | 0;
        this.Fh = T256_IV[10] | 0;
        this.Fl = T256_IV[11] | 0;
        this.Gh = T256_IV[12] | 0;
        this.Gl = T256_IV[13] | 0;
        this.Hh = T256_IV[14] | 0;
        this.Hl = T256_IV[15] | 0;
    }
}
/**
 * SHA2-256 hash function from RFC 4634.
 *
 * It is the fastest JS hash, even faster than Blake3.
 * To break sha256 using birthday attack, attackers need to try 2^128 hashes.
 * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
 */
export const sha256 = /* @__PURE__ */ createHasher(() => new SHA256());
/** SHA2-224 hash function from RFC 4634 */
export const sha224 = /* @__PURE__ */ createHasher(() => new SHA224());
/** SHA2-512 hash function from RFC 4634. */
export const sha512 = /* @__PURE__ */ createHasher(() => new SHA512());
/** SHA2-384 hash function from RFC 4634. */
export const sha384 = /* @__PURE__ */ createHasher(() => new SHA384());
/**
 * SHA2-512/256 "truncated" hash function, with improved resistance to length extension attacks.
 * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).
 */
export const sha512_256 = /* @__PURE__ */ createHasher(() => new SHA512_256());
/**
 * SHA2-512/224 "truncated" hash function, with improved resistance to length extension attacks.
 * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).
 */
export const sha512_224 = /* @__PURE__ */ createHasher(() => new SHA512_224());
//# sourceMappingURL=sha2.js.map/**
 * Utilities for hex, bytes, CSPRNG.
 * @module
 */
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
// node.js versions earlier than v19 don't declare it in global scope.
// For node.js, package.json#exports field mapping rewrites import
// from `crypto` to `cryptoNode`, which imports native module.
// Makes the utils un-importable in browsers without a bundler.
// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.
import { crypto } from '@noble/hashes/crypto';
/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */
export function isBytes(a) {
    return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
}
/** Asserts something is positive integer. */
export function anumber(n) {
    if (!Number.isSafeInteger(n) || n < 0)
        throw new Error('positive integer expected, got ' + n);
}
/** Asserts something is Uint8Array. */
export function abytes(b, ...lengths) {
    if (!isBytes(b))
        throw new Error('Uint8Array expected');
    if (lengths.length > 0 && !lengths.includes(b.length))
        throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);
}
/** Asserts something is hash */
export function ahash(h) {
    if (typeof h !== 'function' || typeof h.create !== 'function')
        throw new Error('Hash should be wrapped by utils.createHasher');
    anumber(h.outputLen);
    anumber(h.blockLen);
}
/** Asserts a hash instance has not been destroyed / finished */
export function aexists(instance, checkFinished = true) {
    if (instance.destroyed)
        throw new Error('Hash instance has been destroyed');
    if (checkFinished && instance.finished)
        throw new Error('Hash#digest() has already been called');
}
/** Asserts output is properly-sized byte array */
export function aoutput(out, instance) {
    abytes(out);
    const min = instance.outputLen;
    if (out.length < min) {
        throw new Error('digestInto() expects output buffer of length at least ' + min);
    }
}
/** Cast u8 / u16 / u32 to u8. */
export function u8(arr) {
    return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
}
/** Cast u8 / u16 / u32 to u32. */
export function u32(arr) {
    return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
}
/** Zeroize a byte array. Warning: JS provides no guarantees. */
export function clean(...arrays) {
    for (let i = 0; i < arrays.length; i++) {
        arrays[i].fill(0);
    }
}
/** Create DataView of an array for easy byte-level manipulation. */
export function createView(arr) {
    return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
}
/** The rotate right (circular right shift) operation for uint32 */
export function rotr(word, shift) {
    return (word << (32 - shift)) | (word >>> shift);
}
/** The rotate left (circular left shift) operation for uint32 */
export function rotl(word, shift) {
    return (word << shift) | ((word >>> (32 - shift)) >>> 0);
}
/** Is current platform little-endian? Most are. Big-Endian platform: IBM */
export const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();
/** The byte swap operation for uint32 */
export function byteSwap(word) {
    return (((word << 24) & 0xff000000) |
        ((word << 8) & 0xff0000) |
        ((word >>> 8) & 0xff00) |
        ((word >>> 24) & 0xff));
}
/** Conditionally byte swap if on a big-endian platform */
export const swap8IfBE = isLE
    ? (n) => n
    : (n) => byteSwap(n);
/** @deprecated */
export const byteSwapIfBE = swap8IfBE;
/** In place byte swap for Uint32Array */
export function byteSwap32(arr) {
    for (let i = 0; i < arr.length; i++) {
        arr[i] = byteSwap(arr[i]);
    }
    return arr;
}
export const swap32IfBE = isLE
    ? (u) => u
    : byteSwap32;
// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex
const hasHexBuiltin = /* @__PURE__ */ (() => 
// @ts-ignore
typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();
// Array where index 0xf0 (240) is mapped to string 'f0'
const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
/**
 * Convert byte array to hex string. Uses built-in function, when available.
 * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
 */
export function bytesToHex(bytes) {
    abytes(bytes);
    // @ts-ignore
    if (hasHexBuiltin)
        return bytes.toHex();
    // pre-caching improves the speed 6x
    let hex = '';
    for (let i = 0; i < bytes.length; i++) {
        hex += hexes[bytes[i]];
    }
    return hex;
}
// We use optimized technique to convert hex string to byte array
const asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
function asciiToBase16(ch) {
    if (ch >= asciis._0 && ch <= asciis._9)
        return ch - asciis._0; // '2' => 50-48
    if (ch >= asciis.A && ch <= asciis.F)
        return ch - (asciis.A - 10); // 'B' => 66-(65-10)
    if (ch >= asciis.a && ch <= asciis.f)
        return ch - (asciis.a - 10); // 'b' => 98-(97-10)
    return;
}
/**
 * Convert hex string to byte array. Uses built-in function, when available.
 * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
 */
export function hexToBytes(hex) {
    if (typeof hex !== 'string')
        throw new Error('hex string expected, got ' + typeof hex);
    // @ts-ignore
    if (hasHexBuiltin)
        return Uint8Array.fromHex(hex);
    const hl = hex.length;
    const al = hl / 2;
    if (hl % 2)
        throw new Error('hex string expected, got unpadded hex of length ' + hl);
    const array = new Uint8Array(al);
    for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
        const n1 = asciiToBase16(hex.charCodeAt(hi));
        const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
        if (n1 === undefined || n2 === undefined) {
            const char = hex[hi] + hex[hi + 1];
            throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
        }
        array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163
    }
    return array;
}
/**
 * There is no setImmediate in browser and setTimeout is slow.
 * Call of async fn will return Promise, which will be fullfiled only on
 * next scheduler queue processing step and this is exactly what we need.
 */
export const nextTick = async () => { };
/** Returns control to thread each 'tick' ms to avoid blocking. */
export async function asyncLoop(iters, tick, cb) {
    let ts = Date.now();
    for (let i = 0; i < iters; i++) {
        cb(i);
        // Date.now() is not monotonic, so in case if clock goes backwards we return return control too
        const diff = Date.now() - ts;
        if (diff >= 0 && diff < tick)
            continue;
        await nextTick();
        ts += diff;
    }
}
/**
 * Converts string to bytes using UTF8 encoding.
 * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])
 */
export function utf8ToBytes(str) {
    if (typeof str !== 'string')
        throw new Error('string expected');
    return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
}
/**
 * Converts bytes to string using UTF8 encoding.
 * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'
 */
export function bytesToUtf8(bytes) {
    return new TextDecoder().decode(bytes);
}
/**
 * Normalizes (non-hex) string or Uint8Array to Uint8Array.
 * Warning: when Uint8Array is passed, it would NOT get copied.
 * Keep in mind for future mutable operations.
 */
export function toBytes(data) {
    if (typeof data === 'string')
        data = utf8ToBytes(data);
    abytes(data);
    return data;
}
/**
 * Helper for KDFs: consumes uint8array or string.
 * When string is passed, does utf8 decoding, using TextDecoder.
 */
export function kdfInputToBytes(data) {
    if (typeof data === 'string')
        data = utf8ToBytes(data);
    abytes(data);
    return data;
}
/** Copies several Uint8Arrays into one. */
export function concatBytes(...arrays) {
    let sum = 0;
    for (let i = 0; i < arrays.length; i++) {
        const a = arrays[i];
        abytes(a);
        sum += a.length;
    }
    const res = new Uint8Array(sum);
    for (let i = 0, pad = 0; i < arrays.length; i++) {
        const a = arrays[i];
        res.set(a, pad);
        pad += a.length;
    }
    return res;
}
export function checkOpts(defaults, opts) {
    if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')
        throw new Error('options should be object or undefined');
    const merged = Object.assign(defaults, opts);
    return merged;
}
/** For runtime check if class implements interface */
export class Hash {
}
/** Wraps hash function, creating an interface on top of it */
export function createHasher(hashCons) {
    const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
    const tmp = hashCons();
    hashC.outputLen = tmp.outputLen;
    hashC.blockLen = tmp.blockLen;
    hashC.create = () => hashCons();
    return hashC;
}
export function createOptHasher(hashCons) {
    const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();
    const tmp = hashCons({});
    hashC.outputLen = tmp.outputLen;
    hashC.blockLen = tmp.blockLen;
    hashC.create = (opts) => hashCons(opts);
    return hashC;
}
export function createXOFer(hashCons) {
    const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();
    const tmp = hashCons({});
    hashC.outputLen = tmp.outputLen;
    hashC.blockLen = tmp.blockLen;
    hashC.create = (opts) => hashCons(opts);
    return hashC;
}
export const wrapConstructor = createHasher;
export const wrapConstructorWithOpts = createOptHasher;
export const wrapXOFConstructorWithOpts = createXOFer;
/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */
export function randomBytes(bytesLength = 32) {
    if (crypto && typeof crypto.getRandomValues === 'function') {
        return crypto.getRandomValues(new Uint8Array(bytesLength));
    }
    // Legacy Node.js compatibility
    if (crypto && typeof crypto.randomBytes === 'function') {
        return Uint8Array.from(crypto.randomBytes(bytesLength));
    }
    throw new Error('crypto.getRandomValues must be defined');
}
//# sourceMappingURL=utils.js.mapimport { encode, encodeInto, objectToTokens, rfc8949EncodeOptions } from './lib/encode.js'
import { decode, decodeFirst, Tokeniser, tokensToObject } from './lib/decode.js'
import { Tagged } from './lib/tagged.js'
import { Token, Type } from './lib/token.js'

/**
 * Export the types that were present in the original manual cborg.d.ts
 * @typedef {import('./interface.js').TagDecodeControl} TagDecodeControl
 * @typedef {import('./interface.js').TagDecoder} TagDecoder
 * There was originally just `TypeEncoder` so don't break types by renaming or not exporting
 * @typedef {import('./interface.js').OptionalTypeEncoder} TypeEncoder
 * @typedef {import('./interface.js').DecodeOptions} DecodeOptions
 * @typedef {import('./interface.js').EncodeOptions} EncodeOptions
 */

export {
  decode,
  decodeFirst,
  Tokeniser as Tokenizer,
  tokensToObject,
  encode,
  encodeInto,
  objectToTokens,
  rfc8949EncodeOptions,
  Tagged,
  Token,
  Type
}
/* globals BigInt */

import { Token, Type } from './token.js'
import { decodeErrPrefix, assertEnoughData } from './common.js'

export const uintBoundaries = [24, 256, 65536, 4294967296, BigInt('18446744073709551616')]

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number}
 */
export function readUint8 (data, offset, options) {
  assertEnoughData(data, offset, 1)
  const value = data[offset]
  if (options.strict === true && value < uintBoundaries[0]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  return value
}

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number}
 */
export function readUint16 (data, offset, options) {
  assertEnoughData(data, offset, 2)
  const value = (data[offset] << 8) | data[offset + 1]
  if (options.strict === true && value < uintBoundaries[1]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  return value
}

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number}
 */
export function readUint32 (data, offset, options) {
  assertEnoughData(data, offset, 4)
  const value = (data[offset] * 16777216 /* 2 ** 24 */) + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]
  if (options.strict === true && value < uintBoundaries[2]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  return value
}

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number|bigint}
 */
export function readUint64 (data, offset, options) {
  // assume BigInt, convert back to Number if within safe range
  assertEnoughData(data, offset, 8)
  const hi = (data[offset] * 16777216 /* 2 ** 24 */) + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]
  const lo = (data[offset + 4] * 16777216 /* 2 ** 24 */) + (data[offset + 5] << 16) + (data[offset + 6] << 8) + data[offset + 7]
  const value = (BigInt(hi) << BigInt(32)) + BigInt(lo)
  if (options.strict === true && value < uintBoundaries[3]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  if (value <= Number.MAX_SAFE_INTEGER) {
    return Number(value)
  }
  if (options.allowBigInt === true) {
    return value
  }
  throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`)
}

/* not required thanks to quick[] list
const oneByteTokens = new Array(24).fill(0).map((v, i) => new Token(Type.uint, i, 1))
export function decodeUintCompact (data, pos, minor, options) {
  return oneByteTokens[minor]
}
*/

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint8 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint8(data, pos + 1, options), 2)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint16 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint16(data, pos + 1, options), 3)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint32 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint32(data, pos + 1, options), 5)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint64 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint64(data, pos + 1, options), 9)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeUint (writer, token) {
  return encodeUintValue(writer, 0, token.value)
}

/**
 * @param {ByteWriter} writer
 * @param {number} major
 * @param {number|bigint} uint
 */
export function encodeUintValue (writer, major, uint) {
  if (uint < uintBoundaries[0]) {
    const nuint = Number(uint)
    // pack into one byte, minor=0, additional=value
    writer.push([major | nuint])
  } else if (uint < uintBoundaries[1]) {
    const nuint = Number(uint)
    // pack into two byte, minor=0, additional=24
    writer.push([major | 24, nuint])
  } else if (uint < uintBoundaries[2]) {
    const nuint = Number(uint)
    // pack into three byte, minor=0, additional=25
    writer.push([major | 25, nuint >>> 8, nuint & 0xff])
  } else if (uint < uintBoundaries[3]) {
    const nuint = Number(uint)
    // pack into five byte, minor=0, additional=26
    writer.push([major | 26, (nuint >>> 24) & 0xff, (nuint >>> 16) & 0xff, (nuint >>> 8) & 0xff, nuint & 0xff])
  } else {
    const buint = BigInt(uint)
    if (buint < uintBoundaries[4]) {
      // pack into nine byte, minor=0, additional=27
      const set = [major | 27, 0, 0, 0, 0, 0, 0, 0]
      // simulate bitwise above 32 bits
      let lo = Number(buint & BigInt(0xffffffff))
      let hi = Number(buint >> BigInt(32) & BigInt(0xffffffff))
      set[8] = lo & 0xff
      lo = lo >> 8
      set[7] = lo & 0xff
      lo = lo >> 8
      set[6] = lo & 0xff
      lo = lo >> 8
      set[5] = lo & 0xff
      set[4] = hi & 0xff
      hi = hi >> 8
      set[3] = hi & 0xff
      hi = hi >> 8
      set[2] = hi & 0xff
      hi = hi >> 8
      set[1] = hi & 0xff
      writer.push(set)
    } else {
      throw new Error(`${decodeErrPrefix} encountered BigInt larger than allowable range`)
    }
  }
}

/**
 * @param {Token} token
 * @returns {number}
 */
encodeUint.encodedSize = function encodedSize (token) {
  return encodeUintValue.encodedSize(token.value)
}

/**
 * @param {number} uint
 * @returns {number}
 */
encodeUintValue.encodedSize = function encodedSize (uint) {
  if (uint < uintBoundaries[0]) {
    return 1
  }
  if (uint < uintBoundaries[1]) {
    return 2
  }
  if (uint < uintBoundaries[2]) {
    return 3
  }
  if (uint < uintBoundaries[3]) {
    return 5
  }
  return 9
}

/**
 * @param {Token} tok1
 * @param {Token} tok2
 * @returns {number}
 */
encodeUint.compareTokens = function compareTokens (tok1, tok2) {
  return tok1.value < tok2.value ? -1 : tok1.value > tok2.value ? 1 : 0
}
/* eslint-env es2020 */

import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import { decodeErrPrefix } from './common.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint8 (data, pos, _minor, options) {
  return new Token(Type.negint, -1 - uint.readUint8(data, pos + 1, options), 2)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint16 (data, pos, _minor, options) {
  return new Token(Type.negint, -1 - uint.readUint16(data, pos + 1, options), 3)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint32 (data, pos, _minor, options) {
  return new Token(Type.negint, -1 - uint.readUint32(data, pos + 1, options), 5)
}

const neg1b = BigInt(-1)
const pos1b = BigInt(1)

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint64 (data, pos, _minor, options) {
  const int = uint.readUint64(data, pos + 1, options)
  if (typeof int !== 'bigint') {
    const value = -1 - int
    if (value >= Number.MIN_SAFE_INTEGER) {
      return new Token(Type.negint, value, 9)
    }
  }
  if (options.allowBigInt !== true) {
    throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`)
  }
  return new Token(Type.negint, neg1b - BigInt(int), 9)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeNegint (writer, token) {
  const negint = token.value
  const unsigned = (typeof negint === 'bigint' ? (negint * neg1b - pos1b) : (negint * -1 - 1))
  uint.encodeUintValue(writer, token.type.majorEncoded, unsigned)
}

/**
 * @param {Token} token
 * @returns {number}
 */
encodeNegint.encodedSize = function encodedSize (token) {
  const negint = token.value
  const unsigned = (typeof negint === 'bigint' ? (negint * neg1b - pos1b) : (negint * -1 - 1))
  // handled by quickEncode, we shouldn't get here but it's included for completeness
  if (unsigned < uint.uintBoundaries[0]) {
    return 1
  }
  if (unsigned < uint.uintBoundaries[1]) {
    return 2
  }
  if (unsigned < uint.uintBoundaries[2]) {
    return 3
  }
  if (unsigned < uint.uintBoundaries[3]) {
    return 5
  }
  return 9
}

/**
 * @param {Token} tok1
 * @param {Token} tok2
 * @returns {number}
 */
encodeNegint.compareTokens = function compareTokens (tok1, tok2) {
  // opposite of the uint comparison since we store the uint version in bytes
  return tok1.value < tok2.value ? 1 : tok1.value > tok2.value ? -1 : 0
}
import { Token, Type } from './token.js'
import { assertEnoughData, decodeErrPrefix } from './common.js'
import * as uint from './0uint.js'
import { compare, fromString } from './byte-utils.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} prefix
 * @param {number} length
 * @returns {Token}
 */
function toToken (data, pos, prefix, length) {
  assertEnoughData(data, pos, prefix + length)
  const buf = data.slice(pos + prefix, pos + prefix + length)
  return new Token(Type.bytes, buf, prefix + length)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeBytesCompact (data, pos, minor, _options) {
  return toToken(data, pos, 1, minor)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer bytes lengths not supported`)
  }
  return toToken(data, pos, 9, l)
}

/**
 * `encodedBytes` allows for caching when we do a byte version of a string
 * for key sorting purposes
 * @param {Token} token
 * @returns {Uint8Array}
 */
function tokenBytes (token) {
  if (token.encodedBytes === undefined) {
    token.encodedBytes = Type.equals(token.type, Type.string) ? fromString(token.value) : token.value
  }
  // @ts-ignore c'mon
  return token.encodedBytes
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeBytes (writer, token) {
  const bytes = tokenBytes(token)
  uint.encodeUintValue(writer, token.type.majorEncoded, bytes.length)
  writer.push(bytes)
}

/**
 * @param {Token} token
 * @returns {number}
 */
encodeBytes.encodedSize = function encodedSize (token) {
  const bytes = tokenBytes(token)
  return uint.encodeUintValue.encodedSize(bytes.length) + bytes.length
}

/**
 * @param {Token} tok1
 * @param {Token} tok2
 * @returns {number}
 */
encodeBytes.compareTokens = function compareTokens (tok1, tok2) {
  return compareBytes(tokenBytes(tok1), tokenBytes(tok2))
}

/**
 * @param {Uint8Array} b1
 * @param {Uint8Array} b2
 * @returns {number}
 */
export function compareBytes (b1, b2) {
  return b1.length < b2.length ? -1 : b1.length > b2.length ? 1 : compare(b1, b2)
}
import { Token, Type } from './token.js'
import { assertEnoughData, decodeErrPrefix } from './common.js'
import * as uint from './0uint.js'
import { encodeBytes } from './2bytes.js'

const textDecoder = new TextDecoder()

// Threshold for ASCII fast-path vs TextDecoder. Short ASCII strings (common for
// map keys) are faster to decode with a simple loop than TextDecoder overhead.
const ASCII_THRESHOLD = 32

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * Decode UTF-8 bytes to string. For short ASCII strings (common case for map keys),
 * a simple loop is faster than TextDecoder.
 * @param {Uint8Array} bytes
 * @param {number} start
 * @param {number} end
 * @returns {string}
 */
function toStr (bytes, start, end) {
  const len = end - start
  if (len < ASCII_THRESHOLD) {
    let str = ''
    for (let i = start; i < end; i++) {
      const c = bytes[i]
      if (c & 0x80) { // non-ASCII, fall back to TextDecoder
        return textDecoder.decode(bytes.subarray(start, end))
      }
      str += String.fromCharCode(c)
    }
    return str
  }
  return textDecoder.decode(bytes.subarray(start, end))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} prefix
 * @param {number} length
 * @param {DecodeOptions} options
 * @returns {Token}
 */
function toToken (data, pos, prefix, length, options) {
  const totLength = prefix + length
  assertEnoughData(data, pos, totLength)
  const tok = new Token(Type.string, toStr(data, pos + prefix, pos + totLength), totLength)
  if (options.retainStringBytes === true) {
    tok.byteValue = data.slice(pos + prefix, pos + totLength)
  }
  return tok
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeStringCompact (data, pos, minor, options) {
  return toToken(data, pos, 1, minor, options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options), options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options), options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options), options)
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer string lengths not supported`)
  }
  return toToken(data, pos, 9, l, options)
}

export const encodeString = encodeBytes
import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import { decodeErrPrefix } from './common.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} prefix
 * @param {number} length
 * @returns {Token}
 */
function toToken (_data, _pos, prefix, length) {
  return new Token(Type.array, length, prefix)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeArrayCompact (data, pos, minor, _options) {
  return toToken(data, pos, 1, minor)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer array lengths not supported`)
  }
  return toToken(data, pos, 9, l)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArrayIndefinite (data, pos, _minor, options) {
  if (options.allowIndefinite === false) {
    throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)
  }
  return toToken(data, pos, 1, Infinity)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeArray (writer, token) {
  uint.encodeUintValue(writer, Type.array.majorEncoded, token.value)
}

// using an array as a map key, are you sure about this? we can only sort
// by map length here, it's up to the encoder to decide to look deeper
encodeArray.compareTokens = uint.encodeUint.compareTokens

/**
 * @param {Token} token
 * @returns {number}
 */
encodeArray.encodedSize = function encodedSize (token) {
  return uint.encodeUintValue.encodedSize(token.value)
}
import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import { decodeErrPrefix } from './common.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} prefix
 * @param {number} length
 * @returns {Token}
 */
function toToken (_data, _pos, prefix, length) {
  return new Token(Type.map, length, prefix)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeMapCompact (data, pos, minor, _options) {
  return toToken(data, pos, 1, minor)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer map lengths not supported`)
  }
  return toToken(data, pos, 9, l)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMapIndefinite (data, pos, _minor, options) {
  if (options.allowIndefinite === false) {
    throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)
  }
  return toToken(data, pos, 1, Infinity)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeMap (writer, token) {
  uint.encodeUintValue(writer, Type.map.majorEncoded, token.value)
}

// using a map as a map key, are you sure about this? we can only sort
// by map length here, it's up to the encoder to decide to look deeper
encodeMap.compareTokens = uint.encodeUint.compareTokens

/**
 * @param {Token} token
 * @returns {number}
 */
encodeMap.encodedSize = function encodedSize (token) {
  return uint.encodeUintValue.encodedSize(token.value)
}
import { Token, Type } from './token.js'
import * as uint from './0uint.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeTagCompact (_data, _pos, minor, _options) {
  return new Token(Type.tag, minor, 1)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag8 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint8(data, pos + 1, options), 2)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag16 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint16(data, pos + 1, options), 3)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag32 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint32(data, pos + 1, options), 5)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag64 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint64(data, pos + 1, options), 9)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeTag (writer, token) {
  uint.encodeUintValue(writer, Type.tag.majorEncoded, token.value)
}

encodeTag.compareTokens = uint.encodeUint.compareTokens

/**
 * @param {Token} token
 * @returns {number}
 */
encodeTag.encodedSize = function encodedSize (token) {
  return uint.encodeUintValue.encodedSize(token.value)
}
// TODO: shift some of the bytes logic to bytes-utils so we can use Buffer
// where possible

import { Token, Type } from './token.js'
import { decodeErrPrefix } from './common.js'
import { encodeUint } from './0uint.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 * @typedef {import('../interface.js').EncodeOptions} EncodeOptions
 */

export const MINOR_FALSE = 20
export const MINOR_TRUE = 21
export const MINOR_NULL = 22
export const MINOR_UNDEFINED = 23

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUndefined (_data, _pos, _minor, options) {
  if (options.allowUndefined === false) {
    throw new Error(`${decodeErrPrefix} undefined values are not supported`)
  } else if (options.coerceUndefinedToNull === true) {
    return new Token(Type.null, null, 1)
  }
  return new Token(Type.undefined, undefined, 1)
}

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBreak (_data, _pos, _minor, options) {
  if (options.allowIndefinite === false) {
    throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)
  }
  return new Token(Type.break, undefined, 1)
}

/**
 * @param {number} value
 * @param {number} bytes
 * @param {DecodeOptions} options
 * @returns {Token}
 */
function createToken (value, bytes, options) {
  if (options) {
    if (options.allowNaN === false && Number.isNaN(value)) {
      throw new Error(`${decodeErrPrefix} NaN values are not supported`)
    }
    if (options.allowInfinity === false && (value === Infinity || value === -Infinity)) {
      throw new Error(`${decodeErrPrefix} Infinity values are not supported`)
    }
  }
  return new Token(Type.float, value, bytes)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeFloat16 (data, pos, _minor, options) {
  return createToken(readFloat16(data, pos + 1), 3, options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeFloat32 (data, pos, _minor, options) {
  return createToken(readFloat32(data, pos + 1), 5, options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeFloat64 (data, pos, _minor, options) {
  return createToken(readFloat64(data, pos + 1), 9, options)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 * @param {EncodeOptions} options
 */
export function encodeFloat (writer, token, options) {
  const float = token.value

  if (float === false) {
    writer.push([Type.float.majorEncoded | MINOR_FALSE])
  } else if (float === true) {
    writer.push([Type.float.majorEncoded | MINOR_TRUE])
  } else if (float === null) {
    writer.push([Type.float.majorEncoded | MINOR_NULL])
  } else if (float === undefined) {
    writer.push([Type.float.majorEncoded | MINOR_UNDEFINED])
  } else {
    let decoded
    let success = false
    if (!options || options.float64 !== true) {
      encodeFloat16(float)
      decoded = readFloat16(ui8a, 1)
      if (float === decoded || Number.isNaN(float)) {
        ui8a[0] = 0xf9
        writer.push(ui8a.slice(0, 3))
        success = true
      } else {
        encodeFloat32(float)
        decoded = readFloat32(ui8a, 1)
        if (float === decoded) {
          ui8a[0] = 0xfa
          writer.push(ui8a.slice(0, 5))
          success = true
        }
      }
    }
    if (!success) {
      encodeFloat64(float)
      decoded = readFloat64(ui8a, 1)
      ui8a[0] = 0xfb
      writer.push(ui8a.slice(0, 9))
    }
  }
}

/**
 * @param {Token} token
 * @param {EncodeOptions} options
 * @returns {number}
 */
encodeFloat.encodedSize = function encodedSize (token, options) {
  const float = token.value

  if (float === false || float === true || float === null || float === undefined) {
    return 1
  }

  if (!options || options.float64 !== true) {
    encodeFloat16(float)
    let decoded = readFloat16(ui8a, 1)
    if (float === decoded || Number.isNaN(float)) {
      return 3
    }
    encodeFloat32(float)
    decoded = readFloat32(ui8a, 1)
    if (float === decoded) {
      return 5
    }
  }
  return 9
}

const buffer = new ArrayBuffer(9)
const dataView = new DataView(buffer, 1)
const ui8a = new Uint8Array(buffer, 0)

/**
 * @param {number} inp
 */
function encodeFloat16 (inp) {
  if (inp === Infinity) {
    dataView.setUint16(0, 0x7c00, false)
  } else if (inp === -Infinity) {
    dataView.setUint16(0, 0xfc00, false)
  } else if (Number.isNaN(inp)) {
    dataView.setUint16(0, 0x7e00, false)
  } else {
    dataView.setFloat32(0, inp)
    const valu32 = dataView.getUint32(0)
    const exponent = (valu32 & 0x7f800000) >> 23
    const mantissa = valu32 & 0x7fffff

    if (exponent === 0xff) {
      // too big, Infinity, but this should be hard (impossible?) to trigger
      dataView.setUint16(0, 0x7c00, false)
    } else if (exponent === 0x00) {
      // 0.0, -0.0 and subnormals, shouldn't be possible to get here because 0.0 should be counted as an int
      // Use valu32 for sign bit since bitwise ops on floats lose -0 sign
      dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | (mantissa >> 13), false)
    } else { // standard numbers
      // chunks of logic here borrowed from https://github.com/PJK/libcbor/blob/c78f437182533e3efa8d963ff4b945bb635c2284/src/cbor/encoding.c#L127
      const logicalExponent = exponent - 127
      // Now we know that 2^exponent <= 0 logically
      if (logicalExponent < -24) {
        /* No unambiguous representation exists, this float is not a half float
          and is too small to be represented using a half, round off to zero.
          Consistent with the reference implementation. */
        // should be difficult (impossible?) to get here in JS
        dataView.setUint16(0, 0)
      } else if (logicalExponent < -14) {
        /* Offset the remaining decimal places by shifting the significand, the
          value is lost. This is an implementation decision that works around the
          absence of standard half-float in the language. */
        dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | /* sign bit */ (1 << (24 + logicalExponent)), false)
      } else {
        dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | ((logicalExponent + 15) << 10) | (mantissa >> 13), false)
      }
    }
  }
}

/**
 * @param {Uint8Array} ui8a
 * @param {number} pos
 * @returns {number}
 */
function readFloat16 (ui8a, pos) {
  if (ui8a.length - pos < 2) {
    throw new Error(`${decodeErrPrefix} not enough data for float16`)
  }

  const half = (ui8a[pos] << 8) + ui8a[pos + 1]
  if (half === 0x7c00) {
    return Infinity
  }
  if (half === 0xfc00) {
    return -Infinity
  }
  if (half === 0x7e00) {
    return NaN
  }
  const exp = (half >> 10) & 0x1f
  const mant = half & 0x3ff
  let val
  if (exp === 0) {
    val = mant * (2 ** -24)
  } else if (exp !== 31) {
    val = (mant + 1024) * (2 ** (exp - 25))
  } else {
    // may not be possible to get here
    val = mant === 0 ? Infinity : NaN
  }
  return (half & 0x8000) ? -val : val
}

/**
 * @param {number} inp
 */
function encodeFloat32 (inp) {
  dataView.setFloat32(0, inp, false)
}

/**
 * @param {Uint8Array} ui8a
 * @param {number} pos
 * @returns {number}
 */
function readFloat32 (ui8a, pos) {
  if (ui8a.length - pos < 4) {
    throw new Error(`${decodeErrPrefix} not enough data for float32`)
  }
  const offset = (ui8a.byteOffset || 0) + pos
  return new DataView(ui8a.buffer, offset, 4).getFloat32(0, false)
}

/**
 * @param {number} inp
 */
function encodeFloat64 (inp) {
  dataView.setFloat64(0, inp, false)
}

/**
 * @param {Uint8Array} ui8a
 * @param {number} pos
 * @returns {number}
 */
function readFloat64 (ui8a, pos) {
  if (ui8a.length - pos < 8) {
    throw new Error(`${decodeErrPrefix} not enough data for float64`)
  }
  const offset = (ui8a.byteOffset || 0) + pos
  return new DataView(ui8a.buffer, offset, 8).getFloat64(0, false)
}

/**
 * @param {Token} _tok1
 * @param {Token} _tok2
 * @returns {number}
 */
encodeFloat.compareTokens = encodeUint.compareTokens
/*
encodeFloat.compareTokens = function compareTokens (_tok1, _tok2) {
  return _tok1
  throw new Error(`${encodeErrPrefix} cannot use floats as map keys`)
}
*/
/**
 * Bl is a list of byte chunks, similar to https://github.com/rvagg/bl but for
 * writing rather than reading.
 * A Bl object accepts set() operations for individual bytes and copyTo() for
 * inserting byte arrays. These write operations don't automatically increment
 * the internal cursor so its "length" won't be changed. Instead, increment()
 * must be called to extend its length to cover the inserted data.
 * The toBytes() call will convert all internal memory to a single Uint8Array of
 * the correct length, truncating any data that is stored but hasn't been
 * included by an increment().
 * get() can retrieve a single byte.
 * All operations (except toBytes()) take an "offset" argument that will perform
 * the write at the offset _from the current cursor_. For most operations this
 * will be `0` to write at the current cursor position but it can be ahead of
 * the current cursor. Negative offsets probably work but are untested.
 */

// TODO: ipjs doesn't support this, only for test files: https://github.com/mikeal/ipjs/blob/master/src/package/testFile.js#L39
import { alloc, concat, slice } from './byte-utils.js'

// the ts-ignores in this file are almost all for the `Uint8Array|number[]` duality that exists
// for perf reasons. Consider better approaches to this or removing it entirely, it is quite
// risky because of some assumptions about small chunks === number[] and everything else === Uint8Array.

const defaultChunkSize = 256

export class Bl {
  /**
   * @param {number} [chunkSize]
   */
  constructor (chunkSize = defaultChunkSize) {
    this.chunkSize = chunkSize
    /** @type {number} */
    this.cursor = 0
    /** @type {number} */
    this.maxCursor = -1
    /** @type {(Uint8Array|number[])[]} */
    this.chunks = []
    // keep the first chunk around if we can to save allocations for future encodes
    /** @type {Uint8Array|number[]|null} */
    this._initReuseChunk = null
  }

  reset () {
    this.cursor = 0
    this.maxCursor = -1
    if (this.chunks.length) {
      this.chunks = []
    }
    if (this._initReuseChunk !== null) {
      this.chunks.push(this._initReuseChunk)
      this.maxCursor = this._initReuseChunk.length - 1
    }
  }

  /**
   * @param {Uint8Array|number[]} bytes
   */
  push (bytes) {
    let topChunk = this.chunks[this.chunks.length - 1]
    const newMax = this.cursor + bytes.length
    if (newMax <= this.maxCursor + 1) {
      // we have at least one chunk and we can fit these bytes into that chunk
      const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1
      // @ts-ignore
      topChunk.set(bytes, chunkPos)
    } else {
      // can't fit it in
      if (topChunk) {
        // trip the last chunk to `cursor` if we need to
        const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1
        if (chunkPos < topChunk.length) {
          // @ts-ignore
          this.chunks[this.chunks.length - 1] = topChunk.subarray(0, chunkPos)
          this.maxCursor = this.cursor - 1
        }
      }
      if (bytes.length < 64 && bytes.length < this.chunkSize) {
        // make a new chunk and copy the new one into it
        topChunk = alloc(this.chunkSize)
        this.chunks.push(topChunk)
        this.maxCursor += topChunk.length
        if (this._initReuseChunk === null) {
          this._initReuseChunk = topChunk
        }
        // @ts-ignore
        topChunk.set(bytes, 0)
      } else {
        // push the new bytes in as its own chunk
        this.chunks.push(bytes)
        this.maxCursor += bytes.length
      }
    }
    this.cursor += bytes.length
  }

  /**
   * @param {boolean} [reset]
   * @returns {Uint8Array}
   */
  toBytes (reset = false) {
    let byts
    if (this.chunks.length === 1) {
      const chunk = this.chunks[0]
      if (reset && this.cursor > chunk.length / 2) {
        // @ts-ignore
        byts = this.cursor === chunk.length ? chunk : chunk.subarray(0, this.cursor)
        this._initReuseChunk = null
        this.chunks = []
      } else {
        // @ts-ignore
        byts = slice(chunk, 0, this.cursor)
      }
    } else {
      // @ts-ignore
      byts = concat(this.chunks, this.cursor)
    }
    if (reset) {
      this.reset()
    }
    return byts
  }
}

/**
 * U8Bl is a buffer list that writes directly to a user-provided Uint8Array.
 * It provides the same interface as Bl but writes to a fixed destination.
 */
export class U8Bl {
  /**
   * @param {Uint8Array} dest
   */
  constructor (dest) {
    this.dest = dest
    /** @type {number} */
    this.cursor = 0
    // chunks is for interface compatibility with Bl - encode.js checks chunks.length
    // as a sanity check for pre-calculated sizes. For U8Bl this is always [dest].
    /** @type {Uint8Array[]} */
    this.chunks = [dest]
  }

  reset () {
    this.cursor = 0
  }

  /**
   * @param {Uint8Array|number[]} bytes
   */
  push (bytes) {
    if (this.cursor + bytes.length > this.dest.length) {
      throw new Error('write out of bounds, destination buffer is too small')
    }
    this.dest.set(bytes, this.cursor)
    this.cursor += bytes.length
  }

  /**
   * @param {boolean} [reset]
   * @returns {Uint8Array}
   */
  toBytes (reset = false) {
    const byts = this.dest.subarray(0, this.cursor)
    if (reset) {
      this.reset()
    }
    return byts
  }
}
// Use Uint8Array directly in the browser, use Buffer in Node.js but don't
// speak its name directly to avoid bundlers pulling in the `Buffer` polyfill

// @ts-ignore
export const useBuffer = globalThis.process &&
  // @ts-ignore
  !globalThis.process.browser &&
  // @ts-ignore
  globalThis.Buffer &&
  // @ts-ignore
  typeof globalThis.Buffer.isBuffer === 'function'

const textEncoder = new TextEncoder()

/**
 * @param {Uint8Array} buf
 * @returns {boolean}
 */
function isBuffer (buf) {
  // @ts-ignore
  return useBuffer && globalThis.Buffer.isBuffer(buf)
}

/**
 * @param {Uint8Array|number[]} buf
 * @returns {Uint8Array}
 */
export function asU8A (buf) {
  if (!(buf instanceof Uint8Array)) {
    return Uint8Array.from(buf)
  }
  return isBuffer(buf) ? new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength) : buf
}

// Threshold for manual UTF-8 encoding vs native methods.
// Node.js Buffer.from: crossover ~24 chars
// Browser TextEncoder: crossover ~200 chars
const FROM_STRING_THRESHOLD_BUFFER = 24
const FROM_STRING_THRESHOLD_TEXTENCODER = 200

export const fromString = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {string} string
     */
    (string) => {
      return string.length >= FROM_STRING_THRESHOLD_BUFFER
        ? // eslint-disable-line operator-linebreak
      // @ts-ignore
        globalThis.Buffer.from(string)
        : utf8ToBytes(string)
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {string} string
     */
    (string) => {
      return string.length >= FROM_STRING_THRESHOLD_TEXTENCODER ? textEncoder.encode(string) : utf8ToBytes(string)
    }

/**
 * Buffer variant not fast enough for what we need
 * @param {number[]} arr
 * @returns {Uint8Array}
 */
export const fromArray = (arr) => {
  return Uint8Array.from(arr)
}

export const slice = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} bytes
     * @param {number} start
     * @param {number} end
     */
    // Buffer.slice() returns a view, not a copy, so we need special handling
    (bytes, start, end) => {
      if (isBuffer(bytes)) {
        return new Uint8Array(bytes.subarray(start, end))
      }
      return bytes.slice(start, end)
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} bytes
     * @param {number} start
     * @param {number} end
     */
    (bytes, start, end) => {
      return bytes.slice(start, end)
    }

export const concat = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array[]} chunks
     * @param {number} length
     * @returns {Uint8Array}
     */
    (chunks, length) => {
      // might get a stray plain Array here
      chunks = chunks.map((c) => c instanceof Uint8Array
        ? c
        : // eslint-disable-line operator-linebreak
        // @ts-ignore
        globalThis.Buffer.from(c))
      // @ts-ignore
      return asU8A(globalThis.Buffer.concat(chunks, length))
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array[]} chunks
     * @param {number} length
     * @returns {Uint8Array}
     */
    (chunks, length) => {
      const out = new Uint8Array(length)
      let off = 0
      for (let b of chunks) {
        if (off + b.length > out.length) {
          // final chunk that's bigger than we need
          b = b.subarray(0, out.length - off)
        }
        out.set(b, off)
        off += b.length
      }
      return out
    }

export const alloc = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {number} size
     * @returns {Uint8Array}
     */
    (size) => {
      // we always write over the contents we expose so this should be safe
      // @ts-ignore
      return globalThis.Buffer.allocUnsafe(size)
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {number} size
     * @returns {Uint8Array}
     */
    (size) => {
      return new Uint8Array(size)
    }

export const toHex = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} d
     * @returns {string}
     */
    (d) => {
      if (typeof d === 'string') {
        return d
      }
      // @ts-ignore
      return globalThis.Buffer.from(toBytes(d)).toString('hex')
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} d
     * @returns {string}
     */
    (d) => {
      if (typeof d === 'string') {
        return d
      }
      // @ts-ignore not smart enough to figure this out
      return Array.prototype.reduce.call(toBytes(d), (p, c) => `${p}${c.toString(16).padStart(2, '0')}`, '')
    }

export const fromHex = useBuffer
  ? // eslint-disable-line operator-linebreak
  /**
   * @param {string|Uint8Array} hex
   * @returns {Uint8Array}
   */
    (hex) => {
      if (hex instanceof Uint8Array) {
        return hex
      }
      // @ts-ignore
      return globalThis.Buffer.from(hex, 'hex')
    }
  : // eslint-disable-line operator-linebreak
  /**
   * @param {string|Uint8Array} hex
   * @returns {Uint8Array}
   */
    (hex) => {
      if (hex instanceof Uint8Array) {
        return hex
      }
      if (!hex.length) {
        return new Uint8Array(0)
      }
      return new Uint8Array(hex.split('')
        .map((/** @type {string} */ c, /** @type {number} */ i, /** @type {string[]} */ d) => i % 2 === 0 ? `0x${c}${d[i + 1]}` : '')
        .filter(Boolean)
        .map((/** @type {string} */ e) => parseInt(e, 16)))
    }

/**
 * @param {Uint8Array|ArrayBuffer|ArrayBufferView} obj
 * @returns {Uint8Array}
 */
function toBytes (obj) {
  if (obj instanceof Uint8Array && obj.constructor.name === 'Uint8Array') {
    return obj
  }
  if (obj instanceof ArrayBuffer) {
    return new Uint8Array(obj)
  }
  if (ArrayBuffer.isView(obj)) {
    return new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength)
  }
  throw new Error('Unknown type, must be binary type')
}

/**
 * @param {Uint8Array} b1
 * @param {Uint8Array} b2
 * @returns {number}
 */
export function compare (b1, b2) {
  if (isBuffer(b1) && isBuffer(b2)) {
    // probably not possible to get here in the current API
    // @ts-ignore Buffer
    return b1.compare(b2)
  }
  for (let i = 0; i < b1.length; i++) {
    if (b1[i] === b2[i]) {
      continue
    }
    return b1[i] < b2[i] ? -1 : 1
  }
  return 0
}

// The below code is taken from https://github.com/google/closure-library/blob/8598d87242af59aac233270742c8984e2b2bdbe0/closure/goog/crypt/crypt.js#L117-L143
// Licensed Apache-2.0.

/**
 * @param {string} str
 * @returns {number[]}
 */
function utf8ToBytes (str) {
  const out = []
  let p = 0
  for (let i = 0; i < str.length; i++) {
    let c = str.charCodeAt(i)
    if (c < 128) {
      out[p++] = c
    } else if (c < 2048) {
      out[p++] = (c >> 6) | 192
      out[p++] = (c & 63) | 128
    } else if (
      ((c & 0xFC00) === 0xD800) && (i + 1) < str.length &&
      ((str.charCodeAt(i + 1) & 0xFC00) === 0xDC00)) {
      // Surrogate Pair
      c = 0x10000 + ((c & 0x03FF) << 10) + (str.charCodeAt(++i) & 0x03FF)
      out[p++] = (c >> 18) | 240
      out[p++] = ((c >> 12) & 63) | 128
      out[p++] = ((c >> 6) & 63) | 128
      out[p++] = (c & 63) | 128
    } else {
      if ((c >= 0xD800) && (c <= 0xDFFF)) {
        c = 0xFFFD // Unpaired Surrogate
      }
      out[p++] = (c >> 12) | 224
      out[p++] = ((c >> 6) & 63) | 128
      out[p++] = (c & 63) | 128
    }
  }
  return out
}

// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
const MAX_ARGUMENTS_LENGTH = 0x1000

/**
 * @param {number[]} codePoints
 * @returns {string}
 */
export function decodeCodePointsArray (codePoints) {
  const len = codePoints.length
  if (len <= MAX_ARGUMENTS_LENGTH) {
    return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  }
  // Decode in chunks to avoid "call stack size exceeded".
  let res = ''
  let i = 0
  while (i < len) {
    res += String.fromCharCode.apply(
      String,
      codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
    )
  }
  return res
}
const decodeErrPrefix = 'CBOR decode error:'
const encodeErrPrefix = 'CBOR encode error:'

const uintMinorPrefixBytes = []
uintMinorPrefixBytes[23] = 1
uintMinorPrefixBytes[24] = 2
uintMinorPrefixBytes[25] = 3
uintMinorPrefixBytes[26] = 5
uintMinorPrefixBytes[27] = 9

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} need
 */
function assertEnoughData (data, pos, need) {
  if (data.length - pos < need) {
    throw new Error(`${decodeErrPrefix} not enough data for type`)
  }
}

export {
  decodeErrPrefix,
  encodeErrPrefix,
  uintMinorPrefixBytes,
  assertEnoughData
}
import { decodeErrPrefix } from './common.js'
import { Type } from './token.js'
import { jump, quick } from './jump.js'
import { asU8A } from './byte-utils.js'

/**
 * @typedef {import('./token.js').Token} Token
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 * @typedef {import('../interface.js').DecodeTokenizer} DecodeTokenizer
 * @typedef {import('../interface.js').TagDecodeControl} TagDecodeControl
 */

const defaultDecodeOptions = {
  strict: false,
  allowIndefinite: true,
  allowUndefined: true,
  allowBigInt: true
}

/**
 * @implements {DecodeTokenizer}
 */
class Tokeniser {
  /**
   * @param {Uint8Array} data
   * @param {DecodeOptions} options
   */
  constructor (data, options = {}) {
    this._pos = 0
    this.data = data
    this.options = options
  }

  pos () {
    return this._pos
  }

  done () {
    return this._pos >= this.data.length
  }

  next () {
    const byt = this.data[this._pos]
    let token = quick[byt]
    if (token === undefined) {
      const decoder = jump[byt]
      // if we're here then there's something wrong with our jump or quick lists!
      if (!decoder) {
        throw new Error(`${decodeErrPrefix} no decoder for major type ${byt >>> 5} (byte 0x${byt.toString(16).padStart(2, '0')})`)
      }
      const minor = byt & 31
      token = decoder(this.data, this._pos, minor, this.options)
    }
    // @ts-ignore we get to assume encodedLength is set (crossing fingers slightly)
    this._pos += token.encodedLength
    return token
  }
}

const DONE = Symbol.for('DONE')
const BREAK = Symbol.for('BREAK')

/**
 * @param {Token} token
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {any|BREAK|DONE}
 */
function tokenToArray (token, tokeniser, options) {
  const arr = []
  for (let i = 0; i < token.value; i++) {
    const value = tokensToObject(tokeniser, options)
    if (value === BREAK) {
      if (token.value === Infinity) {
        // normal end to indefinite length array
        break
      }
      throw new Error(`${decodeErrPrefix} got unexpected break to lengthed array`)
    }
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} found array but not enough entries (got ${i}, expected ${token.value})`)
    }
    arr[i] = value
  }
  return arr
}

/**
 * @param {Token} token
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {any|BREAK|DONE}
 */
function tokenToMap (token, tokeniser, options) {
  const useMaps = options.useMaps === true
  const rejectDuplicateMapKeys = options.rejectDuplicateMapKeys === true
  const obj = useMaps ? undefined : {}
  const m = useMaps ? new Map() : undefined
  for (let i = 0; i < token.value; i++) {
    const key = tokensToObject(tokeniser, options)
    if (key === BREAK) {
      if (token.value === Infinity) {
        // normal end to indefinite length map
        break
      }
      throw new Error(`${decodeErrPrefix} got unexpected break to lengthed map`)
    }
    if (key === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no key], expected ${token.value})`)
    }
    if (!useMaps && typeof key !== 'string') {
      throw new Error(`${decodeErrPrefix} non-string keys not supported (got ${typeof key})`)
    }
    if (rejectDuplicateMapKeys) {
      // @ts-ignore
      if ((useMaps && m.has(key)) || (!useMaps && Object.hasOwn(obj, key))) {
        throw new Error(`${decodeErrPrefix} found repeat map key "${key}"`)
      }
    }
    const value = tokensToObject(tokeniser, options)
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no value], expected ${token.value})`)
    }
    if (useMaps) {
      // @ts-ignore TODO reconsider this .. maybe needs to be strict about key types
      m.set(key, value)
    } else {
      // @ts-ignore TODO reconsider this .. maybe needs to be strict about key types
      obj[key] = value
    }
  }
  // @ts-ignore c'mon man
  return useMaps ? m : obj
}

/**
 * Generator that yields [key, value] entries from a CBOR map token.
 * Used by tag decoders that need to preserve key types (e.g., Tag 259 Map).
 * @param {Token} token - The map token
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {Generator<[any, any], void, unknown>}
 */
function * tokenToMapEntries (token, tokeniser, options) {
  for (let i = 0; i < token.value; i++) {
    const key = tokensToObject(tokeniser, options)
    if (key === BREAK) {
      if (token.value === Infinity) {
        // normal end to indefinite length map
        break
      }
      throw new Error(`${decodeErrPrefix} got unexpected break to lengthed map`)
    }
    if (key === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no key], expected ${token.value})`)
    }
    const value = tokensToObject(tokeniser, options)
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no value], expected ${token.value})`)
    }
    yield [key, value]
  }
}

/**
 * Creates a TagDecodeControl object for tag decoders.
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {TagDecodeControl}
 */
function createTagDecodeControl (tokeniser, options) {
  let called = false

  /**
   * @type {TagDecodeControl}
   */
  const decode = function () {
    if (called) {
      throw new Error(`${decodeErrPrefix} tag decode() may only be called once`)
    }
    called = true
    const value = tokensToObject(tokeniser, options)
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} tag content missing`)
    }
    if (value === BREAK) {
      throw new Error(`${decodeErrPrefix} got unexpected break in tag content`)
    }
    return value
  }

  decode.entries = function () {
    if (called) {
      throw new Error(`${decodeErrPrefix} tag decode() may only be called once`)
    }
    called = true

    // Get the next token and ensure it's a map
    const token = tokeniser.next()
    if (!Type.equals(token.type, Type.map)) {
      throw new Error(`${decodeErrPrefix} entries() requires map content, got ${token.type.name}`)
    }

    // Collect all entries into an array (ensures full content consumption)
    const entries = []
    for (const entry of tokenToMapEntries(token, tokeniser, options)) {
      entries.push(entry)
    }
    return entries
  }

  // For internal tracking
  Object.defineProperty(decode, '_called', {
    get () { return called },
    enumerable: false
  })

  return decode
}

/**
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {any|BREAK|DONE}
 */
function tokensToObject (tokeniser, options) {
  // should we support array as an argument?
  // check for tokenIter[Symbol.iterator] and replace tokenIter with what that returns?
  if (tokeniser.done()) {
    return DONE
  }

  const token = tokeniser.next()

  if (Type.equals(token.type, Type.break)) {
    return BREAK
  }

  if (token.type.terminal) {
    return token.value
  }

  if (Type.equals(token.type, Type.array)) {
    return tokenToArray(token, tokeniser, options)
  }

  if (Type.equals(token.type, Type.map)) {
    return tokenToMap(token, tokeniser, options)
  }

  if (Type.equals(token.type, Type.tag)) {
    if (options.tags && typeof options.tags[token.value] === 'function') {
      const decodeControl = createTagDecodeControl(tokeniser, options)
      const result = options.tags[token.value](decodeControl)
      if (!decodeControl._called) {
        throw new Error(`${decodeErrPrefix} tag decoder must call decode() or entries()`)
      }
      return result
    }
    throw new Error(`${decodeErrPrefix} tag not supported (${token.value})`)
  }
  throw new Error('unsupported')
}

/**
 * @param {Uint8Array} data
 * @param {DecodeOptions} [options]
 * @returns {[any, Uint8Array]}
 */
function decodeFirst (data, options) {
  if (!(data instanceof Uint8Array)) {
    throw new Error(`${decodeErrPrefix} data to decode must be a Uint8Array`)
  }
  options = Object.assign({}, defaultDecodeOptions, options)
  // Convert Buffer to plain Uint8Array for faster slicing in decode path
  const u8aData = asU8A(data)
  const tokeniser = options.tokenizer || new Tokeniser(u8aData, options)
  const decoded = tokensToObject(tokeniser, options)
  if (decoded === DONE) {
    throw new Error(`${decodeErrPrefix} did not find any content to decode`)
  }
  if (decoded === BREAK) {
    throw new Error(`${decodeErrPrefix} got unexpected break`)
  }
  return [decoded, data.subarray(tokeniser.pos())]
}

/**
 * @param {Uint8Array} data
 * @param {DecodeOptions} [options]
 * @returns {any}
 */
function decode (data, options) {
  const [decoded, remainder] = decodeFirst(data, options)
  if (remainder.length > 0) {
    throw new Error(`${decodeErrPrefix} too many terminals, data makes no sense`)
  }
  return decoded
}

export { Tokeniser, tokensToObject, decode, decodeFirst }
import { is } from './is.js'
import { Token, Type } from './token.js'
import { Bl, U8Bl } from './bl.js'
import { encodeErrPrefix } from './common.js'
import { quickEncodeToken } from './jump.js'
import { asU8A, compare, fromString } from './byte-utils.js'

import { encodeUint, encodeUintValue } from './0uint.js'
import { encodeNegint } from './1negint.js'
import { encodeBytes } from './2bytes.js'
import { encodeString } from './3string.js'
import { encodeArray } from './4array.js'
import { encodeMap } from './5map.js'
import { encodeTag } from './6tag.js'
import { encodeFloat, MINOR_FALSE, MINOR_TRUE, MINOR_NULL, MINOR_UNDEFINED } from './7float.js'

/**
 * @typedef {import('../interface.js').EncodeOptions} EncodeOptions
 * @typedef {import('../interface.js').OptionalTypeEncoder} OptionalTypeEncoder
 * @typedef {import('../interface.js').Reference} Reference
 * @typedef {import('../interface.js').StrictTypeEncoder} StrictTypeEncoder
 * @typedef {import('../interface.js').TokenTypeEncoder} TokenTypeEncoder
 * @typedef {import('../interface.js').TokenOrNestedTokens} TokenOrNestedTokens
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 */

/** @type {EncodeOptions} */
const defaultEncodeOptions = {
  float64: false,
  mapSorter,
  quickEncodeToken
}

/** @type {EncodeOptions} */
export const rfc8949EncodeOptions = Object.freeze({
  mapSorter: rfc8949MapSorter,
  quickEncodeToken
})

/** @returns {TokenTypeEncoder[]} */
export function makeCborEncoders () {
  const encoders = []
  encoders[Type.uint.major] = encodeUint
  encoders[Type.negint.major] = encodeNegint
  encoders[Type.bytes.major] = encodeBytes
  encoders[Type.string.major] = encodeString
  encoders[Type.array.major] = encodeArray
  encoders[Type.map.major] = encodeMap
  encoders[Type.tag.major] = encodeTag
  encoders[Type.float.major] = encodeFloat
  return encoders
}

const cborEncoders = makeCborEncoders()

const defaultWriter = new Bl()

/** @implements {Reference} */
class Ref {
  /**
   * @param {object|any[]} obj
   * @param {Reference|undefined} parent
   */
  constructor (obj, parent) {
    this.obj = obj
    this.parent = parent
  }

  /**
   * @param {object|any[]} obj
   * @returns {boolean}
   */
  includes (obj) {
    /** @type {Reference|undefined} */
    let p = this
    do {
      if (p.obj === obj) {
        return true
      }
    } while (p = p.parent) // eslint-disable-line
    return false
  }

  /**
   * @param {Reference|undefined} stack
   * @param {object|any[]} obj
   * @returns {Reference}
   */
  static createCheck (stack, obj) {
    if (stack && stack.includes(obj)) {
      throw new Error(`${encodeErrPrefix} object contains circular references`)
    }
    return new Ref(obj, stack)
  }
}

const simpleTokens = {
  null: new Token(Type.null, null),
  undefined: new Token(Type.undefined, undefined),
  true: new Token(Type.true, true),
  false: new Token(Type.false, false),
  emptyArray: new Token(Type.array, 0),
  emptyMap: new Token(Type.map, 0)
}

/** @type {{[typeName: string]: StrictTypeEncoder}} */
const typeEncoders = {
  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  number (obj, _typ, _options, _refStack) {
    if (!Number.isInteger(obj) || !Number.isSafeInteger(obj)) {
      return new Token(Type.float, obj)
    } else if (obj >= 0) {
      return new Token(Type.uint, obj)
    } else {
      return new Token(Type.negint, obj)
    }
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  bigint (obj, _typ, _options, _refStack) {
    if (obj >= BigInt(0)) {
      return new Token(Type.uint, obj)
    } else {
      return new Token(Type.negint, obj)
    }
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  Uint8Array (obj, _typ, _options, _refStack) {
    return new Token(Type.bytes, obj)
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  string (obj, _typ, _options, _refStack) {
    return new Token(Type.string, obj)
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  boolean (obj, _typ, _options, _refStack) {
    return obj ? simpleTokens.true : simpleTokens.false
  },

  /**
   * @param {any} _obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  null (_obj, _typ, _options, _refStack) {
    return simpleTokens.null
  },

  /**
   * @param {any} _obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  undefined (_obj, _typ, _options, _refStack) {
    return simpleTokens.undefined
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  ArrayBuffer (obj, _typ, _options, _refStack) {
    return new Token(Type.bytes, new Uint8Array(obj))
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  DataView (obj, _typ, _options, _refStack) {
    return new Token(Type.bytes, new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength))
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} options
   * @param {Reference} [refStack]
   * @returns {TokenOrNestedTokens}
   */
  Array (obj, _typ, options, refStack) {
    if (!obj.length) {
      if (options.addBreakTokens === true) {
        return [simpleTokens.emptyArray, new Token(Type.break)]
      }
      return simpleTokens.emptyArray
    }
    refStack = Ref.createCheck(refStack, obj)
    const entries = []
    let i = 0
    for (const e of obj) {
      entries[i++] = objectToTokens(e, options, refStack)
    }
    if (options.addBreakTokens) {
      return [new Token(Type.array, obj.length), entries, new Token(Type.break)]
    }
    return [new Token(Type.array, obj.length), entries]
  },

  /**
   * @param {any} obj
   * @param {string} typ
   * @param {EncodeOptions} options
   * @param {Reference} [refStack]
   * @returns {TokenOrNestedTokens}
   */
  Object (obj, typ, options, refStack) {
    // could be an Object or a Map
    const isMap = typ !== 'Object'
    // it's slightly quicker to use Object.keys() than Object.entries()
    const keys = isMap ? obj.keys() : Object.keys(obj)
    const maxLength = isMap ? obj.size : keys.length

    /** @type {undefined | [TokenOrNestedTokens, TokenOrNestedTokens][]} */
    let entries

    if (maxLength) {
      // Pre-allocate the array with the expected size
      entries = new Array(maxLength)
      refStack = Ref.createCheck(refStack, obj)
      const skipUndefined = !isMap && options.ignoreUndefinedProperties

      let i = 0
      for (const key of keys) {
        const value = isMap ? obj.get(key) : obj[key]
        if (skipUndefined && value === undefined) {
          continue
        }
        entries[i++] = [
          objectToTokens(key, options, refStack),
          objectToTokens(value, options, refStack)
        ]
      }

      // Truncate only if properties were skipped
      if (i < maxLength) {
        entries.length = i
      }
    }

    if (!entries?.length) {
      if (options.addBreakTokens === true) {
        return [simpleTokens.emptyMap, new Token(Type.break)]
      }
      return simpleTokens.emptyMap
    }

    sortMapEntries(entries, options)
    if (options.addBreakTokens) {
      return [new Token(Type.map, entries.length), entries, new Token(Type.break)]
    }
    return [new Token(Type.map, entries.length), entries]
  },

  /**
   * Encode a `Tagged` wrapper as a CBOR tag header followed by the encoded
   * form of the wrapped value. The value is recursively tokenised through
   * `objectToTokens()` so any registered `typeEncoders` apply to it.
   *
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} options
   * @param {Reference} [refStack]
   * @returns {TokenOrNestedTokens}
   */
  Tagged (obj, _typ, options, refStack) {
    return [
      new Token(Type.tag, obj.tag),
      objectToTokens(obj.value, options, refStack)
    ]
  }
}

typeEncoders.Map = typeEncoders.Object
typeEncoders.Buffer = typeEncoders.Uint8Array
for (const typ of 'Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64'.split(' ')) {
  typeEncoders[`${typ}Array`] = typeEncoders.DataView
}

/**
 * @param {any} obj
 * @param {EncodeOptions} [options]
 * @param {Reference} [refStack]
 * @returns {TokenOrNestedTokens}
 */
function objectToTokens (obj, options = {}, refStack) {
  const typ = is(obj)
  const customTypeEncoder = (options && options.typeEncoders && /** @type {OptionalTypeEncoder} */ options.typeEncoders[typ]) || typeEncoders[typ]
  if (typeof customTypeEncoder === 'function') {
    const tokens = customTypeEncoder(obj, typ, options, refStack)
    if (tokens != null) {
      return tokens
    }
  }
  const typeEncoder = typeEncoders[typ]
  if (!typeEncoder) {
    throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`)
  }
  return typeEncoder(obj, typ, options, refStack)
}

/*
CBOR key sorting is a mess.

The canonicalisation recommendation from https://tools.ietf.org/html/rfc7049#section-3.9
includes the wording:

> The keys in every map must be sorted lowest value to highest.
> Sorting is performed on the bytes of the representation of the key
> data items without paying attention to the 3/5 bit splitting for
> major types.
> ...
>  *  If two keys have different lengths, the shorter one sorts
      earlier;
>  *  If two keys have the same length, the one with the lower value
      in (byte-wise) lexical order sorts earlier.

1. It is not clear what "bytes of the representation of the key" means: is it
   the CBOR representation, or the binary representation of the object itself?
   Consider the int and uint difference here.
2. It is not clear what "without paying attention to" means: do we include it
   and compare on that? Or do we omit the special prefix byte, (mostly) treating
   the key in its plain binary representation form.

The FIDO 2.0: Client To Authenticator Protocol spec takes the original CBOR
wording and clarifies it according to their understanding.
https://fidoalliance.org/specs/fido-v2.0-rd-20170927/fido-client-to-authenticator-protocol-v2.0-rd-20170927.html#message-encoding

> The keys in every map must be sorted lowest value to highest. Sorting is
> performed on the bytes of the representation of the key data items without
> paying attention to the 3/5 bit splitting for major types. The sorting rules
> are:
>  * If the major types are different, the one with the lower value in numerical
>    order sorts earlier.
>  * If two keys have different lengths, the shorter one sorts earlier;
>  * If two keys have the same length, the one with the lower value in
>    (byte-wise) lexical order sorts earlier.

Some other implementations, such as borc, do a full encode then do a
length-first, byte-wise-second comparison:
https://github.com/dignifiedquire/borc/blob/b6bae8b0bcde7c3976b0f0f0957208095c392a36/src/encoder.js#L358
https://github.com/dignifiedquire/borc/blob/b6bae8b0bcde7c3976b0f0f0957208095c392a36/src/utils.js#L143-L151

This has the benefit of being able to easily handle arbitrary keys, including
complex types (maps and arrays).

We'll opt for the FIDO approach, since it affords some efficies since we don't
need a full encode of each key to determine order and can defer to the types
to determine how to most efficiently order their values (i.e. int and uint
ordering can be done on the numbers, no need for byte-wise, for example).

Recommendation: stick to single key types or you'll get into trouble, and prefer
string keys because it's much simpler that way.
*/

/**
 * @param {TokenOrNestedTokens[]} entries
 * @param {EncodeOptions} options
 */
function sortMapEntries (entries, options) {
  if (options.mapSorter) {
    entries.sort(options.mapSorter)
  }
}

/**
 * @param {(Token|Token[])[]} e1
 * @param {(Token|Token[])[]} e2
 * @returns {number}
 */
function mapSorter (e1, e2) {
  // the key position ([0]) could have a single token or an array
  // almost always it'll be a single token but complex key might get involved
  const keyToken1 = Array.isArray(e1[0]) ? e1[0][0] : e1[0]
  const keyToken2 = Array.isArray(e2[0]) ? e2[0][0] : e2[0]

  // different key types
  if (keyToken1.type !== keyToken2.type) {
    return keyToken1.type.compare(keyToken2.type)
  }

  const major = keyToken1.type.major
  // TODO: handle case where cmp === 0 but there are more keyToken e. complex type)
  const tcmp = cborEncoders[major].compareTokens(keyToken1, keyToken2)
  if (tcmp === 0) {
    // duplicate key or complex type where the first token matched,
    // i.e. a map or array and we're only comparing the opening token
    console.warn('WARNING: complex key types used, CBOR key sorting guarantees are gone')
  }
  return tcmp
}

/**
 * @typedef {Token & { _keyBytes?: Uint8Array }} TokenEx
 *
 * @param {(Token|Token[])[]} e1
 * @param {(Token|Token[])[]} e2
 * @returns {number}
 */
function rfc8949MapSorter (e1, e2) {
  if (e1[0] instanceof Token && e2[0] instanceof Token) {
    const t1 = /** @type {TokenEx} */ (e1[0])
    const t2 = /** @type {TokenEx} */ (e2[0])

    if (!t1._keyBytes) {
      t1._keyBytes = encodeRfc8949(t1.value)
    }

    if (!t2._keyBytes) {
      t2._keyBytes = encodeRfc8949(t2.value)
    }

    return compare(t1._keyBytes, t2._keyBytes)
  }

  throw new Error('rfc8949MapSorter: complex key types are not supported yet')
}

/**
 * @param {any} data
 * @returns {Uint8Array}
 */
function encodeRfc8949 (data) {
  return encodeCustom(data, cborEncoders, rfc8949EncodeOptions)
}

/**
 * @param {ByteWriter} writer
 * @param {TokenOrNestedTokens} tokens
 * @param {TokenTypeEncoder[]} encoders
 * @param {EncodeOptions} options
 */
function tokensToEncoded (writer, tokens, encoders, options) {
  if (Array.isArray(tokens)) {
    for (const token of tokens) {
      tokensToEncoded(writer, token, encoders, options)
    }
  } else {
    encoders[tokens.type.major](writer, tokens, options)
  }
}

// CBOR major type prefixes, cached from Type for hot path performance
const MAJOR_UINT = Type.uint.majorEncoded
const MAJOR_NEGINT = Type.negint.majorEncoded
const MAJOR_BYTES = Type.bytes.majorEncoded
const MAJOR_STRING = Type.string.majorEncoded
const MAJOR_ARRAY = Type.array.majorEncoded

// Simple value bytes (CBOR major type 7 + minor value)
const SIMPLE_FALSE = Type.float.majorEncoded | MINOR_FALSE
const SIMPLE_TRUE = Type.float.majorEncoded | MINOR_TRUE
const SIMPLE_NULL = Type.float.majorEncoded | MINOR_NULL
const SIMPLE_UNDEFINED = Type.float.majorEncoded | MINOR_UNDEFINED

const neg1b = BigInt(-1)
const pos1b = BigInt(1)

/**
 * Check if direct encoding can be used for the given options.
 * Direct encoding bypasses token creation for most values.
 * @param {EncodeOptions} options
 * @returns {boolean}
 */
function canDirectEncode (options) {
  // Cannot use direct encode with addBreakTokens (needs special break token handling).
  // Direct encode checks typeEncoders per-value, falling back to tokens as needed.
  // Maps fall back to token-based encoding for efficient key sorting.
  return options.addBreakTokens !== true
}

/**
 * Direct encode a value to the writer, bypassing token creation for most types.
 * Falls back to token-based encoding for custom type encoders.
 * @param {ByteWriter} writer
 * @param {any} data
 * @param {EncodeOptions} options
 * @param {Reference|undefined} refStack
 */
function directEncode (writer, data, options, refStack) {
  const typ = is(data)

  // Check for custom encoder for THIS specific type
  const customEncoder = options.typeEncoders && options.typeEncoders[typ]
  if (customEncoder) {
    const tokens = customEncoder(data, typ, options, refStack)
    if (tokens != null) {
      // Custom encoder returned tokens, serialize immediately
      tokensToEncoded(writer, tokens, cborEncoders, options)
      return
    }
    // Custom encoder returned null, fall through to default handling
  }

  // Direct encode based on type
  switch (typ) {
    case 'null':
      writer.push([SIMPLE_NULL])
      return

    case 'undefined':
      writer.push([SIMPLE_UNDEFINED])
      return

    case 'boolean':
      writer.push([data ? SIMPLE_TRUE : SIMPLE_FALSE])
      return

    case 'number':
      if (!Number.isInteger(data) || !Number.isSafeInteger(data)) {
        // Float, use token encoder for complex float encoding
        encodeFloat(writer, new Token(Type.float, data), options)
      } else if (data >= 0) {
        encodeUintValue(writer, MAJOR_UINT, data)
      } else {
        // Negative integer
        encodeUintValue(writer, MAJOR_NEGINT, data * -1 - 1)
      }
      return

    case 'bigint':
      if (data >= BigInt(0)) {
        encodeUintValue(writer, MAJOR_UINT, data)
      } else {
        encodeUintValue(writer, MAJOR_NEGINT, data * neg1b - pos1b)
      }
      return

    case 'string': {
      const bytes = fromString(data)
      encodeUintValue(writer, MAJOR_STRING, bytes.length)
      writer.push(bytes)
      return
    }

    case 'Uint8Array':
      encodeUintValue(writer, MAJOR_BYTES, data.length)
      writer.push(data)
      return

    case 'Array':
      if (!data.length) {
        writer.push([MAJOR_ARRAY]) // Empty array: 0x80
        return
      }
      refStack = Ref.createCheck(refStack, data)
      encodeUintValue(writer, MAJOR_ARRAY, data.length)
      for (const elem of data) {
        directEncode(writer, elem, options, refStack)
      }
      return

    case 'Object':
    case 'Map':
      // Maps require key sorting, use token-based encoding for efficiency
      // (pre-encoding all keys for sorting is expensive)
      {
        const tokens = typeEncoders.Object(data, typ, options, refStack)
        tokensToEncoded(writer, tokens, cborEncoders, options)
      }
      return

    default:
    // Fall back to token-based encoding for other types (DataView, TypedArrays, etc.)
    {
      const typeEncoder = typeEncoders[typ]
      if (!typeEncoder) {
        throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`)
      }
      const tokens = typeEncoder(data, typ, options, refStack)
      tokensToEncoded(writer, tokens, cborEncoders, options)
    }
  }
}

/**
 * @param {any} data
 * @param {TokenTypeEncoder[]} encoders
 * @param {EncodeOptions} options
 * @param {Uint8Array} [destination]
 * @returns {Uint8Array}
 */
function encodeCustom (data, encoders, options, destination) {
  // arg ordering is different to encodeInto for backward compatibility
  const hasDest = destination instanceof Uint8Array
  let writeTo = hasDest ? new U8Bl(destination) : defaultWriter

  const tokens = objectToTokens(data, options)
  if (!Array.isArray(tokens) && options.quickEncodeToken) {
    const quickBytes = options.quickEncodeToken(tokens)
    if (quickBytes) {
      if (hasDest) {
        // Copy quick bytes into destination buffer
        writeTo.push(quickBytes)
        return writeTo.toBytes()
      }
      return quickBytes
    }
    const encoder = encoders[tokens.type.major]
    if (encoder.encodedSize) {
      const size = encoder.encodedSize(tokens, options)
      if (!hasDest) {
        writeTo = new Bl(size)
      }
      encoder(writeTo, tokens, options)
      // this would be a problem with encodedSize() functions
      if (writeTo.chunks.length !== 1) {
        throw new Error(`Unexpected error: pre-calculated length for ${tokens} was wrong`)
      }
      return hasDest ? writeTo.toBytes() : asU8A(writeTo.chunks[0])
    }
  }
  writeTo.reset()
  tokensToEncoded(writeTo, tokens, encoders, options)
  return writeTo.toBytes(true)
}

/**
 * @param {any} data
 * @param {EncodeOptions} [options]
 * @returns {Uint8Array}
 */
function encode (data, options) {
  options = Object.assign({}, defaultEncodeOptions, options)

  // Use direct encode path when possible
  if (canDirectEncode(options)) {
    defaultWriter.reset()
    directEncode(defaultWriter, data, options, undefined)
    return defaultWriter.toBytes(true)
  }

  return encodeCustom(data, cborEncoders, options)
}

/**
 * @param {any} data
 * @param {Uint8Array} destination
 * @param {EncodeOptions} [options]
 * @returns {{ written: number }}
 */
function encodeInto (data, destination, options) {
  options = Object.assign({}, defaultEncodeOptions, options)

  // Use direct encode path when possible
  if (canDirectEncode(options)) {
    const writer = new U8Bl(destination)
    directEncode(writer, data, options, undefined)
    return { written: writer.toBytes().length }
  }

  const result = encodeCustom(data, cborEncoders, options, destination)
  return { written: result.length }
}

export { objectToTokens, encode, encodeCustom, encodeInto, Ref }
// This is an unfortunate replacement for @sindresorhus/is that we need to
// re-implement for performance purposes. In particular the is.observable()
// check is expensive, and unnecessary for our purposes. The values returned
// are compatible with @sindresorhus/is, however.

// Types that reach getObjectType() - excludes types with fast-paths above:
// primitives (typeof), Array (isArray), Uint8Array (instanceof), plain Object (constructor)
const objectTypeNames = [
  'Object', // for Object.create(null) and other non-plain objects
  'RegExp',
  'Date',
  'Error',
  'Map',
  'Set',
  'WeakMap',
  'WeakSet',
  'ArrayBuffer',
  'SharedArrayBuffer',
  'DataView',
  'Promise',
  'URL',
  'HTMLElement',
  'Int8Array',
  'Uint8ClampedArray',
  'Int16Array',
  'Uint16Array',
  'Int32Array',
  'Uint32Array',
  'Float32Array',
  'Float64Array',
  'BigInt64Array',
  'BigUint64Array',
  'Tagged'
]

/**
 * @param {any} value
 * @returns {string}
 */
export function is (value) {
  if (value === null) {
    return 'null'
  }
  if (value === undefined) {
    return 'undefined'
  }
  if (value === true || value === false) {
    return 'boolean'
  }
  const typeOf = typeof value
  if (typeOf === 'string' || typeOf === 'number' || typeOf === 'bigint' || typeOf === 'symbol') {
    return typeOf
  }
  if (typeOf === 'function') {
    return 'Function'
  }
  if (Array.isArray(value)) {
    return 'Array'
  }
  // Also catches Node.js Buffer which extends Uint8Array
  if (value instanceof Uint8Array) {
    return 'Uint8Array'
  }
  // Fast path for plain objects (most common case after primitives/arrays/bytes)
  if (value.constructor === Object) {
    return 'Object'
  }
  const objectType = getObjectType(value)
  if (objectType) {
    return objectType
  }
  return 'Object'
}

/**
 * @param {any} value
 * @returns {string|undefined}
 */
function getObjectType (value) {
  const objectTypeName = Object.prototype.toString.call(value).slice(8, -1)
  if (objectTypeNames.includes(objectTypeName)) {
    return objectTypeName
  }
  return undefined
}
import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import * as negint from './1negint.js'
import * as bytes from './2bytes.js'
import * as string from './3string.js'
import * as array from './4array.js'
import * as map from './5map.js'
import * as tag from './6tag.js'
import * as float from './7float.js'
import { decodeErrPrefix } from './common.js'
import { fromArray } from './byte-utils.js'

/**
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 */
function invalidMinor (data, pos, minor) {
  throw new Error(`${decodeErrPrefix} encountered invalid minor (${minor}) for major ${data[pos] >>> 5}`)
}

/**
 * @param {string} msg
 * @returns {()=>any}
 */
function errorer (msg) {
  return () => { throw new Error(`${decodeErrPrefix} ${msg}`) }
}

/** @type {((data:Uint8Array, pos:number, minor:number, options?:DecodeOptions) => any)[]} */
export const jump = []

// unsigned integer, 0x00..0x17 (0..23)
for (let i = 0; i <= 0x17; i++) {
  jump[i] = invalidMinor // uint.decodeUintCompact, handled by quick[]
}
jump[0x18] = uint.decodeUint8 // unsigned integer, one-byte uint8_t follows
jump[0x19] = uint.decodeUint16 // unsigned integer, two-byte uint16_t follows
jump[0x1a] = uint.decodeUint32 // unsigned integer, four-byte uint32_t follows
jump[0x1b] = uint.decodeUint64 // unsigned integer, eight-byte uint64_t follows
jump[0x1c] = invalidMinor
jump[0x1d] = invalidMinor
jump[0x1e] = invalidMinor
jump[0x1f] = invalidMinor
// negative integer, -1-0x00..-1-0x17 (-1..-24)
for (let i = 0x20; i <= 0x37; i++) {
  jump[i] = invalidMinor // negintDecode, handled by quick[]
}
jump[0x38] = negint.decodeNegint8 // negative integer, -1-n one-byte uint8_t for n follows
jump[0x39] = negint.decodeNegint16 // negative integer, -1-n two-byte uint16_t for n follows
jump[0x3a] = negint.decodeNegint32 // negative integer, -1-n four-byte uint32_t for follows
jump[0x3b] = negint.decodeNegint64 // negative integer, -1-n eight-byte uint64_t for follows
jump[0x3c] = invalidMinor
jump[0x3d] = invalidMinor
jump[0x3e] = invalidMinor
jump[0x3f] = invalidMinor
// byte string, 0x00..0x17 bytes follow
for (let i = 0x40; i <= 0x57; i++) {
  jump[i] = bytes.decodeBytesCompact
}
jump[0x58] = bytes.decodeBytes8 // byte string, one-byte uint8_t for n, and then n bytes follow
jump[0x59] = bytes.decodeBytes16 // byte string, two-byte uint16_t for n, and then n bytes follow
jump[0x5a] = bytes.decodeBytes32 // byte string, four-byte uint32_t for n, and then n bytes follow
jump[0x5b] = bytes.decodeBytes64 // byte string, eight-byte uint64_t for n, and then n bytes follow
jump[0x5c] = invalidMinor
jump[0x5d] = invalidMinor
jump[0x5e] = invalidMinor
jump[0x5f] = errorer('indefinite length bytes/strings are not supported') // byte string, byte strings follow, terminated by "break"
// UTF-8 string 0x00..0x17 bytes follow
for (let i = 0x60; i <= 0x77; i++) {
  jump[i] = string.decodeStringCompact
}
jump[0x78] = string.decodeString8 // UTF-8 string, one-byte uint8_t for n, and then n bytes follow
jump[0x79] = string.decodeString16 // UTF-8 string, two-byte uint16_t for n, and then n bytes follow
jump[0x7a] = string.decodeString32 // UTF-8 string, four-byte uint32_t for n, and then n bytes follow
jump[0x7b] = string.decodeString64 // UTF-8 string, eight-byte uint64_t for n, and then n bytes follow
jump[0x7c] = invalidMinor
jump[0x7d] = invalidMinor
jump[0x7e] = invalidMinor
jump[0x7f] = errorer('indefinite length bytes/strings are not supported') // UTF-8 strings follow, terminated by "break"
// array, 0x00..0x17 data items follow
for (let i = 0x80; i <= 0x97; i++) {
  jump[i] = array.decodeArrayCompact
}
jump[0x98] = array.decodeArray8 // array, one-byte uint8_t for n, and then n data items follow
jump[0x99] = array.decodeArray16 // array, two-byte uint16_t for n, and then n data items follow
jump[0x9a] = array.decodeArray32 // array, four-byte uint32_t for n, and then n data items follow
jump[0x9b] = array.decodeArray64 // array, eight-byte uint64_t for n, and then n data items follow
jump[0x9c] = invalidMinor
jump[0x9d] = invalidMinor
jump[0x9e] = invalidMinor
jump[0x9f] = array.decodeArrayIndefinite // array, data items follow, terminated by "break"
// map, 0x00..0x17 pairs of data items follow
for (let i = 0xa0; i <= 0xb7; i++) {
  jump[i] = map.decodeMapCompact
}
jump[0xb8] = map.decodeMap8 // map, one-byte uint8_t for n, and then n pairs of data items follow
jump[0xb9] = map.decodeMap16 // map, two-byte uint16_t for n, and then n pairs of data items follow
jump[0xba] = map.decodeMap32 // map, four-byte uint32_t for n, and then n pairs of data items follow
jump[0xbb] = map.decodeMap64 // map, eight-byte uint64_t for n, and then n pairs of data items follow
jump[0xbc] = invalidMinor
jump[0xbd] = invalidMinor
jump[0xbe] = invalidMinor
jump[0xbf] = map.decodeMapIndefinite // map, pairs of data items follow, terminated by "break"
// tags
for (let i = 0xc0; i <= 0xd7; i++) {
  jump[i] = tag.decodeTagCompact
}
jump[0xd8] = tag.decodeTag8
jump[0xd9] = tag.decodeTag16
jump[0xda] = tag.decodeTag32
jump[0xdb] = tag.decodeTag64
jump[0xdc] = invalidMinor
jump[0xdd] = invalidMinor
jump[0xde] = invalidMinor
jump[0xdf] = invalidMinor
// 0xe0..0xf3 simple values, unsupported
for (let i = 0xe0; i <= 0xf3; i++) {
  jump[i] = errorer('simple values are not supported')
}
jump[0xf4] = invalidMinor // false, handled by quick[]
jump[0xf5] = invalidMinor // true, handled by quick[]
jump[0xf6] = invalidMinor // null, handled by quick[]
jump[0xf7] = float.decodeUndefined // undefined
jump[0xf8] = errorer('simple values are not supported') // simple value, one byte follows, unsupported
jump[0xf9] = float.decodeFloat16 // half-precision float (two-byte IEEE 754)
jump[0xfa] = float.decodeFloat32 // single-precision float (four-byte IEEE 754)
jump[0xfb] = float.decodeFloat64 // double-precision float (eight-byte IEEE 754)
jump[0xfc] = invalidMinor
jump[0xfd] = invalidMinor
jump[0xfe] = invalidMinor
jump[0xff] = float.decodeBreak // "break" stop code

/** @type {Token[]} */
export const quick = []
// ints <24
for (let i = 0; i < 24; i++) {
  quick[i] = new Token(Type.uint, i, 1)
}
// negints >= -24
for (let i = -1; i >= -24; i--) {
  quick[31 - i] = new Token(Type.negint, i, 1)
}
// empty bytes
quick[0x40] = new Token(Type.bytes, new Uint8Array(0), 1)
// empty string
quick[0x60] = new Token(Type.string, '', 1)
// empty list
quick[0x80] = new Token(Type.array, 0, 1)
// empty map
quick[0xa0] = new Token(Type.map, 0, 1)
// false
quick[0xf4] = new Token(Type.false, false, 1)
// true
quick[0xf5] = new Token(Type.true, true, 1)
// null
quick[0xf6] = new Token(Type.null, null, 1)

/**
 * @param {Token} token
 * @returns {Uint8Array|undefined}
 */
export function quickEncodeToken (token) {
  switch (token.type) {
    case Type.false:
      return fromArray([0xf4])
    case Type.true:
      return fromArray([0xf5])
    case Type.null:
      return fromArray([0xf6])
    case Type.bytes:
      if (!token.value.length) {
        return fromArray([0x40])
      }
      return
    case Type.string:
      if (token.value === '') {
        return fromArray([0x60])
      }
      return
    case Type.array:
      if (token.value === 0) {
        return fromArray([0x80])
      }
      // shouldn't be possible if this were called when there was only one token
      return
    case Type.map:
      if (token.value === 0) {
        return fromArray([0xa0])
      }
      // shouldn't be possible if this were called when there was only one token
      return
    case Type.uint:
      if (token.value < 24) {
        return fromArray([Number(token.value)])
      }
      return
    case Type.negint:
      if (token.value >= -24) {
        return fromArray([31 - Number(token.value)])
      }
  }
}
/**
 * @typedef {import('../interface.js').TagDecodeControl} TagDecodeControl
 * @typedef {(decode: TagDecodeControl) => Tagged} TaggedTagDecoder
 */

/**
 * A wrapper class for representing a CBOR tag with an arbitrary nested value.
 *
 * `Tagged` is a symmetric primitive: it can be passed to `encode()` to emit
 * a CBOR tag header followed by the encoded form of `value`, and it can be
 * returned from a tag decoder (via `Tagged.decoder(tag)` or `Tagged.preserve()`)
 * to round-trip a tag through decode without losing the tag number.
 *
 * Use `Tagged` for one-off tag handling where defining a dedicated
 * `typeEncoders` entry and tag decoder pair would be heavyweight, e.g. when
 * wrapping a structure in a single application-specific tag (COSE, dCBOR
 * envelopes, etc.).
 *
 * For systematic mapping of a JS type to a tag (e.g. CID -> tag 42), prefer
 * a dedicated `typeEncoders` entry instead.
 */
export class Tagged {
  /**
   * @param {number} tag - CBOR tag number, a non-negative integer
   * @param {any} value - The value to be tagged; encoded recursively
   */
  constructor (tag, value) {
    if (typeof tag !== 'number' || !Number.isInteger(tag) || tag < 0) {
      throw new TypeError('Tagged: tag must be a non-negative integer')
    }
    this.tag = tag
    this.value = value
  }

  /**
   * Build a tag decoder for use in `decode()`'s `tags` option that returns the
   * decoded content wrapped in a `Tagged` instance, preserving the tag number
   * for the caller to inspect.
   *
   * @param {number} tag - The CBOR tag number this decoder will be registered for
   * @returns {TaggedTagDecoder}
   *
   * @example
   * import { decode, Tagged } from 'cborg'
   * const value = decode(bytes, { tags: { 16: Tagged.decoder(16) } })
   * // value instanceof Tagged; value.tag === 16
   */
  static decoder (tag) {
    return (decode) => new Tagged(tag, decode())
  }

  /**
   * Build a `tags` option for `decode()` that wraps each listed tag number in
   * a `Tagged` instance, preserving those tags through decode without
   * registering a dedicated decoder per tag.
   *
   * @param {...number} tagNumbers - One or more CBOR tag numbers to preserve
   * @returns {{[tagNumber: number]: TaggedTagDecoder}}
   *
   * @example
   * import { decode, Tagged } from 'cborg'
   * const value = decode(bytes, { tags: Tagged.preserve(16, 96) })
   */
  static preserve (...tagNumbers) {
    /** @type {{[tagNumber: number]: TaggedTagDecoder}} */
    const tags = {}
    for (const tag of tagNumbers) {
      tags[tag] = Tagged.decoder(tag)
    }
    return tags
  }
}

// Symbol.toStringTag so the internal `is()` type detection returns 'Tagged'
// for instances, allowing the default Tagged typeEncoder to match.
Object.defineProperty(Tagged.prototype, Symbol.toStringTag, {
  value: 'Tagged'
})
class Type {
  /**
   * @param {number} major
   * @param {string} name
   * @param {boolean} terminal
   */
  constructor (major, name, terminal) {
    this.major = major
    this.majorEncoded = major << 5
    this.name = name
    this.terminal = terminal
  }

  toString () {
    return `Type[${this.major}].${this.name}`
  }

  /**
   * @param {Type} typ
   * @returns {number}
   */
  compare (typ) {
    return this.major < typ.major ? -1 : this.major > typ.major ? 1 : 0
  }

  /**
   * Check equality between two Type instances. Safe to use across different
   * copies of the Type class (e.g., when bundlers duplicate the module).
   * (major, name) uniquely identifies a Type; terminal is implied by these.
   * @param {Type} a
   * @param {Type} b
   * @returns {boolean}
   */
  static equals (a, b) {
    return a === b || (a.major === b.major && a.name === b.name)
  }
}

// convert to static fields when better supported
Type.uint = new Type(0, 'uint', true)
Type.negint = new Type(1, 'negint', true)
Type.bytes = new Type(2, 'bytes', true)
Type.string = new Type(3, 'string', true)
Type.array = new Type(4, 'array', false)
Type.map = new Type(5, 'map', false)
Type.tag = new Type(6, 'tag', false) // terminal?
Type.float = new Type(7, 'float', true)
Type.false = new Type(7, 'false', true)
Type.true = new Type(7, 'true', true)
Type.null = new Type(7, 'null', true)
Type.undefined = new Type(7, 'undefined', true)
Type.break = new Type(7, 'break', true)
// Type.indefiniteLength = new Type(0, 'indefiniteLength', true)

class Token {
  /**
   * @param {Type} type
   * @param {any} [value]
   * @param {number} [encodedLength]
   */
  constructor (type, value, encodedLength) {
    this.type = type
    this.value = value
    this.encodedLength = encodedLength
    /** @type {Uint8Array|undefined} */
    this.encodedBytes = undefined
    /** @type {Uint8Array|undefined} */
    this.byteValue = undefined
  }

  toString () {
    return `Token[${this.type}].${this.value}`
  }
}

export { Type, Token }
{
  "name": "cborg",
  "version": "5.1.6",
  "description": "Fast CBOR with a focus on strictness",
  "main": "cborg.js",
  "type": "module",
  "bin": {
    "cborg": "lib/bin.js"
  },
  "scripts": {
    "lint": "standard *.js lib/*.js test/*.js",
    "build": "npm run build:types",
    "build:types": "tsc --build",
    "prepublishOnly": "npm run build",
    "test:node": "mocha test/test-*.js",
    "test:node-bin": "mocha test/node-test-bin.js",
    "test:browser": "polendina --cleanup test/test-*.js",
    "test": "npm run lint && npm run build && npm run test:node && npm run test:node-bin && npm run test:browser",
    "test:ci": "npm run test"
  },
  "repository": {
    "type": "git",
    "url": "git@github.com:rvagg/cborg.git"
  },
  "keywords": [
    "cbor"
  ],
  "author": "Rod <rod@vagg.org> (http://r.va.gg/)",
  "license": "Apache-2.0",
  "devDependencies": {
    "@semantic-release/changelog": "^6.0.3",
    "@semantic-release/commit-analyzer": "^13.0.1",
    "@semantic-release/git": "^10.0.1",
    "@semantic-release/github": "^12.0.6",
    "@semantic-release/npm": "^13.1.5",
    "@semantic-release/release-notes-generator": "^14.1.0",
    "@types/chai": "^5.2.3",
    "@types/mocha": "^10.0.10",
    "@types/node": "^26.0.1",
    "chai": "^6.2.2",
    "conventional-changelog-conventionalcommits": "^10.0.0",
    "ipld-garbage": "^5.0.0",
    "mocha": "^11.7.5",
    "polendina": "^3.2.20",
    "semantic-release": "^25.0.3",
    "standard": "^17.1.2",
    "typescript": "^6.0.2"
  },
  "exports": {
    ".": {
      "import": "./cborg.js",
      "types": "./types/cborg.d.ts"
    },
    "./length": {
      "import": "./lib/length.js",
      "types": "./types/lib/length.d.ts"
    },
    "./taglib": {
      "import": "./lib/taglib.js",
      "types": "./types/lib/taglib.d.ts"
    },
    "./json": {
      "import": "./lib/json/json.js",
      "types": "./types/lib/json/json.d.ts"
    },
    "./extended": {
      "import": "./lib/extended/extended.js",
      "types": "./types/lib/extended/extended.d.ts"
    },
    "./interface": {
      "types": "./types/interface.d.ts"
    }
  },
  "types": "cborg.d.ts",
  "typesVersions": {
    "*": {
      "json": [
        "types/lib/json/json.d.ts"
      ],
      "length": [
        "types/lib/length.d.ts"
      ],
      "*": [
        "types/*"
      ],
      "types/*": [
        "types/*"
      ]
    }
  },
  "release": {
    "branches": [
      "master"
    ],
    "plugins": [
      [
        "@semantic-release/commit-analyzer",
        {
          "preset": "conventionalcommits",
          "releaseRules": [
            {
              "breaking": true,
              "release": "major"
            },
            {
              "revert": true,
              "release": "patch"
            },
            {
              "type": "feat",
              "release": "minor"
            },
            {
              "type": "fix",
              "release": "patch"
            },
            {
              "type": "chore",
              "release": "patch"
            },
            {
              "type": "docs",
              "release": "patch"
            },
            {
              "type": "test",
              "release": "patch"
            },
            {
              "scope": "no-release",
              "release": false
            }
          ]
        }
      ],
      [
        "@semantic-release/release-notes-generator",
        {
          "preset": "conventionalcommits",
          "presetConfig": {
            "types": [
              {
                "type": "feat",
                "section": "Features"
              },
              {
                "type": "fix",
                "section": "Bug Fixes"
              },
              {
                "type": "chore",
                "section": "Trivial Changes"
              },
              {
                "type": "docs",
                "section": "Trivial Changes"
              },
              {
                "type": "test",
                "section": "Tests"
              }
            ]
          }
        }
      ],
      "@semantic-release/changelog",
      "@semantic-release/npm",
      "@semantic-release/github",
      "@semantic-release/git"
    ]
  }
}
import { coerce } from '../bytes.js';
import basex from '../vendor/base-x.js';
/**
 * Class represents both BaseEncoder and MultibaseEncoder meaning it
 * can be used to encode to multibase or base encode without multibase
 * prefix.
 */
class Encoder {
    name;
    prefix;
    baseEncode;
    constructor(name, prefix, baseEncode) {
        this.name = name;
        this.prefix = prefix;
        this.baseEncode = baseEncode;
    }
    encode(bytes) {
        if (bytes instanceof Uint8Array) {
            return `${this.prefix}${this.baseEncode(bytes)}`;
        }
        else {
            throw Error('Unknown type, must be binary type');
        }
    }
}
/**
 * Class represents both BaseDecoder and MultibaseDecoder so it could be used
 * to decode multibases (with matching prefix) or just base decode strings
 * with corresponding base encoding.
 */
class Decoder {
    name;
    prefix;
    baseDecode;
    prefixCodePoint;
    constructor(name, prefix, baseDecode) {
        this.name = name;
        this.prefix = prefix;
        const prefixCodePoint = prefix.codePointAt(0);
        /* c8 ignore next 3 */
        if (prefixCodePoint === undefined) {
            throw new Error('Invalid prefix character');
        }
        this.prefixCodePoint = prefixCodePoint;
        this.baseDecode = baseDecode;
    }
    decode(text) {
        if (typeof text === 'string') {
            if (text.codePointAt(0) !== this.prefixCodePoint) {
                throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);
            }
            return this.baseDecode(text.slice(this.prefix.length));
        }
        else {
            throw Error('Can only multibase decode strings');
        }
    }
    or(decoder) {
        return or(this, decoder);
    }
}
class ComposedDecoder {
    decoders;
    constructor(decoders) {
        this.decoders = decoders;
    }
    or(decoder) {
        return or(this, decoder);
    }
    decode(input) {
        const prefix = input[0];
        const decoder = this.decoders[prefix];
        if (decoder != null) {
            return decoder.decode(input);
        }
        else {
            throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);
        }
    }
}
export function or(left, right) {
    return new ComposedDecoder({
        ...(left.decoders ?? { [left.prefix]: left }),
        ...(right.decoders ?? { [right.prefix]: right })
    });
}
export class Codec {
    name;
    prefix;
    baseEncode;
    baseDecode;
    encoder;
    decoder;
    constructor(name, prefix, baseEncode, baseDecode) {
        this.name = name;
        this.prefix = prefix;
        this.baseEncode = baseEncode;
        this.baseDecode = baseDecode;
        this.encoder = new Encoder(name, prefix, baseEncode);
        this.decoder = new Decoder(name, prefix, baseDecode);
    }
    encode(input) {
        return this.encoder.encode(input);
    }
    decode(input) {
        return this.decoder.decode(input);
    }
}
export function from({ name, prefix, encode, decode }) {
    return new Codec(name, prefix, encode, decode);
}
export function baseX({ name, prefix, alphabet }) {
    const { encode, decode } = basex(alphabet, name);
    return from({
        prefix,
        name,
        encode,
        decode: (text) => coerce(decode(text))
    });
}
function decode(string, alphabetIdx, bitsPerChar, name) {
    // Count the padding bytes:
    let end = string.length;
    while (string[end - 1] === '=') {
        --end;
    }
    // Allocate the output:
    const out = new Uint8Array((end * bitsPerChar / 8) | 0);
    // Parse the data:
    let bits = 0; // Number of bits currently in the buffer
    let buffer = 0; // Bits waiting to be written out, MSB first
    let written = 0; // Next byte to write
    for (let i = 0; i < end; ++i) {
        // Read one character from the string:
        const value = alphabetIdx[string[i]];
        if (value === undefined) {
            throw new SyntaxError(`Non-${name} character`);
        }
        // Append the bits to the buffer:
        buffer = (buffer << bitsPerChar) | value;
        bits += bitsPerChar;
        // Write out some bits if the buffer has a byte's worth:
        if (bits >= 8) {
            bits -= 8;
            out[written++] = 0xff & (buffer >> bits);
        }
    }
    // Verify that we have received just enough bits:
    if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {
        throw new SyntaxError('Unexpected end of data');
    }
    return out;
}
function encode(data, alphabet, bitsPerChar) {
    const pad = alphabet[alphabet.length - 1] === '=';
    const mask = (1 << bitsPerChar) - 1;
    let out = '';
    let bits = 0; // Number of bits currently in the buffer
    let buffer = 0; // Bits waiting to be written out, MSB first
    for (let i = 0; i < data.length; ++i) {
        // Slurp data into the buffer:
        buffer = (buffer << 8) | data[i];
        bits += 8;
        // Write out as much as we can:
        while (bits > bitsPerChar) {
            bits -= bitsPerChar;
            out += alphabet[mask & (buffer >> bits)];
        }
    }
    // Partial character:
    if (bits !== 0) {
        out += alphabet[mask & (buffer << (bitsPerChar - bits))];
    }
    // Add padding characters until we hit a byte boundary:
    if (pad) {
        while (((out.length * bitsPerChar) & 7) !== 0) {
            out += '=';
        }
    }
    return out;
}
function createAlphabetIdx(alphabet) {
    // Build the character lookup table:
    const alphabetIdx = {};
    for (let i = 0; i < alphabet.length; ++i) {
        alphabetIdx[alphabet[i]] = i;
    }
    return alphabetIdx;
}
/**
 * RFC4648 Factory
 */
export function rfc4648({ name, prefix, bitsPerChar, alphabet }) {
    const alphabetIdx = createAlphabetIdx(alphabet);
    return from({
        prefix,
        name,
        encode(input) {
            return encode(input, alphabet, bitsPerChar);
        },
        decode(input) {
            return decode(input, alphabetIdx, bitsPerChar, name);
        }
    });
}
//# sourceMappingURL=base.js.mapimport { rfc4648 } from './base.js';
export const base32 = rfc4648({
    prefix: 'b',
    name: 'base32',
    alphabet: 'abcdefghijklmnopqrstuvwxyz234567',
    bitsPerChar: 5
});
export const base32upper = rfc4648({
    prefix: 'B',
    name: 'base32upper',
    alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',
    bitsPerChar: 5
});
export const base32pad = rfc4648({
    prefix: 'c',
    name: 'base32pad',
    alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',
    bitsPerChar: 5
});
export const base32padupper = rfc4648({
    prefix: 'C',
    name: 'base32padupper',
    alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',
    bitsPerChar: 5
});
export const base32hex = rfc4648({
    prefix: 'v',
    name: 'base32hex',
    alphabet: '0123456789abcdefghijklmnopqrstuv',
    bitsPerChar: 5
});
export const base32hexupper = rfc4648({
    prefix: 'V',
    name: 'base32hexupper',
    alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',
    bitsPerChar: 5
});
export const base32hexpad = rfc4648({
    prefix: 't',
    name: 'base32hexpad',
    alphabet: '0123456789abcdefghijklmnopqrstuv=',
    bitsPerChar: 5
});
export const base32hexpadupper = rfc4648({
    prefix: 'T',
    name: 'base32hexpadupper',
    alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',
    bitsPerChar: 5
});
export const base32z = rfc4648({
    prefix: 'h',
    name: 'base32z',
    alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',
    bitsPerChar: 5
});
//# sourceMappingURL=base32.js.mapimport { baseX } from './base.js';
export const base36 = baseX({
    prefix: 'k',
    name: 'base36',
    alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'
});
export const base36upper = baseX({
    prefix: 'K',
    name: 'base36upper',
    alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
});
//# sourceMappingURL=base36.js.mapimport { baseX } from './base.js';
export const base58btc = baseX({
    name: 'base58btc',
    prefix: 'z',
    alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
});
export const base58flickr = baseX({
    name: 'base58flickr',
    prefix: 'Z',
    alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'
});
//# sourceMappingURL=base58.js.mapexport const empty = new Uint8Array(0);
export function toHex(d) {
    return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '');
}
export function fromHex(hex) {
    const hexes = hex.match(/../g);
    return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty;
}
export function equals(aa, bb) {
    if (aa === bb) {
        return true;
    }
    if (aa.byteLength !== bb.byteLength) {
        return false;
    }
    for (let ii = 0; ii < aa.byteLength; ii++) {
        if (aa[ii] !== bb[ii]) {
            return false;
        }
    }
    return true;
}
export function coerce(o) {
    if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') {
        return o;
    }
    if (o instanceof ArrayBuffer) {
        return new Uint8Array(o);
    }
    if (ArrayBuffer.isView(o)) {
        return new Uint8Array(o.buffer, o.byteOffset, o.byteLength);
    }
    throw new Error('Unknown type, must be binary type');
}
export function isBinary(o) {
    return o instanceof ArrayBuffer || ArrayBuffer.isView(o);
}
export function fromString(str) {
    return new TextEncoder().encode(str);
}
export function toString(b) {
    return new TextDecoder().decode(b);
}
//# sourceMappingURL=bytes.js.mapimport { base32 } from './bases/base32.js';
import { base36 } from './bases/base36.js';
import { base58btc } from './bases/base58.js';
import { coerce } from './bytes.js';
import * as Digest from './hashes/digest.js';
import * as varint from './varint.js';
// This way TS will also expose all the types from module
export * from './link/interface.js';
export function format(link, base) {
    const { bytes, version } = link;
    switch (version) {
        case 0:
            return toStringV0(bytes, baseCache(link), base ?? base58btc.encoder);
        default:
            return toStringV1(bytes, baseCache(link), (base ?? base32.encoder));
    }
}
export function toJSON(link) {
    return {
        '/': format(link)
    };
}
export function fromJSON(json) {
    return CID.parse(json['/']);
}
const cache = new WeakMap();
function baseCache(cid) {
    const baseCache = cache.get(cid);
    if (baseCache == null) {
        const baseCache = new Map();
        cache.set(cid, baseCache);
        return baseCache;
    }
    return baseCache;
}
export class CID {
    code;
    version;
    multihash;
    bytes;
    '/';
    /**
     * @param version - Version of the CID
     * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
     * @param multihash - (Multi)hash of the of the content.
     */
    constructor(version, code, multihash, bytes) {
        this.code = code;
        this.version = version;
        this.multihash = multihash;
        this.bytes = bytes;
        // flag to serializers that this is a CID and
        // should be treated specially
        this['/'] = bytes;
    }
    /**
     * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`
     * please either use `CID.asCID(cid)` or switch to new signalling mechanism
     *
     * @deprecated
     */
    get asCID() {
        return this;
    }
    // ArrayBufferView
    get byteOffset() {
        return this.bytes.byteOffset;
    }
    // ArrayBufferView
    get byteLength() {
        return this.bytes.byteLength;
    }
    toV0() {
        switch (this.version) {
            case 0: {
                return this;
            }
            case 1: {
                const { code, multihash } = this;
                if (code !== DAG_PB_CODE) {
                    throw new Error('Cannot convert a non dag-pb CID to CIDv0');
                }
                // sha2-256
                if (multihash.code !== SHA_256_CODE) {
                    throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0');
                }
                return (CID.createV0(multihash));
            }
            default: {
                throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);
            }
        }
    }
    toV1() {
        switch (this.version) {
            case 0: {
                const { code, digest } = this.multihash;
                const multihash = Digest.create(code, digest);
                return (CID.createV1(this.code, multihash));
            }
            case 1: {
                return this;
            }
            default: {
                throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);
            }
        }
    }
    equals(other) {
        return CID.equals(this, other);
    }
    static equals(self, other) {
        const unknown = other;
        return (unknown != null &&
            self.code === unknown.code &&
            self.version === unknown.version &&
            Digest.equals(self.multihash, unknown.multihash));
    }
    toString(base) {
        return format(this, base);
    }
    toJSON() {
        return { '/': format(this) };
    }
    link() {
        return this;
    }
    [Symbol.toStringTag] = 'CID';
    // Legacy
    [Symbol.for('nodejs.util.inspect.custom')]() {
        return `CID(${this.toString()})`;
    }
    /**
     * Takes any input `value` and returns a `CID` instance if it was
     * a `CID` otherwise returns `null`. If `value` is instanceof `CID`
     * it will return value back. If `value` is not instance of this CID
     * class, but is compatible CID it will return new instance of this
     * `CID` class. Otherwise returns null.
     *
     * This allows two different incompatible versions of CID library to
     * co-exist and interop as long as binary interface is compatible.
     */
    static asCID(input) {
        if (input == null) {
            return null;
        }
        const value = input;
        if (value instanceof CID) {
            // If value is instance of CID then we're all set.
            return value;
        }
        else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {
            // If value isn't instance of this CID class but `this.asCID === this` or
            // `value['/'] === value.bytes` is true it is CID instance coming from a
            // different implementation (diff version or duplicate). In that case we
            // rebase it to this `CID` implementation so caller is guaranteed to get
            // instance with expected API.
            const { version, code, multihash, bytes } = value;
            return new CID(version, code, multihash, bytes ?? encodeCID(version, code, multihash.bytes));
        }
        else if (value[cidSymbol] === true) {
            // If value is a CID from older implementation that used to be tagged via
            // symbol we still rebase it to the this `CID` implementation by
            // delegating that to a constructor.
            const { version, multihash, code } = value;
            const digest = Digest.decode(multihash);
            return CID.create(version, code, digest);
        }
        else {
            // Otherwise value is not a CID (or an incompatible version of it) in
            // which case we return `null`.
            return null;
        }
    }
    /**
     * @param version - Version of the CID
     * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
     * @param digest - (Multi)hash of the of the content.
     */
    static create(version, code, digest) {
        if (typeof code !== 'number') {
            throw new Error('String codecs are no longer supported');
        }
        if (!(digest.bytes instanceof Uint8Array)) {
            throw new Error('Invalid digest');
        }
        switch (version) {
            case 0: {
                if (code !== DAG_PB_CODE) {
                    throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);
                }
                else {
                    return new CID(version, code, digest, digest.bytes);
                }
            }
            case 1: {
                const bytes = encodeCID(version, code, digest.bytes);
                return new CID(version, code, digest, bytes);
            }
            default: {
                throw new Error('Invalid version');
            }
        }
    }
    /**
     * Simplified version of `create` for CIDv0.
     */
    static createV0(digest) {
        return CID.create(0, DAG_PB_CODE, digest);
    }
    /**
     * Simplified version of `create` for CIDv1.
     *
     * @param code - Content encoding format code.
     * @param digest - Multihash of the content.
     */
    static createV1(code, digest) {
        return CID.create(1, code, digest);
    }
    /**
     * Decoded a CID from its binary representation. The byte array must contain
     * only the CID with no additional bytes.
     *
     * An error will be thrown if the bytes provided do not contain a valid
     * binary representation of a CID.
     */
    static decode(bytes) {
        const [cid, remainder] = CID.decodeFirst(bytes);
        if (remainder.length !== 0) {
            throw new Error('Incorrect length');
        }
        return cid;
    }
    /**
     * Decoded a CID from its binary representation at the beginning of a byte
     * array.
     *
     * Returns an array with the first element containing the CID and the second
     * element containing the remainder of the original byte array. The remainder
     * will be a zero-length byte array if the provided bytes only contained a
     * binary CID representation.
     */
    static decodeFirst(bytes) {
        const specs = CID.inspectBytes(bytes);
        const prefixSize = specs.size - specs.multihashSize;
        const multihashBytes = coerce(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));
        if (multihashBytes.byteLength !== specs.multihashSize) {
            throw new Error('Incorrect length');
        }
        const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);
        const digest = new Digest.Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);
        const cid = specs.version === 0
            ? CID.createV0(digest)
            : CID.createV1(specs.codec, digest);
        return [cid, bytes.subarray(specs.size)];
    }
    /**
     * Inspect the initial bytes of a CID to determine its properties.
     *
     * Involves decoding up to 4 varints. Typically this will require only 4 to 6
     * bytes but for larger multicodec code values and larger multihash digest
     * lengths these varints can be quite large. It is recommended that at least
     * 10 bytes be made available in the `initialBytes` argument for a complete
     * inspection.
     */
    static inspectBytes(initialBytes) {
        let offset = 0;
        const next = () => {
            const [i, length] = varint.decode(initialBytes.subarray(offset));
            offset += length;
            return i;
        };
        let version = next();
        let codec = DAG_PB_CODE;
        if (version === 18) {
            // CIDv0
            version = 0;
            offset = 0;
        }
        else {
            codec = next();
        }
        if (version !== 0 && version !== 1) {
            throw new RangeError(`Invalid CID version ${version}`);
        }
        const prefixSize = offset;
        const multihashCode = next(); // multihash code
        const digestSize = next(); // multihash length
        const size = offset + digestSize;
        const multihashSize = size - prefixSize;
        return { version, codec, multihashCode, digestSize, multihashSize, size };
    }
    /**
     * Takes cid in a string representation and creates an instance. If `base`
     * decoder is not provided will use a default from the configuration. It will
     * throw an error if encoding of the CID is not compatible with supplied (or
     * a default decoder).
     */
    static parse(source, base) {
        const [prefix, bytes] = parseCIDtoBytes(source, base);
        const cid = CID.decode(bytes);
        if (cid.version === 0 && source[0] !== 'Q') {
            throw Error('Version 0 CID string must not include multibase prefix');
        }
        // Cache string representation to avoid computing it on `this.toString()`
        baseCache(cid).set(prefix, source);
        return cid;
    }
}
function parseCIDtoBytes(source, base) {
    switch (source[0]) {
        // CIDv0 is parsed differently
        case 'Q': {
            const decoder = base ?? base58btc;
            return [
                base58btc.prefix,
                decoder.decode(`${base58btc.prefix}${source}`)
            ];
        }
        case base58btc.prefix: {
            const decoder = base ?? base58btc;
            return [base58btc.prefix, decoder.decode(source)];
        }
        case base32.prefix: {
            const decoder = base ?? base32;
            return [base32.prefix, decoder.decode(source)];
        }
        case base36.prefix: {
            const decoder = base ?? base36;
            return [base36.prefix, decoder.decode(source)];
        }
        default: {
            if (base == null) {
                throw Error('To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided');
            }
            return [source[0], base.decode(source)];
        }
    }
}
function toStringV0(bytes, cache, base) {
    const { prefix } = base;
    if (prefix !== base58btc.prefix) {
        throw Error(`Cannot string encode V0 in ${base.name} encoding`);
    }
    const cid = cache.get(prefix);
    if (cid == null) {
        const cid = base.encode(bytes).slice(1);
        cache.set(prefix, cid);
        return cid;
    }
    else {
        return cid;
    }
}
function toStringV1(bytes, cache, base) {
    const { prefix } = base;
    const cid = cache.get(prefix);
    if (cid == null) {
        const cid = base.encode(bytes);
        cache.set(prefix, cid);
        return cid;
    }
    else {
        return cid;
    }
}
const DAG_PB_CODE = 0x70;
const SHA_256_CODE = 0x12;
function encodeCID(version, code, multihash) {
    const codeOffset = varint.encodingLength(version);
    const hashOffset = codeOffset + varint.encodingLength(code);
    const bytes = new Uint8Array(hashOffset + multihash.byteLength);
    varint.encodeTo(version, bytes, 0);
    varint.encodeTo(code, bytes, codeOffset);
    bytes.set(multihash, hashOffset);
    return bytes;
}
const cidSymbol = Symbol.for('@ipld/js-cid/CID');
//# sourceMappingURL=cid.js.mapimport { coerce } from '../bytes.js';
export const name = 'raw';
export const code = 0x55;
export function encode(node) {
    return coerce(node);
}
export function decode(data) {
    return coerce(data);
}
//# sourceMappingURL=raw.js.mapimport { coerce, equals as equalBytes } from '../bytes.js';
import * as varint from '../varint.js';
/**
 * Creates a multihash digest.
 */
export function create(code, digest) {
    const size = digest.byteLength;
    const sizeOffset = varint.encodingLength(code);
    const digestOffset = sizeOffset + varint.encodingLength(size);
    const bytes = new Uint8Array(digestOffset + size);
    varint.encodeTo(code, bytes, 0);
    varint.encodeTo(size, bytes, sizeOffset);
    bytes.set(digest, digestOffset);
    return new Digest(code, size, digest, bytes);
}
/**
 * Turns bytes representation of multihash digest into an instance.
 */
export function decode(multihash) {
    const bytes = coerce(multihash);
    const [code, sizeOffset] = varint.decode(bytes);
    const [size, digestOffset] = varint.decode(bytes.subarray(sizeOffset));
    const digest = bytes.subarray(sizeOffset + digestOffset);
    if (digest.byteLength !== size) {
        throw new Error('Incorrect length');
    }
    return new Digest(code, size, digest, bytes);
}
export function equals(a, b) {
    if (a === b) {
        return true;
    }
    else {
        const data = b;
        return (a.code === data.code &&
            a.size === data.size &&
            data.bytes instanceof Uint8Array &&
            equalBytes(a.bytes, data.bytes));
    }
}
/**
 * Represents a multihash digest which carries information about the
 * hashing algorithm and an actual hash digest.
 */
export class Digest {
    code;
    size;
    digest;
    bytes;
    /**
     * Creates a multihash digest.
     */
    constructor(code, size, digest, bytes) {
        this.code = code;
        this.size = size;
        this.digest = digest;
        this.bytes = bytes;
    }
}
/**
 * Used to check that the passed multihash has the passed code
 */
export function hasCode(digest, code) {
    return digest.code === code;
}
//# sourceMappingURL=digest.js.mapexport {};
//# sourceMappingURL=interface.js.mapimport varint from './vendor/varint.js';
export function decode(data, offset = 0) {
    const code = varint.decode(data, offset);
    return [code, varint.decode.bytes];
}
export function encodeTo(int, target, offset = 0) {
    varint.encode(int, target, offset);
    return target;
}
export function encodingLength(int) {
    return varint.encodingLength(int);
}
//# sourceMappingURL=varint.js.map/* eslint-disable */
// base-x encoding / decoding
// Copyright (c) 2018 base-x contributors
// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)
// Distributed under the MIT software license, see the accompanying
// file LICENSE or http://www.opensource.org/licenses/mit-license.php.
/**
 * @param {string} ALPHABET
 * @param {any} name
 */
function base(ALPHABET, name) {
    if (ALPHABET.length >= 255) {
        throw new TypeError('Alphabet too long');
    }
    var BASE_MAP = new Uint8Array(256);
    for (var j = 0; j < BASE_MAP.length; j++) {
        BASE_MAP[j] = 255;
    }
    for (var i = 0; i < ALPHABET.length; i++) {
        var x = ALPHABET.charAt(i);
        var xc = x.charCodeAt(0);
        if (BASE_MAP[xc] !== 255) {
            throw new TypeError(x + ' is ambiguous');
        }
        BASE_MAP[xc] = i;
    }
    var BASE = ALPHABET.length;
    var LEADER = ALPHABET.charAt(0);
    var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up
    var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up
    /**
     * @param {any[] | Iterable<number>} source
     */
    function encode(source) {
        // @ts-ignore
        if (source instanceof Uint8Array)
            ;
        else if (ArrayBuffer.isView(source)) {
            source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
        }
        else if (Array.isArray(source)) {
            source = Uint8Array.from(source);
        }
        if (!(source instanceof Uint8Array)) {
            throw new TypeError('Expected Uint8Array');
        }
        if (source.length === 0) {
            return '';
        }
        // Skip & count leading zeroes.
        var zeroes = 0;
        var length = 0;
        var pbegin = 0;
        var pend = source.length;
        while (pbegin !== pend && source[pbegin] === 0) {
            pbegin++;
            zeroes++;
        }
        // Allocate enough space in big-endian base58 representation.
        var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;
        var b58 = new Uint8Array(size);
        // Process the bytes.
        while (pbegin !== pend) {
            var carry = source[pbegin];
            // Apply "b58 = b58 * 256 + ch".
            var i = 0;
            for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {
                carry += (256 * b58[it1]) >>> 0;
                b58[it1] = (carry % BASE) >>> 0;
                carry = (carry / BASE) >>> 0;
            }
            if (carry !== 0) {
                throw new Error('Non-zero carry');
            }
            length = i;
            pbegin++;
        }
        // Skip leading zeroes in base58 result.
        var it2 = size - length;
        while (it2 !== size && b58[it2] === 0) {
            it2++;
        }
        // Translate the result into a string.
        var str = LEADER.repeat(zeroes);
        for (; it2 < size; ++it2) {
            str += ALPHABET.charAt(b58[it2]);
        }
        return str;
    }
    /**
     * @param {string | string[]} source
     */
    function decodeUnsafe(source) {
        if (typeof source !== 'string') {
            throw new TypeError('Expected String');
        }
        if (source.length === 0) {
            return new Uint8Array();
        }
        var psz = 0;
        // Skip leading spaces.
        if (source[psz] === ' ') {
            return;
        }
        // Skip and count leading '1's.
        var zeroes = 0;
        var length = 0;
        while (source[psz] === LEADER) {
            zeroes++;
            psz++;
        }
        // Allocate enough space in big-endian base256 representation.
        var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.
        var b256 = new Uint8Array(size);
        // Process the characters.
        while (source[psz]) {
            // Decode character
            var carry = BASE_MAP[source.charCodeAt(psz)];
            // Invalid character
            if (carry === 255) {
                return;
            }
            var i = 0;
            for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {
                carry += (BASE * b256[it3]) >>> 0;
                b256[it3] = (carry % 256) >>> 0;
                carry = (carry / 256) >>> 0;
            }
            if (carry !== 0) {
                throw new Error('Non-zero carry');
            }
            length = i;
            psz++;
        }
        // Skip trailing spaces.
        if (source[psz] === ' ') {
            return;
        }
        // Skip leading zeroes in b256.
        var it4 = size - length;
        while (it4 !== size && b256[it4] === 0) {
            it4++;
        }
        var vch = new Uint8Array(zeroes + (size - it4));
        var j = zeroes;
        while (it4 !== size) {
            vch[j++] = b256[it4++];
        }
        return vch;
    }
    /**
     * @param {string | string[]} string
     */
    function decode(string) {
        var buffer = decodeUnsafe(string);
        if (buffer) {
            return buffer;
        }
        throw new Error(`Non-${name} character`);
    }
    return {
        encode: encode,
        decodeUnsafe: decodeUnsafe,
        decode: decode
    };
}
var src = base;
var _brrp__multiformats_scope_baseX = src;
export default _brrp__multiformats_scope_baseX;
//# sourceMappingURL=base-x.js.map/* eslint-disable */
var encode_1 = encode;
var MSB = 0x80, REST = 0x7F, MSBALL = ~REST, INT = Math.pow(2, 31);
/**
 * @param {number} num
 * @param {number[]} out
 * @param {number} offset
 */
function encode(num, out, offset) {
    out = out || [];
    offset = offset || 0;
    var oldOffset = offset;
    while (num >= INT) {
        out[offset++] = (num & 0xFF) | MSB;
        num /= 128;
    }
    while (num & MSBALL) {
        out[offset++] = (num & 0xFF) | MSB;
        num >>>= 7;
    }
    out[offset] = num | 0;
    // @ts-ignore
    encode.bytes = offset - oldOffset + 1;
    return out;
}
var decode = read;
var MSB$1 = 0x80, REST$1 = 0x7F;
/**
 * @param {string | any[]} buf
 * @param {number} offset
 */
function read(buf, offset) {
    var res = 0, offset = offset || 0, shift = 0, counter = offset, b, l = buf.length;
    do {
        if (counter >= l) {
            // @ts-ignore
            read.bytes = 0;
            throw new RangeError('Could not decode varint');
        }
        b = buf[counter++];
        res += shift < 28
            ? (b & REST$1) << shift
            : (b & REST$1) * Math.pow(2, shift);
        shift += 7;
    } while (b >= MSB$1);
    // @ts-ignore
    read.bytes = counter - offset;
    return res;
}
var N1 = Math.pow(2, 7);
var N2 = Math.pow(2, 14);
var N3 = Math.pow(2, 21);
var N4 = Math.pow(2, 28);
var N5 = Math.pow(2, 35);
var N6 = Math.pow(2, 42);
var N7 = Math.pow(2, 49);
var N8 = Math.pow(2, 56);
var N9 = Math.pow(2, 63);
var length = function (/** @type {number} */ value) {
    return (value < N1 ? 1
        : value < N2 ? 2
            : value < N3 ? 3
                : value < N4 ? 4
                    : value < N5 ? 5
                        : value < N6 ? 6
                            : value < N7 ? 7
                                : value < N8 ? 8
                                    : value < N9 ? 9
                                        : 10);
};
var varint = {
    encode: encode_1,
    decode: decode,
    encodingLength: length
};
var _brrp_varint = varint;
export default _brrp_varint;
//# sourceMappingURL=varint.js.map{
  "name": "multiformats",
  "version": "13.4.2",
  "description": "Interface for multihash, multicodec, multibase and CID",
  "author": "Mikeal Rogers <mikeal.rogers@gmail.com> (https://www.mikealrogers.com/)",
  "license": "Apache-2.0 OR MIT",
  "homepage": "https://github.com/multiformats/js-multiformats#readme",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/multiformats/js-multiformats.git"
  },
  "bugs": {
    "url": "https://github.com/multiformats/js-multiformats/issues"
  },
  "publishConfig": {
    "access": "public",
    "provenance": true
  },
  "keywords": [
    "ipfs",
    "ipld",
    "multiformats"
  ],
  "type": "module",
  "types": "./dist/src/index.d.ts",
  "typesVersions": {
    "*": {
      "*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ],
      "src/*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ]
    }
  },
  "files": [
    "src",
    "dist",
    "!dist/test",
    "!**/*.tsbuildinfo"
  ],
  "exports": {
    ".": {
      "types": "./dist/src/index.d.ts",
      "import": "./dist/src/index.js"
    },
    "./bases/base10": {
      "types": "./dist/src/bases/base10.d.ts",
      "import": "./dist/src/bases/base10.js"
    },
    "./bases/base16": {
      "types": "./dist/src/bases/base16.d.ts",
      "import": "./dist/src/bases/base16.js"
    },
    "./bases/base2": {
      "types": "./dist/src/bases/base2.d.ts",
      "import": "./dist/src/bases/base2.js"
    },
    "./bases/base256emoji": {
      "types": "./dist/src/bases/base256emoji.d.ts",
      "import": "./dist/src/bases/base256emoji.js"
    },
    "./bases/base32": {
      "types": "./dist/src/bases/base32.d.ts",
      "import": "./dist/src/bases/base32.js"
    },
    "./bases/base36": {
      "types": "./dist/src/bases/base36.d.ts",
      "import": "./dist/src/bases/base36.js"
    },
    "./bases/base58": {
      "types": "./dist/src/bases/base58.d.ts",
      "import": "./dist/src/bases/base58.js"
    },
    "./bases/base64": {
      "types": "./dist/src/bases/base64.d.ts",
      "import": "./dist/src/bases/base64.js"
    },
    "./bases/base8": {
      "types": "./dist/src/bases/base8.d.ts",
      "import": "./dist/src/bases/base8.js"
    },
    "./bases/identity": {
      "types": "./dist/src/bases/identity.d.ts",
      "import": "./dist/src/bases/identity.js"
    },
    "./bases/interface": {
      "types": "./dist/src/bases/interface.d.ts",
      "import": "./dist/src/bases/interface.js"
    },
    "./basics": {
      "types": "./dist/src/basics.d.ts",
      "import": "./dist/src/basics.js"
    },
    "./block": {
      "types": "./dist/src/block.d.ts",
      "import": "./dist/src/block.js"
    },
    "./block/interface": {
      "types": "./dist/src/block/interface.d.ts",
      "import": "./dist/src/block/interface.js"
    },
    "./bytes": {
      "types": "./dist/src/bytes.d.ts",
      "import": "./dist/src/bytes.js"
    },
    "./cid": {
      "types": "./dist/src/cid.d.ts",
      "import": "./dist/src/cid.js"
    },
    "./codecs/interface": {
      "types": "./dist/src/codecs/interface.d.ts",
      "import": "./dist/src/codecs/interface.js"
    },
    "./codecs/json": {
      "types": "./dist/src/codecs/json.d.ts",
      "import": "./dist/src/codecs/json.js"
    },
    "./codecs/raw": {
      "types": "./dist/src/codecs/raw.d.ts",
      "import": "./dist/src/codecs/raw.js"
    },
    "./hashes/digest": {
      "types": "./dist/src/hashes/digest.d.ts",
      "import": "./dist/src/hashes/digest.js"
    },
    "./hashes/hasher": {
      "types": "./dist/src/hashes/hasher.d.ts",
      "import": "./dist/src/hashes/hasher.js"
    },
    "./hashes/identity": {
      "types": "./dist/src/hashes/identity.d.ts",
      "import": "./dist/src/hashes/identity.js"
    },
    "./hashes/interface": {
      "types": "./dist/src/hashes/interface.d.ts",
      "import": "./dist/src/hashes/interface.js"
    },
    "./hashes/sha1": {
      "types": "./dist/types/src/hashes/sha1.d.ts",
      "browser": "./dist/src/hashes/sha1-browser.js",
      "import": "./dist/src/hashes/sha1.js"
    },
    "./hashes/sha2": {
      "types": "./dist/src/hashes/sha2.d.ts",
      "browser": "./dist/src/hashes/sha2-browser.js",
      "import": "./dist/src/hashes/sha2.js"
    },
    "./interface": {
      "types": "./dist/src/interface.d.ts",
      "import": "./dist/src/interface.js"
    },
    "./link": {
      "types": "./dist/src/link.d.ts",
      "import": "./dist/src/link.js"
    },
    "./link/interface": {
      "types": "./dist/src/link/interface.d.ts",
      "import": "./dist/src/link/interface.js"
    },
    "./traversal": {
      "types": "./dist/src/traversal.d.ts",
      "import": "./dist/src/traversal.js"
    }
  },
  "eslintConfig": {
    "extends": "ipfs",
    "parserOptions": {
      "project": true,
      "sourceType": "module"
    }
  },
  "release": {
    "branches": [
      "master"
    ],
    "plugins": [
      [
        "@semantic-release/commit-analyzer",
        {
          "preset": "conventionalcommits",
          "releaseRules": [
            {
              "breaking": true,
              "release": "major"
            },
            {
              "revert": true,
              "release": "patch"
            },
            {
              "type": "feat",
              "release": "minor"
            },
            {
              "type": "fix",
              "release": "patch"
            },
            {
              "type": "docs",
              "release": "patch"
            },
            {
              "type": "test",
              "release": "patch"
            },
            {
              "type": "deps",
              "release": "patch"
            },
            {
              "scope": "no-release",
              "release": false
            }
          ]
        }
      ],
      [
        "@semantic-release/release-notes-generator",
        {
          "preset": "conventionalcommits",
          "presetConfig": {
            "types": [
              {
                "type": "feat",
                "section": "Features"
              },
              {
                "type": "fix",
                "section": "Bug Fixes"
              },
              {
                "type": "chore",
                "section": "Trivial Changes"
              },
              {
                "type": "docs",
                "section": "Documentation"
              },
              {
                "type": "deps",
                "section": "Dependencies"
              },
              {
                "type": "test",
                "section": "Tests"
              }
            ]
          }
        }
      ],
      "@semantic-release/changelog",
      "@semantic-release/npm",
      "@semantic-release/github",
      [
        "@semantic-release/git",
        {
          "assets": [
            "CHANGELOG.md",
            "package.json"
          ]
        }
      ]
    ]
  },
  "scripts": {
    "clean": "aegir clean",
    "lint": "aegir lint",
    "build": "aegir build",
    "release": "aegir release",
    "docs": "aegir docs",
    "test": "npm run lint && npm run test:node && npm run test:chrome",
    "test:node": "aegir test -t node --cov",
    "test:chrome": "aegir test -t browser --cov",
    "test:chrome-webworker": "aegir test -t webworker",
    "test:firefox": "aegir test -t browser -- --browser firefox",
    "test:firefox-webworker": "aegir test -t webworker -- --browser firefox",
    "test:electron-main": "aegir test -t electron-main"
  },
  "devDependencies": {
    "@stablelib/sha256": "^2.0.0",
    "@stablelib/sha512": "^2.0.0",
    "@types/node": "^25.0.0",
    "aegir": "^47.0.7",
    "buffer": "^6.0.3",
    "cids": "^1.1.9",
    "crypto-hash": "^4.0.0"
  },
  "aegir": {
    "test": {
      "target": [
        "node",
        "browser"
      ]
    }
  },
  "browser": {
    "./hashes/sha1": "./dist/src/hashes/sha1-browser.js",
    "./dist/src/hashes/sha1.js": "./dist/src/hashes/sha1-browser.js",
    "./hashes/sha2": "./dist/src/hashes/sha2-browser.js",
    "./dist/src/hashes/sha2.js": "./dist/src/hashes/sha2-browser.js"
  }
}
{
  "name": "atproto-repo",
  "version": "0.0.1",
  "description": "Byte-exact atproto repo layer — CAR + DAG-CBOR + CID + MST — over Hypercore-friendly primitives. Verified against real relay-accepted repos.",
  "type": "module",
  "main": "lib/repo.js",
  "scripts": {
    "test": "brittle-node test/*.test.js",
    "postinstall": "node scripts/bare-deps.mjs"
  },
  "dependencies": {
    "@ipld/car": "^5.4.0",
    "@ipld/dag-cbor": "^9.2.1",
    "@noble/curves": "^1.9.7",
    "@noble/hashes": "^1.5.0",
    "multiformats": "^13.3.0"
  },
  "devDependencies": {
    "atproto-identity": "file:../atproto-identity",
    "brittle": "^4.0.2"
  }
}
// The store package owns the Holepunch substrate — so the corestore dependency resolves
// here (store/node_modules), and higher layers (pds) compose store abstractions without
// reaching for corestore directly.

import Corestore from 'corestore'

// A dir path (or an existing Corestore) -> a Corestore. Idempotent on an instance.
export function openCorestore (storage) {
  return isCorestore(storage) ? storage : new Corestore(storage)
}

// ⛔ NOT `instanceof`. That compares against ONE module instance's class object, and a nested
// node_modules tree routinely yields two copies of corestore — which is what bare-pack ships to the
// phone (…/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/corestore
// alongside the daemon's own). A store built by copy A then fails `instanceof` against copy B, and every
// discriminator here reads that as "not a store, therefore a PATH", so Corestore tried to path.join an
// OBJECT and the node died with `Cannot read properties of undefined (reading 'length')` — a message
// that names a JS idiom and no cause (hyper-social #40).
//
// It cannot reproduce on a workstation, where the tree is deduped to one copy. The environments differ
// in their module graph, not their code, so identity is the wrong question: a store is what it DOES.
// `get` + `namespace` + `replicate` are the surface every caller here uses and nothing else implements.
// The instanceof check stays as a fast path for the common single-copy case.
export function isCorestore (x) {
  if (!x || typeof x !== 'object') return false
  if (x instanceof Corestore) return true
  return typeof x.get === 'function' && typeof x.namespace === 'function' && typeof x.replicate === 'function'
}

export { Corestore }
// Firehose #commit frame — the atproto com.atproto.sync.subscribeRepos wire format.
//
// A frame = dag-cbor({t:'#commit', op:1})  ++  dag-cbor(body). Built to match millipds
// (repo_ops.py apply_writes) field-for-field. `seq` and `time` are firehose-server
// state supplied by the caller. `blocks` is a CAR (root = the new commit) of the
// changed blocks.

import * as dagCbor from '@ipld/dag-cbor'
import { writeCar } from 'atproto-repo/lib/repo.js'
import { commitCid } from 'atproto-repo/lib/commit.js'

// subscribeRepos frame = dag-cbor(header {t, op:1}) ++ dag-cbor(body). Each header is
// a constant byte prefix (dag-cbor canonicalises map order), so we emit/detect by it.
export const COMMIT_HEADER = dagCbor.encode({ t: '#commit', op: 1 })
export const IDENTITY_HEADER = dagCbor.encode({ t: '#identity', op: 1 })
export const ACCOUNT_HEADER = dagCbor.encode({ t: '#account', op: 1 })
export const SYNC_HEADER = dagCbor.encode({ t: '#sync', op: 1 })

function frame (header, body) {
  const bodyBytes = dagCbor.encode(body)
  const out = new Uint8Array(header.length + bodyBytes.length)
  out.set(header, 0)
  out.set(bodyBytes, header.length)
  return out
}

// Assemble a #commit frame from a RepoManager.applyWrite() result.
export async function commitFrame (write, { seq, time }) {
  const carBytes = await writeCar(write.commitCid, [write.commitBlock, ...write.newBlocks])
  return frame(COMMIT_HEADER, {
    ops: write.ops,
    seq,
    rev: write.rev,
    since: write.since,
    prev: null,
    repo: write.signedCommit.did,
    time,
    blobs: [],
    blocks: carBytes,
    commit: write.commitCid,
    rebase: false,
    tooBig: false,
    prevData: write.prevData
  })
}

// #identity — tells a relay a repo's handle/DID binding (needed for discovery).
export function identityFrame ({ seq, did, handle, time }) {
  const body = { seq, did, time }
  if (handle) body.handle = handle
  return frame(IDENTITY_HEADER, body)
}

// #account — repo hosting status (active true = "this PDS hosts this repo").
export function accountFrame ({ seq, did, active = true, status, time }) {
  const body = { seq, did, time, active }
  if (status) body.status = status
  return frame(ACCOUNT_HEADER, body)
}

// #sync (Sync 1.1) — tells a relay to RE-BASELINE the repo to `signedCommit` (re-anchor via
// getRepo) instead of applying incremental deltas. This is the sanctioned signal for a repo
// whose commit chain is discontinuous vs the relay's last-known state (e.g. a custodial→
// self-custody migration that re-authored the repo). `blocks` is a CAR carrying ONLY the
// commit block (root = its CID), ≤10KB. `rev`/`did` MUST match the commit object.
export async function syncFrame ({ seq, did, signedCommit, time }) {
  const cid = commitCid(signedCommit)
  const blocks = await writeCar(cid, [{ cid, bytes: dagCbor.encode(signedCommit) }])
  return frame(SYNC_HEADER, { seq, did, blocks, rev: signedCommit.rev, time })
}

const HEADERS = [['#commit', COMMIT_HEADER], ['#identity', IDENTITY_HEADER], ['#account', ACCOUNT_HEADER], ['#sync', SYNC_HEADER]]

// Re-stamp a frame's `seq` (relay egress): a relay aggregates many PDS firehoses and MUST
// present its own monotonic seq in each frame (the cursor contract). Decodes, replaces
// body.seq, re-encodes with the same header. Unknown frames pass through unchanged.
export function restampFrame (frameBytes, seq) {
  const d = decodeFrame(frameBytes)
  if (!d) return frameBytes
  const header = d.t === '#commit' ? COMMIT_HEADER : d.t === '#identity' ? IDENTITY_HEADER : d.t === '#account' ? ACCOUNT_HEADER : SYNC_HEADER
  d.body.seq = seq
  const bodyBytes = dagCbor.encode(d.body)
  const out = new Uint8Array(header.length + bodyBytes.length)
  out.set(header, 0)
  out.set(bodyBytes, header.length)
  return out
}

// Split + decode ANY known subscribeRepos frame → { t, body } (null if unknown).
export function decodeFrame (frameBytes) {
  for (const [t, header] of HEADERS) {
    if (frameBytes.length >= header.length &&
        Buffer.from(frameBytes.subarray(0, header.length)).equals(Buffer.from(header))) {
      return { t, body: dagCbor.decode(frameBytes.subarray(header.length)) }
    }
  }
  return null
}

// Split + decode a #commit frame. Returns { header, body } or null if not a #commit.
export function decodeCommitFrame (frameBytes) {
  const prefix = frameBytes.subarray(0, COMMIT_HEADER.length)
  if (!Buffer.from(prefix).equals(Buffer.from(COMMIT_HEADER))) return null
  return {
    header: { t: '#commit', op: 1 },
    body: dagCbor.decode(frameBytes.subarray(COMMIT_HEADER.length))
  }
}
// Bridge READ-view — pure functions turning RepoStore (Hyperbee) state into atproto
// wire responses (com.atproto.sync.* / repo.*). No HTTP here (that's the thin face,
// later); no storage-specific atproto state in the store. rev/prev are INPUTS — commit
// head-state (monotonic rev, prev-linking) advances on writes, which is the next slice.
//
// Curve note: the commit block carries our secp256k1 sig (millipds uses P-256), so the
// commit CID differs from millipds — but the MST + record blocks are curve-independent
// and byte-identical to millipds output (verified against the golden CAR).

import * as dagCbor from '@ipld/dag-cbor'
import { buildMst, reachableBlocks } from 'atproto-repo/lib/mst.js'
import { unsignedCommit, signCommit, commitCid } from 'atproto-repo/lib/commit.js'
import { cidForBytesSync } from 'atproto-repo/lib/cid.js'
import { writeCar } from 'atproto-repo/lib/repo.js'

// Build every block of the repo from the store's exact bytes (no re-encode).
async function assembleRepo (store, { did, rev, prev = null, privateKey }) {
  const recs = await store.records() // [{ key, bytes, record }]
  const recordBlocks = []
  const mstRecords = []
  for (const r of recs) {
    const cid = cidForBytesSync(r.bytes)
    recordBlocks.push({ cid, bytes: r.bytes })
    mstRecords.push({ key: r.key, value: cid })
  }
  const { root: dataCid, ns } = buildMst(mstRecords)
  const mstBlocks = [...reachableBlocks(ns, dataCid).values()]
  const signed = signCommit(unsignedCommit({ did, rev, data: dataCid, prev }), privateKey)
  const cCid = commitCid(signed)
  const commitBlock = { cid: cCid, bytes: dagCbor.encode(signed) }
  return { commitCid: cCid, dataCid, signedCommit: signed, commitBlock, mstBlocks, recordBlocks }
}

// com.atproto.sync.getRepo -> full CAR (commit + MST + records).
export async function getRepo (store, meta) {
  const r = await assembleRepo(store, meta)
  const carBytes = await writeCar(r.commitCid, [r.commitBlock, ...r.mstBlocks, ...r.recordBlocks])
  return { carBytes, commitCid: r.commitCid, dataCid: r.dataCid, signedCommit: r.signedCommit }
}

// KEYLESS getRepo (peer/bridge split): assemble the full CAR from the store's records + a
// PROVIDED signed commit — e.g. one a bridge read from a peer's replicated firehose. The
// MST/records are curve-independent so they rebuild without the key; the signature travels
// IN the commit, never re-derived. Integrity: the provided commit must commit to exactly
// these records (its data CID == the rebuilt MST root), else we refuse to serve a mismatched
// repo. Signature verification (vs the peer's did:key) is the caller's concern.
export async function getRepoFromCommit (store, signedCommit) {
  const recs = await store.records()
  const recordBlocks = []
  const mstRecords = []
  for (const r of recs) {
    const cid = cidForBytesSync(r.bytes)
    recordBlocks.push({ cid, bytes: r.bytes })
    mstRecords.push({ key: r.key, value: cid })
  }
  const { root: dataCid, ns } = buildMst(mstRecords)
  if (!dataCid.equals(signedCommit.data)) {
    throw new Error('getRepoFromCommit: signed commit data CID != rebuilt MST root (repo/commit mismatch)')
  }
  const cCid = commitCid(signedCommit)
  const commitBlock = { cid: cCid, bytes: dagCbor.encode(signedCommit) }
  const mstBlocks = [...reachableBlocks(ns, dataCid).values()]
  const carBytes = await writeCar(cCid, [commitBlock, ...mstBlocks, ...recordBlocks])
  return { carBytes, commitCid: cCid, dataCid }
}

// com.atproto.sync.getLatestCommit -> { cid, rev }.
export async function getLatestCommit (store, meta) {
  const r = await assembleRepo(store, meta)
  return { cid: r.commitCid.toString(), rev: r.signedCommit.rev }
}

// com.atproto.repo.getRecord -> { uri, cid, value }.
export async function getRecord (store, collection, rkey, { did }) {
  const raw = await store.getRaw(collection, rkey)
  if (!raw) return null
  return {
    uri: `at://${did}/${collection}/${rkey}`,
    cid: cidForBytesSync(raw.bytes).toString(),
    value: raw.record
  }
}

// com.atproto.repo.listRecords -> [{ uri, cid, value }] for a collection.
// com.atproto.repo.listRecords. `limit`, `reverse` and `cursor` were ACCEPTED AND IGNORED, so every
// caller silently got the whole collection in ascending order no matter what it asked for — a client
// paging our repo would loop forever on a cursor that never advanced, and one asking for the newest 10
// would get the oldest N thousand. Non-conformance that looks like success is the worst kind.
//
// The lexicon's contract, implemented here:
//   limit    1..100, default 50
//   reverse  true = DESCENDING rkey order (newest first for TID rkeys)
//   cursor   opaque; here it is the last rkey returned, and paging resumes STRICTLY after it
//   returns  { records, cursor } — cursor ABSENT when the page is the last one, which is how a client
//            knows to stop. Returning a cursor at the end is what makes a pager loop.
export async function listRecords (store, collection, { did, limit = 50, reverse = false, cursor = null } = {}) {
  const n = Math.min(100, Math.max(1, Number(limit) || 50))
  // store.list yields in ascending key (byte) order — the same order the MST uses.
  const all = []
  for await (const { rkey, record } of store.list(collection)) all.push({ rkey, record })
  if (reverse) all.reverse()
  let start = 0
  if (cursor) {
    // Resume strictly AFTER the cursor. `>` not `>=`, or the cursor row is returned twice and a pager
    // that dedupes by uri silently stalls instead of advancing.
    const i = all.findIndex((r) => r.rkey === cursor)
    start = i >= 0 ? i + 1 : all.length
  }
  const page = all.slice(start, start + n)
  const records = page.map(({ rkey, record }) => ({
    uri: `at://${did}/${collection}/${rkey}`,
    // NOTE: this CIDs a re-encode of the decoded record, not the stored bytes. A canonical DAG-CBOR
    // round-trip is byte-identical so this is correct today, but getRaw would be strictly safer — the
    // 2026-07-31 incidents were all re-encode-vs-canonical mismatches. Left as-is rather than widened
    // here; worth revisiting with a raw-bytes list().
    cid: cidForBytesSync(dagCbor.encode(record)).toString(),
    value: record
  }))
  const last = page.length ? page[page.length - 1].rkey : null
  // No cursor on the final page — its ABSENCE is the stop signal.
  const more = start + page.length < all.length
  return { records, cursor: more && last ? last : undefined }
}
// com.atproto.sync.getRepo?since — the PARTIAL CAR, assembled from the firehose.
//
// ⛔ WHAT `since` ACTUALLY MEANS. The lexicon calls it "the revision of the repo to create a diff from",
// and the reference PDS answers it by streaming every block whose creation rev is greater than `since`,
// rooted at the CURRENT commit. That is NOT a self-contained repo: the MST nodes that did not change are
// deliberately ABSENT, so the tree cannot be walked from the root without the blocks the caller is
// assumed to already hold. A consumer with a block store applies the diff and re-walks; a consumer
// without one CANNOT USE IT AT ALL. This distinction is the whole hazard in the feature and every
// surface here states which side it is on.
//
// WHY THE FIREHOSE AND NOT A BLOCK-REV INDEX. Our record store holds the CURRENT records and rebuilds
// the MST on demand (read-view.js:assembleRepo) — there is no per-block "created at rev" tag to filter
// on, and no historical MST to diff against. But every `#commit` frame ALREADY carries exactly the right
// bytes: `blocks` is a CAR of the blocks that were new at that commit (firehose.js:commitFrame). The
// union of those CARs over the frames newer than `since` IS the diff, by construction, with no new
// storage and no second source of truth. This is the "firehose range" spec/convergence.md §7 named.
//
// ⚠ A DIFF IS NOT NECESSARILY SMALLER, and the intuition that it must be is wrong here. A diff spanning
// N commits carries every INTERMEDIATE MST root; the full repo carries only the final one. On a small
// repo — favela's wj62 is 45 KB — a multi-commit diff can be the LARGER of the two. The saving appears
// only once the untouched part of the tree dwarfs the churn, which is precisely why spec/convergence.md
// §7 ranked this last. Nothing here should be sold as a size optimisation for a small repo.
//
// ⚠ COVERAGE IS PROVEN, NEVER ASSUMED. A firehose that does not reach back to `since` cannot produce a
// complete diff, and a diff missing its middle is far worse than no diff — the caller would apply it,
// see a valid-looking commit, and hold a repo with a hole. So `covered` is only ever true when we have
// POSITIVE evidence: either a frame at or older than `since` (proof we hold that history), or a genesis
// frame (proof there is no earlier history to hold). Anything else falls back to the full CAR and says
// so, out loud, rather than serving a diff it cannot justify.

import { readCar, writeCar } from 'atproto-repo/lib/repo.js'
import { decodeFrame } from './firehose.js'

// TIDs are lexicographically ordered by construction, so string comparison IS rev comparison. Used
// throughout this stack (favela-web's head check does the same) — stated here so nobody "fixes" it into
// a numeric parse.
const newer = (a, b) => String(a) > String(b)

// Read frames BACKWARD from the end of a firehose until we have both (a) every #commit newer than
// `since` and (b) the proof of coverage described above. Bounded by the number of commits since that
// rev plus one — never a full-history scan, which matters on a repo with thousands of frames.
//
// getFrame(i) -> frame bytes for the 0-based index i. length = the number of frames.
export async function collectFramesSince ({ getFrame, length, since }) {
  const newerFrames = []   // #commit bodies with rev > since, OLDEST FIRST
  let covered = false
  let anchorRev = null     // the rev we are diffing FROM, once proven
  for (let i = length - 1; i >= 0; i--) {
    let d = null
    try { d = decodeFrame(await getFrame(i)) } catch { d = null }
    if (!d || d.t !== '#commit' || !d.body || !d.body.rev) continue
    if (newer(d.body.rev, since)) { newerFrames.unshift(d.body); continue }
    // A frame at or older than `since`: we demonstrably hold history reaching back that far.
    covered = true
    anchorRev = d.body.rev
    break
  }
  // The scan ran off the front of the firehose without finding an older frame. The oldest frame we DO
  // have still carries the rev it built on, in its own `since` field — and that is enough to decide.
  //
  // ⚠ There is no "first frame has no since" case to lean on here, though it reads like the obvious one.
  // RepoManager.init() mints an EMPTY genesis commit and persists it as the head WITHOUT sequencing it,
  // so the first frame a repo ever emits already has a real `since` pointing at that unsequenced commit.
  // A genesis heuristic written against the lexicon rather than against this producer is dead code.
  if (!covered && newerFrames.length) {
    const base = newerFrames[0].since
    if (base === null || base === undefined) {
      // ⛔ FROM-GENESIS IS REFUSED, and this is a size argument rather than a correctness one.
      //
      // The oldest frame we hold declares NO prior state, so the union of every frame is complete and
      // walkable on its own — this branch used to serve it. Measured on prod 2026-08-07 (wj62, whose
      // firehose genuinely starts with a null `since` after its re-authoring): that answer was
      // **202,262 bytes / 719 blocks** against **46,106 bytes / 224 blocks** for the full repo. 4.4x
      // LARGER, for the same 168 records.
      //
      // That is not a fixture artefact, it is structural: the union from genesis contains every block
      // the repo has EVER held — every superseded MST node and every deleted record — so it is
      // ALWAYS a superset of the current repo. A from-genesis diff can therefore never beat the full
      // CAR, and refusing hands the caller the smaller, simpler, complete answer they actually wanted.
      //
      // Deliberately NOT `covered = true`. My unit fixture never reached this branch (RepoManager.init
      // mints an unsequenced genesis commit, so a synthetic repo's first frame carries a real `since`)
      // and only a live repo exposed it. See the test named for exactly that.
      return { frames: newerFrames, covered: false, anchorRev: null, reason: 'from-genesis' }
    } else if (!newer(base, since)) {
      // The oldest frame we hold builds on a state at or BEFORE what the caller has. There is no commit
      // between the two, so nothing is missing from the middle.
      covered = true
      anchorRev = base
    }
    // Otherwise `base` is NEWER than the caller's rev: at least one commit sits between their state and
    // our oldest frame, and we do not have it. Refuse — the caller gets the full CAR instead. This is
    // also what a `since` from before the repo existed hits, which is correct: we cannot prove our
    // firehose reaches the repo's first write rather than having been truncated, and the full repo is
    // the right answer to "give me everything" anyway.
  }
  return { frames: newerFrames, covered, anchorRev }
}

// Union the `blocks` CARs of the given #commit frames into ONE CAR rooted at `headCommit`.
//
// Deduped by CID: a block touched by three commits appears once. Returns null when the head block is
// neither in the frames nor supplied — the caller must then LOCATE it (findCommitBlock) or refuse,
// because a CAR rooted at a commit nobody carries cannot be walked by anyone.
export async function unionDiffCar ({ frames, headCommitCid, headCommitBytes = null }) {
  const blocks = new Map() // cidStr -> { cid, bytes }
  for (const body of frames) {
    if (!body || !body.blocks) continue
    let car = null
    try { car = await readCar(body.blocks) } catch { continue }
    for (const [cidStr, block] of car.blocks) if (!blocks.has(cidStr)) blocks.set(cidStr, block)
  }
  const headStr = headCommitCid.toString()
  if (!blocks.has(headStr)) {
    if (!headCommitBytes) return null // caller must locate it; see findCommitBlock
    blocks.set(headStr, { cid: headCommitCid, bytes: headCommitBytes })
  }
  const carBytes = await writeCar(headCommitCid, [...blocks.values()])
  return { carBytes, blocks: blocks.size }
}

// Find a commit block BY CID inside the firehose, newest frame first.
//
// ⛔ THE HEAD BLOCK IS NEVER SYNTHESISED. It would be easy to hand `dagCbor.encode(head.signed)` in from
// the front and root the CAR at that — and it would also mean serving a CAR rooted at a commit the
// firehose does not actually carry, which cannot be walked even by a caller holding everything else. So
// the block is LOCATED in the frames instead. That the search can fail is the point: a head the firehose
// never carried is a refusal, not a block we invent. It also removes any need for a dag-cbor dependency
// in the front.
export async function findCommitBlock ({ getFrame, length, cid, scanLimit = 64 }) {
  const want = cid.toString()
  const stop = Math.max(0, length - scanLimit)
  for (let i = length - 1; i >= stop; i--) {
    let d = null
    try { d = decodeFrame(await getFrame(i)) } catch { continue }
    if (!d || d.t !== '#commit' || !d.body || !d.body.blocks) continue
    try {
      const car = await readCar(d.body.blocks)
      const hit = car.blocks.get(want)
      if (hit) return hit
    } catch { continue }
  }
  return null
}

// The whole operation: firehose + a verified head -> a partial CAR, or an honest refusal.
//
// Returns { ok, carBytes, blocks, fromRev, toRev, reason }. `ok: false` means DO NOT SERVE A DIFF — the
// caller must fall back to the full CAR and report that `since` was not honoured. It never throws for a
// coverage problem, because "I cannot answer that" is a normal answer here, not an error.
export async function repoDiffSince ({ getFrame, length, since, headCommitCid, headCommitBytes = null, headRev }) {
  if (!since) return { ok: false, reason: 'no since given' }
  if (!length) return { ok: false, reason: 'firehose is empty — no history to diff from' }
  const c = await collectFramesSince({ getFrame, length, since })
  const { frames, covered, anchorRev } = c
  if (!covered) {
    return {
      ok: false,
      reason: c.reason === 'from-genesis'
        ? 'since predates the firehose start — a from-genesis diff is always a superset of the full repo, so the full CAR is smaller and complete'
        : 'firehose does not reach back to rev ' + since + ' — cannot prove the diff is complete'
    }
  }
  // The head block, located in the firehose rather than supplied. `headCommitBytes` remains accepted so a
  // caller that legitimately holds the bytes (a test, or a producer assembling its own commit) can pass
  // them, but the normal path finds them.
  const locate = async () => headCommitBytes
    ? { cid: headCommitCid, bytes: headCommitBytes }
    : await findCommitBlock({ getFrame, length, cid: headCommitCid })
  // `since` is at or ahead of our head: nothing has changed that the caller does not have. The correct
  // answer is a CAR carrying the commit alone — an EMPTY diff, which is a real answer and not an error.
  if (!frames.length) {
    const head = await locate()
    if (!head) return { ok: false, reason: 'the verified head commit is not carried by this firehose' }
    const car = await unionDiffCar({ frames: [], headCommitCid, headCommitBytes: head.bytes })
    return { ok: true, ...car, fromRev: anchorRev, toRev: headRev || null, empty: true }
  }
  // The head we serve must be the head these frames build up to. If the front's verified head is NEWER
  // than the last frame we have, the firehose we are reading is behind it and the diff would be rooted
  // at a commit whose blocks are not in the union — a CAR that cannot be walked even WITH the caller's
  // prior state. Refuse rather than emit it.
  const lastRev = frames[frames.length - 1].rev
  if (headRev && newer(headRev, lastRev)) {
    return { ok: false, reason: 'verified head (' + headRev + ') is ahead of the firehose tail (' + lastRev + ')' }
  }
  let car = await unionDiffCar({ frames, headCommitCid, headCommitBytes })
  if (!car) {
    // The frames did not carry the head block. Look for it before giving up — then refuse rather than
    // synthesise one, because a CAR rooted at a commit this firehose never carried is unwalkable for
    // everyone, including a caller holding every other block.
    const head = await locate()
    if (!head) return { ok: false, reason: 'the verified head commit is not carried by this firehose' }
    car = await unionDiffCar({ frames, headCommitCid, headCommitBytes: head.bytes })
  }
  return { ok: true, ...car, fromRev: anchorRev, toRev: lastRev, empty: false }
}
// RepoStore — the Holepunch-native home for an atproto repo.
//
// Records live in a CLASSIC Hyperbee (matches our production stack — NOT hyperbee2/
// autobee, which are experimental; see the ecosystem audit): key = `collection/rkey`,
// value = the record's canonical DAG-CBOR bytes. Single-writer (one author key);
// multi-device is handled by sharing the mnemonic-derived key. The atproto-repo
// module is the *bridge* that reads this store and emits MST/CAR/commits on demand —
// this layer stores nothing atproto-specific beyond the records themselves.

import Corestore from 'corestore'
import { isCorestore } from './corestore.js'
import Hyperbee from 'hyperbee'
import * as dagCbor from '@ipld/dag-cbor'
import b4a from 'b4a'

// Range upper bound for a `collection/` prefix scan. '/' (0x2f) + 1 = '0' (0x30),
// and all atproto rkey chars sort >= '2' > '/', so `collection/…` < `collection0`.
function prefixUpper (prefix) {
  return prefix.slice(0, -1) + String.fromCharCode(prefix.charCodeAt(prefix.length - 1) + 1)
}

export class RepoStore {
  constructor (storage, opts = {}) {
    // Behavioural check, NOT `instanceof` — a second copy of corestore in a bundled tree makes a real
    // store look like a path and Corestore then path.join()s an object. See lib/corestore.js.
    this._ownStore = !isCorestore(storage)
    this._store = this._ownStore ? new Corestore(storage) : storage
    this._name = opts.name || 'atproto-repo'
    this._key = opts.key || null // open a specific core by KEY (a replica of another instance's repo)
    this.bee = null
    this.core = null
  }

  static key (collection, rkey) { return `${collection}/${rkey}` }

  // The underlying Corestore — so the PDS can open sibling cores (e.g. the firehose
  // sequence log) on the SAME store rather than a second Corestore over the same dir.
  get corestore () { return this._store }

  async ready () {
    // By KEY = replicate another instance's repo (read-only over the swarm); by NAME = our own.
    this.core = this._key ? this._store.get({ key: this._key }) : this._store.get({ name: this._name })
    await this.core.ready()
    // alwaysDuplicate:false enables Hyperbee's byte-identical value-dedup — a re-put of an unchanged
    // (key,value) becomes a no-op READ instead of appending a fresh B-tree path. Without it (the default
    // TRUE), redundant puts (e.g. a projection re-putting the whole record set on a timer) balloon this
    // append-only core to millions of dead blocks. Defense-in-depth under every caller.
    this.bee = new Hyperbee(this.core, { keyEncoding: 'utf-8', valueEncoding: 'binary', alwaysDuplicate: false })
    await this.bee.ready()
    return this
  }

  async put (collection, rkey, record) {
    await this.bee.put(RepoStore.key(collection, rkey), b4a.from(dagCbor.encode(record)))
  }

  async get (collection, rkey) {
    const node = await this.bee.get(RepoStore.key(collection, rkey))
    return node ? dagCbor.decode(node.value) : null
  }

  // Raw stored bytes + decoded record (the bridge CIDs the exact bytes).
  async getRaw (collection, rkey) {
    const node = await this.bee.get(RepoStore.key(collection, rkey))
    return node ? { bytes: node.value, record: dagCbor.decode(node.value) } : null
  }

  async del (collection, rkey) {
    await this.bee.del(RepoStore.key(collection, rkey))
  }

  // Yield { rkey, record } for one collection, in key order.
  async * list (collection) {
    const gte = `${collection}/`
    const lt = prefixUpper(gte)
    for await (const node of this.bee.createReadStream({ gte, lt })) {
      yield { rkey: node.key.slice(gte.length), record: dagCbor.decode(node.value) }
    }
  }

  // All records as { key, bytes, record } in key order. `bytes` is the canonical
  // DAG-CBOR — the bridge CIDs these directly to build the MST (byte-exact).
  async records () {
    const out = []
    for await (const node of this.bee.createReadStream()) {
      out.push({ key: node.key, bytes: node.value, record: dagCbor.decode(node.value) })
    }
    return out
  }

  // Persist the commit head ({ rev, commitCid, dataCid }) as core USER DATA — NOT a record,
  // so it never appears in records()/the MST. This is what makes the head stable across a
  // restart: the rev is restored, not re-minted (which would forge a phantom commit).
  async saveHead (head) {
    await this.core.setUserData('atproto-head', b4a.from(JSON.stringify(head)))
  }

  async loadHead () {
    const v = await this.core.getUserData('atproto-head')
    return v ? JSON.parse(b4a.toString(v)) : null
  }

  async close () {
    if (this.bee) await this.bee.close()
    if (this._ownStore) await this._store.close()
  }
}
// FirehoseSequencer — the atproto firehose as a Hypercore.
//
// Each subscribeRepos message (a framed dag-cbor #commit/#identity/#account) is one
// append to a single-writer Hypercore; the block index + 1 IS the atproto `seq`
// (1-based, monotonic). `subscribe(cursor)` replays persisted frames with seq > cursor
// then live-tails — so a freshly-attached relay gets full history from cursor=0 (the
// fix for the non-archival-relay root cause, POSTMORTEM.md §Federation).
//
// This is both the atproto sequenced-firehose model and the P2P-native thesis: the
// firehose is not a side-channel, it's a replicable append-only log.

import { commitFrame, identityFrame, accountFrame } from './firehose.js'

export class FirehoseSequencer {
  constructor (core) { this.core = core } // a Hypercore, binary values

  async ready () { await this.core.ready(); return this }
  get length () { return this.core.length }        // == the latest seq
  async close () { await this.core.close() }

  // Append a pre-framed message; returns its 1-based seq.
  async append (frameBytes) {
    const seq = this.core.length + 1
    await this.core.append(frameBytes)
    return seq
  }

  // Sequence a #commit: assign the seq FIRST (frame body carries it), then append.
  async sequenceCommit (write, { time }) {
    const seq = this.core.length + 1
    const frame = await commitFrame(write, { seq, time })
    await this.core.append(frame)
    return { seq, frame }
  }

  async sequenceIdentity ({ did, handle, time }) {
    const seq = this.core.length + 1
    const frame = identityFrame({ seq, did, handle, time })
    await this.core.append(frame)
    return { seq, frame }
  }

  async sequenceAccount ({ did, active = true, status, time }) {
    const seq = this.core.length + 1
    const frame = accountFrame({ seq, did, active, status, time })
    await this.core.append(frame)
    return { seq, frame }
  }

  // Async iterator over { seq, bytes }: backfill frames with seq > cursor, then
  // live-tail new appends. cursor is the last seq the consumer holds (0/absent =
  // from the start). Pass an AbortSignal to stop (WS disconnect).
  async * subscribe (cursor = 0, { signal } = {}) {
    let next = Math.max(0, cursor | 0) // seq > cursor  <=>  index >= cursor
    while (true) {
      if (signal && signal.aborted) return
      if (next < this.core.length) {
        const bytes = await this.core.get(next)
        yield { seq: next + 1, bytes }
        next++
        continue
      }
      // caught up — wait for the next append (or abort)
      await new Promise((resolve) => {
        const onAppend = () => { cleanup(); resolve() }
        const onAbort = () => { cleanup(); resolve() }
        const cleanup = () => {
          this.core.off('append', onAppend)
          if (signal) signal.removeEventListener('abort', onAbort)
        }
        this.core.on('append', onAppend)
        if (signal) signal.addEventListener('abort', onAbort, { once: true })
      })
      if (signal && signal.aborted) return
    }
  }
}
const { Pull, Push, HEADERBYTES, KEYBYTES, ABYTES } = require('sodium-secretstream')
const sodium = require('sodium-universal')
const crypto = require('hypercore-crypto')
const { Duplex, Writable, getStreamError } = require('streamx')
const b4a = require('b4a')
const Timeout = require('timeout-refresh')
const unslab = require('unslab')
const Bridge = require('./lib/bridge')
const Handshake = require('./lib/handshake')

const IDHEADERBYTES = HEADERBYTES + 32
const [NS_INITIATOR, NS_RESPONDER, NS_SEND] = crypto.namespace('hyperswarm/secret-stream', 3)
const MAX_ATOMIC_WRITE = 256 * 256 * 256 - 1

module.exports = class NoiseSecretStream extends Duplex {
  constructor(isInitiator, rawStream, opts = {}) {
    super({ mapWritable: toBuffer })

    if (typeof isInitiator !== 'boolean') {
      throw new Error('isInitiator should be a boolean')
    }

    this.noiseStream = this
    this.isInitiator = isInitiator
    this.rawStream = null

    this.publicKey = opts.publicKey || null
    this.remotePublicKey = opts.remotePublicKey || null
    this.handshakeHash = null
    this.connected = false
    this.keepAlive = opts.keepAlive || 0
    this.timeout = 0
    this.enableSend = opts.enableSend !== false

    // pointer for upstream to set data here if they want
    this.userData = null

    let openedDone = null
    this.opened = new Promise((resolve) => {
      openedDone = resolve
    })

    this.rawBytesWritten = 0
    this.rawBytesRead = 0

    // metadata used by 'hyperdht'
    this.relay = null
    this.puncher = null

    // unwrapped raw stream
    this._rawStream = null

    // handshake state
    this._handshake = null
    this._handshakePattern = opts.pattern || null
    this._handshakeDone = null

    // message parsing state
    this._state = 0
    this._len = 0
    this._tmp = 1
    this._message = null

    this._openedDone = openedDone
    this._startDone = null
    this._drainDone = null
    this._outgoingPlain = null
    this._outgoingWrapped = null
    this._utp = null
    this._setup = true
    this._ended = 2
    this._encrypt = null
    this._decrypt = null
    this._timeoutTimer = null
    this._keepAliveTimer = null
    this._sendState = null

    if (opts.autoStart !== false) this.start(rawStream, opts)

    // wiggle it to trigger open immediately (TODO add streamx option for this)
    this.resume()
    this.pause()
  }

  static keyPair(seed) {
    return Handshake.keyPair(seed)
  }

  static id(handshakeHash, isInitiator, id) {
    return streamId(handshakeHash, isInitiator, id)
  }

  setTimeout(ms) {
    if (!ms) ms = 0

    this._clearTimeout()
    this.timeout = ms

    if (!ms || this.rawStream === null) return

    this._timeoutTimer = Timeout.once(ms, destroyTimeout, this)
    this._timeoutTimer.unref()
  }

  setKeepAlive(ms) {
    if (!ms) ms = 0

    this._clearKeepAlive()

    this.keepAlive = ms

    if (!ms || this.rawStream === null) return

    this._keepAliveTimer = Timeout.on(ms, sendKeepAlive, this)
    this._keepAliveTimer.unref()
  }

  sendKeepAlive() {
    const empty = this.alloc(0)
    this.write(empty)
  }

  start(rawStream, opts = {}) {
    if (rawStream) {
      this.rawStream = rawStream
      this._rawStream = rawStream
      if (typeof this.rawStream.setContentSize === 'function') {
        this._utp = rawStream
      }
    } else {
      this.rawStream = new Bridge(this)
      this._rawStream = this.rawStream.reverse
    }

    this.rawStream.on('error', this._onrawerror.bind(this))
    this.rawStream.on('close', this._onrawclose.bind(this))

    this._startHandshake(opts.handshake, opts.keyPair || null)
    this._continueOpen(null)

    if (this.destroying) return

    if (opts.data) this._onrawdata(opts.data)
    if (opts.ended) this._onrawend()

    if (this.keepAlive > 0 && this._keepAliveTimer === null) {
      this.setKeepAlive(this.keepAlive)
    }

    if (this.timeout > 0 && this._timeoutTimer === null) {
      this.setTimeout(this.timeout)
    }
  }

  async flush() {
    if ((await this.opened) === false) return false
    if ((await Writable.drained(this)) === false) return false
    if (this.destroying) return false

    if (this.rawStream !== null && this.rawStream.flush) {
      return await this.rawStream.flush()
    }

    return true
  }

  _continueOpen(err) {
    if (err) this.destroy(err)
    if (this._startDone === null) return
    const done = this._startDone
    this._startDone = null
    this._open(done)
  }

  _onkeypairpromise(p) {
    const self = this
    const cont = this._continueOpen.bind(this)

    p.then(onkeypair, cont)

    function onkeypair(kp) {
      self._onkeypair(kp)
      cont(null)
    }
  }

  _onkeypair(keyPair) {
    const pattern = this._handshakePattern || 'XX'
    const remotePublicKey = this.remotePublicKey

    this._handshake = new Handshake(this.isInitiator, keyPair, remotePublicKey, pattern)
    this.publicKey = this._handshake.keyPair.publicKey
  }

  _startHandshake(handshake, keyPair) {
    if (handshake) {
      const { tx, rx, hash, publicKey, remotePublicKey } = handshake
      this._setupSecretStream(tx, rx, hash, publicKey, remotePublicKey)
      return
    }

    if (!keyPair) keyPair = Handshake.keyPair()

    if (typeof keyPair.then === 'function') {
      this._onkeypairpromise(keyPair)
    } else {
      this._onkeypair(keyPair)
    }
  }

  _onrawerror(err) {
    this.destroy(err)
  }

  _onrawclose() {
    if (this._ended !== 0) this.destroy()
  }

  _onrawdata(data) {
    let offset = 0

    if (this._timeoutTimer !== null) {
      this._timeoutTimer.refresh()
    }

    do {
      switch (this._state) {
        case 0: {
          while (this._tmp !== 0x1000000 && offset < data.byteLength) {
            const v = data[offset++]
            this._len += this._tmp * v
            this._tmp *= 256
          }

          if (this._tmp === 0x1000000) {
            this._tmp = 0
            this._state = 1
            const unprocessed = data.byteLength - offset
            if (unprocessed < this._len && this._utp !== null)
              this._utp.setContentSize(this._len - unprocessed)
          }

          break
        }

        case 1: {
          const missing = this._len - this._tmp
          const end = missing + offset

          if (this._message === null && end <= data.byteLength) {
            this._message = data.subarray(offset, end)
            offset += missing
            this._incoming()
            break
          }

          const unprocessed = data.byteLength - offset

          if (this._message === null) {
            this._message = b4a.allocUnsafe(this._len)
          }

          b4a.copy(data, this._message, this._tmp, offset)
          this._tmp += unprocessed

          if (end <= data.byteLength) {
            offset += missing
            this._incoming()
          } else {
            offset += unprocessed
          }

          break
        }
      }
    } while (offset < data.byteLength && !this.destroying)
  }

  _onrawend() {
    this._ended--
    this.push(null)
  }

  _onrawdrain() {
    const drain = this._drainDone
    if (drain === null) return
    this._drainDone = null
    drain()
  }

  _read(cb) {
    this.rawStream.resume()
    cb(null)
  }

  _incoming() {
    const message = this._message

    this._state = 0
    this._len = 0
    this._tmp = 1
    this._message = null

    if (this._setup === true) {
      if (this._handshake) {
        this._onhandshakert(this._handshake.recv(message))
      } else {
        if (message.byteLength !== IDHEADERBYTES) {
          this.destroy(new Error('Invalid header message received'))
          return
        }

        const remoteId = message.subarray(0, 32)
        const expectedId = streamId(this.handshakeHash, !this.isInitiator)
        const header = message.subarray(32)

        if (!b4a.equals(expectedId, remoteId)) {
          this.destroy(new Error('Invalid header received'))
          return
        }

        this._decrypt.init(header)
        this._setup = false // setup is now done
      }
      return
    }

    if (message.byteLength < ABYTES) {
      this.destroy(new Error('Invalid message received'))
      return
    }

    this.rawBytesRead += message.byteLength

    const plain = message.subarray(1, message.byteLength - ABYTES + 1)

    try {
      this._decrypt.next(message, plain)
    } catch (err) {
      this.destroy(err)
      return
    }

    // If keep alive is selective, eat the empty buffers (ie assume the other side has it enabled also)
    if (plain.byteLength === 0 && this.keepAlive !== 0) return

    if (this.push(plain) === false) {
      this.rawStream.pause()
    }
  }

  _onhandshakert(h) {
    if (this._handshakeDone === null) return

    if (h !== null) {
      if (h.data) this._rawStream.write(h.data)
      if (!h.tx) return
    }

    const done = this._handshakeDone
    const publicKey = this._handshake.keyPair.publicKey

    this._handshakeDone = null
    this._handshake = null

    if (h === null) return done(new Error('Noise handshake failed'))

    this._setupSecretStream(h.tx, h.rx, h.hash, publicKey, h.remotePublicKey)
    this._resolveOpened(true)
    done(null)
  }

  _setupSecretStream(tx, rx, handshakeHash, publicKey, remotePublicKey) {
    const buf = b4a.allocUnsafeSlow(3 + IDHEADERBYTES)
    writeUint24le(IDHEADERBYTES, buf)

    this._encrypt = new Push(unslab(tx.subarray(0, KEYBYTES)), undefined, buf.subarray(3 + 32))
    this._decrypt = new Pull(unslab(rx.subarray(0, KEYBYTES)))

    this.publicKey = publicKey
    this.remotePublicKey = remotePublicKey
    this.handshakeHash = handshakeHash

    const id = buf.subarray(3, 3 + 32)
    streamId(handshakeHash, this.isInitiator, id)

    // initialize secretbox state for unordered messages
    this._setupSecretSend(handshakeHash)

    this.emit('handshake')
    // if rawStream is a bridge, also emit it there
    if (this.rawStream !== this._rawStream) this.rawStream.emit('handshake')

    if (this.destroying) return

    this._rawStream.write(buf)
  }

  _setupSecretSend(handshakeHash) {
    this._sendState = b4a.allocUnsafeSlow(32 + 32 + 8 + 8)
    const encrypt = this._sendState.subarray(0, 32) // secrets
    const decrypt = this._sendState.subarray(32, 64)
    const counter = this._sendState.subarray(64, 72) // nonce
    const initial = this._sendState.subarray(72)

    const inputs = this.isInitiator
      ? [
          [NS_INITIATOR, NS_SEND],
          [NS_RESPONDER, NS_SEND]
        ]
      : [
          [NS_RESPONDER, NS_SEND],
          [NS_INITIATOR, NS_SEND]
        ]

    sodium.crypto_generichash_batch(encrypt, inputs[0], handshakeHash)
    sodium.crypto_generichash_batch(decrypt, inputs[1], handshakeHash)

    sodium.randombytes_buf(initial)
    counter.set(initial)
  }

  _open(cb) {
    // no autostart or no handshake yet
    if (this._rawStream === null || (this._handshake === null && this._encrypt === null)) {
      this._startDone = cb
      return
    }

    this._rawStream.on('data', this._onrawdata.bind(this))
    this._rawStream.on('end', this._onrawend.bind(this))
    this._rawStream.on('drain', this._onrawdrain.bind(this))

    if (this.enableSend) this._rawStream.on('message', this._onmessage.bind(this))

    if (this._encrypt !== null) {
      this._resolveOpened(true)
      return cb(null)
    }

    this._handshakeDone = cb

    if (this.isInitiator) this._onhandshakert(this._handshake.send())
  }

  _predestroy() {
    if (this.rawStream) {
      const error = getStreamError(this)
      this.rawStream.destroy(error)
    }

    if (this._startDone !== null) {
      const done = this._startDone
      this._startDone = null
      done(new Error('Stream destroyed'))
    }

    if (this._handshakeDone !== null) {
      const done = this._handshakeDone
      this._handshakeDone = null
      done(new Error('Stream destroyed'))
    }

    if (this._drainDone !== null) {
      const done = this._drainDone
      this._drainDone = null
      done(new Error('Stream destroyed'))
    }
  }

  _write(data, cb) {
    let wrapped = this._outgoingWrapped

    if (data !== this._outgoingPlain) {
      wrapped = b4a.allocUnsafe(data.byteLength + 3 + ABYTES)
      wrapped.set(data, 4)
    } else {
      this._outgoingWrapped = this._outgoingPlain = null
    }

    if (wrapped.byteLength - 3 > MAX_ATOMIC_WRITE) {
      return cb(
        new Error(
          'Message is too large for an atomic write. Max size is ' + MAX_ATOMIC_WRITE + ' bytes.'
        )
      )
    }
    this.rawBytesWritten += wrapped.byteLength

    writeUint24le(wrapped.byteLength - 3, wrapped)
    // offset 4 so we can do it in-place
    this._encrypt.next(wrapped.subarray(4, 4 + data.byteLength), wrapped.subarray(3))

    if (this._keepAliveTimer !== null) this._keepAliveTimer.refresh()

    if (this._rawStream.write(wrapped) === false) {
      this._drainDone = cb
    } else {
      cb(null)
    }
  }

  _final(cb) {
    this._clearKeepAlive()
    this._ended--
    this._rawStream.end()
    cb(null)
  }

  _resolveOpened(val) {
    if (this._openedDone === null) return
    const opened = this._openedDone
    this._openedDone = null
    opened(val)
    if (!val) return
    this.connected = true
    this.emit('connect')
  }

  _clearTimeout() {
    if (this._timeoutTimer === null) return
    this._timeoutTimer.destroy()
    this._timeoutTimer = null
    this.timeout = 0
  }

  _clearKeepAlive() {
    if (this._keepAliveTimer === null) return
    this._keepAliveTimer.destroy()
    this._keepAliveTimer = null
    this.keepAlive = 0
  }

  _destroy(cb) {
    this._clearKeepAlive()
    this._clearTimeout()
    this._resolveOpened(false)
    cb(null)
  }

  _boxMessage(buffer) {
    const MB = sodium.crypto_secretbox_MACBYTES // 16
    const NB = sodium.crypto_secretbox_NONCEBYTES // 24

    const counter = this._sendState.subarray(64, 72)
    sodium.sodium_increment(counter)
    if (b4a.equals(counter, this._sendState.subarray(72))) {
      this.destroy(new Error('udp send nonce exchausted'))
      return
    }

    const secret = this._sendState.subarray(0, 32)
    const envelope = b4a.allocUnsafe(8 + MB + buffer.byteLength)
    const nonce = envelope.subarray(0, NB)
    const ciphertext = envelope.subarray(8)

    b4a.fill(nonce, 0) // pad suffix
    nonce.set(counter)

    sodium.crypto_secretbox_easy(ciphertext, buffer, nonce, secret)
    return envelope
  }

  send(buffer) {
    if (!this._sendState) return
    if (!this.rawStream?.send) return // udx-stream expected

    const message = this._boxMessage(buffer)
    return this.rawStream.send(message)
  }

  trySend(buffer) {
    if (!this._sendState) return
    if (!this.rawStream?.trySend) return // udx-stream expected

    const message = this._boxMessage(buffer)
    this.rawStream.trySend(message)
  }

  _onmessage(buffer) {
    if (!this._sendState) return // messages before handshake are dropped

    const MB = sodium.crypto_secretbox_MACBYTES // 16
    const NB = sodium.crypto_secretbox_NONCEBYTES // 24

    if (buffer.byteLength < NB) return // Invalid message

    const nonce = b4a.allocUnsafe(NB)
    b4a.fill(nonce, 0)
    nonce.set(buffer.subarray(0, 8))

    const secret = this._sendState.subarray(32, 64)
    const ciphertext = buffer.subarray(8)
    const plain = buffer.subarray(8, buffer.byteLength - MB)

    if (ciphertext.byteLength < MB) return // invalid message

    const success = sodium.crypto_secretbox_open_easy(plain, ciphertext, nonce, secret)

    if (success) this.emit('message', plain)
  }

  alloc(len) {
    const buf = b4a.allocUnsafe(len + 3 + ABYTES)
    this._outgoingWrapped = buf
    this._outgoingPlain = buf.subarray(4, buf.byteLength - ABYTES + 1)
    return this._outgoingPlain
  }

  toJSON() {
    return {
      isInitiator: this.isInitiator,
      publicKey: this.publicKey && b4a.toString(this.publicKey, 'hex'),
      remotePublicKey: this.remotePublicKey && b4a.toString(this.remotePublicKey, 'hex'),
      connected: this.connected,
      destroying: this.destroying,
      destroyed: this.destroyed,
      rawStream: this.rawStream && this.rawStream.toJSON ? this.rawStream.toJSON() : null
    }
  }
}

function writeUint24le(n, buf) {
  buf[0] = n & 255
  buf[1] = (n >>> 8) & 255
  buf[2] = (n >>> 16) & 255
}

function streamId(handshakeHash, isInitiator, out = b4a.allocUnsafe(32)) {
  sodium.crypto_generichash(out, isInitiator ? NS_INITIATOR : NS_RESPONDER, handshakeHash)
  return out
}

function toBuffer(data) {
  return typeof data === 'string' ? b4a.from(data) : data
}

function destroyTimeout() {
  this.destroy(new Error('Stream timed out'))
}

function sendKeepAlive() {
  const empty = this.alloc(0)
  this.write(empty)
}
const { Duplex, Writable } = require('streamx')

class ReversePassThrough extends Duplex {
  constructor(s) {
    super()
    this._stream = s
    this._ondrain = null
  }

  _write(data, cb) {
    if (this._stream.push(data) === false) {
      this._stream._ondrain = cb
    } else {
      cb(null)
    }
  }

  _final(cb) {
    this._stream.push(null)
    cb(null)
  }

  _read(cb) {
    const ondrain = this._ondrain
    this._ondrain = null
    if (ondrain) ondrain()
    cb(null)
  }
}

module.exports = class Bridge extends Duplex {
  constructor(noiseStream) {
    super()

    this.noiseStream = noiseStream

    this._ondrain = null
    this.reverse = new ReversePassThrough(this)
  }

  get publicKey() {
    return this.noiseStream.publicKey
  }

  get remotePublicKey() {
    return this.noiseStream.remotePublicKey
  }

  get handshakeHash() {
    return this.noiseStream.handshakeHash
  }

  flush() {
    return Writable.drained(this)
  }

  _read(cb) {
    const ondrain = this._ondrain
    this._ondrain = null
    if (ondrain) ondrain()
    cb(null)
  }

  _write(data, cb) {
    if (this.reverse.push(data) === false) {
      this.reverse._ondrain = cb
    } else {
      cb(null)
    }
  }

  _final(cb) {
    this.reverse.push(null)
    cb(null)
  }
}
const sodium = require('sodium-universal')
const curve = require('noise-curve-ed')
const Noise = require('noise-handshake')
const b4a = require('b4a')

const EMPTY = b4a.alloc(0)

module.exports = class Handshake {
  constructor(isInitiator, keyPair, remotePublicKey, pattern) {
    this.isInitiator = isInitiator
    this.keyPair = keyPair
    this.noise = new Noise(pattern, isInitiator, keyPair, { curve })
    this.noise.initialise(EMPTY, remotePublicKey)
    this.destroyed = false
  }

  static keyPair(seed) {
    const publicKey = b4a.alloc(32)
    const secretKey = b4a.alloc(64)
    if (seed) sodium.crypto_sign_seed_keypair(publicKey, secretKey, seed)
    else sodium.crypto_sign_keypair(publicKey, secretKey)
    return { publicKey, secretKey }
  }

  recv(data) {
    try {
      this.noise.recv(data)
      if (this.noise.complete) return this._return(null)
      return this.send()
    } catch {
      this.destroy()
      return null
    }
  }

  // note that the data returned here is framed so we don't have to do an extra copy
  // when sending it...
  send() {
    try {
      const data = this.noise.send()
      const wrap = b4a.allocUnsafe(data.byteLength + 3)

      writeUint24le(data.byteLength, wrap)
      wrap.set(data, 3)

      return this._return(wrap)
    } catch {
      this.destroy()
      return null
    }
  }

  destroy() {
    if (this.destroyed) return
    this.destroyed = true
  }

  _return(data) {
    const tx = this.noise.complete ? b4a.toBuffer(this.noise.tx) : null
    const rx = this.noise.complete ? b4a.toBuffer(this.noise.rx) : null
    const hash = this.noise.complete ? b4a.toBuffer(this.noise.hash) : null
    const remotePublicKey = this.noise.complete ? b4a.toBuffer(this.noise.rs) : null

    return {
      data,
      remotePublicKey,
      hash,
      tx,
      rx
    }
  }
}

function writeUint24le(n, buf) {
  buf[0] = n & 255
  buf[1] = (n >>> 8) & 255
  buf[2] = (n >>> 16) & 255
}
{
  "name": "@hyperswarm/secret-stream",
  "version": "6.9.1",
  "description": "Secret stream backed by Noise and libsodium's secretstream",
  "main": "index.js",
  "files": [
    "index.js",
    "lib/**.js"
  ],
  "dependencies": {
    "b4a": "^1.1.0",
    "hypercore-crypto": "^3.3.1",
    "noise-curve-ed": "^2.0.1",
    "noise-handshake": "^4.0.0",
    "sodium-secretstream": "^1.1.0",
    "sodium-universal": "^5.0.0",
    "streamx": "^2.14.0",
    "timeout-refresh": "^2.0.0",
    "unslab": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "udx-native": "^1.13.2"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check .",
    "test": "brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/hyperswarm-secret-stream.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/hyperswarm-secret-stream/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperswarm-secret-stream"
}
{
  "name": "@ipld/dag-cbor",
  "version": "9.2.7",
  "description": "JS implementation of DAG-CBOR",
  "author": "Rod <rod@vagg.org> (http://r.va.gg/)",
  "license": "Apache-2.0 OR MIT",
  "homepage": "https://github.com/ipld/js-dag-cbor#readme",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/ipld/js-dag-cbor.git"
  },
  "bugs": {
    "url": "https://github.com/ipld/js-dag-cbor/issues"
  },
  "publishConfig": {
    "access": "public",
    "provenance": true
  },
  "keywords": [
    "ipfs",
    "ipld",
    "multiformats"
  ],
  "type": "module",
  "types": "./dist/src/index.d.ts",
  "typesVersions": {
    "*": {
      "*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ],
      "src/*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ]
    }
  },
  "files": [
    "src",
    "dist",
    "!dist/test",
    "!**/*.tsbuildinfo"
  ],
  "exports": {
    ".": {
      "types": "./dist/src/index.d.ts",
      "import": "./src/index.js",
      "module-sync": "./src/index.js"
    }
  },
  "release": {
    "branches": [
      "master"
    ],
    "plugins": [
      [
        "@semantic-release/commit-analyzer",
        {
          "preset": "conventionalcommits",
          "releaseRules": [
            {
              "breaking": true,
              "release": "major"
            },
            {
              "revert": true,
              "release": "patch"
            },
            {
              "type": "feat",
              "release": "minor"
            },
            {
              "type": "fix",
              "release": "patch"
            },
            {
              "type": "docs",
              "release": "patch"
            },
            {
              "type": "test",
              "release": "patch"
            },
            {
              "type": "deps",
              "release": "patch"
            },
            {
              "scope": "no-release",
              "release": false
            }
          ]
        }
      ],
      [
        "@semantic-release/release-notes-generator",
        {
          "preset": "conventionalcommits",
          "presetConfig": {
            "types": [
              {
                "type": "feat",
                "section": "Features"
              },
              {
                "type": "fix",
                "section": "Bug Fixes"
              },
              {
                "type": "chore",
                "section": "Trivial Changes"
              },
              {
                "type": "docs",
                "section": "Documentation"
              },
              {
                "type": "deps",
                "section": "Dependencies"
              },
              {
                "type": "test",
                "section": "Tests"
              }
            ]
          }
        }
      ],
      "@semantic-release/changelog",
      "@semantic-release/npm",
      "@semantic-release/github",
      [
        "@semantic-release/git",
        {
          "assets": [
            "CHANGELOG.md",
            "package.json"
          ]
        }
      ]
    ]
  },
  "scripts": {
    "clean": "aegir clean",
    "lint": "aegir lint",
    "build": "aegir build",
    "release": "aegir release",
    "test": "npm run lint && aegir test",
    "test:ts": "npm run test --prefix test/ts-use",
    "test:node": "aegir test -t node --cov",
    "test:chrome": "aegir test -t browser --cov",
    "test:chrome-webworker": "aegir test -t webworker",
    "test:firefox": "aegir test -t browser -- --browser firefox",
    "test:firefox-webworker": "aegir test -t webworker -- --browser firefox",
    "test:electron-main": "aegir test -t electron-main",
    "dep-check": "aegir dep-check"
  },
  "dependencies": {
    "cborg": "^5.0.1",
    "multiformats": "^13.1.0"
  },
  "devDependencies": {
    "@ipld/garbage": "^6.0.0",
    "aegir": "^48.0.1"
  }
}
import * as cborg from 'cborg'
import { CID } from 'multiformats/cid'

// https://github.com/ipfs/go-ipfs/issues/3570#issuecomment-273931692
const CID_CBOR_TAG = 42

/**
 * @template T
 * @typedef {import('multiformats/codecs/interface').ByteView<T>} ByteView
 */

/**
 * @template T
 * @typedef {import('multiformats/codecs/interface').ArrayBufferView<T>} ArrayBufferView
 */

/**
 * @template T
 * @param {ByteView<T> | ArrayBufferView<T>} buf
 * @returns {ByteView<T>}
 */
export function toByteView (buf) {
  if (buf instanceof ArrayBuffer) {
    return new Uint8Array(buf, 0, buf.byteLength)
  }

  return buf
}

/**
 * cidEncoder will receive all Objects during encode, it needs to filter out
 * anything that's not a CID and return `null` for that so it's encoded as
 * normal.
 *
 * @param {any} obj
 * @returns {cborg.Token[]|null}
 */
function cidEncoder (obj) {
  if (obj.asCID !== obj && obj['/'] !== obj.bytes) {
    return null // any other kind of object
  }
  const cid = CID.asCID(obj)
  /* c8 ignore next 4 */
  // very unlikely case, and it'll probably throw a recursion error in cborg
  if (!cid) {
    return null
  }
  const bytes = new Uint8Array(cid.bytes.byteLength + 1)
  bytes.set(cid.bytes, 1) // prefix is 0x00, for historical reasons
  return [
    new cborg.Token(cborg.Type.tag, CID_CBOR_TAG),
    new cborg.Token(cborg.Type.bytes, bytes)
  ]
}

// eslint-disable-next-line jsdoc/require-returns-check
/**
 * Intercept all `undefined` values from an object walk and reject the entire
 * object if we find one.
 *
 * @returns {null}
 */
function undefinedEncoder () {
  throw new Error('`undefined` is not supported by the IPLD Data Model and cannot be encoded')
}

/**
 * Intercept all `number` values from an object walk and reject the entire
 * object if we find something that doesn't fit the IPLD data model (NaN &
 * Infinity).
 *
 * @param {number} num
 * @returns {null}
 */
function numberEncoder (num) {
  if (Number.isNaN(num)) {
    throw new Error('`NaN` is not supported by the IPLD Data Model and cannot be encoded')
  }
  if (num === Infinity || num === -Infinity) {
    throw new Error('`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded')
  }
  return null
}

/**
 * @param {Map<any, any>} map
 * @returns {null}
 */
function mapEncoder (map) {
  for (const key of map.keys()) {
    if (typeof key !== 'string' || key.length === 0) {
      throw new Error('Non-string Map keys are not supported by the IPLD Data Model and cannot be encoded')
    }
  }
  return null
}

const _encodeOptions = {
  float64: true,
  typeEncoders: {
    Map: mapEncoder,
    Object: cidEncoder,
    undefined: undefinedEncoder,
    number: numberEncoder
  }
}

export const encodeOptions = {
  ..._encodeOptions,
  typeEncoders: {
    ..._encodeOptions.typeEncoders
  }
}

/**
 * @param {import('cborg').TagDecodeControl} decode
 * @returns {CID}
 */
function cidDecoder (decode) {
  const bytes = /** @type {Uint8Array} */ (decode())
  if (bytes[0] !== 0) {
    throw new Error('Invalid CID for CBOR tag 42; expected leading 0x00')
  }
  return CID.decode(bytes.subarray(1)) // ignore leading 0x00
}

const _decodeOptions = {
  allowIndefinite: false,
  coerceUndefinedToNull: true,
  allowNaN: false,
  allowInfinity: false,
  allowBigInt: true, // this will lead to BigInt for ints outside of
  // safe-integer range, which may surprise users
  strict: true,
  useMaps: false,
  rejectDuplicateMapKeys: true,
  /** @type {{ [tagNumber: number]: import('cborg').TagDecoder }} */
  tags: { [CID_CBOR_TAG]: cidDecoder }
}

export const decodeOptions = {
  ..._decodeOptions,
  tags: { ..._decodeOptions.tags }
}

export const name = 'dag-cbor'
export const code = 0x71

/**
 * @template T
 * @param {T} node
 * @returns {ByteView<T>}
 */
export const encode = (node) => cborg.encode(node, _encodeOptions)

/**
 * @template T
 * @param {ByteView<T> | ArrayBufferView<T>} data
 * @returns {T}
 */
export const decode = (data) => cborg.decode(toByteView(data), _decodeOptions)
// Minimal CAR v1 codec — bare-safe, dependency-light replacement for @ipld/car.
//
// CAR v1 is a trivial container: varint(headerLen) ++ dag-cbor({version:1, roots:[…]})
// then, per block, varint(len) ++ CIDbytes ++ blockBytes. We only need whole-buffer
// read/write (no streaming, no file I/O), so this is ~40 lines of pure JS over
// multiformats' CID (byte-exact with @ipld/car — verified by the repo tests + the
// @atproto/repo conformance reader). Drops @ipld/car (which imports `fs`/streams and
// won't load under Bare).
//
// ⚠️ LIMITATIONS vs @ipld/car (tracked in memory: bare-car-limitations). Fine for our
// current use (whole-buffer, CARv1, OUR-OWN trusted output); add the feature before the
// gate it guards:
//   - No streaming — whole CAR is buffered in memory. GATE: large repos (getRepo of a
//     big repo could be GBs). Add an async-iterator read/write path.
//   - No untrusted-input hardening — readCar trusts varints/lengths/CIDs. GATE: reading
//     UNTRUSTED CARs (com.atproto.repo.importRepo, ingress bridge). Add bounds/overflow/
//     truncation checks + duplicate-CID handling before then.
//   - CARv1 only (no CARv2/index). atproto is CARv1, so no gate today.
// Fully-featured path: grow this file at each gate, OR extract a standalone bare-native
// `bare-car` package (the holepunch ecosystem lacks one — a real contribution).

import { CID } from 'multiformats/cid'
import * as dagCbor from '@ipld/dag-cbor'

function varintEncode (n) {
  const out = []
  while (n >= 0x80) { out.push((n & 0x7f) | 0x80); n >>>= 7 }
  out.push(n)
  return Uint8Array.from(out)
}

function varintDecode (bytes, offset) {
  let n = 0; let shift = 0; let i = offset
  for (;;) {
    const b = bytes[i++]
    n |= (b & 0x7f) << shift
    if ((b & 0x80) === 0) break
    shift += 7
  }
  return [n >>> 0, i]
}

// Serialise { root, blocks } to CAR bytes. `blocks` is an iterable of { cid, bytes }.
export async function writeCar (rootCid, blocks) {
  const header = dagCbor.encode({ version: 1, roots: [rootCid] })
  const parts = [Buffer.from(varintEncode(header.length)), Buffer.from(header)]
  for (const { cid, bytes } of blocks) {
    const cidBytes = cid.bytes
    const body = new Uint8Array(cidBytes.length + bytes.length)
    body.set(cidBytes, 0)
    body.set(bytes, cidBytes.length)
    parts.push(Buffer.from(varintEncode(body.length)), Buffer.from(body))
  }
  return Buffer.concat(parts)
}

// Read a CAR into { roots, blocks } where blocks maps cid-string -> { cid, bytes }.
export async function readCar (carBytes) {
  const bytes = carBytes instanceof Uint8Array ? carBytes : new Uint8Array(carBytes)
  let [hlen, off] = varintDecode(bytes, 0)
  const header = dagCbor.decode(bytes.subarray(off, off + hlen))
  off += hlen
  const blocks = new Map()
  while (off < bytes.length) {
    const [blen, bodyStart] = varintDecode(bytes, off)
    const end = bodyStart + blen
    const [cid, rest] = CID.decodeFirst(bytes.subarray(bodyStart, end))
    blocks.set(cid.toString(), { cid, bytes: rest })
    off = end
  }
  return { roots: header.roots, blocks }
}
// atproto block CIDs — CIDv1, dag-cbor codec (0x71), sha2-256 multihash (0x12).
// Every block in a repo (commit, MST node, record) is content-addressed this way,
// so computeCid(dag-cbor(block)) IS the block's identity. This is the anchor for
// byte-exact fidelity: if our re-encoded bytes hash to the same CID the reference
// produced, our encoding is byte-identical.

import { CID } from 'multiformats/cid'
import * as Digest from 'multiformats/hashes/digest'
import { sha256 as nobleSha256 } from '@noble/hashes/sha2'
import * as dagCbor from '@ipld/dag-cbor'
import * as raw from 'multiformats/codecs/raw'

// raw block bytes -> CID. Uses noble's pure-JS sha256 (same as the sync path) rather
// than multiformats' `crypto.subtle` path — identical CID, and no WebCrypto dependency
// (so it loads + runs under Bare, which has no crypto.subtle).
export async function cidForBytes (bytes) {
  return cidForBytesSync(bytes)
}

// Synchronous variant — needed by the recursive MST build. Same result as
// cidForBytes (CIDv1 / dag-cbor 0x71 / sha2-256 0x12), just without the async
// WebCrypto digest.
export function cidForBytesSync (bytes) {
  const digest = Digest.create(0x12, nobleSha256(bytes)) // 0x12 = sha2-256 multihash code
  return CID.createV1(dagCbor.code, digest)
}

// BLOB CID — CIDv1, RAW codec (0x55), sha2-256. atproto blobs (images/avatars) are
// content-addressed with the raw codec (opaque bytes), NOT dag-cbor. This is the CID that
// goes in a blob ref ({$type:'blob', ref:{$link:<this>}, mimeType, size}) and the key
// com.atproto.sync.getBlob serves by.
export function cidForBlobSync (bytes) {
  const digest = Digest.create(0x12, nobleSha256(bytes))
  return CID.createV1(raw.code, digest)
}

// a JS value -> its canonical dag-cbor bytes + CID
export async function cidForValue (value) {
  const bytes = dagCbor.encode(value)
  return { bytes, cid: await cidForBytes(bytes) }
}
// atproto repo commit — sign + verify.
//
// A commit is { did, version: 3, data: <MST root CID>, rev, prev, sig }. The
// signature is ECDSA-secp256k1 (low-S) over sha256(dag-cbor(unsignedCommit)), stored
// as a raw 64-byte CBOR byte string (NOT base64url — that's the did:plc genesis).
// The relay validates this sig against the DID doc's verificationMethod.

import * as dagCbor from '@ipld/dag-cbor'
import { sha256 as nobleSha256 } from '@noble/hashes/sha2'
import { secp256k1 } from '@noble/curves/secp256k1'
import { cidForBytesSync } from './cid.js'

export const REPO_VERSION = 3

// The unsigned commit (everything the signature covers).
export function unsignedCommit ({ did, rev, data, prev = null }) {
  return { did, version: REPO_VERSION, data, rev, prev }
}

// Sign an unsigned commit -> signed commit with `sig` (64 raw bytes).
export function signCommit (unsigned, privateKey) {
  const hash = nobleSha256(dagCbor.encode(unsigned))
  const sig = secp256k1.sign(hash, privateKey, { lowS: true }).toCompactRawBytes()
  return { ...unsigned, sig }
}

export function commitCid (signedCommit) {
  return cidForBytesSync(dagCbor.encode(signedCommit))
}

// Verify a signed commit against a compressed secp256k1 pubkey (33 bytes).
export function verifyCommit (signedCommit, publicKey) {
  const { sig, ...unsigned } = signedCommit
  const hash = nobleSha256(dagCbor.encode(unsigned))
  return secp256k1.verify(sig, hash, publicKey, { lowS: true })
}
// atproto MST — WRITE path (slice 2).
//
// A faithful port of millipds's `atmst` (mst/node.py + node_wrangler.py) — the exact
// code that produced our golden CAR. Byte-exactness is verified two ways: rebuilding
// the golden repo's MST, and matching atmst's own root CIDs for a multi-height tree
// (build + delete oracles). See test/mst-write.test.js.
//
// Node shape (interleaved): subtrees[0], (keys[0],vals[0]), subtrees[1], … ,subtrees[n].
// key layer = leading-zero BITS of sha256(key), // 2 (fanout 4).

import * as dagCbor from '@ipld/dag-cbor'
import { sha256 as nobleSha256 } from '@noble/hashes/sha2'
import { cidForBytesSync } from './cid.js'

const cidEq = (a, b) => (a === null || b === null) ? a === b : a.equals(b)
const replaceAt = (arr, i, v) => { const c = arr.slice(); c[i] = v; return c }
const insertAt = (arr, i, v) => arr.slice(0, i).concat([v], arr.slice(i))
const removeAt = (arr, i) => arr.slice(0, i).concat(arr.slice(i + 1))

export function keyHeight (key) {
  const h = nobleSha256(Buffer.from(key, 'utf8')) // 32 bytes
  let zeros = 0
  for (const byte of h) {
    if (byte === 0) { zeros += 8; continue }
    zeros += Math.clz32(byte) - 24 // leading zero bits within this byte
    break
  }
  return zeros >> 1 // // 2
}

export class MSTNode {
  constructor (keys, vals, subtrees) {
    this.keys = keys // [string]
    this.vals = vals // [CID]
    this.subtrees = subtrees // [CID|null], length keys.length + 1
  }

  static empty () { return new MSTNode([], [], [null]) }

  isEmpty () { return this.keys.length === 0 && this.subtrees.length === 1 && this.subtrees[0] === null }

  serialise () {
    const e = []
    let prevKey = Buffer.alloc(0)
    for (let i = 0; i < this.keys.length; i++) {
      const keyBytes = Buffer.from(this.keys[i], 'utf8')
      const max = Math.min(prevKey.length, keyBytes.length)
      let p = 0
      while (p < max && prevKey[p] === keyBytes[p]) p++
      e.push({ k: keyBytes.subarray(p), p, t: this.subtrees[i + 1], v: this.vals[i] })
      prevKey = keyBytes
    }
    return dagCbor.encode({ e, l: this.subtrees[0] }) // dag-cbor canonicalises map key order
  }

  cid () { return cidForBytesSync(this.serialise()) }

  toOptional () { return this.isEmpty() ? null : this.cid() }

  gteIndex (key) { let i = 0; while (i < this.keys.length && key > this.keys[i]) i++; return i }

  height () {
    if (this.keys.length) return keyHeight(this.keys[0])
    if (this.subtrees[0] === null) return 0
    return null // indeterminate (empty intermediate node)
  }

  static deserialise (bytes) {
    const cbor = dagCbor.decode(bytes)
    const subtrees = [cbor.l]
    const keys = []
    const vals = []
    let prevKey = Buffer.alloc(0)
    for (const e of cbor.e) {
      const suffix = Buffer.from(e.k)
      const thisKey = Buffer.concat([prevKey.subarray(0, e.p), suffix])
      keys.push(thisKey.toString('utf8'))
      vals.push(e.v)
      subtrees.push(e.t)
      prevKey = thisKey
    }
    return new MSTNode(keys, vals, subtrees)
  }
}

// In-memory node store — maps CID string -> { cid, bytes }. get(null) returns the
// (stored) empty node, matching atmst NodeStore.get_node(None).
export class NodeStore {
  constructor () { this.blocks = new Map() }

  storedNode (node) {
    const bytes = node.serialise()
    const cid = cidForBytesSync(bytes)
    this.blocks.set(cid.toString(), { cid, bytes })
    return node
  }

  getNode (cid) {
    if (cid === null || cid === undefined) return this.storedNode(MSTNode.empty())
    const b = this.blocks.get(cid.toString())
    if (!b) throw new Error(`missing MST node ${cid}`)
    return MSTNode.deserialise(b.bytes)
  }
}

export class NodeWrangler {
  constructor (ns) { this.ns = ns }

  putRecord (rootCid, key, val) {
    const root = this.ns.getNode(rootCid)
    if (root.isEmpty()) return this._putHere(root, key, val).cid()
    return this._putRecursive(root, key, val, keyHeight(key), root.height()).cid()
  }

  delRecord (rootCid, key) {
    const root = this.ns.getNode(rootCid)
    const afterDel = this._deleteRecursive(root, key, keyHeight(key), root.height())
    return this.ns.getNode(this._squashTop(afterDel)).cid()
  }

  _putHere (node, key, val) {
    const i = node.gteIndex(key)
    if (i < node.keys.length && node.keys[i] === key) {
      if (cidEq(node.vals[i], val)) return node
      return this.ns.storedNode(new MSTNode(node.keys.slice(), replaceAt(node.vals, i, val), node.subtrees.slice()))
    }
    const [lsub, rsub] = this._splitOnKey(node.subtrees[i], key)
    return this.ns.storedNode(new MSTNode(
      insertAt(node.keys, i, key),
      insertAt(node.vals, i, val),
      node.subtrees.slice(0, i).concat([lsub, rsub], node.subtrees.slice(i + 1))
    ))
  }

  _putRecursive (node, key, val, keyH, treeH) {
    if (keyH > treeH) { // grow the tree upward
      return this.ns.storedNode(this._putRecursive(
        this.ns.storedNode(new MSTNode([], [], [node.cid()])),
        key, val, keyH, treeH + 1
      ))
    }
    if (keyH < treeH) { // descend
      const i = node.gteIndex(key)
      return this.ns.storedNode(new MSTNode(
        node.keys.slice(), node.vals.slice(),
        replaceAt(node.subtrees, i, this._putRecursive(this.ns.getNode(node.subtrees[i]), key, val, keyH, treeH - 1).cid())
      ))
    }
    return this._putHere(node, key, val) // keyH === treeH
  }

  _splitOnKey (nodeCid, key) {
    if (nodeCid === null || nodeCid === undefined) return [null, null]
    const node = this.ns.getNode(nodeCid)
    const i = node.gteIndex(key)
    const [lsub, rsub] = this._splitOnKey(node.subtrees[i], key)
    const left = this.ns.storedNode(new MSTNode(node.keys.slice(0, i), node.vals.slice(0, i), node.subtrees.slice(0, i).concat([lsub]))).toOptional()
    const right = this.ns.storedNode(new MSTNode(node.keys.slice(i), node.vals.slice(i), [rsub].concat(node.subtrees.slice(i + 1)))).toOptional()
    return [left, right]
  }

  _squashTop (nodeCid) {
    const node = this.ns.getNode(nodeCid)
    if (node.keys.length) return nodeCid
    if (node.subtrees[0] === null) return nodeCid
    return this._squashTop(node.subtrees[0])
  }

  _deleteRecursive (node, key, keyH, treeH) {
    if (keyH > treeH) return node.toOptional()
    let i = node.gteIndex(key)
    if (keyH < treeH) {
      if (node.subtrees[i] === null) return node.toOptional()
      return this.ns.storedNode(new MSTNode(
        node.keys.slice(), node.vals.slice(),
        replaceAt(node.subtrees, i, this._deleteRecursive(this.ns.getNode(node.subtrees[i]), key, keyH, treeH - 1))
      )).toOptional()
    }
    i = node.gteIndex(key)
    if (i === node.keys.length || node.keys[i] !== key) return node.toOptional()
    return this.ns.storedNode(new MSTNode(
      removeAt(node.keys, i), removeAt(node.vals, i),
      node.subtrees.slice(0, i).concat([this._merge(node.subtrees[i], node.subtrees[i + 1])], node.subtrees.slice(i + 2))
    )).toOptional()
  }

  _merge (leftCid, rightCid) {
    if (leftCid === null) return rightCid
    if (rightCid === null) return leftCid
    const left = this.ns.getNode(leftCid)
    const right = this.ns.getNode(rightCid)
    return this.ns.storedNode(new MSTNode(
      left.keys.concat(right.keys), left.vals.concat(right.vals),
      left.subtrees.slice(0, -1).concat([this._merge(left.subtrees[left.subtrees.length - 1], right.subtrees[0])], right.subtrees.slice(1))
    )).toOptional()
  }
}

// Build an MST from records [{ key, value: CID }] (any order). Returns
// { root: CID, ns: NodeStore }. ns.blocks holds every node created; use
// reachableBlocks(ns, root) for just the live set (CAR output).
export function buildMst (records) {
  const ns = new NodeStore()
  const w = new NodeWrangler(ns)
  let root = ns.storedNode(MSTNode.empty()).cid()
  for (const { key, value } of records) root = w.putRecord(root, key, value)
  return { root, ns, wrangler: w }
}

// BFS the live MST nodes reachable from root (for CAR block sets).
export function reachableBlocks (ns, rootCid) {
  const out = new Map()
  const stack = [rootCid]
  while (stack.length) {
    const cid = stack.pop()
    if (cid === null || cid === undefined) continue
    const key = cid.toString()
    if (out.has(key)) continue
    const b = ns.blocks.get(key)
    if (!b) throw new Error(`missing node ${key}`)
    out.set(key, b)
    const node = MSTNode.deserialise(b.bytes)
    for (const t of node.subtrees) if (t) stack.push(t)
  }
  return out
}

// ---- Firehose MST-inversion proof (slice 3b) ----
//
// A #commit's `blocks` CAR must be a MINIMAL, self-contained proof of the
// old→new transition — not the whole tree (that would trip a relay's `tooBig`).
// This ports millipds `repo_ops.py:apply_writes` step 2b + `atmst` proof.py:
//   blocks = created | deletion_proof_cids | inductive_proof_nodes  (+ new records)
// where `inductive_proof_nodes` = every MST node READ while replaying the ops
// backward from the new root, which must reproduce the old (prevData) root.
// The prior record CIDs travel in each op's `prev` (like millipds), so a cold
// relay can invert with no old-tree state of its own.

// A NodeStore overlay: writes land in an in-memory upper layer (NOT logged);
// reads that fall through to `lower` are recorded in `.gets`. Mirrors millipds's
// OverlayBlockStore(MemoryBlockStore, LoggingBlockStoreWrapper(bs)).
export class OverlayNodeStore {
  constructor (lower) { this.lower = lower; this.upper = new Map(); this.gets = new Set() }

  storedNode (node) {
    const bytes = node.serialise()
    const cid = cidForBytesSync(bytes)
    this.upper.set(cid.toString(), { cid, bytes })
    return node
  }

  getNode (cid) {
    if (cid === null || cid === undefined) return MSTNode.empty()
    const k = cid.toString()
    const u = this.upper.get(k)
    if (u) return MSTNode.deserialise(u.bytes)
    this.gets.add(k) // a read of a pre-existing node — part of the inductive proof
    return this.lower.getNode(cid)
  }
}

// Follow the search path for `key` from `rootCid`, collecting every node visited.
// Returns { value: CID|null, proof: Set<cidStr> }. value===null ⇒ exclusion proof;
// value!==null ⇒ inclusion proof. Port of atmst find_rpath_and_build_proof.
export function findRpathProof (ns, rootCid, key) {
  const proof = new Set()
  let cid = rootCid
  while (cid !== null && cid !== undefined) {
    const node = ns.getNode(cid)
    proof.add(cid.toString())
    const i = node.gteIndex(key)
    if (i < node.keys.length && node.keys[i] === key) return { value: node.vals[i], proof }
    cid = node.subtrees[i] // descend the subtree left of the first key >= target
  }
  return { value: null, proof }
}

// Build a NodeStore holding exactly the given blocks (cid-string -> { cid, bytes }).
export function nodeStoreFromBlocks (blocks) {
  const ns = new NodeStore()
  for (const [k, v] of blocks) ns.blocks.set(k, v)
  return ns
}

// Compute the minimal firehose block set for a single commit's ops.
//   oldRecords / newRecords : [{ key, value: CID }] — the record sets BEFORE/AFTER.
//   ops : [{ action:'create'|'update'|'delete', path, cid: CID|null, prev: CID|null }]
// Returns { blocks: Map<cidStr,{cid,bytes}>, dataCid, oldRoot } — MST nodes only
// (record + commit blocks are added by the caller). Throws if the backward replay
// does not reproduce the old root (i.e. the proof would be invalid).
export function firehoseProofBlocks ({ oldRecords, newRecords, ops }) {
  const oldB = buildMst(oldRecords)
  const newB = buildMst(newRecords)
  const oldRoot = oldB.root
  const newRoot = newB.root

  const oldSet = reachableBlocks(oldB.ns, oldRoot)
  const newSet = reachableBlocks(newB.ns, newRoot)

  // combined store holds every node of BOTH trees (proof reads span both)
  const combined = new NodeStore()
  for (const [k, v] of oldSet) combined.blocks.set(k, v)
  for (const [k, v] of newSet) combined.blocks.set(k, v)

  const proofCids = new Set()

  // created: new-tree nodes not present in the old tree
  for (const k of newSet.keys()) if (!oldSet.has(k)) proofCids.add(k)

  // deletion proofs: for each delete, the exclusion-proof path in the NEW tree
  for (const op of ops) {
    if (op.action !== 'delete') continue
    const { value, proof } = findRpathProof(combined, newRoot, op.path)
    if (value !== null) throw new Error(`delete proof: ${op.path} still present in new tree`)
    for (const c of proof) proofCids.add(c)
  }

  // inductive proof: replay ops backward from newRoot; every node read is required.
  const overlay = new OverlayNodeStore(combined)
  const w = new NodeWrangler(overlay)
  let inv = newRoot
  for (let i = ops.length - 1; i >= 0; i--) {
    const op = ops[i]
    if (op.action === 'create') {
      inv = w.delRecord(inv, op.path)
    } else { // update | delete → restore the prior value
      if (op.prev === null || op.prev === undefined) throw new Error(`inversion: ${op.action} ${op.path} missing prev`)
      inv = w.putRecord(inv, op.path, op.prev)
    }
  }
  if (!inv.equals(oldRoot)) throw new Error('inversion proof failed: backward replay did not reproduce prevData root')
  for (const k of overlay.gets) proofCids.add(k)

  const blocks = new Map()
  for (const k of proofCids) blocks.set(k, combined.blocks.get(k))
  return { blocks, dataCid: newRoot, oldRoot }
}
// atproto repo — READ path (slice 1).
//
// A repo is a CAR whose root is a signed commit; the commit's `data` CID points at
// the root of a Merkle Search Tree (MST) of records. This module reads a CAR, walks
// the MST, and — most importantly — VERIFIES byte-exact fidelity by re-encoding every
// block and checking its CID. Writing/mutating the MST is slice 2.

import * as dagCbor from '@ipld/dag-cbor'
import { cidForBytes, cidForBytesSync } from './cid.js'
import { buildMst, reachableBlocks } from './mst.js'
import { unsignedCommit, signCommit, commitCid } from './commit.js'
import { readCar, writeCar } from './car.js'

// CAR read/write moved to the bare-safe minimal codec in ./car.js (was @ipld/car).
export { readCar, writeCar }

export function getBlock (car, cid) {
  const b = car.blocks.get(cid.toString())
  if (!b) throw new Error(`missing block ${cid}`)
  return b
}

export function decodeBlock (car, cid) {
  return dagCbor.decode(getBlock(car, cid).bytes)
}

// The signed commit at the CAR root.
export function loadCommit (car) {
  if (car.roots.length !== 1) throw new Error(`expected 1 root, got ${car.roots.length}`)
  const commit = decodeBlock(car, car.roots[0])
  if (!commit || !commit.did || commit.data === undefined) throw new Error('root is not a commit')
  return { cid: car.roots[0], value: commit }
}

// Walk the MST in key order, yielding { key, value: recordCid }. MST node shape:
//   { l: CID|null, e: [ { p: int, k: bytes, v: CID, t: CID|null } ] }
// keys are prefix-compressed against the previous key in the SAME node.
export function * walkMst (car, rootCid, _prevKey = '') {
  const node = decodeBlock(car, rootCid)
  if (!node || !Array.isArray(node.e)) throw new Error(`not an MST node: ${rootCid}`)
  if (node.l) yield * walkMst(car, node.l)
  let prev = ''
  for (const e of node.e) {
    const suffix = Buffer.from(e.k).toString('utf8')
    const key = prev.slice(0, e.p) + suffix
    prev = key
    yield { key, value: e.v }
    if (e.t) yield * walkMst(car, e.t)
  }
}

// All records as { key, cid, value } in key order.
export function listRecords (car) {
  const commit = loadCommit(car)
  const out = []
  for (const { key, value } of walkMst(car, commit.value.data)) {
    out.push({ key, cid: value, value: decodeBlock(car, value) })
  }
  return out
}

// Byte-exact fidelity check: re-encode every block and confirm its CID is unchanged.
// Also confirms the commit's data CID and every MST value CID resolve to a present
// block. Returns { blocks, records, ok, mismatches }.
export async function verifyRepo (car) {
  const mismatches = []
  for (const [cidStr, { cid, bytes }] of car.blocks) {
    // re-encode: decode then canonical-encode; must reproduce the exact bytes + CID
    const reencoded = dagCbor.encode(dagCbor.decode(bytes))
    const sameBytes = Buffer.from(reencoded).equals(Buffer.from(bytes))
    const recomputed = await cidForBytes(reencoded)
    if (!sameBytes || !recomputed.equals(cid)) {
      mismatches.push({ cid: cidStr, sameBytes, recomputed: recomputed.toString() })
    }
  }
  const commit = loadCommit(car)
  getBlock(car, commit.value.data) // MST root must be present
  const records = listRecords(car)
  for (const r of records) getBlock(car, r.cid) // each record block present
  return { blocks: car.blocks.size, records: records.length, ok: mismatches.length === 0, mismatches }
}

// ---- WRITE path (slice 3) ----

// Originate a full atproto repo from records. Each record is
// { collection, rkey, record } (or { key, value }). Returns the CAR bytes plus the
// commit/data CIDs. `privateKey` is the atproto secp256k1 signing key.
export async function createRepo ({ records, did, rev, privateKey }) {
  const recordBlocks = new Map()
  const mstRecords = []
  for (const r of records) {
    const key = r.key !== undefined ? r.key : `${r.collection}/${r.rkey}`
    const value = r.record !== undefined ? r.record : r.value
    const bytes = dagCbor.encode(value)
    const cid = cidForBytesSync(bytes)
    recordBlocks.set(cid.toString(), { cid, bytes })
    mstRecords.push({ key, value: cid })
  }
  const { root: dataCid, ns } = buildMst(mstRecords)
  const mstBlocks = reachableBlocks(ns, dataCid)

  const signed = signCommit(unsignedCommit({ did, rev, data: dataCid }), privateKey)
  const cCid = commitCid(signed)
  const commitBytes = dagCbor.encode(signed)

  const blocks = [{ cid: cCid, bytes: commitBytes }, ...mstBlocks.values(), ...recordBlocks.values()]
  const carBytes = await writeCar(cCid, blocks)
  return { carBytes, commitCid: cCid, dataCid, signedCommit: signed }
}
{
  "name": "@ipld/dag-cbor",
  "version": "9.2.7",
  "description": "JS implementation of DAG-CBOR",
  "author": "Rod <rod@vagg.org> (http://r.va.gg/)",
  "license": "Apache-2.0 OR MIT",
  "homepage": "https://github.com/ipld/js-dag-cbor#readme",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/ipld/js-dag-cbor.git"
  },
  "bugs": {
    "url": "https://github.com/ipld/js-dag-cbor/issues"
  },
  "publishConfig": {
    "access": "public",
    "provenance": true
  },
  "keywords": [
    "ipfs",
    "ipld",
    "multiformats"
  ],
  "type": "module",
  "types": "./dist/src/index.d.ts",
  "typesVersions": {
    "*": {
      "*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ],
      "src/*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ]
    }
  },
  "files": [
    "src",
    "dist",
    "!dist/test",
    "!**/*.tsbuildinfo"
  ],
  "exports": {
    ".": {
      "types": "./dist/src/index.d.ts",
      "import": "./src/index.js",
      "module-sync": "./src/index.js"
    }
  },
  "release": {
    "branches": [
      "master"
    ],
    "plugins": [
      [
        "@semantic-release/commit-analyzer",
        {
          "preset": "conventionalcommits",
          "releaseRules": [
            {
              "breaking": true,
              "release": "major"
            },
            {
              "revert": true,
              "release": "patch"
            },
            {
              "type": "feat",
              "release": "minor"
            },
            {
              "type": "fix",
              "release": "patch"
            },
            {
              "type": "docs",
              "release": "patch"
            },
            {
              "type": "test",
              "release": "patch"
            },
            {
              "type": "deps",
              "release": "patch"
            },
            {
              "scope": "no-release",
              "release": false
            }
          ]
        }
      ],
      [
        "@semantic-release/release-notes-generator",
        {
          "preset": "conventionalcommits",
          "presetConfig": {
            "types": [
              {
                "type": "feat",
                "section": "Features"
              },
              {
                "type": "fix",
                "section": "Bug Fixes"
              },
              {
                "type": "chore",
                "section": "Trivial Changes"
              },
              {
                "type": "docs",
                "section": "Documentation"
              },
              {
                "type": "deps",
                "section": "Dependencies"
              },
              {
                "type": "test",
                "section": "Tests"
              }
            ]
          }
        }
      ],
      "@semantic-release/changelog",
      "@semantic-release/npm",
      "@semantic-release/github",
      [
        "@semantic-release/git",
        {
          "assets": [
            "CHANGELOG.md",
            "package.json"
          ]
        }
      ]
    ]
  },
  "scripts": {
    "clean": "aegir clean",
    "lint": "aegir lint",
    "build": "aegir build",
    "release": "aegir release",
    "test": "npm run lint && aegir test",
    "test:ts": "npm run test --prefix test/ts-use",
    "test:node": "aegir test -t node --cov",
    "test:chrome": "aegir test -t browser --cov",
    "test:chrome-webworker": "aegir test -t webworker",
    "test:firefox": "aegir test -t browser -- --browser firefox",
    "test:firefox-webworker": "aegir test -t webworker -- --browser firefox",
    "test:electron-main": "aegir test -t electron-main",
    "dep-check": "aegir dep-check"
  },
  "dependencies": {
    "cborg": "^5.0.1",
    "multiformats": "^13.1.0"
  },
  "devDependencies": {
    "@ipld/garbage": "^6.0.0",
    "aegir": "^48.0.1"
  }
}
import * as cborg from 'cborg'
import { CID } from 'multiformats/cid'

// https://github.com/ipfs/go-ipfs/issues/3570#issuecomment-273931692
const CID_CBOR_TAG = 42

/**
 * @template T
 * @typedef {import('multiformats/codecs/interface').ByteView<T>} ByteView
 */

/**
 * @template T
 * @typedef {import('multiformats/codecs/interface').ArrayBufferView<T>} ArrayBufferView
 */

/**
 * @template T
 * @param {ByteView<T> | ArrayBufferView<T>} buf
 * @returns {ByteView<T>}
 */
export function toByteView (buf) {
  if (buf instanceof ArrayBuffer) {
    return new Uint8Array(buf, 0, buf.byteLength)
  }

  return buf
}

/**
 * cidEncoder will receive all Objects during encode, it needs to filter out
 * anything that's not a CID and return `null` for that so it's encoded as
 * normal.
 *
 * @param {any} obj
 * @returns {cborg.Token[]|null}
 */
function cidEncoder (obj) {
  if (obj.asCID !== obj && obj['/'] !== obj.bytes) {
    return null // any other kind of object
  }
  const cid = CID.asCID(obj)
  /* c8 ignore next 4 */
  // very unlikely case, and it'll probably throw a recursion error in cborg
  if (!cid) {
    return null
  }
  const bytes = new Uint8Array(cid.bytes.byteLength + 1)
  bytes.set(cid.bytes, 1) // prefix is 0x00, for historical reasons
  return [
    new cborg.Token(cborg.Type.tag, CID_CBOR_TAG),
    new cborg.Token(cborg.Type.bytes, bytes)
  ]
}

// eslint-disable-next-line jsdoc/require-returns-check
/**
 * Intercept all `undefined` values from an object walk and reject the entire
 * object if we find one.
 *
 * @returns {null}
 */
function undefinedEncoder () {
  throw new Error('`undefined` is not supported by the IPLD Data Model and cannot be encoded')
}

/**
 * Intercept all `number` values from an object walk and reject the entire
 * object if we find something that doesn't fit the IPLD data model (NaN &
 * Infinity).
 *
 * @param {number} num
 * @returns {null}
 */
function numberEncoder (num) {
  if (Number.isNaN(num)) {
    throw new Error('`NaN` is not supported by the IPLD Data Model and cannot be encoded')
  }
  if (num === Infinity || num === -Infinity) {
    throw new Error('`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded')
  }
  return null
}

/**
 * @param {Map<any, any>} map
 * @returns {null}
 */
function mapEncoder (map) {
  for (const key of map.keys()) {
    if (typeof key !== 'string' || key.length === 0) {
      throw new Error('Non-string Map keys are not supported by the IPLD Data Model and cannot be encoded')
    }
  }
  return null
}

const _encodeOptions = {
  float64: true,
  typeEncoders: {
    Map: mapEncoder,
    Object: cidEncoder,
    undefined: undefinedEncoder,
    number: numberEncoder
  }
}

export const encodeOptions = {
  ..._encodeOptions,
  typeEncoders: {
    ..._encodeOptions.typeEncoders
  }
}

/**
 * @param {import('cborg').TagDecodeControl} decode
 * @returns {CID}
 */
function cidDecoder (decode) {
  const bytes = /** @type {Uint8Array} */ (decode())
  if (bytes[0] !== 0) {
    throw new Error('Invalid CID for CBOR tag 42; expected leading 0x00')
  }
  return CID.decode(bytes.subarray(1)) // ignore leading 0x00
}

const _decodeOptions = {
  allowIndefinite: false,
  coerceUndefinedToNull: true,
  allowNaN: false,
  allowInfinity: false,
  allowBigInt: true, // this will lead to BigInt for ints outside of
  // safe-integer range, which may surprise users
  strict: true,
  useMaps: false,
  rejectDuplicateMapKeys: true,
  /** @type {{ [tagNumber: number]: import('cborg').TagDecoder }} */
  tags: { [CID_CBOR_TAG]: cidDecoder }
}

export const decodeOptions = {
  ..._decodeOptions,
  tags: { ..._decodeOptions.tags }
}

export const name = 'dag-cbor'
export const code = 0x71

/**
 * @template T
 * @param {T} node
 * @returns {ByteView<T>}
 */
export const encode = (node) => cborg.encode(node, _encodeOptions)

/**
 * @template T
 * @param {ByteView<T> | ArrayBufferView<T>} data
 * @returns {T}
 */
export const decode = (data) => cborg.decode(toByteView(data), _decodeOptions)
/**
 * Utilities for short weierstrass curves, combined with noble-hashes.
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { weierstrass } from "./abstract/weierstrass.js";
/** connects noble-curves to noble-hashes */
export function getHash(hash) {
    return { hash };
}
/** @deprecated use new `weierstrass()` and `ecdsa()` methods */
export function createCurve(curveDef, defHash) {
    const create = (hash) => weierstrass({ ...curveDef, hash: hash });
    return { ...create(defHash), create };
}
//# sourceMappingURL=_shortw_utils.js.map/**
 * Methods for elliptic curve multiplication by scalars.
 * Contains wNAF, pippenger.
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { bitLen, bitMask, validateObject } from "../utils.js";
import { Field, FpInvertBatch, nLength, validateField } from "./modular.js";
const _0n = BigInt(0);
const _1n = BigInt(1);
export function negateCt(condition, item) {
    const neg = item.negate();
    return condition ? neg : item;
}
/**
 * Takes a bunch of Projective Points but executes only one
 * inversion on all of them. Inversion is very slow operation,
 * so this improves performance massively.
 * Optimization: converts a list of projective points to a list of identical points with Z=1.
 */
export function normalizeZ(c, points) {
    const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
    return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
}
function validateW(W, bits) {
    if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
        throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);
}
function calcWOpts(W, scalarBits) {
    validateW(W, scalarBits);
    const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero
    const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero
    const maxNumber = 2 ** W; // W=8 256
    const mask = bitMask(W); // W=8 255 == mask 0b11111111
    const shiftBy = BigInt(W); // W=8 8
    return { windows, windowSize, mask, maxNumber, shiftBy };
}
function calcOffsets(n, window, wOpts) {
    const { windowSize, mask, maxNumber, shiftBy } = wOpts;
    let wbits = Number(n & mask); // extract W bits.
    let nextN = n >> shiftBy; // shift number by W bits.
    // What actually happens here:
    // const highestBit = Number(mask ^ (mask >> 1n));
    // let wbits2 = wbits - 1; // skip zero
    // if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);
    // split if bits > max: +224 => 256-32
    if (wbits > windowSize) {
        // we skip zero, which means instead of `>= size-1`, we do `> size`
        wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.
        nextN += _1n; // +256 (carry)
    }
    const offsetStart = window * windowSize;
    const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero
    const isZero = wbits === 0; // is current window slice a 0?
    const isNeg = wbits < 0; // is current window slice negative?
    const isNegF = window % 2 !== 0; // fake random statement for noise
    const offsetF = offsetStart; // fake offset for noise
    return { nextN, offset, isZero, isNeg, isNegF, offsetF };
}
function validateMSMPoints(points, c) {
    if (!Array.isArray(points))
        throw new Error('array expected');
    points.forEach((p, i) => {
        if (!(p instanceof c))
            throw new Error('invalid point at index ' + i);
    });
}
function validateMSMScalars(scalars, field) {
    if (!Array.isArray(scalars))
        throw new Error('array of scalars expected');
    scalars.forEach((s, i) => {
        if (!field.isValid(s))
            throw new Error('invalid scalar at index ' + i);
    });
}
// Since points in different groups cannot be equal (different object constructor),
// we can have single place to store precomputes.
// Allows to make points frozen / immutable.
const pointPrecomputes = new WeakMap();
const pointWindowSizes = new WeakMap();
function getW(P) {
    // To disable precomputes:
    // return 1;
    return pointWindowSizes.get(P) || 1;
}
function assert0(n) {
    if (n !== _0n)
        throw new Error('invalid wNAF');
}
/**
 * Elliptic curve multiplication of Point by scalar. Fragile.
 * Table generation takes **30MB of ram and 10ms on high-end CPU**,
 * but may take much longer on slow devices. Actual generation will happen on
 * first call of `multiply()`. By default, `BASE` point is precomputed.
 *
 * Scalars should always be less than curve order: this should be checked inside of a curve itself.
 * Creates precomputation tables for fast multiplication:
 * - private scalar is split by fixed size windows of W bits
 * - every window point is collected from window's table & added to accumulator
 * - since windows are different, same point inside tables won't be accessed more than once per calc
 * - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)
 * - +1 window is neccessary for wNAF
 * - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication
 *
 * @todo Research returning 2d JS array of windows, instead of a single window.
 * This would allow windows to be in different memory locations
 */
export class wNAF {
    // Parametrized with a given Point class (not individual point)
    constructor(Point, bits) {
        this.BASE = Point.BASE;
        this.ZERO = Point.ZERO;
        this.Fn = Point.Fn;
        this.bits = bits;
    }
    // non-const time multiplication ladder
    _unsafeLadder(elm, n, p = this.ZERO) {
        let d = elm;
        while (n > _0n) {
            if (n & _1n)
                p = p.add(d);
            d = d.double();
            n >>= _1n;
        }
        return p;
    }
    /**
     * Creates a wNAF precomputation window. Used for caching.
     * Default window size is set by `utils.precompute()` and is equal to 8.
     * Number of precomputed points depends on the curve size:
     * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
     * - 𝑊 is the window size
     * - 𝑛 is the bitlength of the curve order.
     * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
     * @param point Point instance
     * @param W window size
     * @returns precomputed point tables flattened to a single array
     */
    precomputeWindow(point, W) {
        const { windows, windowSize } = calcWOpts(W, this.bits);
        const points = [];
        let p = point;
        let base = p;
        for (let window = 0; window < windows; window++) {
            base = p;
            points.push(base);
            // i=1, bc we skip 0
            for (let i = 1; i < windowSize; i++) {
                base = base.add(p);
                points.push(base);
            }
            p = base.double();
        }
        return points;
    }
    /**
     * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
     * More compact implementation:
     * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
     * @returns real and fake (for const-time) points
     */
    wNAF(W, precomputes, n) {
        // Scalar should be smaller than field order
        if (!this.Fn.isValid(n))
            throw new Error('invalid scalar');
        // Accumulators
        let p = this.ZERO;
        let f = this.BASE;
        // This code was first written with assumption that 'f' and 'p' will never be infinity point:
        // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,
        // there is negate now: it is possible that negated element from low value
        // would be the same as high element, which will create carry into next window.
        // It's not obvious how this can fail, but still worth investigating later.
        const wo = calcWOpts(W, this.bits);
        for (let window = 0; window < wo.windows; window++) {
            // (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise
            const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
            n = nextN;
            if (isZero) {
                // bits are 0: add garbage to fake point
                // Important part for const-time getPublicKey: add random "noise" point to f.
                f = f.add(negateCt(isNegF, precomputes[offsetF]));
            }
            else {
                // bits are 1: add to result point
                p = p.add(negateCt(isNeg, precomputes[offset]));
            }
        }
        assert0(n);
        // Return both real and fake points: JIT won't eliminate f.
        // At this point there is a way to F be infinity-point even if p is not,
        // which makes it less const-time: around 1 bigint multiply.
        return { p, f };
    }
    /**
     * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
     * @param acc accumulator point to add result of multiplication
     * @returns point
     */
    wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
        const wo = calcWOpts(W, this.bits);
        for (let window = 0; window < wo.windows; window++) {
            if (n === _0n)
                break; // Early-exit, skip 0 value
            const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
            n = nextN;
            if (isZero) {
                // Window bits are 0: skip processing.
                // Move to next window.
                continue;
            }
            else {
                const item = precomputes[offset];
                acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM
            }
        }
        assert0(n);
        return acc;
    }
    getPrecomputes(W, point, transform) {
        // Calculate precomputes on a first run, reuse them after
        let comp = pointPrecomputes.get(point);
        if (!comp) {
            comp = this.precomputeWindow(point, W);
            if (W !== 1) {
                // Doing transform outside of if brings 15% perf hit
                if (typeof transform === 'function')
                    comp = transform(comp);
                pointPrecomputes.set(point, comp);
            }
        }
        return comp;
    }
    cached(point, scalar, transform) {
        const W = getW(point);
        return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
    }
    unsafe(point, scalar, transform, prev) {
        const W = getW(point);
        if (W === 1)
            return this._unsafeLadder(point, scalar, prev); // For W=1 ladder is ~x2 faster
        return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
    }
    // We calculate precomputes for elliptic curve point multiplication
    // using windowed method. This specifies window size and
    // stores precomputed values. Usually only base point would be precomputed.
    createCache(P, W) {
        validateW(W, this.bits);
        pointWindowSizes.set(P, W);
        pointPrecomputes.delete(P);
    }
    hasCache(elm) {
        return getW(elm) !== 1;
    }
}
/**
 * Endomorphism-specific multiplication for Koblitz curves.
 * Cost: 128 dbl, 0-256 adds.
 */
export function mulEndoUnsafe(Point, point, k1, k2) {
    let acc = point;
    let p1 = Point.ZERO;
    let p2 = Point.ZERO;
    while (k1 > _0n || k2 > _0n) {
        if (k1 & _1n)
            p1 = p1.add(acc);
        if (k2 & _1n)
            p2 = p2.add(acc);
        acc = acc.double();
        k1 >>= _1n;
        k2 >>= _1n;
    }
    return { p1, p2 };
}
/**
 * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).
 * 30x faster vs naive addition on L=4096, 10x faster than precomputes.
 * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.
 * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.
 * @param c Curve Point constructor
 * @param fieldN field over CURVE.N - important that it's not over CURVE.P
 * @param points array of L curve points
 * @param scalars array of L scalars (aka secret keys / bigints)
 */
export function pippenger(c, fieldN, points, scalars) {
    // If we split scalars by some window (let's say 8 bits), every chunk will only
    // take 256 buckets even if there are 4096 scalars, also re-uses double.
    // TODO:
    // - https://eprint.iacr.org/2024/750.pdf
    // - https://tches.iacr.org/index.php/TCHES/article/view/10287
    // 0 is accepted in scalars
    validateMSMPoints(points, c);
    validateMSMScalars(scalars, fieldN);
    const plength = points.length;
    const slength = scalars.length;
    if (plength !== slength)
        throw new Error('arrays of points and scalars must have equal length');
    // if (plength === 0) throw new Error('array must be of length >= 2');
    const zero = c.ZERO;
    const wbits = bitLen(BigInt(plength));
    let windowSize = 1; // bits
    if (wbits > 12)
        windowSize = wbits - 3;
    else if (wbits > 4)
        windowSize = wbits - 2;
    else if (wbits > 0)
        windowSize = 2;
    const MASK = bitMask(windowSize);
    const buckets = new Array(Number(MASK) + 1).fill(zero); // +1 for zero array
    const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;
    let sum = zero;
    for (let i = lastBits; i >= 0; i -= windowSize) {
        buckets.fill(zero);
        for (let j = 0; j < slength; j++) {
            const scalar = scalars[j];
            const wbits = Number((scalar >> BigInt(i)) & MASK);
            buckets[wbits] = buckets[wbits].add(points[j]);
        }
        let resI = zero; // not using this will do small speed-up, but will lose ct
        // Skip first bucket, because it is zero
        for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {
            sumI = sumI.add(buckets[j]);
            resI = resI.add(sumI);
        }
        sum = sum.add(resI);
        if (i !== 0)
            for (let j = 0; j < windowSize; j++)
                sum = sum.double();
    }
    return sum;
}
/**
 * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).
 * @param c Curve Point constructor
 * @param fieldN field over CURVE.N - important that it's not over CURVE.P
 * @param points array of L curve points
 * @returns function which multiplies points with scaars
 */
export function precomputeMSMUnsafe(c, fieldN, points, windowSize) {
    /**
     * Performance Analysis of Window-based Precomputation
     *
     * Base Case (256-bit scalar, 8-bit window):
     * - Standard precomputation requires:
     *   - 31 additions per scalar × 256 scalars = 7,936 ops
     *   - Plus 255 summary additions = 8,191 total ops
     *   Note: Summary additions can be optimized via accumulator
     *
     * Chunked Precomputation Analysis:
     * - Using 32 chunks requires:
     *   - 255 additions per chunk
     *   - 256 doublings
     *   - Total: (255 × 32) + 256 = 8,416 ops
     *
     * Memory Usage Comparison:
     * Window Size | Standard Points | Chunked Points
     * ------------|-----------------|---------------
     *     4-bit   |     520         |      15
     *     8-bit   |    4,224        |     255
     *    10-bit   |   13,824        |   1,023
     *    16-bit   |  557,056        |  65,535
     *
     * Key Advantages:
     * 1. Enables larger window sizes due to reduced memory overhead
     * 2. More efficient for smaller scalar counts:
     *    - 16 chunks: (16 × 255) + 256 = 4,336 ops
     *    - ~2x faster than standard 8,191 ops
     *
     * Limitations:
     * - Not suitable for plain precomputes (requires 256 constant doublings)
     * - Performance degrades with larger scalar counts:
     *   - Optimal for ~256 scalars
     *   - Less efficient for 4096+ scalars (Pippenger preferred)
     */
    validateW(windowSize, fieldN.BITS);
    validateMSMPoints(points, c);
    const zero = c.ZERO;
    const tableSize = 2 ** windowSize - 1; // table size (without zero)
    const chunks = Math.ceil(fieldN.BITS / windowSize); // chunks of item
    const MASK = bitMask(windowSize);
    const tables = points.map((p) => {
        const res = [];
        for (let i = 0, acc = p; i < tableSize; i++) {
            res.push(acc);
            acc = acc.add(p);
        }
        return res;
    });
    return (scalars) => {
        validateMSMScalars(scalars, fieldN);
        if (scalars.length > points.length)
            throw new Error('array of scalars must be smaller than array of points');
        let res = zero;
        for (let i = 0; i < chunks; i++) {
            // No need to double if accumulator is still zero.
            if (res !== zero)
                for (let j = 0; j < windowSize; j++)
                    res = res.double();
            const shiftBy = BigInt(chunks * windowSize - (i + 1) * windowSize);
            for (let j = 0; j < scalars.length; j++) {
                const n = scalars[j];
                const curr = Number((n >> shiftBy) & MASK);
                if (!curr)
                    continue; // skip zero scalars chunks
                res = res.add(tables[j][curr - 1]);
            }
        }
        return res;
    };
}
// TODO: remove
/** @deprecated */
export function validateBasic(curve) {
    validateField(curve.Fp);
    validateObject(curve, {
        n: 'bigint',
        h: 'bigint',
        Gx: 'field',
        Gy: 'field',
    }, {
        nBitLength: 'isSafeInteger',
        nByteLength: 'isSafeInteger',
    });
    // Set defaults
    return Object.freeze({
        ...nLength(curve.n, curve.nBitLength),
        ...curve,
        ...{ p: curve.Fp.ORDER },
    });
}
function createField(order, field, isLE) {
    if (field) {
        if (field.ORDER !== order)
            throw new Error('Field.ORDER must match order: Fp == p, Fn == n');
        validateField(field);
        return field;
    }
    else {
        return Field(order, { isLE });
    }
}
/** Validates CURVE opts and creates fields */
export function _createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
    if (FpFnLE === undefined)
        FpFnLE = type === 'edwards';
    if (!CURVE || typeof CURVE !== 'object')
        throw new Error(`expected valid ${type} CURVE object`);
    for (const p of ['p', 'n', 'h']) {
        const val = CURVE[p];
        if (!(typeof val === 'bigint' && val > _0n))
            throw new Error(`CURVE.${p} must be positive bigint`);
    }
    const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);
    const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
    const _b = type === 'weierstrass' ? 'b' : 'd';
    const params = ['Gx', 'Gy', 'a', _b];
    for (const p of params) {
        // @ts-ignore
        if (!Fp.isValid(CURVE[p]))
            throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
    }
    CURVE = Object.freeze(Object.assign({}, CURVE));
    return { CURVE, Fp, Fn };
}
//# sourceMappingURL=curve.js.mapimport { _validateObject, abytes, bytesToNumberBE, concatBytes, isBytes, isHash, utf8ToBytes, } from "../utils.js";
import { FpInvertBatch, mod } from "./modular.js";
// Octet Stream to Integer. "spec" implementation of os2ip is 2.5x slower vs bytesToNumberBE.
const os2ip = bytesToNumberBE;
// Integer to Octet Stream (numberToBytesBE)
function i2osp(value, length) {
    anum(value);
    anum(length);
    if (value < 0 || value >= 1 << (8 * length))
        throw new Error('invalid I2OSP input: ' + value);
    const res = Array.from({ length }).fill(0);
    for (let i = length - 1; i >= 0; i--) {
        res[i] = value & 0xff;
        value >>>= 8;
    }
    return new Uint8Array(res);
}
function strxor(a, b) {
    const arr = new Uint8Array(a.length);
    for (let i = 0; i < a.length; i++) {
        arr[i] = a[i] ^ b[i];
    }
    return arr;
}
function anum(item) {
    if (!Number.isSafeInteger(item))
        throw new Error('number expected');
}
function normDST(DST) {
    if (!isBytes(DST) && typeof DST !== 'string')
        throw new Error('DST must be Uint8Array or string');
    return typeof DST === 'string' ? utf8ToBytes(DST) : DST;
}
/**
 * Produces a uniformly random byte string using a cryptographic hash function H that outputs b bits.
 * [RFC 9380 5.3.1](https://www.rfc-editor.org/rfc/rfc9380#section-5.3.1).
 */
export function expand_message_xmd(msg, DST, lenInBytes, H) {
    abytes(msg);
    anum(lenInBytes);
    DST = normDST(DST);
    // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3
    if (DST.length > 255)
        DST = H(concatBytes(utf8ToBytes('H2C-OVERSIZE-DST-'), DST));
    const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H;
    const ell = Math.ceil(lenInBytes / b_in_bytes);
    if (lenInBytes > 65535 || ell > 255)
        throw new Error('expand_message_xmd: invalid lenInBytes');
    const DST_prime = concatBytes(DST, i2osp(DST.length, 1));
    const Z_pad = i2osp(0, r_in_bytes);
    const l_i_b_str = i2osp(lenInBytes, 2); // len_in_bytes_str
    const b = new Array(ell);
    const b_0 = H(concatBytes(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));
    b[0] = H(concatBytes(b_0, i2osp(1, 1), DST_prime));
    for (let i = 1; i <= ell; i++) {
        const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime];
        b[i] = H(concatBytes(...args));
    }
    const pseudo_random_bytes = concatBytes(...b);
    return pseudo_random_bytes.slice(0, lenInBytes);
}
/**
 * Produces a uniformly random byte string using an extendable-output function (XOF) H.
 * 1. The collision resistance of H MUST be at least k bits.
 * 2. H MUST be an XOF that has been proved indifferentiable from
 *    a random oracle under a reasonable cryptographic assumption.
 * [RFC 9380 5.3.2](https://www.rfc-editor.org/rfc/rfc9380#section-5.3.2).
 */
export function expand_message_xof(msg, DST, lenInBytes, k, H) {
    abytes(msg);
    anum(lenInBytes);
    DST = normDST(DST);
    // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3
    // DST = H('H2C-OVERSIZE-DST-' || a_very_long_DST, Math.ceil((lenInBytes * k) / 8));
    if (DST.length > 255) {
        const dkLen = Math.ceil((2 * k) / 8);
        DST = H.create({ dkLen }).update(utf8ToBytes('H2C-OVERSIZE-DST-')).update(DST).digest();
    }
    if (lenInBytes > 65535 || DST.length > 255)
        throw new Error('expand_message_xof: invalid lenInBytes');
    return (H.create({ dkLen: lenInBytes })
        .update(msg)
        .update(i2osp(lenInBytes, 2))
        // 2. DST_prime = DST || I2OSP(len(DST), 1)
        .update(DST)
        .update(i2osp(DST.length, 1))
        .digest());
}
/**
 * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F.
 * [RFC 9380 5.2](https://www.rfc-editor.org/rfc/rfc9380#section-5.2).
 * @param msg a byte string containing the message to hash
 * @param count the number of elements of F to output
 * @param options `{DST: string, p: bigint, m: number, k: number, expand: 'xmd' | 'xof', hash: H}`, see above
 * @returns [u_0, ..., u_(count - 1)], a list of field elements.
 */
export function hash_to_field(msg, count, options) {
    _validateObject(options, {
        p: 'bigint',
        m: 'number',
        k: 'number',
        hash: 'function',
    });
    const { p, k, m, hash, expand, DST } = options;
    if (!isHash(options.hash))
        throw new Error('expected valid hash');
    abytes(msg);
    anum(count);
    const log2p = p.toString(2).length;
    const L = Math.ceil((log2p + k) / 8); // section 5.1 of ietf draft link above
    const len_in_bytes = count * m * L;
    let prb; // pseudo_random_bytes
    if (expand === 'xmd') {
        prb = expand_message_xmd(msg, DST, len_in_bytes, hash);
    }
    else if (expand === 'xof') {
        prb = expand_message_xof(msg, DST, len_in_bytes, k, hash);
    }
    else if (expand === '_internal_pass') {
        // for internal tests only
        prb = msg;
    }
    else {
        throw new Error('expand must be "xmd" or "xof"');
    }
    const u = new Array(count);
    for (let i = 0; i < count; i++) {
        const e = new Array(m);
        for (let j = 0; j < m; j++) {
            const elm_offset = L * (j + i * m);
            const tv = prb.subarray(elm_offset, elm_offset + L);
            e[j] = mod(os2ip(tv), p);
        }
        u[i] = e;
    }
    return u;
}
export function isogenyMap(field, map) {
    // Make same order as in spec
    const coeff = map.map((i) => Array.from(i).reverse());
    return (x, y) => {
        const [xn, xd, yn, yd] = coeff.map((val) => val.reduce((acc, i) => field.add(field.mul(acc, x), i)));
        // 6.6.3
        // Exceptional cases of iso_map are inputs that cause the denominator of
        // either rational function to evaluate to zero; such cases MUST return
        // the identity point on E.
        const [xd_inv, yd_inv] = FpInvertBatch(field, [xd, yd], true);
        x = field.mul(xn, xd_inv); // xNum / xDen
        y = field.mul(y, field.mul(yn, yd_inv)); // y * (yNum / yDev)
        return { x, y };
    };
}
export const _DST_scalar = utf8ToBytes('HashToScalar-');
/** Creates hash-to-curve methods from EC Point and mapToCurve function. See {@link H2CHasher}. */
export function createHasher(Point, mapToCurve, defaults) {
    if (typeof mapToCurve !== 'function')
        throw new Error('mapToCurve() must be defined');
    function map(num) {
        return Point.fromAffine(mapToCurve(num));
    }
    function clear(initial) {
        const P = initial.clearCofactor();
        if (P.equals(Point.ZERO))
            return Point.ZERO; // zero will throw in assert
        P.assertValidity();
        return P;
    }
    return {
        defaults,
        hashToCurve(msg, options) {
            const opts = Object.assign({}, defaults, options);
            const u = hash_to_field(msg, 2, opts);
            const u0 = map(u[0]);
            const u1 = map(u[1]);
            return clear(u0.add(u1));
        },
        encodeToCurve(msg, options) {
            const optsDst = defaults.encodeDST ? { DST: defaults.encodeDST } : {};
            const opts = Object.assign({}, defaults, optsDst, options);
            const u = hash_to_field(msg, 1, opts);
            const u0 = map(u[0]);
            return clear(u0);
        },
        /** See {@link H2CHasher} */
        mapToCurve(scalars) {
            if (!Array.isArray(scalars))
                throw new Error('expected array of bigints');
            for (const i of scalars)
                if (typeof i !== 'bigint')
                    throw new Error('expected array of bigints');
            return clear(map(scalars));
        },
        // hash_to_scalar can produce 0: https://www.rfc-editor.org/errata/eid8393
        // RFC 9380, draft-irtf-cfrg-bbs-signatures-08
        hashToScalar(msg, options) {
            // @ts-ignore
            const N = Point.Fn.ORDER;
            const opts = Object.assign({}, defaults, { p: N, m: 1, DST: _DST_scalar }, options);
            return hash_to_field(msg, 1, opts)[0][0];
        },
    };
}
//# sourceMappingURL=hash-to-curve.js.map/**
 * Utils for modular division and fields.
 * Field over 11 is a finite (Galois) field is integer number operations `mod 11`.
 * There is no division: it is replaced by modular multiplicative inverse.
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { _validateObject, anumber, bitMask, bytesToNumberBE, bytesToNumberLE, ensureBytes, numberToBytesBE, numberToBytesLE, } from "../utils.js";
// prettier-ignore
const _0n = BigInt(0), _1n = BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3);
// prettier-ignore
const _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5), _7n = /* @__PURE__ */ BigInt(7);
// prettier-ignore
const _8n = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9), _16n = /* @__PURE__ */ BigInt(16);
// Calculates a modulo b
export function mod(a, b) {
    const result = a % b;
    return result >= _0n ? result : b + result;
}
/**
 * Efficiently raise num to power and do modular division.
 * Unsafe in some contexts: uses ladder, so can expose bigint bits.
 * @example
 * pow(2n, 6n, 11n) // 64n % 11n == 9n
 */
export function pow(num, power, modulo) {
    return FpPow(Field(modulo), num, power);
}
/** Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)` */
export function pow2(x, power, modulo) {
    let res = x;
    while (power-- > _0n) {
        res *= res;
        res %= modulo;
    }
    return res;
}
/**
 * Inverses number over modulo.
 * Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).
 */
export function invert(number, modulo) {
    if (number === _0n)
        throw new Error('invert: expected non-zero number');
    if (modulo <= _0n)
        throw new Error('invert: expected positive modulus, got ' + modulo);
    // Fermat's little theorem "CT-like" version inv(n) = n^(m-2) mod m is 30x slower.
    let a = mod(number, modulo);
    let b = modulo;
    // prettier-ignore
    let x = _0n, y = _1n, u = _1n, v = _0n;
    while (a !== _0n) {
        // JIT applies optimization if those two lines follow each other
        const q = b / a;
        const r = b % a;
        const m = x - u * q;
        const n = y - v * q;
        // prettier-ignore
        b = a, a = r, x = u, y = v, u = m, v = n;
    }
    const gcd = b;
    if (gcd !== _1n)
        throw new Error('invert: does not exist');
    return mod(x, modulo);
}
function assertIsSquare(Fp, root, n) {
    if (!Fp.eql(Fp.sqr(root), n))
        throw new Error('Cannot find square root');
}
// Not all roots are possible! Example which will throw:
// const NUM =
// n = 72057594037927816n;
// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));
function sqrt3mod4(Fp, n) {
    const p1div4 = (Fp.ORDER + _1n) / _4n;
    const root = Fp.pow(n, p1div4);
    assertIsSquare(Fp, root, n);
    return root;
}
function sqrt5mod8(Fp, n) {
    const p5div8 = (Fp.ORDER - _5n) / _8n;
    const n2 = Fp.mul(n, _2n);
    const v = Fp.pow(n2, p5div8);
    const nv = Fp.mul(n, v);
    const i = Fp.mul(Fp.mul(nv, _2n), v);
    const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
    assertIsSquare(Fp, root, n);
    return root;
}
// Based on RFC9380, Kong algorithm
// prettier-ignore
function sqrt9mod16(P) {
    const Fp_ = Field(P);
    const tn = tonelliShanks(P);
    const c1 = tn(Fp_, Fp_.neg(Fp_.ONE)); //  1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F
    const c2 = tn(Fp_, c1); //  2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F
    const c3 = tn(Fp_, Fp_.neg(c1)); //  3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F
    const c4 = (P + _7n) / _16n; //  4. c4 = (q + 7) / 16        # Integer arithmetic
    return (Fp, n) => {
        let tv1 = Fp.pow(n, c4); //  1. tv1 = x^c4
        let tv2 = Fp.mul(tv1, c1); //  2. tv2 = c1 * tv1
        const tv3 = Fp.mul(tv1, c2); //  3. tv3 = c2 * tv1
        const tv4 = Fp.mul(tv1, c3); //  4. tv4 = c3 * tv1
        const e1 = Fp.eql(Fp.sqr(tv2), n); //  5.  e1 = (tv2^2) == x
        const e2 = Fp.eql(Fp.sqr(tv3), n); //  6.  e2 = (tv3^2) == x
        tv1 = Fp.cmov(tv1, tv2, e1); //  7. tv1 = CMOV(tv1, tv2, e1)  # Select tv2 if (tv2^2) == x
        tv2 = Fp.cmov(tv4, tv3, e2); //  8. tv2 = CMOV(tv4, tv3, e2)  # Select tv3 if (tv3^2) == x
        const e3 = Fp.eql(Fp.sqr(tv2), n); //  9.  e3 = (tv2^2) == x
        const root = Fp.cmov(tv1, tv2, e3); // 10.  z = CMOV(tv1, tv2, e3)   # Select sqrt from tv1 & tv2
        assertIsSquare(Fp, root, n);
        return root;
    };
}
/**
 * Tonelli-Shanks square root search algorithm.
 * 1. https://eprint.iacr.org/2012/685.pdf (page 12)
 * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks
 * @param P field order
 * @returns function that takes field Fp (created from P) and number n
 */
export function tonelliShanks(P) {
    // Initialization (precomputation).
    // Caching initialization could boost perf by 7%.
    if (P < _3n)
        throw new Error('sqrt is not defined for small field');
    // Factor P - 1 = Q * 2^S, where Q is odd
    let Q = P - _1n;
    let S = 0;
    while (Q % _2n === _0n) {
        Q /= _2n;
        S++;
    }
    // Find the first quadratic non-residue Z >= 2
    let Z = _2n;
    const _Fp = Field(P);
    while (FpLegendre(_Fp, Z) === 1) {
        // Basic primality test for P. After x iterations, chance of
        // not finding quadratic non-residue is 2^x, so 2^1000.
        if (Z++ > 1000)
            throw new Error('Cannot find square root: probably non-prime P');
    }
    // Fast-path; usually done before Z, but we do "primality test".
    if (S === 1)
        return sqrt3mod4;
    // Slow-path
    // TODO: test on Fp2 and others
    let cc = _Fp.pow(Z, Q); // c = z^Q
    const Q1div2 = (Q + _1n) / _2n;
    return function tonelliSlow(Fp, n) {
        if (Fp.is0(n))
            return n;
        // Check if n is a quadratic residue using Legendre symbol
        if (FpLegendre(Fp, n) !== 1)
            throw new Error('Cannot find square root');
        // Initialize variables for the main loop
        let M = S;
        let c = Fp.mul(Fp.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp
        let t = Fp.pow(n, Q); // t = n^Q, first guess at the fudge factor
        let R = Fp.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root
        // Main loop
        // while t != 1
        while (!Fp.eql(t, Fp.ONE)) {
            if (Fp.is0(t))
                return Fp.ZERO; // if t=0 return R=0
            let i = 1;
            // Find the smallest i >= 1 such that t^(2^i) ≡ 1 (mod P)
            let t_tmp = Fp.sqr(t); // t^(2^1)
            while (!Fp.eql(t_tmp, Fp.ONE)) {
                i++;
                t_tmp = Fp.sqr(t_tmp); // t^(2^2)...
                if (i === M)
                    throw new Error('Cannot find square root');
            }
            // Calculate the exponent for b: 2^(M - i - 1)
            const exponent = _1n << BigInt(M - i - 1); // bigint is important
            const b = Fp.pow(c, exponent); // b = 2^(M - i - 1)
            // Update variables
            M = i;
            c = Fp.sqr(b); // c = b^2
            t = Fp.mul(t, c); // t = (t * b^2)
            R = Fp.mul(R, b); // R = R*b
        }
        return R;
    };
}
/**
 * Square root for a finite field. Will try optimized versions first:
 *
 * 1. P ≡ 3 (mod 4)
 * 2. P ≡ 5 (mod 8)
 * 3. P ≡ 9 (mod 16)
 * 4. Tonelli-Shanks algorithm
 *
 * Different algorithms can give different roots, it is up to user to decide which one they want.
 * For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).
 */
export function FpSqrt(P) {
    // P ≡ 3 (mod 4) => √n = n^((P+1)/4)
    if (P % _4n === _3n)
        return sqrt3mod4;
    // P ≡ 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf
    if (P % _8n === _5n)
        return sqrt5mod8;
    // P ≡ 9 (mod 16) => Kong algorithm, page 11 of https://eprint.iacr.org/2012/685.pdf (algorithm 4)
    if (P % _16n === _9n)
        return sqrt9mod16(P);
    // Tonelli-Shanks algorithm
    return tonelliShanks(P);
}
// Little-endian check for first LE bit (last BE bit);
export const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n;
// prettier-ignore
const FIELD_FIELDS = [
    'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',
    'eql', 'add', 'sub', 'mul', 'pow', 'div',
    'addN', 'subN', 'mulN', 'sqrN'
];
export function validateField(field) {
    const initial = {
        ORDER: 'bigint',
        MASK: 'bigint',
        BYTES: 'number',
        BITS: 'number',
    };
    const opts = FIELD_FIELDS.reduce((map, val) => {
        map[val] = 'function';
        return map;
    }, initial);
    _validateObject(field, opts);
    // const max = 16384;
    // if (field.BYTES < 1 || field.BYTES > max) throw new Error('invalid field');
    // if (field.BITS < 1 || field.BITS > 8 * max) throw new Error('invalid field');
    return field;
}
// Generic field functions
/**
 * Same as `pow` but for Fp: non-constant-time.
 * Unsafe in some contexts: uses ladder, so can expose bigint bits.
 */
export function FpPow(Fp, num, power) {
    if (power < _0n)
        throw new Error('invalid exponent, negatives unsupported');
    if (power === _0n)
        return Fp.ONE;
    if (power === _1n)
        return num;
    let p = Fp.ONE;
    let d = num;
    while (power > _0n) {
        if (power & _1n)
            p = Fp.mul(p, d);
        d = Fp.sqr(d);
        power >>= _1n;
    }
    return p;
}
/**
 * Efficiently invert an array of Field elements.
 * Exception-free. Will return `undefined` for 0 elements.
 * @param passZero map 0 to 0 (instead of undefined)
 */
export function FpInvertBatch(Fp, nums, passZero = false) {
    const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : undefined);
    // Walk from first to last, multiply them by each other MOD p
    const multipliedAcc = nums.reduce((acc, num, i) => {
        if (Fp.is0(num))
            return acc;
        inverted[i] = acc;
        return Fp.mul(acc, num);
    }, Fp.ONE);
    // Invert last element
    const invertedAcc = Fp.inv(multipliedAcc);
    // Walk from last to first, multiply them by inverted each other MOD p
    nums.reduceRight((acc, num, i) => {
        if (Fp.is0(num))
            return acc;
        inverted[i] = Fp.mul(acc, inverted[i]);
        return Fp.mul(acc, num);
    }, invertedAcc);
    return inverted;
}
// TODO: remove
export function FpDiv(Fp, lhs, rhs) {
    return Fp.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, Fp.ORDER) : Fp.inv(rhs));
}
/**
 * Legendre symbol.
 * Legendre constant is used to calculate Legendre symbol (a | p)
 * which denotes the value of a^((p-1)/2) (mod p).
 *
 * * (a | p) ≡ 1    if a is a square (mod p), quadratic residue
 * * (a | p) ≡ -1   if a is not a square (mod p), quadratic non residue
 * * (a | p) ≡ 0    if a ≡ 0 (mod p)
 */
export function FpLegendre(Fp, n) {
    // We can use 3rd argument as optional cache of this value
    // but seems unneeded for now. The operation is very fast.
    const p1mod2 = (Fp.ORDER - _1n) / _2n;
    const powered = Fp.pow(n, p1mod2);
    const yes = Fp.eql(powered, Fp.ONE);
    const zero = Fp.eql(powered, Fp.ZERO);
    const no = Fp.eql(powered, Fp.neg(Fp.ONE));
    if (!yes && !zero && !no)
        throw new Error('invalid Legendre symbol result');
    return yes ? 1 : zero ? 0 : -1;
}
// This function returns True whenever the value x is a square in the field F.
export function FpIsSquare(Fp, n) {
    const l = FpLegendre(Fp, n);
    return l === 1;
}
// CURVE.n lengths
export function nLength(n, nBitLength) {
    // Bit size, byte size of CURVE.n
    if (nBitLength !== undefined)
        anumber(nBitLength);
    const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;
    const nByteLength = Math.ceil(_nBitLength / 8);
    return { nBitLength: _nBitLength, nByteLength };
}
/**
 * Creates a finite field. Major performance optimizations:
 * * 1. Denormalized operations like mulN instead of mul.
 * * 2. Identical object shape: never add or remove keys.
 * * 3. `Object.freeze`.
 * Fragile: always run a benchmark on a change.
 * Security note: operations don't check 'isValid' for all elements for performance reasons,
 * it is caller responsibility to check this.
 * This is low-level code, please make sure you know what you're doing.
 *
 * Note about field properties:
 * * CHARACTERISTIC p = prime number, number of elements in main subgroup.
 * * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.
 *
 * @param ORDER field order, probably prime, or could be composite
 * @param bitLen how many bits the field consumes
 * @param isLE (default: false) if encoding / decoding should be in little-endian
 * @param redef optional faster redefinitions of sqrt and other methods
 */
export function Field(ORDER, bitLenOrOpts, // TODO: use opts only in v2?
isLE = false, opts = {}) {
    if (ORDER <= _0n)
        throw new Error('invalid field: expected ORDER > 0, got ' + ORDER);
    let _nbitLength = undefined;
    let _sqrt = undefined;
    let modFromBytes = false;
    let allowedLengths = undefined;
    if (typeof bitLenOrOpts === 'object' && bitLenOrOpts != null) {
        if (opts.sqrt || isLE)
            throw new Error('cannot specify opts in two arguments');
        const _opts = bitLenOrOpts;
        if (_opts.BITS)
            _nbitLength = _opts.BITS;
        if (_opts.sqrt)
            _sqrt = _opts.sqrt;
        if (typeof _opts.isLE === 'boolean')
            isLE = _opts.isLE;
        if (typeof _opts.modFromBytes === 'boolean')
            modFromBytes = _opts.modFromBytes;
        allowedLengths = _opts.allowedLengths;
    }
    else {
        if (typeof bitLenOrOpts === 'number')
            _nbitLength = bitLenOrOpts;
        if (opts.sqrt)
            _sqrt = opts.sqrt;
    }
    const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, _nbitLength);
    if (BYTES > 2048)
        throw new Error('invalid field: expected ORDER of <= 2048 bytes');
    let sqrtP; // cached sqrtP
    const f = Object.freeze({
        ORDER,
        isLE,
        BITS,
        BYTES,
        MASK: bitMask(BITS),
        ZERO: _0n,
        ONE: _1n,
        allowedLengths: allowedLengths,
        create: (num) => mod(num, ORDER),
        isValid: (num) => {
            if (typeof num !== 'bigint')
                throw new Error('invalid field element: expected bigint, got ' + typeof num);
            return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible
        },
        is0: (num) => num === _0n,
        // is valid and invertible
        isValidNot0: (num) => !f.is0(num) && f.isValid(num),
        isOdd: (num) => (num & _1n) === _1n,
        neg: (num) => mod(-num, ORDER),
        eql: (lhs, rhs) => lhs === rhs,
        sqr: (num) => mod(num * num, ORDER),
        add: (lhs, rhs) => mod(lhs + rhs, ORDER),
        sub: (lhs, rhs) => mod(lhs - rhs, ORDER),
        mul: (lhs, rhs) => mod(lhs * rhs, ORDER),
        pow: (num, power) => FpPow(f, num, power),
        div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),
        // Same as above, but doesn't normalize
        sqrN: (num) => num * num,
        addN: (lhs, rhs) => lhs + rhs,
        subN: (lhs, rhs) => lhs - rhs,
        mulN: (lhs, rhs) => lhs * rhs,
        inv: (num) => invert(num, ORDER),
        sqrt: _sqrt ||
            ((n) => {
                if (!sqrtP)
                    sqrtP = FpSqrt(ORDER);
                return sqrtP(f, n);
            }),
        toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),
        fromBytes: (bytes, skipValidation = true) => {
            if (allowedLengths) {
                if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
                    throw new Error('Field.fromBytes: expected ' + allowedLengths + ' bytes, got ' + bytes.length);
                }
                const padded = new Uint8Array(BYTES);
                // isLE add 0 to right, !isLE to the left.
                padded.set(bytes, isLE ? 0 : padded.length - bytes.length);
                bytes = padded;
            }
            if (bytes.length !== BYTES)
                throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);
            let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
            if (modFromBytes)
                scalar = mod(scalar, ORDER);
            if (!skipValidation)
                if (!f.isValid(scalar))
                    throw new Error('invalid field element: outside of range 0..ORDER');
            // NOTE: we don't validate scalar here, please use isValid. This done such way because some
            // protocol may allow non-reduced scalar that reduced later or changed some other way.
            return scalar;
        },
        // TODO: we don't need it here, move out to separate fn
        invertBatch: (lst) => FpInvertBatch(f, lst),
        // We can't move this out because Fp6, Fp12 implement it
        // and it's unclear what to return in there.
        cmov: (a, b, c) => (c ? b : a),
    });
    return Object.freeze(f);
}
// Generic random scalar, we can do same for other fields if via Fp2.mul(Fp2.ONE, Fp2.random)?
// This allows unsafe methods like ignore bias or zero. These unsafe, but often used in different protocols (if deterministic RNG).
// which mean we cannot force this via opts.
// Not sure what to do with randomBytes, we can accept it inside opts if wanted.
// Probably need to export getMinHashLength somewhere?
// random(bytes?: Uint8Array, unsafeAllowZero = false, unsafeAllowBias = false) {
//   const LEN = !unsafeAllowBias ? getMinHashLength(ORDER) : BYTES;
//   if (bytes === undefined) bytes = randomBytes(LEN); // _opts.randomBytes?
//   const num = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
//   // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0
//   const reduced = unsafeAllowZero ? mod(num, ORDER) : mod(num, ORDER - _1n) + _1n;
//   return reduced;
// },
export function FpSqrtOdd(Fp, elm) {
    if (!Fp.isOdd)
        throw new Error("Field doesn't have isOdd");
    const root = Fp.sqrt(elm);
    return Fp.isOdd(root) ? root : Fp.neg(root);
}
export function FpSqrtEven(Fp, elm) {
    if (!Fp.isOdd)
        throw new Error("Field doesn't have isOdd");
    const root = Fp.sqrt(elm);
    return Fp.isOdd(root) ? Fp.neg(root) : root;
}
/**
 * "Constant-time" private key generation utility.
 * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field).
 * Which makes it slightly more biased, less secure.
 * @deprecated use `mapKeyToField` instead
 */
export function hashToPrivateScalar(hash, groupOrder, isLE = false) {
    hash = ensureBytes('privateHash', hash);
    const hashLen = hash.length;
    const minLen = nLength(groupOrder).nByteLength + 8;
    if (minLen < 24 || hashLen < minLen || hashLen > 1024)
        throw new Error('hashToPrivateScalar: expected ' + minLen + '-1024 bytes of input, got ' + hashLen);
    const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash);
    return mod(num, groupOrder - _1n) + _1n;
}
/**
 * Returns total number of bytes consumed by the field element.
 * For example, 32 bytes for usual 256-bit weierstrass curve.
 * @param fieldOrder number of field elements, usually CURVE.n
 * @returns byte length of field
 */
export function getFieldBytesLength(fieldOrder) {
    if (typeof fieldOrder !== 'bigint')
        throw new Error('field order must be bigint');
    const bitLength = fieldOrder.toString(2).length;
    return Math.ceil(bitLength / 8);
}
/**
 * Returns minimal amount of bytes that can be safely reduced
 * by field order.
 * Should be 2^-128 for 128-bit curve such as P256.
 * @param fieldOrder number of field elements, usually CURVE.n
 * @returns byte length of target hash
 */
export function getMinHashLength(fieldOrder) {
    const length = getFieldBytesLength(fieldOrder);
    return length + Math.ceil(length / 2);
}
/**
 * "Constant-time" private key generation utility.
 * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF
 * and convert them into private scalar, with the modulo bias being negligible.
 * Needs at least 48 bytes of input for 32-byte private key.
 * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/
 * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final
 * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5
 * @param hash hash output from SHA3 or a similar function
 * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)
 * @param isLE interpret hash bytes as LE num
 * @returns valid private scalar
 */
export function mapHashToField(key, fieldOrder, isLE = false) {
    const len = key.length;
    const fieldLen = getFieldBytesLength(fieldOrder);
    const minLen = getMinHashLength(fieldOrder);
    // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.
    if (len < 16 || len < minLen || len > 1024)
        throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);
    const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);
    // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0
    const reduced = mod(num, fieldOrder - _1n) + _1n;
    return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
}
//# sourceMappingURL=modular.js.map/**
 * Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.
 *
 * ### Design rationale for types
 *
 * * Interaction between classes from different curves should fail:
 *   `k256.Point.BASE.add(p256.Point.BASE)`
 * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime
 * * Different calls of `curve()` would return different classes -
 *   `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,
 *   it won't affect others
 *
 * TypeScript can't infer types for classes created inside a function. Classes is one instance
 * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create
 * unique type for every function call.
 *
 * We can use generic types via some param, like curve opts, but that would:
 *     1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)
 *     which is hard to debug.
 *     2. Params can be generic and we can't enforce them to be constant value:
 *     if somebody creates curve from non-constant params,
 *     it would be allowed to interact with other curves with non-constant params
 *
 * @todo https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { hmac as nobleHmac } from '@noble/hashes/hmac.js';
import { ahash } from '@noble/hashes/utils';
import { _validateObject, _abool2 as abool, _abytes2 as abytes, aInRange, bitLen, bitMask, bytesToHex, bytesToNumberBE, concatBytes, createHmacDrbg, ensureBytes, hexToBytes, inRange, isBytes, memoized, numberToHexUnpadded, randomBytes as randomBytesWeb, } from "../utils.js";
import { _createCurveFields, mulEndoUnsafe, negateCt, normalizeZ, pippenger, wNAF, } from "./curve.js";
import { Field, FpInvertBatch, getMinHashLength, mapHashToField, nLength, validateField, } from "./modular.js";
// We construct basis in such way that den is always positive and equals n, but num sign depends on basis (not on secret value)
const divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n) / den;
/**
 * Splits scalar for GLV endomorphism.
 */
export function _splitEndoScalar(k, basis, n) {
    // Split scalar into two such that part is ~half bits: `abs(part) < sqrt(N)`
    // Since part can be negative, we need to do this on point.
    // TODO: verifyScalar function which consumes lambda
    const [[a1, b1], [a2, b2]] = basis;
    const c1 = divNearest(b2 * k, n);
    const c2 = divNearest(-b1 * k, n);
    // |k1|/|k2| is < sqrt(N), but can be negative.
    // If we do `k1 mod N`, we'll get big scalar (`> sqrt(N)`): so, we do cheaper negation instead.
    let k1 = k - c1 * a1 - c2 * a2;
    let k2 = -c1 * b1 - c2 * b2;
    const k1neg = k1 < _0n;
    const k2neg = k2 < _0n;
    if (k1neg)
        k1 = -k1;
    if (k2neg)
        k2 = -k2;
    // Double check that resulting scalar less than half bits of N: otherwise wNAF will fail.
    // This should only happen on wrong basises. Also, math inside is too complex and I don't trust it.
    const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n; // Half bits of N
    if (k1 < _0n || k1 >= MAX_NUM || k2 < _0n || k2 >= MAX_NUM) {
        throw new Error('splitScalar (endomorphism): failed, k=' + k);
    }
    return { k1neg, k1, k2neg, k2 };
}
function validateSigFormat(format) {
    if (!['compact', 'recovered', 'der'].includes(format))
        throw new Error('Signature format must be "compact", "recovered", or "der"');
    return format;
}
function validateSigOpts(opts, def) {
    const optsn = {};
    for (let optName of Object.keys(def)) {
        // @ts-ignore
        optsn[optName] = opts[optName] === undefined ? def[optName] : opts[optName];
    }
    abool(optsn.lowS, 'lowS');
    abool(optsn.prehash, 'prehash');
    if (optsn.format !== undefined)
        validateSigFormat(optsn.format);
    return optsn;
}
export class DERErr extends Error {
    constructor(m = '') {
        super(m);
    }
}
/**
 * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:
 *
 *     [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]
 *
 * Docs: https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/, https://luca.ntop.org/Teaching/Appunti/asn1.html
 */
export const DER = {
    // asn.1 DER encoding utils
    Err: DERErr,
    // Basic building block is TLV (Tag-Length-Value)
    _tlv: {
        encode: (tag, data) => {
            const { Err: E } = DER;
            if (tag < 0 || tag > 256)
                throw new E('tlv.encode: wrong tag');
            if (data.length & 1)
                throw new E('tlv.encode: unpadded data');
            const dataLen = data.length / 2;
            const len = numberToHexUnpadded(dataLen);
            if ((len.length / 2) & 128)
                throw new E('tlv.encode: long form length too big');
            // length of length with long form flag
            const lenLen = dataLen > 127 ? numberToHexUnpadded((len.length / 2) | 128) : '';
            const t = numberToHexUnpadded(tag);
            return t + lenLen + len + data;
        },
        // v - value, l - left bytes (unparsed)
        decode(tag, data) {
            const { Err: E } = DER;
            let pos = 0;
            if (tag < 0 || tag > 256)
                throw new E('tlv.encode: wrong tag');
            if (data.length < 2 || data[pos++] !== tag)
                throw new E('tlv.decode: wrong tlv');
            const first = data[pos++];
            const isLong = !!(first & 128); // First bit of first length byte is flag for short/long form
            let length = 0;
            if (!isLong)
                length = first;
            else {
                // Long form: [longFlag(1bit), lengthLength(7bit), length (BE)]
                const lenLen = first & 127;
                if (!lenLen)
                    throw new E('tlv.decode(long): indefinite length not supported');
                if (lenLen > 4)
                    throw new E('tlv.decode(long): byte length is too big'); // this will overflow u32 in js
                const lengthBytes = data.subarray(pos, pos + lenLen);
                if (lengthBytes.length !== lenLen)
                    throw new E('tlv.decode: length bytes not complete');
                if (lengthBytes[0] === 0)
                    throw new E('tlv.decode(long): zero leftmost byte');
                for (const b of lengthBytes)
                    length = (length << 8) | b;
                pos += lenLen;
                if (length < 128)
                    throw new E('tlv.decode(long): not minimal encoding');
            }
            const v = data.subarray(pos, pos + length);
            if (v.length !== length)
                throw new E('tlv.decode: wrong value length');
            return { v, l: data.subarray(pos + length) };
        },
    },
    // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
    // since we always use positive integers here. It must always be empty:
    // - add zero byte if exists
    // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
    _int: {
        encode(num) {
            const { Err: E } = DER;
            if (num < _0n)
                throw new E('integer: negative integers are not allowed');
            let hex = numberToHexUnpadded(num);
            // Pad with zero byte if negative flag is present
            if (Number.parseInt(hex[0], 16) & 0b1000)
                hex = '00' + hex;
            if (hex.length & 1)
                throw new E('unexpected DER parsing assertion: unpadded hex');
            return hex;
        },
        decode(data) {
            const { Err: E } = DER;
            if (data[0] & 128)
                throw new E('invalid signature integer: negative');
            if (data[0] === 0x00 && !(data[1] & 128))
                throw new E('invalid signature integer: unnecessary leading zero');
            return bytesToNumberBE(data);
        },
    },
    toSig(hex) {
        // parse DER signature
        const { Err: E, _int: int, _tlv: tlv } = DER;
        const data = ensureBytes('signature', hex);
        const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);
        if (seqLeftBytes.length)
            throw new E('invalid signature: left bytes after parsing');
        const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);
        const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);
        if (sLeftBytes.length)
            throw new E('invalid signature: left bytes after parsing');
        return { r: int.decode(rBytes), s: int.decode(sBytes) };
    },
    hexFromSig(sig) {
        const { _tlv: tlv, _int: int } = DER;
        const rs = tlv.encode(0x02, int.encode(sig.r));
        const ss = tlv.encode(0x02, int.encode(sig.s));
        const seq = rs + ss;
        return tlv.encode(0x30, seq);
    },
};
// Be friendly to bad ECMAScript parsers by not using bigint literals
// prettier-ignore
const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4);
export function _normFnElement(Fn, key) {
    const { BYTES: expected } = Fn;
    let num;
    if (typeof key === 'bigint') {
        num = key;
    }
    else {
        let bytes = ensureBytes('private key', key);
        try {
            num = Fn.fromBytes(bytes);
        }
        catch (error) {
            throw new Error(`invalid private key: expected ui8a of size ${expected}, got ${typeof key}`);
        }
    }
    if (!Fn.isValidNot0(num))
        throw new Error('invalid private key: out of range [1..N-1]');
    return num;
}
/**
 * Creates weierstrass Point constructor, based on specified curve options.
 *
 * @example
```js
const opts = {
  p: BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff'),
  n: BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551'),
  h: BigInt(1),
  a: BigInt('0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc'),
  b: BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b'),
  Gx: BigInt('0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296'),
  Gy: BigInt('0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5'),
};
const p256_Point = weierstrass(opts);
```
 */
export function weierstrassN(params, extraOpts = {}) {
    const validated = _createCurveFields('weierstrass', params, extraOpts);
    const { Fp, Fn } = validated;
    let CURVE = validated.CURVE;
    const { h: cofactor, n: CURVE_ORDER } = CURVE;
    _validateObject(extraOpts, {}, {
        allowInfinityPoint: 'boolean',
        clearCofactor: 'function',
        isTorsionFree: 'function',
        fromBytes: 'function',
        toBytes: 'function',
        endo: 'object',
        wrapPrivateKey: 'boolean',
    });
    const { endo } = extraOpts;
    if (endo) {
        // validateObject(endo, { beta: 'bigint', splitScalar: 'function' });
        if (!Fp.is0(CURVE.a) || typeof endo.beta !== 'bigint' || !Array.isArray(endo.basises)) {
            throw new Error('invalid endo: expected "beta": bigint and "basises": array');
        }
    }
    const lengths = getWLengths(Fp, Fn);
    function assertCompressionIsSupported() {
        if (!Fp.isOdd)
            throw new Error('compression is not supported: Field does not have .isOdd()');
    }
    // Implements IEEE P1363 point encoding
    function pointToBytes(_c, point, isCompressed) {
        const { x, y } = point.toAffine();
        const bx = Fp.toBytes(x);
        abool(isCompressed, 'isCompressed');
        if (isCompressed) {
            assertCompressionIsSupported();
            const hasEvenY = !Fp.isOdd(y);
            return concatBytes(pprefix(hasEvenY), bx);
        }
        else {
            return concatBytes(Uint8Array.of(0x04), bx, Fp.toBytes(y));
        }
    }
    function pointFromBytes(bytes) {
        abytes(bytes, undefined, 'Point');
        const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths; // e.g. for 32-byte: 33, 65
        const length = bytes.length;
        const head = bytes[0];
        const tail = bytes.subarray(1);
        // No actual validation is done here: use .assertValidity()
        if (length === comp && (head === 0x02 || head === 0x03)) {
            const x = Fp.fromBytes(tail);
            if (!Fp.isValid(x))
                throw new Error('bad point: is not on curve, wrong x');
            const y2 = weierstrassEquation(x); // y² = x³ + ax + b
            let y;
            try {
                y = Fp.sqrt(y2); // y = y² ^ (p+1)/4
            }
            catch (sqrtError) {
                const err = sqrtError instanceof Error ? ': ' + sqrtError.message : '';
                throw new Error('bad point: is not on curve, sqrt error' + err);
            }
            assertCompressionIsSupported();
            const isYOdd = Fp.isOdd(y); // (y & _1n) === _1n;
            const isHeadOdd = (head & 1) === 1; // ECDSA-specific
            if (isHeadOdd !== isYOdd)
                y = Fp.neg(y);
            return { x, y };
        }
        else if (length === uncomp && head === 0x04) {
            // TODO: more checks
            const L = Fp.BYTES;
            const x = Fp.fromBytes(tail.subarray(0, L));
            const y = Fp.fromBytes(tail.subarray(L, L * 2));
            if (!isValidXY(x, y))
                throw new Error('bad point: is not on curve');
            return { x, y };
        }
        else {
            throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);
        }
    }
    const encodePoint = extraOpts.toBytes || pointToBytes;
    const decodePoint = extraOpts.fromBytes || pointFromBytes;
    function weierstrassEquation(x) {
        const x2 = Fp.sqr(x); // x * x
        const x3 = Fp.mul(x2, x); // x² * x
        return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b); // x³ + a * x + b
    }
    // TODO: move top-level
    /** Checks whether equation holds for given x, y: y² == x³ + ax + b */
    function isValidXY(x, y) {
        const left = Fp.sqr(y); // y²
        const right = weierstrassEquation(x); // x³ + ax + b
        return Fp.eql(left, right);
    }
    // Validate whether the passed curve params are valid.
    // Test 1: equation y² = x³ + ax + b should work for generator point.
    if (!isValidXY(CURVE.Gx, CURVE.Gy))
        throw new Error('bad curve params: generator point');
    // Test 2: discriminant Δ part should be non-zero: 4a³ + 27b² != 0.
    // Guarantees curve is genus-1, smooth (non-singular).
    const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n), _4n);
    const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));
    if (Fp.is0(Fp.add(_4a3, _27b2)))
        throw new Error('bad curve params: a or b');
    /** Asserts coordinate is valid: 0 <= n < Fp.ORDER. */
    function acoord(title, n, banZero = false) {
        if (!Fp.isValid(n) || (banZero && Fp.is0(n)))
            throw new Error(`bad point coordinate ${title}`);
        return n;
    }
    function aprjpoint(other) {
        if (!(other instanceof Point))
            throw new Error('ProjectivePoint expected');
    }
    function splitEndoScalarN(k) {
        if (!endo || !endo.basises)
            throw new Error('no endo');
        return _splitEndoScalar(k, endo.basises, Fn.ORDER);
    }
    // Memoized toAffine / validity check. They are heavy. Points are immutable.
    // Converts Projective point to affine (x, y) coordinates.
    // Can accept precomputed Z^-1 - for example, from invertBatch.
    // (X, Y, Z) ∋ (x=X/Z, y=Y/Z)
    const toAffineMemo = memoized((p, iz) => {
        const { X, Y, Z } = p;
        // Fast-path for normalized points
        if (Fp.eql(Z, Fp.ONE))
            return { x: X, y: Y };
        const is0 = p.is0();
        // If invZ was 0, we return zero point. However we still want to execute
        // all operations, so we replace invZ with a random number, 1.
        if (iz == null)
            iz = is0 ? Fp.ONE : Fp.inv(Z);
        const x = Fp.mul(X, iz);
        const y = Fp.mul(Y, iz);
        const zz = Fp.mul(Z, iz);
        if (is0)
            return { x: Fp.ZERO, y: Fp.ZERO };
        if (!Fp.eql(zz, Fp.ONE))
            throw new Error('invZ was invalid');
        return { x, y };
    });
    // NOTE: on exception this will crash 'cached' and no value will be set.
    // Otherwise true will be return
    const assertValidMemo = memoized((p) => {
        if (p.is0()) {
            // (0, 1, 0) aka ZERO is invalid in most contexts.
            // In BLS, ZERO can be serialized, so we allow it.
            // (0, 0, 0) is invalid representation of ZERO.
            if (extraOpts.allowInfinityPoint && !Fp.is0(p.Y))
                return;
            throw new Error('bad point: ZERO');
        }
        // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`
        const { x, y } = p.toAffine();
        if (!Fp.isValid(x) || !Fp.isValid(y))
            throw new Error('bad point: x or y not field elements');
        if (!isValidXY(x, y))
            throw new Error('bad point: equation left != right');
        if (!p.isTorsionFree())
            throw new Error('bad point: not in prime-order subgroup');
        return true;
    });
    function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) {
        k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);
        k1p = negateCt(k1neg, k1p);
        k2p = negateCt(k2neg, k2p);
        return k1p.add(k2p);
    }
    /**
     * Projective Point works in 3d / projective (homogeneous) coordinates:(X, Y, Z) ∋ (x=X/Z, y=Y/Z).
     * Default Point works in 2d / affine coordinates: (x, y).
     * We're doing calculations in projective, because its operations don't require costly inversion.
     */
    class Point {
        /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
        constructor(X, Y, Z) {
            this.X = acoord('x', X);
            this.Y = acoord('y', Y, true);
            this.Z = acoord('z', Z);
            Object.freeze(this);
        }
        static CURVE() {
            return CURVE;
        }
        /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
        static fromAffine(p) {
            const { x, y } = p || {};
            if (!p || !Fp.isValid(x) || !Fp.isValid(y))
                throw new Error('invalid affine point');
            if (p instanceof Point)
                throw new Error('projective point not allowed');
            // (0, 0) would've produced (0, 0, 1) - instead, we need (0, 1, 0)
            if (Fp.is0(x) && Fp.is0(y))
                return Point.ZERO;
            return new Point(x, y, Fp.ONE);
        }
        static fromBytes(bytes) {
            const P = Point.fromAffine(decodePoint(abytes(bytes, undefined, 'point')));
            P.assertValidity();
            return P;
        }
        static fromHex(hex) {
            return Point.fromBytes(ensureBytes('pointHex', hex));
        }
        get x() {
            return this.toAffine().x;
        }
        get y() {
            return this.toAffine().y;
        }
        /**
         *
         * @param windowSize
         * @param isLazy true will defer table computation until the first multiplication
         * @returns
         */
        precompute(windowSize = 8, isLazy = true) {
            wnaf.createCache(this, windowSize);
            if (!isLazy)
                this.multiply(_3n); // random number
            return this;
        }
        // TODO: return `this`
        /** A point on curve is valid if it conforms to equation. */
        assertValidity() {
            assertValidMemo(this);
        }
        hasEvenY() {
            const { y } = this.toAffine();
            if (!Fp.isOdd)
                throw new Error("Field doesn't support isOdd");
            return !Fp.isOdd(y);
        }
        /** Compare one point to another. */
        equals(other) {
            aprjpoint(other);
            const { X: X1, Y: Y1, Z: Z1 } = this;
            const { X: X2, Y: Y2, Z: Z2 } = other;
            const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
            const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
            return U1 && U2;
        }
        /** Flips point to one corresponding to (x, -y) in Affine coordinates. */
        negate() {
            return new Point(this.X, Fp.neg(this.Y), this.Z);
        }
        // Renes-Costello-Batina exception-free doubling formula.
        // There is 30% faster Jacobian formula, but it is not complete.
        // https://eprint.iacr.org/2015/1060, algorithm 3
        // Cost: 8M + 3S + 3*a + 2*b3 + 15add.
        double() {
            const { a, b } = CURVE;
            const b3 = Fp.mul(b, _3n);
            const { X: X1, Y: Y1, Z: Z1 } = this;
            let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore
            let t0 = Fp.mul(X1, X1); // step 1
            let t1 = Fp.mul(Y1, Y1);
            let t2 = Fp.mul(Z1, Z1);
            let t3 = Fp.mul(X1, Y1);
            t3 = Fp.add(t3, t3); // step 5
            Z3 = Fp.mul(X1, Z1);
            Z3 = Fp.add(Z3, Z3);
            X3 = Fp.mul(a, Z3);
            Y3 = Fp.mul(b3, t2);
            Y3 = Fp.add(X3, Y3); // step 10
            X3 = Fp.sub(t1, Y3);
            Y3 = Fp.add(t1, Y3);
            Y3 = Fp.mul(X3, Y3);
            X3 = Fp.mul(t3, X3);
            Z3 = Fp.mul(b3, Z3); // step 15
            t2 = Fp.mul(a, t2);
            t3 = Fp.sub(t0, t2);
            t3 = Fp.mul(a, t3);
            t3 = Fp.add(t3, Z3);
            Z3 = Fp.add(t0, t0); // step 20
            t0 = Fp.add(Z3, t0);
            t0 = Fp.add(t0, t2);
            t0 = Fp.mul(t0, t3);
            Y3 = Fp.add(Y3, t0);
            t2 = Fp.mul(Y1, Z1); // step 25
            t2 = Fp.add(t2, t2);
            t0 = Fp.mul(t2, t3);
            X3 = Fp.sub(X3, t0);
            Z3 = Fp.mul(t2, t1);
            Z3 = Fp.add(Z3, Z3); // step 30
            Z3 = Fp.add(Z3, Z3);
            return new Point(X3, Y3, Z3);
        }
        // Renes-Costello-Batina exception-free addition formula.
        // There is 30% faster Jacobian formula, but it is not complete.
        // https://eprint.iacr.org/2015/1060, algorithm 1
        // Cost: 12M + 0S + 3*a + 3*b3 + 23add.
        add(other) {
            aprjpoint(other);
            const { X: X1, Y: Y1, Z: Z1 } = this;
            const { X: X2, Y: Y2, Z: Z2 } = other;
            let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore
            const a = CURVE.a;
            const b3 = Fp.mul(CURVE.b, _3n);
            let t0 = Fp.mul(X1, X2); // step 1
            let t1 = Fp.mul(Y1, Y2);
            let t2 = Fp.mul(Z1, Z2);
            let t3 = Fp.add(X1, Y1);
            let t4 = Fp.add(X2, Y2); // step 5
            t3 = Fp.mul(t3, t4);
            t4 = Fp.add(t0, t1);
            t3 = Fp.sub(t3, t4);
            t4 = Fp.add(X1, Z1);
            let t5 = Fp.add(X2, Z2); // step 10
            t4 = Fp.mul(t4, t5);
            t5 = Fp.add(t0, t2);
            t4 = Fp.sub(t4, t5);
            t5 = Fp.add(Y1, Z1);
            X3 = Fp.add(Y2, Z2); // step 15
            t5 = Fp.mul(t5, X3);
            X3 = Fp.add(t1, t2);
            t5 = Fp.sub(t5, X3);
            Z3 = Fp.mul(a, t4);
            X3 = Fp.mul(b3, t2); // step 20
            Z3 = Fp.add(X3, Z3);
            X3 = Fp.sub(t1, Z3);
            Z3 = Fp.add(t1, Z3);
            Y3 = Fp.mul(X3, Z3);
            t1 = Fp.add(t0, t0); // step 25
            t1 = Fp.add(t1, t0);
            t2 = Fp.mul(a, t2);
            t4 = Fp.mul(b3, t4);
            t1 = Fp.add(t1, t2);
            t2 = Fp.sub(t0, t2); // step 30
            t2 = Fp.mul(a, t2);
            t4 = Fp.add(t4, t2);
            t0 = Fp.mul(t1, t4);
            Y3 = Fp.add(Y3, t0);
            t0 = Fp.mul(t5, t4); // step 35
            X3 = Fp.mul(t3, X3);
            X3 = Fp.sub(X3, t0);
            t0 = Fp.mul(t3, t1);
            Z3 = Fp.mul(t5, Z3);
            Z3 = Fp.add(Z3, t0); // step 40
            return new Point(X3, Y3, Z3);
        }
        subtract(other) {
            return this.add(other.negate());
        }
        is0() {
            return this.equals(Point.ZERO);
        }
        /**
         * Constant time multiplication.
         * Uses wNAF method. Windowed method may be 10% faster,
         * but takes 2x longer to generate and consumes 2x memory.
         * Uses precomputes when available.
         * Uses endomorphism for Koblitz curves.
         * @param scalar by which the point would be multiplied
         * @returns New point
         */
        multiply(scalar) {
            const { endo } = extraOpts;
            if (!Fn.isValidNot0(scalar))
                throw new Error('invalid scalar: out of range'); // 0 is invalid
            let point, fake; // Fake point is used to const-time mult
            const mul = (n) => wnaf.cached(this, n, (p) => normalizeZ(Point, p));
            /** See docs for {@link EndomorphismOpts} */
            if (endo) {
                const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);
                const { p: k1p, f: k1f } = mul(k1);
                const { p: k2p, f: k2f } = mul(k2);
                fake = k1f.add(k2f);
                point = finishEndo(endo.beta, k1p, k2p, k1neg, k2neg);
            }
            else {
                const { p, f } = mul(scalar);
                point = p;
                fake = f;
            }
            // Normalize `z` for both points, but return only real one
            return normalizeZ(Point, [point, fake])[0];
        }
        /**
         * Non-constant-time multiplication. Uses double-and-add algorithm.
         * It's faster, but should only be used when you don't care about
         * an exposed secret key e.g. sig verification, which works over *public* keys.
         */
        multiplyUnsafe(sc) {
            const { endo } = extraOpts;
            const p = this;
            if (!Fn.isValid(sc))
                throw new Error('invalid scalar: out of range'); // 0 is valid
            if (sc === _0n || p.is0())
                return Point.ZERO;
            if (sc === _1n)
                return p; // fast-path
            if (wnaf.hasCache(this))
                return this.multiply(sc);
            if (endo) {
                const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);
                const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2); // 30% faster vs wnaf.unsafe
                return finishEndo(endo.beta, p1, p2, k1neg, k2neg);
            }
            else {
                return wnaf.unsafe(p, sc);
            }
        }
        multiplyAndAddUnsafe(Q, a, b) {
            const sum = this.multiplyUnsafe(a).add(Q.multiplyUnsafe(b));
            return sum.is0() ? undefined : sum;
        }
        /**
         * Converts Projective point to affine (x, y) coordinates.
         * @param invertedZ Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch
         */
        toAffine(invertedZ) {
            return toAffineMemo(this, invertedZ);
        }
        /**
         * Checks whether Point is free of torsion elements (is in prime subgroup).
         * Always torsion-free for cofactor=1 curves.
         */
        isTorsionFree() {
            const { isTorsionFree } = extraOpts;
            if (cofactor === _1n)
                return true;
            if (isTorsionFree)
                return isTorsionFree(Point, this);
            return wnaf.unsafe(this, CURVE_ORDER).is0();
        }
        clearCofactor() {
            const { clearCofactor } = extraOpts;
            if (cofactor === _1n)
                return this; // Fast-path
            if (clearCofactor)
                return clearCofactor(Point, this);
            return this.multiplyUnsafe(cofactor);
        }
        isSmallOrder() {
            // can we use this.clearCofactor()?
            return this.multiplyUnsafe(cofactor).is0();
        }
        toBytes(isCompressed = true) {
            abool(isCompressed, 'isCompressed');
            this.assertValidity();
            return encodePoint(Point, this, isCompressed);
        }
        toHex(isCompressed = true) {
            return bytesToHex(this.toBytes(isCompressed));
        }
        toString() {
            return `<Point ${this.is0() ? 'ZERO' : this.toHex()}>`;
        }
        // TODO: remove
        get px() {
            return this.X;
        }
        get py() {
            return this.X;
        }
        get pz() {
            return this.Z;
        }
        toRawBytes(isCompressed = true) {
            return this.toBytes(isCompressed);
        }
        _setWindowSize(windowSize) {
            this.precompute(windowSize);
        }
        static normalizeZ(points) {
            return normalizeZ(Point, points);
        }
        static msm(points, scalars) {
            return pippenger(Point, Fn, points, scalars);
        }
        static fromPrivateKey(privateKey) {
            return Point.BASE.multiply(_normFnElement(Fn, privateKey));
        }
    }
    // base / generator point
    Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
    // zero / infinity / identity point
    Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); // 0, 1, 0
    // math field
    Point.Fp = Fp;
    // scalar field
    Point.Fn = Fn;
    const bits = Fn.BITS;
    const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);
    Point.BASE.precompute(8); // Enable precomputes. Slows down first publicKey computation by 20ms.
    return Point;
}
// Points start with byte 0x02 when y is even; otherwise 0x03
function pprefix(hasEvenY) {
    return Uint8Array.of(hasEvenY ? 0x02 : 0x03);
}
/**
 * Implementation of the Shallue and van de Woestijne method for any weierstrass curve.
 * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular.
 * b = True and y = sqrt(u / v) if (u / v) is square in F, and
 * b = False and y = sqrt(Z * (u / v)) otherwise.
 * @param Fp
 * @param Z
 * @returns
 */
export function SWUFpSqrtRatio(Fp, Z) {
    // Generic implementation
    const q = Fp.ORDER;
    let l = _0n;
    for (let o = q - _1n; o % _2n === _0n; o /= _2n)
        l += _1n;
    const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1.
    // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<.
    // 2n ** c1 == 2n << (c1-1)
    const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n);
    const _2n_pow_c1 = _2n_pow_c1_1 * _2n;
    const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1)  # Integer arithmetic
    const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2            # Integer arithmetic
    const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1                # Integer arithmetic
    const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1)                  # Integer arithmetic
    const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2
    const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2)
    let sqrtRatio = (u, v) => {
        let tv1 = c6; // 1. tv1 = c6
        let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4
        let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2
        tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v
        let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3
        tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3
        tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2
        tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v
        tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u
        let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2
        tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5
        let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1
        tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7
        tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1
        tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR)
        tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR)
        // 17. for i in (c1, c1 - 1, ..., 2):
        for (let i = c1; i > _1n; i--) {
            let tv5 = i - _2n; // 18.    tv5 = i - 2
            tv5 = _2n << (tv5 - _1n); // 19.    tv5 = 2^tv5
            let tvv5 = Fp.pow(tv4, tv5); // 20.    tv5 = tv4^tv5
            const e1 = Fp.eql(tvv5, Fp.ONE); // 21.    e1 = tv5 == 1
            tv2 = Fp.mul(tv3, tv1); // 22.    tv2 = tv3 * tv1
            tv1 = Fp.mul(tv1, tv1); // 23.    tv1 = tv1 * tv1
            tvv5 = Fp.mul(tv4, tv1); // 24.    tv5 = tv4 * tv1
            tv3 = Fp.cmov(tv2, tv3, e1); // 25.    tv3 = CMOV(tv2, tv3, e1)
            tv4 = Fp.cmov(tvv5, tv4, e1); // 26.    tv4 = CMOV(tv5, tv4, e1)
        }
        return { isValid: isQR, value: tv3 };
    };
    if (Fp.ORDER % _4n === _3n) {
        // sqrt_ratio_3mod4(u, v)
        const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4     # Integer arithmetic
        const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z)
        sqrtRatio = (u, v) => {
            let tv1 = Fp.sqr(v); // 1. tv1 = v^2
            const tv2 = Fp.mul(u, v); // 2. tv2 = u * v
            tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2
            let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1
            y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2
            const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2
            const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v
            const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u
            let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR)
            return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2
        };
    }
    // No curves uses that
    // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8
    return sqrtRatio;
}
/**
 * Simplified Shallue-van de Woestijne-Ulas Method
 * https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2
 */
export function mapToCurveSimpleSWU(Fp, opts) {
    validateField(Fp);
    const { A, B, Z } = opts;
    if (!Fp.isValid(A) || !Fp.isValid(B) || !Fp.isValid(Z))
        throw new Error('mapToCurveSimpleSWU: invalid opts');
    const sqrtRatio = SWUFpSqrtRatio(Fp, Z);
    if (!Fp.isOdd)
        throw new Error('Field does not have .isOdd()');
    // Input: u, an element of F.
    // Output: (x, y), a point on E.
    return (u) => {
        // prettier-ignore
        let tv1, tv2, tv3, tv4, tv5, tv6, x, y;
        tv1 = Fp.sqr(u); // 1.  tv1 = u^2
        tv1 = Fp.mul(tv1, Z); // 2.  tv1 = Z * tv1
        tv2 = Fp.sqr(tv1); // 3.  tv2 = tv1^2
        tv2 = Fp.add(tv2, tv1); // 4.  tv2 = tv2 + tv1
        tv3 = Fp.add(tv2, Fp.ONE); // 5.  tv3 = tv2 + 1
        tv3 = Fp.mul(tv3, B); // 6.  tv3 = B * tv3
        tv4 = Fp.cmov(Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7.  tv4 = CMOV(Z, -tv2, tv2 != 0)
        tv4 = Fp.mul(tv4, A); // 8.  tv4 = A * tv4
        tv2 = Fp.sqr(tv3); // 9.  tv2 = tv3^2
        tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2
        tv5 = Fp.mul(tv6, A); // 11. tv5 = A * tv6
        tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5
        tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3
        tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4
        tv5 = Fp.mul(tv6, B); // 15. tv5 = B * tv6
        tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5
        x = Fp.mul(tv1, tv3); // 17.   x = tv1 * tv3
        const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6)
        y = Fp.mul(tv1, u); // 19.   y = tv1 * u  -> Z * u^3 * y1
        y = Fp.mul(y, value); // 20.   y = y * y1
        x = Fp.cmov(x, tv3, isValid); // 21.   x = CMOV(x, tv3, is_gx1_square)
        y = Fp.cmov(y, value, isValid); // 22.   y = CMOV(y, y1, is_gx1_square)
        const e1 = Fp.isOdd(u) === Fp.isOdd(y); // 23.  e1 = sgn0(u) == sgn0(y)
        y = Fp.cmov(Fp.neg(y), y, e1); // 24.   y = CMOV(-y, y, e1)
        const tv4_inv = FpInvertBatch(Fp, [tv4], true)[0];
        x = Fp.mul(x, tv4_inv); // 25.   x = x / tv4
        return { x, y };
    };
}
function getWLengths(Fp, Fn) {
    return {
        secretKey: Fn.BYTES,
        publicKey: 1 + Fp.BYTES,
        publicKeyUncompressed: 1 + 2 * Fp.BYTES,
        publicKeyHasPrefix: true,
        signature: 2 * Fn.BYTES,
    };
}
/**
 * Sometimes users only need getPublicKey, getSharedSecret, and secret key handling.
 * This helper ensures no signature functionality is present. Less code, smaller bundle size.
 */
export function ecdh(Point, ecdhOpts = {}) {
    const { Fn } = Point;
    const randomBytes_ = ecdhOpts.randomBytes || randomBytesWeb;
    const lengths = Object.assign(getWLengths(Point.Fp, Fn), { seed: getMinHashLength(Fn.ORDER) });
    function isValidSecretKey(secretKey) {
        try {
            return !!_normFnElement(Fn, secretKey);
        }
        catch (error) {
            return false;
        }
    }
    function isValidPublicKey(publicKey, isCompressed) {
        const { publicKey: comp, publicKeyUncompressed } = lengths;
        try {
            const l = publicKey.length;
            if (isCompressed === true && l !== comp)
                return false;
            if (isCompressed === false && l !== publicKeyUncompressed)
                return false;
            return !!Point.fromBytes(publicKey);
        }
        catch (error) {
            return false;
        }
    }
    /**
     * Produces cryptographically secure secret key from random of size
     * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.
     */
    function randomSecretKey(seed = randomBytes_(lengths.seed)) {
        return mapHashToField(abytes(seed, lengths.seed, 'seed'), Fn.ORDER);
    }
    /**
     * Computes public key for a secret key. Checks for validity of the secret key.
     * @param isCompressed whether to return compact (default), or full key
     * @returns Public key, full when isCompressed=false; short when isCompressed=true
     */
    function getPublicKey(secretKey, isCompressed = true) {
        return Point.BASE.multiply(_normFnElement(Fn, secretKey)).toBytes(isCompressed);
    }
    function keygen(seed) {
        const secretKey = randomSecretKey(seed);
        return { secretKey, publicKey: getPublicKey(secretKey) };
    }
    /**
     * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.
     */
    function isProbPub(item) {
        if (typeof item === 'bigint')
            return false;
        if (item instanceof Point)
            return true;
        const { secretKey, publicKey, publicKeyUncompressed } = lengths;
        if (Fn.allowedLengths || secretKey === publicKey)
            return undefined;
        const l = ensureBytes('key', item).length;
        return l === publicKey || l === publicKeyUncompressed;
    }
    /**
     * ECDH (Elliptic Curve Diffie Hellman).
     * Computes shared public key from secret key A and public key B.
     * Checks: 1) secret key validity 2) shared key is on-curve.
     * Does NOT hash the result.
     * @param isCompressed whether to return compact (default), or full key
     * @returns shared public key
     */
    function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {
        if (isProbPub(secretKeyA) === true)
            throw new Error('first arg must be private key');
        if (isProbPub(publicKeyB) === false)
            throw new Error('second arg must be public key');
        const s = _normFnElement(Fn, secretKeyA);
        const b = Point.fromHex(publicKeyB); // checks for being on-curve
        return b.multiply(s).toBytes(isCompressed);
    }
    const utils = {
        isValidSecretKey,
        isValidPublicKey,
        randomSecretKey,
        // TODO: remove
        isValidPrivateKey: isValidSecretKey,
        randomPrivateKey: randomSecretKey,
        normPrivateKeyToScalar: (key) => _normFnElement(Fn, key),
        precompute(windowSize = 8, point = Point.BASE) {
            return point.precompute(windowSize, false);
        },
    };
    return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point, utils, lengths });
}
/**
 * Creates ECDSA signing interface for given elliptic curve `Point` and `hash` function.
 * We need `hash` for 2 features:
 * 1. Message prehash-ing. NOT used if `sign` / `verify` are called with `prehash: false`
 * 2. k generation in `sign`, using HMAC-drbg(hash)
 *
 * ECDSAOpts are only rarely needed.
 *
 * @example
 * ```js
 * const p256_Point = weierstrass(...);
 * const p256_sha256 = ecdsa(p256_Point, sha256);
 * const p256_sha224 = ecdsa(p256_Point, sha224);
 * const p256_sha224_r = ecdsa(p256_Point, sha224, { randomBytes: (length) => { ... } });
 * ```
 */
export function ecdsa(Point, hash, ecdsaOpts = {}) {
    ahash(hash);
    _validateObject(ecdsaOpts, {}, {
        hmac: 'function',
        lowS: 'boolean',
        randomBytes: 'function',
        bits2int: 'function',
        bits2int_modN: 'function',
    });
    const randomBytes = ecdsaOpts.randomBytes || randomBytesWeb;
    const hmac = ecdsaOpts.hmac ||
        ((key, ...msgs) => nobleHmac(hash, key, concatBytes(...msgs)));
    const { Fp, Fn } = Point;
    const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;
    const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);
    const defaultSigOpts = {
        prehash: false,
        lowS: typeof ecdsaOpts.lowS === 'boolean' ? ecdsaOpts.lowS : false,
        format: undefined, //'compact' as ECDSASigFormat,
        extraEntropy: false,
    };
    const defaultSigOpts_format = 'compact';
    function isBiggerThanHalfOrder(number) {
        const HALF = CURVE_ORDER >> _1n;
        return number > HALF;
    }
    function validateRS(title, num) {
        if (!Fn.isValidNot0(num))
            throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);
        return num;
    }
    function validateSigLength(bytes, format) {
        validateSigFormat(format);
        const size = lengths.signature;
        const sizer = format === 'compact' ? size : format === 'recovered' ? size + 1 : undefined;
        return abytes(bytes, sizer, `${format} signature`);
    }
    /**
     * ECDSA signature with its (r, s) properties. Supports compact, recovered & DER representations.
     */
    class Signature {
        constructor(r, s, recovery) {
            this.r = validateRS('r', r); // r in [1..N-1];
            this.s = validateRS('s', s); // s in [1..N-1];
            if (recovery != null)
                this.recovery = recovery;
            Object.freeze(this);
        }
        static fromBytes(bytes, format = defaultSigOpts_format) {
            validateSigLength(bytes, format);
            let recid;
            if (format === 'der') {
                const { r, s } = DER.toSig(abytes(bytes));
                return new Signature(r, s);
            }
            if (format === 'recovered') {
                recid = bytes[0];
                format = 'compact';
                bytes = bytes.subarray(1);
            }
            const L = Fn.BYTES;
            const r = bytes.subarray(0, L);
            const s = bytes.subarray(L, L * 2);
            return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);
        }
        static fromHex(hex, format) {
            return this.fromBytes(hexToBytes(hex), format);
        }
        addRecoveryBit(recovery) {
            return new Signature(this.r, this.s, recovery);
        }
        recoverPublicKey(messageHash) {
            const FIELD_ORDER = Fp.ORDER;
            const { r, s, recovery: rec } = this;
            if (rec == null || ![0, 1, 2, 3].includes(rec))
                throw new Error('recovery id invalid');
            // ECDSA recovery is hard for cofactor > 1 curves.
            // In sign, `r = q.x mod n`, and here we recover q.x from r.
            // While recovering q.x >= n, we need to add r+n for cofactor=1 curves.
            // However, for cofactor>1, r+n may not get q.x:
            // r+n*i would need to be done instead where i is unknown.
            // To easily get i, we either need to:
            // a. increase amount of valid recid values (4, 5...); OR
            // b. prohibit non-prime-order signatures (recid > 1).
            const hasCofactor = CURVE_ORDER * _2n < FIELD_ORDER;
            if (hasCofactor && rec > 1)
                throw new Error('recovery id is ambiguous for h>1 curve');
            const radj = rec === 2 || rec === 3 ? r + CURVE_ORDER : r;
            if (!Fp.isValid(radj))
                throw new Error('recovery id 2 or 3 invalid');
            const x = Fp.toBytes(radj);
            const R = Point.fromBytes(concatBytes(pprefix((rec & 1) === 0), x));
            const ir = Fn.inv(radj); // r^-1
            const h = bits2int_modN(ensureBytes('msgHash', messageHash)); // Truncate hash
            const u1 = Fn.create(-h * ir); // -hr^-1
            const u2 = Fn.create(s * ir); // sr^-1
            // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1). unsafe is fine: there is no private data.
            const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));
            if (Q.is0())
                throw new Error('point at infinify');
            Q.assertValidity();
            return Q;
        }
        // Signatures should be low-s, to prevent malleability.
        hasHighS() {
            return isBiggerThanHalfOrder(this.s);
        }
        toBytes(format = defaultSigOpts_format) {
            validateSigFormat(format);
            if (format === 'der')
                return hexToBytes(DER.hexFromSig(this));
            const r = Fn.toBytes(this.r);
            const s = Fn.toBytes(this.s);
            if (format === 'recovered') {
                if (this.recovery == null)
                    throw new Error('recovery bit must be present');
                return concatBytes(Uint8Array.of(this.recovery), r, s);
            }
            return concatBytes(r, s);
        }
        toHex(format) {
            return bytesToHex(this.toBytes(format));
        }
        // TODO: remove
        assertValidity() { }
        static fromCompact(hex) {
            return Signature.fromBytes(ensureBytes('sig', hex), 'compact');
        }
        static fromDER(hex) {
            return Signature.fromBytes(ensureBytes('sig', hex), 'der');
        }
        normalizeS() {
            return this.hasHighS() ? new Signature(this.r, Fn.neg(this.s), this.recovery) : this;
        }
        toDERRawBytes() {
            return this.toBytes('der');
        }
        toDERHex() {
            return bytesToHex(this.toBytes('der'));
        }
        toCompactRawBytes() {
            return this.toBytes('compact');
        }
        toCompactHex() {
            return bytesToHex(this.toBytes('compact'));
        }
    }
    // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.
    // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.
    // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.
    // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors
    const bits2int = ecdsaOpts.bits2int ||
        function bits2int_def(bytes) {
            // Our custom check "just in case", for protection against DoS
            if (bytes.length > 8192)
                throw new Error('input is too large');
            // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)
            // for some cases, since bytes.length * 8 is not actual bitLength.
            const num = bytesToNumberBE(bytes); // check for == u8 done here
            const delta = bytes.length * 8 - fnBits; // truncate to nBitLength leftmost bits
            return delta > 0 ? num >> BigInt(delta) : num;
        };
    const bits2int_modN = ecdsaOpts.bits2int_modN ||
        function bits2int_modN_def(bytes) {
            return Fn.create(bits2int(bytes)); // can't use bytesToNumberBE here
        };
    // Pads output with zero as per spec
    const ORDER_MASK = bitMask(fnBits);
    /** Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. */
    function int2octets(num) {
        // IMPORTANT: the check ensures working for case `Fn.BYTES != Fn.BITS * 8`
        aInRange('num < 2^' + fnBits, num, _0n, ORDER_MASK);
        return Fn.toBytes(num);
    }
    function validateMsgAndHash(message, prehash) {
        abytes(message, undefined, 'message');
        return prehash ? abytes(hash(message), undefined, 'prehashed message') : message;
    }
    /**
     * Steps A, D of RFC6979 3.2.
     * Creates RFC6979 seed; converts msg/privKey to numbers.
     * Used only in sign, not in verify.
     *
     * Warning: we cannot assume here that message has same amount of bytes as curve order,
     * this will be invalid at least for P521. Also it can be bigger for P224 + SHA256.
     */
    function prepSig(message, privateKey, opts) {
        if (['recovered', 'canonical'].some((k) => k in opts))
            throw new Error('sign() legacy options not supported');
        const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);
        message = validateMsgAndHash(message, prehash); // RFC6979 3.2 A: h1 = H(m)
        // We can't later call bits2octets, since nested bits2int is broken for curves
        // with fnBits % 8 !== 0. Because of that, we unwrap it here as int2octets call.
        // const bits2octets = (bits) => int2octets(bits2int_modN(bits))
        const h1int = bits2int_modN(message);
        const d = _normFnElement(Fn, privateKey); // validate secret key, convert to bigint
        const seedArgs = [int2octets(d), int2octets(h1int)];
        // extraEntropy. RFC6979 3.6: additional k' (optional).
        if (extraEntropy != null && extraEntropy !== false) {
            // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')
            // gen random bytes OR pass as-is
            const e = extraEntropy === true ? randomBytes(lengths.secretKey) : extraEntropy;
            seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes
        }
        const seed = concatBytes(...seedArgs); // Step D of RFC6979 3.2
        const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash!
        // Converts signature params into point w r/s, checks result for validity.
        // To transform k => Signature:
        // q = k⋅G
        // r = q.x mod n
        // s = k^-1(m + rd) mod n
        // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to
        // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:
        // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT
        function k2sig(kBytes) {
            // RFC 6979 Section 3.2, step 3: k = bits2int(T)
            // Important: all mod() calls here must be done over N
            const k = bits2int(kBytes); // mod n, not mod p
            if (!Fn.isValidNot0(k))
                return; // Valid scalars (including k) must be in 1..N-1
            const ik = Fn.inv(k); // k^-1 mod n
            const q = Point.BASE.multiply(k).toAffine(); // q = k⋅G
            const r = Fn.create(q.x); // r = q.x mod n
            if (r === _0n)
                return;
            const s = Fn.create(ik * Fn.create(m + r * d)); // Not using blinding here, see comment above
            if (s === _0n)
                return;
            let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n)
            let normS = s;
            if (lowS && isBiggerThanHalfOrder(s)) {
                normS = Fn.neg(s); // if lowS was passed, ensure s is always
                recovery ^= 1; // // in the bottom half of N
            }
            return new Signature(r, normS, recovery); // use normS, not s
        }
        return { seed, k2sig };
    }
    /**
     * Signs message hash with a secret key.
     *
     * ```
     * sign(m, d) where
     *   k = rfc6979_hmac_drbg(m, d)
     *   (x, y) = G × k
     *   r = x mod n
     *   s = (m + dr) / k mod n
     * ```
     */
    function sign(message, secretKey, opts = {}) {
        message = ensureBytes('message', message);
        const { seed, k2sig } = prepSig(message, secretKey, opts); // Steps A, D of RFC6979 3.2.
        const drbg = createHmacDrbg(hash.outputLen, Fn.BYTES, hmac);
        const sig = drbg(seed, k2sig); // Steps B, C, D, E, F, G
        return sig;
    }
    function tryParsingSig(sg) {
        // Try to deduce format
        let sig = undefined;
        const isHex = typeof sg === 'string' || isBytes(sg);
        const isObj = !isHex &&
            sg !== null &&
            typeof sg === 'object' &&
            typeof sg.r === 'bigint' &&
            typeof sg.s === 'bigint';
        if (!isHex && !isObj)
            throw new Error('invalid signature, expected Uint8Array, hex string or Signature instance');
        if (isObj) {
            sig = new Signature(sg.r, sg.s);
        }
        else if (isHex) {
            try {
                sig = Signature.fromBytes(ensureBytes('sig', sg), 'der');
            }
            catch (derError) {
                if (!(derError instanceof DER.Err))
                    throw derError;
            }
            if (!sig) {
                try {
                    sig = Signature.fromBytes(ensureBytes('sig', sg), 'compact');
                }
                catch (error) {
                    return false;
                }
            }
        }
        if (!sig)
            return false;
        return sig;
    }
    /**
     * Verifies a signature against message and public key.
     * Rejects lowS signatures by default: see {@link ECDSAVerifyOpts}.
     * Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:
     *
     * ```
     * verify(r, s, h, P) where
     *   u1 = hs^-1 mod n
     *   u2 = rs^-1 mod n
     *   R = u1⋅G + u2⋅P
     *   mod(R.x, n) == r
     * ```
     */
    function verify(signature, message, publicKey, opts = {}) {
        const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);
        publicKey = ensureBytes('publicKey', publicKey);
        message = validateMsgAndHash(ensureBytes('message', message), prehash);
        if ('strict' in opts)
            throw new Error('options.strict was renamed to lowS');
        const sig = format === undefined
            ? tryParsingSig(signature)
            : Signature.fromBytes(ensureBytes('sig', signature), format);
        if (sig === false)
            return false;
        try {
            const P = Point.fromBytes(publicKey);
            if (lowS && sig.hasHighS())
                return false;
            const { r, s } = sig;
            const h = bits2int_modN(message); // mod n, not mod p
            const is = Fn.inv(s); // s^-1 mod n
            const u1 = Fn.create(h * is); // u1 = hs^-1 mod n
            const u2 = Fn.create(r * is); // u2 = rs^-1 mod n
            const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2)); // u1⋅G + u2⋅P
            if (R.is0())
                return false;
            const v = Fn.create(R.x); // v = r.x mod n
            return v === r;
        }
        catch (e) {
            return false;
        }
    }
    function recoverPublicKey(signature, message, opts = {}) {
        const { prehash } = validateSigOpts(opts, defaultSigOpts);
        message = validateMsgAndHash(message, prehash);
        return Signature.fromBytes(signature, 'recovered').recoverPublicKey(message).toBytes();
    }
    return Object.freeze({
        keygen,
        getPublicKey,
        getSharedSecret,
        utils,
        lengths,
        Point,
        sign,
        verify,
        recoverPublicKey,
        Signature,
        hash,
    });
}
/** @deprecated use `weierstrass` in newer releases */
export function weierstrassPoints(c) {
    const { CURVE, curveOpts } = _weierstrass_legacy_opts_to_new(c);
    const Point = weierstrassN(CURVE, curveOpts);
    return _weierstrass_new_output_to_legacy(c, Point);
}
function _weierstrass_legacy_opts_to_new(c) {
    const CURVE = {
        a: c.a,
        b: c.b,
        p: c.Fp.ORDER,
        n: c.n,
        h: c.h,
        Gx: c.Gx,
        Gy: c.Gy,
    };
    const Fp = c.Fp;
    let allowedLengths = c.allowedPrivateKeyLengths
        ? Array.from(new Set(c.allowedPrivateKeyLengths.map((l) => Math.ceil(l / 2))))
        : undefined;
    const Fn = Field(CURVE.n, {
        BITS: c.nBitLength,
        allowedLengths: allowedLengths,
        modFromBytes: c.wrapPrivateKey,
    });
    const curveOpts = {
        Fp,
        Fn,
        allowInfinityPoint: c.allowInfinityPoint,
        endo: c.endo,
        isTorsionFree: c.isTorsionFree,
        clearCofactor: c.clearCofactor,
        fromBytes: c.fromBytes,
        toBytes: c.toBytes,
    };
    return { CURVE, curveOpts };
}
function _ecdsa_legacy_opts_to_new(c) {
    const { CURVE, curveOpts } = _weierstrass_legacy_opts_to_new(c);
    const ecdsaOpts = {
        hmac: c.hmac,
        randomBytes: c.randomBytes,
        lowS: c.lowS,
        bits2int: c.bits2int,
        bits2int_modN: c.bits2int_modN,
    };
    return { CURVE, curveOpts, hash: c.hash, ecdsaOpts };
}
export function _legacyHelperEquat(Fp, a, b) {
    /**
     * y² = x³ + ax + b: Short weierstrass curve formula. Takes x, returns y².
     * @returns y²
     */
    function weierstrassEquation(x) {
        const x2 = Fp.sqr(x); // x * x
        const x3 = Fp.mul(x2, x); // x² * x
        return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x³ + a * x + b
    }
    return weierstrassEquation;
}
function _weierstrass_new_output_to_legacy(c, Point) {
    const { Fp, Fn } = Point;
    function isWithinCurveOrder(num) {
        return inRange(num, _1n, Fn.ORDER);
    }
    const weierstrassEquation = _legacyHelperEquat(Fp, c.a, c.b);
    return Object.assign({}, {
        CURVE: c,
        Point: Point,
        ProjectivePoint: Point,
        normPrivateKeyToScalar: (key) => _normFnElement(Fn, key),
        weierstrassEquation,
        isWithinCurveOrder,
    });
}
function _ecdsa_new_output_to_legacy(c, _ecdsa) {
    const Point = _ecdsa.Point;
    return Object.assign({}, _ecdsa, {
        ProjectivePoint: Point,
        CURVE: Object.assign({}, c, nLength(Point.Fn.ORDER, Point.Fn.BITS)),
    });
}
// _ecdsa_legacy
export function weierstrass(c) {
    const { CURVE, curveOpts, hash, ecdsaOpts } = _ecdsa_legacy_opts_to_new(c);
    const Point = weierstrassN(CURVE, curveOpts);
    const signs = ecdsa(Point, hash, ecdsaOpts);
    return _ecdsa_new_output_to_legacy(c, signs);
}
//# sourceMappingURL=weierstrass.js.map{
  "type": "module",
  "sideEffects": false
}
/**
 * SECG secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).
 *
 * Belongs to Koblitz curves: it has efficiently-computable GLV endomorphism ψ,
 * check out {@link EndomorphismOpts}. Seems to be rigid (not backdoored).
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { sha256 } from '@noble/hashes/sha2.js';
import { randomBytes } from '@noble/hashes/utils.js';
import { createCurve } from "./_shortw_utils.js";
import { createHasher, isogenyMap, } from "./abstract/hash-to-curve.js";
import { Field, mapHashToField, mod, pow2 } from "./abstract/modular.js";
import { _normFnElement, mapToCurveSimpleSWU, } from "./abstract/weierstrass.js";
import { bytesToNumberBE, concatBytes, ensureBytes, inRange, numberToBytesBE, utf8ToBytes, } from "./utils.js";
// Seems like generator was produced from some seed:
// `Point.BASE.multiply(Point.Fn.inv(2n, N)).toAffine().x`
// // gives short x 0x3b78ce563f89a0ed9414f5aa28ad0d96d6795f9c63n
const secp256k1_CURVE = {
    p: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'),
    n: BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'),
    h: BigInt(1),
    a: BigInt(0),
    b: BigInt(7),
    Gx: BigInt('0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'),
    Gy: BigInt('0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8'),
};
const secp256k1_ENDO = {
    beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),
    basises: [
        [BigInt('0x3086d221a7d46bcde86c90e49284eb15'), -BigInt('0xe4437ed6010e88286f547fa90abfe4c3')],
        [BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'), BigInt('0x3086d221a7d46bcde86c90e49284eb15')],
    ],
};
const _0n = /* @__PURE__ */ BigInt(0);
const _1n = /* @__PURE__ */ BigInt(1);
const _2n = /* @__PURE__ */ BigInt(2);
/**
 * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.
 * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]
 */
function sqrtMod(y) {
    const P = secp256k1_CURVE.p;
    // prettier-ignore
    const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
    // prettier-ignore
    const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
    const b2 = (y * y * y) % P; // x^3, 11
    const b3 = (b2 * b2 * y) % P; // x^7
    const b6 = (pow2(b3, _3n, P) * b3) % P;
    const b9 = (pow2(b6, _3n, P) * b3) % P;
    const b11 = (pow2(b9, _2n, P) * b2) % P;
    const b22 = (pow2(b11, _11n, P) * b11) % P;
    const b44 = (pow2(b22, _22n, P) * b22) % P;
    const b88 = (pow2(b44, _44n, P) * b44) % P;
    const b176 = (pow2(b88, _88n, P) * b88) % P;
    const b220 = (pow2(b176, _44n, P) * b44) % P;
    const b223 = (pow2(b220, _3n, P) * b3) % P;
    const t1 = (pow2(b223, _23n, P) * b22) % P;
    const t2 = (pow2(t1, _6n, P) * b2) % P;
    const root = pow2(t2, _2n, P);
    if (!Fpk1.eql(Fpk1.sqr(root), y))
        throw new Error('Cannot find square root');
    return root;
}
const Fpk1 = Field(secp256k1_CURVE.p, { sqrt: sqrtMod });
/**
 * secp256k1 curve, ECDSA and ECDH methods.
 *
 * Field: `2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n`
 *
 * @example
 * ```js
 * import { secp256k1 } from '@noble/curves/secp256k1';
 * const { secretKey, publicKey } = secp256k1.keygen();
 * const msg = new TextEncoder().encode('hello');
 * const sig = secp256k1.sign(msg, secretKey);
 * const isValid = secp256k1.verify(sig, msg, publicKey) === true;
 * ```
 */
export const secp256k1 = createCurve({ ...secp256k1_CURVE, Fp: Fpk1, lowS: true, endo: secp256k1_ENDO }, sha256);
// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.
// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki
/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */
const TAGGED_HASH_PREFIXES = {};
function taggedHash(tag, ...messages) {
    let tagP = TAGGED_HASH_PREFIXES[tag];
    if (tagP === undefined) {
        const tagH = sha256(utf8ToBytes(tag));
        tagP = concatBytes(tagH, tagH);
        TAGGED_HASH_PREFIXES[tag] = tagP;
    }
    return sha256(concatBytes(tagP, ...messages));
}
// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03
const pointToBytes = (point) => point.toBytes(true).slice(1);
const Pointk1 = /* @__PURE__ */ (() => secp256k1.Point)();
const hasEven = (y) => y % _2n === _0n;
// Calculate point, scalar and bytes
function schnorrGetExtPubKey(priv) {
    const { Fn, BASE } = Pointk1;
    const d_ = _normFnElement(Fn, priv);
    const p = BASE.multiply(d_); // P = d'⋅G; 0 < d' < n check is done inside
    const scalar = hasEven(p.y) ? d_ : Fn.neg(d_);
    return { scalar, bytes: pointToBytes(p) };
}
/**
 * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.
 * @returns valid point checked for being on-curve
 */
function lift_x(x) {
    const Fp = Fpk1;
    if (!Fp.isValidNot0(x))
        throw new Error('invalid x: Fail if x ≥ p');
    const xx = Fp.create(x * x);
    const c = Fp.create(xx * x + BigInt(7)); // Let c = x³ + 7 mod p.
    let y = Fp.sqrt(c); // Let y = c^(p+1)/4 mod p. Same as sqrt().
    // Return the unique point P such that x(P) = x and
    // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.
    if (!hasEven(y))
        y = Fp.neg(y);
    const p = Pointk1.fromAffine({ x, y });
    p.assertValidity();
    return p;
}
const num = bytesToNumberBE;
/**
 * Create tagged hash, convert it to bigint, reduce modulo-n.
 */
function challenge(...args) {
    return Pointk1.Fn.create(num(taggedHash('BIP0340/challenge', ...args)));
}
/**
 * Schnorr public key is just `x` coordinate of Point as per BIP340.
 */
function schnorrGetPublicKey(secretKey) {
    return schnorrGetExtPubKey(secretKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G)
}
/**
 * Creates Schnorr signature as per BIP340. Verifies itself before returning anything.
 * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous.
 */
function schnorrSign(message, secretKey, auxRand = randomBytes(32)) {
    const { Fn } = Pointk1;
    const m = ensureBytes('message', message);
    const { bytes: px, scalar: d } = schnorrGetExtPubKey(secretKey); // checks for isWithinCurveOrder
    const a = ensureBytes('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array
    const t = Fn.toBytes(d ^ num(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a)
    const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m)
    // Let k' = int(rand) mod n. Fail if k' = 0. Let R = k'⋅G
    const { bytes: rx, scalar: k } = schnorrGetExtPubKey(rand);
    const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.
    const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n).
    sig.set(rx, 0);
    sig.set(Fn.toBytes(Fn.create(k + e * d)), 32);
    // If Verify(bytes(P), m, sig) (see below) returns failure, abort
    if (!schnorrVerify(sig, m, px))
        throw new Error('sign: Invalid signature produced');
    return sig;
}
/**
 * Verifies Schnorr signature.
 * Will swallow errors & return false except for initial type validation of arguments.
 */
function schnorrVerify(signature, message, publicKey) {
    const { Fn, BASE } = Pointk1;
    const sig = ensureBytes('signature', signature, 64);
    const m = ensureBytes('message', message);
    const pub = ensureBytes('publicKey', publicKey, 32);
    try {
        const P = lift_x(num(pub)); // P = lift_x(int(pk)); fail if that fails
        const r = num(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r ≥ p.
        if (!inRange(r, _1n, secp256k1_CURVE.p))
            return false;
        const s = num(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n.
        if (!inRange(s, _1n, secp256k1_CURVE.n))
            return false;
        // int(challenge(bytes(r)||bytes(P)||m))%n
        const e = challenge(Fn.toBytes(r), pointToBytes(P), m);
        // R = s⋅G - e⋅P, where -eP == (n-e)P
        const R = BASE.multiplyUnsafe(s).add(P.multiplyUnsafe(Fn.neg(e)));
        const { x, y } = R.toAffine();
        // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r.
        if (R.is0() || !hasEven(y) || x !== r)
            return false;
        return true;
    }
    catch (error) {
        return false;
    }
}
/**
 * Schnorr signatures over secp256k1.
 * https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki
 * @example
 * ```js
 * import { schnorr } from '@noble/curves/secp256k1';
 * const { secretKey, publicKey } = schnorr.keygen();
 * // const publicKey = schnorr.getPublicKey(secretKey);
 * const msg = new TextEncoder().encode('hello');
 * const sig = schnorr.sign(msg, secretKey);
 * const isValid = schnorr.verify(sig, msg, publicKey);
 * ```
 */
export const schnorr = /* @__PURE__ */ (() => {
    const size = 32;
    const seedLength = 48;
    const randomSecretKey = (seed = randomBytes(seedLength)) => {
        return mapHashToField(seed, secp256k1_CURVE.n);
    };
    // TODO: remove
    secp256k1.utils.randomSecretKey;
    function keygen(seed) {
        const secretKey = randomSecretKey(seed);
        return { secretKey, publicKey: schnorrGetPublicKey(secretKey) };
    }
    return {
        keygen,
        getPublicKey: schnorrGetPublicKey,
        sign: schnorrSign,
        verify: schnorrVerify,
        Point: Pointk1,
        utils: {
            randomSecretKey: randomSecretKey,
            randomPrivateKey: randomSecretKey,
            taggedHash,
            // TODO: remove
            lift_x,
            pointToBytes,
            numberToBytesBE,
            bytesToNumberBE,
            mod,
        },
        lengths: {
            secretKey: size,
            publicKey: size,
            publicKeyHasPrefix: false,
            signature: size * 2,
            seed: seedLength,
        },
    };
})();
const isoMap = /* @__PURE__ */ (() => isogenyMap(Fpk1, [
    // xNum
    [
        '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7',
        '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581',
        '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262',
        '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c',
    ],
    // xDen
    [
        '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b',
        '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14',
        '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1
    ],
    // yNum
    [
        '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c',
        '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3',
        '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931',
        '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84',
    ],
    // yDen
    [
        '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b',
        '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573',
        '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f',
        '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1
    ],
].map((i) => i.map((j) => BigInt(j)))))();
const mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fpk1, {
    A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),
    B: BigInt('1771'),
    Z: Fpk1.create(BigInt('-11')),
}))();
/** Hashing / encoding to secp256k1 points / field. RFC 9380 methods. */
export const secp256k1_hasher = /* @__PURE__ */ (() => createHasher(secp256k1.Point, (scalars) => {
    const { x, y } = mapSWU(Fpk1.create(scalars[0]));
    return isoMap(x, y);
}, {
    DST: 'secp256k1_XMD:SHA-256_SSWU_RO_',
    encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_',
    p: Fpk1.ORDER,
    m: 1,
    k: 128,
    expand: 'xmd',
    hash: sha256,
}))();
/** @deprecated use `import { secp256k1_hasher } from '@noble/curves/secp256k1.js';` */
export const hashToCurve = /* @__PURE__ */ (() => secp256k1_hasher.hashToCurve)();
/** @deprecated use `import { secp256k1_hasher } from '@noble/curves/secp256k1.js';` */
export const encodeToCurve = /* @__PURE__ */ (() => secp256k1_hasher.encodeToCurve)();
//# sourceMappingURL=secp256k1.js.map/**
 * Hex, bytes and number utilities.
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { abytes as abytes_, bytesToHex as bytesToHex_, concatBytes as concatBytes_, hexToBytes as hexToBytes_, isBytes as isBytes_, } from '@noble/hashes/utils.js';
export { abytes, anumber, bytesToHex, bytesToUtf8, concatBytes, hexToBytes, isBytes, randomBytes, utf8ToBytes, } from '@noble/hashes/utils.js';
const _0n = /* @__PURE__ */ BigInt(0);
const _1n = /* @__PURE__ */ BigInt(1);
export function abool(title, value) {
    if (typeof value !== 'boolean')
        throw new Error(title + ' boolean expected, got ' + value);
}
// tmp name until v2
export function _abool2(value, title = '') {
    if (typeof value !== 'boolean') {
        const prefix = title && `"${title}"`;
        throw new Error(prefix + 'expected boolean, got type=' + typeof value);
    }
    return value;
}
// tmp name until v2
/** Asserts something is Uint8Array. */
export function _abytes2(value, length, title = '') {
    const bytes = isBytes_(value);
    const len = value?.length;
    const needsLen = length !== undefined;
    if (!bytes || (needsLen && len !== length)) {
        const prefix = title && `"${title}" `;
        const ofLen = needsLen ? ` of length ${length}` : '';
        const got = bytes ? `length=${len}` : `type=${typeof value}`;
        throw new Error(prefix + 'expected Uint8Array' + ofLen + ', got ' + got);
    }
    return value;
}
// Used in weierstrass, der
export function numberToHexUnpadded(num) {
    const hex = num.toString(16);
    return hex.length & 1 ? '0' + hex : hex;
}
export function hexToNumber(hex) {
    if (typeof hex !== 'string')
        throw new Error('hex string expected, got ' + typeof hex);
    return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian
}
// BE: Big Endian, LE: Little Endian
export function bytesToNumberBE(bytes) {
    return hexToNumber(bytesToHex_(bytes));
}
export function bytesToNumberLE(bytes) {
    abytes_(bytes);
    return hexToNumber(bytesToHex_(Uint8Array.from(bytes).reverse()));
}
export function numberToBytesBE(n, len) {
    return hexToBytes_(n.toString(16).padStart(len * 2, '0'));
}
export function numberToBytesLE(n, len) {
    return numberToBytesBE(n, len).reverse();
}
// Unpadded, rarely used
export function numberToVarBytesBE(n) {
    return hexToBytes_(numberToHexUnpadded(n));
}
/**
 * Takes hex string or Uint8Array, converts to Uint8Array.
 * Validates output length.
 * Will throw error for other types.
 * @param title descriptive title for an error e.g. 'secret key'
 * @param hex hex string or Uint8Array
 * @param expectedLength optional, will compare to result array's length
 * @returns
 */
export function ensureBytes(title, hex, expectedLength) {
    let res;
    if (typeof hex === 'string') {
        try {
            res = hexToBytes_(hex);
        }
        catch (e) {
            throw new Error(title + ' must be hex string or Uint8Array, cause: ' + e);
        }
    }
    else if (isBytes_(hex)) {
        // Uint8Array.from() instead of hash.slice() because node.js Buffer
        // is instance of Uint8Array, and its slice() creates **mutable** copy
        res = Uint8Array.from(hex);
    }
    else {
        throw new Error(title + ' must be hex string or Uint8Array');
    }
    const len = res.length;
    if (typeof expectedLength === 'number' && len !== expectedLength)
        throw new Error(title + ' of length ' + expectedLength + ' expected, got ' + len);
    return res;
}
// Compares 2 u8a-s in kinda constant time
export function equalBytes(a, b) {
    if (a.length !== b.length)
        return false;
    let diff = 0;
    for (let i = 0; i < a.length; i++)
        diff |= a[i] ^ b[i];
    return diff === 0;
}
/**
 * Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,
 * and Buffer#slice creates mutable copy. Never use Buffers!
 */
export function copyBytes(bytes) {
    return Uint8Array.from(bytes);
}
/**
 * Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols
 * Should be safe to use for things expected to be ASCII.
 * Returns exact same result as utf8ToBytes for ASCII or throws.
 */
export function asciiToBytes(ascii) {
    return Uint8Array.from(ascii, (c, i) => {
        const charCode = c.charCodeAt(0);
        if (c.length !== 1 || charCode > 127) {
            throw new Error(`string contains non-ASCII character "${ascii[i]}" with code ${charCode} at position ${i}`);
        }
        return charCode;
    });
}
/**
 * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
 */
// export const utf8ToBytes: typeof utf8ToBytes_ = utf8ToBytes_;
/**
 * Converts bytes to string using UTF8 encoding.
 * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'
 */
// export const bytesToUtf8: typeof bytesToUtf8_ = bytesToUtf8_;
// Is positive bigint
const isPosBig = (n) => typeof n === 'bigint' && _0n <= n;
export function inRange(n, min, max) {
    return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
}
/**
 * Asserts min <= n < max. NOTE: It's < max and not <= max.
 * @example
 * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)
 */
export function aInRange(title, n, min, max) {
    // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?
    // consider P=256n, min=0n, max=P
    // - a for min=0 would require -1:          `inRange('x', x, -1n, P)`
    // - b would commonly require subtraction:  `inRange('x', x, 0n, P - 1n)`
    // - our way is the cleanest:               `inRange('x', x, 0n, P)
    if (!inRange(n, min, max))
        throw new Error('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);
}
// Bit operations
/**
 * Calculates amount of bits in a bigint.
 * Same as `n.toString(2).length`
 * TODO: merge with nLength in modular
 */
export function bitLen(n) {
    let len;
    for (len = 0; n > _0n; n >>= _1n, len += 1)
        ;
    return len;
}
/**
 * Gets single bit at position.
 * NOTE: first bit position is 0 (same as arrays)
 * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`
 */
export function bitGet(n, pos) {
    return (n >> BigInt(pos)) & _1n;
}
/**
 * Sets single bit at position.
 */
export function bitSet(n, pos, value) {
    return n | ((value ? _1n : _0n) << BigInt(pos));
}
/**
 * Calculate mask for N bits. Not using ** operator with bigints because of old engines.
 * Same as BigInt(`0b${Array(i).fill('1').join('')}`)
 */
export const bitMask = (n) => (_1n << BigInt(n)) - _1n;
/**
 * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
 * @returns function that will call DRBG until 2nd arg returns something meaningful
 * @example
 *   const drbg = createHmacDRBG<Key>(32, 32, hmac);
 *   drbg(seed, bytesToKey); // bytesToKey must return Key or undefined
 */
export function createHmacDrbg(hashLen, qByteLen, hmacFn) {
    if (typeof hashLen !== 'number' || hashLen < 2)
        throw new Error('hashLen must be a number');
    if (typeof qByteLen !== 'number' || qByteLen < 2)
        throw new Error('qByteLen must be a number');
    if (typeof hmacFn !== 'function')
        throw new Error('hmacFn must be a function');
    // Step B, Step C: set hashLen to 8*ceil(hlen/8)
    const u8n = (len) => new Uint8Array(len); // creates Uint8Array
    const u8of = (byte) => Uint8Array.of(byte); // another shortcut
    let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
    let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same
    let i = 0; // Iterations counter, will throw when over 1000
    const reset = () => {
        v.fill(1);
        k.fill(0);
        i = 0;
    };
    const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)
    const reseed = (seed = u8n(0)) => {
        // HMAC-DRBG reseed() function. Steps D-G
        k = h(u8of(0x00), seed); // k = hmac(k || v || 0x00 || seed)
        v = h(); // v = hmac(k || v)
        if (seed.length === 0)
            return;
        k = h(u8of(0x01), seed); // k = hmac(k || v || 0x01 || seed)
        v = h(); // v = hmac(k || v)
    };
    const gen = () => {
        // HMAC-DRBG generate() function
        if (i++ >= 1000)
            throw new Error('drbg: tried 1000 values');
        let len = 0;
        const out = [];
        while (len < qByteLen) {
            v = h();
            const sl = v.slice();
            out.push(sl);
            len += v.length;
        }
        return concatBytes_(...out);
    };
    const genUntil = (seed, pred) => {
        reset();
        reseed(seed); // Steps D-G
        let res = undefined; // Step H: grind until k is in [1..n-1]
        while (!(res = pred(gen())))
            reseed();
        reset();
        return res;
    };
    return genUntil;
}
// Validating curves and fields
const validatorFns = {
    bigint: (val) => typeof val === 'bigint',
    function: (val) => typeof val === 'function',
    boolean: (val) => typeof val === 'boolean',
    string: (val) => typeof val === 'string',
    stringOrUint8Array: (val) => typeof val === 'string' || isBytes_(val),
    isSafeInteger: (val) => Number.isSafeInteger(val),
    array: (val) => Array.isArray(val),
    field: (val, object) => object.Fp.isValid(val),
    hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),
};
// type Record<K extends string | number | symbol, T> = { [P in K]: T; }
export function validateObject(object, validators, optValidators = {}) {
    const checkField = (fieldName, type, isOptional) => {
        const checkVal = validatorFns[type];
        if (typeof checkVal !== 'function')
            throw new Error('invalid validator function');
        const val = object[fieldName];
        if (isOptional && val === undefined)
            return;
        if (!checkVal(val, object)) {
            throw new Error('param ' + String(fieldName) + ' is invalid. Expected ' + type + ', got ' + val);
        }
    };
    for (const [fieldName, type] of Object.entries(validators))
        checkField(fieldName, type, false);
    for (const [fieldName, type] of Object.entries(optValidators))
        checkField(fieldName, type, true);
    return object;
}
// validate type tests
// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };
// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!
// // Should fail type-check
// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });
// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });
// const z3 = validateObject(o, { test: 'boolean', z: 'bug' });
// const z4 = validateObject(o, { a: 'boolean', z: 'bug' });
export function isHash(val) {
    return typeof val === 'function' && Number.isSafeInteger(val.outputLen);
}
export function _validateObject(object, fields, optFields = {}) {
    if (!object || typeof object !== 'object')
        throw new Error('expected valid options object');
    function checkField(fieldName, expectedType, isOpt) {
        const val = object[fieldName];
        if (isOpt && val === undefined)
            return;
        const current = typeof val;
        if (current !== expectedType || val === null)
            throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
    }
    Object.entries(fields).forEach(([k, v]) => checkField(k, v, false));
    Object.entries(optFields).forEach(([k, v]) => checkField(k, v, true));
}
/**
 * throws not implemented error
 */
export const notImplemented = () => {
    throw new Error('not implemented');
};
/**
 * Memoizes (caches) computation result.
 * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.
 */
export function memoized(fn) {
    const map = new WeakMap();
    return (arg, ...args) => {
        const val = map.get(arg);
        if (val !== undefined)
            return val;
        const computed = fn(arg, ...args);
        map.set(arg, computed);
        return computed;
    };
}
//# sourceMappingURL=utils.js.map/**
 * Internal Merkle-Damgard hash utils.
 * @module
 */
import { Hash, abytes, aexists, aoutput, clean, createView, toBytes } from "./utils.js";
/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */
export function setBigUint64(view, byteOffset, value, isLE) {
    if (typeof view.setBigUint64 === 'function')
        return view.setBigUint64(byteOffset, value, isLE);
    const _32n = BigInt(32);
    const _u32_max = BigInt(0xffffffff);
    const wh = Number((value >> _32n) & _u32_max);
    const wl = Number(value & _u32_max);
    const h = isLE ? 4 : 0;
    const l = isLE ? 0 : 4;
    view.setUint32(byteOffset + h, wh, isLE);
    view.setUint32(byteOffset + l, wl, isLE);
}
/** Choice: a ? b : c */
export function Chi(a, b, c) {
    return (a & b) ^ (~a & c);
}
/** Majority function, true if any two inputs is true. */
export function Maj(a, b, c) {
    return (a & b) ^ (a & c) ^ (b & c);
}
/**
 * Merkle-Damgard hash construction base class.
 * Could be used to create MD5, RIPEMD, SHA1, SHA2.
 */
export class HashMD extends Hash {
    constructor(blockLen, outputLen, padOffset, isLE) {
        super();
        this.finished = false;
        this.length = 0;
        this.pos = 0;
        this.destroyed = false;
        this.blockLen = blockLen;
        this.outputLen = outputLen;
        this.padOffset = padOffset;
        this.isLE = isLE;
        this.buffer = new Uint8Array(blockLen);
        this.view = createView(this.buffer);
    }
    update(data) {
        aexists(this);
        data = toBytes(data);
        abytes(data);
        const { view, buffer, blockLen } = this;
        const len = data.length;
        for (let pos = 0; pos < len;) {
            const take = Math.min(blockLen - this.pos, len - pos);
            // Fast path: we have at least one block in input, cast it to view and process
            if (take === blockLen) {
                const dataView = createView(data);
                for (; blockLen <= len - pos; pos += blockLen)
                    this.process(dataView, pos);
                continue;
            }
            buffer.set(data.subarray(pos, pos + take), this.pos);
            this.pos += take;
            pos += take;
            if (this.pos === blockLen) {
                this.process(view, 0);
                this.pos = 0;
            }
        }
        this.length += data.length;
        this.roundClean();
        return this;
    }
    digestInto(out) {
        aexists(this);
        aoutput(out, this);
        this.finished = true;
        // Padding
        // We can avoid allocation of buffer for padding completely if it
        // was previously not allocated here. But it won't change performance.
        const { buffer, view, blockLen, isLE } = this;
        let { pos } = this;
        // append the bit '1' to the message
        buffer[pos++] = 0b10000000;
        clean(this.buffer.subarray(pos));
        // we have less than padOffset left in buffer, so we cannot put length in
        // current block, need process it and pad again
        if (this.padOffset > blockLen - pos) {
            this.process(view, 0);
            pos = 0;
        }
        // Pad until full block byte with zeros
        for (let i = pos; i < blockLen; i++)
            buffer[i] = 0;
        // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that
        // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.
        // So we just write lowest 64 bits of that value.
        setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
        this.process(view, 0);
        const oview = createView(out);
        const len = this.outputLen;
        // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT
        if (len % 4)
            throw new Error('_sha2: outputLen should be aligned to 32bit');
        const outLen = len / 4;
        const state = this.get();
        if (outLen > state.length)
            throw new Error('_sha2: outputLen bigger than state');
        for (let i = 0; i < outLen; i++)
            oview.setUint32(4 * i, state[i], isLE);
    }
    digest() {
        const { buffer, outputLen } = this;
        this.digestInto(buffer);
        const res = buffer.slice(0, outputLen);
        this.destroy();
        return res;
    }
    _cloneInto(to) {
        to || (to = new this.constructor());
        to.set(...this.get());
        const { blockLen, buffer, length, finished, destroyed, pos } = this;
        to.destroyed = destroyed;
        to.finished = finished;
        to.length = length;
        to.pos = pos;
        if (length % blockLen)
            to.buffer.set(buffer);
        return to;
    }
    clone() {
        return this._cloneInto();
    }
}
/**
 * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.
 * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.
 */
/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */
export const SHA256_IV = /* @__PURE__ */ Uint32Array.from([
    0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
]);
/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */
export const SHA224_IV = /* @__PURE__ */ Uint32Array.from([
    0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,
]);
/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */
export const SHA384_IV = /* @__PURE__ */ Uint32Array.from([
    0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,
    0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,
]);
/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */
export const SHA512_IV = /* @__PURE__ */ Uint32Array.from([
    0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,
    0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,
]);
//# sourceMappingURL=_md.js.map/**
 * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.
 * @todo re-check https://issues.chromium.org/issues/42212588
 * @module
 */
const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
const _32n = /* @__PURE__ */ BigInt(32);
function fromBig(n, le = false) {
    if (le)
        return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };
    return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
}
function split(lst, le = false) {
    const len = lst.length;
    let Ah = new Uint32Array(len);
    let Al = new Uint32Array(len);
    for (let i = 0; i < len; i++) {
        const { h, l } = fromBig(lst[i], le);
        [Ah[i], Al[i]] = [h, l];
    }
    return [Ah, Al];
}
const toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);
// for Shift in [0, 32)
const shrSH = (h, _l, s) => h >>> s;
const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
// Right rotate for Shift in [1, 32)
const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));
const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
// Right rotate for Shift in (32, 64), NOTE: 32 is special case.
const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));
const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));
// Right rotate for shift===32 (just swaps l&h)
const rotr32H = (_h, l) => l;
const rotr32L = (h, _l) => h;
// Left rotate for Shift in [1, 32)
const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));
const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));
// Left rotate for Shift in (32, 64), NOTE: 32 is special case.
const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));
const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));
// JS uses 32-bit signed integers for bitwise operations which means we cannot
// simple take carry out of low bit sum by shift, we need to use division.
function add(Ah, Al, Bh, Bl) {
    const l = (Al >>> 0) + (Bl >>> 0);
    return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };
}
// Addition with more than 2 elements
const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;
const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;
const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;
// prettier-ignore
export { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig };
// prettier-ignore
const u64 = {
    fromBig, split, toBig,
    shrSH, shrSL,
    rotrSH, rotrSL, rotrBH, rotrBL,
    rotr32H, rotr32L,
    rotlSH, rotlSL, rotlBH, rotlBL,
    add, add3L, add3H, add4L, add4H, add5H, add5L,
};
export default u64;
//# sourceMappingURL=_u64.js.mapexport const crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;
//# sourceMappingURL=crypto.js.map/**
 * HMAC: RFC2104 message authentication code.
 * @module
 */
import { abytes, aexists, ahash, clean, Hash, toBytes } from "./utils.js";
export class HMAC extends Hash {
    constructor(hash, _key) {
        super();
        this.finished = false;
        this.destroyed = false;
        ahash(hash);
        const key = toBytes(_key);
        this.iHash = hash.create();
        if (typeof this.iHash.update !== 'function')
            throw new Error('Expected instance of class which extends utils.Hash');
        this.blockLen = this.iHash.blockLen;
        this.outputLen = this.iHash.outputLen;
        const blockLen = this.blockLen;
        const pad = new Uint8Array(blockLen);
        // blockLen can be bigger than outputLen
        pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
        for (let i = 0; i < pad.length; i++)
            pad[i] ^= 0x36;
        this.iHash.update(pad);
        // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone
        this.oHash = hash.create();
        // Undo internal XOR && apply outer XOR
        for (let i = 0; i < pad.length; i++)
            pad[i] ^= 0x36 ^ 0x5c;
        this.oHash.update(pad);
        clean(pad);
    }
    update(buf) {
        aexists(this);
        this.iHash.update(buf);
        return this;
    }
    digestInto(out) {
        aexists(this);
        abytes(out, this.outputLen);
        this.finished = true;
        this.iHash.digestInto(out);
        this.oHash.update(out);
        this.oHash.digestInto(out);
        this.destroy();
    }
    digest() {
        const out = new Uint8Array(this.oHash.outputLen);
        this.digestInto(out);
        return out;
    }
    _cloneInto(to) {
        // Create new instance without calling constructor since key already in state and we don't know it.
        to || (to = Object.create(Object.getPrototypeOf(this), {}));
        const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
        to = to;
        to.finished = finished;
        to.destroyed = destroyed;
        to.blockLen = blockLen;
        to.outputLen = outputLen;
        to.oHash = oHash._cloneInto(to.oHash);
        to.iHash = iHash._cloneInto(to.iHash);
        return to;
    }
    clone() {
        return this._cloneInto();
    }
    destroy() {
        this.destroyed = true;
        this.oHash.destroy();
        this.iHash.destroy();
    }
}
/**
 * HMAC: RFC2104 message authentication code.
 * @param hash - function that would be used e.g. sha256
 * @param key - message key
 * @param message - message data
 * @example
 * import { hmac } from '@noble/hashes/hmac';
 * import { sha256 } from '@noble/hashes/sha2';
 * const mac1 = hmac(sha256, 'key', 'message');
 */
export const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
hmac.create = (hash, key) => new HMAC(hash, key);
//# sourceMappingURL=hmac.js.map{
  "type": "module",
  "sideEffects": false,
  "browser": {
    "node:crypto": false
  },
  "node": {
    "./crypto": "./esm/cryptoNode.js"
  }
}
/**
 * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.
 * SHA256 is the fastest hash implementable in JS, even faster than Blake3.
 * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and
 * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).
 * @module
 */
import { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from "./_md.js";
import * as u64 from "./_u64.js";
import { clean, createHasher, rotr } from "./utils.js";
/**
 * Round constants:
 * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)
 */
// prettier-ignore
const SHA256_K = /* @__PURE__ */ Uint32Array.from([
    0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
    0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
    0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
    0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
    0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
    0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
    0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
    0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
]);
/** Reusable temporary buffer. "W" comes straight from spec. */
const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
export class SHA256 extends HashMD {
    constructor(outputLen = 32) {
        super(64, outputLen, 8, false);
        // We cannot use array here since array allows indexing by variable
        // which means optimizer/compiler cannot use registers.
        this.A = SHA256_IV[0] | 0;
        this.B = SHA256_IV[1] | 0;
        this.C = SHA256_IV[2] | 0;
        this.D = SHA256_IV[3] | 0;
        this.E = SHA256_IV[4] | 0;
        this.F = SHA256_IV[5] | 0;
        this.G = SHA256_IV[6] | 0;
        this.H = SHA256_IV[7] | 0;
    }
    get() {
        const { A, B, C, D, E, F, G, H } = this;
        return [A, B, C, D, E, F, G, H];
    }
    // prettier-ignore
    set(A, B, C, D, E, F, G, H) {
        this.A = A | 0;
        this.B = B | 0;
        this.C = C | 0;
        this.D = D | 0;
        this.E = E | 0;
        this.F = F | 0;
        this.G = G | 0;
        this.H = H | 0;
    }
    process(view, offset) {
        // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array
        for (let i = 0; i < 16; i++, offset += 4)
            SHA256_W[i] = view.getUint32(offset, false);
        for (let i = 16; i < 64; i++) {
            const W15 = SHA256_W[i - 15];
            const W2 = SHA256_W[i - 2];
            const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);
            const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);
            SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;
        }
        // Compression function main loop, 64 rounds
        let { A, B, C, D, E, F, G, H } = this;
        for (let i = 0; i < 64; i++) {
            const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
            const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
            const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
            const T2 = (sigma0 + Maj(A, B, C)) | 0;
            H = G;
            G = F;
            F = E;
            E = (D + T1) | 0;
            D = C;
            C = B;
            B = A;
            A = (T1 + T2) | 0;
        }
        // Add the compressed chunk to the current hash value
        A = (A + this.A) | 0;
        B = (B + this.B) | 0;
        C = (C + this.C) | 0;
        D = (D + this.D) | 0;
        E = (E + this.E) | 0;
        F = (F + this.F) | 0;
        G = (G + this.G) | 0;
        H = (H + this.H) | 0;
        this.set(A, B, C, D, E, F, G, H);
    }
    roundClean() {
        clean(SHA256_W);
    }
    destroy() {
        this.set(0, 0, 0, 0, 0, 0, 0, 0);
        clean(this.buffer);
    }
}
export class SHA224 extends SHA256 {
    constructor() {
        super(28);
        this.A = SHA224_IV[0] | 0;
        this.B = SHA224_IV[1] | 0;
        this.C = SHA224_IV[2] | 0;
        this.D = SHA224_IV[3] | 0;
        this.E = SHA224_IV[4] | 0;
        this.F = SHA224_IV[5] | 0;
        this.G = SHA224_IV[6] | 0;
        this.H = SHA224_IV[7] | 0;
    }
}
// SHA2-512 is slower than sha256 in js because u64 operations are slow.
// Round contants
// First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409
// prettier-ignore
const K512 = /* @__PURE__ */ (() => u64.split([
    '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',
    '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',
    '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',
    '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',
    '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',
    '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',
    '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',
    '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',
    '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',
    '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',
    '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',
    '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',
    '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',
    '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',
    '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',
    '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',
    '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',
    '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',
    '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',
    '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'
].map(n => BigInt(n))))();
const SHA512_Kh = /* @__PURE__ */ (() => K512[0])();
const SHA512_Kl = /* @__PURE__ */ (() => K512[1])();
// Reusable temporary buffers
const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
export class SHA512 extends HashMD {
    constructor(outputLen = 64) {
        super(128, outputLen, 16, false);
        // We cannot use array here since array allows indexing by variable
        // which means optimizer/compiler cannot use registers.
        // h -- high 32 bits, l -- low 32 bits
        this.Ah = SHA512_IV[0] | 0;
        this.Al = SHA512_IV[1] | 0;
        this.Bh = SHA512_IV[2] | 0;
        this.Bl = SHA512_IV[3] | 0;
        this.Ch = SHA512_IV[4] | 0;
        this.Cl = SHA512_IV[5] | 0;
        this.Dh = SHA512_IV[6] | 0;
        this.Dl = SHA512_IV[7] | 0;
        this.Eh = SHA512_IV[8] | 0;
        this.El = SHA512_IV[9] | 0;
        this.Fh = SHA512_IV[10] | 0;
        this.Fl = SHA512_IV[11] | 0;
        this.Gh = SHA512_IV[12] | 0;
        this.Gl = SHA512_IV[13] | 0;
        this.Hh = SHA512_IV[14] | 0;
        this.Hl = SHA512_IV[15] | 0;
    }
    // prettier-ignore
    get() {
        const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
        return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
    }
    // prettier-ignore
    set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
        this.Ah = Ah | 0;
        this.Al = Al | 0;
        this.Bh = Bh | 0;
        this.Bl = Bl | 0;
        this.Ch = Ch | 0;
        this.Cl = Cl | 0;
        this.Dh = Dh | 0;
        this.Dl = Dl | 0;
        this.Eh = Eh | 0;
        this.El = El | 0;
        this.Fh = Fh | 0;
        this.Fl = Fl | 0;
        this.Gh = Gh | 0;
        this.Gl = Gl | 0;
        this.Hh = Hh | 0;
        this.Hl = Hl | 0;
    }
    process(view, offset) {
        // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array
        for (let i = 0; i < 16; i++, offset += 4) {
            SHA512_W_H[i] = view.getUint32(offset);
            SHA512_W_L[i] = view.getUint32((offset += 4));
        }
        for (let i = 16; i < 80; i++) {
            // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)
            const W15h = SHA512_W_H[i - 15] | 0;
            const W15l = SHA512_W_L[i - 15] | 0;
            const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);
            const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);
            // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)
            const W2h = SHA512_W_H[i - 2] | 0;
            const W2l = SHA512_W_L[i - 2] | 0;
            const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);
            const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);
            // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];
            const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
            const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
            SHA512_W_H[i] = SUMh | 0;
            SHA512_W_L[i] = SUMl | 0;
        }
        let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
        // Compression function main loop, 80 rounds
        for (let i = 0; i < 80; i++) {
            // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)
            const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);
            const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);
            //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
            const CHIh = (Eh & Fh) ^ (~Eh & Gh);
            const CHIl = (El & Fl) ^ (~El & Gl);
            // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]
            // prettier-ignore
            const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
            const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
            const T1l = T1ll | 0;
            // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)
            const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);
            const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);
            const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);
            const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);
            Hh = Gh | 0;
            Hl = Gl | 0;
            Gh = Fh | 0;
            Gl = Fl | 0;
            Fh = Eh | 0;
            Fl = El | 0;
            ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
            Dh = Ch | 0;
            Dl = Cl | 0;
            Ch = Bh | 0;
            Cl = Bl | 0;
            Bh = Ah | 0;
            Bl = Al | 0;
            const All = u64.add3L(T1l, sigma0l, MAJl);
            Ah = u64.add3H(All, T1h, sigma0h, MAJh);
            Al = All | 0;
        }
        // Add the compressed chunk to the current hash value
        ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
        ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
        ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
        ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
        ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
        ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
        ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
        ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
        this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
    }
    roundClean() {
        clean(SHA512_W_H, SHA512_W_L);
    }
    destroy() {
        clean(this.buffer);
        this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
    }
}
export class SHA384 extends SHA512 {
    constructor() {
        super(48);
        this.Ah = SHA384_IV[0] | 0;
        this.Al = SHA384_IV[1] | 0;
        this.Bh = SHA384_IV[2] | 0;
        this.Bl = SHA384_IV[3] | 0;
        this.Ch = SHA384_IV[4] | 0;
        this.Cl = SHA384_IV[5] | 0;
        this.Dh = SHA384_IV[6] | 0;
        this.Dl = SHA384_IV[7] | 0;
        this.Eh = SHA384_IV[8] | 0;
        this.El = SHA384_IV[9] | 0;
        this.Fh = SHA384_IV[10] | 0;
        this.Fl = SHA384_IV[11] | 0;
        this.Gh = SHA384_IV[12] | 0;
        this.Gl = SHA384_IV[13] | 0;
        this.Hh = SHA384_IV[14] | 0;
        this.Hl = SHA384_IV[15] | 0;
    }
}
/**
 * Truncated SHA512/256 and SHA512/224.
 * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as "intermediary" IV of SHA512/t.
 * Then t hashes string to produce result IV.
 * See `test/misc/sha2-gen-iv.js`.
 */
/** SHA512/224 IV */
const T224_IV = /* @__PURE__ */ Uint32Array.from([
    0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,
    0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,
]);
/** SHA512/256 IV */
const T256_IV = /* @__PURE__ */ Uint32Array.from([
    0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,
    0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,
]);
export class SHA512_224 extends SHA512 {
    constructor() {
        super(28);
        this.Ah = T224_IV[0] | 0;
        this.Al = T224_IV[1] | 0;
        this.Bh = T224_IV[2] | 0;
        this.Bl = T224_IV[3] | 0;
        this.Ch = T224_IV[4] | 0;
        this.Cl = T224_IV[5] | 0;
        this.Dh = T224_IV[6] | 0;
        this.Dl = T224_IV[7] | 0;
        this.Eh = T224_IV[8] | 0;
        this.El = T224_IV[9] | 0;
        this.Fh = T224_IV[10] | 0;
        this.Fl = T224_IV[11] | 0;
        this.Gh = T224_IV[12] | 0;
        this.Gl = T224_IV[13] | 0;
        this.Hh = T224_IV[14] | 0;
        this.Hl = T224_IV[15] | 0;
    }
}
export class SHA512_256 extends SHA512 {
    constructor() {
        super(32);
        this.Ah = T256_IV[0] | 0;
        this.Al = T256_IV[1] | 0;
        this.Bh = T256_IV[2] | 0;
        this.Bl = T256_IV[3] | 0;
        this.Ch = T256_IV[4] | 0;
        this.Cl = T256_IV[5] | 0;
        this.Dh = T256_IV[6] | 0;
        this.Dl = T256_IV[7] | 0;
        this.Eh = T256_IV[8] | 0;
        this.El = T256_IV[9] | 0;
        this.Fh = T256_IV[10] | 0;
        this.Fl = T256_IV[11] | 0;
        this.Gh = T256_IV[12] | 0;
        this.Gl = T256_IV[13] | 0;
        this.Hh = T256_IV[14] | 0;
        this.Hl = T256_IV[15] | 0;
    }
}
/**
 * SHA2-256 hash function from RFC 4634.
 *
 * It is the fastest JS hash, even faster than Blake3.
 * To break sha256 using birthday attack, attackers need to try 2^128 hashes.
 * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
 */
export const sha256 = /* @__PURE__ */ createHasher(() => new SHA256());
/** SHA2-224 hash function from RFC 4634 */
export const sha224 = /* @__PURE__ */ createHasher(() => new SHA224());
/** SHA2-512 hash function from RFC 4634. */
export const sha512 = /* @__PURE__ */ createHasher(() => new SHA512());
/** SHA2-384 hash function from RFC 4634. */
export const sha384 = /* @__PURE__ */ createHasher(() => new SHA384());
/**
 * SHA2-512/256 "truncated" hash function, with improved resistance to length extension attacks.
 * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).
 */
export const sha512_256 = /* @__PURE__ */ createHasher(() => new SHA512_256());
/**
 * SHA2-512/224 "truncated" hash function, with improved resistance to length extension attacks.
 * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).
 */
export const sha512_224 = /* @__PURE__ */ createHasher(() => new SHA512_224());
//# sourceMappingURL=sha2.js.map/**
 * Utilities for hex, bytes, CSPRNG.
 * @module
 */
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
// node.js versions earlier than v19 don't declare it in global scope.
// For node.js, package.json#exports field mapping rewrites import
// from `crypto` to `cryptoNode`, which imports native module.
// Makes the utils un-importable in browsers without a bundler.
// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.
import { crypto } from '@noble/hashes/crypto';
/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */
export function isBytes(a) {
    return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
}
/** Asserts something is positive integer. */
export function anumber(n) {
    if (!Number.isSafeInteger(n) || n < 0)
        throw new Error('positive integer expected, got ' + n);
}
/** Asserts something is Uint8Array. */
export function abytes(b, ...lengths) {
    if (!isBytes(b))
        throw new Error('Uint8Array expected');
    if (lengths.length > 0 && !lengths.includes(b.length))
        throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);
}
/** Asserts something is hash */
export function ahash(h) {
    if (typeof h !== 'function' || typeof h.create !== 'function')
        throw new Error('Hash should be wrapped by utils.createHasher');
    anumber(h.outputLen);
    anumber(h.blockLen);
}
/** Asserts a hash instance has not been destroyed / finished */
export function aexists(instance, checkFinished = true) {
    if (instance.destroyed)
        throw new Error('Hash instance has been destroyed');
    if (checkFinished && instance.finished)
        throw new Error('Hash#digest() has already been called');
}
/** Asserts output is properly-sized byte array */
export function aoutput(out, instance) {
    abytes(out);
    const min = instance.outputLen;
    if (out.length < min) {
        throw new Error('digestInto() expects output buffer of length at least ' + min);
    }
}
/** Cast u8 / u16 / u32 to u8. */
export function u8(arr) {
    return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
}
/** Cast u8 / u16 / u32 to u32. */
export function u32(arr) {
    return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
}
/** Zeroize a byte array. Warning: JS provides no guarantees. */
export function clean(...arrays) {
    for (let i = 0; i < arrays.length; i++) {
        arrays[i].fill(0);
    }
}
/** Create DataView of an array for easy byte-level manipulation. */
export function createView(arr) {
    return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
}
/** The rotate right (circular right shift) operation for uint32 */
export function rotr(word, shift) {
    return (word << (32 - shift)) | (word >>> shift);
}
/** The rotate left (circular left shift) operation for uint32 */
export function rotl(word, shift) {
    return (word << shift) | ((word >>> (32 - shift)) >>> 0);
}
/** Is current platform little-endian? Most are. Big-Endian platform: IBM */
export const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();
/** The byte swap operation for uint32 */
export function byteSwap(word) {
    return (((word << 24) & 0xff000000) |
        ((word << 8) & 0xff0000) |
        ((word >>> 8) & 0xff00) |
        ((word >>> 24) & 0xff));
}
/** Conditionally byte swap if on a big-endian platform */
export const swap8IfBE = isLE
    ? (n) => n
    : (n) => byteSwap(n);
/** @deprecated */
export const byteSwapIfBE = swap8IfBE;
/** In place byte swap for Uint32Array */
export function byteSwap32(arr) {
    for (let i = 0; i < arr.length; i++) {
        arr[i] = byteSwap(arr[i]);
    }
    return arr;
}
export const swap32IfBE = isLE
    ? (u) => u
    : byteSwap32;
// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex
const hasHexBuiltin = /* @__PURE__ */ (() => 
// @ts-ignore
typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();
// Array where index 0xf0 (240) is mapped to string 'f0'
const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
/**
 * Convert byte array to hex string. Uses built-in function, when available.
 * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
 */
export function bytesToHex(bytes) {
    abytes(bytes);
    // @ts-ignore
    if (hasHexBuiltin)
        return bytes.toHex();
    // pre-caching improves the speed 6x
    let hex = '';
    for (let i = 0; i < bytes.length; i++) {
        hex += hexes[bytes[i]];
    }
    return hex;
}
// We use optimized technique to convert hex string to byte array
const asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
function asciiToBase16(ch) {
    if (ch >= asciis._0 && ch <= asciis._9)
        return ch - asciis._0; // '2' => 50-48
    if (ch >= asciis.A && ch <= asciis.F)
        return ch - (asciis.A - 10); // 'B' => 66-(65-10)
    if (ch >= asciis.a && ch <= asciis.f)
        return ch - (asciis.a - 10); // 'b' => 98-(97-10)
    return;
}
/**
 * Convert hex string to byte array. Uses built-in function, when available.
 * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
 */
export function hexToBytes(hex) {
    if (typeof hex !== 'string')
        throw new Error('hex string expected, got ' + typeof hex);
    // @ts-ignore
    if (hasHexBuiltin)
        return Uint8Array.fromHex(hex);
    const hl = hex.length;
    const al = hl / 2;
    if (hl % 2)
        throw new Error('hex string expected, got unpadded hex of length ' + hl);
    const array = new Uint8Array(al);
    for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
        const n1 = asciiToBase16(hex.charCodeAt(hi));
        const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
        if (n1 === undefined || n2 === undefined) {
            const char = hex[hi] + hex[hi + 1];
            throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
        }
        array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163
    }
    return array;
}
/**
 * There is no setImmediate in browser and setTimeout is slow.
 * Call of async fn will return Promise, which will be fullfiled only on
 * next scheduler queue processing step and this is exactly what we need.
 */
export const nextTick = async () => { };
/** Returns control to thread each 'tick' ms to avoid blocking. */
export async function asyncLoop(iters, tick, cb) {
    let ts = Date.now();
    for (let i = 0; i < iters; i++) {
        cb(i);
        // Date.now() is not monotonic, so in case if clock goes backwards we return return control too
        const diff = Date.now() - ts;
        if (diff >= 0 && diff < tick)
            continue;
        await nextTick();
        ts += diff;
    }
}
/**
 * Converts string to bytes using UTF8 encoding.
 * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])
 */
export function utf8ToBytes(str) {
    if (typeof str !== 'string')
        throw new Error('string expected');
    return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
}
/**
 * Converts bytes to string using UTF8 encoding.
 * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'
 */
export function bytesToUtf8(bytes) {
    return new TextDecoder().decode(bytes);
}
/**
 * Normalizes (non-hex) string or Uint8Array to Uint8Array.
 * Warning: when Uint8Array is passed, it would NOT get copied.
 * Keep in mind for future mutable operations.
 */
export function toBytes(data) {
    if (typeof data === 'string')
        data = utf8ToBytes(data);
    abytes(data);
    return data;
}
/**
 * Helper for KDFs: consumes uint8array or string.
 * When string is passed, does utf8 decoding, using TextDecoder.
 */
export function kdfInputToBytes(data) {
    if (typeof data === 'string')
        data = utf8ToBytes(data);
    abytes(data);
    return data;
}
/** Copies several Uint8Arrays into one. */
export function concatBytes(...arrays) {
    let sum = 0;
    for (let i = 0; i < arrays.length; i++) {
        const a = arrays[i];
        abytes(a);
        sum += a.length;
    }
    const res = new Uint8Array(sum);
    for (let i = 0, pad = 0; i < arrays.length; i++) {
        const a = arrays[i];
        res.set(a, pad);
        pad += a.length;
    }
    return res;
}
export function checkOpts(defaults, opts) {
    if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')
        throw new Error('options should be object or undefined');
    const merged = Object.assign(defaults, opts);
    return merged;
}
/** For runtime check if class implements interface */
export class Hash {
}
/** Wraps hash function, creating an interface on top of it */
export function createHasher(hashCons) {
    const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
    const tmp = hashCons();
    hashC.outputLen = tmp.outputLen;
    hashC.blockLen = tmp.blockLen;
    hashC.create = () => hashCons();
    return hashC;
}
export function createOptHasher(hashCons) {
    const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();
    const tmp = hashCons({});
    hashC.outputLen = tmp.outputLen;
    hashC.blockLen = tmp.blockLen;
    hashC.create = (opts) => hashCons(opts);
    return hashC;
}
export function createXOFer(hashCons) {
    const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();
    const tmp = hashCons({});
    hashC.outputLen = tmp.outputLen;
    hashC.blockLen = tmp.blockLen;
    hashC.create = (opts) => hashCons(opts);
    return hashC;
}
export const wrapConstructor = createHasher;
export const wrapConstructorWithOpts = createOptHasher;
export const wrapXOFConstructorWithOpts = createXOFer;
/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */
export function randomBytes(bytesLength = 32) {
    if (crypto && typeof crypto.getRandomValues === 'function') {
        return crypto.getRandomValues(new Uint8Array(bytesLength));
    }
    // Legacy Node.js compatibility
    if (crypto && typeof crypto.randomBytes === 'function') {
        return Uint8Array.from(crypto.randomBytes(bytesLength));
    }
    throw new Error('crypto.getRandomValues must be defined');
}
//# sourceMappingURL=utils.js.mapimport { encode, encodeInto, objectToTokens, rfc8949EncodeOptions } from './lib/encode.js'
import { decode, decodeFirst, Tokeniser, tokensToObject } from './lib/decode.js'
import { Tagged } from './lib/tagged.js'
import { Token, Type } from './lib/token.js'

/**
 * Export the types that were present in the original manual cborg.d.ts
 * @typedef {import('./interface.js').TagDecodeControl} TagDecodeControl
 * @typedef {import('./interface.js').TagDecoder} TagDecoder
 * There was originally just `TypeEncoder` so don't break types by renaming or not exporting
 * @typedef {import('./interface.js').OptionalTypeEncoder} TypeEncoder
 * @typedef {import('./interface.js').DecodeOptions} DecodeOptions
 * @typedef {import('./interface.js').EncodeOptions} EncodeOptions
 */

export {
  decode,
  decodeFirst,
  Tokeniser as Tokenizer,
  tokensToObject,
  encode,
  encodeInto,
  objectToTokens,
  rfc8949EncodeOptions,
  Tagged,
  Token,
  Type
}
/* globals BigInt */

import { Token, Type } from './token.js'
import { decodeErrPrefix, assertEnoughData } from './common.js'

export const uintBoundaries = [24, 256, 65536, 4294967296, BigInt('18446744073709551616')]

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number}
 */
export function readUint8 (data, offset, options) {
  assertEnoughData(data, offset, 1)
  const value = data[offset]
  if (options.strict === true && value < uintBoundaries[0]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  return value
}

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number}
 */
export function readUint16 (data, offset, options) {
  assertEnoughData(data, offset, 2)
  const value = (data[offset] << 8) | data[offset + 1]
  if (options.strict === true && value < uintBoundaries[1]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  return value
}

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number}
 */
export function readUint32 (data, offset, options) {
  assertEnoughData(data, offset, 4)
  const value = (data[offset] * 16777216 /* 2 ** 24 */) + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]
  if (options.strict === true && value < uintBoundaries[2]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  return value
}

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number|bigint}
 */
export function readUint64 (data, offset, options) {
  // assume BigInt, convert back to Number if within safe range
  assertEnoughData(data, offset, 8)
  const hi = (data[offset] * 16777216 /* 2 ** 24 */) + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]
  const lo = (data[offset + 4] * 16777216 /* 2 ** 24 */) + (data[offset + 5] << 16) + (data[offset + 6] << 8) + data[offset + 7]
  const value = (BigInt(hi) << BigInt(32)) + BigInt(lo)
  if (options.strict === true && value < uintBoundaries[3]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  if (value <= Number.MAX_SAFE_INTEGER) {
    return Number(value)
  }
  if (options.allowBigInt === true) {
    return value
  }
  throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`)
}

/* not required thanks to quick[] list
const oneByteTokens = new Array(24).fill(0).map((v, i) => new Token(Type.uint, i, 1))
export function decodeUintCompact (data, pos, minor, options) {
  return oneByteTokens[minor]
}
*/

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint8 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint8(data, pos + 1, options), 2)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint16 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint16(data, pos + 1, options), 3)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint32 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint32(data, pos + 1, options), 5)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint64 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint64(data, pos + 1, options), 9)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeUint (writer, token) {
  return encodeUintValue(writer, 0, token.value)
}

/**
 * @param {ByteWriter} writer
 * @param {number} major
 * @param {number|bigint} uint
 */
export function encodeUintValue (writer, major, uint) {
  if (uint < uintBoundaries[0]) {
    const nuint = Number(uint)
    // pack into one byte, minor=0, additional=value
    writer.push([major | nuint])
  } else if (uint < uintBoundaries[1]) {
    const nuint = Number(uint)
    // pack into two byte, minor=0, additional=24
    writer.push([major | 24, nuint])
  } else if (uint < uintBoundaries[2]) {
    const nuint = Number(uint)
    // pack into three byte, minor=0, additional=25
    writer.push([major | 25, nuint >>> 8, nuint & 0xff])
  } else if (uint < uintBoundaries[3]) {
    const nuint = Number(uint)
    // pack into five byte, minor=0, additional=26
    writer.push([major | 26, (nuint >>> 24) & 0xff, (nuint >>> 16) & 0xff, (nuint >>> 8) & 0xff, nuint & 0xff])
  } else {
    const buint = BigInt(uint)
    if (buint < uintBoundaries[4]) {
      // pack into nine byte, minor=0, additional=27
      const set = [major | 27, 0, 0, 0, 0, 0, 0, 0]
      // simulate bitwise above 32 bits
      let lo = Number(buint & BigInt(0xffffffff))
      let hi = Number(buint >> BigInt(32) & BigInt(0xffffffff))
      set[8] = lo & 0xff
      lo = lo >> 8
      set[7] = lo & 0xff
      lo = lo >> 8
      set[6] = lo & 0xff
      lo = lo >> 8
      set[5] = lo & 0xff
      set[4] = hi & 0xff
      hi = hi >> 8
      set[3] = hi & 0xff
      hi = hi >> 8
      set[2] = hi & 0xff
      hi = hi >> 8
      set[1] = hi & 0xff
      writer.push(set)
    } else {
      throw new Error(`${decodeErrPrefix} encountered BigInt larger than allowable range`)
    }
  }
}

/**
 * @param {Token} token
 * @returns {number}
 */
encodeUint.encodedSize = function encodedSize (token) {
  return encodeUintValue.encodedSize(token.value)
}

/**
 * @param {number} uint
 * @returns {number}
 */
encodeUintValue.encodedSize = function encodedSize (uint) {
  if (uint < uintBoundaries[0]) {
    return 1
  }
  if (uint < uintBoundaries[1]) {
    return 2
  }
  if (uint < uintBoundaries[2]) {
    return 3
  }
  if (uint < uintBoundaries[3]) {
    return 5
  }
  return 9
}

/**
 * @param {Token} tok1
 * @param {Token} tok2
 * @returns {number}
 */
encodeUint.compareTokens = function compareTokens (tok1, tok2) {
  return tok1.value < tok2.value ? -1 : tok1.value > tok2.value ? 1 : 0
}
/* eslint-env es2020 */

import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import { decodeErrPrefix } from './common.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint8 (data, pos, _minor, options) {
  return new Token(Type.negint, -1 - uint.readUint8(data, pos + 1, options), 2)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint16 (data, pos, _minor, options) {
  return new Token(Type.negint, -1 - uint.readUint16(data, pos + 1, options), 3)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint32 (data, pos, _minor, options) {
  return new Token(Type.negint, -1 - uint.readUint32(data, pos + 1, options), 5)
}

const neg1b = BigInt(-1)
const pos1b = BigInt(1)

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint64 (data, pos, _minor, options) {
  const int = uint.readUint64(data, pos + 1, options)
  if (typeof int !== 'bigint') {
    const value = -1 - int
    if (value >= Number.MIN_SAFE_INTEGER) {
      return new Token(Type.negint, value, 9)
    }
  }
  if (options.allowBigInt !== true) {
    throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`)
  }
  return new Token(Type.negint, neg1b - BigInt(int), 9)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeNegint (writer, token) {
  const negint = token.value
  const unsigned = (typeof negint === 'bigint' ? (negint * neg1b - pos1b) : (negint * -1 - 1))
  uint.encodeUintValue(writer, token.type.majorEncoded, unsigned)
}

/**
 * @param {Token} token
 * @returns {number}
 */
encodeNegint.encodedSize = function encodedSize (token) {
  const negint = token.value
  const unsigned = (typeof negint === 'bigint' ? (negint * neg1b - pos1b) : (negint * -1 - 1))
  // handled by quickEncode, we shouldn't get here but it's included for completeness
  if (unsigned < uint.uintBoundaries[0]) {
    return 1
  }
  if (unsigned < uint.uintBoundaries[1]) {
    return 2
  }
  if (unsigned < uint.uintBoundaries[2]) {
    return 3
  }
  if (unsigned < uint.uintBoundaries[3]) {
    return 5
  }
  return 9
}

/**
 * @param {Token} tok1
 * @param {Token} tok2
 * @returns {number}
 */
encodeNegint.compareTokens = function compareTokens (tok1, tok2) {
  // opposite of the uint comparison since we store the uint version in bytes
  return tok1.value < tok2.value ? 1 : tok1.value > tok2.value ? -1 : 0
}
import { Token, Type } from './token.js'
import { assertEnoughData, decodeErrPrefix } from './common.js'
import * as uint from './0uint.js'
import { compare, fromString } from './byte-utils.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} prefix
 * @param {number} length
 * @returns {Token}
 */
function toToken (data, pos, prefix, length) {
  assertEnoughData(data, pos, prefix + length)
  const buf = data.slice(pos + prefix, pos + prefix + length)
  return new Token(Type.bytes, buf, prefix + length)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeBytesCompact (data, pos, minor, _options) {
  return toToken(data, pos, 1, minor)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer bytes lengths not supported`)
  }
  return toToken(data, pos, 9, l)
}

/**
 * `encodedBytes` allows for caching when we do a byte version of a string
 * for key sorting purposes
 * @param {Token} token
 * @returns {Uint8Array}
 */
function tokenBytes (token) {
  if (token.encodedBytes === undefined) {
    token.encodedBytes = Type.equals(token.type, Type.string) ? fromString(token.value) : token.value
  }
  // @ts-ignore c'mon
  return token.encodedBytes
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeBytes (writer, token) {
  const bytes = tokenBytes(token)
  uint.encodeUintValue(writer, token.type.majorEncoded, bytes.length)
  writer.push(bytes)
}

/**
 * @param {Token} token
 * @returns {number}
 */
encodeBytes.encodedSize = function encodedSize (token) {
  const bytes = tokenBytes(token)
  return uint.encodeUintValue.encodedSize(bytes.length) + bytes.length
}

/**
 * @param {Token} tok1
 * @param {Token} tok2
 * @returns {number}
 */
encodeBytes.compareTokens = function compareTokens (tok1, tok2) {
  return compareBytes(tokenBytes(tok1), tokenBytes(tok2))
}

/**
 * @param {Uint8Array} b1
 * @param {Uint8Array} b2
 * @returns {number}
 */
export function compareBytes (b1, b2) {
  return b1.length < b2.length ? -1 : b1.length > b2.length ? 1 : compare(b1, b2)
}
import { Token, Type } from './token.js'
import { assertEnoughData, decodeErrPrefix } from './common.js'
import * as uint from './0uint.js'
import { encodeBytes } from './2bytes.js'

const textDecoder = new TextDecoder()

// Threshold for ASCII fast-path vs TextDecoder. Short ASCII strings (common for
// map keys) are faster to decode with a simple loop than TextDecoder overhead.
const ASCII_THRESHOLD = 32

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * Decode UTF-8 bytes to string. For short ASCII strings (common case for map keys),
 * a simple loop is faster than TextDecoder.
 * @param {Uint8Array} bytes
 * @param {number} start
 * @param {number} end
 * @returns {string}
 */
function toStr (bytes, start, end) {
  const len = end - start
  if (len < ASCII_THRESHOLD) {
    let str = ''
    for (let i = start; i < end; i++) {
      const c = bytes[i]
      if (c & 0x80) { // non-ASCII, fall back to TextDecoder
        return textDecoder.decode(bytes.subarray(start, end))
      }
      str += String.fromCharCode(c)
    }
    return str
  }
  return textDecoder.decode(bytes.subarray(start, end))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} prefix
 * @param {number} length
 * @param {DecodeOptions} options
 * @returns {Token}
 */
function toToken (data, pos, prefix, length, options) {
  const totLength = prefix + length
  assertEnoughData(data, pos, totLength)
  const tok = new Token(Type.string, toStr(data, pos + prefix, pos + totLength), totLength)
  if (options.retainStringBytes === true) {
    tok.byteValue = data.slice(pos + prefix, pos + totLength)
  }
  return tok
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeStringCompact (data, pos, minor, options) {
  return toToken(data, pos, 1, minor, options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options), options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options), options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options), options)
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer string lengths not supported`)
  }
  return toToken(data, pos, 9, l, options)
}

export const encodeString = encodeBytes
import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import { decodeErrPrefix } from './common.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} prefix
 * @param {number} length
 * @returns {Token}
 */
function toToken (_data, _pos, prefix, length) {
  return new Token(Type.array, length, prefix)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeArrayCompact (data, pos, minor, _options) {
  return toToken(data, pos, 1, minor)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer array lengths not supported`)
  }
  return toToken(data, pos, 9, l)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArrayIndefinite (data, pos, _minor, options) {
  if (options.allowIndefinite === false) {
    throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)
  }
  return toToken(data, pos, 1, Infinity)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeArray (writer, token) {
  uint.encodeUintValue(writer, Type.array.majorEncoded, token.value)
}

// using an array as a map key, are you sure about this? we can only sort
// by map length here, it's up to the encoder to decide to look deeper
encodeArray.compareTokens = uint.encodeUint.compareTokens

/**
 * @param {Token} token
 * @returns {number}
 */
encodeArray.encodedSize = function encodedSize (token) {
  return uint.encodeUintValue.encodedSize(token.value)
}
import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import { decodeErrPrefix } from './common.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} prefix
 * @param {number} length
 * @returns {Token}
 */
function toToken (_data, _pos, prefix, length) {
  return new Token(Type.map, length, prefix)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeMapCompact (data, pos, minor, _options) {
  return toToken(data, pos, 1, minor)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer map lengths not supported`)
  }
  return toToken(data, pos, 9, l)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMapIndefinite (data, pos, _minor, options) {
  if (options.allowIndefinite === false) {
    throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)
  }
  return toToken(data, pos, 1, Infinity)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeMap (writer, token) {
  uint.encodeUintValue(writer, Type.map.majorEncoded, token.value)
}

// using a map as a map key, are you sure about this? we can only sort
// by map length here, it's up to the encoder to decide to look deeper
encodeMap.compareTokens = uint.encodeUint.compareTokens

/**
 * @param {Token} token
 * @returns {number}
 */
encodeMap.encodedSize = function encodedSize (token) {
  return uint.encodeUintValue.encodedSize(token.value)
}
import { Token, Type } from './token.js'
import * as uint from './0uint.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeTagCompact (_data, _pos, minor, _options) {
  return new Token(Type.tag, minor, 1)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag8 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint8(data, pos + 1, options), 2)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag16 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint16(data, pos + 1, options), 3)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag32 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint32(data, pos + 1, options), 5)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag64 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint64(data, pos + 1, options), 9)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeTag (writer, token) {
  uint.encodeUintValue(writer, Type.tag.majorEncoded, token.value)
}

encodeTag.compareTokens = uint.encodeUint.compareTokens

/**
 * @param {Token} token
 * @returns {number}
 */
encodeTag.encodedSize = function encodedSize (token) {
  return uint.encodeUintValue.encodedSize(token.value)
}
// TODO: shift some of the bytes logic to bytes-utils so we can use Buffer
// where possible

import { Token, Type } from './token.js'
import { decodeErrPrefix } from './common.js'
import { encodeUint } from './0uint.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 * @typedef {import('../interface.js').EncodeOptions} EncodeOptions
 */

export const MINOR_FALSE = 20
export const MINOR_TRUE = 21
export const MINOR_NULL = 22
export const MINOR_UNDEFINED = 23

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUndefined (_data, _pos, _minor, options) {
  if (options.allowUndefined === false) {
    throw new Error(`${decodeErrPrefix} undefined values are not supported`)
  } else if (options.coerceUndefinedToNull === true) {
    return new Token(Type.null, null, 1)
  }
  return new Token(Type.undefined, undefined, 1)
}

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBreak (_data, _pos, _minor, options) {
  if (options.allowIndefinite === false) {
    throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)
  }
  return new Token(Type.break, undefined, 1)
}

/**
 * @param {number} value
 * @param {number} bytes
 * @param {DecodeOptions} options
 * @returns {Token}
 */
function createToken (value, bytes, options) {
  if (options) {
    if (options.allowNaN === false && Number.isNaN(value)) {
      throw new Error(`${decodeErrPrefix} NaN values are not supported`)
    }
    if (options.allowInfinity === false && (value === Infinity || value === -Infinity)) {
      throw new Error(`${decodeErrPrefix} Infinity values are not supported`)
    }
  }
  return new Token(Type.float, value, bytes)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeFloat16 (data, pos, _minor, options) {
  return createToken(readFloat16(data, pos + 1), 3, options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeFloat32 (data, pos, _minor, options) {
  return createToken(readFloat32(data, pos + 1), 5, options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeFloat64 (data, pos, _minor, options) {
  return createToken(readFloat64(data, pos + 1), 9, options)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 * @param {EncodeOptions} options
 */
export function encodeFloat (writer, token, options) {
  const float = token.value

  if (float === false) {
    writer.push([Type.float.majorEncoded | MINOR_FALSE])
  } else if (float === true) {
    writer.push([Type.float.majorEncoded | MINOR_TRUE])
  } else if (float === null) {
    writer.push([Type.float.majorEncoded | MINOR_NULL])
  } else if (float === undefined) {
    writer.push([Type.float.majorEncoded | MINOR_UNDEFINED])
  } else {
    let decoded
    let success = false
    if (!options || options.float64 !== true) {
      encodeFloat16(float)
      decoded = readFloat16(ui8a, 1)
      if (float === decoded || Number.isNaN(float)) {
        ui8a[0] = 0xf9
        writer.push(ui8a.slice(0, 3))
        success = true
      } else {
        encodeFloat32(float)
        decoded = readFloat32(ui8a, 1)
        if (float === decoded) {
          ui8a[0] = 0xfa
          writer.push(ui8a.slice(0, 5))
          success = true
        }
      }
    }
    if (!success) {
      encodeFloat64(float)
      decoded = readFloat64(ui8a, 1)
      ui8a[0] = 0xfb
      writer.push(ui8a.slice(0, 9))
    }
  }
}

/**
 * @param {Token} token
 * @param {EncodeOptions} options
 * @returns {number}
 */
encodeFloat.encodedSize = function encodedSize (token, options) {
  const float = token.value

  if (float === false || float === true || float === null || float === undefined) {
    return 1
  }

  if (!options || options.float64 !== true) {
    encodeFloat16(float)
    let decoded = readFloat16(ui8a, 1)
    if (float === decoded || Number.isNaN(float)) {
      return 3
    }
    encodeFloat32(float)
    decoded = readFloat32(ui8a, 1)
    if (float === decoded) {
      return 5
    }
  }
  return 9
}

const buffer = new ArrayBuffer(9)
const dataView = new DataView(buffer, 1)
const ui8a = new Uint8Array(buffer, 0)

/**
 * @param {number} inp
 */
function encodeFloat16 (inp) {
  if (inp === Infinity) {
    dataView.setUint16(0, 0x7c00, false)
  } else if (inp === -Infinity) {
    dataView.setUint16(0, 0xfc00, false)
  } else if (Number.isNaN(inp)) {
    dataView.setUint16(0, 0x7e00, false)
  } else {
    dataView.setFloat32(0, inp)
    const valu32 = dataView.getUint32(0)
    const exponent = (valu32 & 0x7f800000) >> 23
    const mantissa = valu32 & 0x7fffff

    if (exponent === 0xff) {
      // too big, Infinity, but this should be hard (impossible?) to trigger
      dataView.setUint16(0, 0x7c00, false)
    } else if (exponent === 0x00) {
      // 0.0, -0.0 and subnormals, shouldn't be possible to get here because 0.0 should be counted as an int
      // Use valu32 for sign bit since bitwise ops on floats lose -0 sign
      dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | (mantissa >> 13), false)
    } else { // standard numbers
      // chunks of logic here borrowed from https://github.com/PJK/libcbor/blob/c78f437182533e3efa8d963ff4b945bb635c2284/src/cbor/encoding.c#L127
      const logicalExponent = exponent - 127
      // Now we know that 2^exponent <= 0 logically
      if (logicalExponent < -24) {
        /* No unambiguous representation exists, this float is not a half float
          and is too small to be represented using a half, round off to zero.
          Consistent with the reference implementation. */
        // should be difficult (impossible?) to get here in JS
        dataView.setUint16(0, 0)
      } else if (logicalExponent < -14) {
        /* Offset the remaining decimal places by shifting the significand, the
          value is lost. This is an implementation decision that works around the
          absence of standard half-float in the language. */
        dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | /* sign bit */ (1 << (24 + logicalExponent)), false)
      } else {
        dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | ((logicalExponent + 15) << 10) | (mantissa >> 13), false)
      }
    }
  }
}

/**
 * @param {Uint8Array} ui8a
 * @param {number} pos
 * @returns {number}
 */
function readFloat16 (ui8a, pos) {
  if (ui8a.length - pos < 2) {
    throw new Error(`${decodeErrPrefix} not enough data for float16`)
  }

  const half = (ui8a[pos] << 8) + ui8a[pos + 1]
  if (half === 0x7c00) {
    return Infinity
  }
  if (half === 0xfc00) {
    return -Infinity
  }
  if (half === 0x7e00) {
    return NaN
  }
  const exp = (half >> 10) & 0x1f
  const mant = half & 0x3ff
  let val
  if (exp === 0) {
    val = mant * (2 ** -24)
  } else if (exp !== 31) {
    val = (mant + 1024) * (2 ** (exp - 25))
  } else {
    // may not be possible to get here
    val = mant === 0 ? Infinity : NaN
  }
  return (half & 0x8000) ? -val : val
}

/**
 * @param {number} inp
 */
function encodeFloat32 (inp) {
  dataView.setFloat32(0, inp, false)
}

/**
 * @param {Uint8Array} ui8a
 * @param {number} pos
 * @returns {number}
 */
function readFloat32 (ui8a, pos) {
  if (ui8a.length - pos < 4) {
    throw new Error(`${decodeErrPrefix} not enough data for float32`)
  }
  const offset = (ui8a.byteOffset || 0) + pos
  return new DataView(ui8a.buffer, offset, 4).getFloat32(0, false)
}

/**
 * @param {number} inp
 */
function encodeFloat64 (inp) {
  dataView.setFloat64(0, inp, false)
}

/**
 * @param {Uint8Array} ui8a
 * @param {number} pos
 * @returns {number}
 */
function readFloat64 (ui8a, pos) {
  if (ui8a.length - pos < 8) {
    throw new Error(`${decodeErrPrefix} not enough data for float64`)
  }
  const offset = (ui8a.byteOffset || 0) + pos
  return new DataView(ui8a.buffer, offset, 8).getFloat64(0, false)
}

/**
 * @param {Token} _tok1
 * @param {Token} _tok2
 * @returns {number}
 */
encodeFloat.compareTokens = encodeUint.compareTokens
/*
encodeFloat.compareTokens = function compareTokens (_tok1, _tok2) {
  return _tok1
  throw new Error(`${encodeErrPrefix} cannot use floats as map keys`)
}
*/
/**
 * Bl is a list of byte chunks, similar to https://github.com/rvagg/bl but for
 * writing rather than reading.
 * A Bl object accepts set() operations for individual bytes and copyTo() for
 * inserting byte arrays. These write operations don't automatically increment
 * the internal cursor so its "length" won't be changed. Instead, increment()
 * must be called to extend its length to cover the inserted data.
 * The toBytes() call will convert all internal memory to a single Uint8Array of
 * the correct length, truncating any data that is stored but hasn't been
 * included by an increment().
 * get() can retrieve a single byte.
 * All operations (except toBytes()) take an "offset" argument that will perform
 * the write at the offset _from the current cursor_. For most operations this
 * will be `0` to write at the current cursor position but it can be ahead of
 * the current cursor. Negative offsets probably work but are untested.
 */

// TODO: ipjs doesn't support this, only for test files: https://github.com/mikeal/ipjs/blob/master/src/package/testFile.js#L39
import { alloc, concat, slice } from './byte-utils.js'

// the ts-ignores in this file are almost all for the `Uint8Array|number[]` duality that exists
// for perf reasons. Consider better approaches to this or removing it entirely, it is quite
// risky because of some assumptions about small chunks === number[] and everything else === Uint8Array.

const defaultChunkSize = 256

export class Bl {
  /**
   * @param {number} [chunkSize]
   */
  constructor (chunkSize = defaultChunkSize) {
    this.chunkSize = chunkSize
    /** @type {number} */
    this.cursor = 0
    /** @type {number} */
    this.maxCursor = -1
    /** @type {(Uint8Array|number[])[]} */
    this.chunks = []
    // keep the first chunk around if we can to save allocations for future encodes
    /** @type {Uint8Array|number[]|null} */
    this._initReuseChunk = null
  }

  reset () {
    this.cursor = 0
    this.maxCursor = -1
    if (this.chunks.length) {
      this.chunks = []
    }
    if (this._initReuseChunk !== null) {
      this.chunks.push(this._initReuseChunk)
      this.maxCursor = this._initReuseChunk.length - 1
    }
  }

  /**
   * @param {Uint8Array|number[]} bytes
   */
  push (bytes) {
    let topChunk = this.chunks[this.chunks.length - 1]
    const newMax = this.cursor + bytes.length
    if (newMax <= this.maxCursor + 1) {
      // we have at least one chunk and we can fit these bytes into that chunk
      const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1
      // @ts-ignore
      topChunk.set(bytes, chunkPos)
    } else {
      // can't fit it in
      if (topChunk) {
        // trip the last chunk to `cursor` if we need to
        const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1
        if (chunkPos < topChunk.length) {
          // @ts-ignore
          this.chunks[this.chunks.length - 1] = topChunk.subarray(0, chunkPos)
          this.maxCursor = this.cursor - 1
        }
      }
      if (bytes.length < 64 && bytes.length < this.chunkSize) {
        // make a new chunk and copy the new one into it
        topChunk = alloc(this.chunkSize)
        this.chunks.push(topChunk)
        this.maxCursor += topChunk.length
        if (this._initReuseChunk === null) {
          this._initReuseChunk = topChunk
        }
        // @ts-ignore
        topChunk.set(bytes, 0)
      } else {
        // push the new bytes in as its own chunk
        this.chunks.push(bytes)
        this.maxCursor += bytes.length
      }
    }
    this.cursor += bytes.length
  }

  /**
   * @param {boolean} [reset]
   * @returns {Uint8Array}
   */
  toBytes (reset = false) {
    let byts
    if (this.chunks.length === 1) {
      const chunk = this.chunks[0]
      if (reset && this.cursor > chunk.length / 2) {
        // @ts-ignore
        byts = this.cursor === chunk.length ? chunk : chunk.subarray(0, this.cursor)
        this._initReuseChunk = null
        this.chunks = []
      } else {
        // @ts-ignore
        byts = slice(chunk, 0, this.cursor)
      }
    } else {
      // @ts-ignore
      byts = concat(this.chunks, this.cursor)
    }
    if (reset) {
      this.reset()
    }
    return byts
  }
}

/**
 * U8Bl is a buffer list that writes directly to a user-provided Uint8Array.
 * It provides the same interface as Bl but writes to a fixed destination.
 */
export class U8Bl {
  /**
   * @param {Uint8Array} dest
   */
  constructor (dest) {
    this.dest = dest
    /** @type {number} */
    this.cursor = 0
    // chunks is for interface compatibility with Bl - encode.js checks chunks.length
    // as a sanity check for pre-calculated sizes. For U8Bl this is always [dest].
    /** @type {Uint8Array[]} */
    this.chunks = [dest]
  }

  reset () {
    this.cursor = 0
  }

  /**
   * @param {Uint8Array|number[]} bytes
   */
  push (bytes) {
    if (this.cursor + bytes.length > this.dest.length) {
      throw new Error('write out of bounds, destination buffer is too small')
    }
    this.dest.set(bytes, this.cursor)
    this.cursor += bytes.length
  }

  /**
   * @param {boolean} [reset]
   * @returns {Uint8Array}
   */
  toBytes (reset = false) {
    const byts = this.dest.subarray(0, this.cursor)
    if (reset) {
      this.reset()
    }
    return byts
  }
}
// Use Uint8Array directly in the browser, use Buffer in Node.js but don't
// speak its name directly to avoid bundlers pulling in the `Buffer` polyfill

// @ts-ignore
export const useBuffer = globalThis.process &&
  // @ts-ignore
  !globalThis.process.browser &&
  // @ts-ignore
  globalThis.Buffer &&
  // @ts-ignore
  typeof globalThis.Buffer.isBuffer === 'function'

const textEncoder = new TextEncoder()

/**
 * @param {Uint8Array} buf
 * @returns {boolean}
 */
function isBuffer (buf) {
  // @ts-ignore
  return useBuffer && globalThis.Buffer.isBuffer(buf)
}

/**
 * @param {Uint8Array|number[]} buf
 * @returns {Uint8Array}
 */
export function asU8A (buf) {
  if (!(buf instanceof Uint8Array)) {
    return Uint8Array.from(buf)
  }
  return isBuffer(buf) ? new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength) : buf
}

// Threshold for manual UTF-8 encoding vs native methods.
// Node.js Buffer.from: crossover ~24 chars
// Browser TextEncoder: crossover ~200 chars
const FROM_STRING_THRESHOLD_BUFFER = 24
const FROM_STRING_THRESHOLD_TEXTENCODER = 200

export const fromString = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {string} string
     */
    (string) => {
      return string.length >= FROM_STRING_THRESHOLD_BUFFER
        ? // eslint-disable-line operator-linebreak
      // @ts-ignore
        globalThis.Buffer.from(string)
        : utf8ToBytes(string)
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {string} string
     */
    (string) => {
      return string.length >= FROM_STRING_THRESHOLD_TEXTENCODER ? textEncoder.encode(string) : utf8ToBytes(string)
    }

/**
 * Buffer variant not fast enough for what we need
 * @param {number[]} arr
 * @returns {Uint8Array}
 */
export const fromArray = (arr) => {
  return Uint8Array.from(arr)
}

export const slice = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} bytes
     * @param {number} start
     * @param {number} end
     */
    // Buffer.slice() returns a view, not a copy, so we need special handling
    (bytes, start, end) => {
      if (isBuffer(bytes)) {
        return new Uint8Array(bytes.subarray(start, end))
      }
      return bytes.slice(start, end)
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} bytes
     * @param {number} start
     * @param {number} end
     */
    (bytes, start, end) => {
      return bytes.slice(start, end)
    }

export const concat = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array[]} chunks
     * @param {number} length
     * @returns {Uint8Array}
     */
    (chunks, length) => {
      // might get a stray plain Array here
      chunks = chunks.map((c) => c instanceof Uint8Array
        ? c
        : // eslint-disable-line operator-linebreak
        // @ts-ignore
        globalThis.Buffer.from(c))
      // @ts-ignore
      return asU8A(globalThis.Buffer.concat(chunks, length))
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array[]} chunks
     * @param {number} length
     * @returns {Uint8Array}
     */
    (chunks, length) => {
      const out = new Uint8Array(length)
      let off = 0
      for (let b of chunks) {
        if (off + b.length > out.length) {
          // final chunk that's bigger than we need
          b = b.subarray(0, out.length - off)
        }
        out.set(b, off)
        off += b.length
      }
      return out
    }

export const alloc = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {number} size
     * @returns {Uint8Array}
     */
    (size) => {
      // we always write over the contents we expose so this should be safe
      // @ts-ignore
      return globalThis.Buffer.allocUnsafe(size)
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {number} size
     * @returns {Uint8Array}
     */
    (size) => {
      return new Uint8Array(size)
    }

export const toHex = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} d
     * @returns {string}
     */
    (d) => {
      if (typeof d === 'string') {
        return d
      }
      // @ts-ignore
      return globalThis.Buffer.from(toBytes(d)).toString('hex')
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} d
     * @returns {string}
     */
    (d) => {
      if (typeof d === 'string') {
        return d
      }
      // @ts-ignore not smart enough to figure this out
      return Array.prototype.reduce.call(toBytes(d), (p, c) => `${p}${c.toString(16).padStart(2, '0')}`, '')
    }

export const fromHex = useBuffer
  ? // eslint-disable-line operator-linebreak
  /**
   * @param {string|Uint8Array} hex
   * @returns {Uint8Array}
   */
    (hex) => {
      if (hex instanceof Uint8Array) {
        return hex
      }
      // @ts-ignore
      return globalThis.Buffer.from(hex, 'hex')
    }
  : // eslint-disable-line operator-linebreak
  /**
   * @param {string|Uint8Array} hex
   * @returns {Uint8Array}
   */
    (hex) => {
      if (hex instanceof Uint8Array) {
        return hex
      }
      if (!hex.length) {
        return new Uint8Array(0)
      }
      return new Uint8Array(hex.split('')
        .map((/** @type {string} */ c, /** @type {number} */ i, /** @type {string[]} */ d) => i % 2 === 0 ? `0x${c}${d[i + 1]}` : '')
        .filter(Boolean)
        .map((/** @type {string} */ e) => parseInt(e, 16)))
    }

/**
 * @param {Uint8Array|ArrayBuffer|ArrayBufferView} obj
 * @returns {Uint8Array}
 */
function toBytes (obj) {
  if (obj instanceof Uint8Array && obj.constructor.name === 'Uint8Array') {
    return obj
  }
  if (obj instanceof ArrayBuffer) {
    return new Uint8Array(obj)
  }
  if (ArrayBuffer.isView(obj)) {
    return new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength)
  }
  throw new Error('Unknown type, must be binary type')
}

/**
 * @param {Uint8Array} b1
 * @param {Uint8Array} b2
 * @returns {number}
 */
export function compare (b1, b2) {
  if (isBuffer(b1) && isBuffer(b2)) {
    // probably not possible to get here in the current API
    // @ts-ignore Buffer
    return b1.compare(b2)
  }
  for (let i = 0; i < b1.length; i++) {
    if (b1[i] === b2[i]) {
      continue
    }
    return b1[i] < b2[i] ? -1 : 1
  }
  return 0
}

// The below code is taken from https://github.com/google/closure-library/blob/8598d87242af59aac233270742c8984e2b2bdbe0/closure/goog/crypt/crypt.js#L117-L143
// Licensed Apache-2.0.

/**
 * @param {string} str
 * @returns {number[]}
 */
function utf8ToBytes (str) {
  const out = []
  let p = 0
  for (let i = 0; i < str.length; i++) {
    let c = str.charCodeAt(i)
    if (c < 128) {
      out[p++] = c
    } else if (c < 2048) {
      out[p++] = (c >> 6) | 192
      out[p++] = (c & 63) | 128
    } else if (
      ((c & 0xFC00) === 0xD800) && (i + 1) < str.length &&
      ((str.charCodeAt(i + 1) & 0xFC00) === 0xDC00)) {
      // Surrogate Pair
      c = 0x10000 + ((c & 0x03FF) << 10) + (str.charCodeAt(++i) & 0x03FF)
      out[p++] = (c >> 18) | 240
      out[p++] = ((c >> 12) & 63) | 128
      out[p++] = ((c >> 6) & 63) | 128
      out[p++] = (c & 63) | 128
    } else {
      if ((c >= 0xD800) && (c <= 0xDFFF)) {
        c = 0xFFFD // Unpaired Surrogate
      }
      out[p++] = (c >> 12) | 224
      out[p++] = ((c >> 6) & 63) | 128
      out[p++] = (c & 63) | 128
    }
  }
  return out
}

// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
const MAX_ARGUMENTS_LENGTH = 0x1000

/**
 * @param {number[]} codePoints
 * @returns {string}
 */
export function decodeCodePointsArray (codePoints) {
  const len = codePoints.length
  if (len <= MAX_ARGUMENTS_LENGTH) {
    return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  }
  // Decode in chunks to avoid "call stack size exceeded".
  let res = ''
  let i = 0
  while (i < len) {
    res += String.fromCharCode.apply(
      String,
      codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
    )
  }
  return res
}
const decodeErrPrefix = 'CBOR decode error:'
const encodeErrPrefix = 'CBOR encode error:'

const uintMinorPrefixBytes = []
uintMinorPrefixBytes[23] = 1
uintMinorPrefixBytes[24] = 2
uintMinorPrefixBytes[25] = 3
uintMinorPrefixBytes[26] = 5
uintMinorPrefixBytes[27] = 9

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} need
 */
function assertEnoughData (data, pos, need) {
  if (data.length - pos < need) {
    throw new Error(`${decodeErrPrefix} not enough data for type`)
  }
}

export {
  decodeErrPrefix,
  encodeErrPrefix,
  uintMinorPrefixBytes,
  assertEnoughData
}
import { decodeErrPrefix } from './common.js'
import { Type } from './token.js'
import { jump, quick } from './jump.js'
import { asU8A } from './byte-utils.js'

/**
 * @typedef {import('./token.js').Token} Token
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 * @typedef {import('../interface.js').DecodeTokenizer} DecodeTokenizer
 * @typedef {import('../interface.js').TagDecodeControl} TagDecodeControl
 */

const defaultDecodeOptions = {
  strict: false,
  allowIndefinite: true,
  allowUndefined: true,
  allowBigInt: true
}

/**
 * @implements {DecodeTokenizer}
 */
class Tokeniser {
  /**
   * @param {Uint8Array} data
   * @param {DecodeOptions} options
   */
  constructor (data, options = {}) {
    this._pos = 0
    this.data = data
    this.options = options
  }

  pos () {
    return this._pos
  }

  done () {
    return this._pos >= this.data.length
  }

  next () {
    const byt = this.data[this._pos]
    let token = quick[byt]
    if (token === undefined) {
      const decoder = jump[byt]
      // if we're here then there's something wrong with our jump or quick lists!
      if (!decoder) {
        throw new Error(`${decodeErrPrefix} no decoder for major type ${byt >>> 5} (byte 0x${byt.toString(16).padStart(2, '0')})`)
      }
      const minor = byt & 31
      token = decoder(this.data, this._pos, minor, this.options)
    }
    // @ts-ignore we get to assume encodedLength is set (crossing fingers slightly)
    this._pos += token.encodedLength
    return token
  }
}

const DONE = Symbol.for('DONE')
const BREAK = Symbol.for('BREAK')

/**
 * @param {Token} token
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {any|BREAK|DONE}
 */
function tokenToArray (token, tokeniser, options) {
  const arr = []
  for (let i = 0; i < token.value; i++) {
    const value = tokensToObject(tokeniser, options)
    if (value === BREAK) {
      if (token.value === Infinity) {
        // normal end to indefinite length array
        break
      }
      throw new Error(`${decodeErrPrefix} got unexpected break to lengthed array`)
    }
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} found array but not enough entries (got ${i}, expected ${token.value})`)
    }
    arr[i] = value
  }
  return arr
}

/**
 * @param {Token} token
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {any|BREAK|DONE}
 */
function tokenToMap (token, tokeniser, options) {
  const useMaps = options.useMaps === true
  const rejectDuplicateMapKeys = options.rejectDuplicateMapKeys === true
  const obj = useMaps ? undefined : {}
  const m = useMaps ? new Map() : undefined
  for (let i = 0; i < token.value; i++) {
    const key = tokensToObject(tokeniser, options)
    if (key === BREAK) {
      if (token.value === Infinity) {
        // normal end to indefinite length map
        break
      }
      throw new Error(`${decodeErrPrefix} got unexpected break to lengthed map`)
    }
    if (key === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no key], expected ${token.value})`)
    }
    if (!useMaps && typeof key !== 'string') {
      throw new Error(`${decodeErrPrefix} non-string keys not supported (got ${typeof key})`)
    }
    if (rejectDuplicateMapKeys) {
      // @ts-ignore
      if ((useMaps && m.has(key)) || (!useMaps && Object.hasOwn(obj, key))) {
        throw new Error(`${decodeErrPrefix} found repeat map key "${key}"`)
      }
    }
    const value = tokensToObject(tokeniser, options)
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no value], expected ${token.value})`)
    }
    if (useMaps) {
      // @ts-ignore TODO reconsider this .. maybe needs to be strict about key types
      m.set(key, value)
    } else {
      // @ts-ignore TODO reconsider this .. maybe needs to be strict about key types
      obj[key] = value
    }
  }
  // @ts-ignore c'mon man
  return useMaps ? m : obj
}

/**
 * Generator that yields [key, value] entries from a CBOR map token.
 * Used by tag decoders that need to preserve key types (e.g., Tag 259 Map).
 * @param {Token} token - The map token
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {Generator<[any, any], void, unknown>}
 */
function * tokenToMapEntries (token, tokeniser, options) {
  for (let i = 0; i < token.value; i++) {
    const key = tokensToObject(tokeniser, options)
    if (key === BREAK) {
      if (token.value === Infinity) {
        // normal end to indefinite length map
        break
      }
      throw new Error(`${decodeErrPrefix} got unexpected break to lengthed map`)
    }
    if (key === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no key], expected ${token.value})`)
    }
    const value = tokensToObject(tokeniser, options)
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no value], expected ${token.value})`)
    }
    yield [key, value]
  }
}

/**
 * Creates a TagDecodeControl object for tag decoders.
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {TagDecodeControl}
 */
function createTagDecodeControl (tokeniser, options) {
  let called = false

  /**
   * @type {TagDecodeControl}
   */
  const decode = function () {
    if (called) {
      throw new Error(`${decodeErrPrefix} tag decode() may only be called once`)
    }
    called = true
    const value = tokensToObject(tokeniser, options)
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} tag content missing`)
    }
    if (value === BREAK) {
      throw new Error(`${decodeErrPrefix} got unexpected break in tag content`)
    }
    return value
  }

  decode.entries = function () {
    if (called) {
      throw new Error(`${decodeErrPrefix} tag decode() may only be called once`)
    }
    called = true

    // Get the next token and ensure it's a map
    const token = tokeniser.next()
    if (!Type.equals(token.type, Type.map)) {
      throw new Error(`${decodeErrPrefix} entries() requires map content, got ${token.type.name}`)
    }

    // Collect all entries into an array (ensures full content consumption)
    const entries = []
    for (const entry of tokenToMapEntries(token, tokeniser, options)) {
      entries.push(entry)
    }
    return entries
  }

  // For internal tracking
  Object.defineProperty(decode, '_called', {
    get () { return called },
    enumerable: false
  })

  return decode
}

/**
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {any|BREAK|DONE}
 */
function tokensToObject (tokeniser, options) {
  // should we support array as an argument?
  // check for tokenIter[Symbol.iterator] and replace tokenIter with what that returns?
  if (tokeniser.done()) {
    return DONE
  }

  const token = tokeniser.next()

  if (Type.equals(token.type, Type.break)) {
    return BREAK
  }

  if (token.type.terminal) {
    return token.value
  }

  if (Type.equals(token.type, Type.array)) {
    return tokenToArray(token, tokeniser, options)
  }

  if (Type.equals(token.type, Type.map)) {
    return tokenToMap(token, tokeniser, options)
  }

  if (Type.equals(token.type, Type.tag)) {
    if (options.tags && typeof options.tags[token.value] === 'function') {
      const decodeControl = createTagDecodeControl(tokeniser, options)
      const result = options.tags[token.value](decodeControl)
      if (!decodeControl._called) {
        throw new Error(`${decodeErrPrefix} tag decoder must call decode() or entries()`)
      }
      return result
    }
    throw new Error(`${decodeErrPrefix} tag not supported (${token.value})`)
  }
  throw new Error('unsupported')
}

/**
 * @param {Uint8Array} data
 * @param {DecodeOptions} [options]
 * @returns {[any, Uint8Array]}
 */
function decodeFirst (data, options) {
  if (!(data instanceof Uint8Array)) {
    throw new Error(`${decodeErrPrefix} data to decode must be a Uint8Array`)
  }
  options = Object.assign({}, defaultDecodeOptions, options)
  // Convert Buffer to plain Uint8Array for faster slicing in decode path
  const u8aData = asU8A(data)
  const tokeniser = options.tokenizer || new Tokeniser(u8aData, options)
  const decoded = tokensToObject(tokeniser, options)
  if (decoded === DONE) {
    throw new Error(`${decodeErrPrefix} did not find any content to decode`)
  }
  if (decoded === BREAK) {
    throw new Error(`${decodeErrPrefix} got unexpected break`)
  }
  return [decoded, data.subarray(tokeniser.pos())]
}

/**
 * @param {Uint8Array} data
 * @param {DecodeOptions} [options]
 * @returns {any}
 */
function decode (data, options) {
  const [decoded, remainder] = decodeFirst(data, options)
  if (remainder.length > 0) {
    throw new Error(`${decodeErrPrefix} too many terminals, data makes no sense`)
  }
  return decoded
}

export { Tokeniser, tokensToObject, decode, decodeFirst }
import { is } from './is.js'
import { Token, Type } from './token.js'
import { Bl, U8Bl } from './bl.js'
import { encodeErrPrefix } from './common.js'
import { quickEncodeToken } from './jump.js'
import { asU8A, compare, fromString } from './byte-utils.js'

import { encodeUint, encodeUintValue } from './0uint.js'
import { encodeNegint } from './1negint.js'
import { encodeBytes } from './2bytes.js'
import { encodeString } from './3string.js'
import { encodeArray } from './4array.js'
import { encodeMap } from './5map.js'
import { encodeTag } from './6tag.js'
import { encodeFloat, MINOR_FALSE, MINOR_TRUE, MINOR_NULL, MINOR_UNDEFINED } from './7float.js'

/**
 * @typedef {import('../interface.js').EncodeOptions} EncodeOptions
 * @typedef {import('../interface.js').OptionalTypeEncoder} OptionalTypeEncoder
 * @typedef {import('../interface.js').Reference} Reference
 * @typedef {import('../interface.js').StrictTypeEncoder} StrictTypeEncoder
 * @typedef {import('../interface.js').TokenTypeEncoder} TokenTypeEncoder
 * @typedef {import('../interface.js').TokenOrNestedTokens} TokenOrNestedTokens
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 */

/** @type {EncodeOptions} */
const defaultEncodeOptions = {
  float64: false,
  mapSorter,
  quickEncodeToken
}

/** @type {EncodeOptions} */
export const rfc8949EncodeOptions = Object.freeze({
  mapSorter: rfc8949MapSorter,
  quickEncodeToken
})

/** @returns {TokenTypeEncoder[]} */
export function makeCborEncoders () {
  const encoders = []
  encoders[Type.uint.major] = encodeUint
  encoders[Type.negint.major] = encodeNegint
  encoders[Type.bytes.major] = encodeBytes
  encoders[Type.string.major] = encodeString
  encoders[Type.array.major] = encodeArray
  encoders[Type.map.major] = encodeMap
  encoders[Type.tag.major] = encodeTag
  encoders[Type.float.major] = encodeFloat
  return encoders
}

const cborEncoders = makeCborEncoders()

const defaultWriter = new Bl()

/** @implements {Reference} */
class Ref {
  /**
   * @param {object|any[]} obj
   * @param {Reference|undefined} parent
   */
  constructor (obj, parent) {
    this.obj = obj
    this.parent = parent
  }

  /**
   * @param {object|any[]} obj
   * @returns {boolean}
   */
  includes (obj) {
    /** @type {Reference|undefined} */
    let p = this
    do {
      if (p.obj === obj) {
        return true
      }
    } while (p = p.parent) // eslint-disable-line
    return false
  }

  /**
   * @param {Reference|undefined} stack
   * @param {object|any[]} obj
   * @returns {Reference}
   */
  static createCheck (stack, obj) {
    if (stack && stack.includes(obj)) {
      throw new Error(`${encodeErrPrefix} object contains circular references`)
    }
    return new Ref(obj, stack)
  }
}

const simpleTokens = {
  null: new Token(Type.null, null),
  undefined: new Token(Type.undefined, undefined),
  true: new Token(Type.true, true),
  false: new Token(Type.false, false),
  emptyArray: new Token(Type.array, 0),
  emptyMap: new Token(Type.map, 0)
}

/** @type {{[typeName: string]: StrictTypeEncoder}} */
const typeEncoders = {
  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  number (obj, _typ, _options, _refStack) {
    if (!Number.isInteger(obj) || !Number.isSafeInteger(obj)) {
      return new Token(Type.float, obj)
    } else if (obj >= 0) {
      return new Token(Type.uint, obj)
    } else {
      return new Token(Type.negint, obj)
    }
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  bigint (obj, _typ, _options, _refStack) {
    if (obj >= BigInt(0)) {
      return new Token(Type.uint, obj)
    } else {
      return new Token(Type.negint, obj)
    }
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  Uint8Array (obj, _typ, _options, _refStack) {
    return new Token(Type.bytes, obj)
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  string (obj, _typ, _options, _refStack) {
    return new Token(Type.string, obj)
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  boolean (obj, _typ, _options, _refStack) {
    return obj ? simpleTokens.true : simpleTokens.false
  },

  /**
   * @param {any} _obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  null (_obj, _typ, _options, _refStack) {
    return simpleTokens.null
  },

  /**
   * @param {any} _obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  undefined (_obj, _typ, _options, _refStack) {
    return simpleTokens.undefined
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  ArrayBuffer (obj, _typ, _options, _refStack) {
    return new Token(Type.bytes, new Uint8Array(obj))
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  DataView (obj, _typ, _options, _refStack) {
    return new Token(Type.bytes, new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength))
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} options
   * @param {Reference} [refStack]
   * @returns {TokenOrNestedTokens}
   */
  Array (obj, _typ, options, refStack) {
    if (!obj.length) {
      if (options.addBreakTokens === true) {
        return [simpleTokens.emptyArray, new Token(Type.break)]
      }
      return simpleTokens.emptyArray
    }
    refStack = Ref.createCheck(refStack, obj)
    const entries = []
    let i = 0
    for (const e of obj) {
      entries[i++] = objectToTokens(e, options, refStack)
    }
    if (options.addBreakTokens) {
      return [new Token(Type.array, obj.length), entries, new Token(Type.break)]
    }
    return [new Token(Type.array, obj.length), entries]
  },

  /**
   * @param {any} obj
   * @param {string} typ
   * @param {EncodeOptions} options
   * @param {Reference} [refStack]
   * @returns {TokenOrNestedTokens}
   */
  Object (obj, typ, options, refStack) {
    // could be an Object or a Map
    const isMap = typ !== 'Object'
    // it's slightly quicker to use Object.keys() than Object.entries()
    const keys = isMap ? obj.keys() : Object.keys(obj)
    const maxLength = isMap ? obj.size : keys.length

    /** @type {undefined | [TokenOrNestedTokens, TokenOrNestedTokens][]} */
    let entries

    if (maxLength) {
      // Pre-allocate the array with the expected size
      entries = new Array(maxLength)
      refStack = Ref.createCheck(refStack, obj)
      const skipUndefined = !isMap && options.ignoreUndefinedProperties

      let i = 0
      for (const key of keys) {
        const value = isMap ? obj.get(key) : obj[key]
        if (skipUndefined && value === undefined) {
          continue
        }
        entries[i++] = [
          objectToTokens(key, options, refStack),
          objectToTokens(value, options, refStack)
        ]
      }

      // Truncate only if properties were skipped
      if (i < maxLength) {
        entries.length = i
      }
    }

    if (!entries?.length) {
      if (options.addBreakTokens === true) {
        return [simpleTokens.emptyMap, new Token(Type.break)]
      }
      return simpleTokens.emptyMap
    }

    sortMapEntries(entries, options)
    if (options.addBreakTokens) {
      return [new Token(Type.map, entries.length), entries, new Token(Type.break)]
    }
    return [new Token(Type.map, entries.length), entries]
  },

  /**
   * Encode a `Tagged` wrapper as a CBOR tag header followed by the encoded
   * form of the wrapped value. The value is recursively tokenised through
   * `objectToTokens()` so any registered `typeEncoders` apply to it.
   *
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} options
   * @param {Reference} [refStack]
   * @returns {TokenOrNestedTokens}
   */
  Tagged (obj, _typ, options, refStack) {
    return [
      new Token(Type.tag, obj.tag),
      objectToTokens(obj.value, options, refStack)
    ]
  }
}

typeEncoders.Map = typeEncoders.Object
typeEncoders.Buffer = typeEncoders.Uint8Array
for (const typ of 'Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64'.split(' ')) {
  typeEncoders[`${typ}Array`] = typeEncoders.DataView
}

/**
 * @param {any} obj
 * @param {EncodeOptions} [options]
 * @param {Reference} [refStack]
 * @returns {TokenOrNestedTokens}
 */
function objectToTokens (obj, options = {}, refStack) {
  const typ = is(obj)
  const customTypeEncoder = (options && options.typeEncoders && /** @type {OptionalTypeEncoder} */ options.typeEncoders[typ]) || typeEncoders[typ]
  if (typeof customTypeEncoder === 'function') {
    const tokens = customTypeEncoder(obj, typ, options, refStack)
    if (tokens != null) {
      return tokens
    }
  }
  const typeEncoder = typeEncoders[typ]
  if (!typeEncoder) {
    throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`)
  }
  return typeEncoder(obj, typ, options, refStack)
}

/*
CBOR key sorting is a mess.

The canonicalisation recommendation from https://tools.ietf.org/html/rfc7049#section-3.9
includes the wording:

> The keys in every map must be sorted lowest value to highest.
> Sorting is performed on the bytes of the representation of the key
> data items without paying attention to the 3/5 bit splitting for
> major types.
> ...
>  *  If two keys have different lengths, the shorter one sorts
      earlier;
>  *  If two keys have the same length, the one with the lower value
      in (byte-wise) lexical order sorts earlier.

1. It is not clear what "bytes of the representation of the key" means: is it
   the CBOR representation, or the binary representation of the object itself?
   Consider the int and uint difference here.
2. It is not clear what "without paying attention to" means: do we include it
   and compare on that? Or do we omit the special prefix byte, (mostly) treating
   the key in its plain binary representation form.

The FIDO 2.0: Client To Authenticator Protocol spec takes the original CBOR
wording and clarifies it according to their understanding.
https://fidoalliance.org/specs/fido-v2.0-rd-20170927/fido-client-to-authenticator-protocol-v2.0-rd-20170927.html#message-encoding

> The keys in every map must be sorted lowest value to highest. Sorting is
> performed on the bytes of the representation of the key data items without
> paying attention to the 3/5 bit splitting for major types. The sorting rules
> are:
>  * If the major types are different, the one with the lower value in numerical
>    order sorts earlier.
>  * If two keys have different lengths, the shorter one sorts earlier;
>  * If two keys have the same length, the one with the lower value in
>    (byte-wise) lexical order sorts earlier.

Some other implementations, such as borc, do a full encode then do a
length-first, byte-wise-second comparison:
https://github.com/dignifiedquire/borc/blob/b6bae8b0bcde7c3976b0f0f0957208095c392a36/src/encoder.js#L358
https://github.com/dignifiedquire/borc/blob/b6bae8b0bcde7c3976b0f0f0957208095c392a36/src/utils.js#L143-L151

This has the benefit of being able to easily handle arbitrary keys, including
complex types (maps and arrays).

We'll opt for the FIDO approach, since it affords some efficies since we don't
need a full encode of each key to determine order and can defer to the types
to determine how to most efficiently order their values (i.e. int and uint
ordering can be done on the numbers, no need for byte-wise, for example).

Recommendation: stick to single key types or you'll get into trouble, and prefer
string keys because it's much simpler that way.
*/

/**
 * @param {TokenOrNestedTokens[]} entries
 * @param {EncodeOptions} options
 */
function sortMapEntries (entries, options) {
  if (options.mapSorter) {
    entries.sort(options.mapSorter)
  }
}

/**
 * @param {(Token|Token[])[]} e1
 * @param {(Token|Token[])[]} e2
 * @returns {number}
 */
function mapSorter (e1, e2) {
  // the key position ([0]) could have a single token or an array
  // almost always it'll be a single token but complex key might get involved
  const keyToken1 = Array.isArray(e1[0]) ? e1[0][0] : e1[0]
  const keyToken2 = Array.isArray(e2[0]) ? e2[0][0] : e2[0]

  // different key types
  if (keyToken1.type !== keyToken2.type) {
    return keyToken1.type.compare(keyToken2.type)
  }

  const major = keyToken1.type.major
  // TODO: handle case where cmp === 0 but there are more keyToken e. complex type)
  const tcmp = cborEncoders[major].compareTokens(keyToken1, keyToken2)
  if (tcmp === 0) {
    // duplicate key or complex type where the first token matched,
    // i.e. a map or array and we're only comparing the opening token
    console.warn('WARNING: complex key types used, CBOR key sorting guarantees are gone')
  }
  return tcmp
}

/**
 * @typedef {Token & { _keyBytes?: Uint8Array }} TokenEx
 *
 * @param {(Token|Token[])[]} e1
 * @param {(Token|Token[])[]} e2
 * @returns {number}
 */
function rfc8949MapSorter (e1, e2) {
  if (e1[0] instanceof Token && e2[0] instanceof Token) {
    const t1 = /** @type {TokenEx} */ (e1[0])
    const t2 = /** @type {TokenEx} */ (e2[0])

    if (!t1._keyBytes) {
      t1._keyBytes = encodeRfc8949(t1.value)
    }

    if (!t2._keyBytes) {
      t2._keyBytes = encodeRfc8949(t2.value)
    }

    return compare(t1._keyBytes, t2._keyBytes)
  }

  throw new Error('rfc8949MapSorter: complex key types are not supported yet')
}

/**
 * @param {any} data
 * @returns {Uint8Array}
 */
function encodeRfc8949 (data) {
  return encodeCustom(data, cborEncoders, rfc8949EncodeOptions)
}

/**
 * @param {ByteWriter} writer
 * @param {TokenOrNestedTokens} tokens
 * @param {TokenTypeEncoder[]} encoders
 * @param {EncodeOptions} options
 */
function tokensToEncoded (writer, tokens, encoders, options) {
  if (Array.isArray(tokens)) {
    for (const token of tokens) {
      tokensToEncoded(writer, token, encoders, options)
    }
  } else {
    encoders[tokens.type.major](writer, tokens, options)
  }
}

// CBOR major type prefixes, cached from Type for hot path performance
const MAJOR_UINT = Type.uint.majorEncoded
const MAJOR_NEGINT = Type.negint.majorEncoded
const MAJOR_BYTES = Type.bytes.majorEncoded
const MAJOR_STRING = Type.string.majorEncoded
const MAJOR_ARRAY = Type.array.majorEncoded

// Simple value bytes (CBOR major type 7 + minor value)
const SIMPLE_FALSE = Type.float.majorEncoded | MINOR_FALSE
const SIMPLE_TRUE = Type.float.majorEncoded | MINOR_TRUE
const SIMPLE_NULL = Type.float.majorEncoded | MINOR_NULL
const SIMPLE_UNDEFINED = Type.float.majorEncoded | MINOR_UNDEFINED

const neg1b = BigInt(-1)
const pos1b = BigInt(1)

/**
 * Check if direct encoding can be used for the given options.
 * Direct encoding bypasses token creation for most values.
 * @param {EncodeOptions} options
 * @returns {boolean}
 */
function canDirectEncode (options) {
  // Cannot use direct encode with addBreakTokens (needs special break token handling).
  // Direct encode checks typeEncoders per-value, falling back to tokens as needed.
  // Maps fall back to token-based encoding for efficient key sorting.
  return options.addBreakTokens !== true
}

/**
 * Direct encode a value to the writer, bypassing token creation for most types.
 * Falls back to token-based encoding for custom type encoders.
 * @param {ByteWriter} writer
 * @param {any} data
 * @param {EncodeOptions} options
 * @param {Reference|undefined} refStack
 */
function directEncode (writer, data, options, refStack) {
  const typ = is(data)

  // Check for custom encoder for THIS specific type
  const customEncoder = options.typeEncoders && options.typeEncoders[typ]
  if (customEncoder) {
    const tokens = customEncoder(data, typ, options, refStack)
    if (tokens != null) {
      // Custom encoder returned tokens, serialize immediately
      tokensToEncoded(writer, tokens, cborEncoders, options)
      return
    }
    // Custom encoder returned null, fall through to default handling
  }

  // Direct encode based on type
  switch (typ) {
    case 'null':
      writer.push([SIMPLE_NULL])
      return

    case 'undefined':
      writer.push([SIMPLE_UNDEFINED])
      return

    case 'boolean':
      writer.push([data ? SIMPLE_TRUE : SIMPLE_FALSE])
      return

    case 'number':
      if (!Number.isInteger(data) || !Number.isSafeInteger(data)) {
        // Float, use token encoder for complex float encoding
        encodeFloat(writer, new Token(Type.float, data), options)
      } else if (data >= 0) {
        encodeUintValue(writer, MAJOR_UINT, data)
      } else {
        // Negative integer
        encodeUintValue(writer, MAJOR_NEGINT, data * -1 - 1)
      }
      return

    case 'bigint':
      if (data >= BigInt(0)) {
        encodeUintValue(writer, MAJOR_UINT, data)
      } else {
        encodeUintValue(writer, MAJOR_NEGINT, data * neg1b - pos1b)
      }
      return

    case 'string': {
      const bytes = fromString(data)
      encodeUintValue(writer, MAJOR_STRING, bytes.length)
      writer.push(bytes)
      return
    }

    case 'Uint8Array':
      encodeUintValue(writer, MAJOR_BYTES, data.length)
      writer.push(data)
      return

    case 'Array':
      if (!data.length) {
        writer.push([MAJOR_ARRAY]) // Empty array: 0x80
        return
      }
      refStack = Ref.createCheck(refStack, data)
      encodeUintValue(writer, MAJOR_ARRAY, data.length)
      for (const elem of data) {
        directEncode(writer, elem, options, refStack)
      }
      return

    case 'Object':
    case 'Map':
      // Maps require key sorting, use token-based encoding for efficiency
      // (pre-encoding all keys for sorting is expensive)
      {
        const tokens = typeEncoders.Object(data, typ, options, refStack)
        tokensToEncoded(writer, tokens, cborEncoders, options)
      }
      return

    default:
    // Fall back to token-based encoding for other types (DataView, TypedArrays, etc.)
    {
      const typeEncoder = typeEncoders[typ]
      if (!typeEncoder) {
        throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`)
      }
      const tokens = typeEncoder(data, typ, options, refStack)
      tokensToEncoded(writer, tokens, cborEncoders, options)
    }
  }
}

/**
 * @param {any} data
 * @param {TokenTypeEncoder[]} encoders
 * @param {EncodeOptions} options
 * @param {Uint8Array} [destination]
 * @returns {Uint8Array}
 */
function encodeCustom (data, encoders, options, destination) {
  // arg ordering is different to encodeInto for backward compatibility
  const hasDest = destination instanceof Uint8Array
  let writeTo = hasDest ? new U8Bl(destination) : defaultWriter

  const tokens = objectToTokens(data, options)
  if (!Array.isArray(tokens) && options.quickEncodeToken) {
    const quickBytes = options.quickEncodeToken(tokens)
    if (quickBytes) {
      if (hasDest) {
        // Copy quick bytes into destination buffer
        writeTo.push(quickBytes)
        return writeTo.toBytes()
      }
      return quickBytes
    }
    const encoder = encoders[tokens.type.major]
    if (encoder.encodedSize) {
      const size = encoder.encodedSize(tokens, options)
      if (!hasDest) {
        writeTo = new Bl(size)
      }
      encoder(writeTo, tokens, options)
      // this would be a problem with encodedSize() functions
      if (writeTo.chunks.length !== 1) {
        throw new Error(`Unexpected error: pre-calculated length for ${tokens} was wrong`)
      }
      return hasDest ? writeTo.toBytes() : asU8A(writeTo.chunks[0])
    }
  }
  writeTo.reset()
  tokensToEncoded(writeTo, tokens, encoders, options)
  return writeTo.toBytes(true)
}

/**
 * @param {any} data
 * @param {EncodeOptions} [options]
 * @returns {Uint8Array}
 */
function encode (data, options) {
  options = Object.assign({}, defaultEncodeOptions, options)

  // Use direct encode path when possible
  if (canDirectEncode(options)) {
    defaultWriter.reset()
    directEncode(defaultWriter, data, options, undefined)
    return defaultWriter.toBytes(true)
  }

  return encodeCustom(data, cborEncoders, options)
}

/**
 * @param {any} data
 * @param {Uint8Array} destination
 * @param {EncodeOptions} [options]
 * @returns {{ written: number }}
 */
function encodeInto (data, destination, options) {
  options = Object.assign({}, defaultEncodeOptions, options)

  // Use direct encode path when possible
  if (canDirectEncode(options)) {
    const writer = new U8Bl(destination)
    directEncode(writer, data, options, undefined)
    return { written: writer.toBytes().length }
  }

  const result = encodeCustom(data, cborEncoders, options, destination)
  return { written: result.length }
}

export { objectToTokens, encode, encodeCustom, encodeInto, Ref }
// This is an unfortunate replacement for @sindresorhus/is that we need to
// re-implement for performance purposes. In particular the is.observable()
// check is expensive, and unnecessary for our purposes. The values returned
// are compatible with @sindresorhus/is, however.

// Types that reach getObjectType() - excludes types with fast-paths above:
// primitives (typeof), Array (isArray), Uint8Array (instanceof), plain Object (constructor)
const objectTypeNames = [
  'Object', // for Object.create(null) and other non-plain objects
  'RegExp',
  'Date',
  'Error',
  'Map',
  'Set',
  'WeakMap',
  'WeakSet',
  'ArrayBuffer',
  'SharedArrayBuffer',
  'DataView',
  'Promise',
  'URL',
  'HTMLElement',
  'Int8Array',
  'Uint8ClampedArray',
  'Int16Array',
  'Uint16Array',
  'Int32Array',
  'Uint32Array',
  'Float32Array',
  'Float64Array',
  'BigInt64Array',
  'BigUint64Array',
  'Tagged'
]

/**
 * @param {any} value
 * @returns {string}
 */
export function is (value) {
  if (value === null) {
    return 'null'
  }
  if (value === undefined) {
    return 'undefined'
  }
  if (value === true || value === false) {
    return 'boolean'
  }
  const typeOf = typeof value
  if (typeOf === 'string' || typeOf === 'number' || typeOf === 'bigint' || typeOf === 'symbol') {
    return typeOf
  }
  if (typeOf === 'function') {
    return 'Function'
  }
  if (Array.isArray(value)) {
    return 'Array'
  }
  // Also catches Node.js Buffer which extends Uint8Array
  if (value instanceof Uint8Array) {
    return 'Uint8Array'
  }
  // Fast path for plain objects (most common case after primitives/arrays/bytes)
  if (value.constructor === Object) {
    return 'Object'
  }
  const objectType = getObjectType(value)
  if (objectType) {
    return objectType
  }
  return 'Object'
}

/**
 * @param {any} value
 * @returns {string|undefined}
 */
function getObjectType (value) {
  const objectTypeName = Object.prototype.toString.call(value).slice(8, -1)
  if (objectTypeNames.includes(objectTypeName)) {
    return objectTypeName
  }
  return undefined
}
import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import * as negint from './1negint.js'
import * as bytes from './2bytes.js'
import * as string from './3string.js'
import * as array from './4array.js'
import * as map from './5map.js'
import * as tag from './6tag.js'
import * as float from './7float.js'
import { decodeErrPrefix } from './common.js'
import { fromArray } from './byte-utils.js'

/**
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 */
function invalidMinor (data, pos, minor) {
  throw new Error(`${decodeErrPrefix} encountered invalid minor (${minor}) for major ${data[pos] >>> 5}`)
}

/**
 * @param {string} msg
 * @returns {()=>any}
 */
function errorer (msg) {
  return () => { throw new Error(`${decodeErrPrefix} ${msg}`) }
}

/** @type {((data:Uint8Array, pos:number, minor:number, options?:DecodeOptions) => any)[]} */
export const jump = []

// unsigned integer, 0x00..0x17 (0..23)
for (let i = 0; i <= 0x17; i++) {
  jump[i] = invalidMinor // uint.decodeUintCompact, handled by quick[]
}
jump[0x18] = uint.decodeUint8 // unsigned integer, one-byte uint8_t follows
jump[0x19] = uint.decodeUint16 // unsigned integer, two-byte uint16_t follows
jump[0x1a] = uint.decodeUint32 // unsigned integer, four-byte uint32_t follows
jump[0x1b] = uint.decodeUint64 // unsigned integer, eight-byte uint64_t follows
jump[0x1c] = invalidMinor
jump[0x1d] = invalidMinor
jump[0x1e] = invalidMinor
jump[0x1f] = invalidMinor
// negative integer, -1-0x00..-1-0x17 (-1..-24)
for (let i = 0x20; i <= 0x37; i++) {
  jump[i] = invalidMinor // negintDecode, handled by quick[]
}
jump[0x38] = negint.decodeNegint8 // negative integer, -1-n one-byte uint8_t for n follows
jump[0x39] = negint.decodeNegint16 // negative integer, -1-n two-byte uint16_t for n follows
jump[0x3a] = negint.decodeNegint32 // negative integer, -1-n four-byte uint32_t for follows
jump[0x3b] = negint.decodeNegint64 // negative integer, -1-n eight-byte uint64_t for follows
jump[0x3c] = invalidMinor
jump[0x3d] = invalidMinor
jump[0x3e] = invalidMinor
jump[0x3f] = invalidMinor
// byte string, 0x00..0x17 bytes follow
for (let i = 0x40; i <= 0x57; i++) {
  jump[i] = bytes.decodeBytesCompact
}
jump[0x58] = bytes.decodeBytes8 // byte string, one-byte uint8_t for n, and then n bytes follow
jump[0x59] = bytes.decodeBytes16 // byte string, two-byte uint16_t for n, and then n bytes follow
jump[0x5a] = bytes.decodeBytes32 // byte string, four-byte uint32_t for n, and then n bytes follow
jump[0x5b] = bytes.decodeBytes64 // byte string, eight-byte uint64_t for n, and then n bytes follow
jump[0x5c] = invalidMinor
jump[0x5d] = invalidMinor
jump[0x5e] = invalidMinor
jump[0x5f] = errorer('indefinite length bytes/strings are not supported') // byte string, byte strings follow, terminated by "break"
// UTF-8 string 0x00..0x17 bytes follow
for (let i = 0x60; i <= 0x77; i++) {
  jump[i] = string.decodeStringCompact
}
jump[0x78] = string.decodeString8 // UTF-8 string, one-byte uint8_t for n, and then n bytes follow
jump[0x79] = string.decodeString16 // UTF-8 string, two-byte uint16_t for n, and then n bytes follow
jump[0x7a] = string.decodeString32 // UTF-8 string, four-byte uint32_t for n, and then n bytes follow
jump[0x7b] = string.decodeString64 // UTF-8 string, eight-byte uint64_t for n, and then n bytes follow
jump[0x7c] = invalidMinor
jump[0x7d] = invalidMinor
jump[0x7e] = invalidMinor
jump[0x7f] = errorer('indefinite length bytes/strings are not supported') // UTF-8 strings follow, terminated by "break"
// array, 0x00..0x17 data items follow
for (let i = 0x80; i <= 0x97; i++) {
  jump[i] = array.decodeArrayCompact
}
jump[0x98] = array.decodeArray8 // array, one-byte uint8_t for n, and then n data items follow
jump[0x99] = array.decodeArray16 // array, two-byte uint16_t for n, and then n data items follow
jump[0x9a] = array.decodeArray32 // array, four-byte uint32_t for n, and then n data items follow
jump[0x9b] = array.decodeArray64 // array, eight-byte uint64_t for n, and then n data items follow
jump[0x9c] = invalidMinor
jump[0x9d] = invalidMinor
jump[0x9e] = invalidMinor
jump[0x9f] = array.decodeArrayIndefinite // array, data items follow, terminated by "break"
// map, 0x00..0x17 pairs of data items follow
for (let i = 0xa0; i <= 0xb7; i++) {
  jump[i] = map.decodeMapCompact
}
jump[0xb8] = map.decodeMap8 // map, one-byte uint8_t for n, and then n pairs of data items follow
jump[0xb9] = map.decodeMap16 // map, two-byte uint16_t for n, and then n pairs of data items follow
jump[0xba] = map.decodeMap32 // map, four-byte uint32_t for n, and then n pairs of data items follow
jump[0xbb] = map.decodeMap64 // map, eight-byte uint64_t for n, and then n pairs of data items follow
jump[0xbc] = invalidMinor
jump[0xbd] = invalidMinor
jump[0xbe] = invalidMinor
jump[0xbf] = map.decodeMapIndefinite // map, pairs of data items follow, terminated by "break"
// tags
for (let i = 0xc0; i <= 0xd7; i++) {
  jump[i] = tag.decodeTagCompact
}
jump[0xd8] = tag.decodeTag8
jump[0xd9] = tag.decodeTag16
jump[0xda] = tag.decodeTag32
jump[0xdb] = tag.decodeTag64
jump[0xdc] = invalidMinor
jump[0xdd] = invalidMinor
jump[0xde] = invalidMinor
jump[0xdf] = invalidMinor
// 0xe0..0xf3 simple values, unsupported
for (let i = 0xe0; i <= 0xf3; i++) {
  jump[i] = errorer('simple values are not supported')
}
jump[0xf4] = invalidMinor // false, handled by quick[]
jump[0xf5] = invalidMinor // true, handled by quick[]
jump[0xf6] = invalidMinor // null, handled by quick[]
jump[0xf7] = float.decodeUndefined // undefined
jump[0xf8] = errorer('simple values are not supported') // simple value, one byte follows, unsupported
jump[0xf9] = float.decodeFloat16 // half-precision float (two-byte IEEE 754)
jump[0xfa] = float.decodeFloat32 // single-precision float (four-byte IEEE 754)
jump[0xfb] = float.decodeFloat64 // double-precision float (eight-byte IEEE 754)
jump[0xfc] = invalidMinor
jump[0xfd] = invalidMinor
jump[0xfe] = invalidMinor
jump[0xff] = float.decodeBreak // "break" stop code

/** @type {Token[]} */
export const quick = []
// ints <24
for (let i = 0; i < 24; i++) {
  quick[i] = new Token(Type.uint, i, 1)
}
// negints >= -24
for (let i = -1; i >= -24; i--) {
  quick[31 - i] = new Token(Type.negint, i, 1)
}
// empty bytes
quick[0x40] = new Token(Type.bytes, new Uint8Array(0), 1)
// empty string
quick[0x60] = new Token(Type.string, '', 1)
// empty list
quick[0x80] = new Token(Type.array, 0, 1)
// empty map
quick[0xa0] = new Token(Type.map, 0, 1)
// false
quick[0xf4] = new Token(Type.false, false, 1)
// true
quick[0xf5] = new Token(Type.true, true, 1)
// null
quick[0xf6] = new Token(Type.null, null, 1)

/**
 * @param {Token} token
 * @returns {Uint8Array|undefined}
 */
export function quickEncodeToken (token) {
  switch (token.type) {
    case Type.false:
      return fromArray([0xf4])
    case Type.true:
      return fromArray([0xf5])
    case Type.null:
      return fromArray([0xf6])
    case Type.bytes:
      if (!token.value.length) {
        return fromArray([0x40])
      }
      return
    case Type.string:
      if (token.value === '') {
        return fromArray([0x60])
      }
      return
    case Type.array:
      if (token.value === 0) {
        return fromArray([0x80])
      }
      // shouldn't be possible if this were called when there was only one token
      return
    case Type.map:
      if (token.value === 0) {
        return fromArray([0xa0])
      }
      // shouldn't be possible if this were called when there was only one token
      return
    case Type.uint:
      if (token.value < 24) {
        return fromArray([Number(token.value)])
      }
      return
    case Type.negint:
      if (token.value >= -24) {
        return fromArray([31 - Number(token.value)])
      }
  }
}
/**
 * @typedef {import('../interface.js').TagDecodeControl} TagDecodeControl
 * @typedef {(decode: TagDecodeControl) => Tagged} TaggedTagDecoder
 */

/**
 * A wrapper class for representing a CBOR tag with an arbitrary nested value.
 *
 * `Tagged` is a symmetric primitive: it can be passed to `encode()` to emit
 * a CBOR tag header followed by the encoded form of `value`, and it can be
 * returned from a tag decoder (via `Tagged.decoder(tag)` or `Tagged.preserve()`)
 * to round-trip a tag through decode without losing the tag number.
 *
 * Use `Tagged` for one-off tag handling where defining a dedicated
 * `typeEncoders` entry and tag decoder pair would be heavyweight, e.g. when
 * wrapping a structure in a single application-specific tag (COSE, dCBOR
 * envelopes, etc.).
 *
 * For systematic mapping of a JS type to a tag (e.g. CID -> tag 42), prefer
 * a dedicated `typeEncoders` entry instead.
 */
export class Tagged {
  /**
   * @param {number} tag - CBOR tag number, a non-negative integer
   * @param {any} value - The value to be tagged; encoded recursively
   */
  constructor (tag, value) {
    if (typeof tag !== 'number' || !Number.isInteger(tag) || tag < 0) {
      throw new TypeError('Tagged: tag must be a non-negative integer')
    }
    this.tag = tag
    this.value = value
  }

  /**
   * Build a tag decoder for use in `decode()`'s `tags` option that returns the
   * decoded content wrapped in a `Tagged` instance, preserving the tag number
   * for the caller to inspect.
   *
   * @param {number} tag - The CBOR tag number this decoder will be registered for
   * @returns {TaggedTagDecoder}
   *
   * @example
   * import { decode, Tagged } from 'cborg'
   * const value = decode(bytes, { tags: { 16: Tagged.decoder(16) } })
   * // value instanceof Tagged; value.tag === 16
   */
  static decoder (tag) {
    return (decode) => new Tagged(tag, decode())
  }

  /**
   * Build a `tags` option for `decode()` that wraps each listed tag number in
   * a `Tagged` instance, preserving those tags through decode without
   * registering a dedicated decoder per tag.
   *
   * @param {...number} tagNumbers - One or more CBOR tag numbers to preserve
   * @returns {{[tagNumber: number]: TaggedTagDecoder}}
   *
   * @example
   * import { decode, Tagged } from 'cborg'
   * const value = decode(bytes, { tags: Tagged.preserve(16, 96) })
   */
  static preserve (...tagNumbers) {
    /** @type {{[tagNumber: number]: TaggedTagDecoder}} */
    const tags = {}
    for (const tag of tagNumbers) {
      tags[tag] = Tagged.decoder(tag)
    }
    return tags
  }
}

// Symbol.toStringTag so the internal `is()` type detection returns 'Tagged'
// for instances, allowing the default Tagged typeEncoder to match.
Object.defineProperty(Tagged.prototype, Symbol.toStringTag, {
  value: 'Tagged'
})
class Type {
  /**
   * @param {number} major
   * @param {string} name
   * @param {boolean} terminal
   */
  constructor (major, name, terminal) {
    this.major = major
    this.majorEncoded = major << 5
    this.name = name
    this.terminal = terminal
  }

  toString () {
    return `Type[${this.major}].${this.name}`
  }

  /**
   * @param {Type} typ
   * @returns {number}
   */
  compare (typ) {
    return this.major < typ.major ? -1 : this.major > typ.major ? 1 : 0
  }

  /**
   * Check equality between two Type instances. Safe to use across different
   * copies of the Type class (e.g., when bundlers duplicate the module).
   * (major, name) uniquely identifies a Type; terminal is implied by these.
   * @param {Type} a
   * @param {Type} b
   * @returns {boolean}
   */
  static equals (a, b) {
    return a === b || (a.major === b.major && a.name === b.name)
  }
}

// convert to static fields when better supported
Type.uint = new Type(0, 'uint', true)
Type.negint = new Type(1, 'negint', true)
Type.bytes = new Type(2, 'bytes', true)
Type.string = new Type(3, 'string', true)
Type.array = new Type(4, 'array', false)
Type.map = new Type(5, 'map', false)
Type.tag = new Type(6, 'tag', false) // terminal?
Type.float = new Type(7, 'float', true)
Type.false = new Type(7, 'false', true)
Type.true = new Type(7, 'true', true)
Type.null = new Type(7, 'null', true)
Type.undefined = new Type(7, 'undefined', true)
Type.break = new Type(7, 'break', true)
// Type.indefiniteLength = new Type(0, 'indefiniteLength', true)

class Token {
  /**
   * @param {Type} type
   * @param {any} [value]
   * @param {number} [encodedLength]
   */
  constructor (type, value, encodedLength) {
    this.type = type
    this.value = value
    this.encodedLength = encodedLength
    /** @type {Uint8Array|undefined} */
    this.encodedBytes = undefined
    /** @type {Uint8Array|undefined} */
    this.byteValue = undefined
  }

  toString () {
    return `Token[${this.type}].${this.value}`
  }
}

export { Type, Token }
{
  "name": "cborg",
  "version": "5.1.6",
  "description": "Fast CBOR with a focus on strictness",
  "main": "cborg.js",
  "type": "module",
  "bin": {
    "cborg": "lib/bin.js"
  },
  "scripts": {
    "lint": "standard *.js lib/*.js test/*.js",
    "build": "npm run build:types",
    "build:types": "tsc --build",
    "prepublishOnly": "npm run build",
    "test:node": "mocha test/test-*.js",
    "test:node-bin": "mocha test/node-test-bin.js",
    "test:browser": "polendina --cleanup test/test-*.js",
    "test": "npm run lint && npm run build && npm run test:node && npm run test:node-bin && npm run test:browser",
    "test:ci": "npm run test"
  },
  "repository": {
    "type": "git",
    "url": "git@github.com:rvagg/cborg.git"
  },
  "keywords": [
    "cbor"
  ],
  "author": "Rod <rod@vagg.org> (http://r.va.gg/)",
  "license": "Apache-2.0",
  "devDependencies": {
    "@semantic-release/changelog": "^6.0.3",
    "@semantic-release/commit-analyzer": "^13.0.1",
    "@semantic-release/git": "^10.0.1",
    "@semantic-release/github": "^12.0.6",
    "@semantic-release/npm": "^13.1.5",
    "@semantic-release/release-notes-generator": "^14.1.0",
    "@types/chai": "^5.2.3",
    "@types/mocha": "^10.0.10",
    "@types/node": "^26.0.1",
    "chai": "^6.2.2",
    "conventional-changelog-conventionalcommits": "^10.0.0",
    "ipld-garbage": "^5.0.0",
    "mocha": "^11.7.5",
    "polendina": "^3.2.20",
    "semantic-release": "^25.0.3",
    "standard": "^17.1.2",
    "typescript": "^6.0.2"
  },
  "exports": {
    ".": {
      "import": "./cborg.js",
      "types": "./types/cborg.d.ts"
    },
    "./length": {
      "import": "./lib/length.js",
      "types": "./types/lib/length.d.ts"
    },
    "./taglib": {
      "import": "./lib/taglib.js",
      "types": "./types/lib/taglib.d.ts"
    },
    "./json": {
      "import": "./lib/json/json.js",
      "types": "./types/lib/json/json.d.ts"
    },
    "./extended": {
      "import": "./lib/extended/extended.js",
      "types": "./types/lib/extended/extended.d.ts"
    },
    "./interface": {
      "types": "./types/interface.d.ts"
    }
  },
  "types": "cborg.d.ts",
  "typesVersions": {
    "*": {
      "json": [
        "types/lib/json/json.d.ts"
      ],
      "length": [
        "types/lib/length.d.ts"
      ],
      "*": [
        "types/*"
      ],
      "types/*": [
        "types/*"
      ]
    }
  },
  "release": {
    "branches": [
      "master"
    ],
    "plugins": [
      [
        "@semantic-release/commit-analyzer",
        {
          "preset": "conventionalcommits",
          "releaseRules": [
            {
              "breaking": true,
              "release": "major"
            },
            {
              "revert": true,
              "release": "patch"
            },
            {
              "type": "feat",
              "release": "minor"
            },
            {
              "type": "fix",
              "release": "patch"
            },
            {
              "type": "chore",
              "release": "patch"
            },
            {
              "type": "docs",
              "release": "patch"
            },
            {
              "type": "test",
              "release": "patch"
            },
            {
              "scope": "no-release",
              "release": false
            }
          ]
        }
      ],
      [
        "@semantic-release/release-notes-generator",
        {
          "preset": "conventionalcommits",
          "presetConfig": {
            "types": [
              {
                "type": "feat",
                "section": "Features"
              },
              {
                "type": "fix",
                "section": "Bug Fixes"
              },
              {
                "type": "chore",
                "section": "Trivial Changes"
              },
              {
                "type": "docs",
                "section": "Trivial Changes"
              },
              {
                "type": "test",
                "section": "Tests"
              }
            ]
          }
        }
      ],
      "@semantic-release/changelog",
      "@semantic-release/npm",
      "@semantic-release/github",
      "@semantic-release/git"
    ]
  }
}
import { coerce } from '../bytes.js';
import basex from '../vendor/base-x.js';
/**
 * Class represents both BaseEncoder and MultibaseEncoder meaning it
 * can be used to encode to multibase or base encode without multibase
 * prefix.
 */
class Encoder {
    name;
    prefix;
    baseEncode;
    constructor(name, prefix, baseEncode) {
        this.name = name;
        this.prefix = prefix;
        this.baseEncode = baseEncode;
    }
    encode(bytes) {
        if (bytes instanceof Uint8Array) {
            return `${this.prefix}${this.baseEncode(bytes)}`;
        }
        else {
            throw Error('Unknown type, must be binary type');
        }
    }
}
/**
 * Class represents both BaseDecoder and MultibaseDecoder so it could be used
 * to decode multibases (with matching prefix) or just base decode strings
 * with corresponding base encoding.
 */
class Decoder {
    name;
    prefix;
    baseDecode;
    prefixCodePoint;
    constructor(name, prefix, baseDecode) {
        this.name = name;
        this.prefix = prefix;
        const prefixCodePoint = prefix.codePointAt(0);
        /* c8 ignore next 3 */
        if (prefixCodePoint === undefined) {
            throw new Error('Invalid prefix character');
        }
        this.prefixCodePoint = prefixCodePoint;
        this.baseDecode = baseDecode;
    }
    decode(text) {
        if (typeof text === 'string') {
            if (text.codePointAt(0) !== this.prefixCodePoint) {
                throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);
            }
            return this.baseDecode(text.slice(this.prefix.length));
        }
        else {
            throw Error('Can only multibase decode strings');
        }
    }
    or(decoder) {
        return or(this, decoder);
    }
}
class ComposedDecoder {
    decoders;
    constructor(decoders) {
        this.decoders = decoders;
    }
    or(decoder) {
        return or(this, decoder);
    }
    decode(input) {
        const prefix = input[0];
        const decoder = this.decoders[prefix];
        if (decoder != null) {
            return decoder.decode(input);
        }
        else {
            throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);
        }
    }
}
export function or(left, right) {
    return new ComposedDecoder({
        ...(left.decoders ?? { [left.prefix]: left }),
        ...(right.decoders ?? { [right.prefix]: right })
    });
}
export class Codec {
    name;
    prefix;
    baseEncode;
    baseDecode;
    encoder;
    decoder;
    constructor(name, prefix, baseEncode, baseDecode) {
        this.name = name;
        this.prefix = prefix;
        this.baseEncode = baseEncode;
        this.baseDecode = baseDecode;
        this.encoder = new Encoder(name, prefix, baseEncode);
        this.decoder = new Decoder(name, prefix, baseDecode);
    }
    encode(input) {
        return this.encoder.encode(input);
    }
    decode(input) {
        return this.decoder.decode(input);
    }
}
export function from({ name, prefix, encode, decode }) {
    return new Codec(name, prefix, encode, decode);
}
export function baseX({ name, prefix, alphabet }) {
    const { encode, decode } = basex(alphabet, name);
    return from({
        prefix,
        name,
        encode,
        decode: (text) => coerce(decode(text))
    });
}
function decode(string, alphabetIdx, bitsPerChar, name) {
    // Count the padding bytes:
    let end = string.length;
    while (string[end - 1] === '=') {
        --end;
    }
    // Allocate the output:
    const out = new Uint8Array((end * bitsPerChar / 8) | 0);
    // Parse the data:
    let bits = 0; // Number of bits currently in the buffer
    let buffer = 0; // Bits waiting to be written out, MSB first
    let written = 0; // Next byte to write
    for (let i = 0; i < end; ++i) {
        // Read one character from the string:
        const value = alphabetIdx[string[i]];
        if (value === undefined) {
            throw new SyntaxError(`Non-${name} character`);
        }
        // Append the bits to the buffer:
        buffer = (buffer << bitsPerChar) | value;
        bits += bitsPerChar;
        // Write out some bits if the buffer has a byte's worth:
        if (bits >= 8) {
            bits -= 8;
            out[written++] = 0xff & (buffer >> bits);
        }
    }
    // Verify that we have received just enough bits:
    if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {
        throw new SyntaxError('Unexpected end of data');
    }
    return out;
}
function encode(data, alphabet, bitsPerChar) {
    const pad = alphabet[alphabet.length - 1] === '=';
    const mask = (1 << bitsPerChar) - 1;
    let out = '';
    let bits = 0; // Number of bits currently in the buffer
    let buffer = 0; // Bits waiting to be written out, MSB first
    for (let i = 0; i < data.length; ++i) {
        // Slurp data into the buffer:
        buffer = (buffer << 8) | data[i];
        bits += 8;
        // Write out as much as we can:
        while (bits > bitsPerChar) {
            bits -= bitsPerChar;
            out += alphabet[mask & (buffer >> bits)];
        }
    }
    // Partial character:
    if (bits !== 0) {
        out += alphabet[mask & (buffer << (bitsPerChar - bits))];
    }
    // Add padding characters until we hit a byte boundary:
    if (pad) {
        while (((out.length * bitsPerChar) & 7) !== 0) {
            out += '=';
        }
    }
    return out;
}
function createAlphabetIdx(alphabet) {
    // Build the character lookup table:
    const alphabetIdx = {};
    for (let i = 0; i < alphabet.length; ++i) {
        alphabetIdx[alphabet[i]] = i;
    }
    return alphabetIdx;
}
/**
 * RFC4648 Factory
 */
export function rfc4648({ name, prefix, bitsPerChar, alphabet }) {
    const alphabetIdx = createAlphabetIdx(alphabet);
    return from({
        prefix,
        name,
        encode(input) {
            return encode(input, alphabet, bitsPerChar);
        },
        decode(input) {
            return decode(input, alphabetIdx, bitsPerChar, name);
        }
    });
}
//# sourceMappingURL=base.js.mapimport { rfc4648 } from './base.js';
export const base32 = rfc4648({
    prefix: 'b',
    name: 'base32',
    alphabet: 'abcdefghijklmnopqrstuvwxyz234567',
    bitsPerChar: 5
});
export const base32upper = rfc4648({
    prefix: 'B',
    name: 'base32upper',
    alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',
    bitsPerChar: 5
});
export const base32pad = rfc4648({
    prefix: 'c',
    name: 'base32pad',
    alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',
    bitsPerChar: 5
});
export const base32padupper = rfc4648({
    prefix: 'C',
    name: 'base32padupper',
    alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',
    bitsPerChar: 5
});
export const base32hex = rfc4648({
    prefix: 'v',
    name: 'base32hex',
    alphabet: '0123456789abcdefghijklmnopqrstuv',
    bitsPerChar: 5
});
export const base32hexupper = rfc4648({
    prefix: 'V',
    name: 'base32hexupper',
    alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',
    bitsPerChar: 5
});
export const base32hexpad = rfc4648({
    prefix: 't',
    name: 'base32hexpad',
    alphabet: '0123456789abcdefghijklmnopqrstuv=',
    bitsPerChar: 5
});
export const base32hexpadupper = rfc4648({
    prefix: 'T',
    name: 'base32hexpadupper',
    alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',
    bitsPerChar: 5
});
export const base32z = rfc4648({
    prefix: 'h',
    name: 'base32z',
    alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',
    bitsPerChar: 5
});
//# sourceMappingURL=base32.js.mapimport { baseX } from './base.js';
export const base36 = baseX({
    prefix: 'k',
    name: 'base36',
    alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'
});
export const base36upper = baseX({
    prefix: 'K',
    name: 'base36upper',
    alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
});
//# sourceMappingURL=base36.js.mapimport { baseX } from './base.js';
export const base58btc = baseX({
    name: 'base58btc',
    prefix: 'z',
    alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
});
export const base58flickr = baseX({
    name: 'base58flickr',
    prefix: 'Z',
    alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'
});
//# sourceMappingURL=base58.js.mapexport const empty = new Uint8Array(0);
export function toHex(d) {
    return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '');
}
export function fromHex(hex) {
    const hexes = hex.match(/../g);
    return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty;
}
export function equals(aa, bb) {
    if (aa === bb) {
        return true;
    }
    if (aa.byteLength !== bb.byteLength) {
        return false;
    }
    for (let ii = 0; ii < aa.byteLength; ii++) {
        if (aa[ii] !== bb[ii]) {
            return false;
        }
    }
    return true;
}
export function coerce(o) {
    if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') {
        return o;
    }
    if (o instanceof ArrayBuffer) {
        return new Uint8Array(o);
    }
    if (ArrayBuffer.isView(o)) {
        return new Uint8Array(o.buffer, o.byteOffset, o.byteLength);
    }
    throw new Error('Unknown type, must be binary type');
}
export function isBinary(o) {
    return o instanceof ArrayBuffer || ArrayBuffer.isView(o);
}
export function fromString(str) {
    return new TextEncoder().encode(str);
}
export function toString(b) {
    return new TextDecoder().decode(b);
}
//# sourceMappingURL=bytes.js.mapimport { base32 } from './bases/base32.js';
import { base36 } from './bases/base36.js';
import { base58btc } from './bases/base58.js';
import { coerce } from './bytes.js';
import * as Digest from './hashes/digest.js';
import * as varint from './varint.js';
// This way TS will also expose all the types from module
export * from './link/interface.js';
export function format(link, base) {
    const { bytes, version } = link;
    switch (version) {
        case 0:
            return toStringV0(bytes, baseCache(link), base ?? base58btc.encoder);
        default:
            return toStringV1(bytes, baseCache(link), (base ?? base32.encoder));
    }
}
export function toJSON(link) {
    return {
        '/': format(link)
    };
}
export function fromJSON(json) {
    return CID.parse(json['/']);
}
const cache = new WeakMap();
function baseCache(cid) {
    const baseCache = cache.get(cid);
    if (baseCache == null) {
        const baseCache = new Map();
        cache.set(cid, baseCache);
        return baseCache;
    }
    return baseCache;
}
export class CID {
    code;
    version;
    multihash;
    bytes;
    '/';
    /**
     * @param version - Version of the CID
     * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
     * @param multihash - (Multi)hash of the of the content.
     */
    constructor(version, code, multihash, bytes) {
        this.code = code;
        this.version = version;
        this.multihash = multihash;
        this.bytes = bytes;
        // flag to serializers that this is a CID and
        // should be treated specially
        this['/'] = bytes;
    }
    /**
     * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`
     * please either use `CID.asCID(cid)` or switch to new signalling mechanism
     *
     * @deprecated
     */
    get asCID() {
        return this;
    }
    // ArrayBufferView
    get byteOffset() {
        return this.bytes.byteOffset;
    }
    // ArrayBufferView
    get byteLength() {
        return this.bytes.byteLength;
    }
    toV0() {
        switch (this.version) {
            case 0: {
                return this;
            }
            case 1: {
                const { code, multihash } = this;
                if (code !== DAG_PB_CODE) {
                    throw new Error('Cannot convert a non dag-pb CID to CIDv0');
                }
                // sha2-256
                if (multihash.code !== SHA_256_CODE) {
                    throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0');
                }
                return (CID.createV0(multihash));
            }
            default: {
                throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);
            }
        }
    }
    toV1() {
        switch (this.version) {
            case 0: {
                const { code, digest } = this.multihash;
                const multihash = Digest.create(code, digest);
                return (CID.createV1(this.code, multihash));
            }
            case 1: {
                return this;
            }
            default: {
                throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);
            }
        }
    }
    equals(other) {
        return CID.equals(this, other);
    }
    static equals(self, other) {
        const unknown = other;
        return (unknown != null &&
            self.code === unknown.code &&
            self.version === unknown.version &&
            Digest.equals(self.multihash, unknown.multihash));
    }
    toString(base) {
        return format(this, base);
    }
    toJSON() {
        return { '/': format(this) };
    }
    link() {
        return this;
    }
    [Symbol.toStringTag] = 'CID';
    // Legacy
    [Symbol.for('nodejs.util.inspect.custom')]() {
        return `CID(${this.toString()})`;
    }
    /**
     * Takes any input `value` and returns a `CID` instance if it was
     * a `CID` otherwise returns `null`. If `value` is instanceof `CID`
     * it will return value back. If `value` is not instance of this CID
     * class, but is compatible CID it will return new instance of this
     * `CID` class. Otherwise returns null.
     *
     * This allows two different incompatible versions of CID library to
     * co-exist and interop as long as binary interface is compatible.
     */
    static asCID(input) {
        if (input == null) {
            return null;
        }
        const value = input;
        if (value instanceof CID) {
            // If value is instance of CID then we're all set.
            return value;
        }
        else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {
            // If value isn't instance of this CID class but `this.asCID === this` or
            // `value['/'] === value.bytes` is true it is CID instance coming from a
            // different implementation (diff version or duplicate). In that case we
            // rebase it to this `CID` implementation so caller is guaranteed to get
            // instance with expected API.
            const { version, code, multihash, bytes } = value;
            return new CID(version, code, multihash, bytes ?? encodeCID(version, code, multihash.bytes));
        }
        else if (value[cidSymbol] === true) {
            // If value is a CID from older implementation that used to be tagged via
            // symbol we still rebase it to the this `CID` implementation by
            // delegating that to a constructor.
            const { version, multihash, code } = value;
            const digest = Digest.decode(multihash);
            return CID.create(version, code, digest);
        }
        else {
            // Otherwise value is not a CID (or an incompatible version of it) in
            // which case we return `null`.
            return null;
        }
    }
    /**
     * @param version - Version of the CID
     * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
     * @param digest - (Multi)hash of the of the content.
     */
    static create(version, code, digest) {
        if (typeof code !== 'number') {
            throw new Error('String codecs are no longer supported');
        }
        if (!(digest.bytes instanceof Uint8Array)) {
            throw new Error('Invalid digest');
        }
        switch (version) {
            case 0: {
                if (code !== DAG_PB_CODE) {
                    throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);
                }
                else {
                    return new CID(version, code, digest, digest.bytes);
                }
            }
            case 1: {
                const bytes = encodeCID(version, code, digest.bytes);
                return new CID(version, code, digest, bytes);
            }
            default: {
                throw new Error('Invalid version');
            }
        }
    }
    /**
     * Simplified version of `create` for CIDv0.
     */
    static createV0(digest) {
        return CID.create(0, DAG_PB_CODE, digest);
    }
    /**
     * Simplified version of `create` for CIDv1.
     *
     * @param code - Content encoding format code.
     * @param digest - Multihash of the content.
     */
    static createV1(code, digest) {
        return CID.create(1, code, digest);
    }
    /**
     * Decoded a CID from its binary representation. The byte array must contain
     * only the CID with no additional bytes.
     *
     * An error will be thrown if the bytes provided do not contain a valid
     * binary representation of a CID.
     */
    static decode(bytes) {
        const [cid, remainder] = CID.decodeFirst(bytes);
        if (remainder.length !== 0) {
            throw new Error('Incorrect length');
        }
        return cid;
    }
    /**
     * Decoded a CID from its binary representation at the beginning of a byte
     * array.
     *
     * Returns an array with the first element containing the CID and the second
     * element containing the remainder of the original byte array. The remainder
     * will be a zero-length byte array if the provided bytes only contained a
     * binary CID representation.
     */
    static decodeFirst(bytes) {
        const specs = CID.inspectBytes(bytes);
        const prefixSize = specs.size - specs.multihashSize;
        const multihashBytes = coerce(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));
        if (multihashBytes.byteLength !== specs.multihashSize) {
            throw new Error('Incorrect length');
        }
        const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);
        const digest = new Digest.Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);
        const cid = specs.version === 0
            ? CID.createV0(digest)
            : CID.createV1(specs.codec, digest);
        return [cid, bytes.subarray(specs.size)];
    }
    /**
     * Inspect the initial bytes of a CID to determine its properties.
     *
     * Involves decoding up to 4 varints. Typically this will require only 4 to 6
     * bytes but for larger multicodec code values and larger multihash digest
     * lengths these varints can be quite large. It is recommended that at least
     * 10 bytes be made available in the `initialBytes` argument for a complete
     * inspection.
     */
    static inspectBytes(initialBytes) {
        let offset = 0;
        const next = () => {
            const [i, length] = varint.decode(initialBytes.subarray(offset));
            offset += length;
            return i;
        };
        let version = next();
        let codec = DAG_PB_CODE;
        if (version === 18) {
            // CIDv0
            version = 0;
            offset = 0;
        }
        else {
            codec = next();
        }
        if (version !== 0 && version !== 1) {
            throw new RangeError(`Invalid CID version ${version}`);
        }
        const prefixSize = offset;
        const multihashCode = next(); // multihash code
        const digestSize = next(); // multihash length
        const size = offset + digestSize;
        const multihashSize = size - prefixSize;
        return { version, codec, multihashCode, digestSize, multihashSize, size };
    }
    /**
     * Takes cid in a string representation and creates an instance. If `base`
     * decoder is not provided will use a default from the configuration. It will
     * throw an error if encoding of the CID is not compatible with supplied (or
     * a default decoder).
     */
    static parse(source, base) {
        const [prefix, bytes] = parseCIDtoBytes(source, base);
        const cid = CID.decode(bytes);
        if (cid.version === 0 && source[0] !== 'Q') {
            throw Error('Version 0 CID string must not include multibase prefix');
        }
        // Cache string representation to avoid computing it on `this.toString()`
        baseCache(cid).set(prefix, source);
        return cid;
    }
}
function parseCIDtoBytes(source, base) {
    switch (source[0]) {
        // CIDv0 is parsed differently
        case 'Q': {
            const decoder = base ?? base58btc;
            return [
                base58btc.prefix,
                decoder.decode(`${base58btc.prefix}${source}`)
            ];
        }
        case base58btc.prefix: {
            const decoder = base ?? base58btc;
            return [base58btc.prefix, decoder.decode(source)];
        }
        case base32.prefix: {
            const decoder = base ?? base32;
            return [base32.prefix, decoder.decode(source)];
        }
        case base36.prefix: {
            const decoder = base ?? base36;
            return [base36.prefix, decoder.decode(source)];
        }
        default: {
            if (base == null) {
                throw Error('To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided');
            }
            return [source[0], base.decode(source)];
        }
    }
}
function toStringV0(bytes, cache, base) {
    const { prefix } = base;
    if (prefix !== base58btc.prefix) {
        throw Error(`Cannot string encode V0 in ${base.name} encoding`);
    }
    const cid = cache.get(prefix);
    if (cid == null) {
        const cid = base.encode(bytes).slice(1);
        cache.set(prefix, cid);
        return cid;
    }
    else {
        return cid;
    }
}
function toStringV1(bytes, cache, base) {
    const { prefix } = base;
    const cid = cache.get(prefix);
    if (cid == null) {
        const cid = base.encode(bytes);
        cache.set(prefix, cid);
        return cid;
    }
    else {
        return cid;
    }
}
const DAG_PB_CODE = 0x70;
const SHA_256_CODE = 0x12;
function encodeCID(version, code, multihash) {
    const codeOffset = varint.encodingLength(version);
    const hashOffset = codeOffset + varint.encodingLength(code);
    const bytes = new Uint8Array(hashOffset + multihash.byteLength);
    varint.encodeTo(version, bytes, 0);
    varint.encodeTo(code, bytes, codeOffset);
    bytes.set(multihash, hashOffset);
    return bytes;
}
const cidSymbol = Symbol.for('@ipld/js-cid/CID');
//# sourceMappingURL=cid.js.mapimport { coerce } from '../bytes.js';
export const name = 'raw';
export const code = 0x55;
export function encode(node) {
    return coerce(node);
}
export function decode(data) {
    return coerce(data);
}
//# sourceMappingURL=raw.js.mapimport { coerce, equals as equalBytes } from '../bytes.js';
import * as varint from '../varint.js';
/**
 * Creates a multihash digest.
 */
export function create(code, digest) {
    const size = digest.byteLength;
    const sizeOffset = varint.encodingLength(code);
    const digestOffset = sizeOffset + varint.encodingLength(size);
    const bytes = new Uint8Array(digestOffset + size);
    varint.encodeTo(code, bytes, 0);
    varint.encodeTo(size, bytes, sizeOffset);
    bytes.set(digest, digestOffset);
    return new Digest(code, size, digest, bytes);
}
/**
 * Turns bytes representation of multihash digest into an instance.
 */
export function decode(multihash) {
    const bytes = coerce(multihash);
    const [code, sizeOffset] = varint.decode(bytes);
    const [size, digestOffset] = varint.decode(bytes.subarray(sizeOffset));
    const digest = bytes.subarray(sizeOffset + digestOffset);
    if (digest.byteLength !== size) {
        throw new Error('Incorrect length');
    }
    return new Digest(code, size, digest, bytes);
}
export function equals(a, b) {
    if (a === b) {
        return true;
    }
    else {
        const data = b;
        return (a.code === data.code &&
            a.size === data.size &&
            data.bytes instanceof Uint8Array &&
            equalBytes(a.bytes, data.bytes));
    }
}
/**
 * Represents a multihash digest which carries information about the
 * hashing algorithm and an actual hash digest.
 */
export class Digest {
    code;
    size;
    digest;
    bytes;
    /**
     * Creates a multihash digest.
     */
    constructor(code, size, digest, bytes) {
        this.code = code;
        this.size = size;
        this.digest = digest;
        this.bytes = bytes;
    }
}
/**
 * Used to check that the passed multihash has the passed code
 */
export function hasCode(digest, code) {
    return digest.code === code;
}
//# sourceMappingURL=digest.js.mapexport {};
//# sourceMappingURL=interface.js.mapimport varint from './vendor/varint.js';
export function decode(data, offset = 0) {
    const code = varint.decode(data, offset);
    return [code, varint.decode.bytes];
}
export function encodeTo(int, target, offset = 0) {
    varint.encode(int, target, offset);
    return target;
}
export function encodingLength(int) {
    return varint.encodingLength(int);
}
//# sourceMappingURL=varint.js.map/* eslint-disable */
// base-x encoding / decoding
// Copyright (c) 2018 base-x contributors
// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)
// Distributed under the MIT software license, see the accompanying
// file LICENSE or http://www.opensource.org/licenses/mit-license.php.
/**
 * @param {string} ALPHABET
 * @param {any} name
 */
function base(ALPHABET, name) {
    if (ALPHABET.length >= 255) {
        throw new TypeError('Alphabet too long');
    }
    var BASE_MAP = new Uint8Array(256);
    for (var j = 0; j < BASE_MAP.length; j++) {
        BASE_MAP[j] = 255;
    }
    for (var i = 0; i < ALPHABET.length; i++) {
        var x = ALPHABET.charAt(i);
        var xc = x.charCodeAt(0);
        if (BASE_MAP[xc] !== 255) {
            throw new TypeError(x + ' is ambiguous');
        }
        BASE_MAP[xc] = i;
    }
    var BASE = ALPHABET.length;
    var LEADER = ALPHABET.charAt(0);
    var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up
    var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up
    /**
     * @param {any[] | Iterable<number>} source
     */
    function encode(source) {
        // @ts-ignore
        if (source instanceof Uint8Array)
            ;
        else if (ArrayBuffer.isView(source)) {
            source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
        }
        else if (Array.isArray(source)) {
            source = Uint8Array.from(source);
        }
        if (!(source instanceof Uint8Array)) {
            throw new TypeError('Expected Uint8Array');
        }
        if (source.length === 0) {
            return '';
        }
        // Skip & count leading zeroes.
        var zeroes = 0;
        var length = 0;
        var pbegin = 0;
        var pend = source.length;
        while (pbegin !== pend && source[pbegin] === 0) {
            pbegin++;
            zeroes++;
        }
        // Allocate enough space in big-endian base58 representation.
        var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;
        var b58 = new Uint8Array(size);
        // Process the bytes.
        while (pbegin !== pend) {
            var carry = source[pbegin];
            // Apply "b58 = b58 * 256 + ch".
            var i = 0;
            for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {
                carry += (256 * b58[it1]) >>> 0;
                b58[it1] = (carry % BASE) >>> 0;
                carry = (carry / BASE) >>> 0;
            }
            if (carry !== 0) {
                throw new Error('Non-zero carry');
            }
            length = i;
            pbegin++;
        }
        // Skip leading zeroes in base58 result.
        var it2 = size - length;
        while (it2 !== size && b58[it2] === 0) {
            it2++;
        }
        // Translate the result into a string.
        var str = LEADER.repeat(zeroes);
        for (; it2 < size; ++it2) {
            str += ALPHABET.charAt(b58[it2]);
        }
        return str;
    }
    /**
     * @param {string | string[]} source
     */
    function decodeUnsafe(source) {
        if (typeof source !== 'string') {
            throw new TypeError('Expected String');
        }
        if (source.length === 0) {
            return new Uint8Array();
        }
        var psz = 0;
        // Skip leading spaces.
        if (source[psz] === ' ') {
            return;
        }
        // Skip and count leading '1's.
        var zeroes = 0;
        var length = 0;
        while (source[psz] === LEADER) {
            zeroes++;
            psz++;
        }
        // Allocate enough space in big-endian base256 representation.
        var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.
        var b256 = new Uint8Array(size);
        // Process the characters.
        while (source[psz]) {
            // Decode character
            var carry = BASE_MAP[source.charCodeAt(psz)];
            // Invalid character
            if (carry === 255) {
                return;
            }
            var i = 0;
            for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {
                carry += (BASE * b256[it3]) >>> 0;
                b256[it3] = (carry % 256) >>> 0;
                carry = (carry / 256) >>> 0;
            }
            if (carry !== 0) {
                throw new Error('Non-zero carry');
            }
            length = i;
            psz++;
        }
        // Skip trailing spaces.
        if (source[psz] === ' ') {
            return;
        }
        // Skip leading zeroes in b256.
        var it4 = size - length;
        while (it4 !== size && b256[it4] === 0) {
            it4++;
        }
        var vch = new Uint8Array(zeroes + (size - it4));
        var j = zeroes;
        while (it4 !== size) {
            vch[j++] = b256[it4++];
        }
        return vch;
    }
    /**
     * @param {string | string[]} string
     */
    function decode(string) {
        var buffer = decodeUnsafe(string);
        if (buffer) {
            return buffer;
        }
        throw new Error(`Non-${name} character`);
    }
    return {
        encode: encode,
        decodeUnsafe: decodeUnsafe,
        decode: decode
    };
}
var src = base;
var _brrp__multiformats_scope_baseX = src;
export default _brrp__multiformats_scope_baseX;
//# sourceMappingURL=base-x.js.map/* eslint-disable */
var encode_1 = encode;
var MSB = 0x80, REST = 0x7F, MSBALL = ~REST, INT = Math.pow(2, 31);
/**
 * @param {number} num
 * @param {number[]} out
 * @param {number} offset
 */
function encode(num, out, offset) {
    out = out || [];
    offset = offset || 0;
    var oldOffset = offset;
    while (num >= INT) {
        out[offset++] = (num & 0xFF) | MSB;
        num /= 128;
    }
    while (num & MSBALL) {
        out[offset++] = (num & 0xFF) | MSB;
        num >>>= 7;
    }
    out[offset] = num | 0;
    // @ts-ignore
    encode.bytes = offset - oldOffset + 1;
    return out;
}
var decode = read;
var MSB$1 = 0x80, REST$1 = 0x7F;
/**
 * @param {string | any[]} buf
 * @param {number} offset
 */
function read(buf, offset) {
    var res = 0, offset = offset || 0, shift = 0, counter = offset, b, l = buf.length;
    do {
        if (counter >= l) {
            // @ts-ignore
            read.bytes = 0;
            throw new RangeError('Could not decode varint');
        }
        b = buf[counter++];
        res += shift < 28
            ? (b & REST$1) << shift
            : (b & REST$1) * Math.pow(2, shift);
        shift += 7;
    } while (b >= MSB$1);
    // @ts-ignore
    read.bytes = counter - offset;
    return res;
}
var N1 = Math.pow(2, 7);
var N2 = Math.pow(2, 14);
var N3 = Math.pow(2, 21);
var N4 = Math.pow(2, 28);
var N5 = Math.pow(2, 35);
var N6 = Math.pow(2, 42);
var N7 = Math.pow(2, 49);
var N8 = Math.pow(2, 56);
var N9 = Math.pow(2, 63);
var length = function (/** @type {number} */ value) {
    return (value < N1 ? 1
        : value < N2 ? 2
            : value < N3 ? 3
                : value < N4 ? 4
                    : value < N5 ? 5
                        : value < N6 ? 6
                            : value < N7 ? 7
                                : value < N8 ? 8
                                    : value < N9 ? 9
                                        : 10);
};
var varint = {
    encode: encode_1,
    decode: decode,
    encodingLength: length
};
var _brrp_varint = varint;
export default _brrp_varint;
//# sourceMappingURL=varint.js.map{
  "name": "multiformats",
  "version": "13.4.2",
  "description": "Interface for multihash, multicodec, multibase and CID",
  "author": "Mikeal Rogers <mikeal.rogers@gmail.com> (https://www.mikealrogers.com/)",
  "license": "Apache-2.0 OR MIT",
  "homepage": "https://github.com/multiformats/js-multiformats#readme",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/multiformats/js-multiformats.git"
  },
  "bugs": {
    "url": "https://github.com/multiformats/js-multiformats/issues"
  },
  "publishConfig": {
    "access": "public",
    "provenance": true
  },
  "keywords": [
    "ipfs",
    "ipld",
    "multiformats"
  ],
  "type": "module",
  "types": "./dist/src/index.d.ts",
  "typesVersions": {
    "*": {
      "*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ],
      "src/*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ]
    }
  },
  "files": [
    "src",
    "dist",
    "!dist/test",
    "!**/*.tsbuildinfo"
  ],
  "exports": {
    ".": {
      "types": "./dist/src/index.d.ts",
      "import": "./dist/src/index.js"
    },
    "./bases/base10": {
      "types": "./dist/src/bases/base10.d.ts",
      "import": "./dist/src/bases/base10.js"
    },
    "./bases/base16": {
      "types": "./dist/src/bases/base16.d.ts",
      "import": "./dist/src/bases/base16.js"
    },
    "./bases/base2": {
      "types": "./dist/src/bases/base2.d.ts",
      "import": "./dist/src/bases/base2.js"
    },
    "./bases/base256emoji": {
      "types": "./dist/src/bases/base256emoji.d.ts",
      "import": "./dist/src/bases/base256emoji.js"
    },
    "./bases/base32": {
      "types": "./dist/src/bases/base32.d.ts",
      "import": "./dist/src/bases/base32.js"
    },
    "./bases/base36": {
      "types": "./dist/src/bases/base36.d.ts",
      "import": "./dist/src/bases/base36.js"
    },
    "./bases/base58": {
      "types": "./dist/src/bases/base58.d.ts",
      "import": "./dist/src/bases/base58.js"
    },
    "./bases/base64": {
      "types": "./dist/src/bases/base64.d.ts",
      "import": "./dist/src/bases/base64.js"
    },
    "./bases/base8": {
      "types": "./dist/src/bases/base8.d.ts",
      "import": "./dist/src/bases/base8.js"
    },
    "./bases/identity": {
      "types": "./dist/src/bases/identity.d.ts",
      "import": "./dist/src/bases/identity.js"
    },
    "./bases/interface": {
      "types": "./dist/src/bases/interface.d.ts",
      "import": "./dist/src/bases/interface.js"
    },
    "./basics": {
      "types": "./dist/src/basics.d.ts",
      "import": "./dist/src/basics.js"
    },
    "./block": {
      "types": "./dist/src/block.d.ts",
      "import": "./dist/src/block.js"
    },
    "./block/interface": {
      "types": "./dist/src/block/interface.d.ts",
      "import": "./dist/src/block/interface.js"
    },
    "./bytes": {
      "types": "./dist/src/bytes.d.ts",
      "import": "./dist/src/bytes.js"
    },
    "./cid": {
      "types": "./dist/src/cid.d.ts",
      "import": "./dist/src/cid.js"
    },
    "./codecs/interface": {
      "types": "./dist/src/codecs/interface.d.ts",
      "import": "./dist/src/codecs/interface.js"
    },
    "./codecs/json": {
      "types": "./dist/src/codecs/json.d.ts",
      "import": "./dist/src/codecs/json.js"
    },
    "./codecs/raw": {
      "types": "./dist/src/codecs/raw.d.ts",
      "import": "./dist/src/codecs/raw.js"
    },
    "./hashes/digest": {
      "types": "./dist/src/hashes/digest.d.ts",
      "import": "./dist/src/hashes/digest.js"
    },
    "./hashes/hasher": {
      "types": "./dist/src/hashes/hasher.d.ts",
      "import": "./dist/src/hashes/hasher.js"
    },
    "./hashes/identity": {
      "types": "./dist/src/hashes/identity.d.ts",
      "import": "./dist/src/hashes/identity.js"
    },
    "./hashes/interface": {
      "types": "./dist/src/hashes/interface.d.ts",
      "import": "./dist/src/hashes/interface.js"
    },
    "./hashes/sha1": {
      "types": "./dist/types/src/hashes/sha1.d.ts",
      "browser": "./dist/src/hashes/sha1-browser.js",
      "import": "./dist/src/hashes/sha1.js"
    },
    "./hashes/sha2": {
      "types": "./dist/src/hashes/sha2.d.ts",
      "browser": "./dist/src/hashes/sha2-browser.js",
      "import": "./dist/src/hashes/sha2.js"
    },
    "./interface": {
      "types": "./dist/src/interface.d.ts",
      "import": "./dist/src/interface.js"
    },
    "./link": {
      "types": "./dist/src/link.d.ts",
      "import": "./dist/src/link.js"
    },
    "./link/interface": {
      "types": "./dist/src/link/interface.d.ts",
      "import": "./dist/src/link/interface.js"
    },
    "./traversal": {
      "types": "./dist/src/traversal.d.ts",
      "import": "./dist/src/traversal.js"
    }
  },
  "eslintConfig": {
    "extends": "ipfs",
    "parserOptions": {
      "project": true,
      "sourceType": "module"
    }
  },
  "release": {
    "branches": [
      "master"
    ],
    "plugins": [
      [
        "@semantic-release/commit-analyzer",
        {
          "preset": "conventionalcommits",
          "releaseRules": [
            {
              "breaking": true,
              "release": "major"
            },
            {
              "revert": true,
              "release": "patch"
            },
            {
              "type": "feat",
              "release": "minor"
            },
            {
              "type": "fix",
              "release": "patch"
            },
            {
              "type": "docs",
              "release": "patch"
            },
            {
              "type": "test",
              "release": "patch"
            },
            {
              "type": "deps",
              "release": "patch"
            },
            {
              "scope": "no-release",
              "release": false
            }
          ]
        }
      ],
      [
        "@semantic-release/release-notes-generator",
        {
          "preset": "conventionalcommits",
          "presetConfig": {
            "types": [
              {
                "type": "feat",
                "section": "Features"
              },
              {
                "type": "fix",
                "section": "Bug Fixes"
              },
              {
                "type": "chore",
                "section": "Trivial Changes"
              },
              {
                "type": "docs",
                "section": "Documentation"
              },
              {
                "type": "deps",
                "section": "Dependencies"
              },
              {
                "type": "test",
                "section": "Tests"
              }
            ]
          }
        }
      ],
      "@semantic-release/changelog",
      "@semantic-release/npm",
      "@semantic-release/github",
      [
        "@semantic-release/git",
        {
          "assets": [
            "CHANGELOG.md",
            "package.json"
          ]
        }
      ]
    ]
  },
  "scripts": {
    "clean": "aegir clean",
    "lint": "aegir lint",
    "build": "aegir build",
    "release": "aegir release",
    "docs": "aegir docs",
    "test": "npm run lint && npm run test:node && npm run test:chrome",
    "test:node": "aegir test -t node --cov",
    "test:chrome": "aegir test -t browser --cov",
    "test:chrome-webworker": "aegir test -t webworker",
    "test:firefox": "aegir test -t browser -- --browser firefox",
    "test:firefox-webworker": "aegir test -t webworker -- --browser firefox",
    "test:electron-main": "aegir test -t electron-main"
  },
  "devDependencies": {
    "@stablelib/sha256": "^2.0.0",
    "@stablelib/sha512": "^2.0.0",
    "@types/node": "^25.0.0",
    "aegir": "^47.0.7",
    "buffer": "^6.0.3",
    "cids": "^1.1.9",
    "crypto-hash": "^4.0.0"
  },
  "aegir": {
    "test": {
      "target": [
        "node",
        "browser"
      ]
    }
  },
  "browser": {
    "./hashes/sha1": "./dist/src/hashes/sha1-browser.js",
    "./dist/src/hashes/sha1.js": "./dist/src/hashes/sha1-browser.js",
    "./hashes/sha2": "./dist/src/hashes/sha2-browser.js",
    "./dist/src/hashes/sha2.js": "./dist/src/hashes/sha2-browser.js"
  }
}
{
  "name": "atproto-repo",
  "version": "0.0.1",
  "description": "Byte-exact atproto repo layer — CAR + DAG-CBOR + CID + MST — over Hypercore-friendly primitives. Verified against real relay-accepted repos.",
  "type": "module",
  "main": "lib/repo.js",
  "scripts": {
    "test": "brittle-node test/*.test.js",
    "postinstall": "node scripts/bare-deps.mjs"
  },
  "dependencies": {
    "@ipld/car": "^5.4.0",
    "@ipld/dag-cbor": "^9.2.1",
    "@noble/curves": "^1.9.7",
    "@noble/hashes": "^1.5.0",
    "multiformats": "^13.3.0"
  },
  "devDependencies": {
    "atproto-identity": "file:../atproto-identity",
    "brittle": "^4.0.2"
  }
}
function isBuffer(value) {
  return Buffer.isBuffer(value) || value instanceof Uint8Array
}

function isEncoding(encoding) {
  return Buffer.isEncoding(encoding)
}

function alloc(size, fill, encoding) {
  return Buffer.alloc(size, fill, encoding)
}

function allocUnsafe(size) {
  return Buffer.allocUnsafe(size)
}

function allocUnsafeSlow(size) {
  return Buffer.allocUnsafeSlow(size)
}

function byteLength(string, encoding) {
  return Buffer.byteLength(string, encoding)
}

function compare(a, b) {
  return Buffer.compare(a, b)
}

function concat(buffers, totalLength) {
  return Buffer.concat(buffers, totalLength)
}

function copy(source, target, targetStart, start, end) {
  return toBuffer(source).copy(target, targetStart, start, end)
}

function equals(a, b) {
  return toBuffer(a).equals(b)
}

function fill(buffer, value, offset, end, encoding) {
  return toBuffer(buffer).fill(value, offset, end, encoding)
}

function from(value, encodingOrOffset, length) {
  return Buffer.from(value, encodingOrOffset, length)
}

function includes(buffer, value, byteOffset, encoding) {
  return toBuffer(buffer).includes(value, byteOffset, encoding)
}

function indexOf(buffer, value, byfeOffset, encoding) {
  return toBuffer(buffer).indexOf(value, byfeOffset, encoding)
}

function lastIndexOf(buffer, value, byteOffset, encoding) {
  return toBuffer(buffer).lastIndexOf(value, byteOffset, encoding)
}

function swap16(buffer) {
  return toBuffer(buffer).swap16()
}

function swap32(buffer) {
  return toBuffer(buffer).swap32()
}

function swap64(buffer) {
  return toBuffer(buffer).swap64()
}

function toBuffer(buffer) {
  if (Buffer.isBuffer(buffer)) return buffer
  return Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

function toString(buffer, encoding, start, end) {
  return toBuffer(buffer).toString(encoding, start, end)
}

function write(buffer, string, offset, length, encoding) {
  return toBuffer(buffer).write(string, offset, length, encoding)
}

function readDoubleBE(buffer, offset) {
  return toBuffer(buffer).readDoubleBE(offset)
}

function readDoubleLE(buffer, offset) {
  return toBuffer(buffer).readDoubleLE(offset)
}

function readFloatBE(buffer, offset) {
  return toBuffer(buffer).readFloatBE(offset)
}

function readFloatLE(buffer, offset) {
  return toBuffer(buffer).readFloatLE(offset)
}

function readInt32BE(buffer, offset) {
  return toBuffer(buffer).readInt32BE(offset)
}

function readInt32LE(buffer, offset) {
  return toBuffer(buffer).readInt32LE(offset)
}

function readUInt32BE(buffer, offset) {
  return toBuffer(buffer).readUInt32BE(offset)
}

function readUInt32LE(buffer, offset) {
  return toBuffer(buffer).readUInt32LE(offset)
}

function writeDoubleBE(buffer, value, offset) {
  return toBuffer(buffer).writeDoubleBE(value, offset)
}

function writeDoubleLE(buffer, value, offset) {
  return toBuffer(buffer).writeDoubleLE(value, offset)
}

function writeFloatBE(buffer, value, offset) {
  return toBuffer(buffer).writeFloatBE(value, offset)
}

function writeFloatLE(buffer, value, offset) {
  return toBuffer(buffer).writeFloatLE(value, offset)
}

function writeInt32BE(buffer, value, offset) {
  return toBuffer(buffer).writeInt32BE(value, offset)
}

function writeInt32LE(buffer, value, offset) {
  return toBuffer(buffer).writeInt32LE(value, offset)
}

function writeUInt32BE(buffer, value, offset) {
  return toBuffer(buffer).writeUInt32BE(value, offset)
}

function writeUInt32LE(buffer, value, offset) {
  return toBuffer(buffer).writeUInt32LE(value, offset)
}

module.exports = {
  isBuffer,
  isEncoding,
  alloc,
  allocUnsafe,
  allocUnsafeSlow,
  byteLength,
  compare,
  concat,
  copy,
  equals,
  fill,
  from,
  includes,
  indexOf,
  lastIndexOf,
  swap16,
  swap32,
  swap64,
  toBuffer,
  toString,
  write,
  readDoubleBE,
  readDoubleLE,
  readFloatBE,
  readFloatLE,
  readInt32BE,
  readInt32LE,
  readUInt32BE,
  readUInt32LE,
  writeDoubleBE,
  writeDoubleLE,
  writeFloatBE,
  writeFloatLE,
  writeInt32BE,
  writeInt32LE,
  writeUInt32BE,
  writeUInt32LE
}
{
  "name": "b4a",
  "version": "1.8.1",
  "description": "Bridging the gap between buffers and typed arrays",
  "exports": {
    "./package": "./package.json",
    ".": {
      "react-native": "./react-native.js",
      "browser": "./browser.js",
      "default": "./index.js"
    }
  },
  "files": [
    "browser.js",
    "index.js",
    "react-native.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:bare && npm run test:node",
    "test:bare": "brittle-bare --coverage test.mjs",
    "test:node": "brittle-node --coverage test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/b4a.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/b4a/issues"
  },
  "homepage": "https://github.com/holepunchto/b4a#readme",
  "devDependencies": {
    "brittle": "^3.5.2",
    "lunte": "^1.7.0",
    "nanobench": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "react-native-b4a": "*"
  },
  "peerDependenciesMeta": {
    "react-native-b4a": {
      "optional": true
    }
  }
}
const ESC = '\x1b'
const CSI = ESC + '['
const SGR = (n) => CSI + n + 'm'

exports.constants = {
  ESC,
  CSI,
  SGR
}

// https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_(Control_Sequence_Introducer)_sequences

exports.cursorHide = CSI + '?25l'
exports.cursorShow = CSI + '?25h'

exports.cursorUp = function cursorUp(n = 1) {
  return CSI + n + 'A'
}

exports.cursorDown = function cursorDown(n = 1) {
  return CSI + n + 'B'
}

exports.cursorForward = function cursorForward(n = 1) {
  return CSI + n + 'C'
}

exports.cursorBack = function cursorBack(n = 1) {
  return CSI + n + 'D'
}

exports.cursorNextLine = function cursorNextLine(n = 1) {
  return CSI + n + 'E'
}

exports.cursorPreviousLine = function cursorPreviousLine(n = 1) {
  return CSI + n + 'F'
}

exports.cursorPosition = function cursorPosition(column, row = 0) {
  if (row === 0) return CSI + (column + 1) + 'G'

  return CSI + (row + 1) + ';' + (column + 1) + 'H'
}

exports.eraseDisplayEnd = CSI + 'J'
exports.eraseDisplayStart = CSI + '1J'
exports.eraseDisplay = CSI + '2J'
exports.eraseLineEnd = CSI + 'K'
exports.eraseLineStart = CSI + '1K'
exports.eraseLine = CSI + '2K'

exports.scrollUp = function scrollUp(n = 1) {
  return CSI + n + 'S'
}

exports.scrollDown = function scrollDown(n = 1) {
  return CSI + n + 'T'
}

// https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_(Select_Graphic_Rendition)_parameters

exports.modifierReset = SGR(0)
exports.modifierBold = SGR(1)
exports.modifierDim = SGR(2)
exports.modifierItalic = SGR(3)
exports.modifierUnderline = SGR(4)
exports.modifierNormal = SGR(22)
exports.modifierNotItalic = SGR(23)
exports.modifierNotUnderline = SGR(24)

// https://en.wikipedia.org/wiki/ANSI_escape_code#Colors

exports.colorBlack = SGR(30)
exports.colorRed = SGR(31)
exports.colorGreen = SGR(32)
exports.colorYellow = SGR(33)
exports.colorBlue = SGR(34)
exports.colorMagenta = SGR(35)
exports.colorCyan = SGR(36)
exports.colorWhite = SGR(37)
exports.colorDefault = SGR(39)
exports.colorBrightBlack = SGR(90)
exports.colorBrightRed = SGR(91)
exports.colorBrightGreen = SGR(92)
exports.colorBrightYellow = SGR(93)
exports.colorBrightBlue = SGR(94)
exports.colorBrightMagenta = SGR(95)
exports.colorBrightCyan = SGR(96)
exports.colorBrightWhite = SGR(97)
{
  "name": "bare-ansi-escapes",
  "version": "2.2.3",
  "description": "Parse and produce ANSI escape sequences",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./key-decoder": {
      "types": "./key-decoder.d.ts",
      "default": "./key-decoder.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "key-decoder.js",
    "key-decoder.d.ts"
  ],
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-ansi-escapes.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-ansi-escapes/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-ansi-escapes#readme",
  "dependencies": {
    "bare-stream": "^2.6.5"
  },
  "devDependencies": {
    "bare-buffer": "^3.0.2",
    "brittle": "^3.3.2",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  },
  "peerDependencies": {
    "bare-buffer": "*"
  },
  "peerDependenciesMeta": {
    "bare-buffer": {
      "optional": true
    }
  }
}
const inspect = require('bare-inspect')

class AssertionError extends Error {
  constructor(opts = {}) {
    let { message = null, actual, expected, operator } = opts

    if (message === null) {
      message = `${inspect(actual)} ${operator} ${inspect(expected)}`
    }

    super(message)

    this.actual = actual
    this.expected = expected
    this.operator = operator
  }

  get name() {
    return 'AssertionError'
  }

  get code() {
    'ASSERTION'
  }
}

function assertFail(opts, fn) {
  if (opts.message instanceof Error) throw opts.message

  const err = new AssertionError(opts)

  if (Error.captureStackTrace) Error.captureStackTrace(err, fn)

  throw err
}

module.exports = exports = function assert(actual, message) {
  if (actual) return

  assertFail({ message, actual, expected: true, operator: '==' }, assert)
}

exports.AssertionError = AssertionError

exports.fail = function fail(message) {
  if (message === undefined) message = 'Failed'

  assertFail({ message, operator: 'fail' }, fail)
}

exports.ok = function ok(actual, message) {
  if (actual) return

  assertFail({ message, actual, expected: true, operator: '==' }, ok)
}

exports.notOk = function ok(actual, message) {
  if (!actual) return

  assertFail({ message, actual, expected: false, operator: '==' }, ok)
}

exports.equal = function equal(actual, expected, message) {
  if (actual == expected || (actual !== actual && expected !== expected)) {
    return
  }

  assertFail({ message, actual, expected, operator: '==' }, equal)
}

exports.notEqual = function notEqual(actual, expected, message) {
  if (actual != expected && (actual === actual || expected === expected)) {
    return
  }

  assertFail({ message, actual, expected, operator: '!=' }, notEqual)
}

exports.strictEqual = function strictEqual(actual, expected, message) {
  if (Object.is(actual, expected)) return

  assertFail(
    { message, actual, expected, operator: 'strictEqual' },
    strictEqual
  )
}

exports.notStrictEqual = function notStrictEqual(actual, expected, message) {
  if (!Object.is(actual, expected)) return

  assertFail(
    { message, actual, expected, operator: 'notStrictEqual' },
    notStrictEqual
  )
}
{
  "name": "bare-assert",
  "version": "1.2.0",
  "description": "Assertion library for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts"
  ],
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-assert.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-assert/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-assert#readme",
  "dependencies": {
    "bare-inspect": "^3.1.2"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  }
}
const errors = require('./lib/errors')

class EventListener {
  constructor() {
    this.list = []
    this.count = 0
  }

  append(ctx, name, fn, once) {
    this.count++
    ctx.emit('newListener', name, fn) // Emit BEFORE adding
    this.list.push([fn, once])
  }

  prepend(ctx, name, fn, once) {
    this.count++
    ctx.emit('newListener', name, fn) // Emit BEFORE adding
    this.list.unshift([fn, once])
  }

  remove(ctx, name, fn) {
    for (let i = 0, n = this.list.length; i < n; i++) {
      const l = this.list[i]

      if (l[0] === fn) {
        this.list.splice(i, 1)

        if (this.count === 1) delete ctx._events[name]

        ctx.emit('removeListener', name, fn) // Emit AFTER removing

        this.count--
        return
      }
    }
  }

  removeAll(ctx, name) {
    const list = [...this.list]
    this.list = []

    if (this.count === list.length) delete ctx._events[name]

    for (let i = list.length - 1; i >= 0; i--) {
      ctx.emit('removeListener', name, list[i][0]) // Emit AFTER removing
    }

    this.count -= list.length
  }

  emit(ctx, name, ...args) {
    const list = [...this.list]

    for (let i = 0, n = list.length; i < n; i++) {
      const l = list[i]

      if (l[1] === true) this.remove(ctx, name, l[0])

      Reflect.apply(l[0], ctx, args)
    }

    return list.length > 0
  }
}

function appendListener(ctx, name, fn, once) {
  if (ctx._events === undefined) ctx._events = Object.create(null)
  const e = ctx._events[name] || (ctx._events[name] = new EventListener())
  e.append(ctx, name, fn, once)
  return ctx
}

function prependListener(ctx, name, fn, once) {
  if (ctx._events === undefined) ctx._events = Object.create(null)
  const e = ctx._events[name] || (ctx._events[name] = new EventListener())
  e.prepend(ctx, name, fn, once)
  return ctx
}

function removeListener(ctx, name, fn) {
  if (ctx._events === undefined) return ctx
  const e = ctx._events[name]
  if (e !== undefined) e.remove(ctx, name, fn)
  return ctx
}

function throwUnhandledError(...args) {
  let err

  if (args.length > 0) err = args[0]

  if (err instanceof Error === false) err = errors.UNHANDLED_ERROR(err)

  if (Error.captureStackTrace) {
    Error.captureStackTrace(err, exports.prototype.emit)
  }

  queueMicrotask(() => {
    throw err
  })
}

module.exports = exports = class EventEmitter {
  constructor() {
    this._events = Object.create(null)
  }

  addListener(name, fn) {
    return appendListener(this, name, fn, false)
  }

  addOnceListener(name, fn) {
    return appendListener(this, name, fn, true)
  }

  prependListener(name, fn) {
    return prependListener(this, name, fn, false)
  }

  prependOnceListener(name, fn) {
    return prependListener(this, name, fn, true)
  }

  removeListener(name, fn) {
    return removeListener(this, name, fn)
  }

  on(name, fn) {
    return appendListener(this, name, fn, false)
  }

  once(name, fn) {
    return appendListener(this, name, fn, true)
  }

  off(name, fn) {
    return removeListener(this, name, fn)
  }

  emit(name, ...args) {
    if (name === 'error' && this._events !== undefined && this._events.error === undefined) {
      throwUnhandledError(...args)
    }

    if (this._events === undefined) return false
    const e = this._events[name]
    return e === undefined ? false : e.emit(this, name, ...args)
  }

  listeners(name) {
    if (this._events === undefined) return []
    const e = this._events[name]
    return e === undefined ? [] : [...e.list]
  }

  rawListeners(name) {
    if (this._events === undefined) return []
    const e = this._events[name]
    return e === undefined ? [] : e.list.map((l) => l[0])
  }

  eventNames() {
    if (this._events === undefined) return []
    return Reflect.ownKeys(this._events)
  }

  listenerCount(name) {
    if (this._events === undefined) return 0
    const e = this._events[name]
    return e === undefined ? 0 : e.list.length
  }

  getMaxListeners() {
    return EventEmitter.defaultMaxListeners
  }

  setMaxListeners(n) {}

  removeAllListeners(name) {
    if (arguments.length === 0) {
      for (const key of Reflect.ownKeys(this._events)) {
        if (key === 'removeListener') continue
        this.removeAllListeners(key)
      }
      this.removeAllListeners('removeListener')
    } else {
      const e = this._events[name]
      if (e !== undefined) e.removeAll(this, name)
    }
    return this
  }
}

exports.EventEmitter = exports

exports.errors = errors

exports.defaultMaxListeners = 10

exports.on = function on(emitter, name, opts = {}) {
  const { signal } = opts

  if (signal && signal.aborted) {
    throw errors.OPERATION_ABORTED(signal.reason)
  }

  let error = null
  let done = false

  const events = []
  const promises = []

  if (name !== 'error') emitter.on('error', onerror)

  if (signal) signal.addEventListener('abort', onabort)

  emitter.on(name, onevent)

  return {
    next() {
      if (events.length) {
        return Promise.resolve({ value: events.shift(), done: false })
      }

      if (error) {
        const err = error

        error = null

        return Promise.reject(err)
      }

      if (done) return onclose()

      return new Promise((resolve, reject) => promises.push({ resolve, reject }))
    },

    return() {
      return onclose()
    },

    throw(err) {
      return onerror(err)
    },

    [Symbol.asyncIterator]() {
      return this
    }
  }

  function onevent(...args) {
    if (promises.length) {
      promises.shift().resolve({ value: args, done: false })
    } else {
      events.push(args)
    }
  }

  function onerror(err) {
    emitter.off(name, onevent).off('error', onerror)

    if (promises.length) {
      promises.shift().reject(err)
    } else {
      error = err
    }

    return Promise.resolve({ done: true })
  }

  function onabort() {
    signal.removeEventListener('abort', onabort)

    onerror(errors.OPERATION_ABORTED(signal.reason))
  }

  function onclose() {
    emitter.off(name, onevent)

    if (name !== 'error') emitter.off('error', onerror)

    if (signal) signal.removeEventListener('abort', onabort)

    done = true

    if (promises.length) promises.shift().resolve({ done: true })

    return Promise.resolve({ done: true })
  }
}

exports.once = function once(emitter, name, opts = {}) {
  const { signal } = opts

  if (signal && signal.aborted) {
    return Promise.reject(errors.OPERATION_ABORTED(signal.reason))
  }

  return new Promise((resolve, reject) => {
    if (name !== 'error') emitter.on('error', onerror)

    if (signal) signal.addEventListener('abort', onabort)

    emitter.once(name, onevent)

    function onevent(...args) {
      if (name !== 'error') emitter.off('error', onerror)

      if (signal) signal.removeEventListener('abort', onabort)

      resolve(args)
    }

    function onerror(err) {
      emitter.off(name, onevent)

      if (name !== 'error') emitter.off('error', onerror)

      reject(err)
    }

    function onabort() {
      signal.removeEventListener('abort', onabort)

      onerror(errors.OPERATION_ABORTED(signal.reason))
    }
  })
}

exports.forward = function forward(from, to, names, opts = {}) {
  if (typeof names === 'string') names = [names]

  const { emit = to.emit.bind(to) } = opts

  const listeners = names.map(
    (name) =>
      function onevent(...args) {
        emit(name, ...args)
      }
  )

  to.on('newListener', (name) => {
    const i = names.indexOf(name)

    if (i !== -1 && to.listenerCount(name) === 0) {
      from.on(name, listeners[i])
    }
  }).on('removeListener', (name) => {
    const i = names.indexOf(name)

    if (i !== -1 && to.listenerCount(name) === 0) {
      from.off(name, listeners[i])
    }
  })
}

exports.listenerCount = function listenerCount(emitter, name) {
  return emitter.listenerCount(name)
}

exports.getMaxListeners = function getMaxListeners(emitter) {
  if (typeof emitter.getMaxListeners === 'function') {
    return emitter.getMaxListeners()
  }

  return exports.defaultMaxListeners
}

exports.setMaxListeners = function setMaxListeners(n, ...emitters) {
  if (emitters.length === 0) exports.defaultMaxListeners = n
  else {
    for (const emitter of emitters) {
      if (typeof emitter.setMaxListeners === 'function') {
        emitter.setMaxListeners(n)
      }
    }
  }
}
module.exports = class EventEmitterError extends Error {
  constructor(msg, code, fn = EventEmitterError, opts) {
    super(`${code}: ${msg}`, opts)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'EventEmitterError'
  }

  static OPERATION_ABORTED(cause, msg = 'Operation aborted') {
    return new EventEmitterError(msg, 'OPERATION_ABORTED', EventEmitterError.OPERATION_ABORTED, {
      cause
    })
  }

  static UNHANDLED_ERROR(cause, msg = 'Unhandled error') {
    return new EventEmitterError(msg, 'UNHANDLED_ERROR', EventEmitterError.UNHANDLED_ERROR, {
      cause
    })
  }
}
{
  "name": "bare-events",
  "version": "2.9.1",
  "description": "Event emitters for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    },
    "./web": {
      "types": "./web.d.ts",
      "default": "./web.js"
    },
    "./errors": "./lib/errors.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "global.js",
    "global.d.ts",
    "web.js",
    "web.d.ts",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:bare && npm run test:node",
    "test:bare": "brittle-bare --coverage test.js",
    "test:node": "brittle-node --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-events.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-events/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-events#readme",
  "devDependencies": {
    "bare-abort-controller": "^1.0.0",
    "brittle": "^3.3.2",
    "lunte": "^1.8.0",
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^2.0.0",
    "uncaughts": "^1.1.1"
  },
  "peerDependencies": {
    "bare-abort-controller": "*"
  },
  "peerDependenciesMeta": {
    "bare-abort-controller": {
      "optional": true
    }
  }
}
module.exports = require.addon()
const FIFO = require('fast-fifo')
const EventEmitter = require('bare-events')
const path = require('bare-path')
const { isURL, fileURLToPath } = require('bare-url')
const { Readable, Writable } = require('bare-stream')
const binding = require('./binding')
const constants = require('./lib/constants')
const FileError = require('./lib/errors')

const isWindows = Bare.platform === 'win32'

exports.constants = constants

class FileRequest {
  static borrow() {
    if (this._free.length > 0) return this._free.pop()
    return new FileRequest()
  }

  static return(req) {
    if (this._free.length < 32) this._free.push(req.reset())
    else req.destroy()
  }

  constructor() {
    this._reset()
    this._handle = binding.requestInit(this, this._onresult)
  }

  get handle() {
    return this._handle
  }

  retain(value) {
    this._retain = value // Tie the lifetime of `value` to the lifetime of `this`
  }

  reset() {
    if (this._handle === null) return this

    binding.requestReset(this._handle)

    this._reset()

    return this
  }

  destroy() {
    if (this._handle === null) return this

    binding.requestDestroy(this._handle)

    this._reset()
    this._handle = null

    return this
  }

  then(resolve, reject) {
    return this._promise.then(resolve, reject)
  }

  return() {
    if (this._handle === null) return this

    FileRequest.return(this)

    return this
  }

  _reset() {
    this._promise = new Promise((resolve, reject) => {
      this._resolve = resolve
      this._reject = reject
    })
    this._retain = null
  }

  _onresult(err, status) {
    if (err) this._reject(err)
    else this._resolve(status)
  }
}

FileRequest._free = []

function ok(result, cb) {
  if (typeof result === 'function') {
    cb = result
    result = undefined
  }

  if (cb) cb(null, result)
  else return result
}

function fail(err, cb) {
  if (cb) cb(err)
  else throw err
}

function done(err, result, cb) {
  if (typeof result === 'function') {
    cb = result
    result = undefined
  }

  if (err) fail(err, cb)
  else return ok(result, cb)
}

async function open(filepath, flags = 'r', mode = 0o666, cb) {
  if (typeof flags === 'function') {
    cb = flags
    flags = 'r'
    mode = 0o666
  } else if (typeof mode === 'function') {
    cb = mode
    mode = 0o666
  }

  if (typeof flags === 'string') flags = toFlags(flags)
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let fd
  let err = null
  try {
    binding.open(req.handle, filepath, flags, mode)

    fd = await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'open',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, fd, cb)
}

function openSync(filepath, flags = 'r', mode = 0o666) {
  if (typeof flags === 'string') flags = toFlags(flags)
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    return binding.openSync(req.handle, filepath, flags, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'open',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function close(fd, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.close(req.handle, fd)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'close', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function closeSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.closeSync(req.handle, fd)
  } catch (e) {
    throw new FileError(e.message, { operation: 'close', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function access(filepath, mode = constants.F_OK, cb) {
  if (typeof mode === 'function') {
    cb = mode
    mode = constants.F_OK
  }

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.access(req.handle, filepath, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'access',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function accessSync(filepath, mode = constants.F_OK) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.accessSync(req.handle, filepath, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'access',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function exists(filepath, cb) {
  let ok = true
  try {
    await access(filepath)
  } catch {
    ok = false
  }

  return done(null, ok, cb)
}

function existsSync(filepath) {
  try {
    accessSync(filepath)
  } catch {
    return false
  }

  return true
}

async function read(fd, buffer, offset = 0, len = buffer.byteLength - offset, pos = -1, cb) {
  if (typeof offset === 'function') {
    cb = offset
    offset = 0
    len = buffer.byteLength
    pos = -1
  } else if (typeof len === 'function') {
    cb = len
    len = buffer.byteLength - offset
    pos = -1
  } else if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.read(req.handle, fd, buffer, offset, len, pos)

    req.retain(buffer)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'read', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function readSync(fd, buffer, offset = 0, len = buffer.byteLength - offset, pos = -1) {
  const req = FileRequest.borrow()

  try {
    return binding.readSync(req.handle, fd, buffer, offset, len, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'read', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function readv(fd, buffers, pos = -1, cb) {
  if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.readv(req.handle, fd, buffers, pos)

    req.retain(buffers)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'readv', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function readvSync(fd, buffers, pos = -1) {
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  try {
    return binding.readvSync(req.handle, fd, buffers, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'readv', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function write(fd, data, offset, len, pos = -1, cb) {
  if (typeof data === 'string') {
    let encoding = len
    cb = pos
    pos = offset

    if (typeof pos === 'function') {
      cb = pos
      pos = -1
      encoding = 'utf8'
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = 'utf8'
    }

    if (typeof pos === 'string') {
      encoding = pos
      pos = -1
    }

    data = Buffer.from(data, encoding)
    offset = 0
    len = data.byteLength
  } else if (typeof offset === 'function') {
    cb = offset
    offset = 0
    len = data.byteLength
    pos = -1
  } else if (typeof len === 'function') {
    cb = len
    len = data.byteLength - offset
    pos = -1
  } else if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof offset !== 'number') offset = 0
  if (typeof len !== 'number') len = data.byteLength - offset
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.write(req.handle, fd, data, offset, len, pos)

    req.retain(data)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'write', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function writeSync(fd, data, offset, len, pos = -1) {
  if (typeof data === 'string') {
    let encoding = len
    pos = offset

    if (typeof pos === 'string') {
      encoding = pos
      pos = -1
    }

    data = Buffer.from(data, encoding)
    offset = 0
    len = data.byteLength
  }

  if (typeof offset !== 'number') offset = 0
  if (typeof len !== 'number') len = data.byteLength - offset
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  try {
    return binding.writeSync(req.handle, fd, data, offset, len, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'write', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function writev(fd, buffers, pos = -1, cb) {
  if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.writev(req.handle, fd, buffers, pos)

    req.retain(buffers)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'writev', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function writevSync(fd, buffers, pos = -1) {
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  try {
    return binding.writevSync(req.handle, fd, buffers, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'writev', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function stat(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.stat(req.handle, filepath)

    await req

    st = new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'stat', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function statSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.statSync(req.handle, filepath)

    return new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'stat', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function lstat(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.lstat(req.handle, filepath)

    await req

    st = new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'lstat', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function lstatSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.lstatSync(req.handle, filepath)

    return new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'lstat', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function fstat(fd, cb) {
  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.fstat(req.handle, fd)

    await req

    st = new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'fstat', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function fstatSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.fstatSync(req.handle, fd)

    return new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'fstat', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function statfs(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.statfs(req.handle, filepath)

    await req

    st = new StatFs(...binding.requestResultStatfs(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'statfs', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function statfsSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.statfsSync(req.handle, filepath)

    return new StatFs(...binding.requestResultStatfs(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'statfs', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function ftruncate(fd, len = 0, cb) {
  if (typeof len === 'function') {
    cb = len
    len = 0
  }

  if (typeof len !== 'number') len = 0

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.ftruncate(req.handle, fd, len)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'ftruncate', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function ftruncateSync(fd, len = 0) {
  if (typeof len !== 'number') len = 0

  const req = FileRequest.borrow()

  try {
    binding.ftruncateSync(req.handle, fd, len)
  } catch (e) {
    throw new FileError(e.message, { operation: 'ftruncate', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function truncate(filepath, len, cb) {
  let fd = -1
  let err

  try {
    fd = await open(filepath, 'r+')

    await ftruncate(fd, len)
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) await close(fd)
  }

  return done(err, cb)
}

function truncateSync(filepath, len) {
  let fd = -1
  let err

  try {
    fd = openSync(filepath, 'r+')

    ftruncateSync(fd, len)
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) closeSync(fd)
  }
}

async function chmod(filepath, mode, cb) {
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.chmod(req.handle, filepath, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'chmod',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function chmodSync(filepath, mode) {
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.chmodSync(req.handle, filepath, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'chmod',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function fchmod(fd, mode, cb) {
  if (typeof mode === 'string') mode = toMode(mode)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fchmod(req.handle, fd, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fchmod', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fchmodSync(fd, mode) {
  if (typeof mode === 'string') mode = toMode(mode)

  const req = FileRequest.borrow()

  try {
    binding.fchmodSync(req.handle, fd, mode)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fchmod', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function chown(filepath, uid, gid, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.chown(req.handle, filepath, uid, gid)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'chown', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function chownSync(filepath, uid, gid) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.chownSync(req.handle, filepath, uid, gid)
  } catch (e) {
    throw new FileError(e.message, { operation: 'chownSync', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function lchown(filepath, uid, gid, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.lchown(req.handle, filepath, uid, gid)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'lchown', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function lchownSync(filepath, uid, gid) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.lchownSync(req.handle, filepath, uid, gid)
  } catch (e) {
    throw new FileError(e.message, { operation: 'lchownSync', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function fchown(fd, uid, gid, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fchown(req.handle, fd, uid, gid)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fchown', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fchownSync(fd, uid, gid) {
  const req = FileRequest.borrow()

  try {
    binding.fchownSync(req.handle, fd, uid, gid)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fchownSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function utimes(filepath, atime, mtime, cb) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.utimes(req.handle, filepath, atime, mtime)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'utimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function utimesSync(filepath, atime, mtime) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.utimesSync(req.handle, filepath, atime, mtime)
  } catch (e) {
    throw new FileError(e.message, { operation: 'utimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function lutimes(filepath, atime, mtime, cb) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.lutimes(req.handle, filepath, atime, mtime)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'lutimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function lutimesSync(filepath, atime, mtime) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.lutimesSync(req.handle, filepath, atime, mtime)
  } catch (e) {
    throw new FileError(e.message, { operation: 'lutimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function futimes(fd, atime, mtime, cb) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.futimes(req.handle, fd, atime, mtime)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'futimes', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function futimesSync(fd, atime, mtime) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  const req = FileRequest.borrow()

  try {
    binding.futimesSync(req.handle, fd, atime, mtime)
  } catch (e) {
    throw new FileError(e.message, { operation: 'futimesSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function link(src, dst, cb) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.link(req.handle, src, dst)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'link', code: e.code, path: src, destination: dst })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function linkSync(src, dst) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  try {
    binding.linkSync(req.handle, src, dst)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'linkSync',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }
}

async function mkdir(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = { mode: 0o777 }
  }

  if (typeof opts === 'number') opts = { mode: opts }
  else if (!opts) opts = {}

  const mode = typeof opts.mode === 'number' ? opts.mode : 0o777

  filepath = toNamespacedPath(filepath)

  if (opts.recursive) {
    let err = null
    try {
      try {
        await mkdir(filepath, { mode })
      } catch (err) {
        if (err.code !== 'ENOENT') {
          if (!(await stat(filepath)).isDirectory()) throw err
        } else {
          while (filepath.endsWith(path.sep)) filepath = filepath.slice(0, -1)
          const i = filepath.lastIndexOf(path.sep)
          if (i <= 0) throw err

          await mkdir(filepath.slice(0, i), { mode, recursive: true })

          try {
            await mkdir(filepath, { mode })
          } catch (err) {
            if (!(await stat(filepath)).isDirectory()) throw err
          }
        }
      }
    } catch (e) {
      err = e
    }

    return done(err, cb)
  }

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.mkdir(req.handle, filepath, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'mkdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function mkdirSync(filepath, opts) {
  if (typeof opts === 'number') opts = { mode: opts }
  else if (!opts) opts = {}

  const mode = typeof opts.mode === 'number' ? opts.mode : 0o777

  filepath = toNamespacedPath(filepath)

  if (opts.recursive) {
    try {
      mkdirSync(filepath, { mode })
    } catch (err) {
      if (err.code !== 'ENOENT') {
        if (!statSync(filepath).isDirectory()) throw err
      } else {
        while (filepath.endsWith(path.sep)) filepath = filepath.slice(0, -1)
        const i = filepath.lastIndexOf(path.sep)
        if (i <= 0) throw err

        mkdirSync(filepath.slice(0, i), { mode, recursive: true })

        try {
          mkdirSync(filepath, { mode })
        } catch (err) {
          if (!statSync(filepath).isDirectory()) throw err
        }
      }
    }

    return
  }

  const req = FileRequest.borrow()

  try {
    binding.mkdirSync(req.handle, filepath, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'mkdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function mkdtemp(prefix, cb) {
  prefix = toNamespacedPath(prefix)

  const req = FileRequest.borrow()

  let res
  let err = null
  try {
    binding.mkdtemp(req.handle, prefix + 'XXXXXX')

    await req

    res = binding.requestResultPath(req.handle)
  } catch (e) {
    err = new FileError(e.message, { operation: 'mkdtemp', code: e.code, path: prefix })
  } finally {
    req.return()
  }

  return done(err, res, cb)
}

function mkdtempSync(prefix) {
  prefix = toNamespacedPath(prefix)

  const req = FileRequest.borrow()

  try {
    binding.mkdtempSync(req.handle, prefix + 'XXXXXX')

    return binding.requestResultPath(req.handle)
  } catch (e) {
    throw new FileError(e.message, { operation: 'mkdtempSync', code: e.code, path: prefix })
  } finally {
    req.return()
  }
}

async function rmdir(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.rmdir(req.handle, filepath)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'rmdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function rmdirSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.rmdirSync(req.handle, filepath)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'rmdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function rm(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  let err = null
  try {
    const st = await lstat(filepath)

    if (st.isDirectory()) {
      if (opts.recursive) {
        try {
          await rmdir(filepath)
        } catch (err) {
          if (err.code !== 'ENOTEMPTY') throw err

          const files = await readdir(filepath)

          for (const file of files) {
            await rm(filepath + path.sep + file, opts)
          }

          await rmdir(filepath)
        }
      } else {
        throw new FileError('is a directory', {
          operation: 'rm',
          code: 'EISDIR',
          path: filepath
        })
      }
    } else {
      await unlink(filepath)
    }
  } catch (e) {
    if (e.code !== 'ENOENT' || !opts.force) err = e
  }

  return done(err, cb)
}

function rmSync(filepath, opts) {
  if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  try {
    const st = lstatSync(filepath)

    if (st.isDirectory()) {
      if (opts.recursive) {
        try {
          rmdirSync(filepath)
        } catch (err) {
          if (err.code !== 'ENOTEMPTY') throw err

          const files = readdirSync(filepath)

          for (const file of files) {
            rmSync(filepath + path.sep + file, opts)
          }

          rmdirSync(filepath)
        }
      } else {
        throw new FileError('is a directory', {
          operation: 'rm',
          code: 'EISDIR',
          path: filepath
        })
      }
    } else {
      unlinkSync(filepath)
    }
  } catch (err) {
    if (err.code !== 'ENOENT' || !opts.force) throw err
  }
}

async function unlink(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.unlink(req.handle, filepath)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'unlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function unlinkSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.unlinkSync(req.handle, filepath)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'unlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function rename(src, dst, cb) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.rename(req.handle, src, dst)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'rename',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function renameSync(src, dst) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  try {
    binding.renameSync(req.handle, src, dst)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'rename',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }
}

async function copyFile(src, dst, mode = 0, cb) {
  if (typeof mode === 'function') {
    cb = mode
    mode = 0
  }

  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.copyfile(req.handle, src, dst, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'copyfile',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function copyFileSync(src, dst, mode = 0) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  try {
    binding.copyfileSync(req.handle, src, dst, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'copyfile',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }
}

async function cp(src, dst, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (!opts) opts = {}

  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  let err = null
  try {
    const st = await lstat(src)

    if (st.isDirectory()) {
      if (opts.recursive !== true) {
        throw new FileError('is a directory', { operation: 'cp', code: 'EISDIR', path: src })
      }

      try {
        await lstat(dst)
      } catch (e) {
        if (e.code !== 'ENOENT') throw e

        await mkdir(dst, { mode: st.mode, recursive: true })
      }

      const dir = await opendir(src)
      for await (const { name } of dir) {
        await cp(path.join(src, name), path.join(dst, name), opts)
      }
    } else if (st.isFile()) {
      await copyFile(src, dst)
      await chmod(dst, st.mode)
    }
  } catch (e) {
    err = e
  }

  return done(err, cb)
}

function cpSync(src, dst, opts = {}) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const st = lstatSync(src)

  if (st.isDirectory()) {
    if (opts.recursive !== true) {
      throw new FileError('is a directory', { operation: 'cp', code: 'EISDIR', path: src })
    }

    try {
      lstatSync(dst)
    } catch (e) {
      if (e.code !== 'ENOENT') throw e

      mkdirSync(dst, { mode: st.mode, recursive: true })
    }

    const dir = opendirSync(src)
    for (const { name } of dir) {
      cpSync(path.join(src, name), path.join(dst, name), opts)
    }
  } else if (st.isFile()) {
    copyFileSync(src, dst)
    chmodSync(dst, st.mode)
  }
}

async function realpath(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let res
  let err = null
  try {
    binding.realpath(req.handle, filepath)

    await req

    res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'realpath',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, res, cb)
}

function realpathSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.realpathSync(req.handle, filepath)

    let res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)

    return res
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'realpath',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function readlink(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let res
  let err = null
  try {
    binding.readlink(req.handle, filepath)

    await req

    res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'readlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, res, cb)
}

function readlinkSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.readlinkSync(req.handle, filepath)

    let res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)

    return res
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'readlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function fsync(fd, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fsync(req.handle, fd)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fsync', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fsyncSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.fsyncSync(req.handle, fd)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fsyncSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function fdatasync(fd, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fdatasync(req.handle, fd)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fdatasync', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fdatasyncSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.fdatasyncSync(req.handle, fd)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fdatasyncSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

function normalizeSymlinkTarget(target, type, filepath) {
  if (isWindows) {
    if (type === constants.UV_FS_SYMLINK_JUNCTION) target = path.resolve(filepath, '..', target)

    if (path.isAbsolute(target)) return path.toNamespacedPath(target)

    return target.replace(/\//g, path.sep)
  }

  return target
}

async function symlink(target, filepath, type, cb) {
  if (typeof type === 'function') {
    cb = type
    type = null
  }

  filepath = toNamespacedPath(filepath)

  if (typeof type === 'string') {
    switch (type) {
      case 'dir':
        type = constants.UV_FS_SYMLINK_DIR
        break
      case 'junction':
        type = constants.UV_FS_SYMLINK_JUNCTION
        break
      case 'file':
      default:
        type = 0
        break
    }
  } else if (typeof type !== 'number') {
    if (isWindows) {
      target = path.resolve(filepath, '..', target)

      try {
        type = (await stat(target)).isDirectory()
          ? constants.UV_FS_SYMLINK_DIR
          : constants.UV_FS_SYMLINK_JUNCTION
      } catch {
        type = 0
      }
    } else {
      type = 0
    }
  }

  target = normalizeSymlinkTarget(target, type, filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.symlink(req.handle, target, filepath, type)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'symlink',
      code: e.code,
      path: target,
      destination: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function symlinkSync(target, filepath, type) {
  filepath = toNamespacedPath(filepath)

  if (typeof type === 'string') {
    switch (type) {
      case 'dir':
        type = constants.UV_FS_SYMLINK_DIR
        break
      case 'junction':
        type = constants.UV_FS_SYMLINK_JUNCTION
        break
      case 'file':
      default:
        type = 0
        break
    }
  } else if (typeof type !== 'number') {
    if (isWindows) {
      target = path.resolve(filepath, '..', target)

      try {
        type = statSync(target).isDirectory()
          ? constants.UV_FS_SYMLINK_DIR
          : constants.UV_FS_SYMLINK_JUNCTION
      } catch {
        type = 0
      }
    } else {
      type = 0
    }
  }

  target = normalizeSymlinkTarget(target, type, filepath)

  const req = FileRequest.borrow()

  try {
    binding.symlinkSync(req.handle, target, filepath, type)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'symlink',
      code: e.code,
      path: target,
      destination: filepath
    })
  } finally {
    req.return()
  }
}

async function opendir(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let dir
  let err = null
  try {
    binding.opendir(req.handle, filepath)

    await req

    dir = new Dir(filepath, binding.requestResultDir(req.handle), opts)
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'opendir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, dir, cb)
}

function opendirSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.opendirSync(req.handle, filepath)

    return new Dir(filepath, binding.requestResultDir(req.handle), opts)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'opendir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function readdir(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { withFileTypes = false, recursive = false } = opts

  filepath = toNamespacedPath(filepath)

  const queue = [filepath]
  let result = []
  let err = null
  try {
    while (queue.length !== 0) {
      const dir = await opendir(queue.pop())

      for await (const entry of dir) {
        const entryPath = path.join(entry.parentPath, entry.name)

        if (withFileTypes) {
          result.push(entry)
        } else {
          result.push(path.relative(filepath, entryPath))
        }

        if (recursive && entry.isDirectory()) queue.push(entryPath)
      }
    }
  } catch (e) {
    result = []
    err = e
  }

  return done(err, result, cb)
}

function readdirSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { withFileTypes = false, recursive = false } = opts

  filepath = toNamespacedPath(filepath)

  const queue = [filepath]
  const result = []

  while (queue.length !== 0) {
    const dir = opendirSync(queue.pop(), opts)

    for (const entry of dir) {
      const entryPath = path.join(entry.parentPath, entry.name)

      if (withFileTypes) {
        result.push(entry)
      } else {
        result.push(path.relative(filepath, entryPath))
      }

      if (recursive && entry.isDirectory()) queue.push(entryPath)
    }
  }

  return result
}

async function readFile(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'buffer' } = opts

  let fd = -1
  let buffer = null
  let err = null
  try {
    fd = await open(filepath, opts.flag || 'r')

    const st = await fstat(fd)

    let len = 0

    if (st.size === 0) {
      const buffers = []

      while (true) {
        buffer = Buffer.allocUnsafe(8192)
        const r = await read(fd, buffer)
        len += r
        if (r === 0) break
        buffers.push(buffer.subarray(0, r))
      }

      buffer = Buffer.concat(buffers)
    } else {
      buffer = Buffer.allocUnsafe(st.size)

      while (true) {
        const r = await read(fd, len ? buffer.subarray(len) : buffer)
        len += r
        if (r === 0 || len === buffer.byteLength) break
      }

      if (len !== buffer.byteLength) buffer = buffer.subarray(0, len)
    }

    if (encoding !== 'buffer') buffer = buffer.toString(encoding)
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) await close(fd)
  }

  return done(err, buffer, cb)
}

function readFileSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'buffer' } = opts

  let fd = -1
  try {
    fd = openSync(filepath, opts.flag || 'r')

    const st = fstatSync(fd)

    let buffer
    let len = 0

    if (st.size === 0) {
      const buffers = []

      while (true) {
        buffer = Buffer.allocUnsafe(8192)
        const r = readSync(fd, buffer)
        len += r
        if (r === 0) break
        buffers.push(buffer.subarray(0, r))
      }

      buffer = Buffer.concat(buffers)
    } else {
      buffer = Buffer.allocUnsafe(st.size)

      while (true) {
        const r = readSync(fd, len ? buffer.subarray(len) : buffer)
        len += r
        if (r === 0 || len === buffer.byteLength) break
      }

      if (len !== buffer.byteLength) buffer = buffer.subarray(0, len)
    }

    if (encoding !== 'buffer') buffer = buffer.toString(encoding)

    return buffer
  } finally {
    if (fd !== -1) closeSync(fd)
  }
}

async function writeFile(filepath, data, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (typeof data === 'string') data = Buffer.from(data, opts.encoding)

  let fd = -1
  let len = 0
  let err = null
  try {
    fd = await open(filepath, opts.flag || 'w', opts.mode || 0o666)

    while (true) {
      len += await write(fd, len ? data.subarray(len) : data)
      if (len === data.byteLength) break
    }
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) await close(fd)
  }

  return done(err, len, cb)
}

function writeFileSync(filepath, data, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (typeof data === 'string') data = Buffer.from(data, opts.encoding)

  let fd = -1
  try {
    fd = openSync(filepath, opts.flag || 'w', opts.mode || 0o666)

    let len = 0

    while (true) {
      len += writeSync(fd, len ? data.subarray(len) : data)
      if (len === data.byteLength) break
    }
  } finally {
    if (fd !== -1) closeSync(fd)
  }
}

function appendFile(filepath, data, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (!opts.flag) opts = { ...opts, flag: 'a' }

  return writeFile(filepath, data, opts, cb)
}

function appendFileSync(filepath, data, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (!opts.flag) opts = { ...opts, flag: 'a' }

  return writeFileSync(filepath, data, opts)
}

function watch(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  return new Watcher(filepath, opts, cb)
}

class Stats {
  constructor(
    dev,
    mode,
    nlink,
    uid,
    gid,
    rdev,
    blksize,
    ino,
    size,
    blocks,
    atimeMs,
    mtimeMs,
    ctimeMs,
    birthtimeMs
  ) {
    this.dev = dev
    this.mode = mode
    this.nlink = nlink
    this.uid = uid
    this.gid = gid
    this.rdev = rdev
    this.blksize = blksize
    this.ino = ino
    this.size = size
    this.blocks = blocks
    this.atimeMs = atimeMs
    this.mtimeMs = mtimeMs
    this.ctimeMs = ctimeMs
    this.birthtimeMs = birthtimeMs
    this.atime = new Date(atimeMs)
    this.mtime = new Date(mtimeMs)
    this.ctime = new Date(ctimeMs)
    this.birthtime = new Date(birthtimeMs)
  }

  isDirectory() {
    return (this.mode & constants.S_IFMT) === constants.S_IFDIR
  }

  isFile() {
    return (this.mode & constants.S_IFMT) === constants.S_IFREG
  }

  isBlockDevice() {
    return (this.mode & constants.S_IFMT) === constants.S_IFBLK
  }

  isCharacterDevice() {
    return (this.mode & constants.S_IFMT) === constants.S_IFCHR
  }

  isFIFO() {
    return (this.mode & constants.S_IFMT) === constants.S_IFIFO
  }

  isSymbolicLink() {
    return (this.mode & constants.S_IFMT) === constants.S_IFLNK
  }

  isSocket() {
    return (this.mode & constants.S_IFMT) === constants.S_IFSOCK
  }
}

class StatFs {
  constructor(type, bsize, blocks, bfree, bavail, files, ffree) {
    this.type = type
    this.bsize = bsize
    this.blocks = blocks
    this.bfree = bfree
    this.bavail = bavail
    this.files = files
    this.ffree = ffree
  }
}

class Dir {
  constructor(path, handle, opts = {}) {
    const { encoding = 'utf8', bufferSize = 32 } = opts

    this.path = path

    this._encoding = encoding
    this._capacity = bufferSize
    this._buffer = new FIFO()
    this._ended = false
    this._handle = handle
  }

  async read(cb) {
    if (this._buffer.length) return ok(this._buffer.shift(), cb)
    if (this._ended) return ok(null, cb)

    const req = FileRequest.borrow()

    let entries
    let err = null
    try {
      req.retain(binding.readdir(req.handle, this._handle, this._capacity))

      await req

      entries = binding.requestResultDirents(req.handle)
    } catch (e) {
      err = new FileError(e.message, {
        operation: 'readdir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    if (err) return fail(err, cb)

    if (entries.length === 0) {
      this._ended = true

      return ok(null, cb)
    }

    for (const entry of entries) {
      let name = Buffer.from(entry.name)

      if (this._encoding !== 'buffer') name = name.toString(this._encoding)

      this._buffer.push(new Dirent(this.path, name, entry.type))
    }

    return ok(this._buffer.shift(), cb)
  }

  readSync() {
    if (this._buffer.length) return this._buffer.shift()
    if (this._ended) return null

    const req = FileRequest.borrow()

    let entries
    try {
      req.retain(binding.readdirSync(req.handle, this._handle, this._capacity))

      entries = binding.requestResultDirents(req.handle)
    } catch (e) {
      throw new FileError(e.message, {
        operation: 'readdir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    if (entries.length === 0) {
      this._ended = true

      return null
    }

    for (const entry of entries) {
      let name = Buffer.from(entry.name)

      if (this._encoding !== 'buffer') name = name.toString(this._encoding)

      this._buffer.push(new Dirent(this.path, name, entry.type))
    }

    return this._buffer.shift()
  }

  async close(cb) {
    const req = FileRequest.borrow()

    let err = null
    try {
      binding.closedir(req.handle, this._handle)

      await req
    } catch (e) {
      err = new FileError(e.message, {
        operation: 'closedir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    this._handle = null

    return done(err, cb)
  }

  closeSync() {
    const req = FileRequest.borrow()

    try {
      binding.closedirSync(req.handle, this._handle)
    } catch (e) {
      throw new FileError(e.message, {
        operation: 'closedir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    this._handle = null
  }

  [Symbol.dispose]() {
    this.closeSync()
  }

  async [Symbol.asyncDispose]() {
    await this.close()
  }

  *[Symbol.iterator]() {
    while (true) {
      const entry = this.readSync()
      if (entry === null) break
      yield entry
    }

    this.closeSync()
  }

  async *[Symbol.asyncIterator]() {
    while (true) {
      const entry = await this.read()
      if (entry === null) break
      yield entry
    }

    await this.close()
  }
}

class Dirent {
  constructor(parentPath, name, type) {
    this.parentPath = parentPath
    this.name = name
    this.type = type
  }

  isFile() {
    return this.type === constants.UV_DIRENT_FILE
  }

  isDirectory() {
    return this.type === constants.UV_DIRENT_DIR
  }

  isSymbolicLink() {
    return this.type === constants.UV_DIRENT_LINK
  }

  isFIFO() {
    return this.type === constants.UV_DIRENT_FIFO
  }

  isSocket() {
    return this.type === constants.UV_DIRENT_SOCKET
  }

  isCharacterDevice() {
    return this.type === constants.UV_DIRENT_CHAR
  }

  isBlockDevice() {
    return this.type === constants.UV_DIRENT_BLOCK
  }
}

class FileReadStream extends Readable {
  constructor(path, opts = {}) {
    const { eagerOpen = true } = opts

    super({ eagerOpen, ...opts })

    this.path = path
    this.fd = typeof opts.fd === 'number' ? opts.fd : -1
    this.flags = opts.flags || 'r'
    this.mode = opts.mode || 0o666

    this._offset = opts.start || 0
    this._missing = 0

    if (opts.length) {
      this._missing = opts.length
    } else if (typeof opts.end === 'number') {
      this._missing = opts.end - this._offset + 1
    } else {
      this._missing = -1
    }
  }

  async _open(cb) {
    let err

    if (this.fd === -1) {
      err = null
      try {
        this.fd = await open(this.path, this.flags, this.mode)
      } catch (e) {
        err = e
      }

      if (err) return cb(err)
    }

    let st
    err = null
    try {
      st = await fstat(this.fd)
    } catch (e) {
      err = e
    }

    if (err) return cb(err)

    if (this._missing === -1) this._missing = st.size

    if (st.size < this._offset) {
      this._offset = st.size
      this._missing = 0
    } else if (st.size < this._offset + this._missing) {
      this._missing = st.size - this._offset
    }

    cb(null)
  }

  async _read(size) {
    if (this._missing <= 0) return this.push(null)

    const data = Buffer.allocUnsafe(Math.min(this._missing, size))

    let len
    let err = null
    try {
      len = await read(this.fd, data, 0, data.byteLength, this._offset)
    } catch (e) {
      err = e
    }

    if (err) return this.destroy(err)

    if (len === 0) return this.push(null)

    if (this._missing < len) len = this._missing

    this._missing -= len
    this._offset += len

    this.push(data.subarray(0, len))
  }

  async _destroy(err, cb) {
    if (this.fd === -1) return cb(err)

    try {
      await close(this.fd)
    } catch (e) {
      err = err || e
    }

    cb(err)
  }
}

class FileWriteStream extends Writable {
  constructor(path, opts = {}) {
    const { eagerOpen = true } = opts

    super({ eagerOpen, ...opts })

    this.path = path
    this.fd = typeof opts.fd === 'number' ? opts.fd : -1
    this.flags = opts.flags || 'w'
    this.mode = opts.mode || 0o666
  }

  async _open(cb) {
    if (this.fd !== -1) return cb(null)

    let err = null
    try {
      this.fd = await open(this.path, this.flags, this.mode)
    } catch (e) {
      err = e
    }

    cb(err)
  }

  async _writev(batch, cb) {
    let err = null
    try {
      await writev(
        this.fd,
        batch.map(({ chunk }) => chunk)
      )
    } catch (e) {
      err = e
    }

    cb(err)
  }

  async _destroy(err, cb) {
    if (this.fd === -1) return cb(err)

    try {
      await close(this.fd)
    } catch (e) {
      err = err || e
    }

    cb(err)
  }
}

class Watcher extends EventEmitter {
  constructor(path, opts, onchange) {
    if (typeof opts === 'function') {
      onchange = opts
      opts = {}
    }

    if (!opts) opts = {}

    const { persistent = true, recursive = false, encoding = 'utf8' } = opts

    super()

    this._closed = false
    this._encoding = encoding
    this._handle = binding.watcherInit(path, recursive, this, this._onevent, this._onclose)

    if (!persistent) this.unref()

    if (onchange) this.on('change', onchange)
  }

  close() {
    if (this._closed) return
    this._closed = true

    binding.watcherClose(this._handle)
  }

  ref() {
    if (this._handle) binding.watcherRef(this._handle)
    return this
  }

  unref() {
    if (this._handle) binding.watcherUnref(this._handle)
    return this
  }

  [Symbol.asyncIterator]() {
    const buffer = []
    let done = false
    let error = null
    let next = null

    this.on('change', (eventType, filename) => {
      if (next) {
        next.resolve({ done: false, value: { eventType, filename } })
        next = null
      } else {
        buffer.push({ eventType, filename })
      }
    })
      .on('error', (err) => {
        done = true
        error = err

        if (next) {
          next.reject(error)
          next = null
        }
      })
      .on('close', () => {
        done = true

        if (next) {
          next.resolve({ done })
          next = null
        }
      })

    return {
      next: () =>
        new Promise((resolve, reject) => {
          if (error) return reject(error)

          if (buffer.length) return resolve({ done: false, value: buffer.shift() })

          if (done) return resolve({ done })

          next = { resolve, reject }
        })
    }
  }

  _onevent(err, events, filename) {
    if (err) {
      this.close()
      this.emit('error', err)
    } else {
      const path =
        this._encoding === 'buffer'
          ? Buffer.from(filename)
          : Buffer.from(filename).toString(this._encoding)

      if (events & binding.UV_RENAME) {
        this.emit('change', 'rename', path)
      }

      if (events & binding.UV_CHANGE) {
        this.emit('change', 'change', path)
      }
    }
  }

  _onclose() {
    this._handle = null

    this.emit('close')
  }
}

exports.access = access
exports.appendFile = appendFile
exports.chmod = chmod
exports.chown = chown
exports.close = close
exports.copyFile = copyFile
exports.cp = cp
exports.exists = exists
exports.fchmod = fchmod
exports.fchown = fchown
exports.fdatasync = fdatasync
exports.fstat = fstat
exports.fsync = fsync
exports.ftruncate = ftruncate
exports.futimes = futimes
exports.lchown = lchown
exports.lutimes = lutimes
exports.link = link
exports.lstat = lstat
exports.mkdir = mkdir
exports.mkdtemp = mkdtemp
exports.open = open
exports.opendir = opendir
exports.read = read
exports.readFile = readFile
exports.readdir = readdir
exports.readlink = readlink
exports.readv = readv
exports.realpath = realpath
exports.rename = rename
exports.rm = rm
exports.rmdir = rmdir
exports.stat = stat
exports.statfs = statfs
exports.symlink = symlink
exports.truncate = truncate
exports.unlink = unlink
exports.utimes = utimes
exports.watch = watch
exports.write = write
exports.writeFile = writeFile
exports.writev = writev

exports.accessSync = accessSync
exports.appendFileSync = appendFileSync
exports.chmodSync = chmodSync
exports.chownSync = chownSync
exports.closeSync = closeSync
exports.copyFileSync = copyFileSync
exports.cpSync = cpSync
exports.existsSync = existsSync
exports.fchmodSync = fchmodSync
exports.fchownSync = fchownSync
exports.fdatasyncSync = fdatasyncSync
exports.fstatSync = fstatSync
exports.fsyncSync = fsyncSync
exports.ftruncateSync = ftruncateSync
exports.futimesSync = futimesSync
exports.lchownSync = lchownSync
exports.lutimesSync = lutimesSync
exports.linkSync = linkSync
exports.lstatSync = lstatSync
exports.mkdirSync = mkdirSync
exports.mkdtempSync = mkdtempSync
exports.openSync = openSync
exports.opendirSync = opendirSync
exports.readFileSync = readFileSync
exports.readSync = readSync
exports.readdirSync = readdirSync
exports.readlinkSync = readlinkSync
exports.readvSync = readvSync
exports.realpathSync = realpathSync
exports.renameSync = renameSync
exports.rmSync = rmSync
exports.rmdirSync = rmdirSync
exports.statSync = statSync
exports.statfsSync = statfsSync
exports.symlinkSync = symlinkSync
exports.truncateSync = truncateSync
exports.unlinkSync = unlinkSync
exports.utimesSync = utimesSync
exports.writeFileSync = writeFileSync
exports.writeSync = writeSync
exports.writevSync = writevSync

exports.promises = require('./promises')

exports.Stats = Stats
exports.StatFs = StatFs
exports.Dir = Dir
exports.Dirent = Dirent
exports.Watcher = Watcher

exports.ReadStream = FileReadStream

exports.createReadStream = function createReadStream(path, opts) {
  return new FileReadStream(path, opts)
}

exports.WriteStream = FileWriteStream

exports.createWriteStream = function createWriteStream(path, opts) {
  return new FileWriteStream(path, opts)
}

function toNamespacedPath(filepath) {
  if (typeof filepath !== 'string') {
    if (isURL(filepath)) filepath = fileURLToPath(filepath)
    else filepath = filepath.toString()
  }

  return path.toNamespacedPath(filepath)
}

function toFlags(flags) {
  switch (flags) {
    case 'r':
      return constants.O_RDONLY
    case 'rs': // Fall through.
    case 'sr':
      return constants.O_RDONLY | constants.O_SYNC
    case 'r+':
      return constants.O_RDWR
    case 'rs+': // Fall through.
    case 'sr+':
      return constants.O_RDWR | constants.O_SYNC

    case 'w':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_WRONLY
    case 'wx': // Fall through.
    case 'xw':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_WRONLY | constants.O_EXCL

    case 'w+':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_RDWR
    case 'wx+': // Fall through.
    case 'xw+':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_RDWR | constants.O_EXCL

    case 'a':
      return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY
    case 'ax': // Fall through.
    case 'xa':
      return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY | constants.O_EXCL
    case 'as': // Fall through.
    case 'sa':
      return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY | constants.O_SYNC

    case 'a+':
      return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR
    case 'ax+': // Fall through.
    case 'xa+':
      return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR | constants.O_EXCL
    case 'as+': // Fall through.
    case 'sa+':
      return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR | constants.O_SYNC
    default:
      return 0
  }
}

function toMode(mode) {
  return parseInt(mode, 8)
}
const binding = require('../binding')

module.exports = {
  O_RDWR: binding.O_RDWR,
  O_RDONLY: binding.O_RDONLY,
  O_WRONLY: binding.O_WRONLY,
  O_CREAT: binding.O_CREAT,
  O_TRUNC: binding.O_TRUNC,
  O_APPEND: binding.O_APPEND,

  F_OK: binding.F_OK || 0,
  R_OK: binding.R_OK || 0,
  W_OK: binding.W_OK || 0,
  X_OK: binding.X_OK || 0,

  S_IFMT: binding.S_IFMT,
  S_IFREG: binding.S_IFREG,
  S_IFDIR: binding.S_IFDIR,
  S_IFCHR: binding.S_IFCHR,
  S_IFLNK: binding.S_IFLNK,
  S_IFBLK: binding.S_IFBLK || 0,
  S_IFIFO: binding.S_IFIFO || 0,
  S_IFSOCK: binding.S_IFSOCK || 0,

  S_IRUSR: binding.S_IRUSR || 0,
  S_IWUSR: binding.S_IWUSR || 0,
  S_IXUSR: binding.S_IXUSR || 0,
  S_IRGRP: binding.S_IRGRP || 0,
  S_IWGRP: binding.S_IWGRP || 0,
  S_IXGRP: binding.S_IXGRP || 0,
  S_IROTH: binding.S_IROTH || 0,
  S_IWOTH: binding.S_IWOTH || 0,
  S_IXOTH: binding.S_IXOTH || 0,

  UV_DIRENT_UNKNOWN: binding.UV_DIRENT_UNKNOWN,
  UV_DIRENT_FILE: binding.UV_DIRENT_FILE,
  UV_DIRENT_DIR: binding.UV_DIRENT_DIR,
  UV_DIRENT_LINK: binding.UV_DIRENT_LINK,
  UV_DIRENT_FIFO: binding.UV_DIRENT_FIFO,
  UV_DIRENT_SOCKET: binding.UV_DIRENT_SOCKET,
  UV_DIRENT_CHAR: binding.UV_DIRENT_CHAR,
  UV_DIRENT_BLOCK: binding.UV_DIRENT_BLOCK,

  COPYFILE_EXCL: binding.UV_FS_COPYFILE_EXCL,
  COPYFILE_FICLONE: binding.UV_FS_COPYFILE_FICLONE,
  COPYFILE_FICLONE_FORCE: binding.UV_FS_COPYFILE_FICLONE_FORCE,
  UV_FS_SYMLINK_DIR: binding.UV_FS_SYMLINK_DIR,
  UV_FS_SYMLINK_JUNCTION: binding.UV_FS_SYMLINK_JUNCTION
}
const os = require('bare-os')

module.exports = class FileError extends Error {
  constructor(msg, opts = {}) {
    const { code, operation = null, path = null, destination = null, fd = -1 } = opts

    if (operation !== null) msg += describe(operation, opts)

    super(`${code}: ${msg}`)

    this.code = code

    if (operation !== null) this.operation = operation
    if (path !== null) this.path = path
    if (destination !== null) this.destination = destination
    if (fd !== -1) this.fd = fd
  }

  get name() {
    return 'FileError'
  }

  // For Node.js compatibility
  get errno() {
    return os.constants.errnos[this.code]
  }

  // For Node.js compatibility
  get syscall() {
    return this.operation
  }

  // For Node.js compatibility
  get dest() {
    return this.destination
  }
}

function describe(operation, opts) {
  const { path = null, destination = null, fd = -1 } = opts

  let result = `, ${operation}`

  if (path !== null) {
    result += ` ${JSON.stringify(path)}`

    if (destination !== null) {
      result += ` -> ${JSON.stringify(destination)}`
    }
  } else if (fd !== -1) {
    result += ` ${fd}`
  }

  return result
}
{
  "name": "bare-fs",
  "version": "4.7.3",
  "description": "Native file system operations for Bare",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./promises": {
      "types": "./promises.d.ts",
      "default": "./promises.js"
    },
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "promises.js",
    "promises.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-fs.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-fs/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-fs#readme",
  "engines": {
    "bare": ">=1.16.0"
  },
  "dependencies": {
    "bare-events": "^2.5.4",
    "bare-path": "^3.0.0",
    "bare-stream": "^2.6.4",
    "bare-url": "^2.2.2",
    "fast-fifo": "^1.3.2"
  },
  "devDependencies": {
    "bare-buffer": "^3.0.2",
    "bare-crypto": "^1.11.2",
    "brittle": "^3.1.1",
    "cmake-bare": "^1.1.7",
    "lunte": "^1.6.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "bare-buffer": "*"
  },
  "peerDependenciesMeta": {
    "bare-buffer": {
      "optional": true
    }
  }
}
const EventEmitter = require('bare-events')
const fs = require('.')

class FileHandle extends EventEmitter {
  constructor(fd) {
    super()

    this.fd = fd
  }

  async close() {
    await fs.close(this.fd)

    this.fd = -1
    this.emit('close')
  }

  async read(buffer, ...args) {
    return {
      bytesRead: await fs.read(this.fd, buffer, ...args),
      buffer
    }
  }

  async readv(buffers, ...args) {
    return {
      bytesRead: await fs.readv(this.fd, buffers, ...args),
      buffers
    }
  }

  async write(buffer, ...args) {
    return {
      bytesWritten: await fs.write(this.fd, buffer, ...args),
      buffer
    }
  }

  async writev(buffers, ...args) {
    return {
      bytesWritten: await fs.writev(this.fd, buffers, ...args),
      buffers
    }
  }

  async stat() {
    return fs.fstat(this.fd)
  }

  async chmod(mode) {
    await fs.fchmod(this.fd, mode)
  }

  async chown(uid, gid) {
    await fs.fchown(this.fd, uid, gid)
  }

  async datasync() {
    return fs.fdatasync(this.fd)
  }

  async sync() {
    return fs.fsync(this.fd)
  }

  async truncate(len) {
    await fs.ftruncate(this.fd, len)
  }

  async utimes(atime, mtime) {
    await fs.futimes(this.fd, atime, mtime)
  }

  createReadStream(opts) {
    return fs.createReadStream(null, { ...opts, fd: this.fd })
  }

  createWriteStream(opts) {
    return fs.createWriteStream(null, { ...opts, fd: this.fd })
  }

  async [Symbol.asyncDispose]() {
    await this.close()
  }
}

exports.open = async function open(filepath, flags, mode) {
  return new FileHandle(await fs.open(filepath, flags, mode))
}

exports.access = fs.access
exports.appendFile = fs.appendFile
exports.chmod = fs.chmod
exports.chown = fs.chown
exports.constants = fs.constants
exports.copyFile = fs.copyFile
exports.cp = fs.cp
exports.lchown = fs.lchown
exports.lutimes = fs.lutimes
exports.link = fs.link
exports.lstat = fs.lstat
exports.mkdir = fs.mkdir
exports.mkdtemp = fs.mkdtemp
exports.opendir = fs.opendir
exports.readFile = fs.readFile
exports.readdir = fs.readdir
exports.readlink = fs.readlink
exports.realpath = fs.realpath
exports.rename = fs.rename
exports.rm = fs.rm
exports.rmdir = fs.rmdir
exports.stat = fs.stat
exports.statfs = fs.statfs
exports.truncate = fs.truncate
exports.symlink = fs.symlink
exports.unlink = fs.unlink
exports.utimes = fs.utimes
exports.watch = fs.watch
exports.writeFile = fs.writeFile
module.exports = require.addon()
const ansiEscapes = require('bare-ansi-escapes')
const getType = require('bare-type')
const binding = require('./binding')

const PLAIN_KEY = /^[a-zA-Z_][a-zA-Z_0-9]*$/

const defaultDepth = 2
const defaultBreakLength = 80
const defaultMaxArrayLength = 40

module.exports = exports = function inspect(value, opts = {}) {
  const {
    colors = false,
    depth = defaultDepth,
    breakLength = defaultBreakLength,
    stylize = defaultStylize(colors)
  } = opts

  const references = new InspectRefMap()

  const tree = inspectValue(value, 0, {
    colors,
    depth,
    breakLength,
    stylize,
    references
  })

  return tree.toString()
}

exports.styles = {
  bigint: ansiEscapes.colorYellow,
  boolean: ansiEscapes.colorYellow,
  date: ansiEscapes.colorMagenta,
  module: ansiEscapes.modifierUnderline,
  name: ansiEscapes.modifierReset,
  null: ansiEscapes.modifierBold,
  number: ansiEscapes.colorYellow,
  regexp: ansiEscapes.colorRed,
  special: ansiEscapes.colorCyan,
  string: ansiEscapes.colorGreen,
  symbol: ansiEscapes.colorGreen,
  undefined: ansiEscapes.colorBrightBlack
}

const styles = exports.styles

function defaultStylize(colors) {
  return function stylize(value, style) {
    const color = colors && styles[style]

    if (color) return color + value + ansiEscapes.modifierReset

    return value
  }
}

class InspectRefMap {
  constructor() {
    this.refs = new WeakMap()
    this.ids = new WeakMap()
    this.nextId = 1
  }

  has(object) {
    return this.refs.has(object)
  }

  get(object) {
    return this.refs.get(object) || null
  }

  set(object, ref) {
    this.refs.set(object, ref)
  }

  id(object) {
    let id = this.ids.get(object)
    if (id) return id

    id = this.nextId++
    this.ids.set(object, id)

    return id
  }
}

class InspectNode {
  constructor(depth, length, opts) {
    const { breakLength = defaultBreakLength, breakAlways = false } = opts

    this.depth = depth
    this.length = length
    this.breakLength = breakLength
    this.breakAlways = breakAlways
  }

  pad(n, string) {
    return string.padStart(n, ' ')
  }

  indent(n, string) {
    return '  '.repeat(n) + string
  }
}

class InspectRef extends InspectNode {
  constructor(depth, opts) {
    super(depth, '[circular *]'.length, opts)

    this.refs = opts.references
    this.count = 0
    this.circular = false
    this.color = opts.colors && styles.special
  }

  get id() {
    return this.refs.id(this)
  }

  increment() {
    return ++this.count
  }

  decrement() {
    return --this.count
  }

  toString(opts = {}) {
    const { offset = 0, pad = 0, indent = 0 } = opts

    let value = this.pad(pad, '[circular *' + this.id + ']')

    if (this.color) value = this.color + value + ansiEscapes.modifierReset

    return offset ? value : this.indent(indent, value)
  }
}

class InspectLeaf extends InspectNode {
  constructor(value, color, depth, opts) {
    const length = value.length

    if (value.includes('\n')) {
      value = value.replaceAll('\n', '\n' + '  '.repeat(depth))

      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.value = value
    this.color = opts.colors && color
  }

  toString(opts = {}) {
    const { offset = 0, pad = 0, indent = 0 } = opts

    let value = this.pad(pad, this.value)

    if (this.color) value = this.color + value + ansiEscapes.modifierReset

    return offset ? value : this.indent(indent, value)
  }
}

class InspectPair extends InspectNode {
  constructor(delim, left, right, depth, opts) {
    const length = left.length + delim.length + right.length

    if (left.breakAlways || right.breakAlways) {
      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.delim = delim
    this.left = left
    this.right = right
  }

  toString(opts = {}) {
    const { indent = 0 } = opts

    return this.indent(
      indent,
      this.left +
        this.delim +
        this.right.toString({
          indent,
          offset: this.left.length + this.delim.length
        })
    )
  }
}

class InspectSuspension extends InspectNode {
  constructor(overflow, depth, opts) {
    const label = `... ${overflow} more`

    super(depth, label.length, opts)

    this.label = label
  }

  toString(opts = {}) {
    const { indent = 0 } = opts

    return this.indent(indent, this.label)
  }
}

class InspectSequence extends InspectNode {
  constructor(header, footer, delim, values, ref, depth, opts) {
    const { tabulate = false } = opts

    const length =
      (ref.circular ? '<ref *>'.length + 1 : 0) +
      header.length +
      values.reduce(
        (length, value, i) =>
          length + value.length + (i === 0 ? 0 : delim.length),
        0
      ) +
      footer.length

    if (values.some((value) => value.breakAlways)) {
      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.header = header
    this.footer = footer
    this.delim = delim
    this.values = values
    this.ref = ref
    this.tabulate = tabulate
  }

  toString(opts = {}) {
    const { offset = 0, indent = 0 } = opts

    const split =
      this.breakAlways ||
      (this.values.length &&
        (offset + this.length > this.breakLength ||
          indent * 2 + this.length > this.breakLength))

    let header = this.header

    if (this.ref.circular) {
      header = '<ref *' + this.ref.id + '> ' + header
    }

    if (this.values.length === 0) {
      header = header.trimEnd()
    }

    if (offset === 0) {
      header = this.indent(indent, header)
    }

    if (split) {
      header = header.trimEnd() + '\n'
    }

    let string = header

    let columns = 1
    let pad = 0

    if (this.tabulate) {
      const widest = this.values.reduce(
        (length, value) =>
          value.breakAlways ? length : Math.max(length, value.length),
        0
      )

      if (widest) {
        columns = Math.max(
          columns,
          Math.floor(
            (this.breakLength - indent * 2) / (widest + this.delim.length)
          )
        )

        if (columns > 1) pad = widest
      }
    }

    for (let i = 0, n = this.values.length, offset = 0; i < n; i++) {
      const value = this.values[i]

      if (split) {
        let part

        if (i % columns === 0 || value.breakAlways) {
          part = value.toString({ indent: indent + 1, pad })
        } else {
          part = value.toString({ pad })
        }

        string += part

        if (i < n - 1) {
          if (i % columns === columns - 1 || this.values[i + 1].breakAlways) {
            string += this.delim.trimEnd() + '\n'
          } else {
            string += this.delim
          }
        }
      } else {
        if (i > 0) string += this.delim

        string += value.toString({ offset })

        offset += value.length
      }
    }

    let footer = this.footer

    if (this.values.length === 0) {
      footer = footer.trimStart()
    }

    if (split) {
      string += '\n' + this.indent(indent, footer.trimStart())
    } else {
      string += footer
    }

    return string
  }
}

function inspectValue(value, depth, opts) {
  const type = getType(value)

  if (type.isUndefined()) return inspectUndefined(depth, opts)
  if (type.isNull()) return inspectNull(depth, opts)
  if (type.isBoolean()) return inspectBoolean(value, depth, opts)
  if (type.isNumber()) return inspectNumber(value, depth, opts)
  if (type.isBigInt()) return inspectBigInt(value, depth, opts)
  if (type.isString()) return inspectString(value, depth, opts)
  if (type.isSymbol()) return inspectSymbol(value, depth, opts)
  if (type.isObject()) return inspectObject(type, value, depth, opts)
  if (type.isFunction()) return inspectFunction(type, value, depth, opts)
  if (type.isExternal()) return inspectExternal(value, opts, opts)
}

function inspectUndefined(depth, opts) {
  return new InspectLeaf('undefined', styles.undefined, depth, opts)
}

function inspectNull(depth, opts) {
  return new InspectLeaf('null', styles.null, depth, opts)
}

function inspectBoolean(value, depth, opts) {
  return new InspectLeaf(value.toString(), styles.boolean, depth, opts)
}

function inspectNumber(value, depth, opts) {
  let string

  if (Object.is(value, -0)) {
    string = '-0'
  } else {
    string = value.toString(10)
  }

  return new InspectLeaf(string, styles.number, depth, opts)
}

function inspectBigInt(value, depth, opts) {
  return new InspectLeaf(value.toString(10) + 'n', styles.bigint, depth, opts)
}

const STRING_ESCAPES =
  /[\ud800-\udbff][\udc00-\udfff]|[\u0000-\u001f'\\\ud800-\udfff]/g

function inspectString(value, depth, opts) {
  // https://tc39.es/ecma262/multipage/structured-data.html#sec-quotejsonstring
  const string = value.replace(STRING_ESCAPES, (match) => {
    if (match.length === 2) return match

    switch (match) {
      case "'":
        return "\\'"
      case '\\':
        return '\\\\'
      case '\b':
        return '\\b'
      case '\t':
        return '\\t'
      case '\n':
        return '\\n'
      case '\f':
        return '\\f'
      case '\r':
        return '\\r'
      default:
        return '\\u' + match.charCodeAt(0).toString(16).padStart(4, '0')
    }
  })

  return new InspectLeaf("'" + string + "'", styles.string, depth, opts)
}

function inspectSymbol(value, depth, opts) {
  return new InspectLeaf(value.toString(), styles.symbol, depth, opts)
}

function inspectKey(value, depth, opts) {
  if (PLAIN_KEY.test(value)) {
    return new InspectLeaf(value, null, depth, opts)
  } else {
    return inspectValue(value, depth, opts)
  }
}

function inspectObject(type, object, depth, opts) {
  const refs = opts.references

  let ref = refs.get(object)
  if (ref === null) {
    ref = new InspectRef(depth, opts)
    refs.set(object, ref)
  } else if (ref.count) {
    ref.circular = true
    return ref
  }

  const maxDepth = typeof opts.depth === 'number' ? opts.depth : Infinity

  if (maxDepth < depth) {
    const constructor = object.constructor

    return new InspectLeaf(
      '[' +
        (constructor && constructor.name ? constructor.name : 'Object') +
        ']',
      styles.special,
      depth,
      opts
    )
  }

  const inspect =
    object[Symbol.for('bare.inspect')] ||
    object[Symbol.for('nodejs.util.inspect.custom')]

  if (typeof inspect === 'function') {
    const value = inspect.call(
      object,
      typeof opts.depth === 'number' ? opts.depth - depth : null,
      {
        colors: opts.colors,
        breakLength: opts.breakLength,
        stylize: opts.stylize
      },
      exports
    )

    if (typeof value === 'object' && value !== null) {
      refs.set(value, ref)
    }

    if (typeof value !== 'string') {
      return inspectValue(value, depth, opts)
    }

    return new InspectLeaf(value, null, depth, opts)
  }

  if (type.isArray()) return inspectArray(object, ref, depth, opts)
  if (type.isDate()) return inspectDate(object, ref, depth, opts)
  if (type.isRegExp()) return inspectRegExp(object, ref, depth, opts)
  if (type.isError()) return inspectError(object, ref, depth, opts)
  if (type.isPromise()) return inspectPromise(object, ref, depth, opts)
  if (type.isMap()) return inspectMap(object, ref, depth, opts)
  if (type.isSet()) return inspectSet(object, ref, depth, opts)
  if (type.isWeakMap()) return inspectWeakMap(object, ref, depth, opts)
  if (type.isWeakSet()) return inspectWeakSet(object, ref, depth, opts)
  if (type.isWeakRef()) return inspectWeakRef(object, ref, depth, opts)
  if (type.isArrayBuffer()) return inspectArrayBuffer(object, ref, depth, opts)
  if (type.isSharedArrayBuffer())
    return inspectSharedArrayBuffer(object, ref, depth, opts)
  if (type.isTypedArray()) return inspectTypedArray(object, ref, depth, opts)
  if (type.isDataView()) return inspectDataView(object, ref, depth, opts)

  ref.increment()

  const values = []

  for (const key in object) {
    if (key === 'constructor') continue

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(object[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  let header = '{ '

  const tag = object[Symbol.toStringTag]

  if (tag) header = '[' + tag + '] ' + header

  if (object.constructor) {
    const name = object.constructor.name

    if (name && name !== 'Object') {
      header = object.constructor.name + ' ' + header
    }
  }

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectArray(array, ref, depth, opts) {
  const { maxArrayLength = defaultMaxArrayLength } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxArrayLength, 0)

  for (let i = 0, n = array.length; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(array.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(inspectValue(array[i], depth + 1, opts))
  }

  for (const key of binding.getOwnNonIndexPropertyNames(array)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(array[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  let header = '[ '

  if (array.constructor.name !== 'Array') {
    header = array.constructor.name + '(' + array.length + ') ' + header
  }

  return new InspectSequence(header, ' ]', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectDate(date, ref, depth, opts) {
  return new InspectLeaf(date.toISOString(), styles.date, depth, opts)
}

function inspectRegExp(regExp, ref, depth, opts) {
  return new InspectLeaf(regExp.toString(), styles.regexp, depth, opts)
}

function inspectError(error, ref, depth, opts) {
  let header

  if ('stack' in error) {
    header = error.stack

    if (depth > 0) {
      header = header.replaceAll('\n', '\n' + '  '.repeat(depth))
    }
  } else {
    header = error.toString()
  }

  const builtins = ['cause']

  if (error.name === 'AggregateError') {
    builtins.push('errors')
  } else if (error.name === 'SuppressedError') {
    builtins.push('error', 'suppressed')
  }

  const values = []

  for (const key of builtins) {
    if (key in error === false) continue

    values.push(
      new InspectPair(
        ': ',
        new InspectLeaf('[' + key + ']', null, depth + 1, opts),
        inspectValue(error[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key in error) {
    if (key === 'constructor' || builtins.includes(key)) continue

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(error[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  if (values.length === 0) return new InspectLeaf(header, null, depth, opts)

  return new InspectSequence(
    header + ' {',
    ' }',
    ', ',
    values,
    ref,
    depth,
    opts
  )
}

function inspectPromise(promise, ref, depth, opts) {
  ref.increment()

  const state = binding.getPromiseState(promise)

  const values = []

  switch (state) {
    case 0: // Pending
      values.push(new InspectLeaf('<pending>', styles.special, depth, opts))
      break

    case 1: // Fulfilled
      values.push(inspectValue(binding.getPromiseResult(promise), depth, opts))
      break

    case 2: // Rejected
      values.push(
        new InspectLeaf('<rejected>', styles.special, depth, opts),
        inspectValue(binding.getPromiseResult(promise), depth, opts)
      )
  }

  ref.decrement()

  const header = promise.constructor.name + ' { '

  return new InspectSequence(header, ' }', ' ', values, ref, depth, opts)
}

function inspectMap(map, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxMapLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = maxMapLength

  for (const entry of map) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(map.size - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )
      break
    }

    values.push(
      new InspectPair(
        ' => ',
        inspectValue(entry[0], depth + 1, opts),
        inspectValue(entry[1], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key in map) {
    if (key === 'constructor') continue

    const value = inspectValue(map[key], depth + 1, opts)

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        value,
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = map.constructor.name + '(' + map.size + ') { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectSet(set, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxSetLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = maxSetLength

  for (const entry of set) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(set.size - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )
      break
    }

    values.push(inspectValue(entry, depth + 1, opts))
  }

  for (const key in set) {
    if (key === 'constructor') continue

    const value = inspectValue(set[key], depth + 1, opts)

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        value,
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = set.constructor.name + '(' + set.size + ') { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectWeakMap(weakMap, ref, depth, opts) {
  const header = weakMap.constructor.name + ' { '

  return new InspectSequence(
    header,
    ' }',
    ' ',
    [new InspectLeaf('<items unknown>', styles.special, depth + 1, opts)],
    ref,
    depth,
    opts
  )
}

function inspectWeakSet(weakSet, ref, depth, opts) {
  const header = weakSet.constructor.name + ' { '

  return new InspectSequence(
    header,
    ' }',
    ' ',
    [new InspectLeaf('<items unknown>', styles.special, depth + 1, opts)],
    ref,
    depth,
    opts
  )
}

function inspectWeakRef(weakRef, ref, depth, opts) {
  const target = weakRef.deref()

  let value

  if (target === undefined) {
    value = new InspectLeaf('<cleared>', styles.special, depth + 1, opts)
  } else {
    value = inspectValue(target, depth + 1, opts)
  }

  const header = weakRef.constructor.name + ' { '

  return new InspectSequence(header, ' }', ' ', [value], ref, depth, opts)
}

function inspectArrayBuffer(arrayBuffer, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(arrayBuffer[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = arrayBuffer.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectSharedArrayBuffer(sharedArrayBuffer, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(sharedArrayBuffer[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = sharedArrayBuffer.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectTypedArray(typedArray, ref, depth, opts) {
  if (Buffer.isBuffer(typedArray)) {
    return inspectBuffer(typedArray, ref, depth, opts)
  }

  const {
    maxArrayLength = defaultMaxArrayLength,
    maxTypedArrayLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxTypedArrayLength, 0)

  for (let i = 0, n = typedArray.length; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(typedArray.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(inspectValue(typedArray[i], depth + 1, opts))
  }

  for (const key of binding.getOwnNonIndexPropertyNames(typedArray)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(typedArray[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = typedArray.constructor.name + '(' + typedArray.length + ') [ '

  return new InspectSequence(header, ' ]', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectBuffer(buffer, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxBufferLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxBufferLength, 0)

  for (let i = 0, n = buffer.byteLength; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(buffer.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(
      new InspectLeaf(
        buffer[i].toString(16).padStart(2, '0'),
        null,
        depth + 1,
        opts
      )
    )
  }

  for (const key of binding.getOwnNonIndexPropertyNames(buffer)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(buffer[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  return new InspectSequence('<Buffer ', '>', ' ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectDataView(dataView, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength', 'byteOffset', 'buffer']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(dataView[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key of binding.getOwnNonIndexPropertyNames(dataView)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(dataView[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = dataView.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectFunction(type, fn, depth, opts) {
  if (fn.toString().startsWith('class')) return inspectClass(fn, depth, opts)

  let tag = 'function'

  if (type.isGeneratorFunction()) tag = 'generator ' + tag
  if (type.isAsyncFunction()) tag = 'async ' + tag

  return new InspectLeaf(
    '[' + tag + ' ' + (fn.name ? fn.name : '(anonymous)') + ']',
    styles.special,
    depth,
    opts
  )
}

function inspectClass(ctor, depth, opts) {
  return new InspectLeaf(
    '[class ' + (ctor.name ? ctor.name : '(anonymous)') + ']',
    styles.special,
    depth,
    opts
  )
}

function inspectExternal(external, depth, opts) {
  return new InspectLeaf(
    '[external 0x' + binding.getExternal(external).toString(16) + ']',
    styles.special,
    depth,
    opts
  )
}
{
  "name": "bare-inspect",
  "version": "3.1.4",
  "description": "Inspect objects as strings for debugging",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-inspect.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-inspect/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-inspect#readme",
  "engines": {
    "bare": ">=1.18.0"
  },
  "dependencies": {
    "bare-ansi-escapes": "^2.1.0",
    "bare-type": "^1.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
module.exports = require.addon()
const binding = require('./binding')
const errors = require('./lib/errors')
const constants = require('./lib/constants')

exports.constants = constants
exports.errors = errors

exports.EOL = binding.platform === 'win32' ? '\r\n' : '\n'

exports.devNull = binding.platform === 'win32' ? '\\\\.\\nul' : '/dev/null'

exports.platform = function platform() {
  return binding.platform
}

exports.arch = function arch() {
  return binding.arch
}

exports.type = function type() {
  return binding.type()
}

exports.version = function version() {
  return binding.version()
}

exports.release = function release() {
  return binding.release()
}

exports.machine = function machine() {
  return binding.machine()
}

exports.execPath = function execPath() {
  return binding.execPath()
}

exports.pid = function pid() {
  return binding.pid()
}

exports.ppid = function ppid() {
  return binding.ppid()
}

exports.cwd = function cwd() {
  return binding.cwd()
}

exports.chdir = function chdir(dir) {
  validateString(dir, 'Directory')

  binding.chdir(dir)
}

exports.tmpdir = function tmpdir() {
  return binding.tmpdir()
}

exports.homedir = function homedir() {
  return binding.homedir()
}

exports.hostname = function hostname() {
  return binding.hostname()
}

exports.userInfo = function userInfo(uid) {
  if (uid !== undefined) validateInteger(uid, 'User ID')

  return binding.userInfo(uid)
}

exports.groupInfo = function groupInfo(gid) {
  if (gid !== undefined) validateInteger(gid, 'Group ID')

  return binding.groupInfo(gid)
}

exports.networkInterfaces = function networkInterfaces() {
  const result = {}

  for (const entry of binding.networkInterfaces()) {
    const { name, ...properties } = entry

    if (result[name]) result[name].push(properties)
    else result[name] = [properties]
  }

  return result
}

exports.kill = function kill(pid, signal = constants.signals.SIGTERM) {
  validateInteger(pid, 'Process ID')

  if (typeof signal === 'string') {
    if (signal in constants.signals === false) {
      throw errors.UNKNOWN_SIGNAL('Unknown signal: ' + signal)
    }

    signal = constants.signals[signal]
  } else {
    validateInteger(signal, 'Signal')
  }

  binding.kill(pid, signal)
}

exports.endianness = function endianness() {
  return binding.isLittleEndian ? 'LE' : 'BE'
}

exports.availableParallelism = function availableParallelism() {
  return binding.availableParallelism()
}

exports.cpuUsage = function cpuUsage(previous) {
  const current = binding.cpuUsage()

  if (previous) {
    return {
      user: current.user - previous.user,
      system: current.system - previous.system
    }
  }

  return current
}

exports.threadCpuUsage = function threadCpuUsage(previous) {
  const current = binding.threadCpuUsage()

  if (previous) {
    return {
      user: current.user - previous.user,
      system: current.system - previous.system
    }
  }

  return current
}

exports.resourceUsage = function resourceUsage() {
  return binding.resourceUsage()
}

exports.memoryUsage = function memoryUsage() {
  return binding.memoryUsage()
}

exports.freemem = function freemem() {
  return binding.freemem()
}

exports.totalmem = function totalmem() {
  return binding.totalmem()
}

exports.availableMemory = function availableMemory() {
  return binding.availableMemory()
}

exports.constrainedMemory = function constrainedMemory() {
  return binding.constrainedMemory()
}

exports.uptime = function uptime() {
  return binding.uptime()
}

exports.loadavg = function loadavg() {
  return binding.loadavg()
}

exports.cpus = function cpus() {
  return binding.cpus()
}

exports.getProcessTitle = function getProcessTitle() {
  return binding.getProcessTitle()
}

exports.setProcessTitle = function setProcessTitle(title) {
  if (typeof title !== 'string') title = title.toString()

  if (title.length >= 256) {
    throw errors.TITLE_OVERFLOW('Process title is too long')
  }

  binding.setProcessTitle(title)
}

exports.getPriority = function getPriority(pid = 0) {
  validateInteger(pid, 'Process ID')

  return binding.getPriority(pid)
}

exports.setPriority = function setPriority(pid, priority) {
  if (priority === undefined) {
    priority = pid
    pid = 0
  }

  validateInteger(pid, 'Process ID')
  validateInteger(priority, 'Priority')

  binding.setPriority(pid, priority)
}

exports.getEnvKeys = function getEnvKeys() {
  return binding.getEnvKeys()
}

exports.getEnv = function getEnv(name) {
  validateString(name, 'Name')

  return binding.getEnv(name)
}

exports.hasEnv = function hasEnv(name) {
  validateString(name, 'Name')

  return binding.hasEnv(name)
}

exports.setEnv = function setEnv(name, value) {
  validateString(name, 'Name')
  validateString(value, 'Value')

  binding.setEnv(name, value)
}

exports.unsetEnv = function unsetEnv(name) {
  validateString(name, 'Name')

  binding.unsetEnv(name)
}

function validateString(value, name) {
  if (typeof value !== 'string') {
    throw new TypeError(`${name} must be a string. Received type ${typeof value} (${value})`)
  }
}

function validateInteger(value, name) {
  if (!Number.isInteger(value)) {
    throw new TypeError(`${name} must be an integer. Received type ${typeof value} (${value})`)
  }
}
const binding = require('../binding')

module.exports = {
  signals: binding.signals,
  errnos: binding.errnos,
  priority: binding.priority
}
module.exports = class OSError extends Error {
  constructor(msg, fn = OSError, code = fn.name) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'OSError'
  }

  static UNKNOWN_SIGNAL(msg) {
    return new OSError(msg, OSError.UNKNOWN_SIGNAL)
  }

  static TITLE_OVERFLOW(msg) {
    return new OSError(msg, OSError.TITLE_OVERFLOW)
  }
}
{
  "name": "bare-os",
  "version": "3.9.3",
  "description": "Operating system utilities for Bare",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    },
    "./errors": {
      "types": "./lib/errors.d.ts",
      "default": "./lib/errors.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-os.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-os/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-os#readme",
  "engines": {
    "bare": ">=1.14.0"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "cmake-bare": "^1.1.6",
    "lunte": "^1.6.0",
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
// This export SHOULD NOT be shortened in any way as having the full
// `module.exports = require(...)` statement is crucial for synthesizing
// ESM exports.

if (Bare.platform === 'win32') {
  module.exports = require('./lib/win32')
} else {
  module.exports = require('./lib/posix')
}
module.exports = {
  CHAR_UPPERCASE_A: 0x41,
  CHAR_LOWERCASE_A: 0x61,
  CHAR_UPPERCASE_Z: 0x5a,
  CHAR_LOWERCASE_Z: 0x7a,
  CHAR_DOT: 0x2e,
  CHAR_FORWARD_SLASH: 0x2f,
  CHAR_BACKWARD_SLASH: 0x5c,
  CHAR_COLON: 0x3a,
  CHAR_QUESTION_MARK: 0x3f
}
const os = require('bare-os')

const { normalizeString } = require('./shared')
const { CHAR_DOT, CHAR_FORWARD_SLASH } = require('./constants')

function isPosixPathSeparator(code) {
  return code === CHAR_FORWARD_SLASH
}

exports.win32 = require('./win32')
exports.posix = exports

exports.sep = '/'
exports.delimiter = ':'

exports.resolve = function resolve(...args) {
  let resolvedPath = ''
  let resolvedAbsolute = false

  for (let i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) {
    const path = i >= 0 ? args[i] : os.cwd()

    if (path.length === 0) {
      continue
    }

    resolvedPath = `${path}/${resolvedPath}`
    resolvedAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH
  }

  resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute, '/', isPosixPathSeparator)

  if (resolvedAbsolute) {
    return `/${resolvedPath}`
  }

  return resolvedPath.length > 0 ? resolvedPath : '.'
}

exports.normalize = function normalize(path) {
  if (path.length === 0) return '.'

  const isAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH
  const trailingSeparator = path.charCodeAt(path.length - 1) === CHAR_FORWARD_SLASH

  path = normalizeString(path, !isAbsolute, '/', isPosixPathSeparator)

  if (path.length === 0) {
    if (isAbsolute) return '/'
    return trailingSeparator ? './' : '.'
  }

  if (trailingSeparator) path += '/'

  return isAbsolute ? `/${path}` : path
}

exports.isAbsolute = function isAbsolute(path) {
  return path.length > 0 && path.charCodeAt(0) === CHAR_FORWARD_SLASH
}

exports.join = function join(...args) {
  if (args.length === 0) return '.'
  let joined
  for (let i = 0; i < args.length; ++i) {
    const arg = args[i]
    if (arg.length > 0) {
      if (joined === undefined) joined = arg
      else joined += `/${arg}`
    }
  }
  if (joined === undefined) return '.'
  return exports.normalize(joined)
}

exports.relative = function relative(from, to) {
  if (from === to) return ''

  from = exports.resolve(from)
  to = exports.resolve(to)

  if (from === to) return ''

  const fromStart = 1
  const fromEnd = from.length
  const fromLen = fromEnd - fromStart
  const toStart = 1
  const toLen = to.length - toStart

  const length = fromLen < toLen ? fromLen : toLen
  let lastCommonSep = -1
  let i = 0
  for (; i < length; i++) {
    const fromCode = from.charCodeAt(fromStart + i)
    if (fromCode !== to.charCodeAt(toStart + i)) {
      break
    } else if (fromCode === CHAR_FORWARD_SLASH) {
      lastCommonSep = i
    }
  }
  if (i === length) {
    if (toLen > length) {
      if (to.charCodeAt(toStart + i) === CHAR_FORWARD_SLASH) {
        return to.substring(toStart + i + 1)
      }
      if (i === 0) {
        return to.substring(toStart + i)
      }
    } else if (fromLen > length) {
      if (from.charCodeAt(fromStart + i) === CHAR_FORWARD_SLASH) {
        lastCommonSep = i
      } else if (i === 0) {
        lastCommonSep = 0
      }
    }
  }

  let out = ''
  for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
    if (i === fromEnd || from.charCodeAt(i) === CHAR_FORWARD_SLASH) {
      out += out.length === 0 ? '..' : '/..'
    }
  }

  return `${out}${to.substring(toStart + lastCommonSep)}`
}

exports.toNamespacedPath = function toNamespacedPath(path) {
  return path
}

exports.dirname = function dirname(path) {
  if (path.length === 0) return '.'
  const hasRoot = path.charCodeAt(0) === CHAR_FORWARD_SLASH
  let end = -1
  let matchedSlash = true
  for (let i = path.length - 1; i >= 1; --i) {
    if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) {
      if (!matchedSlash) {
        end = i
        break
      }
    } else {
      matchedSlash = false
    }
  }

  if (end === -1) return hasRoot ? '/' : '.'
  if (hasRoot && end === 1) return '//'
  return path.substring(0, end)
}

exports.basename = function basename(path, suffix) {
  let start = 0
  let end = -1
  let matchedSlash = true

  if (suffix !== undefined && suffix.length > 0 && suffix.length <= path.length) {
    if (suffix === path) {
      return ''
    }
    let extIdx = suffix.length - 1
    let firstNonSlashEnd = -1
    for (let i = path.length - 1; i >= 0; --i) {
      const code = path.charCodeAt(i)
      if (code === CHAR_FORWARD_SLASH) {
        if (!matchedSlash) {
          start = i + 1
          break
        }
      } else {
        if (firstNonSlashEnd === -1) {
          matchedSlash = false
          firstNonSlashEnd = i + 1
        }
        if (extIdx >= 0) {
          if (code === suffix.charCodeAt(extIdx)) {
            if (--extIdx === -1) {
              end = i
            }
          } else {
            extIdx = -1
            end = firstNonSlashEnd
          }
        }
      }
    }

    if (start === end) end = firstNonSlashEnd
    else if (end === -1) end = path.length
    return path.substring(start, end)
  }

  for (let i = path.length - 1; i >= 0; --i) {
    if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) {
      if (!matchedSlash) {
        start = i + 1
        break
      }
    } else if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
  }

  if (end === -1) return ''
  return path.substring(start, end)
}

exports.extname = function extname(path) {
  let startDot = -1
  let startPart = 0
  let end = -1
  let matchedSlash = true
  let preDotState = 0
  for (let i = path.length - 1; i >= 0; --i) {
    const code = path.charCodeAt(i)
    if (code === CHAR_FORWARD_SLASH) {
      if (!matchedSlash) {
        startPart = i + 1
        break
      }
      continue
    }
    if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
    if (code === CHAR_DOT) {
      if (startDot === -1) startDot = i
      else if (preDotState !== 1) preDotState = 1
    } else if (startDot !== -1) {
      preDotState = -1
    }
  }

  if (
    startDot === -1 ||
    end === -1 ||
    preDotState === 0 ||
    (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1)
  ) {
    return ''
  }
  return path.substring(startDot, end)
}
const { CHAR_DOT, CHAR_FORWARD_SLASH } = require('./constants')

exports.normalizeString = function normalizeString(
  path,
  allowAboveRoot,
  separator,
  isPathSeparator
) {
  let res = ''
  let lastSegmentLength = 0
  let lastSlash = -1
  let dots = 0
  let code = 0
  for (let i = 0; i <= path.length; ++i) {
    if (i < path.length) {
      code = path.charCodeAt(i)
    } else if (isPathSeparator(code)) {
      break
    } else {
      code = CHAR_FORWARD_SLASH
    }

    if (isPathSeparator(code)) {
      if (lastSlash === i - 1 || dots === 1);
      else if (dots === 2) {
        if (
          res.length < 2 ||
          lastSegmentLength !== 2 ||
          res.charCodeAt(res.length - 1) !== CHAR_DOT ||
          res.charCodeAt(res.length - 2) !== CHAR_DOT
        ) {
          if (res.length > 2) {
            const lastSlashIndex = res.lastIndexOf(separator)
            if (lastSlashIndex === -1) {
              res = ''
              lastSegmentLength = 0
            } else {
              res = res.substring(0, lastSlashIndex)
              lastSegmentLength = res.length - 1 - res.lastIndexOf(separator)
            }
            lastSlash = i
            dots = 0
            continue
          } else if (res.length !== 0) {
            res = ''
            lastSegmentLength = 0
            lastSlash = i
            dots = 0
            continue
          }
        }
        if (allowAboveRoot) {
          res += res.length > 0 ? `${separator}..` : '..'
          lastSegmentLength = 2
        }
      } else {
        if (res.length > 0) {
          res += `${separator}${path.substring(lastSlash + 1, i)}`
        } else {
          res = path.substring(lastSlash + 1, i)
        }
        lastSegmentLength = i - lastSlash - 1
      }
      lastSlash = i
      dots = 0
    } else if (code === CHAR_DOT && dots !== -1) {
      ++dots
    } else {
      dots = -1
    }
  }
  return res
}
const os = require('bare-os')

const { normalizeString } = require('./shared')
const {
  CHAR_UPPERCASE_A,
  CHAR_LOWERCASE_A,
  CHAR_UPPERCASE_Z,
  CHAR_LOWERCASE_Z,
  CHAR_DOT,
  CHAR_FORWARD_SLASH,
  CHAR_BACKWARD_SLASH,
  CHAR_COLON,
  CHAR_QUESTION_MARK
} = require('./constants')

function isWindowsPathSeparator(code) {
  return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH
}

function isWindowsDeviceRoot(code) {
  return (
    (code >= CHAR_UPPERCASE_A && code <= CHAR_UPPERCASE_Z) ||
    (code >= CHAR_LOWERCASE_A && code <= CHAR_LOWERCASE_Z)
  )
}

exports.posix = require('./posix')
exports.win32 = exports

exports.sep = '\\'
exports.delimiter = ';'

exports.resolve = function resolve(...args) {
  let resolvedDevice = ''
  let resolvedTail = ''
  let resolvedAbsolute = false

  for (let i = args.length - 1; i >= -1; i--) {
    let path
    if (i >= 0) {
      path = args[i]

      if (path.length === 0) continue
    } else if (resolvedDevice.length === 0) {
      path = os.cwd()
    } else {
      path = os.getEnv(`=${resolvedDevice}`) || os.cwd()

      if (
        path === undefined ||
        (path.substring(0, 2).toLowerCase() !== resolvedDevice.toLowerCase() &&
          path.charCodeAt(2) === CHAR_BACKWARD_SLASH)
      ) {
        path = `${resolvedDevice}\\`
      }
    }

    const len = path.length
    let rootEnd = 0
    let device = ''
    let isAbsolute = false
    const code = path.charCodeAt(0)

    if (len === 1) {
      if (isWindowsPathSeparator(code)) {
        rootEnd = 1
        isAbsolute = true
      }
    } else if (isWindowsPathSeparator(code)) {
      isAbsolute = true

      if (isWindowsPathSeparator(path.charCodeAt(1))) {
        let j = 2
        let last = j
        while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
          j++
        }
        if (j < len && j !== last) {
          const firstPart = path.substring(last, j)
          last = j
          while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
            j++
          }
          if (j < len && j !== last) {
            last = j
            while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
              j++
            }
            if (j === len || j !== last) {
              device = `\\\\${firstPart}\\${path.substring(last, j)}`
              rootEnd = j
            }
          }
        }
      } else {
        rootEnd = 1
      }
    } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
      device = path.substring(0, 2)
      rootEnd = 2
      if (len > 2 && isWindowsPathSeparator(path.charCodeAt(2))) {
        isAbsolute = true
        rootEnd = 3
      }
    }

    if (device.length > 0) {
      if (resolvedDevice.length > 0) {
        if (device.toLowerCase() !== resolvedDevice.toLowerCase()) {
          continue
        }
      } else {
        resolvedDevice = device
      }
    }

    if (resolvedAbsolute) {
      if (resolvedDevice.length > 0) {
        break
      }
    } else {
      resolvedTail = `${path.substring(rootEnd)}\\${resolvedTail}`
      resolvedAbsolute = isAbsolute
      if (isAbsolute && resolvedDevice.length > 0) {
        break
      }
    }
  }

  resolvedTail = normalizeString(resolvedTail, !resolvedAbsolute, '\\', isWindowsPathSeparator)

  return resolvedAbsolute
    ? `${resolvedDevice}\\${resolvedTail}`
    : `${resolvedDevice}${resolvedTail}` || '.'
}

exports.normalize = function normalize(path) {
  const len = path.length
  if (len === 0) return '.'
  let rootEnd = 0
  let device
  let isAbsolute = false
  const code = path.charCodeAt(0)

  if (len === 1) {
    return code === CHAR_FORWARD_SLASH ? '\\' : path
  }

  if (isWindowsPathSeparator(code)) {
    isAbsolute = true

    if (isWindowsPathSeparator(path.charCodeAt(1))) {
      let j = 2
      let last = j
      while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
        j++
      }
      if (j < len && j !== last) {
        const firstPart = path.substring(last, j)
        last = j
        while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
          j++
        }
        if (j < len && j !== last) {
          last = j
          while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
            j++
          }
          if (j === len) {
            return `\\\\${firstPart}\\${path.substring(last)}\\`
          }
          if (j !== last) {
            device = `\\\\${firstPart}\\${path.substring(last, j)}`
            rootEnd = j
          }
        }
      }
    } else {
      rootEnd = 1
    }
  } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
    device = path.substring(0, 2)
    rootEnd = 2
    if (len > 2 && isWindowsPathSeparator(path.charCodeAt(2))) {
      isAbsolute = true
      rootEnd = 3
    }
  }

  let tail =
    rootEnd < len
      ? normalizeString(path.substring(rootEnd), !isAbsolute, '\\', isWindowsPathSeparator)
      : ''
  if (tail.length === 0 && !isAbsolute) {
    tail = '.'
  }
  if (tail.length > 0 && isWindowsPathSeparator(path.charCodeAt(len - 1))) {
    tail += '\\'
  }
  if (device === undefined) {
    return isAbsolute ? `\\${tail}` : tail
  }
  return isAbsolute ? `${device}\\${tail}` : `${device}${tail}`
}

exports.isAbsolute = function isAbsolute(path) {
  const len = path.length
  if (len === 0) return false

  const code = path.charCodeAt(0)

  return (
    isWindowsPathSeparator(code) ||
    (len > 2 &&
      isWindowsDeviceRoot(code) &&
      path.charCodeAt(1) === CHAR_COLON &&
      isWindowsPathSeparator(path.charCodeAt(2)))
  )
}

exports.join = function join(...args) {
  if (args.length === 0) return '.'

  let joined
  let firstPart
  for (let i = 0; i < args.length; ++i) {
    const arg = args[i]
    if (arg.length > 0) {
      if (joined === undefined) joined = firstPart = arg
      else joined += `\\${arg}`
    }
  }

  if (joined === undefined) return '.'

  let needsReplace = true
  let slashCount = 0
  if (isWindowsPathSeparator(firstPart.charCodeAt(0))) {
    ++slashCount
    const firstLen = firstPart.length
    if (firstLen > 1 && isWindowsPathSeparator(firstPart.charCodeAt(1))) {
      ++slashCount
      if (firstLen > 2) {
        if (isWindowsPathSeparator(firstPart.charCodeAt(2))) {
          ++slashCount
        } else {
          needsReplace = false
        }
      }
    }
  }
  if (needsReplace) {
    while (slashCount < joined.length && isWindowsPathSeparator(joined.charCodeAt(slashCount))) {
      slashCount++
    }

    if (slashCount >= 2) {
      joined = `\\${joined.substring(slashCount)}`
    }
  }

  return exports.normalize(joined)
}

exports.relative = function relative(from, to) {
  if (from === to) return ''

  const fromOrig = exports.resolve(from)
  const toOrig = exports.resolve(to)

  if (fromOrig === toOrig) return ''

  from = fromOrig.toLowerCase()
  to = toOrig.toLowerCase()

  if (from === to) return ''

  let fromStart = 0
  while (fromStart < from.length && from.charCodeAt(fromStart) === CHAR_BACKWARD_SLASH) {
    fromStart++
  }
  let fromEnd = from.length
  while (fromEnd - 1 > fromStart && from.charCodeAt(fromEnd - 1) === CHAR_BACKWARD_SLASH) {
    fromEnd--
  }
  const fromLen = fromEnd - fromStart

  let toStart = 0
  while (toStart < to.length && to.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) {
    toStart++
  }
  let toEnd = to.length
  while (toEnd - 1 > toStart && to.charCodeAt(toEnd - 1) === CHAR_BACKWARD_SLASH) {
    toEnd--
  }
  const toLen = toEnd - toStart

  const length = fromLen < toLen ? fromLen : toLen
  let lastCommonSep = -1
  let i = 0
  for (; i < length; i++) {
    const fromCode = from.charCodeAt(fromStart + i)
    if (fromCode !== to.charCodeAt(toStart + i)) {
      break
    } else if (fromCode === CHAR_BACKWARD_SLASH) {
      lastCommonSep = i
    }
  }

  if (i !== length) {
    if (lastCommonSep === -1) return toOrig
  } else {
    if (toLen > length) {
      if (to.charCodeAt(toStart + i) === CHAR_BACKWARD_SLASH) {
        return toOrig.substring(toStart + i + 1)
      }
      if (i === 2) {
        return toOrig.substring(toStart + i)
      }
    }
    if (fromLen > length) {
      if (from.charCodeAt(fromStart + i) === CHAR_BACKWARD_SLASH) {
        lastCommonSep = i
      } else if (i === 2) {
        lastCommonSep = 3
      }
    }
    if (lastCommonSep === -1) lastCommonSep = 0
  }

  let out = ''
  for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
    if (i === fromEnd || from.charCodeAt(i) === CHAR_BACKWARD_SLASH) {
      out += out.length === 0 ? '..' : '\\..'
    }
  }

  toStart += lastCommonSep

  if (out.length > 0) {
    return `${out}${toOrig.substring(toStart, toEnd)}`
  }
  if (toOrig.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) {
    ++toStart
  }
  return toOrig.substring(toStart, toEnd)
}

exports.toNamespacedPath = function toNamespacedPath(path) {
  if (path.length === 0) return path

  const resolvedPath = exports.resolve(path)

  if (resolvedPath.length <= 2) return path

  if (resolvedPath.charCodeAt(0) === CHAR_BACKWARD_SLASH) {
    if (resolvedPath.charCodeAt(1) === CHAR_BACKWARD_SLASH) {
      const code = resolvedPath.charCodeAt(2)
      if (code !== CHAR_QUESTION_MARK && code !== CHAR_DOT) {
        return `\\\\?\\UNC\\${resolvedPath.substring(2)}`
      }
    }
  } else if (
    isWindowsDeviceRoot(resolvedPath.charCodeAt(0)) &&
    resolvedPath.charCodeAt(1) === CHAR_COLON &&
    resolvedPath.charCodeAt(2) === CHAR_BACKWARD_SLASH
  ) {
    return `\\\\?\\${resolvedPath}`
  }

  return path
}

exports.dirname = function dirname(path) {
  const len = path.length
  if (len === 0) return '.'
  let rootEnd = -1
  let offset = 0
  const code = path.charCodeAt(0)

  if (len === 1) {
    return isWindowsPathSeparator(code) ? path : '.'
  }

  if (isWindowsPathSeparator(code)) {
    rootEnd = offset = 1

    if (isWindowsPathSeparator(path.charCodeAt(1))) {
      let j = 2
      let last = j
      while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
        j++
      }
      if (j < len && j !== last) {
        last = j
        while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
          j++
        }
        if (j < len && j !== last) {
          last = j
          while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
            j++
          }
          if (j === len) {
            return path
          }
          if (j !== last) {
            rootEnd = offset = j + 1
          }
        }
      }
    }
  } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
    rootEnd = len > 2 && isWindowsPathSeparator(path.charCodeAt(2)) ? 3 : 2
    offset = rootEnd
  }

  let end = -1
  let matchedSlash = true
  for (let i = len - 1; i >= offset; --i) {
    if (isWindowsPathSeparator(path.charCodeAt(i))) {
      if (!matchedSlash) {
        end = i
        break
      }
    } else {
      matchedSlash = false
    }
  }

  if (end === -1) {
    if (rootEnd === -1) return '.'

    end = rootEnd
  }
  return path.substring(0, end)
}

exports.basename = function basename(path, suffix) {
  let start = 0
  let end = -1
  let matchedSlash = true

  if (
    path.length >= 2 &&
    isWindowsDeviceRoot(path.charCodeAt(0)) &&
    path.charCodeAt(1) === CHAR_COLON
  ) {
    start = 2
  }

  if (suffix !== undefined && suffix.length > 0 && suffix.length <= path.length) {
    if (suffix === path) return ''
    let extIdx = suffix.length - 1
    let firstNonSlashEnd = -1
    for (let i = path.length - 1; i >= start; --i) {
      const code = path.charCodeAt(i)
      if (isWindowsPathSeparator(code)) {
        if (!matchedSlash) {
          start = i + 1
          break
        }
      } else {
        if (firstNonSlashEnd === -1) {
          matchedSlash = false
          firstNonSlashEnd = i + 1
        }
        if (extIdx >= 0) {
          if (code === suffix.charCodeAt(extIdx)) {
            if (--extIdx === -1) {
              end = i
            }
          } else {
            extIdx = -1
            end = firstNonSlashEnd
          }
        }
      }
    }

    if (start === end) end = firstNonSlashEnd
    else if (end === -1) end = path.length
    return path.substring(start, end)
  }
  for (let i = path.length - 1; i >= start; --i) {
    if (isWindowsPathSeparator(path.charCodeAt(i))) {
      if (!matchedSlash) {
        start = i + 1
        break
      }
    } else if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
  }

  if (end === -1) return ''
  return path.substring(start, end)
}

exports.extname = function extname(path) {
  let start = 0
  let startDot = -1
  let startPart = 0
  let end = -1
  let matchedSlash = true
  let preDotState = 0

  if (
    path.length >= 2 &&
    path.charCodeAt(1) === CHAR_COLON &&
    isWindowsDeviceRoot(path.charCodeAt(0))
  ) {
    start = startPart = 2
  }

  for (let i = path.length - 1; i >= start; --i) {
    const code = path.charCodeAt(i)
    if (isWindowsPathSeparator(code)) {
      if (!matchedSlash) {
        startPart = i + 1
        break
      }
      continue
    }
    if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
    if (code === CHAR_DOT) {
      if (startDot === -1) startDot = i
      else if (preDotState !== 1) preDotState = 1
    } else if (startDot !== -1) {
      preDotState = -1
    }
  }

  if (
    startDot === -1 ||
    end === -1 ||
    preDotState === 0 ||
    (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1)
  ) {
    return ''
  }
  return path.substring(startDot, end)
}
{
  "name": "bare-path",
  "version": "3.0.1",
  "description": "Path manipulation library for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./posix": "./lib/posix.js",
    "./win32": "./lib/win32.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "lib",
    "NOTICE"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-path.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-path/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-path#readme",
  "dependencies": {
    "bare-os": "^3.0.1"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "lunte": "^1.8.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
const b4a = require('b4a')
const stream = require('streamx')
const { ReadableStream, WritableStream } = require('./web')

const defaultEncoding = 'utf8'

module.exports = exports = stream.Stream

exports.pipeline = stream.pipeline

exports.isStream = stream.isStream
exports.isEnding = stream.isEnding
exports.isEnded = stream.isEnded
exports.isFinishing = stream.isFinishing
exports.isFinished = stream.isFinished
exports.isDisturbed = stream.isDisturbed

exports.isErrored = function isErrored(stream) {
  return exports.getStreamError(stream) !== null
}

exports.isReadable = function isReadable(stream) {
  return stream.readable && !stream.destroying && !exports.isEnded(stream)
}

exports.isWritable = function isWritable(stream) {
  return stream.writable && !stream.destroying && !exports.isFinishing(stream)
}

exports.getStreamError = stream.getStreamError

exports.addAbortSignal = function addAbortSignal(signal, stream) {
  function onAbort() {
    stream.destroy(signal.reason)
  }

  if (signal.aborted) onAbort()
  else signal.addEventListener('abort', onAbort)

  return stream
}

exports.Stream = exports

exports.Readable = class Readable extends stream.Readable {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthReadable: null,
      map: null,
      mapReadable: null
    })

    if (this._construct) this._open = this._construct

    if (this._read !== stream.Readable.prototype._read) {
      this._read = read.bind(this, this._read)
    }

    if (this._destroy !== stream.Stream.prototype._destroy) {
      this._destroy = destroy.bind(this, this._destroy)
    }
  }

  get closed() {
    return !exports.isReadable(this)
  }

  get errored() {
    return stream.getStreamError(this)
  }

  push(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    return super.push(chunk)
  }

  unshift(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    super.unshift(chunk)
  }

  static fromWeb(readableStream, opts = {}) {
    const stream = readableStream._stream

    if (opts.encoding) stream.setEncoding(opts.encoding)
    if (opts.signal) exports.addAbortSignal(opts.signal, stream)

    return stream
  }

  static toWeb(readable, opts = {}) {
    return new ReadableStream(readable, opts.strategy)
  }

  async [Symbol.asyncDispose]() {
    if (!this.destroyed) this.destroy()

    await new Promise((resolve) => exports.finished(this, resolve))
  }
}

exports.Writable = class Writable extends stream.Writable {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthWritable,
      map: null,
      mapWritable: null
    })

    if (this._construct) this._open = this._construct

    if (this._write !== stream.Writable.prototype._write) {
      this._write = write.bind(this, this._write)
    }

    if (this._destroy !== stream.Stream.prototype._destroy) {
      this._destroy = destroy.bind(this, this._destroy)
    }
  }

  get closed() {
    return !exports.isWritable(this)
  }

  get errored() {
    return stream.getStreamError(this)
  }

  write(chunk, encoding, cb) {
    if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result = super.write({ chunk, encoding })

    if (cb) stream.Writable.drained(this).then(() => cb(null), cb)

    return result
  }

  end(chunk, encoding, cb) {
    if (typeof chunk === 'function') {
      cb = chunk
      chunk = null
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    } else {
      encoding = 'buffer'
    }

    const result =
      chunk !== undefined && chunk !== null ? super.end({ chunk, encoding }) : super.end()

    if (cb) this.once('finish', () => cb(null))

    return result
  }

  static fromWeb(writableStream, opts = {}) {
    const stream = writableStream._stream

    if (opts.signal) exports.addAbortSignal(opts.signal, stream)

    return stream
  }

  static toWeb(writable) {
    return new WritableStream(writable)
  }

  async [Symbol.asyncDispose]() {
    if (!this.destroyed) this.destroy()

    await new Promise((resolve) => exports.finished(this, resolve))
  }
}

exports.Duplex = class Duplex extends stream.Duplex {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthReadable: null,
      byteLengthWritable,
      map: null,
      mapReadable: null,
      mapWritable: null
    })

    if (this._construct) this._open = this._construct

    if (this._read !== stream.Readable.prototype._read) {
      this._read = read.bind(this, this._read)
    }

    if (this._write !== stream.Duplex.prototype._write) {
      this._write = write.bind(this, this._write)
    }

    if (this._destroy !== stream.Stream.prototype._destroy) {
      this._destroy = destroy.bind(this, this._destroy)
    }
  }

  push(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    return super.push(chunk)
  }

  unshift(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    super.unshift(chunk)
  }

  write(chunk, encoding, cb) {
    if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result = super.write({ chunk, encoding })

    if (cb) stream.Writable.drained(this).then(() => cb(null), cb)

    return result
  }

  end(chunk, encoding, cb) {
    if (typeof chunk === 'function') {
      cb = chunk
      chunk = null
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result =
      chunk !== undefined && chunk !== null ? super.end({ chunk, encoding }) : super.end()

    if (cb) this.once('finish', () => cb(null))

    return result
  }

  static fromWeb({ readable: readableStream, writable: writableStream }, opts) {
    const readable = exports.Readable.fromWeb(readableStream, opts)
    const writable = exports.Writable.fromWeb(writableStream, opts)

    const duplex = new exports.Duplex({
      write(data, encoding, cb) {
        writable.write(data, encoding, cb)
      }
    })

    readable
      .on('data', (data) => duplex.push(data))
      .on('end', () => duplex.push(null))
      .on('error', (err) => duplex.destroy(err))

    writable.on('finish', () => duplex.end()).on('error', (err) => duplex.destroy(err))

    return duplex
  }

  static toWeb(duplex) {
    const readableStream = exports.Readable.toWeb(duplex)
    const writableStream = exports.Writable.toWeb(duplex)

    return { readable: readableStream, writable: writableStream }
  }
}

class DuplexSide extends exports.Duplex {
  constructor(opts) {
    super(opts)

    this._otherSide = null
    this._cb = null
  }

  _read() {
    const cb = this._cb
    if (!cb) return

    this._cb = null
    cb()
  }

  _write(chunk, encoding, cb) {
    this._otherSide.push(chunk, encoding)
    this._otherSide._cb = cb
  }

  _final(cb) {
    this._otherSide.on('end', cb)
    this._otherSide.push(null)
  }
}

exports.duplexPair = function duplexPair(opts) {
  const sideA = new DuplexSide(opts)
  const sideB = new DuplexSide(opts)

  sideA._otherSide = sideB
  sideB._otherSide = sideA

  return [sideA, sideB]
}

exports.Transform = class Transform extends stream.Transform {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthReadable: null,
      byteLengthWritable,
      map: null,
      mapReadable: null,
      mapWritable: null
    })

    if (this._transform !== stream.Transform.prototype._transform) {
      this._transform = transform.bind(this, this._transform)
    } else {
      this._transform = passthrough
    }
  }

  push(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    return super.push(chunk)
  }

  unshift(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    super.unshift(chunk)
  }

  write(chunk, encoding, cb) {
    if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result = super.write({ chunk, encoding })

    if (cb) stream.Writable.drained(this).then(() => cb(null), cb)

    return result
  }

  end(chunk, encoding, cb) {
    if (typeof chunk === 'function') {
      cb = chunk
      chunk = null
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result =
      chunk !== undefined && chunk !== null ? super.end({ chunk, encoding }) : super.end()

    if (cb) this.once('finish', () => cb(null))

    return result
  }
}

exports.PassThrough = class PassThrough extends exports.Transform {}

exports.finished = function finished(stream, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (!opts) opts = {}

  const { cleanup = false } = opts

  const done = () => {
    cb(exports.getStreamError(stream, { all: true }))

    if (cleanup) detach()
  }

  const detach = () => {
    stream.off('close', done)
    stream.off('error', noop)
  }

  if (stream.destroyed) {
    done()
  } else {
    stream.on('close', done)
    stream.on('error', noop)
  }

  return detach
}

function read(read, cb) {
  read.call(this, 65536)

  cb(null)
}

function write(write, data, cb) {
  write.call(this, data.chunk, data.encoding, cb)
}

function transform(transform, data, cb) {
  transform.call(this, data.chunk, data.encoding, cb)
}

function destroy(destroy, cb) {
  destroy.call(this, exports.getStreamError(this), cb)
}

function passthrough(data, cb) {
  cb(null, data.chunk)
}

function byteLengthWritable(data) {
  return data.chunk.byteLength
}

function noop() {}
{
  "name": "bare-stream",
  "version": "2.13.3",
  "description": "Streaming data for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./promises": "./promises.js",
    "./web": {
      "types": "./web.d.ts",
      "default": "./web.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "promises.js",
    "web.js",
    "web.d.ts",
    "global.js",
    "global.d.ts"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-stream.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-stream/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-stream#readme",
  "dependencies": {
    "b4a": "^1.8.1",
    "streamx": "^2.25.0",
    "teex": "^1.0.1"
  },
  "devDependencies": {
    "bare-abort-controller": "^1.1.0",
    "bare-buffer": "^3.0.0",
    "bare-events": "^2.5.4",
    "brittle": "^3.5.2",
    "lunte": "^1.6.0",
    "prettier": "^3.3.3",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "bare-abort-controller": "*",
    "bare-buffer": "*",
    "bare-events": "*"
  },
  "peerDependenciesMeta": {
    "bare-abort-controller": {
      "optional": true
    },
    "bare-buffer": {
      "optional": true
    },
    "bare-events": {
      "optional": true
    }
  }
}
const { Readable, Writable, Transform, getStreamError, isStreamx, isDisturbed } = require('streamx')
const tee = require('teex')

const readableKind = Symbol.for('bare.stream.readable.kind')
const writableKind = Symbol.for('bare.stream.writable.kind')
const transformKind = Symbol.for('bare.stream.transform.kind')

// https://streams.spec.whatwg.org/#readablestreamdefaultreader
exports.ReadableStreamDefaultReader = class ReadableStreamDefaultReader {
  constructor(stream) {
    this._stream = stream
    this._stream._stream.once('close', onclose).once('error', onerror)

    const closed = Promise.withResolvers()

    // Avoid unhandled exceptions
    closed.promise.catch(noop)

    this._closed = closed

    function onclose() {
      closed.resolve()
    }

    function onerror(err) {
      closed.reject(err)
    }
  }

  get closed() {
    return this._closed.promise
  }

  read() {
    const stream = this._stream._stream

    return new Promise((resolve, reject) => {
      const err = getStreamError(stream)

      if (err) return reject(err)

      if (stream.destroyed) {
        return resolve({ value: undefined, done: true })
      }

      const value = stream.read()

      if (value !== null) {
        return resolve({ value, done: false })
      }

      stream.once('readable', onreadable).once('close', onclose).once('error', onerror)

      function onreadable() {
        const value = stream.read()

        ondone(null, value === null ? { value: undefined, done: true } : { value, done: false })
      }

      function onclose() {
        ondone(null, { value: undefined, done: true })
      }

      function onerror(err) {
        ondone(err, null)
      }

      function ondone(err, value) {
        stream.off('readable', onreadable).off('close', onclose).off('error', onerror)

        if (err) reject(err)
        else resolve(value)
      }
    })
  }

  releaseLock() {
    this._closed.reject(new TypeError('Reader was released'))
    this._stream._releaseLock()
    this._stream = null
  }

  cancel(reason = new TypeError('Stream was cancelled')) {
    const stream = this._stream._stream

    if (stream.destroyed) return Promise.resolve()

    return new Promise((resolve) =>
      stream.once('close', resolve).once('error', noop).destroy(reason)
    )
  }
}

// https://streams.spec.whatwg.org/#readablestreamdefaultcontroller
exports.ReadableStreamDefaultController = class ReadableStreamDefaultController {
  constructor(stream) {
    this._stream = stream
  }

  get desiredSize() {
    const stream = this._stream._stream

    return stream._readableState.highWaterMark - stream._readableState.buffered
  }

  enqueue(data) {
    this._stream._stream.push(data)
  }

  close() {
    this._stream._stream.push(null)
  }

  error(err) {
    this._stream._stream.destroy(err)
  }
}

// https://streams.spec.whatwg.org/#readablestream
class ReadableStream {
  static get [readableKind]() {
    return 0 // Compatibility version
  }

  static from(iterable) {
    return new ReadableStream(Readable.from(iterable))
  }

  constructor(underlyingSource = {}, queuingStrategy) {
    if (isStreamx(underlyingSource)) {
      this._stream = underlyingSource
    } else {
      if (queuingStrategy === undefined) {
        queuingStrategy = new exports.CountQueuingStrategy()
      }

      const { start, pull, cancel } = underlyingSource
      const { highWaterMark = 1, size = defaultSize } = queuingStrategy

      this._stream = new Readable({ highWaterMark, byteLength: size })

      const controller = new exports.ReadableStreamDefaultController(this)

      try {
        let starting = Promise.resolve()

        if (start) starting = forwardError(start.call(this, controller), controller)

        if (pull) {
          this._stream._read = this._read.bind(this, starting, pull.bind(this, controller))
        }

        if (cancel) {
          this._stream.once('error', cancel.bind(this))
        }
      } catch (err) {
        controller.error(err)
      }
    }

    this._reader = null
  }

  get [readableKind]() {
    return ReadableStream[readableKind]
  }

  get locked() {
    return this._reader !== null
  }

  getReader() {
    if (this.locked) throw new TypeError('Stream is locked')

    this._reader = new exports.ReadableStreamDefaultReader(this)

    return this._reader
  }

  cancel(reason = new TypeError('Stream was cancelled')) {
    const stream = this._stream

    if (stream.destroyed) return Promise.resolve()

    if (this.locked) return Promise.reject(new TypeError('Stream is locked'))

    return new Promise((resolve) =>
      stream.once('close', resolve).once('error', noop).destroy(reason)
    )
  }

  tee() {
    const [a, b] = tee(this._stream)

    return [new ReadableStream(a), new ReadableStream(b)]
  }

  pipeTo(destination) {
    return new Promise((resolve, reject) =>
      this._stream.pipe(destination._stream, (err) => {
        err ? reject(err) : resolve()
      })
    )
  }

  [Symbol.asyncIterator]() {
    return this._stream[Symbol.asyncIterator]()
  }

  _releaseLock() {
    this._reader = null
  }

  async _read(starting, pull, cb) {
    await starting

    let err = null
    try {
      await pull()
    } catch (e) {
      err = e
    }
    cb(err)
  }
}

function defaultSize() {
  return 1
}

exports.ReadableStream = ReadableStream

// https://streams.spec.whatwg.org/#countqueuingstrategy
exports.CountQueuingStrategy = class CountQueuingStrategy {
  constructor(opts = {}) {
    const { highWaterMark = 1 } = opts

    this.highWaterMark = highWaterMark
  }

  size(chunk) {
    return 1
  }
}

// https://streams.spec.whatwg.org/#bytelengthqueuingstrategy
exports.ByteLengthQueuingStrategy = class ByteLengthQueuingStrategy {
  constructor(opts = {}) {
    const { highWaterMark = 16384 } = opts

    this.highWaterMark = highWaterMark
  }

  size(chunk) {
    return chunk.byteLength
  }
}

exports.isReadableStream = function isReadableStream(value) {
  if (value instanceof ReadableStream) return true

  return (
    typeof value === 'object' &&
    value !== null &&
    value[readableKind] === ReadableStream[readableKind]
  )
}

// https://streams.spec.whatwg.org/#readablestream-errored
exports.isReadableStreamErrored = function isReadableStreamErrored(stream) {
  return getStreamError(stream._stream) !== null
}

// https://streams.spec.whatwg.org/#is-readable-stream-disturbed
exports.isReadableStreamDisturbed = function isReadableStreamDisturbed(stream) {
  return isDisturbed(stream._stream)
}

// https://streams.spec.whatwg.org/#writablestreamdefaultwriter
exports.WritableStreamDefaultWriter = class WritableStreamDefaultWriter {
  constructor(stream) {
    this._stream = stream
    this._stream._stream.once('close', onclose).once('error', onerror)

    const closed = Promise.withResolvers()

    // Avoid unhandled exceptions
    closed.promise.catch(noop)

    this._closed = closed

    function onclose() {
      closed.resolve()
    }

    function onerror(err) {
      closed.reject(err)
    }
  }

  get desiredSize() {
    const stream = this._stream._stream

    return stream._writableState.highWaterMark - stream._writableState.buffered
  }

  get closed() {
    return this._closed.promise
  }

  get ready() {
    const stream = this._stream._stream

    if (getStreamError(stream)) return Promise.reject()

    return Writable.drained(stream).then()
  }

  async write(chunk) {
    const stream = this._stream._stream

    let err = getStreamError(stream)
    if (err) return Promise.reject(err)

    stream.write(chunk)

    await Writable.drained(stream)

    err = getStreamError(stream)
    if (err) return Promise.reject(err)
  }

  releaseLock() {
    this._closed.reject(new TypeError('Writer was released'))
    this._stream._releaseLock()
    this._stream = null
  }

  close() {
    const stream = this._stream._stream

    if (stream.destroyed) return Promise.resolve()

    return new Promise((resolve) => stream.once('close', resolve).end())
  }

  abort(reason = new TypeError('Stream was aborted')) {
    const stream = this._stream._stream

    if (stream.destroyed) return Promise.resolve()

    return new Promise((resolve) => stream.once('close', resolve).destroy(reason))
  }
}

// https://streams.spec.whatwg.org/#writablestreamdefaultcontroller
exports.WritableStreamDefaultController = class WritableStreamDefaultController {
  constructor(stream) {
    this._stream = stream
  }

  error(err) {
    this._stream._stream.destroy(err)
  }
}

// https://streams.spec.whatwg.org/#writablestream
class WritableStream {
  static get [writableKind]() {
    return 0 // Compatibility version
  }

  constructor(underlyingSink = {}, queuingStrategy = {}) {
    if (isStreamx(underlyingSink)) {
      this._stream = underlyingSink
    } else {
      if (queuingStrategy === undefined) {
        queuingStrategy = new exports.CountQueuingStrategy()
      }

      const { start, write, close, abort } = underlyingSink
      const { highWaterMark = 1, size = defaultSize } = queuingStrategy

      this._stream = new Writable({ highWaterMark, byteLength: size })

      const controller = new exports.WritableStreamDefaultController(this)

      this._controller = controller

      try {
        let starting = Promise.resolve()

        if (start) starting = forwardError(start.call(this, controller), controller)

        if (write) {
          this._stream._write = this._write.bind(this, starting, write.bind(this))
        }

        if (close) {
          this._stream._destroy = this._destroy.bind(this, close.call(this))
        }

        if (abort) {
          this._stream.once('error', abort.bind(this))
        }
      } catch (err) {
        controller.error(err)
      }
    }

    this._writer = null
  }

  get [writableKind]() {
    return WritableStream[writableKind]
  }

  get locked() {
    return this._writer !== null
  }

  getWriter() {
    if (this.locked) throw new TypeError('Stream is locked')

    this._writer = new exports.WritableStreamDefaultWriter(this)

    return this._writer
  }

  abort(reason = new TypeError('Stream was aborted')) {
    if (this._stream.destroyed) return Promise.resolve()

    if (this.locked) return Promise.reject(new TypeError('Stream is locked'))

    return new Promise((resolve) => this._stream.once('close', resolve).destroy(reason))
  }

  close() {
    if (this._stream.destroyed) return Promise.resolve()

    if (this.locked) return Promise.reject(new TypeError('Stream is locked'))

    return new Promise((resolve) => this._stream.once('close', resolve).end())
  }

  _releaseLock() {
    this._writer = null
  }

  async _write(starting, write, data, cb) {
    await starting

    let err = null
    try {
      await write(data, this._controller)
    } catch (e) {
      err = e
    }
    cb(err)
  }

  async _destroy(closing, cb) {
    let err = null
    try {
      await closing
    } catch (e) {
      err = e
    }
    cb(err)
  }
}

exports.WritableStream = WritableStream

exports.isWritableStream = function isWritableStream(value) {
  if (value instanceof WritableStream) return true

  return (
    typeof value === 'object' &&
    value !== null &&
    value[writableKind] === WritableStream[writableKind]
  )
}

// https://streams.spec.whatwg.org/#transformstreamdefaultcontroller
exports.TransformStreamDefaultController = class TransformStreamDefaultController {
  constructor(stream) {
    this._stream = stream
  }

  get desiredSize() {
    const stream = this._stream._stream

    return stream._readableState.highWaterMark - stream._readableState.buffered
  }

  enqueue(data) {
    this._stream._stream.push(data)
  }

  error(err) {
    this._stream._stream.destroy(err)
  }

  terminate() {
    const stream = this._stream._stream

    stream.push(null)
    stream.destroy(new TypeError('Stream has been terminated'))
  }
}

// https://streams.spec.whatwg.org/#transformstream
class TransformStream {
  static get [transformKind]() {
    return 0 // Compatibility version
  }

  constructor(transformer = {}, writableStrategy = {}, readableStrategy = {}) {
    if (isStreamx(transformer)) {
      this._stream = transformer
    } else {
      const { start, transform, flush } = transformer

      this._stream = new Transform({ ...writableStrategy, ...readableStrategy })

      const controller = new exports.TransformStreamDefaultController(this)

      this._controller = controller

      try {
        let starting = Promise.resolve()

        if (start) starting = forwardError(start.call(this, controller), controller)

        if (transform) {
          this._stream._transform = this._transform.bind(this, starting, transform.bind(this))
        }

        if (flush) {
          this._stream._flush = this._flush.bind(this, flush.call(this, this._controller))
        }
      } catch (err) {
        controller.error(err)
      }
    }

    this._writable = new WritableStream(this._stream)
    this._readable = new ReadableStream(this._stream)
  }

  get [transformKind]() {
    return TransformStream[transformKind]
  }

  get writable() {
    return this._writable
  }

  get readable() {
    return this._readable
  }

  async _transform(starting, transform, data, cb) {
    await starting

    let err = null
    try {
      await transform(data, this._controller)
    } catch (e) {
      err = e
    }
    cb(err)
  }

  async _flush(flush, cb) {
    let err = null
    try {
      await flush
    } catch (e) {
      err = e
    }
    cb(err)
  }
}

exports.TransformStream = TransformStream

exports.isTransformStream = function isTransformStream(value) {
  if (value instanceof TransformStream) return true

  return (
    typeof value === 'object' &&
    value !== null &&
    value[transformKind] === TransformStream[transformKind]
  )
}

async function forwardError(promise, controller) {
  try {
    await promise
  } catch (err) {
    controller.error(err)
  }
}

function noop() {}
module.exports = require.addon()
const binding = require('./binding')

const t = binding.constants

class Type {
  constructor(type) {
    this._type = type
  }

  isUndefined() {
    return this._type === t.UNDEFINED
  }

  isNull() {
    return this._type === t.NULL
  }

  isBoolean() {
    return this._type === t.BOOLEAN
  }

  isNumber() {
    return (this._type & 0xff) === t.NUMBER
  }

  isInt32() {
    return (this._type & (0xff | t.INT32)) === (t.NUMBER | t.INT32)
  }

  isUint32() {
    return (this._type & (0xff | t.UINT32)) === (t.NUMBER | t.UINT32)
  }

  isString() {
    return this._type === t.STRING
  }

  isSymbol() {
    return this._type === t.SYMBOL
  }

  isObject() {
    return (this._type & 0xff) === t.OBJECT
  }

  isArray() {
    return this._type === (t.OBJECT | t.ARRAY)
  }

  isArguments() {
    return this._type === (t.OBJECT | t.ARGUMENTS)
  }

  isDate() {
    return this._type === (t.OBJECT | t.DATE)
  }

  isRegExp() {
    return this._type === (t.OBJECT | t.REGEXP)
  }

  isError() {
    return this._type === (t.OBJECT | t.ERROR)
  }

  isPromise() {
    return this._type === (t.OBJECT | t.PROMISE)
  }

  isProxy() {
    return this._type === (t.OBJECT | t.PROXY)
  }

  isGenerator() {
    return this._type === (t.OBJECT | t.GENERATOR)
  }

  isMap() {
    return this._type === (t.OBJECT | t.MAP)
  }

  isSet() {
    return this._type === (t.OBJECT | t.SET)
  }

  isWeakMap() {
    return this._type === (t.OBJECT | t.WEAK_MAP)
  }

  isWeakSet() {
    return this._type === (t.OBJECT | t.WEAK_SET)
  }

  isWeakRef() {
    return this._type === (t.OBJECT | t.WEAK_REF)
  }

  isArrayBuffer() {
    return this._type === (t.OBJECT | t.ARRAYBUFFER)
  }

  isSharedArrayBuffer() {
    return this._type === (t.OBJECT | t.SHAREDARRAYBUFFER)
  }

  isTypedArray() {
    return (this._type & 0xffff) === (t.OBJECT | t.TYPEDARRAY)
  }

  isInt8Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT8ARRAY)
  }

  isUint8Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT8ARRAY)
  }

  isUint8ClampedArray() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT8CLAMPEDARRAY)
  }

  isInt16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT16ARRAY)
  }

  isUint16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT16ARRAY)
  }

  isInt32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT32ARRAY)
  }

  isUint32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT32ARRAY)
  }

  isFloat16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT16ARRAY)
  }

  isFloat32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT32ARRAY)
  }

  isFloat64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT64ARRAY)
  }

  isBigInt64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.BIGINT64ARRAY)
  }

  isBigUint64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.BIGUINT64ARRAY)
  }

  isDataView() {
    return this._type === (t.OBJECT | t.DATAVIEW)
  }

  isModuleNamespace() {
    return this._type === (t.OBJECT | t.MODULE_NAMESPACE)
  }

  isFunction() {
    return (this._type & 0xff) === t.FUNCTION
  }

  isAsyncFunction() {
    return (
      (this._type & (0xff | t.ASYNC_FUNCTION)) ===
      (t.FUNCTION | t.ASYNC_FUNCTION)
    )
  }

  isGeneratorFunction() {
    return (
      (this._type & (0xff | t.GENERATOR_FUNCTION)) ===
      (t.FUNCTION | t.GENERATOR_FUNCTION)
    )
  }

  isExternal() {
    return this._type === t.EXTERNAL
  }

  isBigInt() {
    return this._type === t.BIGINT
  }
}

module.exports = exports = function type(value) {
  switch (typeof value) {
    case 'undefined':
      return new Type(t.UNDEFINED)
    case 'boolean':
      return new Type(t.BOOLEAN)
    case 'number':
      return new Type(
        Number.isSafeInteger(value) ? binding.type(value) : t.NUMBER
      )
    case 'string':
      return new Type(t.STRING)
    case 'symbol':
      return new Type(t.SYMBOL)
    case 'object':
      return new Type(value === null ? t.NULL : binding.type(value))
    case 'function':
      return new Type(binding.type(value))
    case 'bigint':
      return new Type(t.BIGINT)
  }
}

exports.createTag = function createTag(...components) {
  const tag = new Uint32Array(4)
  for (let i = 0; i < 4; i++) tag[i] = components[i] || 0
  return tag
}

exports.addTag = function addTag(object, tag) {
  binding.addTag(object, tag)
}

exports.checkTag = function checkTag(object, tag) {
  return binding.checkTag(object, tag)
}
{
  "name": "bare-type",
  "version": "1.1.0",
  "description": "Cross-realm type predicates for Bare",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-type.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-type/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-type#readme",
  "engines": {
    "bare": ">=1.2.0"
  },
  "devDependencies": {
    "brittle": "^3.4.0",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
module.exports = require.addon()
const path = require('bare-path')
const binding = require('./binding')
const errors = require('./lib/errors')
const URLSearchParams = require('./lib/url-search-params')

const kind = Symbol.for('bare.url.kind')

const isWindows = Bare.platform === 'win32'

class URL {
  static get [kind]() {
    return 0 // Compatibility version
  }

  constructor(input, base, opts = {}) {
    if (arguments.length === 0) throw errors.INVALID_URL()

    input = String(input)

    if (base !== undefined) base = String(base)

    this._components = new Uint32Array(8)

    this._parse(input, base, opts.throw !== false)

    if (this._href) this._params = new URLSearchParams(this.search, this)
  }

  get [kind]() {
    return URL[kind]
  }

  // https://url.spec.whatwg.org/#dom-url-href

  get href() {
    return this._href
  }

  set href(value) {
    this._update(value)

    this._params._parse(this.search)
  }

  // https://url.spec.whatwg.org/#dom-url-protocol

  get protocol() {
    return this._slice(0, this._components[0]) + ':'
  }

  set protocol(value) {
    this._update(this._replace(value.replace(/:+$/, ''), 0, this._components[0]))
  }

  // https://url.spec.whatwg.org/#dom-url-username

  get username() {
    return this._slice(this._components[0] + 3 /* :// */, this._components[1])
  }

  set username(value) {
    if (cannotHaveCredentialsOrPort(this)) {
      return
    }

    if (this.username === '') value += '@'

    this._update(this._replace(value, this._components[0] + 3 /* :// */, this._components[1]))
  }

  // https://url.spec.whatwg.org/#dom-url-password

  get password() {
    return this._href.slice(this._components[1] + 1 /* : */, this._components[2] - 1 /* @ */)
  }

  set password(value) {
    if (cannotHaveCredentialsOrPort(this)) {
      return
    }

    let start = this._components[1] + 1 /* : */
    let end = this._components[2] - 1 /* @ */

    if (this.password === '') {
      value = ':' + value
      start--
    }

    if (this.username === '') {
      value += '@'
      end++
    }

    this._update(this._replace(value, start, end))
  }

  // https://url.spec.whatwg.org/#dom-url-host

  get host() {
    return this._slice(this._components[2], this._components[5])
  }

  set host(value) {
    if (hasOpaquePath(this)) {
      return
    }

    this._update(
      this._replace(value, this._components[2], this._components[value.includes(':') ? 5 : 3])
    )
  }

  // https://url.spec.whatwg.org/#dom-url-hostname

  get hostname() {
    return this._slice(this._components[2], this._components[3])
  }

  set hostname(value) {
    if (hasOpaquePath(this)) {
      return
    }

    this._update(this._replace(value, this._components[2], this._components[3]))
  }

  // https://url.spec.whatwg.org/#dom-url-port

  get port() {
    return this._slice(this._components[3] + 1 /* : */, this._components[5])
  }

  set port(value) {
    if (cannotHaveCredentialsOrPort(this)) {
      return
    }

    let start = this._components[3] + 1 /* : */

    if (this.port === '') {
      value = ':' + value
      start--
    }

    this._update(this._replace(value, start, this._components[5]))
  }

  // https://url.spec.whatwg.org/#dom-url-pathname

  get pathname() {
    return this._slice(this._components[5], this._components[6] - 1 /* ? */)
  }

  set pathname(value) {
    if (hasOpaquePath(this)) {
      return
    }

    if (value[0] !== '/' && value[0] !== '\\') {
      value = '/' + value
    }

    this._update(this._replace(value, this._components[5], this._components[6] - 1 /* ? */))
  }

  // https://url.spec.whatwg.org/#dom-url-search

  get search() {
    return this._slice(this._components[6] - 1 /* ? */, this._components[7] - 1 /* # */)
  }

  set search(value) {
    if (value && value[0] !== '?') value = '?' + value

    this._update(
      this._replace(value, this._components[6] - 1 /* ? */, this._components[7] - 1 /* # */)
    )

    this._params._parse(this.search)
  }

  // https://url.spec.whatwg.org/#dom-url-searchparams

  get searchParams() {
    return this._params
  }

  // https://url.spec.whatwg.org/#dom-url-hash

  get hash() {
    return this._slice(this._components[7] - 1 /* # */)
  }

  set hash(value) {
    if (value && value[0] !== '#') value = '#' + value

    this._update(this._replace(value, this._components[7] - 1 /* # */))
  }

  toString() {
    return this._href
  }

  toJSON() {
    return this._href
  }

  [Symbol.for('bare.inspect')]() {
    return {
      __proto__: { constructor: URL },

      href: this.href,
      protocol: this.protocol,
      username: this.username,
      password: this.password,
      host: this.host,
      hostname: this.hostname,
      port: this.port,
      pathname: this.pathname,
      search: this.search,
      searchParams: this.searchParams,
      hash: this.hash
    }
  }

  _slice(start, end = this._href.length) {
    return this._href.slice(start, end)
  }

  _replace(replacement, start, end = this._href.length) {
    return this._slice(0, start) + replacement + this._slice(end)
  }

  _parse(input, base, shouldThrow) {
    try {
      this._href = binding.parse(
        String(input),
        base ? String(base) : null,
        this._components,
        shouldThrow
      )
    } catch (err) {
      if (err instanceof TypeError) throw err

      throw errors.INVALID_URL(`Invalid URL '${input}'`, input)
    }
  }

  _update(input) {
    try {
      this._parse(input, null, true)
    } catch (err) {
      if (err instanceof TypeError) throw err
    }
  }
}

module.exports = exports = URL

// https://url.spec.whatwg.org/#url-opaque-path
function hasOpaquePath(url) {
  return url.pathname[0] !== '/'
}

// https://url.spec.whatwg.org/#cannot-have-a-username-password-port
function cannotHaveCredentialsOrPort(url) {
  return url.hostname === '' || url.protocol === 'file:'
}

exports.URL = URL
exports.URLSearchParams = URLSearchParams

exports.errors = errors

exports.isURL = function isURL(value) {
  if (value instanceof URL) return true

  return typeof value === 'object' && value !== null && value[kind] === URL[kind]
}

exports.isURLSearchParams = URLSearchParams.isURLSearchParams

// https://url.spec.whatwg.org/#dom-url-parse
exports.parse = function parse(input, base) {
  const url = new URL(input, base, { throw: false })
  return url._href ? url : null
}

// https://url.spec.whatwg.org/#dom-url-canparse
exports.canParse = function canParse(input, base) {
  return binding.canParse(String(input), base ? String(base) : null)
}

exports.fileURLToPath = function fileURLToPath(url) {
  if (typeof url === 'string') {
    url = new URL(url)
  }

  if (url.protocol !== 'file:') {
    throw errors.INVALID_URL_SCHEME('The URL must use the file: protocol')
  }

  if (isWindows) {
    if (/%2f|%5c/i.test(url.pathname)) {
      throw errors.INVALID_FILE_URL_PATH(
        'The file: URL path must not include encoded \\ or / characters'
      )
    }
  } else {
    if (url.hostname) {
      throw errors.INVALID_FILE_URL_HOST("The file: URL host must be 'localhost' or empty")
    }

    if (/%2f/i.test(url.pathname)) {
      throw errors.INVALID_FILE_URL_PATH('The file: URL path must not include encoded / characters')
    }
  }

  if (/%00/i.test(url.pathname)) {
    throw errors.INVALID_FILE_URL_PATH('The file: URL path must not include encoded NUL characters')
  }

  const pathname = path.normalize(decodeURIComponent(url.pathname))

  if (isWindows) {
    if (url.hostname) return '\\\\' + url.hostname + pathname

    const letter = pathname.charCodeAt(1) | 0x20

    if (letter < 0x61 /* a */ || letter > 0x7a /* z */ || pathname.charCodeAt(2) !== 0x3a /* : */) {
      throw errors.INVALID_FILE_URL_PATH('The file: URL path must be absolute')
    }

    return pathname.slice(1)
  }

  return pathname
}

exports.pathToFileURL = function pathToFileURL(pathname) {
  let resolved = path.resolve(pathname)

  if (pathname[pathname.length - 1] === '/') {
    resolved += '/'
  } else if (isWindows && pathname[pathname.length - 1] === '\\') {
    resolved += '\\'
  }

  resolved = resolved
    .replaceAll('%', '%25') // Must be first
    .replaceAll('#', '%23')
    .replaceAll('?', '%3f')
    .replaceAll('\n', '%0a')
    .replaceAll('\r', '%0d')
    .replaceAll('\t', '%09')

  if (!isWindows) {
    resolved = resolved.replaceAll('\\', '%5c')
  }

  return new URL('file:' + resolved)
}

exports.format = function format(parts) {
  const { protocol, auth, host, hostname, port, pathname, search, query, hash, slashes } = parts

  let result = ''

  if (typeof protocol === 'string') {
    result += protocol

    if (protocol[protocol.length - 1] !== ':') {
      result += ':'
    }

    if (slashes === true || /https?|ftp|gopher|file/.test(protocol)) {
      result += '//'
    }
  }

  if (typeof auth === 'string') {
    if (host || hostname) result += auth + '@'
  }

  if (typeof host === 'string') result += host
  else {
    result += hostname

    if (port) result += ':' + port
  }

  if (typeof pathname === 'string' && pathname !== '') {
    if (pathname[0] !== '/') result += '/'
    result += pathname
  }

  if (typeof search === 'string') {
    if (search[0] !== '?') result += '?'
    result += search
  } else if (typeof query === 'object' && query !== null) {
    result += '?' + new URLSearchParams(query)
  }

  if (typeof hash === 'string') {
    if (hash[0] !== '#') result += '#'
    result += hash
  }

  return result
}
module.exports = class URLError extends Error {
  constructor(msg, fn = URLError, code = fn.name) {
    super(`${code}: ${msg}`)

    this.code = code

    if (Error.captureStackTrace) Error.captureStackTrace(this, fn)
  }

  get name() {
    return 'URLError'
  }

  static INVALID_URL(msg, input) {
    const err = new URLError(msg, URLError.INVALID_URL)

    err.input = input

    return err
  }

  static INVALID_URL_SCHEME(msg = 'Invalid URL') {
    return new URLError(msg, URLError.INVALID_URL_SCHEME)
  }

  static INVALID_FILE_URL_HOST(msg = 'Invalid file: URL host') {
    return new URLError(msg, URLError.INVALID_FILE_URL_HOST)
  }

  static INVALID_FILE_URL_PATH(msg = 'Invalid file: URL path') {
    return new URLError(msg, URLError.INVALID_FILE_URL_PATH)
  }
}
const kind = Symbol.for('bare.url.search-params.kind')

class URLSearchParams {
  static _urls = new WeakMap()

  static get [kind]() {
    return 0 // Compatibility version
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-urlsearchparams
  constructor(init, url = null) {
    this._params = new Map()

    if (url) URLSearchParams._urls.set(this, url)

    if (typeof init === 'string') {
      this._parse(init)
    } else if (init) {
      for (const [name, value] of typeof init[Symbol.iterator] === 'function'
        ? init
        : Object.entries(init)) {
        this.append(name, value)
      }
    }
  }

  get [kind]() {
    return URLSearchParams[kind]
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-size
  get size() {
    return this._params.length
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-append
  append(name, value = null) {
    if (value === null) return

    let list = this._params.get(name)

    if (list === undefined) {
      list = []
      this._params.set(name, list)
    }

    list.push(value)

    this._update()
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-delete
  delete(name, value = null) {
    if (value === null) this._params.delete(name)
    else {
      let list = this._params.get(name)

      if (list === undefined) return

      list = list.filter((found) => found !== value)

      if (list.length === 0) this._params.delete(name)
      else this._params.set(name, list)
    }

    this._update()
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-get
  get(name) {
    const list = this._params.get(name)

    if (list === undefined) return null

    return list[0]
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-getall
  getAll(name) {
    const list = this._params.get(name)

    if (list === undefined) return []

    return Array.from(list)
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-has
  has(name, value = null) {
    const list = this._params.get(name)

    if (list === undefined) return false

    if (value === null) return true

    return list.includes(value)
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-set
  set(name, value = null) {
    if (value === null) this._params.delete(name)
    else this._params.set(name, [value])

    this._update()
  }

  toString() {
    return this._serialize()
  }

  toJSON() {
    return [...this]
  }

  *[Symbol.iterator]() {
    for (const [name, values] of this._params) {
      for (const value of values) yield [name, value]
    }
  }

  [Symbol.for('bare.inspect')]() {
    const object = {
      __proto__: { constructor: URLSearchParams }
    }

    for (const [name, values] of this._params) {
      if (values.length === 1) object[name] = values[0]
      else object[name] = values
    }

    return object
  }

  // https://url.spec.whatwg.org/#concept-urlsearchparams-update
  _update() {
    const url = URLSearchParams._urls.get(this)

    if (url === undefined) return

    url.search = this._serialize()
  }

  // https://url.spec.whatwg.org/#concept-urlencoded-parser
  _parse(input) {
    if (input[0] === '?') input = input.substring(1)

    this._params = new Map()

    for (let sequence of input.split('&')) {
      if (sequence.length === 0) continue

      sequence = sequence.replace(/\+/g, ' ')

      let i = sequence.indexOf('=')
      if (i === -1) i = sequence.length

      const name = decodeURIComponent(sequence.substring(0, i))
      const value = decodeURIComponent(sequence.substring(i + 1, sequence.length))

      let list = this._params.get(name)

      if (list === undefined) {
        list = []
        this._params.set(name, list)
      }

      list.push(value)
    }
  }

  // https://url.spec.whatwg.org/#concept-urlencoded-serializer
  _serialize() {
    let output = ''

    for (let [name, values] of this._params) {
      name = encodeURIComponent(name)

      for (const value of values) {
        if (output) output += '&'

        output += name + '=' + encodeURIComponent(value)
      }
    }

    return output
  }
}

module.exports = exports = URLSearchParams

exports.isURLSearchParams = function isURLSearchParams(value) {
  if (value instanceof URLSearchParams) return true

  return typeof value === 'object' && value !== null && value[kind] === URLSearchParams[kind]
}
{
  "name": "bare-url",
  "version": "2.4.5",
  "description": "WHATWG URL implementation for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "global.js",
    "global.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-url.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-url/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-url",
  "dependencies": {
    "bare-path": "^3.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "cmake-bare": "^1.1.6",
    "cmake-fetch": "^1.0.0",
    "lunte": "^1.6.0",
    "prettier": "^3.3.3",
    "prettier-config-holepunch": "^2.0.0"
  }
}
const FACTOR = new Uint16Array(8)

function factor4096 (i, n) {
  while (n > 0) {
    const f = i & 4095
    FACTOR[--n] = f
    i = (i - f) / 4096
  }
  return FACTOR
}

module.exports = class BigSparseArray {
  constructor () {
    this.tiny = new TinyArray()
    this.maxLength = 4096
    this.factor = 1
  }

  set (index, val) {
    if (val !== undefined) {
      while (index >= this.maxLength) {
        this.maxLength *= 4096
        this.factor++
        if (!this.tiny.isEmptyish()) {
          const t = new TinyArray()
          t.set(0, this.tiny)
          this.tiny = t
        }
      }
    }

    const f = factor4096(index, this.factor)
    const last = this.factor - 1

    let tiny = this.tiny
    for (let i = 0; i < last; i++) {
      const next = tiny.get(f[i])
      if (next === undefined) {
        if (val === undefined) return
        tiny = tiny.set(f[i], new TinyArray())
      } else {
        tiny = next
      }
    }

    return tiny.set(f[last], val)
  }

  get (index) {
    if (index >= this.maxLength) return

    const f = factor4096(index, this.factor)
    const last = this.factor - 1

    let tiny = this.tiny
    for (let i = 0; i < last; i++) {
      tiny = tiny.get(f[i])
      if (tiny === undefined) return
    }

    return tiny.get(f[last])
  }
}

class TinyArray {
  constructor () {
    this.s = 0
    this.b = new Array(1)
    this.f = new Uint16Array(1)
  }

  isEmptyish () {
    return this.b.length === 1 && this.b[0] === undefined
  }

  get (i) {
    if (this.s === 12) return this.b[i]
    const f = i >>> this.s
    const r = i & (this.b.length - 1)
    return this.f[r] === f ? this.b[r] : undefined
  }

  set (i, v) {
    while (this.s !== 12) {
      const f = i >>> this.s
      const r = i & (this.b.length - 1)
      const o = this.b[r]

      if (o === undefined || f === this.f[r]) {
        this.b[r] = v
        this.f[r] = f
        return v
      }

      this.grow()
    }

    this.b[i] = v
    return v
  }

  grow () {
    const os = this.s
    const ob = this.b
    const of = this.f

    this.s += 4
    this.b = new Array(this.b.length << 4)
    this.f = this.s === 12 ? null : new Uint8Array(this.b.length)

    const m = this.b.length - 1

    for (let or = 0; or < ob.length; or++) {
      if (ob[or] === undefined) continue

      const i = of[or] << os | or
      const f = i >>> this.s
      const r = i & m

      this.b[r] = ob[or]
      if (this.s !== 12) this.f[r] = f
    }
  }
}
{
  "name": "big-sparse-array",
  "version": "1.0.3",
  "description": "A sparse array optimised for low memory whilst still being fast",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "brittle": "^3.1.1",
    "standard": "^16.0.3"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/big-sparse-array.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/big-sparse-array/issues"
  },
  "homepage": "https://github.com/mafintosh/big-sparse-array"
}
import { encode, encodeInto, objectToTokens, rfc8949EncodeOptions } from './lib/encode.js'
import { decode, decodeFirst, Tokeniser, tokensToObject } from './lib/decode.js'
import { Tagged } from './lib/tagged.js'
import { Token, Type } from './lib/token.js'

/**
 * Export the types that were present in the original manual cborg.d.ts
 * @typedef {import('./interface.js').TagDecodeControl} TagDecodeControl
 * @typedef {import('./interface.js').TagDecoder} TagDecoder
 * There was originally just `TypeEncoder` so don't break types by renaming or not exporting
 * @typedef {import('./interface.js').OptionalTypeEncoder} TypeEncoder
 * @typedef {import('./interface.js').DecodeOptions} DecodeOptions
 * @typedef {import('./interface.js').EncodeOptions} EncodeOptions
 */

export {
  decode,
  decodeFirst,
  Tokeniser as Tokenizer,
  tokensToObject,
  encode,
  encodeInto,
  objectToTokens,
  rfc8949EncodeOptions,
  Tagged,
  Token,
  Type
}
/* globals BigInt */

import { Token, Type } from './token.js'
import { decodeErrPrefix, assertEnoughData } from './common.js'

export const uintBoundaries = [24, 256, 65536, 4294967296, BigInt('18446744073709551616')]

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number}
 */
export function readUint8 (data, offset, options) {
  assertEnoughData(data, offset, 1)
  const value = data[offset]
  if (options.strict === true && value < uintBoundaries[0]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  return value
}

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number}
 */
export function readUint16 (data, offset, options) {
  assertEnoughData(data, offset, 2)
  const value = (data[offset] << 8) | data[offset + 1]
  if (options.strict === true && value < uintBoundaries[1]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  return value
}

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number}
 */
export function readUint32 (data, offset, options) {
  assertEnoughData(data, offset, 4)
  const value = (data[offset] * 16777216 /* 2 ** 24 */) + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]
  if (options.strict === true && value < uintBoundaries[2]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  return value
}

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number|bigint}
 */
export function readUint64 (data, offset, options) {
  // assume BigInt, convert back to Number if within safe range
  assertEnoughData(data, offset, 8)
  const hi = (data[offset] * 16777216 /* 2 ** 24 */) + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]
  const lo = (data[offset + 4] * 16777216 /* 2 ** 24 */) + (data[offset + 5] << 16) + (data[offset + 6] << 8) + data[offset + 7]
  const value = (BigInt(hi) << BigInt(32)) + BigInt(lo)
  if (options.strict === true && value < uintBoundaries[3]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  if (value <= Number.MAX_SAFE_INTEGER) {
    return Number(value)
  }
  if (options.allowBigInt === true) {
    return value
  }
  throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`)
}

/* not required thanks to quick[] list
const oneByteTokens = new Array(24).fill(0).map((v, i) => new Token(Type.uint, i, 1))
export function decodeUintCompact (data, pos, minor, options) {
  return oneByteTokens[minor]
}
*/

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint8 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint8(data, pos + 1, options), 2)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint16 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint16(data, pos + 1, options), 3)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint32 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint32(data, pos + 1, options), 5)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint64 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint64(data, pos + 1, options), 9)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeUint (writer, token) {
  return encodeUintValue(writer, 0, token.value)
}

/**
 * @param {ByteWriter} writer
 * @param {number} major
 * @param {number|bigint} uint
 */
export function encodeUintValue (writer, major, uint) {
  if (uint < uintBoundaries[0]) {
    const nuint = Number(uint)
    // pack into one byte, minor=0, additional=value
    writer.push([major | nuint])
  } else if (uint < uintBoundaries[1]) {
    const nuint = Number(uint)
    // pack into two byte, minor=0, additional=24
    writer.push([major | 24, nuint])
  } else if (uint < uintBoundaries[2]) {
    const nuint = Number(uint)
    // pack into three byte, minor=0, additional=25
    writer.push([major | 25, nuint >>> 8, nuint & 0xff])
  } else if (uint < uintBoundaries[3]) {
    const nuint = Number(uint)
    // pack into five byte, minor=0, additional=26
    writer.push([major | 26, (nuint >>> 24) & 0xff, (nuint >>> 16) & 0xff, (nuint >>> 8) & 0xff, nuint & 0xff])
  } else {
    const buint = BigInt(uint)
    if (buint < uintBoundaries[4]) {
      // pack into nine byte, minor=0, additional=27
      const set = [major | 27, 0, 0, 0, 0, 0, 0, 0]
      // simulate bitwise above 32 bits
      let lo = Number(buint & BigInt(0xffffffff))
      let hi = Number(buint >> BigInt(32) & BigInt(0xffffffff))
      set[8] = lo & 0xff
      lo = lo >> 8
      set[7] = lo & 0xff
      lo = lo >> 8
      set[6] = lo & 0xff
      lo = lo >> 8
      set[5] = lo & 0xff
      set[4] = hi & 0xff
      hi = hi >> 8
      set[3] = hi & 0xff
      hi = hi >> 8
      set[2] = hi & 0xff
      hi = hi >> 8
      set[1] = hi & 0xff
      writer.push(set)
    } else {
      throw new Error(`${decodeErrPrefix} encountered BigInt larger than allowable range`)
    }
  }
}

/**
 * @param {Token} token
 * @returns {number}
 */
encodeUint.encodedSize = function encodedSize (token) {
  return encodeUintValue.encodedSize(token.value)
}

/**
 * @param {number} uint
 * @returns {number}
 */
encodeUintValue.encodedSize = function encodedSize (uint) {
  if (uint < uintBoundaries[0]) {
    return 1
  }
  if (uint < uintBoundaries[1]) {
    return 2
  }
  if (uint < uintBoundaries[2]) {
    return 3
  }
  if (uint < uintBoundaries[3]) {
    return 5
  }
  return 9
}

/**
 * @param {Token} tok1
 * @param {Token} tok2
 * @returns {number}
 */
encodeUint.compareTokens = function compareTokens (tok1, tok2) {
  return tok1.value < tok2.value ? -1 : tok1.value > tok2.value ? 1 : 0
}
/* eslint-env es2020 */

import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import { decodeErrPrefix } from './common.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint8 (data, pos, _minor, options) {
  return new Token(Type.negint, -1 - uint.readUint8(data, pos + 1, options), 2)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint16 (data, pos, _minor, options) {
  return new Token(Type.negint, -1 - uint.readUint16(data, pos + 1, options), 3)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint32 (data, pos, _minor, options) {
  return new Token(Type.negint, -1 - uint.readUint32(data, pos + 1, options), 5)
}

const neg1b = BigInt(-1)
const pos1b = BigInt(1)

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint64 (data, pos, _minor, options) {
  const int = uint.readUint64(data, pos + 1, options)
  if (typeof int !== 'bigint') {
    const value = -1 - int
    if (value >= Number.MIN_SAFE_INTEGER) {
      return new Token(Type.negint, value, 9)
    }
  }
  if (options.allowBigInt !== true) {
    throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`)
  }
  return new Token(Type.negint, neg1b - BigInt(int), 9)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeNegint (writer, token) {
  const negint = token.value
  const unsigned = (typeof negint === 'bigint' ? (negint * neg1b - pos1b) : (negint * -1 - 1))
  uint.encodeUintValue(writer, token.type.majorEncoded, unsigned)
}

/**
 * @param {Token} token
 * @returns {number}
 */
encodeNegint.encodedSize = function encodedSize (token) {
  const negint = token.value
  const unsigned = (typeof negint === 'bigint' ? (negint * neg1b - pos1b) : (negint * -1 - 1))
  // handled by quickEncode, we shouldn't get here but it's included for completeness
  if (unsigned < uint.uintBoundaries[0]) {
    return 1
  }
  if (unsigned < uint.uintBoundaries[1]) {
    return 2
  }
  if (unsigned < uint.uintBoundaries[2]) {
    return 3
  }
  if (unsigned < uint.uintBoundaries[3]) {
    return 5
  }
  return 9
}

/**
 * @param {Token} tok1
 * @param {Token} tok2
 * @returns {number}
 */
encodeNegint.compareTokens = function compareTokens (tok1, tok2) {
  // opposite of the uint comparison since we store the uint version in bytes
  return tok1.value < tok2.value ? 1 : tok1.value > tok2.value ? -1 : 0
}
import { Token, Type } from './token.js'
import { assertEnoughData, decodeErrPrefix } from './common.js'
import * as uint from './0uint.js'
import { compare, fromString } from './byte-utils.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} prefix
 * @param {number} length
 * @returns {Token}
 */
function toToken (data, pos, prefix, length) {
  assertEnoughData(data, pos, prefix + length)
  const buf = data.slice(pos + prefix, pos + prefix + length)
  return new Token(Type.bytes, buf, prefix + length)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeBytesCompact (data, pos, minor, _options) {
  return toToken(data, pos, 1, minor)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer bytes lengths not supported`)
  }
  return toToken(data, pos, 9, l)
}

/**
 * `encodedBytes` allows for caching when we do a byte version of a string
 * for key sorting purposes
 * @param {Token} token
 * @returns {Uint8Array}
 */
function tokenBytes (token) {
  if (token.encodedBytes === undefined) {
    token.encodedBytes = Type.equals(token.type, Type.string) ? fromString(token.value) : token.value
  }
  // @ts-ignore c'mon
  return token.encodedBytes
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeBytes (writer, token) {
  const bytes = tokenBytes(token)
  uint.encodeUintValue(writer, token.type.majorEncoded, bytes.length)
  writer.push(bytes)
}

/**
 * @param {Token} token
 * @returns {number}
 */
encodeBytes.encodedSize = function encodedSize (token) {
  const bytes = tokenBytes(token)
  return uint.encodeUintValue.encodedSize(bytes.length) + bytes.length
}

/**
 * @param {Token} tok1
 * @param {Token} tok2
 * @returns {number}
 */
encodeBytes.compareTokens = function compareTokens (tok1, tok2) {
  return compareBytes(tokenBytes(tok1), tokenBytes(tok2))
}

/**
 * @param {Uint8Array} b1
 * @param {Uint8Array} b2
 * @returns {number}
 */
export function compareBytes (b1, b2) {
  return b1.length < b2.length ? -1 : b1.length > b2.length ? 1 : compare(b1, b2)
}
import { Token, Type } from './token.js'
import { assertEnoughData, decodeErrPrefix } from './common.js'
import * as uint from './0uint.js'
import { encodeBytes } from './2bytes.js'

const textDecoder = new TextDecoder()

// Threshold for ASCII fast-path vs TextDecoder. Short ASCII strings (common for
// map keys) are faster to decode with a simple loop than TextDecoder overhead.
const ASCII_THRESHOLD = 32

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * Decode UTF-8 bytes to string. For short ASCII strings (common case for map keys),
 * a simple loop is faster than TextDecoder.
 * @param {Uint8Array} bytes
 * @param {number} start
 * @param {number} end
 * @returns {string}
 */
function toStr (bytes, start, end) {
  const len = end - start
  if (len < ASCII_THRESHOLD) {
    let str = ''
    for (let i = start; i < end; i++) {
      const c = bytes[i]
      if (c & 0x80) { // non-ASCII, fall back to TextDecoder
        return textDecoder.decode(bytes.subarray(start, end))
      }
      str += String.fromCharCode(c)
    }
    return str
  }
  return textDecoder.decode(bytes.subarray(start, end))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} prefix
 * @param {number} length
 * @param {DecodeOptions} options
 * @returns {Token}
 */
function toToken (data, pos, prefix, length, options) {
  const totLength = prefix + length
  assertEnoughData(data, pos, totLength)
  const tok = new Token(Type.string, toStr(data, pos + prefix, pos + totLength), totLength)
  if (options.retainStringBytes === true) {
    tok.byteValue = data.slice(pos + prefix, pos + totLength)
  }
  return tok
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeStringCompact (data, pos, minor, options) {
  return toToken(data, pos, 1, minor, options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options), options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options), options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options), options)
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer string lengths not supported`)
  }
  return toToken(data, pos, 9, l, options)
}

export const encodeString = encodeBytes
import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import { decodeErrPrefix } from './common.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} prefix
 * @param {number} length
 * @returns {Token}
 */
function toToken (_data, _pos, prefix, length) {
  return new Token(Type.array, length, prefix)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeArrayCompact (data, pos, minor, _options) {
  return toToken(data, pos, 1, minor)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer array lengths not supported`)
  }
  return toToken(data, pos, 9, l)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArrayIndefinite (data, pos, _minor, options) {
  if (options.allowIndefinite === false) {
    throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)
  }
  return toToken(data, pos, 1, Infinity)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeArray (writer, token) {
  uint.encodeUintValue(writer, Type.array.majorEncoded, token.value)
}

// using an array as a map key, are you sure about this? we can only sort
// by map length here, it's up to the encoder to decide to look deeper
encodeArray.compareTokens = uint.encodeUint.compareTokens

/**
 * @param {Token} token
 * @returns {number}
 */
encodeArray.encodedSize = function encodedSize (token) {
  return uint.encodeUintValue.encodedSize(token.value)
}
import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import { decodeErrPrefix } from './common.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} prefix
 * @param {number} length
 * @returns {Token}
 */
function toToken (_data, _pos, prefix, length) {
  return new Token(Type.map, length, prefix)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeMapCompact (data, pos, minor, _options) {
  return toToken(data, pos, 1, minor)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer map lengths not supported`)
  }
  return toToken(data, pos, 9, l)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMapIndefinite (data, pos, _minor, options) {
  if (options.allowIndefinite === false) {
    throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)
  }
  return toToken(data, pos, 1, Infinity)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeMap (writer, token) {
  uint.encodeUintValue(writer, Type.map.majorEncoded, token.value)
}

// using a map as a map key, are you sure about this? we can only sort
// by map length here, it's up to the encoder to decide to look deeper
encodeMap.compareTokens = uint.encodeUint.compareTokens

/**
 * @param {Token} token
 * @returns {number}
 */
encodeMap.encodedSize = function encodedSize (token) {
  return uint.encodeUintValue.encodedSize(token.value)
}
import { Token, Type } from './token.js'
import * as uint from './0uint.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeTagCompact (_data, _pos, minor, _options) {
  return new Token(Type.tag, minor, 1)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag8 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint8(data, pos + 1, options), 2)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag16 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint16(data, pos + 1, options), 3)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag32 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint32(data, pos + 1, options), 5)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag64 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint64(data, pos + 1, options), 9)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeTag (writer, token) {
  uint.encodeUintValue(writer, Type.tag.majorEncoded, token.value)
}

encodeTag.compareTokens = uint.encodeUint.compareTokens

/**
 * @param {Token} token
 * @returns {number}
 */
encodeTag.encodedSize = function encodedSize (token) {
  return uint.encodeUintValue.encodedSize(token.value)
}
// TODO: shift some of the bytes logic to bytes-utils so we can use Buffer
// where possible

import { Token, Type } from './token.js'
import { decodeErrPrefix } from './common.js'
import { encodeUint } from './0uint.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 * @typedef {import('../interface.js').EncodeOptions} EncodeOptions
 */

export const MINOR_FALSE = 20
export const MINOR_TRUE = 21
export const MINOR_NULL = 22
export const MINOR_UNDEFINED = 23

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUndefined (_data, _pos, _minor, options) {
  if (options.allowUndefined === false) {
    throw new Error(`${decodeErrPrefix} undefined values are not supported`)
  } else if (options.coerceUndefinedToNull === true) {
    return new Token(Type.null, null, 1)
  }
  return new Token(Type.undefined, undefined, 1)
}

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBreak (_data, _pos, _minor, options) {
  if (options.allowIndefinite === false) {
    throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)
  }
  return new Token(Type.break, undefined, 1)
}

/**
 * @param {number} value
 * @param {number} bytes
 * @param {DecodeOptions} options
 * @returns {Token}
 */
function createToken (value, bytes, options) {
  if (options) {
    if (options.allowNaN === false && Number.isNaN(value)) {
      throw new Error(`${decodeErrPrefix} NaN values are not supported`)
    }
    if (options.allowInfinity === false && (value === Infinity || value === -Infinity)) {
      throw new Error(`${decodeErrPrefix} Infinity values are not supported`)
    }
  }
  return new Token(Type.float, value, bytes)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeFloat16 (data, pos, _minor, options) {
  return createToken(readFloat16(data, pos + 1), 3, options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeFloat32 (data, pos, _minor, options) {
  return createToken(readFloat32(data, pos + 1), 5, options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeFloat64 (data, pos, _minor, options) {
  return createToken(readFloat64(data, pos + 1), 9, options)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 * @param {EncodeOptions} options
 */
export function encodeFloat (writer, token, options) {
  const float = token.value

  if (float === false) {
    writer.push([Type.float.majorEncoded | MINOR_FALSE])
  } else if (float === true) {
    writer.push([Type.float.majorEncoded | MINOR_TRUE])
  } else if (float === null) {
    writer.push([Type.float.majorEncoded | MINOR_NULL])
  } else if (float === undefined) {
    writer.push([Type.float.majorEncoded | MINOR_UNDEFINED])
  } else {
    let decoded
    let success = false
    if (!options || options.float64 !== true) {
      encodeFloat16(float)
      decoded = readFloat16(ui8a, 1)
      if (float === decoded || Number.isNaN(float)) {
        ui8a[0] = 0xf9
        writer.push(ui8a.slice(0, 3))
        success = true
      } else {
        encodeFloat32(float)
        decoded = readFloat32(ui8a, 1)
        if (float === decoded) {
          ui8a[0] = 0xfa
          writer.push(ui8a.slice(0, 5))
          success = true
        }
      }
    }
    if (!success) {
      encodeFloat64(float)
      decoded = readFloat64(ui8a, 1)
      ui8a[0] = 0xfb
      writer.push(ui8a.slice(0, 9))
    }
  }
}

/**
 * @param {Token} token
 * @param {EncodeOptions} options
 * @returns {number}
 */
encodeFloat.encodedSize = function encodedSize (token, options) {
  const float = token.value

  if (float === false || float === true || float === null || float === undefined) {
    return 1
  }

  if (!options || options.float64 !== true) {
    encodeFloat16(float)
    let decoded = readFloat16(ui8a, 1)
    if (float === decoded || Number.isNaN(float)) {
      return 3
    }
    encodeFloat32(float)
    decoded = readFloat32(ui8a, 1)
    if (float === decoded) {
      return 5
    }
  }
  return 9
}

const buffer = new ArrayBuffer(9)
const dataView = new DataView(buffer, 1)
const ui8a = new Uint8Array(buffer, 0)

/**
 * @param {number} inp
 */
function encodeFloat16 (inp) {
  if (inp === Infinity) {
    dataView.setUint16(0, 0x7c00, false)
  } else if (inp === -Infinity) {
    dataView.setUint16(0, 0xfc00, false)
  } else if (Number.isNaN(inp)) {
    dataView.setUint16(0, 0x7e00, false)
  } else {
    dataView.setFloat32(0, inp)
    const valu32 = dataView.getUint32(0)
    const exponent = (valu32 & 0x7f800000) >> 23
    const mantissa = valu32 & 0x7fffff

    if (exponent === 0xff) {
      // too big, Infinity, but this should be hard (impossible?) to trigger
      dataView.setUint16(0, 0x7c00, false)
    } else if (exponent === 0x00) {
      // 0.0, -0.0 and subnormals, shouldn't be possible to get here because 0.0 should be counted as an int
      // Use valu32 for sign bit since bitwise ops on floats lose -0 sign
      dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | (mantissa >> 13), false)
    } else { // standard numbers
      // chunks of logic here borrowed from https://github.com/PJK/libcbor/blob/c78f437182533e3efa8d963ff4b945bb635c2284/src/cbor/encoding.c#L127
      const logicalExponent = exponent - 127
      // Now we know that 2^exponent <= 0 logically
      if (logicalExponent < -24) {
        /* No unambiguous representation exists, this float is not a half float
          and is too small to be represented using a half, round off to zero.
          Consistent with the reference implementation. */
        // should be difficult (impossible?) to get here in JS
        dataView.setUint16(0, 0)
      } else if (logicalExponent < -14) {
        /* Offset the remaining decimal places by shifting the significand, the
          value is lost. This is an implementation decision that works around the
          absence of standard half-float in the language. */
        dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | /* sign bit */ (1 << (24 + logicalExponent)), false)
      } else {
        dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | ((logicalExponent + 15) << 10) | (mantissa >> 13), false)
      }
    }
  }
}

/**
 * @param {Uint8Array} ui8a
 * @param {number} pos
 * @returns {number}
 */
function readFloat16 (ui8a, pos) {
  if (ui8a.length - pos < 2) {
    throw new Error(`${decodeErrPrefix} not enough data for float16`)
  }

  const half = (ui8a[pos] << 8) + ui8a[pos + 1]
  if (half === 0x7c00) {
    return Infinity
  }
  if (half === 0xfc00) {
    return -Infinity
  }
  if (half === 0x7e00) {
    return NaN
  }
  const exp = (half >> 10) & 0x1f
  const mant = half & 0x3ff
  let val
  if (exp === 0) {
    val = mant * (2 ** -24)
  } else if (exp !== 31) {
    val = (mant + 1024) * (2 ** (exp - 25))
  } else {
    // may not be possible to get here
    val = mant === 0 ? Infinity : NaN
  }
  return (half & 0x8000) ? -val : val
}

/**
 * @param {number} inp
 */
function encodeFloat32 (inp) {
  dataView.setFloat32(0, inp, false)
}

/**
 * @param {Uint8Array} ui8a
 * @param {number} pos
 * @returns {number}
 */
function readFloat32 (ui8a, pos) {
  if (ui8a.length - pos < 4) {
    throw new Error(`${decodeErrPrefix} not enough data for float32`)
  }
  const offset = (ui8a.byteOffset || 0) + pos
  return new DataView(ui8a.buffer, offset, 4).getFloat32(0, false)
}

/**
 * @param {number} inp
 */
function encodeFloat64 (inp) {
  dataView.setFloat64(0, inp, false)
}

/**
 * @param {Uint8Array} ui8a
 * @param {number} pos
 * @returns {number}
 */
function readFloat64 (ui8a, pos) {
  if (ui8a.length - pos < 8) {
    throw new Error(`${decodeErrPrefix} not enough data for float64`)
  }
  const offset = (ui8a.byteOffset || 0) + pos
  return new DataView(ui8a.buffer, offset, 8).getFloat64(0, false)
}

/**
 * @param {Token} _tok1
 * @param {Token} _tok2
 * @returns {number}
 */
encodeFloat.compareTokens = encodeUint.compareTokens
/*
encodeFloat.compareTokens = function compareTokens (_tok1, _tok2) {
  return _tok1
  throw new Error(`${encodeErrPrefix} cannot use floats as map keys`)
}
*/
/**
 * Bl is a list of byte chunks, similar to https://github.com/rvagg/bl but for
 * writing rather than reading.
 * A Bl object accepts set() operations for individual bytes and copyTo() for
 * inserting byte arrays. These write operations don't automatically increment
 * the internal cursor so its "length" won't be changed. Instead, increment()
 * must be called to extend its length to cover the inserted data.
 * The toBytes() call will convert all internal memory to a single Uint8Array of
 * the correct length, truncating any data that is stored but hasn't been
 * included by an increment().
 * get() can retrieve a single byte.
 * All operations (except toBytes()) take an "offset" argument that will perform
 * the write at the offset _from the current cursor_. For most operations this
 * will be `0` to write at the current cursor position but it can be ahead of
 * the current cursor. Negative offsets probably work but are untested.
 */

// TODO: ipjs doesn't support this, only for test files: https://github.com/mikeal/ipjs/blob/master/src/package/testFile.js#L39
import { alloc, concat, slice } from './byte-utils.js'

// the ts-ignores in this file are almost all for the `Uint8Array|number[]` duality that exists
// for perf reasons. Consider better approaches to this or removing it entirely, it is quite
// risky because of some assumptions about small chunks === number[] and everything else === Uint8Array.

const defaultChunkSize = 256

export class Bl {
  /**
   * @param {number} [chunkSize]
   */
  constructor (chunkSize = defaultChunkSize) {
    this.chunkSize = chunkSize
    /** @type {number} */
    this.cursor = 0
    /** @type {number} */
    this.maxCursor = -1
    /** @type {(Uint8Array|number[])[]} */
    this.chunks = []
    // keep the first chunk around if we can to save allocations for future encodes
    /** @type {Uint8Array|number[]|null} */
    this._initReuseChunk = null
  }

  reset () {
    this.cursor = 0
    this.maxCursor = -1
    if (this.chunks.length) {
      this.chunks = []
    }
    if (this._initReuseChunk !== null) {
      this.chunks.push(this._initReuseChunk)
      this.maxCursor = this._initReuseChunk.length - 1
    }
  }

  /**
   * @param {Uint8Array|number[]} bytes
   */
  push (bytes) {
    let topChunk = this.chunks[this.chunks.length - 1]
    const newMax = this.cursor + bytes.length
    if (newMax <= this.maxCursor + 1) {
      // we have at least one chunk and we can fit these bytes into that chunk
      const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1
      // @ts-ignore
      topChunk.set(bytes, chunkPos)
    } else {
      // can't fit it in
      if (topChunk) {
        // trip the last chunk to `cursor` if we need to
        const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1
        if (chunkPos < topChunk.length) {
          // @ts-ignore
          this.chunks[this.chunks.length - 1] = topChunk.subarray(0, chunkPos)
          this.maxCursor = this.cursor - 1
        }
      }
      if (bytes.length < 64 && bytes.length < this.chunkSize) {
        // make a new chunk and copy the new one into it
        topChunk = alloc(this.chunkSize)
        this.chunks.push(topChunk)
        this.maxCursor += topChunk.length
        if (this._initReuseChunk === null) {
          this._initReuseChunk = topChunk
        }
        // @ts-ignore
        topChunk.set(bytes, 0)
      } else {
        // push the new bytes in as its own chunk
        this.chunks.push(bytes)
        this.maxCursor += bytes.length
      }
    }
    this.cursor += bytes.length
  }

  /**
   * @param {boolean} [reset]
   * @returns {Uint8Array}
   */
  toBytes (reset = false) {
    let byts
    if (this.chunks.length === 1) {
      const chunk = this.chunks[0]
      if (reset && this.cursor > chunk.length / 2) {
        // @ts-ignore
        byts = this.cursor === chunk.length ? chunk : chunk.subarray(0, this.cursor)
        this._initReuseChunk = null
        this.chunks = []
      } else {
        // @ts-ignore
        byts = slice(chunk, 0, this.cursor)
      }
    } else {
      // @ts-ignore
      byts = concat(this.chunks, this.cursor)
    }
    if (reset) {
      this.reset()
    }
    return byts
  }
}

/**
 * U8Bl is a buffer list that writes directly to a user-provided Uint8Array.
 * It provides the same interface as Bl but writes to a fixed destination.
 */
export class U8Bl {
  /**
   * @param {Uint8Array} dest
   */
  constructor (dest) {
    this.dest = dest
    /** @type {number} */
    this.cursor = 0
    // chunks is for interface compatibility with Bl - encode.js checks chunks.length
    // as a sanity check for pre-calculated sizes. For U8Bl this is always [dest].
    /** @type {Uint8Array[]} */
    this.chunks = [dest]
  }

  reset () {
    this.cursor = 0
  }

  /**
   * @param {Uint8Array|number[]} bytes
   */
  push (bytes) {
    if (this.cursor + bytes.length > this.dest.length) {
      throw new Error('write out of bounds, destination buffer is too small')
    }
    this.dest.set(bytes, this.cursor)
    this.cursor += bytes.length
  }

  /**
   * @param {boolean} [reset]
   * @returns {Uint8Array}
   */
  toBytes (reset = false) {
    const byts = this.dest.subarray(0, this.cursor)
    if (reset) {
      this.reset()
    }
    return byts
  }
}
// Use Uint8Array directly in the browser, use Buffer in Node.js but don't
// speak its name directly to avoid bundlers pulling in the `Buffer` polyfill

// @ts-ignore
export const useBuffer = globalThis.process &&
  // @ts-ignore
  !globalThis.process.browser &&
  // @ts-ignore
  globalThis.Buffer &&
  // @ts-ignore
  typeof globalThis.Buffer.isBuffer === 'function'

const textEncoder = new TextEncoder()

/**
 * @param {Uint8Array} buf
 * @returns {boolean}
 */
function isBuffer (buf) {
  // @ts-ignore
  return useBuffer && globalThis.Buffer.isBuffer(buf)
}

/**
 * @param {Uint8Array|number[]} buf
 * @returns {Uint8Array}
 */
export function asU8A (buf) {
  if (!(buf instanceof Uint8Array)) {
    return Uint8Array.from(buf)
  }
  return isBuffer(buf) ? new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength) : buf
}

// Threshold for manual UTF-8 encoding vs native methods.
// Node.js Buffer.from: crossover ~24 chars
// Browser TextEncoder: crossover ~200 chars
const FROM_STRING_THRESHOLD_BUFFER = 24
const FROM_STRING_THRESHOLD_TEXTENCODER = 200

export const fromString = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {string} string
     */
    (string) => {
      return string.length >= FROM_STRING_THRESHOLD_BUFFER
        ? // eslint-disable-line operator-linebreak
      // @ts-ignore
        globalThis.Buffer.from(string)
        : utf8ToBytes(string)
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {string} string
     */
    (string) => {
      return string.length >= FROM_STRING_THRESHOLD_TEXTENCODER ? textEncoder.encode(string) : utf8ToBytes(string)
    }

/**
 * Buffer variant not fast enough for what we need
 * @param {number[]} arr
 * @returns {Uint8Array}
 */
export const fromArray = (arr) => {
  return Uint8Array.from(arr)
}

export const slice = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} bytes
     * @param {number} start
     * @param {number} end
     */
    // Buffer.slice() returns a view, not a copy, so we need special handling
    (bytes, start, end) => {
      if (isBuffer(bytes)) {
        return new Uint8Array(bytes.subarray(start, end))
      }
      return bytes.slice(start, end)
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} bytes
     * @param {number} start
     * @param {number} end
     */
    (bytes, start, end) => {
      return bytes.slice(start, end)
    }

export const concat = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array[]} chunks
     * @param {number} length
     * @returns {Uint8Array}
     */
    (chunks, length) => {
      // might get a stray plain Array here
      chunks = chunks.map((c) => c instanceof Uint8Array
        ? c
        : // eslint-disable-line operator-linebreak
        // @ts-ignore
        globalThis.Buffer.from(c))
      // @ts-ignore
      return asU8A(globalThis.Buffer.concat(chunks, length))
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array[]} chunks
     * @param {number} length
     * @returns {Uint8Array}
     */
    (chunks, length) => {
      const out = new Uint8Array(length)
      let off = 0
      for (let b of chunks) {
        if (off + b.length > out.length) {
          // final chunk that's bigger than we need
          b = b.subarray(0, out.length - off)
        }
        out.set(b, off)
        off += b.length
      }
      return out
    }

export const alloc = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {number} size
     * @returns {Uint8Array}
     */
    (size) => {
      // we always write over the contents we expose so this should be safe
      // @ts-ignore
      return globalThis.Buffer.allocUnsafe(size)
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {number} size
     * @returns {Uint8Array}
     */
    (size) => {
      return new Uint8Array(size)
    }

export const toHex = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} d
     * @returns {string}
     */
    (d) => {
      if (typeof d === 'string') {
        return d
      }
      // @ts-ignore
      return globalThis.Buffer.from(toBytes(d)).toString('hex')
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} d
     * @returns {string}
     */
    (d) => {
      if (typeof d === 'string') {
        return d
      }
      // @ts-ignore not smart enough to figure this out
      return Array.prototype.reduce.call(toBytes(d), (p, c) => `${p}${c.toString(16).padStart(2, '0')}`, '')
    }

export const fromHex = useBuffer
  ? // eslint-disable-line operator-linebreak
  /**
   * @param {string|Uint8Array} hex
   * @returns {Uint8Array}
   */
    (hex) => {
      if (hex instanceof Uint8Array) {
        return hex
      }
      // @ts-ignore
      return globalThis.Buffer.from(hex, 'hex')
    }
  : // eslint-disable-line operator-linebreak
  /**
   * @param {string|Uint8Array} hex
   * @returns {Uint8Array}
   */
    (hex) => {
      if (hex instanceof Uint8Array) {
        return hex
      }
      if (!hex.length) {
        return new Uint8Array(0)
      }
      return new Uint8Array(hex.split('')
        .map((/** @type {string} */ c, /** @type {number} */ i, /** @type {string[]} */ d) => i % 2 === 0 ? `0x${c}${d[i + 1]}` : '')
        .filter(Boolean)
        .map((/** @type {string} */ e) => parseInt(e, 16)))
    }

/**
 * @param {Uint8Array|ArrayBuffer|ArrayBufferView} obj
 * @returns {Uint8Array}
 */
function toBytes (obj) {
  if (obj instanceof Uint8Array && obj.constructor.name === 'Uint8Array') {
    return obj
  }
  if (obj instanceof ArrayBuffer) {
    return new Uint8Array(obj)
  }
  if (ArrayBuffer.isView(obj)) {
    return new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength)
  }
  throw new Error('Unknown type, must be binary type')
}

/**
 * @param {Uint8Array} b1
 * @param {Uint8Array} b2
 * @returns {number}
 */
export function compare (b1, b2) {
  if (isBuffer(b1) && isBuffer(b2)) {
    // probably not possible to get here in the current API
    // @ts-ignore Buffer
    return b1.compare(b2)
  }
  for (let i = 0; i < b1.length; i++) {
    if (b1[i] === b2[i]) {
      continue
    }
    return b1[i] < b2[i] ? -1 : 1
  }
  return 0
}

// The below code is taken from https://github.com/google/closure-library/blob/8598d87242af59aac233270742c8984e2b2bdbe0/closure/goog/crypt/crypt.js#L117-L143
// Licensed Apache-2.0.

/**
 * @param {string} str
 * @returns {number[]}
 */
function utf8ToBytes (str) {
  const out = []
  let p = 0
  for (let i = 0; i < str.length; i++) {
    let c = str.charCodeAt(i)
    if (c < 128) {
      out[p++] = c
    } else if (c < 2048) {
      out[p++] = (c >> 6) | 192
      out[p++] = (c & 63) | 128
    } else if (
      ((c & 0xFC00) === 0xD800) && (i + 1) < str.length &&
      ((str.charCodeAt(i + 1) & 0xFC00) === 0xDC00)) {
      // Surrogate Pair
      c = 0x10000 + ((c & 0x03FF) << 10) + (str.charCodeAt(++i) & 0x03FF)
      out[p++] = (c >> 18) | 240
      out[p++] = ((c >> 12) & 63) | 128
      out[p++] = ((c >> 6) & 63) | 128
      out[p++] = (c & 63) | 128
    } else {
      if ((c >= 0xD800) && (c <= 0xDFFF)) {
        c = 0xFFFD // Unpaired Surrogate
      }
      out[p++] = (c >> 12) | 224
      out[p++] = ((c >> 6) & 63) | 128
      out[p++] = (c & 63) | 128
    }
  }
  return out
}

// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
const MAX_ARGUMENTS_LENGTH = 0x1000

/**
 * @param {number[]} codePoints
 * @returns {string}
 */
export function decodeCodePointsArray (codePoints) {
  const len = codePoints.length
  if (len <= MAX_ARGUMENTS_LENGTH) {
    return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  }
  // Decode in chunks to avoid "call stack size exceeded".
  let res = ''
  let i = 0
  while (i < len) {
    res += String.fromCharCode.apply(
      String,
      codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
    )
  }
  return res
}
const decodeErrPrefix = 'CBOR decode error:'
const encodeErrPrefix = 'CBOR encode error:'

const uintMinorPrefixBytes = []
uintMinorPrefixBytes[23] = 1
uintMinorPrefixBytes[24] = 2
uintMinorPrefixBytes[25] = 3
uintMinorPrefixBytes[26] = 5
uintMinorPrefixBytes[27] = 9

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} need
 */
function assertEnoughData (data, pos, need) {
  if (data.length - pos < need) {
    throw new Error(`${decodeErrPrefix} not enough data for type`)
  }
}

export {
  decodeErrPrefix,
  encodeErrPrefix,
  uintMinorPrefixBytes,
  assertEnoughData
}
import { decodeErrPrefix } from './common.js'
import { Type } from './token.js'
import { jump, quick } from './jump.js'
import { asU8A } from './byte-utils.js'

/**
 * @typedef {import('./token.js').Token} Token
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 * @typedef {import('../interface.js').DecodeTokenizer} DecodeTokenizer
 * @typedef {import('../interface.js').TagDecodeControl} TagDecodeControl
 */

const defaultDecodeOptions = {
  strict: false,
  allowIndefinite: true,
  allowUndefined: true,
  allowBigInt: true
}

/**
 * @implements {DecodeTokenizer}
 */
class Tokeniser {
  /**
   * @param {Uint8Array} data
   * @param {DecodeOptions} options
   */
  constructor (data, options = {}) {
    this._pos = 0
    this.data = data
    this.options = options
  }

  pos () {
    return this._pos
  }

  done () {
    return this._pos >= this.data.length
  }

  next () {
    const byt = this.data[this._pos]
    let token = quick[byt]
    if (token === undefined) {
      const decoder = jump[byt]
      // if we're here then there's something wrong with our jump or quick lists!
      if (!decoder) {
        throw new Error(`${decodeErrPrefix} no decoder for major type ${byt >>> 5} (byte 0x${byt.toString(16).padStart(2, '0')})`)
      }
      const minor = byt & 31
      token = decoder(this.data, this._pos, minor, this.options)
    }
    // @ts-ignore we get to assume encodedLength is set (crossing fingers slightly)
    this._pos += token.encodedLength
    return token
  }
}

const DONE = Symbol.for('DONE')
const BREAK = Symbol.for('BREAK')

/**
 * @param {Token} token
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {any|BREAK|DONE}
 */
function tokenToArray (token, tokeniser, options) {
  const arr = []
  for (let i = 0; i < token.value; i++) {
    const value = tokensToObject(tokeniser, options)
    if (value === BREAK) {
      if (token.value === Infinity) {
        // normal end to indefinite length array
        break
      }
      throw new Error(`${decodeErrPrefix} got unexpected break to lengthed array`)
    }
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} found array but not enough entries (got ${i}, expected ${token.value})`)
    }
    arr[i] = value
  }
  return arr
}

/**
 * @param {Token} token
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {any|BREAK|DONE}
 */
function tokenToMap (token, tokeniser, options) {
  const useMaps = options.useMaps === true
  const rejectDuplicateMapKeys = options.rejectDuplicateMapKeys === true
  const obj = useMaps ? undefined : {}
  const m = useMaps ? new Map() : undefined
  for (let i = 0; i < token.value; i++) {
    const key = tokensToObject(tokeniser, options)
    if (key === BREAK) {
      if (token.value === Infinity) {
        // normal end to indefinite length map
        break
      }
      throw new Error(`${decodeErrPrefix} got unexpected break to lengthed map`)
    }
    if (key === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no key], expected ${token.value})`)
    }
    if (!useMaps && typeof key !== 'string') {
      throw new Error(`${decodeErrPrefix} non-string keys not supported (got ${typeof key})`)
    }
    if (rejectDuplicateMapKeys) {
      // @ts-ignore
      if ((useMaps && m.has(key)) || (!useMaps && Object.hasOwn(obj, key))) {
        throw new Error(`${decodeErrPrefix} found repeat map key "${key}"`)
      }
    }
    const value = tokensToObject(tokeniser, options)
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no value], expected ${token.value})`)
    }
    if (useMaps) {
      // @ts-ignore TODO reconsider this .. maybe needs to be strict about key types
      m.set(key, value)
    } else {
      // @ts-ignore TODO reconsider this .. maybe needs to be strict about key types
      obj[key] = value
    }
  }
  // @ts-ignore c'mon man
  return useMaps ? m : obj
}

/**
 * Generator that yields [key, value] entries from a CBOR map token.
 * Used by tag decoders that need to preserve key types (e.g., Tag 259 Map).
 * @param {Token} token - The map token
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {Generator<[any, any], void, unknown>}
 */
function * tokenToMapEntries (token, tokeniser, options) {
  for (let i = 0; i < token.value; i++) {
    const key = tokensToObject(tokeniser, options)
    if (key === BREAK) {
      if (token.value === Infinity) {
        // normal end to indefinite length map
        break
      }
      throw new Error(`${decodeErrPrefix} got unexpected break to lengthed map`)
    }
    if (key === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no key], expected ${token.value})`)
    }
    const value = tokensToObject(tokeniser, options)
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no value], expected ${token.value})`)
    }
    yield [key, value]
  }
}

/**
 * Creates a TagDecodeControl object for tag decoders.
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {TagDecodeControl}
 */
function createTagDecodeControl (tokeniser, options) {
  let called = false

  /**
   * @type {TagDecodeControl}
   */
  const decode = function () {
    if (called) {
      throw new Error(`${decodeErrPrefix} tag decode() may only be called once`)
    }
    called = true
    const value = tokensToObject(tokeniser, options)
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} tag content missing`)
    }
    if (value === BREAK) {
      throw new Error(`${decodeErrPrefix} got unexpected break in tag content`)
    }
    return value
  }

  decode.entries = function () {
    if (called) {
      throw new Error(`${decodeErrPrefix} tag decode() may only be called once`)
    }
    called = true

    // Get the next token and ensure it's a map
    const token = tokeniser.next()
    if (!Type.equals(token.type, Type.map)) {
      throw new Error(`${decodeErrPrefix} entries() requires map content, got ${token.type.name}`)
    }

    // Collect all entries into an array (ensures full content consumption)
    const entries = []
    for (const entry of tokenToMapEntries(token, tokeniser, options)) {
      entries.push(entry)
    }
    return entries
  }

  // For internal tracking
  Object.defineProperty(decode, '_called', {
    get () { return called },
    enumerable: false
  })

  return decode
}

/**
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {any|BREAK|DONE}
 */
function tokensToObject (tokeniser, options) {
  // should we support array as an argument?
  // check for tokenIter[Symbol.iterator] and replace tokenIter with what that returns?
  if (tokeniser.done()) {
    return DONE
  }

  const token = tokeniser.next()

  if (Type.equals(token.type, Type.break)) {
    return BREAK
  }

  if (token.type.terminal) {
    return token.value
  }

  if (Type.equals(token.type, Type.array)) {
    return tokenToArray(token, tokeniser, options)
  }

  if (Type.equals(token.type, Type.map)) {
    return tokenToMap(token, tokeniser, options)
  }

  if (Type.equals(token.type, Type.tag)) {
    if (options.tags && typeof options.tags[token.value] === 'function') {
      const decodeControl = createTagDecodeControl(tokeniser, options)
      const result = options.tags[token.value](decodeControl)
      if (!decodeControl._called) {
        throw new Error(`${decodeErrPrefix} tag decoder must call decode() or entries()`)
      }
      return result
    }
    throw new Error(`${decodeErrPrefix} tag not supported (${token.value})`)
  }
  throw new Error('unsupported')
}

/**
 * @param {Uint8Array} data
 * @param {DecodeOptions} [options]
 * @returns {[any, Uint8Array]}
 */
function decodeFirst (data, options) {
  if (!(data instanceof Uint8Array)) {
    throw new Error(`${decodeErrPrefix} data to decode must be a Uint8Array`)
  }
  options = Object.assign({}, defaultDecodeOptions, options)
  // Convert Buffer to plain Uint8Array for faster slicing in decode path
  const u8aData = asU8A(data)
  const tokeniser = options.tokenizer || new Tokeniser(u8aData, options)
  const decoded = tokensToObject(tokeniser, options)
  if (decoded === DONE) {
    throw new Error(`${decodeErrPrefix} did not find any content to decode`)
  }
  if (decoded === BREAK) {
    throw new Error(`${decodeErrPrefix} got unexpected break`)
  }
  return [decoded, data.subarray(tokeniser.pos())]
}

/**
 * @param {Uint8Array} data
 * @param {DecodeOptions} [options]
 * @returns {any}
 */
function decode (data, options) {
  const [decoded, remainder] = decodeFirst(data, options)
  if (remainder.length > 0) {
    throw new Error(`${decodeErrPrefix} too many terminals, data makes no sense`)
  }
  return decoded
}

export { Tokeniser, tokensToObject, decode, decodeFirst }
import { is } from './is.js'
import { Token, Type } from './token.js'
import { Bl, U8Bl } from './bl.js'
import { encodeErrPrefix } from './common.js'
import { quickEncodeToken } from './jump.js'
import { asU8A, compare, fromString } from './byte-utils.js'

import { encodeUint, encodeUintValue } from './0uint.js'
import { encodeNegint } from './1negint.js'
import { encodeBytes } from './2bytes.js'
import { encodeString } from './3string.js'
import { encodeArray } from './4array.js'
import { encodeMap } from './5map.js'
import { encodeTag } from './6tag.js'
import { encodeFloat, MINOR_FALSE, MINOR_TRUE, MINOR_NULL, MINOR_UNDEFINED } from './7float.js'

/**
 * @typedef {import('../interface.js').EncodeOptions} EncodeOptions
 * @typedef {import('../interface.js').OptionalTypeEncoder} OptionalTypeEncoder
 * @typedef {import('../interface.js').Reference} Reference
 * @typedef {import('../interface.js').StrictTypeEncoder} StrictTypeEncoder
 * @typedef {import('../interface.js').TokenTypeEncoder} TokenTypeEncoder
 * @typedef {import('../interface.js').TokenOrNestedTokens} TokenOrNestedTokens
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 */

/** @type {EncodeOptions} */
const defaultEncodeOptions = {
  float64: false,
  mapSorter,
  quickEncodeToken
}

/** @type {EncodeOptions} */
export const rfc8949EncodeOptions = Object.freeze({
  mapSorter: rfc8949MapSorter,
  quickEncodeToken
})

/** @returns {TokenTypeEncoder[]} */
export function makeCborEncoders () {
  const encoders = []
  encoders[Type.uint.major] = encodeUint
  encoders[Type.negint.major] = encodeNegint
  encoders[Type.bytes.major] = encodeBytes
  encoders[Type.string.major] = encodeString
  encoders[Type.array.major] = encodeArray
  encoders[Type.map.major] = encodeMap
  encoders[Type.tag.major] = encodeTag
  encoders[Type.float.major] = encodeFloat
  return encoders
}

const cborEncoders = makeCborEncoders()

const defaultWriter = new Bl()

/** @implements {Reference} */
class Ref {
  /**
   * @param {object|any[]} obj
   * @param {Reference|undefined} parent
   */
  constructor (obj, parent) {
    this.obj = obj
    this.parent = parent
  }

  /**
   * @param {object|any[]} obj
   * @returns {boolean}
   */
  includes (obj) {
    /** @type {Reference|undefined} */
    let p = this
    do {
      if (p.obj === obj) {
        return true
      }
    } while (p = p.parent) // eslint-disable-line
    return false
  }

  /**
   * @param {Reference|undefined} stack
   * @param {object|any[]} obj
   * @returns {Reference}
   */
  static createCheck (stack, obj) {
    if (stack && stack.includes(obj)) {
      throw new Error(`${encodeErrPrefix} object contains circular references`)
    }
    return new Ref(obj, stack)
  }
}

const simpleTokens = {
  null: new Token(Type.null, null),
  undefined: new Token(Type.undefined, undefined),
  true: new Token(Type.true, true),
  false: new Token(Type.false, false),
  emptyArray: new Token(Type.array, 0),
  emptyMap: new Token(Type.map, 0)
}

/** @type {{[typeName: string]: StrictTypeEncoder}} */
const typeEncoders = {
  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  number (obj, _typ, _options, _refStack) {
    if (!Number.isInteger(obj) || !Number.isSafeInteger(obj)) {
      return new Token(Type.float, obj)
    } else if (obj >= 0) {
      return new Token(Type.uint, obj)
    } else {
      return new Token(Type.negint, obj)
    }
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  bigint (obj, _typ, _options, _refStack) {
    if (obj >= BigInt(0)) {
      return new Token(Type.uint, obj)
    } else {
      return new Token(Type.negint, obj)
    }
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  Uint8Array (obj, _typ, _options, _refStack) {
    return new Token(Type.bytes, obj)
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  string (obj, _typ, _options, _refStack) {
    return new Token(Type.string, obj)
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  boolean (obj, _typ, _options, _refStack) {
    return obj ? simpleTokens.true : simpleTokens.false
  },

  /**
   * @param {any} _obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  null (_obj, _typ, _options, _refStack) {
    return simpleTokens.null
  },

  /**
   * @param {any} _obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  undefined (_obj, _typ, _options, _refStack) {
    return simpleTokens.undefined
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  ArrayBuffer (obj, _typ, _options, _refStack) {
    return new Token(Type.bytes, new Uint8Array(obj))
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  DataView (obj, _typ, _options, _refStack) {
    return new Token(Type.bytes, new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength))
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} options
   * @param {Reference} [refStack]
   * @returns {TokenOrNestedTokens}
   */
  Array (obj, _typ, options, refStack) {
    if (!obj.length) {
      if (options.addBreakTokens === true) {
        return [simpleTokens.emptyArray, new Token(Type.break)]
      }
      return simpleTokens.emptyArray
    }
    refStack = Ref.createCheck(refStack, obj)
    const entries = []
    let i = 0
    for (const e of obj) {
      entries[i++] = objectToTokens(e, options, refStack)
    }
    if (options.addBreakTokens) {
      return [new Token(Type.array, obj.length), entries, new Token(Type.break)]
    }
    return [new Token(Type.array, obj.length), entries]
  },

  /**
   * @param {any} obj
   * @param {string} typ
   * @param {EncodeOptions} options
   * @param {Reference} [refStack]
   * @returns {TokenOrNestedTokens}
   */
  Object (obj, typ, options, refStack) {
    // could be an Object or a Map
    const isMap = typ !== 'Object'
    // it's slightly quicker to use Object.keys() than Object.entries()
    const keys = isMap ? obj.keys() : Object.keys(obj)
    const maxLength = isMap ? obj.size : keys.length

    /** @type {undefined | [TokenOrNestedTokens, TokenOrNestedTokens][]} */
    let entries

    if (maxLength) {
      // Pre-allocate the array with the expected size
      entries = new Array(maxLength)
      refStack = Ref.createCheck(refStack, obj)
      const skipUndefined = !isMap && options.ignoreUndefinedProperties

      let i = 0
      for (const key of keys) {
        const value = isMap ? obj.get(key) : obj[key]
        if (skipUndefined && value === undefined) {
          continue
        }
        entries[i++] = [
          objectToTokens(key, options, refStack),
          objectToTokens(value, options, refStack)
        ]
      }

      // Truncate only if properties were skipped
      if (i < maxLength) {
        entries.length = i
      }
    }

    if (!entries?.length) {
      if (options.addBreakTokens === true) {
        return [simpleTokens.emptyMap, new Token(Type.break)]
      }
      return simpleTokens.emptyMap
    }

    sortMapEntries(entries, options)
    if (options.addBreakTokens) {
      return [new Token(Type.map, entries.length), entries, new Token(Type.break)]
    }
    return [new Token(Type.map, entries.length), entries]
  },

  /**
   * Encode a `Tagged` wrapper as a CBOR tag header followed by the encoded
   * form of the wrapped value. The value is recursively tokenised through
   * `objectToTokens()` so any registered `typeEncoders` apply to it.
   *
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} options
   * @param {Reference} [refStack]
   * @returns {TokenOrNestedTokens}
   */
  Tagged (obj, _typ, options, refStack) {
    return [
      new Token(Type.tag, obj.tag),
      objectToTokens(obj.value, options, refStack)
    ]
  }
}

typeEncoders.Map = typeEncoders.Object
typeEncoders.Buffer = typeEncoders.Uint8Array
for (const typ of 'Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64'.split(' ')) {
  typeEncoders[`${typ}Array`] = typeEncoders.DataView
}

/**
 * @param {any} obj
 * @param {EncodeOptions} [options]
 * @param {Reference} [refStack]
 * @returns {TokenOrNestedTokens}
 */
function objectToTokens (obj, options = {}, refStack) {
  const typ = is(obj)
  const customTypeEncoder = (options && options.typeEncoders && /** @type {OptionalTypeEncoder} */ options.typeEncoders[typ]) || typeEncoders[typ]
  if (typeof customTypeEncoder === 'function') {
    const tokens = customTypeEncoder(obj, typ, options, refStack)
    if (tokens != null) {
      return tokens
    }
  }
  const typeEncoder = typeEncoders[typ]
  if (!typeEncoder) {
    throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`)
  }
  return typeEncoder(obj, typ, options, refStack)
}

/*
CBOR key sorting is a mess.

The canonicalisation recommendation from https://tools.ietf.org/html/rfc7049#section-3.9
includes the wording:

> The keys in every map must be sorted lowest value to highest.
> Sorting is performed on the bytes of the representation of the key
> data items without paying attention to the 3/5 bit splitting for
> major types.
> ...
>  *  If two keys have different lengths, the shorter one sorts
      earlier;
>  *  If two keys have the same length, the one with the lower value
      in (byte-wise) lexical order sorts earlier.

1. It is not clear what "bytes of the representation of the key" means: is it
   the CBOR representation, or the binary representation of the object itself?
   Consider the int and uint difference here.
2. It is not clear what "without paying attention to" means: do we include it
   and compare on that? Or do we omit the special prefix byte, (mostly) treating
   the key in its plain binary representation form.

The FIDO 2.0: Client To Authenticator Protocol spec takes the original CBOR
wording and clarifies it according to their understanding.
https://fidoalliance.org/specs/fido-v2.0-rd-20170927/fido-client-to-authenticator-protocol-v2.0-rd-20170927.html#message-encoding

> The keys in every map must be sorted lowest value to highest. Sorting is
> performed on the bytes of the representation of the key data items without
> paying attention to the 3/5 bit splitting for major types. The sorting rules
> are:
>  * If the major types are different, the one with the lower value in numerical
>    order sorts earlier.
>  * If two keys have different lengths, the shorter one sorts earlier;
>  * If two keys have the same length, the one with the lower value in
>    (byte-wise) lexical order sorts earlier.

Some other implementations, such as borc, do a full encode then do a
length-first, byte-wise-second comparison:
https://github.com/dignifiedquire/borc/blob/b6bae8b0bcde7c3976b0f0f0957208095c392a36/src/encoder.js#L358
https://github.com/dignifiedquire/borc/blob/b6bae8b0bcde7c3976b0f0f0957208095c392a36/src/utils.js#L143-L151

This has the benefit of being able to easily handle arbitrary keys, including
complex types (maps and arrays).

We'll opt for the FIDO approach, since it affords some efficies since we don't
need a full encode of each key to determine order and can defer to the types
to determine how to most efficiently order their values (i.e. int and uint
ordering can be done on the numbers, no need for byte-wise, for example).

Recommendation: stick to single key types or you'll get into trouble, and prefer
string keys because it's much simpler that way.
*/

/**
 * @param {TokenOrNestedTokens[]} entries
 * @param {EncodeOptions} options
 */
function sortMapEntries (entries, options) {
  if (options.mapSorter) {
    entries.sort(options.mapSorter)
  }
}

/**
 * @param {(Token|Token[])[]} e1
 * @param {(Token|Token[])[]} e2
 * @returns {number}
 */
function mapSorter (e1, e2) {
  // the key position ([0]) could have a single token or an array
  // almost always it'll be a single token but complex key might get involved
  const keyToken1 = Array.isArray(e1[0]) ? e1[0][0] : e1[0]
  const keyToken2 = Array.isArray(e2[0]) ? e2[0][0] : e2[0]

  // different key types
  if (keyToken1.type !== keyToken2.type) {
    return keyToken1.type.compare(keyToken2.type)
  }

  const major = keyToken1.type.major
  // TODO: handle case where cmp === 0 but there are more keyToken e. complex type)
  const tcmp = cborEncoders[major].compareTokens(keyToken1, keyToken2)
  if (tcmp === 0) {
    // duplicate key or complex type where the first token matched,
    // i.e. a map or array and we're only comparing the opening token
    console.warn('WARNING: complex key types used, CBOR key sorting guarantees are gone')
  }
  return tcmp
}

/**
 * @typedef {Token & { _keyBytes?: Uint8Array }} TokenEx
 *
 * @param {(Token|Token[])[]} e1
 * @param {(Token|Token[])[]} e2
 * @returns {number}
 */
function rfc8949MapSorter (e1, e2) {
  if (e1[0] instanceof Token && e2[0] instanceof Token) {
    const t1 = /** @type {TokenEx} */ (e1[0])
    const t2 = /** @type {TokenEx} */ (e2[0])

    if (!t1._keyBytes) {
      t1._keyBytes = encodeRfc8949(t1.value)
    }

    if (!t2._keyBytes) {
      t2._keyBytes = encodeRfc8949(t2.value)
    }

    return compare(t1._keyBytes, t2._keyBytes)
  }

  throw new Error('rfc8949MapSorter: complex key types are not supported yet')
}

/**
 * @param {any} data
 * @returns {Uint8Array}
 */
function encodeRfc8949 (data) {
  return encodeCustom(data, cborEncoders, rfc8949EncodeOptions)
}

/**
 * @param {ByteWriter} writer
 * @param {TokenOrNestedTokens} tokens
 * @param {TokenTypeEncoder[]} encoders
 * @param {EncodeOptions} options
 */
function tokensToEncoded (writer, tokens, encoders, options) {
  if (Array.isArray(tokens)) {
    for (const token of tokens) {
      tokensToEncoded(writer, token, encoders, options)
    }
  } else {
    encoders[tokens.type.major](writer, tokens, options)
  }
}

// CBOR major type prefixes, cached from Type for hot path performance
const MAJOR_UINT = Type.uint.majorEncoded
const MAJOR_NEGINT = Type.negint.majorEncoded
const MAJOR_BYTES = Type.bytes.majorEncoded
const MAJOR_STRING = Type.string.majorEncoded
const MAJOR_ARRAY = Type.array.majorEncoded

// Simple value bytes (CBOR major type 7 + minor value)
const SIMPLE_FALSE = Type.float.majorEncoded | MINOR_FALSE
const SIMPLE_TRUE = Type.float.majorEncoded | MINOR_TRUE
const SIMPLE_NULL = Type.float.majorEncoded | MINOR_NULL
const SIMPLE_UNDEFINED = Type.float.majorEncoded | MINOR_UNDEFINED

const neg1b = BigInt(-1)
const pos1b = BigInt(1)

/**
 * Check if direct encoding can be used for the given options.
 * Direct encoding bypasses token creation for most values.
 * @param {EncodeOptions} options
 * @returns {boolean}
 */
function canDirectEncode (options) {
  // Cannot use direct encode with addBreakTokens (needs special break token handling).
  // Direct encode checks typeEncoders per-value, falling back to tokens as needed.
  // Maps fall back to token-based encoding for efficient key sorting.
  return options.addBreakTokens !== true
}

/**
 * Direct encode a value to the writer, bypassing token creation for most types.
 * Falls back to token-based encoding for custom type encoders.
 * @param {ByteWriter} writer
 * @param {any} data
 * @param {EncodeOptions} options
 * @param {Reference|undefined} refStack
 */
function directEncode (writer, data, options, refStack) {
  const typ = is(data)

  // Check for custom encoder for THIS specific type
  const customEncoder = options.typeEncoders && options.typeEncoders[typ]
  if (customEncoder) {
    const tokens = customEncoder(data, typ, options, refStack)
    if (tokens != null) {
      // Custom encoder returned tokens, serialize immediately
      tokensToEncoded(writer, tokens, cborEncoders, options)
      return
    }
    // Custom encoder returned null, fall through to default handling
  }

  // Direct encode based on type
  switch (typ) {
    case 'null':
      writer.push([SIMPLE_NULL])
      return

    case 'undefined':
      writer.push([SIMPLE_UNDEFINED])
      return

    case 'boolean':
      writer.push([data ? SIMPLE_TRUE : SIMPLE_FALSE])
      return

    case 'number':
      if (!Number.isInteger(data) || !Number.isSafeInteger(data)) {
        // Float, use token encoder for complex float encoding
        encodeFloat(writer, new Token(Type.float, data), options)
      } else if (data >= 0) {
        encodeUintValue(writer, MAJOR_UINT, data)
      } else {
        // Negative integer
        encodeUintValue(writer, MAJOR_NEGINT, data * -1 - 1)
      }
      return

    case 'bigint':
      if (data >= BigInt(0)) {
        encodeUintValue(writer, MAJOR_UINT, data)
      } else {
        encodeUintValue(writer, MAJOR_NEGINT, data * neg1b - pos1b)
      }
      return

    case 'string': {
      const bytes = fromString(data)
      encodeUintValue(writer, MAJOR_STRING, bytes.length)
      writer.push(bytes)
      return
    }

    case 'Uint8Array':
      encodeUintValue(writer, MAJOR_BYTES, data.length)
      writer.push(data)
      return

    case 'Array':
      if (!data.length) {
        writer.push([MAJOR_ARRAY]) // Empty array: 0x80
        return
      }
      refStack = Ref.createCheck(refStack, data)
      encodeUintValue(writer, MAJOR_ARRAY, data.length)
      for (const elem of data) {
        directEncode(writer, elem, options, refStack)
      }
      return

    case 'Object':
    case 'Map':
      // Maps require key sorting, use token-based encoding for efficiency
      // (pre-encoding all keys for sorting is expensive)
      {
        const tokens = typeEncoders.Object(data, typ, options, refStack)
        tokensToEncoded(writer, tokens, cborEncoders, options)
      }
      return

    default:
    // Fall back to token-based encoding for other types (DataView, TypedArrays, etc.)
    {
      const typeEncoder = typeEncoders[typ]
      if (!typeEncoder) {
        throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`)
      }
      const tokens = typeEncoder(data, typ, options, refStack)
      tokensToEncoded(writer, tokens, cborEncoders, options)
    }
  }
}

/**
 * @param {any} data
 * @param {TokenTypeEncoder[]} encoders
 * @param {EncodeOptions} options
 * @param {Uint8Array} [destination]
 * @returns {Uint8Array}
 */
function encodeCustom (data, encoders, options, destination) {
  // arg ordering is different to encodeInto for backward compatibility
  const hasDest = destination instanceof Uint8Array
  let writeTo = hasDest ? new U8Bl(destination) : defaultWriter

  const tokens = objectToTokens(data, options)
  if (!Array.isArray(tokens) && options.quickEncodeToken) {
    const quickBytes = options.quickEncodeToken(tokens)
    if (quickBytes) {
      if (hasDest) {
        // Copy quick bytes into destination buffer
        writeTo.push(quickBytes)
        return writeTo.toBytes()
      }
      return quickBytes
    }
    const encoder = encoders[tokens.type.major]
    if (encoder.encodedSize) {
      const size = encoder.encodedSize(tokens, options)
      if (!hasDest) {
        writeTo = new Bl(size)
      }
      encoder(writeTo, tokens, options)
      // this would be a problem with encodedSize() functions
      if (writeTo.chunks.length !== 1) {
        throw new Error(`Unexpected error: pre-calculated length for ${tokens} was wrong`)
      }
      return hasDest ? writeTo.toBytes() : asU8A(writeTo.chunks[0])
    }
  }
  writeTo.reset()
  tokensToEncoded(writeTo, tokens, encoders, options)
  return writeTo.toBytes(true)
}

/**
 * @param {any} data
 * @param {EncodeOptions} [options]
 * @returns {Uint8Array}
 */
function encode (data, options) {
  options = Object.assign({}, defaultEncodeOptions, options)

  // Use direct encode path when possible
  if (canDirectEncode(options)) {
    defaultWriter.reset()
    directEncode(defaultWriter, data, options, undefined)
    return defaultWriter.toBytes(true)
  }

  return encodeCustom(data, cborEncoders, options)
}

/**
 * @param {any} data
 * @param {Uint8Array} destination
 * @param {EncodeOptions} [options]
 * @returns {{ written: number }}
 */
function encodeInto (data, destination, options) {
  options = Object.assign({}, defaultEncodeOptions, options)

  // Use direct encode path when possible
  if (canDirectEncode(options)) {
    const writer = new U8Bl(destination)
    directEncode(writer, data, options, undefined)
    return { written: writer.toBytes().length }
  }

  const result = encodeCustom(data, cborEncoders, options, destination)
  return { written: result.length }
}

export { objectToTokens, encode, encodeCustom, encodeInto, Ref }
// This is an unfortunate replacement for @sindresorhus/is that we need to
// re-implement for performance purposes. In particular the is.observable()
// check is expensive, and unnecessary for our purposes. The values returned
// are compatible with @sindresorhus/is, however.

// Types that reach getObjectType() - excludes types with fast-paths above:
// primitives (typeof), Array (isArray), Uint8Array (instanceof), plain Object (constructor)
const objectTypeNames = [
  'Object', // for Object.create(null) and other non-plain objects
  'RegExp',
  'Date',
  'Error',
  'Map',
  'Set',
  'WeakMap',
  'WeakSet',
  'ArrayBuffer',
  'SharedArrayBuffer',
  'DataView',
  'Promise',
  'URL',
  'HTMLElement',
  'Int8Array',
  'Uint8ClampedArray',
  'Int16Array',
  'Uint16Array',
  'Int32Array',
  'Uint32Array',
  'Float32Array',
  'Float64Array',
  'BigInt64Array',
  'BigUint64Array',
  'Tagged'
]

/**
 * @param {any} value
 * @returns {string}
 */
export function is (value) {
  if (value === null) {
    return 'null'
  }
  if (value === undefined) {
    return 'undefined'
  }
  if (value === true || value === false) {
    return 'boolean'
  }
  const typeOf = typeof value
  if (typeOf === 'string' || typeOf === 'number' || typeOf === 'bigint' || typeOf === 'symbol') {
    return typeOf
  }
  if (typeOf === 'function') {
    return 'Function'
  }
  if (Array.isArray(value)) {
    return 'Array'
  }
  // Also catches Node.js Buffer which extends Uint8Array
  if (value instanceof Uint8Array) {
    return 'Uint8Array'
  }
  // Fast path for plain objects (most common case after primitives/arrays/bytes)
  if (value.constructor === Object) {
    return 'Object'
  }
  const objectType = getObjectType(value)
  if (objectType) {
    return objectType
  }
  return 'Object'
}

/**
 * @param {any} value
 * @returns {string|undefined}
 */
function getObjectType (value) {
  const objectTypeName = Object.prototype.toString.call(value).slice(8, -1)
  if (objectTypeNames.includes(objectTypeName)) {
    return objectTypeName
  }
  return undefined
}
import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import * as negint from './1negint.js'
import * as bytes from './2bytes.js'
import * as string from './3string.js'
import * as array from './4array.js'
import * as map from './5map.js'
import * as tag from './6tag.js'
import * as float from './7float.js'
import { decodeErrPrefix } from './common.js'
import { fromArray } from './byte-utils.js'

/**
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 */
function invalidMinor (data, pos, minor) {
  throw new Error(`${decodeErrPrefix} encountered invalid minor (${minor}) for major ${data[pos] >>> 5}`)
}

/**
 * @param {string} msg
 * @returns {()=>any}
 */
function errorer (msg) {
  return () => { throw new Error(`${decodeErrPrefix} ${msg}`) }
}

/** @type {((data:Uint8Array, pos:number, minor:number, options?:DecodeOptions) => any)[]} */
export const jump = []

// unsigned integer, 0x00..0x17 (0..23)
for (let i = 0; i <= 0x17; i++) {
  jump[i] = invalidMinor // uint.decodeUintCompact, handled by quick[]
}
jump[0x18] = uint.decodeUint8 // unsigned integer, one-byte uint8_t follows
jump[0x19] = uint.decodeUint16 // unsigned integer, two-byte uint16_t follows
jump[0x1a] = uint.decodeUint32 // unsigned integer, four-byte uint32_t follows
jump[0x1b] = uint.decodeUint64 // unsigned integer, eight-byte uint64_t follows
jump[0x1c] = invalidMinor
jump[0x1d] = invalidMinor
jump[0x1e] = invalidMinor
jump[0x1f] = invalidMinor
// negative integer, -1-0x00..-1-0x17 (-1..-24)
for (let i = 0x20; i <= 0x37; i++) {
  jump[i] = invalidMinor // negintDecode, handled by quick[]
}
jump[0x38] = negint.decodeNegint8 // negative integer, -1-n one-byte uint8_t for n follows
jump[0x39] = negint.decodeNegint16 // negative integer, -1-n two-byte uint16_t for n follows
jump[0x3a] = negint.decodeNegint32 // negative integer, -1-n four-byte uint32_t for follows
jump[0x3b] = negint.decodeNegint64 // negative integer, -1-n eight-byte uint64_t for follows
jump[0x3c] = invalidMinor
jump[0x3d] = invalidMinor
jump[0x3e] = invalidMinor
jump[0x3f] = invalidMinor
// byte string, 0x00..0x17 bytes follow
for (let i = 0x40; i <= 0x57; i++) {
  jump[i] = bytes.decodeBytesCompact
}
jump[0x58] = bytes.decodeBytes8 // byte string, one-byte uint8_t for n, and then n bytes follow
jump[0x59] = bytes.decodeBytes16 // byte string, two-byte uint16_t for n, and then n bytes follow
jump[0x5a] = bytes.decodeBytes32 // byte string, four-byte uint32_t for n, and then n bytes follow
jump[0x5b] = bytes.decodeBytes64 // byte string, eight-byte uint64_t for n, and then n bytes follow
jump[0x5c] = invalidMinor
jump[0x5d] = invalidMinor
jump[0x5e] = invalidMinor
jump[0x5f] = errorer('indefinite length bytes/strings are not supported') // byte string, byte strings follow, terminated by "break"
// UTF-8 string 0x00..0x17 bytes follow
for (let i = 0x60; i <= 0x77; i++) {
  jump[i] = string.decodeStringCompact
}
jump[0x78] = string.decodeString8 // UTF-8 string, one-byte uint8_t for n, and then n bytes follow
jump[0x79] = string.decodeString16 // UTF-8 string, two-byte uint16_t for n, and then n bytes follow
jump[0x7a] = string.decodeString32 // UTF-8 string, four-byte uint32_t for n, and then n bytes follow
jump[0x7b] = string.decodeString64 // UTF-8 string, eight-byte uint64_t for n, and then n bytes follow
jump[0x7c] = invalidMinor
jump[0x7d] = invalidMinor
jump[0x7e] = invalidMinor
jump[0x7f] = errorer('indefinite length bytes/strings are not supported') // UTF-8 strings follow, terminated by "break"
// array, 0x00..0x17 data items follow
for (let i = 0x80; i <= 0x97; i++) {
  jump[i] = array.decodeArrayCompact
}
jump[0x98] = array.decodeArray8 // array, one-byte uint8_t for n, and then n data items follow
jump[0x99] = array.decodeArray16 // array, two-byte uint16_t for n, and then n data items follow
jump[0x9a] = array.decodeArray32 // array, four-byte uint32_t for n, and then n data items follow
jump[0x9b] = array.decodeArray64 // array, eight-byte uint64_t for n, and then n data items follow
jump[0x9c] = invalidMinor
jump[0x9d] = invalidMinor
jump[0x9e] = invalidMinor
jump[0x9f] = array.decodeArrayIndefinite // array, data items follow, terminated by "break"
// map, 0x00..0x17 pairs of data items follow
for (let i = 0xa0; i <= 0xb7; i++) {
  jump[i] = map.decodeMapCompact
}
jump[0xb8] = map.decodeMap8 // map, one-byte uint8_t for n, and then n pairs of data items follow
jump[0xb9] = map.decodeMap16 // map, two-byte uint16_t for n, and then n pairs of data items follow
jump[0xba] = map.decodeMap32 // map, four-byte uint32_t for n, and then n pairs of data items follow
jump[0xbb] = map.decodeMap64 // map, eight-byte uint64_t for n, and then n pairs of data items follow
jump[0xbc] = invalidMinor
jump[0xbd] = invalidMinor
jump[0xbe] = invalidMinor
jump[0xbf] = map.decodeMapIndefinite // map, pairs of data items follow, terminated by "break"
// tags
for (let i = 0xc0; i <= 0xd7; i++) {
  jump[i] = tag.decodeTagCompact
}
jump[0xd8] = tag.decodeTag8
jump[0xd9] = tag.decodeTag16
jump[0xda] = tag.decodeTag32
jump[0xdb] = tag.decodeTag64
jump[0xdc] = invalidMinor
jump[0xdd] = invalidMinor
jump[0xde] = invalidMinor
jump[0xdf] = invalidMinor
// 0xe0..0xf3 simple values, unsupported
for (let i = 0xe0; i <= 0xf3; i++) {
  jump[i] = errorer('simple values are not supported')
}
jump[0xf4] = invalidMinor // false, handled by quick[]
jump[0xf5] = invalidMinor // true, handled by quick[]
jump[0xf6] = invalidMinor // null, handled by quick[]
jump[0xf7] = float.decodeUndefined // undefined
jump[0xf8] = errorer('simple values are not supported') // simple value, one byte follows, unsupported
jump[0xf9] = float.decodeFloat16 // half-precision float (two-byte IEEE 754)
jump[0xfa] = float.decodeFloat32 // single-precision float (four-byte IEEE 754)
jump[0xfb] = float.decodeFloat64 // double-precision float (eight-byte IEEE 754)
jump[0xfc] = invalidMinor
jump[0xfd] = invalidMinor
jump[0xfe] = invalidMinor
jump[0xff] = float.decodeBreak // "break" stop code

/** @type {Token[]} */
export const quick = []
// ints <24
for (let i = 0; i < 24; i++) {
  quick[i] = new Token(Type.uint, i, 1)
}
// negints >= -24
for (let i = -1; i >= -24; i--) {
  quick[31 - i] = new Token(Type.negint, i, 1)
}
// empty bytes
quick[0x40] = new Token(Type.bytes, new Uint8Array(0), 1)
// empty string
quick[0x60] = new Token(Type.string, '', 1)
// empty list
quick[0x80] = new Token(Type.array, 0, 1)
// empty map
quick[0xa0] = new Token(Type.map, 0, 1)
// false
quick[0xf4] = new Token(Type.false, false, 1)
// true
quick[0xf5] = new Token(Type.true, true, 1)
// null
quick[0xf6] = new Token(Type.null, null, 1)

/**
 * @param {Token} token
 * @returns {Uint8Array|undefined}
 */
export function quickEncodeToken (token) {
  switch (token.type) {
    case Type.false:
      return fromArray([0xf4])
    case Type.true:
      return fromArray([0xf5])
    case Type.null:
      return fromArray([0xf6])
    case Type.bytes:
      if (!token.value.length) {
        return fromArray([0x40])
      }
      return
    case Type.string:
      if (token.value === '') {
        return fromArray([0x60])
      }
      return
    case Type.array:
      if (token.value === 0) {
        return fromArray([0x80])
      }
      // shouldn't be possible if this were called when there was only one token
      return
    case Type.map:
      if (token.value === 0) {
        return fromArray([0xa0])
      }
      // shouldn't be possible if this were called when there was only one token
      return
    case Type.uint:
      if (token.value < 24) {
        return fromArray([Number(token.value)])
      }
      return
    case Type.negint:
      if (token.value >= -24) {
        return fromArray([31 - Number(token.value)])
      }
  }
}
/**
 * @typedef {import('../interface.js').TagDecodeControl} TagDecodeControl
 * @typedef {(decode: TagDecodeControl) => Tagged} TaggedTagDecoder
 */

/**
 * A wrapper class for representing a CBOR tag with an arbitrary nested value.
 *
 * `Tagged` is a symmetric primitive: it can be passed to `encode()` to emit
 * a CBOR tag header followed by the encoded form of `value`, and it can be
 * returned from a tag decoder (via `Tagged.decoder(tag)` or `Tagged.preserve()`)
 * to round-trip a tag through decode without losing the tag number.
 *
 * Use `Tagged` for one-off tag handling where defining a dedicated
 * `typeEncoders` entry and tag decoder pair would be heavyweight, e.g. when
 * wrapping a structure in a single application-specific tag (COSE, dCBOR
 * envelopes, etc.).
 *
 * For systematic mapping of a JS type to a tag (e.g. CID -> tag 42), prefer
 * a dedicated `typeEncoders` entry instead.
 */
export class Tagged {
  /**
   * @param {number} tag - CBOR tag number, a non-negative integer
   * @param {any} value - The value to be tagged; encoded recursively
   */
  constructor (tag, value) {
    if (typeof tag !== 'number' || !Number.isInteger(tag) || tag < 0) {
      throw new TypeError('Tagged: tag must be a non-negative integer')
    }
    this.tag = tag
    this.value = value
  }

  /**
   * Build a tag decoder for use in `decode()`'s `tags` option that returns the
   * decoded content wrapped in a `Tagged` instance, preserving the tag number
   * for the caller to inspect.
   *
   * @param {number} tag - The CBOR tag number this decoder will be registered for
   * @returns {TaggedTagDecoder}
   *
   * @example
   * import { decode, Tagged } from 'cborg'
   * const value = decode(bytes, { tags: { 16: Tagged.decoder(16) } })
   * // value instanceof Tagged; value.tag === 16
   */
  static decoder (tag) {
    return (decode) => new Tagged(tag, decode())
  }

  /**
   * Build a `tags` option for `decode()` that wraps each listed tag number in
   * a `Tagged` instance, preserving those tags through decode without
   * registering a dedicated decoder per tag.
   *
   * @param {...number} tagNumbers - One or more CBOR tag numbers to preserve
   * @returns {{[tagNumber: number]: TaggedTagDecoder}}
   *
   * @example
   * import { decode, Tagged } from 'cborg'
   * const value = decode(bytes, { tags: Tagged.preserve(16, 96) })
   */
  static preserve (...tagNumbers) {
    /** @type {{[tagNumber: number]: TaggedTagDecoder}} */
    const tags = {}
    for (const tag of tagNumbers) {
      tags[tag] = Tagged.decoder(tag)
    }
    return tags
  }
}

// Symbol.toStringTag so the internal `is()` type detection returns 'Tagged'
// for instances, allowing the default Tagged typeEncoder to match.
Object.defineProperty(Tagged.prototype, Symbol.toStringTag, {
  value: 'Tagged'
})
class Type {
  /**
   * @param {number} major
   * @param {string} name
   * @param {boolean} terminal
   */
  constructor (major, name, terminal) {
    this.major = major
    this.majorEncoded = major << 5
    this.name = name
    this.terminal = terminal
  }

  toString () {
    return `Type[${this.major}].${this.name}`
  }

  /**
   * @param {Type} typ
   * @returns {number}
   */
  compare (typ) {
    return this.major < typ.major ? -1 : this.major > typ.major ? 1 : 0
  }

  /**
   * Check equality between two Type instances. Safe to use across different
   * copies of the Type class (e.g., when bundlers duplicate the module).
   * (major, name) uniquely identifies a Type; terminal is implied by these.
   * @param {Type} a
   * @param {Type} b
   * @returns {boolean}
   */
  static equals (a, b) {
    return a === b || (a.major === b.major && a.name === b.name)
  }
}

// convert to static fields when better supported
Type.uint = new Type(0, 'uint', true)
Type.negint = new Type(1, 'negint', true)
Type.bytes = new Type(2, 'bytes', true)
Type.string = new Type(3, 'string', true)
Type.array = new Type(4, 'array', false)
Type.map = new Type(5, 'map', false)
Type.tag = new Type(6, 'tag', false) // terminal?
Type.float = new Type(7, 'float', true)
Type.false = new Type(7, 'false', true)
Type.true = new Type(7, 'true', true)
Type.null = new Type(7, 'null', true)
Type.undefined = new Type(7, 'undefined', true)
Type.break = new Type(7, 'break', true)
// Type.indefiniteLength = new Type(0, 'indefiniteLength', true)

class Token {
  /**
   * @param {Type} type
   * @param {any} [value]
   * @param {number} [encodedLength]
   */
  constructor (type, value, encodedLength) {
    this.type = type
    this.value = value
    this.encodedLength = encodedLength
    /** @type {Uint8Array|undefined} */
    this.encodedBytes = undefined
    /** @type {Uint8Array|undefined} */
    this.byteValue = undefined
  }

  toString () {
    return `Token[${this.type}].${this.value}`
  }
}

export { Type, Token }
{
  "name": "cborg",
  "version": "5.1.6",
  "description": "Fast CBOR with a focus on strictness",
  "main": "cborg.js",
  "type": "module",
  "bin": {
    "cborg": "lib/bin.js"
  },
  "scripts": {
    "lint": "standard *.js lib/*.js test/*.js",
    "build": "npm run build:types",
    "build:types": "tsc --build",
    "prepublishOnly": "npm run build",
    "test:node": "mocha test/test-*.js",
    "test:node-bin": "mocha test/node-test-bin.js",
    "test:browser": "polendina --cleanup test/test-*.js",
    "test": "npm run lint && npm run build && npm run test:node && npm run test:node-bin && npm run test:browser",
    "test:ci": "npm run test"
  },
  "repository": {
    "type": "git",
    "url": "git@github.com:rvagg/cborg.git"
  },
  "keywords": [
    "cbor"
  ],
  "author": "Rod <rod@vagg.org> (http://r.va.gg/)",
  "license": "Apache-2.0",
  "devDependencies": {
    "@semantic-release/changelog": "^6.0.3",
    "@semantic-release/commit-analyzer": "^13.0.1",
    "@semantic-release/git": "^10.0.1",
    "@semantic-release/github": "^12.0.6",
    "@semantic-release/npm": "^13.1.5",
    "@semantic-release/release-notes-generator": "^14.1.0",
    "@types/chai": "^5.2.3",
    "@types/mocha": "^10.0.10",
    "@types/node": "^26.0.1",
    "chai": "^6.2.2",
    "conventional-changelog-conventionalcommits": "^10.0.0",
    "ipld-garbage": "^5.0.0",
    "mocha": "^11.7.5",
    "polendina": "^3.2.20",
    "semantic-release": "^25.0.3",
    "standard": "^17.1.2",
    "typescript": "^6.0.2"
  },
  "exports": {
    ".": {
      "import": "./cborg.js",
      "types": "./types/cborg.d.ts"
    },
    "./length": {
      "import": "./lib/length.js",
      "types": "./types/lib/length.d.ts"
    },
    "./taglib": {
      "import": "./lib/taglib.js",
      "types": "./types/lib/taglib.d.ts"
    },
    "./json": {
      "import": "./lib/json/json.js",
      "types": "./types/lib/json/json.d.ts"
    },
    "./extended": {
      "import": "./lib/extended/extended.js",
      "types": "./types/lib/extended/extended.d.ts"
    },
    "./interface": {
      "types": "./types/interface.d.ts"
    }
  },
  "types": "cborg.d.ts",
  "typesVersions": {
    "*": {
      "json": [
        "types/lib/json/json.d.ts"
      ],
      "length": [
        "types/lib/length.d.ts"
      ],
      "*": [
        "types/*"
      ],
      "types/*": [
        "types/*"
      ]
    }
  },
  "release": {
    "branches": [
      "master"
    ],
    "plugins": [
      [
        "@semantic-release/commit-analyzer",
        {
          "preset": "conventionalcommits",
          "releaseRules": [
            {
              "breaking": true,
              "release": "major"
            },
            {
              "revert": true,
              "release": "patch"
            },
            {
              "type": "feat",
              "release": "minor"
            },
            {
              "type": "fix",
              "release": "patch"
            },
            {
              "type": "chore",
              "release": "patch"
            },
            {
              "type": "docs",
              "release": "patch"
            },
            {
              "type": "test",
              "release": "patch"
            },
            {
              "scope": "no-release",
              "release": false
            }
          ]
        }
      ],
      [
        "@semantic-release/release-notes-generator",
        {
          "preset": "conventionalcommits",
          "presetConfig": {
            "types": [
              {
                "type": "feat",
                "section": "Features"
              },
              {
                "type": "fix",
                "section": "Bug Fixes"
              },
              {
                "type": "chore",
                "section": "Trivial Changes"
              },
              {
                "type": "docs",
                "section": "Trivial Changes"
              },
              {
                "type": "test",
                "section": "Tests"
              }
            ]
          }
        }
      ],
      "@semantic-release/changelog",
      "@semantic-release/npm",
      "@semantic-release/github",
      "@semantic-release/git"
    ]
  }
}
const b4a = require('b4a')

module.exports = codecs

codecs.ascii = createString('ascii')
codecs.utf8 = createString('utf-8')
codecs.hex = createString('hex')
codecs.base64 = createString('base64')
codecs.ucs2 = createString('ucs2')
codecs.utf16le = createString('utf16le')
codecs.ndjson = createJSON(true)
codecs.json = createJSON(false)
codecs.binary = {
  name: 'binary',
  encode: function encodeBinary (obj) {
    return typeof obj === 'string'
      ? b4a.from(obj, 'utf-8')
      : b4a.toBuffer(obj)
  },
  decode: function decodeBinary (buf) {
    return b4a.toBuffer(buf)
  }
}

function isCompactEncoding (c) {
  return !!(c.encode && c.decode && c.preencode)
}

function fromCompactEncoding (c) {
  return {
    name: 'compact-encoding',
    encode: function encodeWithCompact (value) {
      const state = { start: 0, end: 0, buffer: null, cache: null }
      c.preencode(state, value)
      state.buffer = b4a.allocUnsafe(state.end)
      c.encode(state, value)
      return state.buffer
    },
    decode: function decodeWithCompact (buffer) {
      return c.decode({ start: 0, end: buffer.byteLength, buffer, cache: null })
    }
  }
}

function codecs (fmt, fallback) {
  if (typeof fmt === 'object' && fmt) {
    return isCompactEncoding(fmt) ? fromCompactEncoding(fmt) : fmt
  }

  switch (fmt) {
    case 'ndjson': return codecs.ndjson
    case 'json': return codecs.json
    case 'ascii': return codecs.ascii
    case 'utf-8':
    case 'utf8': return codecs.utf8
    case 'hex': return codecs.hex
    case 'base64': return codecs.base64
    case 'ucs-2':
    case 'ucs2': return codecs.ucs2
    case 'utf16-le':
    case 'utf16le': return codecs.utf16le
  }

  return fallback !== undefined ? fallback : codecs.binary
}

function createJSON (newline) {
  return {
    name: newline ? 'ndjson' : 'json',
    encode: newline ? encodeNDJSON : encodeJSON,
    decode: function decodeJSON (buf) {
      return JSON.parse(b4a.toString(buf))
    }
  }

  function encodeJSON (val) {
    return b4a.from(JSON.stringify(val))
  }

  function encodeNDJSON (val) {
    return b4a.from(JSON.stringify(val) + '\n')
  }
}

function createString (type) {
  return {
    name: type,
    encode: function encodeString (val) {
      if (typeof val !== 'string') val = val.toString()
      return b4a.from(val, type)
    },
    decode: function decodeString (buf) {
      return b4a.toString(buf, type)
    }
  }
}
{
  "name": "codecs",
  "version": "3.1.0",
  "description": "Create an binary encoder/decoder for json, utf-8 or custom types",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.6.3"
  },
  "devDependencies": {
    "brittle": "^3.2.1",
    "compact-encoding": "^2.11.0",
    "standard": "^17.0.0"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/codecs.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/codecs/issues"
  },
  "homepage": "https://github.com/mafintosh/codecs"
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
const b4a = require('b4a')
const Hypercore = require('hypercore')
const ReadyResource = require('ready-resource')
const sodium = require('sodium-universal')
const crypto = require('hypercore-crypto')
const ID = require('hypercore-id-encoding')
const { isAndroid } = require('which-runtime')
const { STORAGE_EMPTY, ASSERTION } = require('hypercore-errors')

const auditStore = require('./lib/audit.js')
const GroupNotifyHandle = require('./lib/notify.js')

const [NS] = crypto.namespace('corestore', 1)
const DEFAULT_NAMESPACE = b4a.alloc(32) // This is meant to be 32 0-bytes

class StreamTracker {
  constructor() {
    this.records = []
  }

  add(stream, isExternal) {
    const record = { index: 0, stream, isExternal }
    record.index = this.records.push(record) - 1
    return record
  }

  remove(record) {
    const popped = this.records.pop()
    if (popped === record) return
    this.records[(popped.index = record.index)] = popped
  }

  attachAll(core) {
    for (let i = 0; i < this.records.length; i++) {
      const record = this.records[i]
      const muxer = record.stream.noiseStream.userData
      if (!core.replicator.attached(muxer)) core.replicator.attachTo(muxer)
    }
  }

  destroy() {
    // reverse is safer cause we delete mb
    for (let i = this.records.length - 1; i >= 0; i--) {
      const record = this.records[i]
      if (!record.isExternal) record.stream.destroy()
    }
  }
}

class SessionTracker {
  constructor() {
    this.map = new Map()
  }

  get size() {
    return this.map.size
  }

  get(id) {
    const existing = this.map.get(id)
    if (existing !== undefined) return existing
    const fresh = []
    this.map.set(id, fresh)
    return fresh
  }

  gc(id) {
    this.map.delete(id)
  }

  list(id) {
    return id ? this.map.get(id) || [] : [...this]
  }

  *[Symbol.iterator]() {
    for (const sessions of this.map.values()) {
      yield* sessions[Symbol.iterator]()
    }
  }
}

class CoreTracker {
  constructor() {
    this.map = new Map()
    this.watching = []

    this._gcing = new Set()
    this._gcInterval = null
    this._gcCycleBound = this._gcCycle.bind(this)
  }

  get size() {
    return this.map.size
  }

  watch(store) {
    if (store.watchIndex !== -1) return
    store.watchIndex = this.watching.push(store) - 1
  }

  unwatch(store) {
    if (store.watchIndex === -1) return
    const head = this.watching.pop()
    if (head !== store) this.watching[(head.watchIndex = store.watchIndex)] = head
    store.watchIndex = -1
  }

  resume(id) {
    const core = this.map.get(id)

    if (!core) return null

    // signal back that we have a closing one stored
    if (core.closing) return core

    if (core.gc) {
      this._gcing.delete(core)
      if (this._gcing.size === 0) this._stopGC()
      core.gc = 0
    }

    return core
  }

  opened(id) {
    const core = this.map.get(id)
    return !!(core && core.opened && !core.closing)
  }

  get(id) {
    // we allow you do call this from the outside, so support normal buffers also
    if (b4a.isBuffer(id)) id = b4a.toString(id, 'hex')
    const core = this.map.get(id)
    if (!core || core.closing) return null
    return core
  }

  set(id, core) {
    this.map.set(id, core)
    if (this.watching.length > 0) this._emit(core)
  }

  _emit(core) {
    for (let i = this.watching.length - 1; i >= 0; i--) {
      const store = this.watching[i]
      for (const fn of store.watchers) fn(core)
    }
  }

  _gc(core) {
    const id = toHex(core.discoveryKey)
    if (this.map.get(id) === core) this.map.delete(id)
  }

  _gcCycle() {
    for (const core of this._gcing) {
      if (++core.gc < 4) continue
      const gc = this._gc.bind(this, core)
      core.close().then(gc, gc)
      this._gcing.delete(core)
    }

    if (this._gcing.size === 0) this._stopGC()
  }

  gc(core) {
    core.gc = 1 // first strike
    this._gcing.add(core)
    if (this._gcing.size === 1) this._startGC()
  }

  _stopGC() {
    clearInterval(this._gcInterval)
    this._gcInterval = null
  }

  _startGC() {
    if (this._gcInterval) return
    this._gcInterval = setInterval(this._gcCycleBound, 2000)
    if (this._gcInterval.unref) this._gcInterval.unref()
  }

  close() {
    this._stopGC()
    this._gcing.clear()

    const all = []
    for (const core of this.map.values()) {
      core.onidle = noop // no reentry
      all.push(core.close())
    }
    this.map.clear()

    return Promise.all(all)
  }

  *[Symbol.iterator]() {
    for (const core of this.map.values()) {
      if (!core.closing) yield core
    }
  }
}

class FindingPeers {
  constructor() {
    this.count = 0
    this.pending = []
    this.destroyed = false
  }

  add(core) {
    if (this.count === 0) return
    this.pending.push(core.findingPeers())
  }

  inc(sessions) {
    if (this.destroyed || ++this.count !== 1) return

    for (const core of sessions) {
      this.pending.push(core.findingPeers())
    }
  }

  dec(sessions) {
    if (this.destroyed || --this.count !== 0) return
    while (this.pending.length > 0) this.pending.pop()()
  }

  destroy() {
    this.destroyed = true
    while (this.pending.length > 0) this.pending.pop()()
  }
}

class Corestore extends ReadyResource {
  constructor(storage, opts = {}) {
    super()

    this.root = opts.root || null
    this.storage = this.root
      ? this.root.storage
      : Hypercore.defaultStorage(storage, {
          id: opts.id,
          allowBackup: opts.allowBackup,
          readOnly: opts.readOnly,
          wait: opts.wait
        })
    this.streamTracker = this.root ? this.root.streamTracker : new StreamTracker()
    this.cores = this.root ? this.root.cores : new CoreTracker()
    this.sessions = new SessionTracker()
    this.corestores = this.root ? this.root.corestores : new Set()
    this.readOnly = opts.writable === false || !!opts.readOnly
    this.globalCache = this.root ? this.root.globalCache : opts.globalCache || null
    this.primaryKey = this.root ? this.root.primaryKey : opts.primaryKey || null
    this.ns = opts.namespace || DEFAULT_NAMESPACE
    this.manifestVersion = opts.manifestVersion || 1
    this.shouldSuspend = isAndroid ? !!opts.suspend : opts.suspend !== false
    this.active = opts.active !== false

    this.watchers = null
    this.watchIndex = -1

    this._groupNotifiers = new Map() // group notifications
    this._findingPeers = null // here for legacy
    this._ongcBound = this._ongc.bind(this)
    this._onGroupActiveBound = this._onGroupActive.bind(this)

    if (opts.primaryKey && !this.root && !opts.unsafe) {
      throw ASSERTION(
        'Passing the primary key is unsafe unless you know what you are doing. Set unsafe: true to acknowledge that'
      )
    }

    this.ready().catch(noop)
  }

  watch(fn) {
    if (this.watchers === null) {
      this.watchers = new Set()
      this.cores.watch(this)
    }

    this.watchers.add(fn)
  }

  unwatch(fn) {
    if (this.watchers === null) return

    this.watchers.delete(fn)

    if (this.watchers.size === 0) {
      this.watchers = null
      this.cores.unwatch(this)
    }
  }

  _onGroupActive(topic, update) {
    this.emit('group-active', topic, update)

    const topicHex = b4a.toString(topic, 'hex')
    const handles = this._groupNotifiers.get(topicHex)
    if (!handles) return
    for (const handle of handles) handle.emit('update', update)
  }

  notifyGroup(topic) {
    const topicHex = b4a.toString(topic, 'hex')
    let handles = this._groupNotifiers.get(topicHex)

    if (!handles) {
      handles = []
      this._groupNotifiers.set(topicHex, handles)
    }

    const handle = new GroupNotifyHandle(this, topic)
    const length = handles.push(handle)
    handle.index = length - 1

    return handle
  }

  _removeGroupNotify(handle) {
    if (handle.index === -1) return

    const topicHex = b4a.toString(handle._topic, 'hex')
    const handles = this._groupNotifiers.get(topicHex)
    if (!handles) return

    const popped = handles.pop()
    if (popped !== handle) handles[(popped.index = handle.index)] = popped
    if (handles.length === 0) this._groupNotifiers.delete(topicHex)
    handle.index = -1
  }

  findingPeers() {
    if (this._findingPeers === null) this._findingPeers = new FindingPeers()
    this._findingPeers.inc(this.sessions)
    let done = false
    return () => {
      if (done || !this._findingPeers) return
      done = true
      this._findingPeers.dec(this.sessions)
    }
  }

  audit(opts = {}) {
    return auditStore(this, opts)
  }

  async suspend({ log = noop } = {}) {
    await log('Flushing db...')
    // If readOnly we don't need to flush
    if (!this.storage.readOnly) {
      await this.storage.db.flush()
      await log('Flusing db completed')
    }
    if (!this.shouldSuspend) return
    await log('Suspending db...')
    await this.storage.suspend({ log })
    await log('Suspending db completed')
  }

  resume() {
    return this.storage.resume()
  }

  session(opts) {
    this._maybeClosed()
    const root = this.root || this
    return new Corestore(null, {
      manifestVersion: this.manifestVersion,
      ...opts,
      root
    })
  }

  namespace(name, opts) {
    return this.session({
      ...opts,
      namespace: generateNamespace(this.ns, name)
    })
  }

  list(namespace) {
    return this.storage.createDiscoveryKeyStream(namespace)
  }

  getAuth(discoveryKey) {
    return this.storage.getAuth(discoveryKey)
  }

  _ongc(session) {
    if (session.sessions.length === 0) this.sessions.gc(session.id)
  }

  async _getOrSetSeed() {
    const seed = await this.storage.getSeed()
    if (seed !== null) return seed
    return await this.storage.setSeed(this.primaryKey || crypto.randomBytes(32))
  }

  async _open() {
    if (this.root !== null) {
      this.corestores.add(this)
      if (this.root.opened === false) await this.root.ready()
      this.primaryKey = this.root.primaryKey
      return
    }

    const primaryKey = await this._getOrSetSeed()

    if (this.primaryKey === null) {
      this.primaryKey = primaryKey
      return
    }

    if (!b4a.equals(primaryKey, this.primaryKey)) {
      throw new Error('Another corestore is stored here')
    }
  }

  async _close() {
    const closing = []
    const hanging = [...this.sessions]
    for (const sess of hanging) closing.push(sess.close())

    if (this.watchers !== null) {
      this.cores.unwatch(this)
      this.watchers = null
    }

    if (this._findingPeers !== null) {
      this._findingPeers.destroy()
      this._findingPeers = null
    }

    if (this.root !== null) {
      await Promise.all(closing)
      this.corestores.delete(this)
      return
    }

    for (const store of this.corestores) {
      closing.push(store.close())
    }

    await Promise.all(closing)

    await this.cores.close()
    await this.storage.close()
  }

  async _attachMaybe(muxer, discoveryKey) {
    if (this.opened === false) await this.ready()
    if (
      !this.cores.opened(toHex(discoveryKey)) &&
      !(await this.storage.hasCore(discoveryKey, { ifMigrated: true }))
    ) {
      return
    }
    if (this.closing) return

    const core = this._openCore(discoveryKey, { createIfMissing: false })

    if (!core) return
    if (!core.opened) await core.ready()

    if (!core.replicator.attached(muxer)) {
      core.replicator.attachTo(muxer)
    }

    core.checkIfIdle()
  }

  _shouldReplicate(core, muxer) {
    return (
      core.replicator.downloading && !core.replicator.attached(muxer) && core.opened && this.active
    )
  }

  replicate(isInitiator, opts) {
    this._maybeClosed()

    const isExternal = isStream(isInitiator)
    const stream = Hypercore.createProtocolStream(isInitiator, {
      ...opts,
      ondiscoverykey: (discoveryKey) => {
        if (this.closing) return
        const muxer = stream.noiseStream.userData
        return this._attachMaybe(muxer, discoveryKey)
      }
    })

    if (this.cores.size > 0) {
      const muxer = stream.noiseStream.userData
      const uncork = muxer.uncork.bind(muxer)
      muxer.cork()

      for (const core of this.cores) {
        if (!this._shouldReplicate(core, muxer)) {
          continue
        }
        core.replicator.attachTo(muxer)
      }

      stream.noiseStream.opened.then(uncork)
    }

    const record = this.streamTracker.add(stream, isExternal)
    stream.once('close', () => this.streamTracker.remove(record))
    return stream
  }

  _maybeClosed() {
    if (this.closing || (this.root !== null && this.root.closing)) {
      throw new Error('Corestore is closed')
    }
  }

  async staticify(core, opts) {
    if (!this.opened) await this.ready()
    if (!core.opened) await core.ready()

    const rx = core.state.storage.read()

    const headPromise = rx.getHead()
    const authPromise = rx.getAuth()

    rx.tryFlush()

    const [head, auth] = await Promise.all([headPromise, authPromise])
    if (!head || head.length === 0) throw new Error('Core must have data')

    const prologue = {
      length: head.length,
      hash: head.rootHash
    }

    const manifest = {
      version: 1,
      hash: auth.manifest.hash,
      quorum: 0,
      signers: [],
      prologue
    }

    const c = {
      key: null,
      discoveryKey: null,
      manifest,
      core: core.state.storage.core
    }

    c.key = Hypercore.key(c.manifest)
    c.discoveryKey = Hypercore.discoveryKey(c.key)

    await this.storage.createCore(c)

    const staticCore = this.get({ ...opts, key: c.key })
    await staticCore.ready()
    return staticCore
  }

  get(opts) {
    this._maybeClosed()

    if (b4a.isBuffer(opts) || typeof opts === 'string') opts = { key: opts }
    if (!opts) opts = {}

    const conf = {
      preload: null,
      sessions: null,
      ongc: null,
      core: null,
      active: opts.active !== false,
      encryption: opts.encryption || null,
      encryptionKey: opts.encryptionKey || null, // back compat, should remove
      isBlockKey: !!opts.isBlockKey, // back compat, should remove
      valueEncoding: opts.valueEncoding || null,
      exclusive: !!opts.exclusive,
      manifest: opts.manifest || null,
      keyPair: opts.keyPair || null,
      onwait: opts.onwait || null,
      pushOnly: opts.pushOnly === true,
      wait: opts.wait !== false,
      timeout: opts.timeout || 0,
      draft: !!opts.draft,
      writable: opts.writable === undefined && this.readOnly ? false : opts.writable
    }

    // name requires us to rt to storage + ready, so needs preload
    // same goes if user has defined async preload obvs
    if (opts.name || opts.preload) {
      conf.preload = this._preload(opts)
      return this._makeSession(conf)
    }

    if (opts.discoveryKey && !opts.key && !opts.manifest) {
      conf.preload = this._preloadCheckIfExists(opts)
      return this._makeSession(conf)
    }

    // if not not we can sync create it, which just is easier for the
    // upstream user in terms of guarantees (key is there etc etc)
    const core = this._openCore(null, opts)

    conf.core = core
    conf.sessions = this.sessions.get(core.id)
    conf.ongc = this._ongcBound

    return this._makeSession(conf)
  }

  _makeSession(conf) {
    const session = new Hypercore(null, null, conf)

    if (this._findingPeers !== null) this._findingPeers.add(session)
    return session
  }

  async createKeyPair(name, ns = this.ns) {
    if (this.opened === false) await this.ready()
    return createKeyPair(this.primaryKey, ns, name)
  }

  async _preloadCheckIfExists(opts) {
    const has = await this.storage.hasCore(opts.discoveryKey)
    if (!has) throw STORAGE_EMPTY('No Hypercore is stored here')
    return this._preload(opts)
  }

  async _preload(opts) {
    if (opts.preload) opts = { ...opts, ...(await opts.preload) }
    if (this.opened === false) await this.ready()

    const discoveryKey = opts.name
      ? await this.storage.getAlias({ name: opts.name, namespace: this.ns })
      : null
    this._maybeClosed()

    const core = this._openCore(discoveryKey, opts)

    return {
      core,
      sessions: this.sessions.get(core.id),
      ongc: this._ongcBound,
      manifest: opts.manifest || null,
      encryption: opts.encryption || null,
      encryptionKey: opts.encryptionKey || null, // back compat, should remove
      isBlockKey: !!opts.isBlockKey // back compat, should remove
    }
  }

  _auth(discoveryKey, opts) {
    const result = {
      keyPair: null,
      key: null,
      discoveryKey,
      manifest: null,
      group: null
    }

    if (opts.name) {
      result.keyPair = createKeyPair(this.primaryKey, this.ns, opts.name)
    } else if (opts.keyPair) {
      result.keyPair = opts.keyPair
    }

    if (opts.manifest) {
      result.manifest = opts.manifest
    } else if (result.keyPair && !result.discoveryKey) {
      result.manifest = {
        version: this.manifestVersion,
        signers: [{ publicKey: result.keyPair.publicKey }]
      }
    }

    if (opts.group) {
      result.group = opts.group
    }

    if (opts.key) result.key = ID.decode(opts.key)
    else if (result.manifest) result.key = Hypercore.key(result.manifest)

    if (result.discoveryKey) return result

    if (opts.discoveryKey) result.discoveryKey = ID.decode(opts.discoveryKey)
    else if (result.key) result.discoveryKey = crypto.discoveryKey(result.key)
    else throw new Error('Could not derive discovery from input')

    return result
  }

  _openCore(discoveryKey, opts) {
    const auth = this._auth(discoveryKey, opts)

    const id = toHex(auth.discoveryKey)
    const existing = this.cores.resume(id, auth.group)
    if (existing && !existing.closing) return existing

    const core = Hypercore.createCore(this.storage, {
      preopen: existing && existing.opened ? existing.closing : null, // always wait for the prev one to close first in any case...
      eagerUpgrade: true,
      notDownloadingLinger: opts.notDownloadingLinger,
      allowFork: opts.allowFork !== false,
      allowPush: !!opts.allowPush,
      inflightRange: opts.inflightRange,
      compat: false, // no compat for now :)
      force: opts.force,
      createIfMissing: opts.createIfMissing,
      discoveryKey: auth.discoveryKey,
      overwrite: opts.overwrite,
      key: auth.key,
      keyPair: auth.keyPair,
      legacy: opts.legacy,
      manifest: auth.manifest,
      group: auth.group,
      globalCache: opts.globalCache || this.globalCache || null,
      alias: opts.name ? { name: opts.name, namespace: this.ns } : null
    })

    core.onidle = () => {
      this.cores.gc(core)
    }

    core.ongroupupdate = this._onGroupActiveBound

    core.replicator.ondownloading = () => {
      if (this.active) this.streamTracker.attachAll(core)
    }

    this.cores.set(id, core)
    return core
  }
}

module.exports = Corestore

function isStream(s) {
  return typeof s === 'object' && s && typeof s.pipe === 'function'
}

function generateNamespace(namespace, name) {
  if (!b4a.isBuffer(name)) name = b4a.from(name)
  const out = b4a.allocUnsafeSlow(32)
  sodium.crypto_generichash_batch(out, [namespace, name])
  return out
}

function deriveSeed(primaryKey, namespace, name) {
  if (!b4a.isBuffer(name)) name = b4a.from(name)
  const out = b4a.alloc(32)
  sodium.crypto_generichash_batch(out, [NS, namespace, name], primaryKey)
  return out
}

function createKeyPair(primaryKey, namespace, name) {
  const seed = deriveSeed(primaryKey, namespace, name)
  const buf = b4a.alloc(sodium.crypto_sign_PUBLICKEYBYTES + sodium.crypto_sign_SECRETKEYBYTES)
  const keyPair = {
    publicKey: buf.subarray(0, sodium.crypto_sign_PUBLICKEYBYTES),
    secretKey: buf.subarray(sodium.crypto_sign_PUBLICKEYBYTES)
  }
  sodium.crypto_sign_seed_keypair(keyPair.publicKey, keyPair.secretKey, seed)
  return keyPair
}

function noop() {}

function toHex(discoveryKey) {
  return b4a.toString(discoveryKey, 'hex')
}
module.exports = async function* audit(store, { dryRun = false } = {}) {
  for await (const { discoveryKey, core } of store.storage.createCoreStream()) {
    if (core.version < 1) continue // not migrated, ignore

    const c = store.get({ discoveryKey, active: false })
    await c.ready()

    yield { discoveryKey, key: c.key, audit: await c.core.audit({ dryRun }) }

    try {
      await c.close()
    } catch {
      // ignore if failed, we are auditing...
    }
  }
}
const { EventEmitter } = require('events')
const { Readable } = require('streamx')

class GroupNotifyHandle extends EventEmitter {
  constructor(store, topic) {
    super()
    this._store = store
    this._topic = topic
    this.index = -1
  }

  updates(opts) {
    return Readable.deferred(async () => {
      const groupId = await this._store.storage.getGroup(this._topic).catch(noop)
      if (groupId === null) return null
      return this._store.storage.createGroupUpdateStream(groupId, opts)
    })
  }

  destroy() {
    this._store._removeGroupNotify(this)
  }
}

module.exports = GroupNotifyHandle

function noop() {}
{
  "name": "corestore",
  "version": "7.11.0",
  "description": "A Hypercore factory that simplifies managing collections of cores.",
  "main": "index.js",
  "files": [
    "index.js",
    "lib/*"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "dependencies": {
    "b4a": "^1.6.7",
    "bare-events": "^2.8.3",
    "hypercore": "^11.32.0",
    "hypercore-crypto": "^3.4.2",
    "hypercore-errors": "^1.4.0",
    "hypercore-id-encoding": "^1.3.0",
    "ready-resource": "^1.1.1",
    "sodium-universal": "^5.0.1",
    "streamx": "^2.26.0",
    "which-runtime": "^1.2.1"
  },
  "devDependencies": {
    "brittle": "^3.7.0",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "rache": "^1.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "test": "npm run test:node && npm run test:bare",
    "test:bare": "brittle-bare --coverage test/all.js",
    "lint": "prettier --check . && lunte",
    "test:node": "brittle-node --coverage test/all.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/corestore.git"
  },
  "author": "Holepunch Inc",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/corestore/issues"
  },
  "homepage": "https://github.com/holepunchto/corestore"
}
module.exports = function debounce (worker, context = null) {
  debounced.running = null
  return debounced

  async function debounced () {
    if (debounced.running !== null) {
      try {
        await debounced.running
      } catch (_) {
        // ignore - do not fail on old errors
      }
    }

    // another "thread" beat us to it, just piggy pack on that one
    if (debounced.running !== null) return debounced.running

    debounced.running = worker.call(context)

    try {
      return await debounced.running
    } finally {
      debounced.running = null
    }
  }
}
{
  "name": "debounceify",
  "version": "1.1.0",
  "description": "Tiny async debouncer",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^16.0.3",
    "tape": "^5.1.1"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/debounceify.git"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/debounceify/issues"
  },
  "homepage": "https://github.com/mafintosh/debounceify"
}
const fs = require('fs')
const path = require('path')
const fsx = require('fs-native-extensions')
const b4a = require('b4a')
const ReadyResource = require('ready-resource')
const FDLock = require('fd-lock')

const PLATFORM = global.Bare ? global.Bare.platform : global.process.platform
const IS_WIN = PLATFORM === 'win32'
const IS_LINUX = PLATFORM === 'linux'
const MODIFIED_SLACK = 5000
const EMPTY = b4a.alloc(0)
const ATTR = IS_LINUX ? 'user.device-file' : 'device-file'

const nl = IS_WIN ? '\r\n' : '\n'

class DeviceFile extends ReadyResource {
  constructor(filename, { create = true, wait = false, lock = wait, data = {} } = {}) {
    super()

    this.filename = filename
    this.data = data
    this.lock = null

    this._create = create
    this._wait = wait
    this._lock = lock
  }

  async _open() {
    if (await verifyDeviceFile(this)) return
    if (!this._create) throwDeviceFileError('No device file present', false)
    await writeDeviceFile(this)
  }

  static async validate(filename, data) {
    const file = new DeviceFile(filename, { create: false, wait: false, data })
    try {
      await verifyDeviceFile(file)
    } catch (err) {
      if (err.fatal && err.code === 'DEVICE_FILE') return false
      throw err
    }
    return true
  }

  transfer() {
    return this.lock ? this.lock.transfer() : -1
  }

  async _close() {
    if (this.lock) await this.lock.close()
  }

  async suspend() {
    if (!this.opened) await this.ready()
    if (this.lock) await this.lock.suspend()
  }

  async resume() {
    if (!this.opened) await this.ready()
    if (this.lock) await this.lock.resume()
  }
}

module.exports = DeviceFile

async function writeDeviceFile(device) {
  let s = ''

  for (const [key, value] of Object.entries(device.data)) {
    if (value === null) continue
    s += key + '=' + value + nl
  }

  await fs.promises.mkdir(path.dirname(device.filename), { recursive: true })

  const fd = await open(device.filename, 'w')

  device.lock = device._lock ? new FDLock(fd, { wait: device._wait }) : null

  if (device.lock) {
    try {
      await device.lock.ready()
    } catch (err) {
      await device.lock.close()
      throw err
    }
  }

  const st = await fstat(fd)

  const created = Date.now()

  s += 'device/platform=' + PLATFORM + nl
  s += 'device/inode=' + st.ino + nl
  s += 'device/created=' + created + nl

  if (await setAttr(fd, ATTR, b4a.from('original'))) {
    s += 'device/attribute=original' + nl
  }

  await write(fd, b4a.from(s))

  if (!device.lock) await close(fd)
}

async function verifyDeviceFile(device) {
  let fd = 0

  try {
    fd = await open(device.filename, 'r+')
  } catch (e) {
    fd = 0
  }

  if (fd === 0) return false

  device.lock = device._lock ? new FDLock(fd, { wait: device._wait }) : null

  if (device.lock) {
    try {
      await device.lock.ready()
    } catch (err) {
      await device.lock.close()
      throw err
    }
  }

  const buf = await read(fd)
  const result = {}

  const s = b4a.toString(buf).trim().split('\n')

  let inode = 0
  let created = 0
  let attr = ''
  let platform = ''

  for (const ln of s) {
    const i = ln.indexOf('=')
    if (i === -1) continue

    const k = ln.slice(0, i).trim()
    const v = ln.slice(i + 1).trim()

    switch (k) {
      case 'device/platform':
        platform = v
        break
      case 'device/inode':
        inode = Number(v)
        break
      case 'device/created':
        created = Number(v)
        break
      case 'device/attribute':
        attr = v
        break
      default:
        result[k] = v
        break
    }
  }

  for (const [k, v] of Object.entries(device.data)) {
    if (v === null) continue
    if (result[k] === undefined) continue // allow upserts
    if (result[k] !== '' + v) {
      await teardown()
      throwDeviceFileError(`Invalid device file, ${k} has changed. Was ${result[k]}, is ${v}`, true)
    }
  }

  const st = await fstat(fd)
  const at = await getAttr(fd, ATTR)

  const sameAttr = b4a.toString(at || EMPTY) === attr
  const modified = Math.max(st.mtime.getTime(), st.birthtime.getTime())

  if (platform && platform !== PLATFORM) {
    await teardown()
    throwDeviceFileError('Invalid device file, was made on different platform', true)
  }

  if (!sameAttr) {
    await teardown()
    throwDeviceFileError('Invalid device file, was moved unsafely', true)
  }

  if (st.ino !== inode || (created && Math.abs(modified - created) >= MODIFIED_SLACK)) {
    await teardown()
    throwDeviceFileError('Invalid device file, was modified', true)
  }

  if (!device.lock) await close(fd)

  device.data = result
  return true

  async function teardown() {
    if (device.lock) await device.lock.close()
    else await close(fd)
  }
}

async function getAttr(fd, name) {
  try {
    return await fsx.getAttr(fd, name)
  } catch {
    return null
  }
}

async function setAttr(fd, name, value) {
  try {
    await fsx.setAttr(fd, name, value)
    return true
  } catch {
    return false
  }
}

function fstat(fd) {
  return new Promise((resolve, reject) => {
    fs.fstat(fd, (err, st) => {
      if (err) reject(err)
      resolve(st)
    })
  })
}

function close(fd) {
  return new Promise((resolve, reject) => {
    fs.close(fd, (err, st) => {
      if (err) reject(err)
      resolve(st)
    })
  })
}

function write(fd, buf) {
  return new Promise((resolve, reject) => {
    let offset = 0

    onwrite(null, 0)

    function onwrite(err, wrote) {
      if (err) return reject(err)
      if (offset === buf.byteLength) return resolve()
      offset += wrote
      fs.write(fd, buf, offset, buf.byteLength - offset, offset, onwrite)
    }
  })
}

function read(fd) {
  const buf = b4a.allocUnsafe(4096)

  return new Promise((resolve, reject) => {
    let offset = 0

    fs.read(fd, buf, 0, buf.byteLength, 0, onread)

    function onread(err, read) {
      if (err) return reject(err)
      if (read === 0) return resolve(buf.subarray(0, offset))
      offset += read
      fs.read(fd, buf, offset, buf.byteLength - offset, offset, onread)
    }
  })
}

function open(filename, flags) {
  return new Promise((resolve, reject) => {
    fs.open(filename, flags, (err, fd) => {
      if (err) reject(err)
      resolve(fd)
    })
  })
}

function throwDeviceFileError(message, fatal) {
  const err = new Error(message)
  err.code = 'DEVICE_FILE'
  err.fatal = fatal
  throw err
}
{
  "name": "device-file",
  "version": "2.3.1",
  "description": "Device only file",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.6.7",
    "bare-fs": "^4.0.1",
    "bare-path": "^3.0.0",
    "fd-lock": "^2.1.0",
    "fs-native-extensions": "^1.4.0",
    "ready-resource": "^1.2.0"
  },
  "devDependencies": {
    "brittle": "^3.13.1",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node --coverage test.js",
    "test:bare": "brittle-bare --coverage test.js"
  },
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    }
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/device-file.git"
  },
  "author": "Holepunch Inc",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/device-file/issues"
  },
  "homepage": "https://github.com/holepunchto/device-file"
}
module.exports = require('bare-events')
{
  "name": "events-universal",
  "version": "1.0.1",
  "description": "Universal wrapper for the Node.js events module",
  "exports": {
    "./package": "./package.json",
    ".": {
      "bare": "./bare.js",
      "react-native": "./react-native.js",
      "default": "./default.js"
    }
  },
  "files": [
    "index.js",
    "default.js",
    "bare.js",
    "react-native.js"
  ],
  "scripts": {
    "test": "prettier . --check"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/events-universal.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/events-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/events-universal#readme",
  "dependencies": {
    "bare-events": "^2.7.0"
  },
  "devDependencies": {
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^1.0.0"
  }
}
module.exports = class FixedFIFO {
  constructor (hwm) {
    if (!(hwm > 0) || ((hwm - 1) & hwm) !== 0) throw new Error('Max size for a FixedFIFO should be a power of two')
    this.buffer = new Array(hwm)
    this.mask = hwm - 1
    this.top = 0
    this.btm = 0
    this.next = null
  }

  clear () {
    this.top = this.btm = 0
    this.next = null
    this.buffer.fill(undefined)
  }

  push (data) {
    if (this.buffer[this.top] !== undefined) return false
    this.buffer[this.top] = data
    this.top = (this.top + 1) & this.mask
    return true
  }

  shift () {
    const last = this.buffer[this.btm]
    if (last === undefined) return undefined
    this.buffer[this.btm] = undefined
    this.btm = (this.btm + 1) & this.mask
    return last
  }

  peek () {
    return this.buffer[this.btm]
  }

  isEmpty () {
    return this.buffer[this.btm] === undefined
  }
}
const FixedFIFO = require('./fixed-size')

module.exports = class FastFIFO {
  constructor (hwm) {
    this.hwm = hwm || 16
    this.head = new FixedFIFO(this.hwm)
    this.tail = this.head
    this.length = 0
  }

  clear () {
    this.head = this.tail
    this.head.clear()
    this.length = 0
  }

  push (val) {
    this.length++
    if (!this.head.push(val)) {
      const prev = this.head
      this.head = prev.next = new FixedFIFO(2 * this.head.buffer.length)
      this.head.push(val)
    }
  }

  shift () {
    if (this.length !== 0) this.length--
    const val = this.tail.shift()
    if (val === undefined && this.tail.next) {
      const next = this.tail.next
      this.tail.next = null
      this.tail = next
      return this.tail.shift()
    }

    return val
  }

  peek () {
    const val = this.tail.peek()
    if (val === undefined && this.tail.next) return this.tail.next.peek()
    return val
  }

  isEmpty () {
    return this.length === 0
  }
}
{
  "name": "fast-fifo",
  "version": "1.3.2",
  "description": "A fast fifo implementation similar to the one powering nextTick in Node.js core",
  "main": "index.js",
  "files": [
    "./index.js",
    "./fixed-size.js"
  ],
  "dependencies": {},
  "devDependencies": {
    "standard": "^17.1.0",
    "brittle": "^3.3.2"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/fast-fifo.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/fast-fifo/issues"
  },
  "homepage": "https://github.com/mafintosh/fast-fifo"
}
const fs = require('fs')
const fsx = require('fs-native-extensions')
const onexit = require('resource-on-exit')
const ReadyResource = require('ready-resource')

module.exports = class FDLock extends ReadyResource {
  constructor(fd, opts = {}) {
    const { wait = false } = opts

    super()

    this._fd = fd
    this._wait = wait
    this._locked = false

    onexit.add(this, closeSync)
  }

  get locked() {
    return this._locked
  }

  async _open() {
    try {
      await this._resume()
    } catch (err) {
      onexit.remove(this)
      await close(this)
      throw err
    }
  }

  async _close() {
    onexit.remove(this)
    await close(this)
    this._locked = false
  }

  transfer() {
    const fd = this._fd
    if (fd === -1) throw new Error('Lock has already been transferred')
    this._fd = -1
    onexit.remove(this)
    return fd
  }

  async suspend() {
    if (!this.opened) await this.ready()
    return this._suspend()
  }

  async _suspend() {
    if (this._fd === -1 || this._locked === false) return
    fsx.unlock(this._fd)
    this._locked = false
  }

  async resume() {
    if (!this.opened) await this.ready()
    return this._resume()
  }

  async _resume() {
    if (this._fd === -1 || this._locked === true) return
    if (this._wait) await fsx.waitForLock(this._fd)
    else if (!fsx.tryLock(this._fd)) {
      throw new Error('File descriptor could not be locked')
    }
    this._locked = true
  }
}

function close(lock) {
  const fd = lock._fd
  if (fd === -1) return
  lock._fd = -1
  return new Promise((resolve) => fs.close(fd, () => resolve()))
}

function closeSync(lock) {
  const fd = lock._fd
  if (fd === -1) return
  lock._fd = -1
  lock._locked = false
  try {
    fs.closeSync(fd)
  } catch {}
}
{
  "name": "fd-lock",
  "version": "2.2.0",
  "description": "Stateful file descriptor locks for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": "./index.js"
  },
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    }
  },
  "files": [
    "index.js"
  ],
  "scripts": {
    "test": "npm run lint && npm run test:bare && npm run test:node",
    "test:bare": "bare test.js",
    "test:node": "node test.js",
    "lint": "prettier --check .",
    "format": "prettier --write ."
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/fd-lock.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/fd-lock/issues"
  },
  "homepage": "https://github.com/holepunchto/fd-lock#readme",
  "dependencies": {
    "bare-fs": "^4.5.0",
    "fs-native-extensions": "^1.4.4",
    "ready-resource": "^1.2.0",
    "resource-on-exit": "^1.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
exports.fullRoots = function (index, result) {
  if (index & 1) throw new Error('You can only look up roots for depth(0) blocks')
  if (!result) result = []

  index /= 2

  let offset = 0
  let factor = 1

  while (true) {
    if (!index) return result
    while (factor * 2 <= index) factor *= 2
    result.push(offset + factor - 1)
    offset = offset + 2 * factor
    index -= factor
    factor = 1
  }
}

exports.futureRoots = function (index, result) {
  if (index & 1) throw new Error('You can only look up future roots for depth(0) blocks')
  if (!result) result = []

  let factor = 1

  // make first root
  while (factor * 2 <= index) factor *= 2

  // full factor of 2 - done
  if (factor * 2 - 2 === index) return result

  let pos = factor / 2 - 1

  // while its not a full tree
  while ((pos + factor / 2 - 1) !== index) {
    pos += factor

    // read too far, to to left child
    while ((pos + factor / 2 - 1) > index) {
      factor /= 2
      pos -= factor / 2
    }

    // the "gap" is a future root
    result.push(pos - factor / 2)
  }

  return result
}

exports.patch = function (from, to) {
  if (from === 0 || from >= to) return []

  const roots = exports.fullRoots(from)
  const target = exports.fullRoots(to)

  // first find the first root that is different

  let i = 0
  for (; i < target.length; i++) {
    if (i >= roots.length || roots[i] !== target[i]) break
  }

  const patch = []

  if (i < roots.length) {
    // now we need to grow the newest root until it hits the diff one
    let prev = roots.length - 1

    const ite = exports.iterator(roots[prev--])

    while (ite.index !== target[i]) {
      ite.sibling()

      if (prev >= 0 && ite.index === roots[prev]) {
        prev--
      } else {
        patch.push(ite.index)
      }

      patch.push(ite.parent())
    }

    i++ // patched to next root, so inc
  }

  // include the rest

  for (; i < target.length; i++) patch.push(target[i])

  return patch
}

exports.depth = function (index) {
  let depth = 0

  index += 1
  while (!(index & 1)) {
    depth++
    index = rightShift(index)
  }

  return depth
}

exports.sibling = function (index, depth) {
  if (!depth) depth = exports.depth(index)
  const offset = exports.offset(index, depth)

  return exports.index(depth, offset & 1 ? offset - 1 : offset + 1)
}

exports.parent = function (index, depth) {
  if (!depth) depth = exports.depth(index)
  const offset = exports.offset(index, depth)

  return exports.index(depth + 1, rightShift(offset))
}

exports.leftChild = function (index, depth) {
  if (!(index & 1)) return -1
  if (!depth) depth = exports.depth(index)
  return exports.index(depth - 1, exports.offset(index, depth) * 2)
}

exports.rightChild = function (index, depth) {
  if (!(index & 1)) return -1
  if (!depth) depth = exports.depth(index)
  return exports.index(depth - 1, 1 + (exports.offset(index, depth) * 2))
}

exports.children = function (index, depth) {
  if (!(index & 1)) return null

  if (!depth) depth = exports.depth(index)
  const offset = exports.offset(index, depth) * 2

  return [
    exports.index(depth - 1, offset),
    exports.index(depth - 1, offset + 1)
  ]
}

exports.leftSpan = function (index, depth) {
  if (!(index & 1)) return index
  if (!depth) depth = exports.depth(index)
  return exports.offset(index, depth) * twoPow(depth + 1)
}

exports.rightSpan = function (index, depth) {
  if (!(index & 1)) return index
  if (!depth) depth = exports.depth(index)
  return (exports.offset(index, depth) + 1) * twoPow(depth + 1) - 2
}

exports.nextLeaf = function (index) {
  let factor = 1
  let r = index

  while ((r & 1) === 1) {
    r = (r - 1) / 2
    factor *= 2
  }

  return index + factor + 1
}

exports.count = function (index, depth) {
  if (!(index & 1)) return 1
  if (!depth) depth = exports.depth(index)
  return twoPow(depth + 1) - 1
}

exports.countLeaves = function (index) {
  return (exports.count(index) + 1) / 2
}

exports.spans = function (index, depth) {
  if (!(index & 1)) return [index, index]
  if (!depth) depth = exports.depth(index)

  const offset = exports.offset(index, depth)
  const width = twoPow(depth + 1)

  return [offset * width, (offset + 1) * width - 2]
}

exports.index = function (depth, offset) {
  return (1 + 2 * offset) * twoPow(depth) - 1
}

exports.offset = function (index, depth) {
  if (!(index & 1)) return index / 2
  if (!depth) depth = exports.depth(index)

  return ((index + 1) / twoPow(depth) - 1) / 2
}

exports.iterator = function (index) {
  const ite = new Iterator()
  ite.seek(index || 0)
  return ite
}

function twoPow (n) {
  return n < 31 ? 1 << n : ((1 << 30) * (1 << (n - 30)))
}

function rightShift (n) {
  return (n - (n & 1)) / 2
}

function Iterator () {
  this.index = 0
  this.offset = 0
  this.factor = 0
}

Iterator.prototype.seek = function (index) {
  this.index = index
  if (this.index & 1) {
    this.offset = exports.offset(index)
    this.factor = twoPow(exports.depth(index) + 1)
  } else {
    this.offset = index / 2
    this.factor = 2
  }
}

Iterator.prototype.isLeft = function () {
  return (this.offset & 1) === 0
}

Iterator.prototype.isRight = function () {
  return (this.offset & 1) === 1
}

Iterator.prototype.isRoot = function (length) {
  const currentLength = 1 + (this.index + this.factor / 2 - 1) / 2
  if (length < currentLength) return false

  const factor = this.factor * 2
  const index = (this.offset & 1)
    ? this.index - this.factor / 2
    : this.index + this.factor / 2

  const parentLength = 1 + (index + factor / 2 - 1) / 2
  return parentLength > length
}

Iterator.prototype.contains = function (index) {
  return index > this.index
    ? index < (this.index + this.factor / 2)
    : index < this.index
      ? index > (this.index - this.factor / 2)
      : true
}

Iterator.prototype.prev = function () {
  if (!this.offset) return this.index
  this.offset--
  this.index -= this.factor
  return this.index
}

Iterator.prototype.next = function () {
  this.offset++
  this.index += this.factor
  return this.index
}

Iterator.prototype.count = function () {
  if (!(this.index & 1)) return 1
  return this.factor - 1
}

Iterator.prototype.countLeaves = function () {
  return (this.count() + 1) / 2
}

Iterator.prototype.sibling = function () {
  return this.isLeft() ? this.next() : this.prev()
}

Iterator.prototype.parent = function () {
  if (this.offset & 1) {
    this.index -= this.factor / 2
    this.offset = (this.offset - 1) / 2
  } else {
    this.index += this.factor / 2
    this.offset /= 2
  }
  this.factor *= 2
  return this.index
}

Iterator.prototype.leftSpan = function () {
  this.index = this.index - this.factor / 2 + 1
  this.offset = this.index / 2
  this.factor = 2
  return this.index
}

Iterator.prototype.peekLeftSpan = function () {
  return this.index - this.factor / 2 + 1
}

Iterator.prototype.rightSpan = function () {
  this.index = this.index + this.factor / 2 - 1
  this.offset = this.index / 2
  this.factor = 2
  return this.index
}

Iterator.prototype.peekRightSpan = function () {
  return this.index + this.factor / 2 - 1
}

Iterator.prototype.leftChild = function () {
  if (this.factor === 2) return this.index
  this.factor /= 2
  this.index -= this.factor / 2
  this.offset *= 2
  return this.index
}

Iterator.prototype.rightChild = function () {
  if (this.factor === 2) return this.index
  this.factor /= 2
  this.index += this.factor / 2
  this.offset = 2 * this.offset + 1
  return this.index
}

Iterator.prototype.nextTree = function () {
  this.index = this.index + this.factor / 2 + 1
  this.offset = this.index / 2
  this.factor = 2
  return this.index
}

Iterator.prototype.prevTree = function () {
  if (!this.offset) {
    this.index = 0
    this.factor = 2
  } else {
    this.index = this.index - this.factor / 2 - 1
    this.offset = this.index / 2
    this.factor = 2
  }
  return this.index
}

Iterator.prototype.fullRoot = function (index) {
  if (index <= this.index || (this.index & 1) > 0) return false
  while (index > this.index + this.factor + this.factor / 2) {
    this.index += this.factor / 2
    this.factor *= 2
    this.offset /= 2
  }
  return true
}
{
  "name": "flat-tree",
  "version": "1.13.0",
  "description": "A series of functions to map a binary tree to a list",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {},
  "devDependencies": {
    "brittle": "^3.3.2",
    "standard": "^17.1.0"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/flat-tree.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/flat-tree/issues"
  },
  "homepage": "https://github.com/mafintosh/flat-tree"
}
require.addon = require('require-addon')

module.exports = require.addon('.', __filename)
const { isWindows } = require('which-runtime')
const binding = require('./binding')

function onwork(err, result) {
  if (err) this.reject(err)
  else this.resolve(result)
}

exports.tryLock = function tryLock(fd, offset = 0, length = 0, opts = {}) {
  if (typeof offset === 'object') {
    opts = offset
    offset = 0
  }

  if (typeof length === 'object') {
    opts = length
    length = 0
  }

  if (typeof opts !== 'object' || opts === null) {
    opts = {}
  }

  try {
    binding.tryLock(fd, offset, length, opts.shared !== true)
  } catch (err) {
    if (err.code === 'EAGAIN') return false
    throw err
  }

  return true
}

exports.waitForLock = function waitForLock(fd, offset = 0, length = 0, opts = {}) {
  if (typeof offset === 'object') {
    opts = offset
    offset = 0
  }

  if (typeof length === 'object') {
    opts = length
    length = 0
  }

  if (typeof opts !== 'object' || opts === null) {
    opts = {}
  }

  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.waitForLock(fd, offset, length, opts.shared !== true, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.waitForLockSync = function waitForLockSync(fd, offset = 0, length = 0, opts = {}) {
  if (typeof offset === 'object') {
    opts = offset
    offset = 0
  }

  if (typeof length === 'object') {
    opts = length
    length = 0
  }

  if (typeof opts !== 'object' || opts === null) {
    opts = {}
  }

  binding.waitForLockSync(fd, offset, length, opts.shared !== true)
}

exports.tryDowngradeLock = function tryDowngradeLock(fd, offset = 0, length = 0) {
  try {
    binding.tryDowngradeLock(fd, offset, length)
  } catch (err) {
    if (err.code === 'EAGAIN') return false
    throw err
  }

  return true
}

exports.waitForDowngradeLock = function downgradeLock(fd, offset = 0, length = 0) {
  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.waitForDowngradeLock(fd, offset, length, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.waitForDowngradeLockSync = function waitForDowngradeLockSync(fd, offset = 0, length = 0) {
  binding.waitForDowngradeLockSync(fd, offset, length)
}

exports.tryUpgradeLock = function tryUpgradeLock(fd, offset = 0, length = 0) {
  try {
    binding.tryUpgradeLock(fd, offset, length)
  } catch (err) {
    if (err.code === 'EAGAIN') return false
    throw err
  }

  return true
}

exports.waitForUpgradeLock = function upgradeLock(fd, offset = 0, length = 0) {
  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.waitForUpgradeLock(fd, offset, length, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.waitForUpgradeLockSync = function waitForUpgradeLockSync(fd, offset = 0, length = 0) {
  binding.waitForUpgradeLockSync(fd, offset, length)
}

exports.unlock = function unlock(fd, offset = 0, length = 0) {
  binding.unlock(fd, offset, length)
}

exports.trim = function trim(fd, offset, length) {
  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.trim(fd, offset, length, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.trimSync = function trimSync(fd, offset, length) {
  binding.trimSync(fd, offset, length)
}

exports.sparse = function sparse(fd) {
  // Short circuit on everything but Windows
  if (!isWindows) return Promise.resolve()

  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.sparse(fd, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.sparseSync = function sparseSync(fd) {
  // Short circuit on everything but Windows
  if (!isWindows) return

  binding.sparseSync(fd)
}

exports.swap = function swap(from, to) {
  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.swap(from, to, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.swapSync = function swapSync(from, to) {
  binding.swapSync(from, to)
}

exports.getAttr = function getAttr(fd, name) {
  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.getAttr(fd, name, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise.then((buffer) => (buffer === null ? null : Buffer.from(buffer)))
}

exports.getAttrSync = function getAttrSync(fd, name) {
  const buffer = binding.getAttrSync(fd, name)
  return buffer === null ? null : Buffer.from(buffer)
}

exports.setAttr = function setAttr(fd, name, value, encoding) {
  if (typeof value === 'string') value = Buffer.from(value, encoding)

  const req = {
    value,
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.setAttr(
      fd,
      name,
      value.buffer,
      value.byteOffset,
      value.byteLength,
      req,
      onwork
    )
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.setAttrSync = function setAttrSync(fd, name, value, encoding) {
  if (typeof value === 'string') value = Buffer.from(value, encoding)

  binding.setAttrSync(fd, name, value.buffer, value.byteOffset, value.byteLength)
}

exports.removeAttr = function removeAttr(fd, name) {
  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.removeAttr(fd, name, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.removeAttrSync = function removeAttrSync(fd, name) {
  binding.removeAttrSync(fd, name)
}

exports.listAttrs = function listAttrs(fd) {
  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.listAttrs(fd, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.listAttrsSync = function listAttrsSync(fd) {
  return binding.listAttrsSync(fd)
}
{
  "name": "fs-native-extensions",
  "version": "1.5.0",
  "description": "Native file system extensions for advanced file operations",
  "main": "index.js",
  "files": [
    "index.js",
    "macros.h",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "include",
    "src",
    "prebuilds"
  ],
  "imports": {
    "child_process": {
      "bare": "bare-subprocess",
      "default": "child_process"
    },
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "fs/*": {
      "bare": "bare-fs/*",
      "default": "fs/*"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    }
  },
  "addon": true,
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:bare": "brittle-bare --coverage test.js",
    "test:node": "brittle-node --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/fs-native-extensions.git"
  },
  "author": "Kasper Isager Dalsgarð <kasper@funktionel.co>",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/fs-native-extensions/issues"
  },
  "homepage": "https://github.com/holepunchto/fs-native-extensions#readme",
  "dependencies": {
    "require-addon": "^1.1.0",
    "which-runtime": "^1.2.0"
  },
  "devDependencies": {
    "bare-compat-napi": "^1.3.8",
    "bare-fs": "^4.4.4",
    "bare-path": "^3.0.0",
    "bare-subprocess": "^4.0.5",
    "brittle": "^3.1.1",
    "cmake-bare": "^1.1.10",
    "cmake-fetch": "^1.4.7",
    "cmake-napi": "^1.0.5",
    "cmake-npm": "^1.1.0",
    "lunte": "^1.6.0",
    "minimist": "^1.2.6",
    "prettier": "^3.5.3",
    "prettier-config-holepunch": "^2.0.0",
    "test-tmp": "^1.2.1"
  }
}
const codecs = require('codecs')
const { Readable } = require('streamx')
const mutexify = require('mutexify/promise')
const b4a = require('b4a')
const safetyCatch = require('safety-catch')
const ReadyResource = require('ready-resource')
const debounce = require('debounceify')
const Rache = require('rache')
const rrp = require('resolve-reject-promise')

const { all: unslabAll } = require('unslab')

const RangeIterator = require('./iterators/range')
const HistoryIterator = require('./iterators/history')
const DiffIterator = require('./iterators/diff')
const LocalBlockIterator = require('./iterators/local')
const Extension = require('./lib/extension')
const { YoloIndex, Node, Header } = require('./lib/messages')
const { BLOCK_NOT_AVAILABLE, DECODING_ERROR } = require('hypercore-errors')

const T = 5
const MIN_KEYS = T - 1
const MAX_CHILDREN = MIN_KEYS * 2 + 1

const SEP = b4a.alloc(1)
const EMPTY = b4a.alloc(0)

class Key {
  constructor(seq, value) {
    this.seq = seq
    this.value = value
  }
}

class Child {
  constructor(seq, offset, value) {
    this.seq = seq
    this.offset = offset
    this.value = value
  }
}

class Cache {
  constructor(rache) {
    this.keys = rache
    this.length = 0
  }

  get(seq) {
    return this.keys.get(seq) || null
  }

  set(seq, key) {
    this.keys.set(seq, key)
    if (seq >= this.length) this.length = seq + 1
  }

  gc(length) {
    // if we need to "work" more than 128 ticks, just bust the cache...
    if (this.length - length > 128) {
      this.keys.clear()
    } else {
      for (let i = length; i < this.length; i++) {
        this.keys.delete(i)
      }
    }

    this.length = length
  }

  clear() {
    this.keys.clear()
  }
}

class Pointers {
  constructor(decoded) {
    this.levels = decoded.levels.map((l) => {
      const children = []
      const keys = []

      for (let i = 0; i < l.keys.length; i++) {
        keys.push(new Key(l.keys[i], null))
      }

      for (let i = 0; i < l.children.length; i += 2) {
        children.push(new Child(l.children[i], l.children[i + 1], null))
      }

      return { keys, children }
    })
  }

  get(i) {
    return this.levels[i]
  }

  hasKey(seq) {
    for (const lvl of this.levels) {
      for (const key of lvl.keys) {
        if (key.seq === seq) return true
      }
    }
    return false
  }
}

function inflate(entry) {
  if (entry.inflated === null) {
    entry.inflated = YoloIndex.decode(entry.index)
    entry.index = null
  }
  return new Pointers(entry.inflated)
}

function deflate(index) {
  const levels = index.map((l) => {
    const keys = []
    const children = []

    for (let i = 0; i < l.value.keys.length; i++) {
      keys.push(l.value.keys[i].seq)
    }

    for (let i = 0; i < l.value.children.length; i++) {
      children.push(l.value.children[i].seq, l.value.children[i].offset)
    }

    return { keys, children }
  })

  return YoloIndex.encode({ levels })
}

class TreeNode {
  constructor(block, keys, children, offset) {
    this.block = block
    this.offset = offset
    this.keys = keys
    this.children = children
    this.changed = false

    this.preload()
  }

  preload() {
    if (this.block === null) return

    const core = getBackingCore(this.block.tree.core)
    if (!core) return

    const bitfield = core.core.bitfield
    const blocks = []

    for (let i = 0; i < this.keys.length; i++) {
      const k = this.keys[i]
      if (k.value) continue
      if (k.seq >= core.signedLength || (bitfield && bitfield.get(k.seq))) continue
      blocks.push(k.seq)
    }
    for (let i = 0; i < this.children.length; i++) {
      const c = this.children[i]
      if (c.value) continue
      if (c.seq >= core.signedLength || (bitfield && bitfield.get(c.seq))) continue
      blocks.push(c.seq)
    }

    if (blocks.length) core.download({ blocks })
  }

  async insertKey(key, value, child, node, encoding, cas) {
    let s = 0
    let e = this.keys.length
    let c

    while (s < e) {
      const mid = (s + e) >> 1
      c = b4a.compare(key.value, await this.getKey(mid))

      if (c === 0) {
        if (cas) {
          const prev = await this.getKeyNode(mid)
          if (!(await cas(prev.final(encoding), node))) return true
        }
        if (!this.block.tree.tree.alwaysDuplicate) {
          const prev = await this.getKeyNode(mid)
          if (sameValue(prev.value, value)) return true
        }
        this.changed = true
        this.keys[mid] = key
        return true
      }

      if (c < 0) e = mid
      else s = mid + 1
    }

    const i = c < 0 ? e : s
    this.keys.splice(i, 0, key)
    if (child) this.children.splice(i + 1, 0, new Child(0, 0, child))
    this.changed = true

    return this.keys.length < MAX_CHILDREN
  }

  removeKey(index) {
    this.keys.splice(index, 1)
    if (this.children.length) {
      this.children[index + 1].seq = 0 // mark as freed
      this.children.splice(index + 1, 1)
    }
    this.changed = true
  }

  async siblings(parent) {
    for (let i = 0; i < parent.children.length; i++) {
      if (parent.children[i].value === this) {
        const [left, right] = await Promise.all([
          i ? parent.getChildNode(i - 1) : null,
          i < parent.children.length - 1 ? parent.getChildNode(i + 1) : null
        ])
        return { left, index: i, right }
      }
    }

    throw new Error('Bad parent')
  }

  merge(node, median) {
    this.changed = true
    this.keys.push(median)
    for (let i = 0; i < node.keys.length; i++) this.keys.push(node.keys[i])
    for (let i = 0; i < node.children.length; i++) this.children.push(node.children[i])
  }

  async split() {
    const len = this.keys.length >> 1
    const right = TreeNode.create(this.block)

    while (right.keys.length < len) right.keys.push(this.keys.pop())
    right.keys.reverse()

    await this.getKey(this.keys.length - 1) // make sure the median is loaded
    const median = this.keys.pop()

    if (this.children.length) {
      while (right.children.length < len + 1) right.children.push(this.children.pop())
      right.children.reverse()
    }

    this.changed = true

    return {
      left: this,
      median,
      right
    }
  }

  getKeyNode(index) {
    return this.block.tree.getBlock(this.keys[index].seq)
  }

  async getChildNode(index) {
    const child = this.children[index]
    if (child.value) return child.value
    const block =
      child.seq === this.block.seq ? this.block : await this.block.tree.getBlock(child.seq)
    return (child.value = block.getTreeNode(child.offset))
  }

  setKey(index, key) {
    this.keys[index] = key
    this.changed = true
  }

  async getKey(index) {
    const key = this.keys[index]
    if (key.value) return key.value
    const k = key.seq === this.block.seq ? this.block.key : await this.block.tree.getKey(key.seq)
    return (key.value = k)
  }

  indexChanges(index, seq) {
    const offset = index.push(null) - 1
    this.changed = false

    for (const child of this.children) {
      if (!child.value || !child.value.changed) continue
      child.seq = seq
      child.offset = child.value.indexChanges(index, seq)
      index[child.offset] = child
    }

    return offset
  }

  updateChildren(seq, block) {
    for (const child of this.children) {
      if (!child.value || child.seq !== seq) continue
      child.value.block = block
      child.value.updateChildren(seq, block)
    }
  }

  static create(block) {
    const node = new TreeNode(block, [], [], 0)
    node.changed = true
    return node
  }
}

class BlockEntry {
  constructor(seq, tree, entry) {
    this.seq = seq
    this.tree = tree
    this.index = null
    this.entry = entry
    this.key = entry.key
    this.value = entry.value
  }

  isTarget(key) {
    return b4a.equals(this.key, key)
  }

  inflate() {
    if (this.index === null) {
      this.index = inflate(this.entry)
    }
  }

  isDeletion() {
    if (this.value !== null) return false

    if (this.index === null) {
      this.index = inflate(this.entry)
    }

    return !this.index.hasKey(this.seq)
  }

  final(encoding) {
    return {
      seq: this.seq,
      key: encoding.key ? encoding.key.decode(this.key) : this.key,
      value: this.value && (encoding.value ? encoding.value.decode(this.value) : this.value)
    }
  }

  getTreeNode(offset) {
    if (this.index === null) {
      this.index = inflate(this.entry)
    }
    const entry = this.index.get(offset)
    return new TreeNode(this, entry.keys, entry.children, offset)
  }
}

class CacheLock {
  constructor() {
    this.map = new Map()
  }

  enter(seq) {
    const pending = this.map.get(seq)

    if (!pending) {
      this.map.set(seq, [])
      return Promise.resolve()
    }

    const { resolve, promise } = rrp()
    pending.push(resolve)
    return promise
  }

  exit(seq) {
    const pending = this.map.get(seq)
    if (!pending.length) {
      this.map.delete(seq)
      return
    }

    pending.pop()()
  }
}

class BatchEntry extends BlockEntry {
  constructor(seq, tree, key, value, index) {
    super(seq, tree, { key, value, index: null, inflated: null })
    this.pendingIndex = index
  }

  isTarget(key) {
    return false
  }

  getTreeNode(offset) {
    return this.pendingIndex[offset].value
  }
}

class Hyperbee extends ReadyResource {
  constructor(core, opts = {}) {
    super()
    // this.feed is now deprecated, and will be this.core going forward
    this.feed = core
    this.core = core

    this.keyEncoding = opts.keyEncoding ? codecs(opts.keyEncoding) : null
    this.valueEncoding = opts.valueEncoding ? codecs(opts.valueEncoding) : null
    this.extension = opts.extension !== false ? getExtension(this, opts) : null
    this.metadata = opts.metadata || null
    this.lock = opts.lock || mutexify()
    this.sep = opts.sep || SEP
    this.readonly = !!opts.readonly
    this.prefix = opts.prefix || null

    // In a future version, this should be false by default
    this.alwaysDuplicate = opts.alwaysDuplicate !== false

    this._unprefixedKeyEncoding = this.keyEncoding
    this._sub = !!this.prefix
    this._checkout = opts.checkout || 0
    this._view = !!opts._view

    this._onappendBound = this._view ? null : this._onappend.bind(this)
    this._ontruncateBound = this._view ? null : this._ontruncate.bind(this)
    this._watchers = this._onappendBound ? [] : null
    this._entryWatchers = this._onappendBound ? [] : null
    this._sessions = opts.sessions !== false

    this._keyCache = null
    this._nodeCache = null
    this._cacheLock = new CacheLock()

    this._batches = []

    if (this._watchers) {
      this.core.on('append', this._onappendBound)
      this.core.on('truncate', this._ontruncateBound)
    }

    if (this.prefix && opts._sub) {
      this.keyEncoding = prefixEncoding(this.prefix, this.keyEncoding)
    }

    this.ready().catch(safetyCatch)
  }

  async _open() {
    if (this.core.opened === false) await this.core.ready()
    // bump the internal ranges since the nodes are small
    if (this._watchers && this.core.replicator.setInflightRange) {
      this.core.replicator.setInflightRange(256, 512)
    }

    // snapshot
    if (this._checkout === -1) this._checkout = Math.max(1, this.core.length)

    const baseCache = Rache.from(this.core.globalCache)
    this._keyCache = new Cache(baseCache)
    this._nodeCache = new Cache(Rache.from(baseCache))
  }

  get version() {
    return Math.max(1, this._checkout || this.core.length)
  }

  get id() {
    return this.core.id
  }

  get key() {
    return this.core.key
  }

  get discoveryKey() {
    return this.core.discoveryKey
  }

  get writable() {
    return this.core.writable
  }

  get readable() {
    return this.core.readable
  }

  replicate(isInitiator, opts) {
    return this.core.replicate(isInitiator, opts)
  }

  update(opts) {
    return this.core.update(opts)
  }

  peek(range, opts) {
    return iteratorPeek(this.createRangeIterator(range, { ...opts, limit: 1 }))
  }

  createRangeIterator(range, opts = {}) {
    // backwards compat range arg
    opts = opts ? { ...opts, ...range } : range

    const extension = opts.extension === false && opts.limit !== 0 ? null : this.extension
    const keyEncoding = opts.keyEncoding ? codecs(opts.keyEncoding) : this.keyEncoding

    if (extension) {
      const { onseq, onwait } = opts
      let version = 0
      let next = 0

      opts = encRange(keyEncoding, {
        ...opts,
        sub: this._sub,
        onseq(seq) {
          if (!version) version = seq + 1
          if (next) next--
          if (onseq) onseq(seq)
        },
        onwait(seq) {
          if (!next) {
            next = Extension.BATCH_SIZE
            extension.iterator(ite.snapshot(version))
          }
          if (onwait) onwait(seq)
        }
      })
    } else {
      opts = encRange(keyEncoding, { ...opts, sub: this._sub })
    }

    const ite = new RangeIterator(
      new Batch(this, this._makeSnapshot(), null, false, opts),
      null,
      opts
    )
    return ite
  }

  createReadStream(range, opts) {
    const signal = (opts && opts.signal) || null
    return iteratorToStream(this.createRangeIterator(range, opts), signal)
  }

  createHistoryStream(opts) {
    const session = opts && opts.live ? this.core.session() : this._makeSnapshot()
    const signal = (opts && opts.signal) || null
    return iteratorToStream(
      new HistoryIterator(new Batch(this, session, null, false, opts), opts),
      signal
    )
  }

  createDiffStream(right, range, opts) {
    if (typeof right === 'number') right = this.checkout(Math.max(1, right), { reuseSession: true })

    // backwards compat range arg
    opts = opts ? { ...opts, ...range } : range

    const signal = (opts && opts.signal) || null

    const keyEncoding = opts && opts.keyEncoding ? codecs(opts.keyEncoding) : this.keyEncoding
    if (keyEncoding) opts = encRange(keyEncoding, { ...opts, sub: this._sub })

    let done
    let closing
    let ite

    const left = this

    const rs = new Readable({
      signal,
      eagerOpen: true,
      async open(cb) {
        try {
          if (right.opened === false) await right.ready()
          if (left.opened === false) await left.ready()
        } catch (err) {
          cb(err)
          return
        }

        if (closing) {
          cb(null)
          return
        }

        if (left.core.closing || right.core.closing) {
          cb(new Error('Bee closed'))
          return
        }

        const snapshot = right.version > left.version ? right._makeSnapshot() : left._makeSnapshot()

        done = cb
        ite = new DiffIterator(
          new Batch(left, snapshot, null, false, opts),
          new Batch(right, snapshot, null, false, opts),
          opts
        )
        ite.open().then(fin, fin)
      },
      read(cb) {
        done = cb
        ite.next().then(push, fin)
      },
      predestroy() {
        if (!ite) {
          closing = Promise.resolve()
        } else {
          closing = ite.close()
          closing.catch(noop)
        }
      },
      destroy(cb) {
        done = cb
        if (!closing) closing = ite.close()
        closing.then(fin, fin)
      }
    })

    return rs

    function fin(err) {
      done(err)
    }

    function push(val) {
      rs.push(val)
      done(null)
    }
  }

  get(key, opts) {
    const b = new Batch(this, this._makeSnapshot(), null, true, opts)
    return b.get(key)
  }

  getBySeq(seq, opts) {
    const b = new Batch(this, this._makeSnapshot(), null, true, opts)
    return b.getBySeq(seq)
  }

  put(key, value, opts) {
    const b = new Batch(this, this.core, null, true, opts)
    return b.put(key, value, opts)
  }

  batch(opts) {
    return new Batch(this, this.core, mutexify(), true, opts)
  }

  del(key, opts) {
    const b = new Batch(this, this.core, null, true, opts)
    return b.del(key, opts)
  }

  watch(range, opts) {
    if (!this._watchers) throw new Error('Can only watch the main bee instance')
    return new Watcher(this, range, opts)
  }

  async getAndWatch(key, opts) {
    if (!this._watchers) throw new Error('Can only watch the main bee instance')

    const watcher = new EntryWatcher(this, key, opts)
    await watcher._debouncedUpdate()

    if (this.closing) {
      await watcher.close()
      throw new Error('Bee closed')
    }

    return watcher
  }

  _onappend() {
    for (const watcher of this._watchers) {
      watcher._onappend()
    }

    for (const watcher of this._entryWatchers) {
      watcher._onappend()
    }
  }

  _ontruncate(length) {
    for (const watcher of this._watchers) {
      watcher._ontruncate()
    }

    for (const watcher of this._entryWatchers) {
      watcher._ontruncate()
    }

    this._nodeCache.gc(length)
    this._keyCache.gc(length)
  }

  _makeSnapshot() {
    if (this._sessions === false) return this.core
    // TODO: better if we could encapsulate this in hypercore in the future
    return this._checkout <= this.core.length || this._checkout <= 1
      ? this.core.snapshot()
      : this.core.session({ snapshot: false })
  }

  async clearUnlinked(options = {}) {
    await this.ready()

    const { gte = 0, lt = this.version - 1, batchSize = 4096, wait = true } = options
    const checkout = this.version

    let prev = this.batch({ wait: false, checkout: gte })
    let b = this.batch({ wait, checkout })

    const iteBatch = this.batch({ wait: false, checkout })
    const ite = new LocalBlockIterator(iteBatch, { gte, lt })
    await ite.open()

    let ticks = 0

    while (true) {
      const data = await ite.next()
      if (!data) break

      if (!(await isLinked(b, data))) {
        if (b.core.closing || this.core.closing || this.closing) break
        await this.core.clear(data.seq)
      }

      const prevNode = await prev.get(data.key, { finalize: false }).catch(toNull)

      if (prevNode && !(await isLinked(b, prevNode))) {
        if (b.core.closing || this.core.closing || this.closing) break
        await this.core.clear(prevNode.seq)
      }

      if (ticks++ >= batchSize) {
        ticks = 0
        await prev.close()
        await b.close()

        prev = this.batch({ wait: false, checkout: gte })
        b = this.batch({ wait, checkout })
      }
    }

    if (b.core.closing || this.core.closing || this.closing) throw new Error('Core is closed')

    await b.close()
    await prev.close()
    await ite.close()
    await iteBatch.close()

    return lt
  }

  checkout(version, opts = {}) {
    if (version === 0) version = 1

    // same as above, just checkout isn't set yet...
    const snap =
      opts.reuseSession || this._sessions === false
        ? this.core
        : version <= this.core.length || version <= 1
          ? this.core.snapshot()
          : this.core.session({ snapshot: false })

    return new Hyperbee(snap, {
      _view: true,
      _sub: false,
      prefix: this.prefix,
      sep: this.sep,
      lock: this.lock,
      checkout: version,
      keyEncoding: opts.keyEncoding || this.keyEncoding,
      valueEncoding: opts.valueEncoding || this.valueEncoding,
      extension: this.extension !== null ? this.extension : false
    })
  }

  snapshot(opts) {
    return this.checkout(
      this.core.opened === false || this._checkout <= 0 ? -1 : Math.max(1, this.version),
      opts
    )
  }

  sub(prefix, opts = {}) {
    let sep = opts.sep || this.sep
    if (!b4a.isBuffer(sep)) sep = b4a.from(sep)

    prefix = b4a.concat([this.prefix || EMPTY, b4a.from(prefix), sep])

    const valueEncoding = codecs(opts.valueEncoding || this.valueEncoding)
    const keyEncoding = codecs(opts.keyEncoding || this._unprefixedKeyEncoding)

    return new Hyperbee(this.core, {
      _view: true,
      _sub: true,
      prefix,
      sep: this.sep,
      lock: this.lock,
      checkout: this._checkout,
      valueEncoding,
      keyEncoding,
      extension: this.extension !== null ? this.extension : false,
      metadata: this.metadata
    })
  }

  async getHeader(opts) {
    const blk = await this.core.get(0, opts)
    try {
      return blk && Header.decode(blk)
    } catch {
      throw DECODING_ERROR()
    }
  }

  async _close() {
    if (!this._view) {
      if (this._keyCache) this._keyCache.clear()
      if (this._nodeCache) this._nodeCache.clear()
    }

    if (this._watchers) {
      this.core.off('append', this._onappendBound)
      this.core.off('truncate', this._ontruncateBound)

      while (this._watchers.length) {
        await this._watchers[this._watchers.length - 1].close()
      }
    }

    if (this._entryWatchers) {
      while (this._entryWatchers.length) {
        await this._entryWatchers[this._entryWatchers.length - 1].close()
      }
    }

    while (this._batches.length) {
      await this._batches[this._batches.length - 1].close()
    }

    return this.core.close()
  }

  static async isHyperbee(core, opts) {
    await core.ready()

    const blk0 = await core.get(0, opts)
    if (blk0 === null) throw BLOCK_NOT_AVAILABLE()

    try {
      return Header.decode(blk0).protocol === 'hyperbee'
    } catch (err) {
      // undecodable
      return false
    }
  }
}

class Batch {
  constructor(tree, core, batchLock, cache, options = {}) {
    this.tree = tree
    // this.feed is now deprecated, and will be this.core going forward
    this.feed = core
    this.core = core
    this.index = tree._batches.push(this) - 1
    this.blocks = cache ? new Map() : null
    this.autoFlush = !batchLock
    this.maxBlocksCached = options.maxBlocksCached || 128
    this.rootSeq = 0
    this.root = null
    this.length = 0
    this.checkout = options.checkout === undefined ? -1 : options.checkout
    this.options = options
    this.locked = null
    this.batchLock = batchLock
    this.onseq = this.options.onseq || noop
    this.appending = null
    this.isSnapshot = this.core !== this.tree.core
    this.shouldUpdate = this.options.update !== false
    this.updating = null
    this.encoding = {
      key: options.keyEncoding ? codecs(options.keyEncoding) : tree.keyEncoding,
      value: options.valueEncoding ? codecs(options.valueEncoding) : tree.valueEncoding
    }
  }

  async ready() {
    if (this.core.opened === false) await this.core.ready()
    if (this.tree.opened === false) await this.tree.ready()
  }

  async lock() {
    if (this.tree.readonly) throw new Error('Hyperbee is marked as read-only')
    if (this.locked === null) this.locked = await this.tree.lock()
  }

  get version() {
    if (this.checkout !== -1) return Math.max(1, this.checkout)
    return Math.max(1, this.tree._checkout || this.core.length + this.length)
  }

  async getRoot(ensureHeader) {
    await this.ready()
    if (ensureHeader) {
      if (this.core.length === 0 && this.core.writable && !this.tree.readonly) {
        await this.core.append(
          Header.encode({
            protocol: 'hyperbee',
            metadata: this.tree.metadata
          })
        )
      }
    }
    if (this.tree._checkout === 0 && this.checkout === -1 && this.shouldUpdate) {
      if (this.updating === null) this.updating = this.core.update()
      await this.updating
    }
    if (this.version < 2) return null
    return (await this.getBlock(this.version - 1)).getTreeNode(0)
  }

  async getKey(seq) {
    await this.tree._cacheLock.enter(seq)

    try {
      const k = this.core.fork === this.tree.core.fork ? this.tree._keyCache.get(seq) : null
      if (k !== null) return k
      const key = (await this._getBlock(seq)).key
      if (this.core.fork === this.tree.core.fork) this.tree._keyCache.set(seq, key)
      return key
    } finally {
      this.tree._cacheLock.exit(seq)
    }
  }

  async _getNode(seq) {
    const cached =
      this.tree._nodeCache !== null && this.core.fork === this.tree.core.fork
        ? this.tree._nodeCache.get(seq)
        : null
    if (cached !== null) return cached
    const entry = await this.core.get(seq, {
      ...this.options,
      valueEncoding: Node
    })
    if (entry === null) throw BLOCK_NOT_AVAILABLE()
    const wrap = copyEntry(entry)
    if (this.core.fork === this.tree.core.fork && this.tree._nodeCache !== null) {
      this.tree._nodeCache.set(seq, wrap)
    }
    return wrap
  }

  async getBlock(seq) {
    if (this.rootSeq === 0) this.rootSeq = seq
    await this.tree._cacheLock.enter(seq)

    try {
      return await this._getBlock(seq)
    } finally {
      this.tree._cacheLock.exit(seq)
    }
  }

  async _getBlock(seq) {
    let b = this.blocks && this.blocks.get(seq)
    if (b) return b
    this.onseq(seq)
    const entry = await this._getNode(seq)
    b = this.blocks && this.blocks.get(seq)
    if (b) return b
    b = new BlockEntry(seq, this, entry)
    if (this.blocks && this.blocks.size - this.length < this.maxBlocksCached) {
      this.blocks.set(seq, b)
    }
    return b
  }

  _onwait(key) {
    this.options.onwait = null
    this.tree.extension.get(this.rootSeq + 1, key)
  }

  _getEncoding(opts) {
    if (!opts) return this.encoding
    return {
      key: opts.keyEncoding ? codecs(opts.keyEncoding) : this.encoding.key,
      value: opts.valueEncoding ? codecs(opts.valueEncoding) : this.encoding.value
    }
  }

  peek(range, opts) {
    return iteratorPeek(this.createRangeIterator(range, { ...opts, limit: 1 }))
  }

  createRangeIterator(range, opts = {}) {
    // backwards compat range arg
    opts = opts ? { ...opts, ...range } : range

    const encoding = this._getEncoding(opts)
    return new RangeIterator(
      this,
      encoding,
      encRange(encoding.key, { ...opts, sub: this.tree._sub })
    )
  }

  createReadStream(range, opts) {
    const signal = (opts && opts.signal) || null
    return iteratorToStream(this.createRangeIterator(range, opts), signal)
  }

  async getBySeq(seq, opts) {
    const encoding = this._getEncoding(opts)

    try {
      const block = (await this.getBlock(seq)).final(encoding)
      return { key: block.key, value: block.value }
    } finally {
      await this._closeSnapshot()
    }
  }

  async get(key, opts) {
    const encoding = this._getEncoding(opts)
    const finalize = opts ? opts.finalize !== false : true

    try {
      return await this._get(key, encoding, finalize)
    } finally {
      await this._closeSnapshot()
    }
  }

  async _get(key, encoding, finalize) {
    key = enc(encoding.key, key)

    if (this.tree.extension !== null && this.options.extension !== false) {
      this.options.onwait = this._onwait.bind(this, key)
    }

    let node = await this.getRoot(false)
    if (!node) return null

    while (true) {
      if (node.block.isTarget(key)) {
        return node.block.isDeletion() ? null : finalize ? node.block.final(encoding) : node.block
      }

      let s = 0
      let e = node.keys.length
      let c

      while (s < e) {
        const mid = (s + e) >> 1

        c = b4a.compare(key, await node.getKey(mid))

        if (c === 0) {
          const block = await this.getBlock(node.keys[mid].seq)
          return finalize ? block.final(encoding) : block
        }

        if (c < 0) e = mid
        else s = mid + 1
      }

      if (!node.children.length) return null

      const i = c < 0 ? e : s
      node = await node.getChildNode(i)
    }
  }

  async links(key, seq) {
    let node = await this.getRoot(false)
    if (!node) return false

    if (node.block.seq === seq) return true

    while (true) {
      if (node.block.isTarget(key)) return false

      let s = 0
      let e = node.keys.length
      let c

      while (s < e) {
        const mid = (s + e) >> 1

        if (node.keys[mid].seq === seq) return true
        c = b4a.compare(key, await node.getKey(mid))

        if (c === 0) return false

        if (c < 0) e = mid
        else s = mid + 1
      }

      if (!node.children.length) return false

      const i = c < 0 ? e : s
      node = await node.getChildNode(i)
      if (node.block.seq === seq) return true
    }
  }

  async put(key, value, opts) {
    const release = this.batchLock ? await this.batchLock() : null

    const cas = (opts && opts.cas) || null
    const encoding = this._getEncoding(opts)

    if (!this.locked) await this.lock()
    if (!release) return this._put(key, value, encoding, cas)

    try {
      return await this._put(key, value, encoding, cas)
    } finally {
      release()
    }
  }

  async _put(key, value, encoding, cas) {
    const newNode = {
      seq: 0,
      key,
      value
    }
    key = enc(encoding.key, key)
    value = enc(encoding.value, value)

    const stack = []

    let root
    let node = (root = await this.getRoot(true))
    if (!node) node = root = TreeNode.create(null)

    const seq = (newNode.seq = this.core.length + this.length)
    const target = new Key(seq, key)

    while (node.children.length) {
      stack.push(node)
      node.changed = true // changed, but compressible

      let s = 0
      let e = node.keys.length
      let c

      while (s < e) {
        const mid = (s + e) >> 1
        c = b4a.compare(target.value, await node.getKey(mid))

        if (c === 0) {
          if (cas) {
            const prev = await node.getKeyNode(mid)
            if (!(await cas(prev.final(encoding), newNode))) return this._unlockMaybe()
          }
          if (!this.tree.alwaysDuplicate) {
            const prev = await node.getKeyNode(mid)
            if (sameValue(prev.value, value)) return this._unlockMaybe()
          }
          node.setKey(mid, target)
          return this._append(root, seq, key, value)
        }

        if (c < 0) e = mid
        else s = mid + 1
      }

      const i = c < 0 ? e : s
      node = await node.getChildNode(i)
    }

    let needsSplit = !(await node.insertKey(target, value, null, newNode, encoding, cas))
    if (!node.changed) return this._unlockMaybe()

    while (needsSplit) {
      const parent = stack.pop()
      const { median, right } = await node.split()

      if (parent) {
        needsSplit = !(await parent.insertKey(median, value, right, null, encoding, null))
        node = parent
      } else {
        root = TreeNode.create(node.block)
        root.changed = true
        root.keys.push(median)
        root.children.push(new Child(0, 0, node), new Child(0, 0, right))
        needsSplit = false
      }
    }

    return this._append(root, seq, key, value)
  }

  async del(key, opts) {
    const release = this.batchLock ? await this.batchLock() : null
    const cas = (opts && opts.cas) || null
    const encoding = this._getEncoding(opts)

    if (!this.locked) await this.lock()
    if (!release) return this._del(key, encoding, cas)

    try {
      return await this._del(key, encoding, cas)
    } finally {
      release()
    }
  }

  async _del(key, encoding, cas) {
    const delNode = {
      seq: 0,
      key,
      value: null
    }

    key = enc(encoding.key, key)

    const stack = []

    let node = await this.getRoot(true)
    if (!node) return this._unlockMaybe()

    const seq = (delNode.seq = this.core.length + this.length)

    while (true) {
      stack.push(node)

      let s = 0
      let e = node.keys.length
      let c

      while (s < e) {
        const mid = (s + e) >> 1
        c = b4a.compare(key, await node.getKey(mid))

        if (c === 0) {
          if (cas) {
            const prev = await node.getKeyNode(mid)
            if (!(await cas(prev.final(encoding), delNode))) return this._unlockMaybe()
          }
          if (node.children.length) await setKeyToNearestLeaf(node, mid, stack)
          else node.removeKey(mid)
          // we mark these as changed late, so we don't rewrite them if it is a 404
          for (const node of stack) node.changed = true
          return this._append(await rebalance(stack), seq, key, null)
        }

        if (c < 0) e = mid
        else s = mid + 1
      }

      if (!node.children.length) return this._unlockMaybe()

      const i = c < 0 ? e : s
      node = await node.getChildNode(i)
    }
  }

  async _closeSnapshot() {
    if (this.isSnapshot) {
      await this.core.close()
      this._finalize()
    }
  }

  async close() {
    if (this.isSnapshot) return this._closeSnapshot()

    this.root = null
    if (this.blocks) this.blocks.clear()
    this.length = 0
    this._unlock()
  }

  destroy() {
    // compat, remove later
    this.close().catch(noop)
  }

  toBlocks() {
    if (this.appending) return this.appending

    const batch = new Array(this.length)

    for (let i = 0; i < this.length; i++) {
      const seq = this.core.length + i
      const { pendingIndex, key, value } = this.blocks.get(seq)

      if (i < this.length - 1) {
        pendingIndex[0] = null
        let j = 0

        while (j < pendingIndex.length) {
          const idx = pendingIndex[j]
          if (idx !== null && idx.seq === seq) {
            idx.offset = j++
            continue
          }
          if (j === pendingIndex.length - 1) pendingIndex.pop()
          else pendingIndex[j] = pendingIndex.pop()
        }
      }

      batch[i] = Node.encode({
        key,
        value,
        index: deflate(pendingIndex)
      })
    }

    this.appending = batch
    return batch
  }

  flush() {
    if (!this.length) return this.close()

    const batch = this.toBlocks()

    this.root = null
    this.blocks.clear()
    this.length = 0

    return this._appendBatch(batch)
  }

  _unlockMaybe() {
    if (this.autoFlush) this._unlock()
  }

  _unlock() {
    const locked = this.locked
    this.locked = null
    if (locked !== null) locked()
    this._finalize()
  }

  _finalize() {
    // technically finalize can be called more than once, so here we just check if we already have been removed
    if (this.index >= this.tree._batches.length || this.tree._batches[this.index] !== this) return
    const top = this.tree._batches.pop()
    if (top === this) return
    top.index = this.index
    this.tree._batches[top.index] = top
  }

  _append(root, seq, key, value) {
    const index = []
    root.indexChanges(index, seq)
    index[0] = new Child(seq, 0, root)

    if (!this.autoFlush) {
      const block = new BatchEntry(seq, this, key, value, index)
      root.block = block
      this.root = root
      this.length++
      this.blocks.set(seq, block)

      root.updateChildren(seq, block)
      return
    }

    return this._appendBatch(
      Node.encode({
        key,
        value,
        index: deflate(index)
      })
    )
  }

  async _appendBatch(raw) {
    try {
      await this.core.append(raw)
    } finally {
      this._unlock()
    }
  }
}

class EntryWatcher extends ReadyResource {
  constructor(bee, key, opts = {}) {
    super()

    this.keyEncoding = opts.keyEncoding || bee.keyEncoding
    this.valueEncoding = opts.valueEncoding || bee.valueEncoding

    this.index = bee._entryWatchers.push(this) - 1
    this.bee = bee

    this.key = key
    this.node = null

    this._forceUpdate = false
    this._debouncedUpdate = debounce(this._processUpdate.bind(this))
  }

  _close() {
    const top = this.bee._entryWatchers.pop()
    if (top !== this) {
      top.index = this.index
      this.bee._entryWatchers[top.index] = top
    }
  }

  _onappend() {
    this._debouncedUpdate()
  }

  _ontruncate() {
    this._forceUpdate = true
    this._debouncedUpdate()
  }

  async _processUpdate() {
    const force = this._forceUpdate
    this._forceUpdate = false

    let newNode
    try {
      newNode = await this.bee.get(this.key, {
        keyEncoding: this.keyEncoding,
        valueEncoding: this.valueEncoding
      })
    } catch (e) {
      if (e.code === 'SNAPSHOT_NOT_AVAILABLE') {
        // There was a truncate event before the get resolved
        // So this handler will run again anyway
        return
      } else if (this.bee.closing) {
        this.close().catch(safetyCatch)
        return
      }
      this.emit('error', e)
      return
    }

    if (force || newNode?.seq !== this.node?.seq) {
      this.node = newNode
      this.emit('update')
    }
  }
}

class Watcher extends ReadyResource {
  constructor(bee, range, opts = {}) {
    super()

    this.keyEncoding = opts.keyEncoding || bee.keyEncoding
    this.valueEncoding = opts.valueEncoding || bee.valueEncoding
    this.index = bee._watchers.push(this) - 1
    this.bee = bee
    this.core = bee.core

    this.latestDiff = 0
    this.range = range
    this.map = opts.map || defaultWatchMap

    this.current = null
    this.previous = null
    this.currentMapped = null
    this.previousMapped = null
    this.stream = null

    this._lock = mutexify()
    this._flowing = false
    this._resolveOnChange = null
    this._differ = opts.differ || defaultDiffer
    this._eager = !!opts.eager
    this._onchange = opts.onchange || null

    this.on('newListener', autoFlowOnUpdate)

    this.ready().catch(safetyCatch)
  }

  async _consume() {
    if (this._flowing) return
    try {
      for await (const _ of this) {
      } // eslint-disable-line
    } catch {}
  }

  async _open() {
    await this.bee.ready()

    const opts = {
      keyEncoding: this.keyEncoding,
      valueEncoding: this.valueEncoding
    }

    // Point from which to start watching
    this.current = this._eager ? this.bee.checkout(1, opts) : this.bee.snapshot(opts)
    await this.current.ready()

    if (this._onchange) {
      if (this._eager) await this._onchange()
      this._consume()
    }
  }

  [Symbol.asyncIterator]() {
    this._flowing = true
    return this
  }

  _ontruncate() {
    this._onappend()
  }

  _onappend() {
    const resolve = this._resolveOnChange
    this._resolveOnChange = null
    if (resolve) resolve()
  }

  async _waitForChanges() {
    if (this.current.version < this.bee.version || this.closing) return

    await new Promise((resolve) => {
      this._resolveOnChange = resolve
    })
  }

  async next() {
    try {
      return await this._next()
    } catch (err) {
      if (this.closing) return { value: undefined, done: true }
      await this.close()
      throw err
    }
  }

  async _next() {
    const release = await this._lock()

    try {
      if (this.closing) return { value: undefined, done: true }

      if (!this.opened) await this.ready()

      while (true) {
        await this._waitForChanges()

        if (this.closing) return { value: undefined, done: true }

        await this._closePrevious()
        this.previous = this.current.snapshot()

        await this._closeCurrent()
        this.current = this.bee.snapshot({
          keyEncoding: this.keyEncoding,
          valueEncoding: this.valueEncoding
        })

        await this.current.ready()
        await this.previous.ready()

        if (this.current.core.fork !== this.previous.core.fork) {
          return await this._yield()
        }

        this.stream = this._differ(this.current, this.previous, this.range)

        try {
          for await (const data of this.stream) {
            // eslint-disable-line
            return await this._yield()
          }
        } finally {
          this.stream = null
        }
      }
    } finally {
      release()
    }
  }

  async _yield() {
    this.currentMapped = this.map(this.current)
    this.previousMapped = this.map(this.previous)

    if (this._onchange) {
      try {
        await this._onchange()
      } catch (err) {
        safetyCatch(err)
      }
    }

    this.emit('update')
    return { done: false, value: [this.currentMapped, this.previousMapped] }
  }

  async return() {
    await this.close()
    return { done: true }
  }

  async _close() {
    const top = this.bee._watchers.pop()
    if (top !== this) {
      top.index = this.index
      this.bee._watchers[top.index] = top
    }

    if (this.stream && !this.stream.destroying) {
      this.stream.destroy()
    }

    this._onappend() // Continue execution being closed

    await this._closeCurrent().catch(safetyCatch)
    await this._closePrevious().catch(safetyCatch)

    const release = await this._lock()
    release()
  }

  destroy() {
    return this.close()
  }

  async _closeCurrent() {
    if (this.currentMapped) await this.currentMapped.close()
    if (this.current) await this.current.close()
    this.current = this.currentMapped = null
  }

  async _closePrevious() {
    if (this.previousMapped) await this.previousMapped.close()
    if (this.previous) await this.previous.close()
    this.previous = this.previousMapped = null
  }
}

function autoFlowOnUpdate(name) {
  if (name === 'update') this._consume()
}

function defaultWatchMap(snapshot) {
  return snapshot
}

async function leafSize(node, goLeft) {
  while (node.children.length) node = await node.getChildNode(goLeft ? 0 : node.children.length - 1)
  return node.keys.length
}

async function setKeyToNearestLeaf(node, index, stack) {
  let [left, right] = await Promise.all([node.getChildNode(index), node.getChildNode(index + 1)])
  const [ls, rs] = await Promise.all([leafSize(left, false), leafSize(right, true)])

  if (ls < rs) {
    // if fewer leaves on the left
    stack.push(right)
    while (right.children.length) stack.push((right = right.children[0].value))
    node.keys[index] = right.keys.shift()
  } else {
    // if fewer leaves on the right
    stack.push(left)
    while (left.children.length) stack.push((left = left.children[left.children.length - 1].value))
    node.keys[index] = left.keys.pop()
  }
}

async function rebalance(stack) {
  const root = stack[0]

  while (stack.length > 1) {
    const node = stack.pop()
    const parent = stack[stack.length - 1]

    if (node.keys.length >= MIN_KEYS) return root

    let { left, index, right } = await node.siblings(parent)

    // maybe borrow from left sibling?
    if (left && left.keys.length > MIN_KEYS) {
      left.changed = true
      node.keys.unshift(parent.keys[index - 1])
      if (left.children.length) node.children.unshift(left.children.pop())
      parent.keys[index - 1] = left.keys.pop()
      return root
    }

    // maybe borrow from right sibling?
    if (right && right.keys.length > MIN_KEYS) {
      right.changed = true
      node.keys.push(parent.keys[index])
      if (right.children.length) node.children.push(right.children.shift())
      parent.keys[index] = right.keys.shift()
      return root
    }

    // merge node with another sibling
    if (left) {
      index--
      right = node
    } else {
      left = node
    }

    left.merge(right, parent.keys[index])
    parent.removeKey(index)
  }

  // check if the tree shrunk
  if (!root.keys.length && root.children.length) return root.getChildNode(0)
  return root
}

function iteratorToStream(ite, signal) {
  let done
  let closing

  const rs = new Readable({
    signal,
    open(cb) {
      done = cb
      ite.open().then(fin, fin)
    },
    read(cb) {
      done = cb
      ite.next().then(push, fin)
    },
    predestroy() {
      closing = ite.close()
      closing.catch(noop)
    },
    destroy(cb) {
      done = cb
      if (!closing) closing = ite.close()
      closing.then(fin, fin)
    }
  })

  return rs

  function fin(err) {
    done(err)
  }

  function push(val) {
    rs.push(val)
    done(null)
  }
}

async function iteratorPeek(ite) {
  try {
    await ite.open()
    return await ite.next()
  } finally {
    await ite.close()
  }
}

function encRange(e, opts) {
  if (!e) return opts

  if (e.encodeRange) {
    const r = e.encodeRange({
      gt: opts.gt,
      gte: opts.gte,
      lt: opts.lt,
      lte: opts.lte
    })
    opts.gt = r.gt
    opts.gte = r.gte
    opts.lt = r.lt
    opts.lte = r.lte
    return opts
  }

  if (opts.gt !== undefined) opts.gt = enc(e, opts.gt)
  if (opts.gte !== undefined) opts.gte = enc(e, opts.gte)
  if (opts.lt !== undefined) opts.lt = enc(e, opts.lt)
  if (opts.lte !== undefined) opts.lte = enc(e, opts.lte)
  if (opts.sub && !opts.gt && !opts.gte) opts.gt = enc(e, SEP)
  if (opts.sub && !opts.lt && !opts.lte) opts.lt = bump(enc(e, EMPTY))

  return opts
}

function bump(key) {
  // key should have been copied by enc above before hitting this
  key[key.length - 1]++
  return key
}

function enc(e, v) {
  if (v === undefined || v === null) return null
  if (e !== null) return e.encode(v)
  if (typeof v === 'string') return b4a.from(v)
  return v
}

function prefixEncoding(prefix, keyEncoding) {
  return {
    encode(key) {
      return b4a.concat([prefix, b4a.isBuffer(key) ? key : enc(keyEncoding, key)])
    },
    decode(key) {
      const sliced = key.slice(prefix.length, key.length)
      return keyEncoding ? keyEncoding.decode(sliced) : sliced
    }
  }
}

function copyEntry(entry) {
  let key = entry.key
  let value = entry.value
  let index = entry.index

  // key, value and index all refer to the same buffer (one hypercore block)
  // If together they are larger than half the buffer's byteLength,
  // this means that they got their own private slab (see Buffer.allocUnsafe docs)
  // so no need to unslab
  const size =
    key.byteLength +
    (value === null ? 0 : value.byteLength) +
    (index === null ? 0 : index.byteLength)
  if (2 * size < key.buffer.byteLength) {
    const [newKey, newValue, newIndex] = unslabAll([entry.key, entry.value, entry.index])
    key = newKey
    value = newValue
    index = newIndex
  }

  return {
    key,
    value,
    index,
    inflated: null
  }
}

function defaultDiffer(currentSnap, previousSnap, opts) {
  return currentSnap.createDiffStream(previousSnap, opts)
}

function toNull() {
  return null
}

function getBackingCore(core) {
  if (core.core) return core
  if (core.getBackingCore) return core.getBackingCore().session
  return null
}

function sameValue(a, b) {
  return a === b || (a !== null && b !== null && b4a.equals(a, b))
}

function noop() {}

function getExtension(db, opts) {
  if (opts.extension === false) return null
  if (opts.extension && opts.extension !== true) return opts.extension
  return Extension.register(db)
}

async function isLinked(batch, block) {
  const seq = block.seq
  block.inflate()

  const keys = [block.key]
  const wait = batch.options.wait

  for (const l of block.index.levels) {
    if (!l.keys.length) continue
    batch.options.wait = false
    try {
      keys.push(await batch.getKey(l.keys[0].seq))
    } catch {}
    batch.options.wait = wait
  }

  for (const k of keys) {
    if (await batch.links(k, seq)) return true
  }

  if (batch.core.closing) throw new Error('Core is closed')

  return false
}

module.exports = Hyperbee
const b4a = require('b4a')

class SubTree {
  constructor(node, parent) {
    this.node = node
    this.parent = parent

    this.isKey = node.children.length === 0
    this.i = this.isKey ? 1 : 0
    this.n = 0

    const child = this.isKey ? null : this.node.children[0]
    this.seq = child !== null ? child.seq : this.node.keys[0].seq
    this.offset = child !== null ? child.offset : 0
  }

  next() {
    this.i++
    this.isKey = (this.i & 1) === 1
    if (!this.isKey && !this.node.children.length) this.i++
    return this.update()
  }

  async bisect(key, incl) {
    let s = 0
    let e = this.node.keys.length
    let c

    while (s < e) {
      const mid = (s + e) >> 1
      c = cmp(key, await this.node.getKey(mid))

      if (c === 0) {
        if (incl) this.i = mid * 2 + 1
        else this.i = mid * 2 + (this.node.children.length ? 2 : 3)
        return true
      }

      if (c < 0) e = mid
      else s = mid + 1
    }

    const i = c < 0 ? e : s
    this.i = 2 * i + (this.node.children.length ? 0 : 1)
    return this.node.children.length === 0
  }

  update() {
    this.isKey = (this.i & 1) === 1
    this.n = this.i >> 1
    if (this.n >= (this.isKey ? this.node.keys.length : this.node.children.length)) return false
    const child = this.isKey ? null : this.node.children[this.n]
    this.seq = child !== null ? child.seq : this.node.keys[this.n].seq
    this.offset = child !== null ? child.offset : 0
    return true
  }

  async key() {
    return this.n < this.node.keys.length
      ? this.node.getKey(this.n)
      : this.parent && this.parent.key()
  }

  async compare(tree) {
    const [a, b] = await Promise.all([this.key(), tree.key()])
    return cmp(a, b)
  }
}

class TreeIterator {
  constructor(batch, opts) {
    this.batch = batch
    this.stack = []
    this.lt = opts.lt || opts.lte || null
    this.lte = !!opts.lte
    this.gt = opts.gt || opts.gte || null
    this.gte = !!opts.gte
    this.seeking = !!this.gt
    this.encoding = opts.encoding || batch.encoding
  }

  async open() {
    const node = await this.batch.getRoot(false)
    if (!node || !node.keys.length) return
    const tree = new SubTree(node, null)
    if (this.seeking && !(await this._seek(tree))) return
    this.stack.push(tree)
  }

  async _seek(tree) {
    const done = await tree.bisect(this.gt, this.gte)
    const oob = !tree.update()
    if (done || oob) {
      this.seeking = false
      if (oob) return false
    }
    return true
  }

  peek() {
    if (!this.stack.length) return null
    return this.stack[this.stack.length - 1]
  }

  skip() {
    if (!this.stack.length) return
    if (!this.stack[this.stack.length - 1].next()) this.stack.pop()
  }

  async nextKey() {
    let n = null
    while (this.stack.length && n === null) n = await this.next()
    if (n === null) return null
    if (!this.lt) return n.final(this.encoding)

    const c = cmp(n.key, this.lt)
    if (this.lte ? c <= 0 : c < 0) return n.final(this.encoding)
    this.stack = []
    return null
  }

  async next() {
    if (!this.stack.length) return null

    const top = this.stack[this.stack.length - 1]
    const { isKey, n, seq } = top

    if (!top.next()) {
      this.stack.pop()
    }

    if (isKey) {
      this.seeking = false
      return this.batch.getBlock(seq)
    }

    const child = await top.node.getChildNode(n)
    top.node.children[n] = null // unlink to save memory
    const tree = new SubTree(child, top)
    if (this.seeking && !(await this._seek(tree))) return null
    this.stack.push(tree)

    return null
  }

  close() {
    return this.batch._closeSnapshot()
  }
}

module.exports = class DiffIterator {
  constructor(left, right, opts = {}) {
    this.left = new TreeIterator(left, opts)
    this.right = new TreeIterator(right, opts)
    this.limit = typeof opts.limit === 'number' ? opts.limit : -1
  }

  async open() {
    await Promise.all([this.left.open(), this.right.open()])
  }

  async next() {
    if (this.limit === 0) return null
    const res = await this._next()
    if (!res || (res.left === null && res.right === null)) return null
    this.limit--
    return res
  }

  async _next() {
    const a = this.left
    const b = this.right

    while (true) {
      const [l, r] = await Promise.all([a.peek(), b.peek()])

      if (!l && !r) return null
      if (!l) return { left: null, right: await b.nextKey() }
      if (!r) return { left: await a.nextKey(), right: null }

      if (l.seq === r.seq && l.isKey === r.isKey && l.offset === r.offset) {
        a.skip()
        b.skip()
        continue
      }

      const c = await l.compare(r)

      if (l.isKey && !r.isKey) {
        await b.next()
        continue
      }

      if (!l.isKey && r.isKey) {
        await a.next()
        continue
      }

      if (l.isKey && r.isKey) {
        if (c === 0) return { left: await a.nextKey(), right: await b.nextKey() }
        if (c < 0) return { left: await a.nextKey(), right: null }
        return { left: null, right: await b.nextKey() }
      }

      if (c === 0) await Promise.all([a.next(), b.next()])
      else if (c < 0) await b.next()
      else await a.next()
    }
  }

  async close() {
    await Promise.all([this.left.close(), this.right.close()])
  }
}

function cmp(a, b) {
  if (!a) return b ? 1 : 0
  if (!b) return a ? -1 : 0
  return b4a.compare(a, b)
}
module.exports = class HistoryIterator {
  constructor(batch, opts = {}) {
    this.batch = batch
    this.options = opts
    this.live = !!opts.live
    this.gte = 0
    this.lt = 0
    this.reverse = !!opts.reverse
    this.limit = typeof opts.limit === 'number' ? opts.limit : -1
    this.encoding = opts.encoding || batch.encoding
    if (this.live && this.reverse) {
      throw new Error('Cannot have both live and reverse enabled')
    }
  }

  async open() {
    await this.batch.getRoot(false) // does the update dance
    this.gte = gte(this.options, this.batch.version)
    this.lt = this.live ? Infinity : lt(this.options, this.batch.version)
  }

  async next() {
    if (this.limit === 0) return null
    if (this.limit > 0) this.limit--

    if (this.gte >= this.lt) return null

    if (this.reverse) {
      if (this.lt <= 1) return null
      return final(await this.batch.getBlock(--this.lt), this.encoding)
    }

    return final(await this.batch.getBlock(this.gte++), this.encoding)
  }

  close() {
    return this.batch._closeSnapshot()
  }
}

function final(node, encoding) {
  const type = node.isDeletion() ? 'del' : 'put'
  return { type, ...node.final(encoding) }
}

function gte(opts, version) {
  if (opts.gt) return (opts.gt < 0 ? opts.gt + version : opts.gt) + 1
  const gte = opts.gte || opts.since || 1
  return gte < 0 ? gte + version : gte
}

function lt(opts, version) {
  if (opts.lte === 0 || opts.lt === 0 || opts.end === 0) return 0
  if (opts.lte) return (opts.lte < 0 ? opts.lte + version : opts.lte) + 1
  const lt = opts.lt || opts.end || version
  return lt < 0 ? lt + version : lt
}
module.exports = class LocalBlocksIterator {
  constructor(batch, opts = {}) {
    this.batch = batch
    this.options = opts
    this.gte = 0
    this.lt = 0
    this.limit = typeof opts.limit === 'number' ? opts.limit : -1
  }

  async open() {
    await this.batch.getRoot(false) // does the update dance
    this.gte = gte(this.options, this.batch.version)
    this.lt = lt(this.options, this.batch.version)
  }

  async next() {
    if (this.limit === 0) return null
    if (this.limit > 0) this.limit--

    while (this.gte < this.lt) {
      try {
        return await this.batch.getBlock(this.gte++)
      } catch {
        continue
      }
    }

    return null
  }

  close() {
    return this.batch._closeSnapshot()
  }
}

function gte(opts, version) {
  if (opts.gt) return (opts.gt < 0 ? opts.gt + version : opts.gt) + 1
  const gte = opts.gte || opts.since || 1
  return gte < 0 ? gte + version : gte
}

function lt(opts, version) {
  if (opts.lte === 0 || opts.lt === 0 || opts.end === 0) return 0
  if (opts.lte) return (opts.lte < 0 ? opts.lte + version : opts.lte) + 1
  const lt = opts.lt || opts.end || version
  return lt < 0 ? lt + version : lt
}
const b4a = require('b4a')

module.exports = class RangeIterator {
  constructor(batch, encoding, opts = {}) {
    this.batch = batch
    this.stack = []
    this.opened = false
    this.encoding = encoding || batch.encoding

    this._limit = typeof opts.limit === 'number' ? opts.limit : -1
    this._gIncl = !opts.gt
    this._gKey = opts.gt || opts.gte || null
    this._lIncl = !opts.lt
    this._lKey = opts.lt || opts.lte || null
    this._reverse = !!opts.reverse
    this._version = 0
    this._checkpoint = opts.checkpoint && opts.checkpoint.length ? opts.checkpoint : null
    this._nexting = false
    this._closed = false
  }

  snapshot(version = this.batch.version) {
    const checkpoint = []
    for (const s of this.stack) {
      let { node, i } = s
      if (this._nexting && s === this.stack[this.stack.length - 1]) {
        i = this._reverse ? i + 1 : i - 1
      }
      if (!node.block) continue
      if (i < 0) continue
      checkpoint.push(node.block.seq, node.offset, i)
    }

    return {
      version,
      gte: this._gIncl ? this._gKey : null,
      gt: this._gIncl ? null : this._gKey,
      lte: this._lIncl ? this._lKey : null,
      lt: this._lIncl ? null : this._lKey,
      limit: this._limit,
      reverse: this._reverse,
      ended: this.opened && !checkpoint.length,
      checkpoint: this.opened ? checkpoint : []
    }
  }

  async open() {
    await this._open()
    this.opened = true
  }

  async _open() {
    if (this._checkpoint) {
      for (let j = 0; j < this._checkpoint.length; j += 3) {
        const seq = this._checkpoint[j]
        const offset = this._checkpoint[j + 1]
        const i = this._checkpoint[j + 2]
        this.stack.push({
          node: (await this.batch.getBlock(seq)).getTreeNode(offset),
          i
        })
      }
      return
    }

    this._nexting = true

    let node = await this.batch.getRoot(false)
    if (!node) {
      this._nexting = false
      return
    }

    const incl = this._reverse ? this._lIncl : this._gIncl
    const start = this._reverse ? this._lKey : this._gKey

    if (!start) {
      this.stack.push({ node, i: this._reverse ? node.keys.length << 1 : 0 })
      this._nexting = false
      this._preloadQuery()
      return
    }

    while (true) {
      const entry = { node, i: this._reverse ? node.keys.length << 1 : 0 }

      let s = 0
      let e = node.keys.length
      let c

      while (s < e) {
        const mid = (s + e) >> 1
        c = b4a.compare(start, await node.getKey(mid))

        if (c === 0) {
          if (incl) entry.i = mid * 2 + 1
          else entry.i = mid * 2 + (this._reverse ? 0 : 2)
          this.stack.push(entry)
          this._nexting = false
          this._preloadQuery()
          return
        }

        if (c < 0) e = mid
        else s = mid + 1
      }

      const i = c < 0 ? e : s
      entry.i = 2 * i + (this._reverse ? -1 : 1)

      if (entry.i >= 0 && entry.i <= node.keys.length << 1) this.stack.push(entry)
      if (!node.children.length) {
        this._nexting = false
        this._preloadQuery()
        return
      }

      node = await node.getChildNode(i)
    }
  }

  _preloadQuery() {
    const max = { nodes: 0, max: 2048 }

    if (this._limit === -1 && !this._reverse && this.stack.length) {
      for (const s of this.stack) {
        const k = (s.i - (s.i & 1)) / 2
        this._preload(s.node, k + 1, this._lKey, max).catch(noop)
      }
    }
  }

  async _preload(node, i, end, max) {
    for (; i < node.keys.length; i++) {
      const key = node.keys[i]
      const block = await this.batch.getBlock(key.seq)
      if (this._closed) return
      const c = end ? b4a.compare(block.key, end) : -1
      if (c >= 0 || max.nodes >= max.max || i >= node.children.length) return
      max.nodes++
      const next = await node.getChildNode(i)
      if (this._closed) return
      this._preload(next, 0, end, max).catch(noop)
    }

    if (node.children.length && max.nodes < max.max) {
      const next = await node.getChildNode(node.children.length - 1)
      if (this._closed) return
      this._preload(next, 0, end, max).catch(noop)
    }
  }

  async next() {
    // TODO: this nexting flag is only needed if someone asks for a snapshot during
    // a lookup (ie the extension, pretty important...).
    // A better solution would be to refactor this so top.i is incremented eagerly
    // to get the current block instead of the way it is done now (++i vs i++)
    this._nexting = true

    const end = this._reverse ? this._gKey : this._lKey
    const incl = this._reverse ? this._gIncl : this._lIncl

    while (this.stack.length && (this._limit === -1 || this._limit > 0)) {
      const top = this.stack[this.stack.length - 1]
      const isKey = (top.i & 1) === 1
      const n = this._reverse ? (top.i < 0 ? top.node.keys.length : top.i-- >> 1) : top.i++ >> 1

      if (!isKey) {
        if (!top.node.children.length) continue
        const node = await top.node.getChildNode(n)
        if (top.node.block.seq < this.batch.core.length) {
          top.node.children[n].value = null // unlink it to save memory
        }
        this.stack.push({ i: this._reverse ? node.keys.length << 1 : 0, node })
        continue
      }

      if (n >= top.node.keys.length) {
        this.stack.pop()
        continue
      }

      const key = top.node.keys[n]
      const block = await this.batch.getBlock(key.seq)
      if (end) {
        const c = b4a.compare(block.key, end)
        if (c === 0 ? !incl : this._reverse ? c < 0 : c > 0) {
          this._limit = 0
          break
        }
      }
      if (this._limit > 0) this._limit--
      this._nexting = false
      return block.final(this.encoding)
    }

    this._nexting = false
    return null
  }

  close() {
    this._closed = true
    return this.batch._closeSnapshot()
  }
}

function noop() {}
const { Extension } = require('./messages')

// const MAX_ACTIVE = 32
const FLUSH_BATCH = 128
const MAX_PASSIVE_BATCH = 2048
const MAX_ACTIVE_BATCH = MAX_PASSIVE_BATCH + FLUSH_BATCH

class Batch {
  constructor(outgoing, from) {
    this.blocks = []
    this.start = 0
    this.end = 0
    this.outgoing = outgoing
    this.from = from
  }

  push(seq) {
    const len = this.blocks.push(seq)
    if (len === 1 || seq < this.start) this.start = seq
    if (len === 1 || seq >= this.end) this.end = seq + 1
    if (len >= FLUSH_BATCH) {
      this.send()
      this.clear()
    }
  }

  send() {
    if (!this.blocks.length) return
    this.outgoing.send(
      Extension.encode({
        cache: { blocks: this.blocks, start: this.start, end: this.end }
      }),
      this.from
    )
  }

  clear() {
    this.start = this.end = 0
    this.blocks = []
  }
}

class HyperbeeExtension {
  constructor(db) {
    this.encoding = null
    this.outgoing = null
    this.db = db
    this.active = 0
  }

  get(version, key) {
    this.outgoing.broadcast(Extension.encode({ get: { version, key } }))
  }

  iterator(snapshot) {
    if (snapshot.ended) return
    if (snapshot.limit === 0) return
    if (snapshot.limit === -1) snapshot.limit = 0
    this.outgoing.broadcast(Extension.encode({ iterator: snapshot }))
  }

  onmessage(buf, from) {
    // TODO: handle max active extension messages
    // this.active++

    const message = decode(buf)
    if (!message) return

    if (message.cache) this.oncache(message.cache, from)
    if (message.get) this.onget(message.get, from)
    if (message.iterator) this.oniterator(message.iterator, from)
  }

  oncache(message, from) {
    if (!message.blocks.length) return
    this.db.core.download(message)
  }

  onget(message, from) {
    if (!message.version || message.version > this.db.version) return

    const b = new Batch(this.outgoing, from)
    const db = this.db.checkout(message.version)

    db.get(message.key, {
      extension: false,
      wait: false,
      update: false,
      onseq
    }).then(done, done)

    function done() {
      db.close().catch(noop)
      b.send()
    }

    function onseq(seq) {
      b.push(seq)
    }
  }

  async oniterator(message, from) {
    if (!message.version || message.version > this.db.version) return

    const b = new Batch(this.outgoing, from)
    const seqs = new Set()

    let skip = message.checkpoint.length
    let work = 0

    const db = this.db.checkout(message.version)
    const ite = db.createRangeIterator({
      ...message,
      wait: false,
      extension: false,
      update: false,
      limit: message.limit === 0 ? -1 : message.limit,
      onseq(seq) {
        if (skip && skip--) return
        if (seqs.has(seq)) return
        work++
        seqs.add(seq)
        b.push(seq)
      }
    })

    try {
      await ite.open()
      // eslint-disable-next-line no-unmodified-loop-condition
      while (work < MAX_ACTIVE_BATCH) {
        if (!(await ite.next())) break
      }
    } catch (_) {
      // do nothing
    } finally {
      ite.close().catch(noop)
      db.close().catch(noop)
      b.send()
    }
  }

  static register(db) {
    const e = new this(db)
    e.outgoing = db.core.registerExtension('hyperbee', e)
    return e
  }
}

HyperbeeExtension.BATCH_SIZE = MAX_PASSIVE_BATCH

module.exports = HyperbeeExtension

function decode(buf) {
  try {
    return Extension.decode(buf)
  } catch (err) {
    return null
  }
}

function noop() {}
// This file is auto generated by the protocol-buffers compiler

/* eslint-disable quotes */
/* eslint-disable indent */
/* eslint-disable no-redeclare */
/* eslint-disable camelcase */
/* eslint-disable no-var */

// Remember to `npm install --save protocol-buffers-encodings`
var encodings = require('protocol-buffers-encodings')
var b4a = require('b4a')
var varint = encodings.varint
var skip = encodings.skip

var YoloIndex = exports.YoloIndex = {
  buffer: true,
  encodingLength: null,
  encode: null,
  decode: null
}

var Header = exports.Header = {
  buffer: true,
  encodingLength: null,
  encode: null,
  decode: null
}

var Node = exports.Node = {
  buffer: true,
  encodingLength: null,
  encode: null,
  decode: null
}

var Extension = exports.Extension = {
  buffer: true,
  encodingLength: null,
  encode: null,
  decode: null
}

defineYoloIndex()
defineHeader()
defineNode()
defineExtension()

function defineYoloIndex () {
  var Level = YoloIndex.Level = {
    buffer: true,
    encodingLength: null,
    encode: null,
    decode: null
  }

  defineLevel()

  function defineLevel () {
    Level.encodingLength = encodingLength
    Level.encode = encode
    Level.decode = decode

    function encodingLength (obj) {
      var length = 0
      if (defined(obj.keys)) {
        var packedLen = 0
        for (var i = 0; i < obj.keys.length; i++) {
          if (!defined(obj.keys[i])) continue
          var len = encodings.varint.encodingLength(obj.keys[i])
          packedLen += len
        }
        if (packedLen) {
          length += 1 + packedLen + varint.encodingLength(packedLen)
        }
      }
      if (defined(obj.children)) {
        var packedLen = 0
        for (var i = 0; i < obj.children.length; i++) {
          if (!defined(obj.children[i])) continue
          var len = encodings.varint.encodingLength(obj.children[i])
          packedLen += len
        }
        if (packedLen) {
          length += 1 + packedLen + varint.encodingLength(packedLen)
        }
      }
      return length
    }

    function encode (obj, buf, offset) {
      if (!offset) offset = 0
      if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
      var oldOffset = offset
      if (defined(obj.keys)) {
        var packedLen = 0
        for (var i = 0; i < obj.keys.length; i++) {
          if (!defined(obj.keys[i])) continue
          packedLen += encodings.varint.encodingLength(obj.keys[i])
        }
        if (packedLen) {
          buf[offset++] = 10
          varint.encode(packedLen, buf, offset)
          offset += varint.encode.bytes
        }
        for (var i = 0; i < obj.keys.length; i++) {
          if (!defined(obj.keys[i])) continue
          encodings.varint.encode(obj.keys[i], buf, offset)
          offset += encodings.varint.encode.bytes
        }
      }
      if (defined(obj.children)) {
        var packedLen = 0
        for (var i = 0; i < obj.children.length; i++) {
          if (!defined(obj.children[i])) continue
          packedLen += encodings.varint.encodingLength(obj.children[i])
        }
        if (packedLen) {
          buf[offset++] = 18
          varint.encode(packedLen, buf, offset)
          offset += varint.encode.bytes
        }
        for (var i = 0; i < obj.children.length; i++) {
          if (!defined(obj.children[i])) continue
          encodings.varint.encode(obj.children[i], buf, offset)
          offset += encodings.varint.encode.bytes
        }
      }
      encode.bytes = offset - oldOffset
      return buf
    }

    function decode (buf, offset, end) {
      if (!offset) offset = 0
      if (!end) end = buf.length
      if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
      var oldOffset = offset
      var obj = {
        keys: [],
        children: []
      }
      while (true) {
        if (end <= offset) {
          decode.bytes = offset - oldOffset
          return obj
        }
        var prefix = varint.decode(buf, offset)
        offset += varint.decode.bytes
        var tag = prefix >> 3
        switch (tag) {
          case 1:
          var packedEnd = varint.decode(buf, offset)
          offset += varint.decode.bytes
          packedEnd += offset
          while (offset < packedEnd) {
            obj.keys.push(encodings.varint.decode(buf, offset))
            offset += encodings.varint.decode.bytes
          }
          break
          case 2:
          var packedEnd = varint.decode(buf, offset)
          offset += varint.decode.bytes
          packedEnd += offset
          while (offset < packedEnd) {
            obj.children.push(encodings.varint.decode(buf, offset))
            offset += encodings.varint.decode.bytes
          }
          break
          default:
          offset = skip(prefix & 7, buf, offset)
        }
      }
    }
  }

  YoloIndex.encodingLength = encodingLength
  YoloIndex.encode = encode
  YoloIndex.decode = decode

  function encodingLength (obj) {
    var length = 0
    if (defined(obj.levels)) {
      for (var i = 0; i < obj.levels.length; i++) {
        if (!defined(obj.levels[i])) continue
        var len = Level.encodingLength(obj.levels[i])
        length += varint.encodingLength(len)
        length += 1 + len
      }
    }
    return length
  }

  function encode (obj, buf, offset) {
    if (!offset) offset = 0
    if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
    var oldOffset = offset
    if (defined(obj.levels)) {
      for (var i = 0; i < obj.levels.length; i++) {
        if (!defined(obj.levels[i])) continue
        buf[offset++] = 10
        varint.encode(Level.encodingLength(obj.levels[i]), buf, offset)
        offset += varint.encode.bytes
        Level.encode(obj.levels[i], buf, offset)
        offset += Level.encode.bytes
      }
    }
    encode.bytes = offset - oldOffset
    return buf
  }

  function decode (buf, offset, end) {
    if (!offset) offset = 0
    if (!end) end = buf.length
    if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
    var oldOffset = offset
    var obj = {
      levels: []
    }
    while (true) {
      if (end <= offset) {
        decode.bytes = offset - oldOffset
        return obj
      }
      var prefix = varint.decode(buf, offset)
      offset += varint.decode.bytes
      var tag = prefix >> 3
      switch (tag) {
        case 1:
        var len = varint.decode(buf, offset)
        offset += varint.decode.bytes
        obj.levels.push(Level.decode(buf, offset, offset + len))
        offset += Level.decode.bytes
        break
        default:
        offset = skip(prefix & 7, buf, offset)
      }
    }
  }
}

function defineHeader () {
  var Metadata = Header.Metadata = {
    buffer: true,
    encodingLength: null,
    encode: null,
    decode: null
  }

  defineMetadata()

  function defineMetadata () {
    Metadata.encodingLength = encodingLength
    Metadata.encode = encode
    Metadata.decode = decode

    function encodingLength (obj) {
      var length = 0
      if (defined(obj.contentFeed)) {
        var len = encodings.bytes.encodingLength(obj.contentFeed)
        length += 1 + len
      }
      if (defined(obj.userData)) {
        var len = encodings.bytes.encodingLength(obj.userData)
        length += 1 + len
      }
      return length
    }

    function encode (obj, buf, offset) {
      if (!offset) offset = 0
      if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
      var oldOffset = offset
      if (defined(obj.contentFeed)) {
        buf[offset++] = 10
        encodings.bytes.encode(obj.contentFeed, buf, offset)
        offset += encodings.bytes.encode.bytes
      }
      if (defined(obj.userData)) {
        buf[offset++] = 18
        encodings.bytes.encode(obj.userData, buf, offset)
        offset += encodings.bytes.encode.bytes
      }
      encode.bytes = offset - oldOffset
      return buf
    }

    function decode (buf, offset, end) {
      if (!offset) offset = 0
      if (!end) end = buf.length
      if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
      var oldOffset = offset
      var obj = {
        contentFeed: null,
        userData: null
      }
      while (true) {
        if (end <= offset) {
          decode.bytes = offset - oldOffset
          return obj
        }
        var prefix = varint.decode(buf, offset)
        offset += varint.decode.bytes
        var tag = prefix >> 3
        switch (tag) {
          case 1:
          obj.contentFeed = encodings.bytes.decode(buf, offset)
          offset += encodings.bytes.decode.bytes
          break
          case 2:
          obj.userData = encodings.bytes.decode(buf, offset)
          offset += encodings.bytes.decode.bytes
          break
          default:
          offset = skip(prefix & 7, buf, offset)
        }
      }
    }
  }

  Header.encodingLength = encodingLength
  Header.encode = encode
  Header.decode = decode

  function encodingLength (obj) {
    var length = 0
    if (!defined(obj.protocol)) throw new Error("protocol is required")
    var len = encodings.string.encodingLength(obj.protocol)
    length += 1 + len
    if (defined(obj.metadata)) {
      var len = Metadata.encodingLength(obj.metadata)
      length += varint.encodingLength(len)
      length += 1 + len
    }
    return length
  }

  function encode (obj, buf, offset) {
    if (!offset) offset = 0
    if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
    var oldOffset = offset
    if (!defined(obj.protocol)) throw new Error("protocol is required")
    buf[offset++] = 10
    encodings.string.encode(obj.protocol, buf, offset)
    offset += encodings.string.encode.bytes
    if (defined(obj.metadata)) {
      buf[offset++] = 18
      varint.encode(Metadata.encodingLength(obj.metadata), buf, offset)
      offset += varint.encode.bytes
      Metadata.encode(obj.metadata, buf, offset)
      offset += Metadata.encode.bytes
    }
    encode.bytes = offset - oldOffset
    return buf
  }

  function decode (buf, offset, end) {
    if (!offset) offset = 0
    if (!end) end = buf.length
    if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
    var oldOffset = offset
    var obj = {
      protocol: "",
      metadata: null
    }
    var found0 = false
    while (true) {
      if (end <= offset) {
        if (!found0) throw new Error("Decoded message is not valid")
        decode.bytes = offset - oldOffset
        return obj
      }
      var prefix = varint.decode(buf, offset)
      offset += varint.decode.bytes
      var tag = prefix >> 3
      switch (tag) {
        case 1:
        obj.protocol = encodings.string.decode(buf, offset)
        offset += encodings.string.decode.bytes
        found0 = true
        break
        case 2:
        var len = varint.decode(buf, offset)
        offset += varint.decode.bytes
        obj.metadata = Metadata.decode(buf, offset, offset + len)
        offset += Metadata.decode.bytes
        break
        default:
        offset = skip(prefix & 7, buf, offset)
      }
    }
  }
}

function defineNode () {
  Node.encodingLength = encodingLength
  Node.encode = encode
  Node.decode = decode

  function encodingLength (obj) {
    var length = 0
    if (!defined(obj.index)) throw new Error("index is required")
    var len = encodings.bytes.encodingLength(obj.index)
    length += 1 + len
    if (!defined(obj.key)) throw new Error("key is required")
    var len = encodings.bytes.encodingLength(obj.key)
    length += 1 + len
    if (defined(obj.value)) {
      var len = encodings.bytes.encodingLength(obj.value)
      length += 1 + len
    }
    return length
  }

  function encode (obj, buf, offset) {
    if (!offset) offset = 0
    if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
    var oldOffset = offset
    if (!defined(obj.index)) throw new Error("index is required")
    buf[offset++] = 10
    encodings.bytes.encode(obj.index, buf, offset)
    offset += encodings.bytes.encode.bytes
    if (!defined(obj.key)) throw new Error("key is required")
    buf[offset++] = 18
    encodings.bytes.encode(obj.key, buf, offset)
    offset += encodings.bytes.encode.bytes
    if (defined(obj.value)) {
      buf[offset++] = 26
      encodings.bytes.encode(obj.value, buf, offset)
      offset += encodings.bytes.encode.bytes
    }
    encode.bytes = offset - oldOffset
    return buf
  }

  function decode (buf, offset, end) {
    if (!offset) offset = 0
    if (!end) end = buf.length
    if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
    var oldOffset = offset
    var obj = {
      index: null,
      key: null,
      value: null
    }
    var found0 = false
    var found1 = false
    while (true) {
      if (end <= offset) {
        if (!found0 || !found1) throw new Error("Decoded message is not valid")
        decode.bytes = offset - oldOffset
        return obj
      }
      var prefix = varint.decode(buf, offset)
      offset += varint.decode.bytes
      var tag = prefix >> 3
      switch (tag) {
        case 1:
        obj.index = encodings.bytes.decode(buf, offset)
        offset += encodings.bytes.decode.bytes
        found0 = true
        break
        case 2:
        obj.key = encodings.bytes.decode(buf, offset)
        offset += encodings.bytes.decode.bytes
        found1 = true
        break
        case 3:
        obj.value = encodings.bytes.decode(buf, offset)
        offset += encodings.bytes.decode.bytes
        break
        default:
        offset = skip(prefix & 7, buf, offset)
      }
    }
  }
}

function defineExtension () {
  var Get = Extension.Get = {
    buffer: true,
    encodingLength: null,
    encode: null,
    decode: null
  }

  var Iterator = Extension.Iterator = {
    buffer: true,
    encodingLength: null,
    encode: null,
    decode: null
  }

  var Cache = Extension.Cache = {
    buffer: true,
    encodingLength: null,
    encode: null,
    decode: null
  }

  defineGet()
  defineIterator()
  defineCache()

  function defineGet () {
    Get.encodingLength = encodingLength
    Get.encode = encode
    Get.decode = decode

    function encodingLength (obj) {
      var length = 0
      if (defined(obj.version)) {
        var len = encodings.varint.encodingLength(obj.version)
        length += 1 + len
      }
      if (defined(obj.key)) {
        var len = encodings.bytes.encodingLength(obj.key)
        length += 1 + len
      }
      return length
    }

    function encode (obj, buf, offset) {
      if (!offset) offset = 0
      if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
      var oldOffset = offset
      if (defined(obj.version)) {
        buf[offset++] = 8
        encodings.varint.encode(obj.version, buf, offset)
        offset += encodings.varint.encode.bytes
      }
      if (defined(obj.key)) {
        buf[offset++] = 18
        encodings.bytes.encode(obj.key, buf, offset)
        offset += encodings.bytes.encode.bytes
      }
      encode.bytes = offset - oldOffset
      return buf
    }

    function decode (buf, offset, end) {
      if (!offset) offset = 0
      if (!end) end = buf.length
      if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
      var oldOffset = offset
      var obj = {
        version: 0,
        key: null
      }
      while (true) {
        if (end <= offset) {
          decode.bytes = offset - oldOffset
          return obj
        }
        var prefix = varint.decode(buf, offset)
        offset += varint.decode.bytes
        var tag = prefix >> 3
        switch (tag) {
          case 1:
          obj.version = encodings.varint.decode(buf, offset)
          offset += encodings.varint.decode.bytes
          break
          case 2:
          obj.key = encodings.bytes.decode(buf, offset)
          offset += encodings.bytes.decode.bytes
          break
          default:
          offset = skip(prefix & 7, buf, offset)
        }
      }
    }
  }

  function defineIterator () {
    Iterator.encodingLength = encodingLength
    Iterator.encode = encode
    Iterator.decode = decode

    function encodingLength (obj) {
      var length = 0
      if (defined(obj.version)) {
        var len = encodings.varint.encodingLength(obj.version)
        length += 1 + len
      }
      if (defined(obj.gte)) {
        var len = encodings.bytes.encodingLength(obj.gte)
        length += 1 + len
      }
      if (defined(obj.gt)) {
        var len = encodings.bytes.encodingLength(obj.gt)
        length += 1 + len
      }
      if (defined(obj.lte)) {
        var len = encodings.bytes.encodingLength(obj.lte)
        length += 1 + len
      }
      if (defined(obj.lt)) {
        var len = encodings.bytes.encodingLength(obj.lt)
        length += 1 + len
      }
      if (defined(obj.limit)) {
        var len = encodings.varint.encodingLength(obj.limit)
        length += 1 + len
      }
      if (defined(obj.reverse)) {
        var len = encodings.bool.encodingLength(obj.reverse)
        length += 1 + len
      }
      if (defined(obj.checkpoint)) {
        var packedLen = 0
        for (var i = 0; i < obj.checkpoint.length; i++) {
          if (!defined(obj.checkpoint[i])) continue
          var len = encodings.varint.encodingLength(obj.checkpoint[i])
          packedLen += len
        }
        if (packedLen) {
          length += 1 + packedLen + varint.encodingLength(packedLen)
        }
      }
      return length
    }

    function encode (obj, buf, offset) {
      if (!offset) offset = 0
      if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
      var oldOffset = offset
      if (defined(obj.version)) {
        buf[offset++] = 8
        encodings.varint.encode(obj.version, buf, offset)
        offset += encodings.varint.encode.bytes
      }
      if (defined(obj.gte)) {
        buf[offset++] = 18
        encodings.bytes.encode(obj.gte, buf, offset)
        offset += encodings.bytes.encode.bytes
      }
      if (defined(obj.gt)) {
        buf[offset++] = 26
        encodings.bytes.encode(obj.gt, buf, offset)
        offset += encodings.bytes.encode.bytes
      }
      if (defined(obj.lte)) {
        buf[offset++] = 34
        encodings.bytes.encode(obj.lte, buf, offset)
        offset += encodings.bytes.encode.bytes
      }
      if (defined(obj.lt)) {
        buf[offset++] = 42
        encodings.bytes.encode(obj.lt, buf, offset)
        offset += encodings.bytes.encode.bytes
      }
      if (defined(obj.limit)) {
        buf[offset++] = 48
        encodings.varint.encode(obj.limit, buf, offset)
        offset += encodings.varint.encode.bytes
      }
      if (defined(obj.reverse)) {
        buf[offset++] = 56
        encodings.bool.encode(obj.reverse, buf, offset)
        offset += encodings.bool.encode.bytes
      }
      if (defined(obj.checkpoint)) {
        var packedLen = 0
        for (var i = 0; i < obj.checkpoint.length; i++) {
          if (!defined(obj.checkpoint[i])) continue
          packedLen += encodings.varint.encodingLength(obj.checkpoint[i])
        }
        if (packedLen) {
          buf[offset++] = 66
          varint.encode(packedLen, buf, offset)
          offset += varint.encode.bytes
        }
        for (var i = 0; i < obj.checkpoint.length; i++) {
          if (!defined(obj.checkpoint[i])) continue
          encodings.varint.encode(obj.checkpoint[i], buf, offset)
          offset += encodings.varint.encode.bytes
        }
      }
      encode.bytes = offset - oldOffset
      return buf
    }

    function decode (buf, offset, end) {
      if (!offset) offset = 0
      if (!end) end = buf.length
      if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
      var oldOffset = offset
      var obj = {
        version: 0,
        gte: null,
        gt: null,
        lte: null,
        lt: null,
        limit: 0,
        reverse: false,
        checkpoint: []
      }
      while (true) {
        if (end <= offset) {
          decode.bytes = offset - oldOffset
          return obj
        }
        var prefix = varint.decode(buf, offset)
        offset += varint.decode.bytes
        var tag = prefix >> 3
        switch (tag) {
          case 1:
          obj.version = encodings.varint.decode(buf, offset)
          offset += encodings.varint.decode.bytes
          break
          case 2:
          obj.gte = encodings.bytes.decode(buf, offset)
          offset += encodings.bytes.decode.bytes
          break
          case 3:
          obj.gt = encodings.bytes.decode(buf, offset)
          offset += encodings.bytes.decode.bytes
          break
          case 4:
          obj.lte = encodings.bytes.decode(buf, offset)
          offset += encodings.bytes.decode.bytes
          break
          case 5:
          obj.lt = encodings.bytes.decode(buf, offset)
          offset += encodings.bytes.decode.bytes
          break
          case 6:
          obj.limit = encodings.varint.decode(buf, offset)
          offset += encodings.varint.decode.bytes
          break
          case 7:
          obj.reverse = encodings.bool.decode(buf, offset)
          offset += encodings.bool.decode.bytes
          break
          case 8:
          var packedEnd = varint.decode(buf, offset)
          offset += varint.decode.bytes
          packedEnd += offset
          while (offset < packedEnd) {
            obj.checkpoint.push(encodings.varint.decode(buf, offset))
            offset += encodings.varint.decode.bytes
          }
          break
          default:
          offset = skip(prefix & 7, buf, offset)
        }
      }
    }
  }

  function defineCache () {
    Cache.encodingLength = encodingLength
    Cache.encode = encode
    Cache.decode = decode

    function encodingLength (obj) {
      var length = 0
      if (!defined(obj.start)) throw new Error("start is required")
      var len = encodings.varint.encodingLength(obj.start)
      length += 1 + len
      if (!defined(obj.end)) throw new Error("end is required")
      var len = encodings.varint.encodingLength(obj.end)
      length += 1 + len
      if (defined(obj.blocks)) {
        var packedLen = 0
        for (var i = 0; i < obj.blocks.length; i++) {
          if (!defined(obj.blocks[i])) continue
          var len = encodings.varint.encodingLength(obj.blocks[i])
          packedLen += len
        }
        if (packedLen) {
          length += 1 + packedLen + varint.encodingLength(packedLen)
        }
      }
      return length
    }

    function encode (obj, buf, offset) {
      if (!offset) offset = 0
      if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
      var oldOffset = offset
      if (!defined(obj.start)) throw new Error("start is required")
      buf[offset++] = 8
      encodings.varint.encode(obj.start, buf, offset)
      offset += encodings.varint.encode.bytes
      if (!defined(obj.end)) throw new Error("end is required")
      buf[offset++] = 16
      encodings.varint.encode(obj.end, buf, offset)
      offset += encodings.varint.encode.bytes
      if (defined(obj.blocks)) {
        var packedLen = 0
        for (var i = 0; i < obj.blocks.length; i++) {
          if (!defined(obj.blocks[i])) continue
          packedLen += encodings.varint.encodingLength(obj.blocks[i])
        }
        if (packedLen) {
          buf[offset++] = 26
          varint.encode(packedLen, buf, offset)
          offset += varint.encode.bytes
        }
        for (var i = 0; i < obj.blocks.length; i++) {
          if (!defined(obj.blocks[i])) continue
          encodings.varint.encode(obj.blocks[i], buf, offset)
          offset += encodings.varint.encode.bytes
        }
      }
      encode.bytes = offset - oldOffset
      return buf
    }

    function decode (buf, offset, end) {
      if (!offset) offset = 0
      if (!end) end = buf.length
      if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
      var oldOffset = offset
      var obj = {
        start: 0,
        end: 0,
        blocks: []
      }
      var found0 = false
      var found1 = false
      while (true) {
        if (end <= offset) {
          if (!found0 || !found1) throw new Error("Decoded message is not valid")
          decode.bytes = offset - oldOffset
          return obj
        }
        var prefix = varint.decode(buf, offset)
        offset += varint.decode.bytes
        var tag = prefix >> 3
        switch (tag) {
          case 1:
          obj.start = encodings.varint.decode(buf, offset)
          offset += encodings.varint.decode.bytes
          found0 = true
          break
          case 2:
          obj.end = encodings.varint.decode(buf, offset)
          offset += encodings.varint.decode.bytes
          found1 = true
          break
          case 3:
          var packedEnd = varint.decode(buf, offset)
          offset += varint.decode.bytes
          packedEnd += offset
          while (offset < packedEnd) {
            obj.blocks.push(encodings.varint.decode(buf, offset))
            offset += encodings.varint.decode.bytes
          }
          break
          default:
          offset = skip(prefix & 7, buf, offset)
        }
      }
    }
  }

  Extension.encodingLength = encodingLength
  Extension.encode = encode
  Extension.decode = decode

  function encodingLength (obj) {
    var length = 0
    if (defined(obj.cache)) {
      var len = Cache.encodingLength(obj.cache)
      length += varint.encodingLength(len)
      length += 1 + len
    }
    if (defined(obj.get)) {
      var len = Get.encodingLength(obj.get)
      length += varint.encodingLength(len)
      length += 1 + len
    }
    if (defined(obj.iterator)) {
      var len = Iterator.encodingLength(obj.iterator)
      length += varint.encodingLength(len)
      length += 1 + len
    }
    return length
  }

  function encode (obj, buf, offset) {
    if (!offset) offset = 0
    if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
    var oldOffset = offset
    if (defined(obj.cache)) {
      buf[offset++] = 10
      varint.encode(Cache.encodingLength(obj.cache), buf, offset)
      offset += varint.encode.bytes
      Cache.encode(obj.cache, buf, offset)
      offset += Cache.encode.bytes
    }
    if (defined(obj.get)) {
      buf[offset++] = 18
      varint.encode(Get.encodingLength(obj.get), buf, offset)
      offset += varint.encode.bytes
      Get.encode(obj.get, buf, offset)
      offset += Get.encode.bytes
    }
    if (defined(obj.iterator)) {
      buf[offset++] = 26
      varint.encode(Iterator.encodingLength(obj.iterator), buf, offset)
      offset += varint.encode.bytes
      Iterator.encode(obj.iterator, buf, offset)
      offset += Iterator.encode.bytes
    }
    encode.bytes = offset - oldOffset
    return buf
  }

  function decode (buf, offset, end) {
    if (!offset) offset = 0
    if (!end) end = buf.length
    if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
    var oldOffset = offset
    var obj = {
      cache: null,
      get: null,
      iterator: null
    }
    while (true) {
      if (end <= offset) {
        decode.bytes = offset - oldOffset
        return obj
      }
      var prefix = varint.decode(buf, offset)
      offset += varint.decode.bytes
      var tag = prefix >> 3
      switch (tag) {
        case 1:
        var len = varint.decode(buf, offset)
        offset += varint.decode.bytes
        obj.cache = Cache.decode(buf, offset, offset + len)
        offset += Cache.decode.bytes
        break
        case 2:
        var len = varint.decode(buf, offset)
        offset += varint.decode.bytes
        obj.get = Get.decode(buf, offset, offset + len)
        offset += Get.decode.bytes
        break
        case 3:
        var len = varint.decode(buf, offset)
        offset += varint.decode.bytes
        obj.iterator = Iterator.decode(buf, offset, offset + len)
        offset += Iterator.decode.bytes
        break
        default:
        offset = skip(prefix & 7, buf, offset)
      }
    }
  }
}

function defined (val) {
  return val !== null && val !== undefined && (typeof val !== 'number' || !isNaN(val))
}
{
  "name": "hyperbee",
  "version": "2.27.3",
  "description": "An append-only B-tree running on a Hypercore.",
  "main": "index.js",
  "files": [
    "index.js",
    "lib/**.js",
    "iterators/**.js"
  ],
  "dependencies": {
    "b4a": "^1.6.0",
    "codecs": "^3.0.0",
    "debounceify": "^1.0.0",
    "hypercore-errors": "^1.0.0",
    "mutexify": "^1.4.0",
    "protocol-buffers-encodings": "^1.2.0",
    "rache": "^1.0.0",
    "ready-resource": "^1.0.0",
    "resolve-reject-promise": "^1.1.0",
    "safety-catch": "^1.0.2",
    "streamx": "^2.12.4",
    "unslab": "^1.2.0"
  },
  "devDependencies": {
    "bare-process": "^4.2.2",
    "brittle": "^3.1.0",
    "hypercore": "^11.0.0",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "protocol-buffers": "^4.2.0",
    "sub-encoder": "^1.0.6",
    "tree-to-string": "^1.1.1"
  },
  "imports": {
    "process": {
      "bare": "bare-process",
      "default": "process"
    }
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test/*.js",
    "test:bare": "brittle-bare test/*.js",
    "protobuf": "protocol-buffers schema.proto -o ./lib/messages.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/hyperbee.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/hyperbee/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperbee"
}
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const b4a = require('b4a')

// https://en.wikipedia.org/wiki/Merkle_tree#Second_preimage_attack
const LEAF_TYPE = b4a.from([0])
const PARENT_TYPE = b4a.from([1])
const ROOT_TYPE = b4a.from([2])

const HYPERCORE = b4a.from('hypercore')

exports.keyPair = function (seed) {
  // key pairs might stay around for a while, so better not to use a default slab to avoid retaining it completely
  const slab = b4a.allocUnsafeSlow(
    sodium.crypto_sign_PUBLICKEYBYTES + sodium.crypto_sign_SECRETKEYBYTES
  )
  const publicKey = slab.subarray(0, sodium.crypto_sign_PUBLICKEYBYTES)
  const secretKey = slab.subarray(sodium.crypto_sign_PUBLICKEYBYTES)

  if (seed) sodium.crypto_sign_seed_keypair(publicKey, secretKey, seed)
  else sodium.crypto_sign_keypair(publicKey, secretKey)

  return {
    publicKey,
    secretKey
  }
}

exports.validateKeyPair = function (keyPair) {
  const pk = b4a.allocUnsafe(sodium.crypto_sign_PUBLICKEYBYTES)
  sodium.crypto_sign_ed25519_sk_to_pk(pk, keyPair.secretKey)
  return b4a.equals(pk, keyPair.publicKey)
}

exports.sign = function (message, secretKey) {
  // Dedicated slab for the signature, to avoid retaining unneeded mem and for security
  const signature = b4a.allocUnsafeSlow(sodium.crypto_sign_BYTES)
  sodium.crypto_sign_detached(signature, message, secretKey)
  return signature
}

exports.verify = function (message, signature, publicKey) {
  if (signature.byteLength !== sodium.crypto_sign_BYTES) return false
  if (publicKey.byteLength !== sodium.crypto_sign_PUBLICKEYBYTES) return false
  return sodium.crypto_sign_verify_detached(signature, message, publicKey)
}

exports.encrypt = function (message, publicKey) {
  const ciphertext = b4a.alloc(message.byteLength + sodium.crypto_box_SEALBYTES)
  sodium.crypto_box_seal(ciphertext, message, publicKey)
  return ciphertext
}

exports.decrypt = function (ciphertext, keyPair) {
  if (ciphertext.byteLength < sodium.crypto_box_SEALBYTES) return null

  const plaintext = b4a.alloc(ciphertext.byteLength - sodium.crypto_box_SEALBYTES)

  if (!sodium.crypto_box_seal_open(plaintext, ciphertext, keyPair.publicKey, keyPair.secretKey)) {
    return null
  }

  return plaintext
}

exports.encryptionKeyPair = function (seed) {
  const publicKey = b4a.alloc(sodium.crypto_box_PUBLICKEYBYTES)
  const secretKey = b4a.alloc(sodium.crypto_box_SECRETKEYBYTES)

  if (seed) {
    sodium.crypto_box_seed_keypair(publicKey, secretKey, seed)
  } else {
    sodium.crypto_box_keypair(publicKey, secretKey)
  }

  return {
    publicKey,
    secretKey
  }
}

exports.data = function (data) {
  const out = b4a.allocUnsafe(32)

  sodium.crypto_generichash_batch(out, [LEAF_TYPE, c.encode(c.uint64, data.byteLength), data])

  return out
}

exports.parent = function (a, b) {
  if (a.index > b.index) {
    const tmp = a
    a = b
    b = tmp
  }

  const out = b4a.allocUnsafe(32)

  sodium.crypto_generichash_batch(out, [
    PARENT_TYPE,
    c.encode(c.uint64, a.size + b.size),
    a.hash,
    b.hash
  ])

  return out
}

exports.tree = function (roots, out) {
  const buffers = new Array(3 * roots.length + 1)
  let j = 0

  buffers[j++] = ROOT_TYPE

  for (let i = 0; i < roots.length; i++) {
    const r = roots[i]
    buffers[j++] = r.hash
    buffers[j++] = c.encode(c.uint64, r.index)
    buffers[j++] = c.encode(c.uint64, r.size)
  }

  if (!out) out = b4a.allocUnsafe(32)
  sodium.crypto_generichash_batch(out, buffers)
  return out
}

exports.hash = function (data, out) {
  if (!out) out = b4a.allocUnsafe(32)
  if (!Array.isArray(data)) data = [data]

  sodium.crypto_generichash_batch(out, data)

  return out
}

exports.randomBytes = function (n) {
  const buf = b4a.allocUnsafe(n)
  sodium.randombytes_buf(buf)
  return buf
}

exports.discoveryKey = function (key) {
  if (!key || key.byteLength !== 32) throw new Error('Must pass a 32 byte buffer')
  // Discovery keys might stay around for a while, so better not to use slab memory (for better gc)
  const digest = b4a.allocUnsafeSlow(32)
  sodium.crypto_generichash(digest, HYPERCORE, key)
  return digest
}

if (sodium.sodium_free) {
  exports.free = function (secureBuf) {
    if (secureBuf.secure) sodium.sodium_free(secureBuf)
  }
} else {
  exports.free = function () {}
}

exports.namespace = function (name, count) {
  const ids = typeof count === 'number' ? range(count) : count

  // Namespaces are long-lived, so better to use a dedicated slab
  const buf = b4a.allocUnsafeSlow(32 * ids.length)

  const list = new Array(ids.length)

  // ns is ephemeral, so default slab
  const ns = b4a.allocUnsafe(33)
  sodium.crypto_generichash(ns.subarray(0, 32), typeof name === 'string' ? b4a.from(name) : name)

  for (let i = 0; i < list.length; i++) {
    list[i] = buf.subarray(32 * i, 32 * i + 32)
    ns[32] = ids[i]
    sodium.crypto_generichash(list[i], ns)
  }

  return list
}

function range(count) {
  const arr = new Array(count)
  for (let i = 0; i < count; i++) arr[i] = i
  return arr
}
{
  "name": "hypercore-crypto",
  "version": "3.7.0",
  "description": "The crypto primitives used in hypercore, extracted into a separate module",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.6.6",
    "compact-encoding": "^3.0.0",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "brittle": "^3.5.0",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/hypercore-crypto.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/hypercore-crypto/issues"
  },
  "homepage": "https://github.com/mafintosh/hypercore-crypto"
}
const IdEnc = require('hypercore-id-encoding')

module.exports = class HypercoreError extends Error {
  constructor (msg, code, fn = HypercoreError, discoveryKey = null) {
    if (discoveryKey) msg = `${msg} (discovery key: ${IdEnc.normalize(discoveryKey)})`
    super(`${code}: ${msg}`)

    this.code = code
    this.discoveryKey = discoveryKey

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name () {
    return 'HypercoreError'
  }

  static ASSERTION (msg, discoveryKey = null) { // ERR_ASSERTION is picked up by safety-catch also
    return new HypercoreError(msg, 'ERR_ASSERTION', HypercoreError.ASSERT, discoveryKey)
  }

  static BAD_ARGUMENT (msg, discoveryKey = null) {
    return new HypercoreError(msg, 'BAD_ARGUMENT', HypercoreError.BAD_ARGUMENT, discoveryKey)
  }

  static STORAGE_EMPTY (msg, discoveryKey = null) {
    return new HypercoreError(msg, 'STORAGE_EMPTY', HypercoreError.STORAGE_EMPTY, discoveryKey)
  }

  static STORAGE_CONFLICT (msg, discoveryKey = null) {
    return new HypercoreError(msg, 'STORAGE_CONFLICT', HypercoreError.STORAGE_CONFLICT, discoveryKey)
  }

  static INVALID_SIGNATURE (msg, discoveryKey = null) {
    return new HypercoreError(msg, 'INVALID_SIGNATURE', HypercoreError.INVALID_SIGNATURE, discoveryKey)
  }

  static INVALID_CAPABILITY (msg, discoveryKey = null) {
    return new HypercoreError(msg, 'INVALID_CAPABILITY', HypercoreError.INVALID_CAPABILITY, discoveryKey)
  }

  static INVALID_CHECKSUM (msg = 'Invalid checksum', discoveryKey = null) {
    return new HypercoreError(msg, 'INVALID_CHECKSUM', HypercoreError.INVALID_CHECKSUM, discoveryKey)
  }

  static INVALID_OPERATION (msg, discoveryKey = null) {
    return new HypercoreError(msg, 'INVALID_OPERATION', HypercoreError.INVALID_OPERATION, discoveryKey)
  }

  static INVALID_PROOF (msg = 'Proof not verifiable', discoveryKey = null) {
    return new HypercoreError(msg, 'INVALID_PROOF', HypercoreError.INVALID_PROOF, discoveryKey)
  }

  static BLOCK_NOT_AVAILABLE (msg = 'Block is not available', discoveryKey = null) {
    return new HypercoreError(msg, 'BLOCK_NOT_AVAILABLE', HypercoreError.BLOCK_NOT_AVAILABLE, discoveryKey)
  }

  static SNAPSHOT_NOT_AVAILABLE (msg = 'Snapshot is not available', discoveryKey = null) {
    return new HypercoreError(msg, 'SNAPSHOT_NOT_AVAILABLE', HypercoreError.SNAPSHOT_NOT_AVAILABLE, discoveryKey)
  }

  static REQUEST_CANCELLED (msg = 'Request was cancelled', discoveryKey = null) {
    return new HypercoreError(msg, 'REQUEST_CANCELLED', HypercoreError.REQUEST_CANCELLED, discoveryKey)
  }

  static REQUEST_TIMEOUT (msg = 'Request timed out', discoveryKey = null) {
    return new HypercoreError(msg, 'REQUEST_TIMEOUT', HypercoreError.REQUEST_TIMEOUT, discoveryKey)
  }

  static SESSION_NOT_WRITABLE (msg = 'Session is not writable', discoveryKey = null) {
    return new HypercoreError(msg, 'SESSION_NOT_WRITABLE', HypercoreError.SESSION_NOT_WRITABLE, discoveryKey)
  }

  static SESSION_CLOSED (msg = 'Session is closed', discoveryKey = null) {
    return new HypercoreError(msg, 'SESSION_CLOSED', HypercoreError.SESSION_CLOSED, discoveryKey)
  }

  static BATCH_UNFLUSHED (msg = 'Batch not yet flushed', discoveryKey = null) {
    return new HypercoreError(msg, 'BATCH_UNFLUSHED', HypercoreError.BATCH_UNFLUSHED, discoveryKey)
  }

  static BATCH_ALREADY_EXISTS (msg = 'Batch already exists', discoveryKey = null) {
    return new HypercoreError(msg, 'BATCH_ALREADY_EXISTS', HypercoreError.BATCH_ALREADY_EXISTS, discoveryKey)
  }

  static BATCH_ALREADY_FLUSHED (msg = 'Batch has already been flushed', discoveryKey = null) {
    return new HypercoreError(msg, 'BATCH_ALREADY_FLUSHED', HypercoreError.BATCH_ALREADY_FLUSHED, discoveryKey)
  }

  static OPLOG_CORRUPT (msg = 'Oplog file appears corrupt or out of date', discoveryKey = null) {
    return new HypercoreError(msg, 'OPLOG_CORRUPT', HypercoreError.OPLOG_CORRUPT, discoveryKey)
  }

  static OPLOG_HEADER_OVERFLOW (msg = 'Oplog header exceeds page size', discoveryKey = null) {
    return new HypercoreError(msg, 'OPLOG_HEADER_OVERFLOW', HypercoreError.OPLOG_HEADER_OVERFLOW, discoveryKey)
  }

  static INVALID_OPLOG_VERSION (msg = 'Invalid header version', discoveryKey = null) {
    return new HypercoreError(msg, 'INVALID_OPLOG_VERSION', HypercoreError.INVALID_OPLOG_VERSION, discoveryKey)
  }

  static WRITE_FAILED (msg = 'Write to storage failed', discoveryKey = null) {
    return new HypercoreError(msg, 'WRITE_FAILED', HypercoreError.WRITE_FAILED, discoveryKey)
  }

  static DECODING_ERROR (msg = 'Decoding error', discoveryKey = null) {
    return new HypercoreError(msg, 'DECODING_ERROR', HypercoreError.DECODING_ERROR, discoveryKey)
  }

  static SESSION_MOVED (msg = 'Session moved', discoveryKey = null) {
    return new HypercoreError(msg, 'SESSION_MOVED', HypercoreError.SESSION_MOVED, discoveryKey)
  }
}
{
  "name": "hypercore-errors",
  "version": "1.5.0",
  "description": "Hypercore errors",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/hypercore-errors.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/hypercore-errors/issues"
  },
  "homepage": "https://github.com/holepunchto/hypercore-errors#readme",
  "devDependencies": {
    "b4a": "^1.6.7",
    "brittle": "^3.1.3",
    "standard": "^17.0.0"
  },
  "dependencies": {
    "hypercore-id-encoding": "^1.3.0"
  }
}
const z32 = require('z32')
const b4a = require('b4a')

module.exports = {
  encode,
  decode,
  normalize,
  isValid
}

function encode (key) {
  if (!b4a.isBuffer(key)) throw new Error('Key must be a Buffer')
  if (key.byteLength !== 32) throw new Error('Key must be 32-bytes long')
  return z32.encode(key)
}

function decode (id) {
  if (b4a.isBuffer(id)) {
    if (id.byteLength !== 32) throw new Error('ID must be 32-bytes long')
    return id
  }
  if (typeof id === 'string') {
    if (id.startsWith('pear://')) id = id.slice(7).split('/')[0]
    if (id.length === 52) return z32.decode(id)
    if (id.length === 64) {
      const buf = b4a.from(id, 'hex')
      if (buf.byteLength === 32) return buf
    }
  }
  throw new Error('Invalid Hypercore key')
}

function normalize (any) {
  return encode(decode(any))
}

function isValid (any) {
  try {
    decode(any)
    return true
  } catch {
    return false
  }
}
{
  "name": "hypercore-id-encoding",
  "version": "1.3.0",
  "description": "Convert Hypercore keys to/from z-base32 or hex",
  "main": "index.js",
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.5.3",
    "z32": "^1.0.0"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "hypercore": "^10.0.0",
    "random-access-memory": "^6.0.0",
    "standard": "^17.1.0"
  },
  "license": "Apache-2.0",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/hypercore-id-encoding.git"
  },
  "keywords": [],
  "author": "",
  "bugs": {
    "url": "https://github.com/holepunchto/hypercore-id-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/hypercore-id-encoding#readme"
}
function headLegacyMap(m) {
  return {
    version: 2, // version bumped from 1
    cores: m.allocated.cores,
    datas: m.allocated.datas,
    groups: 0,
    seed: m.seed,
    defaultDiscoveryKey: m.defaultDiscoveryKey
  }
}

module.exports = {
  headLegacyMap
}
// This file is autogenerated by the hyperschema compiler
// Schema Version: 2
/* eslint-disable camelcase */
/* eslint-disable quotes */
/* eslint-disable space-before-function-paren */

const { c } = require('hyperschema/runtime')
const external0 = require('../../external.js')

const VERSION = 2

// eslint-disable-next-line no-unused-vars
let version = VERSION

// @corestore/allocated
const encoding0 = {
  preencode(state, m) {
    c.uint.preencode(state, m.cores)
    c.uint.preencode(state, m.datas)
  },
  encode(state, m) {
    c.uint.encode(state, m.cores)
    c.uint.encode(state, m.datas)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const r1 = c.uint.decode(state)

    return {
      cores: r0,
      datas: r1
    }
  }
}

// @corestore/head-v1
const encoding1 = {
  preencode(state, m) {
    state.end++ // max flag is 4 so always one byte

    if (m.allocated) encoding0.preencode(state, m.allocated)
    if (m.seed) c.fixed32.preencode(state, m.seed)
    if (m.defaultDiscoveryKey) c.fixed32.preencode(state, m.defaultDiscoveryKey)
  },
  encode(state, m) {
    const flags = (m.allocated ? 1 : 0) | (m.seed ? 2 : 0) | (m.defaultDiscoveryKey ? 4 : 0)

    c.uint.encode(state, flags)

    if (m.allocated) encoding0.encode(state, m.allocated)
    if (m.seed) c.fixed32.encode(state, m.seed)
    if (m.defaultDiscoveryKey) c.fixed32.encode(state, m.defaultDiscoveryKey)
  },
  decode(state) {
    const v = c.uint.decode(state)
    const flags = c.uint.decode(state)

    return {
      version: v,
      allocated: (flags & 1) !== 0 ? encoding0.decode(state) : null,
      seed: (flags & 2) !== 0 ? c.fixed32.decode(state) : null,
      defaultDiscoveryKey: (flags & 4) !== 0 ? c.fixed32.decode(state) : null
    }
  }
}

// @corestore/head-v2
const encoding2 = {
  preencode(state, m) {
    c.uint.preencode(state, m.cores)
    c.uint.preencode(state, m.datas)
    c.uint.preencode(state, m.groups)
    state.end++ // max flag is 2 so always one byte

    if (m.seed) c.fixed32.preencode(state, m.seed)
    if (m.defaultDiscoveryKey) c.fixed32.preencode(state, m.defaultDiscoveryKey)
  },
  encode(state, m) {
    const flags = (m.seed ? 1 : 0) | (m.defaultDiscoveryKey ? 2 : 0)

    c.uint.encode(state, m.cores)
    c.uint.encode(state, m.datas)
    c.uint.encode(state, m.groups)
    c.uint.encode(state, flags)

    if (m.seed) c.fixed32.encode(state, m.seed)
    if (m.defaultDiscoveryKey) c.fixed32.encode(state, m.defaultDiscoveryKey)
  },
  decode(state) {
    const v = c.uint.decode(state)
    const r0 = c.uint.decode(state)
    const r1 = c.uint.decode(state)
    const r2 = c.uint.decode(state)
    const flags = c.uint.decode(state)

    return {
      version: v,
      cores: r0,
      datas: r1,
      groups: r2,
      seed: (flags & 1) !== 0 ? c.fixed32.decode(state) : null,
      defaultDiscoveryKey: (flags & 2) !== 0 ? c.fixed32.decode(state) : null
    }
  }
}

// @corestore/head
const encoding3 = {
  preencode(state, m) {
    c.uint.preencode(state, m.version)
    switch (m.version) {
      case 0:
      case 1:
        encoding1.preencode(state, m)
        break
      case 2:
        encoding2.preencode(state, m)
        break
      default:
        throw new Error('Unsupported version')
    }
  },
  encode(state, m) {
    c.uint.encode(state, m.version)
    switch (m.version) {
      case 0:
      case 1:
        encoding1.encode(state, m)
        break
      case 2:
        encoding2.encode(state, m)
        break
      default:
        throw new Error('Unsupported version')
    }
  },
  decode(state) {
    const start = state.start
    const v = c.uint.decode(state)
    state.start = start
    switch (v) {
      case 0:
      case 1: {
        const decoded = encoding1.decode(state)
        const map = external0.headLegacyMap
        return map(decoded)
      }
      case 2: {
        const decoded = encoding2.decode(state)
        return decoded
      }
      default:
        throw new Error('Unsupported version')
    }
  }
}

// @corestore/alias
const encoding4 = {
  preencode(state, m) {
    c.string.preencode(state, m.name)
    c.fixed32.preencode(state, m.namespace)
  },
  encode(state, m) {
    c.string.encode(state, m.name)
    c.fixed32.encode(state, m.namespace)
  },
  decode(state) {
    const r0 = c.string.decode(state)
    const r1 = c.fixed32.decode(state)

    return {
      name: r0,
      namespace: r1
    }
  }
}

// @corestore/core
const encoding5 = {
  preencode(state, m) {
    c.uint.preencode(state, m.version)
    c.uint.preencode(state, m.corePointer)
    c.uint.preencode(state, m.dataPointer)
    state.end++ // max flag is 1 so always one byte

    if (m.alias) encoding4.preencode(state, m.alias)
  },
  encode(state, m) {
    const flags = m.alias ? 1 : 0

    c.uint.encode(state, m.version)
    c.uint.encode(state, m.corePointer)
    c.uint.encode(state, m.dataPointer)
    c.uint.encode(state, flags)

    if (m.alias) encoding4.encode(state, m.alias)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const r1 = c.uint.decode(state)
    const r2 = c.uint.decode(state)
    const flags = c.uint.decode(state)

    return {
      version: r0,
      corePointer: r1,
      dataPointer: r2,
      alias: (flags & 1) !== 0 ? encoding4.decode(state) : null
    }
  }
}

const encoding6_enum = {
  blake2b: 'blake2b'
}

// @core/hashes enum
const encoding6 = {
  preencode(state, m) {
    state.end++ // max enum is 0 so always one byte
  },
  encode(state, m) {
    switch (m) {
      case 'blake2b':
        c.uint.encode(state, 0)
        break
      default:
        throw new Error('Unknown enum')
    }
  },
  decode(state) {
    switch (c.uint.decode(state)) {
      case 0:
        return 'blake2b'
      default:
        return null
    }
  }
}

const encoding7_enum = {
  ed25519: 'ed25519'
}

// @core/signatures enum
const encoding7 = {
  preencode(state, m) {
    state.end++ // max enum is 0 so always one byte
  },
  encode(state, m) {
    switch (m) {
      case 'ed25519':
        c.uint.encode(state, 0)
        break
      default:
        throw new Error('Unknown enum')
    }
  },
  decode(state) {
    switch (c.uint.decode(state)) {
      case 0:
        return 'ed25519'
      default:
        return null
    }
  }
}

// @core/tree-node
const encoding8 = {
  preencode(state, m) {
    c.uint.preencode(state, m.index)
    c.uint.preencode(state, m.size)
    c.fixed32.preencode(state, m.hash)
  },
  encode(state, m) {
    c.uint.encode(state, m.index)
    c.uint.encode(state, m.size)
    c.fixed32.encode(state, m.hash)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const r1 = c.uint.decode(state)
    const r2 = c.fixed32.decode(state)

    return {
      index: r0,
      size: r1,
      hash: r2
    }
  }
}

// @core/signer
const encoding9 = {
  preencode(state, m) {
    encoding7.preencode(state, m.signature)
    c.fixed32.preencode(state, m.namespace)
    c.fixed32.preencode(state, m.publicKey)
  },
  encode(state, m) {
    encoding7.encode(state, m.signature)
    c.fixed32.encode(state, m.namespace)
    c.fixed32.encode(state, m.publicKey)
  },
  decode(state) {
    const r0 = encoding7.decode(state)
    const r1 = c.fixed32.decode(state)
    const r2 = c.fixed32.decode(state)

    return {
      signature: r0,
      namespace: r1,
      publicKey: r2
    }
  }
}

// @core/prologue
const encoding10 = {
  preencode(state, m) {
    c.fixed32.preencode(state, m.hash)
    c.uint.preencode(state, m.length)
  },
  encode(state, m) {
    c.fixed32.encode(state, m.hash)
    c.uint.encode(state, m.length)
  },
  decode(state) {
    const r0 = c.fixed32.decode(state)
    const r1 = c.uint.decode(state)

    return {
      hash: r0,
      length: r1
    }
  }
}

// @core/manifest.signers
const encoding11_4 = c.array(encoding9)
// @core/manifest.linked
const encoding11_6 = c.array(c.fixed32)

// @core/manifest
const encoding11 = {
  preencode(state, m) {
    c.uint.preencode(state, m.version)
    state.end++ // max flag is 8 so always one byte
    encoding6.preencode(state, m.hash)
    c.uint.preencode(state, m.quorum)
    encoding11_4.preencode(state, m.signers)

    if (m.prologue) encoding10.preencode(state, m.prologue)
    if (m.linked) encoding11_6.preencode(state, m.linked)
    if (m.userData) c.buffer.preencode(state, m.userData)
  },
  encode(state, m) {
    const flags =
      (m.allowPatch ? 1 : 0) | (m.prologue ? 2 : 0) | (m.linked ? 4 : 0) | (m.userData ? 8 : 0)

    c.uint.encode(state, m.version)
    c.uint.encode(state, flags)
    encoding6.encode(state, m.hash)
    c.uint.encode(state, m.quorum)
    encoding11_4.encode(state, m.signers)

    if (m.prologue) encoding10.encode(state, m.prologue)
    if (m.linked) encoding11_6.encode(state, m.linked)
    if (m.userData) c.buffer.encode(state, m.userData)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const flags = c.uint.decode(state)

    return {
      version: r0,
      hash: encoding6.decode(state),
      quorum: c.uint.decode(state),
      allowPatch: (flags & 1) !== 0,
      signers: encoding11_4.decode(state),
      prologue: (flags & 2) !== 0 ? encoding10.decode(state) : null,
      linked: (flags & 4) !== 0 ? encoding11_6.decode(state) : null,
      userData: (flags & 8) !== 0 ? c.buffer.decode(state) : null
    }
  }
}

// @core/keyPair
const encoding12 = {
  preencode(state, m) {
    c.buffer.preencode(state, m.publicKey)
    c.optionalBuffer.preencode(state, m.secretKey)
  },
  encode(state, m) {
    c.buffer.encode(state, m.publicKey)
    c.optionalBuffer.encode(state, m.secretKey)
  },
  decode(state) {
    const r0 = c.buffer.decode(state)
    const r1 = c.optionalBuffer.decode(state)

    return {
      publicKey: r0,
      secretKey: r1
    }
  }
}

// @core/group
const encoding13 = {
  preencode(state, m) {
    state.end++ // max flag is 2 so always one byte

    if (m.key) c.fixed32.preencode(state, m.key)
    if (m.pointer) c.uint.preencode(state, m.pointer)
  },
  encode(state, m) {
    const flags = (m.key ? 1 : 0) | (m.pointer ? 2 : 0)

    c.uint.encode(state, flags)

    if (m.key) c.fixed32.encode(state, m.key)
    if (m.pointer) c.uint.encode(state, m.pointer)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      key: (flags & 1) !== 0 ? c.fixed32.decode(state) : null,
      pointer: (flags & 2) !== 0 ? c.uint.decode(state) : 0
    }
  }
}

// @core/auth.manifest
const encoding14_2 = c.frame(encoding11)

// @core/auth
const encoding14 = {
  preencode(state, m) {
    c.fixed32.preencode(state, m.key)
    c.fixed32.preencode(state, m.discoveryKey)
    state.end++ // max flag is 4 so always one byte

    if (m.manifest) encoding14_2.preencode(state, m.manifest)
    if (m.keyPair) encoding12.preencode(state, m.keyPair)
    if (m.encryptionKey) c.buffer.preencode(state, m.encryptionKey)
  },
  encode(state, m) {
    const flags = (m.manifest ? 1 : 0) | (m.keyPair ? 2 : 0) | (m.encryptionKey ? 4 : 0)

    c.fixed32.encode(state, m.key)
    c.fixed32.encode(state, m.discoveryKey)
    c.uint.encode(state, flags)

    if (m.manifest) encoding14_2.encode(state, m.manifest)
    if (m.keyPair) encoding12.encode(state, m.keyPair)
    if (m.encryptionKey) c.buffer.encode(state, m.encryptionKey)
  },
  decode(state) {
    const r0 = c.fixed32.decode(state)
    const r1 = c.fixed32.decode(state)
    const flags = c.uint.decode(state)

    return {
      key: r0,
      discoveryKey: r1,
      manifest: (flags & 1) !== 0 ? encoding14_2.decode(state) : null,
      keyPair: (flags & 2) !== 0 ? encoding12.decode(state) : null,
      encryptionKey: (flags & 4) !== 0 ? c.buffer.decode(state) : null
    }
  }
}

// @core/head
const encoding15 = {
  preencode(state, m) {
    c.uint.preencode(state, m.fork)
    c.uint.preencode(state, m.length)
    c.fixed32.preencode(state, m.rootHash)
    c.optionalBuffer.preencode(state, m.signature)
    state.end++ // max flag is 1 so always one byte

    if (version >= 2 && m.timestamp) c.uint64.preencode(state, m.timestamp)
  },
  encode(state, m) {
    const flags = version >= 2 && m.timestamp ? 1 : 0

    c.uint.encode(state, m.fork)
    c.uint.encode(state, m.length)
    c.fixed32.encode(state, m.rootHash)
    c.optionalBuffer.encode(state, m.signature)
    c.uint.encode(state, flags)

    if (version >= 2 && m.timestamp) c.uint64.encode(state, m.timestamp)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const r1 = c.uint.decode(state)
    const r2 = c.fixed32.decode(state)
    const r3 = c.optionalBuffer.decode(state)
    const flags = state.start < state.end ? c.uint.decode(state) : 0

    return {
      fork: r0,
      length: r1,
      rootHash: r2,
      signature: r3,
      timestamp: version >= 2 && (flags & 1) !== 0 ? c.uint64.decode(state) : 0
    }
  }
}

// @core/hints
const encoding16 = {
  preencode(state, m) {
    state.end++ // max flag is 4 so always one byte

    if (m.contiguousLength) c.uint.preencode(state, m.contiguousLength)
    if (m.remoteContiguousLength) c.uint.preencode(state, m.remoteContiguousLength)
    if (m.recovering) c.uint.preencode(state, m.recovering)
  },
  encode(state, m) {
    const flags =
      (m.contiguousLength ? 1 : 0) | (m.remoteContiguousLength ? 2 : 0) | (m.recovering ? 4 : 0)

    c.uint.encode(state, flags)

    if (m.contiguousLength) c.uint.encode(state, m.contiguousLength)
    if (m.remoteContiguousLength) c.uint.encode(state, m.remoteContiguousLength)
    if (m.recovering) c.uint.encode(state, m.recovering)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      contiguousLength: (flags & 1) !== 0 ? c.uint.decode(state) : 0,
      remoteContiguousLength: (flags & 2) !== 0 ? c.uint.decode(state) : 0,
      recovering: (flags & 4) !== 0 ? c.uint.decode(state) : 0
    }
  }
}

// @core/session
const encoding17 = {
  preencode(state, m) {
    c.string.preencode(state, m.name)
    c.uint.preencode(state, m.dataPointer)
  },
  encode(state, m) {
    c.string.encode(state, m.name)
    c.uint.encode(state, m.dataPointer)
  },
  decode(state) {
    const r0 = c.string.decode(state)
    const r1 = c.uint.decode(state)

    return {
      name: r0,
      dataPointer: r1
    }
  }
}

// @core/sessions
const encoding18 = c.array(encoding17)

// @core/dependency
const encoding19 = {
  preencode(state, m) {
    c.uint.preencode(state, m.dataPointer)
    c.uint.preencode(state, m.length)
  },
  encode(state, m) {
    c.uint.encode(state, m.dataPointer)
    c.uint.encode(state, m.length)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const r1 = c.uint.decode(state)

    return {
      dataPointer: r0,
      length: r1
    }
  }
}

function setVersion(v) {
  version = v
}

function encode(name, value, v = VERSION) {
  version = v
  return c.encode(getEncoding(name), value)
}

function decode(name, buffer, v = VERSION) {
  version = v
  return c.decode(getEncoding(name), buffer)
}

function getEnum(name) {
  switch (name) {
    case '@core/hashes':
      return encoding6_enum
    case '@core/signatures':
      return encoding7_enum
    default:
      throw new Error('Enum not found ' + name)
  }
}

function getEncoding(name) {
  switch (name) {
    case '@corestore/allocated':
      return encoding0
    case '@corestore/head-v1':
      return encoding1
    case '@corestore/head-v2':
      return encoding2
    case '@corestore/head':
      return encoding3
    case '@corestore/alias':
      return encoding4
    case '@corestore/core':
      return encoding5
    case '@core/hashes':
      return encoding6
    case '@core/signatures':
      return encoding7
    case '@core/tree-node':
      return encoding8
    case '@core/signer':
      return encoding9
    case '@core/prologue':
      return encoding10
    case '@core/manifest':
      return encoding11
    case '@core/keyPair':
      return encoding12
    case '@core/group':
      return encoding13
    case '@core/auth':
      return encoding14
    case '@core/head':
      return encoding15
    case '@core/hints':
      return encoding16
    case '@core/session':
      return encoding17
    case '@core/sessions':
      return encoding18
    case '@core/dependency':
      return encoding19
    default:
      throw new Error('Encoder not found ' + name)
  }
}

function getStruct(name, v = VERSION) {
  const enc = getEncoding(name)
  return {
    preencode(state, m) {
      version = v
      enc.preencode(state, m)
    },
    encode(state, m) {
      version = v
      enc.encode(state, m)
    },
    decode(state) {
      version = v
      return enc.decode(state)
    }
  }
}

const resolveStruct = getStruct // compat

module.exports = {
  resolveStruct,
  getStruct,
  getEnum,
  getEncoding,
  encode,
  decode,
  setVersion,
  version
}
const RocksDB = require('rocksdb-native')
const rrp = require('resolve-reject-promise')
const ScopeLock = require('scope-lock')
const DeviceFile = require('device-file')
const path = require('path')
const fs = require('fs')
const Xache = require('xache')

const View = require('./lib/view.js')

const VERSION = 2
const COLUMN_FAMILY = 'corestore'

const { store, core } = require('./lib/keys.js')

const { CorestoreRX, CorestoreTX, CoreTX, CoreRX } = require('./lib/tx.js')

const {
  createCoreStream,
  createAliasStream,
  createDiscoveryKeyStream,
  createBlockStream,
  createBitfieldStream,
  createUserDataStream,
  createTreeNodeStream,
  createMarkStream,
  createLocalStream,
  createGroupUpdateStream
} = require('./lib/streams.js')

const EMPTY = new View()

class Atom {
  constructor(db) {
    this.db = db
    this.view = new View()
    this.flushedPromise = null
    this.flushing = false
    this.preflushes = []
    this.flushes = []
  }

  preflush(fn) {
    this.preflushes.push(fn)
  }

  onflush(fn) {
    this.flushes.push(fn)
  }

  flushed() {
    if (!this.flushing) return Promise.resolve()
    if (this.flushedPromise !== null) return this.flushedPromise.promise
    this.flushedPromise = rrp()
    return this.flushedPromise.promise
  }

  _resolve() {
    const f = this.flushedPromise
    this.flushedPromise = null
    f.resolve()
  }

  async flush() {
    if (this.flushing) throw new Error('Atom already flushing')
    this.flushing = true

    try {
      const plen = this.preflushes.length
      for (let i = 0; i < plen; i++) this.preflushes[i]()

      await View.flush(this.view.changes, this.db)

      const promises = []
      const len = this.flushes.length // in case of reentry
      for (let i = 0; i < len; i++) promises.push(this.flushes[i]())

      await Promise.all(promises)
    } finally {
      this.view.reset()
      this.flushing = false
      if (this.flushedPromise !== null) this._resolve()
    }
  }
}

class HypercoreStorage {
  constructor(store, db, treeCache, core, view, atom) {
    this.store = store
    this.db = db
    this.core = core
    this.view = view
    this.atom = atom

    this.view.readStart()
    this.treeCache = treeCache
  }

  get readOnly() {
    return this.store.readOnly
  }

  get dependencies() {
    return this.core.dependencies
  }

  getDependencyLength() {
    return this.core.dependencies.length
      ? this.core.dependencies[this.core.dependencies.length - 1].length
      : -1
  }

  getDependency(length) {
    for (let i = this.core.dependencies.length - 1; i >= 0; i--) {
      const dep = this.core.dependencies[i]
      if (dep.length < length) return dep
    }

    return null
  }

  setDependencyHead(dep) {
    if (dep === null) {
      this.core.dependencies = []
      return
    }

    const deps = this.core.dependencies

    for (let i = deps.length - 1; i >= 0; i--) {
      const d = deps[i]

      if (d.dataPointer !== dep.dataPointer) continue

      // check if nothing changed
      if (d.length === dep.length && i === deps.length - 1) return

      this.core = {
        corePointer: this.core.corePointer,
        dataPointer: this.core.dataPointer,
        dependencies: deps.slice(0, i + 1)
      }

      this.core.dependencies[i] = {
        dataPointer: dep.dataPointer,
        length: dep.length
      }
      return // updated head so done
    }

    this.core.dependencies = [
      {
        dataPointer: dep.dataPointer,
        length: dep.length
      }
    ]
  }

  // TODO: this might have to be async if the dependents have changed, but prop ok for now
  updateDependencyLength(length, truncated) {
    const deps = this.core.dependencies

    const i = this.findDependencyIndex(length, truncated)
    if (i === -1) throw new Error('Dependency not found')

    this.core = {
      corePointer: this.core.corePointer,
      dataPointer: this.core.dataPointer,
      dependencies: deps.slice(0, i + 1)
    }

    if (this.core.dependencies[i].length !== length) {
      this.core.dependencies[i] = {
        dataPointer: deps[i].dataPointer,
        length
      }
    }
  }

  findDependencyIndex(length, truncated) {
    const deps = this.core.dependencies

    if (truncated) {
      for (let i = 0; i < deps.length; i++) {
        if (deps[i].length >= length) return i
      }

      return -1
    }

    for (let i = deps.length - 1; i >= 0; i--) {
      if (deps[i].length <= length) return i
    }

    return -1
  }

  get snapshotted() {
    return this.db._snapshot !== null
  }

  snapshot() {
    return new HypercoreStorage(
      this.store,
      this.db.snapshot(),
      this.treeCache,
      this.core,
      this.view.snapshot(),
      this.atom
    )
  }

  compact() {
    return Promise.all([
      this.db.compactRange(core.core(this.core.corePointer), core.core(this.core.corePointer)),
      this.db.compactRange(core.data(this.core.dataPointer), core.data(this.core.dataPointer))
    ])
  }

  atomize(atom) {
    if (this.atom && this.atom !== atom) {
      throw new Error('Cannot atomize and atomized session with a new atom')
    }

    return new HypercoreStorage(
      this.store,
      this.db.session(),
      this.treeCache,
      this.core,
      atom.view,
      atom
    )
  }

  createAtom() {
    return this.store.createAtom()
  }

  createBlockStream(opts) {
    return createBlockStream(this.core, this.db, this.view, opts)
  }

  createTreeNodeStream(opts) {
    return createTreeNodeStream(this.core, this.db, this.view, opts)
  }

  createBitfieldStream(opts) {
    return createBitfieldStream(this.core, this.db, this.view, opts)
  }

  createUserDataStream(opts) {
    return createUserDataStream(this.core, this.db, this.view, opts)
  }

  createMarkStream(opts) {
    return createMarkStream(this.core, this.db, this.view, opts)
  }

  createLocalStream(opts) {
    return createLocalStream(this.core, this.db, this.view, opts)
  }

  async resumeSession(name) {
    const rx = this.read()
    const existingSessionsPromise = rx.getSessions()

    rx.tryFlush()
    const existingSessions = await existingSessionsPromise

    const sessions = existingSessions || []
    const session = getSession(sessions, name, false)

    if (session === null) return null

    const core = {
      corePointer: this.core.corePointer,
      dataPointer: session.dataPointer,
      dependencies: []
    }

    const coreRx = new CoreRX(core, this.db, this.view, this.treeCache, this.store.stats, -1)

    const dependencyPromise = coreRx.getDependency()
    coreRx.tryFlush()

    const dependency = await dependencyPromise
    if (dependency) core.dependencies = this._addDependency(dependency)

    return new HypercoreStorage(
      this.store,
      this.db.session(),
      this.treeCache,
      core,
      this.atom ? this.view : new View(),
      this.atom
    )
  }

  async createSession(name, head) {
    const rx = this.read()

    const existingSessionsPromise = rx.getSessions()
    const existingHeadPromise = rx.getHead()

    rx.tryFlush()

    const [existingSessions, existingHead] = await Promise.all([
      existingSessionsPromise,
      existingHeadPromise
    ])
    if (head === null) head = existingHead

    if (existingHead !== null && head.length > existingHead.length) {
      throw new Error('Invalid head passed, ahead of core')
    }

    const sessions = existingSessions || []
    const session = getSession(sessions, name, true)
    const fresh = session.dataPointer === -1

    if (fresh) {
      session.dataPointer = await this.store._allocData()
    }

    const tx = this.write()

    tx.setSessions(sessions)

    const length = head === null ? 0 : head.length
    const core = {
      corePointer: this.core.corePointer,
      dataPointer: session.dataPointer,
      dependencies: this._addDependency({
        dataPointer: this.core.dataPointer,
        length
      })
    }

    const coreTx = new CoreTX(core, this.db, tx.view, tx.changes)

    if (length > 0) coreTx.setHead(head)
    coreTx.setDependency(core.dependencies[core.dependencies.length - 1])

    if (!fresh) {
      // nuke all existing state...
      coreTx.deleteBlockRange(0, -1)
      coreTx.deleteTreeNodeRange(0, -1)
      coreTx.deleteBitfieldPageRange(0, -1)
    }

    await tx.flush()

    return new HypercoreStorage(
      this.store,
      this.db.session(),
      this.treeCache,
      core,
      this.atom ? this.view : new View(),
      this.atom
    )
  }

  async createAtomicSession(atom, head) {
    const length = head === null ? 0 : head.length
    const core = {
      corePointer: this.core.corePointer,
      dataPointer: this.core.dataPointer,
      dependencies: this._addDependency(null)
    }

    const coreTx = new CoreTX(core, this.db, atom.view, [])

    if (length > 0) coreTx.setHead(head)

    await coreTx.flush()

    return this.atomize(atom)
  }

  _addDependency(dep) {
    const deps = []

    for (let i = 0; i < this.core.dependencies.length; i++) {
      const d = this.core.dependencies[i]

      if (dep !== null && d.length > dep.length) {
        if (d.dataPointer !== dep.dataPointer) {
          deps.push({ dataPointer: d.dataPointer, length: dep.length })
        }
        return deps
      }

      deps.push(d)
    }

    if (
      dep !== null &&
      (deps.length === 0 || deps[deps.length - 1].dataPointer !== dep.dataPointer)
    ) {
      deps.push(dep)
    }
    return deps
  }

  async deleteSessions() {
    const rx = this.read()
    const existingSessionsPromise = rx.getSessions()
    rx.tryFlush()

    const existingSessions = await existingSessionsPromise

    // Remove batches
    const coreTx = this.write()
    coreTx.setSessions([]) // Clear sessions record
    await coreTx.flush()

    const tx = this.db.write({ autoDestroy: true })

    for (const { dataPointer } of existingSessions) {
      const start = core.data(dataPointer)
      const end = core.data(dataPointer + 1)
      tx.tryDeleteRange(start, end)
    }

    await tx.flush()
  }

  read(fork = -1) {
    let treeCache = null
    if (!this.atom) treeCache = this.treeCache

    return new CoreRX(this.core, this.db, this.view, treeCache, this.store.stats, fork)
  }

  write() {
    return new CoreTX(this.core, this.db, this.atom ? this.view : null, [])
  }

  close() {
    if (this.view !== null) {
      this.view.readStop()
      this.view = null
    }

    return this.db.close()
  }

  static async export(ptr, db, { batches = false } = {}) {
    const rx = new CoreRX(ptr, db, EMPTY, null, null, -1)

    const core = {
      head: null,
      auth: null,
      sessions: [],
      data: null
    }

    const sessionsPromise = rx.getSessions()
    const headPromise = rx.getHead()
    const authPromise = rx.getAuth()

    rx.tryFlush()

    const [sessions, head, auth] = await Promise.all([sessionsPromise, headPromise, authPromise])

    core.head = head
    core.auth = { ...auth, keyPair: null }
    if (sessions) core.sessions = sessions.map((s) => s.name)

    const data = []

    data.push(exportData(ptr, db))

    if (batches) {
      for (const { dataPointer } of sessions) {
        data.push(exportData({ dataPointer, dependencies: [] }, db))
      }
    }

    core.data = await Promise.all(data)

    return core
  }

  static isParentStorage(storage, parent) {
    const last = getLastDependency(storage)
    return !!last && last.dataPointer === parent.core.dataPointer
  }
}

class CorestoreStorage {
  constructor(db, opts = {}) {
    const storage = typeof db === 'string' ? db : null

    this.bootstrap = storage !== null
    this.path = storage !== null ? storage : path.join(db.path, '..')
    this.alwaysRecover = !!opts.alwaysRecover
    this.readOnly = !!opts.readOnly
    this.allowBackup = !!opts.allowBackup
    this.deviceFile = null
    this.wait = !!opts.wait

    // tmp sync fix for simplicty since not super deployed yet
    if (this.bootstrap && !this.readOnly) tmpFixStorage(this.path)

    this.id = opts.id || null
    this.view = null
    this.enters = 0
    this.lock = new ScopeLock()
    this.flushing = null
    this.version = 0
    this.migrating = null

    if ((this.bootstrap && !this.readOnly && !this.allowBackup) || this.wait) {
      const corestoreFile = path.join(this.path, 'CORESTORE')

      this.deviceFile = new DeviceFile(corestoreFile, {
        lock: true,
        wait: this.wait,
        data: { id: this.id }
      })
    }

    const dbPath = path.join(this.path, 'db')

    this.stats = {
      treeCache: {
        hits: 0,
        misses: 0,
        parallel: 0,
        skips: 0
      }
    }
    this.rocks = storage === null ? db : new RocksDB(dbPath, { ...opts, lock: this.deviceFile })
    this.db = createColumnFamily(this.rocks, opts)

    const { treeCache = { maxSize: 8192 } } = opts
    this.treeCache = new Xache(treeCache)
  }

  get opened() {
    return this.db.opened
  }

  get closed() {
    return this.db.closed
  }

  async ready() {
    if (this.version === 0) await this._migrateStore()
    return this.db.ready()
  }

  compact(opts) {
    return this.db.compactRange(opts)
  }

  async audit() {
    for await (const { core } of this.createCoreStream()) {
      const coreRx = new CoreRX(core, this.db, EMPTY, this.treeCache, this.stats, -1)
      const authPromise = coreRx.getAuth()

      coreRx.tryFlush()

      const auth = await authPromise

      if (!auth.manifest || auth.manifest.version > 0) continue
      if (auth.manifest.linked === null) continue

      auth.manifest.linked = null
      const coreTx = new CoreTX(core, this.db, null, [])
      coreTx.setAuth(auth)
      await coreTx.flush()
    }
  }

  async deleteCore(ptr) {
    const rx = new CoreRX(ptr, this.db, EMPTY, this.treeCache, this.stats, -1)

    const authPromise = rx.getAuth()
    const sessionsPromise = rx.getSessions()

    rx.tryFlush()

    const auth = await authPromise
    const sessions = await sessionsPromise

    // no core stored here
    if (!auth) return

    const tx = this.db.write({ autoDestroy: true })

    tx.tryDelete(store.core(auth.discoveryKey))

    // clear core
    const start = core.core(ptr.corePointer)
    const end = core.core(ptr.corePointer + 1)
    tx.tryDeleteRange(start, end)

    if (sessions) {
      for (const { dataPointer } of sessions) {
        const start = core.data(dataPointer)
        const end = core.data(dataPointer + 1)
        tx.tryDeleteRange(start, end)
      }
    }

    return tx.flush()
  }

  static isCoreStorage(db) {
    return isCorestoreStorage(db)
  }

  static from(db) {
    if (isCorestoreStorage(db)) return db
    return new this(db)
  }

  async _flush() {
    while (this.enters > 0) {
      await this.lock.lock()
      await this.lock.unlock()
    }
  }

  async _maybeRecover(view) {
    const r = path.join(this.db.path, 'RECOVERING')
    if (!(await fileExists(r))) return
    await this.setRecovering(view)
    await fs.promises.unlink(r)
  }

  _maybeRecoverLater(err) {
    if (!shouldRecover(err) && !this.alwaysRecover) return
    fs.writeFileSync(path.join(this.db.path, 'RECOVERING'), '')
    for (const file of fs.readdirSync(this.db.path)) {
      if (file.endsWith('.log')) fs.unlinkSync(path.join(this.db.path, file))
    }
  }

  // runs pre any other mutation and read
  async _migrateStore() {
    const view = await this._enter()

    try {
      if (this.version === VERSION) return

      await this._preopen

      try {
        await this.db.ready()
      } catch (err) {
        this._maybeRecoverLater(err)
        throw err
      }

      await this._maybeRecover(view)

      const rx = new CorestoreRX(this.db, view)
      const headPromise = rx.getHead()

      rx.tryFlush()
      const head = await headPromise

      const version = head === null ? 0 : head.version
      if (version === VERSION) {
        this.version = VERSION
        return
      }

      const target = { version: VERSION, dryRun: false }

      switch (version) {
        case 0: {
          await require('./migrations/0').store(this, target)
          break
        }
        case 1: {
          // implicit migration on write
          break
        }
        default: {
          throw new Error(
            'Unsupported version: ' + version + ' - you should probably upgrade your dependencies'
          )
        }
      }

      this.version = VERSION
    } finally {
      await this._exit()
    }
  }

  // runs pre the core is returned to the user
  async _migrateCore(core, discoveryKey, version, locked) {
    const view = locked ? this.view : await this._enter()
    try {
      if (version === VERSION) return

      const target = { version: VERSION, dryRun: false }

      switch (version) {
        case 0: {
          await require('./migrations/0').core(core, target)
          break
        }
        case 1: {
          await require('./migrations/1').core(core, target)
          break
        }
        default: {
          throw new Error(
            'Unsupported version: ' + version + ' - you should probably upgrade your dependencies'
          )
        }
      }

      if (locked === false) return

      // if its locked, then move the core state into the memview
      // in case the core is reopened from the memview, pre flush

      const rx = new CorestoreRX(this.db, EMPTY)
      const tx = new CorestoreTX(view)

      const corePromise = rx.getCore(discoveryKey)
      rx.tryFlush()

      tx.putCore(discoveryKey, await corePromise)
      tx.apply()
    } finally {
      if (!locked) await this._exit()
    }
  }

  async _enter() {
    this.enters++
    await this.lock.lock()
    if (this.view === null) this.view = new View()
    return this.view
  }

  async _exit() {
    this.enters--

    if (this.flushing === null) this.flushing = rrp()
    const flushed = this.flushing.promise

    if (this.enters === 0 || this.view.size() > 128) {
      try {
        await View.flush(this.view.changes, this.db)
        this.flushing.resolve()
      } catch (err) {
        this.flushing.reject(err)
      } finally {
        this.flushing = null
        this.view = null
      }
    }

    this.lock.unlock()
    return flushed
  }

  // when used with core catches this isnt transactional for simplicity, HOWEVER, its just a number
  // so worth the tradeoff
  async _allocData() {
    let dataPointer = 0

    const view = await this._enter()
    const tx = new CorestoreTX(view)

    try {
      const head = await this._getHead(view)

      dataPointer = head.datas++

      tx.setHead(head)
      tx.apply()
    } finally {
      await this._exit()
    }

    return dataPointer
  }

  // exposes here so migrations can easily access the head in an init state
  async _getHead(view) {
    const rx = new CorestoreRX(this.db, view)
    const headPromise = rx.getHead()
    rx.tryFlush()

    const head = await headPromise
    return head === null ? initStoreHead() : head
  }

  createAtom() {
    return new Atom(this.db)
  }

  async flush() {
    await this.rocks.flush()
  }

  async close() {
    if (this.db.closed) return
    await this._flush()
    await this.db.close()
    await this.rocks.close()
    this.treeCache.destroy()
    if (this.deviceFile) await this.deviceFile.close()
  }

  async clear() {
    if (this.version === 0) await this._migrateStore()

    const view = await this._enter()
    const tx = new CorestoreTX(view)

    tx.clear()
    tx.apply()

    await this._exit()
  }

  createCoreStream() {
    // TODO: be nice to run the mgiration here also, but too much plumbing atm
    return createCoreStream(this.db, EMPTY)
  }

  createAliasStream(namespace) {
    // TODO: be nice to run the mgiration here also, but too much plumbing atm
    return createAliasStream(this.db, EMPTY, namespace)
  }

  createDiscoveryKeyStream(namespace) {
    return createDiscoveryKeyStream(this.db, EMPTY, namespace)
  }

  createGroupUpdateStream(group, { since, reverse } = {}) {
    return createGroupUpdateStream(this.db, EMPTY, group, { gte: since, reverse })
  }

  async getAlias(alias) {
    if (this.version === 0) await this._migrateStore()

    const rx = new CorestoreRX(this.db, EMPTY)
    const discoveryKeyPromise = rx.getCoreByAlias(alias)
    rx.tryFlush()
    return discoveryKeyPromise
  }

  async getSeed() {
    if (this.version === 0) await this._migrateStore()

    const rx = new CorestoreRX(this.db, EMPTY)
    const headPromise = rx.getHead()

    rx.tryFlush()

    const head = await headPromise
    return head === null ? null : head.seed
  }

  async getGroup(topic) {
    if (this.version === 0) await this._migrateStore()

    const rx = new CorestoreRX(this.db, EMPTY)
    const groupPromise = rx.getGroup(topic)
    rx.tryFlush()
    return groupPromise
  }

  async setSeed(seed, { overwrite = true } = {}) {
    if (this.version === 0) await this._migrateStore()

    const view = await this._enter()
    const tx = new CorestoreTX(view)

    try {
      const rx = new CorestoreRX(this.db, view)
      const headPromise = rx.getHead()

      rx.tryFlush()

      const head = (await headPromise) || initStoreHead()

      if (head.seed === null || overwrite) head.seed = seed
      tx.setHead(head)
      tx.apply()

      return head.seed
    } finally {
      await this._exit()
    }
  }

  async setRecovering(view = null) {
    const recovering = Date.now()
    let keys = []

    for await (const data of this.createDiscoveryKeyStream()) {
      keys.push(data)
      if (keys.length > 16 * 1024) {
        await this._flushRecovering(recovering, view, keys)
        keys = []
      }
    }

    if (keys.length) await this._flushRecovering(recovering, view, keys)
  }

  async _flushRecovering(recovering, view, keys) {
    const own = !view
    if (own) view = await this._enter()
    const tx = new CorestoreTX(view)

    try {
      const infos = await this._getInfos(keys, { auth: false, head: false, hints: true })
      for (const inf of infos) {
        tx.setCoreHints(inf.core, { ...inf.hints, recovering })
      }
      tx.apply()
    } finally {
      if (own) await this._exit()
    }
  }

  async getDefaultDiscoveryKey() {
    if (this.version === 0) await this._migrateStore()

    const rx = new CorestoreRX(this.db, EMPTY)
    const headPromise = rx.getHead()

    rx.tryFlush()

    const head = await headPromise
    return head === null ? null : head.defaultDiscoveryKey
  }

  async setDefaultDiscoveryKey(discoveryKey, { overwrite = true } = {}) {
    if (this.version === 0) await this._migrateStore()

    const view = await this._enter()
    const tx = new CorestoreTX(view)

    try {
      const rx = new CorestoreRX(this.db, view)
      const headPromise = rx.getHead()

      rx.tryFlush()

      const head = (await headPromise) || initStoreHead()

      if (head.defaultDiscoveryKey === null || overwrite) head.defaultDiscoveryKey = discoveryKey
      tx.setHead(head)
      tx.apply()

      return head.defaultDiscoveryKey
    } finally {
      await this._exit()
    }
  }

  async hasCore(discoveryKey, { ifMigrated = false } = {}) {
    if (this.version === 0) await this._migrateStore()

    const rx = new CorestoreRX(this.db, EMPTY)
    const promise = rx.getCore(discoveryKey)

    rx.tryFlush()

    const core = await promise

    if (core === null) return false
    if (core.version === 0 && ifMigrated) return false

    return true
  }

  async getAuth(discoveryKey) {
    if (this.version === 0) await this._migrateStore()

    const rx = new CorestoreRX(this.db, EMPTY)
    const corePromise = rx.getCore(discoveryKey)

    rx.tryFlush()

    const core = await corePromise
    if (core === null) return null

    const read = this.db.read({ autoDestroy: true })
    const authPromise = CoreRX.getAuth(read, core)

    read.tryFlush()

    return authPromise
  }

  async getInfo(discoveryKey, opts) {
    return (await this.getInfos([discoveryKey], opts))[0]
  }

  async getInfos(discoveryKeys, opts) {
    if (this.version === 0) await this._migrateStore()
    return this._getInfos(discoveryKeys, opts)
  }

  async _getInfos(discoveryKeys, { auth = true, head = true, hints = true } = {}) {
    const rx = new CorestoreRX(this.db, EMPTY)
    const corePromises = new Array(discoveryKeys.length)

    for (let i = 0; i < discoveryKeys.length; i++) {
      corePromises[i] = rx.getCore(discoveryKeys[i])
    }

    rx.tryFlush()

    const cores = await Promise.all(corePromises)
    const read = this.db.read({ autoDestroy: true })

    const resultPromises = new Array(cores.length)

    for (let i = 0; i < cores.length; i++) {
      resultPromises[i] = cores[i]
        ? getInfoFromBatch(read, cores[i], discoveryKeys[i], auth, head, hints)
        : null
    }

    read.tryFlush()

    return Promise.all(resultPromises)
  }

  async suspend({ log = noop } = {}) {
    await log('Suspending hypercore storage...')
    await this.db.suspend()
    await log('db suspended')
    if (this.deviceFile) {
      await log('suspend deviceFile')
      await this.deviceFile.suspend()
      await log('deviceFile suspended')
    }
  }

  async resume() {
    if (this.deviceFile) await this.deviceFile.resume()
    await this.db.resume()
  }

  async resumeCore(discoveryKey) {
    if (this.version === 0) await this._migrateStore()

    if (!discoveryKey) {
      discoveryKey = await this.getDefaultDiscoveryKey()
      if (!discoveryKey) return null
    }

    const rx = new CorestoreRX(this.db, EMPTY)
    const corePromise = rx.getCore(discoveryKey)

    rx.tryFlush()
    const core = await corePromise

    if (core === null) return null
    return this._resumeFromPointers(EMPTY, discoveryKey, false, core)
  }

  async export(discoveryKey, opts) {
    const rx = new CorestoreRX(this.db, EMPTY)
    const corePromise = rx.getCore(discoveryKey)

    rx.tryFlush()
    const core = await corePromise
    if (core === null) return null

    let { dataPointer, corePointer } = core

    const ptr = { corePointer, dataPointer, dependencies: [] }

    while (true) {
      const rx = new CoreRX(
        { dataPointer, corePointer: 0, dependencies: [] },
        this.db,
        EMPTY,
        this.treeCache,
        this.stats,
        -1
      )
      const dependencyPromise = rx.getDependency()
      rx.tryFlush()
      const dependency = await dependencyPromise
      if (!dependency) break
      ptr.dependencies.push(dependency)
      dataPointer = dependency.dataPointer
    }

    const session = this.db.session()
    try {
      return await HypercoreStorage.export(ptr, session, opts)
    } finally {
      await session.close()
    }
  }

  async _resumeFromPointers(view, discoveryKey, create, { version, corePointer, dataPointer }) {
    const core = { corePointer, dataPointer, dependencies: [] }

    while (true) {
      const rx = new CoreRX(
        { dataPointer, corePointer: 0, dependencies: [] },
        this.db,
        view,
        this.treeCache,
        this.stats,
        -1
      )
      const dependencyPromise = rx.getDependency()
      rx.tryFlush()
      const dependency = await dependencyPromise
      if (!dependency) break
      core.dependencies.push(dependency)
      dataPointer = dependency.dataPointer
    }

    const result = new HypercoreStorage(this, this.db.session(), this.treeCache, core, EMPTY, null)

    if (version < VERSION) await this._migrateCore(result, discoveryKey, version, create)
    return result
  }

  // not allowed to throw validation errors as its a shared tx!
  async _create(
    view,
    { key, manifest, keyPair, encryptionKey, discoveryKey, alias, userData, core: ptrs }
  ) {
    const rx = new CorestoreRX(this.db, view)
    const tx = new CorestoreTX(view)

    const corePromise = rx.getCore(discoveryKey)
    const headPromise = rx.getHead()

    rx.tryFlush()

    let [core, head] = await Promise.all([corePromise, headPromise])
    if (core) return this._resumeFromPointers(view, discoveryKey, true, core)

    if (head === null) head = initStoreHead()
    if (head.defaultDiscoveryKey === null) head.defaultDiscoveryKey = discoveryKey

    const corePointer = ptrs ? ptrs.corePointer : head.cores++
    const dataPointer = ptrs ? ptrs.dataPointer : head.datas++

    core = { version: VERSION, corePointer, dataPointer, alias }

    tx.setHead(head)
    tx.putCore(discoveryKey, core)
    if (alias) tx.putCoreByAlias(alias, discoveryKey)

    const ptr = { corePointer, dataPointer, dependencies: [] }
    const ctx = new CoreTX(ptr, this.db, view, tx.changes)

    ctx.setAuth({
      key,
      discoveryKey,
      manifest,
      keyPair,
      encryptionKey
    })

    if (userData) {
      for (const { key, value } of userData) {
        ctx.putUserData(key, value)
      }
    }

    tx.apply()

    return new HypercoreStorage(this, this.db.session(), this.treeCache, ptr, EMPTY, null)
  }

  async createCore(data) {
    if (this.version === 0) await this._migrateStore()

    const view = await this._enter()

    try {
      return await this._create(view, data)
    } finally {
      await this._exit()
    }
  }

  // not allowed to throw validation errors as its a shared tx!
  async _createGroup(view, topic) {
    const rx = new CorestoreRX(this.db, view)
    const tx = new CorestoreTX(view)

    const groupPromise = rx.getGroup(topic)
    const headPromise = rx.getHead()

    rx.tryFlush()

    let group = await groupPromise
    if (group !== null) {
      return {
        key: topic,
        pointer: group
      }
    }

    let head = await headPromise
    if (head === null) head = initStoreHead()

    group = head.groups++

    tx.putGroup(topic, group)
    tx.setHead(head)
    tx.apply()

    return {
      key: topic,
      pointer: group
    }
  }

  async createGroup(topic) {
    if (this.version === 0) await this._migrateStore()

    const view = await this._enter()

    try {
      return await this._createGroup(view, topic)
    } finally {
      await this._exit()
    }
  }

  static isParentStorage(storage, parent) {
    return HypercoreStorage.isParentStorage(storage, parent)
  }
}

module.exports = CorestoreStorage

function initStoreHead() {
  return {
    version: 0, // cause we wanna run the migration
    datas: 0,
    cores: 0,
    groups: 0,
    seed: null,
    defaultDiscoveryKey: null
  }
}

function getSession(sessions, name, alloc) {
  for (let i = 0; i < sessions.length; i++) {
    if (sessions[i].name === name) return sessions[i]
  }

  if (!alloc) return null

  const result = { name, dataPointer: -1 }
  sessions.push(result)
  return result
}

function isCorestoreStorage(s) {
  return typeof s === 'object' && !!s && typeof s.setDefaultDiscoveryKey === 'function'
}

function createColumnFamily(db, opts = {}) {
  const {
    tableCacheIndexAndFilterBlocks = true,
    blockCache = true,
    optimizeFiltersForMemory = false,
    blobFileSize = 256 * 1024 * 1024,
    blobGarbageCollectionAgeCutOff = 0.25,
    blobGarbageCollectionForceThreshold = 1.0
  } = opts

  const col = new RocksDB.ColumnFamily(COLUMN_FAMILY, {
    enableBlobFiles: true,
    minBlobSize: 4096,
    blobFileSize,
    enableBlobGarbageCollection: true,
    tableBlockSize: 8192,
    tableCacheIndexAndFilterBlocks,
    tableFormatVersion: 6,
    optimizeFiltersForMemory,
    blockCache,
    blobGarbageCollectionAgeCutOff,
    blobGarbageCollectionForceThreshold
  })

  return db.columnFamily(col)
}

function getLastDependency(storage) {
  return storage.dependencies.length ? storage.dependencies[storage.dependencies.length - 1] : null
}

// TODO: remove in like 3-6 mo
function tmpFixStorage(p) {
  // if CORESTORE file is written, new format
  if (fs.existsSync(path.join(p, 'CORESTORE'))) return

  let files = []

  try {
    files = fs.readdirSync(p)
  } catch {}

  const notRocks = new Set([
    'CORESTORE',
    'primary-key',
    'cores',
    'app-preferences',
    'cache',
    'preferences.json',
    'db',
    'clone',
    'core',
    'notifications'
  ])

  for (const f of files) {
    if (notRocks.has(f)) continue

    try {
      fs.mkdirSync(path.join(p, 'db'))
    } catch {}

    fs.renameSync(path.join(p, f), path.join(p, 'db', f))
  }
}

async function exportData(ptr, db, opts) {
  // just need dataPointer
  const reads = [
    toArray(createBlockStream(ptr, db, EMPTY, opts)),
    toArray(createTreeNodeStream(ptr, db, EMPTY, opts)),
    toArray(createBitfieldStream(ptr, db, EMPTY, opts))
  ]

  const [blocks, tree, bitfield] = await Promise.all(reads)

  return {
    blocks,
    tree,
    bitfield
  }
}

async function toArray(stream) {
  const all = []
  for await (const e of stream) all.push(e)
  return all
}

async function fileExists(path) {
  try {
    await fs.promises.stat(path)
    return true
  } catch {
    return false
  }
}

function shouldRecover(err) {
  return err.message.toLowerCase().indexOf('sequence number is being set backwards') > -1
}

function noop() {}

async function getInfoFromBatch(db, c, discoveryKey, getAuth, getHead, getHints) {
  const authPromise = getAuth ? CoreRX.getAuth(db, c) : null
  const headPromise = getHead ? CoreRX.getHead(db, c) : null
  const hintsPromise = getHints ? CoreRX.getHints(db, c) : null

  // ensure no uncaughts
  if (authPromise) authPromise.catch(noop)
  if (headPromise) headPromise.catch(noop)
  if (hintsPromise) hintsPromise.catch(noop)

  return {
    discoveryKey,
    core: c,
    auth: await authPromise,
    head: await headPromise,
    hints: await hintsPromise
  }
}
const { Readable, getStreamError } = require('streamx')
const { core } = require('./keys')

module.exports = class BlockStream extends Readable {
  constructor(core, db, updates, start, end, reverse) {
    super()

    this.core = core
    this.db = db
    this.updates = updates
    this.start = start
    this.end = end
    this.reverse = reverse === true

    this._drained = true
    this._consumed = 0
    this._stream = null
    this._oncloseBound = this._onclose.bind(this)
    this._maybeDrainBound = this._maybeDrain.bind(this)

    this._update()
  }

  _update() {
    if (this._consumed > this.core.dependencies.length) return

    const deps = this.core.dependencies
    const index = this._findDependencyIndex(deps)

    const curr = index < deps.length ? deps[index] : null
    const prev = index > 0 && index - 1 < deps.length ? deps[index - 1] : null

    const start = prev && prev.length > this.start ? prev.length : this.start
    const end = curr && (this.end === -1 || curr.length < this.end) ? curr.length : this.end

    const ptr = curr ? curr.dataPointer : this.core.dataPointer

    this._makeStream(core.block(ptr, start), core.block(ptr, end))
  }

  _findDependencyIndex(deps) {
    if (!this.reverse) return this._consumed++

    let i = deps.length - this._consumed++
    while (i > 0) {
      if (deps[i - 1].length <= this.end) return i
      i--
      this._consumed++
    }

    return 0
  }

  _predestroy() {
    if (this._stream !== null) this._stream.destroy()
  }

  _read(cb) {
    this._drained = this._onreadable()
    cb(null)
  }

  _maybeDrain() {
    if (this._drained === true) return
    this._drained = this._onreadable()
  }

  _onreadable() {
    if (this._stream === null) {
      this.push(null)
      return true
    }

    let data = this._stream.read()

    if (data === null) return false

    do {
      this.push(data)
      data = this._stream.read()
    } while (data !== null)

    return true
  }

  _onclose() {
    if (this.destroying) return

    const err = getStreamError(this._stream)

    if (err !== null) {
      this.destroy(err)
      return
    }

    // empty the current stream
    if (this._onreadable() === true) this._drained = true

    this._stream = null

    this._update()
    this._maybeDrain()
  }

  _makeStream(start, end) {
    this._stream = this.updates.iterator(this.db, start, end, this.reverse)
    this._stream.on('readable', this._maybeDrainBound)
    this._stream.on('error', noop)
    this._stream.on('close', this._oncloseBound)
  }
}

function noop() {}
const { Readable } = require('streamx')

// used for returned a stream that just errors (during read during teardown)

module.exports = class CloseErrorStream extends Readable {
  constructor(err) {
    super()
    this.error = err
  }

  _open(cb) {
    cb(this.error)
  }
}
const { UINT, STRING } = require('index-encoder')
const c = require('compact-encoding')
const b4a = require('b4a')

const TL_HEAD = 0
const TL_CORE_BY_DKEY = 1
const TL_CORE_BY_ALIAS = 2
const TL_CORE = 3
const TL_DATA = 4
const TL_GROUP_BY_TOPIC = 5
const TL_GROUP = 6

const TL_END = TL_GROUP + 1

const CORE_AUTH = 0
const CORE_SESSIONS = 1
const CORE_GROUP = 2

const DATA_HEAD = 0
const DATA_DEPENDENCY = 1
const DATA_HINTS = 2
const DATA_BLOCK = 3
const DATA_TREE = 4
const DATA_BITFIELD = 5
const DATA_USER_DATA = 6
const DATA_LOCAL = 7
const DATA_MARK = 8

const slab = { buffer: b4a.allocUnsafe(65536), start: 0, end: 0 }

const store = {}
const core = {}
const group = {}

store.clear = function () {
  const state = alloc()
  let start = state.start
  UINT.encode(state, 0)
  const a = state.buffer.subarray(start, state.start)
  start = state.start
  UINT.encode(state, TL_END)
  const b = state.buffer.subarray(start, state.start)
  return [a, b]
}

store.head = function () {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_HEAD)
  return state.buffer.subarray(start, state.start)
}

store.core = function (discoveryKey) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE_BY_DKEY)
  c.fixed32.encode(state, discoveryKey)
  return state.buffer.subarray(start, state.start)
}

store.coreStart = function () {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE_BY_DKEY)
  return state.buffer.subarray(start, state.start)
}

store.coreEnd = function () {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE_BY_DKEY + 1)
  return state.buffer.subarray(start, state.start)
}

store.coreByAlias = function ({ namespace, name }) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE_BY_ALIAS)
  c.fixed32.encode(state, namespace)
  STRING.encode(state, name)
  return state.buffer.subarray(start, state.start)
}

store.coreByAliasStart = function (namespace) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE_BY_ALIAS)
  if (namespace) c.fixed32.encode(state, namespace)
  return state.buffer.subarray(start, state.start)
}

store.coreByAliasEnd = function (namespace) {
  const state = alloc()
  const start = state.start

  if (namespace) {
    UINT.encode(state, TL_CORE_BY_ALIAS)
    c.fixed32.encode(state, namespace)
    state.buffer[state.start++] = 0xff
  } else {
    UINT.encode(state, TL_CORE_BY_ALIAS + 1)
  }

  return state.buffer.subarray(start, state.start)
}

store.alias = function (buffer) {
  const state = { buffer, start: 0, end: buffer.byteLength }
  UINT.decode(state) // ns
  const namespace = c.fixed32.decode(state)
  const name = STRING.decode(state)
  return { namespace, name }
}

store.discoveryKey = function (buffer) {
  const state = { buffer, start: 0, end: buffer.byteLength }
  UINT.decode(state) // ns
  return c.fixed32.decode(state)
}

core.core = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE)
  UINT.encode(state, ptr)
  return state.buffer.subarray(start, state.start)
}

core.data = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  return state.buffer.subarray(start, state.start)
}

core.auth = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE)
  UINT.encode(state, ptr)
  UINT.encode(state, CORE_AUTH)
  return state.buffer.subarray(start, state.start)
}

core.group = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE)
  UINT.encode(state, ptr)
  UINT.encode(state, CORE_GROUP)
  return state.buffer.subarray(start, state.start)
}

core.sessions = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE)
  UINT.encode(state, ptr)
  UINT.encode(state, CORE_SESSIONS)
  return state.buffer.subarray(start, state.start)
}

core.head = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_HEAD)
  return state.buffer.subarray(start, state.start)
}

core.dependency = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_DEPENDENCY)
  return state.buffer.subarray(start, state.start)
}

core.hints = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_HINTS)
  return state.buffer.subarray(start, state.start)
}

core.block = function (ptr, index) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_BLOCK)
  UINT.encode(state, index)
  return state.buffer.subarray(start, state.start)
}

core.tree = function (ptr, index) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_TREE)
  UINT.encode(state, index)
  return state.buffer.subarray(start, state.start)
}

core.bitfield = function (ptr, index, type) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_BITFIELD)
  UINT.encode(state, index)
  UINT.encode(state, type)
  return state.buffer.subarray(start, state.start)
}

core.userData = function (ptr, key) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_USER_DATA)
  STRING.encode(state, key)
  return state.buffer.subarray(start, state.start)
}

core.userDataEnd = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_USER_DATA + 1)
  return state.buffer.subarray(start, state.start)
}

core.mark = function (ptr, index) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_MARK)
  UINT.encode(state, index)
  return state.buffer.subarray(start, state.start)
}

core.local = function (ptr, key) {
  if (key.byteLength > 2048) {
    throw new Error('local keys has an upper limit of 2048 bytes atm')
  }

  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_LOCAL)

  state.buffer.set(key, state.start)
  state.start += key.byteLength
  return state.buffer.subarray(start, state.start)
}

core.localEnd = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_LOCAL + 1)
  return state.buffer.subarray(start, state.start)
}

core.blockIndex = function (buffer) {
  const state = { buffer, start: 0, end: buffer.byteLength }
  UINT.decode(state) // ns
  UINT.decode(state) // ptr
  UINT.decode(state) // type
  return UINT.decode(state)
}

core.bitfieldIndexAndType = function (buffer) {
  const state = { buffer, start: 0, end: buffer.byteLength }
  UINT.decode(state) // ns
  UINT.decode(state) // ptr
  UINT.decode(state) // type
  return [UINT.decode(state), UINT.decode(state)]
}

core.userDataKey = function (buffer) {
  const state = { buffer, start: 0, end: buffer.byteLength }
  UINT.decode(state) // ns
  UINT.decode(state) // ptr
  UINT.decode(state) // type
  return STRING.decode(state)
}

core.markKey = function (buffer) {
  const state = { buffer, start: 0, end: buffer.byteLength }
  UINT.decode(state) // ns
  UINT.decode(state) // ptr
  UINT.decode(state) // type
  return UINT.decode(state)
}

core.localKey = function (buffer) {
  const state = { buffer, start: 0, end: buffer.byteLength }
  UINT.decode(state) // ns
  UINT.decode(state) // ptr
  UINT.decode(state) // type
  return state.buffer.subarray(state.start, state.end)
}

group.topic = function (topic) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_GROUP_BY_TOPIC)
  c.fixed32.encode(state, topic)
  return state.buffer.subarray(start, state.start)
}

group.entry = function (group, timestamp, ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_GROUP)
  UINT.encode(state, group)
  c.uint64be.encode(state, timestamp)
  UINT.encode(state, ptr)
  return state.buffer.subarray(start, state.start)
}

module.exports = { store, core, group }

function alloc() {
  if (slab.buffer.byteLength - slab.start < 4096) {
    slab.buffer = b4a.allocUnsafe(slab.buffer.byteLength)
    slab.start = 0
  }
  return slab
}
const b4a = require('b4a')
const BlockDependencyStream = require('./block-dependency-stream.js')
const { core, store, group } = require('./keys.js')
const schema = require('../encoding/spec/hyperschema')

const CORESTORE_CORE = schema.getEncoding('@corestore/core')
const CORE_TREE_NODE = schema.getEncoding('@core/tree-node')
const EMPTY = b4a.alloc(0)

module.exports = {
  createBlockStream,
  createBitfieldStream,
  createUserDataStream,
  createCoreStream,
  createAliasStream,
  createDiscoveryKeyStream,
  createTreeNodeStream,
  createMarkStream,
  createLocalStream,
  createGroupUpdateStream
}

function createCoreStream(db, view) {
  const start = store.coreStart()
  const end = store.coreEnd()

  const ite = view.iterator(db, start, end, false)

  ite._readableState.map = mapCore
  return ite
}

function createDiscoveryKeyStream(db, view, namespace) {
  const start = namespace ? store.coreByAliasStart(namespace) : store.coreStart()
  const end = namespace ? store.coreByAliasEnd(namespace) : store.coreEnd()

  const ite = view.iterator(db, start, end, false)

  ite._readableState.map = namespace ? mapNamespaceDiscoveryKeys : mapAllDiscoveryKeys
  return ite
}

function createAliasStream(db, view, namespace) {
  const start = store.coreByAliasStart(namespace)
  const end = store.coreByAliasEnd(namespace)

  const ite = view.iterator(db, start, end, false)

  ite._readableState.map = mapAlias
  return ite
}

function createGroupUpdateStream(db, view, groupID, { gte = 0, reverse = true } = {}) {
  const start = group.entry(groupID, gte, 0)
  const end = group.entry(groupID + 1, 0, 0)

  const ite = view.iterator(db, start, end, reverse)

  ite._readableState.map = mapGroupUpdate
  return ite
}

function createBlockIterator(ptr, db, view, start, end, reverse) {
  if (ptr.dependencies.length > 0) {
    return new BlockDependencyStream(ptr, db, view, start, end, reverse)
  }

  const s = core.block(ptr.dataPointer, start)
  const e = core.block(ptr.dataPointer, end === -1 ? Infinity : end)
  return view.iterator(db, s, e, reverse)
}

function createBlockStream(
  ptr,
  db,
  view,
  { gt = -1, gte = gt + 1, lte = -1, lt = lte === -1 ? -1 : lte + 1, reverse = false } = {}
) {
  const ite = createBlockIterator(ptr, db, view, gte, lt, reverse)

  ite._readableState.map = mapBlock
  return ite
}

function createBitfieldStream(
  ptr,
  db,
  view,
  { gt = -1, gte = gt + 1, lte = -1, lt = lte === -1 ? -1 : lte + 1, reverse = false } = {}
) {
  const s = core.bitfield(ptr.dataPointer, gte, 0)
  const e = core.bitfield(ptr.dataPointer, lt === -1 ? Infinity : lt, 0)
  const ite = view.iterator(db, s, e, false)

  ite._readableState.map = mapBitfield
  return ite
}

// NOTE: this does not do dependency lookups atm
function createTreeNodeStream(
  ptr,
  db,
  view,
  { gt = -1, gte = gt + 1, lte = -1, lt = lte === -1 ? -1 : lte + 1, reverse = false } = {}
) {
  const s = core.tree(ptr.dataPointer, gte, 0)
  const e = core.tree(ptr.dataPointer, lt === -1 ? Infinity : lt, 0)
  const ite = view.iterator(db, s, e, false)

  ite._readableState.map = mapTreeNode
  return ite
}

function createUserDataStream(
  ptr,
  db,
  view,
  { gt = null, gte = '', lte = null, lt = null, reverse = false } = {}
) {
  if (gt !== null || lte !== null) {
    throw new Error('gt and lte not yet supported for user data streams')
  }

  const s = core.userData(ptr.dataPointer, gte)
  const e = lt === null ? core.userDataEnd(ptr.dataPointer) : core.userData(ptr.dataPointer, lt)
  const ite = view.iterator(db, s, e, false)

  ite._readableState.map = mapUserData
  return ite
}

function createMarkStream(
  ptr,
  db,
  view,
  { gt = -1, gte = gt + 1, lte = -1, lt = lte === -1 ? -1 : lte + 1, reverse = false } = {}
) {
  const s = core.mark(ptr.dataPointer, gte)
  const e = core.mark(ptr.dataPointer, lt === -1 ? Infinity : lt)
  const ite = view.iterator(db, s, e, reverse)

  ite._readableState.map = mapMark
  return ite
}

function createLocalStream(
  ptr,
  db,
  view,
  { gt = null, gte = EMPTY, lte = null, lt = null, reverse = false } = {}
) {
  if (gt !== null || lte !== null) throw new Error('gt and lte not yet supported for local streams')

  const s = core.local(ptr.dataPointer, gte)
  const e = lt === null ? core.localEnd(ptr.dataPointer) : core.local(ptr.dataPointer, lt)
  const ite = view.iterator(db, s, e, false)

  ite._readableState.map = mapLocal
  return ite
}

function mapBitfield(data) {
  const [index, type] = core.bitfieldIndexAndType(data.key)
  if (type !== 0) return null // ignore for now
  return { index, page: data.value }
}

function mapMark(data) {
  const index = core.markKey(data.key)
  return { index, page: data.value }
}

function mapLocal(data) {
  const key = core.localKey(data.key)
  return { key, value: data.value }
}

function mapGroupUpdate(data) {
  return data.value
}

function mapUserData(data) {
  const key = core.userDataKey(data.key)
  return { key, value: data.value }
}

function mapCore(data) {
  const discoveryKey = store.discoveryKey(data.key)
  const core = CORESTORE_CORE.decode({
    start: 0,
    end: data.value.byteLength,
    buffer: data.value
  })
  return { discoveryKey, core }
}

function mapAllDiscoveryKeys(data) {
  return store.discoveryKey(data.key)
}

function mapNamespaceDiscoveryKeys(data) {
  return data.value
}

function mapAlias(data) {
  const alias = store.alias(data.key)
  return { alias, discoveryKey: data.value }
}

function mapBlock(data) {
  return { index: core.blockIndex(data.key), value: data.value }
}

function mapTreeNode(data) {
  return CORE_TREE_NODE.decode({
    start: 0,
    end: data.value.byteLength,
    buffer: data.value
  })
}
const b4a = require('b4a')
const c = require('compact-encoding')
const flat = require('flat-tree')

const schema = require('../encoding/spec/hyperschema')
const { store, core, group } = require('./keys.js')
const View = require('./view.js')

const CORESTORE_HEAD = schema.getEncoding('@corestore/head')
const CORESTORE_CORE = schema.getEncoding('@corestore/core')
const CORESTORE_GROUP = c.uint

const CORE_AUTH = schema.getEncoding('@core/auth')
const CORE_GROUP = schema.getEncoding('@core/group')
const CORE_SESSIONS = schema.getEncoding('@core/sessions')
const CORE_HEAD = schema.getEncoding('@core/head')
const CORE_TREE_NODE = schema.getEncoding('@core/tree-node')
const CORE_DEPENDENCY = schema.getEncoding('@core/dependency')
const CORE_HINTS = schema.getEncoding('@core/hints')

class CoreTX {
  constructor(core, db, view, changes) {
    if (db.snapshotted) throw new Error('Cannot open core tx on snapshot')
    this.core = core
    this.db = db
    this.view = view
    this.changes = changes
  }

  setAuth(auth) {
    this.changes.push([core.auth(this.core.corePointer), encode(CORE_AUTH, auth), null])
  }

  setSessions(sessions) {
    this.changes.push([core.sessions(this.core.corePointer), encode(CORE_SESSIONS, sessions), null])
  }

  setHead(head) {
    this.changes.push([core.head(this.core.dataPointer), encode(CORE_HEAD, head), null])
  }

  deleteHead() {
    this.changes.push([core.head(this.core.dataPointer), null, null])
  }

  setDependency(dep) {
    this.changes.push([core.dependency(this.core.dataPointer), encode(CORE_DEPENDENCY, dep), null])
  }

  setGroup(group) {
    this.changes.push([core.group(this.core.dataPointer), encode(CORE_GROUP, group), null])
  }

  deleteGroup() {
    this.changes.push([core.group(this.core.dataPointer), null, null])
  }

  setHints(hints) {
    this.changes.push([core.hints(this.core.dataPointer), encode(CORE_HINTS, hints), null])
  }

  putBlock(index, data) {
    this.changes.push([core.block(this.core.dataPointer, index), data, null])
  }

  deleteBlock(index) {
    this.changes.push([core.block(this.core.dataPointer, index), null, null])
  }

  deleteBlockRange(start, end) {
    this.changes.push([
      core.block(this.core.dataPointer, start),
      null,
      core.block(this.core.dataPointer, end === -1 ? Infinity : end)
    ])
  }

  putBitfieldPage(index, data) {
    this.changes.push([core.bitfield(this.core.dataPointer, index, 0), data, null])
  }

  deleteBitfieldPage(index) {
    this.changes.push([core.bitfield(this.core.dataPointer, index, 0), null, null])
  }

  deleteBitfieldPageRange(start, end) {
    this.changes.push([
      core.bitfield(this.core.dataPointer, start, 0),
      null,
      core.bitfield(this.core.dataPointer, end === -1 ? Infinity : end, 0)
    ])
  }

  putTreeNode(node) {
    this.changes.push([
      core.tree(this.core.dataPointer, node.index),
      encode(CORE_TREE_NODE, node),
      null
    ])
  }

  deleteTreeNode(index) {
    this.changes.push([core.tree(this.core.dataPointer, index), null, null])
  }

  deleteTreeNodeRange(start, end) {
    this.changes.push([
      core.tree(this.core.dataPointer, start),
      null,
      core.tree(this.core.dataPointer, end === -1 ? Infinity : end)
    ])
  }

  putUserData(key, value) {
    const buffer = typeof value === 'string' ? b4a.from(value) : value
    this.changes.push([core.userData(this.core.dataPointer, key), buffer, null])
  }

  deleteUserData(key) {
    this.changes.push([core.userData(this.core.dataPointer, key), null, null])
  }

  putMark(index, data) {
    this.changes.push([core.mark(this.core.dataPointer, index), data, null])
  }

  deleteMark(index) {
    this.changes.push([core.mark(this.core.dataPointer, index), null, null])
  }

  deleteMarkRange(start, end) {
    this.changes.push([
      core.mark(this.core.dataPointer, start),
      null,
      core.mark(this.core.dataPointer, end === -1 ? Infinity : end)
    ])
  }

  putLocal(key, value) {
    this.changes.push([core.local(this.core.dataPointer, key), value, null])
  }

  deleteLocal(key) {
    this.changes.push([core.local(this.core.dataPointer, key), null, null])
  }

  deleteLocalRange(start, end) {
    this.changes.push([
      core.local(this.core.dataPointer, start),
      null,
      end === null ? core.localEnd(this.core.dataPointer) : core.local(this.core.dataPointer, end)
    ])
  }

  putGroupUpdate(groupPtr, timestamp, key) {
    this.changes.push([group.entry(groupPtr, timestamp, this.core.corePointer), key, null])
  }

  deleteGroupUpdate(groupPtr, timestamp) {
    this.changes.push([group.entry(groupPtr, timestamp, this.core.corePointer), null, null])
  }

  flush() {
    const changes = this.changes
    if (changes === null) return Promise.resolve(!this.view)

    this.changes = null

    if (this.view) {
      this.view.apply(changes)
      return Promise.resolve(false)
    }

    return View.flush(changes, this.db)
  }
}

class CoreRX {
  constructor(core, db, view, treeCache, stats, fork) {
    this.core = core
    this.read = db.read({ autoDestroy: true })
    this.view = view
    this.treeCache = treeCache
    this.fork = fork
    this.stats = stats

    view.readStart()
  }

  static async getAuth(db, c) {
    return decode(CORE_AUTH, await db.get(core.auth(c.corePointer)))
  }

  async getAuth() {
    return decode(CORE_AUTH, await this.view.get(this.read, core.auth(this.core.corePointer)))
  }

  async getSessions() {
    return decode(
      CORE_SESSIONS,
      await this.view.get(this.read, core.sessions(this.core.corePointer))
    )
  }

  static async getHead(db, c) {
    return decode(CORE_HEAD, await db.get(core.head(c.dataPointer)))
  }

  async getHead() {
    return decode(CORE_HEAD, await this.view.get(this.read, core.head(this.core.dataPointer)))
  }

  async getDependency() {
    return decode(
      CORE_DEPENDENCY,
      await this.view.get(this.read, core.dependency(this.core.dataPointer))
    )
  }

  async getGroup() {
    return await decode(
      CORE_GROUP,
      await this.view.get(this.read, core.group(this.core.corePointer))
    )
  }

  static async getHints(db, c) {
    return decode(CORE_HINTS, await db.get(core.hints(c.dataPointer)))
  }

  async getHints() {
    return decode(CORE_HINTS, await this.view.get(this.read, core.hints(this.core.dataPointer)))
  }

  getBlock(index) {
    const dep = findBlockDependency(this.core.dependencies, index)
    const data = dep === null ? this.core.dataPointer : dep.dataPointer
    return this.view.get(this.read, core.block(data, index))
  }

  getBitfieldPage(index) {
    return this.view.get(this.read, core.bitfield(this.core.dataPointer, index, 0))
  }

  async _resolveTreeCache(key, promise, entry) {
    try {
      const value = decode(CORE_TREE_NODE, await promise)
      const cached = this.treeCache.get(key)

      // preflight is gone; no-op
      if (cached !== entry) return value

      if (value !== null) {
        // replace cached entry with value
        this.treeCache.set(key, { pending: null, value })
      } else {
        // discard non-existing values
        this.treeCache.delete(key)
      }

      return value
    } catch (err) {
      // cleanup
      const cached = this.treeCache.get(key)
      if (cached === entry) {
        this.treeCache.delete(key)
      }

      throw err
    }
  }

  async getTreeNode(index) {
    const dep = findTreeDependency(this.core.dependencies, index)
    const data = dep === null ? this.core.dataPointer : dep.dataPointer

    if (!this.treeCache || this.fork < 0) {
      if (this.stats !== null) this.stats.treeCache.skips++
      // no-cache
      return decode(CORE_TREE_NODE, await this.view.get(this.read, core.tree(data, index)))
    }

    const key = `${data}:${index}:${this.fork}`
    let entry = this.treeCache.get(key)
    if (entry) {
      if (entry.pending) {
        if (this.stats !== null) this.stats.treeCache.parallel++
        return entry.pending
      }

      if (this.stats !== null) this.stats.treeCache.hits++
      return entry.value
    }

    if (this.stats !== null) this.stats.treeCache.misses++

    const promise = this.view.get(this.read, core.tree(data, index))
    entry = { pending: null, value: null }
    entry.pending = this._resolveTreeCache(key, promise, entry)
    this.treeCache.set(key, entry)

    return entry.pending
  }

  async hasTreeNode(index) {
    return (await this.getTreeNode(index)) !== null
  }

  getUserData(key) {
    return this.view.get(this.read, core.userData(this.core.dataPointer, key))
  }

  getMark(index) {
    return this.view.get(this.read, core.mark(this.core.dataPointer, index))
  }

  getLocal(key) {
    return this.view.get(this.read, core.local(this.core.dataPointer, key))
  }

  tryFlush() {
    this.read.tryFlush()
    this._free()
  }

  destroy() {
    this.read.destroy()
    this._free()
  }

  _free() {
    if (this.view === null) return
    this.view.readStop()
    this.view = null
  }
}

class CorestoreTX {
  constructor(view) {
    this.view = view
    this.changes = []
  }

  setHead(head) {
    this.changes.push([store.head(), encode(CORESTORE_HEAD, head), null])
  }

  setCoreHints(c, hints) {
    this.changes.push([core.hints(c.dataPointer), encode(CORE_HINTS, hints), null])
  }

  putCore(discoveryKey, ptr) {
    this.changes.push([store.core(discoveryKey), encode(CORESTORE_CORE, ptr), null])
  }

  putCoreByAlias(alias, discoveryKey) {
    this.changes.push([store.coreByAlias(alias), discoveryKey, null])
  }

  putGroup(topic, groupPtr) {
    this.changes.push([group.topic(topic), encode(CORESTORE_GROUP, groupPtr), null])
  }

  deleteGroup(topic) {
    this.changes.push([group.topic(topic), null, null])
  }

  clear() {
    const [start, end] = store.clear()
    this.changes.push([start, null, end])
  }

  apply() {
    if (this.changes === null) return
    this.view.apply(this.changes)
    this.changes = null
  }
}

class CorestoreRX {
  constructor(db, view) {
    this.read = db.read({ autoDestroy: true })
    this.view = view

    view.readStart()
  }

  async getHeadRaw(db) {
    return await this.view.get(this.read, store.head())
  }

  async getHead() {
    return decode(CORESTORE_HEAD, await this.view.get(this.read, store.head()))
  }

  async getCore(discoveryKey) {
    return decode(CORESTORE_CORE, await this.view.get(this.read, store.core(discoveryKey)))
  }

  getCoreByAlias(alias) {
    return this.view.get(this.read, store.coreByAlias(alias))
  }

  async getGroup(topic) {
    return decode(CORESTORE_GROUP, await this.view.get(this.read, group.topic(topic)))
  }

  tryFlush() {
    this.read.tryFlush()
    this._free()
  }

  destroy() {
    this.read.destroy()
    this._free()
  }

  _free() {
    if (this.view === null) return
    this.view.readStop()
    this.view = null
  }
}

module.exports = { CorestoreTX, CorestoreRX, CoreTX, CoreRX }

function findBlockDependency(dependencies, index) {
  for (let i = 0; i < dependencies.length; i++) {
    const dep = dependencies[i]
    if (index < dep.length) return dep
  }

  return null
}

function findTreeDependency(dependencies, index) {
  for (let i = 0; i < dependencies.length; i++) {
    const dep = dependencies[i]
    if (flat.rightSpan(index) <= (dep.length - 1) * 2) return dep
  }

  return null
}

function decode(enc, buffer) {
  if (buffer === null) return null
  return enc.decode({ start: 0, end: buffer.byteLength, buffer })
}

function encode(enc, m) {
  // TODO: use fancy slab for small messages
  const state = { start: 0, end: 0, buffer: null }
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}
const { Readable, getStreamError } = require('streamx')
const CloseErrorStream = require('./close-error-stream.js')
const b4a = require('b4a')

class OverlayStream extends Readable {
  constructor(stream, start, end, reverse, changes, cleared) {
    super()

    this.start = start
    this.end = end
    this.reverse = reverse
    this.changes = changes
    this.cleared = cleared
    this.change = 0
    this.range = 0

    this._stream = stream
    this._drained = false

    this._stream.on('readable', this._drainMaybe.bind(this))
    this._stream.on('error', noop)
    this._stream.on('close', this._onclose.bind(this))
  }

  _drainMaybe() {
    if (this._drained === true) return
    this._drained = this._onreadable()
  }

  _onclose() {
    if (this.destroying) return

    const err = getStreamError(this._stream)

    if (err !== null) {
      this.destroy(err)
      return
    }

    while (this.change < this.changes.length) {
      const c = this.changes[this.change++]
      const key = c[0]
      const value = c[1]

      if (value !== null && this._inRange(key)) this.push({ key, value })
    }

    this.push(null)
    this._stream = null
  }

  _onreadable() {
    let data = this._stream.read()
    if (data === null) return false

    let drained = false

    do {
      if (this._push(data) === true) drained = true
      data = this._stream.read()
    } while (data !== null)

    return drained
  }

  _read(cb) {
    this._drained = this._onreadable()
    cb(null)
  }

  _predestroy() {
    this._stream.destroy()
  }

  _push(entry) {
    const key = entry.key

    while (this.range < this.cleared.length) {
      const c = this.cleared[this.range]

      // we moved past the range
      if (this.reverse ? b4a.compare(key, c[0]) < 0 : b4a.compare(c[2], key) <= 0) {
        this.range++
        continue
      }

      // we didnt move past and are in, drop
      if (b4a.compare(c[0], key) <= 0 && b4a.compare(key, c[2]) < 0) {
        return false
      }

      break
    }

    let updated = false

    while (this.change < this.changes.length) {
      const c = this.changes[this.change]
      const key = c[0]
      const value = typeof c[1] === 'string' ? b4a.from(c[1]) : c[1]
      const cmp = b4a.compare(key, entry.key)

      // same value, if not deleted, return new one
      if (cmp === 0) {
        this.change++
        if (value === null || this._inRange(key) === false) return updated
        this.push({ key, value })
        return true
      }

      // we moved past the change, push it
      if (this.reverse ? cmp > 0 : cmp < 0) {
        this.change++
        if (value === null || this._inRange(key) === false) continue
        this.push({ key, value })
        updated = true
        continue
      }

      this.push(entry)
      return true
    }

    this.push(entry)
    return true
  }

  _inRange(key) {
    return b4a.compare(this.start, key) <= 0 && b4a.compare(key, this.end) < 0
  }
}

class Overlay {
  constructor() {
    this.indexed = 0
    this.changes = null
    this.cleared = null
    this.reverse = false
  }

  update(view, reverse) {
    if (view.indexed === this.indexed) return

    const changes = view.map === null ? [] : [...view.map.values()]
    const cleared = view.cleared === null ? [] : view.cleared.slice(0)

    const cmp = reverse ? cmpChangeReverse : cmpChange

    changes.sort(cmp)
    cleared.sort(cmp)

    this.indexed = view.indexed
    this.changes = changes
    this.cleared = cleared
    this.reverse = reverse
  }

  createStream(stream, start, end, reverse) {
    return new OverlayStream(
      stream,
      start,
      end,
      reverse,
      this.reverse === reverse ? this.changes : reverseArray(this.changes),
      this.reverse === reverse ? this.cleared : reverseArray(this.cleared)
    )
  }
}

class View {
  constructor() {
    this.map = null
    this.indexed = 0
    this.changes = null
    this.cleared = null
    this.overlay = null
    this.snap = null
    this.readers = 0
  }

  snapshot() {
    if (this._attached()) return this.snap.snapshot()

    const snap = new View()

    snap.map = this.map
    snap.indexed = this.indexed
    snap.changes = this.changes
    snap.cleared = this.cleared

    if (this._frozen()) return snap

    this.readers++
    snap.snap = this

    return snap
  }

  readStart() {
    if (this.snap !== null) this.readers++
  }

  readStop() {
    if (this.snap !== null && --this.readers === 0) this.snap.readers--
  }

  size() {
    return this.changes === null ? 0 : this.changes.length
  }

  updated() {
    return this.changes === null
  }

  get(read, key) {
    return this.changes === null ? read.get(key) : this._indexAndGet(read, key)
  }

  reset() {
    this.indexed = 0
    this.snap = this.map = this.changes = this.cleared = this.overlay = null
  }

  iterator(db, start, end, reverse) {
    if (dbClosing(db)) return new CloseErrorStream(new Error('RocksDB session is closed'))

    const stream = db.iterator({ gte: start, lt: end, reverse })
    if (this.changes === null) return stream

    this._index()

    if (this.overlay === null) this.overlay = new Overlay()
    this.overlay.update(this, reverse)
    return this.overlay.createStream(stream, start, end, reverse)
  }

  _indexAndGet(read, key) {
    this._index()
    const change = this.map.get(b4a.toString(key, 'hex'))

    if (change === undefined) {
      return this.cleared === null ? read.get(key) : this._readAndMaybeDrop(read, key)
    }

    return Promise.resolve(change[1])
  }

  async _readAndMaybeDrop(read, key) {
    const cleared = this.cleared // in case its cleared
    const value = await read.get(key)
    if (value === null) return null

    for (let i = 0; i < cleared.length; i++) {
      const c = cleared[i]
      // check if in range
      if (b4a.compare(c[0], key) <= 0 && b4a.compare(key, c[2]) < 0) return null
    }

    return value
  }

  _attached() {
    return this.snap !== null && this.changes === this.snap.changes
  }

  _frozen() {
    return this.changes === null || (this.snap !== null && this.changes !== this.snap.changes)
  }

  _index() {
    // if we are a snap and we are still attached (ie no mutations), simply copy the refs
    if (this._attached()) {
      this.snap._index()
      this.map = this.snap.map
      this.cleared = this.snap.cleared
      this.indexed = this.snap.indexed
      return
    }

    if (this.map === null) this.map = new Map()
    if (this.changes.length === this.indexed) return

    while (this.indexed < this.changes.length) {
      const c = this.changes[this.indexed++]

      if (c[2] === null) this.map.set(b4a.toString(c[0], 'hex'), c)
      else this._indexRange(c)
    }
  }

  _indexRange(range) {
    const s = b4a.toString(range[0], 'hex')
    const e = b4a.toString(range[2], 'hex')

    for (const [key, c] of this.map) {
      if (s <= key && key < e) this.map.set(key, [c[0], null, null])
    }

    if (this.cleared === null) this.cleared = []
    this.cleared.push(range)
  }

  apply(changes) {
    if (this.snap !== null) throw new Error('Illegal to push changes to a snapshot')

    if (this.readers !== 0 && this.changes !== null) {
      this.changes = this.changes.slice(0)
      this.cleared = this.cleared === null ? null : this.cleared.slice(0)
      this.map = this.map === null ? null : new Map([...this.map])
    }

    if (this.changes === null) {
      this.changes = changes
      return
    }

    for (let i = 0; i < changes.length; i++) {
      this.changes.push(changes[i])
    }
  }

  static async flush(changes, db) {
    if (changes === null) return true

    const w = db.write({ autoDestroy: true })

    for (const [start, value, end] of changes) {
      if (end !== null) w.tryDeleteRange(start, end)
      else if (value !== null) w.tryPut(start, value)
      else w.tryDelete(start)
    }

    await w.flush()

    return true
  }
}

module.exports = View

function cmpChange(a, b) {
  const c = b4a.compare(a[0], b[0])
  return c === 0 ? b4a.compare(a[2], b[2]) : c
}

function cmpChangeReverse(a, b) {
  return cmpChange(b, a)
}

function noop() {}

function reverseArray(list) {
  const r = new Array(list.length)
  for (let i = 0; i < list.length; i++) r[r.length - 1 - i] = list[i]
  return r
}

// TODO: expose from rocks instead
function dbClosing(db) {
  return db._state.closing || db._index === -1
}
const fs = require('fs')
const path = require('path')
const { Readable } = require('streamx')
const b4a = require('b4a')
const flat = require('flat-tree')
const crypto = require('hypercore-crypto')
const c = require('compact-encoding')
const m = require('./messages.js')
const View = require('../../lib/view.js')
const { CorestoreTX, CoreTX, CorestoreRX } = require('../../lib/tx.js')

const EMPTY_NODE = b4a.alloc(40)
const EMPTY_PAGE = b4a.alloc(4096)

let TREE_01_SKIP = null
let TREE_04_SKIP = null
let TREE_16_SKIP = null

class CoreListStream extends Readable {
  constructor (storage) {
    super()

    this.storage = storage
    this.stack = []
  }

  async _open (cb) {
    for (const a of await readdir(path.join(this.storage, 'cores'))) {
      for (const b of await readdir(path.join(this.storage, 'cores', a))) {
        for (const dkey of await readdir(path.join(this.storage, 'cores', a, b))) {
          this.stack.push(path.join(this.storage, 'cores', a, b, dkey))
        }
      }
    }

    cb(null)
  }

  async _read (cb) {
    while (true) {
      const next = this.stack.pop()
      if (!next) {
        this.push(null)
        break
      }

      const oplog = path.join(next, 'oplog')
      const result = await readOplog(oplog)
      if (!result) continue

      this.push(result)
      break
    }

    cb(null)
  }
}

function decodeOplogHeader (state) {
  c.uint32.decode(state) // cksum, ignore for now

  const l = c.uint32.decode(state)
  const length = l >> 2
  const headerBit = l & 1
  const partialBit = l & 2

  if (state.end - state.start < length) return null

  const end = state.start + length
  const result = { header: headerBit, partial: partialBit !== 0, byteLength: length + 8, message: null }

  try {
    result.message = m.oplog.header.decode({ start: state.start, end, buffer: state.buffer })
  } catch {
    return null
  }

  state.start = end
  return result
}

function decodeOplogEntry (state) {
  if (state.end - state.start < 8) return null

  c.uint32.decode(state) // cksum, ignore for now

  const l = c.uint32.decode(state)
  const length = l >>> 2
  const headerBit = l & 1
  const partialBit = l & 2

  if (state.end - state.start < length) return null

  const end = state.start + length

  const result = { header: headerBit, partial: partialBit !== 0, byteLength: length + 8, message: null }

  try {
    result.message = m.oplog.entry.decode({ start: state.start, end, buffer: state.buffer })
  } catch {
    return null
  }

  state.start = end

  return result
}

module.exports = { store, core }

async function store (storage, { version, dryRun = true, gc = true }) {
  const stream = new CoreListStream(storage.path)
  const view = new View()

  const tx = new CorestoreTX(view)
  const head = await storage._getHead(view)
  const primaryKeyFile = path.join(storage.path, 'primary-key')

  const primaryKey = await readFile(primaryKeyFile)

  if (!head.seed) head.seed = primaryKey

  for await (const data of stream) {
    const key = data.header.key
    const discoveryKey = crypto.discoveryKey(data.header.key)
    const files = getFiles(data.path)

    if (head.defaultDiscoveryKey === null) head.defaultDiscoveryKey = discoveryKey

    const core = {
      version: 0, // need later migration
      corePointer: head.allocated.cores++,
      dataPointer: head.allocated.datas++,
      alias: null
    }

    const ptr = { version: 0, corePointer: core.corePointer, dataPointer: core.dataPointer, dependencies: [] }
    const ctx = new CoreTX(ptr, storage.db, view, [])
    const userData = new Map()
    const treeNodes = new Map()

    const auth = {
      key,
      discoveryKey,
      manifest: data.header.manifest,
      keyPair: data.header.keyPair,
      encryptionKey: null
    }

    const tree = {
      length: 0,
      fork: 0,
      rootHash: null,
      signature: null
    }

    if (data.header.tree && data.header.tree.length) {
      tree.length = data.header.tree.length
      tree.fork = data.header.tree.fork
      tree.rootHash = data.header.tree.rootHash
      tree.signature = data.header.tree.signature
    }

    for (const { key, value } of data.header.userData) {
      userData.set(key, value)
    }

    for (const e of data.entries) {
      if (e.userData) userData.set(e.userData.key, e.userData.value)

      if (e.treeNodes) {
        for (const node of e.treeNodes) {
          treeNodes.set(node.index, node)
          ctx.putTreeNode(node)
        }
      }

      if (e.treeUpgrade) {
        if (e.treeUpgrade.ancestors !== tree.length) {
          throw new Error('Unflushed truncations not migrate-able atm')
        }

        tree.length = e.treeUpgrade.length
        tree.fork = e.treeUpgrade.fork
        tree.rootHash = null
        tree.signature = e.treeUpgrade.signature
      }
    }

    if (userData.has('corestore/name') && userData.has('corestore/namespace')) {
      core.alias = {
        name: b4a.toString(userData.get('corestore/name')),
        namespace: userData.get('corestore/namespace')
      }
      userData.delete('corestore/name')
      userData.delete('corestore/namespace')
    }

    for (const [key, value] of userData) {
      ctx.putUserData(key, value)
    }

    ctx.setAuth(auth)

    const getTreeNode = (index) => (treeNodes.get(index) || getTreeNodeFromFile(files.tree, index))

    if (tree.length) {
      if (tree.rootHash === null) tree.rootHash = crypto.tree(await getRoots(tree.length, getTreeNode))
      ctx.setHead(tree)
    }

    tx.putCore(discoveryKey, core)
    if (core.alias) tx.putCoreByAlias(core.alias, discoveryKey)

    await ctx.flush()
  }

  head.version = version
  tx.setHead(head)
  tx.apply()

  if (dryRun) return

  await View.flush(view.changes, storage.db)

  if (gc) await rm(primaryKeyFile)
}

class BlockSlicer {
  constructor (filename) {
    this.stream = fs.createReadStream(filename)
    this.closed = new Promise(resolve => this.stream.once('close', resolve))
    this.offset = 0
    this.overflow = null
  }

  async take (offset, size) {
    let buffer = null
    if (offset < this.offset) throw new Error('overread')

    while (true) {
      let data = null

      if (this.overflow) {
        data = this.overflow
        this.overflow = null
      } else {
        data = this.stream.read()

        if (!data) {
          await new Promise(resolve => this.stream.once('readable', resolve))
          continue
        }
      }

      let chunk = null

      if (this.offset === offset || buffer) {
        chunk = data
      } else if (this.offset + data.byteLength > offset) {
        chunk = data.subarray(offset - this.offset)
      }

      this.offset += data.byteLength
      if (!chunk) continue

      if (buffer) buffer = b4a.concat([buffer, chunk])
      else buffer = chunk

      if (buffer.byteLength < size) continue

      const result = buffer.subarray(0, size)
      this.overflow = size === buffer.byteLength ? null : buffer.subarray(result.byteLength)
      this.offset -= (this.overflow ? this.overflow.byteLength : 0)
      return result
    }
  }

  close () {
    this.stream.on('error', noop)
    this.stream.destroy()
    return this.closed
  }
}

class TreeSlicer {
  constructor () {
    this.buffer = null
    this.offset = 0
  }

  get size () {
    return this.buffer === null ? 0 : this.buffer.byteLength
  }

  push (data) {
    if (this.buffer === null) this.buffer = data
    else this.buffer = b4a.concat([this.buffer, data])
    this.offset += data.byteLength
  }

  skip () {
    let skipped = 0

    if (TREE_01_SKIP === null) {
      TREE_16_SKIP = b4a.alloc(16 * 40 * 100)
      TREE_04_SKIP = TREE_16_SKIP.subarray(0, 4 * 40 * 100)
      TREE_01_SKIP = TREE_16_SKIP.subarray(0, 1 * 40 * 100)
    }

    while (true) {
      if (this.buffer.byteLength >= TREE_16_SKIP.byteLength) {
        if (b4a.equals(this.buffer.subarray(0, TREE_16_SKIP.byteLength), TREE_16_SKIP)) {
          this.buffer = this.buffer.subarray(TREE_16_SKIP.byteLength)
          skipped += 1600
          continue
        }
      }

      if (this.buffer.byteLength >= TREE_04_SKIP.byteLength) {
        if (b4a.equals(this.buffer.subarray(0, TREE_04_SKIP.byteLength), TREE_04_SKIP)) {
          this.buffer = this.buffer.subarray(TREE_04_SKIP.byteLength)
          skipped += 400
          continue
        }
      }

      if (this.buffer.byteLength >= TREE_01_SKIP.byteLength) {
        if (b4a.equals(this.buffer.subarray(0, TREE_01_SKIP.byteLength), TREE_01_SKIP)) {
          this.buffer = this.buffer.subarray(TREE_01_SKIP.byteLength)
          skipped += 100
          continue
        }
      }
      break
    }

    return skipped
  }

  take () {
    const len = 40

    if (len <= this.size) {
      const chunk = this.buffer.subarray(0, len)
      this.buffer = this.buffer.subarray(len)
      return chunk
    }

    return null
  }
}

async function core (core, { version, dryRun = true, gc = true }) {
  if (dryRun) return // dryRun mode not supported atm

  const rx = core.read()

  const promises = [rx.getAuth(), rx.getHead()]
  rx.tryFlush()

  const [auth, head] = await Promise.all(promises)

  if (!auth) return

  const dk = b4a.toString(auth.discoveryKey, 'hex')
  const files = getFiles(path.join(core.store.path, 'cores', dk.slice(0, 2), dk.slice(2, 4), dk))

  if (head === null || head.length === 0) {
    await commitCoreMigration(auth, core, version)
    if (gc) await runGC()
    return // no data
  }

  const oplog = await readOplog(files.oplog)
  if (!oplog) {
    const writable = !!auth.keyPair

    if (writable) {
      throw new Error('No oplog available writable core for ' + files.oplog + ', length = ' + (head ? head.length : 0))
    }

    // if not writable, just nuke it to recover, some bad state happened here, prop corruption from earlier versions
    const w = core.write()

    w.deleteBlockRange(0, -1)
    w.deleteTreeNodeRange(0, -1)
    w.deleteBitfieldPageRange(0, -1)
    w.deleteHead()

    await w.flush()

    await commitCoreMigration(auth, core, version)
    if (gc) await runGC()
    return // no data
  }

  const treeData = new TreeSlicer()

  let treeIndex = 0

  if (await exists(files.tree)) {
    for await (const data of fs.createReadStream(files.tree)) {
      treeData.push(data)

      let write = null

      while (true) {
        const skip = treeData.skip()
        treeIndex += skip

        const buf = treeData.take()
        if (buf === null) break

        const index = treeIndex++
        if (b4a.equals(buf, EMPTY_NODE)) continue

        if (write === null) write = core.write()
        write.putTreeNode(decodeTreeNode(index, buf))
      }

      if (write !== null) await write.flush()
    }
  }

  const buf = []
  if (await exists(files.bitfield)) {
    for await (const data of fs.createReadStream(files.bitfield)) {
      buf.push(data)
    }
  }

  let bitfield = b4a.concat(buf)
  if (bitfield.byteLength & 4095) bitfield = b4a.concat([bitfield, b4a.alloc(4096 - (bitfield.byteLength & 4095))])

  const pages = new Map()
  const headerBits = new Map()

  const roots = await getRootsFromStorage(core, head.length)

  for (const e of oplog.entries) {
    if (!e.bitfield) continue

    for (let i = 0; i < e.bitfield.length; i++) {
      headerBits.set(i + e.bitfield.start, !e.bitfield.drop)
    }
  }

  let batch = []

  const cache = new Map()
  const blocks = new BlockSlicer(files.data)

  for (const index of allBits(bitfield)) {
    if (headerBits.get(index) === false) continue
    if (index >= head.length) continue

    setBitInPage(index)

    batch.push(index)
    if (batch.length < 1024) continue

    await writeBlocksBatch()
    continue
  }

  if (batch.length) await writeBlocksBatch()

  await blocks.close()

  const w = core.write()

  for (const [index, bit] of headerBits) {
    if (!bit) continue
    if (index >= head.length) continue

    setBitInPage(index)

    const blk = await getBlockFromFile(files.data, core, index, roots, cache)
    w.putBlock(index, blk)
  }

  for (const [index, page] of pages) {
    w.putBitfieldPage(index, b4a.from(page.buffer, page.byteOffset, page.byteLength))
  }

  await w.flush()

  let contiguousLength = 0
  for await (const data of core.createBlockStream()) {
    if (data.index === contiguousLength) contiguousLength++
    else break
  }

  if (contiguousLength) {
    const w = core.write()
    w.setHints({ contiguousLength })
    await w.flush()
  }

  await commitCoreMigration(auth, core, version)

  if (gc) await runGC()

  async function runGC () {
    await rm(files.path)
    await rmdir(path.join(files.path, '..'))
    await rmdir(path.join(files.path, '../..'))
    await rmdir(path.join(core.store.path, 'cores'))
  }

  function setBitInPage (index) {
    const n = index & 32767
    const p = (index - n) / 32768

    let page = pages.get(p)

    if (!page) {
      page = new Uint32Array(1024)
      pages.set(p, page)
    }

    const o = n & 31
    const b = (n - o) / 32
    const v = 1 << o

    page[b] |= v
  }

  async function writeBlocksBatch () {
    const read = core.read()
    const promises = []
    for (const index of batch) promises.push(getByteRangeFromStorage(read, 2 * index, roots, cache))
    read.tryFlush()

    const r = await Promise.all(promises)
    const tx = core.write()

    for (let i = 0; i < r.length; i++) {
      const index = batch[i]
      const [offset, size] = r[i]

      const blk = await blocks.take(offset, size)
      tx.putBlock(index, blk)
    }

    batch = []
    if (cache.size > 16384) cache.clear()

    await tx.flush()
  }
}

async function commitCoreMigration (auth, core, version) {
  const view = new View()
  const rx = new CorestoreRX(core.db, view)

  const storeCorePromise = rx.getCore(auth.discoveryKey)
  rx.tryFlush()

  const storeCore = await storeCorePromise

  storeCore.version = version

  const tx = new CorestoreTX(view)

  tx.putCore(auth.discoveryKey, storeCore)
  tx.apply()

  await View.flush(view.changes, core.db)
}

async function getBlockFromFile (file, core, index, roots, cache) {
  const rx = core.read()
  const promise = getByteRangeFromStorage(rx, 2 * index, roots, cache)
  rx.tryFlush()
  const [offset, size] = await promise

  return new Promise(function (resolve) {
    readAll(file, size, offset, function (err, buf) {
      if (err) return resolve(null)
      resolve(buf)
    })
  })
}

function getFiles (dir) {
  return {
    path: dir,
    oplog: path.join(dir, 'oplog'),
    data: path.join(dir, 'data'),
    tree: path.join(dir, 'tree'),
    bitfield: path.join(dir, 'bitfield')
  }
}

async function getRootsFromStorage (core, length) {
  const all = []
  const rx = core.read()
  for (const index of flat.fullRoots(2 * length)) {
    all.push(rx.getTreeNode(index))
  }
  rx.tryFlush()
  return Promise.all(all)
}

async function getRoots (length, getTreeNode) {
  const all = []
  for (const index of flat.fullRoots(2 * length)) {
    all.push(await getTreeNode(index))
  }
  return all
}

function getCached (read, cache, index) {
  if (cache.has(index)) return cache.get(index)
  const p = read.getTreeNode(index)
  cache.set(index, p)
  return p
}

async function getByteRangeFromStorage (read, index, roots, cache) {
  const promises = [getCached(read, cache, index), getByteOffsetFromStorage(read, index, roots, cache)]
  const [node, offset] = await Promise.all(promises)
  if (!node) throw new Error('Node not found during migration: ' + index)
  return [offset, node.size]
}

async function getByteOffsetFromStorage (rx, index, roots, cache) {
  if (index === 0) return 0
  if ((index & 1) === 1) index = flat.leftSpan(index)

  let head = 0
  let offset = 0

  for (const node of roots) { // all async ticks happen once we find the root so safe
    head += 2 * ((node.index - head) + 1)

    if (index >= head) {
      offset += node.size
      continue
    }

    const ite = flat.iterator(node.index)
    const promises = []

    while (ite.index !== index) {
      if (index < ite.index) {
        ite.leftChild()
      } else {
        promises.push(getCached(rx, cache, ite.leftChild()))
        ite.sibling()
      }
    }

    const nodes = await Promise.all(promises)
    for (const node of nodes) offset += node.size

    return offset
  }

  throw new Error('Failed to find offset')
}

function decodeTreeNode (index, buf) {
  return { index, size: c.decode(c.uint64, buf), hash: buf.subarray(8) }
}

async function getTreeNodeFromFile (file, index) {
  return new Promise(function (resolve) {
    readAll(file, 40, index * 40, function (err, buf) {
      if (err) return resolve(null)
      resolve(decodeTreeNode(index, buf))
    })
  })
}

function readAll (filename, length, pos, cb) {
  const buf = b4a.alloc(length)

  fs.open(filename, 'r', function (err, fd) {
    if (err) return cb(err)

    let offset = 0

    fs.read(fd, buf, offset, buf.byteLength, pos, function loop (err, read) {
      if (err) return done(err)
      if (read === 0) return done(new Error('Partial read'))
      offset += read
      if (offset === buf.byteLength) return done(null, buf)
      fs.read(fd, offset, buf.byteLength - offset, buf, pos + offset, loop)
    })

    function done (err, value) {
      fs.close(fd, () => cb(err, value))
    }
  })
}

async function readdir (dir) {
  try {
    return await fs.promises.readdir(dir)
  } catch {
    return []
  }
}

async function exists (file) {
  try {
    await fs.promises.stat(file)
    return true
  } catch {
    return false
  }
}

async function readFile (file) {
  try {
    return await fs.promises.readFile(file)
  } catch {
    return null
  }
}

async function rm (dir) {
  try {
    await fs.promises.rm(dir, { recursive: true })
  } catch {}
}

async function rmdir (dir) {
  try {
    await fs.promises.rmdir(dir)
  } catch {}
}

function * allBits (buffer) {
  for (let i = 0; i < buffer.byteLength; i += EMPTY_PAGE.byteLength) {
    const page = buffer.subarray(i, i + EMPTY_NODE.byteLength)
    if (b4a.equals(page, EMPTY_PAGE)) continue

    const view = new Uint32Array(page.buffer, page.byteOffset, EMPTY_PAGE.byteLength / 4)

    for (let j = 0; j < view.length; j++) {
      const n = view[j]
      if (n === 0) continue

      for (let k = 0; k < 32; k++) {
        const m = 1 << k
        if (n & m) yield i * 8 + j * 32 + k
      }
    }
  }
}

function readOplog (oplog) {
  return new Promise(function (resolve) {
    fs.readFile(oplog, function (err, buffer) {
      if (err) return resolve(null)

      const state = { start: 0, end: buffer.byteLength, buffer }
      const headers = [1, 0]

      const h1 = decodeOplogHeader(state)
      state.start = 4096

      const h2 = decodeOplogHeader(state)
      state.start = 4096 * 2

      if (!h1 && !h2) return resolve(null)

      if (h1 && !h2) {
        headers[0] = h1.header
        headers[1] = h1.header
      } else if (!h1 && h2) {
        headers[0] = (h2.header + 1) & 1
        headers[1] = h2.header
      } else {
        headers[0] = h1.header
        headers[1] = h2.header
      }

      const header = (headers[0] + headers[1]) & 1
      const result = { path: path.dirname(oplog), header: null, entries: [] }
      const decoded = []

      result.header = header ? h2.message : h1.message

      if (result.header.external) {
        fs.readFile(path.join(oplog, '../header'), function (err, buffer) {
          if (err) return resolve(null)
          const start = result.header.external.start
          const end = start + result.header.external.length
          result.header = m.oplog.header.decode({ buffer, start, end })
          finish()
        })
        return
      }

      finish()

      function finish () {
        while (true) {
          const entry = decodeOplogEntry(state)
          if (!entry) break
          if (entry.header !== header) break

          decoded.push(entry)
        }

        while (decoded.length > 0 && decoded[decoded.length - 1].partial) decoded.pop()

        for (const e of decoded) {
          result.entries.push(e.message)
        }

        resolve(result)
      }
    })
  })
}

function noop () {}
// needed here for compat, copied from old hypercore, do not change this

const c = require('compact-encoding')
const b4a = require('b4a')

const EMPTY = b4a.alloc(0)
const DEFAULT_NAMESPACE = b4a.from('4144eea531e483d54e0c14f4ca68e0644f355343ff6fcb0f005200e12cd747cb', 'hex')

const hashes = {
  preencode (state, m) {
    state.end++ // small uint
  },
  encode (state, m) {
    if (m === 'blake2b') {
      c.uint.encode(state, 0)
      return
    }

    throw new Error('Unknown hash: ' + m)
  },
  decode (state) {
    const n = c.uint.decode(state)
    if (n === 0) return 'blake2b'
    throw new Error('Unknown hash id: ' + n)
  }
}

const signatures = {
  preencode (state, m) {
    state.end++ // small uint
  },
  encode (state, m) {
    if (m === 'ed25519') {
      c.uint.encode(state, 0)
      return
    }

    throw new Error('Unknown signature: ' + m)
  },
  decode (state) {
    const n = c.uint.decode(state)
    if (n === 0) return 'ed25519'
    throw new Error('Unknown signature id: ' + n)
  }
}

const signer = {
  preencode (state, m) {
    signatures.preencode(state, m.signature)
    c.fixed32.preencode(state, m.namespace)
    c.fixed32.preencode(state, m.publicKey)
  },
  encode (state, m) {
    signatures.encode(state, m.signature)
    c.fixed32.encode(state, m.namespace)
    c.fixed32.encode(state, m.publicKey)
  },
  decode (state) {
    return {
      signature: signatures.decode(state),
      namespace: c.fixed32.decode(state),
      publicKey: c.fixed32.decode(state)
    }
  }
}

const signerArray = c.array(signer)

const prologue = {
  preencode (state, p) {
    c.fixed32.preencode(state, p.hash)
    c.uint.preencode(state, p.length)
  },
  encode (state, p) {
    c.fixed32.encode(state, p.hash)
    c.uint.encode(state, p.length)
  },
  decode (state) {
    return {
      hash: c.fixed32.decode(state),
      length: c.uint.decode(state)
    }
  }
}

const manifestv0 = {
  preencode (state, m) {
    hashes.preencode(state, m.hash)
    state.end++ // type

    if (m.prologue && m.signers.length === 0) {
      c.fixed32.preencode(state, m.prologue.hash)
      return
    }

    if (m.quorum === 1 && m.signers.length === 1 && !m.allowPatch) {
      signer.preencode(state, m.signers[0])
    } else {
      state.end++ // flags
      c.uint.preencode(state, m.quorum)
      signerArray.preencode(state, m.signers)
    }
  },
  encode (state, m) {
    hashes.encode(state, m.hash)

    if (m.prologue && m.signers.length === 0) {
      c.uint.encode(state, 0)
      c.fixed32.encode(state, m.prologue.hash)
      return
    }

    if (m.quorum === 1 && m.signers.length === 1 && !m.allowPatch) {
      c.uint.encode(state, 1)
      signer.encode(state, m.signers[0])
    } else {
      c.uint.encode(state, 2)
      c.uint.encode(state, m.allowPatch ? 1 : 0)
      c.uint.encode(state, m.quorum)
      signerArray.encode(state, m.signers)
    }
  },
  decode (state) {
    const hash = hashes.decode(state)
    const type = c.uint.decode(state)

    if (type > 2) throw new Error('Unknown type: ' + type)

    if (type === 0) {
      return {
        version: 0,
        hash,
        allowPatch: false,
        quorum: 0,
        signers: [],
        prologue: {
          hash: c.fixed32.decode(state),
          length: 0
        }
      }
    }

    if (type === 1) {
      return {
        version: 0,
        hash,
        allowPatch: false,
        quorum: 1,
        signers: [signer.decode(state)],
        prologue: null
      }
    }

    const flags = c.uint.decode(state)

    return {
      version: 0,
      hash,
      allowPatch: (flags & 1) !== 0,
      quorum: c.uint.decode(state),
      signers: signerArray.decode(state),
      prologue: null
    }
  }
}

const manifest = exports.manifest = {
  preencode (state, m) {
    state.end++ // version
    if (m.version === 0) return manifestv0.preencode(state, m)

    state.end++ // flags
    hashes.preencode(state, m.hash)

    c.uint.preencode(state, m.quorum)
    signerArray.preencode(state, m.signers)
    if (m.prologue) prologue.preencode(state, m.prologue)
  },
  encode (state, m) {
    c.uint.encode(state, m.version)
    if (m.version === 0) return manifestv0.encode(state, m)

    c.uint.encode(state, (m.allowPatch ? 1 : 0) | (m.prologue ? 2 : 0) | (m.unencrypted ? 4 : 0))
    hashes.encode(state, m.hash)

    c.uint.encode(state, m.quorum)
    signerArray.encode(state, m.signers)
    if (m.prologue) prologue.encode(state, m.prologue)
  },
  decode (state) {
    const v = c.uint.decode(state)
    if (v === 0) return manifestv0.decode(state)
    if (v !== 1) throw new Error('Unknown version: ' + v)

    const flags = c.uint.decode(state)
    const hash = hashes.decode(state)
    const quorum = c.uint.decode(state)
    const signers = signerArray.decode(state)
    const unencrypted = (flags & 4) !== 0

    return {
      version: 1,
      hash,
      allowPatch: (flags & 1) !== 0,
      quorum,
      signers,
      prologue: (flags & 2) === 0 ? null : prologue.decode(state),
      unencrypted
    }
  }
}

const node = {
  preencode (state, n) {
    c.uint.preencode(state, n.index)
    c.uint.preencode(state, n.size)
    c.fixed32.preencode(state, n.hash)
  },
  encode (state, n) {
    c.uint.encode(state, n.index)
    c.uint.encode(state, n.size)
    c.fixed32.encode(state, n.hash)
  },
  decode (state) {
    return {
      index: c.uint.decode(state),
      size: c.uint.decode(state),
      hash: c.fixed32.decode(state)
    }
  }
}

const nodeArray = c.array(node)

const wire = exports.wire = {}

wire.handshake = {
  preencode (state, m) {
    c.uint.preencode(state, 1)
    c.fixed32.preencode(state, m.capability)
  },
  encode (state, m) {
    c.uint.encode(state, m.seeks ? 1 : 0)
    c.fixed32.encode(state, m.capability)
  },
  decode (state) {
    const flags = c.uint.decode(state)
    return {
      seeks: (flags & 1) !== 0,
      capability: c.fixed32.decode(state)
    }
  }
}

const requestBlock = {
  preencode (state, b) {
    c.uint.preencode(state, b.index)
    c.uint.preencode(state, b.nodes)
  },
  encode (state, b) {
    c.uint.encode(state, b.index)
    c.uint.encode(state, b.nodes)
  },
  decode (state) {
    return {
      index: c.uint.decode(state),
      nodes: c.uint.decode(state)
    }
  }
}

const requestSeek = {
  preencode (state, s) {
    c.uint.preencode(state, s.bytes)
    c.uint.preencode(state, s.padding)
  },
  encode (state, s) {
    c.uint.encode(state, s.bytes)
    c.uint.encode(state, s.padding)
  },
  decode (state) {
    return {
      bytes: c.uint.decode(state),
      padding: c.uint.decode(state)
    }
  }
}

const requestUpgrade = {
  preencode (state, u) {
    c.uint.preencode(state, u.start)
    c.uint.preencode(state, u.length)
  },
  encode (state, u) {
    c.uint.encode(state, u.start)
    c.uint.encode(state, u.length)
  },
  decode (state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

wire.request = {
  preencode (state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.id)
    c.uint.preencode(state, m.fork)

    if (m.block) requestBlock.preencode(state, m.block)
    if (m.hash) requestBlock.preencode(state, m.hash)
    if (m.seek) requestSeek.preencode(state, m.seek)
    if (m.upgrade) requestUpgrade.preencode(state, m.upgrade)
    if (m.priority) c.uint.preencode(state, m.priority)
  },
  encode (state, m) {
    const flags = (m.block ? 1 : 0) | (m.hash ? 2 : 0) | (m.seek ? 4 : 0) | (m.upgrade ? 8 : 0) | (m.manifest ? 16 : 0) | (m.priority ? 32 : 0)

    c.uint.encode(state, flags)
    c.uint.encode(state, m.id)
    c.uint.encode(state, m.fork)

    if (m.block) requestBlock.encode(state, m.block)
    if (m.hash) requestBlock.encode(state, m.hash)
    if (m.seek) requestSeek.encode(state, m.seek)
    if (m.upgrade) requestUpgrade.encode(state, m.upgrade)
    if (m.priority) c.uint.encode(state, m.priority)
  },
  decode (state) {
    const flags = c.uint.decode(state)

    return {
      id: c.uint.decode(state),
      fork: c.uint.decode(state),
      block: flags & 1 ? requestBlock.decode(state) : null,
      hash: flags & 2 ? requestBlock.decode(state) : null,
      seek: flags & 4 ? requestSeek.decode(state) : null,
      upgrade: flags & 8 ? requestUpgrade.decode(state) : null,
      manifest: (flags & 16) !== 0,
      priority: flags & 32 ? c.uint.decode(state) : 0
    }
  }
}

wire.cancel = {
  preencode (state, m) {
    c.uint.preencode(state, m.request)
  },
  encode (state, m) {
    c.uint.encode(state, m.request)
  },
  decode (state, m) {
    return {
      request: c.uint.decode(state)
    }
  }
}

const dataUpgrade = {
  preencode (state, u) {
    c.uint.preencode(state, u.start)
    c.uint.preencode(state, u.length)
    nodeArray.preencode(state, u.nodes)
    nodeArray.preencode(state, u.additionalNodes)
    c.optionalBuffer.preencode(state, u.signature)
  },
  encode (state, u) {
    c.uint.encode(state, u.start)
    c.uint.encode(state, u.length)
    nodeArray.encode(state, u.nodes)
    nodeArray.encode(state, u.additionalNodes)
    c.optionalBuffer.encode(state, u.signature)
  },
  decode (state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state),
      nodes: nodeArray.decode(state),
      additionalNodes: nodeArray.decode(state),
      signature: c.optionalBuffer.decode(state)
    }
  }
}

const dataSeek = {
  preencode (state, s) {
    c.uint.preencode(state, s.bytes)
    nodeArray.preencode(state, s.nodes)
  },
  encode (state, s) {
    c.uint.encode(state, s.bytes)
    nodeArray.encode(state, s.nodes)
  },
  decode (state) {
    return {
      bytes: c.uint.decode(state),
      nodes: nodeArray.decode(state)
    }
  }
}

const dataBlock = {
  preencode (state, b) {
    c.uint.preencode(state, b.index)
    c.optionalBuffer.preencode(state, b.value)
    nodeArray.preencode(state, b.nodes)
  },
  encode (state, b) {
    c.uint.encode(state, b.index)
    c.optionalBuffer.encode(state, b.value)
    nodeArray.encode(state, b.nodes)
  },
  decode (state) {
    return {
      index: c.uint.decode(state),
      value: c.optionalBuffer.decode(state) || EMPTY,
      nodes: nodeArray.decode(state)
    }
  }
}

const dataHash = {
  preencode (state, b) {
    c.uint.preencode(state, b.index)
    nodeArray.preencode(state, b.nodes)
  },
  encode (state, b) {
    c.uint.encode(state, b.index)
    nodeArray.encode(state, b.nodes)
  },
  decode (state) {
    return {
      index: c.uint.decode(state),
      nodes: nodeArray.decode(state)
    }
  }
}

wire.data = {
  preencode (state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.request)
    c.uint.preencode(state, m.fork)

    if (m.block) dataBlock.preencode(state, m.block)
    if (m.hash) dataHash.preencode(state, m.hash)
    if (m.seek) dataSeek.preencode(state, m.seek)
    if (m.upgrade) dataUpgrade.preencode(state, m.upgrade)
    if (m.manifest) manifest.preencode(state, m.manifest)
  },
  encode (state, m) {
    const flags = (m.block ? 1 : 0) | (m.hash ? 2 : 0) | (m.seek ? 4 : 0) | (m.upgrade ? 8 : 0) | (m.manifest ? 16 : 0)

    c.uint.encode(state, flags)
    c.uint.encode(state, m.request)
    c.uint.encode(state, m.fork)

    if (m.block) dataBlock.encode(state, m.block)
    if (m.hash) dataHash.encode(state, m.hash)
    if (m.seek) dataSeek.encode(state, m.seek)
    if (m.upgrade) dataUpgrade.encode(state, m.upgrade)
    if (m.manifest) manifest.encode(state, m.manifest)
  },
  decode (state) {
    const flags = c.uint.decode(state)

    return {
      request: c.uint.decode(state),
      fork: c.uint.decode(state),
      block: flags & 1 ? dataBlock.decode(state) : null,
      hash: flags & 2 ? dataHash.decode(state) : null,
      seek: flags & 4 ? dataSeek.decode(state) : null,
      upgrade: flags & 8 ? dataUpgrade.decode(state) : null,
      manifest: flags & 16 ? manifest.decode(state) : null
    }
  }
}

wire.noData = {
  preencode (state, m) {
    c.uint.preencode(state, m.request)
  },
  encode (state, m) {
    c.uint.encode(state, m.request)
  },
  decode (state, m) {
    return {
      request: c.uint.decode(state)
    }
  }
}

wire.want = {
  preencode (state, m) {
    c.uint.preencode(state, m.start)
    c.uint.preencode(state, m.length)
  },
  encode (state, m) {
    c.uint.encode(state, m.start)
    c.uint.encode(state, m.length)
  },
  decode (state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

wire.unwant = {
  preencode (state, m) {
    c.uint.preencode(state, m.start)
    c.uint.preencode(state, m.length)
  },
  encode (state, m) {
    c.uint.encode(state, m.start)
    c.uint.encode(state, m.length)
  },
  decode (state, m) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

wire.range = {
  preencode (state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.start)
    if (m.length !== 1) c.uint.preencode(state, m.length)
  },
  encode (state, m) {
    c.uint.encode(state, (m.drop ? 1 : 0) | (m.length === 1 ? 2 : 0))
    c.uint.encode(state, m.start)
    if (m.length !== 1) c.uint.encode(state, m.length)
  },
  decode (state) {
    const flags = c.uint.decode(state)

    return {
      drop: (flags & 1) !== 0,
      start: c.uint.decode(state),
      length: (flags & 2) !== 0 ? 1 : c.uint.decode(state)
    }
  }
}

wire.bitfield = {
  preencode (state, m) {
    c.uint.preencode(state, m.start)
    c.uint32array.preencode(state, m.bitfield)
  },
  encode (state, m) {
    c.uint.encode(state, m.start)
    c.uint32array.encode(state, m.bitfield)
  },
  decode (state, m) {
    return {
      start: c.uint.decode(state),
      bitfield: c.uint32array.decode(state)
    }
  }
}

wire.sync = {
  preencode (state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.fork)
    c.uint.preencode(state, m.length)
    c.uint.preencode(state, m.remoteLength)
  },
  encode (state, m) {
    c.uint.encode(state, (m.canUpgrade ? 1 : 0) | (m.uploading ? 2 : 0) | (m.downloading ? 4 : 0) | (m.hasManifest ? 8 : 0))
    c.uint.encode(state, m.fork)
    c.uint.encode(state, m.length)
    c.uint.encode(state, m.remoteLength)
  },
  decode (state) {
    const flags = c.uint.decode(state)

    return {
      fork: c.uint.decode(state),
      length: c.uint.decode(state),
      remoteLength: c.uint.decode(state),
      canUpgrade: (flags & 1) !== 0,
      uploading: (flags & 2) !== 0,
      downloading: (flags & 4) !== 0,
      hasManifest: (flags & 8) !== 0
    }
  }
}

wire.reorgHint = {
  preencode (state, m) {
    c.uint.preencode(state, m.from)
    c.uint.preencode(state, m.to)
    c.uint.preencode(state, m.ancestors)
  },
  encode (state, m) {
    c.uint.encode(state, m.from)
    c.uint.encode(state, m.to)
    c.uint.encode(state, m.ancestors)
  },
  decode (state) {
    return {
      from: c.uint.encode(state),
      to: c.uint.encode(state),
      ancestors: c.uint.encode(state)
    }
  }
}

wire.extension = {
  preencode (state, m) {
    c.string.preencode(state, m.name)
    c.raw.preencode(state, m.message)
  },
  encode (state, m) {
    c.string.encode(state, m.name)
    c.raw.encode(state, m.message)
  },
  decode (state) {
    return {
      name: c.string.decode(state),
      message: c.raw.decode(state)
    }
  }
}

const keyValue = {
  preencode (state, p) {
    c.string.preencode(state, p.key)
    c.optionalBuffer.preencode(state, p.value)
  },
  encode (state, p) {
    c.string.encode(state, p.key)
    c.optionalBuffer.encode(state, p.value)
  },
  decode (state) {
    return {
      key: c.string.decode(state),
      value: c.optionalBuffer.decode(state)
    }
  }
}

const treeUpgrade = {
  preencode (state, u) {
    c.uint.preencode(state, u.fork)
    c.uint.preencode(state, u.ancestors)
    c.uint.preencode(state, u.length)
    c.optionalBuffer.preencode(state, u.signature)
  },
  encode (state, u) {
    c.uint.encode(state, u.fork)
    c.uint.encode(state, u.ancestors)
    c.uint.encode(state, u.length)
    c.optionalBuffer.encode(state, u.signature)
  },
  decode (state) {
    return {
      fork: c.uint.decode(state),
      ancestors: c.uint.decode(state),
      length: c.uint.decode(state),
      signature: c.optionalBuffer.decode(state)
    }
  }
}

const bitfieldUpdate = { // TODO: can maybe be folded into a HAVE later on with the most recent spec
  preencode (state, b) {
    state.end++ // flags
    c.uint.preencode(state, b.start)
    c.uint.preencode(state, b.length)
  },
  encode (state, b) {
    state.buffer[state.start++] = b.drop ? 1 : 0
    c.uint.encode(state, b.start)
    c.uint.encode(state, b.length)
  },
  decode (state) {
    const flags = c.uint.decode(state)
    return {
      drop: (flags & 1) !== 0,
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

const oplog = exports.oplog = {}

oplog.entry = {
  preencode (state, m) {
    state.end++ // flags
    if (m.userData) keyValue.preencode(state, m.userData)
    if (m.treeNodes) nodeArray.preencode(state, m.treeNodes)
    if (m.treeUpgrade) treeUpgrade.preencode(state, m.treeUpgrade)
    if (m.bitfield) bitfieldUpdate.preencode(state, m.bitfield)
  },
  encode (state, m) {
    const s = state.start++
    let flags = 0

    if (m.userData) {
      flags |= 1
      keyValue.encode(state, m.userData)
    }
    if (m.treeNodes) {
      flags |= 2
      nodeArray.encode(state, m.treeNodes)
    }
    if (m.treeUpgrade) {
      flags |= 4
      treeUpgrade.encode(state, m.treeUpgrade)
    }
    if (m.bitfield) {
      flags |= 8
      bitfieldUpdate.encode(state, m.bitfield)
    }

    state.buffer[s] = flags
  },
  decode (state) {
    const flags = c.uint.decode(state)
    return {
      userData: (flags & 1) !== 0 ? keyValue.decode(state) : null,
      treeNodes: (flags & 2) !== 0 ? nodeArray.decode(state) : null,
      treeUpgrade: (flags & 4) !== 0 ? treeUpgrade.decode(state) : null,
      bitfield: (flags & 8) !== 0 ? bitfieldUpdate.decode(state) : null
    }
  }
}

const keyPair = {
  preencode (state, kp) {
    c.optionalBuffer.preencode(state, kp.publicKey)
    c.optionalBuffer.preencode(state, kp.secretKey)
  },
  encode (state, kp) {
    c.optionalBuffer.encode(state, kp.publicKey)
    c.optionalBuffer.encode(state, kp.secretKey)
  },
  decode (state) {
    return {
      publicKey: c.optionalBuffer.decode(state),
      secretKey: c.optionalBuffer.decode(state)
    }
  }
}

const reorgHint = {
  preencode (state, r) {
    c.uint.preencode(state, r.from)
    c.uint.preencode(state, r.to)
    c.uint.preencode(state, r.ancestors)
  },
  encode (state, r) {
    c.uint.encode(state, r.from)
    c.uint.encode(state, r.to)
    c.uint.encode(state, r.ancestors)
  },
  decode (state) {
    return {
      from: c.uint.decode(state),
      to: c.uint.decode(state),
      ancestors: c.uint.decode(state)
    }
  }
}

const reorgHintArray = c.array(reorgHint)

const hints = {
  preencode (state, h) {
    reorgHintArray.preencode(state, h.reorgs)
    c.uint.preencode(state, h.contiguousLength)
  },
  encode (state, h) {
    reorgHintArray.encode(state, h.reorgs)
    c.uint.encode(state, h.contiguousLength)
  },
  decode (state) {
    return {
      reorgs: reorgHintArray.decode(state),
      contiguousLength: state.start < state.end ? c.uint.decode(state) : 0
    }
  }
}

const treeHeader = {
  preencode (state, t) {
    c.uint.preencode(state, t.fork)
    c.uint.preencode(state, t.length)
    c.optionalBuffer.preencode(state, t.rootHash)
    c.optionalBuffer.preencode(state, t.signature)
  },
  encode (state, t) {
    c.uint.encode(state, t.fork)
    c.uint.encode(state, t.length)
    c.optionalBuffer.encode(state, t.rootHash)
    c.optionalBuffer.encode(state, t.signature)
  },
  decode (state) {
    return {
      fork: c.uint.decode(state),
      length: c.uint.decode(state),
      rootHash: c.optionalBuffer.decode(state),
      signature: c.optionalBuffer.decode(state)
    }
  }
}

const types = {
  preencode (state, t) {
    c.string.preencode(state, t.tree)
    c.string.preencode(state, t.bitfield)
    c.string.preencode(state, t.signer)
  },
  encode (state, t) {
    c.string.encode(state, t.tree)
    c.string.encode(state, t.bitfield)
    c.string.encode(state, t.signer)
  },
  decode (state) {
    return {
      tree: c.string.decode(state),
      bitfield: c.string.decode(state),
      signer: c.string.decode(state)
    }
  }
}

const externalHeader = {
  preencode (state, m) {
    c.uint.preencode(state, m.start)
    c.uint.preencode(state, m.length)
  },
  encode (state, m) {
    c.uint.encode(state, m.start)
    c.uint.encode(state, m.length)
  },
  decode (state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

const keyValueArray = c.array(keyValue)

oplog.header = {
  preencode (state, h) {
    state.end += 2 // version + flags
    if (h.external) {
      externalHeader.preencode(state, h.external)
      return
    }
    c.fixed32.preencode(state, h.key)
    if (h.manifest) manifest.preencode(state, h.manifest)
    if (h.keyPair) keyPair.preencode(state, h.keyPair)
    keyValueArray.preencode(state, h.userData)
    treeHeader.preencode(state, h.tree)
    hints.preencode(state, h.hints)
  },
  encode (state, h) {
    c.uint.encode(state, 1)
    if (h.external) {
      c.uint.encode(state, 1) // ONLY set the first big for clarity
      externalHeader.encode(state, h.external)
      return
    }
    c.uint.encode(state, (h.manifest ? 2 : 0) | (h.keyPair ? 4 : 0))
    c.fixed32.encode(state, h.key)
    if (h.manifest) manifest.encode(state, h.manifest)
    if (h.keyPair) keyPair.encode(state, h.keyPair)
    keyValueArray.encode(state, h.userData)
    treeHeader.encode(state, h.tree)
    hints.encode(state, h.hints)
  },
  decode (state) {
    const version = c.uint.decode(state)

    if (version > 1) {
      throw new Error('Invalid header version. Expected <= 1, got ' + version)
    }

    if (version === 0) {
      const old = {
        types: types.decode(state),
        userData: keyValueArray.decode(state),
        tree: treeHeader.decode(state),
        signer: keyPair.decode(state),
        hints: hints.decode(state)
      }

      return {
        external: null,
        key: old.signer.publicKey,
        manifest: {
          version: 0,
          hash: old.types.tree,
          allowPatch: false,
          quorum: 1,
          signers: [{
            signature: old.types.signer,
            namespace: DEFAULT_NAMESPACE,
            publicKey: old.signer.publicKey
          }],
          prologue: null
        },
        keyPair: old.signer.secretKey ? old.signer : null,
        userData: old.userData,
        tree: old.tree,
        hints: old.hints
      }
    }

    const flags = c.uint.decode(state)

    if (flags & 1) {
      return {
        external: externalHeader.decode(state),
        key: null,
        manifest: null,
        keyPair: null,
        userData: null,
        tree: null,
        hints: null
      }
    }

    return {
      external: null,
      key: c.fixed32.decode(state),
      manifest: (flags & 2) !== 0 ? manifest.decode(state) : null,
      keyPair: (flags & 4) !== 0 ? keyPair.decode(state) : null,
      userData: keyValueArray.decode(state),
      tree: treeHeader.decode(state),
      hints: hints.decode(state)
    }
  }
}

const uintArray = c.array(c.uint)

const multisigInput = {
  preencode (state, inp) {
    c.uint.preencode(state, inp.signer)
    c.fixed64.preencode(state, inp.signature)
    c.uint.preencode(state, inp.patch)
  },
  encode (state, inp) {
    c.uint.encode(state, inp.signer)
    c.fixed64.encode(state, inp.signature)
    c.uint.encode(state, inp.patch)
  },
  decode (state) {
    return {
      signer: c.uint.decode(state),
      signature: c.fixed64.decode(state),
      patch: c.uint.decode(state)
    }
  }
}

const patchEncodingv0 = {
  preencode (state, n) {
    c.uint.preencode(state, n.start)
    c.uint.preencode(state, n.length)
    uintArray.preencode(state, n.nodes)
  },
  encode (state, n) {
    c.uint.encode(state, n.start)
    c.uint.encode(state, n.length)
    uintArray.encode(state, n.nodes)
  },
  decode (state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state),
      nodes: uintArray.decode(state)
    }
  }
}

const multisigInputv0 = {
  preencode (state, n) {
    state.end++
    c.uint.preencode(state, n.signer)
    c.fixed64.preencode(state, n.signature)
    if (n.patch) patchEncodingv0.preencode(state, n.patch)
  },
  encode (state, n) {
    c.uint.encode(state, n.patch ? 1 : 0)
    c.uint.encode(state, n.signer)
    c.fixed64.encode(state, n.signature)
    if (n.patch) patchEncodingv0.encode(state, n.patch)
  },
  decode (state) {
    const flags = c.uint.decode(state)
    return {
      signer: c.uint.decode(state),
      signature: c.fixed64.decode(state),
      patch: (flags & 1) ? patchEncodingv0.decode(state) : null
    }
  }
}

const multisigInputArrayv0 = c.array(multisigInputv0)
const multisigInputArray = c.array(multisigInput)

const compactNode = {
  preencode (state, n) {
    c.uint.preencode(state, n.index)
    c.uint.preencode(state, n.size)
    c.fixed32.preencode(state, n.hash)
  },
  encode (state, n) {
    c.uint.encode(state, n.index)
    c.uint.encode(state, n.size)
    c.fixed32.encode(state, n.hash)
  },
  decode (state) {
    return {
      index: c.uint.decode(state),
      size: c.uint.decode(state),
      hash: c.fixed32.decode(state)
    }
  }
}

const compactNodeArray = c.array(compactNode)

exports.multiSignaturev0 = {
  preencode (state, s) {
    multisigInputArrayv0.preencode(state, s.proofs)
    compactNodeArray.preencode(state, s.patch)
  },
  encode (state, s) {
    multisigInputArrayv0.encode(state, s.proofs)
    compactNodeArray.encode(state, s.patch)
  },
  decode (state) {
    return {
      proofs: multisigInputArrayv0.decode(state),
      patch: compactNodeArray.decode(state)
    }
  }
}

exports.multiSignature = {
  preencode (state, s) {
    multisigInputArray.preencode(state, s.proofs)
    compactNodeArray.preencode(state, s.patch)
  },
  encode (state, s) {
    multisigInputArray.encode(state, s.proofs)
    compactNodeArray.encode(state, s.patch)
  },
  decode (state) {
    return {
      proofs: multisigInputArray.decode(state),
      patch: compactNodeArray.decode(state)
    }
  }
}
const c = require('compact-encoding')
const schema = require('../../encoding/spec/hyperschema')
const { core: coreKey } = require('../../lib/keys.js')
const View = require('../../lib/view.js')

const CORE_AUTH = schema.getEncoding('@core/auth')

const { CorestoreRX, CorestoreTX } = require('../../lib/tx.js')

async function core (core, { version, dryRun = false } = {}) {
  if (dryRun) return // dryRun mode not supported atm

  const rx = core.db.read({ autoDestroy: true })
  const storedAuthPromise = rx.get(coreKey.auth(core.core.corePointer))

  rx.tryFlush()

  const storedAuth = await storedAuthPromise
  if (!storedAuth) return

  const auth = c.decode(CORE_AUTH, storedAuth)
  await commitCoreMigration(auth, core, version)
}

module.exports = { core }

async function commitCoreMigration (auth, core, version) {
  const view = new View()
  const rx = new CorestoreRX(core.db, view)

  const storeCorePromise = rx.getCore(auth.discoveryKey)
  rx.tryFlush()

  const storeCore = await storeCorePromise

  storeCore.version = version

  const tx = new CorestoreTX(view)
  tx.putCore(auth.discoveryKey, storeCore)
  tx.apply()

  await View.flush(view.changes, core.db)
}
{
  "name": "hypercore-storage",
  "version": "3.2.0",
  "main": "index.js",
  "files": [
    "index.js",
    "lib/*.js",
    "encoding/*",
    "migrations/0/*.js",
    "migrations/1/*.js"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:bare": "brittle-bare test/all.js",
    "test:generate": "brittle -r test/all.js test/*.js",
    "test:node": "brittle-node test/all.js"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "description": "Storage engine for Hypercore",
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "fs/*": {
      "bare": "bare-fs/*",
      "default": "fs/*"
    },
    "os": {
      "bare": "bare-os",
      "default": "os"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    }
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/hypercore-storage.git"
  },
  "bugs": {
    "url": "https://github.com/holepunchto/hypercore-storage/issues"
  },
  "homepage": "https://github.com/holepunchto/hypercore-storage#readme",
  "dependencies": {
    "b4a": "^1.6.7",
    "bare-path": "^3.0.0",
    "compact-encoding": "^3.1.0",
    "device-file": "^2.1.2",
    "flat-tree": "^1.12.1",
    "hypercore-crypto": "^3.4.2",
    "hyperschema": "^1.21.0",
    "index-encoder": "^3.3.2",
    "resolve-reject-promise": "^1.0.0",
    "rocksdb-native": "^3.11.0",
    "scope-lock": "^1.2.4",
    "streamx": "^2.21.1",
    "xache": "^1.2.1"
  },
  "devDependencies": {
    "bare-os": "^3.9.1",
    "brittle": "^3.7.0",
    "hypercore-storage-2.9.0": "npm:hypercore-storage@^2.9.0",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "test-tmp": "^1.3.1"
  }
}
const { EventEmitter } = require('events')
const isOptions = require('is-options')
const crypto = require('hypercore-crypto')
const CoreStorage = require('hypercore-storage')
const c = require('compact-encoding')
const b4a = require('b4a')
const NoiseSecretStream = require('@hyperswarm/secret-stream')
const Protomux = require('protomux')
const id = require('hypercore-id-encoding')
const safetyCatch = require('safety-catch')
const unslab = require('unslab')
const flat = require('flat-tree')
const assert = require('nanoassert')

const { SMALL_WANTS } = require('./lib/feature-flags')
const { UPDATE_COMPAT } = require('./lib/wants')
const MarkBitfield = require('./lib/mark-bitfield')

const inspect = require('./lib/inspect')
const Core = require('./lib/core')
const Info = require('./lib/info')
const Download = require('./lib/download')
const DefaultEncryption = require('./lib/default-encryption')
const caps = require('./lib/caps')
const Replicator = require('./lib/replicator')
const { manifestHash, createManifest } = require('./lib/verifier')
const { ReadStream, WriteStream, ByteStream } = require('./lib/streams')
const { MerkleTree } = require('./lib/merkle-tree')
const { proof, verify } = require('./lib/fully-remote-proof')
const {
  ASSERTION,
  BAD_ARGUMENT,
  SESSION_CLOSED,
  SESSION_MOVED,
  SESSION_NOT_WRITABLE,
  SNAPSHOT_NOT_AVAILABLE,
  DECODING_ERROR,
  REQUEST_CANCELLED
} = require('hypercore-errors')

// Hypercore actually does not have any notion of max/min block sizes
// but we enforce 15mb to ensure smooth replication (each block is transmitted atomically)
const MAX_SUGGESTED_BLOCK_SIZE = 15 * 1024 * 1024

class Hypercore extends EventEmitter {
  constructor(storage, key, opts) {
    super()

    if (isOptions(storage) && !storage.db) {
      opts = storage
      storage = null
      key = opts.key || null
    } else if (isOptions(key)) {
      opts = key
      key = opts.key || null
    }

    if (key && typeof key === 'string') key = id.decode(key)
    if (!opts) opts = {}

    if (!storage) storage = opts.storage

    this.core = null
    this.state = null
    this.encryption = null
    this.extensions = new Map()

    this.valueEncoding = null
    this.encodeBatch = null
    this.activeRequests = []
    this.sessions = null
    this.ongc = null

    this.keyPair = opts.keyPair || null
    this.readable = true
    this.writable = false
    this.exclusive = false
    this.opened = false
    this.closed = false
    this.weak = !!opts.weak
    this.snapshotted = !!opts.snapshot
    this.onseq = opts.onseq || null
    this.onwait = opts.onwait || null
    this.wait = opts.wait !== false
    this.timeout = opts.timeout || 0
    this.preload = null
    this.closing = null
    this.opening = null

    this._readonly = opts.writable === false
    this._preappend = preappend.bind(this)
    this._snapshot = null
    this._findingPeers = 0
    this._active = opts.weak ? !!opts.active : opts.active !== false

    this.waits = 0

    // Mark & Sweep GC
    this._marking = false
    this._marks = null

    this._sessionIndex = -1
    this._stateIndex = -1 // maintained by session state
    this._monitorIndex = -1 // maintained by replication state

    this.opening = this._open(storage, key, opts)
    this.opening.catch(safetyCatch)

    this.on('newListener', maybeAddMonitor)
  }

  [Symbol.for('nodejs.util.inspect.custom')](depth, opts) {
    return inspect(this, depth, opts)
  }

  static MAX_SUGGESTED_BLOCK_SIZE = MAX_SUGGESTED_BLOCK_SIZE

  static DefaultEncryption = DefaultEncryption

  static SMALL_WANTS = SMALL_WANTS

  static enable(flag) {
    const enableCompat = (flag & SMALL_WANTS) === 0
    UPDATE_COMPAT(enableCompat)
  }

  static setRecoveryPeers(peers) {
    Core.setRecoveryPeers(peers)
  }

  static key(manifest, { compat, version, namespace } = {}) {
    if (b4a.isBuffer(manifest)) {
      manifest = { version, signers: [{ publicKey: manifest, namespace }] }
    }
    return compat ? manifest.signers[0].publicKey : manifestHash(createManifest(manifest))
  }

  static discoveryKey(key) {
    return crypto.discoveryKey(key)
  }

  static blockEncryptionKey(key, encryptionKey) {
    return DefaultEncryption.blockEncryptionKey(key, encryptionKey)
  }

  static getProtocolMuxer(stream) {
    return stream.noiseStream.userData
  }

  static createCore(storage, opts) {
    return new Core(Hypercore.defaultStorage(storage), { autoClose: false, ...opts })
  }

  static createProtocolStream(isInitiator, opts = {}) {
    let outerStream = Protomux.isProtomux(isInitiator)
      ? isInitiator.stream
      : isStream(isInitiator)
        ? isInitiator
        : opts.stream

    let noiseStream = null

    if (outerStream) {
      noiseStream = outerStream.noiseStream
    } else {
      noiseStream = new NoiseSecretStream(isInitiator, null, opts)
      outerStream = noiseStream.rawStream
    }
    if (!noiseStream) throw BAD_ARGUMENT('Invalid stream', this.discoveryKey)

    if (!noiseStream.userData) {
      const protocol = Protomux.from(noiseStream)

      if (opts.keepAlive !== false && noiseStream.keepAlive === 0) {
        noiseStream.setKeepAlive(5000)
      }
      noiseStream.userData = protocol
    }

    if (opts.ondiscoverykey) {
      const ondiscoverykey = createDiscoveryKeyHandler(opts.ondiscoverykey)
      noiseStream.userData.pair({ protocol: 'hypercore/alpha' }, ondiscoverykey)
    }

    return outerStream
  }

  static defaultStorage(storage, opts = {}) {
    if (CoreStorage.isCoreStorage(storage)) return storage

    const directory = storage
    return new CoreStorage(directory, opts)
  }

  static clearRequests(session, err) {
    Replicator.clearRequests(session, err)
  }

  static destroyRequests(session, err) {
    if (isRequestsDestroyed(session)) return
    Replicator.clearRequests(session, err)
    session.push(null) // mark as dead
  }

  static async treeHashFromStorage(session, length = session.length) {
    const roots = await MerkleTree.getRoots(session.state, length)
    return crypto.tree(roots)
  }

  snapshot(opts) {
    return this.session({ ...opts, snapshot: true })
  }

  compact() {
    return this.core.compact()
  }

  session(opts = {}) {
    if (this.closing) {
      // This makes the closing logic a lot easier. If this turns out to be a problem
      // in practice, open an issue and we'll try to make a solution for it.
      throw SESSION_CLOSED('Cannot make sessions on a closing core', this.discoveryKey)
    }
    if (opts.checkout !== undefined && !opts.name && !opts.atom) {
      throw ASSERTION('Checkouts are only supported on atoms or named sessions', this.discoveryKey)
    }

    const wait = opts.wait === false ? false : this.wait
    const writable = opts.writable === undefined ? !this._readonly : opts.writable === true
    const onwait = opts.onwait === undefined ? this.onwait : opts.onwait
    const onseq = opts.onseq === undefined ? this.onseq : opts.onseq
    const timeout = opts.timeout === undefined ? this.timeout : opts.timeout
    const weak = opts.weak === undefined ? this.weak : opts.weak
    const marking = this._marking
    const marks = this._marks
    const Clz = opts.class || Hypercore
    const s = new Clz(null, this.key, {
      ...opts,
      wait,
      onwait,
      onseq,
      timeout,
      writable,
      weak,
      parent: this
    })
    s._marking = marking
    s._marks = marks

    return s
  }

  async setEncryptionKey(key, opts) {
    if (!this.opened) await this.opening
    const encryption = this._getEncryptionProvider({ key, block: !!(opts && opts.block) })
    return this.setEncryption(encryption)
  }

  async setEncryption(encryption) {
    if (!this.opened) await this.opening

    if (encryption === null) {
      this.encryption = encryption
      return
    }

    if (!isEncryptionProvider(encryption)) {
      throw ASSERTION('Provider does not satisfy HypercoreEncryption interface', this.discoveryKey)
    }

    this.encryption = encryption
  }

  async setGroup(topic) {
    if (!this.opened) await this.opening
    return this.core.setGroup(topic)
  }

  setKeyPair(keyPair) {
    this.keyPair = keyPair
  }

  setActive(bool) {
    const active = !!bool
    if (active === this._active || this.closing) return
    this._active = active
    if (!this.opened) return
    this.core.replicator.updateActivity(this._active ? 1 : -1)
  }

  async _open(storage, key, opts) {
    const preload = opts.preload || (opts.parent && opts.parent.preload)

    if (preload) {
      this.sessions = [] // in case someone looks at it like with peers
      this.preload = preload
      opts = { ...opts, ...(await this.preload) }
      this.preload = null
    }

    const parent = opts.parent || null
    const core = opts.core || (parent && parent.core)
    const sessions = opts.sessions || (parent && parent.sessions)
    const ongc = opts.ongc || (parent && parent.ongc)

    if (core) this.core = core
    if (ongc) this.ongc = ongc
    if (sessions) this.sessions = sessions

    if (this.sessions === null) this.sessions = []
    this._sessionIndex = this.sessions.push(this) - 1

    if (this.core === null) initOnce(this, storage, key, opts)
    if (this._monitorIndex === -2) this.core.addMonitor(this)

    try {
      await this._openSession(opts)
    } catch (err) {
      if (this.core.autoClose && this.core.hasSession() === false) await this.core.close()

      if (this.exclusive) this.core.unlockExclusive()

      this.core.removeMonitor(this)
      this._removeSession()

      if (this.state !== null) this.state.removeSession(this)

      this.closed = true
      this.emit('close')
      throw err
    }

    // Setup automatic recovery if in repair mode
    if (this.core._repairMode) {
      const recoverTreeNodeFromPeersBound = this.recoverTreeNodeFromPeers.bind(this)
      this.once('repaired', () => {
        this.off('peer-add', recoverTreeNodeFromPeersBound)
      })
      this.on('peer-add', recoverTreeNodeFromPeersBound)
    }

    this.emit('ready')

    // if we are a weak session the core might have closed...
    if (this.core.closing) this.close().catch(safetyCatch)
  }

  _removeSession() {
    if (this._sessionIndex === -1) return
    const head = this.sessions.pop()
    if (head !== this) this.sessions[(head._sessionIndex = this._sessionIndex)] = head
    this._sessionIndex = -1
    if (this.ongc !== null) this.ongc(this)
  }

  async _openSession(opts) {
    if (this.core.opened === false) await this.core.ready()

    if (this.keyPair === null) this.keyPair = opts.keyPair || this.core.header.keyPair

    const parent = opts.parent || null
    if (parent && parent.encryption) this.encryption = parent.encryption

    const e = getEncryptionOption(opts)
    if (!this.encryption) this.encryption = this._getEncryptionProvider(e)

    this.writable = this._isWritable()

    if (opts.valueEncoding) {
      this.valueEncoding = c.from(opts.valueEncoding)
    }
    if (opts.encodeBatch) {
      this.encodeBatch = opts.encodeBatch
    }

    // one session sets for pushOnly for all
    if (opts.pushOnly === true) {
      this.core.replicator.setPushOnly(true)
    }

    if (parent) {
      if (parent._stateIndex === -1) await parent.ready()
      if (!this.keyPair) this.keyPair = parent.keyPair

      const ps = parent.state

      if (ps) {
        const shouldSnapshot = this.snapshotted && !ps.isSnapshot()
        this.state = shouldSnapshot ? await ps.snapshot() : ps.ref()
      }

      if (this.snapshotted && this.core && !this._snapshot) {
        this._updateSnapshot()
      }
    }

    if (opts.exclusive && opts.writable !== false) {
      this.exclusive = true
      await this.core.lockExclusive()
    }

    const parentState = parent ? parent.state : this.core.state
    const checkout = opts.checkout === undefined ? -1 : opts.checkout
    const state = this.state

    if (opts.atom) {
      this.state = await parentState.createSession(null, false, opts.atom)
      if (state) state.unref()
    } else if (opts.name) {
      // todo: need to make named sessions safe before ready
      // atm we always copy the state in passCapabilities
      this.state = await parentState.createSession(opts.name, !!opts.overwrite, null)
      if (state) state.unref() // ref'ed above in setup session
    }

    if (this.state && checkout !== -1) {
      if (!opts.name && !opts.atom) {
        throw ASSERTION('Checkouts must be named or atomized', this.discoveryKey)
      }
      if (checkout > this.state.length) {
        throw ASSERTION(
          `Invalid checkout ${checkout} for ${opts.name}, length is ${this.state.length}`,
          this.discoveryKey
        )
      }
      if (this.state.prologue && checkout < this.state.prologue.length) {
        throw ASSERTION(
          `Invalid checkout ${checkout} for ${opts.name}, prologue length is ${this.state.prologue.length}`,
          this.discoveryKey
        )
      }
      if (checkout < this.state.length) await this.state.truncate(checkout, this.fork)
    }

    if (this.state === null) {
      this.state = this.core.state.ref()
    }

    this.writable = this._isWritable()

    if (this.snapshotted && this.core) this._updateSnapshot()

    this.state.addSession(this)
    // TODO: we need to rework the core reference flow, as the state and session do not always agree now due to moveTo
    this.core = this.state.core // in case it was wrong...

    if (opts.userData) {
      const tx = this.state.storage.write()
      for (const [key, value] of Object.entries(opts.userData)) {
        tx.putUserData(key, value)
      }
      await tx.flush()
    }

    if (opts.manifest && !this.core.header.manifest) {
      await this.core.setManifest(createManifest(opts.manifest))
    }

    this.core.replicator.updateActivity(this._active ? 1 : 0)

    this.opened = true
  }

  get replicator() {
    return this.core === null ? null : this.core.replicator
  }

  _getSnapshot() {
    return {
      length: this.state.length,
      byteLength: this.state.byteLength,
      fork: this.state.fork
    }
  }

  _updateSnapshot() {
    const prev = this._snapshot
    const next = (this._snapshot = this._getSnapshot())

    if (!prev) return true
    return prev.length !== next.length || prev.fork !== next.fork
  }

  _isWritable() {
    if (this._readonly) return false
    if (this.state && !this.state.isDefault()) return true
    return !!(this.keyPair && this.keyPair.secretKey)
  }

  close({ error } = {}) {
    if (this.closing) return this.closing

    this.closing = this._close(error || null)
    return this.closing
  }

  clearRequests(activeRequests, error) {
    if (!activeRequests.length) return
    if (this.core) this.core.replicator.clearRequests(activeRequests, error)
  }

  async _close(error) {
    if (this.opened === false) {
      try {
        await this.opening
      } catch (err) {
        if (!this.closed) throw err
      }
    }

    if (this.closed === true) return

    this.core.removeMonitor(this)
    this.state.removeSession(this)
    this._removeSession()

    this.readable = false
    this.writable = false
    this.opened = false

    const gc = []
    for (const ext of this.extensions.values()) {
      if (ext.session === this) gc.push(ext)
    }
    for (const ext of gc) ext.destroy()

    this.core.replicator.findingPeers -= this._findingPeers
    this.core.replicator.clearRequests(this.activeRequests, error)
    this.core.replicator.updateActivity(this._active ? -1 : 0)

    this._findingPeers = 0

    this.state.unref()

    if (this.exclusive) this.core.unlockExclusive()

    if (this.core.hasSession()) {
      // emit "fake" close as this is a session
      this.closed = true
      this.emit('close')
      return
    }

    if (this.core.autoClose) await this.core.close()

    this.closed = true
    this.emit('close')
  }

  async commit(session, opts) {
    await this.ready()
    await session.ready()

    return this.state.commit(session.state, { keyPair: this.keyPair, ...opts })
  }

  replicate(isInitiator, opts = {}) {
    // Only limitation here is that ondiscoverykey doesn't work atm when passing a muxer directly,
    // because it doesn't really make a lot of sense.
    if (Protomux.isProtomux(isInitiator)) return this._attachToMuxer(isInitiator)

    // if same stream is passed twice, ignore the 2nd one before we make sessions etc
    if (isStream(isInitiator) && this._isAttached(isInitiator)) return isInitiator

    const protocolStream = Hypercore.createProtocolStream(isInitiator, opts)
    const noiseStream = protocolStream.noiseStream
    const protocol = noiseStream.userData

    this._attachToMuxer(protocol)

    return protocolStream
  }

  _isAttached(stream) {
    return (
      stream.userData &&
      this.core &&
      this.core.replicator &&
      this.core.replicator.attached(stream.userData)
    )
  }

  _attachToMuxer(mux) {
    if (this.opened) {
      this.core.replicator.attachTo(mux)
    } else {
      this.opening.then(() => this.core.replicator.attachTo(mux), mux.destroy.bind(mux))
    }

    return mux
  }

  get id() {
    return this.core === null ? null : this.core.id
  }

  get key() {
    return this.core === null ? null : this.core.key
  }

  get discoveryKey() {
    return this.core === null ? null : this.core.discoveryKey
  }

  get manifest() {
    return this.core === null ? null : this.core.manifest
  }

  get length() {
    if (this._snapshot) return this._snapshot.length
    return this.opened === false ? 0 : this.state.length
  }

  get signedLength() {
    return this.opened === false ? 0 : this.state.signedLength()
  }

  /**
   * Deprecated. Use `const { byteLength } = await core.info()`.
   */
  get byteLength() {
    if (this.opened === false) return 0
    if (this._snapshot) return this._snapshot.byteLength
    return this.state.byteLength - this.state.length * this.padding
  }

  get remoteContiguousLength() {
    if (this.opened === false) return 0
    return Math.min(this.core.state.length, this.core.header.hints.remoteContiguousLength)
  }

  get contiguousLength() {
    if (this.opened === false) return 0
    return Math.min(this.core.state.length, this.core.header.hints.contiguousLength)
  }

  get contiguousByteLength() {
    return 0
  }

  get fork() {
    if (this.opened === false) return 0
    return this.state.fork
  }

  get padding() {
    if (this.encryption && this.key && this.manifest) {
      return this.encryption.padding(this.core, this.length)
    }

    return 0
  }

  get peers() {
    return this.opened === false ? [] : this.core.replicator.peers
  }

  get globalCache() {
    return this.opened === false ? null : this.core.globalCache
  }

  get recovering() {
    return this.opened === false ? 0 : this.core.header.hints.recovering
  }

  ready() {
    return this.opening
  }

  async recover() {
    if (this.opened === false) await this.opening
    return this.state.waitForRecovery()
  }

  async setUserData(key, value) {
    if (this.opened === false) await this.opening
    const existing = await this.getUserData(key)
    if (existing && b4a.isBuffer(value) && b4a.equals(existing, value)) return
    await this.state.setUserData(key, value)
  }

  async getUserData(key) {
    if (this.opened === false) await this.opening
    const batch = this.state.storage.read()
    const p = batch.getUserData(key)
    batch.tryFlush()
    return p
  }

  transferSession(core) {
    // todo: validate we can move

    if (this.weak === false) {
      this.core.activeSessions--
      core.activeSessions++
    }

    if (this._monitorIndex >= 0) {
      this.core.removeMonitor(this)
      core.addMonitor(this)
    }

    const old = this.core

    this.core = core

    old.replicator.clearRequests(this.activeRequests, SESSION_MOVED())

    this.emit('migrate', this.key)
  }

  findingPeers() {
    this._findingPeers++
    if (this.core !== null && !this.closing) this.core.replicator.findingPeers++

    let once = true

    return () => {
      if (this.closing || !once) return
      once = false
      this._findingPeers--
      if (this.core !== null && --this.core.replicator.findingPeers === 0) {
        this.core.replicator.queueUpdateAll()
      }
    }
  }

  async info(opts) {
    if (this.opened === false) await this.opening

    return Info.from(this, opts)
  }

  async update(opts) {
    if (this.opened === false) await this.opening
    if (this.closing !== null) return false
    if (this.snapshotted) return false

    if (this.writable && (!opts || opts.force !== true)) return false

    const remoteWait = this._shouldWait(opts, this.core.replicator.findingPeers > 0)

    let upgraded = false

    if (await this.core.replicator.applyPendingReorg()) {
      upgraded = true
    }

    if (!upgraded && remoteWait) {
      const activeRequests = (opts && opts.activeRequests) || this.activeRequests
      if (isRequestsDestroyed(activeRequests)) throw REQUEST_CANCELLED()

      const req = this.core.replicator.addUpgrade(activeRequests)

      try {
        upgraded = await req.promise
      } catch (err) {
        if (isSessionMoved(err)) return this.update(opts)
        throw err
      }
    }

    if (!upgraded) return false
    return true
  }

  async seek(bytes, opts) {
    if (this.opened === false) await this.opening
    if (!isValidIndex(bytes)) throw ASSERTION('seek is invalid', this.discoveryKey)

    const activeRequests = (opts && opts.activeRequests) || this.activeRequests
    if (isRequestsDestroyed(activeRequests)) throw REQUEST_CANCELLED()

    if (this.encryption && !this.core.manifest) {
      const req = this.replicator.addUpgrade(activeRequests)
      try {
        await req.promise
      } catch (err) {
        if (isSessionMoved(err)) return this.seek(bytes, opts)
        throw err
      }
    }

    const s = MerkleTree.seek(this.state, bytes, this.padding)

    const offset = await s.update()
    if (offset) return offset

    if (this.closing !== null) {
      throw SESSION_CLOSED('cannot seek on a closed session', this.discoveryKey)
    }

    if (!this._shouldWait(opts, this.wait)) return null

    if (isRequestsDestroyed(activeRequests)) throw REQUEST_CANCELLED()
    const req = this.core.replicator.addSeek(activeRequests, s)

    const timeout = opts && opts.timeout !== undefined ? opts.timeout : this.timeout
    if (timeout) req.context.setTimeout(req, timeout)

    try {
      return await req.promise
    } catch (err) {
      if (isSessionMoved(err)) return this.seek(bytes, opts)
      throw err
    }
  }

  async has(start, end = start + 1) {
    if (this.opened === false) await this.opening
    if (!isValidIndex(start) || !isValidIndex(end)) {
      throw ASSERTION('has range is invalid', this.discoveryKey)
    }

    if (this.state.isDefault()) {
      if (end === start + 1) return this.core.bitfield.get(start)

      const i = this.core.bitfield.firstUnset(start)
      return i === -1 || i >= end
    }

    if (end === start + 1) {
      const rx = this.state.storage.read()
      const block = rx.getBlock(start)
      rx.tryFlush()

      return (await block) !== null
    }

    let count = 0

    const stream = this.state.storage.createBlockStream({ gte: start, lt: end })
    for await (const block of stream) {
      if (block === null) return false
      count++
    }

    return count === end - start
  }

  async get(index, opts) {
    if (this.opened === false) await this.opening
    if (!isValidIndex(index)) throw ASSERTION('block index is invalid', this.discoveryKey)

    if (this.closing !== null) {
      throw SESSION_CLOSED('cannot get on a closed session', this.discoveryKey)
    }

    const encoding =
      (opts && opts.valueEncoding && c.from(opts.valueEncoding)) || this.valueEncoding

    if (this.onseq !== null) this.onseq(index, this)
    if (this._marking) await this.markBlock(index)

    const req = this._get(index, opts)

    let block = await req
    if (!block) return null

    if (opts && opts.raw) return block

    if (this.encryption && (!opts || opts.decrypt !== false)) {
      // Copy the block as it might be shared with other sessions.
      block = b4a.from(block)

      await this.encryption.decrypt(index, block, this.core)
    }

    return this._decode(encoding, block, index)
  }

  async clear(start, end = start + 1, opts) {
    if (this.opened === false) await this.opening
    if (this.closing !== null) {
      throw SESSION_CLOSED('cannot clear on a closed session', this.discoveryKey)
    }

    if (typeof end === 'object') {
      opts = end
      end = start + 1
    }

    if (!isValidIndex(start) || !isValidIndex(end)) {
      throw ASSERTION('clear range is invalid', this.discoveryKey)
    }

    const cleared = opts && opts.diff ? { blocks: 0 } : null

    if (start >= end) return cleared
    if (start >= this.length) return cleared

    await this.state.clear(start, end, cleared)

    return cleared
  }

  async purge() {
    await this._closeAllSessions(null)
    await this.core.purge()
  }

  async _get(index, opts) {
    const block = await readBlock(this.state.storage.read(), index)

    if (block !== null) return block

    if (this.closing !== null) {
      throw SESSION_CLOSED('cannot get on a closed session', this.discoveryKey)
    }

    // snapshot should check if core has block
    if (this._snapshot !== null) {
      checkSnapshot(this, index)
      const coreBlock = await readBlock(this.core.state.storage.read(), index)

      checkSnapshot(this, index)
      if (coreBlock !== null) return coreBlock
    }

    // lets check the bitfield to see if we got it during the above async calls
    // this is the last resort before replication, so always safe.
    if (this.core.bitfield.get(index)) {
      const coreBlock = await readBlock(this.state.storage.read(), index)
      // TODO: this should not be needed, only needed atm in case we are doing a moveTo during this (we should fix)
      if (coreBlock !== null) return coreBlock
    }

    if (!this._shouldWait(opts, this.wait)) return null

    this.waits++
    if (opts && opts.onwait) opts.onwait(index, this)
    if (this.onwait) this.onwait(index, this)

    const activeRequests = (opts && opts.activeRequests) || this.activeRequests
    if (isRequestsDestroyed(activeRequests)) throw REQUEST_CANCELLED()

    const force = opts ? opts.force === true : false
    const req = this.core.replicator.addBlock(activeRequests, index, force)
    req.snapshot = index < this.length

    const timeout = opts && opts.timeout !== undefined ? opts.timeout : this.timeout
    if (timeout) req.context.setTimeout(req, timeout)

    let replicatedBlock = null

    try {
      replicatedBlock = await req.promise
    } catch (err) {
      if (isSessionMoved(err)) return this._get(index, opts)
      throw err
    }

    if (this._snapshot !== null) checkSnapshot(this, index)
    return maybeUnslab(replicatedBlock)
  }

  _shouldWait(opts, defaultValue) {
    if (opts) {
      if (opts.wait === false) return false
      if (opts.wait === true) return true
    }
    return defaultValue
  }

  _setupMarks() {
    if (this._marks === null) {
      const storage = this.snapshotted ? this.core.state.storage : this.state.storage
      this._marks = new MarkBitfield(storage)
    }
  }

  async markBlock(start, end = start + 1) {
    if (this.opened === false) await this.opening

    this._setupMarks()

    // TODO support as single rocks batch
    const setPromises = []
    for (let i = start; i < end; i++) {
      setPromises.push(this._marks.set(i, true))
    }

    return Promise.all(setPromises)
  }

  async clearMarkings() {
    if (this.opened === false) await this.opening

    this._setupMarks()

    await this._marks.clear()
    this._marks = null
  }

  async startMarking() {
    if (this._marking) {
      throw ASSERTION("Hypercore cannot be gc'ed when already in gc mode", this.discoveryKey)
    }
    if (this.state && this.state.name) {
      throw ASSERTION("Hypercore cannot be gc'ed when a named session", this.discoveryKey)
    }
    if (this.state && this.state.storage.atom) {
      throw ASSERTION("Hypercore cannot be gc'ed when an atomic session", this.discoveryKey)
    }
    if (this.opened === false) await this.opening
    await this.clearMarkings()

    this._marking = true
  }

  async sweep({ batchSize = 1000 } = {}) {
    if (this.opened === false) await this.opening

    assert(!this.snapshotted, 'Cannot sweep a snapshot')

    // No marks - load from storage
    this._setupMarks()

    let clearing = []
    let prevIndex = this.length
    for await (const index of this._marks.createMarkStream({ reverse: true })) {
      if (index + 1 === prevIndex) {
        prevIndex = index
        continue
      }
      clearing.push(this.clear(index + 1, prevIndex))
      if (clearing.length >= batchSize) {
        await Promise.all(clearing)
        clearing = []
      }
      prevIndex = index
    }
    // Clear range from the very start if not marked
    if (prevIndex > 0) clearing.push(this.clear(0, prevIndex))
    await Promise.all(clearing)

    this._marking = false
    await this.clearMarkings()
  }

  createReadStream(opts) {
    return new ReadStream(this, opts)
  }

  createWriteStream() {
    return new WriteStream(this)
  }

  createByteStream(opts) {
    return new ByteStream(this, opts)
  }

  download(range) {
    return new Download(this, range)
  }

  // TODO: get rid of this / deprecate it?
  undownload(range) {
    range.destroy(null)
  }

  // TODO: get rid of this / deprecate it?
  cancel(request) {
    // Do nothing for now
  }

  async truncate(newLength = 0, opts = {}) {
    if (this.opened === false) await this.opening
    if (this.closing) throw SESSION_CLOSED('Cannot append to a closed session', this.discoveryKey)

    const {
      fork = this.state.fork + 1,
      keyPair = this.keyPair,
      signature = null
    } = typeof opts === 'number' ? { fork: opts } : opts

    const isDefault = this.state === this.core.state
    const writable = !this._readonly && !!(signature || (keyPair && keyPair.secretKey))
    if (isDefault && writable === false && (newLength > 0 || fork !== this.state.fork)) {
      throw SESSION_NOT_WRITABLE('cannot append to a non-writable core', this.discoveryKey)
    }

    await this.state.truncate(newLength, fork, { keyPair, signature })

    // TODO: Should propagate from an event triggered by the oplog
    if (this.state === this.core.state) this.core.replicator.updateAll()
  }

  async append(blocks, opts = {}) {
    if (this.opened === false) await this.opening
    if (this.closing) throw SESSION_CLOSED('Cannot append to a closed session', this.discoveryKey)

    const isDefault = this.state === this.core.state
    const defaultKeyPair = this.state.name === null ? this.keyPair : null

    const { keyPair = defaultKeyPair, signature = null, maxLength, postappend = null } = opts
    const writable =
      !isDefault || !!signature || !!(keyPair && keyPair.secretKey) || opts.writable === true

    if (this._readonly || writable === false) {
      throw SESSION_NOT_WRITABLE('cannot append to a readonly core', this.discoveryKey)
    }

    blocks = Array.isArray(blocks) ? blocks : [blocks]

    const preappend = this.encryption && this._preappend

    const buffers = this.encodeBatch !== null ? this.encodeBatch(blocks) : new Array(blocks.length)

    if (this.encodeBatch === null) {
      for (let i = 0; i < blocks.length; i++) {
        buffers[i] = this._encode(this.valueEncoding, blocks[i])
      }
    }
    for (const b of buffers) {
      if (b.byteLength > MAX_SUGGESTED_BLOCK_SIZE) {
        throw BAD_ARGUMENT(
          'Appended block exceeds the maximum suggested block size',
          this.discoveryKey
        )
      }
    }

    return this.state.append(buffers, { keyPair, signature, preappend, postappend, maxLength })
  }

  async signable(length = -1, fork = -1) {
    if (this.opened === false) await this.opening
    if (length === -1) length = this.length
    if (fork === -1) fork = this.fork

    return caps.treeSignable(this.key, await this.treeHash(length), length, fork)
  }

  async treeHash(length = -1) {
    if (this.opened === false) await this.opening
    if (length === -1) length = this.length
    if (length > 0 && !(await this.has(length - 1))) await this.get(length - 1)

    const roots = await MerkleTree.getRoots(this.state, length)
    return crypto.tree(roots)
  }

  async missingNodes(index) {
    if (this.opened === false) await this.opening
    return await MerkleTree.missingNodes(this.core.state, 2 * index, this.core.state.length)
  }

  async proof(opts) {
    if (this.opened === false) await this.opening
    const rx = this.state.storage.read()
    const proofPromise = MerkleTree.proof(this.state, rx, opts)
    const blockPromise = opts && opts.block ? rx.getBlock(opts.block.index) : null
    rx.tryFlush()
    const [proof, block] = await Promise.all([proofPromise, blockPromise])
    const settled = await proof.settle()
    if (block) settled.block.value = block
    return settled
  }

  async applyProof(proof, from) {
    if (this.opened === false) await this.opening
    return this.core.verify(proof, from)
  }

  async verifyFullyRemote(proof) {
    if (this.opened === false) await this.opening
    const batch = await MerkleTree.verifyFullyRemote(this.state, proof)
    await this.core._verifyBatchUpgrade(batch, proof.manifest)
    return batch
  }

  generateRemoteProofForTreeNode(treeNodeIndex) {
    const blockProofIndex = flat.rightSpan(treeNodeIndex) / 2
    return proof(this, {
      index: blockProofIndex,
      // + 1 to length so the block is included
      upgrade: { start: 0, length: blockProofIndex + 1 }
    })
  }

  async recoverFromRemoteProof(remoteProof) {
    this.core.replicator.setPushOnly(true)
    this.core._repairMode = true

    await this.core.state.mutex.lock()

    try {
      const p = await verify(this.core.db, remoteProof)
      if (!p) return false

      const tx = this.core.storage.write()
      for (const node of p.proof.upgrade.nodes) {
        tx.putTreeNode(node)
      }
      await tx.flush()

      const succeed = p.proof.upgrade.nodes.length !== 0
      if (succeed) {
        this.core.replicator.setPushOnly(false)
      }
      return succeed
    } finally {
      this.core.state.mutex.unlock()
    }
  }

  recoverTreeNodeFromPeers() {
    this.core.replicator.setPushOnly(true)

    for (const peer of this.core.replicator.peers) {
      const req = {
        id: 0,
        fork: this.fork,
        upgrade: {
          start: 0,
          length: this.length
        }
      }
      peer.wireRequest.send(req)
    }
  }

  registerExtension(name, handlers = {}) {
    if (this.extensions.has(name)) {
      const ext = this.extensions.get(name)
      ext.handlers = handlers
      ext.encoding = c.from(handlers.encoding || c.buffer)
      ext.session = this
      return ext
    }

    const ext = {
      name,
      handlers,
      encoding: c.from(handlers.encoding || c.buffer),
      session: this,
      send(message, peer) {
        const buffer = c.encode(this.encoding, message)
        peer.extension(name, buffer)
      },
      broadcast(message) {
        const buffer = c.encode(this.encoding, message)
        for (const peer of this.session.peers) {
          peer.extension(name, buffer)
        }
      },
      destroy() {
        for (const peer of this.session.peers) {
          if (peer.extensions.get(name) === ext) peer.extensions.delete(name)
        }
        this.session.extensions.delete(name)
      },
      _onmessage(state, peer) {
        const m = this.encoding.decode(state)
        if (this.handlers.onmessage) this.handlers.onmessage(m, peer)
      }
    }

    this.extensions.set(name, ext)

    if (this.core === null) this._monitorIndex = -2
    else this.core.addMonitor(this)

    for (const peer of this.peers) {
      peer.extensions.set(name, ext)
    }

    return ext
  }

  _encode(enc, val) {
    const state = { start: this.padding, end: this.padding, buffer: null }

    if (b4a.isBuffer(val)) {
      if (state.start === 0) return val
      state.end += val.byteLength
    } else if (enc) {
      enc.preencode(state, val)
    } else {
      val = b4a.from(val)
      if (state.start === 0) return val
      state.end += val.byteLength
    }

    state.buffer = b4a.allocUnsafe(state.end)

    if (enc) enc.encode(state, val)
    else state.buffer.set(val, state.start)

    return state.buffer
  }

  _decode(enc, block, index) {
    if (this.encryption) block = block.subarray(this.encryption.padding(this.core, index))
    try {
      if (enc) return c.decode(enc, block)
    } catch (err) {
      throw DECODING_ERROR(err.message, this.discoveryKey)
    }
    return block
  }

  _getEncryptionProvider(e) {
    if (isEncryptionProvider(e)) return e
    if (!e || !e.key) return null
    return new DefaultEncryption(e.key, this.key, { block: e.block, compat: this.core.compat })
  }
}

module.exports = Hypercore

function isStream(s) {
  return typeof s === 'object' && s && typeof s.pipe === 'function'
}

async function preappend(blocks) {
  const offset = this.state.length
  const fork = this.state.encryptionFork

  for (let i = 0; i < blocks.length; i++) {
    await this.encryption.encrypt(offset + i, blocks[i], fork, this.core)
  }
}

function isValidIndex(index) {
  return index === 0 || index > 0
}

function maybeUnslab(block) {
  // Unslab only when it takes up less then half the slab
  return block !== null && 2 * block.byteLength < block.buffer.byteLength ? unslab(block) : block
}

function checkSnapshot(snapshot, index) {
  if (index >= snapshot.state.snapshotCompatLength) {
    throw SNAPSHOT_NOT_AVAILABLE(
      `snapshot at index ${index} not available (max compat length ${snapshot.state.snapshotCompatLength})`,
      snapshot.discoveryKey
    )
  }
}

function readBlock(rx, index) {
  const promise = rx.getBlock(index)
  rx.tryFlush()
  return promise
}

function initOnce(session, storage, key, opts) {
  if (storage === null) storage = opts.storage || null
  if (key === null) key = opts.key || null

  session.core = new Core(Hypercore.defaultStorage(storage), {
    preopen: opts.preopen,
    eagerUpgrade: opts.eagerUpgrade !== false,
    notDownloadingLinger: opts.notDownloadingLinger,
    allowFork: opts.allowFork !== false,
    allowPush: !!opts.allowPush,
    pushOnly: !!opts.pushOnly,
    alwaysLatestBlock: !!opts.allowLatestBlock,
    inflightRange: opts.inflightRange,
    compat: opts.compat === true,
    force: opts.force,
    createIfMissing: opts.createIfMissing,
    discoveryKey: opts.discoveryKey,
    overwrite: opts.overwrite,
    key,
    keyPair: opts.keyPair,
    legacy: opts.legacy,
    manifest: opts.manifest,
    group: opts.group,
    globalCache: opts.globalCache || null // session is a temp option, not to be relied on unless you know what you are doing (no semver guarantees)
  })
}

function maybeAddMonitor(name) {
  if (name === 'append' || name === 'truncate') return
  if (this._monitorIndex >= 0 || this.closing) return

  if (this.core === null) {
    this._monitorIndex = -2
  } else {
    this.core.addMonitor(this)
  }
}

function isSessionMoved(err) {
  return err.code === 'SESSION_MOVED'
}

function getEncryptionOption(opts) {
  // old style, supported for now but will go away
  if (opts.encryptionKey) return { key: opts.encryptionKey, block: !!opts.isBlockKey }
  if (!opts.encryption) return null
  return b4a.isBuffer(opts.encryption) ? { key: opts.encryption } : opts.encryption
}

function isEncryptionProvider(e) {
  return e && isFunction(e.padding) && isFunction(e.encrypt) && isFunction(e.decrypt)
}

function isFunction(fn) {
  return !!fn && typeof fn === 'function'
}

function createDiscoveryKeyHandler(fn) {
  return ondiscoverykey
  function ondiscoverykey(id) {
    if (!id || id.byteLength !== 32) throw BAD_ARGUMENT('Invalid discovery key')
    return fn(id)
  }
}

function isRequestsDestroyed(activeRequests) {
  // TODO: move this to an object instead so we can store a property in next major
  return activeRequests.length > 0 && activeRequests[0] === null
}
const crypto = require('hypercore-crypto')
const flat = require('flat-tree')
const b4a = require('b4a')
const { MerkleTree } = require('./merkle-tree')

module.exports = async function auditCore(
  core,
  { tree = true, blocks = true, bitfield = true, dryRun = false } = {}
) {
  const length = core.state.length
  const stats = {
    treeNodes: 0,
    blocks: 0,
    bits: 0,
    droppedTreeNodes: 0,
    droppedBlocks: 0,
    droppedBits: 0,
    corrupt: false
  }

  // audit the tree
  if (tree) {
    let tx = null

    const roots = await MerkleTree.getRootsFromStorage(core.state.storage, length)
    const stack = []

    for (const r of roots) {
      if (r === null) {
        if (!dryRun) {
          const storage = core.state.storage
          await storage.store.deleteCore(storage.core)
          return null
        }

        stats.corrupt = true
      }

      stack.push(r)
    }

    stats.treeNodes += roots.length

    while (stack.length > 0) {
      const node = stack.pop()

      if ((node.index & 1) === 0) continue

      const [left, right] = flat.children(node.index)

      const rx = core.state.storage.read()
      const leftNodePromise = rx.getTreeNode(left)
      const rightNodePromise = rx.getTreeNode(right)

      rx.tryFlush()

      const [leftNode, rightNode] = await Promise.all([leftNodePromise, rightNodePromise])

      if (isBadTree(node, leftNode, rightNode)) {
        if (!tx && !stats.corrupt) tx = core.state.storage.write()
        const [l, r] = flat.spans(node.index)
        tx.deleteTreeNodeRange(l, r + 1)
        stats.droppedTreeNodes++
        continue
      }

      if (!leftNode) continue

      stats.treeNodes += 2
      stack.push(leftNode, rightNode)
    }

    if (tx && !dryRun) await tx.flush()
  }

  // audit the blocks
  if (blocks) {
    let tx = null

    for await (const block of core.state.storage.createBlockStream()) {
      if (!core.bitfield.get(block.index)) {
        if (!tx && !stats.corrupt) tx = core.state.storage.write()
        tx.deleteBlock(block.index)
        stats.droppedBlocks++
      }

      const rx = core.state.storage.read()
      const treeNodePromise = rx.getTreeNode(2 * block.index)

      rx.tryFlush()

      const treeNode = await treeNodePromise

      if (isBadBlock(treeNode, block.value)) {
        if (!tx && !stats.corrupt) tx = core.state.storage.write()
        tx.deleteBlock(block.index)
        stats.droppedBlocks++
        continue
      }

      stats.blocks++
    }

    if (tx && !dryRun) await tx.flush()
  }

  if (bitfield) {
    let tx = null

    for (const index of allBits(core.bitfield)) {
      const rx = core.state.storage.read()
      const blockPromise = rx.getBlock(index)

      rx.tryFlush()

      const block = await blockPromise
      if (!block) {
        stats.droppedBits++
        if (dryRun) continue

        if (!tx && !stats.corrupt) tx = core.state.storage.write()

        core.bitfield.set(index, false)

        const page = core.bitfield.getBitfield(index)
        if (page.bitfield) tx.putBitfieldPage(page.index, page.bitfield)
        else tx.deleteBitfieldPage(page.index)
        continue
      }

      stats.bits++
    }

    if (tx && !dryRun) await tx.flush()
  }

  return stats
}

function isBadBlock(node, block) {
  if (!node) return true
  const hash = crypto.data(block)
  return !b4a.equals(hash, node.hash) || node.size !== block.byteLength
}

function isBadTree(parent, left, right) {
  if (!left && !right) return false
  if (!left || !right) return true
  const hash = crypto.parent(left, right)
  return !b4a.equals(hash, parent.hash) || parent.size !== left.size + right.size
}

function* allBits(bitfield) {
  let i = 0
  if (bitfield.get(0)) yield 0
  while (true) {
    i = bitfield.findFirst(true, i + 1)
    if (i === -1) break
    yield i
  }
}
const b4a = require('b4a')
const quickbit = require('./compat').quickbit

module.exports = class BitInterlude {
  constructor() {
    this.ranges = []
  }

  contiguousLength(from) {
    for (const r of this.ranges) {
      if (r.start > from) break
      if (!r.value && r.start <= from) return r.start
    }

    // TODO: be smarter
    while (this.get(from) === true) from++
    return from
  }

  get(index) {
    let start = 0
    let end = this.ranges.length

    while (start < end) {
      const mid = (start + end) >> 1
      const r = this.ranges[mid]

      if (index < r.start) {
        end = mid
        continue
      }

      if (index >= r.end) {
        if (mid === start) break
        start = mid
        continue
      }

      return r.value
    }

    return false
  }

  setRange(start, end, value) {
    if (start === end) return

    let r = null

    for (let i = 0; i < this.ranges.length; i++) {
      r = this.ranges[i]

      // if already inside, stop
      if (r.start <= start && end <= r.end) {
        if (value === r.value) return

        const ranges = mergeRanges(r, { start, end, value })
        this.ranges.splice(i, 1, ...ranges)

        return
      }

      // we wanna overun the interval
      if (start > r.end) {
        continue
      }

      // we overran but this interval is ending after us, move it back
      if (end >= r.start && end <= r.end) {
        r.start = r.value === value ? start : end
        if (r.value !== value) this.ranges.splice(i, 0, { start, end, value })
        return
      }

      // we overran but our start is contained in this interval, move start back
      if (start >= r.start && start <= r.end) {
        if (r.value !== value) {
          r.end = start // Crop current comparison

          // If there's a next range
          if (this.ranges.length - 1 > i) {
            const next = this.ranges[i + 1]
            // If the same, go next
            if (next.value === value) continue
            // Else we overlap so update next range
            if (next.start < end) next.start = end
          }

          this.ranges.splice(++i, 0, { start, end, value })
          return
        }

        start = r.start
      }

      let remove = 0

      for (let j = i; j < this.ranges.length; j++) {
        const n = this.ranges[j]
        if (n.start > end || n.value !== value) break
        if (n.start <= end && n.end > end) end = n.end
        remove++
      }

      this.ranges.splice(i, remove, { start, end, value })
      return
    }

    if (r !== null) {
      if (start <= r.end && end > r.end) {
        r.end = end
        return
      }

      // we never
      if (r.end > start) return
    }

    this.ranges.push({ start, end, value })
  }

  flush(tx, bitfield) {
    if (!this.ranges.length) return []

    let index = this.ranges[0].start
    const final = this.ranges[this.ranges.length - 1].end

    let i = 0

    while (index < final) {
      const page = bitfield.getBitfield(index) // read only
      const pageIndex = page ? page.index : bitfield.getPageIndex(index)

      const buf = b4a.allocUnsafe(bitfield.getPageByteLength())

      if (page) {
        const src = page.bitfield // Uint32Array
        buf.set(b4a.from(src.buffer, src.byteOffset, src.byteLength), 0)
      } else {
        b4a.fill(buf, 0)
      }

      const last = (pageIndex + 1) * (buf.byteLength << 3)
      const offset = pageIndex * (buf.byteLength << 3)

      let hasValue = false

      while (i < this.ranges.length) {
        const { start, end, value } = this.ranges[i]

        if (!hasValue && value) hasValue = true

        const from = start < index ? index : start
        const to = end < last ? end : last

        quickbit.fill(buf, value, from - offset, to - offset)

        index = to

        if (to === last) break

        i++
      }

      if (page || hasValue) tx.putBitfieldPage(pageIndex, buf)
    }

    return this.ranges
  }
}

function mergeRanges(a, b) {
  const ranges = []
  if (a.start < b.start) ranges.push({ start: a.start, end: b.start, value: a.value })
  ranges.push({ start: b.start, end: b.end, value: b.value })
  if (b.end < a.end) ranges.push({ start: b.end, end: a.end, value: a.value })

  return ranges
}
const BigSparseArray = require('big-sparse-array')
const b4a = require('b4a')
const quickbit = require('./compat').quickbit

const BITS_PER_PAGE = 32768
const BYTES_PER_PAGE = BITS_PER_PAGE / 8
const WORDS_PER_PAGE = BYTES_PER_PAGE / 4
const BITS_PER_SEGMENT = 2097152
const BYTES_PER_SEGMENT = BITS_PER_SEGMENT / 8
const WORDS_PER_SEGMENT = BYTES_PER_SEGMENT / 4
const INITIAL_WORDS_PER_SEGMENT = 1024
const PAGES_PER_SEGMENT = BITS_PER_SEGMENT / BITS_PER_PAGE
const SEGMENT_GROWTH_FACTOR = 4

class BitfieldPage {
  constructor(index, segment) {
    this.index = index
    this.offset = index * BYTES_PER_PAGE - segment.offset
    this.bitfield = null
    this.segment = segment

    segment.add(this)
  }

  get tree() {
    return this.segment.tree
  }

  get(index, dirty) {
    return quickbit.get(this.bitfield, index)
  }

  set(index, val) {
    if (quickbit.set(this.bitfield, index, val)) {
      this.tree.update(this.offset * 8 + index)
    }
  }

  setRange(start, end, val) {
    quickbit.fill(this.bitfield, val, start, end)

    let i = Math.floor(start / 128)
    const n = i + Math.ceil((end - start) / 128)

    while (i <= n) this.tree.update(this.offset * 8 + i++ * 128)
  }

  findFirst(val, position) {
    return quickbit.findFirst(this.bitfield, val, position)
  }

  findLast(val, position) {
    return quickbit.findLast(this.bitfield, val, position)
  }

  count(start, length, val) {
    const end = start + length

    let i = start
    let c = 0

    while (length > 0) {
      const l = this.findFirst(val, i)
      if (l === -1 || l >= end) return c

      const h = this.findFirst(!val, l + 1)
      if (h === -1 || h >= end) return c + end - l

      c += h - l
      length -= h - i
      i = h
    }

    return c
  }
}

class BitfieldSegment {
  constructor(index, bitfield) {
    this.index = index
    this.offset = index * BYTES_PER_SEGMENT
    this.tree = quickbit.Index.from(bitfield, BYTES_PER_SEGMENT)
    this.pages = new Array(PAGES_PER_SEGMENT)
  }

  get bitfield() {
    return this.tree.field
  }

  add(page) {
    const i = page.index - this.index * PAGES_PER_SEGMENT
    this.pages[i] = page

    const start = i * WORDS_PER_PAGE
    const end = start + WORDS_PER_PAGE

    if (end >= this.bitfield.length) this.reallocate(end)

    page.bitfield = this.bitfield.subarray(start, end)
  }

  reallocate(length) {
    let target = this.bitfield.length
    while (target < length) target *= SEGMENT_GROWTH_FACTOR

    const bitfield = new Uint32Array(target)
    bitfield.set(this.bitfield)

    this.tree = quickbit.Index.from(bitfield, BYTES_PER_SEGMENT)

    for (let i = 0; i < this.pages.length; i++) {
      const page = this.pages[i]
      if (!page) continue

      const start = i * WORDS_PER_PAGE
      const end = start + WORDS_PER_PAGE

      page.bitfield = bitfield.subarray(start, end)
    }
  }

  findFirst(val, position) {
    position = this.tree.skipFirst(!val, position)

    let j = position & (BITS_PER_PAGE - 1)
    let i = (position - j) / BITS_PER_PAGE

    if (i >= PAGES_PER_SEGMENT) return -1

    while (i < this.pages.length) {
      const p = this.pages[i]

      let index = -1

      if (p) index = p.findFirst(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_PAGE + index

      j = 0
      i++
    }

    return -1
  }

  findLast(val, position) {
    position = this.tree.skipLast(!val, position)

    let j = position & (BITS_PER_PAGE - 1)
    let i = (position - j) / BITS_PER_PAGE

    if (i >= PAGES_PER_SEGMENT) return -1

    while (i >= 0) {
      const p = this.pages[i]

      let index = -1

      if (p) index = p.findLast(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_PAGE + index

      j = BITS_PER_PAGE - 1
      i--
    }

    return -1
  }
}

module.exports = class Bitfield {
  static BITS_PER_PAGE = BITS_PER_PAGE
  static BYTES_PER_PAGE = BYTES_PER_PAGE

  constructor(buffer) {
    this.resumed = !!(buffer && buffer.byteLength >= 0)

    this._pages = new BigSparseArray()
    this._segments = new BigSparseArray()

    const view = this.resumed
      ? new Uint32Array(buffer.buffer, buffer.byteOffset, Math.floor(buffer.byteLength / 4))
      : new Uint32Array(INITIAL_WORDS_PER_SEGMENT)

    for (let i = 0; i < view.length; i += WORDS_PER_SEGMENT) {
      let bitfield = view.subarray(i, i + WORDS_PER_SEGMENT)
      let length = WORDS_PER_SEGMENT

      if (i === 0) {
        length = INITIAL_WORDS_PER_SEGMENT
        while (length < bitfield.length) length *= SEGMENT_GROWTH_FACTOR
      }

      if (bitfield.length !== length) {
        const copy = new Uint32Array(length)
        copy.set(bitfield, 0)
        bitfield = copy
      }

      const segment = new BitfieldSegment(i / WORDS_PER_SEGMENT, bitfield)
      this._segments.set(segment.index, segment)

      for (let j = 0; j < bitfield.length; j += WORDS_PER_PAGE) {
        const page = new BitfieldPage((i + j) / WORDS_PER_PAGE, segment)
        this._pages.set(page.index, page)
      }
    }
  }

  static from(bitfield) {
    return new Bitfield(bitfield.toBuffer(bitfield._pages.maxLength * BITS_PER_PAGE))
  }

  toBuffer(length) {
    const pages = Math.ceil(length / BITS_PER_PAGE)
    const buffer = b4a.allocUnsafe(pages * BYTES_PER_PAGE)

    for (let i = 0; i < pages; i++) {
      const page = this._pages.get(i)
      const offset = i * BYTES_PER_PAGE

      if (page) {
        const buf = b4a.from(
          page.bitfield.buffer,
          page.bitfield.byteOffset,
          page.bitfield.byteLength
        )

        buffer.set(buf, offset)
      } else {
        buffer.fill(0, offset, offset + BYTES_PER_PAGE)
      }
    }

    return buffer
  }

  getBitfield(index) {
    const i = this.getPageIndex(index)

    const p = this._pages.get(i)
    return p || null
  }

  merge(bitfield, length) {
    let i = 0

    while (i < length) {
      const start = bitfield.firstSet(i)
      if (start === -1) break

      i = bitfield.firstUnset(start)

      if (i === -1 || i > length) i = length

      this.setRange(start, i, true)

      if (i >= length) break
    }
  }

  get(index) {
    const j = index & (BITS_PER_PAGE - 1)
    const i = (index - j) / BITS_PER_PAGE

    const p = this._pages.get(i)

    return p ? p.get(j) : false
  }

  getPageByteLength() {
    return BYTES_PER_PAGE
  }

  getPageIndex(index) {
    const j = index & (BITS_PER_PAGE - 1)
    return (index - j) / BITS_PER_PAGE
  }

  getPage(index, create) {
    const i = this.getPageIndex(index)

    let p = this._pages.get(i)

    if (p) return p

    if (!create) return null

    const k = Math.floor(i / PAGES_PER_SEGMENT)
    const s =
      this._segments.get(k) ||
      this._segments.set(
        k,
        new BitfieldSegment(
          k,
          new Uint32Array(k === 0 ? INITIAL_WORDS_PER_SEGMENT : WORDS_PER_SEGMENT)
        )
      )

    p = this._pages.set(i, new BitfieldPage(i, s))

    return p
  }

  set(index, val) {
    const j = index & (BITS_PER_PAGE - 1)
    const i = (index - j) / BITS_PER_PAGE

    let p = this._pages.get(i)

    if (!p && val) {
      const k = Math.floor(i / PAGES_PER_SEGMENT)
      const s =
        this._segments.get(k) ||
        this._segments.set(
          k,
          new BitfieldSegment(
            k,
            new Uint32Array(k === 0 ? INITIAL_WORDS_PER_SEGMENT : WORDS_PER_SEGMENT)
          )
        )

      p = this._pages.set(i, new BitfieldPage(i, s))
    }

    if (p) p.set(j, val)
  }

  setRange(start, end, val) {
    let j = start & (BITS_PER_PAGE - 1)
    let i = (start - j) / BITS_PER_PAGE

    while (start < end) {
      let p = this._pages.get(i)

      if (!p && val) {
        const k = Math.floor(i / PAGES_PER_SEGMENT)
        const s =
          this._segments.get(k) ||
          this._segments.set(
            k,
            new BitfieldSegment(
              k,
              new Uint32Array(k === 0 ? INITIAL_WORDS_PER_SEGMENT : WORDS_PER_SEGMENT)
            )
          )

        p = this._pages.set(i, new BitfieldPage(i, s))
      }

      const offset = i * BITS_PER_PAGE
      const last = Math.min(end - offset, BITS_PER_PAGE)
      const range = last - j

      if (p) p.setRange(j, last, val)

      j = 0
      i++
      start += range
    }
  }

  findFirst(val, position) {
    let j = position & (BITS_PER_SEGMENT - 1)
    let i = (position - j) / BITS_PER_SEGMENT

    while (i < this._segments.maxLength) {
      const s = this._segments.get(i)

      let index = -1

      if (s) index = s.findFirst(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_SEGMENT + index

      j = 0
      i++
    }

    return val ? -1 : this._segments.maxLength * BITS_PER_SEGMENT
  }

  firstSet(position) {
    return this.findFirst(true, position)
  }

  firstUnset(position) {
    return this.findFirst(false, position)
  }

  findLast(val, position) {
    let j = position & (BITS_PER_SEGMENT - 1)
    let i = (position - j) / BITS_PER_SEGMENT

    while (i >= 0) {
      const s = this._segments.get(i)

      let index = -1

      if (s) index = s.findLast(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_SEGMENT + index

      j = BITS_PER_SEGMENT - 1
      i--
    }

    return -1
  }

  lastSet(position) {
    return this.findLast(true, position)
  }

  lastUnset(position) {
    return this.findLast(false, position)
  }

  hasUnset(start, length) {
    const end = start + length

    let j = start & (BITS_PER_SEGMENT - 1)
    let i = (start - j) / BITS_PER_SEGMENT

    while (i < this._segments.maxLength) {
      const s = this._segments.get(i)
      const index = s ? s.findFirst(false, j) : j
      if (index !== -1) return i * BITS_PER_SEGMENT + index < end

      j = 0
      i++

      if (i * BITS_PER_SEGMENT >= end) return false
    }

    return true
  }

  hasSet(start, length) {
    const end = start + length

    let j = start & (BITS_PER_SEGMENT - 1)
    let i = (start - j) / BITS_PER_SEGMENT

    while (i < this._segments.maxLength) {
      const s = this._segments.get(i)

      let index = -1

      if (s) index = s.findFirst(true, j)

      if (index !== -1) return i * BITS_PER_SEGMENT + index < end

      j = 0
      i++

      if (i * BITS_PER_SEGMENT >= end) return false
    }

    return false
  }

  count(start, length, val) {
    let j = start & (BITS_PER_PAGE - 1)
    let i = (start - j) / BITS_PER_PAGE
    let c = 0

    while (length > 0) {
      const p = this._pages.get(i)

      const end = Math.min(j + length, BITS_PER_PAGE)
      const range = end - j

      if (p) c += p.count(j, range, val)
      else if (!val) c += range

      j = 0
      i++
      length -= range
    }

    return c
  }

  countSet(start, length) {
    return this.count(start, length, true)
  }

  countUnset(start, length) {
    return this.count(start, length, false)
  }

  *want(start, length) {
    if (start & 31) {
      const d = start & 31
      start -= d
      length += d
    }

    let j = start & (BITS_PER_SEGMENT - 1)
    let i = (start - j) / BITS_PER_SEGMENT

    while (length > 0) {
      const s = this._segments.get(i)

      if (s) {
        let end = Math.min(j + length, BITS_PER_SEGMENT)
        if (end & 31) end += 32 - (end & 31)

        yield {
          start: i * BITS_PER_SEGMENT + j,
          bitfield: s.bitfield.subarray(j / 32, end / 32)
        }
      }

      j = 0
      i++
      length -= BITS_PER_SEGMENT
    }
  }

  clear(tx) {
    return tx.deleteBitfieldPageRange(0, -1)
  }

  onupdate(ranges) {
    for (const { start, end, value } of ranges) {
      this.setRange(start, end, value)
    }
  }

  static async open(storage, length) {
    if (length === 0) return new Bitfield(storage, null)

    const pages = Math.ceil(length / BITS_PER_PAGE)
    const buffer = b4a.alloc(pages * BYTES_PER_PAGE)
    const stream = storage.createBitfieldStream({ lt: pages })

    for await (const { index, page } of stream) {
      buffer.set(page, index * BYTES_PER_PAGE)
    }

    return new Bitfield(buffer)
  }
}
const crypto = require('hypercore-crypto')
const sodium = require('sodium-universal')
const b4a = require('b4a')
const c = require('compact-encoding')

// TODO: rename this to "crypto" and move everything hashing related etc in here
// Also lets move the tree stuff from hypercore-crypto here

const [
  TREE,
  REPLICATE_INITIATOR,
  REPLICATE_RESPONDER,
  MANIFEST,
  DEFAULT_NAMESPACE,
  DEFAULT_ENCRYPTION
] = crypto.namespace('hypercore', 6)

exports.MANIFEST = MANIFEST
exports.DEFAULT_NAMESPACE = DEFAULT_NAMESPACE
exports.DEFAULT_ENCRYPTION = DEFAULT_ENCRYPTION

exports.replicate = function (isInitiator, key, handshakeHash) {
  const out = b4a.allocUnsafe(32)
  sodium.crypto_generichash_batch(
    out,
    [isInitiator ? REPLICATE_INITIATOR : REPLICATE_RESPONDER, key],
    handshakeHash
  )
  return out
}

exports.treeSignable = function (manifestHash, treeHash, length, fork) {
  const state = { start: 0, end: 112, buffer: b4a.allocUnsafe(112) }
  c.fixed32.encode(state, TREE)
  c.fixed32.encode(state, manifestHash)
  c.fixed32.encode(state, treeHash)
  c.uint64.encode(state, length)
  c.uint64.encode(state, fork)
  return state.buffer
}

exports.treeSignableCompat = function (hash, length, fork, noHeader) {
  const end = noHeader ? 48 : 80
  const state = { start: 0, end, buffer: b4a.allocUnsafe(end) }
  if (!noHeader) c.fixed32.encode(state, TREE) // ultra legacy mode, kill in future major
  c.fixed32.encode(state, hash)
  c.uint64.encode(state, length)
  c.uint64.encode(state, fork)
  return state.buffer
}
// Export the appropriate version of `quickbit-universal` as the plain import
// may resolve to an older version in some environments
let quickbit = require('quickbit-universal')
if (
  typeof quickbit.findFirst !== 'function' ||
  typeof quickbit.findLast !== 'function' ||
  typeof quickbit.clear !== 'function'
) {
  // This should always load the fallback from the locally installed version
  quickbit = require('quickbit-universal/fallback')
}
exports.quickbit = quickbit
const crypto = require('hypercore-crypto')
const flat = require('flat-tree')
const b4a = require('b4a')
const quickbit = require('quickbit-universal')
const Bitfield = require('./bitfield')

const MAX_BATCH_USED = 4 * 1024 * 1024
const MIN_BATCH_USED = 512 * 1024

// just in its own file as its a bit involved

module.exports = copyPrologue

async function copyPrologue(src, dst) {
  const prologue = dst.header.manifest.prologue

  if (src.length < prologue.length || prologue.length === 0) return

  const stack = []
  const roots = flat.fullRoots(prologue.length * 2)
  const batch = { roots, first: true, last: false, contig: 0, used: 0, tree: [], blocks: [] }

  for (let i = 0; i < roots.length; i++) {
    const node = roots[i]
    batch.tree.push(node)
    stack.push(node)
  }

  let lastPage = -1
  let lastBlock = -1

  for await (const data of src.storage.createBlockStream({
    gte: 0,
    lt: prologue.length,
    reverse: true
  })) {
    if (walkTree(stack, data.index * 2, batch) === false) {
      throw new Error('Missing block or tree node for ' + data.index)
    }

    batch.contig = data.index + 1 === lastBlock ? batch.contig + 1 : 1
    lastBlock = data.index

    const page = getBitfieldPage(data.index)
    batch.blocks.push(data)

    if (lastPage !== page) batch.used += 4096
    batch.used += Math.max(data.value.byteLength, 128) // 128 is just a sanity number to avoid mega batches

    // always safe to partially flush so we do that ondemand to reduce memory usage...
    if ((batch.used >= MIN_BATCH_USED && page !== lastPage) || batch.used >= MAX_BATCH_USED) {
      await flushBatch(prologue, src, dst, batch)
    }

    lastPage = page
  }

  if (lastBlock !== 0) batch.contig = 0

  batch.last = true
  await flushBatch(prologue, src, dst, batch)
}

async function flushBatch(prologue, src, dst, batch) {
  const nodePromises = []

  const srcReader = src.storage.read()
  for (const index of batch.tree) {
    nodePromises.push(srcReader.getTreeNode(index))
  }
  srcReader.tryFlush()

  const nodes = await Promise.all(nodePromises)

  const pagePromises = []
  const dstReader = dst.storage.read()

  const headPromise = batch.first ? dstReader.getHead() : null
  if (headPromise) headPromise.catch(noop)

  let lastPage = -1
  for (const { index } of batch.blocks) {
    const page = getBitfieldPage(index)
    if (page === lastPage) continue
    lastPage = page
    pagePromises.push(dstReader.getBitfieldPage(page))
  }

  dstReader.tryFlush()

  const pages = await Promise.all(pagePromises)
  const head = headPromise === null ? null : await headPromise
  const userData = []

  // reads done!

  if (batch.first) {
    const roots = nodes.slice(0, batch.roots.length)

    for (const node of roots) {
      if (!node) throw new Error('Missing nodes for prologue hash')
    }

    const treeHash = crypto.tree(roots)
    if (!b4a.equals(treeHash, prologue.hash)) throw new Error('Prologue does not match source')
  }

  if (batch.first) {
    for await (const data of src.storage.createUserDataStream()) userData.push(data)
  }

  for (let i = 0; i < pages.length; i++) {
    if (!pages[i]) pages[i] = b4a.alloc(4096)
  }

  const tx = dst.storage.write()

  for (const node of nodes) tx.putTreeNode(node)

  lastPage = -1
  let pageIndex = -1

  for (const { index, value } of batch.blocks) {
    const page = getBitfieldPage(index)

    if (page !== lastPage) {
      lastPage = page
      pageIndex++
      // queue the page now, we mutate it below but its the same ref
      tx.putBitfieldPage(pageIndex, pages[pageIndex])
    }

    const pageBuffer = pages[pageIndex]
    quickbit.set(pageBuffer, getBitfieldOffset(index), true)
    tx.putBlock(index, value)
  }

  for (const { key, value } of userData) {
    tx.putUserData(key, value)
  }

  let upgraded = batch.first && !head
  if (upgraded) {
    tx.setHead(prologueToTree(prologue))
  }

  await tx.flush()

  if (upgraded) {
    const roots = nodes.slice(0, batch.roots.length)
    dst.state.setRoots(roots)
    dst.header.tree = prologueToTree(prologue)
  }

  if (userData.length > 0) {
    dst.header.userData = userData.concat(dst.header.userData)
  }

  if (batch.contig) {
    // TODO: we need to persist this somehow
    dst.header.hints.contiguousLength = batch.contig
  }

  let start = 0
  let length = 0

  // update in memory bitfield
  for (const { index } of batch.blocks) {
    if (start === 0 || start - 1 === index) {
      length++
    } else {
      if (length > 0) signalReplicator(dst, upgraded, start, length)
      upgraded = false
      length = 1
    }

    start = index
    dst.bitfield.set(index, true)
  }

  if (length > 0) signalReplicator(dst, upgraded, start, length)

  // unlink
  batch.tree = []
  batch.blocks = []
  batch.first = false
  batch.used = 0
}

function signalReplicator(core, upgraded, start, length) {
  if (upgraded) {
    core.replicator.cork()
    core.replicator.onhave(start, length, false)
    core.replicator.onupgrade()
    core.replicator.uncork()
  } else {
    core.replicator.onhave(start, length, false)
  }
}

function prologueToTree(prologue) {
  return {
    fork: 0,
    length: prologue.length,
    rootHash: prologue.hash,
    signature: null
  }
}

function getBitfieldPage(index) {
  return Math.floor(index / Bitfield.BITS_PER_PAGE)
}

function getBitfieldOffset(index) {
  return index & (Bitfield.BITS_PER_PAGE - 1)
}

function walkTree(stack, target, batch) {
  while (stack.length > 0) {
    const node = stack.pop()

    if ((node & 1) === 0) {
      if (node === target) return true
      continue
    }

    const ite = flat.iterator(node)
    if (!ite.contains(target)) continue

    while ((ite.index & 1) !== 0) {
      const left = ite.leftChild()
      const right = ite.sibling() // is right child

      batch.tree.push(left, right)

      if (ite.contains(target)) stack.push(left)
      else ite.sibling()
    }

    if (ite.index === target) return true
  }

  return false
}

function noop() {}
const crypto = require('hypercore-crypto')
const b4a = require('b4a')
const unslab = require('unslab')
const z32 = require('z32')
const Mutex = require('./mutex')
const { MerkleTree, ReorgBatch } = require('./merkle-tree')
const BitInterlude = require('./bit-interlude')
const Bitfield = require('./bitfield')
const RemoteBitfield = require('./remote-bitfield')
const {
  BAD_ARGUMENT,
  STORAGE_EMPTY,
  STORAGE_CONFLICT,
  INVALID_SIGNATURE,
  INVALID_CHECKSUM
} = require('hypercore-errors')
const Verifier = require('./verifier')
const audit = require('./audit')
const copyPrologue = require('./copy-prologue')
const SessionState = require('./session-state')
const Replicator = require('./replicator')

module.exports = class Core {
  constructor(db, opts = {}) {
    this.db = db
    this.storage = null
    this.replicator = new Replicator(this, opts)
    this.sessionStates = []
    this.monitors = []
    this.activeSessions = 0
    this.gc = 0 // corestore uses this to main a gc strike pool

    this.id = opts.key ? z32.encode(opts.key) : null
    this.key = opts.key || null
    this.discoveryKey = opts.discoveryKey || (opts.key && crypto.discoveryKey(opts.key)) || null
    this.manifest = null
    this.opening = null
    this.closing = null
    this.exclusive = null

    this.preupdate = null
    this.header = null
    this.compat = false
    this.bitfield = null
    this.verifier = null
    this.truncating = 0
    this.skipBitfield = null
    this.globalCache = opts.globalCache || null
    this.autoClose = opts.autoClose !== false
    this.onidle = noop
    this.ongroupupdate = noop

    this.state = null
    this.opened = false
    this.destroyed = false
    this.closed = false

    this.hintsChanged = false
    this.remoteContiguousLengthChanged = false

    this._bitfield = null
    this._verifies = null
    this._verifiesFlushed = null
    this._legacy = !!opts.legacy
    this._repairMode = false

    this.opening = this._open(opts)
    this.opening.catch(noop)
  }

  static setRecoveryPeers(peers) {
    SessionState.RECOVERY_PEERS = peers
  }

  ready() {
    return this.opening
  }

  addMonitor(s) {
    if (s._monitorIndex >= 0) return
    s._monitorIndex = this.monitors.push(s) - 1
  }

  removeMonitor(s) {
    if (s._monitorIndex < 0) return
    const head = this.monitors.pop()
    if (head !== s) this.monitors[(head._monitorIndex = s._monitorIndex)] = head
    s._monitorIndex = -1
  }

  emitRemoteContiguousLength() {
    if (!this.remoteContiguousLengthChanged) return
    this.remoteContiguousLengthChanged = false

    const length = this.header.hints.remoteContiguousLength

    for (let i = this.monitors.length - 1; i >= 0; i--) {
      this.monitors[i].emit('remote-contiguous-length', length)
    }
  }

  emitManifest() {
    for (let i = this.monitors.length - 1; i >= 0; i--) {
      this.monitors[i].emit('manifest')
    }
  }

  createUserDataStream(opts, session = this.state) {
    return session.storage.createUserDataStream(opts)
  }

  allSessions() {
    const sessions = []
    for (const state of this.sessionStates) {
      if (state.sessions.length) sessions.push(...state.sessions)
    }
    return sessions
  }

  hasSession() {
    return this.activeSessions !== 0
  }

  compact() {
    const compacting = []
    for (const s of this.sessionStates) {
      compacting.push(s.storage.compact())
    }
    return Promise.all(compacting)
  }

  checkIfIdle() {
    if (!this.opened || this.destroyed === true || this.hasSession() === true) return
    if (this.replicator.idle() === false) return
    if (this.state === null || this.state.mutex.idle() === false) return
    this.onidle()
  }

  async lockExclusive() {
    if (this.exclusive === null) this.exclusive = new Mutex()
    await this.exclusive.lock()
  }

  unlockExclusive() {
    if (this.exclusive !== null) this.exclusive.unlock()
  }

  async _open(opts) {
    try {
      await this._tryOpen(opts)
    } catch (err) {
      this.onidle()
      throw err
    }

    this.opened = true
  }

  async _tryOpen(opts) {
    if (opts.preopen) await opts.preopen // just a hook to allow exclusive access here...

    let storage = await this.db.resumeCore(this.discoveryKey)

    let overwrite = opts.overwrite === true

    const force = opts.force === true
    const createIfMissing = opts.createIfMissing !== false
    // kill this flag soon
    const legacy = !!opts.legacy

    // default to true for now if no manifest is provided
    let compat = opts.compat === true || (opts.compat !== false && !opts.manifest)

    let header = storage ? parseHeader(await getCoreInfo(storage)) : null

    const hadManifest = !!header && !!header.manifest && !!header.key
    const hadKeyPair = !!header && !!header.keyPair

    if (force && opts.key && header && !b4a.equals(header.key, opts.key)) {
      overwrite = true
    }

    if (!header && opts.discoveryKey && !(opts.key || opts.manifest)) {
      throw STORAGE_EMPTY('No Hypercore is stored here', this.discoveryKey)
    }

    if (!header || overwrite) {
      if (!createIfMissing) {
        throw STORAGE_EMPTY('No Hypercore is stored here', this.discoveryKey)
      }

      if (compat) {
        if (opts.key && opts.keyPair && !b4a.equals(opts.key, opts.keyPair.publicKey)) {
          throw BAD_ARGUMENT('Key must match publicKey when in compat mode', this.discoveryKey)
        }
      }

      const keyPair = opts.keyPair || (opts.key ? null : crypto.keyPair())

      const defaultManifest =
        !opts.manifest &&
        (!!opts.compat || !opts.key || !!(keyPair && b4a.equals(opts.key, keyPair.publicKey)))
      const manifest = defaultManifest
        ? Verifier.defaultSignerManifest(opts.key || keyPair.publicKey)
        : Verifier.createManifest(opts.manifest)

      header = {
        key: opts.key || (compat ? manifest.signers[0].publicKey : Verifier.manifestHash(manifest)),
        manifest,
        keyPair: keyPair
          ? { publicKey: keyPair.publicKey, secretKey: keyPair.secretKey || null }
          : null,
        frozen: false,
        tree: {
          fork: 0,
          length: 0,
          rootHash: null,
          signature: null,
          timestamp: 0
        },
        group: null,
        hints: {
          reorgs: [],
          contiguousLength: 0,
          remoteContiguousLength: 0,
          recovering: 0
        }
      }

      const discoveryKey = opts.discoveryKey || crypto.discoveryKey(header.key)

      storage = await this.db.createCore({
        key: header.key,
        manifest,
        keyPair,
        frozen: false,
        discoveryKey,
        userData: opts.userData || [],
        alias: opts.alias || null
      })
    }

    // unslab the long lived buffers to avoid keeping the slab alive
    header.key = unslab(header.key)

    if (header.tree) {
      header.tree.rootHash = unslab(header.tree.rootHash)
      header.tree.signature = unslab(header.tree.signature)
    }

    if (header.keyPair) {
      header.keyPair.publicKey = unslab(header.keyPair.publicKey)
      header.keyPair.secretKey = unslab(header.keyPair.secretKey)
    }

    if (header.keyPair) {
      header.keyPair.publicKey = unslab(header.keyPair.publicKey)
      header.keyPair.secretKey = unslab(header.keyPair.secretKey)
    }

    if (opts.manifest) {
      // if we provide a manifest and no key, verify that the stored key is the same
      if (
        !opts.key &&
        !Verifier.isValidManifest(header.key, Verifier.createManifest(opts.manifest))
      ) {
        throw STORAGE_CONFLICT('Manifest does not hash to provided key', this.discoveryKey)
      }

      if (!header.manifest) header.manifest = opts.manifest
    }

    if (opts.key && !b4a.equals(header.key, opts.key)) {
      throw STORAGE_CONFLICT('Another Hypercore is stored here', this.discoveryKey)
    }

    // if we signalled compat, but already now this core isn't disable it
    if (compat && header.manifest && !Verifier.isCompat(header.key, header.manifest)) {
      compat = false
    } else if (!compat && header.manifest && Verifier.isCompat(header.key, header.manifest)) {
      compat = true
    }

    const prologue = header.manifest ? header.manifest.prologue : null

    const bitfield = await Bitfield.open(storage, header.tree.length)

    const treeInfo = {
      fork: header.tree.fork,
      length: header.tree.length,
      signature: header.tree.signature,
      roots: await maybeGetRootsFromStorage(storage, header.tree.length),
      prologue
    }

    this._repairMode = !treeInfo.roots.length && treeInfo.length && !overwrite
    // Set push only mode if in repair mode
    if (this._repairMode) {
      this.replicator.setPushOnly(true)
    }

    if (opts.group) {
      if (!header.group) header.group = await this.db.createGroup(opts.group)
      else if (!b4a.equals(header.group.key, opts.group)) {
        throw STORAGE_CONFLICT(
          'Core is already register to group: ' + b4a.toString(header.group.key, 'hex')
        )
      }

      const tx = storage.write()
      tx.setGroup(header.group)
      await tx.flush()
    }

    if (overwrite) {
      const tx = storage.write()
      tx.deleteTreeNodeRange(0, -1)
      tx.deleteBlockRange(0, -1)
      bitfield.clear(tx)
      await tx.flush()
    }

    const len = bitfield.findFirst(false, header.hints.contiguousLength)
    if (header.hints.contiguousLength !== len && !storage.readOnly) {
      header.hints.contiguousLength = len
      const tx = storage.write()
      tx.setHints(header.hints)
      await tx.flush()
    }

    // to unslab
    if (header.manifest) {
      header.manifest = Verifier.createManifest(header.manifest)
      if (!hadManifest || (header.keyPair && !hadKeyPair)) {
        const tx = storage.write()
        tx.setAuth({
          key: header.key,
          discoveryKey: crypto.discoveryKey(header.key),
          manifest: header.manifest,
          keyPair: header.keyPair
        })
        await tx.flush()
      }
    }

    const verifier = header.manifest
      ? new Verifier(header.key, header.manifest, { crypto, legacy })
      : null

    this.storage = storage
    this.header = header
    this.compat = compat
    this.bitfield = bitfield
    this.verifier = verifier
    this.state = new SessionState(this, null, storage, treeInfo, null)

    if (this.key === null) this.key = this.header.key
    if (this.discoveryKey === null) this.discoveryKey = crypto.discoveryKey(this.key)
    if (this.id === null) this.id = z32.encode(this.key)
    if (this.manifest === null) this.manifest = this.header.manifest
  }

  async audit(opts) {
    await this.state.mutex.lock()

    try {
      return await audit(this, opts)
    } finally {
      this.state._unlock()
    }
  }

  async setGroup(group) {
    await this.state.mutex.lock()
    try {
      if (!this.header.group) this.header.group = await this.db.createGroup(group)
      else if (!b4a.equals(this.header.group.key, group)) {
        throw STORAGE_CONFLICT(
          'Core is already register to group: ' + b4a.toString(this.header.group.key, 'hex')
        )
      }

      const tx = this.storage.write()
      tx.setGroup(this.header.group)
      await tx.flush()
    } finally {
      this.state.mutex.unlock()
    }
  }

  async setManifest(manifest) {
    await this.state.mutex.lock()

    try {
      if (manifest && this.header.manifest === null) {
        if (!Verifier.isValidManifest(this.header.key, manifest)) {
          throw INVALID_CHECKSUM('Manifest hash does not match', this.discoveryKey)
        }

        const tx = this.state.createWriteBatch()
        this._setManifest(tx, Verifier.createManifest(manifest), null)
        await this.state.flush()
      }
    } finally {
      this.state._unlock()
    }
  }

  _setManifest(tx, manifest, keyPair) {
    if (!manifest && b4a.equals(keyPair.publicKey, this.header.key)) {
      manifest = Verifier.defaultSignerManifest(this.header.key)
    }
    if (!manifest) return

    const verifier = new Verifier(this.header.key, manifest, { legacy: this._legacy })

    if (verifier.prologue) this.state.prologue = Object.assign({}, verifier.prologue)

    this.manifest = this.header.manifest = manifest

    tx.setAuth({
      key: this.header.key,
      discoveryKey: this.discoveryKey,
      manifest,
      keyPair: this.header.keyPair
      // TODO: encryptionKey?
    })

    this.compat = verifier.compat
    this.verifier = verifier

    this.replicator.onupgrade()
    this.emitManifest()
  }

  async copyPrologue(src) {
    await this.state.mutex.lock()

    try {
      await src.mutex.lock()
    } catch (err) {
      this.state.mutex.unlock()
      throw err
    }

    try {
      await copyPrologue(src, this)
    } finally {
      src.mutex.unlock()
      this.state.mutex.unlock()
      this.checkIfIdle()
    }
  }

  flushed() {
    return this.state.flushed()
  }

  async _validateCommit(state, treeLength) {
    if (this.state.length > state.length) {
      return false // TODO: partial commit and truncation possible in the future
    }

    if (this.state.length > treeLength) {
      for (const root of this.state.roots) {
        const batchRoot = await MerkleTree.get(state, root.index)
        if (batchRoot.size !== root.size || !b4a.equals(batchRoot.hash, root.hash)) {
          return false
        }
      }
    }

    if (this.verifier === null) {
      return false // easier to assert than upsert
    }

    return true
  }

  _verifyBatchUpgrade(batch, manifest) {
    if (!this.header.manifest) {
      // compat, drop at some point
      if (!manifest) manifest = Verifier.defaultSignerManifest(this.header.key)

      if (
        !manifest ||
        !(
          Verifier.isValidManifest(this.header.key, manifest) ||
          Verifier.isCompat(this.header.key, manifest)
        )
      ) {
        throw INVALID_SIGNATURE('Proof contains an invalid manifest', this.discoveryKey) // TODO: proper error type
      }
    }

    const verifier =
      this.verifier ||
      new Verifier(this.header.key, Verifier.createManifest(manifest), { legacy: this._legacy })

    if (!verifier.verify(batch, batch.signature)) {
      throw INVALID_SIGNATURE('Proof contains an invalid signature', this.discoveryKey)
    }

    return manifest
  }

  async _verifyExclusive({ batch, bitfield, value, manifest }) {
    manifest = this._verifyBatchUpgrade(batch, manifest)

    if (
      !(await this.state._verifyBlock(
        batch,
        bitfield,
        value,
        this.header.manifest ? null : manifest
      ))
    ) {
      return false
    }

    if (!batch.upgraded && bitfield) {
      this.replicator.onhave(bitfield.start, bitfield.length, bitfield.drop)
    }

    return true
  }

  async _verifyShared() {
    if (!this._verifies.length) return false

    await this.state.mutex.lock()

    const tx = this.state.createWriteBatch()

    const verifies = this._verifies
    this._verifies = null
    this._verified = null

    try {
      for (const { batch, bitfield, value } of verifies) {
        if (!batch.commitable()) continue

        if (bitfield) {
          tx.putBlock(bitfield.start, value)
        }
      }

      const bits = new BitInterlude()

      for (let i = 0; i < verifies.length; i++) {
        const { batch, bitfield, manifest } = verifies[i]

        if (!batch.commitable()) {
          verifies[i] = null // signal that we cannot commit this one
          continue
        }

        if (bitfield) {
          bits.setRange(bitfield.start, bitfield.start + 1, true)
        }

        // if we got a manifest AND its strictly a non compat one, lets store it
        if (manifest && this.header.manifest === null) {
          if (!Verifier.isValidManifest(this.header.key, manifest)) {
            throw INVALID_CHECKSUM('Manifest hash does not match', this.discoveryKey)
          }
          this._setManifest(tx, manifest, null)
        }

        if (batch.commitable()) batch.commit(tx)
      }

      const ranges = bits.flush(tx, this.bitfield)

      await this.state.flush()

      for (const { start, end, value } of ranges) {
        this._setBitfieldRanges(start, end, value)
      }

      for (let i = 0; i < verifies.length; i++) {
        const bitfield = verifies[i] && verifies[i].bitfield
        if (bitfield) {
          this.updateContiguousLength(bitfield)
          this.replicator.onhave(bitfield.start, bitfield.length, bitfield.drop)
        }
      }

      if (this.hintsChanged) await this.flushHints()
    } finally {
      this.state._clearActiveBatch()
      this.state.mutex.unlock()
    }

    return verifies[0] !== null
  }

  async flushHints() {
    if (!this.hintsChanged) return
    this.hintsChanged = false // we unset this immediately as a "debounce"

    const tx = this.state.storage.write()

    tx.setHints({
      contiguousLength: this.header.hints.contiguousLength,
      remoteContiguousLength: this.header.hints.remoteContiguousLength,
      recovering: this.header.hints.recovering
    })

    await tx.flush()
  }

  async checkConflict(proof, from) {
    if (this.state.length < proof.upgrade.length || proof.fork !== this.state.fork) {
      // out of date this proof - ignore for now
      return false
    }

    // sanity check -> no manifest, no way to verify
    if (!this.header.manifest) {
      return false
    }

    const batch = MerkleTree.verifyFullyRemote(this.state, proof)

    try {
      this._verifyBatchUpgrade(batch, proof.manifest)
    } catch {
      return true
    }

    const roots = await maybeGetRootsFromStorage(this.storage, proof.upgrade.length)
    const remoteTreeHash = crypto.tree(proof.upgrade.nodes)
    const localTreeHash = crypto.tree(roots)

    try {
      const rx = this.state.storage.read()
      const treeProofPromise = MerkleTree.proof(this.state, rx, {
        block: null,
        hash: null,
        seek: null,
        upgrade: {
          start: 0,
          length: proof.upgrade.length
        }
      })

      rx.tryFlush()

      const treeProof = await treeProofPromise

      const verifyBatch = MerkleTree.verifyFullyRemote(this.state, await treeProof.settle())
      this._verifyBatchUpgrade(verifyBatch, this.header.manifest)
    } catch (err) {
      if (err.code !== 'INVALID_OPERATION') return true

      return !(await this._repairTreeNodes(proof))
    }

    // both proofs are valid, now check if they forked
    if (b4a.equals(localTreeHash, remoteTreeHash)) return false

    await this.state.mutex.lock()

    try {
      const tx = this.state.createWriteBatch()

      this.header.frozen = true

      tx.setAuth({
        key: this.header.key,
        discoveryKey: this.discoveryKey,
        manifest: this.header.manifest,
        keyPair: this.header.keyPair,
        frozen: true
      })

      await this.state.flush()
    } finally {
      this.state.mutex.unlock()
    }

    // tmp log so we can see these
    const id = b4a.toString(this.discoveryKey, 'hex')
    console.log(
      '[hypercore] conflict detected in ' +
        id +
        ' (writable=' +
        !!this.header.keyPair +
        ',quorum=' +
        this.header.manifest.quorum +
        ')'
    )
    await this._onconflict(proof)
    return true
  }

  async _repairTreeNodes(proof) {
    if (!this._repairMode) return false

    await this.state.mutex.lock()

    for (let i = this.monitors.length - 1; i >= 0; i--) {
      this.monitors[i].emit('repairing', proof)
    }

    try {
      const batch = MerkleTree.verifyFullyRemote(this.state, proof)
      this._verifyBatchUpgrade(batch, proof.manifest)
    } catch {
      this.state.mutex.unlock()
      for (let i = this.monitors.length - 1; i >= 0; i--) {
        this.monitors[i].emit('repair-failed')
      }
      return false
    }

    // Attempt to repair local merkle tree with remote roots
    const atom = this.storage.createAtom()
    const atomized = this.storage.atomize(atom)
    const tx = atomized.write()
    for (const node of proof.upgrade.nodes) {
      tx.putTreeNode(node)
    }
    await tx.flush()

    // Try local proof again
    try {
      const rx = atomized.read()
      const treeProofPromise = MerkleTree.proof(this.state, rx, {
        block: null,
        hash: null,
        seek: null,
        upgrade: {
          start: 0,
          length: proof.upgrade.length
        }
      })

      rx.tryFlush()

      const treeProof = await treeProofPromise

      const verifyBatch = MerkleTree.verifyFullyRemote(this.state, await treeProof.settle())
      this._verifyBatchUpgrade(verifyBatch, this.header.manifest)
    } catch (err) {
      this.state.mutex.unlock()
      for (let i = this.monitors.length - 1; i >= 0; i--) {
        this.monitors[i].emit('repair-failed')
      }
      return false
    }

    await atom.flush()

    for (let i = this.monitors.length - 1; i >= 0; i--) {
      this.monitors[i].emit('repaired', proof)
    }
    this.replicator.setPushOnly(false)
    this.state.mutex.unlock()
    return true
  }

  async verifyReorg(proof) {
    const batch = new ReorgBatch(this.state)
    await MerkleTree.reorg(this.state, proof, batch)
    const manifest = this._verifyBatchUpgrade(batch, proof.manifest)

    if (manifest && !this.header.manifest) {
      await this.state.mutex.lock()
      try {
        if (manifest && this.header.manifest === null) {
          const tx = this.state.createWriteBatch()
          this._setManifest(tx, Verifier.createManifest(manifest), null)
          await this.state.flush()
        }
      } finally {
        this.state._unlock()
      }
    }

    return batch
  }

  async verify(proof, from) {
    // We cannot apply "other forks" atm.
    // We should probably still try and they are likely super similar for non upgrades
    // but this is easy atm (and the above layer will just retry)
    if (proof.fork !== this.state.fork) return false

    const batch = await MerkleTree.verify(this.state, proof)

    if (batch.upgraded && batch.length <= this.state.length) {
      await batch.downgrade()
    }

    if (!batch.commitable()) {
      return false
    }

    const value = (proof.block && proof.block.value) || null
    const op = {
      batch,
      bitfield: value && { drop: false, start: proof.block.index, length: 1 },
      value,
      manifest: proof.manifest,
      from
    }

    if (batch.upgraded) {
      return this._verifyExclusive(op)
    }

    if (this._verifies !== null) {
      const verifies = this._verifies
      const i = verifies.push(op)
      await this._verified
      return verifies[i] !== null
    }

    this._verifies = [op]
    this._verified = this._verifyShared()

    return this._verified
  }

  async reorg(batch) {
    if (!batch.commitable()) return false

    this.truncating++

    try {
      await this.state.reorg(batch)
    } finally {
      this.truncating--
    }

    return true
  }

  openSkipBitfield() {
    if (this.skipBitfield !== null) return this.skipBitfield
    this.skipBitfield = new RemoteBitfield()
    const buf = this.bitfield.toBuffer(this.state.length)
    const bitfield = new Uint32Array(buf.buffer, buf.byteOffset, buf.byteLength / 4)
    this.skipBitfield.insert(0, bitfield)
    return this.skipBitfield
  }

  _setBitfieldRanges(start, end, value) {
    this.bitfield.setRange(start, end, value)
    if (this.skipBitfield !== null) this.skipBitfield.setRange(start, end, value)
  }

  close() {
    if (!this.closing) this.closing = this._close()
    return this.closing
  }

  updateContiguousLength(bitfield) {
    const contig = updateContigBatch(this.header.hints.contiguousLength, bitfield, this.bitfield)

    if (contig.length !== -1 && contig.length !== this.header.hints.contiguousLength) {
      this.header.hints.contiguousLength = contig.length
      this.hintsChanged = true
    }
  }

  updateRemoteContiguousLength(length) {
    this.header.hints.remoteContiguousLength = length
    this.hintsChanged = true
    this.remoteContiguousLengthChanged = true
  }

  onappend(tree, bitfield) {
    this.header.tree = tree

    if (!bitfield) {
      this.replicator.onupgrade()
      return
    }

    this.replicator.cork()

    const { start, length, drop } = bitfield

    this._setBitfieldRanges(start, start + length, true)
    this.updateContiguousLength({ start, length, drop: false })

    this.replicator.onupgrade()
    this.replicator.onhave(start, length, drop)
    this.replicator.uncork()
  }

  ontruncate(tree, { start, length }) {
    if (tree) this.header.tree = tree

    this.replicator.cork()

    this.replicator.ontruncate(start, length)
    this.replicator.onhave(start, length, true)
    this.replicator.onupgrade()
    this.replicator.uncork()

    for (const sessionState of this.sessionStates) {
      if (start < sessionState.snapshotCompatLength) sessionState.snapshotCompatLength = start
    }

    this._setBitfieldRanges(start, start + length, false)
    this.updateContiguousLength({ start, length, drop: true })
  }

  async _onconflict(proof) {
    await this.replicator.onconflict()

    for (let i = this.monitors.length - 1; i >= 0; i--) {
      const s = this.monitors[i]
      s.emit('conflict', proof.upgrade.length, proof.fork, proof)
    }

    const err = new Error('Two conflicting signatures exist for length ' + proof.upgrade.length)
    await this.closeAllSessions(err)
  }

  async closeAllSessions(err) {
    // this.sessions modifies itself when a session closes
    // This way we ensure we indeed iterate over all sessions
    const sessions = this.allSessions()

    const all = []
    for (const s of sessions) all.push(s.close({ error: err, force: false })) // force false or else infinite recursion
    await Promise.allSettled(all)
  }

  async destroy() {
    if (this.destroyed === true) return
    this.destroyed = true

    if (this.hasSession() === true) throw new Error('Cannot destroy while sessions are open')

    const weakSessions = this.allSessions()

    if (this.replicator) this.replicator.destroy()
    if (this.state) await this.state.close()

    // close all pending weak sessions...
    for (const s of weakSessions) s.close().catch(noop)
  }

  async _close() {
    if (this.opened === false) await this.opening
    if (this.hasSession() === true) throw new Error('Cannot close while sessions are open')

    if (this.replicator) await this.replicator.close()

    await this.destroy()
    if (this.autoClose) await this.storage.store.close()

    this.closed = true
  }
}

function updateContigBatch(start, upd, bitfield) {
  const end = upd.start + upd.length

  let c = start

  if (upd.drop) {
    // If we dropped a block in the current contig range, "downgrade" it
    if (c > upd.start) {
      c = upd.start
    }
  } else {
    if (c <= end && c >= upd.start) {
      c = end
      while (bitfield.get(c)) c++
    }
  }

  if (c === start) {
    return {
      length: -1
    }
  }

  if (c > start) {
    return {
      length: c
    }
  }

  return {
    length: c
  }
}

function getDefaultTree() {
  return {
    fork: 0,
    length: 0,
    rootHash: null,
    signature: null,
    timestamp: 0
  }
}

function parseHeader(info) {
  if (!info) return null

  return {
    key: info.key,
    manifest: info.manifest,
    external: null,
    keyPair: info.keyPair,
    tree: info.head || getDefaultTree(),
    group: info.group,
    hints: {
      reorgs: [],
      contiguousLength: info.hints ? info.hints.contiguousLength : 0,
      remoteContiguousLength: info.hints ? info.hints.remoteContiguousLength : 0,
      recovering: info.hints ? info.hints.recovering : 0
    }
  }
}

async function maybeGetRootsFromStorage(storage, length) {
  try {
    return length ? await MerkleTree.getRootsFromStorage(storage, length) : []
  } catch (err) {
    if (err.code !== 'INVALID_OPERATION') throw err
    // If INVALID_OPERATION, a root is likely missing so load empty roots to try to recover
    return []
  }
}

function noop() {}

async function getCoreInfo(storage) {
  const r = storage.read()

  const auth = r.getAuth()
  const head = r.getHead()
  const hints = r.getHints()
  const group = r.getGroup()

  r.tryFlush()

  const [authInfo, headInfo, hintsInfo, groupInfo] = await Promise.all([auth, head, hints, group])
  return {
    ...authInfo,
    head: headInfo,
    hints: hintsInfo,
    group: groupInfo
  }
}
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const b4a = require('b4a')
const { DEFAULT_ENCRYPTION } = require('./caps')

const nonce = b4a.alloc(sodium.crypto_stream_NONCEBYTES)

module.exports = class DefaultEncryption {
  static PADDING = 8

  constructor(encryptionKey, hypercoreKey, opts = {}) {
    this.key = encryptionKey
    this.compat = opts.compat === true

    const keys = DefaultEncryption.deriveKeys(encryptionKey, hypercoreKey, opts)

    this.blockKey = keys.block
    this.blindingKey = keys.blinding
  }

  static deriveKeys(encryptionKey, hypercoreKey, { block = false, compat = false } = {}) {
    const subKeys = b4a.alloc(2 * sodium.crypto_stream_KEYBYTES)

    const blockKey = block ? encryptionKey : subKeys.subarray(0, sodium.crypto_stream_KEYBYTES)
    const blindingKey = subKeys.subarray(sodium.crypto_stream_KEYBYTES)

    if (!block) {
      if (compat) {
        sodium.crypto_generichash_batch(blockKey, [encryptionKey], hypercoreKey)
      } else {
        sodium.crypto_generichash_batch(blockKey, [DEFAULT_ENCRYPTION, hypercoreKey, encryptionKey])
      }
    }

    sodium.crypto_generichash(blindingKey, blockKey)

    return {
      blinding: blindingKey,
      block: blockKey
    }
  }

  static blockEncryptionKey(hypercoreKey, encryptionKey) {
    const blockKey = b4a.alloc(sodium.crypto_stream_KEYBYTES)
    sodium.crypto_generichash_batch(blockKey, [DEFAULT_ENCRYPTION, hypercoreKey, encryptionKey])
    return blockKey
  }

  static encrypt(index, block, fork, blockKey, blindingKey) {
    const padding = block.subarray(0, DefaultEncryption.PADDING)
    block = block.subarray(DefaultEncryption.PADDING)

    c.uint64.encode({ start: 0, end: 8, buffer: padding }, fork)
    c.uint64.encode({ start: 0, end: 8, buffer: nonce }, index)

    // Zero out any previous padding.
    nonce.fill(0, 8, 8 + padding.byteLength)

    // Blind the fork ID, possibly risking reusing the nonce on a reorg of the
    // Hypercore. This is fine as the blinding is best-effort and the latest
    // fork ID shared on replication anyway.
    sodium.crypto_stream_xor(padding, padding, nonce, blindingKey)

    nonce.set(padding, 8)

    // The combination of a (blinded) fork ID and a block index is unique for a
    // given Hypercore and is therefore a valid nonce for encrypting the block.
    sodium.crypto_stream_xor(block, block, nonce, blockKey)
  }

  static decrypt(index, block, blockKey) {
    const padding = block.subarray(0, DefaultEncryption.PADDING)
    block = block.subarray(DefaultEncryption.PADDING)

    c.uint64.encode({ start: 0, end: 8, buffer: nonce }, index)

    nonce.set(padding, 8)

    // Decrypt the block using the blinded fork ID.
    sodium.crypto_stream_xor(block, block, nonce, blockKey)
  }

  encrypt(index, block, fork, core) {
    if (core.compat !== this.compat) this._reload(core)
    return DefaultEncryption.encrypt(index, block, fork, this.blockKey, this.blindingKey)
  }

  decrypt(index, block, core) {
    if (core.compat !== this.compat) this._reload(core)
    return DefaultEncryption.decrypt(index, block, this.blockKey)
  }

  padding() {
    return DefaultEncryption.PADDING
  }

  _reload(core) {
    const block = b4a.equals(this.key, this.blockKey)
    const keys = DefaultEncryption.deriveKeys(this.key, core.key, { block, compat: core.compat })

    this.blockKey = keys.blockKey
    this.blindingKey = keys.blindingKey
  }
}
module.exports = class Download {
  constructor(session, range) {
    this.session = session
    this.range = range
    this.request = null
    this.opened = false
    this.opening = this._open()
    this.opening.catch(noop)
  }

  ready() {
    return this.opening
  }

  async _open() {
    if (this.session.opened === false) await this.session.opening
    this._download()
    this.opened = true
  }

  async done() {
    await this.ready()

    try {
      return await this.request.promise
    } catch (err) {
      if (isSessionMoved(err)) return this._download()
      throw err
    }
  }

  _download() {
    const activeRequests = (this.range && this.range.activeRequests) || this.session.activeRequests
    this.request = this.session.core.replicator.addRange(activeRequests, this.range)
    this.request.promise.catch(noop)
    return this.request.promise
  }

  /**
   * Deprecated. Use `range.done()`.
   */
  downloaded() {
    return this.done()
  }

  destroy() {
    this._destroyBackground().catch(noop)
  }

  async _destroyBackground() {
    if (this.opened === false) await this.ready()
    if (this.request.context) this.request.context.detach(this.request)
  }
}

function noop() {}

function isSessionMoved(err) {
  return err.code === 'SESSION_MOVED'
}
module.exports = {
  SMALL_WANTS: 1
}
// this helper is for fully remote proofs, is like in a push notification where no other context exists

const { MerkleTree } = require('./merkle-tree.js')
const messages = require('./messages.js')
const b4a = require('b4a')
const c = require('compact-encoding')
const crypto = require('hypercore-crypto')
const flat = require('flat-tree')

class SlimSession {
  constructor(storage, auth, head, roots) {
    this.fork = head ? head.fork : 0
    this.roots = roots
    this.length = head ? head.length : 0
    this.signature = head ? head.signature : null
    this.ancestors = this.length
    this.byteLength = 0
    this.prologue = auth.manifest.prologue
    this.storage = storage

    for (let i = 0; i < roots.length; i++) this.byteLength += roots[i].size
  }
}

module.exports = { verify, proof }

async function verify(storage, buffer, { referrer = null } = {}) {
  const state = { buffer, start: 0, end: buffer.byteLength }

  const discoveryKey = c.fixed32.decode(state)
  const proof = messages.wire.data.decode(state)

  const result = {
    key: null,
    discoveryKey,
    newer: true,
    length: 0,
    proof,
    block: null
  }

  const core = await storage.resumeCore(discoveryKey)
  if (core === null) return null

  let rx = core.read()
  const authPromise = rx.getAuth()
  const headPromise = rx.getHead()
  const referrerPromise = rx.getUserData('referrer')

  rx.tryFlush()

  const [auth, head, ref] = await Promise.all([authPromise, headPromise, referrerPromise])

  if (auth === null) return null

  if (referrer && (!ref || !b4a.equals(ref, referrer))) return null

  rx = core.read()

  const rootPromises = []

  for (const index of flat.fullRoots(head ? 2 * head.length : 0)) {
    rootPromises.push(rx.getTreeNode(index))
  }

  rx.tryFlush()

  let roots = await Promise.all(rootPromises)
  if (roots.some(isNull)) roots = []

  const length = head ? head.length : 0

  if (!auth.manifest || !auth.manifest.signers.length) return null

  const batch = await MerkleTree.verifyFullyRemote(new SlimSession(core, auth, head, roots), proof)
  const publicKey = auth.manifest.signers[0].publicKey

  let signable = null
  let signature = null

  if (auth.manifest.version === 0) {
    signable = batch.signable(auth.manifest.signers[0].namespace)
    signature = batch.signature
  } else {
    if (batch.signature[0] !== 1) return null
    if (batch.signature[1] !== 0) return null

    signable = batch.signable(auth.key)
    signature = batch.signature.subarray(2, 66)
  }

  if (!crypto.verify(signable, signature, publicKey)) {
    return null
  }

  result.key = auth.key
  result.discoveryKey = discoveryKey
  result.newer = batch.length > length
  result.length = batch.length
  result.block = proof.block

  return result
}

async function proof(sender, { index, block = null, upgrade = null } = {}) {
  const proof = await sender.proof({
    block: block ? { index, nodes: 0 } : null,
    upgrade: upgrade ? upgrade : { start: 0, length: sender.length }
  })

  if (block) proof.block.value = block
  proof.manifest = sender.core.header.manifest

  const state = { buffer: null, start: 0, end: 0 }
  const data = { request: 0, ...proof }

  c.fixed32.preencode(state, sender.discoveryKey)
  messages.wire.data.preencode(state, data)

  state.buffer = b4a.allocUnsafe(state.end)

  c.fixed32.encode(state, sender.discoveryKey)
  messages.wire.data.encode(state, data)

  return state.buffer
}

function isNull(x) {
  return x === null
}
const TICKS = 16

module.exports = class HotswapQueue {
  constructor() {
    this.priorities = [[], [], []]
  }

  *pick(peer) {
    for (let i = 0; i < this.priorities.length; i++) {
      // try first one more than second one etc etc
      let ticks = (this.priorities.length - i) * TICKS
      const queue = this.priorities[i]

      for (let j = 0; j < queue.length; j++) {
        const r = j + Math.floor(Math.random() * queue.length - j)
        const a = queue[j]
        const b = queue[r]

        if (r !== j) {
          queue[(b.hotswap.index = j)] = b
          queue[(a.hotswap.index = r)] = a
        }

        if (hasInflight(b, peer)) continue

        yield b

        if (--ticks <= 0) break
      }
    }
  }

  add(block) {
    if (block.hotswap !== null) this.remove(block)
    if (block.inflight.length === 0 || block.inflight.length >= 3) return

    // TODO: also use other stuff to determine queue prio
    const queue = this.priorities[block.inflight.length - 1]

    const index = queue.push(block) - 1
    block.hotswap = { ref: this, queue, index }
  }

  remove(block) {
    const hotswap = block.hotswap
    if (hotswap === null) return

    block.hotswap = null
    const head = hotswap.queue.pop()
    if (head === block) return
    hotswap.queue[(head.hotswap.index = hotswap.index)] = head
  }
}

function hasInflight(block, peer) {
  for (let j = 0; j < block.inflight.length; j++) {
    if (block.inflight[j].peer === peer) return true
  }
  return false
}
module.exports = class Info {
  constructor(opts = {}) {
    this.key = opts.key
    this.discoveryKey = opts.discoveryKey
    this.length = opts.length || 0
    this.contiguousLength = opts.contiguousLength || 0
    this.byteLength = opts.byteLength || 0
    this.fork = opts.fork || 0
    this.padding = opts.padding || 0
    this.storage = opts.storage || null
  }

  static async from(session, opts = {}) {
    return new Info({
      key: session.key,
      discoveryKey: session.discoveryKey,
      length: session.length,
      contiguousLength: session.contiguousLength,
      byteLength: session.byteLength,
      fork: session.fork,
      padding: session.padding,
      storage: opts.storage ? await this.storage(session) : null
    })
  }

  static async storage(session) {
    const { oplog, tree, blocks, bitfield } = session.core
    try {
      return {
        oplog: await Info.bytesUsed(oplog.storage),
        tree: await Info.bytesUsed(tree.storage),
        blocks: await Info.bytesUsed(blocks.storage),
        bitfield: await Info.bytesUsed(bitfield.storage)
      }
    } catch {
      return null
    }
  }

  static bytesUsed(file) {
    return new Promise((resolve, reject) => {
      file.stat((err, st) => {
        if (err) {
          resolve(0) // prob just file not found (TODO, improve)
        } else if (typeof st.blocks !== 'number') {
          reject(new Error('cannot determine bytes used'))
        } else {
          resolve(st.blocks * 512)
        }
      })
    })
  }
}
const b4a = require('b4a')

module.exports = function (core, depth, opts) {
  let indent = ''
  if (typeof opts.indentationLvl === 'number') {
    while (indent.length < opts.indentationLvl) indent += ' '
  }

  let peers = ''
  const min = Math.min(core.peers.length, 5)

  for (let i = 0; i < min; i++) {
    const peer = core.peers[i]

    peers += `${indent}    Peer(\n`
    peers += `${indent}      remotePublicKey: ${opts.stylize(toHex(peer.remotePublicKey), 'string')}\n`
    peers += `${indent}      remoteLength: ${opts.stylize(peer.remoteLength, 'number')}\n`
    peers += `${indent}      remoteFork: ${opts.stylize(peer.remoteFork, 'number')}\n`
    peers += `${indent}      remoteCanUpgrade: ${opts.stylize(peer.remoteCanUpgrade, 'boolean')}\n`
    peers += `${indent}    )\n`
  }

  if (core.peers.length > 5) {
    peers += `${indent}  ... and ${core.peers.length - 5} more\n`
  }

  if (peers) peers = `[\n${peers}${indent}  ]`
  else peers = `[ ${opts.stylize(0, 'number')} ]`

  return (
    `${core.constructor.name}(\n` +
    `${indent}  id: ${opts.stylize(core.id, 'string')}\n` +
    `${indent}  key: ${opts.stylize(toHex(core.key), 'string')}\n` +
    `${indent}  discoveryKey: ${opts.stylize(toHex(core.discoveryKey), 'string')}\n` +
    `${indent}  opened: ${opts.stylize(core.opened, 'boolean')}\n` +
    `${indent}  closed: ${opts.stylize(core.closed, 'boolean')}\n` +
    `${indent}  snapshotted: ${opts.stylize(core.snapshotted, 'boolean')}\n` +
    `${indent}  writable: ${opts.stylize(core.writable, 'boolean')}\n` +
    `${indent}  length: ${opts.stylize(core.length, 'number')}\n` +
    `${indent}  fork: ${opts.stylize(core.fork, 'number')}\n` +
    `${indent}  sessions: [ ${opts.stylize(core.sessions.length, 'number')} ]\n` +
    `${indent}  activeRequests: [ ${opts.stylize(core.activeRequests.length, 'number')} ]\n` +
    `${indent}  peers: ${peers}\n` +
    `${indent})`
  )
}

function toHex(buf) {
  return buf && b4a.toString(buf, 'hex')
}
const BigSparseArray = require('big-sparse-array')
const { Transform } = require('streamx')
const quickbit = require('./compat').quickbit
const b4a = require('b4a')

const BITS_PER_PAGE = 32768
const BYTES_PER_PAGE = BITS_PER_PAGE / 8

class MarkPage {
  constructor() {
    this.bitfield = null
    this.loaded = new Promise((resolve) => {
      this.load = resolve
    })
  }

  setBitfield(bitfield) {
    this.bitfield = bitfield
    this.load()
  }

  get(index) {
    return quickbit.get(this.bitfield, index)
  }

  set(index, val) {
    quickbit.set(this.bitfield, index, val)
  }
}

module.exports = class MarkBitfield {
  static BITS_PER_PAGE = BITS_PER_PAGE
  static BYTES_PER_PAGE = BYTES_PER_PAGE

  constructor(storage) {
    this.storage = storage
    this._pages = new BigSparseArray()
  }

  async loadPage(pageIndex) {
    const p = this._pages.set(pageIndex, new MarkPage())
    const rx = this.storage.read()
    const pageBuf = rx.getMark(pageIndex)
    rx.tryFlush()
    const bitfield = (await pageBuf) ?? b4a.alloc(BYTES_PER_PAGE)
    await p.setBitfield(bitfield)
    return p
  }

  async get(index) {
    const j = index & (BITS_PER_PAGE - 1)
    const i = (index - j) / BITS_PER_PAGE

    let p = this._pages.get(i)
    if (!p) p = await this.loadPage(i)

    return p.get(j)
  }

  async set(index, val) {
    const j = index & (BITS_PER_PAGE - 1)
    const i = (index - j) / BITS_PER_PAGE

    let p = this._pages.get(i)

    if (!p && val) p = await this.loadPage(i)

    if (p) {
      await p.loaded
      p.set(j, val)
      const tx = this.storage.write()
      tx.putMark(i, p.bitfield)
      await tx.flush()
    }
  }

  async clear() {
    const tx = this.storage.write()
    tx.deleteMarkRange(0, -1)
    await tx.flush()
    this._pages = new BigSparseArray()
  }

  createMarkStream({ reverse = false } = {}) {
    return this.storage.createMarkStream({ reverse }).pipe(
      new Transform({
        transform({ index, page }, cb) {
          let bitIndex = reverse
            ? quickbit.findLast(page, true, BITS_PER_PAGE)
            : quickbit.findFirst(page, true, 0)
          while (bitIndex !== -1) {
            const blockIndex = index * BITS_PER_PAGE + bitIndex
            this.push(blockIndex)

            // Account for `bitIndex` being either causing infinite loop
            if (bitIndex === 0 && reverse) break

            bitIndex = reverse
              ? quickbit.findLast(page, true, bitIndex - 1)
              : quickbit.findFirst(page, true, bitIndex + 1)
          }

          cb(null)
        }
      })
    )
  }
}
const flat = require('flat-tree')
const crypto = require('hypercore-crypto')
const b4a = require('b4a')
const unslab = require('unslab')
const caps = require('./caps')
const {
  INVALID_PROOF,
  INVALID_CHECKSUM,
  INVALID_OPERATION,
  BAD_ARGUMENT,
  ASSERTION
} = require('hypercore-errors')

class NodeQueue {
  constructor(nodes, extra = null) {
    this.i = 0
    this.nodes = nodes
    this.extra = extra
    this.length = nodes.length + (this.extra === null ? 0 : 1)
  }

  shift(index) {
    if (this.extra !== null && this.extra.index === index) {
      const node = this.extra
      this.extra = null
      this.length--
      return node
    }

    if (this.i >= this.nodes.length) {
      throw INVALID_OPERATION('Expected node ' + index + ', got (nil)')
    }

    const node = this.nodes[this.i++]
    if (node.index !== index) {
      throw INVALID_OPERATION('Expected node ' + index + ', got node ' + node.index)
    }

    this.length--
    return node
  }
}

class MerkleTreeBatch {
  constructor(session) {
    this.fork = session.fork
    this.roots = [...session.roots]
    this.length = session.length
    this.signature = session.signature
    this.ancestors = session.length
    this.byteLength = session.byteLength
    this.prologue = session.prologue
    this.hashCached = null

    this.committed = false
    this.truncated = false
    this.treeLength = session.length
    this.treeFork = session.fork
    this.storage = session.storage
    this.session = session
    this.nodes = []
    this.upgraded = false
  }

  checkout(length, additionalRoots) {
    const roots = []
    let r = 0

    const head = 2 * length - 2
    const gaps = new Set()
    const all = new Map()

    // additional roots is so the original roots can be passed (we mutate the array in appendRoot)
    if (additionalRoots) {
      for (const node of additionalRoots) all.set(node.index, node)
    }

    for (const node of this.nodes) all.set(node.index, node)

    for (const index of flat.fullRoots(head + 2)) {
      const left = flat.leftSpan(index)
      if (left !== 0) gaps.add(left - 1)

      if (r < this.roots.length && this.roots[r].index === index) {
        roots.push(this.roots[r++])
        continue
      }
      const node = all.get(index)
      if (!node) throw new BAD_ARGUMENT('root missing for given length')
      roots.push(node)
    }

    this.roots = roots
    this.length = length
    this.byteLength = totalSize(roots)
    this.hashCached = null
    this.signature = null

    for (let i = 0; i < this.nodes.length; i++) {
      const index = this.nodes[i].index
      if (index <= head && !gaps.has(index)) continue
      const last = this.nodes.pop()
      if (i < this.nodes.length) this.nodes[i--] = last
    }
  }

  prune(length) {
    if (length === 0) return

    const head = 2 * length - 2
    const gaps = new Set()

    // TODO: make a function for this in flat-tree
    for (const index of flat.fullRoots(head + 2)) {
      const left = flat.leftSpan(index)
      if (left !== 0) gaps.add(left - 1)
    }

    for (let i = 0; i < this.nodes.length; i++) {
      const index = this.nodes[i].index
      if (index > head || gaps.has(index)) continue
      const last = this.nodes.pop()
      if (i < this.nodes.length) this.nodes[i--] = last
    }
  }

  clone() {
    const b = new MerkleTreeBatch(this.session)

    b.fork = this.fork
    b.roots = [...this.roots]
    b.length = this.length
    b.byteLength = this.byteLength
    b.signature = this.signature
    b.treeLength = this.treeLength
    b.treeFork = this.treeFork
    b.tree = this.tree
    b.nodes = [...this.nodes]
    b.upgraded = this.upgraded

    return b
  }

  hash() {
    if (this.hashCached === null) this.hashCached = unslab(crypto.tree(this.roots))
    return this.hashCached
  }

  signable(manifestHash) {
    return caps.treeSignable(manifestHash, this.hash(), this.length, this.fork)
  }

  signableCompat(noHeader) {
    return caps.treeSignableCompat(this.hash(), this.length, this.fork, noHeader)
  }

  get(index) {
    if (index >= this.length * 2) {
      return null
    }

    for (const n of this.nodes) {
      if (n.index === index) return n
    }

    return getTreeNodeFromStorage(this.session.storage, index)
  }

  // deprecated, use sssion proof instead
  proof(batch, { block, hash, seek, upgrade }) {
    return generateProof(this.session, batch, block, hash, seek, upgrade)
  }

  verifyUpgrade(proof) {
    const unverified = verifyTree(proof, this.nodes)

    if (!proof.upgrade) throw INVALID_OPERATION('Expected upgrade proof')

    return verifyUpgrade(proof, unverified, this)
  }

  addNodesUnsafe(nodes) {
    for (let i = 0; i < nodes.length; i++) {
      this.nodes.push(nodes[i])
    }
  }

  append(buf) {
    const head = this.length * 2
    const ite = flat.iterator(head)
    const node = blockNode(head, buf)

    this.appendRoot(node, ite)
  }

  appendRoot(node, ite) {
    node = unslabNode(node)
    this.hashCached = null
    this.upgraded = true
    this.length += ite.factor / 2
    this.byteLength += node.size
    this.roots.push(node)
    this.nodes.push(node)

    while (this.roots.length > 1) {
      const a = this.roots[this.roots.length - 1]
      const b = this.roots[this.roots.length - 2]

      // TODO: just have a peek sibling instead? (pretty sure it's always the left sib as well)
      if (ite.sibling() !== b.index) {
        ite.sibling() // unset so it always points to last root
        break
      }

      const node = unslabNode(parentNode(ite.parent(), a, b))
      this.nodes.push(node)
      this.roots.pop()
      this.roots.pop()
      this.roots.push(node)
    }
  }

  commitable() {
    return (
      this.treeFork === this.session.fork &&
      (this.upgraded
        ? this.treeLength === this.session.length
        : this.treeLength <= this.session.length)
    )
  }

  commit(tx) {
    if (tx === undefined) throw INVALID_OPERATION('No database batch was passed')

    if (this.session.core._repairMode) {
      throw ASSERTION('Cannot commit while repair mode is on')
    }

    if (!this.commitable()) {
      throw INVALID_OPERATION('Tree was modified during batch, refusing to commit')
    }

    if (this.upgraded) this._commitUpgrade(tx)

    for (let i = 0; i < this.nodes.length; i++) {
      const node = this.nodes[i]
      tx.putTreeNode(node)
    }

    this.committed = true

    return this
  }

  _commitUpgrade(tx) {
    // TODO: If easy to detect, we should refuse an trunc+append here without a fork id
    // change. Will only happen on user error so mostly to prevent that.

    if (this.ancestors < this.treeLength) {
      tx.deleteTreeNodeRange(this.ancestors * 2, this.treeLength * 2)

      if (this.ancestors > 0) {
        const head = this.ancestors * 2
        const ite = flat.iterator(head - 2)

        while (true) {
          if (ite.contains(head) && ite.index < head) {
            tx.deleteTreeNode(ite.index)
          }
          if (ite.offset === 0) break
          ite.parent()
        }

        this.truncated = true
      }
    }
  }

  seek(bytes, padding) {
    return new ByteSeeker(this, this, bytes, padding)
  }

  byteRange(index) {
    const rx = this.storage.read()
    const range = getByteRange(this, index, rx)
    rx.tryFlush()

    return range
  }

  byteOffset(index) {
    if (index === 2 * this.length) return this.byteLength

    const rx = this.storage.read()
    const offset = getByteOffset(this, index, rx)
    rx.tryFlush()

    return offset
  }

  async downgrade() {
    if (!this.upgraded) return true

    const rx = this.storage.read()
    const nodePromises = []

    for (const r of this.roots) {
      nodePromises.push(rx.getTreeNode(r.index))
    }

    rx.tryFlush()

    const nodes = await Promise.all(nodePromises)

    for (let i = 0; i < this.roots.length; i++) {
      const root = this.roots[i]
      const node = nodes[i]

      if (!node) return false
      if (!b4a.equals(node.hash, root.hash)) return false
    }

    this.upgraded = false
    return true
  }

  async restore(length) {
    if (length === this.length) return this

    const roots = unslabNodes(await MerkleTree.getRootsFromStorage(this.storage, length))

    this.roots = roots
    this.length = length
    this.byteLength = totalSize(roots)
    this.ancestors = length

    for (const node of roots) this.byteLength += node.size

    return this
  }
}

class ReorgBatch extends MerkleTreeBatch {
  constructor(session) {
    super(session)

    this.roots = []
    this.length = 0
    this.byteLength = 0
    this.diff = null
    this.ancestors = 0
    // We set upgraded because reorgs are signed so hit will
    // hit the same code paths (like the treeLength check in commit)
    this.upgraded = true
    this.want = {
      nodes: 0,
      start: 0,
      end: 0
    }
  }

  get finished() {
    return this.want === null
  }

  update(proof) {
    if (this.want === null) return true

    const nodes = []
    const root = verifyTree(proof, nodes)

    if (root === null || !b4a.equals(root.hash, this.diff.hash)) return false

    this.nodes.push(...nodes)
    return this._update(nodes)
  }

  async _update(nodes) {
    const n = new Map()
    for (const node of nodes) n.set(node.index, node)

    let diff = null
    const ite = flat.iterator(this.diff.index)
    const startingDiff = this.diff

    while ((ite.index & 1) !== 0) {
      const left = n.get(ite.leftChild())
      if (!left) break

      const existing = await getTreeNodeFromStorage(this.session.storage, left.index)
      if (!existing || !b4a.equals(existing.hash, left.hash)) {
        diff = left
      } else {
        diff = n.get(ite.sibling())
      }
    }

    if ((this.diff.index & 1) === 0) return true
    if (diff === null) return false
    if (startingDiff !== this.diff) return false

    return this._updateDiffRoot(diff)
  }

  _updateDiffRoot(diff) {
    if (this.want === null) return true

    const spans = flat.spans(diff.index)
    const start = spans[0] / 2
    const end = Math.min(this.treeLength, spans[1] / 2 + 1)
    const len = end - start

    this.ancestors = start
    this.diff = diff

    if ((diff.index & 1) === 0 || this.want.start >= this.treeLength || len <= 0) {
      this.want = null
      return true
    }

    this.want.start = start
    this.want.end = end
    this.want.nodes = log2(spans[1] - spans[0] + 2) - 1

    return false
  }
}

class ByteSeeker {
  constructor(session, bytes, padding = 0) {
    this.session = session
    this.bytes = bytes
    this.padding = padding

    const size = session.byteLength - session.length * padding

    this.start = bytes >= size ? session.length : 0
    this.end = bytes < size ? session.length : 0
  }

  async _seek(bytes) {
    if (!bytes) return [0, 0]

    for (const node of this.session.roots) {
      // all async ticks happen once we find the root so safe
      const size = getUnpaddedSize(node, this.padding, null)

      if (bytes === size) return [flat.rightSpan(node.index) + 2, 0]
      if (bytes > size) {
        bytes -= size
        continue
      }

      const ite = flat.iterator(node.index)

      while ((ite.index & 1) !== 0) {
        const l = await getTreeNodeFromStorage(this.session.storage, ite.leftChild())

        if (l) {
          const size = getUnpaddedSize(l, this.padding, ite)

          if (size === bytes) return [ite.rightSpan() + 2, 0]
          if (size > bytes) continue
          bytes -= size
          ite.sibling()
        } else {
          ite.parent()
          return [ite.index, bytes]
        }
      }

      return [ite.index, bytes]
    }

    return null
  }

  async update() {
    // TODO: combine _seek and this, much simpler
    const res = await this._seek(this.bytes)
    if (!res) return null
    if ((res[0] & 1) === 0) return [res[0] / 2, res[1]]

    const span = flat.spans(res[0])
    this.start = span[0] / 2
    this.end = span[1] / 2 + 1

    return null
  }
}

class TreeProof {
  constructor(session, block, hash, seek, upgrade) {
    this.fork = session.fork
    this.signature = session.signature

    this.block = block
    this.hash = hash
    this.seek = seek
    this.upgrade = upgrade

    this.pending = {
      node: null,
      seek: null,
      upgrade: null,
      additionalUpgrade: null
    }
  }

  async settle() {
    const result = {
      fork: this.fork,
      block: null,
      hash: null,
      seek: null,
      upgrade: null,
      manifest: null
    }

    const [pNode, pSeek, pUpgrade, pAdditional] = await settleProof(this.pending)

    if (this.block) {
      if (pNode === null) throw INVALID_OPERATION('Invalid block request')
      result.block = {
        index: this.block.index,
        value: null, // populated upstream, alloc it here for simplicity
        nodes: pNode
      }
    } else if (this.hash) {
      if (pNode === null) throw INVALID_OPERATION('Invalid block request')
      result.hash = {
        index: this.hash.index,
        nodes: pNode
      }
    }

    if (this.seek && pSeek !== null) {
      result.seek = {
        bytes: this.seek.bytes,
        nodes: pSeek
      }
    }

    if (this.upgrade) {
      result.upgrade = {
        start: this.upgrade.start,
        length: this.upgrade.length,
        nodes: pUpgrade,
        additionalNodes: pAdditional || [],
        signature: this.signature
      }
    }

    return result
  }
}

class MerkleTree {
  static hash(s) {
    return unslab(crypto.tree(s.roots))
  }

  static signable(s, namespace) {
    return caps.treeSignable(namespace, MerkleTree.hash(s), s.length, s.fork)
  }

  static size(roots) {
    return totalSize(roots)
  }

  static span(roots) {
    return totalSpan(roots)
  }

  static getRoots(session, length) {
    return MerkleTree.getRootsFromStorage(session.storage, length)
  }

  static getRootsFromStorage(storage, length) {
    const indexes = flat.fullRoots(2 * length)
    const roots = new Array(indexes.length)
    const rx = storage.read()

    for (let i = 0; i < indexes.length; i++) {
      roots[i] = getTreeNodeOrError(rx, indexes[i])
    }

    rx.tryFlush()

    return Promise.all(roots)
  }

  static async upgradeable(session, length) {
    const indexes = flat.fullRoots(2 * length)
    const roots = new Array(indexes.length)
    const rx = session.storage.read()

    for (let i = 0; i < indexes.length; i++) {
      roots[i] = rx.getTreeNode(indexes[i])
    }

    rx.tryFlush()

    for (const node of await Promise.all(roots)) {
      if (node === null) return false
    }

    return true
  }

  static seek(session, bytes, padding) {
    return new ByteSeeker(session, bytes, padding)
  }

  static get(session, index) {
    return getTreeNodeFromStorage(session.storage, index)
  }

  static async truncate(session, length, batch, fork = batch.fork) {
    const head = length * 2
    const fullRoots = flat.fullRoots(head)

    for (let i = 0; i < fullRoots.length; i++) {
      const root = fullRoots[i]
      if (i < batch.roots.length && batch.roots[i].index === root) continue

      while (batch.roots.length > i) batch.roots.pop()
      batch.roots.push(unslabNode(await getTreeNodeFromStorageOrError(session.storage, root)))
    }

    while (batch.roots.length > fullRoots.length) {
      batch.roots.pop()
    }

    batch.fork = fork
    batch.length = length
    batch.ancestors = length
    batch.byteLength = totalSize(batch.roots)
    batch.upgraded = true

    return batch
  }

  static async reorg(session, proof, batch) {
    let unverified = null

    if (proof.block || proof.hash || proof.seek) {
      unverified = verifyTree(proof, batch.nodes)
    }

    if (!verifyUpgrade(proof, unverified, batch)) {
      throw INVALID_PROOF('Fork proof not verifiable')
    }

    for (const root of batch.roots) {
      const existing = await getTreeNodeFromStorage(session.storage, root.index)
      if (existing && b4a.equals(existing.hash, root.hash)) continue
      batch._updateDiffRoot(root)
      break
    }

    if (batch.diff !== null) {
      await batch._update(batch.nodes)
    } else {
      batch.want = null
      batch.ancestors = batch.length
    }

    return batch
  }

  static verifyFullyRemote(session, proof) {
    // TODO: impl this less hackishly
    const batch = new MerkleTreeBatch(session)

    batch.fork = proof.fork
    batch.roots = []
    batch.length = 0
    batch.ancestors = 0
    batch.byteLength = 0

    let unverified = verifyTree(proof, batch.nodes)

    if (proof.upgrade) {
      if (verifyUpgrade(proof, unverified, batch)) {
        unverified = null
      }
    }

    return batch
  }

  static async verify(session, proof) {
    const batch = new MerkleTreeBatch(session)

    let unverified = verifyTree(proof, batch.nodes)

    if (proof.upgrade) {
      if (verifyUpgrade(proof, unverified, batch)) {
        unverified = null
      }
    }

    if (unverified) {
      const verified = await getTreeNodeFromStorageOrError(session.storage, unverified.index)
      if (!b4a.equals(verified.hash, unverified.hash)) {
        throw INVALID_CHECKSUM('Invalid checksum at node ' + unverified.index)
      }
    }

    return batch
  }

  static proof(session, rx, { block, hash, seek, upgrade }) {
    return generateProof(session, rx, block, hash, seek, upgrade)
  }

  static maxMissingNodes(index, length) {
    const head = 2 * length
    const ite = flat.iterator(index)

    // See iterator.rightSpan()
    const iteRightSpan = ite.index + ite.factor / 2 - 1
    // If the index is not in the current tree, we do not know how many missing nodes there are...
    if (iteRightSpan >= head) return 0

    for (const r of flat.fullRoots(head)) {
      if (r === index) return 0
    }

    // need missing nodes not inclusive of index
    ite.parent()

    let cnt = 0
    while (!ite.contains(head)) {
      cnt++
      ite.parent()
    }

    return cnt
  }

  static async missingNodes(session, index, length) {
    const head = 2 * length
    const ite = flat.iterator(index)

    // See iterator.rightSpan()
    const iteRightSpan = ite.index + ite.factor / 2 - 1
    // If the index is not in the current tree, we do not know how many missing nodes there are...
    if (iteRightSpan >= head) return 0

    let cnt = 0
    // TODO: we could prop use a read batch here and do this in blocks of X for perf
    while (!ite.contains(head) && !(await hasTreeNode(session.storage, ite.index))) {
      cnt++
      if (cnt >= 1024) {
        throw ASSERTION('Bad arguments to missingNodes index=' + index + ' at length=' + length)
      }
      ite.parent()
    }

    return cnt
  }

  static byteOffset(session, index) {
    return getByteOffsetSession(session, index, null)
  }

  static byteRange(session, index) {
    const rx = session.storage.read()
    const offset = getByteOffsetSession(session, index, rx)
    const size = getNodeSize(index, rx)
    rx.tryFlush()
    return Promise.all([offset, size])
  }

  static upgradeLength(proof) {
    const extra = proof.additionalNodes

    if (extra.length) {
      const last = extra[extra.length - 1]
      const index = flat.rightSpan(last.index)
      return index / 2 + 1
    }

    return proof.start + proof.length
  }
}

module.exports = {
  MerkleTreeBatch,
  ReorgBatch,
  MerkleTree
}

async function getNodeSize(index, rx) {
  return (await getTreeNodeOrError(rx, index)).size
}

async function getByteOffsetSession(session, index, rx) {
  if (index === 2 * session.length) return session.byteLength

  const treeNodes =
    rx === null
      ? await getByteOffsetBatchFlush(session.roots, index, session.storage.read())
      : await getByteOffsetBatch(session.roots, index, rx)

  let offset = 0
  for (const node of treeNodes) offset += node.size

  return offset
}

async function getByteOffset(tree, index, rx) {
  if (index === 2 * tree.length) return tree.byteLength

  const treeNodes = await getByteOffsetBatch(tree.roots, index, rx)

  let offset = 0
  for (const node of treeNodes) offset += node.size

  return offset
}

function getByteOffsetBatchFlush(roots, index, rx) {
  const treeNodes = getByteOffsetBatch(roots, index, rx)
  rx.tryFlush()
  return treeNodes
}

function getByteOffsetBatch(roots, index, rx) {
  if ((index & 1) === 1) index = flat.leftSpan(index)

  let head = 0
  let cnt = 0

  const promises = []

  for (const node of roots) {
    // all async ticks happen once we find the root so safe
    head += 2 * (node.index - head + 1)

    if (index >= head) {
      promises.push(node.size)
      continue
    }

    const ite = flat.iterator(node.index)

    while (ite.index !== index) {
      if (++cnt >= 1024) throw ASSERTION('Bad getByteOffsetSession index=' + index)

      if (index < ite.index) {
        ite.leftChild()
      } else {
        promises.push(getTreeNodeOrError(rx, ite.leftChild()))
        ite.sibling()
      }
    }

    return Promise.all(promises)
  }

  throw ASSERTION('Failed to find offset')
}

function getByteRange(tree, index, rx) {
  const head = 2 * tree.length
  if (((index & 1) === 0 ? index : flat.rightSpan(index)) >= head) {
    throw BAD_ARGUMENT('Index is out of bounds')
  }

  const offset = getByteOffset(tree, index, rx)
  const size = getNodeSize(index, rx)

  return Promise.all([offset, size])
}

// All the methods needed for proof verification

function verifyTree({ block, hash, seek }, nodes) {
  const untrustedNode = block
    ? { index: 2 * block.index, value: block.value, nodes: block.nodes }
    : hash
      ? { index: hash.index, value: null, nodes: hash.nodes }
      : null

  if (untrustedNode === null && (!seek || !seek.nodes.length)) return null

  let root = null

  if (seek && seek.nodes.length) {
    const ite = flat.iterator(seek.nodes[0].index)
    const q = new NodeQueue(seek.nodes)

    root = q.shift(ite.index)
    nodes.push(root)

    while (q.length > 0) {
      const node = q.shift(ite.sibling())

      root = parentNode(ite.parent(), root, node)
      nodes.push(node)
      nodes.push(root)
    }
  }

  if (untrustedNode === null) return root

  const ite = flat.iterator(untrustedNode.index)
  const blockHash = untrustedNode.value && blockNode(ite.index, untrustedNode.value)

  const q = new NodeQueue(untrustedNode.nodes, root)

  root = blockHash || q.shift(ite.index)
  nodes.push(root)

  while (q.length > 0) {
    const node = q.shift(ite.sibling())

    root = parentNode(ite.parent(), root, node)
    nodes.push(node)
    nodes.push(root)
  }

  return root
}

function verifyUpgrade({ fork, upgrade }, blockRoot, batch) {
  const prologue = batch.prologue

  if (prologue) {
    const { start, length } = upgrade
    if (start < prologue.length && (start !== 0 || length < prologue.length)) {
      throw INVALID_PROOF('Upgrade does not satisfy prologue')
    }
  }

  const q = new NodeQueue(upgrade.nodes, blockRoot)

  let grow = batch.roots.length > 0
  let i = 0

  const to = 2 * (upgrade.start + upgrade.length)
  const ite = flat.iterator(0)

  for (; ite.fullRoot(to); ite.nextTree()) {
    if (i < batch.roots.length && batch.roots[i].index === ite.index) {
      i++
      continue
    }

    if (grow) {
      grow = false
      const root = ite.index
      if (i < batch.roots.length) {
        ite.seek(batch.roots[batch.roots.length - 1].index)
        while (ite.index !== root) {
          batch.appendRoot(q.shift(ite.sibling()), ite)
        }
        continue
      }
    }

    batch.appendRoot(q.shift(ite.index), ite)
  }

  if (prologue && batch.length === prologue.length) {
    if (!b4a.equals(prologue.hash, batch.hash())) {
      throw INVALID_PROOF('Invalid hash')
    }
  }

  const extra = upgrade.additionalNodes

  ite.seek(batch.roots[batch.roots.length - 1].index)
  i = 0

  while (i < extra.length && extra[i].index === ite.sibling()) {
    batch.appendRoot(extra[i++], ite)
  }

  while (i < extra.length) {
    const node = extra[i++]

    while (node.index !== ite.index) {
      if (ite.factor === 2) throw INVALID_OPERATION('Unexpected node: ' + node.index)
      ite.leftChild()
    }

    batch.appendRoot(node, ite)
    ite.sibling()
  }

  batch.signature = unslab(upgrade.signature)
  batch.fork = fork

  return q.extra === null
}

async function seekFromHead(session, head, bytes, padding) {
  const roots = flat.fullRoots(head)

  for (let i = 0; i < roots.length; i++) {
    const root = roots[i]
    const node = await getTreeNodeFromStorage(session.storage, root)
    const size = getUnpaddedSize(node, padding, null)

    if (bytes === size) return root
    if (bytes > size) {
      bytes -= size
      continue
    }

    return seekTrustedTree(session, root, bytes, padding)
  }

  return head
}

// trust that bytes are within the root tree and find the block at bytes

async function seekTrustedTree(session, root, bytes, padding) {
  if (!bytes) return root

  const ite = flat.iterator(root)
  let cnt = 0

  while ((ite.index & 1) !== 0) {
    if (++cnt >= 1024) throw ASSERTION('Bad seekTrusted bytes=' + bytes + ', paddding=' + padding)
    const l = await getTreeNodeFromStorage(session.storage, ite.leftChild())

    if (l) {
      const size = getUnpaddedSize(l, padding, ite)
      if (size === bytes) return ite.index
      if (size > bytes) continue
      bytes -= size
      ite.sibling()
    } else {
      ite.parent()
      return ite.index
    }
  }

  return ite.index
}

// try to find the block at bytes without trusting that is *is* within the root passed

async function seekUntrustedTree(session, root, bytes, padding) {
  const offset =
    (await getByteOffsetSession(session, root, null)) -
    (padding ? (padding * flat.leftSpan(root)) / 2 : 0)

  if (offset > bytes) throw INVALID_OPERATION('Invalid seek')
  if (offset === bytes) return root

  bytes -= offset

  const node = await getTreeNodeFromStorageOrError(session.storage, root)

  if (getUnpaddedSize(node, padding, null) <= bytes) throw INVALID_OPERATION('Invalid seek')

  return seekTrustedTree(session, root, bytes, padding)
}

// Below is proof production, ie, construct proofs to verify a request
// Note, that all these methods are sync as we can statically infer which nodes
// are needed for the remote to verify given they arguments they passed us

function seekProof(session, rx, seekRoot, root, p) {
  const ite = flat.iterator(seekRoot)
  let cnt = 0

  p.seek = []
  p.seek.push(getTreeNodeOrError(rx, ite.index))

  while (ite.index !== root) {
    if (++cnt >= 1024) throw ASSERTION('Bad seekProof seekRoot=' + seekRoot + ', root=' + root)
    ite.sibling()
    p.seek.push(getTreeNodeOrError(rx, ite.index))
    ite.parent()
  }
}

function blockAndSeekProof(session, rx, node, seek, seekRoot, root, p) {
  if (!node) return seekProof(session, rx, seekRoot, root, p)

  const ite = flat.iterator(node.index)
  let cnt = 0

  p.node = []
  if (!node.value) p.node.push(getTreeNodeOrError(rx, ite.index))

  while (ite.index !== root) {
    if (++cnt >= 1024) {
      throw ASSERTION('Bad blockAndSeekProof seekRoot=' + seekRoot + ', root=' + root)
    }
    ite.sibling()

    if (seek && ite.contains(seekRoot) && ite.index !== seekRoot) {
      seekProof(session, rx, seekRoot, ite.index, p)
    } else {
      p.node.push(getTreeNodeOrError(rx, ite.index))
    }

    ite.parent()
  }
}

function upgradeProof(session, rx, node, seek, from, to, subTree, p) {
  if (from === 0) p.upgrade = []

  for (const ite = flat.iterator(0); ite.fullRoot(to); ite.nextTree()) {
    // check if they already have the node
    if (ite.index + ite.factor / 2 < from) continue

    // connect existing tree
    if (p.upgrade === null && ite.contains(from - 2)) {
      p.upgrade = []

      const root = ite.index
      const target = from - 2
      let cnt = 0

      ite.seek(target)

      while (ite.index !== root) {
        if (++cnt >= 1024) throw ASSERTION('Bad upgradeProof target=' + target + ', root=' + root)

        ite.sibling()
        if (ite.index > target) {
          if (p.node === null && p.seek === null && ite.contains(subTree)) {
            blockAndSeekProof(session, rx, node, seek, subTree, ite.index, p)
          } else {
            p.upgrade.push(getTreeNodeOrError(rx, ite.index))
          }
        }
        ite.parent()
      }

      continue
    }

    if (p.upgrade === null) {
      p.upgrade = []
    }

    // if the subtree included is a child of this tree, include that one
    // instead of a dup node
    if (p.node === null && p.seek === null && ite.contains(subTree)) {
      blockAndSeekProof(session, rx, node, seek, subTree, ite.index, p)
      continue
    }

    // add root (can be optimised since the root might be in tree.roots)
    p.upgrade.push(getTreeNodeOrError(rx, ite.index))
  }
}

function additionalUpgradeProof(session, rx, from, to, p) {
  if (from === 0) p.additionalUpgrade = []

  for (const ite = flat.iterator(0); ite.fullRoot(to); ite.nextTree()) {
    // check if they already have the node
    if (ite.index + ite.factor / 2 < from) continue

    // connect existing tree
    if (p.additionalUpgrade === null && ite.contains(from - 2)) {
      p.additionalUpgrade = []

      const root = ite.index
      const target = from - 2
      let cnt = 0

      ite.seek(target)

      while (ite.index !== root) {
        if (++cnt >= 1024) {
          throw ASSERTION(
            'Bad arguments to additionalUpgradeProof root=' + root + ' target=' + target
          )
        }
        ite.sibling()
        if (ite.index > target) {
          p.additionalUpgrade.push(getTreeNodeOrError(rx, ite.index))
        }
        ite.parent()
      }

      continue
    }

    if (p.additionalUpgrade === null) {
      p.additionalUpgrade = []
    }

    // add root (can be optimised since the root is in tree.roots)
    p.additionalUpgrade.push(getTreeNodeOrError(rx, ite.index))
  }
}

function nodesToRoot(index, nodes, head) {
  const ite = flat.iterator(index)

  for (let i = 0; i < nodes; i++) {
    ite.parent()
    if (ite.contains(head)) throw INVALID_OPERATION('Nodes is out of bounds')
  }

  return ite.index
}

function totalSize(nodes) {
  let s = 0
  for (const node of nodes) s += node.size
  return s
}

function totalSpan(nodes) {
  let s = 0
  for (const node of nodes) s += 2 * (node.index - s + 1)
  return s
}

function blockNode(index, value) {
  return { index, size: value.byteLength, hash: crypto.data(value) }
}

function parentNode(index, a, b) {
  return { index, size: a.size + b.size, hash: crypto.parent(a, b) }
}

function log2(n) {
  let res = 1

  while (n > 2) {
    n /= 2
    res++
  }

  return res
}

function normalizeIndexed(block, hash) {
  if (block) {
    return {
      value: true,
      index: block.index * 2,
      nodes: block.nodes,
      lastIndex: block.index
    }
  }
  if (hash) {
    return {
      value: false,
      index: hash.index,
      nodes: hash.nodes,
      lastIndex: flat.rightSpan(hash.index) / 2
    }
  }
  return null
}

async function getTreeNodeOrError(rx, index) {
  const node = await rx.getTreeNode(index)
  if (node === null) {
    throw INVALID_OPERATION('Expected tree node ' + index + ' from storage, got (nil)')
  }
  return node
}

function getTreeNodeFromStorageOrError(storage, index) {
  const rx = storage.read()
  const p = getTreeNodeOrError(rx, index)
  rx.tryFlush()
  return p
}

function getTreeNodeFromStorage(storage, index) {
  const rx = storage.read()
  const node = rx.getTreeNode(index)
  rx.tryFlush()
  return node
}

function hasTreeNode(storage, index) {
  const rx = storage.read()
  const has = rx.hasTreeNode(index)
  rx.tryFlush()
  return has
}

async function settleProof(p) {
  const result = [
    p.node && Promise.all(p.node),
    p.seek && Promise.all(p.seek),
    p.upgrade && Promise.all(p.upgrade),
    p.additionalUpgrade && Promise.all(p.additionalUpgrade)
  ]

  try {
    return await Promise.all(result)
  } catch (err) {
    if (p.node) await Promise.allSettled(p.node)
    if (p.seek) await Promise.allSettled(p.seek)
    if (p.upgrade) await Promise.allSettled(p.upgrade)
    if (p.additionalUpgrade) await Promise.allSettled(p.additionalUpgrade)
    throw err
  }
}

// tree can be either the merkle tree or a merkle tree batch
async function generateProof(session, rx, block, hash, seek, upgrade) {
  // Important that this does not throw inbetween making the promise arrays
  // and finalise being called, otherwise there will be lingering promises in the background

  if (session.prologue && upgrade) {
    upgrade.start = upgrade.start < session.prologue.length ? 0 : upgrade.start
    upgrade.length =
      upgrade.start < session.prologue.length ? session.prologue.length : upgrade.length
  }

  const head = 2 * session.length
  const from = upgrade ? upgrade.start * 2 : 0
  const to = upgrade ? from + upgrade.length * 2 : head
  const node = normalizeIndexed(block, hash)

  // can't do anything as we have no data...
  if (head === 0) return new TreeProof(session, null, null, null, null)

  if (from >= to || to > head) {
    throw INVALID_OPERATION('Invalid upgrade')
  }
  if (seek && upgrade && node !== null && node.index >= from) {
    throw INVALID_OPERATION('Cannot both do a seek and block/hash request when upgrading')
  }

  let subTree = head

  const p = new TreeProof(session, block, hash, seek, upgrade)

  if (node !== null && (!upgrade || node.lastIndex < upgrade.start)) {
    subTree = nodesToRoot(node.index, node.nodes, to)
    const seekRoot = seek
      ? await seekUntrustedTree(session, subTree, seek.bytes, seek.padding)
      : head
    blockAndSeekProof(session, rx, node, seek, seekRoot, subTree, p.pending)
  } else if ((node || seek) && upgrade) {
    subTree = seek ? await seekFromHead(session, to, seek.bytes, seek.padding) : node.index
  }

  if (upgrade) {
    upgradeProof(session, rx, node, seek, from, to, subTree, p.pending)
    if (head > to) additionalUpgradeProof(session, rx, to, head, p.pending)
  }

  return p
}

function getUnpaddedSize(node, padding, ite) {
  return padding === 0
    ? node.size
    : node.size - padding * (ite ? ite.countLeaves() : flat.countLeaves(node.index))
}

function unslabNodes(nodes) {
  for (const node of nodes) unslabNode(node)
  return nodes
}

function unslabNode(node) {
  if (node === null) return node
  node.hash = unslab(node.hash)
  return node
}
const c = require('compact-encoding')
const { DEFAULT_NAMESPACE } = require('./caps')
const { INVALID_OPLOG_VERSION } = require('hypercore-errors')
const unslab = require('unslab')

const MANIFEST_PATCH = 0b00000001
const MANIFEST_PROLOGUE = 0b00000010
const MANIFEST_LINKED = 0b00000100
const MANIFEST_USER_DATA = 0b00001000

const hashes = {
  preencode(state, m) {
    state.end++ // small uint
  },
  encode(state, m) {
    if (m === 'blake2b') {
      c.uint.encode(state, 0)
      return
    }

    throw new Error('Unknown hash: ' + m)
  },
  decode(state) {
    const n = c.uint.decode(state)
    if (n === 0) return 'blake2b'
    throw new Error('Unknown hash id: ' + n)
  }
}

const signatures = {
  preencode(state, m) {
    state.end++ // small uint
  },
  encode(state, m) {
    if (m === 'ed25519') {
      c.uint.encode(state, 0)
      return
    }

    throw new Error('Unknown signature: ' + m)
  },
  decode(state) {
    const n = c.uint.decode(state)
    if (n === 0) return 'ed25519'
    throw new Error('Unknown signature id: ' + n)
  }
}

const signer = {
  preencode(state, m) {
    signatures.preencode(state, m.signature)
    c.fixed32.preencode(state, m.namespace)
    c.fixed32.preencode(state, m.publicKey)
  },
  encode(state, m) {
    signatures.encode(state, m.signature)
    c.fixed32.encode(state, m.namespace)
    c.fixed32.encode(state, m.publicKey)
  },
  decode(state) {
    return {
      signature: signatures.decode(state),
      namespace: c.fixed32.decode(state),
      publicKey: c.fixed32.decode(state)
    }
  }
}

const signerArray = c.array(signer)

const prologue = {
  preencode(state, p) {
    c.fixed32.preencode(state, p.hash)
    c.uint.preencode(state, p.length)
  },
  encode(state, p) {
    c.fixed32.encode(state, p.hash)
    c.uint.encode(state, p.length)
  },
  decode(state) {
    return {
      hash: c.fixed32.decode(state),
      length: c.uint.decode(state)
    }
  }
}

const manifestv0 = {
  preencode(state, m) {
    hashes.preencode(state, m.hash)
    state.end++ // type

    if (m.prologue && m.signers.length === 0) {
      c.fixed32.preencode(state, m.prologue.hash)
      return
    }

    if (m.quorum === 1 && m.signers.length === 1 && !m.allowPatch) {
      signer.preencode(state, m.signers[0])
    } else {
      state.end++ // flags
      c.uint.preencode(state, m.quorum)
      signerArray.preencode(state, m.signers)
    }
  },
  encode(state, m) {
    hashes.encode(state, m.hash)

    if (m.prologue && m.signers.length === 0) {
      c.uint.encode(state, 0)
      c.fixed32.encode(state, m.prologue.hash)
      return
    }

    if (m.quorum === 1 && m.signers.length === 1 && !m.allowPatch) {
      c.uint.encode(state, 1)
      signer.encode(state, m.signers[0])
    } else {
      c.uint.encode(state, 2)
      c.uint.encode(state, m.allowPatch ? 1 : 0)
      c.uint.encode(state, m.quorum)
      signerArray.encode(state, m.signers)
    }
  },
  decode(state) {
    const hash = hashes.decode(state)
    const type = c.uint.decode(state)

    if (type > 2) throw new Error('Unknown type: ' + type)

    if (type === 0) {
      return {
        version: 0,
        hash,
        allowPatch: false,
        quorum: 0,
        signers: [],
        prologue: {
          hash: c.fixed32.decode(state),
          length: 0
        },
        linked: null,
        userData: null
      }
    }

    if (type === 1) {
      return {
        version: 0,
        hash,
        allowPatch: false,
        quorum: 1,
        signers: [signer.decode(state)],
        prologue: null,
        linked: null,
        userData: null
      }
    }

    const flags = c.uint.decode(state)

    return {
      version: 0,
      hash,
      allowPatch: (flags & 1) !== 0,
      quorum: c.uint.decode(state),
      signers: signerArray.decode(state),
      prologue: null,
      linked: null,
      userData: null
    }
  }
}

const fixed32Array = c.array(c.fixed32)

const manifest = (exports.manifest = {
  preencode(state, m) {
    state.end++ // version

    if (m.version === 0) return manifestv0.preencode(state, m)

    state.end++ // flags
    hashes.preencode(state, m.hash)

    c.uint.preencode(state, m.quorum)
    signerArray.preencode(state, m.signers)

    if (m.prologue) prologue.preencode(state, m.prologue)
    if (m.linked) fixed32Array.preencode(state, m.linked)
    if (m.userData) c.buffer.preencode(state, m.userData)
  },
  encode(state, m) {
    c.uint.encode(state, m.version)

    if (m.version === 0) return manifestv0.encode(state, m)

    let flags = 0
    if (m.allowPatch) flags |= MANIFEST_PATCH
    if (m.prologue) flags |= MANIFEST_PROLOGUE
    if (m.linked) flags |= MANIFEST_LINKED
    if (m.userData) flags |= MANIFEST_USER_DATA

    c.uint.encode(state, flags)
    hashes.encode(state, m.hash)

    c.uint.encode(state, m.quorum)
    signerArray.encode(state, m.signers)

    if (m.prologue) prologue.encode(state, m.prologue)
    if (m.linked) fixed32Array.encode(state, m.linked)
    if (m.userData) c.buffer.encode(state, m.userData)
  },
  decode(state) {
    const version = c.uint.decode(state)

    if (version === 0) return manifestv0.decode(state)
    if (version > 2) throw new Error('Unknown version: ' + version)

    const flags = c.uint.decode(state)
    const hash = hashes.decode(state)
    const quorum = c.uint.decode(state)
    const signers = signerArray.decode(state)

    const hasPatch = (flags & MANIFEST_PATCH) !== 0
    const hasPrologue = (flags & MANIFEST_PROLOGUE) !== 0
    const hasLinked = (flags & MANIFEST_LINKED) !== 0
    const hasUserData = (flags & MANIFEST_USER_DATA) !== 0

    return {
      version,
      hash,
      allowPatch: hasPatch,
      quorum,
      signers,
      prologue: hasPrologue ? prologue.decode(state) : null,
      linked: hasLinked ? fixed32Array.decode(state) : null,
      userData: hasUserData ? c.buffer.decode(state) : null
    }
  }
})

const node = {
  preencode(state, n) {
    c.uint.preencode(state, n.index)
    c.uint.preencode(state, n.size)
    c.fixed32.preencode(state, n.hash)
  },
  encode(state, n) {
    c.uint.encode(state, n.index)
    c.uint.encode(state, n.size)
    c.fixed32.encode(state, n.hash)
  },
  decode(state) {
    return {
      index: c.uint.decode(state),
      size: c.uint.decode(state),
      hash: c.fixed32.decode(state)
    }
  }
}

const nodeArray = c.array(node)

const wire = (exports.wire = {})

wire.handshake = {
  preencode(state, m) {
    c.uint.preencode(state, 1)
    c.fixed32.preencode(state, m.capability)
  },
  encode(state, m) {
    c.uint.encode(state, m.seeks ? 1 : 0)
    c.fixed32.encode(state, m.capability)
  },
  decode(state) {
    const flags = c.uint.decode(state)
    return {
      seeks: (flags & 1) !== 0,
      capability: unslab(c.fixed32.decode(state))
    }
  }
}

const requestBlock = {
  preencode(state, b) {
    c.uint.preencode(state, b.index)
    c.uint.preencode(state, b.nodes)
  },
  encode(state, b) {
    c.uint.encode(state, b.index)
    c.uint.encode(state, b.nodes)
  },
  decode(state) {
    return {
      index: c.uint.decode(state),
      nodes: c.uint.decode(state)
    }
  }
}

const requestSeek = {
  preencode(state, s) {
    c.uint.preencode(state, s.bytes)
    c.uint.preencode(state, s.padding)
  },
  encode(state, s) {
    c.uint.encode(state, s.bytes)
    c.uint.encode(state, s.padding)
  },
  decode(state) {
    return {
      bytes: c.uint.decode(state),
      padding: c.uint.decode(state)
    }
  }
}

const requestUpgrade = {
  preencode(state, u) {
    c.uint.preencode(state, u.start)
    c.uint.preencode(state, u.length)
  },
  encode(state, u) {
    c.uint.encode(state, u.start)
    c.uint.encode(state, u.length)
  },
  decode(state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

wire.request = {
  preencode(state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.id)
    c.uint.preencode(state, m.fork)

    if (m.block) requestBlock.preencode(state, m.block)
    if (m.hash) requestBlock.preencode(state, m.hash)
    if (m.seek) requestSeek.preencode(state, m.seek)
    if (m.upgrade) requestUpgrade.preencode(state, m.upgrade)
    if (m.priority) c.uint.preencode(state, m.priority)
  },
  encode(state, m) {
    const flags =
      (m.block ? 1 : 0) |
      (m.hash ? 2 : 0) |
      (m.seek ? 4 : 0) |
      (m.upgrade ? 8 : 0) |
      (m.manifest ? 16 : 0) |
      (m.priority ? 32 : 0)

    c.uint.encode(state, flags)
    c.uint.encode(state, m.id)
    c.uint.encode(state, m.fork)

    if (m.block) requestBlock.encode(state, m.block)
    if (m.hash) requestBlock.encode(state, m.hash)
    if (m.seek) requestSeek.encode(state, m.seek)
    if (m.upgrade) requestUpgrade.encode(state, m.upgrade)
    if (m.priority) c.uint.encode(state, m.priority)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      id: c.uint.decode(state),
      fork: c.uint.decode(state),
      block: flags & 1 ? requestBlock.decode(state) : null,
      hash: flags & 2 ? requestBlock.decode(state) : null,
      seek: flags & 4 ? requestSeek.decode(state) : null,
      upgrade: flags & 8 ? requestUpgrade.decode(state) : null,
      manifest: (flags & 16) !== 0,
      priority: flags & 32 ? c.uint.decode(state) : 0
    }
  }
}

wire.cancel = {
  preencode(state, m) {
    c.uint.preencode(state, m.request)
  },
  encode(state, m) {
    c.uint.encode(state, m.request)
  },
  decode(state, m) {
    return {
      request: c.uint.decode(state)
    }
  }
}

const dataUpgrade = {
  preencode(state, u) {
    c.uint.preencode(state, u.start)
    c.uint.preencode(state, u.length)
    nodeArray.preencode(state, u.nodes)
    nodeArray.preencode(state, u.additionalNodes)
    c.optionalBuffer.preencode(state, u.signature)
  },
  encode(state, u) {
    c.uint.encode(state, u.start)
    c.uint.encode(state, u.length)
    nodeArray.encode(state, u.nodes)
    nodeArray.encode(state, u.additionalNodes)
    c.optionalBuffer.encode(state, u.signature)
  },
  decode(state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state),
      nodes: nodeArray.decode(state),
      additionalNodes: nodeArray.decode(state),
      signature: c.optionalBuffer.decode(state)
    }
  }
}

const dataSeek = {
  preencode(state, s) {
    c.uint.preencode(state, s.bytes)
    nodeArray.preencode(state, s.nodes)
  },
  encode(state, s) {
    c.uint.encode(state, s.bytes)
    nodeArray.encode(state, s.nodes)
  },
  decode(state) {
    return {
      bytes: c.uint.decode(state),
      nodes: nodeArray.decode(state)
    }
  }
}

const dataBlock = {
  preencode(state, b) {
    c.uint.preencode(state, b.index)
    c.buffer.preencode(state, b.value)
    nodeArray.preencode(state, b.nodes)
  },
  encode(state, b) {
    c.uint.encode(state, b.index)
    c.buffer.encode(state, b.value)
    nodeArray.encode(state, b.nodes)
  },
  decode(state) {
    return {
      index: c.uint.decode(state),
      value: c.buffer.decode(state),
      nodes: nodeArray.decode(state)
    }
  }
}

const dataHash = {
  preencode(state, b) {
    c.uint.preencode(state, b.index)
    nodeArray.preencode(state, b.nodes)
  },
  encode(state, b) {
    c.uint.encode(state, b.index)
    nodeArray.encode(state, b.nodes)
  },
  decode(state) {
    return {
      index: c.uint.decode(state),
      nodes: nodeArray.decode(state)
    }
  }
}

wire.data = {
  preencode(state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.request)
    c.uint.preencode(state, m.fork)

    if (m.block) dataBlock.preencode(state, m.block)
    if (m.hash) dataHash.preencode(state, m.hash)
    if (m.seek) dataSeek.preencode(state, m.seek)
    if (m.upgrade) dataUpgrade.preencode(state, m.upgrade)
    if (m.manifest) manifest.preencode(state, m.manifest)
  },
  encode(state, m) {
    const flags =
      (m.block ? 1 : 0) |
      (m.hash ? 2 : 0) |
      (m.seek ? 4 : 0) |
      (m.upgrade ? 8 : 0) |
      (m.manifest ? 16 : 0)

    c.uint.encode(state, flags)
    c.uint.encode(state, m.request)
    c.uint.encode(state, m.fork)

    if (m.block) dataBlock.encode(state, m.block)
    if (m.hash) dataHash.encode(state, m.hash)
    if (m.seek) dataSeek.encode(state, m.seek)
    if (m.upgrade) dataUpgrade.encode(state, m.upgrade)
    if (m.manifest) manifest.encode(state, m.manifest)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      request: c.uint.decode(state),
      fork: c.uint.decode(state),
      block: flags & 1 ? dataBlock.decode(state) : null,
      hash: flags & 2 ? dataHash.decode(state) : null,
      seek: flags & 4 ? dataSeek.decode(state) : null,
      upgrade: flags & 8 ? dataUpgrade.decode(state) : null,
      manifest: flags & 16 ? manifest.decode(state) : null
    }
  }
}

wire.noData = {
  preencode(state, m) {
    c.uint.preencode(state, m.request)
    c.uint.preencode(state, m.reason ? 1 : 0)
    if (m.reason) c.uint.preencode(state, m.reason)
  },
  encode(state, m) {
    c.uint.encode(state, m.request)
    c.uint.encode(state, m.reason ? 1 : 0)
    if (m.reason) c.uint.encode(state, m.reason)
  },
  decode(state, m) {
    const request = c.uint.decode(state)
    const flags = state.start < state.end ? c.uint.decode(state) : 0
    return {
      request,
      reason: flags & 1 ? c.uint.decode(state) : 0
    }
  }
}

// TODO: we should move to having these have a handle like in data, easier since they
// allocate state in practice
wire.want = {
  preencode(state, m) {
    c.uint.preencode(state, m.start)
    c.uint.preencode(state, m.length)

    const flags = m.any ? 1 : 0
    if (flags !== 0) c.uint.preencode(state, flags)
  },
  encode(state, m) {
    c.uint.encode(state, m.start)
    c.uint.encode(state, m.length)

    const flags = m.any ? 1 : 0
    if (flags !== 0) c.uint.encode(state, flags)
  },
  decode(state) {
    const start = c.uint.decode(state)
    const length = c.uint.decode(state)
    const flags = state.start < state.end ? c.uint.decode(state) : 0

    return {
      start,
      length,
      any: (flags & 1) !== 0
    }
  }
}

wire.unwant = {
  preencode(state, m) {
    c.uint.preencode(state, m.start)
    c.uint.preencode(state, m.length)

    const flags = m.any ? 1 : 0
    if (flags !== 0) c.uint.preencode(state, flags)
  },
  encode(state, m) {
    c.uint.encode(state, m.start)
    c.uint.encode(state, m.length)

    const flags = m.any ? 1 : 0
    if (flags !== 0) c.uint.encode(state, flags)
  },
  decode(state, m) {
    const start = c.uint.decode(state)
    const length = c.uint.decode(state)
    const flags = state.start < state.end ? c.uint.decode(state) : 0

    return {
      start,
      length,
      any: (flags & 1) !== 0
    }
  }
}

wire.range = {
  preencode(state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.start)
    if (m.length !== 1) c.uint.preencode(state, m.length)
  },
  encode(state, m) {
    c.uint.encode(state, (m.drop ? 1 : 0) | (m.length === 1 ? 2 : 0))
    c.uint.encode(state, m.start)
    if (m.length !== 1) c.uint.encode(state, m.length)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      drop: (flags & 1) !== 0,
      start: c.uint.decode(state),
      length: (flags & 2) !== 0 ? 1 : c.uint.decode(state)
    }
  }
}

wire.bitfield = {
  preencode(state, m) {
    c.uint.preencode(state, m.start)
    c.uint32array.preencode(state, m.bitfield)
  },
  encode(state, m) {
    c.uint.encode(state, m.start)
    c.uint32array.encode(state, m.bitfield)
  },
  decode(state, m) {
    return {
      start: c.uint.decode(state),
      bitfield: c.uint32array.decode(state)
    }
  }
}

wire.sync = {
  preencode(state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.fork)
    c.uint.preencode(state, m.length)
    c.uint.preencode(state, m.remoteLength)
  },
  encode(state, m) {
    c.uint.encode(
      state,
      (m.canUpgrade ? 1 : 0) |
        (m.uploading ? 2 : 0) |
        (m.downloading ? 4 : 0) |
        (m.hasManifest ? 8 : 0) |
        (m.allowPush ? 16 : 0)
    )
    c.uint.encode(state, m.fork)
    c.uint.encode(state, m.length)
    c.uint.encode(state, m.remoteLength)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      fork: c.uint.decode(state),
      length: c.uint.decode(state),
      remoteLength: c.uint.decode(state),
      canUpgrade: (flags & 1) !== 0,
      uploading: (flags & 2) !== 0,
      downloading: (flags & 4) !== 0,
      hasManifest: (flags & 8) !== 0,
      allowPush: (flags & 16) !== 0
    }
  }
}

wire.reorgHint = {
  preencode(state, m) {
    c.uint.preencode(state, m.from)
    c.uint.preencode(state, m.to)
    c.uint.preencode(state, m.ancestors)
  },
  encode(state, m) {
    c.uint.encode(state, m.from)
    c.uint.encode(state, m.to)
    c.uint.encode(state, m.ancestors)
  },
  decode(state) {
    return {
      from: c.uint.decode(state),
      to: c.uint.decode(state),
      ancestors: c.uint.decode(state)
    }
  }
}

wire.extension = {
  preencode(state, m) {
    c.string.preencode(state, m.name)
    c.raw.preencode(state, m.message)
  },
  encode(state, m) {
    c.string.encode(state, m.name)
    c.raw.encode(state, m.message)
  },
  decode(state) {
    return {
      name: c.string.decode(state),
      message: c.raw.decode(state)
    }
  }
}

const keyValue = {
  preencode(state, p) {
    c.string.preencode(state, p.key)
    c.buffer.preencode(state, p.value)
  },
  encode(state, p) {
    c.string.encode(state, p.key)
    c.buffer.encode(state, p.value)
  },
  decode(state) {
    return {
      key: c.string.decode(state),
      value: c.buffer.decode(state)
    }
  }
}

const treeUpgrade = {
  preencode(state, u) {
    c.uint.preencode(state, u.fork)
    c.uint.preencode(state, u.ancestors)
    c.uint.preencode(state, u.length)
    c.buffer.preencode(state, u.signature)
  },
  encode(state, u) {
    c.uint.encode(state, u.fork)
    c.uint.encode(state, u.ancestors)
    c.uint.encode(state, u.length)
    c.buffer.encode(state, u.signature)
  },
  decode(state) {
    return {
      fork: c.uint.decode(state),
      ancestors: c.uint.decode(state),
      length: c.uint.decode(state),
      signature: c.buffer.decode(state)
    }
  }
}

const bitfieldUpdate = {
  // TODO: can maybe be folded into a HAVE later on with the most recent spec
  preencode(state, b) {
    state.end++ // flags
    c.uint.preencode(state, b.start)
    c.uint.preencode(state, b.length)
  },
  encode(state, b) {
    state.buffer[state.start++] = b.drop ? 1 : 0
    c.uint.encode(state, b.start)
    c.uint.encode(state, b.length)
  },
  decode(state) {
    const flags = c.uint.decode(state)
    return {
      drop: (flags & 1) !== 0,
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

const oplog = (exports.oplog = {})

oplog.entry = {
  preencode(state, m) {
    state.end++ // flags
    if (m.userData) keyValue.preencode(state, m.userData)
    if (m.treeNodes) nodeArray.preencode(state, m.treeNodes)
    if (m.treeUpgrade) treeUpgrade.preencode(state, m.treeUpgrade)
    if (m.bitfield) bitfieldUpdate.preencode(state, m.bitfield)
  },
  encode(state, m) {
    const s = state.start++
    let flags = 0

    if (m.userData) {
      flags |= 1
      keyValue.encode(state, m.userData)
    }
    if (m.treeNodes) {
      flags |= 2
      nodeArray.encode(state, m.treeNodes)
    }
    if (m.treeUpgrade) {
      flags |= 4
      treeUpgrade.encode(state, m.treeUpgrade)
    }
    if (m.bitfield) {
      flags |= 8
      bitfieldUpdate.encode(state, m.bitfield)
    }

    state.buffer[s] = flags
  },
  decode(state) {
    const flags = c.uint.decode(state)
    return {
      userData: (flags & 1) !== 0 ? keyValue.decode(state) : null,
      treeNodes: (flags & 2) !== 0 ? nodeArray.decode(state) : null,
      treeUpgrade: (flags & 4) !== 0 ? treeUpgrade.decode(state) : null,
      bitfield: (flags & 8) !== 0 ? bitfieldUpdate.decode(state) : null
    }
  }
}

const keyPair = {
  preencode(state, kp) {
    c.buffer.preencode(state, kp.publicKey)
    c.buffer.preencode(state, kp.secretKey)
  },
  encode(state, kp) {
    c.buffer.encode(state, kp.publicKey)
    c.buffer.encode(state, kp.secretKey)
  },
  decode(state) {
    return {
      publicKey: c.buffer.decode(state),
      secretKey: c.buffer.decode(state)
    }
  }
}

const reorgHint = {
  preencode(state, r) {
    c.uint.preencode(state, r.from)
    c.uint.preencode(state, r.to)
    c.uint.preencode(state, r.ancestors)
  },
  encode(state, r) {
    c.uint.encode(state, r.from)
    c.uint.encode(state, r.to)
    c.uint.encode(state, r.ancestors)
  },
  decode(state) {
    return {
      from: c.uint.decode(state),
      to: c.uint.decode(state),
      ancestors: c.uint.decode(state)
    }
  }
}

const reorgHintArray = c.array(reorgHint)

const hints = {
  preencode(state, h) {
    reorgHintArray.preencode(state, h.reorgs)
    c.uint.preencode(state, h.contiguousLength)
  },
  encode(state, h) {
    reorgHintArray.encode(state, h.reorgs)
    c.uint.encode(state, h.contiguousLength)
  },
  decode(state) {
    return {
      reorgs: reorgHintArray.decode(state),
      contiguousLength: state.start < state.end ? c.uint.decode(state) : 0
    }
  }
}

const treeHeader = {
  preencode(state, t) {
    c.uint.preencode(state, t.fork)
    c.uint.preencode(state, t.length)
    c.buffer.preencode(state, t.rootHash)
    c.buffer.preencode(state, t.signature)
  },
  encode(state, t) {
    c.uint.encode(state, t.fork)
    c.uint.encode(state, t.length)
    c.buffer.encode(state, t.rootHash)
    c.buffer.encode(state, t.signature)
  },
  decode(state) {
    return {
      fork: c.uint.decode(state),
      length: c.uint.decode(state),
      rootHash: c.buffer.decode(state),
      signature: c.buffer.decode(state)
    }
  }
}

const types = {
  preencode(state, t) {
    c.string.preencode(state, t.tree)
    c.string.preencode(state, t.bitfield)
    c.string.preencode(state, t.signer)
  },
  encode(state, t) {
    c.string.encode(state, t.tree)
    c.string.encode(state, t.bitfield)
    c.string.encode(state, t.signer)
  },
  decode(state) {
    return {
      tree: c.string.decode(state),
      bitfield: c.string.decode(state),
      signer: c.string.decode(state)
    }
  }
}

const externalHeader = {
  preencode(state, m) {
    c.uint.preencode(state, m.start)
    c.uint.preencode(state, m.length)
  },
  encode(state, m) {
    c.uint.encode(state, m.start)
    c.uint.encode(state, m.length)
  },
  decode(state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

const keyValueArray = c.array(keyValue)

oplog.header = {
  preencode(state, h) {
    state.end += 2 // version + flags
    if (h.external) {
      externalHeader.preencode(state, h.external)
      return
    }
    c.fixed32.preencode(state, h.key)
    if (h.manifest) manifest.preencode(state, h.manifest)
    if (h.keyPair) keyPair.preencode(state, h.keyPair)
    keyValueArray.preencode(state, h.userData)
    treeHeader.preencode(state, h.tree)
    hints.preencode(state, h.hints)
  },
  encode(state, h) {
    c.uint.encode(state, 1)
    if (h.external) {
      c.uint.encode(state, 1) // ONLY set the first big for clarity
      externalHeader.encode(state, h.external)
      return
    }
    c.uint.encode(state, (h.manifest ? 2 : 0) | (h.keyPair ? 4 : 0))
    c.fixed32.encode(state, h.key)
    if (h.manifest) manifest.encode(state, h.manifest)
    if (h.keyPair) keyPair.encode(state, h.keyPair)
    keyValueArray.encode(state, h.userData)
    treeHeader.encode(state, h.tree)
    hints.encode(state, h.hints)
  },
  decode(state) {
    const version = c.uint.decode(state)

    if (version > 1) {
      throw INVALID_OPLOG_VERSION('Invalid header version. Expected <= 1, got ' + version)
    }

    if (version === 0) {
      const old = {
        types: types.decode(state),
        userData: keyValueArray.decode(state),
        tree: treeHeader.decode(state),
        signer: keyPair.decode(state),
        hints: hints.decode(state)
      }

      return {
        external: null,
        key: old.signer.publicKey,
        manifest: {
          version: 0,
          hash: old.types.tree,
          allowPatch: false,
          quorum: 1,
          signers: [
            {
              signature: old.types.signer,
              namespace: DEFAULT_NAMESPACE,
              publicKey: old.signer.publicKey
            }
          ],
          prologue: null,
          linked: null,
          userData: null
        },
        keyPair: old.signer.secretKey ? old.signer : null,
        userData: old.userData,
        tree: old.tree,
        hints: old.hints
      }
    }

    const flags = c.uint.decode(state)

    if (flags & 1) {
      return {
        external: externalHeader.decode(state),
        key: null,
        manifest: null,
        keyPair: null,
        userData: null,
        tree: null,
        hints: null
      }
    }

    return {
      external: null,
      key: c.fixed32.decode(state),
      manifest: (flags & 2) !== 0 ? manifest.decode(state) : null,
      keyPair: (flags & 4) !== 0 ? keyPair.decode(state) : null,
      userData: keyValueArray.decode(state),
      tree: treeHeader.decode(state),
      hints: hints.decode(state)
    }
  }
}

const uintArray = c.array(c.uint)

const multisigInput = {
  preencode(state, inp) {
    c.uint.preencode(state, inp.signer)
    c.fixed64.preencode(state, inp.signature)
    c.uint.preencode(state, inp.patch)
  },
  encode(state, inp) {
    c.uint.encode(state, inp.signer)
    c.fixed64.encode(state, inp.signature)
    c.uint.encode(state, inp.patch)
  },
  decode(state) {
    return {
      signer: c.uint.decode(state),
      signature: c.fixed64.decode(state),
      patch: c.uint.decode(state)
    }
  }
}

const patchEncodingv0 = {
  preencode(state, n) {
    c.uint.preencode(state, n.start)
    c.uint.preencode(state, n.length)
    uintArray.preencode(state, n.nodes)
  },
  encode(state, n) {
    c.uint.encode(state, n.start)
    c.uint.encode(state, n.length)
    uintArray.encode(state, n.nodes)
  },
  decode(state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state),
      nodes: uintArray.decode(state)
    }
  }
}

const multisigInputv0 = {
  preencode(state, n) {
    state.end++
    c.uint.preencode(state, n.signer)
    c.fixed64.preencode(state, n.signature)
    if (n.patch) patchEncodingv0.preencode(state, n.patch)
  },
  encode(state, n) {
    c.uint.encode(state, n.patch ? 1 : 0)
    c.uint.encode(state, n.signer)
    c.fixed64.encode(state, n.signature)
    if (n.patch) patchEncodingv0.encode(state, n.patch)
  },
  decode(state) {
    const flags = c.uint.decode(state)
    return {
      signer: c.uint.decode(state),
      signature: c.fixed64.decode(state),
      patch: flags & 1 ? patchEncodingv0.decode(state) : null
    }
  }
}

const multisigInputArrayv0 = c.array(multisigInputv0)
const multisigInputArray = c.array(multisigInput)

const compactNode = {
  preencode(state, n) {
    c.uint.preencode(state, n.index)
    c.uint.preencode(state, n.size)
    c.fixed32.preencode(state, n.hash)
  },
  encode(state, n) {
    c.uint.encode(state, n.index)
    c.uint.encode(state, n.size)
    c.fixed32.encode(state, n.hash)
  },
  decode(state) {
    return {
      index: c.uint.decode(state),
      size: c.uint.decode(state),
      hash: c.fixed32.decode(state)
    }
  }
}

const compactNodeArray = c.array(compactNode)

exports.multiSignaturev0 = {
  preencode(state, s) {
    multisigInputArrayv0.preencode(state, s.proofs)
    compactNodeArray.preencode(state, s.patch)
  },
  encode(state, s) {
    multisigInputArrayv0.encode(state, s.proofs)
    compactNodeArray.encode(state, s.patch)
  },
  decode(state) {
    return {
      proofs: multisigInputArrayv0.decode(state),
      patch: compactNodeArray.decode(state)
    }
  }
}

exports.multiSignature = {
  preencode(state, s) {
    multisigInputArray.preencode(state, s.proofs)
    compactNodeArray.preencode(state, s.patch)
  },
  encode(state, s) {
    multisigInputArray.encode(state, s.proofs)
    compactNodeArray.encode(state, s.patch)
  },
  decode(state) {
    return {
      proofs: multisigInputArray.decode(state),
      patch: compactNodeArray.decode(state)
    }
  }
}
const c = require('compact-encoding')
const b4a = require('b4a')
const flat = require('flat-tree')
const { MerkleTree } = require('./merkle-tree')
const { multiSignature, multiSignaturev0 } = require('./messages')

module.exports = {
  assemblev0,
  assemble,
  inflatev0,
  inflate,
  partialSignature,
  signableLength
}

function inflatev0(data) {
  return c.decode(multiSignaturev0, data)
}

function inflate(data) {
  return c.decode(multiSignature, data)
}

async function partialSignature(
  core,
  signer,
  from,
  to = core.state.length,
  signature = core.state.signature
) {
  if (from > core.state.length) return null
  const nodes = to <= from ? null : await upgradeNodes(core, from, to)

  if (signature.byteLength !== 64) {
    signature = c.decode(multiSignature, signature).proofs[0].signature
  }

  return {
    signer,
    signature,
    patch: nodes ? to - from : 0,
    nodes
  }
}

async function upgradeNodes(core, from, to) {
  const rx = core.state.storage.read()
  let p = null
  try {
    p = await MerkleTree.proof(core.state, rx, { upgrade: { start: from, length: to - from } })
  } catch (err) {
    rx.destroy()
    throw err
  }
  rx.tryFlush()
  return (await p.settle()).upgrade.nodes
}

function signableLength(lengths, quorum) {
  if (quorum <= 0) quorum = 1
  if (quorum > lengths.length) return 0

  return lengths.sort(cmp)[quorum - 1]
}

function cmp(a, b) {
  return b - a
}

function assemblev0(inputs) {
  const proofs = []
  const patch = []

  for (const u of inputs) {
    proofs.push(compressProof(u, patch))
  }

  return c.encode(multiSignaturev0, { proofs, patch })
}

function assemble(inputs) {
  const proofs = []
  const patch = []
  const seen = new Set()

  for (const u of inputs) {
    if (u.nodes) {
      for (const node of u.nodes) {
        if (seen.has(node.index)) continue
        seen.add(node.index)
        patch.push(node)
      }
    }

    proofs.push({
      signer: u.signer,
      signature: u.signature,
      patch: u.patch
    })
  }

  return c.encode(multiSignature, { proofs, patch })
}

function compareNode(a, b) {
  if (a.index !== b.index) return false
  if (a.size !== b.size) return false
  return b4a.equals(a.hash, b.hash)
}

function compressProof(proof, nodes) {
  return {
    signer: proof.signer,
    signature: proof.signature,
    patch: proof.patch ? compressUpgrade(proof, nodes) : null
  }
}

function compressUpgrade(p, nodes) {
  const u = {
    start: flat.rightSpan(p.nodes[p.nodes.length - 1].index) / 2 + 1,
    length: p.patch,
    nodes: []
  }

  for (const node of p.nodes) {
    let present = false
    for (let i = 0; i < nodes.length; i++) {
      if (!compareNode(nodes[i], node)) continue

      u.nodes.push(i)
      present = true
      break
    }

    if (present) continue
    u.nodes.push(nodes.push(node) - 1)
  }

  return u
}
module.exports = class Mutex {
  constructor() {
    this.locked = false
    this.destroyed = false

    this._destroying = null
    this._destroyError = null
    this._queue = []
    this._enqueue = (resolve, reject) => this._queue.push([resolve, reject])
  }

  idle() {
    return this._queue.length === 0 && this.locked === false
  }

  lock() {
    if (this.destroyed) {
      return Promise.reject(this._destroyError || new Error('Mutex has been destroyed'))
    }
    if (this.locked) return new Promise(this._enqueue)
    this.locked = true
    return Promise.resolve()
  }

  unlock() {
    if (!this._queue.length) {
      this.locked = false
      return
    }
    this._queue.shift()[0]()
  }

  destroy(err) {
    if (!this._destroying) {
      this._destroying = this.locked ? this.lock().catch(() => {}) : Promise.resolve()
    }

    this.destroyed = true
    if (err) this._destroyError = err

    if (err) {
      while (this._queue.length) this._queue.shift()[1](err)
    }

    return this._destroying
  }
}
const FIFO = require('fast-fifo')

module.exports = class ReceiverQueue {
  constructor() {
    this.queue = new FIFO()
    this.priority = []
    this.requests = new Map()
    this.length = 0
  }

  push(req) {
    // TODO: use a heap at some point if we wanna support multiple prios
    if (req.priority > 0) this.priority.push(req)
    else this.queue.push(req)

    this.requests.set(req.id, req)
    this.length++
  }

  shift() {
    while (this.priority.length > 0) {
      const msg = this.priority.pop()
      const req = this._processRequest(msg)
      if (req !== null) return req
    }

    while (this.queue.length > 0) {
      const msg = this.queue.shift()
      const req = this._processRequest(msg)
      if (req !== null) return req
    }

    return null
  }

  _processRequest(req) {
    if (req.block || req.hash || req.seek || req.upgrade || req.manifest) {
      this.requests.delete(req.id)
      this.length--
      return req
    }

    return null
  }

  clear() {
    this.queue.clear()
    this.priority = []
    this.length = 0
    this.requests.clear()
  }

  delete(id) {
    const req = this.requests.get(id)
    if (!req) return

    req.block = null
    req.hash = null
    req.seek = null
    req.upgrade = null
    req.manifest = false

    this.requests.delete(id)
    this.length--

    if (this.length === 0) {
      this.queue.clear()
      this.priority = []
    }
  }
}
const BigSparseArray = require('big-sparse-array')
const quickbit = require('./compat').quickbit

const BITS_PER_PAGE = 32768
const BYTES_PER_PAGE = BITS_PER_PAGE / 8
const WORDS_PER_PAGE = BYTES_PER_PAGE / 4
const BITS_PER_SEGMENT = 2097152
const BYTES_PER_SEGMENT = BITS_PER_SEGMENT / 8
const PAGES_PER_SEGMENT = BITS_PER_SEGMENT / BITS_PER_PAGE

class RemoteBitfieldPage {
  constructor(index, bitfield, segment) {
    this.index = index
    this.offset = index * BYTES_PER_PAGE - segment.offset
    this.bitfield = bitfield
    this.segment = segment

    segment.add(this)
  }

  get tree() {
    return this.segment.tree
  }

  get(index) {
    return quickbit.get(this.bitfield, index)
  }

  set(index, val) {
    if (quickbit.set(this.bitfield, index, val)) {
      this.tree.update(this.offset * 8 + index)
    }
  }

  setRange(start, end, val) {
    quickbit.fill(this.bitfield, val, start, end)

    let i = Math.floor(start / 128)
    const n = i + Math.ceil((end - start) / 128)

    while (i <= n) this.tree.update(this.offset * 8 + i++ * 128)
  }

  findFirst(val, position) {
    return quickbit.findFirst(this.bitfield, val, position)
  }

  findLast(val, position) {
    return quickbit.findLast(this.bitfield, val, position)
  }

  insert(start, bitfield) {
    this.bitfield.set(bitfield, start / 32)
    this.segment.refresh()
  }

  clear(start, bitfield) {
    quickbit.clear(this.bitfield, { field: bitfield, offset: start })
  }
}

class RemoteBitfieldSegment {
  constructor(index) {
    this.index = index
    this.offset = index * BYTES_PER_SEGMENT
    this.tree = quickbit.Index.from([], BYTES_PER_SEGMENT)
    this.pages = new Array(PAGES_PER_SEGMENT)
    this.pagesLength = 0
  }

  get chunks() {
    return this.tree.chunks
  }

  refresh() {
    this.tree = quickbit.Index.from(this.tree.chunks, BYTES_PER_SEGMENT)
  }

  add(page) {
    const pageIndex = page.index - this.index * PAGES_PER_SEGMENT
    if (pageIndex >= this.pagesLength) this.pagesLength = pageIndex + 1

    this.pages[pageIndex] = page

    const chunk = { field: page.bitfield, offset: page.offset }

    this.chunks.push(chunk)

    for (let i = this.chunks.length - 2; i >= 0; i--) {
      const prev = this.chunks[i]
      if (prev.offset <= chunk.offset) break
      this.chunks[i] = chunk
      this.chunks[i + 1] = prev
    }
  }

  findFirst(val, position) {
    position = this.tree.skipFirst(!val, position)

    let j = position & (BITS_PER_PAGE - 1)
    let i = (position - j) / BITS_PER_PAGE

    if (i >= PAGES_PER_SEGMENT) return -1

    while (i < this.pagesLength) {
      const p = this.pages[i]

      let index = -1

      if (p) index = p.findFirst(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_PAGE + index

      j = 0
      i++
    }

    return val || this.pagesLength === PAGES_PER_SEGMENT ? -1 : this.pagesLength * BITS_PER_PAGE
  }

  findLast(val, position) {
    position = this.tree.skipLast(!val, position)

    let j = position & (BITS_PER_PAGE - 1)
    let i = (position - j) / BITS_PER_PAGE

    if (i >= PAGES_PER_SEGMENT) return -1

    while (i >= 0) {
      const p = this.pages[i]

      let index = -1

      if (p) index = p.findLast(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_PAGE + index

      j = BITS_PER_PAGE - 1
      i--
    }

    return -1
  }
}

module.exports = class RemoteBitfield {
  static BITS_PER_PAGE = BITS_PER_PAGE
  static BITS_PER_SEGMENT = BITS_PER_SEGMENT

  constructor() {
    this._pages = new BigSparseArray()
    this._segments = new BigSparseArray()
    this._maxSegments = 0
  }

  getBitfield(index) {
    const j = index & (BITS_PER_PAGE - 1)
    const i = (index - j) / BITS_PER_PAGE

    const p = this._pages.get(i)
    return p || null
  }

  get(index) {
    const j = index & (BITS_PER_PAGE - 1)
    const i = (index - j) / BITS_PER_PAGE

    const p = this._pages.get(i)

    return p ? p.get(j) : false
  }

  set(index, val) {
    const j = index & (BITS_PER_PAGE - 1)
    const i = (index - j) / BITS_PER_PAGE

    let p = this._pages.get(i)

    if (!p && val) {
      const k = Math.floor(i / PAGES_PER_SEGMENT)
      const s = this._segments.get(k) || this._segments.set(k, new RemoteBitfieldSegment(k))
      if (this._maxSegments <= k) this._maxSegments = k + 1

      p = this._pages.set(i, new RemoteBitfieldPage(i, new Uint32Array(WORDS_PER_PAGE), s))
    }

    if (p) p.set(j, val)
  }

  setRange(start, end, val) {
    let j = start & (BITS_PER_PAGE - 1)
    let i = (start - j) / BITS_PER_PAGE

    while (start < end) {
      let p = this._pages.get(i)

      if (!p && val) {
        const k = Math.floor(i / PAGES_PER_SEGMENT)
        const s = this._segments.get(k) || this._segments.set(k, new RemoteBitfieldSegment(k))
        if (this._maxSegments <= k) this._maxSegments = k + 1

        p = this._pages.set(i, new RemoteBitfieldPage(i, new Uint32Array(WORDS_PER_PAGE), s))
      }

      const offset = i * BITS_PER_PAGE
      const last = Math.min(end - offset, BITS_PER_PAGE)
      const range = last - j

      if (p) p.setRange(j, last, val)

      j = 0
      i++
      start += range
    }
  }

  findFirst(val, position) {
    let j = position & (BITS_PER_SEGMENT - 1)
    let i = (position - j) / BITS_PER_SEGMENT

    while (i < this._maxSegments) {
      const s = this._segments.get(i)

      let index = -1

      if (s) index = s.findFirst(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_SEGMENT + index

      j = 0
      i++
    }

    // For the val === false case, we always return at least
    // the 'position', also if nothing was found
    return val ? -1 : Math.max(position, this._maxSegments * BITS_PER_SEGMENT)
  }

  firstSet(position) {
    return this.findFirst(true, position)
  }

  firstUnset(position) {
    return this.findFirst(false, position)
  }

  findLast(val, position) {
    let j = position & (BITS_PER_SEGMENT - 1)
    let i = (position - j) / BITS_PER_SEGMENT

    while (i >= 0) {
      const s = this._segments.get(i)

      let index = -1

      if (s) index = s.findLast(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_SEGMENT + index

      j = BITS_PER_SEGMENT - 1
      i--
    }

    return -1
  }

  lastSet(position) {
    return this.findLast(true, position)
  }

  lastUnset(position) {
    return this.findLast(false, position)
  }

  insert(start, bitfield) {
    if (start % 32 !== 0) return false

    let length = bitfield.byteLength * 8

    let j = start & (BITS_PER_PAGE - 1)
    let i = (start - j) / BITS_PER_PAGE

    while (length > 0) {
      let p = this._pages.get(i)

      if (!p) {
        const k = Math.floor(i / PAGES_PER_SEGMENT)
        const s = this._segments.get(k) || this._segments.set(k, new RemoteBitfieldSegment(k))
        if (this._maxSegments <= k) this._maxSegments = k + 1

        p = this._pages.set(i, new RemoteBitfieldPage(i, new Uint32Array(WORDS_PER_PAGE), s))
      }

      const end = Math.min(j + length, BITS_PER_PAGE)
      const range = end - j

      p.insert(j, bitfield.subarray(0, range / 32))

      bitfield = bitfield.subarray(range / 32)

      j = 0
      i++
      length -= range
    }

    return true
  }

  clear(start, bitfield) {
    if (start % 32 !== 0) return false

    let length = bitfield.byteLength * 8

    let j = start & (BITS_PER_PAGE - 1)
    let i = (start - j) / BITS_PER_PAGE

    while (length > 0) {
      let p = this._pages.get(i)

      if (!p) {
        const k = Math.floor(i / PAGES_PER_SEGMENT)
        const s = this._segments.get(k) || this._segments.set(k, new RemoteBitfieldSegment(k))
        if (this._maxSegments <= k) this._maxSegments = k + 1

        p = this._pages.set(i, new RemoteBitfieldPage(i, new Uint32Array(WORDS_PER_PAGE), s))
      }

      const end = Math.min(j + length, BITS_PER_PAGE)
      const range = end - j

      p.clear(j, bitfield.subarray(0, range / 32))

      bitfield = bitfield.subarray(range / 32)

      j = 0
      i++
      length -= range
    }

    return true
  }
}
/* DEV DOCS
  Every hypercore has one Replicator object managing its connections to other peers.
  There is one Peer object per peer connected to the Hypercore.
  Hypercores do not know about other hypercores, so when a peer is connected to multiple cores, there exists one Peer object per core.

  Hypercore indicates block should be downloaded through methods like Replicator.addRange or Replicator.addBlock
  Hypercore calls Replicator.updateActivity every time a hypercore session opens/closes
  Replicator.updateActivity ensures the Hypercore is downloading blocks as expected
  Replicator keeps track of:
    - Which blocks need to be downloaded (Replicator._blocks)
    - Which blocks currently have inflight requests (Replicator._inflight)

  Blocks are requested from remote peers by Peer objects. The flow is:
    - The replicator's updatePeer method gets called
    - The replicator detects whether the Peer can accept more requests (for example by checking if it's maxed out on inflight blocks)
    - The replicator then tells the Peer what to request (e.g. Peer_requestRange or Peer._requestBlock methods)

  The Peer object is responsible for tracking
    - Which blocks does the Peer have available (tracked in remoteBitfield)
    - Which blocks are you actively looking for from this peer (tracked in missingBlocks)
    - How many blocks are currently inflight (tracked in inflight)
  The Peer uses this information to decide which blocks to request from the peer in response to _requestRange requests and the like.
*/

const b4a = require('b4a')
const safetyCatch = require('safety-catch')
const RandomIterator = require('random-array-iterator')
const flatTree = require('flat-tree')
const Mutex = require('./mutex')
const ReceiverQueue = require('./receiver-queue')
const HotswapQueue = require('./hotswap-queue')
const RemoteBitfield = require('./remote-bitfield')
const { MerkleTree } = require('./merkle-tree')
const w = require('./wants')
const { LocalWants, RemoteWants } = w
const {
  REQUEST_CANCELLED,
  REQUEST_TIMEOUT,
  INVALID_CAPABILITY,
  SNAPSHOT_NOT_AVAILABLE,
  ASSERTION
} = require('hypercore-errors')
const m = require('./messages')
const caps = require('./caps')

const DEFAULT_MAX_INFLIGHT = [16, 512]
const SCALE_LATENCY = 50
const NOT_DOWNLOADING_SLACK = (20000 + Math.random() * 20000) | 0
const MAX_PEERS_UPGRADE = 3
const LAST_BLOCKS = 256
const MAX_RANGES = 64
const MIN_PEER_UPDATE_ALL = 40

const NOT_AVAILABLE = 1
const INVALID_REQUEST = 2
const MAX_INVALID_REQUESTS = 64
const MAX_BACKOFFS = MAX_INVALID_REQUESTS / 2

const PRIORITY = {
  NORMAL: 0,
  HIGH: 1,
  VERY_HIGH: 2,
  CANCELLED: 255 // reserved to mark cancellation
}

class Attachable {
  constructor(replicator) {
    this.replicator = replicator
    this.resolved = false
    this.processing = false
    this.refs = []
    this.wants = null
  }

  addWant(w) {
    if (this.wants === null) this.wants = new Set()
    this.wants.add(w)
  }

  removeWant(w) {
    if (this.wants === null) return
    this.wants.delete(w)
  }

  attach(session) {
    const r = {
      context: this,
      session,
      sindex: 0,
      rindex: 0,
      snapshot: true,
      resolve: null,
      reject: null,
      promise: null,
      timeout: null
    }

    r.sindex = session.push(r) - 1
    r.rindex = this.refs.push(r) - 1
    r.promise = new Promise((resolve, reject) => {
      r.resolve = resolve
      r.reject = reject
    })

    return r
  }

  detach(r, err = null) {
    if (r.context !== this) return false

    this._detach(r)
    this._cancel(r, err)
    this.gc()

    return true
  }

  _detach(r) {
    const rh = this.refs.pop()
    const sh = r.session.pop()

    if (r.rindex < this.refs.length) this.refs[(rh.rindex = r.rindex)] = rh
    if (r.sindex < r.session.length) r.session[(sh.sindex = r.sindex)] = sh

    destroyRequestTimeout(r)
    r.context = null

    return r
  }

  gc() {
    if (this.refs.length > 0 || this.processing) return
    this._unref()

    if (this.wants === null) return

    const wants = this.wants
    this.wants = null

    let update = null

    for (const w of wants) {
      if (w.any) {
        const removed = w.wants.removeAnyRange(w.start, w.length, this)
        if (!removed) continue
        if (update === null) update = new Set()
        update.add(w.wants.peer)
        // TODO: should also use a free list for simplicity
        w.wants.peer.wireUnwant.send(removed)
        continue
      }

      if (w.wants.removeBatch(w.start, this)) {
        if (update === null) update = new Set()
        update.add(w.wants.peer)
      }
    }

    if (update === null) return
    for (const peer of update) {
      this.replicator.updatePeer(peer)
    }
  }

  processed() {
    this.processing = false
    this.gc()
  }

  _cancel(r, err) {
    r.reject(err || REQUEST_CANCELLED())
  }

  _unref() {
    // overwrite me
  }

  resolve(val) {
    this.resolved = true
    while (this.refs.length > 0) {
      this._detach(this.refs[this.refs.length - 1]).resolve(val)
    }
    this.gc()
  }

  reject(err) {
    this.resolved = true
    while (this.refs.length > 0) {
      this._detach(this.refs[this.refs.length - 1]).reject(err)
    }
    this.gc()
  }

  setTimeout(r, ms) {
    destroyRequestTimeout(r)
    r.timeout = setTimeout(onrequesttimeout, ms, r)
  }
}

class BlockRequest extends Attachable {
  constructor(replicator, tracker, index, priority, force) {
    super(replicator)

    this.index = index
    this.priority = priority
    this.inflight = []
    this.queued = false
    this.hotswap = null
    this.tracker = tracker
    this.force = force
  }

  _unref() {
    if (this.resolved) return
    this.queued = false

    for (const req of this.inflight) {
      req.peer._cancelRequest(req)
    }

    this.tracker.remove(this.index)
    removeHotswap(this)
  }
}

class RangeBatchRequest extends Attachable {
  constructor(replicator, batch) {
    super(replicator)

    this.batch = batch
    this.index = 0
  }
}

class RangeRequest extends Attachable {
  constructor(replicator, ranges, start, end, linear, blocks) {
    super(replicator)

    this.start = start
    this.end = end
    this.linear = linear
    this.blocks = blocks
    this.ranges = ranges
    this.batches = []

    ranges.push(this)

    if (this.end === -1) {
      this.replicator._alwaysLatestBlock++
    }

    // As passed by the user, immut
    this.userStart = start
    this.userEnd = end
  }

  addBatch(batch) {
    for (let i = 0; i < this.batches.length; i++) {
      const b = this.batches[i]
      if (b.batch === batch) return false
    }
    const b = new RangeBatchRequest(this.replicator, batch)
    b.index = this.batches.length
    this.batches.push(b)
    return true
  }

  removeBatch(batch) {
    const head = this.batches.pop()

    if (head !== batch) {
      head.index = batch.index
      this.batches[head.index] = head
    }

    batch.gc()
  }

  _unref() {
    const rangeIndex = this.ranges.indexOf(this)
    if (rangeIndex === -1) return

    const h = this.ranges.pop()
    if (h !== this) {
      this.ranges[rangeIndex] = h
    }

    if (this.end === -1) {
      this.replicator._alwaysLatestBlock--
    }

    while (this.batches.length) {
      this.batches.pop().gc()
    }
  }

  _cancel(r) {
    r.resolve(false)
  }
}

class UpgradeRequest extends Attachable {
  constructor(replicator, fork, length) {
    super(replicator)

    this.fork = fork
    this.length = length
    this.inflight = []
  }

  _unref() {
    if (this.resolved) return
    if (this.replicator.eagerUpgrade === true || this.inflight.length > 0) return
    this.replicator._upgrade = null
  }

  _cancel(r) {
    r.resolve(false)
  }
}

class SeekRequest extends Attachable {
  constructor(replicator, seeks, seeker) {
    super(replicator)

    this.seeker = seeker
    this.inflight = []
    this.seeks = seeks
  }

  _unref() {
    if (this.resolved) return
    if (this.inflight.length > 0) return
    const i = this.seeks.indexOf(this)
    if (i === -1) return
    const h = this.seeks.pop()
    if (i < this.seeks.length) this.seeks[i] = h
  }
}

class ForkRequest extends Attachable {
  constructor(replicator, fork) {
    super(replicator)
    this.fork = fork
    this.inflight = []
    this.batch = null
  }
}

class InflightTracker {
  constructor() {
    this._requests = []
    this._free = []
    this._active = 0
  }

  get idle() {
    return this._active === 0
  }

  *[Symbol.iterator]() {
    for (const req of this._requests) {
      if (req !== null) yield req
    }
  }

  add(req) {
    const id = this._free.length ? this._free.pop() : this._requests.push(null)
    req.id = id
    this._requests[id - 1] = req
    this._active++
    return req
  }

  get(id) {
    return id <= this._requests.length ? this._requests[id - 1] : null
  }

  remove(id, roundtrip) {
    if (id > this._requests.length) return
    if (this._requests[id - 1]) this._active--
    this._requests[id - 1] = null
    if (roundtrip === true) this._free.push(id)
  }

  reusable(id) {
    this._free.push(id)
  }
}

class BlockTracker {
  constructor(replicator) {
    this._replicator = replicator
    this._map = new Map()
  }

  [Symbol.iterator]() {
    return this._map.values()
  }

  isEmpty() {
    return this._map.size === 0
  }

  has(index) {
    return this._map.has(index)
  }

  get(index) {
    return this._map.get(index) || null
  }

  add(index, priority, force) {
    let b = this._map.get(index)
    if (b) return b

    b = new BlockRequest(this._replicator, this, index, priority, force)
    this._map.set(index, b)

    return b
  }

  remove(index) {
    const b = this.get(index)
    this._map.delete(index)
    return b
  }
}

class RoundtripQueue {
  constructor() {
    this.queue = []
    this.tick = 0
  }

  clear() {
    const ids = new Array(this.queue.length)
    for (let i = 0; i < ids.length; i++) {
      ids[i] = this.queue[i][1]
    }

    this.queue = []

    return ids
  }

  add(id) {
    this.queue.push([++this.tick, id])
  }

  flush(tick) {
    let flushed = null

    for (let i = 0; i < this.queue.length; i++) {
      if (this.queue[i][0] > tick) break
      if (flushed === null) flushed = []
      flushed.push(this.queue[i][1])
    }

    if (flushed !== null) this.queue.splice(0, flushed.length)
    return flushed
  }
}

class ProofRequest {
  constructor(msg, proof, block, manifest) {
    this.msg = msg
    this.proof = proof
    this.block = block
    this.manifest = manifest
  }

  async fulfill() {
    if (this.proof === null) return null

    const [proof, block] = await Promise.all([this.proof.settle(), this.block])

    if (this.manifest) proof.manifest = this.manifest
    if (!block && proof.block) return null

    if (block) proof.block.value = block
    return proof
  }
}

class Peer {
  constructor(replicator, protomux, channel, inflightRange) {
    this.core = replicator.core
    this.replicator = replicator
    this.stream = protomux.stream
    this.protomux = protomux
    this.remotePublicKey = this.stream.remotePublicKey
    this.remoteSupportsSeeks = false
    this.inflightRange = inflightRange
    this.fullyDownloadedSignaled = 0

    this.paused = false
    this.removed = false

    this.channel = channel
    this.channel.userData = this

    this.wireSync = this.channel.messages[0]
    this.wireRequest = this.channel.messages[1]
    this.wireCancel = this.channel.messages[2]
    this.wireData = this.channel.messages[3]
    this.wireNoData = this.channel.messages[4]
    this.wireWant = this.channel.messages[5]
    this.wireUnwant = this.channel.messages[6]
    this.wireBitfield = this.channel.messages[7]
    this.wireRange = this.channel.messages[8]
    this.wireExtension = this.channel.messages[9]

    // Same stats as replicator, but for this specific peer
    this.stats = {
      wireSync: { tx: 0, rx: 0 },
      wireRequest: { tx: 0, rx: 0 },
      wireCancel: { tx: 0, rx: 0 },
      wireData: { tx: 0, rx: 0 },
      wireWant: { tx: 0, rx: 0 },
      wireUnwant: { tx: 0, rx: 0 },
      wireBitfield: { tx: 0, rx: 0 },
      wireRange: { tx: 0, rx: 0 },
      wireExtension: { tx: 0, rx: 0 },
      hotswaps: 0,
      invalidData: 0,
      invalidRequests: 0,
      backoffs: 0,
      notAvailableBackoffs: 0
    }

    this.receiverQueue = new ReceiverQueue()
    this.receiverBusy = false

    // most often not used, so made on demand
    this.roundtripQueue = null

    this.inflight = 0
    this.dataProcessing = 0

    this.canUpgrade = true

    this.needsSync = false
    this.syncsProcessing = 0
    this.lastUpgradableLength = 0
    this.lastUpgradableFork = 0

    this._remoteContiguousLength = 0

    // TODO: tweak pipelining so that data sent BEFORE remoteOpened is not cap verified!
    // we might wanna tweak that with some crypto, ie use the cap to encrypt it...
    // or just be aware of that, to only push non leaky data

    this.remoteOpened = false
    this.remoteBitfield = new RemoteBitfield()
    this.missingBlocks = new RemoteBitfield()

    this.pushedLength = 0

    this.remoteFork = 0
    this.remoteLength = 0
    this.remoteCanUpgrade = false
    this.remoteUploading = true
    this.remoteDownloading = true
    this.remoteSynced = false
    this.remoteHasManifest = false
    this.remoteAllowPush = false
    this.remoteRequests = new Map()

    this.segmentsWanted = new Set()
    this.broadcastedNonSparse = false

    this.wants = new LocalWants(this)
    this.remoteWants = new RemoteWants(this)

    this.lengthAcked = 0

    this.extensions = new Map()
    this.lastExtensionSent = ''
    this.lastExtensionRecv = ''

    replicator._ifAvailable++
    replicator._active++
  }

  get remoteContiguousLength() {
    return this.remoteBitfield.findFirst(false, this._remoteContiguousLength)
  }

  getMaxInflight() {
    const stream = this.stream.rawStream
    if (!stream.udx) return Math.min(this.inflightRange[1], this.inflightRange[0] * 3)

    const scale =
      stream.rtt <= SCALE_LATENCY
        ? 1
        : (stream.rtt / SCALE_LATENCY) * Math.min(1, 2 / this.replicator.peers.length)
    return Math.max(
      this.inflightRange[0],
      Math.round(Math.min(this.inflightRange[1], this.inflightRange[0] * scale))
    )
  }

  getMaxHotswapInflight() {
    const inf = this.getMaxInflight()
    return Math.max(16, inf / 2)
  }

  signalUpgrade() {
    if (this._shouldUpdateCanUpgrade() === true) this._updateCanUpgradeAndSync()
    else this.sendSync()
  }

  _markInflight(index) {
    this.missingBlocks.set(index, false)
  }

  broadcastRange(start, length, drop) {
    if (!this.isActive()) return

    if (drop) this._unclearLocalRange(start, length)
    else this._clearLocalRange(start, length)

    const fullyContig = this.core.header.hints.contiguousLength === this.core.state.length

    if (start + LAST_BLOCKS < this.core.state.length && !drop && !fullyContig) {
      if (!this.remoteWants.hasRange(start, length)) return
    }

    let force = false
    if (fullyContig && !drop) {
      start = 0
      length = this.core.state.length

      // Always send the broadcast when we switch from sparse to fully contiguous, so remote knows too
      if (this.fullyDownloadedSignaled < length) {
        this.fullyDownloadedSignaled = length
        force = true
      }
    }

    // TODO: consider also adding early-returns on the drop===true case
    if (!force && !drop) {
      // No need to broadcast if the remote already has this range

      if (this._remoteContiguousLength >= start + length) return

      if (length === 1) {
        if (this.remoteBitfield.get(start)) return
      } else {
        if (this.remoteBitfield.firstUnset(start) >= start + length) return
      }
    }

    this.wireRange.send({
      drop,
      start,
      length
    })
    incrementTx(this.stats.wireRange, this.replicator.stats.wireRange)
  }

  extension(name, message) {
    this.wireExtension.send({ name: name === this.lastExtensionSent ? '' : name, message })
    incrementTx(this.stats.wireExtension, this.replicator.stats.wireExtension)
    this.lastExtensionSent = name
  }

  onextension(message) {
    const name = message.name || this.lastExtensionRecv
    this.lastExtensionRecv = name
    const ext = this.extensions.get(name)
    if (ext) {
      ext._onmessage({ start: 0, end: message.message.byteLength, buffer: message.message }, this)
    }
  }

  sendSync() {
    // Skip syncs if in repair mode
    if (this.core._repairMode) return

    if (this.syncsProcessing !== 0) {
      this.needsSync = true
      return
    }

    if (this.core.state.fork !== this.remoteFork) {
      this.canUpgrade = false
    }

    this.needsSync = false

    this.wireSync.send({
      fork: this.core.state.fork,
      length: this.core.state.length,
      remoteLength: this.core.state.fork === this.remoteFork ? this.remoteLength : 0,
      canUpgrade: this.canUpgrade,
      uploading: true,
      downloading: this.replicator.isDownloading(),
      hasManifest: !!this.core.header.manifest && this.core.compat === false,
      allowPush: this.replicator.isAllowingPush()
    })
    incrementTx(this.stats.wireSync, this.replicator.stats.wireSync)
  }

  onopen({ seeks, capability }) {
    const expected = caps.replicate(
      this.stream.isInitiator === false,
      this.core.key,
      this.stream.handshakeHash
    )

    if (b4a.equals(capability, expected) !== true) {
      // TODO: change this to a rejection instead, less leakage
      throw INVALID_CAPABILITY('Remote sent an invalid replication capability')
    }

    if (this.remoteOpened === true) return
    this.remoteOpened = true
    this.remoteSupportsSeeks = seeks

    this.protomux.cork()

    this.sendSync()

    const contig = Math.min(this.core.state.length, this.core.header.hints.contiguousLength)
    if (contig > 0) {
      this.broadcastRange(0, contig, false)

      if (contig === this.core.state.length) {
        this.broadcastedNonSparse = true
      }
    }

    this.replicator._ifAvailable--
    this.replicator._addPeer(this)

    this.protomux.uncork()

    this.core.checkIfIdle()
  }

  onclose(isRemote) {
    // we might have signalled to the remote that we are done (ie not downloading) and the remote might agree on that
    // if that happens, the channel might be closed by the remote. if so just renegotiate it.
    // TODO: add a CLOSE_REASON to mux to we can make this cleaner...
    const reopen =
      isRemote === true &&
      this.remoteOpened === true &&
      this.remoteDownloading === false &&
      this.remoteUploading === true &&
      this.replicator.downloading === true

    if (this.remoteOpened === false) {
      this.replicator._ifAvailable--
      this.replicator.queueUpdateAll()
      return
    }

    this.remoteOpened = false
    this.removed = true
    this.remoteRequests.clear() // cancel all
    this.receiverQueue.clear()

    if (this.roundtripQueue !== null) {
      for (const id of this.roundtripQueue.clear()) this.replicator._inflight.reusable(id)
    }

    this.replicator._removePeer(this)

    if (reopen) {
      this.replicator._makePeer(this.protomux)
    }
  }

  closeIfIdle() {
    if (this.remoteDownloading === false && this.replicator.isDownloading() === false) {
      // idling, shut it down...
      this.channel.close()
      return true
    }

    return false
  }

  async onsync(msg) {
    const {
      fork,
      length,
      remoteLength,
      canUpgrade,
      uploading,
      downloading,
      hasManifest,
      allowPush
    } = msg

    const lengthChanged = length !== this.remoteLength
    const sameFork = fork === this.core.state.fork

    this.remoteSynced = true
    this.remoteFork = fork
    this.remoteLength = length
    this.remoteCanUpgrade = canUpgrade
    this.remoteUploading = uploading
    this.remoteDownloading = downloading
    this.remoteHasManifest = hasManifest
    this.remoteAllowPush = allowPush

    if (this.closeIfIdle()) return

    this.lengthAcked = sameFork ? remoteLength : 0
    this.syncsProcessing++

    this.replicator._updateFork(this)

    if (this.remoteLength > this.core.state.length && this.lengthAcked === this.core.state.length) {
      if (this.replicator._addUpgradeMaybe() !== null) this._update()
    }

    const upgrade =
      lengthChanged === false || sameFork === false
        ? this.canUpgrade && sameFork
        : await this._canUpgrade(length, fork)

    if (length === this.remoteLength && fork === this.core.state.fork) {
      this.canUpgrade = upgrade
      if (upgrade) {
        this.lastUpgradableFork = fork
        this.lastUpgradableLength = length
      }
    }

    if (--this.syncsProcessing !== 0) return // ie not latest

    if (
      this.needsSync === true ||
      (this.core.state.fork === this.remoteFork && this.core.state.length > this.remoteLength)
    ) {
      this.signalUpgrade()
    }

    this._update()
  }

  _shouldUpdateCanUpgrade() {
    return (
      this.core.state.fork === this.remoteFork &&
      this.core.state.length > this.remoteLength &&
      this.canUpgrade === false &&
      this.syncsProcessing === 0
    )
  }

  async _updateCanUpgradeAndSync() {
    const { length, fork } = this.core.state

    const remoteLength = this.remoteLength
    const remoteFork = this.remoteFork
    const canUpgrade = await this._canUpgrade(this.remoteLength, this.remoteFork)

    if (
      this.syncsProcessing > 0 ||
      length !== this.core.state.length ||
      fork !== this.core.state.fork
    ) {
      return
    }
    if (remoteLength !== this.remoteLength || remoteFork !== this.remoteFork) {
      return
    }
    if (canUpgrade === this.canUpgrade) {
      return
    }

    this.canUpgrade = canUpgrade
    if (canUpgrade) {
      this.lastUpgradableLength = this.remoteLength
      this.lastUpgradableFork = this.remoteFork
    }

    this.sendSync()
  }

  // Safe to call in the background - never fails
  async _canUpgrade(remoteLength, remoteFork) {
    if (remoteFork !== this.core.state.fork) return false

    if (remoteLength === 0) return true
    if (remoteLength >= this.core.state.length) return false

    try {
      // Rely on caching to make sure this is cheap...
      const canUpgrade = await MerkleTree.upgradeable(this.core.state, remoteLength)

      if (remoteFork !== this.core.state.fork) return false

      return canUpgrade
    } catch {
      return false
    }
  }

  async _getProof(batch, msg, pushing) {
    let block = null

    if (msg.block) {
      const index = msg.block.index

      if (!pushing && (msg.fork !== this.core.state.fork || !this.core.bitfield.get(index))) {
        return new ProofRequest(msg, null, null, null)
      }

      block = batch.getBlock(index)
      block.catch(noop)
    }

    const manifest = msg.manifest && !this.core.compat ? this.core.header.manifest : null

    try {
      const proof = await MerkleTree.proof(this.core.state, batch, msg)
      return new ProofRequest(msg, proof, block, manifest)
    } catch (err) {
      batch.destroy()

      this.replicator._oninvalidrequest(err, msg, this)

      if (this.stats.invalidRequests >= MAX_INVALID_REQUESTS) throw err

      await backoff(this.stats.invalidRequests)
      return null
    }
  }

  async onrequest(msg) {
    const size = this.remoteRequests.size
    this.remoteRequests.set(msg.id, msg)

    // if size didnt change -> id overwrite -> old one is deleted, cancel current and re-add
    if (size === this.remoteRequests.size) {
      this._cancel(msg.id)
      this.remoteRequests.set(msg.id, msg)
    }

    if (!this.protomux.drained || this.receiverQueue.length) {
      this.receiverQueue.push(msg)
      return
    }

    if (this.replicator.destroyed) return

    await this._handleRequest(msg)
  }

  oncancel(msg) {
    this._cancel(msg.request)
  }

  _cancel(id) {
    this.remoteRequests.delete(id)
    this.receiverQueue.delete(id)
  }

  ondrain() {
    return this._handleRequests()
  }

  async _handleRequests() {
    if (this.receiverBusy || this.replicator.destroyed) return
    this.receiverBusy = true
    this.protomux.cork()

    while (
      this.remoteOpened &&
      this.protomux.drained &&
      this.receiverQueue.length > 0 &&
      !this.removed
    ) {
      const msg = this.receiverQueue.shift()
      await this._handleRequest(msg)
    }

    this.protomux.uncork()
    this.receiverBusy = false
  }

  async push(index) {
    if (!this.remoteAllowPush) return
    if (!this.remoteDownloading) return
    if (this.core.state.length <= index) return
    if (this.core.state.fork !== this.remoteFork) return
    if (this.remoteBitfield.get(index)) return

    const msg = {
      id: 0,
      fork: this.core.state.fork,
      block: null,
      hash: null,
      seek: null,
      upgrade: null,
      manifest: this.remoteLength === 0,
      priority: 0
    }

    await this.replicator._txLock.lock()
    try {
      const remoteLength = Math.max(this.remoteLength, this.pushedLength)

      msg.block = {
        index,
        nodes: MerkleTree.maxMissingNodes(2 * index, remoteLength)
      }

      if (index >= remoteLength) {
        msg.upgrade = {
          start: remoteLength,
          length: this.core.state.length - remoteLength
        }
      }

      let req = null
      const batch = this.core.storage.read()
      try {
        req = await this._getProof(batch, msg, true)
      } catch (err) {
        this.replicator._oninvalidrequest(err, msg, this)
        return
      }

      if (req === null) return
      batch.tryFlush()

      await this._fulfillRequest(req, true)
    } finally {
      this.replicator._txLock.unlock()
    }
  }

  async _handleRequest(msg) {
    const locked = !!msg.upgrade && this.remoteAllowPush

    if (locked) {
      // ensure contig push proofs
      await this.replicator._txLock.lock()
      const end = msg.upgrade.start + msg.upgrade.length

      if (this.pushedLength < end) {
        msg.upgrade.start = this.pushedLength
        msg.upgrade.length = end - this.pushedLength
      }
    }

    try {
      const batch = this.core.storage.read()

      // TODO: could still be answerable if (index, fork) is an ancestor of the current fork
      const req =
        msg.fork === this.core.state.fork
          ? await this._getProof(batch, msg, false)
          : new ProofRequest(msg, null, null, null)

      if (req === null) {
        this.wireNoData.send({ request: msg.id, reason: INVALID_REQUEST })
        return
      }

      batch.tryFlush()

      await this._fulfillRequest(req, false)
    } finally {
      if (locked) this.replicator._txLock.unlock()
    }
  }

  async _fulfillRequest(req, pushing) {
    if (this.core._repairMode) {
      // if cancelled do not reply
      if (this.remoteRequests.get(req.msg.id) !== req.msg) {
        return
      }

      // sync from now on, so safe to delete from the map
      this.remoteRequests.delete(req.msg.id)

      // If cutting off the fulfillment, ensure promise is caught.
      // While repairing merkle tree nodes can be `nil` so can throw.
      req.fulfill().catch(safetyCatch)
      return
    }

    const proof = await req.fulfill()

    if (!pushing) {
      // if cancelled do not reply
      if (this.remoteRequests.get(req.msg.id) !== req.msg) {
        return
      }

      // sync from now on, so safe to delete from the map
      this.remoteRequests.delete(req.msg.id)
    } else if (!this.remoteAllowPush) {
      // if pushing but remote disabled it, just drop it
      return
    }

    if (!this.isActive() && proof.block !== null) {
      return
    }

    if (proof === null) {
      if (req.msg.manifest && this.core.header.manifest) {
        const manifest = this.core.header.manifest
        this.wireData.send({
          request: req.msg.id,
          fork: this.core.state.fork,
          block: null,
          hash: null,
          seek: null,
          upgrade: null,
          manifest
        })
        incrementTx(this.stats.wireData, this.replicator.stats.wireData)
        return
      }

      this.wireNoData.send({ request: req.msg.id, reason: NOT_AVAILABLE })
      return
    }

    if (proof.block !== null) {
      this.replicator._onupload(proof.block.index, proof.block.value.byteLength, this)
    }

    if (proof.upgrade) {
      const remoteLength = MerkleTree.upgradeLength(proof.upgrade)
      if (remoteLength > this.pushedLength) this.pushedLength = remoteLength
    }

    this.wireData.send({
      request: req.msg.id,
      fork: req.msg.fork,
      block: proof.block,
      hash: proof.hash,
      seek: proof.seek,
      upgrade: proof.upgrade,
      manifest: proof.manifest
    })
    incrementTx(this.stats.wireData, this.replicator.stats.wireData)
  }

  _cancelRequest(req) {
    if (req.priority === PRIORITY.CANCELLED) return
    // mark as cancelled also and avoid re-entry
    req.priority = PRIORITY.CANCELLED

    this.inflight--
    this.replicator._requestDone(req.id, false)

    // clear inflight state
    if (isBlockRequest(req)) this.replicator._unmarkInflight(req.block.index)
    if (isUpgradeRequest(req)) this.replicator._clearInflightUpgrade(req)

    if (this.roundtripQueue === null) this.roundtripQueue = new RoundtripQueue()
    this.roundtripQueue.add(req.id)
    this.wireCancel.send({ request: req.id })
    incrementTx(this.stats.wireCancel, this.replicator.stats.wireCancel)
  }

  _checkIfConflict() {
    this.paused = true

    const length = Math.min(this.core.state.length, this.remoteLength)
    if (length === 0) return // pause and ignore

    this.wireRequest.send({
      id: 0, // TODO: use an more explicit id for this eventually...
      fork: this.remoteFork,
      block: null,
      hash: null,
      seek: null,
      upgrade: {
        start: 0,
        length
      }
    })

    incrementTx(this.stats.wireRequest, this.replicator.stats.wireRequest)
  }

  _unmarkInflightBlockRequest(req, data) {
    if (isBlockRequest(req)) this.replicator._unmarkInflight(req.block.index)
    else if (data.block && !req) this.replicator._unmarkInflight(data.block.index)
  }

  async ondata(data) {
    if (data.request !== 0 && !data.upgrade) return this._handleData(data)

    await this.replicator._rxLock.lock()
    try {
      await this._handleData(data)
    } finally {
      this.replicator._rxLock.unlock()
    }
  }

  async _handleData(data) {
    // always allow a fork conflict proof to be sent
    if (data.request === 0 && data.upgrade && data.upgrade.start === 0) {
      if (await this.core.checkConflict(data, this)) return
      this.paused = false
    }

    const req = data.request > 0 ? this.replicator._inflight.get(data.request) : null
    const reorg = data.fork > this.core.state.fork

    // no push atm, TODO: check if this satisfies another pending request
    // allow reorg pushes tho as those are not written to storage so we'll take all the help we can get
    if (req === null && reorg === false && !this.replicator.allowPush) {
      return
    }

    // Skip accepting data if in repair mode to avoid corruption
    if (this.core._repairMode) {
      this.replicator._onnodata(this, req, NOT_AVAILABLE)
      return
    }

    if (req === null && reorg === false && data.block) {
      // mark this as inflight to avoid parallel requests
      this.replicator._markInflight(data.block.index)
    }

    if (req !== null) {
      if (req.peer !== this) return
      this._onrequestroundtrip(req)
    }

    try {
      if (reorg === true) return await this.replicator._onreorgdata(this, req, data)
    } catch (err) {
      safetyCatch(err)
      this._unmarkInflightBlockRequest(req, data)

      this.paused = true
      this.replicator._oninvaliddata(err, req, data, this)
      return
    }

    this.dataProcessing++
    if (isBlockRequest(req)) this.replicator._markProcessing(req.block.index)

    try {
      if (!this.replicator._matchingRequest(req, data) || !(await this.core.verify(data, this))) {
        this.replicator._onnodata(this, req, 0)
        return
      }
    } catch (err) {
      safetyCatch(err)
      this._unmarkInflightBlockRequest(req, data)

      if (err.code === 'WRITE_FAILED') {
        // For example, we don't want to keep pulling data when storage is full
        // TODO: notify the user somehow
        this.paused = true
        return
      }

      if (this.core.closed && !isCriticalError(err)) return

      if (err.code !== 'INVALID_OPERATION') {
        // might be a fork, verify
        this._checkIfConflict()
      }

      // if push mode, we MIGHT get an occasional bad message
      // no need to mega bail for that. TODO: rate limit instead as a general thing
      if (!this.replicator.allowPush) {
        this.paused = true
      }

      this.replicator._onnodata(this, req, 0)
      this.replicator._oninvaliddata(err, req, data, this)
      return
    } finally {
      if (isBlockRequest(req)) this.replicator._markProcessed(req.block.index)
      this.dataProcessing--
    }

    this.replicator._ondata(this, req, data)

    if (this._shouldUpdateCanUpgrade() === true) {
      this._updateCanUpgradeAndSync()
    }
  }

  onnodata({ request, reason }) {
    const req = request > 0 ? this.replicator._inflight.get(request) : null

    if (req === null || req.peer !== this) {
      this.replicator.queueUpdateAll()
      return
    }

    this._onrequestroundtrip(req)
    this.replicator._onnodata(this, req, reason)
  }

  _onrequestroundtrip(req) {
    if (req.priority === PRIORITY.CANCELLED) return
    // to avoid re-entry we also just mark it as cancelled
    req.priority = PRIORITY.CANCELLED

    this.inflight--
    this.replicator._requestDone(req.id, true)
    if (this.roundtripQueue === null) return
    const flushed = this.roundtripQueue.flush(req.rt)
    if (flushed === null) return
    for (const id of flushed) this.replicator._inflight.reusable(id)
  }

  onwant(range) {
    if (!this.remoteWants.add(range)) return
    this.replicator._onwant(this, range.start, range.length, range.any)
  }

  onunwant(range) {
    this.remoteWants.remove(range)
  }

  onbitfield({ start, bitfield }) {
    if (start < this._remoteContiguousLength) this._remoteContiguousLength = start // bitfield is always the truth
    this.remoteBitfield.insert(start, bitfield)
    this.missingBlocks.insert(start, bitfield)
    this._clearLocalRange(start, bitfield.byteLength * 8)
    this._update()
  }

  _clearLocalRange(start, length) {
    const bitfield = this.core.skipBitfield === null ? this.core.bitfield : this.core.skipBitfield

    if (length === 1) {
      this.missingBlocks.set(start, this._remoteHasBlock(start) && !bitfield.get(start))
      return
    }

    const contig = Math.min(this.core.state.length, this.core.header.hints.contiguousLength)

    if (start + length < contig) {
      this.missingBlocks.setRange(start, contig, false)
      return
    }

    const rem = start & 32767
    if (rem > 0) {
      start -= rem
      length += rem
    }

    const end = start + Math.min(length, this.core.state.length)
    while (start < end) {
      const local = bitfield.getBitfield(start)

      if (local && local.bitfield) {
        this.missingBlocks.clear(start, local.bitfield)
      }

      start += 32768
    }
  }

  _resetMissingBlock(index) {
    const bitfield = this.core.skipBitfield === null ? this.core.bitfield : this.core.skipBitfield
    this.missingBlocks.set(index, this._remoteHasBlock(index) && !bitfield.get(index))
  }

  _unclearLocalRange(start, length) {
    if (length === 1) {
      this._resetMissingBlock(start)
      return
    }

    const rem = start & (RemoteBitfield.BITS_PER_SEGMENT - 1)
    if (rem > 0) {
      start -= rem
      length += rem
    }

    const fixedStart = start

    const end = start + Math.min(length, this.remoteLength)
    while (start < end) {
      const remote = this.remoteBitfield.getBitfield(start)
      if (remote && remote.bitfield) {
        this.missingBlocks.insert(start, remote.bitfield)
      }

      start += RemoteBitfield.BITS_PER_SEGMENT
    }

    this._clearLocalRange(fixedStart, length)
  }

  async onrange({ drop, start, length }) {
    const has = drop === false

    if (drop === true && start < this._remoteContiguousLength) {
      this._remoteContiguousLength = start
    }

    if (start === 0 && drop === false) {
      if (length > this._remoteContiguousLength) {
        this._remoteContiguousLength = length
        if (
          this.remoteFork === this.core.state.fork &&
          length > this.core.header.hints.remoteContiguousLength
        ) {
          this.core.updateRemoteContiguousLength(length)
        }
      }
    } else if (length === 1) {
      const bitfield = this.core.skipBitfield === null ? this.core.bitfield : this.core.skipBitfield
      this.remoteBitfield.set(start, has)
      this.missingBlocks.set(start, has && !bitfield.get(start))
    } else {
      const rangeStart = this.remoteBitfield.findFirst(!has, start)
      const rangeEnd = length + start

      if (rangeStart !== -1 && rangeStart < rangeEnd) {
        this.remoteBitfield.setRange(rangeStart, rangeEnd, has)
        this.missingBlocks.setRange(rangeStart, rangeEnd, has)
        if (has) this._clearLocalRange(rangeStart, rangeEnd - rangeStart)
      }
    }

    if (this.core.hintsChanged) await this.core.flushHints()
    if (drop === false) this._update()

    this.core.emitRemoteContiguousLength()
  }

  onreorghint() {
    // TODO
  }

  _update() {
    // TODO: if this is in a batch or similar it would be better to defer it
    // we could do that with nextTick/microtick mb? (combined with a property on the session to signal read buffer mb)
    this.replicator.updatePeer(this)
  }

  async _onconflict() {
    this.protomux.cork()
    if (this.remoteLength > 0 && this.core.state.fork === this.remoteFork) {
      await this.onrequest({
        id: 0,
        fork: this.core.state.fork,
        block: null,
        hash: null,
        seek: null,
        upgrade: {
          start: 0,
          length: Math.min(this.core.state.length, this.remoteLength)
        }
      })
    }
    this.channel.close()
    this.protomux.uncork()
  }

  _makeRequest(needsUpgrade, priority, minLength) {
    if (needsUpgrade === true && this.replicator._shouldUpgrade(this) === false) {
      return null
    }

    // ensure that the remote has signalled they have the length we request
    if (this.remoteLength < minLength) {
      return null
    }

    if (needsUpgrade === false && this.replicator._autoUpgrade(this) === true) {
      needsUpgrade = true
    }

    return {
      peer: this,
      rt: this.roundtripQueue === null ? 0 : this.roundtripQueue.tick,
      id: 0,
      fork: this.remoteFork,
      block: null,
      hash: null,
      seek: null,
      upgrade:
        needsUpgrade === false
          ? null
          : { start: this.core.state.length, length: this.remoteLength - this.core.state.length },
      // remote manifest check can be removed eventually...
      manifest: this.core.header.manifest === null && this.remoteHasManifest === true,
      priority,
      timestamp: Date.now(),
      elapsed: 0
    }
  }

  _requestManifest() {
    const req = this._makeRequest(false, 0, 0)
    if (req === null) return

    this._send(req)
  }

  _includeLastBlock() {
    if (this.replicator._alwaysLatestBlock === 0) return null

    const index = this.remoteLength - 1

    // only valid if its an OOB get
    if (index < this.core.state.length) return null

    // do the normal checks
    if (!this._remoteHasBlock(index)) return null
    if (!this._canRequest(index, false)) return null

    // atm we only ever do one upgrade request in parallel, if that changes
    // then we should add some check here for inflights to avoid over requesting
    const b = this.replicator._blocks.add(index, PRIORITY.NORMAL, false)
    return b
  }

  _requestUpgrade(u) {
    if (this.replicator.pushOnly) return false

    const req = this._makeRequest(true, 0, 0)
    if (req === null) return false

    const b = this._includeLastBlock()

    if (b) this._sendBlockRequest(req, b)
    else this._send(req)

    return true
  }

  _requestSeek(s) {
    // if replicator is updating the seeks etc, bail and wait for it to drain
    if (this.replicator._updatesPending > 0) return false
    if (this.replicator.pushOnly) return false

    const { length, fork } = this.core.state

    if (fork !== this.remoteFork) return false

    if (s.seeker.start >= length) {
      const req = this._makeRequest(true, 0, 0)

      // We need an upgrade for the seek, if non can be provided, skip
      if (req === null) return false

      req.seek = this.remoteSupportsSeeks
        ? { bytes: s.seeker.bytes, padding: s.seeker.padding }
        : null

      s.inflight.push(req)
      this._send(req)

      return true
    }

    const len = s.seeker.end - s.seeker.start
    const off = s.seeker.start + Math.floor(Math.random() * len)

    for (let i = 0; i < len; i++) {
      let index = off + i
      if (index > s.seeker.end) index -= len

      if (this._remoteHasBlock(index) === false) continue
      if (this.core.bitfield.get(index) === true) continue
      if (!this._canRequest(index, false)) continue

      // Check if this block is currently inflight - if so pick another
      const b = this.replicator._blocks.get(index)
      if (b !== null && b.inflight.length > 0) continue

      // Block is not inflight, but we only want the hash, check if that is inflight
      const h = this.replicator._hashes.add(index, PRIORITY.NORMAL, false)
      if (h.inflight.length > 0) continue

      const req = this._makeRequest(false, h.priority, index + 1)
      if (req === null) continue

      const nodes = flatTree.depth(s.seeker.start + s.seeker.end - 1)

      req.hash = { index: 2 * index, nodes }
      req.seek = this.remoteSupportsSeeks
        ? { bytes: s.seeker.bytes, padding: s.seeker.padding }
        : null

      s.inflight.push(req)
      h.inflight.push(req)
      this._send(req)

      return true
    }

    this._maybeWantAnyRange(s.seeker.start, len, s)
    return false
  }

  _canRequest(index, force) {
    if (!(index >= 0)) throw ASSERTION('bad index to _canRequest: ' + index)

    if (!force && this.replicator.pushOnly) {
      return false
    }

    if (this.remoteLength >= this.core.state.length) {
      return true
    }

    if (index < this.lastUpgradableLength && this.lastUpgradableFork === this.core.state.fork) {
      return true
    }

    if (this.canUpgrade && this.syncsProcessing === 0) {
      return true
    }

    return false
  }

  _remoteHasBlock(index) {
    return index < this._remoteContiguousLength || this.remoteBitfield.get(index) === true
  }

  _sendBlockRequest(req, b) {
    if (this.core._repairMode) return

    req.block = { index: b.index, nodes: 0 }
    this.replicator._markInflight(b.index)

    b.inflight.push(req)
    this.replicator.hotswaps.add(b)
    this._send(req)
  }

  _requestBlock(b) {
    const { length, fork } = this.core.state

    if (this._remoteHasBlock(b.index) === false || fork !== this.remoteFork) {
      if (!this.core.bitfield.get(b.index)) this._maybeWant(b.index, b)
      return false
    }

    if (!this._canRequest(b.index, b.force)) return false

    const req = this._makeRequest(b.index >= length, b.priority, b.index + 1)
    if (req === null) return false

    this._sendBlockRequest(req, b)

    return true
  }

  _maybeWant(index, handle) {
    if (index < this.remoteContiguousLength) return

    const res = this.wants.add(index, handle)
    if (!res) return

    const batch = res.want && res.unwant
    if (batch) this.protomux.cork()

    if (res.unwant) {
      this.wireUnwant.send(res.unwant)
      incrementTx(this.stats.wireUnwant, this.replicator.stats.wireUnwant)
    }
    if (res.want) {
      this.wireWant.send(res.want)
      incrementTx(this.stats.wireWant, this.replicator.stats.wireWant)
    }

    if (batch) this.protomux.uncork()
  }

  _maybeWantAnyRange(start, length, handle) {
    if (handle.wants) {
      for (const w of handle.wants) {
        if ((w.start !== start || w.length !== length) && w.any) {
          const req = this.wants.removeAnyRange(w.start, w.length, handle)
          if (req) this.wireUnwant.send(req)
        }
      }
    }

    if (start + length <= this.remoteContiguousLength) return

    const req = this.wants.addAnyRange(start, length, handle)
    if (req) this.wireWant.send(req)
  }

  _requestRangeBlock(index, length) {
    if (this.core.bitfield.get(index) === true || !this._canRequest(index, false)) return false

    const b = this.replicator._blocks.add(index, PRIORITY.NORMAL, false)
    if (b.inflight.length > 0) {
      this.missingBlocks.set(index, false) // in case we missed some states just set them ondemand, nbd
      return false
    }

    const req = this._makeRequest(index >= length, b.priority, index + 1)

    // If the request cannot be satisfied, dealloc the block request if no one is subscribed to it
    if (req === null) {
      b.gc()
      return false
    }

    this._sendBlockRequest(req, b)

    // Don't think this will ever happen, as the pending queue is drained before the range queue
    // but doesn't hurt to check this explicitly here also.
    if (b.queued) b.queued = false
    return true
  }

  _findNext(i) {
    if (i < this._remoteContiguousLength) {
      if (this.core.skipBitfield === null) this.replicator._openSkipBitfield()
      i = this.core.skipBitfield.findFirst(false, i)
      if (i < this._remoteContiguousLength && i > -1) return i
      i = this._remoteContiguousLength
    }

    return this.missingBlocks.findFirst(true, i)
  }

  _addRangeBatch(r, offset, end) {
    const { WANT_BATCH } = w
    while (offset < end) {
      const next = this.core.bitfield.findFirst(false, offset)
      if (next === -1 || next >= end) return false

      const b = (next - (next & (WANT_BATCH - 1))) / WANT_BATCH

      if (r.addBatch(b)) return true

      offset = (b + 1) * WANT_BATCH
    }

    return false
  }

  _populateRangeBatches(r) {
    const { WANT_BATCH } = w
    for (let i = r.batches.length - 1; i >= 0; i--) {
      const b = r.batches[i]
      const minStart = b.batch * WANT_BATCH
      const maxEnd = minStart + WANT_BATCH

      const start = Math.max(r.start, minStart)
      const end = Math.min(r.end === -1 ? maxEnd : r.end, maxEnd)

      if (start < end && this.core.bitfield.hasUnset(start, end - start)) continue

      r.removeBatch(b)
    }

    while (r.batches.length < 3) {
      const end = r.end === -1 ? this.core.state.length : r.end
      if (end <= r.start) return

      const len = end - r.start
      const off = r.start + (r.linear ? 0 : Math.floor(Math.random() * len))

      if (!this._addRangeBatch(r, off, end) && !this._addRangeBatch(r, r.start, end)) break
    }
  }

  _requestRangeBatch(start, end, length) {
    let tries = this.inflight

    do {
      start = this._findNext(start)
      if (start === -1 || start >= end) break

      if (this._requestRangeBlock(start, length)) return true
      start++
    } while (tries-- > 0)

    return false
  }

  _getValidEnd(maxEnd) {
    // if we can upgrade the remote, or the remote is ahead, then all the remotes blocks are valid
    // otherwise truncate to the last length the remote has acked for us
    const maxLocalLength =
      this.canUpgrade || this.remoteLength >= this.core.state.length
        ? this.core.state.length
        : this.core.state.fork === this.lastUpgradableFork
          ? Math.min(this.lastUpgradableLength, this.core.state.length)
          : 0

    return Math.min(
      maxLocalLength,
      Math.min(maxEnd === -1 ? this.remoteLength : maxEnd, this.remoteLength)
    )
  }

  _requestRange(r) {
    const { WANT_BATCH } = w
    if (this.syncsProcessing > 0) return false

    const { length, fork } = this.core.state

    if (r.blocks) {
      for (let i = r.start; i < r.end; i++) {
        const index = r.blocks[i]
        const has = index < this._remoteContiguousLength || this.missingBlocks.get(index) === true
        if (has === true && this._requestRangeBlock(index, length)) return true
        this._maybeWant(index, r)
      }

      return false
    }

    this._populateRangeBatches(r)

    const end = this._getValidEnd(r.end)

    if (end <= r.start || fork !== this.remoteFork) return false

    for (let i = 0; i < r.batches.length; i++) {
      const b = r.batches[i]

      const batchStart = Math.max(b.batch * WANT_BATCH, r.start)
      const batchEnd = Math.min((b.batch + 1) * WANT_BATCH, end)
      const len = batchEnd - batchStart
      const off = batchStart + (r.linear ? 0 : Math.floor(Math.random() * len))

      if (
        this._requestRangeBatch(off, end, length) ||
        this._requestRangeBatch(batchStart, off, length)
      ) {
        return true
      }

      this._maybeWant(batchStart, b)
    }

    // Here we should consider making an OOB request (ie if the remote says they have a newer block)
    // but the upgrade code already does that, so no big deal for now

    return false
  }

  _requestForkProof(f) {
    if (!this.remoteLength) return
    if (this.replicator.pushOnly) return

    const req = this._makeRequest(false, 0, 0)
    if (req === null) return

    req.upgrade = { start: 0, length: this.remoteLength }
    req.manifest = !this.core.header.manifest

    f.inflight.push(req)
    this._send(req)
  }

  _requestForkRange(f) {
    if (f.fork !== this.remoteFork || f.batch.want === null) return false
    if (this.replicator.pushOnly) return false

    const end = Math.min(f.batch.want.end, this.remoteLength)
    if (end < f.batch.want.start) return false

    const len = end - f.batch.want.start
    const off = f.batch.want.start + Math.floor(Math.random() * len)

    for (let i = 0; i < len; i++) {
      let index = off + i
      if (index >= end) index -= len

      if (this._remoteHasBlock(index) === false) continue

      const req = this._makeRequest(false, 0, 0)
      if (req === null) return false

      req.hash = { index: 2 * index, nodes: f.batch.want.nodes }

      f.inflight.push(req)
      this._send(req)

      return true
    }

    this._maybeWantAnyRange(f.batch.want.start, len, f)
    return false
  }

  isActive() {
    if (this.paused || this.removed || this.core.header.frozen) return false
    return true
  }

  async _send(req) {
    const fork = this.core.state.fork

    this.inflight++
    this.replicator._inflight.add(req)

    if (req.upgrade !== null && req.fork === fork) {
      const u = this.replicator._addUpgrade()
      u.inflight.push(req)
    }

    try {
      if (req.block !== null && req.fork === fork) {
        req.block.nodes = await MerkleTree.missingNodes(
          this.core.state,
          2 * req.block.index,
          this.core.state.length
        )
        if (req.priority === PRIORITY.CANCELLED) return
      }
      if (req.hash !== null && req.fork === fork && req.hash.nodes === 0) {
        req.hash.nodes = await MerkleTree.missingNodes(
          this.core.state,
          req.hash.index,
          this.core.state.length
        )
        if (req.priority === PRIORITY.CANCELLED) return

        // nodes === 0, we already have it, bail
        if (req.hash.nodes === 0 && (req.hash.index & 1) === 0) {
          this.inflight--
          this.replicator._resolveHashLocally(this, req)
          return
        }
      }
    } catch (err) {
      this.stream.destroy(err)
      return
    }

    this.wireRequest.send(req)
    incrementTx(this.stats.wireRequest, this.replicator.stats.wireRequest)
  }
}

module.exports = class Replicator {
  static Peer = Peer // hack to be able to access Peer from outside this module

  constructor(
    core,
    {
      notDownloadingLinger = NOT_DOWNLOADING_SLACK,
      eagerUpgrade = true,
      allowFork = true,
      allowPush = false,
      alwaysLatestBlock = false,
      inflightRange = null
    } = {}
  ) {
    this.core = core
    this.eagerUpgrade = eagerUpgrade
    this.allowFork = allowFork
    this.allowPush = allowPush
    this.ondownloading = null // optional external hook for monitoring downloading status
    this.peers = []
    this.findingPeers = 0 // updatable from the outside
    this.destroyed = false
    this.downloading = false
    this.pushOnly = false
    this.activeSessions = 0

    this.hotswaps = new HotswapQueue()
    this.inflightRange = inflightRange || DEFAULT_MAX_INFLIGHT

    // Note: nodata and unwant not currently tracked
    // tx = transmitted, rx = received
    this.stats = {
      wireSync: { tx: 0, rx: 0 },
      wireRequest: { tx: 0, rx: 0 },
      wireCancel: { tx: 0, rx: 0 },
      wireData: { tx: 0, rx: 0 },
      wireWant: { tx: 0, rx: 0 },
      wireUnwant: { tx: 0, rx: 0 },
      wireBitfield: { tx: 0, rx: 0 },
      wireRange: { tx: 0, rx: 0 },
      wireExtension: { tx: 0, rx: 0 },
      hotswaps: 0,
      invalidData: 0,
      invalidRequests: 0,
      backoffs: 0,
      notAvailableBackoffs: 0
    }

    this._attached = new Set()
    this._inflight = new InflightTracker()
    this._blocks = new BlockTracker(this)
    this._hashes = new BlockTracker(this)

    this._alwaysLatestBlock = alwaysLatestBlock ? 1 : 0
    this._queued = []

    this._seeks = []
    this._upgrade = null
    this._reorgs = []
    this._ranges = []

    this._rxLock = new Mutex()
    this._txLock = new Mutex()

    this._hadPeers = false
    this._active = 0
    this._ifAvailable = 0
    this._updatesPending = 0
    this._applyingReorg = null
    this._manifestPeer = null
    this._notDownloadingLinger = notDownloadingLinger
    this._notDownloadingTimer = null

    this._updateAllBump = null
    this._updateAllBound = this.updateAll.bind(this)

    const self = this
    this._onstreamclose = onstreamclose

    function onstreamclose() {
      self.detachFrom(this.userData)
    }
  }

  setInflightRange(min, max) {
    const def = this.inflightRange
    this.inflightRange = [min, max]
    for (const peer of this.peers) {
      if (peer.inflightRange !== def) continue
      peer.inflightRange = this.inflightRange
    }
  }

  updateActivity(inc, session) {
    this.activeSessions += inc
    this.setDownloading(this.activeSessions !== 0, session)
  }

  isDownloading() {
    return this.downloading || !this._inflight.idle
  }

  async push(index) {
    const all = []
    for (const peer of this.peers) {
      all.push(peer.push(index))
    }
    await Promise.all(all)
  }

  setAllowPush(allowPush) {
    if (allowPush === this.allowPush) return
    this.allowPush = allowPush
    for (const peer of this.peers) peer.sendSync()
  }

  isAllowingPush() {
    if (!this.allowPush) return false
    if (this._notDownloadingTimer) return false
    return this.downloading
  }

  setPushOnly(pushOnly) {
    if (pushOnly === this.pushOnly) return
    this.pushOnly = pushOnly
  }

  setDownloading(downloading) {
    const allowPush = this.isAllowingPush()
    const linger = this._notDownloadingLinger

    if (this._notDownloadingTimer) {
      clearTimeout(this._notDownloadingTimer)
      this._notDownloadingTimer = null
    }

    if (this.destroyed) return

    if (downloading || linger === 0) {
      if (!this._setDownloadingNow(downloading)) this.signalAllowPush(allowPush)
      return
    }

    this._notDownloadingTimer = setTimeout(setNotDownloadingLater, linger, this)
    if (this._notDownloadingTimer.unref) this._notDownloadingTimer.unref()
    this.signalAllowPush(allowPush)
  }

  signalAllowPush(allowPush) {
    if (allowPush === this.isAllowingPush()) return
    for (const peer of this.peers) peer.signalUpgrade()
  }

  _setDownloadingNow(downloading) {
    this._notDownloadingTimer = null

    if (this.downloading === downloading) return false
    this.downloading = downloading

    if (!downloading && this.isDownloading()) return false

    for (const peer of this.peers) peer.signalUpgrade()

    if (downloading) {
      // restart channel if needed...
      for (const protomux of this._attached) {
        if (!protomux.stream.handshakeHash) continue
        if (protomux.opened({ protocol: 'hypercore/alpha', id: this.core.discoveryKey })) continue
        this._makePeer(protomux, true)
      }
    } else {
      for (const peer of this.peers) peer.closeIfIdle()
    }

    if (this.ondownloading !== null && downloading) this.ondownloading()
    return true
  }

  cork() {
    for (const peer of this.peers) peer.protomux.cork()
  }

  uncork() {
    for (const peer of this.peers) peer.protomux.uncork()
  }

  // Called externally when a range of new blocks has been processed/removed
  onhave(start, length, drop = false) {
    for (const peer of this.peers) peer.broadcastRange(start, length, drop)
  }

  // Called externally when a truncation upgrade has been processed
  ontruncate(newLength, truncated) {
    const notify = []

    for (const blk of this._blocks) {
      if (blk.index < newLength) continue
      notify.push(blk)
    }

    for (const blk of notify) {
      for (const r of blk.refs) {
        if (r.snapshot === false) continue
        blk.detach(r, SNAPSHOT_NOT_AVAILABLE())
      }
    }

    for (const peer of this.peers) {
      peer.fullyDownloadedSignaled = Math.min(newLength, peer.fullyDownloadedSignaled)
      peer._unclearLocalRange(newLength, truncated)
    }
  }

  // Called externally when a upgrade has been processed
  onupgrade() {
    for (const peer of this.peers) peer.signalUpgrade()
    if (this._blocks.isEmpty() === false) this._resolveBlocksLocally()
    if (this._upgrade !== null) this._resolveUpgradeRequest(null)
    if (!this._blocks.isEmpty() || this._ranges.length !== 0 || this._seeks.length !== 0) {
      this._updateNonPrimary(true)
    }
  }

  // Called externally when a conflict has been detected and verified
  async onconflict() {
    const all = []
    for (const peer of this.peers) {
      all.push(peer._onconflict())
    }
    await Promise.allSettled(all)
  }

  async applyPendingReorg() {
    if (this._applyingReorg !== null) {
      await this._applyingReorg
      return true
    }

    for (let i = this._reorgs.length - 1; i >= 0; i--) {
      const f = this._reorgs[i]
      if (f.batch !== null && f.batch.finished) {
        await this._applyReorg(f)
        return true
      }
    }

    return false
  }

  addUpgrade(session) {
    if (this._upgrade !== null) {
      const ref = this._upgrade.attach(session)
      this._checkUpgradeIfAvailable()
      return ref
    }

    const ref = this._addUpgrade().attach(session)

    this.queueUpdateAll()

    return ref
  }

  addBlock(session, index, force) {
    const b = this._blocks.add(index, PRIORITY.HIGH, force)
    const ref = b.attach(session)

    this._queueBlock(b)
    this.queueUpdateAll()

    return ref
  }

  addSeek(session, seeker) {
    const s = new SeekRequest(this, this._seeks, seeker)
    const ref = s.attach(session)

    this._seeks.push(s)
    this.queueUpdateAll()

    return ref
  }

  addRange(
    session,
    { start = 0, end = -1, length = toLength(start, end), blocks = null, linear = false } = {}
  ) {
    if (blocks !== null) {
      // if using blocks, start, end just acts as frames around the blocks array
      start = 0
      end = length = blocks.length
    }

    const r = new RangeRequest(
      this,
      this._ranges,
      start,
      length === -1 ? -1 : start + length,
      linear,
      blocks
    )

    const ref = r.attach(session)

    // Trigger this to see if this is already resolved...
    // Also auto compresses the range based on local bitfield
    clampRange(this.core, r)

    if (r.end !== -1 && r.start >= r.end) {
      this._resolveRangeRequest(r)
      return ref
    }

    this.queueUpdateAll()

    return ref
  }

  cancel(ref) {
    ref.context.detach(ref, null)
  }

  static clearRequests(session, err) {
    if (session.length === 0) return
    if (session.length === 1 && session[0] === null) return

    const updated = new Set()

    while (session.length > 0) {
      const ref = session[session.length - 1]
      updated.add(ref.context.replicator)
      ref.context.detach(ref, err)
    }

    for (const replicator of updated) {
      replicator.queueUpdateAll()
    }
  }

  clearRequests(session, err = null) {
    let cleared = false
    while (session.length > 0) {
      const ref = session[session.length - 1]
      ref.context.detach(ref, err)
      cleared = true
    }

    if (cleared) this.queueUpdateAll()
  }

  _matchingRequest(req, data) {
    if (this.allowPush) {
      return true
    }
    if (data.block !== null && (req.block === null || req.block.index !== data.block.index)) {
      return false
    }
    if (data.hash !== null && (req.hash === null || req.hash.index !== data.hash.index)) {
      return false
    }
    if (data.seek !== null && (req.seek === null || req.seek.bytes !== data.seek.bytes)) {
      return false
    }
    if (data.upgrade !== null && req.upgrade === null) {
      return false
    }
    return req.fork === data.fork
  }

  _addUpgradeMaybe() {
    return this.eagerUpgrade === true ? this._addUpgrade() : this._upgrade
  }

  // TODO: this function is OVER called atm, at each updatePeer/updateAll
  // instead its more efficient to only call it when the conditions in here change - ie on sync/add/remove peer
  // Do this when we have more tests.
  _checkUpgradeIfAvailable() {
    if (this._ifAvailable > 0 && this.peers.length < MAX_PEERS_UPGRADE) return
    if (this._upgrade === null || this._upgrade.refs.length === 0) return
    if (this._hadPeers === false && this.findingPeers > 0) return

    const maxPeers = Math.min(this.peers.length, MAX_PEERS_UPGRADE)

    // check if a peer can upgrade us

    for (let i = 0; i < maxPeers; i++) {
      const peer = this.peers[i]

      if (peer.remoteSynced === false) return

      if (this.core.state.length === 0 && peer.remoteLength > 0) return

      if (peer.remoteLength <= this._upgrade.length || peer.remoteFork !== this._upgrade.fork) {
        continue
      }

      if (peer.syncsProcessing > 0) return

      if (peer.lengthAcked !== this.core.state.length && peer.remoteFork === this.core.state.fork) {
        return
      }

      if (peer.remoteCanUpgrade === true) return
    }

    // check if reorgs in progress...

    if (this._applyingReorg !== null) return

    // TODO: we prob should NOT wait for inflight reorgs here, seems better to just resolve the upgrade
    // and then apply the reorg on the next call in case it's slow - needs some testing in practice

    for (let i = 0; i < this._reorgs.length; i++) {
      const r = this._reorgs[i]
      if (r.inflight.length > 0) return
    }

    // if something is inflight, wait for that first
    if (this._upgrade.inflight.length > 0) return

    // nothing to do, indicate no update avail

    const u = this._upgrade
    this._upgrade = null
    u.resolve(false)
  }

  _addUpgrade() {
    if (this._upgrade !== null) return this._upgrade

    // TODO: needs a reorg: true/false flag to indicate if the user requested a reorg
    this._upgrade = new UpgradeRequest(this, this.core.state.fork, this.core.state.length)

    return this._upgrade
  }

  _addReorg(fork, peer) {
    if (this.allowFork === false) return null

    // TODO: eager gc old reorgs from the same peer
    // not super important because they'll get gc'ed when the request finishes
    // but just spam the remote can do ...

    for (const f of this._reorgs) {
      if (f.fork > fork && f.batch !== null) return null
      if (f.fork === fork) return f
    }

    const f = new ForkRequest(this, fork)

    this._reorgs.push(f)

    // maintain sorted by fork
    let i = this._reorgs.length - 1
    while (i > 0 && this._reorgs[i - 1].fork > fork) {
      this._reorgs[i] = this._reorgs[i - 1]
      this._reorgs[--i] = f
    }

    return f
  }

  _shouldUpgrade(peer) {
    if (this._upgrade !== null && this._upgrade.inflight.length > 0) return false
    return (
      peer.remoteCanUpgrade === true &&
      peer.remoteLength > this.core.state.length &&
      peer.lengthAcked === this.core.state.length
    )
  }

  _autoUpgrade(peer) {
    return (
      this._upgrade !== null &&
      peer.remoteFork === this.core.state.fork &&
      this._shouldUpgrade(peer)
    )
  }

  _addPeer(peer) {
    this._hadPeers = true
    this.peers.push(peer)
    this.updatePeer(peer)
    this._onpeerupdate(true, peer)
  }

  _requestDone(id, roundtrip) {
    this._inflight.remove(id, roundtrip)
    if (this.isDownloading() === true) return
    for (const peer of this.peers) peer.signalUpgrade()
  }

  _removePeer(peer) {
    this.peers.splice(this.peers.indexOf(peer), 1)
    peer.wants.destroy()

    if (this._manifestPeer === peer) this._manifestPeer = null

    let inflight = false
    for (const req of this._inflight) {
      if (req.peer !== peer) continue
      inflight = true
      this._inflight.remove(req.id, true)
      this._clearRequest(peer, req)
    }

    this._onpeerupdate(false, peer)
    if (inflight) {
      this.queueUpdateAll()
    } else {
      this._checkUpgradeIfAvailable()
    }
  }

  _queueBlock(b) {
    if (b.inflight.length > 0 || b.queued === true) return
    b.queued = true
    this._queued.push(b)
  }

  _resolveHashLocally(peer, req) {
    this._requestDone(req.id, false)
    this._resolveBlockRequest(this._hashes, req.hash.index / 2, null, req)
    this.updatePeer(peer)
  }

  // Runs in the background - not allowed to throw
  async _resolveBlocksLocally() {
    // TODO: check if fork compat etc. Requires that we pass down truncation info

    const clear = []
    const blocks = []

    const reader = this.core.storage.read()
    for (const b of this._blocks) {
      if (this.core.bitfield.get(b.index) === false) continue
      blocks.push(this._resolveLocalBlock(b, reader, clear))
    }
    reader.tryFlush()

    await Promise.all(blocks)

    if (!clear.length) return

    // Currently the block tracker does not support deletes during iteration, so we make
    // sure to clear them afterwards.
    for (const b of clear) {
      this._blocks.remove(b.index)
      removeHotswap(b)
    }
  }

  async _resolveLocalBlock(b, reader, resolved) {
    try {
      b.resolve(await reader.getBlock(b.index))
    } catch (err) {
      b.reject(err)
      return
    }

    resolved.push(b)
  }

  _resolveBlockRequest(tracker, index, value, req) {
    const b = tracker.remove(index)
    if (b === null) return false

    removeInflight(b.inflight, req)
    removeHotswap(b)
    b.queued = false

    b.resolve(value)

    if (b.inflight.length > 0) {
      // if anything is still inflight, cancel it
      for (let i = b.inflight.length - 1; i >= 0; i--) {
        const req = b.inflight[i]
        req.peer._cancelRequest(req)
      }
    }

    return true
  }

  _resolveUpgradeRequest(req) {
    if (req !== null) removeInflight(this._upgrade.inflight, req)

    if (
      this.core.state.length === this._upgrade.length &&
      this.core.state.fork === this._upgrade.fork
    ) {
      return false
    }

    const u = this._upgrade
    this._upgrade = null
    u.resolve(true)

    return true
  }

  _resolveRangeRequest(req) {
    req.resolve(true)
    req.gc()
  }

  _clearInflightBlock(tracker, req) {
    const isBlock = tracker === this._blocks
    const index = isBlock === true ? req.block.index : req.hash.index / 2
    const b = tracker.get(index)

    if (b === null || removeInflight(b.inflight, req) === false) return

    if (removeHotswap(b) === true && b.inflight.length > 0) {
      this.hotswaps.add(b)
    }

    if (b.refs.length > 0 && isBlock === true) {
      this._queueBlock(b)
      return
    }

    b.gc()
  }

  _clearInflightUpgrade(req) {
    if (this._upgrade === null || removeInflight(this._upgrade.inflight, req) === false) return
    this._upgrade.gc()
  }

  _clearInflightSeeks(req) {
    for (const s of this._seeks) {
      if (removeInflight(s.inflight, req) === false) continue
      s.gc()
    }
  }

  _clearInflightReorgs(req) {
    for (const r of this._reorgs) {
      removeInflight(r.inflight, req)
    }
  }

  _clearOldReorgs(fork) {
    for (let i = 0; i < this._reorgs.length; i++) {
      const f = this._reorgs[i]
      if (f.fork >= fork) continue
      if (i === this._reorgs.length - 1) this._reorgs.pop()
      else this._reorgs[i] = this._reorgs.pop()
      i--
    }
  }

  // "slow" updates here - async but not allowed to ever throw
  async _updateNonPrimary(updateAll) {
    // Check if running, if so skip it and the running one will issue another update for us (debounce)
    while (++this._updatesPending === 1) {
      let len = Math.min(MAX_RANGES, this._ranges.length)

      for (let i = 0; i < len; i++) {
        const r = this._ranges[i]

        clampRange(this.core, r)

        if (r.end !== -1 && r.start >= r.end) {
          this._resolveRangeRequest(r)
          i--
          if (len > this._ranges.length) len--
          if (this._ranges.length === MAX_RANGES) updateAll = true
        }
      }

      for (let i = 0; i < this._seeks.length; i++) {
        const s = this._seeks[i]

        let err = null
        let res = null

        try {
          res = await s.seeker.update()
        } catch (error) {
          err = error
        }

        if (!res && !err) continue

        if (i < this._seeks.length - 1) this._seeks[i] = this._seeks.pop()
        else this._seeks.pop()

        i--

        if (err) s.reject(err)
        else s.resolve(res)
      }

      // No additional updates scheduled - break
      if (--this._updatesPending === 0) break
      // Debounce the additional updates - continue
      this._updatesPending = 0
    }

    if (this._inflight.idle || updateAll) this.queueUpdateAll()
  }

  _clearRequest(peer, req) {
    if (req.block !== null) {
      this._clearInflightBlock(this._blocks, req)
      this._unmarkInflight(req.block.index)
    }

    if (req.hash !== null) {
      this._clearInflightBlock(this._hashes, req)
    }

    if (req.upgrade !== null && this._upgrade !== null) {
      this._clearInflightUpgrade(req)
    }

    if (this._seeks.length > 0) {
      this._clearInflightSeeks(req)
    }

    if (this._reorgs.length > 0) {
      this._clearInflightReorgs(req)
    }
  }

  _onnodata(peer, req, reason) {
    if (reason === NOT_AVAILABLE) {
      peer.stats.notAvailableBackoffs++
      this.stats.notAvailableBackoffs++

      if (peer.stats.notAvailableBackoffs >= MAX_BACKOFFS) {
        peer.paused = true
      }
    }

    if (reason === INVALID_REQUEST) {
      peer.stats.backoffs++
      this.stats.backoffs++

      if (peer.stats.backoffs >= MAX_BACKOFFS) {
        peer.paused = true
      }
    }

    if (req) {
      this._clearRequest(peer, req)
    }

    this.queueUpdateAll()
  }

  _openSkipBitfield() {
    // technically the skip bitfield gets bits cleared if .clear() is called
    // also which might be in inflight also, but that just results in that section being overcalled shortly
    // worst case, so ok for now

    const bitfield = this.core.openSkipBitfield()

    for (const req of this._inflight) {
      if (req.block) bitfield.set(req.block.index, true) // skip
    }
  }

  _markProcessing(index) {
    const b = this._blocks.get(index)
    if (b) {
      b.processing = true
      return
    }

    const h = this._hashes.get(index)
    if (h) h.processing = true
  }

  _markProcessed(index) {
    const b = this._blocks.get(index)
    if (b) return b.processed()

    const h = this._hashes.get(index)
    if (h) h.processed()
  }

  _markInflight(index) {
    if (this.core.skipBitfield !== null) this.core.skipBitfield.set(index, true)
    for (const peer of this.peers) peer._markInflight(index)
  }

  _unmarkInflight(index) {
    if (this.core.skipBitfield !== null) {
      this.core.skipBitfield.set(index, this.core.bitfield.get(index))
    }
    for (const peer of this.peers) peer._resetMissingBlock(index)
  }

  _ondata(peer, req, data) {
    if (req) {
      req.elapsed = Date.now() - req.timestamp
    }

    if (data.block !== null) {
      this._resolveBlockRequest(this._blocks, data.block.index, data.block.value, req)
      this._ondownload(data.block.index, data.block.value.byteLength, peer, req)
    }

    if (data.hash !== null && (data.hash.index & 1) === 0) {
      this._resolveBlockRequest(this._hashes, data.hash.index / 2, null, req)
    }

    if (this._upgrade !== null) {
      this._resolveUpgradeRequest(req)
    }

    if (this._seeks.length > 0) {
      this._clearInflightSeeks(req)
    }

    if (this._reorgs.length > 0) {
      this._clearInflightReorgs(req)
    }

    if (this._manifestPeer === peer && this.core.header.manifest !== null) {
      this._manifestPeer = null
    }

    if (this._seeks.length > 0 || this._ranges.length > 0) {
      this._updateNonPrimary(this._seeks.length > 0)
    }

    this.updatePeer(peer)
  }

  _onwant(peer, start, length, any) {
    if (!peer.isActive()) return

    const contig = Math.min(this.core.state.length, this.core.header.hints.contiguousLength)

    if (start + length < contig || this.core.state.length === contig || (any && start < contig)) {
      peer.wireRange.send({
        drop: false,
        start: 0,
        length: contig
      })
      incrementTx(peer.stats.wireRange, this.stats.wireRange)
      return
    }

    length = Math.min(length, this.core.state.length - start)

    if (any) {
      const bit = this.core.bitfield.firstSet(start)
      if (bit > -1 && bit < start + length) {
        peer.wireRange.send({
          drop: false,
          start: bit,
          length: 1
        })
      }
      return
    }

    for (const msg of this.core.bitfield.want(start, length)) {
      peer.wireBitfield.send(msg)
      incrementTx(peer.stats.wireBitfield, this.stats.wireBitfield)
    }
  }

  async _onreorgdata(peer, req, data) {
    const newBatch = data.upgrade && (await this.core.verifyReorg(data))
    const f = this._addReorg(data.fork, peer)

    if (f === null) {
      this.queueUpdateAll()
      return
    }

    removeInflight(f.inflight, req)

    if (f.batch) {
      await f.batch.update(data)
    } else if (data.upgrade) {
      f.batch = newBatch

      // Remove "older" reorgs in progress as we just verified this one.
      this._clearOldReorgs(f.fork)
    }

    if (f.batch && f.batch.finished) {
      if (this._addUpgradeMaybe() !== null) {
        await this._applyReorg(f)
      }
    }

    this.queueUpdateAll()
  }

  // Never throws, allowed to run in the background
  async _applyReorg(f) {
    // TODO: more optimal here to check if potentially a better reorg
    // is available, ie higher fork, and request that one first.
    // This will request that one after this finishes, which is fine, but we
    // should investigate the complexity in going the other way

    const u = this._upgrade
    const old = this._reorgs

    this._reorgs = [] // clear all as the nodes are against the old tree - easier
    this._applyingReorg = this.core.reorg(f.batch, null) // TODO: null should be the first/last peer?

    try {
      await this._applyingReorg
    } catch (err) {
      this._upgrade = null
      u.reject(err)
    }

    this._applyingReorg = null

    if (this._upgrade !== null) {
      this._resolveUpgradeRequest(null)
    }

    for (const peer of this.peers) this._updateFork(peer)

    // TODO: all the remaining is a tmp workaround until we have a flag/way for ANY_FORK
    for (const r of this._ranges) {
      r.start = r.userStart
      r.end = r.userEnd
    }

    for (const f of old) f.resolve()
    f.resolve()

    this.queueUpdateAll()
  }

  _maybeUpdate() {
    return this._upgrade !== null && this._upgrade.inflight.length === 0
  }

  _maybeRequestManifest() {
    return this.core.header.manifest === null && this._manifestPeer === null
  }

  _updateFork(peer) {
    if (
      this._applyingReorg !== null ||
      this.allowFork === false ||
      peer.remoteFork <= this.core.state.fork
    ) {
      return false
    }

    const f = this._addReorg(peer.remoteFork, peer)

    // TODO: one per peer is better
    if (f !== null && f.batch === null && f.inflight.length === 0) {
      return peer._requestForkProof(f)
    }

    return false
  }

  _updateHotswap(peer) {
    const maxHotswaps = peer.getMaxHotswapInflight()
    if (!peer.isActive() || peer.inflight >= maxHotswaps) return

    for (const b of this.hotswaps.pick(peer)) {
      if (peer._requestBlock(b) === false) continue
      peer.stats.hotswaps++
      peer.replicator.stats.hotswaps++
      if (peer.inflight >= maxHotswaps) break
    }
  }

  _updatePeer(peer) {
    if (!peer.isActive() || peer.inflight >= peer.getMaxInflight() || !peer.remoteUploading) {
      return false
    }

    // Eagerly request the manifest even if the remote length is 0. If not 0 we'll get as part of the upgrade request...
    if (
      this._maybeRequestManifest() === true &&
      peer.remoteLength === 0 &&
      peer.remoteHasManifest === true
    ) {
      this._manifestPeer = peer
      peer._requestManifest()
    }

    for (const s of this._seeks) {
      if (s.inflight.length > 0) continue // TODO: one per peer is better
      if (peer._requestSeek(s) === true) {
        return true
      }
    }

    // Implied that any block in the queue should be requested, no matter how many inflights
    const blks = new RandomIterator(this._queued)

    for (const b of blks) {
      if (b.queued === false || peer._requestBlock(b) === true) {
        b.queued = false
        blks.dequeue()
        return true
      }
    }

    return false
  }

  _updatePeerNonPrimary(peer) {
    if (!peer.isActive() || peer.inflight >= peer.getMaxInflight() || !peer.remoteUploading) {
      return false
    }

    const ranges = new RandomIterator(this._ranges)
    let tried = 0

    for (const r of ranges) {
      if (peer._requestRange(r) === true) {
        return true
      }
      if (++tried >= MAX_RANGES) break
    }

    // Iterate from newest fork to oldest fork...
    for (let i = this._reorgs.length - 1; i >= 0; i--) {
      const f = this._reorgs[i]
      if (f.batch !== null && f.inflight.length === 0 && peer._requestForkRange(f) === true) {
        return true
      }
    }

    if (this._maybeUpdate() === true && peer._requestUpgrade(this._upgrade) === true) {
      return true
    }

    return false
  }

  updatePeer(peer) {
    // Quick shortcut to wait for flushing reorgs - not needed but less waisted requests
    if (this._applyingReorg !== null) return

    while (this._updatePeer(peer) === true);
    while (this._updatePeerNonPrimary(peer) === true);

    if (this.peers.length > 1 && this._blocks.isEmpty() === false) {
      this._updateHotswap(peer)
    }

    this._checkUpgradeIfAvailable()
  }

  updateSubset() {
    return this.updateAll(false)
  }

  updateAll(all = true) {
    // Clear queued scan if a full scan
    if (this._updateAllBump !== null && all) {
      clearTimeout(this._updateAllBump)
      this._updateAllBump = null
    }

    // Quick shortcut to wait for flushing reorgs - not needed but less waisted requests
    if (this._applyingReorg !== null) return

    const peers = new RandomIterator(this.peers)

    const limit = all ? peers.length : MIN_PEER_UPDATE_ALL
    let tried = 0
    for (const peer of peers) {
      tried++
      if (this._updatePeer(peer) === true) {
        peers.requeue()
      }
      if (tried >= limit) break
    }

    // Check if we can skip the non primary check fully
    if (this._maybeUpdate() === false && this._ranges.length === 0 && this._reorgs.length === 0) {
      this._checkUpgradeIfAvailable()
      return
    }

    tried = 0
    for (const peer of peers.restart()) {
      tried++
      if (this._updatePeerNonPrimary(peer) === true) {
        peers.requeue()
      }
      if (tried >= limit) break
    }

    this._checkUpgradeIfAvailable()
  }

  getUpdateAllDelay(peers) {
    return Math.min(3000, Math.max(100, (peers.length - MIN_PEER_UPDATE_ALL) * 5))
  }

  queueUpdateAll() {
    if (this.peers.length < MIN_PEER_UPDATE_ALL) return this.updateAll()

    // Immediately scan subset
    this.updateSubset()

    // Schedule full scan
    if (this._updateAllBump !== null) return //skip if already scheduled
    this._updateAllBump = setTimeout(this._updateAllBound, this.getUpdateAllDelay(this.peers))
  }

  onpeerdestroy() {
    if (--this._active === 0) this.core.checkIfIdle()
  }

  attached(protomux) {
    return this._attached.has(protomux)
  }

  attachTo(protomux) {
    if (this.core.closed) return

    const makePeer = this._makePeer.bind(this, protomux)

    this._attached.add(protomux)
    protomux.pair({ protocol: 'hypercore/alpha', id: this.core.discoveryKey }, makePeer)
    protomux.stream.setMaxListeners(0)
    protomux.stream.on('close', this._onstreamclose)

    this._ifAvailable++
    this._active++

    protomux.stream.opened.then((opened) => {
      this._ifAvailable--
      this._active--

      if (opened && !this.destroyed) makePeer()
      this._checkUpgradeIfAvailable()

      this.core.checkIfIdle()
    })
  }

  detachFrom(protomux) {
    if (this._attached.delete(protomux)) {
      protomux.stream.removeListener('close', this._onstreamclose)
      protomux.unpair({ protocol: 'hypercore/alpha', id: this.core.discoveryKey })
    }
  }

  idle() {
    return this.peers.length === 0 && this._active === 0
  }

  close() {
    const waiting = []

    for (const peer of this.peers) {
      waiting.push(peer.channel.fullyClosed())
    }

    this.destroy()
    return Promise.all(waiting)
  }

  destroy() {
    if (this.destroyed) return
    this.destroyed = true

    if (this._notDownloadingTimer) {
      clearTimeout(this._notDownloadingTimer)
      this._notDownloadingTimer = null
    }

    if (this._updateAllBump) {
      clearTimeout(this._updateAllBump)
      this._updateAllBump = null
    }

    while (this.peers.length) {
      const peer = this.peers[this.peers.length - 1]
      this.detachFrom(peer.protomux)
      peer.channel.close() // peer is removed from array in onclose
    }

    for (const protomux of this._attached) {
      this.detachFrom(protomux)
    }
  }

  _makePeer(protomux) {
    const replicator = this
    if (protomux.opened({ protocol: 'hypercore/alpha', id: this.core.discoveryKey })) {
      return onnochannel()
    }

    const channel = protomux.createChannel({
      userData: null,
      protocol: 'hypercore/alpha',
      aliases: ['hypercore'],
      id: this.core.discoveryKey,
      handshake: m.wire.handshake,
      messages: [
        { encoding: m.wire.sync, onmessage: onwiresync },
        { encoding: m.wire.request, onmessage: onwirerequest },
        { encoding: m.wire.cancel, onmessage: onwirecancel },
        { encoding: m.wire.data, onmessage: onwiredata },
        { encoding: m.wire.noData, onmessage: onwirenodata },
        { encoding: m.wire.want, onmessage: onwirewant },
        { encoding: m.wire.unwant, onmessage: onwireunwant },
        { encoding: m.wire.bitfield, onmessage: onwirebitfield },
        { encoding: m.wire.range, onmessage: onwirerange },
        { encoding: m.wire.extension, onmessage: onwireextension }
      ],
      onopen: onwireopen,
      onclose: onwireclose,
      ondrain: onwiredrain,
      ondestroy: onwiredestroy
    })

    if (channel === null) return onnochannel()

    const peer = new Peer(replicator, protomux, channel, this.inflightRange)
    const stream = protomux.stream

    peer.channel.open({
      seeks: true,
      capability: caps.replicate(stream.isInitiator, this.core.key, stream.handshakeHash)
    })

    return true

    function onnochannel() {
      return false
    }
  }

  _onpeerupdate(added, peer) {
    const name = added ? 'peer-add' : 'peer-remove'
    const sessions = this.core.monitors

    for (let i = sessions.length - 1; i >= 0; i--) {
      sessions[i].emit(name, peer)

      if (added) {
        for (const ext of sessions[i].extensions.values()) {
          peer.extensions.set(ext.name, ext)
        }
      }
    }
  }

  _ondownload(index, byteLength, from, req) {
    const sessions = this.core.monitors

    for (let i = sessions.length - 1; i >= 0; i--) {
      const s = sessions[i]
      s.emit('download', index, byteLength - s.padding, from, req)
    }
  }

  _onupload(index, byteLength, from) {
    const sessions = this.core.monitors

    for (let i = sessions.length - 1; i >= 0; i--) {
      const s = sessions[i]
      s.emit('upload', index, byteLength - s.padding, from)
    }
  }

  _oninvaliddata(err, req, res, from) {
    const sessions = this.core.monitors

    this.stats.invalidData++
    from.stats.invalidData++
    for (let i = 0; i < sessions.length; i++) {
      sessions[i].emit('verification-error', err, req, res, from)
    }
  }

  _oninvalidrequest(err, req, from) {
    const sessions = this.core.monitors

    from.stats.invalidRequests++
    this.stats.invalidRequests++
    for (let i = 0; i < sessions.length; i++) {
      sessions[i].emit('invalid-request', err, req, from)
    }
  }
}

function removeHotswap(block) {
  if (block.hotswap === null) return false
  block.hotswap.ref.remove(block)
  return true
}

function removeInflight(inf, req) {
  const i = inf.indexOf(req)
  if (i === -1) return false
  if (i < inf.length - 1) inf[i] = inf.pop()
  else inf.pop()
  return true
}

function toLength(start, end) {
  return end === -1 ? -1 : end < start ? 0 : end - start
}

function clampRange(core, r) {
  if (r.blocks === null) {
    const start = core.bitfield.firstUnset(r.start)

    if (r.end === -1) r.start = start === -1 ? core.state.length : start
    else if (start === -1 || start >= r.end) r.start = r.end
    else {
      r.start = start

      const end = core.bitfield.lastUnset(r.end - 1)

      if (end === -1 || start >= end + 1) r.end = r.start
      else r.end = end + 1
    }
  } else {
    while (r.start < r.end && core.bitfield.get(r.blocks[r.start])) r.start++
    while (r.start < r.end && core.bitfield.get(r.blocks[r.end - 1])) r.end--
  }
}

function onrequesttimeout(req) {
  if (req.context) req.context.detach(req, REQUEST_TIMEOUT())
}

function destroyRequestTimeout(req) {
  if (req.timeout !== null) {
    clearTimeout(req.timeout)
    req.timeout = null
  }
}

function isCriticalError(err) {
  // TODO: expose .critical or similar on the hypercore errors that are critical (if all not are)
  return err.name === 'HypercoreError'
}

function onwireopen(m, c) {
  return c.userData.onopen(m)
}

function onwireclose(isRemote, c) {
  return c.userData.onclose(isRemote)
}

function onwiredestroy(c) {
  c.userData.replicator.onpeerdestroy()
}

function onwiredrain(c) {
  return c.userData.ondrain()
}

function onwiresync(m, c) {
  incrementRx(c.userData.stats.wireSync, c.userData.replicator.stats.wireSync)
  return c.userData.onsync(m)
}

function onwirerequest(m, c) {
  incrementRx(c.userData.stats.wireRequest, c.userData.replicator.stats.wireRequest)
  return c.userData.onrequest(m)
}

function onwirecancel(m, c) {
  incrementRx(c.userData.stats.wireCancel, c.userData.replicator.stats.wireCancel)
  return c.userData.oncancel(m)
}

function onwiredata(m, c) {
  incrementRx(c.userData.stats.wireData, c.userData.replicator.stats.wireData)
  return c.userData.ondata(m)
}

function onwirenodata(m, c) {
  return c.userData.onnodata(m)
}

function onwirewant(m, c) {
  incrementRx(c.userData.stats.wireWant, c.userData.replicator.stats.wireWant)
  return c.userData.onwant(m)
}

function onwireunwant(m, c) {
  return c.userData.onunwant(m)
}

function onwirebitfield(m, c) {
  incrementRx(c.userData.stats.wireBitfield, c.userData.replicator.stats.wireBitfield)
  return c.userData.onbitfield(m)
}

function onwirerange(m, c) {
  incrementRx(c.userData.stats.wireRange, c.userData.replicator.stats.wireRange)
  return c.userData.onrange(m)
}

function onwireextension(m, c) {
  incrementRx(c.userData.stats.wireExtension, c.userData.replicator.stats.wireExtension)
  return c.userData.onextension(m)
}

function setNotDownloadingLater(repl, session) {
  repl._setDownloadingNow(false, session)
}

function isBlockRequest(req) {
  return req !== null && req.block !== null
}

function isUpgradeRequest(req) {
  return req !== null && req.upgrade !== null
}

function incrementTx(stats1, stats2) {
  stats1.tx++
  stats2.tx++
}

function incrementRx(stats1, stats2) {
  stats1.rx++
  stats2.rx++
}

function noop() {}

function backoff(times) {
  const sleep = times < 2 ? 200 : times < 5 ? 500 : times < 40 ? 1000 : 5000
  return new Promise((resolve) => setTimeout(resolve, sleep))
}
const crypto = require('hypercore-crypto')
const b4a = require('b4a')
const assert = require('nanoassert')
const flat = require('flat-tree')
const quickbit = require('quickbit-universal')
const HypercoreStorage = require('hypercore-storage')

const {
  INVALID_OPERATION,
  INVALID_SIGNATURE,
  ASSERTION,
  SESSION_CLOSED,
  SESSION_NOT_WRITABLE
} = require('hypercore-errors')

const Mutex = require('./mutex')
const Bitfield = require('./bitfield')
const { MerkleTree, MerkleTreeBatch } = require('./merkle-tree')

class SessionState {
  constructor(core, parent, storage, treeInfo, name) {
    this.core = core
    this.index = this.core.sessionStates.push(this) - 1

    this.storage = storage
    this.name = name
    this.sessions = []

    // small hack to close old storages as late as possible.
    // TODO: add a read lock so we can avoid that
    this.lingers = null

    this.parent = parent
    this.atomized = null
    this.mutex = new Mutex()

    // merkle state
    this.roots = treeInfo.roots.length ? treeInfo.roots : []
    this.fork = treeInfo.fork || 0
    this.length = this.roots.length ? MerkleTree.span(this.roots) / 2 : treeInfo.length
    this.byteLength = MerkleTree.size(this.roots)
    this.prologue = treeInfo.prologue || null
    this.signature = treeInfo.signature || null

    this.snapshotCompatLength = this.isSnapshot()
      ? Math.min(this.length, this.core.state.length)
      : -1
    this.lastTruncation = null
    this.groupUpdated = false

    this.active = 0

    this._activeTx = null
    this._pendingBitfield = null

    this.ref()
  }

  static RECOVERY_PEERS = null

  isSnapshot() {
    return this.storage.snapshotted
  }

  isDefault() {
    return this.core.state === this || this.isAtomicDefault()
  }

  isAtomicDefault() {
    return !!this.storage.atom && !!this.parent && this.parent.isDefault()
  }

  createTreeBatch() {
    return new MerkleTreeBatch(this)
  }

  addSession(s) {
    if (s._stateIndex !== -1) return
    s._stateIndex = this.sessions.push(s) - 1
    if (s.weak === false) this.core.activeSessions++
  }

  removeSession(s) {
    if (s._stateIndex === -1) return
    const head = this.sessions.pop()
    if (head !== s) this.sessions[(head._stateIndex = s._stateIndex)] = head
    s._stateIndex = -1
    if (s.weak === false) this.core.activeSessions--
    this.core.checkIfIdle()
  }

  flushedLength() {
    if (this.isDefault() || this.isSnapshot()) return this.length
    const deps = this.storage.dependencies
    if (deps.length) return deps[deps.length - 1].length
    return 0
  }

  signedLength() {
    const l = Math.min(this.flushedLength(), this.core.state.length)
    return this.isSnapshot() && l > this.snapshotCompatLength ? this.snapshotCompatLength : l
  }

  unref() {
    if (--this.active > 0) return
    this.close().catch(noop) // technically async, but only for the last db session
  }

  ref() {
    this.active++
    return this
  }

  hash() {
    return MerkleTree.hash(this)
  }

  setRoots(roots) {
    this.roots = roots
    this.length = MerkleTree.span(roots) / 2
    this.byteLength = MerkleTree.size(roots)
  }

  get encryptionFork() {
    return this.core.header.tree.fork
  }

  async _updateSnapshotStorage(storage) {
    if (!this.atomized || !this.atomized.flushing) return this.treeInfo()
    while (this.atomized.flushing) await this.atomized.flushed()

    let rx = storage.read()
    const headPromise = rx.getHead()
    const authPromise = rx.getAuth()
    const depPromise = rx.getDependency()

    rx.tryFlush()
    const [head, auth, dep] = await Promise.all([headPromise, authPromise, depPromise])

    storage.setDependencyHead(dep)

    const fork = head ? head.fork : 0
    const length = head ? head.length : 0

    rx = storage.read()
    const rootPromises = []
    for (const r of flat.fullRoots(length * 2)) {
      rootPromises.push(rx.getTreeNode(r))
    }

    rx.tryFlush()

    const roots = await Promise.all(rootPromises)

    // dbl check if we are hitting an regression from earler
    for (const root of roots) {
      if (root === null) {
        throw new Error(
          'Bad snapshot from atomized session, id = ' +
            this.core.id +
            ' length = ' +
            length +
            ' fork = ' +
            fork
        )
      }
    }

    return {
      fork,
      roots,
      length,
      prologue: auth.manifest && auth.manifest.prologue,
      signature: head && head.signature
    }
  }

  treeInfo() {
    return {
      fork: this.fork,
      roots: this.roots.slice(),
      length: this.length,
      prologue: this.prologue,
      signature: this.signature
    }
  }

  async close() {
    if (this.index === -1) return

    this.active = 0
    this.mutex.destroy(new Error('Closed')).catch(noop)
    if (this.parent && this.parent.atomized) this.parent.atomized = null

    const closing = this.storage.close()

    const head = this.core.sessionStates.pop()
    if (head !== this) this.core.sessionStates[(head.index = this.index)] = head

    this.index = -1
    this.core.checkIfIdle()

    if (this.lingers !== null) {
      for (const storage of this.lingers) await storage.close()
    }

    return closing
  }

  async snapshot() {
    const storage = this.storage.snapshot()
    const treeInfo = await this._updateSnapshotStorage(storage)

    return new SessionState(this.core, null, storage, treeInfo, this.name)
  }

  updateDependency(tx, length) {
    const dependency = updateDependency(this, length, false)
    if (dependency) tx.setDependency(dependency)
    return dependency
  }

  updateGroupIndex(tx, tree) {
    const { pointer } = this.core.header.group

    tx.deleteGroupUpdate(pointer, this.core.header.tree.timestamp)
    tx.putGroupUpdate(pointer, tree.timestamp, this.core.header.key)

    this.groupUpdated = true
  }

  _clearActiveBatch() {
    this._activeTx = null
  }

  createWriteBatch() {
    assert(!this._activeTx && !this.storage.snapshotted)

    this._activeTx = this.storage.write()
    return this._activeTx
  }

  _unlock() {
    this._clearActiveBatch()
    this.mutex.unlock()
    this.core.checkIfIdle()
  }

  _flushHooks() {
    if (!this.groupUpdated) return
    this.groupUpdated = false
    this.core.ongroupupdate(this.core.header.group.key, {
      key: this.core.key,
      length: this.length,
      fork: this.fork
    })
  }

  async flush() {
    const tx = this._activeTx
    this._activeTx = null

    try {
      if (!(await tx.flush())) return false
    } finally {
      this._clearActiveBatch()
    }

    this.lastTruncation = null
    return true
  }

  _precommit(state) {
    assert(
      state.parent === this && state.storage.core.dataPointer === this.storage.core.dataPointer,
      'Atomic state must flush to parent'
    )
  }

  async _commit() {
    await this.mutex.lock()

    try {
      const bitfield = this._pendingBitfield
      this._pendingBitfield = null
      this.lastTruncation = null
      await this.parent._oncommit(this, bitfield)
    } finally {
      this.mutex.unlock()
    }
  }

  async _oncommit(src, bitfield) {
    await this.mutex.lock()

    try {
      const currLength = this.length

      // load dependency into memory
      const rx = this.storage.read()
      const dependencyPromise = rx.getDependency()

      rx.tryFlush()

      const dependency = await dependencyPromise

      this.fork = src.fork
      this.length = src.length
      this.byteLength = src.byteLength
      this.roots = src.roots.slice()
      this.signature = src.signature

      const tree = {
        fork: this.fork,
        length: this.length,
        rootHash: this.hash(),
        signature: this.signature,
        timestamp: Date.now()
      }

      if (this.isDefault() && this.core.header.group) {
        const tx = this.createWriteBatch()
        this.updateGroupIndex(tx, tree)
        await this.flush()
        this._flushHooks()
      }

      if (dependency) this.storage.setDependencyHead(dependency)

      const b = bitfield

      if (b && b.truncated && b.start < currLength) {
        this.ontruncate(tree, b.start, currLength, true)
        if (!b || b.appends === 0) return
      }

      const append = b ? { start: b.start, length: b.appends, drop: false } : null

      this.onappend(tree, append, true)

      if (this.core.hintsChanged && this.isDefault()) await this.core.flushHints()
    } finally {
      this._unlock()
    }
  }

  async setUserData(key, value) {
    await this.mutex.lock()

    try {
      const tx = this.createWriteBatch()
      tx.putUserData(key, value)

      return await this.flush()
    } finally {
      this._unlock()
    }
  }

  async _verifyBlock(batch, bitfield, value, manifest, from) {
    await this.mutex.lock()

    try {
      if (batch.upgraded && batch.length <= this.length) {
        await batch.downgrade()
      }

      if (!batch.commitable()) {
        return false
      }

      if (this.core.preupdate !== null) {
        await this.core.preupdate(batch, this.core.header.key)
      }

      const tx = this.createWriteBatch()

      if (bitfield) {
        tx.putBlock(bitfield.start, value)
      }

      if (bitfield && this.isDefault()) {
        await storeBitfieldRange(this.storage, tx, bitfield.start, bitfield.start + 1, true)
      }

      if (manifest) this.core._setManifest(tx, manifest, null)

      assert(batch.commitable(), 'Should still be commitable')
      batch.commit(tx)

      const head = {
        fork: batch.fork,
        length: batch.length,
        rootHash: batch.hash(),
        signature: batch.signature,
        timestamp: Date.now()
      }

      if (batch.upgraded) {
        tx.setHead(head)

        if (this.core.header.group) {
          this.updateGroupIndex(tx, head)
        }
      }

      const flushed = await this.flush()

      if (batch.upgraded) {
        this.roots = batch.roots
        this.length = batch.length
        this.byteLength = batch.byteLength
        this.fork = batch.fork
        this.signature = batch.signature

        this.onappend(head, bitfield, flushed)
      }

      if (this.core.hintsChanged && this.isDefault()) await this.core.flushHints()
    } finally {
      this._unlock()
    }

    return true
  }

  async truncate(length, fork, { signature, keyPair } = {}) {
    if (!keyPair && this.isDefault()) keyPair = this.core.header.keyPair

    await this.mutex.lock()

    try {
      if (this.prologue && length < this.prologue.length) {
        throw INVALID_OPERATION('Truncation breaks prologue', this.core.discoveryKey)
      }
      if (length > this.length) {
        throw INVALID_OPERATION(
          'Not a truncation, ' + length + ' must be less or equal to ' + this.length,
          this.core.discoveryKey
        )
      }

      const batch = this.createTreeBatch()
      await MerkleTree.truncate(this, length, batch, fork)

      if (signature) {
        batch.signature = signature
        this.core._verifyBatchUpgrade(batch)
      } else if (keyPair) {
        batch.signature = this.core.verifier.sign(batch, keyPair)
      }

      const tx = this.createWriteBatch()

      // upsert compat manifest
      if (this.core.verifier === null && keyPair) this.core._setManifest(tx, null, keyPair)

      const { dependency, tree, roots } = await this._truncate(tx, batch)

      for (const sessionState of this.core.sessionStates) {
        if (
          sessionState.isSnapshot() &&
          sessionState.name === this.name &&
          length < sessionState.snapshotCompatLength
        ) {
          sessionState.snapshotCompatLength = length
        }
      }

      const flushed = await this.flush()

      this.fork = tree.fork
      this.length = tree.length
      this.byteLength = MerkleTree.size(roots)
      this.roots = roots
      this.signature = tree.signature

      if (dependency) this.storage.setDependencyHead(dependency)

      this.ontruncate(tree, tree.length, batch.treeLength, flushed)

      if (this.core.hintsChanged && this.isDefault()) await this.core.flushHints()
    } finally {
      this._unlock()
    }
  }

  async reorg(batch) {
    await this.mutex.lock()

    const storage = this.createWriteBatch()

    try {
      if (!batch.commitable()) return false

      const { dependency, tree } = await this._truncate(storage, batch)

      const flushed = await this.flush()

      this.fork = batch.fork
      this.length = batch.length
      this.byteLength = batch.byteLength
      this.roots = batch.roots
      this.signature = batch.signature

      if (dependency) this.storage.setDependencyHead(dependency)

      this.ontruncate(tree, batch.ancestors, batch.treeLength, flushed)

      if (this.core.hintsChanged && this.isDefault()) await this.core.flushHints()
    } finally {
      this._unlock()
    }
  }

  async _truncate(storage, batch) {
    storage.deleteBlockRange(batch.ancestors, batch.treeLength)

    assert(batch.commitable(), 'Batch must be commitable')

    const tree = {
      fork: batch.fork,
      length: batch.length,
      rootHash: batch.hash(),
      signature: batch.signature,
      timestamp: Date.now()
    }

    if (this.isDefault() && this.core.header.group) {
      this.updateGroupIndex(storage, tree)
    }

    storage.setHead(tree)
    batch.commit(storage)

    const truncated = batch.length < this.flushedLength()
    const dependency = truncated ? updateDependency(this, batch.length, true) : null

    if (dependency) storage.setDependency(dependency)

    if (this.isDefault()) {
      await storeBitfieldRange(this.storage, storage, batch.ancestors, batch.treeLength, false)
      if (batch.ancestors < this.core.header.hints.contiguousLength) {
        this.core.header.hints.remoteContiguousLength = Math.min(
          batch.length,
          this.core.header.hints.remoteContiguousLength
        )
        storage.setHints({
          contiguousLength: batch.ancestors,
          remoteContiguousLength: this.core.header.hints.remoteContiguousLength
        })
      }
    }

    return { dependency, tree, roots: batch.roots }
  }

  async clear(start, end, cleared) {
    await this.mutex.lock()

    try {
      const tx = this.createWriteBatch()

      const ite = flat.iterator(start * 2)
      while (!isRootIndex(ite.index, this.roots)) {
        const a = ite.index
        const b = ite.sibling()
        ite.parent()

        const [left, right] = flat.spans(b)
        const s = left / 2
        const e = right / 2 + 1
        const has = s <= start && e <= end ? false : this.core.bitfield.hasSet(s, e - s)
        if (has) break

        tx.deleteTreeNode(a)
        tx.deleteTreeNode(b)
      }

      if (this.isDefault()) {
        await storeBitfieldRange(this.storage, tx, start, end, false)
        if (start < this.core.header.hints.contiguousLength) {
          tx.setHints({
            contiguousLength: start,
            remoteContiguousLength: this.core.header.hints.remoteContiguousLength
          })
        }
      }

      if (end - start === 1) tx.deleteBlock(start)
      else tx.deleteBlockRange(start, end)

      const dependency = start < this.flushedLength() ? updateDependency(this, start, true) : null

      const flushed = await this.flush()

      if (dependency) this.storage.setDependencyHead(dependency)

      // todo: atomic event handle
      if (this.isDefault() && flushed) {
        const length = end - start

        this.core.updateContiguousLength({ start, length, drop: true })
        this.core._setBitfieldRanges(start, end, false)
        this.core.replicator.onhave(start, length, true)

        if (this.core.hintsChanged) await this.core.flushHints()
      }
    } finally {
      this._unlock()
    }
  }

  // simple tool to wait for other peers to catch us up
  async waitForRecovery() {
    const length = this.length
    const replicator = this.core.replicator

    while (!this.closing) {
      let peers = getRecoveryPeers(replicator.peers)

      if (peers.length < 1) {
        await new Promise((resolve) => setTimeout(resolve, 5000))
        continue
      }

      let restart = false

      for (let i = 0; i < 32; i++) {
        await new Promise((resolve) => setTimeout(resolve, 250))

        peers = getRecoveryPeers(replicator.peers)

        if (this.closing || !validateRecoveryPeers(peers, this.length)) {
          restart = true
          break
        }
      }

      if (restart) continue

      if (this.length !== length) {
        throw SESSION_NOT_WRITABLE('core recovered during append')
      }

      this.core.header.hints.recovering = 0
      this.core.hintsChanged = true

      await this.mutex.lock()
      try {
        await this.core.flushHints()
        return
      } finally {
        this.mutex.unlock()
      }
    }

    throw SESSION_CLOSED('Cannot recover a closed session', this.discoveryKey)
  }

  async append(values, { signature, keyPair, preappend, postappend, maxLength = -1 } = {}) {
    if (!keyPair && this.isDefault()) keyPair = this.core.header.keyPair

    if (this.isDefault() && this.core.header.hints.recovering) await this.waitForRecovery()

    await this.mutex.lock()

    try {
      if (maxLength >= 0 && this.length + values.length > maxLength) {
        return { length: this.length, byteLength: this.byteLength }
      }

      const tx = this.createWriteBatch()

      // upsert compat manifest
      if (this.core.verifier === null && keyPair) this.core._setManifest(tx, null, keyPair)

      if (preappend) await preappend(values)

      if (!values.length) {
        await this.flush()
        return { length: this.length, byteLength: this.byteLength }
      }

      const batch = this.createTreeBatch()
      for (const val of values) batch.append(val)

      // only multisig can have prologue so signature is always present
      if (this.prologue && batch.length < this.prologue.length) {
        throw INVALID_OPERATION('Append is not consistent with prologue', this.core.discoveryKey)
      }

      if (signature) {
        batch.signature = signature
        this.core._verifyBatchUpgrade(batch)
      } else if (keyPair) {
        batch.signature = this.core.verifier.sign(batch, keyPair)
      }

      batch.commit(tx)

      const tree = {
        fork: batch.fork,
        length: batch.length,
        rootHash: batch.hash(),
        signature: batch.signature,
        timestamp: Date.now()
      }

      tx.setHead(tree)

      if (this.isDefault()) {
        await storeBitfieldRange(this.storage, tx, batch.ancestors, batch.length, true)
        if (this.length === this.core.header.hints.contiguousLength) {
          tx.setHints({
            contiguousLength: this.length + values.length,
            remoteContiguousLength: this.core.header.hints.remoteContiguousLength
          })
        }

        if (this.core.header.group) {
          this.updateGroupIndex(tx, tree)
        }
      }

      for (let i = 0; i < values.length; i++) {
        tx.putBlock(this.length + i, values[i])
      }

      const bitfield = {
        drop: false,
        start: batch.ancestors,
        length: values.length
      }

      const flushed = await this.flush()

      this.fork = batch.fork
      this.roots = batch.roots
      this.length = batch.length
      this.byteLength = batch.byteLength
      this.signature = batch.signature

      if (postappend) await postappend(values)

      this.onappend(tree, bitfield, flushed)

      if (this.core.hintsChanged && this.isDefault()) await this.core.flushHints()

      return { length: this.length, byteLength: this.byteLength }
    } finally {
      this._unlock()
    }
  }

  onappend(tree, bitfield, flushed) {
    if (!flushed) this._updateBitfield(bitfield)
    else if (this.isDefault()) this.core.onappend(tree, bitfield)

    for (let i = this.sessions.length - 1; i >= 0; i--) {
      this.sessions[i].emit('append')
    }

    this._flushHooks()
  }

  ontruncate(tree, to, from, flushed) {
    const bitfield = { start: to, length: from - to, drop: true }

    this.lastTruncation = { from, to }

    if (!flushed) this._updateBitfield(bitfield)
    else if (this.isDefault()) this.core.ontruncate(tree, bitfield)

    for (const sessionState of this.core.sessionStates) {
      if (
        sessionState.isSnapshot() &&
        sessionState.name === this.name &&
        to < sessionState.snapshotCompatLength
      ) {
        sessionState.snapshotCompatLength = to
      }
    }

    for (let i = this.sessions.length - 1; i >= 0; i--) {
      this.sessions[i].emit('truncate', to, tree.fork)
    }

    this._flushHooks()
  }

  _updateBitfield(bitfield, flushed) {
    if (!bitfield) return

    const p = this._pendingBitfield
    const b = bitfield

    if (b.drop) {
      // truncation must be from end
      if (p && b.start + b.length !== p.start + p.appends) {
        throw INVALID_OPERATION('Atomic truncations must be contiguous', this.core.discoveryKey)
      }

      // actual truncation
      if (p === null || b.start < p.start) {
        this._pendingBitfield = { truncated: true, start: b.start, appends: 0 }
        return
      }

      // just clearing batch data
      p.appends = b.start - p.start

      // we cleared the current batch
      if (p.appends === 0) this._pendingBitfield = null

      return
    }

    if (p === null) {
      this._pendingBitfield = { truncated: false, start: b.start, appends: b.length }
      return
    }

    if (b.start !== p.start + p.appends) {
      throw INVALID_OPERATION('Atomic operations must be contiguous', this.core.discoveryKey)
    }

    p.appends += b.length
  }

  async catchup(length) {
    assert(!this.isDefault(), 'Cannot catchup signed state') // TODO: make this check better

    await this.mutex.lock()

    try {
      const origLength = this.length

      let sharedLength = 0
      for (let i = this.storage.dependencies.length - 1; i >= 0; i--) {
        const dep = this.storage.dependencies[i]
        if (dep.dataPointer === this.core.state.storage.core.dataPointer) {
          sharedLength = dep.length
          break
        }
      }

      const tx = this.createWriteBatch()
      const rx = this.core.state.storage.read()
      const rootPromises = []

      for (const root of flat.fullRoots(length * 2)) {
        rootPromises.push(rx.getTreeNode(root))
      }

      rx.tryFlush()

      const roots = await Promise.all(rootPromises)
      const truncating = sharedLength < origLength

      for (const node of roots) {
        if (node === null) {
          throw INVALID_OPERATION(
            'Invalid catchup length, tree nodes not available',
            this.core.discoveryKey
          )
        }
      }

      const fork = truncating ? this.fork + 1 : this.fork

      // overwrite it atm, TODO: keep what we can connect to the tree
      tx.deleteBlockRange(0, -1)
      tx.deleteTreeNodeRange(0, -1)
      tx.deleteBitfieldPageRange(0, -1)

      const tree = {
        fork,
        length,
        rootHash: crypto.tree(roots),
        signature: null,
        timestamp: Date.now()
      }

      // never default state so do not update group index
      tx.setHead(tree)

      // prop a better way to do this
      const dep = updateDependency(this, sharedLength, true)
      dep.length = length

      tx.setDependency(dep)

      const flushed = await this.flush()

      this.storage.setDependencyHead(dep)

      this.fork = tree.fork
      this.roots = roots
      this.length = tree.length
      this.byteLength = MerkleTree.size(roots)

      if (truncating) this.ontruncate(tree, sharedLength, origLength, flushed)
      if (sharedLength < length) this.onappend(tree, null, flushed)

      if (this.core.hintsChanged && this.isDefault()) await this.core.flushHints()
    } finally {
      this._unlock()
    }
  }

  async _overwrite(source, fork, length, treeLength, signature) {
    const blockPromises = []
    const treePromises = []
    const rootPromises = []

    const rx = source.storage.read()

    for (const root of flat.fullRoots(length * 2)) {
      rootPromises.push(rx.getTreeNode(root))
    }

    for (const index of flat.patch(treeLength * 2, length * 2)) {
      treePromises.push(rx.getTreeNode(index))
    }

    for (let i = treeLength; i < length; i++) {
      treePromises.push(rx.getTreeNode(i * 2))
      treePromises.push(rx.getTreeNode(i * 2 + 1))
      blockPromises.push(rx.getBlock(i))
    }

    rx.tryFlush()

    const [blocks, nodes, roots] = await Promise.all([
      Promise.all(blockPromises),
      Promise.all(treePromises),
      Promise.all(rootPromises)
    ])

    if (this.core.destroyed) throw new Error('Core destroyed')

    if (signature) {
      const batch = this.createTreeBatch()
      batch.roots = roots
      batch.length = length

      if (!this.core.verifier.verify(batch, signature)) {
        throw INVALID_SIGNATURE(
          'Signature is not valid over committed tree',
          this.core.discoveryKey
        )
      }
    }

    const tx = this.createWriteBatch()

    // truncate existing tree
    if (treeLength < this.length) {
      tx.deleteBlockRange(treeLength, this.length)
    }

    for (const root of roots) tx.putTreeNode(root)

    // no nodes will be copied in shallow mode
    for (const node of nodes) {
      if (node !== null) tx.putTreeNode(node)
    }

    for (let i = 0; i < blocks.length; i++) {
      assert(blocks[i] !== null, 'has block')
      tx.putBlock(i + treeLength, blocks[i])
    }

    const totalLength = Math.max(length, this.length)

    if (totalLength > treeLength) {
      const firstPage = getBitfieldPage(treeLength)
      const lastPage = getBitfieldPage(totalLength - 1)

      const srx = this.storage.read()
      const bitfieldPagePromise = srx.getBitfieldPage(firstPage)
      srx.tryFlush()

      const bitfieldPage = await bitfieldPagePromise

      let index = treeLength

      for (let i = firstPage; i <= lastPage; i++) {
        const page = b4a.alloc(Bitfield.BYTES_PER_PAGE)
        tx.putBitfieldPage(i, page)

        // copy existing bits in
        if (i === firstPage && bitfieldPage) page.set(bitfieldPage)

        if (index < length) {
          index = fillBitfieldPage(page, index, length, i, true)
          if (index < length) continue
        }

        if (index < this.length) {
          index = fillBitfieldPage(page, index, this.length, i, false)
        }
      }
    }

    const tree = {
      fork,
      length,
      rootHash: crypto.tree(roots),
      signature,
      timestamp: Date.now()
    }

    if (this.isDefault() && this.core.header.group) {
      this.updateGroupIndex(tx, tree)
    }

    const upgraded = treeLength < this.length || this.length < length || tree.fork !== this.fork

    if (upgraded) tx.setHead(tree)

    const flushed = await this.flush()

    this.fork = tree.fork
    this.roots = roots
    this.length = length
    this.byteLength = MerkleTree.size(roots)
    this.signature = signature

    return { tree, flushed }
  }

  static isParent(state, parent) {
    // atomic batches have parent set
    if (state.parent && state.parent === parent) return true

    return HypercoreStorage.isParentStorage(state.storage, parent.storage)
  }

  async commit(state, { signature, keyPair, length = state.length, treeLength = -1 } = {}) {
    assert(
      this.isDefault() || (this.parent && this.parent.isDefault()),
      'Can only commit into default state'
    )

    assert(SessionState.isParent(state, this), 'Cannot commit across cores')

    if (this.core._repairMode) {
      throw ASSERTION('Cannot commit while repair mode is on')
    }

    if (this.core.header.hints.recovering) await this.waitForRecovery()

    let srcLocked = false
    await this.mutex.lock()

    try {
      await state.mutex.lock()
      srcLocked = true

      if (treeLength === -1) treeLength = state.flushedLength()

      if (!(await this.core._validateCommit(state, treeLength))) return null
      if (this.length > length) return null

      if (this.length < length && !signature) {
        if (!keyPair) keyPair = this.core.header.keyPair
        const batch = state.createTreeBatch()
        if (length !== batch.length) await batch.restore(length)
        signature = this.core.verifier.sign(batch, keyPair)
      }

      const { tree, flushed } = await this._overwrite(
        state,
        this.fork,
        length,
        treeLength,
        signature
      )

      // gc blocks from source
      if (treeLength < length) {
        const tx = state.createWriteBatch()

        tx.deleteBlockRange(treeLength, length)
        const dependency = state.updateDependency(tx, length)

        await state.flush(tx)

        if (dependency) state.storage.setDependencyHead(dependency)
      }

      const bitfield = { start: treeLength, length: length - treeLength, drop: false }
      this.onappend(tree, bitfield, flushed)

      return {
        length: this.length,
        byteLength: this.byteLength
      }
    } finally {
      if (srcLocked) state._unlock()
      this._unlock()
    }
  }

  async _getTreeHeadAt(length) {
    if (length === null) return this.treeInfo()

    const head = getDefaultTree()

    head.length = length

    const roots = await MerkleTree.getRootsFromStorage(this.storage, length)
    const rootHash = crypto.tree(roots)

    head.fork = this.fork
    head.rootHash = rootHash

    if (length === this.length) head.signature = this.signature

    return head
  }

  _moveToCore(core, truncated, appended) {
    const head = this.core.sessionStates.pop()
    if (head !== this) this.core.sessionStates[(head.index = this.index)] = head

    this.core = core
    this.index = this.core.sessionStates.push(this) - 1

    for (let i = this.sessions.length - 1; i >= 0; i--) {
      const s = this.sessions[i]
      const manifest = s.manifest
      s.transferSession(this.core)
      if (!manifest && s.manifest) s.emit('manifest')
      if (truncated) s.emit('truncate', truncated.to, truncated.fork)
      if (appended) s.emit('append')
    }
  }

  async moveTo(core, length) {
    const state = core.state

    await this.mutex.lock()

    try {
      // if (state.storage && (await state.storage.resumeSession(this.name)) !== null) {
      //   throw STORAGE_CONFLICT('Batch has already been created')
      // }

      const treeLength = this.length

      let truncated = null
      let appended = false

      if (!this.isSnapshot()) {
        if (this.lingers === null) this.lingers = []
        this.lingers.push(this.storage)

        const resumed = await state.storage.resumeSession(this.name)

        const truncation = length < this.length ? await truncateAndFlush(this, length) : null
        const treeInfo = truncation
          ? truncation.tree
          : resumed
            ? null
            : await state._getTreeHeadAt(this.length)

        const fork = truncation ? this.fork + 1 : this.fork

        // todo: validate treeInfo

        let storage = null

        if (resumed) {
          storage = resumed
        } else {
          treeInfo.fork = fork
          storage = await state.storage.createSession(this.name, treeInfo)
        }

        const roots = await MerkleTree.getRootsFromStorage(storage, length)

        this.storage = storage
        this.prologue = state.prologue
        this.fork = fork
        this.length = length
        this.byteLength = MerkleTree.size(roots)
        this.roots = roots

        if (truncation) {
          const { dependency } = truncation

          if (dependency) this.storage.setDependencyHead(dependency)
          truncated = { to: treeLength, fork }
        }

        if (this.length > treeLength) {
          appended = true
        }
      }

      for (let i = this.core.sessionStates.length - 1; i >= 0; i--) {
        const state = this.core.sessionStates[i]
        if (state === this) continue
        if (state.name === this.name) state._moveToCore(core.core)
      }

      this._moveToCore(core.core, truncated, appended)
    } finally {
      this._unlock()
    }
  }

  async createSession(name, overwrite, atom) {
    await this.mutex.lock()

    try {
      let storage = null
      let treeInfo = null

      if (!atom && !overwrite && this.storage) {
        storage = await this.storage.resumeSession(name)

        if (storage !== null) treeInfo = (await getCoreHead(storage)) || getDefaultTree()
      }

      const length = treeInfo ? treeInfo.length : this.length

      if (storage === null) {
        treeInfo = await this._getTreeHeadAt(length)

        if (atom) {
          storage = await this.storage.createAtomicSession(atom, treeInfo)
        } else {
          storage = await this.storage.createSession(name, treeInfo)
        }
      }

      if (this.atomized && atom) {
        throw new Error('Session already atomized')
      }

      const head = {
        fork: this.fork,
        roots:
          length === this.length
            ? this.roots.slice()
            : await MerkleTree.getRootsFromStorage(storage, length),
        length,
        prologue: this.prologue,
        signature: length === this.length ? this.signature : null
      }

      const state = new SessionState(
        this.core,
        atom ? this : null,
        storage,
        head,
        atom ? this.name : name
      )

      if (atom) {
        this.atomized = atom
        atom.preflush(this._precommit.bind(this, state))
        atom.onflush(state._commit.bind(state))
      }

      return state
    } finally {
      this._unlock()
    }
  }
}

module.exports = SessionState

function noop() {}

function getBitfieldPage(index) {
  return Math.floor(index / Bitfield.BITS_PER_PAGE)
}

function fillBitfieldPage(page, start, end, pageIndex, value) {
  const offset = pageIndex * Bitfield.BITS_PER_PAGE
  const max = offset + Bitfield.BITS_PER_PAGE

  const index = max < end ? max : end

  const from = start - offset
  const to = index - offset

  quickbit.fill(page, value, from, to)

  return index
}

async function storeBitfieldRange(storage, tx, from, to, value) {
  if (from >= to) return

  const firstPage = getBitfieldPage(from)
  const lastPage = getBitfieldPage(to - 1)

  let index = from

  const rx = storage.read()

  const promises = []
  for (let i = firstPage; i <= lastPage; i++) {
    promises.push(rx.getBitfieldPage(i))
  }

  rx.tryFlush()

  const pages = await Promise.all(promises)
  const cnt = lastPage - firstPage + 1

  for (let i = 0; i < cnt; i++) {
    const pageIndex = i + firstPage
    if (!pages[i]) pages[i] = b4a.alloc(Bitfield.BYTES_PER_PAGE)

    index = fillBitfieldPage(pages[i], index, to, pageIndex, value)
    tx.putBitfieldPage(pageIndex, pages[i])
  }
}

async function truncateAndFlush(s, length) {
  const batch = s.createTreeBatch()
  await MerkleTree.truncate(s, length, batch, s.fork)
  const tx = s.createWriteBatch()

  const info = await s._truncate(tx, batch)
  const flushed = await s.flush()

  return {
    tree: info.tree,
    roots: info.roots,
    dependency: info.dependency,
    flushed
  }
}

function updateDependency(state, length, truncated) {
  const i = state.storage.findDependencyIndex(length, truncated)
  if (i === -1) return null // skip default state and overlays of default

  return {
    dataPointer: state.storage.dependencies[i].dataPointer,
    length
  }
}

function getDefaultTree() {
  return {
    fork: 0,
    length: 0,
    rootHash: null,
    signature: null
  }
}

function getCoreHead(storage) {
  const b = storage.read()
  const p = b.getHead()
  b.tryFlush()
  return p
}

function isRootIndex(index, roots) {
  for (const node of roots) {
    if (node.index === index) return true
  }

  return false
}

function getRecoveryPeers(peers) {
  if (!SessionState.RECOVERY_PEERS) return peers

  const actual = []

  for (const p of peers) {
    for (const r of SessionState.RECOVERY_PEERS) {
      if (b4a.equals(p.remotePublicKey, r)) {
        actual.push(p)
        break
      }
    }
  }

  return actual
}

function validateRecoveryPeers(peers, length) {
  if (peers.length < 1) return false

  for (const p of peers) {
    if (p.remoteLength > length) return false
    if (p.remoteLength === 0 && !p.remoteSynced) return false
  }

  return true
}
const { Writable, Readable } = require('streamx')

class ReadStream extends Readable {
  constructor(core, opts = {}) {
    super()

    this.core = core
    this.start = opts.start || 0
    this.end = typeof opts.end === 'number' ? opts.end : -1
    this.snapshot = !opts.live && opts.snapshot !== false
    this.live = this.end === -1 ? !!opts.live : false
    this.wait = typeof opts.wait === 'boolean' ? opts.wait : this.core.wait
    this.timeout = opts.timeout || core.timeout
  }

  _open(cb) {
    this._openP().then(cb, cb)
  }

  _read(cb) {
    this._readP().then(cb, cb)
  }

  async _openP() {
    if (this.end === -1) await this.core.update()
    else await this.core.ready()
    if (this.snapshot && this.end === -1) this.end = this.core.length
  }

  async _readP() {
    const end = this.live ? -1 : this.end === -1 ? this.core.length : this.end
    if (end >= 0 && this.start >= end) {
      this.push(null)
      return
    }

    this.push(await this.core.get(this.start++, { wait: this.wait, timeout: this.timeout }))
  }
}

exports.ReadStream = ReadStream

class WriteStream extends Writable {
  constructor(core) {
    super()
    this.core = core
  }

  _writev(batch, cb) {
    this._writevP(batch).then(cb, cb)
  }

  async _writevP(batch) {
    await this.core.append(batch)
  }
}

exports.WriteStream = WriteStream

class ByteStream extends Readable {
  constructor(core, opts = {}) {
    super()

    this._core = core
    this._index = 0
    this._range = null

    this._byteOffset = opts.byteOffset || 0
    this._byteLength = typeof opts.byteLength === 'number' ? opts.byteLength : -1
    this._prefetch = typeof opts.prefetch === 'number' ? opts.prefetch : 32

    this._applyOffset = this._byteOffset > 0
  }

  _open(cb) {
    this._openp().then(cb, cb)
  }

  _read(cb) {
    this._readp().then(cb, cb)
  }

  async _openp() {
    if (this._byteLength === -1) {
      await this._core.update()
      this._byteLength = Math.max(this._core.byteLength - this._byteOffset, 0)
    }
  }

  async _readp() {
    let data = null

    if (this._byteLength === 0) {
      this.push(null)
      return
    }

    let relativeOffset = 0

    if (this._applyOffset) {
      this._applyOffset = false

      const [block, byteOffset] = await this._core.seek(this._byteOffset)

      this._index = block
      relativeOffset = byteOffset
    }

    this._predownload(this._index + 1)
    data = await this._core.get(this._index++, { valueEncoding: 'binary' })

    if (relativeOffset > 0) data = data.subarray(relativeOffset)

    if (data.byteLength > this._byteLength) data = data.subarray(0, this._byteLength)
    this._byteLength -= data.byteLength

    this.push(data)
    if (this._byteLength === 0) this.push(null)
  }

  _predownload(index) {
    if (this._range) this._range.destroy()
    this._range = this._core.download({ start: index, end: index + this._prefetch, linear: true })
  }

  _destroy(cb) {
    if (this._range) this._range.destroy()
    cb(null)
  }
}

exports.ByteStream = ByteStream
const crypto = require('hypercore-crypto')
const b4a = require('b4a')
const c = require('compact-encoding')
const flat = require('flat-tree')
const { BAD_ARGUMENT } = require('hypercore-errors')
const unslab = require('unslab')

const m = require('./messages')
const multisig = require('./multisig')
const caps = require('./caps')

class Signer {
  constructor(
    manifestHash,
    version,
    index,
    { signature = 'ed25519', publicKey, namespace = caps.DEFAULT_NAMESPACE } = {}
  ) {
    if (!publicKey) throw BAD_ARGUMENT('public key is required for a signer')
    if (signature !== 'ed25519') throw BAD_ARGUMENT('Only Ed25519 signatures are supported')

    this.manifestHash = manifestHash
    this.version = version
    this.signer = index
    this.signature = signature
    this.publicKey = publicKey
    this.namespace = namespace
  }

  _ctx() {
    return this.version === 0 ? this.namespace : this.manifestHash
  }

  verify(batch, signature) {
    return crypto.verify(batch.signable(this._ctx()), signature, this.publicKey)
  }

  sign(batch, keyPair) {
    return crypto.sign(batch.signable(this._ctx()), keyPair.secretKey)
  }
}

class CompatSigner extends Signer {
  constructor(index, signer, legacy) {
    super(null, 0, index, signer)
    this.legacy = legacy
  }

  verify(batch, signature) {
    return crypto.verify(batch.signableCompat(this.legacy), signature, this.publicKey)
  }

  sign(batch, keyPair) {
    return crypto.sign(batch.signableCompat(this.legacy), keyPair.secretKey)
  }
}

module.exports = class Verifier {
  constructor(
    manifestHash,
    manifest,
    { compat = isCompat(manifestHash, manifest), legacy = false } = {}
  ) {
    const self = this

    this.manifestHash = manifestHash
    this.compat = compat || manifest === null
    this.version = this.compat ? 0 : typeof manifest.version === 'number' ? manifest.version : 1
    this.hash = manifest.hash || 'blake2b'
    this.allowPatch = !this.compat && !!manifest.allowPatch
    this.quorum = this.compat ? 1 : defaultQuorum(manifest)

    this.signers = manifest.signers ? manifest.signers.map(createSigner) : []
    this.prologue = this.compat ? null : manifest.prologue || null

    function createSigner(signer, index) {
      return self.compat
        ? new CompatSigner(index, signer, legacy)
        : new Signer(manifestHash, self.version, index, signer)
    }
  }

  _verifyCompat(batch, signature) {
    if (!signature) return false

    if (this.compat || (!this.allowPatch && this.signers.length === 1)) {
      return !!signature && this.signers[0].verify(batch, signature)
    }

    return this._verifyMulti(batch, signature)
  }

  _inflate(signature) {
    if (this.version >= 1) return multisig.inflate(signature)
    const { proofs, patch } = multisig.inflatev0(signature)

    return {
      proofs: proofs.map(proofToVersion1),
      patch
    }
  }

  _verifyMulti(batch, signature) {
    if (!signature || this.quorum === 0) return false

    const { proofs, patch } = this._inflate(signature)
    if (proofs.length < this.quorum) return false

    const tried = new Uint8Array(this.signers.length)
    const nodes = this.allowPatch && patch.length ? toMap(patch) : null

    for (let i = 0; i < this.quorum; i++) {
      const inp = proofs[i]

      let tree = batch

      if (inp.patch && this.allowPatch) {
        tree = batch.clone()

        const upgrade = generateUpgrade(nodes, batch.length, inp.patch)
        const proof = {
          fork: tree.fork,
          block: null,
          hash: null,
          seek: null,
          upgrade,
          manifest: null
        }

        try {
          if (!tree.verifyUpgrade(proof)) return false
        } catch {
          return false
        }
      }

      if (inp.signer >= this.signers.length || tried[inp.signer]) return false
      tried[inp.signer] = 1

      const s = this.signers[inp.signer]
      if (!s.verify(tree, inp.signature)) return false
    }

    return true
  }

  verify(batch, signature) {
    if (this.version === 0) {
      return this._verifyCompat(batch, signature)
    }

    if (this.prologue !== null && batch.length <= this.prologue.length) {
      return batch.length === this.prologue.length && b4a.equals(batch.hash(), this.prologue.hash)
    }

    return this._verifyMulti(batch, signature)
  }

  // TODO: better api for this that is more ... multisig-ey
  sign(batch, keyPair) {
    if (!keyPair || !keyPair.secretKey) throw BAD_ARGUMENT('No key pair was passed')

    for (const s of this.signers) {
      if (b4a.equals(s.publicKey, keyPair.publicKey)) {
        const signature = s.sign(batch, keyPair)
        if (this.signers.length !== 1 || this.version === 0) return signature
        return this.assemble([{ signer: 0, signature, patch: 0, nodes: null }])
      }
    }

    throw BAD_ARGUMENT('Public key is not a declared signer')
  }

  assemble(inputs) {
    return this.version === 0 ? multisig.assemblev0(inputs) : multisig.assemble(inputs)
  }

  static manifestHash(manifest) {
    return manifestHash(manifest)
  }

  static encodeManifest(manifest) {
    return c.encode(m.manifest, manifest)
  }

  static decodeManifest(manifest) {
    return c.decode(m.manifest, manifest)
  }

  static defaultSignerManifest(publicKey) {
    return {
      version: 1,
      hash: 'blake2b',
      allowPatch: false,
      quorum: 1,
      signers: [
        {
          signature: 'ed25519',
          namespace: caps.DEFAULT_NAMESPACE,
          publicKey
        }
      ],
      prologue: null,
      linked: null,
      userData: null
    }
  }

  static fromManifest(manifest, opts) {
    const m = this.createManifest(manifest)
    return new this(manifestHash(m), m, opts)
  }

  static createManifest(inp) {
    if (!inp) return null

    if (inp.quorum && inp.quorum < 0) throw BAD_ARGUMENT('Quorum cannot be negative')
    if (inp.quorum && inp.signers && inp.quorum > inp.signers.length) {
      throw BAD_ARGUMENT('Quorum should not be higher than the number of signers')
    }

    const manifest = {
      version: getManifestVersion(inp), // defaults to v1
      hash: 'blake2b',
      allowPatch: !!inp.allowPatch,
      quorum: defaultQuorum(inp),
      signers: inp.signers ? inp.signers.map(parseSigner) : [],
      prologue: null,
      linked: null,
      userData: inp.userData || null
    }

    if (inp.hash && inp.hash !== 'blake2b') throw BAD_ARGUMENT('Only Blake2b hashes are supported')

    if (inp.prologue) {
      if (
        !(b4a.isBuffer(inp.prologue.hash) && inp.prologue.hash.byteLength === 32) ||
        !(inp.prologue.length >= 0)
      ) {
        throw BAD_ARGUMENT('Invalid prologue')
      }

      manifest.prologue = inp.prologue
      manifest.prologue.hash = unslab(manifest.prologue.hash)
    }

    if (manifest.userData !== null && manifest.version < 2) {
      throw BAD_ARGUMENT('Invalid field: userData')
    }

    if (inp.linked && inp.linked.length) {
      if (manifest.version < 2) throw BAD_ARGUMENT('Invalid field: linked')

      for (const key of inp.linked) {
        if (!(b4a.isBuffer(key) && key.byteLength === 32)) {
          throw BAD_ARGUMENT('Invalid key')
        }
      }

      manifest.linked = inp.linked
    }

    return manifest
  }

  static isValidManifest(key, manifest) {
    return b4a.equals(key, manifestHash(manifest))
  }

  static isCompat(key, manifest) {
    return isCompat(key, manifest)
  }

  static sign(manifest, batch, keyPair, opts) {
    return Verifier.fromManifest(manifest, opts).sign(batch, keyPair)
  }
}

function toMap(nodes) {
  const m = new Map()
  for (const node of nodes) m.set(node.index, node)
  return m
}

function isCompat(key, manifest) {
  return !!(
    manifest &&
    manifest.signers.length === 1 &&
    b4a.equals(key, manifest.signers[0].publicKey)
  )
}

function defaultQuorum(man) {
  if (typeof man.quorum === 'number') return man.quorum
  if (!man.signers || !man.signers.length) return 0
  return (man.signers.length >> 1) + 1
}

function generateUpgrade(patch, start, length) {
  const upgrade = { start, length, nodes: null, additionalNodes: [], signature: null }

  const from = start * 2
  const to = from + length * 2

  for (const ite = flat.iterator(0); ite.fullRoot(to); ite.nextTree()) {
    if (ite.index + ite.factor / 2 < from) continue

    if (upgrade.nodes === null && ite.contains(from - 2)) {
      upgrade.nodes = []

      const root = ite.index
      const target = from - 2

      ite.seek(target)

      while (ite.index !== root) {
        ite.sibling()
        if (ite.index > target) upgrade.nodes.push(patch.get(ite.index))
        ite.parent()
      }

      continue
    }

    if (upgrade.nodes === null) upgrade.nodes = []
    upgrade.nodes.push(patch.get(ite.index))
  }

  if (upgrade.nodes === null) upgrade.nodes = []
  return upgrade
}

function parseSigner(signer) {
  validateSigner(signer)
  return {
    signature: 'ed25519',
    namespace: unslab(signer.namespace || caps.DEFAULT_NAMESPACE),
    publicKey: unslab(signer.publicKey)
  }
}

function validateSigner(signer) {
  if (!signer || !signer.publicKey) throw BAD_ARGUMENT('Signer missing public key')
  if (signer.signature && signer.signature !== 'ed25519') {
    throw BAD_ARGUMENT('Only Ed25519 signatures are supported')
  }
}

function manifestHash(manifest) {
  const state = { start: 0, end: 32, buffer: null }
  m.manifest.preencode(state, manifest)
  state.buffer = b4a.allocUnsafe(state.end)
  c.raw.encode(state, caps.MANIFEST)
  m.manifest.encode(state, manifest)
  return crypto.hash(state.buffer)
}

function proofToVersion1(proof) {
  return {
    signer: proof.signer,
    signature: proof.signature,
    patch: proof.patch ? proof.patch.length : 0
  }
}

function getManifestVersion(inp) {
  if (typeof inp.version === 'number') return inp.version
  if (inp.linked && inp.linked.length) return 2
  if (inp.userData) return 2
  return 1
}
let COMPAT = true
let BATCH_UINTS = COMPAT ? 65536 : 128
let BATCH_BYTES = BATCH_UINTS * 4
let BATCH = BATCH_BYTES * 8 // in bits
const MAX_REMOTE_BATCHES = 4
const MAX_RANGE = 8 * 256 * 1024
const MIN_RANGE = 32 // 4bit ints
const MAX = 512
const MAX_ANY = 16

class LocalWants {
  constructor(peer) {
    this.destroyed = false
    this.peer = peer
    this.wants = new Map()
    this.free = new Set()
    this.any = null
  }

  add(index, handle) {
    const b = (index - (index & (BATCH - 1))) / BATCH
    return this.addBatch(b, handle)
  }

  addAnyRange(start, length, handle) {
    if (this.destroyed) return null
    if (this.any === null) this.any = []

    if (COMPAT) {
      let r = start & (BATCH - 1)
      start -= r
      length += r
      r = length & (BATCH - 1)
      if (r) length = length - r + BATCH
    }

    for (let i = 0; i < this.any.length; i++) {
      const w = this.any[i]
      if (w.start === start && w.length === length) {
        w.handles.add(handle)
        handle.addWant(w)
        return null
      }
    }

    const w = { wants: this, start, length, any: true, handles: new Set([handle]) }
    this.any.push(w)
    handle.addWant(w)

    return { start, length, any: !COMPAT }
  }

  removeAnyRange(start, length, handle) {
    if (this.any === null) return null

    for (let i = 0; i < this.any.length; i++) {
      const w = this.any[i]
      if (w.start !== start || w.length !== length) continue

      w.handles.delete(handle)
      handle.removeWant(w)
      if (w.handles.size > 0) return null

      const head = this.any.pop()
      if (head !== w) this.any[i] = head
      return { start, length, any: !COMPAT }
    }

    return null
  }

  addBatch(index, handle) {
    if (this.destroyed) return null
    let w = this.wants.get(index)

    if (w) {
      const size = w.handles.size
      w.handles.add(handle)
      if (w.handles.size !== size) {
        handle.addWant(w)
      }
      return null
    }

    // start here is the batch number for simplicity....
    w = { wants: this, start: index, length: 0, any: false, handles: new Set([handle]) }

    if (this.free.has(index)) {
      this.free.delete(index)
      this.wants.set(index, w)
      handle.addWant(w)
      return null
    }

    let unwant = null
    if (this.wants.size + this.free.size === MAX) {
      if (this.free.size === 0) {
        return null
      }
      unwant = this._unwant()
    }

    this.wants.set(index, w)
    handle.addWant(w)

    return {
      want: { start: index * BATCH, length: BATCH, any: false },
      unwant
    }
  }

  remove(index, handle) {
    const b = (index - (index & (BATCH - 1))) / BATCH
    return this.removeBatch(b, handle)
  }

  removeBatch(index, handle) {
    if (this.destroyed) return false

    const w = this.wants.get(index)
    if (!w) {
      return false
    }

    w.handles.delete(handle)
    handle.removeWant(w)

    if (w.handles.size === 0) {
      this.free.add(index)
      this.wants.delete(index)
      return this.free.size === 1 && this.wants.size === MAX - 1
    }

    return false
  }

  destroy() {
    if (this.destroyed) return
    this.destroyed = true

    for (const w of this.wants.values()) {
      for (const handle of w.handles) {
        handle.removeWant(w)
      }
    }

    this.wants.clear()
  }

  _unwant() {
    for (const index of this.free) {
      this.free.delete(index)
      return { start: index * BATCH, length: BATCH, any: false }
    }
    return null
  }
}

class RemoteWants {
  constructor() {
    this.any = null
    this.all = false
    this.size = 0
    this.batches = []
  }

  hasAny(start, length) {
    for (let i = 0; i < this.any.length; i++) {
      const a = this.any[i]
      const e = start + length
      const end = a.start + a.length

      if (a.start <= start && start < end) return true
      if (a.start < e && e <= end) return true
    }

    return this.all
  }

  hasRange(start, length) {
    if (this.any !== null && this.hasAny(start, length)) return true
    if (length === 1) return this.has(start)

    let smallest = -1

    for (let i = 0; i < this.batches.length; i++) {
      const b = this.batches[i]
      if (b.length < smallest || smallest === -1) smallest = b.length
    }

    if (smallest === -1) return this.all

    const r = start & (smallest - 1)
    const end = start + length

    let max = 3

    for (let i = start - r; i < end; i += smallest) {
      if (max-- === 0) return true // just to save work
      if (this.has(i)) return true
    }

    return this.all
  }

  has(index) {
    for (let i = 0; i < this.batches.length; i++) {
      const b = this.batches[i]
      const block = (index - (index & (b.length - 1))) / b.length
      if (b.ranges.has(block)) return true
    }

    return this.all
  }

  add(range) {
    if (range.any) {
      if (this.any === null) this.any = []
      if (this.any.length < MAX_ANY) this.any.push(range)
      else this.all = true
      return true
    }

    if (range.length > MAX_RANGE) return false

    if (!validateBatchRange(range)) {
      this.all = true
      return true
    }

    if (this.size >= MAX) {
      this.all = true
      return true
    }

    for (let i = 0; i < this.batches.length; i++) {
      const b = this.batches[i]
      if (b.length === range.length) {
        b.ranges.add(range.start / range.length)
        this.size++
        return true
      }
    }

    if (this.batches.length >= MAX_REMOTE_BATCHES) {
      this.all = true
      return true
    }

    this.batches.push({
      length: range.length,
      ranges: new Set([range.start / range.length])
    })
    this.size++

    return true
  }

  remove(range) {
    if (range.any) {
      if (this.any === null) return false

      for (let i = 0; i < this.any.length; i++) {
        const a = this.any[i]

        if (a.start === range.start && a.length === range.length) {
          const head = this.any.pop()
          if (head !== a) this.any[i] = head
          return true
        }
      }

      return false
    }

    if (!validateBatchRange(range)) return false

    for (let i = 0; i < this.batches.length; i++) {
      const b = this.batches[i]
      if (b.length !== range.length) continue

      const size = b.ranges.size
      b.ranges.delete(range.start / range.length)
      if (b.ranges.size !== size) this.size--

      if (b.ranges.size === 0) {
        const head = this.batches.pop()
        if (head !== b) this.batches[i] = head
      }

      return true
    }

    return false
  }
}

function UPDATE_COMPAT(isCompat) {
  COMPAT = isCompat
  BATCH_UINTS = COMPAT ? 65536 : 128
  BATCH_BYTES = BATCH_UINTS * 4
  BATCH = BATCH_BYTES * 8 // in bits
  exports.WANT_BATCH = BATCH
}

exports.LocalWants = LocalWants
exports.RemoteWants = RemoteWants
exports.WANT_BATCH = BATCH
exports.UPDATE_COMPAT = UPDATE_COMPAT

function validateBatchRange(range) {
  if (range.length > MAX_RANGE || range.length < MIN_RANGE) {
    return false
  }
  // check if power of two
  if ((range.length & (range.length - 1)) !== 0) {
    return false
  }
  // start must be a multiple of the length
  if (range.start & (range.length - 1)) {
    return false
  }

  return true
}
{
  "name": "hypercore",
  "version": "11.33.5",
  "description": "Hypercore is a secure, distributed append-only log",
  "main": "index.js",
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "brittle test/all.js",
    "test:bare": "bare test/all.js",
    "test:generate": "brittle -r test/all.js test/*.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/hypercore.git"
  },
  "contributors": [
    {
      "name": "Mathias Buus",
      "email": "mathiasbuus@gmail.com",
      "url": "https://mafinto.sh"
    },
    {
      "name": "Andrew Osheroff",
      "email": "andrewosh@gmail.com",
      "url": "https://andrewosh.com"
    }
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/hypercore/issues"
  },
  "homepage": "https://github.com/holepunchto/hypercore#readme",
  "files": [
    "index.js",
    "errors.js",
    "messages.js",
    "lib/**.js"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "dependencies": {
    "@hyperswarm/secret-stream": "^6.0.0",
    "b4a": "^1.1.0",
    "bare-events": "^2.2.0",
    "big-sparse-array": "^1.0.3",
    "compact-encoding": "^3.0.0",
    "fast-fifo": "^1.3.0",
    "flat-tree": "^1.9.0",
    "hypercore-crypto": "^3.2.1",
    "hypercore-errors": "^1.5.0",
    "hypercore-id-encoding": "^1.2.0",
    "hypercore-storage": "^3.0.0",
    "is-options": "^1.0.1",
    "nanoassert": "^2.0.0",
    "protomux": "^3.5.0",
    "quickbit-universal": "^2.2.0",
    "random-array-iterator": "^1.0.0",
    "safety-catch": "^1.0.1",
    "sodium-universal": "^5.0.1",
    "streamx": "^2.12.4",
    "unslab": "^1.3.0",
    "z32": "^1.0.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "debugging-stream": "^3.1.0",
    "hyperswarm": "^4.3.6",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "rache": "^1.0.0",
    "range-parser": "^1.2.1",
    "resolve-reject-promise": "^1.1.0",
    "speedometer": "^1.1.0",
    "test-tmp": "^1.0.2",
    "tiny-byte-size": "^1.1.0",
    "udx-native": "^1.6.1",
    "uncaughts": "^1.1.0"
  }
}
{
  "name": "hyperschema",
  "version": "1.21.0",
  "description": "Create registries of declarative compact-encoding schemas",
  "files": [
    "lib/*.js",
    "builder.mjs",
    "builder.cjs",
    "runtime.mjs",
    "runtime.cjs",
    "primitives.mjs",
    "primitives.cjs"
  ],
  "exports": {
    "./package": "./package.json",
    ".": {
      "import": "./builder.mjs",
      "default": "./builder.cjs"
    },
    "./runtime": {
      "import": "./runtime.mjs",
      "default": "./runtime.cjs"
    },
    "./primitives": {
      "import": "./primitives.mjs",
      "default": "./primitives.cjs"
    }
  },
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    }
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test/index.js",
    "test:bare": "prettier . --check && bare test/index.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/hyperschema.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/hyperschema/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperschema#readme",
  "dependencies": {
    "bare-fs": "^4.0.1",
    "compact-encoding": "^3.0.0",
    "generate-object-property": "^2.0.0",
    "generate-string": "^1.0.1"
  },
  "devDependencies": {
    "brittle": "^3.7.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "test-tmp": "^1.3.0"
  }
}
module.exports = {
  c: require('compact-encoding')
}
const b4a = require('b4a')

const EMPTY = b4a.alloc(0)
const MAX = b4a.from([0xff])
const BUFFER = {}

BUFFER.preencode = function (state, buf) {
  if (buf === null) buf = EMPTY

  let i = 0
  let extra = 3

  while ((i = b4a.indexOf(buf, 0x00, i)) > -1) {
    i++
    extra++
  }

  state.end += buf.byteLength + extra
}

BUFFER.encode = function (state, buf) {
  if (buf === null) buf = EMPTY

  state.buffer[state.start++] = 0x00

  let prev = 0
  let i = 0

  while ((i = b4a.indexOf(buf, 0x00, i)) > -1) {
    const slice = buf.subarray(prev, ++i)

    state.buffer.set(slice, state.start)
    state.start += slice.byteLength
    state.buffer[state.start++] = 0x02
    prev = i
  }

  const slice = buf.subarray(prev)

  state.buffer.set(slice, state.start)
  state.start += slice.byteLength

  state.buffer[state.start++] = 0x00
  state.buffer[state.start++] = 0x01
}

BUFFER.decode = function (state) {
  if (state.start >= state.end) throw new Error('Out of bounds')
  if (state.buffer[state.start++] !== 0x00) {
    throw new Error('Invalid start of string')
  }

  let escaped = null

  let prev = state.start
  let i = state.start

  while ((i = b4a.indexOf(state.buffer, 0x00, i)) > -1) {
    const next = ++i < state.end ? state.buffer[i] : 0x00

    i++

    if (next === 0x01) {
      break
    }

    if (next === 0x02) {
      if (escaped === null) escaped = []
      escaped.push(state.buffer.subarray(prev, i - 1))
      prev = i
      continue
    }

    throw new Error('Unknown value in terminator')
  }

  if (i === -1) {
    throw new Error('No terminator found')
  }

  state.start = i
  const last = state.buffer.subarray(prev, i - 2)
  if (escaped === null) return last

  escaped.push(last)
  return b4a.concat(escaped)
}

// TODO: can be optimised a lot

const STRING = {}

STRING.preencode = function (state, str) {
  BUFFER.preencode(state, b4a.from(str || ''))
}

STRING.encode = function (state, str) {
  BUFFER.encode(state, b4a.from(str || ''))
}

STRING.decode = function (state, str) {
  return b4a.toString(BUFFER.decode(state))
}

const UINT = {}

UINT.preencode = function (state, n) {
  state.end += n <= 0xfb ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : n === Infinity ? 1 : 9
}

UINT.encode = function (state, n) {
  if (n === Infinity) {
    state.buffer[state.start++] = 0xff
    return
  }

  if (n <= 0xfb) {
    state.buffer[state.start++] = n
    return
  }

  if (n <= 0xffff) {
    state.buffer[state.start++] = 0xfc
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
    return
  }

  if (n <= 0xffffffff) {
    state.buffer[state.start++] = 0xfd
    encodeUint32(state, n)
    return
  }

  if (Number.isSafeInteger(n)) {
    state.buffer[state.start++] = 0xfe

    const r = Math.floor(n / 0x100000000)
    encodeUint32(state, r)
    encodeUint32(state, n)
    return
  }

  throw new Error('Invalid number ' + n)
}

UINT.decode = function (state) {
  if (state.start >= state.end) throw new Error('Out of bounds')

  const a = state.buffer[state.start++]

  if (a <= 0xfb) return a

  if (a === 0xfc) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] * 0x100 + state.buffer[state.start++]
  }

  if (a === 0xfd) {
    return decodeUint32(state)
  }

  if (a === 0xfe) {
    return decodeUint32(state) * 0x100000000 + decodeUint32(state)
  }

  return Infinity
}

const INT = {}

INT.preencode = function (state, n) {
  // One asymmetric condition
  if (n >= -0xff && n < 0) {
    state.end += 2
    return
  }
  n = Math.abs(n)
  state.end += n <= 0xf6 ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : n === Infinity ? 1 : 9
}

INT.encode = function (state, n) {
  if (n === Infinity) {
    state.buffer[state.start++] = 0xff
    return
  }

  if (n === -Infinity) {
    state.buffer[state.start++] = 0x00
    return
  }

  // Negative 64 bit
  if (n < -0xffffffff) {
    if (!Number.isSafeInteger(n)) throw new Error('Invalid number ' + n)
    state.buffer[state.start++] = 0x01

    const r = Math.floor(-n / 0x100000000)
    encodeUint32(state, -r + 0xffffffff)
    encodeUint32(state, -(-n % 0x100000000) + 0xffffffff)
    return
  }

  // Negative 32 bit
  if (n < -0xffff) {
    state.buffer[state.start++] = 0x02

    n += 0xffffffff
    encodeUint32(state, n)
    return
  }

  // Negative 16bit
  if (n < -0xff) {
    state.buffer[state.start++] = 0x03

    n += 0xffff
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
    return
  }

  // Negative 8bit
  if (n < 0) {
    state.buffer[state.start++] = 0x04

    n += 0xff
    state.buffer[state.start++] = n
    return
  }

  // Remainder of 8bit space for positive int
  if (n <= 0xf6) {
    state.buffer[state.start++] = n + 0x05
    return
  }

  // Positive 16bit
  if (n <= 0xffff) {
    state.buffer[state.start++] = 0xfc
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
    return
  }

  // Positive 32bit
  if (n <= 0xffffffff) {
    state.buffer[state.start++] = 0xfd
    encodeUint32(state, n)
    return
  }

  // Positive 64bit
  if (Number.isSafeInteger(n)) {
    state.buffer[state.start++] = 0xfe

    const r = Math.floor(n / 0x100000000)
    encodeUint32(state, r)
    encodeUint32(state, n)
    return
  }

  throw new Error('Invalid number ' + n)
}

INT.decode = function (state) {
  if (state.start >= state.end) throw new Error('Out of bounds')

  const a = state.buffer[state.start++]

  if (a === 0x00) return -Infinity

  if (a === 0x01) {
    // Split (2^64 - 1) into its 32 bit components
    // r * 0x100000000 + n - (2^64 - 1)
    // r * 0x100000000 + n - (0xffffffff * 0x100000000) - 0xffffffff
    // (r - 0xffffffff) * 0x100000000 + n - 0xffffffff
    return (decodeUint32(state) - 0xffffffff) * 0x100000000 + decodeUint32(state) - 0xffffffff
  }

  if (a === 0x02) {
    return decodeUint32(state) - 0xffffffff
  }

  if (a === 0x03) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] * 0x100 + state.buffer[state.start++] - 0xffff
  }

  if (a === 0x04) return state.buffer[state.start++] - 0xff

  if (a <= 0xfb) return a - 0x05

  if (a === 0xfc) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] * 0x100 + state.buffer[state.start++]
  }

  if (a === 0xfd) {
    return decodeUint32(state)
  }

  if (a === 0xfe) {
    return decodeUint32(state) * 0x100000000 + decodeUint32(state)
  }

  return Infinity
}

const DATE = {}

DATE.preencode = (state, d) => INT.preencode(state, d.getTime())
DATE.encode = (state, d) => INT.encode(state, d.getTime())
DATE.decode = (state) => new Date(INT.decode(state))

const BOOL = {}

BOOL.preencode = (state, b) => UINT.preencode(state, b ? 1 : 0)
BOOL.encode = (state, b) => UINT.encode(state, b ? 1 : 0)
BOOL.decode = (state) => !!UINT.decode(state)

module.exports = class IndexEncoder {
  constructor(encodings, { prefix = -1 } = {}) {
    this.encodings = encodings
    this.prefix = prefix
  }

  static BUFFER = BUFFER
  static STRING = STRING
  static UINT = UINT
  static INT = INT
  static DATE = DATE
  static BOOL = BOOL

  static lookup(c) {
    switch (c) {
      case 'uint':
        return UINT
      case 'uint8':
        return UINT
      case 'uint16':
        return UINT
      case 'uint24':
        return UINT
      case 'uint32':
        return UINT
      case 'uint40':
        return UINT
      case 'uint48':
        return UINT
      case 'uint56':
        return UINT
      case 'uint64':
        return UINT
      case 'int':
        return INT
      case 'int8':
        return INT
      case 'int16':
        return INT
      case 'int24':
        return INT
      case 'int32':
        return INT
      case 'int40':
        return INT
      case 'int48':
        return INT
      case 'int56':
        return INT
      case 'int64':
        return INT
      case 'string':
        return STRING
      case 'utf8':
        return STRING
      case 'ascii':
        return STRING
      case 'hex':
        return STRING
      case 'base64':
        return STRING
      case 'fixed32':
        return BUFFER
      case 'fixed64':
        return BUFFER
      case 'buffer':
        return BUFFER
      case 'date':
        return DATE
      case 'bool':
        return BOOL
    }

    throw new Error('Unknown type')
  }

  encode(keys) {
    return this._encode(keys, false)
  }

  _encode(keys, terminate) {
    if (b4a.isBuffer(keys)) return keys

    const state = { start: 0, end: 0, buffer: null }

    if (this.prefix !== -1) UINT.preencode(state, this.prefix)
    for (let i = 0; i < keys.length; i++) {
      this.encodings[i].preencode(state, keys[i])
    }

    if (terminate && keys.length < this.encodings.length) {
      state.end++
    }

    state.buffer = b4a.allocUnsafe(state.end)

    if (this.prefix !== -1) UINT.encode(state, this.prefix)
    for (let i = 0; i < keys.length; i++) {
      this.encodings[i].encode(state, keys[i])
    }

    if (terminate && keys.length < this.encodings.length) {
      state.buffer[state.start++] = MAX[0]
    }

    return state.buffer
  }

  decode(buffer) {
    const state = { start: 0, end: buffer.byteLength, buffer }
    const result = []

    if (this.prefix !== -1) UINT.decode(state)
    for (const enc of this.encodings) {
      const key = state.start < state.end ? enc.decode(state) : enc === UINT ? 0 : null
      result.push(key)
    }

    return result
  }

  encodeRange({ gt, gte, lt, lte }) {
    const range = {
      gt: gt && this._encode(gt, true),
      gte: gte && this._encode(gte, false),
      lt: lt && this._encode(lt, false),
      lte: lte && this._encode(lte, true)
    }

    if (this.prefix !== -1) {
      if (!gt && !gte) range.gte = encodeUint(this.prefix)
      if (!lt && !lte) range.lt = encodeUint(this.prefix + 1)
    }

    return range
  }
}

function encodeUint(n) {
  const state = { start: 0, end: 0, buffer: null }
  UINT.preencode(state, n)
  state.buffer = b4a.allocUnsafe(state.end)
  UINT.encode(state, n)
  return state.buffer
}

function encodeUint32(state, n) {
  state.buffer[state.start++] = n >>> 24
  state.buffer[state.start++] = n >>> 16
  state.buffer[state.start++] = n >>> 8
  state.buffer[state.start++] = n
}

function decodeUint32(state) {
  if (state.end - state.start < 4) throw new Error('Out of bounds')
  return (
    state.buffer[state.start++] * 0x1000000 +
    state.buffer[state.start++] * 0x10000 +
    state.buffer[state.start++] * 0x100 +
    state.buffer[state.start++]
  )
}
{
  "name": "index-encoder",
  "version": "3.5.0",
  "description": "Encode multiple values into sorted keys",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.6.4"
  },
  "devDependencies": {
    "brittle": "^3.2.1",
    "hyperbee": "^2.10.5",
    "hypercore": "^11.0.0",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/index-encoder.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/index-encoder/issues"
  },
  "homepage": "https://github.com/holepunchto/index-encoder"
}
const b4a = require('b4a')

module.exports = function isOptions (opts) {
  return typeof opts === 'object' && opts && !b4a.isBuffer(opts)
}
{
  "name": "is-options",
  "version": "1.0.2",
  "description": "Easily check if input is an options map",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.1.1"
  },
  "devDependencies": {
    "standard": "^11.0.1",
    "tape": "^4.9.0"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/is-options.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/is-options/issues"
  },
  "homepage": "https://github.com/mafintosh/is-options"
}
import { coerce } from '../bytes.js';
import basex from '../vendor/base-x.js';
/**
 * Class represents both BaseEncoder and MultibaseEncoder meaning it
 * can be used to encode to multibase or base encode without multibase
 * prefix.
 */
class Encoder {
    name;
    prefix;
    baseEncode;
    constructor(name, prefix, baseEncode) {
        this.name = name;
        this.prefix = prefix;
        this.baseEncode = baseEncode;
    }
    encode(bytes) {
        if (bytes instanceof Uint8Array) {
            return `${this.prefix}${this.baseEncode(bytes)}`;
        }
        else {
            throw Error('Unknown type, must be binary type');
        }
    }
}
/**
 * Class represents both BaseDecoder and MultibaseDecoder so it could be used
 * to decode multibases (with matching prefix) or just base decode strings
 * with corresponding base encoding.
 */
class Decoder {
    name;
    prefix;
    baseDecode;
    prefixCodePoint;
    constructor(name, prefix, baseDecode) {
        this.name = name;
        this.prefix = prefix;
        const prefixCodePoint = prefix.codePointAt(0);
        /* c8 ignore next 3 */
        if (prefixCodePoint === undefined) {
            throw new Error('Invalid prefix character');
        }
        this.prefixCodePoint = prefixCodePoint;
        this.baseDecode = baseDecode;
    }
    decode(text) {
        if (typeof text === 'string') {
            if (text.codePointAt(0) !== this.prefixCodePoint) {
                throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);
            }
            return this.baseDecode(text.slice(this.prefix.length));
        }
        else {
            throw Error('Can only multibase decode strings');
        }
    }
    or(decoder) {
        return or(this, decoder);
    }
}
class ComposedDecoder {
    decoders;
    constructor(decoders) {
        this.decoders = decoders;
    }
    or(decoder) {
        return or(this, decoder);
    }
    decode(input) {
        const prefix = input[0];
        const decoder = this.decoders[prefix];
        if (decoder != null) {
            return decoder.decode(input);
        }
        else {
            throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);
        }
    }
}
export function or(left, right) {
    return new ComposedDecoder({
        ...(left.decoders ?? { [left.prefix]: left }),
        ...(right.decoders ?? { [right.prefix]: right })
    });
}
export class Codec {
    name;
    prefix;
    baseEncode;
    baseDecode;
    encoder;
    decoder;
    constructor(name, prefix, baseEncode, baseDecode) {
        this.name = name;
        this.prefix = prefix;
        this.baseEncode = baseEncode;
        this.baseDecode = baseDecode;
        this.encoder = new Encoder(name, prefix, baseEncode);
        this.decoder = new Decoder(name, prefix, baseDecode);
    }
    encode(input) {
        return this.encoder.encode(input);
    }
    decode(input) {
        return this.decoder.decode(input);
    }
}
export function from({ name, prefix, encode, decode }) {
    return new Codec(name, prefix, encode, decode);
}
export function baseX({ name, prefix, alphabet }) {
    const { encode, decode } = basex(alphabet, name);
    return from({
        prefix,
        name,
        encode,
        decode: (text) => coerce(decode(text))
    });
}
function decode(string, alphabetIdx, bitsPerChar, name) {
    // Count the padding bytes:
    let end = string.length;
    while (string[end - 1] === '=') {
        --end;
    }
    // Allocate the output:
    const out = new Uint8Array((end * bitsPerChar / 8) | 0);
    // Parse the data:
    let bits = 0; // Number of bits currently in the buffer
    let buffer = 0; // Bits waiting to be written out, MSB first
    let written = 0; // Next byte to write
    for (let i = 0; i < end; ++i) {
        // Read one character from the string:
        const value = alphabetIdx[string[i]];
        if (value === undefined) {
            throw new SyntaxError(`Non-${name} character`);
        }
        // Append the bits to the buffer:
        buffer = (buffer << bitsPerChar) | value;
        bits += bitsPerChar;
        // Write out some bits if the buffer has a byte's worth:
        if (bits >= 8) {
            bits -= 8;
            out[written++] = 0xff & (buffer >> bits);
        }
    }
    // Verify that we have received just enough bits:
    if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {
        throw new SyntaxError('Unexpected end of data');
    }
    return out;
}
function encode(data, alphabet, bitsPerChar) {
    const pad = alphabet[alphabet.length - 1] === '=';
    const mask = (1 << bitsPerChar) - 1;
    let out = '';
    let bits = 0; // Number of bits currently in the buffer
    let buffer = 0; // Bits waiting to be written out, MSB first
    for (let i = 0; i < data.length; ++i) {
        // Slurp data into the buffer:
        buffer = (buffer << 8) | data[i];
        bits += 8;
        // Write out as much as we can:
        while (bits > bitsPerChar) {
            bits -= bitsPerChar;
            out += alphabet[mask & (buffer >> bits)];
        }
    }
    // Partial character:
    if (bits !== 0) {
        out += alphabet[mask & (buffer << (bitsPerChar - bits))];
    }
    // Add padding characters until we hit a byte boundary:
    if (pad) {
        while (((out.length * bitsPerChar) & 7) !== 0) {
            out += '=';
        }
    }
    return out;
}
function createAlphabetIdx(alphabet) {
    // Build the character lookup table:
    const alphabetIdx = {};
    for (let i = 0; i < alphabet.length; ++i) {
        alphabetIdx[alphabet[i]] = i;
    }
    return alphabetIdx;
}
/**
 * RFC4648 Factory
 */
export function rfc4648({ name, prefix, bitsPerChar, alphabet }) {
    const alphabetIdx = createAlphabetIdx(alphabet);
    return from({
        prefix,
        name,
        encode(input) {
            return encode(input, alphabet, bitsPerChar);
        },
        decode(input) {
            return decode(input, alphabetIdx, bitsPerChar, name);
        }
    });
}
//# sourceMappingURL=base.js.mapimport { rfc4648 } from './base.js';
export const base32 = rfc4648({
    prefix: 'b',
    name: 'base32',
    alphabet: 'abcdefghijklmnopqrstuvwxyz234567',
    bitsPerChar: 5
});
export const base32upper = rfc4648({
    prefix: 'B',
    name: 'base32upper',
    alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',
    bitsPerChar: 5
});
export const base32pad = rfc4648({
    prefix: 'c',
    name: 'base32pad',
    alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',
    bitsPerChar: 5
});
export const base32padupper = rfc4648({
    prefix: 'C',
    name: 'base32padupper',
    alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',
    bitsPerChar: 5
});
export const base32hex = rfc4648({
    prefix: 'v',
    name: 'base32hex',
    alphabet: '0123456789abcdefghijklmnopqrstuv',
    bitsPerChar: 5
});
export const base32hexupper = rfc4648({
    prefix: 'V',
    name: 'base32hexupper',
    alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',
    bitsPerChar: 5
});
export const base32hexpad = rfc4648({
    prefix: 't',
    name: 'base32hexpad',
    alphabet: '0123456789abcdefghijklmnopqrstuv=',
    bitsPerChar: 5
});
export const base32hexpadupper = rfc4648({
    prefix: 'T',
    name: 'base32hexpadupper',
    alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',
    bitsPerChar: 5
});
export const base32z = rfc4648({
    prefix: 'h',
    name: 'base32z',
    alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',
    bitsPerChar: 5
});
//# sourceMappingURL=base32.js.mapimport { baseX } from './base.js';
export const base36 = baseX({
    prefix: 'k',
    name: 'base36',
    alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'
});
export const base36upper = baseX({
    prefix: 'K',
    name: 'base36upper',
    alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
});
//# sourceMappingURL=base36.js.mapimport { baseX } from './base.js';
export const base58btc = baseX({
    name: 'base58btc',
    prefix: 'z',
    alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
});
export const base58flickr = baseX({
    name: 'base58flickr',
    prefix: 'Z',
    alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'
});
//# sourceMappingURL=base58.js.mapexport const empty = new Uint8Array(0);
export function toHex(d) {
    return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '');
}
export function fromHex(hex) {
    const hexes = hex.match(/../g);
    return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty;
}
export function equals(aa, bb) {
    if (aa === bb) {
        return true;
    }
    if (aa.byteLength !== bb.byteLength) {
        return false;
    }
    for (let ii = 0; ii < aa.byteLength; ii++) {
        if (aa[ii] !== bb[ii]) {
            return false;
        }
    }
    return true;
}
export function coerce(o) {
    if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') {
        return o;
    }
    if (o instanceof ArrayBuffer) {
        return new Uint8Array(o);
    }
    if (ArrayBuffer.isView(o)) {
        return new Uint8Array(o.buffer, o.byteOffset, o.byteLength);
    }
    throw new Error('Unknown type, must be binary type');
}
export function isBinary(o) {
    return o instanceof ArrayBuffer || ArrayBuffer.isView(o);
}
export function fromString(str) {
    return new TextEncoder().encode(str);
}
export function toString(b) {
    return new TextDecoder().decode(b);
}
//# sourceMappingURL=bytes.js.mapimport { base32 } from './bases/base32.js';
import { base36 } from './bases/base36.js';
import { base58btc } from './bases/base58.js';
import { coerce } from './bytes.js';
import * as Digest from './hashes/digest.js';
import * as varint from './varint.js';
// This way TS will also expose all the types from module
export * from './link/interface.js';
export function format(link, base) {
    const { bytes, version } = link;
    switch (version) {
        case 0:
            return toStringV0(bytes, baseCache(link), base ?? base58btc.encoder);
        default:
            return toStringV1(bytes, baseCache(link), (base ?? base32.encoder));
    }
}
export function toJSON(link) {
    return {
        '/': format(link)
    };
}
export function fromJSON(json) {
    return CID.parse(json['/']);
}
const cache = new WeakMap();
function baseCache(cid) {
    const baseCache = cache.get(cid);
    if (baseCache == null) {
        const baseCache = new Map();
        cache.set(cid, baseCache);
        return baseCache;
    }
    return baseCache;
}
export class CID {
    code;
    version;
    multihash;
    bytes;
    '/';
    /**
     * @param version - Version of the CID
     * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
     * @param multihash - (Multi)hash of the of the content.
     */
    constructor(version, code, multihash, bytes) {
        this.code = code;
        this.version = version;
        this.multihash = multihash;
        this.bytes = bytes;
        // flag to serializers that this is a CID and
        // should be treated specially
        this['/'] = bytes;
    }
    /**
     * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`
     * please either use `CID.asCID(cid)` or switch to new signalling mechanism
     *
     * @deprecated
     */
    get asCID() {
        return this;
    }
    // ArrayBufferView
    get byteOffset() {
        return this.bytes.byteOffset;
    }
    // ArrayBufferView
    get byteLength() {
        return this.bytes.byteLength;
    }
    toV0() {
        switch (this.version) {
            case 0: {
                return this;
            }
            case 1: {
                const { code, multihash } = this;
                if (code !== DAG_PB_CODE) {
                    throw new Error('Cannot convert a non dag-pb CID to CIDv0');
                }
                // sha2-256
                if (multihash.code !== SHA_256_CODE) {
                    throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0');
                }
                return (CID.createV0(multihash));
            }
            default: {
                throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);
            }
        }
    }
    toV1() {
        switch (this.version) {
            case 0: {
                const { code, digest } = this.multihash;
                const multihash = Digest.create(code, digest);
                return (CID.createV1(this.code, multihash));
            }
            case 1: {
                return this;
            }
            default: {
                throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);
            }
        }
    }
    equals(other) {
        return CID.equals(this, other);
    }
    static equals(self, other) {
        const unknown = other;
        return (unknown != null &&
            self.code === unknown.code &&
            self.version === unknown.version &&
            Digest.equals(self.multihash, unknown.multihash));
    }
    toString(base) {
        return format(this, base);
    }
    toJSON() {
        return { '/': format(this) };
    }
    link() {
        return this;
    }
    [Symbol.toStringTag] = 'CID';
    // Legacy
    [Symbol.for('nodejs.util.inspect.custom')]() {
        return `CID(${this.toString()})`;
    }
    /**
     * Takes any input `value` and returns a `CID` instance if it was
     * a `CID` otherwise returns `null`. If `value` is instanceof `CID`
     * it will return value back. If `value` is not instance of this CID
     * class, but is compatible CID it will return new instance of this
     * `CID` class. Otherwise returns null.
     *
     * This allows two different incompatible versions of CID library to
     * co-exist and interop as long as binary interface is compatible.
     */
    static asCID(input) {
        if (input == null) {
            return null;
        }
        const value = input;
        if (value instanceof CID) {
            // If value is instance of CID then we're all set.
            return value;
        }
        else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {
            // If value isn't instance of this CID class but `this.asCID === this` or
            // `value['/'] === value.bytes` is true it is CID instance coming from a
            // different implementation (diff version or duplicate). In that case we
            // rebase it to this `CID` implementation so caller is guaranteed to get
            // instance with expected API.
            const { version, code, multihash, bytes } = value;
            return new CID(version, code, multihash, bytes ?? encodeCID(version, code, multihash.bytes));
        }
        else if (value[cidSymbol] === true) {
            // If value is a CID from older implementation that used to be tagged via
            // symbol we still rebase it to the this `CID` implementation by
            // delegating that to a constructor.
            const { version, multihash, code } = value;
            const digest = Digest.decode(multihash);
            return CID.create(version, code, digest);
        }
        else {
            // Otherwise value is not a CID (or an incompatible version of it) in
            // which case we return `null`.
            return null;
        }
    }
    /**
     * @param version - Version of the CID
     * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
     * @param digest - (Multi)hash of the of the content.
     */
    static create(version, code, digest) {
        if (typeof code !== 'number') {
            throw new Error('String codecs are no longer supported');
        }
        if (!(digest.bytes instanceof Uint8Array)) {
            throw new Error('Invalid digest');
        }
        switch (version) {
            case 0: {
                if (code !== DAG_PB_CODE) {
                    throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);
                }
                else {
                    return new CID(version, code, digest, digest.bytes);
                }
            }
            case 1: {
                const bytes = encodeCID(version, code, digest.bytes);
                return new CID(version, code, digest, bytes);
            }
            default: {
                throw new Error('Invalid version');
            }
        }
    }
    /**
     * Simplified version of `create` for CIDv0.
     */
    static createV0(digest) {
        return CID.create(0, DAG_PB_CODE, digest);
    }
    /**
     * Simplified version of `create` for CIDv1.
     *
     * @param code - Content encoding format code.
     * @param digest - Multihash of the content.
     */
    static createV1(code, digest) {
        return CID.create(1, code, digest);
    }
    /**
     * Decoded a CID from its binary representation. The byte array must contain
     * only the CID with no additional bytes.
     *
     * An error will be thrown if the bytes provided do not contain a valid
     * binary representation of a CID.
     */
    static decode(bytes) {
        const [cid, remainder] = CID.decodeFirst(bytes);
        if (remainder.length !== 0) {
            throw new Error('Incorrect length');
        }
        return cid;
    }
    /**
     * Decoded a CID from its binary representation at the beginning of a byte
     * array.
     *
     * Returns an array with the first element containing the CID and the second
     * element containing the remainder of the original byte array. The remainder
     * will be a zero-length byte array if the provided bytes only contained a
     * binary CID representation.
     */
    static decodeFirst(bytes) {
        const specs = CID.inspectBytes(bytes);
        const prefixSize = specs.size - specs.multihashSize;
        const multihashBytes = coerce(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));
        if (multihashBytes.byteLength !== specs.multihashSize) {
            throw new Error('Incorrect length');
        }
        const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);
        const digest = new Digest.Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);
        const cid = specs.version === 0
            ? CID.createV0(digest)
            : CID.createV1(specs.codec, digest);
        return [cid, bytes.subarray(specs.size)];
    }
    /**
     * Inspect the initial bytes of a CID to determine its properties.
     *
     * Involves decoding up to 4 varints. Typically this will require only 4 to 6
     * bytes but for larger multicodec code values and larger multihash digest
     * lengths these varints can be quite large. It is recommended that at least
     * 10 bytes be made available in the `initialBytes` argument for a complete
     * inspection.
     */
    static inspectBytes(initialBytes) {
        let offset = 0;
        const next = () => {
            const [i, length] = varint.decode(initialBytes.subarray(offset));
            offset += length;
            return i;
        };
        let version = next();
        let codec = DAG_PB_CODE;
        if (version === 18) {
            // CIDv0
            version = 0;
            offset = 0;
        }
        else {
            codec = next();
        }
        if (version !== 0 && version !== 1) {
            throw new RangeError(`Invalid CID version ${version}`);
        }
        const prefixSize = offset;
        const multihashCode = next(); // multihash code
        const digestSize = next(); // multihash length
        const size = offset + digestSize;
        const multihashSize = size - prefixSize;
        return { version, codec, multihashCode, digestSize, multihashSize, size };
    }
    /**
     * Takes cid in a string representation and creates an instance. If `base`
     * decoder is not provided will use a default from the configuration. It will
     * throw an error if encoding of the CID is not compatible with supplied (or
     * a default decoder).
     */
    static parse(source, base) {
        const [prefix, bytes] = parseCIDtoBytes(source, base);
        const cid = CID.decode(bytes);
        if (cid.version === 0 && source[0] !== 'Q') {
            throw Error('Version 0 CID string must not include multibase prefix');
        }
        // Cache string representation to avoid computing it on `this.toString()`
        baseCache(cid).set(prefix, source);
        return cid;
    }
}
function parseCIDtoBytes(source, base) {
    switch (source[0]) {
        // CIDv0 is parsed differently
        case 'Q': {
            const decoder = base ?? base58btc;
            return [
                base58btc.prefix,
                decoder.decode(`${base58btc.prefix}${source}`)
            ];
        }
        case base58btc.prefix: {
            const decoder = base ?? base58btc;
            return [base58btc.prefix, decoder.decode(source)];
        }
        case base32.prefix: {
            const decoder = base ?? base32;
            return [base32.prefix, decoder.decode(source)];
        }
        case base36.prefix: {
            const decoder = base ?? base36;
            return [base36.prefix, decoder.decode(source)];
        }
        default: {
            if (base == null) {
                throw Error('To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided');
            }
            return [source[0], base.decode(source)];
        }
    }
}
function toStringV0(bytes, cache, base) {
    const { prefix } = base;
    if (prefix !== base58btc.prefix) {
        throw Error(`Cannot string encode V0 in ${base.name} encoding`);
    }
    const cid = cache.get(prefix);
    if (cid == null) {
        const cid = base.encode(bytes).slice(1);
        cache.set(prefix, cid);
        return cid;
    }
    else {
        return cid;
    }
}
function toStringV1(bytes, cache, base) {
    const { prefix } = base;
    const cid = cache.get(prefix);
    if (cid == null) {
        const cid = base.encode(bytes);
        cache.set(prefix, cid);
        return cid;
    }
    else {
        return cid;
    }
}
const DAG_PB_CODE = 0x70;
const SHA_256_CODE = 0x12;
function encodeCID(version, code, multihash) {
    const codeOffset = varint.encodingLength(version);
    const hashOffset = codeOffset + varint.encodingLength(code);
    const bytes = new Uint8Array(hashOffset + multihash.byteLength);
    varint.encodeTo(version, bytes, 0);
    varint.encodeTo(code, bytes, codeOffset);
    bytes.set(multihash, hashOffset);
    return bytes;
}
const cidSymbol = Symbol.for('@ipld/js-cid/CID');
//# sourceMappingURL=cid.js.mapimport { coerce, equals as equalBytes } from '../bytes.js';
import * as varint from '../varint.js';
/**
 * Creates a multihash digest.
 */
export function create(code, digest) {
    const size = digest.byteLength;
    const sizeOffset = varint.encodingLength(code);
    const digestOffset = sizeOffset + varint.encodingLength(size);
    const bytes = new Uint8Array(digestOffset + size);
    varint.encodeTo(code, bytes, 0);
    varint.encodeTo(size, bytes, sizeOffset);
    bytes.set(digest, digestOffset);
    return new Digest(code, size, digest, bytes);
}
/**
 * Turns bytes representation of multihash digest into an instance.
 */
export function decode(multihash) {
    const bytes = coerce(multihash);
    const [code, sizeOffset] = varint.decode(bytes);
    const [size, digestOffset] = varint.decode(bytes.subarray(sizeOffset));
    const digest = bytes.subarray(sizeOffset + digestOffset);
    if (digest.byteLength !== size) {
        throw new Error('Incorrect length');
    }
    return new Digest(code, size, digest, bytes);
}
export function equals(a, b) {
    if (a === b) {
        return true;
    }
    else {
        const data = b;
        return (a.code === data.code &&
            a.size === data.size &&
            data.bytes instanceof Uint8Array &&
            equalBytes(a.bytes, data.bytes));
    }
}
/**
 * Represents a multihash digest which carries information about the
 * hashing algorithm and an actual hash digest.
 */
export class Digest {
    code;
    size;
    digest;
    bytes;
    /**
     * Creates a multihash digest.
     */
    constructor(code, size, digest, bytes) {
        this.code = code;
        this.size = size;
        this.digest = digest;
        this.bytes = bytes;
    }
}
/**
 * Used to check that the passed multihash has the passed code
 */
export function hasCode(digest, code) {
    return digest.code === code;
}
//# sourceMappingURL=digest.js.mapexport {};
//# sourceMappingURL=interface.js.mapimport varint from './vendor/varint.js';
export function decode(data, offset = 0) {
    const code = varint.decode(data, offset);
    return [code, varint.decode.bytes];
}
export function encodeTo(int, target, offset = 0) {
    varint.encode(int, target, offset);
    return target;
}
export function encodingLength(int) {
    return varint.encodingLength(int);
}
//# sourceMappingURL=varint.js.map/* eslint-disable */
// base-x encoding / decoding
// Copyright (c) 2018 base-x contributors
// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)
// Distributed under the MIT software license, see the accompanying
// file LICENSE or http://www.opensource.org/licenses/mit-license.php.
/**
 * @param {string} ALPHABET
 * @param {any} name
 */
function base(ALPHABET, name) {
    if (ALPHABET.length >= 255) {
        throw new TypeError('Alphabet too long');
    }
    var BASE_MAP = new Uint8Array(256);
    for (var j = 0; j < BASE_MAP.length; j++) {
        BASE_MAP[j] = 255;
    }
    for (var i = 0; i < ALPHABET.length; i++) {
        var x = ALPHABET.charAt(i);
        var xc = x.charCodeAt(0);
        if (BASE_MAP[xc] !== 255) {
            throw new TypeError(x + ' is ambiguous');
        }
        BASE_MAP[xc] = i;
    }
    var BASE = ALPHABET.length;
    var LEADER = ALPHABET.charAt(0);
    var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up
    var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up
    /**
     * @param {any[] | Iterable<number>} source
     */
    function encode(source) {
        // @ts-ignore
        if (source instanceof Uint8Array)
            ;
        else if (ArrayBuffer.isView(source)) {
            source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
        }
        else if (Array.isArray(source)) {
            source = Uint8Array.from(source);
        }
        if (!(source instanceof Uint8Array)) {
            throw new TypeError('Expected Uint8Array');
        }
        if (source.length === 0) {
            return '';
        }
        // Skip & count leading zeroes.
        var zeroes = 0;
        var length = 0;
        var pbegin = 0;
        var pend = source.length;
        while (pbegin !== pend && source[pbegin] === 0) {
            pbegin++;
            zeroes++;
        }
        // Allocate enough space in big-endian base58 representation.
        var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;
        var b58 = new Uint8Array(size);
        // Process the bytes.
        while (pbegin !== pend) {
            var carry = source[pbegin];
            // Apply "b58 = b58 * 256 + ch".
            var i = 0;
            for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {
                carry += (256 * b58[it1]) >>> 0;
                b58[it1] = (carry % BASE) >>> 0;
                carry = (carry / BASE) >>> 0;
            }
            if (carry !== 0) {
                throw new Error('Non-zero carry');
            }
            length = i;
            pbegin++;
        }
        // Skip leading zeroes in base58 result.
        var it2 = size - length;
        while (it2 !== size && b58[it2] === 0) {
            it2++;
        }
        // Translate the result into a string.
        var str = LEADER.repeat(zeroes);
        for (; it2 < size; ++it2) {
            str += ALPHABET.charAt(b58[it2]);
        }
        return str;
    }
    /**
     * @param {string | string[]} source
     */
    function decodeUnsafe(source) {
        if (typeof source !== 'string') {
            throw new TypeError('Expected String');
        }
        if (source.length === 0) {
            return new Uint8Array();
        }
        var psz = 0;
        // Skip leading spaces.
        if (source[psz] === ' ') {
            return;
        }
        // Skip and count leading '1's.
        var zeroes = 0;
        var length = 0;
        while (source[psz] === LEADER) {
            zeroes++;
            psz++;
        }
        // Allocate enough space in big-endian base256 representation.
        var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.
        var b256 = new Uint8Array(size);
        // Process the characters.
        while (source[psz]) {
            // Decode character
            var carry = BASE_MAP[source.charCodeAt(psz)];
            // Invalid character
            if (carry === 255) {
                return;
            }
            var i = 0;
            for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {
                carry += (BASE * b256[it3]) >>> 0;
                b256[it3] = (carry % 256) >>> 0;
                carry = (carry / 256) >>> 0;
            }
            if (carry !== 0) {
                throw new Error('Non-zero carry');
            }
            length = i;
            psz++;
        }
        // Skip trailing spaces.
        if (source[psz] === ' ') {
            return;
        }
        // Skip leading zeroes in b256.
        var it4 = size - length;
        while (it4 !== size && b256[it4] === 0) {
            it4++;
        }
        var vch = new Uint8Array(zeroes + (size - it4));
        var j = zeroes;
        while (it4 !== size) {
            vch[j++] = b256[it4++];
        }
        return vch;
    }
    /**
     * @param {string | string[]} string
     */
    function decode(string) {
        var buffer = decodeUnsafe(string);
        if (buffer) {
            return buffer;
        }
        throw new Error(`Non-${name} character`);
    }
    return {
        encode: encode,
        decodeUnsafe: decodeUnsafe,
        decode: decode
    };
}
var src = base;
var _brrp__multiformats_scope_baseX = src;
export default _brrp__multiformats_scope_baseX;
//# sourceMappingURL=base-x.js.map/* eslint-disable */
var encode_1 = encode;
var MSB = 0x80, REST = 0x7F, MSBALL = ~REST, INT = Math.pow(2, 31);
/**
 * @param {number} num
 * @param {number[]} out
 * @param {number} offset
 */
function encode(num, out, offset) {
    out = out || [];
    offset = offset || 0;
    var oldOffset = offset;
    while (num >= INT) {
        out[offset++] = (num & 0xFF) | MSB;
        num /= 128;
    }
    while (num & MSBALL) {
        out[offset++] = (num & 0xFF) | MSB;
        num >>>= 7;
    }
    out[offset] = num | 0;
    // @ts-ignore
    encode.bytes = offset - oldOffset + 1;
    return out;
}
var decode = read;
var MSB$1 = 0x80, REST$1 = 0x7F;
/**
 * @param {string | any[]} buf
 * @param {number} offset
 */
function read(buf, offset) {
    var res = 0, offset = offset || 0, shift = 0, counter = offset, b, l = buf.length;
    do {
        if (counter >= l) {
            // @ts-ignore
            read.bytes = 0;
            throw new RangeError('Could not decode varint');
        }
        b = buf[counter++];
        res += shift < 28
            ? (b & REST$1) << shift
            : (b & REST$1) * Math.pow(2, shift);
        shift += 7;
    } while (b >= MSB$1);
    // @ts-ignore
    read.bytes = counter - offset;
    return res;
}
var N1 = Math.pow(2, 7);
var N2 = Math.pow(2, 14);
var N3 = Math.pow(2, 21);
var N4 = Math.pow(2, 28);
var N5 = Math.pow(2, 35);
var N6 = Math.pow(2, 42);
var N7 = Math.pow(2, 49);
var N8 = Math.pow(2, 56);
var N9 = Math.pow(2, 63);
var length = function (/** @type {number} */ value) {
    return (value < N1 ? 1
        : value < N2 ? 2
            : value < N3 ? 3
                : value < N4 ? 4
                    : value < N5 ? 5
                        : value < N6 ? 6
                            : value < N7 ? 7
                                : value < N8 ? 8
                                    : value < N9 ? 9
                                        : 10);
};
var varint = {
    encode: encode_1,
    decode: decode,
    encodingLength: length
};
var _brrp_varint = varint;
export default _brrp_varint;
//# sourceMappingURL=varint.js.map{
  "name": "multiformats",
  "version": "13.4.2",
  "description": "Interface for multihash, multicodec, multibase and CID",
  "author": "Mikeal Rogers <mikeal.rogers@gmail.com> (https://www.mikealrogers.com/)",
  "license": "Apache-2.0 OR MIT",
  "homepage": "https://github.com/multiformats/js-multiformats#readme",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/multiformats/js-multiformats.git"
  },
  "bugs": {
    "url": "https://github.com/multiformats/js-multiformats/issues"
  },
  "publishConfig": {
    "access": "public",
    "provenance": true
  },
  "keywords": [
    "ipfs",
    "ipld",
    "multiformats"
  ],
  "type": "module",
  "types": "./dist/src/index.d.ts",
  "typesVersions": {
    "*": {
      "*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ],
      "src/*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ]
    }
  },
  "files": [
    "src",
    "dist",
    "!dist/test",
    "!**/*.tsbuildinfo"
  ],
  "exports": {
    ".": {
      "types": "./dist/src/index.d.ts",
      "import": "./dist/src/index.js"
    },
    "./bases/base10": {
      "types": "./dist/src/bases/base10.d.ts",
      "import": "./dist/src/bases/base10.js"
    },
    "./bases/base16": {
      "types": "./dist/src/bases/base16.d.ts",
      "import": "./dist/src/bases/base16.js"
    },
    "./bases/base2": {
      "types": "./dist/src/bases/base2.d.ts",
      "import": "./dist/src/bases/base2.js"
    },
    "./bases/base256emoji": {
      "types": "./dist/src/bases/base256emoji.d.ts",
      "import": "./dist/src/bases/base256emoji.js"
    },
    "./bases/base32": {
      "types": "./dist/src/bases/base32.d.ts",
      "import": "./dist/src/bases/base32.js"
    },
    "./bases/base36": {
      "types": "./dist/src/bases/base36.d.ts",
      "import": "./dist/src/bases/base36.js"
    },
    "./bases/base58": {
      "types": "./dist/src/bases/base58.d.ts",
      "import": "./dist/src/bases/base58.js"
    },
    "./bases/base64": {
      "types": "./dist/src/bases/base64.d.ts",
      "import": "./dist/src/bases/base64.js"
    },
    "./bases/base8": {
      "types": "./dist/src/bases/base8.d.ts",
      "import": "./dist/src/bases/base8.js"
    },
    "./bases/identity": {
      "types": "./dist/src/bases/identity.d.ts",
      "import": "./dist/src/bases/identity.js"
    },
    "./bases/interface": {
      "types": "./dist/src/bases/interface.d.ts",
      "import": "./dist/src/bases/interface.js"
    },
    "./basics": {
      "types": "./dist/src/basics.d.ts",
      "import": "./dist/src/basics.js"
    },
    "./block": {
      "types": "./dist/src/block.d.ts",
      "import": "./dist/src/block.js"
    },
    "./block/interface": {
      "types": "./dist/src/block/interface.d.ts",
      "import": "./dist/src/block/interface.js"
    },
    "./bytes": {
      "types": "./dist/src/bytes.d.ts",
      "import": "./dist/src/bytes.js"
    },
    "./cid": {
      "types": "./dist/src/cid.d.ts",
      "import": "./dist/src/cid.js"
    },
    "./codecs/interface": {
      "types": "./dist/src/codecs/interface.d.ts",
      "import": "./dist/src/codecs/interface.js"
    },
    "./codecs/json": {
      "types": "./dist/src/codecs/json.d.ts",
      "import": "./dist/src/codecs/json.js"
    },
    "./codecs/raw": {
      "types": "./dist/src/codecs/raw.d.ts",
      "import": "./dist/src/codecs/raw.js"
    },
    "./hashes/digest": {
      "types": "./dist/src/hashes/digest.d.ts",
      "import": "./dist/src/hashes/digest.js"
    },
    "./hashes/hasher": {
      "types": "./dist/src/hashes/hasher.d.ts",
      "import": "./dist/src/hashes/hasher.js"
    },
    "./hashes/identity": {
      "types": "./dist/src/hashes/identity.d.ts",
      "import": "./dist/src/hashes/identity.js"
    },
    "./hashes/interface": {
      "types": "./dist/src/hashes/interface.d.ts",
      "import": "./dist/src/hashes/interface.js"
    },
    "./hashes/sha1": {
      "types": "./dist/types/src/hashes/sha1.d.ts",
      "browser": "./dist/src/hashes/sha1-browser.js",
      "import": "./dist/src/hashes/sha1.js"
    },
    "./hashes/sha2": {
      "types": "./dist/src/hashes/sha2.d.ts",
      "browser": "./dist/src/hashes/sha2-browser.js",
      "import": "./dist/src/hashes/sha2.js"
    },
    "./interface": {
      "types": "./dist/src/interface.d.ts",
      "import": "./dist/src/interface.js"
    },
    "./link": {
      "types": "./dist/src/link.d.ts",
      "import": "./dist/src/link.js"
    },
    "./link/interface": {
      "types": "./dist/src/link/interface.d.ts",
      "import": "./dist/src/link/interface.js"
    },
    "./traversal": {
      "types": "./dist/src/traversal.d.ts",
      "import": "./dist/src/traversal.js"
    }
  },
  "eslintConfig": {
    "extends": "ipfs",
    "parserOptions": {
      "project": true,
      "sourceType": "module"
    }
  },
  "release": {
    "branches": [
      "master"
    ],
    "plugins": [
      [
        "@semantic-release/commit-analyzer",
        {
          "preset": "conventionalcommits",
          "releaseRules": [
            {
              "breaking": true,
              "release": "major"
            },
            {
              "revert": true,
              "release": "patch"
            },
            {
              "type": "feat",
              "release": "minor"
            },
            {
              "type": "fix",
              "release": "patch"
            },
            {
              "type": "docs",
              "release": "patch"
            },
            {
              "type": "test",
              "release": "patch"
            },
            {
              "type": "deps",
              "release": "patch"
            },
            {
              "scope": "no-release",
              "release": false
            }
          ]
        }
      ],
      [
        "@semantic-release/release-notes-generator",
        {
          "preset": "conventionalcommits",
          "presetConfig": {
            "types": [
              {
                "type": "feat",
                "section": "Features"
              },
              {
                "type": "fix",
                "section": "Bug Fixes"
              },
              {
                "type": "chore",
                "section": "Trivial Changes"
              },
              {
                "type": "docs",
                "section": "Documentation"
              },
              {
                "type": "deps",
                "section": "Dependencies"
              },
              {
                "type": "test",
                "section": "Tests"
              }
            ]
          }
        }
      ],
      "@semantic-release/changelog",
      "@semantic-release/npm",
      "@semantic-release/github",
      [
        "@semantic-release/git",
        {
          "assets": [
            "CHANGELOG.md",
            "package.json"
          ]
        }
      ]
    ]
  },
  "scripts": {
    "clean": "aegir clean",
    "lint": "aegir lint",
    "build": "aegir build",
    "release": "aegir release",
    "docs": "aegir docs",
    "test": "npm run lint && npm run test:node && npm run test:chrome",
    "test:node": "aegir test -t node --cov",
    "test:chrome": "aegir test -t browser --cov",
    "test:chrome-webworker": "aegir test -t webworker",
    "test:firefox": "aegir test -t browser -- --browser firefox",
    "test:firefox-webworker": "aegir test -t webworker -- --browser firefox",
    "test:electron-main": "aegir test -t electron-main"
  },
  "devDependencies": {
    "@stablelib/sha256": "^2.0.0",
    "@stablelib/sha512": "^2.0.0",
    "@types/node": "^25.0.0",
    "aegir": "^47.0.7",
    "buffer": "^6.0.3",
    "cids": "^1.1.9",
    "crypto-hash": "^4.0.0"
  },
  "aegir": {
    "test": {
      "target": [
        "node",
        "browser"
      ]
    }
  },
  "browser": {
    "./hashes/sha1": "./dist/src/hashes/sha1-browser.js",
    "./dist/src/hashes/sha1.js": "./dist/src/hashes/sha1-browser.js",
    "./hashes/sha2": "./dist/src/hashes/sha2-browser.js",
    "./dist/src/hashes/sha2.js": "./dist/src/hashes/sha2-browser.js"
  }
}
var queueTick = require('queue-tick')

var mutexify = function () {
  var queue = []
  var used = null

  var call = function () {
    used(release)
  }

  var acquire = function (fn) {
    if (used) return queue.push(fn)
    used = fn
    acquire.locked = true
    queueTick(call)
    return 0
  }

  acquire.locked = false

  var release = function (fn, err, value) {
    used = null
    acquire.locked = false
    if (queue.length) acquire(queue.shift())
    if (fn) fn(err, value)
  }

  return acquire
}

module.exports = mutexify
{
  "name": "mutexify",
  "version": "1.4.0",
  "description": "mutex lock for javascript",
  "main": "index.js",
  "dependencies": {
    "queue-tick": "^1.0.0"
  },
  "devDependencies": {
    "standard": "^14.3.3",
    "tape": "^3.0.2"
  },
  "scripts": {
    "test": "tape test.js",
    "posttest": "npm run lint",
    "lint": "standard"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/mutexify.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/mutexify/issues"
  },
  "keywords": [
    "mutex",
    "lock"
  ],
  "homepage": "https://github.com/mafintosh/mutexify"
}
var mutexify = require('.')

var mutexifyPromise = function () {
  var lock = mutexify()

  var acquire = function () {
    return new Promise(lock)
  }

  Object.defineProperty(acquire, 'locked', {
    get: function () { return lock.locked },
    enumerable: true
  })

  return acquire
}

module.exports = mutexifyPromise
module.exports = assert

class AssertionError extends Error {}
AssertionError.prototype.name = 'AssertionError'

/**
 * Minimal assert function
 * @param  {any} t Value to check if falsy
 * @param  {string=} m Optional assertion error message
 * @throws {AssertionError}
 */
function assert (t, m) {
  if (!t) {
    var err = new AssertionError(m)
    if (Error.captureStackTrace) Error.captureStackTrace(err, assert)
    throw err
  }
}
{
  "name": "nanoassert",
  "version": "2.0.0",
  "description": "Nanoscale assertion module",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "tape": "^4.9.1"
  },
  "scripts": {
    "test": "tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/emilbayes/nanoassert.git"
  },
  "keywords": [
    "assert",
    "unassert",
    "power-assert",
    "tiny",
    "nano",
    "pico"
  ],
  "author": "Emil Bay <github@tixz.dk>",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/emilbayes/nanoassert/issues"
  },
  "homepage": "https://github.com/emilbayes/nanoassert#readme"
}
/* eslint-disable camelcase */
const sodium = require('sodium-universal')
const assert = require('nanoassert')
const b4a = require('b4a')

const DHLEN = sodium.crypto_scalarmult_ed25519_BYTES
const PKLEN = sodium.crypto_scalarmult_ed25519_BYTES
const SCALARLEN = sodium.crypto_scalarmult_ed25519_BYTES
const SKLEN = sodium.crypto_sign_SECRETKEYBYTES
const ALG = 'Ed25519'

module.exports = {
  DHLEN,
  PKLEN,
  SCALARLEN,
  SKLEN,
  ALG,
  name: ALG,
  generateKeyPair,
  dh
}

function generateKeyPair (privKey) {
  if (privKey) return generateSeedKeyPair(privKey.subarray(0, 32))

  const keyPair = {}
  keyPair.secretKey = b4a.alloc(SKLEN)
  keyPair.publicKey = b4a.alloc(PKLEN)

  sodium.crypto_sign_keypair(keyPair.publicKey, keyPair.secretKey)
  return keyPair
}

function generateSeedKeyPair (seed) {
  const keyPair = {}
  keyPair.secretKey = b4a.alloc(SKLEN)
  keyPair.publicKey = b4a.alloc(PKLEN)

  sodium.crypto_sign_seed_keypair(keyPair.publicKey, keyPair.secretKey, seed)
  return keyPair
}

function dh (publicKey, { scalar, secretKey }) {
  // tweaked keys expose scalar directly
  if (!scalar) {
    assert(secretKey.byteLength === SKLEN)

    // libsodium stores seed not actual scalar
    const sk = b4a.alloc(64)
    sodium.crypto_hash_sha512(sk, secretKey.subarray(0, 32))
    sk[0] &= 248
    sk[31] &= 127
    sk[31] |= 64

    scalar = sk.subarray(0, 32)
  }

  assert(scalar.byteLength === SCALARLEN)
  assert(publicKey.byteLength === PKLEN)

  const output = b4a.alloc(DHLEN)

  // we clamp if necessary above
  sodium.crypto_scalarmult_ed25519_noclamp(
    output,
    scalar,
    publicKey
  )

  return output
}
{
  "name": "noise-curve-ed",
  "version": "2.1.0",
  "description": "Ed25519 elliptic curve operations for [`noise-handshake`](https://github.com/chm-diederichs/noise-handshake)",
  "main": "index.js",
  "scripts": {
    "test": "npx standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/chm-diederichs/noise-curve-ed.git"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/chm-diederichs/noise-curve-ed/issues"
  },
  "homepage": "https://github.com/chm-diederichs/noise-curve-ed#readme",
  "dependencies": {
    "b4a": "^1.1.0",
    "nanoassert": "^2.0.0",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "noise-handshake": "^3.0.0",
    "standard": "^16.0.3",
    "tape": "^5.2.2"
  }
}
const sodium = require('sodium-universal')
const b4a = require('b4a')

module.exports = class CipherState {
  constructor (key) {
    this.key = key || null
    this.nonce = 0
    this.CIPHER_ALG = 'ChaChaPoly'
  }

  initialiseKey (key) {
    this.key = key
    this.nonce = 0
  }

  setNonce (nonce) {
    this.nonce = nonce
  }

  encrypt (plaintext, ad) {
    if (!this.hasKey) return plaintext
    if (!ad) ad = b4a.alloc(0)

    const ciphertext = encryptWithAD(this.key, this.nonce, ad, plaintext)
    if (ciphertext.length > 65535) throw new Error(`ciphertext length of ${ciphertext.length} exceeds maximum Noise message length of 65535`)
    this.nonce++

    return ciphertext
  }

  decrypt (ciphertext, ad) {
    if (!this.hasKey) return ciphertext
    if (!ad) ad = b4a.alloc(0)
    if (ciphertext.length > 65535) throw new Error(`ciphertext length of ${ciphertext.length} exceeds maximum Noise message length of 65535`)

    const plaintext = decryptWithAD(this.key, this.nonce, ad, ciphertext)
    this.nonce++

    return plaintext
  }

  get hasKey () {
    return this.key !== null
  }

  _clear () {
    sodium.sodium_memzero(this.key)
    this.key = null
    this.nonce = null
  }

  static get MACBYTES () {
    return 16
  }

  static get NONCEBYTES () {
    return 8
  }

  static get KEYBYTES () {
    return 32
  }
}

function encryptWithAD (key, counter, additionalData, plaintext) {
  // for our purposes, additionalData will always be a pubkey so we encode from hex
  if (!b4a.isBuffer(additionalData)) additionalData = b4a.from(additionalData, 'hex')
  if (!b4a.isBuffer(plaintext)) plaintext = b4a.from(plaintext, 'hex')

  const nonce = b4a.alloc(sodium.crypto_aead_chacha20poly1305_ietf_NPUBBYTES)
  const view = new DataView(nonce.buffer, nonce.byteOffset, nonce.byteLength)
  view.setUint32(4, counter, true)

  const ciphertext = b4a.alloc(plaintext.byteLength + sodium.crypto_aead_chacha20poly1305_ietf_ABYTES)

  sodium.crypto_aead_chacha20poly1305_ietf_encrypt(ciphertext, plaintext, additionalData, null, nonce, key)
  return ciphertext
}

function decryptWithAD (key, counter, additionalData, ciphertext) {
  // for our purposes, additionalData will always be a pubkey so we encode from hex
  if (!b4a.isBuffer(additionalData)) additionalData = b4a.from(additionalData, 'hex')
  if (!b4a.isBuffer(ciphertext)) ciphertext = b4a.from(ciphertext, 'hex')

  const nonce = b4a.alloc(sodium.crypto_aead_chacha20poly1305_ietf_NPUBBYTES)
  const view = new DataView(nonce.buffer, nonce.byteOffset, nonce.byteLength)
  view.setUint32(4, counter, true)

  const plaintext = b4a.alloc(ciphertext.byteLength - sodium.crypto_aead_chacha20poly1305_ietf_ABYTES)

  sodium.crypto_aead_chacha20poly1305_ietf_decrypt(plaintext, null, ciphertext, additionalData, nonce, key)
  return plaintext
}
/* eslint-disable camelcase */
const {
  crypto_kx_SEEDBYTES,
  crypto_kx_keypair,
  crypto_kx_seed_keypair,
  crypto_scalarmult_BYTES,
  crypto_scalarmult_SCALARBYTES,
  crypto_scalarmult,
  crypto_scalarmult_base
} = require('sodium-universal')

const assert = require('nanoassert')
const b4a = require('b4a')

const DHLEN = crypto_scalarmult_BYTES
const PKLEN = crypto_scalarmult_BYTES
const SKLEN = crypto_scalarmult_SCALARBYTES
const SEEDLEN = crypto_kx_SEEDBYTES
const ALG = '25519'

module.exports = {
  DHLEN,
  PKLEN,
  SKLEN,
  SEEDLEN,
  ALG,
  generateKeyPair,
  generateSeedKeyPair,
  dh
}

function generateKeyPair (privKey) {
  const keyPair = {}

  keyPair.secretKey = privKey || b4a.alloc(SKLEN)
  keyPair.publicKey = b4a.alloc(PKLEN)

  if (privKey) {
    crypto_scalarmult_base(keyPair.publicKey, keyPair.secretKey)
  } else {
    crypto_kx_keypair(keyPair.publicKey, keyPair.secretKey)
  }

  return keyPair
}

function generateSeedKeyPair (seed) {
  assert(seed.byteLength === SKLEN)

  const keyPair = {}
  keyPair.secretKey = b4a.alloc(SKLEN)
  keyPair.publicKey = b4a.alloc(PKLEN)

  crypto_kx_seed_keypair(keyPair.publicKey, keyPair.secretKey, seed)
  return keyPair
}

function dh (publicKey, { secretKey }) {
  assert(secretKey.byteLength === SKLEN)
  assert(publicKey.byteLength === PKLEN)

  const output = b4a.alloc(DHLEN)

  crypto_scalarmult(
    output,
    secretKey,
    publicKey
  )

  return output
}
const hmacBlake2b = require('./hmac')
const b4a = require('b4a')

const HASHLEN = 64

module.exports = {
  hkdf,
  HASHLEN
}

// HMAC-based Extract-and-Expand KDF
// https://www.ietf.org/rfc/rfc5869.txt

function hkdf (salt, inputKeyMaterial, info = '', length = 2 * HASHLEN) {
  const pseudoRandomKey = hkdfExtract(salt, inputKeyMaterial)
  return hkdfExpand(pseudoRandomKey, info, length)
}

function hkdfExtract (salt, inputKeyMaterial) {
  const hmac = b4a.alloc(HASHLEN)
  return hmacDigest(hmac, salt, inputKeyMaterial)
}

function hkdfExpand (key, info, length) {
  // Put in dedicated slab to avoid keeping shared slab from being gc'ed
  const buffer = b4a.allocUnsafeSlow(length)

  const infoBuf = b4a.from(info)
  let prev = infoBuf

  const result = []
  for (let i = 0; i < length; i += HASHLEN) {
    const pos = b4a.from([(i / HASHLEN) + 1])

    const out = buffer.subarray(i, i + HASHLEN)
    result.push(out)

    prev = hmacDigest(out, key, [prev, infoBuf, pos])
  }

  return result
}

function hmacDigest (out, key, input) {
  hmacBlake2b(out, input, key)
  return out
}
/* eslint-disable camelcase */
const b4a = require('b4a')
const { sodium_memzero, crypto_generichash, crypto_generichash_batch } = require('sodium-universal')

const HASHLEN = 64
const BLOCKLEN = 128
const scratch = b4a.alloc(BLOCKLEN * 3)
const HMACKey = scratch.subarray(BLOCKLEN * 0, BLOCKLEN * 1)
const OuterKeyPad = scratch.subarray(BLOCKLEN * 1, BLOCKLEN * 2)
const InnerKeyPad = scratch.subarray(BLOCKLEN * 2, BLOCKLEN * 3)

// Post-fill is done in the cases where someone caught an exception that
// happened before we were able to clear data at the end

module.exports = function hmac (out, batch, key) {
  if (key.byteLength > BLOCKLEN) {
    crypto_generichash(HMACKey.subarray(0, HASHLEN), key)
    sodium_memzero(HMACKey.subarray(HASHLEN))
  } else {
    // Covers key <= BLOCKLEN
    HMACKey.set(key)
    sodium_memzero(HMACKey.subarray(key.byteLength))
  }

  for (let i = 0; i < HMACKey.byteLength; i++) {
    OuterKeyPad[i] = 0x5c ^ HMACKey[i]
    InnerKeyPad[i] = 0x36 ^ HMACKey[i]
  }
  sodium_memzero(HMACKey)

  crypto_generichash_batch(out, [InnerKeyPad].concat(batch))
  sodium_memzero(InnerKeyPad)
  crypto_generichash_batch(out, [OuterKeyPad, out])
  sodium_memzero(OuterKeyPad)
}

module.exports.BYTES = HASHLEN
module.exports.KEYBYTES = BLOCKLEN
const assert = require('nanoassert')
const b4a = require('b4a')

const SymmetricState = require('./symmetric-state')
const { HASHLEN } = require('./hkdf')

const PRESHARE_IS = Symbol('initiator static key preshared')
const PRESHARE_RS = Symbol('responder static key preshared')

const TOK_PSK = Symbol('psk')

const TOK_S = Symbol('s')
const TOK_E = Symbol('e')

const TOK_ES = Symbol('es')
const TOK_SE = Symbol('se')
const TOK_EE = Symbol('ee')
const TOK_SS = Symbol('ss')

const HANDSHAKES = Object.freeze({
  NN: [
    [TOK_E],
    [TOK_E, TOK_EE]
  ],
  NNpsk0: [
    [TOK_PSK, TOK_E],
    [TOK_E, TOK_EE]
  ],
  XX: [
    [TOK_E],
    [TOK_E, TOK_EE, TOK_S, TOK_ES],
    [TOK_S, TOK_SE]
  ],
  XXpsk0: [
    [TOK_PSK, TOK_E],
    [TOK_E, TOK_EE, TOK_S, TOK_ES],
    [TOK_S, TOK_SE]
  ],
  IK: [
    PRESHARE_RS,
    [TOK_E, TOK_ES, TOK_S, TOK_SS],
    [TOK_E, TOK_EE, TOK_SE]
  ],
  XK: [
    PRESHARE_RS,
    [TOK_E, TOK_ES],
    [TOK_E, TOK_EE],
    [TOK_S, TOK_SE]
  ]
})

class Writer {
  constructor () {
    this.size = 0
    this.buffers = []
  }

  push (b) {
    this.size += b.byteLength
    this.buffers.push(b)
  }

  end () {
    const all = b4a.alloc(this.size)
    let offset = 0
    for (const b of this.buffers) {
      all.set(b, offset)
      offset += b.byteLength
    }
    return all
  }
}

class Reader {
  constructor (buf) {
    this.offset = 0
    this.buffer = buf
  }

  shift (n) {
    const start = this.offset
    const end = this.offset += n
    if (end > this.buffer.byteLength) throw new Error('Insufficient bytes')
    return this.buffer.subarray(start, end)
  }

  end () {
    return this.shift(this.buffer.byteLength - this.offset)
  }
}

module.exports = class NoiseState extends SymmetricState {
  constructor (pattern, initiator, staticKeypair, opts = {}) {
    super(opts)

    this.s = staticKeypair || this.curve.generateKeyPair()
    this.e = null

    this.psk = null
    if (opts && opts.psk) this.psk = opts.psk

    this.re = null
    this.rs = null

    this.pattern = pattern
    this.handshake = HANDSHAKES[this.pattern].slice()

    this.isPskHandshake = !!this.psk && hasPskToken(this.handshake)

    this.protocol = b4a.from([
      'Noise',
      this.pattern,
      this.DH_ALG,
      this.CIPHER_ALG,
      'BLAKE2b'
    ].join('_'))

    this.initiator = initiator
    this.complete = false

    this.rx = null
    this.tx = null
    this.hash = null
  }

  initialise (prologue, remoteStatic) {
    if (this.protocol.byteLength <= HASHLEN) this.digest.set(this.protocol)
    else this.mixHash(this.protocol)

    this.chainingKey = b4a.from(this.digest)

    this.mixHash(prologue)

    while (!Array.isArray(this.handshake[0])) {
      const message = this.handshake.shift()

      // handshake steps should be as arrays, only
      // preshare tokens are provided otherwise
      assert(message === PRESHARE_RS || message === PRESHARE_IS,
        'Unexpected pattern')

      const takeRemoteKey = this.initiator
        ? message === PRESHARE_RS
        : message === PRESHARE_IS

      if (takeRemoteKey) this.rs = remoteStatic

      const key = takeRemoteKey ? this.rs : this.s.publicKey
      assert(key != null, 'Remote pubkey required')

      this.mixHash(key)
    }
  }

  final () {
    const [k1, k2] = this.split()

    this.tx = this.initiator ? k1 : k2
    this.rx = this.initiator ? k2 : k1

    this.complete = true
    this.hash = this.getHandshakeHash()

    this._clear()
  }

  recv (buf) {
    const r = new Reader(buf)

    for (const pattern of this.handshake.shift()) {
      switch (pattern) {
        case TOK_PSK :
          this.mixKeyAndHash(this.psk)
          break

        case TOK_E :
          this.re = r.shift(this.curve.PKLEN)
          this.mixHash(this.re)
          if (this.isPskHandshake) this.mixKeyNormal(this.re)
          break

        case TOK_S : {
          const klen = this.hasKey ? this.curve.PKLEN + 16 : this.curve.PKLEN
          this.rs = this.decryptAndHash(r.shift(klen))
          break
        }

        case TOK_EE :
        case TOK_ES :
        case TOK_SE :
        case TOK_SS : {
          const useStatic = keyPattern(pattern, this.initiator)

          const localKey = useStatic.local ? this.s : this.e
          const remoteKey = useStatic.remote ? this.rs : this.re

          this.mixKey(remoteKey, localKey)
          break
        }

        default :
          throw new Error('Unexpected message')
      }
    }

    const payload = this.decryptAndHash(r.end())

    if (!this.handshake.length) this.final()
    return payload
  }

  send (payload = b4a.alloc(0)) {
    const w = new Writer()

    for (const pattern of this.handshake.shift()) {
      switch (pattern) {
        case TOK_PSK :
          this.mixKeyAndHash(this.psk)
          break

        case TOK_E :
          if (this.e === null) this.e = this.curve.generateKeyPair()
          this.mixHash(this.e.publicKey)
          if (this.isPskHandshake) this.mixKeyNormal(this.e.publicKey)
          w.push(this.e.publicKey)
          break

        case TOK_S :
          w.push(this.encryptAndHash(this.s.publicKey))
          break

        case TOK_ES :
        case TOK_SE :
        case TOK_EE :
        case TOK_SS : {
          const useStatic = keyPattern(pattern, this.initiator)

          const localKey = useStatic.local ? this.s : this.e
          const remoteKey = useStatic.remote ? this.rs : this.re

          this.mixKey(remoteKey, localKey)
          break
        }

        default :
          throw new Error('Unexpected message')
      }
    }

    w.push(this.encryptAndHash(payload))
    const response = w.end()

    if (!this.handshake.length) this.final()
    return response
  }

  _clear () {
    super._clear()

    this.e.secretKey.fill(0)
    this.e.publicKey.fill(0)

    this.re.fill(0)

    this.e = null
    this.re = null
  }
}

function keyPattern (pattern, initiator) {
  const ret = {
    local: false,
    remote: false
  }

  switch (pattern) {
    case TOK_EE:
      return ret

    case TOK_ES:
      ret.local ^= !initiator
      ret.remote ^= initiator
      return ret

    case TOK_SE:
      ret.local ^= initiator
      ret.remote ^= !initiator
      return ret

    case TOK_SS:
      ret.local ^= 1
      ret.remote ^= 1
      return ret
  }
}

function hasPskToken (handshake) {
  return handshake.some(x => {
    return Array.isArray(x) && x.indexOf(TOK_PSK) !== -1
  })
}
{
  "name": "noise-handshake",
  "version": "4.2.0",
  "description": "Noise protocol handshake",
  "main": "noise.js",
  "files": [
    "*.js"
  ],
  "scripts": {
    "test": "standard && brittle test/*.js"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/noise-handshake.git"
  },
  "dependencies": {
    "b4a": "^1.1.0",
    "nanoassert": "^2.0.0",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "noise-protocol": "chm-diederichs/noise-protocol.git#xx-ephemeral-key",
    "standard": "^16.0.3"
  }
}
const sodium = require('sodium-universal')
const assert = require('nanoassert')
const b4a = require('b4a')
const CipherState = require('./cipher')
const curve = require('./dh')
const { HASHLEN, hkdf } = require('./hkdf')

module.exports = class SymmetricState extends CipherState {
  constructor (opts = {}) {
    super()

    this.curve = opts.curve || curve
    this.digest = b4a.alloc(HASHLEN)
    this.chainingKey = null
    this.offset = 0

    this.DH_ALG = this.curve.ALG
  }

  mixHash (data) {
    accumulateDigest(this.digest, data)
  }

  mixKeyAndHash (key) {
    const [ck, tempH, tempK] = hkdf(this.chainingKey, key, '', 3 * HASHLEN)
    this.chainingKey = ck
    this.mixHash(tempH)
    this.initialiseKey(tempK.subarray(0, 32))
  }

  mixKeyNormal (key) {
    const [ck, tempK] = hkdf(this.chainingKey, key)
    this.chainingKey = ck
    this.initialiseKey(tempK.subarray(0, 32))
  }

  mixKey (remoteKey, localKey) {
    const dh = this.curve.dh(remoteKey, localKey)
    const hkdfResult = hkdf(this.chainingKey, dh)
    this.chainingKey = hkdfResult[0]
    this.initialiseKey(hkdfResult[1].subarray(0, 32))
  }

  encryptAndHash (plaintext) {
    const ciphertext = this.encrypt(plaintext, this.digest)
    accumulateDigest(this.digest, ciphertext)
    return ciphertext
  }

  decryptAndHash (ciphertext) {
    const plaintext = this.decrypt(ciphertext, this.digest)
    accumulateDigest(this.digest, ciphertext)
    return plaintext
  }

  getHandshakeHash (out) {
    if (!out) return this.getHandshakeHash(b4a.alloc(HASHLEN))
    assert(out.byteLength === HASHLEN, `output must be ${HASHLEN} bytes`)

    out.set(this.digest)
    return out
  }

  split () {
    const res = hkdf(this.chainingKey, b4a.alloc(0))
    return res.map(k => k.subarray(0, 32))
  }

  _clear () {
    super._clear()

    sodium.sodium_memzero(this.digest)
    sodium.sodium_memzero(this.chainingKey)

    this.digest = null
    this.chainingKey = null
    this.offset = null

    this.curve = null
  }

  static get alg () {
    return CipherState.alg + '_BLAKE2b'
  }
}

function accumulateDigest (digest, input) {
  const toHash = b4a.concat([digest, input])
  sodium.crypto_generichash(digest, toHash)
}
var varint = require('varint')
var svarint = require('signed-varint')
var b4a = require('b4a')

exports.make = encoder

exports.name = function (enc) {
  var keys = Object.keys(exports)
  for (var i = 0; i < keys.length; i++) {
    if (exports[keys[i]] === enc) return keys[i]
  }
  return null
}

exports.skip = function (type, buffer, offset) {
  switch (type) {
    case 0:
      varint.decode(buffer, offset)
      return offset + varint.decode.bytes

    case 1:
      return offset + 8

    case 2:
      var len = varint.decode(buffer, offset)
      return offset + varint.decode.bytes + len

    case 3:
    case 4:
      throw new Error('Groups are not supported')

    case 5:
      return offset + 4
  }

  throw new Error('Unknown wire type: ' + type)
}

exports.bytes = encoder(2,
  function encode (val, buffer, offset) {
    var oldOffset = offset
    var len = bufferLength(val)

    varint.encode(len, buffer, offset)
    offset += varint.encode.bytes

    if (b4a.isBuffer(val)) b4a.copy(val, buffer, offset)
    else b4a.write(buffer, val, offset, len)
    offset += len

    encode.bytes = offset - oldOffset
    return buffer
  },
  function decode (buffer, offset) {
    var oldOffset = offset

    var len = varint.decode(buffer, offset)
    offset += varint.decode.bytes

    var val = buffer.subarray(offset, offset + len)
    offset += val.length

    decode.bytes = offset - oldOffset
    return val
  },
  function encodingLength (val) {
    var len = bufferLength(val)
    return varint.encodingLength(len) + len
  }
)

exports.string = encoder(2,
  function encode (val, buffer, offset) {
    var oldOffset = offset
    var len = b4a.byteLength(val)

    varint.encode(len, buffer, offset, 'utf-8')
    offset += varint.encode.bytes

    b4a.write(buffer, val, offset, len)
    offset += len

    encode.bytes = offset - oldOffset
    return buffer
  },
  function decode (buffer, offset) {
    var oldOffset = offset

    var len = varint.decode(buffer, offset)
    offset += varint.decode.bytes

    var val = b4a.toString(buffer, 'utf-8', offset, offset + len)
    offset += len

    decode.bytes = offset - oldOffset
    return val
  },
  function encodingLength (val) {
    var len = b4a.byteLength(val)
    return varint.encodingLength(len) + len
  }
)

exports.bool = encoder(0,
  function encode (val, buffer, offset) {
    buffer[offset] = val ? 1 : 0
    encode.bytes = 1
    return buffer
  },
  function decode (buffer, offset) {
    var bool = buffer[offset] > 0
    decode.bytes = 1
    return bool
  },
  function encodingLength () {
    return 1
  }
)

exports.int32 = encoder(0,
  function encode (val, buffer, offset) {
    varint.encode(val < 0 ? val + 4294967296 : val, buffer, offset)
    encode.bytes = varint.encode.bytes
    return buffer
  },
  function decode (buffer, offset) {
    var val = varint.decode(buffer, offset)
    decode.bytes = varint.decode.bytes
    return val > 2147483647 ? val - 4294967296 : val
  },
  function encodingLength (val) {
    return varint.encodingLength(val < 0 ? val + 4294967296 : val)
  }
)

exports.int64 = encoder(0,
  function encode (val, buffer, offset) {
    if (val < 0) {
      var last = offset + 9
      varint.encode(val * -1, buffer, offset)
      offset += varint.encode.bytes - 1
      buffer[offset] = buffer[offset] | 0x80
      while (offset < last - 1) {
        offset++
        buffer[offset] = 0xff
      }
      buffer[last] = 0x01
      encode.bytes = 10
    } else {
      varint.encode(val, buffer, offset)
      encode.bytes = varint.encode.bytes
    }
    return buffer
  },
  function decode (buffer, offset) {
    var val = varint.decode(buffer, offset)
    if (val >= Math.pow(2, 63)) {
      var limit = 9
      while (buffer[offset + limit - 1] === 0xff) limit--
      limit = limit || 9
      var subset = b4a.allocUnsafe(limit)
      b4a.copy(buffer, subset, 0, offset, offset + limit)
      subset[limit - 1] = subset[limit - 1] & 0x7f
      val = -1 * varint.decode(subset, 0)
      decode.bytes = 10
    } else {
      decode.bytes = varint.decode.bytes
    }
    return val
  },
  function encodingLength (val) {
    return val < 0 ? 10 : varint.encodingLength(val)
  }
)

exports.sint32 =
exports.sint64 = encoder(0,
  svarint.encode,
  svarint.decode,
  svarint.encodingLength
)

exports.uint32 =
exports.uint64 =
exports.enum =
exports.varint = encoder(0,
  varint.encode,
  varint.decode,
  varint.encodingLength
)

// we cannot represent these in javascript so we just use buffers
exports.fixed64 =
exports.sfixed64 = encoder(1,
  function encode (val, buffer, offset) {
    b4a.copy(val, buffer, offset)
    encode.bytes = 8
    return buffer
  },
  function decode (buffer, offset) {
    var val = buffer.subarray(offset, offset + 8)
    decode.bytes = 8
    return val
  },
  function encodingLength () {
    return 8
  }
)

exports.double = encoder(1,
  function encode (val, buffer, offset) {
    b4a.writeDoubleLE(buffer, val, offset)
    encode.bytes = 8
    return buffer
  },
  function decode (buffer, offset) {
    var val = b4a.readDoubleLE(buffer, offset)
    decode.bytes = 8
    return val
  },
  function encodingLength () {
    return 8
  }
)

exports.fixed32 = encoder(5,
  function encode (val, buffer, offset) {
    b4a.writeUInt32LE(buffer, val, offset)
    encode.bytes = 4
    return buffer
  },
  function decode (buffer, offset) {
    var val = b4a.readUInt32LE(buffer, offset)
    decode.bytes = 4
    return val
  },
  function encodingLength () {
    return 4
  }
)

exports.sfixed32 = encoder(5,
  function encode (val, buffer, offset) {
    b4a.writeInt32LE(buffer, val, offset)
    encode.bytes = 4
    return buffer
  },
  function decode (buffer, offset) {
    var val = b4a.readInt32LE(buffer, offset)
    decode.bytes = 4
    return val
  },
  function encodingLength () {
    return 4
  }
)

exports.float = encoder(5,
  function encode (val, buffer, offset) {
    b4a.writeFloatLE(buffer, val, offset)
    encode.bytes = 4
    return buffer
  },
  function decode (buffer, offset) {
    var val = b4a.readFloatLE(buffer, offset)
    decode.bytes = 4
    return val
  },
  function encodingLength () {
    return 4
  }
)

function encoder (type, encode, decode, encodingLength) {
  encode.bytes = decode.bytes = 0

  return {
    type: type,
    encode: encode,
    decode: decode,
    encodingLength: encodingLength
  }
}

function bufferLength (val) {
  return b4a.isBuffer(val) ? val.length : b4a.byteLength(val)
}
{
  "name": "protocol-buffers-encodings",
  "version": "1.2.0",
  "description": "Base encodings for protocol-buffers",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.6.0",
    "signed-varint": "^2.0.1",
    "varint": "5.0.0"
  },
  "devDependencies": {
    "standard": "^14.3.4",
    "tape": "^5.0.1"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/protocol-buffers-encodings.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/protocol-buffers-encodings/issues"
  },
  "homepage": "https://github.com/mafintosh/protocol-buffers-encodings"
}
const b4a = require('b4a')
const c = require('compact-encoding')
const queueTick = require('queue-tick')
const safetyCatch = require('safety-catch')
const unslab = require('unslab')

const MAX_BUFFERED = 32768
const MAX_BACKLOG = Infinity // TODO: impl "open" backpressure
const MAX_BATCH = 8 * 1024 * 1024

class Channel {
  constructor(
    mux,
    info,
    userData,
    protocol,
    aliases,
    id,
    handshake,
    messages,
    onopen,
    onclose,
    ondestroy,
    ondrain
  ) {
    this.userData = userData
    this.protocol = protocol
    this.aliases = aliases
    this.id = id
    this.handshake = null
    this.messages = []

    this.opened = false
    this.closed = false
    this.destroyed = false

    this.onopen = onopen
    this.onclose = onclose
    this.ondestroy = ondestroy
    this.ondrain = ondrain

    this._handshake = handshake
    this._mux = mux
    this._info = info
    this._localId = 0
    this._remoteId = 0
    this._active = 0
    this._extensions = null

    this._decBound = this._dec.bind(this)
    this._decAndDestroyBound = this._decAndDestroy.bind(this)

    this._openedPromise = null
    this._openedResolve = null

    this._destroyedPromise = null
    this._destroyedResolve = null

    for (const m of messages) this.addMessage(m)
  }

  get drained() {
    return this._mux.drained
  }

  fullyOpened() {
    if (this.opened) return Promise.resolve(true)
    if (this.closed) return Promise.resolve(false)
    if (this._openedPromise) return this._openedPromise

    this._openedPromise = new Promise((resolve) => {
      this._openedResolve = resolve
    })
    return this._openedPromise
  }

  fullyClosed() {
    if (this.destroyed) return Promise.resolve()
    if (this._destroyedPromise) return this._destroyedPromise

    this._destroyedPromise = new Promise((resolve) => {
      this._destroyedResolve = resolve
    })
    return this._destroyedPromise
  }

  open(handshake) {
    const id = this._mux._free.length > 0 ? this._mux._free.pop() : this._mux._local.push(null) - 1

    this._info.opened++
    this._info.lastChannel = this
    this._localId = id + 1
    this._mux._local[id] = this

    if (this._remoteId === 0) {
      this._info.outgoing.push(this._localId)
    }

    const state = { buffer: null, start: 2, end: 2 }

    c.uint.preencode(state, this._localId)
    c.string.preencode(state, this.protocol)
    c.optionalBuffer.preencode(state, this.id)
    if (this._handshake) this._handshake.preencode(state, handshake)

    state.buffer = this._mux._alloc(state.end)

    state.buffer[0] = 0
    state.buffer[1] = 1
    c.uint.encode(state, this._localId)
    c.string.encode(state, this.protocol)
    c.optionalBuffer.encode(state, this.id)
    if (this._handshake) this._handshake.encode(state, handshake)

    this._mux._write0(state.buffer)
  }

  _dec() {
    if (--this._active === 0 && this.closed === true) this._destroy()
  }

  _decAndDestroy(err) {
    this._dec()
    this._mux._safeDestroy(err)
  }

  _fullyOpenSoon() {
    this._mux._remote[this._remoteId - 1].session = this
    queueTick(this._fullyOpenOrDestroy.bind(this))
  }

  _fullyOpenOrDestroy() {
    try {
      this._fullyOpen()
    } catch (err) {
      this._mux._safeDestroyBound(err)
    }
  }

  _fullyOpen() {
    if (this.opened === true || this.closed === true) return

    const remote = this._mux._remote[this._remoteId - 1]

    this.handshake = this._handshake ? this._handshake.decode(remote.state) : null
    this._track(this.onopen(this.handshake, this))

    remote.session = this
    remote.state = null
    if (remote.pending !== null) this._drain(remote)
    if (this._mux._destroying === true) return

    this.opened = true
    this._resolveOpen(true)
  }

  _resolveOpen(opened) {
    if (this._openedResolve !== null) {
      this._openedResolve(opened)
      this._openedResolve = this._openedPromise = null
    }
  }

  _resolveDestroyed() {
    if (this._destroyedResolve !== null) {
      this._destroyedResolve()
      this._destroyedResolve = this._destroyedPromise = null
    }
  }

  _drain(remote) {
    for (let i = 0; i < remote.pending.length; i++) {
      const p = remote.pending[i]
      this._mux._buffered -= byteSize(p.state)
      this._recv(p.type, p.state)
      if (this._mux._destroying === true) return
    }

    remote.pending = null
    this._mux._resumeMaybe()
  }

  _track(p) {
    if (isPromise(p) === true) {
      this._active++
      return p.then(this._decBound, this._decAndDestroyBound)
    }

    return null
  }

  _close(isRemote) {
    if (this.closed === true) return
    this.closed = true

    this._info.opened--
    if (this._info.lastChannel === this) this._info.lastChannel = null

    if (this._remoteId > 0) {
      this._mux._remote[this._remoteId - 1] = null
      this._remoteId = 0
      // If remote has acked, we can reuse the local id now
      // otherwise, we need to wait for the "ack" to arrive
      this._mux._free.push(this._localId - 1)
    }

    this._mux._local[this._localId - 1] = null
    this._localId = 0

    this._mux._gc(this._info)
    this._track(this.onclose(isRemote, this))

    if (this._active === 0) this._destroy()

    this._resolveOpen(false)
  }

  _destroy() {
    if (this.destroyed === true) return
    this.destroyed = true
    this._track(this.ondestroy(this))
    this._resolveDestroyed()
  }

  _recv(type, state) {
    if (type < this.messages.length) {
      const m = this.messages[type]
      const p = m.recv(state, this)
      if (m.autoBatch === true) return p
    }
    return null
  }

  cork() {
    this._mux.cork()
  }

  uncork() {
    this._mux.uncork()
  }

  close() {
    if (this.closed === true) return

    const state = { buffer: null, start: 2, end: 2 }

    c.uint.preencode(state, this._localId)

    state.buffer = this._mux._alloc(state.end)

    state.buffer[0] = 0
    state.buffer[1] = 3
    c.uint.encode(state, this._localId)

    this._close(false)
    this._mux._write0(state.buffer)
  }

  addMessage(opts) {
    if (!opts) return this._skipMessage()

    const type = this.messages.length
    const autoBatch = opts.autoBatch !== false
    const encoding = opts.encoding || c.raw
    const onmessage = opts.onmessage || noop

    const s = this
    const typeLen = encodingLength(c.uint, type)

    const m = {
      type,
      autoBatch,
      encoding,
      onmessage,
      recv(state, session) {
        return session._track(m.onmessage(encoding.decode(state), session))
      },
      send(m, session = s) {
        if (session.closed === true) return false

        const mux = session._mux
        const state = { buffer: null, start: 0, end: typeLen }

        if (mux._batch !== null) {
          encoding.preencode(state, m)
          state.buffer = mux._alloc(state.end)

          c.uint.encode(state, type)
          encoding.encode(state, m)

          mux._pushBatch(session._localId, state.buffer)
          return true
        }

        c.uint.preencode(state, session._localId)
        encoding.preencode(state, m)

        state.buffer = mux._alloc(state.end)

        c.uint.encode(state, session._localId)
        c.uint.encode(state, type)
        encoding.encode(state, m)

        mux.drained = mux.stream.write(state.buffer)

        return mux.drained
      }
    }

    this.messages.push(m)

    return m
  }

  _skipMessage() {
    const type = this.messages.length
    const m = {
      type,
      encoding: c.raw,
      onmessage: noop,
      recv(state, session) {},
      send(m, session) {}
    }

    this.messages.push(m)
    return m
  }
}

module.exports = class Protomux {
  constructor(stream, { alloc } = {}) {
    if (stream.userData === null) stream.userData = this

    this.isProtomux = true
    this.stream = stream
    this.corked = 0
    this.drained = true

    this._alloc =
      alloc || (typeof stream.alloc === 'function' ? stream.alloc.bind(stream) : b4a.allocUnsafe)
    this._safeDestroyBound = this._safeDestroy.bind(this)
    this._uncorkBound = this.uncork.bind(this)

    this._remoteBacklog = 0
    this._buffered = 0
    this._paused = false
    this._remote = []
    this._local = []
    this._free = []
    this._batch = null
    this._batchState = null

    this._infos = new Map()
    this._notify = new Map()
    // stream.destroyed flips asynchronously on streamx-based transports.
    this._destroying = false

    this.stream.on('data', this._ondata.bind(this))
    this.stream.on('drain', this._ondrain.bind(this))
    this.stream.on('end', this._onend.bind(this))
    this.stream.on('error', noop) // we handle this in "close"
    this.stream.on('close', this._shutdown.bind(this))
  }

  static from(stream, opts) {
    if (stream.userData && stream.userData.isProtomux) return stream.userData
    if (stream.isProtomux) return stream
    return new this(stream, opts)
  }

  static isProtomux(mux) {
    return typeof mux === 'object' && mux.isProtomux === true
  }

  *[Symbol.iterator]() {
    for (const session of this._local) {
      if (session !== null) yield session
    }
  }

  isIdle() {
    return this._local.length === this._free.length
  }

  cork() {
    if (++this.corked === 1) {
      this._batch = []
      this._batchState = { buffer: null, start: 0, end: 1 }
    }
  }

  uncork() {
    if (--this.corked === 0) {
      this._sendBatch(this._batch, this._batchState)
      this._batch = null
      this._batchState = null
    }
  }

  getLastChannel({ protocol, id = null }) {
    const key = toKey(protocol, id)
    const info = this._infos.get(key)
    if (info) return info.lastChannel
    return null
  }

  pair({ protocol, id = null }, notify) {
    this._notify.set(toKey(protocol, id), notify)
  }

  unpair({ protocol, id = null }) {
    this._notify.delete(toKey(protocol, id))
  }

  opened({ protocol, id = null }) {
    const key = toKey(protocol, id)
    const info = this._infos.get(key)
    return info ? info.opened > 0 : false
  }

  createChannel({
    userData = null,
    protocol,
    aliases = [],
    id = null,
    unique = true,
    handshake = null,
    messages = [],
    onopen = noop,
    onclose = noop,
    ondestroy = noop,
    ondrain = noop
  }) {
    if (this.stream.destroyed) return null

    const info = this._get(protocol, id, aliases)
    if (unique && info.opened > 0) return null

    if (info.incoming.length === 0) {
      return new Channel(
        this,
        info,
        userData,
        protocol,
        aliases,
        id,
        handshake,
        messages,
        onopen,
        onclose,
        ondestroy,
        ondrain
      )
    }

    this._remoteBacklog--

    const remoteId = info.incoming.shift()
    const r = this._remote[remoteId - 1]
    if (r === null) return null

    const session = new Channel(
      this,
      info,
      userData,
      protocol,
      aliases,
      id,
      handshake,
      messages,
      onopen,
      onclose,
      ondestroy,
      ondrain
    )

    session._remoteId = remoteId
    session._fullyOpenSoon()

    return session
  }

  _pushBatch(localId, buffer) {
    if (this._batchState.end >= MAX_BATCH) {
      this._sendBatch(this._batch, this._batchState)
      this._batch = []
      this._batchState = { buffer: null, start: 0, end: 1 }
    }

    if (this._batch.length === 0 || this._batch[this._batch.length - 1].localId !== localId) {
      this._batchState.end++
      c.uint.preencode(this._batchState, localId)
    }
    c.buffer.preencode(this._batchState, buffer)
    this._batch.push({ localId, buffer })
  }

  _sendBatch(batch, state) {
    if (batch.length === 0) return

    let prev = batch[0].localId

    state.buffer = this._alloc(state.end)
    state.buffer[state.start++] = 0
    state.buffer[state.start++] = 0

    c.uint.encode(state, prev)

    for (let i = 0; i < batch.length; i++) {
      const b = batch[i]
      if (prev !== b.localId) {
        state.buffer[state.start++] = 0
        c.uint.encode(state, (prev = b.localId))
      }
      c.buffer.encode(state, b.buffer)
    }

    this.drained = this.stream.write(state.buffer)
  }

  _get(protocol, id, aliases = []) {
    const key = toKey(protocol, id)

    let info = this._infos.get(key)
    if (info) return info

    info = {
      key,
      protocol,
      aliases: [],
      id,
      pairing: 0,
      opened: 0,
      incoming: [],
      outgoing: [],
      lastChannel: null
    }
    this._infos.set(key, info)

    for (const alias of aliases) {
      const key = toKey(alias, id)
      info.aliases.push(key)

      this._infos.set(key, info)
    }

    return info
  }

  _gc(info) {
    if (info.opened === 0 && info.outgoing.length === 0 && info.incoming.length === 0) {
      this._infos.delete(info.key)

      for (const alias of info.aliases) this._infos.delete(alias)
    }
  }

  _ondata(buffer) {
    if (buffer.byteLength === 0) return // ignore empty frames...
    try {
      const state = { buffer, start: 0, end: buffer.byteLength }
      this._decode(c.uint.decode(state), state)
    } catch (err) {
      this._safeDestroy(err)
    }
  }

  _ondrain() {
    this.drained = true

    for (const s of this._local) {
      if (s !== null) s._track(s.ondrain(s))
    }
  }

  _onend() {
    // TODO: support half open mode for the users who wants that here
    this.stream.end()
  }

  _decode(remoteId, state) {
    const type = c.uint.decode(state)

    if (remoteId === 0) {
      return this._oncontrolsession(type, state)
    }

    const r = remoteId <= this._remote.length ? this._remote[remoteId - 1] : null

    // if the channel is closed ignore - could just be a pipeline message...
    if (r === null) return null

    if (r.pending !== null) {
      this._bufferMessage(r, type, state)
      return null
    }

    return r.session._recv(type, state)
  }

  _oncontrolsession(type, state) {
    switch (type) {
      case 0:
        this._onbatch(state)
        break

      case 1:
        // return the promise back up as this has sideeffects so we can batch reply
        return this._onopensession(state)

      case 2:
        this._onrejectsession(state)
        break

      case 3:
        this._onclosesession(state)
        break
    }

    return null
  }

  _bufferMessage(r, type, { buffer, start, end }) {
    const state = { buffer, start, end } // copy
    r.pending.push({ type, state })
    this._buffered += byteSize(state)
    this._pauseMaybe()
  }

  _pauseMaybe() {
    if (this._paused === true || this._buffered <= MAX_BUFFERED) return
    this._paused = true
    this.stream.pause()
  }

  _resumeMaybe() {
    if (this._paused === false || this._buffered > MAX_BUFFERED) return
    this._paused = false
    this.stream.resume()
  }

  _onbatch(state) {
    const end = state.end
    let remoteId = c.uint.decode(state)

    let waiting = null

    while (state.end > state.start) {
      const len = c.uint.decode(state)
      if (len === 0) {
        remoteId = c.uint.decode(state)
        continue
      }
      state.end = state.start + len
      // if batch contains more than one message, cork it so we reply back with a batch
      if (end !== state.end && waiting === null) {
        waiting = []
        this.cork()
      }
      const p = this._decode(remoteId, state)
      if (waiting !== null && p !== null) waiting.push(p)
      state.start = state.end
      state.end = end
    }

    if (waiting !== null) {
      // the waiting promises are not allowed to throw but we destroy the stream in case we are wrong
      Promise.all(waiting).then(this._uncorkBound, this._safeDestroyBound)
    }
  }

  _onopensession(state) {
    const remoteId = c.uint.decode(state)
    const protocol = c.string.decode(state)
    const id = unslab(c.optionalBuffer.decode(state))

    // remote tried to open the control session - auto reject for now
    // as we can use as an explicit control protocol declaration if we need to
    if (remoteId === 0) {
      this._rejectSession(0)
      return null
    }

    const rid = remoteId - 1
    const info = this._get(protocol, id)

    // allow the remote to grow the ids by one
    if (this._remote.length === rid) {
      this._remote.push(null)
    }

    if (rid >= this._remote.length || this._remote[rid] !== null) {
      throw new Error('Invalid open message')
    }

    if (info.outgoing.length > 0) {
      const localId = info.outgoing.shift()
      const session = this._local[localId - 1]

      if (session === null) {
        // we already closed the channel - ignore
        this._free.push(localId - 1)
        return null
      }

      this._remote[rid] = { state, pending: null, session: null }

      session._remoteId = remoteId
      session._fullyOpen()
      return null
    }

    const copyState = { buffer: state.buffer, start: state.start, end: state.end }
    this._remote[rid] = { state: copyState, pending: [], session: null }

    if (++this._remoteBacklog > MAX_BACKLOG) {
      throw new Error('Remote exceeded backlog')
    }

    info.pairing++
    info.incoming.push(remoteId)

    return this._requestSession(protocol, id, info).catch(this._safeDestroyBound)
  }

  _onrejectsession(state) {
    const localId = c.uint.decode(state)

    // TODO: can be done smarter...
    for (const info of this._infos.values()) {
      const i = info.outgoing.indexOf(localId)
      if (i === -1) continue

      info.outgoing.splice(i, 1)

      const session = this._local[localId - 1]

      this._free.push(localId - 1)
      if (session !== null) session._close(true)

      this._gc(info)
      return
    }

    throw new Error('Invalid reject message')
  }

  _onclosesession(state) {
    const remoteId = c.uint.decode(state)

    if (remoteId === 0) return // ignore

    const rid = remoteId - 1
    const r = rid < this._remote.length ? this._remote[rid] : null

    if (r === null) return

    if (r.session !== null) r.session._close(true)
  }

  async _requestSession(protocol, id, info) {
    const notify = this._notify.get(toKey(protocol, id)) || this._notify.get(toKey(protocol, null))

    if (notify) await notify(id)

    if (--info.pairing > 0) return

    while (info.incoming.length > 0) {
      this._rejectSession(info, info.incoming.shift())
    }

    this._gc(info)
  }

  _rejectSession(info, remoteId) {
    if (remoteId > 0) {
      const r = this._remote[remoteId - 1]

      if (r.pending !== null) {
        for (let i = 0; i < r.pending.length; i++) {
          this._buffered -= byteSize(r.pending[i].state)
        }
      }

      this._remote[remoteId - 1] = null
      this._resumeMaybe()
    }

    const state = { buffer: null, start: 2, end: 2 }

    c.uint.preencode(state, remoteId)

    state.buffer = this._alloc(state.end)

    state.buffer[0] = 0
    state.buffer[1] = 2
    c.uint.encode(state, remoteId)

    this._write0(state.buffer)
  }

  _write0(buffer) {
    if (this._batch !== null) {
      this._pushBatch(0, buffer.subarray(1))
      return
    }

    this.drained = this.stream.write(buffer)
  }

  destroy(err) {
    this._destroying = true
    this.stream.destroy(err)
  }

  _safeDestroy(err) {
    safetyCatch(err)
    this._destroying = true
    this.stream.destroy(err)
  }

  _shutdown() {
    this._destroying = true
    for (const s of this._local) {
      if (s !== null) s._close(true)
    }
  }
}

function noop() {}

function toKey(protocol, id) {
  return protocol + '##' + (id ? b4a.toString(id, 'hex') : '')
}

function byteSize(state) {
  return 512 + (state.end - state.start)
}

function isPromise(p) {
  return !!(p && typeof p.then === 'function')
}

function encodingLength(enc, val) {
  const state = { buffer: null, start: 0, end: 0 }
  enc.preencode(state, val)
  return state.end
}
{
  "name": "protomux",
  "version": "3.11.0",
  "description": "Multiplex multiple message oriented protocols over a stream",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.3.1",
    "compact-encoding": "^3.0.0",
    "queue-tick": "^1.0.0",
    "safety-catch": "^1.0.1",
    "unslab": "^1.3.0"
  },
  "devDependencies": {
    "@hyperswarm/secret-stream": "^6.0.0",
    "brittle": "^3.0.0",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/protomux.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/protomux/issues"
  },
  "homepage": "https://github.com/holepunchto/protomux"
}
{
  "name": "queue-tick",
  "version": "1.0.1",
  "description": "Next tick shim that prefers process.nextTick over queueMicrotask for compat",
  "main": "./process-next-tick.js",
  "browser": "./queue-microtask.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^16.0.3",
    "tape": "^5.3.1"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/queue-tick.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/queue-tick/issues"
  },
  "homepage": "https://github.com/mafintosh/queue-tick"
}
module.exports = (typeof process !== 'undefined' && typeof process.nextTick === 'function')
  ? process.nextTick.bind(process)
  : require('./queue-microtask')
module.exports = typeof queueMicrotask === 'function' ? queueMicrotask : (fn) => Promise.resolve().then(fn)
require.addon = require('require-addon')

module.exports = require.addon('.', __filename)
const binding = require('./binding')

exports.get = function get(field, bit) {
  const n = field.byteLength * 8

  if (bit < 0) bit += n
  if (bit < 0 || bit >= n) return false

  return binding.quickbit_napi_get(toBuffer(field), bit) !== 0
}

exports.set = function set(field, bit, value = true) {
  const n = field.byteLength * 8

  if (bit < 0) bit += n
  if (bit < 0 || bit >= n) return false

  return binding.quickbit_napi_set(toBuffer(field), bit, value ? 1 : 0) !== 0
}

exports.fill = function fill(
  field,
  value,
  start = 0,
  end = field.byteLength * 8
) {
  const n = field.byteLength * 8

  if (start < 0) start += n
  if (end < 0) end += n
  if (start < 0 || start >= field.byteLength * 8 || start >= end) return field

  binding.quickbit_napi_fill(toBuffer(field), value ? 1 : 0, start, end)
  return field
}

exports.clear = function clear(field, ...chunks) {
  binding.quickbit_napi_clear(toBuffer(field), chunks.map(toBufferChunk))
}

exports.findFirst = function findFirst(field, value, position = 0) {
  const n = field.byteLength * 8

  if (position < 0) position += n
  if (position < 0) position = 0
  if (position >= n) return -1

  return binding.quickbit_napi_find_first(
    toBuffer(field),
    value ? 1 : 0,
    position
  )
}

exports.findLast = function findLast(
  field,
  value,
  position = field.byteLength * 8 - 1
) {
  const n = field.byteLength * 8

  if (position < 0) position += n
  if (position < 0) return -1
  if (position >= n) position = n - 1

  return binding.quickbit_napi_find_last(
    toBuffer(field),
    value ? 1 : 0,
    position
  )
}

function toBuffer(field) {
  if (field.BYTES_PER_ELEMENT === 1) return field
  return new Uint8Array(field.buffer, field.byteOffset, field.byteLength)
}

function toBufferChunk(chunk) {
  return { field: toBuffer(chunk.field), offset: chunk.offset }
}

class Index {
  static from(fieldOrChunks, byteLength = -1) {
    if (Array.isArray(fieldOrChunks)) {
      return new SparseIndex(fieldOrChunks, byteLength)
    } else {
      return new DenseIndex(fieldOrChunks, byteLength)
    }
  }

  constructor(byteLength) {
    this._byteLength = byteLength
    this.handle = Buffer.allocUnsafe(binding.sizeof_quickbit_index_t)
  }

  get byteLength() {
    return this._byteLength
  }

  skipFirst(value, position = 0) {
    const n = this.byteLength * 8

    if (position < 0) position += n
    if (position < 0) position = 0
    if (position >= n) return n - 1

    return binding.quickbit_napi_skip_first(
      this.handle,
      this.byteLength,
      value ? 1 : 0,
      position
    )
  }

  skipLast(value, position = this.byteLength * 8 - 1) {
    const n = this.byteLength * 8

    if (position < 0) position += n
    if (position < 0) return 0
    if (position >= n) position = n - 1

    return binding.quickbit_napi_skip_last(
      this.handle,
      this.byteLength,
      value ? 1 : 0,
      position
    )
  }
}

exports.Index = Index

class DenseIndex extends Index {
  constructor(field, byteLength) {
    super(byteLength)
    this.field = field

    binding.quickbit_napi_index_init(this.handle, toBuffer(this.field))
  }

  get byteLength() {
    if (this._byteLength !== -1) return this._byteLength
    return this.field.byteLength
  }

  update(bit) {
    const n = this.byteLength * 8

    if (bit < 0) bit += n
    if (bit < 0 || bit >= n) return false

    return (
      binding.quickbit_napi_index_update(
        this.handle,
        toBuffer(this.field),
        bit
      ) !== 0
    )
  }
}

function selectChunk(chunks, offset) {
  for (let i = 0; i < chunks.length; i++) {
    const next = chunks[i]

    const start = next.offset
    const end = next.offset + next.field.byteLength

    if (offset >= start && offset + 16 <= end) {
      return next
    }
  }

  return null
}

class SparseIndex extends Index {
  constructor(chunks, byteLength) {
    super(byteLength)
    this.chunks = chunks

    binding.quickbit_napi_index_init_sparse(
      this.handle,
      this.chunks.map(toBufferChunk)
    )
  }

  get byteLength() {
    if (this._byteLength !== -1) return this._byteLength
    const last = this.chunks[this.chunks.length - 1]
    return last ? last.offset + last.field.byteLength : 0
  }

  update(bit) {
    const n = this.byteLength * 8

    if (bit < 0) bit += n
    if (bit < 0 || bit >= n) return false

    const j = Math.floor(bit / 128)

    const offset = j * 16

    const chunk = selectChunk(this.chunks, offset)

    if (chunk === null) return false

    return (
      binding.quickbit_napi_index_update_sparse(
        this.handle,
        toBuffer(chunk.field),
        chunk.offset,
        bit
      ) !== 0
    )
  }
}
{
  "name": "quickbit-native",
  "version": "2.4.8",
  "description": "libquickbit JavaScript bindings for Node.js",
  "main": "index.js",
  "files": [
    "index.js",
    "macros.h",
    "binding.cc",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "npm run lint && npm run test:bare && npm run test:node",
    "test:bare": "bare test.mjs",
    "test:node": "node test.mjs",
    "lint": "prettier . --check"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/quickbit-native.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/quickbit-native/issues"
  },
  "homepage": "https://github.com/holepunchto/quickbit-native#readme",
  "dependencies": {
    "require-addon": "^1.1.0"
  },
  "devDependencies": {
    "b4a": "^1.6.7",
    "bare-compat-napi": "^1.3.2",
    "brittle": "^3.1.0",
    "cmake-bare": "^1.1.7",
    "cmake-fetch": "^1.1.0",
    "cmake-napi": "^1.0.2",
    "prettier": "^3.5.3",
    "prettier-config-standard": "^7.0.0"
  }
}
const simdle = require('simdle-universal')

const INDEX_LEN = (16 /* root */ + 128 * 16 /* children */) * 2

const get = exports.get = function get (field, bit) {
  const n = field.byteLength * 8

  if (bit < 0) bit += n
  if (bit < 0 || bit >= n) return false

  const m = field.BYTES_PER_ELEMENT * 8

  const offset = bit & (m - 1)
  const i = (bit - offset) / m

  return (field[i] & (1 << offset)) !== 0
}

const set = exports.set = function set (field, bit, value = true) {
  const n = field.byteLength * 8

  if (bit < 0) bit += n
  if (bit < 0 || bit >= n) return false

  const m = field.BYTES_PER_ELEMENT * 8

  const offset = bit & (m - 1)
  const i = (bit - offset) / m
  const mask = 1 << offset

  if (value) {
    if ((field[i] & mask) !== 0) return false
  } else {
    if ((field[i] & mask) === 0) return false
  }

  field[i] ^= mask

  return true
}

exports.fill = function fill (field, value, start = 0, end = field.byteLength * 8) {
  const n = field.byteLength * 8

  if (start < 0) start += n
  if (end < 0) end += n
  if (start < 0 || start >= field.byteLength * 8 || start >= end) return field

  const m = field.BYTES_PER_ELEMENT * 8

  let i, j

  {
    const offset = start & (m - 1)
    i = (start - offset) / m

    if (offset !== 0) {
      let shift = m - offset
      if (end - start < shift) shift = end - start

      const mask = ((1 << shift) - 1) << offset

      if (value) field[i] |= mask
      else field[i] &= ~mask

      i++
    }
  }

  {
    const offset = end & (m - 1)
    j = (end - offset) / m

    if (offset !== 0 && j >= i) {
      const mask = (1 << offset) - 1

      if (value) field[j] |= mask
      else field[j] &= ~mask
    }
  }

  if (i < j) field.fill(value ? (2 ** m) - 1 : 0, i, j)

  return field
}

exports.clear = function clear (field, ...chunks) {
  const n = field.byteLength

  for (const chunk of chunks) {
    if (chunk.offset >= n) continue

    const m = chunk.field.byteLength

    let i = chunk.offset
    let j = 0

    while (((i & 15) !== 0 || (j & 15) !== 0) && i < n && j < m) {
      field[i] = field[i] & ~chunk.field[j]
      i++
      j++
    }

    if (i + 15 < n && j + 15 < m) {
      const len = Math.min(n - (n & 15) - i, m - (m & 15) - j)

      simdle.clear(field.subarray(i, i + len), chunk.field.subarray(j, j + len), field.subarray(i, i + len))
    }

    while (i < n && j < m) {
      field[i] = field[i] & ~chunk.field[j]
      i++
      j++
    }
  }
}

function bitOffset (bit, offset) {
  return !bit ? offset : (INDEX_LEN * 8 / 2) + offset
}

function byteOffset (bit, offset) {
  return !bit ? offset : (INDEX_LEN / 2) + offset
}

exports.findFirst = function findFirst (field, value, position = 0) {
  const n = field.byteLength * 8

  if (position < 0) position += n
  if (position < 0) position = 0
  if (position >= n) return -1

  value = !!value

  for (let i = position; i < n; i++) {
    if (get(field, i) === value) return i
  }

  return -1
}

exports.findLast = function findLast (field, value, position = field.byteLength * 8 - 1) {
  const n = field.byteLength * 8

  if (position < 0) position += n
  if (position < 0) return -1
  if (position >= n) position = n - 1

  value = !!value

  for (let i = position; i >= 0; i--) {
    if (get(field, i) === value) return i
  }

  return -1
}

const Index = exports.Index = class Index {
  static from (fieldOrChunks, byteLength = -1) {
    if (Array.isArray(fieldOrChunks)) {
      return new SparseIndex(fieldOrChunks, byteLength)
    } else {
      return new DenseIndex(fieldOrChunks, byteLength)
    }
  }

  constructor (byteLength) {
    this._byteLength = byteLength
    this.handle = new Uint32Array(INDEX_LEN / 4)
  }

  get byteLength () {
    return this._byteLength
  }

  skipFirst (value, position = 0) {
    const n = this.byteLength * 8

    if (position < 0) position += n
    if (position < 0) position = 0
    if (position >= n) return n - 1

    let i = Math.floor(position / 16384)

    if (i > 127) return position

    while (i <= 127 && get(this.handle, bitOffset(value, i))) {
      i++
    }

    if (i === 128) return n - 1

    let k = i * 16384
    let j = 0

    if (position > k) j = Math.floor((position - k) / 128)

    while (j <= 127 && get(this.handle, bitOffset(value, i * 128 + j + 128))) {
      j++
      k += 128
    }

    if (j === 128 && i !== 127) return this.skipFirst(value, (i + 1) * 16384)

    if (k > position) position = k

    return position < n ? position : n - 1
  }

  skipLast (value, position = this.byteLength * 8 - 1) {
    const n = this.byteLength * 8

    if (position < 0) position += n
    if (position < 0) return 0
    if (position >= n) position = n - 1

    let i = Math.floor(position / 16384)

    if (i > 127) return position

    while (i >= 0 && get(this.handle, bitOffset(value, i))) {
      i--
    }

    if (i === -1) return 0

    let k = ((i + 1) * 16384) - 1
    let j = 127

    if (position < k) j = 128 - Math.ceil((k - position) / 128)

    while (j >= 0 && get(this.handle, bitOffset(value, i * 128 + j + 128))) {
      j--
      k -= 128
    }

    if (j === -1 && i !== 0) return this.skipLast(value, i * 16384 - 1)

    if (k < position) position = k

    return position
  }
}

class DenseIndex extends Index {
  constructor (field, byteLength) {
    super(byteLength)
    this.field = field

    const m = field.BYTES_PER_ELEMENT

    for (let i = 0; i < 128; i++) {
      for (let j = 0; j < 128; j++) {
        const offset = (i * 128 + j) * 16
        let allz = true
        let allo = false

        if (offset + 16 <= this.field.byteLength) {
          const vec = this.field.subarray(offset / m, (offset + 16) / m)

          allz = simdle.allz(vec)
          allo = simdle.allo(vec)
        }

        const k = i * 128 + 128 + j

        set(this.handle, bitOffset(false, k), allz)
        set(this.handle, bitOffset(true, k), allo)
      }

      {
        const offset = byteOffset(false, i * 16 + 16) / 4
        const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

        set(this.handle, bitOffset(false, i), allo)
      }

      {
        const offset = byteOffset(true, i * 16 + 16) / 4
        const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

        set(this.handle, bitOffset(true, i), allo)
      }
    }
  }

  get byteLength () {
    if (this._byteLength !== -1) return this._byteLength
    return this.field.byteLength
  }

  update (bit) {
    const n = this.byteLength * 8

    if (bit < 0) bit += n
    if (bit < 0 || bit >= n) return false

    const m = this.field.BYTES_PER_ELEMENT

    const i = Math.floor(bit / 16384)
    const j = Math.floor(bit / 128)

    const offset = (j * 16) / m
    const vec = this.field.subarray(offset, offset + (16 / m))

    const allz = simdle.allz(vec)
    const allo = simdle.allo(vec)

    let changed = false

    if (set(this.handle, bitOffset(false, 128 + j), allz)) {
      changed = true

      const offset = byteOffset(false, i * 16 + 16) / 4
      const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

      set(this.handle, bitOffset(false, i), allo)
    }

    if (set(this.handle, bitOffset(true, 128 + j), allo)) {
      changed = true

      const offset = byteOffset(true, i * 16 + 16) / 4
      const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

      set(this.handle, bitOffset(true, i), allo)
    }

    return changed
  }
}

function selectChunk (chunks, offset) {
  for (let i = 0; i < chunks.length; i++) {
    const next = chunks[i]

    const start = next.offset
    const end = next.offset + next.field.byteLength

    if (offset >= start && offset + 16 <= end) {
      return next
    }
  }

  return null
}

class SparseIndex extends Index {
  constructor (chunks, byteLength) {
    super(byteLength)
    this.chunks = chunks

    for (let i = 0; i < 128; i++) {
      for (let j = 0; j < 128; j++) {
        const offset = (i * 128 + j) * 16
        let allz = true
        let allo = false

        const chunk = selectChunk(this.chunks, offset)

        if (chunk !== null) {
          const m = chunk.field.BYTES_PER_ELEMENT

          const vec = chunk.field.subarray((offset - chunk.offset) / m, (offset - chunk.offset + 16) / m)

          allz = simdle.allz(vec)
          allo = simdle.allo(vec)
        }

        const k = i * 128 + 128 + j

        set(this.handle, bitOffset(false, k), allz)
        set(this.handle, bitOffset(true, k), allo)
      }

      {
        const offset = byteOffset(false, i * 16 + 16) / 4
        const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

        set(this.handle, bitOffset(false, i), allo)
      }

      {
        const offset = byteOffset(true, i * 16 + 16) / 4
        const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

        set(this.handle, bitOffset(true, i), allo)
      }
    }
  }

  get byteLength () {
    if (this._byteLength !== -1) return this._byteLength
    const last = this.chunks[this.chunks.length - 1]
    return last ? last.offset + last.field.byteLength : 0
  }

  update (bit) {
    const n = this.byteLength * 8

    if (bit < 0) bit += n
    if (bit < 0 || bit >= n) return false

    const i = Math.floor(bit / 16384)
    const j = Math.floor(bit / 128)

    const offset = j * 16

    const chunk = selectChunk(this.chunks, offset)

    if (chunk === null) return false

    const m = chunk.field.BYTES_PER_ELEMENT

    const vec = chunk.field.subarray((offset - chunk.offset) / m, (offset - chunk.offset + 16) / m)

    const allz = simdle.allz(vec)
    const allo = simdle.allo(vec)

    let changed = false

    if (set(this.handle, bitOffset(false, 128 + j), allz)) {
      changed = true

      const offset = byteOffset(false, i * 16 + 16) / 4
      const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

      set(this.handle, bitOffset(false, i), allo)
    }

    if (set(this.handle, bitOffset(true, 128 + j), allo)) {
      changed = true

      const offset = byteOffset(true, i * 16 + 16) / 4
      const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

      set(this.handle, bitOffset(true, i), allo)
    }

    return changed
  }
}
const fallback = require('./fallback')

try {
  const native = require('quickbit-native')

  // These functions are faster in JavaScript
  exports.get = fallback.get
  exports.set = fallback.set
  exports.fill = fallback.fill

  // These functions are faster in C
  exports.clear = native.clear
  exports.findFirst = native.findFirst
  exports.findLast = native.findLast
  exports.Index = native.Index
} catch {
  module.exports = fallback
}
{
  "name": "quickbit-universal",
  "version": "2.2.0",
  "description": "Universal wrapper for libquickbit with a JavaScript fallback",
  "main": "index.js",
  "files": [
    "fallback.js",
    "index.js"
  ],
  "browser": {
    "./index.js": "./fallback.js"
  },
  "scripts": {
    "test": "standard && brittle test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/quickbit-universal.git"
  },
  "author": "Kasper Isager Dalsgarð <kasper@funktionel.co>",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/holepunchto/quickbit-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/quickbit-universal#readme",
  "dependencies": {
    "b4a": "^1.6.0",
    "simdle-universal": "^1.1.0"
  },
  "optionalDependencies": {
    "quickbit-native": "^2.2.0"
  },
  "devDependencies": {
    "brittle": "^3.1.0",
    "standard": "^17.0.0"
  }
}
class CacheEntry {
  constructor (key, index, map) {
    this.key = key
    this.index = index
    this.map = map
  }
}

class CacheValue {
  constructor (entry, value) {
    this.entry = entry
    this.value = value
  }
}

class Rache {
  constructor ({ maxSize = 65536, parent = null } = {}) {
    this.maxSize = parent?.maxSize || maxSize

    this._array = parent?._array || []
    this._map = new Map()
  }

  static from (cache) {
    return cache ? new this({ parent: cache }) : new this()
  }

  get globalSize () {
    return this._array.length
  }

  get size () {
    return this._map.size
  }

  sub () {
    return new Rache({ parent: this })
  }

  set (key, value) { // ~constant time
    const existing = this._map.get(key)
    if (existing !== undefined) {
      existing.value = value
      return
    }

    if (this._array.length >= this.maxSize) this._gc()

    const entry = new CacheEntry(key, this._array.length, this._map)
    this._array.push(entry)
    const cacheValue = new CacheValue(entry, value)
    this._map.set(key, cacheValue)
  }

  delete (key) {
    const existing = this._map.get(key)
    if (existing === undefined) return false

    this._delete(existing.entry.index)
    return true
  }

  get (key) {
    const existing = this._map.get(key)
    return existing === undefined ? undefined : existing.value
  }

  * [Symbol.iterator] () {
    for (const [key, { value }] of this._map) {
      yield [key, value]
    }
  }

  keys () {
    return this._map.keys()
  }

  * values () {
    for (const { value } of this._map.values()) {
      yield value
    }
  }

  clear () {
    // The entries in map linger on in _array,
    // so on top of clearing the map, we also kill the ref,
    // so that any gc running later on the old map won't interfere
    // (in case a new entry was added with the same key as a cleared entry)

    this._map.clear()
    this._map = new Map()
  }

  destroy () {
    this._map = null
    this._array = null
  }

  _gc () {
    this._delete(Math.floor(Math.random() * this._array.length))
  }

  _delete (index) { // ~constant time
    if (index >= this._array.length) throw new Error('Cannot delete unused index (logic bug?)')

    const head = this._array.pop()
    let removed = head

    if (index < this._array.length) {
      removed = this._array[index]
      head.index = index
      this._array[index] = head
    }

    removed.map.delete(removed.key)
  }
}

module.exports = Rache
{
  "name": "rache",
  "version": "1.0.0",
  "description": "Random-eviction cache",
  "main": "index.js",
  "scripts": {
    "test": "standard && brittle test.js --coverage"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/rache.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/rache/issues"
  },
  "homepage": "https://github.com/holepunchto/rache#readme",
  "files": [
    "index.js"
  ],
  "dependencies": {},
  "devDependencies": {
    "brittle": "^3.5.2",
    "standard": "^17.1.0"
  }
}
module.exports = class RandomArrayIterator {
  constructor (values) {
    this.values = values
    this.start = 0
    this.length = this.values.length
  }

  next () {
    if (this.length === 0) {
      if (this.start === 0) return { done: true, value: undefined }
      this.length = this.start
      this.start = 0
    }

    const i = this.start + ((Math.random() * this.length) | 0)
    const j = this.start + --this.length
    const value = this.values[i]

    this.values[i] = this.values[j]
    this.values[j] = value

    return { done: false, value }
  }

  dequeue () {
    this.values[this.start + this.length] = this.values[this.values.length - 1]
    this.values.pop()
  }

  requeue () {
    const i = this.start + this.length
    const value = this.values[i]
    this.values[i] = this.values[this.start]
    this.values[this.start++] = value
  }

  restart () {
    this.start = 0
    this.length = this.values.length
    return this
  }

  [Symbol.iterator] () {
    return this
  }
}
{
  "name": "random-array-iterator",
  "version": "1.0.0",
  "description": "An iterator to iterate an array in random order with controls to requeue or dequeue elements during the iteration",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^16.0.3",
    "tape": "^5.0.1"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/random-array-iterator.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/random-array-iterator/issues"
  },
  "homepage": "https://github.com/mafintosh/random-array-iterator"
}
const EventEmitter = require('events')

module.exports = class ReadyResource extends EventEmitter {
  constructor () {
    super()

    this.opening = null
    this.closing = null

    this.opened = false
    this.closed = false
  }

  ready () {
    if (this.opening !== null) return this.opening
    this.opening = open(this)
    return this.opening
  }

  close () {
    if (this.closing !== null) return this.closing
    this.closing = close(this)
    return this.closing
  }

  async _open () {
    // add impl here
  }

  async _close () {
    // add impl here
  }
}

async function open (self) {
  // open after close
  if (self.closing !== null) return

  try {
    await self._open()
  } catch (err) {
    self.close() // safe to run in bg
    throw err
  }

  self.opened = true
  self.emit('ready')
}

async function close (self) {
  try {
    if (self.opened === false && self.opening !== null) await self.opening
  } catch {
    // ignore errors on closing
  }
  if (self.opened === true || self.opening === null) await self._close()
  self.closed = true
  self.emit('close')
}
{
  "name": "ready-resource",
  "version": "1.2.0",
  "description": "Modern single resource management",
  "main": "index.js",
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "types": "index.d.ts",
  "files": [
    "index.js",
    "index.d.ts"
  ],
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "devDependencies": {
    "brittle": "^3.1.0",
    "standard": "^17.0.0"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/ready-resource.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/ready-resource/issues"
  },
  "homepage": "https://github.com/holepunchto/ready-resource",
  "dependencies": {
    "bare-events": "^2.2.0"
  }
}
module.exports = class RefCounter {
  constructor() {
    this.count = 0

    this._onidle = null
    this._idle = null
  }

  isIdle() {
    return this.count === 0
  }

  idle() {
    if (this.count === 0) return Promise.resolve()
    if (this._idle !== null) return this._idle

    this._idle = new Promise((resolve) => {
      this._onidle = resolve
    })

    return this._idle
  }

  inc() {
    this.count++
  }

  dec() {
    if (--this.count > 0) return

    if (this._onidle !== null) {
      const resolve = this._onidle
      this._idle = null
      this._onidle = null
      resolve()
    }
  }
}
{
  "name": "refcounter",
  "version": "1.0.0",
  "description": "Simple refcounter",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {},
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/refcounter.git"
  },
  "author": "Holepunch Inc",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/refcounter/issues"
  },
  "homepage": "https://github.com/holepunchto/refcounter"
}
module.exports = require.addon.bind(require)
{
  "name": "require-addon",
  "version": "1.2.0",
  "description": "Import native addons across JavaScript runtimes",
  "exports": {
    "./package": "./package.json",
    ".": {
      "bare": "./lib/bare.js",
      "node": "./lib/node.js",
      "default": "./lib/default.js"
    }
  },
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    },
    "url": {
      "bare": "bare-url",
      "default": "url"
    }
  },
  "files": [
    "lib"
  ],
  "scripts": {
    "test": "npm run lint && npm run test:bare && npm run test:node",
    "test:bare": "bare test.js",
    "test:node": "node test.js",
    "lint": "prettier --check .",
    "format": "prettier --write ."
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/require-addon.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/require-addon/issues"
  },
  "homepage": "https://github.com/holepunchto/require-addon#readme",
  "engines": {
    "bare": ">=1.10.0"
  },
  "dependencies": {
    "bare-addon-resolve": "^1.3.0"
  },
  "devDependencies": {
    "bare-bundle": "^1.8.1",
    "bare-bundle-evaluate": "^1.1.0",
    "bare-fs": "^4.0.0",
    "bare-path": "^3.0.0",
    "bare-url": "^2.1.0",
    "brittle": "^3.7.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
let tmpResolve = null
let tmpReject = null

if (Promise.withResolvers) {
  module.exports = Promise.withResolvers.bind(Promise)
} else {
  module.exports = function resolveRejectPromise () {
    const promise = new Promise(setTmp)
    const result = { promise, resolve: tmpResolve, reject: tmpReject }
    tmpResolve = tmpReject = null
    return result
  }
}

function setTmp (resolve, reject) {
  tmpResolve = resolve
  tmpReject = reject
}
{
  "name": "resolve-reject-promise",
  "version": "1.1.0",
  "description": "Create an inverted promise with no function allocs",
  "main": "index.js",
  "scripts": {
    "test": "standard"
  },
  "devDependencies": {
    "standard": "^17.1.2"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/resolve-reject-promise.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/resolve-reject-promise/issues"
  },
  "homepage": "https://github.com/mafintosh/resolve-reject-promise"
}
const resources = new Map()

exports.add = function(resource, teardown) {
  resources.set(resource, teardown)
}

exports.remove = function(resource) {
  resources.delete(resource)
}

if (global.Bare) global.Bare.on('exit', run)
else global.process.on('exit', run)

function run() {
  for (const [resource, teardown] of resources) {
    teardown(resource)
  }
}
{
  "name": "resource-on-exit",
  "version": "1.0.0",
  "description": "Register sync teardown handlers for a resource",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {},
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/bare-teardown.git"
  },
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-teardown/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-teardown"
}
require.addon = require('require-addon')

module.exports = require.addon('.', __filename)
const ColumnFamily = require('./lib/column-family')
const Iterator = require('./lib/iterator')
const Snapshot = require('./lib/snapshot')
const State = require('./lib/state')
const { BloomFilterPolicy, RibbonFilterPolicy } = require('./lib/filter-policy')
const constants = require('./lib/constants')

class RocksDB {
  constructor(path, opts = {}) {
    const {
      columnFamily,
      state = new State(this, path, opts),
      snapshot = null,
      keyEncoding = null,
      valueEncoding = null
    } = opts

    this._state = state
    this._snapshot = snapshot
    this._columnFamily = state.getColumnFamily(columnFamily)
    this._keyEncoding = keyEncoding
    this._valueEncoding = valueEncoding
    this._index = -1

    this._state.addSession(this)
  }

  get opened() {
    return this._state.opened
  }

  get closed() {
    return this.isRoot() ? this._state.closed : this._index === -1
  }

  get path() {
    return this._state.path
  }

  get stats() {
    return this._state.stats
  }

  get snapshotted() {
    return this._snapshot !== null
  }

  get defaultColumnFamily() {
    return this._columnFamily
  }

  session({
    columnFamily = this._columnFamily,
    snapshot = this._snapshot !== null,
    keyEncoding = this._keyEncoding,
    valueEncoding = this._valueEncoding
  } = {}) {
    maybeClosed(this)

    return new RocksDB(null, {
      state: this._state,
      columnFamily,
      snapshot: snapshot ? this._snapshot || new Snapshot(this._state) : null,
      keyEncoding,
      valueEncoding
    })
  }

  columnFamily(name, opts) {
    return this.session({ ...opts, columnFamily: name })
  }

  snapshot() {
    return this.session({ snapshot: true })
  }

  isRoot() {
    return this === this._state.db
  }

  ready() {
    return this._state.ready()
  }

  async close({ force } = {}) {
    if (!this._state.opened) await this._state.ready()

    if (this._index !== -1) this._state.removeSession(this)

    if (force) {
      while (this._state.sessions.length > 0) {
        await this._state.sessions[this._state.sessions.length - 1].close()
      }
    }

    return this.isRoot() ? this._state.close() : Promise.resolve()
  }

  suspend() {
    maybeClosed(this)

    return this._state.suspend()
  }

  resume() {
    maybeClosed(this)

    return this._state.resume()
  }

  isIdle() {
    return this._state.handles.isIdle()
  }

  idle() {
    return this._state.handles.idle()
  }

  iterator(range, opts) {
    maybeClosed(this)

    return new Iterator(this, { ...range, ...opts })
  }

  async *keys(range, opts) {
    for await (const { key } of this.iterator(range, {
      ...opts,
      values: false
    })) {
      yield key
    }
  }

  async peek(range, opts) {
    for await (const value of this.iterator({ ...range, ...opts, limit: 1 })) {
      return value
    }

    return null
  }

  read(opts) {
    maybeClosed(this)

    return this._state.createReadBatch(this, opts)
  }

  write(opts) {
    maybeClosed(this)

    return this._state.createWriteBatch(this, opts)
  }

  flush(opts) {
    maybeClosed(this)

    return this._state.flush(this, opts)
  }

  async get(key, opts) {
    const batch = this.read({ ...opts, capacity: 1, autoDestroy: true })
    const value = batch.get(key)
    batch.tryFlush()
    return value
  }

  async put(key, value, opts) {
    const batch = this.write({ ...opts, capacity: 1, autoDestroy: true })
    batch.tryPut(key, value)
    await batch.flush()
  }

  async delete(key, opts) {
    const batch = this.write({ ...opts, capacity: 1, autoDestroy: true })
    batch.tryDelete(key)
    await batch.flush()
  }

  async deleteRange(start, end, opts) {
    const batch = this.write({ ...opts, capacity: 1, autoDestroy: true })
    batch.tryDeleteRange(start, end)
    await batch.flush()
  }

  async compact(opts = {}) {
    maybeClosed(this)

    await this._state.compact(this, opts)
  }

  async compactRange(start = null, end = null, opts = {}) {
    if (typeof end === 'object' && end !== null) {
      opts = end
      end = null
    } else if (typeof start === 'object' && start !== null) {
      opts = start
      start = null
      end = null
    }

    await this._state.compactRange(this, start, end, opts)
  }

  async approximateSize(start, end, opts = {}) {
    return this._state.approximateSize(this, start, end, opts)
  }

  async currentWalFile() {
    maybeClosed(this)

    return this._state.currentWalFile()
  }

  async getStatsLevel() {
    maybeClosed(this)

    return this._state.getStatsLevel()
  }

  async setStatsLevel(level) {
    maybeClosed(this)

    await this._state.setStatsLevel(level)
  }

  async getProperty(name) {
    maybeClosed(this)

    return this._state.getProperty(name)
  }

  _ref() {
    if (this._snapshot) this._snapshot.ref()
    this._state.handles.inc()
  }

  _unref() {
    if (this._snapshot) this._snapshot.unref()
    this._state.handles.dec()
  }

  diagnostics() {
    return this._state.diagnostics()
  }
}

module.exports = exports = RocksDB

exports.constants = constants

exports.ColumnFamily = ColumnFamily
exports.BloomFilterPolicy = BloomFilterPolicy
exports.RibbonFilterPolicy = RibbonFilterPolicy

function maybeClosed(db) {
  if (db._state.closing || db._index === -1) throw new Error('RocksDB session is closed')
}
const c = require('compact-encoding')
const binding = require('../binding')

const empty = Buffer.alloc(0)
const resolved = Promise.resolve()

class RocksDBBatch {
  constructor(db, opts = {}) {
    const { capacity = 8, autoDestroy = false } = opts

    db._ref()

    this._db = db
    this._destroyed = false
    this._capacity = capacity
    this._operations = []
    this._promises = []

    this._enqueuePromise = this._enqueuePromise.bind(this)

    this._request = null
    this._resolve = null
    this._reject = null

    this._handle = null
    this._buffer = null
    this._autoDestroy = autoDestroy
    this._stats = null

    this._resetStats()

    if (db._state.opened === true) this.ready()
  }

  _reuse(db, opts = {}) {
    const { autoDestroy = false } = opts

    db._ref()

    this._db = db
    this._destroyed = false
    this._autoDestroy = autoDestroy
  }

  _onfinished(err) {
    const resolve = this._resolve
    const reject = this._reject

    if (this._request) this._db._state.io.dec()

    this._operations = []
    this._promises = []
    this._request = null
    this._resolve = null
    this._reject = null

    this._resetStats()

    if (this._autoDestroy === true) this.destroy()

    if (reject !== null && err) reject(err)
    else if (resolve !== null) resolve()
  }

  _resize() {
    if (this._operations.length <= this._capacity) return false

    while (this._operations.length > this._capacity) {
      this._capacity *= 2
    }

    return true
  }

  async ready() {
    if (this._handle !== null) return

    if (this._db._state.opened === false) await this._db._state.ready()

    this._init()
  }

  destroy() {
    if (this._request) throw new Error('Request in progress')
    if (this._destroyed) return

    this._destroyed = true

    if (this._promises.length) this._abort()

    this._db._unref()
    this._onfree()
  }

  _onfree() {
    this._resetStats()
    this._db._state.freeBatch(this, false)
    this._db = null
  }

  _abort() {
    for (let i = 0; i < this._promises.length; i++) {
      const promise = this._promises[i]
      if (promise !== null) promise.reject(new Error('Batch is destroyed'))
    }

    this._onfinished(new Error('Batch is destroyed'))
  }

  _resetStats() {}

  async flush() {
    if (this._request) throw new Error('Request in progress')
    if (this._destroyed) throw new Error('Batch is destroyed')

    this._request = new Promise((resolve, reject) => {
      this._resolve = resolve
      this._reject = reject
    })

    this._flush()

    return this._request
  }

  tryFlush() {
    if (this._request) throw new Error('Request in progress')
    if (this._destroyed) throw new Error('Batch is destroyed')

    this._request = resolved

    this._flush()
  }

  async _flush() {
    if (this._handle === null) await this.ready()

    this._db._state.io.inc()

    if (this._db._state.resumed !== null) {
      const resumed = await this._db._state.resumed.promise

      if (!resumed) {
        if (this._destroyed) {
          this._db._state.io.dec()
        } else {
          this._destroyed = true
          this._abort()
          this._db._unref()
        }
      }
    }
  }

  _enqueuePromise(resolve, reject) {
    this._promises.push({ resolve, reject })
  }

  _encodeKey(k) {
    if (this._db._keyEncoding) return c.encode(this._db._keyEncoding, k)
    if (typeof k === 'string') return Buffer.from(k)
    return k
  }

  _encodeValue(v) {
    if (this._db._valueEncoding) return c.encode(this._db._valueEncoding, v)
    if (v === null) return empty
    if (typeof v === 'string') return Buffer.from(v)
    return v
  }

  _decodeValue(b) {
    if (this._db._valueEncoding) return c.decode(this._db._valueEncoding, b)
    return b
  }
}

exports.ReadBatch = class RocksDBReadBatch extends RocksDBBatch {
  constructor(db, opts = {}) {
    super(db, opts)

    const { asyncIO = false, fillCache = true } = opts

    this._asyncIO = asyncIO
    this._fillCache = fillCache
  }

  _init() {
    this._handle = binding.readInit()
    this._buffer = binding.readBuffer(this._handle, this._capacity)
  }

  _resize() {
    if (super._resize() && this._handle !== null) {
      this._buffer = binding.readBuffer(this._handle, this._capacity)
    }
  }

  async _flush() {
    await super._flush()

    if (this._destroyed) return

    try {
      binding.read(
        this._db._state._handle,
        this._handle,
        this._operations,
        this._db._snapshot ? this._db._snapshot._handle : undefined,
        this._asyncIO,
        this._fillCache,
        this,
        this._onread
      )
    } catch (err) {
      this._db._state.io.dec()
      throw err
    }

    this._db._state.stats.gets += this._stats.gets
    this._db._state.stats.readBatches++
  }

  _onread(errs, values) {
    let applied = true

    for (let i = 0, n = this._promises.length; i < n; i++) {
      const err = errs[i]
      if (err) applied = false

      const promise = this._promises[i]
      if (promise === null) continue

      if (err) promise.reject(err)
      else promise.resolve(values[i] ? this._decodeValue(Buffer.from(values[i])) : null)
    }

    this._onfinished(applied ? null : new AggregateError(errs, 'Batch was not applied'))
  }

  _resetStats() {
    this._stats = { gets: 0 }
  }

  get(key) {
    if (this._request) throw new Error('Request already in progress')
    this._stats.gets++

    const promise = new Promise(this._enqueuePromise)

    this._operations.push(new RocksDBGet(this._encodeKey(key), this._db._columnFamily))

    this._resize()

    return promise
  }
}

exports.WriteBatch = class RocksDBWriteBatch extends RocksDBBatch {
  _init() {
    this._handle = binding.writeInit()
    this._buffer = binding.writeBuffer(this._handle, this._capacity)
  }

  _resize() {
    if (super._resize() && this._handle !== null) {
      this._buffer = binding.writeBuffer(this._handle, this._capacity)
    }
  }

  _onfree() {
    this._resetStats()
    this._db._state.freeBatch(this, true)
    this._db = null
  }

  async _flush() {
    await super._flush()

    if (this._destroyed) return

    try {
      binding.write(this._db._state._handle, this._handle, this._operations, this, this._onwrite)
    } catch (err) {
      this._db._state.io.dec()
      throw err
    }

    this._db._state.stats.puts += this._stats.puts
    this._db._state.stats.deletes += this._stats.deletes
    this._db._state.stats.rangeDeletes += this._stats.rangeDeletes
    this._db._state.stats.writeBatches++
  }

  _onwrite(err) {
    const applied = !err

    for (let i = 0, n = this._promises.length; i < n; i++) {
      const promise = this._promises[i]
      if (promise === null) continue

      if (err) promise.reject(err)
      else promise.resolve()
    }

    this._onfinished(applied ? null : new Error('Batch was not applied', { cause: err }))
  }

  _resetStats() {
    this._stats = { puts: 0, deletes: 0, rangeDeletes: 0 }
  }

  put(key, value) {
    if (this._request) throw new Error('Request already in progress')
    this._stats.puts++

    const promise = new Promise(this._enqueuePromise)

    this._operations.push(
      new RocksDBPut(this._encodeKey(key), this._encodeValue(value), this._db._columnFamily)
    )

    this._resize()

    return promise
  }

  tryPut(key, value) {
    if (this._request) throw new Error('Request already in progress')
    this._stats.puts++

    this._operations.push(
      new RocksDBPut(this._encodeKey(key), this._encodeValue(value), this._db._columnFamily)
    )

    this._promises.push(null)

    this._resize()
  }

  delete(key) {
    if (this._request) throw new Error('Request already in progress')
    this._stats.deletes++

    const promise = new Promise(this._enqueuePromise)

    this._operations.push(new RocksDBDelete(this._encodeKey(key), this._db._columnFamily))

    this._resize()

    return promise
  }

  tryDelete(key) {
    if (this._request) throw new Error('Request already in progress')
    this._stats.deletes++

    this._operations.push(new RocksDBDelete(this._encodeKey(key), this._db._columnFamily))

    this._promises.push(null)

    this._resize()
  }

  deleteRange(start, end) {
    if (this._request) throw new Error('Request already in progress')
    this._stats.rangeDeletes++

    const promise = new Promise(this._enqueuePromise)

    this._operations.push(
      new RocksDBDeleteRange(this._encodeKey(start), this._encodeKey(end), this._db._columnFamily)
    )

    this._resize()

    return promise
  }

  tryDeleteRange(start, end) {
    if (this._request) throw new Error('Request already in progress')
    this._stats.rangeDeletes++

    this._operations.push(
      new RocksDBDeleteRange(this._encodeKey(start), this._encodeKey(end), this._db._columnFamily)
    )

    this._promises.push(null)

    this._resize()
  }
}

class RocksDBGet {
  constructor(key, columnFamily) {
    this.key = key
    this.columnFamily = columnFamily._handle
  }

  get type() {
    return binding.GET
  }
}

class RocksDBPut {
  constructor(key, value, columnFamily) {
    this.key = key
    this.value = value
    this.columnFamily = columnFamily._handle
  }

  get type() {
    return binding.PUT
  }
}

class RocksDBDelete {
  constructor(key, columnFamily) {
    this.key = key
    this.columnFamily = columnFamily._handle
  }

  get type() {
    return binding.DELETE
  }
}

class RocksDBDeleteRange {
  constructor(start, end, columnFamily) {
    this.start = start
    this.end = end
    this.columnFamily = columnFamily._handle
  }

  get type() {
    return binding.DELETE_RANGE
  }
}
const binding = require('../binding')
const constants = require('./constants')
const { BloomFilterPolicy } = require('./filter-policy')

class RocksDBColumnFamily {
  constructor(name, opts = {}) {
    const {
      // Blob options
      enableBlobFiles = false,
      minBlobSize = 0,
      blobFileSize = 0,
      enableBlobGarbageCollection = true,
      // Block table options
      tableBlockSize = 8192,
      tableCacheIndexAndFilterBlocks = true,
      tableFormatVersion = 6,
      optimizeFiltersForMemory = false,
      blockCache = true,
      filterPolicy = new BloomFilterPolicy(10),
      topLevelIndexPinningTier = constants.pinningTier.ALL,
      partitionPinningTier = constants.pinningTier.ALL,
      unpartitionedPinningTier = constants.pinningTier.ALL,
      optimizeFiltersForHits = false,
      numLevels = 7,
      maxWriteBufferNumber = 2,
      blobGarbageCollectionAgeCutOff = 0.25,
      blobGarbageCollectionForceThreshold = 1.0
    } = opts

    this._name = name
    this._flushing = null
    this._options = {
      enableBlobFiles,
      minBlobSize,
      blobFileSize,
      enableBlobGarbageCollection,
      tableBlockSize,
      tableCacheIndexAndFilterBlocks,
      tableFormatVersion,
      optimizeFiltersForMemory,
      blockCache,
      filterPolicy,
      topLevelIndexPinningTier,
      partitionPinningTier,
      unpartitionedPinningTier,
      optimizeFiltersForHits,
      numLevels,
      maxWriteBufferNumber,
      blobGarbageCollectionAgeCutOff,
      blobGarbageCollectionForceThreshold
    }

    const filterPolicyArguments = [0, 0, 0]

    if (filterPolicy !== null) {
      filterPolicyArguments[0] = filterPolicy.type

      switch (filterPolicy.type) {
        case 1: // Bloom filter policy
          filterPolicyArguments[1] = filterPolicy.bitsPerKey
          break
        case 2: // Ribbon filter policy
          filterPolicyArguments[1] = filterPolicy.bloomEquivalentBitsPerKey
          filterPolicyArguments[2] = filterPolicy.bloomBeforeLevel

          break
      }
    }

    this._handle = binding.columnFamilyInit(
      name,
      enableBlobFiles,
      minBlobSize,
      blobFileSize,
      enableBlobGarbageCollection,
      tableBlockSize,
      tableCacheIndexAndFilterBlocks,
      tableFormatVersion,
      optimizeFiltersForMemory,
      blockCache === false,
      ...filterPolicyArguments,
      topLevelIndexPinningTier,
      partitionPinningTier,
      unpartitionedPinningTier,
      optimizeFiltersForHits,
      numLevels,
      maxWriteBufferNumber,
      blobGarbageCollectionAgeCutOff,
      blobGarbageCollectionForceThreshold
    )
  }

  cloneSettings(name) {
    return new RocksDBColumnFamily(name, this._options)
  }

  get name() {
    return this._name
  }

  destroy() {
    if (this._handle === null) return

    binding.columnFamilyDestroy(this._handle)

    this._handle = null
  }
}

module.exports = RocksDBColumnFamily
module.exports = {
  pinningTier: {
    NONE: 0,
    FLUSHED_AND_SIMILAR: 1,
    ALL: 2
  },
  garbageCollectionPolicy: {
    DEFAULT: 0,
    FORCE: 1,
    DISABLE: 2
  },
  bottommostLevelCompaction: {
    NONE: 0,
    SKIP: 1,
    FORCE: 2
  },
  walRecoveryMode: {
    TOLERATE_CORRUPTED_TAIL_RECORDS: 0,
    ABSOLUTE_CONSISTENCY: 1,
    POINT_IN_TIME: 2,
    SKIP_ANY_CORRUPTED_RECORDS: 3
  },
  statsLevel: {
    DISABLE_ALL: 0,
    EXCEPT_HISTOGRAM_OR_TIMERS: 1,
    EXCEPT_TIMERS: 2,
    EXCEPT_DETAILED_TIMERS: 3,
    EXCEPT_TIME_FOR_MUTEX: 4,
    ALL: 5
  },
  walFileType: {
    ARCHIVED: 0,
    ALIVE: 1
  }
}
exports.BloomFilterPolicy = class RocksDBBloomFilterPolicy {
  get type() {
    return 1
  }

  constructor(bitsPerKey) {
    this.bitsPerKey = bitsPerKey
  }
}

exports.RibbonFilterPolicy = class RocksDBRibbonFilterPolicy {
  get type() {
    return 2
  }

  constructor(bloomEquivalentBitsPerKey, bloomBeforeLevel = 0) {
    this.bloomEquivalentBitsPerKey = bloomEquivalentBitsPerKey
    this.bloomBeforeLevel = bloomBeforeLevel
  }
}
const { Readable } = require('streamx')
const c = require('compact-encoding')
const binding = require('../binding')

const empty = Buffer.alloc(0)

module.exports = class RocksDBIterator extends Readable {
  constructor(db, opts = {}) {
    const {
      gt = null,
      gte = null,
      lt = null,
      lte = null,
      reverse = false,
      values = true,
      limit = Infinity,
      capacity = 8
    } = opts

    super()

    db._ref()

    this._db = db

    this._gt = gt ? this._encodeKey(gt) : empty
    this._gte = gte ? this._encodeKey(gte) : empty
    this._lt = lt ? this._encodeKey(lt) : empty
    this._lte = lte ? this._encodeKey(lte) : empty

    this._reverse = reverse
    this._values = values
    this._limit = limit < 0 ? Infinity : limit
    this._capacity = capacity
    this._opened = false

    this._pendingOpen = null
    this._pendingRead = null
    this._pendingDestroy = null

    this._buffer = null
    this._handle = null

    if (this._db._state.opened === true) this.ready()
  }

  _onopen(err) {
    const cb = this._pendingOpen
    this._pendingOpen = null
    this._opened = true
    this._db._state.io.dec()
    cb(err)
  }

  _onread(err, keys, values) {
    const cb = this._pendingRead
    this._pendingRead = null
    this._db._state.io.dec()
    if (err) return cb(err)

    const n = keys.length

    this._limit -= n

    for (let i = 0; i < n; i++) {
      this.push({
        key: this._decodeKey(Buffer.from(keys[i])),
        value: this._values ? this._decodeValue(Buffer.from(values[i])) : null
      })
    }

    if (n < this._capacity) this.push(null)

    cb(null)
  }

  _onclose(err) {
    const cb = this._pendingDestroy
    this._pendingDestroy = null
    this._db._state.io.dec()
    this._db._unref()
    cb(err)
  }

  _resize() {
    if (this._handle !== null) {
      this._buffer = binding.iteratorBuffer(this._handle, this._capacity)
    }
  }

  async ready() {
    if (this._handle !== null) return

    if (this._db._state.opened === false) await this._db._state.ready()

    this._init()
  }

  _init() {
    this._handle = binding.iteratorInit()
    this._buffer = binding.iteratorBuffer(this._handle, this._capacity)
  }

  async _open(cb) {
    await this.ready()

    this._db._state.io.inc()

    if (this._db._state.resumed !== null) {
      const resumed = await this._db._state.resumed.promise

      if (!resumed) {
        this._db._state.io.dec()

        return cb(new Error('RocksDB session is closed'))
      }
    }

    this._pendingOpen = cb

    try {
      binding.iteratorOpen(
        this._db._state._handle,
        this._handle,
        this._db._columnFamily._handle,
        this._gt,
        this._gte,
        this._lt,
        this._lte,
        this._reverse,
        !this._values, // Keys only
        this._db._snapshot ? this._db._snapshot._handle : undefined,
        this,
        this._onopen,
        this._onclose,
        this._onread
      )
    } catch (err) {
      this._db._state.io.dec()

      cb(err)
    }
  }

  async _read(cb) {
    this._db._state.io.inc()

    if (this._db._state.resumed !== null) {
      const resumed = await this._db._state.resumed.promise

      if (!resumed) {
        this._db._state.io.dec()

        return cb(new Error('RocksDB session is closed'))
      }
    }

    this._pendingRead = cb

    try {
      binding.iteratorRead(this._handle, Math.min(this._capacity, this._limit))
    } catch (err) {
      this._db._state.io.dec()

      cb(err)
    }
  }

  async _destroy(cb) {
    await this.ready()

    this._db._state.io.inc()

    if (this._opened === false) {
      this._db._state.io.dec()
      this._db._unref()

      return cb(null)
    }

    this._pendingDestroy = cb

    try {
      binding.iteratorClose(this._handle)
    } catch (err) {
      this._db._state.io.dec()
      this._db._unref()

      cb(err)
    }
  }

  _encodeKey(k) {
    if (this._db._keyEncoding !== null) return c.encode(this._db._keyEncoding, k)
    if (typeof k === 'string') return Buffer.from(k)
    return k
  }

  _decodeKey(b) {
    if (this._db._keyEncoding !== null) return c.decode(this._db._keyEncoding, b)
    return b
  }

  _decodeValue(b) {
    if (this._db._valueEncoding !== null) return c.decode(this._db._valueEncoding, b)
    return b
  }
}
const binding = require('../binding')

module.exports = class RocksDBSnapshot {
  constructor(state) {
    this._state = state

    this._handle = null
    this._refs = 0

    if (state.deferSnapshotInit === false) this._init()
  }

  _init() {
    this._handle = binding.snapshotCreate(this._state._handle)
  }

  ref() {
    this._refs++
  }

  unref() {
    if (--this._refs > 0) return

    if (this._handle === null) return

    binding.snapshotDestroy(this._handle)

    this._handle = null
  }
}
const ReadyResource = require('ready-resource')
const RefCounter = require('refcounter')
const rrp = require('resolve-reject-promise')
const SignalPromise = require('signal-promise')
const c = require('compact-encoding')
const { ReadBatch, WriteBatch } = require('./batch')
const ColumnFamily = require('./column-family')
const binding = require('../binding')
const constants = require('./constants')

const MAX_BATCH_REUSE = 64
const empty = Buffer.alloc(0)

module.exports = class RocksDBState extends ReadyResource {
  constructor(db, path, opts) {
    super()

    const {
      columnFamily = new ColumnFamily('default', opts),
      columnFamilies = [],
      readOnly = false,
      createIfMissing = true,
      createMissingColumnFamilies = true,
      maxBackgroundJobs = 6,
      bytesPerSync = 1048576,
      maxOpenFiles = -1,
      useDirectReads = false,
      avoidUnnecessaryBlockingIO = false,
      skipStatsUpdateOnOpen = false,
      useDirectIOForFlushAndCompaction = false,
      maxFileOpeningThreads = 16,
      lock = null,
      walRecoveryMode = constants.walRecoveryMode.POINT_IN_TIME,
      bestEffortsRecovery = false,
      enableStatistics = false,
      statsLevel = constants.statsLevel.EXCEPT_HISTOGRAM_OR_TIMERS,
      walTtlSeconds = 0,
      walSizeLimitMegabytes = 0,
      avoidFlushDuringShutdown = false,
      walFilterPrefixes = []
    } = opts

    this.path = path
    this.db = db
    this.handles = new RefCounter()
    this.io = new RefCounter()
    this.sessions = []
    this.columnFamilies = [columnFamily]
    this.deferSnapshotInit = true
    this.resumed = null
    this.stats = {
      gets: 0,
      puts: 0,
      deletes: 0,
      rangeDeletes: 0,
      readBatches: 0,
      writeBatches: 0
    }

    this._suspended = false
    this._suspending = false
    this._updating = false
    this._updatingSignal = new SignalPromise()
    this._columnsFlushed = false
    this._lock = lock
    this._readBatches = []
    this._writeBatches = []

    for (const columnFamily of columnFamilies) {
      this.columnFamilies.push(
        typeof columnFamily === 'string' ? new ColumnFamily(columnFamily, opts) : columnFamily
      )
    }

    this._handle = binding.init(
      readOnly,
      createIfMissing,
      createMissingColumnFamilies,
      maxBackgroundJobs,
      bytesPerSync,
      maxOpenFiles,
      useDirectReads,
      avoidUnnecessaryBlockingIO,
      skipStatsUpdateOnOpen,
      useDirectIOForFlushAndCompaction,
      maxFileOpeningThreads,
      walRecoveryMode,
      bestEffortsRecovery,
      enableStatistics,
      statsLevel,
      walTtlSeconds,
      walSizeLimitMegabytes,
      avoidFlushDuringShutdown,
      walFilterPrefixes.map(encodePrefix)
    )
  }

  createReadBatch(db, opts) {
    if (this._readBatches.length === 0) return new ReadBatch(db, opts)
    const batch = this._readBatches.pop()
    batch._reuse(db, opts)
    return batch
  }

  createWriteBatch(db, opts) {
    if (this._writeBatches.length === 0) return new WriteBatch(db, opts)
    const batch = this._writeBatches.pop()
    batch._reuse(db, opts)
    return batch
  }

  freeBatch(batch, writable) {
    if (batch._capacity > 16) return
    const queue = writable ? this._writeBatches : this._readBatches
    if (queue.length >= MAX_BATCH_REUSE) return
    queue.push(batch)
  }

  addSession(db) {
    db._index = this.sessions.push(db) - 1
    if (db._snapshot) db._snapshot.ref()
  }

  removeSession(db) {
    const head = this.sessions.pop()
    if (head !== db) this.sessions[(head._index = db._index)] = head
    db._index = -1
    if (db._snapshot) db._snapshot.unref()
  }

  upsertColumnFamily(c) {
    if (typeof c === 'string') {
      let col = this.getColumnFamilyByName(c)
      if (col) return col
      col = this.columnFamilies[0].cloneSettings(c)
      this.columnFamilies.push(col)
      return col
    }

    if (this.columnFamilies.includes(c)) return c
    this.columnFamilies.push(c)
    return c
  }

  getColumnFamily(c) {
    if (!c) return this.columnFamilies[0]
    if (!this._columnsFlushed) return this.upsertColumnFamily(c)

    if (typeof c !== 'string') return c

    const col = this.getColumnFamilyByName(c)
    if (col === null) throw new Error('Unknown column family')
    return col
  }

  getColumnFamilyByName(name) {
    for (const col of this.columnFamilies) {
      if (col.name === name) return col
    }
    return null
  }

  async _open() {
    await Promise.resolve() // Allow column families to populate if on-demand

    if (this._lock) await this._lock.ready()

    const req = { resolve: null, reject: null, handle: null }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    this._columnsFlushed = true

    const lock = this._lock === null ? -1 : this._lock.transfer()

    req.handle = binding.open(
      this._handle,
      this,
      this.path,
      this.columnFamilies.map((c) => c._handle),
      lock,
      req,
      onopen
    )

    await promise

    this.deferSnapshotInit = false

    for (const session of this.sessions) {
      if (session._snapshot) session._snapshot._init()
    }

    function onopen(err) {
      if (err) req.reject(err)
      else req.resolve()
    }
  }

  async _close() {
    while (this._updating) await this._updatingSignal.wait()
    if (this.resumed) this.resumed.resolve(false)

    while (!this.io.isIdle()) await this.io.idle()
    while (!this.handles.isIdle()) await this.handles.idle()

    while (this.sessions.length > 0) {
      await this.sessions[this.sessions.length - 1].close()
    }

    for (const columnFamily of this.columnFamilies) columnFamily.destroy()

    const req = { resolve: null, reject: null, handle: null }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    req.handle = binding.close(this._handle, req, onclose)

    try {
      await promise
    } finally {
      if (this._lock) await this._lock.close()
    }

    function onclose(err) {
      if (err) req.reject(err)
      else req.resolve()
    }
  }

  async flush(db, opts) {
    if (this.opened === false) await this.ready()

    this.io.inc()

    if (this.resumed !== null) {
      const resumed = await this.resumed.promise

      if (!resumed) {
        this.io.dec()

        throw new Error('RocksDB session is closed')
      }
    }

    const req = { resolve: null, reject: null, handle: null }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    try {
      req.handle = binding.flush(this._handle, db._columnFamily._handle, req, onflush)

      await promise
    } finally {
      this.io.dec()
    }

    function onflush(err) {
      if (err) req.reject(err)
      else req.resolve()
    }
  }

  suspend() {
    this._suspending = true
    return this.update()
  }

  resume() {
    this._suspending = false
    return this.update()
  }

  async update() {
    while (this._updating) await this._updatingSignal.wait()
    if (this._suspending === this._suspended || this.closing) return
    this._updating = true
    try {
      if (this._suspending) await this._suspend()
      else await this._resume()
    } finally {
      this._updating = false
      this._updatingSignal.notify()
    }
  }

  async _suspend() {
    if (this._suspended === true) return

    while (!this.io.isIdle()) await this.io.idle()

    this.io.inc()
    this.resumed = rrp()

    const req = { resolve: null, reject: null, handle: null }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    try {
      req.handle = binding.suspend(this._handle, req, onsuspend)

      await promise

      this._suspended = true
    } finally {
      this.io.dec()
    }

    function onsuspend(err) {
      if (err) req.reject(err)
      else req.resolve()
    }
  }

  async _resume() {
    if (this._suspended === false) return

    const req = { resolve: null, reject: null, handle: null }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    req.handle = binding.resume(this._handle, req, onresume)

    await promise

    this._suspended = false

    const resumed = this.resumed
    this.resumed = null
    resumed.resolve(true)

    function onresume(err) {
      if (err) req.reject(err)
      else req.resolve()
    }
  }

  async compact(db, opts) {
    if (this.opened === false) await this.ready()

    this.io.inc()

    const {
      exclusive = false,
      blobGarbageCollectionPolicy = constants.garbageCollectionPolicy.DEFAULT,
      blobGarbageCollectionAgeCutoff = 0.25,
      bottommostLevelCompaction = constants.bottommostLevelCompaction.NONE
    } = opts

    const req = { resolve: null, reject: null, handle: null }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    try {
      req.handle = binding.compact(
        this._handle,
        db._columnFamily._handle,
        exclusive,
        blobGarbageCollectionPolicy,
        blobGarbageCollectionAgeCutoff,
        bottommostLevelCompaction,
        req,
        oncompact
      )

      await promise
    } finally {
      this.io.dec()
    }

    function oncompact(err) {
      if (err) req.reject(err)
      else req.resolve()
    }
  }

  async compactRange(db, start, end, opts) {
    if (this.opened === false) await this.ready()

    this.io.inc()

    const {
      exclusive = false,
      blobGarbageCollectionPolicy = constants.garbageCollectionPolicy.DEFAULT,
      blobGarbageCollectionAgeCutoff = 0.25,
      bottommostLevelCompaction = constants.bottommostLevelCompaction.NONE
    } = opts

    start = this._encodeKey(start)
    end = this._encodeKey(end)

    const req = { resolve: null, reject: null, handle: null, start, end }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    try {
      req.handle = binding.compactRange(
        this._handle,
        db._columnFamily._handle,
        start,
        end,
        exclusive,
        blobGarbageCollectionPolicy,
        blobGarbageCollectionAgeCutoff,
        bottommostLevelCompaction,
        req,
        oncompactrange
      )

      await promise
    } finally {
      this.io.dec()
    }

    function oncompactrange(err) {
      if (err) req.reject(err)
      else req.resolve()
    }
  }

  async approximateSize(db, start, end, opts) {
    if (this.opened === false) await this.ready()

    this.io.inc()

    const { includeMemtables = false, includeFiles = true, filesSizeErrorMargin = -1 } = opts

    start = this._encodeKey(start)
    end = this._encodeKey(end)

    const req = { resolve: null, reject: null, handle: null, start, end }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    try {
      req.handle = binding.approximateSize(
        this._handle,
        db._columnFamily._handle,
        start,
        end,
        includeMemtables,
        includeFiles,
        filesSizeErrorMargin,
        req,
        onapproximatesize
      )

      return await promise
    } finally {
      this.io.dec()
    }

    function onapproximatesize(err, result) {
      if (err) req.reject(err)
      else req.resolve(result)
    }
  }

  async currentWalFile() {
    if (this.opened === false) await this.ready()

    this.io.inc()

    const req = { resolve: null, reject: null, handle: null }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    try {
      req.handle = binding.currentWalFile(this._handle, req, oncurrentwalfile)

      return await promise
    } finally {
      this.io.dec()
    }

    function oncurrentwalfile(err, path, number, type, startSequence, size) {
      if (err) req.reject(err)
      else req.resolve({ path, number, type, startSequence, size })
    }
  }

  async getStatsLevel() {
    if (this.opened === false) await this.ready()

    return binding.statsLevelGet(this._handle)
  }

  async setStatsLevel(level) {
    if (this.opened === false) await this.ready()

    binding.statsLevelSet(this._handle, level)
  }

  async getProperty(name) {
    if (this.opened === false) await this.ready()

    return binding.propertyGet(this._handle, name)
  }

  _encodeKey(k) {
    if (this.db._keyEncoding) return c.encode(this.db._keyEncoding, k)
    if (typeof k === 'string') return Buffer.from(k)
    if (k === null) return empty
    return k
  }

  diagnostics() {
    return {
      suspended: this._suspended,
      suspending: this._suspending,
      updating: this._updating,
      resumedPending: this.resumed !== null,
      io: this.io.count,
      handles: this.handles.count,
      sessions: this.sessions.length
    }
  }
}

function encodePrefix(prefix) {
  if (typeof prefix === 'string') return Buffer.from(prefix)
  return prefix
}
{
  "name": "rocksdb-native",
  "version": "3.17.2",
  "description": "librocksdb bindings for JavaScript",
  "exports": {
    ".": "./index.js",
    "./package": "./package.json"
  },
  "imports": {
    "crypto": {
      "bare": "bare-crypto",
      "default": "crypto"
    },
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    }
  },
  "files": [
    "index.js",
    "binding.cc",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds",
    "!prebuilds/android-*/**/*.node"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:bare && npm run test:node",
    "test:bare": "brittle-bare --coverage test.js",
    "test:node": "brittle-node --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/rocksdb-native.git"
  },
  "author": "Holepunch Inc",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/rocksdb-native/issues"
  },
  "homepage": "https://github.com/holepunchto/rocksdb-native",
  "engines": {
    "bare": ">=1.16.0"
  },
  "dependencies": {
    "compact-encoding": "^3.0.0",
    "ready-resource": "^1.0.0",
    "refcounter": "^1.0.0",
    "require-addon": "^1.0.2",
    "resolve-reject-promise": "^1.1.0",
    "signal-promise": "^1.0.3",
    "streamx": "^2.16.1"
  },
  "devDependencies": {
    "bare-compat-napi": "^1.3.0",
    "bare-crypto": "^1.12.0",
    "bare-fs": "^4.5.0",
    "bare-path": "^3.0.0",
    "brittle": "^3.5.0",
    "cmake-bare": "^1.1.14",
    "cmake-fetch": "^1.0.1",
    "cmake-napi": "^1.0.6",
    "fd-lock": "^2.0.0",
    "lunte": "^1.8.0",
    "paparam": "^1.9.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = safetyCatch

function isActuallyUncaught (err) {
  if (!err) return false
  return err instanceof TypeError ||
    err instanceof SyntaxError ||
    err instanceof ReferenceError ||
    err instanceof EvalError ||
    err instanceof RangeError ||
    err instanceof URIError ||
    err.code === 'ERR_ASSERTION' ||
    err.name === 'AssertionError'
}

function throwErrorNT (err) {
  queueMicrotask(() => { throw err })
}

function safetyCatch (err) {
  if (isActuallyUncaught(err)) {
    throwErrorNT(err)
    throw err
  }
}
{
  "name": "safety-catch",
  "version": "1.0.3",
  "description": "Small module that makes sure your catch, caught an actual error and not a programming mistake or assertion",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {},
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/safety-catch.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/safety-catch/issues"
  },
  "homepage": "https://github.com/mafintosh/safety-catch"
}
let tmpResolve = null

module.exports = class ScopeLock {
  constructor ({ debounce = false } = {}) {
    this.debounce = debounce
    this.waiting = []
    this.locked = false
    this.skip = 0
    this.destroyed = false
  }

  flush () {
    if (this.locked === false && this.waiting.length === 0) return Promise.resolve(this.destroyed === false)

    const promise = new Promise(setTmpResolve)
    const resolve = tmpResolve

    tmpResolve = null
    this.waiting.push({ lock: false, resolve })

    return promise
  }

  destroy () {
    this.destroyed = true
  }

  lock () {
    const promise = new Promise(setTmpResolve)
    const resolve = tmpResolve

    tmpResolve = null

    if (this.locked === true) {
      this.waiting.push({ lock: true, resolve })
      return promise
    }

    if (this.destroyed === true) {
      resolve(false)
      return promise
    }

    this.locked = true
    resolve(true)

    return promise
  }

  unlock () {
    if (this.destroyed === true) {
      for (let i = 0; i < this.waiting.length; i++) {
        this.waiting[i].resolve(false)
      }
      this.waiting = []
      this.skip = 0
      this.locked = false
      return
    }

    if (this.skip !== 0) {
      for (let i = 0; i < this.skip; i++) {
        const { lock, resolve } = this.waiting[i]
        resolve(lock === false)
      }

      this.waiting = this.waiting.slice(this.skip)
      this.skip = 0
    }

    while (this.waiting.length > 0 && this.waiting[0].lock === false) {
      this.waiting.shift().resolve(true)
    }

    if (this.waiting.length === 0) {
      this.locked = false
      return
    }

    const { resolve } = this.waiting.shift()
    if (this.debounce === true) this.skip = this.waiting.length

    resolve(true)
  }
}

function setTmpResolve (resolve) {
  tmpResolve = resolve
}
{
  "name": "scope-lock",
  "version": "1.2.4",
  "description": "Some concurrency semantics around entering scopes",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "devDependencies": {
    "brittle": "^3.7.0",
    "standard": "^17.1.2"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/scope-lock.git"
  },
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/scope-lock/issues"
  },
  "homepage": "https://github.com/holepunchto/scope-lock"
}
module.exports = class Signal {
  constructor () {
    this._resolve = null
    this._reject = null
    this._promise = null
    this._bind = bind.bind(this)
    this._onerror = clear.bind(this)
    this._onsuccess = clear.bind(this, null)
    this._timers = new Set()
  }

  wait (max) {
    if (!this._promise) {
      this._promise = new Promise(this._bind)
      this._promise.then(this._onsuccess).catch(this._onerror)
    }
    if (max) return this._sleep(max)
    return this._promise
  }

  _sleep (max) {
    const s = new Promise((resolve, reject) => {
      const done = () => {
        this._timers.delete(state)
        resolve(true)
      }
      const id = setTimeout(done, max)
      const state = { id, resolve, reject }
      this._timers.add(state)
    })

    return s
  }

  notify (err) {
    if (!this._promise) return
    const resolve = this._resolve
    const reject = this._reject
    this._promise = null
    if (err) reject(err)
    else resolve(true)
  }
}

function clear (err) {
  for (const { id, resolve, reject } of this._timers) {
    clearTimeout(id)
    if (err) reject(err)
    else resolve(true)
  }
  this._timers.clear()
}

function bind (resolve, reject) {
  this._resolve = resolve
  this._reject = reject
}
{
  "name": "signal-promise",
  "version": "1.0.3",
  "description": "Simple wait/notify promise with optional max wait time",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {},
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/signal-promise.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/signal-promise/issues"
  },
  "homepage": "https://github.com/mafintosh/signal-promise"
}
var varint = require('varint')
exports.encode = function encode (v, b, o) {
  v = v >= 0 ? v*2 : v*-2 - 1
  var r = varint.encode(v, b, o)
  encode.bytes = varint.encode.bytes
  return r
}
exports.decode = function decode (b, o) {
  var v = varint.decode(b, o)
  decode.bytes = varint.decode.bytes
  return v & 1 ? (v+1) / -2 : v / 2
}

exports.encodingLength = function (v) {
  return varint.encodingLength(v >= 0 ? v*2 : v*-2 - 1)
}
{
  "name": "signed-varint",
  "description": "efficiently store signed integers in varint",
  "version": "2.0.1",
  "homepage": "https://github.com/dominictarr/signed-varint",
  "repository": {
    "type": "git",
    "url": "git://github.com/dominictarr/signed-varint.git"
  },
  "dependencies": {
    "varint": "~5.0.0"
  },
  "devDependencies": {
    "tape": "~2.12.3"
  },
  "scripts": {
    "test": "node test.js"
  },
  "author": "Dominic Tarr <dominic.tarr@gmail.com> (http://dominictarr.com)",
  "license": "MIT"
}
require.addon = require('require-addon')

module.exports = require.addon('.', __filename)
const binding = require('./binding')
const b4a = require('b4a')

function predicate(u8, u16, u32) {
  return function predicate(buf) {
    if (buf.byteLength % 16 !== 0) {
      throw new Error('Buffer length must be a multiple of 16')
    }

    const n = buf.BYTES_PER_ELEMENT

    if (n === 1) return u8(buf)
    if (n === 2) return u16(buf)
    return u32(buf)
  }
}

function unary(u8, u16, u32) {
  return function unary(buf, result = b4a.allocUnsafe(buf.byteLength)) {
    if (buf.byteLength % 16 !== 0) {
      throw new Error('Buffer length must be a multiple of 16')
    }

    if (buf.byteLength !== result.byteLength) {
      throw new Error('Length of result buffer is insufficient')
    }

    const n = buf.BYTES_PER_ELEMENT

    if (n === 1) u8(buf, result)
    else if (n === 2) u16(buf, result)
    else u32(buf, result)

    return result
  }
}

function binary(u8, u16, u32) {
  return function binary(a, b, result = b4a.allocUnsafe(a.byteLength)) {
    if (a.byteLength % 16 !== 0) {
      throw new Error('Buffer length must be a multiple of 16')
    }

    if (a.byteLength !== b.byteLength || a.byteLength !== result.byteLength) {
      throw new Error('Buffers must be the same length')
    }

    const n = a.BYTES_PER_ELEMENT

    if (n === 1) u8(a, b, result)
    else if (n === 2) u16(a, b, result)
    else u32(a, b, result)

    return result
  }
}

function reduce(u8, u16, u32) {
  return function reduce(buf) {
    if (buf.byteLength % 16 !== 0) {
      throw new Error('Buffer length must be a multiple of 16')
    }

    const n = buf.BYTES_PER_ELEMENT

    if (n === 1) return u8(buf)
    if (n === 2) return u16(buf)
    return u32(buf)
  }
}

exports.allo = predicate(
  binding.simdle_native_allo_v128_u8,
  binding.simdle_native_allo_v128_u16,
  binding.simdle_native_allo_v128_u32
)

exports.allz = predicate(
  binding.simdle_native_allz_v128_u8,
  binding.simdle_native_allz_v128_u16,
  binding.simdle_native_allz_v128_u32
)

exports.and = binary(
  binding.simdle_native_and_v128_u8,
  binding.simdle_native_and_v128_u16,
  binding.simdle_native_and_v128_u32
)

exports.clear = binary(
  binding.simdle_native_clear_v128_u8,
  binding.simdle_native_clear_v128_u16,
  binding.simdle_native_clear_v128_u32
)

exports.clo = unary(
  binding.simdle_native_clo_v128_u8,
  binding.simdle_native_clo_v128_u16,
  binding.simdle_native_clo_v128_u32
)

exports.clz = unary(
  binding.simdle_native_clz_v128_u8,
  binding.simdle_native_clz_v128_u16,
  binding.simdle_native_clz_v128_u32
)

exports.cnt = unary(
  binding.simdle_native_cnt_v128_u8,
  binding.simdle_native_cnt_v128_u16,
  binding.simdle_native_cnt_v128_u32
)

exports.cto = unary(
  binding.simdle_native_cto_v128_u8,
  binding.simdle_native_cto_v128_u16,
  binding.simdle_native_cto_v128_u32
)

exports.ctz = unary(
  binding.simdle_native_ctz_v128_u8,
  binding.simdle_native_ctz_v128_u16,
  binding.simdle_native_ctz_v128_u32
)

exports.not = unary(
  binding.simdle_native_not_v128_u8,
  binding.simdle_native_not_v128_u16,
  binding.simdle_native_not_v128_u32
)

exports.or = binary(
  binding.simdle_native_or_v128_u8,
  binding.simdle_native_or_v128_u16,
  binding.simdle_native_or_v128_u32
)

exports.sum = reduce(
  binding.simdle_native_sum_v128_u8,
  binding.simdle_native_sum_v128_u16,
  binding.simdle_native_sum_v128_u32
)

exports.xor = binary(
  binding.simdle_native_xor_v128_u8,
  binding.simdle_native_xor_v128_u16,
  binding.simdle_native_xor_v128_u32
)
{
  "name": "simdle-native",
  "version": "1.3.9",
  "description": "libsimdle JavaScript bindings for Node.js",
  "main": "index.js",
  "files": [
    "index.js",
    "binding.cc",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check .",
    "test": "npm run lint && npm run test:bare && npm run test:node",
    "test:bare": "bare test.mjs",
    "test:node": "node test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/simdle-native.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/simdle-native/issues"
  },
  "homepage": "https://github.com/holepunchto/simdle-native#readme",
  "dependencies": {
    "b4a": "^1.6.0",
    "require-addon": "^1.1.0"
  },
  "devDependencies": {
    "bare-compat-napi": "^1.3.2",
    "brittle": "^3.1.0",
    "cmake-bare": "^1.1.7",
    "cmake-fetch": "^1.1.0",
    "cmake-napi": "^1.0.2",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  }
}
const b4a = require('b4a')
const scalar = require('./scalar')

function view (buf, n) {
  if (n === buf.BYTES_PER_ELEMENT) return buf

  let TypedArray

  if (n === 1) TypedArray = Uint8Array
  else if (n === 2) TypedArray = Uint16Array
  else TypedArray = Uint32Array

  return new TypedArray(buf.buffer, buf.byteOffset, buf.byteLength / n)
}

function unary (u8, u16 = u8, u32 = u16) {
  return function unary (buf, result = b4a.allocUnsafe(buf.byteLength)) {
    if (buf.byteLength % 16 !== 0) {
      throw new Error('Buffer length must be a multiple of 16')
    }

    if (buf.byteLength !== result.byteLength) {
      throw new Error('Length of result buffer is insufficient')
    }

    const n = buf.BYTES_PER_ELEMENT

    if (n === 1) u8(buf, view(result, n))
    else if (n === 2) u16(buf, view(result, n))
    else u32(buf, view(result, n))

    return result
  }
}

function binary (u8, u16 = u8, u32 = u16) {
  return function binary (a, b, result = b4a.allocUnsafe(a.byteLength)) {
    if (a.byteLength % 16 !== 0) {
      throw new Error('Buffer length must be a multiple of 16')
    }

    if (a.byteLength !== b.byteLength || a.byteLength !== result.byteLength) {
      throw new Error('Buffers must be the same length')
    }

    const n = a.BYTES_PER_ELEMENT

    if (n === 1) u8(a, b, view(result, n))
    else if (n === 2) u16(a, b, view(result, n))
    else u32(a, b, view(result, n))

    return result
  }
}

function reduce (u8, u16 = u8, u32 = u16) {
  return function reduce (buf) {
    if (buf.byteLength % 16 !== 0) {
      throw new Error('Buffer length must be a multiple of 16')
    }

    const n = buf.BYTES_PER_ELEMENT

    if (n === 1) return u8(buf)
    if (n === 2) return u16(buf)
    return u32(buf)
  }
}

exports.allo = function allo (buf) {
  if (buf.byteLength % 16 !== 0) {
    throw new Error('Buffer length must be a multiple of 16')
  }

  const m = 2 ** (buf.BYTES_PER_ELEMENT * 8) - 1

  for (let i = 0, n = buf.length; i < n; i++) {
    if (buf[i] !== m) return false
  }

  return true
}

exports.allz = function allz (buf) {
  if (buf.byteLength % 16 !== 0) {
    throw new Error('Buffer length must be a multiple of 16')
  }

  for (let i = 0, n = buf.length; i < n; i++) {
    if (buf[i] !== 0) return false
  }

  return true
}

exports.and = binary(
  (a, b, result) => {
    for (let i = 0, n = result.length; i < n; i++) {
      result[i] = a[i] & b[i]
    }
  }
)

exports.clear = binary(
  (a, b, result) => {
    for (let i = 0, n = result.length; i < n; i++) {
      result[i] = a[i] & ~b[i]
    }
  }
)

exports.clo = unary(
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = 24 - scalar.clo(buf[i])
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = 16 - scalar.clo(buf[i])
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = scalar.clo(buf[i])
    }
  }
)

exports.clz = unary(
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = 24 - scalar.clz(buf[i])
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = 16 - scalar.clz(buf[i])
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = scalar.clz(buf[i])
    }
  }
)

exports.cnt = unary(
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = scalar.cnt(buf[i]) & 0xff
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = scalar.cnt(buf[i]) & 0xffff
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = scalar.cnt(buf[i])
    }
  }
)

exports.cto = unary(
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = Math.min(scalar.cto(buf[i]), 8)
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = Math.min(scalar.cto(buf[i]), 16)
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = scalar.cto(buf[i])
    }
  }
)

exports.ctz = unary(
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = Math.min(scalar.ctz(buf[i]), 8)
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = Math.min(scalar.ctz(buf[i]), 16)
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = scalar.ctz(buf[i])
    }
  }
)

exports.not = unary(
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = ~buf[i]
    }
  }
)

exports.or = binary(
  (a, b, result) => {
    for (let i = 0, n = result.length; i < n; i++) {
      result[i] = a[i] | b[i]
    }
  }
)

exports.sum = reduce(
  (buf) => {
    let result = 0n

    for (let i = 0, n = buf.length; i < n; i++) {
      result += BigInt(buf[i])
    }

    return result
  }
)

exports.xor = binary(
  (a, b, result) => {
    for (let i = 0, n = result.length; i < n; i++) {
      result[i] = a[i] ^ b[i]
    }
  }
)
try {
  module.exports = require('simdle-native')
} catch {
  module.exports = require('./fallback')
}
{
  "name": "simdle-universal",
  "version": "1.1.2",
  "description": "Universal wrapper for libsimdle with a JavaScript fallback",
  "main": "index.js",
  "files": [
    "fallback.js",
    "index.js",
    "scalar.js"
  ],
  "browser": {
    "./index.js": "./fallback.js"
  },
  "scripts": {
    "test": "standard && brittle test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/simdle-universal.git"
  },
  "author": "Kasper Isager Dalsgarð <kasper@funktionel.co>",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/holepunchto/simdle-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/simdle-universal#readme",
  "dependencies": {
    "b4a": "^1.6.0"
  },
  "optionalDependencies": {
    "simdle-native": "^1.1.1"
  },
  "devDependencies": {
    "brittle": "^3.1.0",
    "standard": "^17.0.0"
  }
}
const clz = exports.clz = function clz (n) {
  return Math.clz32(n)
}

exports.clo = function clo (n) {
  return clz(~n)
}

const ctz = exports.ctz = function ctz (n) {
  return 32 - (n === 0 ? 0 : (clz(n & -n) + 1))
}

exports.cto = function cto (n) {
  return ctz(~n)
}

exports.cnt = function cnt (n) {
  n = n - ((n >>> 1) & 0x55555555)
  n = (n & 0x33333333) + ((n >>> 2) & 0x33333333)
  n = (n + (n >>> 4)) & 0x0f0f0f0f
  n = (n * 0x01010101) >>> 24
  return n
}
require.addon = require('require-addon')
module.exports = require.addon('.', __filename)
const assert = require('assert')
const binding = require('./binding')
const { isNode } = require('which-runtime')

const OPTIONAL = Buffer.from(new ArrayBuffer(0))

module.exports = exports = { ...binding }

// memory

exports.sodium_memzero = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  binding.sodium_memzero(buf)
}

exports.sodium_mlock = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  const res = binding.sodium_mlock(buf)

  if (res !== 0) throw new Error('memory lock failed')
}

exports.sodium_munlock = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  const res = binding.sodium_munlock(buf)

  if (res !== 0) throw new Error('memory unlock failed')
}

exports.sodium_malloc = function (size) {
  assert(size >= 0, 'invalid size')

  const buf = Buffer.from(binding.sodium_malloc(size))
  buf.secure = true
  return buf
}

exports.sodium_free = function (buf) {
  if (!buf || !buf.secure) return

  binding.sodium_free(buf.buffer)
}

exports.sodium_mprotect_noaccess = function (buf) {
  const res = binding.sodium_mprotect_noaccess(buf.buffer)

  if (res !== 0) throw new Error('failed to lock buffer')
}

exports.sodium_mprotect_readonly = function (buf) {
  const res = binding.sodium_mprotect_readonly(buf.buffer)

  if (res !== 0) throw new Error('failed to unlock buffer')
}

exports.sodium_mprotect_readwrite = function (buf) {
  const res = binding.sodium_mprotect_readwrite(buf.buffer)

  if (res !== 0) throw new Error('failed to unlock buffer')
}

// crypto_randombytes

exports.randombytes_buf = function (buffer) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')

  binding.randombytes_buf(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

exports.randombytes_buf_deterministic = function (buffer, seed) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    seed.byteLength === binding.randombytes_SEEDBYTES,
    "seed must be 'randombytes_SEEDBYTES' bytes"
  )

  binding.randombytes_buf_deterministic(
    buffer.buffer,
    buffer.byteOffset,
    buffer.byteLength,

    seed.buffer,
    seed.byteOffset,
    seed.byteLength
  )
}

// sodium_helpers

exports.sodium_memcmp = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  return binding.sodium_memcmp(a, b)
}

exports.sodium_add = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  binding.sodium_add(a, b)
}

exports.sodium_sub = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  binding.sodium_sub(a, b)
}

exports.sodium_compare = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  return binding.sodium_compare(a, b)
}

exports.sodium_is_zero = function (buffer, length) {
  if (length === undefined) length = buffer.byteLength

  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(length >= 0 && length <= buffer.byteLength, 'invalid length')

  return binding.sodium_is_zero(buffer, length)
}

exports.sodium_pad = function (buffer, unpaddedBuflen, blockSize) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(unpaddedBuflen <= buffer.byteLength, 'unpadded length cannot exceed buffer length')
  assert(blockSize <= buffer.byteLength, 'block size cannot exceed buffer length')
  assert(blockSize >= 1, 'block size must be at least 1 byte')
  assert(
    buffer.byteLength >= unpaddedBuflen + (blockSize - (unpaddedBuflen % blockSize)),
    'buf not long enough'
  )

  return binding.sodium_pad(buffer, unpaddedBuflen, blockSize)
}

exports.sodium_unpad = function (buffer, paddedBuflen, blockSize) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(paddedBuflen <= buffer.byteLength, 'unpadded length cannot exceed buffer length')
  assert(blockSize <= buffer.byteLength, 'block size cannot exceed buffer length')
  assert(blockSize >= 1, 'block size must be at least 1 byte')

  return binding.sodium_unpad(buffer, paddedBuflen, blockSize)
}

// crypto_sign

exports.crypto_sign_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )
  assert(
    seed.byteLength === binding.crypto_sign_SEEDBYTES,
    "seed must be 'crypto_sign_SEEDBYTES' bytes"
  )

  const res = binding.crypto_sign_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign = function (sm, m, sk) {
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sm.byteLength === binding.crypto_sign_BYTES + m.byteLength,
    "sm must be 'm.byteLength + crypto_sign_BYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign(sm, m, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_open = function (m, sm, pk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sm.byteLength >= binding.crypto_sign_BYTES,
    "sm must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    m.byteLength === sm.byteLength - binding.crypto_sign_BYTES,
    "m must be 'sm.byteLength - crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_open(m, sm, pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_open = function (m, sm, pk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sm.byteLength >= binding.crypto_sign_BYTES,
    "sm must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    m.byteLength === sm.byteLength - binding.crypto_sign_BYTES,
    "m must be 'sm.byteLength - crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  return binding.crypto_sign_open(m, sm, pk)
}

exports.crypto_sign_detached = function (sig, m, sk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(sig.byteLength === binding.crypto_sign_BYTES, "sig must be 'crypto_sign_BYTES' bytes")
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_detached(sig, m, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_verify_detached = function (sig, m, pk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sig.byteLength >= binding.crypto_sign_BYTES,
    "sig must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  return binding.crypto_sign_verify_detached(
    sig.buffer,
    sig.byteOffset,
    sig.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    pk.buffer,
    pk.byteOffset,
    pk.byteLength
  )
}

exports.crypto_sign_ed25519_sk_to_pk = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_sk_to_pk(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_ed25519_pk_to_curve25519 = function (x25519pk, ed25519pk) {
  assert(ArrayBuffer.isView(x25519pk), 'x25519pk must be a typed array')
  assert(ArrayBuffer.isView(ed25519pk), 'ed25519pk must be a typed array')
  assert(
    x25519pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "x25519pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    ed25519pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "ed25519pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_pk_to_curve25519(x25519pk, ed25519pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_ed25519_sk_to_curve25519 = function (x25519sk, ed25519sk) {
  assert(ArrayBuffer.isView(x25519sk), 'x25519sk must be a typed array')
  assert(ArrayBuffer.isView(ed25519sk), 'ed25519sk must be a typed array')
  assert(
    x25519sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "x25519sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const edLen = ed25519sk.byteLength

  assert(
    edLen === binding.crypto_sign_SECRETKEYBYTES || edLen === binding.crypto_box_SECRETKEYBYTES,
    "ed25519sk must be 'crypto_sign_SECRETKEYBYTES' or 'crypto_sign_SECRETKEYBYTES - crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_sk_to_curve25519(x25519sk, ed25519sk)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_box

exports.crypto_box_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    seed.byteLength === binding.crypto_box_SEEDBYTES,
    "seed must be 'crypto_box_SEEDBYTES' bytes"
  )

  const res = binding.crypto_box_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_easy = function (c, m, n, pk, sk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength === m.byteLength + exports.crypto_box_MACBYTES,
    "c must be 'm.byteLength + crypto_box_MACBYTES' bytes"
  )
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_easy(c, m, n, pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_detached = function (c, mac, m, n, pk, sk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(mac.byteLength === exports.crypto_box_MACBYTES, "mac must be 'crypto_box_MACBYTES' bytes")
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_detached(c, mac, m, n, pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_open_easy = function (m, c, n, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength >= exports.crypto_box_MACBYTES,
    "c must be at least 'crypto_box_MACBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - exports.crypto_box_MACBYTES,
    "m must be 'c.byteLength - crypto_box_MACBYTES' bytes"
  )
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_open_easy(m, c, n, pk, sk)
}

exports.crypto_box_open_detached = function (m, c, mac, n, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(mac.byteLength === exports.crypto_box_MACBYTES, "mac must be 'crypto_box_MACBYTES' bytes")
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_open_detached(m, c, mac, n, pk, sk)
}

exports.crypto_box_seal = function (c, m, pk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    c.byteLength === m.byteLength + exports.crypto_box_SEALBYTES,
    "c must be 'm.byteLength + crypto_box_SEALBYTES' bytes"
  )
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_box_seal(c, m, pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_seal_open = function (m, c, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength >= exports.crypto_box_SEALBYTES,
    "c must be at least 'crypto_box_SEALBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - exports.crypto_box_SEALBYTES,
    "m must be 'c.byteLength - crypto_box_SEALBYTES' bytes"
  )
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_seal_open(
    m.buffer,
    m.byteOffset,
    m.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    pk.buffer,
    pk.byteOffset,
    pk.byteLength,

    sk.buffer,
    sk.byteOffset,
    sk.byteLength
  )
}

// crypto_secretbox

exports.crypto_secretbox_easy = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_secretbox_MACBYTES,
    "c must be 'm.byteLength + crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretbox_easy(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretbox_open_easy = function (m, c, n, k) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    c.byteLength >= binding.crypto_secretbox_MACBYTES,
    "c must be at least 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - binding.crypto_secretbox_MACBYTES,
    "m must be 'c.byteLength - crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  return binding.crypto_secretbox_open_easy(m, c, n, k)
}

exports.crypto_secretbox_detached = function (c, mac, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    mac.byteLength === binding.crypto_secretbox_MACBYTES,
    "mac must be 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretbox_detached(c, mac, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretbox_open_detached = function (m, c, mac, n, k) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(
    mac.byteLength === binding.crypto_secretbox_MACBYTES,
    "mac must be 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  return binding.crypto_secretbox_open_detached(m, c, mac, n, k)
}

// crypto_generichash

exports.crypto_generichash = function (output, input, key) {
  if (!key) key = OPTIONAL

  assert(ArrayBuffer.isView(output), 'output must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    output.byteLength >= binding.crypto_generichash_BYTES_MIN &&
      output.byteLength <= binding.crypto_generichash_BYTES_MAX,
    'output must be between crypto_generichash_BYTES_MIN and crypto_generichash_BYTES_MAX bytes'
  )

  if (key !== OPTIONAL) {
    assert(ArrayBuffer.isView(key), 'key must be a typed array')
    assert(
      key.byteLength >= binding.crypto_generichash_KEYBYTES_MIN &&
        key.byteLength <= binding.crypto_generichash_KEYBYTES_MAX,
      'key must be between crypto_generichash_KEYBYTES_MIN and crypto_generichash_KEYBYTES_MAX bytes'
    )
  }

  const res = binding.crypto_generichash(
    output.buffer,
    output.byteOffset,
    output.byteLength,

    input.buffer,
    input.byteOffset,
    input.byteLength,

    key.buffer,
    key.byteOffset,
    key.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_batch = function (output, batch, key) {
  assert(ArrayBuffer.isView(output), 'output must be a typed array')

  if (isNode || batch.length < 4) {
    const res = binding.crypto_generichash_batch(output, batch, !!key, key || OPTIONAL)
    if (res !== 0) throw new Error('status: ' + res)
  } else {
    const state = Buffer.alloc(binding.crypto_generichash_STATEBYTES)

    exports.crypto_generichash_init(state, key, output.byteLength)

    for (const buf of batch) {
      exports.crypto_generichash_update(state, buf)
    }

    exports.crypto_generichash_final(state, output)
  }
}

exports.crypto_generichash_keygen = function (key) {
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(
    key.byteLength === binding.crypto_generichash_KEYBYTES,
    "key must be 'crypto_generichash_KEYBYTES' bytes"
  )

  const res = binding.crypto_generichash_keygen(key.buffer, key.byteOffset, key.byteLength)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_init = function (state, key, outputLength) {
  if (!key) key = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_init(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    key.buffer,
    key.byteOffset,
    key.byteLength,

    outputLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_update(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    input.buffer,
    input.byteOffset,
    input.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_final = function (state, output) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(output), 'output must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_final(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    output.buffer,
    output.byteOffset,
    output.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

// secretstream

exports.crypto_secretstream_xchacha20poly1305_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  binding.crypto_secretstream_xchacha20poly1305_keygen(k.buffer, k.byteOffset, k.byteLength)
}

exports.crypto_secretstream_xchacha20poly1305_init_push = function (state, header, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(header), 'header must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    header.byteLength === binding.crypto_secretstream_xchacha20poly1305_HEADERBYTES,
    "header must be 'crypto_secretstream_xchacha20poly1305_HEADERBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_init_push(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    header.buffer,
    header.byteOffset,
    header.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretstream_xchacha20poly1305_init_pull = function (state, header, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(header), 'header must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    header.byteLength === binding.crypto_secretstream_xchacha20poly1305_HEADERBYTES,
    "header must be 'crypto_secretstream_xchacha20poly1305_HEADERBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_init_pull(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    header.buffer,
    header.byteOffset,
    header.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretstream_xchacha20poly1305_push = function (state, c, m, ad, tag) {
  if (!ad) ad = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    c.byteLength === m.byteLength + binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "c must be 'm.byteLength + crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_push(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    ad.buffer,
    ad.byteOffset,
    ad.byteLength,

    tag
  )

  if (res < 0) throw new Error('push failed')

  return res
}

exports.crypto_secretstream_xchacha20poly1305_pull = function (state, m, tag, c, ad) {
  if (!ad) ad = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(tag), 'tag must be a typed array')
  assert(tag.byteLength === 1, 'tag must be 1 byte')

  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    c.byteLength >= binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "c must be at least 'crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "m must be 'c.byteLength - crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_pull(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    tag.buffer,
    tag.byteOffset,
    tag.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    ad.buffer,
    ad.byteOffset,
    ad.byteLength
  )

  if (res < 0) throw new Error('pull failed')

  return res
}

exports.crypto_secretstream_xchacha20poly1305_rekey = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )

  binding.crypto_secretstream_xchacha20poly1305_rekey(
    state.buffer,
    state.byteOffset,
    state.byteLength
  )
}

// crypto_stream

exports.crypto_stream = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xor(
    c.buffer,
    c.byteOffset,
    c.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    n.buffer,
    n.byteOffset,
    n.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_auth

exports.crypto_auth = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(out.byteLength === binding.crypto_auth_BYTES, "out must be 'crypto_auth_BYTES' bytes")
  assert(k.byteLength === binding.crypto_auth_KEYBYTES, "k must be 'crypto_auth_KEYBYTES' bytes")

  const res = binding.crypto_auth(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_auth_verify = function (h, input, k) {
  assert(ArrayBuffer.isView(h), 'h must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(h.byteLength === binding.crypto_auth_BYTES, "h must be 'crypto_auth_BYTES' bytes")
  assert(k.byteLength === binding.crypto_auth_KEYBYTES, "k must be 'crypto_auth_KEYBYTES' bytes")

  return binding.crypto_auth_verify(h, input, k)
}

// crypto_onetimeauth

exports.crypto_onetimeauth = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    out.byteLength === binding.crypto_onetimeauth_BYTES,
    "out must be 'crypto_onetimeauth_BYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_init = function (state, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_init(state, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )
  assert(
    out.byteLength === binding.crypto_onetimeauth_BYTES,
    "out must be 'crypto_onetimeauth_BYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_verify = function (h, input, k) {
  assert(ArrayBuffer.isView(h), 'h must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    h.byteLength === binding.crypto_onetimeauth_BYTES,
    "h must be 'crypto_onetimeauth_BYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  return binding.crypto_onetimeauth_verify(h, input, k)
}

// crypto_pwhash

exports.crypto_pwhash = function (out, passwd, salt, opslimit, memlimit, alg) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_BYTES_MIN,
    "out must be at least 'crypto_pwhash_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_BYTES_MAX,
    "out must be at most 'crypto_pwhash_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_SALTBYTES,
    "salt must be 'crypto_pwhash_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )
  assert(alg >= 1 && alg <= 2, 'alg must be either Argon2i 1.3 or Argon2id 1.3')

  const res = binding.crypto_pwhash(out, passwd, salt, opslimit, memlimit, alg)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_async = function (
  out,
  passwd,
  salt,
  opslimit,
  memlimit,
  alg,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_BYTES_MIN,
    "out must be at least 'crypto_pwhash_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_BYTES_MAX,
    "out must be at most 'crypto_pwhash_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_SALTBYTES,
    "salt must be 'crypto_pwhash_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )
  assert(alg >= 1 && alg <= 2, 'alg must be either Argon2i 1.3 or Argon2id 1.3')

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    opslimit,
    memlimit,
    alg,

    done
  )

  return promise
}

exports.crypto_pwhash_str = function (out, passwd, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_STRBYTES,
    "out must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(typeof opslimit === 'number', 'opslimit must be a number')
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(typeof memlimit === 'number', 'memlimit must be a number')
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_str(out, passwd, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_str_async = function (out, passwd, opslimit, memlimit, callback = undefined) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_STRBYTES,
    "out must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(typeof opslimit === 'number', 'opslimit must be a number')
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(typeof memlimit === 'number', 'memlimit must be a number')
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_str_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_str_verify = function (str, passwd) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )

  return binding.crypto_pwhash_str_verify(str, passwd)
}

exports.crypto_pwhash_str_verify_async = function (str, passwd, callback = undefined) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  const [done, promise] = checkStatus(callback, true)

  binding.crypto_pwhash_str_verify_async(
    str.buffer,
    str.byteOffset,
    str.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    done
  )

  return promise
}

exports.crypto_pwhash_str_needs_rehash = function (str, opslimit, memlimit) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  return binding.crypto_pwhash_str_needs_rehash(str, opslimit, memlimit)
}

exports.crypto_pwhash_scryptsalsa208sha256 = function (out, passwd, salt, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MIN,
    "out must be at least 'crypto_pwhash_scryptsalsa208sha256_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MAX,
    "out must be at most 'crypto_pwhash_scryptsalsa208sha256_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_SALTBYTES,
    "salt must be 'crypto_pwhash_scryptsalsa208sha256_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_scryptsalsa208sha256(out, passwd, salt, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_scryptsalsa208sha256_async = function (
  out,
  passwd,
  salt,
  opslimit,
  memlimit,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MIN,
    "out must be at least 'crypto_pwhash_scryptsalsa208sha256_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MAX,
    "out must be at most 'crypto_pwhash_scryptsalsa208sha256_BYTES_MAX' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    salt.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_SALTBYTES,
    "salt must be 'crypto_pwhash_scryptsalsa208sha256_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_scryptsalsa208sha256_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str_async = function (
  out,
  passwd,
  opslimit,
  memlimit,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "out must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_scryptsalsa208sha256_str_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str = function (out, passwd, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "out must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_scryptsalsa208sha256_str(out, passwd, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_scryptsalsa208sha256_str_verify_async = function (
  str,
  passwd,
  callback = undefined
) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  const [done, promise] = checkStatus(callback, true)

  binding.crypto_pwhash_scryptsalsa208sha256_str_verify_async(
    str.buffer,
    str.byteOffset,
    str.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str_verify = function (str, passwd) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  return binding.crypto_pwhash_scryptsalsa208sha256_str_verify(str, passwd)
}

exports.crypto_pwhash_scryptsalsa208sha256_str_needs_rehash = function (str, opslimit, memlimit) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  return binding.crypto_pwhash_scryptsalsa208sha256_str_needs_rehash(str, opslimit, memlimit)
}

// crypto_kx

exports.crypto_kx_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "pk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "sk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    pk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "pk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "sk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    seed.byteLength === binding.crypto_kx_SEEDBYTES,
    "seed must be 'crypto_kx_SEEDBYTES' bytes"
  )

  const res = binding.crypto_kx_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_client_session_keys = function (rx, tx, clientPk, clientSk, serverPk) {
  if (!rx) rx = undefined
  if (!tx) tx = undefined

  assert(rx || tx, 'at least one session key must be specified')

  if (rx) {
    assert(ArrayBuffer.isView(rx), 'rx must be a typed array')
    assert(
      rx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "rx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  if (tx) {
    assert(ArrayBuffer.isView(tx), 'tx must be a typed array')
    assert(
      tx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "tx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  assert(ArrayBuffer.isView(clientPk), 'clientPk must be a typed array')
  assert(ArrayBuffer.isView(clientSk), 'clientSk must be a typed array')
  assert(ArrayBuffer.isView(serverPk), 'serverPk must be a typed array')
  assert(
    clientPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "clientPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    clientSk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "clientSk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    serverPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "serverPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_client_session_keys(rx, tx, clientPk, clientSk, serverPk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_server_session_keys = function (rx, tx, serverPk, serverSk, clientPk) {
  if (!rx) rx = undefined
  if (!tx) tx = undefined

  assert(rx || tx, 'at least one session key must be specified')

  if (rx) {
    assert(ArrayBuffer.isView(rx), 'rx must be a typed array')
    assert(
      rx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "rx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  if (tx) {
    assert(ArrayBuffer.isView(tx), 'tx must be a typed array')
    assert(
      tx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "tx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  assert(ArrayBuffer.isView(serverPk), 'serverPk must be a typed array')
  assert(ArrayBuffer.isView(serverSk), 'serverSk must be a typed array')
  assert(ArrayBuffer.isView(clientPk), 'clientPk must be a typed array')
  assert(
    serverPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "serverPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    serverSk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "serverSk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    clientPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "clientPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_server_session_keys(rx, tx, serverPk, serverSk, clientPk)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_scalarmult

exports.crypto_scalarmult_base = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_BYTES,
    "q must be 'crypto_scalarmult_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_SCALARBYTES,
    "n must be 'crypto_scalarmult_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_base(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_BYTES,
    "q must be 'crypto_scalarmult_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_SCALARBYTES,
    "n must be 'crypto_scalarmult_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_BYTES,
    "p must be 'crypto_scalarmult_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_base = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_base(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519 = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "p must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_is_valid_point = function (p) {
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )

  return binding.crypto_core_ed25519_is_valid_point(p)
}

exports.crypto_core_ed25519_from_uniform = function (p, r) {
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_UNIFORMBYTES,
    "r must be 'crypto_core_ed25519_UNIFORMBYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_from_uniform(p, r)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_base_noclamp = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_base_noclamp(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_noclamp = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "p must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_noclamp(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_core

exports.crypto_core_ed25519_add = function (r, p, q) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_BYTES,
    "r must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_core_ed25519_BYTES,
    "q must be 'crypto_core_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_add(r, p, q)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_sub = function (r, p, q) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_BYTES,
    "r must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_core_ed25519_BYTES,
    "q must be 'crypto_core_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_sub(r, p, q)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_scalar_random = function (r) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "r must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_random(r)
}

exports.crypto_core_ed25519_scalar_reduce = function (r, s) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "r must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_NONREDUCEDSCALARBYTES,
    "s must be 'crypto_core_ed25519_NONREDUCEDSCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_reduce(r, s)
}

exports.crypto_core_ed25519_scalar_invert = function (recip, s) {
  assert(ArrayBuffer.isView(recip), 'recip must be a typed array')
  assert(
    recip.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "recip must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_invert(recip, s)
}

exports.crypto_core_ed25519_scalar_negate = function (neg, s) {
  assert(ArrayBuffer.isView(neg), 'neg must be a typed array')
  assert(
    neg.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "neg must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_negate(neg, s)
}

exports.crypto_core_ed25519_scalar_complement = function (comp, s) {
  assert(ArrayBuffer.isView(comp), 'comp must be a typed array')
  assert(
    comp.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "comp must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_complement(comp, s)
}

exports.crypto_core_ed25519_scalar_add = function (z, x, y) {
  assert(ArrayBuffer.isView(z), 'z must be a typed array')
  assert(
    z.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "z must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(x), 'x must be a typed array')
  assert(
    x.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "x must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(y), 'y must be a typed array')
  assert(
    y.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "y must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_add(z, x, y)
}

exports.crypto_core_ed25519_scalar_sub = function (z, x, y) {
  assert(ArrayBuffer.isView(z), 'z must be a typed array')
  assert(
    z.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "z must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(x), 'x must be a typed array')
  assert(
    x.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "x must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(y), 'y must be a typed array')
  assert(
    y.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "y must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_sub(z, x, y)
}

// crypto_shorthash

exports.crypto_shorthash = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_shorthash_BYTES,
    "out must be 'crypto_shorthash_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_shorthash_KEYBYTES,
    "k must be 'crypto_shorthash_KEYBYTES' bytes"
  )

  const res = binding.crypto_shorthash(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_kdf

exports.crypto_kdf_keygen = function (key) {
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(key.byteLength === binding.crypto_kdf_KEYBYTES, "key must be 'crypto_kdf_KEYBYTES' bytes")

  binding.crypto_kdf_keygen(key)
}

exports.crypto_kdf_derive_from_key = function (subkey, subkeyId, ctx, key) {
  assert(ArrayBuffer.isView(subkey), 'subkey must be a typed array')
  assert(
    subkey.byteLength >= binding.crypto_kdf_BYTES_MIN,
    "subkey must be at least 'crypto_kdf_BYTES_MIN' bytes"
  )
  assert(
    subkey.byteLength <= binding.crypto_kdf_BYTES_MAX,
    "subkey must be at most 'crypto_kdf_BYTES_MAX' bytes"
  )
  assert(ArrayBuffer.isView(ctx), 'ctx must be a typed array')
  assert(
    ctx.byteLength === binding.crypto_kdf_CONTEXTBYTES,
    "ctx must be 'crypto_kdf_CONTEXTBYTES' bytes"
  )
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(key.byteLength === binding.crypto_kdf_KEYBYTES, "key must be 'crypto_kdf_KEYBYTES' bytes")

  const res = binding.crypto_kdf_derive_from_key(subkey, subkeyId, ctx, key)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_hash

exports.crypto_hash = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(out.byteLength === binding.crypto_hash_BYTES, "out must be 'crypto_hash_BYTES' bytes")

  const res = binding.crypto_hash(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256 = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha256_BYTES,
    "out must be 'crypto_hash_sha256_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha256(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_init = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_init(state)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha256_BYTES,
    "out must be 'crypto_hash_sha256_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512 = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha512_BYTES,
    "out must be 'crypto_hash_sha512_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha512(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_init = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_init(state)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha512_BYTES,
    "out must be 'crypto_hash_sha512_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_aead

exports.crypto_aead_xchacha20poly1305_ietf_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  binding.crypto_aead_xchacha20poly1305_ietf_keygen(k)
}

exports.crypto_aead_xchacha20poly1305_ietf_encrypt = function (c, m, ad, nsec, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "c must be 'm.byteLength + crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(c.byteLength <= 0xffffffff, 'c.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_encrypt(c, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_decrypt = function (m, nsec, c, ad, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "m must be 'c.byteLength - crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(m.byteLength <= 0xffffffff, 'm.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_decrypt(m, c, ad, npub, k)

  if (res < 0) throw new Error('could not verify data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_encrypt_detached = function (
  c,
  mac,
  m,
  ad,
  nsec,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_encrypt_detached(c, mac, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_decrypt_detached = function (
  m,
  nsec,
  c,
  mac,
  ad,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_decrypt_detached(m, c, mac, ad, npub, k)

  if (res !== 0) throw new Error('could not verify data')
}

exports.crypto_aead_chacha20poly1305_ietf_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  binding.crypto_aead_chacha20poly1305_ietf_keygen(k)
}

exports.crypto_aead_chacha20poly1305_ietf_encrypt = function (c, m, ad, nsec, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "c must be 'm.byteLength + crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(c.byteLength <= 0xffffffff, 'c.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_encrypt(c, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_decrypt = function (m, nsec, c, ad, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "m must be 'c.byteLength - crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(m.byteLength <= 0xffffffff, 'm.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_decrypt(m, c, ad, npub, k)

  if (res < 0) throw new Error('could not verify data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_encrypt_detached = function (
  c,
  mac,
  m,
  ad,
  nsec,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_encrypt_detached(c, mac, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_decrypt_detached = function (
  m,
  nsec,
  c,
  mac,
  ad,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_decrypt_detached(m, c, mac, ad, npub, k)

  if (res !== 0) throw new Error('could not verify data')
}

// crypto_stream

exports.crypto_stream_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  binding.crypto_stream_xor_wrap_init(state, n, k)
}

exports.crypto_stream_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_xor_wrap_update(state, c, m)
}

exports.crypto_stream_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_xor_wrap_final(state)
}

exports.crypto_stream_chacha20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  binding.crypto_stream_chacha20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_chacha20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_chacha20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_chacha20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_chacha20_xor_wrap_final(state)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  binding.crypto_stream_chacha20_ietf_xor_wrap_init(state, n, k)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_chacha20_ietf_xor_wrap_update(state, c, m)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_chacha20_ietf_xor_wrap_final(state)
}

exports.crypto_stream_xchacha20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  binding.crypto_stream_xchacha20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_xchacha20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_xchacha20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_xchacha20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_xchacha20_xor_wrap_final(state)
}

exports.crypto_stream_salsa20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  binding.crypto_stream_salsa20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_salsa20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_salsa20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_salsa20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_salsa20_xor_wrap_final(state)
}

// experimental

exports.extension_tweak_ed25519_base = function (n, p, ns) {
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.extension_tweak_ed25519_BYTES,
    "p must be 'extension_tweak_ed25519_BYTES' bytes"
  )

  binding.extension_tweak_ed25519_base(n, p, ns)
}

exports.extension_tweak_ed25519_sign_detached = function (sig, m, scalar, pk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(sig.byteLength === binding.crypto_sign_BYTES, "sig must be 'crypto_sign_BYTES' bytes")
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  if (pk) {
    assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
    assert(
      pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
      "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
    )
  }

  const res = binding.extension_tweak_ed25519_sign_detached(sig, m, scalar, pk)

  if (res !== 0) throw new Error('failed to compute signature')
}

exports.extension_tweak_ed25519_sk_to_scalar = function (n, sk) {
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  binding.extension_tweak_ed25519_sk_to_scalar(n, sk)
}

exports.extension_tweak_ed25519_scalar = function (scalarOut, scalar, ns) {
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_scalar(scalarOut, scalar, ns)
}

exports.extension_tweak_ed25519_pk = function (tpk, pk, ns) {
  assert(ArrayBuffer.isView(tpk), 'tpk must be a typed array')
  assert(
    tpk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "tpk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_pk(tpk, pk, ns)

  if (res !== 0) throw new Error('failed to tweak public key')
}

exports.extension_tweak_ed25519_keypair = function (pk, scalarOut, scalarIn, ns) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.extension_tweak_ed25519_BYTES,
    "pk must be 'extension_tweak_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarIn), 'scalarIn must be a typed array')
  assert(
    scalarIn.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarIn must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_keypair(pk, scalarOut, scalarIn, ns)
}

exports.extension_tweak_ed25519_scalar_add = function (scalarOut, scalar, n) {
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_scalar_add(scalarOut, scalar, n)
}

exports.extension_tweak_ed25519_pk_add = function (tpk, pk, p) {
  assert(ArrayBuffer.isView(tpk), 'tpk must be a typed array')
  assert(
    tpk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "tpk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "p must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_pk_add(tpk, pk, p)

  if (res !== 0) throw new Error('failed to add tweak to public key')
}

exports.extension_tweak_ed25519_keypair_add = function (pk, scalarOut, scalarIn, tweak) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.extension_tweak_ed25519_BYTES,
    "pk must be 'extension_tweak_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarIn), 'scalarIn must be a typed array')
  assert(
    scalarIn.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarIn must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(tweak), 'tweak must be a typed array')
  assert(
    tweak.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "tweak must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_keypair_add(pk, scalarOut, scalarIn, tweak)

  if (res !== 0) throw new Error('failed to add tweak to keypair')
}

exports.extension_pbkdf2_sha512_async = function (out, passwd, salt, iter, outlen, callback) {
  assert(
    iter >= binding.extension_pbkdf2_sha512_ITERATIONS_MIN,
    "iter must be at least 'extension_pbkdf2_sha512_ITERATIONS_MIN'"
  )
  assert(
    outlen <= binding.extension_pbkdf2_sha512_BYTES_MAX,
    "outlen must be at most 'extension_pbkdf2_sha512_BYTES_MAX'"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(out.byteLength >= outlen, "out must be at least 'outlen' bytes")
  assert(out.byteLength > 0, 'out must not be empty')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(salt.byteLength > 0, 'salt must not be empty')

  const [done, promise] = checkStatus(callback)

  binding.extension_pbkdf2_sha512_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    iter,
    outlen,

    done
  )

  return promise
}

exports.extension_pbkdf2_sha512 = function (out, passwd, salt, iter, outlen) {
  assert(
    iter >= binding.extension_pbkdf2_sha512_ITERATIONS_MIN,
    "iter must be at least 'extension_pbkdf2_sha512_ITERATIONS_MIN'"
  )
  assert(
    outlen <= binding.extension_pbkdf2_sha512_BYTES_MAX,
    "outlen must be at most 'extension_pbkdf2_sha512_BYTES_MAX'"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(out.byteLength >= outlen, "out must be at least 'outlen' bytes")
  assert(out.byteLength > 0, 'out must not be empty')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(salt.byteLength > 0, 'salt must not be empty')

  const res = binding.extension_pbkdf2_sha512(out, passwd, salt, iter, outlen)

  if (res !== 0) throw new Error('failed to add tweak to public key')
}

function checkStatus(callback, booleanResult = false) {
  let done, promise

  if (typeof callback === 'function') {
    done = function (status) {
      if (booleanResult) callback(null, status === 0)
      else if (status === 0) callback(null)
      else callback(new Error('status: ' + status))
    }
  } else {
    promise = new Promise(function (resolve, reject) {
      done = function (status) {
        if (booleanResult) resolve(status === 0)
        else if (status === 0) resolve()
        else reject(new Error('status: ' + status))
      }
    })
  }

  return [done, promise]
}
{
  "name": "sodium-native",
  "version": "5.1.0",
  "description": "Low level bindings for libsodium",
  "main": "index.js",
  "files": [
    "index.js",
    "binding.cc",
    "binding.js",
    "extensions",
    "prebuilds",
    "CMakeLists.txt"
  ],
  "imports": {
    "assert": {
      "bare": "bare-assert",
      "node": "assert"
    }
  },
  "addon": true,
  "dependencies": {
    "bare-assert": "^1.2.0",
    "require-addon": "^1.1.0",
    "which-runtime": "^1.2.1"
  },
  "devDependencies": {
    "bare-compat-napi": "^1.3.5",
    "brittle": "^3.16.2",
    "cmake-bare": "^1.6.1",
    "cmake-fetch": "^1.4.3",
    "cmake-napi": "^1.2.1",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "test": "prettier . --check && npm run test:node && npm run test:bare",
    "test:node": "node test/all.js",
    "test:bare": "bare test/all.js"
  },
  "standard": {
    "ignore": [
      "/test/fixtures/*.js"
    ]
  },
  "engines": {
    "bare": ">=1.16.0"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sodium-native.git"
  },
  "contributors": [
    "Emil Bay <github@tixz.dk> (http://bayes.dk)",
    "Mathias Buus <mathiasbuus@gmail.com> (https://mafinto.sh)",
    "Christophe Diederichs <chm-diederichs@hyperdivision.dk>"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/sodium-native/issues"
  },
  "homepage": "https://github.com/holepunchto/sodium-native"
}
const sodium = require('sodium-universal')
const b4a = require('b4a')

const ABYTES = sodium.crypto_secretstream_xchacha20poly1305_ABYTES
const TAG_MESSAGE = sodium.crypto_secretstream_xchacha20poly1305_TAG_MESSAGE
const TAG_FINAL = sodium.crypto_secretstream_xchacha20poly1305_TAG_FINAL
const STATEBYTES = sodium.crypto_secretstream_xchacha20poly1305_STATEBYTES
const HEADERBYTES = sodium.crypto_secretstream_xchacha20poly1305_HEADERBYTES
const KEYBYTES = sodium.crypto_secretstream_xchacha20poly1305_KEYBYTES
const TAG_FINAL_BYTE = b4a.isBuffer(TAG_FINAL) ? TAG_FINAL[0] : TAG_FINAL

const EMPTY = b4a.alloc(0)
const TAG = b4a.alloc(1)

class Push {
  constructor (key, state = b4a.allocUnsafeSlow(STATEBYTES), header = b4a.allocUnsafeSlow(HEADERBYTES)) {
    if (!TAG_FINAL) throw new Error('JavaScript sodium version needs to support crypto_secretstream_xchacha20poly')

    this.key = key
    this.state = state
    this.header = header

    sodium.crypto_secretstream_xchacha20poly1305_init_push(this.state, this.header, this.key)
  }

  next (message, cipher = b4a.allocUnsafe(message.byteLength + ABYTES)) {
    sodium.crypto_secretstream_xchacha20poly1305_push(this.state, cipher, message, null, TAG_MESSAGE)
    return cipher
  }

  final (message = EMPTY, cipher = b4a.allocUnsafe(ABYTES)) {
    sodium.crypto_secretstream_xchacha20poly1305_push(this.state, cipher, message, null, TAG_FINAL)
    return cipher
  }
}

class Pull {
  constructor (key, state = b4a.allocUnsafeSlow(STATEBYTES)) {
    if (!TAG_FINAL) throw new Error('JavaScript sodium version needs to support crypto_secretstream_xchacha20poly')

    this.key = key
    this.state = state
    this.final = false
  }

  init (header) {
    sodium.crypto_secretstream_xchacha20poly1305_init_pull(this.state, header, this.key)
  }

  next (cipher, message = b4a.allocUnsafe(cipher.byteLength - ABYTES)) {
    sodium.crypto_secretstream_xchacha20poly1305_pull(this.state, message, TAG, cipher, null)
    this.final = TAG[0] === TAG_FINAL_BYTE
    return message
  }
}

function keygen (buf = b4a.alloc(KEYBYTES)) {
  sodium.crypto_secretstream_xchacha20poly1305_keygen(buf)
  return buf
}

module.exports = {
  keygen,
  KEYBYTES,
  ABYTES,
  STATEBYTES,
  HEADERBYTES,
  Push,
  Pull
}
{
  "name": "sodium-secretstream",
  "version": "1.2.0",
  "description": "Wraps libsodiums secretstream in a higher level abstraction",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.1.1",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "standard": "^17.0.0"
  },
  "scripts": {
    "test": "standard"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/sodium-secretstream.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/sodium-secretstream/issues"
  },
  "homepage": "https://github.com/mafintosh/sodium-secretstream"
}
module.exports = require('sodium-native')
{
  "name": "sodium-universal",
  "version": "5.0.1",
  "description": "Universal wrapper for sodium-javascript and sodium-native working in Node.js and the Browser",
  "main": "index.js",
  "dependencies": {
    "sodium-native": "^5.0.1"
  },
  "peerDependencies": {
    "sodium-javascript": "~0.8.0"
  },
  "peerDependenciesMeta": {
    "sodium-javascript": {
      "optional": true
    }
  },
  "scripts": {
    "prepublish": "./build-scripts/generate.js"
  },
  "browser": {
    "sodium-native": "sodium-javascript"
  },
  "browserify": {
    "transform": [
      "./build-scripts/transform.js"
    ]
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sodium-universal.git"
  },
  "keywords": [
    "libsodium",
    "sodium",
    "sodium-native",
    "sodium-javascript",
    "browserify"
  ],
  "contributors": [
    "Emil Bay <github@tixz.dk> (http://bayes.dk)",
    "Mathias Buus <mathiasbuus@gmail.com> (https://mafinto.sh)",
    "Christophe Diederichs <chm-diederichs@hyperdivision.dk>"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/sodium-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/sodium-universal#readme"
}
const { EventEmitter } = require('events-universal')
const FIFO = require('fast-fifo')
const TextDecoder = require('text-decoder')

const StreamError = require('./lib/errors.js')

// if we do a future major, expect queue microtask to be there always, for now a bit defensive
const qmt =
  typeof queueMicrotask === 'undefined' ? (fn) => global.process.nextTick(fn) : queueMicrotask

// 29 bits used total (4 from shared, 14 from read, and 11 from write)
const MAX = (1 << 29) - 1

// Shared state
const OPENING = 0b0001
const PREDESTROYING = 0b0010
const DESTROYING = 0b0100
const DESTROYED = 0b1000

const NOT_OPENING = MAX ^ OPENING
const NOT_PREDESTROYING = MAX ^ PREDESTROYING

// Read state (4 bit offset from shared state)
const READ_ACTIVE = 0b00000000000001 << 4
const READ_UPDATING = 0b00000000000010 << 4
const READ_PRIMARY = 0b00000000000100 << 4
const READ_QUEUED = 0b00000000001000 << 4
const READ_RESUMED = 0b00000000010000 << 4
const READ_PIPE_DRAINED = 0b00000000100000 << 4
const READ_ENDING = 0b00000001000000 << 4
const READ_EMIT_DATA = 0b00000010000000 << 4
const READ_EMIT_READABLE = 0b00000100000000 << 4
const READ_EMITTED_READABLE = 0b00001000000000 << 4
const READ_DONE = 0b00010000000000 << 4
const READ_NEXT_TICK = 0b00100000000000 << 4
const READ_NEEDS_PUSH = 0b01000000000000 << 4
const READ_READ_AHEAD = 0b10000000000000 << 4

// Combined read state
const READ_FLOWING = READ_RESUMED | READ_PIPE_DRAINED
const READ_ACTIVE_AND_NEEDS_PUSH = READ_ACTIVE | READ_NEEDS_PUSH
const READ_PRIMARY_AND_ACTIVE = READ_PRIMARY | READ_ACTIVE
const READ_EMIT_READABLE_AND_QUEUED = READ_EMIT_READABLE | READ_QUEUED
const READ_RESUMED_READ_AHEAD = READ_RESUMED | READ_READ_AHEAD

const READ_NOT_ACTIVE = MAX ^ READ_ACTIVE
const READ_NON_PRIMARY = MAX ^ READ_PRIMARY
const READ_NON_PRIMARY_AND_PUSHED = MAX ^ (READ_PRIMARY | READ_NEEDS_PUSH)
const READ_PUSHED = MAX ^ READ_NEEDS_PUSH
const READ_PAUSED = MAX ^ READ_RESUMED
const READ_NOT_QUEUED = MAX ^ (READ_QUEUED | READ_EMITTED_READABLE)
const READ_NOT_ENDING = MAX ^ READ_ENDING
const READ_PIPE_NOT_DRAINED = MAX ^ READ_FLOWING
const READ_NOT_NEXT_TICK = MAX ^ READ_NEXT_TICK
const READ_NOT_UPDATING = MAX ^ READ_UPDATING
const READ_NO_READ_AHEAD = MAX ^ READ_READ_AHEAD
const READ_PAUSED_NO_READ_AHEAD = MAX ^ READ_RESUMED_READ_AHEAD

// Write state (18 bit offset, 4 bit offset from shared state and 14 from read state)
const WRITE_ACTIVE = 0b00000000001 << 18
const WRITE_UPDATING = 0b00000000010 << 18
const WRITE_PRIMARY = 0b00000000100 << 18
const WRITE_QUEUED = 0b00000001000 << 18
const WRITE_UNDRAINED = 0b00000010000 << 18
const WRITE_DONE = 0b00000100000 << 18
const WRITE_EMIT_DRAIN = 0b00001000000 << 18
const WRITE_NEXT_TICK = 0b00010000000 << 18
const WRITE_WRITING = 0b00100000000 << 18
const WRITE_FINISHING = 0b01000000000 << 18
const WRITE_CORKED = 0b10000000000 << 18

const WRITE_NOT_ACTIVE = MAX ^ (WRITE_ACTIVE | WRITE_WRITING)
const WRITE_NON_PRIMARY = MAX ^ WRITE_PRIMARY
const WRITE_NOT_FINISHING = MAX ^ (WRITE_ACTIVE | WRITE_FINISHING)
const WRITE_DRAINED = MAX ^ WRITE_UNDRAINED
const WRITE_NOT_QUEUED = MAX ^ WRITE_QUEUED
const WRITE_NOT_NEXT_TICK = MAX ^ WRITE_NEXT_TICK
const WRITE_NOT_UPDATING = MAX ^ WRITE_UPDATING
const WRITE_NOT_CORKED = MAX ^ WRITE_CORKED

// Combined shared state
const ACTIVE = READ_ACTIVE | WRITE_ACTIVE
const NOT_ACTIVE = MAX ^ ACTIVE
const DONE = READ_DONE | WRITE_DONE
const DESTROY_STATUS = DESTROYING | DESTROYED | PREDESTROYING
const OPEN_STATUS = DESTROY_STATUS | OPENING
const AUTO_DESTROY = DESTROY_STATUS | DONE
const NON_PRIMARY = WRITE_NON_PRIMARY & READ_NON_PRIMARY
const ACTIVE_OR_TICKING = WRITE_NEXT_TICK | READ_NEXT_TICK
const TICKING = ACTIVE_OR_TICKING & NOT_ACTIVE
const IS_OPENING = OPEN_STATUS | TICKING

// Combined shared state and read state
const READ_PRIMARY_STATUS = OPEN_STATUS | READ_ENDING | READ_DONE
const READ_STATUS = OPEN_STATUS | READ_DONE | READ_QUEUED
const READ_ENDING_STATUS = OPEN_STATUS | READ_ENDING | READ_QUEUED
const READ_READABLE_STATUS = OPEN_STATUS | READ_EMIT_READABLE | READ_QUEUED | READ_EMITTED_READABLE
const SHOULD_NOT_READ =
  OPEN_STATUS | READ_ACTIVE | READ_ENDING | READ_DONE | READ_NEEDS_PUSH | READ_READ_AHEAD
const READ_BACKPRESSURE_STATUS = DESTROY_STATUS | READ_ENDING | READ_DONE
const READ_UPDATE_SYNC_STATUS = READ_UPDATING | OPEN_STATUS | READ_NEXT_TICK | READ_PRIMARY
const READ_NEXT_TICK_OR_OPENING = READ_NEXT_TICK | OPENING

// Combined write state
const WRITE_PRIMARY_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_DONE
const WRITE_QUEUED_AND_UNDRAINED = WRITE_QUEUED | WRITE_UNDRAINED
const WRITE_QUEUED_AND_ACTIVE = WRITE_QUEUED | WRITE_ACTIVE
const WRITE_DRAIN_STATUS = WRITE_QUEUED | WRITE_UNDRAINED | OPEN_STATUS | WRITE_ACTIVE
const WRITE_STATUS = OPEN_STATUS | WRITE_ACTIVE | WRITE_QUEUED | WRITE_CORKED
const WRITE_PRIMARY_AND_ACTIVE = WRITE_PRIMARY | WRITE_ACTIVE
const WRITE_ACTIVE_AND_WRITING = WRITE_ACTIVE | WRITE_WRITING
const WRITE_FINISHING_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_QUEUED_AND_ACTIVE | WRITE_DONE
const WRITE_BACKPRESSURE_STATUS = WRITE_UNDRAINED | DESTROY_STATUS | WRITE_FINISHING | WRITE_DONE
const WRITE_UPDATE_SYNC_STATUS = WRITE_UPDATING | OPEN_STATUS | WRITE_NEXT_TICK | WRITE_PRIMARY
const WRITE_DROP_DATA = WRITE_FINISHING | WRITE_DONE | DESTROY_STATUS

const asyncIterator = Symbol.asyncIterator || Symbol('asyncIterator')

class WritableState {
  constructor(
    stream,
    { highWaterMark = 16384, map = null, mapWritable, byteLength, byteLengthWritable } = {}
  ) {
    this.stream = stream
    this.queue = new FIFO()
    this.highWaterMark = highWaterMark
    this.buffered = 0
    this.error = null
    this.pipeline = null
    this.drains = null // if we add more seldomly used helpers we might them into a subobject so its a single ptr
    this.byteLength = byteLengthWritable || byteLength || defaultByteLength
    this.map = mapWritable || map
    this.afterWrite = afterWrite.bind(this)
    this.afterUpdateNextTick = updateWriteNT.bind(this)
  }

  get ending() {
    return (this.stream._duplexState & WRITE_FINISHING) !== 0
  }

  get ended() {
    return (this.stream._duplexState & WRITE_DONE) !== 0
  }

  push(data) {
    if ((this.stream._duplexState & WRITE_DROP_DATA) !== 0) return false
    if (this.map !== null) data = this.map(data)

    this.buffered += this.byteLength(data)
    this.queue.push(data)

    if (this.buffered < this.highWaterMark) {
      this.stream._duplexState |= WRITE_QUEUED
      return true
    }

    this.stream._duplexState |= WRITE_QUEUED_AND_UNDRAINED
    return false
  }

  shift() {
    const data = this.queue.shift()

    this.buffered -= this.byteLength(data)
    if (this.buffered === 0) this.stream._duplexState &= WRITE_NOT_QUEUED

    return data
  }

  end(data) {
    if (typeof data === 'function') {
      this.stream.once('finish', data)
    } else if (data !== undefined && data !== null) {
      this.push(data)
    }

    this.stream._duplexState = (this.stream._duplexState | WRITE_FINISHING) & WRITE_NON_PRIMARY
  }

  autoBatch(data, cb) {
    const buffer = []
    const stream = this.stream

    buffer.push(data)
    while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED_AND_ACTIVE) {
      buffer.push(stream._writableState.shift())
    }

    if ((stream._duplexState & OPEN_STATUS) !== 0) return cb(null)
    stream._writev(buffer, cb)
  }

  update() {
    const stream = this.stream

    stream._duplexState |= WRITE_UPDATING

    do {
      while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED) {
        const data = this.shift()
        stream._duplexState |= WRITE_ACTIVE_AND_WRITING
        stream._write(data, this.afterWrite)
      }

      if ((stream._duplexState & WRITE_PRIMARY_AND_ACTIVE) === 0) this.updateNonPrimary()
    } while (this.continueUpdate() === true)

    stream._duplexState &= WRITE_NOT_UPDATING
  }

  updateNonPrimary() {
    const stream = this.stream

    if ((stream._duplexState & WRITE_FINISHING_STATUS) === WRITE_FINISHING) {
      stream._duplexState = stream._duplexState | WRITE_ACTIVE
      stream._final(afterFinal.bind(this))
      return
    }

    if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
      if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
        stream._duplexState |= ACTIVE
        stream._destroy(afterDestroy.bind(this))
      }
      return
    }

    if ((stream._duplexState & IS_OPENING) === OPENING) {
      stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING
      stream._open(afterOpen.bind(this))
    }
  }

  continueUpdate() {
    if ((this.stream._duplexState & WRITE_NEXT_TICK) === 0) return false
    this.stream._duplexState &= WRITE_NOT_NEXT_TICK
    return true
  }

  updateCallback() {
    if ((this.stream._duplexState & WRITE_UPDATE_SYNC_STATUS) === WRITE_PRIMARY) {
      this.update()
    } else {
      this.updateNextTick()
    }
  }

  updateNextTick() {
    if ((this.stream._duplexState & WRITE_NEXT_TICK) !== 0) return
    this.stream._duplexState |= WRITE_NEXT_TICK
    if ((this.stream._duplexState & WRITE_UPDATING) === 0) qmt(this.afterUpdateNextTick)
  }
}

class ReadableState {
  constructor(
    stream,
    { highWaterMark = 16384, map = null, mapReadable, byteLength, byteLengthReadable } = {}
  ) {
    this.stream = stream
    this.queue = new FIFO()
    this.highWaterMark = highWaterMark === 0 ? 1 : highWaterMark
    this.buffered = 0
    this.readAhead = highWaterMark > 0
    this.error = null
    this.pipeline = null
    this.byteLength = byteLengthReadable || byteLength || defaultByteLength
    this.map = mapReadable || map
    this.pipeTo = null
    this.afterRead = afterRead.bind(this)
    this.afterUpdateNextTick = updateReadNT.bind(this)
  }

  get ending() {
    return (this.stream._duplexState & READ_ENDING) !== 0
  }

  get ended() {
    return (this.stream._duplexState & READ_DONE) !== 0
  }

  pipe(pipeTo, cb) {
    if (this.pipeTo !== null) throw StreamError.BAD_ARGUMENT('Can only pipe to one destination')
    if (typeof cb !== 'function') cb = null

    this.stream._duplexState |= READ_PIPE_DRAINED
    this.pipeTo = pipeTo
    this.pipeline = new Pipeline(this.stream, pipeTo, cb)

    if (cb) this.stream.on('error', noop) // We already error handle this so supress crashes

    if (isStreamx(pipeTo)) {
      pipeTo._writableState.pipeline = this.pipeline
      if (cb) pipeTo.on('error', noop) // We already error handle this so supress crashes
      pipeTo.on('finish', this.pipeline.finished.bind(this.pipeline)) // TODO: just call finished from pipeTo itself
    } else {
      const onerror = this.pipeline.done.bind(this.pipeline, pipeTo)
      const onclose = this.pipeline.done.bind(this.pipeline, pipeTo, null) // onclose has a weird bool arg
      pipeTo.on('error', onerror)
      pipeTo.on('close', onclose)
      pipeTo.on('finish', this.pipeline.finished.bind(this.pipeline))
    }

    pipeTo.on('drain', afterDrain.bind(this))
    this.stream.emit('piping', pipeTo)
    pipeTo.emit('pipe', this.stream)
  }

  push(data) {
    const stream = this.stream

    if (data === null) {
      this.highWaterMark = 0
      stream._duplexState = (stream._duplexState | READ_ENDING) & READ_NON_PRIMARY_AND_PUSHED
      return false
    }

    if (this.map !== null) {
      data = this.map(data)
      if (data === null) {
        stream._duplexState &= READ_PUSHED
        return this.buffered < this.highWaterMark
      }
    }

    this.buffered += this.byteLength(data)
    this.queue.push(data)

    stream._duplexState = (stream._duplexState | READ_QUEUED) & READ_PUSHED

    return this.buffered < this.highWaterMark
  }

  shift() {
    const data = this.queue.shift()

    this.buffered -= this.byteLength(data)
    if (this.buffered === 0) {
      this.stream._duplexState &= READ_NOT_QUEUED
    }

    return data
  }

  unshift(data) {
    const pending = [this.map !== null ? this.map(data) : data]
    while (this.buffered > 0) pending.push(this.shift())

    for (let i = 0; i < pending.length - 1; i++) {
      const data = pending[i]
      this.buffered += this.byteLength(data)
      this.queue.push(data)
    }

    this.push(pending[pending.length - 1])
  }

  read() {
    const stream = this.stream

    if ((stream._duplexState & READ_STATUS) === READ_QUEUED) {
      const data = this.shift()

      if (this.pipeTo !== null && this.pipeTo.write(data) === false) {
        stream._duplexState &= READ_PIPE_NOT_DRAINED
      }

      if ((stream._duplexState & READ_EMIT_DATA) !== 0) {
        stream.emit('data', data)
      }

      return data
    }

    if (this.readAhead === false) {
      stream._duplexState |= READ_READ_AHEAD
      this.updateNextTick()
    }

    return null
  }

  drain() {
    const stream = this.stream

    while (
      (stream._duplexState & READ_STATUS) === READ_QUEUED &&
      (stream._duplexState & READ_FLOWING) !== 0
    ) {
      const data = this.shift()

      if (this.pipeTo !== null && this.pipeTo.write(data) === false) {
        stream._duplexState &= READ_PIPE_NOT_DRAINED
      }

      if ((stream._duplexState & READ_EMIT_DATA) !== 0) {
        stream.emit('data', data)
      }
    }
  }

  update() {
    const stream = this.stream

    stream._duplexState |= READ_UPDATING

    do {
      this.drain()

      while (
        this.buffered < this.highWaterMark &&
        (stream._duplexState & SHOULD_NOT_READ) === READ_READ_AHEAD
      ) {
        stream._duplexState |= READ_ACTIVE_AND_NEEDS_PUSH
        stream._read(this.afterRead)
        this.drain()
      }

      if ((stream._duplexState & READ_READABLE_STATUS) === READ_EMIT_READABLE_AND_QUEUED) {
        stream._duplexState |= READ_EMITTED_READABLE
        stream.emit('readable')
      }

      if ((stream._duplexState & READ_PRIMARY_AND_ACTIVE) === 0) {
        this.updateNonPrimary()
      }
    } while (this.continueUpdate() === true)

    stream._duplexState &= READ_NOT_UPDATING
  }

  updateNonPrimary() {
    const stream = this.stream

    if ((stream._duplexState & READ_ENDING_STATUS) === READ_ENDING) {
      stream._duplexState = (stream._duplexState | READ_DONE) & READ_NOT_ENDING
      stream.emit('end')

      if ((stream._duplexState & AUTO_DESTROY) === DONE) {
        stream._duplexState |= DESTROYING
      }

      if (this.pipeTo !== null) {
        this.pipeTo.end()
      }
    }

    if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
      if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
        stream._duplexState |= ACTIVE
        stream._destroy(afterDestroy.bind(this))
      }
      return
    }

    if ((stream._duplexState & IS_OPENING) === OPENING) {
      stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING
      stream._open(afterOpen.bind(this))
    }
  }

  continueUpdate() {
    if ((this.stream._duplexState & READ_NEXT_TICK) === 0) return false
    this.stream._duplexState &= READ_NOT_NEXT_TICK
    return true
  }

  updateCallback() {
    if ((this.stream._duplexState & READ_UPDATE_SYNC_STATUS) === READ_PRIMARY) {
      this.update()
    } else {
      this.updateNextTick()
    }
  }

  updateNextTickIfOpen() {
    if ((this.stream._duplexState & READ_NEXT_TICK_OR_OPENING) !== 0) return
    this.stream._duplexState |= READ_NEXT_TICK
    if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick)
  }

  updateNextTick() {
    if ((this.stream._duplexState & READ_NEXT_TICK) !== 0) return
    this.stream._duplexState |= READ_NEXT_TICK
    if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick)
  }
}

class TransformState {
  constructor(stream) {
    this.data = null
    this.afterTransform = afterTransform.bind(stream)
    this.afterFinal = null
  }
}

class Pipeline {
  constructor(src, dst, cb) {
    this.from = src
    this.to = dst
    this.afterPipe = cb
    this.error = null
    this.pipeToFinished = false
  }

  finished() {
    this.pipeToFinished = true
  }

  done(stream, err) {
    if (err) this.error = err

    if (stream === this.to) {
      this.to = null

      if (this.from !== null) {
        if ((this.from._duplexState & READ_DONE) === 0 || !this.pipeToFinished) {
          this.from.destroy(this.error || StreamError.PREMATURE_CLOSE('Writable stream closed'))
        }
        return
      }
    }

    if (stream === this.from) {
      this.from = null

      if (this.to !== null) {
        if ((stream._duplexState & READ_DONE) === 0) {
          this.to.destroy(this.error || StreamError.PREMATURE_CLOSE('Readable stream closed'))
        }
        return
      }
    }

    if (this.afterPipe !== null) this.afterPipe(this.error)
    this.to = this.from = this.afterPipe = null
  }
}

function afterDrain() {
  this.stream._duplexState |= READ_PIPE_DRAINED
  this.updateCallback()
}

function afterFinal(err) {
  const stream = this.stream
  if (err) stream.destroy(err)

  if ((stream._duplexState & DESTROY_STATUS) === 0) {
    stream._duplexState |= WRITE_DONE
    stream.emit('finish')
  }

  if ((stream._duplexState & AUTO_DESTROY) === DONE) {
    stream._duplexState |= DESTROYING
  }

  stream._duplexState &= WRITE_NOT_FINISHING

  // no need to wait the extra tick here, so we short circuit that
  if ((stream._duplexState & WRITE_UPDATING) === 0) {
    this.update()
  } else {
    this.updateNextTick()
  }
}

function afterDestroy(err) {
  const stream = this.stream

  if (!err && !StreamError.isStreamDestroyed(this.error)) err = this.error
  if (err) stream.emit('error', err)

  stream._duplexState |= DESTROYED
  stream.emit('close')

  const rs = stream._readableState
  const ws = stream._writableState

  if (rs !== null && rs.pipeline !== null) {
    rs.pipeline.done(stream, err)
  }

  if (ws !== null) {
    while (ws.drains !== null && ws.drains.length > 0) {
      ws.drains.shift().resolve(false)
    }

    if (ws.pipeline !== null) {
      ws.pipeline.done(stream, err)
    }
  }
}

function afterWrite(err) {
  const stream = this.stream

  if (err) stream.destroy(err)
  stream._duplexState &= WRITE_NOT_ACTIVE

  if (this.drains !== null) tickDrains(this.drains)

  if ((stream._duplexState & WRITE_DRAIN_STATUS) === WRITE_UNDRAINED) {
    stream._duplexState &= WRITE_DRAINED

    if ((stream._duplexState & WRITE_EMIT_DRAIN) === WRITE_EMIT_DRAIN) {
      stream.emit('drain')
    }
  }

  this.updateCallback()
}

function afterRead(err) {
  if (err) this.stream.destroy(err)
  this.stream._duplexState &= READ_NOT_ACTIVE

  if (this.readAhead === false && (this.stream._duplexState & READ_RESUMED) === 0) {
    this.stream._duplexState &= READ_NO_READ_AHEAD
  }

  this.updateCallback()
}

function updateReadNT() {
  if ((this.stream._duplexState & READ_UPDATING) === 0) {
    this.stream._duplexState &= READ_NOT_NEXT_TICK
    this.update()
  }
}

function updateWriteNT() {
  if ((this.stream._duplexState & WRITE_UPDATING) === 0) {
    this.stream._duplexState &= WRITE_NOT_NEXT_TICK
    this.update()
  }
}

function tickDrains(drains) {
  for (let i = 0; i < drains.length; i++) {
    // drains.writes are monotonic, so if one is 0 its always the first one
    if (--drains[i].writes === 0) {
      drains.shift().resolve(true)
      i--
    }
  }
}

function afterOpen(err) {
  const stream = this.stream

  if (err) stream.destroy(err)

  if ((stream._duplexState & DESTROYING) === 0) {
    if ((stream._duplexState & READ_PRIMARY_STATUS) === 0) {
      stream._duplexState |= READ_PRIMARY
    }

    if ((stream._duplexState & WRITE_PRIMARY_STATUS) === 0) {
      stream._duplexState |= WRITE_PRIMARY
    }

    stream.emit('open')
  }

  stream._duplexState &= NOT_ACTIVE

  if (stream._writableState !== null) {
    stream._writableState.updateCallback()
  }

  if (stream._readableState !== null) {
    stream._readableState.updateCallback()
  }
}

function afterTransform(err, data) {
  if (data !== undefined && data !== null) this.push(data)
  this._writableState.afterWrite(err)
}

function newListener(name) {
  if (this._readableState !== null) {
    if (name === 'data') {
      this._duplexState |= READ_EMIT_DATA | READ_RESUMED_READ_AHEAD
      this._readableState.updateNextTick()
    }
    if (name === 'readable') {
      this._duplexState |= READ_EMIT_READABLE
      this._readableState.updateNextTick()
    }
  }

  if (this._writableState !== null) {
    if (name === 'drain') {
      this._duplexState |= WRITE_EMIT_DRAIN
      this._writableState.updateNextTick()
    }
  }
}

class Stream extends EventEmitter {
  constructor(opts) {
    super()

    this._duplexState = 0
    this._readableState = null
    this._writableState = null

    if (opts) {
      if (opts.open) this._open = opts.open
      if (opts.destroy) this._destroy = opts.destroy
      if (opts.predestroy) this._predestroy = opts.predestroy
      if (opts.signal) opts.signal.addEventListener('abort', abort.bind(this))
    }

    this.on('newListener', newListener)
  }

  _open(cb) {
    cb(null)
  }

  _destroy(cb) {
    cb(null)
  }

  _predestroy() {
    // does nothing
  }

  get readable() {
    return this._readableState !== null ? true : undefined
  }

  get writable() {
    return this._writableState !== null ? true : undefined
  }

  get destroyed() {
    return (this._duplexState & DESTROYED) !== 0
  }

  get destroying() {
    return (this._duplexState & DESTROY_STATUS) !== 0
  }

  destroy(err) {
    if ((this._duplexState & DESTROY_STATUS) === 0) {
      if (!err) err = StreamError.STREAM_DESTROYED()
      this._duplexState = (this._duplexState | DESTROYING) & NON_PRIMARY

      if (this._readableState !== null) {
        this._readableState.highWaterMark = 0
        this._readableState.error = err
      }

      if (this._writableState !== null) {
        this._writableState.highWaterMark = 0
        this._writableState.error = err
      }

      this._duplexState |= PREDESTROYING
      this._predestroy()
      this._duplexState &= NOT_PREDESTROYING

      if (this._readableState !== null) {
        this._readableState.updateNextTick()
      }

      if (this._writableState !== null) {
        this._writableState.updateNextTick()
      }
    }
  }
}

class Readable extends Stream {
  constructor(opts) {
    super(opts)

    this._duplexState |= OPENING | WRITE_DONE | READ_READ_AHEAD
    this._readableState = new ReadableState(this, opts)

    if (opts) {
      if (this._readableState.readAhead === false) this._duplexState &= READ_NO_READ_AHEAD
      if (opts.read) this._read = opts.read
      if (opts.eagerOpen) this._readableState.updateNextTick()
      if (opts.encoding) this.setEncoding(opts.encoding)
    }
  }

  static deferred(fn, opts) {
    const out = new PassThrough(opts)

    fn()
      .then((src) => {
        if (src === null) return out.end()
        if (out.destroying) return
        pipeline(src, out, noop)
      })
      .catch((err) => out.destroy(err))

    return out
  }

  setEncoding(encoding) {
    const dec = new TextDecoder(encoding)
    const map = this._readableState.map || echo
    this._readableState.map = mapOrSkip
    return this

    function mapOrSkip(data) {
      const next = dec.push(data)
      return next === '' && (data.byteLength !== 0 || dec.remaining > 0) ? null : map(next)
    }
  }

  _read(cb) {
    cb(null)
  }

  pipe(dest, cb) {
    this._readableState.updateNextTick()
    this._readableState.pipe(dest, cb)
    return dest
  }

  read() {
    this._readableState.updateNextTick()
    return this._readableState.read()
  }

  push(data) {
    this._readableState.updateNextTickIfOpen()
    return this._readableState.push(data)
  }

  unshift(data) {
    this._readableState.updateNextTickIfOpen()
    return this._readableState.unshift(data)
  }

  resume() {
    this._duplexState |= READ_RESUMED_READ_AHEAD
    this._readableState.updateNextTick()
    return this
  }

  pause() {
    this._duplexState &=
      this._readableState.readAhead === false ? READ_PAUSED_NO_READ_AHEAD : READ_PAUSED
    return this
  }

  static _fromAsyncIterator(ite, opts) {
    let destroy

    const rs = new Readable({
      ...opts,
      read(cb) {
        ite.next().then(push).then(cb.bind(null, null)).catch(cb)
      },
      predestroy() {
        destroy = ite.return()
      },
      destroy(cb) {
        if (!destroy) return cb(null)
        destroy.then(cb.bind(null, null)).catch(cb)
      }
    })

    return rs

    function push(data) {
      if (data.done) rs.push(null)
      else rs.push(data.value)
    }
  }

  static from(data, opts) {
    if (isReadStreamx(data)) return data
    if (data[asyncIterator]) return this._fromAsyncIterator(data[asyncIterator](), opts)
    if (!Array.isArray(data)) data = data === undefined ? [] : [data]

    let i = 0
    return new Readable({
      ...opts,
      read(cb) {
        this.push(i === data.length ? null : data[i++])
        cb(null)
      }
    })
  }

  static isBackpressured(rs) {
    return (
      (rs._duplexState & READ_BACKPRESSURE_STATUS) !== 0 ||
      rs._readableState.buffered >= rs._readableState.highWaterMark
    )
  }

  static isPaused(rs) {
    return (rs._duplexState & READ_RESUMED) === 0
  }

  [asyncIterator]() {
    const stream = this

    let error = null
    let promiseResolve = null
    let promiseReject = null

    this.on('error', (err) => {
      error = err
    })
    this.on('readable', onreadable)
    this.on('close', onclose)

    return {
      [asyncIterator]() {
        return this
      },
      next() {
        return new Promise(function (resolve, reject) {
          promiseResolve = resolve
          promiseReject = reject
          const data = stream.read()
          if (data !== null) ondata(data)
          else if ((stream._duplexState & DESTROYED) !== 0) ondata(null)
        })
      },
      return() {
        return destroy(null)
      },
      throw(err) {
        return destroy(err)
      }
    }

    function onreadable() {
      if (promiseResolve !== null) ondata(stream.read())
    }

    function onclose() {
      if (promiseResolve !== null) ondata(null)
    }

    function ondata(data) {
      if (promiseReject === null) return
      if (error) {
        promiseReject(error)
      } else if (data === null && (stream._duplexState & READ_DONE) === 0) {
        promiseReject(StreamError.STREAM_DESTROYED())
      } else {
        promiseResolve({ value: data, done: data === null })
      }
      promiseReject = promiseResolve = null
    }

    function destroy(err) {
      stream.destroy(err)
      return new Promise((resolve, reject) => {
        if (stream._duplexState & DESTROYED) return resolve({ value: undefined, done: true })
        stream.once('close', function () {
          if (err) reject(err)
          else resolve({ value: undefined, done: true })
        })
      })
    }
  }
}

class Writable extends Stream {
  constructor(opts) {
    super(opts)

    this._duplexState |= OPENING | READ_DONE
    this._writableState = new WritableState(this, opts)

    if (opts) {
      if (opts.writev) this._writev = opts.writev
      if (opts.write) this._write = opts.write
      if (opts.final) this._final = opts.final
      if (opts.eagerOpen) this._writableState.updateNextTick()
    }
  }

  cork() {
    this._duplexState |= WRITE_CORKED
  }

  uncork() {
    this._duplexState &= WRITE_NOT_CORKED
    this._writableState.updateNextTick()
  }

  _writev(batch, cb) {
    cb(null)
  }

  _write(data, cb) {
    this._writableState.autoBatch(data, cb)
  }

  _final(cb) {
    cb(null)
  }

  static isBackpressured(ws) {
    return (ws._duplexState & WRITE_BACKPRESSURE_STATUS) !== 0
  }

  static drained(ws) {
    if (ws.destroyed) return Promise.resolve(false)

    const state = ws._writableState
    const pending = isWritev(ws) ? Math.min(1, state.queue.length) : state.queue.length
    const writes = pending + (ws._duplexState & WRITE_WRITING ? 1 : 0)
    if (writes === 0) return Promise.resolve(true)

    if (state.drains === null) state.drains = []
    return new Promise((resolve) => {
      state.drains.push({ writes, resolve })
    })
  }

  write(data) {
    this._writableState.updateNextTick()
    return this._writableState.push(data)
  }

  end(data) {
    this._writableState.updateNextTick()
    this._writableState.end(data)
    return this
  }
}

class Duplex extends Readable {
  // and Writable
  constructor(opts) {
    super(opts)

    this._duplexState = OPENING | (this._duplexState & READ_READ_AHEAD)
    this._writableState = new WritableState(this, opts)

    if (opts) {
      if (opts.writev) this._writev = opts.writev
      if (opts.write) this._write = opts.write
      if (opts.final) this._final = opts.final
    }
  }

  cork() {
    this._duplexState |= WRITE_CORKED
  }

  uncork() {
    this._duplexState &= WRITE_NOT_CORKED
    this._writableState.updateNextTick()
  }

  _writev(batch, cb) {
    cb(null)
  }

  _write(data, cb) {
    this._writableState.autoBatch(data, cb)
  }

  _final(cb) {
    cb(null)
  }

  write(data) {
    this._writableState.updateNextTick()
    return this._writableState.push(data)
  }

  end(data) {
    this._writableState.updateNextTick()
    this._writableState.end(data)
    return this
  }
}

class Transform extends Duplex {
  constructor(opts) {
    super(opts)
    this._transformState = new TransformState(this)

    if (opts) {
      if (opts.transform) this._transform = opts.transform
      if (opts.flush) this._flush = opts.flush
    }
  }

  _write(data, cb) {
    if (this._readableState.buffered >= this._readableState.highWaterMark) {
      this._transformState.data = data
    } else {
      this._transform(data, this._transformState.afterTransform)
    }
  }

  _read(cb) {
    if (this._transformState.data !== null) {
      const data = this._transformState.data
      this._transformState.data = null
      cb(null)
      this._transform(data, this._transformState.afterTransform)
    } else {
      cb(null)
    }
  }

  destroy(err) {
    super.destroy(err)
    if (this._transformState.data !== null) {
      this._transformState.data = null
      this._transformState.afterTransform()
    }
  }

  _transform(data, cb) {
    cb(null, data)
  }

  _flush(cb) {
    cb(null)
  }

  _final(cb) {
    this._transformState.afterFinal = cb
    this._flush(transformAfterFlush.bind(this))
  }
}

class PassThrough extends Transform {}

function transformAfterFlush(err, data) {
  const cb = this._transformState.afterFinal
  if (err) return cb(err)

  if (data !== null && data !== undefined) this.push(data)
  this.push(null)
  cb(null)
}

function pipelinePromise(...streams) {
  return new Promise((resolve, reject) => {
    return pipeline(...streams, (err) => {
      if (err) return reject(err)
      resolve()
    })
  })
}

function pipeline(stream, ...streams) {
  const all = Array.isArray(stream) ? [...stream, ...streams] : [stream, ...streams]
  const done = all.length && typeof all[all.length - 1] === 'function' ? all.pop() : null

  if (all.length < 2) throw StreamError.BAD_ARGUMENT('Pipeline requires at least 2 streams')

  let src = all[0]
  let dest = null
  let error = null

  for (let i = 1; i < all.length; i++) {
    dest = all[i]

    if (isStreamx(src)) {
      src.pipe(dest, onerror)
    } else {
      errorHandle(src, true, i > 1, onerror)
      src.pipe(dest)
    }

    src = dest
  }

  if (done) {
    let fin = false

    const autoDestroy =
      isStreamx(dest) || !!(dest._writableState && dest._writableState.autoDestroy)

    dest.on('error', (err) => {
      if (error === null) error = err
    })

    dest.on('finish', () => {
      fin = true
      if (!autoDestroy) done(error)
    })

    if (autoDestroy) {
      dest.on('close', () => done(error || (fin ? null : StreamError.PREMATURE_CLOSE())))
    }
  }

  return dest

  function errorHandle(s, rd, wr, onerror) {
    s.on('error', onerror)
    s.on('close', onclose)

    function onclose() {
      if (rd && s._readableState && !s._readableState.ended) {
        return onerror(StreamError.PREMATURE_CLOSE())
      }
      if (wr && s._writableState && !s._writableState.ended) {
        return onerror(StreamError.PREMATURE_CLOSE())
      }
    }
  }

  function onerror(err) {
    if (!err || error) return
    error = err

    for (const s of all) {
      s.destroy(err)
    }
  }
}

function echo(s) {
  return s
}

function isStream(stream) {
  return !!stream._readableState || !!stream._writableState
}

function isStreamx(stream) {
  return typeof stream._duplexState === 'number' && isStream(stream)
}

function isEnding(stream) {
  return !!stream._readableState && stream._readableState.ending
}

function isEnded(stream) {
  return !!stream._readableState && stream._readableState.ended
}

function isFinishing(stream) {
  return !!stream._writableState && stream._writableState.ending
}

function isFinished(stream) {
  return !!stream._writableState && stream._writableState.ended
}

function getStreamError(stream, opts = {}) {
  const err =
    (stream._readableState && stream._readableState.error) ||
    (stream._writableState && stream._writableState.error)

  // avoid implicit errors by default
  return !opts.all && StreamError.isStreamDestroyed(err) ? null : err
}

function isReadStreamx(stream) {
  return isStreamx(stream) && stream.readable
}

function isDisturbed(stream) {
  return (
    (stream._duplexState & OPENING) !== OPENING ||
    (stream._duplexState & DESTROYING) === DESTROYING ||
    (stream._duplexState & ACTIVE_OR_TICKING) !== 0
  )
}

function isTypedArray(data) {
  return typeof data === 'object' && data !== null && typeof data.byteLength === 'number'
}

function defaultByteLength(data) {
  return isTypedArray(data) ? data.byteLength : 1024
}

function noop() {}

function abort() {
  this.destroy(StreamError.ABORTED())
}

function isWritev(s) {
  return s._writev !== Writable.prototype._writev && s._writev !== Duplex.prototype._writev
}

module.exports = {
  pipeline,
  pipelinePromise,
  isStream,
  isStreamx,
  isEnding,
  isEnded,
  isFinishing,
  isFinished,
  isDisturbed,
  getStreamError,
  Stream,
  Writable,
  Readable,
  Duplex,
  Transform,
  // Export PassThrough for compatibility with Node.js core's stream module
  PassThrough
}
module.exports = class StreamError extends Error {
  constructor(msg, code, fn = StreamError) {
    super(msg)

    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  static isStreamDestroyed(err) {
    return err && err.code === 'STREAM_DESTROYED'
  }

  static isPrematureClose(err) {
    return err && err.code === 'PREMATURE_CLOSE'
  }

  static isAborted(err) {
    return err && err.code === 'ABORTED'
  }

  static isBadArgument(err) {
    return err && err.code === 'BAD_ARGUMENT'
  }

  get name() {
    return 'StreamError'
  }

  static STREAM_DESTROYED() {
    return new StreamError('Stream was destroyed', 'STREAM_DESTROYED', StreamError.STREAM_DESTROYED)
  }

  static PREMATURE_CLOSE(msg = 'Premature close') {
    return new StreamError(msg, 'PREMATURE_CLOSE', StreamError.PREMATURE_CLOSE)
  }

  static ABORTED() {
    return new StreamError('Stream aborted', 'ABORTED', StreamError.ABORTED)
  }

  static BAD_ARGUMENT(msg = 'Bad argument') {
    return new StreamError(msg, 'BAD_ARGUMENT', StreamError.BAD_ARGUMENT)
  }
}
{
  "name": "streamx",
  "version": "2.28.0",
  "description": "An iteration of the Node.js core streams with a series of improvements",
  "main": "index.js",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./errors": {
      "types": "./lib/errors.d.ts",
      "default": "./lib/errors"
    }
  },
  "dependencies": {
    "events-universal": "^1.0.0",
    "fast-fifo": "^1.3.2",
    "text-decoder": "^1.1.0"
  },
  "devDependencies": {
    "b4a": "^1.6.6",
    "brittle": "^3.1.1",
    "end-of-stream": "^1.4.4",
    "lunte": "^1.8.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "runtime.d.ts",
    "lib"
  ],
  "scripts": {
    "format": "prettier . --write",
    "test": "brittle test/all.js && brittle-bare test/all.js",
    "lint": "prettier . --check && lunte"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/streamx.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/streamx/issues"
  },
  "homepage": "https://github.com/mafintosh/streamx"
}
const { Readable } = require('streamx')

module.exports = function (s, forks = 2) {
  const streams = new Array(forks)
  const status = new Array(forks).fill(true)

  let ended = false

  for (let i = 0; i < forks; i++) {
    streams[i] = new Readable({
      read (cb) {
        const check = !status[i]
        status[i] = true
        if (check && allReadable()) s.resume()
        cb(null)
      }
    })
  }

  s.on('end', function () {
    ended = true
    for (const stream of streams) stream.push(null)
  })

  s.on('error', function (err) {
    for (const stream of streams) stream.destroy(err)
  })

  s.on('close', function () {
    if (ended) return
    for (const stream of streams) stream.destroy()
  })

  s.on('data', function (data) {
    let needsPause = false
    for (let i = 0; i < streams.length; i++) {
      if (!(status[i] = streams[i].push(data))) {
        needsPause = true
      }
    }
    if (needsPause) s.pause()
  })

  return streams

  function allReadable () {
    for (let j = 0; j < status.length; j++) {
      if (!status[j]) return false
    }
    return true
  }
}
{
  "name": "teex",
  "version": "1.0.1",
  "description": "Turn a readable stream into multiple readable streamx streams",
  "main": "index.js",
  "dependencies": {
    "streamx": "^2.12.5"
  },
  "devDependencies": {
    "standard": "^14.3.4",
    "tape": "^5.0.1"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/teex.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/teex/issues"
  },
  "homepage": "https://github.com/mafintosh/teex"
}
const PassThroughDecoder = require('./lib/pass-through-decoder')
const UTF8Decoder = require('./lib/utf8-decoder')

module.exports = class TextDecoder {
  constructor(encoding = 'utf8') {
    this.encoding = normalizeEncoding(encoding)

    switch (this.encoding) {
      case 'utf8':
        this.decoder = new UTF8Decoder()
        break
      case 'utf16le':
      case 'base64':
        throw new Error('Unsupported encoding: ' + this.encoding)
      default:
        this.decoder = new PassThroughDecoder(this.encoding)
    }
  }

  get remaining() {
    return this.decoder.remaining
  }

  push(data) {
    if (typeof data === 'string') return data
    return this.decoder.decode(data)
  }

  // For Node.js compatibility
  write(data) {
    return this.push(data)
  }

  end(data) {
    let result = ''
    if (data) result = this.push(data)
    result += this.decoder.flush()
    return result
  }
}

function normalizeEncoding(encoding) {
  encoding = encoding.toLowerCase()

  switch (encoding) {
    case 'utf8':
    case 'utf-8':
      return 'utf8'
    case 'ucs2':
    case 'ucs-2':
    case 'utf16le':
    case 'utf-16le':
      return 'utf16le'
    case 'latin1':
    case 'binary':
      return 'latin1'
    case 'base64':
    case 'ascii':
    case 'hex':
      return encoding
    default:
      throw new Error('Unknown encoding: ' + encoding)
  }
}
const b4a = require('b4a')

module.exports = class PassThroughDecoder {
  constructor(encoding) {
    this.encoding = encoding
  }

  get remaining() {
    return 0
  }

  decode(data) {
    return b4a.toString(data, this.encoding)
  }

  flush() {
    return ''
  }
}
const b4a = require('b4a')

/**
 * https://encoding.spec.whatwg.org/#utf-8-decoder
 */
module.exports = class UTF8Decoder {
  constructor() {
    this._reset()
  }

  get remaining() {
    return this.bytesSeen
  }

  decode(data) {
    if (data.byteLength === 0) return ''

    if (this.bytesNeeded === 0 && trailingIncomplete(data, 0) === 0) {
      this.bytesSeen = trailingBytesSeen(data)
      return b4a.toString(data, 'utf8')
    }

    let result = ''
    let start = 0

    if (this.bytesNeeded > 0) {
      while (start < data.byteLength) {
        const byte = data[start]

        if (byte < this.lowerBoundary || byte > this.upperBoundary) {
          result += '\ufffd'
          this._reset()
          break
        }

        this.lowerBoundary = 0x80
        this.upperBoundary = 0xbf
        this.codePoint = (this.codePoint << 6) | (byte & 0x3f)
        this.bytesSeen++
        start++

        if (this.bytesSeen === this.bytesNeeded) {
          result += String.fromCodePoint(this.codePoint)
          this._reset()
          break
        }
      }

      if (this.bytesNeeded > 0) return result
    }

    const trailing = trailingIncomplete(data, start)
    const end = data.byteLength - trailing

    if (end > start) result += b4a.toString(data, 'utf8', start, end)

    for (let i = end; i < data.byteLength; i++) {
      const byte = data[i]

      if (this.bytesNeeded === 0) {
        if (byte <= 0x7f) {
          this.bytesSeen = 0
          result += String.fromCharCode(byte)
        } else if (byte >= 0xc2 && byte <= 0xdf) {
          this.bytesNeeded = 2
          this.bytesSeen = 1
          this.codePoint = byte & 0x1f
        } else if (byte >= 0xe0 && byte <= 0xef) {
          if (byte === 0xe0) this.lowerBoundary = 0xa0
          else if (byte === 0xed) this.upperBoundary = 0x9f
          this.bytesNeeded = 3
          this.bytesSeen = 1
          this.codePoint = byte & 0xf
        } else if (byte >= 0xf0 && byte <= 0xf4) {
          if (byte === 0xf0) this.lowerBoundary = 0x90
          else if (byte === 0xf4) this.upperBoundary = 0x8f
          this.bytesNeeded = 4
          this.bytesSeen = 1
          this.codePoint = byte & 0x7
        } else {
          this.bytesSeen = 1
          result += '\ufffd'
        }

        continue
      }

      if (byte < this.lowerBoundary || byte > this.upperBoundary) {
        result += '\ufffd'
        i--
        this._reset()

        continue
      }

      this.lowerBoundary = 0x80
      this.upperBoundary = 0xbf

      this.codePoint = (this.codePoint << 6) | (byte & 0x3f)
      this.bytesSeen++

      if (this.bytesSeen === this.bytesNeeded) {
        result += String.fromCodePoint(this.codePoint)
        this._reset()
      }
    }

    return result
  }

  flush() {
    const result = this.bytesNeeded > 0 ? '\ufffd' : ''
    this._reset()
    return result
  }

  _reset() {
    this.codePoint = 0
    this.bytesNeeded = 0
    this.bytesSeen = 0
    this.lowerBoundary = 0x80
    this.upperBoundary = 0xbf
  }
}

function trailingIncomplete(data, start) {
  const len = data.byteLength
  if (len <= start) return 0

  const limit = Math.max(start, len - 4)

  let i = len - 1
  while (i > limit && (data[i] & 0xc0) === 0x80) i--

  if (i < start) return 0

  const byte = data[i]

  let needed
  if (byte <= 0x7f) return 0
  if (byte >= 0xc2 && byte <= 0xdf) needed = 2
  else if (byte >= 0xe0 && byte <= 0xef) needed = 3
  else if (byte >= 0xf0 && byte <= 0xf4) needed = 4
  else return 0

  const available = len - i
  return available < needed ? available : 0
}

function trailingBytesSeen(data) {
  const len = data.byteLength
  if (len === 0) return 0

  const last = data[len - 1]

  if (last <= 0x7f) return 0
  if ((last & 0xc0) !== 0x80) return 1

  const limit = Math.max(0, len - 4)

  let i = len - 2
  while (i >= limit && (data[i] & 0xc0) === 0x80) i--

  if (i < 0) return 1

  const first = data[i]

  let needed
  if (first >= 0xc2 && first <= 0xdf) needed = 2
  else if (first >= 0xe0 && first <= 0xef) needed = 3
  else if (first >= 0xf0 && first <= 0xf4) needed = 4
  else return 1

  if (len - i !== needed) return 1

  if (needed >= 3) {
    const second = data[i + 1]
    if (first === 0xe0 && second < 0xa0) return 1
    if (first === 0xed && second > 0x9f) return 1
    if (first === 0xf0 && second < 0x90) return 1
    if (first === 0xf4 && second > 0x8f) return 1
  }

  return 0
}
{
  "name": "text-decoder",
  "version": "1.2.7",
  "description": "Streaming text decoder that preserves multibyte Unicode characters",
  "exports": {
    "./package": "./package.json",
    ".": "./index.js"
  },
  "files": [
    "index.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/text-decoder.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/text-decoder/issues"
  },
  "homepage": "https://github.com/holepunchto/text-decoder#readme",
  "dependencies": {
    "b4a": "^1.6.4"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  }
}
module.exports = class TimerBrowser {
  constructor (ms, fn, ctx = null, interval = false) {
    this.ms = ms
    this.ontimeout = fn
    this.context = ctx || null
    this.interval = interval
    this.done = false

    this._timer = interval
      ? setInterval(callInterval, ms, this)
      : setTimeout(callTimeout, ms, this)
  }

  unref () {}

  ref () {}

  refresh () {
    if (this.done) return

    if (this.interval) {
      clearInterval(this._timer)
      this._timer = setInterval(callInterval, this.ms, this)
    } else {
      clearTimeout(this._timer)
      this._timer = setTimeout(callTimeout, this.ms, this)
    }
  }

  destroy () {
    this.done = true
    this.ontimeout = null

    if (this.interval) clearInterval(this._timer)
    else clearTimeout(this._timer)
  }

  static once (ms, fn, ctx) {
    return new this(ms, fn, ctx, false)
  }

  static on (ms, fn, ctx) {
    return new this(ms, fn, ctx, true)
  }
}

function callTimeout (self) {
  self.done = true
  self.ontimeout.call(self.context)
}

function callInterval (self) {
  self.ontimeout.call(self.context)
}
module.exports = isNode()
  ? require('./node')
  : require('./browser')

function isNode () {
  const to = setTimeout(function () {}, 1000)
  clearTimeout(to)
  return !!to.refresh
}
module.exports = class Timer {
  constructor (ms, fn, ctx = null, interval = false) {
    this.ms = ms
    this.ontimeout = fn
    this.context = ctx
    this.interval = interval
    this.done = false

    this._timer = interval
      ? setInterval(callInterval, ms, this)
      : setTimeout(callTimeout, ms, this)
  }

  unref () {
    this._timer.unref()
  }

  ref () {
    this._timer.ref()
  }

  refresh () {
    if (this.done !== true) this._timer.refresh()
  }

  destroy () {
    this.done = true
    this.ontimeout = null
    if (this.interval) clearInterval(this._timer)
    else clearTimeout(this._timer)
  }

  static once (ms, fn, ctx) {
    return new this(ms, fn, ctx, false)
  }

  static on (ms, fn, ctx) {
    return new this(ms, fn, ctx, true)
  }
}

function callTimeout (self) {
  self.done = true
  self.ontimeout.call(self.context)
}

function callInterval (self) {
  self.ontimeout.call(self.context)
}
{
  "name": "timeout-refresh",
  "version": "2.0.1",
  "description": "Efficiently refresh a timer",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^16.0.4",
    "tape": "^5.5.2"
  },
  "browser": "./browser.js",
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/timeout-refresh.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/timeout-refresh/issues"
  },
  "homepage": "https://github.com/mafintosh/timeout-refresh"
}
const b4a = require('b4a')

unslab.all = all
unslab.is = is

module.exports = unslab

function unslab (buf) {
  if (buf === null || buf.buffer.byteLength === buf.byteLength) return buf
  const copy = b4a.allocUnsafeSlow(buf.byteLength)
  copy.set(buf, 0)
  return copy
}

function is (buf) {
  return buf.buffer.byteLength !== buf.byteLength
}

function all (list) {
  let size = 0
  for (let i = 0; i < list.length; i++) {
    const buf = list[i]
    size += buf === null || buf.buffer.byteLength === buf.byteLength ? 0 : buf.byteLength
  }

  const copy = b4a.allocUnsafeSlow(size)
  const result = new Array(list.length)

  let offset = 0
  for (let i = 0; i < list.length; i++) {
    let buf = list[i]

    if (buf !== null && buf.buffer.byteLength !== buf.byteLength) {
      copy.set(buf, offset)
      buf = copy.subarray(offset, offset += buf.byteLength)
    }

    result[i] = buf
  }

  return result
}
{
  "name": "unslab",
  "version": "1.3.0",
  "description": "Unslab some slab'ed buffers",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.6.6"
  },
  "devDependencies": {
    "brittle": "^3.5.2",
    "standard": "^17.1.0"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/unslab.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/unslab/issues"
  },
  "homepage": "https://github.com/holepunchto/unslab"
}
module.exports = read

var MSB = 0x80
  , REST = 0x7F

function read(buf, offset) {
  var res    = 0
    , offset = offset || 0
    , shift  = 0
    , counter = offset
    , b
    , l = buf.length

  do {
    if (counter >= l) {
      read.bytes = 0
      throw new RangeError('Could not decode varint')
    }
    b = buf[counter++]
    res += shift < 28
      ? (b & REST) << shift
      : (b & REST) * Math.pow(2, shift)
    shift += 7
  } while (b >= MSB)

  read.bytes = counter - offset

  return res
}
module.exports = encode

var MSB = 0x80
  , REST = 0x7F
  , MSBALL = ~REST
  , INT = Math.pow(2, 31)

function encode(num, out, offset) {
  out = out || []
  offset = offset || 0
  var oldOffset = offset

  while(num >= INT) {
    out[offset++] = (num & 0xFF) | MSB
    num /= 128
  }
  while(num & MSBALL) {
    out[offset++] = (num & 0xFF) | MSB
    num >>>= 7
  }
  out[offset] = num | 0
  
  encode.bytes = offset - oldOffset + 1
  
  return out
}
module.exports = {
    encode: require('./encode.js')
  , decode: require('./decode.js')
  , encodingLength: require('./length.js')
}

var N1 = Math.pow(2,  7)
var N2 = Math.pow(2, 14)
var N3 = Math.pow(2, 21)
var N4 = Math.pow(2, 28)
var N5 = Math.pow(2, 35)
var N6 = Math.pow(2, 42)
var N7 = Math.pow(2, 49)
var N8 = Math.pow(2, 56)
var N9 = Math.pow(2, 63)

module.exports = function (value) {
  return (
    value < N1 ? 1
  : value < N2 ? 2
  : value < N3 ? 3
  : value < N4 ? 4
  : value < N5 ? 5
  : value < N6 ? 6
  : value < N7 ? 7
  : value < N8 ? 8
  : value < N9 ? 9
  :              10
  )
}
{
  "name": "varint",
  "version": "5.0.0",
  "description": "protobuf-style varint bytes - use msb to create integer values of varying sizes",
  "main": "index.js",
  "scripts": {
    "test": "node test.js"
  },
  "repository": {
    "type": "git",
    "url": "git://github.com/chrisdickinson/varint.git"
  },
  "keywords": [
    "varint",
    "protobuf",
    "encode",
    "decode"
  ],
  "author": "Chris Dickinson <chris@neversaw.us>",
  "license": "MIT",
  "devDependencies": {
    "tape": "~2.12.3"
  }
}
const { runtime, platform, arch, version } =
  typeof Bare !== 'undefined'
    ? {
        runtime: 'bare',
        platform: global.Bare.platform,
        arch: global.Bare.arch,
        version: global.Bare.version
      }
    : typeof process !== 'undefined'
      ? {
          runtime: 'node',
          platform: global.process.platform,
          arch: global.process.arch,
          version: global.process.version
        }
      : typeof Window !== 'undefined'
        ? { runtime: 'browser', platform: 'unknown', arch: 'unknown', version: 'unknown' }
        : { runtime: 'unknown', platform: 'unknown', arch: 'unknown', version: 'unknown' }

exports.runtime = runtime
exports.version = version
exports.platform = platform
exports.arch = arch
exports.isBare = runtime === 'bare'
exports.isBareKit = exports.isBare && typeof BareKit !== 'undefined'
exports.isPear = typeof Pear !== 'undefined'
exports.isNode = runtime === 'node'
exports.isBrowser = runtime === 'browser'
exports.isWindows = platform === 'win32'
exports.isLinux = platform === 'linux'
exports.isMac = platform === 'darwin'
exports.isIOS = platform === 'ios' || platform === 'ios-simulator'
exports.isAndroid = platform === 'android'
exports.isElectron = typeof process !== 'undefined' && !!global.process.versions?.electron
exports.isElectronRenderer = exports.isElectron && global.process.type === 'renderer'
exports.isElectronWorker = exports.isElectron && global.process.type === 'worker'
{
  "name": "which-runtime",
  "version": "1.4.0",
  "description": "Detect if you are in Bare or Node and which os etc",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte .",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/which-runtime.git"
  },
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/which-runtime/issues"
  },
  "homepage": "https://github.com/holepunchto/which-runtime",
  "devDependencies": {
    "brittle": "^3.0.0",
    "lunte": "^1.4.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = class MaxCache {
  constructor({ maxSize, maxAge, createMap, ongc }) {
    this.maxSize = maxSize
    this.maxAge = maxAge
    this.ongc = ongc || null

    this._createMap = createMap || defaultCreateMap
    this._latest = this._createMap()
    this._oldest = this._createMap()
    this._retained = this._createMap()
    this._gced = false
    this._interval = null

    if (this.maxAge > 0 && this.maxAge < Infinity) {
      const tick = Math.ceil((2 / 3) * this.maxAge)
      this._interval = setInterval(this._gcAuto.bind(this), tick)
      if (this._interval.unref) this._interval.unref()
    }
  }

  get size() {
    return this._latest.size + this._oldest.size + this._retained.size
  }

  *[Symbol.iterator]() {
    for (const it of [this._latest, this._oldest, this._retained]) {
      yield* it
    }
  }

  *keys() {
    for (const it of [this._latest, this._oldest, this._retained]) {
      yield* it.keys()
    }
  }

  *values() {
    for (const it of [this._latest, this._oldest, this._retained]) {
      yield* it.values()
    }
  }

  destroy() {
    this.clear()
    clearInterval(this._interval)
    this._interval = null
  }

  clear() {
    this._gced = true
    this._latest.clear()
    this._oldest.clear()
    this._retained.clear()
  }

  set(k, v) {
    if (this._retained.has(k)) return this
    this._latest.set(k, v)
    this._oldest.delete(k) || this._retained.delete(k)
    if (this._latest.size >= this.maxSize) this._gc()
    return this
  }

  retain(k, v) {
    this._retained.set(k, v)
    this._latest.delete(k) || this._oldest.delete(k)
    return this
  }

  delete(k) {
    return (
      this._latest.delete(k) ||
      this._oldest.delete(k) ||
      this._retained.delete(k)
    )
  }

  has(k) {
    return this._latest.has(k) || this._oldest.has(k) || this._retained.has(k)
  }

  get(k) {
    if (this._latest.has(k)) {
      return this._latest.get(k)
    }

    if (this._oldest.has(k)) {
      const v = this._oldest.get(k)
      this._latest.set(k, v)
      this._oldest.delete(k)
      return v
    }

    if (this._retained.has(k)) {
      return this._retained.get(k)
    }

    return null
  }

  _gcAuto() {
    if (!this._gced) this._gc()
    this._gced = false
  }

  _gc() {
    this._gced = true
    if (this.ongc !== null && this._oldest.size > 0) this.ongc(this._oldest)
    this._oldest = this._latest
    this._latest = this._createMap()
  }
}

function defaultCreateMap() {
  return new Map()
}
{
  "name": "xache",
  "version": "1.3.0",
  "description": "Yet another auto expiring, max sizable cache",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "devDependencies": {
    "brittle": "^3.3.2",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "test": "prettier --check . && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/xache.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/xache/issues"
  },
  "homepage": "https://github.com/mafintosh/xache"
}
const b4a = require('b4a')

const ALPHABET = 'ybndrfg8ejkmcpqxot1uwisza345h769'
const MIN = 0x31 // 1
const MAX = 0x7a // z
const REVERSE = new Int8Array(1 + MAX - MIN)

REVERSE.fill(-1)

for (let i = 0; i < ALPHABET.length; i++) {
  const v = ALPHABET.charCodeAt(i) - MIN
  REVERSE[v] = i
}

exports.encode = encode
exports.decode = decode
exports.ALPHABET = ALPHABET

function decode (s, out) {
  let pb = 0
  let ps = 0

  const r = s.length & 7
  const q = (s.length - r) / 8

  if (!out) out = b4a.allocUnsafe(Math.ceil(s.length * 5 / 8))

  // 0 5 2 7 4 1 6 3 (+5 mod 8)
  for (let i = 0; i < q; i++) {
    const a = quintet(s, ps++)
    const b = quintet(s, ps++)
    const c = quintet(s, ps++)
    const d = quintet(s, ps++)
    const e = quintet(s, ps++)
    const f = quintet(s, ps++)
    const g = quintet(s, ps++)
    const h = quintet(s, ps++)

    out[pb++] = (a << 3) | (b >>> 2)
    out[pb++] = ((b & 0b11) << 6) | (c << 1) | (d >>> 4)
    out[pb++] = ((d & 0b1111) << 4) | (e >>> 1)
    out[pb++] = ((e & 0b1) << 7) | (f << 2) | (g >>> 3)
    out[pb++] = ((g & 0b111) << 5) | h
  }

  if (r === 0) return out.subarray(0, pb)

  const a = quintet(s, ps++)
  const b = quintet(s, ps++)

  out[pb++] = (a << 3) | (b >>> 2)

  if (r <= 2) return out.subarray(0, pb)

  const c = quintet(s, ps++)
  const d = quintet(s, ps++)

  out[pb++] = ((b & 0b11) << 6) | (c << 1) | (d >>> 4)

  if (r <= 4) return out.subarray(0, pb)

  const e = quintet(s, ps++)

  out[pb++] = ((d & 0b1111) << 4) | (e >>> 1)

  if (r <= 5) return out.subarray(0, pb)

  const f = quintet(s, ps++)
  const g = quintet(s, ps++)

  out[pb++] = ((e & 0b1) << 7) | (f << 2) | (g >>> 3)

  if (r <= 7) return out.subarray(0, pb)

  const h = quintet(s, ps++)

  out[pb++] = ((g & 0b111) << 5) | h

  return out.subarray(0, pb)
}

function encode (buf) {
  if (typeof buf === 'string') buf = b4a.from(buf)

  const max = buf.byteLength * 8

  let s = ''

  for (let p = 0; p < max; p += 5) {
    const i = p >>> 3
    const j = p & 7

    if (j <= 3) {
      s += ALPHABET[(buf[i] >>> (3 - j)) & 0b11111]
      continue
    }

    const of = j - 3
    const h = (buf[i] << of) & 0b11111
    const l = (i >= buf.byteLength ? 0 : buf[i + 1]) >>> (8 - of)

    s += ALPHABET[h | l]
  }

  return s
}

function quintet (s, i) {
  if (i > s.length) {
    return 0
  }

  const v = s.charCodeAt(i)

  if (v < MIN || v > MAX) {
    throw Error('Invalid character in base32 input: "' + s[i] + '" at position ' + i)
  }

  const bits = REVERSE[v - MIN]

  if (bits === -1) {
    throw Error('Invalid character in base32 input: "' + s[i] + '" at position ' + i)
  }

  return bits
}
{
  "name": "z32",
  "version": "1.1.0",
  "description": "Encode & decode z-base32",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.5.3"
  },
  "devDependencies": {
    "base-x": "^4.0.0",
    "base32": "0.0.7",
    "brittle": "^3.1.3",
    "nanobench": "^3.0.0",
    "rfc4648": "^1.5.2",
    "standard": "^17.0.0"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/z32.git"
  },
  "scripts": {
    "test": "standard && brittle test.js",
    "bench": "node benchmark.js"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/z32/issues"
  },
  "homepage": "https://github.com/mafintosh/z32"
}
{
  "name": "atproto-store",
  "version": "0.0.25",
  "description": "Holepunch-native atproto repo store — records in a classic Hyperbee (collection/rkey -> DAG-CBOR). The P2P home; the atproto-repo module is the bridge serializer over it.",
  "type": "module",
  "main": "lib/repo-store.js",
  "scripts": {
    "test": "brittle-node test/*.test.js"
  },
  "dependencies": {
    "atproto-repo": "file:../atproto-repo",
    "@ipld/dag-cbor": "^9.2.1",
    "b4a": "^1.6.0",
    "corestore": "^7.4.0",
    "hyperbee": "^2.20.0",
    "random-access-memory": "^6.2.0",
    "bare-fs": "^4.7.3",
    "bare-path": "^3.0.1"
  },
  "devDependencies": {
    "brittle": "^4.0.2"
  },
  "imports": {
    "#node:fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "#node:path": {
      "bare": "bare-path",
      "default": "path"
    }
  },
  "overrides": {
    "rocksdb-native": "3.17.2",
    "hypercore-storage": "3.2.0"
  }
}
function isBuffer(value) {
  return Buffer.isBuffer(value) || value instanceof Uint8Array
}

function isEncoding(encoding) {
  return Buffer.isEncoding(encoding)
}

function alloc(size, fill, encoding) {
  return Buffer.alloc(size, fill, encoding)
}

function allocUnsafe(size) {
  return Buffer.allocUnsafe(size)
}

function allocUnsafeSlow(size) {
  return Buffer.allocUnsafeSlow(size)
}

function byteLength(string, encoding) {
  return Buffer.byteLength(string, encoding)
}

function compare(a, b) {
  return Buffer.compare(a, b)
}

function concat(buffers, totalLength) {
  return Buffer.concat(buffers, totalLength)
}

function copy(source, target, targetStart, start, end) {
  return toBuffer(source).copy(target, targetStart, start, end)
}

function equals(a, b) {
  return toBuffer(a).equals(b)
}

function fill(buffer, value, offset, end, encoding) {
  return toBuffer(buffer).fill(value, offset, end, encoding)
}

function from(value, encodingOrOffset, length) {
  return Buffer.from(value, encodingOrOffset, length)
}

function includes(buffer, value, byteOffset, encoding) {
  return toBuffer(buffer).includes(value, byteOffset, encoding)
}

function indexOf(buffer, value, byfeOffset, encoding) {
  return toBuffer(buffer).indexOf(value, byfeOffset, encoding)
}

function lastIndexOf(buffer, value, byteOffset, encoding) {
  return toBuffer(buffer).lastIndexOf(value, byteOffset, encoding)
}

function swap16(buffer) {
  return toBuffer(buffer).swap16()
}

function swap32(buffer) {
  return toBuffer(buffer).swap32()
}

function swap64(buffer) {
  return toBuffer(buffer).swap64()
}

function toBuffer(buffer) {
  if (Buffer.isBuffer(buffer)) return buffer
  return Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

function toString(buffer, encoding, start, end) {
  return toBuffer(buffer).toString(encoding, start, end)
}

function write(buffer, string, offset, length, encoding) {
  return toBuffer(buffer).write(string, offset, length, encoding)
}

function readDoubleBE(buffer, offset) {
  return toBuffer(buffer).readDoubleBE(offset)
}

function readDoubleLE(buffer, offset) {
  return toBuffer(buffer).readDoubleLE(offset)
}

function readFloatBE(buffer, offset) {
  return toBuffer(buffer).readFloatBE(offset)
}

function readFloatLE(buffer, offset) {
  return toBuffer(buffer).readFloatLE(offset)
}

function readInt32BE(buffer, offset) {
  return toBuffer(buffer).readInt32BE(offset)
}

function readInt32LE(buffer, offset) {
  return toBuffer(buffer).readInt32LE(offset)
}

function readUInt32BE(buffer, offset) {
  return toBuffer(buffer).readUInt32BE(offset)
}

function readUInt32LE(buffer, offset) {
  return toBuffer(buffer).readUInt32LE(offset)
}

function writeDoubleBE(buffer, value, offset) {
  return toBuffer(buffer).writeDoubleBE(value, offset)
}

function writeDoubleLE(buffer, value, offset) {
  return toBuffer(buffer).writeDoubleLE(value, offset)
}

function writeFloatBE(buffer, value, offset) {
  return toBuffer(buffer).writeFloatBE(value, offset)
}

function writeFloatLE(buffer, value, offset) {
  return toBuffer(buffer).writeFloatLE(value, offset)
}

function writeInt32BE(buffer, value, offset) {
  return toBuffer(buffer).writeInt32BE(value, offset)
}

function writeInt32LE(buffer, value, offset) {
  return toBuffer(buffer).writeInt32LE(value, offset)
}

function writeUInt32BE(buffer, value, offset) {
  return toBuffer(buffer).writeUInt32BE(value, offset)
}

function writeUInt32LE(buffer, value, offset) {
  return toBuffer(buffer).writeUInt32LE(value, offset)
}

module.exports = {
  isBuffer,
  isEncoding,
  alloc,
  allocUnsafe,
  allocUnsafeSlow,
  byteLength,
  compare,
  concat,
  copy,
  equals,
  fill,
  from,
  includes,
  indexOf,
  lastIndexOf,
  swap16,
  swap32,
  swap64,
  toBuffer,
  toString,
  write,
  readDoubleBE,
  readDoubleLE,
  readFloatBE,
  readFloatLE,
  readInt32BE,
  readInt32LE,
  readUInt32BE,
  readUInt32LE,
  writeDoubleBE,
  writeDoubleLE,
  writeFloatBE,
  writeFloatLE,
  writeInt32BE,
  writeInt32LE,
  writeUInt32BE,
  writeUInt32LE
}
{
  "name": "b4a",
  "version": "1.8.1",
  "description": "Bridging the gap between buffers and typed arrays",
  "exports": {
    "./package": "./package.json",
    ".": {
      "react-native": "./react-native.js",
      "browser": "./browser.js",
      "default": "./index.js"
    }
  },
  "files": [
    "browser.js",
    "index.js",
    "react-native.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:bare && npm run test:node",
    "test:bare": "brittle-bare --coverage test.mjs",
    "test:node": "brittle-node --coverage test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/b4a.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/b4a/issues"
  },
  "homepage": "https://github.com/holepunchto/b4a#readme",
  "devDependencies": {
    "brittle": "^3.5.2",
    "lunte": "^1.7.0",
    "nanobench": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "react-native-b4a": "*"
  },
  "peerDependenciesMeta": {
    "react-native-b4a": {
      "optional": true
    }
  }
}
const errors = require('./lib/errors')

class EventListener {
  constructor() {
    this.list = []
    this.count = 0
  }

  append(ctx, name, fn, once) {
    this.count++
    ctx.emit('newListener', name, fn) // Emit BEFORE adding
    this.list.push([fn, once])
  }

  prepend(ctx, name, fn, once) {
    this.count++
    ctx.emit('newListener', name, fn) // Emit BEFORE adding
    this.list.unshift([fn, once])
  }

  remove(ctx, name, fn) {
    for (let i = 0, n = this.list.length; i < n; i++) {
      const l = this.list[i]

      if (l[0] === fn) {
        this.list.splice(i, 1)

        if (this.count === 1) delete ctx._events[name]

        ctx.emit('removeListener', name, fn) // Emit AFTER removing

        this.count--
        return
      }
    }
  }

  removeAll(ctx, name) {
    const list = [...this.list]
    this.list = []

    if (this.count === list.length) delete ctx._events[name]

    for (let i = list.length - 1; i >= 0; i--) {
      ctx.emit('removeListener', name, list[i][0]) // Emit AFTER removing
    }

    this.count -= list.length
  }

  emit(ctx, name, ...args) {
    const list = [...this.list]

    for (let i = 0, n = list.length; i < n; i++) {
      const l = list[i]

      if (l[1] === true) this.remove(ctx, name, l[0])

      Reflect.apply(l[0], ctx, args)
    }

    return list.length > 0
  }
}

function appendListener(ctx, name, fn, once) {
  if (ctx._events === undefined) ctx._events = Object.create(null)
  const e = ctx._events[name] || (ctx._events[name] = new EventListener())
  e.append(ctx, name, fn, once)
  return ctx
}

function prependListener(ctx, name, fn, once) {
  if (ctx._events === undefined) ctx._events = Object.create(null)
  const e = ctx._events[name] || (ctx._events[name] = new EventListener())
  e.prepend(ctx, name, fn, once)
  return ctx
}

function removeListener(ctx, name, fn) {
  if (ctx._events === undefined) return ctx
  const e = ctx._events[name]
  if (e !== undefined) e.remove(ctx, name, fn)
  return ctx
}

function throwUnhandledError(...args) {
  let err

  if (args.length > 0) err = args[0]

  if (err instanceof Error === false) err = errors.UNHANDLED_ERROR(err)

  if (Error.captureStackTrace) {
    Error.captureStackTrace(err, exports.prototype.emit)
  }

  queueMicrotask(() => {
    throw err
  })
}

module.exports = exports = class EventEmitter {
  constructor() {
    this._events = Object.create(null)
  }

  addListener(name, fn) {
    return appendListener(this, name, fn, false)
  }

  addOnceListener(name, fn) {
    return appendListener(this, name, fn, true)
  }

  prependListener(name, fn) {
    return prependListener(this, name, fn, false)
  }

  prependOnceListener(name, fn) {
    return prependListener(this, name, fn, true)
  }

  removeListener(name, fn) {
    return removeListener(this, name, fn)
  }

  on(name, fn) {
    return appendListener(this, name, fn, false)
  }

  once(name, fn) {
    return appendListener(this, name, fn, true)
  }

  off(name, fn) {
    return removeListener(this, name, fn)
  }

  emit(name, ...args) {
    if (name === 'error' && this._events !== undefined && this._events.error === undefined) {
      throwUnhandledError(...args)
    }

    if (this._events === undefined) return false
    const e = this._events[name]
    return e === undefined ? false : e.emit(this, name, ...args)
  }

  listeners(name) {
    if (this._events === undefined) return []
    const e = this._events[name]
    return e === undefined ? [] : [...e.list]
  }

  rawListeners(name) {
    if (this._events === undefined) return []
    const e = this._events[name]
    return e === undefined ? [] : e.list.map((l) => l[0])
  }

  eventNames() {
    if (this._events === undefined) return []
    return Reflect.ownKeys(this._events)
  }

  listenerCount(name) {
    if (this._events === undefined) return 0
    const e = this._events[name]
    return e === undefined ? 0 : e.list.length
  }

  getMaxListeners() {
    return EventEmitter.defaultMaxListeners
  }

  setMaxListeners(n) {}

  removeAllListeners(name) {
    if (arguments.length === 0) {
      for (const key of Reflect.ownKeys(this._events)) {
        if (key === 'removeListener') continue
        this.removeAllListeners(key)
      }
      this.removeAllListeners('removeListener')
    } else {
      const e = this._events[name]
      if (e !== undefined) e.removeAll(this, name)
    }
    return this
  }
}

exports.EventEmitter = exports

exports.errors = errors

exports.defaultMaxListeners = 10

exports.on = function on(emitter, name, opts = {}) {
  const { signal } = opts

  if (signal && signal.aborted) {
    throw errors.OPERATION_ABORTED(signal.reason)
  }

  let error = null
  let done = false

  const events = []
  const promises = []

  if (name !== 'error') emitter.on('error', onerror)

  if (signal) signal.addEventListener('abort', onabort)

  emitter.on(name, onevent)

  return {
    next() {
      if (events.length) {
        return Promise.resolve({ value: events.shift(), done: false })
      }

      if (error) {
        const err = error

        error = null

        return Promise.reject(err)
      }

      if (done) return onclose()

      return new Promise((resolve, reject) => promises.push({ resolve, reject }))
    },

    return() {
      return onclose()
    },

    throw(err) {
      return onerror(err)
    },

    [Symbol.asyncIterator]() {
      return this
    }
  }

  function onevent(...args) {
    if (promises.length) {
      promises.shift().resolve({ value: args, done: false })
    } else {
      events.push(args)
    }
  }

  function onerror(err) {
    emitter.off(name, onevent).off('error', onerror)

    if (promises.length) {
      promises.shift().reject(err)
    } else {
      error = err
    }

    return Promise.resolve({ done: true })
  }

  function onabort() {
    signal.removeEventListener('abort', onabort)

    onerror(errors.OPERATION_ABORTED(signal.reason))
  }

  function onclose() {
    emitter.off(name, onevent)

    if (name !== 'error') emitter.off('error', onerror)

    if (signal) signal.removeEventListener('abort', onabort)

    done = true

    if (promises.length) promises.shift().resolve({ done: true })

    return Promise.resolve({ done: true })
  }
}

exports.once = function once(emitter, name, opts = {}) {
  const { signal } = opts

  if (signal && signal.aborted) {
    return Promise.reject(errors.OPERATION_ABORTED(signal.reason))
  }

  return new Promise((resolve, reject) => {
    if (name !== 'error') emitter.on('error', onerror)

    if (signal) signal.addEventListener('abort', onabort)

    emitter.once(name, onevent)

    function onevent(...args) {
      if (name !== 'error') emitter.off('error', onerror)

      if (signal) signal.removeEventListener('abort', onabort)

      resolve(args)
    }

    function onerror(err) {
      emitter.off(name, onevent)

      if (name !== 'error') emitter.off('error', onerror)

      reject(err)
    }

    function onabort() {
      signal.removeEventListener('abort', onabort)

      onerror(errors.OPERATION_ABORTED(signal.reason))
    }
  })
}

exports.forward = function forward(from, to, names, opts = {}) {
  if (typeof names === 'string') names = [names]

  const { emit = to.emit.bind(to) } = opts

  const listeners = names.map(
    (name) =>
      function onevent(...args) {
        emit(name, ...args)
      }
  )

  to.on('newListener', (name) => {
    const i = names.indexOf(name)

    if (i !== -1 && to.listenerCount(name) === 0) {
      from.on(name, listeners[i])
    }
  }).on('removeListener', (name) => {
    const i = names.indexOf(name)

    if (i !== -1 && to.listenerCount(name) === 0) {
      from.off(name, listeners[i])
    }
  })
}

exports.listenerCount = function listenerCount(emitter, name) {
  return emitter.listenerCount(name)
}

exports.getMaxListeners = function getMaxListeners(emitter) {
  if (typeof emitter.getMaxListeners === 'function') {
    return emitter.getMaxListeners()
  }

  return exports.defaultMaxListeners
}

exports.setMaxListeners = function setMaxListeners(n, ...emitters) {
  if (emitters.length === 0) exports.defaultMaxListeners = n
  else {
    for (const emitter of emitters) {
      if (typeof emitter.setMaxListeners === 'function') {
        emitter.setMaxListeners(n)
      }
    }
  }
}
module.exports = class EventEmitterError extends Error {
  constructor(msg, code, fn = EventEmitterError, opts) {
    super(`${code}: ${msg}`, opts)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'EventEmitterError'
  }

  static OPERATION_ABORTED(cause, msg = 'Operation aborted') {
    return new EventEmitterError(msg, 'OPERATION_ABORTED', EventEmitterError.OPERATION_ABORTED, {
      cause
    })
  }

  static UNHANDLED_ERROR(cause, msg = 'Unhandled error') {
    return new EventEmitterError(msg, 'UNHANDLED_ERROR', EventEmitterError.UNHANDLED_ERROR, {
      cause
    })
  }
}
{
  "name": "bare-events",
  "version": "2.9.1",
  "description": "Event emitters for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    },
    "./web": {
      "types": "./web.d.ts",
      "default": "./web.js"
    },
    "./errors": "./lib/errors.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "global.js",
    "global.d.ts",
    "web.js",
    "web.d.ts",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:bare && npm run test:node",
    "test:bare": "brittle-bare --coverage test.js",
    "test:node": "brittle-node --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-events.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-events/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-events#readme",
  "devDependencies": {
    "bare-abort-controller": "^1.0.0",
    "brittle": "^3.3.2",
    "lunte": "^1.8.0",
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^2.0.0",
    "uncaughts": "^1.1.1"
  },
  "peerDependencies": {
    "bare-abort-controller": "*"
  },
  "peerDependenciesMeta": {
    "bare-abort-controller": {
      "optional": true
    }
  }
}
const b4a = require('b4a')

function byteLength (size) {
  return Math.ceil(size / 8)
}

function get (buffer, bit) {
  const n = buffer.BYTES_PER_ELEMENT * 8

  const offset = bit & (n - 1)
  const i = (bit - offset) / n

  return (buffer[i] & (1 << offset)) !== 0
}

function set (buffer, bit, value = true) {
  const n = buffer.BYTES_PER_ELEMENT * 8

  const offset = bit & (n - 1)
  const i = (bit - offset) / n
  const mask = 1 << offset

  if (value) {
    if ((buffer[i] & mask) !== 0) return false
  } else {
    if ((buffer[i] & mask) === 0) return false
  }

  buffer[i] ^= mask
  return true
}

function setRange (buffer, start, end, value = true) {
  const n = buffer.BYTES_PER_ELEMENT * 8

  let remaining = end - start
  let offset = start & (n - 1)
  let i = (start - offset) / n

  let changed = false

  while (remaining > 0) {
    const mask = (2 ** Math.min(remaining, n - offset) - 1) << offset

    if (value) {
      if ((buffer[i] & mask) !== mask) {
        buffer[i] |= mask
        changed = true
      }
    } else {
      if ((buffer[i] & mask) !== 0) {
        buffer[i] &= ~mask
        changed = true
      }
    }

    remaining -= n - offset
    offset = 0
    i++
  }

  return changed
}

function fill (buffer, value, start = 0, end = buffer.byteLength * 8) {
  const n = buffer.BYTES_PER_ELEMENT * 8
  let i, j

  {
    const offset = start & (n - 1)
    i = (start - offset) / n

    if (offset !== 0) {
      const mask = (2 ** Math.min(n - offset, end - start) - 1) << offset

      if (value) buffer[i] |= mask
      else buffer[i] &= ~mask

      i++
    }
  }

  {
    const offset = end & (n - 1)
    j = (end - offset) / n

    if (offset !== 0 && j >= i) {
      const mask = (2 ** offset) - 1

      if (value) buffer[j] |= mask
      else buffer[j] &= ~mask
    }
  }

  return buffer.fill(value ? (2 ** n) - 1 : 0, i, j)
}

function toggle (buffer, bit) {
  const n = buffer.BYTES_PER_ELEMENT * 8

  const offset = bit & (n - 1)
  const i = (bit - offset) / n
  const mask = 1 << offset

  buffer[i] ^= mask
  return (buffer[i] & mask) !== 0
}

function remove (buffer, bit) {
  return set(buffer, bit, false)
}

function removeRange (buffer, start, end) {
  return setRange(buffer, start, end, false)
}

function indexOf (buffer, value, position = 0) {
  for (let i = position, n = buffer.byteLength * 8; i < n; i++) {
    if (get(buffer, i) === value) return i
  }

  return -1
}

function lastIndexOf (buffer, value, position = buffer.byteLength * 8 - 1) {
  for (let i = position; i >= 0; i--) {
    if (get(buffer, i) === value) return i
  }

  return -1
}

function of (...bits) {
  return from(bits)
}

function from (bits) {
  const buffer = b4a.alloc(byteLength(bits.length))
  for (let i = 0; i < bits.length; i++) set(buffer, i, bits[i])
  return buffer
}

function * iterator (buffer) {
  for (let i = 0, n = buffer.byteLength * 8; i < n; i++) yield get(buffer, i)
}

module.exports = {
  byteLength,
  get,
  set,
  setRange,
  fill,
  toggle,
  remove,
  removeRange,
  indexOf,
  lastIndexOf,
  of,
  from,
  iterator
}
{
  "name": "bits-to-bytes",
  "version": "1.3.0",
  "description": "Functions for doing bit manipulation of typed arrays",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "scripts": {
    "test": "standard && brittle test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bits-to-bytes.git"
  },
  "author": "Kasper Isager Dalsgarð <kasper@funktionel.co>",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/holepunchto/bits-to-bytes/issues"
  },
  "homepage": "https://github.com/holepunchto/bits-to-bytes#readme",
  "dependencies": {
    "b4a": "^1.5.0"
  },
  "devDependencies": {
    "brittle": "^2.3.1",
    "standard": "^17.0.0"
  }
}
const c = require('compact-encoding')

module.exports = function bitfield(length) {
  if (length > 64) {
    throw new RangeError('Bitfield cannot be larger than 64 bits')
  }

  let byteLength
  if (length < 8) byteLength = 1
  else if (length <= 16) byteLength = 2
  else if (length <= 32) byteLength = 4
  else byteLength = 8

  return {
    preencode(state) {
      state.end++ // Length byte, used for data when byteLength === 1

      if (byteLength === 1);
      else if (byteLength === 2) c.uint16.preencode(state)
      else if (byteLength === 4) c.uint32.preencode(state)
      else c.uint64.preencode(state)
    },

    encode(state, b) {
      if (byteLength === 1);
      else if (byteLength === 2) c.uint8.encode(state, 0xfd)
      else if (byteLength === 4) c.uint8.encode(state, 0xfe)
      else c.uint8.encode(state, 0xff)

      if (typeof b === 'number') {
        if (byteLength === 1) c.uint8.encode(state, b)
        else if (byteLength === 2) c.uint16.encode(state, b)
        else if (byteLength === 4) c.uint32.encode(state, b)
        else c.uint64.encode(state, b)
      } else {
        state.buffer.set(b, state.start)

        if (b.byteLength < byteLength) {
          // Zero-fill the rest of the byte length.
          state.buffer.fill(
            0,
            state.start + b.byteLength,
            state.start + byteLength
          )
        }

        state.start += byteLength
      }
    },

    decode(state) {
      const byte = state.buffer[state.start]

      let byteLength
      if (byte <= 0xfc) byteLength = 1
      else if (byte === 0xfd) byteLength = 2
      else if (byte === 0xfe) byteLength = 4
      else byteLength = 8

      if (byteLength > 1) state.start++ // Skip the length byte

      if (state.end - state.start < byteLength) throw new Error('Out of bounds')

      const b = state.buffer.subarray(state.start, (state.start += byteLength))

      return length <= 8 ? b.subarray(0, 1) : b
    }
  }
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "compact-encoding-bitfield",
  "version": "1.1.0",
  "description": "Compact codec for bitfields",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node --coverage test.mjs",
    "test:bare": "brittle-bare --coverage test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/compact-encoding/compact-encoding-bitfield.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/compact-encoding/compact-encoding-bitfield/issues"
  },
  "homepage": "https://github.com/compact-encoding/compact-encoding-bitfield#readme",
  "imports": {
    "util": {
      "bare": "bare-utils",
      "default": "util"
    }
  },
  "dependencies": {
    "compact-encoding": "^3.0.0"
  },
  "devDependencies": {
    "bare-utils": "^1.5.1",
    "brittle": "^3.1.0",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  }
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return uint24.decode(state) + 0x1000000 * uint32.decode(state)
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return uint32.decode(state) + 0x100000000 * uint32.decode(state)
  }
})

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "2.19.2",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    if (b.byteLength === 0) return null
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
const EventEmitter = require('events')
const Protomux = require('protomux')
const c = require('compact-encoding')
const bitfield = require('compact-encoding-bitfield')
const bits = require('bits-to-bytes')
const safetyCatch = require('safety-catch')
const errors = require('./lib/errors')

module.exports = class ProtomuxRPC extends EventEmitter {
  constructor(stream, options = {}) {
    super()

    const {
      id,
      protocol = 'protomux-rpc',
      valueEncoding = c.optionalBuffer,
      handshake = null,
      handshakeEncoding
    } = options

    this._mux = Protomux.from(stream)
    this._defaultValueEncoding = valueEncoding

    this._id = 1
    this._ending = null
    this._destroyed = false
    this._error = null
    this._responding = 0

    this._requests = new Map()
    this._responders = new Map()

    this._channel = this._mux.createChannel({
      protocol,
      id,
      handshake: handshake === null ? null : handshakeEncoding || c.raw,
      onopen: this._onopen.bind(this),
      onclose: this._onclose.bind(this),
      ondestroy: this._ondestroy.bind(this)
    })

    if (this._channel === null) throw errors.DUPLICATE_CHANNEL()

    this._request = this._channel.addMessage({
      encoding: request,
      onmessage: this._onrequest.bind(this)
    })

    this._response = this._channel.addMessage({
      encoding: response,
      onmessage: this._onresponse.bind(this)
    })

    this._channel.open(handshake)
  }

  _onopen(handshake) {
    this.emit('open', handshake)
  }

  _onclose() {
    this._ending = Promise.resolve()

    const err = this._error || errors.CHANNEL_CLOSED()

    for (const request of this._requests.values()) {
      request.reject(err)
      if (request.timeout) clearTimeout(request.timeout)
    }

    this._requests.clear()
    this._responders.clear()

    this.emit('close')
  }

  _ondestroy() {
    this._destroyed = true
    this.emit('destroy')
  }

  async _onrequest({ id, method, value }) {
    let error = null

    const responder = this._responders.get(method)

    if (responder === undefined) error = errors.UNKNOWN_METHOD(`Unknown method '${method}'`)
    else {
      const {
        valueEncoding = this._defaultValueEncoding,
        requestEncoding = valueEncoding,
        responseEncoding = valueEncoding
      } = responder.options

      this._responding++

      try {
        if (requestEncoding) value = c.decode(requestEncoding, value)

        try {
          value = await responder.handler(value)
        } catch (err) {
          safetyCatch(err)

          error = errors.REQUEST_ERROR('Request failed', err)
        }
      } catch (err) {
        safetyCatch(err)

        error = errors.DECODE_ERROR('Could not decode request', err)
      }

      this._responding--

      if (!error && responseEncoding && id) {
        try {
          value = c.encode(responseEncoding, value)
        } catch (err) {
          safetyCatch(err)

          error = errors.ENCODE_ERROR('Could not encode response', err)
        }
      }
    }

    if (id) this._response.send({ id, error, value })

    this._endMaybe()
  }

  _onresponse({ id, error, value }) {
    if (id === 0) return

    const request = this._requests.get(id)

    if (request === undefined) return

    this._requests.delete(id)

    if (request.timeout) clearTimeout(request.timeout)

    if (error) request.reject(error)
    else {
      const { valueEncoding = this._defaultValueEncoding, responseEncoding = valueEncoding } =
        request.options

      try {
        if (responseEncoding) value = c.decode(responseEncoding, value)

        request.resolve(value)
      } catch (err) {
        safetyCatch(err)

        request.reject(errors.DECODE_ERROR('Could not decode response', err))
      }
    }

    this._endMaybe()
  }

  _ontimeout(id, timeout) {
    const request = this._requests.get(id)

    if (request === undefined) return

    this._requests.delete(id)

    request.reject(errors.TIMEOUT_EXCEEDED(`timeout of ${timeout}ms exceeded`))

    this._endMaybe()
  }

  get opened() {
    return this._channel.opened
  }

  get closed() {
    return this._channel.closed
  }

  get mux() {
    return this._mux
  }

  get stream() {
    return this._mux.stream
  }

  async fullyOpened() {
    await this._channel.fullyOpened()
  }

  respond(method, options, handler) {
    if (typeof options === 'function') {
      handler = options
      options = {}
    }

    this._responders.set(method, { options, handler })

    return this
  }

  unrespond(method) {
    this._responders.delete(method)

    return this
  }

  async request(method, value, options = {}) {
    if (this.closed) throw errors.CHANNEL_CLOSED()

    const {
      valueEncoding = this._defaultValueEncoding,
      requestEncoding = valueEncoding,
      timeout = -1
    } = options

    if (requestEncoding) value = c.encode(requestEncoding, value)

    const id = this._id++

    this._request.send({ id, method, value })

    return new Promise((resolve, reject) =>
      this._requests.set(id, {
        options,
        resolve,
        reject,
        timeout: timeout > 0 && setTimeout(this._ontimeout.bind(this, id, timeout), timeout)
      })
    )
  }

  event(method, value, options = {}) {
    if (this.closed) throw errors.CHANNEL_CLOSED()

    const { valueEncoding = this._defaultValueEncoding, requestEncoding = valueEncoding } = options

    if (requestEncoding) value = c.encode(requestEncoding, value)

    this._request.send({ id: 0, method, value })
  }

  cork() {
    this._channel.cork()
  }

  uncork() {
    this._channel.uncork()
  }

  async end() {
    if (this._ending) return this._ending

    this._ending = EventEmitter.once(this, 'close')
    this._endMaybe()

    return this._ending
  }

  _endMaybe() {
    if (this._ending && this._responding === 0 && this._requests.size === 0) {
      this._channel.close()
    }
  }

  destroy(err) {
    if (this._destroyed) return
    this._destroyed = true

    this._error = err || errors.CHANNEL_DESTROYED()
    this._channel.close()
  }
}

const request = {
  preencode(state, m) {
    c.uint.preencode(state, m.id)
    c.string.preencode(state, m.method)
    c.raw.preencode(state, m.value)
  },
  encode(state, m) {
    c.uint.encode(state, m.id)
    c.string.encode(state, m.method)
    c.raw.encode(state, m.value)
  },
  decode(state) {
    return {
      id: c.uint.decode(state),
      method: c.string.decode(state),
      value: c.raw.decode(state)
    }
  }
}

const flags = bitfield(1)

const response = {
  preencode(state, m) {
    flags.preencode(state)

    c.uint.preencode(state, m.id)

    if (m.error) {
      c.string.preencode(state, m.error.message.replace(m.error.code + ': ', ''))

      if (m.error.code) c.string.preencode(state, m.error.code)

      if (m.error.cause) {
        const cause = m.error.cause

        c.string.preencode(state, cause.message)
        c.string.preencode(state, cause.code || '')

        if (cause.context) c.string.preencode(state, cause.context)
      }
    } else {
      c.raw.preencode(state, m.value)
    }
  },
  encode(state, m) {
    flags.encode(
      state,
      bits.of(
        !!m.error,
        !!(m.error && m.error.code),
        !!(m.error && m.error.cause),
        !!(m.error && m.error.cause && m.error.cause.context)
      )
    )

    c.uint.encode(state, m.id)

    if (m.error) {
      c.string.encode(state, m.error.message.replace(m.error.code + ': ', ''))

      if (m.error.code) c.string.encode(state, m.error.code)

      if (m.error.cause) {
        const cause = m.error.cause

        c.string.encode(state, cause.message)
        c.string.encode(state, cause.code || '')

        if (cause.context) c.string.encode(state, cause.context)
      }
    } else {
      c.raw.encode(state, m.value)
    }
  },
  decode(state) {
    const [hasError, hasErrorCode, hasErrorCause, hasErrorContext] = bits.iterator(
      flags.decode(state)
    )

    const id = c.uint.decode(state)

    let error = null
    let value = null

    if (hasError) {
      const message = c.string.decode(state)
      const code = hasErrorCode ? c.string.decode(state) : null

      let cause
      if (hasErrorCause) {
        cause = new Error(c.string.decode(state))

        const code = c.string.decode(state)
        if (code) cause.code = code

        const context = hasErrorContext ? c.string.decode(state) : null
        if (context) cause.context = context
      }

      switch (code) {
        case 'UNKNOWN_METHOD':
          error = errors.UNKNOWN_METHOD(message)
          break
        case 'REQUEST_ERROR':
          error = errors.REQUEST_ERROR(message, cause)
          break
        case 'DECODE_ERROR':
          error = errors.DECODE_ERROR(message, cause)
          break
        case 'ENCODE_ERROR':
          error = errors.ENCODE_ERROR(message, cause)
          break
        default:
          error = new Error(message, { cause })
      }
    } else {
      value = c.raw.decode(state)
    }

    return {
      id,
      error,
      value
    }
  }
}
module.exports = class RPCError extends Error {
  constructor(msg, code, fn = RPCError, { cause } = {}) {
    super(`${code}: ${msg}`, { cause })
    this.code = code

    if (Error.captureStackTrace) Error.captureStackTrace(this, fn)
  }

  get name() {
    return 'RPCError'
  }

  static DUPLICATE_CHANNEL(msg = 'duplicate channel') {
    return new RPCError(msg, 'DUPLICATE_CHANNEL', RPCError.DUPLICATE_CHANNEL)
  }

  static CHANNEL_CLOSED(msg = 'channel closed') {
    return new RPCError(msg, 'CHANNEL_CLOSED', RPCError.CHANNEL_CLOSED)
  }

  static CHANNEL_DESTROYED(msg = 'channel destroyed') {
    return new RPCError(msg, 'CHANNEL_DESTROYED', RPCError.CHANNEL_DESTROYED)
  }

  static REQUEST_ERROR(msg, cause) {
    return new RPCError(msg, 'REQUEST_ERROR', RPCError.REQUEST_ERROR, { cause })
  }

  static TIMEOUT_EXCEEDED(msg) {
    return new RPCError(msg, 'TIMEOUT_EXCEEDED', RPCError.TIMEOUT_EXCEEDED)
  }

  static UNKNOWN_METHOD(msg) {
    return new RPCError(msg, 'UNKNOWN_METHOD', RPCError.UNKNOWN_METHOD)
  }

  static DECODE_ERROR(msg, cause) {
    return new RPCError(msg, 'DECODE_ERROR', RPCError.DECODE_ERROR, { cause })
  }

  static ENCODE_ERROR(msg, cause) {
    return new RPCError(msg, 'ENCODE_ERROR', RPCError.ENCODE_ERROR, { cause })
  }
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "protomux-rpc",
  "version": "1.10.0",
  "description": "RPC over Protomux channels",
  "main": "index.js",
  "files": [
    "index.js",
    "lib"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "exports": {
    "./package": "./package.json",
    ".": "./index.js",
    "./errors": "./lib/errors.js"
  },
  "scripts": {
    "test": "prettier . --check && brittle test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/protomux-rpc.git"
  },
  "author": "Kasper Isager Dalsgarð <kasper@funktionel.co>",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/protomux-rpc/issues"
  },
  "homepage": "https://github.com/holepunchto/protomux-rpc#readme",
  "dependencies": {
    "bits-to-bytes": "^1.0.0",
    "compact-encoding": "^3.0.0",
    "compact-encoding-bitfield": "^1.0.0",
    "protomux": "^3.7.0",
    "safety-catch": "^1.0.2"
  },
  "optionalDependencies": {
    "bare-events": "^2.2.0"
  },
  "devDependencies": {
    "brittle": "^3.3.0",
    "prettier": "^3.7.4",
    "prettier-config-holepunch": "^2.0.0",
    "streamx": "^2.12.4"
  }
}
const b4a = require('b4a')
const c = require('compact-encoding')
const queueTick = require('queue-tick')
const safetyCatch = require('safety-catch')
const unslab = require('unslab')

const MAX_BUFFERED = 32768
const MAX_BACKLOG = Infinity // TODO: impl "open" backpressure
const MAX_BATCH = 8 * 1024 * 1024

class Channel {
  constructor(
    mux,
    info,
    userData,
    protocol,
    aliases,
    id,
    handshake,
    messages,
    onopen,
    onclose,
    ondestroy,
    ondrain
  ) {
    this.userData = userData
    this.protocol = protocol
    this.aliases = aliases
    this.id = id
    this.handshake = null
    this.messages = []

    this.opened = false
    this.closed = false
    this.destroyed = false

    this.onopen = onopen
    this.onclose = onclose
    this.ondestroy = ondestroy
    this.ondrain = ondrain

    this._handshake = handshake
    this._mux = mux
    this._info = info
    this._localId = 0
    this._remoteId = 0
    this._active = 0
    this._extensions = null

    this._decBound = this._dec.bind(this)
    this._decAndDestroyBound = this._decAndDestroy.bind(this)

    this._openedPromise = null
    this._openedResolve = null

    this._destroyedPromise = null
    this._destroyedResolve = null

    for (const m of messages) this.addMessage(m)
  }

  get drained() {
    return this._mux.drained
  }

  fullyOpened() {
    if (this.opened) return Promise.resolve(true)
    if (this.closed) return Promise.resolve(false)
    if (this._openedPromise) return this._openedPromise

    this._openedPromise = new Promise((resolve) => {
      this._openedResolve = resolve
    })
    return this._openedPromise
  }

  fullyClosed() {
    if (this.destroyed) return Promise.resolve()
    if (this._destroyedPromise) return this._destroyedPromise

    this._destroyedPromise = new Promise((resolve) => {
      this._destroyedResolve = resolve
    })
    return this._destroyedPromise
  }

  open(handshake) {
    const id = this._mux._free.length > 0 ? this._mux._free.pop() : this._mux._local.push(null) - 1

    this._info.opened++
    this._info.lastChannel = this
    this._localId = id + 1
    this._mux._local[id] = this

    if (this._remoteId === 0) {
      this._info.outgoing.push(this._localId)
    }

    const state = { buffer: null, start: 2, end: 2 }

    c.uint.preencode(state, this._localId)
    c.string.preencode(state, this.protocol)
    c.optionalBuffer.preencode(state, this.id)
    if (this._handshake) this._handshake.preencode(state, handshake)

    state.buffer = this._mux._alloc(state.end)

    state.buffer[0] = 0
    state.buffer[1] = 1
    c.uint.encode(state, this._localId)
    c.string.encode(state, this.protocol)
    c.optionalBuffer.encode(state, this.id)
    if (this._handshake) this._handshake.encode(state, handshake)

    this._mux._write0(state.buffer)
  }

  _dec() {
    if (--this._active === 0 && this.closed === true) this._destroy()
  }

  _decAndDestroy(err) {
    this._dec()
    this._mux._safeDestroy(err)
  }

  _fullyOpenSoon() {
    this._mux._remote[this._remoteId - 1].session = this
    queueTick(this._fullyOpenOrDestroy.bind(this))
  }

  _fullyOpenOrDestroy() {
    try {
      this._fullyOpen()
    } catch (err) {
      this._mux._safeDestroyBound(err)
    }
  }

  _fullyOpen() {
    if (this.opened === true || this.closed === true) return

    const remote = this._mux._remote[this._remoteId - 1]

    this.handshake = this._handshake ? this._handshake.decode(remote.state) : null
    this._track(this.onopen(this.handshake, this))

    remote.session = this
    remote.state = null
    if (remote.pending !== null) this._drain(remote)
    if (this._mux._destroying === true) return

    this.opened = true
    this._resolveOpen(true)
  }

  _resolveOpen(opened) {
    if (this._openedResolve !== null) {
      this._openedResolve(opened)
      this._openedResolve = this._openedPromise = null
    }
  }

  _resolveDestroyed() {
    if (this._destroyedResolve !== null) {
      this._destroyedResolve()
      this._destroyedResolve = this._destroyedPromise = null
    }
  }

  _drain(remote) {
    for (let i = 0; i < remote.pending.length; i++) {
      const p = remote.pending[i]
      this._mux._buffered -= byteSize(p.state)
      this._recv(p.type, p.state)
      if (this._mux._destroying === true) return
    }

    remote.pending = null
    this._mux._resumeMaybe()
  }

  _track(p) {
    if (isPromise(p) === true) {
      this._active++
      return p.then(this._decBound, this._decAndDestroyBound)
    }

    return null
  }

  _close(isRemote) {
    if (this.closed === true) return
    this.closed = true

    this._info.opened--
    if (this._info.lastChannel === this) this._info.lastChannel = null

    if (this._remoteId > 0) {
      this._mux._remote[this._remoteId - 1] = null
      this._remoteId = 0
      // If remote has acked, we can reuse the local id now
      // otherwise, we need to wait for the "ack" to arrive
      this._mux._free.push(this._localId - 1)
    }

    this._mux._local[this._localId - 1] = null
    this._localId = 0

    this._mux._gc(this._info)
    this._track(this.onclose(isRemote, this))

    if (this._active === 0) this._destroy()

    this._resolveOpen(false)
  }

  _destroy() {
    if (this.destroyed === true) return
    this.destroyed = true
    this._track(this.ondestroy(this))
    this._resolveDestroyed()
  }

  _recv(type, state) {
    if (type < this.messages.length) {
      const m = this.messages[type]
      const p = m.recv(state, this)
      if (m.autoBatch === true) return p
    }
    return null
  }

  cork() {
    this._mux.cork()
  }

  uncork() {
    this._mux.uncork()
  }

  close() {
    if (this.closed === true) return

    const state = { buffer: null, start: 2, end: 2 }

    c.uint.preencode(state, this._localId)

    state.buffer = this._mux._alloc(state.end)

    state.buffer[0] = 0
    state.buffer[1] = 3
    c.uint.encode(state, this._localId)

    this._close(false)
    this._mux._write0(state.buffer)
  }

  addMessage(opts) {
    if (!opts) return this._skipMessage()

    const type = this.messages.length
    const autoBatch = opts.autoBatch !== false
    const encoding = opts.encoding || c.raw
    const onmessage = opts.onmessage || noop

    const s = this
    const typeLen = encodingLength(c.uint, type)

    const m = {
      type,
      autoBatch,
      encoding,
      onmessage,
      recv(state, session) {
        return session._track(m.onmessage(encoding.decode(state), session))
      },
      send(m, session = s) {
        if (session.closed === true) return false

        const mux = session._mux
        const state = { buffer: null, start: 0, end: typeLen }

        if (mux._batch !== null) {
          encoding.preencode(state, m)
          state.buffer = mux._alloc(state.end)

          c.uint.encode(state, type)
          encoding.encode(state, m)

          mux._pushBatch(session._localId, state.buffer)
          return true
        }

        c.uint.preencode(state, session._localId)
        encoding.preencode(state, m)

        state.buffer = mux._alloc(state.end)

        c.uint.encode(state, session._localId)
        c.uint.encode(state, type)
        encoding.encode(state, m)

        mux.drained = mux.stream.write(state.buffer)

        return mux.drained
      }
    }

    this.messages.push(m)

    return m
  }

  _skipMessage() {
    const type = this.messages.length
    const m = {
      type,
      encoding: c.raw,
      onmessage: noop,
      recv(state, session) {},
      send(m, session) {}
    }

    this.messages.push(m)
    return m
  }
}

module.exports = class Protomux {
  constructor(stream, { alloc } = {}) {
    if (stream.userData === null) stream.userData = this

    this.isProtomux = true
    this.stream = stream
    this.corked = 0
    this.drained = true

    this._alloc =
      alloc || (typeof stream.alloc === 'function' ? stream.alloc.bind(stream) : b4a.allocUnsafe)
    this._safeDestroyBound = this._safeDestroy.bind(this)
    this._uncorkBound = this.uncork.bind(this)

    this._remoteBacklog = 0
    this._buffered = 0
    this._paused = false
    this._remote = []
    this._local = []
    this._free = []
    this._batch = null
    this._batchState = null

    this._infos = new Map()
    this._notify = new Map()
    // stream.destroyed flips asynchronously on streamx-based transports.
    this._destroying = false

    this.stream.on('data', this._ondata.bind(this))
    this.stream.on('drain', this._ondrain.bind(this))
    this.stream.on('end', this._onend.bind(this))
    this.stream.on('error', noop) // we handle this in "close"
    this.stream.on('close', this._shutdown.bind(this))
  }

  static from(stream, opts) {
    if (stream.userData && stream.userData.isProtomux) return stream.userData
    if (stream.isProtomux) return stream
    return new this(stream, opts)
  }

  static isProtomux(mux) {
    return typeof mux === 'object' && mux.isProtomux === true
  }

  *[Symbol.iterator]() {
    for (const session of this._local) {
      if (session !== null) yield session
    }
  }

  isIdle() {
    return this._local.length === this._free.length
  }

  cork() {
    if (++this.corked === 1) {
      this._batch = []
      this._batchState = { buffer: null, start: 0, end: 1 }
    }
  }

  uncork() {
    if (--this.corked === 0) {
      this._sendBatch(this._batch, this._batchState)
      this._batch = null
      this._batchState = null
    }
  }

  getLastChannel({ protocol, id = null }) {
    const key = toKey(protocol, id)
    const info = this._infos.get(key)
    if (info) return info.lastChannel
    return null
  }

  pair({ protocol, id = null }, notify) {
    this._notify.set(toKey(protocol, id), notify)
  }

  unpair({ protocol, id = null }) {
    this._notify.delete(toKey(protocol, id))
  }

  opened({ protocol, id = null }) {
    const key = toKey(protocol, id)
    const info = this._infos.get(key)
    return info ? info.opened > 0 : false
  }

  createChannel({
    userData = null,
    protocol,
    aliases = [],
    id = null,
    unique = true,
    handshake = null,
    messages = [],
    onopen = noop,
    onclose = noop,
    ondestroy = noop,
    ondrain = noop
  }) {
    if (this.stream.destroyed) return null

    const info = this._get(protocol, id, aliases)
    if (unique && info.opened > 0) return null

    if (info.incoming.length === 0) {
      return new Channel(
        this,
        info,
        userData,
        protocol,
        aliases,
        id,
        handshake,
        messages,
        onopen,
        onclose,
        ondestroy,
        ondrain
      )
    }

    this._remoteBacklog--

    const remoteId = info.incoming.shift()
    const r = this._remote[remoteId - 1]
    if (r === null) return null

    const session = new Channel(
      this,
      info,
      userData,
      protocol,
      aliases,
      id,
      handshake,
      messages,
      onopen,
      onclose,
      ondestroy,
      ondrain
    )

    session._remoteId = remoteId
    session._fullyOpenSoon()

    return session
  }

  _pushBatch(localId, buffer) {
    if (this._batchState.end >= MAX_BATCH) {
      this._sendBatch(this._batch, this._batchState)
      this._batch = []
      this._batchState = { buffer: null, start: 0, end: 1 }
    }

    if (this._batch.length === 0 || this._batch[this._batch.length - 1].localId !== localId) {
      this._batchState.end++
      c.uint.preencode(this._batchState, localId)
    }
    c.buffer.preencode(this._batchState, buffer)
    this._batch.push({ localId, buffer })
  }

  _sendBatch(batch, state) {
    if (batch.length === 0) return

    let prev = batch[0].localId

    state.buffer = this._alloc(state.end)
    state.buffer[state.start++] = 0
    state.buffer[state.start++] = 0

    c.uint.encode(state, prev)

    for (let i = 0; i < batch.length; i++) {
      const b = batch[i]
      if (prev !== b.localId) {
        state.buffer[state.start++] = 0
        c.uint.encode(state, (prev = b.localId))
      }
      c.buffer.encode(state, b.buffer)
    }

    this.drained = this.stream.write(state.buffer)
  }

  _get(protocol, id, aliases = []) {
    const key = toKey(protocol, id)

    let info = this._infos.get(key)
    if (info) return info

    info = {
      key,
      protocol,
      aliases: [],
      id,
      pairing: 0,
      opened: 0,
      incoming: [],
      outgoing: [],
      lastChannel: null
    }
    this._infos.set(key, info)

    for (const alias of aliases) {
      const key = toKey(alias, id)
      info.aliases.push(key)

      this._infos.set(key, info)
    }

    return info
  }

  _gc(info) {
    if (info.opened === 0 && info.outgoing.length === 0 && info.incoming.length === 0) {
      this._infos.delete(info.key)

      for (const alias of info.aliases) this._infos.delete(alias)
    }
  }

  _ondata(buffer) {
    if (buffer.byteLength === 0) return // ignore empty frames...
    try {
      const state = { buffer, start: 0, end: buffer.byteLength }
      this._decode(c.uint.decode(state), state)
    } catch (err) {
      this._safeDestroy(err)
    }
  }

  _ondrain() {
    this.drained = true

    for (const s of this._local) {
      if (s !== null) s._track(s.ondrain(s))
    }
  }

  _onend() {
    // TODO: support half open mode for the users who wants that here
    this.stream.end()
  }

  _decode(remoteId, state) {
    const type = c.uint.decode(state)

    if (remoteId === 0) {
      return this._oncontrolsession(type, state)
    }

    const r = remoteId <= this._remote.length ? this._remote[remoteId - 1] : null

    // if the channel is closed ignore - could just be a pipeline message...
    if (r === null) return null

    if (r.pending !== null) {
      this._bufferMessage(r, type, state)
      return null
    }

    return r.session._recv(type, state)
  }

  _oncontrolsession(type, state) {
    switch (type) {
      case 0:
        this._onbatch(state)
        break

      case 1:
        // return the promise back up as this has sideeffects so we can batch reply
        return this._onopensession(state)

      case 2:
        this._onrejectsession(state)
        break

      case 3:
        this._onclosesession(state)
        break
    }

    return null
  }

  _bufferMessage(r, type, { buffer, start, end }) {
    const state = { buffer, start, end } // copy
    r.pending.push({ type, state })
    this._buffered += byteSize(state)
    this._pauseMaybe()
  }

  _pauseMaybe() {
    if (this._paused === true || this._buffered <= MAX_BUFFERED) return
    this._paused = true
    this.stream.pause()
  }

  _resumeMaybe() {
    if (this._paused === false || this._buffered > MAX_BUFFERED) return
    this._paused = false
    this.stream.resume()
  }

  _onbatch(state) {
    const end = state.end
    let remoteId = c.uint.decode(state)

    let waiting = null

    while (state.end > state.start) {
      const len = c.uint.decode(state)
      if (len === 0) {
        remoteId = c.uint.decode(state)
        continue
      }
      state.end = state.start + len
      // if batch contains more than one message, cork it so we reply back with a batch
      if (end !== state.end && waiting === null) {
        waiting = []
        this.cork()
      }
      const p = this._decode(remoteId, state)
      if (waiting !== null && p !== null) waiting.push(p)
      state.start = state.end
      state.end = end
    }

    if (waiting !== null) {
      // the waiting promises are not allowed to throw but we destroy the stream in case we are wrong
      Promise.all(waiting).then(this._uncorkBound, this._safeDestroyBound)
    }
  }

  _onopensession(state) {
    const remoteId = c.uint.decode(state)
    const protocol = c.string.decode(state)
    const id = unslab(c.optionalBuffer.decode(state))

    // remote tried to open the control session - auto reject for now
    // as we can use as an explicit control protocol declaration if we need to
    if (remoteId === 0) {
      this._rejectSession(0)
      return null
    }

    const rid = remoteId - 1
    const info = this._get(protocol, id)

    // allow the remote to grow the ids by one
    if (this._remote.length === rid) {
      this._remote.push(null)
    }

    if (rid >= this._remote.length || this._remote[rid] !== null) {
      throw new Error('Invalid open message')
    }

    if (info.outgoing.length > 0) {
      const localId = info.outgoing.shift()
      const session = this._local[localId - 1]

      if (session === null) {
        // we already closed the channel - ignore
        this._free.push(localId - 1)
        return null
      }

      this._remote[rid] = { state, pending: null, session: null }

      session._remoteId = remoteId
      session._fullyOpen()
      return null
    }

    const copyState = { buffer: state.buffer, start: state.start, end: state.end }
    this._remote[rid] = { state: copyState, pending: [], session: null }

    if (++this._remoteBacklog > MAX_BACKLOG) {
      throw new Error('Remote exceeded backlog')
    }

    info.pairing++
    info.incoming.push(remoteId)

    return this._requestSession(protocol, id, info).catch(this._safeDestroyBound)
  }

  _onrejectsession(state) {
    const localId = c.uint.decode(state)

    // TODO: can be done smarter...
    for (const info of this._infos.values()) {
      const i = info.outgoing.indexOf(localId)
      if (i === -1) continue

      info.outgoing.splice(i, 1)

      const session = this._local[localId - 1]

      this._free.push(localId - 1)
      if (session !== null) session._close(true)

      this._gc(info)
      return
    }

    throw new Error('Invalid reject message')
  }

  _onclosesession(state) {
    const remoteId = c.uint.decode(state)

    if (remoteId === 0) return // ignore

    const rid = remoteId - 1
    const r = rid < this._remote.length ? this._remote[rid] : null

    if (r === null) return

    if (r.session !== null) r.session._close(true)
  }

  async _requestSession(protocol, id, info) {
    const notify = this._notify.get(toKey(protocol, id)) || this._notify.get(toKey(protocol, null))

    if (notify) await notify(id)

    if (--info.pairing > 0) return

    while (info.incoming.length > 0) {
      this._rejectSession(info, info.incoming.shift())
    }

    this._gc(info)
  }

  _rejectSession(info, remoteId) {
    if (remoteId > 0) {
      const r = this._remote[remoteId - 1]

      if (r.pending !== null) {
        for (let i = 0; i < r.pending.length; i++) {
          this._buffered -= byteSize(r.pending[i].state)
        }
      }

      this._remote[remoteId - 1] = null
      this._resumeMaybe()
    }

    const state = { buffer: null, start: 2, end: 2 }

    c.uint.preencode(state, remoteId)

    state.buffer = this._alloc(state.end)

    state.buffer[0] = 0
    state.buffer[1] = 2
    c.uint.encode(state, remoteId)

    this._write0(state.buffer)
  }

  _write0(buffer) {
    if (this._batch !== null) {
      this._pushBatch(0, buffer.subarray(1))
      return
    }

    this.drained = this.stream.write(buffer)
  }

  destroy(err) {
    this._destroying = true
    this.stream.destroy(err)
  }

  _safeDestroy(err) {
    safetyCatch(err)
    this._destroying = true
    this.stream.destroy(err)
  }

  _shutdown() {
    this._destroying = true
    for (const s of this._local) {
      if (s !== null) s._close(true)
    }
  }
}

function noop() {}

function toKey(protocol, id) {
  return protocol + '##' + (id ? b4a.toString(id, 'hex') : '')
}

function byteSize(state) {
  return 512 + (state.end - state.start)
}

function isPromise(p) {
  return !!(p && typeof p.then === 'function')
}

function encodingLength(enc, val) {
  const state = { buffer: null, start: 0, end: 0 }
  enc.preencode(state, val)
  return state.end
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "protomux",
  "version": "3.11.0",
  "description": "Multiplex multiple message oriented protocols over a stream",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.3.1",
    "compact-encoding": "^3.0.0",
    "queue-tick": "^1.0.0",
    "safety-catch": "^1.0.1",
    "unslab": "^1.3.0"
  },
  "devDependencies": {
    "@hyperswarm/secret-stream": "^6.0.0",
    "brittle": "^3.0.0",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/protomux.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/protomux/issues"
  },
  "homepage": "https://github.com/holepunchto/protomux"
}
{
  "name": "queue-tick",
  "version": "1.0.1",
  "description": "Next tick shim that prefers process.nextTick over queueMicrotask for compat",
  "main": "./process-next-tick.js",
  "browser": "./queue-microtask.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^16.0.3",
    "tape": "^5.3.1"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/queue-tick.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/queue-tick/issues"
  },
  "homepage": "https://github.com/mafintosh/queue-tick"
}
module.exports = (typeof process !== 'undefined' && typeof process.nextTick === 'function')
  ? process.nextTick.bind(process)
  : require('./queue-microtask')
module.exports = typeof queueMicrotask === 'function' ? queueMicrotask : (fn) => Promise.resolve().then(fn)
module.exports = safetyCatch

function isActuallyUncaught (err) {
  if (!err) return false
  return err instanceof TypeError ||
    err instanceof SyntaxError ||
    err instanceof ReferenceError ||
    err instanceof EvalError ||
    err instanceof RangeError ||
    err instanceof URIError ||
    err.code === 'ERR_ASSERTION' ||
    err.name === 'AssertionError'
}

function throwErrorNT (err) {
  queueMicrotask(() => { throw err })
}

function safetyCatch (err) {
  if (isActuallyUncaught(err)) {
    throwErrorNT(err)
    throw err
  }
}
{
  "name": "safety-catch",
  "version": "1.0.3",
  "description": "Small module that makes sure your catch, caught an actual error and not a programming mistake or assertion",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {},
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/safety-catch.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/safety-catch/issues"
  },
  "homepage": "https://github.com/mafintosh/safety-catch"
}
const b4a = require('b4a')

unslab.all = all
unslab.is = is

module.exports = unslab

function unslab (buf) {
  if (buf === null || buf.buffer.byteLength === buf.byteLength) return buf
  const copy = b4a.allocUnsafeSlow(buf.byteLength)
  copy.set(buf, 0)
  return copy
}

function is (buf) {
  return buf.buffer.byteLength !== buf.byteLength
}

function all (list) {
  let size = 0
  for (let i = 0; i < list.length; i++) {
    const buf = list[i]
    size += buf === null || buf.buffer.byteLength === buf.byteLength ? 0 : buf.byteLength
  }

  const copy = b4a.allocUnsafeSlow(size)
  const result = new Array(list.length)

  let offset = 0
  for (let i = 0; i < list.length; i++) {
    let buf = list[i]

    if (buf !== null && buf.buffer.byteLength !== buf.byteLength) {
      copy.set(buf, offset)
      buf = copy.subarray(offset, offset += buf.byteLength)
    }

    result[i] = buf
  }

  return result
}
{
  "name": "unslab",
  "version": "1.3.0",
  "description": "Unslab some slab'ed buffers",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.6.6"
  },
  "devDependencies": {
    "brittle": "^3.5.2",
    "standard": "^17.1.0"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/unslab.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/unslab/issues"
  },
  "homepage": "https://github.com/holepunchto/unslab"
}
{
  "name": "atproto-did-peer",
  "version": "0.2.12",
  "description": "Keyless, direction-free P2P reader/seeder for an atproto DID's repo+firehose Hypercores: announce-push discovery + event-driven head reconciliation + a keyless read surface. The shared primitive beneath atproto-bridge, atproto-relay and favela (extracted from atproto-bridge did-peer.js).",
  "type": "module",
  "main": "index.js",
  "exports": {
    ".": "./index.js"
  },
  "scripts": {
    "test": "node test/commitops.test.mjs && node test/router.test.mjs && node test/co-owned.test.mjs && node test/coowner-set.test.mjs && node test/evict.test.mjs && node test/fork.test.mjs && node test/rpc-candidates.test.mjs && node test/no-repo.test.mjs && node test/get-repo-since.test.mjs && node test/rpc-timeout.test.mjs",
    "test:live": "node test/read-live.mjs"
  },
  "dependencies": {
    "atproto-repo": "file:../atproto-repo",
    "atproto-store": "file:../atproto-store",
    "b4a": "^1.8.1",
    "compact-encoding": "^2.19.0",
    "protomux": "^3.11.0",
    "protomux-rpc": "^1.10.0"
  },
  "devDependencies": {
    "@hyperswarm/testnet": "^3.1.4",
    "atproto-identity": "file:../atproto-identity",
    "corestore": "^7.4.0",
    "hyperswarm": "^4.11.0"
  }
}
// Seed-anchored atproto identity — the secp256k1 / did:plc half.
//
// One BIP39 mnemonic anchors both worlds:
//   mnemonic -> Ed25519  (keet-identity-key)  -> Hypercore log signing   [NEXT increment]
//   mnemonic -> secp256k1 (this module)        -> did:plc + atproto commits
//
// This module owns the atproto side: deterministic secp256k1 derivation, did:key
// encoding, and building/signing a did:plc genesis operation — entirely offline.
// It never submits to the PLC directory (the op-log is permanent; don't churn).

import { mnemonicToSeedSync } from '@scure/bip39'
import { HDKey } from '@scure/bip32'
import { secp256k1 } from '@noble/curves/secp256k1'
import { sha256 } from '@noble/hashes/sha2'
import { base64url } from 'multiformats/bases/base64'
import { encodeDidKey, CURVE_SECP256K1 } from './did-key.js'
import { encodeOp, unsignedOp, didForCreateOp, opCid } from './did-plc.js'

// Our fixed derivation path. No BIP44 coin type is registered for atproto, so this
// is a project convention — the *mnemonic* is the recovery anchor; the path is fixed
// by this constant so the same phrase always yields the same atproto key.
export const ATPROTO_SIGNING_PATH = "m/44'/0'/0'/0/0"
// A SEPARATE derivation for the swarm's ROOT recovery/rotation key — held only by the root, NEVER
// distributed to devices. Distinct account index ('1') so a device that holds the signing key
// cannot derive this. See atproto-base-REVOCATION.md §4-5.
export const ATPROTO_RECOVERY_PATH = "m/44'/0'/1'/0/0"

// raw base64url (no multibase prefix, no padding) — atproto's sig encoding.
function sigToBase64url (bytes) {
  return base64url.encode(bytes).slice(1) // drop multibase 'u'
}
export function base64urlToBytes (str) {
  return base64url.decode('u' + str)
}

// mnemonic -> deterministic secp256k1 keypair for atproto signing.
export function deriveAtprotoKey (mnemonic, path = ATPROTO_SIGNING_PATH) {
  const seed = mnemonicToSeedSync(mnemonic)
  const node = HDKey.fromMasterSeed(seed).derive(path)
  if (!node.privateKey) throw new Error('derivation produced no private key')
  return keyFromPrivate(node.privateKey)
}

// raw 32-byte secp256k1 private key -> { privateKey, publicKey, didKey }.
export function keyFromPrivate (privateKey) {
  const publicKey = secp256k1.getPublicKey(privateKey, true) // 33-byte compressed
  return { privateKey, publicKey, didKey: encodeDidKey(CURVE_SECP256K1, publicKey) }
}

// A fresh random atproto signing keypair (server-minted accounts with no seed anchor).
export function generateAtprotoKey () {
  return keyFromPrivate(secp256k1.utils.randomPrivateKey())
}

// ECDSA sign the sha256 of DAG-CBOR(unsignedOp), low-S, compact -> base64url.
export function signOp (unsigned, privateKey) {
  const hash = sha256(encodeOp(unsigned))
  const sig = secp256k1.sign(hash, privateKey, { lowS: true })
  return sigToBase64url(sig.toCompactRawBytes())
}

// verify a signature string against an unsigned op + did:key-encoded pubkey bytes.
export function verifyOp (unsigned, sigB64url, publicKey) {
  const hash = sha256(encodeOp(unsigned))
  return secp256k1.verify(base64urlToBytes(sigB64url), hash, publicKey, { lowS: true })
}

// Build an UNSIGNED did:plc genesis op. rotationKey defaults to the signing key
// (single-key setup); pass a distinct rotation didKey for key-separation.
// A HANDLE AND A PDS ARE OPTIONAL, and omitting both is the P2P-only genesis (hyper-social #54 §8):
// an identity that names nobody's infrastructure. Creating a did:plc and joining someone's service are
// different decisions, and requiring both at once is what made minting undecidable — you could not have
// an identity without first answering "whose server are you on?". Accepting an invite from
// atproto-bridge or ap-bridge is a LATER PLC UPDATE op that adds the domain handle and the endpoint, so
// creation stays free and joining stays reversible.
//
// ⛔ THEY USED TO BE UNCONDITIONAL, and the two failure modes were not equally survivable. A missing
// pdsUrl put the VALUE `undefined` in the op and dag-cbor refused to encode it — loud, and safe. A
// missing handle produced the STRING 'at://undefined', which encodes perfectly and would have been
// appended to a global, permanent, public log. The silent one is the one this guards.
//
// The directory requires neither: checkGenesisOp (lib/plc-directory.js) asks only for a plc_operation
// with prev:null, rotationKeys, a verificationMethods.atproto and a self-signature.
export function buildGenesisOp ({ signingDidKey, rotationDidKeys, handle = null, pdsUrl = null, labelDidKey = null, feedGenEndpoint = null, labelerEndpoint = null }) {
  const verificationMethods = { atproto: signingDidKey }
  const services = {}
  if (pdsUrl) services.atproto_pds = { type: 'AtprotoPersonalDataServer', endpoint: pdsUrl }
  // Lens-export service entries (a self-custody feed-generator + labeler — e.g. a favela community DID).
  // The PLC op's `services`/`verificationMethods` KEYS become DID-doc fragments: services.bsky_fg → the
  // #bsky_fg service, verificationMethods.atproto_label → the #atproto_label VM. Endpoints point at where
  // the getFeedSkeleton / queryLabels+subscribeLabels XRPC is served (the membrane). #atproto_label
  // defaults to the #atproto signing key (labels co-signed by the shared key) unless a distinct key is given.
  if (feedGenEndpoint) services.bsky_fg = { type: 'BskyFeedGenerator', endpoint: feedGenEndpoint }
  if (labelerEndpoint) {
    services.atproto_labeler = { type: 'AtprotoLabeler', endpoint: labelerEndpoint }
    verificationMethods.atproto_label = labelDidKey || signingDidKey
  } else if (labelDidKey) {
    verificationMethods.atproto_label = labelDidKey
  }
  return {
    type: 'plc_operation',
    rotationKeys: rotationDidKeys && rotationDidKeys.length ? rotationDidKeys : [signingDidKey],
    verificationMethods,
    // Empty, not absent: an identity with no handle claims no alias. The domain handle arrives with the
    // invite, as an update op — it is not a thing you are born with.
    alsoKnownAs: handle ? [`at://${handle}`] : [],
    services,
    prev: null
  }
}

// key { privateKey, publicKey, didKey } -> signed genesis op + did:plc.
export function identityFromKey (key, { handle, pdsUrl }) {
  const unsigned = buildGenesisOp({ signingDidKey: key.didKey, handle, pdsUrl })
  const sig = signOp(unsigned, key.privateKey)
  const signedOp = { ...unsigned, sig }
  const did = didForCreateOp(signedOp)
  return { did, didKey: key.didKey, publicKey: key.publicKey, privateKey: key.privateKey, signedOp }
}

// Full offline flow: mnemonic -> signed genesis op + did:plc.
export function createAtprotoIdentity (mnemonic, { handle, pdsUrl, path = ATPROTO_SIGNING_PATH }) {
  return identityFromKey(deriveAtprotoKey(mnemonic, path), { handle, pdsUrl })
}

// Same, but from a raw private key (server-minted / bring-your-own accounts).
export function createAtprotoIdentityFromKey (privateKey, { handle, pdsUrl }) {
  return identityFromKey(keyFromPrivate(privateKey), { handle, pdsUrl })
}

// The atproto-base SWARM identity: ONE did:plc whose #atproto signing key is SHARED among N
// attested devices, but whose ROTATION authority is a SEPARATE root recovery key that is NEVER
// distributed to devices. Devices sign commits (verificationMethods.atproto = shared signing key)
// but have ZERO PLC authority — only the root (recovery key) can rotate/revoke. Revocation = the
// root rotates the shared signing key via a PLC update; a device holds only the old signing key,
// not the root, so it cannot self-recover. Contrast createAtprotoIdentity (rotationKeys =
// [signingKey], no separation — a device could rotate the DID). The genesis is signed by the
// recovery key (a genesis must be signed by one of its own rotationKeys). See
// atproto-base-REVOCATION.md §5. Returns { did, signedOp, signingKey, recoveryKey } — `signingKey`
// is distributed to attested devices; `recoveryKey` STAYS WITH THE ROOT.
export function createSwarmIdentity (mnemonic, { handle, pdsUrl, feedGenEndpoint = null, labelerEndpoint = null, labelDidKey = null } = {}) {
  const signingKey = deriveAtprotoKey(mnemonic, ATPROTO_SIGNING_PATH)
  const recoveryKey = deriveAtprotoKey(mnemonic, ATPROTO_RECOVERY_PATH)
  const unsigned = buildGenesisOp({ signingDidKey: signingKey.didKey, rotationDidKeys: [recoveryKey.didKey], handle, pdsUrl, feedGenEndpoint, labelerEndpoint, labelDidKey })
  const sig = signOp(unsigned, recoveryKey.privateKey)
  const signedOp = { ...unsigned, sig }
  const did = didForCreateOp(signedOp)
  return { did, signedOp, signingKey, recoveryKey, didKey: signingKey.didKey }
}

// ── Post-genesis PLC operations (device attestation = rotation, NOT genesis) ──
//
// A did:plc is fixed at genesis; you evolve it with UPDATE operations that chain via
// `prev` (the CID of the previous signed op) and are signed by one of the CURRENT
// rotationKeys. This is how a device signing key is attested AFTER genesis without
// changing the DID — the atproto-correct model (see DESIGN.md §4a). The genesis stays
// deterministic (root-derived signing key → reproducible DID); the device key arrives
// as a rotation of verificationMethods.atproto.

// Build an UNSIGNED update op. `prevSignedOp` is the previous op in the log (its CID
// becomes `prev`). The remaining fields are the FULL new operation state — carry
// forward what you're not changing (a PLC op replaces the whole doc state, it is not a
// patch). This module never submits to the PLC directory; it only builds/signs offline.
export function buildUpdateOp ({ prevSignedOp, rotationDidKeys, verificationMethods, alsoKnownAs, services }) {
  if (!prevSignedOp) throw new Error('buildUpdateOp: prevSignedOp required')
  return {
    type: 'plc_operation',
    rotationKeys: rotationDidKeys,
    verificationMethods,
    alsoKnownAs,
    services,
    prev: opCid(prevSignedOp)
  }
}

// Attest a device by ROTATING verificationMethods.atproto to the device's did:key,
// carrying every other field forward from `prevSignedOp`, signed by a rotation key
// (the root — `signerPrivateKey` must correspond to one of prevSignedOp.rotationKeys).
// The DID is UNCHANGED. Returns the signed update op ready to submit to the PLC log.
export function rotateVerificationMethod ({ prevSignedOp, newAtprotoDidKey, signerPrivateKey }) {
  const unsigned = buildUpdateOp({
    prevSignedOp,
    rotationDidKeys: prevSignedOp.rotationKeys,
    verificationMethods: { ...prevSignedOp.verificationMethods, atproto: newAtprotoDidKey },
    alsoKnownAs: prevSignedOp.alsoKnownAs,
    services: prevSignedOp.services
  })
  const sig = signOp(unsigned, signerPrivateKey)
  return { ...unsigned, sig }
}

// Full self-custody onboarding — the atproto-correct device-attested model. A DETERMINISTIC,
// root-derived genesis pins the DID (reproducible from rootMnemonic+handle+pdsUrl), then a
// POST-genesis rotation attests a per-device signing key. The DID is f(root,handle,pds) — NOT
// f(device key) — so it reproduces across runs and can span multiple devices. The root key
// signs the genesis + the rotation and is then discarded (the user keeps it via hyperident);
// the peer holds ONLY the device key. This supersedes buildAttestedIdentity, which baked the
// device key INTO the genesis (making did:plc = f(device key) — non-reproducible, single-device).
// Pass a device secp256k1 privateKey to pin it; otherwise a fresh device key is minted.
export function selfCustodyIdentity ({ rootMnemonic, rootKey, handle, pdsUrl, deviceKey, path = ATPROTO_SIGNING_PATH }) {
  const genesis = rootKey
    ? createAtprotoIdentityFromKey(rootKey, { handle, pdsUrl })
    : createAtprotoIdentity(rootMnemonic, { handle, pdsUrl, path })
  const device = deviceKey ? keyFromPrivate(deviceKey) : generateAtprotoKey()
  const rotationOp = rotateVerificationMethod({
    prevSignedOp: genesis.signedOp,
    newAtprotoDidKey: device.didKey,
    signerPrivateKey: genesis.privateKey // the root — a rotationKey of the genesis
  })
  return {
    did: genesis.did, // = f(root, handle, pds) — reproducible, device-independent
    genesisOp: genesis.signedOp, // vm = root-derived key, signed by root, prev:null
    rotationOp, // vm → device key, signed by root, prev = cid(genesis)
    deviceKey: device, // { privateKey, publicKey, didKey } — the peer holds THIS
    rootDidKey: genesis.didKey, // the root (rotation / recovery) key's did:key
    rootPublicKey: genesis.publicKey,
    rotationKeys: genesis.signedOp.rotationKeys
  }
}

export { unsignedOp, didForCreateOp, opCid }
// PDS auth primitives — password hashing + HS256 session tokens. Pure and bare-safe:
// scrypt/hmac/sha256 are @noble/hashes (pure JS, no crypto global), randomness comes from
// hypercore-crypto (bare-native via sodium). No I/O — the caller owns storage + clock.
//
// This is the ONLY auth the bsky-facing HTTP membrane needs: a client calls createSession
// with {identifier,password}, gets an opaque accessJwt, and presents it as `Authorization:
// Bearer` on writes. The PDS verifies the HMAC + expiry and reads `sub` (the repo DID).
// Standard atproto shape, so any @atproto/api client works unchanged.

import { scrypt } from '@noble/hashes/scrypt'
import { hmac } from '@noble/hashes/hmac'
import { sha256 } from '@noble/hashes/sha2'
import { secp256k1 } from '@noble/curves/secp256k1'
import { randomBytes } from 'hypercore-crypto'

const enc = new TextEncoder()
const dec = new TextDecoder()

// scrypt work factor — ~16 MiB, interactive-login appropriate. Embedded in the stored
// string so the params can evolve without breaking existing hashes.
const SCRYPT = { N: 16384, r: 8, p: 1, dkLen: 32 }

// ---- base64url (JWT segments) — base64 is universally supported (node + bare-buffer);
// the +/ -> -_ transform makes it url-safe without needing 'base64url' encoder support. ----
export function b64url (bytes) {
  return Buffer.from(bytes).toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
}
export function b64urlToBytes (str) {
  let s = str.replace(/-/g, '+').replace(/_/g, '/')
  while (s.length % 4) s += '='
  return new Uint8Array(Buffer.from(s, 'base64'))
}

function hex (bytes) { return Buffer.from(bytes).toString('hex') }
function fromHex (str) { return new Uint8Array(Buffer.from(str, 'hex')) }

// Constant-time equality — never leak match progress via early return.
export function timingSafeEqual (a, b) {
  if (a.length !== b.length) return false
  let d = 0
  for (let i = 0; i < a.length; i++) d |= a[i] ^ b[i]
  return d === 0
}

// ---- passwords ----
// Stored form: `scrypt$<N>$<r>$<p>$<saltHex>$<hashHex>`.
export function hashPassword (password, { salt } = {}) {
  const s = salt || randomBytes(16)
  const h = scrypt(enc.encode(password), s, SCRYPT)
  return `scrypt$${SCRYPT.N}$${SCRYPT.r}$${SCRYPT.p}$${hex(s)}$${hex(h)}`
}

export function verifyPassword (password, stored) {
  if (typeof stored !== 'string' || !stored.startsWith('scrypt$')) return false
  const parts = stored.split('$')
  if (parts.length !== 6) return false
  const N = parseInt(parts[1], 10)
  const r = parseInt(parts[2], 10)
  const p = parseInt(parts[3], 10)
  const salt = fromHex(parts[4])
  const expect = fromHex(parts[5])
  const got = scrypt(enc.encode(password), salt, { N, r, p, dkLen: expect.length })
  return timingSafeEqual(got, expect)
}

// ---- HS256 JWTs ----
function segment (obj) { return b64url(enc.encode(JSON.stringify(obj))) }

export function signJwt (payload, secret) {
  const head = segment({ alg: 'HS256', typ: 'JWT' })
  const body = segment(payload)
  const signingInput = `${head}.${body}`
  const sig = hmac(sha256, secret, enc.encode(signingInput))
  return `${signingInput}.${b64url(sig)}`
}

// Verify signature + expiry (nowSec = current time in epoch seconds). Throws a typed
// Error ({ status, error }) on any failure so the membrane can map it to an XRPC error.
export function verifyJwt (token, secret, { nowSec } = {}) {
  const parts = typeof token === 'string' ? token.split('.') : []
  if (parts.length !== 3) throw authError(401, 'AuthMissing', 'malformed token')
  const signingInput = `${parts[0]}.${parts[1]}`
  const expected = hmac(sha256, secret, enc.encode(signingInput))
  const got = b64urlToBytes(parts[2])
  if (!timingSafeEqual(got, expected)) throw authError(401, 'InvalidToken', 'bad signature')
  let payload
  try { payload = JSON.parse(dec.decode(b64urlToBytes(parts[1]))) } catch { throw authError(401, 'InvalidToken', 'bad payload') }
  const now = nowSec != null ? nowSec : Math.floor(Date.now() / 1000)
  if (payload.exp != null && now >= payload.exp) throw authError(401, 'ExpiredToken', 'token expired')
  return payload
}

// ---- ES256K signed assertions — the key-native login (also atproto's service-auth
// shape). A caller proves control of an account's atproto signing key by signing a
// short-lived assertion; the PDS verifies against the key already published in the DID,
// so NO secret is stored. This is the P2P trust root (key possession) brought to the
// HTTP edge — the same key that signs the repo's commits. ----
export function signAssertion (payload, privKey) {
  const head = segment({ alg: 'ES256K', typ: 'JWT' })
  const body = segment(payload)
  const signingInput = `${head}.${body}`
  const sig = secp256k1.sign(sha256(enc.encode(signingInput)), privKey, { lowS: true }).toCompactRawBytes()
  return `${signingInput}.${b64url(sig)}`
}

// Verify signature + expiry against a compressed secp256k1 public key. Throws typed.
export function verifyAssertion (token, pubKeyCompressed, { nowSec } = {}) {
  const parts = typeof token === 'string' ? token.split('.') : []
  if (parts.length !== 3) throw authError(401, 'AuthMissing', 'malformed assertion')
  const signingInput = `${parts[0]}.${parts[1]}`
  let okSig = false
  try { okSig = secp256k1.verify(b64urlToBytes(parts[2]), sha256(enc.encode(signingInput)), pubKeyCompressed, { lowS: true }) } catch { okSig = false }
  if (!okSig) throw authError(401, 'InvalidToken', 'bad assertion signature')
  let payload
  try { payload = JSON.parse(dec.decode(b64urlToBytes(parts[1]))) } catch { throw authError(401, 'InvalidToken', 'bad assertion payload') }
  const now = nowSec != null ? nowSec : Math.floor(Date.now() / 1000)
  if (payload.exp != null && now >= payload.exp) throw authError(401, 'ExpiredToken', 'assertion expired')
  return payload
}

// Decode a JWT/assertion segment (header or claims) WITHOUT verifying — used to read the
// issuer before we know which key to verify against. null on malformed input.
export function decodeSegment (seg) {
  try { return JSON.parse(dec.decode(b64urlToBytes(seg))) } catch { return null }
}

export function parseBearer (authHeader) {
  if (typeof authHeader !== 'string') return null
  const m = authHeader.match(/^Bearer\s+(.+)$/i)
  return m ? m[1].trim() : null
}

export function authError (status, error, message) {
  const e = new Error(message || error)
  e.status = status
  e.error = error
  return e
}

export const ACCESS_SCOPE = 'com.atproto.access'
export const REFRESH_SCOPE = 'com.atproto.refresh'
// did:key encoding/decoding for the two curves atproto accepts.
//
//   did:key:z<base58btc( <multicodec-varint> ++ <compressed-pubkey> )>
//
// Multicodec key-type prefixes (unsigned-varint):
//   secp256k1-pub = 0xe7   -> varint [0xe7, 0x01]   -> did:key:zQ3s...
//   p256-pub      = 0x1200 -> varint [0x80, 0x24]   -> did:key:zDna...
//
// The pubkey is the 33-byte SEC1 compressed point (0x02/0x03 ++ x). This matches
// @atproto/crypto's formatDidKey. Validated by the P-256 golden round-trip test.

import { base58btc } from 'multiformats/bases/base58'

export const CURVE_SECP256K1 = 'secp256k1'
export const CURVE_P256 = 'p256'

const MULTICODEC = {
  [CURVE_SECP256K1]: 0xe7,
  [CURVE_P256]: 0x1200
}
const BY_CODE = { 0xe7: CURVE_SECP256K1, 0x1200: CURVE_P256 }

function varintEncode (n) {
  const out = []
  while (n >= 0x80) { out.push((n & 0x7f) | 0x80); n >>>= 7 }
  out.push(n)
  return Uint8Array.from(out)
}

function varintDecode (bytes) {
  let n = 0, shift = 0, i = 0
  for (;;) {
    const b = bytes[i++]
    n |= (b & 0x7f) << shift
    if ((b & 0x80) === 0) break
    shift += 7
  }
  return { code: n >>> 0, length: i }
}

// compressed pubkey bytes (33) -> did:key string
export function encodeDidKey (curve, compressedPubkey) {
  const code = MULTICODEC[curve]
  if (code === undefined) throw new Error(`unsupported curve: ${curve}`)
  const prefix = varintEncode(code)
  const bytes = new Uint8Array(prefix.length + compressedPubkey.length)
  bytes.set(prefix, 0)
  bytes.set(compressedPubkey, prefix.length)
  return `did:key:${base58btc.encode(bytes)}` // base58btc.encode already prepends 'z'
}

// did:key string -> { curve, pubkey (compressed bytes) }
export function decodeDidKey (didKey) {
  if (!didKey.startsWith('did:key:')) throw new Error('not a did:key')
  const mb = didKey.slice('did:key:'.length)
  const bytes = base58btc.decode(mb) // expects leading 'z'
  const { code, length } = varintDecode(bytes)
  const curve = BY_CODE[code]
  if (!curve) throw new Error(`unknown multicodec 0x${code.toString(16)}`)
  return { curve, pubkey: bytes.slice(length) }
}
// did:plc computation — byte-exact.
//
// A did:plc is derived from its *genesis* operation:
//   did = "did:plc:" + base32( sha256( dag-cbor(signedGenesisOp) ) ).slice(0, 24)
//
// The hash is over the SIGNED op (the `sig` field is included). DAG-CBOR gives a
// canonical byte layout (sorted map keys, definite lengths), so the DID is a pure
// function of the op. base32 here is RFC-4648 lowercase, NO padding, and NO
// multibase prefix (did-method-plc uses raw base32, not multiformats' 'b'-prefixed
// multibase form) — see the golden-vector test.
//
// Reference: https://github.com/did-method-plc/did-method-plc (didForCreateOp)

import * as dagCbor from '@ipld/dag-cbor'
import { sha256 } from '@noble/hashes/sha2'
import { base32 } from 'multiformats/bases/base32'
import { CID } from 'multiformats/cid'
import * as Digest from 'multiformats/hashes/digest'

// multiformats' base32.encode returns a multibase string prefixed with 'b'.
// did:plc uses the raw base32 alphabet output, so strip the leading multibase char.
function rawBase32 (bytes) {
  const multibase = base32.encode(bytes) // 'b' + <rfc4648-lower-nopad>
  return multibase.slice(1)
}

// Canonical DAG-CBOR bytes for an operation object.
export function encodeOp (op) {
  return dagCbor.encode(op)
}

// Compute the did:plc for a signed genesis operation.
export function didForCreateOp (signedOp, truncate = 24) {
  const bytes = encodeOp(signedOp)
  const hash = sha256(bytes)
  const b32 = rawBase32(hash)
  return `did:plc:${b32.slice(0, truncate)}`
}

// The unsigned operation is everything except `sig`. did:plc signs the DAG-CBOR of
// the unsigned op; the signature is then attached and the DID hashes the signed form.
export function unsignedOp (op) {
  const { sig, ...rest } = op // eslint-disable-line no-unused-vars
  return rest
}

// The CID of a SIGNED operation — CIDv1, dag-cbor codec (0x71), sha2-256 multihash
// (0x12), rendered as a base32 string. This is the value the NEXT operation carries in
// its `prev` field to chain the PLC op-log (genesis has `prev: null`). Same encoding as
// atproto-repo/lib/cid.js cidForBytesSync, over DAG-CBOR(signedOp). Reference: the
// did-method-plc CID = CID.create(1, 0x71, sha256(cborEncode(op))).
export function opCid (signedOp) {
  const bytes = encodeOp(signedOp)
  const digest = Digest.create(0x12, sha256(bytes))
  return CID.createV1(dagCbor.code, digest).toString()
}
// DID-derived P2P discovery (the "sneaky P2P" binding, Option 2).
//
// The rendezvous topic for a DID is DERIVED, not written anywhere: the DID document stays
// 100% vanilla atproto (only atproto_pds -> the bridge), so bsky/HTTP never sees a P2P side.
// A self-custody peer announces on discoveryTopic(did); a bridge, given the DID, derives the
// SAME topic, connects, and AUTHENTICATES the peer on connect (the peer's served repo must
// sign against the DID's key — a squatter on the public topic can't forge that). So the lookup
// is deterministic + unauthenticated; trust is established at the connection, not the address.

import crypto from 'hypercore-crypto'

const NS = 'hyper-proto-peer/discovery/v1:'

// did (string) -> 32-byte Hyperswarm topic. Deterministic; anyone with the DID can compute it.
export function discoveryTopic (did) {
  if (!did || typeof did !== 'string') throw new Error('discoveryTopic: did (string) required')
  return crypto.data(new TextEncoder().encode(NS + did))
}
// com.atproto.label — build / sign / verify atproto moderation labels (com.atproto.label.defs#label).
//
// A label is a SIGNED tag on a subject: `uri` is an AT-URI (a record, e.g. a post) OR an account DID;
// `val` is the label value ('spam', '!hide', a custom value); `src` is the labeler's DID. Retraction is
// NEGATION, not deletion (`neg:true` with the same src/uri/val). The signature is a raw 64-byte
// secp256k1 (low-S) signature over the DAG-CBOR of the label WITHOUT its `sig` field — byte-matching
// atproto/ozone (which signs with an #atproto_label key; verified against that did:key).
//
// Lives in atproto-identity because the crypto (dag-cbor + secp256k1 + verifySig + did:key) already
// does; extractable to a dedicated `atproto-label` module later (step 6). The moderation POLICY (which
// labelers to trust, how a `val` renders) is the CONSUMER's job, not this codec's.
import * as dagCbor from '@ipld/dag-cbor'
import { secp256k1 } from '@noble/curves/secp256k1'
import { sha256 } from '@noble/hashes/sha2'
import { verifySig } from './plc-directory.js'

// Canonical bytes signed/verified: DAG-CBOR of the label minus `sig`, undefined fields omitted. DAG-CBOR
// sorts map keys deterministically, so signer and verifier agree regardless of field insertion order.
export function labelSigningBytes (label) {
  const clean = {}
  for (const k of Object.keys(label)) { if (k !== 'sig' && label[k] !== undefined) clean[k] = label[k] }
  return dagCbor.encode(clean)
}

// Build an UNSIGNED label. cts (created-at, ISO datetime) is caller-supplied for determinism.
export function buildLabel ({ src, uri, val, cts, cid, neg, exp, ver }) {
  if (!src || !uri || !val || !cts) throw new Error('buildLabel: src, uri, val, cts are required')
  const label = { src, uri, val, cts }
  if (cid !== undefined) label.cid = cid
  if (neg !== undefined) label.neg = neg
  if (exp !== undefined) label.exp = exp
  if (ver !== undefined) label.ver = ver
  return label
}

// Sign a label with the labeler's raw secp256k1 private key -> the label with a 64-byte `sig` (bytes).
export function signLabel (label, privateKey) {
  const sig = secp256k1.sign(sha256(labelSigningBytes(label)), privateKey, { lowS: true }).toCompactRawBytes()
  return { ...label, sig }
}

// Verify a signed label against the labeler's signing did:key. Returns false on any mismatch/decode
// error (never throws). Reuses the audited verifySig (raw 64-byte, low-S enforced, DER rejected).
export function verifyLabel (label, labelerDidKey) {
  if (!label || !label.sig) return false
  return verifySig(labelSigningBytes(label), label.sig, labelerDidKey)
}

// Wire codec for a full (signed) label — one block of a label feed. `sig` (bytes) round-trips as
// DAG-CBOR bytes. Distinct from labelSigningBytes (which strips sig for the signature domain).
export function encodeLabel (label) { return dagCbor.encode(label) }
export function decodeLabel (bytes) { return dagCbor.decode(bytes) }
// PLC Directory submit ceremony — the SUBMIT half of did:plc (the offline half lives in
// did-plc.js / atproto-identity.js and is byte-exact-proven). See the did-plc skill +
// atproto-base/docs/did-plc-contract-reference.md.
//
// ⚠️ POST /:did is a PERMANENT, irreversible append to the global PLC op-log (nullifiable only
// by a higher-authority fork within a 72h window). So this module is OFFLINE-FIRST: the op
// construction (elsewhere), the §6 validation MIRROR (checkGenesisOp / checkUpdateOp), and the
// ceremony orchestration are all pure/injectable and fully tested WITHOUT the network. The only
// I/O is the injectable `fetchImpl`; nothing here touches the live directory at import.
//
// The self-custody sequence (did-plc skill §5):
//   GET /:did/log/last → live head → opCid(head) == our prev → build full-state op → sign with a
//   CURRENT rotation key → LOCALLY re-validate (§6) → POST /:did → confirm via GET /:did/data.

import { sha256 } from '@noble/hashes/sha2'
import { secp256k1 } from '@noble/curves/secp256k1'
import { p256 } from '@noble/curves/p256'
import { encodeOp, unsignedOp, didForCreateOp, opCid } from './did-plc.js'
import { base64urlToBytes, rotateVerificationMethod } from './atproto-identity.js'
import { decodeDidKey, CURVE_P256 } from './did-key.js'

const DEFAULT_PLC = 'https://plc.directory'

function err (message) { return { ok: false, error: message } }

// ── §6 local validation mirror (pure — run BEFORE the irreversible write) ──

// Verify an atproto ECDSA signature: sig over sha256(messageBytes) against a did:key, honoring
// its curve (secp256k1 or P-256), low-S enforced (§2 — high-S and DER-encoded sigs are rejected).
// The atproto signing primitive. Returns false on any decode/verify error (never throws).
export function verifySig (messageBytes, sigBytes, didKey) {
  let dk
  try { dk = decodeDidKey(didKey) } catch { return false }
  // atproto requires the raw 64-byte (r‖s) compact form — DER-encoded sigs (longer) are INVALID
  // even if cryptographically sound (conformance rule §2). noble would otherwise parse DER.
  if (!sigBytes || sigBytes.length !== 64) return false
  const hash = sha256(messageBytes)
  const curve = dk.curve === CURVE_P256 ? p256 : secp256k1
  try { return curve.verify(sigBytes, hash, dk.pubkey, { lowS: true }) } catch { return false }
}

// Verify a PLC op's signature (over dag-cbor of the unsigned op) against a did:key.
export function verifyOpSig (signedOp, didKey) {
  let sig
  try { sig = base64urlToBytes(signedOp.sig) } catch { return false }
  return verifySig(encodeOp(unsignedOp(signedOp)), sig, didKey)
}

// True iff the op is signed by AT LEAST ONE of the given rotation did:keys (the directory
// accepts if any current rotation key matches — did-plc skill §2).
export function verifyOpSignedByAny (signedOp, rotationDidKeys) {
  return Array.isArray(rotationDidKeys) && rotationDidKeys.some((rk) => verifyOpSig(signedOp, rk))
}

// Local mirror of the directory's genesis validation (§6.2): plc_operation shape, prev:null,
// DID hashes from the op, sig by one of its OWN rotationKeys.
export function checkGenesisOp (signedOp, did) {
  if (!signedOp || signedOp.type !== 'plc_operation') return err('not a plc_operation')
  if (signedOp.prev !== null) return err('genesis prev must be null')
  if (!Array.isArray(signedOp.rotationKeys) || signedOp.rotationKeys.length === 0) return err('no rotationKeys')
  if (!signedOp.verificationMethods || !signedOp.verificationMethods.atproto) return err('no atproto verificationMethod')
  if (!signedOp.sig) return err('op is unsigned')
  let computed
  try { computed = didForCreateOp(signedOp) } catch (e) { return err('DID computation failed: ' + e.message) }
  if (did && computed !== did) return err('DID mismatch: op hashes to ' + computed + ', not ' + did)
  if (!verifyOpSignedByAny(signedOp, signedOp.rotationKeys)) return err('sig not by any of its own rotationKeys')
  return { ok: true, error: null, did: computed }
}

// Local mirror of the directory's forward-extension validation (§6.3-4): the op chains onto
// `prevSignedOp` (prev == its CID) and is signed by one of the HEAD op's rotationKeys.
export function checkUpdateOp (signedOp, prevSignedOp) {
  if (!signedOp || (signedOp.type !== 'plc_operation' && signedOp.type !== 'plc_tombstone')) return err('not a plc op')
  if (typeof signedOp.prev !== 'string' || signedOp.prev.length === 0) return err('update prev must be the head op CID')
  if (!signedOp.sig) return err('op is unsigned')
  if (!prevSignedOp) return err('no prev (head) op to validate against')
  let prevCid
  try { prevCid = opCid(prevSignedOp) } catch (e) { return err('prev CID computation failed: ' + e.message) }
  if (signedOp.prev !== prevCid) return err('prev != head CID (' + signedOp.prev + ' != ' + prevCid + ')')
  if (!verifyOpSignedByAny(signedOp, prevSignedOp.rotationKeys)) return err('sig not by a current (head) rotationKey')
  return { ok: true, error: null }
}

// Normalize a fetched op to EXACTLY the signed-op fields, so opCid() hashes the canonical bytes
// regardless of whether the endpoint wrapped it (`.operation`) or added audit fields (cid/…).
function opFieldsOnly (o) {
  const op = o && o.operation ? o.operation : o
  if (!op || typeof op !== 'object') return op
  if (op.type === 'plc_tombstone') return { type: op.type, prev: op.prev, sig: op.sig }
  return {
    type: op.type,
    rotationKeys: op.rotationKeys,
    verificationMethods: op.verificationMethods,
    alsoKnownAs: op.alsoKnownAs,
    services: op.services,
    prev: op.prev,
    sig: op.sig
  }
}

async function plcError (res, ctx) {
  let body = null
  try { body = await res.json() } catch { try { body = await res.text() } catch { /* ignore */ } }
  const msg = (body && body.message) || (body && body.error) || (typeof body === 'string' && body) || res.statusText || 'error'
  const e = new Error('PLC ' + ctx + ' failed (' + res.status + '): ' + msg)
  e.status = res.status
  e.plc = body
  return e
}

// ── the directory client + ceremony (injectable fetch — offline-testable) ──

export class PlcDirectory {
  constructor ({ baseUrl = DEFAULT_PLC, fetchImpl } = {}) {
    const f = fetchImpl || (typeof globalThis.fetch === 'function' ? globalThis.fetch.bind(globalThis) : null)
    if (typeof f !== 'function') throw new Error('PlcDirectory: no fetch available — pass { fetchImpl }')
    this.baseUrl = String(baseUrl).replace(/\/+$/, '')
    this._fetch = f
  }

  async _get (path) {
    const res = await this._fetch(this.baseUrl + path, { method: 'GET' })
    if (!res.ok) throw await plcError(res, 'GET ' + path)
    return res.json()
  }

  // GET /:did/log/last → the head op (normalized to canonical op fields for opCid).
  async getHead (did) { return opFieldsOnly(await this._get('/' + did + '/log/last')) }
  // GET /:did/data → current PLC state { did, verificationMethods, rotationKeys, alsoKnownAs, services }.
  getData (did) { return this._get('/' + did + '/data') }
  // GET /:did → the DID document.
  resolve (did) { return this._get('/' + did) }
  // GET /:did/log/audit → the audit log (incl. nullified ops).
  getAuditLog (did) { return this._get('/' + did + '/log/audit') }

  // POST /:did — the raw irreversible append (body = the signed op, unwrapped). No local check;
  // callers should use submitGenesis / submitUpdate which validate first.
  async submitRaw (did, signedOp) {
    const res = await this._fetch(this.baseUrl + '/' + did, {
      method: 'POST',
      headers: { 'content-type': 'application/json' },
      body: JSON.stringify(signedOp)
    })
    if (!res.ok) throw await plcError(res, 'POST /' + did)
    return true
  }

  // Submit a genesis op: local §6.2 validation → POST → confirm via getData.
  async submitGenesis ({ did, signedOp, confirm = true }) {
    const chk = checkGenesisOp(signedOp, did)
    if (!chk.ok) throw new Error('refusing to submit invalid genesis: ' + chk.error)
    await this.submitRaw(did, signedOp)
    return confirm ? this.getData(did) : true
  }

  // Submit an update op: fetch the LIVE head, require our op chains onto it (prev == opCid(head))
  // AND passes §6 validation, then POST → confirm. Re-fetching the head at submit time closes the
  // build-vs-submit TOCTOU (a MisorderedOperation reject on the live directory otherwise).
  async submitUpdate ({ did, signedOp, confirm = true }) {
    const head = await this.getHead(did)
    if (signedOp.prev !== opCid(head)) throw new Error('refusing to submit: op.prev != live head CID — refetch the head and rebuild')
    const chk = checkUpdateOp(signedOp, head)
    if (!chk.ok) throw new Error('refusing to submit invalid update: ' + chk.error)
    await this.submitRaw(did, signedOp)
    return confirm ? this.getData(did) : true
  }

  // The device-attestation migration primitive: rotate verificationMethods.atproto to a device
  // key on-chain. Fetches the live head, builds a root-signed rotation off it, validates, submits.
  // signerPrivateKey must correspond to a CURRENT rotation key (the root).
  async rotateVerificationMethodOnChain ({ did, newAtprotoDidKey, signerPrivateKey, confirm = true }) {
    const head = await this.getHead(did)
    const op = rotateVerificationMethod({ prevSignedOp: head, newAtprotoDidKey, signerPrivateKey })
    return this.submitUpdate({ did, signedOp: op, confirm })
  }
}
// atproto-identity/lib/web-auth.js — DID web sign-in verify (the atproto-native "pgv3 method").
//
// The reusable VERIFY half of DID web sign-in. A browser holds a secp256k1 SUB-KEY; the DID's
// #atproto key DELEGATES it (a signed assertion, anchored to the DID's PLC-published key). Login: the
// sub-key signs the fresh server challenge as an ES256K assertion. This is the atproto analog of
// pgv3's root-anchored multi-identity — the DID is the ROOT anchor, sub-keys are the delegated DEVICES
// (revoke a device by expiring/removing its delegation; the DID is untouched). Everything is
// secp256k1/ES256K (signAssertion/verifyAssertion) — no keet, no anproto.
//
// This module owns ONLY the crypto verify. The challenge store (single-use/TTL) and the session live
// in the consumer (e.g. favela wraps this + hyper-identity's AtprotoProvider). resolveVerifyKey(did) →
// the DID's #atproto compressed pubkey is INJECTED (a PLC-directory resolver in prod, a mock in tests)
// so this stays network-free + unit-testable. Fails closed on any bad/absent/expired input.
import { verifyAssertion } from './auth.js'

const hexToBytes = (h) => { const b = new Uint8Array(h.length >> 1); for (let i = 0; i < b.length; i++) b[i] = parseInt(h.substr(i * 2, 2), 16); return b }
const toBytes = (k) => (typeof k === 'string' ? hexToBytes(k) : k)
const toHex = (k) => (typeof k === 'string' ? k : Array.from(k).map((b) => b.toString(16).padStart(2, '0')).join(''))

// The sub-key signed THIS challenge (proves live key control + anti-replay). sig = an ES256K assertion
// signAssertion({ challenge, … }, subPrivKey). subKey is the compressed pubkey (hex or bytes).
export function verifyChallengeSig ({ subKey, challenge, sig } = {}) {
  if (!subKey || !challenge || !sig) return false
  let p
  try { p = verifyAssertion(sig, toBytes(subKey)) } catch { return false } // bad sig / expired → reject
  return !!p && p.challenge === challenge
}

// The DID's #atproto key delegated this sub-key. delegation = an ES256K assertion
// signAssertion({ iss: did, sub: <subKey hex>, exp }, atprotoPrivKey), minted once by the keyholder
// (hpp). resolveVerifyKey(did) → the DID's #atproto compressed pubkey (PLC-published). Fails closed.
export function makeVerifyDelegation ({ resolveVerifyKey } = {}) {
  if (typeof resolveVerifyKey !== 'function') throw new Error('makeVerifyDelegation: resolveVerifyKey(did) required')
  return async function verifyDelegation ({ did, subKey, delegation } = {}) {
    if (!did || !subKey || !delegation) return false
    const subHex = toHex(subKey)
    let vk
    try { vk = await resolveVerifyKey(did) } catch { return false }
    if (!vk) return false
    let p
    try { p = verifyAssertion(delegation, vk) } catch { return false }
    return !!p && p.iss === did && p.sub === subHex
  }
}

// Combined login-proof verify — the injected `verify` for hyper-identity's AtprotoProvider.
//   proof = { did, subKey(hex), challenge(hex), sig, delegation, handle?, didKey? }
// Checks the sub-key signed the challenge AND the DID's #atproto key delegated the sub-key (PLC-
// anchored, re-verified every login — no TOFU). Returns the binding { did, subKey, handle, didKey } or
// false. The challenge's single-use/freshness is the CALLER's job (consume it before/around this).
export function makeAtprotoWebVerify ({ resolveVerifyKey } = {}) {
  const verifyDelegation = makeVerifyDelegation({ resolveVerifyKey })
  return async function verify (proof) {
    if (!proof) return false
    const { did, subKey, challenge, sig, delegation } = proof
    if (!verifyChallengeSig({ subKey, challenge, sig })) return false
    if (!(await verifyDelegation({ did, subKey, delegation }).catch(() => false))) return false
    return { did, subKey: toHex(subKey), handle: proof.handle || null, didKey: proof.didKey || null }
  }
}
{
  "name": "@ipld/dag-cbor",
  "version": "9.2.7",
  "description": "JS implementation of DAG-CBOR",
  "author": "Rod <rod@vagg.org> (http://r.va.gg/)",
  "license": "Apache-2.0 OR MIT",
  "homepage": "https://github.com/ipld/js-dag-cbor#readme",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/ipld/js-dag-cbor.git"
  },
  "bugs": {
    "url": "https://github.com/ipld/js-dag-cbor/issues"
  },
  "publishConfig": {
    "access": "public",
    "provenance": true
  },
  "keywords": [
    "ipfs",
    "ipld",
    "multiformats"
  ],
  "type": "module",
  "types": "./dist/src/index.d.ts",
  "typesVersions": {
    "*": {
      "*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ],
      "src/*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ]
    }
  },
  "files": [
    "src",
    "dist",
    "!dist/test",
    "!**/*.tsbuildinfo"
  ],
  "exports": {
    ".": {
      "types": "./dist/src/index.d.ts",
      "import": "./src/index.js",
      "module-sync": "./src/index.js"
    }
  },
  "release": {
    "branches": [
      "master"
    ],
    "plugins": [
      [
        "@semantic-release/commit-analyzer",
        {
          "preset": "conventionalcommits",
          "releaseRules": [
            {
              "breaking": true,
              "release": "major"
            },
            {
              "revert": true,
              "release": "patch"
            },
            {
              "type": "feat",
              "release": "minor"
            },
            {
              "type": "fix",
              "release": "patch"
            },
            {
              "type": "docs",
              "release": "patch"
            },
            {
              "type": "test",
              "release": "patch"
            },
            {
              "type": "deps",
              "release": "patch"
            },
            {
              "scope": "no-release",
              "release": false
            }
          ]
        }
      ],
      [
        "@semantic-release/release-notes-generator",
        {
          "preset": "conventionalcommits",
          "presetConfig": {
            "types": [
              {
                "type": "feat",
                "section": "Features"
              },
              {
                "type": "fix",
                "section": "Bug Fixes"
              },
              {
                "type": "chore",
                "section": "Trivial Changes"
              },
              {
                "type": "docs",
                "section": "Documentation"
              },
              {
                "type": "deps",
                "section": "Dependencies"
              },
              {
                "type": "test",
                "section": "Tests"
              }
            ]
          }
        }
      ],
      "@semantic-release/changelog",
      "@semantic-release/npm",
      "@semantic-release/github",
      [
        "@semantic-release/git",
        {
          "assets": [
            "CHANGELOG.md",
            "package.json"
          ]
        }
      ]
    ]
  },
  "scripts": {
    "clean": "aegir clean",
    "lint": "aegir lint",
    "build": "aegir build",
    "release": "aegir release",
    "test": "npm run lint && aegir test",
    "test:ts": "npm run test --prefix test/ts-use",
    "test:node": "aegir test -t node --cov",
    "test:chrome": "aegir test -t browser --cov",
    "test:chrome-webworker": "aegir test -t webworker",
    "test:firefox": "aegir test -t browser -- --browser firefox",
    "test:firefox-webworker": "aegir test -t webworker -- --browser firefox",
    "test:electron-main": "aegir test -t electron-main",
    "dep-check": "aegir dep-check"
  },
  "dependencies": {
    "cborg": "^5.0.1",
    "multiformats": "^13.1.0"
  },
  "devDependencies": {
    "@ipld/garbage": "^6.0.0",
    "aegir": "^48.0.1"
  }
}
import * as cborg from 'cborg'
import { CID } from 'multiformats/cid'

// https://github.com/ipfs/go-ipfs/issues/3570#issuecomment-273931692
const CID_CBOR_TAG = 42

/**
 * @template T
 * @typedef {import('multiformats/codecs/interface').ByteView<T>} ByteView
 */

/**
 * @template T
 * @typedef {import('multiformats/codecs/interface').ArrayBufferView<T>} ArrayBufferView
 */

/**
 * @template T
 * @param {ByteView<T> | ArrayBufferView<T>} buf
 * @returns {ByteView<T>}
 */
export function toByteView (buf) {
  if (buf instanceof ArrayBuffer) {
    return new Uint8Array(buf, 0, buf.byteLength)
  }

  return buf
}

/**
 * cidEncoder will receive all Objects during encode, it needs to filter out
 * anything that's not a CID and return `null` for that so it's encoded as
 * normal.
 *
 * @param {any} obj
 * @returns {cborg.Token[]|null}
 */
function cidEncoder (obj) {
  if (obj.asCID !== obj && obj['/'] !== obj.bytes) {
    return null // any other kind of object
  }
  const cid = CID.asCID(obj)
  /* c8 ignore next 4 */
  // very unlikely case, and it'll probably throw a recursion error in cborg
  if (!cid) {
    return null
  }
  const bytes = new Uint8Array(cid.bytes.byteLength + 1)
  bytes.set(cid.bytes, 1) // prefix is 0x00, for historical reasons
  return [
    new cborg.Token(cborg.Type.tag, CID_CBOR_TAG),
    new cborg.Token(cborg.Type.bytes, bytes)
  ]
}

// eslint-disable-next-line jsdoc/require-returns-check
/**
 * Intercept all `undefined` values from an object walk and reject the entire
 * object if we find one.
 *
 * @returns {null}
 */
function undefinedEncoder () {
  throw new Error('`undefined` is not supported by the IPLD Data Model and cannot be encoded')
}

/**
 * Intercept all `number` values from an object walk and reject the entire
 * object if we find something that doesn't fit the IPLD data model (NaN &
 * Infinity).
 *
 * @param {number} num
 * @returns {null}
 */
function numberEncoder (num) {
  if (Number.isNaN(num)) {
    throw new Error('`NaN` is not supported by the IPLD Data Model and cannot be encoded')
  }
  if (num === Infinity || num === -Infinity) {
    throw new Error('`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded')
  }
  return null
}

/**
 * @param {Map<any, any>} map
 * @returns {null}
 */
function mapEncoder (map) {
  for (const key of map.keys()) {
    if (typeof key !== 'string' || key.length === 0) {
      throw new Error('Non-string Map keys are not supported by the IPLD Data Model and cannot be encoded')
    }
  }
  return null
}

const _encodeOptions = {
  float64: true,
  typeEncoders: {
    Map: mapEncoder,
    Object: cidEncoder,
    undefined: undefinedEncoder,
    number: numberEncoder
  }
}

export const encodeOptions = {
  ..._encodeOptions,
  typeEncoders: {
    ..._encodeOptions.typeEncoders
  }
}

/**
 * @param {import('cborg').TagDecodeControl} decode
 * @returns {CID}
 */
function cidDecoder (decode) {
  const bytes = /** @type {Uint8Array} */ (decode())
  if (bytes[0] !== 0) {
    throw new Error('Invalid CID for CBOR tag 42; expected leading 0x00')
  }
  return CID.decode(bytes.subarray(1)) // ignore leading 0x00
}

const _decodeOptions = {
  allowIndefinite: false,
  coerceUndefinedToNull: true,
  allowNaN: false,
  allowInfinity: false,
  allowBigInt: true, // this will lead to BigInt for ints outside of
  // safe-integer range, which may surprise users
  strict: true,
  useMaps: false,
  rejectDuplicateMapKeys: true,
  /** @type {{ [tagNumber: number]: import('cborg').TagDecoder }} */
  tags: { [CID_CBOR_TAG]: cidDecoder }
}

export const decodeOptions = {
  ..._decodeOptions,
  tags: { ..._decodeOptions.tags }
}

export const name = 'dag-cbor'
export const code = 0x71

/**
 * @template T
 * @param {T} node
 * @returns {ByteView<T>}
 */
export const encode = (node) => cborg.encode(node, _encodeOptions)

/**
 * @template T
 * @param {ByteView<T> | ArrayBufferView<T>} data
 * @returns {T}
 */
export const decode = (data) => cborg.decode(toByteView(data), _decodeOptions)
/**
 * Utilities for short weierstrass curves, combined with noble-hashes.
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { weierstrass } from "./abstract/weierstrass.js";
/** connects noble-curves to noble-hashes */
export function getHash(hash) {
    return { hash };
}
/** @deprecated use new `weierstrass()` and `ecdsa()` methods */
export function createCurve(curveDef, defHash) {
    const create = (hash) => weierstrass({ ...curveDef, hash: hash });
    return { ...create(defHash), create };
}
//# sourceMappingURL=_shortw_utils.js.map/**
 * Methods for elliptic curve multiplication by scalars.
 * Contains wNAF, pippenger.
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { bitLen, bitMask, validateObject } from "../utils.js";
import { Field, FpInvertBatch, nLength, validateField } from "./modular.js";
const _0n = BigInt(0);
const _1n = BigInt(1);
export function negateCt(condition, item) {
    const neg = item.negate();
    return condition ? neg : item;
}
/**
 * Takes a bunch of Projective Points but executes only one
 * inversion on all of them. Inversion is very slow operation,
 * so this improves performance massively.
 * Optimization: converts a list of projective points to a list of identical points with Z=1.
 */
export function normalizeZ(c, points) {
    const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
    return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
}
function validateW(W, bits) {
    if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
        throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);
}
function calcWOpts(W, scalarBits) {
    validateW(W, scalarBits);
    const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero
    const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero
    const maxNumber = 2 ** W; // W=8 256
    const mask = bitMask(W); // W=8 255 == mask 0b11111111
    const shiftBy = BigInt(W); // W=8 8
    return { windows, windowSize, mask, maxNumber, shiftBy };
}
function calcOffsets(n, window, wOpts) {
    const { windowSize, mask, maxNumber, shiftBy } = wOpts;
    let wbits = Number(n & mask); // extract W bits.
    let nextN = n >> shiftBy; // shift number by W bits.
    // What actually happens here:
    // const highestBit = Number(mask ^ (mask >> 1n));
    // let wbits2 = wbits - 1; // skip zero
    // if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);
    // split if bits > max: +224 => 256-32
    if (wbits > windowSize) {
        // we skip zero, which means instead of `>= size-1`, we do `> size`
        wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.
        nextN += _1n; // +256 (carry)
    }
    const offsetStart = window * windowSize;
    const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero
    const isZero = wbits === 0; // is current window slice a 0?
    const isNeg = wbits < 0; // is current window slice negative?
    const isNegF = window % 2 !== 0; // fake random statement for noise
    const offsetF = offsetStart; // fake offset for noise
    return { nextN, offset, isZero, isNeg, isNegF, offsetF };
}
function validateMSMPoints(points, c) {
    if (!Array.isArray(points))
        throw new Error('array expected');
    points.forEach((p, i) => {
        if (!(p instanceof c))
            throw new Error('invalid point at index ' + i);
    });
}
function validateMSMScalars(scalars, field) {
    if (!Array.isArray(scalars))
        throw new Error('array of scalars expected');
    scalars.forEach((s, i) => {
        if (!field.isValid(s))
            throw new Error('invalid scalar at index ' + i);
    });
}
// Since points in different groups cannot be equal (different object constructor),
// we can have single place to store precomputes.
// Allows to make points frozen / immutable.
const pointPrecomputes = new WeakMap();
const pointWindowSizes = new WeakMap();
function getW(P) {
    // To disable precomputes:
    // return 1;
    return pointWindowSizes.get(P) || 1;
}
function assert0(n) {
    if (n !== _0n)
        throw new Error('invalid wNAF');
}
/**
 * Elliptic curve multiplication of Point by scalar. Fragile.
 * Table generation takes **30MB of ram and 10ms on high-end CPU**,
 * but may take much longer on slow devices. Actual generation will happen on
 * first call of `multiply()`. By default, `BASE` point is precomputed.
 *
 * Scalars should always be less than curve order: this should be checked inside of a curve itself.
 * Creates precomputation tables for fast multiplication:
 * - private scalar is split by fixed size windows of W bits
 * - every window point is collected from window's table & added to accumulator
 * - since windows are different, same point inside tables won't be accessed more than once per calc
 * - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)
 * - +1 window is neccessary for wNAF
 * - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication
 *
 * @todo Research returning 2d JS array of windows, instead of a single window.
 * This would allow windows to be in different memory locations
 */
export class wNAF {
    // Parametrized with a given Point class (not individual point)
    constructor(Point, bits) {
        this.BASE = Point.BASE;
        this.ZERO = Point.ZERO;
        this.Fn = Point.Fn;
        this.bits = bits;
    }
    // non-const time multiplication ladder
    _unsafeLadder(elm, n, p = this.ZERO) {
        let d = elm;
        while (n > _0n) {
            if (n & _1n)
                p = p.add(d);
            d = d.double();
            n >>= _1n;
        }
        return p;
    }
    /**
     * Creates a wNAF precomputation window. Used for caching.
     * Default window size is set by `utils.precompute()` and is equal to 8.
     * Number of precomputed points depends on the curve size:
     * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
     * - 𝑊 is the window size
     * - 𝑛 is the bitlength of the curve order.
     * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
     * @param point Point instance
     * @param W window size
     * @returns precomputed point tables flattened to a single array
     */
    precomputeWindow(point, W) {
        const { windows, windowSize } = calcWOpts(W, this.bits);
        const points = [];
        let p = point;
        let base = p;
        for (let window = 0; window < windows; window++) {
            base = p;
            points.push(base);
            // i=1, bc we skip 0
            for (let i = 1; i < windowSize; i++) {
                base = base.add(p);
                points.push(base);
            }
            p = base.double();
        }
        return points;
    }
    /**
     * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
     * More compact implementation:
     * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
     * @returns real and fake (for const-time) points
     */
    wNAF(W, precomputes, n) {
        // Scalar should be smaller than field order
        if (!this.Fn.isValid(n))
            throw new Error('invalid scalar');
        // Accumulators
        let p = this.ZERO;
        let f = this.BASE;
        // This code was first written with assumption that 'f' and 'p' will never be infinity point:
        // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,
        // there is negate now: it is possible that negated element from low value
        // would be the same as high element, which will create carry into next window.
        // It's not obvious how this can fail, but still worth investigating later.
        const wo = calcWOpts(W, this.bits);
        for (let window = 0; window < wo.windows; window++) {
            // (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise
            const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
            n = nextN;
            if (isZero) {
                // bits are 0: add garbage to fake point
                // Important part for const-time getPublicKey: add random "noise" point to f.
                f = f.add(negateCt(isNegF, precomputes[offsetF]));
            }
            else {
                // bits are 1: add to result point
                p = p.add(negateCt(isNeg, precomputes[offset]));
            }
        }
        assert0(n);
        // Return both real and fake points: JIT won't eliminate f.
        // At this point there is a way to F be infinity-point even if p is not,
        // which makes it less const-time: around 1 bigint multiply.
        return { p, f };
    }
    /**
     * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
     * @param acc accumulator point to add result of multiplication
     * @returns point
     */
    wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
        const wo = calcWOpts(W, this.bits);
        for (let window = 0; window < wo.windows; window++) {
            if (n === _0n)
                break; // Early-exit, skip 0 value
            const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
            n = nextN;
            if (isZero) {
                // Window bits are 0: skip processing.
                // Move to next window.
                continue;
            }
            else {
                const item = precomputes[offset];
                acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM
            }
        }
        assert0(n);
        return acc;
    }
    getPrecomputes(W, point, transform) {
        // Calculate precomputes on a first run, reuse them after
        let comp = pointPrecomputes.get(point);
        if (!comp) {
            comp = this.precomputeWindow(point, W);
            if (W !== 1) {
                // Doing transform outside of if brings 15% perf hit
                if (typeof transform === 'function')
                    comp = transform(comp);
                pointPrecomputes.set(point, comp);
            }
        }
        return comp;
    }
    cached(point, scalar, transform) {
        const W = getW(point);
        return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
    }
    unsafe(point, scalar, transform, prev) {
        const W = getW(point);
        if (W === 1)
            return this._unsafeLadder(point, scalar, prev); // For W=1 ladder is ~x2 faster
        return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
    }
    // We calculate precomputes for elliptic curve point multiplication
    // using windowed method. This specifies window size and
    // stores precomputed values. Usually only base point would be precomputed.
    createCache(P, W) {
        validateW(W, this.bits);
        pointWindowSizes.set(P, W);
        pointPrecomputes.delete(P);
    }
    hasCache(elm) {
        return getW(elm) !== 1;
    }
}
/**
 * Endomorphism-specific multiplication for Koblitz curves.
 * Cost: 128 dbl, 0-256 adds.
 */
export function mulEndoUnsafe(Point, point, k1, k2) {
    let acc = point;
    let p1 = Point.ZERO;
    let p2 = Point.ZERO;
    while (k1 > _0n || k2 > _0n) {
        if (k1 & _1n)
            p1 = p1.add(acc);
        if (k2 & _1n)
            p2 = p2.add(acc);
        acc = acc.double();
        k1 >>= _1n;
        k2 >>= _1n;
    }
    return { p1, p2 };
}
/**
 * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).
 * 30x faster vs naive addition on L=4096, 10x faster than precomputes.
 * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.
 * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.
 * @param c Curve Point constructor
 * @param fieldN field over CURVE.N - important that it's not over CURVE.P
 * @param points array of L curve points
 * @param scalars array of L scalars (aka secret keys / bigints)
 */
export function pippenger(c, fieldN, points, scalars) {
    // If we split scalars by some window (let's say 8 bits), every chunk will only
    // take 256 buckets even if there are 4096 scalars, also re-uses double.
    // TODO:
    // - https://eprint.iacr.org/2024/750.pdf
    // - https://tches.iacr.org/index.php/TCHES/article/view/10287
    // 0 is accepted in scalars
    validateMSMPoints(points, c);
    validateMSMScalars(scalars, fieldN);
    const plength = points.length;
    const slength = scalars.length;
    if (plength !== slength)
        throw new Error('arrays of points and scalars must have equal length');
    // if (plength === 0) throw new Error('array must be of length >= 2');
    const zero = c.ZERO;
    const wbits = bitLen(BigInt(plength));
    let windowSize = 1; // bits
    if (wbits > 12)
        windowSize = wbits - 3;
    else if (wbits > 4)
        windowSize = wbits - 2;
    else if (wbits > 0)
        windowSize = 2;
    const MASK = bitMask(windowSize);
    const buckets = new Array(Number(MASK) + 1).fill(zero); // +1 for zero array
    const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;
    let sum = zero;
    for (let i = lastBits; i >= 0; i -= windowSize) {
        buckets.fill(zero);
        for (let j = 0; j < slength; j++) {
            const scalar = scalars[j];
            const wbits = Number((scalar >> BigInt(i)) & MASK);
            buckets[wbits] = buckets[wbits].add(points[j]);
        }
        let resI = zero; // not using this will do small speed-up, but will lose ct
        // Skip first bucket, because it is zero
        for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {
            sumI = sumI.add(buckets[j]);
            resI = resI.add(sumI);
        }
        sum = sum.add(resI);
        if (i !== 0)
            for (let j = 0; j < windowSize; j++)
                sum = sum.double();
    }
    return sum;
}
/**
 * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).
 * @param c Curve Point constructor
 * @param fieldN field over CURVE.N - important that it's not over CURVE.P
 * @param points array of L curve points
 * @returns function which multiplies points with scaars
 */
export function precomputeMSMUnsafe(c, fieldN, points, windowSize) {
    /**
     * Performance Analysis of Window-based Precomputation
     *
     * Base Case (256-bit scalar, 8-bit window):
     * - Standard precomputation requires:
     *   - 31 additions per scalar × 256 scalars = 7,936 ops
     *   - Plus 255 summary additions = 8,191 total ops
     *   Note: Summary additions can be optimized via accumulator
     *
     * Chunked Precomputation Analysis:
     * - Using 32 chunks requires:
     *   - 255 additions per chunk
     *   - 256 doublings
     *   - Total: (255 × 32) + 256 = 8,416 ops
     *
     * Memory Usage Comparison:
     * Window Size | Standard Points | Chunked Points
     * ------------|-----------------|---------------
     *     4-bit   |     520         |      15
     *     8-bit   |    4,224        |     255
     *    10-bit   |   13,824        |   1,023
     *    16-bit   |  557,056        |  65,535
     *
     * Key Advantages:
     * 1. Enables larger window sizes due to reduced memory overhead
     * 2. More efficient for smaller scalar counts:
     *    - 16 chunks: (16 × 255) + 256 = 4,336 ops
     *    - ~2x faster than standard 8,191 ops
     *
     * Limitations:
     * - Not suitable for plain precomputes (requires 256 constant doublings)
     * - Performance degrades with larger scalar counts:
     *   - Optimal for ~256 scalars
     *   - Less efficient for 4096+ scalars (Pippenger preferred)
     */
    validateW(windowSize, fieldN.BITS);
    validateMSMPoints(points, c);
    const zero = c.ZERO;
    const tableSize = 2 ** windowSize - 1; // table size (without zero)
    const chunks = Math.ceil(fieldN.BITS / windowSize); // chunks of item
    const MASK = bitMask(windowSize);
    const tables = points.map((p) => {
        const res = [];
        for (let i = 0, acc = p; i < tableSize; i++) {
            res.push(acc);
            acc = acc.add(p);
        }
        return res;
    });
    return (scalars) => {
        validateMSMScalars(scalars, fieldN);
        if (scalars.length > points.length)
            throw new Error('array of scalars must be smaller than array of points');
        let res = zero;
        for (let i = 0; i < chunks; i++) {
            // No need to double if accumulator is still zero.
            if (res !== zero)
                for (let j = 0; j < windowSize; j++)
                    res = res.double();
            const shiftBy = BigInt(chunks * windowSize - (i + 1) * windowSize);
            for (let j = 0; j < scalars.length; j++) {
                const n = scalars[j];
                const curr = Number((n >> shiftBy) & MASK);
                if (!curr)
                    continue; // skip zero scalars chunks
                res = res.add(tables[j][curr - 1]);
            }
        }
        return res;
    };
}
// TODO: remove
/** @deprecated */
export function validateBasic(curve) {
    validateField(curve.Fp);
    validateObject(curve, {
        n: 'bigint',
        h: 'bigint',
        Gx: 'field',
        Gy: 'field',
    }, {
        nBitLength: 'isSafeInteger',
        nByteLength: 'isSafeInteger',
    });
    // Set defaults
    return Object.freeze({
        ...nLength(curve.n, curve.nBitLength),
        ...curve,
        ...{ p: curve.Fp.ORDER },
    });
}
function createField(order, field, isLE) {
    if (field) {
        if (field.ORDER !== order)
            throw new Error('Field.ORDER must match order: Fp == p, Fn == n');
        validateField(field);
        return field;
    }
    else {
        return Field(order, { isLE });
    }
}
/** Validates CURVE opts and creates fields */
export function _createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
    if (FpFnLE === undefined)
        FpFnLE = type === 'edwards';
    if (!CURVE || typeof CURVE !== 'object')
        throw new Error(`expected valid ${type} CURVE object`);
    for (const p of ['p', 'n', 'h']) {
        const val = CURVE[p];
        if (!(typeof val === 'bigint' && val > _0n))
            throw new Error(`CURVE.${p} must be positive bigint`);
    }
    const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);
    const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
    const _b = type === 'weierstrass' ? 'b' : 'd';
    const params = ['Gx', 'Gy', 'a', _b];
    for (const p of params) {
        // @ts-ignore
        if (!Fp.isValid(CURVE[p]))
            throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
    }
    CURVE = Object.freeze(Object.assign({}, CURVE));
    return { CURVE, Fp, Fn };
}
//# sourceMappingURL=curve.js.mapimport { _validateObject, abytes, bytesToNumberBE, concatBytes, isBytes, isHash, utf8ToBytes, } from "../utils.js";
import { FpInvertBatch, mod } from "./modular.js";
// Octet Stream to Integer. "spec" implementation of os2ip is 2.5x slower vs bytesToNumberBE.
const os2ip = bytesToNumberBE;
// Integer to Octet Stream (numberToBytesBE)
function i2osp(value, length) {
    anum(value);
    anum(length);
    if (value < 0 || value >= 1 << (8 * length))
        throw new Error('invalid I2OSP input: ' + value);
    const res = Array.from({ length }).fill(0);
    for (let i = length - 1; i >= 0; i--) {
        res[i] = value & 0xff;
        value >>>= 8;
    }
    return new Uint8Array(res);
}
function strxor(a, b) {
    const arr = new Uint8Array(a.length);
    for (let i = 0; i < a.length; i++) {
        arr[i] = a[i] ^ b[i];
    }
    return arr;
}
function anum(item) {
    if (!Number.isSafeInteger(item))
        throw new Error('number expected');
}
function normDST(DST) {
    if (!isBytes(DST) && typeof DST !== 'string')
        throw new Error('DST must be Uint8Array or string');
    return typeof DST === 'string' ? utf8ToBytes(DST) : DST;
}
/**
 * Produces a uniformly random byte string using a cryptographic hash function H that outputs b bits.
 * [RFC 9380 5.3.1](https://www.rfc-editor.org/rfc/rfc9380#section-5.3.1).
 */
export function expand_message_xmd(msg, DST, lenInBytes, H) {
    abytes(msg);
    anum(lenInBytes);
    DST = normDST(DST);
    // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3
    if (DST.length > 255)
        DST = H(concatBytes(utf8ToBytes('H2C-OVERSIZE-DST-'), DST));
    const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H;
    const ell = Math.ceil(lenInBytes / b_in_bytes);
    if (lenInBytes > 65535 || ell > 255)
        throw new Error('expand_message_xmd: invalid lenInBytes');
    const DST_prime = concatBytes(DST, i2osp(DST.length, 1));
    const Z_pad = i2osp(0, r_in_bytes);
    const l_i_b_str = i2osp(lenInBytes, 2); // len_in_bytes_str
    const b = new Array(ell);
    const b_0 = H(concatBytes(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));
    b[0] = H(concatBytes(b_0, i2osp(1, 1), DST_prime));
    for (let i = 1; i <= ell; i++) {
        const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime];
        b[i] = H(concatBytes(...args));
    }
    const pseudo_random_bytes = concatBytes(...b);
    return pseudo_random_bytes.slice(0, lenInBytes);
}
/**
 * Produces a uniformly random byte string using an extendable-output function (XOF) H.
 * 1. The collision resistance of H MUST be at least k bits.
 * 2. H MUST be an XOF that has been proved indifferentiable from
 *    a random oracle under a reasonable cryptographic assumption.
 * [RFC 9380 5.3.2](https://www.rfc-editor.org/rfc/rfc9380#section-5.3.2).
 */
export function expand_message_xof(msg, DST, lenInBytes, k, H) {
    abytes(msg);
    anum(lenInBytes);
    DST = normDST(DST);
    // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3
    // DST = H('H2C-OVERSIZE-DST-' || a_very_long_DST, Math.ceil((lenInBytes * k) / 8));
    if (DST.length > 255) {
        const dkLen = Math.ceil((2 * k) / 8);
        DST = H.create({ dkLen }).update(utf8ToBytes('H2C-OVERSIZE-DST-')).update(DST).digest();
    }
    if (lenInBytes > 65535 || DST.length > 255)
        throw new Error('expand_message_xof: invalid lenInBytes');
    return (H.create({ dkLen: lenInBytes })
        .update(msg)
        .update(i2osp(lenInBytes, 2))
        // 2. DST_prime = DST || I2OSP(len(DST), 1)
        .update(DST)
        .update(i2osp(DST.length, 1))
        .digest());
}
/**
 * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F.
 * [RFC 9380 5.2](https://www.rfc-editor.org/rfc/rfc9380#section-5.2).
 * @param msg a byte string containing the message to hash
 * @param count the number of elements of F to output
 * @param options `{DST: string, p: bigint, m: number, k: number, expand: 'xmd' | 'xof', hash: H}`, see above
 * @returns [u_0, ..., u_(count - 1)], a list of field elements.
 */
export function hash_to_field(msg, count, options) {
    _validateObject(options, {
        p: 'bigint',
        m: 'number',
        k: 'number',
        hash: 'function',
    });
    const { p, k, m, hash, expand, DST } = options;
    if (!isHash(options.hash))
        throw new Error('expected valid hash');
    abytes(msg);
    anum(count);
    const log2p = p.toString(2).length;
    const L = Math.ceil((log2p + k) / 8); // section 5.1 of ietf draft link above
    const len_in_bytes = count * m * L;
    let prb; // pseudo_random_bytes
    if (expand === 'xmd') {
        prb = expand_message_xmd(msg, DST, len_in_bytes, hash);
    }
    else if (expand === 'xof') {
        prb = expand_message_xof(msg, DST, len_in_bytes, k, hash);
    }
    else if (expand === '_internal_pass') {
        // for internal tests only
        prb = msg;
    }
    else {
        throw new Error('expand must be "xmd" or "xof"');
    }
    const u = new Array(count);
    for (let i = 0; i < count; i++) {
        const e = new Array(m);
        for (let j = 0; j < m; j++) {
            const elm_offset = L * (j + i * m);
            const tv = prb.subarray(elm_offset, elm_offset + L);
            e[j] = mod(os2ip(tv), p);
        }
        u[i] = e;
    }
    return u;
}
export function isogenyMap(field, map) {
    // Make same order as in spec
    const coeff = map.map((i) => Array.from(i).reverse());
    return (x, y) => {
        const [xn, xd, yn, yd] = coeff.map((val) => val.reduce((acc, i) => field.add(field.mul(acc, x), i)));
        // 6.6.3
        // Exceptional cases of iso_map are inputs that cause the denominator of
        // either rational function to evaluate to zero; such cases MUST return
        // the identity point on E.
        const [xd_inv, yd_inv] = FpInvertBatch(field, [xd, yd], true);
        x = field.mul(xn, xd_inv); // xNum / xDen
        y = field.mul(y, field.mul(yn, yd_inv)); // y * (yNum / yDev)
        return { x, y };
    };
}
export const _DST_scalar = utf8ToBytes('HashToScalar-');
/** Creates hash-to-curve methods from EC Point and mapToCurve function. See {@link H2CHasher}. */
export function createHasher(Point, mapToCurve, defaults) {
    if (typeof mapToCurve !== 'function')
        throw new Error('mapToCurve() must be defined');
    function map(num) {
        return Point.fromAffine(mapToCurve(num));
    }
    function clear(initial) {
        const P = initial.clearCofactor();
        if (P.equals(Point.ZERO))
            return Point.ZERO; // zero will throw in assert
        P.assertValidity();
        return P;
    }
    return {
        defaults,
        hashToCurve(msg, options) {
            const opts = Object.assign({}, defaults, options);
            const u = hash_to_field(msg, 2, opts);
            const u0 = map(u[0]);
            const u1 = map(u[1]);
            return clear(u0.add(u1));
        },
        encodeToCurve(msg, options) {
            const optsDst = defaults.encodeDST ? { DST: defaults.encodeDST } : {};
            const opts = Object.assign({}, defaults, optsDst, options);
            const u = hash_to_field(msg, 1, opts);
            const u0 = map(u[0]);
            return clear(u0);
        },
        /** See {@link H2CHasher} */
        mapToCurve(scalars) {
            if (!Array.isArray(scalars))
                throw new Error('expected array of bigints');
            for (const i of scalars)
                if (typeof i !== 'bigint')
                    throw new Error('expected array of bigints');
            return clear(map(scalars));
        },
        // hash_to_scalar can produce 0: https://www.rfc-editor.org/errata/eid8393
        // RFC 9380, draft-irtf-cfrg-bbs-signatures-08
        hashToScalar(msg, options) {
            // @ts-ignore
            const N = Point.Fn.ORDER;
            const opts = Object.assign({}, defaults, { p: N, m: 1, DST: _DST_scalar }, options);
            return hash_to_field(msg, 1, opts)[0][0];
        },
    };
}
//# sourceMappingURL=hash-to-curve.js.map/**
 * Utils for modular division and fields.
 * Field over 11 is a finite (Galois) field is integer number operations `mod 11`.
 * There is no division: it is replaced by modular multiplicative inverse.
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { _validateObject, anumber, bitMask, bytesToNumberBE, bytesToNumberLE, ensureBytes, numberToBytesBE, numberToBytesLE, } from "../utils.js";
// prettier-ignore
const _0n = BigInt(0), _1n = BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3);
// prettier-ignore
const _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5), _7n = /* @__PURE__ */ BigInt(7);
// prettier-ignore
const _8n = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9), _16n = /* @__PURE__ */ BigInt(16);
// Calculates a modulo b
export function mod(a, b) {
    const result = a % b;
    return result >= _0n ? result : b + result;
}
/**
 * Efficiently raise num to power and do modular division.
 * Unsafe in some contexts: uses ladder, so can expose bigint bits.
 * @example
 * pow(2n, 6n, 11n) // 64n % 11n == 9n
 */
export function pow(num, power, modulo) {
    return FpPow(Field(modulo), num, power);
}
/** Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)` */
export function pow2(x, power, modulo) {
    let res = x;
    while (power-- > _0n) {
        res *= res;
        res %= modulo;
    }
    return res;
}
/**
 * Inverses number over modulo.
 * Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).
 */
export function invert(number, modulo) {
    if (number === _0n)
        throw new Error('invert: expected non-zero number');
    if (modulo <= _0n)
        throw new Error('invert: expected positive modulus, got ' + modulo);
    // Fermat's little theorem "CT-like" version inv(n) = n^(m-2) mod m is 30x slower.
    let a = mod(number, modulo);
    let b = modulo;
    // prettier-ignore
    let x = _0n, y = _1n, u = _1n, v = _0n;
    while (a !== _0n) {
        // JIT applies optimization if those two lines follow each other
        const q = b / a;
        const r = b % a;
        const m = x - u * q;
        const n = y - v * q;
        // prettier-ignore
        b = a, a = r, x = u, y = v, u = m, v = n;
    }
    const gcd = b;
    if (gcd !== _1n)
        throw new Error('invert: does not exist');
    return mod(x, modulo);
}
function assertIsSquare(Fp, root, n) {
    if (!Fp.eql(Fp.sqr(root), n))
        throw new Error('Cannot find square root');
}
// Not all roots are possible! Example which will throw:
// const NUM =
// n = 72057594037927816n;
// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));
function sqrt3mod4(Fp, n) {
    const p1div4 = (Fp.ORDER + _1n) / _4n;
    const root = Fp.pow(n, p1div4);
    assertIsSquare(Fp, root, n);
    return root;
}
function sqrt5mod8(Fp, n) {
    const p5div8 = (Fp.ORDER - _5n) / _8n;
    const n2 = Fp.mul(n, _2n);
    const v = Fp.pow(n2, p5div8);
    const nv = Fp.mul(n, v);
    const i = Fp.mul(Fp.mul(nv, _2n), v);
    const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
    assertIsSquare(Fp, root, n);
    return root;
}
// Based on RFC9380, Kong algorithm
// prettier-ignore
function sqrt9mod16(P) {
    const Fp_ = Field(P);
    const tn = tonelliShanks(P);
    const c1 = tn(Fp_, Fp_.neg(Fp_.ONE)); //  1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F
    const c2 = tn(Fp_, c1); //  2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F
    const c3 = tn(Fp_, Fp_.neg(c1)); //  3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F
    const c4 = (P + _7n) / _16n; //  4. c4 = (q + 7) / 16        # Integer arithmetic
    return (Fp, n) => {
        let tv1 = Fp.pow(n, c4); //  1. tv1 = x^c4
        let tv2 = Fp.mul(tv1, c1); //  2. tv2 = c1 * tv1
        const tv3 = Fp.mul(tv1, c2); //  3. tv3 = c2 * tv1
        const tv4 = Fp.mul(tv1, c3); //  4. tv4 = c3 * tv1
        const e1 = Fp.eql(Fp.sqr(tv2), n); //  5.  e1 = (tv2^2) == x
        const e2 = Fp.eql(Fp.sqr(tv3), n); //  6.  e2 = (tv3^2) == x
        tv1 = Fp.cmov(tv1, tv2, e1); //  7. tv1 = CMOV(tv1, tv2, e1)  # Select tv2 if (tv2^2) == x
        tv2 = Fp.cmov(tv4, tv3, e2); //  8. tv2 = CMOV(tv4, tv3, e2)  # Select tv3 if (tv3^2) == x
        const e3 = Fp.eql(Fp.sqr(tv2), n); //  9.  e3 = (tv2^2) == x
        const root = Fp.cmov(tv1, tv2, e3); // 10.  z = CMOV(tv1, tv2, e3)   # Select sqrt from tv1 & tv2
        assertIsSquare(Fp, root, n);
        return root;
    };
}
/**
 * Tonelli-Shanks square root search algorithm.
 * 1. https://eprint.iacr.org/2012/685.pdf (page 12)
 * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks
 * @param P field order
 * @returns function that takes field Fp (created from P) and number n
 */
export function tonelliShanks(P) {
    // Initialization (precomputation).
    // Caching initialization could boost perf by 7%.
    if (P < _3n)
        throw new Error('sqrt is not defined for small field');
    // Factor P - 1 = Q * 2^S, where Q is odd
    let Q = P - _1n;
    let S = 0;
    while (Q % _2n === _0n) {
        Q /= _2n;
        S++;
    }
    // Find the first quadratic non-residue Z >= 2
    let Z = _2n;
    const _Fp = Field(P);
    while (FpLegendre(_Fp, Z) === 1) {
        // Basic primality test for P. After x iterations, chance of
        // not finding quadratic non-residue is 2^x, so 2^1000.
        if (Z++ > 1000)
            throw new Error('Cannot find square root: probably non-prime P');
    }
    // Fast-path; usually done before Z, but we do "primality test".
    if (S === 1)
        return sqrt3mod4;
    // Slow-path
    // TODO: test on Fp2 and others
    let cc = _Fp.pow(Z, Q); // c = z^Q
    const Q1div2 = (Q + _1n) / _2n;
    return function tonelliSlow(Fp, n) {
        if (Fp.is0(n))
            return n;
        // Check if n is a quadratic residue using Legendre symbol
        if (FpLegendre(Fp, n) !== 1)
            throw new Error('Cannot find square root');
        // Initialize variables for the main loop
        let M = S;
        let c = Fp.mul(Fp.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp
        let t = Fp.pow(n, Q); // t = n^Q, first guess at the fudge factor
        let R = Fp.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root
        // Main loop
        // while t != 1
        while (!Fp.eql(t, Fp.ONE)) {
            if (Fp.is0(t))
                return Fp.ZERO; // if t=0 return R=0
            let i = 1;
            // Find the smallest i >= 1 such that t^(2^i) ≡ 1 (mod P)
            let t_tmp = Fp.sqr(t); // t^(2^1)
            while (!Fp.eql(t_tmp, Fp.ONE)) {
                i++;
                t_tmp = Fp.sqr(t_tmp); // t^(2^2)...
                if (i === M)
                    throw new Error('Cannot find square root');
            }
            // Calculate the exponent for b: 2^(M - i - 1)
            const exponent = _1n << BigInt(M - i - 1); // bigint is important
            const b = Fp.pow(c, exponent); // b = 2^(M - i - 1)
            // Update variables
            M = i;
            c = Fp.sqr(b); // c = b^2
            t = Fp.mul(t, c); // t = (t * b^2)
            R = Fp.mul(R, b); // R = R*b
        }
        return R;
    };
}
/**
 * Square root for a finite field. Will try optimized versions first:
 *
 * 1. P ≡ 3 (mod 4)
 * 2. P ≡ 5 (mod 8)
 * 3. P ≡ 9 (mod 16)
 * 4. Tonelli-Shanks algorithm
 *
 * Different algorithms can give different roots, it is up to user to decide which one they want.
 * For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).
 */
export function FpSqrt(P) {
    // P ≡ 3 (mod 4) => √n = n^((P+1)/4)
    if (P % _4n === _3n)
        return sqrt3mod4;
    // P ≡ 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf
    if (P % _8n === _5n)
        return sqrt5mod8;
    // P ≡ 9 (mod 16) => Kong algorithm, page 11 of https://eprint.iacr.org/2012/685.pdf (algorithm 4)
    if (P % _16n === _9n)
        return sqrt9mod16(P);
    // Tonelli-Shanks algorithm
    return tonelliShanks(P);
}
// Little-endian check for first LE bit (last BE bit);
export const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n;
// prettier-ignore
const FIELD_FIELDS = [
    'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',
    'eql', 'add', 'sub', 'mul', 'pow', 'div',
    'addN', 'subN', 'mulN', 'sqrN'
];
export function validateField(field) {
    const initial = {
        ORDER: 'bigint',
        MASK: 'bigint',
        BYTES: 'number',
        BITS: 'number',
    };
    const opts = FIELD_FIELDS.reduce((map, val) => {
        map[val] = 'function';
        return map;
    }, initial);
    _validateObject(field, opts);
    // const max = 16384;
    // if (field.BYTES < 1 || field.BYTES > max) throw new Error('invalid field');
    // if (field.BITS < 1 || field.BITS > 8 * max) throw new Error('invalid field');
    return field;
}
// Generic field functions
/**
 * Same as `pow` but for Fp: non-constant-time.
 * Unsafe in some contexts: uses ladder, so can expose bigint bits.
 */
export function FpPow(Fp, num, power) {
    if (power < _0n)
        throw new Error('invalid exponent, negatives unsupported');
    if (power === _0n)
        return Fp.ONE;
    if (power === _1n)
        return num;
    let p = Fp.ONE;
    let d = num;
    while (power > _0n) {
        if (power & _1n)
            p = Fp.mul(p, d);
        d = Fp.sqr(d);
        power >>= _1n;
    }
    return p;
}
/**
 * Efficiently invert an array of Field elements.
 * Exception-free. Will return `undefined` for 0 elements.
 * @param passZero map 0 to 0 (instead of undefined)
 */
export function FpInvertBatch(Fp, nums, passZero = false) {
    const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : undefined);
    // Walk from first to last, multiply them by each other MOD p
    const multipliedAcc = nums.reduce((acc, num, i) => {
        if (Fp.is0(num))
            return acc;
        inverted[i] = acc;
        return Fp.mul(acc, num);
    }, Fp.ONE);
    // Invert last element
    const invertedAcc = Fp.inv(multipliedAcc);
    // Walk from last to first, multiply them by inverted each other MOD p
    nums.reduceRight((acc, num, i) => {
        if (Fp.is0(num))
            return acc;
        inverted[i] = Fp.mul(acc, inverted[i]);
        return Fp.mul(acc, num);
    }, invertedAcc);
    return inverted;
}
// TODO: remove
export function FpDiv(Fp, lhs, rhs) {
    return Fp.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, Fp.ORDER) : Fp.inv(rhs));
}
/**
 * Legendre symbol.
 * Legendre constant is used to calculate Legendre symbol (a | p)
 * which denotes the value of a^((p-1)/2) (mod p).
 *
 * * (a | p) ≡ 1    if a is a square (mod p), quadratic residue
 * * (a | p) ≡ -1   if a is not a square (mod p), quadratic non residue
 * * (a | p) ≡ 0    if a ≡ 0 (mod p)
 */
export function FpLegendre(Fp, n) {
    // We can use 3rd argument as optional cache of this value
    // but seems unneeded for now. The operation is very fast.
    const p1mod2 = (Fp.ORDER - _1n) / _2n;
    const powered = Fp.pow(n, p1mod2);
    const yes = Fp.eql(powered, Fp.ONE);
    const zero = Fp.eql(powered, Fp.ZERO);
    const no = Fp.eql(powered, Fp.neg(Fp.ONE));
    if (!yes && !zero && !no)
        throw new Error('invalid Legendre symbol result');
    return yes ? 1 : zero ? 0 : -1;
}
// This function returns True whenever the value x is a square in the field F.
export function FpIsSquare(Fp, n) {
    const l = FpLegendre(Fp, n);
    return l === 1;
}
// CURVE.n lengths
export function nLength(n, nBitLength) {
    // Bit size, byte size of CURVE.n
    if (nBitLength !== undefined)
        anumber(nBitLength);
    const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;
    const nByteLength = Math.ceil(_nBitLength / 8);
    return { nBitLength: _nBitLength, nByteLength };
}
/**
 * Creates a finite field. Major performance optimizations:
 * * 1. Denormalized operations like mulN instead of mul.
 * * 2. Identical object shape: never add or remove keys.
 * * 3. `Object.freeze`.
 * Fragile: always run a benchmark on a change.
 * Security note: operations don't check 'isValid' for all elements for performance reasons,
 * it is caller responsibility to check this.
 * This is low-level code, please make sure you know what you're doing.
 *
 * Note about field properties:
 * * CHARACTERISTIC p = prime number, number of elements in main subgroup.
 * * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.
 *
 * @param ORDER field order, probably prime, or could be composite
 * @param bitLen how many bits the field consumes
 * @param isLE (default: false) if encoding / decoding should be in little-endian
 * @param redef optional faster redefinitions of sqrt and other methods
 */
export function Field(ORDER, bitLenOrOpts, // TODO: use opts only in v2?
isLE = false, opts = {}) {
    if (ORDER <= _0n)
        throw new Error('invalid field: expected ORDER > 0, got ' + ORDER);
    let _nbitLength = undefined;
    let _sqrt = undefined;
    let modFromBytes = false;
    let allowedLengths = undefined;
    if (typeof bitLenOrOpts === 'object' && bitLenOrOpts != null) {
        if (opts.sqrt || isLE)
            throw new Error('cannot specify opts in two arguments');
        const _opts = bitLenOrOpts;
        if (_opts.BITS)
            _nbitLength = _opts.BITS;
        if (_opts.sqrt)
            _sqrt = _opts.sqrt;
        if (typeof _opts.isLE === 'boolean')
            isLE = _opts.isLE;
        if (typeof _opts.modFromBytes === 'boolean')
            modFromBytes = _opts.modFromBytes;
        allowedLengths = _opts.allowedLengths;
    }
    else {
        if (typeof bitLenOrOpts === 'number')
            _nbitLength = bitLenOrOpts;
        if (opts.sqrt)
            _sqrt = opts.sqrt;
    }
    const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, _nbitLength);
    if (BYTES > 2048)
        throw new Error('invalid field: expected ORDER of <= 2048 bytes');
    let sqrtP; // cached sqrtP
    const f = Object.freeze({
        ORDER,
        isLE,
        BITS,
        BYTES,
        MASK: bitMask(BITS),
        ZERO: _0n,
        ONE: _1n,
        allowedLengths: allowedLengths,
        create: (num) => mod(num, ORDER),
        isValid: (num) => {
            if (typeof num !== 'bigint')
                throw new Error('invalid field element: expected bigint, got ' + typeof num);
            return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible
        },
        is0: (num) => num === _0n,
        // is valid and invertible
        isValidNot0: (num) => !f.is0(num) && f.isValid(num),
        isOdd: (num) => (num & _1n) === _1n,
        neg: (num) => mod(-num, ORDER),
        eql: (lhs, rhs) => lhs === rhs,
        sqr: (num) => mod(num * num, ORDER),
        add: (lhs, rhs) => mod(lhs + rhs, ORDER),
        sub: (lhs, rhs) => mod(lhs - rhs, ORDER),
        mul: (lhs, rhs) => mod(lhs * rhs, ORDER),
        pow: (num, power) => FpPow(f, num, power),
        div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),
        // Same as above, but doesn't normalize
        sqrN: (num) => num * num,
        addN: (lhs, rhs) => lhs + rhs,
        subN: (lhs, rhs) => lhs - rhs,
        mulN: (lhs, rhs) => lhs * rhs,
        inv: (num) => invert(num, ORDER),
        sqrt: _sqrt ||
            ((n) => {
                if (!sqrtP)
                    sqrtP = FpSqrt(ORDER);
                return sqrtP(f, n);
            }),
        toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),
        fromBytes: (bytes, skipValidation = true) => {
            if (allowedLengths) {
                if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
                    throw new Error('Field.fromBytes: expected ' + allowedLengths + ' bytes, got ' + bytes.length);
                }
                const padded = new Uint8Array(BYTES);
                // isLE add 0 to right, !isLE to the left.
                padded.set(bytes, isLE ? 0 : padded.length - bytes.length);
                bytes = padded;
            }
            if (bytes.length !== BYTES)
                throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);
            let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
            if (modFromBytes)
                scalar = mod(scalar, ORDER);
            if (!skipValidation)
                if (!f.isValid(scalar))
                    throw new Error('invalid field element: outside of range 0..ORDER');
            // NOTE: we don't validate scalar here, please use isValid. This done such way because some
            // protocol may allow non-reduced scalar that reduced later or changed some other way.
            return scalar;
        },
        // TODO: we don't need it here, move out to separate fn
        invertBatch: (lst) => FpInvertBatch(f, lst),
        // We can't move this out because Fp6, Fp12 implement it
        // and it's unclear what to return in there.
        cmov: (a, b, c) => (c ? b : a),
    });
    return Object.freeze(f);
}
// Generic random scalar, we can do same for other fields if via Fp2.mul(Fp2.ONE, Fp2.random)?
// This allows unsafe methods like ignore bias or zero. These unsafe, but often used in different protocols (if deterministic RNG).
// which mean we cannot force this via opts.
// Not sure what to do with randomBytes, we can accept it inside opts if wanted.
// Probably need to export getMinHashLength somewhere?
// random(bytes?: Uint8Array, unsafeAllowZero = false, unsafeAllowBias = false) {
//   const LEN = !unsafeAllowBias ? getMinHashLength(ORDER) : BYTES;
//   if (bytes === undefined) bytes = randomBytes(LEN); // _opts.randomBytes?
//   const num = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
//   // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0
//   const reduced = unsafeAllowZero ? mod(num, ORDER) : mod(num, ORDER - _1n) + _1n;
//   return reduced;
// },
export function FpSqrtOdd(Fp, elm) {
    if (!Fp.isOdd)
        throw new Error("Field doesn't have isOdd");
    const root = Fp.sqrt(elm);
    return Fp.isOdd(root) ? root : Fp.neg(root);
}
export function FpSqrtEven(Fp, elm) {
    if (!Fp.isOdd)
        throw new Error("Field doesn't have isOdd");
    const root = Fp.sqrt(elm);
    return Fp.isOdd(root) ? Fp.neg(root) : root;
}
/**
 * "Constant-time" private key generation utility.
 * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field).
 * Which makes it slightly more biased, less secure.
 * @deprecated use `mapKeyToField` instead
 */
export function hashToPrivateScalar(hash, groupOrder, isLE = false) {
    hash = ensureBytes('privateHash', hash);
    const hashLen = hash.length;
    const minLen = nLength(groupOrder).nByteLength + 8;
    if (minLen < 24 || hashLen < minLen || hashLen > 1024)
        throw new Error('hashToPrivateScalar: expected ' + minLen + '-1024 bytes of input, got ' + hashLen);
    const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash);
    return mod(num, groupOrder - _1n) + _1n;
}
/**
 * Returns total number of bytes consumed by the field element.
 * For example, 32 bytes for usual 256-bit weierstrass curve.
 * @param fieldOrder number of field elements, usually CURVE.n
 * @returns byte length of field
 */
export function getFieldBytesLength(fieldOrder) {
    if (typeof fieldOrder !== 'bigint')
        throw new Error('field order must be bigint');
    const bitLength = fieldOrder.toString(2).length;
    return Math.ceil(bitLength / 8);
}
/**
 * Returns minimal amount of bytes that can be safely reduced
 * by field order.
 * Should be 2^-128 for 128-bit curve such as P256.
 * @param fieldOrder number of field elements, usually CURVE.n
 * @returns byte length of target hash
 */
export function getMinHashLength(fieldOrder) {
    const length = getFieldBytesLength(fieldOrder);
    return length + Math.ceil(length / 2);
}
/**
 * "Constant-time" private key generation utility.
 * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF
 * and convert them into private scalar, with the modulo bias being negligible.
 * Needs at least 48 bytes of input for 32-byte private key.
 * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/
 * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final
 * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5
 * @param hash hash output from SHA3 or a similar function
 * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)
 * @param isLE interpret hash bytes as LE num
 * @returns valid private scalar
 */
export function mapHashToField(key, fieldOrder, isLE = false) {
    const len = key.length;
    const fieldLen = getFieldBytesLength(fieldOrder);
    const minLen = getMinHashLength(fieldOrder);
    // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.
    if (len < 16 || len < minLen || len > 1024)
        throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);
    const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);
    // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0
    const reduced = mod(num, fieldOrder - _1n) + _1n;
    return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
}
//# sourceMappingURL=modular.js.map/**
 * Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.
 *
 * ### Design rationale for types
 *
 * * Interaction between classes from different curves should fail:
 *   `k256.Point.BASE.add(p256.Point.BASE)`
 * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime
 * * Different calls of `curve()` would return different classes -
 *   `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,
 *   it won't affect others
 *
 * TypeScript can't infer types for classes created inside a function. Classes is one instance
 * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create
 * unique type for every function call.
 *
 * We can use generic types via some param, like curve opts, but that would:
 *     1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)
 *     which is hard to debug.
 *     2. Params can be generic and we can't enforce them to be constant value:
 *     if somebody creates curve from non-constant params,
 *     it would be allowed to interact with other curves with non-constant params
 *
 * @todo https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { hmac as nobleHmac } from '@noble/hashes/hmac.js';
import { ahash } from '@noble/hashes/utils';
import { _validateObject, _abool2 as abool, _abytes2 as abytes, aInRange, bitLen, bitMask, bytesToHex, bytesToNumberBE, concatBytes, createHmacDrbg, ensureBytes, hexToBytes, inRange, isBytes, memoized, numberToHexUnpadded, randomBytes as randomBytesWeb, } from "../utils.js";
import { _createCurveFields, mulEndoUnsafe, negateCt, normalizeZ, pippenger, wNAF, } from "./curve.js";
import { Field, FpInvertBatch, getMinHashLength, mapHashToField, nLength, validateField, } from "./modular.js";
// We construct basis in such way that den is always positive and equals n, but num sign depends on basis (not on secret value)
const divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n) / den;
/**
 * Splits scalar for GLV endomorphism.
 */
export function _splitEndoScalar(k, basis, n) {
    // Split scalar into two such that part is ~half bits: `abs(part) < sqrt(N)`
    // Since part can be negative, we need to do this on point.
    // TODO: verifyScalar function which consumes lambda
    const [[a1, b1], [a2, b2]] = basis;
    const c1 = divNearest(b2 * k, n);
    const c2 = divNearest(-b1 * k, n);
    // |k1|/|k2| is < sqrt(N), but can be negative.
    // If we do `k1 mod N`, we'll get big scalar (`> sqrt(N)`): so, we do cheaper negation instead.
    let k1 = k - c1 * a1 - c2 * a2;
    let k2 = -c1 * b1 - c2 * b2;
    const k1neg = k1 < _0n;
    const k2neg = k2 < _0n;
    if (k1neg)
        k1 = -k1;
    if (k2neg)
        k2 = -k2;
    // Double check that resulting scalar less than half bits of N: otherwise wNAF will fail.
    // This should only happen on wrong basises. Also, math inside is too complex and I don't trust it.
    const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n; // Half bits of N
    if (k1 < _0n || k1 >= MAX_NUM || k2 < _0n || k2 >= MAX_NUM) {
        throw new Error('splitScalar (endomorphism): failed, k=' + k);
    }
    return { k1neg, k1, k2neg, k2 };
}
function validateSigFormat(format) {
    if (!['compact', 'recovered', 'der'].includes(format))
        throw new Error('Signature format must be "compact", "recovered", or "der"');
    return format;
}
function validateSigOpts(opts, def) {
    const optsn = {};
    for (let optName of Object.keys(def)) {
        // @ts-ignore
        optsn[optName] = opts[optName] === undefined ? def[optName] : opts[optName];
    }
    abool(optsn.lowS, 'lowS');
    abool(optsn.prehash, 'prehash');
    if (optsn.format !== undefined)
        validateSigFormat(optsn.format);
    return optsn;
}
export class DERErr extends Error {
    constructor(m = '') {
        super(m);
    }
}
/**
 * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:
 *
 *     [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]
 *
 * Docs: https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/, https://luca.ntop.org/Teaching/Appunti/asn1.html
 */
export const DER = {
    // asn.1 DER encoding utils
    Err: DERErr,
    // Basic building block is TLV (Tag-Length-Value)
    _tlv: {
        encode: (tag, data) => {
            const { Err: E } = DER;
            if (tag < 0 || tag > 256)
                throw new E('tlv.encode: wrong tag');
            if (data.length & 1)
                throw new E('tlv.encode: unpadded data');
            const dataLen = data.length / 2;
            const len = numberToHexUnpadded(dataLen);
            if ((len.length / 2) & 128)
                throw new E('tlv.encode: long form length too big');
            // length of length with long form flag
            const lenLen = dataLen > 127 ? numberToHexUnpadded((len.length / 2) | 128) : '';
            const t = numberToHexUnpadded(tag);
            return t + lenLen + len + data;
        },
        // v - value, l - left bytes (unparsed)
        decode(tag, data) {
            const { Err: E } = DER;
            let pos = 0;
            if (tag < 0 || tag > 256)
                throw new E('tlv.encode: wrong tag');
            if (data.length < 2 || data[pos++] !== tag)
                throw new E('tlv.decode: wrong tlv');
            const first = data[pos++];
            const isLong = !!(first & 128); // First bit of first length byte is flag for short/long form
            let length = 0;
            if (!isLong)
                length = first;
            else {
                // Long form: [longFlag(1bit), lengthLength(7bit), length (BE)]
                const lenLen = first & 127;
                if (!lenLen)
                    throw new E('tlv.decode(long): indefinite length not supported');
                if (lenLen > 4)
                    throw new E('tlv.decode(long): byte length is too big'); // this will overflow u32 in js
                const lengthBytes = data.subarray(pos, pos + lenLen);
                if (lengthBytes.length !== lenLen)
                    throw new E('tlv.decode: length bytes not complete');
                if (lengthBytes[0] === 0)
                    throw new E('tlv.decode(long): zero leftmost byte');
                for (const b of lengthBytes)
                    length = (length << 8) | b;
                pos += lenLen;
                if (length < 128)
                    throw new E('tlv.decode(long): not minimal encoding');
            }
            const v = data.subarray(pos, pos + length);
            if (v.length !== length)
                throw new E('tlv.decode: wrong value length');
            return { v, l: data.subarray(pos + length) };
        },
    },
    // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
    // since we always use positive integers here. It must always be empty:
    // - add zero byte if exists
    // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
    _int: {
        encode(num) {
            const { Err: E } = DER;
            if (num < _0n)
                throw new E('integer: negative integers are not allowed');
            let hex = numberToHexUnpadded(num);
            // Pad with zero byte if negative flag is present
            if (Number.parseInt(hex[0], 16) & 0b1000)
                hex = '00' + hex;
            if (hex.length & 1)
                throw new E('unexpected DER parsing assertion: unpadded hex');
            return hex;
        },
        decode(data) {
            const { Err: E } = DER;
            if (data[0] & 128)
                throw new E('invalid signature integer: negative');
            if (data[0] === 0x00 && !(data[1] & 128))
                throw new E('invalid signature integer: unnecessary leading zero');
            return bytesToNumberBE(data);
        },
    },
    toSig(hex) {
        // parse DER signature
        const { Err: E, _int: int, _tlv: tlv } = DER;
        const data = ensureBytes('signature', hex);
        const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);
        if (seqLeftBytes.length)
            throw new E('invalid signature: left bytes after parsing');
        const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);
        const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);
        if (sLeftBytes.length)
            throw new E('invalid signature: left bytes after parsing');
        return { r: int.decode(rBytes), s: int.decode(sBytes) };
    },
    hexFromSig(sig) {
        const { _tlv: tlv, _int: int } = DER;
        const rs = tlv.encode(0x02, int.encode(sig.r));
        const ss = tlv.encode(0x02, int.encode(sig.s));
        const seq = rs + ss;
        return tlv.encode(0x30, seq);
    },
};
// Be friendly to bad ECMAScript parsers by not using bigint literals
// prettier-ignore
const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4);
export function _normFnElement(Fn, key) {
    const { BYTES: expected } = Fn;
    let num;
    if (typeof key === 'bigint') {
        num = key;
    }
    else {
        let bytes = ensureBytes('private key', key);
        try {
            num = Fn.fromBytes(bytes);
        }
        catch (error) {
            throw new Error(`invalid private key: expected ui8a of size ${expected}, got ${typeof key}`);
        }
    }
    if (!Fn.isValidNot0(num))
        throw new Error('invalid private key: out of range [1..N-1]');
    return num;
}
/**
 * Creates weierstrass Point constructor, based on specified curve options.
 *
 * @example
```js
const opts = {
  p: BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff'),
  n: BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551'),
  h: BigInt(1),
  a: BigInt('0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc'),
  b: BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b'),
  Gx: BigInt('0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296'),
  Gy: BigInt('0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5'),
};
const p256_Point = weierstrass(opts);
```
 */
export function weierstrassN(params, extraOpts = {}) {
    const validated = _createCurveFields('weierstrass', params, extraOpts);
    const { Fp, Fn } = validated;
    let CURVE = validated.CURVE;
    const { h: cofactor, n: CURVE_ORDER } = CURVE;
    _validateObject(extraOpts, {}, {
        allowInfinityPoint: 'boolean',
        clearCofactor: 'function',
        isTorsionFree: 'function',
        fromBytes: 'function',
        toBytes: 'function',
        endo: 'object',
        wrapPrivateKey: 'boolean',
    });
    const { endo } = extraOpts;
    if (endo) {
        // validateObject(endo, { beta: 'bigint', splitScalar: 'function' });
        if (!Fp.is0(CURVE.a) || typeof endo.beta !== 'bigint' || !Array.isArray(endo.basises)) {
            throw new Error('invalid endo: expected "beta": bigint and "basises": array');
        }
    }
    const lengths = getWLengths(Fp, Fn);
    function assertCompressionIsSupported() {
        if (!Fp.isOdd)
            throw new Error('compression is not supported: Field does not have .isOdd()');
    }
    // Implements IEEE P1363 point encoding
    function pointToBytes(_c, point, isCompressed) {
        const { x, y } = point.toAffine();
        const bx = Fp.toBytes(x);
        abool(isCompressed, 'isCompressed');
        if (isCompressed) {
            assertCompressionIsSupported();
            const hasEvenY = !Fp.isOdd(y);
            return concatBytes(pprefix(hasEvenY), bx);
        }
        else {
            return concatBytes(Uint8Array.of(0x04), bx, Fp.toBytes(y));
        }
    }
    function pointFromBytes(bytes) {
        abytes(bytes, undefined, 'Point');
        const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths; // e.g. for 32-byte: 33, 65
        const length = bytes.length;
        const head = bytes[0];
        const tail = bytes.subarray(1);
        // No actual validation is done here: use .assertValidity()
        if (length === comp && (head === 0x02 || head === 0x03)) {
            const x = Fp.fromBytes(tail);
            if (!Fp.isValid(x))
                throw new Error('bad point: is not on curve, wrong x');
            const y2 = weierstrassEquation(x); // y² = x³ + ax + b
            let y;
            try {
                y = Fp.sqrt(y2); // y = y² ^ (p+1)/4
            }
            catch (sqrtError) {
                const err = sqrtError instanceof Error ? ': ' + sqrtError.message : '';
                throw new Error('bad point: is not on curve, sqrt error' + err);
            }
            assertCompressionIsSupported();
            const isYOdd = Fp.isOdd(y); // (y & _1n) === _1n;
            const isHeadOdd = (head & 1) === 1; // ECDSA-specific
            if (isHeadOdd !== isYOdd)
                y = Fp.neg(y);
            return { x, y };
        }
        else if (length === uncomp && head === 0x04) {
            // TODO: more checks
            const L = Fp.BYTES;
            const x = Fp.fromBytes(tail.subarray(0, L));
            const y = Fp.fromBytes(tail.subarray(L, L * 2));
            if (!isValidXY(x, y))
                throw new Error('bad point: is not on curve');
            return { x, y };
        }
        else {
            throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);
        }
    }
    const encodePoint = extraOpts.toBytes || pointToBytes;
    const decodePoint = extraOpts.fromBytes || pointFromBytes;
    function weierstrassEquation(x) {
        const x2 = Fp.sqr(x); // x * x
        const x3 = Fp.mul(x2, x); // x² * x
        return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b); // x³ + a * x + b
    }
    // TODO: move top-level
    /** Checks whether equation holds for given x, y: y² == x³ + ax + b */
    function isValidXY(x, y) {
        const left = Fp.sqr(y); // y²
        const right = weierstrassEquation(x); // x³ + ax + b
        return Fp.eql(left, right);
    }
    // Validate whether the passed curve params are valid.
    // Test 1: equation y² = x³ + ax + b should work for generator point.
    if (!isValidXY(CURVE.Gx, CURVE.Gy))
        throw new Error('bad curve params: generator point');
    // Test 2: discriminant Δ part should be non-zero: 4a³ + 27b² != 0.
    // Guarantees curve is genus-1, smooth (non-singular).
    const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n), _4n);
    const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));
    if (Fp.is0(Fp.add(_4a3, _27b2)))
        throw new Error('bad curve params: a or b');
    /** Asserts coordinate is valid: 0 <= n < Fp.ORDER. */
    function acoord(title, n, banZero = false) {
        if (!Fp.isValid(n) || (banZero && Fp.is0(n)))
            throw new Error(`bad point coordinate ${title}`);
        return n;
    }
    function aprjpoint(other) {
        if (!(other instanceof Point))
            throw new Error('ProjectivePoint expected');
    }
    function splitEndoScalarN(k) {
        if (!endo || !endo.basises)
            throw new Error('no endo');
        return _splitEndoScalar(k, endo.basises, Fn.ORDER);
    }
    // Memoized toAffine / validity check. They are heavy. Points are immutable.
    // Converts Projective point to affine (x, y) coordinates.
    // Can accept precomputed Z^-1 - for example, from invertBatch.
    // (X, Y, Z) ∋ (x=X/Z, y=Y/Z)
    const toAffineMemo = memoized((p, iz) => {
        const { X, Y, Z } = p;
        // Fast-path for normalized points
        if (Fp.eql(Z, Fp.ONE))
            return { x: X, y: Y };
        const is0 = p.is0();
        // If invZ was 0, we return zero point. However we still want to execute
        // all operations, so we replace invZ with a random number, 1.
        if (iz == null)
            iz = is0 ? Fp.ONE : Fp.inv(Z);
        const x = Fp.mul(X, iz);
        const y = Fp.mul(Y, iz);
        const zz = Fp.mul(Z, iz);
        if (is0)
            return { x: Fp.ZERO, y: Fp.ZERO };
        if (!Fp.eql(zz, Fp.ONE))
            throw new Error('invZ was invalid');
        return { x, y };
    });
    // NOTE: on exception this will crash 'cached' and no value will be set.
    // Otherwise true will be return
    const assertValidMemo = memoized((p) => {
        if (p.is0()) {
            // (0, 1, 0) aka ZERO is invalid in most contexts.
            // In BLS, ZERO can be serialized, so we allow it.
            // (0, 0, 0) is invalid representation of ZERO.
            if (extraOpts.allowInfinityPoint && !Fp.is0(p.Y))
                return;
            throw new Error('bad point: ZERO');
        }
        // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`
        const { x, y } = p.toAffine();
        if (!Fp.isValid(x) || !Fp.isValid(y))
            throw new Error('bad point: x or y not field elements');
        if (!isValidXY(x, y))
            throw new Error('bad point: equation left != right');
        if (!p.isTorsionFree())
            throw new Error('bad point: not in prime-order subgroup');
        return true;
    });
    function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) {
        k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);
        k1p = negateCt(k1neg, k1p);
        k2p = negateCt(k2neg, k2p);
        return k1p.add(k2p);
    }
    /**
     * Projective Point works in 3d / projective (homogeneous) coordinates:(X, Y, Z) ∋ (x=X/Z, y=Y/Z).
     * Default Point works in 2d / affine coordinates: (x, y).
     * We're doing calculations in projective, because its operations don't require costly inversion.
     */
    class Point {
        /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
        constructor(X, Y, Z) {
            this.X = acoord('x', X);
            this.Y = acoord('y', Y, true);
            this.Z = acoord('z', Z);
            Object.freeze(this);
        }
        static CURVE() {
            return CURVE;
        }
        /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
        static fromAffine(p) {
            const { x, y } = p || {};
            if (!p || !Fp.isValid(x) || !Fp.isValid(y))
                throw new Error('invalid affine point');
            if (p instanceof Point)
                throw new Error('projective point not allowed');
            // (0, 0) would've produced (0, 0, 1) - instead, we need (0, 1, 0)
            if (Fp.is0(x) && Fp.is0(y))
                return Point.ZERO;
            return new Point(x, y, Fp.ONE);
        }
        static fromBytes(bytes) {
            const P = Point.fromAffine(decodePoint(abytes(bytes, undefined, 'point')));
            P.assertValidity();
            return P;
        }
        static fromHex(hex) {
            return Point.fromBytes(ensureBytes('pointHex', hex));
        }
        get x() {
            return this.toAffine().x;
        }
        get y() {
            return this.toAffine().y;
        }
        /**
         *
         * @param windowSize
         * @param isLazy true will defer table computation until the first multiplication
         * @returns
         */
        precompute(windowSize = 8, isLazy = true) {
            wnaf.createCache(this, windowSize);
            if (!isLazy)
                this.multiply(_3n); // random number
            return this;
        }
        // TODO: return `this`
        /** A point on curve is valid if it conforms to equation. */
        assertValidity() {
            assertValidMemo(this);
        }
        hasEvenY() {
            const { y } = this.toAffine();
            if (!Fp.isOdd)
                throw new Error("Field doesn't support isOdd");
            return !Fp.isOdd(y);
        }
        /** Compare one point to another. */
        equals(other) {
            aprjpoint(other);
            const { X: X1, Y: Y1, Z: Z1 } = this;
            const { X: X2, Y: Y2, Z: Z2 } = other;
            const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
            const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
            return U1 && U2;
        }
        /** Flips point to one corresponding to (x, -y) in Affine coordinates. */
        negate() {
            return new Point(this.X, Fp.neg(this.Y), this.Z);
        }
        // Renes-Costello-Batina exception-free doubling formula.
        // There is 30% faster Jacobian formula, but it is not complete.
        // https://eprint.iacr.org/2015/1060, algorithm 3
        // Cost: 8M + 3S + 3*a + 2*b3 + 15add.
        double() {
            const { a, b } = CURVE;
            const b3 = Fp.mul(b, _3n);
            const { X: X1, Y: Y1, Z: Z1 } = this;
            let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore
            let t0 = Fp.mul(X1, X1); // step 1
            let t1 = Fp.mul(Y1, Y1);
            let t2 = Fp.mul(Z1, Z1);
            let t3 = Fp.mul(X1, Y1);
            t3 = Fp.add(t3, t3); // step 5
            Z3 = Fp.mul(X1, Z1);
            Z3 = Fp.add(Z3, Z3);
            X3 = Fp.mul(a, Z3);
            Y3 = Fp.mul(b3, t2);
            Y3 = Fp.add(X3, Y3); // step 10
            X3 = Fp.sub(t1, Y3);
            Y3 = Fp.add(t1, Y3);
            Y3 = Fp.mul(X3, Y3);
            X3 = Fp.mul(t3, X3);
            Z3 = Fp.mul(b3, Z3); // step 15
            t2 = Fp.mul(a, t2);
            t3 = Fp.sub(t0, t2);
            t3 = Fp.mul(a, t3);
            t3 = Fp.add(t3, Z3);
            Z3 = Fp.add(t0, t0); // step 20
            t0 = Fp.add(Z3, t0);
            t0 = Fp.add(t0, t2);
            t0 = Fp.mul(t0, t3);
            Y3 = Fp.add(Y3, t0);
            t2 = Fp.mul(Y1, Z1); // step 25
            t2 = Fp.add(t2, t2);
            t0 = Fp.mul(t2, t3);
            X3 = Fp.sub(X3, t0);
            Z3 = Fp.mul(t2, t1);
            Z3 = Fp.add(Z3, Z3); // step 30
            Z3 = Fp.add(Z3, Z3);
            return new Point(X3, Y3, Z3);
        }
        // Renes-Costello-Batina exception-free addition formula.
        // There is 30% faster Jacobian formula, but it is not complete.
        // https://eprint.iacr.org/2015/1060, algorithm 1
        // Cost: 12M + 0S + 3*a + 3*b3 + 23add.
        add(other) {
            aprjpoint(other);
            const { X: X1, Y: Y1, Z: Z1 } = this;
            const { X: X2, Y: Y2, Z: Z2 } = other;
            let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore
            const a = CURVE.a;
            const b3 = Fp.mul(CURVE.b, _3n);
            let t0 = Fp.mul(X1, X2); // step 1
            let t1 = Fp.mul(Y1, Y2);
            let t2 = Fp.mul(Z1, Z2);
            let t3 = Fp.add(X1, Y1);
            let t4 = Fp.add(X2, Y2); // step 5
            t3 = Fp.mul(t3, t4);
            t4 = Fp.add(t0, t1);
            t3 = Fp.sub(t3, t4);
            t4 = Fp.add(X1, Z1);
            let t5 = Fp.add(X2, Z2); // step 10
            t4 = Fp.mul(t4, t5);
            t5 = Fp.add(t0, t2);
            t4 = Fp.sub(t4, t5);
            t5 = Fp.add(Y1, Z1);
            X3 = Fp.add(Y2, Z2); // step 15
            t5 = Fp.mul(t5, X3);
            X3 = Fp.add(t1, t2);
            t5 = Fp.sub(t5, X3);
            Z3 = Fp.mul(a, t4);
            X3 = Fp.mul(b3, t2); // step 20
            Z3 = Fp.add(X3, Z3);
            X3 = Fp.sub(t1, Z3);
            Z3 = Fp.add(t1, Z3);
            Y3 = Fp.mul(X3, Z3);
            t1 = Fp.add(t0, t0); // step 25
            t1 = Fp.add(t1, t0);
            t2 = Fp.mul(a, t2);
            t4 = Fp.mul(b3, t4);
            t1 = Fp.add(t1, t2);
            t2 = Fp.sub(t0, t2); // step 30
            t2 = Fp.mul(a, t2);
            t4 = Fp.add(t4, t2);
            t0 = Fp.mul(t1, t4);
            Y3 = Fp.add(Y3, t0);
            t0 = Fp.mul(t5, t4); // step 35
            X3 = Fp.mul(t3, X3);
            X3 = Fp.sub(X3, t0);
            t0 = Fp.mul(t3, t1);
            Z3 = Fp.mul(t5, Z3);
            Z3 = Fp.add(Z3, t0); // step 40
            return new Point(X3, Y3, Z3);
        }
        subtract(other) {
            return this.add(other.negate());
        }
        is0() {
            return this.equals(Point.ZERO);
        }
        /**
         * Constant time multiplication.
         * Uses wNAF method. Windowed method may be 10% faster,
         * but takes 2x longer to generate and consumes 2x memory.
         * Uses precomputes when available.
         * Uses endomorphism for Koblitz curves.
         * @param scalar by which the point would be multiplied
         * @returns New point
         */
        multiply(scalar) {
            const { endo } = extraOpts;
            if (!Fn.isValidNot0(scalar))
                throw new Error('invalid scalar: out of range'); // 0 is invalid
            let point, fake; // Fake point is used to const-time mult
            const mul = (n) => wnaf.cached(this, n, (p) => normalizeZ(Point, p));
            /** See docs for {@link EndomorphismOpts} */
            if (endo) {
                const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);
                const { p: k1p, f: k1f } = mul(k1);
                const { p: k2p, f: k2f } = mul(k2);
                fake = k1f.add(k2f);
                point = finishEndo(endo.beta, k1p, k2p, k1neg, k2neg);
            }
            else {
                const { p, f } = mul(scalar);
                point = p;
                fake = f;
            }
            // Normalize `z` for both points, but return only real one
            return normalizeZ(Point, [point, fake])[0];
        }
        /**
         * Non-constant-time multiplication. Uses double-and-add algorithm.
         * It's faster, but should only be used when you don't care about
         * an exposed secret key e.g. sig verification, which works over *public* keys.
         */
        multiplyUnsafe(sc) {
            const { endo } = extraOpts;
            const p = this;
            if (!Fn.isValid(sc))
                throw new Error('invalid scalar: out of range'); // 0 is valid
            if (sc === _0n || p.is0())
                return Point.ZERO;
            if (sc === _1n)
                return p; // fast-path
            if (wnaf.hasCache(this))
                return this.multiply(sc);
            if (endo) {
                const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);
                const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2); // 30% faster vs wnaf.unsafe
                return finishEndo(endo.beta, p1, p2, k1neg, k2neg);
            }
            else {
                return wnaf.unsafe(p, sc);
            }
        }
        multiplyAndAddUnsafe(Q, a, b) {
            const sum = this.multiplyUnsafe(a).add(Q.multiplyUnsafe(b));
            return sum.is0() ? undefined : sum;
        }
        /**
         * Converts Projective point to affine (x, y) coordinates.
         * @param invertedZ Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch
         */
        toAffine(invertedZ) {
            return toAffineMemo(this, invertedZ);
        }
        /**
         * Checks whether Point is free of torsion elements (is in prime subgroup).
         * Always torsion-free for cofactor=1 curves.
         */
        isTorsionFree() {
            const { isTorsionFree } = extraOpts;
            if (cofactor === _1n)
                return true;
            if (isTorsionFree)
                return isTorsionFree(Point, this);
            return wnaf.unsafe(this, CURVE_ORDER).is0();
        }
        clearCofactor() {
            const { clearCofactor } = extraOpts;
            if (cofactor === _1n)
                return this; // Fast-path
            if (clearCofactor)
                return clearCofactor(Point, this);
            return this.multiplyUnsafe(cofactor);
        }
        isSmallOrder() {
            // can we use this.clearCofactor()?
            return this.multiplyUnsafe(cofactor).is0();
        }
        toBytes(isCompressed = true) {
            abool(isCompressed, 'isCompressed');
            this.assertValidity();
            return encodePoint(Point, this, isCompressed);
        }
        toHex(isCompressed = true) {
            return bytesToHex(this.toBytes(isCompressed));
        }
        toString() {
            return `<Point ${this.is0() ? 'ZERO' : this.toHex()}>`;
        }
        // TODO: remove
        get px() {
            return this.X;
        }
        get py() {
            return this.X;
        }
        get pz() {
            return this.Z;
        }
        toRawBytes(isCompressed = true) {
            return this.toBytes(isCompressed);
        }
        _setWindowSize(windowSize) {
            this.precompute(windowSize);
        }
        static normalizeZ(points) {
            return normalizeZ(Point, points);
        }
        static msm(points, scalars) {
            return pippenger(Point, Fn, points, scalars);
        }
        static fromPrivateKey(privateKey) {
            return Point.BASE.multiply(_normFnElement(Fn, privateKey));
        }
    }
    // base / generator point
    Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
    // zero / infinity / identity point
    Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); // 0, 1, 0
    // math field
    Point.Fp = Fp;
    // scalar field
    Point.Fn = Fn;
    const bits = Fn.BITS;
    const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);
    Point.BASE.precompute(8); // Enable precomputes. Slows down first publicKey computation by 20ms.
    return Point;
}
// Points start with byte 0x02 when y is even; otherwise 0x03
function pprefix(hasEvenY) {
    return Uint8Array.of(hasEvenY ? 0x02 : 0x03);
}
/**
 * Implementation of the Shallue and van de Woestijne method for any weierstrass curve.
 * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular.
 * b = True and y = sqrt(u / v) if (u / v) is square in F, and
 * b = False and y = sqrt(Z * (u / v)) otherwise.
 * @param Fp
 * @param Z
 * @returns
 */
export function SWUFpSqrtRatio(Fp, Z) {
    // Generic implementation
    const q = Fp.ORDER;
    let l = _0n;
    for (let o = q - _1n; o % _2n === _0n; o /= _2n)
        l += _1n;
    const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1.
    // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<.
    // 2n ** c1 == 2n << (c1-1)
    const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n);
    const _2n_pow_c1 = _2n_pow_c1_1 * _2n;
    const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1)  # Integer arithmetic
    const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2            # Integer arithmetic
    const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1                # Integer arithmetic
    const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1)                  # Integer arithmetic
    const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2
    const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2)
    let sqrtRatio = (u, v) => {
        let tv1 = c6; // 1. tv1 = c6
        let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4
        let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2
        tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v
        let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3
        tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3
        tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2
        tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v
        tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u
        let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2
        tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5
        let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1
        tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7
        tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1
        tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR)
        tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR)
        // 17. for i in (c1, c1 - 1, ..., 2):
        for (let i = c1; i > _1n; i--) {
            let tv5 = i - _2n; // 18.    tv5 = i - 2
            tv5 = _2n << (tv5 - _1n); // 19.    tv5 = 2^tv5
            let tvv5 = Fp.pow(tv4, tv5); // 20.    tv5 = tv4^tv5
            const e1 = Fp.eql(tvv5, Fp.ONE); // 21.    e1 = tv5 == 1
            tv2 = Fp.mul(tv3, tv1); // 22.    tv2 = tv3 * tv1
            tv1 = Fp.mul(tv1, tv1); // 23.    tv1 = tv1 * tv1
            tvv5 = Fp.mul(tv4, tv1); // 24.    tv5 = tv4 * tv1
            tv3 = Fp.cmov(tv2, tv3, e1); // 25.    tv3 = CMOV(tv2, tv3, e1)
            tv4 = Fp.cmov(tvv5, tv4, e1); // 26.    tv4 = CMOV(tv5, tv4, e1)
        }
        return { isValid: isQR, value: tv3 };
    };
    if (Fp.ORDER % _4n === _3n) {
        // sqrt_ratio_3mod4(u, v)
        const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4     # Integer arithmetic
        const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z)
        sqrtRatio = (u, v) => {
            let tv1 = Fp.sqr(v); // 1. tv1 = v^2
            const tv2 = Fp.mul(u, v); // 2. tv2 = u * v
            tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2
            let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1
            y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2
            const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2
            const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v
            const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u
            let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR)
            return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2
        };
    }
    // No curves uses that
    // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8
    return sqrtRatio;
}
/**
 * Simplified Shallue-van de Woestijne-Ulas Method
 * https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2
 */
export function mapToCurveSimpleSWU(Fp, opts) {
    validateField(Fp);
    const { A, B, Z } = opts;
    if (!Fp.isValid(A) || !Fp.isValid(B) || !Fp.isValid(Z))
        throw new Error('mapToCurveSimpleSWU: invalid opts');
    const sqrtRatio = SWUFpSqrtRatio(Fp, Z);
    if (!Fp.isOdd)
        throw new Error('Field does not have .isOdd()');
    // Input: u, an element of F.
    // Output: (x, y), a point on E.
    return (u) => {
        // prettier-ignore
        let tv1, tv2, tv3, tv4, tv5, tv6, x, y;
        tv1 = Fp.sqr(u); // 1.  tv1 = u^2
        tv1 = Fp.mul(tv1, Z); // 2.  tv1 = Z * tv1
        tv2 = Fp.sqr(tv1); // 3.  tv2 = tv1^2
        tv2 = Fp.add(tv2, tv1); // 4.  tv2 = tv2 + tv1
        tv3 = Fp.add(tv2, Fp.ONE); // 5.  tv3 = tv2 + 1
        tv3 = Fp.mul(tv3, B); // 6.  tv3 = B * tv3
        tv4 = Fp.cmov(Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7.  tv4 = CMOV(Z, -tv2, tv2 != 0)
        tv4 = Fp.mul(tv4, A); // 8.  tv4 = A * tv4
        tv2 = Fp.sqr(tv3); // 9.  tv2 = tv3^2
        tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2
        tv5 = Fp.mul(tv6, A); // 11. tv5 = A * tv6
        tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5
        tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3
        tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4
        tv5 = Fp.mul(tv6, B); // 15. tv5 = B * tv6
        tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5
        x = Fp.mul(tv1, tv3); // 17.   x = tv1 * tv3
        const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6)
        y = Fp.mul(tv1, u); // 19.   y = tv1 * u  -> Z * u^3 * y1
        y = Fp.mul(y, value); // 20.   y = y * y1
        x = Fp.cmov(x, tv3, isValid); // 21.   x = CMOV(x, tv3, is_gx1_square)
        y = Fp.cmov(y, value, isValid); // 22.   y = CMOV(y, y1, is_gx1_square)
        const e1 = Fp.isOdd(u) === Fp.isOdd(y); // 23.  e1 = sgn0(u) == sgn0(y)
        y = Fp.cmov(Fp.neg(y), y, e1); // 24.   y = CMOV(-y, y, e1)
        const tv4_inv = FpInvertBatch(Fp, [tv4], true)[0];
        x = Fp.mul(x, tv4_inv); // 25.   x = x / tv4
        return { x, y };
    };
}
function getWLengths(Fp, Fn) {
    return {
        secretKey: Fn.BYTES,
        publicKey: 1 + Fp.BYTES,
        publicKeyUncompressed: 1 + 2 * Fp.BYTES,
        publicKeyHasPrefix: true,
        signature: 2 * Fn.BYTES,
    };
}
/**
 * Sometimes users only need getPublicKey, getSharedSecret, and secret key handling.
 * This helper ensures no signature functionality is present. Less code, smaller bundle size.
 */
export function ecdh(Point, ecdhOpts = {}) {
    const { Fn } = Point;
    const randomBytes_ = ecdhOpts.randomBytes || randomBytesWeb;
    const lengths = Object.assign(getWLengths(Point.Fp, Fn), { seed: getMinHashLength(Fn.ORDER) });
    function isValidSecretKey(secretKey) {
        try {
            return !!_normFnElement(Fn, secretKey);
        }
        catch (error) {
            return false;
        }
    }
    function isValidPublicKey(publicKey, isCompressed) {
        const { publicKey: comp, publicKeyUncompressed } = lengths;
        try {
            const l = publicKey.length;
            if (isCompressed === true && l !== comp)
                return false;
            if (isCompressed === false && l !== publicKeyUncompressed)
                return false;
            return !!Point.fromBytes(publicKey);
        }
        catch (error) {
            return false;
        }
    }
    /**
     * Produces cryptographically secure secret key from random of size
     * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.
     */
    function randomSecretKey(seed = randomBytes_(lengths.seed)) {
        return mapHashToField(abytes(seed, lengths.seed, 'seed'), Fn.ORDER);
    }
    /**
     * Computes public key for a secret key. Checks for validity of the secret key.
     * @param isCompressed whether to return compact (default), or full key
     * @returns Public key, full when isCompressed=false; short when isCompressed=true
     */
    function getPublicKey(secretKey, isCompressed = true) {
        return Point.BASE.multiply(_normFnElement(Fn, secretKey)).toBytes(isCompressed);
    }
    function keygen(seed) {
        const secretKey = randomSecretKey(seed);
        return { secretKey, publicKey: getPublicKey(secretKey) };
    }
    /**
     * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.
     */
    function isProbPub(item) {
        if (typeof item === 'bigint')
            return false;
        if (item instanceof Point)
            return true;
        const { secretKey, publicKey, publicKeyUncompressed } = lengths;
        if (Fn.allowedLengths || secretKey === publicKey)
            return undefined;
        const l = ensureBytes('key', item).length;
        return l === publicKey || l === publicKeyUncompressed;
    }
    /**
     * ECDH (Elliptic Curve Diffie Hellman).
     * Computes shared public key from secret key A and public key B.
     * Checks: 1) secret key validity 2) shared key is on-curve.
     * Does NOT hash the result.
     * @param isCompressed whether to return compact (default), or full key
     * @returns shared public key
     */
    function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {
        if (isProbPub(secretKeyA) === true)
            throw new Error('first arg must be private key');
        if (isProbPub(publicKeyB) === false)
            throw new Error('second arg must be public key');
        const s = _normFnElement(Fn, secretKeyA);
        const b = Point.fromHex(publicKeyB); // checks for being on-curve
        return b.multiply(s).toBytes(isCompressed);
    }
    const utils = {
        isValidSecretKey,
        isValidPublicKey,
        randomSecretKey,
        // TODO: remove
        isValidPrivateKey: isValidSecretKey,
        randomPrivateKey: randomSecretKey,
        normPrivateKeyToScalar: (key) => _normFnElement(Fn, key),
        precompute(windowSize = 8, point = Point.BASE) {
            return point.precompute(windowSize, false);
        },
    };
    return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point, utils, lengths });
}
/**
 * Creates ECDSA signing interface for given elliptic curve `Point` and `hash` function.
 * We need `hash` for 2 features:
 * 1. Message prehash-ing. NOT used if `sign` / `verify` are called with `prehash: false`
 * 2. k generation in `sign`, using HMAC-drbg(hash)
 *
 * ECDSAOpts are only rarely needed.
 *
 * @example
 * ```js
 * const p256_Point = weierstrass(...);
 * const p256_sha256 = ecdsa(p256_Point, sha256);
 * const p256_sha224 = ecdsa(p256_Point, sha224);
 * const p256_sha224_r = ecdsa(p256_Point, sha224, { randomBytes: (length) => { ... } });
 * ```
 */
export function ecdsa(Point, hash, ecdsaOpts = {}) {
    ahash(hash);
    _validateObject(ecdsaOpts, {}, {
        hmac: 'function',
        lowS: 'boolean',
        randomBytes: 'function',
        bits2int: 'function',
        bits2int_modN: 'function',
    });
    const randomBytes = ecdsaOpts.randomBytes || randomBytesWeb;
    const hmac = ecdsaOpts.hmac ||
        ((key, ...msgs) => nobleHmac(hash, key, concatBytes(...msgs)));
    const { Fp, Fn } = Point;
    const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;
    const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);
    const defaultSigOpts = {
        prehash: false,
        lowS: typeof ecdsaOpts.lowS === 'boolean' ? ecdsaOpts.lowS : false,
        format: undefined, //'compact' as ECDSASigFormat,
        extraEntropy: false,
    };
    const defaultSigOpts_format = 'compact';
    function isBiggerThanHalfOrder(number) {
        const HALF = CURVE_ORDER >> _1n;
        return number > HALF;
    }
    function validateRS(title, num) {
        if (!Fn.isValidNot0(num))
            throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);
        return num;
    }
    function validateSigLength(bytes, format) {
        validateSigFormat(format);
        const size = lengths.signature;
        const sizer = format === 'compact' ? size : format === 'recovered' ? size + 1 : undefined;
        return abytes(bytes, sizer, `${format} signature`);
    }
    /**
     * ECDSA signature with its (r, s) properties. Supports compact, recovered & DER representations.
     */
    class Signature {
        constructor(r, s, recovery) {
            this.r = validateRS('r', r); // r in [1..N-1];
            this.s = validateRS('s', s); // s in [1..N-1];
            if (recovery != null)
                this.recovery = recovery;
            Object.freeze(this);
        }
        static fromBytes(bytes, format = defaultSigOpts_format) {
            validateSigLength(bytes, format);
            let recid;
            if (format === 'der') {
                const { r, s } = DER.toSig(abytes(bytes));
                return new Signature(r, s);
            }
            if (format === 'recovered') {
                recid = bytes[0];
                format = 'compact';
                bytes = bytes.subarray(1);
            }
            const L = Fn.BYTES;
            const r = bytes.subarray(0, L);
            const s = bytes.subarray(L, L * 2);
            return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);
        }
        static fromHex(hex, format) {
            return this.fromBytes(hexToBytes(hex), format);
        }
        addRecoveryBit(recovery) {
            return new Signature(this.r, this.s, recovery);
        }
        recoverPublicKey(messageHash) {
            const FIELD_ORDER = Fp.ORDER;
            const { r, s, recovery: rec } = this;
            if (rec == null || ![0, 1, 2, 3].includes(rec))
                throw new Error('recovery id invalid');
            // ECDSA recovery is hard for cofactor > 1 curves.
            // In sign, `r = q.x mod n`, and here we recover q.x from r.
            // While recovering q.x >= n, we need to add r+n for cofactor=1 curves.
            // However, for cofactor>1, r+n may not get q.x:
            // r+n*i would need to be done instead where i is unknown.
            // To easily get i, we either need to:
            // a. increase amount of valid recid values (4, 5...); OR
            // b. prohibit non-prime-order signatures (recid > 1).
            const hasCofactor = CURVE_ORDER * _2n < FIELD_ORDER;
            if (hasCofactor && rec > 1)
                throw new Error('recovery id is ambiguous for h>1 curve');
            const radj = rec === 2 || rec === 3 ? r + CURVE_ORDER : r;
            if (!Fp.isValid(radj))
                throw new Error('recovery id 2 or 3 invalid');
            const x = Fp.toBytes(radj);
            const R = Point.fromBytes(concatBytes(pprefix((rec & 1) === 0), x));
            const ir = Fn.inv(radj); // r^-1
            const h = bits2int_modN(ensureBytes('msgHash', messageHash)); // Truncate hash
            const u1 = Fn.create(-h * ir); // -hr^-1
            const u2 = Fn.create(s * ir); // sr^-1
            // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1). unsafe is fine: there is no private data.
            const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));
            if (Q.is0())
                throw new Error('point at infinify');
            Q.assertValidity();
            return Q;
        }
        // Signatures should be low-s, to prevent malleability.
        hasHighS() {
            return isBiggerThanHalfOrder(this.s);
        }
        toBytes(format = defaultSigOpts_format) {
            validateSigFormat(format);
            if (format === 'der')
                return hexToBytes(DER.hexFromSig(this));
            const r = Fn.toBytes(this.r);
            const s = Fn.toBytes(this.s);
            if (format === 'recovered') {
                if (this.recovery == null)
                    throw new Error('recovery bit must be present');
                return concatBytes(Uint8Array.of(this.recovery), r, s);
            }
            return concatBytes(r, s);
        }
        toHex(format) {
            return bytesToHex(this.toBytes(format));
        }
        // TODO: remove
        assertValidity() { }
        static fromCompact(hex) {
            return Signature.fromBytes(ensureBytes('sig', hex), 'compact');
        }
        static fromDER(hex) {
            return Signature.fromBytes(ensureBytes('sig', hex), 'der');
        }
        normalizeS() {
            return this.hasHighS() ? new Signature(this.r, Fn.neg(this.s), this.recovery) : this;
        }
        toDERRawBytes() {
            return this.toBytes('der');
        }
        toDERHex() {
            return bytesToHex(this.toBytes('der'));
        }
        toCompactRawBytes() {
            return this.toBytes('compact');
        }
        toCompactHex() {
            return bytesToHex(this.toBytes('compact'));
        }
    }
    // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.
    // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.
    // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.
    // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors
    const bits2int = ecdsaOpts.bits2int ||
        function bits2int_def(bytes) {
            // Our custom check "just in case", for protection against DoS
            if (bytes.length > 8192)
                throw new Error('input is too large');
            // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)
            // for some cases, since bytes.length * 8 is not actual bitLength.
            const num = bytesToNumberBE(bytes); // check for == u8 done here
            const delta = bytes.length * 8 - fnBits; // truncate to nBitLength leftmost bits
            return delta > 0 ? num >> BigInt(delta) : num;
        };
    const bits2int_modN = ecdsaOpts.bits2int_modN ||
        function bits2int_modN_def(bytes) {
            return Fn.create(bits2int(bytes)); // can't use bytesToNumberBE here
        };
    // Pads output with zero as per spec
    const ORDER_MASK = bitMask(fnBits);
    /** Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. */
    function int2octets(num) {
        // IMPORTANT: the check ensures working for case `Fn.BYTES != Fn.BITS * 8`
        aInRange('num < 2^' + fnBits, num, _0n, ORDER_MASK);
        return Fn.toBytes(num);
    }
    function validateMsgAndHash(message, prehash) {
        abytes(message, undefined, 'message');
        return prehash ? abytes(hash(message), undefined, 'prehashed message') : message;
    }
    /**
     * Steps A, D of RFC6979 3.2.
     * Creates RFC6979 seed; converts msg/privKey to numbers.
     * Used only in sign, not in verify.
     *
     * Warning: we cannot assume here that message has same amount of bytes as curve order,
     * this will be invalid at least for P521. Also it can be bigger for P224 + SHA256.
     */
    function prepSig(message, privateKey, opts) {
        if (['recovered', 'canonical'].some((k) => k in opts))
            throw new Error('sign() legacy options not supported');
        const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);
        message = validateMsgAndHash(message, prehash); // RFC6979 3.2 A: h1 = H(m)
        // We can't later call bits2octets, since nested bits2int is broken for curves
        // with fnBits % 8 !== 0. Because of that, we unwrap it here as int2octets call.
        // const bits2octets = (bits) => int2octets(bits2int_modN(bits))
        const h1int = bits2int_modN(message);
        const d = _normFnElement(Fn, privateKey); // validate secret key, convert to bigint
        const seedArgs = [int2octets(d), int2octets(h1int)];
        // extraEntropy. RFC6979 3.6: additional k' (optional).
        if (extraEntropy != null && extraEntropy !== false) {
            // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')
            // gen random bytes OR pass as-is
            const e = extraEntropy === true ? randomBytes(lengths.secretKey) : extraEntropy;
            seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes
        }
        const seed = concatBytes(...seedArgs); // Step D of RFC6979 3.2
        const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash!
        // Converts signature params into point w r/s, checks result for validity.
        // To transform k => Signature:
        // q = k⋅G
        // r = q.x mod n
        // s = k^-1(m + rd) mod n
        // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to
        // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:
        // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT
        function k2sig(kBytes) {
            // RFC 6979 Section 3.2, step 3: k = bits2int(T)
            // Important: all mod() calls here must be done over N
            const k = bits2int(kBytes); // mod n, not mod p
            if (!Fn.isValidNot0(k))
                return; // Valid scalars (including k) must be in 1..N-1
            const ik = Fn.inv(k); // k^-1 mod n
            const q = Point.BASE.multiply(k).toAffine(); // q = k⋅G
            const r = Fn.create(q.x); // r = q.x mod n
            if (r === _0n)
                return;
            const s = Fn.create(ik * Fn.create(m + r * d)); // Not using blinding here, see comment above
            if (s === _0n)
                return;
            let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n)
            let normS = s;
            if (lowS && isBiggerThanHalfOrder(s)) {
                normS = Fn.neg(s); // if lowS was passed, ensure s is always
                recovery ^= 1; // // in the bottom half of N
            }
            return new Signature(r, normS, recovery); // use normS, not s
        }
        return { seed, k2sig };
    }
    /**
     * Signs message hash with a secret key.
     *
     * ```
     * sign(m, d) where
     *   k = rfc6979_hmac_drbg(m, d)
     *   (x, y) = G × k
     *   r = x mod n
     *   s = (m + dr) / k mod n
     * ```
     */
    function sign(message, secretKey, opts = {}) {
        message = ensureBytes('message', message);
        const { seed, k2sig } = prepSig(message, secretKey, opts); // Steps A, D of RFC6979 3.2.
        const drbg = createHmacDrbg(hash.outputLen, Fn.BYTES, hmac);
        const sig = drbg(seed, k2sig); // Steps B, C, D, E, F, G
        return sig;
    }
    function tryParsingSig(sg) {
        // Try to deduce format
        let sig = undefined;
        const isHex = typeof sg === 'string' || isBytes(sg);
        const isObj = !isHex &&
            sg !== null &&
            typeof sg === 'object' &&
            typeof sg.r === 'bigint' &&
            typeof sg.s === 'bigint';
        if (!isHex && !isObj)
            throw new Error('invalid signature, expected Uint8Array, hex string or Signature instance');
        if (isObj) {
            sig = new Signature(sg.r, sg.s);
        }
        else if (isHex) {
            try {
                sig = Signature.fromBytes(ensureBytes('sig', sg), 'der');
            }
            catch (derError) {
                if (!(derError instanceof DER.Err))
                    throw derError;
            }
            if (!sig) {
                try {
                    sig = Signature.fromBytes(ensureBytes('sig', sg), 'compact');
                }
                catch (error) {
                    return false;
                }
            }
        }
        if (!sig)
            return false;
        return sig;
    }
    /**
     * Verifies a signature against message and public key.
     * Rejects lowS signatures by default: see {@link ECDSAVerifyOpts}.
     * Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:
     *
     * ```
     * verify(r, s, h, P) where
     *   u1 = hs^-1 mod n
     *   u2 = rs^-1 mod n
     *   R = u1⋅G + u2⋅P
     *   mod(R.x, n) == r
     * ```
     */
    function verify(signature, message, publicKey, opts = {}) {
        const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);
        publicKey = ensureBytes('publicKey', publicKey);
        message = validateMsgAndHash(ensureBytes('message', message), prehash);
        if ('strict' in opts)
            throw new Error('options.strict was renamed to lowS');
        const sig = format === undefined
            ? tryParsingSig(signature)
            : Signature.fromBytes(ensureBytes('sig', signature), format);
        if (sig === false)
            return false;
        try {
            const P = Point.fromBytes(publicKey);
            if (lowS && sig.hasHighS())
                return false;
            const { r, s } = sig;
            const h = bits2int_modN(message); // mod n, not mod p
            const is = Fn.inv(s); // s^-1 mod n
            const u1 = Fn.create(h * is); // u1 = hs^-1 mod n
            const u2 = Fn.create(r * is); // u2 = rs^-1 mod n
            const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2)); // u1⋅G + u2⋅P
            if (R.is0())
                return false;
            const v = Fn.create(R.x); // v = r.x mod n
            return v === r;
        }
        catch (e) {
            return false;
        }
    }
    function recoverPublicKey(signature, message, opts = {}) {
        const { prehash } = validateSigOpts(opts, defaultSigOpts);
        message = validateMsgAndHash(message, prehash);
        return Signature.fromBytes(signature, 'recovered').recoverPublicKey(message).toBytes();
    }
    return Object.freeze({
        keygen,
        getPublicKey,
        getSharedSecret,
        utils,
        lengths,
        Point,
        sign,
        verify,
        recoverPublicKey,
        Signature,
        hash,
    });
}
/** @deprecated use `weierstrass` in newer releases */
export function weierstrassPoints(c) {
    const { CURVE, curveOpts } = _weierstrass_legacy_opts_to_new(c);
    const Point = weierstrassN(CURVE, curveOpts);
    return _weierstrass_new_output_to_legacy(c, Point);
}
function _weierstrass_legacy_opts_to_new(c) {
    const CURVE = {
        a: c.a,
        b: c.b,
        p: c.Fp.ORDER,
        n: c.n,
        h: c.h,
        Gx: c.Gx,
        Gy: c.Gy,
    };
    const Fp = c.Fp;
    let allowedLengths = c.allowedPrivateKeyLengths
        ? Array.from(new Set(c.allowedPrivateKeyLengths.map((l) => Math.ceil(l / 2))))
        : undefined;
    const Fn = Field(CURVE.n, {
        BITS: c.nBitLength,
        allowedLengths: allowedLengths,
        modFromBytes: c.wrapPrivateKey,
    });
    const curveOpts = {
        Fp,
        Fn,
        allowInfinityPoint: c.allowInfinityPoint,
        endo: c.endo,
        isTorsionFree: c.isTorsionFree,
        clearCofactor: c.clearCofactor,
        fromBytes: c.fromBytes,
        toBytes: c.toBytes,
    };
    return { CURVE, curveOpts };
}
function _ecdsa_legacy_opts_to_new(c) {
    const { CURVE, curveOpts } = _weierstrass_legacy_opts_to_new(c);
    const ecdsaOpts = {
        hmac: c.hmac,
        randomBytes: c.randomBytes,
        lowS: c.lowS,
        bits2int: c.bits2int,
        bits2int_modN: c.bits2int_modN,
    };
    return { CURVE, curveOpts, hash: c.hash, ecdsaOpts };
}
export function _legacyHelperEquat(Fp, a, b) {
    /**
     * y² = x³ + ax + b: Short weierstrass curve formula. Takes x, returns y².
     * @returns y²
     */
    function weierstrassEquation(x) {
        const x2 = Fp.sqr(x); // x * x
        const x3 = Fp.mul(x2, x); // x² * x
        return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x³ + a * x + b
    }
    return weierstrassEquation;
}
function _weierstrass_new_output_to_legacy(c, Point) {
    const { Fp, Fn } = Point;
    function isWithinCurveOrder(num) {
        return inRange(num, _1n, Fn.ORDER);
    }
    const weierstrassEquation = _legacyHelperEquat(Fp, c.a, c.b);
    return Object.assign({}, {
        CURVE: c,
        Point: Point,
        ProjectivePoint: Point,
        normPrivateKeyToScalar: (key) => _normFnElement(Fn, key),
        weierstrassEquation,
        isWithinCurveOrder,
    });
}
function _ecdsa_new_output_to_legacy(c, _ecdsa) {
    const Point = _ecdsa.Point;
    return Object.assign({}, _ecdsa, {
        ProjectivePoint: Point,
        CURVE: Object.assign({}, c, nLength(Point.Fn.ORDER, Point.Fn.BITS)),
    });
}
// _ecdsa_legacy
export function weierstrass(c) {
    const { CURVE, curveOpts, hash, ecdsaOpts } = _ecdsa_legacy_opts_to_new(c);
    const Point = weierstrassN(CURVE, curveOpts);
    const signs = ecdsa(Point, hash, ecdsaOpts);
    return _ecdsa_new_output_to_legacy(c, signs);
}
//# sourceMappingURL=weierstrass.js.map/**
 * Internal module for NIST P256, P384, P521 curves.
 * Do not use for now.
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { sha256, sha384, sha512 } from '@noble/hashes/sha2.js';
import { createCurve } from "./_shortw_utils.js";
import { createHasher } from "./abstract/hash-to-curve.js";
import { Field } from "./abstract/modular.js";
import { mapToCurveSimpleSWU, } from "./abstract/weierstrass.js";
// p = 2n**224n * (2n**32n-1n) + 2n**192n + 2n**96n - 1n
// a = Fp256.create(BigInt('-3'));
const p256_CURVE = {
    p: BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff'),
    n: BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551'),
    h: BigInt(1),
    a: BigInt('0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc'),
    b: BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b'),
    Gx: BigInt('0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296'),
    Gy: BigInt('0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5'),
};
// p = 2n**384n - 2n**128n - 2n**96n + 2n**32n - 1n
const p384_CURVE = {
    p: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff'),
    n: BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973'),
    h: BigInt(1),
    a: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc'),
    b: BigInt('0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef'),
    Gx: BigInt('0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7'),
    Gy: BigInt('0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f'),
};
// p = 2n**521n - 1n
const p521_CURVE = {
    p: BigInt('0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'),
    n: BigInt('0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409'),
    h: BigInt(1),
    a: BigInt('0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc'),
    b: BigInt('0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00'),
    Gx: BigInt('0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66'),
    Gy: BigInt('0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650'),
};
const Fp256 = Field(p256_CURVE.p);
const Fp384 = Field(p384_CURVE.p);
const Fp521 = Field(p521_CURVE.p);
function createSWU(Point, opts) {
    const map = mapToCurveSimpleSWU(Point.Fp, opts);
    return (scalars) => map(scalars[0]);
}
/** NIST P256 (aka secp256r1, prime256v1) curve, ECDSA and ECDH methods. */
export const p256 = createCurve({ ...p256_CURVE, Fp: Fp256, lowS: false }, sha256);
/** Hashing / encoding to p256 points / field. RFC 9380 methods. */
export const p256_hasher = /* @__PURE__ */ (() => {
    return createHasher(p256.Point, createSWU(p256.Point, {
        A: p256_CURVE.a,
        B: p256_CURVE.b,
        Z: p256.Point.Fp.create(BigInt('-10')),
    }), {
        DST: 'P256_XMD:SHA-256_SSWU_RO_',
        encodeDST: 'P256_XMD:SHA-256_SSWU_NU_',
        p: p256_CURVE.p,
        m: 1,
        k: 128,
        expand: 'xmd',
        hash: sha256,
    });
})();
// export const p256_oprf: OPRF = createORPF({
//   name: 'P256-SHA256',
//   Point: p256.Point,
//   hash: sha256,
//   hashToGroup: p256_hasher.hashToCurve,
//   hashToScalar: p256_hasher.hashToScalar,
// });
/** NIST P384 (aka secp384r1) curve, ECDSA and ECDH methods. */
export const p384 = createCurve({ ...p384_CURVE, Fp: Fp384, lowS: false }, sha384);
/** Hashing / encoding to p384 points / field. RFC 9380 methods. */
export const p384_hasher = /* @__PURE__ */ (() => {
    return createHasher(p384.Point, createSWU(p384.Point, {
        A: p384_CURVE.a,
        B: p384_CURVE.b,
        Z: p384.Point.Fp.create(BigInt('-12')),
    }), {
        DST: 'P384_XMD:SHA-384_SSWU_RO_',
        encodeDST: 'P384_XMD:SHA-384_SSWU_NU_',
        p: p384_CURVE.p,
        m: 1,
        k: 192,
        expand: 'xmd',
        hash: sha384,
    });
})();
// export const p384_oprf: OPRF = createORPF({
//   name: 'P384-SHA384',
//   Point: p384.Point,
//   hash: sha384,
//   hashToGroup: p384_hasher.hashToCurve,
//   hashToScalar: p384_hasher.hashToScalar,
// });
// const Fn521 = Field(p521_CURVE.n, { allowedScalarLengths: [65, 66] });
/** NIST P521 (aka secp521r1) curve, ECDSA and ECDH methods. */
export const p521 = createCurve({ ...p521_CURVE, Fp: Fp521, lowS: false, allowedPrivateKeyLengths: [130, 131, 132] }, sha512);
/** @deprecated use `p256` for consistency with `p256_hasher` */
export const secp256r1 = p256;
/** @deprecated use `p384` for consistency with `p384_hasher` */
export const secp384r1 = p384;
/** @deprecated use `p521` for consistency with `p521_hasher` */
export const secp521r1 = p521;
/** Hashing / encoding to p521 points / field. RFC 9380 methods. */
export const p521_hasher = /* @__PURE__ */ (() => {
    return createHasher(p521.Point, createSWU(p521.Point, {
        A: p521_CURVE.a,
        B: p521_CURVE.b,
        Z: p521.Point.Fp.create(BigInt('-4')),
    }), {
        DST: 'P521_XMD:SHA-512_SSWU_RO_',
        encodeDST: 'P521_XMD:SHA-512_SSWU_NU_',
        p: p521_CURVE.p,
        m: 1,
        k: 256,
        expand: 'xmd',
        hash: sha512,
    });
})();
// export const p521_oprf: OPRF = createORPF({
//   name: 'P521-SHA512',
//   Point: p521.Point,
//   hash: sha512,
//   hashToGroup: p521_hasher.hashToCurve,
//   hashToScalar: p521_hasher.hashToScalar, // produces L=98 just like in RFC
// });
//# sourceMappingURL=nist.js.map/**
 * NIST secp256r1 aka p256.
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import {} from "./abstract/hash-to-curve.js";
import { p256_hasher, p256 as p256n } from "./nist.js";
/** @deprecated use `import { p256 } from '@noble/curves/nist.js';` */
export const p256 = p256n;
/** @deprecated use `import { p256 } from '@noble/curves/nist.js';` */
export const secp256r1 = p256n;
/** @deprecated use `import { p256_hasher } from '@noble/curves/nist.js';` */
export const hashToCurve = /* @__PURE__ */ (() => p256_hasher.hashToCurve)();
/** @deprecated use `import { p256_hasher } from '@noble/curves/nist.js';` */
export const encodeToCurve = /* @__PURE__ */ (() => p256_hasher.encodeToCurve)();
//# sourceMappingURL=p256.js.map{
  "type": "module",
  "sideEffects": false
}
/**
 * SECG secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).
 *
 * Belongs to Koblitz curves: it has efficiently-computable GLV endomorphism ψ,
 * check out {@link EndomorphismOpts}. Seems to be rigid (not backdoored).
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { sha256 } from '@noble/hashes/sha2.js';
import { randomBytes } from '@noble/hashes/utils.js';
import { createCurve } from "./_shortw_utils.js";
import { createHasher, isogenyMap, } from "./abstract/hash-to-curve.js";
import { Field, mapHashToField, mod, pow2 } from "./abstract/modular.js";
import { _normFnElement, mapToCurveSimpleSWU, } from "./abstract/weierstrass.js";
import { bytesToNumberBE, concatBytes, ensureBytes, inRange, numberToBytesBE, utf8ToBytes, } from "./utils.js";
// Seems like generator was produced from some seed:
// `Point.BASE.multiply(Point.Fn.inv(2n, N)).toAffine().x`
// // gives short x 0x3b78ce563f89a0ed9414f5aa28ad0d96d6795f9c63n
const secp256k1_CURVE = {
    p: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'),
    n: BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'),
    h: BigInt(1),
    a: BigInt(0),
    b: BigInt(7),
    Gx: BigInt('0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'),
    Gy: BigInt('0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8'),
};
const secp256k1_ENDO = {
    beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),
    basises: [
        [BigInt('0x3086d221a7d46bcde86c90e49284eb15'), -BigInt('0xe4437ed6010e88286f547fa90abfe4c3')],
        [BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'), BigInt('0x3086d221a7d46bcde86c90e49284eb15')],
    ],
};
const _0n = /* @__PURE__ */ BigInt(0);
const _1n = /* @__PURE__ */ BigInt(1);
const _2n = /* @__PURE__ */ BigInt(2);
/**
 * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.
 * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]
 */
function sqrtMod(y) {
    const P = secp256k1_CURVE.p;
    // prettier-ignore
    const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
    // prettier-ignore
    const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
    const b2 = (y * y * y) % P; // x^3, 11
    const b3 = (b2 * b2 * y) % P; // x^7
    const b6 = (pow2(b3, _3n, P) * b3) % P;
    const b9 = (pow2(b6, _3n, P) * b3) % P;
    const b11 = (pow2(b9, _2n, P) * b2) % P;
    const b22 = (pow2(b11, _11n, P) * b11) % P;
    const b44 = (pow2(b22, _22n, P) * b22) % P;
    const b88 = (pow2(b44, _44n, P) * b44) % P;
    const b176 = (pow2(b88, _88n, P) * b88) % P;
    const b220 = (pow2(b176, _44n, P) * b44) % P;
    const b223 = (pow2(b220, _3n, P) * b3) % P;
    const t1 = (pow2(b223, _23n, P) * b22) % P;
    const t2 = (pow2(t1, _6n, P) * b2) % P;
    const root = pow2(t2, _2n, P);
    if (!Fpk1.eql(Fpk1.sqr(root), y))
        throw new Error('Cannot find square root');
    return root;
}
const Fpk1 = Field(secp256k1_CURVE.p, { sqrt: sqrtMod });
/**
 * secp256k1 curve, ECDSA and ECDH methods.
 *
 * Field: `2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n`
 *
 * @example
 * ```js
 * import { secp256k1 } from '@noble/curves/secp256k1';
 * const { secretKey, publicKey } = secp256k1.keygen();
 * const msg = new TextEncoder().encode('hello');
 * const sig = secp256k1.sign(msg, secretKey);
 * const isValid = secp256k1.verify(sig, msg, publicKey) === true;
 * ```
 */
export const secp256k1 = createCurve({ ...secp256k1_CURVE, Fp: Fpk1, lowS: true, endo: secp256k1_ENDO }, sha256);
// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.
// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki
/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */
const TAGGED_HASH_PREFIXES = {};
function taggedHash(tag, ...messages) {
    let tagP = TAGGED_HASH_PREFIXES[tag];
    if (tagP === undefined) {
        const tagH = sha256(utf8ToBytes(tag));
        tagP = concatBytes(tagH, tagH);
        TAGGED_HASH_PREFIXES[tag] = tagP;
    }
    return sha256(concatBytes(tagP, ...messages));
}
// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03
const pointToBytes = (point) => point.toBytes(true).slice(1);
const Pointk1 = /* @__PURE__ */ (() => secp256k1.Point)();
const hasEven = (y) => y % _2n === _0n;
// Calculate point, scalar and bytes
function schnorrGetExtPubKey(priv) {
    const { Fn, BASE } = Pointk1;
    const d_ = _normFnElement(Fn, priv);
    const p = BASE.multiply(d_); // P = d'⋅G; 0 < d' < n check is done inside
    const scalar = hasEven(p.y) ? d_ : Fn.neg(d_);
    return { scalar, bytes: pointToBytes(p) };
}
/**
 * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.
 * @returns valid point checked for being on-curve
 */
function lift_x(x) {
    const Fp = Fpk1;
    if (!Fp.isValidNot0(x))
        throw new Error('invalid x: Fail if x ≥ p');
    const xx = Fp.create(x * x);
    const c = Fp.create(xx * x + BigInt(7)); // Let c = x³ + 7 mod p.
    let y = Fp.sqrt(c); // Let y = c^(p+1)/4 mod p. Same as sqrt().
    // Return the unique point P such that x(P) = x and
    // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.
    if (!hasEven(y))
        y = Fp.neg(y);
    const p = Pointk1.fromAffine({ x, y });
    p.assertValidity();
    return p;
}
const num = bytesToNumberBE;
/**
 * Create tagged hash, convert it to bigint, reduce modulo-n.
 */
function challenge(...args) {
    return Pointk1.Fn.create(num(taggedHash('BIP0340/challenge', ...args)));
}
/**
 * Schnorr public key is just `x` coordinate of Point as per BIP340.
 */
function schnorrGetPublicKey(secretKey) {
    return schnorrGetExtPubKey(secretKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G)
}
/**
 * Creates Schnorr signature as per BIP340. Verifies itself before returning anything.
 * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous.
 */
function schnorrSign(message, secretKey, auxRand = randomBytes(32)) {
    const { Fn } = Pointk1;
    const m = ensureBytes('message', message);
    const { bytes: px, scalar: d } = schnorrGetExtPubKey(secretKey); // checks for isWithinCurveOrder
    const a = ensureBytes('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array
    const t = Fn.toBytes(d ^ num(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a)
    const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m)
    // Let k' = int(rand) mod n. Fail if k' = 0. Let R = k'⋅G
    const { bytes: rx, scalar: k } = schnorrGetExtPubKey(rand);
    const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.
    const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n).
    sig.set(rx, 0);
    sig.set(Fn.toBytes(Fn.create(k + e * d)), 32);
    // If Verify(bytes(P), m, sig) (see below) returns failure, abort
    if (!schnorrVerify(sig, m, px))
        throw new Error('sign: Invalid signature produced');
    return sig;
}
/**
 * Verifies Schnorr signature.
 * Will swallow errors & return false except for initial type validation of arguments.
 */
function schnorrVerify(signature, message, publicKey) {
    const { Fn, BASE } = Pointk1;
    const sig = ensureBytes('signature', signature, 64);
    const m = ensureBytes('message', message);
    const pub = ensureBytes('publicKey', publicKey, 32);
    try {
        const P = lift_x(num(pub)); // P = lift_x(int(pk)); fail if that fails
        const r = num(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r ≥ p.
        if (!inRange(r, _1n, secp256k1_CURVE.p))
            return false;
        const s = num(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n.
        if (!inRange(s, _1n, secp256k1_CURVE.n))
            return false;
        // int(challenge(bytes(r)||bytes(P)||m))%n
        const e = challenge(Fn.toBytes(r), pointToBytes(P), m);
        // R = s⋅G - e⋅P, where -eP == (n-e)P
        const R = BASE.multiplyUnsafe(s).add(P.multiplyUnsafe(Fn.neg(e)));
        const { x, y } = R.toAffine();
        // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r.
        if (R.is0() || !hasEven(y) || x !== r)
            return false;
        return true;
    }
    catch (error) {
        return false;
    }
}
/**
 * Schnorr signatures over secp256k1.
 * https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki
 * @example
 * ```js
 * import { schnorr } from '@noble/curves/secp256k1';
 * const { secretKey, publicKey } = schnorr.keygen();
 * // const publicKey = schnorr.getPublicKey(secretKey);
 * const msg = new TextEncoder().encode('hello');
 * const sig = schnorr.sign(msg, secretKey);
 * const isValid = schnorr.verify(sig, msg, publicKey);
 * ```
 */
export const schnorr = /* @__PURE__ */ (() => {
    const size = 32;
    const seedLength = 48;
    const randomSecretKey = (seed = randomBytes(seedLength)) => {
        return mapHashToField(seed, secp256k1_CURVE.n);
    };
    // TODO: remove
    secp256k1.utils.randomSecretKey;
    function keygen(seed) {
        const secretKey = randomSecretKey(seed);
        return { secretKey, publicKey: schnorrGetPublicKey(secretKey) };
    }
    return {
        keygen,
        getPublicKey: schnorrGetPublicKey,
        sign: schnorrSign,
        verify: schnorrVerify,
        Point: Pointk1,
        utils: {
            randomSecretKey: randomSecretKey,
            randomPrivateKey: randomSecretKey,
            taggedHash,
            // TODO: remove
            lift_x,
            pointToBytes,
            numberToBytesBE,
            bytesToNumberBE,
            mod,
        },
        lengths: {
            secretKey: size,
            publicKey: size,
            publicKeyHasPrefix: false,
            signature: size * 2,
            seed: seedLength,
        },
    };
})();
const isoMap = /* @__PURE__ */ (() => isogenyMap(Fpk1, [
    // xNum
    [
        '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7',
        '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581',
        '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262',
        '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c',
    ],
    // xDen
    [
        '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b',
        '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14',
        '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1
    ],
    // yNum
    [
        '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c',
        '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3',
        '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931',
        '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84',
    ],
    // yDen
    [
        '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b',
        '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573',
        '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f',
        '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1
    ],
].map((i) => i.map((j) => BigInt(j)))))();
const mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fpk1, {
    A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),
    B: BigInt('1771'),
    Z: Fpk1.create(BigInt('-11')),
}))();
/** Hashing / encoding to secp256k1 points / field. RFC 9380 methods. */
export const secp256k1_hasher = /* @__PURE__ */ (() => createHasher(secp256k1.Point, (scalars) => {
    const { x, y } = mapSWU(Fpk1.create(scalars[0]));
    return isoMap(x, y);
}, {
    DST: 'secp256k1_XMD:SHA-256_SSWU_RO_',
    encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_',
    p: Fpk1.ORDER,
    m: 1,
    k: 128,
    expand: 'xmd',
    hash: sha256,
}))();
/** @deprecated use `import { secp256k1_hasher } from '@noble/curves/secp256k1.js';` */
export const hashToCurve = /* @__PURE__ */ (() => secp256k1_hasher.hashToCurve)();
/** @deprecated use `import { secp256k1_hasher } from '@noble/curves/secp256k1.js';` */
export const encodeToCurve = /* @__PURE__ */ (() => secp256k1_hasher.encodeToCurve)();
//# sourceMappingURL=secp256k1.js.map/**
 * Hex, bytes and number utilities.
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { abytes as abytes_, bytesToHex as bytesToHex_, concatBytes as concatBytes_, hexToBytes as hexToBytes_, isBytes as isBytes_, } from '@noble/hashes/utils.js';
export { abytes, anumber, bytesToHex, bytesToUtf8, concatBytes, hexToBytes, isBytes, randomBytes, utf8ToBytes, } from '@noble/hashes/utils.js';
const _0n = /* @__PURE__ */ BigInt(0);
const _1n = /* @__PURE__ */ BigInt(1);
export function abool(title, value) {
    if (typeof value !== 'boolean')
        throw new Error(title + ' boolean expected, got ' + value);
}
// tmp name until v2
export function _abool2(value, title = '') {
    if (typeof value !== 'boolean') {
        const prefix = title && `"${title}"`;
        throw new Error(prefix + 'expected boolean, got type=' + typeof value);
    }
    return value;
}
// tmp name until v2
/** Asserts something is Uint8Array. */
export function _abytes2(value, length, title = '') {
    const bytes = isBytes_(value);
    const len = value?.length;
    const needsLen = length !== undefined;
    if (!bytes || (needsLen && len !== length)) {
        const prefix = title && `"${title}" `;
        const ofLen = needsLen ? ` of length ${length}` : '';
        const got = bytes ? `length=${len}` : `type=${typeof value}`;
        throw new Error(prefix + 'expected Uint8Array' + ofLen + ', got ' + got);
    }
    return value;
}
// Used in weierstrass, der
export function numberToHexUnpadded(num) {
    const hex = num.toString(16);
    return hex.length & 1 ? '0' + hex : hex;
}
export function hexToNumber(hex) {
    if (typeof hex !== 'string')
        throw new Error('hex string expected, got ' + typeof hex);
    return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian
}
// BE: Big Endian, LE: Little Endian
export function bytesToNumberBE(bytes) {
    return hexToNumber(bytesToHex_(bytes));
}
export function bytesToNumberLE(bytes) {
    abytes_(bytes);
    return hexToNumber(bytesToHex_(Uint8Array.from(bytes).reverse()));
}
export function numberToBytesBE(n, len) {
    return hexToBytes_(n.toString(16).padStart(len * 2, '0'));
}
export function numberToBytesLE(n, len) {
    return numberToBytesBE(n, len).reverse();
}
// Unpadded, rarely used
export function numberToVarBytesBE(n) {
    return hexToBytes_(numberToHexUnpadded(n));
}
/**
 * Takes hex string or Uint8Array, converts to Uint8Array.
 * Validates output length.
 * Will throw error for other types.
 * @param title descriptive title for an error e.g. 'secret key'
 * @param hex hex string or Uint8Array
 * @param expectedLength optional, will compare to result array's length
 * @returns
 */
export function ensureBytes(title, hex, expectedLength) {
    let res;
    if (typeof hex === 'string') {
        try {
            res = hexToBytes_(hex);
        }
        catch (e) {
            throw new Error(title + ' must be hex string or Uint8Array, cause: ' + e);
        }
    }
    else if (isBytes_(hex)) {
        // Uint8Array.from() instead of hash.slice() because node.js Buffer
        // is instance of Uint8Array, and its slice() creates **mutable** copy
        res = Uint8Array.from(hex);
    }
    else {
        throw new Error(title + ' must be hex string or Uint8Array');
    }
    const len = res.length;
    if (typeof expectedLength === 'number' && len !== expectedLength)
        throw new Error(title + ' of length ' + expectedLength + ' expected, got ' + len);
    return res;
}
// Compares 2 u8a-s in kinda constant time
export function equalBytes(a, b) {
    if (a.length !== b.length)
        return false;
    let diff = 0;
    for (let i = 0; i < a.length; i++)
        diff |= a[i] ^ b[i];
    return diff === 0;
}
/**
 * Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,
 * and Buffer#slice creates mutable copy. Never use Buffers!
 */
export function copyBytes(bytes) {
    return Uint8Array.from(bytes);
}
/**
 * Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols
 * Should be safe to use for things expected to be ASCII.
 * Returns exact same result as utf8ToBytes for ASCII or throws.
 */
export function asciiToBytes(ascii) {
    return Uint8Array.from(ascii, (c, i) => {
        const charCode = c.charCodeAt(0);
        if (c.length !== 1 || charCode > 127) {
            throw new Error(`string contains non-ASCII character "${ascii[i]}" with code ${charCode} at position ${i}`);
        }
        return charCode;
    });
}
/**
 * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
 */
// export const utf8ToBytes: typeof utf8ToBytes_ = utf8ToBytes_;
/**
 * Converts bytes to string using UTF8 encoding.
 * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'
 */
// export const bytesToUtf8: typeof bytesToUtf8_ = bytesToUtf8_;
// Is positive bigint
const isPosBig = (n) => typeof n === 'bigint' && _0n <= n;
export function inRange(n, min, max) {
    return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
}
/**
 * Asserts min <= n < max. NOTE: It's < max and not <= max.
 * @example
 * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)
 */
export function aInRange(title, n, min, max) {
    // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?
    // consider P=256n, min=0n, max=P
    // - a for min=0 would require -1:          `inRange('x', x, -1n, P)`
    // - b would commonly require subtraction:  `inRange('x', x, 0n, P - 1n)`
    // - our way is the cleanest:               `inRange('x', x, 0n, P)
    if (!inRange(n, min, max))
        throw new Error('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);
}
// Bit operations
/**
 * Calculates amount of bits in a bigint.
 * Same as `n.toString(2).length`
 * TODO: merge with nLength in modular
 */
export function bitLen(n) {
    let len;
    for (len = 0; n > _0n; n >>= _1n, len += 1)
        ;
    return len;
}
/**
 * Gets single bit at position.
 * NOTE: first bit position is 0 (same as arrays)
 * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`
 */
export function bitGet(n, pos) {
    return (n >> BigInt(pos)) & _1n;
}
/**
 * Sets single bit at position.
 */
export function bitSet(n, pos, value) {
    return n | ((value ? _1n : _0n) << BigInt(pos));
}
/**
 * Calculate mask for N bits. Not using ** operator with bigints because of old engines.
 * Same as BigInt(`0b${Array(i).fill('1').join('')}`)
 */
export const bitMask = (n) => (_1n << BigInt(n)) - _1n;
/**
 * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
 * @returns function that will call DRBG until 2nd arg returns something meaningful
 * @example
 *   const drbg = createHmacDRBG<Key>(32, 32, hmac);
 *   drbg(seed, bytesToKey); // bytesToKey must return Key or undefined
 */
export function createHmacDrbg(hashLen, qByteLen, hmacFn) {
    if (typeof hashLen !== 'number' || hashLen < 2)
        throw new Error('hashLen must be a number');
    if (typeof qByteLen !== 'number' || qByteLen < 2)
        throw new Error('qByteLen must be a number');
    if (typeof hmacFn !== 'function')
        throw new Error('hmacFn must be a function');
    // Step B, Step C: set hashLen to 8*ceil(hlen/8)
    const u8n = (len) => new Uint8Array(len); // creates Uint8Array
    const u8of = (byte) => Uint8Array.of(byte); // another shortcut
    let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
    let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same
    let i = 0; // Iterations counter, will throw when over 1000
    const reset = () => {
        v.fill(1);
        k.fill(0);
        i = 0;
    };
    const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)
    const reseed = (seed = u8n(0)) => {
        // HMAC-DRBG reseed() function. Steps D-G
        k = h(u8of(0x00), seed); // k = hmac(k || v || 0x00 || seed)
        v = h(); // v = hmac(k || v)
        if (seed.length === 0)
            return;
        k = h(u8of(0x01), seed); // k = hmac(k || v || 0x01 || seed)
        v = h(); // v = hmac(k || v)
    };
    const gen = () => {
        // HMAC-DRBG generate() function
        if (i++ >= 1000)
            throw new Error('drbg: tried 1000 values');
        let len = 0;
        const out = [];
        while (len < qByteLen) {
            v = h();
            const sl = v.slice();
            out.push(sl);
            len += v.length;
        }
        return concatBytes_(...out);
    };
    const genUntil = (seed, pred) => {
        reset();
        reseed(seed); // Steps D-G
        let res = undefined; // Step H: grind until k is in [1..n-1]
        while (!(res = pred(gen())))
            reseed();
        reset();
        return res;
    };
    return genUntil;
}
// Validating curves and fields
const validatorFns = {
    bigint: (val) => typeof val === 'bigint',
    function: (val) => typeof val === 'function',
    boolean: (val) => typeof val === 'boolean',
    string: (val) => typeof val === 'string',
    stringOrUint8Array: (val) => typeof val === 'string' || isBytes_(val),
    isSafeInteger: (val) => Number.isSafeInteger(val),
    array: (val) => Array.isArray(val),
    field: (val, object) => object.Fp.isValid(val),
    hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),
};
// type Record<K extends string | number | symbol, T> = { [P in K]: T; }
export function validateObject(object, validators, optValidators = {}) {
    const checkField = (fieldName, type, isOptional) => {
        const checkVal = validatorFns[type];
        if (typeof checkVal !== 'function')
            throw new Error('invalid validator function');
        const val = object[fieldName];
        if (isOptional && val === undefined)
            return;
        if (!checkVal(val, object)) {
            throw new Error('param ' + String(fieldName) + ' is invalid. Expected ' + type + ', got ' + val);
        }
    };
    for (const [fieldName, type] of Object.entries(validators))
        checkField(fieldName, type, false);
    for (const [fieldName, type] of Object.entries(optValidators))
        checkField(fieldName, type, true);
    return object;
}
// validate type tests
// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };
// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!
// // Should fail type-check
// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });
// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });
// const z3 = validateObject(o, { test: 'boolean', z: 'bug' });
// const z4 = validateObject(o, { a: 'boolean', z: 'bug' });
export function isHash(val) {
    return typeof val === 'function' && Number.isSafeInteger(val.outputLen);
}
export function _validateObject(object, fields, optFields = {}) {
    if (!object || typeof object !== 'object')
        throw new Error('expected valid options object');
    function checkField(fieldName, expectedType, isOpt) {
        const val = object[fieldName];
        if (isOpt && val === undefined)
            return;
        const current = typeof val;
        if (current !== expectedType || val === null)
            throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
    }
    Object.entries(fields).forEach(([k, v]) => checkField(k, v, false));
    Object.entries(optFields).forEach(([k, v]) => checkField(k, v, true));
}
/**
 * throws not implemented error
 */
export const notImplemented = () => {
    throw new Error('not implemented');
};
/**
 * Memoizes (caches) computation result.
 * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.
 */
export function memoized(fn) {
    const map = new WeakMap();
    return (arg, ...args) => {
        const val = map.get(arg);
        if (val !== undefined)
            return val;
        const computed = fn(arg, ...args);
        map.set(arg, computed);
        return computed;
    };
}
//# sourceMappingURL=utils.js.map/**
 * Internal Merkle-Damgard hash utils.
 * @module
 */
import { Hash, abytes, aexists, aoutput, clean, createView, toBytes } from "./utils.js";
/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */
export function setBigUint64(view, byteOffset, value, isLE) {
    if (typeof view.setBigUint64 === 'function')
        return view.setBigUint64(byteOffset, value, isLE);
    const _32n = BigInt(32);
    const _u32_max = BigInt(0xffffffff);
    const wh = Number((value >> _32n) & _u32_max);
    const wl = Number(value & _u32_max);
    const h = isLE ? 4 : 0;
    const l = isLE ? 0 : 4;
    view.setUint32(byteOffset + h, wh, isLE);
    view.setUint32(byteOffset + l, wl, isLE);
}
/** Choice: a ? b : c */
export function Chi(a, b, c) {
    return (a & b) ^ (~a & c);
}
/** Majority function, true if any two inputs is true. */
export function Maj(a, b, c) {
    return (a & b) ^ (a & c) ^ (b & c);
}
/**
 * Merkle-Damgard hash construction base class.
 * Could be used to create MD5, RIPEMD, SHA1, SHA2.
 */
export class HashMD extends Hash {
    constructor(blockLen, outputLen, padOffset, isLE) {
        super();
        this.finished = false;
        this.length = 0;
        this.pos = 0;
        this.destroyed = false;
        this.blockLen = blockLen;
        this.outputLen = outputLen;
        this.padOffset = padOffset;
        this.isLE = isLE;
        this.buffer = new Uint8Array(blockLen);
        this.view = createView(this.buffer);
    }
    update(data) {
        aexists(this);
        data = toBytes(data);
        abytes(data);
        const { view, buffer, blockLen } = this;
        const len = data.length;
        for (let pos = 0; pos < len;) {
            const take = Math.min(blockLen - this.pos, len - pos);
            // Fast path: we have at least one block in input, cast it to view and process
            if (take === blockLen) {
                const dataView = createView(data);
                for (; blockLen <= len - pos; pos += blockLen)
                    this.process(dataView, pos);
                continue;
            }
            buffer.set(data.subarray(pos, pos + take), this.pos);
            this.pos += take;
            pos += take;
            if (this.pos === blockLen) {
                this.process(view, 0);
                this.pos = 0;
            }
        }
        this.length += data.length;
        this.roundClean();
        return this;
    }
    digestInto(out) {
        aexists(this);
        aoutput(out, this);
        this.finished = true;
        // Padding
        // We can avoid allocation of buffer for padding completely if it
        // was previously not allocated here. But it won't change performance.
        const { buffer, view, blockLen, isLE } = this;
        let { pos } = this;
        // append the bit '1' to the message
        buffer[pos++] = 0b10000000;
        clean(this.buffer.subarray(pos));
        // we have less than padOffset left in buffer, so we cannot put length in
        // current block, need process it and pad again
        if (this.padOffset > blockLen - pos) {
            this.process(view, 0);
            pos = 0;
        }
        // Pad until full block byte with zeros
        for (let i = pos; i < blockLen; i++)
            buffer[i] = 0;
        // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that
        // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.
        // So we just write lowest 64 bits of that value.
        setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
        this.process(view, 0);
        const oview = createView(out);
        const len = this.outputLen;
        // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT
        if (len % 4)
            throw new Error('_sha2: outputLen should be aligned to 32bit');
        const outLen = len / 4;
        const state = this.get();
        if (outLen > state.length)
            throw new Error('_sha2: outputLen bigger than state');
        for (let i = 0; i < outLen; i++)
            oview.setUint32(4 * i, state[i], isLE);
    }
    digest() {
        const { buffer, outputLen } = this;
        this.digestInto(buffer);
        const res = buffer.slice(0, outputLen);
        this.destroy();
        return res;
    }
    _cloneInto(to) {
        to || (to = new this.constructor());
        to.set(...this.get());
        const { blockLen, buffer, length, finished, destroyed, pos } = this;
        to.destroyed = destroyed;
        to.finished = finished;
        to.length = length;
        to.pos = pos;
        if (length % blockLen)
            to.buffer.set(buffer);
        return to;
    }
    clone() {
        return this._cloneInto();
    }
}
/**
 * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.
 * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.
 */
/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */
export const SHA256_IV = /* @__PURE__ */ Uint32Array.from([
    0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
]);
/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */
export const SHA224_IV = /* @__PURE__ */ Uint32Array.from([
    0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,
]);
/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */
export const SHA384_IV = /* @__PURE__ */ Uint32Array.from([
    0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,
    0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,
]);
/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */
export const SHA512_IV = /* @__PURE__ */ Uint32Array.from([
    0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,
    0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,
]);
//# sourceMappingURL=_md.js.map/**
 * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.
 * @todo re-check https://issues.chromium.org/issues/42212588
 * @module
 */
const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
const _32n = /* @__PURE__ */ BigInt(32);
function fromBig(n, le = false) {
    if (le)
        return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };
    return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
}
function split(lst, le = false) {
    const len = lst.length;
    let Ah = new Uint32Array(len);
    let Al = new Uint32Array(len);
    for (let i = 0; i < len; i++) {
        const { h, l } = fromBig(lst[i], le);
        [Ah[i], Al[i]] = [h, l];
    }
    return [Ah, Al];
}
const toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);
// for Shift in [0, 32)
const shrSH = (h, _l, s) => h >>> s;
const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
// Right rotate for Shift in [1, 32)
const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));
const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
// Right rotate for Shift in (32, 64), NOTE: 32 is special case.
const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));
const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));
// Right rotate for shift===32 (just swaps l&h)
const rotr32H = (_h, l) => l;
const rotr32L = (h, _l) => h;
// Left rotate for Shift in [1, 32)
const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));
const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));
// Left rotate for Shift in (32, 64), NOTE: 32 is special case.
const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));
const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));
// JS uses 32-bit signed integers for bitwise operations which means we cannot
// simple take carry out of low bit sum by shift, we need to use division.
function add(Ah, Al, Bh, Bl) {
    const l = (Al >>> 0) + (Bl >>> 0);
    return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };
}
// Addition with more than 2 elements
const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;
const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;
const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;
// prettier-ignore
export { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig };
// prettier-ignore
const u64 = {
    fromBig, split, toBig,
    shrSH, shrSL,
    rotrSH, rotrSL, rotrBH, rotrBL,
    rotr32H, rotr32L,
    rotlSH, rotlSL, rotlBH, rotlBL,
    add, add3L, add3H, add4L, add4H, add5H, add5L,
};
export default u64;
//# sourceMappingURL=_u64.js.mapexport const crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;
//# sourceMappingURL=crypto.js.map/**
 * HMAC: RFC2104 message authentication code.
 * @module
 */
import { abytes, aexists, ahash, clean, Hash, toBytes } from "./utils.js";
export class HMAC extends Hash {
    constructor(hash, _key) {
        super();
        this.finished = false;
        this.destroyed = false;
        ahash(hash);
        const key = toBytes(_key);
        this.iHash = hash.create();
        if (typeof this.iHash.update !== 'function')
            throw new Error('Expected instance of class which extends utils.Hash');
        this.blockLen = this.iHash.blockLen;
        this.outputLen = this.iHash.outputLen;
        const blockLen = this.blockLen;
        const pad = new Uint8Array(blockLen);
        // blockLen can be bigger than outputLen
        pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
        for (let i = 0; i < pad.length; i++)
            pad[i] ^= 0x36;
        this.iHash.update(pad);
        // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone
        this.oHash = hash.create();
        // Undo internal XOR && apply outer XOR
        for (let i = 0; i < pad.length; i++)
            pad[i] ^= 0x36 ^ 0x5c;
        this.oHash.update(pad);
        clean(pad);
    }
    update(buf) {
        aexists(this);
        this.iHash.update(buf);
        return this;
    }
    digestInto(out) {
        aexists(this);
        abytes(out, this.outputLen);
        this.finished = true;
        this.iHash.digestInto(out);
        this.oHash.update(out);
        this.oHash.digestInto(out);
        this.destroy();
    }
    digest() {
        const out = new Uint8Array(this.oHash.outputLen);
        this.digestInto(out);
        return out;
    }
    _cloneInto(to) {
        // Create new instance without calling constructor since key already in state and we don't know it.
        to || (to = Object.create(Object.getPrototypeOf(this), {}));
        const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
        to = to;
        to.finished = finished;
        to.destroyed = destroyed;
        to.blockLen = blockLen;
        to.outputLen = outputLen;
        to.oHash = oHash._cloneInto(to.oHash);
        to.iHash = iHash._cloneInto(to.iHash);
        return to;
    }
    clone() {
        return this._cloneInto();
    }
    destroy() {
        this.destroyed = true;
        this.oHash.destroy();
        this.iHash.destroy();
    }
}
/**
 * HMAC: RFC2104 message authentication code.
 * @param hash - function that would be used e.g. sha256
 * @param key - message key
 * @param message - message data
 * @example
 * import { hmac } from '@noble/hashes/hmac';
 * import { sha256 } from '@noble/hashes/sha2';
 * const mac1 = hmac(sha256, 'key', 'message');
 */
export const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
hmac.create = (hash, key) => new HMAC(hash, key);
//# sourceMappingURL=hmac.js.map/**

SHA1 (RFC 3174), MD5 (RFC 1321) and RIPEMD160 (RFC 2286) legacy, weak hash functions.
Don't use them in a new protocol. What "weak" means:

- Collisions can be made with 2^18 effort in MD5, 2^60 in SHA1, 2^80 in RIPEMD160.
- No practical pre-image attacks (only theoretical, 2^123.4)
- HMAC seems kinda ok: https://datatracker.ietf.org/doc/html/rfc6151
 * @module
 */
import { Chi, HashMD, Maj } from "./_md.js";
import { clean, createHasher, rotl } from "./utils.js";
/** Initial SHA1 state */
const SHA1_IV = /* @__PURE__ */ Uint32Array.from([
    0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0,
]);
// Reusable temporary buffer
const SHA1_W = /* @__PURE__ */ new Uint32Array(80);
/** SHA1 legacy hash class. */
export class SHA1 extends HashMD {
    constructor() {
        super(64, 20, 8, false);
        this.A = SHA1_IV[0] | 0;
        this.B = SHA1_IV[1] | 0;
        this.C = SHA1_IV[2] | 0;
        this.D = SHA1_IV[3] | 0;
        this.E = SHA1_IV[4] | 0;
    }
    get() {
        const { A, B, C, D, E } = this;
        return [A, B, C, D, E];
    }
    set(A, B, C, D, E) {
        this.A = A | 0;
        this.B = B | 0;
        this.C = C | 0;
        this.D = D | 0;
        this.E = E | 0;
    }
    process(view, offset) {
        for (let i = 0; i < 16; i++, offset += 4)
            SHA1_W[i] = view.getUint32(offset, false);
        for (let i = 16; i < 80; i++)
            SHA1_W[i] = rotl(SHA1_W[i - 3] ^ SHA1_W[i - 8] ^ SHA1_W[i - 14] ^ SHA1_W[i - 16], 1);
        // Compression function main loop, 80 rounds
        let { A, B, C, D, E } = this;
        for (let i = 0; i < 80; i++) {
            let F, K;
            if (i < 20) {
                F = Chi(B, C, D);
                K = 0x5a827999;
            }
            else if (i < 40) {
                F = B ^ C ^ D;
                K = 0x6ed9eba1;
            }
            else if (i < 60) {
                F = Maj(B, C, D);
                K = 0x8f1bbcdc;
            }
            else {
                F = B ^ C ^ D;
                K = 0xca62c1d6;
            }
            const T = (rotl(A, 5) + F + E + K + SHA1_W[i]) | 0;
            E = D;
            D = C;
            C = rotl(B, 30);
            B = A;
            A = T;
        }
        // Add the compressed chunk to the current hash value
        A = (A + this.A) | 0;
        B = (B + this.B) | 0;
        C = (C + this.C) | 0;
        D = (D + this.D) | 0;
        E = (E + this.E) | 0;
        this.set(A, B, C, D, E);
    }
    roundClean() {
        clean(SHA1_W);
    }
    destroy() {
        this.set(0, 0, 0, 0, 0);
        clean(this.buffer);
    }
}
/** SHA1 (RFC 3174) legacy hash function. It was cryptographically broken. */
export const sha1 = /* @__PURE__ */ createHasher(() => new SHA1());
/** Per-round constants */
const p32 = /* @__PURE__ */ Math.pow(2, 32);
const K = /* @__PURE__ */ Array.from({ length: 64 }, (_, i) => Math.floor(p32 * Math.abs(Math.sin(i + 1))));
/** md5 initial state: same as sha1, but 4 u32 instead of 5. */
const MD5_IV = /* @__PURE__ */ SHA1_IV.slice(0, 4);
// Reusable temporary buffer
const MD5_W = /* @__PURE__ */ new Uint32Array(16);
/** MD5 legacy hash class. */
export class MD5 extends HashMD {
    constructor() {
        super(64, 16, 8, true);
        this.A = MD5_IV[0] | 0;
        this.B = MD5_IV[1] | 0;
        this.C = MD5_IV[2] | 0;
        this.D = MD5_IV[3] | 0;
    }
    get() {
        const { A, B, C, D } = this;
        return [A, B, C, D];
    }
    set(A, B, C, D) {
        this.A = A | 0;
        this.B = B | 0;
        this.C = C | 0;
        this.D = D | 0;
    }
    process(view, offset) {
        for (let i = 0; i < 16; i++, offset += 4)
            MD5_W[i] = view.getUint32(offset, true);
        // Compression function main loop, 64 rounds
        let { A, B, C, D } = this;
        for (let i = 0; i < 64; i++) {
            let F, g, s;
            if (i < 16) {
                F = Chi(B, C, D);
                g = i;
                s = [7, 12, 17, 22];
            }
            else if (i < 32) {
                F = Chi(D, B, C);
                g = (5 * i + 1) % 16;
                s = [5, 9, 14, 20];
            }
            else if (i < 48) {
                F = B ^ C ^ D;
                g = (3 * i + 5) % 16;
                s = [4, 11, 16, 23];
            }
            else {
                F = C ^ (B | ~D);
                g = (7 * i) % 16;
                s = [6, 10, 15, 21];
            }
            F = F + A + K[i] + MD5_W[g];
            A = D;
            D = C;
            C = B;
            B = B + rotl(F, s[i % 4]);
        }
        // Add the compressed chunk to the current hash value
        A = (A + this.A) | 0;
        B = (B + this.B) | 0;
        C = (C + this.C) | 0;
        D = (D + this.D) | 0;
        this.set(A, B, C, D);
    }
    roundClean() {
        clean(MD5_W);
    }
    destroy() {
        this.set(0, 0, 0, 0);
        clean(this.buffer);
    }
}
/**
 * MD5 (RFC 1321) legacy hash function. It was cryptographically broken.
 * MD5 architecture is similar to SHA1, with some differences:
 * - Reduced output length: 16 bytes (128 bit) instead of 20
 * - 64 rounds, instead of 80
 * - Little-endian: could be faster, but will require more code
 * - Non-linear index selection: huge speed-up for unroll
 * - Per round constants: more memory accesses, additional speed-up for unroll
 */
export const md5 = /* @__PURE__ */ createHasher(() => new MD5());
// RIPEMD-160
const Rho160 = /* @__PURE__ */ Uint8Array.from([
    7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
]);
const Id160 = /* @__PURE__ */ (() => Uint8Array.from(new Array(16).fill(0).map((_, i) => i)))();
const Pi160 = /* @__PURE__ */ (() => Id160.map((i) => (9 * i + 5) % 16))();
const idxLR = /* @__PURE__ */ (() => {
    const L = [Id160];
    const R = [Pi160];
    const res = [L, R];
    for (let i = 0; i < 4; i++)
        for (let j of res)
            j.push(j[i].map((k) => Rho160[k]));
    return res;
})();
const idxL = /* @__PURE__ */ (() => idxLR[0])();
const idxR = /* @__PURE__ */ (() => idxLR[1])();
// const [idxL, idxR] = idxLR;
const shifts160 = /* @__PURE__ */ [
    [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8],
    [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7],
    [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9],
    [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6],
    [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5],
].map((i) => Uint8Array.from(i));
const shiftsL160 = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts160[i][j]));
const shiftsR160 = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts160[i][j]));
const Kl160 = /* @__PURE__ */ Uint32Array.from([
    0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e,
]);
const Kr160 = /* @__PURE__ */ Uint32Array.from([
    0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000,
]);
// It's called f() in spec.
function ripemd_f(group, x, y, z) {
    if (group === 0)
        return x ^ y ^ z;
    if (group === 1)
        return (x & y) | (~x & z);
    if (group === 2)
        return (x | ~y) ^ z;
    if (group === 3)
        return (x & z) | (y & ~z);
    return x ^ (y | ~z);
}
// Reusable temporary buffer
const BUF_160 = /* @__PURE__ */ new Uint32Array(16);
export class RIPEMD160 extends HashMD {
    constructor() {
        super(64, 20, 8, true);
        this.h0 = 0x67452301 | 0;
        this.h1 = 0xefcdab89 | 0;
        this.h2 = 0x98badcfe | 0;
        this.h3 = 0x10325476 | 0;
        this.h4 = 0xc3d2e1f0 | 0;
    }
    get() {
        const { h0, h1, h2, h3, h4 } = this;
        return [h0, h1, h2, h3, h4];
    }
    set(h0, h1, h2, h3, h4) {
        this.h0 = h0 | 0;
        this.h1 = h1 | 0;
        this.h2 = h2 | 0;
        this.h3 = h3 | 0;
        this.h4 = h4 | 0;
    }
    process(view, offset) {
        for (let i = 0; i < 16; i++, offset += 4)
            BUF_160[i] = view.getUint32(offset, true);
        // prettier-ignore
        let al = this.h0 | 0, ar = al, bl = this.h1 | 0, br = bl, cl = this.h2 | 0, cr = cl, dl = this.h3 | 0, dr = dl, el = this.h4 | 0, er = el;
        // Instead of iterating 0 to 80, we split it into 5 groups
        // And use the groups in constants, functions, etc. Much simpler
        for (let group = 0; group < 5; group++) {
            const rGroup = 4 - group;
            const hbl = Kl160[group], hbr = Kr160[group]; // prettier-ignore
            const rl = idxL[group], rr = idxR[group]; // prettier-ignore
            const sl = shiftsL160[group], sr = shiftsR160[group]; // prettier-ignore
            for (let i = 0; i < 16; i++) {
                const tl = (rotl(al + ripemd_f(group, bl, cl, dl) + BUF_160[rl[i]] + hbl, sl[i]) + el) | 0;
                al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore
            }
            // 2 loops are 10% faster
            for (let i = 0; i < 16; i++) {
                const tr = (rotl(ar + ripemd_f(rGroup, br, cr, dr) + BUF_160[rr[i]] + hbr, sr[i]) + er) | 0;
                ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr; // prettier-ignore
            }
        }
        // Add the compressed chunk to the current hash value
        this.set((this.h1 + cl + dr) | 0, (this.h2 + dl + er) | 0, (this.h3 + el + ar) | 0, (this.h4 + al + br) | 0, (this.h0 + bl + cr) | 0);
    }
    roundClean() {
        clean(BUF_160);
    }
    destroy() {
        this.destroyed = true;
        clean(this.buffer);
        this.set(0, 0, 0, 0, 0);
    }
}
/**
 * RIPEMD-160 - a legacy hash function from 1990s.
 * * https://homes.esat.kuleuven.be/~bosselae/ripemd160.html
 * * https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf
 */
export const ripemd160 = /* @__PURE__ */ createHasher(() => new RIPEMD160());
//# sourceMappingURL=legacy.js.map{
  "type": "module",
  "sideEffects": false,
  "browser": {
    "node:crypto": false
  },
  "node": {
    "./crypto": "./esm/cryptoNode.js"
  }
}
/**
 * PBKDF (RFC 2898). Can be used to create a key from password and salt.
 * @module
 */
import { hmac } from "./hmac.js";
// prettier-ignore
import { ahash, anumber, asyncLoop, checkOpts, clean, createView, Hash, kdfInputToBytes } from "./utils.js";
// Common prologue and epilogue for sync/async functions
function pbkdf2Init(hash, _password, _salt, _opts) {
    ahash(hash);
    const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts);
    const { c, dkLen, asyncTick } = opts;
    anumber(c);
    anumber(dkLen);
    anumber(asyncTick);
    if (c < 1)
        throw new Error('iterations (c) should be >= 1');
    const password = kdfInputToBytes(_password);
    const salt = kdfInputToBytes(_salt);
    // DK = PBKDF2(PRF, Password, Salt, c, dkLen);
    const DK = new Uint8Array(dkLen);
    // U1 = PRF(Password, Salt + INT_32_BE(i))
    const PRF = hmac.create(hash, password);
    const PRFSalt = PRF._cloneInto().update(salt);
    return { c, dkLen, asyncTick, DK, PRF, PRFSalt };
}
function pbkdf2Output(PRF, PRFSalt, DK, prfW, u) {
    PRF.destroy();
    PRFSalt.destroy();
    if (prfW)
        prfW.destroy();
    clean(u);
    return DK;
}
/**
 * PBKDF2-HMAC: RFC 2898 key derivation function
 * @param hash - hash function that would be used e.g. sha256
 * @param password - password from which a derived key is generated
 * @param salt - cryptographic salt
 * @param opts - {c, dkLen} where c is work factor and dkLen is output message size
 * @example
 * const key = pbkdf2(sha256, 'password', 'salt', { dkLen: 32, c: Math.pow(2, 18) });
 */
export function pbkdf2(hash, password, salt, opts) {
    const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);
    let prfW; // Working copy
    const arr = new Uint8Array(4);
    const view = createView(arr);
    const u = new Uint8Array(PRF.outputLen);
    // DK = T1 + T2 + ⋯ + Tdklen/hlen
    for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {
        // Ti = F(Password, Salt, c, i)
        const Ti = DK.subarray(pos, pos + PRF.outputLen);
        view.setInt32(0, ti, false);
        // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc
        // U1 = PRF(Password, Salt + INT_32_BE(i))
        (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);
        Ti.set(u.subarray(0, Ti.length));
        for (let ui = 1; ui < c; ui++) {
            // Uc = PRF(Password, Uc−1)
            PRF._cloneInto(prfW).update(u).digestInto(u);
            for (let i = 0; i < Ti.length; i++)
                Ti[i] ^= u[i];
        }
    }
    return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);
}
/**
 * PBKDF2-HMAC: RFC 2898 key derivation function. Async version.
 * @example
 * await pbkdf2Async(sha256, 'password', 'salt', { dkLen: 32, c: 500_000 });
 */
export async function pbkdf2Async(hash, password, salt, opts) {
    const { c, dkLen, asyncTick, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);
    let prfW; // Working copy
    const arr = new Uint8Array(4);
    const view = createView(arr);
    const u = new Uint8Array(PRF.outputLen);
    // DK = T1 + T2 + ⋯ + Tdklen/hlen
    for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {
        // Ti = F(Password, Salt, c, i)
        const Ti = DK.subarray(pos, pos + PRF.outputLen);
        view.setInt32(0, ti, false);
        // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc
        // U1 = PRF(Password, Salt + INT_32_BE(i))
        (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);
        Ti.set(u.subarray(0, Ti.length));
        await asyncLoop(c - 1, asyncTick, () => {
            // Uc = PRF(Password, Uc−1)
            PRF._cloneInto(prfW).update(u).digestInto(u);
            for (let i = 0; i < Ti.length; i++)
                Ti[i] ^= u[i];
        });
    }
    return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);
}
//# sourceMappingURL=pbkdf2.js.map/**
 * RFC 7914 Scrypt KDF. Can be used to create a key from password and salt.
 * @module
 */
import { pbkdf2 } from "./pbkdf2.js";
import { sha256 } from "./sha2.js";
// prettier-ignore
import { anumber, asyncLoop, checkOpts, clean, rotl, swap32IfBE, u32 } from "./utils.js";
// The main Scrypt loop: uses Salsa extensively.
// Six versions of the function were tried, this is the fastest one.
// prettier-ignore
function XorAndSalsa(prev, pi, input, ii, out, oi) {
    // Based on https://cr.yp.to/salsa20.html
    // Xor blocks
    let y00 = prev[pi++] ^ input[ii++], y01 = prev[pi++] ^ input[ii++];
    let y02 = prev[pi++] ^ input[ii++], y03 = prev[pi++] ^ input[ii++];
    let y04 = prev[pi++] ^ input[ii++], y05 = prev[pi++] ^ input[ii++];
    let y06 = prev[pi++] ^ input[ii++], y07 = prev[pi++] ^ input[ii++];
    let y08 = prev[pi++] ^ input[ii++], y09 = prev[pi++] ^ input[ii++];
    let y10 = prev[pi++] ^ input[ii++], y11 = prev[pi++] ^ input[ii++];
    let y12 = prev[pi++] ^ input[ii++], y13 = prev[pi++] ^ input[ii++];
    let y14 = prev[pi++] ^ input[ii++], y15 = prev[pi++] ^ input[ii++];
    // Save state to temporary variables (salsa)
    let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15;
    // Main loop (salsa)
    for (let i = 0; i < 8; i += 2) {
        x04 ^= rotl(x00 + x12 | 0, 7);
        x08 ^= rotl(x04 + x00 | 0, 9);
        x12 ^= rotl(x08 + x04 | 0, 13);
        x00 ^= rotl(x12 + x08 | 0, 18);
        x09 ^= rotl(x05 + x01 | 0, 7);
        x13 ^= rotl(x09 + x05 | 0, 9);
        x01 ^= rotl(x13 + x09 | 0, 13);
        x05 ^= rotl(x01 + x13 | 0, 18);
        x14 ^= rotl(x10 + x06 | 0, 7);
        x02 ^= rotl(x14 + x10 | 0, 9);
        x06 ^= rotl(x02 + x14 | 0, 13);
        x10 ^= rotl(x06 + x02 | 0, 18);
        x03 ^= rotl(x15 + x11 | 0, 7);
        x07 ^= rotl(x03 + x15 | 0, 9);
        x11 ^= rotl(x07 + x03 | 0, 13);
        x15 ^= rotl(x11 + x07 | 0, 18);
        x01 ^= rotl(x00 + x03 | 0, 7);
        x02 ^= rotl(x01 + x00 | 0, 9);
        x03 ^= rotl(x02 + x01 | 0, 13);
        x00 ^= rotl(x03 + x02 | 0, 18);
        x06 ^= rotl(x05 + x04 | 0, 7);
        x07 ^= rotl(x06 + x05 | 0, 9);
        x04 ^= rotl(x07 + x06 | 0, 13);
        x05 ^= rotl(x04 + x07 | 0, 18);
        x11 ^= rotl(x10 + x09 | 0, 7);
        x08 ^= rotl(x11 + x10 | 0, 9);
        x09 ^= rotl(x08 + x11 | 0, 13);
        x10 ^= rotl(x09 + x08 | 0, 18);
        x12 ^= rotl(x15 + x14 | 0, 7);
        x13 ^= rotl(x12 + x15 | 0, 9);
        x14 ^= rotl(x13 + x12 | 0, 13);
        x15 ^= rotl(x14 + x13 | 0, 18);
    }
    // Write output (salsa)
    out[oi++] = (y00 + x00) | 0;
    out[oi++] = (y01 + x01) | 0;
    out[oi++] = (y02 + x02) | 0;
    out[oi++] = (y03 + x03) | 0;
    out[oi++] = (y04 + x04) | 0;
    out[oi++] = (y05 + x05) | 0;
    out[oi++] = (y06 + x06) | 0;
    out[oi++] = (y07 + x07) | 0;
    out[oi++] = (y08 + x08) | 0;
    out[oi++] = (y09 + x09) | 0;
    out[oi++] = (y10 + x10) | 0;
    out[oi++] = (y11 + x11) | 0;
    out[oi++] = (y12 + x12) | 0;
    out[oi++] = (y13 + x13) | 0;
    out[oi++] = (y14 + x14) | 0;
    out[oi++] = (y15 + x15) | 0;
}
function BlockMix(input, ii, out, oi, r) {
    // The block B is r 128-byte chunks (which is equivalent of 2r 64-byte chunks)
    let head = oi + 0;
    let tail = oi + 16 * r;
    for (let i = 0; i < 16; i++)
        out[tail + i] = input[ii + (2 * r - 1) * 16 + i]; // X ← B[2r−1]
    for (let i = 0; i < r; i++, head += 16, ii += 16) {
        // We write odd & even Yi at same time. Even: 0bXXXXX0 Odd:  0bXXXXX1
        XorAndSalsa(out, tail, input, ii, out, head); // head[i] = Salsa(blockIn[2*i] ^ tail[i-1])
        if (i > 0)
            tail += 16; // First iteration overwrites tmp value in tail
        XorAndSalsa(out, head, input, (ii += 16), out, tail); // tail[i] = Salsa(blockIn[2*i+1] ^ head[i])
    }
}
// Common prologue and epilogue for sync/async functions
function scryptInit(password, salt, _opts) {
    // Maxmem - 1GB+1KB by default
    const opts = checkOpts({
        dkLen: 32,
        asyncTick: 10,
        maxmem: 1024 ** 3 + 1024,
    }, _opts);
    const { N, r, p, dkLen, asyncTick, maxmem, onProgress } = opts;
    anumber(N);
    anumber(r);
    anumber(p);
    anumber(dkLen);
    anumber(asyncTick);
    anumber(maxmem);
    if (onProgress !== undefined && typeof onProgress !== 'function')
        throw new Error('progressCb should be function');
    const blockSize = 128 * r;
    const blockSize32 = blockSize / 4;
    // Max N is 2^32 (Integrify is 32-bit). Real limit is 2^22: JS engines Uint8Array limit is 4GB in 2024.
    // Spec check `N >= 2^(blockSize / 8)` is not done for compat with popular libs,
    // which used incorrect r: 1, p: 8. Also, the check seems to be a spec error:
    // https://www.rfc-editor.org/errata_search.php?rfc=7914
    const pow32 = Math.pow(2, 32);
    if (N <= 1 || (N & (N - 1)) !== 0 || N > pow32) {
        throw new Error('Scrypt: N must be larger than 1, a power of 2, and less than 2^32');
    }
    if (p < 0 || p > ((pow32 - 1) * 32) / blockSize) {
        throw new Error('Scrypt: p must be a positive integer less than or equal to ((2^32 - 1) * 32) / (128 * r)');
    }
    if (dkLen < 0 || dkLen > (pow32 - 1) * 32) {
        throw new Error('Scrypt: dkLen should be positive integer less than or equal to (2^32 - 1) * 32');
    }
    const memUsed = blockSize * (N + p);
    if (memUsed > maxmem) {
        throw new Error('Scrypt: memused is bigger than maxMem. Expected 128 * r * (N + p) > maxmem of ' + maxmem);
    }
    // [B0...Bp−1] ← PBKDF2HMAC-SHA256(Passphrase, Salt, 1, blockSize*ParallelizationFactor)
    // Since it has only one iteration there is no reason to use async variant
    const B = pbkdf2(sha256, password, salt, { c: 1, dkLen: blockSize * p });
    const B32 = u32(B);
    // Re-used between parallel iterations. Array(iterations) of B
    const V = u32(new Uint8Array(blockSize * N));
    const tmp = u32(new Uint8Array(blockSize));
    let blockMixCb = () => { };
    if (onProgress) {
        const totalBlockMix = 2 * N * p;
        // Invoke callback if progress changes from 10.01 to 10.02
        // Allows to draw smooth progress bar on up to 8K screen
        const callbackPer = Math.max(Math.floor(totalBlockMix / 10000), 1);
        let blockMixCnt = 0;
        blockMixCb = () => {
            blockMixCnt++;
            if (onProgress && (!(blockMixCnt % callbackPer) || blockMixCnt === totalBlockMix))
                onProgress(blockMixCnt / totalBlockMix);
        };
    }
    return { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick };
}
function scryptOutput(password, dkLen, B, V, tmp) {
    const res = pbkdf2(sha256, password, B, { c: 1, dkLen });
    clean(B, V, tmp);
    return res;
}
/**
 * Scrypt KDF from RFC 7914.
 * @param password - pass
 * @param salt - salt
 * @param opts - parameters
 * - `N` is cpu/mem work factor (power of 2 e.g. 2**18)
 * - `r` is block size (8 is common), fine-tunes sequential memory read size and performance
 * - `p` is parallelization factor (1 is common)
 * - `dkLen` is output key length in bytes e.g. 32.
 * - `asyncTick` - (default: 10) max time in ms for which async function can block execution
 * - `maxmem` - (default: `1024 ** 3 + 1024` aka 1GB+1KB). A limit that the app could use for scrypt
 * - `onProgress` - callback function that would be executed for progress report
 * @returns Derived key
 * @example
 * scrypt('password', 'salt', { N: 2**18, r: 8, p: 1, dkLen: 32 });
 */
export function scrypt(password, salt, opts) {
    const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb } = scryptInit(password, salt, opts);
    swap32IfBE(B32);
    for (let pi = 0; pi < p; pi++) {
        const Pi = blockSize32 * pi;
        for (let i = 0; i < blockSize32; i++)
            V[i] = B32[Pi + i]; // V[0] = B[i]
        for (let i = 0, pos = 0; i < N - 1; i++) {
            BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]);
            blockMixCb();
        }
        BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element
        blockMixCb();
        for (let i = 0; i < N; i++) {
            // First u32 of the last 64-byte block (u32 is LE)
            const j = B32[Pi + blockSize32 - 16] % N; // j = Integrify(X) % iterations
            for (let k = 0; k < blockSize32; k++)
                tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; // tmp = B ^ V[j]
            BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j])
            blockMixCb();
        }
    }
    swap32IfBE(B32);
    return scryptOutput(password, dkLen, B, V, tmp);
}
/**
 * Scrypt KDF from RFC 7914. Async version.
 * @example
 * await scryptAsync('password', 'salt', { N: 2**18, r: 8, p: 1, dkLen: 32 });
 */
export async function scryptAsync(password, salt, opts) {
    const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick } = scryptInit(password, salt, opts);
    swap32IfBE(B32);
    for (let pi = 0; pi < p; pi++) {
        const Pi = blockSize32 * pi;
        for (let i = 0; i < blockSize32; i++)
            V[i] = B32[Pi + i]; // V[0] = B[i]
        let pos = 0;
        await asyncLoop(N - 1, asyncTick, () => {
            BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]);
            blockMixCb();
        });
        BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element
        blockMixCb();
        await asyncLoop(N, asyncTick, () => {
            // First u32 of the last 64-byte block (u32 is LE)
            const j = B32[Pi + blockSize32 - 16] % N; // j = Integrify(X) % iterations
            for (let k = 0; k < blockSize32; k++)
                tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; // tmp = B ^ V[j]
            BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j])
            blockMixCb();
        });
    }
    swap32IfBE(B32);
    return scryptOutput(password, dkLen, B, V, tmp);
}
//# sourceMappingURL=scrypt.js.map/**
 * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.
 * SHA256 is the fastest hash implementable in JS, even faster than Blake3.
 * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and
 * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).
 * @module
 */
import { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from "./_md.js";
import * as u64 from "./_u64.js";
import { clean, createHasher, rotr } from "./utils.js";
/**
 * Round constants:
 * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)
 */
// prettier-ignore
const SHA256_K = /* @__PURE__ */ Uint32Array.from([
    0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
    0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
    0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
    0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
    0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
    0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
    0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
    0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
]);
/** Reusable temporary buffer. "W" comes straight from spec. */
const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
export class SHA256 extends HashMD {
    constructor(outputLen = 32) {
        super(64, outputLen, 8, false);
        // We cannot use array here since array allows indexing by variable
        // which means optimizer/compiler cannot use registers.
        this.A = SHA256_IV[0] | 0;
        this.B = SHA256_IV[1] | 0;
        this.C = SHA256_IV[2] | 0;
        this.D = SHA256_IV[3] | 0;
        this.E = SHA256_IV[4] | 0;
        this.F = SHA256_IV[5] | 0;
        this.G = SHA256_IV[6] | 0;
        this.H = SHA256_IV[7] | 0;
    }
    get() {
        const { A, B, C, D, E, F, G, H } = this;
        return [A, B, C, D, E, F, G, H];
    }
    // prettier-ignore
    set(A, B, C, D, E, F, G, H) {
        this.A = A | 0;
        this.B = B | 0;
        this.C = C | 0;
        this.D = D | 0;
        this.E = E | 0;
        this.F = F | 0;
        this.G = G | 0;
        this.H = H | 0;
    }
    process(view, offset) {
        // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array
        for (let i = 0; i < 16; i++, offset += 4)
            SHA256_W[i] = view.getUint32(offset, false);
        for (let i = 16; i < 64; i++) {
            const W15 = SHA256_W[i - 15];
            const W2 = SHA256_W[i - 2];
            const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);
            const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);
            SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;
        }
        // Compression function main loop, 64 rounds
        let { A, B, C, D, E, F, G, H } = this;
        for (let i = 0; i < 64; i++) {
            const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
            const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
            const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
            const T2 = (sigma0 + Maj(A, B, C)) | 0;
            H = G;
            G = F;
            F = E;
            E = (D + T1) | 0;
            D = C;
            C = B;
            B = A;
            A = (T1 + T2) | 0;
        }
        // Add the compressed chunk to the current hash value
        A = (A + this.A) | 0;
        B = (B + this.B) | 0;
        C = (C + this.C) | 0;
        D = (D + this.D) | 0;
        E = (E + this.E) | 0;
        F = (F + this.F) | 0;
        G = (G + this.G) | 0;
        H = (H + this.H) | 0;
        this.set(A, B, C, D, E, F, G, H);
    }
    roundClean() {
        clean(SHA256_W);
    }
    destroy() {
        this.set(0, 0, 0, 0, 0, 0, 0, 0);
        clean(this.buffer);
    }
}
export class SHA224 extends SHA256 {
    constructor() {
        super(28);
        this.A = SHA224_IV[0] | 0;
        this.B = SHA224_IV[1] | 0;
        this.C = SHA224_IV[2] | 0;
        this.D = SHA224_IV[3] | 0;
        this.E = SHA224_IV[4] | 0;
        this.F = SHA224_IV[5] | 0;
        this.G = SHA224_IV[6] | 0;
        this.H = SHA224_IV[7] | 0;
    }
}
// SHA2-512 is slower than sha256 in js because u64 operations are slow.
// Round contants
// First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409
// prettier-ignore
const K512 = /* @__PURE__ */ (() => u64.split([
    '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',
    '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',
    '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',
    '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',
    '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',
    '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',
    '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',
    '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',
    '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',
    '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',
    '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',
    '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',
    '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',
    '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',
    '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',
    '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',
    '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',
    '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',
    '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',
    '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'
].map(n => BigInt(n))))();
const SHA512_Kh = /* @__PURE__ */ (() => K512[0])();
const SHA512_Kl = /* @__PURE__ */ (() => K512[1])();
// Reusable temporary buffers
const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
export class SHA512 extends HashMD {
    constructor(outputLen = 64) {
        super(128, outputLen, 16, false);
        // We cannot use array here since array allows indexing by variable
        // which means optimizer/compiler cannot use registers.
        // h -- high 32 bits, l -- low 32 bits
        this.Ah = SHA512_IV[0] | 0;
        this.Al = SHA512_IV[1] | 0;
        this.Bh = SHA512_IV[2] | 0;
        this.Bl = SHA512_IV[3] | 0;
        this.Ch = SHA512_IV[4] | 0;
        this.Cl = SHA512_IV[5] | 0;
        this.Dh = SHA512_IV[6] | 0;
        this.Dl = SHA512_IV[7] | 0;
        this.Eh = SHA512_IV[8] | 0;
        this.El = SHA512_IV[9] | 0;
        this.Fh = SHA512_IV[10] | 0;
        this.Fl = SHA512_IV[11] | 0;
        this.Gh = SHA512_IV[12] | 0;
        this.Gl = SHA512_IV[13] | 0;
        this.Hh = SHA512_IV[14] | 0;
        this.Hl = SHA512_IV[15] | 0;
    }
    // prettier-ignore
    get() {
        const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
        return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
    }
    // prettier-ignore
    set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
        this.Ah = Ah | 0;
        this.Al = Al | 0;
        this.Bh = Bh | 0;
        this.Bl = Bl | 0;
        this.Ch = Ch | 0;
        this.Cl = Cl | 0;
        this.Dh = Dh | 0;
        this.Dl = Dl | 0;
        this.Eh = Eh | 0;
        this.El = El | 0;
        this.Fh = Fh | 0;
        this.Fl = Fl | 0;
        this.Gh = Gh | 0;
        this.Gl = Gl | 0;
        this.Hh = Hh | 0;
        this.Hl = Hl | 0;
    }
    process(view, offset) {
        // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array
        for (let i = 0; i < 16; i++, offset += 4) {
            SHA512_W_H[i] = view.getUint32(offset);
            SHA512_W_L[i] = view.getUint32((offset += 4));
        }
        for (let i = 16; i < 80; i++) {
            // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)
            const W15h = SHA512_W_H[i - 15] | 0;
            const W15l = SHA512_W_L[i - 15] | 0;
            const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);
            const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);
            // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)
            const W2h = SHA512_W_H[i - 2] | 0;
            const W2l = SHA512_W_L[i - 2] | 0;
            const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);
            const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);
            // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];
            const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
            const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
            SHA512_W_H[i] = SUMh | 0;
            SHA512_W_L[i] = SUMl | 0;
        }
        let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
        // Compression function main loop, 80 rounds
        for (let i = 0; i < 80; i++) {
            // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)
            const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);
            const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);
            //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
            const CHIh = (Eh & Fh) ^ (~Eh & Gh);
            const CHIl = (El & Fl) ^ (~El & Gl);
            // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]
            // prettier-ignore
            const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
            const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
            const T1l = T1ll | 0;
            // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)
            const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);
            const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);
            const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);
            const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);
            Hh = Gh | 0;
            Hl = Gl | 0;
            Gh = Fh | 0;
            Gl = Fl | 0;
            Fh = Eh | 0;
            Fl = El | 0;
            ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
            Dh = Ch | 0;
            Dl = Cl | 0;
            Ch = Bh | 0;
            Cl = Bl | 0;
            Bh = Ah | 0;
            Bl = Al | 0;
            const All = u64.add3L(T1l, sigma0l, MAJl);
            Ah = u64.add3H(All, T1h, sigma0h, MAJh);
            Al = All | 0;
        }
        // Add the compressed chunk to the current hash value
        ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
        ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
        ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
        ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
        ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
        ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
        ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
        ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
        this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
    }
    roundClean() {
        clean(SHA512_W_H, SHA512_W_L);
    }
    destroy() {
        clean(this.buffer);
        this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
    }
}
export class SHA384 extends SHA512 {
    constructor() {
        super(48);
        this.Ah = SHA384_IV[0] | 0;
        this.Al = SHA384_IV[1] | 0;
        this.Bh = SHA384_IV[2] | 0;
        this.Bl = SHA384_IV[3] | 0;
        this.Ch = SHA384_IV[4] | 0;
        this.Cl = SHA384_IV[5] | 0;
        this.Dh = SHA384_IV[6] | 0;
        this.Dl = SHA384_IV[7] | 0;
        this.Eh = SHA384_IV[8] | 0;
        this.El = SHA384_IV[9] | 0;
        this.Fh = SHA384_IV[10] | 0;
        this.Fl = SHA384_IV[11] | 0;
        this.Gh = SHA384_IV[12] | 0;
        this.Gl = SHA384_IV[13] | 0;
        this.Hh = SHA384_IV[14] | 0;
        this.Hl = SHA384_IV[15] | 0;
    }
}
/**
 * Truncated SHA512/256 and SHA512/224.
 * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as "intermediary" IV of SHA512/t.
 * Then t hashes string to produce result IV.
 * See `test/misc/sha2-gen-iv.js`.
 */
/** SHA512/224 IV */
const T224_IV = /* @__PURE__ */ Uint32Array.from([
    0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,
    0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,
]);
/** SHA512/256 IV */
const T256_IV = /* @__PURE__ */ Uint32Array.from([
    0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,
    0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,
]);
export class SHA512_224 extends SHA512 {
    constructor() {
        super(28);
        this.Ah = T224_IV[0] | 0;
        this.Al = T224_IV[1] | 0;
        this.Bh = T224_IV[2] | 0;
        this.Bl = T224_IV[3] | 0;
        this.Ch = T224_IV[4] | 0;
        this.Cl = T224_IV[5] | 0;
        this.Dh = T224_IV[6] | 0;
        this.Dl = T224_IV[7] | 0;
        this.Eh = T224_IV[8] | 0;
        this.El = T224_IV[9] | 0;
        this.Fh = T224_IV[10] | 0;
        this.Fl = T224_IV[11] | 0;
        this.Gh = T224_IV[12] | 0;
        this.Gl = T224_IV[13] | 0;
        this.Hh = T224_IV[14] | 0;
        this.Hl = T224_IV[15] | 0;
    }
}
export class SHA512_256 extends SHA512 {
    constructor() {
        super(32);
        this.Ah = T256_IV[0] | 0;
        this.Al = T256_IV[1] | 0;
        this.Bh = T256_IV[2] | 0;
        this.Bl = T256_IV[3] | 0;
        this.Ch = T256_IV[4] | 0;
        this.Cl = T256_IV[5] | 0;
        this.Dh = T256_IV[6] | 0;
        this.Dl = T256_IV[7] | 0;
        this.Eh = T256_IV[8] | 0;
        this.El = T256_IV[9] | 0;
        this.Fh = T256_IV[10] | 0;
        this.Fl = T256_IV[11] | 0;
        this.Gh = T256_IV[12] | 0;
        this.Gl = T256_IV[13] | 0;
        this.Hh = T256_IV[14] | 0;
        this.Hl = T256_IV[15] | 0;
    }
}
/**
 * SHA2-256 hash function from RFC 4634.
 *
 * It is the fastest JS hash, even faster than Blake3.
 * To break sha256 using birthday attack, attackers need to try 2^128 hashes.
 * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
 */
export const sha256 = /* @__PURE__ */ createHasher(() => new SHA256());
/** SHA2-224 hash function from RFC 4634 */
export const sha224 = /* @__PURE__ */ createHasher(() => new SHA224());
/** SHA2-512 hash function from RFC 4634. */
export const sha512 = /* @__PURE__ */ createHasher(() => new SHA512());
/** SHA2-384 hash function from RFC 4634. */
export const sha384 = /* @__PURE__ */ createHasher(() => new SHA384());
/**
 * SHA2-512/256 "truncated" hash function, with improved resistance to length extension attacks.
 * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).
 */
export const sha512_256 = /* @__PURE__ */ createHasher(() => new SHA512_256());
/**
 * SHA2-512/224 "truncated" hash function, with improved resistance to length extension attacks.
 * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).
 */
export const sha512_224 = /* @__PURE__ */ createHasher(() => new SHA512_224());
//# sourceMappingURL=sha2.js.map/**
 * Utilities for hex, bytes, CSPRNG.
 * @module
 */
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
// node.js versions earlier than v19 don't declare it in global scope.
// For node.js, package.json#exports field mapping rewrites import
// from `crypto` to `cryptoNode`, which imports native module.
// Makes the utils un-importable in browsers without a bundler.
// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.
import { crypto } from '@noble/hashes/crypto';
/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */
export function isBytes(a) {
    return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
}
/** Asserts something is positive integer. */
export function anumber(n) {
    if (!Number.isSafeInteger(n) || n < 0)
        throw new Error('positive integer expected, got ' + n);
}
/** Asserts something is Uint8Array. */
export function abytes(b, ...lengths) {
    if (!isBytes(b))
        throw new Error('Uint8Array expected');
    if (lengths.length > 0 && !lengths.includes(b.length))
        throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);
}
/** Asserts something is hash */
export function ahash(h) {
    if (typeof h !== 'function' || typeof h.create !== 'function')
        throw new Error('Hash should be wrapped by utils.createHasher');
    anumber(h.outputLen);
    anumber(h.blockLen);
}
/** Asserts a hash instance has not been destroyed / finished */
export function aexists(instance, checkFinished = true) {
    if (instance.destroyed)
        throw new Error('Hash instance has been destroyed');
    if (checkFinished && instance.finished)
        throw new Error('Hash#digest() has already been called');
}
/** Asserts output is properly-sized byte array */
export function aoutput(out, instance) {
    abytes(out);
    const min = instance.outputLen;
    if (out.length < min) {
        throw new Error('digestInto() expects output buffer of length at least ' + min);
    }
}
/** Cast u8 / u16 / u32 to u8. */
export function u8(arr) {
    return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
}
/** Cast u8 / u16 / u32 to u32. */
export function u32(arr) {
    return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
}
/** Zeroize a byte array. Warning: JS provides no guarantees. */
export function clean(...arrays) {
    for (let i = 0; i < arrays.length; i++) {
        arrays[i].fill(0);
    }
}
/** Create DataView of an array for easy byte-level manipulation. */
export function createView(arr) {
    return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
}
/** The rotate right (circular right shift) operation for uint32 */
export function rotr(word, shift) {
    return (word << (32 - shift)) | (word >>> shift);
}
/** The rotate left (circular left shift) operation for uint32 */
export function rotl(word, shift) {
    return (word << shift) | ((word >>> (32 - shift)) >>> 0);
}
/** Is current platform little-endian? Most are. Big-Endian platform: IBM */
export const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();
/** The byte swap operation for uint32 */
export function byteSwap(word) {
    return (((word << 24) & 0xff000000) |
        ((word << 8) & 0xff0000) |
        ((word >>> 8) & 0xff00) |
        ((word >>> 24) & 0xff));
}
/** Conditionally byte swap if on a big-endian platform */
export const swap8IfBE = isLE
    ? (n) => n
    : (n) => byteSwap(n);
/** @deprecated */
export const byteSwapIfBE = swap8IfBE;
/** In place byte swap for Uint32Array */
export function byteSwap32(arr) {
    for (let i = 0; i < arr.length; i++) {
        arr[i] = byteSwap(arr[i]);
    }
    return arr;
}
export const swap32IfBE = isLE
    ? (u) => u
    : byteSwap32;
// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex
const hasHexBuiltin = /* @__PURE__ */ (() => 
// @ts-ignore
typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();
// Array where index 0xf0 (240) is mapped to string 'f0'
const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
/**
 * Convert byte array to hex string. Uses built-in function, when available.
 * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
 */
export function bytesToHex(bytes) {
    abytes(bytes);
    // @ts-ignore
    if (hasHexBuiltin)
        return bytes.toHex();
    // pre-caching improves the speed 6x
    let hex = '';
    for (let i = 0; i < bytes.length; i++) {
        hex += hexes[bytes[i]];
    }
    return hex;
}
// We use optimized technique to convert hex string to byte array
const asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
function asciiToBase16(ch) {
    if (ch >= asciis._0 && ch <= asciis._9)
        return ch - asciis._0; // '2' => 50-48
    if (ch >= asciis.A && ch <= asciis.F)
        return ch - (asciis.A - 10); // 'B' => 66-(65-10)
    if (ch >= asciis.a && ch <= asciis.f)
        return ch - (asciis.a - 10); // 'b' => 98-(97-10)
    return;
}
/**
 * Convert hex string to byte array. Uses built-in function, when available.
 * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
 */
export function hexToBytes(hex) {
    if (typeof hex !== 'string')
        throw new Error('hex string expected, got ' + typeof hex);
    // @ts-ignore
    if (hasHexBuiltin)
        return Uint8Array.fromHex(hex);
    const hl = hex.length;
    const al = hl / 2;
    if (hl % 2)
        throw new Error('hex string expected, got unpadded hex of length ' + hl);
    const array = new Uint8Array(al);
    for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
        const n1 = asciiToBase16(hex.charCodeAt(hi));
        const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
        if (n1 === undefined || n2 === undefined) {
            const char = hex[hi] + hex[hi + 1];
            throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
        }
        array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163
    }
    return array;
}
/**
 * There is no setImmediate in browser and setTimeout is slow.
 * Call of async fn will return Promise, which will be fullfiled only on
 * next scheduler queue processing step and this is exactly what we need.
 */
export const nextTick = async () => { };
/** Returns control to thread each 'tick' ms to avoid blocking. */
export async function asyncLoop(iters, tick, cb) {
    let ts = Date.now();
    for (let i = 0; i < iters; i++) {
        cb(i);
        // Date.now() is not monotonic, so in case if clock goes backwards we return return control too
        const diff = Date.now() - ts;
        if (diff >= 0 && diff < tick)
            continue;
        await nextTick();
        ts += diff;
    }
}
/**
 * Converts string to bytes using UTF8 encoding.
 * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])
 */
export function utf8ToBytes(str) {
    if (typeof str !== 'string')
        throw new Error('string expected');
    return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
}
/**
 * Converts bytes to string using UTF8 encoding.
 * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'
 */
export function bytesToUtf8(bytes) {
    return new TextDecoder().decode(bytes);
}
/**
 * Normalizes (non-hex) string or Uint8Array to Uint8Array.
 * Warning: when Uint8Array is passed, it would NOT get copied.
 * Keep in mind for future mutable operations.
 */
export function toBytes(data) {
    if (typeof data === 'string')
        data = utf8ToBytes(data);
    abytes(data);
    return data;
}
/**
 * Helper for KDFs: consumes uint8array or string.
 * When string is passed, does utf8 decoding, using TextDecoder.
 */
export function kdfInputToBytes(data) {
    if (typeof data === 'string')
        data = utf8ToBytes(data);
    abytes(data);
    return data;
}
/** Copies several Uint8Arrays into one. */
export function concatBytes(...arrays) {
    let sum = 0;
    for (let i = 0; i < arrays.length; i++) {
        const a = arrays[i];
        abytes(a);
        sum += a.length;
    }
    const res = new Uint8Array(sum);
    for (let i = 0, pad = 0; i < arrays.length; i++) {
        const a = arrays[i];
        res.set(a, pad);
        pad += a.length;
    }
    return res;
}
export function checkOpts(defaults, opts) {
    if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')
        throw new Error('options should be object or undefined');
    const merged = Object.assign(defaults, opts);
    return merged;
}
/** For runtime check if class implements interface */
export class Hash {
}
/** Wraps hash function, creating an interface on top of it */
export function createHasher(hashCons) {
    const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
    const tmp = hashCons();
    hashC.outputLen = tmp.outputLen;
    hashC.blockLen = tmp.blockLen;
    hashC.create = () => hashCons();
    return hashC;
}
export function createOptHasher(hashCons) {
    const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();
    const tmp = hashCons({});
    hashC.outputLen = tmp.outputLen;
    hashC.blockLen = tmp.blockLen;
    hashC.create = (opts) => hashCons(opts);
    return hashC;
}
export function createXOFer(hashCons) {
    const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();
    const tmp = hashCons({});
    hashC.outputLen = tmp.outputLen;
    hashC.blockLen = tmp.blockLen;
    hashC.create = (opts) => hashCons(opts);
    return hashC;
}
export const wrapConstructor = createHasher;
export const wrapConstructorWithOpts = createOptHasher;
export const wrapXOFConstructorWithOpts = createXOFer;
/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */
export function randomBytes(bytesLength = 32) {
    if (crypto && typeof crypto.getRandomValues === 'function') {
        return crypto.getRandomValues(new Uint8Array(bytesLength));
    }
    // Legacy Node.js compatibility
    if (crypto && typeof crypto.randomBytes === 'function') {
        return Uint8Array.from(crypto.randomBytes(bytesLength));
    }
    throw new Error('crypto.getRandomValues must be defined');
}
//# sourceMappingURL=utils.js.map/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */
function isBytes(a) {
    return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
}
/** Asserts something is Uint8Array. */
function abytes(b, ...lengths) {
    if (!isBytes(b))
        throw new Error('Uint8Array expected');
    if (lengths.length > 0 && !lengths.includes(b.length))
        throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);
}
function isArrayOf(isString, arr) {
    if (!Array.isArray(arr))
        return false;
    if (arr.length === 0)
        return true;
    if (isString) {
        return arr.every((item) => typeof item === 'string');
    }
    else {
        return arr.every((item) => Number.isSafeInteger(item));
    }
}
// no abytes: seems to have 10% slowdown. Why?!
function afn(input) {
    if (typeof input !== 'function')
        throw new Error('function expected');
    return true;
}
function astr(label, input) {
    if (typeof input !== 'string')
        throw new Error(`${label}: string expected`);
    return true;
}
function anumber(n) {
    if (!Number.isSafeInteger(n))
        throw new Error(`invalid integer: ${n}`);
}
function aArr(input) {
    if (!Array.isArray(input))
        throw new Error('array expected');
}
function astrArr(label, input) {
    if (!isArrayOf(true, input))
        throw new Error(`${label}: array of strings expected`);
}
function anumArr(label, input) {
    if (!isArrayOf(false, input))
        throw new Error(`${label}: array of numbers expected`);
}
/**
 * @__NO_SIDE_EFFECTS__
 */
function chain(...args) {
    const id = (a) => a;
    // Wrap call in closure so JIT can inline calls
    const wrap = (a, b) => (c) => a(b(c));
    // Construct chain of args[-1].encode(args[-2].encode([...]))
    const encode = args.map((x) => x.encode).reduceRight(wrap, id);
    // Construct chain of args[0].decode(args[1].decode(...))
    const decode = args.map((x) => x.decode).reduce(wrap, id);
    return { encode, decode };
}
/**
 * Encodes integer radix representation to array of strings using alphabet and back.
 * Could also be array of strings.
 * @__NO_SIDE_EFFECTS__
 */
function alphabet(letters) {
    // mapping 1 to "b"
    const lettersA = typeof letters === 'string' ? letters.split('') : letters;
    const len = lettersA.length;
    astrArr('alphabet', lettersA);
    // mapping "b" to 1
    const indexes = new Map(lettersA.map((l, i) => [l, i]));
    return {
        encode: (digits) => {
            aArr(digits);
            return digits.map((i) => {
                if (!Number.isSafeInteger(i) || i < 0 || i >= len)
                    throw new Error(`alphabet.encode: digit index outside alphabet "${i}". Allowed: ${letters}`);
                return lettersA[i];
            });
        },
        decode: (input) => {
            aArr(input);
            return input.map((letter) => {
                astr('alphabet.decode', letter);
                const i = indexes.get(letter);
                if (i === undefined)
                    throw new Error(`Unknown letter: "${letter}". Allowed: ${letters}`);
                return i;
            });
        },
    };
}
/**
 * @__NO_SIDE_EFFECTS__
 */
function join(separator = '') {
    astr('join', separator);
    return {
        encode: (from) => {
            astrArr('join.decode', from);
            return from.join(separator);
        },
        decode: (to) => {
            astr('join.decode', to);
            return to.split(separator);
        },
    };
}
/**
 * Pad strings array so it has integer number of bits
 * @__NO_SIDE_EFFECTS__
 */
function padding(bits, chr = '=') {
    anumber(bits);
    astr('padding', chr);
    return {
        encode(data) {
            astrArr('padding.encode', data);
            while ((data.length * bits) % 8)
                data.push(chr);
            return data;
        },
        decode(input) {
            astrArr('padding.decode', input);
            let end = input.length;
            if ((end * bits) % 8)
                throw new Error('padding: invalid, string should have whole number of bytes');
            for (; end > 0 && input[end - 1] === chr; end--) {
                const last = end - 1;
                const byte = last * bits;
                if (byte % 8 === 0)
                    throw new Error('padding: invalid, string has too much padding');
            }
            return input.slice(0, end);
        },
    };
}
/**
 * @__NO_SIDE_EFFECTS__
 */
function normalize(fn) {
    afn(fn);
    return { encode: (from) => from, decode: (to) => fn(to) };
}
/**
 * Slow: O(n^2) time complexity
 */
function convertRadix(data, from, to) {
    // base 1 is impossible
    if (from < 2)
        throw new Error(`convertRadix: invalid from=${from}, base cannot be less than 2`);
    if (to < 2)
        throw new Error(`convertRadix: invalid to=${to}, base cannot be less than 2`);
    aArr(data);
    if (!data.length)
        return [];
    let pos = 0;
    const res = [];
    const digits = Array.from(data, (d) => {
        anumber(d);
        if (d < 0 || d >= from)
            throw new Error(`invalid integer: ${d}`);
        return d;
    });
    const dlen = digits.length;
    while (true) {
        let carry = 0;
        let done = true;
        for (let i = pos; i < dlen; i++) {
            const digit = digits[i];
            const fromCarry = from * carry;
            const digitBase = fromCarry + digit;
            if (!Number.isSafeInteger(digitBase) ||
                fromCarry / from !== carry ||
                digitBase - digit !== fromCarry) {
                throw new Error('convertRadix: carry overflow');
            }
            const div = digitBase / to;
            carry = digitBase % to;
            const rounded = Math.floor(div);
            digits[i] = rounded;
            if (!Number.isSafeInteger(rounded) || rounded * to + carry !== digitBase)
                throw new Error('convertRadix: carry overflow');
            if (!done)
                continue;
            else if (!rounded)
                pos = i;
            else
                done = false;
        }
        res.push(carry);
        if (done)
            break;
    }
    for (let i = 0; i < data.length - 1 && data[i] === 0; i++)
        res.push(0);
    return res.reverse();
}
const gcd = (a, b) => (b === 0 ? a : gcd(b, a % b));
const radix2carry = /* @__NO_SIDE_EFFECTS__ */ (from, to) => from + (to - gcd(from, to));
const powers = /* @__PURE__ */ (() => {
    let res = [];
    for (let i = 0; i < 40; i++)
        res.push(2 ** i);
    return res;
})();
/**
 * Implemented with numbers, because BigInt is 5x slower
 */
function convertRadix2(data, from, to, padding) {
    aArr(data);
    if (from <= 0 || from > 32)
        throw new Error(`convertRadix2: wrong from=${from}`);
    if (to <= 0 || to > 32)
        throw new Error(`convertRadix2: wrong to=${to}`);
    if (radix2carry(from, to) > 32) {
        throw new Error(`convertRadix2: carry overflow from=${from} to=${to} carryBits=${radix2carry(from, to)}`);
    }
    let carry = 0;
    let pos = 0; // bitwise position in current element
    const max = powers[from];
    const mask = powers[to] - 1;
    const res = [];
    for (const n of data) {
        anumber(n);
        if (n >= max)
            throw new Error(`convertRadix2: invalid data word=${n} from=${from}`);
        carry = (carry << from) | n;
        if (pos + from > 32)
            throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from}`);
        pos += from;
        for (; pos >= to; pos -= to)
            res.push(((carry >> (pos - to)) & mask) >>> 0);
        const pow = powers[pos];
        if (pow === undefined)
            throw new Error('invalid carry');
        carry &= pow - 1; // clean carry, otherwise it will cause overflow
    }
    carry = (carry << (to - pos)) & mask;
    if (!padding && pos >= from)
        throw new Error('Excess padding');
    if (!padding && carry > 0)
        throw new Error(`Non-zero padding: ${carry}`);
    if (padding && pos > 0)
        res.push(carry >>> 0);
    return res;
}
/**
 * @__NO_SIDE_EFFECTS__
 */
function radix(num) {
    anumber(num);
    const _256 = 2 ** 8;
    return {
        encode: (bytes) => {
            if (!isBytes(bytes))
                throw new Error('radix.encode input should be Uint8Array');
            return convertRadix(Array.from(bytes), _256, num);
        },
        decode: (digits) => {
            anumArr('radix.decode', digits);
            return Uint8Array.from(convertRadix(digits, num, _256));
        },
    };
}
/**
 * If both bases are power of same number (like `2**8 <-> 2**64`),
 * there is a linear algorithm. For now we have implementation for power-of-two bases only.
 * @__NO_SIDE_EFFECTS__
 */
function radix2(bits, revPadding = false) {
    anumber(bits);
    if (bits <= 0 || bits > 32)
        throw new Error('radix2: bits should be in (0..32]');
    if (radix2carry(8, bits) > 32 || radix2carry(bits, 8) > 32)
        throw new Error('radix2: carry overflow');
    return {
        encode: (bytes) => {
            if (!isBytes(bytes))
                throw new Error('radix2.encode input should be Uint8Array');
            return convertRadix2(Array.from(bytes), 8, bits, !revPadding);
        },
        decode: (digits) => {
            anumArr('radix2.decode', digits);
            return Uint8Array.from(convertRadix2(digits, bits, 8, revPadding));
        },
    };
}
function unsafeWrapper(fn) {
    afn(fn);
    return function (...args) {
        try {
            return fn.apply(null, args);
        }
        catch (e) { }
    };
}
function checksum(len, fn) {
    anumber(len);
    afn(fn);
    return {
        encode(data) {
            if (!isBytes(data))
                throw new Error('checksum.encode: input should be Uint8Array');
            const sum = fn(data).slice(0, len);
            const res = new Uint8Array(data.length + len);
            res.set(data);
            res.set(sum, data.length);
            return res;
        },
        decode(data) {
            if (!isBytes(data))
                throw new Error('checksum.decode: input should be Uint8Array');
            const payload = data.slice(0, -len);
            const oldChecksum = data.slice(-len);
            const newChecksum = fn(payload).slice(0, len);
            for (let i = 0; i < len; i++)
                if (newChecksum[i] !== oldChecksum[i])
                    throw new Error('Invalid checksum');
            return payload;
        },
    };
}
// prettier-ignore
export const utils = {
    alphabet, chain, checksum, convertRadix, convertRadix2, radix, radix2, join, padding,
};
// RFC 4648 aka RFC 3548
// ---------------------
/**
 * base16 encoding from RFC 4648.
 * @example
 * ```js
 * base16.encode(Uint8Array.from([0x12, 0xab]));
 * // => '12AB'
 * ```
 */
export const base16 = chain(radix2(4), alphabet('0123456789ABCDEF'), join(''));
/**
 * base32 encoding from RFC 4648. Has padding.
 * Use `base32nopad` for unpadded version.
 * Also check out `base32hex`, `base32hexnopad`, `base32crockford`.
 * @example
 * ```js
 * base32.encode(Uint8Array.from([0x12, 0xab]));
 * // => 'CKVQ===='
 * base32.decode('CKVQ====');
 * // => Uint8Array.from([0x12, 0xab])
 * ```
 */
export const base32 = chain(radix2(5), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'), padding(5), join(''));
/**
 * base32 encoding from RFC 4648. No padding.
 * Use `base32` for padded version.
 * Also check out `base32hex`, `base32hexnopad`, `base32crockford`.
 * @example
 * ```js
 * base32nopad.encode(Uint8Array.from([0x12, 0xab]));
 * // => 'CKVQ'
 * base32nopad.decode('CKVQ');
 * // => Uint8Array.from([0x12, 0xab])
 * ```
 */
export const base32nopad = chain(radix2(5), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'), join(''));
/**
 * base32 encoding from RFC 4648. Padded. Compared to ordinary `base32`, slightly different alphabet.
 * Use `base32hexnopad` for unpadded version.
 * @example
 * ```js
 * base32hex.encode(Uint8Array.from([0x12, 0xab]));
 * // => '2ALG===='
 * base32hex.decode('2ALG====');
 * // => Uint8Array.from([0x12, 0xab])
 * ```
 */
export const base32hex = chain(radix2(5), alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'), padding(5), join(''));
/**
 * base32 encoding from RFC 4648. No padding. Compared to ordinary `base32`, slightly different alphabet.
 * Use `base32hex` for padded version.
 * @example
 * ```js
 * base32hexnopad.encode(Uint8Array.from([0x12, 0xab]));
 * // => '2ALG'
 * base32hexnopad.decode('2ALG');
 * // => Uint8Array.from([0x12, 0xab])
 * ```
 */
export const base32hexnopad = chain(radix2(5), alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'), join(''));
/**
 * base32 encoding from RFC 4648. Doug Crockford's version.
 * https://www.crockford.com/base32.html
 * @example
 * ```js
 * base32crockford.encode(Uint8Array.from([0x12, 0xab]));
 * // => '2ANG'
 * base32crockford.decode('2ANG');
 * // => Uint8Array.from([0x12, 0xab])
 * ```
 */
export const base32crockford = chain(radix2(5), alphabet('0123456789ABCDEFGHJKMNPQRSTVWXYZ'), join(''), normalize((s) => s.toUpperCase().replace(/O/g, '0').replace(/[IL]/g, '1')));
// Built-in base64 conversion https://caniuse.com/mdn-javascript_builtins_uint8array_frombase64
// prettier-ignore
const hasBase64Builtin = /* @__PURE__ */ (() => typeof Uint8Array.from([]).toBase64 === 'function' &&
    typeof Uint8Array.fromBase64 === 'function')();
const decodeBase64Builtin = (s, isUrl) => {
    astr('base64', s);
    const re = isUrl ? /^[A-Za-z0-9=_-]+$/ : /^[A-Za-z0-9=+/]+$/;
    const alphabet = isUrl ? 'base64url' : 'base64';
    if (s.length > 0 && !re.test(s))
        throw new Error('invalid base64');
    return Uint8Array.fromBase64(s, { alphabet, lastChunkHandling: 'strict' });
};
/**
 * base64 from RFC 4648. Padded.
 * Use `base64nopad` for unpadded version.
 * Also check out `base64url`, `base64urlnopad`.
 * Falls back to built-in function, when available.
 * @example
 * ```js
 * base64.encode(Uint8Array.from([0x12, 0xab]));
 * // => 'Eqs='
 * base64.decode('Eqs=');
 * // => Uint8Array.from([0x12, 0xab])
 * ```
 */
// prettier-ignore
export const base64 = hasBase64Builtin ? {
    encode(b) { abytes(b); return b.toBase64(); },
    decode(s) { return decodeBase64Builtin(s, false); },
} : chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'), padding(6), join(''));
/**
 * base64 from RFC 4648. No padding.
 * Use `base64` for padded version.
 * @example
 * ```js
 * base64nopad.encode(Uint8Array.from([0x12, 0xab]));
 * // => 'Eqs'
 * base64nopad.decode('Eqs');
 * // => Uint8Array.from([0x12, 0xab])
 * ```
 */
export const base64nopad = chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'), join(''));
/**
 * base64 from RFC 4648, using URL-safe alphabet. Padded.
 * Use `base64urlnopad` for unpadded version.
 * Falls back to built-in function, when available.
 * @example
 * ```js
 * base64url.encode(Uint8Array.from([0x12, 0xab]));
 * // => 'Eqs='
 * base64url.decode('Eqs=');
 * // => Uint8Array.from([0x12, 0xab])
 * ```
 */
// prettier-ignore
export const base64url = hasBase64Builtin ? {
    encode(b) { abytes(b); return b.toBase64({ alphabet: 'base64url' }); },
    decode(s) { return decodeBase64Builtin(s, true); },
} : chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'), padding(6), join(''));
/**
 * base64 from RFC 4648, using URL-safe alphabet. No padding.
 * Use `base64url` for padded version.
 * @example
 * ```js
 * base64urlnopad.encode(Uint8Array.from([0x12, 0xab]));
 * // => 'Eqs'
 * base64urlnopad.decode('Eqs');
 * // => Uint8Array.from([0x12, 0xab])
 * ```
 */
export const base64urlnopad = chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'), join(''));
// base58 code
// -----------
const genBase58 = /* @__NO_SIDE_EFFECTS__ */ (abc) => chain(radix(58), alphabet(abc), join(''));
/**
 * base58: base64 without ambigous characters +, /, 0, O, I, l.
 * Quadratic (O(n^2)) - so, can't be used on large inputs.
 * @example
 * ```js
 * base58.decode('01abcdef');
 * // => '3UhJW'
 * ```
 */
export const base58 = genBase58('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz');
/**
 * base58: flickr version. Check out `base58`.
 */
export const base58flickr = genBase58('123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ');
/**
 * base58: XRP version. Check out `base58`.
 */
export const base58xrp = genBase58('rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz');
// Data len (index) -> encoded block len
const XMR_BLOCK_LEN = [0, 2, 3, 5, 6, 7, 9, 10, 11];
/**
 * base58: XMR version. Check out `base58`.
 * Done in 8-byte blocks (which equals 11 chars in decoding). Last (non-full) block padded with '1' to size in XMR_BLOCK_LEN.
 * Block encoding significantly reduces quadratic complexity of base58.
 */
export const base58xmr = {
    encode(data) {
        let res = '';
        for (let i = 0; i < data.length; i += 8) {
            const block = data.subarray(i, i + 8);
            res += base58.encode(block).padStart(XMR_BLOCK_LEN[block.length], '1');
        }
        return res;
    },
    decode(str) {
        let res = [];
        for (let i = 0; i < str.length; i += 11) {
            const slice = str.slice(i, i + 11);
            const blockLen = XMR_BLOCK_LEN.indexOf(slice.length);
            const block = base58.decode(slice);
            for (let j = 0; j < block.length - blockLen; j++) {
                if (block[j] !== 0)
                    throw new Error('base58xmr: wrong padding');
            }
            res = res.concat(Array.from(block.slice(block.length - blockLen)));
        }
        return Uint8Array.from(res);
    },
};
/**
 * Method, which creates base58check encoder.
 * Requires function, calculating sha256.
 */
export const createBase58check = (sha256) => chain(checksum(4, (data) => sha256(sha256(data))), base58);
/**
 * Use `createBase58check` instead.
 * @deprecated
 */
export const base58check = createBase58check;
const BECH_ALPHABET = chain(alphabet('qpzry9x8gf2tvdw0s3jn54khce6mua7l'), join(''));
const POLYMOD_GENERATORS = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];
function bech32Polymod(pre) {
    const b = pre >> 25;
    let chk = (pre & 0x1ffffff) << 5;
    for (let i = 0; i < POLYMOD_GENERATORS.length; i++) {
        if (((b >> i) & 1) === 1)
            chk ^= POLYMOD_GENERATORS[i];
    }
    return chk;
}
function bechChecksum(prefix, words, encodingConst = 1) {
    const len = prefix.length;
    let chk = 1;
    for (let i = 0; i < len; i++) {
        const c = prefix.charCodeAt(i);
        if (c < 33 || c > 126)
            throw new Error(`Invalid prefix (${prefix})`);
        chk = bech32Polymod(chk) ^ (c >> 5);
    }
    chk = bech32Polymod(chk);
    for (let i = 0; i < len; i++)
        chk = bech32Polymod(chk) ^ (prefix.charCodeAt(i) & 0x1f);
    for (let v of words)
        chk = bech32Polymod(chk) ^ v;
    for (let i = 0; i < 6; i++)
        chk = bech32Polymod(chk);
    chk ^= encodingConst;
    return BECH_ALPHABET.encode(convertRadix2([chk % powers[30]], 30, 5, false));
}
/**
 * @__NO_SIDE_EFFECTS__
 */
function genBech32(encoding) {
    const ENCODING_CONST = encoding === 'bech32' ? 1 : 0x2bc830a3;
    const _words = radix2(5);
    const fromWords = _words.decode;
    const toWords = _words.encode;
    const fromWordsUnsafe = unsafeWrapper(fromWords);
    function encode(prefix, words, limit = 90) {
        astr('bech32.encode prefix', prefix);
        if (isBytes(words))
            words = Array.from(words);
        anumArr('bech32.encode', words);
        const plen = prefix.length;
        if (plen === 0)
            throw new TypeError(`Invalid prefix length ${plen}`);
        const actualLength = plen + 7 + words.length;
        if (limit !== false && actualLength > limit)
            throw new TypeError(`Length ${actualLength} exceeds limit ${limit}`);
        const lowered = prefix.toLowerCase();
        const sum = bechChecksum(lowered, words, ENCODING_CONST);
        return `${lowered}1${BECH_ALPHABET.encode(words)}${sum}`;
    }
    function decode(str, limit = 90) {
        astr('bech32.decode input', str);
        const slen = str.length;
        if (slen < 8 || (limit !== false && slen > limit))
            throw new TypeError(`invalid string length: ${slen} (${str}). Expected (8..${limit})`);
        // don't allow mixed case
        const lowered = str.toLowerCase();
        if (str !== lowered && str !== str.toUpperCase())
            throw new Error(`String must be lowercase or uppercase`);
        const sepIndex = lowered.lastIndexOf('1');
        if (sepIndex === 0 || sepIndex === -1)
            throw new Error(`Letter "1" must be present between prefix and data only`);
        const prefix = lowered.slice(0, sepIndex);
        const data = lowered.slice(sepIndex + 1);
        if (data.length < 6)
            throw new Error('Data must be at least 6 characters long');
        const words = BECH_ALPHABET.decode(data).slice(0, -6);
        const sum = bechChecksum(prefix, words, ENCODING_CONST);
        if (!data.endsWith(sum))
            throw new Error(`Invalid checksum in ${str}: expected "${sum}"`);
        return { prefix, words };
    }
    const decodeUnsafe = unsafeWrapper(decode);
    function decodeToBytes(str) {
        const { prefix, words } = decode(str, false);
        return { prefix, words, bytes: fromWords(words) };
    }
    function encodeFromBytes(prefix, bytes) {
        return encode(prefix, toWords(bytes));
    }
    return {
        encode,
        decode,
        encodeFromBytes,
        decodeToBytes,
        decodeUnsafe,
        fromWords,
        fromWordsUnsafe,
        toWords,
    };
}
/**
 * bech32 from BIP 173. Operates on words.
 * For high-level, check out scure-btc-signer:
 * https://github.com/paulmillr/scure-btc-signer.
 */
export const bech32 = genBech32('bech32');
/**
 * bech32m from BIP 350. Operates on words.
 * It was to mitigate `bech32` weaknesses.
 * For high-level, check out scure-btc-signer:
 * https://github.com/paulmillr/scure-btc-signer.
 */
export const bech32m = genBech32('bech32m');
/**
 * UTF-8-to-byte decoder. Uses built-in TextDecoder / TextEncoder.
 * @example
 * ```js
 * const b = utf8.decode("hey"); // => new Uint8Array([ 104, 101, 121 ])
 * const str = utf8.encode(b); // "hey"
 * ```
 */
export const utf8 = {
    encode: (data) => new TextDecoder().decode(data),
    decode: (str) => new TextEncoder().encode(str),
};
// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex
// prettier-ignore
const hasHexBuiltin = /* @__PURE__ */ (() => typeof Uint8Array.from([]).toHex === 'function' &&
    typeof Uint8Array.fromHex === 'function')();
// prettier-ignore
const hexBuiltin = {
    encode(data) { abytes(data); return data.toHex(); },
    decode(s) { astr('hex', s); return Uint8Array.fromHex(s); },
};
/**
 * hex string decoder. Uses built-in function, when available.
 * @example
 * ```js
 * const b = hex.decode("0102ff"); // => new Uint8Array([ 1, 2, 255 ])
 * const str = hex.encode(b); // "0102ff"
 * ```
 */
export const hex = hasHexBuiltin
    ? hexBuiltin
    : chain(radix2(4), alphabet('0123456789abcdef'), join(''), normalize((s) => {
        if (typeof s !== 'string' || s.length % 2 !== 0)
            throw new TypeError(`hex.decode: expected string, got ${typeof s} with length ${s.length}`);
        return s.toLowerCase();
    }));
// prettier-ignore
const CODERS = {
    utf8, hex, base16, base32, base64, base64url, base58, base58xmr
};
const coderTypeError = 'Invalid encoding type. Available types: utf8, hex, base16, base32, base64, base64url, base58, base58xmr';
/** @deprecated */
export const bytesToString = (type, bytes) => {
    if (typeof type !== 'string' || !CODERS.hasOwnProperty(type))
        throw new TypeError(coderTypeError);
    if (!isBytes(bytes))
        throw new TypeError('bytesToString() expects Uint8Array');
    return CODERS[type].encode(bytes);
};
/** @deprecated */
export const str = bytesToString; // as in python, but for bytes only
/** @deprecated */
export const stringToBytes = (type, str) => {
    if (!CODERS.hasOwnProperty(type))
        throw new TypeError(coderTypeError);
    if (typeof str !== 'string')
        throw new TypeError('stringToBytes() expects string');
    return CODERS[type].decode(str);
};
/** @deprecated */
export const bytes = stringToBytes;
//# sourceMappingURL=index.js.map{ "type": "module", "sideEffects": false }
/**
 * @module BIP32 hierarchical deterministic (HD) wallets over secp256k1.
 * @example
 * ```js
 * import { HDKey } from "@scure/bip32";
 * const hdkey1 = HDKey.fromMasterSeed(seed);
 * const hdkey2 = HDKey.fromExtendedKey(base58key);
 * const hdkey3 = HDKey.fromJSON({ xpriv: string });
 *
 * // props
 * [hdkey1.depth, hdkey1.index, hdkey1.chainCode];
 * console.log(hdkey2.privateKey, hdkey2.publicKey);
 * console.log(hdkey3.derive("m/0/2147483647'/1"));
 * const sig = hdkey3.sign(hash);
 * hdkey3.verify(hash, sig);
 * ```
 */
/*! scure-bip32 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) */
import { mod } from '@noble/curves/abstract/modular';
import { secp256k1 as secp } from '@noble/curves/secp256k1';
import { hmac } from '@noble/hashes/hmac';
import { ripemd160 } from '@noble/hashes/legacy';
import { sha256, sha512 } from '@noble/hashes/sha2';
import { abytes, bytesToHex, concatBytes, createView, hexToBytes, utf8ToBytes, } from '@noble/hashes/utils';
import { createBase58check } from '@scure/base';
const Point = secp.ProjectivePoint;
const base58check = createBase58check(sha256);
function bytesToNumber(bytes) {
    abytes(bytes);
    const h = bytes.length === 0 ? '0' : bytesToHex(bytes);
    return BigInt('0x' + h);
}
function numberToBytes(num) {
    if (typeof num !== 'bigint')
        throw new Error('bigint expected');
    return hexToBytes(num.toString(16).padStart(64, '0'));
}
const MASTER_SECRET = utf8ToBytes('Bitcoin seed');
// Bitcoin hardcoded by default
const BITCOIN_VERSIONS = { private: 0x0488ade4, public: 0x0488b21e };
export const HARDENED_OFFSET = 0x80000000;
const hash160 = (data) => ripemd160(sha256(data));
const fromU32 = (data) => createView(data).getUint32(0, false);
const toU32 = (n) => {
    if (!Number.isSafeInteger(n) || n < 0 || n > 2 ** 32 - 1) {
        throw new Error('invalid number, should be from 0 to 2**32-1, got ' + n);
    }
    const buf = new Uint8Array(4);
    createView(buf).setUint32(0, n, false);
    return buf;
};
export class HDKey {
    get fingerprint() {
        if (!this.pubHash) {
            throw new Error('No publicKey set!');
        }
        return fromU32(this.pubHash);
    }
    get identifier() {
        return this.pubHash;
    }
    get pubKeyHash() {
        return this.pubHash;
    }
    get privateKey() {
        return this.privKeyBytes || null;
    }
    get publicKey() {
        return this.pubKey || null;
    }
    get privateExtendedKey() {
        const priv = this.privateKey;
        if (!priv) {
            throw new Error('No private key');
        }
        return base58check.encode(this.serialize(this.versions.private, concatBytes(new Uint8Array([0]), priv)));
    }
    get publicExtendedKey() {
        if (!this.pubKey) {
            throw new Error('No public key');
        }
        return base58check.encode(this.serialize(this.versions.public, this.pubKey));
    }
    static fromMasterSeed(seed, versions = BITCOIN_VERSIONS) {
        abytes(seed);
        if (8 * seed.length < 128 || 8 * seed.length > 512) {
            throw new Error('HDKey: seed length must be between 128 and 512 bits; 256 bits is advised, got ' +
                seed.length);
        }
        const I = hmac(sha512, MASTER_SECRET, seed);
        return new HDKey({
            versions,
            chainCode: I.slice(32),
            privateKey: I.slice(0, 32),
        });
    }
    static fromExtendedKey(base58key, versions = BITCOIN_VERSIONS) {
        // => version(4) || depth(1) || fingerprint(4) || index(4) || chain(32) || key(33)
        const keyBuffer = base58check.decode(base58key);
        const keyView = createView(keyBuffer);
        const version = keyView.getUint32(0, false);
        const opt = {
            versions,
            depth: keyBuffer[4],
            parentFingerprint: keyView.getUint32(5, false),
            index: keyView.getUint32(9, false),
            chainCode: keyBuffer.slice(13, 45),
        };
        const key = keyBuffer.slice(45);
        const isPriv = key[0] === 0;
        if (version !== versions[isPriv ? 'private' : 'public']) {
            throw new Error('Version mismatch');
        }
        if (isPriv) {
            return new HDKey({ ...opt, privateKey: key.slice(1) });
        }
        else {
            return new HDKey({ ...opt, publicKey: key });
        }
    }
    static fromJSON(json) {
        return HDKey.fromExtendedKey(json.xpriv);
    }
    constructor(opt) {
        this.depth = 0;
        this.index = 0;
        this.chainCode = null;
        this.parentFingerprint = 0;
        if (!opt || typeof opt !== 'object') {
            throw new Error('HDKey.constructor must not be called directly');
        }
        this.versions = opt.versions || BITCOIN_VERSIONS;
        this.depth = opt.depth || 0;
        this.chainCode = opt.chainCode || null;
        this.index = opt.index || 0;
        this.parentFingerprint = opt.parentFingerprint || 0;
        if (!this.depth) {
            if (this.parentFingerprint || this.index) {
                throw new Error('HDKey: zero depth with non-zero index/parent fingerprint');
            }
        }
        if (opt.publicKey && opt.privateKey) {
            throw new Error('HDKey: publicKey and privateKey at same time.');
        }
        if (opt.privateKey) {
            if (!secp.utils.isValidPrivateKey(opt.privateKey)) {
                throw new Error('Invalid private key');
            }
            this.privKey =
                typeof opt.privateKey === 'bigint' ? opt.privateKey : bytesToNumber(opt.privateKey);
            this.privKeyBytes = numberToBytes(this.privKey);
            this.pubKey = secp.getPublicKey(opt.privateKey, true);
        }
        else if (opt.publicKey) {
            this.pubKey = Point.fromHex(opt.publicKey).toRawBytes(true); // force compressed point
        }
        else {
            throw new Error('HDKey: no public or private key provided');
        }
        this.pubHash = hash160(this.pubKey);
    }
    derive(path) {
        if (!/^[mM]'?/.test(path)) {
            throw new Error('Path must start with "m" or "M"');
        }
        if (/^[mM]'?$/.test(path)) {
            return this;
        }
        const parts = path.replace(/^[mM]'?\//, '').split('/');
        // tslint:disable-next-line
        let child = this;
        for (const c of parts) {
            const m = /^(\d+)('?)$/.exec(c);
            const m1 = m && m[1];
            if (!m || m.length !== 3 || typeof m1 !== 'string')
                throw new Error('invalid child index: ' + c);
            let idx = +m1;
            if (!Number.isSafeInteger(idx) || idx >= HARDENED_OFFSET) {
                throw new Error('Invalid index');
            }
            // hardened key
            if (m[2] === "'") {
                idx += HARDENED_OFFSET;
            }
            child = child.deriveChild(idx);
        }
        return child;
    }
    deriveChild(index) {
        if (!this.pubKey || !this.chainCode) {
            throw new Error('No publicKey or chainCode set');
        }
        let data = toU32(index);
        if (index >= HARDENED_OFFSET) {
            // Hardened
            const priv = this.privateKey;
            if (!priv) {
                throw new Error('Could not derive hardened child key');
            }
            // Hardened child: 0x00 || ser256(kpar) || ser32(index)
            data = concatBytes(new Uint8Array([0]), priv, data);
        }
        else {
            // Normal child: serP(point(kpar)) || ser32(index)
            data = concatBytes(this.pubKey, data);
        }
        const I = hmac(sha512, this.chainCode, data);
        const childTweak = bytesToNumber(I.slice(0, 32));
        const chainCode = I.slice(32);
        if (!secp.utils.isValidPrivateKey(childTweak)) {
            throw new Error('Tweak bigger than curve order');
        }
        const opt = {
            versions: this.versions,
            chainCode,
            depth: this.depth + 1,
            parentFingerprint: this.fingerprint,
            index,
        };
        try {
            // Private parent key -> private child key
            if (this.privateKey) {
                const added = mod(this.privKey + childTweak, secp.CURVE.n);
                if (!secp.utils.isValidPrivateKey(added)) {
                    throw new Error('The tweak was out of range or the resulted private key is invalid');
                }
                opt.privateKey = added;
            }
            else {
                const added = Point.fromHex(this.pubKey).add(Point.fromPrivateKey(childTweak));
                // Cryptographically impossible: hmac-sha512 preimage would need to be found
                if (added.equals(Point.ZERO)) {
                    throw new Error('The tweak was equal to negative P, which made the result key invalid');
                }
                opt.publicKey = added.toRawBytes(true);
            }
            return new HDKey(opt);
        }
        catch (err) {
            return this.deriveChild(index + 1);
        }
    }
    sign(hash) {
        if (!this.privateKey) {
            throw new Error('No privateKey set!');
        }
        abytes(hash, 32);
        return secp.sign(hash, this.privKey).toCompactRawBytes();
    }
    verify(hash, signature) {
        abytes(hash, 32);
        abytes(signature, 64);
        if (!this.publicKey) {
            throw new Error('No publicKey set!');
        }
        let sig;
        try {
            sig = secp.Signature.fromCompact(signature);
        }
        catch (error) {
            return false;
        }
        return secp.verify(sig, hash, this.publicKey);
    }
    wipePrivateData() {
        this.privKey = undefined;
        if (this.privKeyBytes) {
            this.privKeyBytes.fill(0);
            this.privKeyBytes = undefined;
        }
        return this;
    }
    toJSON() {
        return {
            xpriv: this.privateExtendedKey,
            xpub: this.publicExtendedKey,
        };
    }
    serialize(version, key) {
        if (!this.chainCode) {
            throw new Error('No chainCode set');
        }
        abytes(key, 33);
        // version(4) || depth(1) || fingerprint(4) || index(4) || chain(32) || key(33)
        return concatBytes(toU32(version), new Uint8Array([this.depth]), toU32(this.parentFingerprint), toU32(this.index), this.chainCode, key);
    }
}
//# sourceMappingURL=index.js.map{
  "type": "module",
  "sideEffects": false
}/**
 * Audited & minimal JS implementation of
 * [BIP39 mnemonic phrases](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki).
 * @module
 * @example
```js
import * as bip39 from '@scure/bip39';
import { wordlist } from '@scure/bip39/wordlists/english';
const mn = bip39.generateMnemonic(wordlist);
console.log(mn);
const ent = bip39.mnemonicToEntropy(mn, wordlist)
bip39.entropyToMnemonic(ent, wordlist);
bip39.validateMnemonic(mn, wordlist);
await bip39.mnemonicToSeed(mn, 'password');
bip39.mnemonicToSeedSync(mn, 'password');

// Wordlists
import { wordlist as czech } from '@scure/bip39/wordlists/czech';
import { wordlist as english } from '@scure/bip39/wordlists/english';
import { wordlist as french } from '@scure/bip39/wordlists/french';
import { wordlist as italian } from '@scure/bip39/wordlists/italian';
import { wordlist as japanese } from '@scure/bip39/wordlists/japanese';
import { wordlist as korean } from '@scure/bip39/wordlists/korean';
import { wordlist as portuguese } from '@scure/bip39/wordlists/portuguese';
import { wordlist as simplifiedChinese } from '@scure/bip39/wordlists/simplified-chinese';
import { wordlist as spanish } from '@scure/bip39/wordlists/spanish';
import { wordlist as traditionalChinese } from '@scure/bip39/wordlists/traditional-chinese';
```
 */
/*! scure-bip39 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) */
import { pbkdf2, pbkdf2Async } from '@noble/hashes/pbkdf2';
import { sha256, sha512 } from '@noble/hashes/sha2';
import { abytes, anumber, randomBytes } from '@noble/hashes/utils';
import { utils as baseUtils } from '@scure/base';
// Japanese wordlist
const isJapanese = (wordlist) => wordlist[0] === '\u3042\u3044\u3053\u304f\u3057\u3093';
// Normalization replaces equivalent sequences of characters
// so that any two texts that are equivalent will be reduced
// to the same sequence of code points, called the normal form of the original text.
// https://tonsky.me/blog/unicode/#why-is-a----
function nfkd(str) {
    if (typeof str !== 'string')
        throw new TypeError('invalid mnemonic type: ' + typeof str);
    return str.normalize('NFKD');
}
function normalize(str) {
    const norm = nfkd(str);
    const words = norm.split(' ');
    if (![12, 15, 18, 21, 24].includes(words.length))
        throw new Error('Invalid mnemonic');
    return { nfkd: norm, words };
}
function aentropy(ent) {
    abytes(ent, 16, 20, 24, 28, 32);
}
/**
 * Generate x random words. Uses Cryptographically-Secure Random Number Generator.
 * @param wordlist imported wordlist for specific language
 * @param strength mnemonic strength 128-256 bits
 * @example
 * generateMnemonic(wordlist, 128)
 * // 'legal winner thank year wave sausage worth useful legal winner thank yellow'
 */
export function generateMnemonic(wordlist, strength = 128) {
    anumber(strength);
    if (strength % 32 !== 0 || strength > 256)
        throw new TypeError('Invalid entropy');
    return entropyToMnemonic(randomBytes(strength / 8), wordlist);
}
const calcChecksum = (entropy) => {
    // Checksum is ent.length/4 bits long
    const bitsLeft = 8 - entropy.length / 4;
    // Zero rightmost "bitsLeft" bits in byte
    // For example: bitsLeft=4 val=10111101 -> 10110000
    return new Uint8Array([(sha256(entropy)[0] >> bitsLeft) << bitsLeft]);
};
function getCoder(wordlist) {
    if (!Array.isArray(wordlist) || wordlist.length !== 2048 || typeof wordlist[0] !== 'string')
        throw new Error('Wordlist: expected array of 2048 strings');
    wordlist.forEach((i) => {
        if (typeof i !== 'string')
            throw new Error('wordlist: non-string element: ' + i);
    });
    return baseUtils.chain(baseUtils.checksum(1, calcChecksum), baseUtils.radix2(11, true), baseUtils.alphabet(wordlist));
}
/**
 * Reversible: Converts mnemonic string to raw entropy in form of byte array.
 * @param mnemonic 12-24 words
 * @param wordlist imported wordlist for specific language
 * @example
 * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';
 * mnemonicToEntropy(mnem, wordlist)
 * // Produces
 * new Uint8Array([
 *   0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f,
 *   0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f
 * ])
 */
export function mnemonicToEntropy(mnemonic, wordlist) {
    const { words } = normalize(mnemonic);
    const entropy = getCoder(wordlist).decode(words);
    aentropy(entropy);
    return entropy;
}
/**
 * Reversible: Converts raw entropy in form of byte array to mnemonic string.
 * @param entropy byte array
 * @param wordlist imported wordlist for specific language
 * @returns 12-24 words
 * @example
 * const ent = new Uint8Array([
 *   0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f,
 *   0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f
 * ]);
 * entropyToMnemonic(ent, wordlist);
 * // 'legal winner thank year wave sausage worth useful legal winner thank yellow'
 */
export function entropyToMnemonic(entropy, wordlist) {
    aentropy(entropy);
    const words = getCoder(wordlist).encode(entropy);
    return words.join(isJapanese(wordlist) ? '\u3000' : ' ');
}
/**
 * Validates mnemonic for being 12-24 words contained in `wordlist`.
 */
export function validateMnemonic(mnemonic, wordlist) {
    try {
        mnemonicToEntropy(mnemonic, wordlist);
    }
    catch (e) {
        return false;
    }
    return true;
}
const psalt = (passphrase) => nfkd('mnemonic' + passphrase);
/**
 * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password.
 * @param mnemonic 12-24 words
 * @param passphrase string that will additionally protect the key
 * @returns 64 bytes of key data
 * @example
 * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';
 * await mnemonicToSeed(mnem, 'password');
 * // new Uint8Array([...64 bytes])
 */
export function mnemonicToSeed(mnemonic, passphrase = '') {
    return pbkdf2Async(sha512, normalize(mnemonic).nfkd, psalt(passphrase), { c: 2048, dkLen: 64 });
}
/**
 * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password.
 * @param mnemonic 12-24 words
 * @param passphrase string that will additionally protect the key
 * @returns 64 bytes of key data
 * @example
 * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';
 * mnemonicToSeedSync(mnem, 'password');
 * // new Uint8Array([...64 bytes])
 */
export function mnemonicToSeedSync(mnemonic, passphrase = '') {
    return pbkdf2(sha512, normalize(mnemonic).nfkd, psalt(passphrase), { c: 2048, dkLen: 64 });
}
{
  "type": "module"
}function isBuffer(value) {
  return Buffer.isBuffer(value) || value instanceof Uint8Array
}

function isEncoding(encoding) {
  return Buffer.isEncoding(encoding)
}

function alloc(size, fill, encoding) {
  return Buffer.alloc(size, fill, encoding)
}

function allocUnsafe(size) {
  return Buffer.allocUnsafe(size)
}

function allocUnsafeSlow(size) {
  return Buffer.allocUnsafeSlow(size)
}

function byteLength(string, encoding) {
  return Buffer.byteLength(string, encoding)
}

function compare(a, b) {
  return Buffer.compare(a, b)
}

function concat(buffers, totalLength) {
  return Buffer.concat(buffers, totalLength)
}

function copy(source, target, targetStart, start, end) {
  return toBuffer(source).copy(target, targetStart, start, end)
}

function equals(a, b) {
  return toBuffer(a).equals(b)
}

function fill(buffer, value, offset, end, encoding) {
  return toBuffer(buffer).fill(value, offset, end, encoding)
}

function from(value, encodingOrOffset, length) {
  return Buffer.from(value, encodingOrOffset, length)
}

function includes(buffer, value, byteOffset, encoding) {
  return toBuffer(buffer).includes(value, byteOffset, encoding)
}

function indexOf(buffer, value, byfeOffset, encoding) {
  return toBuffer(buffer).indexOf(value, byfeOffset, encoding)
}

function lastIndexOf(buffer, value, byteOffset, encoding) {
  return toBuffer(buffer).lastIndexOf(value, byteOffset, encoding)
}

function swap16(buffer) {
  return toBuffer(buffer).swap16()
}

function swap32(buffer) {
  return toBuffer(buffer).swap32()
}

function swap64(buffer) {
  return toBuffer(buffer).swap64()
}

function toBuffer(buffer) {
  if (Buffer.isBuffer(buffer)) return buffer
  return Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

function toString(buffer, encoding, start, end) {
  return toBuffer(buffer).toString(encoding, start, end)
}

function write(buffer, string, offset, length, encoding) {
  return toBuffer(buffer).write(string, offset, length, encoding)
}

function readDoubleBE(buffer, offset) {
  return toBuffer(buffer).readDoubleBE(offset)
}

function readDoubleLE(buffer, offset) {
  return toBuffer(buffer).readDoubleLE(offset)
}

function readFloatBE(buffer, offset) {
  return toBuffer(buffer).readFloatBE(offset)
}

function readFloatLE(buffer, offset) {
  return toBuffer(buffer).readFloatLE(offset)
}

function readInt32BE(buffer, offset) {
  return toBuffer(buffer).readInt32BE(offset)
}

function readInt32LE(buffer, offset) {
  return toBuffer(buffer).readInt32LE(offset)
}

function readUInt32BE(buffer, offset) {
  return toBuffer(buffer).readUInt32BE(offset)
}

function readUInt32LE(buffer, offset) {
  return toBuffer(buffer).readUInt32LE(offset)
}

function writeDoubleBE(buffer, value, offset) {
  return toBuffer(buffer).writeDoubleBE(value, offset)
}

function writeDoubleLE(buffer, value, offset) {
  return toBuffer(buffer).writeDoubleLE(value, offset)
}

function writeFloatBE(buffer, value, offset) {
  return toBuffer(buffer).writeFloatBE(value, offset)
}

function writeFloatLE(buffer, value, offset) {
  return toBuffer(buffer).writeFloatLE(value, offset)
}

function writeInt32BE(buffer, value, offset) {
  return toBuffer(buffer).writeInt32BE(value, offset)
}

function writeInt32LE(buffer, value, offset) {
  return toBuffer(buffer).writeInt32LE(value, offset)
}

function writeUInt32BE(buffer, value, offset) {
  return toBuffer(buffer).writeUInt32BE(value, offset)
}

function writeUInt32LE(buffer, value, offset) {
  return toBuffer(buffer).writeUInt32LE(value, offset)
}

module.exports = {
  isBuffer,
  isEncoding,
  alloc,
  allocUnsafe,
  allocUnsafeSlow,
  byteLength,
  compare,
  concat,
  copy,
  equals,
  fill,
  from,
  includes,
  indexOf,
  lastIndexOf,
  swap16,
  swap32,
  swap64,
  toBuffer,
  toString,
  write,
  readDoubleBE,
  readDoubleLE,
  readFloatBE,
  readFloatLE,
  readInt32BE,
  readInt32LE,
  readUInt32BE,
  readUInt32LE,
  writeDoubleBE,
  writeDoubleLE,
  writeFloatBE,
  writeFloatLE,
  writeInt32BE,
  writeInt32LE,
  writeUInt32BE,
  writeUInt32LE
}
{
  "name": "b4a",
  "version": "1.8.1",
  "description": "Bridging the gap between buffers and typed arrays",
  "exports": {
    "./package": "./package.json",
    ".": {
      "react-native": "./react-native.js",
      "browser": "./browser.js",
      "default": "./index.js"
    }
  },
  "files": [
    "browser.js",
    "index.js",
    "react-native.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:bare && npm run test:node",
    "test:bare": "brittle-bare --coverage test.mjs",
    "test:node": "brittle-node --coverage test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/b4a.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/b4a/issues"
  },
  "homepage": "https://github.com/holepunchto/b4a#readme",
  "devDependencies": {
    "brittle": "^3.5.2",
    "lunte": "^1.7.0",
    "nanobench": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "react-native-b4a": "*"
  },
  "peerDependenciesMeta": {
    "react-native-b4a": {
      "optional": true
    }
  }
}
const ESC = '\x1b'
const CSI = ESC + '['
const SGR = (n) => CSI + n + 'm'

exports.constants = {
  ESC,
  CSI,
  SGR
}

// https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_(Control_Sequence_Introducer)_sequences

exports.cursorHide = CSI + '?25l'
exports.cursorShow = CSI + '?25h'

exports.cursorUp = function cursorUp(n = 1) {
  return CSI + n + 'A'
}

exports.cursorDown = function cursorDown(n = 1) {
  return CSI + n + 'B'
}

exports.cursorForward = function cursorForward(n = 1) {
  return CSI + n + 'C'
}

exports.cursorBack = function cursorBack(n = 1) {
  return CSI + n + 'D'
}

exports.cursorNextLine = function cursorNextLine(n = 1) {
  return CSI + n + 'E'
}

exports.cursorPreviousLine = function cursorPreviousLine(n = 1) {
  return CSI + n + 'F'
}

exports.cursorPosition = function cursorPosition(column, row = 0) {
  if (row === 0) return CSI + (column + 1) + 'G'

  return CSI + (row + 1) + ';' + (column + 1) + 'H'
}

exports.eraseDisplayEnd = CSI + 'J'
exports.eraseDisplayStart = CSI + '1J'
exports.eraseDisplay = CSI + '2J'
exports.eraseLineEnd = CSI + 'K'
exports.eraseLineStart = CSI + '1K'
exports.eraseLine = CSI + '2K'

exports.scrollUp = function scrollUp(n = 1) {
  return CSI + n + 'S'
}

exports.scrollDown = function scrollDown(n = 1) {
  return CSI + n + 'T'
}

// https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_(Select_Graphic_Rendition)_parameters

exports.modifierReset = SGR(0)
exports.modifierBold = SGR(1)
exports.modifierDim = SGR(2)
exports.modifierItalic = SGR(3)
exports.modifierUnderline = SGR(4)
exports.modifierNormal = SGR(22)
exports.modifierNotItalic = SGR(23)
exports.modifierNotUnderline = SGR(24)

// https://en.wikipedia.org/wiki/ANSI_escape_code#Colors

exports.colorBlack = SGR(30)
exports.colorRed = SGR(31)
exports.colorGreen = SGR(32)
exports.colorYellow = SGR(33)
exports.colorBlue = SGR(34)
exports.colorMagenta = SGR(35)
exports.colorCyan = SGR(36)
exports.colorWhite = SGR(37)
exports.colorDefault = SGR(39)
exports.colorBrightBlack = SGR(90)
exports.colorBrightRed = SGR(91)
exports.colorBrightGreen = SGR(92)
exports.colorBrightYellow = SGR(93)
exports.colorBrightBlue = SGR(94)
exports.colorBrightMagenta = SGR(95)
exports.colorBrightCyan = SGR(96)
exports.colorBrightWhite = SGR(97)
{
  "name": "bare-ansi-escapes",
  "version": "2.2.3",
  "description": "Parse and produce ANSI escape sequences",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./key-decoder": {
      "types": "./key-decoder.d.ts",
      "default": "./key-decoder.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "key-decoder.js",
    "key-decoder.d.ts"
  ],
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-ansi-escapes.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-ansi-escapes/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-ansi-escapes#readme",
  "dependencies": {
    "bare-stream": "^2.6.5"
  },
  "devDependencies": {
    "bare-buffer": "^3.0.2",
    "brittle": "^3.3.2",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  },
  "peerDependencies": {
    "bare-buffer": "*"
  },
  "peerDependenciesMeta": {
    "bare-buffer": {
      "optional": true
    }
  }
}
const inspect = require('bare-inspect')

class AssertionError extends Error {
  constructor(opts = {}) {
    let { message = null, actual, expected, operator } = opts

    if (message === null) {
      message = `${inspect(actual)} ${operator} ${inspect(expected)}`
    }

    super(message)

    this.actual = actual
    this.expected = expected
    this.operator = operator
  }

  get name() {
    return 'AssertionError'
  }

  get code() {
    'ASSERTION'
  }
}

function assertFail(opts, fn) {
  if (opts.message instanceof Error) throw opts.message

  const err = new AssertionError(opts)

  if (Error.captureStackTrace) Error.captureStackTrace(err, fn)

  throw err
}

module.exports = exports = function assert(actual, message) {
  if (actual) return

  assertFail({ message, actual, expected: true, operator: '==' }, assert)
}

exports.AssertionError = AssertionError

exports.fail = function fail(message) {
  if (message === undefined) message = 'Failed'

  assertFail({ message, operator: 'fail' }, fail)
}

exports.ok = function ok(actual, message) {
  if (actual) return

  assertFail({ message, actual, expected: true, operator: '==' }, ok)
}

exports.notOk = function ok(actual, message) {
  if (!actual) return

  assertFail({ message, actual, expected: false, operator: '==' }, ok)
}

exports.equal = function equal(actual, expected, message) {
  if (actual == expected || (actual !== actual && expected !== expected)) {
    return
  }

  assertFail({ message, actual, expected, operator: '==' }, equal)
}

exports.notEqual = function notEqual(actual, expected, message) {
  if (actual != expected && (actual === actual || expected === expected)) {
    return
  }

  assertFail({ message, actual, expected, operator: '!=' }, notEqual)
}

exports.strictEqual = function strictEqual(actual, expected, message) {
  if (Object.is(actual, expected)) return

  assertFail(
    { message, actual, expected, operator: 'strictEqual' },
    strictEqual
  )
}

exports.notStrictEqual = function notStrictEqual(actual, expected, message) {
  if (!Object.is(actual, expected)) return

  assertFail(
    { message, actual, expected, operator: 'notStrictEqual' },
    notStrictEqual
  )
}
{
  "name": "bare-assert",
  "version": "1.2.0",
  "description": "Assertion library for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts"
  ],
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-assert.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-assert/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-assert#readme",
  "dependencies": {
    "bare-inspect": "^3.1.2"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  }
}
module.exports = require.addon()
const ansiEscapes = require('bare-ansi-escapes')
const getType = require('bare-type')
const binding = require('./binding')

const PLAIN_KEY = /^[a-zA-Z_][a-zA-Z_0-9]*$/

const defaultDepth = 2
const defaultBreakLength = 80
const defaultMaxArrayLength = 40

module.exports = exports = function inspect(value, opts = {}) {
  const {
    colors = false,
    depth = defaultDepth,
    breakLength = defaultBreakLength,
    stylize = defaultStylize(colors)
  } = opts

  const references = new InspectRefMap()

  const tree = inspectValue(value, 0, {
    colors,
    depth,
    breakLength,
    stylize,
    references
  })

  return tree.toString()
}

exports.styles = {
  bigint: ansiEscapes.colorYellow,
  boolean: ansiEscapes.colorYellow,
  date: ansiEscapes.colorMagenta,
  module: ansiEscapes.modifierUnderline,
  name: ansiEscapes.modifierReset,
  null: ansiEscapes.modifierBold,
  number: ansiEscapes.colorYellow,
  regexp: ansiEscapes.colorRed,
  special: ansiEscapes.colorCyan,
  string: ansiEscapes.colorGreen,
  symbol: ansiEscapes.colorGreen,
  undefined: ansiEscapes.colorBrightBlack
}

const styles = exports.styles

function defaultStylize(colors) {
  return function stylize(value, style) {
    const color = colors && styles[style]

    if (color) return color + value + ansiEscapes.modifierReset

    return value
  }
}

class InspectRefMap {
  constructor() {
    this.refs = new WeakMap()
    this.ids = new WeakMap()
    this.nextId = 1
  }

  has(object) {
    return this.refs.has(object)
  }

  get(object) {
    return this.refs.get(object) || null
  }

  set(object, ref) {
    this.refs.set(object, ref)
  }

  id(object) {
    let id = this.ids.get(object)
    if (id) return id

    id = this.nextId++
    this.ids.set(object, id)

    return id
  }
}

class InspectNode {
  constructor(depth, length, opts) {
    const { breakLength = defaultBreakLength, breakAlways = false } = opts

    this.depth = depth
    this.length = length
    this.breakLength = breakLength
    this.breakAlways = breakAlways
  }

  pad(n, string) {
    return string.padStart(n, ' ')
  }

  indent(n, string) {
    return '  '.repeat(n) + string
  }
}

class InspectRef extends InspectNode {
  constructor(depth, opts) {
    super(depth, '[circular *]'.length, opts)

    this.refs = opts.references
    this.count = 0
    this.circular = false
    this.color = opts.colors && styles.special
  }

  get id() {
    return this.refs.id(this)
  }

  increment() {
    return ++this.count
  }

  decrement() {
    return --this.count
  }

  toString(opts = {}) {
    const { offset = 0, pad = 0, indent = 0 } = opts

    let value = this.pad(pad, '[circular *' + this.id + ']')

    if (this.color) value = this.color + value + ansiEscapes.modifierReset

    return offset ? value : this.indent(indent, value)
  }
}

class InspectLeaf extends InspectNode {
  constructor(value, color, depth, opts) {
    const length = value.length

    if (value.includes('\n')) {
      value = value.replaceAll('\n', '\n' + '  '.repeat(depth))

      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.value = value
    this.color = opts.colors && color
  }

  toString(opts = {}) {
    const { offset = 0, pad = 0, indent = 0 } = opts

    let value = this.pad(pad, this.value)

    if (this.color) value = this.color + value + ansiEscapes.modifierReset

    return offset ? value : this.indent(indent, value)
  }
}

class InspectPair extends InspectNode {
  constructor(delim, left, right, depth, opts) {
    const length = left.length + delim.length + right.length

    if (left.breakAlways || right.breakAlways) {
      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.delim = delim
    this.left = left
    this.right = right
  }

  toString(opts = {}) {
    const { indent = 0 } = opts

    return this.indent(
      indent,
      this.left +
        this.delim +
        this.right.toString({
          indent,
          offset: this.left.length + this.delim.length
        })
    )
  }
}

class InspectSuspension extends InspectNode {
  constructor(overflow, depth, opts) {
    const label = `... ${overflow} more`

    super(depth, label.length, opts)

    this.label = label
  }

  toString(opts = {}) {
    const { indent = 0 } = opts

    return this.indent(indent, this.label)
  }
}

class InspectSequence extends InspectNode {
  constructor(header, footer, delim, values, ref, depth, opts) {
    const { tabulate = false } = opts

    const length =
      (ref.circular ? '<ref *>'.length + 1 : 0) +
      header.length +
      values.reduce(
        (length, value, i) =>
          length + value.length + (i === 0 ? 0 : delim.length),
        0
      ) +
      footer.length

    if (values.some((value) => value.breakAlways)) {
      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.header = header
    this.footer = footer
    this.delim = delim
    this.values = values
    this.ref = ref
    this.tabulate = tabulate
  }

  toString(opts = {}) {
    const { offset = 0, indent = 0 } = opts

    const split =
      this.breakAlways ||
      (this.values.length &&
        (offset + this.length > this.breakLength ||
          indent * 2 + this.length > this.breakLength))

    let header = this.header

    if (this.ref.circular) {
      header = '<ref *' + this.ref.id + '> ' + header
    }

    if (this.values.length === 0) {
      header = header.trimEnd()
    }

    if (offset === 0) {
      header = this.indent(indent, header)
    }

    if (split) {
      header = header.trimEnd() + '\n'
    }

    let string = header

    let columns = 1
    let pad = 0

    if (this.tabulate) {
      const widest = this.values.reduce(
        (length, value) =>
          value.breakAlways ? length : Math.max(length, value.length),
        0
      )

      if (widest) {
        columns = Math.max(
          columns,
          Math.floor(
            (this.breakLength - indent * 2) / (widest + this.delim.length)
          )
        )

        if (columns > 1) pad = widest
      }
    }

    for (let i = 0, n = this.values.length, offset = 0; i < n; i++) {
      const value = this.values[i]

      if (split) {
        let part

        if (i % columns === 0 || value.breakAlways) {
          part = value.toString({ indent: indent + 1, pad })
        } else {
          part = value.toString({ pad })
        }

        string += part

        if (i < n - 1) {
          if (i % columns === columns - 1 || this.values[i + 1].breakAlways) {
            string += this.delim.trimEnd() + '\n'
          } else {
            string += this.delim
          }
        }
      } else {
        if (i > 0) string += this.delim

        string += value.toString({ offset })

        offset += value.length
      }
    }

    let footer = this.footer

    if (this.values.length === 0) {
      footer = footer.trimStart()
    }

    if (split) {
      string += '\n' + this.indent(indent, footer.trimStart())
    } else {
      string += footer
    }

    return string
  }
}

function inspectValue(value, depth, opts) {
  const type = getType(value)

  if (type.isUndefined()) return inspectUndefined(depth, opts)
  if (type.isNull()) return inspectNull(depth, opts)
  if (type.isBoolean()) return inspectBoolean(value, depth, opts)
  if (type.isNumber()) return inspectNumber(value, depth, opts)
  if (type.isBigInt()) return inspectBigInt(value, depth, opts)
  if (type.isString()) return inspectString(value, depth, opts)
  if (type.isSymbol()) return inspectSymbol(value, depth, opts)
  if (type.isObject()) return inspectObject(type, value, depth, opts)
  if (type.isFunction()) return inspectFunction(type, value, depth, opts)
  if (type.isExternal()) return inspectExternal(value, opts, opts)
}

function inspectUndefined(depth, opts) {
  return new InspectLeaf('undefined', styles.undefined, depth, opts)
}

function inspectNull(depth, opts) {
  return new InspectLeaf('null', styles.null, depth, opts)
}

function inspectBoolean(value, depth, opts) {
  return new InspectLeaf(value.toString(), styles.boolean, depth, opts)
}

function inspectNumber(value, depth, opts) {
  let string

  if (Object.is(value, -0)) {
    string = '-0'
  } else {
    string = value.toString(10)
  }

  return new InspectLeaf(string, styles.number, depth, opts)
}

function inspectBigInt(value, depth, opts) {
  return new InspectLeaf(value.toString(10) + 'n', styles.bigint, depth, opts)
}

const STRING_ESCAPES =
  /[\ud800-\udbff][\udc00-\udfff]|[\u0000-\u001f'\\\ud800-\udfff]/g

function inspectString(value, depth, opts) {
  // https://tc39.es/ecma262/multipage/structured-data.html#sec-quotejsonstring
  const string = value.replace(STRING_ESCAPES, (match) => {
    if (match.length === 2) return match

    switch (match) {
      case "'":
        return "\\'"
      case '\\':
        return '\\\\'
      case '\b':
        return '\\b'
      case '\t':
        return '\\t'
      case '\n':
        return '\\n'
      case '\f':
        return '\\f'
      case '\r':
        return '\\r'
      default:
        return '\\u' + match.charCodeAt(0).toString(16).padStart(4, '0')
    }
  })

  return new InspectLeaf("'" + string + "'", styles.string, depth, opts)
}

function inspectSymbol(value, depth, opts) {
  return new InspectLeaf(value.toString(), styles.symbol, depth, opts)
}

function inspectKey(value, depth, opts) {
  if (PLAIN_KEY.test(value)) {
    return new InspectLeaf(value, null, depth, opts)
  } else {
    return inspectValue(value, depth, opts)
  }
}

function inspectObject(type, object, depth, opts) {
  const refs = opts.references

  let ref = refs.get(object)
  if (ref === null) {
    ref = new InspectRef(depth, opts)
    refs.set(object, ref)
  } else if (ref.count) {
    ref.circular = true
    return ref
  }

  const maxDepth = typeof opts.depth === 'number' ? opts.depth : Infinity

  if (maxDepth < depth) {
    const constructor = object.constructor

    return new InspectLeaf(
      '[' +
        (constructor && constructor.name ? constructor.name : 'Object') +
        ']',
      styles.special,
      depth,
      opts
    )
  }

  const inspect =
    object[Symbol.for('bare.inspect')] ||
    object[Symbol.for('nodejs.util.inspect.custom')]

  if (typeof inspect === 'function') {
    const value = inspect.call(
      object,
      typeof opts.depth === 'number' ? opts.depth - depth : null,
      {
        colors: opts.colors,
        breakLength: opts.breakLength,
        stylize: opts.stylize
      },
      exports
    )

    if (typeof value === 'object' && value !== null) {
      refs.set(value, ref)
    }

    if (typeof value !== 'string') {
      return inspectValue(value, depth, opts)
    }

    return new InspectLeaf(value, null, depth, opts)
  }

  if (type.isArray()) return inspectArray(object, ref, depth, opts)
  if (type.isDate()) return inspectDate(object, ref, depth, opts)
  if (type.isRegExp()) return inspectRegExp(object, ref, depth, opts)
  if (type.isError()) return inspectError(object, ref, depth, opts)
  if (type.isPromise()) return inspectPromise(object, ref, depth, opts)
  if (type.isMap()) return inspectMap(object, ref, depth, opts)
  if (type.isSet()) return inspectSet(object, ref, depth, opts)
  if (type.isWeakMap()) return inspectWeakMap(object, ref, depth, opts)
  if (type.isWeakSet()) return inspectWeakSet(object, ref, depth, opts)
  if (type.isWeakRef()) return inspectWeakRef(object, ref, depth, opts)
  if (type.isArrayBuffer()) return inspectArrayBuffer(object, ref, depth, opts)
  if (type.isSharedArrayBuffer())
    return inspectSharedArrayBuffer(object, ref, depth, opts)
  if (type.isTypedArray()) return inspectTypedArray(object, ref, depth, opts)
  if (type.isDataView()) return inspectDataView(object, ref, depth, opts)

  ref.increment()

  const values = []

  for (const key in object) {
    if (key === 'constructor') continue

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(object[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  let header = '{ '

  const tag = object[Symbol.toStringTag]

  if (tag) header = '[' + tag + '] ' + header

  if (object.constructor) {
    const name = object.constructor.name

    if (name && name !== 'Object') {
      header = object.constructor.name + ' ' + header
    }
  }

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectArray(array, ref, depth, opts) {
  const { maxArrayLength = defaultMaxArrayLength } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxArrayLength, 0)

  for (let i = 0, n = array.length; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(array.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(inspectValue(array[i], depth + 1, opts))
  }

  for (const key of binding.getOwnNonIndexPropertyNames(array)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(array[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  let header = '[ '

  if (array.constructor.name !== 'Array') {
    header = array.constructor.name + '(' + array.length + ') ' + header
  }

  return new InspectSequence(header, ' ]', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectDate(date, ref, depth, opts) {
  return new InspectLeaf(date.toISOString(), styles.date, depth, opts)
}

function inspectRegExp(regExp, ref, depth, opts) {
  return new InspectLeaf(regExp.toString(), styles.regexp, depth, opts)
}

function inspectError(error, ref, depth, opts) {
  let header

  if ('stack' in error) {
    header = error.stack

    if (depth > 0) {
      header = header.replaceAll('\n', '\n' + '  '.repeat(depth))
    }
  } else {
    header = error.toString()
  }

  const builtins = ['cause']

  if (error.name === 'AggregateError') {
    builtins.push('errors')
  } else if (error.name === 'SuppressedError') {
    builtins.push('error', 'suppressed')
  }

  const values = []

  for (const key of builtins) {
    if (key in error === false) continue

    values.push(
      new InspectPair(
        ': ',
        new InspectLeaf('[' + key + ']', null, depth + 1, opts),
        inspectValue(error[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key in error) {
    if (key === 'constructor' || builtins.includes(key)) continue

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(error[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  if (values.length === 0) return new InspectLeaf(header, null, depth, opts)

  return new InspectSequence(
    header + ' {',
    ' }',
    ', ',
    values,
    ref,
    depth,
    opts
  )
}

function inspectPromise(promise, ref, depth, opts) {
  ref.increment()

  const state = binding.getPromiseState(promise)

  const values = []

  switch (state) {
    case 0: // Pending
      values.push(new InspectLeaf('<pending>', styles.special, depth, opts))
      break

    case 1: // Fulfilled
      values.push(inspectValue(binding.getPromiseResult(promise), depth, opts))
      break

    case 2: // Rejected
      values.push(
        new InspectLeaf('<rejected>', styles.special, depth, opts),
        inspectValue(binding.getPromiseResult(promise), depth, opts)
      )
  }

  ref.decrement()

  const header = promise.constructor.name + ' { '

  return new InspectSequence(header, ' }', ' ', values, ref, depth, opts)
}

function inspectMap(map, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxMapLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = maxMapLength

  for (const entry of map) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(map.size - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )
      break
    }

    values.push(
      new InspectPair(
        ' => ',
        inspectValue(entry[0], depth + 1, opts),
        inspectValue(entry[1], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key in map) {
    if (key === 'constructor') continue

    const value = inspectValue(map[key], depth + 1, opts)

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        value,
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = map.constructor.name + '(' + map.size + ') { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectSet(set, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxSetLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = maxSetLength

  for (const entry of set) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(set.size - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )
      break
    }

    values.push(inspectValue(entry, depth + 1, opts))
  }

  for (const key in set) {
    if (key === 'constructor') continue

    const value = inspectValue(set[key], depth + 1, opts)

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        value,
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = set.constructor.name + '(' + set.size + ') { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectWeakMap(weakMap, ref, depth, opts) {
  const header = weakMap.constructor.name + ' { '

  return new InspectSequence(
    header,
    ' }',
    ' ',
    [new InspectLeaf('<items unknown>', styles.special, depth + 1, opts)],
    ref,
    depth,
    opts
  )
}

function inspectWeakSet(weakSet, ref, depth, opts) {
  const header = weakSet.constructor.name + ' { '

  return new InspectSequence(
    header,
    ' }',
    ' ',
    [new InspectLeaf('<items unknown>', styles.special, depth + 1, opts)],
    ref,
    depth,
    opts
  )
}

function inspectWeakRef(weakRef, ref, depth, opts) {
  const target = weakRef.deref()

  let value

  if (target === undefined) {
    value = new InspectLeaf('<cleared>', styles.special, depth + 1, opts)
  } else {
    value = inspectValue(target, depth + 1, opts)
  }

  const header = weakRef.constructor.name + ' { '

  return new InspectSequence(header, ' }', ' ', [value], ref, depth, opts)
}

function inspectArrayBuffer(arrayBuffer, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(arrayBuffer[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = arrayBuffer.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectSharedArrayBuffer(sharedArrayBuffer, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(sharedArrayBuffer[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = sharedArrayBuffer.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectTypedArray(typedArray, ref, depth, opts) {
  if (Buffer.isBuffer(typedArray)) {
    return inspectBuffer(typedArray, ref, depth, opts)
  }

  const {
    maxArrayLength = defaultMaxArrayLength,
    maxTypedArrayLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxTypedArrayLength, 0)

  for (let i = 0, n = typedArray.length; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(typedArray.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(inspectValue(typedArray[i], depth + 1, opts))
  }

  for (const key of binding.getOwnNonIndexPropertyNames(typedArray)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(typedArray[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = typedArray.constructor.name + '(' + typedArray.length + ') [ '

  return new InspectSequence(header, ' ]', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectBuffer(buffer, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxBufferLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxBufferLength, 0)

  for (let i = 0, n = buffer.byteLength; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(buffer.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(
      new InspectLeaf(
        buffer[i].toString(16).padStart(2, '0'),
        null,
        depth + 1,
        opts
      )
    )
  }

  for (const key of binding.getOwnNonIndexPropertyNames(buffer)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(buffer[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  return new InspectSequence('<Buffer ', '>', ' ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectDataView(dataView, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength', 'byteOffset', 'buffer']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(dataView[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key of binding.getOwnNonIndexPropertyNames(dataView)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(dataView[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = dataView.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectFunction(type, fn, depth, opts) {
  if (fn.toString().startsWith('class')) return inspectClass(fn, depth, opts)

  let tag = 'function'

  if (type.isGeneratorFunction()) tag = 'generator ' + tag
  if (type.isAsyncFunction()) tag = 'async ' + tag

  return new InspectLeaf(
    '[' + tag + ' ' + (fn.name ? fn.name : '(anonymous)') + ']',
    styles.special,
    depth,
    opts
  )
}

function inspectClass(ctor, depth, opts) {
  return new InspectLeaf(
    '[class ' + (ctor.name ? ctor.name : '(anonymous)') + ']',
    styles.special,
    depth,
    opts
  )
}

function inspectExternal(external, depth, opts) {
  return new InspectLeaf(
    '[external 0x' + binding.getExternal(external).toString(16) + ']',
    styles.special,
    depth,
    opts
  )
}
{
  "name": "bare-inspect",
  "version": "3.1.4",
  "description": "Inspect objects as strings for debugging",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-inspect.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-inspect/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-inspect#readme",
  "engines": {
    "bare": ">=1.18.0"
  },
  "dependencies": {
    "bare-ansi-escapes": "^2.1.0",
    "bare-type": "^1.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
module.exports = require.addon()
const binding = require('./binding')

const t = binding.constants

class Type {
  constructor(type) {
    this._type = type
  }

  isUndefined() {
    return this._type === t.UNDEFINED
  }

  isNull() {
    return this._type === t.NULL
  }

  isBoolean() {
    return this._type === t.BOOLEAN
  }

  isNumber() {
    return (this._type & 0xff) === t.NUMBER
  }

  isInt32() {
    return (this._type & (0xff | t.INT32)) === (t.NUMBER | t.INT32)
  }

  isUint32() {
    return (this._type & (0xff | t.UINT32)) === (t.NUMBER | t.UINT32)
  }

  isString() {
    return this._type === t.STRING
  }

  isSymbol() {
    return this._type === t.SYMBOL
  }

  isObject() {
    return (this._type & 0xff) === t.OBJECT
  }

  isArray() {
    return this._type === (t.OBJECT | t.ARRAY)
  }

  isArguments() {
    return this._type === (t.OBJECT | t.ARGUMENTS)
  }

  isDate() {
    return this._type === (t.OBJECT | t.DATE)
  }

  isRegExp() {
    return this._type === (t.OBJECT | t.REGEXP)
  }

  isError() {
    return this._type === (t.OBJECT | t.ERROR)
  }

  isPromise() {
    return this._type === (t.OBJECT | t.PROMISE)
  }

  isProxy() {
    return this._type === (t.OBJECT | t.PROXY)
  }

  isGenerator() {
    return this._type === (t.OBJECT | t.GENERATOR)
  }

  isMap() {
    return this._type === (t.OBJECT | t.MAP)
  }

  isSet() {
    return this._type === (t.OBJECT | t.SET)
  }

  isWeakMap() {
    return this._type === (t.OBJECT | t.WEAK_MAP)
  }

  isWeakSet() {
    return this._type === (t.OBJECT | t.WEAK_SET)
  }

  isWeakRef() {
    return this._type === (t.OBJECT | t.WEAK_REF)
  }

  isArrayBuffer() {
    return this._type === (t.OBJECT | t.ARRAYBUFFER)
  }

  isSharedArrayBuffer() {
    return this._type === (t.OBJECT | t.SHAREDARRAYBUFFER)
  }

  isTypedArray() {
    return (this._type & 0xffff) === (t.OBJECT | t.TYPEDARRAY)
  }

  isInt8Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT8ARRAY)
  }

  isUint8Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT8ARRAY)
  }

  isUint8ClampedArray() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT8CLAMPEDARRAY)
  }

  isInt16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT16ARRAY)
  }

  isUint16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT16ARRAY)
  }

  isInt32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT32ARRAY)
  }

  isUint32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT32ARRAY)
  }

  isFloat16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT16ARRAY)
  }

  isFloat32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT32ARRAY)
  }

  isFloat64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT64ARRAY)
  }

  isBigInt64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.BIGINT64ARRAY)
  }

  isBigUint64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.BIGUINT64ARRAY)
  }

  isDataView() {
    return this._type === (t.OBJECT | t.DATAVIEW)
  }

  isModuleNamespace() {
    return this._type === (t.OBJECT | t.MODULE_NAMESPACE)
  }

  isFunction() {
    return (this._type & 0xff) === t.FUNCTION
  }

  isAsyncFunction() {
    return (
      (this._type & (0xff | t.ASYNC_FUNCTION)) ===
      (t.FUNCTION | t.ASYNC_FUNCTION)
    )
  }

  isGeneratorFunction() {
    return (
      (this._type & (0xff | t.GENERATOR_FUNCTION)) ===
      (t.FUNCTION | t.GENERATOR_FUNCTION)
    )
  }

  isExternal() {
    return this._type === t.EXTERNAL
  }

  isBigInt() {
    return this._type === t.BIGINT
  }
}

module.exports = exports = function type(value) {
  switch (typeof value) {
    case 'undefined':
      return new Type(t.UNDEFINED)
    case 'boolean':
      return new Type(t.BOOLEAN)
    case 'number':
      return new Type(
        Number.isSafeInteger(value) ? binding.type(value) : t.NUMBER
      )
    case 'string':
      return new Type(t.STRING)
    case 'symbol':
      return new Type(t.SYMBOL)
    case 'object':
      return new Type(value === null ? t.NULL : binding.type(value))
    case 'function':
      return new Type(binding.type(value))
    case 'bigint':
      return new Type(t.BIGINT)
  }
}

exports.createTag = function createTag(...components) {
  const tag = new Uint32Array(4)
  for (let i = 0; i < 4; i++) tag[i] = components[i] || 0
  return tag
}

exports.addTag = function addTag(object, tag) {
  binding.addTag(object, tag)
}

exports.checkTag = function checkTag(object, tag) {
  return binding.checkTag(object, tag)
}
{
  "name": "bare-type",
  "version": "1.1.0",
  "description": "Cross-realm type predicates for Bare",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-type.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-type/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-type#readme",
  "engines": {
    "bare": ">=1.2.0"
  },
  "devDependencies": {
    "brittle": "^3.4.0",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
import { encode, encodeInto, objectToTokens, rfc8949EncodeOptions } from './lib/encode.js'
import { decode, decodeFirst, Tokeniser, tokensToObject } from './lib/decode.js'
import { Tagged } from './lib/tagged.js'
import { Token, Type } from './lib/token.js'

/**
 * Export the types that were present in the original manual cborg.d.ts
 * @typedef {import('./interface.js').TagDecodeControl} TagDecodeControl
 * @typedef {import('./interface.js').TagDecoder} TagDecoder
 * There was originally just `TypeEncoder` so don't break types by renaming or not exporting
 * @typedef {import('./interface.js').OptionalTypeEncoder} TypeEncoder
 * @typedef {import('./interface.js').DecodeOptions} DecodeOptions
 * @typedef {import('./interface.js').EncodeOptions} EncodeOptions
 */

export {
  decode,
  decodeFirst,
  Tokeniser as Tokenizer,
  tokensToObject,
  encode,
  encodeInto,
  objectToTokens,
  rfc8949EncodeOptions,
  Tagged,
  Token,
  Type
}
/* globals BigInt */

import { Token, Type } from './token.js'
import { decodeErrPrefix, assertEnoughData } from './common.js'

export const uintBoundaries = [24, 256, 65536, 4294967296, BigInt('18446744073709551616')]

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number}
 */
export function readUint8 (data, offset, options) {
  assertEnoughData(data, offset, 1)
  const value = data[offset]
  if (options.strict === true && value < uintBoundaries[0]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  return value
}

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number}
 */
export function readUint16 (data, offset, options) {
  assertEnoughData(data, offset, 2)
  const value = (data[offset] << 8) | data[offset + 1]
  if (options.strict === true && value < uintBoundaries[1]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  return value
}

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number}
 */
export function readUint32 (data, offset, options) {
  assertEnoughData(data, offset, 4)
  const value = (data[offset] * 16777216 /* 2 ** 24 */) + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]
  if (options.strict === true && value < uintBoundaries[2]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  return value
}

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number|bigint}
 */
export function readUint64 (data, offset, options) {
  // assume BigInt, convert back to Number if within safe range
  assertEnoughData(data, offset, 8)
  const hi = (data[offset] * 16777216 /* 2 ** 24 */) + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]
  const lo = (data[offset + 4] * 16777216 /* 2 ** 24 */) + (data[offset + 5] << 16) + (data[offset + 6] << 8) + data[offset + 7]
  const value = (BigInt(hi) << BigInt(32)) + BigInt(lo)
  if (options.strict === true && value < uintBoundaries[3]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  if (value <= Number.MAX_SAFE_INTEGER) {
    return Number(value)
  }
  if (options.allowBigInt === true) {
    return value
  }
  throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`)
}

/* not required thanks to quick[] list
const oneByteTokens = new Array(24).fill(0).map((v, i) => new Token(Type.uint, i, 1))
export function decodeUintCompact (data, pos, minor, options) {
  return oneByteTokens[minor]
}
*/

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint8 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint8(data, pos + 1, options), 2)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint16 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint16(data, pos + 1, options), 3)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint32 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint32(data, pos + 1, options), 5)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint64 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint64(data, pos + 1, options), 9)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeUint (writer, token) {
  return encodeUintValue(writer, 0, token.value)
}

/**
 * @param {ByteWriter} writer
 * @param {number} major
 * @param {number|bigint} uint
 */
export function encodeUintValue (writer, major, uint) {
  if (uint < uintBoundaries[0]) {
    const nuint = Number(uint)
    // pack into one byte, minor=0, additional=value
    writer.push([major | nuint])
  } else if (uint < uintBoundaries[1]) {
    const nuint = Number(uint)
    // pack into two byte, minor=0, additional=24
    writer.push([major | 24, nuint])
  } else if (uint < uintBoundaries[2]) {
    const nuint = Number(uint)
    // pack into three byte, minor=0, additional=25
    writer.push([major | 25, nuint >>> 8, nuint & 0xff])
  } else if (uint < uintBoundaries[3]) {
    const nuint = Number(uint)
    // pack into five byte, minor=0, additional=26
    writer.push([major | 26, (nuint >>> 24) & 0xff, (nuint >>> 16) & 0xff, (nuint >>> 8) & 0xff, nuint & 0xff])
  } else {
    const buint = BigInt(uint)
    if (buint < uintBoundaries[4]) {
      // pack into nine byte, minor=0, additional=27
      const set = [major | 27, 0, 0, 0, 0, 0, 0, 0]
      // simulate bitwise above 32 bits
      let lo = Number(buint & BigInt(0xffffffff))
      let hi = Number(buint >> BigInt(32) & BigInt(0xffffffff))
      set[8] = lo & 0xff
      lo = lo >> 8
      set[7] = lo & 0xff
      lo = lo >> 8
      set[6] = lo & 0xff
      lo = lo >> 8
      set[5] = lo & 0xff
      set[4] = hi & 0xff
      hi = hi >> 8
      set[3] = hi & 0xff
      hi = hi >> 8
      set[2] = hi & 0xff
      hi = hi >> 8
      set[1] = hi & 0xff
      writer.push(set)
    } else {
      throw new Error(`${decodeErrPrefix} encountered BigInt larger than allowable range`)
    }
  }
}

/**
 * @param {Token} token
 * @returns {number}
 */
encodeUint.encodedSize = function encodedSize (token) {
  return encodeUintValue.encodedSize(token.value)
}

/**
 * @param {number} uint
 * @returns {number}
 */
encodeUintValue.encodedSize = function encodedSize (uint) {
  if (uint < uintBoundaries[0]) {
    return 1
  }
  if (uint < uintBoundaries[1]) {
    return 2
  }
  if (uint < uintBoundaries[2]) {
    return 3
  }
  if (uint < uintBoundaries[3]) {
    return 5
  }
  return 9
}

/**
 * @param {Token} tok1
 * @param {Token} tok2
 * @returns {number}
 */
encodeUint.compareTokens = function compareTokens (tok1, tok2) {
  return tok1.value < tok2.value ? -1 : tok1.value > tok2.value ? 1 : 0
}
/* eslint-env es2020 */

import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import { decodeErrPrefix } from './common.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint8 (data, pos, _minor, options) {
  return new Token(Type.negint, -1 - uint.readUint8(data, pos + 1, options), 2)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint16 (data, pos, _minor, options) {
  return new Token(Type.negint, -1 - uint.readUint16(data, pos + 1, options), 3)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint32 (data, pos, _minor, options) {
  return new Token(Type.negint, -1 - uint.readUint32(data, pos + 1, options), 5)
}

const neg1b = BigInt(-1)
const pos1b = BigInt(1)

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint64 (data, pos, _minor, options) {
  const int = uint.readUint64(data, pos + 1, options)
  if (typeof int !== 'bigint') {
    const value = -1 - int
    if (value >= Number.MIN_SAFE_INTEGER) {
      return new Token(Type.negint, value, 9)
    }
  }
  if (options.allowBigInt !== true) {
    throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`)
  }
  return new Token(Type.negint, neg1b - BigInt(int), 9)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeNegint (writer, token) {
  const negint = token.value
  const unsigned = (typeof negint === 'bigint' ? (negint * neg1b - pos1b) : (negint * -1 - 1))
  uint.encodeUintValue(writer, token.type.majorEncoded, unsigned)
}

/**
 * @param {Token} token
 * @returns {number}
 */
encodeNegint.encodedSize = function encodedSize (token) {
  const negint = token.value
  const unsigned = (typeof negint === 'bigint' ? (negint * neg1b - pos1b) : (negint * -1 - 1))
  // handled by quickEncode, we shouldn't get here but it's included for completeness
  if (unsigned < uint.uintBoundaries[0]) {
    return 1
  }
  if (unsigned < uint.uintBoundaries[1]) {
    return 2
  }
  if (unsigned < uint.uintBoundaries[2]) {
    return 3
  }
  if (unsigned < uint.uintBoundaries[3]) {
    return 5
  }
  return 9
}

/**
 * @param {Token} tok1
 * @param {Token} tok2
 * @returns {number}
 */
encodeNegint.compareTokens = function compareTokens (tok1, tok2) {
  // opposite of the uint comparison since we store the uint version in bytes
  return tok1.value < tok2.value ? 1 : tok1.value > tok2.value ? -1 : 0
}
import { Token, Type } from './token.js'
import { assertEnoughData, decodeErrPrefix } from './common.js'
import * as uint from './0uint.js'
import { compare, fromString } from './byte-utils.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} prefix
 * @param {number} length
 * @returns {Token}
 */
function toToken (data, pos, prefix, length) {
  assertEnoughData(data, pos, prefix + length)
  const buf = data.slice(pos + prefix, pos + prefix + length)
  return new Token(Type.bytes, buf, prefix + length)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeBytesCompact (data, pos, minor, _options) {
  return toToken(data, pos, 1, minor)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer bytes lengths not supported`)
  }
  return toToken(data, pos, 9, l)
}

/**
 * `encodedBytes` allows for caching when we do a byte version of a string
 * for key sorting purposes
 * @param {Token} token
 * @returns {Uint8Array}
 */
function tokenBytes (token) {
  if (token.encodedBytes === undefined) {
    token.encodedBytes = Type.equals(token.type, Type.string) ? fromString(token.value) : token.value
  }
  // @ts-ignore c'mon
  return token.encodedBytes
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeBytes (writer, token) {
  const bytes = tokenBytes(token)
  uint.encodeUintValue(writer, token.type.majorEncoded, bytes.length)
  writer.push(bytes)
}

/**
 * @param {Token} token
 * @returns {number}
 */
encodeBytes.encodedSize = function encodedSize (token) {
  const bytes = tokenBytes(token)
  return uint.encodeUintValue.encodedSize(bytes.length) + bytes.length
}

/**
 * @param {Token} tok1
 * @param {Token} tok2
 * @returns {number}
 */
encodeBytes.compareTokens = function compareTokens (tok1, tok2) {
  return compareBytes(tokenBytes(tok1), tokenBytes(tok2))
}

/**
 * @param {Uint8Array} b1
 * @param {Uint8Array} b2
 * @returns {number}
 */
export function compareBytes (b1, b2) {
  return b1.length < b2.length ? -1 : b1.length > b2.length ? 1 : compare(b1, b2)
}
import { Token, Type } from './token.js'
import { assertEnoughData, decodeErrPrefix } from './common.js'
import * as uint from './0uint.js'
import { encodeBytes } from './2bytes.js'

const textDecoder = new TextDecoder()

// Threshold for ASCII fast-path vs TextDecoder. Short ASCII strings (common for
// map keys) are faster to decode with a simple loop than TextDecoder overhead.
const ASCII_THRESHOLD = 32

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * Decode UTF-8 bytes to string. For short ASCII strings (common case for map keys),
 * a simple loop is faster than TextDecoder.
 * @param {Uint8Array} bytes
 * @param {number} start
 * @param {number} end
 * @returns {string}
 */
function toStr (bytes, start, end) {
  const len = end - start
  if (len < ASCII_THRESHOLD) {
    let str = ''
    for (let i = start; i < end; i++) {
      const c = bytes[i]
      if (c & 0x80) { // non-ASCII, fall back to TextDecoder
        return textDecoder.decode(bytes.subarray(start, end))
      }
      str += String.fromCharCode(c)
    }
    return str
  }
  return textDecoder.decode(bytes.subarray(start, end))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} prefix
 * @param {number} length
 * @param {DecodeOptions} options
 * @returns {Token}
 */
function toToken (data, pos, prefix, length, options) {
  const totLength = prefix + length
  assertEnoughData(data, pos, totLength)
  const tok = new Token(Type.string, toStr(data, pos + prefix, pos + totLength), totLength)
  if (options.retainStringBytes === true) {
    tok.byteValue = data.slice(pos + prefix, pos + totLength)
  }
  return tok
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeStringCompact (data, pos, minor, options) {
  return toToken(data, pos, 1, minor, options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options), options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options), options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options), options)
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer string lengths not supported`)
  }
  return toToken(data, pos, 9, l, options)
}

export const encodeString = encodeBytes
import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import { decodeErrPrefix } from './common.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} prefix
 * @param {number} length
 * @returns {Token}
 */
function toToken (_data, _pos, prefix, length) {
  return new Token(Type.array, length, prefix)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeArrayCompact (data, pos, minor, _options) {
  return toToken(data, pos, 1, minor)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer array lengths not supported`)
  }
  return toToken(data, pos, 9, l)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArrayIndefinite (data, pos, _minor, options) {
  if (options.allowIndefinite === false) {
    throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)
  }
  return toToken(data, pos, 1, Infinity)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeArray (writer, token) {
  uint.encodeUintValue(writer, Type.array.majorEncoded, token.value)
}

// using an array as a map key, are you sure about this? we can only sort
// by map length here, it's up to the encoder to decide to look deeper
encodeArray.compareTokens = uint.encodeUint.compareTokens

/**
 * @param {Token} token
 * @returns {number}
 */
encodeArray.encodedSize = function encodedSize (token) {
  return uint.encodeUintValue.encodedSize(token.value)
}
import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import { decodeErrPrefix } from './common.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} prefix
 * @param {number} length
 * @returns {Token}
 */
function toToken (_data, _pos, prefix, length) {
  return new Token(Type.map, length, prefix)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeMapCompact (data, pos, minor, _options) {
  return toToken(data, pos, 1, minor)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer map lengths not supported`)
  }
  return toToken(data, pos, 9, l)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMapIndefinite (data, pos, _minor, options) {
  if (options.allowIndefinite === false) {
    throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)
  }
  return toToken(data, pos, 1, Infinity)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeMap (writer, token) {
  uint.encodeUintValue(writer, Type.map.majorEncoded, token.value)
}

// using a map as a map key, are you sure about this? we can only sort
// by map length here, it's up to the encoder to decide to look deeper
encodeMap.compareTokens = uint.encodeUint.compareTokens

/**
 * @param {Token} token
 * @returns {number}
 */
encodeMap.encodedSize = function encodedSize (token) {
  return uint.encodeUintValue.encodedSize(token.value)
}
import { Token, Type } from './token.js'
import * as uint from './0uint.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeTagCompact (_data, _pos, minor, _options) {
  return new Token(Type.tag, minor, 1)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag8 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint8(data, pos + 1, options), 2)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag16 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint16(data, pos + 1, options), 3)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag32 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint32(data, pos + 1, options), 5)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag64 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint64(data, pos + 1, options), 9)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeTag (writer, token) {
  uint.encodeUintValue(writer, Type.tag.majorEncoded, token.value)
}

encodeTag.compareTokens = uint.encodeUint.compareTokens

/**
 * @param {Token} token
 * @returns {number}
 */
encodeTag.encodedSize = function encodedSize (token) {
  return uint.encodeUintValue.encodedSize(token.value)
}
// TODO: shift some of the bytes logic to bytes-utils so we can use Buffer
// where possible

import { Token, Type } from './token.js'
import { decodeErrPrefix } from './common.js'
import { encodeUint } from './0uint.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 * @typedef {import('../interface.js').EncodeOptions} EncodeOptions
 */

export const MINOR_FALSE = 20
export const MINOR_TRUE = 21
export const MINOR_NULL = 22
export const MINOR_UNDEFINED = 23

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUndefined (_data, _pos, _minor, options) {
  if (options.allowUndefined === false) {
    throw new Error(`${decodeErrPrefix} undefined values are not supported`)
  } else if (options.coerceUndefinedToNull === true) {
    return new Token(Type.null, null, 1)
  }
  return new Token(Type.undefined, undefined, 1)
}

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBreak (_data, _pos, _minor, options) {
  if (options.allowIndefinite === false) {
    throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)
  }
  return new Token(Type.break, undefined, 1)
}

/**
 * @param {number} value
 * @param {number} bytes
 * @param {DecodeOptions} options
 * @returns {Token}
 */
function createToken (value, bytes, options) {
  if (options) {
    if (options.allowNaN === false && Number.isNaN(value)) {
      throw new Error(`${decodeErrPrefix} NaN values are not supported`)
    }
    if (options.allowInfinity === false && (value === Infinity || value === -Infinity)) {
      throw new Error(`${decodeErrPrefix} Infinity values are not supported`)
    }
  }
  return new Token(Type.float, value, bytes)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeFloat16 (data, pos, _minor, options) {
  return createToken(readFloat16(data, pos + 1), 3, options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeFloat32 (data, pos, _minor, options) {
  return createToken(readFloat32(data, pos + 1), 5, options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeFloat64 (data, pos, _minor, options) {
  return createToken(readFloat64(data, pos + 1), 9, options)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 * @param {EncodeOptions} options
 */
export function encodeFloat (writer, token, options) {
  const float = token.value

  if (float === false) {
    writer.push([Type.float.majorEncoded | MINOR_FALSE])
  } else if (float === true) {
    writer.push([Type.float.majorEncoded | MINOR_TRUE])
  } else if (float === null) {
    writer.push([Type.float.majorEncoded | MINOR_NULL])
  } else if (float === undefined) {
    writer.push([Type.float.majorEncoded | MINOR_UNDEFINED])
  } else {
    let decoded
    let success = false
    if (!options || options.float64 !== true) {
      encodeFloat16(float)
      decoded = readFloat16(ui8a, 1)
      if (float === decoded || Number.isNaN(float)) {
        ui8a[0] = 0xf9
        writer.push(ui8a.slice(0, 3))
        success = true
      } else {
        encodeFloat32(float)
        decoded = readFloat32(ui8a, 1)
        if (float === decoded) {
          ui8a[0] = 0xfa
          writer.push(ui8a.slice(0, 5))
          success = true
        }
      }
    }
    if (!success) {
      encodeFloat64(float)
      decoded = readFloat64(ui8a, 1)
      ui8a[0] = 0xfb
      writer.push(ui8a.slice(0, 9))
    }
  }
}

/**
 * @param {Token} token
 * @param {EncodeOptions} options
 * @returns {number}
 */
encodeFloat.encodedSize = function encodedSize (token, options) {
  const float = token.value

  if (float === false || float === true || float === null || float === undefined) {
    return 1
  }

  if (!options || options.float64 !== true) {
    encodeFloat16(float)
    let decoded = readFloat16(ui8a, 1)
    if (float === decoded || Number.isNaN(float)) {
      return 3
    }
    encodeFloat32(float)
    decoded = readFloat32(ui8a, 1)
    if (float === decoded) {
      return 5
    }
  }
  return 9
}

const buffer = new ArrayBuffer(9)
const dataView = new DataView(buffer, 1)
const ui8a = new Uint8Array(buffer, 0)

/**
 * @param {number} inp
 */
function encodeFloat16 (inp) {
  if (inp === Infinity) {
    dataView.setUint16(0, 0x7c00, false)
  } else if (inp === -Infinity) {
    dataView.setUint16(0, 0xfc00, false)
  } else if (Number.isNaN(inp)) {
    dataView.setUint16(0, 0x7e00, false)
  } else {
    dataView.setFloat32(0, inp)
    const valu32 = dataView.getUint32(0)
    const exponent = (valu32 & 0x7f800000) >> 23
    const mantissa = valu32 & 0x7fffff

    if (exponent === 0xff) {
      // too big, Infinity, but this should be hard (impossible?) to trigger
      dataView.setUint16(0, 0x7c00, false)
    } else if (exponent === 0x00) {
      // 0.0, -0.0 and subnormals, shouldn't be possible to get here because 0.0 should be counted as an int
      // Use valu32 for sign bit since bitwise ops on floats lose -0 sign
      dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | (mantissa >> 13), false)
    } else { // standard numbers
      // chunks of logic here borrowed from https://github.com/PJK/libcbor/blob/c78f437182533e3efa8d963ff4b945bb635c2284/src/cbor/encoding.c#L127
      const logicalExponent = exponent - 127
      // Now we know that 2^exponent <= 0 logically
      if (logicalExponent < -24) {
        /* No unambiguous representation exists, this float is not a half float
          and is too small to be represented using a half, round off to zero.
          Consistent with the reference implementation. */
        // should be difficult (impossible?) to get here in JS
        dataView.setUint16(0, 0)
      } else if (logicalExponent < -14) {
        /* Offset the remaining decimal places by shifting the significand, the
          value is lost. This is an implementation decision that works around the
          absence of standard half-float in the language. */
        dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | /* sign bit */ (1 << (24 + logicalExponent)), false)
      } else {
        dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | ((logicalExponent + 15) << 10) | (mantissa >> 13), false)
      }
    }
  }
}

/**
 * @param {Uint8Array} ui8a
 * @param {number} pos
 * @returns {number}
 */
function readFloat16 (ui8a, pos) {
  if (ui8a.length - pos < 2) {
    throw new Error(`${decodeErrPrefix} not enough data for float16`)
  }

  const half = (ui8a[pos] << 8) + ui8a[pos + 1]
  if (half === 0x7c00) {
    return Infinity
  }
  if (half === 0xfc00) {
    return -Infinity
  }
  if (half === 0x7e00) {
    return NaN
  }
  const exp = (half >> 10) & 0x1f
  const mant = half & 0x3ff
  let val
  if (exp === 0) {
    val = mant * (2 ** -24)
  } else if (exp !== 31) {
    val = (mant + 1024) * (2 ** (exp - 25))
  } else {
    // may not be possible to get here
    val = mant === 0 ? Infinity : NaN
  }
  return (half & 0x8000) ? -val : val
}

/**
 * @param {number} inp
 */
function encodeFloat32 (inp) {
  dataView.setFloat32(0, inp, false)
}

/**
 * @param {Uint8Array} ui8a
 * @param {number} pos
 * @returns {number}
 */
function readFloat32 (ui8a, pos) {
  if (ui8a.length - pos < 4) {
    throw new Error(`${decodeErrPrefix} not enough data for float32`)
  }
  const offset = (ui8a.byteOffset || 0) + pos
  return new DataView(ui8a.buffer, offset, 4).getFloat32(0, false)
}

/**
 * @param {number} inp
 */
function encodeFloat64 (inp) {
  dataView.setFloat64(0, inp, false)
}

/**
 * @param {Uint8Array} ui8a
 * @param {number} pos
 * @returns {number}
 */
function readFloat64 (ui8a, pos) {
  if (ui8a.length - pos < 8) {
    throw new Error(`${decodeErrPrefix} not enough data for float64`)
  }
  const offset = (ui8a.byteOffset || 0) + pos
  return new DataView(ui8a.buffer, offset, 8).getFloat64(0, false)
}

/**
 * @param {Token} _tok1
 * @param {Token} _tok2
 * @returns {number}
 */
encodeFloat.compareTokens = encodeUint.compareTokens
/*
encodeFloat.compareTokens = function compareTokens (_tok1, _tok2) {
  return _tok1
  throw new Error(`${encodeErrPrefix} cannot use floats as map keys`)
}
*/
/**
 * Bl is a list of byte chunks, similar to https://github.com/rvagg/bl but for
 * writing rather than reading.
 * A Bl object accepts set() operations for individual bytes and copyTo() for
 * inserting byte arrays. These write operations don't automatically increment
 * the internal cursor so its "length" won't be changed. Instead, increment()
 * must be called to extend its length to cover the inserted data.
 * The toBytes() call will convert all internal memory to a single Uint8Array of
 * the correct length, truncating any data that is stored but hasn't been
 * included by an increment().
 * get() can retrieve a single byte.
 * All operations (except toBytes()) take an "offset" argument that will perform
 * the write at the offset _from the current cursor_. For most operations this
 * will be `0` to write at the current cursor position but it can be ahead of
 * the current cursor. Negative offsets probably work but are untested.
 */

// TODO: ipjs doesn't support this, only for test files: https://github.com/mikeal/ipjs/blob/master/src/package/testFile.js#L39
import { alloc, concat, slice } from './byte-utils.js'

// the ts-ignores in this file are almost all for the `Uint8Array|number[]` duality that exists
// for perf reasons. Consider better approaches to this or removing it entirely, it is quite
// risky because of some assumptions about small chunks === number[] and everything else === Uint8Array.

const defaultChunkSize = 256

export class Bl {
  /**
   * @param {number} [chunkSize]
   */
  constructor (chunkSize = defaultChunkSize) {
    this.chunkSize = chunkSize
    /** @type {number} */
    this.cursor = 0
    /** @type {number} */
    this.maxCursor = -1
    /** @type {(Uint8Array|number[])[]} */
    this.chunks = []
    // keep the first chunk around if we can to save allocations for future encodes
    /** @type {Uint8Array|number[]|null} */
    this._initReuseChunk = null
  }

  reset () {
    this.cursor = 0
    this.maxCursor = -1
    if (this.chunks.length) {
      this.chunks = []
    }
    if (this._initReuseChunk !== null) {
      this.chunks.push(this._initReuseChunk)
      this.maxCursor = this._initReuseChunk.length - 1
    }
  }

  /**
   * @param {Uint8Array|number[]} bytes
   */
  push (bytes) {
    let topChunk = this.chunks[this.chunks.length - 1]
    const newMax = this.cursor + bytes.length
    if (newMax <= this.maxCursor + 1) {
      // we have at least one chunk and we can fit these bytes into that chunk
      const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1
      // @ts-ignore
      topChunk.set(bytes, chunkPos)
    } else {
      // can't fit it in
      if (topChunk) {
        // trip the last chunk to `cursor` if we need to
        const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1
        if (chunkPos < topChunk.length) {
          // @ts-ignore
          this.chunks[this.chunks.length - 1] = topChunk.subarray(0, chunkPos)
          this.maxCursor = this.cursor - 1
        }
      }
      if (bytes.length < 64 && bytes.length < this.chunkSize) {
        // make a new chunk and copy the new one into it
        topChunk = alloc(this.chunkSize)
        this.chunks.push(topChunk)
        this.maxCursor += topChunk.length
        if (this._initReuseChunk === null) {
          this._initReuseChunk = topChunk
        }
        // @ts-ignore
        topChunk.set(bytes, 0)
      } else {
        // push the new bytes in as its own chunk
        this.chunks.push(bytes)
        this.maxCursor += bytes.length
      }
    }
    this.cursor += bytes.length
  }

  /**
   * @param {boolean} [reset]
   * @returns {Uint8Array}
   */
  toBytes (reset = false) {
    let byts
    if (this.chunks.length === 1) {
      const chunk = this.chunks[0]
      if (reset && this.cursor > chunk.length / 2) {
        // @ts-ignore
        byts = this.cursor === chunk.length ? chunk : chunk.subarray(0, this.cursor)
        this._initReuseChunk = null
        this.chunks = []
      } else {
        // @ts-ignore
        byts = slice(chunk, 0, this.cursor)
      }
    } else {
      // @ts-ignore
      byts = concat(this.chunks, this.cursor)
    }
    if (reset) {
      this.reset()
    }
    return byts
  }
}

/**
 * U8Bl is a buffer list that writes directly to a user-provided Uint8Array.
 * It provides the same interface as Bl but writes to a fixed destination.
 */
export class U8Bl {
  /**
   * @param {Uint8Array} dest
   */
  constructor (dest) {
    this.dest = dest
    /** @type {number} */
    this.cursor = 0
    // chunks is for interface compatibility with Bl - encode.js checks chunks.length
    // as a sanity check for pre-calculated sizes. For U8Bl this is always [dest].
    /** @type {Uint8Array[]} */
    this.chunks = [dest]
  }

  reset () {
    this.cursor = 0
  }

  /**
   * @param {Uint8Array|number[]} bytes
   */
  push (bytes) {
    if (this.cursor + bytes.length > this.dest.length) {
      throw new Error('write out of bounds, destination buffer is too small')
    }
    this.dest.set(bytes, this.cursor)
    this.cursor += bytes.length
  }

  /**
   * @param {boolean} [reset]
   * @returns {Uint8Array}
   */
  toBytes (reset = false) {
    const byts = this.dest.subarray(0, this.cursor)
    if (reset) {
      this.reset()
    }
    return byts
  }
}
// Use Uint8Array directly in the browser, use Buffer in Node.js but don't
// speak its name directly to avoid bundlers pulling in the `Buffer` polyfill

// @ts-ignore
export const useBuffer = globalThis.process &&
  // @ts-ignore
  !globalThis.process.browser &&
  // @ts-ignore
  globalThis.Buffer &&
  // @ts-ignore
  typeof globalThis.Buffer.isBuffer === 'function'

const textEncoder = new TextEncoder()

/**
 * @param {Uint8Array} buf
 * @returns {boolean}
 */
function isBuffer (buf) {
  // @ts-ignore
  return useBuffer && globalThis.Buffer.isBuffer(buf)
}

/**
 * @param {Uint8Array|number[]} buf
 * @returns {Uint8Array}
 */
export function asU8A (buf) {
  if (!(buf instanceof Uint8Array)) {
    return Uint8Array.from(buf)
  }
  return isBuffer(buf) ? new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength) : buf
}

// Threshold for manual UTF-8 encoding vs native methods.
// Node.js Buffer.from: crossover ~24 chars
// Browser TextEncoder: crossover ~200 chars
const FROM_STRING_THRESHOLD_BUFFER = 24
const FROM_STRING_THRESHOLD_TEXTENCODER = 200

export const fromString = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {string} string
     */
    (string) => {
      return string.length >= FROM_STRING_THRESHOLD_BUFFER
        ? // eslint-disable-line operator-linebreak
      // @ts-ignore
        globalThis.Buffer.from(string)
        : utf8ToBytes(string)
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {string} string
     */
    (string) => {
      return string.length >= FROM_STRING_THRESHOLD_TEXTENCODER ? textEncoder.encode(string) : utf8ToBytes(string)
    }

/**
 * Buffer variant not fast enough for what we need
 * @param {number[]} arr
 * @returns {Uint8Array}
 */
export const fromArray = (arr) => {
  return Uint8Array.from(arr)
}

export const slice = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} bytes
     * @param {number} start
     * @param {number} end
     */
    // Buffer.slice() returns a view, not a copy, so we need special handling
    (bytes, start, end) => {
      if (isBuffer(bytes)) {
        return new Uint8Array(bytes.subarray(start, end))
      }
      return bytes.slice(start, end)
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} bytes
     * @param {number} start
     * @param {number} end
     */
    (bytes, start, end) => {
      return bytes.slice(start, end)
    }

export const concat = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array[]} chunks
     * @param {number} length
     * @returns {Uint8Array}
     */
    (chunks, length) => {
      // might get a stray plain Array here
      chunks = chunks.map((c) => c instanceof Uint8Array
        ? c
        : // eslint-disable-line operator-linebreak
        // @ts-ignore
        globalThis.Buffer.from(c))
      // @ts-ignore
      return asU8A(globalThis.Buffer.concat(chunks, length))
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array[]} chunks
     * @param {number} length
     * @returns {Uint8Array}
     */
    (chunks, length) => {
      const out = new Uint8Array(length)
      let off = 0
      for (let b of chunks) {
        if (off + b.length > out.length) {
          // final chunk that's bigger than we need
          b = b.subarray(0, out.length - off)
        }
        out.set(b, off)
        off += b.length
      }
      return out
    }

export const alloc = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {number} size
     * @returns {Uint8Array}
     */
    (size) => {
      // we always write over the contents we expose so this should be safe
      // @ts-ignore
      return globalThis.Buffer.allocUnsafe(size)
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {number} size
     * @returns {Uint8Array}
     */
    (size) => {
      return new Uint8Array(size)
    }

export const toHex = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} d
     * @returns {string}
     */
    (d) => {
      if (typeof d === 'string') {
        return d
      }
      // @ts-ignore
      return globalThis.Buffer.from(toBytes(d)).toString('hex')
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} d
     * @returns {string}
     */
    (d) => {
      if (typeof d === 'string') {
        return d
      }
      // @ts-ignore not smart enough to figure this out
      return Array.prototype.reduce.call(toBytes(d), (p, c) => `${p}${c.toString(16).padStart(2, '0')}`, '')
    }

export const fromHex = useBuffer
  ? // eslint-disable-line operator-linebreak
  /**
   * @param {string|Uint8Array} hex
   * @returns {Uint8Array}
   */
    (hex) => {
      if (hex instanceof Uint8Array) {
        return hex
      }
      // @ts-ignore
      return globalThis.Buffer.from(hex, 'hex')
    }
  : // eslint-disable-line operator-linebreak
  /**
   * @param {string|Uint8Array} hex
   * @returns {Uint8Array}
   */
    (hex) => {
      if (hex instanceof Uint8Array) {
        return hex
      }
      if (!hex.length) {
        return new Uint8Array(0)
      }
      return new Uint8Array(hex.split('')
        .map((/** @type {string} */ c, /** @type {number} */ i, /** @type {string[]} */ d) => i % 2 === 0 ? `0x${c}${d[i + 1]}` : '')
        .filter(Boolean)
        .map((/** @type {string} */ e) => parseInt(e, 16)))
    }

/**
 * @param {Uint8Array|ArrayBuffer|ArrayBufferView} obj
 * @returns {Uint8Array}
 */
function toBytes (obj) {
  if (obj instanceof Uint8Array && obj.constructor.name === 'Uint8Array') {
    return obj
  }
  if (obj instanceof ArrayBuffer) {
    return new Uint8Array(obj)
  }
  if (ArrayBuffer.isView(obj)) {
    return new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength)
  }
  throw new Error('Unknown type, must be binary type')
}

/**
 * @param {Uint8Array} b1
 * @param {Uint8Array} b2
 * @returns {number}
 */
export function compare (b1, b2) {
  if (isBuffer(b1) && isBuffer(b2)) {
    // probably not possible to get here in the current API
    // @ts-ignore Buffer
    return b1.compare(b2)
  }
  for (let i = 0; i < b1.length; i++) {
    if (b1[i] === b2[i]) {
      continue
    }
    return b1[i] < b2[i] ? -1 : 1
  }
  return 0
}

// The below code is taken from https://github.com/google/closure-library/blob/8598d87242af59aac233270742c8984e2b2bdbe0/closure/goog/crypt/crypt.js#L117-L143
// Licensed Apache-2.0.

/**
 * @param {string} str
 * @returns {number[]}
 */
function utf8ToBytes (str) {
  const out = []
  let p = 0
  for (let i = 0; i < str.length; i++) {
    let c = str.charCodeAt(i)
    if (c < 128) {
      out[p++] = c
    } else if (c < 2048) {
      out[p++] = (c >> 6) | 192
      out[p++] = (c & 63) | 128
    } else if (
      ((c & 0xFC00) === 0xD800) && (i + 1) < str.length &&
      ((str.charCodeAt(i + 1) & 0xFC00) === 0xDC00)) {
      // Surrogate Pair
      c = 0x10000 + ((c & 0x03FF) << 10) + (str.charCodeAt(++i) & 0x03FF)
      out[p++] = (c >> 18) | 240
      out[p++] = ((c >> 12) & 63) | 128
      out[p++] = ((c >> 6) & 63) | 128
      out[p++] = (c & 63) | 128
    } else {
      if ((c >= 0xD800) && (c <= 0xDFFF)) {
        c = 0xFFFD // Unpaired Surrogate
      }
      out[p++] = (c >> 12) | 224
      out[p++] = ((c >> 6) & 63) | 128
      out[p++] = (c & 63) | 128
    }
  }
  return out
}

// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
const MAX_ARGUMENTS_LENGTH = 0x1000

/**
 * @param {number[]} codePoints
 * @returns {string}
 */
export function decodeCodePointsArray (codePoints) {
  const len = codePoints.length
  if (len <= MAX_ARGUMENTS_LENGTH) {
    return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  }
  // Decode in chunks to avoid "call stack size exceeded".
  let res = ''
  let i = 0
  while (i < len) {
    res += String.fromCharCode.apply(
      String,
      codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
    )
  }
  return res
}
const decodeErrPrefix = 'CBOR decode error:'
const encodeErrPrefix = 'CBOR encode error:'

const uintMinorPrefixBytes = []
uintMinorPrefixBytes[23] = 1
uintMinorPrefixBytes[24] = 2
uintMinorPrefixBytes[25] = 3
uintMinorPrefixBytes[26] = 5
uintMinorPrefixBytes[27] = 9

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} need
 */
function assertEnoughData (data, pos, need) {
  if (data.length - pos < need) {
    throw new Error(`${decodeErrPrefix} not enough data for type`)
  }
}

export {
  decodeErrPrefix,
  encodeErrPrefix,
  uintMinorPrefixBytes,
  assertEnoughData
}
import { decodeErrPrefix } from './common.js'
import { Type } from './token.js'
import { jump, quick } from './jump.js'
import { asU8A } from './byte-utils.js'

/**
 * @typedef {import('./token.js').Token} Token
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 * @typedef {import('../interface.js').DecodeTokenizer} DecodeTokenizer
 * @typedef {import('../interface.js').TagDecodeControl} TagDecodeControl
 */

const defaultDecodeOptions = {
  strict: false,
  allowIndefinite: true,
  allowUndefined: true,
  allowBigInt: true
}

/**
 * @implements {DecodeTokenizer}
 */
class Tokeniser {
  /**
   * @param {Uint8Array} data
   * @param {DecodeOptions} options
   */
  constructor (data, options = {}) {
    this._pos = 0
    this.data = data
    this.options = options
  }

  pos () {
    return this._pos
  }

  done () {
    return this._pos >= this.data.length
  }

  next () {
    const byt = this.data[this._pos]
    let token = quick[byt]
    if (token === undefined) {
      const decoder = jump[byt]
      // if we're here then there's something wrong with our jump or quick lists!
      if (!decoder) {
        throw new Error(`${decodeErrPrefix} no decoder for major type ${byt >>> 5} (byte 0x${byt.toString(16).padStart(2, '0')})`)
      }
      const minor = byt & 31
      token = decoder(this.data, this._pos, minor, this.options)
    }
    // @ts-ignore we get to assume encodedLength is set (crossing fingers slightly)
    this._pos += token.encodedLength
    return token
  }
}

const DONE = Symbol.for('DONE')
const BREAK = Symbol.for('BREAK')

/**
 * @param {Token} token
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {any|BREAK|DONE}
 */
function tokenToArray (token, tokeniser, options) {
  const arr = []
  for (let i = 0; i < token.value; i++) {
    const value = tokensToObject(tokeniser, options)
    if (value === BREAK) {
      if (token.value === Infinity) {
        // normal end to indefinite length array
        break
      }
      throw new Error(`${decodeErrPrefix} got unexpected break to lengthed array`)
    }
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} found array but not enough entries (got ${i}, expected ${token.value})`)
    }
    arr[i] = value
  }
  return arr
}

/**
 * @param {Token} token
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {any|BREAK|DONE}
 */
function tokenToMap (token, tokeniser, options) {
  const useMaps = options.useMaps === true
  const rejectDuplicateMapKeys = options.rejectDuplicateMapKeys === true
  const obj = useMaps ? undefined : {}
  const m = useMaps ? new Map() : undefined
  for (let i = 0; i < token.value; i++) {
    const key = tokensToObject(tokeniser, options)
    if (key === BREAK) {
      if (token.value === Infinity) {
        // normal end to indefinite length map
        break
      }
      throw new Error(`${decodeErrPrefix} got unexpected break to lengthed map`)
    }
    if (key === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no key], expected ${token.value})`)
    }
    if (!useMaps && typeof key !== 'string') {
      throw new Error(`${decodeErrPrefix} non-string keys not supported (got ${typeof key})`)
    }
    if (rejectDuplicateMapKeys) {
      // @ts-ignore
      if ((useMaps && m.has(key)) || (!useMaps && Object.hasOwn(obj, key))) {
        throw new Error(`${decodeErrPrefix} found repeat map key "${key}"`)
      }
    }
    const value = tokensToObject(tokeniser, options)
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no value], expected ${token.value})`)
    }
    if (useMaps) {
      // @ts-ignore TODO reconsider this .. maybe needs to be strict about key types
      m.set(key, value)
    } else {
      // @ts-ignore TODO reconsider this .. maybe needs to be strict about key types
      obj[key] = value
    }
  }
  // @ts-ignore c'mon man
  return useMaps ? m : obj
}

/**
 * Generator that yields [key, value] entries from a CBOR map token.
 * Used by tag decoders that need to preserve key types (e.g., Tag 259 Map).
 * @param {Token} token - The map token
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {Generator<[any, any], void, unknown>}
 */
function * tokenToMapEntries (token, tokeniser, options) {
  for (let i = 0; i < token.value; i++) {
    const key = tokensToObject(tokeniser, options)
    if (key === BREAK) {
      if (token.value === Infinity) {
        // normal end to indefinite length map
        break
      }
      throw new Error(`${decodeErrPrefix} got unexpected break to lengthed map`)
    }
    if (key === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no key], expected ${token.value})`)
    }
    const value = tokensToObject(tokeniser, options)
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no value], expected ${token.value})`)
    }
    yield [key, value]
  }
}

/**
 * Creates a TagDecodeControl object for tag decoders.
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {TagDecodeControl}
 */
function createTagDecodeControl (tokeniser, options) {
  let called = false

  /**
   * @type {TagDecodeControl}
   */
  const decode = function () {
    if (called) {
      throw new Error(`${decodeErrPrefix} tag decode() may only be called once`)
    }
    called = true
    const value = tokensToObject(tokeniser, options)
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} tag content missing`)
    }
    if (value === BREAK) {
      throw new Error(`${decodeErrPrefix} got unexpected break in tag content`)
    }
    return value
  }

  decode.entries = function () {
    if (called) {
      throw new Error(`${decodeErrPrefix} tag decode() may only be called once`)
    }
    called = true

    // Get the next token and ensure it's a map
    const token = tokeniser.next()
    if (!Type.equals(token.type, Type.map)) {
      throw new Error(`${decodeErrPrefix} entries() requires map content, got ${token.type.name}`)
    }

    // Collect all entries into an array (ensures full content consumption)
    const entries = []
    for (const entry of tokenToMapEntries(token, tokeniser, options)) {
      entries.push(entry)
    }
    return entries
  }

  // For internal tracking
  Object.defineProperty(decode, '_called', {
    get () { return called },
    enumerable: false
  })

  return decode
}

/**
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {any|BREAK|DONE}
 */
function tokensToObject (tokeniser, options) {
  // should we support array as an argument?
  // check for tokenIter[Symbol.iterator] and replace tokenIter with what that returns?
  if (tokeniser.done()) {
    return DONE
  }

  const token = tokeniser.next()

  if (Type.equals(token.type, Type.break)) {
    return BREAK
  }

  if (token.type.terminal) {
    return token.value
  }

  if (Type.equals(token.type, Type.array)) {
    return tokenToArray(token, tokeniser, options)
  }

  if (Type.equals(token.type, Type.map)) {
    return tokenToMap(token, tokeniser, options)
  }

  if (Type.equals(token.type, Type.tag)) {
    if (options.tags && typeof options.tags[token.value] === 'function') {
      const decodeControl = createTagDecodeControl(tokeniser, options)
      const result = options.tags[token.value](decodeControl)
      if (!decodeControl._called) {
        throw new Error(`${decodeErrPrefix} tag decoder must call decode() or entries()`)
      }
      return result
    }
    throw new Error(`${decodeErrPrefix} tag not supported (${token.value})`)
  }
  throw new Error('unsupported')
}

/**
 * @param {Uint8Array} data
 * @param {DecodeOptions} [options]
 * @returns {[any, Uint8Array]}
 */
function decodeFirst (data, options) {
  if (!(data instanceof Uint8Array)) {
    throw new Error(`${decodeErrPrefix} data to decode must be a Uint8Array`)
  }
  options = Object.assign({}, defaultDecodeOptions, options)
  // Convert Buffer to plain Uint8Array for faster slicing in decode path
  const u8aData = asU8A(data)
  const tokeniser = options.tokenizer || new Tokeniser(u8aData, options)
  const decoded = tokensToObject(tokeniser, options)
  if (decoded === DONE) {
    throw new Error(`${decodeErrPrefix} did not find any content to decode`)
  }
  if (decoded === BREAK) {
    throw new Error(`${decodeErrPrefix} got unexpected break`)
  }
  return [decoded, data.subarray(tokeniser.pos())]
}

/**
 * @param {Uint8Array} data
 * @param {DecodeOptions} [options]
 * @returns {any}
 */
function decode (data, options) {
  const [decoded, remainder] = decodeFirst(data, options)
  if (remainder.length > 0) {
    throw new Error(`${decodeErrPrefix} too many terminals, data makes no sense`)
  }
  return decoded
}

export { Tokeniser, tokensToObject, decode, decodeFirst }
import { is } from './is.js'
import { Token, Type } from './token.js'
import { Bl, U8Bl } from './bl.js'
import { encodeErrPrefix } from './common.js'
import { quickEncodeToken } from './jump.js'
import { asU8A, compare, fromString } from './byte-utils.js'

import { encodeUint, encodeUintValue } from './0uint.js'
import { encodeNegint } from './1negint.js'
import { encodeBytes } from './2bytes.js'
import { encodeString } from './3string.js'
import { encodeArray } from './4array.js'
import { encodeMap } from './5map.js'
import { encodeTag } from './6tag.js'
import { encodeFloat, MINOR_FALSE, MINOR_TRUE, MINOR_NULL, MINOR_UNDEFINED } from './7float.js'

/**
 * @typedef {import('../interface.js').EncodeOptions} EncodeOptions
 * @typedef {import('../interface.js').OptionalTypeEncoder} OptionalTypeEncoder
 * @typedef {import('../interface.js').Reference} Reference
 * @typedef {import('../interface.js').StrictTypeEncoder} StrictTypeEncoder
 * @typedef {import('../interface.js').TokenTypeEncoder} TokenTypeEncoder
 * @typedef {import('../interface.js').TokenOrNestedTokens} TokenOrNestedTokens
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 */

/** @type {EncodeOptions} */
const defaultEncodeOptions = {
  float64: false,
  mapSorter,
  quickEncodeToken
}

/** @type {EncodeOptions} */
export const rfc8949EncodeOptions = Object.freeze({
  mapSorter: rfc8949MapSorter,
  quickEncodeToken
})

/** @returns {TokenTypeEncoder[]} */
export function makeCborEncoders () {
  const encoders = []
  encoders[Type.uint.major] = encodeUint
  encoders[Type.negint.major] = encodeNegint
  encoders[Type.bytes.major] = encodeBytes
  encoders[Type.string.major] = encodeString
  encoders[Type.array.major] = encodeArray
  encoders[Type.map.major] = encodeMap
  encoders[Type.tag.major] = encodeTag
  encoders[Type.float.major] = encodeFloat
  return encoders
}

const cborEncoders = makeCborEncoders()

const defaultWriter = new Bl()

/** @implements {Reference} */
class Ref {
  /**
   * @param {object|any[]} obj
   * @param {Reference|undefined} parent
   */
  constructor (obj, parent) {
    this.obj = obj
    this.parent = parent
  }

  /**
   * @param {object|any[]} obj
   * @returns {boolean}
   */
  includes (obj) {
    /** @type {Reference|undefined} */
    let p = this
    do {
      if (p.obj === obj) {
        return true
      }
    } while (p = p.parent) // eslint-disable-line
    return false
  }

  /**
   * @param {Reference|undefined} stack
   * @param {object|any[]} obj
   * @returns {Reference}
   */
  static createCheck (stack, obj) {
    if (stack && stack.includes(obj)) {
      throw new Error(`${encodeErrPrefix} object contains circular references`)
    }
    return new Ref(obj, stack)
  }
}

const simpleTokens = {
  null: new Token(Type.null, null),
  undefined: new Token(Type.undefined, undefined),
  true: new Token(Type.true, true),
  false: new Token(Type.false, false),
  emptyArray: new Token(Type.array, 0),
  emptyMap: new Token(Type.map, 0)
}

/** @type {{[typeName: string]: StrictTypeEncoder}} */
const typeEncoders = {
  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  number (obj, _typ, _options, _refStack) {
    if (!Number.isInteger(obj) || !Number.isSafeInteger(obj)) {
      return new Token(Type.float, obj)
    } else if (obj >= 0) {
      return new Token(Type.uint, obj)
    } else {
      return new Token(Type.negint, obj)
    }
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  bigint (obj, _typ, _options, _refStack) {
    if (obj >= BigInt(0)) {
      return new Token(Type.uint, obj)
    } else {
      return new Token(Type.negint, obj)
    }
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  Uint8Array (obj, _typ, _options, _refStack) {
    return new Token(Type.bytes, obj)
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  string (obj, _typ, _options, _refStack) {
    return new Token(Type.string, obj)
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  boolean (obj, _typ, _options, _refStack) {
    return obj ? simpleTokens.true : simpleTokens.false
  },

  /**
   * @param {any} _obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  null (_obj, _typ, _options, _refStack) {
    return simpleTokens.null
  },

  /**
   * @param {any} _obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  undefined (_obj, _typ, _options, _refStack) {
    return simpleTokens.undefined
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  ArrayBuffer (obj, _typ, _options, _refStack) {
    return new Token(Type.bytes, new Uint8Array(obj))
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  DataView (obj, _typ, _options, _refStack) {
    return new Token(Type.bytes, new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength))
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} options
   * @param {Reference} [refStack]
   * @returns {TokenOrNestedTokens}
   */
  Array (obj, _typ, options, refStack) {
    if (!obj.length) {
      if (options.addBreakTokens === true) {
        return [simpleTokens.emptyArray, new Token(Type.break)]
      }
      return simpleTokens.emptyArray
    }
    refStack = Ref.createCheck(refStack, obj)
    const entries = []
    let i = 0
    for (const e of obj) {
      entries[i++] = objectToTokens(e, options, refStack)
    }
    if (options.addBreakTokens) {
      return [new Token(Type.array, obj.length), entries, new Token(Type.break)]
    }
    return [new Token(Type.array, obj.length), entries]
  },

  /**
   * @param {any} obj
   * @param {string} typ
   * @param {EncodeOptions} options
   * @param {Reference} [refStack]
   * @returns {TokenOrNestedTokens}
   */
  Object (obj, typ, options, refStack) {
    // could be an Object or a Map
    const isMap = typ !== 'Object'
    // it's slightly quicker to use Object.keys() than Object.entries()
    const keys = isMap ? obj.keys() : Object.keys(obj)
    const maxLength = isMap ? obj.size : keys.length

    /** @type {undefined | [TokenOrNestedTokens, TokenOrNestedTokens][]} */
    let entries

    if (maxLength) {
      // Pre-allocate the array with the expected size
      entries = new Array(maxLength)
      refStack = Ref.createCheck(refStack, obj)
      const skipUndefined = !isMap && options.ignoreUndefinedProperties

      let i = 0
      for (const key of keys) {
        const value = isMap ? obj.get(key) : obj[key]
        if (skipUndefined && value === undefined) {
          continue
        }
        entries[i++] = [
          objectToTokens(key, options, refStack),
          objectToTokens(value, options, refStack)
        ]
      }

      // Truncate only if properties were skipped
      if (i < maxLength) {
        entries.length = i
      }
    }

    if (!entries?.length) {
      if (options.addBreakTokens === true) {
        return [simpleTokens.emptyMap, new Token(Type.break)]
      }
      return simpleTokens.emptyMap
    }

    sortMapEntries(entries, options)
    if (options.addBreakTokens) {
      return [new Token(Type.map, entries.length), entries, new Token(Type.break)]
    }
    return [new Token(Type.map, entries.length), entries]
  },

  /**
   * Encode a `Tagged` wrapper as a CBOR tag header followed by the encoded
   * form of the wrapped value. The value is recursively tokenised through
   * `objectToTokens()` so any registered `typeEncoders` apply to it.
   *
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} options
   * @param {Reference} [refStack]
   * @returns {TokenOrNestedTokens}
   */
  Tagged (obj, _typ, options, refStack) {
    return [
      new Token(Type.tag, obj.tag),
      objectToTokens(obj.value, options, refStack)
    ]
  }
}

typeEncoders.Map = typeEncoders.Object
typeEncoders.Buffer = typeEncoders.Uint8Array
for (const typ of 'Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64'.split(' ')) {
  typeEncoders[`${typ}Array`] = typeEncoders.DataView
}

/**
 * @param {any} obj
 * @param {EncodeOptions} [options]
 * @param {Reference} [refStack]
 * @returns {TokenOrNestedTokens}
 */
function objectToTokens (obj, options = {}, refStack) {
  const typ = is(obj)
  const customTypeEncoder = (options && options.typeEncoders && /** @type {OptionalTypeEncoder} */ options.typeEncoders[typ]) || typeEncoders[typ]
  if (typeof customTypeEncoder === 'function') {
    const tokens = customTypeEncoder(obj, typ, options, refStack)
    if (tokens != null) {
      return tokens
    }
  }
  const typeEncoder = typeEncoders[typ]
  if (!typeEncoder) {
    throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`)
  }
  return typeEncoder(obj, typ, options, refStack)
}

/*
CBOR key sorting is a mess.

The canonicalisation recommendation from https://tools.ietf.org/html/rfc7049#section-3.9
includes the wording:

> The keys in every map must be sorted lowest value to highest.
> Sorting is performed on the bytes of the representation of the key
> data items without paying attention to the 3/5 bit splitting for
> major types.
> ...
>  *  If two keys have different lengths, the shorter one sorts
      earlier;
>  *  If two keys have the same length, the one with the lower value
      in (byte-wise) lexical order sorts earlier.

1. It is not clear what "bytes of the representation of the key" means: is it
   the CBOR representation, or the binary representation of the object itself?
   Consider the int and uint difference here.
2. It is not clear what "without paying attention to" means: do we include it
   and compare on that? Or do we omit the special prefix byte, (mostly) treating
   the key in its plain binary representation form.

The FIDO 2.0: Client To Authenticator Protocol spec takes the original CBOR
wording and clarifies it according to their understanding.
https://fidoalliance.org/specs/fido-v2.0-rd-20170927/fido-client-to-authenticator-protocol-v2.0-rd-20170927.html#message-encoding

> The keys in every map must be sorted lowest value to highest. Sorting is
> performed on the bytes of the representation of the key data items without
> paying attention to the 3/5 bit splitting for major types. The sorting rules
> are:
>  * If the major types are different, the one with the lower value in numerical
>    order sorts earlier.
>  * If two keys have different lengths, the shorter one sorts earlier;
>  * If two keys have the same length, the one with the lower value in
>    (byte-wise) lexical order sorts earlier.

Some other implementations, such as borc, do a full encode then do a
length-first, byte-wise-second comparison:
https://github.com/dignifiedquire/borc/blob/b6bae8b0bcde7c3976b0f0f0957208095c392a36/src/encoder.js#L358
https://github.com/dignifiedquire/borc/blob/b6bae8b0bcde7c3976b0f0f0957208095c392a36/src/utils.js#L143-L151

This has the benefit of being able to easily handle arbitrary keys, including
complex types (maps and arrays).

We'll opt for the FIDO approach, since it affords some efficies since we don't
need a full encode of each key to determine order and can defer to the types
to determine how to most efficiently order their values (i.e. int and uint
ordering can be done on the numbers, no need for byte-wise, for example).

Recommendation: stick to single key types or you'll get into trouble, and prefer
string keys because it's much simpler that way.
*/

/**
 * @param {TokenOrNestedTokens[]} entries
 * @param {EncodeOptions} options
 */
function sortMapEntries (entries, options) {
  if (options.mapSorter) {
    entries.sort(options.mapSorter)
  }
}

/**
 * @param {(Token|Token[])[]} e1
 * @param {(Token|Token[])[]} e2
 * @returns {number}
 */
function mapSorter (e1, e2) {
  // the key position ([0]) could have a single token or an array
  // almost always it'll be a single token but complex key might get involved
  const keyToken1 = Array.isArray(e1[0]) ? e1[0][0] : e1[0]
  const keyToken2 = Array.isArray(e2[0]) ? e2[0][0] : e2[0]

  // different key types
  if (keyToken1.type !== keyToken2.type) {
    return keyToken1.type.compare(keyToken2.type)
  }

  const major = keyToken1.type.major
  // TODO: handle case where cmp === 0 but there are more keyToken e. complex type)
  const tcmp = cborEncoders[major].compareTokens(keyToken1, keyToken2)
  if (tcmp === 0) {
    // duplicate key or complex type where the first token matched,
    // i.e. a map or array and we're only comparing the opening token
    console.warn('WARNING: complex key types used, CBOR key sorting guarantees are gone')
  }
  return tcmp
}

/**
 * @typedef {Token & { _keyBytes?: Uint8Array }} TokenEx
 *
 * @param {(Token|Token[])[]} e1
 * @param {(Token|Token[])[]} e2
 * @returns {number}
 */
function rfc8949MapSorter (e1, e2) {
  if (e1[0] instanceof Token && e2[0] instanceof Token) {
    const t1 = /** @type {TokenEx} */ (e1[0])
    const t2 = /** @type {TokenEx} */ (e2[0])

    if (!t1._keyBytes) {
      t1._keyBytes = encodeRfc8949(t1.value)
    }

    if (!t2._keyBytes) {
      t2._keyBytes = encodeRfc8949(t2.value)
    }

    return compare(t1._keyBytes, t2._keyBytes)
  }

  throw new Error('rfc8949MapSorter: complex key types are not supported yet')
}

/**
 * @param {any} data
 * @returns {Uint8Array}
 */
function encodeRfc8949 (data) {
  return encodeCustom(data, cborEncoders, rfc8949EncodeOptions)
}

/**
 * @param {ByteWriter} writer
 * @param {TokenOrNestedTokens} tokens
 * @param {TokenTypeEncoder[]} encoders
 * @param {EncodeOptions} options
 */
function tokensToEncoded (writer, tokens, encoders, options) {
  if (Array.isArray(tokens)) {
    for (const token of tokens) {
      tokensToEncoded(writer, token, encoders, options)
    }
  } else {
    encoders[tokens.type.major](writer, tokens, options)
  }
}

// CBOR major type prefixes, cached from Type for hot path performance
const MAJOR_UINT = Type.uint.majorEncoded
const MAJOR_NEGINT = Type.negint.majorEncoded
const MAJOR_BYTES = Type.bytes.majorEncoded
const MAJOR_STRING = Type.string.majorEncoded
const MAJOR_ARRAY = Type.array.majorEncoded

// Simple value bytes (CBOR major type 7 + minor value)
const SIMPLE_FALSE = Type.float.majorEncoded | MINOR_FALSE
const SIMPLE_TRUE = Type.float.majorEncoded | MINOR_TRUE
const SIMPLE_NULL = Type.float.majorEncoded | MINOR_NULL
const SIMPLE_UNDEFINED = Type.float.majorEncoded | MINOR_UNDEFINED

const neg1b = BigInt(-1)
const pos1b = BigInt(1)

/**
 * Check if direct encoding can be used for the given options.
 * Direct encoding bypasses token creation for most values.
 * @param {EncodeOptions} options
 * @returns {boolean}
 */
function canDirectEncode (options) {
  // Cannot use direct encode with addBreakTokens (needs special break token handling).
  // Direct encode checks typeEncoders per-value, falling back to tokens as needed.
  // Maps fall back to token-based encoding for efficient key sorting.
  return options.addBreakTokens !== true
}

/**
 * Direct encode a value to the writer, bypassing token creation for most types.
 * Falls back to token-based encoding for custom type encoders.
 * @param {ByteWriter} writer
 * @param {any} data
 * @param {EncodeOptions} options
 * @param {Reference|undefined} refStack
 */
function directEncode (writer, data, options, refStack) {
  const typ = is(data)

  // Check for custom encoder for THIS specific type
  const customEncoder = options.typeEncoders && options.typeEncoders[typ]
  if (customEncoder) {
    const tokens = customEncoder(data, typ, options, refStack)
    if (tokens != null) {
      // Custom encoder returned tokens, serialize immediately
      tokensToEncoded(writer, tokens, cborEncoders, options)
      return
    }
    // Custom encoder returned null, fall through to default handling
  }

  // Direct encode based on type
  switch (typ) {
    case 'null':
      writer.push([SIMPLE_NULL])
      return

    case 'undefined':
      writer.push([SIMPLE_UNDEFINED])
      return

    case 'boolean':
      writer.push([data ? SIMPLE_TRUE : SIMPLE_FALSE])
      return

    case 'number':
      if (!Number.isInteger(data) || !Number.isSafeInteger(data)) {
        // Float, use token encoder for complex float encoding
        encodeFloat(writer, new Token(Type.float, data), options)
      } else if (data >= 0) {
        encodeUintValue(writer, MAJOR_UINT, data)
      } else {
        // Negative integer
        encodeUintValue(writer, MAJOR_NEGINT, data * -1 - 1)
      }
      return

    case 'bigint':
      if (data >= BigInt(0)) {
        encodeUintValue(writer, MAJOR_UINT, data)
      } else {
        encodeUintValue(writer, MAJOR_NEGINT, data * neg1b - pos1b)
      }
      return

    case 'string': {
      const bytes = fromString(data)
      encodeUintValue(writer, MAJOR_STRING, bytes.length)
      writer.push(bytes)
      return
    }

    case 'Uint8Array':
      encodeUintValue(writer, MAJOR_BYTES, data.length)
      writer.push(data)
      return

    case 'Array':
      if (!data.length) {
        writer.push([MAJOR_ARRAY]) // Empty array: 0x80
        return
      }
      refStack = Ref.createCheck(refStack, data)
      encodeUintValue(writer, MAJOR_ARRAY, data.length)
      for (const elem of data) {
        directEncode(writer, elem, options, refStack)
      }
      return

    case 'Object':
    case 'Map':
      // Maps require key sorting, use token-based encoding for efficiency
      // (pre-encoding all keys for sorting is expensive)
      {
        const tokens = typeEncoders.Object(data, typ, options, refStack)
        tokensToEncoded(writer, tokens, cborEncoders, options)
      }
      return

    default:
    // Fall back to token-based encoding for other types (DataView, TypedArrays, etc.)
    {
      const typeEncoder = typeEncoders[typ]
      if (!typeEncoder) {
        throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`)
      }
      const tokens = typeEncoder(data, typ, options, refStack)
      tokensToEncoded(writer, tokens, cborEncoders, options)
    }
  }
}

/**
 * @param {any} data
 * @param {TokenTypeEncoder[]} encoders
 * @param {EncodeOptions} options
 * @param {Uint8Array} [destination]
 * @returns {Uint8Array}
 */
function encodeCustom (data, encoders, options, destination) {
  // arg ordering is different to encodeInto for backward compatibility
  const hasDest = destination instanceof Uint8Array
  let writeTo = hasDest ? new U8Bl(destination) : defaultWriter

  const tokens = objectToTokens(data, options)
  if (!Array.isArray(tokens) && options.quickEncodeToken) {
    const quickBytes = options.quickEncodeToken(tokens)
    if (quickBytes) {
      if (hasDest) {
        // Copy quick bytes into destination buffer
        writeTo.push(quickBytes)
        return writeTo.toBytes()
      }
      return quickBytes
    }
    const encoder = encoders[tokens.type.major]
    if (encoder.encodedSize) {
      const size = encoder.encodedSize(tokens, options)
      if (!hasDest) {
        writeTo = new Bl(size)
      }
      encoder(writeTo, tokens, options)
      // this would be a problem with encodedSize() functions
      if (writeTo.chunks.length !== 1) {
        throw new Error(`Unexpected error: pre-calculated length for ${tokens} was wrong`)
      }
      return hasDest ? writeTo.toBytes() : asU8A(writeTo.chunks[0])
    }
  }
  writeTo.reset()
  tokensToEncoded(writeTo, tokens, encoders, options)
  return writeTo.toBytes(true)
}

/**
 * @param {any} data
 * @param {EncodeOptions} [options]
 * @returns {Uint8Array}
 */
function encode (data, options) {
  options = Object.assign({}, defaultEncodeOptions, options)

  // Use direct encode path when possible
  if (canDirectEncode(options)) {
    defaultWriter.reset()
    directEncode(defaultWriter, data, options, undefined)
    return defaultWriter.toBytes(true)
  }

  return encodeCustom(data, cborEncoders, options)
}

/**
 * @param {any} data
 * @param {Uint8Array} destination
 * @param {EncodeOptions} [options]
 * @returns {{ written: number }}
 */
function encodeInto (data, destination, options) {
  options = Object.assign({}, defaultEncodeOptions, options)

  // Use direct encode path when possible
  if (canDirectEncode(options)) {
    const writer = new U8Bl(destination)
    directEncode(writer, data, options, undefined)
    return { written: writer.toBytes().length }
  }

  const result = encodeCustom(data, cborEncoders, options, destination)
  return { written: result.length }
}

export { objectToTokens, encode, encodeCustom, encodeInto, Ref }
// This is an unfortunate replacement for @sindresorhus/is that we need to
// re-implement for performance purposes. In particular the is.observable()
// check is expensive, and unnecessary for our purposes. The values returned
// are compatible with @sindresorhus/is, however.

// Types that reach getObjectType() - excludes types with fast-paths above:
// primitives (typeof), Array (isArray), Uint8Array (instanceof), plain Object (constructor)
const objectTypeNames = [
  'Object', // for Object.create(null) and other non-plain objects
  'RegExp',
  'Date',
  'Error',
  'Map',
  'Set',
  'WeakMap',
  'WeakSet',
  'ArrayBuffer',
  'SharedArrayBuffer',
  'DataView',
  'Promise',
  'URL',
  'HTMLElement',
  'Int8Array',
  'Uint8ClampedArray',
  'Int16Array',
  'Uint16Array',
  'Int32Array',
  'Uint32Array',
  'Float32Array',
  'Float64Array',
  'BigInt64Array',
  'BigUint64Array',
  'Tagged'
]

/**
 * @param {any} value
 * @returns {string}
 */
export function is (value) {
  if (value === null) {
    return 'null'
  }
  if (value === undefined) {
    return 'undefined'
  }
  if (value === true || value === false) {
    return 'boolean'
  }
  const typeOf = typeof value
  if (typeOf === 'string' || typeOf === 'number' || typeOf === 'bigint' || typeOf === 'symbol') {
    return typeOf
  }
  if (typeOf === 'function') {
    return 'Function'
  }
  if (Array.isArray(value)) {
    return 'Array'
  }
  // Also catches Node.js Buffer which extends Uint8Array
  if (value instanceof Uint8Array) {
    return 'Uint8Array'
  }
  // Fast path for plain objects (most common case after primitives/arrays/bytes)
  if (value.constructor === Object) {
    return 'Object'
  }
  const objectType = getObjectType(value)
  if (objectType) {
    return objectType
  }
  return 'Object'
}

/**
 * @param {any} value
 * @returns {string|undefined}
 */
function getObjectType (value) {
  const objectTypeName = Object.prototype.toString.call(value).slice(8, -1)
  if (objectTypeNames.includes(objectTypeName)) {
    return objectTypeName
  }
  return undefined
}
import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import * as negint from './1negint.js'
import * as bytes from './2bytes.js'
import * as string from './3string.js'
import * as array from './4array.js'
import * as map from './5map.js'
import * as tag from './6tag.js'
import * as float from './7float.js'
import { decodeErrPrefix } from './common.js'
import { fromArray } from './byte-utils.js'

/**
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 */
function invalidMinor (data, pos, minor) {
  throw new Error(`${decodeErrPrefix} encountered invalid minor (${minor}) for major ${data[pos] >>> 5}`)
}

/**
 * @param {string} msg
 * @returns {()=>any}
 */
function errorer (msg) {
  return () => { throw new Error(`${decodeErrPrefix} ${msg}`) }
}

/** @type {((data:Uint8Array, pos:number, minor:number, options?:DecodeOptions) => any)[]} */
export const jump = []

// unsigned integer, 0x00..0x17 (0..23)
for (let i = 0; i <= 0x17; i++) {
  jump[i] = invalidMinor // uint.decodeUintCompact, handled by quick[]
}
jump[0x18] = uint.decodeUint8 // unsigned integer, one-byte uint8_t follows
jump[0x19] = uint.decodeUint16 // unsigned integer, two-byte uint16_t follows
jump[0x1a] = uint.decodeUint32 // unsigned integer, four-byte uint32_t follows
jump[0x1b] = uint.decodeUint64 // unsigned integer, eight-byte uint64_t follows
jump[0x1c] = invalidMinor
jump[0x1d] = invalidMinor
jump[0x1e] = invalidMinor
jump[0x1f] = invalidMinor
// negative integer, -1-0x00..-1-0x17 (-1..-24)
for (let i = 0x20; i <= 0x37; i++) {
  jump[i] = invalidMinor // negintDecode, handled by quick[]
}
jump[0x38] = negint.decodeNegint8 // negative integer, -1-n one-byte uint8_t for n follows
jump[0x39] = negint.decodeNegint16 // negative integer, -1-n two-byte uint16_t for n follows
jump[0x3a] = negint.decodeNegint32 // negative integer, -1-n four-byte uint32_t for follows
jump[0x3b] = negint.decodeNegint64 // negative integer, -1-n eight-byte uint64_t for follows
jump[0x3c] = invalidMinor
jump[0x3d] = invalidMinor
jump[0x3e] = invalidMinor
jump[0x3f] = invalidMinor
// byte string, 0x00..0x17 bytes follow
for (let i = 0x40; i <= 0x57; i++) {
  jump[i] = bytes.decodeBytesCompact
}
jump[0x58] = bytes.decodeBytes8 // byte string, one-byte uint8_t for n, and then n bytes follow
jump[0x59] = bytes.decodeBytes16 // byte string, two-byte uint16_t for n, and then n bytes follow
jump[0x5a] = bytes.decodeBytes32 // byte string, four-byte uint32_t for n, and then n bytes follow
jump[0x5b] = bytes.decodeBytes64 // byte string, eight-byte uint64_t for n, and then n bytes follow
jump[0x5c] = invalidMinor
jump[0x5d] = invalidMinor
jump[0x5e] = invalidMinor
jump[0x5f] = errorer('indefinite length bytes/strings are not supported') // byte string, byte strings follow, terminated by "break"
// UTF-8 string 0x00..0x17 bytes follow
for (let i = 0x60; i <= 0x77; i++) {
  jump[i] = string.decodeStringCompact
}
jump[0x78] = string.decodeString8 // UTF-8 string, one-byte uint8_t for n, and then n bytes follow
jump[0x79] = string.decodeString16 // UTF-8 string, two-byte uint16_t for n, and then n bytes follow
jump[0x7a] = string.decodeString32 // UTF-8 string, four-byte uint32_t for n, and then n bytes follow
jump[0x7b] = string.decodeString64 // UTF-8 string, eight-byte uint64_t for n, and then n bytes follow
jump[0x7c] = invalidMinor
jump[0x7d] = invalidMinor
jump[0x7e] = invalidMinor
jump[0x7f] = errorer('indefinite length bytes/strings are not supported') // UTF-8 strings follow, terminated by "break"
// array, 0x00..0x17 data items follow
for (let i = 0x80; i <= 0x97; i++) {
  jump[i] = array.decodeArrayCompact
}
jump[0x98] = array.decodeArray8 // array, one-byte uint8_t for n, and then n data items follow
jump[0x99] = array.decodeArray16 // array, two-byte uint16_t for n, and then n data items follow
jump[0x9a] = array.decodeArray32 // array, four-byte uint32_t for n, and then n data items follow
jump[0x9b] = array.decodeArray64 // array, eight-byte uint64_t for n, and then n data items follow
jump[0x9c] = invalidMinor
jump[0x9d] = invalidMinor
jump[0x9e] = invalidMinor
jump[0x9f] = array.decodeArrayIndefinite // array, data items follow, terminated by "break"
// map, 0x00..0x17 pairs of data items follow
for (let i = 0xa0; i <= 0xb7; i++) {
  jump[i] = map.decodeMapCompact
}
jump[0xb8] = map.decodeMap8 // map, one-byte uint8_t for n, and then n pairs of data items follow
jump[0xb9] = map.decodeMap16 // map, two-byte uint16_t for n, and then n pairs of data items follow
jump[0xba] = map.decodeMap32 // map, four-byte uint32_t for n, and then n pairs of data items follow
jump[0xbb] = map.decodeMap64 // map, eight-byte uint64_t for n, and then n pairs of data items follow
jump[0xbc] = invalidMinor
jump[0xbd] = invalidMinor
jump[0xbe] = invalidMinor
jump[0xbf] = map.decodeMapIndefinite // map, pairs of data items follow, terminated by "break"
// tags
for (let i = 0xc0; i <= 0xd7; i++) {
  jump[i] = tag.decodeTagCompact
}
jump[0xd8] = tag.decodeTag8
jump[0xd9] = tag.decodeTag16
jump[0xda] = tag.decodeTag32
jump[0xdb] = tag.decodeTag64
jump[0xdc] = invalidMinor
jump[0xdd] = invalidMinor
jump[0xde] = invalidMinor
jump[0xdf] = invalidMinor
// 0xe0..0xf3 simple values, unsupported
for (let i = 0xe0; i <= 0xf3; i++) {
  jump[i] = errorer('simple values are not supported')
}
jump[0xf4] = invalidMinor // false, handled by quick[]
jump[0xf5] = invalidMinor // true, handled by quick[]
jump[0xf6] = invalidMinor // null, handled by quick[]
jump[0xf7] = float.decodeUndefined // undefined
jump[0xf8] = errorer('simple values are not supported') // simple value, one byte follows, unsupported
jump[0xf9] = float.decodeFloat16 // half-precision float (two-byte IEEE 754)
jump[0xfa] = float.decodeFloat32 // single-precision float (four-byte IEEE 754)
jump[0xfb] = float.decodeFloat64 // double-precision float (eight-byte IEEE 754)
jump[0xfc] = invalidMinor
jump[0xfd] = invalidMinor
jump[0xfe] = invalidMinor
jump[0xff] = float.decodeBreak // "break" stop code

/** @type {Token[]} */
export const quick = []
// ints <24
for (let i = 0; i < 24; i++) {
  quick[i] = new Token(Type.uint, i, 1)
}
// negints >= -24
for (let i = -1; i >= -24; i--) {
  quick[31 - i] = new Token(Type.negint, i, 1)
}
// empty bytes
quick[0x40] = new Token(Type.bytes, new Uint8Array(0), 1)
// empty string
quick[0x60] = new Token(Type.string, '', 1)
// empty list
quick[0x80] = new Token(Type.array, 0, 1)
// empty map
quick[0xa0] = new Token(Type.map, 0, 1)
// false
quick[0xf4] = new Token(Type.false, false, 1)
// true
quick[0xf5] = new Token(Type.true, true, 1)
// null
quick[0xf6] = new Token(Type.null, null, 1)

/**
 * @param {Token} token
 * @returns {Uint8Array|undefined}
 */
export function quickEncodeToken (token) {
  switch (token.type) {
    case Type.false:
      return fromArray([0xf4])
    case Type.true:
      return fromArray([0xf5])
    case Type.null:
      return fromArray([0xf6])
    case Type.bytes:
      if (!token.value.length) {
        return fromArray([0x40])
      }
      return
    case Type.string:
      if (token.value === '') {
        return fromArray([0x60])
      }
      return
    case Type.array:
      if (token.value === 0) {
        return fromArray([0x80])
      }
      // shouldn't be possible if this were called when there was only one token
      return
    case Type.map:
      if (token.value === 0) {
        return fromArray([0xa0])
      }
      // shouldn't be possible if this were called when there was only one token
      return
    case Type.uint:
      if (token.value < 24) {
        return fromArray([Number(token.value)])
      }
      return
    case Type.negint:
      if (token.value >= -24) {
        return fromArray([31 - Number(token.value)])
      }
  }
}
/**
 * @typedef {import('../interface.js').TagDecodeControl} TagDecodeControl
 * @typedef {(decode: TagDecodeControl) => Tagged} TaggedTagDecoder
 */

/**
 * A wrapper class for representing a CBOR tag with an arbitrary nested value.
 *
 * `Tagged` is a symmetric primitive: it can be passed to `encode()` to emit
 * a CBOR tag header followed by the encoded form of `value`, and it can be
 * returned from a tag decoder (via `Tagged.decoder(tag)` or `Tagged.preserve()`)
 * to round-trip a tag through decode without losing the tag number.
 *
 * Use `Tagged` for one-off tag handling where defining a dedicated
 * `typeEncoders` entry and tag decoder pair would be heavyweight, e.g. when
 * wrapping a structure in a single application-specific tag (COSE, dCBOR
 * envelopes, etc.).
 *
 * For systematic mapping of a JS type to a tag (e.g. CID -> tag 42), prefer
 * a dedicated `typeEncoders` entry instead.
 */
export class Tagged {
  /**
   * @param {number} tag - CBOR tag number, a non-negative integer
   * @param {any} value - The value to be tagged; encoded recursively
   */
  constructor (tag, value) {
    if (typeof tag !== 'number' || !Number.isInteger(tag) || tag < 0) {
      throw new TypeError('Tagged: tag must be a non-negative integer')
    }
    this.tag = tag
    this.value = value
  }

  /**
   * Build a tag decoder for use in `decode()`'s `tags` option that returns the
   * decoded content wrapped in a `Tagged` instance, preserving the tag number
   * for the caller to inspect.
   *
   * @param {number} tag - The CBOR tag number this decoder will be registered for
   * @returns {TaggedTagDecoder}
   *
   * @example
   * import { decode, Tagged } from 'cborg'
   * const value = decode(bytes, { tags: { 16: Tagged.decoder(16) } })
   * // value instanceof Tagged; value.tag === 16
   */
  static decoder (tag) {
    return (decode) => new Tagged(tag, decode())
  }

  /**
   * Build a `tags` option for `decode()` that wraps each listed tag number in
   * a `Tagged` instance, preserving those tags through decode without
   * registering a dedicated decoder per tag.
   *
   * @param {...number} tagNumbers - One or more CBOR tag numbers to preserve
   * @returns {{[tagNumber: number]: TaggedTagDecoder}}
   *
   * @example
   * import { decode, Tagged } from 'cborg'
   * const value = decode(bytes, { tags: Tagged.preserve(16, 96) })
   */
  static preserve (...tagNumbers) {
    /** @type {{[tagNumber: number]: TaggedTagDecoder}} */
    const tags = {}
    for (const tag of tagNumbers) {
      tags[tag] = Tagged.decoder(tag)
    }
    return tags
  }
}

// Symbol.toStringTag so the internal `is()` type detection returns 'Tagged'
// for instances, allowing the default Tagged typeEncoder to match.
Object.defineProperty(Tagged.prototype, Symbol.toStringTag, {
  value: 'Tagged'
})
class Type {
  /**
   * @param {number} major
   * @param {string} name
   * @param {boolean} terminal
   */
  constructor (major, name, terminal) {
    this.major = major
    this.majorEncoded = major << 5
    this.name = name
    this.terminal = terminal
  }

  toString () {
    return `Type[${this.major}].${this.name}`
  }

  /**
   * @param {Type} typ
   * @returns {number}
   */
  compare (typ) {
    return this.major < typ.major ? -1 : this.major > typ.major ? 1 : 0
  }

  /**
   * Check equality between two Type instances. Safe to use across different
   * copies of the Type class (e.g., when bundlers duplicate the module).
   * (major, name) uniquely identifies a Type; terminal is implied by these.
   * @param {Type} a
   * @param {Type} b
   * @returns {boolean}
   */
  static equals (a, b) {
    return a === b || (a.major === b.major && a.name === b.name)
  }
}

// convert to static fields when better supported
Type.uint = new Type(0, 'uint', true)
Type.negint = new Type(1, 'negint', true)
Type.bytes = new Type(2, 'bytes', true)
Type.string = new Type(3, 'string', true)
Type.array = new Type(4, 'array', false)
Type.map = new Type(5, 'map', false)
Type.tag = new Type(6, 'tag', false) // terminal?
Type.float = new Type(7, 'float', true)
Type.false = new Type(7, 'false', true)
Type.true = new Type(7, 'true', true)
Type.null = new Type(7, 'null', true)
Type.undefined = new Type(7, 'undefined', true)
Type.break = new Type(7, 'break', true)
// Type.indefiniteLength = new Type(0, 'indefiniteLength', true)

class Token {
  /**
   * @param {Type} type
   * @param {any} [value]
   * @param {number} [encodedLength]
   */
  constructor (type, value, encodedLength) {
    this.type = type
    this.value = value
    this.encodedLength = encodedLength
    /** @type {Uint8Array|undefined} */
    this.encodedBytes = undefined
    /** @type {Uint8Array|undefined} */
    this.byteValue = undefined
  }

  toString () {
    return `Token[${this.type}].${this.value}`
  }
}

export { Type, Token }
{
  "name": "cborg",
  "version": "5.1.6",
  "description": "Fast CBOR with a focus on strictness",
  "main": "cborg.js",
  "type": "module",
  "bin": {
    "cborg": "lib/bin.js"
  },
  "scripts": {
    "lint": "standard *.js lib/*.js test/*.js",
    "build": "npm run build:types",
    "build:types": "tsc --build",
    "prepublishOnly": "npm run build",
    "test:node": "mocha test/test-*.js",
    "test:node-bin": "mocha test/node-test-bin.js",
    "test:browser": "polendina --cleanup test/test-*.js",
    "test": "npm run lint && npm run build && npm run test:node && npm run test:node-bin && npm run test:browser",
    "test:ci": "npm run test"
  },
  "repository": {
    "type": "git",
    "url": "git@github.com:rvagg/cborg.git"
  },
  "keywords": [
    "cbor"
  ],
  "author": "Rod <rod@vagg.org> (http://r.va.gg/)",
  "license": "Apache-2.0",
  "devDependencies": {
    "@semantic-release/changelog": "^6.0.3",
    "@semantic-release/commit-analyzer": "^13.0.1",
    "@semantic-release/git": "^10.0.1",
    "@semantic-release/github": "^12.0.6",
    "@semantic-release/npm": "^13.1.5",
    "@semantic-release/release-notes-generator": "^14.1.0",
    "@types/chai": "^5.2.3",
    "@types/mocha": "^10.0.10",
    "@types/node": "^26.0.1",
    "chai": "^6.2.2",
    "conventional-changelog-conventionalcommits": "^10.0.0",
    "ipld-garbage": "^5.0.0",
    "mocha": "^11.7.5",
    "polendina": "^3.2.20",
    "semantic-release": "^25.0.3",
    "standard": "^17.1.2",
    "typescript": "^6.0.2"
  },
  "exports": {
    ".": {
      "import": "./cborg.js",
      "types": "./types/cborg.d.ts"
    },
    "./length": {
      "import": "./lib/length.js",
      "types": "./types/lib/length.d.ts"
    },
    "./taglib": {
      "import": "./lib/taglib.js",
      "types": "./types/lib/taglib.d.ts"
    },
    "./json": {
      "import": "./lib/json/json.js",
      "types": "./types/lib/json/json.d.ts"
    },
    "./extended": {
      "import": "./lib/extended/extended.js",
      "types": "./types/lib/extended/extended.d.ts"
    },
    "./interface": {
      "types": "./types/interface.d.ts"
    }
  },
  "types": "cborg.d.ts",
  "typesVersions": {
    "*": {
      "json": [
        "types/lib/json/json.d.ts"
      ],
      "length": [
        "types/lib/length.d.ts"
      ],
      "*": [
        "types/*"
      ],
      "types/*": [
        "types/*"
      ]
    }
  },
  "release": {
    "branches": [
      "master"
    ],
    "plugins": [
      [
        "@semantic-release/commit-analyzer",
        {
          "preset": "conventionalcommits",
          "releaseRules": [
            {
              "breaking": true,
              "release": "major"
            },
            {
              "revert": true,
              "release": "patch"
            },
            {
              "type": "feat",
              "release": "minor"
            },
            {
              "type": "fix",
              "release": "patch"
            },
            {
              "type": "chore",
              "release": "patch"
            },
            {
              "type": "docs",
              "release": "patch"
            },
            {
              "type": "test",
              "release": "patch"
            },
            {
              "scope": "no-release",
              "release": false
            }
          ]
        }
      ],
      [
        "@semantic-release/release-notes-generator",
        {
          "preset": "conventionalcommits",
          "presetConfig": {
            "types": [
              {
                "type": "feat",
                "section": "Features"
              },
              {
                "type": "fix",
                "section": "Bug Fixes"
              },
              {
                "type": "chore",
                "section": "Trivial Changes"
              },
              {
                "type": "docs",
                "section": "Trivial Changes"
              },
              {
                "type": "test",
                "section": "Tests"
              }
            ]
          }
        }
      ],
      "@semantic-release/changelog",
      "@semantic-release/npm",
      "@semantic-release/github",
      "@semantic-release/git"
    ]
  }
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const b4a = require('b4a')

// https://en.wikipedia.org/wiki/Merkle_tree#Second_preimage_attack
const LEAF_TYPE = b4a.from([0])
const PARENT_TYPE = b4a.from([1])
const ROOT_TYPE = b4a.from([2])

const HYPERCORE = b4a.from('hypercore')

exports.keyPair = function (seed) {
  // key pairs might stay around for a while, so better not to use a default slab to avoid retaining it completely
  const slab = b4a.allocUnsafeSlow(
    sodium.crypto_sign_PUBLICKEYBYTES + sodium.crypto_sign_SECRETKEYBYTES
  )
  const publicKey = slab.subarray(0, sodium.crypto_sign_PUBLICKEYBYTES)
  const secretKey = slab.subarray(sodium.crypto_sign_PUBLICKEYBYTES)

  if (seed) sodium.crypto_sign_seed_keypair(publicKey, secretKey, seed)
  else sodium.crypto_sign_keypair(publicKey, secretKey)

  return {
    publicKey,
    secretKey
  }
}

exports.validateKeyPair = function (keyPair) {
  const pk = b4a.allocUnsafe(sodium.crypto_sign_PUBLICKEYBYTES)
  sodium.crypto_sign_ed25519_sk_to_pk(pk, keyPair.secretKey)
  return b4a.equals(pk, keyPair.publicKey)
}

exports.sign = function (message, secretKey) {
  // Dedicated slab for the signature, to avoid retaining unneeded mem and for security
  const signature = b4a.allocUnsafeSlow(sodium.crypto_sign_BYTES)
  sodium.crypto_sign_detached(signature, message, secretKey)
  return signature
}

exports.verify = function (message, signature, publicKey) {
  if (signature.byteLength !== sodium.crypto_sign_BYTES) return false
  if (publicKey.byteLength !== sodium.crypto_sign_PUBLICKEYBYTES) return false
  return sodium.crypto_sign_verify_detached(signature, message, publicKey)
}

exports.encrypt = function (message, publicKey) {
  const ciphertext = b4a.alloc(message.byteLength + sodium.crypto_box_SEALBYTES)
  sodium.crypto_box_seal(ciphertext, message, publicKey)
  return ciphertext
}

exports.decrypt = function (ciphertext, keyPair) {
  if (ciphertext.byteLength < sodium.crypto_box_SEALBYTES) return null

  const plaintext = b4a.alloc(ciphertext.byteLength - sodium.crypto_box_SEALBYTES)

  if (!sodium.crypto_box_seal_open(plaintext, ciphertext, keyPair.publicKey, keyPair.secretKey)) {
    return null
  }

  return plaintext
}

exports.encryptionKeyPair = function (seed) {
  const publicKey = b4a.alloc(sodium.crypto_box_PUBLICKEYBYTES)
  const secretKey = b4a.alloc(sodium.crypto_box_SECRETKEYBYTES)

  if (seed) {
    sodium.crypto_box_seed_keypair(publicKey, secretKey, seed)
  } else {
    sodium.crypto_box_keypair(publicKey, secretKey)
  }

  return {
    publicKey,
    secretKey
  }
}

exports.data = function (data) {
  const out = b4a.allocUnsafe(32)

  sodium.crypto_generichash_batch(out, [LEAF_TYPE, c.encode(c.uint64, data.byteLength), data])

  return out
}

exports.parent = function (a, b) {
  if (a.index > b.index) {
    const tmp = a
    a = b
    b = tmp
  }

  const out = b4a.allocUnsafe(32)

  sodium.crypto_generichash_batch(out, [
    PARENT_TYPE,
    c.encode(c.uint64, a.size + b.size),
    a.hash,
    b.hash
  ])

  return out
}

exports.tree = function (roots, out) {
  const buffers = new Array(3 * roots.length + 1)
  let j = 0

  buffers[j++] = ROOT_TYPE

  for (let i = 0; i < roots.length; i++) {
    const r = roots[i]
    buffers[j++] = r.hash
    buffers[j++] = c.encode(c.uint64, r.index)
    buffers[j++] = c.encode(c.uint64, r.size)
  }

  if (!out) out = b4a.allocUnsafe(32)
  sodium.crypto_generichash_batch(out, buffers)
  return out
}

exports.hash = function (data, out) {
  if (!out) out = b4a.allocUnsafe(32)
  if (!Array.isArray(data)) data = [data]

  sodium.crypto_generichash_batch(out, data)

  return out
}

exports.randomBytes = function (n) {
  const buf = b4a.allocUnsafe(n)
  sodium.randombytes_buf(buf)
  return buf
}

exports.discoveryKey = function (key) {
  if (!key || key.byteLength !== 32) throw new Error('Must pass a 32 byte buffer')
  // Discovery keys might stay around for a while, so better not to use slab memory (for better gc)
  const digest = b4a.allocUnsafeSlow(32)
  sodium.crypto_generichash(digest, HYPERCORE, key)
  return digest
}

if (sodium.sodium_free) {
  exports.free = function (secureBuf) {
    if (secureBuf.secure) sodium.sodium_free(secureBuf)
  }
} else {
  exports.free = function () {}
}

exports.namespace = function (name, count) {
  const ids = typeof count === 'number' ? range(count) : count

  // Namespaces are long-lived, so better to use a dedicated slab
  const buf = b4a.allocUnsafeSlow(32 * ids.length)

  const list = new Array(ids.length)

  // ns is ephemeral, so default slab
  const ns = b4a.allocUnsafe(33)
  sodium.crypto_generichash(ns.subarray(0, 32), typeof name === 'string' ? b4a.from(name) : name)

  for (let i = 0; i < list.length; i++) {
    list[i] = buf.subarray(32 * i, 32 * i + 32)
    ns[32] = ids[i]
    sodium.crypto_generichash(list[i], ns)
  }

  return list
}

function range(count) {
  const arr = new Array(count)
  for (let i = 0; i < count; i++) arr[i] = i
  return arr
}
{
  "name": "hypercore-crypto",
  "version": "3.7.0",
  "description": "The crypto primitives used in hypercore, extracted into a separate module",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.6.6",
    "compact-encoding": "^3.0.0",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "brittle": "^3.5.0",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/hypercore-crypto.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/hypercore-crypto/issues"
  },
  "homepage": "https://github.com/mafintosh/hypercore-crypto"
}
import { coerce } from '../bytes.js';
import basex from '../vendor/base-x.js';
/**
 * Class represents both BaseEncoder and MultibaseEncoder meaning it
 * can be used to encode to multibase or base encode without multibase
 * prefix.
 */
class Encoder {
    name;
    prefix;
    baseEncode;
    constructor(name, prefix, baseEncode) {
        this.name = name;
        this.prefix = prefix;
        this.baseEncode = baseEncode;
    }
    encode(bytes) {
        if (bytes instanceof Uint8Array) {
            return `${this.prefix}${this.baseEncode(bytes)}`;
        }
        else {
            throw Error('Unknown type, must be binary type');
        }
    }
}
/**
 * Class represents both BaseDecoder and MultibaseDecoder so it could be used
 * to decode multibases (with matching prefix) or just base decode strings
 * with corresponding base encoding.
 */
class Decoder {
    name;
    prefix;
    baseDecode;
    prefixCodePoint;
    constructor(name, prefix, baseDecode) {
        this.name = name;
        this.prefix = prefix;
        const prefixCodePoint = prefix.codePointAt(0);
        /* c8 ignore next 3 */
        if (prefixCodePoint === undefined) {
            throw new Error('Invalid prefix character');
        }
        this.prefixCodePoint = prefixCodePoint;
        this.baseDecode = baseDecode;
    }
    decode(text) {
        if (typeof text === 'string') {
            if (text.codePointAt(0) !== this.prefixCodePoint) {
                throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);
            }
            return this.baseDecode(text.slice(this.prefix.length));
        }
        else {
            throw Error('Can only multibase decode strings');
        }
    }
    or(decoder) {
        return or(this, decoder);
    }
}
class ComposedDecoder {
    decoders;
    constructor(decoders) {
        this.decoders = decoders;
    }
    or(decoder) {
        return or(this, decoder);
    }
    decode(input) {
        const prefix = input[0];
        const decoder = this.decoders[prefix];
        if (decoder != null) {
            return decoder.decode(input);
        }
        else {
            throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);
        }
    }
}
export function or(left, right) {
    return new ComposedDecoder({
        ...(left.decoders ?? { [left.prefix]: left }),
        ...(right.decoders ?? { [right.prefix]: right })
    });
}
export class Codec {
    name;
    prefix;
    baseEncode;
    baseDecode;
    encoder;
    decoder;
    constructor(name, prefix, baseEncode, baseDecode) {
        this.name = name;
        this.prefix = prefix;
        this.baseEncode = baseEncode;
        this.baseDecode = baseDecode;
        this.encoder = new Encoder(name, prefix, baseEncode);
        this.decoder = new Decoder(name, prefix, baseDecode);
    }
    encode(input) {
        return this.encoder.encode(input);
    }
    decode(input) {
        return this.decoder.decode(input);
    }
}
export function from({ name, prefix, encode, decode }) {
    return new Codec(name, prefix, encode, decode);
}
export function baseX({ name, prefix, alphabet }) {
    const { encode, decode } = basex(alphabet, name);
    return from({
        prefix,
        name,
        encode,
        decode: (text) => coerce(decode(text))
    });
}
function decode(string, alphabetIdx, bitsPerChar, name) {
    // Count the padding bytes:
    let end = string.length;
    while (string[end - 1] === '=') {
        --end;
    }
    // Allocate the output:
    const out = new Uint8Array((end * bitsPerChar / 8) | 0);
    // Parse the data:
    let bits = 0; // Number of bits currently in the buffer
    let buffer = 0; // Bits waiting to be written out, MSB first
    let written = 0; // Next byte to write
    for (let i = 0; i < end; ++i) {
        // Read one character from the string:
        const value = alphabetIdx[string[i]];
        if (value === undefined) {
            throw new SyntaxError(`Non-${name} character`);
        }
        // Append the bits to the buffer:
        buffer = (buffer << bitsPerChar) | value;
        bits += bitsPerChar;
        // Write out some bits if the buffer has a byte's worth:
        if (bits >= 8) {
            bits -= 8;
            out[written++] = 0xff & (buffer >> bits);
        }
    }
    // Verify that we have received just enough bits:
    if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {
        throw new SyntaxError('Unexpected end of data');
    }
    return out;
}
function encode(data, alphabet, bitsPerChar) {
    const pad = alphabet[alphabet.length - 1] === '=';
    const mask = (1 << bitsPerChar) - 1;
    let out = '';
    let bits = 0; // Number of bits currently in the buffer
    let buffer = 0; // Bits waiting to be written out, MSB first
    for (let i = 0; i < data.length; ++i) {
        // Slurp data into the buffer:
        buffer = (buffer << 8) | data[i];
        bits += 8;
        // Write out as much as we can:
        while (bits > bitsPerChar) {
            bits -= bitsPerChar;
            out += alphabet[mask & (buffer >> bits)];
        }
    }
    // Partial character:
    if (bits !== 0) {
        out += alphabet[mask & (buffer << (bitsPerChar - bits))];
    }
    // Add padding characters until we hit a byte boundary:
    if (pad) {
        while (((out.length * bitsPerChar) & 7) !== 0) {
            out += '=';
        }
    }
    return out;
}
function createAlphabetIdx(alphabet) {
    // Build the character lookup table:
    const alphabetIdx = {};
    for (let i = 0; i < alphabet.length; ++i) {
        alphabetIdx[alphabet[i]] = i;
    }
    return alphabetIdx;
}
/**
 * RFC4648 Factory
 */
export function rfc4648({ name, prefix, bitsPerChar, alphabet }) {
    const alphabetIdx = createAlphabetIdx(alphabet);
    return from({
        prefix,
        name,
        encode(input) {
            return encode(input, alphabet, bitsPerChar);
        },
        decode(input) {
            return decode(input, alphabetIdx, bitsPerChar, name);
        }
    });
}
//# sourceMappingURL=base.js.mapimport { rfc4648 } from './base.js';
export const base32 = rfc4648({
    prefix: 'b',
    name: 'base32',
    alphabet: 'abcdefghijklmnopqrstuvwxyz234567',
    bitsPerChar: 5
});
export const base32upper = rfc4648({
    prefix: 'B',
    name: 'base32upper',
    alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',
    bitsPerChar: 5
});
export const base32pad = rfc4648({
    prefix: 'c',
    name: 'base32pad',
    alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',
    bitsPerChar: 5
});
export const base32padupper = rfc4648({
    prefix: 'C',
    name: 'base32padupper',
    alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',
    bitsPerChar: 5
});
export const base32hex = rfc4648({
    prefix: 'v',
    name: 'base32hex',
    alphabet: '0123456789abcdefghijklmnopqrstuv',
    bitsPerChar: 5
});
export const base32hexupper = rfc4648({
    prefix: 'V',
    name: 'base32hexupper',
    alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',
    bitsPerChar: 5
});
export const base32hexpad = rfc4648({
    prefix: 't',
    name: 'base32hexpad',
    alphabet: '0123456789abcdefghijklmnopqrstuv=',
    bitsPerChar: 5
});
export const base32hexpadupper = rfc4648({
    prefix: 'T',
    name: 'base32hexpadupper',
    alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',
    bitsPerChar: 5
});
export const base32z = rfc4648({
    prefix: 'h',
    name: 'base32z',
    alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',
    bitsPerChar: 5
});
//# sourceMappingURL=base32.js.mapimport { baseX } from './base.js';
export const base36 = baseX({
    prefix: 'k',
    name: 'base36',
    alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'
});
export const base36upper = baseX({
    prefix: 'K',
    name: 'base36upper',
    alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
});
//# sourceMappingURL=base36.js.mapimport { baseX } from './base.js';
export const base58btc = baseX({
    name: 'base58btc',
    prefix: 'z',
    alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
});
export const base58flickr = baseX({
    name: 'base58flickr',
    prefix: 'Z',
    alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'
});
//# sourceMappingURL=base58.js.mapimport { rfc4648 } from './base.js';
export const base64 = rfc4648({
    prefix: 'm',
    name: 'base64',
    alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',
    bitsPerChar: 6
});
export const base64pad = rfc4648({
    prefix: 'M',
    name: 'base64pad',
    alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',
    bitsPerChar: 6
});
export const base64url = rfc4648({
    prefix: 'u',
    name: 'base64url',
    alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',
    bitsPerChar: 6
});
export const base64urlpad = rfc4648({
    prefix: 'U',
    name: 'base64urlpad',
    alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',
    bitsPerChar: 6
});
//# sourceMappingURL=base64.js.mapexport const empty = new Uint8Array(0);
export function toHex(d) {
    return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '');
}
export function fromHex(hex) {
    const hexes = hex.match(/../g);
    return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty;
}
export function equals(aa, bb) {
    if (aa === bb) {
        return true;
    }
    if (aa.byteLength !== bb.byteLength) {
        return false;
    }
    for (let ii = 0; ii < aa.byteLength; ii++) {
        if (aa[ii] !== bb[ii]) {
            return false;
        }
    }
    return true;
}
export function coerce(o) {
    if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') {
        return o;
    }
    if (o instanceof ArrayBuffer) {
        return new Uint8Array(o);
    }
    if (ArrayBuffer.isView(o)) {
        return new Uint8Array(o.buffer, o.byteOffset, o.byteLength);
    }
    throw new Error('Unknown type, must be binary type');
}
export function isBinary(o) {
    return o instanceof ArrayBuffer || ArrayBuffer.isView(o);
}
export function fromString(str) {
    return new TextEncoder().encode(str);
}
export function toString(b) {
    return new TextDecoder().decode(b);
}
//# sourceMappingURL=bytes.js.mapimport { base32 } from './bases/base32.js';
import { base36 } from './bases/base36.js';
import { base58btc } from './bases/base58.js';
import { coerce } from './bytes.js';
import * as Digest from './hashes/digest.js';
import * as varint from './varint.js';
// This way TS will also expose all the types from module
export * from './link/interface.js';
export function format(link, base) {
    const { bytes, version } = link;
    switch (version) {
        case 0:
            return toStringV0(bytes, baseCache(link), base ?? base58btc.encoder);
        default:
            return toStringV1(bytes, baseCache(link), (base ?? base32.encoder));
    }
}
export function toJSON(link) {
    return {
        '/': format(link)
    };
}
export function fromJSON(json) {
    return CID.parse(json['/']);
}
const cache = new WeakMap();
function baseCache(cid) {
    const baseCache = cache.get(cid);
    if (baseCache == null) {
        const baseCache = new Map();
        cache.set(cid, baseCache);
        return baseCache;
    }
    return baseCache;
}
export class CID {
    code;
    version;
    multihash;
    bytes;
    '/';
    /**
     * @param version - Version of the CID
     * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
     * @param multihash - (Multi)hash of the of the content.
     */
    constructor(version, code, multihash, bytes) {
        this.code = code;
        this.version = version;
        this.multihash = multihash;
        this.bytes = bytes;
        // flag to serializers that this is a CID and
        // should be treated specially
        this['/'] = bytes;
    }
    /**
     * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`
     * please either use `CID.asCID(cid)` or switch to new signalling mechanism
     *
     * @deprecated
     */
    get asCID() {
        return this;
    }
    // ArrayBufferView
    get byteOffset() {
        return this.bytes.byteOffset;
    }
    // ArrayBufferView
    get byteLength() {
        return this.bytes.byteLength;
    }
    toV0() {
        switch (this.version) {
            case 0: {
                return this;
            }
            case 1: {
                const { code, multihash } = this;
                if (code !== DAG_PB_CODE) {
                    throw new Error('Cannot convert a non dag-pb CID to CIDv0');
                }
                // sha2-256
                if (multihash.code !== SHA_256_CODE) {
                    throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0');
                }
                return (CID.createV0(multihash));
            }
            default: {
                throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);
            }
        }
    }
    toV1() {
        switch (this.version) {
            case 0: {
                const { code, digest } = this.multihash;
                const multihash = Digest.create(code, digest);
                return (CID.createV1(this.code, multihash));
            }
            case 1: {
                return this;
            }
            default: {
                throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);
            }
        }
    }
    equals(other) {
        return CID.equals(this, other);
    }
    static equals(self, other) {
        const unknown = other;
        return (unknown != null &&
            self.code === unknown.code &&
            self.version === unknown.version &&
            Digest.equals(self.multihash, unknown.multihash));
    }
    toString(base) {
        return format(this, base);
    }
    toJSON() {
        return { '/': format(this) };
    }
    link() {
        return this;
    }
    [Symbol.toStringTag] = 'CID';
    // Legacy
    [Symbol.for('nodejs.util.inspect.custom')]() {
        return `CID(${this.toString()})`;
    }
    /**
     * Takes any input `value` and returns a `CID` instance if it was
     * a `CID` otherwise returns `null`. If `value` is instanceof `CID`
     * it will return value back. If `value` is not instance of this CID
     * class, but is compatible CID it will return new instance of this
     * `CID` class. Otherwise returns null.
     *
     * This allows two different incompatible versions of CID library to
     * co-exist and interop as long as binary interface is compatible.
     */
    static asCID(input) {
        if (input == null) {
            return null;
        }
        const value = input;
        if (value instanceof CID) {
            // If value is instance of CID then we're all set.
            return value;
        }
        else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {
            // If value isn't instance of this CID class but `this.asCID === this` or
            // `value['/'] === value.bytes` is true it is CID instance coming from a
            // different implementation (diff version or duplicate). In that case we
            // rebase it to this `CID` implementation so caller is guaranteed to get
            // instance with expected API.
            const { version, code, multihash, bytes } = value;
            return new CID(version, code, multihash, bytes ?? encodeCID(version, code, multihash.bytes));
        }
        else if (value[cidSymbol] === true) {
            // If value is a CID from older implementation that used to be tagged via
            // symbol we still rebase it to the this `CID` implementation by
            // delegating that to a constructor.
            const { version, multihash, code } = value;
            const digest = Digest.decode(multihash);
            return CID.create(version, code, digest);
        }
        else {
            // Otherwise value is not a CID (or an incompatible version of it) in
            // which case we return `null`.
            return null;
        }
    }
    /**
     * @param version - Version of the CID
     * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
     * @param digest - (Multi)hash of the of the content.
     */
    static create(version, code, digest) {
        if (typeof code !== 'number') {
            throw new Error('String codecs are no longer supported');
        }
        if (!(digest.bytes instanceof Uint8Array)) {
            throw new Error('Invalid digest');
        }
        switch (version) {
            case 0: {
                if (code !== DAG_PB_CODE) {
                    throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);
                }
                else {
                    return new CID(version, code, digest, digest.bytes);
                }
            }
            case 1: {
                const bytes = encodeCID(version, code, digest.bytes);
                return new CID(version, code, digest, bytes);
            }
            default: {
                throw new Error('Invalid version');
            }
        }
    }
    /**
     * Simplified version of `create` for CIDv0.
     */
    static createV0(digest) {
        return CID.create(0, DAG_PB_CODE, digest);
    }
    /**
     * Simplified version of `create` for CIDv1.
     *
     * @param code - Content encoding format code.
     * @param digest - Multihash of the content.
     */
    static createV1(code, digest) {
        return CID.create(1, code, digest);
    }
    /**
     * Decoded a CID from its binary representation. The byte array must contain
     * only the CID with no additional bytes.
     *
     * An error will be thrown if the bytes provided do not contain a valid
     * binary representation of a CID.
     */
    static decode(bytes) {
        const [cid, remainder] = CID.decodeFirst(bytes);
        if (remainder.length !== 0) {
            throw new Error('Incorrect length');
        }
        return cid;
    }
    /**
     * Decoded a CID from its binary representation at the beginning of a byte
     * array.
     *
     * Returns an array with the first element containing the CID and the second
     * element containing the remainder of the original byte array. The remainder
     * will be a zero-length byte array if the provided bytes only contained a
     * binary CID representation.
     */
    static decodeFirst(bytes) {
        const specs = CID.inspectBytes(bytes);
        const prefixSize = specs.size - specs.multihashSize;
        const multihashBytes = coerce(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));
        if (multihashBytes.byteLength !== specs.multihashSize) {
            throw new Error('Incorrect length');
        }
        const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);
        const digest = new Digest.Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);
        const cid = specs.version === 0
            ? CID.createV0(digest)
            : CID.createV1(specs.codec, digest);
        return [cid, bytes.subarray(specs.size)];
    }
    /**
     * Inspect the initial bytes of a CID to determine its properties.
     *
     * Involves decoding up to 4 varints. Typically this will require only 4 to 6
     * bytes but for larger multicodec code values and larger multihash digest
     * lengths these varints can be quite large. It is recommended that at least
     * 10 bytes be made available in the `initialBytes` argument for a complete
     * inspection.
     */
    static inspectBytes(initialBytes) {
        let offset = 0;
        const next = () => {
            const [i, length] = varint.decode(initialBytes.subarray(offset));
            offset += length;
            return i;
        };
        let version = next();
        let codec = DAG_PB_CODE;
        if (version === 18) {
            // CIDv0
            version = 0;
            offset = 0;
        }
        else {
            codec = next();
        }
        if (version !== 0 && version !== 1) {
            throw new RangeError(`Invalid CID version ${version}`);
        }
        const prefixSize = offset;
        const multihashCode = next(); // multihash code
        const digestSize = next(); // multihash length
        const size = offset + digestSize;
        const multihashSize = size - prefixSize;
        return { version, codec, multihashCode, digestSize, multihashSize, size };
    }
    /**
     * Takes cid in a string representation and creates an instance. If `base`
     * decoder is not provided will use a default from the configuration. It will
     * throw an error if encoding of the CID is not compatible with supplied (or
     * a default decoder).
     */
    static parse(source, base) {
        const [prefix, bytes] = parseCIDtoBytes(source, base);
        const cid = CID.decode(bytes);
        if (cid.version === 0 && source[0] !== 'Q') {
            throw Error('Version 0 CID string must not include multibase prefix');
        }
        // Cache string representation to avoid computing it on `this.toString()`
        baseCache(cid).set(prefix, source);
        return cid;
    }
}
function parseCIDtoBytes(source, base) {
    switch (source[0]) {
        // CIDv0 is parsed differently
        case 'Q': {
            const decoder = base ?? base58btc;
            return [
                base58btc.prefix,
                decoder.decode(`${base58btc.prefix}${source}`)
            ];
        }
        case base58btc.prefix: {
            const decoder = base ?? base58btc;
            return [base58btc.prefix, decoder.decode(source)];
        }
        case base32.prefix: {
            const decoder = base ?? base32;
            return [base32.prefix, decoder.decode(source)];
        }
        case base36.prefix: {
            const decoder = base ?? base36;
            return [base36.prefix, decoder.decode(source)];
        }
        default: {
            if (base == null) {
                throw Error('To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided');
            }
            return [source[0], base.decode(source)];
        }
    }
}
function toStringV0(bytes, cache, base) {
    const { prefix } = base;
    if (prefix !== base58btc.prefix) {
        throw Error(`Cannot string encode V0 in ${base.name} encoding`);
    }
    const cid = cache.get(prefix);
    if (cid == null) {
        const cid = base.encode(bytes).slice(1);
        cache.set(prefix, cid);
        return cid;
    }
    else {
        return cid;
    }
}
function toStringV1(bytes, cache, base) {
    const { prefix } = base;
    const cid = cache.get(prefix);
    if (cid == null) {
        const cid = base.encode(bytes);
        cache.set(prefix, cid);
        return cid;
    }
    else {
        return cid;
    }
}
const DAG_PB_CODE = 0x70;
const SHA_256_CODE = 0x12;
function encodeCID(version, code, multihash) {
    const codeOffset = varint.encodingLength(version);
    const hashOffset = codeOffset + varint.encodingLength(code);
    const bytes = new Uint8Array(hashOffset + multihash.byteLength);
    varint.encodeTo(version, bytes, 0);
    varint.encodeTo(code, bytes, codeOffset);
    bytes.set(multihash, hashOffset);
    return bytes;
}
const cidSymbol = Symbol.for('@ipld/js-cid/CID');
//# sourceMappingURL=cid.js.mapimport { coerce, equals as equalBytes } from '../bytes.js';
import * as varint from '../varint.js';
/**
 * Creates a multihash digest.
 */
export function create(code, digest) {
    const size = digest.byteLength;
    const sizeOffset = varint.encodingLength(code);
    const digestOffset = sizeOffset + varint.encodingLength(size);
    const bytes = new Uint8Array(digestOffset + size);
    varint.encodeTo(code, bytes, 0);
    varint.encodeTo(size, bytes, sizeOffset);
    bytes.set(digest, digestOffset);
    return new Digest(code, size, digest, bytes);
}
/**
 * Turns bytes representation of multihash digest into an instance.
 */
export function decode(multihash) {
    const bytes = coerce(multihash);
    const [code, sizeOffset] = varint.decode(bytes);
    const [size, digestOffset] = varint.decode(bytes.subarray(sizeOffset));
    const digest = bytes.subarray(sizeOffset + digestOffset);
    if (digest.byteLength !== size) {
        throw new Error('Incorrect length');
    }
    return new Digest(code, size, digest, bytes);
}
export function equals(a, b) {
    if (a === b) {
        return true;
    }
    else {
        const data = b;
        return (a.code === data.code &&
            a.size === data.size &&
            data.bytes instanceof Uint8Array &&
            equalBytes(a.bytes, data.bytes));
    }
}
/**
 * Represents a multihash digest which carries information about the
 * hashing algorithm and an actual hash digest.
 */
export class Digest {
    code;
    size;
    digest;
    bytes;
    /**
     * Creates a multihash digest.
     */
    constructor(code, size, digest, bytes) {
        this.code = code;
        this.size = size;
        this.digest = digest;
        this.bytes = bytes;
    }
}
/**
 * Used to check that the passed multihash has the passed code
 */
export function hasCode(digest, code) {
    return digest.code === code;
}
//# sourceMappingURL=digest.js.mapexport {};
//# sourceMappingURL=interface.js.mapimport varint from './vendor/varint.js';
export function decode(data, offset = 0) {
    const code = varint.decode(data, offset);
    return [code, varint.decode.bytes];
}
export function encodeTo(int, target, offset = 0) {
    varint.encode(int, target, offset);
    return target;
}
export function encodingLength(int) {
    return varint.encodingLength(int);
}
//# sourceMappingURL=varint.js.map/* eslint-disable */
// base-x encoding / decoding
// Copyright (c) 2018 base-x contributors
// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)
// Distributed under the MIT software license, see the accompanying
// file LICENSE or http://www.opensource.org/licenses/mit-license.php.
/**
 * @param {string} ALPHABET
 * @param {any} name
 */
function base(ALPHABET, name) {
    if (ALPHABET.length >= 255) {
        throw new TypeError('Alphabet too long');
    }
    var BASE_MAP = new Uint8Array(256);
    for (var j = 0; j < BASE_MAP.length; j++) {
        BASE_MAP[j] = 255;
    }
    for (var i = 0; i < ALPHABET.length; i++) {
        var x = ALPHABET.charAt(i);
        var xc = x.charCodeAt(0);
        if (BASE_MAP[xc] !== 255) {
            throw new TypeError(x + ' is ambiguous');
        }
        BASE_MAP[xc] = i;
    }
    var BASE = ALPHABET.length;
    var LEADER = ALPHABET.charAt(0);
    var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up
    var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up
    /**
     * @param {any[] | Iterable<number>} source
     */
    function encode(source) {
        // @ts-ignore
        if (source instanceof Uint8Array)
            ;
        else if (ArrayBuffer.isView(source)) {
            source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
        }
        else if (Array.isArray(source)) {
            source = Uint8Array.from(source);
        }
        if (!(source instanceof Uint8Array)) {
            throw new TypeError('Expected Uint8Array');
        }
        if (source.length === 0) {
            return '';
        }
        // Skip & count leading zeroes.
        var zeroes = 0;
        var length = 0;
        var pbegin = 0;
        var pend = source.length;
        while (pbegin !== pend && source[pbegin] === 0) {
            pbegin++;
            zeroes++;
        }
        // Allocate enough space in big-endian base58 representation.
        var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;
        var b58 = new Uint8Array(size);
        // Process the bytes.
        while (pbegin !== pend) {
            var carry = source[pbegin];
            // Apply "b58 = b58 * 256 + ch".
            var i = 0;
            for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {
                carry += (256 * b58[it1]) >>> 0;
                b58[it1] = (carry % BASE) >>> 0;
                carry = (carry / BASE) >>> 0;
            }
            if (carry !== 0) {
                throw new Error('Non-zero carry');
            }
            length = i;
            pbegin++;
        }
        // Skip leading zeroes in base58 result.
        var it2 = size - length;
        while (it2 !== size && b58[it2] === 0) {
            it2++;
        }
        // Translate the result into a string.
        var str = LEADER.repeat(zeroes);
        for (; it2 < size; ++it2) {
            str += ALPHABET.charAt(b58[it2]);
        }
        return str;
    }
    /**
     * @param {string | string[]} source
     */
    function decodeUnsafe(source) {
        if (typeof source !== 'string') {
            throw new TypeError('Expected String');
        }
        if (source.length === 0) {
            return new Uint8Array();
        }
        var psz = 0;
        // Skip leading spaces.
        if (source[psz] === ' ') {
            return;
        }
        // Skip and count leading '1's.
        var zeroes = 0;
        var length = 0;
        while (source[psz] === LEADER) {
            zeroes++;
            psz++;
        }
        // Allocate enough space in big-endian base256 representation.
        var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.
        var b256 = new Uint8Array(size);
        // Process the characters.
        while (source[psz]) {
            // Decode character
            var carry = BASE_MAP[source.charCodeAt(psz)];
            // Invalid character
            if (carry === 255) {
                return;
            }
            var i = 0;
            for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {
                carry += (BASE * b256[it3]) >>> 0;
                b256[it3] = (carry % 256) >>> 0;
                carry = (carry / 256) >>> 0;
            }
            if (carry !== 0) {
                throw new Error('Non-zero carry');
            }
            length = i;
            psz++;
        }
        // Skip trailing spaces.
        if (source[psz] === ' ') {
            return;
        }
        // Skip leading zeroes in b256.
        var it4 = size - length;
        while (it4 !== size && b256[it4] === 0) {
            it4++;
        }
        var vch = new Uint8Array(zeroes + (size - it4));
        var j = zeroes;
        while (it4 !== size) {
            vch[j++] = b256[it4++];
        }
        return vch;
    }
    /**
     * @param {string | string[]} string
     */
    function decode(string) {
        var buffer = decodeUnsafe(string);
        if (buffer) {
            return buffer;
        }
        throw new Error(`Non-${name} character`);
    }
    return {
        encode: encode,
        decodeUnsafe: decodeUnsafe,
        decode: decode
    };
}
var src = base;
var _brrp__multiformats_scope_baseX = src;
export default _brrp__multiformats_scope_baseX;
//# sourceMappingURL=base-x.js.map/* eslint-disable */
var encode_1 = encode;
var MSB = 0x80, REST = 0x7F, MSBALL = ~REST, INT = Math.pow(2, 31);
/**
 * @param {number} num
 * @param {number[]} out
 * @param {number} offset
 */
function encode(num, out, offset) {
    out = out || [];
    offset = offset || 0;
    var oldOffset = offset;
    while (num >= INT) {
        out[offset++] = (num & 0xFF) | MSB;
        num /= 128;
    }
    while (num & MSBALL) {
        out[offset++] = (num & 0xFF) | MSB;
        num >>>= 7;
    }
    out[offset] = num | 0;
    // @ts-ignore
    encode.bytes = offset - oldOffset + 1;
    return out;
}
var decode = read;
var MSB$1 = 0x80, REST$1 = 0x7F;
/**
 * @param {string | any[]} buf
 * @param {number} offset
 */
function read(buf, offset) {
    var res = 0, offset = offset || 0, shift = 0, counter = offset, b, l = buf.length;
    do {
        if (counter >= l) {
            // @ts-ignore
            read.bytes = 0;
            throw new RangeError('Could not decode varint');
        }
        b = buf[counter++];
        res += shift < 28
            ? (b & REST$1) << shift
            : (b & REST$1) * Math.pow(2, shift);
        shift += 7;
    } while (b >= MSB$1);
    // @ts-ignore
    read.bytes = counter - offset;
    return res;
}
var N1 = Math.pow(2, 7);
var N2 = Math.pow(2, 14);
var N3 = Math.pow(2, 21);
var N4 = Math.pow(2, 28);
var N5 = Math.pow(2, 35);
var N6 = Math.pow(2, 42);
var N7 = Math.pow(2, 49);
var N8 = Math.pow(2, 56);
var N9 = Math.pow(2, 63);
var length = function (/** @type {number} */ value) {
    return (value < N1 ? 1
        : value < N2 ? 2
            : value < N3 ? 3
                : value < N4 ? 4
                    : value < N5 ? 5
                        : value < N6 ? 6
                            : value < N7 ? 7
                                : value < N8 ? 8
                                    : value < N9 ? 9
                                        : 10);
};
var varint = {
    encode: encode_1,
    decode: decode,
    encodingLength: length
};
var _brrp_varint = varint;
export default _brrp_varint;
//# sourceMappingURL=varint.js.map{
  "name": "multiformats",
  "version": "13.4.2",
  "description": "Interface for multihash, multicodec, multibase and CID",
  "author": "Mikeal Rogers <mikeal.rogers@gmail.com> (https://www.mikealrogers.com/)",
  "license": "Apache-2.0 OR MIT",
  "homepage": "https://github.com/multiformats/js-multiformats#readme",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/multiformats/js-multiformats.git"
  },
  "bugs": {
    "url": "https://github.com/multiformats/js-multiformats/issues"
  },
  "publishConfig": {
    "access": "public",
    "provenance": true
  },
  "keywords": [
    "ipfs",
    "ipld",
    "multiformats"
  ],
  "type": "module",
  "types": "./dist/src/index.d.ts",
  "typesVersions": {
    "*": {
      "*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ],
      "src/*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ]
    }
  },
  "files": [
    "src",
    "dist",
    "!dist/test",
    "!**/*.tsbuildinfo"
  ],
  "exports": {
    ".": {
      "types": "./dist/src/index.d.ts",
      "import": "./dist/src/index.js"
    },
    "./bases/base10": {
      "types": "./dist/src/bases/base10.d.ts",
      "import": "./dist/src/bases/base10.js"
    },
    "./bases/base16": {
      "types": "./dist/src/bases/base16.d.ts",
      "import": "./dist/src/bases/base16.js"
    },
    "./bases/base2": {
      "types": "./dist/src/bases/base2.d.ts",
      "import": "./dist/src/bases/base2.js"
    },
    "./bases/base256emoji": {
      "types": "./dist/src/bases/base256emoji.d.ts",
      "import": "./dist/src/bases/base256emoji.js"
    },
    "./bases/base32": {
      "types": "./dist/src/bases/base32.d.ts",
      "import": "./dist/src/bases/base32.js"
    },
    "./bases/base36": {
      "types": "./dist/src/bases/base36.d.ts",
      "import": "./dist/src/bases/base36.js"
    },
    "./bases/base58": {
      "types": "./dist/src/bases/base58.d.ts",
      "import": "./dist/src/bases/base58.js"
    },
    "./bases/base64": {
      "types": "./dist/src/bases/base64.d.ts",
      "import": "./dist/src/bases/base64.js"
    },
    "./bases/base8": {
      "types": "./dist/src/bases/base8.d.ts",
      "import": "./dist/src/bases/base8.js"
    },
    "./bases/identity": {
      "types": "./dist/src/bases/identity.d.ts",
      "import": "./dist/src/bases/identity.js"
    },
    "./bases/interface": {
      "types": "./dist/src/bases/interface.d.ts",
      "import": "./dist/src/bases/interface.js"
    },
    "./basics": {
      "types": "./dist/src/basics.d.ts",
      "import": "./dist/src/basics.js"
    },
    "./block": {
      "types": "./dist/src/block.d.ts",
      "import": "./dist/src/block.js"
    },
    "./block/interface": {
      "types": "./dist/src/block/interface.d.ts",
      "import": "./dist/src/block/interface.js"
    },
    "./bytes": {
      "types": "./dist/src/bytes.d.ts",
      "import": "./dist/src/bytes.js"
    },
    "./cid": {
      "types": "./dist/src/cid.d.ts",
      "import": "./dist/src/cid.js"
    },
    "./codecs/interface": {
      "types": "./dist/src/codecs/interface.d.ts",
      "import": "./dist/src/codecs/interface.js"
    },
    "./codecs/json": {
      "types": "./dist/src/codecs/json.d.ts",
      "import": "./dist/src/codecs/json.js"
    },
    "./codecs/raw": {
      "types": "./dist/src/codecs/raw.d.ts",
      "import": "./dist/src/codecs/raw.js"
    },
    "./hashes/digest": {
      "types": "./dist/src/hashes/digest.d.ts",
      "import": "./dist/src/hashes/digest.js"
    },
    "./hashes/hasher": {
      "types": "./dist/src/hashes/hasher.d.ts",
      "import": "./dist/src/hashes/hasher.js"
    },
    "./hashes/identity": {
      "types": "./dist/src/hashes/identity.d.ts",
      "import": "./dist/src/hashes/identity.js"
    },
    "./hashes/interface": {
      "types": "./dist/src/hashes/interface.d.ts",
      "import": "./dist/src/hashes/interface.js"
    },
    "./hashes/sha1": {
      "types": "./dist/types/src/hashes/sha1.d.ts",
      "browser": "./dist/src/hashes/sha1-browser.js",
      "import": "./dist/src/hashes/sha1.js"
    },
    "./hashes/sha2": {
      "types": "./dist/src/hashes/sha2.d.ts",
      "browser": "./dist/src/hashes/sha2-browser.js",
      "import": "./dist/src/hashes/sha2.js"
    },
    "./interface": {
      "types": "./dist/src/interface.d.ts",
      "import": "./dist/src/interface.js"
    },
    "./link": {
      "types": "./dist/src/link.d.ts",
      "import": "./dist/src/link.js"
    },
    "./link/interface": {
      "types": "./dist/src/link/interface.d.ts",
      "import": "./dist/src/link/interface.js"
    },
    "./traversal": {
      "types": "./dist/src/traversal.d.ts",
      "import": "./dist/src/traversal.js"
    }
  },
  "eslintConfig": {
    "extends": "ipfs",
    "parserOptions": {
      "project": true,
      "sourceType": "module"
    }
  },
  "release": {
    "branches": [
      "master"
    ],
    "plugins": [
      [
        "@semantic-release/commit-analyzer",
        {
          "preset": "conventionalcommits",
          "releaseRules": [
            {
              "breaking": true,
              "release": "major"
            },
            {
              "revert": true,
              "release": "patch"
            },
            {
              "type": "feat",
              "release": "minor"
            },
            {
              "type": "fix",
              "release": "patch"
            },
            {
              "type": "docs",
              "release": "patch"
            },
            {
              "type": "test",
              "release": "patch"
            },
            {
              "type": "deps",
              "release": "patch"
            },
            {
              "scope": "no-release",
              "release": false
            }
          ]
        }
      ],
      [
        "@semantic-release/release-notes-generator",
        {
          "preset": "conventionalcommits",
          "presetConfig": {
            "types": [
              {
                "type": "feat",
                "section": "Features"
              },
              {
                "type": "fix",
                "section": "Bug Fixes"
              },
              {
                "type": "chore",
                "section": "Trivial Changes"
              },
              {
                "type": "docs",
                "section": "Documentation"
              },
              {
                "type": "deps",
                "section": "Dependencies"
              },
              {
                "type": "test",
                "section": "Tests"
              }
            ]
          }
        }
      ],
      "@semantic-release/changelog",
      "@semantic-release/npm",
      "@semantic-release/github",
      [
        "@semantic-release/git",
        {
          "assets": [
            "CHANGELOG.md",
            "package.json"
          ]
        }
      ]
    ]
  },
  "scripts": {
    "clean": "aegir clean",
    "lint": "aegir lint",
    "build": "aegir build",
    "release": "aegir release",
    "docs": "aegir docs",
    "test": "npm run lint && npm run test:node && npm run test:chrome",
    "test:node": "aegir test -t node --cov",
    "test:chrome": "aegir test -t browser --cov",
    "test:chrome-webworker": "aegir test -t webworker",
    "test:firefox": "aegir test -t browser -- --browser firefox",
    "test:firefox-webworker": "aegir test -t webworker -- --browser firefox",
    "test:electron-main": "aegir test -t electron-main"
  },
  "devDependencies": {
    "@stablelib/sha256": "^2.0.0",
    "@stablelib/sha512": "^2.0.0",
    "@types/node": "^25.0.0",
    "aegir": "^47.0.7",
    "buffer": "^6.0.3",
    "cids": "^1.1.9",
    "crypto-hash": "^4.0.0"
  },
  "aegir": {
    "test": {
      "target": [
        "node",
        "browser"
      ]
    }
  },
  "browser": {
    "./hashes/sha1": "./dist/src/hashes/sha1-browser.js",
    "./dist/src/hashes/sha1.js": "./dist/src/hashes/sha1-browser.js",
    "./hashes/sha2": "./dist/src/hashes/sha2-browser.js",
    "./dist/src/hashes/sha2.js": "./dist/src/hashes/sha2-browser.js"
  }
}
module.exports = require.addon.bind(require)
{
  "name": "require-addon",
  "version": "1.2.0",
  "description": "Import native addons across JavaScript runtimes",
  "exports": {
    "./package": "./package.json",
    ".": {
      "bare": "./lib/bare.js",
      "node": "./lib/node.js",
      "default": "./lib/default.js"
    }
  },
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    },
    "url": {
      "bare": "bare-url",
      "default": "url"
    }
  },
  "files": [
    "lib"
  ],
  "scripts": {
    "test": "npm run lint && npm run test:bare && npm run test:node",
    "test:bare": "bare test.js",
    "test:node": "node test.js",
    "lint": "prettier --check .",
    "format": "prettier --write ."
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/require-addon.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/require-addon/issues"
  },
  "homepage": "https://github.com/holepunchto/require-addon#readme",
  "engines": {
    "bare": ">=1.10.0"
  },
  "dependencies": {
    "bare-addon-resolve": "^1.3.0"
  },
  "devDependencies": {
    "bare-bundle": "^1.8.1",
    "bare-bundle-evaluate": "^1.1.0",
    "bare-fs": "^4.0.0",
    "bare-path": "^3.0.0",
    "bare-url": "^2.1.0",
    "brittle": "^3.7.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
require.addon = require('require-addon')
module.exports = require.addon('.', __filename)
const assert = require('assert')
const binding = require('./binding')
const { isNode } = require('which-runtime')

const OPTIONAL = Buffer.from(new ArrayBuffer(0))

module.exports = exports = { ...binding }

// memory

exports.sodium_memzero = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  binding.sodium_memzero(buf)
}

exports.sodium_mlock = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  const res = binding.sodium_mlock(buf)

  if (res !== 0) throw new Error('memory lock failed')
}

exports.sodium_munlock = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  const res = binding.sodium_munlock(buf)

  if (res !== 0) throw new Error('memory unlock failed')
}

exports.sodium_malloc = function (size) {
  assert(size >= 0, 'invalid size')

  const buf = Buffer.from(binding.sodium_malloc(size))
  buf.secure = true
  return buf
}

exports.sodium_free = function (buf) {
  if (!buf || !buf.secure) return

  binding.sodium_free(buf.buffer)
}

exports.sodium_mprotect_noaccess = function (buf) {
  const res = binding.sodium_mprotect_noaccess(buf.buffer)

  if (res !== 0) throw new Error('failed to lock buffer')
}

exports.sodium_mprotect_readonly = function (buf) {
  const res = binding.sodium_mprotect_readonly(buf.buffer)

  if (res !== 0) throw new Error('failed to unlock buffer')
}

exports.sodium_mprotect_readwrite = function (buf) {
  const res = binding.sodium_mprotect_readwrite(buf.buffer)

  if (res !== 0) throw new Error('failed to unlock buffer')
}

// crypto_randombytes

exports.randombytes_buf = function (buffer) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')

  binding.randombytes_buf(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

exports.randombytes_buf_deterministic = function (buffer, seed) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    seed.byteLength === binding.randombytes_SEEDBYTES,
    "seed must be 'randombytes_SEEDBYTES' bytes"
  )

  binding.randombytes_buf_deterministic(
    buffer.buffer,
    buffer.byteOffset,
    buffer.byteLength,

    seed.buffer,
    seed.byteOffset,
    seed.byteLength
  )
}

// sodium_helpers

exports.sodium_memcmp = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  return binding.sodium_memcmp(a, b)
}

exports.sodium_add = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  binding.sodium_add(a, b)
}

exports.sodium_sub = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  binding.sodium_sub(a, b)
}

exports.sodium_compare = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  return binding.sodium_compare(a, b)
}

exports.sodium_is_zero = function (buffer, length) {
  if (length === undefined) length = buffer.byteLength

  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(length >= 0 && length <= buffer.byteLength, 'invalid length')

  return binding.sodium_is_zero(buffer, length)
}

exports.sodium_pad = function (buffer, unpaddedBuflen, blockSize) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(unpaddedBuflen <= buffer.byteLength, 'unpadded length cannot exceed buffer length')
  assert(blockSize <= buffer.byteLength, 'block size cannot exceed buffer length')
  assert(blockSize >= 1, 'block size must be at least 1 byte')
  assert(
    buffer.byteLength >= unpaddedBuflen + (blockSize - (unpaddedBuflen % blockSize)),
    'buf not long enough'
  )

  return binding.sodium_pad(buffer, unpaddedBuflen, blockSize)
}

exports.sodium_unpad = function (buffer, paddedBuflen, blockSize) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(paddedBuflen <= buffer.byteLength, 'unpadded length cannot exceed buffer length')
  assert(blockSize <= buffer.byteLength, 'block size cannot exceed buffer length')
  assert(blockSize >= 1, 'block size must be at least 1 byte')

  return binding.sodium_unpad(buffer, paddedBuflen, blockSize)
}

// crypto_sign

exports.crypto_sign_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )
  assert(
    seed.byteLength === binding.crypto_sign_SEEDBYTES,
    "seed must be 'crypto_sign_SEEDBYTES' bytes"
  )

  const res = binding.crypto_sign_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign = function (sm, m, sk) {
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sm.byteLength === binding.crypto_sign_BYTES + m.byteLength,
    "sm must be 'm.byteLength + crypto_sign_BYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign(sm, m, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_open = function (m, sm, pk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sm.byteLength >= binding.crypto_sign_BYTES,
    "sm must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    m.byteLength === sm.byteLength - binding.crypto_sign_BYTES,
    "m must be 'sm.byteLength - crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_open(m, sm, pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_open = function (m, sm, pk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sm.byteLength >= binding.crypto_sign_BYTES,
    "sm must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    m.byteLength === sm.byteLength - binding.crypto_sign_BYTES,
    "m must be 'sm.byteLength - crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  return binding.crypto_sign_open(m, sm, pk)
}

exports.crypto_sign_detached = function (sig, m, sk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(sig.byteLength === binding.crypto_sign_BYTES, "sig must be 'crypto_sign_BYTES' bytes")
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_detached(sig, m, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_verify_detached = function (sig, m, pk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sig.byteLength >= binding.crypto_sign_BYTES,
    "sig must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  return binding.crypto_sign_verify_detached(
    sig.buffer,
    sig.byteOffset,
    sig.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    pk.buffer,
    pk.byteOffset,
    pk.byteLength
  )
}

exports.crypto_sign_ed25519_sk_to_pk = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_sk_to_pk(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_ed25519_pk_to_curve25519 = function (x25519pk, ed25519pk) {
  assert(ArrayBuffer.isView(x25519pk), 'x25519pk must be a typed array')
  assert(ArrayBuffer.isView(ed25519pk), 'ed25519pk must be a typed array')
  assert(
    x25519pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "x25519pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    ed25519pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "ed25519pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_pk_to_curve25519(x25519pk, ed25519pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_ed25519_sk_to_curve25519 = function (x25519sk, ed25519sk) {
  assert(ArrayBuffer.isView(x25519sk), 'x25519sk must be a typed array')
  assert(ArrayBuffer.isView(ed25519sk), 'ed25519sk must be a typed array')
  assert(
    x25519sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "x25519sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const edLen = ed25519sk.byteLength

  assert(
    edLen === binding.crypto_sign_SECRETKEYBYTES || edLen === binding.crypto_box_SECRETKEYBYTES,
    "ed25519sk must be 'crypto_sign_SECRETKEYBYTES' or 'crypto_sign_SECRETKEYBYTES - crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_sk_to_curve25519(x25519sk, ed25519sk)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_box

exports.crypto_box_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    seed.byteLength === binding.crypto_box_SEEDBYTES,
    "seed must be 'crypto_box_SEEDBYTES' bytes"
  )

  const res = binding.crypto_box_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_easy = function (c, m, n, pk, sk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength === m.byteLength + exports.crypto_box_MACBYTES,
    "c must be 'm.byteLength + crypto_box_MACBYTES' bytes"
  )
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_easy(c, m, n, pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_detached = function (c, mac, m, n, pk, sk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(mac.byteLength === exports.crypto_box_MACBYTES, "mac must be 'crypto_box_MACBYTES' bytes")
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_detached(c, mac, m, n, pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_open_easy = function (m, c, n, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength >= exports.crypto_box_MACBYTES,
    "c must be at least 'crypto_box_MACBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - exports.crypto_box_MACBYTES,
    "m must be 'c.byteLength - crypto_box_MACBYTES' bytes"
  )
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_open_easy(m, c, n, pk, sk)
}

exports.crypto_box_open_detached = function (m, c, mac, n, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(mac.byteLength === exports.crypto_box_MACBYTES, "mac must be 'crypto_box_MACBYTES' bytes")
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_open_detached(m, c, mac, n, pk, sk)
}

exports.crypto_box_seal = function (c, m, pk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    c.byteLength === m.byteLength + exports.crypto_box_SEALBYTES,
    "c must be 'm.byteLength + crypto_box_SEALBYTES' bytes"
  )
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_box_seal(c, m, pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_seal_open = function (m, c, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength >= exports.crypto_box_SEALBYTES,
    "c must be at least 'crypto_box_SEALBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - exports.crypto_box_SEALBYTES,
    "m must be 'c.byteLength - crypto_box_SEALBYTES' bytes"
  )
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_seal_open(
    m.buffer,
    m.byteOffset,
    m.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    pk.buffer,
    pk.byteOffset,
    pk.byteLength,

    sk.buffer,
    sk.byteOffset,
    sk.byteLength
  )
}

// crypto_secretbox

exports.crypto_secretbox_easy = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_secretbox_MACBYTES,
    "c must be 'm.byteLength + crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretbox_easy(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretbox_open_easy = function (m, c, n, k) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    c.byteLength >= binding.crypto_secretbox_MACBYTES,
    "c must be at least 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - binding.crypto_secretbox_MACBYTES,
    "m must be 'c.byteLength - crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  return binding.crypto_secretbox_open_easy(m, c, n, k)
}

exports.crypto_secretbox_detached = function (c, mac, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    mac.byteLength === binding.crypto_secretbox_MACBYTES,
    "mac must be 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretbox_detached(c, mac, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretbox_open_detached = function (m, c, mac, n, k) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(
    mac.byteLength === binding.crypto_secretbox_MACBYTES,
    "mac must be 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  return binding.crypto_secretbox_open_detached(m, c, mac, n, k)
}

// crypto_generichash

exports.crypto_generichash = function (output, input, key) {
  if (!key) key = OPTIONAL

  assert(ArrayBuffer.isView(output), 'output must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    output.byteLength >= binding.crypto_generichash_BYTES_MIN &&
      output.byteLength <= binding.crypto_generichash_BYTES_MAX,
    'output must be between crypto_generichash_BYTES_MIN and crypto_generichash_BYTES_MAX bytes'
  )

  if (key !== OPTIONAL) {
    assert(ArrayBuffer.isView(key), 'key must be a typed array')
    assert(
      key.byteLength >= binding.crypto_generichash_KEYBYTES_MIN &&
        key.byteLength <= binding.crypto_generichash_KEYBYTES_MAX,
      'key must be between crypto_generichash_KEYBYTES_MIN and crypto_generichash_KEYBYTES_MAX bytes'
    )
  }

  const res = binding.crypto_generichash(
    output.buffer,
    output.byteOffset,
    output.byteLength,

    input.buffer,
    input.byteOffset,
    input.byteLength,

    key.buffer,
    key.byteOffset,
    key.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_batch = function (output, batch, key) {
  assert(ArrayBuffer.isView(output), 'output must be a typed array')

  if (isNode || batch.length < 4) {
    const res = binding.crypto_generichash_batch(output, batch, !!key, key || OPTIONAL)
    if (res !== 0) throw new Error('status: ' + res)
  } else {
    const state = Buffer.alloc(binding.crypto_generichash_STATEBYTES)

    exports.crypto_generichash_init(state, key, output.byteLength)

    for (const buf of batch) {
      exports.crypto_generichash_update(state, buf)
    }

    exports.crypto_generichash_final(state, output)
  }
}

exports.crypto_generichash_keygen = function (key) {
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(
    key.byteLength === binding.crypto_generichash_KEYBYTES,
    "key must be 'crypto_generichash_KEYBYTES' bytes"
  )

  const res = binding.crypto_generichash_keygen(key.buffer, key.byteOffset, key.byteLength)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_init = function (state, key, outputLength) {
  if (!key) key = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_init(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    key.buffer,
    key.byteOffset,
    key.byteLength,

    outputLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_update(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    input.buffer,
    input.byteOffset,
    input.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_final = function (state, output) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(output), 'output must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_final(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    output.buffer,
    output.byteOffset,
    output.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

// secretstream

exports.crypto_secretstream_xchacha20poly1305_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  binding.crypto_secretstream_xchacha20poly1305_keygen(k.buffer, k.byteOffset, k.byteLength)
}

exports.crypto_secretstream_xchacha20poly1305_init_push = function (state, header, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(header), 'header must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    header.byteLength === binding.crypto_secretstream_xchacha20poly1305_HEADERBYTES,
    "header must be 'crypto_secretstream_xchacha20poly1305_HEADERBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_init_push(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    header.buffer,
    header.byteOffset,
    header.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretstream_xchacha20poly1305_init_pull = function (state, header, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(header), 'header must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    header.byteLength === binding.crypto_secretstream_xchacha20poly1305_HEADERBYTES,
    "header must be 'crypto_secretstream_xchacha20poly1305_HEADERBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_init_pull(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    header.buffer,
    header.byteOffset,
    header.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretstream_xchacha20poly1305_push = function (state, c, m, ad, tag) {
  if (!ad) ad = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    c.byteLength === m.byteLength + binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "c must be 'm.byteLength + crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_push(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    ad.buffer,
    ad.byteOffset,
    ad.byteLength,

    tag
  )

  if (res < 0) throw new Error('push failed')

  return res
}

exports.crypto_secretstream_xchacha20poly1305_pull = function (state, m, tag, c, ad) {
  if (!ad) ad = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(tag), 'tag must be a typed array')
  assert(tag.byteLength === 1, 'tag must be 1 byte')

  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    c.byteLength >= binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "c must be at least 'crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "m must be 'c.byteLength - crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_pull(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    tag.buffer,
    tag.byteOffset,
    tag.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    ad.buffer,
    ad.byteOffset,
    ad.byteLength
  )

  if (res < 0) throw new Error('pull failed')

  return res
}

exports.crypto_secretstream_xchacha20poly1305_rekey = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )

  binding.crypto_secretstream_xchacha20poly1305_rekey(
    state.buffer,
    state.byteOffset,
    state.byteLength
  )
}

// crypto_stream

exports.crypto_stream = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xor(
    c.buffer,
    c.byteOffset,
    c.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    n.buffer,
    n.byteOffset,
    n.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_auth

exports.crypto_auth = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(out.byteLength === binding.crypto_auth_BYTES, "out must be 'crypto_auth_BYTES' bytes")
  assert(k.byteLength === binding.crypto_auth_KEYBYTES, "k must be 'crypto_auth_KEYBYTES' bytes")

  const res = binding.crypto_auth(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_auth_verify = function (h, input, k) {
  assert(ArrayBuffer.isView(h), 'h must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(h.byteLength === binding.crypto_auth_BYTES, "h must be 'crypto_auth_BYTES' bytes")
  assert(k.byteLength === binding.crypto_auth_KEYBYTES, "k must be 'crypto_auth_KEYBYTES' bytes")

  return binding.crypto_auth_verify(h, input, k)
}

// crypto_onetimeauth

exports.crypto_onetimeauth = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    out.byteLength === binding.crypto_onetimeauth_BYTES,
    "out must be 'crypto_onetimeauth_BYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_init = function (state, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_init(state, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )
  assert(
    out.byteLength === binding.crypto_onetimeauth_BYTES,
    "out must be 'crypto_onetimeauth_BYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_verify = function (h, input, k) {
  assert(ArrayBuffer.isView(h), 'h must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    h.byteLength === binding.crypto_onetimeauth_BYTES,
    "h must be 'crypto_onetimeauth_BYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  return binding.crypto_onetimeauth_verify(h, input, k)
}

// crypto_pwhash

exports.crypto_pwhash = function (out, passwd, salt, opslimit, memlimit, alg) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_BYTES_MIN,
    "out must be at least 'crypto_pwhash_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_BYTES_MAX,
    "out must be at most 'crypto_pwhash_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_SALTBYTES,
    "salt must be 'crypto_pwhash_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )
  assert(alg >= 1 && alg <= 2, 'alg must be either Argon2i 1.3 or Argon2id 1.3')

  const res = binding.crypto_pwhash(out, passwd, salt, opslimit, memlimit, alg)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_async = function (
  out,
  passwd,
  salt,
  opslimit,
  memlimit,
  alg,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_BYTES_MIN,
    "out must be at least 'crypto_pwhash_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_BYTES_MAX,
    "out must be at most 'crypto_pwhash_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_SALTBYTES,
    "salt must be 'crypto_pwhash_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )
  assert(alg >= 1 && alg <= 2, 'alg must be either Argon2i 1.3 or Argon2id 1.3')

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    opslimit,
    memlimit,
    alg,

    done
  )

  return promise
}

exports.crypto_pwhash_str = function (out, passwd, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_STRBYTES,
    "out must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(typeof opslimit === 'number', 'opslimit must be a number')
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(typeof memlimit === 'number', 'memlimit must be a number')
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_str(out, passwd, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_str_async = function (out, passwd, opslimit, memlimit, callback = undefined) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_STRBYTES,
    "out must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(typeof opslimit === 'number', 'opslimit must be a number')
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(typeof memlimit === 'number', 'memlimit must be a number')
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_str_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_str_verify = function (str, passwd) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )

  return binding.crypto_pwhash_str_verify(str, passwd)
}

exports.crypto_pwhash_str_verify_async = function (str, passwd, callback = undefined) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  const [done, promise] = checkStatus(callback, true)

  binding.crypto_pwhash_str_verify_async(
    str.buffer,
    str.byteOffset,
    str.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    done
  )

  return promise
}

exports.crypto_pwhash_str_needs_rehash = function (str, opslimit, memlimit) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  return binding.crypto_pwhash_str_needs_rehash(str, opslimit, memlimit)
}

exports.crypto_pwhash_scryptsalsa208sha256 = function (out, passwd, salt, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MIN,
    "out must be at least 'crypto_pwhash_scryptsalsa208sha256_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MAX,
    "out must be at most 'crypto_pwhash_scryptsalsa208sha256_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_SALTBYTES,
    "salt must be 'crypto_pwhash_scryptsalsa208sha256_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_scryptsalsa208sha256(out, passwd, salt, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_scryptsalsa208sha256_async = function (
  out,
  passwd,
  salt,
  opslimit,
  memlimit,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MIN,
    "out must be at least 'crypto_pwhash_scryptsalsa208sha256_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MAX,
    "out must be at most 'crypto_pwhash_scryptsalsa208sha256_BYTES_MAX' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    salt.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_SALTBYTES,
    "salt must be 'crypto_pwhash_scryptsalsa208sha256_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_scryptsalsa208sha256_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str_async = function (
  out,
  passwd,
  opslimit,
  memlimit,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "out must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_scryptsalsa208sha256_str_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str = function (out, passwd, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "out must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_scryptsalsa208sha256_str(out, passwd, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_scryptsalsa208sha256_str_verify_async = function (
  str,
  passwd,
  callback = undefined
) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  const [done, promise] = checkStatus(callback, true)

  binding.crypto_pwhash_scryptsalsa208sha256_str_verify_async(
    str.buffer,
    str.byteOffset,
    str.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str_verify = function (str, passwd) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  return binding.crypto_pwhash_scryptsalsa208sha256_str_verify(str, passwd)
}

exports.crypto_pwhash_scryptsalsa208sha256_str_needs_rehash = function (str, opslimit, memlimit) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  return binding.crypto_pwhash_scryptsalsa208sha256_str_needs_rehash(str, opslimit, memlimit)
}

// crypto_kx

exports.crypto_kx_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "pk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "sk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    pk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "pk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "sk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    seed.byteLength === binding.crypto_kx_SEEDBYTES,
    "seed must be 'crypto_kx_SEEDBYTES' bytes"
  )

  const res = binding.crypto_kx_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_client_session_keys = function (rx, tx, clientPk, clientSk, serverPk) {
  if (!rx) rx = undefined
  if (!tx) tx = undefined

  assert(rx || tx, 'at least one session key must be specified')

  if (rx) {
    assert(ArrayBuffer.isView(rx), 'rx must be a typed array')
    assert(
      rx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "rx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  if (tx) {
    assert(ArrayBuffer.isView(tx), 'tx must be a typed array')
    assert(
      tx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "tx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  assert(ArrayBuffer.isView(clientPk), 'clientPk must be a typed array')
  assert(ArrayBuffer.isView(clientSk), 'clientSk must be a typed array')
  assert(ArrayBuffer.isView(serverPk), 'serverPk must be a typed array')
  assert(
    clientPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "clientPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    clientSk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "clientSk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    serverPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "serverPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_client_session_keys(rx, tx, clientPk, clientSk, serverPk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_server_session_keys = function (rx, tx, serverPk, serverSk, clientPk) {
  if (!rx) rx = undefined
  if (!tx) tx = undefined

  assert(rx || tx, 'at least one session key must be specified')

  if (rx) {
    assert(ArrayBuffer.isView(rx), 'rx must be a typed array')
    assert(
      rx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "rx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  if (tx) {
    assert(ArrayBuffer.isView(tx), 'tx must be a typed array')
    assert(
      tx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "tx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  assert(ArrayBuffer.isView(serverPk), 'serverPk must be a typed array')
  assert(ArrayBuffer.isView(serverSk), 'serverSk must be a typed array')
  assert(ArrayBuffer.isView(clientPk), 'clientPk must be a typed array')
  assert(
    serverPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "serverPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    serverSk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "serverSk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    clientPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "clientPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_server_session_keys(rx, tx, serverPk, serverSk, clientPk)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_scalarmult

exports.crypto_scalarmult_base = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_BYTES,
    "q must be 'crypto_scalarmult_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_SCALARBYTES,
    "n must be 'crypto_scalarmult_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_base(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_BYTES,
    "q must be 'crypto_scalarmult_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_SCALARBYTES,
    "n must be 'crypto_scalarmult_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_BYTES,
    "p must be 'crypto_scalarmult_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_base = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_base(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519 = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "p must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_is_valid_point = function (p) {
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )

  return binding.crypto_core_ed25519_is_valid_point(p)
}

exports.crypto_core_ed25519_from_uniform = function (p, r) {
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_UNIFORMBYTES,
    "r must be 'crypto_core_ed25519_UNIFORMBYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_from_uniform(p, r)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_base_noclamp = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_base_noclamp(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_noclamp = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "p must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_noclamp(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_core

exports.crypto_core_ed25519_add = function (r, p, q) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_BYTES,
    "r must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_core_ed25519_BYTES,
    "q must be 'crypto_core_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_add(r, p, q)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_sub = function (r, p, q) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_BYTES,
    "r must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_core_ed25519_BYTES,
    "q must be 'crypto_core_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_sub(r, p, q)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_scalar_random = function (r) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "r must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_random(r)
}

exports.crypto_core_ed25519_scalar_reduce = function (r, s) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "r must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_NONREDUCEDSCALARBYTES,
    "s must be 'crypto_core_ed25519_NONREDUCEDSCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_reduce(r, s)
}

exports.crypto_core_ed25519_scalar_invert = function (recip, s) {
  assert(ArrayBuffer.isView(recip), 'recip must be a typed array')
  assert(
    recip.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "recip must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_invert(recip, s)
}

exports.crypto_core_ed25519_scalar_negate = function (neg, s) {
  assert(ArrayBuffer.isView(neg), 'neg must be a typed array')
  assert(
    neg.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "neg must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_negate(neg, s)
}

exports.crypto_core_ed25519_scalar_complement = function (comp, s) {
  assert(ArrayBuffer.isView(comp), 'comp must be a typed array')
  assert(
    comp.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "comp must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_complement(comp, s)
}

exports.crypto_core_ed25519_scalar_add = function (z, x, y) {
  assert(ArrayBuffer.isView(z), 'z must be a typed array')
  assert(
    z.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "z must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(x), 'x must be a typed array')
  assert(
    x.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "x must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(y), 'y must be a typed array')
  assert(
    y.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "y must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_add(z, x, y)
}

exports.crypto_core_ed25519_scalar_sub = function (z, x, y) {
  assert(ArrayBuffer.isView(z), 'z must be a typed array')
  assert(
    z.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "z must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(x), 'x must be a typed array')
  assert(
    x.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "x must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(y), 'y must be a typed array')
  assert(
    y.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "y must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_sub(z, x, y)
}

// crypto_shorthash

exports.crypto_shorthash = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_shorthash_BYTES,
    "out must be 'crypto_shorthash_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_shorthash_KEYBYTES,
    "k must be 'crypto_shorthash_KEYBYTES' bytes"
  )

  const res = binding.crypto_shorthash(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_kdf

exports.crypto_kdf_keygen = function (key) {
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(key.byteLength === binding.crypto_kdf_KEYBYTES, "key must be 'crypto_kdf_KEYBYTES' bytes")

  binding.crypto_kdf_keygen(key)
}

exports.crypto_kdf_derive_from_key = function (subkey, subkeyId, ctx, key) {
  assert(ArrayBuffer.isView(subkey), 'subkey must be a typed array')
  assert(
    subkey.byteLength >= binding.crypto_kdf_BYTES_MIN,
    "subkey must be at least 'crypto_kdf_BYTES_MIN' bytes"
  )
  assert(
    subkey.byteLength <= binding.crypto_kdf_BYTES_MAX,
    "subkey must be at most 'crypto_kdf_BYTES_MAX' bytes"
  )
  assert(ArrayBuffer.isView(ctx), 'ctx must be a typed array')
  assert(
    ctx.byteLength === binding.crypto_kdf_CONTEXTBYTES,
    "ctx must be 'crypto_kdf_CONTEXTBYTES' bytes"
  )
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(key.byteLength === binding.crypto_kdf_KEYBYTES, "key must be 'crypto_kdf_KEYBYTES' bytes")

  const res = binding.crypto_kdf_derive_from_key(subkey, subkeyId, ctx, key)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_hash

exports.crypto_hash = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(out.byteLength === binding.crypto_hash_BYTES, "out must be 'crypto_hash_BYTES' bytes")

  const res = binding.crypto_hash(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256 = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha256_BYTES,
    "out must be 'crypto_hash_sha256_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha256(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_init = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_init(state)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha256_BYTES,
    "out must be 'crypto_hash_sha256_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512 = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha512_BYTES,
    "out must be 'crypto_hash_sha512_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha512(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_init = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_init(state)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha512_BYTES,
    "out must be 'crypto_hash_sha512_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_aead

exports.crypto_aead_xchacha20poly1305_ietf_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  binding.crypto_aead_xchacha20poly1305_ietf_keygen(k)
}

exports.crypto_aead_xchacha20poly1305_ietf_encrypt = function (c, m, ad, nsec, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "c must be 'm.byteLength + crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(c.byteLength <= 0xffffffff, 'c.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_encrypt(c, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_decrypt = function (m, nsec, c, ad, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "m must be 'c.byteLength - crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(m.byteLength <= 0xffffffff, 'm.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_decrypt(m, c, ad, npub, k)

  if (res < 0) throw new Error('could not verify data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_encrypt_detached = function (
  c,
  mac,
  m,
  ad,
  nsec,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_encrypt_detached(c, mac, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_decrypt_detached = function (
  m,
  nsec,
  c,
  mac,
  ad,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_decrypt_detached(m, c, mac, ad, npub, k)

  if (res !== 0) throw new Error('could not verify data')
}

exports.crypto_aead_chacha20poly1305_ietf_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  binding.crypto_aead_chacha20poly1305_ietf_keygen(k)
}

exports.crypto_aead_chacha20poly1305_ietf_encrypt = function (c, m, ad, nsec, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "c must be 'm.byteLength + crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(c.byteLength <= 0xffffffff, 'c.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_encrypt(c, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_decrypt = function (m, nsec, c, ad, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "m must be 'c.byteLength - crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(m.byteLength <= 0xffffffff, 'm.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_decrypt(m, c, ad, npub, k)

  if (res < 0) throw new Error('could not verify data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_encrypt_detached = function (
  c,
  mac,
  m,
  ad,
  nsec,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_encrypt_detached(c, mac, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_decrypt_detached = function (
  m,
  nsec,
  c,
  mac,
  ad,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_decrypt_detached(m, c, mac, ad, npub, k)

  if (res !== 0) throw new Error('could not verify data')
}

// crypto_stream

exports.crypto_stream_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  binding.crypto_stream_xor_wrap_init(state, n, k)
}

exports.crypto_stream_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_xor_wrap_update(state, c, m)
}

exports.crypto_stream_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_xor_wrap_final(state)
}

exports.crypto_stream_chacha20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  binding.crypto_stream_chacha20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_chacha20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_chacha20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_chacha20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_chacha20_xor_wrap_final(state)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  binding.crypto_stream_chacha20_ietf_xor_wrap_init(state, n, k)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_chacha20_ietf_xor_wrap_update(state, c, m)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_chacha20_ietf_xor_wrap_final(state)
}

exports.crypto_stream_xchacha20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  binding.crypto_stream_xchacha20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_xchacha20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_xchacha20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_xchacha20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_xchacha20_xor_wrap_final(state)
}

exports.crypto_stream_salsa20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  binding.crypto_stream_salsa20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_salsa20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_salsa20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_salsa20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_salsa20_xor_wrap_final(state)
}

// experimental

exports.extension_tweak_ed25519_base = function (n, p, ns) {
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.extension_tweak_ed25519_BYTES,
    "p must be 'extension_tweak_ed25519_BYTES' bytes"
  )

  binding.extension_tweak_ed25519_base(n, p, ns)
}

exports.extension_tweak_ed25519_sign_detached = function (sig, m, scalar, pk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(sig.byteLength === binding.crypto_sign_BYTES, "sig must be 'crypto_sign_BYTES' bytes")
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  if (pk) {
    assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
    assert(
      pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
      "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
    )
  }

  const res = binding.extension_tweak_ed25519_sign_detached(sig, m, scalar, pk)

  if (res !== 0) throw new Error('failed to compute signature')
}

exports.extension_tweak_ed25519_sk_to_scalar = function (n, sk) {
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  binding.extension_tweak_ed25519_sk_to_scalar(n, sk)
}

exports.extension_tweak_ed25519_scalar = function (scalarOut, scalar, ns) {
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_scalar(scalarOut, scalar, ns)
}

exports.extension_tweak_ed25519_pk = function (tpk, pk, ns) {
  assert(ArrayBuffer.isView(tpk), 'tpk must be a typed array')
  assert(
    tpk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "tpk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_pk(tpk, pk, ns)

  if (res !== 0) throw new Error('failed to tweak public key')
}

exports.extension_tweak_ed25519_keypair = function (pk, scalarOut, scalarIn, ns) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.extension_tweak_ed25519_BYTES,
    "pk must be 'extension_tweak_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarIn), 'scalarIn must be a typed array')
  assert(
    scalarIn.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarIn must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_keypair(pk, scalarOut, scalarIn, ns)
}

exports.extension_tweak_ed25519_scalar_add = function (scalarOut, scalar, n) {
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_scalar_add(scalarOut, scalar, n)
}

exports.extension_tweak_ed25519_pk_add = function (tpk, pk, p) {
  assert(ArrayBuffer.isView(tpk), 'tpk must be a typed array')
  assert(
    tpk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "tpk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "p must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_pk_add(tpk, pk, p)

  if (res !== 0) throw new Error('failed to add tweak to public key')
}

exports.extension_tweak_ed25519_keypair_add = function (pk, scalarOut, scalarIn, tweak) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.extension_tweak_ed25519_BYTES,
    "pk must be 'extension_tweak_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarIn), 'scalarIn must be a typed array')
  assert(
    scalarIn.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarIn must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(tweak), 'tweak must be a typed array')
  assert(
    tweak.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "tweak must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_keypair_add(pk, scalarOut, scalarIn, tweak)

  if (res !== 0) throw new Error('failed to add tweak to keypair')
}

exports.extension_pbkdf2_sha512_async = function (out, passwd, salt, iter, outlen, callback) {
  assert(
    iter >= binding.extension_pbkdf2_sha512_ITERATIONS_MIN,
    "iter must be at least 'extension_pbkdf2_sha512_ITERATIONS_MIN'"
  )
  assert(
    outlen <= binding.extension_pbkdf2_sha512_BYTES_MAX,
    "outlen must be at most 'extension_pbkdf2_sha512_BYTES_MAX'"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(out.byteLength >= outlen, "out must be at least 'outlen' bytes")
  assert(out.byteLength > 0, 'out must not be empty')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(salt.byteLength > 0, 'salt must not be empty')

  const [done, promise] = checkStatus(callback)

  binding.extension_pbkdf2_sha512_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    iter,
    outlen,

    done
  )

  return promise
}

exports.extension_pbkdf2_sha512 = function (out, passwd, salt, iter, outlen) {
  assert(
    iter >= binding.extension_pbkdf2_sha512_ITERATIONS_MIN,
    "iter must be at least 'extension_pbkdf2_sha512_ITERATIONS_MIN'"
  )
  assert(
    outlen <= binding.extension_pbkdf2_sha512_BYTES_MAX,
    "outlen must be at most 'extension_pbkdf2_sha512_BYTES_MAX'"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(out.byteLength >= outlen, "out must be at least 'outlen' bytes")
  assert(out.byteLength > 0, 'out must not be empty')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(salt.byteLength > 0, 'salt must not be empty')

  const res = binding.extension_pbkdf2_sha512(out, passwd, salt, iter, outlen)

  if (res !== 0) throw new Error('failed to add tweak to public key')
}

function checkStatus(callback, booleanResult = false) {
  let done, promise

  if (typeof callback === 'function') {
    done = function (status) {
      if (booleanResult) callback(null, status === 0)
      else if (status === 0) callback(null)
      else callback(new Error('status: ' + status))
    }
  } else {
    promise = new Promise(function (resolve, reject) {
      done = function (status) {
        if (booleanResult) resolve(status === 0)
        else if (status === 0) resolve()
        else reject(new Error('status: ' + status))
      }
    })
  }

  return [done, promise]
}
{
  "name": "sodium-native",
  "version": "5.1.0",
  "description": "Low level bindings for libsodium",
  "main": "index.js",
  "files": [
    "index.js",
    "binding.cc",
    "binding.js",
    "extensions",
    "prebuilds",
    "CMakeLists.txt"
  ],
  "imports": {
    "assert": {
      "bare": "bare-assert",
      "node": "assert"
    }
  },
  "addon": true,
  "dependencies": {
    "bare-assert": "^1.2.0",
    "require-addon": "^1.1.0",
    "which-runtime": "^1.2.1"
  },
  "devDependencies": {
    "bare-compat-napi": "^1.3.5",
    "brittle": "^3.16.2",
    "cmake-bare": "^1.6.1",
    "cmake-fetch": "^1.4.3",
    "cmake-napi": "^1.2.1",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "test": "prettier . --check && npm run test:node && npm run test:bare",
    "test:node": "node test/all.js",
    "test:bare": "bare test/all.js"
  },
  "standard": {
    "ignore": [
      "/test/fixtures/*.js"
    ]
  },
  "engines": {
    "bare": ">=1.16.0"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sodium-native.git"
  },
  "contributors": [
    "Emil Bay <github@tixz.dk> (http://bayes.dk)",
    "Mathias Buus <mathiasbuus@gmail.com> (https://mafinto.sh)",
    "Christophe Diederichs <chm-diederichs@hyperdivision.dk>"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/sodium-native/issues"
  },
  "homepage": "https://github.com/holepunchto/sodium-native"
}
module.exports = require('sodium-native')
{
  "name": "sodium-universal",
  "version": "5.0.1",
  "description": "Universal wrapper for sodium-javascript and sodium-native working in Node.js and the Browser",
  "main": "index.js",
  "dependencies": {
    "sodium-native": "^5.0.1"
  },
  "peerDependencies": {
    "sodium-javascript": "~0.8.0"
  },
  "peerDependenciesMeta": {
    "sodium-javascript": {
      "optional": true
    }
  },
  "scripts": {
    "prepublish": "./build-scripts/generate.js"
  },
  "browser": {
    "sodium-native": "sodium-javascript"
  },
  "browserify": {
    "transform": [
      "./build-scripts/transform.js"
    ]
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sodium-universal.git"
  },
  "keywords": [
    "libsodium",
    "sodium",
    "sodium-native",
    "sodium-javascript",
    "browserify"
  ],
  "contributors": [
    "Emil Bay <github@tixz.dk> (http://bayes.dk)",
    "Mathias Buus <mathiasbuus@gmail.com> (https://mafinto.sh)",
    "Christophe Diederichs <chm-diederichs@hyperdivision.dk>"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/sodium-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/sodium-universal#readme"
}
const { runtime, platform, arch, version } =
  typeof Bare !== 'undefined'
    ? {
        runtime: 'bare',
        platform: global.Bare.platform,
        arch: global.Bare.arch,
        version: global.Bare.version
      }
    : typeof process !== 'undefined'
      ? {
          runtime: 'node',
          platform: global.process.platform,
          arch: global.process.arch,
          version: global.process.version
        }
      : typeof Window !== 'undefined'
        ? { runtime: 'browser', platform: 'unknown', arch: 'unknown', version: 'unknown' }
        : { runtime: 'unknown', platform: 'unknown', arch: 'unknown', version: 'unknown' }

exports.runtime = runtime
exports.version = version
exports.platform = platform
exports.arch = arch
exports.isBare = runtime === 'bare'
exports.isBareKit = exports.isBare && typeof BareKit !== 'undefined'
exports.isPear = typeof Pear !== 'undefined'
exports.isNode = runtime === 'node'
exports.isBrowser = runtime === 'browser'
exports.isWindows = platform === 'win32'
exports.isLinux = platform === 'linux'
exports.isMac = platform === 'darwin'
exports.isIOS = platform === 'ios' || platform === 'ios-simulator'
exports.isAndroid = platform === 'android'
exports.isElectron = typeof process !== 'undefined' && !!global.process.versions?.electron
exports.isElectronRenderer = exports.isElectron && global.process.type === 'renderer'
exports.isElectronWorker = exports.isElectron && global.process.type === 'worker'
{
  "name": "which-runtime",
  "version": "1.4.0",
  "description": "Detect if you are in Bare or Node and which os etc",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte .",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/which-runtime.git"
  },
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/which-runtime/issues"
  },
  "homepage": "https://github.com/holepunchto/which-runtime",
  "devDependencies": {
    "brittle": "^3.0.0",
    "lunte": "^1.4.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
{
  "name": "atproto-identity",
  "version": "0.0.4",
  "description": "Seed-anchored atproto identity: one BIP39 mnemonic -> Ed25519 (Hypercore) + secp256k1 (did:plc). Offline did:plc genesis + verification.",
  "type": "module",
  "main": "lib/atproto-identity.js",
  "scripts": {
    "test": "brittle-node test/*.test.js && node test/labels.test.mjs",
    "postinstall": "node scripts/bare-deps.mjs"
  },
  "dependencies": {
    "@ipld/dag-cbor": "^9.2.1",
    "@noble/curves": "^1.6.0",
    "@noble/hashes": "^1.5.0",
    "@scure/bip32": "^1.5.0",
    "@scure/bip39": "^1.4.0",
    "b4a": "^1.6.7",
    "hypercore-crypto": "^3.0.0",
    "keet-identity-key": "^3.2.0",
    "multiformats": "^13.3.0",
    "sodium-native": "^5.1.0"
  },
  "devDependencies": {
    "brittle": "^4.0.2"
  }
}
// Minimal CAR v1 codec — bare-safe, dependency-light replacement for @ipld/car.
//
// CAR v1 is a trivial container: varint(headerLen) ++ dag-cbor({version:1, roots:[…]})
// then, per block, varint(len) ++ CIDbytes ++ blockBytes. We only need whole-buffer
// read/write (no streaming, no file I/O), so this is ~40 lines of pure JS over
// multiformats' CID (byte-exact with @ipld/car — verified by the repo tests + the
// @atproto/repo conformance reader). Drops @ipld/car (which imports `fs`/streams and
// won't load under Bare).
//
// ⚠️ LIMITATIONS vs @ipld/car (tracked in memory: bare-car-limitations). Fine for our
// current use (whole-buffer, CARv1, OUR-OWN trusted output); add the feature before the
// gate it guards:
//   - No streaming — whole CAR is buffered in memory. GATE: large repos (getRepo of a
//     big repo could be GBs). Add an async-iterator read/write path.
//   - No untrusted-input hardening — readCar trusts varints/lengths/CIDs. GATE: reading
//     UNTRUSTED CARs (com.atproto.repo.importRepo, ingress bridge). Add bounds/overflow/
//     truncation checks + duplicate-CID handling before then.
//   - CARv1 only (no CARv2/index). atproto is CARv1, so no gate today.
// Fully-featured path: grow this file at each gate, OR extract a standalone bare-native
// `bare-car` package (the holepunch ecosystem lacks one — a real contribution).

import { CID } from 'multiformats/cid'
import * as dagCbor from '@ipld/dag-cbor'

function varintEncode (n) {
  const out = []
  while (n >= 0x80) { out.push((n & 0x7f) | 0x80); n >>>= 7 }
  out.push(n)
  return Uint8Array.from(out)
}

function varintDecode (bytes, offset) {
  let n = 0; let shift = 0; let i = offset
  for (;;) {
    const b = bytes[i++]
    n |= (b & 0x7f) << shift
    if ((b & 0x80) === 0) break
    shift += 7
  }
  return [n >>> 0, i]
}

// Serialise { root, blocks } to CAR bytes. `blocks` is an iterable of { cid, bytes }.
export async function writeCar (rootCid, blocks) {
  const header = dagCbor.encode({ version: 1, roots: [rootCid] })
  const parts = [Buffer.from(varintEncode(header.length)), Buffer.from(header)]
  for (const { cid, bytes } of blocks) {
    const cidBytes = cid.bytes
    const body = new Uint8Array(cidBytes.length + bytes.length)
    body.set(cidBytes, 0)
    body.set(bytes, cidBytes.length)
    parts.push(Buffer.from(varintEncode(body.length)), Buffer.from(body))
  }
  return Buffer.concat(parts)
}

// Read a CAR into { roots, blocks } where blocks maps cid-string -> { cid, bytes }.
export async function readCar (carBytes) {
  const bytes = carBytes instanceof Uint8Array ? carBytes : new Uint8Array(carBytes)
  let [hlen, off] = varintDecode(bytes, 0)
  const header = dagCbor.decode(bytes.subarray(off, off + hlen))
  off += hlen
  const blocks = new Map()
  while (off < bytes.length) {
    const [blen, bodyStart] = varintDecode(bytes, off)
    const end = bodyStart + blen
    const [cid, rest] = CID.decodeFirst(bytes.subarray(bodyStart, end))
    blocks.set(cid.toString(), { cid, bytes: rest })
    off = end
  }
  return { roots: header.roots, blocks }
}
// atproto block CIDs — CIDv1, dag-cbor codec (0x71), sha2-256 multihash (0x12).
// Every block in a repo (commit, MST node, record) is content-addressed this way,
// so computeCid(dag-cbor(block)) IS the block's identity. This is the anchor for
// byte-exact fidelity: if our re-encoded bytes hash to the same CID the reference
// produced, our encoding is byte-identical.

import { CID } from 'multiformats/cid'
import * as Digest from 'multiformats/hashes/digest'
import { sha256 as nobleSha256 } from '@noble/hashes/sha2'
import * as dagCbor from '@ipld/dag-cbor'
import * as raw from 'multiformats/codecs/raw'

// raw block bytes -> CID. Uses noble's pure-JS sha256 (same as the sync path) rather
// than multiformats' `crypto.subtle` path — identical CID, and no WebCrypto dependency
// (so it loads + runs under Bare, which has no crypto.subtle).
export async function cidForBytes (bytes) {
  return cidForBytesSync(bytes)
}

// Synchronous variant — needed by the recursive MST build. Same result as
// cidForBytes (CIDv1 / dag-cbor 0x71 / sha2-256 0x12), just without the async
// WebCrypto digest.
export function cidForBytesSync (bytes) {
  const digest = Digest.create(0x12, nobleSha256(bytes)) // 0x12 = sha2-256 multihash code
  return CID.createV1(dagCbor.code, digest)
}

// BLOB CID — CIDv1, RAW codec (0x55), sha2-256. atproto blobs (images/avatars) are
// content-addressed with the raw codec (opaque bytes), NOT dag-cbor. This is the CID that
// goes in a blob ref ({$type:'blob', ref:{$link:<this>}, mimeType, size}) and the key
// com.atproto.sync.getBlob serves by.
export function cidForBlobSync (bytes) {
  const digest = Digest.create(0x12, nobleSha256(bytes))
  return CID.createV1(raw.code, digest)
}

// a JS value -> its canonical dag-cbor bytes + CID
export async function cidForValue (value) {
  const bytes = dagCbor.encode(value)
  return { bytes, cid: await cidForBytes(bytes) }
}
// atproto repo commit — sign + verify.
//
// A commit is { did, version: 3, data: <MST root CID>, rev, prev, sig }. The
// signature is ECDSA-secp256k1 (low-S) over sha256(dag-cbor(unsignedCommit)), stored
// as a raw 64-byte CBOR byte string (NOT base64url — that's the did:plc genesis).
// The relay validates this sig against the DID doc's verificationMethod.

import * as dagCbor from '@ipld/dag-cbor'
import { sha256 as nobleSha256 } from '@noble/hashes/sha2'
import { secp256k1 } from '@noble/curves/secp256k1'
import { cidForBytesSync } from './cid.js'

export const REPO_VERSION = 3

// The unsigned commit (everything the signature covers).
export function unsignedCommit ({ did, rev, data, prev = null }) {
  return { did, version: REPO_VERSION, data, rev, prev }
}

// Sign an unsigned commit -> signed commit with `sig` (64 raw bytes).
export function signCommit (unsigned, privateKey) {
  const hash = nobleSha256(dagCbor.encode(unsigned))
  const sig = secp256k1.sign(hash, privateKey, { lowS: true }).toCompactRawBytes()
  return { ...unsigned, sig }
}

export function commitCid (signedCommit) {
  return cidForBytesSync(dagCbor.encode(signedCommit))
}

// Verify a signed commit against a compressed secp256k1 pubkey (33 bytes).
export function verifyCommit (signedCommit, publicKey) {
  const { sig, ...unsigned } = signedCommit
  const hash = nobleSha256(dagCbor.encode(unsigned))
  return secp256k1.verify(sig, hash, publicKey, { lowS: true })
}
// atproto MST — WRITE path (slice 2).
//
// A faithful port of millipds's `atmst` (mst/node.py + node_wrangler.py) — the exact
// code that produced our golden CAR. Byte-exactness is verified two ways: rebuilding
// the golden repo's MST, and matching atmst's own root CIDs for a multi-height tree
// (build + delete oracles). See test/mst-write.test.js.
//
// Node shape (interleaved): subtrees[0], (keys[0],vals[0]), subtrees[1], … ,subtrees[n].
// key layer = leading-zero BITS of sha256(key), // 2 (fanout 4).

import * as dagCbor from '@ipld/dag-cbor'
import { sha256 as nobleSha256 } from '@noble/hashes/sha2'
import { cidForBytesSync } from './cid.js'

const cidEq = (a, b) => (a === null || b === null) ? a === b : a.equals(b)
const replaceAt = (arr, i, v) => { const c = arr.slice(); c[i] = v; return c }
const insertAt = (arr, i, v) => arr.slice(0, i).concat([v], arr.slice(i))
const removeAt = (arr, i) => arr.slice(0, i).concat(arr.slice(i + 1))

export function keyHeight (key) {
  const h = nobleSha256(Buffer.from(key, 'utf8')) // 32 bytes
  let zeros = 0
  for (const byte of h) {
    if (byte === 0) { zeros += 8; continue }
    zeros += Math.clz32(byte) - 24 // leading zero bits within this byte
    break
  }
  return zeros >> 1 // // 2
}

export class MSTNode {
  constructor (keys, vals, subtrees) {
    this.keys = keys // [string]
    this.vals = vals // [CID]
    this.subtrees = subtrees // [CID|null], length keys.length + 1
  }

  static empty () { return new MSTNode([], [], [null]) }

  isEmpty () { return this.keys.length === 0 && this.subtrees.length === 1 && this.subtrees[0] === null }

  serialise () {
    const e = []
    let prevKey = Buffer.alloc(0)
    for (let i = 0; i < this.keys.length; i++) {
      const keyBytes = Buffer.from(this.keys[i], 'utf8')
      const max = Math.min(prevKey.length, keyBytes.length)
      let p = 0
      while (p < max && prevKey[p] === keyBytes[p]) p++
      e.push({ k: keyBytes.subarray(p), p, t: this.subtrees[i + 1], v: this.vals[i] })
      prevKey = keyBytes
    }
    return dagCbor.encode({ e, l: this.subtrees[0] }) // dag-cbor canonicalises map key order
  }

  cid () { return cidForBytesSync(this.serialise()) }

  toOptional () { return this.isEmpty() ? null : this.cid() }

  gteIndex (key) { let i = 0; while (i < this.keys.length && key > this.keys[i]) i++; return i }

  height () {
    if (this.keys.length) return keyHeight(this.keys[0])
    if (this.subtrees[0] === null) return 0
    return null // indeterminate (empty intermediate node)
  }

  static deserialise (bytes) {
    const cbor = dagCbor.decode(bytes)
    const subtrees = [cbor.l]
    const keys = []
    const vals = []
    let prevKey = Buffer.alloc(0)
    for (const e of cbor.e) {
      const suffix = Buffer.from(e.k)
      const thisKey = Buffer.concat([prevKey.subarray(0, e.p), suffix])
      keys.push(thisKey.toString('utf8'))
      vals.push(e.v)
      subtrees.push(e.t)
      prevKey = thisKey
    }
    return new MSTNode(keys, vals, subtrees)
  }
}

// In-memory node store — maps CID string -> { cid, bytes }. get(null) returns the
// (stored) empty node, matching atmst NodeStore.get_node(None).
export class NodeStore {
  constructor () { this.blocks = new Map() }

  storedNode (node) {
    const bytes = node.serialise()
    const cid = cidForBytesSync(bytes)
    this.blocks.set(cid.toString(), { cid, bytes })
    return node
  }

  getNode (cid) {
    if (cid === null || cid === undefined) return this.storedNode(MSTNode.empty())
    const b = this.blocks.get(cid.toString())
    if (!b) throw new Error(`missing MST node ${cid}`)
    return MSTNode.deserialise(b.bytes)
  }
}

export class NodeWrangler {
  constructor (ns) { this.ns = ns }

  putRecord (rootCid, key, val) {
    const root = this.ns.getNode(rootCid)
    if (root.isEmpty()) return this._putHere(root, key, val).cid()
    return this._putRecursive(root, key, val, keyHeight(key), root.height()).cid()
  }

  delRecord (rootCid, key) {
    const root = this.ns.getNode(rootCid)
    const afterDel = this._deleteRecursive(root, key, keyHeight(key), root.height())
    return this.ns.getNode(this._squashTop(afterDel)).cid()
  }

  _putHere (node, key, val) {
    const i = node.gteIndex(key)
    if (i < node.keys.length && node.keys[i] === key) {
      if (cidEq(node.vals[i], val)) return node
      return this.ns.storedNode(new MSTNode(node.keys.slice(), replaceAt(node.vals, i, val), node.subtrees.slice()))
    }
    const [lsub, rsub] = this._splitOnKey(node.subtrees[i], key)
    return this.ns.storedNode(new MSTNode(
      insertAt(node.keys, i, key),
      insertAt(node.vals, i, val),
      node.subtrees.slice(0, i).concat([lsub, rsub], node.subtrees.slice(i + 1))
    ))
  }

  _putRecursive (node, key, val, keyH, treeH) {
    if (keyH > treeH) { // grow the tree upward
      return this.ns.storedNode(this._putRecursive(
        this.ns.storedNode(new MSTNode([], [], [node.cid()])),
        key, val, keyH, treeH + 1
      ))
    }
    if (keyH < treeH) { // descend
      const i = node.gteIndex(key)
      return this.ns.storedNode(new MSTNode(
        node.keys.slice(), node.vals.slice(),
        replaceAt(node.subtrees, i, this._putRecursive(this.ns.getNode(node.subtrees[i]), key, val, keyH, treeH - 1).cid())
      ))
    }
    return this._putHere(node, key, val) // keyH === treeH
  }

  _splitOnKey (nodeCid, key) {
    if (nodeCid === null || nodeCid === undefined) return [null, null]
    const node = this.ns.getNode(nodeCid)
    const i = node.gteIndex(key)
    const [lsub, rsub] = this._splitOnKey(node.subtrees[i], key)
    const left = this.ns.storedNode(new MSTNode(node.keys.slice(0, i), node.vals.slice(0, i), node.subtrees.slice(0, i).concat([lsub]))).toOptional()
    const right = this.ns.storedNode(new MSTNode(node.keys.slice(i), node.vals.slice(i), [rsub].concat(node.subtrees.slice(i + 1)))).toOptional()
    return [left, right]
  }

  _squashTop (nodeCid) {
    const node = this.ns.getNode(nodeCid)
    if (node.keys.length) return nodeCid
    if (node.subtrees[0] === null) return nodeCid
    return this._squashTop(node.subtrees[0])
  }

  _deleteRecursive (node, key, keyH, treeH) {
    if (keyH > treeH) return node.toOptional()
    let i = node.gteIndex(key)
    if (keyH < treeH) {
      if (node.subtrees[i] === null) return node.toOptional()
      return this.ns.storedNode(new MSTNode(
        node.keys.slice(), node.vals.slice(),
        replaceAt(node.subtrees, i, this._deleteRecursive(this.ns.getNode(node.subtrees[i]), key, keyH, treeH - 1))
      )).toOptional()
    }
    i = node.gteIndex(key)
    if (i === node.keys.length || node.keys[i] !== key) return node.toOptional()
    return this.ns.storedNode(new MSTNode(
      removeAt(node.keys, i), removeAt(node.vals, i),
      node.subtrees.slice(0, i).concat([this._merge(node.subtrees[i], node.subtrees[i + 1])], node.subtrees.slice(i + 2))
    )).toOptional()
  }

  _merge (leftCid, rightCid) {
    if (leftCid === null) return rightCid
    if (rightCid === null) return leftCid
    const left = this.ns.getNode(leftCid)
    const right = this.ns.getNode(rightCid)
    return this.ns.storedNode(new MSTNode(
      left.keys.concat(right.keys), left.vals.concat(right.vals),
      left.subtrees.slice(0, -1).concat([this._merge(left.subtrees[left.subtrees.length - 1], right.subtrees[0])], right.subtrees.slice(1))
    )).toOptional()
  }
}

// Build an MST from records [{ key, value: CID }] (any order). Returns
// { root: CID, ns: NodeStore }. ns.blocks holds every node created; use
// reachableBlocks(ns, root) for just the live set (CAR output).
export function buildMst (records) {
  const ns = new NodeStore()
  const w = new NodeWrangler(ns)
  let root = ns.storedNode(MSTNode.empty()).cid()
  for (const { key, value } of records) root = w.putRecord(root, key, value)
  return { root, ns, wrangler: w }
}

// BFS the live MST nodes reachable from root (for CAR block sets).
export function reachableBlocks (ns, rootCid) {
  const out = new Map()
  const stack = [rootCid]
  while (stack.length) {
    const cid = stack.pop()
    if (cid === null || cid === undefined) continue
    const key = cid.toString()
    if (out.has(key)) continue
    const b = ns.blocks.get(key)
    if (!b) throw new Error(`missing node ${key}`)
    out.set(key, b)
    const node = MSTNode.deserialise(b.bytes)
    for (const t of node.subtrees) if (t) stack.push(t)
  }
  return out
}

// ---- Firehose MST-inversion proof (slice 3b) ----
//
// A #commit's `blocks` CAR must be a MINIMAL, self-contained proof of the
// old→new transition — not the whole tree (that would trip a relay's `tooBig`).
// This ports millipds `repo_ops.py:apply_writes` step 2b + `atmst` proof.py:
//   blocks = created | deletion_proof_cids | inductive_proof_nodes  (+ new records)
// where `inductive_proof_nodes` = every MST node READ while replaying the ops
// backward from the new root, which must reproduce the old (prevData) root.
// The prior record CIDs travel in each op's `prev` (like millipds), so a cold
// relay can invert with no old-tree state of its own.

// A NodeStore overlay: writes land in an in-memory upper layer (NOT logged);
// reads that fall through to `lower` are recorded in `.gets`. Mirrors millipds's
// OverlayBlockStore(MemoryBlockStore, LoggingBlockStoreWrapper(bs)).
export class OverlayNodeStore {
  constructor (lower) { this.lower = lower; this.upper = new Map(); this.gets = new Set() }

  storedNode (node) {
    const bytes = node.serialise()
    const cid = cidForBytesSync(bytes)
    this.upper.set(cid.toString(), { cid, bytes })
    return node
  }

  getNode (cid) {
    if (cid === null || cid === undefined) return MSTNode.empty()
    const k = cid.toString()
    const u = this.upper.get(k)
    if (u) return MSTNode.deserialise(u.bytes)
    this.gets.add(k) // a read of a pre-existing node — part of the inductive proof
    return this.lower.getNode(cid)
  }
}

// Follow the search path for `key` from `rootCid`, collecting every node visited.
// Returns { value: CID|null, proof: Set<cidStr> }. value===null ⇒ exclusion proof;
// value!==null ⇒ inclusion proof. Port of atmst find_rpath_and_build_proof.
export function findRpathProof (ns, rootCid, key) {
  const proof = new Set()
  let cid = rootCid
  while (cid !== null && cid !== undefined) {
    const node = ns.getNode(cid)
    proof.add(cid.toString())
    const i = node.gteIndex(key)
    if (i < node.keys.length && node.keys[i] === key) return { value: node.vals[i], proof }
    cid = node.subtrees[i] // descend the subtree left of the first key >= target
  }
  return { value: null, proof }
}

// Build a NodeStore holding exactly the given blocks (cid-string -> { cid, bytes }).
export function nodeStoreFromBlocks (blocks) {
  const ns = new NodeStore()
  for (const [k, v] of blocks) ns.blocks.set(k, v)
  return ns
}

// Compute the minimal firehose block set for a single commit's ops.
//   oldRecords / newRecords : [{ key, value: CID }] — the record sets BEFORE/AFTER.
//   ops : [{ action:'create'|'update'|'delete', path, cid: CID|null, prev: CID|null }]
// Returns { blocks: Map<cidStr,{cid,bytes}>, dataCid, oldRoot } — MST nodes only
// (record + commit blocks are added by the caller). Throws if the backward replay
// does not reproduce the old root (i.e. the proof would be invalid).
export function firehoseProofBlocks ({ oldRecords, newRecords, ops }) {
  const oldB = buildMst(oldRecords)
  const newB = buildMst(newRecords)
  const oldRoot = oldB.root
  const newRoot = newB.root

  const oldSet = reachableBlocks(oldB.ns, oldRoot)
  const newSet = reachableBlocks(newB.ns, newRoot)

  // combined store holds every node of BOTH trees (proof reads span both)
  const combined = new NodeStore()
  for (const [k, v] of oldSet) combined.blocks.set(k, v)
  for (const [k, v] of newSet) combined.blocks.set(k, v)

  const proofCids = new Set()

  // created: new-tree nodes not present in the old tree
  for (const k of newSet.keys()) if (!oldSet.has(k)) proofCids.add(k)

  // deletion proofs: for each delete, the exclusion-proof path in the NEW tree
  for (const op of ops) {
    if (op.action !== 'delete') continue
    const { value, proof } = findRpathProof(combined, newRoot, op.path)
    if (value !== null) throw new Error(`delete proof: ${op.path} still present in new tree`)
    for (const c of proof) proofCids.add(c)
  }

  // inductive proof: replay ops backward from newRoot; every node read is required.
  const overlay = new OverlayNodeStore(combined)
  const w = new NodeWrangler(overlay)
  let inv = newRoot
  for (let i = ops.length - 1; i >= 0; i--) {
    const op = ops[i]
    if (op.action === 'create') {
      inv = w.delRecord(inv, op.path)
    } else { // update | delete → restore the prior value
      if (op.prev === null || op.prev === undefined) throw new Error(`inversion: ${op.action} ${op.path} missing prev`)
      inv = w.putRecord(inv, op.path, op.prev)
    }
  }
  if (!inv.equals(oldRoot)) throw new Error('inversion proof failed: backward replay did not reproduce prevData root')
  for (const k of overlay.gets) proofCids.add(k)

  const blocks = new Map()
  for (const k of proofCids) blocks.set(k, combined.blocks.get(k))
  return { blocks, dataCid: newRoot, oldRoot }
}
// atproto repo — READ path (slice 1).
//
// A repo is a CAR whose root is a signed commit; the commit's `data` CID points at
// the root of a Merkle Search Tree (MST) of records. This module reads a CAR, walks
// the MST, and — most importantly — VERIFIES byte-exact fidelity by re-encoding every
// block and checking its CID. Writing/mutating the MST is slice 2.

import * as dagCbor from '@ipld/dag-cbor'
import { cidForBytes, cidForBytesSync } from './cid.js'
import { buildMst, reachableBlocks } from './mst.js'
import { unsignedCommit, signCommit, commitCid } from './commit.js'
import { readCar, writeCar } from './car.js'

// CAR read/write moved to the bare-safe minimal codec in ./car.js (was @ipld/car).
export { readCar, writeCar }

export function getBlock (car, cid) {
  const b = car.blocks.get(cid.toString())
  if (!b) throw new Error(`missing block ${cid}`)
  return b
}

export function decodeBlock (car, cid) {
  return dagCbor.decode(getBlock(car, cid).bytes)
}

// The signed commit at the CAR root.
export function loadCommit (car) {
  if (car.roots.length !== 1) throw new Error(`expected 1 root, got ${car.roots.length}`)
  const commit = decodeBlock(car, car.roots[0])
  if (!commit || !commit.did || commit.data === undefined) throw new Error('root is not a commit')
  return { cid: car.roots[0], value: commit }
}

// Walk the MST in key order, yielding { key, value: recordCid }. MST node shape:
//   { l: CID|null, e: [ { p: int, k: bytes, v: CID, t: CID|null } ] }
// keys are prefix-compressed against the previous key in the SAME node.
export function * walkMst (car, rootCid, _prevKey = '') {
  const node = decodeBlock(car, rootCid)
  if (!node || !Array.isArray(node.e)) throw new Error(`not an MST node: ${rootCid}`)
  if (node.l) yield * walkMst(car, node.l)
  let prev = ''
  for (const e of node.e) {
    const suffix = Buffer.from(e.k).toString('utf8')
    const key = prev.slice(0, e.p) + suffix
    prev = key
    yield { key, value: e.v }
    if (e.t) yield * walkMst(car, e.t)
  }
}

// All records as { key, cid, value } in key order.
export function listRecords (car) {
  const commit = loadCommit(car)
  const out = []
  for (const { key, value } of walkMst(car, commit.value.data)) {
    out.push({ key, cid: value, value: decodeBlock(car, value) })
  }
  return out
}

// Byte-exact fidelity check: re-encode every block and confirm its CID is unchanged.
// Also confirms the commit's data CID and every MST value CID resolve to a present
// block. Returns { blocks, records, ok, mismatches }.
export async function verifyRepo (car) {
  const mismatches = []
  for (const [cidStr, { cid, bytes }] of car.blocks) {
    // re-encode: decode then canonical-encode; must reproduce the exact bytes + CID
    const reencoded = dagCbor.encode(dagCbor.decode(bytes))
    const sameBytes = Buffer.from(reencoded).equals(Buffer.from(bytes))
    const recomputed = await cidForBytes(reencoded)
    if (!sameBytes || !recomputed.equals(cid)) {
      mismatches.push({ cid: cidStr, sameBytes, recomputed: recomputed.toString() })
    }
  }
  const commit = loadCommit(car)
  getBlock(car, commit.value.data) // MST root must be present
  const records = listRecords(car)
  for (const r of records) getBlock(car, r.cid) // each record block present
  return { blocks: car.blocks.size, records: records.length, ok: mismatches.length === 0, mismatches }
}

// ---- WRITE path (slice 3) ----

// Originate a full atproto repo from records. Each record is
// { collection, rkey, record } (or { key, value }). Returns the CAR bytes plus the
// commit/data CIDs. `privateKey` is the atproto secp256k1 signing key.
export async function createRepo ({ records, did, rev, privateKey }) {
  const recordBlocks = new Map()
  const mstRecords = []
  for (const r of records) {
    const key = r.key !== undefined ? r.key : `${r.collection}/${r.rkey}`
    const value = r.record !== undefined ? r.record : r.value
    const bytes = dagCbor.encode(value)
    const cid = cidForBytesSync(bytes)
    recordBlocks.set(cid.toString(), { cid, bytes })
    mstRecords.push({ key, value: cid })
  }
  const { root: dataCid, ns } = buildMst(mstRecords)
  const mstBlocks = reachableBlocks(ns, dataCid)

  const signed = signCommit(unsignedCommit({ did, rev, data: dataCid }), privateKey)
  const cCid = commitCid(signed)
  const commitBytes = dagCbor.encode(signed)

  const blocks = [{ cid: cCid, bytes: commitBytes }, ...mstBlocks.values(), ...recordBlocks.values()]
  const carBytes = await writeCar(cCid, blocks)
  return { carBytes, commitCid: cCid, dataCid, signedCommit: signed }
}
{
  "name": "@ipld/dag-cbor",
  "version": "9.2.7",
  "description": "JS implementation of DAG-CBOR",
  "author": "Rod <rod@vagg.org> (http://r.va.gg/)",
  "license": "Apache-2.0 OR MIT",
  "homepage": "https://github.com/ipld/js-dag-cbor#readme",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/ipld/js-dag-cbor.git"
  },
  "bugs": {
    "url": "https://github.com/ipld/js-dag-cbor/issues"
  },
  "publishConfig": {
    "access": "public",
    "provenance": true
  },
  "keywords": [
    "ipfs",
    "ipld",
    "multiformats"
  ],
  "type": "module",
  "types": "./dist/src/index.d.ts",
  "typesVersions": {
    "*": {
      "*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ],
      "src/*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ]
    }
  },
  "files": [
    "src",
    "dist",
    "!dist/test",
    "!**/*.tsbuildinfo"
  ],
  "exports": {
    ".": {
      "types": "./dist/src/index.d.ts",
      "import": "./src/index.js",
      "module-sync": "./src/index.js"
    }
  },
  "release": {
    "branches": [
      "master"
    ],
    "plugins": [
      [
        "@semantic-release/commit-analyzer",
        {
          "preset": "conventionalcommits",
          "releaseRules": [
            {
              "breaking": true,
              "release": "major"
            },
            {
              "revert": true,
              "release": "patch"
            },
            {
              "type": "feat",
              "release": "minor"
            },
            {
              "type": "fix",
              "release": "patch"
            },
            {
              "type": "docs",
              "release": "patch"
            },
            {
              "type": "test",
              "release": "patch"
            },
            {
              "type": "deps",
              "release": "patch"
            },
            {
              "scope": "no-release",
              "release": false
            }
          ]
        }
      ],
      [
        "@semantic-release/release-notes-generator",
        {
          "preset": "conventionalcommits",
          "presetConfig": {
            "types": [
              {
                "type": "feat",
                "section": "Features"
              },
              {
                "type": "fix",
                "section": "Bug Fixes"
              },
              {
                "type": "chore",
                "section": "Trivial Changes"
              },
              {
                "type": "docs",
                "section": "Documentation"
              },
              {
                "type": "deps",
                "section": "Dependencies"
              },
              {
                "type": "test",
                "section": "Tests"
              }
            ]
          }
        }
      ],
      "@semantic-release/changelog",
      "@semantic-release/npm",
      "@semantic-release/github",
      [
        "@semantic-release/git",
        {
          "assets": [
            "CHANGELOG.md",
            "package.json"
          ]
        }
      ]
    ]
  },
  "scripts": {
    "clean": "aegir clean",
    "lint": "aegir lint",
    "build": "aegir build",
    "release": "aegir release",
    "test": "npm run lint && aegir test",
    "test:ts": "npm run test --prefix test/ts-use",
    "test:node": "aegir test -t node --cov",
    "test:chrome": "aegir test -t browser --cov",
    "test:chrome-webworker": "aegir test -t webworker",
    "test:firefox": "aegir test -t browser -- --browser firefox",
    "test:firefox-webworker": "aegir test -t webworker -- --browser firefox",
    "test:electron-main": "aegir test -t electron-main",
    "dep-check": "aegir dep-check"
  },
  "dependencies": {
    "cborg": "^5.0.1",
    "multiformats": "^13.1.0"
  },
  "devDependencies": {
    "@ipld/garbage": "^6.0.0",
    "aegir": "^48.0.1"
  }
}
import * as cborg from 'cborg'
import { CID } from 'multiformats/cid'

// https://github.com/ipfs/go-ipfs/issues/3570#issuecomment-273931692
const CID_CBOR_TAG = 42

/**
 * @template T
 * @typedef {import('multiformats/codecs/interface').ByteView<T>} ByteView
 */

/**
 * @template T
 * @typedef {import('multiformats/codecs/interface').ArrayBufferView<T>} ArrayBufferView
 */

/**
 * @template T
 * @param {ByteView<T> | ArrayBufferView<T>} buf
 * @returns {ByteView<T>}
 */
export function toByteView (buf) {
  if (buf instanceof ArrayBuffer) {
    return new Uint8Array(buf, 0, buf.byteLength)
  }

  return buf
}

/**
 * cidEncoder will receive all Objects during encode, it needs to filter out
 * anything that's not a CID and return `null` for that so it's encoded as
 * normal.
 *
 * @param {any} obj
 * @returns {cborg.Token[]|null}
 */
function cidEncoder (obj) {
  if (obj.asCID !== obj && obj['/'] !== obj.bytes) {
    return null // any other kind of object
  }
  const cid = CID.asCID(obj)
  /* c8 ignore next 4 */
  // very unlikely case, and it'll probably throw a recursion error in cborg
  if (!cid) {
    return null
  }
  const bytes = new Uint8Array(cid.bytes.byteLength + 1)
  bytes.set(cid.bytes, 1) // prefix is 0x00, for historical reasons
  return [
    new cborg.Token(cborg.Type.tag, CID_CBOR_TAG),
    new cborg.Token(cborg.Type.bytes, bytes)
  ]
}

// eslint-disable-next-line jsdoc/require-returns-check
/**
 * Intercept all `undefined` values from an object walk and reject the entire
 * object if we find one.
 *
 * @returns {null}
 */
function undefinedEncoder () {
  throw new Error('`undefined` is not supported by the IPLD Data Model and cannot be encoded')
}

/**
 * Intercept all `number` values from an object walk and reject the entire
 * object if we find something that doesn't fit the IPLD data model (NaN &
 * Infinity).
 *
 * @param {number} num
 * @returns {null}
 */
function numberEncoder (num) {
  if (Number.isNaN(num)) {
    throw new Error('`NaN` is not supported by the IPLD Data Model and cannot be encoded')
  }
  if (num === Infinity || num === -Infinity) {
    throw new Error('`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded')
  }
  return null
}

/**
 * @param {Map<any, any>} map
 * @returns {null}
 */
function mapEncoder (map) {
  for (const key of map.keys()) {
    if (typeof key !== 'string' || key.length === 0) {
      throw new Error('Non-string Map keys are not supported by the IPLD Data Model and cannot be encoded')
    }
  }
  return null
}

const _encodeOptions = {
  float64: true,
  typeEncoders: {
    Map: mapEncoder,
    Object: cidEncoder,
    undefined: undefinedEncoder,
    number: numberEncoder
  }
}

export const encodeOptions = {
  ..._encodeOptions,
  typeEncoders: {
    ..._encodeOptions.typeEncoders
  }
}

/**
 * @param {import('cborg').TagDecodeControl} decode
 * @returns {CID}
 */
function cidDecoder (decode) {
  const bytes = /** @type {Uint8Array} */ (decode())
  if (bytes[0] !== 0) {
    throw new Error('Invalid CID for CBOR tag 42; expected leading 0x00')
  }
  return CID.decode(bytes.subarray(1)) // ignore leading 0x00
}

const _decodeOptions = {
  allowIndefinite: false,
  coerceUndefinedToNull: true,
  allowNaN: false,
  allowInfinity: false,
  allowBigInt: true, // this will lead to BigInt for ints outside of
  // safe-integer range, which may surprise users
  strict: true,
  useMaps: false,
  rejectDuplicateMapKeys: true,
  /** @type {{ [tagNumber: number]: import('cborg').TagDecoder }} */
  tags: { [CID_CBOR_TAG]: cidDecoder }
}

export const decodeOptions = {
  ..._decodeOptions,
  tags: { ..._decodeOptions.tags }
}

export const name = 'dag-cbor'
export const code = 0x71

/**
 * @template T
 * @param {T} node
 * @returns {ByteView<T>}
 */
export const encode = (node) => cborg.encode(node, _encodeOptions)

/**
 * @template T
 * @param {ByteView<T> | ArrayBufferView<T>} data
 * @returns {T}
 */
export const decode = (data) => cborg.decode(toByteView(data), _decodeOptions)
/**
 * Utilities for short weierstrass curves, combined with noble-hashes.
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { weierstrass } from "./abstract/weierstrass.js";
/** connects noble-curves to noble-hashes */
export function getHash(hash) {
    return { hash };
}
/** @deprecated use new `weierstrass()` and `ecdsa()` methods */
export function createCurve(curveDef, defHash) {
    const create = (hash) => weierstrass({ ...curveDef, hash: hash });
    return { ...create(defHash), create };
}
//# sourceMappingURL=_shortw_utils.js.map/**
 * Methods for elliptic curve multiplication by scalars.
 * Contains wNAF, pippenger.
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { bitLen, bitMask, validateObject } from "../utils.js";
import { Field, FpInvertBatch, nLength, validateField } from "./modular.js";
const _0n = BigInt(0);
const _1n = BigInt(1);
export function negateCt(condition, item) {
    const neg = item.negate();
    return condition ? neg : item;
}
/**
 * Takes a bunch of Projective Points but executes only one
 * inversion on all of them. Inversion is very slow operation,
 * so this improves performance massively.
 * Optimization: converts a list of projective points to a list of identical points with Z=1.
 */
export function normalizeZ(c, points) {
    const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
    return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
}
function validateW(W, bits) {
    if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
        throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);
}
function calcWOpts(W, scalarBits) {
    validateW(W, scalarBits);
    const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero
    const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero
    const maxNumber = 2 ** W; // W=8 256
    const mask = bitMask(W); // W=8 255 == mask 0b11111111
    const shiftBy = BigInt(W); // W=8 8
    return { windows, windowSize, mask, maxNumber, shiftBy };
}
function calcOffsets(n, window, wOpts) {
    const { windowSize, mask, maxNumber, shiftBy } = wOpts;
    let wbits = Number(n & mask); // extract W bits.
    let nextN = n >> shiftBy; // shift number by W bits.
    // What actually happens here:
    // const highestBit = Number(mask ^ (mask >> 1n));
    // let wbits2 = wbits - 1; // skip zero
    // if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);
    // split if bits > max: +224 => 256-32
    if (wbits > windowSize) {
        // we skip zero, which means instead of `>= size-1`, we do `> size`
        wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.
        nextN += _1n; // +256 (carry)
    }
    const offsetStart = window * windowSize;
    const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero
    const isZero = wbits === 0; // is current window slice a 0?
    const isNeg = wbits < 0; // is current window slice negative?
    const isNegF = window % 2 !== 0; // fake random statement for noise
    const offsetF = offsetStart; // fake offset for noise
    return { nextN, offset, isZero, isNeg, isNegF, offsetF };
}
function validateMSMPoints(points, c) {
    if (!Array.isArray(points))
        throw new Error('array expected');
    points.forEach((p, i) => {
        if (!(p instanceof c))
            throw new Error('invalid point at index ' + i);
    });
}
function validateMSMScalars(scalars, field) {
    if (!Array.isArray(scalars))
        throw new Error('array of scalars expected');
    scalars.forEach((s, i) => {
        if (!field.isValid(s))
            throw new Error('invalid scalar at index ' + i);
    });
}
// Since points in different groups cannot be equal (different object constructor),
// we can have single place to store precomputes.
// Allows to make points frozen / immutable.
const pointPrecomputes = new WeakMap();
const pointWindowSizes = new WeakMap();
function getW(P) {
    // To disable precomputes:
    // return 1;
    return pointWindowSizes.get(P) || 1;
}
function assert0(n) {
    if (n !== _0n)
        throw new Error('invalid wNAF');
}
/**
 * Elliptic curve multiplication of Point by scalar. Fragile.
 * Table generation takes **30MB of ram and 10ms on high-end CPU**,
 * but may take much longer on slow devices. Actual generation will happen on
 * first call of `multiply()`. By default, `BASE` point is precomputed.
 *
 * Scalars should always be less than curve order: this should be checked inside of a curve itself.
 * Creates precomputation tables for fast multiplication:
 * - private scalar is split by fixed size windows of W bits
 * - every window point is collected from window's table & added to accumulator
 * - since windows are different, same point inside tables won't be accessed more than once per calc
 * - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)
 * - +1 window is neccessary for wNAF
 * - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication
 *
 * @todo Research returning 2d JS array of windows, instead of a single window.
 * This would allow windows to be in different memory locations
 */
export class wNAF {
    // Parametrized with a given Point class (not individual point)
    constructor(Point, bits) {
        this.BASE = Point.BASE;
        this.ZERO = Point.ZERO;
        this.Fn = Point.Fn;
        this.bits = bits;
    }
    // non-const time multiplication ladder
    _unsafeLadder(elm, n, p = this.ZERO) {
        let d = elm;
        while (n > _0n) {
            if (n & _1n)
                p = p.add(d);
            d = d.double();
            n >>= _1n;
        }
        return p;
    }
    /**
     * Creates a wNAF precomputation window. Used for caching.
     * Default window size is set by `utils.precompute()` and is equal to 8.
     * Number of precomputed points depends on the curve size:
     * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
     * - 𝑊 is the window size
     * - 𝑛 is the bitlength of the curve order.
     * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
     * @param point Point instance
     * @param W window size
     * @returns precomputed point tables flattened to a single array
     */
    precomputeWindow(point, W) {
        const { windows, windowSize } = calcWOpts(W, this.bits);
        const points = [];
        let p = point;
        let base = p;
        for (let window = 0; window < windows; window++) {
            base = p;
            points.push(base);
            // i=1, bc we skip 0
            for (let i = 1; i < windowSize; i++) {
                base = base.add(p);
                points.push(base);
            }
            p = base.double();
        }
        return points;
    }
    /**
     * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
     * More compact implementation:
     * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
     * @returns real and fake (for const-time) points
     */
    wNAF(W, precomputes, n) {
        // Scalar should be smaller than field order
        if (!this.Fn.isValid(n))
            throw new Error('invalid scalar');
        // Accumulators
        let p = this.ZERO;
        let f = this.BASE;
        // This code was first written with assumption that 'f' and 'p' will never be infinity point:
        // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,
        // there is negate now: it is possible that negated element from low value
        // would be the same as high element, which will create carry into next window.
        // It's not obvious how this can fail, but still worth investigating later.
        const wo = calcWOpts(W, this.bits);
        for (let window = 0; window < wo.windows; window++) {
            // (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise
            const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
            n = nextN;
            if (isZero) {
                // bits are 0: add garbage to fake point
                // Important part for const-time getPublicKey: add random "noise" point to f.
                f = f.add(negateCt(isNegF, precomputes[offsetF]));
            }
            else {
                // bits are 1: add to result point
                p = p.add(negateCt(isNeg, precomputes[offset]));
            }
        }
        assert0(n);
        // Return both real and fake points: JIT won't eliminate f.
        // At this point there is a way to F be infinity-point even if p is not,
        // which makes it less const-time: around 1 bigint multiply.
        return { p, f };
    }
    /**
     * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
     * @param acc accumulator point to add result of multiplication
     * @returns point
     */
    wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
        const wo = calcWOpts(W, this.bits);
        for (let window = 0; window < wo.windows; window++) {
            if (n === _0n)
                break; // Early-exit, skip 0 value
            const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
            n = nextN;
            if (isZero) {
                // Window bits are 0: skip processing.
                // Move to next window.
                continue;
            }
            else {
                const item = precomputes[offset];
                acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM
            }
        }
        assert0(n);
        return acc;
    }
    getPrecomputes(W, point, transform) {
        // Calculate precomputes on a first run, reuse them after
        let comp = pointPrecomputes.get(point);
        if (!comp) {
            comp = this.precomputeWindow(point, W);
            if (W !== 1) {
                // Doing transform outside of if brings 15% perf hit
                if (typeof transform === 'function')
                    comp = transform(comp);
                pointPrecomputes.set(point, comp);
            }
        }
        return comp;
    }
    cached(point, scalar, transform) {
        const W = getW(point);
        return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
    }
    unsafe(point, scalar, transform, prev) {
        const W = getW(point);
        if (W === 1)
            return this._unsafeLadder(point, scalar, prev); // For W=1 ladder is ~x2 faster
        return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
    }
    // We calculate precomputes for elliptic curve point multiplication
    // using windowed method. This specifies window size and
    // stores precomputed values. Usually only base point would be precomputed.
    createCache(P, W) {
        validateW(W, this.bits);
        pointWindowSizes.set(P, W);
        pointPrecomputes.delete(P);
    }
    hasCache(elm) {
        return getW(elm) !== 1;
    }
}
/**
 * Endomorphism-specific multiplication for Koblitz curves.
 * Cost: 128 dbl, 0-256 adds.
 */
export function mulEndoUnsafe(Point, point, k1, k2) {
    let acc = point;
    let p1 = Point.ZERO;
    let p2 = Point.ZERO;
    while (k1 > _0n || k2 > _0n) {
        if (k1 & _1n)
            p1 = p1.add(acc);
        if (k2 & _1n)
            p2 = p2.add(acc);
        acc = acc.double();
        k1 >>= _1n;
        k2 >>= _1n;
    }
    return { p1, p2 };
}
/**
 * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).
 * 30x faster vs naive addition on L=4096, 10x faster than precomputes.
 * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.
 * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.
 * @param c Curve Point constructor
 * @param fieldN field over CURVE.N - important that it's not over CURVE.P
 * @param points array of L curve points
 * @param scalars array of L scalars (aka secret keys / bigints)
 */
export function pippenger(c, fieldN, points, scalars) {
    // If we split scalars by some window (let's say 8 bits), every chunk will only
    // take 256 buckets even if there are 4096 scalars, also re-uses double.
    // TODO:
    // - https://eprint.iacr.org/2024/750.pdf
    // - https://tches.iacr.org/index.php/TCHES/article/view/10287
    // 0 is accepted in scalars
    validateMSMPoints(points, c);
    validateMSMScalars(scalars, fieldN);
    const plength = points.length;
    const slength = scalars.length;
    if (plength !== slength)
        throw new Error('arrays of points and scalars must have equal length');
    // if (plength === 0) throw new Error('array must be of length >= 2');
    const zero = c.ZERO;
    const wbits = bitLen(BigInt(plength));
    let windowSize = 1; // bits
    if (wbits > 12)
        windowSize = wbits - 3;
    else if (wbits > 4)
        windowSize = wbits - 2;
    else if (wbits > 0)
        windowSize = 2;
    const MASK = bitMask(windowSize);
    const buckets = new Array(Number(MASK) + 1).fill(zero); // +1 for zero array
    const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;
    let sum = zero;
    for (let i = lastBits; i >= 0; i -= windowSize) {
        buckets.fill(zero);
        for (let j = 0; j < slength; j++) {
            const scalar = scalars[j];
            const wbits = Number((scalar >> BigInt(i)) & MASK);
            buckets[wbits] = buckets[wbits].add(points[j]);
        }
        let resI = zero; // not using this will do small speed-up, but will lose ct
        // Skip first bucket, because it is zero
        for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {
            sumI = sumI.add(buckets[j]);
            resI = resI.add(sumI);
        }
        sum = sum.add(resI);
        if (i !== 0)
            for (let j = 0; j < windowSize; j++)
                sum = sum.double();
    }
    return sum;
}
/**
 * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).
 * @param c Curve Point constructor
 * @param fieldN field over CURVE.N - important that it's not over CURVE.P
 * @param points array of L curve points
 * @returns function which multiplies points with scaars
 */
export function precomputeMSMUnsafe(c, fieldN, points, windowSize) {
    /**
     * Performance Analysis of Window-based Precomputation
     *
     * Base Case (256-bit scalar, 8-bit window):
     * - Standard precomputation requires:
     *   - 31 additions per scalar × 256 scalars = 7,936 ops
     *   - Plus 255 summary additions = 8,191 total ops
     *   Note: Summary additions can be optimized via accumulator
     *
     * Chunked Precomputation Analysis:
     * - Using 32 chunks requires:
     *   - 255 additions per chunk
     *   - 256 doublings
     *   - Total: (255 × 32) + 256 = 8,416 ops
     *
     * Memory Usage Comparison:
     * Window Size | Standard Points | Chunked Points
     * ------------|-----------------|---------------
     *     4-bit   |     520         |      15
     *     8-bit   |    4,224        |     255
     *    10-bit   |   13,824        |   1,023
     *    16-bit   |  557,056        |  65,535
     *
     * Key Advantages:
     * 1. Enables larger window sizes due to reduced memory overhead
     * 2. More efficient for smaller scalar counts:
     *    - 16 chunks: (16 × 255) + 256 = 4,336 ops
     *    - ~2x faster than standard 8,191 ops
     *
     * Limitations:
     * - Not suitable for plain precomputes (requires 256 constant doublings)
     * - Performance degrades with larger scalar counts:
     *   - Optimal for ~256 scalars
     *   - Less efficient for 4096+ scalars (Pippenger preferred)
     */
    validateW(windowSize, fieldN.BITS);
    validateMSMPoints(points, c);
    const zero = c.ZERO;
    const tableSize = 2 ** windowSize - 1; // table size (without zero)
    const chunks = Math.ceil(fieldN.BITS / windowSize); // chunks of item
    const MASK = bitMask(windowSize);
    const tables = points.map((p) => {
        const res = [];
        for (let i = 0, acc = p; i < tableSize; i++) {
            res.push(acc);
            acc = acc.add(p);
        }
        return res;
    });
    return (scalars) => {
        validateMSMScalars(scalars, fieldN);
        if (scalars.length > points.length)
            throw new Error('array of scalars must be smaller than array of points');
        let res = zero;
        for (let i = 0; i < chunks; i++) {
            // No need to double if accumulator is still zero.
            if (res !== zero)
                for (let j = 0; j < windowSize; j++)
                    res = res.double();
            const shiftBy = BigInt(chunks * windowSize - (i + 1) * windowSize);
            for (let j = 0; j < scalars.length; j++) {
                const n = scalars[j];
                const curr = Number((n >> shiftBy) & MASK);
                if (!curr)
                    continue; // skip zero scalars chunks
                res = res.add(tables[j][curr - 1]);
            }
        }
        return res;
    };
}
// TODO: remove
/** @deprecated */
export function validateBasic(curve) {
    validateField(curve.Fp);
    validateObject(curve, {
        n: 'bigint',
        h: 'bigint',
        Gx: 'field',
        Gy: 'field',
    }, {
        nBitLength: 'isSafeInteger',
        nByteLength: 'isSafeInteger',
    });
    // Set defaults
    return Object.freeze({
        ...nLength(curve.n, curve.nBitLength),
        ...curve,
        ...{ p: curve.Fp.ORDER },
    });
}
function createField(order, field, isLE) {
    if (field) {
        if (field.ORDER !== order)
            throw new Error('Field.ORDER must match order: Fp == p, Fn == n');
        validateField(field);
        return field;
    }
    else {
        return Field(order, { isLE });
    }
}
/** Validates CURVE opts and creates fields */
export function _createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
    if (FpFnLE === undefined)
        FpFnLE = type === 'edwards';
    if (!CURVE || typeof CURVE !== 'object')
        throw new Error(`expected valid ${type} CURVE object`);
    for (const p of ['p', 'n', 'h']) {
        const val = CURVE[p];
        if (!(typeof val === 'bigint' && val > _0n))
            throw new Error(`CURVE.${p} must be positive bigint`);
    }
    const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);
    const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
    const _b = type === 'weierstrass' ? 'b' : 'd';
    const params = ['Gx', 'Gy', 'a', _b];
    for (const p of params) {
        // @ts-ignore
        if (!Fp.isValid(CURVE[p]))
            throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
    }
    CURVE = Object.freeze(Object.assign({}, CURVE));
    return { CURVE, Fp, Fn };
}
//# sourceMappingURL=curve.js.mapimport { _validateObject, abytes, bytesToNumberBE, concatBytes, isBytes, isHash, utf8ToBytes, } from "../utils.js";
import { FpInvertBatch, mod } from "./modular.js";
// Octet Stream to Integer. "spec" implementation of os2ip is 2.5x slower vs bytesToNumberBE.
const os2ip = bytesToNumberBE;
// Integer to Octet Stream (numberToBytesBE)
function i2osp(value, length) {
    anum(value);
    anum(length);
    if (value < 0 || value >= 1 << (8 * length))
        throw new Error('invalid I2OSP input: ' + value);
    const res = Array.from({ length }).fill(0);
    for (let i = length - 1; i >= 0; i--) {
        res[i] = value & 0xff;
        value >>>= 8;
    }
    return new Uint8Array(res);
}
function strxor(a, b) {
    const arr = new Uint8Array(a.length);
    for (let i = 0; i < a.length; i++) {
        arr[i] = a[i] ^ b[i];
    }
    return arr;
}
function anum(item) {
    if (!Number.isSafeInteger(item))
        throw new Error('number expected');
}
function normDST(DST) {
    if (!isBytes(DST) && typeof DST !== 'string')
        throw new Error('DST must be Uint8Array or string');
    return typeof DST === 'string' ? utf8ToBytes(DST) : DST;
}
/**
 * Produces a uniformly random byte string using a cryptographic hash function H that outputs b bits.
 * [RFC 9380 5.3.1](https://www.rfc-editor.org/rfc/rfc9380#section-5.3.1).
 */
export function expand_message_xmd(msg, DST, lenInBytes, H) {
    abytes(msg);
    anum(lenInBytes);
    DST = normDST(DST);
    // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3
    if (DST.length > 255)
        DST = H(concatBytes(utf8ToBytes('H2C-OVERSIZE-DST-'), DST));
    const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H;
    const ell = Math.ceil(lenInBytes / b_in_bytes);
    if (lenInBytes > 65535 || ell > 255)
        throw new Error('expand_message_xmd: invalid lenInBytes');
    const DST_prime = concatBytes(DST, i2osp(DST.length, 1));
    const Z_pad = i2osp(0, r_in_bytes);
    const l_i_b_str = i2osp(lenInBytes, 2); // len_in_bytes_str
    const b = new Array(ell);
    const b_0 = H(concatBytes(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));
    b[0] = H(concatBytes(b_0, i2osp(1, 1), DST_prime));
    for (let i = 1; i <= ell; i++) {
        const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime];
        b[i] = H(concatBytes(...args));
    }
    const pseudo_random_bytes = concatBytes(...b);
    return pseudo_random_bytes.slice(0, lenInBytes);
}
/**
 * Produces a uniformly random byte string using an extendable-output function (XOF) H.
 * 1. The collision resistance of H MUST be at least k bits.
 * 2. H MUST be an XOF that has been proved indifferentiable from
 *    a random oracle under a reasonable cryptographic assumption.
 * [RFC 9380 5.3.2](https://www.rfc-editor.org/rfc/rfc9380#section-5.3.2).
 */
export function expand_message_xof(msg, DST, lenInBytes, k, H) {
    abytes(msg);
    anum(lenInBytes);
    DST = normDST(DST);
    // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3
    // DST = H('H2C-OVERSIZE-DST-' || a_very_long_DST, Math.ceil((lenInBytes * k) / 8));
    if (DST.length > 255) {
        const dkLen = Math.ceil((2 * k) / 8);
        DST = H.create({ dkLen }).update(utf8ToBytes('H2C-OVERSIZE-DST-')).update(DST).digest();
    }
    if (lenInBytes > 65535 || DST.length > 255)
        throw new Error('expand_message_xof: invalid lenInBytes');
    return (H.create({ dkLen: lenInBytes })
        .update(msg)
        .update(i2osp(lenInBytes, 2))
        // 2. DST_prime = DST || I2OSP(len(DST), 1)
        .update(DST)
        .update(i2osp(DST.length, 1))
        .digest());
}
/**
 * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F.
 * [RFC 9380 5.2](https://www.rfc-editor.org/rfc/rfc9380#section-5.2).
 * @param msg a byte string containing the message to hash
 * @param count the number of elements of F to output
 * @param options `{DST: string, p: bigint, m: number, k: number, expand: 'xmd' | 'xof', hash: H}`, see above
 * @returns [u_0, ..., u_(count - 1)], a list of field elements.
 */
export function hash_to_field(msg, count, options) {
    _validateObject(options, {
        p: 'bigint',
        m: 'number',
        k: 'number',
        hash: 'function',
    });
    const { p, k, m, hash, expand, DST } = options;
    if (!isHash(options.hash))
        throw new Error('expected valid hash');
    abytes(msg);
    anum(count);
    const log2p = p.toString(2).length;
    const L = Math.ceil((log2p + k) / 8); // section 5.1 of ietf draft link above
    const len_in_bytes = count * m * L;
    let prb; // pseudo_random_bytes
    if (expand === 'xmd') {
        prb = expand_message_xmd(msg, DST, len_in_bytes, hash);
    }
    else if (expand === 'xof') {
        prb = expand_message_xof(msg, DST, len_in_bytes, k, hash);
    }
    else if (expand === '_internal_pass') {
        // for internal tests only
        prb = msg;
    }
    else {
        throw new Error('expand must be "xmd" or "xof"');
    }
    const u = new Array(count);
    for (let i = 0; i < count; i++) {
        const e = new Array(m);
        for (let j = 0; j < m; j++) {
            const elm_offset = L * (j + i * m);
            const tv = prb.subarray(elm_offset, elm_offset + L);
            e[j] = mod(os2ip(tv), p);
        }
        u[i] = e;
    }
    return u;
}
export function isogenyMap(field, map) {
    // Make same order as in spec
    const coeff = map.map((i) => Array.from(i).reverse());
    return (x, y) => {
        const [xn, xd, yn, yd] = coeff.map((val) => val.reduce((acc, i) => field.add(field.mul(acc, x), i)));
        // 6.6.3
        // Exceptional cases of iso_map are inputs that cause the denominator of
        // either rational function to evaluate to zero; such cases MUST return
        // the identity point on E.
        const [xd_inv, yd_inv] = FpInvertBatch(field, [xd, yd], true);
        x = field.mul(xn, xd_inv); // xNum / xDen
        y = field.mul(y, field.mul(yn, yd_inv)); // y * (yNum / yDev)
        return { x, y };
    };
}
export const _DST_scalar = utf8ToBytes('HashToScalar-');
/** Creates hash-to-curve methods from EC Point and mapToCurve function. See {@link H2CHasher}. */
export function createHasher(Point, mapToCurve, defaults) {
    if (typeof mapToCurve !== 'function')
        throw new Error('mapToCurve() must be defined');
    function map(num) {
        return Point.fromAffine(mapToCurve(num));
    }
    function clear(initial) {
        const P = initial.clearCofactor();
        if (P.equals(Point.ZERO))
            return Point.ZERO; // zero will throw in assert
        P.assertValidity();
        return P;
    }
    return {
        defaults,
        hashToCurve(msg, options) {
            const opts = Object.assign({}, defaults, options);
            const u = hash_to_field(msg, 2, opts);
            const u0 = map(u[0]);
            const u1 = map(u[1]);
            return clear(u0.add(u1));
        },
        encodeToCurve(msg, options) {
            const optsDst = defaults.encodeDST ? { DST: defaults.encodeDST } : {};
            const opts = Object.assign({}, defaults, optsDst, options);
            const u = hash_to_field(msg, 1, opts);
            const u0 = map(u[0]);
            return clear(u0);
        },
        /** See {@link H2CHasher} */
        mapToCurve(scalars) {
            if (!Array.isArray(scalars))
                throw new Error('expected array of bigints');
            for (const i of scalars)
                if (typeof i !== 'bigint')
                    throw new Error('expected array of bigints');
            return clear(map(scalars));
        },
        // hash_to_scalar can produce 0: https://www.rfc-editor.org/errata/eid8393
        // RFC 9380, draft-irtf-cfrg-bbs-signatures-08
        hashToScalar(msg, options) {
            // @ts-ignore
            const N = Point.Fn.ORDER;
            const opts = Object.assign({}, defaults, { p: N, m: 1, DST: _DST_scalar }, options);
            return hash_to_field(msg, 1, opts)[0][0];
        },
    };
}
//# sourceMappingURL=hash-to-curve.js.map/**
 * Utils for modular division and fields.
 * Field over 11 is a finite (Galois) field is integer number operations `mod 11`.
 * There is no division: it is replaced by modular multiplicative inverse.
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { _validateObject, anumber, bitMask, bytesToNumberBE, bytesToNumberLE, ensureBytes, numberToBytesBE, numberToBytesLE, } from "../utils.js";
// prettier-ignore
const _0n = BigInt(0), _1n = BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3);
// prettier-ignore
const _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5), _7n = /* @__PURE__ */ BigInt(7);
// prettier-ignore
const _8n = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9), _16n = /* @__PURE__ */ BigInt(16);
// Calculates a modulo b
export function mod(a, b) {
    const result = a % b;
    return result >= _0n ? result : b + result;
}
/**
 * Efficiently raise num to power and do modular division.
 * Unsafe in some contexts: uses ladder, so can expose bigint bits.
 * @example
 * pow(2n, 6n, 11n) // 64n % 11n == 9n
 */
export function pow(num, power, modulo) {
    return FpPow(Field(modulo), num, power);
}
/** Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)` */
export function pow2(x, power, modulo) {
    let res = x;
    while (power-- > _0n) {
        res *= res;
        res %= modulo;
    }
    return res;
}
/**
 * Inverses number over modulo.
 * Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).
 */
export function invert(number, modulo) {
    if (number === _0n)
        throw new Error('invert: expected non-zero number');
    if (modulo <= _0n)
        throw new Error('invert: expected positive modulus, got ' + modulo);
    // Fermat's little theorem "CT-like" version inv(n) = n^(m-2) mod m is 30x slower.
    let a = mod(number, modulo);
    let b = modulo;
    // prettier-ignore
    let x = _0n, y = _1n, u = _1n, v = _0n;
    while (a !== _0n) {
        // JIT applies optimization if those two lines follow each other
        const q = b / a;
        const r = b % a;
        const m = x - u * q;
        const n = y - v * q;
        // prettier-ignore
        b = a, a = r, x = u, y = v, u = m, v = n;
    }
    const gcd = b;
    if (gcd !== _1n)
        throw new Error('invert: does not exist');
    return mod(x, modulo);
}
function assertIsSquare(Fp, root, n) {
    if (!Fp.eql(Fp.sqr(root), n))
        throw new Error('Cannot find square root');
}
// Not all roots are possible! Example which will throw:
// const NUM =
// n = 72057594037927816n;
// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));
function sqrt3mod4(Fp, n) {
    const p1div4 = (Fp.ORDER + _1n) / _4n;
    const root = Fp.pow(n, p1div4);
    assertIsSquare(Fp, root, n);
    return root;
}
function sqrt5mod8(Fp, n) {
    const p5div8 = (Fp.ORDER - _5n) / _8n;
    const n2 = Fp.mul(n, _2n);
    const v = Fp.pow(n2, p5div8);
    const nv = Fp.mul(n, v);
    const i = Fp.mul(Fp.mul(nv, _2n), v);
    const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
    assertIsSquare(Fp, root, n);
    return root;
}
// Based on RFC9380, Kong algorithm
// prettier-ignore
function sqrt9mod16(P) {
    const Fp_ = Field(P);
    const tn = tonelliShanks(P);
    const c1 = tn(Fp_, Fp_.neg(Fp_.ONE)); //  1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F
    const c2 = tn(Fp_, c1); //  2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F
    const c3 = tn(Fp_, Fp_.neg(c1)); //  3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F
    const c4 = (P + _7n) / _16n; //  4. c4 = (q + 7) / 16        # Integer arithmetic
    return (Fp, n) => {
        let tv1 = Fp.pow(n, c4); //  1. tv1 = x^c4
        let tv2 = Fp.mul(tv1, c1); //  2. tv2 = c1 * tv1
        const tv3 = Fp.mul(tv1, c2); //  3. tv3 = c2 * tv1
        const tv4 = Fp.mul(tv1, c3); //  4. tv4 = c3 * tv1
        const e1 = Fp.eql(Fp.sqr(tv2), n); //  5.  e1 = (tv2^2) == x
        const e2 = Fp.eql(Fp.sqr(tv3), n); //  6.  e2 = (tv3^2) == x
        tv1 = Fp.cmov(tv1, tv2, e1); //  7. tv1 = CMOV(tv1, tv2, e1)  # Select tv2 if (tv2^2) == x
        tv2 = Fp.cmov(tv4, tv3, e2); //  8. tv2 = CMOV(tv4, tv3, e2)  # Select tv3 if (tv3^2) == x
        const e3 = Fp.eql(Fp.sqr(tv2), n); //  9.  e3 = (tv2^2) == x
        const root = Fp.cmov(tv1, tv2, e3); // 10.  z = CMOV(tv1, tv2, e3)   # Select sqrt from tv1 & tv2
        assertIsSquare(Fp, root, n);
        return root;
    };
}
/**
 * Tonelli-Shanks square root search algorithm.
 * 1. https://eprint.iacr.org/2012/685.pdf (page 12)
 * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks
 * @param P field order
 * @returns function that takes field Fp (created from P) and number n
 */
export function tonelliShanks(P) {
    // Initialization (precomputation).
    // Caching initialization could boost perf by 7%.
    if (P < _3n)
        throw new Error('sqrt is not defined for small field');
    // Factor P - 1 = Q * 2^S, where Q is odd
    let Q = P - _1n;
    let S = 0;
    while (Q % _2n === _0n) {
        Q /= _2n;
        S++;
    }
    // Find the first quadratic non-residue Z >= 2
    let Z = _2n;
    const _Fp = Field(P);
    while (FpLegendre(_Fp, Z) === 1) {
        // Basic primality test for P. After x iterations, chance of
        // not finding quadratic non-residue is 2^x, so 2^1000.
        if (Z++ > 1000)
            throw new Error('Cannot find square root: probably non-prime P');
    }
    // Fast-path; usually done before Z, but we do "primality test".
    if (S === 1)
        return sqrt3mod4;
    // Slow-path
    // TODO: test on Fp2 and others
    let cc = _Fp.pow(Z, Q); // c = z^Q
    const Q1div2 = (Q + _1n) / _2n;
    return function tonelliSlow(Fp, n) {
        if (Fp.is0(n))
            return n;
        // Check if n is a quadratic residue using Legendre symbol
        if (FpLegendre(Fp, n) !== 1)
            throw new Error('Cannot find square root');
        // Initialize variables for the main loop
        let M = S;
        let c = Fp.mul(Fp.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp
        let t = Fp.pow(n, Q); // t = n^Q, first guess at the fudge factor
        let R = Fp.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root
        // Main loop
        // while t != 1
        while (!Fp.eql(t, Fp.ONE)) {
            if (Fp.is0(t))
                return Fp.ZERO; // if t=0 return R=0
            let i = 1;
            // Find the smallest i >= 1 such that t^(2^i) ≡ 1 (mod P)
            let t_tmp = Fp.sqr(t); // t^(2^1)
            while (!Fp.eql(t_tmp, Fp.ONE)) {
                i++;
                t_tmp = Fp.sqr(t_tmp); // t^(2^2)...
                if (i === M)
                    throw new Error('Cannot find square root');
            }
            // Calculate the exponent for b: 2^(M - i - 1)
            const exponent = _1n << BigInt(M - i - 1); // bigint is important
            const b = Fp.pow(c, exponent); // b = 2^(M - i - 1)
            // Update variables
            M = i;
            c = Fp.sqr(b); // c = b^2
            t = Fp.mul(t, c); // t = (t * b^2)
            R = Fp.mul(R, b); // R = R*b
        }
        return R;
    };
}
/**
 * Square root for a finite field. Will try optimized versions first:
 *
 * 1. P ≡ 3 (mod 4)
 * 2. P ≡ 5 (mod 8)
 * 3. P ≡ 9 (mod 16)
 * 4. Tonelli-Shanks algorithm
 *
 * Different algorithms can give different roots, it is up to user to decide which one they want.
 * For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).
 */
export function FpSqrt(P) {
    // P ≡ 3 (mod 4) => √n = n^((P+1)/4)
    if (P % _4n === _3n)
        return sqrt3mod4;
    // P ≡ 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf
    if (P % _8n === _5n)
        return sqrt5mod8;
    // P ≡ 9 (mod 16) => Kong algorithm, page 11 of https://eprint.iacr.org/2012/685.pdf (algorithm 4)
    if (P % _16n === _9n)
        return sqrt9mod16(P);
    // Tonelli-Shanks algorithm
    return tonelliShanks(P);
}
// Little-endian check for first LE bit (last BE bit);
export const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n;
// prettier-ignore
const FIELD_FIELDS = [
    'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',
    'eql', 'add', 'sub', 'mul', 'pow', 'div',
    'addN', 'subN', 'mulN', 'sqrN'
];
export function validateField(field) {
    const initial = {
        ORDER: 'bigint',
        MASK: 'bigint',
        BYTES: 'number',
        BITS: 'number',
    };
    const opts = FIELD_FIELDS.reduce((map, val) => {
        map[val] = 'function';
        return map;
    }, initial);
    _validateObject(field, opts);
    // const max = 16384;
    // if (field.BYTES < 1 || field.BYTES > max) throw new Error('invalid field');
    // if (field.BITS < 1 || field.BITS > 8 * max) throw new Error('invalid field');
    return field;
}
// Generic field functions
/**
 * Same as `pow` but for Fp: non-constant-time.
 * Unsafe in some contexts: uses ladder, so can expose bigint bits.
 */
export function FpPow(Fp, num, power) {
    if (power < _0n)
        throw new Error('invalid exponent, negatives unsupported');
    if (power === _0n)
        return Fp.ONE;
    if (power === _1n)
        return num;
    let p = Fp.ONE;
    let d = num;
    while (power > _0n) {
        if (power & _1n)
            p = Fp.mul(p, d);
        d = Fp.sqr(d);
        power >>= _1n;
    }
    return p;
}
/**
 * Efficiently invert an array of Field elements.
 * Exception-free. Will return `undefined` for 0 elements.
 * @param passZero map 0 to 0 (instead of undefined)
 */
export function FpInvertBatch(Fp, nums, passZero = false) {
    const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : undefined);
    // Walk from first to last, multiply them by each other MOD p
    const multipliedAcc = nums.reduce((acc, num, i) => {
        if (Fp.is0(num))
            return acc;
        inverted[i] = acc;
        return Fp.mul(acc, num);
    }, Fp.ONE);
    // Invert last element
    const invertedAcc = Fp.inv(multipliedAcc);
    // Walk from last to first, multiply them by inverted each other MOD p
    nums.reduceRight((acc, num, i) => {
        if (Fp.is0(num))
            return acc;
        inverted[i] = Fp.mul(acc, inverted[i]);
        return Fp.mul(acc, num);
    }, invertedAcc);
    return inverted;
}
// TODO: remove
export function FpDiv(Fp, lhs, rhs) {
    return Fp.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, Fp.ORDER) : Fp.inv(rhs));
}
/**
 * Legendre symbol.
 * Legendre constant is used to calculate Legendre symbol (a | p)
 * which denotes the value of a^((p-1)/2) (mod p).
 *
 * * (a | p) ≡ 1    if a is a square (mod p), quadratic residue
 * * (a | p) ≡ -1   if a is not a square (mod p), quadratic non residue
 * * (a | p) ≡ 0    if a ≡ 0 (mod p)
 */
export function FpLegendre(Fp, n) {
    // We can use 3rd argument as optional cache of this value
    // but seems unneeded for now. The operation is very fast.
    const p1mod2 = (Fp.ORDER - _1n) / _2n;
    const powered = Fp.pow(n, p1mod2);
    const yes = Fp.eql(powered, Fp.ONE);
    const zero = Fp.eql(powered, Fp.ZERO);
    const no = Fp.eql(powered, Fp.neg(Fp.ONE));
    if (!yes && !zero && !no)
        throw new Error('invalid Legendre symbol result');
    return yes ? 1 : zero ? 0 : -1;
}
// This function returns True whenever the value x is a square in the field F.
export function FpIsSquare(Fp, n) {
    const l = FpLegendre(Fp, n);
    return l === 1;
}
// CURVE.n lengths
export function nLength(n, nBitLength) {
    // Bit size, byte size of CURVE.n
    if (nBitLength !== undefined)
        anumber(nBitLength);
    const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;
    const nByteLength = Math.ceil(_nBitLength / 8);
    return { nBitLength: _nBitLength, nByteLength };
}
/**
 * Creates a finite field. Major performance optimizations:
 * * 1. Denormalized operations like mulN instead of mul.
 * * 2. Identical object shape: never add or remove keys.
 * * 3. `Object.freeze`.
 * Fragile: always run a benchmark on a change.
 * Security note: operations don't check 'isValid' for all elements for performance reasons,
 * it is caller responsibility to check this.
 * This is low-level code, please make sure you know what you're doing.
 *
 * Note about field properties:
 * * CHARACTERISTIC p = prime number, number of elements in main subgroup.
 * * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.
 *
 * @param ORDER field order, probably prime, or could be composite
 * @param bitLen how many bits the field consumes
 * @param isLE (default: false) if encoding / decoding should be in little-endian
 * @param redef optional faster redefinitions of sqrt and other methods
 */
export function Field(ORDER, bitLenOrOpts, // TODO: use opts only in v2?
isLE = false, opts = {}) {
    if (ORDER <= _0n)
        throw new Error('invalid field: expected ORDER > 0, got ' + ORDER);
    let _nbitLength = undefined;
    let _sqrt = undefined;
    let modFromBytes = false;
    let allowedLengths = undefined;
    if (typeof bitLenOrOpts === 'object' && bitLenOrOpts != null) {
        if (opts.sqrt || isLE)
            throw new Error('cannot specify opts in two arguments');
        const _opts = bitLenOrOpts;
        if (_opts.BITS)
            _nbitLength = _opts.BITS;
        if (_opts.sqrt)
            _sqrt = _opts.sqrt;
        if (typeof _opts.isLE === 'boolean')
            isLE = _opts.isLE;
        if (typeof _opts.modFromBytes === 'boolean')
            modFromBytes = _opts.modFromBytes;
        allowedLengths = _opts.allowedLengths;
    }
    else {
        if (typeof bitLenOrOpts === 'number')
            _nbitLength = bitLenOrOpts;
        if (opts.sqrt)
            _sqrt = opts.sqrt;
    }
    const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, _nbitLength);
    if (BYTES > 2048)
        throw new Error('invalid field: expected ORDER of <= 2048 bytes');
    let sqrtP; // cached sqrtP
    const f = Object.freeze({
        ORDER,
        isLE,
        BITS,
        BYTES,
        MASK: bitMask(BITS),
        ZERO: _0n,
        ONE: _1n,
        allowedLengths: allowedLengths,
        create: (num) => mod(num, ORDER),
        isValid: (num) => {
            if (typeof num !== 'bigint')
                throw new Error('invalid field element: expected bigint, got ' + typeof num);
            return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible
        },
        is0: (num) => num === _0n,
        // is valid and invertible
        isValidNot0: (num) => !f.is0(num) && f.isValid(num),
        isOdd: (num) => (num & _1n) === _1n,
        neg: (num) => mod(-num, ORDER),
        eql: (lhs, rhs) => lhs === rhs,
        sqr: (num) => mod(num * num, ORDER),
        add: (lhs, rhs) => mod(lhs + rhs, ORDER),
        sub: (lhs, rhs) => mod(lhs - rhs, ORDER),
        mul: (lhs, rhs) => mod(lhs * rhs, ORDER),
        pow: (num, power) => FpPow(f, num, power),
        div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),
        // Same as above, but doesn't normalize
        sqrN: (num) => num * num,
        addN: (lhs, rhs) => lhs + rhs,
        subN: (lhs, rhs) => lhs - rhs,
        mulN: (lhs, rhs) => lhs * rhs,
        inv: (num) => invert(num, ORDER),
        sqrt: _sqrt ||
            ((n) => {
                if (!sqrtP)
                    sqrtP = FpSqrt(ORDER);
                return sqrtP(f, n);
            }),
        toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),
        fromBytes: (bytes, skipValidation = true) => {
            if (allowedLengths) {
                if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
                    throw new Error('Field.fromBytes: expected ' + allowedLengths + ' bytes, got ' + bytes.length);
                }
                const padded = new Uint8Array(BYTES);
                // isLE add 0 to right, !isLE to the left.
                padded.set(bytes, isLE ? 0 : padded.length - bytes.length);
                bytes = padded;
            }
            if (bytes.length !== BYTES)
                throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);
            let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
            if (modFromBytes)
                scalar = mod(scalar, ORDER);
            if (!skipValidation)
                if (!f.isValid(scalar))
                    throw new Error('invalid field element: outside of range 0..ORDER');
            // NOTE: we don't validate scalar here, please use isValid. This done such way because some
            // protocol may allow non-reduced scalar that reduced later or changed some other way.
            return scalar;
        },
        // TODO: we don't need it here, move out to separate fn
        invertBatch: (lst) => FpInvertBatch(f, lst),
        // We can't move this out because Fp6, Fp12 implement it
        // and it's unclear what to return in there.
        cmov: (a, b, c) => (c ? b : a),
    });
    return Object.freeze(f);
}
// Generic random scalar, we can do same for other fields if via Fp2.mul(Fp2.ONE, Fp2.random)?
// This allows unsafe methods like ignore bias or zero. These unsafe, but often used in different protocols (if deterministic RNG).
// which mean we cannot force this via opts.
// Not sure what to do with randomBytes, we can accept it inside opts if wanted.
// Probably need to export getMinHashLength somewhere?
// random(bytes?: Uint8Array, unsafeAllowZero = false, unsafeAllowBias = false) {
//   const LEN = !unsafeAllowBias ? getMinHashLength(ORDER) : BYTES;
//   if (bytes === undefined) bytes = randomBytes(LEN); // _opts.randomBytes?
//   const num = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
//   // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0
//   const reduced = unsafeAllowZero ? mod(num, ORDER) : mod(num, ORDER - _1n) + _1n;
//   return reduced;
// },
export function FpSqrtOdd(Fp, elm) {
    if (!Fp.isOdd)
        throw new Error("Field doesn't have isOdd");
    const root = Fp.sqrt(elm);
    return Fp.isOdd(root) ? root : Fp.neg(root);
}
export function FpSqrtEven(Fp, elm) {
    if (!Fp.isOdd)
        throw new Error("Field doesn't have isOdd");
    const root = Fp.sqrt(elm);
    return Fp.isOdd(root) ? Fp.neg(root) : root;
}
/**
 * "Constant-time" private key generation utility.
 * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field).
 * Which makes it slightly more biased, less secure.
 * @deprecated use `mapKeyToField` instead
 */
export function hashToPrivateScalar(hash, groupOrder, isLE = false) {
    hash = ensureBytes('privateHash', hash);
    const hashLen = hash.length;
    const minLen = nLength(groupOrder).nByteLength + 8;
    if (minLen < 24 || hashLen < minLen || hashLen > 1024)
        throw new Error('hashToPrivateScalar: expected ' + minLen + '-1024 bytes of input, got ' + hashLen);
    const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash);
    return mod(num, groupOrder - _1n) + _1n;
}
/**
 * Returns total number of bytes consumed by the field element.
 * For example, 32 bytes for usual 256-bit weierstrass curve.
 * @param fieldOrder number of field elements, usually CURVE.n
 * @returns byte length of field
 */
export function getFieldBytesLength(fieldOrder) {
    if (typeof fieldOrder !== 'bigint')
        throw new Error('field order must be bigint');
    const bitLength = fieldOrder.toString(2).length;
    return Math.ceil(bitLength / 8);
}
/**
 * Returns minimal amount of bytes that can be safely reduced
 * by field order.
 * Should be 2^-128 for 128-bit curve such as P256.
 * @param fieldOrder number of field elements, usually CURVE.n
 * @returns byte length of target hash
 */
export function getMinHashLength(fieldOrder) {
    const length = getFieldBytesLength(fieldOrder);
    return length + Math.ceil(length / 2);
}
/**
 * "Constant-time" private key generation utility.
 * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF
 * and convert them into private scalar, with the modulo bias being negligible.
 * Needs at least 48 bytes of input for 32-byte private key.
 * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/
 * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final
 * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5
 * @param hash hash output from SHA3 or a similar function
 * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)
 * @param isLE interpret hash bytes as LE num
 * @returns valid private scalar
 */
export function mapHashToField(key, fieldOrder, isLE = false) {
    const len = key.length;
    const fieldLen = getFieldBytesLength(fieldOrder);
    const minLen = getMinHashLength(fieldOrder);
    // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.
    if (len < 16 || len < minLen || len > 1024)
        throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);
    const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);
    // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0
    const reduced = mod(num, fieldOrder - _1n) + _1n;
    return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
}
//# sourceMappingURL=modular.js.map/**
 * Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.
 *
 * ### Design rationale for types
 *
 * * Interaction between classes from different curves should fail:
 *   `k256.Point.BASE.add(p256.Point.BASE)`
 * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime
 * * Different calls of `curve()` would return different classes -
 *   `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,
 *   it won't affect others
 *
 * TypeScript can't infer types for classes created inside a function. Classes is one instance
 * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create
 * unique type for every function call.
 *
 * We can use generic types via some param, like curve opts, but that would:
 *     1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)
 *     which is hard to debug.
 *     2. Params can be generic and we can't enforce them to be constant value:
 *     if somebody creates curve from non-constant params,
 *     it would be allowed to interact with other curves with non-constant params
 *
 * @todo https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { hmac as nobleHmac } from '@noble/hashes/hmac.js';
import { ahash } from '@noble/hashes/utils';
import { _validateObject, _abool2 as abool, _abytes2 as abytes, aInRange, bitLen, bitMask, bytesToHex, bytesToNumberBE, concatBytes, createHmacDrbg, ensureBytes, hexToBytes, inRange, isBytes, memoized, numberToHexUnpadded, randomBytes as randomBytesWeb, } from "../utils.js";
import { _createCurveFields, mulEndoUnsafe, negateCt, normalizeZ, pippenger, wNAF, } from "./curve.js";
import { Field, FpInvertBatch, getMinHashLength, mapHashToField, nLength, validateField, } from "./modular.js";
// We construct basis in such way that den is always positive and equals n, but num sign depends on basis (not on secret value)
const divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n) / den;
/**
 * Splits scalar for GLV endomorphism.
 */
export function _splitEndoScalar(k, basis, n) {
    // Split scalar into two such that part is ~half bits: `abs(part) < sqrt(N)`
    // Since part can be negative, we need to do this on point.
    // TODO: verifyScalar function which consumes lambda
    const [[a1, b1], [a2, b2]] = basis;
    const c1 = divNearest(b2 * k, n);
    const c2 = divNearest(-b1 * k, n);
    // |k1|/|k2| is < sqrt(N), but can be negative.
    // If we do `k1 mod N`, we'll get big scalar (`> sqrt(N)`): so, we do cheaper negation instead.
    let k1 = k - c1 * a1 - c2 * a2;
    let k2 = -c1 * b1 - c2 * b2;
    const k1neg = k1 < _0n;
    const k2neg = k2 < _0n;
    if (k1neg)
        k1 = -k1;
    if (k2neg)
        k2 = -k2;
    // Double check that resulting scalar less than half bits of N: otherwise wNAF will fail.
    // This should only happen on wrong basises. Also, math inside is too complex and I don't trust it.
    const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n; // Half bits of N
    if (k1 < _0n || k1 >= MAX_NUM || k2 < _0n || k2 >= MAX_NUM) {
        throw new Error('splitScalar (endomorphism): failed, k=' + k);
    }
    return { k1neg, k1, k2neg, k2 };
}
function validateSigFormat(format) {
    if (!['compact', 'recovered', 'der'].includes(format))
        throw new Error('Signature format must be "compact", "recovered", or "der"');
    return format;
}
function validateSigOpts(opts, def) {
    const optsn = {};
    for (let optName of Object.keys(def)) {
        // @ts-ignore
        optsn[optName] = opts[optName] === undefined ? def[optName] : opts[optName];
    }
    abool(optsn.lowS, 'lowS');
    abool(optsn.prehash, 'prehash');
    if (optsn.format !== undefined)
        validateSigFormat(optsn.format);
    return optsn;
}
export class DERErr extends Error {
    constructor(m = '') {
        super(m);
    }
}
/**
 * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:
 *
 *     [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]
 *
 * Docs: https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/, https://luca.ntop.org/Teaching/Appunti/asn1.html
 */
export const DER = {
    // asn.1 DER encoding utils
    Err: DERErr,
    // Basic building block is TLV (Tag-Length-Value)
    _tlv: {
        encode: (tag, data) => {
            const { Err: E } = DER;
            if (tag < 0 || tag > 256)
                throw new E('tlv.encode: wrong tag');
            if (data.length & 1)
                throw new E('tlv.encode: unpadded data');
            const dataLen = data.length / 2;
            const len = numberToHexUnpadded(dataLen);
            if ((len.length / 2) & 128)
                throw new E('tlv.encode: long form length too big');
            // length of length with long form flag
            const lenLen = dataLen > 127 ? numberToHexUnpadded((len.length / 2) | 128) : '';
            const t = numberToHexUnpadded(tag);
            return t + lenLen + len + data;
        },
        // v - value, l - left bytes (unparsed)
        decode(tag, data) {
            const { Err: E } = DER;
            let pos = 0;
            if (tag < 0 || tag > 256)
                throw new E('tlv.encode: wrong tag');
            if (data.length < 2 || data[pos++] !== tag)
                throw new E('tlv.decode: wrong tlv');
            const first = data[pos++];
            const isLong = !!(first & 128); // First bit of first length byte is flag for short/long form
            let length = 0;
            if (!isLong)
                length = first;
            else {
                // Long form: [longFlag(1bit), lengthLength(7bit), length (BE)]
                const lenLen = first & 127;
                if (!lenLen)
                    throw new E('tlv.decode(long): indefinite length not supported');
                if (lenLen > 4)
                    throw new E('tlv.decode(long): byte length is too big'); // this will overflow u32 in js
                const lengthBytes = data.subarray(pos, pos + lenLen);
                if (lengthBytes.length !== lenLen)
                    throw new E('tlv.decode: length bytes not complete');
                if (lengthBytes[0] === 0)
                    throw new E('tlv.decode(long): zero leftmost byte');
                for (const b of lengthBytes)
                    length = (length << 8) | b;
                pos += lenLen;
                if (length < 128)
                    throw new E('tlv.decode(long): not minimal encoding');
            }
            const v = data.subarray(pos, pos + length);
            if (v.length !== length)
                throw new E('tlv.decode: wrong value length');
            return { v, l: data.subarray(pos + length) };
        },
    },
    // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
    // since we always use positive integers here. It must always be empty:
    // - add zero byte if exists
    // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
    _int: {
        encode(num) {
            const { Err: E } = DER;
            if (num < _0n)
                throw new E('integer: negative integers are not allowed');
            let hex = numberToHexUnpadded(num);
            // Pad with zero byte if negative flag is present
            if (Number.parseInt(hex[0], 16) & 0b1000)
                hex = '00' + hex;
            if (hex.length & 1)
                throw new E('unexpected DER parsing assertion: unpadded hex');
            return hex;
        },
        decode(data) {
            const { Err: E } = DER;
            if (data[0] & 128)
                throw new E('invalid signature integer: negative');
            if (data[0] === 0x00 && !(data[1] & 128))
                throw new E('invalid signature integer: unnecessary leading zero');
            return bytesToNumberBE(data);
        },
    },
    toSig(hex) {
        // parse DER signature
        const { Err: E, _int: int, _tlv: tlv } = DER;
        const data = ensureBytes('signature', hex);
        const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);
        if (seqLeftBytes.length)
            throw new E('invalid signature: left bytes after parsing');
        const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);
        const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);
        if (sLeftBytes.length)
            throw new E('invalid signature: left bytes after parsing');
        return { r: int.decode(rBytes), s: int.decode(sBytes) };
    },
    hexFromSig(sig) {
        const { _tlv: tlv, _int: int } = DER;
        const rs = tlv.encode(0x02, int.encode(sig.r));
        const ss = tlv.encode(0x02, int.encode(sig.s));
        const seq = rs + ss;
        return tlv.encode(0x30, seq);
    },
};
// Be friendly to bad ECMAScript parsers by not using bigint literals
// prettier-ignore
const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4);
export function _normFnElement(Fn, key) {
    const { BYTES: expected } = Fn;
    let num;
    if (typeof key === 'bigint') {
        num = key;
    }
    else {
        let bytes = ensureBytes('private key', key);
        try {
            num = Fn.fromBytes(bytes);
        }
        catch (error) {
            throw new Error(`invalid private key: expected ui8a of size ${expected}, got ${typeof key}`);
        }
    }
    if (!Fn.isValidNot0(num))
        throw new Error('invalid private key: out of range [1..N-1]');
    return num;
}
/**
 * Creates weierstrass Point constructor, based on specified curve options.
 *
 * @example
```js
const opts = {
  p: BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff'),
  n: BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551'),
  h: BigInt(1),
  a: BigInt('0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc'),
  b: BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b'),
  Gx: BigInt('0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296'),
  Gy: BigInt('0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5'),
};
const p256_Point = weierstrass(opts);
```
 */
export function weierstrassN(params, extraOpts = {}) {
    const validated = _createCurveFields('weierstrass', params, extraOpts);
    const { Fp, Fn } = validated;
    let CURVE = validated.CURVE;
    const { h: cofactor, n: CURVE_ORDER } = CURVE;
    _validateObject(extraOpts, {}, {
        allowInfinityPoint: 'boolean',
        clearCofactor: 'function',
        isTorsionFree: 'function',
        fromBytes: 'function',
        toBytes: 'function',
        endo: 'object',
        wrapPrivateKey: 'boolean',
    });
    const { endo } = extraOpts;
    if (endo) {
        // validateObject(endo, { beta: 'bigint', splitScalar: 'function' });
        if (!Fp.is0(CURVE.a) || typeof endo.beta !== 'bigint' || !Array.isArray(endo.basises)) {
            throw new Error('invalid endo: expected "beta": bigint and "basises": array');
        }
    }
    const lengths = getWLengths(Fp, Fn);
    function assertCompressionIsSupported() {
        if (!Fp.isOdd)
            throw new Error('compression is not supported: Field does not have .isOdd()');
    }
    // Implements IEEE P1363 point encoding
    function pointToBytes(_c, point, isCompressed) {
        const { x, y } = point.toAffine();
        const bx = Fp.toBytes(x);
        abool(isCompressed, 'isCompressed');
        if (isCompressed) {
            assertCompressionIsSupported();
            const hasEvenY = !Fp.isOdd(y);
            return concatBytes(pprefix(hasEvenY), bx);
        }
        else {
            return concatBytes(Uint8Array.of(0x04), bx, Fp.toBytes(y));
        }
    }
    function pointFromBytes(bytes) {
        abytes(bytes, undefined, 'Point');
        const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths; // e.g. for 32-byte: 33, 65
        const length = bytes.length;
        const head = bytes[0];
        const tail = bytes.subarray(1);
        // No actual validation is done here: use .assertValidity()
        if (length === comp && (head === 0x02 || head === 0x03)) {
            const x = Fp.fromBytes(tail);
            if (!Fp.isValid(x))
                throw new Error('bad point: is not on curve, wrong x');
            const y2 = weierstrassEquation(x); // y² = x³ + ax + b
            let y;
            try {
                y = Fp.sqrt(y2); // y = y² ^ (p+1)/4
            }
            catch (sqrtError) {
                const err = sqrtError instanceof Error ? ': ' + sqrtError.message : '';
                throw new Error('bad point: is not on curve, sqrt error' + err);
            }
            assertCompressionIsSupported();
            const isYOdd = Fp.isOdd(y); // (y & _1n) === _1n;
            const isHeadOdd = (head & 1) === 1; // ECDSA-specific
            if (isHeadOdd !== isYOdd)
                y = Fp.neg(y);
            return { x, y };
        }
        else if (length === uncomp && head === 0x04) {
            // TODO: more checks
            const L = Fp.BYTES;
            const x = Fp.fromBytes(tail.subarray(0, L));
            const y = Fp.fromBytes(tail.subarray(L, L * 2));
            if (!isValidXY(x, y))
                throw new Error('bad point: is not on curve');
            return { x, y };
        }
        else {
            throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);
        }
    }
    const encodePoint = extraOpts.toBytes || pointToBytes;
    const decodePoint = extraOpts.fromBytes || pointFromBytes;
    function weierstrassEquation(x) {
        const x2 = Fp.sqr(x); // x * x
        const x3 = Fp.mul(x2, x); // x² * x
        return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b); // x³ + a * x + b
    }
    // TODO: move top-level
    /** Checks whether equation holds for given x, y: y² == x³ + ax + b */
    function isValidXY(x, y) {
        const left = Fp.sqr(y); // y²
        const right = weierstrassEquation(x); // x³ + ax + b
        return Fp.eql(left, right);
    }
    // Validate whether the passed curve params are valid.
    // Test 1: equation y² = x³ + ax + b should work for generator point.
    if (!isValidXY(CURVE.Gx, CURVE.Gy))
        throw new Error('bad curve params: generator point');
    // Test 2: discriminant Δ part should be non-zero: 4a³ + 27b² != 0.
    // Guarantees curve is genus-1, smooth (non-singular).
    const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n), _4n);
    const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));
    if (Fp.is0(Fp.add(_4a3, _27b2)))
        throw new Error('bad curve params: a or b');
    /** Asserts coordinate is valid: 0 <= n < Fp.ORDER. */
    function acoord(title, n, banZero = false) {
        if (!Fp.isValid(n) || (banZero && Fp.is0(n)))
            throw new Error(`bad point coordinate ${title}`);
        return n;
    }
    function aprjpoint(other) {
        if (!(other instanceof Point))
            throw new Error('ProjectivePoint expected');
    }
    function splitEndoScalarN(k) {
        if (!endo || !endo.basises)
            throw new Error('no endo');
        return _splitEndoScalar(k, endo.basises, Fn.ORDER);
    }
    // Memoized toAffine / validity check. They are heavy. Points are immutable.
    // Converts Projective point to affine (x, y) coordinates.
    // Can accept precomputed Z^-1 - for example, from invertBatch.
    // (X, Y, Z) ∋ (x=X/Z, y=Y/Z)
    const toAffineMemo = memoized((p, iz) => {
        const { X, Y, Z } = p;
        // Fast-path for normalized points
        if (Fp.eql(Z, Fp.ONE))
            return { x: X, y: Y };
        const is0 = p.is0();
        // If invZ was 0, we return zero point. However we still want to execute
        // all operations, so we replace invZ with a random number, 1.
        if (iz == null)
            iz = is0 ? Fp.ONE : Fp.inv(Z);
        const x = Fp.mul(X, iz);
        const y = Fp.mul(Y, iz);
        const zz = Fp.mul(Z, iz);
        if (is0)
            return { x: Fp.ZERO, y: Fp.ZERO };
        if (!Fp.eql(zz, Fp.ONE))
            throw new Error('invZ was invalid');
        return { x, y };
    });
    // NOTE: on exception this will crash 'cached' and no value will be set.
    // Otherwise true will be return
    const assertValidMemo = memoized((p) => {
        if (p.is0()) {
            // (0, 1, 0) aka ZERO is invalid in most contexts.
            // In BLS, ZERO can be serialized, so we allow it.
            // (0, 0, 0) is invalid representation of ZERO.
            if (extraOpts.allowInfinityPoint && !Fp.is0(p.Y))
                return;
            throw new Error('bad point: ZERO');
        }
        // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`
        const { x, y } = p.toAffine();
        if (!Fp.isValid(x) || !Fp.isValid(y))
            throw new Error('bad point: x or y not field elements');
        if (!isValidXY(x, y))
            throw new Error('bad point: equation left != right');
        if (!p.isTorsionFree())
            throw new Error('bad point: not in prime-order subgroup');
        return true;
    });
    function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) {
        k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);
        k1p = negateCt(k1neg, k1p);
        k2p = negateCt(k2neg, k2p);
        return k1p.add(k2p);
    }
    /**
     * Projective Point works in 3d / projective (homogeneous) coordinates:(X, Y, Z) ∋ (x=X/Z, y=Y/Z).
     * Default Point works in 2d / affine coordinates: (x, y).
     * We're doing calculations in projective, because its operations don't require costly inversion.
     */
    class Point {
        /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
        constructor(X, Y, Z) {
            this.X = acoord('x', X);
            this.Y = acoord('y', Y, true);
            this.Z = acoord('z', Z);
            Object.freeze(this);
        }
        static CURVE() {
            return CURVE;
        }
        /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
        static fromAffine(p) {
            const { x, y } = p || {};
            if (!p || !Fp.isValid(x) || !Fp.isValid(y))
                throw new Error('invalid affine point');
            if (p instanceof Point)
                throw new Error('projective point not allowed');
            // (0, 0) would've produced (0, 0, 1) - instead, we need (0, 1, 0)
            if (Fp.is0(x) && Fp.is0(y))
                return Point.ZERO;
            return new Point(x, y, Fp.ONE);
        }
        static fromBytes(bytes) {
            const P = Point.fromAffine(decodePoint(abytes(bytes, undefined, 'point')));
            P.assertValidity();
            return P;
        }
        static fromHex(hex) {
            return Point.fromBytes(ensureBytes('pointHex', hex));
        }
        get x() {
            return this.toAffine().x;
        }
        get y() {
            return this.toAffine().y;
        }
        /**
         *
         * @param windowSize
         * @param isLazy true will defer table computation until the first multiplication
         * @returns
         */
        precompute(windowSize = 8, isLazy = true) {
            wnaf.createCache(this, windowSize);
            if (!isLazy)
                this.multiply(_3n); // random number
            return this;
        }
        // TODO: return `this`
        /** A point on curve is valid if it conforms to equation. */
        assertValidity() {
            assertValidMemo(this);
        }
        hasEvenY() {
            const { y } = this.toAffine();
            if (!Fp.isOdd)
                throw new Error("Field doesn't support isOdd");
            return !Fp.isOdd(y);
        }
        /** Compare one point to another. */
        equals(other) {
            aprjpoint(other);
            const { X: X1, Y: Y1, Z: Z1 } = this;
            const { X: X2, Y: Y2, Z: Z2 } = other;
            const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
            const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
            return U1 && U2;
        }
        /** Flips point to one corresponding to (x, -y) in Affine coordinates. */
        negate() {
            return new Point(this.X, Fp.neg(this.Y), this.Z);
        }
        // Renes-Costello-Batina exception-free doubling formula.
        // There is 30% faster Jacobian formula, but it is not complete.
        // https://eprint.iacr.org/2015/1060, algorithm 3
        // Cost: 8M + 3S + 3*a + 2*b3 + 15add.
        double() {
            const { a, b } = CURVE;
            const b3 = Fp.mul(b, _3n);
            const { X: X1, Y: Y1, Z: Z1 } = this;
            let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore
            let t0 = Fp.mul(X1, X1); // step 1
            let t1 = Fp.mul(Y1, Y1);
            let t2 = Fp.mul(Z1, Z1);
            let t3 = Fp.mul(X1, Y1);
            t3 = Fp.add(t3, t3); // step 5
            Z3 = Fp.mul(X1, Z1);
            Z3 = Fp.add(Z3, Z3);
            X3 = Fp.mul(a, Z3);
            Y3 = Fp.mul(b3, t2);
            Y3 = Fp.add(X3, Y3); // step 10
            X3 = Fp.sub(t1, Y3);
            Y3 = Fp.add(t1, Y3);
            Y3 = Fp.mul(X3, Y3);
            X3 = Fp.mul(t3, X3);
            Z3 = Fp.mul(b3, Z3); // step 15
            t2 = Fp.mul(a, t2);
            t3 = Fp.sub(t0, t2);
            t3 = Fp.mul(a, t3);
            t3 = Fp.add(t3, Z3);
            Z3 = Fp.add(t0, t0); // step 20
            t0 = Fp.add(Z3, t0);
            t0 = Fp.add(t0, t2);
            t0 = Fp.mul(t0, t3);
            Y3 = Fp.add(Y3, t0);
            t2 = Fp.mul(Y1, Z1); // step 25
            t2 = Fp.add(t2, t2);
            t0 = Fp.mul(t2, t3);
            X3 = Fp.sub(X3, t0);
            Z3 = Fp.mul(t2, t1);
            Z3 = Fp.add(Z3, Z3); // step 30
            Z3 = Fp.add(Z3, Z3);
            return new Point(X3, Y3, Z3);
        }
        // Renes-Costello-Batina exception-free addition formula.
        // There is 30% faster Jacobian formula, but it is not complete.
        // https://eprint.iacr.org/2015/1060, algorithm 1
        // Cost: 12M + 0S + 3*a + 3*b3 + 23add.
        add(other) {
            aprjpoint(other);
            const { X: X1, Y: Y1, Z: Z1 } = this;
            const { X: X2, Y: Y2, Z: Z2 } = other;
            let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore
            const a = CURVE.a;
            const b3 = Fp.mul(CURVE.b, _3n);
            let t0 = Fp.mul(X1, X2); // step 1
            let t1 = Fp.mul(Y1, Y2);
            let t2 = Fp.mul(Z1, Z2);
            let t3 = Fp.add(X1, Y1);
            let t4 = Fp.add(X2, Y2); // step 5
            t3 = Fp.mul(t3, t4);
            t4 = Fp.add(t0, t1);
            t3 = Fp.sub(t3, t4);
            t4 = Fp.add(X1, Z1);
            let t5 = Fp.add(X2, Z2); // step 10
            t4 = Fp.mul(t4, t5);
            t5 = Fp.add(t0, t2);
            t4 = Fp.sub(t4, t5);
            t5 = Fp.add(Y1, Z1);
            X3 = Fp.add(Y2, Z2); // step 15
            t5 = Fp.mul(t5, X3);
            X3 = Fp.add(t1, t2);
            t5 = Fp.sub(t5, X3);
            Z3 = Fp.mul(a, t4);
            X3 = Fp.mul(b3, t2); // step 20
            Z3 = Fp.add(X3, Z3);
            X3 = Fp.sub(t1, Z3);
            Z3 = Fp.add(t1, Z3);
            Y3 = Fp.mul(X3, Z3);
            t1 = Fp.add(t0, t0); // step 25
            t1 = Fp.add(t1, t0);
            t2 = Fp.mul(a, t2);
            t4 = Fp.mul(b3, t4);
            t1 = Fp.add(t1, t2);
            t2 = Fp.sub(t0, t2); // step 30
            t2 = Fp.mul(a, t2);
            t4 = Fp.add(t4, t2);
            t0 = Fp.mul(t1, t4);
            Y3 = Fp.add(Y3, t0);
            t0 = Fp.mul(t5, t4); // step 35
            X3 = Fp.mul(t3, X3);
            X3 = Fp.sub(X3, t0);
            t0 = Fp.mul(t3, t1);
            Z3 = Fp.mul(t5, Z3);
            Z3 = Fp.add(Z3, t0); // step 40
            return new Point(X3, Y3, Z3);
        }
        subtract(other) {
            return this.add(other.negate());
        }
        is0() {
            return this.equals(Point.ZERO);
        }
        /**
         * Constant time multiplication.
         * Uses wNAF method. Windowed method may be 10% faster,
         * but takes 2x longer to generate and consumes 2x memory.
         * Uses precomputes when available.
         * Uses endomorphism for Koblitz curves.
         * @param scalar by which the point would be multiplied
         * @returns New point
         */
        multiply(scalar) {
            const { endo } = extraOpts;
            if (!Fn.isValidNot0(scalar))
                throw new Error('invalid scalar: out of range'); // 0 is invalid
            let point, fake; // Fake point is used to const-time mult
            const mul = (n) => wnaf.cached(this, n, (p) => normalizeZ(Point, p));
            /** See docs for {@link EndomorphismOpts} */
            if (endo) {
                const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);
                const { p: k1p, f: k1f } = mul(k1);
                const { p: k2p, f: k2f } = mul(k2);
                fake = k1f.add(k2f);
                point = finishEndo(endo.beta, k1p, k2p, k1neg, k2neg);
            }
            else {
                const { p, f } = mul(scalar);
                point = p;
                fake = f;
            }
            // Normalize `z` for both points, but return only real one
            return normalizeZ(Point, [point, fake])[0];
        }
        /**
         * Non-constant-time multiplication. Uses double-and-add algorithm.
         * It's faster, but should only be used when you don't care about
         * an exposed secret key e.g. sig verification, which works over *public* keys.
         */
        multiplyUnsafe(sc) {
            const { endo } = extraOpts;
            const p = this;
            if (!Fn.isValid(sc))
                throw new Error('invalid scalar: out of range'); // 0 is valid
            if (sc === _0n || p.is0())
                return Point.ZERO;
            if (sc === _1n)
                return p; // fast-path
            if (wnaf.hasCache(this))
                return this.multiply(sc);
            if (endo) {
                const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);
                const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2); // 30% faster vs wnaf.unsafe
                return finishEndo(endo.beta, p1, p2, k1neg, k2neg);
            }
            else {
                return wnaf.unsafe(p, sc);
            }
        }
        multiplyAndAddUnsafe(Q, a, b) {
            const sum = this.multiplyUnsafe(a).add(Q.multiplyUnsafe(b));
            return sum.is0() ? undefined : sum;
        }
        /**
         * Converts Projective point to affine (x, y) coordinates.
         * @param invertedZ Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch
         */
        toAffine(invertedZ) {
            return toAffineMemo(this, invertedZ);
        }
        /**
         * Checks whether Point is free of torsion elements (is in prime subgroup).
         * Always torsion-free for cofactor=1 curves.
         */
        isTorsionFree() {
            const { isTorsionFree } = extraOpts;
            if (cofactor === _1n)
                return true;
            if (isTorsionFree)
                return isTorsionFree(Point, this);
            return wnaf.unsafe(this, CURVE_ORDER).is0();
        }
        clearCofactor() {
            const { clearCofactor } = extraOpts;
            if (cofactor === _1n)
                return this; // Fast-path
            if (clearCofactor)
                return clearCofactor(Point, this);
            return this.multiplyUnsafe(cofactor);
        }
        isSmallOrder() {
            // can we use this.clearCofactor()?
            return this.multiplyUnsafe(cofactor).is0();
        }
        toBytes(isCompressed = true) {
            abool(isCompressed, 'isCompressed');
            this.assertValidity();
            return encodePoint(Point, this, isCompressed);
        }
        toHex(isCompressed = true) {
            return bytesToHex(this.toBytes(isCompressed));
        }
        toString() {
            return `<Point ${this.is0() ? 'ZERO' : this.toHex()}>`;
        }
        // TODO: remove
        get px() {
            return this.X;
        }
        get py() {
            return this.X;
        }
        get pz() {
            return this.Z;
        }
        toRawBytes(isCompressed = true) {
            return this.toBytes(isCompressed);
        }
        _setWindowSize(windowSize) {
            this.precompute(windowSize);
        }
        static normalizeZ(points) {
            return normalizeZ(Point, points);
        }
        static msm(points, scalars) {
            return pippenger(Point, Fn, points, scalars);
        }
        static fromPrivateKey(privateKey) {
            return Point.BASE.multiply(_normFnElement(Fn, privateKey));
        }
    }
    // base / generator point
    Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
    // zero / infinity / identity point
    Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); // 0, 1, 0
    // math field
    Point.Fp = Fp;
    // scalar field
    Point.Fn = Fn;
    const bits = Fn.BITS;
    const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);
    Point.BASE.precompute(8); // Enable precomputes. Slows down first publicKey computation by 20ms.
    return Point;
}
// Points start with byte 0x02 when y is even; otherwise 0x03
function pprefix(hasEvenY) {
    return Uint8Array.of(hasEvenY ? 0x02 : 0x03);
}
/**
 * Implementation of the Shallue and van de Woestijne method for any weierstrass curve.
 * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular.
 * b = True and y = sqrt(u / v) if (u / v) is square in F, and
 * b = False and y = sqrt(Z * (u / v)) otherwise.
 * @param Fp
 * @param Z
 * @returns
 */
export function SWUFpSqrtRatio(Fp, Z) {
    // Generic implementation
    const q = Fp.ORDER;
    let l = _0n;
    for (let o = q - _1n; o % _2n === _0n; o /= _2n)
        l += _1n;
    const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1.
    // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<.
    // 2n ** c1 == 2n << (c1-1)
    const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n);
    const _2n_pow_c1 = _2n_pow_c1_1 * _2n;
    const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1)  # Integer arithmetic
    const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2            # Integer arithmetic
    const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1                # Integer arithmetic
    const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1)                  # Integer arithmetic
    const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2
    const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2)
    let sqrtRatio = (u, v) => {
        let tv1 = c6; // 1. tv1 = c6
        let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4
        let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2
        tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v
        let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3
        tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3
        tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2
        tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v
        tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u
        let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2
        tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5
        let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1
        tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7
        tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1
        tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR)
        tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR)
        // 17. for i in (c1, c1 - 1, ..., 2):
        for (let i = c1; i > _1n; i--) {
            let tv5 = i - _2n; // 18.    tv5 = i - 2
            tv5 = _2n << (tv5 - _1n); // 19.    tv5 = 2^tv5
            let tvv5 = Fp.pow(tv4, tv5); // 20.    tv5 = tv4^tv5
            const e1 = Fp.eql(tvv5, Fp.ONE); // 21.    e1 = tv5 == 1
            tv2 = Fp.mul(tv3, tv1); // 22.    tv2 = tv3 * tv1
            tv1 = Fp.mul(tv1, tv1); // 23.    tv1 = tv1 * tv1
            tvv5 = Fp.mul(tv4, tv1); // 24.    tv5 = tv4 * tv1
            tv3 = Fp.cmov(tv2, tv3, e1); // 25.    tv3 = CMOV(tv2, tv3, e1)
            tv4 = Fp.cmov(tvv5, tv4, e1); // 26.    tv4 = CMOV(tv5, tv4, e1)
        }
        return { isValid: isQR, value: tv3 };
    };
    if (Fp.ORDER % _4n === _3n) {
        // sqrt_ratio_3mod4(u, v)
        const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4     # Integer arithmetic
        const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z)
        sqrtRatio = (u, v) => {
            let tv1 = Fp.sqr(v); // 1. tv1 = v^2
            const tv2 = Fp.mul(u, v); // 2. tv2 = u * v
            tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2
            let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1
            y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2
            const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2
            const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v
            const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u
            let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR)
            return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2
        };
    }
    // No curves uses that
    // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8
    return sqrtRatio;
}
/**
 * Simplified Shallue-van de Woestijne-Ulas Method
 * https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2
 */
export function mapToCurveSimpleSWU(Fp, opts) {
    validateField(Fp);
    const { A, B, Z } = opts;
    if (!Fp.isValid(A) || !Fp.isValid(B) || !Fp.isValid(Z))
        throw new Error('mapToCurveSimpleSWU: invalid opts');
    const sqrtRatio = SWUFpSqrtRatio(Fp, Z);
    if (!Fp.isOdd)
        throw new Error('Field does not have .isOdd()');
    // Input: u, an element of F.
    // Output: (x, y), a point on E.
    return (u) => {
        // prettier-ignore
        let tv1, tv2, tv3, tv4, tv5, tv6, x, y;
        tv1 = Fp.sqr(u); // 1.  tv1 = u^2
        tv1 = Fp.mul(tv1, Z); // 2.  tv1 = Z * tv1
        tv2 = Fp.sqr(tv1); // 3.  tv2 = tv1^2
        tv2 = Fp.add(tv2, tv1); // 4.  tv2 = tv2 + tv1
        tv3 = Fp.add(tv2, Fp.ONE); // 5.  tv3 = tv2 + 1
        tv3 = Fp.mul(tv3, B); // 6.  tv3 = B * tv3
        tv4 = Fp.cmov(Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7.  tv4 = CMOV(Z, -tv2, tv2 != 0)
        tv4 = Fp.mul(tv4, A); // 8.  tv4 = A * tv4
        tv2 = Fp.sqr(tv3); // 9.  tv2 = tv3^2
        tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2
        tv5 = Fp.mul(tv6, A); // 11. tv5 = A * tv6
        tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5
        tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3
        tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4
        tv5 = Fp.mul(tv6, B); // 15. tv5 = B * tv6
        tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5
        x = Fp.mul(tv1, tv3); // 17.   x = tv1 * tv3
        const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6)
        y = Fp.mul(tv1, u); // 19.   y = tv1 * u  -> Z * u^3 * y1
        y = Fp.mul(y, value); // 20.   y = y * y1
        x = Fp.cmov(x, tv3, isValid); // 21.   x = CMOV(x, tv3, is_gx1_square)
        y = Fp.cmov(y, value, isValid); // 22.   y = CMOV(y, y1, is_gx1_square)
        const e1 = Fp.isOdd(u) === Fp.isOdd(y); // 23.  e1 = sgn0(u) == sgn0(y)
        y = Fp.cmov(Fp.neg(y), y, e1); // 24.   y = CMOV(-y, y, e1)
        const tv4_inv = FpInvertBatch(Fp, [tv4], true)[0];
        x = Fp.mul(x, tv4_inv); // 25.   x = x / tv4
        return { x, y };
    };
}
function getWLengths(Fp, Fn) {
    return {
        secretKey: Fn.BYTES,
        publicKey: 1 + Fp.BYTES,
        publicKeyUncompressed: 1 + 2 * Fp.BYTES,
        publicKeyHasPrefix: true,
        signature: 2 * Fn.BYTES,
    };
}
/**
 * Sometimes users only need getPublicKey, getSharedSecret, and secret key handling.
 * This helper ensures no signature functionality is present. Less code, smaller bundle size.
 */
export function ecdh(Point, ecdhOpts = {}) {
    const { Fn } = Point;
    const randomBytes_ = ecdhOpts.randomBytes || randomBytesWeb;
    const lengths = Object.assign(getWLengths(Point.Fp, Fn), { seed: getMinHashLength(Fn.ORDER) });
    function isValidSecretKey(secretKey) {
        try {
            return !!_normFnElement(Fn, secretKey);
        }
        catch (error) {
            return false;
        }
    }
    function isValidPublicKey(publicKey, isCompressed) {
        const { publicKey: comp, publicKeyUncompressed } = lengths;
        try {
            const l = publicKey.length;
            if (isCompressed === true && l !== comp)
                return false;
            if (isCompressed === false && l !== publicKeyUncompressed)
                return false;
            return !!Point.fromBytes(publicKey);
        }
        catch (error) {
            return false;
        }
    }
    /**
     * Produces cryptographically secure secret key from random of size
     * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.
     */
    function randomSecretKey(seed = randomBytes_(lengths.seed)) {
        return mapHashToField(abytes(seed, lengths.seed, 'seed'), Fn.ORDER);
    }
    /**
     * Computes public key for a secret key. Checks for validity of the secret key.
     * @param isCompressed whether to return compact (default), or full key
     * @returns Public key, full when isCompressed=false; short when isCompressed=true
     */
    function getPublicKey(secretKey, isCompressed = true) {
        return Point.BASE.multiply(_normFnElement(Fn, secretKey)).toBytes(isCompressed);
    }
    function keygen(seed) {
        const secretKey = randomSecretKey(seed);
        return { secretKey, publicKey: getPublicKey(secretKey) };
    }
    /**
     * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.
     */
    function isProbPub(item) {
        if (typeof item === 'bigint')
            return false;
        if (item instanceof Point)
            return true;
        const { secretKey, publicKey, publicKeyUncompressed } = lengths;
        if (Fn.allowedLengths || secretKey === publicKey)
            return undefined;
        const l = ensureBytes('key', item).length;
        return l === publicKey || l === publicKeyUncompressed;
    }
    /**
     * ECDH (Elliptic Curve Diffie Hellman).
     * Computes shared public key from secret key A and public key B.
     * Checks: 1) secret key validity 2) shared key is on-curve.
     * Does NOT hash the result.
     * @param isCompressed whether to return compact (default), or full key
     * @returns shared public key
     */
    function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {
        if (isProbPub(secretKeyA) === true)
            throw new Error('first arg must be private key');
        if (isProbPub(publicKeyB) === false)
            throw new Error('second arg must be public key');
        const s = _normFnElement(Fn, secretKeyA);
        const b = Point.fromHex(publicKeyB); // checks for being on-curve
        return b.multiply(s).toBytes(isCompressed);
    }
    const utils = {
        isValidSecretKey,
        isValidPublicKey,
        randomSecretKey,
        // TODO: remove
        isValidPrivateKey: isValidSecretKey,
        randomPrivateKey: randomSecretKey,
        normPrivateKeyToScalar: (key) => _normFnElement(Fn, key),
        precompute(windowSize = 8, point = Point.BASE) {
            return point.precompute(windowSize, false);
        },
    };
    return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point, utils, lengths });
}
/**
 * Creates ECDSA signing interface for given elliptic curve `Point` and `hash` function.
 * We need `hash` for 2 features:
 * 1. Message prehash-ing. NOT used if `sign` / `verify` are called with `prehash: false`
 * 2. k generation in `sign`, using HMAC-drbg(hash)
 *
 * ECDSAOpts are only rarely needed.
 *
 * @example
 * ```js
 * const p256_Point = weierstrass(...);
 * const p256_sha256 = ecdsa(p256_Point, sha256);
 * const p256_sha224 = ecdsa(p256_Point, sha224);
 * const p256_sha224_r = ecdsa(p256_Point, sha224, { randomBytes: (length) => { ... } });
 * ```
 */
export function ecdsa(Point, hash, ecdsaOpts = {}) {
    ahash(hash);
    _validateObject(ecdsaOpts, {}, {
        hmac: 'function',
        lowS: 'boolean',
        randomBytes: 'function',
        bits2int: 'function',
        bits2int_modN: 'function',
    });
    const randomBytes = ecdsaOpts.randomBytes || randomBytesWeb;
    const hmac = ecdsaOpts.hmac ||
        ((key, ...msgs) => nobleHmac(hash, key, concatBytes(...msgs)));
    const { Fp, Fn } = Point;
    const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;
    const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);
    const defaultSigOpts = {
        prehash: false,
        lowS: typeof ecdsaOpts.lowS === 'boolean' ? ecdsaOpts.lowS : false,
        format: undefined, //'compact' as ECDSASigFormat,
        extraEntropy: false,
    };
    const defaultSigOpts_format = 'compact';
    function isBiggerThanHalfOrder(number) {
        const HALF = CURVE_ORDER >> _1n;
        return number > HALF;
    }
    function validateRS(title, num) {
        if (!Fn.isValidNot0(num))
            throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);
        return num;
    }
    function validateSigLength(bytes, format) {
        validateSigFormat(format);
        const size = lengths.signature;
        const sizer = format === 'compact' ? size : format === 'recovered' ? size + 1 : undefined;
        return abytes(bytes, sizer, `${format} signature`);
    }
    /**
     * ECDSA signature with its (r, s) properties. Supports compact, recovered & DER representations.
     */
    class Signature {
        constructor(r, s, recovery) {
            this.r = validateRS('r', r); // r in [1..N-1];
            this.s = validateRS('s', s); // s in [1..N-1];
            if (recovery != null)
                this.recovery = recovery;
            Object.freeze(this);
        }
        static fromBytes(bytes, format = defaultSigOpts_format) {
            validateSigLength(bytes, format);
            let recid;
            if (format === 'der') {
                const { r, s } = DER.toSig(abytes(bytes));
                return new Signature(r, s);
            }
            if (format === 'recovered') {
                recid = bytes[0];
                format = 'compact';
                bytes = bytes.subarray(1);
            }
            const L = Fn.BYTES;
            const r = bytes.subarray(0, L);
            const s = bytes.subarray(L, L * 2);
            return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);
        }
        static fromHex(hex, format) {
            return this.fromBytes(hexToBytes(hex), format);
        }
        addRecoveryBit(recovery) {
            return new Signature(this.r, this.s, recovery);
        }
        recoverPublicKey(messageHash) {
            const FIELD_ORDER = Fp.ORDER;
            const { r, s, recovery: rec } = this;
            if (rec == null || ![0, 1, 2, 3].includes(rec))
                throw new Error('recovery id invalid');
            // ECDSA recovery is hard for cofactor > 1 curves.
            // In sign, `r = q.x mod n`, and here we recover q.x from r.
            // While recovering q.x >= n, we need to add r+n for cofactor=1 curves.
            // However, for cofactor>1, r+n may not get q.x:
            // r+n*i would need to be done instead where i is unknown.
            // To easily get i, we either need to:
            // a. increase amount of valid recid values (4, 5...); OR
            // b. prohibit non-prime-order signatures (recid > 1).
            const hasCofactor = CURVE_ORDER * _2n < FIELD_ORDER;
            if (hasCofactor && rec > 1)
                throw new Error('recovery id is ambiguous for h>1 curve');
            const radj = rec === 2 || rec === 3 ? r + CURVE_ORDER : r;
            if (!Fp.isValid(radj))
                throw new Error('recovery id 2 or 3 invalid');
            const x = Fp.toBytes(radj);
            const R = Point.fromBytes(concatBytes(pprefix((rec & 1) === 0), x));
            const ir = Fn.inv(radj); // r^-1
            const h = bits2int_modN(ensureBytes('msgHash', messageHash)); // Truncate hash
            const u1 = Fn.create(-h * ir); // -hr^-1
            const u2 = Fn.create(s * ir); // sr^-1
            // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1). unsafe is fine: there is no private data.
            const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));
            if (Q.is0())
                throw new Error('point at infinify');
            Q.assertValidity();
            return Q;
        }
        // Signatures should be low-s, to prevent malleability.
        hasHighS() {
            return isBiggerThanHalfOrder(this.s);
        }
        toBytes(format = defaultSigOpts_format) {
            validateSigFormat(format);
            if (format === 'der')
                return hexToBytes(DER.hexFromSig(this));
            const r = Fn.toBytes(this.r);
            const s = Fn.toBytes(this.s);
            if (format === 'recovered') {
                if (this.recovery == null)
                    throw new Error('recovery bit must be present');
                return concatBytes(Uint8Array.of(this.recovery), r, s);
            }
            return concatBytes(r, s);
        }
        toHex(format) {
            return bytesToHex(this.toBytes(format));
        }
        // TODO: remove
        assertValidity() { }
        static fromCompact(hex) {
            return Signature.fromBytes(ensureBytes('sig', hex), 'compact');
        }
        static fromDER(hex) {
            return Signature.fromBytes(ensureBytes('sig', hex), 'der');
        }
        normalizeS() {
            return this.hasHighS() ? new Signature(this.r, Fn.neg(this.s), this.recovery) : this;
        }
        toDERRawBytes() {
            return this.toBytes('der');
        }
        toDERHex() {
            return bytesToHex(this.toBytes('der'));
        }
        toCompactRawBytes() {
            return this.toBytes('compact');
        }
        toCompactHex() {
            return bytesToHex(this.toBytes('compact'));
        }
    }
    // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.
    // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.
    // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.
    // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors
    const bits2int = ecdsaOpts.bits2int ||
        function bits2int_def(bytes) {
            // Our custom check "just in case", for protection against DoS
            if (bytes.length > 8192)
                throw new Error('input is too large');
            // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)
            // for some cases, since bytes.length * 8 is not actual bitLength.
            const num = bytesToNumberBE(bytes); // check for == u8 done here
            const delta = bytes.length * 8 - fnBits; // truncate to nBitLength leftmost bits
            return delta > 0 ? num >> BigInt(delta) : num;
        };
    const bits2int_modN = ecdsaOpts.bits2int_modN ||
        function bits2int_modN_def(bytes) {
            return Fn.create(bits2int(bytes)); // can't use bytesToNumberBE here
        };
    // Pads output with zero as per spec
    const ORDER_MASK = bitMask(fnBits);
    /** Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. */
    function int2octets(num) {
        // IMPORTANT: the check ensures working for case `Fn.BYTES != Fn.BITS * 8`
        aInRange('num < 2^' + fnBits, num, _0n, ORDER_MASK);
        return Fn.toBytes(num);
    }
    function validateMsgAndHash(message, prehash) {
        abytes(message, undefined, 'message');
        return prehash ? abytes(hash(message), undefined, 'prehashed message') : message;
    }
    /**
     * Steps A, D of RFC6979 3.2.
     * Creates RFC6979 seed; converts msg/privKey to numbers.
     * Used only in sign, not in verify.
     *
     * Warning: we cannot assume here that message has same amount of bytes as curve order,
     * this will be invalid at least for P521. Also it can be bigger for P224 + SHA256.
     */
    function prepSig(message, privateKey, opts) {
        if (['recovered', 'canonical'].some((k) => k in opts))
            throw new Error('sign() legacy options not supported');
        const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);
        message = validateMsgAndHash(message, prehash); // RFC6979 3.2 A: h1 = H(m)
        // We can't later call bits2octets, since nested bits2int is broken for curves
        // with fnBits % 8 !== 0. Because of that, we unwrap it here as int2octets call.
        // const bits2octets = (bits) => int2octets(bits2int_modN(bits))
        const h1int = bits2int_modN(message);
        const d = _normFnElement(Fn, privateKey); // validate secret key, convert to bigint
        const seedArgs = [int2octets(d), int2octets(h1int)];
        // extraEntropy. RFC6979 3.6: additional k' (optional).
        if (extraEntropy != null && extraEntropy !== false) {
            // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')
            // gen random bytes OR pass as-is
            const e = extraEntropy === true ? randomBytes(lengths.secretKey) : extraEntropy;
            seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes
        }
        const seed = concatBytes(...seedArgs); // Step D of RFC6979 3.2
        const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash!
        // Converts signature params into point w r/s, checks result for validity.
        // To transform k => Signature:
        // q = k⋅G
        // r = q.x mod n
        // s = k^-1(m + rd) mod n
        // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to
        // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:
        // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT
        function k2sig(kBytes) {
            // RFC 6979 Section 3.2, step 3: k = bits2int(T)
            // Important: all mod() calls here must be done over N
            const k = bits2int(kBytes); // mod n, not mod p
            if (!Fn.isValidNot0(k))
                return; // Valid scalars (including k) must be in 1..N-1
            const ik = Fn.inv(k); // k^-1 mod n
            const q = Point.BASE.multiply(k).toAffine(); // q = k⋅G
            const r = Fn.create(q.x); // r = q.x mod n
            if (r === _0n)
                return;
            const s = Fn.create(ik * Fn.create(m + r * d)); // Not using blinding here, see comment above
            if (s === _0n)
                return;
            let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n)
            let normS = s;
            if (lowS && isBiggerThanHalfOrder(s)) {
                normS = Fn.neg(s); // if lowS was passed, ensure s is always
                recovery ^= 1; // // in the bottom half of N
            }
            return new Signature(r, normS, recovery); // use normS, not s
        }
        return { seed, k2sig };
    }
    /**
     * Signs message hash with a secret key.
     *
     * ```
     * sign(m, d) where
     *   k = rfc6979_hmac_drbg(m, d)
     *   (x, y) = G × k
     *   r = x mod n
     *   s = (m + dr) / k mod n
     * ```
     */
    function sign(message, secretKey, opts = {}) {
        message = ensureBytes('message', message);
        const { seed, k2sig } = prepSig(message, secretKey, opts); // Steps A, D of RFC6979 3.2.
        const drbg = createHmacDrbg(hash.outputLen, Fn.BYTES, hmac);
        const sig = drbg(seed, k2sig); // Steps B, C, D, E, F, G
        return sig;
    }
    function tryParsingSig(sg) {
        // Try to deduce format
        let sig = undefined;
        const isHex = typeof sg === 'string' || isBytes(sg);
        const isObj = !isHex &&
            sg !== null &&
            typeof sg === 'object' &&
            typeof sg.r === 'bigint' &&
            typeof sg.s === 'bigint';
        if (!isHex && !isObj)
            throw new Error('invalid signature, expected Uint8Array, hex string or Signature instance');
        if (isObj) {
            sig = new Signature(sg.r, sg.s);
        }
        else if (isHex) {
            try {
                sig = Signature.fromBytes(ensureBytes('sig', sg), 'der');
            }
            catch (derError) {
                if (!(derError instanceof DER.Err))
                    throw derError;
            }
            if (!sig) {
                try {
                    sig = Signature.fromBytes(ensureBytes('sig', sg), 'compact');
                }
                catch (error) {
                    return false;
                }
            }
        }
        if (!sig)
            return false;
        return sig;
    }
    /**
     * Verifies a signature against message and public key.
     * Rejects lowS signatures by default: see {@link ECDSAVerifyOpts}.
     * Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:
     *
     * ```
     * verify(r, s, h, P) where
     *   u1 = hs^-1 mod n
     *   u2 = rs^-1 mod n
     *   R = u1⋅G + u2⋅P
     *   mod(R.x, n) == r
     * ```
     */
    function verify(signature, message, publicKey, opts = {}) {
        const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);
        publicKey = ensureBytes('publicKey', publicKey);
        message = validateMsgAndHash(ensureBytes('message', message), prehash);
        if ('strict' in opts)
            throw new Error('options.strict was renamed to lowS');
        const sig = format === undefined
            ? tryParsingSig(signature)
            : Signature.fromBytes(ensureBytes('sig', signature), format);
        if (sig === false)
            return false;
        try {
            const P = Point.fromBytes(publicKey);
            if (lowS && sig.hasHighS())
                return false;
            const { r, s } = sig;
            const h = bits2int_modN(message); // mod n, not mod p
            const is = Fn.inv(s); // s^-1 mod n
            const u1 = Fn.create(h * is); // u1 = hs^-1 mod n
            const u2 = Fn.create(r * is); // u2 = rs^-1 mod n
            const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2)); // u1⋅G + u2⋅P
            if (R.is0())
                return false;
            const v = Fn.create(R.x); // v = r.x mod n
            return v === r;
        }
        catch (e) {
            return false;
        }
    }
    function recoverPublicKey(signature, message, opts = {}) {
        const { prehash } = validateSigOpts(opts, defaultSigOpts);
        message = validateMsgAndHash(message, prehash);
        return Signature.fromBytes(signature, 'recovered').recoverPublicKey(message).toBytes();
    }
    return Object.freeze({
        keygen,
        getPublicKey,
        getSharedSecret,
        utils,
        lengths,
        Point,
        sign,
        verify,
        recoverPublicKey,
        Signature,
        hash,
    });
}
/** @deprecated use `weierstrass` in newer releases */
export function weierstrassPoints(c) {
    const { CURVE, curveOpts } = _weierstrass_legacy_opts_to_new(c);
    const Point = weierstrassN(CURVE, curveOpts);
    return _weierstrass_new_output_to_legacy(c, Point);
}
function _weierstrass_legacy_opts_to_new(c) {
    const CURVE = {
        a: c.a,
        b: c.b,
        p: c.Fp.ORDER,
        n: c.n,
        h: c.h,
        Gx: c.Gx,
        Gy: c.Gy,
    };
    const Fp = c.Fp;
    let allowedLengths = c.allowedPrivateKeyLengths
        ? Array.from(new Set(c.allowedPrivateKeyLengths.map((l) => Math.ceil(l / 2))))
        : undefined;
    const Fn = Field(CURVE.n, {
        BITS: c.nBitLength,
        allowedLengths: allowedLengths,
        modFromBytes: c.wrapPrivateKey,
    });
    const curveOpts = {
        Fp,
        Fn,
        allowInfinityPoint: c.allowInfinityPoint,
        endo: c.endo,
        isTorsionFree: c.isTorsionFree,
        clearCofactor: c.clearCofactor,
        fromBytes: c.fromBytes,
        toBytes: c.toBytes,
    };
    return { CURVE, curveOpts };
}
function _ecdsa_legacy_opts_to_new(c) {
    const { CURVE, curveOpts } = _weierstrass_legacy_opts_to_new(c);
    const ecdsaOpts = {
        hmac: c.hmac,
        randomBytes: c.randomBytes,
        lowS: c.lowS,
        bits2int: c.bits2int,
        bits2int_modN: c.bits2int_modN,
    };
    return { CURVE, curveOpts, hash: c.hash, ecdsaOpts };
}
export function _legacyHelperEquat(Fp, a, b) {
    /**
     * y² = x³ + ax + b: Short weierstrass curve formula. Takes x, returns y².
     * @returns y²
     */
    function weierstrassEquation(x) {
        const x2 = Fp.sqr(x); // x * x
        const x3 = Fp.mul(x2, x); // x² * x
        return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x³ + a * x + b
    }
    return weierstrassEquation;
}
function _weierstrass_new_output_to_legacy(c, Point) {
    const { Fp, Fn } = Point;
    function isWithinCurveOrder(num) {
        return inRange(num, _1n, Fn.ORDER);
    }
    const weierstrassEquation = _legacyHelperEquat(Fp, c.a, c.b);
    return Object.assign({}, {
        CURVE: c,
        Point: Point,
        ProjectivePoint: Point,
        normPrivateKeyToScalar: (key) => _normFnElement(Fn, key),
        weierstrassEquation,
        isWithinCurveOrder,
    });
}
function _ecdsa_new_output_to_legacy(c, _ecdsa) {
    const Point = _ecdsa.Point;
    return Object.assign({}, _ecdsa, {
        ProjectivePoint: Point,
        CURVE: Object.assign({}, c, nLength(Point.Fn.ORDER, Point.Fn.BITS)),
    });
}
// _ecdsa_legacy
export function weierstrass(c) {
    const { CURVE, curveOpts, hash, ecdsaOpts } = _ecdsa_legacy_opts_to_new(c);
    const Point = weierstrassN(CURVE, curveOpts);
    const signs = ecdsa(Point, hash, ecdsaOpts);
    return _ecdsa_new_output_to_legacy(c, signs);
}
//# sourceMappingURL=weierstrass.js.map{
  "type": "module",
  "sideEffects": false
}
/**
 * SECG secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).
 *
 * Belongs to Koblitz curves: it has efficiently-computable GLV endomorphism ψ,
 * check out {@link EndomorphismOpts}. Seems to be rigid (not backdoored).
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { sha256 } from '@noble/hashes/sha2.js';
import { randomBytes } from '@noble/hashes/utils.js';
import { createCurve } from "./_shortw_utils.js";
import { createHasher, isogenyMap, } from "./abstract/hash-to-curve.js";
import { Field, mapHashToField, mod, pow2 } from "./abstract/modular.js";
import { _normFnElement, mapToCurveSimpleSWU, } from "./abstract/weierstrass.js";
import { bytesToNumberBE, concatBytes, ensureBytes, inRange, numberToBytesBE, utf8ToBytes, } from "./utils.js";
// Seems like generator was produced from some seed:
// `Point.BASE.multiply(Point.Fn.inv(2n, N)).toAffine().x`
// // gives short x 0x3b78ce563f89a0ed9414f5aa28ad0d96d6795f9c63n
const secp256k1_CURVE = {
    p: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'),
    n: BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'),
    h: BigInt(1),
    a: BigInt(0),
    b: BigInt(7),
    Gx: BigInt('0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'),
    Gy: BigInt('0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8'),
};
const secp256k1_ENDO = {
    beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),
    basises: [
        [BigInt('0x3086d221a7d46bcde86c90e49284eb15'), -BigInt('0xe4437ed6010e88286f547fa90abfe4c3')],
        [BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'), BigInt('0x3086d221a7d46bcde86c90e49284eb15')],
    ],
};
const _0n = /* @__PURE__ */ BigInt(0);
const _1n = /* @__PURE__ */ BigInt(1);
const _2n = /* @__PURE__ */ BigInt(2);
/**
 * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.
 * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]
 */
function sqrtMod(y) {
    const P = secp256k1_CURVE.p;
    // prettier-ignore
    const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
    // prettier-ignore
    const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
    const b2 = (y * y * y) % P; // x^3, 11
    const b3 = (b2 * b2 * y) % P; // x^7
    const b6 = (pow2(b3, _3n, P) * b3) % P;
    const b9 = (pow2(b6, _3n, P) * b3) % P;
    const b11 = (pow2(b9, _2n, P) * b2) % P;
    const b22 = (pow2(b11, _11n, P) * b11) % P;
    const b44 = (pow2(b22, _22n, P) * b22) % P;
    const b88 = (pow2(b44, _44n, P) * b44) % P;
    const b176 = (pow2(b88, _88n, P) * b88) % P;
    const b220 = (pow2(b176, _44n, P) * b44) % P;
    const b223 = (pow2(b220, _3n, P) * b3) % P;
    const t1 = (pow2(b223, _23n, P) * b22) % P;
    const t2 = (pow2(t1, _6n, P) * b2) % P;
    const root = pow2(t2, _2n, P);
    if (!Fpk1.eql(Fpk1.sqr(root), y))
        throw new Error('Cannot find square root');
    return root;
}
const Fpk1 = Field(secp256k1_CURVE.p, { sqrt: sqrtMod });
/**
 * secp256k1 curve, ECDSA and ECDH methods.
 *
 * Field: `2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n`
 *
 * @example
 * ```js
 * import { secp256k1 } from '@noble/curves/secp256k1';
 * const { secretKey, publicKey } = secp256k1.keygen();
 * const msg = new TextEncoder().encode('hello');
 * const sig = secp256k1.sign(msg, secretKey);
 * const isValid = secp256k1.verify(sig, msg, publicKey) === true;
 * ```
 */
export const secp256k1 = createCurve({ ...secp256k1_CURVE, Fp: Fpk1, lowS: true, endo: secp256k1_ENDO }, sha256);
// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.
// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki
/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */
const TAGGED_HASH_PREFIXES = {};
function taggedHash(tag, ...messages) {
    let tagP = TAGGED_HASH_PREFIXES[tag];
    if (tagP === undefined) {
        const tagH = sha256(utf8ToBytes(tag));
        tagP = concatBytes(tagH, tagH);
        TAGGED_HASH_PREFIXES[tag] = tagP;
    }
    return sha256(concatBytes(tagP, ...messages));
}
// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03
const pointToBytes = (point) => point.toBytes(true).slice(1);
const Pointk1 = /* @__PURE__ */ (() => secp256k1.Point)();
const hasEven = (y) => y % _2n === _0n;
// Calculate point, scalar and bytes
function schnorrGetExtPubKey(priv) {
    const { Fn, BASE } = Pointk1;
    const d_ = _normFnElement(Fn, priv);
    const p = BASE.multiply(d_); // P = d'⋅G; 0 < d' < n check is done inside
    const scalar = hasEven(p.y) ? d_ : Fn.neg(d_);
    return { scalar, bytes: pointToBytes(p) };
}
/**
 * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.
 * @returns valid point checked for being on-curve
 */
function lift_x(x) {
    const Fp = Fpk1;
    if (!Fp.isValidNot0(x))
        throw new Error('invalid x: Fail if x ≥ p');
    const xx = Fp.create(x * x);
    const c = Fp.create(xx * x + BigInt(7)); // Let c = x³ + 7 mod p.
    let y = Fp.sqrt(c); // Let y = c^(p+1)/4 mod p. Same as sqrt().
    // Return the unique point P such that x(P) = x and
    // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.
    if (!hasEven(y))
        y = Fp.neg(y);
    const p = Pointk1.fromAffine({ x, y });
    p.assertValidity();
    return p;
}
const num = bytesToNumberBE;
/**
 * Create tagged hash, convert it to bigint, reduce modulo-n.
 */
function challenge(...args) {
    return Pointk1.Fn.create(num(taggedHash('BIP0340/challenge', ...args)));
}
/**
 * Schnorr public key is just `x` coordinate of Point as per BIP340.
 */
function schnorrGetPublicKey(secretKey) {
    return schnorrGetExtPubKey(secretKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G)
}
/**
 * Creates Schnorr signature as per BIP340. Verifies itself before returning anything.
 * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous.
 */
function schnorrSign(message, secretKey, auxRand = randomBytes(32)) {
    const { Fn } = Pointk1;
    const m = ensureBytes('message', message);
    const { bytes: px, scalar: d } = schnorrGetExtPubKey(secretKey); // checks for isWithinCurveOrder
    const a = ensureBytes('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array
    const t = Fn.toBytes(d ^ num(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a)
    const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m)
    // Let k' = int(rand) mod n. Fail if k' = 0. Let R = k'⋅G
    const { bytes: rx, scalar: k } = schnorrGetExtPubKey(rand);
    const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.
    const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n).
    sig.set(rx, 0);
    sig.set(Fn.toBytes(Fn.create(k + e * d)), 32);
    // If Verify(bytes(P), m, sig) (see below) returns failure, abort
    if (!schnorrVerify(sig, m, px))
        throw new Error('sign: Invalid signature produced');
    return sig;
}
/**
 * Verifies Schnorr signature.
 * Will swallow errors & return false except for initial type validation of arguments.
 */
function schnorrVerify(signature, message, publicKey) {
    const { Fn, BASE } = Pointk1;
    const sig = ensureBytes('signature', signature, 64);
    const m = ensureBytes('message', message);
    const pub = ensureBytes('publicKey', publicKey, 32);
    try {
        const P = lift_x(num(pub)); // P = lift_x(int(pk)); fail if that fails
        const r = num(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r ≥ p.
        if (!inRange(r, _1n, secp256k1_CURVE.p))
            return false;
        const s = num(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n.
        if (!inRange(s, _1n, secp256k1_CURVE.n))
            return false;
        // int(challenge(bytes(r)||bytes(P)||m))%n
        const e = challenge(Fn.toBytes(r), pointToBytes(P), m);
        // R = s⋅G - e⋅P, where -eP == (n-e)P
        const R = BASE.multiplyUnsafe(s).add(P.multiplyUnsafe(Fn.neg(e)));
        const { x, y } = R.toAffine();
        // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r.
        if (R.is0() || !hasEven(y) || x !== r)
            return false;
        return true;
    }
    catch (error) {
        return false;
    }
}
/**
 * Schnorr signatures over secp256k1.
 * https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki
 * @example
 * ```js
 * import { schnorr } from '@noble/curves/secp256k1';
 * const { secretKey, publicKey } = schnorr.keygen();
 * // const publicKey = schnorr.getPublicKey(secretKey);
 * const msg = new TextEncoder().encode('hello');
 * const sig = schnorr.sign(msg, secretKey);
 * const isValid = schnorr.verify(sig, msg, publicKey);
 * ```
 */
export const schnorr = /* @__PURE__ */ (() => {
    const size = 32;
    const seedLength = 48;
    const randomSecretKey = (seed = randomBytes(seedLength)) => {
        return mapHashToField(seed, secp256k1_CURVE.n);
    };
    // TODO: remove
    secp256k1.utils.randomSecretKey;
    function keygen(seed) {
        const secretKey = randomSecretKey(seed);
        return { secretKey, publicKey: schnorrGetPublicKey(secretKey) };
    }
    return {
        keygen,
        getPublicKey: schnorrGetPublicKey,
        sign: schnorrSign,
        verify: schnorrVerify,
        Point: Pointk1,
        utils: {
            randomSecretKey: randomSecretKey,
            randomPrivateKey: randomSecretKey,
            taggedHash,
            // TODO: remove
            lift_x,
            pointToBytes,
            numberToBytesBE,
            bytesToNumberBE,
            mod,
        },
        lengths: {
            secretKey: size,
            publicKey: size,
            publicKeyHasPrefix: false,
            signature: size * 2,
            seed: seedLength,
        },
    };
})();
const isoMap = /* @__PURE__ */ (() => isogenyMap(Fpk1, [
    // xNum
    [
        '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7',
        '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581',
        '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262',
        '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c',
    ],
    // xDen
    [
        '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b',
        '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14',
        '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1
    ],
    // yNum
    [
        '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c',
        '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3',
        '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931',
        '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84',
    ],
    // yDen
    [
        '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b',
        '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573',
        '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f',
        '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1
    ],
].map((i) => i.map((j) => BigInt(j)))))();
const mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fpk1, {
    A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),
    B: BigInt('1771'),
    Z: Fpk1.create(BigInt('-11')),
}))();
/** Hashing / encoding to secp256k1 points / field. RFC 9380 methods. */
export const secp256k1_hasher = /* @__PURE__ */ (() => createHasher(secp256k1.Point, (scalars) => {
    const { x, y } = mapSWU(Fpk1.create(scalars[0]));
    return isoMap(x, y);
}, {
    DST: 'secp256k1_XMD:SHA-256_SSWU_RO_',
    encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_',
    p: Fpk1.ORDER,
    m: 1,
    k: 128,
    expand: 'xmd',
    hash: sha256,
}))();
/** @deprecated use `import { secp256k1_hasher } from '@noble/curves/secp256k1.js';` */
export const hashToCurve = /* @__PURE__ */ (() => secp256k1_hasher.hashToCurve)();
/** @deprecated use `import { secp256k1_hasher } from '@noble/curves/secp256k1.js';` */
export const encodeToCurve = /* @__PURE__ */ (() => secp256k1_hasher.encodeToCurve)();
//# sourceMappingURL=secp256k1.js.map/**
 * Hex, bytes and number utilities.
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { abytes as abytes_, bytesToHex as bytesToHex_, concatBytes as concatBytes_, hexToBytes as hexToBytes_, isBytes as isBytes_, } from '@noble/hashes/utils.js';
export { abytes, anumber, bytesToHex, bytesToUtf8, concatBytes, hexToBytes, isBytes, randomBytes, utf8ToBytes, } from '@noble/hashes/utils.js';
const _0n = /* @__PURE__ */ BigInt(0);
const _1n = /* @__PURE__ */ BigInt(1);
export function abool(title, value) {
    if (typeof value !== 'boolean')
        throw new Error(title + ' boolean expected, got ' + value);
}
// tmp name until v2
export function _abool2(value, title = '') {
    if (typeof value !== 'boolean') {
        const prefix = title && `"${title}"`;
        throw new Error(prefix + 'expected boolean, got type=' + typeof value);
    }
    return value;
}
// tmp name until v2
/** Asserts something is Uint8Array. */
export function _abytes2(value, length, title = '') {
    const bytes = isBytes_(value);
    const len = value?.length;
    const needsLen = length !== undefined;
    if (!bytes || (needsLen && len !== length)) {
        const prefix = title && `"${title}" `;
        const ofLen = needsLen ? ` of length ${length}` : '';
        const got = bytes ? `length=${len}` : `type=${typeof value}`;
        throw new Error(prefix + 'expected Uint8Array' + ofLen + ', got ' + got);
    }
    return value;
}
// Used in weierstrass, der
export function numberToHexUnpadded(num) {
    const hex = num.toString(16);
    return hex.length & 1 ? '0' + hex : hex;
}
export function hexToNumber(hex) {
    if (typeof hex !== 'string')
        throw new Error('hex string expected, got ' + typeof hex);
    return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian
}
// BE: Big Endian, LE: Little Endian
export function bytesToNumberBE(bytes) {
    return hexToNumber(bytesToHex_(bytes));
}
export function bytesToNumberLE(bytes) {
    abytes_(bytes);
    return hexToNumber(bytesToHex_(Uint8Array.from(bytes).reverse()));
}
export function numberToBytesBE(n, len) {
    return hexToBytes_(n.toString(16).padStart(len * 2, '0'));
}
export function numberToBytesLE(n, len) {
    return numberToBytesBE(n, len).reverse();
}
// Unpadded, rarely used
export function numberToVarBytesBE(n) {
    return hexToBytes_(numberToHexUnpadded(n));
}
/**
 * Takes hex string or Uint8Array, converts to Uint8Array.
 * Validates output length.
 * Will throw error for other types.
 * @param title descriptive title for an error e.g. 'secret key'
 * @param hex hex string or Uint8Array
 * @param expectedLength optional, will compare to result array's length
 * @returns
 */
export function ensureBytes(title, hex, expectedLength) {
    let res;
    if (typeof hex === 'string') {
        try {
            res = hexToBytes_(hex);
        }
        catch (e) {
            throw new Error(title + ' must be hex string or Uint8Array, cause: ' + e);
        }
    }
    else if (isBytes_(hex)) {
        // Uint8Array.from() instead of hash.slice() because node.js Buffer
        // is instance of Uint8Array, and its slice() creates **mutable** copy
        res = Uint8Array.from(hex);
    }
    else {
        throw new Error(title + ' must be hex string or Uint8Array');
    }
    const len = res.length;
    if (typeof expectedLength === 'number' && len !== expectedLength)
        throw new Error(title + ' of length ' + expectedLength + ' expected, got ' + len);
    return res;
}
// Compares 2 u8a-s in kinda constant time
export function equalBytes(a, b) {
    if (a.length !== b.length)
        return false;
    let diff = 0;
    for (let i = 0; i < a.length; i++)
        diff |= a[i] ^ b[i];
    return diff === 0;
}
/**
 * Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,
 * and Buffer#slice creates mutable copy. Never use Buffers!
 */
export function copyBytes(bytes) {
    return Uint8Array.from(bytes);
}
/**
 * Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols
 * Should be safe to use for things expected to be ASCII.
 * Returns exact same result as utf8ToBytes for ASCII or throws.
 */
export function asciiToBytes(ascii) {
    return Uint8Array.from(ascii, (c, i) => {
        const charCode = c.charCodeAt(0);
        if (c.length !== 1 || charCode > 127) {
            throw new Error(`string contains non-ASCII character "${ascii[i]}" with code ${charCode} at position ${i}`);
        }
        return charCode;
    });
}
/**
 * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
 */
// export const utf8ToBytes: typeof utf8ToBytes_ = utf8ToBytes_;
/**
 * Converts bytes to string using UTF8 encoding.
 * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'
 */
// export const bytesToUtf8: typeof bytesToUtf8_ = bytesToUtf8_;
// Is positive bigint
const isPosBig = (n) => typeof n === 'bigint' && _0n <= n;
export function inRange(n, min, max) {
    return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
}
/**
 * Asserts min <= n < max. NOTE: It's < max and not <= max.
 * @example
 * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)
 */
export function aInRange(title, n, min, max) {
    // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?
    // consider P=256n, min=0n, max=P
    // - a for min=0 would require -1:          `inRange('x', x, -1n, P)`
    // - b would commonly require subtraction:  `inRange('x', x, 0n, P - 1n)`
    // - our way is the cleanest:               `inRange('x', x, 0n, P)
    if (!inRange(n, min, max))
        throw new Error('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);
}
// Bit operations
/**
 * Calculates amount of bits in a bigint.
 * Same as `n.toString(2).length`
 * TODO: merge with nLength in modular
 */
export function bitLen(n) {
    let len;
    for (len = 0; n > _0n; n >>= _1n, len += 1)
        ;
    return len;
}
/**
 * Gets single bit at position.
 * NOTE: first bit position is 0 (same as arrays)
 * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`
 */
export function bitGet(n, pos) {
    return (n >> BigInt(pos)) & _1n;
}
/**
 * Sets single bit at position.
 */
export function bitSet(n, pos, value) {
    return n | ((value ? _1n : _0n) << BigInt(pos));
}
/**
 * Calculate mask for N bits. Not using ** operator with bigints because of old engines.
 * Same as BigInt(`0b${Array(i).fill('1').join('')}`)
 */
export const bitMask = (n) => (_1n << BigInt(n)) - _1n;
/**
 * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
 * @returns function that will call DRBG until 2nd arg returns something meaningful
 * @example
 *   const drbg = createHmacDRBG<Key>(32, 32, hmac);
 *   drbg(seed, bytesToKey); // bytesToKey must return Key or undefined
 */
export function createHmacDrbg(hashLen, qByteLen, hmacFn) {
    if (typeof hashLen !== 'number' || hashLen < 2)
        throw new Error('hashLen must be a number');
    if (typeof qByteLen !== 'number' || qByteLen < 2)
        throw new Error('qByteLen must be a number');
    if (typeof hmacFn !== 'function')
        throw new Error('hmacFn must be a function');
    // Step B, Step C: set hashLen to 8*ceil(hlen/8)
    const u8n = (len) => new Uint8Array(len); // creates Uint8Array
    const u8of = (byte) => Uint8Array.of(byte); // another shortcut
    let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
    let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same
    let i = 0; // Iterations counter, will throw when over 1000
    const reset = () => {
        v.fill(1);
        k.fill(0);
        i = 0;
    };
    const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)
    const reseed = (seed = u8n(0)) => {
        // HMAC-DRBG reseed() function. Steps D-G
        k = h(u8of(0x00), seed); // k = hmac(k || v || 0x00 || seed)
        v = h(); // v = hmac(k || v)
        if (seed.length === 0)
            return;
        k = h(u8of(0x01), seed); // k = hmac(k || v || 0x01 || seed)
        v = h(); // v = hmac(k || v)
    };
    const gen = () => {
        // HMAC-DRBG generate() function
        if (i++ >= 1000)
            throw new Error('drbg: tried 1000 values');
        let len = 0;
        const out = [];
        while (len < qByteLen) {
            v = h();
            const sl = v.slice();
            out.push(sl);
            len += v.length;
        }
        return concatBytes_(...out);
    };
    const genUntil = (seed, pred) => {
        reset();
        reseed(seed); // Steps D-G
        let res = undefined; // Step H: grind until k is in [1..n-1]
        while (!(res = pred(gen())))
            reseed();
        reset();
        return res;
    };
    return genUntil;
}
// Validating curves and fields
const validatorFns = {
    bigint: (val) => typeof val === 'bigint',
    function: (val) => typeof val === 'function',
    boolean: (val) => typeof val === 'boolean',
    string: (val) => typeof val === 'string',
    stringOrUint8Array: (val) => typeof val === 'string' || isBytes_(val),
    isSafeInteger: (val) => Number.isSafeInteger(val),
    array: (val) => Array.isArray(val),
    field: (val, object) => object.Fp.isValid(val),
    hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),
};
// type Record<K extends string | number | symbol, T> = { [P in K]: T; }
export function validateObject(object, validators, optValidators = {}) {
    const checkField = (fieldName, type, isOptional) => {
        const checkVal = validatorFns[type];
        if (typeof checkVal !== 'function')
            throw new Error('invalid validator function');
        const val = object[fieldName];
        if (isOptional && val === undefined)
            return;
        if (!checkVal(val, object)) {
            throw new Error('param ' + String(fieldName) + ' is invalid. Expected ' + type + ', got ' + val);
        }
    };
    for (const [fieldName, type] of Object.entries(validators))
        checkField(fieldName, type, false);
    for (const [fieldName, type] of Object.entries(optValidators))
        checkField(fieldName, type, true);
    return object;
}
// validate type tests
// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };
// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!
// // Should fail type-check
// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });
// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });
// const z3 = validateObject(o, { test: 'boolean', z: 'bug' });
// const z4 = validateObject(o, { a: 'boolean', z: 'bug' });
export function isHash(val) {
    return typeof val === 'function' && Number.isSafeInteger(val.outputLen);
}
export function _validateObject(object, fields, optFields = {}) {
    if (!object || typeof object !== 'object')
        throw new Error('expected valid options object');
    function checkField(fieldName, expectedType, isOpt) {
        const val = object[fieldName];
        if (isOpt && val === undefined)
            return;
        const current = typeof val;
        if (current !== expectedType || val === null)
            throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
    }
    Object.entries(fields).forEach(([k, v]) => checkField(k, v, false));
    Object.entries(optFields).forEach(([k, v]) => checkField(k, v, true));
}
/**
 * throws not implemented error
 */
export const notImplemented = () => {
    throw new Error('not implemented');
};
/**
 * Memoizes (caches) computation result.
 * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.
 */
export function memoized(fn) {
    const map = new WeakMap();
    return (arg, ...args) => {
        const val = map.get(arg);
        if (val !== undefined)
            return val;
        const computed = fn(arg, ...args);
        map.set(arg, computed);
        return computed;
    };
}
//# sourceMappingURL=utils.js.map/**
 * Internal Merkle-Damgard hash utils.
 * @module
 */
import { Hash, abytes, aexists, aoutput, clean, createView, toBytes } from "./utils.js";
/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */
export function setBigUint64(view, byteOffset, value, isLE) {
    if (typeof view.setBigUint64 === 'function')
        return view.setBigUint64(byteOffset, value, isLE);
    const _32n = BigInt(32);
    const _u32_max = BigInt(0xffffffff);
    const wh = Number((value >> _32n) & _u32_max);
    const wl = Number(value & _u32_max);
    const h = isLE ? 4 : 0;
    const l = isLE ? 0 : 4;
    view.setUint32(byteOffset + h, wh, isLE);
    view.setUint32(byteOffset + l, wl, isLE);
}
/** Choice: a ? b : c */
export function Chi(a, b, c) {
    return (a & b) ^ (~a & c);
}
/** Majority function, true if any two inputs is true. */
export function Maj(a, b, c) {
    return (a & b) ^ (a & c) ^ (b & c);
}
/**
 * Merkle-Damgard hash construction base class.
 * Could be used to create MD5, RIPEMD, SHA1, SHA2.
 */
export class HashMD extends Hash {
    constructor(blockLen, outputLen, padOffset, isLE) {
        super();
        this.finished = false;
        this.length = 0;
        this.pos = 0;
        this.destroyed = false;
        this.blockLen = blockLen;
        this.outputLen = outputLen;
        this.padOffset = padOffset;
        this.isLE = isLE;
        this.buffer = new Uint8Array(blockLen);
        this.view = createView(this.buffer);
    }
    update(data) {
        aexists(this);
        data = toBytes(data);
        abytes(data);
        const { view, buffer, blockLen } = this;
        const len = data.length;
        for (let pos = 0; pos < len;) {
            const take = Math.min(blockLen - this.pos, len - pos);
            // Fast path: we have at least one block in input, cast it to view and process
            if (take === blockLen) {
                const dataView = createView(data);
                for (; blockLen <= len - pos; pos += blockLen)
                    this.process(dataView, pos);
                continue;
            }
            buffer.set(data.subarray(pos, pos + take), this.pos);
            this.pos += take;
            pos += take;
            if (this.pos === blockLen) {
                this.process(view, 0);
                this.pos = 0;
            }
        }
        this.length += data.length;
        this.roundClean();
        return this;
    }
    digestInto(out) {
        aexists(this);
        aoutput(out, this);
        this.finished = true;
        // Padding
        // We can avoid allocation of buffer for padding completely if it
        // was previously not allocated here. But it won't change performance.
        const { buffer, view, blockLen, isLE } = this;
        let { pos } = this;
        // append the bit '1' to the message
        buffer[pos++] = 0b10000000;
        clean(this.buffer.subarray(pos));
        // we have less than padOffset left in buffer, so we cannot put length in
        // current block, need process it and pad again
        if (this.padOffset > blockLen - pos) {
            this.process(view, 0);
            pos = 0;
        }
        // Pad until full block byte with zeros
        for (let i = pos; i < blockLen; i++)
            buffer[i] = 0;
        // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that
        // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.
        // So we just write lowest 64 bits of that value.
        setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
        this.process(view, 0);
        const oview = createView(out);
        const len = this.outputLen;
        // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT
        if (len % 4)
            throw new Error('_sha2: outputLen should be aligned to 32bit');
        const outLen = len / 4;
        const state = this.get();
        if (outLen > state.length)
            throw new Error('_sha2: outputLen bigger than state');
        for (let i = 0; i < outLen; i++)
            oview.setUint32(4 * i, state[i], isLE);
    }
    digest() {
        const { buffer, outputLen } = this;
        this.digestInto(buffer);
        const res = buffer.slice(0, outputLen);
        this.destroy();
        return res;
    }
    _cloneInto(to) {
        to || (to = new this.constructor());
        to.set(...this.get());
        const { blockLen, buffer, length, finished, destroyed, pos } = this;
        to.destroyed = destroyed;
        to.finished = finished;
        to.length = length;
        to.pos = pos;
        if (length % blockLen)
            to.buffer.set(buffer);
        return to;
    }
    clone() {
        return this._cloneInto();
    }
}
/**
 * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.
 * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.
 */
/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */
export const SHA256_IV = /* @__PURE__ */ Uint32Array.from([
    0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
]);
/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */
export const SHA224_IV = /* @__PURE__ */ Uint32Array.from([
    0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,
]);
/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */
export const SHA384_IV = /* @__PURE__ */ Uint32Array.from([
    0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,
    0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,
]);
/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */
export const SHA512_IV = /* @__PURE__ */ Uint32Array.from([
    0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,
    0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,
]);
//# sourceMappingURL=_md.js.map/**
 * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.
 * @todo re-check https://issues.chromium.org/issues/42212588
 * @module
 */
const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
const _32n = /* @__PURE__ */ BigInt(32);
function fromBig(n, le = false) {
    if (le)
        return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };
    return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
}
function split(lst, le = false) {
    const len = lst.length;
    let Ah = new Uint32Array(len);
    let Al = new Uint32Array(len);
    for (let i = 0; i < len; i++) {
        const { h, l } = fromBig(lst[i], le);
        [Ah[i], Al[i]] = [h, l];
    }
    return [Ah, Al];
}
const toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);
// for Shift in [0, 32)
const shrSH = (h, _l, s) => h >>> s;
const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
// Right rotate for Shift in [1, 32)
const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));
const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
// Right rotate for Shift in (32, 64), NOTE: 32 is special case.
const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));
const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));
// Right rotate for shift===32 (just swaps l&h)
const rotr32H = (_h, l) => l;
const rotr32L = (h, _l) => h;
// Left rotate for Shift in [1, 32)
const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));
const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));
// Left rotate for Shift in (32, 64), NOTE: 32 is special case.
const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));
const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));
// JS uses 32-bit signed integers for bitwise operations which means we cannot
// simple take carry out of low bit sum by shift, we need to use division.
function add(Ah, Al, Bh, Bl) {
    const l = (Al >>> 0) + (Bl >>> 0);
    return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };
}
// Addition with more than 2 elements
const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;
const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;
const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;
// prettier-ignore
export { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig };
// prettier-ignore
const u64 = {
    fromBig, split, toBig,
    shrSH, shrSL,
    rotrSH, rotrSL, rotrBH, rotrBL,
    rotr32H, rotr32L,
    rotlSH, rotlSL, rotlBH, rotlBL,
    add, add3L, add3H, add4L, add4H, add5H, add5L,
};
export default u64;
//# sourceMappingURL=_u64.js.mapexport const crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;
//# sourceMappingURL=crypto.js.map/**
 * HMAC: RFC2104 message authentication code.
 * @module
 */
import { abytes, aexists, ahash, clean, Hash, toBytes } from "./utils.js";
export class HMAC extends Hash {
    constructor(hash, _key) {
        super();
        this.finished = false;
        this.destroyed = false;
        ahash(hash);
        const key = toBytes(_key);
        this.iHash = hash.create();
        if (typeof this.iHash.update !== 'function')
            throw new Error('Expected instance of class which extends utils.Hash');
        this.blockLen = this.iHash.blockLen;
        this.outputLen = this.iHash.outputLen;
        const blockLen = this.blockLen;
        const pad = new Uint8Array(blockLen);
        // blockLen can be bigger than outputLen
        pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
        for (let i = 0; i < pad.length; i++)
            pad[i] ^= 0x36;
        this.iHash.update(pad);
        // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone
        this.oHash = hash.create();
        // Undo internal XOR && apply outer XOR
        for (let i = 0; i < pad.length; i++)
            pad[i] ^= 0x36 ^ 0x5c;
        this.oHash.update(pad);
        clean(pad);
    }
    update(buf) {
        aexists(this);
        this.iHash.update(buf);
        return this;
    }
    digestInto(out) {
        aexists(this);
        abytes(out, this.outputLen);
        this.finished = true;
        this.iHash.digestInto(out);
        this.oHash.update(out);
        this.oHash.digestInto(out);
        this.destroy();
    }
    digest() {
        const out = new Uint8Array(this.oHash.outputLen);
        this.digestInto(out);
        return out;
    }
    _cloneInto(to) {
        // Create new instance without calling constructor since key already in state and we don't know it.
        to || (to = Object.create(Object.getPrototypeOf(this), {}));
        const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
        to = to;
        to.finished = finished;
        to.destroyed = destroyed;
        to.blockLen = blockLen;
        to.outputLen = outputLen;
        to.oHash = oHash._cloneInto(to.oHash);
        to.iHash = iHash._cloneInto(to.iHash);
        return to;
    }
    clone() {
        return this._cloneInto();
    }
    destroy() {
        this.destroyed = true;
        this.oHash.destroy();
        this.iHash.destroy();
    }
}
/**
 * HMAC: RFC2104 message authentication code.
 * @param hash - function that would be used e.g. sha256
 * @param key - message key
 * @param message - message data
 * @example
 * import { hmac } from '@noble/hashes/hmac';
 * import { sha256 } from '@noble/hashes/sha2';
 * const mac1 = hmac(sha256, 'key', 'message');
 */
export const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
hmac.create = (hash, key) => new HMAC(hash, key);
//# sourceMappingURL=hmac.js.map{
  "type": "module",
  "sideEffects": false,
  "browser": {
    "node:crypto": false
  },
  "node": {
    "./crypto": "./esm/cryptoNode.js"
  }
}
/**
 * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.
 * SHA256 is the fastest hash implementable in JS, even faster than Blake3.
 * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and
 * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).
 * @module
 */
import { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from "./_md.js";
import * as u64 from "./_u64.js";
import { clean, createHasher, rotr } from "./utils.js";
/**
 * Round constants:
 * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)
 */
// prettier-ignore
const SHA256_K = /* @__PURE__ */ Uint32Array.from([
    0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
    0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
    0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
    0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
    0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
    0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
    0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
    0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
]);
/** Reusable temporary buffer. "W" comes straight from spec. */
const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
export class SHA256 extends HashMD {
    constructor(outputLen = 32) {
        super(64, outputLen, 8, false);
        // We cannot use array here since array allows indexing by variable
        // which means optimizer/compiler cannot use registers.
        this.A = SHA256_IV[0] | 0;
        this.B = SHA256_IV[1] | 0;
        this.C = SHA256_IV[2] | 0;
        this.D = SHA256_IV[3] | 0;
        this.E = SHA256_IV[4] | 0;
        this.F = SHA256_IV[5] | 0;
        this.G = SHA256_IV[6] | 0;
        this.H = SHA256_IV[7] | 0;
    }
    get() {
        const { A, B, C, D, E, F, G, H } = this;
        return [A, B, C, D, E, F, G, H];
    }
    // prettier-ignore
    set(A, B, C, D, E, F, G, H) {
        this.A = A | 0;
        this.B = B | 0;
        this.C = C | 0;
        this.D = D | 0;
        this.E = E | 0;
        this.F = F | 0;
        this.G = G | 0;
        this.H = H | 0;
    }
    process(view, offset) {
        // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array
        for (let i = 0; i < 16; i++, offset += 4)
            SHA256_W[i] = view.getUint32(offset, false);
        for (let i = 16; i < 64; i++) {
            const W15 = SHA256_W[i - 15];
            const W2 = SHA256_W[i - 2];
            const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);
            const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);
            SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;
        }
        // Compression function main loop, 64 rounds
        let { A, B, C, D, E, F, G, H } = this;
        for (let i = 0; i < 64; i++) {
            const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
            const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
            const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
            const T2 = (sigma0 + Maj(A, B, C)) | 0;
            H = G;
            G = F;
            F = E;
            E = (D + T1) | 0;
            D = C;
            C = B;
            B = A;
            A = (T1 + T2) | 0;
        }
        // Add the compressed chunk to the current hash value
        A = (A + this.A) | 0;
        B = (B + this.B) | 0;
        C = (C + this.C) | 0;
        D = (D + this.D) | 0;
        E = (E + this.E) | 0;
        F = (F + this.F) | 0;
        G = (G + this.G) | 0;
        H = (H + this.H) | 0;
        this.set(A, B, C, D, E, F, G, H);
    }
    roundClean() {
        clean(SHA256_W);
    }
    destroy() {
        this.set(0, 0, 0, 0, 0, 0, 0, 0);
        clean(this.buffer);
    }
}
export class SHA224 extends SHA256 {
    constructor() {
        super(28);
        this.A = SHA224_IV[0] | 0;
        this.B = SHA224_IV[1] | 0;
        this.C = SHA224_IV[2] | 0;
        this.D = SHA224_IV[3] | 0;
        this.E = SHA224_IV[4] | 0;
        this.F = SHA224_IV[5] | 0;
        this.G = SHA224_IV[6] | 0;
        this.H = SHA224_IV[7] | 0;
    }
}
// SHA2-512 is slower than sha256 in js because u64 operations are slow.
// Round contants
// First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409
// prettier-ignore
const K512 = /* @__PURE__ */ (() => u64.split([
    '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',
    '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',
    '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',
    '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',
    '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',
    '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',
    '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',
    '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',
    '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',
    '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',
    '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',
    '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',
    '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',
    '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',
    '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',
    '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',
    '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',
    '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',
    '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',
    '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'
].map(n => BigInt(n))))();
const SHA512_Kh = /* @__PURE__ */ (() => K512[0])();
const SHA512_Kl = /* @__PURE__ */ (() => K512[1])();
// Reusable temporary buffers
const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
export class SHA512 extends HashMD {
    constructor(outputLen = 64) {
        super(128, outputLen, 16, false);
        // We cannot use array here since array allows indexing by variable
        // which means optimizer/compiler cannot use registers.
        // h -- high 32 bits, l -- low 32 bits
        this.Ah = SHA512_IV[0] | 0;
        this.Al = SHA512_IV[1] | 0;
        this.Bh = SHA512_IV[2] | 0;
        this.Bl = SHA512_IV[3] | 0;
        this.Ch = SHA512_IV[4] | 0;
        this.Cl = SHA512_IV[5] | 0;
        this.Dh = SHA512_IV[6] | 0;
        this.Dl = SHA512_IV[7] | 0;
        this.Eh = SHA512_IV[8] | 0;
        this.El = SHA512_IV[9] | 0;
        this.Fh = SHA512_IV[10] | 0;
        this.Fl = SHA512_IV[11] | 0;
        this.Gh = SHA512_IV[12] | 0;
        this.Gl = SHA512_IV[13] | 0;
        this.Hh = SHA512_IV[14] | 0;
        this.Hl = SHA512_IV[15] | 0;
    }
    // prettier-ignore
    get() {
        const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
        return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
    }
    // prettier-ignore
    set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
        this.Ah = Ah | 0;
        this.Al = Al | 0;
        this.Bh = Bh | 0;
        this.Bl = Bl | 0;
        this.Ch = Ch | 0;
        this.Cl = Cl | 0;
        this.Dh = Dh | 0;
        this.Dl = Dl | 0;
        this.Eh = Eh | 0;
        this.El = El | 0;
        this.Fh = Fh | 0;
        this.Fl = Fl | 0;
        this.Gh = Gh | 0;
        this.Gl = Gl | 0;
        this.Hh = Hh | 0;
        this.Hl = Hl | 0;
    }
    process(view, offset) {
        // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array
        for (let i = 0; i < 16; i++, offset += 4) {
            SHA512_W_H[i] = view.getUint32(offset);
            SHA512_W_L[i] = view.getUint32((offset += 4));
        }
        for (let i = 16; i < 80; i++) {
            // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)
            const W15h = SHA512_W_H[i - 15] | 0;
            const W15l = SHA512_W_L[i - 15] | 0;
            const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);
            const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);
            // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)
            const W2h = SHA512_W_H[i - 2] | 0;
            const W2l = SHA512_W_L[i - 2] | 0;
            const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);
            const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);
            // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];
            const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
            const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
            SHA512_W_H[i] = SUMh | 0;
            SHA512_W_L[i] = SUMl | 0;
        }
        let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
        // Compression function main loop, 80 rounds
        for (let i = 0; i < 80; i++) {
            // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)
            const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);
            const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);
            //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
            const CHIh = (Eh & Fh) ^ (~Eh & Gh);
            const CHIl = (El & Fl) ^ (~El & Gl);
            // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]
            // prettier-ignore
            const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
            const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
            const T1l = T1ll | 0;
            // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)
            const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);
            const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);
            const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);
            const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);
            Hh = Gh | 0;
            Hl = Gl | 0;
            Gh = Fh | 0;
            Gl = Fl | 0;
            Fh = Eh | 0;
            Fl = El | 0;
            ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
            Dh = Ch | 0;
            Dl = Cl | 0;
            Ch = Bh | 0;
            Cl = Bl | 0;
            Bh = Ah | 0;
            Bl = Al | 0;
            const All = u64.add3L(T1l, sigma0l, MAJl);
            Ah = u64.add3H(All, T1h, sigma0h, MAJh);
            Al = All | 0;
        }
        // Add the compressed chunk to the current hash value
        ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
        ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
        ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
        ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
        ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
        ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
        ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
        ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
        this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
    }
    roundClean() {
        clean(SHA512_W_H, SHA512_W_L);
    }
    destroy() {
        clean(this.buffer);
        this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
    }
}
export class SHA384 extends SHA512 {
    constructor() {
        super(48);
        this.Ah = SHA384_IV[0] | 0;
        this.Al = SHA384_IV[1] | 0;
        this.Bh = SHA384_IV[2] | 0;
        this.Bl = SHA384_IV[3] | 0;
        this.Ch = SHA384_IV[4] | 0;
        this.Cl = SHA384_IV[5] | 0;
        this.Dh = SHA384_IV[6] | 0;
        this.Dl = SHA384_IV[7] | 0;
        this.Eh = SHA384_IV[8] | 0;
        this.El = SHA384_IV[9] | 0;
        this.Fh = SHA384_IV[10] | 0;
        this.Fl = SHA384_IV[11] | 0;
        this.Gh = SHA384_IV[12] | 0;
        this.Gl = SHA384_IV[13] | 0;
        this.Hh = SHA384_IV[14] | 0;
        this.Hl = SHA384_IV[15] | 0;
    }
}
/**
 * Truncated SHA512/256 and SHA512/224.
 * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as "intermediary" IV of SHA512/t.
 * Then t hashes string to produce result IV.
 * See `test/misc/sha2-gen-iv.js`.
 */
/** SHA512/224 IV */
const T224_IV = /* @__PURE__ */ Uint32Array.from([
    0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,
    0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,
]);
/** SHA512/256 IV */
const T256_IV = /* @__PURE__ */ Uint32Array.from([
    0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,
    0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,
]);
export class SHA512_224 extends SHA512 {
    constructor() {
        super(28);
        this.Ah = T224_IV[0] | 0;
        this.Al = T224_IV[1] | 0;
        this.Bh = T224_IV[2] | 0;
        this.Bl = T224_IV[3] | 0;
        this.Ch = T224_IV[4] | 0;
        this.Cl = T224_IV[5] | 0;
        this.Dh = T224_IV[6] | 0;
        this.Dl = T224_IV[7] | 0;
        this.Eh = T224_IV[8] | 0;
        this.El = T224_IV[9] | 0;
        this.Fh = T224_IV[10] | 0;
        this.Fl = T224_IV[11] | 0;
        this.Gh = T224_IV[12] | 0;
        this.Gl = T224_IV[13] | 0;
        this.Hh = T224_IV[14] | 0;
        this.Hl = T224_IV[15] | 0;
    }
}
export class SHA512_256 extends SHA512 {
    constructor() {
        super(32);
        this.Ah = T256_IV[0] | 0;
        this.Al = T256_IV[1] | 0;
        this.Bh = T256_IV[2] | 0;
        this.Bl = T256_IV[3] | 0;
        this.Ch = T256_IV[4] | 0;
        this.Cl = T256_IV[5] | 0;
        this.Dh = T256_IV[6] | 0;
        this.Dl = T256_IV[7] | 0;
        this.Eh = T256_IV[8] | 0;
        this.El = T256_IV[9] | 0;
        this.Fh = T256_IV[10] | 0;
        this.Fl = T256_IV[11] | 0;
        this.Gh = T256_IV[12] | 0;
        this.Gl = T256_IV[13] | 0;
        this.Hh = T256_IV[14] | 0;
        this.Hl = T256_IV[15] | 0;
    }
}
/**
 * SHA2-256 hash function from RFC 4634.
 *
 * It is the fastest JS hash, even faster than Blake3.
 * To break sha256 using birthday attack, attackers need to try 2^128 hashes.
 * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
 */
export const sha256 = /* @__PURE__ */ createHasher(() => new SHA256());
/** SHA2-224 hash function from RFC 4634 */
export const sha224 = /* @__PURE__ */ createHasher(() => new SHA224());
/** SHA2-512 hash function from RFC 4634. */
export const sha512 = /* @__PURE__ */ createHasher(() => new SHA512());
/** SHA2-384 hash function from RFC 4634. */
export const sha384 = /* @__PURE__ */ createHasher(() => new SHA384());
/**
 * SHA2-512/256 "truncated" hash function, with improved resistance to length extension attacks.
 * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).
 */
export const sha512_256 = /* @__PURE__ */ createHasher(() => new SHA512_256());
/**
 * SHA2-512/224 "truncated" hash function, with improved resistance to length extension attacks.
 * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).
 */
export const sha512_224 = /* @__PURE__ */ createHasher(() => new SHA512_224());
//# sourceMappingURL=sha2.js.map/**
 * Utilities for hex, bytes, CSPRNG.
 * @module
 */
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
// node.js versions earlier than v19 don't declare it in global scope.
// For node.js, package.json#exports field mapping rewrites import
// from `crypto` to `cryptoNode`, which imports native module.
// Makes the utils un-importable in browsers without a bundler.
// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.
import { crypto } from '@noble/hashes/crypto';
/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */
export function isBytes(a) {
    return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
}
/** Asserts something is positive integer. */
export function anumber(n) {
    if (!Number.isSafeInteger(n) || n < 0)
        throw new Error('positive integer expected, got ' + n);
}
/** Asserts something is Uint8Array. */
export function abytes(b, ...lengths) {
    if (!isBytes(b))
        throw new Error('Uint8Array expected');
    if (lengths.length > 0 && !lengths.includes(b.length))
        throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);
}
/** Asserts something is hash */
export function ahash(h) {
    if (typeof h !== 'function' || typeof h.create !== 'function')
        throw new Error('Hash should be wrapped by utils.createHasher');
    anumber(h.outputLen);
    anumber(h.blockLen);
}
/** Asserts a hash instance has not been destroyed / finished */
export function aexists(instance, checkFinished = true) {
    if (instance.destroyed)
        throw new Error('Hash instance has been destroyed');
    if (checkFinished && instance.finished)
        throw new Error('Hash#digest() has already been called');
}
/** Asserts output is properly-sized byte array */
export function aoutput(out, instance) {
    abytes(out);
    const min = instance.outputLen;
    if (out.length < min) {
        throw new Error('digestInto() expects output buffer of length at least ' + min);
    }
}
/** Cast u8 / u16 / u32 to u8. */
export function u8(arr) {
    return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
}
/** Cast u8 / u16 / u32 to u32. */
export function u32(arr) {
    return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
}
/** Zeroize a byte array. Warning: JS provides no guarantees. */
export function clean(...arrays) {
    for (let i = 0; i < arrays.length; i++) {
        arrays[i].fill(0);
    }
}
/** Create DataView of an array for easy byte-level manipulation. */
export function createView(arr) {
    return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
}
/** The rotate right (circular right shift) operation for uint32 */
export function rotr(word, shift) {
    return (word << (32 - shift)) | (word >>> shift);
}
/** The rotate left (circular left shift) operation for uint32 */
export function rotl(word, shift) {
    return (word << shift) | ((word >>> (32 - shift)) >>> 0);
}
/** Is current platform little-endian? Most are. Big-Endian platform: IBM */
export const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();
/** The byte swap operation for uint32 */
export function byteSwap(word) {
    return (((word << 24) & 0xff000000) |
        ((word << 8) & 0xff0000) |
        ((word >>> 8) & 0xff00) |
        ((word >>> 24) & 0xff));
}
/** Conditionally byte swap if on a big-endian platform */
export const swap8IfBE = isLE
    ? (n) => n
    : (n) => byteSwap(n);
/** @deprecated */
export const byteSwapIfBE = swap8IfBE;
/** In place byte swap for Uint32Array */
export function byteSwap32(arr) {
    for (let i = 0; i < arr.length; i++) {
        arr[i] = byteSwap(arr[i]);
    }
    return arr;
}
export const swap32IfBE = isLE
    ? (u) => u
    : byteSwap32;
// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex
const hasHexBuiltin = /* @__PURE__ */ (() => 
// @ts-ignore
typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();
// Array where index 0xf0 (240) is mapped to string 'f0'
const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
/**
 * Convert byte array to hex string. Uses built-in function, when available.
 * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
 */
export function bytesToHex(bytes) {
    abytes(bytes);
    // @ts-ignore
    if (hasHexBuiltin)
        return bytes.toHex();
    // pre-caching improves the speed 6x
    let hex = '';
    for (let i = 0; i < bytes.length; i++) {
        hex += hexes[bytes[i]];
    }
    return hex;
}
// We use optimized technique to convert hex string to byte array
const asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
function asciiToBase16(ch) {
    if (ch >= asciis._0 && ch <= asciis._9)
        return ch - asciis._0; // '2' => 50-48
    if (ch >= asciis.A && ch <= asciis.F)
        return ch - (asciis.A - 10); // 'B' => 66-(65-10)
    if (ch >= asciis.a && ch <= asciis.f)
        return ch - (asciis.a - 10); // 'b' => 98-(97-10)
    return;
}
/**
 * Convert hex string to byte array. Uses built-in function, when available.
 * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
 */
export function hexToBytes(hex) {
    if (typeof hex !== 'string')
        throw new Error('hex string expected, got ' + typeof hex);
    // @ts-ignore
    if (hasHexBuiltin)
        return Uint8Array.fromHex(hex);
    const hl = hex.length;
    const al = hl / 2;
    if (hl % 2)
        throw new Error('hex string expected, got unpadded hex of length ' + hl);
    const array = new Uint8Array(al);
    for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
        const n1 = asciiToBase16(hex.charCodeAt(hi));
        const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
        if (n1 === undefined || n2 === undefined) {
            const char = hex[hi] + hex[hi + 1];
            throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
        }
        array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163
    }
    return array;
}
/**
 * There is no setImmediate in browser and setTimeout is slow.
 * Call of async fn will return Promise, which will be fullfiled only on
 * next scheduler queue processing step and this is exactly what we need.
 */
export const nextTick = async () => { };
/** Returns control to thread each 'tick' ms to avoid blocking. */
export async function asyncLoop(iters, tick, cb) {
    let ts = Date.now();
    for (let i = 0; i < iters; i++) {
        cb(i);
        // Date.now() is not monotonic, so in case if clock goes backwards we return return control too
        const diff = Date.now() - ts;
        if (diff >= 0 && diff < tick)
            continue;
        await nextTick();
        ts += diff;
    }
}
/**
 * Converts string to bytes using UTF8 encoding.
 * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])
 */
export function utf8ToBytes(str) {
    if (typeof str !== 'string')
        throw new Error('string expected');
    return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
}
/**
 * Converts bytes to string using UTF8 encoding.
 * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'
 */
export function bytesToUtf8(bytes) {
    return new TextDecoder().decode(bytes);
}
/**
 * Normalizes (non-hex) string or Uint8Array to Uint8Array.
 * Warning: when Uint8Array is passed, it would NOT get copied.
 * Keep in mind for future mutable operations.
 */
export function toBytes(data) {
    if (typeof data === 'string')
        data = utf8ToBytes(data);
    abytes(data);
    return data;
}
/**
 * Helper for KDFs: consumes uint8array or string.
 * When string is passed, does utf8 decoding, using TextDecoder.
 */
export function kdfInputToBytes(data) {
    if (typeof data === 'string')
        data = utf8ToBytes(data);
    abytes(data);
    return data;
}
/** Copies several Uint8Arrays into one. */
export function concatBytes(...arrays) {
    let sum = 0;
    for (let i = 0; i < arrays.length; i++) {
        const a = arrays[i];
        abytes(a);
        sum += a.length;
    }
    const res = new Uint8Array(sum);
    for (let i = 0, pad = 0; i < arrays.length; i++) {
        const a = arrays[i];
        res.set(a, pad);
        pad += a.length;
    }
    return res;
}
export function checkOpts(defaults, opts) {
    if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')
        throw new Error('options should be object or undefined');
    const merged = Object.assign(defaults, opts);
    return merged;
}
/** For runtime check if class implements interface */
export class Hash {
}
/** Wraps hash function, creating an interface on top of it */
export function createHasher(hashCons) {
    const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
    const tmp = hashCons();
    hashC.outputLen = tmp.outputLen;
    hashC.blockLen = tmp.blockLen;
    hashC.create = () => hashCons();
    return hashC;
}
export function createOptHasher(hashCons) {
    const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();
    const tmp = hashCons({});
    hashC.outputLen = tmp.outputLen;
    hashC.blockLen = tmp.blockLen;
    hashC.create = (opts) => hashCons(opts);
    return hashC;
}
export function createXOFer(hashCons) {
    const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();
    const tmp = hashCons({});
    hashC.outputLen = tmp.outputLen;
    hashC.blockLen = tmp.blockLen;
    hashC.create = (opts) => hashCons(opts);
    return hashC;
}
export const wrapConstructor = createHasher;
export const wrapConstructorWithOpts = createOptHasher;
export const wrapXOFConstructorWithOpts = createXOFer;
/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */
export function randomBytes(bytesLength = 32) {
    if (crypto && typeof crypto.getRandomValues === 'function') {
        return crypto.getRandomValues(new Uint8Array(bytesLength));
    }
    // Legacy Node.js compatibility
    if (crypto && typeof crypto.randomBytes === 'function') {
        return Uint8Array.from(crypto.randomBytes(bytesLength));
    }
    throw new Error('crypto.getRandomValues must be defined');
}
//# sourceMappingURL=utils.js.mapimport { encode, encodeInto, objectToTokens, rfc8949EncodeOptions } from './lib/encode.js'
import { decode, decodeFirst, Tokeniser, tokensToObject } from './lib/decode.js'
import { Tagged } from './lib/tagged.js'
import { Token, Type } from './lib/token.js'

/**
 * Export the types that were present in the original manual cborg.d.ts
 * @typedef {import('./interface.js').TagDecodeControl} TagDecodeControl
 * @typedef {import('./interface.js').TagDecoder} TagDecoder
 * There was originally just `TypeEncoder` so don't break types by renaming or not exporting
 * @typedef {import('./interface.js').OptionalTypeEncoder} TypeEncoder
 * @typedef {import('./interface.js').DecodeOptions} DecodeOptions
 * @typedef {import('./interface.js').EncodeOptions} EncodeOptions
 */

export {
  decode,
  decodeFirst,
  Tokeniser as Tokenizer,
  tokensToObject,
  encode,
  encodeInto,
  objectToTokens,
  rfc8949EncodeOptions,
  Tagged,
  Token,
  Type
}
/* globals BigInt */

import { Token, Type } from './token.js'
import { decodeErrPrefix, assertEnoughData } from './common.js'

export const uintBoundaries = [24, 256, 65536, 4294967296, BigInt('18446744073709551616')]

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number}
 */
export function readUint8 (data, offset, options) {
  assertEnoughData(data, offset, 1)
  const value = data[offset]
  if (options.strict === true && value < uintBoundaries[0]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  return value
}

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number}
 */
export function readUint16 (data, offset, options) {
  assertEnoughData(data, offset, 2)
  const value = (data[offset] << 8) | data[offset + 1]
  if (options.strict === true && value < uintBoundaries[1]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  return value
}

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number}
 */
export function readUint32 (data, offset, options) {
  assertEnoughData(data, offset, 4)
  const value = (data[offset] * 16777216 /* 2 ** 24 */) + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]
  if (options.strict === true && value < uintBoundaries[2]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  return value
}

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number|bigint}
 */
export function readUint64 (data, offset, options) {
  // assume BigInt, convert back to Number if within safe range
  assertEnoughData(data, offset, 8)
  const hi = (data[offset] * 16777216 /* 2 ** 24 */) + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]
  const lo = (data[offset + 4] * 16777216 /* 2 ** 24 */) + (data[offset + 5] << 16) + (data[offset + 6] << 8) + data[offset + 7]
  const value = (BigInt(hi) << BigInt(32)) + BigInt(lo)
  if (options.strict === true && value < uintBoundaries[3]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  if (value <= Number.MAX_SAFE_INTEGER) {
    return Number(value)
  }
  if (options.allowBigInt === true) {
    return value
  }
  throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`)
}

/* not required thanks to quick[] list
const oneByteTokens = new Array(24).fill(0).map((v, i) => new Token(Type.uint, i, 1))
export function decodeUintCompact (data, pos, minor, options) {
  return oneByteTokens[minor]
}
*/

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint8 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint8(data, pos + 1, options), 2)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint16 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint16(data, pos + 1, options), 3)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint32 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint32(data, pos + 1, options), 5)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint64 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint64(data, pos + 1, options), 9)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeUint (writer, token) {
  return encodeUintValue(writer, 0, token.value)
}

/**
 * @param {ByteWriter} writer
 * @param {number} major
 * @param {number|bigint} uint
 */
export function encodeUintValue (writer, major, uint) {
  if (uint < uintBoundaries[0]) {
    const nuint = Number(uint)
    // pack into one byte, minor=0, additional=value
    writer.push([major | nuint])
  } else if (uint < uintBoundaries[1]) {
    const nuint = Number(uint)
    // pack into two byte, minor=0, additional=24
    writer.push([major | 24, nuint])
  } else if (uint < uintBoundaries[2]) {
    const nuint = Number(uint)
    // pack into three byte, minor=0, additional=25
    writer.push([major | 25, nuint >>> 8, nuint & 0xff])
  } else if (uint < uintBoundaries[3]) {
    const nuint = Number(uint)
    // pack into five byte, minor=0, additional=26
    writer.push([major | 26, (nuint >>> 24) & 0xff, (nuint >>> 16) & 0xff, (nuint >>> 8) & 0xff, nuint & 0xff])
  } else {
    const buint = BigInt(uint)
    if (buint < uintBoundaries[4]) {
      // pack into nine byte, minor=0, additional=27
      const set = [major | 27, 0, 0, 0, 0, 0, 0, 0]
      // simulate bitwise above 32 bits
      let lo = Number(buint & BigInt(0xffffffff))
      let hi = Number(buint >> BigInt(32) & BigInt(0xffffffff))
      set[8] = lo & 0xff
      lo = lo >> 8
      set[7] = lo & 0xff
      lo = lo >> 8
      set[6] = lo & 0xff
      lo = lo >> 8
      set[5] = lo & 0xff
      set[4] = hi & 0xff
      hi = hi >> 8
      set[3] = hi & 0xff
      hi = hi >> 8
      set[2] = hi & 0xff
      hi = hi >> 8
      set[1] = hi & 0xff
      writer.push(set)
    } else {
      throw new Error(`${decodeErrPrefix} encountered BigInt larger than allowable range`)
    }
  }
}

/**
 * @param {Token} token
 * @returns {number}
 */
encodeUint.encodedSize = function encodedSize (token) {
  return encodeUintValue.encodedSize(token.value)
}

/**
 * @param {number} uint
 * @returns {number}
 */
encodeUintValue.encodedSize = function encodedSize (uint) {
  if (uint < uintBoundaries[0]) {
    return 1
  }
  if (uint < uintBoundaries[1]) {
    return 2
  }
  if (uint < uintBoundaries[2]) {
    return 3
  }
  if (uint < uintBoundaries[3]) {
    return 5
  }
  return 9
}

/**
 * @param {Token} tok1
 * @param {Token} tok2
 * @returns {number}
 */
encodeUint.compareTokens = function compareTokens (tok1, tok2) {
  return tok1.value < tok2.value ? -1 : tok1.value > tok2.value ? 1 : 0
}
/* eslint-env es2020 */

import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import { decodeErrPrefix } from './common.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint8 (data, pos, _minor, options) {
  return new Token(Type.negint, -1 - uint.readUint8(data, pos + 1, options), 2)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint16 (data, pos, _minor, options) {
  return new Token(Type.negint, -1 - uint.readUint16(data, pos + 1, options), 3)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint32 (data, pos, _minor, options) {
  return new Token(Type.negint, -1 - uint.readUint32(data, pos + 1, options), 5)
}

const neg1b = BigInt(-1)
const pos1b = BigInt(1)

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint64 (data, pos, _minor, options) {
  const int = uint.readUint64(data, pos + 1, options)
  if (typeof int !== 'bigint') {
    const value = -1 - int
    if (value >= Number.MIN_SAFE_INTEGER) {
      return new Token(Type.negint, value, 9)
    }
  }
  if (options.allowBigInt !== true) {
    throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`)
  }
  return new Token(Type.negint, neg1b - BigInt(int), 9)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeNegint (writer, token) {
  const negint = token.value
  const unsigned = (typeof negint === 'bigint' ? (negint * neg1b - pos1b) : (negint * -1 - 1))
  uint.encodeUintValue(writer, token.type.majorEncoded, unsigned)
}

/**
 * @param {Token} token
 * @returns {number}
 */
encodeNegint.encodedSize = function encodedSize (token) {
  const negint = token.value
  const unsigned = (typeof negint === 'bigint' ? (negint * neg1b - pos1b) : (negint * -1 - 1))
  // handled by quickEncode, we shouldn't get here but it's included for completeness
  if (unsigned < uint.uintBoundaries[0]) {
    return 1
  }
  if (unsigned < uint.uintBoundaries[1]) {
    return 2
  }
  if (unsigned < uint.uintBoundaries[2]) {
    return 3
  }
  if (unsigned < uint.uintBoundaries[3]) {
    return 5
  }
  return 9
}

/**
 * @param {Token} tok1
 * @param {Token} tok2
 * @returns {number}
 */
encodeNegint.compareTokens = function compareTokens (tok1, tok2) {
  // opposite of the uint comparison since we store the uint version in bytes
  return tok1.value < tok2.value ? 1 : tok1.value > tok2.value ? -1 : 0
}
import { Token, Type } from './token.js'
import { assertEnoughData, decodeErrPrefix } from './common.js'
import * as uint from './0uint.js'
import { compare, fromString } from './byte-utils.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} prefix
 * @param {number} length
 * @returns {Token}
 */
function toToken (data, pos, prefix, length) {
  assertEnoughData(data, pos, prefix + length)
  const buf = data.slice(pos + prefix, pos + prefix + length)
  return new Token(Type.bytes, buf, prefix + length)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeBytesCompact (data, pos, minor, _options) {
  return toToken(data, pos, 1, minor)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer bytes lengths not supported`)
  }
  return toToken(data, pos, 9, l)
}

/**
 * `encodedBytes` allows for caching when we do a byte version of a string
 * for key sorting purposes
 * @param {Token} token
 * @returns {Uint8Array}
 */
function tokenBytes (token) {
  if (token.encodedBytes === undefined) {
    token.encodedBytes = Type.equals(token.type, Type.string) ? fromString(token.value) : token.value
  }
  // @ts-ignore c'mon
  return token.encodedBytes
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeBytes (writer, token) {
  const bytes = tokenBytes(token)
  uint.encodeUintValue(writer, token.type.majorEncoded, bytes.length)
  writer.push(bytes)
}

/**
 * @param {Token} token
 * @returns {number}
 */
encodeBytes.encodedSize = function encodedSize (token) {
  const bytes = tokenBytes(token)
  return uint.encodeUintValue.encodedSize(bytes.length) + bytes.length
}

/**
 * @param {Token} tok1
 * @param {Token} tok2
 * @returns {number}
 */
encodeBytes.compareTokens = function compareTokens (tok1, tok2) {
  return compareBytes(tokenBytes(tok1), tokenBytes(tok2))
}

/**
 * @param {Uint8Array} b1
 * @param {Uint8Array} b2
 * @returns {number}
 */
export function compareBytes (b1, b2) {
  return b1.length < b2.length ? -1 : b1.length > b2.length ? 1 : compare(b1, b2)
}
import { Token, Type } from './token.js'
import { assertEnoughData, decodeErrPrefix } from './common.js'
import * as uint from './0uint.js'
import { encodeBytes } from './2bytes.js'

const textDecoder = new TextDecoder()

// Threshold for ASCII fast-path vs TextDecoder. Short ASCII strings (common for
// map keys) are faster to decode with a simple loop than TextDecoder overhead.
const ASCII_THRESHOLD = 32

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * Decode UTF-8 bytes to string. For short ASCII strings (common case for map keys),
 * a simple loop is faster than TextDecoder.
 * @param {Uint8Array} bytes
 * @param {number} start
 * @param {number} end
 * @returns {string}
 */
function toStr (bytes, start, end) {
  const len = end - start
  if (len < ASCII_THRESHOLD) {
    let str = ''
    for (let i = start; i < end; i++) {
      const c = bytes[i]
      if (c & 0x80) { // non-ASCII, fall back to TextDecoder
        return textDecoder.decode(bytes.subarray(start, end))
      }
      str += String.fromCharCode(c)
    }
    return str
  }
  return textDecoder.decode(bytes.subarray(start, end))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} prefix
 * @param {number} length
 * @param {DecodeOptions} options
 * @returns {Token}
 */
function toToken (data, pos, prefix, length, options) {
  const totLength = prefix + length
  assertEnoughData(data, pos, totLength)
  const tok = new Token(Type.string, toStr(data, pos + prefix, pos + totLength), totLength)
  if (options.retainStringBytes === true) {
    tok.byteValue = data.slice(pos + prefix, pos + totLength)
  }
  return tok
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeStringCompact (data, pos, minor, options) {
  return toToken(data, pos, 1, minor, options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options), options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options), options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options), options)
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer string lengths not supported`)
  }
  return toToken(data, pos, 9, l, options)
}

export const encodeString = encodeBytes
import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import { decodeErrPrefix } from './common.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} prefix
 * @param {number} length
 * @returns {Token}
 */
function toToken (_data, _pos, prefix, length) {
  return new Token(Type.array, length, prefix)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeArrayCompact (data, pos, minor, _options) {
  return toToken(data, pos, 1, minor)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer array lengths not supported`)
  }
  return toToken(data, pos, 9, l)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArrayIndefinite (data, pos, _minor, options) {
  if (options.allowIndefinite === false) {
    throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)
  }
  return toToken(data, pos, 1, Infinity)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeArray (writer, token) {
  uint.encodeUintValue(writer, Type.array.majorEncoded, token.value)
}

// using an array as a map key, are you sure about this? we can only sort
// by map length here, it's up to the encoder to decide to look deeper
encodeArray.compareTokens = uint.encodeUint.compareTokens

/**
 * @param {Token} token
 * @returns {number}
 */
encodeArray.encodedSize = function encodedSize (token) {
  return uint.encodeUintValue.encodedSize(token.value)
}
import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import { decodeErrPrefix } from './common.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} prefix
 * @param {number} length
 * @returns {Token}
 */
function toToken (_data, _pos, prefix, length) {
  return new Token(Type.map, length, prefix)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeMapCompact (data, pos, minor, _options) {
  return toToken(data, pos, 1, minor)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer map lengths not supported`)
  }
  return toToken(data, pos, 9, l)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMapIndefinite (data, pos, _minor, options) {
  if (options.allowIndefinite === false) {
    throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)
  }
  return toToken(data, pos, 1, Infinity)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeMap (writer, token) {
  uint.encodeUintValue(writer, Type.map.majorEncoded, token.value)
}

// using a map as a map key, are you sure about this? we can only sort
// by map length here, it's up to the encoder to decide to look deeper
encodeMap.compareTokens = uint.encodeUint.compareTokens

/**
 * @param {Token} token
 * @returns {number}
 */
encodeMap.encodedSize = function encodedSize (token) {
  return uint.encodeUintValue.encodedSize(token.value)
}
import { Token, Type } from './token.js'
import * as uint from './0uint.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeTagCompact (_data, _pos, minor, _options) {
  return new Token(Type.tag, minor, 1)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag8 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint8(data, pos + 1, options), 2)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag16 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint16(data, pos + 1, options), 3)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag32 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint32(data, pos + 1, options), 5)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag64 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint64(data, pos + 1, options), 9)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeTag (writer, token) {
  uint.encodeUintValue(writer, Type.tag.majorEncoded, token.value)
}

encodeTag.compareTokens = uint.encodeUint.compareTokens

/**
 * @param {Token} token
 * @returns {number}
 */
encodeTag.encodedSize = function encodedSize (token) {
  return uint.encodeUintValue.encodedSize(token.value)
}
// TODO: shift some of the bytes logic to bytes-utils so we can use Buffer
// where possible

import { Token, Type } from './token.js'
import { decodeErrPrefix } from './common.js'
import { encodeUint } from './0uint.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 * @typedef {import('../interface.js').EncodeOptions} EncodeOptions
 */

export const MINOR_FALSE = 20
export const MINOR_TRUE = 21
export const MINOR_NULL = 22
export const MINOR_UNDEFINED = 23

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUndefined (_data, _pos, _minor, options) {
  if (options.allowUndefined === false) {
    throw new Error(`${decodeErrPrefix} undefined values are not supported`)
  } else if (options.coerceUndefinedToNull === true) {
    return new Token(Type.null, null, 1)
  }
  return new Token(Type.undefined, undefined, 1)
}

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBreak (_data, _pos, _minor, options) {
  if (options.allowIndefinite === false) {
    throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)
  }
  return new Token(Type.break, undefined, 1)
}

/**
 * @param {number} value
 * @param {number} bytes
 * @param {DecodeOptions} options
 * @returns {Token}
 */
function createToken (value, bytes, options) {
  if (options) {
    if (options.allowNaN === false && Number.isNaN(value)) {
      throw new Error(`${decodeErrPrefix} NaN values are not supported`)
    }
    if (options.allowInfinity === false && (value === Infinity || value === -Infinity)) {
      throw new Error(`${decodeErrPrefix} Infinity values are not supported`)
    }
  }
  return new Token(Type.float, value, bytes)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeFloat16 (data, pos, _minor, options) {
  return createToken(readFloat16(data, pos + 1), 3, options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeFloat32 (data, pos, _minor, options) {
  return createToken(readFloat32(data, pos + 1), 5, options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeFloat64 (data, pos, _minor, options) {
  return createToken(readFloat64(data, pos + 1), 9, options)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 * @param {EncodeOptions} options
 */
export function encodeFloat (writer, token, options) {
  const float = token.value

  if (float === false) {
    writer.push([Type.float.majorEncoded | MINOR_FALSE])
  } else if (float === true) {
    writer.push([Type.float.majorEncoded | MINOR_TRUE])
  } else if (float === null) {
    writer.push([Type.float.majorEncoded | MINOR_NULL])
  } else if (float === undefined) {
    writer.push([Type.float.majorEncoded | MINOR_UNDEFINED])
  } else {
    let decoded
    let success = false
    if (!options || options.float64 !== true) {
      encodeFloat16(float)
      decoded = readFloat16(ui8a, 1)
      if (float === decoded || Number.isNaN(float)) {
        ui8a[0] = 0xf9
        writer.push(ui8a.slice(0, 3))
        success = true
      } else {
        encodeFloat32(float)
        decoded = readFloat32(ui8a, 1)
        if (float === decoded) {
          ui8a[0] = 0xfa
          writer.push(ui8a.slice(0, 5))
          success = true
        }
      }
    }
    if (!success) {
      encodeFloat64(float)
      decoded = readFloat64(ui8a, 1)
      ui8a[0] = 0xfb
      writer.push(ui8a.slice(0, 9))
    }
  }
}

/**
 * @param {Token} token
 * @param {EncodeOptions} options
 * @returns {number}
 */
encodeFloat.encodedSize = function encodedSize (token, options) {
  const float = token.value

  if (float === false || float === true || float === null || float === undefined) {
    return 1
  }

  if (!options || options.float64 !== true) {
    encodeFloat16(float)
    let decoded = readFloat16(ui8a, 1)
    if (float === decoded || Number.isNaN(float)) {
      return 3
    }
    encodeFloat32(float)
    decoded = readFloat32(ui8a, 1)
    if (float === decoded) {
      return 5
    }
  }
  return 9
}

const buffer = new ArrayBuffer(9)
const dataView = new DataView(buffer, 1)
const ui8a = new Uint8Array(buffer, 0)

/**
 * @param {number} inp
 */
function encodeFloat16 (inp) {
  if (inp === Infinity) {
    dataView.setUint16(0, 0x7c00, false)
  } else if (inp === -Infinity) {
    dataView.setUint16(0, 0xfc00, false)
  } else if (Number.isNaN(inp)) {
    dataView.setUint16(0, 0x7e00, false)
  } else {
    dataView.setFloat32(0, inp)
    const valu32 = dataView.getUint32(0)
    const exponent = (valu32 & 0x7f800000) >> 23
    const mantissa = valu32 & 0x7fffff

    if (exponent === 0xff) {
      // too big, Infinity, but this should be hard (impossible?) to trigger
      dataView.setUint16(0, 0x7c00, false)
    } else if (exponent === 0x00) {
      // 0.0, -0.0 and subnormals, shouldn't be possible to get here because 0.0 should be counted as an int
      // Use valu32 for sign bit since bitwise ops on floats lose -0 sign
      dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | (mantissa >> 13), false)
    } else { // standard numbers
      // chunks of logic here borrowed from https://github.com/PJK/libcbor/blob/c78f437182533e3efa8d963ff4b945bb635c2284/src/cbor/encoding.c#L127
      const logicalExponent = exponent - 127
      // Now we know that 2^exponent <= 0 logically
      if (logicalExponent < -24) {
        /* No unambiguous representation exists, this float is not a half float
          and is too small to be represented using a half, round off to zero.
          Consistent with the reference implementation. */
        // should be difficult (impossible?) to get here in JS
        dataView.setUint16(0, 0)
      } else if (logicalExponent < -14) {
        /* Offset the remaining decimal places by shifting the significand, the
          value is lost. This is an implementation decision that works around the
          absence of standard half-float in the language. */
        dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | /* sign bit */ (1 << (24 + logicalExponent)), false)
      } else {
        dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | ((logicalExponent + 15) << 10) | (mantissa >> 13), false)
      }
    }
  }
}

/**
 * @param {Uint8Array} ui8a
 * @param {number} pos
 * @returns {number}
 */
function readFloat16 (ui8a, pos) {
  if (ui8a.length - pos < 2) {
    throw new Error(`${decodeErrPrefix} not enough data for float16`)
  }

  const half = (ui8a[pos] << 8) + ui8a[pos + 1]
  if (half === 0x7c00) {
    return Infinity
  }
  if (half === 0xfc00) {
    return -Infinity
  }
  if (half === 0x7e00) {
    return NaN
  }
  const exp = (half >> 10) & 0x1f
  const mant = half & 0x3ff
  let val
  if (exp === 0) {
    val = mant * (2 ** -24)
  } else if (exp !== 31) {
    val = (mant + 1024) * (2 ** (exp - 25))
  } else {
    // may not be possible to get here
    val = mant === 0 ? Infinity : NaN
  }
  return (half & 0x8000) ? -val : val
}

/**
 * @param {number} inp
 */
function encodeFloat32 (inp) {
  dataView.setFloat32(0, inp, false)
}

/**
 * @param {Uint8Array} ui8a
 * @param {number} pos
 * @returns {number}
 */
function readFloat32 (ui8a, pos) {
  if (ui8a.length - pos < 4) {
    throw new Error(`${decodeErrPrefix} not enough data for float32`)
  }
  const offset = (ui8a.byteOffset || 0) + pos
  return new DataView(ui8a.buffer, offset, 4).getFloat32(0, false)
}

/**
 * @param {number} inp
 */
function encodeFloat64 (inp) {
  dataView.setFloat64(0, inp, false)
}

/**
 * @param {Uint8Array} ui8a
 * @param {number} pos
 * @returns {number}
 */
function readFloat64 (ui8a, pos) {
  if (ui8a.length - pos < 8) {
    throw new Error(`${decodeErrPrefix} not enough data for float64`)
  }
  const offset = (ui8a.byteOffset || 0) + pos
  return new DataView(ui8a.buffer, offset, 8).getFloat64(0, false)
}

/**
 * @param {Token} _tok1
 * @param {Token} _tok2
 * @returns {number}
 */
encodeFloat.compareTokens = encodeUint.compareTokens
/*
encodeFloat.compareTokens = function compareTokens (_tok1, _tok2) {
  return _tok1
  throw new Error(`${encodeErrPrefix} cannot use floats as map keys`)
}
*/
/**
 * Bl is a list of byte chunks, similar to https://github.com/rvagg/bl but for
 * writing rather than reading.
 * A Bl object accepts set() operations for individual bytes and copyTo() for
 * inserting byte arrays. These write operations don't automatically increment
 * the internal cursor so its "length" won't be changed. Instead, increment()
 * must be called to extend its length to cover the inserted data.
 * The toBytes() call will convert all internal memory to a single Uint8Array of
 * the correct length, truncating any data that is stored but hasn't been
 * included by an increment().
 * get() can retrieve a single byte.
 * All operations (except toBytes()) take an "offset" argument that will perform
 * the write at the offset _from the current cursor_. For most operations this
 * will be `0` to write at the current cursor position but it can be ahead of
 * the current cursor. Negative offsets probably work but are untested.
 */

// TODO: ipjs doesn't support this, only for test files: https://github.com/mikeal/ipjs/blob/master/src/package/testFile.js#L39
import { alloc, concat, slice } from './byte-utils.js'

// the ts-ignores in this file are almost all for the `Uint8Array|number[]` duality that exists
// for perf reasons. Consider better approaches to this or removing it entirely, it is quite
// risky because of some assumptions about small chunks === number[] and everything else === Uint8Array.

const defaultChunkSize = 256

export class Bl {
  /**
   * @param {number} [chunkSize]
   */
  constructor (chunkSize = defaultChunkSize) {
    this.chunkSize = chunkSize
    /** @type {number} */
    this.cursor = 0
    /** @type {number} */
    this.maxCursor = -1
    /** @type {(Uint8Array|number[])[]} */
    this.chunks = []
    // keep the first chunk around if we can to save allocations for future encodes
    /** @type {Uint8Array|number[]|null} */
    this._initReuseChunk = null
  }

  reset () {
    this.cursor = 0
    this.maxCursor = -1
    if (this.chunks.length) {
      this.chunks = []
    }
    if (this._initReuseChunk !== null) {
      this.chunks.push(this._initReuseChunk)
      this.maxCursor = this._initReuseChunk.length - 1
    }
  }

  /**
   * @param {Uint8Array|number[]} bytes
   */
  push (bytes) {
    let topChunk = this.chunks[this.chunks.length - 1]
    const newMax = this.cursor + bytes.length
    if (newMax <= this.maxCursor + 1) {
      // we have at least one chunk and we can fit these bytes into that chunk
      const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1
      // @ts-ignore
      topChunk.set(bytes, chunkPos)
    } else {
      // can't fit it in
      if (topChunk) {
        // trip the last chunk to `cursor` if we need to
        const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1
        if (chunkPos < topChunk.length) {
          // @ts-ignore
          this.chunks[this.chunks.length - 1] = topChunk.subarray(0, chunkPos)
          this.maxCursor = this.cursor - 1
        }
      }
      if (bytes.length < 64 && bytes.length < this.chunkSize) {
        // make a new chunk and copy the new one into it
        topChunk = alloc(this.chunkSize)
        this.chunks.push(topChunk)
        this.maxCursor += topChunk.length
        if (this._initReuseChunk === null) {
          this._initReuseChunk = topChunk
        }
        // @ts-ignore
        topChunk.set(bytes, 0)
      } else {
        // push the new bytes in as its own chunk
        this.chunks.push(bytes)
        this.maxCursor += bytes.length
      }
    }
    this.cursor += bytes.length
  }

  /**
   * @param {boolean} [reset]
   * @returns {Uint8Array}
   */
  toBytes (reset = false) {
    let byts
    if (this.chunks.length === 1) {
      const chunk = this.chunks[0]
      if (reset && this.cursor > chunk.length / 2) {
        // @ts-ignore
        byts = this.cursor === chunk.length ? chunk : chunk.subarray(0, this.cursor)
        this._initReuseChunk = null
        this.chunks = []
      } else {
        // @ts-ignore
        byts = slice(chunk, 0, this.cursor)
      }
    } else {
      // @ts-ignore
      byts = concat(this.chunks, this.cursor)
    }
    if (reset) {
      this.reset()
    }
    return byts
  }
}

/**
 * U8Bl is a buffer list that writes directly to a user-provided Uint8Array.
 * It provides the same interface as Bl but writes to a fixed destination.
 */
export class U8Bl {
  /**
   * @param {Uint8Array} dest
   */
  constructor (dest) {
    this.dest = dest
    /** @type {number} */
    this.cursor = 0
    // chunks is for interface compatibility with Bl - encode.js checks chunks.length
    // as a sanity check for pre-calculated sizes. For U8Bl this is always [dest].
    /** @type {Uint8Array[]} */
    this.chunks = [dest]
  }

  reset () {
    this.cursor = 0
  }

  /**
   * @param {Uint8Array|number[]} bytes
   */
  push (bytes) {
    if (this.cursor + bytes.length > this.dest.length) {
      throw new Error('write out of bounds, destination buffer is too small')
    }
    this.dest.set(bytes, this.cursor)
    this.cursor += bytes.length
  }

  /**
   * @param {boolean} [reset]
   * @returns {Uint8Array}
   */
  toBytes (reset = false) {
    const byts = this.dest.subarray(0, this.cursor)
    if (reset) {
      this.reset()
    }
    return byts
  }
}
// Use Uint8Array directly in the browser, use Buffer in Node.js but don't
// speak its name directly to avoid bundlers pulling in the `Buffer` polyfill

// @ts-ignore
export const useBuffer = globalThis.process &&
  // @ts-ignore
  !globalThis.process.browser &&
  // @ts-ignore
  globalThis.Buffer &&
  // @ts-ignore
  typeof globalThis.Buffer.isBuffer === 'function'

const textEncoder = new TextEncoder()

/**
 * @param {Uint8Array} buf
 * @returns {boolean}
 */
function isBuffer (buf) {
  // @ts-ignore
  return useBuffer && globalThis.Buffer.isBuffer(buf)
}

/**
 * @param {Uint8Array|number[]} buf
 * @returns {Uint8Array}
 */
export function asU8A (buf) {
  if (!(buf instanceof Uint8Array)) {
    return Uint8Array.from(buf)
  }
  return isBuffer(buf) ? new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength) : buf
}

// Threshold for manual UTF-8 encoding vs native methods.
// Node.js Buffer.from: crossover ~24 chars
// Browser TextEncoder: crossover ~200 chars
const FROM_STRING_THRESHOLD_BUFFER = 24
const FROM_STRING_THRESHOLD_TEXTENCODER = 200

export const fromString = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {string} string
     */
    (string) => {
      return string.length >= FROM_STRING_THRESHOLD_BUFFER
        ? // eslint-disable-line operator-linebreak
      // @ts-ignore
        globalThis.Buffer.from(string)
        : utf8ToBytes(string)
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {string} string
     */
    (string) => {
      return string.length >= FROM_STRING_THRESHOLD_TEXTENCODER ? textEncoder.encode(string) : utf8ToBytes(string)
    }

/**
 * Buffer variant not fast enough for what we need
 * @param {number[]} arr
 * @returns {Uint8Array}
 */
export const fromArray = (arr) => {
  return Uint8Array.from(arr)
}

export const slice = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} bytes
     * @param {number} start
     * @param {number} end
     */
    // Buffer.slice() returns a view, not a copy, so we need special handling
    (bytes, start, end) => {
      if (isBuffer(bytes)) {
        return new Uint8Array(bytes.subarray(start, end))
      }
      return bytes.slice(start, end)
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} bytes
     * @param {number} start
     * @param {number} end
     */
    (bytes, start, end) => {
      return bytes.slice(start, end)
    }

export const concat = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array[]} chunks
     * @param {number} length
     * @returns {Uint8Array}
     */
    (chunks, length) => {
      // might get a stray plain Array here
      chunks = chunks.map((c) => c instanceof Uint8Array
        ? c
        : // eslint-disable-line operator-linebreak
        // @ts-ignore
        globalThis.Buffer.from(c))
      // @ts-ignore
      return asU8A(globalThis.Buffer.concat(chunks, length))
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array[]} chunks
     * @param {number} length
     * @returns {Uint8Array}
     */
    (chunks, length) => {
      const out = new Uint8Array(length)
      let off = 0
      for (let b of chunks) {
        if (off + b.length > out.length) {
          // final chunk that's bigger than we need
          b = b.subarray(0, out.length - off)
        }
        out.set(b, off)
        off += b.length
      }
      return out
    }

export const alloc = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {number} size
     * @returns {Uint8Array}
     */
    (size) => {
      // we always write over the contents we expose so this should be safe
      // @ts-ignore
      return globalThis.Buffer.allocUnsafe(size)
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {number} size
     * @returns {Uint8Array}
     */
    (size) => {
      return new Uint8Array(size)
    }

export const toHex = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} d
     * @returns {string}
     */
    (d) => {
      if (typeof d === 'string') {
        return d
      }
      // @ts-ignore
      return globalThis.Buffer.from(toBytes(d)).toString('hex')
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} d
     * @returns {string}
     */
    (d) => {
      if (typeof d === 'string') {
        return d
      }
      // @ts-ignore not smart enough to figure this out
      return Array.prototype.reduce.call(toBytes(d), (p, c) => `${p}${c.toString(16).padStart(2, '0')}`, '')
    }

export const fromHex = useBuffer
  ? // eslint-disable-line operator-linebreak
  /**
   * @param {string|Uint8Array} hex
   * @returns {Uint8Array}
   */
    (hex) => {
      if (hex instanceof Uint8Array) {
        return hex
      }
      // @ts-ignore
      return globalThis.Buffer.from(hex, 'hex')
    }
  : // eslint-disable-line operator-linebreak
  /**
   * @param {string|Uint8Array} hex
   * @returns {Uint8Array}
   */
    (hex) => {
      if (hex instanceof Uint8Array) {
        return hex
      }
      if (!hex.length) {
        return new Uint8Array(0)
      }
      return new Uint8Array(hex.split('')
        .map((/** @type {string} */ c, /** @type {number} */ i, /** @type {string[]} */ d) => i % 2 === 0 ? `0x${c}${d[i + 1]}` : '')
        .filter(Boolean)
        .map((/** @type {string} */ e) => parseInt(e, 16)))
    }

/**
 * @param {Uint8Array|ArrayBuffer|ArrayBufferView} obj
 * @returns {Uint8Array}
 */
function toBytes (obj) {
  if (obj instanceof Uint8Array && obj.constructor.name === 'Uint8Array') {
    return obj
  }
  if (obj instanceof ArrayBuffer) {
    return new Uint8Array(obj)
  }
  if (ArrayBuffer.isView(obj)) {
    return new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength)
  }
  throw new Error('Unknown type, must be binary type')
}

/**
 * @param {Uint8Array} b1
 * @param {Uint8Array} b2
 * @returns {number}
 */
export function compare (b1, b2) {
  if (isBuffer(b1) && isBuffer(b2)) {
    // probably not possible to get here in the current API
    // @ts-ignore Buffer
    return b1.compare(b2)
  }
  for (let i = 0; i < b1.length; i++) {
    if (b1[i] === b2[i]) {
      continue
    }
    return b1[i] < b2[i] ? -1 : 1
  }
  return 0
}

// The below code is taken from https://github.com/google/closure-library/blob/8598d87242af59aac233270742c8984e2b2bdbe0/closure/goog/crypt/crypt.js#L117-L143
// Licensed Apache-2.0.

/**
 * @param {string} str
 * @returns {number[]}
 */
function utf8ToBytes (str) {
  const out = []
  let p = 0
  for (let i = 0; i < str.length; i++) {
    let c = str.charCodeAt(i)
    if (c < 128) {
      out[p++] = c
    } else if (c < 2048) {
      out[p++] = (c >> 6) | 192
      out[p++] = (c & 63) | 128
    } else if (
      ((c & 0xFC00) === 0xD800) && (i + 1) < str.length &&
      ((str.charCodeAt(i + 1) & 0xFC00) === 0xDC00)) {
      // Surrogate Pair
      c = 0x10000 + ((c & 0x03FF) << 10) + (str.charCodeAt(++i) & 0x03FF)
      out[p++] = (c >> 18) | 240
      out[p++] = ((c >> 12) & 63) | 128
      out[p++] = ((c >> 6) & 63) | 128
      out[p++] = (c & 63) | 128
    } else {
      if ((c >= 0xD800) && (c <= 0xDFFF)) {
        c = 0xFFFD // Unpaired Surrogate
      }
      out[p++] = (c >> 12) | 224
      out[p++] = ((c >> 6) & 63) | 128
      out[p++] = (c & 63) | 128
    }
  }
  return out
}

// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
const MAX_ARGUMENTS_LENGTH = 0x1000

/**
 * @param {number[]} codePoints
 * @returns {string}
 */
export function decodeCodePointsArray (codePoints) {
  const len = codePoints.length
  if (len <= MAX_ARGUMENTS_LENGTH) {
    return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  }
  // Decode in chunks to avoid "call stack size exceeded".
  let res = ''
  let i = 0
  while (i < len) {
    res += String.fromCharCode.apply(
      String,
      codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
    )
  }
  return res
}
const decodeErrPrefix = 'CBOR decode error:'
const encodeErrPrefix = 'CBOR encode error:'

const uintMinorPrefixBytes = []
uintMinorPrefixBytes[23] = 1
uintMinorPrefixBytes[24] = 2
uintMinorPrefixBytes[25] = 3
uintMinorPrefixBytes[26] = 5
uintMinorPrefixBytes[27] = 9

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} need
 */
function assertEnoughData (data, pos, need) {
  if (data.length - pos < need) {
    throw new Error(`${decodeErrPrefix} not enough data for type`)
  }
}

export {
  decodeErrPrefix,
  encodeErrPrefix,
  uintMinorPrefixBytes,
  assertEnoughData
}
import { decodeErrPrefix } from './common.js'
import { Type } from './token.js'
import { jump, quick } from './jump.js'
import { asU8A } from './byte-utils.js'

/**
 * @typedef {import('./token.js').Token} Token
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 * @typedef {import('../interface.js').DecodeTokenizer} DecodeTokenizer
 * @typedef {import('../interface.js').TagDecodeControl} TagDecodeControl
 */

const defaultDecodeOptions = {
  strict: false,
  allowIndefinite: true,
  allowUndefined: true,
  allowBigInt: true
}

/**
 * @implements {DecodeTokenizer}
 */
class Tokeniser {
  /**
   * @param {Uint8Array} data
   * @param {DecodeOptions} options
   */
  constructor (data, options = {}) {
    this._pos = 0
    this.data = data
    this.options = options
  }

  pos () {
    return this._pos
  }

  done () {
    return this._pos >= this.data.length
  }

  next () {
    const byt = this.data[this._pos]
    let token = quick[byt]
    if (token === undefined) {
      const decoder = jump[byt]
      // if we're here then there's something wrong with our jump or quick lists!
      if (!decoder) {
        throw new Error(`${decodeErrPrefix} no decoder for major type ${byt >>> 5} (byte 0x${byt.toString(16).padStart(2, '0')})`)
      }
      const minor = byt & 31
      token = decoder(this.data, this._pos, minor, this.options)
    }
    // @ts-ignore we get to assume encodedLength is set (crossing fingers slightly)
    this._pos += token.encodedLength
    return token
  }
}

const DONE = Symbol.for('DONE')
const BREAK = Symbol.for('BREAK')

/**
 * @param {Token} token
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {any|BREAK|DONE}
 */
function tokenToArray (token, tokeniser, options) {
  const arr = []
  for (let i = 0; i < token.value; i++) {
    const value = tokensToObject(tokeniser, options)
    if (value === BREAK) {
      if (token.value === Infinity) {
        // normal end to indefinite length array
        break
      }
      throw new Error(`${decodeErrPrefix} got unexpected break to lengthed array`)
    }
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} found array but not enough entries (got ${i}, expected ${token.value})`)
    }
    arr[i] = value
  }
  return arr
}

/**
 * @param {Token} token
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {any|BREAK|DONE}
 */
function tokenToMap (token, tokeniser, options) {
  const useMaps = options.useMaps === true
  const rejectDuplicateMapKeys = options.rejectDuplicateMapKeys === true
  const obj = useMaps ? undefined : {}
  const m = useMaps ? new Map() : undefined
  for (let i = 0; i < token.value; i++) {
    const key = tokensToObject(tokeniser, options)
    if (key === BREAK) {
      if (token.value === Infinity) {
        // normal end to indefinite length map
        break
      }
      throw new Error(`${decodeErrPrefix} got unexpected break to lengthed map`)
    }
    if (key === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no key], expected ${token.value})`)
    }
    if (!useMaps && typeof key !== 'string') {
      throw new Error(`${decodeErrPrefix} non-string keys not supported (got ${typeof key})`)
    }
    if (rejectDuplicateMapKeys) {
      // @ts-ignore
      if ((useMaps && m.has(key)) || (!useMaps && Object.hasOwn(obj, key))) {
        throw new Error(`${decodeErrPrefix} found repeat map key "${key}"`)
      }
    }
    const value = tokensToObject(tokeniser, options)
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no value], expected ${token.value})`)
    }
    if (useMaps) {
      // @ts-ignore TODO reconsider this .. maybe needs to be strict about key types
      m.set(key, value)
    } else {
      // @ts-ignore TODO reconsider this .. maybe needs to be strict about key types
      obj[key] = value
    }
  }
  // @ts-ignore c'mon man
  return useMaps ? m : obj
}

/**
 * Generator that yields [key, value] entries from a CBOR map token.
 * Used by tag decoders that need to preserve key types (e.g., Tag 259 Map).
 * @param {Token} token - The map token
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {Generator<[any, any], void, unknown>}
 */
function * tokenToMapEntries (token, tokeniser, options) {
  for (let i = 0; i < token.value; i++) {
    const key = tokensToObject(tokeniser, options)
    if (key === BREAK) {
      if (token.value === Infinity) {
        // normal end to indefinite length map
        break
      }
      throw new Error(`${decodeErrPrefix} got unexpected break to lengthed map`)
    }
    if (key === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no key], expected ${token.value})`)
    }
    const value = tokensToObject(tokeniser, options)
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no value], expected ${token.value})`)
    }
    yield [key, value]
  }
}

/**
 * Creates a TagDecodeControl object for tag decoders.
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {TagDecodeControl}
 */
function createTagDecodeControl (tokeniser, options) {
  let called = false

  /**
   * @type {TagDecodeControl}
   */
  const decode = function () {
    if (called) {
      throw new Error(`${decodeErrPrefix} tag decode() may only be called once`)
    }
    called = true
    const value = tokensToObject(tokeniser, options)
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} tag content missing`)
    }
    if (value === BREAK) {
      throw new Error(`${decodeErrPrefix} got unexpected break in tag content`)
    }
    return value
  }

  decode.entries = function () {
    if (called) {
      throw new Error(`${decodeErrPrefix} tag decode() may only be called once`)
    }
    called = true

    // Get the next token and ensure it's a map
    const token = tokeniser.next()
    if (!Type.equals(token.type, Type.map)) {
      throw new Error(`${decodeErrPrefix} entries() requires map content, got ${token.type.name}`)
    }

    // Collect all entries into an array (ensures full content consumption)
    const entries = []
    for (const entry of tokenToMapEntries(token, tokeniser, options)) {
      entries.push(entry)
    }
    return entries
  }

  // For internal tracking
  Object.defineProperty(decode, '_called', {
    get () { return called },
    enumerable: false
  })

  return decode
}

/**
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {any|BREAK|DONE}
 */
function tokensToObject (tokeniser, options) {
  // should we support array as an argument?
  // check for tokenIter[Symbol.iterator] and replace tokenIter with what that returns?
  if (tokeniser.done()) {
    return DONE
  }

  const token = tokeniser.next()

  if (Type.equals(token.type, Type.break)) {
    return BREAK
  }

  if (token.type.terminal) {
    return token.value
  }

  if (Type.equals(token.type, Type.array)) {
    return tokenToArray(token, tokeniser, options)
  }

  if (Type.equals(token.type, Type.map)) {
    return tokenToMap(token, tokeniser, options)
  }

  if (Type.equals(token.type, Type.tag)) {
    if (options.tags && typeof options.tags[token.value] === 'function') {
      const decodeControl = createTagDecodeControl(tokeniser, options)
      const result = options.tags[token.value](decodeControl)
      if (!decodeControl._called) {
        throw new Error(`${decodeErrPrefix} tag decoder must call decode() or entries()`)
      }
      return result
    }
    throw new Error(`${decodeErrPrefix} tag not supported (${token.value})`)
  }
  throw new Error('unsupported')
}

/**
 * @param {Uint8Array} data
 * @param {DecodeOptions} [options]
 * @returns {[any, Uint8Array]}
 */
function decodeFirst (data, options) {
  if (!(data instanceof Uint8Array)) {
    throw new Error(`${decodeErrPrefix} data to decode must be a Uint8Array`)
  }
  options = Object.assign({}, defaultDecodeOptions, options)
  // Convert Buffer to plain Uint8Array for faster slicing in decode path
  const u8aData = asU8A(data)
  const tokeniser = options.tokenizer || new Tokeniser(u8aData, options)
  const decoded = tokensToObject(tokeniser, options)
  if (decoded === DONE) {
    throw new Error(`${decodeErrPrefix} did not find any content to decode`)
  }
  if (decoded === BREAK) {
    throw new Error(`${decodeErrPrefix} got unexpected break`)
  }
  return [decoded, data.subarray(tokeniser.pos())]
}

/**
 * @param {Uint8Array} data
 * @param {DecodeOptions} [options]
 * @returns {any}
 */
function decode (data, options) {
  const [decoded, remainder] = decodeFirst(data, options)
  if (remainder.length > 0) {
    throw new Error(`${decodeErrPrefix} too many terminals, data makes no sense`)
  }
  return decoded
}

export { Tokeniser, tokensToObject, decode, decodeFirst }
import { is } from './is.js'
import { Token, Type } from './token.js'
import { Bl, U8Bl } from './bl.js'
import { encodeErrPrefix } from './common.js'
import { quickEncodeToken } from './jump.js'
import { asU8A, compare, fromString } from './byte-utils.js'

import { encodeUint, encodeUintValue } from './0uint.js'
import { encodeNegint } from './1negint.js'
import { encodeBytes } from './2bytes.js'
import { encodeString } from './3string.js'
import { encodeArray } from './4array.js'
import { encodeMap } from './5map.js'
import { encodeTag } from './6tag.js'
import { encodeFloat, MINOR_FALSE, MINOR_TRUE, MINOR_NULL, MINOR_UNDEFINED } from './7float.js'

/**
 * @typedef {import('../interface.js').EncodeOptions} EncodeOptions
 * @typedef {import('../interface.js').OptionalTypeEncoder} OptionalTypeEncoder
 * @typedef {import('../interface.js').Reference} Reference
 * @typedef {import('../interface.js').StrictTypeEncoder} StrictTypeEncoder
 * @typedef {import('../interface.js').TokenTypeEncoder} TokenTypeEncoder
 * @typedef {import('../interface.js').TokenOrNestedTokens} TokenOrNestedTokens
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 */

/** @type {EncodeOptions} */
const defaultEncodeOptions = {
  float64: false,
  mapSorter,
  quickEncodeToken
}

/** @type {EncodeOptions} */
export const rfc8949EncodeOptions = Object.freeze({
  mapSorter: rfc8949MapSorter,
  quickEncodeToken
})

/** @returns {TokenTypeEncoder[]} */
export function makeCborEncoders () {
  const encoders = []
  encoders[Type.uint.major] = encodeUint
  encoders[Type.negint.major] = encodeNegint
  encoders[Type.bytes.major] = encodeBytes
  encoders[Type.string.major] = encodeString
  encoders[Type.array.major] = encodeArray
  encoders[Type.map.major] = encodeMap
  encoders[Type.tag.major] = encodeTag
  encoders[Type.float.major] = encodeFloat
  return encoders
}

const cborEncoders = makeCborEncoders()

const defaultWriter = new Bl()

/** @implements {Reference} */
class Ref {
  /**
   * @param {object|any[]} obj
   * @param {Reference|undefined} parent
   */
  constructor (obj, parent) {
    this.obj = obj
    this.parent = parent
  }

  /**
   * @param {object|any[]} obj
   * @returns {boolean}
   */
  includes (obj) {
    /** @type {Reference|undefined} */
    let p = this
    do {
      if (p.obj === obj) {
        return true
      }
    } while (p = p.parent) // eslint-disable-line
    return false
  }

  /**
   * @param {Reference|undefined} stack
   * @param {object|any[]} obj
   * @returns {Reference}
   */
  static createCheck (stack, obj) {
    if (stack && stack.includes(obj)) {
      throw new Error(`${encodeErrPrefix} object contains circular references`)
    }
    return new Ref(obj, stack)
  }
}

const simpleTokens = {
  null: new Token(Type.null, null),
  undefined: new Token(Type.undefined, undefined),
  true: new Token(Type.true, true),
  false: new Token(Type.false, false),
  emptyArray: new Token(Type.array, 0),
  emptyMap: new Token(Type.map, 0)
}

/** @type {{[typeName: string]: StrictTypeEncoder}} */
const typeEncoders = {
  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  number (obj, _typ, _options, _refStack) {
    if (!Number.isInteger(obj) || !Number.isSafeInteger(obj)) {
      return new Token(Type.float, obj)
    } else if (obj >= 0) {
      return new Token(Type.uint, obj)
    } else {
      return new Token(Type.negint, obj)
    }
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  bigint (obj, _typ, _options, _refStack) {
    if (obj >= BigInt(0)) {
      return new Token(Type.uint, obj)
    } else {
      return new Token(Type.negint, obj)
    }
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  Uint8Array (obj, _typ, _options, _refStack) {
    return new Token(Type.bytes, obj)
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  string (obj, _typ, _options, _refStack) {
    return new Token(Type.string, obj)
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  boolean (obj, _typ, _options, _refStack) {
    return obj ? simpleTokens.true : simpleTokens.false
  },

  /**
   * @param {any} _obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  null (_obj, _typ, _options, _refStack) {
    return simpleTokens.null
  },

  /**
   * @param {any} _obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  undefined (_obj, _typ, _options, _refStack) {
    return simpleTokens.undefined
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  ArrayBuffer (obj, _typ, _options, _refStack) {
    return new Token(Type.bytes, new Uint8Array(obj))
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  DataView (obj, _typ, _options, _refStack) {
    return new Token(Type.bytes, new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength))
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} options
   * @param {Reference} [refStack]
   * @returns {TokenOrNestedTokens}
   */
  Array (obj, _typ, options, refStack) {
    if (!obj.length) {
      if (options.addBreakTokens === true) {
        return [simpleTokens.emptyArray, new Token(Type.break)]
      }
      return simpleTokens.emptyArray
    }
    refStack = Ref.createCheck(refStack, obj)
    const entries = []
    let i = 0
    for (const e of obj) {
      entries[i++] = objectToTokens(e, options, refStack)
    }
    if (options.addBreakTokens) {
      return [new Token(Type.array, obj.length), entries, new Token(Type.break)]
    }
    return [new Token(Type.array, obj.length), entries]
  },

  /**
   * @param {any} obj
   * @param {string} typ
   * @param {EncodeOptions} options
   * @param {Reference} [refStack]
   * @returns {TokenOrNestedTokens}
   */
  Object (obj, typ, options, refStack) {
    // could be an Object or a Map
    const isMap = typ !== 'Object'
    // it's slightly quicker to use Object.keys() than Object.entries()
    const keys = isMap ? obj.keys() : Object.keys(obj)
    const maxLength = isMap ? obj.size : keys.length

    /** @type {undefined | [TokenOrNestedTokens, TokenOrNestedTokens][]} */
    let entries

    if (maxLength) {
      // Pre-allocate the array with the expected size
      entries = new Array(maxLength)
      refStack = Ref.createCheck(refStack, obj)
      const skipUndefined = !isMap && options.ignoreUndefinedProperties

      let i = 0
      for (const key of keys) {
        const value = isMap ? obj.get(key) : obj[key]
        if (skipUndefined && value === undefined) {
          continue
        }
        entries[i++] = [
          objectToTokens(key, options, refStack),
          objectToTokens(value, options, refStack)
        ]
      }

      // Truncate only if properties were skipped
      if (i < maxLength) {
        entries.length = i
      }
    }

    if (!entries?.length) {
      if (options.addBreakTokens === true) {
        return [simpleTokens.emptyMap, new Token(Type.break)]
      }
      return simpleTokens.emptyMap
    }

    sortMapEntries(entries, options)
    if (options.addBreakTokens) {
      return [new Token(Type.map, entries.length), entries, new Token(Type.break)]
    }
    return [new Token(Type.map, entries.length), entries]
  },

  /**
   * Encode a `Tagged` wrapper as a CBOR tag header followed by the encoded
   * form of the wrapped value. The value is recursively tokenised through
   * `objectToTokens()` so any registered `typeEncoders` apply to it.
   *
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} options
   * @param {Reference} [refStack]
   * @returns {TokenOrNestedTokens}
   */
  Tagged (obj, _typ, options, refStack) {
    return [
      new Token(Type.tag, obj.tag),
      objectToTokens(obj.value, options, refStack)
    ]
  }
}

typeEncoders.Map = typeEncoders.Object
typeEncoders.Buffer = typeEncoders.Uint8Array
for (const typ of 'Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64'.split(' ')) {
  typeEncoders[`${typ}Array`] = typeEncoders.DataView
}

/**
 * @param {any} obj
 * @param {EncodeOptions} [options]
 * @param {Reference} [refStack]
 * @returns {TokenOrNestedTokens}
 */
function objectToTokens (obj, options = {}, refStack) {
  const typ = is(obj)
  const customTypeEncoder = (options && options.typeEncoders && /** @type {OptionalTypeEncoder} */ options.typeEncoders[typ]) || typeEncoders[typ]
  if (typeof customTypeEncoder === 'function') {
    const tokens = customTypeEncoder(obj, typ, options, refStack)
    if (tokens != null) {
      return tokens
    }
  }
  const typeEncoder = typeEncoders[typ]
  if (!typeEncoder) {
    throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`)
  }
  return typeEncoder(obj, typ, options, refStack)
}

/*
CBOR key sorting is a mess.

The canonicalisation recommendation from https://tools.ietf.org/html/rfc7049#section-3.9
includes the wording:

> The keys in every map must be sorted lowest value to highest.
> Sorting is performed on the bytes of the representation of the key
> data items without paying attention to the 3/5 bit splitting for
> major types.
> ...
>  *  If two keys have different lengths, the shorter one sorts
      earlier;
>  *  If two keys have the same length, the one with the lower value
      in (byte-wise) lexical order sorts earlier.

1. It is not clear what "bytes of the representation of the key" means: is it
   the CBOR representation, or the binary representation of the object itself?
   Consider the int and uint difference here.
2. It is not clear what "without paying attention to" means: do we include it
   and compare on that? Or do we omit the special prefix byte, (mostly) treating
   the key in its plain binary representation form.

The FIDO 2.0: Client To Authenticator Protocol spec takes the original CBOR
wording and clarifies it according to their understanding.
https://fidoalliance.org/specs/fido-v2.0-rd-20170927/fido-client-to-authenticator-protocol-v2.0-rd-20170927.html#message-encoding

> The keys in every map must be sorted lowest value to highest. Sorting is
> performed on the bytes of the representation of the key data items without
> paying attention to the 3/5 bit splitting for major types. The sorting rules
> are:
>  * If the major types are different, the one with the lower value in numerical
>    order sorts earlier.
>  * If two keys have different lengths, the shorter one sorts earlier;
>  * If two keys have the same length, the one with the lower value in
>    (byte-wise) lexical order sorts earlier.

Some other implementations, such as borc, do a full encode then do a
length-first, byte-wise-second comparison:
https://github.com/dignifiedquire/borc/blob/b6bae8b0bcde7c3976b0f0f0957208095c392a36/src/encoder.js#L358
https://github.com/dignifiedquire/borc/blob/b6bae8b0bcde7c3976b0f0f0957208095c392a36/src/utils.js#L143-L151

This has the benefit of being able to easily handle arbitrary keys, including
complex types (maps and arrays).

We'll opt for the FIDO approach, since it affords some efficies since we don't
need a full encode of each key to determine order and can defer to the types
to determine how to most efficiently order their values (i.e. int and uint
ordering can be done on the numbers, no need for byte-wise, for example).

Recommendation: stick to single key types or you'll get into trouble, and prefer
string keys because it's much simpler that way.
*/

/**
 * @param {TokenOrNestedTokens[]} entries
 * @param {EncodeOptions} options
 */
function sortMapEntries (entries, options) {
  if (options.mapSorter) {
    entries.sort(options.mapSorter)
  }
}

/**
 * @param {(Token|Token[])[]} e1
 * @param {(Token|Token[])[]} e2
 * @returns {number}
 */
function mapSorter (e1, e2) {
  // the key position ([0]) could have a single token or an array
  // almost always it'll be a single token but complex key might get involved
  const keyToken1 = Array.isArray(e1[0]) ? e1[0][0] : e1[0]
  const keyToken2 = Array.isArray(e2[0]) ? e2[0][0] : e2[0]

  // different key types
  if (keyToken1.type !== keyToken2.type) {
    return keyToken1.type.compare(keyToken2.type)
  }

  const major = keyToken1.type.major
  // TODO: handle case where cmp === 0 but there are more keyToken e. complex type)
  const tcmp = cborEncoders[major].compareTokens(keyToken1, keyToken2)
  if (tcmp === 0) {
    // duplicate key or complex type where the first token matched,
    // i.e. a map or array and we're only comparing the opening token
    console.warn('WARNING: complex key types used, CBOR key sorting guarantees are gone')
  }
  return tcmp
}

/**
 * @typedef {Token & { _keyBytes?: Uint8Array }} TokenEx
 *
 * @param {(Token|Token[])[]} e1
 * @param {(Token|Token[])[]} e2
 * @returns {number}
 */
function rfc8949MapSorter (e1, e2) {
  if (e1[0] instanceof Token && e2[0] instanceof Token) {
    const t1 = /** @type {TokenEx} */ (e1[0])
    const t2 = /** @type {TokenEx} */ (e2[0])

    if (!t1._keyBytes) {
      t1._keyBytes = encodeRfc8949(t1.value)
    }

    if (!t2._keyBytes) {
      t2._keyBytes = encodeRfc8949(t2.value)
    }

    return compare(t1._keyBytes, t2._keyBytes)
  }

  throw new Error('rfc8949MapSorter: complex key types are not supported yet')
}

/**
 * @param {any} data
 * @returns {Uint8Array}
 */
function encodeRfc8949 (data) {
  return encodeCustom(data, cborEncoders, rfc8949EncodeOptions)
}

/**
 * @param {ByteWriter} writer
 * @param {TokenOrNestedTokens} tokens
 * @param {TokenTypeEncoder[]} encoders
 * @param {EncodeOptions} options
 */
function tokensToEncoded (writer, tokens, encoders, options) {
  if (Array.isArray(tokens)) {
    for (const token of tokens) {
      tokensToEncoded(writer, token, encoders, options)
    }
  } else {
    encoders[tokens.type.major](writer, tokens, options)
  }
}

// CBOR major type prefixes, cached from Type for hot path performance
const MAJOR_UINT = Type.uint.majorEncoded
const MAJOR_NEGINT = Type.negint.majorEncoded
const MAJOR_BYTES = Type.bytes.majorEncoded
const MAJOR_STRING = Type.string.majorEncoded
const MAJOR_ARRAY = Type.array.majorEncoded

// Simple value bytes (CBOR major type 7 + minor value)
const SIMPLE_FALSE = Type.float.majorEncoded | MINOR_FALSE
const SIMPLE_TRUE = Type.float.majorEncoded | MINOR_TRUE
const SIMPLE_NULL = Type.float.majorEncoded | MINOR_NULL
const SIMPLE_UNDEFINED = Type.float.majorEncoded | MINOR_UNDEFINED

const neg1b = BigInt(-1)
const pos1b = BigInt(1)

/**
 * Check if direct encoding can be used for the given options.
 * Direct encoding bypasses token creation for most values.
 * @param {EncodeOptions} options
 * @returns {boolean}
 */
function canDirectEncode (options) {
  // Cannot use direct encode with addBreakTokens (needs special break token handling).
  // Direct encode checks typeEncoders per-value, falling back to tokens as needed.
  // Maps fall back to token-based encoding for efficient key sorting.
  return options.addBreakTokens !== true
}

/**
 * Direct encode a value to the writer, bypassing token creation for most types.
 * Falls back to token-based encoding for custom type encoders.
 * @param {ByteWriter} writer
 * @param {any} data
 * @param {EncodeOptions} options
 * @param {Reference|undefined} refStack
 */
function directEncode (writer, data, options, refStack) {
  const typ = is(data)

  // Check for custom encoder for THIS specific type
  const customEncoder = options.typeEncoders && options.typeEncoders[typ]
  if (customEncoder) {
    const tokens = customEncoder(data, typ, options, refStack)
    if (tokens != null) {
      // Custom encoder returned tokens, serialize immediately
      tokensToEncoded(writer, tokens, cborEncoders, options)
      return
    }
    // Custom encoder returned null, fall through to default handling
  }

  // Direct encode based on type
  switch (typ) {
    case 'null':
      writer.push([SIMPLE_NULL])
      return

    case 'undefined':
      writer.push([SIMPLE_UNDEFINED])
      return

    case 'boolean':
      writer.push([data ? SIMPLE_TRUE : SIMPLE_FALSE])
      return

    case 'number':
      if (!Number.isInteger(data) || !Number.isSafeInteger(data)) {
        // Float, use token encoder for complex float encoding
        encodeFloat(writer, new Token(Type.float, data), options)
      } else if (data >= 0) {
        encodeUintValue(writer, MAJOR_UINT, data)
      } else {
        // Negative integer
        encodeUintValue(writer, MAJOR_NEGINT, data * -1 - 1)
      }
      return

    case 'bigint':
      if (data >= BigInt(0)) {
        encodeUintValue(writer, MAJOR_UINT, data)
      } else {
        encodeUintValue(writer, MAJOR_NEGINT, data * neg1b - pos1b)
      }
      return

    case 'string': {
      const bytes = fromString(data)
      encodeUintValue(writer, MAJOR_STRING, bytes.length)
      writer.push(bytes)
      return
    }

    case 'Uint8Array':
      encodeUintValue(writer, MAJOR_BYTES, data.length)
      writer.push(data)
      return

    case 'Array':
      if (!data.length) {
        writer.push([MAJOR_ARRAY]) // Empty array: 0x80
        return
      }
      refStack = Ref.createCheck(refStack, data)
      encodeUintValue(writer, MAJOR_ARRAY, data.length)
      for (const elem of data) {
        directEncode(writer, elem, options, refStack)
      }
      return

    case 'Object':
    case 'Map':
      // Maps require key sorting, use token-based encoding for efficiency
      // (pre-encoding all keys for sorting is expensive)
      {
        const tokens = typeEncoders.Object(data, typ, options, refStack)
        tokensToEncoded(writer, tokens, cborEncoders, options)
      }
      return

    default:
    // Fall back to token-based encoding for other types (DataView, TypedArrays, etc.)
    {
      const typeEncoder = typeEncoders[typ]
      if (!typeEncoder) {
        throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`)
      }
      const tokens = typeEncoder(data, typ, options, refStack)
      tokensToEncoded(writer, tokens, cborEncoders, options)
    }
  }
}

/**
 * @param {any} data
 * @param {TokenTypeEncoder[]} encoders
 * @param {EncodeOptions} options
 * @param {Uint8Array} [destination]
 * @returns {Uint8Array}
 */
function encodeCustom (data, encoders, options, destination) {
  // arg ordering is different to encodeInto for backward compatibility
  const hasDest = destination instanceof Uint8Array
  let writeTo = hasDest ? new U8Bl(destination) : defaultWriter

  const tokens = objectToTokens(data, options)
  if (!Array.isArray(tokens) && options.quickEncodeToken) {
    const quickBytes = options.quickEncodeToken(tokens)
    if (quickBytes) {
      if (hasDest) {
        // Copy quick bytes into destination buffer
        writeTo.push(quickBytes)
        return writeTo.toBytes()
      }
      return quickBytes
    }
    const encoder = encoders[tokens.type.major]
    if (encoder.encodedSize) {
      const size = encoder.encodedSize(tokens, options)
      if (!hasDest) {
        writeTo = new Bl(size)
      }
      encoder(writeTo, tokens, options)
      // this would be a problem with encodedSize() functions
      if (writeTo.chunks.length !== 1) {
        throw new Error(`Unexpected error: pre-calculated length for ${tokens} was wrong`)
      }
      return hasDest ? writeTo.toBytes() : asU8A(writeTo.chunks[0])
    }
  }
  writeTo.reset()
  tokensToEncoded(writeTo, tokens, encoders, options)
  return writeTo.toBytes(true)
}

/**
 * @param {any} data
 * @param {EncodeOptions} [options]
 * @returns {Uint8Array}
 */
function encode (data, options) {
  options = Object.assign({}, defaultEncodeOptions, options)

  // Use direct encode path when possible
  if (canDirectEncode(options)) {
    defaultWriter.reset()
    directEncode(defaultWriter, data, options, undefined)
    return defaultWriter.toBytes(true)
  }

  return encodeCustom(data, cborEncoders, options)
}

/**
 * @param {any} data
 * @param {Uint8Array} destination
 * @param {EncodeOptions} [options]
 * @returns {{ written: number }}
 */
function encodeInto (data, destination, options) {
  options = Object.assign({}, defaultEncodeOptions, options)

  // Use direct encode path when possible
  if (canDirectEncode(options)) {
    const writer = new U8Bl(destination)
    directEncode(writer, data, options, undefined)
    return { written: writer.toBytes().length }
  }

  const result = encodeCustom(data, cborEncoders, options, destination)
  return { written: result.length }
}

export { objectToTokens, encode, encodeCustom, encodeInto, Ref }
// This is an unfortunate replacement for @sindresorhus/is that we need to
// re-implement for performance purposes. In particular the is.observable()
// check is expensive, and unnecessary for our purposes. The values returned
// are compatible with @sindresorhus/is, however.

// Types that reach getObjectType() - excludes types with fast-paths above:
// primitives (typeof), Array (isArray), Uint8Array (instanceof), plain Object (constructor)
const objectTypeNames = [
  'Object', // for Object.create(null) and other non-plain objects
  'RegExp',
  'Date',
  'Error',
  'Map',
  'Set',
  'WeakMap',
  'WeakSet',
  'ArrayBuffer',
  'SharedArrayBuffer',
  'DataView',
  'Promise',
  'URL',
  'HTMLElement',
  'Int8Array',
  'Uint8ClampedArray',
  'Int16Array',
  'Uint16Array',
  'Int32Array',
  'Uint32Array',
  'Float32Array',
  'Float64Array',
  'BigInt64Array',
  'BigUint64Array',
  'Tagged'
]

/**
 * @param {any} value
 * @returns {string}
 */
export function is (value) {
  if (value === null) {
    return 'null'
  }
  if (value === undefined) {
    return 'undefined'
  }
  if (value === true || value === false) {
    return 'boolean'
  }
  const typeOf = typeof value
  if (typeOf === 'string' || typeOf === 'number' || typeOf === 'bigint' || typeOf === 'symbol') {
    return typeOf
  }
  if (typeOf === 'function') {
    return 'Function'
  }
  if (Array.isArray(value)) {
    return 'Array'
  }
  // Also catches Node.js Buffer which extends Uint8Array
  if (value instanceof Uint8Array) {
    return 'Uint8Array'
  }
  // Fast path for plain objects (most common case after primitives/arrays/bytes)
  if (value.constructor === Object) {
    return 'Object'
  }
  const objectType = getObjectType(value)
  if (objectType) {
    return objectType
  }
  return 'Object'
}

/**
 * @param {any} value
 * @returns {string|undefined}
 */
function getObjectType (value) {
  const objectTypeName = Object.prototype.toString.call(value).slice(8, -1)
  if (objectTypeNames.includes(objectTypeName)) {
    return objectTypeName
  }
  return undefined
}
import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import * as negint from './1negint.js'
import * as bytes from './2bytes.js'
import * as string from './3string.js'
import * as array from './4array.js'
import * as map from './5map.js'
import * as tag from './6tag.js'
import * as float from './7float.js'
import { decodeErrPrefix } from './common.js'
import { fromArray } from './byte-utils.js'

/**
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 */
function invalidMinor (data, pos, minor) {
  throw new Error(`${decodeErrPrefix} encountered invalid minor (${minor}) for major ${data[pos] >>> 5}`)
}

/**
 * @param {string} msg
 * @returns {()=>any}
 */
function errorer (msg) {
  return () => { throw new Error(`${decodeErrPrefix} ${msg}`) }
}

/** @type {((data:Uint8Array, pos:number, minor:number, options?:DecodeOptions) => any)[]} */
export const jump = []

// unsigned integer, 0x00..0x17 (0..23)
for (let i = 0; i <= 0x17; i++) {
  jump[i] = invalidMinor // uint.decodeUintCompact, handled by quick[]
}
jump[0x18] = uint.decodeUint8 // unsigned integer, one-byte uint8_t follows
jump[0x19] = uint.decodeUint16 // unsigned integer, two-byte uint16_t follows
jump[0x1a] = uint.decodeUint32 // unsigned integer, four-byte uint32_t follows
jump[0x1b] = uint.decodeUint64 // unsigned integer, eight-byte uint64_t follows
jump[0x1c] = invalidMinor
jump[0x1d] = invalidMinor
jump[0x1e] = invalidMinor
jump[0x1f] = invalidMinor
// negative integer, -1-0x00..-1-0x17 (-1..-24)
for (let i = 0x20; i <= 0x37; i++) {
  jump[i] = invalidMinor // negintDecode, handled by quick[]
}
jump[0x38] = negint.decodeNegint8 // negative integer, -1-n one-byte uint8_t for n follows
jump[0x39] = negint.decodeNegint16 // negative integer, -1-n two-byte uint16_t for n follows
jump[0x3a] = negint.decodeNegint32 // negative integer, -1-n four-byte uint32_t for follows
jump[0x3b] = negint.decodeNegint64 // negative integer, -1-n eight-byte uint64_t for follows
jump[0x3c] = invalidMinor
jump[0x3d] = invalidMinor
jump[0x3e] = invalidMinor
jump[0x3f] = invalidMinor
// byte string, 0x00..0x17 bytes follow
for (let i = 0x40; i <= 0x57; i++) {
  jump[i] = bytes.decodeBytesCompact
}
jump[0x58] = bytes.decodeBytes8 // byte string, one-byte uint8_t for n, and then n bytes follow
jump[0x59] = bytes.decodeBytes16 // byte string, two-byte uint16_t for n, and then n bytes follow
jump[0x5a] = bytes.decodeBytes32 // byte string, four-byte uint32_t for n, and then n bytes follow
jump[0x5b] = bytes.decodeBytes64 // byte string, eight-byte uint64_t for n, and then n bytes follow
jump[0x5c] = invalidMinor
jump[0x5d] = invalidMinor
jump[0x5e] = invalidMinor
jump[0x5f] = errorer('indefinite length bytes/strings are not supported') // byte string, byte strings follow, terminated by "break"
// UTF-8 string 0x00..0x17 bytes follow
for (let i = 0x60; i <= 0x77; i++) {
  jump[i] = string.decodeStringCompact
}
jump[0x78] = string.decodeString8 // UTF-8 string, one-byte uint8_t for n, and then n bytes follow
jump[0x79] = string.decodeString16 // UTF-8 string, two-byte uint16_t for n, and then n bytes follow
jump[0x7a] = string.decodeString32 // UTF-8 string, four-byte uint32_t for n, and then n bytes follow
jump[0x7b] = string.decodeString64 // UTF-8 string, eight-byte uint64_t for n, and then n bytes follow
jump[0x7c] = invalidMinor
jump[0x7d] = invalidMinor
jump[0x7e] = invalidMinor
jump[0x7f] = errorer('indefinite length bytes/strings are not supported') // UTF-8 strings follow, terminated by "break"
// array, 0x00..0x17 data items follow
for (let i = 0x80; i <= 0x97; i++) {
  jump[i] = array.decodeArrayCompact
}
jump[0x98] = array.decodeArray8 // array, one-byte uint8_t for n, and then n data items follow
jump[0x99] = array.decodeArray16 // array, two-byte uint16_t for n, and then n data items follow
jump[0x9a] = array.decodeArray32 // array, four-byte uint32_t for n, and then n data items follow
jump[0x9b] = array.decodeArray64 // array, eight-byte uint64_t for n, and then n data items follow
jump[0x9c] = invalidMinor
jump[0x9d] = invalidMinor
jump[0x9e] = invalidMinor
jump[0x9f] = array.decodeArrayIndefinite // array, data items follow, terminated by "break"
// map, 0x00..0x17 pairs of data items follow
for (let i = 0xa0; i <= 0xb7; i++) {
  jump[i] = map.decodeMapCompact
}
jump[0xb8] = map.decodeMap8 // map, one-byte uint8_t for n, and then n pairs of data items follow
jump[0xb9] = map.decodeMap16 // map, two-byte uint16_t for n, and then n pairs of data items follow
jump[0xba] = map.decodeMap32 // map, four-byte uint32_t for n, and then n pairs of data items follow
jump[0xbb] = map.decodeMap64 // map, eight-byte uint64_t for n, and then n pairs of data items follow
jump[0xbc] = invalidMinor
jump[0xbd] = invalidMinor
jump[0xbe] = invalidMinor
jump[0xbf] = map.decodeMapIndefinite // map, pairs of data items follow, terminated by "break"
// tags
for (let i = 0xc0; i <= 0xd7; i++) {
  jump[i] = tag.decodeTagCompact
}
jump[0xd8] = tag.decodeTag8
jump[0xd9] = tag.decodeTag16
jump[0xda] = tag.decodeTag32
jump[0xdb] = tag.decodeTag64
jump[0xdc] = invalidMinor
jump[0xdd] = invalidMinor
jump[0xde] = invalidMinor
jump[0xdf] = invalidMinor
// 0xe0..0xf3 simple values, unsupported
for (let i = 0xe0; i <= 0xf3; i++) {
  jump[i] = errorer('simple values are not supported')
}
jump[0xf4] = invalidMinor // false, handled by quick[]
jump[0xf5] = invalidMinor // true, handled by quick[]
jump[0xf6] = invalidMinor // null, handled by quick[]
jump[0xf7] = float.decodeUndefined // undefined
jump[0xf8] = errorer('simple values are not supported') // simple value, one byte follows, unsupported
jump[0xf9] = float.decodeFloat16 // half-precision float (two-byte IEEE 754)
jump[0xfa] = float.decodeFloat32 // single-precision float (four-byte IEEE 754)
jump[0xfb] = float.decodeFloat64 // double-precision float (eight-byte IEEE 754)
jump[0xfc] = invalidMinor
jump[0xfd] = invalidMinor
jump[0xfe] = invalidMinor
jump[0xff] = float.decodeBreak // "break" stop code

/** @type {Token[]} */
export const quick = []
// ints <24
for (let i = 0; i < 24; i++) {
  quick[i] = new Token(Type.uint, i, 1)
}
// negints >= -24
for (let i = -1; i >= -24; i--) {
  quick[31 - i] = new Token(Type.negint, i, 1)
}
// empty bytes
quick[0x40] = new Token(Type.bytes, new Uint8Array(0), 1)
// empty string
quick[0x60] = new Token(Type.string, '', 1)
// empty list
quick[0x80] = new Token(Type.array, 0, 1)
// empty map
quick[0xa0] = new Token(Type.map, 0, 1)
// false
quick[0xf4] = new Token(Type.false, false, 1)
// true
quick[0xf5] = new Token(Type.true, true, 1)
// null
quick[0xf6] = new Token(Type.null, null, 1)

/**
 * @param {Token} token
 * @returns {Uint8Array|undefined}
 */
export function quickEncodeToken (token) {
  switch (token.type) {
    case Type.false:
      return fromArray([0xf4])
    case Type.true:
      return fromArray([0xf5])
    case Type.null:
      return fromArray([0xf6])
    case Type.bytes:
      if (!token.value.length) {
        return fromArray([0x40])
      }
      return
    case Type.string:
      if (token.value === '') {
        return fromArray([0x60])
      }
      return
    case Type.array:
      if (token.value === 0) {
        return fromArray([0x80])
      }
      // shouldn't be possible if this were called when there was only one token
      return
    case Type.map:
      if (token.value === 0) {
        return fromArray([0xa0])
      }
      // shouldn't be possible if this were called when there was only one token
      return
    case Type.uint:
      if (token.value < 24) {
        return fromArray([Number(token.value)])
      }
      return
    case Type.negint:
      if (token.value >= -24) {
        return fromArray([31 - Number(token.value)])
      }
  }
}
/**
 * @typedef {import('../interface.js').TagDecodeControl} TagDecodeControl
 * @typedef {(decode: TagDecodeControl) => Tagged} TaggedTagDecoder
 */

/**
 * A wrapper class for representing a CBOR tag with an arbitrary nested value.
 *
 * `Tagged` is a symmetric primitive: it can be passed to `encode()` to emit
 * a CBOR tag header followed by the encoded form of `value`, and it can be
 * returned from a tag decoder (via `Tagged.decoder(tag)` or `Tagged.preserve()`)
 * to round-trip a tag through decode without losing the tag number.
 *
 * Use `Tagged` for one-off tag handling where defining a dedicated
 * `typeEncoders` entry and tag decoder pair would be heavyweight, e.g. when
 * wrapping a structure in a single application-specific tag (COSE, dCBOR
 * envelopes, etc.).
 *
 * For systematic mapping of a JS type to a tag (e.g. CID -> tag 42), prefer
 * a dedicated `typeEncoders` entry instead.
 */
export class Tagged {
  /**
   * @param {number} tag - CBOR tag number, a non-negative integer
   * @param {any} value - The value to be tagged; encoded recursively
   */
  constructor (tag, value) {
    if (typeof tag !== 'number' || !Number.isInteger(tag) || tag < 0) {
      throw new TypeError('Tagged: tag must be a non-negative integer')
    }
    this.tag = tag
    this.value = value
  }

  /**
   * Build a tag decoder for use in `decode()`'s `tags` option that returns the
   * decoded content wrapped in a `Tagged` instance, preserving the tag number
   * for the caller to inspect.
   *
   * @param {number} tag - The CBOR tag number this decoder will be registered for
   * @returns {TaggedTagDecoder}
   *
   * @example
   * import { decode, Tagged } from 'cborg'
   * const value = decode(bytes, { tags: { 16: Tagged.decoder(16) } })
   * // value instanceof Tagged; value.tag === 16
   */
  static decoder (tag) {
    return (decode) => new Tagged(tag, decode())
  }

  /**
   * Build a `tags` option for `decode()` that wraps each listed tag number in
   * a `Tagged` instance, preserving those tags through decode without
   * registering a dedicated decoder per tag.
   *
   * @param {...number} tagNumbers - One or more CBOR tag numbers to preserve
   * @returns {{[tagNumber: number]: TaggedTagDecoder}}
   *
   * @example
   * import { decode, Tagged } from 'cborg'
   * const value = decode(bytes, { tags: Tagged.preserve(16, 96) })
   */
  static preserve (...tagNumbers) {
    /** @type {{[tagNumber: number]: TaggedTagDecoder}} */
    const tags = {}
    for (const tag of tagNumbers) {
      tags[tag] = Tagged.decoder(tag)
    }
    return tags
  }
}

// Symbol.toStringTag so the internal `is()` type detection returns 'Tagged'
// for instances, allowing the default Tagged typeEncoder to match.
Object.defineProperty(Tagged.prototype, Symbol.toStringTag, {
  value: 'Tagged'
})
class Type {
  /**
   * @param {number} major
   * @param {string} name
   * @param {boolean} terminal
   */
  constructor (major, name, terminal) {
    this.major = major
    this.majorEncoded = major << 5
    this.name = name
    this.terminal = terminal
  }

  toString () {
    return `Type[${this.major}].${this.name}`
  }

  /**
   * @param {Type} typ
   * @returns {number}
   */
  compare (typ) {
    return this.major < typ.major ? -1 : this.major > typ.major ? 1 : 0
  }

  /**
   * Check equality between two Type instances. Safe to use across different
   * copies of the Type class (e.g., when bundlers duplicate the module).
   * (major, name) uniquely identifies a Type; terminal is implied by these.
   * @param {Type} a
   * @param {Type} b
   * @returns {boolean}
   */
  static equals (a, b) {
    return a === b || (a.major === b.major && a.name === b.name)
  }
}

// convert to static fields when better supported
Type.uint = new Type(0, 'uint', true)
Type.negint = new Type(1, 'negint', true)
Type.bytes = new Type(2, 'bytes', true)
Type.string = new Type(3, 'string', true)
Type.array = new Type(4, 'array', false)
Type.map = new Type(5, 'map', false)
Type.tag = new Type(6, 'tag', false) // terminal?
Type.float = new Type(7, 'float', true)
Type.false = new Type(7, 'false', true)
Type.true = new Type(7, 'true', true)
Type.null = new Type(7, 'null', true)
Type.undefined = new Type(7, 'undefined', true)
Type.break = new Type(7, 'break', true)
// Type.indefiniteLength = new Type(0, 'indefiniteLength', true)

class Token {
  /**
   * @param {Type} type
   * @param {any} [value]
   * @param {number} [encodedLength]
   */
  constructor (type, value, encodedLength) {
    this.type = type
    this.value = value
    this.encodedLength = encodedLength
    /** @type {Uint8Array|undefined} */
    this.encodedBytes = undefined
    /** @type {Uint8Array|undefined} */
    this.byteValue = undefined
  }

  toString () {
    return `Token[${this.type}].${this.value}`
  }
}

export { Type, Token }
{
  "name": "cborg",
  "version": "5.1.6",
  "description": "Fast CBOR with a focus on strictness",
  "main": "cborg.js",
  "type": "module",
  "bin": {
    "cborg": "lib/bin.js"
  },
  "scripts": {
    "lint": "standard *.js lib/*.js test/*.js",
    "build": "npm run build:types",
    "build:types": "tsc --build",
    "prepublishOnly": "npm run build",
    "test:node": "mocha test/test-*.js",
    "test:node-bin": "mocha test/node-test-bin.js",
    "test:browser": "polendina --cleanup test/test-*.js",
    "test": "npm run lint && npm run build && npm run test:node && npm run test:node-bin && npm run test:browser",
    "test:ci": "npm run test"
  },
  "repository": {
    "type": "git",
    "url": "git@github.com:rvagg/cborg.git"
  },
  "keywords": [
    "cbor"
  ],
  "author": "Rod <rod@vagg.org> (http://r.va.gg/)",
  "license": "Apache-2.0",
  "devDependencies": {
    "@semantic-release/changelog": "^6.0.3",
    "@semantic-release/commit-analyzer": "^13.0.1",
    "@semantic-release/git": "^10.0.1",
    "@semantic-release/github": "^12.0.6",
    "@semantic-release/npm": "^13.1.5",
    "@semantic-release/release-notes-generator": "^14.1.0",
    "@types/chai": "^5.2.3",
    "@types/mocha": "^10.0.10",
    "@types/node": "^26.0.1",
    "chai": "^6.2.2",
    "conventional-changelog-conventionalcommits": "^10.0.0",
    "ipld-garbage": "^5.0.0",
    "mocha": "^11.7.5",
    "polendina": "^3.2.20",
    "semantic-release": "^25.0.3",
    "standard": "^17.1.2",
    "typescript": "^6.0.2"
  },
  "exports": {
    ".": {
      "import": "./cborg.js",
      "types": "./types/cborg.d.ts"
    },
    "./length": {
      "import": "./lib/length.js",
      "types": "./types/lib/length.d.ts"
    },
    "./taglib": {
      "import": "./lib/taglib.js",
      "types": "./types/lib/taglib.d.ts"
    },
    "./json": {
      "import": "./lib/json/json.js",
      "types": "./types/lib/json/json.d.ts"
    },
    "./extended": {
      "import": "./lib/extended/extended.js",
      "types": "./types/lib/extended/extended.d.ts"
    },
    "./interface": {
      "types": "./types/interface.d.ts"
    }
  },
  "types": "cborg.d.ts",
  "typesVersions": {
    "*": {
      "json": [
        "types/lib/json/json.d.ts"
      ],
      "length": [
        "types/lib/length.d.ts"
      ],
      "*": [
        "types/*"
      ],
      "types/*": [
        "types/*"
      ]
    }
  },
  "release": {
    "branches": [
      "master"
    ],
    "plugins": [
      [
        "@semantic-release/commit-analyzer",
        {
          "preset": "conventionalcommits",
          "releaseRules": [
            {
              "breaking": true,
              "release": "major"
            },
            {
              "revert": true,
              "release": "patch"
            },
            {
              "type": "feat",
              "release": "minor"
            },
            {
              "type": "fix",
              "release": "patch"
            },
            {
              "type": "chore",
              "release": "patch"
            },
            {
              "type": "docs",
              "release": "patch"
            },
            {
              "type": "test",
              "release": "patch"
            },
            {
              "scope": "no-release",
              "release": false
            }
          ]
        }
      ],
      [
        "@semantic-release/release-notes-generator",
        {
          "preset": "conventionalcommits",
          "presetConfig": {
            "types": [
              {
                "type": "feat",
                "section": "Features"
              },
              {
                "type": "fix",
                "section": "Bug Fixes"
              },
              {
                "type": "chore",
                "section": "Trivial Changes"
              },
              {
                "type": "docs",
                "section": "Trivial Changes"
              },
              {
                "type": "test",
                "section": "Tests"
              }
            ]
          }
        }
      ],
      "@semantic-release/changelog",
      "@semantic-release/npm",
      "@semantic-release/github",
      "@semantic-release/git"
    ]
  }
}
import { coerce } from '../bytes.js';
import basex from '../vendor/base-x.js';
/**
 * Class represents both BaseEncoder and MultibaseEncoder meaning it
 * can be used to encode to multibase or base encode without multibase
 * prefix.
 */
class Encoder {
    name;
    prefix;
    baseEncode;
    constructor(name, prefix, baseEncode) {
        this.name = name;
        this.prefix = prefix;
        this.baseEncode = baseEncode;
    }
    encode(bytes) {
        if (bytes instanceof Uint8Array) {
            return `${this.prefix}${this.baseEncode(bytes)}`;
        }
        else {
            throw Error('Unknown type, must be binary type');
        }
    }
}
/**
 * Class represents both BaseDecoder and MultibaseDecoder so it could be used
 * to decode multibases (with matching prefix) or just base decode strings
 * with corresponding base encoding.
 */
class Decoder {
    name;
    prefix;
    baseDecode;
    prefixCodePoint;
    constructor(name, prefix, baseDecode) {
        this.name = name;
        this.prefix = prefix;
        const prefixCodePoint = prefix.codePointAt(0);
        /* c8 ignore next 3 */
        if (prefixCodePoint === undefined) {
            throw new Error('Invalid prefix character');
        }
        this.prefixCodePoint = prefixCodePoint;
        this.baseDecode = baseDecode;
    }
    decode(text) {
        if (typeof text === 'string') {
            if (text.codePointAt(0) !== this.prefixCodePoint) {
                throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);
            }
            return this.baseDecode(text.slice(this.prefix.length));
        }
        else {
            throw Error('Can only multibase decode strings');
        }
    }
    or(decoder) {
        return or(this, decoder);
    }
}
class ComposedDecoder {
    decoders;
    constructor(decoders) {
        this.decoders = decoders;
    }
    or(decoder) {
        return or(this, decoder);
    }
    decode(input) {
        const prefix = input[0];
        const decoder = this.decoders[prefix];
        if (decoder != null) {
            return decoder.decode(input);
        }
        else {
            throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);
        }
    }
}
export function or(left, right) {
    return new ComposedDecoder({
        ...(left.decoders ?? { [left.prefix]: left }),
        ...(right.decoders ?? { [right.prefix]: right })
    });
}
export class Codec {
    name;
    prefix;
    baseEncode;
    baseDecode;
    encoder;
    decoder;
    constructor(name, prefix, baseEncode, baseDecode) {
        this.name = name;
        this.prefix = prefix;
        this.baseEncode = baseEncode;
        this.baseDecode = baseDecode;
        this.encoder = new Encoder(name, prefix, baseEncode);
        this.decoder = new Decoder(name, prefix, baseDecode);
    }
    encode(input) {
        return this.encoder.encode(input);
    }
    decode(input) {
        return this.decoder.decode(input);
    }
}
export function from({ name, prefix, encode, decode }) {
    return new Codec(name, prefix, encode, decode);
}
export function baseX({ name, prefix, alphabet }) {
    const { encode, decode } = basex(alphabet, name);
    return from({
        prefix,
        name,
        encode,
        decode: (text) => coerce(decode(text))
    });
}
function decode(string, alphabetIdx, bitsPerChar, name) {
    // Count the padding bytes:
    let end = string.length;
    while (string[end - 1] === '=') {
        --end;
    }
    // Allocate the output:
    const out = new Uint8Array((end * bitsPerChar / 8) | 0);
    // Parse the data:
    let bits = 0; // Number of bits currently in the buffer
    let buffer = 0; // Bits waiting to be written out, MSB first
    let written = 0; // Next byte to write
    for (let i = 0; i < end; ++i) {
        // Read one character from the string:
        const value = alphabetIdx[string[i]];
        if (value === undefined) {
            throw new SyntaxError(`Non-${name} character`);
        }
        // Append the bits to the buffer:
        buffer = (buffer << bitsPerChar) | value;
        bits += bitsPerChar;
        // Write out some bits if the buffer has a byte's worth:
        if (bits >= 8) {
            bits -= 8;
            out[written++] = 0xff & (buffer >> bits);
        }
    }
    // Verify that we have received just enough bits:
    if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {
        throw new SyntaxError('Unexpected end of data');
    }
    return out;
}
function encode(data, alphabet, bitsPerChar) {
    const pad = alphabet[alphabet.length - 1] === '=';
    const mask = (1 << bitsPerChar) - 1;
    let out = '';
    let bits = 0; // Number of bits currently in the buffer
    let buffer = 0; // Bits waiting to be written out, MSB first
    for (let i = 0; i < data.length; ++i) {
        // Slurp data into the buffer:
        buffer = (buffer << 8) | data[i];
        bits += 8;
        // Write out as much as we can:
        while (bits > bitsPerChar) {
            bits -= bitsPerChar;
            out += alphabet[mask & (buffer >> bits)];
        }
    }
    // Partial character:
    if (bits !== 0) {
        out += alphabet[mask & (buffer << (bitsPerChar - bits))];
    }
    // Add padding characters until we hit a byte boundary:
    if (pad) {
        while (((out.length * bitsPerChar) & 7) !== 0) {
            out += '=';
        }
    }
    return out;
}
function createAlphabetIdx(alphabet) {
    // Build the character lookup table:
    const alphabetIdx = {};
    for (let i = 0; i < alphabet.length; ++i) {
        alphabetIdx[alphabet[i]] = i;
    }
    return alphabetIdx;
}
/**
 * RFC4648 Factory
 */
export function rfc4648({ name, prefix, bitsPerChar, alphabet }) {
    const alphabetIdx = createAlphabetIdx(alphabet);
    return from({
        prefix,
        name,
        encode(input) {
            return encode(input, alphabet, bitsPerChar);
        },
        decode(input) {
            return decode(input, alphabetIdx, bitsPerChar, name);
        }
    });
}
//# sourceMappingURL=base.js.mapimport { rfc4648 } from './base.js';
export const base32 = rfc4648({
    prefix: 'b',
    name: 'base32',
    alphabet: 'abcdefghijklmnopqrstuvwxyz234567',
    bitsPerChar: 5
});
export const base32upper = rfc4648({
    prefix: 'B',
    name: 'base32upper',
    alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',
    bitsPerChar: 5
});
export const base32pad = rfc4648({
    prefix: 'c',
    name: 'base32pad',
    alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',
    bitsPerChar: 5
});
export const base32padupper = rfc4648({
    prefix: 'C',
    name: 'base32padupper',
    alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',
    bitsPerChar: 5
});
export const base32hex = rfc4648({
    prefix: 'v',
    name: 'base32hex',
    alphabet: '0123456789abcdefghijklmnopqrstuv',
    bitsPerChar: 5
});
export const base32hexupper = rfc4648({
    prefix: 'V',
    name: 'base32hexupper',
    alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',
    bitsPerChar: 5
});
export const base32hexpad = rfc4648({
    prefix: 't',
    name: 'base32hexpad',
    alphabet: '0123456789abcdefghijklmnopqrstuv=',
    bitsPerChar: 5
});
export const base32hexpadupper = rfc4648({
    prefix: 'T',
    name: 'base32hexpadupper',
    alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',
    bitsPerChar: 5
});
export const base32z = rfc4648({
    prefix: 'h',
    name: 'base32z',
    alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',
    bitsPerChar: 5
});
//# sourceMappingURL=base32.js.mapimport { baseX } from './base.js';
export const base36 = baseX({
    prefix: 'k',
    name: 'base36',
    alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'
});
export const base36upper = baseX({
    prefix: 'K',
    name: 'base36upper',
    alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
});
//# sourceMappingURL=base36.js.mapimport { baseX } from './base.js';
export const base58btc = baseX({
    name: 'base58btc',
    prefix: 'z',
    alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
});
export const base58flickr = baseX({
    name: 'base58flickr',
    prefix: 'Z',
    alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'
});
//# sourceMappingURL=base58.js.mapexport const empty = new Uint8Array(0);
export function toHex(d) {
    return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '');
}
export function fromHex(hex) {
    const hexes = hex.match(/../g);
    return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty;
}
export function equals(aa, bb) {
    if (aa === bb) {
        return true;
    }
    if (aa.byteLength !== bb.byteLength) {
        return false;
    }
    for (let ii = 0; ii < aa.byteLength; ii++) {
        if (aa[ii] !== bb[ii]) {
            return false;
        }
    }
    return true;
}
export function coerce(o) {
    if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') {
        return o;
    }
    if (o instanceof ArrayBuffer) {
        return new Uint8Array(o);
    }
    if (ArrayBuffer.isView(o)) {
        return new Uint8Array(o.buffer, o.byteOffset, o.byteLength);
    }
    throw new Error('Unknown type, must be binary type');
}
export function isBinary(o) {
    return o instanceof ArrayBuffer || ArrayBuffer.isView(o);
}
export function fromString(str) {
    return new TextEncoder().encode(str);
}
export function toString(b) {
    return new TextDecoder().decode(b);
}
//# sourceMappingURL=bytes.js.mapimport { base32 } from './bases/base32.js';
import { base36 } from './bases/base36.js';
import { base58btc } from './bases/base58.js';
import { coerce } from './bytes.js';
import * as Digest from './hashes/digest.js';
import * as varint from './varint.js';
// This way TS will also expose all the types from module
export * from './link/interface.js';
export function format(link, base) {
    const { bytes, version } = link;
    switch (version) {
        case 0:
            return toStringV0(bytes, baseCache(link), base ?? base58btc.encoder);
        default:
            return toStringV1(bytes, baseCache(link), (base ?? base32.encoder));
    }
}
export function toJSON(link) {
    return {
        '/': format(link)
    };
}
export function fromJSON(json) {
    return CID.parse(json['/']);
}
const cache = new WeakMap();
function baseCache(cid) {
    const baseCache = cache.get(cid);
    if (baseCache == null) {
        const baseCache = new Map();
        cache.set(cid, baseCache);
        return baseCache;
    }
    return baseCache;
}
export class CID {
    code;
    version;
    multihash;
    bytes;
    '/';
    /**
     * @param version - Version of the CID
     * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
     * @param multihash - (Multi)hash of the of the content.
     */
    constructor(version, code, multihash, bytes) {
        this.code = code;
        this.version = version;
        this.multihash = multihash;
        this.bytes = bytes;
        // flag to serializers that this is a CID and
        // should be treated specially
        this['/'] = bytes;
    }
    /**
     * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`
     * please either use `CID.asCID(cid)` or switch to new signalling mechanism
     *
     * @deprecated
     */
    get asCID() {
        return this;
    }
    // ArrayBufferView
    get byteOffset() {
        return this.bytes.byteOffset;
    }
    // ArrayBufferView
    get byteLength() {
        return this.bytes.byteLength;
    }
    toV0() {
        switch (this.version) {
            case 0: {
                return this;
            }
            case 1: {
                const { code, multihash } = this;
                if (code !== DAG_PB_CODE) {
                    throw new Error('Cannot convert a non dag-pb CID to CIDv0');
                }
                // sha2-256
                if (multihash.code !== SHA_256_CODE) {
                    throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0');
                }
                return (CID.createV0(multihash));
            }
            default: {
                throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);
            }
        }
    }
    toV1() {
        switch (this.version) {
            case 0: {
                const { code, digest } = this.multihash;
                const multihash = Digest.create(code, digest);
                return (CID.createV1(this.code, multihash));
            }
            case 1: {
                return this;
            }
            default: {
                throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);
            }
        }
    }
    equals(other) {
        return CID.equals(this, other);
    }
    static equals(self, other) {
        const unknown = other;
        return (unknown != null &&
            self.code === unknown.code &&
            self.version === unknown.version &&
            Digest.equals(self.multihash, unknown.multihash));
    }
    toString(base) {
        return format(this, base);
    }
    toJSON() {
        return { '/': format(this) };
    }
    link() {
        return this;
    }
    [Symbol.toStringTag] = 'CID';
    // Legacy
    [Symbol.for('nodejs.util.inspect.custom')]() {
        return `CID(${this.toString()})`;
    }
    /**
     * Takes any input `value` and returns a `CID` instance if it was
     * a `CID` otherwise returns `null`. If `value` is instanceof `CID`
     * it will return value back. If `value` is not instance of this CID
     * class, but is compatible CID it will return new instance of this
     * `CID` class. Otherwise returns null.
     *
     * This allows two different incompatible versions of CID library to
     * co-exist and interop as long as binary interface is compatible.
     */
    static asCID(input) {
        if (input == null) {
            return null;
        }
        const value = input;
        if (value instanceof CID) {
            // If value is instance of CID then we're all set.
            return value;
        }
        else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {
            // If value isn't instance of this CID class but `this.asCID === this` or
            // `value['/'] === value.bytes` is true it is CID instance coming from a
            // different implementation (diff version or duplicate). In that case we
            // rebase it to this `CID` implementation so caller is guaranteed to get
            // instance with expected API.
            const { version, code, multihash, bytes } = value;
            return new CID(version, code, multihash, bytes ?? encodeCID(version, code, multihash.bytes));
        }
        else if (value[cidSymbol] === true) {
            // If value is a CID from older implementation that used to be tagged via
            // symbol we still rebase it to the this `CID` implementation by
            // delegating that to a constructor.
            const { version, multihash, code } = value;
            const digest = Digest.decode(multihash);
            return CID.create(version, code, digest);
        }
        else {
            // Otherwise value is not a CID (or an incompatible version of it) in
            // which case we return `null`.
            return null;
        }
    }
    /**
     * @param version - Version of the CID
     * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
     * @param digest - (Multi)hash of the of the content.
     */
    static create(version, code, digest) {
        if (typeof code !== 'number') {
            throw new Error('String codecs are no longer supported');
        }
        if (!(digest.bytes instanceof Uint8Array)) {
            throw new Error('Invalid digest');
        }
        switch (version) {
            case 0: {
                if (code !== DAG_PB_CODE) {
                    throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);
                }
                else {
                    return new CID(version, code, digest, digest.bytes);
                }
            }
            case 1: {
                const bytes = encodeCID(version, code, digest.bytes);
                return new CID(version, code, digest, bytes);
            }
            default: {
                throw new Error('Invalid version');
            }
        }
    }
    /**
     * Simplified version of `create` for CIDv0.
     */
    static createV0(digest) {
        return CID.create(0, DAG_PB_CODE, digest);
    }
    /**
     * Simplified version of `create` for CIDv1.
     *
     * @param code - Content encoding format code.
     * @param digest - Multihash of the content.
     */
    static createV1(code, digest) {
        return CID.create(1, code, digest);
    }
    /**
     * Decoded a CID from its binary representation. The byte array must contain
     * only the CID with no additional bytes.
     *
     * An error will be thrown if the bytes provided do not contain a valid
     * binary representation of a CID.
     */
    static decode(bytes) {
        const [cid, remainder] = CID.decodeFirst(bytes);
        if (remainder.length !== 0) {
            throw new Error('Incorrect length');
        }
        return cid;
    }
    /**
     * Decoded a CID from its binary representation at the beginning of a byte
     * array.
     *
     * Returns an array with the first element containing the CID and the second
     * element containing the remainder of the original byte array. The remainder
     * will be a zero-length byte array if the provided bytes only contained a
     * binary CID representation.
     */
    static decodeFirst(bytes) {
        const specs = CID.inspectBytes(bytes);
        const prefixSize = specs.size - specs.multihashSize;
        const multihashBytes = coerce(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));
        if (multihashBytes.byteLength !== specs.multihashSize) {
            throw new Error('Incorrect length');
        }
        const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);
        const digest = new Digest.Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);
        const cid = specs.version === 0
            ? CID.createV0(digest)
            : CID.createV1(specs.codec, digest);
        return [cid, bytes.subarray(specs.size)];
    }
    /**
     * Inspect the initial bytes of a CID to determine its properties.
     *
     * Involves decoding up to 4 varints. Typically this will require only 4 to 6
     * bytes but for larger multicodec code values and larger multihash digest
     * lengths these varints can be quite large. It is recommended that at least
     * 10 bytes be made available in the `initialBytes` argument for a complete
     * inspection.
     */
    static inspectBytes(initialBytes) {
        let offset = 0;
        const next = () => {
            const [i, length] = varint.decode(initialBytes.subarray(offset));
            offset += length;
            return i;
        };
        let version = next();
        let codec = DAG_PB_CODE;
        if (version === 18) {
            // CIDv0
            version = 0;
            offset = 0;
        }
        else {
            codec = next();
        }
        if (version !== 0 && version !== 1) {
            throw new RangeError(`Invalid CID version ${version}`);
        }
        const prefixSize = offset;
        const multihashCode = next(); // multihash code
        const digestSize = next(); // multihash length
        const size = offset + digestSize;
        const multihashSize = size - prefixSize;
        return { version, codec, multihashCode, digestSize, multihashSize, size };
    }
    /**
     * Takes cid in a string representation and creates an instance. If `base`
     * decoder is not provided will use a default from the configuration. It will
     * throw an error if encoding of the CID is not compatible with supplied (or
     * a default decoder).
     */
    static parse(source, base) {
        const [prefix, bytes] = parseCIDtoBytes(source, base);
        const cid = CID.decode(bytes);
        if (cid.version === 0 && source[0] !== 'Q') {
            throw Error('Version 0 CID string must not include multibase prefix');
        }
        // Cache string representation to avoid computing it on `this.toString()`
        baseCache(cid).set(prefix, source);
        return cid;
    }
}
function parseCIDtoBytes(source, base) {
    switch (source[0]) {
        // CIDv0 is parsed differently
        case 'Q': {
            const decoder = base ?? base58btc;
            return [
                base58btc.prefix,
                decoder.decode(`${base58btc.prefix}${source}`)
            ];
        }
        case base58btc.prefix: {
            const decoder = base ?? base58btc;
            return [base58btc.prefix, decoder.decode(source)];
        }
        case base32.prefix: {
            const decoder = base ?? base32;
            return [base32.prefix, decoder.decode(source)];
        }
        case base36.prefix: {
            const decoder = base ?? base36;
            return [base36.prefix, decoder.decode(source)];
        }
        default: {
            if (base == null) {
                throw Error('To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided');
            }
            return [source[0], base.decode(source)];
        }
    }
}
function toStringV0(bytes, cache, base) {
    const { prefix } = base;
    if (prefix !== base58btc.prefix) {
        throw Error(`Cannot string encode V0 in ${base.name} encoding`);
    }
    const cid = cache.get(prefix);
    if (cid == null) {
        const cid = base.encode(bytes).slice(1);
        cache.set(prefix, cid);
        return cid;
    }
    else {
        return cid;
    }
}
function toStringV1(bytes, cache, base) {
    const { prefix } = base;
    const cid = cache.get(prefix);
    if (cid == null) {
        const cid = base.encode(bytes);
        cache.set(prefix, cid);
        return cid;
    }
    else {
        return cid;
    }
}
const DAG_PB_CODE = 0x70;
const SHA_256_CODE = 0x12;
function encodeCID(version, code, multihash) {
    const codeOffset = varint.encodingLength(version);
    const hashOffset = codeOffset + varint.encodingLength(code);
    const bytes = new Uint8Array(hashOffset + multihash.byteLength);
    varint.encodeTo(version, bytes, 0);
    varint.encodeTo(code, bytes, codeOffset);
    bytes.set(multihash, hashOffset);
    return bytes;
}
const cidSymbol = Symbol.for('@ipld/js-cid/CID');
//# sourceMappingURL=cid.js.mapimport { coerce } from '../bytes.js';
export const name = 'raw';
export const code = 0x55;
export function encode(node) {
    return coerce(node);
}
export function decode(data) {
    return coerce(data);
}
//# sourceMappingURL=raw.js.mapimport { coerce, equals as equalBytes } from '../bytes.js';
import * as varint from '../varint.js';
/**
 * Creates a multihash digest.
 */
export function create(code, digest) {
    const size = digest.byteLength;
    const sizeOffset = varint.encodingLength(code);
    const digestOffset = sizeOffset + varint.encodingLength(size);
    const bytes = new Uint8Array(digestOffset + size);
    varint.encodeTo(code, bytes, 0);
    varint.encodeTo(size, bytes, sizeOffset);
    bytes.set(digest, digestOffset);
    return new Digest(code, size, digest, bytes);
}
/**
 * Turns bytes representation of multihash digest into an instance.
 */
export function decode(multihash) {
    const bytes = coerce(multihash);
    const [code, sizeOffset] = varint.decode(bytes);
    const [size, digestOffset] = varint.decode(bytes.subarray(sizeOffset));
    const digest = bytes.subarray(sizeOffset + digestOffset);
    if (digest.byteLength !== size) {
        throw new Error('Incorrect length');
    }
    return new Digest(code, size, digest, bytes);
}
export function equals(a, b) {
    if (a === b) {
        return true;
    }
    else {
        const data = b;
        return (a.code === data.code &&
            a.size === data.size &&
            data.bytes instanceof Uint8Array &&
            equalBytes(a.bytes, data.bytes));
    }
}
/**
 * Represents a multihash digest which carries information about the
 * hashing algorithm and an actual hash digest.
 */
export class Digest {
    code;
    size;
    digest;
    bytes;
    /**
     * Creates a multihash digest.
     */
    constructor(code, size, digest, bytes) {
        this.code = code;
        this.size = size;
        this.digest = digest;
        this.bytes = bytes;
    }
}
/**
 * Used to check that the passed multihash has the passed code
 */
export function hasCode(digest, code) {
    return digest.code === code;
}
//# sourceMappingURL=digest.js.mapexport {};
//# sourceMappingURL=interface.js.mapimport varint from './vendor/varint.js';
export function decode(data, offset = 0) {
    const code = varint.decode(data, offset);
    return [code, varint.decode.bytes];
}
export function encodeTo(int, target, offset = 0) {
    varint.encode(int, target, offset);
    return target;
}
export function encodingLength(int) {
    return varint.encodingLength(int);
}
//# sourceMappingURL=varint.js.map/* eslint-disable */
// base-x encoding / decoding
// Copyright (c) 2018 base-x contributors
// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)
// Distributed under the MIT software license, see the accompanying
// file LICENSE or http://www.opensource.org/licenses/mit-license.php.
/**
 * @param {string} ALPHABET
 * @param {any} name
 */
function base(ALPHABET, name) {
    if (ALPHABET.length >= 255) {
        throw new TypeError('Alphabet too long');
    }
    var BASE_MAP = new Uint8Array(256);
    for (var j = 0; j < BASE_MAP.length; j++) {
        BASE_MAP[j] = 255;
    }
    for (var i = 0; i < ALPHABET.length; i++) {
        var x = ALPHABET.charAt(i);
        var xc = x.charCodeAt(0);
        if (BASE_MAP[xc] !== 255) {
            throw new TypeError(x + ' is ambiguous');
        }
        BASE_MAP[xc] = i;
    }
    var BASE = ALPHABET.length;
    var LEADER = ALPHABET.charAt(0);
    var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up
    var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up
    /**
     * @param {any[] | Iterable<number>} source
     */
    function encode(source) {
        // @ts-ignore
        if (source instanceof Uint8Array)
            ;
        else if (ArrayBuffer.isView(source)) {
            source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
        }
        else if (Array.isArray(source)) {
            source = Uint8Array.from(source);
        }
        if (!(source instanceof Uint8Array)) {
            throw new TypeError('Expected Uint8Array');
        }
        if (source.length === 0) {
            return '';
        }
        // Skip & count leading zeroes.
        var zeroes = 0;
        var length = 0;
        var pbegin = 0;
        var pend = source.length;
        while (pbegin !== pend && source[pbegin] === 0) {
            pbegin++;
            zeroes++;
        }
        // Allocate enough space in big-endian base58 representation.
        var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;
        var b58 = new Uint8Array(size);
        // Process the bytes.
        while (pbegin !== pend) {
            var carry = source[pbegin];
            // Apply "b58 = b58 * 256 + ch".
            var i = 0;
            for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {
                carry += (256 * b58[it1]) >>> 0;
                b58[it1] = (carry % BASE) >>> 0;
                carry = (carry / BASE) >>> 0;
            }
            if (carry !== 0) {
                throw new Error('Non-zero carry');
            }
            length = i;
            pbegin++;
        }
        // Skip leading zeroes in base58 result.
        var it2 = size - length;
        while (it2 !== size && b58[it2] === 0) {
            it2++;
        }
        // Translate the result into a string.
        var str = LEADER.repeat(zeroes);
        for (; it2 < size; ++it2) {
            str += ALPHABET.charAt(b58[it2]);
        }
        return str;
    }
    /**
     * @param {string | string[]} source
     */
    function decodeUnsafe(source) {
        if (typeof source !== 'string') {
            throw new TypeError('Expected String');
        }
        if (source.length === 0) {
            return new Uint8Array();
        }
        var psz = 0;
        // Skip leading spaces.
        if (source[psz] === ' ') {
            return;
        }
        // Skip and count leading '1's.
        var zeroes = 0;
        var length = 0;
        while (source[psz] === LEADER) {
            zeroes++;
            psz++;
        }
        // Allocate enough space in big-endian base256 representation.
        var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.
        var b256 = new Uint8Array(size);
        // Process the characters.
        while (source[psz]) {
            // Decode character
            var carry = BASE_MAP[source.charCodeAt(psz)];
            // Invalid character
            if (carry === 255) {
                return;
            }
            var i = 0;
            for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {
                carry += (BASE * b256[it3]) >>> 0;
                b256[it3] = (carry % 256) >>> 0;
                carry = (carry / 256) >>> 0;
            }
            if (carry !== 0) {
                throw new Error('Non-zero carry');
            }
            length = i;
            psz++;
        }
        // Skip trailing spaces.
        if (source[psz] === ' ') {
            return;
        }
        // Skip leading zeroes in b256.
        var it4 = size - length;
        while (it4 !== size && b256[it4] === 0) {
            it4++;
        }
        var vch = new Uint8Array(zeroes + (size - it4));
        var j = zeroes;
        while (it4 !== size) {
            vch[j++] = b256[it4++];
        }
        return vch;
    }
    /**
     * @param {string | string[]} string
     */
    function decode(string) {
        var buffer = decodeUnsafe(string);
        if (buffer) {
            return buffer;
        }
        throw new Error(`Non-${name} character`);
    }
    return {
        encode: encode,
        decodeUnsafe: decodeUnsafe,
        decode: decode
    };
}
var src = base;
var _brrp__multiformats_scope_baseX = src;
export default _brrp__multiformats_scope_baseX;
//# sourceMappingURL=base-x.js.map/* eslint-disable */
var encode_1 = encode;
var MSB = 0x80, REST = 0x7F, MSBALL = ~REST, INT = Math.pow(2, 31);
/**
 * @param {number} num
 * @param {number[]} out
 * @param {number} offset
 */
function encode(num, out, offset) {
    out = out || [];
    offset = offset || 0;
    var oldOffset = offset;
    while (num >= INT) {
        out[offset++] = (num & 0xFF) | MSB;
        num /= 128;
    }
    while (num & MSBALL) {
        out[offset++] = (num & 0xFF) | MSB;
        num >>>= 7;
    }
    out[offset] = num | 0;
    // @ts-ignore
    encode.bytes = offset - oldOffset + 1;
    return out;
}
var decode = read;
var MSB$1 = 0x80, REST$1 = 0x7F;
/**
 * @param {string | any[]} buf
 * @param {number} offset
 */
function read(buf, offset) {
    var res = 0, offset = offset || 0, shift = 0, counter = offset, b, l = buf.length;
    do {
        if (counter >= l) {
            // @ts-ignore
            read.bytes = 0;
            throw new RangeError('Could not decode varint');
        }
        b = buf[counter++];
        res += shift < 28
            ? (b & REST$1) << shift
            : (b & REST$1) * Math.pow(2, shift);
        shift += 7;
    } while (b >= MSB$1);
    // @ts-ignore
    read.bytes = counter - offset;
    return res;
}
var N1 = Math.pow(2, 7);
var N2 = Math.pow(2, 14);
var N3 = Math.pow(2, 21);
var N4 = Math.pow(2, 28);
var N5 = Math.pow(2, 35);
var N6 = Math.pow(2, 42);
var N7 = Math.pow(2, 49);
var N8 = Math.pow(2, 56);
var N9 = Math.pow(2, 63);
var length = function (/** @type {number} */ value) {
    return (value < N1 ? 1
        : value < N2 ? 2
            : value < N3 ? 3
                : value < N4 ? 4
                    : value < N5 ? 5
                        : value < N6 ? 6
                            : value < N7 ? 7
                                : value < N8 ? 8
                                    : value < N9 ? 9
                                        : 10);
};
var varint = {
    encode: encode_1,
    decode: decode,
    encodingLength: length
};
var _brrp_varint = varint;
export default _brrp_varint;
//# sourceMappingURL=varint.js.map{
  "name": "multiformats",
  "version": "13.4.2",
  "description": "Interface for multihash, multicodec, multibase and CID",
  "author": "Mikeal Rogers <mikeal.rogers@gmail.com> (https://www.mikealrogers.com/)",
  "license": "Apache-2.0 OR MIT",
  "homepage": "https://github.com/multiformats/js-multiformats#readme",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/multiformats/js-multiformats.git"
  },
  "bugs": {
    "url": "https://github.com/multiformats/js-multiformats/issues"
  },
  "publishConfig": {
    "access": "public",
    "provenance": true
  },
  "keywords": [
    "ipfs",
    "ipld",
    "multiformats"
  ],
  "type": "module",
  "types": "./dist/src/index.d.ts",
  "typesVersions": {
    "*": {
      "*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ],
      "src/*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ]
    }
  },
  "files": [
    "src",
    "dist",
    "!dist/test",
    "!**/*.tsbuildinfo"
  ],
  "exports": {
    ".": {
      "types": "./dist/src/index.d.ts",
      "import": "./dist/src/index.js"
    },
    "./bases/base10": {
      "types": "./dist/src/bases/base10.d.ts",
      "import": "./dist/src/bases/base10.js"
    },
    "./bases/base16": {
      "types": "./dist/src/bases/base16.d.ts",
      "import": "./dist/src/bases/base16.js"
    },
    "./bases/base2": {
      "types": "./dist/src/bases/base2.d.ts",
      "import": "./dist/src/bases/base2.js"
    },
    "./bases/base256emoji": {
      "types": "./dist/src/bases/base256emoji.d.ts",
      "import": "./dist/src/bases/base256emoji.js"
    },
    "./bases/base32": {
      "types": "./dist/src/bases/base32.d.ts",
      "import": "./dist/src/bases/base32.js"
    },
    "./bases/base36": {
      "types": "./dist/src/bases/base36.d.ts",
      "import": "./dist/src/bases/base36.js"
    },
    "./bases/base58": {
      "types": "./dist/src/bases/base58.d.ts",
      "import": "./dist/src/bases/base58.js"
    },
    "./bases/base64": {
      "types": "./dist/src/bases/base64.d.ts",
      "import": "./dist/src/bases/base64.js"
    },
    "./bases/base8": {
      "types": "./dist/src/bases/base8.d.ts",
      "import": "./dist/src/bases/base8.js"
    },
    "./bases/identity": {
      "types": "./dist/src/bases/identity.d.ts",
      "import": "./dist/src/bases/identity.js"
    },
    "./bases/interface": {
      "types": "./dist/src/bases/interface.d.ts",
      "import": "./dist/src/bases/interface.js"
    },
    "./basics": {
      "types": "./dist/src/basics.d.ts",
      "import": "./dist/src/basics.js"
    },
    "./block": {
      "types": "./dist/src/block.d.ts",
      "import": "./dist/src/block.js"
    },
    "./block/interface": {
      "types": "./dist/src/block/interface.d.ts",
      "import": "./dist/src/block/interface.js"
    },
    "./bytes": {
      "types": "./dist/src/bytes.d.ts",
      "import": "./dist/src/bytes.js"
    },
    "./cid": {
      "types": "./dist/src/cid.d.ts",
      "import": "./dist/src/cid.js"
    },
    "./codecs/interface": {
      "types": "./dist/src/codecs/interface.d.ts",
      "import": "./dist/src/codecs/interface.js"
    },
    "./codecs/json": {
      "types": "./dist/src/codecs/json.d.ts",
      "import": "./dist/src/codecs/json.js"
    },
    "./codecs/raw": {
      "types": "./dist/src/codecs/raw.d.ts",
      "import": "./dist/src/codecs/raw.js"
    },
    "./hashes/digest": {
      "types": "./dist/src/hashes/digest.d.ts",
      "import": "./dist/src/hashes/digest.js"
    },
    "./hashes/hasher": {
      "types": "./dist/src/hashes/hasher.d.ts",
      "import": "./dist/src/hashes/hasher.js"
    },
    "./hashes/identity": {
      "types": "./dist/src/hashes/identity.d.ts",
      "import": "./dist/src/hashes/identity.js"
    },
    "./hashes/interface": {
      "types": "./dist/src/hashes/interface.d.ts",
      "import": "./dist/src/hashes/interface.js"
    },
    "./hashes/sha1": {
      "types": "./dist/types/src/hashes/sha1.d.ts",
      "browser": "./dist/src/hashes/sha1-browser.js",
      "import": "./dist/src/hashes/sha1.js"
    },
    "./hashes/sha2": {
      "types": "./dist/src/hashes/sha2.d.ts",
      "browser": "./dist/src/hashes/sha2-browser.js",
      "import": "./dist/src/hashes/sha2.js"
    },
    "./interface": {
      "types": "./dist/src/interface.d.ts",
      "import": "./dist/src/interface.js"
    },
    "./link": {
      "types": "./dist/src/link.d.ts",
      "import": "./dist/src/link.js"
    },
    "./link/interface": {
      "types": "./dist/src/link/interface.d.ts",
      "import": "./dist/src/link/interface.js"
    },
    "./traversal": {
      "types": "./dist/src/traversal.d.ts",
      "import": "./dist/src/traversal.js"
    }
  },
  "eslintConfig": {
    "extends": "ipfs",
    "parserOptions": {
      "project": true,
      "sourceType": "module"
    }
  },
  "release": {
    "branches": [
      "master"
    ],
    "plugins": [
      [
        "@semantic-release/commit-analyzer",
        {
          "preset": "conventionalcommits",
          "releaseRules": [
            {
              "breaking": true,
              "release": "major"
            },
            {
              "revert": true,
              "release": "patch"
            },
            {
              "type": "feat",
              "release": "minor"
            },
            {
              "type": "fix",
              "release": "patch"
            },
            {
              "type": "docs",
              "release": "patch"
            },
            {
              "type": "test",
              "release": "patch"
            },
            {
              "type": "deps",
              "release": "patch"
            },
            {
              "scope": "no-release",
              "release": false
            }
          ]
        }
      ],
      [
        "@semantic-release/release-notes-generator",
        {
          "preset": "conventionalcommits",
          "presetConfig": {
            "types": [
              {
                "type": "feat",
                "section": "Features"
              },
              {
                "type": "fix",
                "section": "Bug Fixes"
              },
              {
                "type": "chore",
                "section": "Trivial Changes"
              },
              {
                "type": "docs",
                "section": "Documentation"
              },
              {
                "type": "deps",
                "section": "Dependencies"
              },
              {
                "type": "test",
                "section": "Tests"
              }
            ]
          }
        }
      ],
      "@semantic-release/changelog",
      "@semantic-release/npm",
      "@semantic-release/github",
      [
        "@semantic-release/git",
        {
          "assets": [
            "CHANGELOG.md",
            "package.json"
          ]
        }
      ]
    ]
  },
  "scripts": {
    "clean": "aegir clean",
    "lint": "aegir lint",
    "build": "aegir build",
    "release": "aegir release",
    "docs": "aegir docs",
    "test": "npm run lint && npm run test:node && npm run test:chrome",
    "test:node": "aegir test -t node --cov",
    "test:chrome": "aegir test -t browser --cov",
    "test:chrome-webworker": "aegir test -t webworker",
    "test:firefox": "aegir test -t browser -- --browser firefox",
    "test:firefox-webworker": "aegir test -t webworker -- --browser firefox",
    "test:electron-main": "aegir test -t electron-main"
  },
  "devDependencies": {
    "@stablelib/sha256": "^2.0.0",
    "@stablelib/sha512": "^2.0.0",
    "@types/node": "^25.0.0",
    "aegir": "^47.0.7",
    "buffer": "^6.0.3",
    "cids": "^1.1.9",
    "crypto-hash": "^4.0.0"
  },
  "aegir": {
    "test": {
      "target": [
        "node",
        "browser"
      ]
    }
  },
  "browser": {
    "./hashes/sha1": "./dist/src/hashes/sha1-browser.js",
    "./dist/src/hashes/sha1.js": "./dist/src/hashes/sha1-browser.js",
    "./hashes/sha2": "./dist/src/hashes/sha2-browser.js",
    "./dist/src/hashes/sha2.js": "./dist/src/hashes/sha2-browser.js"
  }
}
{
  "name": "atproto-repo",
  "version": "0.0.1",
  "description": "Byte-exact atproto repo layer — CAR + DAG-CBOR + CID + MST — over Hypercore-friendly primitives. Verified against real relay-accepted repos.",
  "type": "module",
  "main": "lib/repo.js",
  "scripts": {
    "test": "brittle-node test/*.test.js",
    "postinstall": "node scripts/bare-deps.mjs"
  },
  "dependencies": {
    "@ipld/car": "^5.4.0",
    "@ipld/dag-cbor": "^9.2.1",
    "@noble/curves": "^1.9.7",
    "@noble/hashes": "^1.5.0",
    "multiformats": "^13.3.0"
  },
  "devDependencies": {
    "atproto-identity": "file:../atproto-identity",
    "brittle": "^4.0.2"
  }
}
// pairing.js — hpp-initiated browser pairing over blind-pairing (the "hash URL" that opens a peer tunnel).
//
// Aligns with pgv3's DeviceLinker (blind-pairing). pgv3's browser auth is TOFU (the daemon IS the identity
// authority, so it self-registers a browser key). favela is KEYLESS — the authority is the remote hpp/DID —
// so a browser sub-key must be DELEGATED by the DID. The DID key-holder (hpp) mints a one-time invite; the
// candidate (favela-web, on the browser's behalf) joins → an E2E tunnel opens over the DHT → the browser's
// sub-key PUBKEY goes up → the hpp delegates it → the delegation comes back. Works REMOTELY (any hpp on the
// DHT) and is owner-gated by construction (only the key-holder can mint an invite; favela-web holds no key).
//
// Direction note: DeviceLinker's source PUSHES a bundle to the joiner; here the candidate must send its
// sub-key UP first, so the sub-key rides the candidate's blind-pairing `userData` (the member's hello) and
// the delegation comes back as the confirm's `additional.data`.
import Hyperswarm from 'hyperswarm'
import BlindPairing from 'blind-pairing'
import crypto from 'hypercore-crypto'
import b4a from 'b4a'

const TIMEOUT_MS = 5 * 60 * 1000

// SOURCE (hpp): mint a one-time pairing invite. onSubkey(subKeyHex) => delegation object (device.delegate).
// Returns { inviteHex, waitForPeer, close }. Stays open for ONE pairing session (owner mints per browser).
export async function createPairInvite ({ onSubkey, swarm = null, timeout = TIMEOUT_MS } = {}) {
  if (typeof onSubkey !== 'function') throw new Error('createPairInvite requires onSubkey(subKey) => delegation')
  const pairingKey = crypto.keyPair()
  const { invite, publicKey: invitePublicKey, discoveryKey, seed } = BlindPairing.createInvite(pairingKey.publicKey)
  const inviteKeyPair = crypto.keyPair(seed)
  const sw = swarm || new Hyperswarm()
  const pairing = new BlindPairing(sw)
  const done = new Promise((resolve, reject) => {
    const timer = setTimeout(() => reject(new Error('createPairInvite: timeout waiting for the browser')), timeout)
    pairing.addMember({
      discoveryKey,
      onadd: async (request) => {
        clearTimeout(timer)
        try {
          request.open(invitePublicKey)
          const hello = JSON.parse(b4a.toString(request.userData)) // the candidate's sub-key
          const delegation = await onSubkey(hello.subKey)
          const data = b4a.from(JSON.stringify(delegation))
          request.confirm({ key: pairingKey.publicKey, encryptionKey: null, additional: { data, signature: crypto.sign(data, inviteKeyPair.secretKey) } })
          resolve({ subKey: hello.subKey, delegation })
        } catch (e) {
          // ⛔ TELL THE CANDIDATE. Rejecting only settles OUR promise; the joiner is left holding an open
          // tunnel with nothing coming back, so it waits out its full timeout (5 min) and reports
          // nothing about why. That is exactly how a BROWSER invite pasted into a NODE presents: the
          // node sends a 64-hex keet device key, delegate() demands 66-hex secp256k1 and throws here,
          // and the node just… hangs. A refusal is information the other side needs.
          //
          // Confirm with an { error } payload — the same shape mintAdoptInvite already returns when a
          // human declines — then reject locally. Best-effort: if the channel is already gone there is
          // nothing to say and the timeout remains the backstop.
          try {
            const data = b4a.from(JSON.stringify({ error: (e && e.message) || String(e) }))
            request.confirm({ key: pairingKey.publicKey, encryptionKey: null, additional: { data, signature: crypto.sign(data, inviteKeyPair.secretKey) } })
          } catch { /* channel gone — the candidate falls back to its timeout */ }
          reject(e)
        }
      }
    })
  })
  return {
    inviteHex: b4a.toString(invite, 'hex'),
    waitForPeer: () => done,
    // DRAIN before teardown (mirrors pgv3 DeviceLinker.close). The confirm frame carrying the delegation
    // is enqueued via protomux AFTER onadd returns, but waitForPeer resolves SYNCHRONOUSLY inside onadd —
    // so the CLI's `await waitForPeer(); await close()` would destroy the swarm before the frame hits the
    // wire. The candidate (favela-web) then never receives the delegation and hangs to timeout, while the
    // source falsely reports success. Awaiting conn.flush() drains protomux→noise→UDX before destroy.
    close: async () => {
      try {
        const flushes = []
        for (const conn of sw.connections) { if (typeof conn.flush === 'function') flushes.push(conn.flush()) }
        await Promise.all(flushes).catch(() => {})
      } catch {}
      try { await pairing.close() } catch {}
      if (!swarm) { try { await sw.destroy() } catch {} }
    }
  }
}

// CANDIDATE (favela-web): join with the invite + the browser's sub-key pubkey → receive the delegation.
// swarm optional (an ephemeral one is created + destroyed). Throws on timeout.
export async function joinPairInvite (inviteHex, { subKey, swarm = null, timeout = TIMEOUT_MS } = {}) {
  if (!subKey) throw new Error('joinPairInvite requires subKey')
  const sw = swarm || new Hyperswarm()
  const pairing = new BlindPairing(sw)
  const userData = b4a.from(JSON.stringify({ subKey }))
  try {
    return await new Promise((resolve, reject) => {
      const timer = setTimeout(() => reject(new Error('joinPairInvite: timeout')), timeout)
      pairing.addCandidate({
        invite: b4a.from(inviteHex, 'hex'),
        userData,
        onadd: (result) => {
          clearTimeout(timer)
          try { resolve(JSON.parse(b4a.toString(result.data))) } catch (e) { reject(e) }
        }
      })
    })
  } finally {
    try { await pairing.close() } catch {}
    if (!swarm) { try { await sw.destroy() } catch {} }
  }
}
const { Pull, Push, HEADERBYTES, KEYBYTES, ABYTES } = require('sodium-secretstream')
const sodium = require('sodium-universal')
const crypto = require('hypercore-crypto')
const { Duplex, Writable, getStreamError } = require('streamx')
const b4a = require('b4a')
const Timeout = require('timeout-refresh')
const unslab = require('unslab')
const Bridge = require('./lib/bridge')
const Handshake = require('./lib/handshake')

const IDHEADERBYTES = HEADERBYTES + 32
const [NS_INITIATOR, NS_RESPONDER, NS_SEND] = crypto.namespace('hyperswarm/secret-stream', 3)
const MAX_ATOMIC_WRITE = 256 * 256 * 256 - 1

module.exports = class NoiseSecretStream extends Duplex {
  constructor(isInitiator, rawStream, opts = {}) {
    super({ mapWritable: toBuffer })

    if (typeof isInitiator !== 'boolean') {
      throw new Error('isInitiator should be a boolean')
    }

    this.noiseStream = this
    this.isInitiator = isInitiator
    this.rawStream = null

    this.publicKey = opts.publicKey || null
    this.remotePublicKey = opts.remotePublicKey || null
    this.handshakeHash = null
    this.connected = false
    this.keepAlive = opts.keepAlive || 0
    this.timeout = 0
    this.enableSend = opts.enableSend !== false

    // pointer for upstream to set data here if they want
    this.userData = null

    let openedDone = null
    this.opened = new Promise((resolve) => {
      openedDone = resolve
    })

    this.rawBytesWritten = 0
    this.rawBytesRead = 0

    // metadata used by 'hyperdht'
    this.relay = null
    this.puncher = null

    // unwrapped raw stream
    this._rawStream = null

    // handshake state
    this._handshake = null
    this._handshakePattern = opts.pattern || null
    this._handshakeDone = null

    // message parsing state
    this._state = 0
    this._len = 0
    this._tmp = 1
    this._message = null

    this._openedDone = openedDone
    this._startDone = null
    this._drainDone = null
    this._outgoingPlain = null
    this._outgoingWrapped = null
    this._utp = null
    this._setup = true
    this._ended = 2
    this._encrypt = null
    this._decrypt = null
    this._timeoutTimer = null
    this._keepAliveTimer = null
    this._sendState = null

    if (opts.autoStart !== false) this.start(rawStream, opts)

    // wiggle it to trigger open immediately (TODO add streamx option for this)
    this.resume()
    this.pause()
  }

  static keyPair(seed) {
    return Handshake.keyPair(seed)
  }

  static id(handshakeHash, isInitiator, id) {
    return streamId(handshakeHash, isInitiator, id)
  }

  setTimeout(ms) {
    if (!ms) ms = 0

    this._clearTimeout()
    this.timeout = ms

    if (!ms || this.rawStream === null) return

    this._timeoutTimer = Timeout.once(ms, destroyTimeout, this)
    this._timeoutTimer.unref()
  }

  setKeepAlive(ms) {
    if (!ms) ms = 0

    this._clearKeepAlive()

    this.keepAlive = ms

    if (!ms || this.rawStream === null) return

    this._keepAliveTimer = Timeout.on(ms, sendKeepAlive, this)
    this._keepAliveTimer.unref()
  }

  sendKeepAlive() {
    const empty = this.alloc(0)
    this.write(empty)
  }

  start(rawStream, opts = {}) {
    if (rawStream) {
      this.rawStream = rawStream
      this._rawStream = rawStream
      if (typeof this.rawStream.setContentSize === 'function') {
        this._utp = rawStream
      }
    } else {
      this.rawStream = new Bridge(this)
      this._rawStream = this.rawStream.reverse
    }

    this.rawStream.on('error', this._onrawerror.bind(this))
    this.rawStream.on('close', this._onrawclose.bind(this))

    this._startHandshake(opts.handshake, opts.keyPair || null)
    this._continueOpen(null)

    if (this.destroying) return

    if (opts.data) this._onrawdata(opts.data)
    if (opts.ended) this._onrawend()

    if (this.keepAlive > 0 && this._keepAliveTimer === null) {
      this.setKeepAlive(this.keepAlive)
    }

    if (this.timeout > 0 && this._timeoutTimer === null) {
      this.setTimeout(this.timeout)
    }
  }

  async flush() {
    if ((await this.opened) === false) return false
    if ((await Writable.drained(this)) === false) return false
    if (this.destroying) return false

    if (this.rawStream !== null && this.rawStream.flush) {
      return await this.rawStream.flush()
    }

    return true
  }

  _continueOpen(err) {
    if (err) this.destroy(err)
    if (this._startDone === null) return
    const done = this._startDone
    this._startDone = null
    this._open(done)
  }

  _onkeypairpromise(p) {
    const self = this
    const cont = this._continueOpen.bind(this)

    p.then(onkeypair, cont)

    function onkeypair(kp) {
      self._onkeypair(kp)
      cont(null)
    }
  }

  _onkeypair(keyPair) {
    const pattern = this._handshakePattern || 'XX'
    const remotePublicKey = this.remotePublicKey

    this._handshake = new Handshake(this.isInitiator, keyPair, remotePublicKey, pattern)
    this.publicKey = this._handshake.keyPair.publicKey
  }

  _startHandshake(handshake, keyPair) {
    if (handshake) {
      const { tx, rx, hash, publicKey, remotePublicKey } = handshake
      this._setupSecretStream(tx, rx, hash, publicKey, remotePublicKey)
      return
    }

    if (!keyPair) keyPair = Handshake.keyPair()

    if (typeof keyPair.then === 'function') {
      this._onkeypairpromise(keyPair)
    } else {
      this._onkeypair(keyPair)
    }
  }

  _onrawerror(err) {
    this.destroy(err)
  }

  _onrawclose() {
    if (this._ended !== 0) this.destroy()
  }

  _onrawdata(data) {
    let offset = 0

    if (this._timeoutTimer !== null) {
      this._timeoutTimer.refresh()
    }

    do {
      switch (this._state) {
        case 0: {
          while (this._tmp !== 0x1000000 && offset < data.byteLength) {
            const v = data[offset++]
            this._len += this._tmp * v
            this._tmp *= 256
          }

          if (this._tmp === 0x1000000) {
            this._tmp = 0
            this._state = 1
            const unprocessed = data.byteLength - offset
            if (unprocessed < this._len && this._utp !== null)
              this._utp.setContentSize(this._len - unprocessed)
          }

          break
        }

        case 1: {
          const missing = this._len - this._tmp
          const end = missing + offset

          if (this._message === null && end <= data.byteLength) {
            this._message = data.subarray(offset, end)
            offset += missing
            this._incoming()
            break
          }

          const unprocessed = data.byteLength - offset

          if (this._message === null) {
            this._message = b4a.allocUnsafe(this._len)
          }

          b4a.copy(data, this._message, this._tmp, offset)
          this._tmp += unprocessed

          if (end <= data.byteLength) {
            offset += missing
            this._incoming()
          } else {
            offset += unprocessed
          }

          break
        }
      }
    } while (offset < data.byteLength && !this.destroying)
  }

  _onrawend() {
    this._ended--
    this.push(null)
  }

  _onrawdrain() {
    const drain = this._drainDone
    if (drain === null) return
    this._drainDone = null
    drain()
  }

  _read(cb) {
    this.rawStream.resume()
    cb(null)
  }

  _incoming() {
    const message = this._message

    this._state = 0
    this._len = 0
    this._tmp = 1
    this._message = null

    if (this._setup === true) {
      if (this._handshake) {
        this._onhandshakert(this._handshake.recv(message))
      } else {
        if (message.byteLength !== IDHEADERBYTES) {
          this.destroy(new Error('Invalid header message received'))
          return
        }

        const remoteId = message.subarray(0, 32)
        const expectedId = streamId(this.handshakeHash, !this.isInitiator)
        const header = message.subarray(32)

        if (!b4a.equals(expectedId, remoteId)) {
          this.destroy(new Error('Invalid header received'))
          return
        }

        this._decrypt.init(header)
        this._setup = false // setup is now done
      }
      return
    }

    if (message.byteLength < ABYTES) {
      this.destroy(new Error('Invalid message received'))
      return
    }

    this.rawBytesRead += message.byteLength

    const plain = message.subarray(1, message.byteLength - ABYTES + 1)

    try {
      this._decrypt.next(message, plain)
    } catch (err) {
      this.destroy(err)
      return
    }

    // If keep alive is selective, eat the empty buffers (ie assume the other side has it enabled also)
    if (plain.byteLength === 0 && this.keepAlive !== 0) return

    if (this.push(plain) === false) {
      this.rawStream.pause()
    }
  }

  _onhandshakert(h) {
    if (this._handshakeDone === null) return

    if (h !== null) {
      if (h.data) this._rawStream.write(h.data)
      if (!h.tx) return
    }

    const done = this._handshakeDone
    const publicKey = this._handshake.keyPair.publicKey

    this._handshakeDone = null
    this._handshake = null

    if (h === null) return done(new Error('Noise handshake failed'))

    this._setupSecretStream(h.tx, h.rx, h.hash, publicKey, h.remotePublicKey)
    this._resolveOpened(true)
    done(null)
  }

  _setupSecretStream(tx, rx, handshakeHash, publicKey, remotePublicKey) {
    const buf = b4a.allocUnsafeSlow(3 + IDHEADERBYTES)
    writeUint24le(IDHEADERBYTES, buf)

    this._encrypt = new Push(unslab(tx.subarray(0, KEYBYTES)), undefined, buf.subarray(3 + 32))
    this._decrypt = new Pull(unslab(rx.subarray(0, KEYBYTES)))

    this.publicKey = publicKey
    this.remotePublicKey = remotePublicKey
    this.handshakeHash = handshakeHash

    const id = buf.subarray(3, 3 + 32)
    streamId(handshakeHash, this.isInitiator, id)

    // initialize secretbox state for unordered messages
    this._setupSecretSend(handshakeHash)

    this.emit('handshake')
    // if rawStream is a bridge, also emit it there
    if (this.rawStream !== this._rawStream) this.rawStream.emit('handshake')

    if (this.destroying) return

    this._rawStream.write(buf)
  }

  _setupSecretSend(handshakeHash) {
    this._sendState = b4a.allocUnsafeSlow(32 + 32 + 8 + 8)
    const encrypt = this._sendState.subarray(0, 32) // secrets
    const decrypt = this._sendState.subarray(32, 64)
    const counter = this._sendState.subarray(64, 72) // nonce
    const initial = this._sendState.subarray(72)

    const inputs = this.isInitiator
      ? [
          [NS_INITIATOR, NS_SEND],
          [NS_RESPONDER, NS_SEND]
        ]
      : [
          [NS_RESPONDER, NS_SEND],
          [NS_INITIATOR, NS_SEND]
        ]

    sodium.crypto_generichash_batch(encrypt, inputs[0], handshakeHash)
    sodium.crypto_generichash_batch(decrypt, inputs[1], handshakeHash)

    sodium.randombytes_buf(initial)
    counter.set(initial)
  }

  _open(cb) {
    // no autostart or no handshake yet
    if (this._rawStream === null || (this._handshake === null && this._encrypt === null)) {
      this._startDone = cb
      return
    }

    this._rawStream.on('data', this._onrawdata.bind(this))
    this._rawStream.on('end', this._onrawend.bind(this))
    this._rawStream.on('drain', this._onrawdrain.bind(this))

    if (this.enableSend) this._rawStream.on('message', this._onmessage.bind(this))

    if (this._encrypt !== null) {
      this._resolveOpened(true)
      return cb(null)
    }

    this._handshakeDone = cb

    if (this.isInitiator) this._onhandshakert(this._handshake.send())
  }

  _predestroy() {
    if (this.rawStream) {
      const error = getStreamError(this)
      this.rawStream.destroy(error)
    }

    if (this._startDone !== null) {
      const done = this._startDone
      this._startDone = null
      done(new Error('Stream destroyed'))
    }

    if (this._handshakeDone !== null) {
      const done = this._handshakeDone
      this._handshakeDone = null
      done(new Error('Stream destroyed'))
    }

    if (this._drainDone !== null) {
      const done = this._drainDone
      this._drainDone = null
      done(new Error('Stream destroyed'))
    }
  }

  _write(data, cb) {
    let wrapped = this._outgoingWrapped

    if (data !== this._outgoingPlain) {
      wrapped = b4a.allocUnsafe(data.byteLength + 3 + ABYTES)
      wrapped.set(data, 4)
    } else {
      this._outgoingWrapped = this._outgoingPlain = null
    }

    if (wrapped.byteLength - 3 > MAX_ATOMIC_WRITE) {
      return cb(
        new Error(
          'Message is too large for an atomic write. Max size is ' + MAX_ATOMIC_WRITE + ' bytes.'
        )
      )
    }
    this.rawBytesWritten += wrapped.byteLength

    writeUint24le(wrapped.byteLength - 3, wrapped)
    // offset 4 so we can do it in-place
    this._encrypt.next(wrapped.subarray(4, 4 + data.byteLength), wrapped.subarray(3))

    if (this._keepAliveTimer !== null) this._keepAliveTimer.refresh()

    if (this._rawStream.write(wrapped) === false) {
      this._drainDone = cb
    } else {
      cb(null)
    }
  }

  _final(cb) {
    this._clearKeepAlive()
    this._ended--
    this._rawStream.end()
    cb(null)
  }

  _resolveOpened(val) {
    if (this._openedDone === null) return
    const opened = this._openedDone
    this._openedDone = null
    opened(val)
    if (!val) return
    this.connected = true
    this.emit('connect')
  }

  _clearTimeout() {
    if (this._timeoutTimer === null) return
    this._timeoutTimer.destroy()
    this._timeoutTimer = null
    this.timeout = 0
  }

  _clearKeepAlive() {
    if (this._keepAliveTimer === null) return
    this._keepAliveTimer.destroy()
    this._keepAliveTimer = null
    this.keepAlive = 0
  }

  _destroy(cb) {
    this._clearKeepAlive()
    this._clearTimeout()
    this._resolveOpened(false)
    cb(null)
  }

  _boxMessage(buffer) {
    const MB = sodium.crypto_secretbox_MACBYTES // 16
    const NB = sodium.crypto_secretbox_NONCEBYTES // 24

    const counter = this._sendState.subarray(64, 72)
    sodium.sodium_increment(counter)
    if (b4a.equals(counter, this._sendState.subarray(72))) {
      this.destroy(new Error('udp send nonce exchausted'))
      return
    }

    const secret = this._sendState.subarray(0, 32)
    const envelope = b4a.allocUnsafe(8 + MB + buffer.byteLength)
    const nonce = envelope.subarray(0, NB)
    const ciphertext = envelope.subarray(8)

    b4a.fill(nonce, 0) // pad suffix
    nonce.set(counter)

    sodium.crypto_secretbox_easy(ciphertext, buffer, nonce, secret)
    return envelope
  }

  send(buffer) {
    if (!this._sendState) return
    if (!this.rawStream?.send) return // udx-stream expected

    const message = this._boxMessage(buffer)
    return this.rawStream.send(message)
  }

  trySend(buffer) {
    if (!this._sendState) return
    if (!this.rawStream?.trySend) return // udx-stream expected

    const message = this._boxMessage(buffer)
    this.rawStream.trySend(message)
  }

  _onmessage(buffer) {
    if (!this._sendState) return // messages before handshake are dropped

    const MB = sodium.crypto_secretbox_MACBYTES // 16
    const NB = sodium.crypto_secretbox_NONCEBYTES // 24

    if (buffer.byteLength < NB) return // Invalid message

    const nonce = b4a.allocUnsafe(NB)
    b4a.fill(nonce, 0)
    nonce.set(buffer.subarray(0, 8))

    const secret = this._sendState.subarray(32, 64)
    const ciphertext = buffer.subarray(8)
    const plain = buffer.subarray(8, buffer.byteLength - MB)

    if (ciphertext.byteLength < MB) return // invalid message

    const success = sodium.crypto_secretbox_open_easy(plain, ciphertext, nonce, secret)

    if (success) this.emit('message', plain)
  }

  alloc(len) {
    const buf = b4a.allocUnsafe(len + 3 + ABYTES)
    this._outgoingWrapped = buf
    this._outgoingPlain = buf.subarray(4, buf.byteLength - ABYTES + 1)
    return this._outgoingPlain
  }

  toJSON() {
    return {
      isInitiator: this.isInitiator,
      publicKey: this.publicKey && b4a.toString(this.publicKey, 'hex'),
      remotePublicKey: this.remotePublicKey && b4a.toString(this.remotePublicKey, 'hex'),
      connected: this.connected,
      destroying: this.destroying,
      destroyed: this.destroyed,
      rawStream: this.rawStream && this.rawStream.toJSON ? this.rawStream.toJSON() : null
    }
  }
}

function writeUint24le(n, buf) {
  buf[0] = n & 255
  buf[1] = (n >>> 8) & 255
  buf[2] = (n >>> 16) & 255
}

function streamId(handshakeHash, isInitiator, out = b4a.allocUnsafe(32)) {
  sodium.crypto_generichash(out, isInitiator ? NS_INITIATOR : NS_RESPONDER, handshakeHash)
  return out
}

function toBuffer(data) {
  return typeof data === 'string' ? b4a.from(data) : data
}

function destroyTimeout() {
  this.destroy(new Error('Stream timed out'))
}

function sendKeepAlive() {
  const empty = this.alloc(0)
  this.write(empty)
}
const { Duplex, Writable } = require('streamx')

class ReversePassThrough extends Duplex {
  constructor(s) {
    super()
    this._stream = s
    this._ondrain = null
  }

  _write(data, cb) {
    if (this._stream.push(data) === false) {
      this._stream._ondrain = cb
    } else {
      cb(null)
    }
  }

  _final(cb) {
    this._stream.push(null)
    cb(null)
  }

  _read(cb) {
    const ondrain = this._ondrain
    this._ondrain = null
    if (ondrain) ondrain()
    cb(null)
  }
}

module.exports = class Bridge extends Duplex {
  constructor(noiseStream) {
    super()

    this.noiseStream = noiseStream

    this._ondrain = null
    this.reverse = new ReversePassThrough(this)
  }

  get publicKey() {
    return this.noiseStream.publicKey
  }

  get remotePublicKey() {
    return this.noiseStream.remotePublicKey
  }

  get handshakeHash() {
    return this.noiseStream.handshakeHash
  }

  flush() {
    return Writable.drained(this)
  }

  _read(cb) {
    const ondrain = this._ondrain
    this._ondrain = null
    if (ondrain) ondrain()
    cb(null)
  }

  _write(data, cb) {
    if (this.reverse.push(data) === false) {
      this.reverse._ondrain = cb
    } else {
      cb(null)
    }
  }

  _final(cb) {
    this.reverse.push(null)
    cb(null)
  }
}
const sodium = require('sodium-universal')
const curve = require('noise-curve-ed')
const Noise = require('noise-handshake')
const b4a = require('b4a')

const EMPTY = b4a.alloc(0)

module.exports = class Handshake {
  constructor(isInitiator, keyPair, remotePublicKey, pattern) {
    this.isInitiator = isInitiator
    this.keyPair = keyPair
    this.noise = new Noise(pattern, isInitiator, keyPair, { curve })
    this.noise.initialise(EMPTY, remotePublicKey)
    this.destroyed = false
  }

  static keyPair(seed) {
    const publicKey = b4a.alloc(32)
    const secretKey = b4a.alloc(64)
    if (seed) sodium.crypto_sign_seed_keypair(publicKey, secretKey, seed)
    else sodium.crypto_sign_keypair(publicKey, secretKey)
    return { publicKey, secretKey }
  }

  recv(data) {
    try {
      this.noise.recv(data)
      if (this.noise.complete) return this._return(null)
      return this.send()
    } catch {
      this.destroy()
      return null
    }
  }

  // note that the data returned here is framed so we don't have to do an extra copy
  // when sending it...
  send() {
    try {
      const data = this.noise.send()
      const wrap = b4a.allocUnsafe(data.byteLength + 3)

      writeUint24le(data.byteLength, wrap)
      wrap.set(data, 3)

      return this._return(wrap)
    } catch {
      this.destroy()
      return null
    }
  }

  destroy() {
    if (this.destroyed) return
    this.destroyed = true
  }

  _return(data) {
    const tx = this.noise.complete ? b4a.toBuffer(this.noise.tx) : null
    const rx = this.noise.complete ? b4a.toBuffer(this.noise.rx) : null
    const hash = this.noise.complete ? b4a.toBuffer(this.noise.hash) : null
    const remotePublicKey = this.noise.complete ? b4a.toBuffer(this.noise.rs) : null

    return {
      data,
      remotePublicKey,
      hash,
      tx,
      rx
    }
  }
}

function writeUint24le(n, buf) {
  buf[0] = n & 255
  buf[1] = (n >>> 8) & 255
  buf[2] = (n >>> 16) & 255
}
{
  "name": "@hyperswarm/secret-stream",
  "version": "6.9.1",
  "description": "Secret stream backed by Noise and libsodium's secretstream",
  "main": "index.js",
  "files": [
    "index.js",
    "lib/**.js"
  ],
  "dependencies": {
    "b4a": "^1.1.0",
    "hypercore-crypto": "^3.3.1",
    "noise-curve-ed": "^2.0.1",
    "noise-handshake": "^4.0.0",
    "sodium-secretstream": "^1.1.0",
    "sodium-universal": "^5.0.0",
    "streamx": "^2.14.0",
    "timeout-refresh": "^2.0.0",
    "unslab": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "udx-native": "^1.13.2"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check .",
    "test": "brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/hyperswarm-secret-stream.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/hyperswarm-secret-stream/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperswarm-secret-stream"
}
const Cache = require('xache')

module.exports = class AdaptiveTimeout {
  constructor(opts = {}) {
    this._cache = new Cache({
      maxSize: opts.maxSize || 65536,
      maxAge: opts.maxAge || 10 * 60 * 1000 // 10 minutes
    })
    this._fallback = opts.fallback || AdaptiveTimeout.TimeoutExponential
    this._min = opts.min ?? 300
    this._max = opts.max || 4000
    this._jitter = opts.jitter ?? 256
  }

  // Default - aggressive ramp
  static TimeoutAggressive = [500, 750, 1000, 1500, 2000]

  // Linear - steady increase
  static TimeoutLinear = [500, 1000, 1500, 2000, 2500]

  // Exponential - slow start, rapid backoff
  static TimeoutExponential = [250, 500, 1000, 2000, 4000]

  // Gentle - conservative, patient
  static TimeoutGentle = [1000, 1250, 1500, 1750, 2000]

  // Fast - rapid fire retries
  static TimeoutFast = [200, 400, 600, 800, 1000]

  // U-shape - long, short, long
  static TimeoutUShape = [1500, 750, 500, 750, 1500]

  // Inverse U - short, long, short
  static TimeoutInverseU = [500, 1000, 1500, 1000, 500]

  // Sawtooth - alternating fast/slow
  static TimeoutSawtooth = [500, 1500, 500, 1500, 500]

  // Plateau - quick ramp then steady
  static TimeoutPlateau = [500, 1000, 2000, 2000, 2000]

  // Logarithmic - diminishing increases
  static TimeoutLogarithmic = [500, 1000, 1300, 1500, 1600]

  getValue(key) {
    return this._cache.get(key)
  }

  put(key, value) {
    let p = this._cache.get(key)

    if (!p) {
      p = { avg: value, variance: value >> 1 }
    } else {
      // blend 75% old + 25% new deviation
      p.variance += (Math.abs(p.avg - value) - p.variance) >> 2
      // blend 87.5% old + 12.5% new sample
      p.avg += (value - p.avg) >> 3
    }

    this._cache.set(key, p)

    return p
  }

  get(key, attempt = 1) {
    const p = this._cache.get(key)
    const jitter = (Math.random() * this._jitter) | 0

    if (p) {
      // known - use adaptive with linear backoff
      const base = p.avg + (p.variance << 1)
      const backoff = base * attempt
      return Math.min(Math.max(backoff + jitter, this._min), this._max)
    } else {
      // unknown - use aggressive fallback
      const base = this._fallback[Math.min(attempt - 1, this._fallback.length - 1)]
      return base + jitter
    }
  }

  has(key) {
    return this._cache.has(key)
  }

  delete(key) {
    return this._cache.delete(key)
  }

  clear() {
    this._cache.clear()
  }
}
{
  "name": "adaptive-timeout",
  "version": "1.0.1",
  "description": "adaptive-timeout",
  "main": "index.js",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    }
  },
  "files": [
    "package.json",
    "index.js",
    "index.d.ts"
  ],
  "devDependencies": {
    "brittle": "^3.19.0",
    "lunte": "^1.2.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && lunte && brittle-bare test/index.js",
    "lint": "lunte"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/adaptive-timeout.git"
  },
  "author": "Holepunch Inc",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/adaptive-timeout/issues"
  },
  "homepage": "https://github.com/holepunchto/adaptive-timeout",
  "dependencies": {
    "xache": "^1.2.1"
  }
}
function isBuffer(value) {
  return Buffer.isBuffer(value) || value instanceof Uint8Array
}

function isEncoding(encoding) {
  return Buffer.isEncoding(encoding)
}

function alloc(size, fill, encoding) {
  return Buffer.alloc(size, fill, encoding)
}

function allocUnsafe(size) {
  return Buffer.allocUnsafe(size)
}

function allocUnsafeSlow(size) {
  return Buffer.allocUnsafeSlow(size)
}

function byteLength(string, encoding) {
  return Buffer.byteLength(string, encoding)
}

function compare(a, b) {
  return Buffer.compare(a, b)
}

function concat(buffers, totalLength) {
  return Buffer.concat(buffers, totalLength)
}

function copy(source, target, targetStart, start, end) {
  return toBuffer(source).copy(target, targetStart, start, end)
}

function equals(a, b) {
  return toBuffer(a).equals(b)
}

function fill(buffer, value, offset, end, encoding) {
  return toBuffer(buffer).fill(value, offset, end, encoding)
}

function from(value, encodingOrOffset, length) {
  return Buffer.from(value, encodingOrOffset, length)
}

function includes(buffer, value, byteOffset, encoding) {
  return toBuffer(buffer).includes(value, byteOffset, encoding)
}

function indexOf(buffer, value, byfeOffset, encoding) {
  return toBuffer(buffer).indexOf(value, byfeOffset, encoding)
}

function lastIndexOf(buffer, value, byteOffset, encoding) {
  return toBuffer(buffer).lastIndexOf(value, byteOffset, encoding)
}

function swap16(buffer) {
  return toBuffer(buffer).swap16()
}

function swap32(buffer) {
  return toBuffer(buffer).swap32()
}

function swap64(buffer) {
  return toBuffer(buffer).swap64()
}

function toBuffer(buffer) {
  if (Buffer.isBuffer(buffer)) return buffer
  return Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

function toString(buffer, encoding, start, end) {
  return toBuffer(buffer).toString(encoding, start, end)
}

function write(buffer, string, offset, length, encoding) {
  return toBuffer(buffer).write(string, offset, length, encoding)
}

function readDoubleBE(buffer, offset) {
  return toBuffer(buffer).readDoubleBE(offset)
}

function readDoubleLE(buffer, offset) {
  return toBuffer(buffer).readDoubleLE(offset)
}

function readFloatBE(buffer, offset) {
  return toBuffer(buffer).readFloatBE(offset)
}

function readFloatLE(buffer, offset) {
  return toBuffer(buffer).readFloatLE(offset)
}

function readInt32BE(buffer, offset) {
  return toBuffer(buffer).readInt32BE(offset)
}

function readInt32LE(buffer, offset) {
  return toBuffer(buffer).readInt32LE(offset)
}

function readUInt32BE(buffer, offset) {
  return toBuffer(buffer).readUInt32BE(offset)
}

function readUInt32LE(buffer, offset) {
  return toBuffer(buffer).readUInt32LE(offset)
}

function writeDoubleBE(buffer, value, offset) {
  return toBuffer(buffer).writeDoubleBE(value, offset)
}

function writeDoubleLE(buffer, value, offset) {
  return toBuffer(buffer).writeDoubleLE(value, offset)
}

function writeFloatBE(buffer, value, offset) {
  return toBuffer(buffer).writeFloatBE(value, offset)
}

function writeFloatLE(buffer, value, offset) {
  return toBuffer(buffer).writeFloatLE(value, offset)
}

function writeInt32BE(buffer, value, offset) {
  return toBuffer(buffer).writeInt32BE(value, offset)
}

function writeInt32LE(buffer, value, offset) {
  return toBuffer(buffer).writeInt32LE(value, offset)
}

function writeUInt32BE(buffer, value, offset) {
  return toBuffer(buffer).writeUInt32BE(value, offset)
}

function writeUInt32LE(buffer, value, offset) {
  return toBuffer(buffer).writeUInt32LE(value, offset)
}

module.exports = {
  isBuffer,
  isEncoding,
  alloc,
  allocUnsafe,
  allocUnsafeSlow,
  byteLength,
  compare,
  concat,
  copy,
  equals,
  fill,
  from,
  includes,
  indexOf,
  lastIndexOf,
  swap16,
  swap32,
  swap64,
  toBuffer,
  toString,
  write,
  readDoubleBE,
  readDoubleLE,
  readFloatBE,
  readFloatLE,
  readInt32BE,
  readInt32LE,
  readUInt32BE,
  readUInt32LE,
  writeDoubleBE,
  writeDoubleLE,
  writeFloatBE,
  writeFloatLE,
  writeInt32BE,
  writeInt32LE,
  writeUInt32BE,
  writeUInt32LE
}
{
  "name": "b4a",
  "version": "1.8.1",
  "description": "Bridging the gap between buffers and typed arrays",
  "exports": {
    "./package": "./package.json",
    ".": {
      "react-native": "./react-native.js",
      "browser": "./browser.js",
      "default": "./index.js"
    }
  },
  "files": [
    "browser.js",
    "index.js",
    "react-native.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:bare && npm run test:node",
    "test:bare": "brittle-bare --coverage test.mjs",
    "test:node": "brittle-node --coverage test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/b4a.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/b4a/issues"
  },
  "homepage": "https://github.com/holepunchto/b4a#readme",
  "devDependencies": {
    "brittle": "^3.5.2",
    "lunte": "^1.7.0",
    "nanobench": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "react-native-b4a": "*"
  },
  "peerDependenciesMeta": {
    "react-native-b4a": {
      "optional": true
    }
  }
}
const ESC = '\x1b'
const CSI = ESC + '['
const SGR = (n) => CSI + n + 'm'

exports.constants = {
  ESC,
  CSI,
  SGR
}

// https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_(Control_Sequence_Introducer)_sequences

exports.cursorHide = CSI + '?25l'
exports.cursorShow = CSI + '?25h'

exports.cursorUp = function cursorUp(n = 1) {
  return CSI + n + 'A'
}

exports.cursorDown = function cursorDown(n = 1) {
  return CSI + n + 'B'
}

exports.cursorForward = function cursorForward(n = 1) {
  return CSI + n + 'C'
}

exports.cursorBack = function cursorBack(n = 1) {
  return CSI + n + 'D'
}

exports.cursorNextLine = function cursorNextLine(n = 1) {
  return CSI + n + 'E'
}

exports.cursorPreviousLine = function cursorPreviousLine(n = 1) {
  return CSI + n + 'F'
}

exports.cursorPosition = function cursorPosition(column, row = 0) {
  if (row === 0) return CSI + (column + 1) + 'G'

  return CSI + (row + 1) + ';' + (column + 1) + 'H'
}

exports.eraseDisplayEnd = CSI + 'J'
exports.eraseDisplayStart = CSI + '1J'
exports.eraseDisplay = CSI + '2J'
exports.eraseLineEnd = CSI + 'K'
exports.eraseLineStart = CSI + '1K'
exports.eraseLine = CSI + '2K'

exports.scrollUp = function scrollUp(n = 1) {
  return CSI + n + 'S'
}

exports.scrollDown = function scrollDown(n = 1) {
  return CSI + n + 'T'
}

// https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_(Select_Graphic_Rendition)_parameters

exports.modifierReset = SGR(0)
exports.modifierBold = SGR(1)
exports.modifierDim = SGR(2)
exports.modifierItalic = SGR(3)
exports.modifierUnderline = SGR(4)
exports.modifierNormal = SGR(22)
exports.modifierNotItalic = SGR(23)
exports.modifierNotUnderline = SGR(24)

// https://en.wikipedia.org/wiki/ANSI_escape_code#Colors

exports.colorBlack = SGR(30)
exports.colorRed = SGR(31)
exports.colorGreen = SGR(32)
exports.colorYellow = SGR(33)
exports.colorBlue = SGR(34)
exports.colorMagenta = SGR(35)
exports.colorCyan = SGR(36)
exports.colorWhite = SGR(37)
exports.colorDefault = SGR(39)
exports.colorBrightBlack = SGR(90)
exports.colorBrightRed = SGR(91)
exports.colorBrightGreen = SGR(92)
exports.colorBrightYellow = SGR(93)
exports.colorBrightBlue = SGR(94)
exports.colorBrightMagenta = SGR(95)
exports.colorBrightCyan = SGR(96)
exports.colorBrightWhite = SGR(97)
{
  "name": "bare-ansi-escapes",
  "version": "2.2.3",
  "description": "Parse and produce ANSI escape sequences",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./key-decoder": {
      "types": "./key-decoder.d.ts",
      "default": "./key-decoder.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "key-decoder.js",
    "key-decoder.d.ts"
  ],
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-ansi-escapes.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-ansi-escapes/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-ansi-escapes#readme",
  "dependencies": {
    "bare-stream": "^2.6.5"
  },
  "devDependencies": {
    "bare-buffer": "^3.0.2",
    "brittle": "^3.3.2",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  },
  "peerDependencies": {
    "bare-buffer": "*"
  },
  "peerDependenciesMeta": {
    "bare-buffer": {
      "optional": true
    }
  }
}
const inspect = require('bare-inspect')

class AssertionError extends Error {
  constructor(opts = {}) {
    let { message = null, actual, expected, operator } = opts

    if (message === null) {
      message = `${inspect(actual)} ${operator} ${inspect(expected)}`
    }

    super(message)

    this.actual = actual
    this.expected = expected
    this.operator = operator
  }

  get name() {
    return 'AssertionError'
  }

  get code() {
    'ASSERTION'
  }
}

function assertFail(opts, fn) {
  if (opts.message instanceof Error) throw opts.message

  const err = new AssertionError(opts)

  if (Error.captureStackTrace) Error.captureStackTrace(err, fn)

  throw err
}

module.exports = exports = function assert(actual, message) {
  if (actual) return

  assertFail({ message, actual, expected: true, operator: '==' }, assert)
}

exports.AssertionError = AssertionError

exports.fail = function fail(message) {
  if (message === undefined) message = 'Failed'

  assertFail({ message, operator: 'fail' }, fail)
}

exports.ok = function ok(actual, message) {
  if (actual) return

  assertFail({ message, actual, expected: true, operator: '==' }, ok)
}

exports.notOk = function ok(actual, message) {
  if (!actual) return

  assertFail({ message, actual, expected: false, operator: '==' }, ok)
}

exports.equal = function equal(actual, expected, message) {
  if (actual == expected || (actual !== actual && expected !== expected)) {
    return
  }

  assertFail({ message, actual, expected, operator: '==' }, equal)
}

exports.notEqual = function notEqual(actual, expected, message) {
  if (actual != expected && (actual === actual || expected === expected)) {
    return
  }

  assertFail({ message, actual, expected, operator: '!=' }, notEqual)
}

exports.strictEqual = function strictEqual(actual, expected, message) {
  if (Object.is(actual, expected)) return

  assertFail(
    { message, actual, expected, operator: 'strictEqual' },
    strictEqual
  )
}

exports.notStrictEqual = function notStrictEqual(actual, expected, message) {
  if (!Object.is(actual, expected)) return

  assertFail(
    { message, actual, expected, operator: 'notStrictEqual' },
    notStrictEqual
  )
}
{
  "name": "bare-assert",
  "version": "1.2.0",
  "description": "Assertion library for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts"
  ],
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-assert.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-assert/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-assert#readme",
  "dependencies": {
    "bare-inspect": "^3.1.2"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  }
}
const errors = require('./lib/errors')

class EventListener {
  constructor() {
    this.list = []
    this.count = 0
  }

  append(ctx, name, fn, once) {
    this.count++
    ctx.emit('newListener', name, fn) // Emit BEFORE adding
    this.list.push([fn, once])
  }

  prepend(ctx, name, fn, once) {
    this.count++
    ctx.emit('newListener', name, fn) // Emit BEFORE adding
    this.list.unshift([fn, once])
  }

  remove(ctx, name, fn) {
    for (let i = 0, n = this.list.length; i < n; i++) {
      const l = this.list[i]

      if (l[0] === fn) {
        this.list.splice(i, 1)

        if (this.count === 1) delete ctx._events[name]

        ctx.emit('removeListener', name, fn) // Emit AFTER removing

        this.count--
        return
      }
    }
  }

  removeAll(ctx, name) {
    const list = [...this.list]
    this.list = []

    if (this.count === list.length) delete ctx._events[name]

    for (let i = list.length - 1; i >= 0; i--) {
      ctx.emit('removeListener', name, list[i][0]) // Emit AFTER removing
    }

    this.count -= list.length
  }

  emit(ctx, name, ...args) {
    const list = [...this.list]

    for (let i = 0, n = list.length; i < n; i++) {
      const l = list[i]

      if (l[1] === true) this.remove(ctx, name, l[0])

      Reflect.apply(l[0], ctx, args)
    }

    return list.length > 0
  }
}

function appendListener(ctx, name, fn, once) {
  if (ctx._events === undefined) ctx._events = Object.create(null)
  const e = ctx._events[name] || (ctx._events[name] = new EventListener())
  e.append(ctx, name, fn, once)
  return ctx
}

function prependListener(ctx, name, fn, once) {
  if (ctx._events === undefined) ctx._events = Object.create(null)
  const e = ctx._events[name] || (ctx._events[name] = new EventListener())
  e.prepend(ctx, name, fn, once)
  return ctx
}

function removeListener(ctx, name, fn) {
  if (ctx._events === undefined) return ctx
  const e = ctx._events[name]
  if (e !== undefined) e.remove(ctx, name, fn)
  return ctx
}

function throwUnhandledError(...args) {
  let err

  if (args.length > 0) err = args[0]

  if (err instanceof Error === false) err = errors.UNHANDLED_ERROR(err)

  if (Error.captureStackTrace) {
    Error.captureStackTrace(err, exports.prototype.emit)
  }

  queueMicrotask(() => {
    throw err
  })
}

module.exports = exports = class EventEmitter {
  constructor() {
    this._events = Object.create(null)
  }

  addListener(name, fn) {
    return appendListener(this, name, fn, false)
  }

  addOnceListener(name, fn) {
    return appendListener(this, name, fn, true)
  }

  prependListener(name, fn) {
    return prependListener(this, name, fn, false)
  }

  prependOnceListener(name, fn) {
    return prependListener(this, name, fn, true)
  }

  removeListener(name, fn) {
    return removeListener(this, name, fn)
  }

  on(name, fn) {
    return appendListener(this, name, fn, false)
  }

  once(name, fn) {
    return appendListener(this, name, fn, true)
  }

  off(name, fn) {
    return removeListener(this, name, fn)
  }

  emit(name, ...args) {
    if (name === 'error' && this._events !== undefined && this._events.error === undefined) {
      throwUnhandledError(...args)
    }

    if (this._events === undefined) return false
    const e = this._events[name]
    return e === undefined ? false : e.emit(this, name, ...args)
  }

  listeners(name) {
    if (this._events === undefined) return []
    const e = this._events[name]
    return e === undefined ? [] : [...e.list]
  }

  rawListeners(name) {
    if (this._events === undefined) return []
    const e = this._events[name]
    return e === undefined ? [] : e.list.map((l) => l[0])
  }

  eventNames() {
    if (this._events === undefined) return []
    return Reflect.ownKeys(this._events)
  }

  listenerCount(name) {
    if (this._events === undefined) return 0
    const e = this._events[name]
    return e === undefined ? 0 : e.list.length
  }

  getMaxListeners() {
    return EventEmitter.defaultMaxListeners
  }

  setMaxListeners(n) {}

  removeAllListeners(name) {
    if (arguments.length === 0) {
      for (const key of Reflect.ownKeys(this._events)) {
        if (key === 'removeListener') continue
        this.removeAllListeners(key)
      }
      this.removeAllListeners('removeListener')
    } else {
      const e = this._events[name]
      if (e !== undefined) e.removeAll(this, name)
    }
    return this
  }
}

exports.EventEmitter = exports

exports.errors = errors

exports.defaultMaxListeners = 10

exports.on = function on(emitter, name, opts = {}) {
  const { signal } = opts

  if (signal && signal.aborted) {
    throw errors.OPERATION_ABORTED(signal.reason)
  }

  let error = null
  let done = false

  const events = []
  const promises = []

  if (name !== 'error') emitter.on('error', onerror)

  if (signal) signal.addEventListener('abort', onabort)

  emitter.on(name, onevent)

  return {
    next() {
      if (events.length) {
        return Promise.resolve({ value: events.shift(), done: false })
      }

      if (error) {
        const err = error

        error = null

        return Promise.reject(err)
      }

      if (done) return onclose()

      return new Promise((resolve, reject) => promises.push({ resolve, reject }))
    },

    return() {
      return onclose()
    },

    throw(err) {
      return onerror(err)
    },

    [Symbol.asyncIterator]() {
      return this
    }
  }

  function onevent(...args) {
    if (promises.length) {
      promises.shift().resolve({ value: args, done: false })
    } else {
      events.push(args)
    }
  }

  function onerror(err) {
    emitter.off(name, onevent).off('error', onerror)

    if (promises.length) {
      promises.shift().reject(err)
    } else {
      error = err
    }

    return Promise.resolve({ done: true })
  }

  function onabort() {
    signal.removeEventListener('abort', onabort)

    onerror(errors.OPERATION_ABORTED(signal.reason))
  }

  function onclose() {
    emitter.off(name, onevent)

    if (name !== 'error') emitter.off('error', onerror)

    if (signal) signal.removeEventListener('abort', onabort)

    done = true

    if (promises.length) promises.shift().resolve({ done: true })

    return Promise.resolve({ done: true })
  }
}

exports.once = function once(emitter, name, opts = {}) {
  const { signal } = opts

  if (signal && signal.aborted) {
    return Promise.reject(errors.OPERATION_ABORTED(signal.reason))
  }

  return new Promise((resolve, reject) => {
    if (name !== 'error') emitter.on('error', onerror)

    if (signal) signal.addEventListener('abort', onabort)

    emitter.once(name, onevent)

    function onevent(...args) {
      if (name !== 'error') emitter.off('error', onerror)

      if (signal) signal.removeEventListener('abort', onabort)

      resolve(args)
    }

    function onerror(err) {
      emitter.off(name, onevent)

      if (name !== 'error') emitter.off('error', onerror)

      reject(err)
    }

    function onabort() {
      signal.removeEventListener('abort', onabort)

      onerror(errors.OPERATION_ABORTED(signal.reason))
    }
  })
}

exports.forward = function forward(from, to, names, opts = {}) {
  if (typeof names === 'string') names = [names]

  const { emit = to.emit.bind(to) } = opts

  const listeners = names.map(
    (name) =>
      function onevent(...args) {
        emit(name, ...args)
      }
  )

  to.on('newListener', (name) => {
    const i = names.indexOf(name)

    if (i !== -1 && to.listenerCount(name) === 0) {
      from.on(name, listeners[i])
    }
  }).on('removeListener', (name) => {
    const i = names.indexOf(name)

    if (i !== -1 && to.listenerCount(name) === 0) {
      from.off(name, listeners[i])
    }
  })
}

exports.listenerCount = function listenerCount(emitter, name) {
  return emitter.listenerCount(name)
}

exports.getMaxListeners = function getMaxListeners(emitter) {
  if (typeof emitter.getMaxListeners === 'function') {
    return emitter.getMaxListeners()
  }

  return exports.defaultMaxListeners
}

exports.setMaxListeners = function setMaxListeners(n, ...emitters) {
  if (emitters.length === 0) exports.defaultMaxListeners = n
  else {
    for (const emitter of emitters) {
      if (typeof emitter.setMaxListeners === 'function') {
        emitter.setMaxListeners(n)
      }
    }
  }
}
module.exports = class EventEmitterError extends Error {
  constructor(msg, code, fn = EventEmitterError, opts) {
    super(`${code}: ${msg}`, opts)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'EventEmitterError'
  }

  static OPERATION_ABORTED(cause, msg = 'Operation aborted') {
    return new EventEmitterError(msg, 'OPERATION_ABORTED', EventEmitterError.OPERATION_ABORTED, {
      cause
    })
  }

  static UNHANDLED_ERROR(cause, msg = 'Unhandled error') {
    return new EventEmitterError(msg, 'UNHANDLED_ERROR', EventEmitterError.UNHANDLED_ERROR, {
      cause
    })
  }
}
{
  "name": "bare-events",
  "version": "2.9.1",
  "description": "Event emitters for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    },
    "./web": {
      "types": "./web.d.ts",
      "default": "./web.js"
    },
    "./errors": "./lib/errors.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "global.js",
    "global.d.ts",
    "web.js",
    "web.d.ts",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:bare && npm run test:node",
    "test:bare": "brittle-bare --coverage test.js",
    "test:node": "brittle-node --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-events.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-events/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-events#readme",
  "devDependencies": {
    "bare-abort-controller": "^1.0.0",
    "brittle": "^3.3.2",
    "lunte": "^1.8.0",
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^2.0.0",
    "uncaughts": "^1.1.1"
  },
  "peerDependencies": {
    "bare-abort-controller": "*"
  },
  "peerDependenciesMeta": {
    "bare-abort-controller": {
      "optional": true
    }
  }
}
module.exports = require.addon()
const ansiEscapes = require('bare-ansi-escapes')
const getType = require('bare-type')
const binding = require('./binding')

const PLAIN_KEY = /^[a-zA-Z_][a-zA-Z_0-9]*$/

const defaultDepth = 2
const defaultBreakLength = 80
const defaultMaxArrayLength = 40

module.exports = exports = function inspect(value, opts = {}) {
  const {
    colors = false,
    depth = defaultDepth,
    breakLength = defaultBreakLength,
    stylize = defaultStylize(colors)
  } = opts

  const references = new InspectRefMap()

  const tree = inspectValue(value, 0, {
    colors,
    depth,
    breakLength,
    stylize,
    references
  })

  return tree.toString()
}

exports.styles = {
  bigint: ansiEscapes.colorYellow,
  boolean: ansiEscapes.colorYellow,
  date: ansiEscapes.colorMagenta,
  module: ansiEscapes.modifierUnderline,
  name: ansiEscapes.modifierReset,
  null: ansiEscapes.modifierBold,
  number: ansiEscapes.colorYellow,
  regexp: ansiEscapes.colorRed,
  special: ansiEscapes.colorCyan,
  string: ansiEscapes.colorGreen,
  symbol: ansiEscapes.colorGreen,
  undefined: ansiEscapes.colorBrightBlack
}

const styles = exports.styles

function defaultStylize(colors) {
  return function stylize(value, style) {
    const color = colors && styles[style]

    if (color) return color + value + ansiEscapes.modifierReset

    return value
  }
}

class InspectRefMap {
  constructor() {
    this.refs = new WeakMap()
    this.ids = new WeakMap()
    this.nextId = 1
  }

  has(object) {
    return this.refs.has(object)
  }

  get(object) {
    return this.refs.get(object) || null
  }

  set(object, ref) {
    this.refs.set(object, ref)
  }

  id(object) {
    let id = this.ids.get(object)
    if (id) return id

    id = this.nextId++
    this.ids.set(object, id)

    return id
  }
}

class InspectNode {
  constructor(depth, length, opts) {
    const { breakLength = defaultBreakLength, breakAlways = false } = opts

    this.depth = depth
    this.length = length
    this.breakLength = breakLength
    this.breakAlways = breakAlways
  }

  pad(n, string) {
    return string.padStart(n, ' ')
  }

  indent(n, string) {
    return '  '.repeat(n) + string
  }
}

class InspectRef extends InspectNode {
  constructor(depth, opts) {
    super(depth, '[circular *]'.length, opts)

    this.refs = opts.references
    this.count = 0
    this.circular = false
    this.color = opts.colors && styles.special
  }

  get id() {
    return this.refs.id(this)
  }

  increment() {
    return ++this.count
  }

  decrement() {
    return --this.count
  }

  toString(opts = {}) {
    const { offset = 0, pad = 0, indent = 0 } = opts

    let value = this.pad(pad, '[circular *' + this.id + ']')

    if (this.color) value = this.color + value + ansiEscapes.modifierReset

    return offset ? value : this.indent(indent, value)
  }
}

class InspectLeaf extends InspectNode {
  constructor(value, color, depth, opts) {
    const length = value.length

    if (value.includes('\n')) {
      value = value.replaceAll('\n', '\n' + '  '.repeat(depth))

      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.value = value
    this.color = opts.colors && color
  }

  toString(opts = {}) {
    const { offset = 0, pad = 0, indent = 0 } = opts

    let value = this.pad(pad, this.value)

    if (this.color) value = this.color + value + ansiEscapes.modifierReset

    return offset ? value : this.indent(indent, value)
  }
}

class InspectPair extends InspectNode {
  constructor(delim, left, right, depth, opts) {
    const length = left.length + delim.length + right.length

    if (left.breakAlways || right.breakAlways) {
      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.delim = delim
    this.left = left
    this.right = right
  }

  toString(opts = {}) {
    const { indent = 0 } = opts

    return this.indent(
      indent,
      this.left +
        this.delim +
        this.right.toString({
          indent,
          offset: this.left.length + this.delim.length
        })
    )
  }
}

class InspectSuspension extends InspectNode {
  constructor(overflow, depth, opts) {
    const label = `... ${overflow} more`

    super(depth, label.length, opts)

    this.label = label
  }

  toString(opts = {}) {
    const { indent = 0 } = opts

    return this.indent(indent, this.label)
  }
}

class InspectSequence extends InspectNode {
  constructor(header, footer, delim, values, ref, depth, opts) {
    const { tabulate = false } = opts

    const length =
      (ref.circular ? '<ref *>'.length + 1 : 0) +
      header.length +
      values.reduce(
        (length, value, i) =>
          length + value.length + (i === 0 ? 0 : delim.length),
        0
      ) +
      footer.length

    if (values.some((value) => value.breakAlways)) {
      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.header = header
    this.footer = footer
    this.delim = delim
    this.values = values
    this.ref = ref
    this.tabulate = tabulate
  }

  toString(opts = {}) {
    const { offset = 0, indent = 0 } = opts

    const split =
      this.breakAlways ||
      (this.values.length &&
        (offset + this.length > this.breakLength ||
          indent * 2 + this.length > this.breakLength))

    let header = this.header

    if (this.ref.circular) {
      header = '<ref *' + this.ref.id + '> ' + header
    }

    if (this.values.length === 0) {
      header = header.trimEnd()
    }

    if (offset === 0) {
      header = this.indent(indent, header)
    }

    if (split) {
      header = header.trimEnd() + '\n'
    }

    let string = header

    let columns = 1
    let pad = 0

    if (this.tabulate) {
      const widest = this.values.reduce(
        (length, value) =>
          value.breakAlways ? length : Math.max(length, value.length),
        0
      )

      if (widest) {
        columns = Math.max(
          columns,
          Math.floor(
            (this.breakLength - indent * 2) / (widest + this.delim.length)
          )
        )

        if (columns > 1) pad = widest
      }
    }

    for (let i = 0, n = this.values.length, offset = 0; i < n; i++) {
      const value = this.values[i]

      if (split) {
        let part

        if (i % columns === 0 || value.breakAlways) {
          part = value.toString({ indent: indent + 1, pad })
        } else {
          part = value.toString({ pad })
        }

        string += part

        if (i < n - 1) {
          if (i % columns === columns - 1 || this.values[i + 1].breakAlways) {
            string += this.delim.trimEnd() + '\n'
          } else {
            string += this.delim
          }
        }
      } else {
        if (i > 0) string += this.delim

        string += value.toString({ offset })

        offset += value.length
      }
    }

    let footer = this.footer

    if (this.values.length === 0) {
      footer = footer.trimStart()
    }

    if (split) {
      string += '\n' + this.indent(indent, footer.trimStart())
    } else {
      string += footer
    }

    return string
  }
}

function inspectValue(value, depth, opts) {
  const type = getType(value)

  if (type.isUndefined()) return inspectUndefined(depth, opts)
  if (type.isNull()) return inspectNull(depth, opts)
  if (type.isBoolean()) return inspectBoolean(value, depth, opts)
  if (type.isNumber()) return inspectNumber(value, depth, opts)
  if (type.isBigInt()) return inspectBigInt(value, depth, opts)
  if (type.isString()) return inspectString(value, depth, opts)
  if (type.isSymbol()) return inspectSymbol(value, depth, opts)
  if (type.isObject()) return inspectObject(type, value, depth, opts)
  if (type.isFunction()) return inspectFunction(type, value, depth, opts)
  if (type.isExternal()) return inspectExternal(value, opts, opts)
}

function inspectUndefined(depth, opts) {
  return new InspectLeaf('undefined', styles.undefined, depth, opts)
}

function inspectNull(depth, opts) {
  return new InspectLeaf('null', styles.null, depth, opts)
}

function inspectBoolean(value, depth, opts) {
  return new InspectLeaf(value.toString(), styles.boolean, depth, opts)
}

function inspectNumber(value, depth, opts) {
  let string

  if (Object.is(value, -0)) {
    string = '-0'
  } else {
    string = value.toString(10)
  }

  return new InspectLeaf(string, styles.number, depth, opts)
}

function inspectBigInt(value, depth, opts) {
  return new InspectLeaf(value.toString(10) + 'n', styles.bigint, depth, opts)
}

const STRING_ESCAPES =
  /[\ud800-\udbff][\udc00-\udfff]|[\u0000-\u001f'\\\ud800-\udfff]/g

function inspectString(value, depth, opts) {
  // https://tc39.es/ecma262/multipage/structured-data.html#sec-quotejsonstring
  const string = value.replace(STRING_ESCAPES, (match) => {
    if (match.length === 2) return match

    switch (match) {
      case "'":
        return "\\'"
      case '\\':
        return '\\\\'
      case '\b':
        return '\\b'
      case '\t':
        return '\\t'
      case '\n':
        return '\\n'
      case '\f':
        return '\\f'
      case '\r':
        return '\\r'
      default:
        return '\\u' + match.charCodeAt(0).toString(16).padStart(4, '0')
    }
  })

  return new InspectLeaf("'" + string + "'", styles.string, depth, opts)
}

function inspectSymbol(value, depth, opts) {
  return new InspectLeaf(value.toString(), styles.symbol, depth, opts)
}

function inspectKey(value, depth, opts) {
  if (PLAIN_KEY.test(value)) {
    return new InspectLeaf(value, null, depth, opts)
  } else {
    return inspectValue(value, depth, opts)
  }
}

function inspectObject(type, object, depth, opts) {
  const refs = opts.references

  let ref = refs.get(object)
  if (ref === null) {
    ref = new InspectRef(depth, opts)
    refs.set(object, ref)
  } else if (ref.count) {
    ref.circular = true
    return ref
  }

  const maxDepth = typeof opts.depth === 'number' ? opts.depth : Infinity

  if (maxDepth < depth) {
    const constructor = object.constructor

    return new InspectLeaf(
      '[' +
        (constructor && constructor.name ? constructor.name : 'Object') +
        ']',
      styles.special,
      depth,
      opts
    )
  }

  const inspect =
    object[Symbol.for('bare.inspect')] ||
    object[Symbol.for('nodejs.util.inspect.custom')]

  if (typeof inspect === 'function') {
    const value = inspect.call(
      object,
      typeof opts.depth === 'number' ? opts.depth - depth : null,
      {
        colors: opts.colors,
        breakLength: opts.breakLength,
        stylize: opts.stylize
      },
      exports
    )

    if (typeof value === 'object' && value !== null) {
      refs.set(value, ref)
    }

    if (typeof value !== 'string') {
      return inspectValue(value, depth, opts)
    }

    return new InspectLeaf(value, null, depth, opts)
  }

  if (type.isArray()) return inspectArray(object, ref, depth, opts)
  if (type.isDate()) return inspectDate(object, ref, depth, opts)
  if (type.isRegExp()) return inspectRegExp(object, ref, depth, opts)
  if (type.isError()) return inspectError(object, ref, depth, opts)
  if (type.isPromise()) return inspectPromise(object, ref, depth, opts)
  if (type.isMap()) return inspectMap(object, ref, depth, opts)
  if (type.isSet()) return inspectSet(object, ref, depth, opts)
  if (type.isWeakMap()) return inspectWeakMap(object, ref, depth, opts)
  if (type.isWeakSet()) return inspectWeakSet(object, ref, depth, opts)
  if (type.isWeakRef()) return inspectWeakRef(object, ref, depth, opts)
  if (type.isArrayBuffer()) return inspectArrayBuffer(object, ref, depth, opts)
  if (type.isSharedArrayBuffer())
    return inspectSharedArrayBuffer(object, ref, depth, opts)
  if (type.isTypedArray()) return inspectTypedArray(object, ref, depth, opts)
  if (type.isDataView()) return inspectDataView(object, ref, depth, opts)

  ref.increment()

  const values = []

  for (const key in object) {
    if (key === 'constructor') continue

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(object[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  let header = '{ '

  const tag = object[Symbol.toStringTag]

  if (tag) header = '[' + tag + '] ' + header

  if (object.constructor) {
    const name = object.constructor.name

    if (name && name !== 'Object') {
      header = object.constructor.name + ' ' + header
    }
  }

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectArray(array, ref, depth, opts) {
  const { maxArrayLength = defaultMaxArrayLength } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxArrayLength, 0)

  for (let i = 0, n = array.length; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(array.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(inspectValue(array[i], depth + 1, opts))
  }

  for (const key of binding.getOwnNonIndexPropertyNames(array)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(array[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  let header = '[ '

  if (array.constructor.name !== 'Array') {
    header = array.constructor.name + '(' + array.length + ') ' + header
  }

  return new InspectSequence(header, ' ]', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectDate(date, ref, depth, opts) {
  return new InspectLeaf(date.toISOString(), styles.date, depth, opts)
}

function inspectRegExp(regExp, ref, depth, opts) {
  return new InspectLeaf(regExp.toString(), styles.regexp, depth, opts)
}

function inspectError(error, ref, depth, opts) {
  let header

  if ('stack' in error) {
    header = error.stack

    if (depth > 0) {
      header = header.replaceAll('\n', '\n' + '  '.repeat(depth))
    }
  } else {
    header = error.toString()
  }

  const builtins = ['cause']

  if (error.name === 'AggregateError') {
    builtins.push('errors')
  } else if (error.name === 'SuppressedError') {
    builtins.push('error', 'suppressed')
  }

  const values = []

  for (const key of builtins) {
    if (key in error === false) continue

    values.push(
      new InspectPair(
        ': ',
        new InspectLeaf('[' + key + ']', null, depth + 1, opts),
        inspectValue(error[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key in error) {
    if (key === 'constructor' || builtins.includes(key)) continue

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(error[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  if (values.length === 0) return new InspectLeaf(header, null, depth, opts)

  return new InspectSequence(
    header + ' {',
    ' }',
    ', ',
    values,
    ref,
    depth,
    opts
  )
}

function inspectPromise(promise, ref, depth, opts) {
  ref.increment()

  const state = binding.getPromiseState(promise)

  const values = []

  switch (state) {
    case 0: // Pending
      values.push(new InspectLeaf('<pending>', styles.special, depth, opts))
      break

    case 1: // Fulfilled
      values.push(inspectValue(binding.getPromiseResult(promise), depth, opts))
      break

    case 2: // Rejected
      values.push(
        new InspectLeaf('<rejected>', styles.special, depth, opts),
        inspectValue(binding.getPromiseResult(promise), depth, opts)
      )
  }

  ref.decrement()

  const header = promise.constructor.name + ' { '

  return new InspectSequence(header, ' }', ' ', values, ref, depth, opts)
}

function inspectMap(map, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxMapLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = maxMapLength

  for (const entry of map) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(map.size - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )
      break
    }

    values.push(
      new InspectPair(
        ' => ',
        inspectValue(entry[0], depth + 1, opts),
        inspectValue(entry[1], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key in map) {
    if (key === 'constructor') continue

    const value = inspectValue(map[key], depth + 1, opts)

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        value,
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = map.constructor.name + '(' + map.size + ') { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectSet(set, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxSetLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = maxSetLength

  for (const entry of set) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(set.size - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )
      break
    }

    values.push(inspectValue(entry, depth + 1, opts))
  }

  for (const key in set) {
    if (key === 'constructor') continue

    const value = inspectValue(set[key], depth + 1, opts)

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        value,
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = set.constructor.name + '(' + set.size + ') { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectWeakMap(weakMap, ref, depth, opts) {
  const header = weakMap.constructor.name + ' { '

  return new InspectSequence(
    header,
    ' }',
    ' ',
    [new InspectLeaf('<items unknown>', styles.special, depth + 1, opts)],
    ref,
    depth,
    opts
  )
}

function inspectWeakSet(weakSet, ref, depth, opts) {
  const header = weakSet.constructor.name + ' { '

  return new InspectSequence(
    header,
    ' }',
    ' ',
    [new InspectLeaf('<items unknown>', styles.special, depth + 1, opts)],
    ref,
    depth,
    opts
  )
}

function inspectWeakRef(weakRef, ref, depth, opts) {
  const target = weakRef.deref()

  let value

  if (target === undefined) {
    value = new InspectLeaf('<cleared>', styles.special, depth + 1, opts)
  } else {
    value = inspectValue(target, depth + 1, opts)
  }

  const header = weakRef.constructor.name + ' { '

  return new InspectSequence(header, ' }', ' ', [value], ref, depth, opts)
}

function inspectArrayBuffer(arrayBuffer, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(arrayBuffer[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = arrayBuffer.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectSharedArrayBuffer(sharedArrayBuffer, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(sharedArrayBuffer[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = sharedArrayBuffer.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectTypedArray(typedArray, ref, depth, opts) {
  if (Buffer.isBuffer(typedArray)) {
    return inspectBuffer(typedArray, ref, depth, opts)
  }

  const {
    maxArrayLength = defaultMaxArrayLength,
    maxTypedArrayLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxTypedArrayLength, 0)

  for (let i = 0, n = typedArray.length; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(typedArray.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(inspectValue(typedArray[i], depth + 1, opts))
  }

  for (const key of binding.getOwnNonIndexPropertyNames(typedArray)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(typedArray[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = typedArray.constructor.name + '(' + typedArray.length + ') [ '

  return new InspectSequence(header, ' ]', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectBuffer(buffer, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxBufferLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxBufferLength, 0)

  for (let i = 0, n = buffer.byteLength; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(buffer.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(
      new InspectLeaf(
        buffer[i].toString(16).padStart(2, '0'),
        null,
        depth + 1,
        opts
      )
    )
  }

  for (const key of binding.getOwnNonIndexPropertyNames(buffer)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(buffer[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  return new InspectSequence('<Buffer ', '>', ' ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectDataView(dataView, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength', 'byteOffset', 'buffer']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(dataView[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key of binding.getOwnNonIndexPropertyNames(dataView)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(dataView[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = dataView.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectFunction(type, fn, depth, opts) {
  if (fn.toString().startsWith('class')) return inspectClass(fn, depth, opts)

  let tag = 'function'

  if (type.isGeneratorFunction()) tag = 'generator ' + tag
  if (type.isAsyncFunction()) tag = 'async ' + tag

  return new InspectLeaf(
    '[' + tag + ' ' + (fn.name ? fn.name : '(anonymous)') + ']',
    styles.special,
    depth,
    opts
  )
}

function inspectClass(ctor, depth, opts) {
  return new InspectLeaf(
    '[class ' + (ctor.name ? ctor.name : '(anonymous)') + ']',
    styles.special,
    depth,
    opts
  )
}

function inspectExternal(external, depth, opts) {
  return new InspectLeaf(
    '[external 0x' + binding.getExternal(external).toString(16) + ']',
    styles.special,
    depth,
    opts
  )
}
{
  "name": "bare-inspect",
  "version": "3.1.4",
  "description": "Inspect objects as strings for debugging",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-inspect.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-inspect/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-inspect#readme",
  "engines": {
    "bare": ">=1.18.0"
  },
  "dependencies": {
    "bare-ansi-escapes": "^2.1.0",
    "bare-type": "^1.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
module.exports = require.addon()
const binding = require('./binding')

const t = binding.constants

class Type {
  constructor(type) {
    this._type = type
  }

  isUndefined() {
    return this._type === t.UNDEFINED
  }

  isNull() {
    return this._type === t.NULL
  }

  isBoolean() {
    return this._type === t.BOOLEAN
  }

  isNumber() {
    return (this._type & 0xff) === t.NUMBER
  }

  isInt32() {
    return (this._type & (0xff | t.INT32)) === (t.NUMBER | t.INT32)
  }

  isUint32() {
    return (this._type & (0xff | t.UINT32)) === (t.NUMBER | t.UINT32)
  }

  isString() {
    return this._type === t.STRING
  }

  isSymbol() {
    return this._type === t.SYMBOL
  }

  isObject() {
    return (this._type & 0xff) === t.OBJECT
  }

  isArray() {
    return this._type === (t.OBJECT | t.ARRAY)
  }

  isArguments() {
    return this._type === (t.OBJECT | t.ARGUMENTS)
  }

  isDate() {
    return this._type === (t.OBJECT | t.DATE)
  }

  isRegExp() {
    return this._type === (t.OBJECT | t.REGEXP)
  }

  isError() {
    return this._type === (t.OBJECT | t.ERROR)
  }

  isPromise() {
    return this._type === (t.OBJECT | t.PROMISE)
  }

  isProxy() {
    return this._type === (t.OBJECT | t.PROXY)
  }

  isGenerator() {
    return this._type === (t.OBJECT | t.GENERATOR)
  }

  isMap() {
    return this._type === (t.OBJECT | t.MAP)
  }

  isSet() {
    return this._type === (t.OBJECT | t.SET)
  }

  isWeakMap() {
    return this._type === (t.OBJECT | t.WEAK_MAP)
  }

  isWeakSet() {
    return this._type === (t.OBJECT | t.WEAK_SET)
  }

  isWeakRef() {
    return this._type === (t.OBJECT | t.WEAK_REF)
  }

  isArrayBuffer() {
    return this._type === (t.OBJECT | t.ARRAYBUFFER)
  }

  isSharedArrayBuffer() {
    return this._type === (t.OBJECT | t.SHAREDARRAYBUFFER)
  }

  isTypedArray() {
    return (this._type & 0xffff) === (t.OBJECT | t.TYPEDARRAY)
  }

  isInt8Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT8ARRAY)
  }

  isUint8Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT8ARRAY)
  }

  isUint8ClampedArray() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT8CLAMPEDARRAY)
  }

  isInt16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT16ARRAY)
  }

  isUint16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT16ARRAY)
  }

  isInt32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT32ARRAY)
  }

  isUint32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT32ARRAY)
  }

  isFloat16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT16ARRAY)
  }

  isFloat32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT32ARRAY)
  }

  isFloat64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT64ARRAY)
  }

  isBigInt64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.BIGINT64ARRAY)
  }

  isBigUint64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.BIGUINT64ARRAY)
  }

  isDataView() {
    return this._type === (t.OBJECT | t.DATAVIEW)
  }

  isModuleNamespace() {
    return this._type === (t.OBJECT | t.MODULE_NAMESPACE)
  }

  isFunction() {
    return (this._type & 0xff) === t.FUNCTION
  }

  isAsyncFunction() {
    return (
      (this._type & (0xff | t.ASYNC_FUNCTION)) ===
      (t.FUNCTION | t.ASYNC_FUNCTION)
    )
  }

  isGeneratorFunction() {
    return (
      (this._type & (0xff | t.GENERATOR_FUNCTION)) ===
      (t.FUNCTION | t.GENERATOR_FUNCTION)
    )
  }

  isExternal() {
    return this._type === t.EXTERNAL
  }

  isBigInt() {
    return this._type === t.BIGINT
  }
}

module.exports = exports = function type(value) {
  switch (typeof value) {
    case 'undefined':
      return new Type(t.UNDEFINED)
    case 'boolean':
      return new Type(t.BOOLEAN)
    case 'number':
      return new Type(
        Number.isSafeInteger(value) ? binding.type(value) : t.NUMBER
      )
    case 'string':
      return new Type(t.STRING)
    case 'symbol':
      return new Type(t.SYMBOL)
    case 'object':
      return new Type(value === null ? t.NULL : binding.type(value))
    case 'function':
      return new Type(binding.type(value))
    case 'bigint':
      return new Type(t.BIGINT)
  }
}

exports.createTag = function createTag(...components) {
  const tag = new Uint32Array(4)
  for (let i = 0; i < 4; i++) tag[i] = components[i] || 0
  return tag
}

exports.addTag = function addTag(object, tag) {
  binding.addTag(object, tag)
}

exports.checkTag = function checkTag(object, tag) {
  return binding.checkTag(object, tag)
}
{
  "name": "bare-type",
  "version": "1.1.0",
  "description": "Cross-realm type predicates for Bare",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-type.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-type/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-type#readme",
  "engines": {
    "bare": ">=1.2.0"
  },
  "devDependencies": {
    "brittle": "^3.4.0",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
const b4a = require('b4a')

function byteLength (size) {
  return Math.ceil(size / 8)
}

function get (buffer, bit) {
  const n = buffer.BYTES_PER_ELEMENT * 8

  const offset = bit & (n - 1)
  const i = (bit - offset) / n

  return (buffer[i] & (1 << offset)) !== 0
}

function set (buffer, bit, value = true) {
  const n = buffer.BYTES_PER_ELEMENT * 8

  const offset = bit & (n - 1)
  const i = (bit - offset) / n
  const mask = 1 << offset

  if (value) {
    if ((buffer[i] & mask) !== 0) return false
  } else {
    if ((buffer[i] & mask) === 0) return false
  }

  buffer[i] ^= mask
  return true
}

function setRange (buffer, start, end, value = true) {
  const n = buffer.BYTES_PER_ELEMENT * 8

  let remaining = end - start
  let offset = start & (n - 1)
  let i = (start - offset) / n

  let changed = false

  while (remaining > 0) {
    const mask = (2 ** Math.min(remaining, n - offset) - 1) << offset

    if (value) {
      if ((buffer[i] & mask) !== mask) {
        buffer[i] |= mask
        changed = true
      }
    } else {
      if ((buffer[i] & mask) !== 0) {
        buffer[i] &= ~mask
        changed = true
      }
    }

    remaining -= n - offset
    offset = 0
    i++
  }

  return changed
}

function fill (buffer, value, start = 0, end = buffer.byteLength * 8) {
  const n = buffer.BYTES_PER_ELEMENT * 8
  let i, j

  {
    const offset = start & (n - 1)
    i = (start - offset) / n

    if (offset !== 0) {
      const mask = (2 ** Math.min(n - offset, end - start) - 1) << offset

      if (value) buffer[i] |= mask
      else buffer[i] &= ~mask

      i++
    }
  }

  {
    const offset = end & (n - 1)
    j = (end - offset) / n

    if (offset !== 0 && j >= i) {
      const mask = (2 ** offset) - 1

      if (value) buffer[j] |= mask
      else buffer[j] &= ~mask
    }
  }

  return buffer.fill(value ? (2 ** n) - 1 : 0, i, j)
}

function toggle (buffer, bit) {
  const n = buffer.BYTES_PER_ELEMENT * 8

  const offset = bit & (n - 1)
  const i = (bit - offset) / n
  const mask = 1 << offset

  buffer[i] ^= mask
  return (buffer[i] & mask) !== 0
}

function remove (buffer, bit) {
  return set(buffer, bit, false)
}

function removeRange (buffer, start, end) {
  return setRange(buffer, start, end, false)
}

function indexOf (buffer, value, position = 0) {
  for (let i = position, n = buffer.byteLength * 8; i < n; i++) {
    if (get(buffer, i) === value) return i
  }

  return -1
}

function lastIndexOf (buffer, value, position = buffer.byteLength * 8 - 1) {
  for (let i = position; i >= 0; i--) {
    if (get(buffer, i) === value) return i
  }

  return -1
}

function of (...bits) {
  return from(bits)
}

function from (bits) {
  const buffer = b4a.alloc(byteLength(bits.length))
  for (let i = 0; i < bits.length; i++) set(buffer, i, bits[i])
  return buffer
}

function * iterator (buffer) {
  for (let i = 0, n = buffer.byteLength * 8; i < n; i++) yield get(buffer, i)
}

module.exports = {
  byteLength,
  get,
  set,
  setRange,
  fill,
  toggle,
  remove,
  removeRange,
  indexOf,
  lastIndexOf,
  of,
  from,
  iterator
}
{
  "name": "bits-to-bytes",
  "version": "1.3.0",
  "description": "Functions for doing bit manipulation of typed arrays",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "scripts": {
    "test": "standard && brittle test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bits-to-bytes.git"
  },
  "author": "Kasper Isager Dalsgarð <kasper@funktionel.co>",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/holepunchto/bits-to-bytes/issues"
  },
  "homepage": "https://github.com/holepunchto/bits-to-bytes#readme",
  "dependencies": {
    "b4a": "^1.5.0"
  },
  "devDependencies": {
    "brittle": "^2.3.1",
    "standard": "^17.0.0"
  }
}
const crypto = require('hypercore-crypto')
const b4a = require('b4a')
const safetyCatch = require('safety-catch')
const ReadyResource = require('ready-resource')
const Xache = require('xache')
const { MemberRequest, CandidateRequest, createInvite, decodeInvite, verifyReceipt, Invite } = require('blind-pairing-core')
const Protomux = require('protomux')
const c = require('compact-encoding')
const debounce = require('debounceify')
const isOptions = require('is-options')

const [NS_EPHEMERAL, NS_REPLY, NS_DISCOVERY] = crypto.namespace('blind-pairing/dht', 3)

const DEFAULT_POLL = 7 * 60 * 1000
const PEER_INTERVAL = 1000

class TimeoutPromise {
  constructor (ms) {
    this.ms = ms
    this.resolve = null
    this.timeout = null
    this.destroyed = false
    this.suspended = false

    this._resolveBound = this._resolve.bind(this)
    this._ontimerBound = this._ontimer.bind(this)
  }

  wait () {
    if (this.destroyed) return Promise.resolve()
    if (this.resolve) this._resolve()
    return new Promise(this._ontimerBound)
  }

  suspend () {
    this.suspended = true
    if (this.timeout !== null) clearTimeout(this.timeout)
    this.timeout = null
  }

  resume () {
    this.suspended = false
    if (this.resolve) this._resolve()
  }

  destroy () {
    this.destroyed = true
    if (this.resolve) this._resolve()
  }

  _ontimer (resolve) {
    this.resolve = resolve
    if (!this.suspended) this.timeout = setTimeout(this._resolveBound, this.ms)
  }

  _resolve () {
    if (this.timeout !== null) clearTimeout(this.timeout)

    const resolve = this.resolve
    this.timeout = null
    this.resolve = null

    resolve()
  }
}

class BlindPairing extends ReadyResource {
  constructor (swarm, { poll = DEFAULT_POLL, onincoming = noop } = {}) {
    super()

    this.swarm = swarm
    this.poll = poll
    this.active = new Map()
    this.suspended = false

    this._onincoming = onincoming
    this._onconnectionBound = this._onconnection.bind(this)
    this._refreshBound = this.refresh.bind(this)
    this._refreshing = null

    this.swarm.on('connection', this._onconnectionBound)
    this.swarm.dht.on('network-change', this._refreshBound)
  }

  static Invite = Invite

  static createInvite (key, opts) {
    return createInvite(key, opts)
  }

  static decodeInvite (invite) {
    return decodeInvite(invite)
  }

  static verifyReceipt (receipt, publicKey) {
    return verifyReceipt(receipt, publicKey)
  }

  static createRequest (invite, userData) {
    return new CandidateRequest(invite, userData)
  }

  async suspend () {
    if (this.suspended) return
    this.suspended = true

    const all = []

    for (const ref of this.active.values()) {
      if (ref.candidate) all.push(ref.candidate._suspend())
      if (ref.member) all.push(ref.member._suspend())
    }

    await Promise.allSettled(all)
  }

  resume () {
    if (!this.suspended) return
    this.suspended = false
    this.refresh().catch(safetyCatch) // no need to wait for the refreshes
  }

  async refresh () {
    if (this._refreshing) {
      await this._refreshing
      return
    }

    if (this.closing || this.suspended) return

    const r = this._refreshing = this._refresh()

    try {
      await r
    } finally {
      if (r === this._refreshing) this._refreshing = null
    }
  }

  async _refresh () {
    if (this.closing || this.suspended) return

    const all = []

    for (const ref of this.active.values()) {
      if (ref.candidate) all.push(ref.candidate.refresh())
      if (ref.member) all.push(ref.member.refresh())
    }

    await Promise.allSettled(all)
  }

  addMember (opts) {
    return new Member(this, opts)
  }

  addCandidate (request, opts) {
    if (isOptions(request)) return this.addCandidate(null, request)
    if (!request) request = new CandidateRequest(opts.invite, opts.userData)
    return new Candidate(this, request, opts)
  }

  async _close () {
    this.swarm.removeListener('connection', this._onconnectionBound)
    this.swarm.dht.removeListener('network-change', this._refreshBound)

    const all = []

    for (const conn of this.swarm.connections) {
      const mux = getMuxer(conn)
      mux.unpair({ protocol: 'blind-pairing' })
      for (const ref of this.active.values()) mux.unpair({ protocol: 'blind-pairing', id: ref.discoveryKey })
    }

    for (const ref of this.active.values()) {
      if (ref.member) all.push(ref.member.close())
      if (ref.candidate) all.push(ref.candidate.close())
      if (ref.discovery) all.push(ref.discovery.destroy())
    }

    await Promise.allSettled(all)
  }

  _randomPoll () {
    return randomInterval(this.poll)
  }

  _add (discoveryKey) {
    const id = b4a.toString(discoveryKey, 'hex')
    const t = this.active.get(id)
    if (t) return t

    const fresh = {
      id,
      discoveryKey,
      member: null,
      candidate: null,
      channels: new Set(),
      alwaysServer: false,
      alwaysClient: false,
      discovery: null
    }

    this.active.set(id, fresh)
    return fresh
  }

  _swarm (ref) {
    const server = ref.alwaysServer || !!ref.member
    const client = ref.alwaysClient || !!ref.candidate

    if (ref.discovery && ref.discovery.isServer === server && ref.discovery.isClient === client) {
      return
    }

    if (ref.discovery) ref.discovery.destroy().catch(safetyCatch)

    // just a sanity check, not needed but doesnt hurt
    if (!server && !client) return

    ref.discovery = this.swarm.join(ref.discoveryKey, { server, client })
    this._attachToSwarm(ref)
  }

  _attachToSwarm (ref) {
    for (const conn of this.swarm.connections) {
      const mux = getMuxer(conn)
      this._attachToMuxer(mux, ref.discoveryKey, ref)
    }
  }

  _gc (ref) {
    if (ref.member || ref.candidate) {
      if (ref.discovery) this._swarm(ref) // in case it needs updating...
      return false
    }
    this.active.delete(ref.id)
    for (const ch of ref.channels) ch.close()
    for (const conn of this.swarm.connections) {
      const mux = getMuxer(conn)
      mux.unpair({ protocol: 'blind-pairing', id: ref.discoveryKey })
    }
    if (ref.discovery) ref.discovery.destroy().catch(safetyCatch)
    return true
  }

  _onconnection (conn) {
    const mux = getMuxer(conn)

    mux.pair({ protocol: 'blind-pairing' }, this._onincoming)

    for (const ref of this.active.values()) {
      this._attachToMuxer(mux, ref.discoveryKey, ref)
    }
  }

  _attachToMuxer (mux, discoveryKey, ref) {
    if (!ref) ref = this._add(discoveryKey)

    const ch = mux.createChannel({
      protocol: 'blind-pairing',
      id: discoveryKey,
      messages: [
        { encoding: c.buffer, onmessage: (req) => this._onpairingrequest(ch, ref, req) },
        { encoding: c.buffer, onmessage: (res) => this._onpairingresponse(ch, ref, res) }
      ],
      onclose: () => {
        ref.channels.delete(ch)
        if (ref.candidate) ref.candidate.visited.delete(ch)
      }
    })

    if (ch === null) return

    ch.open()
    mux.pair({ protocol: 'blind-pairing', id: discoveryKey }, () => this._attachToMuxer(mux, discoveryKey, null))
    ref.channels.add(ch)

    if (ref.candidate) ref.candidate.broadcast()
  }

  async _onpairingrequest (ch, ref, req) {
    if (!ref.member) return

    const request = await ref.member._addRequest(req)
    if (!request) return

    ch.messages[1].send(request.response)
  }

  async _onpairingresponse (ch, ref, res) {
    if (!ref.candidate) return

    await ref.candidate._addResponse(res, false)
  }
}

class Member extends ReadyResource {
  constructor (blind, { announce = true, discoveryKey, onadd = noop } = {}) {
    super()

    if (!discoveryKey) {
      throw new Error('Must provide discoveryKey')
    }

    const ref = blind._add(discoveryKey)

    if (ref.member) {
      throw new Error('Active member already exist')
    }

    ref.member = this

    this._pendingRequests = new Map()

    this.blind = blind
    this.dht = blind.swarm.dht
    this.discoveryKey = discoveryKey
    this.pairingDiscoveryKey = deriveDiscoveryKey(discoveryKey)
    this.timeout = new TimeoutPromise(blind._randomPoll())
    this.pairing = null
    this.skip = new Xache({ maxSize: 512 })
    this.ref = ref
    this.onadd = onadd

    this._activeQuery = null
    this._activePoll = null
    this._closestNodes = null
    this._autoAnnounce = announce

    this.ready()
  }

  announce () {
    if (this.pairing) return this.pairing

    this.blind._swarm(this.ref)
    this.pairing = this._run()
    this.pairing.catch(safetyCatch)

    return this.pairing
  }

  async flushed () {
    if (!this.ref.discovery) return
    return this.ref.discovery.flushed()
  }

  _open () {
    if (this._autoAnnounce) this.announce()
    else this.blind._attachToSwarm(this.ref)
  }

  _suspend () {
    this.timeout.suspend()
    return this._abort()
  }

  async _abort () {
    if (this._activeQuery) this._activeQuery.destroy()
    while (this._activePoll !== null) await this._activePoll
  }

  async refresh () {
    await this._abort()
    this.timeout.resume()
  }

  async _close () {
    this.ref.member = null
    this.blind._gc(this.ref)
    this.timeout.destroy()
    await this._abort()

    try {
      await this.pairing
    } catch {
      // ignore errors since we teardown
    }
  }

  async _run () {
    while (!this.closing) {
      this._activePoll = this._poll()
      await this._activePoll
      this._activePoll = null
      await this.timeout.wait()
    }
  }

  async _poll () {
    const visited = new Set()
    let alwaysClient = false

    if (this._activeQuery) this._activeQuery.destroy()

    const query = this._activeQuery = this.dht.lookup(this.pairingDiscoveryKey, { closestNodes: this._closestNodes })

    try {
      for await (const data of this._activeQuery) {
        if (this.closing || this.blind.suspended) return

        for (const peer of data.peers) {
          const id = b4a.toString(peer.publicKey, 'hex')

          if (visited.has(id) || this.skip.get(id)) continue
          visited.add(id)

          try {
            if (await this._add(peer.publicKey, id)) alwaysClient = true
          } catch (err) {
            safetyCatch(err)
          }

          if (this.closing || this.blind.suspended) return

          if (alwaysClient && !this.ref.alwaysClient) {
            this.ref.alwaysClient = true
            this.blind._swarm(this.ref)
          }
        }
      }
    } catch {
      // do nothing
    } finally {
      const nodes = this._activeQuery.closestNodes
      if (this._activeQuery === query) this._activeQuery = null
      if (nodes && nodes.length > 0) this._closestNodes = nodes
    }

    if (alwaysClient) this._revertClientAfterFlush() // safe to do in bg
  }

  async _revertClientAfterFlush () {
    try {
      await this.blind.swarm.flush()
    } catch {
      return
    }
    if (this.closing || this.blind.suspended) return

    this.ref.alwaysClient = false
    this.blind._swarm(this.ref)
  }

  async _addRequest (value) {
    let request = null
    try {
      request = MemberRequest.from(value)
    } catch {
      return null
    }

    request.discoveryKey = this.discoveryKey

    const session = b4a.toString(request.requestData.session, 'hex')

    if (!this._pendingRequests.has(session)) {
      this._pendingRequests.set(session, {
        request,
        promise: this.onadd(request)
      })
    }

    // laod existing request if it exists
    const pending = this._pendingRequests.get(session)

    try {
      await pending.promise
    } catch (e) {
      safetyCatch(e)
      return null
    }

    this._pendingRequests.delete(session)

    if (!pending.request.response) return null

    return pending.request
  }

  async _add (publicKey, id) {
    const node = await this.dht.mutableGet(publicKey, { latest: false })
    if (!node) return false

    this.skip.set(id, true)

    const request = await this._addRequest(node.value)
    if (!request) return false

    const replyKeyPair = deriveReplyKeyPair(request.token)
    await this.dht.mutablePut(replyKeyPair, request.response)

    return true
  }
}

class Candidate extends ReadyResource {
  constructor (blind, request, { discoveryKey = request.discoveryKey, onadd = noop } = {}) {
    super()

    const ref = blind._add(discoveryKey)
    if (ref.candidate) {
      throw new Error('Active candidate already exist')
    }

    ref.candidate = this

    this.blind = blind
    this.discoveryKey = discoveryKey
    this.pairingDiscoveryKey = deriveDiscoveryKey(discoveryKey)
    this.dht = blind.swarm.dht
    this.request = request
    this.token = request.token
    this.timeout = new TimeoutPromise(blind._randomPoll())
    this.announced = false
    this.gcing = null
    this.ref = ref
    this.paired = null
    this.pairing = null
    this.onadd = onadd

    this.signal = null
    this.visited = new Set()
    this.broadcast = debounce(this._broadcast.bind(this))

    this._activePoll = null

    this.ready()
  }

  _open () {
    this.blind._swarm(this.ref)
    this.pairing = this._run()
    this.broadcast()
  }

  _suspend () {
    this.timeout.suspend()
    // no good way to suspend the mut gets atm unfortunately so we just rely on the polls timing out
  }

  async refresh () {
    while (this._activePoll !== null) await this._activePoll
    this.announced = false
    this.timeout.resume()
  }

  async _close () {
    this.ref.candidate = null
    this.blind._gc(this.ref)
    this.timeout.destroy()
    this.visited.clear()
    await this.pairing
    // gc never throws
    if (this.gcing) await this.gcing
  }

  async _addResponse (value, gc) {
    if (this.paired) return

    const paired = this.request.handleResponse(value)
    if (!paired) return

    this.paired = paired
    if (this.signal) this.signal.destroy()

    if ((gc || this.announced) && !this.gcing) this.gcing = this._gc() // gc in the background
    await this.onadd(paired)
    this.timeout.destroy()
  }

  async _run () {
    while (!this._done()) {
      this._activePoll = this._poll()
      await this._activePoll
      this._activePoll = null
      if (this._done()) break
      await this.timeout.wait()
    }

    this.close().catch(safetyCatch)
    return this.paired
  }

  _done () {
    return !!(this.closing || this.paired)
  }

  async _announce () {
    const eph = deriveEphemeralKeyPair(this.token)

    await this.dht.mutablePut(eph, this.request.encode())
    if (this._done()) return

    await this.dht.announce(this.pairingDiscoveryKey, eph).finished()
    if (this._done()) return

    if (!this.paired) {
      this.ref.alwaysServer = true
      this.blind._swarm(this.ref)
    }

    this.emit('announce')
  }

  async _gc () {
    const eph = deriveEphemeralKeyPair(this.token)

    try {
      await this.dht.unannounce(this.pairingDiscoveryKey, eph)
    } catch (err) {
      safetyCatch(err) // just gc, whatevs
    }
  }

  _sendRequest (ch) {
    ch.messages[0].send(this.request.encode())
    this.visited.add(ch)
  }

  async _broadcast () {
    for (const channel of this.closestPeers()) {
      this.signal = new TimeoutPromise(randomInterval(PEER_INTERVAL))
      if (channel) this._sendRequest(channel)

      await this.signal.wait() // resolves on destroy

      if (this.paired || this.suspended) break
    }
  }

  * closestPeers () {
    while (!this.paired) {
      const closest = Infinity
      let channel = null

      for (const ch of this.ref.channels) {
        if (this.visited.has(ch)) continue

        const { rtt } = ch._mux.stream.rawStream
        if (rtt < closest) channel = ch
      }

      if (!channel) return

      yield channel
    }
  }

  async _poll () {
    try {
      const value = await this._getReply()
      if (this._done() || this.blind.suspended) return

      if (value) {
        await this._addResponse(value, true)
        if (this._done() || this.blind.suspended) return
      }

      if (!this.announced) {
        this.announced = true
        await this._announce()
      }
    } catch {
      // can run in bg, should never crash it
    }
  }

  async _getReply () {
    const { publicKey } = deriveReplyKeyPair(this.token)
    const node = await this.dht.mutableGet(publicKey, { latest: false })
    if (!node) return null
    return node.value
  }
}

module.exports = BlindPairing

function noop () {}

function deriveReplyKeyPair (token) {
  return crypto.keyPair(crypto.hash([NS_REPLY, token]))
}

function deriveEphemeralKeyPair (token) {
  return crypto.keyPair(crypto.hash([NS_EPHEMERAL, token]))
}

function deriveDiscoveryKey (discoveryKey) {
  return crypto.hash([NS_DISCOVERY, discoveryKey])
}

function getMuxer (stream) {
  if (stream.userData) return stream.userData
  const protocol = Protomux.from(stream)
  stream.setKeepAlive(5000)
  stream.userData = protocol
  return protocol
}

function randomInterval (n) {
  return n + (n * 0.5 * Math.random()) | 0
}
{
  "name": "blind-pairing",
  "version": "2.3.1",
  "description": "Blind pairing using Hyperswarm",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "blind-pairing-core": "^2.0.0",
    "b4a": "^1.6.4",
    "debounceify": "^1.1.0",
    "hypercore-crypto": "^3.4.0",
    "is-options": "^1.0.2",
    "ready-resource": "^1.0.0",
    "safety-catch": "^1.0.2",
    "xache": "^1.2.0"
  },
  "devDependencies": {
    "@hyperswarm/testnet": "^3.1.4",
    "brittle": "^3.3.2",
    "hyperdht": "^6.8.9",
    "hyperswarm": "^4.7.3",
    "minimist": "^1.2.8",
    "standard": "^17.1.0",
    "z32": "^1.0.1"
  },
  "scripts": {
    "test": "standard && brittle test/*.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/blind-pairing.git"
  },
  "author": "Holepunch Inc",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/blind-pairing/issues"
  },
  "homepage": "https://github.com/holepunchto/blind-pairing"
}
const EventEmitter = require('events')
const Protomux = require('protomux')
const { Readable } = require('streamx')
const sodium = require('sodium-universal')
const b4a = require('b4a')
const c = require('compact-encoding')
const bitfield = require('compact-encoding-bitfield')
const bits = require('bits-to-bytes')
const errors = require('./lib/errors')

exports.Server = class BlindRelayServer extends EventEmitter {
  constructor(opts = {}) {
    super()

    const { createStream } = opts

    this._createStream = createStream
    this._pairing = new Map()
    this._activePairingRefs = new Map()
    this._sessions = new Set()
    this.stats = createStats()
  }

  get sessions() {
    return this._sessions[Symbol.iterator]()
  }

  accept(stream, opts) {
    const session = new BlindRelaySession(this, stream, opts)

    this._sessions.add(session)
    this.stats.sessions.accepted++

    return session
  }

  async close() {
    const ending = []

    for (const session of this._sessions) {
      ending.push(session.end())
    }

    await Promise.all(ending)

    this._pairing.clear()
  }

  _trackActiveLink(keyString) {
    const refs = this._activePairingRefs.get(keyString) || 0

    if (refs === 0) this.stats.pairings.active++

    this._activePairingRefs.set(keyString, refs + 1)
  }

  _untrackActiveLink(keyString) {
    const refs = this._activePairingRefs.get(keyString)

    if (refs === undefined) return

    if (refs === 1) {
      this._activePairingRefs.delete(keyString)
      this.stats.pairings.active--
    } else {
      this._activePairingRefs.set(keyString, refs - 1)
    }
  }
}

class BlindRelaySession extends EventEmitter {
  constructor(server, stream, opts = {}) {
    super()

    const { id, handshake, handshakeEncoding } = opts

    this._server = server
    this._mux = Protomux.from(stream)

    this._channel = this._mux.createChannel({
      protocol: 'blind-relay',
      id,
      handshake: handshake ? handshakeEncoding || c.raw : null,
      onopen: this._onopen.bind(this),
      onclose: this._onclose.bind(this),
      ondestroy: this._ondestroy.bind(this)
    })

    this._pair = this._channel.addMessage({
      encoding: m.pair,
      onmessage: this._onpair.bind(this)
    })

    this._unpair = this._channel.addMessage({
      encoding: m.unpair,
      onmessage: this._onunpair.bind(this)
    })

    this._ending = null
    this._destroyed = false
    this._error = null
    this._pairing = new Set()
    this._links = new Map()

    this._onerror = (err) => {
      this._server.stats.streams.errors++
      this.emit('error', err)
    }

    this._channel.open(handshake)
  }

  get closed() {
    return this._channel.closed
  }

  get mux() {
    return this._mux
  }

  get stream() {
    return this._mux.stream
  }

  _onopen() {
    this._server.stats.sessions.opened++
    this.emit('open')
  }

  _onclose() {
    this._ending = Promise.resolve()

    const err = this._error || errors.CHANNEL_CLOSED()
    this._server.stats.pairings.cancelled += this._pairing.size

    for (const token of this._pairing) {
      if (this._server._pairing.delete(token.toString('hex'))) {
        this._server.stats.pairings.pending--
      }
    }

    for (const link of this._links.values()) {
      link.destroy(err)
    }

    this._pairing.clear()
    this._links.clear()

    this._server._sessions.delete(this)
    this._server.stats.sessions.closed++

    this.emit('close')
  }

  _ondestroy() {
    this._destroyed = true
    this.emit('destroy')
  }

  _onpair({ isInitiator, token, id: remoteId }) {
    const keyString = token.toString('hex')

    let pair = this._server._pairing.get(keyString)

    if (pair === undefined) {
      pair = new BlindRelayPair(token)
      this._server._pairing.set(keyString, pair)
      this._server.stats.pairings.pending++
    } else if (pair.links[+isInitiator]) return

    this._pairing.add(keyString)
    this._server.stats.pairings.requested++

    pair.links[+isInitiator] = new BlindRelayLink(this, isInitiator, remoteId)

    if (!pair.paired) return

    this._server._pairing.delete(keyString)
    this._server.stats.pairings.pending--
    this._server.stats.pairings.matched++

    // 1st pass: Create the raw streams needed for each end of the link.
    for (const link of pair.links) {
      link.createStream()
    }

    // 2nd pass: Connect the raw streams and set up handlers.
    for (const link of pair.links) {
      link.remote = pair.remote(link.isInitiator)
      link.activate(keyString)
    }

    // 3rd pass: Let either end of the link know the streams were set up.
    for (const { isInitiator, session, remoteId, stream } of pair.links) {
      session._pair.send({
        isInitiator,
        token,
        id: stream.id,
        seq: 0
      })

      session._endMaybe()

      session.emit('pair', isInitiator, token, stream, remoteId)
    }
  }

  _onunpair({ token }) {
    const keyString = token.toString('hex')

    const pair = this._server._pairing.get(keyString)

    if (pair) {
      for (const link of pair.links) {
        if (link) link.session._pairing.delete(keyString)
      }

      this._server._pairing.delete(keyString)
      this._server.stats.pairings.pending--
      this._server.stats.pairings.cancelled++
      return
    }

    const link = this._links.get(keyString)

    if (link) {
      link.destroyPair(errors.PAIRING_CANCELLED())
      this._server.stats.pairings.cancelled++
    }
  }

  cork() {
    this._channel.cork()
  }

  uncork() {
    this._channel.uncork()
  }

  async end() {
    if (this._ending) return this._ending

    this._ending = EventEmitter.once(this, 'close')
    this._endMaybe()

    return this._ending
  }

  _endMaybe() {
    if (this._ending && this._pairing.size === 0) {
      this._channel.close()
    }
  }

  destroy(err) {
    if (this._destroyed) return
    this._destroyed = true

    this._error = err || errors.CHANNEL_DESTROYED()
    this._channel.close()
  }
}

class BlindRelayPair {
  constructor(token) {
    this.token = token
    this.links = [null, null]
  }

  get paired() {
    return this.links[0] !== null && this.links[1] !== null
  }

  remote(isInitiator) {
    return this.links[isInitiator ? 0 : 1]
  }
}

class BlindRelayLink {
  constructor(session, isInitiator, remoteId) {
    this.session = session
    this.isInitiator = isInitiator
    this.remoteId = remoteId
    this.stream = null
    this.remote = null
    this.keyString = null
    this._onclose = null
  }

  createStream() {
    if (this.stream) return

    this.stream = this.session._server._createStream({
      firewall: this._onfirewall.bind(this)
    })
  }

  activate(keyString) {
    const stream = this.stream

    this.keyString = keyString
    this._onclose = () => {
      if (this.stream !== stream) return

      this.stream = null
      unlink(this)
      this.session._links.delete(keyString)
      this.session._server._untrackActiveLink(keyString)
      this.session._server.stats.streams.closed++
    }

    stream.on('error', this.session._onerror).on('close', this._onclose).relayTo(this.remote.stream)

    this.session._pairing.delete(keyString)
    this.session._links.set(keyString, this)
    this.session._server._trackActiveLink(keyString)
    this.session._server.stats.streams.opened++
  }

  destroy(err) {
    const stream = this.stream

    if (!stream) return

    this.stream = null

    stream.off('close', this._onclose)
    this._onclose = null

    stream.off('error', this.session._onerror)
    unlink(this)
    this.session._links.delete(this.keyString)
    this.session._server._untrackActiveLink(this.keyString)
    this.session._server.stats.streams.closed++
    stream.on('error', noop).destroy(err)
  }

  destroyPair(err) {
    const remote = this.remote

    this.destroy(err)
    if (remote) remote.destroy(err)
  }

  _onfirewall(socket, port, host) {
    this.stream.connect(socket, this.remoteId, port, host)

    return false
  }
}

exports.Client = class BlindRelayClient extends EventEmitter {
  static _clients = new WeakMap()

  static from(stream, opts) {
    let client = this._clients.get(stream)
    if (client) return client
    client = new this(stream, opts)
    this._clients.set(stream, client)
    return client
  }

  constructor(stream, opts = {}) {
    super()

    const { id, handshake, handshakeEncoding } = opts

    this._mux = Protomux.from(stream)

    this._channel = this._mux.createChannel({
      protocol: 'blind-relay',
      id,
      handshake: handshake ? handshakeEncoding || c.raw : null,
      onopen: this._onopen.bind(this),
      onclose: this._onclose.bind(this),
      ondestroy: this._ondestroy.bind(this)
    })

    this._pair = this._channel.addMessage({
      encoding: m.pair,
      onmessage: this._onpair.bind(this)
    })

    this._unpair = this._channel.addMessage({
      encoding: m.unpair
    })

    this._ending = false
    this._destroyed = false
    this._error = null
    this._requests = new Map()

    this._channel.open(handshake)
  }

  get closed() {
    return this._channel.closed
  }

  get mux() {
    return this._mux
  }

  get stream() {
    return this._mux.stream
  }

  get requests() {
    return this._requests.values()
  }

  _onopen() {
    this.emit('open')
  }

  _onclose() {
    this._ending = Promise.resolve()

    const err = this._error || errors.CHANNEL_CLOSED()

    for (const request of this._requests.values()) {
      request.destroy(err)
    }

    this._requests.clear()

    this.constructor._clients.delete(this.stream)

    this.emit('close')
  }

  _ondestroy() {
    this._destroyed = true
    this.emit('destroy')
  }

  _onpair({ isInitiator, token, id: remoteId }) {
    const request = this._requests.get(token.toString('hex'))

    if (request === undefined || request.isInitiator !== isInitiator) return

    request.push(remoteId)
    request.push(null)

    this.emit('pair', request.isInitiator, request.token, request.stream, remoteId)
  }

  pair(isInitiator, token, stream) {
    if (this._destroyed) throw errors.CHANNEL_DESTROYED()

    const keyString = token.toString('hex')

    if (this._requests.has(keyString)) throw errors.ALREADY_PAIRING()

    const request = new BlindRelayRequest(this, isInitiator, token, stream)

    this._requests.set(keyString, request)

    return request
  }

  unpair(token) {
    if (this._destroyed) throw errors.CHANNEL_DESTROYED()

    const request = this._requests.get(token.toString('hex'))

    if (request) request.destroy(errors.PAIRING_CANCELLED())

    this._unpair.send({ token })
  }

  cork() {
    this._channel.cork()
  }

  uncork() {
    this._channel.uncork()
  }

  async end() {
    if (this._ending) return this._ending

    this._ending = EventEmitter.once(this, 'close')
    this._endMaybe()

    return this._ending
  }

  _endMaybe() {
    if (this._ending && this._requests.size === 0) {
      this._channel.close()
    }
  }

  destroy(err) {
    if (this._destroyed) return
    this._destroyed = true

    this._error = err || errors.CHANNEL_DESTROYED()
    this._channel.close()
  }
}

class BlindRelayRequest extends Readable {
  constructor(client, isInitiator, token, stream) {
    super()

    this.client = client
    this.isInitiator = isInitiator
    this.token = token
    this.stream = stream
  }

  _open(cb) {
    if (this.client._destroyed) return cb(errors.CHANNEL_DESTROYED())

    this.client._pair.send({
      isInitiator: this.isInitiator,
      token: this.token,
      id: this.stream.id,
      seq: 0
    })

    cb(null)
  }

  _destroy(cb) {
    this.client._requests.delete(this.token.toString('hex'))

    cb(null)

    this.client._endMaybe()
  }
}

exports.token = function token(buf = b4a.allocUnsafe(32)) {
  sodium.randombytes_buf(buf)
  return buf
}

function noop() {}

function unlink(link) {
  const remote = link.remote

  link.remote = null

  if (remote && remote.remote === link) {
    remote.remote = null
  }
}

function createStats() {
  const stats = {
    sessions: {
      accepted: 0,
      opened: 0,
      closed: 0,
      get active() {
        return this.accepted - this.closed
      }
    },
    pairings: {
      requested: 0,
      matched: 0,
      cancelled: 0,
      pending: 0,
      active: 0
    },
    streams: {
      opened: 0,
      closed: 0,
      errors: 0,
      get active() {
        return this.opened - this.closed
      }
    }
  }

  return stats
}

const m = (exports.messages = {})

const flags = bitfield(7)

m.pair = {
  preencode(state, m) {
    flags.preencode(state)
    c.fixed32.preencode(state, m.token)
    c.uint.preencode(state, m.id)
    c.uint.preencode(state, m.seq)
  },
  encode(state, m) {
    flags.encode(state, bits.of(m.isInitiator))
    c.fixed32.encode(state, m.token)
    c.uint.encode(state, m.id)
    c.uint.encode(state, m.seq)
  },
  decode(state) {
    const [isInitiator] = bits.iterator(flags.decode(state))

    return {
      isInitiator,
      token: c.fixed32.decode(state),
      id: c.uint.decode(state),
      seq: c.uint.decode(state)
    }
  }
}

m.unpair = {
  preencode(state, m) {
    flags.preencode(state)
    c.fixed32.preencode(state, m.token)
  },
  encode(state, m) {
    flags.encode(state, bits.of())
    c.fixed32.encode(state, m.token)
  },
  decode(state) {
    flags.decode(state)

    return {
      token: c.fixed32.decode(state)
    }
  }
}
module.exports = class BlindRelayError extends Error {
  constructor(msg, code, fn = BlindRelayError) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'BlindRelayError'
  }

  static DUPLICATE_CHANNEL(msg = 'Duplicate channel') {
    return new BlindRelayError(msg, 'DUPLICATE_CHANNEL', BlindRelayError.DUPLICATE_CHANNEL)
  }

  static CHANNEL_CLOSED(msg = 'Channel closed') {
    return new BlindRelayError(msg, 'CHANNEL_CLOSED', BlindRelayError.CHANNEL_CLOSED)
  }

  static CHANNEL_DESTROYED(msg = 'Channel destroyed') {
    return new BlindRelayError(msg, 'CHANNEL_DESTROYED', BlindRelayError.CHANNEL_DESTROYED)
  }

  static ALREADY_PAIRING(msg = 'Already pairing') {
    return new BlindRelayError(msg, 'ALREADY_PAIRING', BlindRelayError.ALREADY_PAIRING)
  }

  static PAIRING_CANCELLED(msg = 'Pairing cancelled') {
    return new BlindRelayError(msg, 'PAIRING_CANCELLED', BlindRelayError.PAIRING_CANCELLED)
  }
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "blind-relay",
  "version": "1.6.1",
  "description": "Blind relay for UDX over Protomux channels",
  "main": "index.js",
  "files": [
    "index.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:bare",
    "test:bare": "brittle-bare --coverage test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/blind-relay.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/blind-relay/issues"
  },
  "homepage": "https://github.com/holepunchto/blind-relay#readme",
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "dependencies": {
    "b4a": "^1.6.4",
    "bare-events": "^2.2.0",
    "bits-to-bytes": "^1.3.0",
    "compact-encoding": "^3.0.0",
    "compact-encoding-bitfield": "^1.0.0",
    "protomux": "^3.5.1",
    "sodium-universal": "^5.0.0",
    "streamx": "^2.15.1"
  },
  "devDependencies": {
    "brittle": "^3.2.1",
    "hyperdht": "^6.6.1",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "udx-native": "^1.6.1"
  }
}
// https://ipinfo.io/bogon

const b4a = require('b4a')
const c = require('compact-encoding')

module.exports = exports = function isBogon (ip) {
  return isBogonIP(ensureBuffer(ip))
}

exports.isBogon = exports

exports.isPrivate = function isPrivate (ip) {
  return isPrivateIP(ensureBuffer(ip))
}

exports.isReserved = function isReserved (ip) {
  return isReservedIP(ensureBuffer(ip))
}

function isBogonIP (ip) {
  return isPrivateIP(ip) || isReservedIP(ip)
}

function isPrivateIP (ip) {
  return ip.byteLength === 4 ? isPrivateIPv4(ip) : false // IPv6 has no private IPs
}

function isPrivateIPv4 (ip) {
  return (
    // 10.0.0.0/8  Private-use networks
    (ip[0] === 10) ||
    // 100.64.0.0/10 Carrier-grade NAT
    (ip[0] === 100 && ip[1] >= 64 && ip[1] <= 127) ||
    // 127.0.0.0/8 Loopback + Name collision occurrence (127.0.53.53)
    (ip[0] === 127) ||
    // 169.254.0.0/16  Link local
    (ip[0] === 169 && ip[1] === 254) ||
    // 172.16.0.0/12 Private-use networks
    (ip[0] === 172 && ip[1] >= 16 && ip[1] <= 31) ||
    // 192.168.0.0/16  Private-use networks
    (ip[0] === 192 && ip[1] === 168)
  )
}

function isReservedIP (ip) {
  return ip.byteLength === 4 ? isReservedIPv4(ip) : isReservedIPv6(ip)
}

function isReservedIPv4 (ip) {
  return (
    // 0.0.0.0/8 "This" network
    (ip[0] === 0) ||
    // 192.0.0.0/24  IETF protocol assignments
    (ip[0] === 192 && ip[1] === 0 && ip[2] === 0) ||
    // 192.0.2.0/24  TEST-NET-1
    (ip[0] === 192 && ip[1] === 0 && ip[2] === 2) ||
    // 198.18.0.0/15 Network interconnect device benchmark testing
    (ip[0] === 198 && ip[1] >= 18 && ip[1] <= 19) ||
    // 198.51.100.0/24 TEST-NET-2
    (ip[0] === 198 && ip[1] === 51 && ip[2] === 100) ||
    // 203.0.113.0/24  TEST-NET-3
    (ip[0] === 203 && ip[1] === 0 && ip[2] === 113) ||
    // 224.0.0.0/4 Multicast
    (ip[0] >= 224 && ip[0] <= 239) ||
    // 240.0.0.0/4 Reserved for future use
    (ip[0] >= 240) ||
    // 255.255.255.255/32
    (ip[0] === 255 && ip[1] === 255 && ip[2] === 255 && ip[3] === 255)
  )
}

function isReservedIPv6 (ip) {
  return (
    // ::/128 Node-scope unicast unspecified address
    // ::1/128 Node-scope unicast loopback address
    (
      ip[0] === 0 && ip[1] === 0 && ip[2] === 0 && ip[3] === 0 && ip[4] === 0 &&
      ip[5] === 0 && ip[6] === 0 && ip[7] === 0 && ip[8] === 0 && ip[9] === 0 &&
      ip[10] === 0 && ip[11] === 0 && ip[12] === 0 && ip[13] === 0 && ip[14] === 0 &&
      ip[15] <= 1
    ) ||
    // ::ffff:0:0/96 IPv4-mapped addresses
    // ::/96 IPv4-compatible addresses
    (
      ip[0] === 0 && ip[1] === 0 && ip[2] === 0 && ip[3] === 0 && ip[4] === 0 &&
      ip[5] === 0 && ip[6] === 0 && ip[7] === 0 && ip[8] === 0 && ip[9] === 0 &&
      (ip[10] === 0 || ip[10] === 0xff) &&
      (ip[11] === 0 || ip[11] === 0xff)
    ) ||
    // 100::/64 Remotely triggered black hole addresses
    (ip[0] === 0x01 && ip[1] === 0 && ip[2] === 0 && ip[3] === 0 && ip[4] === 0 && ip[5] === 0 && ip[6] === 0 && ip[7] === 0) ||
    // 2001:10::/28 Overlay routable cryptographic hash identifiers (ORCHID)
    (ip[0] === 0x20 && ip[1] === 0x01 && ip[2] === 0 && ip[3] >= 0x10 && ip[3] <= 0x1f) ||
    // 2001:20::/28 Overlay routable cryptographic hash identifiers version 2 (ORCHIDv2)
    (ip[0] === 0x20 && ip[1] === 0x01 && ip[2] === 0 && ip[3] >= 0x20 && ip[3] <= 0x2f) ||
    // 2001:db8::/32 Documentation prefix
    (ip[0] === 0x20 && ip[1] === 0x01 && ip[2] === 0x0d && ip[3] === 0xb8) ||
    // fc00::/7 Unique local addresses (ULA)
    (ip[0] >= 0xfc && ip[0] <= 0xfd) ||
    // fe80::/10 Link-local unicast
    (ip[0] === 0xfe && ip[1] >= 0x80 && ip[1] <= 0xbf) ||
    // ff00::/8 Multicast
    (ip[0] === 0xff)
  )
}

const state = c.state(0, 0, b4a.allocUnsafe(1 /* family */ + 16))

function ensureBuffer (ip) {
  if (b4a.isBuffer(ip)) return ip

  c.ip.preencode(state, ip)
  c.ip.encode(state, ip)

  const buffer = state.buffer.subarray(1 /* family */, state.end)

  state.start = 0
  state.end = 0

  return buffer
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "bogon",
  "version": "1.3.0",
  "description": "Check if an IP is a bogon",
  "main": "index.js",
  "scripts": {
    "test": "standard && brittle test.mjs"
  },
  "dependencies": {
    "compact-encoding": "^3.0.0",
    "compact-encoding-net": "^1.2.0"
  },
  "devDependencies": {
    "brittle": "^3.0.4",
    "nanobench": "^2.1.1",
    "standard": "^17.0.0"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/bogon.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/bogon/issues"
  },
  "homepage": "https://github.com/mafintosh/bogon"
}
const c = require('compact-encoding')

module.exports = function bitfield(length) {
  if (length > 64) {
    throw new RangeError('Bitfield cannot be larger than 64 bits')
  }

  let byteLength
  if (length < 8) byteLength = 1
  else if (length <= 16) byteLength = 2
  else if (length <= 32) byteLength = 4
  else byteLength = 8

  return {
    preencode(state) {
      state.end++ // Length byte, used for data when byteLength === 1

      if (byteLength === 1);
      else if (byteLength === 2) c.uint16.preencode(state)
      else if (byteLength === 4) c.uint32.preencode(state)
      else c.uint64.preencode(state)
    },

    encode(state, b) {
      if (byteLength === 1);
      else if (byteLength === 2) c.uint8.encode(state, 0xfd)
      else if (byteLength === 4) c.uint8.encode(state, 0xfe)
      else c.uint8.encode(state, 0xff)

      if (typeof b === 'number') {
        if (byteLength === 1) c.uint8.encode(state, b)
        else if (byteLength === 2) c.uint16.encode(state, b)
        else if (byteLength === 4) c.uint32.encode(state, b)
        else c.uint64.encode(state, b)
      } else {
        state.buffer.set(b, state.start)

        if (b.byteLength < byteLength) {
          // Zero-fill the rest of the byte length.
          state.buffer.fill(
            0,
            state.start + b.byteLength,
            state.start + byteLength
          )
        }

        state.start += byteLength
      }
    },

    decode(state) {
      const byte = state.buffer[state.start]

      let byteLength
      if (byte <= 0xfc) byteLength = 1
      else if (byte === 0xfd) byteLength = 2
      else if (byte === 0xfe) byteLength = 4
      else byteLength = 8

      if (byteLength > 1) state.start++ // Skip the length byte

      if (state.end - state.start < byteLength) throw new Error('Out of bounds')

      const b = state.buffer.subarray(state.start, (state.start += byteLength))

      return length <= 8 ? b.subarray(0, 1) : b
    }
  }
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "compact-encoding-bitfield",
  "version": "1.1.0",
  "description": "Compact codec for bitfields",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node --coverage test.mjs",
    "test:bare": "brittle-bare --coverage test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/compact-encoding/compact-encoding-bitfield.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/compact-encoding/compact-encoding-bitfield/issues"
  },
  "homepage": "https://github.com/compact-encoding/compact-encoding-bitfield#readme",
  "imports": {
    "util": {
      "bare": "bare-utils",
      "default": "util"
    }
  },
  "dependencies": {
    "compact-encoding": "^3.0.0"
  },
  "devDependencies": {
    "bare-utils": "^1.5.1",
    "brittle": "^3.1.0",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  }
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return uint24.decode(state) + 0x1000000 * uint32.decode(state)
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return uint32.decode(state) + 0x100000000 * uint32.decode(state)
  }
})

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "2.19.2",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    if (b.byteLength === 0) return null
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
module.exports = function debounce (worker, context = null) {
  debounced.running = null
  return debounced

  async function debounced () {
    if (debounced.running !== null) {
      try {
        await debounced.running
      } catch (_) {
        // ignore - do not fail on old errors
      }
    }

    // another "thread" beat us to it, just piggy pack on that one
    if (debounced.running !== null) return debounced.running

    debounced.running = worker.call(context)

    try {
      return await debounced.running
    } finally {
      debounced.running = null
    }
  }
}
{
  "name": "debounceify",
  "version": "1.1.0",
  "description": "Tiny async debouncer",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^16.0.3",
    "tape": "^5.1.1"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/debounceify.git"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/debounceify/issues"
  },
  "homepage": "https://github.com/mafintosh/debounceify"
}
const { EventEmitter } = require('events')
const Table = require('kademlia-routing-table')
const TOS = require('time-ordered-set')
const UDX = require('udx-native')
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const NatSampler = require('nat-sampler')
const b4a = require('b4a')
const NetworkHealth = require('./lib/health')
const IO = require('./lib/io')
const Query = require('./lib/query')
const Session = require('./lib/session')
const peer = require('./lib/peer')
const { UNKNOWN_COMMAND, INVALID_TOKEN } = require('./lib/errors')
const { PING, PING_NAT, FIND_NODE, DOWN_HINT, DELAYED_PING } = require('./lib/commands')

const TMP = b4a.allocUnsafe(32)
const TICK_INTERVAL = 5000
const SLEEPING_INTERVAL = 3 * TICK_INTERVAL
const STABLE_TICKS = 240 // if nothing major bad happens in ~20mins we can consider this node stable (if nat is friendly)
const MORE_STABLE_TICKS = 3 * STABLE_TICKS
const REFRESH_TICKS = 60 // refresh every ~5min when idle
const RECENT_NODE = 12 // we've heard from a node less than 1min ago
const OLD_NODE = 360 // if an node has been around more than 30 min we consider it old

const DEFAULTS = {
  concurrency: 10,
  maxWindow: IO.DEFAULT_MAX_WINDOW,
  maxPingDelay: 10_000
}

class DHT extends EventEmitter {
  constructor(opts = {}) {
    super()

    this.bootstrapNodes = opts.bootstrap === false ? [] : (opts.bootstrap || []).map(parseNode)
    this.table = new Table(randomBytes(32))
    this.nodes = new TOS()
    this.udx = opts.udx || new UDX()
    this.io = new IO(this.table, this.udx, {
      ...opts,
      onrequest: this._onrequest.bind(this),
      onresponse: this._onresponse.bind(this),
      ontimeout: this._ontimeout.bind(this)
    })
    this.health = new NetworkHealth(this)

    this.concurrency = opts.concurrency || DEFAULTS.concurrency
    this.maxPingDelay = opts.maxPingDelay || DEFAULTS.maxPingDelay
    this.bootstrapped = false
    this.ephemeral = true
    this.firewalled = this.io.firewalled
    this.adaptive = typeof opts.ephemeral !== 'boolean' && opts.adaptive !== false
    this.destroyed = false
    this.suspended = false
    this.online = true
    this.degraded = false
    this.stats = {
      queries: { active: 0, total: 0 },
      requests: this.io.stats.requests,
      commands: {
        ping: this.io.stats.commands[PING],
        pingNat: this.io.stats.commands[PING_NAT],
        findNode: this.io.stats.commands[FIND_NODE],
        downHint: this.io.stats.commands[DOWN_HINT]
      }
    }

    this._nat = new NatSampler()
    this._quickFirewall = opts.quickFirewall !== false
    this._forcePersistent = opts.ephemeral === false
    this._repinging = 0
    this._checks = 0
    this._tick = randomOffset(100) // make sure to random offset all the network ticks
    this._refreshTicks = randomOffset(REFRESH_TICKS)
    this._stableTicks = this.adaptive ? STABLE_TICKS : 0
    this._tickInterval = setInterval(this._ontick.bind(this), TICK_INTERVAL)
    this._lastTick = Date.now()
    this._lastHost = null
    this._filterNode = opts.filterNode || opts.addNode || null // opts.addNode is deprecating, use opts.filterNode instead
    this._onrow = (row) => row.on('full', (node) => this._onfullrow(node, row))
    this._nonePersistentSamples = []
    this._bootstrapping = this._bootstrap()
    this._bootstrapping.catch(noop)
    this._sendDownHints = opts.sendDownHints !== false
    this._downHintsRateLimit =
      opts.downHintsRateLimit !== undefined ? opts.downHintsRateLimit : 10 * 5
    this._downHintsSentPerTick = 0
    this._pendingTimers = new Set()

    this.table.on('row', this._onrow)

    this.io.networkInterfaces.on('change', (interfaces) => this._onnetworkchange(interfaces))

    if (opts.nodes) {
      for (let i = opts.nodes.length - 1; i >= 0; i--) {
        this.addNode(opts.nodes[i])
      }
    }
  }

  static DEFAULTS = DEFAULTS

  static bootstrapper(port, host, opts) {
    if (!port) throw new Error('Port is required')
    if (!host) throw new Error('Host is required')
    if (host === '0.0.0.0' || host === '::') throw new Error('Invalid host')
    if (!UDX.isIPv4(host)) throw new Error('Host must be a IPv4 address')

    const dht = new this({
      port,
      ephemeral: false,
      firewalled: false,
      anyPort: false,
      bootstrap: [],
      ...opts
    })
    dht._nat.add(host, port)
    return dht
  }

  get id() {
    return this.ephemeral ? null : this.table.id
  }

  get host() {
    return this._nat.host
  }

  get port() {
    return this._nat.port
  }

  get randomized() {
    return this._nat.host !== null && this._nat.port === 0
  }

  get socket() {
    return this.firewalled ? this.io.clientSocket : this.io.serverSocket
  }

  get config() {
    return {
      concurrency: this.concurrency,
      maxWindow: this.io.congestion._maxWindow,
      randomPunchInterval: this._randomPunchInterval,
      connectionKeepAlive: this.connectionKeepAlive,
      sendDownHints: this._sendDownHints,
      downHintsRateLimit: this._downHintsRateLimit
    }
  }

  onmessage(socket, buf, rinfo) {
    if (buf.byteLength > 1) this.io.onmessage(socket, buf, rinfo)
  }

  bind() {
    return this.io.bind()
  }

  async suspend({ log = noop } = {}) {
    log('Suspending waiting for io bind...')
    await this.io.bind()
    log('Done, continuing')
    if (this.suspended || this.destroyed) return
    this.suspended = true
    clearInterval(this._tickInterval)
    log('Done, suspending io')
    await this.io.suspend({ log })
    log('Done, dht suspended')
    this.emit('suspend')
  }

  async resume({ log = noop } = {}) {
    if (!this.suspended || this.destroyed) return
    this.suspended = false
    this._tickInterval = setInterval(this._ontick.bind(this), TICK_INTERVAL)
    this._onwakeup()
    log('Resuming io')
    await this.io.resume()
    log('Done, dht resumed')
    this.io.networkInterfaces.on('change', (interfaces) => this._onnetworkchange(interfaces))
    this.refresh()
    this.emit('resume')
  }

  address() {
    const socket = this.socket
    return socket ? socket.address() : null
  }

  localAddress() {
    if (!this.io.serverSocket) return null

    return {
      host: localIP(this.udx),
      port: this.io.serverSocket.address().port
    }
  }

  remoteAddress() {
    if (!this.host) return null
    if (!this.port) return null
    if (this.firewalled) return null
    if (!this.io.serverSocket) return null

    const port = this.io.serverSocket.address().port
    if (port !== this.port) return null

    return {
      host: this.host,
      port
    }
  }

  addNode({ host, port }) {
    this._addNode({
      id: peer.id(host, port),
      port,
      host,
      token: null,
      to: null,
      sampled: 0,
      added: this._tick,
      pinged: 0,
      seen: 0,
      downHints: 0,
      prev: null,
      next: null
    })
  }

  toArray(opts) {
    const limit = opts && opts.limit
    if (limit === 0) return []
    return this.nodes.toArray({ limit, reverse: true }).map(({ host, port }) => ({ host, port }))
  }

  async fullyBootstrapped() {
    return this._bootstrapping
  }

  ready() {
    // Deprecating, use fullyBootstrapped instead (removed on next major)
    return this.fullyBootstrapped()
  }

  findNode(target, opts) {
    if (this.destroyed) throw new Error('Node destroyed')
    this._refreshTicks = REFRESH_TICKS
    return new Query(this, target, true, FIND_NODE, null, opts)
  }

  query({ target, command, value }, opts) {
    if (this.destroyed) throw new Error('Node destroyed')
    this._refreshTicks = REFRESH_TICKS
    return new Query(this, target, false, command, value || null, opts)
  }

  ping({ host, port }, opts) {
    let value = null

    if (opts && opts.size && opts.size > 0) value = b4a.alloc(opts.size)

    const req = this.io.createRequest(
      { id: null, host, port },
      null,
      true,
      PING,
      null,
      value,
      (opts && opts.session) || null,
      opts && opts.ttl
    )
    return this._requestToPromise(req, opts)
  }

  delayedPing({ host, port }, delayMs, opts) {
    if (delayMs > this.maxPingDelay) {
      throw new Error(`Delay exceeds max delay: ${this.maxPingDelay}ms`)
    }

    const value = b4a.allocUnsafe(4)
    c.uint32.encode({ start: 0, end: 4, buffer: value }, delayMs)

    const req = this.io.createRequest(
      { id: null, host, port },
      null,
      true,
      DELAYED_PING,
      null,
      value,
      (opts && opts.session) || null,
      opts && opts.ttl
    )
    // add 1 second to the timeout to account for network overhead
    req.timeout = delayMs + 1_000
    return this._requestToPromise(req, opts)
  }

  async rttStats() {
    const stats = {
      successes: 0,
      errors: 0,
      responses: {
        avgRtt: 0,
        errors: 0,
        avgCloserNodes: 0
      },
      closestReplies: {
        avgRtt: 0,
        errors: 0,
        avgCloserNodes: 0
      }
    }

    if (this.nodes.latest) {
      const q = this.findNode(this.nodes.latest.id)

      let responseCount = 0
      let closestCount = 0

      for await (const msg of q) {
        stats.responses.avgRtt += msg.rtt
        stats.responses.errors += msg.error
        stats.responses.avgCloserNodes += msg.closerNodes?.length || 0
        responseCount++
      }
      stats.responses.avgRtt /= responseCount
      stats.responses.avgCloserNodes /= responseCount

      for await (const msg of q.closestReplies) {
        stats.closestReplies.avgRtt += msg.rtt
        stats.closestReplies.errors += msg.error
        stats.closestReplies.avgCloserNodes += msg.closerNodes?.length || 0
        closestCount++
      }
      stats.closestReplies.avgRtt /= closestCount
      stats.closestReplies.avgCloserNodes /= closestCount

      stats.successes = q.successes
      stats.errors = q.errors
    }

    return stats
  }

  request({ token = null, command, target = null, value = null }, { host, port }, opts) {
    const req = this.io.createRequest(
      { id: null, host, port },
      token,
      false,
      command,
      target,
      value,
      (opts && opts.session) || null,
      opts && opts.ttl
    )
    return this._requestToPromise(req, opts)
  }

  session() {
    return new Session(this)
  }

  _requestToPromise(req, opts) {
    if (req === null) return Promise.reject(new Error('Node destroyed'))

    if (opts && opts.socket) req.socket = opts.socket
    if (opts && opts.retry === false) req.retries = 0

    return new Promise((resolve, reject) => {
      req.onresponse = resolve
      req.onerror = reject
      req.send()
    })
  }

  async _bootstrap() {
    const self = this

    await Promise.resolve() // wait a tick, so apis can be used from the outside
    await this.io.bind()

    this.emit('listening')

    // TODO: some papers describe more advanced ways of bootstrapping - we should prob look into that

    let first = this.firewalled && this._quickFirewall && !this._forcePersistent
    let testNat = false

    const onlyFirewall = !this._forcePersistent

    for (let i = 0; i < 2; i++) {
      await this._backgroundQuery(this.table.id).on('data', ondata).finished()

      if (this.bootstrapped || (!testNat && !this._forcePersistent)) break
      if (!(await this._updateNetworkState(onlyFirewall))) break
    }

    if (this.bootstrapped) return
    this.bootstrapped = true

    this.emit('ready')

    function ondata(data) {
      // Simple QUICK nat heuristic.
      // If we get ONE positive nat ping before the bootstrap query finishes
      // then we always to a nat test, no matter if we are adaptive...
      // This should be expanded in the future to try more than one node etc, not always hit the first etc
      // If this fails, then nbd, as the onstable hook will pick it up later.

      if (!first) return
      first = false

      const value = b4a.allocUnsafe(2)
      c.uint16.encode({ start: 0, end: 2, buffer: value }, self.io.serverSocket.address().port)

      self._request(
        data.from,
        false,
        true,
        PING_NAT,
        null,
        value,
        null,
        () => {
          testNat = true
        },
        noop
      )
    }
  }

  refresh() {
    const node = this.table.random()
    this._backgroundQuery(node ? node.id : this.table.id).on('error', noop)
  }

  async destroy() {
    const emitClose = !this.destroyed
    this.destroyed = true
    clearInterval(this._tickInterval)
    for (const timer of this._pendingTimers) {
      clearTimeout(timer)
    }
    await this.io.destroy()
    if (emitClose) this.emit('close')
  }

  _request(to, force, internal, command, target, value, session, onresponse, onerror) {
    if (internal && !this._sendDownHints && command === DOWN_HINT) return null
    const req = this.io.createRequest(to, null, internal, command, target, value, session)
    if (req === null) return null

    req.onresponse = onresponse
    req.onerror = onerror
    req.send(force)

    return req
  }

  _natAdd(host, port) {
    const prevHost = this._nat.host
    const prevPort = this._nat.port

    this._nat.add(host, port)

    if (prevHost === this._nat.host && prevPort === this._nat.port) return

    this.emit('nat-update', this._nat.host, this._nat.port)
  }

  // we don't check that this is a bootstrap node but we limit the sample size to very few nodes, so fine
  _sampleBootstrapMaybe(from, to) {
    if (this._nonePersistentSamples.length >= Math.max(1, this.bootstrapNodes.length)) return
    const id = from.host + ':' + from.port
    if (this._nonePersistentSamples.indexOf(id) > -1) return
    this._nonePersistentSamples.push(id)
    this._natAdd(to.host, to.port)
  }

  _addNodeFromNetwork(sample, from, to) {
    if (this._filterNode !== null && !this._filterNode(from)) {
      return
    }

    if (from.id === null) {
      this._sampleBootstrapMaybe(from, to)
      return
    }

    const oldNode = this.table.get(from.id)

    // refresh it, if we've seen this before
    if (oldNode) {
      if (sample && (oldNode.sampled === 0 || this._tick - oldNode.sampled >= OLD_NODE)) {
        oldNode.to = to
        oldNode.sampled = this._tick
        this._natAdd(to.host, to.port)
      }

      oldNode.pinged = oldNode.seen = this._tick
      this.nodes.add(oldNode)
      return
    }

    this._addNode({
      id: from.id,
      port: from.port,
      host: from.host,
      to,
      sampled: 0,
      added: this._tick,
      pinged: this._tick, // last time we interacted with them
      seen: this._tick, // last time we heard from them
      downHints: 0,
      prev: null,
      next: null
    })
  }

  _addNode(node) {
    if (this.nodes.has(node) || b4a.equals(node.id, this.table.id)) return

    node.added = node.pinged = node.seen = this._tick

    if (!this.table.add(node)) return
    this.nodes.add(node)

    if (node.to && node.sampled === 0) {
      node.sampled = this._tick
      this._natAdd(node.to.host, node.to.port)
    }

    this.emit('add-node', node)
  }

  _removeStaleNode(node, lastSeen) {
    if (node.seen <= lastSeen) this._removeNode(node)
  }

  _removeNode(node) {
    if (!this.nodes.has(node)) return

    this.table.remove(node.id)
    this.nodes.remove(node)

    this.emit('remove-node', node)
  }

  _onwakeup() {
    this._tick += 2 * OLD_NODE // bump the tick enough that everything appears old.
    this._tick += 8 - (this._tick & 7) - 2 // triggers a series of pings in two ticks
    this._stableTicks = MORE_STABLE_TICKS
    this._refreshTicks = 1 // triggers a refresh next tick (allow network time to wake up also)
    this._lastHost = null // clear network cache check
    this.health.reset()

    if (this.adaptive) {
      // TODO: re-enable this as soon as we find out why this is over triggering in some edge cases
      // this.firewalled = true
      // this.io.firewalled = true

      if (!this.ephemeral) {
        this.ephemeral = true
        this.io.ephemeral = true
        this.emit('ephemeral')
      }
    }

    this.emit('wakeup')
  }

  _onfullrow(newNode, row) {
    if (!this.bootstrapped || this._repinging >= 3) return

    let oldest = null
    for (const node of row.nodes) {
      if (node.pinged === this._tick) continue
      if (
        oldest === null ||
        oldest.pinged > node.pinged ||
        (oldest.pinged === node.pinged && oldest.added > node.added)
      ) {
        oldest = node
      }
    }

    if (oldest === null) return
    if (this._tick - oldest.pinged < RECENT_NODE && this._tick - oldest.added > OLD_NODE) return

    this._repingAndSwap(newNode, oldest)
  }

  _onnetworkchange(interfaces) {
    this.emit('network-change', interfaces)
    this.emit('network-update')
  }

  _repingAndSwap(newNode, oldNode) {
    const self = this
    const lastSeen = oldNode.seen

    oldNode.pinged = this._tick

    this._repinging++
    this._request(
      { id: null, host: oldNode.host, port: oldNode.port },
      false,
      true,
      PING,
      null,
      null,
      null,
      onsuccess,
      onswap
    )

    function onsuccess(m) {
      if (oldNode.seen <= lastSeen) return onswap()
      self._repinging--
    }

    function onswap(e) {
      self._repinging--
      self._removeNode(oldNode)
      self._addNode(newNode)
    }
  }

  _onrequest(req, external) {
    if (req.from.id !== null) {
      this._addNodeFromNetwork(!external, req.from, req.to)
    }

    if (req.internal) {
      switch (req.command) {
        // standard keep alive call
        case PING: {
          req.sendReply(0, null, false, false)
          return
        }
        case DELAYED_PING: {
          this._ondelayedping(req)
          return
        }
        // check if the other side can receive a message to their other socket
        case PING_NAT: {
          if (req.value === null || req.value.byteLength < 2) return
          const port = c.uint16.decode({ start: 0, end: 2, buffer: req.value })
          if (port === 0) return
          req.from.port = port
          req.sendReply(0, null, false, false)
          return
        }
        // empty dht reply back
        case FIND_NODE: {
          if (!req.target) return
          req.sendReply(0, null, false, true)
          return
        }
        // "this is node you sent me is down" - let's try to ping it
        case DOWN_HINT: {
          if (req.value === null || req.value.byteLength < 6) return
          if (this._checks < 10) {
            sodium.crypto_generichash(TMP, req.value.subarray(0, 6))
            const node = this.table.get(TMP)
            if (node && (node.pinged < this._tick || node.downHints === 0)) {
              node.downHints++
              this._check(node)
            }
          }
          req.sendReply(0, null, false, false)
          return
        }
      }

      req.sendReply(UNKNOWN_COMMAND, null, false, req.target !== null)
      return
    }

    // ask the user to handle it or reply back with a bad command
    if (this.onrequest(req) === false) {
      req.sendReply(UNKNOWN_COMMAND, null, false, req.target !== null)
    }
  }

  onrequest(req) {
    return this.emit('request', req)
  }

  _ondelayedping(req) {
    if (req.value === null || req.value.byteLength < 4) return
    const delayMs = c.uint32.decode({ start: 0, end: 4, buffer: req.value })
    if (delayMs > this.maxPingDelay) return
    const timer = setTimeout(() => {
      if (this.destroyed) return
      this._pendingTimers.delete(timer)
      req.sendReply(0, null, false, false)
    }, delayMs)
    this._pendingTimers.add(timer)
  }

  _onresponse(res, external) {
    this._addNodeFromNetwork(!external, res.from, res.to)
  }

  _ontimeout(req) {
    if (!req.to.id) return
    const node = this.table.get(req.to.id)
    if (node) this._removeNode(node)
  }

  _pingSome() {
    let cnt = this.io.inflight.length > 2 ? 3 : 5
    let oldest = this.nodes.oldest

    // tiny dht, pinged the bootstrap again
    if (!oldest) {
      this.refresh()
      return
    }

    // we've recently pinged the oldest one, so only trigger a couple of repings
    if (this._tick - oldest.pinged < RECENT_NODE) {
      cnt = 2
    }

    while (cnt--) {
      if (!oldest || this._tick === oldest.pinged) continue
      this._check(oldest)
      oldest = oldest.next
    }
  }

  _check(node) {
    node.pinged = this._tick

    const lastSeen = node.seen
    const onresponse = () => {
      this._checks--
      this._removeStaleNode(node, lastSeen)
    }
    const onerror = () => {
      this._checks--
      this._removeNode(node)
    }

    this._checks++
    this._request(
      { id: null, host: node.host, port: node.port },
      false,
      true,
      PING,
      null,
      null,
      null,
      onresponse,
      onerror
    )
  }

  _ontick() {
    const time = Date.now()

    if (time - this._lastTick > SLEEPING_INTERVAL && this.suspended === false) {
      this._onwakeup()
    } else {
      this._tick++
    }

    this._lastTick = time

    if (!this.bootstrapped || this.suspended) return

    if (this.adaptive && this.ephemeral && --this._stableTicks <= 0) {
      if (this._lastHost === this._nat.host) {
        // do not recheck the same network...
        this._stableTicks = MORE_STABLE_TICKS
      } else {
        this._updateNetworkState() // the promise returned here never fails so just ignore it
      }
    }

    if ((this._tick & 7) === 0) {
      this._pingSome()
    }

    if (
      ((this._tick & 63) === 0 && this.nodes.length < this.table.k) ||
      --this._refreshTicks <= 0
    ) {
      this.refresh()
    }

    this._downHintsSentPerTick = 0
    this.health.update()
  }

  async _updateNetworkState(onlyFirewall = false) {
    if (!this.ephemeral) return false
    if (onlyFirewall && !this.firewalled) return false

    const { host, port } = this._nat

    if (!onlyFirewall) {
      // remember what host we checked and reset the counter
      this._stableTicks = MORE_STABLE_TICKS
      this._lastHost = host
    }

    // check if we have a consistent host and port
    if (host === null || port === 0) {
      return false
    }

    const natSampler = this.firewalled ? new NatSampler() : this._nat

    // ask remote nodes to ping us on our server socket to see if we have the port open
    const firewalled = this.firewalled && (await this._checkIfFirewalled(natSampler))
    if (firewalled) return false

    this.firewalled = this.io.firewalled = false

    // incase it's called in parallel for some reason, or if our nat status somehow changed
    if (!this.ephemeral || host !== this._nat.host || port !== this._nat.port) return false
    // if the firewall probe returned a different host / non consistent port, bail as well
    if (natSampler.host !== host || natSampler.port === 0) return false

    const id = peer.id(natSampler.host, natSampler.port)

    if (!onlyFirewall) {
      this.ephemeral = this.io.ephemeral = false
    }

    if (natSampler !== this._nat) {
      const prevHost = this._nat.host
      const prevPort = this._nat.port

      this._nonePersistentSamples = []
      this._nat = natSampler

      if (prevHost !== this._nat.host || prevPort !== this._nat.port) {
        this.emit('nat-update', this._nat.host, this._nat.port)
      }
    }

    // TODO: we should make this a bit more defensive in terms of using more
    // resources to make sure that the new routing table contains as many alive nodes
    // as possible, vs blindly copying them over...

    // all good! copy over the old routing table to the new one
    if (!b4a.equals(this.table.id, id)) {
      const nodes = this.table.toArray()

      this.table = this.io.table = new Table(id)

      for (const node of nodes) {
        if (b4a.equals(node.id, id)) continue
        if (!this.table.add(node)) this.nodes.remove(node)
      }

      this.table.on('row', this._onrow)

      // we need to rebootstrap/refresh since we updated our id
      if (this.bootstrapped) this.refresh()
    }

    if (!this.ephemeral) {
      this.emit('persistent')
    }

    return true
  }

  async *_resolveBootstrapNodes() {
    for (let { host, port } of this.bootstrapNodes) {
      let doLookup = false

      if (host.indexOf('@') === -1) {
        doLookup = true
      } else {
        const [suggestedIP, fallbackHost] = host.split('@')
        try {
          await this.ping({ host: suggestedIP, port })
          host = suggestedIP
        } catch {
          host = fallbackHost
          doLookup = true
        }
      }

      if (doLookup) {
        try {
          host = UDX.isIPv4(host) ? host : (await this.udx.lookup(host, { family: 4 })).host
        } catch {
          continue
        }
      }

      yield {
        id: peer.id(host, port),
        host,
        port
      }
    }
  }

  async _addBootstrapNodes(nodes) {
    for await (const node of this._resolveBootstrapNodes()) {
      nodes.push(node)
    }
  }

  async _checkIfFirewalled(natSampler = new NatSampler()) {
    const nodes = []
    for (let node = this.nodes.latest; node && nodes.length < 5; node = node.prev) {
      nodes.push(node)
    }

    if (nodes.length < 5) await this._addBootstrapNodes(nodes)
    // if no nodes are available, including bootstrappers - bail
    if (nodes.length === 0) return true

    const hosts = new Set()
    const value = b4a.allocUnsafe(2)

    c.uint16.encode({ start: 0, end: 2, buffer: value }, this.io.serverSocket.address().port)

    // double check they actually came on the server socket...
    this.io.serverSocket.on('message', onmessage)

    const pongs = await requestAll(this, true, PING_NAT, value, nodes)

    let count = 0
    for (const res of pongs) {
      if (hosts.has(res.from.host)) {
        count++
        natSampler.add(res.to.host, res.to.port)
      }
    }

    this.io.serverSocket.removeListener('message', onmessage)

    // if we got no or very few replies, consider it a fluke
    if (count < (nodes.length >= 5 ? 3 : 1)) return true

    // check that the server socket has the same ip as the client socket
    if (natSampler.host === null || this._nat.host !== natSampler.host) return true

    // check that the local port of the server socket is the same as the remote port
    // TODO: we might want a flag to opt out of this heuristic for specific remapped port servers
    if (natSampler.port === 0 || natSampler.port !== this.io.serverSocket.address().port) {
      return true
    }

    return false

    function onmessage(_, { host }) {
      hosts.add(host)
    }
  }

  _backgroundQuery(target) {
    this._refreshTicks = REFRESH_TICKS

    const backgroundCon = Math.min(this.concurrency, Math.max(2, (this.concurrency / 8) | 0))
    const q = new Query(this, target, true, FIND_NODE, null, {
      concurrency: backgroundCon
    })

    q.on('data', () => {
      // yield to other traffic
      q.concurrency = this.io.inflight.length < 3 ? this.concurrency : backgroundCon
    })

    return q
  }

  // called by health
  _online() {
    if (this.online && !this.degraded) return
    this.online = true
    this.degraded = false
    this.emit('network-update')
  }

  // called by health
  _degraded() {
    if (this.degraded) return
    this.online = true
    this.degraded = true
    this.emit('network-update')
  }

  // called by health
  _offline() {
    if (!this.online) return
    this.online = false
    this.degraded = false
    this.emit('network-update')
  }
}

DHT.OK = 0
DHT.ERROR_UNKNOWN_COMMAND = UNKNOWN_COMMAND
DHT.ERROR_INVALID_TOKEN = INVALID_TOKEN

module.exports = DHT

function localIP(udx, family = 4) {
  let host = null

  for (const n of udx.networkInterfaces()) {
    if (n.family !== family || n.internal) continue

    // mac really likes en0, mb a better way but this shouldnt be bad anywhere so return now
    if (n.name === 'en0') return n.host

    // otherwise pick the first non internal host (let the loop continue in case we see en0)
    if (host === null) host = n.host
  }

  return host || (family === 4 ? '127.0.0.1' : '::1')
}

function parseNode(s) {
  if (typeof s === 'object') return s
  if (typeof s === 'number') return { host: '127.0.0.1', port: s }
  const [host, port] = s.split(':')
  if (!port) throw new Error('Bootstrap node format is host:port')

  return {
    host,
    port: Number(port)
  }
}

function randomBytes(n) {
  const b = b4a.alloc(n)
  sodium.randombytes_buf(b)
  return b
}

function randomOffset(n) {
  return n - ((Math.random() * 0.5 * n) | 0)
}

function requestAll(dht, internal, command, value, nodes) {
  let missing = nodes.length
  const replies = []

  return new Promise((resolve) => {
    for (const node of nodes) {
      const req = dht._request(
        node,
        false,
        internal,
        command,
        null,
        value,
        null,
        onsuccess,
        onerror
      )
      if (!req) return resolve(replies)
    }

    function onsuccess(res) {
      replies.push(res)
      if (--missing === 0) resolve(replies)
    }

    function onerror() {
      if (--missing === 0) resolve(replies)
    }
  })
}

function noop() {}
exports.PING = 0
exports.PING_NAT = 1
exports.FIND_NODE = 2
exports.DOWN_HINT = 3
exports.DELAYED_PING = 4
module.exports = class DHTError extends Error {
  constructor(msg, code, fn = DHTError) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'DHTError'
  }

  static UNKNOWN_COMMAND = 1
  static INVALID_TOKEN = 2

  static REQUEST_TIMEOUT(msg = 'Request timed out') {
    return new DHTError(msg, 'REQUEST_TIMEOUT', DHTError.REQUEST_TIMEOUT)
  }

  static REQUEST_DESTROYED(msg = 'Request destroyed') {
    return new DHTError(msg, 'REQUEST_DESTROYED', DHTError.REQUEST_DESTROYED)
  }

  static IO_SUSPENDED(msg = 'I/O suspended') {
    return new DHTError(msg, 'IO_SUSPENDED', DHTError.IO_SUSPENDED)
  }
}
const MAX_HEALTH_WINDOW = 4
const OFFLINE_THRESHOLD = 2
const IDLE_THRESHOLD = 4
const DEGRADED_TIMEOUT_RATE_THRESHOLD = 0.5

module.exports = class NetworkHealth {
  constructor(dht) {
    this._dht = dht
    this._window = []
    this._head = -1
    this._offlineTicks = 0
    this._degradedTicks = 0
    this._healthyTicks = 0
    this.online = true
    this.degraded = false
  }

  get oldest() {
    return this._window[this._tail]
  }

  get previous() {
    return this._window[(this._head - 1 + MAX_HEALTH_WINDOW) % MAX_HEALTH_WINDOW]
  }

  get newest() {
    return this._window[this._head]
  }

  get responses() {
    if (!this.newest || !this.previous) return 0
    return this.newest.responses - this.previous.responses
  }

  get timeouts() {
    if (!this.newest || !this.previous) return 0
    return this.newest.timeouts - this.previous.timeouts
  }

  get timeoutsRate() {
    if (this.timeouts === 0) return 0
    return this.timeouts / (this.responses + this.timeouts)
  }

  get cold() {
    return this._window.length < MAX_HEALTH_WINDOW
  }

  get idle() {
    return this.responses + this.timeouts < IDLE_THRESHOLD
  }

  get stats() {
    return {
      online: this.online,
      degraded: this.degraded,
      cold: this.cold,
      idle: this.idle,
      responses: this.responses,
      timeouts: this.timeouts,
      timeoutsRate: this.timeoutsRate
    }
  }

  get _tail() {
    return (this._head + 1) % MAX_HEALTH_WINDOW
  }

  reset() {
    this._window = []
    this._head = -1
    this._offlineTicks = 0
    this._degradedTicks = 0
    this._healthyTicks = 0
    this.online = true
    this.degraded = false
    this._dht._online()
  }

  update() {
    // update counters before dropping oldest
    if (this.oldest?.degraded) this._degradedTicks--
    else if (this.oldest?.degraded === false) this._healthyTicks--

    // move window
    this._head = this._tail
    this._window[this._head] = {
      responses: this._dht.stats.requests.responses,
      timeouts: this._dht.stats.requests.timeouts
    }

    // skip state changes
    if (this.cold || this.idle) return

    // update newest
    this.newest.offline = this.responses === 0
    this.newest.degraded =
      !this.newest.offline && this.timeoutsRate > DEGRADED_TIMEOUT_RATE_THRESHOLD

    // update counters
    if (this.newest.offline) this._offlineTicks++
    else {
      this._offlineTicks = 0
      if (this.newest.degraded) this._degradedTicks++
      else this._healthyTicks++
    }

    // check online/offline
    if (!this.newest.offline) this.online = true
    else if (this._offlineTicks >= OFFLINE_THRESHOLD) this.online = false

    // check degraded
    if (!this.online || this._healthyTicks === MAX_HEALTH_WINDOW) this.degraded = false
    else if (this._degradedTicks === MAX_HEALTH_WINDOW) this.degraded = true

    // fire events
    if (this.online && !this.degraded) this._dht._online()
    else if (this.degraded) this._dht._degraded()
    else this._dht._offline()
  }
}
const FIFO = require('fast-fifo')
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const b4a = require('b4a')
const AdaptiveTimeout = require('adaptive-timeout')
const peer = require('./peer')
const { INVALID_TOKEN, REQUEST_TIMEOUT, REQUEST_DESTROYED, IO_SUSPENDED } = require('./errors')

const VERSION = 0b11
const RESPONSE_ID = (0b0001 << 4) | VERSION
const REQUEST_ID = (0b0000 << 4) | VERSION
const EMPTY_ARRAY = []
const MAX_WINDOW = 80

module.exports = class IO {
  constructor(
    table,
    udx,
    {
      maxWindow = MAX_WINDOW,
      port = 0,
      host = '0.0.0.0',
      anyPort = true,
      firewalled = true,
      onrequest,
      onresponse = noop,
      ontimeout = noop,
      adaptiveTimeout
    } = {}
  ) {
    this.table = table
    this.udx = udx
    this.inflight = []
    this.clientSocket = null
    this.serverSocket = null
    this.firewalled = firewalled !== false
    this.ephemeral = true
    this.congestion = new CongestionWindow(maxWindow)
    this.networkInterfaces = udx.watchNetworkInterfaces()
    this.suspended = false

    this.stats = {
      requests: {
        active: 0,
        total: 0,
        responses: 0,
        timeouts: 0,
        retries: 0
      },
      commands: [
        { tx: 0, rx: 0 }, // tx = transmitted, rx = received
        { tx: 0, rx: 0 },
        { tx: 0, rx: 0 },
        { tx: 0, rx: 0 }
      ]
    }

    this.onrequest = onrequest
    this.onresponse = onresponse
    this.ontimeout = ontimeout

    this._pending = new FIFO()
    this._rotateSecrets = 10
    this._tid = (Math.random() * 65536) | 0
    this._secrets = null
    this._drainInterval = null
    this._destroying = null
    this._binding = null

    // port can be a number or a range [start, to]
    this.portRange = port.length ? port : port === 0 ? [0, 0] : [port, port + 5]

    this._host = host
    this._anyPort = anyPort !== false
    this._boundServerPort = 0
    this._boundClientPort = 0

    this._adt = adaptiveTimeout ? new AdaptiveTimeout(adaptiveTimeout) : null
  }

  static DEFAULT_MAX_WINDOW = MAX_WINDOW

  onmessage(socket, buffer, { host, port }) {
    if (buffer.byteLength < 2 || !(port > 0 && port < 65536) || this.suspended === true) return

    const from = { id: null, host, port }
    const state = { start: 1, end: buffer.byteLength, buffer }
    const expectedSocket = this.firewalled ? this.clientSocket : this.serverSocket
    const external = socket !== expectedSocket

    if (buffer[0] === REQUEST_ID) {
      const req = Request.decode(this, socket, from, state)
      if (req === null) return
      if (
        req.token !== null &&
        !b4a.equals(req.token, this.token(req.from, 1)) &&
        !b4a.equals(req.token, this.token(req.from, 0))
      ) {
        req.error(INVALID_TOKEN, { token: true })
        return
      }
      this.onrequest(req, external)
      return
    }

    if (buffer[0] === RESPONSE_ID) {
      const res = decodeReply(from, state)
      if (res === null) return

      for (let i = 0; i < this.inflight.length; i++) {
        const req = this.inflight[i]
        if (req.tid !== res.tid) continue

        res.rtt = Date.now() - req._timestamp

        if (this._adt && req.sent <= 2) {
          this._adt.put(`${req.to.host}:${req.to.port}`, res.rtt)
        }

        if (i === this.inflight.length - 1) this.inflight.pop()
        else this.inflight[i] = this.inflight.pop()

        if (req.session) req.session._detach(req)

        // TODO: Auto retry here if errors.INVALID_TOKEN is returned?

        if (req._timeout) {
          clearTimeout(req._timeout)
          req._timeout = null
        }

        this.congestion.recv()

        if (req.internal && req.command < this.stats.commands.length) {
          this.stats.commands[req.command].rx++
        }

        this.stats.requests.active--
        this.stats.requests.responses++

        this.onresponse(res, external)
        req.onresponse(res, req)
        break
      }
    }
  }

  token(addr, i) {
    if (this._secrets === null) {
      const buf = b4a.alloc(64)
      this._secrets = [buf.subarray(0, 32), buf.subarray(32, 64)]
      sodium.randombytes_buf(this._secrets[0])
      sodium.randombytes_buf(this._secrets[1])
    }

    const token = b4a.allocUnsafe(32)
    sodium.crypto_generichash(token, b4a.from(addr.host), this._secrets[i])
    return token
  }

  async destroy() {
    if (this._destroying) return this._destroying
    this._destroying = this._destroy()
    return this._destroying
  }

  async _destroy() {
    // simplifies timing to await the bind here also, although it might be unneeded
    await this.bind()
    await this._clear(false)
  }

  async _clear(suspended) {
    if (this._drainInterval) {
      clearInterval(this._drainInterval)
      this._drainInterval = null
    }

    while (this.inflight.length) {
      const req = this.inflight.pop()
      if (req._timeout) clearTimeout(req._timeout)
      req._timeout = null
      req.destroyed = true

      if (req.session) req.session._detach(req)

      this.congestion.recv()
      this.stats.requests.active--

      req.onerror(suspended ? IO_SUSPENDED() : REQUEST_DESTROYED(), req)
    }

    await Promise.allSettled([this.serverSocket.close(), this.clientSocket.close()])

    this.networkInterfaces.destroy()
  }

  async suspend() {
    this.suspended = true
    await this._clear(true)

    this.congestion.clear()

    if (this._drainInterval) {
      clearInterval(this._drainInterval)
      this._drainInterval = null
    }
  }

  async _rebind(binding) {
    if (binding) await binding
    if (this._destroying) return this._destroying
    await this._bindSockets()
    this.networkInterfaces = this.udx.watchNetworkInterfaces()
  }

  resume() {
    this.suspended = false
    const binding = this._binding
    this._binding = this._rebind(binding)
    return this._binding
  }

  bind() {
    if (this._binding) return this._binding
    this._binding = this._bindSockets()
    return this._binding
  }

  async _bindSockets() {
    const serverSocket = this.udx.createSocket()

    const candidatePorts = []

    // Retrying previous port always has precedence
    if (this._boundServerPort) candidatePorts.push(this._boundServerPort)

    for (let i = this.portRange[0]; i < this.portRange[1]; i++) candidatePorts.push(i)

    for (const port of candidatePorts) {
      if (serverSocket.bound) break

      try {
        serverSocket.bind(port, this._host)
      } catch (err) {
        if (!this._anyPort) {
          await serverSocket.close()
          throw err
        }
      }
    }

    if (!serverSocket.bound) {
      try {
        serverSocket.bind(0, this._host)
      } catch (err) {
        await serverSocket.close()
        throw err
      }
    }

    const clientSocket = this.udx.createSocket()

    try {
      clientSocket.bind(this._boundClientPort || 0, this._host)
    } catch {
      try {
        clientSocket.bind(0, this._host)
      } catch (err) {
        await serverSocket.close()
        await clientSocket.close()
        throw err
      }
    }

    this._boundServerPort = serverSocket.address().port
    this._boundClientPort = clientSocket.address().port

    this.clientSocket = clientSocket
    this.serverSocket = serverSocket

    this.serverSocket.on('message', this.onmessage.bind(this, this.serverSocket))
    this.clientSocket.on('message', this.onmessage.bind(this, this.clientSocket))

    if (this._drainInterval === null) {
      this._drainInterval = setInterval(this._drain.bind(this), 750)
      if (this._drainInterval.unref) this._drainInterval.unref()
    }

    for (const req of this.inflight) {
      if (!req.socket) req.socket = this.firewalled ? this.clientSocket : this.serverSocket
      req.sent = 0
      req.send(false)
    }
  }

  _drain() {
    if (this._secrets !== null && --this._rotateSecrets === 0) {
      this._rotateSecrets = 10
      const tmp = this._secrets[0]
      this._secrets[0] = this._secrets[1]
      this._secrets[1] = tmp
      sodium.crypto_generichash(tmp, tmp)
    }

    this.congestion.drain()

    while (!this.congestion.isFull()) {
      const p = this._pending.shift()
      if (p === undefined) return
      p._sendNow()
    }
  }

  createRequest(to, token, internal, command, target, value, session, ttl) {
    if (this._destroying !== null) return null

    if (this._tid === 65536) this._tid = 0

    const tid = this._tid++
    const socket = this.firewalled ? this.clientSocket : this.serverSocket

    const req = new Request(
      this,
      socket,
      tid,
      null,
      to,
      token,
      internal,
      command,
      target,
      value,
      session,
      ttl || 0
    )
    this.inflight.push(req)
    if (session) session._attach(req)

    if (internal && command < this.stats.commands.length) {
      this.stats.commands[command].tx++
    }

    this.stats.requests.active++
    this.stats.requests.total++

    return req
  }
}

class Request {
  constructor(io, socket, tid, from, to, token, internal, command, target, value, session, ttl) {
    this.socket = socket
    this.tid = tid
    this.from = from
    this.to = to
    this.token = token
    this.command = command
    this.target = target
    this.value = value
    this.internal = internal
    this.session = session
    this.ttl = ttl
    this.index = -1
    this.sent = 0
    this.retries = 3
    this.destroyed = false
    this.timeout = 0

    this.oncycle = noop
    this.onerror = noop
    this.onresponse = noop

    this._buffer = null
    this._io = io
    this._timeout = null
    this._timestamp = Date.now()
  }

  static decode(io, socket, from, state) {
    try {
      const flags = c.uint.decode(state)
      const tid = c.uint16.decode(state)
      const to = peer.ipv4.decode(state)
      const id = flags & 1 ? c.fixed32.decode(state) : null
      const token = flags & 2 ? c.fixed32.decode(state) : null
      const internal = (flags & 4) !== 0
      const command = c.uint.decode(state)
      const target = flags & 8 ? c.fixed32.decode(state) : null
      const value = flags & 16 ? c.buffer.decode(state) : null

      if (id !== null) from.id = validateId(id, from)

      return new Request(
        io,
        socket,
        tid,
        from,
        to,
        token,
        internal,
        command,
        target,
        value,
        null,
        0
      )
    } catch {
      return null
    }
  }

  reply(value, opts = {}) {
    const socket = opts.socket || this.socket
    const to = opts.to || this.from
    this._sendReply(0, value || null, opts.token !== false, opts.closerNodes !== false, to, socket)
  }

  error(code, opts = {}) {
    const socket = opts.socket || this.socket
    const to = opts.to || this.from
    this._sendReply(code, null, opts.token === true, opts.closerNodes !== false, to, socket)
  }

  relay(value, to, opts) {
    const socket = (opts && opts.socket) || this.socket
    const buffer = this._encodeRequest(null, value, to, socket)
    socket.trySend(buffer, to.port, to.host, this.ttl)
  }

  send(force = false) {
    if (this.destroyed) return

    if (this.socket === null) return
    if (this._buffer === null) {
      this._buffer = this._encodeRequest(this.token, this.value, this.to, this.socket)
    }

    if (!force && this._io.congestion.isFull()) {
      this._io._pending.push(this)
      return
    }

    this._sendNow()
  }

  sendReply(error, value, token, hasCloserNodes) {
    this._sendReply(error, value, token, hasCloserNodes, this.from, this.socket, null)
  }

  _sendNow() {
    if (this.destroyed) return
    this.sent++
    this._io.congestion.send()
    this.socket.trySend(this._buffer, this.to.port, this.to.host, this.ttl)
    if (this._timeout) clearTimeout(this._timeout)
    const value =
      this.timeout || this._io._adt?.get(`${this.to.host}:${this.to.port}`, this.sent) || 1000
    this._timeout = setTimeout(oncycle, value, this)
  }

  destroy(err) {
    if (this.destroyed) return
    this.destroyed = true

    if (this._timeout) {
      clearTimeout(this._timeout)
      this._timeout = null
    }

    const i = this._io.inflight.indexOf(this)
    if (i === -1) return

    if (i === this._io.inflight.length - 1) this._io.inflight.pop()
    else this._io.inflight[i] = this._io.inflight.pop()

    if (this.session) this.session._detach(this)

    this._io.stats.requests.active--
    this._io.congestion.recv()

    this.onerror(err || REQUEST_DESTROYED(), this)
  }

  _sendReply(error, value, token, hasCloserNodes, from, socket) {
    if (socket === null || this.destroyed) return

    const id = this._io.ephemeral === false && socket === this._io.serverSocket
    const closerNodes =
      this.target !== null && hasCloserNodes ? this._io.table.closest(this.target) : EMPTY_ARRAY
    const state = { start: 0, end: 1 + 1 + 6 + 2, buffer: null } // (type | version) + flags + to + tid

    if (id) state.end += 32
    if (token) state.end += 32
    if (closerNodes.length > 0) peer.ipv4Array.preencode(state, closerNodes)
    if (error > 0) c.uint.preencode(state, error)
    if (value) c.buffer.preencode(state, value)

    state.buffer = b4a.allocUnsafe(state.end)
    state.buffer[state.start++] = RESPONSE_ID
    state.buffer[state.start++] =
      (id ? 1 : 0) |
      (token ? 2 : 0) |
      (closerNodes.length > 0 ? 4 : 0) |
      (error > 0 ? 8 : 0) |
      (value ? 16 : 0)

    c.uint16.encode(state, this.tid)
    peer.ipv4.encode(state, from)

    if (id) c.fixed32.encode(state, this._io.table.id)
    if (token) c.fixed32.encode(state, this._io.token(from, 1))
    if (closerNodes.length > 0) peer.ipv4Array.encode(state, closerNodes)
    if (error > 0) c.uint.encode(state, error)
    if (value) c.buffer.encode(state, value)

    socket.trySend(state.buffer, from.port, from.host, this.ttl)
  }

  _encodeRequest(token, value, to, socket) {
    const id = this._io.ephemeral === false && socket === this._io.serverSocket
    const state = { start: 0, end: 1 + 1 + 6 + 2, buffer: null } // (type | version) + flags + to + tid

    if (id) state.end += 32
    if (token) state.end += 32

    c.uint.preencode(state, this.command)

    if (this.target) state.end += 32
    if (value) c.buffer.preencode(state, value)

    state.buffer = b4a.allocUnsafe(state.end)
    state.buffer[state.start++] = REQUEST_ID
    state.buffer[state.start++] =
      (id ? 1 : 0) |
      (token ? 2 : 0) |
      (this.internal ? 4 : 0) |
      (this.target ? 8 : 0) |
      (value ? 16 : 0)

    c.uint16.encode(state, this.tid)
    peer.ipv4.encode(state, to)

    if (id) c.fixed32.encode(state, this._io.table.id)
    if (token) c.fixed32.encode(state, token)

    c.uint.encode(state, this.command)

    if (this.target) c.fixed32.encode(state, this.target)
    if (value) c.buffer.encode(state, value)

    return state.buffer
  }
}

class CongestionWindow {
  constructor(maxWindow) {
    this._i = 0
    this._total = 0
    this._window = [0, 0, 0, 0]
    this._maxWindow = maxWindow
  }

  clear() {
    this._i = 0
    this._total = 0
    this._window = [0, 0, 0, 0]
  }

  isFull() {
    return this._total >= 2 * this._maxWindow || this._window[this._i] >= this._maxWindow
  }

  recv() {
    if (this._window[this._i] > 0) {
      this._window[this._i]--
      this._total--
    }
  }

  send() {
    this._total++
    this._window[this._i]++
  }

  drain() {
    this._i = (this._i + 1) & 3
    this._total -= this._window[this._i]
    this._window[this._i] = 0 // clear oldest
  }
}

function noop() {}

function oncycle(req) {
  req._timeout = null
  req.oncycle(req)
  if (req.sent > req.retries) {
    req._io.stats.requests.timeouts++
    req.destroy(REQUEST_TIMEOUT())
    req._io.ontimeout(req)
  } else {
    req._io.stats.requests.retries++
    req.send()
  }
}

function decodeReply(from, state) {
  try {
    const flags = c.uint.decode(state)
    const tid = c.uint16.decode(state)
    const to = peer.ipv4.decode(state)
    const id = flags & 1 ? c.fixed32.decode(state) : null
    const token = flags & 2 ? c.fixed32.decode(state) : null
    const closerNodes = flags & 4 ? peer.ipv4Array.decode(state) : null
    const error = flags & 8 ? c.uint.decode(state) : 0
    const value = flags & 16 ? c.buffer.decode(state) : null

    if (id !== null) from.id = validateId(id, from)

    return { tid, rtt: 0, from, to, token, closerNodes, error, value }
  } catch {
    return null
  }
}

function validateId(id, from) {
  const expected = peer.id(from.host, from.port)
  return b4a.equals(expected, id) ? expected : null
}
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const b4a = require('b4a')

const ipv4 = {
  ...c.ipv4Address,
  decode(state) {
    const ip = c.ipv4Address.decode(state)
    return {
      id: null, // populated by the callee
      host: ip.host,
      port: ip.port
    }
  }
}

module.exports = { id, ipv4, ipv4Array: c.array(ipv4) }

function id(host, port, out = b4a.allocUnsafeSlow(32)) {
  const addr = out.subarray(0, 6)
  ipv4.encode({ start: 0, end: 6, buffer: addr }, { host, port })
  sodium.crypto_generichash(out, addr)
  return out
}
const { Readable, getStreamError } = require('streamx')
const b4a = require('b4a')
const peer = require('./peer')
const { DOWN_HINT } = require('./commands')

const DONE = []
const DOWN = []

module.exports = class Query extends Readable {
  constructor(dht, target, internal, command, value, opts = {}) {
    super()

    dht.stats.queries.total++
    dht.stats.queries.active++

    this.force = !!opts.force
    this.dht = dht
    this.k = this.dht.table.k
    this.target = target
    this.internal = internal
    this.command = command
    this.value = value
    this.errors = 0
    this.successes = 0
    this.concurrency = opts.concurrency || this.dht.concurrency
    this.inflight = 0
    this.map = opts.map || defaultMap
    this.retries =
      opts.retries === 0 ? 0 : opts.retries || (this.internal && command === DOWN_HINT ? 3 : 5)
    this.closestReplies = []

    this._slow = 0
    this._slowdown = false
    this._seen = new Map()
    this._pending = []
    this._fromTable = false
    this._commit = opts.commit === true ? autoCommit : opts.commit || null
    this._commiting = false
    this._session = opts.session || dht.session()
    this._autoDestroySession = !opts.session
    this._onlyClosestNodes = false

    this._onvisitbound = this._onvisit.bind(this)
    this._onerrorbound = this._onerror.bind(this)
    this._oncyclebound = this._oncycle.bind(this)

    const nodes = opts.nodes || opts.closestNodes
    const replies = opts.replies || opts.closestReplies

    // add them reverse as we pop below
    if (nodes) {
      for (let i = nodes.length - 1; i >= 0; i--) {
        const node = nodes[i]
        this._addPending(
          {
            id: node.id || peer.id(node.host, node.port),
            host: node.host,
            port: node.port
          },
          null
        )
      }
    } else if (replies) {
      for (let i = replies.length - 1; i >= 0; i--) {
        this._addPending(replies[i].from, null)
      }
    }

    if (opts.onlyClosestNodes) this._onlyClosestNodes = true
  }

  get closestNodes() {
    const nodes = new Array(this.closestReplies.length)

    for (let i = 0; i < nodes.length; i++) {
      nodes[i] = this.closestReplies[i].from
    }

    return nodes
  }

  finished() {
    return new Promise((resolve, reject) => {
      if (this.destroyed) {
        const error = getStreamError(this)
        if (error) reject(error)
        else resolve()
        return
      }

      const self = this
      let error = null

      this.resume()
      this.on('error', onerror)
      this.on('close', onclose)

      function onclose() {
        self.removeListener('error', onerror)
        self.removeListener('close', onclose)
        if (error) reject(error)
        else resolve()
      }

      function onerror(err) {
        error = err
      }
    })
  }

  _addFromTable() {
    if (this._pending.length >= this.k) return
    this._fromTable = true

    const closest = this.dht.table.closest(this.target, this.k - this._pending.length)

    for (const node of closest) {
      this._addPending({ id: node.id, host: node.host, port: node.port }, null)
    }
  }

  async _open(cb) {
    this._addFromTable()
    if (this._pending.length >= this.k) return cb(null)

    for await (const node of this.dht._resolveBootstrapNodes()) {
      this._addPending(node, null)
    }

    cb(null)
  }

  _isCloser(id) {
    return (
      this.closestReplies.length < this.k ||
      this._compare(id, this.closestReplies[this.closestReplies.length - 1].from.id) < 0
    )
  }

  _addPending(node, ref) {
    if (this._onlyClosestNodes) return false

    const addr = node.host + ':' + node.port
    const refs = this._seen.get(addr)
    const isCloser = this._isCloser(node.id)

    if (refs === DONE) {
      return isCloser
    }

    if (refs === DOWN) {
      if (ref) this._downHint(ref, node)
      return isCloser
    }

    if (refs) {
      if (ref !== null) refs.push(ref)
      return isCloser
    }

    if (!isCloser) {
      return false
    }

    this._seen.set(addr, ref === null ? [] : [ref])
    this._pending.push(node)

    return true
  }

  _read(cb) {
    this._readMore()
    cb(null)
  }

  _readMore() {
    if (this.destroying || this._commiting) return

    const concurrency = (this._slowdown ? 3 : this.concurrency) + this._slow

    while (this.inflight < concurrency && this._pending.length > 0) {
      const next = this._pending.pop()
      if (next && next.id && !this._isCloser(next.id)) continue
      this._visit(next)
    }

    // if reusing closest nodes, slow down after the first readMore tick to allow
    // the closest node a chance to reply before going broad to question more
    if (!this._fromTable && this.successes === 0 && this.errors === 0) {
      this._slowdown = true
    }

    if (this._pending.length > 0) return

    // if no inflight OR all the queries we are waiting on are marked as slow and we have a full result.
    if (
      this.inflight === 0 ||
      (this._slow === this.inflight && this.closestReplies.length >= this.k)
    ) {
      // if more than 3/4 failed and we only used cached nodes, try again from the routing table
      if (!this._fromTable && this.successes < this.k / 4) {
        this._addFromTable()
        this._readMore()
        return
      }

      this._flush()
    }
  }

  _flush() {
    if (this._commiting) return
    this._commiting = true

    if (this._commit === null) {
      this.push(null)
      return
    }

    const p = []
    for (const m of this.closestReplies) p.push(this._commit(m, this.dht, this))
    this._endAfterCommit(p)
  }

  _endAfterCommit(ps) {
    if (!ps.length) {
      this.destroy(new Error('Too few nodes responded'))
      return
    }

    const self = this

    let pending = ps.length
    let success = 0

    for (const p of ps) p.then(ondone, onerror)

    function ondone() {
      success++
      if (--pending === 0) self.push(null)
    }

    function onerror(err) {
      if (--pending > 0) return
      if (success) self.push(null)
      else self.destroy(err)
    }
  }

  _dec(req) {
    if (req.oncycle === noop) {
      this._slow--
    } else {
      req.oncycle = noop
    }
    this.inflight--
  }

  _onvisit(m, req) {
    this._dec(req)

    const addr = req.to.host + ':' + req.to.port
    this._seen.set(addr, DONE)

    if (this._commiting) return

    if (m.error === 0) this.successes++
    else this.errors++

    if (m.error === 0 && m.from.id !== null && this._isCloser(m.from.id)) this._pushClosest(m)

    if (m.closerNodes !== null) {
      for (const node of m.closerNodes) {
        node.id = peer.id(node.host, node.port)
        if (this.dht._filterNode !== null && !this.dht._filterNode(node)) continue
        if (b4a.equals(node.id, this.dht.table.id)) continue
        // TODO: we could continue here instead of breaking to ensure that one of the nodes in the closer list
        // is later marked as DOWN that we gossip that back
        if (!this._addPending(node, m.from)) break
      }
    }

    if (!this._fromTable && this.successes + this.errors >= this.concurrency) {
      this._slowdown = false
    }

    if (m.error !== 0) {
      this._readMore()
      return
    }

    const data = this.map(m)
    if (!data || this.push(data) !== false) {
      this._readMore()
    }
  }

  _onerror(err, req) {
    const addr = req.to.host + ':' + req.to.port
    const refs = this._seen.get(addr)

    if (err.code === 'REQUEST_TIMEOUT') {
      this._seen.set(addr, DOWN)
      for (const node of refs) this._downHint(node, req.to)
    }

    this._dec(req)
    this.errors++
    this._readMore()
  }

  _oncycle(req) {
    req.oncycle = noop
    this._slow++
    this._readMore()
  }

  _downHint(node, down) {
    // Check rate limit
    if (
      this.dht._downHintsRateLimit !== -1 &&
      this.dht._downHintsSentPerTick >= this.dht._downHintsRateLimit
    ) {
      return null
    }

    this.dht._downHintsSentPerTick++

    const state = { start: 0, end: 6, buffer: b4a.allocUnsafe(6) }
    peer.ipv4.encode(state, down)
    this.dht._request(node, false, true, DOWN_HINT, null, state.buffer, this._session, noop, noop)
  }

  _pushClosest(m) {
    this.closestReplies.push(m)
    for (let i = this.closestReplies.length - 2; i >= 0; i--) {
      const prev = this.closestReplies[i]
      const cmp = this._compare(prev.from.id, m.from.id)
      // if sorted, done!
      if (cmp < 0) break
      // if dup, splice it out (rare)
      if (cmp === 0) {
        this.closestReplies.splice(i + 1, 1)
        break
      }
      // swap and continue down
      this.closestReplies[i + 1] = prev
      this.closestReplies[i] = m
    }
    if (this.closestReplies.length > this.k) this.closestReplies.pop()
  }

  _compare(a, b) {
    for (let i = 0; i < a.length; i++) {
      if (a[i] === b[i]) continue
      const t = this.target[i]
      return (t ^ a[i]) - (t ^ b[i])
    }
    return 0
  }

  _visit(to) {
    this.inflight++

    const req = this.dht._request(
      to,
      this.force,
      this.internal,
      this.command,
      this.target,
      this.value,
      this._session,
      this._onvisitbound,
      this._onerrorbound
    )
    if (req === null) {
      this.destroy(new Error('Node was destroyed'))
      return
    }
    req.retries = this.retries
    req.oncycle = this._oncyclebound
    if (this.force) req.retries = 0
  }

  _destroy(cb) {
    this.dht.stats.queries.active--
    if (this._autoDestroySession) this._session.destroy()
    cb(null)
  }
}

function autoCommit(reply, dht, query) {
  if (!reply.token) return Promise.reject(new Error('No token received for closest node'))
  return dht.request(
    {
      token: reply.token,
      target: query.target,
      command: query.command,
      value: query.value
    },
    reply.from
  )
}

function defaultMap(m) {
  return m
}

function noop() {}
module.exports = class Session {
  constructor(dht) {
    this.dht = dht
    this.inflight = []
  }

  _attach(req) {
    req.index = this.inflight.push(req) - 1
  }

  _detach(req) {
    const i = req.index
    if (i === -1) return
    req.index = -1

    if (i === this.inflight.length - 1) this.inflight.pop()
    else {
      const req = (this.inflight[i] = this.inflight.pop())
      req.index = i
    }
  }

  query({ target, command, value }, opts = {}) {
    return this.dht.query({ target, command, value }, { ...opts, session: this })
  }

  request({ token, command, target, value }, { host, port }, opts = {}) {
    return this.dht.request(
      { token, command, target, value },
      { host, port },
      { ...opts, session: this }
    )
  }

  ping({ host, port }, opts = {}) {
    return this.dht.ping({ host, port }, { ...opts, session: this })
  }

  destroy(err) {
    while (this.inflight.length) {
      const req = this.inflight[0]
      // prevent destroyed requests from contributing to congestion counts
      this.dht.io.congestion.recv()
      req.destroy(err)
    }
  }
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "dht-rpc",
  "version": "6.27.0",
  "description": "Make RPC calls over a Kademlia based DHT",
  "main": "index.js",
  "files": [
    "index.js",
    "lib/*.js"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "dependencies": {
    "adaptive-timeout": "^1.0.1",
    "b4a": "^1.6.1",
    "bare-events": "^2.2.0",
    "compact-encoding": "^3.0.0",
    "compact-encoding-net": "^1.2.0",
    "fast-fifo": "^1.1.0",
    "kademlia-routing-table": "^1.0.1",
    "nat-sampler": "^1.0.1",
    "sodium-universal": "^5.0.0",
    "streamx": "^2.13.2",
    "time-ordered-set": "^2.0.0",
    "udx-native": "^1.5.3"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "test-suspend": "^1.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "test": "npm run test:node && npm run test:bare",
    "test:bare": "brittle-bare --coverage test.js",
    "lint": "prettier --check . && lunte",
    "test:node": "brittle-node --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/dht-rpc.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/dht-rpc/issues"
  },
  "homepage": "https://github.com/holepunchto/dht-rpc#"
}
module.exports = require('bare-events')
{
  "name": "events-universal",
  "version": "1.0.1",
  "description": "Universal wrapper for the Node.js events module",
  "exports": {
    "./package": "./package.json",
    ".": {
      "bare": "./bare.js",
      "react-native": "./react-native.js",
      "default": "./default.js"
    }
  },
  "files": [
    "index.js",
    "default.js",
    "bare.js",
    "react-native.js"
  ],
  "scripts": {
    "test": "prettier . --check"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/events-universal.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/events-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/events-universal#readme",
  "dependencies": {
    "bare-events": "^2.7.0"
  },
  "devDependencies": {
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^1.0.0"
  }
}
module.exports = class FixedFIFO {
  constructor (hwm) {
    if (!(hwm > 0) || ((hwm - 1) & hwm) !== 0) throw new Error('Max size for a FixedFIFO should be a power of two')
    this.buffer = new Array(hwm)
    this.mask = hwm - 1
    this.top = 0
    this.btm = 0
    this.next = null
  }

  clear () {
    this.top = this.btm = 0
    this.next = null
    this.buffer.fill(undefined)
  }

  push (data) {
    if (this.buffer[this.top] !== undefined) return false
    this.buffer[this.top] = data
    this.top = (this.top + 1) & this.mask
    return true
  }

  shift () {
    const last = this.buffer[this.btm]
    if (last === undefined) return undefined
    this.buffer[this.btm] = undefined
    this.btm = (this.btm + 1) & this.mask
    return last
  }

  peek () {
    return this.buffer[this.btm]
  }

  isEmpty () {
    return this.buffer[this.btm] === undefined
  }
}
const FixedFIFO = require('./fixed-size')

module.exports = class FastFIFO {
  constructor (hwm) {
    this.hwm = hwm || 16
    this.head = new FixedFIFO(this.hwm)
    this.tail = this.head
    this.length = 0
  }

  clear () {
    this.head = this.tail
    this.head.clear()
    this.length = 0
  }

  push (val) {
    this.length++
    if (!this.head.push(val)) {
      const prev = this.head
      this.head = prev.next = new FixedFIFO(2 * this.head.buffer.length)
      this.head.push(val)
    }
  }

  shift () {
    if (this.length !== 0) this.length--
    const val = this.tail.shift()
    if (val === undefined && this.tail.next) {
      const next = this.tail.next
      this.tail.next = null
      this.tail = next
      return this.tail.shift()
    }

    return val
  }

  peek () {
    const val = this.tail.peek()
    if (val === undefined && this.tail.next) return this.tail.next.peek()
    return val
  }

  isEmpty () {
    return this.length === 0
  }
}
{
  "name": "fast-fifo",
  "version": "1.3.2",
  "description": "A fast fifo implementation similar to the one powering nextTick in Node.js core",
  "main": "index.js",
  "files": [
    "./index.js",
    "./fixed-size.js"
  ],
  "dependencies": {},
  "devDependencies": {
    "standard": "^17.1.0",
    "brittle": "^3.3.2"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/fast-fifo.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/fast-fifo/issues"
  },
  "homepage": "https://github.com/mafintosh/fast-fifo"
}
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const b4a = require('b4a')

// https://en.wikipedia.org/wiki/Merkle_tree#Second_preimage_attack
const LEAF_TYPE = b4a.from([0])
const PARENT_TYPE = b4a.from([1])
const ROOT_TYPE = b4a.from([2])

const HYPERCORE = b4a.from('hypercore')

exports.keyPair = function (seed) {
  // key pairs might stay around for a while, so better not to use a default slab to avoid retaining it completely
  const slab = b4a.allocUnsafeSlow(
    sodium.crypto_sign_PUBLICKEYBYTES + sodium.crypto_sign_SECRETKEYBYTES
  )
  const publicKey = slab.subarray(0, sodium.crypto_sign_PUBLICKEYBYTES)
  const secretKey = slab.subarray(sodium.crypto_sign_PUBLICKEYBYTES)

  if (seed) sodium.crypto_sign_seed_keypair(publicKey, secretKey, seed)
  else sodium.crypto_sign_keypair(publicKey, secretKey)

  return {
    publicKey,
    secretKey
  }
}

exports.validateKeyPair = function (keyPair) {
  const pk = b4a.allocUnsafe(sodium.crypto_sign_PUBLICKEYBYTES)
  sodium.crypto_sign_ed25519_sk_to_pk(pk, keyPair.secretKey)
  return b4a.equals(pk, keyPair.publicKey)
}

exports.sign = function (message, secretKey) {
  // Dedicated slab for the signature, to avoid retaining unneeded mem and for security
  const signature = b4a.allocUnsafeSlow(sodium.crypto_sign_BYTES)
  sodium.crypto_sign_detached(signature, message, secretKey)
  return signature
}

exports.verify = function (message, signature, publicKey) {
  if (signature.byteLength !== sodium.crypto_sign_BYTES) return false
  if (publicKey.byteLength !== sodium.crypto_sign_PUBLICKEYBYTES) return false
  return sodium.crypto_sign_verify_detached(signature, message, publicKey)
}

exports.encrypt = function (message, publicKey) {
  const ciphertext = b4a.alloc(message.byteLength + sodium.crypto_box_SEALBYTES)
  sodium.crypto_box_seal(ciphertext, message, publicKey)
  return ciphertext
}

exports.decrypt = function (ciphertext, keyPair) {
  if (ciphertext.byteLength < sodium.crypto_box_SEALBYTES) return null

  const plaintext = b4a.alloc(ciphertext.byteLength - sodium.crypto_box_SEALBYTES)

  if (!sodium.crypto_box_seal_open(plaintext, ciphertext, keyPair.publicKey, keyPair.secretKey)) {
    return null
  }

  return plaintext
}

exports.encryptionKeyPair = function (seed) {
  const publicKey = b4a.alloc(sodium.crypto_box_PUBLICKEYBYTES)
  const secretKey = b4a.alloc(sodium.crypto_box_SECRETKEYBYTES)

  if (seed) {
    sodium.crypto_box_seed_keypair(publicKey, secretKey, seed)
  } else {
    sodium.crypto_box_keypair(publicKey, secretKey)
  }

  return {
    publicKey,
    secretKey
  }
}

exports.data = function (data) {
  const out = b4a.allocUnsafe(32)

  sodium.crypto_generichash_batch(out, [LEAF_TYPE, c.encode(c.uint64, data.byteLength), data])

  return out
}

exports.parent = function (a, b) {
  if (a.index > b.index) {
    const tmp = a
    a = b
    b = tmp
  }

  const out = b4a.allocUnsafe(32)

  sodium.crypto_generichash_batch(out, [
    PARENT_TYPE,
    c.encode(c.uint64, a.size + b.size),
    a.hash,
    b.hash
  ])

  return out
}

exports.tree = function (roots, out) {
  const buffers = new Array(3 * roots.length + 1)
  let j = 0

  buffers[j++] = ROOT_TYPE

  for (let i = 0; i < roots.length; i++) {
    const r = roots[i]
    buffers[j++] = r.hash
    buffers[j++] = c.encode(c.uint64, r.index)
    buffers[j++] = c.encode(c.uint64, r.size)
  }

  if (!out) out = b4a.allocUnsafe(32)
  sodium.crypto_generichash_batch(out, buffers)
  return out
}

exports.hash = function (data, out) {
  if (!out) out = b4a.allocUnsafe(32)
  if (!Array.isArray(data)) data = [data]

  sodium.crypto_generichash_batch(out, data)

  return out
}

exports.randomBytes = function (n) {
  const buf = b4a.allocUnsafe(n)
  sodium.randombytes_buf(buf)
  return buf
}

exports.discoveryKey = function (key) {
  if (!key || key.byteLength !== 32) throw new Error('Must pass a 32 byte buffer')
  // Discovery keys might stay around for a while, so better not to use slab memory (for better gc)
  const digest = b4a.allocUnsafeSlow(32)
  sodium.crypto_generichash(digest, HYPERCORE, key)
  return digest
}

if (sodium.sodium_free) {
  exports.free = function (secureBuf) {
    if (secureBuf.secure) sodium.sodium_free(secureBuf)
  }
} else {
  exports.free = function () {}
}

exports.namespace = function (name, count) {
  const ids = typeof count === 'number' ? range(count) : count

  // Namespaces are long-lived, so better to use a dedicated slab
  const buf = b4a.allocUnsafeSlow(32 * ids.length)

  const list = new Array(ids.length)

  // ns is ephemeral, so default slab
  const ns = b4a.allocUnsafe(33)
  sodium.crypto_generichash(ns.subarray(0, 32), typeof name === 'string' ? b4a.from(name) : name)

  for (let i = 0; i < list.length; i++) {
    list[i] = buf.subarray(32 * i, 32 * i + 32)
    ns[32] = ids[i]
    sodium.crypto_generichash(list[i], ns)
  }

  return list
}

function range(count) {
  const arr = new Array(count)
  for (let i = 0; i < count; i++) arr[i] = i
  return arr
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "hypercore-crypto",
  "version": "3.7.0",
  "description": "The crypto primitives used in hypercore, extracted into a separate module",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.6.6",
    "compact-encoding": "^3.0.0",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "brittle": "^3.5.0",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/hypercore-crypto.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/hypercore-crypto/issues"
  },
  "homepage": "https://github.com/mafintosh/hypercore-crypto"
}
const z32 = require('z32')
const b4a = require('b4a')

module.exports = {
  encode,
  decode,
  normalize,
  isValid
}

function encode (key) {
  if (!b4a.isBuffer(key)) throw new Error('Key must be a Buffer')
  if (key.byteLength !== 32) throw new Error('Key must be 32-bytes long')
  return z32.encode(key)
}

function decode (id) {
  if (b4a.isBuffer(id)) {
    if (id.byteLength !== 32) throw new Error('ID must be 32-bytes long')
    return id
  }
  if (typeof id === 'string') {
    if (id.startsWith('pear://')) id = id.slice(7).split('/')[0]
    if (id.length === 52) return z32.decode(id)
    if (id.length === 64) {
      const buf = b4a.from(id, 'hex')
      if (buf.byteLength === 32) return buf
    }
  }
  throw new Error('Invalid Hypercore key')
}

function normalize (any) {
  return encode(decode(any))
}

function isValid (any) {
  try {
    decode(any)
    return true
  } catch {
    return false
  }
}
{
  "name": "hypercore-id-encoding",
  "version": "1.3.0",
  "description": "Convert Hypercore keys to/from z-base32 or hex",
  "main": "index.js",
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.5.3",
    "z32": "^1.0.0"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "hypercore": "^10.0.0",
    "random-access-memory": "^6.0.0",
    "standard": "^17.1.0"
  },
  "license": "Apache-2.0",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/hypercore-id-encoding.git"
  },
  "keywords": [],
  "author": "",
  "bugs": {
    "url": "https://github.com/holepunchto/hypercore-id-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/hypercore-id-encoding#readme"
}
const c = require('compact-encoding')
const { getEncoding } = require('./spec/hyperschema')

const HyperdhtAddress = getEncoding('@hyperdht/address')

function decode(buf) {
  const addr = c.decode(HyperdhtAddress, buf)
  return addr
}

function encode(key, nodes) {
  return c.encode(HyperdhtAddress, { key, nodes })
}

module.exports = { decode, encode }
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "hyperdht-address",
  "version": "1.1.1",
  "description": "hyperdht-address",
  "main": "index.js",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    }
  },
  "files": [
    "package.json",
    "index.js",
    "index.d.ts",
    "spec"
  ],
  "devDependencies": {
    "b4a": "^1.8.0",
    "brittle": "^3.19.0",
    "lunte": "^1.2.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && lunte && brittle-bare test/index.js",
    "lint": "lunte"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/hyperdht-address.git"
  },
  "author": "Holepunch Inc",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/hyperdht-address/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperdht-address",
  "dependencies": {
    "compact-encoding": "^3.0.0",
    "hyperschema": "^1.20.1"
  }
}
// This file is autogenerated by the hyperschema compiler
// Schema Version: 2
/* eslint-disable camelcase */
/* eslint-disable quotes */
/* eslint-disable space-before-function-paren */

const { c } = require('hyperschema/runtime')

const VERSION = 2

// eslint-disable-next-line no-unused-vars
let version = VERSION

// @hyperdht/address.nodes
const encoding0_1 = c.array(c.ipv4Address)

// @hyperdht/address
const encoding0 = {
  preencode(state, m) {
    c.fixed32.preencode(state, m.key)
    state.end++ // max flag is 1 so always one byte

    if (version >= 2 && m.nodes) encoding0_1.preencode(state, m.nodes)
  },
  encode(state, m) {
    const flags = version >= 2 && m.nodes ? 1 : 0

    c.fixed32.encode(state, m.key)
    c.uint.encode(state, flags)

    if (version >= 2 && m.nodes) encoding0_1.encode(state, m.nodes)
  },
  decode(state) {
    const r0 = c.fixed32.decode(state)
    const flags = state.start < state.end ? c.uint.decode(state) : 0

    return {
      key: r0,
      nodes: version >= 2 && (flags & 1) !== 0 ? encoding0_1.decode(state) : null
    }
  }
}

function setVersion(v) {
  version = v
}

function encode(name, value, v = VERSION) {
  version = v
  return c.encode(getEncoding(name), value)
}

function decode(name, buffer, v = VERSION) {
  version = v
  return c.decode(getEncoding(name), buffer)
}

function getEnum(name) {
  switch (name) {
    default:
      throw new Error('Enum not found ' + name)
  }
}

function getEncoding(name) {
  switch (name) {
    case '@hyperdht/address':
      return encoding0
    default:
      throw new Error('Encoder not found ' + name)
  }
}

function getStruct(name, v = VERSION) {
  const enc = getEncoding(name)
  return {
    preencode(state, m) {
      version = v
      enc.preencode(state, m)
    },
    encode(state, m) {
      version = v
      enc.encode(state, m)
    },
    decode(state) {
      version = v
      return enc.decode(state)
    }
  }
}

const resolveStruct = getStruct // compat

module.exports = {
  resolveStruct,
  getStruct,
  getEnum,
  getEncoding,
  encode,
  decode,
  setVersion,
  version
}
const DHT = require('dht-rpc')
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const b4a = require('b4a')
const safetyCatch = require('safety-catch')
const m = require('./lib/messages')
const SocketPool = require('./lib/socket-pool')
const Persistent = require('./lib/persistent')
const Router = require('./lib/router')
const Cache = require('xache')
const Server = require('./lib/server')
const connect = require('./lib/connect')
const { FIREWALL, BOOTSTRAP_NODES, COMMANDS } = require('./lib/constants')
const { hash, createKeyPair } = require('./lib/crypto')
const RawStreamSet = require('./lib/raw-stream-set')
const ConnectionPool = require('./lib/connection-pool')
const { STREAM_NOT_CONNECTED } = require('./lib/errors')

const DEFAULTS = {
  ...DHT.DEFAULTS,
  connectionKeepAlive: 5000,
  randomPunchInterval: 20000
}

class HyperDHT extends DHT {
  constructor(opts = {}) {
    const port = opts.port || 49737
    const bootstrap = opts.bootstrap || BOOTSTRAP_NODES
    const nodes = opts.nodes || []

    super({ ...opts, port, bootstrap, nodes, filterNode })

    const { router, relayAddresses, persistent } = defaultCacheOpts(opts)

    this.defaultKeyPair = opts.keyPair || createKeyPair(opts.seed)
    this.listening = new Set()
    this.connectionKeepAlive =
      opts.connectionKeepAlive === false
        ? 0
        : opts.connectionKeepAlive || DEFAULTS.connectionKeepAlive

    // stats is inherited from dht-rpc so fwd the ones from there
    this.stats = {
      punches: { consistent: 0, random: 0, open: 0 },
      relaying: { attempts: 0, successes: 0, aborts: 0 },
      ...this.stats
    }
    this.rawStreams = new RawStreamSet(this)
    this.plugins = new Map()

    this._router = new Router(this, router)
    this._socketPool = new SocketPool(this, opts.host || '0.0.0.0')
    this._persistent = null
    this._validatedLocalAddresses = new Map()
    this._relayAddressesCache = new Cache(relayAddresses)

    this._deferRandomPunch = !!opts.deferRandomPunch
    this._lastRandomPunch = this._deferRandomPunch ? Date.now() : 0
    this._connectable = true
    this._randomPunchInterval = opts.randomPunchInterval || DEFAULTS.randomPunchInterval // min 20s between random punches...
    this._randomPunches = 0
    this._randomPunchLimit = 1 // set to one for extra safety for now

    this.once('persistent', () => {
      this._persistent = new Persistent(this, persistent)
      for (const plugin of this.plugins.values()) plugin.onpersistent()
    })

    this.on('network-change', () => {
      for (const server of this.listening) server.refresh()
    })

    this.on('network-update', () => {
      if (!this.online) return
      for (const server of this.listening) server.notifyOnline()
    })
  }

  static DEFAULTS = DEFAULTS

  connect(remotePublicKey, opts) {
    return connect(this, remotePublicKey, opts)
  }

  createServer(opts, onconnection) {
    if (typeof opts === 'function') return this.createServer({}, opts)
    if (opts && opts.onconnection) onconnection = opts.onconnection
    const s = new Server(this, opts)
    if (onconnection) s.on('connection', onconnection)
    return s
  }

  pool() {
    return new ConnectionPool(this)
  }

  async resume({ log = noop } = {}) {
    if (this._deferRandomPunch) this._lastRandomPunch = Date.now()
    await super.resume({ log })
    const resuming = []
    for (const server of this.listening) resuming.push(server.resume())
    log('Resuming hyperdht servers')
    await Promise.allSettled(resuming)
    log('Done, hyperdht fully resumed')
  }

  async suspend({ log = noop } = {}) {
    this._connectable = false // just so nothing gets connected during suspension
    const suspending = []
    for (const server of this.listening) suspending.push(server.suspend())
    log('Suspending all hyperdht servers')
    await Promise.allSettled(suspending)
    log('Done, clearing all raw streams')
    await this.rawStreams.clear()
    log('Done, suspending dht-rpc')
    await super.suspend({ log })
    log('Done, clearing raw streams again')
    await this.rawStreams.clear()
    log('Done, hyperdht fully suspended')
    this._connectable = true
  }

  async destroy({ force = false } = {}) {
    if (!force) {
      const closing = []
      for (const server of this.listening) closing.push(server.close())
      await Promise.allSettled(closing)
    }
    this._router.destroy()
    if (this._persistent) this._persistent.destroy()
    for (const plugin of this.plugins.values()) plugin.destroy()
    await this.rawStreams.clear()
    await this._socketPool.destroy()
    await super.destroy()
  }

  async validateLocalAddresses(addresses) {
    const list = []
    const socks = []
    const waiting = []

    for (const addr of addresses) {
      const { host } = addr

      if (this._validatedLocalAddresses.has(host)) {
        if (await this._validatedLocalAddresses.get(host)) {
          list.push(addr)
        }
        continue
      }

      const sock = this.udx.createSocket()
      try {
        sock.bind(0, host)
      } catch {
        this._validatedLocalAddresses.set(host, Promise.resolve(false))
        continue
      }

      socks.push(sock)

      // semi terrible heuristic until we proper fix local connections by racing them to the remote...
      const promise = new Promise((resolve) => {
        sock.on('message', () => resolve(true))
        setTimeout(() => resolve(false), 500)
        sock.trySend(b4a.alloc(1), sock.address().port, addr.host)
      })

      this._validatedLocalAddresses.set(host, promise)
      waiting.push(addr)
    }

    for (const addr of waiting) {
      const { host } = addr
      if (this._validatedLocalAddresses.has(host)) {
        if (await this._validatedLocalAddresses.get(host)) {
          list.push(addr)
        }
        continue
      }
    }

    for (const sock of socks) await sock.close()

    return list
  }

  findPeer(publicKey, opts = {}) {
    const target = opts.hash === false ? publicKey : hash(publicKey)
    opts = { ...opts, map: mapFindPeer }
    return this.query({ target, command: COMMANDS.FIND_PEER, value: null }, opts)
  }

  lookup(target, opts = {}) {
    opts = { ...opts, map: mapLookup }
    return this.query({ target, command: COMMANDS.LOOKUP, value: null }, opts)
  }

  lookupAndUnannounce(target, keyPair, opts = {}) {
    const unannounces = []
    const dht = this
    const userCommit = opts.commit || noop
    const signUnannounce = opts.signUnannounce || Persistent.signUnannounce

    if (this._persistent !== null) {
      // unlink self
      this._persistent.unannounce(target, keyPair.publicKey)
    }

    opts = { ...opts, map, commit }
    return this.query({ target, command: COMMANDS.LOOKUP, value: null }, opts)

    async function commit(reply, dht, query) {
      await Promise.all(unannounces) // can never fail, caught below
      return userCommit(reply, dht, query)
    }

    function map(reply) {
      const data = mapLookup(reply)

      if (!data || !data.token) return data

      let found = data.peers.length >= 20
      for (let i = 0; !found && i < data.peers.length; i++) {
        found = b4a.equals(data.peers[i].publicKey, keyPair.publicKey)
      }

      if (!found) return data

      if (!data.from.id) return data

      unannounces.push(
        dht
          ._requestUnannounce(keyPair, dht, target, data.token, data.from, signUnannounce)
          .catch(safetyCatch)
      )

      return data
    }
  }

  unannounce(target, keyPair, opts = {}) {
    return this.lookupAndUnannounce(target, keyPair, opts).finished()
  }

  announce(target, keyPair, relayAddresses, opts = {}) {
    const signAnnounce = opts.signAnnounce || Persistent.signAnnounce
    const bump = opts.bump || 0

    opts = { ...opts, commit }

    return opts.clear ? this.lookupAndUnannounce(target, keyPair, opts) : this.lookup(target, opts)

    function commit(reply, dht) {
      return dht._requestAnnounce(
        keyPair,
        dht,
        target,
        reply.token,
        reply.from,
        relayAddresses,
        signAnnounce,
        bump
      )
    }
  }

  async immutableGet(target, opts = {}) {
    opts = { ...opts, map: mapImmutable }

    const query = this.query({ target, command: COMMANDS.IMMUTABLE_GET, value: null }, opts)
    const check = b4a.allocUnsafe(32)

    for await (const node of query) {
      const { value } = node
      sodium.crypto_generichash(check, value)
      if (b4a.equals(check, target)) return node
    }

    return null
  }

  async immutablePut(value, opts = {}) {
    const target = b4a.allocUnsafe(32)
    sodium.crypto_generichash(target, value)

    opts = {
      ...opts,
      map: mapImmutable,
      commit(reply, dht) {
        return dht.request(
          { token: reply.token, target, command: COMMANDS.IMMUTABLE_PUT, value },
          reply.from
        )
      }
    }

    const query = this.query({ target, command: COMMANDS.IMMUTABLE_GET, value: null }, opts)
    await query.finished()

    return { hash: target, closestNodes: query.closestNodes }
  }

  async mutableGet(publicKey, opts = {}) {
    let refresh = opts.refresh || null
    let signed = null
    let result = null

    opts = { ...opts, map: mapMutable, commit: refresh ? commit : null }

    const target = b4a.allocUnsafe(32)
    sodium.crypto_generichash(target, publicKey)

    const userSeq = opts.seq || 0
    const query = this.query(
      { target, command: COMMANDS.MUTABLE_GET, value: c.encode(c.uint, userSeq) },
      opts
    )
    const latest = opts.latest !== false

    for await (const node of query) {
      if (result && node.seq <= result.seq) continue
      if (
        node.seq < userSeq ||
        !Persistent.verifyMutable(node.signature, node.seq, node.value, publicKey)
      )
        continue
      if (!latest) return node
      if (!result || node.seq > result.seq) result = node
    }

    return result

    function commit(reply, dht) {
      if (!signed && result && refresh) {
        if (refresh(result)) {
          signed = c.encode(m.mutablePutRequest, {
            publicKey,
            seq: result.seq,
            value: result.value,
            signature: result.signature
          })
        } else {
          refresh = null
        }
      }

      return signed
        ? dht.request(
            { token: reply.token, target, command: COMMANDS.MUTABLE_PUT, value: signed },
            reply.from
          )
        : Promise.resolve(null)
    }
  }

  async mutablePut(keyPair, value, opts = {}) {
    const signMutable = opts.signMutable || Persistent.signMutable

    const target = b4a.allocUnsafe(32)
    sodium.crypto_generichash(target, keyPair.publicKey)

    const seq = opts.seq || 0
    const signature = await signMutable(seq, value, keyPair)

    const signed = c.encode(m.mutablePutRequest, {
      publicKey: keyPair.publicKey,
      seq,
      value,
      signature
    })

    opts = {
      ...opts,
      map: mapMutable,
      commit(reply, dht) {
        return dht.request(
          { token: reply.token, target, command: COMMANDS.MUTABLE_PUT, value: signed },
          reply.from
        )
      }
    }

    // use seq = 0, for the query part here, as we don't care about the actual values
    const query = this.query(
      { target, command: COMMANDS.MUTABLE_GET, value: c.encode(c.uint, 0) },
      opts
    )
    await query.finished()

    return { publicKey: keyPair.publicKey, closestNodes: query.closestNodes, seq, signature }
  }

  onrequest(req) {
    switch (req.command) {
      case COMMANDS.PEER_HANDSHAKE: {
        this._router.onpeerhandshake(req)
        return true
      }
      case COMMANDS.PEER_HOLEPUNCH: {
        this._router.onpeerholepunch(req)
        return true
      }
    }

    if (this._persistent === null || this.id === null) return false

    switch (req.command) {
      case COMMANDS.FIND_PEER: {
        this._persistent.onfindpeer(req)
        return true
      }
      case COMMANDS.LOOKUP: {
        this._persistent.onlookup(req)
        return true
      }
      case COMMANDS.ANNOUNCE: {
        this._persistent.onannounce(req)
        return true
      }
      case COMMANDS.UNANNOUNCE: {
        this._persistent.onunannounce(req)
        return true
      }
      case COMMANDS.MUTABLE_PUT: {
        this._persistent.onmutableput(req)
        return true
      }
      case COMMANDS.MUTABLE_GET: {
        this._persistent.onmutableget(req)
        return true
      }
      case COMMANDS.IMMUTABLE_PUT: {
        this._persistent.onimmutableput(req)
        return true
      }
      case COMMANDS.IMMUTABLE_GET: {
        this._persistent.onimmutableget(req)
        return true
      }
      case COMMANDS.PLUGIN: {
        this._persistent.onplugin(req)
        return true
      }
    }

    return false
  }

  static keyPair(seed) {
    return createKeyPair(seed)
  }

  static hash(data) {
    return hash(data)
  }

  static connectRawStream(encryptedStream, rawStream, remoteId) {
    const stream = encryptedStream.rawStream

    if (!stream.connected) throw STREAM_NOT_CONNECTED()

    rawStream.connect(stream.socket, remoteId, stream.remotePort, stream.remoteHost)
  }

  createRawStream(opts) {
    return this.rawStreams.add(opts)
  }

  async _requestAnnounce(keyPair, dht, target, token, from, relayAddresses, sign, bump) {
    const ann = {
      peer: {
        publicKey: keyPair.publicKey,
        relayAddresses: relayAddresses || []
      },
      refresh: null,
      signature: null,
      bump
    }

    ann.signature = await sign(target, token, from.id, ann, keyPair)

    const value = c.encode(m.announce, ann)

    return dht.request(
      {
        token,
        target,
        command: COMMANDS.ANNOUNCE,
        value
      },
      from
    )
  }

  async _requestUnannounce(keyPair, dht, target, token, from, sign) {
    const unann = {
      peer: {
        publicKey: keyPair.publicKey,
        relayAddresses: []
      },
      signature: null
    }

    unann.signature = await sign(target, token, from.id, unann, keyPair)

    const value = c.encode(m.announce, unann)

    return dht.request(
      {
        token,
        target,
        command: COMMANDS.UNANNOUNCE,
        value
      },
      from
    )
  }

  register(name, plugin) {
    this.plugins.set(name, plugin)
    plugin.onregister(this)
  }
}

HyperDHT.BOOTSTRAP = BOOTSTRAP_NODES
HyperDHT.FIREWALL = FIREWALL

module.exports = HyperDHT

function mapLookup(node) {
  if (!node.value) return null

  try {
    const l = c.decode(m.lookupRawReply, node.value)

    return {
      token: node.token,
      from: node.from,
      to: node.to,
      peers: l.peers,
      bump: l.bump
    }
  } catch {
    return null
  }
}

function mapFindPeer(node) {
  if (!node.value) return null

  try {
    return {
      token: node.token,
      from: node.from,
      to: node.to,
      peer: c.decode(m.peer, node.value)
    }
  } catch {
    return null
  }
}

function mapImmutable(node) {
  if (!node.value) return null

  return {
    token: node.token,
    from: node.from,
    to: node.to,
    value: node.value
  }
}

function mapMutable(node) {
  if (!node.value) return null

  try {
    const { seq, value, signature } = c.decode(m.mutableGetResponse, node.value)

    return {
      token: node.token,
      from: node.from,
      to: node.to,
      seq,
      value,
      signature
    }
  } catch {
    return null
  }
}

function noop() {}

function filterNode(node) {
  // always skip these testnet nodes that got mixed in by accident, until they get updated
  return (
    !(node.port === 49738 && (node.host === '134.209.28.98' || node.host === '167.99.142.185')) &&
    !(node.port === 9400 && node.host === '35.233.47.252') &&
    !(node.host === '150.136.142.116')
  )
}

const defaultMaxSize = 65536
const defaultMaxAge = 20 * 60 * 1000 // 20 minutes

function defaultCacheOpts(opts) {
  const maxSize = opts.maxSize || defaultMaxSize
  const maxAge = opts.maxAge || defaultMaxAge

  return {
    router: {
      forwards: { maxSize, maxAge }
    },
    relayAddresses: { maxSize: Math.min(maxSize, 512), maxAge: 0 },
    persistent: {
      records: { maxSize, maxAge },
      refreshes: { maxSize, maxAge },
      mutables: {
        maxSize: (maxSize / 2) | 0,
        maxAge: opts.maxAge || 48 * 60 * 60 * 1000 // 48 hours
      },
      immutables: {
        maxSize: (maxSize / 2) | 0,
        maxAge: opts.maxAge || 48 * 60 * 60 * 1000 // 48 hours
      },
      bumps: { maxSize, maxAge }
    }
  }
}
const safetyCatch = require('safety-catch')
const c = require('compact-encoding')
const Signal = require('signal-promise')
const { encodeUnslab } = require('./encode')
const Sleeper = require('./sleeper')
const m = require('./messages')
const Persistent = require('./persistent')
const { COMMANDS } = require('./constants')

const MIN_ACTIVE = 3

module.exports = class Announcer {
  constructor(dht, keyPair, target, opts = {}) {
    this.dht = dht
    this.keyPair = keyPair
    this.target = target
    this.relays = []
    this.relayAddresses = []
    this.stopped = false
    this.suspended = false
    this.record = encodeUnslab(m.peer, { publicKey: keyPair.publicKey, relayAddresses: [] })
    this.online = new Signal()

    this._refreshing = false
    this._closestNodes = null
    this._active = null
    this._sleeper = new Sleeper()
    this._resumed = new Signal()
    this._signAnnounce = opts.signAnnounce || Persistent.signAnnounce
    this._signUnannounce = opts.signUnannounce || Persistent.signUnannounce
    this._updating = null
    this._activeQuery = null
    this._unannouncing = null

    this._serverRelays = [new Map(), new Map(), new Map()]
  }

  isRelay(addr) {
    const id = addr.host + ':' + addr.port
    const [a, b, c] = this._serverRelays
    return a.has(id) || b.has(id) || c.has(id)
  }

  async suspend({ log = noop } = {}) {
    if (this.suspended) return
    this.suspended = true

    log('Suspending announcer')

    // Suspend has its own sleep logic
    // so we don't want to hang on this one
    this.online.notify()

    if (this._activeQuery) this._activeQuery.destroy()

    this._sleeper.resume()
    if (this._updating) await this._updating
    log('Suspending announcer (post update)')

    if (this.suspended === false || this.stopped) return

    log('Suspending announcer (pre unannounce)')
    await this._unannounceCurrent()
    log('Suspending announcer (post unannounce)')
  }

  resume() {
    if (!this.suspended) return
    this.suspended = false

    this.refresh()
    this._sleeper.resume()
    this._resumed.notify()
  }

  refresh() {
    if (this.stopped) return
    this._refreshing = true
  }

  async start() {
    if (this.stopped) return
    this._active = this._runUpdate()
    await this._active
    if (this.stopped) return
    this._active = this._background()
  }

  async stop() {
    this.stopped = true
    this.online.notify() // Break out of the _background loop if we're offline
    this._sleeper.resume()
    this._resumed.notify()
    await this._active
    await this._unannounceCurrent()
  }

  async _unannounceCurrent() {
    while (this._unannouncing !== null) await this._unannouncing
    const un = (this._unannouncing = this._unannounceAll(this._serverRelays[2].values()))
    await this._unannouncing
    if (un === this._unannouncing) this._unannouncing = null
  }

  async _background() {
    while (!this.dht.destroyed && !this.stopped) {
      try {
        this._refreshing = false

        // ~5min +-
        for (let i = 0; i < 100 && !this.stopped && !this._refreshing && !this.suspended; i++) {
          const pings = []

          for (const node of this._serverRelays[2].values()) {
            pings.push(this.dht.ping(node))
          }

          const active = await resolved(pings)
          if (active < Math.min(pings.length, MIN_ACTIVE)) {
            this.refresh() // we lost too many relay nodes, retry all
          }

          if (this.stopped) return

          if (!this.suspended && !this._refreshing) await this._sleeper.pause(3000)
        }

        while (!this.stopped && this.suspended) await this._resumed.wait()

        if (!this.stopped) await this._runUpdate()

        while (!this.dht.online && !this.stopped && !this.suspended) {
          // Being offline can make _background repeat very quickly
          // So wait until we're back online
          await this.online.wait()
        }
      } catch (err) {
        safetyCatch(err)
      }
    }
  }

  async _runUpdate() {
    this._updating = this._update()
    await this._updating
    this._updating = null
  }

  async _update() {
    while (this._unannouncing) await this._unannouncing

    this._cycle()

    const q = (this._activeQuery = this.dht.findPeer(this.target, {
      hash: false,
      nodes: this._closestNodes
    }))

    try {
      await q.finished()
    } catch {
      // ignore failures...
    }

    this._activeQuery = null

    if (this.stopped || this.suspended) return

    const ann = []
    const replies = pickBest(q.closestReplies)

    const relays = []
    const relayAddresses = []

    if (!this.dht.firewalled) {
      const addr = this.dht.remoteAddress()
      if (addr) relayAddresses.push(addr)
    }

    for (const msg of replies) {
      ann.push(this._commit(msg, relays, relayAddresses))
    }

    await Promise.allSettled(ann)
    if (this.stopped || this.suspended) return

    this._closestNodes = q.closestNodes
    this.relays = relays
    this.relayAddresses = relayAddresses

    const removed = []
    for (const [key, value] of this._serverRelays[1]) {
      if (!this._serverRelays[2].has(key)) removed.push(value)
    }

    await this._unannounceAll(removed)
  }

  _unannounceAll(relays) {
    const unann = []
    for (const r of relays) unann.push(this._unannounce(r))
    return Promise.allSettled(unann)
  }

  async _unannounce(to) {
    const unann = {
      peer: {
        publicKey: this.keyPair.publicKey,
        relayAddresses: []
      },
      refresh: null,
      signature: null
    }

    const { from, token, value } = await this.dht.request(
      {
        token: null,
        command: COMMANDS.FIND_PEER,
        target: this.target,
        value: null
      },
      to
    )

    if (!token || !from.id || !value) return

    unann.signature = await this._signUnannounce(this.target, token, from.id, unann, this.keyPair)

    await this.dht.request(
      {
        token,
        command: COMMANDS.UNANNOUNCE,
        target: this.target,
        value: c.encode(m.announce, unann)
      },
      to
    )
  }

  async _commit(msg, relays, relayAddresses) {
    const ann = {
      peer: {
        publicKey: this.keyPair.publicKey,
        relayAddresses: []
      },
      refresh: null,
      signature: null
    }

    ann.signature = await this._signAnnounce(this.target, msg.token, msg.from.id, ann, this.keyPair)

    const res = await this.dht.request(
      {
        token: msg.token,
        command: COMMANDS.ANNOUNCE,
        target: this.target,
        value: c.encode(m.announce, ann)
      },
      msg.from
    )

    if (res.error !== 0) return

    if (relayAddresses.length < 3) relayAddresses.push({ host: msg.from.host, port: msg.from.port })
    relays.push({ relayAddress: msg.from, peerAddress: msg.to })

    this._serverRelays[2].set(msg.from.host + ':' + msg.from.port, msg.from)
  }

  _cycle() {
    const tmp = this._serverRelays[0]
    this._serverRelays[0] = this._serverRelays[1]
    this._serverRelays[1] = this._serverRelays[2]
    this._serverRelays[2] = tmp
    tmp.clear()
  }
}

function resolved(ps) {
  let replied = 0
  let ticks = ps.length + 1

  return new Promise((resolve) => {
    for (const p of ps) p.then(push, tick)
    tick()

    function push(v) {
      replied++
      tick()
    }

    function tick() {
      if (--ticks === 0) resolve(replied)
    }
  })
}

function pickBest(replies) {
  // TODO: pick the ones closest to us RTT wise
  return replies.slice(0, 3)
}

function noop() {}
const NoiseSecretStream = require('@hyperswarm/secret-stream')
const b4a = require('b4a')
const relay = require('blind-relay')
const { isReserved, isBogon } = require('bogon')
const safetyCatch = require('safety-catch')
const unslab = require('unslab')
const Semaphore = require('./semaphore')
const NoiseWrap = require('./noise-wrap')
const SecurePayload = require('./secure-payload')
const Holepuncher = require('./holepuncher')
const Sleeper = require('./sleeper')
const {
  clearRelayTimeout,
  confirmDirectUpgrade,
  destroyRelayConnection
} = require('./relay-connection')
const { FIREWALL, ERROR } = require('./constants')
const { unslabbedHash } = require('./crypto')
const {
  CANNOT_HOLEPUNCH,
  HANDSHAKE_INVALID,
  HOLEPUNCH_ABORTED,
  HOLEPUNCH_INVALID,
  HOLEPUNCH_PROBE_TIMEOUT,
  HOLEPUNCH_DOUBLE_RANDOMIZED_NATS,
  PEER_CONNECTION_FAILED,
  PEER_NOT_FOUND,
  REMOTE_ABORTED,
  REMOTE_NOT_HOLEPUNCHABLE,
  REMOTE_NOT_HOLEPUNCHING,
  SERVER_ERROR,
  SERVER_INCOMPATIBLE,
  RELAY_ABORTED,
  SUSPENDED
} = require('./errors')
const { decode } = require('hypercore-id-encoding')
const HyperDHTAddress = require('hyperdht-address')

module.exports = function connect(dht, publicKey, opts = {}) {
  const pool = opts.pool || null

  const { key, nodes: providedNodes } = HyperDHTAddress.decode(
    b4a.isBuffer(publicKey) ? publicKey : decode(publicKey)
  )
  publicKey = key

  if (pool && pool.has(publicKey)) return pool.get(publicKey)

  publicKey = unslab(publicKey)

  opts.relayAddresses = opts.relayAddresses || providedNodes || []
  const keyPair = opts.keyPair || dht.defaultKeyPair
  const relayThrough = selectRelay(opts.relayThrough || null)
  const encryptedSocket = (opts.createSecretStream || defaultCreateSecretStream)(true, null, {
    publicKey: keyPair.publicKey,
    remotePublicKey: publicKey,
    autoStart: false,
    keepAlive: dht.connectionKeepAlive
  })

  // in case a socket is made during suspended state, destroy it immediately
  if (dht.suspended || !dht._connectable) {
    encryptedSocket.destroy(SUSPENDED())
    return encryptedSocket
  }

  if (pool) pool._attachStream(encryptedSocket, false)

  const id = b4a.toString(publicKey, 'hex')
  const c = {
    id,
    dht,
    session: dht.session(),
    relayAddresses: opts.relayAddresses,
    remoteRelayAddresses: [],
    pool,
    round: 0,
    target: unslabbedHash(publicKey),
    remotePublicKey: publicKey,
    reusableSocket: !!opts.reusableSocket,
    handshake: (opts.createHandshake || defaultCreateHandshake)(keyPair, publicKey),
    request: null,
    requesting: false,
    lan: opts.localConnection !== false,
    firewall: FIREWALL.UNKNOWN,
    rawStream: dht.createRawStream({ framed: true, firewall }),
    connect: null,
    query: null,
    puncher: null,
    payload: null,
    passiveConnectTimeout: null,
    serverSocket: null,
    serverAddress: null,
    onsocket: null,
    sleeper: new Sleeper(),
    encryptedSocket,

    // Relay state
    relayTimeout: null,
    relayThrough,
    relayToken: relayThrough ? relay.token() : null,
    relaySocket: null,
    relayClient: null,
    relayPaired: false,
    validUpgrade: true,
    relayKeepAlive: opts.relayKeepAlive || 5000
  }

  // If the raw stream receives an error signal pre connect (ie from the firewall hook), make sure
  // to forward that to the encrypted socket for proper teardown
  c.rawStream.on('error', autoDestroy)
  c.rawStream.once('connect', () => {
    c.rawStream.removeListener('error', autoDestroy)
  })

  encryptedSocket.on('close', function () {
    if (c.passiveConnectTimeout) clearPassiveConnectTimeout(c)
    if (c.query) c.query.destroy()
    if (c.puncher) c.puncher.destroy()
    if (c.rawStream) c.rawStream.destroy()
    c.session.destroy()
    c.sleeper.resume()
  })

  // Safe to run in the background - never throws
  if (dht.suspended) encryptedSocket.destroy(SUSPENDED())
  else connectAndHolepunch(c, opts)

  return encryptedSocket

  function autoDestroy(err) {
    maybeDestroyEncryptedSocket(c, err)
  }

  function firewall(socket, port, host) {
    // Check if the traffic originated from the socket on which we're expecting relay traffic. If so,
    // we haven't hole punched yet and the other side is just sending us traffic through the relay.
    if (c.relaySocket && isRelay(c.relaySocket, socket, port, host)) {
      c.validUpgrade = false
      return false
    }

    c.validUpgrade = true
    if (c.onsocket) {
      c.onsocket(socket, port, host)
    } else {
      c.serverSocket = socket
      c.serverAddress = { port, host }
    }
    return false
  }
}

function isDone(c) {
  // we are destroying or the puncher is connected - done
  if (c.encryptedSocket.destroying || !!(c.puncher && c.puncher.connected)) {
    return true
  }
  // not destroying, but no raw stream - def not done
  if (c.encryptedSocket.rawStream === null) {
    return false
  }
  // we are relayed, but the puncher is not done yet
  if (c.relaySocket && !!(c.puncher && !c.puncher.connected && !c.puncher.destroyed)) {
    return false
  }
  // we are done
  return true
}

async function retryRoute(c, route) {
  const ref = c.dht._socketPool.lookup(route.socket)

  if (!ref) {
    if (route.socket === c.dht.socket) {
      await connectThroughNode(c, route.address, c.dht.socket)
    }
    return
  }

  ref.active()

  try {
    await connectThroughNode(c, route.address, route.socket)
  } catch {
    // if error, just ignore, and continue through the existing strat
  }

  ref.inactive()
}

async function connectAndHolepunch(c, opts) {
  const route = c.reusableSocket ? c.dht._socketPool.routes.get(c.remotePublicKey) : null

  if (route) {
    await retryRoute(c, route)
    if (isDone(c)) return
  }

  await findAndConnect(c, opts)
  if (isDone(c)) return

  if (!c.connect) {
    // TODO: just a quick fix for now, should retry prob
    maybeDestroyEncryptedSocket(c, HANDSHAKE_INVALID())
    return
  }

  await holepunch(c, opts)
}

function getFirstRemoteAddress(addrs, serverAddress) {
  for (const addr of addrs) {
    if (isBogon(addr.host)) continue
    return addr
  }

  return serverAddress
}

async function holepunch(c, opts) {
  let { relayAddress, serverAddress, clientAddress, payload } = c.connect

  const remoteHolepunchable = !!(payload.holepunch && payload.holepunch.relays.length)
  const relayed = diffAddress(serverAddress, relayAddress)

  if (payload.firewall === FIREWALL.OPEN || (relayed && !remoteHolepunchable)) {
    const addr = getFirstRemoteAddress(payload.addresses4, serverAddress)
    if (addr) {
      const socket = c.dht.socket
      c.dht.stats.punches.open++
      c.onsocket(socket, addr.port, addr.host)
      return
    }
    // TODO: check all addresses also obvs
  }

  const onabort = () => {
    c.session.destroy()
    maybeDestroyEncryptedSocket(c, HOLEPUNCH_ABORTED())
  }

  if (c.firewall === FIREWALL.OPEN) {
    c.passiveConnectTimeout = setTimeout(onabort, 10000)
    return
  }

  // Race the LAN shortcut with normal holepunch when possible. A blocked LAN ping
  // should not abort a connection that can still holepunch. If the remote is not
  // holepunchable, the LAN ping is the only remaining path.
  if (c.lan && relayed && clientAddress.host === serverAddress.host) {
    const serverAddresses = payload.addresses4.filter(onlyNonReserved)

    if (serverAddresses.length > 0) {
      const myAddresses = Holepuncher.localAddresses(c.dht.io.serverSocket)
      const addr = Holepuncher.matchAddress(myAddresses, serverAddresses) || serverAddresses[0]

      const socket = c.dht.io.serverSocket
      c.dht.ping(addr).then(onlanconnect, onlanerror)
      if (!remoteHolepunchable) return

      function onlanconnect() {
        // LAN and holepunch completions both converge through onsocket,
        // which claims c.rawStream once and ignores later winners.
        if (isDone(c)) return
        c.onsocket(socket, addr.port, addr.host)
      }

      function onlanerror() {
        if (!remoteHolepunchable) {
          maybeDestroyEncryptedSocket(c, HOLEPUNCH_ABORTED())
        }
      }
    }
  }

  if (!remoteHolepunchable) {
    maybeDestroyEncryptedSocket(c, CANNOT_HOLEPUNCH())
    return
  }

  c.puncher = new Holepuncher(c.dht, c.session, true, payload.firewall)

  c.puncher.onconnect = c.onsocket
  c.puncher.onabort = onabort

  const serverRelay = pickServerRelay(payload.holepunch.relays, relayAddress)

  // Begin holepunching!

  let probe
  try {
    probe = await probeRound(c, opts.fastOpen === false ? null : serverAddress, serverRelay, true)
  } catch (err) {
    destroyPuncher(c)
    // TODO: we should retry here with some of the other relays, bail for now
    maybeDestroyEncryptedSocket(c, err)
    return
  }

  if (isDone(c) || !probe) return
  const { token, peerAddress } = probe

  // If the relay the server picked is the same as the relay the client picked,
  // then we can use the peerAddress that round one indicates the server wants to use.
  // This shaves off a roundtrip if the server chose to reroll its socket due to some NAT
  // issue with the first one it picked (ie mobile nat inconsistencies...).
  // If the relays were different, then the server would not have a UDP session open on this address
  // to the client relay, which round2 uses.
  if (
    !diffAddress(serverRelay.relayAddress, relayAddress) &&
    diffAddress(serverAddress, peerAddress)
  ) {
    serverAddress = peerAddress
    await c.puncher.openSession(serverAddress)
    if (isDone(c)) return
  }

  // TODO: still continue here if a local connection might work, but then do not holepunch...
  if (
    opts.holepunch &&
    !opts.holepunch(
      c.puncher.remoteFirewall,
      c.puncher.nat.firewall,
      c.puncher.remoteAddresses,
      c.puncher.nat.addresses
    )
  ) {
    await abort(c, serverRelay, HOLEPUNCH_ABORTED('Client aborted holepunch'))
    return
  }

  try {
    await roundPunch(c, serverAddress, token, relayAddress, serverRelay, false)
  } catch (err) {
    destroyPuncher(c)
    // TODO: retry with another relay?
    maybeDestroyEncryptedSocket(c, err)
  }
}

async function connectThroughNodes(c, addresses, socket) {
  for (const address of addresses) {
    if (isDone(c) || c.connect) return

    c.remoteRelayAddresses.push(address)
    await connectThroughNode(c, address, socket)
  }
}

async function findAndConnect(c, opts) {
  let attempts = 0
  let relayAddresses =
    opts.relayAddresses && opts.relayAddresses.length ? opts.relayAddresses : null

  if (!relayAddresses) {
    const cachedRelayAddresses = c.dht._relayAddressesCache.get(c.id)
    if (cachedRelayAddresses) relayAddresses = cachedRelayAddresses
  }

  if (c.dht._persistent) {
    // check if we know the route ourself...
    const route = c.dht._router.get(c.target)
    if (route && route.relay !== null) {
      relayAddresses = [{ host: route.relay.host, port: route.relay.port }]
    }
  }

  // 2 is how many parallel connect attempts we want to do, we can make this configurable
  const preConnect = relayAddresses !== null && relayAddresses.length > 0
  const sem = new Semaphore(preConnect ? 3 : 2)
  const signal = sem.signal.bind(sem)
  const tries = relayAddresses !== null ? 2 : 1

  if (preConnect) {
    await sem.wait()
    connectThroughNodes(c, relayAddresses, null).then(signal, signal)
  }

  try {
    for (let i = 0; i < tries && !isDone(c) && !c.connect; i++) {
      c.query = c.dht.findPeer(c.target, {
        hash: false,
        session: c.session,
        nodes: relayAddresses,
        retries: 3
      })

      for await (const data of c.query) {
        await sem.wait()
        if (isDone(c)) return

        if (c.connect) {
          sem.signal()
          break
        }

        // Skip node already run via preConnect
        if (preConnect && relayAddresses && isRelayAddress(relayAddresses, data)) {
          sem.signal()
          continue
        }

        c.remoteRelayAddresses.push(data.from)
        attempts++
        connectThroughNode(c, data.from, null).then(signal, signal)
      }

      relayAddresses = null

      if (attempts > 0) await sem.flush()
    }

    c.query = null
    if (isDone(c)) return

    // flush the semaphore
    await sem.flush()
    if (isDone(c)) return
  } catch (err) {
    c.query = null
    maybeDestroyEncryptedSocket(c, err)
    return
  }

  if (!c.connect) {
    maybeDestroyEncryptedSocket(c, attempts ? PEER_CONNECTION_FAILED() : PEER_NOT_FOUND())
  }
}

async function connectThroughNode(c, address, socket) {
  if (!c.requesting) {
    // If we have a stable server address, send it over now
    const addr = c.dht.remoteAddress()
    const localAddrs = c.lan ? Holepuncher.localAddresses(c.dht.io.serverSocket) : null
    const addresses4 = []

    if (addr) addresses4.push(addr)
    if (localAddrs) addresses4.push(...localAddrs)

    c.firewall = addr ? FIREWALL.OPEN : FIREWALL.UNKNOWN
    c.requesting = true
    c.request = await c.handshake.send({
      error: ERROR.NONE,
      firewall: c.firewall,
      holepunch: null,
      addresses4,
      addresses6: [],
      udx: {
        reusableSocket: c.reusableSocket,
        id: c.rawStream.id,
        seq: 0
      },
      secretStream: {},
      relayThrough: c.relayThrough ? { publicKey: c.relayThrough, token: c.relayToken } : null
    })
    if (isDone(c)) return
  }

  const { serverAddress, clientAddress, relayed, noise } = await c.dht._router.peerHandshake(
    c.target,
    { noise: c.request, socket, session: c.session },
    address
  )
  if (isDone(c) || c.connect) return

  const payload = await c.handshake.recv(noise)
  if (isDone(c) || !payload) return

  if (payload.version !== 1) {
    maybeDestroyEncryptedSocket(c, SERVER_INCOMPATIBLE())
    return
  }
  if (payload.error !== ERROR.NONE) {
    maybeDestroyEncryptedSocket(c, SERVER_ERROR())
    return
  }
  if (!payload.udx) {
    maybeDestroyEncryptedSocket(c, SERVER_ERROR('Server did not send UDX data'))
    return
  }

  const hs = c.handshake.final()

  c.handshake = null
  c.request = null
  c.requesting = false
  c.connect = {
    relayed,
    relayAddress: address,
    clientAddress,
    serverAddress,
    payload
  }

  c.payload = new SecurePayload(hs.holepunchSecret)

  c.onsocket = function (socket, port, host) {
    if (c.rawStream === null) return // Already hole punched

    if (c.rawStream.connected) {
      const rawStream = c.rawStream
      const remoteChanging = rawStream.changeRemote(socket, c.connect.payload.udx.id, port, host)
      confirmDirectUpgrade(c, rawStream, remoteChanging)
    } else {
      // cache the relay addrs for a future reconnect, we prefer the remote one so they
      // can give us the correct ones from their pov
      if (payload.relayAddresses && payload.relayAddresses.length) {
        c.dht._relayAddressesCache.set(c.id, payload.relayAddresses)
      } else if (c.remoteRelayAddresses.length) {
        c.dht._relayAddressesCache.set(c.id, c.remoteRelayAddresses)
      }

      c.rawStream.connect(socket, c.connect.payload.udx.id, port, host)
      c.encryptedSocket.start(c.rawStream, { handshake: hs })
    }

    if (c.reusableSocket && payload.udx.reusableSocket) {
      c.dht._socketPool.routes.add(c.remotePublicKey, c.rawStream)
    }

    if (c.puncher) {
      c.puncher.onabort = noop
      c.puncher.destroy()
    }

    if (c.passiveConnectTimeout) {
      clearPassiveConnectTimeout(c)
    }

    c.rawStream = null
  }

  if (payload.relayThrough || c.relayThrough) {
    relayConnection(c, c.relayThrough, payload, hs)
  }

  if (c.serverSocket) {
    c.onsocket(c.serverSocket, c.serverAddress.port, c.serverAddress.host)
    return
  }

  if (!relayed) {
    c.onsocket(socket || c.dht.socket, address.port, address.host)
  }

  c.session.destroy()
}

async function updateHolepunch(c, peerAddress, relayAddr, payload) {
  const holepunch = await c.dht._router.peerHolepunch(
    c.target,
    {
      id: c.connect.payload.holepunch.id,
      payload: c.payload.encrypt(payload),
      peerAddress,
      socket: c.puncher.socket,
      session: c.session
    },
    relayAddr
  )

  if (isDone(c)) return null

  const remotePayload = c.payload.decrypt(holepunch.payload)
  if (!remotePayload) {
    throw HOLEPUNCH_INVALID()
  }

  const { error, firewall, punching, addresses, remoteToken } = remotePayload

  if (error === ERROR.TRY_LATER && c.relayToken && payload.punching) {
    return {
      tryLater: true,
      ...holepunch,
      payload: remotePayload
    }
  }

  if (error !== ERROR.NONE) {
    throw REMOTE_ABORTED('Remote aborted with error code ' + error)
  }

  const echoed = !!(remoteToken && payload.token && b4a.equals(remoteToken, payload.token))

  c.puncher.updateRemote({
    punching,
    firewall,
    addresses,
    verified: echoed ? peerAddress.host : null
  })

  return {
    tryLater: false,
    ...holepunch,
    payload: remotePayload
  }
}

async function probeRound(c, serverAddress, serverRelay, retry) {
  // Open a quick low ttl session against what we think is the server
  if (serverAddress) await c.puncher.openSession(serverAddress)

  if (isDone(c)) return null

  const reply = await updateHolepunch(c, serverRelay.peerAddress, serverRelay.relayAddress, {
    error: ERROR.NONE,
    firewall: c.puncher.nat.firewall,
    round: c.round++,
    connected: false,
    punching: false,
    addresses: c.puncher.nat.addresses,
    remoteAddress: serverAddress,
    token: null,
    remoteToken: null
  })

  if (isDone(c) || !reply) return null

  const { peerAddress } = reply
  const { address, token } = reply.payload

  c.puncher.nat.add(reply.to, reply.from)

  // Open another quick low ttl session against what the server says their address is,
  // if they haven't said they are random yet
  if (
    c.puncher.remoteFirewall < FIREWALL.RANDOM &&
    address &&
    address.host &&
    address.port &&
    diffAddress(address, serverAddress)
  ) {
    await c.puncher.openSession(address)
    if (isDone(c)) return null
  }

  // If the remote told us they didn't know their nat firewall yet, give them a chance to figure it out
  // They might say this to see if the "fast mode" punch comes through first.
  if (c.puncher.remoteFirewall === FIREWALL.UNKNOWN) {
    await c.sleeper.pause(1000)
    if (isDone(c)) return null
  }

  let stable = await c.puncher.analyze(false)
  if (isDone(c)) return null

  // If the socket seems unstable, try to make it stable by setting the "allowReopen" flag
  // Mostly relevant for mobile networks
  if (!stable) {
    stable = await c.puncher.analyze(true)
    if (isDone(c)) return null
    if (stable) return probeRound(c, serverAddress, serverRelay, false)
  }

  if ((c.puncher.remoteFirewall === FIREWALL.UNKNOWN || !token) && retry) {
    return probeRound(c, serverAddress, serverRelay, false)
  }

  if (
    c.puncher.remoteFirewall === FIREWALL.UNKNOWN ||
    c.puncher.nat.firewall === FIREWALL.UNKNOWN
  ) {
    await abort(c, serverRelay, HOLEPUNCH_PROBE_TIMEOUT())
    return null
  }

  if (c.puncher.remoteFirewall >= FIREWALL.RANDOM && c.puncher.nat.firewall >= FIREWALL.RANDOM) {
    await abort(c, serverRelay, HOLEPUNCH_DOUBLE_RANDOMIZED_NATS())
    return null
  }

  return { token, peerAddress }
}

async function roundPunch(c, serverAddress, remoteToken, clientRelay, serverRelay, delayed) {
  // We are gossiping our final NAT status to the other peer now
  // so make sure we don't update our local view for now as that can make things weird
  c.puncher.nat.freeze()

  const isRandom =
    c.puncher.remoteFirewall >= FIREWALL.RANDOM || c.puncher.nat.firewall >= FIREWALL.RANDOM
  if (isRandom) {
    while (
      c.dht._randomPunches >= c.dht._randomPunchLimit ||
      Date.now() - c.dht._lastRandomPunch < c.dht._randomPunchInterval
    ) {
      // if no relay can help, bail
      if (!c.relayToken) throw HOLEPUNCH_ABORTED()

      if (!delayed) {
        delayed = true
        await updateHolepunch(c, serverAddress, clientRelay, {
          error: ERROR.NONE,
          firewall: c.puncher.nat.firewall,
          round: c.round++,
          connected: false,
          punching: false,
          addresses: c.puncher.nat.addresses,
          remoteAddress: null,
          token: c.payload.token(serverAddress),
          remoteToken
        })
        if (isDone(c)) return
      }

      await tryLater(c)
      if (isDone(c)) return
    }
  }

  // increment now, so we can commit to punching
  if (isRandom) c.dht._randomPunches++

  let reply

  try {
    // if delayed switch to the servers chosen relay - we validated anyway
    reply = await updateHolepunch(
      c,
      delayed ? serverRelay.peerAddress : serverAddress,
      delayed ? serverRelay.relayAddress : clientRelay,
      {
        error: ERROR.NONE,
        firewall: c.puncher.nat.firewall,
        round: c.round++,
        connected: false,
        punching: true,
        addresses: c.puncher.nat.addresses,
        remoteAddress: null,
        token: delayed ? null : c.payload.token(serverAddress),
        remoteToken
      }
    )
  } finally {
    // decrement as punch increments for us
    if (isRandom) c.dht._randomPunches--
  }

  if (isDone(c)) return
  if (!reply) return

  if (reply.tryLater) {
    await tryLater(c)
    if (isDone(c)) return
    return roundPunch(c, serverAddress, remoteToken, clientRelay, serverRelay, true)
  }

  if (!c.puncher.remoteHolepunching) {
    throw REMOTE_NOT_HOLEPUNCHING()
  }

  if (!(await c.puncher.punch())) {
    throw REMOTE_NOT_HOLEPUNCHABLE()
  }
}

async function tryLater(c) {
  if (!c.relayToken) throw HOLEPUNCH_ABORTED()
  await c.sleeper.pause(10000 + Math.round(Math.random() * 10000))
}

function maybeDestroyEncryptedSocket(c, err) {
  if (isDone(c)) return
  if (c.encryptedSocket.rawStream) return
  if (c.relaySocket) return // waiting for the relay
  if (c.puncher && !c.puncher.destroyed) return // waiting for the puncher
  c.session.destroy()
  c.encryptedSocket.destroy(err)
}

async function abort(c, { peerAddress, relayAddress }, err) {
  try {
    await updateHolepunch(c, peerAddress, relayAddress, {
      error: ERROR.ABORTED,
      firewall: FIREWALL.UNKNOWN,
      round: c.round++,
      connected: false,
      punching: false,
      addresses: null,
      remoteAddress: null,
      token: null,
      remoteToken: null
    })
  } catch (err) {
    safetyCatch(err)
  }

  destroyPuncher(c)
  maybeDestroyEncryptedSocket(c, err)
}

function relayConnection(c, relayThrough, payload, hs) {
  let isInitiator
  let publicKey
  let token

  if (payload.relayThrough) {
    isInitiator = false
    publicKey = payload.relayThrough.publicKey
    token = payload.relayThrough.token
  } else {
    isInitiator = true
    publicKey = relayThrough
    token = c.relayToken
  }

  c.relayToken = token
  c.relaySocket = c.dht.connect(publicKey)
  c.relaySocket.setKeepAlive(c.relayKeepAlive)
  c.relayClient = relay.Client.from(c.relaySocket, { id: c.relaySocket.publicKey })
  c.relayTimeout = setTimeout(onabort, 15000, null)

  c.relayClient.pair(isInitiator, token, c.rawStream).on('error', onabort).on('data', ondata)

  function ondata(remoteId) {
    if (c.relayTimeout) clearRelayTimeout(c)
    if (c.rawStream === null) {
      onabort(null)
      return
    }

    c.relayPaired = true

    const { remotePort, remoteHost, socket } = c.relaySocket.rawStream

    c.rawStream
      .on('close', () => destroyRelayConnection(c))
      .connect(socket, remoteId, remotePort, remoteHost)

    c.encryptedSocket.start(c.rawStream, { handshake: hs })
  }

  function onabort(err) {
    destroyRelayConnection(c)
    maybeDestroyEncryptedSocket(c, err || RELAY_ABORTED())
  }
}

function clearPassiveConnectTimeout(c) {
  clearTimeout(c.passiveConnectTimeout)
  c.passiveConnectTimeout = null
}

function destroyPuncher(c) {
  if (c.puncher) c.puncher.destroy()
  c.session.destroy()
}

function pickServerRelay(relays, clientRelay) {
  for (const r of relays) {
    if (!diffAddress(r.relayAddress, clientRelay)) return r
  }
  return relays[0]
}

function diffAddress(a, b) {
  return a.host !== b.host || a.port !== b.port
}

function defaultCreateHandshake(keyPair, remotePublicKey) {
  return new NoiseWrap(keyPair, remotePublicKey)
}

function defaultCreateSecretStream(isInitiator, rawStream, opts) {
  return new NoiseSecretStream(isInitiator, rawStream, opts)
}

function onlyNonReserved(addr) {
  return !isReserved(addr.host)
}

function isRelay(relaySocket, socket, port, host) {
  const stream = relaySocket.rawStream
  if (!stream) return false
  if (stream.socket !== socket) return false
  return port === stream.remotePort && host === stream.remoteHost
}

function selectRelay(relayThrough) {
  if (typeof relayThrough === 'function') relayThrough = relayThrough()
  if (relayThrough === null) return null
  if (Array.isArray(relayThrough))
    return relayThrough[Math.floor(Math.random() * relayThrough.length)]
  return relayThrough
}

function isRelayAddress(relayAddresses, data) {
  for (const node of relayAddresses) {
    if (node.host === data.from.host && node.port === data.from.port) return true
  }

  return false
}

function noop() {}
const EventEmitter = require('events')
const b4a = require('b4a')
const errors = require('./errors')

module.exports = class ConnectionPool extends EventEmitter {
  constructor(dht) {
    super()

    this._dht = dht
    this._servers = new Map()
    this._connecting = new Map()
    this._connections = new Map()
  }

  _attachServer(server) {
    const keyString = b4a.toString(server.publicKey, 'hex')

    this._servers.set(keyString, server)

    server
      .on('close', () => {
        this._servers.delete(keyString)
      })
      .on('connection', (socket) => {
        this._attachStream(socket, true)
      })
  }

  _attachStream(stream, opened) {
    const existing = this.get(stream.remotePublicKey)

    if (existing) {
      const keepNew =
        stream.isInitiator === existing.isInitiator ||
        b4a.compare(stream.publicKey, stream.remotePublicKey) > 0

      if (keepNew) {
        let closed = false

        const onclose = () => {
          closed = true
        }

        existing
          .on('error', noop)
          .on('close', () => {
            if (closed) return

            stream.off('error', noop).off('close', onclose)

            this._attachStream(stream, opened)
          })
          .destroy(errors.DUPLICATE_CONNECTION())

        stream.on('error', noop).on('close', onclose)
      } else {
        stream.on('error', noop).destroy(errors.DUPLICATE_CONNECTION())
      }

      return
    }

    const session = new ConnectionRef(this, stream)

    const keyString = b4a.toString(stream.remotePublicKey, 'hex')

    if (opened) {
      this._connections.set(keyString, session)

      stream.on('close', () => {
        this._connections.delete(keyString)
      })

      this.emit('connection', stream, session)
    } else {
      this._connecting.set(keyString, session)

      stream
        .on('error', noop)
        .on('close', () => {
          if (opened) this._connections.delete(keyString)
          else this._connecting.delete(keyString)
        })
        .on('open', () => {
          opened = true

          this._connecting.delete(keyString)
          this._connections.set(keyString, session)

          stream.off('error', noop)

          this.emit('connection', stream, session)
        })
    }

    return session
  }

  get connecting() {
    return this._connecting.size
  }

  get connections() {
    return this._connections.values()
  }

  has(publicKey) {
    const keyString = b4a.toString(publicKey, 'hex')

    return this._connections.has(keyString) || this._connecting.has(keyString)
  }

  get(publicKey) {
    const keyString = b4a.toString(publicKey, 'hex')

    const existing = this._connections.get(keyString) || this._connecting.get(keyString)

    return existing?._stream || null
  }
}

class ConnectionRef {
  constructor(pool, stream) {
    this._pool = pool
    this._stream = stream
    this._refs = 0
  }

  active() {
    this._refs++
  }

  inactive() {
    this._refs--
  }

  release() {
    this._stream.destroy()
  }
}

function noop() {}
const crypto = require('hypercore-crypto')

const COMMANDS = (exports.COMMANDS = {
  PEER_HANDSHAKE: 0,
  PEER_HOLEPUNCH: 1,
  FIND_PEER: 2,
  LOOKUP: 3,
  ANNOUNCE: 4,
  UNANNOUNCE: 5,
  MUTABLE_PUT: 6,
  MUTABLE_GET: 7,
  IMMUTABLE_PUT: 8,
  IMMUTABLE_GET: 9,
  PLUGIN: 10
})

exports.BOOTSTRAP_NODES = [
  '88.99.3.86@node1.hyperdht.org:49737',
  '142.93.90.113@node2.hyperdht.org:49737',
  '138.68.147.8@node3.hyperdht.org:49737'
]

exports.FIREWALL = {
  UNKNOWN: 0,
  OPEN: 1,
  CONSISTENT: 2,
  RANDOM: 3
}

exports.ERROR = {
  // noise / connection related
  NONE: 0,
  ABORTED: 1,
  VERSION_MISMATCH: 2,
  TRY_LATER: 3,
  // dht related
  SEQ_REUSED: 16,
  SEQ_TOO_LOW: 17
}

const [
  NS_ANNOUNCE,
  NS_UNANNOUNCE,
  NS_MUTABLE_PUT,
  NS_PEER_HANDSHAKE,
  NS_PEER_HOLEPUNCH,
  NS_PLUGIN
] = crypto.namespace('hyperswarm/dht', [
  COMMANDS.ANNOUNCE,
  COMMANDS.UNANNOUNCE,
  COMMANDS.MUTABLE_PUT,
  COMMANDS.PEER_HANDSHAKE,
  COMMANDS.PEER_HOLEPUNCH,
  COMMANDS.PLUGIN
])

exports.NS = {
  ANNOUNCE: NS_ANNOUNCE,
  UNANNOUNCE: NS_UNANNOUNCE,
  MUTABLE_PUT: NS_MUTABLE_PUT,
  PEER_HANDSHAKE: NS_PEER_HANDSHAKE,
  PEER_HOLEPUNCH: NS_PEER_HOLEPUNCH,
  PLUGIN: NS_PLUGIN
}
const sodium = require('sodium-universal')
const b4a = require('b4a')

function hash(data) {
  const out = b4a.allocUnsafe(32)
  sodium.crypto_generichash(out, data)
  return out
}

function unslabbedHash(data) {
  const out = b4a.allocUnsafeSlow(32)
  sodium.crypto_generichash(out, data)
  return out
}

function createKeyPair(seed) {
  const publicKey = b4a.alloc(32)
  const secretKey = b4a.alloc(64)
  if (seed) sodium.crypto_sign_seed_keypair(publicKey, secretKey, seed)
  else sodium.crypto_sign_keypair(publicKey, secretKey)
  return { publicKey, secretKey }
}

module.exports = {
  hash,
  unslabbedHash,
  createKeyPair
}
const b4a = require('b4a')
const cenc = require('compact-encoding')

function encodeUnslab(enc, m) {
  // Faster than unslab(c.encode(enc, data)) because it avoids the mem copy.
  // Makes sense to put in compact-encoding when we need it in other modules too
  const state = cenc.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafeSlow(state.end)
  enc.encode(state, m)
  return state.buffer
}

module.exports = {
  encodeUnslab
}
module.exports = class DHTError extends Error {
  constructor(msg, code, fn = DHTError) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'DHTError'
  }

  static BAD_HANDSHAKE_REPLY(msg = 'Bad handshake reply') {
    return new DHTError(msg, 'BAD_HANDSHAKE_REPLY', DHTError.BAD_HANDSHAKE_REPLY)
  }

  static BAD_HOLEPUNCH_REPLY(msg = 'Bad holepunch reply') {
    return new DHTError(msg, 'BAD_HOLEPUNCH_REPLY', DHTError.BAD_HOLEPUNCH_REPLY)
  }

  static HOLEPUNCH_ABORTED(msg = 'Holepunch aborted') {
    return new DHTError(msg, 'HOLEPUNCH_ABORTED', DHTError.HOLEPUNCH_ABORTED)
  }

  static HOLEPUNCH_INVALID(msg = 'Invalid holepunch payload') {
    return new DHTError(msg, 'HOLEPUNCH_INVALID', DHTError.HOLEPUNCH_INVALID)
  }

  static HOLEPUNCH_PROBE_TIMEOUT(msg = 'Holepunching probe did not finish in time') {
    return new DHTError(msg, 'HOLEPUNCH_PROBE_TIMEOUT', DHTError.HOLEPUNCH_PROBE_TIMEOUT)
  }

  static HOLEPUNCH_DOUBLE_RANDOMIZED_NATS(msg = 'Both remote and local NATs are randomized') {
    return new DHTError(
      msg,
      'HOLEPUNCH_DOUBLE_RANDOMIZED_NATS',
      DHTError.HOLEPUNCH_DOUBLE_RANDOMIZED_NATS
    )
  }

  static CANNOT_HOLEPUNCH(msg = 'Cannot holepunch to remote') {
    return new DHTError(msg, 'CANNOT_HOLEPUNCH', DHTError.CANNOT_HOLEPUNCH)
  }

  static REMOTE_NOT_HOLEPUNCHING(msg = 'Remote is not holepunching') {
    return new DHTError(msg, 'REMOTE_NOT_HOLEPUNCHING', DHTError.REMOTE_NOT_HOLEPUNCHING)
  }

  static REMOTE_NOT_HOLEPUNCHABLE(msg = 'Remote is not holepunchable') {
    return new DHTError(msg, 'REMOTE_NOT_HOLEPUNCHABLE', DHTError.REMOTE_NOT_HOLEPUNCHABLE)
  }

  static REMOTE_ABORTED(msg = 'Remote aborted') {
    return new DHTError(msg, 'REMOTE_ABORTED', DHTError.REMOTE_ABORTED)
  }

  static HANDSHAKE_UNFINISHED(msg = 'Handshake did not finish') {
    return new DHTError(msg, 'HANDSHAKE_UNFINISHED', DHTError.HANDSHAKE_UNFINISHED)
  }

  static HANDSHAKE_INVALID(msg = 'Received invalid handshake') {
    return new DHTError(msg, 'HANDSHAKE_INVALID', DHTError.HANDSHAKE_INVALID)
  }

  static ALREADY_LISTENING(msg = 'Already listening') {
    return new DHTError(msg, 'ALREADY_LISTENING', DHTError.ALREADY_LISTENING)
  }

  static KEYPAIR_ALREADY_USED(msg = 'Keypair already used') {
    return new DHTError(msg, 'KEYPAIR_ALREADY_USED', DHTError.KEYPAIR_ALREADY_USED)
  }

  static NODE_DESTROYED(msg = 'Node destroyed') {
    return new DHTError(msg, 'NODE_DESTROYED', DHTError.NODE_DESTROYED)
  }

  static PEER_CONNECTION_FAILED(msg = 'Could not connect to peer') {
    return new DHTError(msg, 'PEER_CONNECTION_FAILED', DHTError.PEER_CONNECTION_FAILED)
  }

  static PEER_NOT_FOUND(msg = 'Peer not found') {
    return new DHTError(msg, 'PEER_NOT_FOUND', DHTError.PEER_NOT_FOUND)
  }

  static STREAM_NOT_CONNECTED(msg = 'Stream is not connected') {
    return new DHTError(msg, 'STREAM_NOT_CONNECTED', DHTError.STREAM_NOT_CONNECTED)
  }

  static SERVER_INCOMPATIBLE(msg = 'Server is using an incompatible version') {
    return new DHTError(msg, 'SERVER_INCOMPATIBLE', DHTError.SERVER_INCOMPATIBLE)
  }

  static SERVER_ERROR(msg = 'Server returned an error') {
    return new DHTError(msg, 'SERVER_ERROR', DHTError.SERVER_ERROR)
  }

  static DUPLICATE_CONNECTION(msg = 'Duplicate connection') {
    return new DHTError(msg, 'DUPLICATE_CONNECTION', DHTError.DUPLICATE_CONNECTION)
  }

  static RELAY_ABORTED(msg = 'Relay aborted') {
    return new DHTError(msg, 'RELAY_ABORTED', DHTError.RELAY_ABORTED)
  }

  static SUSPENDED(msg = 'Suspended') {
    return new DHTError(msg, 'SUSPENDED', DHTError.SUSPENDED)
  }
}
const b4a = require('b4a')
const Nat = require('./nat')
const Sleeper = require('./sleeper')
const { FIREWALL } = require('./constants')

const BIRTHDAY_SOCKETS = 256
const HOLEPUNCH = b4a.from([0])
const HOLEPUNCH_TTL = 5
const DEFAULT_TTL = 64
const MAX_REOPENS = 3

module.exports = class Holepuncher {
  constructor(dht, session, isInitiator, remoteFirewall = FIREWALL.UNKNOWN) {
    const holder = dht._socketPool.acquire()

    this.dht = dht
    this.session = session

    this.nat = new Nat(dht, session, holder.socket)
    this.nat.autoSample()

    this.isInitiator = isInitiator

    // events
    this.onconnect = noop
    this.onabort = noop

    this.punching = false
    this.connected = false
    this.destroyed = false
    this.randomized = false

    // track remote state
    this.remoteFirewall = remoteFirewall
    this.remoteAddresses = []
    this.remoteHolepunching = false

    this._sleeper = new Sleeper()
    this._reopening = null
    this._timeout = null
    this._punching = null
    this._allHolders = []
    this._holder = this._addRef(holder)
  }

  get socket() {
    return this._holder.socket
  }

  updateRemote({ punching, firewall, addresses, verified }) {
    const remoteAddresses = []

    if (addresses) {
      for (const addr of addresses) {
        remoteAddresses.push({
          host: addr.host,
          port: addr.port,
          verified: verified === addr.host || this._isVerified(addr.host)
        })
      }
    }

    this.remoteFirewall = firewall
    this.remoteAddresses = remoteAddresses
    this.remoteHolepunching = punching
  }

  _isVerified(host) {
    for (const addr of this.remoteAddresses) {
      if (addr.verified && addr.host === host) {
        return true
      }
    }
    return false
  }

  ping(addr, socket = this._holder.socket) {
    return holepunch(socket, addr, false)
  }

  openSession(addr, socket = this._holder.socket) {
    return holepunch(socket, addr, true)
  }

  async analyze(allowReopen) {
    await this.nat.analyzing
    if (this._unstable()) {
      if (!allowReopen) return false
      if (!this._reopening) this._reopening = this._reopen()
      return this._reopening
    }
    return true
  }

  _unstable() {
    // TODO!!: We need an additional heuristic here... If we were NOT random in the past we should also do this.
    const firewall = this.nat.firewall
    return (
      (this.remoteFirewall >= FIREWALL.RANDOM && firewall >= FIREWALL.RANDOM) ||
      firewall === FIREWALL.UNKNOWN
    )
  }

  _reset() {
    const prev = this._holder

    this._allHolders.pop()
    this._holder = this._addRef(this.dht._socketPool.acquire())

    prev.release()
    this.nat.destroy()

    this.nat = new Nat(this.dht, this.session, this._holder.socket)
    // TODO: maybe make auto sampling configurable somehow?
    this.nat.autoSample()
  }

  _addRef(ref) {
    this._allHolders.push(ref)
    ref.onholepunchmessage = (msg, rinfo) => this._onholepunchmessage(msg, rinfo, ref)
    return ref
  }

  _onholepunchmessage(_, addr, ref) {
    if (!this.isInitiator) {
      // TODO: we don't need this if we had a way to connect a socket to many hosts
      holepunch(ref.socket, addr, false) // never fails
      return
    }

    if (this.connected) return

    this.connected = true
    this.punching = false

    for (const r of this._allHolders) {
      if (r === ref) continue
      r.release()
    }

    this._allHolders[0] = ref
    while (this._allHolders.length > 1) this._allHolders.pop()

    this._decrementRandomized()
    this.onconnect(ref.socket, addr.port, addr.host)
  }

  _done() {
    return this.destroyed || this.connected
  }

  async _reopen() {
    for (let i = 0; this._unstable() && i < MAX_REOPENS && !this._done() && !this.punching; i++) {
      this._reset()
      await this.nat.analyzing
    }

    return coerceFirewall(this.nat.firewall) === FIREWALL.CONSISTENT
  }

  punch() {
    if (!this._punching) this._punching = this._punch()
    return this._punching
  }

  async _punch() {
    if (this._done() || !this.remoteAddresses.length) return false

    this.punching = true

    // Coerce into consistency for now. Obvs we could make this this more efficient if we use that info
    // but that's seldomly used since those will just use tcp most of the time.

    const local = coerceFirewall(this.nat.firewall)
    const remote = coerceFirewall(this.remoteFirewall)

    // Note that most of these async functions are meant to run in the background
    // which is why we don't await them here and why they are not allowed to throw

    let remoteVerifiedAddress = null
    for (const addr of this.remoteAddresses) {
      if (addr.verified) {
        remoteVerifiedAddress = addr
        break
      }
    }

    if (local === FIREWALL.CONSISTENT && remote === FIREWALL.CONSISTENT) {
      this.dht.stats.punches.consistent++
      this._consistentProbe()
      return true
    }

    if (!remoteVerifiedAddress) return false

    if (local === FIREWALL.CONSISTENT && remote >= FIREWALL.RANDOM) {
      this.dht.stats.punches.random++
      this._incrementRandomized()
      this._randomProbes(remoteVerifiedAddress)
      return true
    }

    if (local >= FIREWALL.RANDOM && remote === FIREWALL.CONSISTENT) {
      this.dht.stats.punches.random++
      this._incrementRandomized()
      await this._openBirthdaySockets(remoteVerifiedAddress)
      if (this.punching) this._keepAliveRandomNat(remoteVerifiedAddress)
      return true
    }

    return false
  }

  // Note that this never throws so it is safe to run in the background
  async _consistentProbe() {
    // Here we do the sleep first because the "fast open" mode in the server just fired a ping
    if (!this.isInitiator) await this._sleeper.pause(1000)

    let tries = 0

    while (this.punching && tries++ < 10) {
      for (const addr of this.remoteAddresses) {
        // only try unverified addresses every 4 ticks
        if (!addr.verified && (tries & 3) !== 0) continue
        await holepunch(this._holder.socket, addr, false)
      }
      if (this.punching) await this._sleeper.pause(1000)
    }

    this._autoDestroy()
  }

  // Note that this never throws so it is safe to run in the background
  async _randomProbes(remoteAddr) {
    let tries = 1750 // ~35s

    while (this.punching && tries-- > 0) {
      const addr = { host: remoteAddr.host, port: randomPort() }
      await holepunch(this._holder.socket, addr, false)
      if (this.punching) await this._sleeper.pause(20)
    }

    this._autoDestroy()
  }

  // Note that this never throws so it is safe to run in the background
  async _keepAliveRandomNat(remoteAddr) {
    let i = 0
    let lowTTLRounds = 1

    // TODO: experiment with this here. We just bursted all the messages in
    // openOtherSockets to ensure the sockets are open, so it's potentially
    // a good idea to slow down for a bit.
    await this._sleeper.pause(100)

    let tries = 1750 // ~35s

    while (this.punching && tries-- > 0) {
      if (i === this._allHolders.length) {
        i = 0
        if (lowTTLRounds > 0) lowTTLRounds--
      }

      await holepunch(this._allHolders[i++].socket, remoteAddr, lowTTLRounds > 0)
      if (this.punching) await this._sleeper.pause(20)
    }

    this._autoDestroy()
  }

  async _openBirthdaySockets(remoteAddr) {
    while (this.punching && this._allHolders.length < BIRTHDAY_SOCKETS) {
      const ref = this._addRef(this.dht._socketPool.acquire())
      await holepunch(ref.socket, remoteAddr, HOLEPUNCH_TTL)
    }
  }

  _autoDestroy() {
    if (!this.connected) this.destroy()
  }

  _incrementRandomized() {
    if (!this.randomized) {
      this.randomized = true
      this.dht._randomPunches++
    }
  }

  _decrementRandomized() {
    if (this.randomized) {
      this.dht._lastRandomPunch = Date.now()
      this.randomized = false
      this.dht._randomPunches--
    }
  }

  destroy() {
    if (this.destroyed) return
    this.destroyed = true
    this.punching = false

    for (const ref of this._allHolders) ref.release()
    this._allHolders = []
    this.nat.destroy()

    if (!this.connected) {
      this._decrementRandomized()
      this.onabort()
    }
  }

  static ping(socket, addr) {
    return holepunch(socket, addr, false)
  }

  static localAddresses(socket) {
    return localAddresses(socket)
  }

  static matchAddress(myAddresses, externalAddresses) {
    return matchAddress(myAddresses, externalAddresses)
  }
}

function holepunch(socket, addr, lowTTL) {
  return socket.send(HOLEPUNCH, addr.port, addr.host, lowTTL ? HOLEPUNCH_TTL : DEFAULT_TTL)
}

function randomPort() {
  return (1000 + Math.random() * 64536) | 0
}

function coerceFirewall(fw) {
  return fw === FIREWALL.OPEN ? FIREWALL.CONSISTENT : fw
}

function localAddresses(socket) {
  const addrs = []
  const { host, port } = socket.address()

  if (host === '127.0.0.1') return [{ host, port }]

  for (const n of socket.udx.networkInterfaces()) {
    if (n.family !== 4 || n.internal) continue

    addrs.push({ host: n.host, port })
  }

  if (addrs.length === 0) {
    addrs.push({ host: '127.0.0.1', port })
  }

  return addrs
}

function matchAddress(localAddresses, remoteLocalAddresses) {
  if (remoteLocalAddresses.length === 0) return null

  let best = { segment: 1, addr: null }

  for (const localAddress of localAddresses) {
    // => 192.168.122.238
    const a = localAddress.host.split('.')

    for (const remoteAddress of remoteLocalAddresses) {
      // => 192.168.0.23
      // => 192.168.122.1
      const b = remoteAddress.host.split('.')

      // Matches 192.*.*.*
      if (a[0] === b[0]) {
        if (best.segment === 1) best = { segment: 2, addr: remoteAddress }

        // Matches 192.168.*.*
        if (a[1] === b[1]) {
          if (best.segment === 2) best = { segment: 3, addr: remoteAddress }

          // Matches 192.168.122.*
          if (a[2] === b[2]) return remoteAddress
        }
      }
    }
  }

  return best.addr
}

function noop() {}
const c = require('compact-encoding')

const ipv4 = {
  ...c.ipv4Address,
  decode(state) {
    const ip = c.ipv4Address.decode(state)
    return {
      host: ip.host,
      port: ip.port
    }
  }
}

const ipv4Array = c.array(ipv4)

const ipv6 = {
  ...c.ipv6Address,
  decode(state) {
    const ip = c.ipv6Address.decode(state)
    return {
      host: ip.host,
      port: ip.port
    }
  }
}

const ipv6Array = c.array(ipv6)

exports.handshake = {
  preencode(state, m) {
    state.end += 1 + 1 + (m.peerAddress ? 6 : 0) + (m.relayAddress ? 6 : 0)
    c.buffer.preencode(state, m.noise)
  },
  encode(state, m) {
    const flags = (m.peerAddress ? 1 : 0) | (m.relayAddress ? 2 : 0)

    c.uint.encode(state, flags)
    c.uint.encode(state, m.mode)
    c.buffer.encode(state, m.noise)

    if (m.peerAddress) ipv4.encode(state, m.peerAddress)
    if (m.relayAddress) ipv4.encode(state, m.relayAddress)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      mode: c.uint.decode(state),
      noise: c.buffer.decode(state),
      peerAddress: flags & 1 ? ipv4.decode(state) : null,
      relayAddress: flags & 2 ? ipv4.decode(state) : null
    }
  }
}

const relayInfo = {
  preencode(state, m) {
    state.end += 12
  },
  encode(state, m) {
    ipv4.encode(state, m.relayAddress)
    ipv4.encode(state, m.peerAddress)
  },
  decode(state) {
    return {
      relayAddress: ipv4.decode(state),
      peerAddress: ipv4.decode(state)
    }
  }
}

const relayInfoArray = c.array(relayInfo)

const holepunchInfo = {
  preencode(state, m) {
    c.uint.preencode(state, m.id)
    relayInfoArray.preencode(state, m.relays)
  },
  encode(state, m) {
    c.uint.encode(state, m.id)
    relayInfoArray.encode(state, m.relays)
  },
  decode(state) {
    return {
      id: c.uint.decode(state),
      relays: relayInfoArray.decode(state)
    }
  }
}

const udxInfo = {
  preencode(state, m) {
    state.end += 2 // version + features
    c.uint.preencode(state, m.id)
    c.uint.preencode(state, m.seq)
  },
  encode(state, m) {
    c.uint.encode(state, 1)
    c.uint.encode(state, m.reusableSocket ? 1 : 0)
    c.uint.encode(state, m.id)
    c.uint.encode(state, m.seq)
  },
  decode(state) {
    const version = c.uint.decode(state)
    const features = c.uint.decode(state)

    return {
      version,
      reusableSocket: (features & 1) !== 0,
      id: c.uint.decode(state),
      seq: c.uint.decode(state)
    }
  }
}

const secretStreamInfo = {
  preencode(state, m) {
    c.uint.preencode(state, 1)
  },
  encode(state, m) {
    c.uint.encode(state, 1)
  },
  decode(state) {
    return {
      version: c.uint.decode(state)
    }
  }
}

const relayThroughInfo = {
  preencode(state, m) {
    c.uint.preencode(state, 1) // version
    c.uint.preencode(state, 0) // flags
    c.fixed32.preencode(state, m.publicKey)
    c.fixed32.preencode(state, m.token)
  },
  encode(state, m) {
    c.uint.encode(state, 1)
    c.uint.encode(state, 0)
    c.fixed32.encode(state, m.publicKey)
    c.fixed32.encode(state, m.token)
  },
  decode(state) {
    const version = c.uint.decode(state)
    c.uint.decode(state)

    return {
      version,
      publicKey: c.fixed32.decode(state),
      token: c.fixed32.decode(state)
    }
  }
}

exports.noisePayload = {
  preencode(state, m) {
    state.end += 4 // version + flags + error + firewall
    if (m.holepunch) holepunchInfo.preencode(state, m.holepunch)
    if (m.addresses4 && m.addresses4.length) ipv4Array.preencode(state, m.addresses4)
    if (m.addresses6 && m.addresses6.length) ipv6Array.preencode(state, m.addresses6)
    if (m.udx) udxInfo.preencode(state, m.udx)
    if (m.secretStream) secretStreamInfo.preencode(state, m.secretStream)
    if (m.relayThrough) relayThroughInfo.preencode(state, m.relayThrough)
    if (m.relayAddresses) ipv4Array.preencode(state, m.relayAddresses)
  },
  encode(state, m) {
    let flags = 0

    if (m.holepunch) flags |= 1
    if (m.addresses4 && m.addresses4.length) flags |= 2
    if (m.addresses6 && m.addresses6.length) flags |= 4
    if (m.udx) flags |= 8
    if (m.secretStream) flags |= 16
    if (m.relayThrough) flags |= 32
    if (m.relayAddresses) flags |= 64

    c.uint.encode(state, 1) // version
    c.uint.encode(state, flags)
    c.uint.encode(state, m.error)
    c.uint.encode(state, m.firewall)

    if (m.holepunch) holepunchInfo.encode(state, m.holepunch)
    if (m.addresses4 && m.addresses4.length) ipv4Array.encode(state, m.addresses4)
    if (m.addresses6 && m.addresses6.length) ipv6Array.encode(state, m.addresses6)
    if (m.udx) udxInfo.encode(state, m.udx)
    if (m.secretStream) secretStreamInfo.encode(state, m.secretStream)
    if (m.relayThrough) relayThroughInfo.encode(state, m.relayThrough)
    if (m.relayAddresses) ipv4Array.encode(state, m.relayAddresses)
  },
  decode(state) {
    const version = c.uint.decode(state)

    if (version !== 1) {
      // Do not attempt to decode but return this back to the user so they can
      // actually handle it
      return {
        version,
        error: 0,
        firewall: 0,
        holepunch: null,
        addresses4: [],
        addresses6: [],
        udx: null,
        secretStream: null,
        relayThrough: null,
        relayAddresses: null
      }
    }

    const flags = c.uint.decode(state)

    return {
      version,
      error: c.uint.decode(state),
      firewall: c.uint.decode(state),
      holepunch: (flags & 1) !== 0 ? holepunchInfo.decode(state) : null,
      addresses4: (flags & 2) !== 0 ? ipv4Array.decode(state) : [],
      addresses6: (flags & 4) !== 0 ? ipv6Array.decode(state) : [],
      udx: (flags & 8) !== 0 ? udxInfo.decode(state) : null,
      secretStream: (flags & 16) !== 0 ? secretStreamInfo.decode(state) : null,
      relayThrough: (flags & 32) !== 0 ? relayThroughInfo.decode(state) : null,
      relayAddresses: (flags & 64) !== 0 ? ipv4Array.decode(state) : null
    }
  }
}

exports.holepunch = {
  preencode(state, m) {
    state.end += 2
    c.uint.preencode(state, m.id)
    c.buffer.preencode(state, m.payload)
    if (m.peerAddress) ipv4.preencode(state, m.peerAddress)
  },
  encode(state, m) {
    const flags = m.peerAddress ? 1 : 0
    c.uint.encode(state, flags)
    c.uint.encode(state, m.mode)
    c.uint.encode(state, m.id)
    c.buffer.encode(state, m.payload)
    if (m.peerAddress) ipv4.encode(state, m.peerAddress)
  },
  decode(state) {
    const flags = c.uint.decode(state)
    return {
      mode: c.uint.decode(state),
      id: c.uint.decode(state),
      payload: c.buffer.decode(state),
      peerAddress: flags & 1 ? ipv4.decode(state) : null
    }
  }
}

exports.holepunchPayload = {
  preencode(state, m) {
    state.end += 4 // flags + error + firewall + round
    if (m.addresses) ipv4Array.preencode(state, m.addresses)
    if (m.remoteAddress) state.end += 6
    if (m.token) state.end += 32
    if (m.remoteToken) state.end += 32
  },
  encode(state, m) {
    const flags =
      (m.connected ? 1 : 0) |
      (m.punching ? 2 : 0) |
      (m.addresses ? 4 : 0) |
      (m.remoteAddress ? 8 : 0) |
      (m.token ? 16 : 0) |
      (m.remoteToken ? 32 : 0)

    c.uint.encode(state, flags)
    c.uint.encode(state, m.error)
    c.uint.encode(state, m.firewall)
    c.uint.encode(state, m.round)

    if (m.addresses) ipv4Array.encode(state, m.addresses)
    if (m.remoteAddress) ipv4.encode(state, m.remoteAddress)
    if (m.token) c.fixed32.encode(state, m.token)
    if (m.remoteToken) c.fixed32.encode(state, m.remoteToken)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      error: c.uint.decode(state),
      firewall: c.uint.decode(state),
      round: c.uint.decode(state),
      connected: (flags & 1) !== 0,
      punching: (flags & 2) !== 0,
      addresses: (flags & 4) !== 0 ? ipv4Array.decode(state) : null,
      remoteAddress: (flags & 8) !== 0 ? ipv4.decode(state) : null,
      token: (flags & 16) !== 0 ? c.fixed32.decode(state) : null,
      remoteToken: (flags & 32) !== 0 ? c.fixed32.decode(state) : null
    }
  }
}

const peer = (exports.peer = {
  preencode(state, m) {
    state.end += 32
    ipv4Array.preencode(state, m.relayAddresses)
  },
  encode(state, m) {
    c.fixed32.encode(state, m.publicKey)
    ipv4Array.encode(state, m.relayAddresses)
  },
  decode(state) {
    return {
      publicKey: c.fixed32.decode(state),
      relayAddresses: ipv4Array.decode(state)
    }
  }
})

const peers = (exports.peers = c.array(peer))

const rawPeers = c.array(c.raw)

exports.lookupRawReply = {
  preencode(state, m) {
    rawPeers.preencode(state, m.peers)
    c.uint.preencode(state, m.bump)
  },
  encode(state, m) {
    rawPeers.encode(state, m.peers)
    c.uint.encode(state, m.bump)
  },
  decode(state) {
    return {
      peers: peers.decode(state),
      bump: state.start < state.end ? c.uint.decode(state) : 0
    }
  }
}

exports.announce = {
  preencode(state, m) {
    state.end++ // flags
    if (m.peer) peer.preencode(state, m.peer)
    if (m.refresh) state.end += 32
    if (m.signature) state.end += 64
    if (m.bump) c.uint.preencode(state, m.bump)
  },
  encode(state, m) {
    const flags = (m.peer ? 1 : 0) | (m.refresh ? 2 : 0) | (m.signature ? 4 : 0) | (m.bump ? 8 : 0)
    c.uint.encode(state, flags)
    if (m.peer) peer.encode(state, m.peer)
    if (m.refresh) c.fixed32.encode(state, m.refresh)
    if (m.signature) c.fixed64.encode(state, m.signature)
    if (m.bump) c.uint.encode(state, m.bump)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      peer: (flags & 1) !== 0 ? peer.decode(state) : null,
      refresh: (flags & 2) !== 0 ? c.fixed32.decode(state) : null,
      signature: (flags & 4) !== 0 ? c.fixed64.decode(state) : null,
      bump: (flags & 8) !== 0 ? c.uint.decode(state) : 0
    }
  }
}

exports.mutableSignable = {
  preencode(state, m) {
    c.uint.preencode(state, m.seq)
    c.buffer.preencode(state, m.value)
  },
  encode(state, m) {
    c.uint.encode(state, m.seq)
    c.buffer.encode(state, m.value)
  },
  decode(state) {
    return {
      seq: c.uint.decode(state),
      value: c.buffer.decode(state)
    }
  }
}

exports.mutablePutRequest = {
  preencode(state, m) {
    c.fixed32.preencode(state, m.publicKey)
    c.uint.preencode(state, m.seq)
    c.buffer.preencode(state, m.value)
    c.fixed64.preencode(state, m.signature)
  },
  encode(state, m) {
    c.fixed32.encode(state, m.publicKey)
    c.uint.encode(state, m.seq)
    c.buffer.encode(state, m.value)
    c.fixed64.encode(state, m.signature)
  },
  decode(state) {
    return {
      publicKey: c.fixed32.decode(state),
      seq: c.uint.decode(state),
      value: c.buffer.decode(state),
      signature: c.fixed64.decode(state)
    }
  }
}

exports.mutableGetResponse = {
  preencode(state, m) {
    c.uint.preencode(state, m.seq)
    c.buffer.preencode(state, m.value)
    c.fixed64.preencode(state, m.signature)
  },
  encode(state, m) {
    c.uint.encode(state, m.seq)
    c.buffer.encode(state, m.value)
    c.fixed64.encode(state, m.signature)
  },
  decode(state) {
    return {
      seq: c.uint.decode(state),
      value: c.buffer.decode(state),
      signature: c.fixed64.decode(state)
    }
  }
}

exports.pluginRequest = {
  preencode(state, m) {
    c.string.preencode(state, m.plugin)
    c.uint.preencode(state, m.version)
    c.uint.preencode(state, m.command)
    state.end++ // max flag is 1 so always one byte

    if (m.value) c.buffer.preencode(state, m.value)
  },
  encode(state, m) {
    const flags = m.value ? 1 : 0

    c.string.encode(state, m.plugin)
    c.uint.encode(state, m.version)
    c.uint.encode(state, m.command)
    c.uint.encode(state, flags)

    if (m.value) c.buffer.encode(state, m.value)
  },
  decode(state) {
    const r0 = c.string.decode(state)
    const r1 = c.uint.decode(state)
    const r2 = c.uint.decode(state)
    const flags = c.uint.decode(state)

    return {
      plugin: r0,
      version: r1,
      command: r2,
      value: (flags & 1) !== 0 ? c.buffer.decode(state) : null
    }
  }
}
const { FIREWALL } = require('../lib/constants')

module.exports = class Nat {
  constructor(dht, session, socket) {
    this._samplesHost = []
    this._samplesFull = []
    this._visited = new Map()
    this._resolve = null
    this._minSamples = 4
    this._autoSampling = false

    this.dht = dht
    this.session = session
    this.socket = socket

    this.sampled = 0
    this.firewall = dht.firewalled ? FIREWALL.UNKNOWN : FIREWALL.OPEN
    this.addresses = null

    this.analyzing = new Promise((resolve) => {
      this._resolve = resolve
    })
  }

  autoSample(retry = true) {
    if (this._autoSampling) return
    this._autoSampling = true

    const self = this
    const socket = this.socket
    const maxPings = this._minSamples

    let skip = this.dht.nodes.length >= 8 ? 5 : 0
    let pending = 0

    // TODO: it would be best to pick the nodes to help us based on latency to us
    // That should reduce connect latency in general. We should investigate tracking that later on.

    // TODO 2: try to pick nodes with different IPs as well, as that'll help multi IP cell connections...
    // If we expose this from the nat sampler then the DHT should be able to help us filter out scams as well...

    for (
      let node = this.dht.nodes.latest;
      node && this.sampled + pending < maxPings;
      node = node.prev
    ) {
      if (skip > 0) {
        skip--
        continue
      }

      const ref = node.host + ':' + node.port

      if (this._visited.has(ref)) continue
      this._visited.set(ref, 1)

      pending++
      this.session.ping(node, { socket, retry: false }).then(onpong, onskip)
    }

    pending++
    onskip()

    function onpong(res) {
      self.add(res.to, res.from)
      onskip()
    }

    function onskip() {
      if (--pending === 0 && self.sampled < self._minSamples) {
        if (retry) {
          self._autoSampling = false
          self.autoSample(false)
          return
        }
        self._resolve()
      }
    }
  }

  destroy() {
    this._autoSampling = true
    this._minSamples = 0
    this._resolve()
  }

  unfreeze() {
    this.frozen = false
    this._updateFirewall()
    this._updateAddresses()
  }

  freeze() {
    this.frozen = true
  }

  _updateFirewall() {
    if (!this.dht.firewalled) {
      this.firewall = FIREWALL.OPEN
      return
    }

    if (this.sampled < 3) return

    const max = this._samplesFull[0].hits

    if (max >= 3) {
      this.firewall = FIREWALL.CONSISTENT
      return
    }

    if (max === 1) {
      this.firewall = FIREWALL.RANDOM
      return
    }

    // else max === 2

    // 1 host, >= 4 total samples ie, 2 bad ones -> random
    if (this._samplesHost.length === 1 && this.sampled > 3) {
      this.firewall = FIREWALL.RANDOM
      return
    }

    // double hit on two different ips -> assume consistent
    if (this._samplesHost.length > 1 && this._samplesFull[1].hits > 1) {
      this.firewall = FIREWALL.CONSISTENT
      return
    }

    // (4 is just means - all the samples we expect) - no decision - assume random
    if (this.sampled > 4) {
      this.firewall = FIREWALL.RANDOM
    }
  }

  _updateAddresses() {
    if (this.firewall === FIREWALL.UNKNOWN) {
      this.addresses = null
      return
    }

    if (this.firewall === FIREWALL.RANDOM) {
      this.addresses = [this._samplesHost[0]]
      return
    }

    if (this.firewall === FIREWALL.CONSISTENT) {
      this.addresses = []
      for (const addr of this._samplesFull) {
        if (addr.hits >= 2 || this.addresses.length < 2) this.addresses.push(addr)
      }
    }
  }

  update() {
    if (this.dht.firewalled && this.firewall === FIREWALL.OPEN) {
      this.firewall = FIREWALL.UNKNOWN
    }
    this._updateFirewall()
    this._updateAddresses()
  }

  add(addr, from) {
    const ref = from.host + ':' + from.port

    if (this._visited.get(ref) === 2) return
    this._visited.set(ref, 2)

    addSample(this._samplesHost, addr.host, 0)
    addSample(this._samplesFull, addr.host, addr.port)

    if ((++this.sampled >= 3 || !this.dht.firewalled) && !this.frozen) {
      this.update()
    }

    if (this.firewall === FIREWALL.CONSISTENT || this.firewall === FIREWALL.OPEN) {
      this._resolve()
    } else if (this.sampled >= this._minSamples) {
      this._resolve()
    }
  }
}

function addSample(samples, host, port) {
  for (let i = 0; i < samples.length; i++) {
    const s = samples[i]

    if (s.port !== port || s.host !== host) continue
    s.hits++

    for (; i > 0; i--) {
      const prev = samples[i - 1]
      if (prev.hits >= s.hits) return
      samples[i - 1] = s
      samples[i] = prev
    }

    return
  }

  samples.push({
    host,
    port,
    hits: 1
  })
}
const NoiseSecretStream = require('@hyperswarm/secret-stream')
const NoiseHandshake = require('noise-handshake')
const curve = require('noise-curve-ed')
const c = require('compact-encoding')
const b4a = require('b4a')
const sodium = require('sodium-universal')
const m = require('./messages')
const { NS } = require('./constants')
const { HANDSHAKE_UNFINISHED } = require('./errors')

const NOISE_PROLOUGE = NS.PEER_HANDSHAKE

module.exports = class NoiseWrap {
  constructor(keyPair, remotePublicKey) {
    this.isInitiator = !!remotePublicKey
    this.remotePublicKey = remotePublicKey
    this.keyPair = keyPair
    this.handshake = new NoiseHandshake('IK', this.isInitiator, keyPair, { curve })
    this.handshake.initialise(NOISE_PROLOUGE, remotePublicKey)
  }

  send(payload) {
    const buf = c.encode(m.noisePayload, payload)
    return this.handshake.send(buf)
  }

  recv(buf) {
    const payload = c.decode(m.noisePayload, this.handshake.recv(buf))
    this.remotePublicKey = b4a.toBuffer(this.handshake.rs)
    return payload
  }

  final() {
    if (!this.handshake.complete) throw HANDSHAKE_UNFINISHED()

    const holepunchSecret = b4a.allocUnsafe(32)

    sodium.crypto_generichash(holepunchSecret, NS.PEER_HOLEPUNCH, this.handshake.hash)

    return {
      isInitiator: this.isInitiator,
      publicKey: this.keyPair.publicKey,
      streamId: this.streamId,
      remotePublicKey: this.remotePublicKey,
      remoteId: NoiseSecretStream.id(this.handshake.hash, !this.isInitiator),
      holepunchSecret,
      hash: b4a.toBuffer(this.handshake.hash),
      rx: b4a.toBuffer(this.handshake.rx),
      tx: b4a.toBuffer(this.handshake.tx)
    }
  }
}
const c = require('compact-encoding')
const sodium = require('sodium-universal')
const RecordCache = require('record-cache')
const Cache = require('xache')
const b4a = require('b4a')
const unslab = require('unslab')

const { encodeUnslab } = require('./encode')
const m = require('./messages')
const { NS, ERROR } = require('./constants')

const EMPTY = b4a.alloc(0)
const TMP = b4a.allocUnsafe(32)
const MAX_BUMP_DRIFT = 60_000

module.exports = class Persistent {
  constructor(dht, opts) {
    this.dht = dht
    this.records = new RecordCache(opts.records)
    this.bumps = new Cache(opts.bumps)
    this.refreshes = new Cache(opts.refreshes)
    this.mutables = new Cache(opts.mutables)
    this.immutables = new Cache(opts.immutables)
  }

  onlookup(req) {
    if (!req.target) return

    const k = b4a.toString(req.target, 'hex')
    const records = this.records.get(k, 20)
    const bump = this.bumps.get(k) || 0
    const fwd = this.dht._router.get(k)

    if (fwd && records.length < 20) records.push(fwd.record)

    req.reply(records.length ? c.encode(m.lookupRawReply, { peers: records, bump }) : null)
  }

  onfindpeer(req) {
    if (!req.target) return
    const fwd = this.dht._router.get(req.target)
    req.reply(fwd ? fwd.record : null)
  }

  unannounce(target, publicKey) {
    const k = b4a.toString(target, 'hex')
    sodium.crypto_generichash(TMP, publicKey)

    if (b4a.equals(TMP, target)) this.dht._router.delete(k)
    this.records.remove(k, publicKey)
  }

  onunannounce(req) {
    if (!req.target || !req.token) return

    const unann = decode(m.announce, req.value)
    if (unann === null) return

    const { peer, signature } = unann
    if (!peer || !signature) return

    const signable = annSignable(req.target, req.token, this.dht.id, unann, NS.UNANNOUNCE)

    if (!sodium.crypto_sign_verify_detached(signature, signable, peer.publicKey)) {
      return
    }

    this.unannounce(req.target, peer.publicKey)
    req.reply(null, { token: false, closerNodes: false })
  }

  _onrefresh(token, req) {
    sodium.crypto_generichash(TMP, token)
    const activeRefresh = b4a.toString(TMP, 'hex')

    const r = this.refreshes.get(activeRefresh)
    if (!r) return

    const { announceSelf, k, record } = r
    const publicKey = record.subarray(0, 32)

    if (announceSelf) {
      this.dht._router.set(k, {
        relay: req.from,
        record,
        onconnect: null,
        onholepunch: null
      })
      this.records.remove(k, publicKey)
    } else {
      this.records.add(k, publicKey, record)
    }

    this.refreshes.delete(activeRefresh)
    this.refreshes.set(b4a.toString(token, 'hex'), r)

    req.reply(null, { token: false, closerNodes: false })
  }

  onannounce(req) {
    if (!req.target || !req.token || !this.dht.id) return

    const ann = decode(m.announce, req.value)
    if (ann === null) return

    const { peer, refresh, signature, bump } = ann

    if (!peer) {
      if (!refresh) return
      this._onrefresh(refresh, req)
      return
    }

    const signable = annSignable(req.target, req.token, this.dht.id, ann, NS.ANNOUNCE)

    if (!signature || !sodium.crypto_sign_verify_detached(signature, signable, peer.publicKey)) {
      return
    }

    // TODO: it would be potentially be more optimal to allow more than 3 addresses here for a findPeer response
    // and only use max 3 for a lookup reply
    if (peer.relayAddresses.length > 3) {
      peer.relayAddresses = peer.relayAddresses.slice(0, 3)
    }

    sodium.crypto_generichash(TMP, peer.publicKey)

    const k = b4a.toString(req.target, 'hex')
    const announceSelf = b4a.equals(TMP, req.target)
    const record = encodeUnslab(m.peer, peer)

    if (announceSelf) {
      this.dht._router.set(k, {
        relay: req.from,
        record,
        onconnect: null,
        onholepunch: null
      })
      this.records.remove(k, peer.publicKey)
    } else {
      const currentBump = this.bumps.get(k) || 0
      if (bump > currentBump && bump <= Date.now() + MAX_BUMP_DRIFT) this.bumps.set(k, bump)
      this.records.add(k, peer.publicKey, record)
    }

    if (refresh) {
      this.refreshes.set(b4a.toString(refresh, 'hex'), { k, record, announceSelf })
    }

    req.reply(null, { token: false, closerNodes: false })
  }

  onmutableget(req) {
    if (!req.target || !req.value) return

    let seq = 0
    try {
      seq = c.decode(c.uint, req.value)
    } catch {
      return
    }

    const k = b4a.toString(req.target, 'hex')
    const value = this.mutables.get(k)

    if (!value) {
      req.reply(null)
      return
    }

    const localSeq = c.decode(c.uint, value)
    req.reply(localSeq < seq ? null : value)
  }

  onmutableput(req) {
    if (!req.target || !req.token || !req.value) return

    const p = decode(m.mutablePutRequest, req.value)
    if (!p) return

    const { publicKey, seq, value, signature } = p

    const hash = b4a.allocUnsafe(32)
    sodium.crypto_generichash(hash, publicKey)
    if (!b4a.equals(hash, req.target)) return

    if (!value || !verifyMutable(signature, seq, value, publicKey)) return

    const k = b4a.toString(hash, 'hex')
    const local = this.mutables.get(k)

    if (local) {
      const existing = c.decode(m.mutableGetResponse, local)
      if (existing.value && existing.seq === seq && b4a.compare(value, existing.value) !== 0) {
        req.error(ERROR.SEQ_REUSED)
        return
      }
      if (seq < existing.seq) {
        req.error(ERROR.SEQ_TOO_LOW)
        return
      }
    }

    this.mutables.set(k, encodeUnslab(m.mutableGetResponse, { seq, value, signature }))
    req.reply(null)
  }

  onimmutableget(req) {
    if (!req.target) return

    const k = b4a.toString(req.target, 'hex')
    const value = this.immutables.get(k)

    req.reply(value || null)
  }

  onimmutableput(req) {
    if (!req.target || !req.token || !req.value) return

    const hash = b4a.alloc(32)
    sodium.crypto_generichash(hash, req.value)
    if (!b4a.equals(hash, req.target)) return

    const k = b4a.toString(hash, 'hex')
    this.immutables.set(k, unslab(req.value))

    req.reply(null)
  }

  onplugin(req) {
    if (!req.value) return

    const plugreq = decode(m.pluginRequest, req.value)
    if (plugreq === null) return

    const p = this.dht.plugins.get(plugreq.plugin)
    if (!p || p.version !== plugreq.version) return

    p.onrequest(plugreq, req)
  }

  destroy() {
    this.records.destroy()
    this.refreshes.destroy()
    this.mutables.destroy()
    this.immutables.destroy()
  }

  static signMutable(seq, value, keyPair) {
    const signable = b4a.allocUnsafe(32 + 32)
    const hash = signable.subarray(32)

    signable.set(NS.MUTABLE_PUT, 0)

    sodium.crypto_generichash(hash, c.encode(m.mutableSignable, { seq, value }))
    return sign(signable, keyPair)
  }

  static verifyMutable(signature, seq, value, publicKey) {
    return verifyMutable(signature, seq, value, publicKey)
  }

  static signAnnounce(target, token, id, ann, keyPair) {
    return sign(annSignable(target, token, id, ann, NS.ANNOUNCE), keyPair)
  }

  static signUnannounce(target, token, id, ann, keyPair) {
    return sign(annSignable(target, token, id, ann, NS.UNANNOUNCE), keyPair)
  }
}

function verifyMutable(signature, seq, value, publicKey) {
  const signable = b4a.allocUnsafe(32 + 32)
  const hash = signable.subarray(32)

  signable.set(NS.MUTABLE_PUT, 0)

  sodium.crypto_generichash(hash, c.encode(m.mutableSignable, { seq, value }))
  return sodium.crypto_sign_verify_detached(signature, signable, publicKey)
}

function annSignable(target, token, id, ann, ns) {
  const signable = b4a.allocUnsafe(32 + 32)
  const hash = signable.subarray(32)

  signable.set(ns, 0)

  sodium.crypto_generichash_batch(hash, [
    target,
    id,
    token,
    c.encode(m.peer, ann.peer), // note that this is the partial encoding of the announce message so we could just use that for perf
    ann.refresh || EMPTY
  ])

  return signable
}

function sign(signable, keyPair) {
  if (keyPair.sign) {
    return keyPair.sign(signable)
  }
  const secretKey = keyPair.secretKey ? keyPair.secretKey : keyPair
  const signature = b4a.allocUnsafe(64)
  sodium.crypto_sign_detached(signature, signable, secretKey)
  return signature
}

function decode(enc, val) {
  try {
    return val && c.decode(enc, val)
  } catch (err) {
    return null
  }
}
module.exports = class RawStreamSet {
  constructor(dht) {
    this._dht = dht

    this._prefix = 16 - 1 // 16 is the default stream-set side in udx
    this._streams = new Map()
  }

  get size() {
    return this._streams.size
  }

  [Symbol.iterator]() {
    return this._streams.values()
  }

  add(opts) {
    const self = this

    // TODO: we should prob have a udx helper for id generation, given the slight complexity
    // of the below. requires a PRNG in udx tho.

    let id = 0

    while (true) {
      id = (Math.random() * 0x100000000) >>> 0

      if (this._streams.has(id & this._prefix)) continue
      break
    }

    // always have ~50% change of rolling a free one
    if (2 * this._streams.size >= this._prefix) {
      // ie 0b11111 = 0b1111 + 1 + 0b1111
      this._prefix = 2 * this._prefix + 1

      // move the prefixes over
      const next = new Map()
      for (const stream of this._streams.values()) {
        next.set(stream.id & this._prefix, stream)
      }
      this._streams = next
    }

    const stream = this._dht.udx.createStream(id, opts)
    this._streams.set(id & this._prefix, stream)

    stream.on('close', onclose)

    return stream

    function onclose() {
      self._streams.delete(id & self._prefix)
    }
  }

  async clear() {
    const destroying = []

    for (const stream of this._streams.values()) {
      destroying.push(new Promise((resolve) => stream.once('close', resolve).destroy()))
    }

    await Promise.allSettled(destroying)
  }
}
const b4a = require('b4a')
const safetyCatch = require('safety-catch')

exports.clearRelayTimeout = clearRelayTimeout
exports.closeRelayConnection = closeRelayConnection
exports.confirmDirectUpgrade = confirmDirectUpgrade
exports.destroyRelayConnection = destroyRelayConnection

function clearRelayTimeout(connectionOrHandshake) {
  clearTimeout(connectionOrHandshake.relayTimeout)
  connectionOrHandshake.relayTimeout = null
}

function closeRelayConnection(connectionOrHandshake) {
  const socket = resetRelayConnection(connectionOrHandshake)

  if (socket) socket.end()
}

function confirmDirectUpgrade(connectionOrHandshake, rawStream, remoteChanging) {
  const cleanup = () => {
    rawStream.off('data', ondirect)
    rawStream.off('message', ondirect)
    rawStream.off('close', cleanup)
  }

  function ondirect() {
    if (!connectionOrHandshake.validUpgrade) {
      // reset, aka assume from direct
      connectionOrHandshake.validUpgrade = true
      return
    }

    cleanup()
    closeRelayConnection(connectionOrHandshake)
  }

  const confirm = () => {
    rawStream.on('data', ondirect)
    rawStream.on('message', ondirect)
    rawStream.once('close', cleanup)

    // Use a raw UDX message to make the peer observe the direct path without
    // writing application data into the secret stream.
    if (rawStream.trySend) rawStream.trySend(b4a.alloc(0))
  }

  if (!remoteChanging) {
    confirm()
    return
  }

  remoteChanging.then(confirm).catch(safetyCatch)
}

function destroyRelayConnection(connectionOrHandshake) {
  const socket = resetRelayConnection(connectionOrHandshake)

  if (socket) socket.destroy()
}

function resetRelayConnection(connectionOrHandshake) {
  if (connectionOrHandshake.relayTimeout) clearRelayTimeout(connectionOrHandshake)

  const socket = connectionOrHandshake.relaySocket
  // Drop relay references so the app connection no longer keeps relay state alive.
  connectionOrHandshake.relayToken = null
  connectionOrHandshake.relaySocket = null
  connectionOrHandshake.relayClient = null

  return socket
}
const c = require('compact-encoding')
const Cache = require('xache')
const safetyCatch = require('safety-catch')
const b4a = require('b4a')
const { handshake, holepunch } = require('./messages')
const { COMMANDS } = require('./constants')
const { BAD_HANDSHAKE_REPLY, BAD_HOLEPUNCH_REPLY } = require('./errors')

const FROM_CLIENT = 0
const FROM_SERVER = 1
const FROM_RELAY = 2
const FROM_SECOND_RELAY = 3
const REPLY = 4

// TODO: While the current design is very trustless in regards to clients/servers trusting the DHT,
// we should add a bunch of rate limits everywhere, especially including here to avoid bad users
// using a DHT node to relay traffic indiscriminately using the connect/holepunch messages.
// That's mostly from an abuse POV as none of the messsages do amplication.

module.exports = class Router {
  constructor(dht, opts) {
    this.dht = dht
    this.forwards = new Cache(opts.forwards)
  }

  set(target, state) {
    if (state.onpeerhandshake) {
      this.forwards.retain(toString(target), state)
    } else {
      this.forwards.set(toString(target), state)
    }
  }

  get(target) {
    return this.forwards.get(toString(target))
  }

  delete(target) {
    this.forwards.delete(toString(target))
  }

  destroy() {
    this.forwards.destroy()
  }

  async peerHandshake(target, { noise, peerAddress, relayAddress, socket, session }, to) {
    const dht = this.dht

    const requestValue = c.encode(handshake, {
      mode: FROM_CLIENT,
      noise,
      peerAddress,
      relayAddress
    })

    const res = await dht.request(
      { command: COMMANDS.PEER_HANDSHAKE, target, value: requestValue },
      to,
      { socket, session }
    )

    const hs = decode(handshake, res.value)
    if (
      !hs ||
      hs.mode !== REPLY ||
      to.host !== res.from.host ||
      to.port !== res.from.port ||
      !hs.noise
    ) {
      throw BAD_HANDSHAKE_REPLY()
    }

    return {
      noise: hs.noise,
      relayed: !!hs.peerAddress,
      serverAddress: hs.peerAddress || to,
      clientAddress: res.to
    }
  }

  async onpeerhandshake(req) {
    const hs = req.value && decode(handshake, req.value)
    if (!hs) return

    const { mode, noise, peerAddress, relayAddress } = hs

    const state = req.target && this.get(req.target)
    const isServer = !!(state && state.onpeerhandshake)
    const relay = state && state.relay

    if (isServer) {
      let reply = null
      try {
        reply = noise && (await state.onpeerhandshake({ noise, peerAddress }, req))
      } catch (e) {
        safetyCatch(e)
        return
      }
      if (!reply || !reply.noise) return
      const opts = { socket: reply.socket, closerNodes: false, token: false }

      switch (mode) {
        case FROM_CLIENT: {
          req.reply(
            c.encode(handshake, { mode: REPLY, noise: reply.noise, peerAddress: null }),
            opts
          )
          return
        }
        case FROM_RELAY: {
          req.relay(
            c.encode(handshake, { mode: FROM_SERVER, noise: reply.noise, peerAddress }),
            req.from,
            opts
          )
          return
        }
        case FROM_SECOND_RELAY: {
          if (!relayAddress) return
          req.relay(
            c.encode(handshake, { mode: FROM_SERVER, noise: reply.noise, peerAddress }),
            relayAddress,
            opts
          )
          return // eslint-disable-line
        }
      }
    } else {
      switch (mode) {
        case FROM_CLIENT: {
          // TODO: if no relay is known route closer to the target instead of timing out
          if (!noise) return
          if (!relay && !relayAddress) {
            // help the user route
            req.reply(null, { token: false, closerNodes: true })
            return
          }
          req.relay(
            c.encode(handshake, {
              mode: FROM_RELAY,
              noise,
              peerAddress: req.from,
              relayAddress: null
            }),
            relayAddress || relay
          )
          return
        }
        case FROM_RELAY: {
          if (!relay || !noise) return
          req.relay(
            c.encode(handshake, {
              mode: FROM_SECOND_RELAY,
              noise,
              peerAddress,
              relayAddress: req.from
            }),
            relay
          )
          return
        }
        case FROM_SERVER: {
          if (!peerAddress || !noise) return
          req.reply(
            c.encode(handshake, { mode: REPLY, noise, peerAddress: req.from, relayAddress: null }),
            { to: peerAddress, closerNodes: false, token: false }
          )
          return // eslint-disable-line
        }
      }
    }
  }

  async peerHolepunch(target, { id, payload, peerAddress, socket, session }, to) {
    const dht = this.dht
    const requestValue = c.encode(holepunch, {
      mode: FROM_CLIENT,
      id,
      payload,
      peerAddress
    })

    const res = await dht.request(
      { command: COMMANDS.PEER_HOLEPUNCH, target, value: requestValue },
      to,
      { socket, session }
    )

    const hp = decode(holepunch, res.value)
    if (!hp || hp.mode !== REPLY || to.host !== res.from.host || to.port !== res.from.port) {
      throw BAD_HOLEPUNCH_REPLY()
    }

    return {
      from: res.from,
      to: res.to,
      payload: hp.payload,
      peerAddress: hp.peerAddress || to
    }
  }

  async onpeerholepunch(req) {
    const hp = req.value && decode(holepunch, req.value)
    if (!hp) return

    const { mode, id, payload, peerAddress } = hp

    const state = req.target && this.get(req.target)
    const isServer = !!(state && state.onpeerholepunch)
    const relay = state && state.relay

    switch (mode) {
      case FROM_CLIENT: {
        if (!peerAddress && !relay) return
        req.relay(
          c.encode(holepunch, { mode: FROM_RELAY, id, payload, peerAddress: req.from }),
          peerAddress || relay
        )
        return
      }
      case FROM_RELAY: {
        if (!isServer || !peerAddress) return
        let reply = null
        try {
          reply = await state.onpeerholepunch({ id, payload, peerAddress }, req)
        } catch (e) {
          safetyCatch(e)
          return
        }
        if (!reply) return
        const opts = { socket: reply.socket, closerNodes: false, token: false }
        req.relay(
          c.encode(holepunch, { mode: FROM_SERVER, id: 0, payload: reply.payload, peerAddress }),
          req.from,
          opts
        )
        return
      }
      case FROM_SERVER: {
        req.reply(c.encode(holepunch, { mode: REPLY, id, payload, peerAddress: req.from }), {
          to: peerAddress,
          closerNodes: false,
          token: false
        })
        return // eslint-disable-line
      }
    }
  }
}

function decode(enc, val) {
  try {
    return c.decode(enc, val)
  } catch {
    return null
  }
}

function toString(t) {
  return typeof t === 'string' ? t : b4a.toString(t, 'hex')
}
const sodium = require('sodium-universal')
const b4a = require('b4a')
const { holepunchPayload } = require('./messages')

module.exports = class HolepunchPayload {
  constructor(holepunchSecret) {
    this._sharedSecret = holepunchSecret
    this._localSecret = b4a.allocUnsafe(32)

    sodium.randombytes_buf(this._localSecret)
  }

  decrypt(buffer) {
    const state = { start: 24, end: buffer.byteLength - 16, buffer }

    if (state.end <= state.start) return null

    const nonce = buffer.subarray(0, 24)
    const msg = state.buffer.subarray(state.start, state.end)
    const cipher = state.buffer.subarray(state.start)

    if (!sodium.crypto_secretbox_open_easy(msg, cipher, nonce, this._sharedSecret)) return null

    try {
      return holepunchPayload.decode(state)
    } catch {
      return null
    }
  }

  encrypt(payload) {
    const state = { start: 24, end: 24, buffer: null }
    holepunchPayload.preencode(state, payload)
    state.buffer = b4a.allocUnsafe(state.end + 16)

    const nonce = state.buffer.subarray(0, 24)
    const msg = state.buffer.subarray(state.start, state.end)
    const cipher = state.buffer.subarray(state.start)

    holepunchPayload.encode(state, payload)
    sodium.randombytes_buf(nonce)
    sodium.crypto_secretbox_easy(cipher, msg, nonce, this._sharedSecret)

    return state.buffer
  }

  token(addr) {
    const out = b4a.allocUnsafe(32)
    sodium.crypto_generichash(out, b4a.from(addr.host), this._localSecret)
    return out
  }
}
const DONE = Promise.resolve(true)
const DESTROYED = Promise.resolve(false)

module.exports = class Semaphore {
  constructor(limit = 1) {
    this.limit = limit
    this.active = 0
    this.waiting = []

    this.flushedPromise = null
    this.flushedResolve = null

    this.destroyed = false

    this._onwait = this._queueWaiting.bind(this)
    this._onflush = this._queueFlushed.bind(this)
  }

  _queueWaiting(resolve) {
    this.waiting.push(resolve)
  }

  _queueFlushed(resolve) {
    this.flushedResolve = resolve
  }

  wait() {
    if (this.destroyed === true) return DESTROYED

    if (this.active < this.limit && this.waiting.length === 0) {
      this.active++
      return DONE
    }

    return new Promise(this._onwait)
  }

  signal() {
    if (this.destroyed === true) return

    this.active--
    while (this.active < this.limit && this.waiting.length > 0 && this.destroyed === false) {
      this.active++
      this.waiting.shift()(true)
    }

    if (this.active === 0 && this.flushedResolve) {
      const resolve = this.flushedResolve
      this.flushedResolve = null
      this.flushedPromise = null
      resolve(true)
    }
  }

  async flush() {
    if (this.destroyed === true) return
    if (this.active === 0) return
    if (this.flushedPromise) return this.flushedPromise
    this.flushedPromise = new Promise(this._onflush)
    return this.flushedPromise
  }

  destroy() {
    this.destroyed = true
    this.active = 0
    while (this.waiting.length) this.waiting.pop()(false)
    if (this.flushedResolve) this.flushedResolve(false)
  }
}
const { EventEmitter } = require('events')
const safetyCatch = require('safety-catch')
const NoiseSecretStream = require('@hyperswarm/secret-stream')
const b4a = require('b4a')
const relay = require('blind-relay')
const NoiseWrap = require('./noise-wrap')
const Announcer = require('./announcer')
const { FIREWALL, ERROR } = require('./constants')
const { unslabbedHash } = require('./crypto')
const SecurePayload = require('./secure-payload')
const Holepuncher = require('./holepuncher')
const {
  clearRelayTimeout,
  confirmDirectUpgrade,
  destroyRelayConnection
} = require('./relay-connection')
const { isPrivate } = require('bogon')
const { ALREADY_LISTENING, NODE_DESTROYED, KEYPAIR_ALREADY_USED } = require('./errors')

const HANDSHAKE_CLEAR_WAIT = 10000
const HANDSHAKE_INITIAL_TIMEOUT = 10000

module.exports = class Server extends EventEmitter {
  constructor(dht, opts = {}) {
    super()

    this.dht = dht
    this.target = null

    this.closed = false
    this.firewall = opts.firewall || (() => false)
    this.holepunch = opts.holepunch || (() => true)
    this.relayThrough = opts.relayThrough || null
    this.relayKeepAlive = opts.relayKeepAlive || 5000
    this.pool = opts.pool || null
    this.createHandshake = opts.createHandshake || defaultCreateHandshake
    this.createSecretStream = opts.createSecretStream || defaultCreateSecretStream
    this.suspended = false
    this.handshakeClearWait = opts.handshakeClearWait || HANDSHAKE_CLEAR_WAIT

    this._shareLocalAddress = opts.shareLocalAddress !== false
    this._reusableSocket = !!opts.reusableSocket
    this._neverPunch = opts.holepunch === false // useful for fully disabling punching
    this._keyPair = null
    this._announcer = null
    this._connects = new Map()
    this._holepunches = []
    this._listening = null
    this._closing = null
  }

  get listening() {
    return this._listening !== null
  }

  get publicKey() {
    return this._keyPair && this._keyPair.publicKey
  }

  get relayAddresses() {
    return this._announcer ? this._announcer.relayAddresses : []
  }

  onconnection(encryptedSocket) {
    this.emit('connection', encryptedSocket)
  }

  async suspend({ log = noop } = {}) {
    log('Suspending hyperdht server')
    if (this._listening !== null) await this._listening
    log('Suspending hyperdht server (post listening)')
    this.suspended = true
    this._clearAll()
    return this._announcer ? this._announcer.suspend({ log }) : Promise.resolve()
  }

  async resume() {
    if (this._listening !== null) await this._listening
    this.suspended = false
    return this._announcer ? this._announcer.resume() : Promise.resolve()
  }

  address() {
    if (!this._keyPair) return null

    return {
      publicKey: this._keyPair.publicKey,
      host: this.dht.host,
      port: this.dht.port
    }
  }

  close() {
    if (this._closing) return this._closing
    this._closing = this._close()
    return this._closing
  }

  _gc() {
    this.dht.listening.delete(this)
    if (this.target) this.dht._router.delete(this.target)
  }

  async _stopListening() {
    try {
      if (this._announcer) await this._announcer.stop()
    } catch {
      // ignore
    }

    this._announcer = null
    this._listening = null
    this._keyPair = null
  }

  async _close() {
    if (this._listening === null) {
      this.closed = true
      this.emit('close')
      return
    }

    try {
      await this._listening
    } catch (err) {
      safetyCatch(err)
    }

    this._gc()
    this._clearAll()

    await this._stopListening()

    this.closed = true
    this.emit('close')
  }

  _clearAll() {
    while (this._holepunches.length > 0) {
      const h = this._holepunches.pop()
      if (h && h.puncher) h.puncher.destroy()
      if (h && h.clearing) clearTimeout(h.clearing)
      if (h && h.prepunching) clearTimeout(h.prepunching)
      if (h && h.rawStream) h.rawStream.destroy()
    }

    this._connects.clear()
  }

  async listen(keyPair = this.dht.defaultKeyPair, opts = {}) {
    if (this._listening !== null) throw ALREADY_LISTENING()
    if (this.dht.destroyed) throw NODE_DESTROYED()

    this._listening = this._listen(keyPair, opts)
    await this._listening
    return this
  }

  async _listen(keyPair, opts) {
    // From now on, the DHT object which created me is responsible for closing me
    this.dht.listening.add(this)

    try {
      await this.dht.bind()
      if (this._closing) return

      for (const s of this.dht.listening) {
        if (s._keyPair && b4a.equals(s._keyPair.publicKey, keyPair.publicKey)) {
          throw KEYPAIR_ALREADY_USED()
        }
      }

      this.target = unslabbedHash(keyPair.publicKey)
      this._keyPair = keyPair
      this._announcer = new Announcer(this.dht, keyPair, this.target, opts)

      this.dht._router.set(this.target, {
        relay: null,
        record: this._announcer.record,
        onpeerhandshake: this._onpeerhandshake.bind(this),
        onpeerholepunch: this._onpeerholepunch.bind(this)
      })

      // warm it up for now
      this._localAddresses().catch(safetyCatch)

      await this._announcer.start()
    } catch (err) {
      await this._stopListening()
      this._gc()
      throw err
    }

    if (this._closing) return
    if (this.suspended) await this._announcer.suspend()

    if (this._closing) return
    if (this.dht.destroyed) throw NODE_DESTROYED()

    if (this.pool) this.pool._attachServer(this)

    this.emit('listening')
  }

  refresh() {
    if (this._announcer && !this.suspended) this._announcer.refresh()
  }

  notifyOnline() {
    if (this._announcer) this._announcer.online.notify()
  }

  _localAddresses() {
    return this.dht.validateLocalAddresses(Holepuncher.localAddresses(this.dht.io.serverSocket))
  }

  async _addHandshake(k, noise, clientAddress, { to: serverAddress, socket }, direct) {
    let id = this._holepunches.indexOf(null)
    if (id === -1) id = this._holepunches.push(null) - 1

    const hs = {
      round: 0,
      reply: null,
      puncher: null,
      payload: null,
      rawStream: null,
      encryptedSocket: null,
      prepunching: null,
      firewalled: true,
      clearing: null,
      replyFromPuncher: false,
      onsocket: null,
      aborted: false,

      // Relay state
      relayTimeout: null,
      relayToken: null,
      relaySocket: null,
      relayClient: null,
      relayPaired: false,
      validUpgrade: true
    }

    this._holepunches[id] = hs

    const handshake = this.createHandshake(this._keyPair, null)

    let remotePayload
    try {
      remotePayload = await handshake.recv(noise)
    } catch (err) {
      safetyCatch(err)
      this._clearLater(hs, id, k)
      return null
    }

    if (this._closing || this.suspended) return null

    try {
      hs.firewalled = await this.firewall(handshake.remotePublicKey, remotePayload, clientAddress)
    } catch (err) {
      safetyCatch(err)
    }

    if (this._closing || this.suspended) return null

    if (hs.firewalled) {
      this._clearLater(hs, id, k)
      return null
    }

    const error =
      remotePayload.version === 1
        ? remotePayload.udx
          ? ERROR.NONE
          : ERROR.ABORTED
        : ERROR.VERSION_MISMATCH

    const addresses = []
    const ourRemoteAddr = this.dht.remoteAddress()
    const ourLocalAddrs = this._shareLocalAddress ? await this._localAddresses() : null

    if (this._closing || this.suspended) return null

    if (ourRemoteAddr) addresses.push(ourRemoteAddr)
    if (ourLocalAddrs) addresses.push(...ourLocalAddrs)

    if (error === ERROR.NONE) {
      hs.rawStream = this.dht.createRawStream({
        framed: true,
        firewall(socket, port, host) {
          if (!(port > 0 && port < 65536)) return true

          // Check if the traffic originated from the socket on which we're expecting relay traffic. If so,
          // we haven't hole punched yet and the other side is just sending us traffic through the relay.
          if (hs.relaySocket && isRelay(hs.relaySocket, socket, port, host)) {
            hs.validUpgrade = false
            return false
          }

          hs.onsocket(socket, port, host)
          hs.validUpgrade = true
          return false
        }
      })

      hs.rawStream.on('error', autoDestroy)

      // Handles the case where onsocket is never called, but the stream got setup
      // This can happen on a relayed connection which never connects directly
      // (onsocket is called there only when the direct connection is established)
      const onrawstreamclose = () => {
        if (this._closing) return
        this._clearLater(hs, id, k)
      }
      hs.rawStream.on('close', onrawstreamclose)

      hs.onsocket = (socket, port, host) => {
        if (hs.rawStream === null) return // Already hole punched

        this._clearLater(hs, id, k)

        if (hs.prepunching) {
          clearTimeout(hs.prepunching)
          hs.prepunching = null
        }

        if (this._reusableSocket && remotePayload.udx.reusableSocket) {
          this.dht._socketPool.routes.add(handshake.remotePublicKey, hs.rawStream)
        }

        hs.rawStream.removeListener('error', autoDestroy)
        hs.rawStream.removeListener('close', onrawstreamclose)

        if (hs.rawStream.connected) {
          const rawStream = hs.rawStream
          const remoteChanging = rawStream.changeRemote(socket, remotePayload.udx.id, port, host)
          confirmDirectUpgrade(hs, rawStream, remoteChanging)
        } else {
          hs.rawStream.connect(socket, remotePayload.udx.id, port, host)
          hs.encryptedSocket = this.createSecretStream(false, hs.rawStream, {
            handshake: h,
            keepAlive: this.dht.connectionKeepAlive
          })

          this.onconnection(hs.encryptedSocket)
        }

        if (hs.puncher) {
          hs.puncher.onabort = noop
          hs.puncher.destroy()
        }

        hs.rawStream = null
      }

      function autoDestroy() {
        if (hs.puncher) hs.puncher.destroy()
      }
    }

    const relayAddresses = this.relayAddresses
    const relayThrough = selectRelay(this.relayThrough)

    if (relayThrough) hs.relayToken = relay.token()

    try {
      hs.reply = await handshake.send({
        error,
        firewall: ourRemoteAddr ? FIREWALL.OPEN : FIREWALL.UNKNOWN,
        holepunch: ourRemoteAddr ? null : { id, relays: this._announcer.relays },
        addresses4: addresses,
        addresses6: null,
        udx: {
          reusableSocket: this._reusableSocket,
          id: hs.rawStream ? hs.rawStream.id : 0,
          seq: 0
        },
        secretStream: {},
        relayThrough: relayThrough ? { publicKey: relayThrough, token: hs.relayToken } : null,
        relayAddresses: relayAddresses.length ? relayAddresses : null
      })
    } catch (err) {
      safetyCatch(err)
      if (hs.rawStream) hs.rawStream.destroy()
      this._clearLater(hs, id, k)
      return null
    }

    if (this._closing || this.suspended) {
      if (hs.rawStream) hs.rawStream.destroy()
      return null
    }

    const h = handshake.final()

    if (error !== ERROR.NONE) {
      if (hs.rawStream) hs.rawStream.destroy()
      this._clearLater(hs, id, k)
      return hs
    }

    if (remotePayload.firewall === FIREWALL.OPEN || direct) {
      const sock = direct ? socket : this.dht.socket
      this.dht.stats.punches.open++
      hs.onsocket(sock, clientAddress.port, clientAddress.host)
      return hs
    }

    if (relayThrough || remotePayload.relayThrough) {
      this._relayConnection(hs, relayThrough, remotePayload, h)
    }

    const onabort = () => {
      hs.aborted = true
      if (hs.prepunching) clearTimeout(hs.prepunching)
      hs.prepunching = null
      if (hs.puncher) {
        hs.puncher.onabort = noop
        hs.puncher.destroy()
      }
      if (hs.rawStream.destroyed) {
        this._clearLater(hs, id, k)
        return
      }

      hs.rawStream.on('close', () => this._clearLater(hs, id, k))
      if (hs.relayToken === null) hs.rawStream.destroy()
    }

    if (!direct && clientAddress.host === serverAddress.host) {
      const clientAddresses = remotePayload.addresses4.filter((addr) => isPrivate(addr.host))

      if (clientAddresses.length > 0 && this._shareLocalAddress) {
        const myAddresses = await this._localAddresses()
        const addr = Holepuncher.matchAddress(myAddresses, clientAddresses)

        if (addr) {
          hs.payload = new SecurePayload(h.holepunchSecret)
          setupHolepuncher(this.dht, hs, remotePayload.firewall, onabort)
          hs.prepunching = setTimeout(onabort, HANDSHAKE_INITIAL_TIMEOUT)
          return hs
        }
      }
    }

    if (this._closing || this.suspended) return null

    if (ourRemoteAddr || this._neverPunch) {
      hs.prepunching = setTimeout(onabort, HANDSHAKE_INITIAL_TIMEOUT)
      return hs
    }

    hs.payload = new SecurePayload(h.holepunchSecret)
    setupHolepuncher(this.dht, hs, remotePayload.firewall, onabort)
    hs.replyFromPuncher = true
    hs.prepunching = setTimeout(hs.puncher.destroy.bind(hs.puncher), HANDSHAKE_INITIAL_TIMEOUT)

    return hs
  }

  _clearLater(hs, id, k) {
    if (hs.clearing) return
    hs.clearing = setTimeout(() => this._clear(hs, id, k), this.handshakeClearWait)
  }

  _clear(hs, id, k) {
    if (id >= this._holepunches.length || this._holepunches[id] !== hs) return
    if (hs.clearing) clearTimeout(hs.clearing)

    this._holepunches[id] = null
    while (
      this._holepunches.length > 0 &&
      this._holepunches[this._holepunches.length - 1] === null
    ) {
      this._holepunches.pop()
    }
    this._connects.delete(k)
  }

  async _onpeerhandshake({ noise, peerAddress }, req) {
    const k = b4a.toString(noise, 'hex')

    // The next couple of statements MUST run within the same tick to prevent
    // a malicious peer from flooding us with handshakes.
    let p = this._connects.get(k)
    if (!p) {
      p = this._addHandshake(k, noise, peerAddress || req.from, req, !peerAddress)
      this._connects.set(k, p)
    }

    const h = await p
    if (!h) return null

    if (this._closing !== null || this.suspended) return null

    // Routed handshake replies advertise the socket they are sent from as the
    // server address. Same-LAN prepunch also creates a puncher, but it must
    // keep advertising the normal server socket so the LAN shortcut can open.
    return { socket: h.replyFromPuncher ? h.puncher.socket : null, noise: h.reply }
  }

  async _onpeerholepunch({ id, peerAddress, payload }, req) {
    const h = id < this._holepunches.length ? this._holepunches[id] : null
    if (!h) return null

    if (!peerAddress || this._closing !== null || this.suspended) return null
    if (!h.payload) return this._abort(h) // not opened

    const remotePayload = h.payload.decrypt(payload)
    if (!remotePayload) return null

    const p = h.puncher
    if (!p || !p.socket) return this._abort(h) // not opened

    const isServerRelay = this._announcer.isRelay(req.from)
    const { error, firewall, round, punching, addresses, remoteAddress, remoteToken } =
      remotePayload

    if (error !== ERROR.NONE) {
      // We actually do not need to set the round here, but just do it for consistency.
      if (round >= h.round) h.round = round
      return this._abort(h)
    }

    const token = h.payload.token(peerAddress)
    const echoed = isServerRelay && !!remoteToken && b4a.equals(token, remoteToken)

    // Update our heuristics here
    if (req.socket === p.socket) {
      p.nat.add(req.to, req.from)
    }

    if (round >= h.round) {
      h.round = round
      p.updateRemote({ punching, firewall, addresses, verified: echoed ? peerAddress.host : null })
    }

    // Wait for the analyzer to reach a conclusion...
    let stable = await p.analyze(false)
    if (p.destroyed) return null

    if (!p.remoteHolepunching && !stable) {
      stable = await p.analyze(true)
      if (p.destroyed) return null
      if (!stable) return this._abort(h)
    }

    // Fast mode! If we are consistent and the remote has opened a session to us (remoteAddress)
    // then fire a quick punch back. Note the await here just waits for the udp socket to flush.
    if (
      isConsistent(p.nat.firewall) &&
      remoteAddress &&
      hasSameAddr(p.nat.addresses, remoteAddress)
    ) {
      await p.ping(peerAddress)
      if (p.destroyed) return null
    }

    // Remote said they are punching (or willing to), so we will punch as well.
    // Note that this returns when the punching has STARTED, so no guarantee
    // we will have a connection after this promise etc.
    if (p.remoteHolepunching) {
      // TODO: still continue here if a local connection might work, but then do not holepunch...
      if (!this.holepunch(p.remoteFirewall, p.nat.firewall, p.remoteAddresses, p.nat.addresses)) {
        return p.destroyed ? null : this._abort(h)
      }

      if (h.prepunching) {
        clearTimeout(h.prepunching)
        h.prepunching = null
      }

      if (p.remoteFirewall >= FIREWALL.RANDOM || p.nat.firewall >= FIREWALL.RANDOM) {
        if (
          this.dht._randomPunches >= this.dht._randomPunchLimit ||
          Date.now() - this.dht._lastRandomPunch < this.dht._randomPunchInterval
        ) {
          if (!h.relayToken) return this._abort(h, ERROR.TRY_LATER)
          return {
            socket: p.socket,
            payload: h.payload.encrypt({
              error: ERROR.TRY_LATER,
              firewall: p.nat.firewall,
              round: h.round,
              connected: p.connected,
              punching: p.punching,
              addresses: p.nat.addresses,
              remoteAddress: null,
              token: isServerRelay ? token : null,
              remoteToken: remotePayload.token
            })
          }
        }
      }

      const punching = await p.punch()
      if (p.destroyed) return null
      if (!punching) return this._abort(h)
    }

    // Freeze that analysis as soon as we have a result we are giving to the other peer
    if (p.nat.firewall !== FIREWALL.UNKNOWN) {
      p.nat.freeze()
    }

    return {
      socket: p.socket,
      payload: h.payload.encrypt({
        error: ERROR.NONE,
        firewall: p.nat.firewall,
        round: h.round,
        connected: p.connected,
        punching: p.punching,
        addresses: p.nat.addresses,
        remoteAddress: null,
        token: isServerRelay ? token : null,
        remoteToken: remotePayload.token
      })
    }
  }

  _abort(h, error = ERROR.ABORTED) {
    if (!h.payload) {
      if (h.puncher) h.puncher.destroy()
      return null
    }

    const payload = h.payload.encrypt({
      error,
      firewall: FIREWALL.UNKNOWN,
      round: h.round,
      connected: false,
      punching: false,
      addresses: null,
      remoteAddress: null,
      token: null,
      remoteToken: null
    })

    if (h.puncher) h.puncher.destroy()

    return { socket: this.dht.socket, payload }
  }

  _relayConnection(hs, relayThrough, remotePayload, h) {
    this.dht.stats.relaying.attempts++

    let isInitiator
    let publicKey
    let token

    if (relayThrough) {
      isInitiator = true
      publicKey = relayThrough
      token = hs.relayToken
    } else {
      isInitiator = false
      publicKey = remotePayload.relayThrough.publicKey
      token = remotePayload.relayThrough.token
    }

    hs.relayToken = token
    hs.relaySocket = this.dht.connect(publicKey)
    hs.relaySocket.setKeepAlive(this.relayKeepAlive)
    hs.relayClient = relay.Client.from(hs.relaySocket, { id: hs.relaySocket.publicKey })
    hs.relayTimeout = setTimeout(onabort, 15000)

    hs.relayClient
      .pair(isInitiator, token, hs.rawStream)
      .on('error', onabort)
      .on('data', (remoteId) => {
        if (hs.relayTimeout) clearRelayTimeout(hs)
        if (hs.rawStream === null) {
          onabort(null)
          return
        }

        hs.relayPaired = true
        this.dht.stats.relaying.successes++

        if (hs.prepunching) clearTimeout(hs.prepunching)
        hs.prepunching = null

        const { remotePort, remoteHost, socket } = hs.relaySocket.rawStream

        hs.rawStream
          .on('close', () => destroyRelayConnection(hs))
          .connect(socket, remoteId, remotePort, remoteHost)

        hs.encryptedSocket = this.createSecretStream(false, hs.rawStream, {
          handshake: h,
          keepAlive: this.dht.connectionKeepAlive
        })

        this.onconnection(hs.encryptedSocket)
      })

    const dht = this.dht
    function onabort() {
      if (!hs.relayPaired) dht.stats.relaying.aborts++
      destroyRelayConnection(hs)
      if (hs.aborted && hs.rawStream) hs.rawStream.destroy()
    }
  }
}

function isConsistent(fw) {
  return fw === FIREWALL.OPEN || fw === FIREWALL.CONSISTENT
}

function hasSameAddr(addrs, other) {
  if (addrs === null) return false

  for (const addr of addrs) {
    if (addr.port === other.port && addr.host === other.host) return true
  }
  return false
}

function defaultCreateHandshake(keyPair, remotePublicKey) {
  return new NoiseWrap(keyPair, remotePublicKey)
}

function defaultCreateSecretStream(isInitiator, rawStream, opts) {
  return new NoiseSecretStream(isInitiator, rawStream, opts)
}

function setupHolepuncher(dht, hs, remoteFirewall, onabort) {
  if (hs.puncher) return

  hs.puncher = new Holepuncher(dht, dht.session(), false, remoteFirewall)
  hs.puncher.onconnect = hs.onsocket
  hs.puncher.onabort = onabort
}

function isRelay(relaySocket, socket, port, host) {
  const stream = relaySocket.rawStream
  if (!stream) return false
  if (stream.socket !== socket) return false
  return port === stream.remotePort && host === stream.remoteHost
}

function selectRelay(relayThrough) {
  if (typeof relayThrough === 'function') relayThrough = relayThrough()
  if (relayThrough === null) return null
  if (Array.isArray(relayThrough)) {
    return relayThrough[Math.floor(Math.random() * relayThrough.length)]
  }
  return relayThrough
}

function noop() {}
module.exports = class Sleeper {
  constructor() {
    this._timeout = null
    this._resolve = null

    this._start = (resolve) => {
      this._resolve = resolve
    }

    this._trigger = () => {
      if (this._resolve === null) return
      const resolve = this._resolve
      this._timeout = null
      this._resolve = null
      resolve()
    }
  }

  pause(ms) {
    const p = new Promise(this._start)
    if (this._timeout !== null) {
      clearTimeout(this._timeout)
      this._trigger()
    }
    this._timeout = setTimeout(this._trigger, ms)
    return p
  }

  resume() {
    if (this._timeout !== null) {
      clearTimeout(this._timeout)
      this._trigger()
    }
  }
}
const b4a = require('b4a')

const LINGER_TIME = 3000

module.exports = class SocketPool {
  constructor(dht, host) {
    this._dht = dht
    this._sockets = new Map()
    this._lingering = new Set() // updated by the ref
    this._host = host

    this.routes = new SocketRoutes(this)
  }

  _onmessage(ref, data, address) {
    this._dht.onmessage(ref.socket, data, address)
  }

  _add(ref) {
    this._sockets.set(ref.socket, ref)
  }

  _remove(ref) {
    this._sockets.delete(ref.socket)
    this._lingering.delete(ref)
  }

  lookup(socket) {
    return this._sockets.get(socket) || null
  }

  setReusable(socket, bool) {
    const ref = this.lookup(socket)
    if (ref) ref.reusable = bool
  }

  acquire() {
    // TODO: Enable socket reuse
    return new SocketRef(this)
  }

  async destroy() {
    const closing = []

    for (const ref of this._sockets.values()) {
      ref._unlinger()
      closing.push(ref.socket.close())
    }

    await Promise.allSettled(closing)
  }
}

class SocketRoutes {
  constructor(pool) {
    this._pool = pool
    this._routes = new Map()
  }

  add(publicKey, rawStream) {
    if (rawStream.socket) this._onconnect(publicKey, rawStream)
    else rawStream.on('connect', this._onconnect.bind(this, publicKey, rawStream))
  }

  get(publicKey) {
    const id = b4a.toString(publicKey, 'hex')
    const route = this._routes.get(id)
    if (!route) return null
    return route
  }

  _onconnect(publicKey, rawStream) {
    const id = b4a.toString(publicKey, 'hex')
    const socket = rawStream.socket

    let route = this._routes.get(id)

    if (!route) {
      const gc = () => {
        if (this._routes.get(id) === route) this._routes.delete(id)
        socket.removeListener('close', gc)
      }

      route = {
        socket,
        address: { host: rawStream.remoteHost, port: rawStream.remotePort },
        gc
      }

      this._routes.set(id, route)
      socket.on('close', gc)
    }

    this._pool.setReusable(socket, true)

    rawStream.on('error', () => {
      this._pool.setReusable(socket, false)
      if (!route) route = this._routes.get(id)
      if (route && route.socket === socket) route.gc()
    })
  }
}

// TODO: we should just make some "user data" object on udx to allow to attach this info
class SocketRef {
  constructor(pool) {
    this._pool = pool

    // Events
    this.onholepunchmessage = noop

    // Whether it should teardown immediately or wait a bit
    this.reusable = false

    this.socket = pool._dht.udx.createSocket()
    this.socket
      .on('close', this._onclose.bind(this))
      .on('message', this._onmessage.bind(this))
      .on('idle', this._onidle.bind(this))
      .on('busy', this._onbusy.bind(this))
      .bind(0, this._pool._host)

    this._refs = 1
    this._released = false
    this._closed = false

    this._timeout = null
    this._wasBusy = false

    this._pool._add(this)
  }

  _onclose() {
    this._pool._remove(this)
  }

  _onmessage(data, address) {
    if (data.byteLength > 1) {
      this._pool._onmessage(this, data, address)
    } else {
      this.onholepunchmessage(data, address, this)
    }
  }

  _onidle() {
    this._closeMaybe()
  }

  _onbusy() {
    this._wasBusy = true
    this._unlinger()
  }

  _reset() {
    this.onholepunchmessage = noop
  }

  _closeMaybe() {
    if (this._refs === 0 && this.socket.idle && !this._timeout) this._close()
  }

  _lingeringClose() {
    this._pool._lingering.delete(this)
    this._timeout = null
    this._closeMaybe()
  }

  _close() {
    this._unlinger()

    if (this.reusable && this._wasBusy) {
      this._wasBusy = false
      this._pool._lingering.add(this)
      this._timeout = setTimeout(this._lingeringClose.bind(this), LINGER_TIME)
      return
    }

    this._closed = true
    this.socket.close()
  }

  _unlinger() {
    if (this._timeout !== null) {
      clearTimeout(this._timeout)
      this._pool._lingering.delete(this)
      this._timeout = null
    }
  }

  get free() {
    return this._refs === 0
  }

  active() {
    this._refs++
    this._unlinger()
  }

  inactive() {
    this._refs--
    this._closeMaybe()
  }

  address() {
    return this.socket.address()
  }

  release() {
    if (this._released) return

    this._released = true
    this._reset()

    this._refs--
    this._closeMaybe()
  }
}

function noop() {}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "hyperdht",
  "version": "6.33.0",
  "description": "The DHT powering Hyperswarm",
  "main": "index.js",
  "browser": "browser.js",
  "bin": {
    "hyperdht": "./bin.js"
  },
  "files": [
    "index.js",
    "browser.js",
    "testnet.js",
    "bin.js",
    "lib/**.js"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    },
    "child_process": {
      "bare": "bare-node-child-process",
      "default": "child_process"
    }
  },
  "dependencies": {
    "@hyperswarm/secret-stream": "^6.6.2",
    "b4a": "^1.3.1",
    "bare-events": "^2.2.0",
    "blind-relay": "^1.3.0",
    "bogon": "^1.0.0",
    "compact-encoding": "^3.0.0",
    "dht-rpc": "^6.15.1",
    "hypercore-crypto": "^3.3.0",
    "hypercore-id-encoding": "^1.2.0",
    "hyperdht-address": "^1.0.1",
    "noise-curve-ed": "^2.0.0",
    "noise-handshake": "^4.0.0",
    "record-cache": "^1.1.1",
    "safety-catch": "^1.0.1",
    "signal-promise": "^1.0.3",
    "sodium-universal": "^5.0.1",
    "streamx": "^2.16.1",
    "unslab": "^1.3.0",
    "xache": "^1.1.0"
  },
  "devDependencies": {
    "bare-node-child-process": "^1.0.1",
    "brittle": "^3.0.0",
    "graceful-goodbye": "^1.3.0",
    "newline-decoder": "^1.0.2",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "test": "prettier --check . && node test/all.js",
    "test:bare": "bare test/all.js",
    "test:generate": "brittle -r test/all.js test/*.js",
    "integration": "brittle test/integration/*.js",
    "end-to-end": "brittle test/end-to-end/*.js"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "directories": {
    "lib": "lib",
    "test": "test"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/hyperdht.git"
  },
  "keywords": [],
  "bugs": {
    "url": "https://github.com/holepunchto/hyperdht/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperdht#readme"
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "hyperschema",
  "version": "1.21.0",
  "description": "Create registries of declarative compact-encoding schemas",
  "files": [
    "lib/*.js",
    "builder.mjs",
    "builder.cjs",
    "runtime.mjs",
    "runtime.cjs",
    "primitives.mjs",
    "primitives.cjs"
  ],
  "exports": {
    "./package": "./package.json",
    ".": {
      "import": "./builder.mjs",
      "default": "./builder.cjs"
    },
    "./runtime": {
      "import": "./runtime.mjs",
      "default": "./runtime.cjs"
    },
    "./primitives": {
      "import": "./primitives.mjs",
      "default": "./primitives.cjs"
    }
  },
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    }
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test/index.js",
    "test:bare": "prettier . --check && bare test/index.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/hyperschema.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/hyperschema/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperschema#readme",
  "dependencies": {
    "bare-fs": "^4.0.1",
    "compact-encoding": "^3.0.0",
    "generate-object-property": "^2.0.0",
    "generate-string": "^1.0.1"
  },
  "devDependencies": {
    "brittle": "^3.7.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "test-tmp": "^1.3.0"
  }
}
module.exports = {
  c: require('compact-encoding')
}
const { EventEmitter } = require('events')
const { getStreamError } = require('streamx')
const DHT = require('hyperdht')
const spq = require('shuffled-priority-queue')
const b4a = require('b4a')
const unslab = require('unslab')

const PeerInfo = require('./lib/peer-info')
const RetryTimer = require('./lib/retry-timer')
const ConnectionSet = require('./lib/connection-set')
const PeerDiscovery = require('./lib/peer-discovery')

const MAX_PEERS = 64
const MAX_PARALLEL = 3
const MAX_CLIENT_CONNECTIONS = Infinity // TODO: Change
const MAX_SERVER_CONNECTIONS = Infinity

const ERR_MISSING_TOPIC = 'Topic is required and must be a 32-byte buffer'
const ERR_DESTROYED = 'Swarm has been destroyed'
const ERR_DUPLICATE = 'Duplicate connection'
const ERR_FIREWALL = 'Peer is firewalled'

module.exports = class Hyperswarm extends EventEmitter {
  constructor(opts = {}) {
    super()
    const {
      seed,
      relayThrough,
      keyPair = DHT.keyPair(seed),
      maxPeers = MAX_PEERS,
      maxClientConnections = MAX_CLIENT_CONNECTIONS,
      maxServerConnections = MAX_SERVER_CONNECTIONS,
      maxParallel = MAX_PARALLEL,
      firewall = allowAll
    } = opts
    this.keyPair = keyPair

    this.dht =
      opts.dht ||
      new DHT({
        bootstrap: opts.bootstrap,
        nodes: opts.nodes,
        port: opts.port,
        deferRandomPunch: opts.deferRandomPunch,
        randomPunchInterval: opts.randomPunchInterval
      })
    this.server = this.dht.createServer(
      {
        firewall: this._handleFirewall.bind(this),
        relayThrough: this._maybeRelayConnection.bind(this),
        handshakeClearWait: opts.handshakeClearWait
      },
      this._handleServerConnection.bind(this)
    )

    this.destroyed = false
    this.suspended = false
    this.maxPeers = maxPeers
    this.maxClientConnections = maxClientConnections
    this.maxServerConnections = maxServerConnections
    this.maxParallel = maxParallel
    this.relayThrough = relayThrough ? toRelayFunction(relayThrough) : null

    this.connecting = 0
    this.connections = new Set()
    this.peers = new Map()
    this.explicitPeers = new Set()
    this.listening = null
    this.stats = {
      updates: 0,
      connects: {
        client: {
          opened: 0,
          closed: 0,
          attempted: 0
        },
        server: {
          // Note: there is no notion of 'attempts' for server connections
          opened: 0,
          closed: 0
        }
      },
      bannedPeers: 0
    }

    this._discovery = new Map()
    this._timer = new RetryTimer(this._requeue.bind(this), {
      backoffs: opts.backoffs,
      jitter: opts.jitter
    })
    this._queue = spq()

    this._allConnections = new ConnectionSet()
    this._pendingFlushes = []
    this._flushTick = 0

    this._drainingQueue = false
    this._clientConnections = 0
    this._serverConnections = 0
    this._firewall = firewall

    this.dht.on('network-change', this._handleNetworkChange.bind(this))
    this.dht.on('network-update', this._handleNetworkUpdate.bind(this))
    this.on('update', this._handleUpdate)
  }

  _maybeRelayConnection(force) {
    if (!this.relayThrough) return null
    return this.relayThrough(force, this)
  }

  _enqueue(peerInfo) {
    if (peerInfo.queued) return
    peerInfo.queued = true
    peerInfo._flushTick = this._flushTick
    this._queue.add(peerInfo)

    this._attemptClientConnections()
  }

  _requeue(batch) {
    if (this.suspended) return
    for (const peerInfo of batch) {
      peerInfo.waiting = false

      if (
        peerInfo._updatePriority() === false ||
        this._allConnections.has(peerInfo.publicKey) ||
        peerInfo.queued
      ) {
        continue
      }
      peerInfo.queued = true
      peerInfo._flushTick = this._flushTick
      this._queue.add(peerInfo)
    }

    this._attemptClientConnections()
  }

  _flushMaybe(peerInfo) {
    for (let i = 0; i < this._pendingFlushes.length; i++) {
      const flush = this._pendingFlushes[i]
      if (peerInfo._flushTick > flush.tick) continue
      if (--flush.missing > 0) continue
      flush.onflush(true)
      this._pendingFlushes.splice(i--, 1)
    }
  }

  _withinMaxPeers() {
    const e = this.explicitPeers.size
    const factor = e === 0 ? 1 : e < 2 ? 2 : e < 4 ? 3 : 4
    return factor * this._allConnections.size < this.maxPeers
  }

  _flushAllMaybe() {
    if (
      this.connecting > 0 ||
      (this._withinMaxPeers() && this._clientConnections < this.maxClientConnections)
    ) {
      return false
    }

    while (this._pendingFlushes.length) {
      const flush = this._pendingFlushes.pop()
      flush.onflush(true)
    }

    return true
  }

  _shouldConnectExplicit() {
    return !this.destroyed && !this.suspended && this.connecting < this.maxParallel
  }

  _shouldConnect() {
    return (
      !this.destroyed &&
      !this.suspended &&
      this.connecting < this.maxParallel &&
      this._withinMaxPeers() &&
      this._clientConnections < this.maxClientConnections
    )
  }

  _shouldRequeue(peerInfo) {
    if (this.suspended) return false
    if (peerInfo.explicit) return true
    for (const topic of peerInfo.topics) {
      if (this._discovery.has(b4a.toString(topic, 'hex')) && !this.destroyed) {
        return true
      }
    }
    return false
  }

  _connect(peerInfo, queued) {
    if (peerInfo.banned || this._allConnections.has(peerInfo.publicKey)) {
      if (queued) this._flushMaybe(peerInfo)
      return
    }

    // TODO: Support async firewalling at some point.
    if (this._handleFirewall(peerInfo.publicKey, null)) {
      if (queued) this._flushMaybe(peerInfo)
      return
    }

    const relayThrough = this._maybeRelayConnection(peerInfo.forceRelaying)
    const conn = this.dht.connect(peerInfo.publicKey, {
      relayAddresses: peerInfo.relayAddresses,
      keyPair: this.keyPair,
      relayThrough
    })
    this._allConnections.add(conn)

    this.stats.connects.client.attempted++

    this.connecting++
    this._clientConnections++
    let opened = false

    const onerror = (err) => {
      if (this.relayThrough && shouldForceRelaying(err.code)) {
        peerInfo.forceRelaying = true
        // Reset the attempts in order to fast connect to relay
        peerInfo.attempts = 0
      }
    }

    // Removed once a connection is opened
    conn.on('error', onerror)

    conn.on('open', () => {
      opened = true
      this.stats.connects.client.opened++

      this._connectDone()
      this.connections.add(conn)
      conn.removeListener('error', onerror)
      peerInfo._connected()
      peerInfo.client = true
      this.emit('connection', conn, peerInfo)
      if (queued) this._flushMaybe(peerInfo)

      this.emit('update')
    })
    conn.on('close', () => {
      if (!opened) this._connectDone()
      this.stats.connects.client.closed++

      const err = getStreamError(conn)
      if (shouldBan(err)) {
        this._banPeer(peerInfo, true, err)
      }

      this.connections.delete(conn)
      this._allConnections.delete(conn)
      this._clientConnections--
      peerInfo._disconnected()

      peerInfo.waiting = this._shouldRequeue(peerInfo) && this._timer.add(peerInfo)
      this._maybeDeletePeer(peerInfo)

      if (!opened && queued) this._flushMaybe(peerInfo)

      this._attemptClientConnections()

      this.emit('update')
    })

    this.emit('update')
  }

  _connectDone() {
    this.connecting--

    if (this.connecting < this.maxParallel) this._attemptClientConnections()
    if (this.connecting === 0) this._flushAllMaybe()
  }

  // Called when the PeerQueue indicates a connection should be attempted.
  _attemptClientConnections() {
    // Guard against re-entries - unsure if it still needed but doesn't hurt
    if (this._drainingQueue || this.suspended) return
    this._drainingQueue = true

    for (const peerInfo of this.explicitPeers) {
      if (!this._shouldConnectExplicit()) break
      if (
        peerInfo.attempts >= 5 ||
        Date.now() - peerInfo.disconnectedTime < peerInfo.attempts * 1000
      ) {
        continue
      }
      this._connect(peerInfo, false)
    }

    while (this._queue.length && this._shouldConnect()) {
      const peerInfo = this._queue.shift()
      peerInfo.queued = false
      this._connect(peerInfo, true)
    }
    this._drainingQueue = false
    if (this.connecting === 0) this._flushAllMaybe()
  }

  _handleFirewall(remotePublicKey, payload) {
    if (b4a.equals(remotePublicKey, this.keyPair.publicKey)) return true

    let peerInfo = this.peers.get(b4a.toString(remotePublicKey, 'hex'))
    if (peerInfo && peerInfo.banned) return true

    const firewalled = this._firewall(remotePublicKey, payload)
    if (firewalled) {
      if (!peerInfo) peerInfo = this._upsertPeer(remotePublicKey)
      this._banPeer(peerInfo, true, new Error(ERR_FIREWALL))
    }

    return firewalled
  }

  _handleServerConnectionSwap(existing, conn) {
    let closed = false

    existing.on('close', () => {
      if (closed) return

      conn.removeListener('error', noop)
      conn.removeListener('close', onclose)

      this._handleServerConnection(conn)
    })

    conn.on('error', noop)
    conn.on('close', onclose)

    function onclose() {
      closed = true
    }
  }

  // Called when the DHT receives a new server connection.
  _handleServerConnection(conn) {
    if (this.destroyed || this.suspended) {
      // TODO: Investigate why a final server connection can be received after close
      conn.on('error', noop)
      return conn.destroy(ERR_DESTROYED)
    }

    const existing = this._allConnections.get(conn.remotePublicKey)

    if (existing) {
      // If both connections are from the same peer,
      // - pick the new one if the existing stream is already established (has sent and received bytes),
      //   because the other client must have lost that connection and be reconnecting
      // - otherwise, pick the one thats expected to initiate in a tie break
      const existingIsOutdated = existing.rawBytesRead > 0 && existing.rawBytesWritten > 0
      const expectedInitiator = b4a.compare(conn.publicKey, conn.remotePublicKey) > 0
      const keepNew = existingIsOutdated || expectedInitiator === conn.isInitiator

      if (keepNew === false) {
        existing.sendKeepAlive()
        conn.on('error', noop)
        conn.destroy(new Error(ERR_DUPLICATE))
        return
      }

      existing.on('error', noop)
      existing.destroy(new Error(ERR_DUPLICATE))
      this._handleServerConnectionSwap(existing, conn)
      return
    }

    // When reaching here, the connection will always be 'opened' next tick
    this.stats.connects.server.opened++

    const peerInfo = this._upsertPeer(conn.remotePublicKey, null)

    this.connections.add(conn)
    this._allConnections.add(conn)
    this._serverConnections++

    conn.on('close', () => {
      const err = getStreamError(conn)
      if (shouldBan(err)) {
        this._banPeer(peerInfo, true, err)
      }

      this.connections.delete(conn)
      this._allConnections.delete(conn)
      this._serverConnections--
      this.stats.connects.server.closed++

      this._maybeDeletePeer(peerInfo)

      this._attemptClientConnections()

      this.emit('update')
    })
    peerInfo.client = false
    this.emit('connection', conn, peerInfo)

    this.emit('update')
  }

  _upsertPeer(publicKey, relayAddresses) {
    if (b4a.equals(publicKey, this.keyPair.publicKey)) return null
    const keyString = b4a.toString(publicKey, 'hex')
    let peerInfo = this.peers.get(keyString)

    if (peerInfo) {
      peerInfo.relayAddresses = relayAddresses // new is always better
      return peerInfo
    }

    peerInfo = new PeerInfo({
      publicKey,
      relayAddresses
    })

    this.peers.set(keyString, peerInfo)
    return peerInfo
  }

  _handleUpdate() {
    this.stats.updates++
  }

  _maybeDeletePeer(peerInfo) {
    if (!peerInfo.shouldGC()) return

    const hasActiveConn = this._allConnections.has(peerInfo.publicKey)
    if (hasActiveConn) return

    const keyString = b4a.toString(peerInfo.publicKey, 'hex')
    this.peers.delete(keyString)
  }

  /*
   * Called when a peer is actively discovered during a lookup.
   *
   * Three conditions:
   *  1. Not a known peer -- insert into queue
   *  2. A known peer with normal priority -- do nothing
   *  3. A known peer with low priority -- bump priority, because it's been rediscovered
   */
  _handlePeer(peer, topic) {
    const peerInfo = this._upsertPeer(peer.publicKey, peer.relayAddresses)
    if (peerInfo) peerInfo._topic(topic)
    if (!peerInfo || this._allConnections.has(peer.publicKey)) return
    if (!peerInfo.prioritized || peerInfo.server) peerInfo._reset()
    if (peerInfo._updatePriority()) {
      this._enqueue(peerInfo)
    }
  }

  async _handleNetworkUpdate() {
    if (!this.online) return
    this._handleNetworkChange()
  }

  async _handleNetworkChange() {
    if (this.suspended) return

    // prioritize figuring out if existing connections are dead
    for (const conn of this._allConnections) {
      conn.sendKeepAlive()
    }

    const refreshes = []

    for (const discovery of this._discovery.values()) {
      refreshes.push(discovery.refresh())
    }

    await Promise.allSettled(refreshes)
  }

  _banPeer(peerInfo, banned, err) {
    peerInfo.ban(banned)
    this.stats.bannedPeers++
    this.emit('ban', peerInfo, err)
  }

  status(key) {
    return this._discovery.get(b4a.toString(key, 'hex')) || null
  }

  listen() {
    if (!this.listening) {
      if (this.destroyed) throw new Error('Swarm destroyed')
      this.listening = this.server.listen(this.keyPair)
    }
    return this.listening
  }

  // Object that exposes a cancellation method (destroy)
  // TODO: When you rejoin, it should reannounce + bump lookup priority
  join(topic, opts = {}) {
    if (this.destroyed) throw new Error('Swarm destroyed')
    if (!topic) throw new Error(ERR_MISSING_TOPIC)
    topic = unslab(topic)

    const topicString = b4a.toString(topic, 'hex')

    let discovery = this._discovery.get(topicString)

    if (discovery && !discovery.destroyed) {
      return discovery.session(opts)
    }

    discovery = new PeerDiscovery(this, topic, {
      limit: opts.limit,
      wait: discovery ? discovery.destroy() : null,
      suspended: this.suspended,
      onpeer: (peer) => this._handlePeer(peer, topic)
    })
    this._discovery.set(topicString, discovery)
    return discovery.session(opts)
  }

  // Returns a promise
  async leave(topic) {
    if (!topic) throw new Error(ERR_MISSING_TOPIC)
    const topicString = b4a.toString(topic, 'hex')
    if (!this._discovery.has(topicString)) return Promise.resolve()

    const discovery = this._discovery.get(topicString)

    try {
      await discovery.destroy()
    } catch {
      // ignore, prop network
    }

    if (this._discovery.get(topicString) === discovery) {
      this._discovery.delete(topicString)
    }
  }

  joinPeer(publicKey) {
    const peerInfo = this._upsertPeer(publicKey, null)
    if (!peerInfo) return
    if (!this.explicitPeers.has(peerInfo)) {
      peerInfo.explicit = true
      this.explicitPeers.add(peerInfo)
    }
    if (this._allConnections.has(publicKey)) return
    if (peerInfo._updatePriority()) {
      this._enqueue(peerInfo)
    }
  }

  leavePeer(publicKey) {
    const keyString = b4a.toString(publicKey, 'hex')
    if (!this.peers.has(keyString)) return

    const peerInfo = this.peers.get(keyString)
    peerInfo.explicit = false
    this.explicitPeers.delete(peerInfo)
    this._maybeDeletePeer(peerInfo)
  }

  // Returns a promise
  async flush() {
    const allFlushed = [...this._discovery.values()].map((v) => v.flushed())
    await Promise.all(allFlushed)
    if (this._flushAllMaybe()) return true
    const pendingSize = this._allConnections.size - this.connections.size
    if (!this._queue.length && !pendingSize) return true
    return new Promise((resolve) => {
      this._pendingFlushes.push({
        onflush: resolve,
        missing: this._queue.length + pendingSize,
        tick: this._flushTick++
      })
    })
  }

  async clear() {
    const cleared = Promise.allSettled([...this._discovery.values()].map((d) => d.destroy()))
    this._discovery.clear()
    return cleared
  }

  async destroy({ force } = {}) {
    if (this.destroyed && !force) return
    this.destroyed = true

    this._timer.destroy()

    if (!force) await this.clear()

    await this.server.close()

    while (this._pendingFlushes.length) {
      const flush = this._pendingFlushes.pop()
      flush.onflush(false)
    }

    await this.dht.destroy({ force })
  }

  async suspend({ log = noop } = {}) {
    if (this.suspended) return

    const promises = []

    promises.push(this.server.suspend({ log }))

    for (const discovery of this._discovery.values()) {
      promises.push(discovery.suspend({ log }))
    }

    const pending = []
    for (const connection of this._allConnections) {
      connection.destroy()
      pending.push(new Promise((resolve) => connection.on('close', resolve)))
    }

    this.suspended = true

    log('Suspending server and discovery... (' + promises.length + ')')
    await Promise.allSettled(promises)
    log('Done, suspending the dht...')
    await this.dht.suspend({ log })
    log('Done, swarm fully suspended')

    await Promise.all(pending)

    // reset queue
    this._timer.destroy()
    this._timer = new RetryTimer(this._requeue.bind(this), {
      backoffs: this._timer.backoffs,
      jitter: this._timer.jitter
    })
    this._queue = spq()
  }

  async resume({ log = noop } = {}) {
    if (!this.suspended) return

    log('Resuming the dht')
    await this.dht.resume()
    log('Done, resuming the server')
    await this.server.resume()
    log('Done, all discovery')

    for (const discovery of this._discovery.values()) {
      discovery.resume()
    }

    this.suspended = false
    this._attemptClientConnections()
  }

  topics() {
    return this._discovery.values()
  }
}

function noop() {}

function allowAll() {
  return false
}

function shouldForceRelaying(code) {
  return (
    code === 'HOLEPUNCH_ABORTED' ||
    code === 'HOLEPUNCH_DOUBLE_RANDOMIZED_NATS' ||
    code === 'REMOTE_NOT_HOLEPUNCHABLE'
  )
}

function shouldBan() {
  // return !!err && err.name === 'HypercoreError' && err.code === 'INVALID_OPERATION'
  return false
}

function toRelayFunction(relayThrough) {
  return typeof relayThrough === 'function'
    ? relayThrough
    : (force, swarm) => (force || swarm.dht.randomized ? relayThrough : null)
}
module.exports = class BulkTimer {
  constructor(time, fn) {
    this._time = time
    this._fn = fn
    this._interval = null
    this._next = []
    this._pending = []
    this._destroyed = false
  }

  destroy() {
    if (this._destroyed) return
    this._destroyed = true
    clearInterval(this._interval)
    this._interval = null
  }

  _ontick() {
    if (!this._next.length && !this._pending.length) return
    if (this._next.length) this._fn(this._next)
    this._next = this._pending
    this._pending = []
  }

  add(info) {
    if (this._destroyed) return
    if (!this._interval) {
      this._interval = setInterval(this._ontick.bind(this), Math.floor(this._time * 0.66))
    }

    this._pending.push(info)
  }
}
const b4a = require('b4a')

module.exports = class ConnectionSet {
  constructor() {
    this._byPublicKey = new Map()
  }

  [Symbol.iterator]() {
    return this._byPublicKey.values()
  }

  get size() {
    return this._byPublicKey.size
  }

  has(publicKey) {
    return this._byPublicKey.has(toHex(publicKey))
  }

  get(publicKey) {
    return this._byPublicKey.get(toHex(publicKey))
  }

  add(connection) {
    this._byPublicKey.set(b4a.toString(connection.remotePublicKey, 'hex'), connection)
  }

  delete(connection) {
    const keyString = b4a.toString(connection.remotePublicKey, 'hex')
    const existing = this._byPublicKey.get(keyString)
    if (existing !== connection) return
    this._byPublicKey.delete(keyString)
  }
}

function toHex(b) {
  return typeof b === 'string' ? b : b4a.toString(b, 'hex')
}
const safetyCatch = require('safety-catch')
const b4a = require('b4a')

const REFRESH_INTERVAL = 1000 * 60 * 10 // 10 min
const RANDOM_JITTER = 1000 * 60 * 2 // 2 min
const DELAY_GRACE_PERIOD = 1000 * 30 // 30s

const MAX_DISCOVERY_CACHE = 64

module.exports = class PeerDiscovery {
  constructor(
    swarm,
    topic,
    { limit = Infinity, wait = null, suspended = false, onpeer = noop, onerror = safetyCatch }
  ) {
    this.limit = limit
    this.swarm = swarm
    this.topic = topic
    this.isClient = false
    this.isServer = false
    this.destroyed = false
    this.destroying = null
    this.suspended = suspended

    this._sessions = []
    this._clientSessions = 0
    this._serverSessions = 0

    this._onpeer = onpeer
    this._onerror = onerror

    this._discovered = new Set()
    this._activeQuery = null
    this._timer = null
    this._currentRefresh = null
    this._closestNodes = null
    this._firstAnnounce = true
    this._needsUnannounce = false
    this._refreshes = 0
    this._wait = wait
  }

  session({ server = true, client = true, limit = Infinity, onerror = safetyCatch }) {
    if (this.destroyed) throw new Error('PeerDiscovery is destroyed')
    const session = new PeerDiscoverySession(this)
    session.refresh({ server, client, limit }).catch(onerror)
    this._sessions.push(session)
    return session
  }

  _refreshLater(eager) {
    const jitter = Math.round(Math.random() * RANDOM_JITTER)
    const delay = !eager ? REFRESH_INTERVAL + jitter : jitter

    if (this._timer) clearTimeout(this._timer)

    const startTime = Date.now()
    this._timer = setTimeout(() => {
      // If your laptop went to sleep, and is coming back online...
      const overdue = Date.now() - startTime > delay + DELAY_GRACE_PERIOD
      if (overdue) this._refreshLater(true)
      else this.refresh().catch(this._onerror)
    }, delay)
  }

  _isActive() {
    return !this.destroyed && !this.suspended
  }

  // TODO: Allow announce to be an argument to this
  // TODO: Maybe announce should be a setter?
  async _refresh() {
    if (this.suspended) return
    const clock = ++this._refreshes

    if (this._wait) {
      await this._wait
      this._wait = null
      if (clock !== this._refreshes || !this._isActive()) return
    }

    const clear = this.isServer && this._firstAnnounce
    if (clear) this._firstAnnounce = false

    const opts = {
      clear,
      closestNodes: this._closestNodes
    }

    if (this.isServer) {
      await this.swarm.listen()
      // if a parallel refresh is happening, yield to the new one
      if (clock !== this._refreshes || !this._isActive()) return
      this._needsUnannounce = true
    }

    let limit = this.limit

    if (limit < Infinity && limit > 0) {
      for (const id of this._discovered) {
        if (!this.swarm.connections.has(id)) continue
        if (--limit === 0) break
      }
    }

    this._discovered.clear()

    const announcing = this.isServer
    const query = (this._activeQuery = announcing
      ? this.swarm.dht.announce(
          this.topic,
          this.swarm.keyPair,
          this.swarm.server.relayAddresses,
          opts
        )
      : this._needsUnannounce
        ? this.swarm.dht.lookupAndUnannounce(this.topic, this.swarm.keyPair, opts)
        : this.swarm.dht.lookup(this.topic, opts))

    try {
      for await (const data of this._activeQuery) {
        if (!this.isClient || !this._isActive()) continue
        for (const peer of data.peers) {
          if (limit < Infinity) {
            const id = b4a.toString(peer.publicKey, 'hex')

            if (this._discovered.size < MAX_DISCOVERY_CACHE) {
              this._discovered.add(id)
            }

            if (limit === 0) continue

            // there is a chance it has updated a connection during discovery and we go over
            // the limit - thats acceptable to avoid a complexity spiral here.
            if (!this.swarm.connections.has(id)) limit--
          }

          this._onpeer(peer, data)
        }
      }
    } catch (err) {
      if (this._isActive()) throw err
    } finally {
      if (this._activeQuery === query) {
        this._activeQuery = null
        if (!this.destroyed && !this.suspended) this._refreshLater(false)
      }
    }

    // This is set at the very end, when the query completes successfully.
    this._closestNodes = query.closestNodes

    if (clock !== this._refreshes) return

    // In this is the latest query, unannounce has been fulfilled as well
    if (!announcing) this._needsUnannounce = false
  }

  async refresh() {
    if (this.destroyed) throw new Error('PeerDiscovery is destroyed')

    const server = this._serverSessions > 0
    const client = this._clientSessions > 0

    if (this.suspended) return

    if (server === this.isServer && client === this.isClient) {
      if (this._currentRefresh) return this._currentRefresh
      this._currentRefresh = this._refresh()
    } else {
      if (this._activeQuery) this._activeQuery.destroy()
      this.isServer = server
      this.isClient = client
      this._currentRefresh = this._refresh()
    }

    const refresh = this._currentRefresh
    try {
      await refresh
    } catch {
      return false
    } finally {
      if (refresh === this._currentRefresh) {
        this._currentRefresh = null
      }
    }

    return true
  }

  async flushed() {
    if (this.swarm.listening) await this.swarm.listening

    try {
      await this._currentRefresh
      return true
    } catch {
      return false
    }
  }

  async _destroyMaybe() {
    if (this.destroyed) return

    try {
      if (this._sessions.length === 0) await this.swarm.leave(this.topic)
      else if (this._serverSessions === 0 && this._needsUnannounce) await this.refresh()
    } catch (err) {
      // ignore network failures here, as we are tearing down
      safetyCatch(err)
    }
  }

  destroy() {
    if (this.destroying) return this.destroying
    this.destroying = this._destroy()
    return this.destroying
  }

  async _abort(log) {
    const id = log === noop ? '' : b4a.toString(this.topic, 'hex')

    log('Aborting discovery', id)
    if (this._wait) await this._wait
    log('Aborting discovery (post wait)', id)

    if (this._activeQuery) {
      this._activeQuery.destroy()
      this._activeQuery = null
    }
    if (this._timer) {
      clearTimeout(this._timer)
      this._timer = null
    }

    let nodes = this._closestNodes

    if (this._currentRefresh) {
      try {
        await this._currentRefresh
      } catch {
        // If the destroy causes the refresh to fail, suppress it.
      }
    }

    log('Aborting discovery (post refresh)', id)
    if (this._isActive()) return

    if (!nodes) nodes = this._closestNodes
    else if (this._closestNodes !== nodes) {
      const len = nodes.length
      for (const newer of this._closestNodes) {
        if (newer.id && !hasNode(nodes, len, newer)) nodes.push(newer)
      }
    }

    if (this._needsUnannounce) {
      log('Unannouncing discovery', id)
      if (nodes && nodes.length) {
        await this.swarm.dht.unannounce(this.topic, this.swarm.keyPair, {
          closestNodes: nodes,
          onlyClosestNodes: true,
          force: true
        })
      }
      this._needsUnannounce = false
      log('Unannouncing discovery (done)', id)
    }
  }

  _destroy() {
    if (this.destroyed) return
    this.destroyed = true
    return this._abort(noop)
  }

  async suspend({ log = noop } = {}) {
    if (this.suspended) return
    this.suspended = true
    try {
      await this._abort(log)
    } catch {
      // ignore
    }
  }

  resume() {
    if (!this.suspended) return
    this.suspended = false
    this.refresh().catch(noop)
  }
}

class PeerDiscoverySession {
  constructor(discovery) {
    this.discovery = discovery
    this.isClient = false
    this.isServer = false
    this.destroyed = false
  }

  get swarm() {
    return this.discovery.swarm
  }

  get topic() {
    return this.discovery.topic
  }

  async refresh({ client = this.isClient, server = this.isServer, limit = Infinity } = {}) {
    if (this.destroyed) throw new Error('PeerDiscovery is destroyed')
    if (!client && !server) throw new Error('Cannot refresh with neither client nor server option')

    if (client !== this.isClient) {
      this.isClient = client
      this.discovery._clientSessions += client ? 1 : -1
    }

    if (server !== this.isServer) {
      this.isServer = server
      this.discovery._serverSessions += server ? 1 : -1
    }

    this.discovery.limit = limit

    return this.discovery.refresh()
  }

  async flushed() {
    return this.discovery.flushed()
  }

  async destroy() {
    if (this.destroyed) return
    this.destroyed = true

    if (this.isClient) this.discovery._clientSessions--
    if (this.isServer) this.discovery._serverSessions--

    const index = this.discovery._sessions.indexOf(this)
    const head = this.discovery._sessions.pop()

    if (head !== this) this.discovery._sessions[index] = head

    return this.discovery._destroyMaybe()
  }
}

function hasNode(nodes, len, node) {
  for (let i = 0; i < len; i++) {
    const existing = nodes[i]
    if (existing.id && b4a.equals(existing.id, node.id)) return true
  }

  return false
}

function noop() {}
const { EventEmitter } = require('events')
const b4a = require('b4a')
const unslab = require('unslab')

const MIN_CONNECTION_TIME = 15000

const VERY_LOW_PRIORITY = 0
const LOW_PRIORITY = 1
const NORMAL_PRIORITY = 2
const HIGH_PRIORITY = 3
const VERY_HIGH_PRIORITY = 4

module.exports = class PeerInfo extends EventEmitter {
  constructor({ publicKey, relayAddresses }) {
    super()

    this.publicKey = unslab(publicKey)
    this.relayAddresses = relayAddresses

    this.reconnecting = true
    this.proven = false
    this.connectedTime = -1
    this.disconnectedTime = 0
    this.banned = false
    this.tried = false
    this.explicit = false
    this.waiting = false
    this.forceRelaying = false

    // Set by the Swarm
    this.queued = false
    this.client = false
    this.topics = [] // TODO: remove on next major (check with mafintosh for context)

    this.attempts = 0
    this.priority = NORMAL_PRIORITY

    // Used by shuffled-priority-queue
    this._index = 0

    // Used for flush management
    this._flushTick = 0

    // Used for topic multiplexing
    this._seenTopics = new Set()
  }

  get server() {
    return !this.client
  }

  get prioritized() {
    return this.priority >= NORMAL_PRIORITY
  }

  _getPriority() {
    const peerIsStale = this.tried && !this.proven
    if (peerIsStale || this.attempts > 3) return VERY_LOW_PRIORITY
    if (this.attempts === 3) return LOW_PRIORITY
    if (this.attempts === 2) return HIGH_PRIORITY
    if (this.attempts === 1) return VERY_HIGH_PRIORITY
    return NORMAL_PRIORITY
  }

  _connected() {
    this.proven = true
    this.connectedTime = Date.now()
  }

  _disconnected() {
    this.disconnectedTime = Date.now()
    if (this.connectedTime > -1) {
      if (this.disconnectedTime - this.connectedTime >= MIN_CONNECTION_TIME) this.attempts = 0 // fast retry
      this.connectedTime = -1
    }
    this.attempts++
  }

  _deprioritize() {
    this.attempts = 3
  }

  _reset() {
    this.client = false
    this.proven = false
    this.tried = false
    this.attempts = 0
  }

  _updatePriority() {
    if (this.explicit && this.attempts > 3) this._deprioritize()
    if (this.banned || this.queued || this.attempts > 3) return false
    this.priority = this._getPriority()
    return true
  }

  _topic(topic) {
    const topicString = b4a.toString(topic, 'hex')
    if (this._seenTopics.has(topicString)) return
    this._seenTopics.add(topicString)
    this.topics.push(topic)
    this.emit('topic', topic)
  }

  reconnect(val) {
    this.reconnecting = !!val
  }

  ban(val) {
    this.banned = !!val
  }

  shouldGC() {
    return !(this.banned || this.queued || this.explicit || this.waiting)
  }
}
const BulkTimer = require('./bulk-timer')

const BACKOFF_JITTER = 500
const BACKOFF_S = 1000 + Math.round(BACKOFF_JITTER * Math.random())
const BACKOFF_M = 5000 + Math.round(2 * BACKOFF_JITTER * Math.random())
const BACKOFF_L = 15000 + Math.round(4 * BACKOFF_JITTER * Math.random())
const BACKOFF_X = 1000 * 60 * 10 + Math.round(240 * BACKOFF_JITTER * Math.random())

module.exports = class RetryTimer {
  constructor(
    push,
    { backoffs = [BACKOFF_S, BACKOFF_M, BACKOFF_L, BACKOFF_X], jitter = BACKOFF_JITTER } = {}
  ) {
    this.jitter = jitter
    this.backoffs = backoffs

    this._sTimer = new BulkTimer(backoffs[0] + Math.round(jitter * Math.random()), push)
    this._mTimer = new BulkTimer(backoffs[1] + Math.round(jitter * Math.random()), push)
    this._lTimer = new BulkTimer(backoffs[2] + Math.round(jitter * Math.random()), push)
    this._xTimer = new BulkTimer(backoffs[3] + Math.round(jitter * Math.random()), push)
  }

  _selectRetryTimer(peerInfo) {
    if (peerInfo.banned || !peerInfo.reconnecting) return null

    if (peerInfo.attempts > 3) {
      return peerInfo.explicit ? this._xTimer : null
    }

    if (peerInfo.attempts === 0) return this._sTimer
    if (peerInfo.proven) {
      switch (peerInfo.attempts) {
        case 1:
          return this._sTimer
        case 2:
          return this._mTimer
        case 3:
          return this._lTimer
      }
    } else {
      switch (peerInfo.attempts) {
        case 1:
          return this._mTimer
        case 2:
          return this._lTimer
        case 3:
          return this._lTimer
      }
    }

    return null
  }

  add(peerInfo) {
    const timer = this._selectRetryTimer(peerInfo)
    if (!timer) return false

    timer.add(peerInfo)
    return true
  }

  destroy() {
    this._sTimer.destroy()
    this._mTimer.destroy()
    this._lTimer.destroy()
    this._xTimer.destroy()
  }
}
{
  "name": "hyperswarm",
  "version": "4.17.0",
  "description": "A distributed networking stack for connecting peers",
  "files": [
    "index.js",
    "lib/**.js"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    },
    "process": {
      "bare": "bare-process",
      "default": "process"
    }
  },
  "dependencies": {
    "b4a": "^1.3.1",
    "bare-events": "^2.2.0",
    "hyperdht": "^6.21.0",
    "safety-catch": "^1.0.2",
    "shuffled-priority-queue": "^2.1.0",
    "streamx": "^2.22.1",
    "unslab": "^1.3.0"
  },
  "devDependencies": {
    "bare-process": "^4.2.2",
    "brittle": "^3.0.2",
    "hypercore-crypto": "^3.4.0",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "which-runtime": "^1.3.2"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:generate": "brittle -r test/all.js test/*.js",
    "test:node": "brittle-node --coverage test/*.js",
    "test:bare": "bare test/all.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/hyperswarm.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "contributors": [
    "David Mark Clements (@davidmarkclem)",
    "Andrew Osheroff (@andrewosh)"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/hyperswarm/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperswarm"
}
const b4a = require('b4a')

module.exports = function isOptions (opts) {
  return typeof opts === 'object' && opts && !b4a.isBuffer(opts)
}
{
  "name": "is-options",
  "version": "1.0.2",
  "description": "Easily check if input is an options map",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.1.1"
  },
  "devDependencies": {
    "standard": "^11.0.1",
    "tape": "^4.9.0"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/is-options.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/is-options/issues"
  },
  "homepage": "https://github.com/mafintosh/is-options"
}
const { EventEmitter } = require('events')

module.exports = class RoutingTable extends EventEmitter {
  constructor (id, opts) {
    if (!opts) opts = {}

    super()

    this.id = id
    this.k = opts.k || 20
    this.size = 0
    this.rows = new Array(id.length * 8)
  }

  add (node) {
    const i = this._diff(node.id)

    let row = this.rows[i]

    if (!row) {
      row = this.rows[i] = new Row(this, i)
      this.emit('row', row)
    }

    const len = row.nodes.length
    if (!row.add(node, this.k)) return false

    this.size += row.nodes.length - len
    return true
  }

  remove (id) {
    const i = this._diff(id)
    const row = this.rows[i]
    if (!row) return false
    if (!row.remove(id)) return false
    this.size--
    return true
  }

  get (id) {
    const i = this._diff(id)
    const row = this.rows[i]
    if (!row) return null
    return row.get(id)
  }

  has (id) {
    return this.get(id) !== null
  }

  random () {
    let n = (Math.random() * this.size) | 0

    for (let i = 0; i < this.rows.length; i++) {
      const r = this.rows[i]
      if (!r) continue
      if (n < r.nodes.length) return r.nodes[n]
      n -= r.nodes.length
    }

    return null
  }

  closest (id, k) {
    if (!k) k = this.k

    const result = []
    const d = this._diff(id)

    // push close nodes
    for (let i = d; i >= 0 && result.length < k; i--) this._pushNodes(i, k, result)

    // if we don't have enough close nodes, populate from other rows, re the paper
    for (let i = d + 1; i < this.rows.length && result.length < k; i++) this._pushNodes(i, k, result)

    return result
  }

  _pushNodes (i, k, result) {
    const row = this.rows[i]
    if (!row) return

    const missing = Math.min(k - result.length, row.nodes.length)
    for (let j = 0; j < missing; j++) result.push(row.nodes[j])
  }

  toArray () {
    return this.closest(this.id, Infinity)
  }

  _diff (id) {
    for (let i = 0; i < id.length; i++) {
      const a = id[i]
      const b = this.id[i]

      if (a !== b) return i * 8 + Math.clz32(a ^ b) - 24
    }

    return this.rows.length - 1
  }
}

class Row extends EventEmitter {
  constructor (table, index) {
    super()

    this.data = null // can be used be upstream for whatevs
    this.byteOffset = index >> 3
    this.index = index
    this.table = table
    this.nodes = []
  }

  add (node) {
    const id = node.id

    let l = 0
    let r = this.nodes.length - 1

    while (l <= r) {
      const m = (l + r) >> 1
      const c = this.compare(id, this.nodes[m].id)

      if (c === 0) {
        this.nodes[m] = node
        return true
      }

      if (c < 0) r = m - 1
      else l = m + 1
    }

    if (this.nodes.length >= this.table.k) {
      this.emit('full', node)
      return false
    }

    this.insert(l, node)
    return true
  }

  remove (id) {
    let l = 0
    let r = this.nodes.length - 1

    while (l <= r) {
      const m = (l + r) >> 1
      const c = this.compare(id, this.nodes[m].id)

      if (c === 0) {
        this.splice(m)
        return true
      }

      if (c < 0) r = m - 1
      else l = m + 1
    }

    return false
  }

  get (id) {
    let l = 0
    let r = this.nodes.length - 1

    while (l <= r) {
      const m = (l + r) >> 1
      const node = this.nodes[m]
      const c = this.compare(id, node.id)

      if (c === 0) return node
      if (c < 0) r = m - 1
      else l = m + 1
    }

    return null
  }

  insert (i, node) {
    this.nodes.push(node) // push node or null or whatevs, just trying to not be polymorphic
    for (let j = this.nodes.length - 1; j > i; j--) this.nodes[j] = this.nodes[j - 1]
    this.nodes[i] = node
    this.emit('add', node)
  }

  splice (i) {
    for (; i < this.nodes.length - 1; i++) this.nodes[i] = this.nodes[i + 1]
    this.emit('remove', this.nodes.pop())
  }

  // very likely they diverge after a couple of bytes so a simple impl, like this is prop fastest vs Buffer.compare
  compare (a, b) {
    for (let i = this.byteOffset; i < a.length; i++) {
      const ai = a[i]
      const bi = b[i]
      if (ai === bi) continue
      return ai < bi ? -1 : 1
    }
    return 0
  }
}
{
  "name": "kademlia-routing-table",
  "version": "1.0.6",
  "description": "XOR based routing table used for P2P networks such as a Kademlia DHT.",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "dependencies": {
    "bare-events": "^2.2.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "standard": "^17.1.0"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "keywords": [
    "kademlia",
    "p2p",
    "k-bucket",
    "k-buckets",
    "xor",
    "routing",
    "distributed",
    "systems"
  ],
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/kademlia-routing-table.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/kademlia-routing-table/issues"
  },
  "homepage": "https://github.com/mafintosh/kademlia-routing-table"
}
module.exports = assert

class AssertionError extends Error {}
AssertionError.prototype.name = 'AssertionError'

/**
 * Minimal assert function
 * @param  {any} t Value to check if falsy
 * @param  {string=} m Optional assertion error message
 * @throws {AssertionError}
 */
function assert (t, m) {
  if (!t) {
    var err = new AssertionError(m)
    if (Error.captureStackTrace) Error.captureStackTrace(err, assert)
    throw err
  }
}
{
  "name": "nanoassert",
  "version": "2.0.0",
  "description": "Nanoscale assertion module",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "tape": "^4.9.1"
  },
  "scripts": {
    "test": "tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/emilbayes/nanoassert.git"
  },
  "keywords": [
    "assert",
    "unassert",
    "power-assert",
    "tiny",
    "nano",
    "pico"
  ],
  "author": "Emil Bay <github@tixz.dk>",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/emilbayes/nanoassert/issues"
  },
  "homepage": "https://github.com/emilbayes/nanoassert#readme"
}
module.exports = class NatSampler {
  constructor () {
    this.host = null
    this.port = 0
    this.size = 0

    this._a = null
    this._b = null
    this._threshold = 0
    this._top = 0
    this._samples = []
  }

  add (host, port) {
    const a = this._bump(host, port, 2)
    const b = this._bump(host, 0, 1)

    if (this._samples.length < 32) {
      this.size++
      this._threshold = this.size - (this.size < 4 ? 0 : this.size < 8 ? 1 : this.size < 12 ? 2 : 3)
      this._samples.push(a, b)
      this._top += 2
    } else {
      if (this._top === 32) this._top = 0

      const oa = this._samples[this._top]
      this._samples[this._top++] = a
      oa.hits--

      const ob = this._samples[this._top]
      this._samples[this._top++] = b
      ob.hits--
    }

    if (this._a === null || this._a.hits < a.hits) this._a = a
    if (this._b === null || this._b.hits < b.hits) this._b = b

    if (this._a.hits >= this._threshold) {
      this.host = this._a.host
      this.port = this._a.port
    } else if (this._b.hits >= this._threshold) {
      this.host = this._b.host
      this.port = 0
    } else {
      this.host = null
      this.port = 0
    }

    return a.hits
  }

  _bump (host, port, inc) {
    for (let i = 0; i < 4; i++) {
      const j = (this._top - inc - (2 * i)) & 31
      if (j >= this._samples.length) return { host, port, hits: 1 }
      const s = this._samples[j]
      if (s.port === port && s.host === host) {
        s.hits++
        return s
      }
    }
    return { host, port, hits: 1 }
  }
}
{
  "name": "nat-sampler",
  "version": "1.0.1",
  "description": "Sample addresses to figure out if a host + port is consistent",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^16.0.3",
    "tape": "^5.2.2"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/nat-sampler.git"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/nat-sampler/issues"
  },
  "homepage": "https://github.com/mafintosh/nat-sampler"
}
/* eslint-disable camelcase */
const sodium = require('sodium-universal')
const assert = require('nanoassert')
const b4a = require('b4a')

const DHLEN = sodium.crypto_scalarmult_ed25519_BYTES
const PKLEN = sodium.crypto_scalarmult_ed25519_BYTES
const SCALARLEN = sodium.crypto_scalarmult_ed25519_BYTES
const SKLEN = sodium.crypto_sign_SECRETKEYBYTES
const ALG = 'Ed25519'

module.exports = {
  DHLEN,
  PKLEN,
  SCALARLEN,
  SKLEN,
  ALG,
  name: ALG,
  generateKeyPair,
  dh
}

function generateKeyPair (privKey) {
  if (privKey) return generateSeedKeyPair(privKey.subarray(0, 32))

  const keyPair = {}
  keyPair.secretKey = b4a.alloc(SKLEN)
  keyPair.publicKey = b4a.alloc(PKLEN)

  sodium.crypto_sign_keypair(keyPair.publicKey, keyPair.secretKey)
  return keyPair
}

function generateSeedKeyPair (seed) {
  const keyPair = {}
  keyPair.secretKey = b4a.alloc(SKLEN)
  keyPair.publicKey = b4a.alloc(PKLEN)

  sodium.crypto_sign_seed_keypair(keyPair.publicKey, keyPair.secretKey, seed)
  return keyPair
}

function dh (publicKey, { scalar, secretKey }) {
  // tweaked keys expose scalar directly
  if (!scalar) {
    assert(secretKey.byteLength === SKLEN)

    // libsodium stores seed not actual scalar
    const sk = b4a.alloc(64)
    sodium.crypto_hash_sha512(sk, secretKey.subarray(0, 32))
    sk[0] &= 248
    sk[31] &= 127
    sk[31] |= 64

    scalar = sk.subarray(0, 32)
  }

  assert(scalar.byteLength === SCALARLEN)
  assert(publicKey.byteLength === PKLEN)

  const output = b4a.alloc(DHLEN)

  // we clamp if necessary above
  sodium.crypto_scalarmult_ed25519_noclamp(
    output,
    scalar,
    publicKey
  )

  return output
}
{
  "name": "noise-curve-ed",
  "version": "2.1.0",
  "description": "Ed25519 elliptic curve operations for [`noise-handshake`](https://github.com/chm-diederichs/noise-handshake)",
  "main": "index.js",
  "scripts": {
    "test": "npx standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/chm-diederichs/noise-curve-ed.git"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/chm-diederichs/noise-curve-ed/issues"
  },
  "homepage": "https://github.com/chm-diederichs/noise-curve-ed#readme",
  "dependencies": {
    "b4a": "^1.1.0",
    "nanoassert": "^2.0.0",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "noise-handshake": "^3.0.0",
    "standard": "^16.0.3",
    "tape": "^5.2.2"
  }
}
const sodium = require('sodium-universal')
const b4a = require('b4a')

module.exports = class CipherState {
  constructor (key) {
    this.key = key || null
    this.nonce = 0
    this.CIPHER_ALG = 'ChaChaPoly'
  }

  initialiseKey (key) {
    this.key = key
    this.nonce = 0
  }

  setNonce (nonce) {
    this.nonce = nonce
  }

  encrypt (plaintext, ad) {
    if (!this.hasKey) return plaintext
    if (!ad) ad = b4a.alloc(0)

    const ciphertext = encryptWithAD(this.key, this.nonce, ad, plaintext)
    if (ciphertext.length > 65535) throw new Error(`ciphertext length of ${ciphertext.length} exceeds maximum Noise message length of 65535`)
    this.nonce++

    return ciphertext
  }

  decrypt (ciphertext, ad) {
    if (!this.hasKey) return ciphertext
    if (!ad) ad = b4a.alloc(0)
    if (ciphertext.length > 65535) throw new Error(`ciphertext length of ${ciphertext.length} exceeds maximum Noise message length of 65535`)

    const plaintext = decryptWithAD(this.key, this.nonce, ad, ciphertext)
    this.nonce++

    return plaintext
  }

  get hasKey () {
    return this.key !== null
  }

  _clear () {
    sodium.sodium_memzero(this.key)
    this.key = null
    this.nonce = null
  }

  static get MACBYTES () {
    return 16
  }

  static get NONCEBYTES () {
    return 8
  }

  static get KEYBYTES () {
    return 32
  }
}

function encryptWithAD (key, counter, additionalData, plaintext) {
  // for our purposes, additionalData will always be a pubkey so we encode from hex
  if (!b4a.isBuffer(additionalData)) additionalData = b4a.from(additionalData, 'hex')
  if (!b4a.isBuffer(plaintext)) plaintext = b4a.from(plaintext, 'hex')

  const nonce = b4a.alloc(sodium.crypto_aead_chacha20poly1305_ietf_NPUBBYTES)
  const view = new DataView(nonce.buffer, nonce.byteOffset, nonce.byteLength)
  view.setUint32(4, counter, true)

  const ciphertext = b4a.alloc(plaintext.byteLength + sodium.crypto_aead_chacha20poly1305_ietf_ABYTES)

  sodium.crypto_aead_chacha20poly1305_ietf_encrypt(ciphertext, plaintext, additionalData, null, nonce, key)
  return ciphertext
}

function decryptWithAD (key, counter, additionalData, ciphertext) {
  // for our purposes, additionalData will always be a pubkey so we encode from hex
  if (!b4a.isBuffer(additionalData)) additionalData = b4a.from(additionalData, 'hex')
  if (!b4a.isBuffer(ciphertext)) ciphertext = b4a.from(ciphertext, 'hex')

  const nonce = b4a.alloc(sodium.crypto_aead_chacha20poly1305_ietf_NPUBBYTES)
  const view = new DataView(nonce.buffer, nonce.byteOffset, nonce.byteLength)
  view.setUint32(4, counter, true)

  const plaintext = b4a.alloc(ciphertext.byteLength - sodium.crypto_aead_chacha20poly1305_ietf_ABYTES)

  sodium.crypto_aead_chacha20poly1305_ietf_decrypt(plaintext, null, ciphertext, additionalData, nonce, key)
  return plaintext
}
/* eslint-disable camelcase */
const {
  crypto_kx_SEEDBYTES,
  crypto_kx_keypair,
  crypto_kx_seed_keypair,
  crypto_scalarmult_BYTES,
  crypto_scalarmult_SCALARBYTES,
  crypto_scalarmult,
  crypto_scalarmult_base
} = require('sodium-universal')

const assert = require('nanoassert')
const b4a = require('b4a')

const DHLEN = crypto_scalarmult_BYTES
const PKLEN = crypto_scalarmult_BYTES
const SKLEN = crypto_scalarmult_SCALARBYTES
const SEEDLEN = crypto_kx_SEEDBYTES
const ALG = '25519'

module.exports = {
  DHLEN,
  PKLEN,
  SKLEN,
  SEEDLEN,
  ALG,
  generateKeyPair,
  generateSeedKeyPair,
  dh
}

function generateKeyPair (privKey) {
  const keyPair = {}

  keyPair.secretKey = privKey || b4a.alloc(SKLEN)
  keyPair.publicKey = b4a.alloc(PKLEN)

  if (privKey) {
    crypto_scalarmult_base(keyPair.publicKey, keyPair.secretKey)
  } else {
    crypto_kx_keypair(keyPair.publicKey, keyPair.secretKey)
  }

  return keyPair
}

function generateSeedKeyPair (seed) {
  assert(seed.byteLength === SKLEN)

  const keyPair = {}
  keyPair.secretKey = b4a.alloc(SKLEN)
  keyPair.publicKey = b4a.alloc(PKLEN)

  crypto_kx_seed_keypair(keyPair.publicKey, keyPair.secretKey, seed)
  return keyPair
}

function dh (publicKey, { secretKey }) {
  assert(secretKey.byteLength === SKLEN)
  assert(publicKey.byteLength === PKLEN)

  const output = b4a.alloc(DHLEN)

  crypto_scalarmult(
    output,
    secretKey,
    publicKey
  )

  return output
}
const hmacBlake2b = require('./hmac')
const b4a = require('b4a')

const HASHLEN = 64

module.exports = {
  hkdf,
  HASHLEN
}

// HMAC-based Extract-and-Expand KDF
// https://www.ietf.org/rfc/rfc5869.txt

function hkdf (salt, inputKeyMaterial, info = '', length = 2 * HASHLEN) {
  const pseudoRandomKey = hkdfExtract(salt, inputKeyMaterial)
  return hkdfExpand(pseudoRandomKey, info, length)
}

function hkdfExtract (salt, inputKeyMaterial) {
  const hmac = b4a.alloc(HASHLEN)
  return hmacDigest(hmac, salt, inputKeyMaterial)
}

function hkdfExpand (key, info, length) {
  // Put in dedicated slab to avoid keeping shared slab from being gc'ed
  const buffer = b4a.allocUnsafeSlow(length)

  const infoBuf = b4a.from(info)
  let prev = infoBuf

  const result = []
  for (let i = 0; i < length; i += HASHLEN) {
    const pos = b4a.from([(i / HASHLEN) + 1])

    const out = buffer.subarray(i, i + HASHLEN)
    result.push(out)

    prev = hmacDigest(out, key, [prev, infoBuf, pos])
  }

  return result
}

function hmacDigest (out, key, input) {
  hmacBlake2b(out, input, key)
  return out
}
/* eslint-disable camelcase */
const b4a = require('b4a')
const { sodium_memzero, crypto_generichash, crypto_generichash_batch } = require('sodium-universal')

const HASHLEN = 64
const BLOCKLEN = 128
const scratch = b4a.alloc(BLOCKLEN * 3)
const HMACKey = scratch.subarray(BLOCKLEN * 0, BLOCKLEN * 1)
const OuterKeyPad = scratch.subarray(BLOCKLEN * 1, BLOCKLEN * 2)
const InnerKeyPad = scratch.subarray(BLOCKLEN * 2, BLOCKLEN * 3)

// Post-fill is done in the cases where someone caught an exception that
// happened before we were able to clear data at the end

module.exports = function hmac (out, batch, key) {
  if (key.byteLength > BLOCKLEN) {
    crypto_generichash(HMACKey.subarray(0, HASHLEN), key)
    sodium_memzero(HMACKey.subarray(HASHLEN))
  } else {
    // Covers key <= BLOCKLEN
    HMACKey.set(key)
    sodium_memzero(HMACKey.subarray(key.byteLength))
  }

  for (let i = 0; i < HMACKey.byteLength; i++) {
    OuterKeyPad[i] = 0x5c ^ HMACKey[i]
    InnerKeyPad[i] = 0x36 ^ HMACKey[i]
  }
  sodium_memzero(HMACKey)

  crypto_generichash_batch(out, [InnerKeyPad].concat(batch))
  sodium_memzero(InnerKeyPad)
  crypto_generichash_batch(out, [OuterKeyPad, out])
  sodium_memzero(OuterKeyPad)
}

module.exports.BYTES = HASHLEN
module.exports.KEYBYTES = BLOCKLEN
const assert = require('nanoassert')
const b4a = require('b4a')

const SymmetricState = require('./symmetric-state')
const { HASHLEN } = require('./hkdf')

const PRESHARE_IS = Symbol('initiator static key preshared')
const PRESHARE_RS = Symbol('responder static key preshared')

const TOK_PSK = Symbol('psk')

const TOK_S = Symbol('s')
const TOK_E = Symbol('e')

const TOK_ES = Symbol('es')
const TOK_SE = Symbol('se')
const TOK_EE = Symbol('ee')
const TOK_SS = Symbol('ss')

const HANDSHAKES = Object.freeze({
  NN: [
    [TOK_E],
    [TOK_E, TOK_EE]
  ],
  NNpsk0: [
    [TOK_PSK, TOK_E],
    [TOK_E, TOK_EE]
  ],
  XX: [
    [TOK_E],
    [TOK_E, TOK_EE, TOK_S, TOK_ES],
    [TOK_S, TOK_SE]
  ],
  XXpsk0: [
    [TOK_PSK, TOK_E],
    [TOK_E, TOK_EE, TOK_S, TOK_ES],
    [TOK_S, TOK_SE]
  ],
  IK: [
    PRESHARE_RS,
    [TOK_E, TOK_ES, TOK_S, TOK_SS],
    [TOK_E, TOK_EE, TOK_SE]
  ],
  XK: [
    PRESHARE_RS,
    [TOK_E, TOK_ES],
    [TOK_E, TOK_EE],
    [TOK_S, TOK_SE]
  ]
})

class Writer {
  constructor () {
    this.size = 0
    this.buffers = []
  }

  push (b) {
    this.size += b.byteLength
    this.buffers.push(b)
  }

  end () {
    const all = b4a.alloc(this.size)
    let offset = 0
    for (const b of this.buffers) {
      all.set(b, offset)
      offset += b.byteLength
    }
    return all
  }
}

class Reader {
  constructor (buf) {
    this.offset = 0
    this.buffer = buf
  }

  shift (n) {
    const start = this.offset
    const end = this.offset += n
    if (end > this.buffer.byteLength) throw new Error('Insufficient bytes')
    return this.buffer.subarray(start, end)
  }

  end () {
    return this.shift(this.buffer.byteLength - this.offset)
  }
}

module.exports = class NoiseState extends SymmetricState {
  constructor (pattern, initiator, staticKeypair, opts = {}) {
    super(opts)

    this.s = staticKeypair || this.curve.generateKeyPair()
    this.e = null

    this.psk = null
    if (opts && opts.psk) this.psk = opts.psk

    this.re = null
    this.rs = null

    this.pattern = pattern
    this.handshake = HANDSHAKES[this.pattern].slice()

    this.isPskHandshake = !!this.psk && hasPskToken(this.handshake)

    this.protocol = b4a.from([
      'Noise',
      this.pattern,
      this.DH_ALG,
      this.CIPHER_ALG,
      'BLAKE2b'
    ].join('_'))

    this.initiator = initiator
    this.complete = false

    this.rx = null
    this.tx = null
    this.hash = null
  }

  initialise (prologue, remoteStatic) {
    if (this.protocol.byteLength <= HASHLEN) this.digest.set(this.protocol)
    else this.mixHash(this.protocol)

    this.chainingKey = b4a.from(this.digest)

    this.mixHash(prologue)

    while (!Array.isArray(this.handshake[0])) {
      const message = this.handshake.shift()

      // handshake steps should be as arrays, only
      // preshare tokens are provided otherwise
      assert(message === PRESHARE_RS || message === PRESHARE_IS,
        'Unexpected pattern')

      const takeRemoteKey = this.initiator
        ? message === PRESHARE_RS
        : message === PRESHARE_IS

      if (takeRemoteKey) this.rs = remoteStatic

      const key = takeRemoteKey ? this.rs : this.s.publicKey
      assert(key != null, 'Remote pubkey required')

      this.mixHash(key)
    }
  }

  final () {
    const [k1, k2] = this.split()

    this.tx = this.initiator ? k1 : k2
    this.rx = this.initiator ? k2 : k1

    this.complete = true
    this.hash = this.getHandshakeHash()

    this._clear()
  }

  recv (buf) {
    const r = new Reader(buf)

    for (const pattern of this.handshake.shift()) {
      switch (pattern) {
        case TOK_PSK :
          this.mixKeyAndHash(this.psk)
          break

        case TOK_E :
          this.re = r.shift(this.curve.PKLEN)
          this.mixHash(this.re)
          if (this.isPskHandshake) this.mixKeyNormal(this.re)
          break

        case TOK_S : {
          const klen = this.hasKey ? this.curve.PKLEN + 16 : this.curve.PKLEN
          this.rs = this.decryptAndHash(r.shift(klen))
          break
        }

        case TOK_EE :
        case TOK_ES :
        case TOK_SE :
        case TOK_SS : {
          const useStatic = keyPattern(pattern, this.initiator)

          const localKey = useStatic.local ? this.s : this.e
          const remoteKey = useStatic.remote ? this.rs : this.re

          this.mixKey(remoteKey, localKey)
          break
        }

        default :
          throw new Error('Unexpected message')
      }
    }

    const payload = this.decryptAndHash(r.end())

    if (!this.handshake.length) this.final()
    return payload
  }

  send (payload = b4a.alloc(0)) {
    const w = new Writer()

    for (const pattern of this.handshake.shift()) {
      switch (pattern) {
        case TOK_PSK :
          this.mixKeyAndHash(this.psk)
          break

        case TOK_E :
          if (this.e === null) this.e = this.curve.generateKeyPair()
          this.mixHash(this.e.publicKey)
          if (this.isPskHandshake) this.mixKeyNormal(this.e.publicKey)
          w.push(this.e.publicKey)
          break

        case TOK_S :
          w.push(this.encryptAndHash(this.s.publicKey))
          break

        case TOK_ES :
        case TOK_SE :
        case TOK_EE :
        case TOK_SS : {
          const useStatic = keyPattern(pattern, this.initiator)

          const localKey = useStatic.local ? this.s : this.e
          const remoteKey = useStatic.remote ? this.rs : this.re

          this.mixKey(remoteKey, localKey)
          break
        }

        default :
          throw new Error('Unexpected message')
      }
    }

    w.push(this.encryptAndHash(payload))
    const response = w.end()

    if (!this.handshake.length) this.final()
    return response
  }

  _clear () {
    super._clear()

    this.e.secretKey.fill(0)
    this.e.publicKey.fill(0)

    this.re.fill(0)

    this.e = null
    this.re = null
  }
}

function keyPattern (pattern, initiator) {
  const ret = {
    local: false,
    remote: false
  }

  switch (pattern) {
    case TOK_EE:
      return ret

    case TOK_ES:
      ret.local ^= !initiator
      ret.remote ^= initiator
      return ret

    case TOK_SE:
      ret.local ^= initiator
      ret.remote ^= !initiator
      return ret

    case TOK_SS:
      ret.local ^= 1
      ret.remote ^= 1
      return ret
  }
}

function hasPskToken (handshake) {
  return handshake.some(x => {
    return Array.isArray(x) && x.indexOf(TOK_PSK) !== -1
  })
}
{
  "name": "noise-handshake",
  "version": "4.2.0",
  "description": "Noise protocol handshake",
  "main": "noise.js",
  "files": [
    "*.js"
  ],
  "scripts": {
    "test": "standard && brittle test/*.js"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/noise-handshake.git"
  },
  "dependencies": {
    "b4a": "^1.1.0",
    "nanoassert": "^2.0.0",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "noise-protocol": "chm-diederichs/noise-protocol.git#xx-ephemeral-key",
    "standard": "^16.0.3"
  }
}
const sodium = require('sodium-universal')
const assert = require('nanoassert')
const b4a = require('b4a')
const CipherState = require('./cipher')
const curve = require('./dh')
const { HASHLEN, hkdf } = require('./hkdf')

module.exports = class SymmetricState extends CipherState {
  constructor (opts = {}) {
    super()

    this.curve = opts.curve || curve
    this.digest = b4a.alloc(HASHLEN)
    this.chainingKey = null
    this.offset = 0

    this.DH_ALG = this.curve.ALG
  }

  mixHash (data) {
    accumulateDigest(this.digest, data)
  }

  mixKeyAndHash (key) {
    const [ck, tempH, tempK] = hkdf(this.chainingKey, key, '', 3 * HASHLEN)
    this.chainingKey = ck
    this.mixHash(tempH)
    this.initialiseKey(tempK.subarray(0, 32))
  }

  mixKeyNormal (key) {
    const [ck, tempK] = hkdf(this.chainingKey, key)
    this.chainingKey = ck
    this.initialiseKey(tempK.subarray(0, 32))
  }

  mixKey (remoteKey, localKey) {
    const dh = this.curve.dh(remoteKey, localKey)
    const hkdfResult = hkdf(this.chainingKey, dh)
    this.chainingKey = hkdfResult[0]
    this.initialiseKey(hkdfResult[1].subarray(0, 32))
  }

  encryptAndHash (plaintext) {
    const ciphertext = this.encrypt(plaintext, this.digest)
    accumulateDigest(this.digest, ciphertext)
    return ciphertext
  }

  decryptAndHash (ciphertext) {
    const plaintext = this.decrypt(ciphertext, this.digest)
    accumulateDigest(this.digest, ciphertext)
    return plaintext
  }

  getHandshakeHash (out) {
    if (!out) return this.getHandshakeHash(b4a.alloc(HASHLEN))
    assert(out.byteLength === HASHLEN, `output must be ${HASHLEN} bytes`)

    out.set(this.digest)
    return out
  }

  split () {
    const res = hkdf(this.chainingKey, b4a.alloc(0))
    return res.map(k => k.subarray(0, 32))
  }

  _clear () {
    super._clear()

    sodium.sodium_memzero(this.digest)
    sodium.sodium_memzero(this.chainingKey)

    this.digest = null
    this.chainingKey = null
    this.offset = null

    this.curve = null
  }

  static get alg () {
    return CipherState.alg + '_BLAKE2b'
  }
}

function accumulateDigest (digest, input) {
  const toHash = b4a.concat([digest, input])
  sodium.crypto_generichash(digest, toHash)
}
const b4a = require('b4a')
const c = require('compact-encoding')
const queueTick = require('queue-tick')
const safetyCatch = require('safety-catch')
const unslab = require('unslab')

const MAX_BUFFERED = 32768
const MAX_BACKLOG = Infinity // TODO: impl "open" backpressure
const MAX_BATCH = 8 * 1024 * 1024

class Channel {
  constructor(
    mux,
    info,
    userData,
    protocol,
    aliases,
    id,
    handshake,
    messages,
    onopen,
    onclose,
    ondestroy,
    ondrain
  ) {
    this.userData = userData
    this.protocol = protocol
    this.aliases = aliases
    this.id = id
    this.handshake = null
    this.messages = []

    this.opened = false
    this.closed = false
    this.destroyed = false

    this.onopen = onopen
    this.onclose = onclose
    this.ondestroy = ondestroy
    this.ondrain = ondrain

    this._handshake = handshake
    this._mux = mux
    this._info = info
    this._localId = 0
    this._remoteId = 0
    this._active = 0
    this._extensions = null

    this._decBound = this._dec.bind(this)
    this._decAndDestroyBound = this._decAndDestroy.bind(this)

    this._openedPromise = null
    this._openedResolve = null

    this._destroyedPromise = null
    this._destroyedResolve = null

    for (const m of messages) this.addMessage(m)
  }

  get drained() {
    return this._mux.drained
  }

  fullyOpened() {
    if (this.opened) return Promise.resolve(true)
    if (this.closed) return Promise.resolve(false)
    if (this._openedPromise) return this._openedPromise

    this._openedPromise = new Promise((resolve) => {
      this._openedResolve = resolve
    })
    return this._openedPromise
  }

  fullyClosed() {
    if (this.destroyed) return Promise.resolve()
    if (this._destroyedPromise) return this._destroyedPromise

    this._destroyedPromise = new Promise((resolve) => {
      this._destroyedResolve = resolve
    })
    return this._destroyedPromise
  }

  open(handshake) {
    const id = this._mux._free.length > 0 ? this._mux._free.pop() : this._mux._local.push(null) - 1

    this._info.opened++
    this._info.lastChannel = this
    this._localId = id + 1
    this._mux._local[id] = this

    if (this._remoteId === 0) {
      this._info.outgoing.push(this._localId)
    }

    const state = { buffer: null, start: 2, end: 2 }

    c.uint.preencode(state, this._localId)
    c.string.preencode(state, this.protocol)
    c.optionalBuffer.preencode(state, this.id)
    if (this._handshake) this._handshake.preencode(state, handshake)

    state.buffer = this._mux._alloc(state.end)

    state.buffer[0] = 0
    state.buffer[1] = 1
    c.uint.encode(state, this._localId)
    c.string.encode(state, this.protocol)
    c.optionalBuffer.encode(state, this.id)
    if (this._handshake) this._handshake.encode(state, handshake)

    this._mux._write0(state.buffer)
  }

  _dec() {
    if (--this._active === 0 && this.closed === true) this._destroy()
  }

  _decAndDestroy(err) {
    this._dec()
    this._mux._safeDestroy(err)
  }

  _fullyOpenSoon() {
    this._mux._remote[this._remoteId - 1].session = this
    queueTick(this._fullyOpenOrDestroy.bind(this))
  }

  _fullyOpenOrDestroy() {
    try {
      this._fullyOpen()
    } catch (err) {
      this._mux._safeDestroyBound(err)
    }
  }

  _fullyOpen() {
    if (this.opened === true || this.closed === true) return

    const remote = this._mux._remote[this._remoteId - 1]

    this.handshake = this._handshake ? this._handshake.decode(remote.state) : null
    this._track(this.onopen(this.handshake, this))

    remote.session = this
    remote.state = null
    if (remote.pending !== null) this._drain(remote)
    if (this._mux._destroying === true) return

    this.opened = true
    this._resolveOpen(true)
  }

  _resolveOpen(opened) {
    if (this._openedResolve !== null) {
      this._openedResolve(opened)
      this._openedResolve = this._openedPromise = null
    }
  }

  _resolveDestroyed() {
    if (this._destroyedResolve !== null) {
      this._destroyedResolve()
      this._destroyedResolve = this._destroyedPromise = null
    }
  }

  _drain(remote) {
    for (let i = 0; i < remote.pending.length; i++) {
      const p = remote.pending[i]
      this._mux._buffered -= byteSize(p.state)
      this._recv(p.type, p.state)
      if (this._mux._destroying === true) return
    }

    remote.pending = null
    this._mux._resumeMaybe()
  }

  _track(p) {
    if (isPromise(p) === true) {
      this._active++
      return p.then(this._decBound, this._decAndDestroyBound)
    }

    return null
  }

  _close(isRemote) {
    if (this.closed === true) return
    this.closed = true

    this._info.opened--
    if (this._info.lastChannel === this) this._info.lastChannel = null

    if (this._remoteId > 0) {
      this._mux._remote[this._remoteId - 1] = null
      this._remoteId = 0
      // If remote has acked, we can reuse the local id now
      // otherwise, we need to wait for the "ack" to arrive
      this._mux._free.push(this._localId - 1)
    }

    this._mux._local[this._localId - 1] = null
    this._localId = 0

    this._mux._gc(this._info)
    this._track(this.onclose(isRemote, this))

    if (this._active === 0) this._destroy()

    this._resolveOpen(false)
  }

  _destroy() {
    if (this.destroyed === true) return
    this.destroyed = true
    this._track(this.ondestroy(this))
    this._resolveDestroyed()
  }

  _recv(type, state) {
    if (type < this.messages.length) {
      const m = this.messages[type]
      const p = m.recv(state, this)
      if (m.autoBatch === true) return p
    }
    return null
  }

  cork() {
    this._mux.cork()
  }

  uncork() {
    this._mux.uncork()
  }

  close() {
    if (this.closed === true) return

    const state = { buffer: null, start: 2, end: 2 }

    c.uint.preencode(state, this._localId)

    state.buffer = this._mux._alloc(state.end)

    state.buffer[0] = 0
    state.buffer[1] = 3
    c.uint.encode(state, this._localId)

    this._close(false)
    this._mux._write0(state.buffer)
  }

  addMessage(opts) {
    if (!opts) return this._skipMessage()

    const type = this.messages.length
    const autoBatch = opts.autoBatch !== false
    const encoding = opts.encoding || c.raw
    const onmessage = opts.onmessage || noop

    const s = this
    const typeLen = encodingLength(c.uint, type)

    const m = {
      type,
      autoBatch,
      encoding,
      onmessage,
      recv(state, session) {
        return session._track(m.onmessage(encoding.decode(state), session))
      },
      send(m, session = s) {
        if (session.closed === true) return false

        const mux = session._mux
        const state = { buffer: null, start: 0, end: typeLen }

        if (mux._batch !== null) {
          encoding.preencode(state, m)
          state.buffer = mux._alloc(state.end)

          c.uint.encode(state, type)
          encoding.encode(state, m)

          mux._pushBatch(session._localId, state.buffer)
          return true
        }

        c.uint.preencode(state, session._localId)
        encoding.preencode(state, m)

        state.buffer = mux._alloc(state.end)

        c.uint.encode(state, session._localId)
        c.uint.encode(state, type)
        encoding.encode(state, m)

        mux.drained = mux.stream.write(state.buffer)

        return mux.drained
      }
    }

    this.messages.push(m)

    return m
  }

  _skipMessage() {
    const type = this.messages.length
    const m = {
      type,
      encoding: c.raw,
      onmessage: noop,
      recv(state, session) {},
      send(m, session) {}
    }

    this.messages.push(m)
    return m
  }
}

module.exports = class Protomux {
  constructor(stream, { alloc } = {}) {
    if (stream.userData === null) stream.userData = this

    this.isProtomux = true
    this.stream = stream
    this.corked = 0
    this.drained = true

    this._alloc =
      alloc || (typeof stream.alloc === 'function' ? stream.alloc.bind(stream) : b4a.allocUnsafe)
    this._safeDestroyBound = this._safeDestroy.bind(this)
    this._uncorkBound = this.uncork.bind(this)

    this._remoteBacklog = 0
    this._buffered = 0
    this._paused = false
    this._remote = []
    this._local = []
    this._free = []
    this._batch = null
    this._batchState = null

    this._infos = new Map()
    this._notify = new Map()
    // stream.destroyed flips asynchronously on streamx-based transports.
    this._destroying = false

    this.stream.on('data', this._ondata.bind(this))
    this.stream.on('drain', this._ondrain.bind(this))
    this.stream.on('end', this._onend.bind(this))
    this.stream.on('error', noop) // we handle this in "close"
    this.stream.on('close', this._shutdown.bind(this))
  }

  static from(stream, opts) {
    if (stream.userData && stream.userData.isProtomux) return stream.userData
    if (stream.isProtomux) return stream
    return new this(stream, opts)
  }

  static isProtomux(mux) {
    return typeof mux === 'object' && mux.isProtomux === true
  }

  *[Symbol.iterator]() {
    for (const session of this._local) {
      if (session !== null) yield session
    }
  }

  isIdle() {
    return this._local.length === this._free.length
  }

  cork() {
    if (++this.corked === 1) {
      this._batch = []
      this._batchState = { buffer: null, start: 0, end: 1 }
    }
  }

  uncork() {
    if (--this.corked === 0) {
      this._sendBatch(this._batch, this._batchState)
      this._batch = null
      this._batchState = null
    }
  }

  getLastChannel({ protocol, id = null }) {
    const key = toKey(protocol, id)
    const info = this._infos.get(key)
    if (info) return info.lastChannel
    return null
  }

  pair({ protocol, id = null }, notify) {
    this._notify.set(toKey(protocol, id), notify)
  }

  unpair({ protocol, id = null }) {
    this._notify.delete(toKey(protocol, id))
  }

  opened({ protocol, id = null }) {
    const key = toKey(protocol, id)
    const info = this._infos.get(key)
    return info ? info.opened > 0 : false
  }

  createChannel({
    userData = null,
    protocol,
    aliases = [],
    id = null,
    unique = true,
    handshake = null,
    messages = [],
    onopen = noop,
    onclose = noop,
    ondestroy = noop,
    ondrain = noop
  }) {
    if (this.stream.destroyed) return null

    const info = this._get(protocol, id, aliases)
    if (unique && info.opened > 0) return null

    if (info.incoming.length === 0) {
      return new Channel(
        this,
        info,
        userData,
        protocol,
        aliases,
        id,
        handshake,
        messages,
        onopen,
        onclose,
        ondestroy,
        ondrain
      )
    }

    this._remoteBacklog--

    const remoteId = info.incoming.shift()
    const r = this._remote[remoteId - 1]
    if (r === null) return null

    const session = new Channel(
      this,
      info,
      userData,
      protocol,
      aliases,
      id,
      handshake,
      messages,
      onopen,
      onclose,
      ondestroy,
      ondrain
    )

    session._remoteId = remoteId
    session._fullyOpenSoon()

    return session
  }

  _pushBatch(localId, buffer) {
    if (this._batchState.end >= MAX_BATCH) {
      this._sendBatch(this._batch, this._batchState)
      this._batch = []
      this._batchState = { buffer: null, start: 0, end: 1 }
    }

    if (this._batch.length === 0 || this._batch[this._batch.length - 1].localId !== localId) {
      this._batchState.end++
      c.uint.preencode(this._batchState, localId)
    }
    c.buffer.preencode(this._batchState, buffer)
    this._batch.push({ localId, buffer })
  }

  _sendBatch(batch, state) {
    if (batch.length === 0) return

    let prev = batch[0].localId

    state.buffer = this._alloc(state.end)
    state.buffer[state.start++] = 0
    state.buffer[state.start++] = 0

    c.uint.encode(state, prev)

    for (let i = 0; i < batch.length; i++) {
      const b = batch[i]
      if (prev !== b.localId) {
        state.buffer[state.start++] = 0
        c.uint.encode(state, (prev = b.localId))
      }
      c.buffer.encode(state, b.buffer)
    }

    this.drained = this.stream.write(state.buffer)
  }

  _get(protocol, id, aliases = []) {
    const key = toKey(protocol, id)

    let info = this._infos.get(key)
    if (info) return info

    info = {
      key,
      protocol,
      aliases: [],
      id,
      pairing: 0,
      opened: 0,
      incoming: [],
      outgoing: [],
      lastChannel: null
    }
    this._infos.set(key, info)

    for (const alias of aliases) {
      const key = toKey(alias, id)
      info.aliases.push(key)

      this._infos.set(key, info)
    }

    return info
  }

  _gc(info) {
    if (info.opened === 0 && info.outgoing.length === 0 && info.incoming.length === 0) {
      this._infos.delete(info.key)

      for (const alias of info.aliases) this._infos.delete(alias)
    }
  }

  _ondata(buffer) {
    if (buffer.byteLength === 0) return // ignore empty frames...
    try {
      const state = { buffer, start: 0, end: buffer.byteLength }
      this._decode(c.uint.decode(state), state)
    } catch (err) {
      this._safeDestroy(err)
    }
  }

  _ondrain() {
    this.drained = true

    for (const s of this._local) {
      if (s !== null) s._track(s.ondrain(s))
    }
  }

  _onend() {
    // TODO: support half open mode for the users who wants that here
    this.stream.end()
  }

  _decode(remoteId, state) {
    const type = c.uint.decode(state)

    if (remoteId === 0) {
      return this._oncontrolsession(type, state)
    }

    const r = remoteId <= this._remote.length ? this._remote[remoteId - 1] : null

    // if the channel is closed ignore - could just be a pipeline message...
    if (r === null) return null

    if (r.pending !== null) {
      this._bufferMessage(r, type, state)
      return null
    }

    return r.session._recv(type, state)
  }

  _oncontrolsession(type, state) {
    switch (type) {
      case 0:
        this._onbatch(state)
        break

      case 1:
        // return the promise back up as this has sideeffects so we can batch reply
        return this._onopensession(state)

      case 2:
        this._onrejectsession(state)
        break

      case 3:
        this._onclosesession(state)
        break
    }

    return null
  }

  _bufferMessage(r, type, { buffer, start, end }) {
    const state = { buffer, start, end } // copy
    r.pending.push({ type, state })
    this._buffered += byteSize(state)
    this._pauseMaybe()
  }

  _pauseMaybe() {
    if (this._paused === true || this._buffered <= MAX_BUFFERED) return
    this._paused = true
    this.stream.pause()
  }

  _resumeMaybe() {
    if (this._paused === false || this._buffered > MAX_BUFFERED) return
    this._paused = false
    this.stream.resume()
  }

  _onbatch(state) {
    const end = state.end
    let remoteId = c.uint.decode(state)

    let waiting = null

    while (state.end > state.start) {
      const len = c.uint.decode(state)
      if (len === 0) {
        remoteId = c.uint.decode(state)
        continue
      }
      state.end = state.start + len
      // if batch contains more than one message, cork it so we reply back with a batch
      if (end !== state.end && waiting === null) {
        waiting = []
        this.cork()
      }
      const p = this._decode(remoteId, state)
      if (waiting !== null && p !== null) waiting.push(p)
      state.start = state.end
      state.end = end
    }

    if (waiting !== null) {
      // the waiting promises are not allowed to throw but we destroy the stream in case we are wrong
      Promise.all(waiting).then(this._uncorkBound, this._safeDestroyBound)
    }
  }

  _onopensession(state) {
    const remoteId = c.uint.decode(state)
    const protocol = c.string.decode(state)
    const id = unslab(c.optionalBuffer.decode(state))

    // remote tried to open the control session - auto reject for now
    // as we can use as an explicit control protocol declaration if we need to
    if (remoteId === 0) {
      this._rejectSession(0)
      return null
    }

    const rid = remoteId - 1
    const info = this._get(protocol, id)

    // allow the remote to grow the ids by one
    if (this._remote.length === rid) {
      this._remote.push(null)
    }

    if (rid >= this._remote.length || this._remote[rid] !== null) {
      throw new Error('Invalid open message')
    }

    if (info.outgoing.length > 0) {
      const localId = info.outgoing.shift()
      const session = this._local[localId - 1]

      if (session === null) {
        // we already closed the channel - ignore
        this._free.push(localId - 1)
        return null
      }

      this._remote[rid] = { state, pending: null, session: null }

      session._remoteId = remoteId
      session._fullyOpen()
      return null
    }

    const copyState = { buffer: state.buffer, start: state.start, end: state.end }
    this._remote[rid] = { state: copyState, pending: [], session: null }

    if (++this._remoteBacklog > MAX_BACKLOG) {
      throw new Error('Remote exceeded backlog')
    }

    info.pairing++
    info.incoming.push(remoteId)

    return this._requestSession(protocol, id, info).catch(this._safeDestroyBound)
  }

  _onrejectsession(state) {
    const localId = c.uint.decode(state)

    // TODO: can be done smarter...
    for (const info of this._infos.values()) {
      const i = info.outgoing.indexOf(localId)
      if (i === -1) continue

      info.outgoing.splice(i, 1)

      const session = this._local[localId - 1]

      this._free.push(localId - 1)
      if (session !== null) session._close(true)

      this._gc(info)
      return
    }

    throw new Error('Invalid reject message')
  }

  _onclosesession(state) {
    const remoteId = c.uint.decode(state)

    if (remoteId === 0) return // ignore

    const rid = remoteId - 1
    const r = rid < this._remote.length ? this._remote[rid] : null

    if (r === null) return

    if (r.session !== null) r.session._close(true)
  }

  async _requestSession(protocol, id, info) {
    const notify = this._notify.get(toKey(protocol, id)) || this._notify.get(toKey(protocol, null))

    if (notify) await notify(id)

    if (--info.pairing > 0) return

    while (info.incoming.length > 0) {
      this._rejectSession(info, info.incoming.shift())
    }

    this._gc(info)
  }

  _rejectSession(info, remoteId) {
    if (remoteId > 0) {
      const r = this._remote[remoteId - 1]

      if (r.pending !== null) {
        for (let i = 0; i < r.pending.length; i++) {
          this._buffered -= byteSize(r.pending[i].state)
        }
      }

      this._remote[remoteId - 1] = null
      this._resumeMaybe()
    }

    const state = { buffer: null, start: 2, end: 2 }

    c.uint.preencode(state, remoteId)

    state.buffer = this._alloc(state.end)

    state.buffer[0] = 0
    state.buffer[1] = 2
    c.uint.encode(state, remoteId)

    this._write0(state.buffer)
  }

  _write0(buffer) {
    if (this._batch !== null) {
      this._pushBatch(0, buffer.subarray(1))
      return
    }

    this.drained = this.stream.write(buffer)
  }

  destroy(err) {
    this._destroying = true
    this.stream.destroy(err)
  }

  _safeDestroy(err) {
    safetyCatch(err)
    this._destroying = true
    this.stream.destroy(err)
  }

  _shutdown() {
    this._destroying = true
    for (const s of this._local) {
      if (s !== null) s._close(true)
    }
  }
}

function noop() {}

function toKey(protocol, id) {
  return protocol + '##' + (id ? b4a.toString(id, 'hex') : '')
}

function byteSize(state) {
  return 512 + (state.end - state.start)
}

function isPromise(p) {
  return !!(p && typeof p.then === 'function')
}

function encodingLength(enc, val) {
  const state = { buffer: null, start: 0, end: 0 }
  enc.preencode(state, val)
  return state.end
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "protomux",
  "version": "3.11.0",
  "description": "Multiplex multiple message oriented protocols over a stream",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.3.1",
    "compact-encoding": "^3.0.0",
    "queue-tick": "^1.0.0",
    "safety-catch": "^1.0.1",
    "unslab": "^1.3.0"
  },
  "devDependencies": {
    "@hyperswarm/secret-stream": "^6.0.0",
    "brittle": "^3.0.0",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/protomux.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/protomux/issues"
  },
  "homepage": "https://github.com/holepunchto/protomux"
}
{
  "name": "queue-tick",
  "version": "1.0.1",
  "description": "Next tick shim that prefers process.nextTick over queueMicrotask for compat",
  "main": "./process-next-tick.js",
  "browser": "./queue-microtask.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^16.0.3",
    "tape": "^5.3.1"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/queue-tick.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/queue-tick/issues"
  },
  "homepage": "https://github.com/mafintosh/queue-tick"
}
module.exports = (typeof process !== 'undefined' && typeof process.nextTick === 'function')
  ? process.nextTick.bind(process)
  : require('./queue-microtask')
module.exports = typeof queueMicrotask === 'function' ? queueMicrotask : (fn) => Promise.resolve().then(fn)
const EventEmitter = require('events')

module.exports = class ReadyResource extends EventEmitter {
  constructor () {
    super()

    this.opening = null
    this.closing = null

    this.opened = false
    this.closed = false
  }

  ready () {
    if (this.opening !== null) return this.opening
    this.opening = open(this)
    return this.opening
  }

  close () {
    if (this.closing !== null) return this.closing
    this.closing = close(this)
    return this.closing
  }

  async _open () {
    // add impl here
  }

  async _close () {
    // add impl here
  }
}

async function open (self) {
  // open after close
  if (self.closing !== null) return

  try {
    await self._open()
  } catch (err) {
    self.close() // safe to run in bg
    throw err
  }

  self.opened = true
  self.emit('ready')
}

async function close (self) {
  try {
    if (self.opened === false && self.opening !== null) await self.opening
  } catch {
    // ignore errors on closing
  }
  if (self.opened === true || self.opening === null) await self._close()
  self.closed = true
  self.emit('close')
}
{
  "name": "ready-resource",
  "version": "1.2.0",
  "description": "Modern single resource management",
  "main": "index.js",
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "types": "index.d.ts",
  "files": [
    "index.js",
    "index.d.ts"
  ],
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "devDependencies": {
    "brittle": "^3.1.0",
    "standard": "^17.0.0"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/ready-resource.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/ready-resource/issues"
  },
  "homepage": "https://github.com/holepunchto/ready-resource",
  "dependencies": {
    "bare-events": "^2.2.0"
  }
}
const b4a = require('b4a')

var EMPTY = []

module.exports = RecordCache

function RecordSet () {
  this.list = []
  this.map = new Map()
}

RecordSet.prototype.add = function (record, value) {
  var k = toString(record)
  var r = this.map.get(k)
  if (r) return false

  r = {index: this.list.length, record: value || record}
  this.list.push(r)
  this.map.set(k, r)
  return true
}

RecordSet.prototype.remove = function (record) {
  var k = toString(record)
  var r = this.map.get(k)
  if (!r) return false

  swap(this.list, r.index, this.list.length - 1)
  this.list.pop()
  this.map.delete(k)
  return true
}

function RecordStore () {
  this.records = new Map()
  this.size = 0
}

RecordStore.prototype.add = function (name, record, value) {
  var r = this.records.get(name)

  if (!r) {
    r = new RecordSet()
    this.records.set(name, r)
  }

  if (r.add(record, value)) {
    this.size++
    return true
  }

  return false
}

RecordStore.prototype.remove = function (name, record, value) {
  var r = this.records.get(name)
  if (!r) return false

  if (r.remove(record, value)) {
    this.size--
    if (!r.map.size) this.records.delete(name)
    return true
  }

  return false
}

RecordStore.prototype.get = function (name) {
  var r = this.records.get(name)
  return r ? r.list : EMPTY
}

function RecordCache (opts) {
  if (!(this instanceof RecordCache)) return new RecordCache(opts)
  if (!opts) opts = {}

  this.maxSize = opts.maxSize || Infinity
  this.maxAge = opts.maxAge || 0

  this._onstale = opts.onStale || opts.onstale || null
  this._fresh = new RecordStore()
  this._stale = new RecordStore()
  this._interval = null
  this._gced = false

  if (this.maxAge && this.maxAge < Infinity) {
    // 2/3 gives us a span of 0.66-1.33 maxAge or avg maxAge
    var tick = Math.ceil(2 / 3 * this.maxAge)
    this._interval = setInterval(this._gcAuto.bind(this), tick)
    if (this._interval.unref) this._interval.unref()
  }
}

Object.defineProperty(RecordCache.prototype, 'size', {
  get: function () {
    return this._fresh.size + this._stale.size
  }
})

RecordCache.prototype.add = function (name, record, value) {
  this._stale.remove(name, record, value)
  if (this._fresh.add(name, record, value) && this._fresh.size > this.maxSize) {
    this._gc()
  }
}

RecordCache.prototype.remove = function (name, record, value) {
  this._fresh.remove(name, record, value)
  this._stale.remove(name, record, value)
}

RecordCache.prototype.get = function (name, n) {
  var a = this._fresh.get(name)
  var b = this._stale.get(name)
  var aLen = a.length
  var bLen = b.length
  var len = aLen + bLen

  if (n > len || !n) n = len
  var result = new Array(n)

  for (var i = 0; i < n; i++) {
    var j = Math.floor(Math.random() * (aLen + bLen))
    if (j < aLen) {
      result[i] = a[j].record
      swap(a, j, --aLen)
    } else {
      j -= aLen
      result[i] = b[j].record
      swap(b, j, --bLen)
    }
  }

  return result
}

RecordCache.prototype._gcAuto = function () {
  if (!this._gced) this._gc()
  this._gced = false
}

RecordCache.prototype._gc = function () {
  if (this._onstale && this._stale.size > 0) this._onstale(this._stale)
  this._stale = this._fresh
  this._fresh = new RecordStore()
  this._gced = true
}

RecordCache.prototype.clear = function () {
  this._gc()
  this._gc()
}

RecordCache.prototype.destroy = function () {
  this.clear()
  clearInterval(this._interval)
  this._interval = null
}

function toString (record) {
  return b4a.isBuffer(record) ? b4a.toString(record, 'hex') : record
}

function swap (list, a, b) {
  var tmp = list[a]
  tmp.index = b
  list[b].index = a
  list[a] = list[b]
  list[b] = tmp
}
{
  "name": "record-cache",
  "version": "1.2.0",
  "description": "Cache optimised for record like things",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.3.1"
  },
  "devDependencies": {
    "standard": "^10.0.3",
    "tape": "^4.8.0"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/record-cache.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/record-cache/issues"
  },
  "homepage": "https://github.com/mafintosh/record-cache"
}
module.exports = require.addon.bind(require)
{
  "name": "require-addon",
  "version": "1.2.0",
  "description": "Import native addons across JavaScript runtimes",
  "exports": {
    "./package": "./package.json",
    ".": {
      "bare": "./lib/bare.js",
      "node": "./lib/node.js",
      "default": "./lib/default.js"
    }
  },
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    },
    "url": {
      "bare": "bare-url",
      "default": "url"
    }
  },
  "files": [
    "lib"
  ],
  "scripts": {
    "test": "npm run lint && npm run test:bare && npm run test:node",
    "test:bare": "bare test.js",
    "test:node": "node test.js",
    "lint": "prettier --check .",
    "format": "prettier --write ."
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/require-addon.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/require-addon/issues"
  },
  "homepage": "https://github.com/holepunchto/require-addon#readme",
  "engines": {
    "bare": ">=1.10.0"
  },
  "dependencies": {
    "bare-addon-resolve": "^1.3.0"
  },
  "devDependencies": {
    "bare-bundle": "^1.8.1",
    "bare-bundle-evaluate": "^1.1.0",
    "bare-fs": "^4.0.0",
    "bare-path": "^3.0.0",
    "bare-url": "^2.1.0",
    "brittle": "^3.7.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = safetyCatch

function isActuallyUncaught (err) {
  if (!err) return false
  return err instanceof TypeError ||
    err instanceof SyntaxError ||
    err instanceof ReferenceError ||
    err instanceof EvalError ||
    err instanceof RangeError ||
    err instanceof URIError ||
    err.code === 'ERR_ASSERTION' ||
    err.name === 'AssertionError'
}

function throwErrorNT (err) {
  queueMicrotask(() => { throw err })
}

function safetyCatch (err) {
  if (isActuallyUncaught(err)) {
    throwErrorNT(err)
    throw err
  }
}
{
  "name": "safety-catch",
  "version": "1.0.3",
  "description": "Small module that makes sure your catch, caught an actual error and not a programming mistake or assertion",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {},
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/safety-catch.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/safety-catch/issues"
  },
  "homepage": "https://github.com/mafintosh/safety-catch"
}
const set = require('unordered-set')

module.exports = opts => new ShuffledPriorityQueue(opts)

class ShuffledPriorityQueue {
  constructor (opts) {
    this.priorities = []
    this.equals = (opts && opts.equals) || null
  }

  get length () {
    return this.priorities.reduce(add, 0)
  }

  [Symbol.iterator] () {
    return new Iterator(this)
  }

  head () {
    for (let i = this.priorities.length - 1; i >= 0; i--) {
      const q = this.priorities[i]
      if (q.length) return shuffle(q, 0)
    }
    return null
  }

  tail () {
    for (let i = 0; i < this.priorities.length; i++) {
      const q = this.priorities[i]
      if (q.length) return shuffle(q, 0)
    }
    return null
  }

  prev (prev) {
    if (!prev) return this.tail()
    return next(this.priorities, prev, 1)
  }

  next (prev) {
    if (!prev) return this.head()
    return next(this.priorities, prev, -1)
  }

  shift () {
    return this.remove(this.head())
  }

  pop () {
    return this.remove(this.tail())
  }

  add (val) {
    const prio = val.priority || 0
    while (prio >= this.priorities.length) this.priorities.push([])
    set.add(this.priorities[prio], val)
    return val
  }

  remove (val) {
    if (!val) return null

    if (val._index === undefined) {
      val = this.find(val)
      if (!val) return null
    }

    return set.remove(this.priorities[val.priority || 0], val)
  }

  has (val) {
    if (val._index === undefined) return this.find(val)
    const priority = val.priority || 0
    if (priority >= this.priorities.length) return false
    return set.has(this.priorities[priority], val)
  }

  find (val) {
    if (val._index !== undefined) return val

    const prio = val.priority || 0
    const qs = this.priorities
    if (prio >= qs.length) return null

    const q = qs[prio]

    for (let i = 0; i < q.length; i++) {
      if (this.equals(q[i], val)) return q[i]
    }

    return null
  }
}

class Iterator {
  constructor (queue) {
    this.prev = null
    this.queue = queue
  }

  next () {
    const next = this.queue.next(this.prev)
    this.prev = next
    return { done: !next, value: next }
  }
}

function shuffle (q, i) {
  const ran = i + Math.floor(Math.random() * (q.length - i))
  set.swap(q, q[ran], q[i])
  return q[i]
}

function next (queues, prev, inc) {
  let i = prev.priority || 0
  let j = (prev._index || 0) + 1

  while (true) {
    if (i < 0 || i >= queues.length) return null
    const q = queues[i]

    if (j >= q.length) {
      i += inc
      j = 0
      continue
    }

    return shuffle(q, j)
  }
}

function add (len, b) {
  return len + b.length
}
{
  "name": "shuffled-priority-queue",
  "version": "2.1.0",
  "description": "A priority queue that shuffles elements with the same priority.",
  "main": "index.js",
  "scripts": {
    "test": "standard && tape test.js"
  },
  "dependencies": {
    "unordered-set": "^2.0.1"
  },
  "devDependencies": {
    "standard": "^12.0.1",
    "tape": "^4.9.1"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/shuffled-priority-queue.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/shuffled-priority-queue/issues"
  },
  "homepage": "https://github.com/mafintosh/shuffled-priority-queue"
}
module.exports = class Signal {
  constructor () {
    this._resolve = null
    this._reject = null
    this._promise = null
    this._bind = bind.bind(this)
    this._onerror = clear.bind(this)
    this._onsuccess = clear.bind(this, null)
    this._timers = new Set()
  }

  wait (max) {
    if (!this._promise) {
      this._promise = new Promise(this._bind)
      this._promise.then(this._onsuccess).catch(this._onerror)
    }
    if (max) return this._sleep(max)
    return this._promise
  }

  _sleep (max) {
    const s = new Promise((resolve, reject) => {
      const done = () => {
        this._timers.delete(state)
        resolve(true)
      }
      const id = setTimeout(done, max)
      const state = { id, resolve, reject }
      this._timers.add(state)
    })

    return s
  }

  notify (err) {
    if (!this._promise) return
    const resolve = this._resolve
    const reject = this._reject
    this._promise = null
    if (err) reject(err)
    else resolve(true)
  }
}

function clear (err) {
  for (const { id, resolve, reject } of this._timers) {
    clearTimeout(id)
    if (err) reject(err)
    else resolve(true)
  }
  this._timers.clear()
}

function bind (resolve, reject) {
  this._resolve = resolve
  this._reject = reject
}
{
  "name": "signal-promise",
  "version": "1.0.3",
  "description": "Simple wait/notify promise with optional max wait time",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {},
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/signal-promise.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/signal-promise/issues"
  },
  "homepage": "https://github.com/mafintosh/signal-promise"
}
require.addon = require('require-addon')
module.exports = require.addon('.', __filename)
const assert = require('assert')
const binding = require('./binding')
const { isNode } = require('which-runtime')

const OPTIONAL = Buffer.from(new ArrayBuffer(0))

module.exports = exports = { ...binding }

// memory

exports.sodium_memzero = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  binding.sodium_memzero(buf)
}

exports.sodium_mlock = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  const res = binding.sodium_mlock(buf)

  if (res !== 0) throw new Error('memory lock failed')
}

exports.sodium_munlock = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  const res = binding.sodium_munlock(buf)

  if (res !== 0) throw new Error('memory unlock failed')
}

exports.sodium_malloc = function (size) {
  assert(size >= 0, 'invalid size')

  const buf = Buffer.from(binding.sodium_malloc(size))
  buf.secure = true
  return buf
}

exports.sodium_free = function (buf) {
  if (!buf || !buf.secure) return

  binding.sodium_free(buf.buffer)
}

exports.sodium_mprotect_noaccess = function (buf) {
  const res = binding.sodium_mprotect_noaccess(buf.buffer)

  if (res !== 0) throw new Error('failed to lock buffer')
}

exports.sodium_mprotect_readonly = function (buf) {
  const res = binding.sodium_mprotect_readonly(buf.buffer)

  if (res !== 0) throw new Error('failed to unlock buffer')
}

exports.sodium_mprotect_readwrite = function (buf) {
  const res = binding.sodium_mprotect_readwrite(buf.buffer)

  if (res !== 0) throw new Error('failed to unlock buffer')
}

// crypto_randombytes

exports.randombytes_buf = function (buffer) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')

  binding.randombytes_buf(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

exports.randombytes_buf_deterministic = function (buffer, seed) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    seed.byteLength === binding.randombytes_SEEDBYTES,
    "seed must be 'randombytes_SEEDBYTES' bytes"
  )

  binding.randombytes_buf_deterministic(
    buffer.buffer,
    buffer.byteOffset,
    buffer.byteLength,

    seed.buffer,
    seed.byteOffset,
    seed.byteLength
  )
}

// sodium_helpers

exports.sodium_memcmp = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  return binding.sodium_memcmp(a, b)
}

exports.sodium_add = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  binding.sodium_add(a, b)
}

exports.sodium_sub = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  binding.sodium_sub(a, b)
}

exports.sodium_compare = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  return binding.sodium_compare(a, b)
}

exports.sodium_is_zero = function (buffer, length) {
  if (length === undefined) length = buffer.byteLength

  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(length >= 0 && length <= buffer.byteLength, 'invalid length')

  return binding.sodium_is_zero(buffer, length)
}

exports.sodium_pad = function (buffer, unpaddedBuflen, blockSize) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(unpaddedBuflen <= buffer.byteLength, 'unpadded length cannot exceed buffer length')
  assert(blockSize <= buffer.byteLength, 'block size cannot exceed buffer length')
  assert(blockSize >= 1, 'block size must be at least 1 byte')
  assert(
    buffer.byteLength >= unpaddedBuflen + (blockSize - (unpaddedBuflen % blockSize)),
    'buf not long enough'
  )

  return binding.sodium_pad(buffer, unpaddedBuflen, blockSize)
}

exports.sodium_unpad = function (buffer, paddedBuflen, blockSize) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(paddedBuflen <= buffer.byteLength, 'unpadded length cannot exceed buffer length')
  assert(blockSize <= buffer.byteLength, 'block size cannot exceed buffer length')
  assert(blockSize >= 1, 'block size must be at least 1 byte')

  return binding.sodium_unpad(buffer, paddedBuflen, blockSize)
}

// crypto_sign

exports.crypto_sign_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )
  assert(
    seed.byteLength === binding.crypto_sign_SEEDBYTES,
    "seed must be 'crypto_sign_SEEDBYTES' bytes"
  )

  const res = binding.crypto_sign_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign = function (sm, m, sk) {
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sm.byteLength === binding.crypto_sign_BYTES + m.byteLength,
    "sm must be 'm.byteLength + crypto_sign_BYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign(sm, m, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_open = function (m, sm, pk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sm.byteLength >= binding.crypto_sign_BYTES,
    "sm must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    m.byteLength === sm.byteLength - binding.crypto_sign_BYTES,
    "m must be 'sm.byteLength - crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_open(m, sm, pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_open = function (m, sm, pk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sm.byteLength >= binding.crypto_sign_BYTES,
    "sm must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    m.byteLength === sm.byteLength - binding.crypto_sign_BYTES,
    "m must be 'sm.byteLength - crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  return binding.crypto_sign_open(m, sm, pk)
}

exports.crypto_sign_detached = function (sig, m, sk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(sig.byteLength === binding.crypto_sign_BYTES, "sig must be 'crypto_sign_BYTES' bytes")
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_detached(sig, m, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_verify_detached = function (sig, m, pk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sig.byteLength >= binding.crypto_sign_BYTES,
    "sig must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  return binding.crypto_sign_verify_detached(
    sig.buffer,
    sig.byteOffset,
    sig.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    pk.buffer,
    pk.byteOffset,
    pk.byteLength
  )
}

exports.crypto_sign_ed25519_sk_to_pk = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_sk_to_pk(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_ed25519_pk_to_curve25519 = function (x25519pk, ed25519pk) {
  assert(ArrayBuffer.isView(x25519pk), 'x25519pk must be a typed array')
  assert(ArrayBuffer.isView(ed25519pk), 'ed25519pk must be a typed array')
  assert(
    x25519pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "x25519pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    ed25519pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "ed25519pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_pk_to_curve25519(x25519pk, ed25519pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_ed25519_sk_to_curve25519 = function (x25519sk, ed25519sk) {
  assert(ArrayBuffer.isView(x25519sk), 'x25519sk must be a typed array')
  assert(ArrayBuffer.isView(ed25519sk), 'ed25519sk must be a typed array')
  assert(
    x25519sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "x25519sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const edLen = ed25519sk.byteLength

  assert(
    edLen === binding.crypto_sign_SECRETKEYBYTES || edLen === binding.crypto_box_SECRETKEYBYTES,
    "ed25519sk must be 'crypto_sign_SECRETKEYBYTES' or 'crypto_sign_SECRETKEYBYTES - crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_sk_to_curve25519(x25519sk, ed25519sk)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_box

exports.crypto_box_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    seed.byteLength === binding.crypto_box_SEEDBYTES,
    "seed must be 'crypto_box_SEEDBYTES' bytes"
  )

  const res = binding.crypto_box_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_easy = function (c, m, n, pk, sk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength === m.byteLength + exports.crypto_box_MACBYTES,
    "c must be 'm.byteLength + crypto_box_MACBYTES' bytes"
  )
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_easy(c, m, n, pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_detached = function (c, mac, m, n, pk, sk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(mac.byteLength === exports.crypto_box_MACBYTES, "mac must be 'crypto_box_MACBYTES' bytes")
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_detached(c, mac, m, n, pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_open_easy = function (m, c, n, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength >= exports.crypto_box_MACBYTES,
    "c must be at least 'crypto_box_MACBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - exports.crypto_box_MACBYTES,
    "m must be 'c.byteLength - crypto_box_MACBYTES' bytes"
  )
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_open_easy(m, c, n, pk, sk)
}

exports.crypto_box_open_detached = function (m, c, mac, n, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(mac.byteLength === exports.crypto_box_MACBYTES, "mac must be 'crypto_box_MACBYTES' bytes")
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_open_detached(m, c, mac, n, pk, sk)
}

exports.crypto_box_seal = function (c, m, pk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    c.byteLength === m.byteLength + exports.crypto_box_SEALBYTES,
    "c must be 'm.byteLength + crypto_box_SEALBYTES' bytes"
  )
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_box_seal(c, m, pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_seal_open = function (m, c, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength >= exports.crypto_box_SEALBYTES,
    "c must be at least 'crypto_box_SEALBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - exports.crypto_box_SEALBYTES,
    "m must be 'c.byteLength - crypto_box_SEALBYTES' bytes"
  )
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_seal_open(
    m.buffer,
    m.byteOffset,
    m.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    pk.buffer,
    pk.byteOffset,
    pk.byteLength,

    sk.buffer,
    sk.byteOffset,
    sk.byteLength
  )
}

// crypto_secretbox

exports.crypto_secretbox_easy = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_secretbox_MACBYTES,
    "c must be 'm.byteLength + crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretbox_easy(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretbox_open_easy = function (m, c, n, k) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    c.byteLength >= binding.crypto_secretbox_MACBYTES,
    "c must be at least 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - binding.crypto_secretbox_MACBYTES,
    "m must be 'c.byteLength - crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  return binding.crypto_secretbox_open_easy(m, c, n, k)
}

exports.crypto_secretbox_detached = function (c, mac, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    mac.byteLength === binding.crypto_secretbox_MACBYTES,
    "mac must be 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretbox_detached(c, mac, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretbox_open_detached = function (m, c, mac, n, k) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(
    mac.byteLength === binding.crypto_secretbox_MACBYTES,
    "mac must be 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  return binding.crypto_secretbox_open_detached(m, c, mac, n, k)
}

// crypto_generichash

exports.crypto_generichash = function (output, input, key) {
  if (!key) key = OPTIONAL

  assert(ArrayBuffer.isView(output), 'output must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    output.byteLength >= binding.crypto_generichash_BYTES_MIN &&
      output.byteLength <= binding.crypto_generichash_BYTES_MAX,
    'output must be between crypto_generichash_BYTES_MIN and crypto_generichash_BYTES_MAX bytes'
  )

  if (key !== OPTIONAL) {
    assert(ArrayBuffer.isView(key), 'key must be a typed array')
    assert(
      key.byteLength >= binding.crypto_generichash_KEYBYTES_MIN &&
        key.byteLength <= binding.crypto_generichash_KEYBYTES_MAX,
      'key must be between crypto_generichash_KEYBYTES_MIN and crypto_generichash_KEYBYTES_MAX bytes'
    )
  }

  const res = binding.crypto_generichash(
    output.buffer,
    output.byteOffset,
    output.byteLength,

    input.buffer,
    input.byteOffset,
    input.byteLength,

    key.buffer,
    key.byteOffset,
    key.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_batch = function (output, batch, key) {
  assert(ArrayBuffer.isView(output), 'output must be a typed array')

  if (isNode || batch.length < 4) {
    const res = binding.crypto_generichash_batch(output, batch, !!key, key || OPTIONAL)
    if (res !== 0) throw new Error('status: ' + res)
  } else {
    const state = Buffer.alloc(binding.crypto_generichash_STATEBYTES)

    exports.crypto_generichash_init(state, key, output.byteLength)

    for (const buf of batch) {
      exports.crypto_generichash_update(state, buf)
    }

    exports.crypto_generichash_final(state, output)
  }
}

exports.crypto_generichash_keygen = function (key) {
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(
    key.byteLength === binding.crypto_generichash_KEYBYTES,
    "key must be 'crypto_generichash_KEYBYTES' bytes"
  )

  const res = binding.crypto_generichash_keygen(key.buffer, key.byteOffset, key.byteLength)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_init = function (state, key, outputLength) {
  if (!key) key = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_init(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    key.buffer,
    key.byteOffset,
    key.byteLength,

    outputLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_update(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    input.buffer,
    input.byteOffset,
    input.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_final = function (state, output) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(output), 'output must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_final(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    output.buffer,
    output.byteOffset,
    output.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

// secretstream

exports.crypto_secretstream_xchacha20poly1305_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  binding.crypto_secretstream_xchacha20poly1305_keygen(k.buffer, k.byteOffset, k.byteLength)
}

exports.crypto_secretstream_xchacha20poly1305_init_push = function (state, header, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(header), 'header must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    header.byteLength === binding.crypto_secretstream_xchacha20poly1305_HEADERBYTES,
    "header must be 'crypto_secretstream_xchacha20poly1305_HEADERBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_init_push(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    header.buffer,
    header.byteOffset,
    header.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretstream_xchacha20poly1305_init_pull = function (state, header, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(header), 'header must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    header.byteLength === binding.crypto_secretstream_xchacha20poly1305_HEADERBYTES,
    "header must be 'crypto_secretstream_xchacha20poly1305_HEADERBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_init_pull(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    header.buffer,
    header.byteOffset,
    header.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretstream_xchacha20poly1305_push = function (state, c, m, ad, tag) {
  if (!ad) ad = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    c.byteLength === m.byteLength + binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "c must be 'm.byteLength + crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_push(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    ad.buffer,
    ad.byteOffset,
    ad.byteLength,

    tag
  )

  if (res < 0) throw new Error('push failed')

  return res
}

exports.crypto_secretstream_xchacha20poly1305_pull = function (state, m, tag, c, ad) {
  if (!ad) ad = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(tag), 'tag must be a typed array')
  assert(tag.byteLength === 1, 'tag must be 1 byte')

  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    c.byteLength >= binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "c must be at least 'crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "m must be 'c.byteLength - crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_pull(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    tag.buffer,
    tag.byteOffset,
    tag.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    ad.buffer,
    ad.byteOffset,
    ad.byteLength
  )

  if (res < 0) throw new Error('pull failed')

  return res
}

exports.crypto_secretstream_xchacha20poly1305_rekey = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )

  binding.crypto_secretstream_xchacha20poly1305_rekey(
    state.buffer,
    state.byteOffset,
    state.byteLength
  )
}

// crypto_stream

exports.crypto_stream = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xor(
    c.buffer,
    c.byteOffset,
    c.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    n.buffer,
    n.byteOffset,
    n.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_auth

exports.crypto_auth = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(out.byteLength === binding.crypto_auth_BYTES, "out must be 'crypto_auth_BYTES' bytes")
  assert(k.byteLength === binding.crypto_auth_KEYBYTES, "k must be 'crypto_auth_KEYBYTES' bytes")

  const res = binding.crypto_auth(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_auth_verify = function (h, input, k) {
  assert(ArrayBuffer.isView(h), 'h must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(h.byteLength === binding.crypto_auth_BYTES, "h must be 'crypto_auth_BYTES' bytes")
  assert(k.byteLength === binding.crypto_auth_KEYBYTES, "k must be 'crypto_auth_KEYBYTES' bytes")

  return binding.crypto_auth_verify(h, input, k)
}

// crypto_onetimeauth

exports.crypto_onetimeauth = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    out.byteLength === binding.crypto_onetimeauth_BYTES,
    "out must be 'crypto_onetimeauth_BYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_init = function (state, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_init(state, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )
  assert(
    out.byteLength === binding.crypto_onetimeauth_BYTES,
    "out must be 'crypto_onetimeauth_BYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_verify = function (h, input, k) {
  assert(ArrayBuffer.isView(h), 'h must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    h.byteLength === binding.crypto_onetimeauth_BYTES,
    "h must be 'crypto_onetimeauth_BYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  return binding.crypto_onetimeauth_verify(h, input, k)
}

// crypto_pwhash

exports.crypto_pwhash = function (out, passwd, salt, opslimit, memlimit, alg) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_BYTES_MIN,
    "out must be at least 'crypto_pwhash_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_BYTES_MAX,
    "out must be at most 'crypto_pwhash_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_SALTBYTES,
    "salt must be 'crypto_pwhash_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )
  assert(alg >= 1 && alg <= 2, 'alg must be either Argon2i 1.3 or Argon2id 1.3')

  const res = binding.crypto_pwhash(out, passwd, salt, opslimit, memlimit, alg)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_async = function (
  out,
  passwd,
  salt,
  opslimit,
  memlimit,
  alg,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_BYTES_MIN,
    "out must be at least 'crypto_pwhash_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_BYTES_MAX,
    "out must be at most 'crypto_pwhash_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_SALTBYTES,
    "salt must be 'crypto_pwhash_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )
  assert(alg >= 1 && alg <= 2, 'alg must be either Argon2i 1.3 or Argon2id 1.3')

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    opslimit,
    memlimit,
    alg,

    done
  )

  return promise
}

exports.crypto_pwhash_str = function (out, passwd, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_STRBYTES,
    "out must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(typeof opslimit === 'number', 'opslimit must be a number')
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(typeof memlimit === 'number', 'memlimit must be a number')
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_str(out, passwd, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_str_async = function (out, passwd, opslimit, memlimit, callback = undefined) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_STRBYTES,
    "out must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(typeof opslimit === 'number', 'opslimit must be a number')
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(typeof memlimit === 'number', 'memlimit must be a number')
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_str_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_str_verify = function (str, passwd) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )

  return binding.crypto_pwhash_str_verify(str, passwd)
}

exports.crypto_pwhash_str_verify_async = function (str, passwd, callback = undefined) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  const [done, promise] = checkStatus(callback, true)

  binding.crypto_pwhash_str_verify_async(
    str.buffer,
    str.byteOffset,
    str.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    done
  )

  return promise
}

exports.crypto_pwhash_str_needs_rehash = function (str, opslimit, memlimit) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  return binding.crypto_pwhash_str_needs_rehash(str, opslimit, memlimit)
}

exports.crypto_pwhash_scryptsalsa208sha256 = function (out, passwd, salt, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MIN,
    "out must be at least 'crypto_pwhash_scryptsalsa208sha256_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MAX,
    "out must be at most 'crypto_pwhash_scryptsalsa208sha256_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_SALTBYTES,
    "salt must be 'crypto_pwhash_scryptsalsa208sha256_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_scryptsalsa208sha256(out, passwd, salt, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_scryptsalsa208sha256_async = function (
  out,
  passwd,
  salt,
  opslimit,
  memlimit,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MIN,
    "out must be at least 'crypto_pwhash_scryptsalsa208sha256_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MAX,
    "out must be at most 'crypto_pwhash_scryptsalsa208sha256_BYTES_MAX' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    salt.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_SALTBYTES,
    "salt must be 'crypto_pwhash_scryptsalsa208sha256_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_scryptsalsa208sha256_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str_async = function (
  out,
  passwd,
  opslimit,
  memlimit,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "out must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_scryptsalsa208sha256_str_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str = function (out, passwd, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "out must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_scryptsalsa208sha256_str(out, passwd, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_scryptsalsa208sha256_str_verify_async = function (
  str,
  passwd,
  callback = undefined
) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  const [done, promise] = checkStatus(callback, true)

  binding.crypto_pwhash_scryptsalsa208sha256_str_verify_async(
    str.buffer,
    str.byteOffset,
    str.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str_verify = function (str, passwd) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  return binding.crypto_pwhash_scryptsalsa208sha256_str_verify(str, passwd)
}

exports.crypto_pwhash_scryptsalsa208sha256_str_needs_rehash = function (str, opslimit, memlimit) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  return binding.crypto_pwhash_scryptsalsa208sha256_str_needs_rehash(str, opslimit, memlimit)
}

// crypto_kx

exports.crypto_kx_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "pk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "sk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    pk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "pk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "sk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    seed.byteLength === binding.crypto_kx_SEEDBYTES,
    "seed must be 'crypto_kx_SEEDBYTES' bytes"
  )

  const res = binding.crypto_kx_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_client_session_keys = function (rx, tx, clientPk, clientSk, serverPk) {
  if (!rx) rx = undefined
  if (!tx) tx = undefined

  assert(rx || tx, 'at least one session key must be specified')

  if (rx) {
    assert(ArrayBuffer.isView(rx), 'rx must be a typed array')
    assert(
      rx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "rx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  if (tx) {
    assert(ArrayBuffer.isView(tx), 'tx must be a typed array')
    assert(
      tx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "tx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  assert(ArrayBuffer.isView(clientPk), 'clientPk must be a typed array')
  assert(ArrayBuffer.isView(clientSk), 'clientSk must be a typed array')
  assert(ArrayBuffer.isView(serverPk), 'serverPk must be a typed array')
  assert(
    clientPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "clientPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    clientSk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "clientSk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    serverPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "serverPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_client_session_keys(rx, tx, clientPk, clientSk, serverPk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_server_session_keys = function (rx, tx, serverPk, serverSk, clientPk) {
  if (!rx) rx = undefined
  if (!tx) tx = undefined

  assert(rx || tx, 'at least one session key must be specified')

  if (rx) {
    assert(ArrayBuffer.isView(rx), 'rx must be a typed array')
    assert(
      rx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "rx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  if (tx) {
    assert(ArrayBuffer.isView(tx), 'tx must be a typed array')
    assert(
      tx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "tx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  assert(ArrayBuffer.isView(serverPk), 'serverPk must be a typed array')
  assert(ArrayBuffer.isView(serverSk), 'serverSk must be a typed array')
  assert(ArrayBuffer.isView(clientPk), 'clientPk must be a typed array')
  assert(
    serverPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "serverPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    serverSk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "serverSk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    clientPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "clientPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_server_session_keys(rx, tx, serverPk, serverSk, clientPk)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_scalarmult

exports.crypto_scalarmult_base = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_BYTES,
    "q must be 'crypto_scalarmult_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_SCALARBYTES,
    "n must be 'crypto_scalarmult_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_base(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_BYTES,
    "q must be 'crypto_scalarmult_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_SCALARBYTES,
    "n must be 'crypto_scalarmult_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_BYTES,
    "p must be 'crypto_scalarmult_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_base = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_base(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519 = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "p must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_is_valid_point = function (p) {
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )

  return binding.crypto_core_ed25519_is_valid_point(p)
}

exports.crypto_core_ed25519_from_uniform = function (p, r) {
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_UNIFORMBYTES,
    "r must be 'crypto_core_ed25519_UNIFORMBYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_from_uniform(p, r)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_base_noclamp = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_base_noclamp(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_noclamp = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "p must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_noclamp(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_core

exports.crypto_core_ed25519_add = function (r, p, q) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_BYTES,
    "r must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_core_ed25519_BYTES,
    "q must be 'crypto_core_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_add(r, p, q)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_sub = function (r, p, q) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_BYTES,
    "r must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_core_ed25519_BYTES,
    "q must be 'crypto_core_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_sub(r, p, q)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_scalar_random = function (r) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "r must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_random(r)
}

exports.crypto_core_ed25519_scalar_reduce = function (r, s) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "r must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_NONREDUCEDSCALARBYTES,
    "s must be 'crypto_core_ed25519_NONREDUCEDSCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_reduce(r, s)
}

exports.crypto_core_ed25519_scalar_invert = function (recip, s) {
  assert(ArrayBuffer.isView(recip), 'recip must be a typed array')
  assert(
    recip.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "recip must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_invert(recip, s)
}

exports.crypto_core_ed25519_scalar_negate = function (neg, s) {
  assert(ArrayBuffer.isView(neg), 'neg must be a typed array')
  assert(
    neg.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "neg must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_negate(neg, s)
}

exports.crypto_core_ed25519_scalar_complement = function (comp, s) {
  assert(ArrayBuffer.isView(comp), 'comp must be a typed array')
  assert(
    comp.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "comp must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_complement(comp, s)
}

exports.crypto_core_ed25519_scalar_add = function (z, x, y) {
  assert(ArrayBuffer.isView(z), 'z must be a typed array')
  assert(
    z.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "z must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(x), 'x must be a typed array')
  assert(
    x.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "x must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(y), 'y must be a typed array')
  assert(
    y.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "y must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_add(z, x, y)
}

exports.crypto_core_ed25519_scalar_sub = function (z, x, y) {
  assert(ArrayBuffer.isView(z), 'z must be a typed array')
  assert(
    z.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "z must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(x), 'x must be a typed array')
  assert(
    x.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "x must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(y), 'y must be a typed array')
  assert(
    y.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "y must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_sub(z, x, y)
}

// crypto_shorthash

exports.crypto_shorthash = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_shorthash_BYTES,
    "out must be 'crypto_shorthash_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_shorthash_KEYBYTES,
    "k must be 'crypto_shorthash_KEYBYTES' bytes"
  )

  const res = binding.crypto_shorthash(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_kdf

exports.crypto_kdf_keygen = function (key) {
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(key.byteLength === binding.crypto_kdf_KEYBYTES, "key must be 'crypto_kdf_KEYBYTES' bytes")

  binding.crypto_kdf_keygen(key)
}

exports.crypto_kdf_derive_from_key = function (subkey, subkeyId, ctx, key) {
  assert(ArrayBuffer.isView(subkey), 'subkey must be a typed array')
  assert(
    subkey.byteLength >= binding.crypto_kdf_BYTES_MIN,
    "subkey must be at least 'crypto_kdf_BYTES_MIN' bytes"
  )
  assert(
    subkey.byteLength <= binding.crypto_kdf_BYTES_MAX,
    "subkey must be at most 'crypto_kdf_BYTES_MAX' bytes"
  )
  assert(ArrayBuffer.isView(ctx), 'ctx must be a typed array')
  assert(
    ctx.byteLength === binding.crypto_kdf_CONTEXTBYTES,
    "ctx must be 'crypto_kdf_CONTEXTBYTES' bytes"
  )
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(key.byteLength === binding.crypto_kdf_KEYBYTES, "key must be 'crypto_kdf_KEYBYTES' bytes")

  const res = binding.crypto_kdf_derive_from_key(subkey, subkeyId, ctx, key)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_hash

exports.crypto_hash = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(out.byteLength === binding.crypto_hash_BYTES, "out must be 'crypto_hash_BYTES' bytes")

  const res = binding.crypto_hash(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256 = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha256_BYTES,
    "out must be 'crypto_hash_sha256_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha256(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_init = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_init(state)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha256_BYTES,
    "out must be 'crypto_hash_sha256_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512 = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha512_BYTES,
    "out must be 'crypto_hash_sha512_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha512(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_init = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_init(state)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha512_BYTES,
    "out must be 'crypto_hash_sha512_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_aead

exports.crypto_aead_xchacha20poly1305_ietf_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  binding.crypto_aead_xchacha20poly1305_ietf_keygen(k)
}

exports.crypto_aead_xchacha20poly1305_ietf_encrypt = function (c, m, ad, nsec, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "c must be 'm.byteLength + crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(c.byteLength <= 0xffffffff, 'c.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_encrypt(c, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_decrypt = function (m, nsec, c, ad, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "m must be 'c.byteLength - crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(m.byteLength <= 0xffffffff, 'm.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_decrypt(m, c, ad, npub, k)

  if (res < 0) throw new Error('could not verify data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_encrypt_detached = function (
  c,
  mac,
  m,
  ad,
  nsec,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_encrypt_detached(c, mac, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_decrypt_detached = function (
  m,
  nsec,
  c,
  mac,
  ad,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_decrypt_detached(m, c, mac, ad, npub, k)

  if (res !== 0) throw new Error('could not verify data')
}

exports.crypto_aead_chacha20poly1305_ietf_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  binding.crypto_aead_chacha20poly1305_ietf_keygen(k)
}

exports.crypto_aead_chacha20poly1305_ietf_encrypt = function (c, m, ad, nsec, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "c must be 'm.byteLength + crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(c.byteLength <= 0xffffffff, 'c.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_encrypt(c, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_decrypt = function (m, nsec, c, ad, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "m must be 'c.byteLength - crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(m.byteLength <= 0xffffffff, 'm.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_decrypt(m, c, ad, npub, k)

  if (res < 0) throw new Error('could not verify data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_encrypt_detached = function (
  c,
  mac,
  m,
  ad,
  nsec,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_encrypt_detached(c, mac, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_decrypt_detached = function (
  m,
  nsec,
  c,
  mac,
  ad,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_decrypt_detached(m, c, mac, ad, npub, k)

  if (res !== 0) throw new Error('could not verify data')
}

// crypto_stream

exports.crypto_stream_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  binding.crypto_stream_xor_wrap_init(state, n, k)
}

exports.crypto_stream_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_xor_wrap_update(state, c, m)
}

exports.crypto_stream_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_xor_wrap_final(state)
}

exports.crypto_stream_chacha20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  binding.crypto_stream_chacha20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_chacha20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_chacha20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_chacha20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_chacha20_xor_wrap_final(state)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  binding.crypto_stream_chacha20_ietf_xor_wrap_init(state, n, k)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_chacha20_ietf_xor_wrap_update(state, c, m)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_chacha20_ietf_xor_wrap_final(state)
}

exports.crypto_stream_xchacha20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  binding.crypto_stream_xchacha20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_xchacha20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_xchacha20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_xchacha20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_xchacha20_xor_wrap_final(state)
}

exports.crypto_stream_salsa20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  binding.crypto_stream_salsa20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_salsa20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_salsa20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_salsa20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_salsa20_xor_wrap_final(state)
}

// experimental

exports.extension_tweak_ed25519_base = function (n, p, ns) {
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.extension_tweak_ed25519_BYTES,
    "p must be 'extension_tweak_ed25519_BYTES' bytes"
  )

  binding.extension_tweak_ed25519_base(n, p, ns)
}

exports.extension_tweak_ed25519_sign_detached = function (sig, m, scalar, pk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(sig.byteLength === binding.crypto_sign_BYTES, "sig must be 'crypto_sign_BYTES' bytes")
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  if (pk) {
    assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
    assert(
      pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
      "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
    )
  }

  const res = binding.extension_tweak_ed25519_sign_detached(sig, m, scalar, pk)

  if (res !== 0) throw new Error('failed to compute signature')
}

exports.extension_tweak_ed25519_sk_to_scalar = function (n, sk) {
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  binding.extension_tweak_ed25519_sk_to_scalar(n, sk)
}

exports.extension_tweak_ed25519_scalar = function (scalarOut, scalar, ns) {
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_scalar(scalarOut, scalar, ns)
}

exports.extension_tweak_ed25519_pk = function (tpk, pk, ns) {
  assert(ArrayBuffer.isView(tpk), 'tpk must be a typed array')
  assert(
    tpk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "tpk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_pk(tpk, pk, ns)

  if (res !== 0) throw new Error('failed to tweak public key')
}

exports.extension_tweak_ed25519_keypair = function (pk, scalarOut, scalarIn, ns) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.extension_tweak_ed25519_BYTES,
    "pk must be 'extension_tweak_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarIn), 'scalarIn must be a typed array')
  assert(
    scalarIn.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarIn must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_keypair(pk, scalarOut, scalarIn, ns)
}

exports.extension_tweak_ed25519_scalar_add = function (scalarOut, scalar, n) {
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_scalar_add(scalarOut, scalar, n)
}

exports.extension_tweak_ed25519_pk_add = function (tpk, pk, p) {
  assert(ArrayBuffer.isView(tpk), 'tpk must be a typed array')
  assert(
    tpk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "tpk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "p must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_pk_add(tpk, pk, p)

  if (res !== 0) throw new Error('failed to add tweak to public key')
}

exports.extension_tweak_ed25519_keypair_add = function (pk, scalarOut, scalarIn, tweak) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.extension_tweak_ed25519_BYTES,
    "pk must be 'extension_tweak_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarIn), 'scalarIn must be a typed array')
  assert(
    scalarIn.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarIn must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(tweak), 'tweak must be a typed array')
  assert(
    tweak.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "tweak must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_keypair_add(pk, scalarOut, scalarIn, tweak)

  if (res !== 0) throw new Error('failed to add tweak to keypair')
}

exports.extension_pbkdf2_sha512_async = function (out, passwd, salt, iter, outlen, callback) {
  assert(
    iter >= binding.extension_pbkdf2_sha512_ITERATIONS_MIN,
    "iter must be at least 'extension_pbkdf2_sha512_ITERATIONS_MIN'"
  )
  assert(
    outlen <= binding.extension_pbkdf2_sha512_BYTES_MAX,
    "outlen must be at most 'extension_pbkdf2_sha512_BYTES_MAX'"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(out.byteLength >= outlen, "out must be at least 'outlen' bytes")
  assert(out.byteLength > 0, 'out must not be empty')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(salt.byteLength > 0, 'salt must not be empty')

  const [done, promise] = checkStatus(callback)

  binding.extension_pbkdf2_sha512_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    iter,
    outlen,

    done
  )

  return promise
}

exports.extension_pbkdf2_sha512 = function (out, passwd, salt, iter, outlen) {
  assert(
    iter >= binding.extension_pbkdf2_sha512_ITERATIONS_MIN,
    "iter must be at least 'extension_pbkdf2_sha512_ITERATIONS_MIN'"
  )
  assert(
    outlen <= binding.extension_pbkdf2_sha512_BYTES_MAX,
    "outlen must be at most 'extension_pbkdf2_sha512_BYTES_MAX'"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(out.byteLength >= outlen, "out must be at least 'outlen' bytes")
  assert(out.byteLength > 0, 'out must not be empty')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(salt.byteLength > 0, 'salt must not be empty')

  const res = binding.extension_pbkdf2_sha512(out, passwd, salt, iter, outlen)

  if (res !== 0) throw new Error('failed to add tweak to public key')
}

function checkStatus(callback, booleanResult = false) {
  let done, promise

  if (typeof callback === 'function') {
    done = function (status) {
      if (booleanResult) callback(null, status === 0)
      else if (status === 0) callback(null)
      else callback(new Error('status: ' + status))
    }
  } else {
    promise = new Promise(function (resolve, reject) {
      done = function (status) {
        if (booleanResult) resolve(status === 0)
        else if (status === 0) resolve()
        else reject(new Error('status: ' + status))
      }
    })
  }

  return [done, promise]
}
{
  "name": "sodium-native",
  "version": "5.1.0",
  "description": "Low level bindings for libsodium",
  "main": "index.js",
  "files": [
    "index.js",
    "binding.cc",
    "binding.js",
    "extensions",
    "prebuilds",
    "CMakeLists.txt"
  ],
  "imports": {
    "assert": {
      "bare": "bare-assert",
      "node": "assert"
    }
  },
  "addon": true,
  "dependencies": {
    "bare-assert": "^1.2.0",
    "require-addon": "^1.1.0",
    "which-runtime": "^1.2.1"
  },
  "devDependencies": {
    "bare-compat-napi": "^1.3.5",
    "brittle": "^3.16.2",
    "cmake-bare": "^1.6.1",
    "cmake-fetch": "^1.4.3",
    "cmake-napi": "^1.2.1",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "test": "prettier . --check && npm run test:node && npm run test:bare",
    "test:node": "node test/all.js",
    "test:bare": "bare test/all.js"
  },
  "standard": {
    "ignore": [
      "/test/fixtures/*.js"
    ]
  },
  "engines": {
    "bare": ">=1.16.0"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sodium-native.git"
  },
  "contributors": [
    "Emil Bay <github@tixz.dk> (http://bayes.dk)",
    "Mathias Buus <mathiasbuus@gmail.com> (https://mafinto.sh)",
    "Christophe Diederichs <chm-diederichs@hyperdivision.dk>"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/sodium-native/issues"
  },
  "homepage": "https://github.com/holepunchto/sodium-native"
}
const sodium = require('sodium-universal')
const b4a = require('b4a')

const ABYTES = sodium.crypto_secretstream_xchacha20poly1305_ABYTES
const TAG_MESSAGE = sodium.crypto_secretstream_xchacha20poly1305_TAG_MESSAGE
const TAG_FINAL = sodium.crypto_secretstream_xchacha20poly1305_TAG_FINAL
const STATEBYTES = sodium.crypto_secretstream_xchacha20poly1305_STATEBYTES
const HEADERBYTES = sodium.crypto_secretstream_xchacha20poly1305_HEADERBYTES
const KEYBYTES = sodium.crypto_secretstream_xchacha20poly1305_KEYBYTES
const TAG_FINAL_BYTE = b4a.isBuffer(TAG_FINAL) ? TAG_FINAL[0] : TAG_FINAL

const EMPTY = b4a.alloc(0)
const TAG = b4a.alloc(1)

class Push {
  constructor (key, state = b4a.allocUnsafeSlow(STATEBYTES), header = b4a.allocUnsafeSlow(HEADERBYTES)) {
    if (!TAG_FINAL) throw new Error('JavaScript sodium version needs to support crypto_secretstream_xchacha20poly')

    this.key = key
    this.state = state
    this.header = header

    sodium.crypto_secretstream_xchacha20poly1305_init_push(this.state, this.header, this.key)
  }

  next (message, cipher = b4a.allocUnsafe(message.byteLength + ABYTES)) {
    sodium.crypto_secretstream_xchacha20poly1305_push(this.state, cipher, message, null, TAG_MESSAGE)
    return cipher
  }

  final (message = EMPTY, cipher = b4a.allocUnsafe(ABYTES)) {
    sodium.crypto_secretstream_xchacha20poly1305_push(this.state, cipher, message, null, TAG_FINAL)
    return cipher
  }
}

class Pull {
  constructor (key, state = b4a.allocUnsafeSlow(STATEBYTES)) {
    if (!TAG_FINAL) throw new Error('JavaScript sodium version needs to support crypto_secretstream_xchacha20poly')

    this.key = key
    this.state = state
    this.final = false
  }

  init (header) {
    sodium.crypto_secretstream_xchacha20poly1305_init_pull(this.state, header, this.key)
  }

  next (cipher, message = b4a.allocUnsafe(cipher.byteLength - ABYTES)) {
    sodium.crypto_secretstream_xchacha20poly1305_pull(this.state, message, TAG, cipher, null)
    this.final = TAG[0] === TAG_FINAL_BYTE
    return message
  }
}

function keygen (buf = b4a.alloc(KEYBYTES)) {
  sodium.crypto_secretstream_xchacha20poly1305_keygen(buf)
  return buf
}

module.exports = {
  keygen,
  KEYBYTES,
  ABYTES,
  STATEBYTES,
  HEADERBYTES,
  Push,
  Pull
}
{
  "name": "sodium-secretstream",
  "version": "1.2.0",
  "description": "Wraps libsodiums secretstream in a higher level abstraction",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.1.1",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "standard": "^17.0.0"
  },
  "scripts": {
    "test": "standard"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/sodium-secretstream.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/sodium-secretstream/issues"
  },
  "homepage": "https://github.com/mafintosh/sodium-secretstream"
}
module.exports = require('sodium-native')
{
  "name": "sodium-universal",
  "version": "5.0.1",
  "description": "Universal wrapper for sodium-javascript and sodium-native working in Node.js and the Browser",
  "main": "index.js",
  "dependencies": {
    "sodium-native": "^5.0.1"
  },
  "peerDependencies": {
    "sodium-javascript": "~0.8.0"
  },
  "peerDependenciesMeta": {
    "sodium-javascript": {
      "optional": true
    }
  },
  "scripts": {
    "prepublish": "./build-scripts/generate.js"
  },
  "browser": {
    "sodium-native": "sodium-javascript"
  },
  "browserify": {
    "transform": [
      "./build-scripts/transform.js"
    ]
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sodium-universal.git"
  },
  "keywords": [
    "libsodium",
    "sodium",
    "sodium-native",
    "sodium-javascript",
    "browserify"
  ],
  "contributors": [
    "Emil Bay <github@tixz.dk> (http://bayes.dk)",
    "Mathias Buus <mathiasbuus@gmail.com> (https://mafinto.sh)",
    "Christophe Diederichs <chm-diederichs@hyperdivision.dk>"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/sodium-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/sodium-universal#readme"
}
const { EventEmitter } = require('events-universal')
const FIFO = require('fast-fifo')
const TextDecoder = require('text-decoder')

const StreamError = require('./lib/errors.js')

// if we do a future major, expect queue microtask to be there always, for now a bit defensive
const qmt =
  typeof queueMicrotask === 'undefined' ? (fn) => global.process.nextTick(fn) : queueMicrotask

// 29 bits used total (4 from shared, 14 from read, and 11 from write)
const MAX = (1 << 29) - 1

// Shared state
const OPENING = 0b0001
const PREDESTROYING = 0b0010
const DESTROYING = 0b0100
const DESTROYED = 0b1000

const NOT_OPENING = MAX ^ OPENING
const NOT_PREDESTROYING = MAX ^ PREDESTROYING

// Read state (4 bit offset from shared state)
const READ_ACTIVE = 0b00000000000001 << 4
const READ_UPDATING = 0b00000000000010 << 4
const READ_PRIMARY = 0b00000000000100 << 4
const READ_QUEUED = 0b00000000001000 << 4
const READ_RESUMED = 0b00000000010000 << 4
const READ_PIPE_DRAINED = 0b00000000100000 << 4
const READ_ENDING = 0b00000001000000 << 4
const READ_EMIT_DATA = 0b00000010000000 << 4
const READ_EMIT_READABLE = 0b00000100000000 << 4
const READ_EMITTED_READABLE = 0b00001000000000 << 4
const READ_DONE = 0b00010000000000 << 4
const READ_NEXT_TICK = 0b00100000000000 << 4
const READ_NEEDS_PUSH = 0b01000000000000 << 4
const READ_READ_AHEAD = 0b10000000000000 << 4

// Combined read state
const READ_FLOWING = READ_RESUMED | READ_PIPE_DRAINED
const READ_ACTIVE_AND_NEEDS_PUSH = READ_ACTIVE | READ_NEEDS_PUSH
const READ_PRIMARY_AND_ACTIVE = READ_PRIMARY | READ_ACTIVE
const READ_EMIT_READABLE_AND_QUEUED = READ_EMIT_READABLE | READ_QUEUED
const READ_RESUMED_READ_AHEAD = READ_RESUMED | READ_READ_AHEAD

const READ_NOT_ACTIVE = MAX ^ READ_ACTIVE
const READ_NON_PRIMARY = MAX ^ READ_PRIMARY
const READ_NON_PRIMARY_AND_PUSHED = MAX ^ (READ_PRIMARY | READ_NEEDS_PUSH)
const READ_PUSHED = MAX ^ READ_NEEDS_PUSH
const READ_PAUSED = MAX ^ READ_RESUMED
const READ_NOT_QUEUED = MAX ^ (READ_QUEUED | READ_EMITTED_READABLE)
const READ_NOT_ENDING = MAX ^ READ_ENDING
const READ_PIPE_NOT_DRAINED = MAX ^ READ_FLOWING
const READ_NOT_NEXT_TICK = MAX ^ READ_NEXT_TICK
const READ_NOT_UPDATING = MAX ^ READ_UPDATING
const READ_NO_READ_AHEAD = MAX ^ READ_READ_AHEAD
const READ_PAUSED_NO_READ_AHEAD = MAX ^ READ_RESUMED_READ_AHEAD

// Write state (18 bit offset, 4 bit offset from shared state and 14 from read state)
const WRITE_ACTIVE = 0b00000000001 << 18
const WRITE_UPDATING = 0b00000000010 << 18
const WRITE_PRIMARY = 0b00000000100 << 18
const WRITE_QUEUED = 0b00000001000 << 18
const WRITE_UNDRAINED = 0b00000010000 << 18
const WRITE_DONE = 0b00000100000 << 18
const WRITE_EMIT_DRAIN = 0b00001000000 << 18
const WRITE_NEXT_TICK = 0b00010000000 << 18
const WRITE_WRITING = 0b00100000000 << 18
const WRITE_FINISHING = 0b01000000000 << 18
const WRITE_CORKED = 0b10000000000 << 18

const WRITE_NOT_ACTIVE = MAX ^ (WRITE_ACTIVE | WRITE_WRITING)
const WRITE_NON_PRIMARY = MAX ^ WRITE_PRIMARY
const WRITE_NOT_FINISHING = MAX ^ (WRITE_ACTIVE | WRITE_FINISHING)
const WRITE_DRAINED = MAX ^ WRITE_UNDRAINED
const WRITE_NOT_QUEUED = MAX ^ WRITE_QUEUED
const WRITE_NOT_NEXT_TICK = MAX ^ WRITE_NEXT_TICK
const WRITE_NOT_UPDATING = MAX ^ WRITE_UPDATING
const WRITE_NOT_CORKED = MAX ^ WRITE_CORKED

// Combined shared state
const ACTIVE = READ_ACTIVE | WRITE_ACTIVE
const NOT_ACTIVE = MAX ^ ACTIVE
const DONE = READ_DONE | WRITE_DONE
const DESTROY_STATUS = DESTROYING | DESTROYED | PREDESTROYING
const OPEN_STATUS = DESTROY_STATUS | OPENING
const AUTO_DESTROY = DESTROY_STATUS | DONE
const NON_PRIMARY = WRITE_NON_PRIMARY & READ_NON_PRIMARY
const ACTIVE_OR_TICKING = WRITE_NEXT_TICK | READ_NEXT_TICK
const TICKING = ACTIVE_OR_TICKING & NOT_ACTIVE
const IS_OPENING = OPEN_STATUS | TICKING

// Combined shared state and read state
const READ_PRIMARY_STATUS = OPEN_STATUS | READ_ENDING | READ_DONE
const READ_STATUS = OPEN_STATUS | READ_DONE | READ_QUEUED
const READ_ENDING_STATUS = OPEN_STATUS | READ_ENDING | READ_QUEUED
const READ_READABLE_STATUS = OPEN_STATUS | READ_EMIT_READABLE | READ_QUEUED | READ_EMITTED_READABLE
const SHOULD_NOT_READ =
  OPEN_STATUS | READ_ACTIVE | READ_ENDING | READ_DONE | READ_NEEDS_PUSH | READ_READ_AHEAD
const READ_BACKPRESSURE_STATUS = DESTROY_STATUS | READ_ENDING | READ_DONE
const READ_UPDATE_SYNC_STATUS = READ_UPDATING | OPEN_STATUS | READ_NEXT_TICK | READ_PRIMARY
const READ_NEXT_TICK_OR_OPENING = READ_NEXT_TICK | OPENING

// Combined write state
const WRITE_PRIMARY_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_DONE
const WRITE_QUEUED_AND_UNDRAINED = WRITE_QUEUED | WRITE_UNDRAINED
const WRITE_QUEUED_AND_ACTIVE = WRITE_QUEUED | WRITE_ACTIVE
const WRITE_DRAIN_STATUS = WRITE_QUEUED | WRITE_UNDRAINED | OPEN_STATUS | WRITE_ACTIVE
const WRITE_STATUS = OPEN_STATUS | WRITE_ACTIVE | WRITE_QUEUED | WRITE_CORKED
const WRITE_PRIMARY_AND_ACTIVE = WRITE_PRIMARY | WRITE_ACTIVE
const WRITE_ACTIVE_AND_WRITING = WRITE_ACTIVE | WRITE_WRITING
const WRITE_FINISHING_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_QUEUED_AND_ACTIVE | WRITE_DONE
const WRITE_BACKPRESSURE_STATUS = WRITE_UNDRAINED | DESTROY_STATUS | WRITE_FINISHING | WRITE_DONE
const WRITE_UPDATE_SYNC_STATUS = WRITE_UPDATING | OPEN_STATUS | WRITE_NEXT_TICK | WRITE_PRIMARY
const WRITE_DROP_DATA = WRITE_FINISHING | WRITE_DONE | DESTROY_STATUS

const asyncIterator = Symbol.asyncIterator || Symbol('asyncIterator')

class WritableState {
  constructor(
    stream,
    { highWaterMark = 16384, map = null, mapWritable, byteLength, byteLengthWritable } = {}
  ) {
    this.stream = stream
    this.queue = new FIFO()
    this.highWaterMark = highWaterMark
    this.buffered = 0
    this.error = null
    this.pipeline = null
    this.drains = null // if we add more seldomly used helpers we might them into a subobject so its a single ptr
    this.byteLength = byteLengthWritable || byteLength || defaultByteLength
    this.map = mapWritable || map
    this.afterWrite = afterWrite.bind(this)
    this.afterUpdateNextTick = updateWriteNT.bind(this)
  }

  get ending() {
    return (this.stream._duplexState & WRITE_FINISHING) !== 0
  }

  get ended() {
    return (this.stream._duplexState & WRITE_DONE) !== 0
  }

  push(data) {
    if ((this.stream._duplexState & WRITE_DROP_DATA) !== 0) return false
    if (this.map !== null) data = this.map(data)

    this.buffered += this.byteLength(data)
    this.queue.push(data)

    if (this.buffered < this.highWaterMark) {
      this.stream._duplexState |= WRITE_QUEUED
      return true
    }

    this.stream._duplexState |= WRITE_QUEUED_AND_UNDRAINED
    return false
  }

  shift() {
    const data = this.queue.shift()

    this.buffered -= this.byteLength(data)
    if (this.buffered === 0) this.stream._duplexState &= WRITE_NOT_QUEUED

    return data
  }

  end(data) {
    if (typeof data === 'function') {
      this.stream.once('finish', data)
    } else if (data !== undefined && data !== null) {
      this.push(data)
    }

    this.stream._duplexState = (this.stream._duplexState | WRITE_FINISHING) & WRITE_NON_PRIMARY
  }

  autoBatch(data, cb) {
    const buffer = []
    const stream = this.stream

    buffer.push(data)
    while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED_AND_ACTIVE) {
      buffer.push(stream._writableState.shift())
    }

    if ((stream._duplexState & OPEN_STATUS) !== 0) return cb(null)
    stream._writev(buffer, cb)
  }

  update() {
    const stream = this.stream

    stream._duplexState |= WRITE_UPDATING

    do {
      while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED) {
        const data = this.shift()
        stream._duplexState |= WRITE_ACTIVE_AND_WRITING
        stream._write(data, this.afterWrite)
      }

      if ((stream._duplexState & WRITE_PRIMARY_AND_ACTIVE) === 0) this.updateNonPrimary()
    } while (this.continueUpdate() === true)

    stream._duplexState &= WRITE_NOT_UPDATING
  }

  updateNonPrimary() {
    const stream = this.stream

    if ((stream._duplexState & WRITE_FINISHING_STATUS) === WRITE_FINISHING) {
      stream._duplexState = stream._duplexState | WRITE_ACTIVE
      stream._final(afterFinal.bind(this))
      return
    }

    if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
      if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
        stream._duplexState |= ACTIVE
        stream._destroy(afterDestroy.bind(this))
      }
      return
    }

    if ((stream._duplexState & IS_OPENING) === OPENING) {
      stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING
      stream._open(afterOpen.bind(this))
    }
  }

  continueUpdate() {
    if ((this.stream._duplexState & WRITE_NEXT_TICK) === 0) return false
    this.stream._duplexState &= WRITE_NOT_NEXT_TICK
    return true
  }

  updateCallback() {
    if ((this.stream._duplexState & WRITE_UPDATE_SYNC_STATUS) === WRITE_PRIMARY) {
      this.update()
    } else {
      this.updateNextTick()
    }
  }

  updateNextTick() {
    if ((this.stream._duplexState & WRITE_NEXT_TICK) !== 0) return
    this.stream._duplexState |= WRITE_NEXT_TICK
    if ((this.stream._duplexState & WRITE_UPDATING) === 0) qmt(this.afterUpdateNextTick)
  }
}

class ReadableState {
  constructor(
    stream,
    { highWaterMark = 16384, map = null, mapReadable, byteLength, byteLengthReadable } = {}
  ) {
    this.stream = stream
    this.queue = new FIFO()
    this.highWaterMark = highWaterMark === 0 ? 1 : highWaterMark
    this.buffered = 0
    this.readAhead = highWaterMark > 0
    this.error = null
    this.pipeline = null
    this.byteLength = byteLengthReadable || byteLength || defaultByteLength
    this.map = mapReadable || map
    this.pipeTo = null
    this.afterRead = afterRead.bind(this)
    this.afterUpdateNextTick = updateReadNT.bind(this)
  }

  get ending() {
    return (this.stream._duplexState & READ_ENDING) !== 0
  }

  get ended() {
    return (this.stream._duplexState & READ_DONE) !== 0
  }

  pipe(pipeTo, cb) {
    if (this.pipeTo !== null) throw StreamError.BAD_ARGUMENT('Can only pipe to one destination')
    if (typeof cb !== 'function') cb = null

    this.stream._duplexState |= READ_PIPE_DRAINED
    this.pipeTo = pipeTo
    this.pipeline = new Pipeline(this.stream, pipeTo, cb)

    if (cb) this.stream.on('error', noop) // We already error handle this so supress crashes

    if (isStreamx(pipeTo)) {
      pipeTo._writableState.pipeline = this.pipeline
      if (cb) pipeTo.on('error', noop) // We already error handle this so supress crashes
      pipeTo.on('finish', this.pipeline.finished.bind(this.pipeline)) // TODO: just call finished from pipeTo itself
    } else {
      const onerror = this.pipeline.done.bind(this.pipeline, pipeTo)
      const onclose = this.pipeline.done.bind(this.pipeline, pipeTo, null) // onclose has a weird bool arg
      pipeTo.on('error', onerror)
      pipeTo.on('close', onclose)
      pipeTo.on('finish', this.pipeline.finished.bind(this.pipeline))
    }

    pipeTo.on('drain', afterDrain.bind(this))
    this.stream.emit('piping', pipeTo)
    pipeTo.emit('pipe', this.stream)
  }

  push(data) {
    const stream = this.stream

    if (data === null) {
      this.highWaterMark = 0
      stream._duplexState = (stream._duplexState | READ_ENDING) & READ_NON_PRIMARY_AND_PUSHED
      return false
    }

    if (this.map !== null) {
      data = this.map(data)
      if (data === null) {
        stream._duplexState &= READ_PUSHED
        return this.buffered < this.highWaterMark
      }
    }

    this.buffered += this.byteLength(data)
    this.queue.push(data)

    stream._duplexState = (stream._duplexState | READ_QUEUED) & READ_PUSHED

    return this.buffered < this.highWaterMark
  }

  shift() {
    const data = this.queue.shift()

    this.buffered -= this.byteLength(data)
    if (this.buffered === 0) {
      this.stream._duplexState &= READ_NOT_QUEUED
    }

    return data
  }

  unshift(data) {
    const pending = [this.map !== null ? this.map(data) : data]
    while (this.buffered > 0) pending.push(this.shift())

    for (let i = 0; i < pending.length - 1; i++) {
      const data = pending[i]
      this.buffered += this.byteLength(data)
      this.queue.push(data)
    }

    this.push(pending[pending.length - 1])
  }

  read() {
    const stream = this.stream

    if ((stream._duplexState & READ_STATUS) === READ_QUEUED) {
      const data = this.shift()

      if (this.pipeTo !== null && this.pipeTo.write(data) === false) {
        stream._duplexState &= READ_PIPE_NOT_DRAINED
      }

      if ((stream._duplexState & READ_EMIT_DATA) !== 0) {
        stream.emit('data', data)
      }

      return data
    }

    if (this.readAhead === false) {
      stream._duplexState |= READ_READ_AHEAD
      this.updateNextTick()
    }

    return null
  }

  drain() {
    const stream = this.stream

    while (
      (stream._duplexState & READ_STATUS) === READ_QUEUED &&
      (stream._duplexState & READ_FLOWING) !== 0
    ) {
      const data = this.shift()

      if (this.pipeTo !== null && this.pipeTo.write(data) === false) {
        stream._duplexState &= READ_PIPE_NOT_DRAINED
      }

      if ((stream._duplexState & READ_EMIT_DATA) !== 0) {
        stream.emit('data', data)
      }
    }
  }

  update() {
    const stream = this.stream

    stream._duplexState |= READ_UPDATING

    do {
      this.drain()

      while (
        this.buffered < this.highWaterMark &&
        (stream._duplexState & SHOULD_NOT_READ) === READ_READ_AHEAD
      ) {
        stream._duplexState |= READ_ACTIVE_AND_NEEDS_PUSH
        stream._read(this.afterRead)
        this.drain()
      }

      if ((stream._duplexState & READ_READABLE_STATUS) === READ_EMIT_READABLE_AND_QUEUED) {
        stream._duplexState |= READ_EMITTED_READABLE
        stream.emit('readable')
      }

      if ((stream._duplexState & READ_PRIMARY_AND_ACTIVE) === 0) {
        this.updateNonPrimary()
      }
    } while (this.continueUpdate() === true)

    stream._duplexState &= READ_NOT_UPDATING
  }

  updateNonPrimary() {
    const stream = this.stream

    if ((stream._duplexState & READ_ENDING_STATUS) === READ_ENDING) {
      stream._duplexState = (stream._duplexState | READ_DONE) & READ_NOT_ENDING
      stream.emit('end')

      if ((stream._duplexState & AUTO_DESTROY) === DONE) {
        stream._duplexState |= DESTROYING
      }

      if (this.pipeTo !== null) {
        this.pipeTo.end()
      }
    }

    if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
      if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
        stream._duplexState |= ACTIVE
        stream._destroy(afterDestroy.bind(this))
      }
      return
    }

    if ((stream._duplexState & IS_OPENING) === OPENING) {
      stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING
      stream._open(afterOpen.bind(this))
    }
  }

  continueUpdate() {
    if ((this.stream._duplexState & READ_NEXT_TICK) === 0) return false
    this.stream._duplexState &= READ_NOT_NEXT_TICK
    return true
  }

  updateCallback() {
    if ((this.stream._duplexState & READ_UPDATE_SYNC_STATUS) === READ_PRIMARY) {
      this.update()
    } else {
      this.updateNextTick()
    }
  }

  updateNextTickIfOpen() {
    if ((this.stream._duplexState & READ_NEXT_TICK_OR_OPENING) !== 0) return
    this.stream._duplexState |= READ_NEXT_TICK
    if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick)
  }

  updateNextTick() {
    if ((this.stream._duplexState & READ_NEXT_TICK) !== 0) return
    this.stream._duplexState |= READ_NEXT_TICK
    if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick)
  }
}

class TransformState {
  constructor(stream) {
    this.data = null
    this.afterTransform = afterTransform.bind(stream)
    this.afterFinal = null
  }
}

class Pipeline {
  constructor(src, dst, cb) {
    this.from = src
    this.to = dst
    this.afterPipe = cb
    this.error = null
    this.pipeToFinished = false
  }

  finished() {
    this.pipeToFinished = true
  }

  done(stream, err) {
    if (err) this.error = err

    if (stream === this.to) {
      this.to = null

      if (this.from !== null) {
        if ((this.from._duplexState & READ_DONE) === 0 || !this.pipeToFinished) {
          this.from.destroy(this.error || StreamError.PREMATURE_CLOSE('Writable stream closed'))
        }
        return
      }
    }

    if (stream === this.from) {
      this.from = null

      if (this.to !== null) {
        if ((stream._duplexState & READ_DONE) === 0) {
          this.to.destroy(this.error || StreamError.PREMATURE_CLOSE('Readable stream closed'))
        }
        return
      }
    }

    if (this.afterPipe !== null) this.afterPipe(this.error)
    this.to = this.from = this.afterPipe = null
  }
}

function afterDrain() {
  this.stream._duplexState |= READ_PIPE_DRAINED
  this.updateCallback()
}

function afterFinal(err) {
  const stream = this.stream
  if (err) stream.destroy(err)

  if ((stream._duplexState & DESTROY_STATUS) === 0) {
    stream._duplexState |= WRITE_DONE
    stream.emit('finish')
  }

  if ((stream._duplexState & AUTO_DESTROY) === DONE) {
    stream._duplexState |= DESTROYING
  }

  stream._duplexState &= WRITE_NOT_FINISHING

  // no need to wait the extra tick here, so we short circuit that
  if ((stream._duplexState & WRITE_UPDATING) === 0) {
    this.update()
  } else {
    this.updateNextTick()
  }
}

function afterDestroy(err) {
  const stream = this.stream

  if (!err && !StreamError.isStreamDestroyed(this.error)) err = this.error
  if (err) stream.emit('error', err)

  stream._duplexState |= DESTROYED
  stream.emit('close')

  const rs = stream._readableState
  const ws = stream._writableState

  if (rs !== null && rs.pipeline !== null) {
    rs.pipeline.done(stream, err)
  }

  if (ws !== null) {
    while (ws.drains !== null && ws.drains.length > 0) {
      ws.drains.shift().resolve(false)
    }

    if (ws.pipeline !== null) {
      ws.pipeline.done(stream, err)
    }
  }
}

function afterWrite(err) {
  const stream = this.stream

  if (err) stream.destroy(err)
  stream._duplexState &= WRITE_NOT_ACTIVE

  if (this.drains !== null) tickDrains(this.drains)

  if ((stream._duplexState & WRITE_DRAIN_STATUS) === WRITE_UNDRAINED) {
    stream._duplexState &= WRITE_DRAINED

    if ((stream._duplexState & WRITE_EMIT_DRAIN) === WRITE_EMIT_DRAIN) {
      stream.emit('drain')
    }
  }

  this.updateCallback()
}

function afterRead(err) {
  if (err) this.stream.destroy(err)
  this.stream._duplexState &= READ_NOT_ACTIVE

  if (this.readAhead === false && (this.stream._duplexState & READ_RESUMED) === 0) {
    this.stream._duplexState &= READ_NO_READ_AHEAD
  }

  this.updateCallback()
}

function updateReadNT() {
  if ((this.stream._duplexState & READ_UPDATING) === 0) {
    this.stream._duplexState &= READ_NOT_NEXT_TICK
    this.update()
  }
}

function updateWriteNT() {
  if ((this.stream._duplexState & WRITE_UPDATING) === 0) {
    this.stream._duplexState &= WRITE_NOT_NEXT_TICK
    this.update()
  }
}

function tickDrains(drains) {
  for (let i = 0; i < drains.length; i++) {
    // drains.writes are monotonic, so if one is 0 its always the first one
    if (--drains[i].writes === 0) {
      drains.shift().resolve(true)
      i--
    }
  }
}

function afterOpen(err) {
  const stream = this.stream

  if (err) stream.destroy(err)

  if ((stream._duplexState & DESTROYING) === 0) {
    if ((stream._duplexState & READ_PRIMARY_STATUS) === 0) {
      stream._duplexState |= READ_PRIMARY
    }

    if ((stream._duplexState & WRITE_PRIMARY_STATUS) === 0) {
      stream._duplexState |= WRITE_PRIMARY
    }

    stream.emit('open')
  }

  stream._duplexState &= NOT_ACTIVE

  if (stream._writableState !== null) {
    stream._writableState.updateCallback()
  }

  if (stream._readableState !== null) {
    stream._readableState.updateCallback()
  }
}

function afterTransform(err, data) {
  if (data !== undefined && data !== null) this.push(data)
  this._writableState.afterWrite(err)
}

function newListener(name) {
  if (this._readableState !== null) {
    if (name === 'data') {
      this._duplexState |= READ_EMIT_DATA | READ_RESUMED_READ_AHEAD
      this._readableState.updateNextTick()
    }
    if (name === 'readable') {
      this._duplexState |= READ_EMIT_READABLE
      this._readableState.updateNextTick()
    }
  }

  if (this._writableState !== null) {
    if (name === 'drain') {
      this._duplexState |= WRITE_EMIT_DRAIN
      this._writableState.updateNextTick()
    }
  }
}

class Stream extends EventEmitter {
  constructor(opts) {
    super()

    this._duplexState = 0
    this._readableState = null
    this._writableState = null

    if (opts) {
      if (opts.open) this._open = opts.open
      if (opts.destroy) this._destroy = opts.destroy
      if (opts.predestroy) this._predestroy = opts.predestroy
      if (opts.signal) opts.signal.addEventListener('abort', abort.bind(this))
    }

    this.on('newListener', newListener)
  }

  _open(cb) {
    cb(null)
  }

  _destroy(cb) {
    cb(null)
  }

  _predestroy() {
    // does nothing
  }

  get readable() {
    return this._readableState !== null ? true : undefined
  }

  get writable() {
    return this._writableState !== null ? true : undefined
  }

  get destroyed() {
    return (this._duplexState & DESTROYED) !== 0
  }

  get destroying() {
    return (this._duplexState & DESTROY_STATUS) !== 0
  }

  destroy(err) {
    if ((this._duplexState & DESTROY_STATUS) === 0) {
      if (!err) err = StreamError.STREAM_DESTROYED()
      this._duplexState = (this._duplexState | DESTROYING) & NON_PRIMARY

      if (this._readableState !== null) {
        this._readableState.highWaterMark = 0
        this._readableState.error = err
      }

      if (this._writableState !== null) {
        this._writableState.highWaterMark = 0
        this._writableState.error = err
      }

      this._duplexState |= PREDESTROYING
      this._predestroy()
      this._duplexState &= NOT_PREDESTROYING

      if (this._readableState !== null) {
        this._readableState.updateNextTick()
      }

      if (this._writableState !== null) {
        this._writableState.updateNextTick()
      }
    }
  }
}

class Readable extends Stream {
  constructor(opts) {
    super(opts)

    this._duplexState |= OPENING | WRITE_DONE | READ_READ_AHEAD
    this._readableState = new ReadableState(this, opts)

    if (opts) {
      if (this._readableState.readAhead === false) this._duplexState &= READ_NO_READ_AHEAD
      if (opts.read) this._read = opts.read
      if (opts.eagerOpen) this._readableState.updateNextTick()
      if (opts.encoding) this.setEncoding(opts.encoding)
    }
  }

  static deferred(fn, opts) {
    const out = new PassThrough(opts)

    fn()
      .then((src) => {
        if (src === null) return out.end()
        if (out.destroying) return
        pipeline(src, out, noop)
      })
      .catch((err) => out.destroy(err))

    return out
  }

  setEncoding(encoding) {
    const dec = new TextDecoder(encoding)
    const map = this._readableState.map || echo
    this._readableState.map = mapOrSkip
    return this

    function mapOrSkip(data) {
      const next = dec.push(data)
      return next === '' && (data.byteLength !== 0 || dec.remaining > 0) ? null : map(next)
    }
  }

  _read(cb) {
    cb(null)
  }

  pipe(dest, cb) {
    this._readableState.updateNextTick()
    this._readableState.pipe(dest, cb)
    return dest
  }

  read() {
    this._readableState.updateNextTick()
    return this._readableState.read()
  }

  push(data) {
    this._readableState.updateNextTickIfOpen()
    return this._readableState.push(data)
  }

  unshift(data) {
    this._readableState.updateNextTickIfOpen()
    return this._readableState.unshift(data)
  }

  resume() {
    this._duplexState |= READ_RESUMED_READ_AHEAD
    this._readableState.updateNextTick()
    return this
  }

  pause() {
    this._duplexState &=
      this._readableState.readAhead === false ? READ_PAUSED_NO_READ_AHEAD : READ_PAUSED
    return this
  }

  static _fromAsyncIterator(ite, opts) {
    let destroy

    const rs = new Readable({
      ...opts,
      read(cb) {
        ite.next().then(push).then(cb.bind(null, null)).catch(cb)
      },
      predestroy() {
        destroy = ite.return()
      },
      destroy(cb) {
        if (!destroy) return cb(null)
        destroy.then(cb.bind(null, null)).catch(cb)
      }
    })

    return rs

    function push(data) {
      if (data.done) rs.push(null)
      else rs.push(data.value)
    }
  }

  static from(data, opts) {
    if (isReadStreamx(data)) return data
    if (data[asyncIterator]) return this._fromAsyncIterator(data[asyncIterator](), opts)
    if (!Array.isArray(data)) data = data === undefined ? [] : [data]

    let i = 0
    return new Readable({
      ...opts,
      read(cb) {
        this.push(i === data.length ? null : data[i++])
        cb(null)
      }
    })
  }

  static isBackpressured(rs) {
    return (
      (rs._duplexState & READ_BACKPRESSURE_STATUS) !== 0 ||
      rs._readableState.buffered >= rs._readableState.highWaterMark
    )
  }

  static isPaused(rs) {
    return (rs._duplexState & READ_RESUMED) === 0
  }

  [asyncIterator]() {
    const stream = this

    let error = null
    let promiseResolve = null
    let promiseReject = null

    this.on('error', (err) => {
      error = err
    })
    this.on('readable', onreadable)
    this.on('close', onclose)

    return {
      [asyncIterator]() {
        return this
      },
      next() {
        return new Promise(function (resolve, reject) {
          promiseResolve = resolve
          promiseReject = reject
          const data = stream.read()
          if (data !== null) ondata(data)
          else if ((stream._duplexState & DESTROYED) !== 0) ondata(null)
        })
      },
      return() {
        return destroy(null)
      },
      throw(err) {
        return destroy(err)
      }
    }

    function onreadable() {
      if (promiseResolve !== null) ondata(stream.read())
    }

    function onclose() {
      if (promiseResolve !== null) ondata(null)
    }

    function ondata(data) {
      if (promiseReject === null) return
      if (error) {
        promiseReject(error)
      } else if (data === null && (stream._duplexState & READ_DONE) === 0) {
        promiseReject(StreamError.STREAM_DESTROYED())
      } else {
        promiseResolve({ value: data, done: data === null })
      }
      promiseReject = promiseResolve = null
    }

    function destroy(err) {
      stream.destroy(err)
      return new Promise((resolve, reject) => {
        if (stream._duplexState & DESTROYED) return resolve({ value: undefined, done: true })
        stream.once('close', function () {
          if (err) reject(err)
          else resolve({ value: undefined, done: true })
        })
      })
    }
  }
}

class Writable extends Stream {
  constructor(opts) {
    super(opts)

    this._duplexState |= OPENING | READ_DONE
    this._writableState = new WritableState(this, opts)

    if (opts) {
      if (opts.writev) this._writev = opts.writev
      if (opts.write) this._write = opts.write
      if (opts.final) this._final = opts.final
      if (opts.eagerOpen) this._writableState.updateNextTick()
    }
  }

  cork() {
    this._duplexState |= WRITE_CORKED
  }

  uncork() {
    this._duplexState &= WRITE_NOT_CORKED
    this._writableState.updateNextTick()
  }

  _writev(batch, cb) {
    cb(null)
  }

  _write(data, cb) {
    this._writableState.autoBatch(data, cb)
  }

  _final(cb) {
    cb(null)
  }

  static isBackpressured(ws) {
    return (ws._duplexState & WRITE_BACKPRESSURE_STATUS) !== 0
  }

  static drained(ws) {
    if (ws.destroyed) return Promise.resolve(false)

    const state = ws._writableState
    const pending = isWritev(ws) ? Math.min(1, state.queue.length) : state.queue.length
    const writes = pending + (ws._duplexState & WRITE_WRITING ? 1 : 0)
    if (writes === 0) return Promise.resolve(true)

    if (state.drains === null) state.drains = []
    return new Promise((resolve) => {
      state.drains.push({ writes, resolve })
    })
  }

  write(data) {
    this._writableState.updateNextTick()
    return this._writableState.push(data)
  }

  end(data) {
    this._writableState.updateNextTick()
    this._writableState.end(data)
    return this
  }
}

class Duplex extends Readable {
  // and Writable
  constructor(opts) {
    super(opts)

    this._duplexState = OPENING | (this._duplexState & READ_READ_AHEAD)
    this._writableState = new WritableState(this, opts)

    if (opts) {
      if (opts.writev) this._writev = opts.writev
      if (opts.write) this._write = opts.write
      if (opts.final) this._final = opts.final
    }
  }

  cork() {
    this._duplexState |= WRITE_CORKED
  }

  uncork() {
    this._duplexState &= WRITE_NOT_CORKED
    this._writableState.updateNextTick()
  }

  _writev(batch, cb) {
    cb(null)
  }

  _write(data, cb) {
    this._writableState.autoBatch(data, cb)
  }

  _final(cb) {
    cb(null)
  }

  write(data) {
    this._writableState.updateNextTick()
    return this._writableState.push(data)
  }

  end(data) {
    this._writableState.updateNextTick()
    this._writableState.end(data)
    return this
  }
}

class Transform extends Duplex {
  constructor(opts) {
    super(opts)
    this._transformState = new TransformState(this)

    if (opts) {
      if (opts.transform) this._transform = opts.transform
      if (opts.flush) this._flush = opts.flush
    }
  }

  _write(data, cb) {
    if (this._readableState.buffered >= this._readableState.highWaterMark) {
      this._transformState.data = data
    } else {
      this._transform(data, this._transformState.afterTransform)
    }
  }

  _read(cb) {
    if (this._transformState.data !== null) {
      const data = this._transformState.data
      this._transformState.data = null
      cb(null)
      this._transform(data, this._transformState.afterTransform)
    } else {
      cb(null)
    }
  }

  destroy(err) {
    super.destroy(err)
    if (this._transformState.data !== null) {
      this._transformState.data = null
      this._transformState.afterTransform()
    }
  }

  _transform(data, cb) {
    cb(null, data)
  }

  _flush(cb) {
    cb(null)
  }

  _final(cb) {
    this._transformState.afterFinal = cb
    this._flush(transformAfterFlush.bind(this))
  }
}

class PassThrough extends Transform {}

function transformAfterFlush(err, data) {
  const cb = this._transformState.afterFinal
  if (err) return cb(err)

  if (data !== null && data !== undefined) this.push(data)
  this.push(null)
  cb(null)
}

function pipelinePromise(...streams) {
  return new Promise((resolve, reject) => {
    return pipeline(...streams, (err) => {
      if (err) return reject(err)
      resolve()
    })
  })
}

function pipeline(stream, ...streams) {
  const all = Array.isArray(stream) ? [...stream, ...streams] : [stream, ...streams]
  const done = all.length && typeof all[all.length - 1] === 'function' ? all.pop() : null

  if (all.length < 2) throw StreamError.BAD_ARGUMENT('Pipeline requires at least 2 streams')

  let src = all[0]
  let dest = null
  let error = null

  for (let i = 1; i < all.length; i++) {
    dest = all[i]

    if (isStreamx(src)) {
      src.pipe(dest, onerror)
    } else {
      errorHandle(src, true, i > 1, onerror)
      src.pipe(dest)
    }

    src = dest
  }

  if (done) {
    let fin = false

    const autoDestroy =
      isStreamx(dest) || !!(dest._writableState && dest._writableState.autoDestroy)

    dest.on('error', (err) => {
      if (error === null) error = err
    })

    dest.on('finish', () => {
      fin = true
      if (!autoDestroy) done(error)
    })

    if (autoDestroy) {
      dest.on('close', () => done(error || (fin ? null : StreamError.PREMATURE_CLOSE())))
    }
  }

  return dest

  function errorHandle(s, rd, wr, onerror) {
    s.on('error', onerror)
    s.on('close', onclose)

    function onclose() {
      if (rd && s._readableState && !s._readableState.ended) {
        return onerror(StreamError.PREMATURE_CLOSE())
      }
      if (wr && s._writableState && !s._writableState.ended) {
        return onerror(StreamError.PREMATURE_CLOSE())
      }
    }
  }

  function onerror(err) {
    if (!err || error) return
    error = err

    for (const s of all) {
      s.destroy(err)
    }
  }
}

function echo(s) {
  return s
}

function isStream(stream) {
  return !!stream._readableState || !!stream._writableState
}

function isStreamx(stream) {
  return typeof stream._duplexState === 'number' && isStream(stream)
}

function isEnding(stream) {
  return !!stream._readableState && stream._readableState.ending
}

function isEnded(stream) {
  return !!stream._readableState && stream._readableState.ended
}

function isFinishing(stream) {
  return !!stream._writableState && stream._writableState.ending
}

function isFinished(stream) {
  return !!stream._writableState && stream._writableState.ended
}

function getStreamError(stream, opts = {}) {
  const err =
    (stream._readableState && stream._readableState.error) ||
    (stream._writableState && stream._writableState.error)

  // avoid implicit errors by default
  return !opts.all && StreamError.isStreamDestroyed(err) ? null : err
}

function isReadStreamx(stream) {
  return isStreamx(stream) && stream.readable
}

function isDisturbed(stream) {
  return (
    (stream._duplexState & OPENING) !== OPENING ||
    (stream._duplexState & DESTROYING) === DESTROYING ||
    (stream._duplexState & ACTIVE_OR_TICKING) !== 0
  )
}

function isTypedArray(data) {
  return typeof data === 'object' && data !== null && typeof data.byteLength === 'number'
}

function defaultByteLength(data) {
  return isTypedArray(data) ? data.byteLength : 1024
}

function noop() {}

function abort() {
  this.destroy(StreamError.ABORTED())
}

function isWritev(s) {
  return s._writev !== Writable.prototype._writev && s._writev !== Duplex.prototype._writev
}

module.exports = {
  pipeline,
  pipelinePromise,
  isStream,
  isStreamx,
  isEnding,
  isEnded,
  isFinishing,
  isFinished,
  isDisturbed,
  getStreamError,
  Stream,
  Writable,
  Readable,
  Duplex,
  Transform,
  // Export PassThrough for compatibility with Node.js core's stream module
  PassThrough
}
module.exports = class StreamError extends Error {
  constructor(msg, code, fn = StreamError) {
    super(msg)

    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  static isStreamDestroyed(err) {
    return err && err.code === 'STREAM_DESTROYED'
  }

  static isPrematureClose(err) {
    return err && err.code === 'PREMATURE_CLOSE'
  }

  static isAborted(err) {
    return err && err.code === 'ABORTED'
  }

  static isBadArgument(err) {
    return err && err.code === 'BAD_ARGUMENT'
  }

  get name() {
    return 'StreamError'
  }

  static STREAM_DESTROYED() {
    return new StreamError('Stream was destroyed', 'STREAM_DESTROYED', StreamError.STREAM_DESTROYED)
  }

  static PREMATURE_CLOSE(msg = 'Premature close') {
    return new StreamError(msg, 'PREMATURE_CLOSE', StreamError.PREMATURE_CLOSE)
  }

  static ABORTED() {
    return new StreamError('Stream aborted', 'ABORTED', StreamError.ABORTED)
  }

  static BAD_ARGUMENT(msg = 'Bad argument') {
    return new StreamError(msg, 'BAD_ARGUMENT', StreamError.BAD_ARGUMENT)
  }
}
{
  "name": "streamx",
  "version": "2.28.0",
  "description": "An iteration of the Node.js core streams with a series of improvements",
  "main": "index.js",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./errors": {
      "types": "./lib/errors.d.ts",
      "default": "./lib/errors"
    }
  },
  "dependencies": {
    "events-universal": "^1.0.0",
    "fast-fifo": "^1.3.2",
    "text-decoder": "^1.1.0"
  },
  "devDependencies": {
    "b4a": "^1.6.6",
    "brittle": "^3.1.1",
    "end-of-stream": "^1.4.4",
    "lunte": "^1.8.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "runtime.d.ts",
    "lib"
  ],
  "scripts": {
    "format": "prettier . --write",
    "test": "brittle test/all.js && brittle-bare test/all.js",
    "lint": "prettier . --check && lunte"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/streamx.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/streamx/issues"
  },
  "homepage": "https://github.com/mafintosh/streamx"
}
const PassThroughDecoder = require('./lib/pass-through-decoder')
const UTF8Decoder = require('./lib/utf8-decoder')

module.exports = class TextDecoder {
  constructor(encoding = 'utf8') {
    this.encoding = normalizeEncoding(encoding)

    switch (this.encoding) {
      case 'utf8':
        this.decoder = new UTF8Decoder()
        break
      case 'utf16le':
      case 'base64':
        throw new Error('Unsupported encoding: ' + this.encoding)
      default:
        this.decoder = new PassThroughDecoder(this.encoding)
    }
  }

  get remaining() {
    return this.decoder.remaining
  }

  push(data) {
    if (typeof data === 'string') return data
    return this.decoder.decode(data)
  }

  // For Node.js compatibility
  write(data) {
    return this.push(data)
  }

  end(data) {
    let result = ''
    if (data) result = this.push(data)
    result += this.decoder.flush()
    return result
  }
}

function normalizeEncoding(encoding) {
  encoding = encoding.toLowerCase()

  switch (encoding) {
    case 'utf8':
    case 'utf-8':
      return 'utf8'
    case 'ucs2':
    case 'ucs-2':
    case 'utf16le':
    case 'utf-16le':
      return 'utf16le'
    case 'latin1':
    case 'binary':
      return 'latin1'
    case 'base64':
    case 'ascii':
    case 'hex':
      return encoding
    default:
      throw new Error('Unknown encoding: ' + encoding)
  }
}
const b4a = require('b4a')

module.exports = class PassThroughDecoder {
  constructor(encoding) {
    this.encoding = encoding
  }

  get remaining() {
    return 0
  }

  decode(data) {
    return b4a.toString(data, this.encoding)
  }

  flush() {
    return ''
  }
}
const b4a = require('b4a')

/**
 * https://encoding.spec.whatwg.org/#utf-8-decoder
 */
module.exports = class UTF8Decoder {
  constructor() {
    this._reset()
  }

  get remaining() {
    return this.bytesSeen
  }

  decode(data) {
    if (data.byteLength === 0) return ''

    if (this.bytesNeeded === 0 && trailingIncomplete(data, 0) === 0) {
      this.bytesSeen = trailingBytesSeen(data)
      return b4a.toString(data, 'utf8')
    }

    let result = ''
    let start = 0

    if (this.bytesNeeded > 0) {
      while (start < data.byteLength) {
        const byte = data[start]

        if (byte < this.lowerBoundary || byte > this.upperBoundary) {
          result += '\ufffd'
          this._reset()
          break
        }

        this.lowerBoundary = 0x80
        this.upperBoundary = 0xbf
        this.codePoint = (this.codePoint << 6) | (byte & 0x3f)
        this.bytesSeen++
        start++

        if (this.bytesSeen === this.bytesNeeded) {
          result += String.fromCodePoint(this.codePoint)
          this._reset()
          break
        }
      }

      if (this.bytesNeeded > 0) return result
    }

    const trailing = trailingIncomplete(data, start)
    const end = data.byteLength - trailing

    if (end > start) result += b4a.toString(data, 'utf8', start, end)

    for (let i = end; i < data.byteLength; i++) {
      const byte = data[i]

      if (this.bytesNeeded === 0) {
        if (byte <= 0x7f) {
          this.bytesSeen = 0
          result += String.fromCharCode(byte)
        } else if (byte >= 0xc2 && byte <= 0xdf) {
          this.bytesNeeded = 2
          this.bytesSeen = 1
          this.codePoint = byte & 0x1f
        } else if (byte >= 0xe0 && byte <= 0xef) {
          if (byte === 0xe0) this.lowerBoundary = 0xa0
          else if (byte === 0xed) this.upperBoundary = 0x9f
          this.bytesNeeded = 3
          this.bytesSeen = 1
          this.codePoint = byte & 0xf
        } else if (byte >= 0xf0 && byte <= 0xf4) {
          if (byte === 0xf0) this.lowerBoundary = 0x90
          else if (byte === 0xf4) this.upperBoundary = 0x8f
          this.bytesNeeded = 4
          this.bytesSeen = 1
          this.codePoint = byte & 0x7
        } else {
          this.bytesSeen = 1
          result += '\ufffd'
        }

        continue
      }

      if (byte < this.lowerBoundary || byte > this.upperBoundary) {
        result += '\ufffd'
        i--
        this._reset()

        continue
      }

      this.lowerBoundary = 0x80
      this.upperBoundary = 0xbf

      this.codePoint = (this.codePoint << 6) | (byte & 0x3f)
      this.bytesSeen++

      if (this.bytesSeen === this.bytesNeeded) {
        result += String.fromCodePoint(this.codePoint)
        this._reset()
      }
    }

    return result
  }

  flush() {
    const result = this.bytesNeeded > 0 ? '\ufffd' : ''
    this._reset()
    return result
  }

  _reset() {
    this.codePoint = 0
    this.bytesNeeded = 0
    this.bytesSeen = 0
    this.lowerBoundary = 0x80
    this.upperBoundary = 0xbf
  }
}

function trailingIncomplete(data, start) {
  const len = data.byteLength
  if (len <= start) return 0

  const limit = Math.max(start, len - 4)

  let i = len - 1
  while (i > limit && (data[i] & 0xc0) === 0x80) i--

  if (i < start) return 0

  const byte = data[i]

  let needed
  if (byte <= 0x7f) return 0
  if (byte >= 0xc2 && byte <= 0xdf) needed = 2
  else if (byte >= 0xe0 && byte <= 0xef) needed = 3
  else if (byte >= 0xf0 && byte <= 0xf4) needed = 4
  else return 0

  const available = len - i
  return available < needed ? available : 0
}

function trailingBytesSeen(data) {
  const len = data.byteLength
  if (len === 0) return 0

  const last = data[len - 1]

  if (last <= 0x7f) return 0
  if ((last & 0xc0) !== 0x80) return 1

  const limit = Math.max(0, len - 4)

  let i = len - 2
  while (i >= limit && (data[i] & 0xc0) === 0x80) i--

  if (i < 0) return 1

  const first = data[i]

  let needed
  if (first >= 0xc2 && first <= 0xdf) needed = 2
  else if (first >= 0xe0 && first <= 0xef) needed = 3
  else if (first >= 0xf0 && first <= 0xf4) needed = 4
  else return 1

  if (len - i !== needed) return 1

  if (needed >= 3) {
    const second = data[i + 1]
    if (first === 0xe0 && second < 0xa0) return 1
    if (first === 0xed && second > 0x9f) return 1
    if (first === 0xf0 && second < 0x90) return 1
    if (first === 0xf4 && second > 0x8f) return 1
  }

  return 0
}
{
  "name": "text-decoder",
  "version": "1.2.7",
  "description": "Streaming text decoder that preserves multibyte Unicode characters",
  "exports": {
    "./package": "./package.json",
    ".": "./index.js"
  },
  "files": [
    "index.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/text-decoder.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/text-decoder/issues"
  },
  "homepage": "https://github.com/holepunchto/text-decoder#readme",
  "dependencies": {
    "b4a": "^1.6.4"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  }
}
module.exports = class TimeOrderedSet {
  constructor () {
    this.oldest = null
    this.latest = null
    this.length = 0
  }

  has (node) {
    return !!(node.next || node.prev) || node === this.oldest
  }

  add (node) {
    if (this.has(node)) this.remove(node)

    if (!this.latest && !this.oldest) {
      this.latest = this.oldest = node
      node.prev = node.next = null
    } else {
      this.latest.next = node
      node.prev = this.latest
      node.next = null
      this.latest = node
    }

    this.length++

    return node
  }

  remove (node) {
    if (!this.has(node)) return node

    if (this.oldest !== node && this.latest !== node) {
      node.prev.next = node.next
      node.next.prev = node.prev
    } else {
      if (this.oldest === node) {
        this.oldest = node.next
        if (this.oldest) this.oldest.prev = null
      }
      if (this.latest === node) {
        this.latest = node.prev
        if (this.latest) this.latest.next = null
      }
    }

    node.next = node.prev = null
    this.length--

    return node
  }

  toArray ({ limit = Infinity, reverse = false } = {}) {
    const list = []

    if (reverse) {
      let node = this.latest
      while (node && limit--) {
        list.push(node)
        node = node.prev
      }
    } else {
      let node = this.oldest
      while (node && limit--) {
        list.push(node)
        node = node.next
      }
    }

    return list
  }
}
{
  "name": "time-ordered-set",
  "version": "2.0.1",
  "description": "Efficiently maintain a set of nodes ordered by the time they were added to the set",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "devDependencies": {
    "brittle": "^3.0.0",
    "standard": "^17.1.2"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/time-ordered-set.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/time-ordered-set/issues"
  },
  "homepage": "https://github.com/mafintosh/time-ordered-set"
}
module.exports = class TimerBrowser {
  constructor (ms, fn, ctx = null, interval = false) {
    this.ms = ms
    this.ontimeout = fn
    this.context = ctx || null
    this.interval = interval
    this.done = false

    this._timer = interval
      ? setInterval(callInterval, ms, this)
      : setTimeout(callTimeout, ms, this)
  }

  unref () {}

  ref () {}

  refresh () {
    if (this.done) return

    if (this.interval) {
      clearInterval(this._timer)
      this._timer = setInterval(callInterval, this.ms, this)
    } else {
      clearTimeout(this._timer)
      this._timer = setTimeout(callTimeout, this.ms, this)
    }
  }

  destroy () {
    this.done = true
    this.ontimeout = null

    if (this.interval) clearInterval(this._timer)
    else clearTimeout(this._timer)
  }

  static once (ms, fn, ctx) {
    return new this(ms, fn, ctx, false)
  }

  static on (ms, fn, ctx) {
    return new this(ms, fn, ctx, true)
  }
}

function callTimeout (self) {
  self.done = true
  self.ontimeout.call(self.context)
}

function callInterval (self) {
  self.ontimeout.call(self.context)
}
module.exports = isNode()
  ? require('./node')
  : require('./browser')

function isNode () {
  const to = setTimeout(function () {}, 1000)
  clearTimeout(to)
  return !!to.refresh
}
module.exports = class Timer {
  constructor (ms, fn, ctx = null, interval = false) {
    this.ms = ms
    this.ontimeout = fn
    this.context = ctx
    this.interval = interval
    this.done = false

    this._timer = interval
      ? setInterval(callInterval, ms, this)
      : setTimeout(callTimeout, ms, this)
  }

  unref () {
    this._timer.unref()
  }

  ref () {
    this._timer.ref()
  }

  refresh () {
    if (this.done !== true) this._timer.refresh()
  }

  destroy () {
    this.done = true
    this.ontimeout = null
    if (this.interval) clearInterval(this._timer)
    else clearTimeout(this._timer)
  }

  static once (ms, fn, ctx) {
    return new this(ms, fn, ctx, false)
  }

  static on (ms, fn, ctx) {
    return new this(ms, fn, ctx, true)
  }
}

function callTimeout (self) {
  self.done = true
  self.ontimeout.call(self.context)
}

function callInterval (self) {
  self.ontimeout.call(self.context)
}
{
  "name": "timeout-refresh",
  "version": "2.0.1",
  "description": "Efficiently refresh a timer",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^16.0.4",
    "tape": "^5.5.2"
  },
  "browser": "./browser.js",
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/timeout-refresh.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/timeout-refresh/issues"
  },
  "homepage": "https://github.com/mafintosh/timeout-refresh"
}
require.addon = require('require-addon')

module.exports = require.addon('.', __filename)
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

const v4Seg = '(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])'
const v4Str = `(${v4Seg}[.]){3}${v4Seg}`
const IPv4Pattern = new RegExp(`^${v4Str}$`)

const v6Seg = '(?:[0-9a-fA-F]{1,4})'
const IPv6Pattern = new RegExp(
  '^(' +
    `(?:${v6Seg}:){7}(?:${v6Seg}|:)|` +
    `(?:${v6Seg}:){6}(?:${v4Str}|:${v6Seg}|:)|` +
    `(?:${v6Seg}:){5}(?::${v4Str}|(:${v6Seg}){1,2}|:)|` +
    `(?:${v6Seg}:){4}(?:(:${v6Seg}){0,1}:${v4Str}|(:${v6Seg}){1,3}|:)|` +
    `(?:${v6Seg}:){3}(?:(:${v6Seg}){0,2}:${v4Str}|(:${v6Seg}){1,4}|:)|` +
    `(?:${v6Seg}:){2}(?:(:${v6Seg}){0,3}:${v4Str}|(:${v6Seg}){1,5}|:)|` +
    `(?:${v6Seg}:){1}(?:(:${v6Seg}){0,4}:${v4Str}|(:${v6Seg}){1,6}|:)|` +
    `(?::((?::${v6Seg}){0,5}:${v4Str}|(?::${v6Seg}){1,7}|:))` +
    ')(%[0-9a-zA-Z-.:]{1,})?$'
)

const isIPv4 = (exports.isIPv4 = function isIPv4(host) {
  return IPv4Pattern.test(host)
})

const isIPv6 = (exports.isIPv6 = function isIPv6(host) {
  return IPv6Pattern.test(host)
})

exports.isIP = function isIP(host) {
  if (isIPv4(host)) return 4
  if (isIPv6(host)) return 6
  return 0
}
const events = require('events')
const b4a = require('b4a')
const binding = require('../binding')

module.exports = class NetworkInterfaces extends events.EventEmitter {
  constructor(udx) {
    super()

    this._handle = b4a.alloc(binding.sizeof_udx_napi_interface_event_t)
    this._watching = false
    this._destroying = null

    binding.udx_napi_interface_event_init(
      udx._handle,
      this._handle,
      this,
      this._onevent,
      this._onclose
    )

    this.interfaces = binding.udx_napi_interface_event_get_addrs(this._handle)
  }

  _onclose() {
    this.emit('close')
  }

  _onevent() {
    this.interfaces = binding.udx_napi_interface_event_get_addrs(this._handle)

    this.emit('change', this.interfaces)
  }

  watch() {
    if (this._watching) return this
    this._watching = true

    binding.udx_napi_interface_event_start(this._handle)

    return this
  }

  unwatch() {
    if (!this._watching) return this
    this._watching = false

    binding.udx_napi_interface_event_stop(this._handle)

    return this
  }

  async destroy() {
    if (this._destroying) return this._destroying
    this._destroying = events.once(this, 'close')

    binding.udx_napi_interface_event_close(this._handle)

    return this._destroying
  }

  [Symbol.iterator]() {
    return this.interfaces[Symbol.iterator]()
  }
}
const events = require('events')
const b4a = require('b4a')
const binding = require('../binding')
const ip = require('./ip')

module.exports = class UDXSocket extends events.EventEmitter {
  constructor(udx, opts = {}) {
    super()

    this.udx = udx

    this._handle = b4a.alloc(binding.sizeof_udx_napi_socket_t)
    this._inited = false
    this._host = null
    this._family = 0
    this._ipv6Only = opts.ipv6Only === true
    this._reuseAddress = opts.reuseAddress === true
    this._port = 0
    this._reqs = []
    this._free = []
    this._closing = null
    this._closed = false

    this._view64 = new BigUint64Array(
      this._handle.buffer,
      this._handle.byteOffset,
      this._handle.byteLength >> 3
    )

    this.streams = new Set()

    this.userData = null
  }

  get bound() {
    return this._port !== 0
  }

  get closing() {
    return this._closing !== null
  }

  get idle() {
    return this.streams.size === 0
  }

  get busy() {
    return this.streams.size > 0
  }

  get bytesTransmitted() {
    if (this._inited !== true) return 0
    return Number(this._view64[binding.offsetof_udx_socket_t_bytes_tx >> 3])
  }

  get packetsTransmitted() {
    if (this._inited !== true) return 0
    return Number(this._view64[binding.offsetof_udx_socket_t_packets_tx >> 3])
  }

  get bytesReceived() {
    if (this._inited !== true) return 0
    return Number(this._view64[binding.offsetof_udx_socket_t_bytes_rx >> 3])
  }

  get packetsReceived() {
    if (this._inited !== true) return 0
    return Number(this._view64[binding.offsetof_udx_socket_t_packets_rx >> 3])
  }

  get packetsDroppedByKernel() {
    if (this._inited !== true) return 0
    return Number(this._view64[binding.offsetof_udx_socket_t_packets_dropped_by_kernel >> 3])
  }

  toJSON() {
    return {
      bound: this.bound,
      closing: this.closing,
      streams: this.streams.size,
      address: this.address(),
      ipv6Only: this._ipv6Only,
      reuseAddress: this._reuseAddress,
      idle: this.idle,
      busy: this.busy
    }
  }

  _init() {
    if (this._inited) return

    binding.udx_napi_socket_init(
      this.udx._handle,
      this._handle,
      this,
      this._onsend,
      this._onmessage,
      this._onclose,
      this._reallocMessage
    )

    this._inited = true
  }

  _onsend(id, err) {
    const req = this._reqs[id]

    const onflush = req.onflush

    req.buffer = null
    req.onflush = null

    this._free.push(id)

    onflush(err >= 0)

    // gc the free list
    if (this._free.length >= 16 && this._free.length === this._reqs.length) {
      this._free = []
      this._reqs = []
    }
  }

  _onmessage(len, port, host, family) {
    this.emit('message', this.udx._consumeMessage(len), { host, family, port })
    return this.udx._buffer
  }

  _onclose() {
    this.emit('close')
  }

  _reallocMessage() {
    return this.udx._reallocMessage()
  }

  _onidle() {
    this.emit('idle')
  }

  _onbusy() {
    this.emit('busy')
  }

  _addStream(stream) {
    if (this.streams.has(stream)) return false
    this.streams.add(stream)
    if (this.streams.size === 1) this._onbusy()
    return true
  }

  _removeStream(stream) {
    if (!this.streams.has(stream)) return false
    this.streams.delete(stream)
    const closed = this._closeMaybe()
    if (this.idle && !closed) this._onidle()
    return true
  }

  address() {
    if (!this.bound) return null
    return { host: this._host, family: this._family, port: this._port }
  }

  bind(port, host) {
    if (this.bound) throw new Error('Already bound')
    if (this.closing) throw new Error('Socket is closed')

    if (!port) port = 0

    let flags = 0
    if (this._ipv6Only) flags |= binding.UV_UDP_IPV6ONLY
    if (this._reuseAddress) flags |= binding.UV_UDP_REUSEADDR

    let family

    if (host) {
      family = ip.isIP(host)
      if (!family) throw new Error(`${host} is not a valid IP address`)

      if (!this._inited) this._init()

      this._port = binding.udx_napi_socket_bind(this._handle, port, host, family, flags)
    } else {
      if (!this._inited) this._init()

      try {
        host = '::'
        family = 6
        this._port = binding.udx_napi_socket_bind(this._handle, port, host, family, flags)
      } catch {
        host = '0.0.0.0'
        family = 4
        this._port = binding.udx_napi_socket_bind(this._handle, port, host, family, flags)
      }
    }

    this._host = host
    this._family = family

    this.emit('listening')
  }

  async close() {
    if (this._closing) return this._closing
    this._closing = new Promise((resolve) => this.once('close', resolve))
    this._closeMaybe()
    return this._closing
  }

  _closeMaybe() {
    if (this._closed || this._closing === null) return this._closed

    if (!this._inited) {
      this._closed = true
      this.emit('close')
      return true
    }

    if (this.idle) {
      binding.udx_napi_socket_close(this._handle)
      this._closed = true
    }

    return this._closed
  }

  setTTL(ttl) {
    if (!this._inited) throw new Error('Socket not active')
    binding.udx_napi_socket_set_ttl(this._handle, ttl)
  }

  getRecvBufferSize() {
    if (!this._inited) throw new Error('Socket not active')
    return binding.udx_napi_socket_get_recv_buffer_size(this._handle)
  }

  setRecvBufferSize(size) {
    if (!this._inited) throw new Error('Socket not active')
    return binding.udx_napi_socket_set_recv_buffer_size(this._handle, size)
  }

  getSendBufferSize() {
    if (!this._inited) throw new Error('Socket not active')
    return binding.udx_napi_socket_get_send_buffer_size(this._handle)
  }

  setSendBufferSize(size) {
    if (!this._inited) throw new Error('Socket not active')
    return binding.udx_napi_socket_set_send_buffer_size(this._handle, size)
  }

  addMembership(group, ifaceAddress) {
    if (!this._inited) throw new Error('Socket not active')
    return binding.udx_napi_socket_set_membership(this._handle, group, ifaceAddress || '', true)
  }

  dropMembership(group, ifaceAddress) {
    if (!this._inited) throw new Error('Socket not active')
    return binding.udx_napi_socket_set_membership(this._handle, group, ifaceAddress || '', false)
  }

  async send(buffer, port, host, ttl) {
    if (this.closing) return false

    if (!host) host = '127.0.0.1'

    const family = ip.isIP(host)
    if (!family) throw new Error(`${host} is not a valid IP address`)

    if (!this.bound) this.bind(0)

    const id = this._allocSend()
    const req = this._reqs[id]

    req.buffer = buffer

    const promise = new Promise((resolve) => {
      req.onflush = resolve
    })

    binding.udx_napi_socket_send_ttl(
      this._handle,
      req.handle,
      id,
      buffer,
      port,
      host,
      family,
      ttl || 0
    )

    return promise
  }

  trySend(buffer, port, host, ttl) {
    if (this.closing) return

    if (!host) host = '127.0.0.1'

    const family = ip.isIP(host)
    if (!family) throw new Error(`${host} is not a valid IP address`)

    if (!this.bound) this.bind(0)

    const id = this._allocSend()
    const req = this._reqs[id]

    req.buffer = buffer
    req.onflush = noop

    binding.udx_napi_socket_send_ttl(
      this._handle,
      req.handle,
      id,
      buffer,
      port,
      host,
      family,
      ttl || 0
    )
  }

  _allocSend() {
    if (this._free.length > 0) return this._free.pop()
    const handle = b4a.allocUnsafe(binding.sizeof_udx_socket_send_t)
    return this._reqs.push({ handle, buffer: null, onflush: null }) - 1
  }
}

function noop() {}
const streamx = require('streamx')
const b4a = require('b4a')
const binding = require('../binding')
const ip = require('./ip')

const MAX_PACKET = 2048
const BUFFER_SIZE = 65536 + MAX_PACKET

module.exports = class UDXStream extends streamx.Duplex {
  constructor(udx, id, opts = {}) {
    super({ mapWritable: toBuffer, eagerOpen: true })

    this.udx = udx
    this.socket = null

    this._handle = b4a.alloc(binding.sizeof_udx_napi_stream_t)
    this._view = new Uint32Array(
      this._handle.buffer,
      this._handle.byteOffset,
      this._handle.byteLength >> 2
    )
    this._view16 = new Uint16Array(
      this._handle.buffer,
      this._handle.byteOffset,
      this._handle.byteLength >> 1
    )
    this._view64 = new BigUint64Array(
      this._handle.buffer,
      this._handle.byteOffset,
      this._handle.byteLength >> 3
    )

    this._wreqs = []
    this._wfree = []

    this._sreqs = []
    this._sfree = []
    this._closed = false

    this._flushing = 0
    this._flushes = []

    this._buffer = null
    this._reallocData()

    this._onwrite = null
    this._ondestroy = null
    this._firewall = opts.firewall || firewallAll

    this._remoteChanging = null
    this._previousSocket = null

    this.id = id
    this.remoteId = 0
    this.remoteHost = null
    this.remoteFamily = 0
    this.remotePort = 0

    this.userData = null

    binding.udx_napi_stream_init(
      this.udx._handle,
      this._handle,
      id,
      opts.framed ? 1 : 0,
      this,
      this._ondata,
      this._onend,
      this._ondrain,
      this._onack,
      this._onsend,
      this._onmessage,
      this._onclose,
      this._onfirewall,
      this._onremotechanged,
      this._reallocData,
      this._reallocMessage
    )

    if (opts.seq) binding.udx_napi_stream_set_seq(this._handle, opts.seq)

    binding.udx_napi_stream_recv_start(this._handle, this._buffer)
  }

  get connected() {
    return this.socket !== null
  }

  get mtu() {
    return this._view16[binding.offsetof_udx_stream_t_mtu >> 1]
  }

  get rtt() {
    return this._view[binding.offsetof_udx_stream_t_srtt >> 2]
  }

  get cwnd() {
    return this._view[binding.offsetof_udx_stream_t_cwnd >> 2]
  }

  get rtoCount() {
    return this._view16[binding.offsetof_udx_stream_t_rto_count >> 1]
  }

  get retransmits() {
    return this._view16[binding.offsetof_udx_stream_t_retransmit_count >> 1]
  }

  get bbrState() {
    const view = new Uint8Array(
      this._handle.buffer,
      this._handle.byteOffset,
      this._handle.byteLength
    )
    return view[binding.offsetof_udx_stream_t_bbr_state]
  }

  get bbrBandwidth() {
    return binding.udx_napi_stream_get_bw(this._handle)
  }

  get fastRecoveries() {
    return this._view16[binding.offsetof_udx_stream_t_fast_recovery_count >> 1]
  }

  get inflight() {
    return this._view[binding.offsetof_udx_stream_t_inflight >> 2]
  }

  get bytesTransmitted() {
    return Number(this._view64[binding.offsetof_udx_stream_t_bytes_tx >> 3])
  }

  get packetsTransmitted() {
    return Number(this._view64[binding.offsetof_udx_stream_t_packets_tx >> 3])
  }

  get bytesReceived() {
    return Number(this._view64[binding.offsetof_udx_stream_t_bytes_rx >> 3])
  }

  get packetsReceived() {
    return Number(this._view64[binding.offsetof_udx_stream_t_packets_rx >> 3])
  }

  get localHost() {
    return this.socket ? this.socket.address().host : null
  }

  get localFamily() {
    return this.socket ? this.socket.address().family : 0
  }

  get localPort() {
    return this.socket ? this.socket.address().port : 0
  }

  setInteractive(bool) {
    if (!this._closed) return
    binding.udx_napi_stream_set_mode(this._handle, bool ? 0 : 1)
  }

  connect(socket, remoteId, port, host, opts = {}) {
    if (this._closed) return

    if (this.connected) throw new Error('Already connected')
    if (socket.closing) throw new Error('Socket is closed')

    if (typeof host === 'object') {
      opts = host
      host = null
    }

    if (!host) host = '127.0.0.1'

    const family = ip.isIP(host)
    if (!family) throw new Error(`${host} is not a valid IP address`)
    if (!(port > 0 && port < 65536)) throw new Error(`${port} is not a valid port`)

    if (!socket.bound) socket.bind(0)

    this.remoteId = remoteId
    this.remotePort = port
    this.remoteHost = host
    this.remoteFamily = family
    this.socket = socket

    if (opts.ack) binding.udx_napi_stream_set_ack(this._handle, opts.ack)

    binding.udx_napi_stream_connect(this._handle, socket._handle, remoteId, port, host, family)

    this.socket._addStream(this)

    this.emit('connect')
  }

  changeRemote(socket, remoteId, port, host) {
    if (this._remoteChanging) throw new Error('Remote already changing')

    if (!this.connected) throw new Error('Not yet connected')
    if (socket.closing) throw new Error('Socket is closed')

    if (this.socket.udx !== socket.udx) {
      throw new Error('Cannot change to a socket on another UDX instance')
    }

    if (!host) host = '127.0.0.1'

    const family = ip.isIP(host)
    if (!family) throw new Error(`${host} is not a valid IP address`)
    if (!(port > 0 && port < 65536)) throw new Error(`${port} is not a valid port`)

    if (this.socket !== socket) this._previousSocket = this.socket

    this.remoteId = remoteId
    this.remotePort = port
    this.remoteHost = host
    this.remoteFamily = family
    this.socket = socket

    this._remoteChanging = new Promise((resolve, reject) => {
      const onchanged = () => {
        this.off('close', onclose)
        resolve()
      }

      const onclose = () => {
        this.off('remote-changed', onchanged)
        reject(new Error('Stream is closed'))
      }

      this.once('remote-changed', onchanged).once('close', onclose)
    })

    binding.udx_napi_stream_change_remote(
      this._handle,
      socket._handle,
      remoteId,
      port,
      host,
      family
    )

    this.socket._addStream(this)

    return this._remoteChanging
  }

  relayTo(destination) {
    if (this._closed) return

    binding.udx_napi_stream_relay_to(this._handle, destination._handle)
  }

  async send(buffer) {
    if (!this.connected || this._closed) return false

    const id = this._allocSend()
    const req = this._sreqs[id]

    req.buffer = buffer

    const promise = new Promise((resolve) => {
      req.onflush = resolve
    })

    binding.udx_napi_stream_send(this._handle, req.handle, id, buffer)

    return promise
  }

  trySend(buffer) {
    if (!this.connected || this._closed) return

    const id = this._allocSend()
    const req = this._sreqs[id]

    req.buffer = buffer
    req.onflush = noop

    binding.udx_napi_stream_send(this._handle, req.handle, id, buffer)
  }

  async flush() {
    if ((await streamx.Writable.drained(this)) === false) return false
    if (this.destroying) return false

    const missing = this._wreqs.length - this._wfree.length
    if (missing === 0) return true

    return new Promise((resolve) => {
      this._flushes.push({ flush: this._flushing++, missing, resolve })
    })
  }

  toJSON() {
    return {
      id: this.id,
      connected: this.connected,
      destroying: this.destroying,
      destroyed: this.destroyed,
      remoteId: this.remoteId,
      remoteHost: this.remoteHost,
      remoteFamily: this.remoteFamily,
      remotePort: this.remotePort,
      mtu: this.mtu,
      rtt: this.rtt,
      cwnd: this.cwnd,
      inflight: this.inflight,
      socket: this.socket ? this.socket.toJSON() : null
    }
  }

  _read(cb) {
    cb(null)
  }

  _writeContinue(err) {
    if (this._onwrite === null) return
    const cb = this._onwrite
    this._onwrite = null
    cb(err)
  }

  _destroyContinue(err) {
    if (this._ondestroy === null) return
    const cb = this._ondestroy
    this._ondestroy = null
    cb(err)
  }

  _writev(buffers, cb) {
    if (!this.connected) {
      throw customError('Writing while not connected not currently supported', 'ERR_ASSERTION')
    }

    let drained = true

    if (buffers.length === 1) {
      const id = this._allocWrite(1)
      const req = this._wreqs[id]

      req.flush = this._flushing
      req.buffer = buffers[0]

      drained = binding.udx_napi_stream_write(this._handle, req.handle, id, req.buffer) !== 0
    } else {
      const id = this._allocWrite(nextBatchSize(buffers.length))
      const req = this._wreqs[id]

      req.flush = this._flushing
      req.buffers = buffers

      drained = binding.udx_napi_stream_writev(this._handle, req.handle, id, req.buffers) !== 0
    }

    if (drained) cb(null)
    else this._onwrite = cb
  }

  _final(cb) {
    const id = this._allocWrite(1)
    const req = this._wreqs[id]

    req.flush = this._flushes
    req.buffer = b4a.allocUnsafe(0)

    const drained =
      binding.udx_napi_stream_write_end(this._handle, req.handle, id, req.buffer) !== 0

    if (drained) cb(null)
    else this._onwrite = cb
  }

  _predestroy() {
    if (!this._closed) binding.udx_napi_stream_destroy(this._handle)
    this._closed = true
    this._writeContinue(null)
  }

  _destroy(cb) {
    if (this.connected) this._ondestroy = cb
    else cb(null)
  }

  _ondata(read) {
    this.push(this._consumeData(read))
    return this._buffer
  }

  _onend(read) {
    if (read > 0) this.push(this._consumeData(read))
    this.push(null)
  }

  _ondrain() {
    this._writeContinue(null)
  }

  _flushAck(flush) {
    for (let i = this._flushes.length - 1; i >= 0; i--) {
      const f = this._flushes[i]
      if (f.flush < flush) break
      f.missing--
    }

    while (this._flushes.length > 0 && this._flushes[0].missing === 0) {
      this._flushes.shift().resolve(true)
    }
  }

  _onack(id) {
    const req = this._wreqs[id]

    req.buffers = req.buffer = null
    this._wfree.push(id)

    if (this._flushes.length > 0) this._flushAck(req.flush)

    // gc the free list
    if (this._wfree.length >= 64 && this._wfree.length === this._wreqs.length) {
      this._wfree = []
      this._wreqs = []
    }
  }

  _onsend(id, err) {
    const req = this._sreqs[id]

    const onflush = req.onflush

    req.buffer = null
    req.onflush = null

    this._sfree.push(id)

    onflush(err >= 0)

    // gc the free list
    if (this._sfree.length >= 16 && this._sfree.length === this._sreqs.length) {
      this._sfree = []
      this._sreqs = []
    }
  }

  _onmessage(len) {
    this.emit('message', this.udx._consumeMessage(len))
    return this.udx._buffer
  }

  _onclose(err) {
    this._closed = true

    if (this.socket) {
      this.socket._removeStream(this)
      this.socket = null
    }

    if (this._previousSocket) {
      this._previousSocket._removeStream(this)
      this._previousSocket = null
    }

    // no error, we don't need to do anything
    if (!err) return this._destroyContinue(null)

    if (this._ondestroy === null) this.destroy(err)
    else this._destroyContinue(err)
  }

  _onfirewall(socket, port, host, family) {
    if (port <= 0 || port > 65535) return 1
    return this._firewall(socket, port, host, family) ? 1 : 0
  }

  _onremotechanged() {
    if (this._previousSocket) {
      this._previousSocket._removeStream(this)
      this._previousSocket = null
    }

    this._remoteChanging = null
    this.emit('remote-changed')
  }

  _consumeData(len) {
    const next = this._buffer.subarray(0, len)
    this._buffer = this._buffer.subarray(len)
    if (this._buffer.byteLength < MAX_PACKET) this._reallocData()
    return next
  }

  _reallocData() {
    this._buffer = b4a.allocUnsafe(BUFFER_SIZE)
    return this._buffer
  }

  _reallocMessage() {
    return this.udx._reallocMessage()
  }

  _allocWrite(size) {
    if (this._wfree.length === 0) {
      const handle = b4a.allocUnsafe(binding.udx_napi_stream_write_sizeof(size))
      return (
        this._wreqs.push({
          handle,
          size,
          buffers: null,
          buffer: null,
          flush: 0
        }) - 1
      )
    }

    const free = this._wfree.pop()
    if (size === 1) return free

    const next = this._wreqs[free]
    if (next.size < size) {
      next.handle = b4a.allocUnsafe(binding.udx_napi_stream_write_sizeof(size))
      next.size = size
    }

    return free
  }

  _allocSend() {
    if (this._sfree.length > 0) return this._sfree.pop()
    const handle = b4a.allocUnsafe(binding.sizeof_udx_stream_send_t)
    return this._sreqs.push({ handle, buffer: null, resolve: null, reject: null }) - 1
  }
}

function noop() {}

function toBuffer(data) {
  return typeof data === 'string' ? b4a.from(data) : data
}

function firewallAll(socket, port, host) {
  return true
}

function customError(message, code) {
  const error = new Error(message)
  error.code = code
  return error
}

function nextBatchSize(n) {
  // try to coerce the the writevs into sameish size
  if (n === 1) return 1
  // group all < 8 to the same size, low mem overhead but save some small allocs
  if (n < 8) return 8
  if (n < 16) return 16
  if (n < 32) return 32
  if (n < 64) return 64
  return n
}
const b4a = require('b4a')
const binding = require('../binding')
const ip = require('./ip')
const Socket = require('./socket')
const Stream = require('./stream')
const NetworkInterfaces = require('./network-interfaces')

const MAX_MESSAGE = 4096
const BUFFER_SIZE = 65536 + MAX_MESSAGE

module.exports = class UDX {
  constructor() {
    this._handle = b4a.alloc(binding.sizeof_udx_napi_t)
    this._watchers = new Set()
    this._view64 = new BigUint64Array(
      this._handle.buffer,
      this._handle.byteOffset,
      this._handle.byteLength >> 3
    )

    this._buffer = null
    this._reallocMessage()

    binding.udx_napi_init(this._handle, this._buffer)
  }

  static isIPv4(host) {
    return ip.isIPv4(host)
  }

  static isIPv6(host) {
    return ip.isIPv6(host)
  }

  static isIP(host) {
    return ip.isIP(host)
  }

  get bytesTransmitted() {
    return Number(this._view64[binding.offsetof_udx_t_bytes_tx >> 3])
  }

  get packetsTransmitted() {
    return Number(this._view64[binding.offsetof_udx_t_packets_tx >> 3])
  }

  get bytesReceived() {
    return Number(this._view64[binding.offsetof_udx_t_bytes_rx >> 3])
  }

  get packetsReceived() {
    return Number(this._view64[binding.offsetof_udx_t_packets_rx >> 3])
  }

  get packetsDroppedByKernel() {
    return Number(this._view64[binding.offsetof_udx_t_packets_dropped_by_kernel >> 3])
  }

  _consumeMessage(len) {
    const next = this._buffer.subarray(0, len)
    this._buffer = this._buffer.subarray(len)
    if (this._buffer.byteLength < MAX_MESSAGE) this._reallocMessage()
    return next
  }

  _reallocMessage() {
    // TODO: move reallocation to native
    this._buffer = b4a.allocUnsafe(BUFFER_SIZE)
    return this._buffer
  }

  createSocket(opts) {
    return new Socket(this, opts)
  }

  createStream(id, opts) {
    return new Stream(this, id, opts)
  }

  networkInterfaces() {
    let [watcher = null] = this._watchers
    if (watcher) return watcher.interfaces

    watcher = new NetworkInterfaces(this)
    watcher.destroy()

    return watcher.interfaces
  }

  watchNetworkInterfaces(onchange) {
    const watcher = new NetworkInterfaces(this)

    this._watchers.add(watcher)
    watcher.on('close', () => {
      this._watchers.delete(watcher)
    })

    if (onchange) watcher.on('change', onchange)

    return watcher.watch()
  }

  async lookup(host, opts = {}) {
    const { family = 0 } = opts

    const req = b4a.alloc(binding.sizeof_udx_napi_lookup_t)
    const ctx = {
      req,
      resolve: null,
      reject: null
    }

    const promise = new Promise((resolve, reject) => {
      ctx.resolve = resolve
      ctx.reject = reject
    })

    binding.udx_napi_lookup(this._handle, req, host, family, ctx, onlookup)

    return promise
  }
}

function onlookup(err, host, family) {
  if (err) this.reject(err)
  else this.resolve({ host, family })
}
{
  "name": "udx-native",
  "version": "1.20.7",
  "description": "udx is reliable, multiplexed, and congestion-controlled streams over udp",
  "main": "lib/udx.js",
  "files": [
    "lib",
    "prebuilds",
    "binding.cc",
    "binding.js",
    "CMakeLists.txt"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "addon": true,
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node --coverage test/*.js",
    "test:bare": "brittle-bare --coverage test/*.js",
    "test:all": "brittle test/*.js test/slow/*.js",
    "test:generate": "brittle -r test/all.js test/*.js",
    "bench": "brittle test/bench/*.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/udx-native.git"
  },
  "keywords": [
    "tcp",
    "udp",
    "stream",
    "reliable"
  ],
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/udx-native/issues"
  },
  "homepage": "https://github.com/holepunchto/udx-native#readme",
  "engines": {
    "bare": ">=1.17.4"
  },
  "dependencies": {
    "b4a": "^1.5.0",
    "bare-events": "^2.2.0",
    "require-addon": "^1.1.0",
    "streamx": "^2.22.0"
  },
  "devDependencies": {
    "bare-compat-napi": "^1.3.0",
    "brittle": "^3.1.0",
    "cmake-bare": "^1.1.10",
    "cmake-fetch": "^1.0.1",
    "cmake-napi": "^1.0.5",
    "is-ci": "^3.0.1",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "tiny-byte-size": "^1.1.0"
  }
}
exports.add = add
exports.has = has
exports.remove = remove
exports.swap = swap

function add (list, item) {
  if (has(list, item)) return item
  item._index = list.length
  list.push(item)
  return item
}

function has (list, item) {
  return item._index < list.length && list[item._index] === item
}

function remove (list, item) {
  if (!has(list, item)) return null

  var last = list.pop()
  if (last !== item) {
    list[item._index] = last
    last._index = item._index
  }

  return item
}

function swap (list, a, b) {
  if (!has(list, a) || !has(list, b)) return
  var tmp = a._index
  a._index = b._index
  list[a._index] = a
  b._index = tmp
  list[b._index] = b
}
{
  "name": "unordered-set",
  "version": "2.0.1",
  "description": "A couple of functions that make it easy to maintain an unordered set as an array in an efficient way",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^6.0.4",
    "tape": "^4.4.0"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/unordered-set.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/unordered-set/issues"
  },
  "homepage": "https://github.com/mafintosh/unordered-set"
}
const b4a = require('b4a')

unslab.all = all
unslab.is = is

module.exports = unslab

function unslab (buf) {
  if (buf === null || buf.buffer.byteLength === buf.byteLength) return buf
  const copy = b4a.allocUnsafeSlow(buf.byteLength)
  copy.set(buf, 0)
  return copy
}

function is (buf) {
  return buf.buffer.byteLength !== buf.byteLength
}

function all (list) {
  let size = 0
  for (let i = 0; i < list.length; i++) {
    const buf = list[i]
    size += buf === null || buf.buffer.byteLength === buf.byteLength ? 0 : buf.byteLength
  }

  const copy = b4a.allocUnsafeSlow(size)
  const result = new Array(list.length)

  let offset = 0
  for (let i = 0; i < list.length; i++) {
    let buf = list[i]

    if (buf !== null && buf.buffer.byteLength !== buf.byteLength) {
      copy.set(buf, offset)
      buf = copy.subarray(offset, offset += buf.byteLength)
    }

    result[i] = buf
  }

  return result
}
{
  "name": "unslab",
  "version": "1.3.0",
  "description": "Unslab some slab'ed buffers",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.6.6"
  },
  "devDependencies": {
    "brittle": "^3.5.2",
    "standard": "^17.1.0"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/unslab.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/unslab/issues"
  },
  "homepage": "https://github.com/holepunchto/unslab"
}
const { runtime, platform, arch, version } =
  typeof Bare !== 'undefined'
    ? {
        runtime: 'bare',
        platform: global.Bare.platform,
        arch: global.Bare.arch,
        version: global.Bare.version
      }
    : typeof process !== 'undefined'
      ? {
          runtime: 'node',
          platform: global.process.platform,
          arch: global.process.arch,
          version: global.process.version
        }
      : typeof Window !== 'undefined'
        ? { runtime: 'browser', platform: 'unknown', arch: 'unknown', version: 'unknown' }
        : { runtime: 'unknown', platform: 'unknown', arch: 'unknown', version: 'unknown' }

exports.runtime = runtime
exports.version = version
exports.platform = platform
exports.arch = arch
exports.isBare = runtime === 'bare'
exports.isBareKit = exports.isBare && typeof BareKit !== 'undefined'
exports.isPear = typeof Pear !== 'undefined'
exports.isNode = runtime === 'node'
exports.isBrowser = runtime === 'browser'
exports.isWindows = platform === 'win32'
exports.isLinux = platform === 'linux'
exports.isMac = platform === 'darwin'
exports.isIOS = platform === 'ios' || platform === 'ios-simulator'
exports.isAndroid = platform === 'android'
exports.isElectron = typeof process !== 'undefined' && !!global.process.versions?.electron
exports.isElectronRenderer = exports.isElectron && global.process.type === 'renderer'
exports.isElectronWorker = exports.isElectron && global.process.type === 'worker'
{
  "name": "which-runtime",
  "version": "1.4.0",
  "description": "Detect if you are in Bare or Node and which os etc",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte .",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/which-runtime.git"
  },
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/which-runtime/issues"
  },
  "homepage": "https://github.com/holepunchto/which-runtime",
  "devDependencies": {
    "brittle": "^3.0.0",
    "lunte": "^1.4.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = class MaxCache {
  constructor ({ maxSize, maxAge, createMap, ongc }) {
    this.maxSize = maxSize
    this.maxAge = maxAge
    this.ongc = ongc || null

    this._createMap = createMap || defaultCreateMap
    this._latest = this._createMap()
    this._oldest = this._createMap()
    this._retained = this._createMap()
    this._gced = false
    this._interval = null

    if (this.maxAge > 0 && this.maxAge < Infinity) {
      const tick = Math.ceil(2 / 3 * this.maxAge)
      this._interval = setInterval(this._gcAuto.bind(this), tick)
      if (this._interval.unref) this._interval.unref()
    }
  }

  * [Symbol.iterator] () {
    for (const it of [this._latest, this._oldest, this._retained]) {
      yield * it
    }
  }

  * keys () {
    for (const it of [this._latest, this._oldest, this._retained]) {
      yield * it.keys()
    }
  }

  * values () {
    for (const it of [this._latest, this._oldest, this._retained]) {
      yield * it.values()
    }
  }

  destroy () {
    this.clear()
    clearInterval(this._interval)
    this._interval = null
  }

  clear () {
    this._gced = true
    this._latest.clear()
    this._oldest.clear()
    this._retained.clear()
  }

  set (k, v) {
    if (this._retained.has(k)) return this
    this._latest.set(k, v)
    this._oldest.delete(k) || this._retained.delete(k)
    if (this._latest.size >= this.maxSize) this._gc()
    return this
  }

  retain (k, v) {
    this._retained.set(k, v)
    this._latest.delete(k) || this._oldest.delete(k)
    return this
  }

  delete (k) {
    return this._latest.delete(k) || this._oldest.delete(k) || this._retained.delete(k)
  }

  has (k) {
    return this._latest.has(k) || this._oldest.has(k) || this._retained.has(k)
  }

  get (k) {
    if (this._latest.has(k)) {
      return this._latest.get(k)
    }

    if (this._oldest.has(k)) {
      const v = this._oldest.get(k)
      this._latest.set(k, v)
      this._oldest.delete(k)
      return v
    }

    if (this._retained.has(k)) {
      return this._retained.get(k)
    }

    return null
  }

  _gcAuto () {
    if (!this._gced) this._gc()
    this._gced = false
  }

  _gc () {
    this._gced = true
    if (this.ongc !== null && this._oldest.size > 0) this.ongc(this._oldest)
    this._oldest = this._latest
    this._latest = this._createMap()
  }
}

function defaultCreateMap () {
  return new Map()
}
{
  "name": "xache",
  "version": "1.2.1",
  "description": "Yet another auto expiring, max sizable cache",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "devDependencies": {
    "brittle": "^3.3.2",
    "standard": "^17.1.0"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/xache.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/xache/issues"
  },
  "homepage": "https://github.com/mafintosh/xache"
}
const b4a = require('b4a')

const ALPHABET = 'ybndrfg8ejkmcpqxot1uwisza345h769'
const MIN = 0x31 // 1
const MAX = 0x7a // z
const REVERSE = new Int8Array(1 + MAX - MIN)

REVERSE.fill(-1)

for (let i = 0; i < ALPHABET.length; i++) {
  const v = ALPHABET.charCodeAt(i) - MIN
  REVERSE[v] = i
}

exports.encode = encode
exports.decode = decode
exports.ALPHABET = ALPHABET

function decode (s, out) {
  let pb = 0
  let ps = 0

  const r = s.length & 7
  const q = (s.length - r) / 8

  if (!out) out = b4a.allocUnsafe(Math.ceil(s.length * 5 / 8))

  // 0 5 2 7 4 1 6 3 (+5 mod 8)
  for (let i = 0; i < q; i++) {
    const a = quintet(s, ps++)
    const b = quintet(s, ps++)
    const c = quintet(s, ps++)
    const d = quintet(s, ps++)
    const e = quintet(s, ps++)
    const f = quintet(s, ps++)
    const g = quintet(s, ps++)
    const h = quintet(s, ps++)

    out[pb++] = (a << 3) | (b >>> 2)
    out[pb++] = ((b & 0b11) << 6) | (c << 1) | (d >>> 4)
    out[pb++] = ((d & 0b1111) << 4) | (e >>> 1)
    out[pb++] = ((e & 0b1) << 7) | (f << 2) | (g >>> 3)
    out[pb++] = ((g & 0b111) << 5) | h
  }

  if (r === 0) return out.subarray(0, pb)

  const a = quintet(s, ps++)
  const b = quintet(s, ps++)

  out[pb++] = (a << 3) | (b >>> 2)

  if (r <= 2) return out.subarray(0, pb)

  const c = quintet(s, ps++)
  const d = quintet(s, ps++)

  out[pb++] = ((b & 0b11) << 6) | (c << 1) | (d >>> 4)

  if (r <= 4) return out.subarray(0, pb)

  const e = quintet(s, ps++)

  out[pb++] = ((d & 0b1111) << 4) | (e >>> 1)

  if (r <= 5) return out.subarray(0, pb)

  const f = quintet(s, ps++)
  const g = quintet(s, ps++)

  out[pb++] = ((e & 0b1) << 7) | (f << 2) | (g >>> 3)

  if (r <= 7) return out.subarray(0, pb)

  const h = quintet(s, ps++)

  out[pb++] = ((g & 0b111) << 5) | h

  return out.subarray(0, pb)
}

function encode (buf) {
  if (typeof buf === 'string') buf = b4a.from(buf)

  const max = buf.byteLength * 8

  let s = ''

  for (let p = 0; p < max; p += 5) {
    const i = p >>> 3
    const j = p & 7

    if (j <= 3) {
      s += ALPHABET[(buf[i] >>> (3 - j)) & 0b11111]
      continue
    }

    const of = j - 3
    const h = (buf[i] << of) & 0b11111
    const l = (i >= buf.byteLength ? 0 : buf[i + 1]) >>> (8 - of)

    s += ALPHABET[h | l]
  }

  return s
}

function quintet (s, i) {
  if (i > s.length) {
    return 0
  }

  const v = s.charCodeAt(i)

  if (v < MIN || v > MAX) {
    throw Error('Invalid character in base32 input: "' + s[i] + '" at position ' + i)
  }

  const bits = REVERSE[v - MIN]

  if (bits === -1) {
    throw Error('Invalid character in base32 input: "' + s[i] + '" at position ' + i)
  }

  return bits
}
{
  "name": "z32",
  "version": "1.1.0",
  "description": "Encode & decode z-base32",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.5.3"
  },
  "devDependencies": {
    "base-x": "^4.0.0",
    "base32": "0.0.7",
    "brittle": "^3.1.3",
    "nanobench": "^3.0.0",
    "rfc4648": "^1.5.2",
    "standard": "^17.0.0"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/z32.git"
  },
  "scripts": {
    "test": "standard && brittle test.js",
    "bench": "node benchmark.js"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/z32/issues"
  },
  "homepage": "https://github.com/mafintosh/z32"
}
{
  "name": "atproto-room",
  "version": "0.2.22",
  "description": "Attestation-gated, encrypted multi-writer room engine — StateBase (keet-model admission) + Lease + signer + RepoBase + LabelBase/LabelRoom + serve-membrane. Extracted from hyper-proto-peer; consumed by the atproto peer (repo devices) and the co-authored labeler.",
  "type": "module",
  "main": "index.js",
  "scripts": {
    "test": "bare test/all.js",
    "test:units": "node test/label-base.test.mjs && node test/label-signer.test.mjs && node test/label-room.test.mjs",
    "postinstall": "node scripts/bare-deps.mjs"
  },
  "dependencies": {
    "@ipld/dag-cbor": "^9.2.1",
    "atproto-identity": "file:../atproto-identity",
    "atproto-repo": "file:../atproto-repo",
    "atproto-store": "file:../atproto-store",
    "autobase": "7.28.1",
    "b4a": "^1.6.0",
    "bare-fs": "^4.7.1",
    "bare-path": "^3.0.1",
    "bare-process": "^4.2.1",
    "blind-pairing": "^2.3.1",
    "compact-encoding": "^2.16.0",
    "corestore": "^7.10.0",
    "hypercore": "^11.33.1",
    "hypercore-crypto": "^3.0.0",
    "hyperdb": "^6.7.0",
    "hyperdispatch": "^1.6.0",
    "hyperschema": "^1.21.0",
    "hyperswarm": "^4.17.0",
    "keet-identity-key": "^3.2.0",
    "multiformats": "^13.4.2",
    "protomux": "^3.11.0",
    "protomux-rpc": "^1.10.0"
  },
  "devDependencies": {
    "@hyperswarm/testnet": "^3.1.4",
    "@noble/curves": "^1.6.0",
    "brittle": "^4.0.2"
  }
}
// The store package owns the Holepunch substrate — so the corestore dependency resolves
// here (store/node_modules), and higher layers (pds) compose store abstractions without
// reaching for corestore directly.

import Corestore from 'corestore'

// A dir path (or an existing Corestore) -> a Corestore. Idempotent on an instance.
export function openCorestore (storage) {
  return isCorestore(storage) ? storage : new Corestore(storage)
}

// ⛔ NOT `instanceof`. That compares against ONE module instance's class object, and a nested
// node_modules tree routinely yields two copies of corestore — which is what bare-pack ships to the
// phone (…/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/corestore
// alongside the daemon's own). A store built by copy A then fails `instanceof` against copy B, and every
// discriminator here reads that as "not a store, therefore a PATH", so Corestore tried to path.join an
// OBJECT and the node died with `Cannot read properties of undefined (reading 'length')` — a message
// that names a JS idiom and no cause (hyper-social #40).
//
// It cannot reproduce on a workstation, where the tree is deduped to one copy. The environments differ
// in their module graph, not their code, so identity is the wrong question: a store is what it DOES.
// `get` + `namespace` + `replicate` are the surface every caller here uses and nothing else implements.
// The instanceof check stays as a fast path for the common single-copy case.
export function isCorestore (x) {
  if (!x || typeof x !== 'object') return false
  if (x instanceof Corestore) return true
  return typeof x.get === 'function' && typeof x.namespace === 'function' && typeof x.replicate === 'function'
}

export { Corestore }
// Firehose #commit frame — the atproto com.atproto.sync.subscribeRepos wire format.
//
// A frame = dag-cbor({t:'#commit', op:1})  ++  dag-cbor(body). Built to match millipds
// (repo_ops.py apply_writes) field-for-field. `seq` and `time` are firehose-server
// state supplied by the caller. `blocks` is a CAR (root = the new commit) of the
// changed blocks.

import * as dagCbor from '@ipld/dag-cbor'
import { writeCar } from 'atproto-repo/lib/repo.js'
import { commitCid } from 'atproto-repo/lib/commit.js'

// subscribeRepos frame = dag-cbor(header {t, op:1}) ++ dag-cbor(body). Each header is
// a constant byte prefix (dag-cbor canonicalises map order), so we emit/detect by it.
export const COMMIT_HEADER = dagCbor.encode({ t: '#commit', op: 1 })
export const IDENTITY_HEADER = dagCbor.encode({ t: '#identity', op: 1 })
export const ACCOUNT_HEADER = dagCbor.encode({ t: '#account', op: 1 })
export const SYNC_HEADER = dagCbor.encode({ t: '#sync', op: 1 })

function frame (header, body) {
  const bodyBytes = dagCbor.encode(body)
  const out = new Uint8Array(header.length + bodyBytes.length)
  out.set(header, 0)
  out.set(bodyBytes, header.length)
  return out
}

// Assemble a #commit frame from a RepoManager.applyWrite() result.
export async function commitFrame (write, { seq, time }) {
  const carBytes = await writeCar(write.commitCid, [write.commitBlock, ...write.newBlocks])
  return frame(COMMIT_HEADER, {
    ops: write.ops,
    seq,
    rev: write.rev,
    since: write.since,
    prev: null,
    repo: write.signedCommit.did,
    time,
    blobs: [],
    blocks: carBytes,
    commit: write.commitCid,
    rebase: false,
    tooBig: false,
    prevData: write.prevData
  })
}

// #identity — tells a relay a repo's handle/DID binding (needed for discovery).
export function identityFrame ({ seq, did, handle, time }) {
  const body = { seq, did, time }
  if (handle) body.handle = handle
  return frame(IDENTITY_HEADER, body)
}

// #account — repo hosting status (active true = "this PDS hosts this repo").
export function accountFrame ({ seq, did, active = true, status, time }) {
  const body = { seq, did, time, active }
  if (status) body.status = status
  return frame(ACCOUNT_HEADER, body)
}

// #sync (Sync 1.1) — tells a relay to RE-BASELINE the repo to `signedCommit` (re-anchor via
// getRepo) instead of applying incremental deltas. This is the sanctioned signal for a repo
// whose commit chain is discontinuous vs the relay's last-known state (e.g. a custodial→
// self-custody migration that re-authored the repo). `blocks` is a CAR carrying ONLY the
// commit block (root = its CID), ≤10KB. `rev`/`did` MUST match the commit object.
export async function syncFrame ({ seq, did, signedCommit, time }) {
  const cid = commitCid(signedCommit)
  const blocks = await writeCar(cid, [{ cid, bytes: dagCbor.encode(signedCommit) }])
  return frame(SYNC_HEADER, { seq, did, blocks, rev: signedCommit.rev, time })
}

const HEADERS = [['#commit', COMMIT_HEADER], ['#identity', IDENTITY_HEADER], ['#account', ACCOUNT_HEADER], ['#sync', SYNC_HEADER]]

// Re-stamp a frame's `seq` (relay egress): a relay aggregates many PDS firehoses and MUST
// present its own monotonic seq in each frame (the cursor contract). Decodes, replaces
// body.seq, re-encodes with the same header. Unknown frames pass through unchanged.
export function restampFrame (frameBytes, seq) {
  const d = decodeFrame(frameBytes)
  if (!d) return frameBytes
  const header = d.t === '#commit' ? COMMIT_HEADER : d.t === '#identity' ? IDENTITY_HEADER : d.t === '#account' ? ACCOUNT_HEADER : SYNC_HEADER
  d.body.seq = seq
  const bodyBytes = dagCbor.encode(d.body)
  const out = new Uint8Array(header.length + bodyBytes.length)
  out.set(header, 0)
  out.set(bodyBytes, header.length)
  return out
}

// Split + decode ANY known subscribeRepos frame → { t, body } (null if unknown).
export function decodeFrame (frameBytes) {
  for (const [t, header] of HEADERS) {
    if (frameBytes.length >= header.length &&
        Buffer.from(frameBytes.subarray(0, header.length)).equals(Buffer.from(header))) {
      return { t, body: dagCbor.decode(frameBytes.subarray(header.length)) }
    }
  }
  return null
}

// Split + decode a #commit frame. Returns { header, body } or null if not a #commit.
export function decodeCommitFrame (frameBytes) {
  const prefix = frameBytes.subarray(0, COMMIT_HEADER.length)
  if (!Buffer.from(prefix).equals(Buffer.from(COMMIT_HEADER))) return null
  return {
    header: { t: '#commit', op: 1 },
    body: dagCbor.decode(frameBytes.subarray(COMMIT_HEADER.length))
  }
}
// OverlayRepoStore — a RepoStore backend that keeps records as canonical DAG-CBOR FILES
// on disk (one file per record at records/<collection>/<rkey>.dagcbor) instead of in an
// append-only Hyperbee. Overwrite-in-place on edit, unlink on delete → the on-disk size is
// O(CURRENT records), not O(operations-ever). MST/commit/CAR are DERIVED on read by the
// atproto-repo codec (read-view.js / repo-manager.js consume only this interface), so nothing
// atproto-specific is stored beyond the record bytes + a tiny head.json.
//
// Byte-exactness (the determinism contract): `put` stores dagCbor.encode(record) VERBATIM —
// byte-identical to the Hyperbee RepoStore — so cidForBytesSync(bytes) and the derived MST +
// commit are identical. records() returns records in Hyperbee key order (utf-8 byte order via
// b4a.compare) so the derivation is order-stable.
//
// The canonical bytes ARE the files on disk. An optional hyper-overlay instance (opts.overlay)
// indexes + replicates them (bytes stay on disk — no corestore balloon; hyper-overlay/index.js).
// Without it the store is a fully-functional local file tree (used by the determinism tests).
// Drop-in for atproto-store/lib/repo-store.js's RepoStore (same method surface).

import * as dagCbor from '@ipld/dag-cbor'
import b4a from 'b4a'
import fs from '#node:fs' // dual-runtime: bare-fs under Bare (the daemon), builtin fs under Node (tests)
import { join } from '#node:path'
import { tidNow } from './tid.js'

const EXT = '.dagcbor'
const byteOrder = (a, b) => b4a.compare(b4a.from(a), b4a.from(b)) // match Hyperbee's key comparison exactly
// atproto collection NSIDs + rkeys are single path segments (no '/'); reject anything else so a
// record key can never escape the records/ dir or collide with a parent path.
const isSafeSeg = (s) => typeof s === 'string' && s.length > 0 && !s.includes('/') && s !== '.' && s !== '..'

export class OverlayRepoStore {
  // root: the per-DID dir (<storage>/dids/<did>). opts.overlay: optional HyperOverlay to
  // register files with (bytes-on-disk indexing/replication). opts.did: for logging/namespacing.
  constructor (root, opts = {}) {
    if (typeof root !== 'string') throw new Error('OverlayRepoStore: root dir path required')
    this._root = root
    this._recordsDir = join(root, 'records')
    this._headFile = join(root, 'head.json')
    this._overlay = opts.overlay || null
    this._did = opts.did || null
  }

  static key (collection, rkey) { return `${collection}/${rkey}` }

  async ready () {
    fs.mkdirSync(this._recordsDir, { recursive: true })
    // Restore servability across restart. The overlay's path maps are in-memory and only registerFile
    // fills them, so without this a restarted node serves ONLY records written since boot — every file
    // still on disk, yet peers get "no connected peer served this oid" (75+ hours of it on wj62), which
    // blocks signing. Seeding from the PERSISTED index costs one scan with no hashing and no file
    // reads, and it avoids the protocol's tier-3 full-index re-scan on every content request.
    // Our overlay paths are disk paths relative to root, so the resolver is a plain join.
    if (this._overlay && typeof this._overlay.seedFilePathsFromIndex === 'function') {
      try {
        const n = await this._overlay.seedFilePathsFromIndex((overlayPath) => join(this._root, overlayPath))
        if (n) console.log(JSON.stringify({ msg: 'overlay: seeded record paths from the persisted index (servable-by-oid after restart)', did: this._did, seeded: n }))
      } catch (err) { console.error(JSON.stringify({ msg: 'overlay path seed FAILED — this node may not serve its records by oid until re-registered', did: this._did, error: err.message })) }
    }
    return this
  }

  // EXPLICIT REPAIR — not a boot step. ready() seeds the path maps from the persisted index, which is
  // the cheap normal path. This is the heavier fallback for a store whose INDEX itself is missing or
  // stale (records written before overlay indexing existed, or an index rebuilt/lost): it re-hashes
  // every record file and re-registers it. Needed once on nodes whose indexes predate the seed fix;
  // deliberately NOT wired into ready(), because re-hashing every file at every boot is the cold-start
  // cost that made pgh-sidecar take ~190s to bind its socket.
  //
  // Re-register every record file with the overlay so peers can fetch it BY OID.
  //
  // hyper-overlay's serve path resolves contentHash -> disk path through an IN-MEMORY map
  // (overlay.js `_contentHashPaths`, populated only by registerFile and handed to protocol.js by
  // reference). Nothing rebuilds it at boot, and the persisted FileIndex stores { contentHash, size,
  // mtime } WITHOUT the disk path — so the overlay cannot repair itself; only the consumer knows the
  // layout. Net effect before this: after a restart a node could serve ONLY the records it had
  // written since boot ("registering a file makes it servable", overlay.js:15), even though every
  // file was still on disk.
  //
  // That silently breaks cross-node byte resolution, which GATES SIGNING: the forward-only sign gate
  // skips while a converged pointer's bytes are unresolved. Measured on the live fleet — wj62's
  // app.bsky.feed.post/3mr6v6r2ofs22 sat unresolvable for 75+ hours while the peer holding it had the
  // exact bytes on disk (hash verified equal to the pointer's oid), reporting only "no connected peer
  // served this oid"; both co-owners held different incomplete subsets for the same reason.
  //
  // Idempotent and safe to run every boot: registerFile re-asserts an identical entry. Deliberately
  // passes NO `rev` (a fresh TID would make a re-registration look like a newer write to rev-wins
  // conflict resolution) and `prepare: false` (the serve path chunks lazily on first request, so we
  // avoid a second full read of every file at boot).
  async reindexOverlay () {
    if (!this._overlay) return { skipped: 'no-overlay' }
    let registered = 0
    let failed = 0
    const files = await this.records()
    for (const { key, bytes } of files) {
      const i = key.indexOf('/')
      const collection = key.slice(0, i)
      const rkey = key.slice(i + 1)
      try {
        const r = await this._overlay.registerFile(this._overlayPath(collection, rkey), this._pathFor(collection, rkey), { size: bytes.length, prepare: false })
        if (r) registered++; else failed++
      } catch { failed++ }
    }
    if (files.length) {
      try { console.log(JSON.stringify({ msg: 'overlay reindex: record files re-registered as servable-by-oid', did: this._did, registered, failed, total: files.length })) } catch {}
    }
    return { registered, failed, total: files.length }
  }

  _pathFor (collection, rkey) {
    if (!isSafeSeg(collection) || !isSafeSeg(rkey)) throw new Error(`OverlayRepoStore: unsafe record key "${collection}/${rkey}"`)
    return join(this._recordsDir, collection, rkey + EXT)
  }

  // READ-ONLY: the overlay oid the record file CURRENTLY on disk hashes to, or null when absent.
  // Writes nothing (no registration, no index entry) — safe against a live store.
  //
  // This is the missing half of the pointer design's integrity story. PointerSubstrate stores
  // { $oid, size } in the shared autobase and resolves it through ensureLocal, which returns a local
  // file hit WITHOUT comparing it to $oid — so a node holding a superseded copy of a record serves it
  // forever and never re-fetches, while its pointer set looks perfectly converged. Nothing in the
  // stack could even ask "does my file match the pointer?", which is why the wj62 profile divergence
  // (two co-owners, identical 139 pointers, different avatar blob refs) was only visible by diffing
  // two signed CARs against each other. Compare this against the pointer's $oid to answer it directly.
  async localOid (collection, rkey) {
    if (!this._overlay || typeof this._overlay.hashFile !== 'function') return null
    let p
    try { p = this._pathFor(collection, rkey) } catch { return null }
    const r = await this._overlay.hashFile(p)
    return r ? { oid: r.contentHash, size: r.size } : null
  }

  // Returns { oid, size }: oid = the overlay content hash (blake2b) that a PEER fetches the bytes by
  // (PointerSubstrate stores {oid,size} as the symmetric autobase pointer). null oid when no overlay.
  async put (collection, rkey, record) {
    const bytes = b4a.from(dagCbor.encode(record))
    const p = this._pathFor(collection, rkey)
    fs.mkdirSync(join(this._recordsDir, collection), { recursive: true })
    fs.writeFileSync(p, bytes)
    // Stamp a monotonic per-write version (TID) so cross-device conflict resolution is atproto-native
    // (rev-wins: the later write wins). Records carry no rev at put time — the commit rev comes at sign.
    // Only affects the overlay change feed, never the canonical record file → determinism is preserved.
    let oid = null
    if (this._overlay) { try { const r = await this._overlay.registerFile(this._overlayPath(collection, rkey), p, { size: bytes.length, rev: tidNow() }); oid = r ? r.contentHash : null } catch {} }
    return { oid, size: bytes.length }
  }

  // Ensure the record BYTES are present locally, fetching from a connected peer by overlay oid if this
  // node holds only the pointer (a follower resolving the converged autobase set). Returns the decoded
  // record or null. Local-hit is the common path; the fetch is the cross-node byte-resolution.
  async ensureLocal (collection, rkey, oid) {
    const local = await this.get(collection, rkey)
    if (local != null) {
      // A local hit used to return here UNCONDITIONALLY, without ever comparing the bytes to the oid
      // the caller asked for. That made the pointer design's central promise unenforced: the autobase
      // converges { $oid, size }, but a node holding a SUPERSEDED copy resolved it happily, never
      // re-fetched, and signed it as truth. Live on wj62 — two co-owners, identical 139 converged
      // pointers, both resolving all 139, different signed repos, differing on exactly one record
      // (app.bsky.actor.profile/self, two avatar blob refs) — so the published profile flipped avatar
      // on every signer change. Content-addressing was being used to FETCH but never to VERIFY.
      if (!oid || !this._overlay || typeof this._overlay.hashFile !== 'function') return local
      const h = await this.localOid(collection, rkey)
      // Only a POSITIVE mismatch is staleness. If the bytes cannot be hashed at all we cannot judge
      // them, and inventing a verdict would re-resolve every record on every pass — behaviour must be
      // unchanged wherever verification is impossible.
      if (!h || h.oid === oid) return local // verified against the converged pointer — the common path
      this._logStaleLocal(collection, rkey, oid, h ? h.oid : null)
      const fetched = await this._refetchOver(collection, rkey, oid)
      // Deliberately null, NOT the stale record, when the authoritative bytes cannot be obtained.
      // Returning the superseded copy is what published wrong content: this record then reads as
      // UNRESOLVED, which is precisely the state the forward-only sign gate is built to handle
      // ("pointer present, bytes unreplicated -> behind -> SKIP"). A node that cannot prove its bytes
      // match the group's pointer must not sign them. Note the trade: if NO peer holds the
      // authoritative bytes, the record stays unresolved and the chain stalls rather than advancing
      // with content nobody agreed on — loudly (see _logStaleLocal) instead of silently.
      return fetched
    }
    if (!this._overlay || !oid) return null
    const disk = this._pathFor(collection, rkey)
    try {
      fs.mkdirSync(join(this._recordsDir, collection), { recursive: true })
      const r = await this._overlay.fetchFile(oid, { destPath: disk })
      if (!r) { this._logFetchMiss(collection, rkey, oid, 'fetchFile returned null'); return null }
    } catch (err) { this._logFetchMiss(collection, rkey, oid, (err && err.message) || String(err)); return null }
    return this.get(collection, rkey)
  }

  // Replace a SUPERSEDED local record file with the authoritative bytes for `oid`, without destroying
  // what we hold until the replacement is verified. Fetches to a sibling temp path (reSeed:false so the
  // overlay never indexes the temp), re-asserts the hash, then renames into place atomically and
  // registers the FINAL path so this node serves the correct bytes afterwards. On any failure the
  // existing file is left exactly as it was and null is returned. Returns the decoded record or null.
  async _refetchOver (collection, rkey, oid) {
    const disk = this._pathFor(collection, rkey)
    const tmp = disk + '.incoming-' + String(oid).slice(0, 12)
    try {
      const r = await this._overlay.fetchFile(oid, { destPath: tmp, reSeed: false })
      if (!r) { this._logFetchMiss(collection, rkey, oid, 'no peer served the authoritative bytes for a superseded local file'); return null }
      // fetchFile verifies incrementally during transfer; re-assert before overwriting persistent state.
      const h = await this._overlay.hashFile(tmp)
      if (!h || h.contentHash !== oid) {
        try { fs.unlinkSync(tmp) } catch {}
        this._logFetchMiss(collection, rkey, oid, 'fetched bytes did not hash to the requested oid')
        return null
      }
      fs.renameSync(tmp, disk)
      try { await this._overlay.registerFile(this._overlayPath(collection, rkey), disk, { size: h.size }) } catch {}
      try {
        console.log(JSON.stringify({ msg: 'ensureLocal: replaced superseded record bytes with the authoritative copy', did: this._did, key: collection + '/' + rkey, oid: String(oid).slice(0, 16) }))
      } catch {}
      return this.get(collection, rkey)
    } catch (err) {
      try { fs.unlinkSync(tmp) } catch {}
      this._logFetchMiss(collection, rkey, oid, (err && err.message) || String(err))
      return null
    }
  }

  // A local file that does not match the converged pointer is an ANOMALY, not routine lag — it means
  // this node has been resolving (and possibly signing) content the group did not agree on. Reported
  // once per key+oid so a persistent case is visible without spamming the resolve loop.
  _logStaleLocal (collection, rkey, oid, localOid) {
    if (!this._staleSeen) this._staleSeen = new Set()
    const k = collection + '/' + rkey + ':' + oid
    if (this._staleSeen.has(k)) return
    this._staleSeen.add(k)
    try {
      console.error(JSON.stringify({
        msg: 'ensureLocal: LOCAL BYTES DO NOT MATCH THE CONVERGED POINTER — this node held a superseded copy; re-fetching the authoritative bytes. Until it succeeds this record reads as unresolved and will not be signed.',
        did: this._did, key: collection + '/' + rkey, pointerOid: String(oid).slice(0, 16), localOid: localOid ? String(localOid).slice(0, 16) : null
      }))
    } catch {}
  }

  // Byte-resolution failures used to be swallowed entirely (`catch { return null }`), which made a
  // record whose bytes never replicated indistinguishable from any ordinary miss. That matters because
  // this path GATES SIGNING: the forward-only sign gate skips while a converged pointer's bytes are
  // unresolved, so a permanent miss silently stops a co-owner signing at all, with no diagnosable
  // cause. Observed on wj62 — one record unresolved for 75+ hours with nothing logged anywhere.
  // Deduped per oid, because the resolve loop calls this once per record on every list().
  // `fetchFile` returns null for two ROOT-DISTINCT reasons and the old message asserted only one of
  // them ("no connected peer served this oid"), which is why a transport-level fault read as a content
  // fault for days. overlay.js:307-315 waits peerWaitMs for a peer and bails if none ever attaches;
  // otherwise it asks the attached peers and they may simply not hold it. Reporting `overlayPeers`
  // separates those: 0 => the overlay channel never attached (a WIRING fault — look at attachProtocol);
  // >0 => genuinely nobody serving that content (a DISTRIBUTION fault — look at the holder's index).
  //
  // Dedup is keyed on oid + peerCount, not oid alone. Deduping per-oid-per-process meant the line was
  // emitted once at boot and never again, so a stale line was indistinguishable from a live failure and
  // could not be used to judge whether a repair had worked. Keying on the peer count keeps the log quiet
  // while still re-emitting the moment connectivity changes — which is exactly when the answer changes.
  _logFetchMiss (collection, rkey, oid, reason) {
    if (!this._fetchMisses) this._fetchMisses = new Set()
    const peers = (this._overlay && typeof this._overlay.peerCount === 'number') ? this._overlay.peerCount : null
    const k = String(oid)
    const dedupKey = k + ':' + peers
    if (this._fetchMisses.has(dedupKey)) return
    this._fetchMisses.add(dedupKey)
    try {
      console.error(JSON.stringify({
        msg: peers === 0
          ? 'overlay byte-resolution FAILED — NO overlay peers attached (transport/wiring fault, not content)'
          : 'overlay byte-resolution FAILED — peers attached but none served this oid (distribution fault)',
        did: this._did, key: `${collection}/${rkey}`, oid: k.slice(0, 16), overlayPeers: peers, reason
      }))
    } catch {}
  }

  async get (collection, rkey) {
    const raw = await this.getRaw(collection, rkey)
    return raw ? raw.record : null
  }

  // Raw stored bytes + decoded record. The bridge CIDs the EXACT bytes (never a re-encode) —
  // so these must be the same bytes `put` wrote.
  async getRaw (collection, rkey) {
    let bytes
    try { bytes = fs.readFileSync(this._pathFor(collection, rkey)) } catch (e) { if (e && e.code === 'ENOENT') return null; throw e }
    return { bytes, record: dagCbor.decode(bytes) }
  }

  async del (collection, rkey) {
    try { fs.unlinkSync(this._pathFor(collection, rkey)) } catch (e) { if (!e || e.code !== 'ENOENT') throw e }
    // Record the deletion in the overlay's change feed so it propagates to peers (attachReplication).
    if (this._overlay) { try { await this._overlay.unregisterFile(this._overlayPath(collection, rkey)) } catch {} }
    try { fs.rmdirSync(join(this._recordsDir, collection)) } catch {} // best-effort: drop an empty collection dir
  }

  // Yield { rkey, record } for one collection, in key (byte) order.
  async * list (collection) {
    const dir = join(this._recordsDir, collection)
    let names
    try { names = fs.readdirSync(dir) } catch (e) { if (e && e.code === 'ENOENT') return; throw e }
    for (const n of names.filter((x) => x.endsWith(EXT)).sort(byteOrder)) {
      const bytes = fs.readFileSync(join(dir, n))
      yield { rkey: n.slice(0, -EXT.length), record: dagCbor.decode(bytes) }
    }
  }

  // All records as { key, bytes, record } in key (byte) order — the sole input to the MST build.
  async records () {
    const out = []
    let collections
    try { collections = fs.readdirSync(this._recordsDir) } catch (e) { if (e && e.code === 'ENOENT') return out; throw e }
    for (const collection of collections) {
      const dir = join(this._recordsDir, collection)
      let st
      try { st = fs.statSync(dir) } catch { continue }
      if (!st.isDirectory()) continue
      for (const n of fs.readdirSync(dir)) {
        if (!n.endsWith(EXT)) continue
        const bytes = fs.readFileSync(join(dir, n))
        out.push({ key: `${collection}/${n.slice(0, -EXT.length)}`, bytes, record: dagCbor.decode(bytes) })
      }
    }
    out.sort((a, b) => byteOrder(a.key, b.key))
    return out
  }

  // Persist the commit head ({ rev, commitCid, dataCid }) — a tiny file, NOT a record, so it never
  // appears in records()/the MST. This is what keeps the head stable across restart: the rev is
  // RESTORED, not re-minted (re-minting forges a phantom commit — see RepoManager.init).
  async saveHead (head) {
    fs.mkdirSync(this._root, { recursive: true })
    fs.writeFileSync(this._headFile, JSON.stringify(head))
  }

  async loadHead () {
    try { return JSON.parse(fs.readFileSync(this._headFile, 'utf8')) } catch (e) { if (e && e.code === 'ENOENT') return null; throw e }
  }

  async close () {}

  _overlayPath (collection, rkey) { return `/records/${collection}/${rkey}${EXT}` }
}
// atproto TID — the 13-char, lexicographically-sortable timestamp id used for `rev`
// (and default rkeys). value = (unixMicros << 10) | clockId(10 bits), top bit 0,
// encoded in the sortable base32 alphabet. Monotonic within a process.

const S32 = '234567abcdefghijklmnopqrstuvwxyz' // atproto sortable base32

function s32encode (n) {
  let s = ''
  for (let i = 0; i < 13; i++) { s = S32[Number(n % 32n)] + s; n /= 32n }
  return s
}

let _last = 0n

// clock() returns micros; injectable for deterministic tests.
export function tidNow (clockId = 0, clock = () => BigInt(Date.now()) * 1000n) {
  let micros = clock()
  const val = (micros << 10n) | (BigInt(clockId) & 0x3ffn)
  const t = val > _last ? val : _last + 1n // strictly monotonic
  _last = t
  return s32encode(t)
}

export function isValidTid (s) {
  return typeof s === 'string' && s.length === 13 && [...s].every(c => S32.includes(c))
}

// The micros component of a TID (drops the 10-bit clock id).
export function tidMicros (tid) {
  let n = 0n
  for (const ch of String(tid)) n = (n << 5n) | BigInt(S32.indexOf(ch))
  return n >> 10n
}

// The DETERMINISTIC next rev after `prevRev` — a pure function of the previous rev, never the
// wall clock. This is what makes the atproto chain indexer-agnostic: two co-owners continuing
// from the SAME head over the SAME finalized record set produce byte-identical commits (RFC6979
// signing is deterministic), so concurrent signers are idempotent rather than forking. Mirrors
// atproto-base/lib/rev.js byte-for-byte (clockId 0) so both implementations agree exactly.
export function nextRev (prevRev) {
  return s32encode((tidMicros(prevRev) + 1n) << 10n)
}
const { Pull, Push, HEADERBYTES, KEYBYTES, ABYTES } = require('sodium-secretstream')
const sodium = require('sodium-universal')
const crypto = require('hypercore-crypto')
const { Duplex, Writable, getStreamError } = require('streamx')
const b4a = require('b4a')
const Timeout = require('timeout-refresh')
const unslab = require('unslab')
const Bridge = require('./lib/bridge')
const Handshake = require('./lib/handshake')

const IDHEADERBYTES = HEADERBYTES + 32
const [NS_INITIATOR, NS_RESPONDER, NS_SEND] = crypto.namespace('hyperswarm/secret-stream', 3)
const MAX_ATOMIC_WRITE = 256 * 256 * 256 - 1

module.exports = class NoiseSecretStream extends Duplex {
  constructor(isInitiator, rawStream, opts = {}) {
    super({ mapWritable: toBuffer })

    if (typeof isInitiator !== 'boolean') {
      throw new Error('isInitiator should be a boolean')
    }

    this.noiseStream = this
    this.isInitiator = isInitiator
    this.rawStream = null

    this.publicKey = opts.publicKey || null
    this.remotePublicKey = opts.remotePublicKey || null
    this.handshakeHash = null
    this.connected = false
    this.keepAlive = opts.keepAlive || 0
    this.timeout = 0
    this.enableSend = opts.enableSend !== false

    // pointer for upstream to set data here if they want
    this.userData = null

    let openedDone = null
    this.opened = new Promise((resolve) => {
      openedDone = resolve
    })

    this.rawBytesWritten = 0
    this.rawBytesRead = 0

    // metadata used by 'hyperdht'
    this.relay = null
    this.puncher = null

    // unwrapped raw stream
    this._rawStream = null

    // handshake state
    this._handshake = null
    this._handshakePattern = opts.pattern || null
    this._handshakeDone = null

    // message parsing state
    this._state = 0
    this._len = 0
    this._tmp = 1
    this._message = null

    this._openedDone = openedDone
    this._startDone = null
    this._drainDone = null
    this._outgoingPlain = null
    this._outgoingWrapped = null
    this._utp = null
    this._setup = true
    this._ended = 2
    this._encrypt = null
    this._decrypt = null
    this._timeoutTimer = null
    this._keepAliveTimer = null
    this._sendState = null

    if (opts.autoStart !== false) this.start(rawStream, opts)

    // wiggle it to trigger open immediately (TODO add streamx option for this)
    this.resume()
    this.pause()
  }

  static keyPair(seed) {
    return Handshake.keyPair(seed)
  }

  static id(handshakeHash, isInitiator, id) {
    return streamId(handshakeHash, isInitiator, id)
  }

  setTimeout(ms) {
    if (!ms) ms = 0

    this._clearTimeout()
    this.timeout = ms

    if (!ms || this.rawStream === null) return

    this._timeoutTimer = Timeout.once(ms, destroyTimeout, this)
    this._timeoutTimer.unref()
  }

  setKeepAlive(ms) {
    if (!ms) ms = 0

    this._clearKeepAlive()

    this.keepAlive = ms

    if (!ms || this.rawStream === null) return

    this._keepAliveTimer = Timeout.on(ms, sendKeepAlive, this)
    this._keepAliveTimer.unref()
  }

  sendKeepAlive() {
    const empty = this.alloc(0)
    this.write(empty)
  }

  start(rawStream, opts = {}) {
    if (rawStream) {
      this.rawStream = rawStream
      this._rawStream = rawStream
      if (typeof this.rawStream.setContentSize === 'function') {
        this._utp = rawStream
      }
    } else {
      this.rawStream = new Bridge(this)
      this._rawStream = this.rawStream.reverse
    }

    this.rawStream.on('error', this._onrawerror.bind(this))
    this.rawStream.on('close', this._onrawclose.bind(this))

    this._startHandshake(opts.handshake, opts.keyPair || null)
    this._continueOpen(null)

    if (this.destroying) return

    if (opts.data) this._onrawdata(opts.data)
    if (opts.ended) this._onrawend()

    if (this.keepAlive > 0 && this._keepAliveTimer === null) {
      this.setKeepAlive(this.keepAlive)
    }

    if (this.timeout > 0 && this._timeoutTimer === null) {
      this.setTimeout(this.timeout)
    }
  }

  async flush() {
    if ((await this.opened) === false) return false
    if ((await Writable.drained(this)) === false) return false
    if (this.destroying) return false

    if (this.rawStream !== null && this.rawStream.flush) {
      return await this.rawStream.flush()
    }

    return true
  }

  _continueOpen(err) {
    if (err) this.destroy(err)
    if (this._startDone === null) return
    const done = this._startDone
    this._startDone = null
    this._open(done)
  }

  _onkeypairpromise(p) {
    const self = this
    const cont = this._continueOpen.bind(this)

    p.then(onkeypair, cont)

    function onkeypair(kp) {
      self._onkeypair(kp)
      cont(null)
    }
  }

  _onkeypair(keyPair) {
    const pattern = this._handshakePattern || 'XX'
    const remotePublicKey = this.remotePublicKey

    this._handshake = new Handshake(this.isInitiator, keyPair, remotePublicKey, pattern)
    this.publicKey = this._handshake.keyPair.publicKey
  }

  _startHandshake(handshake, keyPair) {
    if (handshake) {
      const { tx, rx, hash, publicKey, remotePublicKey } = handshake
      this._setupSecretStream(tx, rx, hash, publicKey, remotePublicKey)
      return
    }

    if (!keyPair) keyPair = Handshake.keyPair()

    if (typeof keyPair.then === 'function') {
      this._onkeypairpromise(keyPair)
    } else {
      this._onkeypair(keyPair)
    }
  }

  _onrawerror(err) {
    this.destroy(err)
  }

  _onrawclose() {
    if (this._ended !== 0) this.destroy()
  }

  _onrawdata(data) {
    let offset = 0

    if (this._timeoutTimer !== null) {
      this._timeoutTimer.refresh()
    }

    do {
      switch (this._state) {
        case 0: {
          while (this._tmp !== 0x1000000 && offset < data.byteLength) {
            const v = data[offset++]
            this._len += this._tmp * v
            this._tmp *= 256
          }

          if (this._tmp === 0x1000000) {
            this._tmp = 0
            this._state = 1
            const unprocessed = data.byteLength - offset
            if (unprocessed < this._len && this._utp !== null)
              this._utp.setContentSize(this._len - unprocessed)
          }

          break
        }

        case 1: {
          const missing = this._len - this._tmp
          const end = missing + offset

          if (this._message === null && end <= data.byteLength) {
            this._message = data.subarray(offset, end)
            offset += missing
            this._incoming()
            break
          }

          const unprocessed = data.byteLength - offset

          if (this._message === null) {
            this._message = b4a.allocUnsafe(this._len)
          }

          b4a.copy(data, this._message, this._tmp, offset)
          this._tmp += unprocessed

          if (end <= data.byteLength) {
            offset += missing
            this._incoming()
          } else {
            offset += unprocessed
          }

          break
        }
      }
    } while (offset < data.byteLength && !this.destroying)
  }

  _onrawend() {
    this._ended--
    this.push(null)
  }

  _onrawdrain() {
    const drain = this._drainDone
    if (drain === null) return
    this._drainDone = null
    drain()
  }

  _read(cb) {
    this.rawStream.resume()
    cb(null)
  }

  _incoming() {
    const message = this._message

    this._state = 0
    this._len = 0
    this._tmp = 1
    this._message = null

    if (this._setup === true) {
      if (this._handshake) {
        this._onhandshakert(this._handshake.recv(message))
      } else {
        if (message.byteLength !== IDHEADERBYTES) {
          this.destroy(new Error('Invalid header message received'))
          return
        }

        const remoteId = message.subarray(0, 32)
        const expectedId = streamId(this.handshakeHash, !this.isInitiator)
        const header = message.subarray(32)

        if (!b4a.equals(expectedId, remoteId)) {
          this.destroy(new Error('Invalid header received'))
          return
        }

        this._decrypt.init(header)
        this._setup = false // setup is now done
      }
      return
    }

    if (message.byteLength < ABYTES) {
      this.destroy(new Error('Invalid message received'))
      return
    }

    this.rawBytesRead += message.byteLength

    const plain = message.subarray(1, message.byteLength - ABYTES + 1)

    try {
      this._decrypt.next(message, plain)
    } catch (err) {
      this.destroy(err)
      return
    }

    // If keep alive is selective, eat the empty buffers (ie assume the other side has it enabled also)
    if (plain.byteLength === 0 && this.keepAlive !== 0) return

    if (this.push(plain) === false) {
      this.rawStream.pause()
    }
  }

  _onhandshakert(h) {
    if (this._handshakeDone === null) return

    if (h !== null) {
      if (h.data) this._rawStream.write(h.data)
      if (!h.tx) return
    }

    const done = this._handshakeDone
    const publicKey = this._handshake.keyPair.publicKey

    this._handshakeDone = null
    this._handshake = null

    if (h === null) return done(new Error('Noise handshake failed'))

    this._setupSecretStream(h.tx, h.rx, h.hash, publicKey, h.remotePublicKey)
    this._resolveOpened(true)
    done(null)
  }

  _setupSecretStream(tx, rx, handshakeHash, publicKey, remotePublicKey) {
    const buf = b4a.allocUnsafeSlow(3 + IDHEADERBYTES)
    writeUint24le(IDHEADERBYTES, buf)

    this._encrypt = new Push(unslab(tx.subarray(0, KEYBYTES)), undefined, buf.subarray(3 + 32))
    this._decrypt = new Pull(unslab(rx.subarray(0, KEYBYTES)))

    this.publicKey = publicKey
    this.remotePublicKey = remotePublicKey
    this.handshakeHash = handshakeHash

    const id = buf.subarray(3, 3 + 32)
    streamId(handshakeHash, this.isInitiator, id)

    // initialize secretbox state for unordered messages
    this._setupSecretSend(handshakeHash)

    this.emit('handshake')
    // if rawStream is a bridge, also emit it there
    if (this.rawStream !== this._rawStream) this.rawStream.emit('handshake')

    if (this.destroying) return

    this._rawStream.write(buf)
  }

  _setupSecretSend(handshakeHash) {
    this._sendState = b4a.allocUnsafeSlow(32 + 32 + 8 + 8)
    const encrypt = this._sendState.subarray(0, 32) // secrets
    const decrypt = this._sendState.subarray(32, 64)
    const counter = this._sendState.subarray(64, 72) // nonce
    const initial = this._sendState.subarray(72)

    const inputs = this.isInitiator
      ? [
          [NS_INITIATOR, NS_SEND],
          [NS_RESPONDER, NS_SEND]
        ]
      : [
          [NS_RESPONDER, NS_SEND],
          [NS_INITIATOR, NS_SEND]
        ]

    sodium.crypto_generichash_batch(encrypt, inputs[0], handshakeHash)
    sodium.crypto_generichash_batch(decrypt, inputs[1], handshakeHash)

    sodium.randombytes_buf(initial)
    counter.set(initial)
  }

  _open(cb) {
    // no autostart or no handshake yet
    if (this._rawStream === null || (this._handshake === null && this._encrypt === null)) {
      this._startDone = cb
      return
    }

    this._rawStream.on('data', this._onrawdata.bind(this))
    this._rawStream.on('end', this._onrawend.bind(this))
    this._rawStream.on('drain', this._onrawdrain.bind(this))

    if (this.enableSend) this._rawStream.on('message', this._onmessage.bind(this))

    if (this._encrypt !== null) {
      this._resolveOpened(true)
      return cb(null)
    }

    this._handshakeDone = cb

    if (this.isInitiator) this._onhandshakert(this._handshake.send())
  }

  _predestroy() {
    if (this.rawStream) {
      const error = getStreamError(this)
      this.rawStream.destroy(error)
    }

    if (this._startDone !== null) {
      const done = this._startDone
      this._startDone = null
      done(new Error('Stream destroyed'))
    }

    if (this._handshakeDone !== null) {
      const done = this._handshakeDone
      this._handshakeDone = null
      done(new Error('Stream destroyed'))
    }

    if (this._drainDone !== null) {
      const done = this._drainDone
      this._drainDone = null
      done(new Error('Stream destroyed'))
    }
  }

  _write(data, cb) {
    let wrapped = this._outgoingWrapped

    if (data !== this._outgoingPlain) {
      wrapped = b4a.allocUnsafe(data.byteLength + 3 + ABYTES)
      wrapped.set(data, 4)
    } else {
      this._outgoingWrapped = this._outgoingPlain = null
    }

    if (wrapped.byteLength - 3 > MAX_ATOMIC_WRITE) {
      return cb(
        new Error(
          'Message is too large for an atomic write. Max size is ' + MAX_ATOMIC_WRITE + ' bytes.'
        )
      )
    }
    this.rawBytesWritten += wrapped.byteLength

    writeUint24le(wrapped.byteLength - 3, wrapped)
    // offset 4 so we can do it in-place
    this._encrypt.next(wrapped.subarray(4, 4 + data.byteLength), wrapped.subarray(3))

    if (this._keepAliveTimer !== null) this._keepAliveTimer.refresh()

    if (this._rawStream.write(wrapped) === false) {
      this._drainDone = cb
    } else {
      cb(null)
    }
  }

  _final(cb) {
    this._clearKeepAlive()
    this._ended--
    this._rawStream.end()
    cb(null)
  }

  _resolveOpened(val) {
    if (this._openedDone === null) return
    const opened = this._openedDone
    this._openedDone = null
    opened(val)
    if (!val) return
    this.connected = true
    this.emit('connect')
  }

  _clearTimeout() {
    if (this._timeoutTimer === null) return
    this._timeoutTimer.destroy()
    this._timeoutTimer = null
    this.timeout = 0
  }

  _clearKeepAlive() {
    if (this._keepAliveTimer === null) return
    this._keepAliveTimer.destroy()
    this._keepAliveTimer = null
    this.keepAlive = 0
  }

  _destroy(cb) {
    this._clearKeepAlive()
    this._clearTimeout()
    this._resolveOpened(false)
    cb(null)
  }

  _boxMessage(buffer) {
    const MB = sodium.crypto_secretbox_MACBYTES // 16
    const NB = sodium.crypto_secretbox_NONCEBYTES // 24

    const counter = this._sendState.subarray(64, 72)
    sodium.sodium_increment(counter)
    if (b4a.equals(counter, this._sendState.subarray(72))) {
      this.destroy(new Error('udp send nonce exchausted'))
      return
    }

    const secret = this._sendState.subarray(0, 32)
    const envelope = b4a.allocUnsafe(8 + MB + buffer.byteLength)
    const nonce = envelope.subarray(0, NB)
    const ciphertext = envelope.subarray(8)

    b4a.fill(nonce, 0) // pad suffix
    nonce.set(counter)

    sodium.crypto_secretbox_easy(ciphertext, buffer, nonce, secret)
    return envelope
  }

  send(buffer) {
    if (!this._sendState) return
    if (!this.rawStream?.send) return // udx-stream expected

    const message = this._boxMessage(buffer)
    return this.rawStream.send(message)
  }

  trySend(buffer) {
    if (!this._sendState) return
    if (!this.rawStream?.trySend) return // udx-stream expected

    const message = this._boxMessage(buffer)
    this.rawStream.trySend(message)
  }

  _onmessage(buffer) {
    if (!this._sendState) return // messages before handshake are dropped

    const MB = sodium.crypto_secretbox_MACBYTES // 16
    const NB = sodium.crypto_secretbox_NONCEBYTES // 24

    if (buffer.byteLength < NB) return // Invalid message

    const nonce = b4a.allocUnsafe(NB)
    b4a.fill(nonce, 0)
    nonce.set(buffer.subarray(0, 8))

    const secret = this._sendState.subarray(32, 64)
    const ciphertext = buffer.subarray(8)
    const plain = buffer.subarray(8, buffer.byteLength - MB)

    if (ciphertext.byteLength < MB) return // invalid message

    const success = sodium.crypto_secretbox_open_easy(plain, ciphertext, nonce, secret)

    if (success) this.emit('message', plain)
  }

  alloc(len) {
    const buf = b4a.allocUnsafe(len + 3 + ABYTES)
    this._outgoingWrapped = buf
    this._outgoingPlain = buf.subarray(4, buf.byteLength - ABYTES + 1)
    return this._outgoingPlain
  }

  toJSON() {
    return {
      isInitiator: this.isInitiator,
      publicKey: this.publicKey && b4a.toString(this.publicKey, 'hex'),
      remotePublicKey: this.remotePublicKey && b4a.toString(this.remotePublicKey, 'hex'),
      connected: this.connected,
      destroying: this.destroying,
      destroyed: this.destroyed,
      rawStream: this.rawStream && this.rawStream.toJSON ? this.rawStream.toJSON() : null
    }
  }
}

function writeUint24le(n, buf) {
  buf[0] = n & 255
  buf[1] = (n >>> 8) & 255
  buf[2] = (n >>> 16) & 255
}

function streamId(handshakeHash, isInitiator, out = b4a.allocUnsafe(32)) {
  sodium.crypto_generichash(out, isInitiator ? NS_INITIATOR : NS_RESPONDER, handshakeHash)
  return out
}

function toBuffer(data) {
  return typeof data === 'string' ? b4a.from(data) : data
}

function destroyTimeout() {
  this.destroy(new Error('Stream timed out'))
}

function sendKeepAlive() {
  const empty = this.alloc(0)
  this.write(empty)
}
const { Duplex, Writable } = require('streamx')

class ReversePassThrough extends Duplex {
  constructor(s) {
    super()
    this._stream = s
    this._ondrain = null
  }

  _write(data, cb) {
    if (this._stream.push(data) === false) {
      this._stream._ondrain = cb
    } else {
      cb(null)
    }
  }

  _final(cb) {
    this._stream.push(null)
    cb(null)
  }

  _read(cb) {
    const ondrain = this._ondrain
    this._ondrain = null
    if (ondrain) ondrain()
    cb(null)
  }
}

module.exports = class Bridge extends Duplex {
  constructor(noiseStream) {
    super()

    this.noiseStream = noiseStream

    this._ondrain = null
    this.reverse = new ReversePassThrough(this)
  }

  get publicKey() {
    return this.noiseStream.publicKey
  }

  get remotePublicKey() {
    return this.noiseStream.remotePublicKey
  }

  get handshakeHash() {
    return this.noiseStream.handshakeHash
  }

  flush() {
    return Writable.drained(this)
  }

  _read(cb) {
    const ondrain = this._ondrain
    this._ondrain = null
    if (ondrain) ondrain()
    cb(null)
  }

  _write(data, cb) {
    if (this.reverse.push(data) === false) {
      this.reverse._ondrain = cb
    } else {
      cb(null)
    }
  }

  _final(cb) {
    this.reverse.push(null)
    cb(null)
  }
}
const sodium = require('sodium-universal')
const curve = require('noise-curve-ed')
const Noise = require('noise-handshake')
const b4a = require('b4a')

const EMPTY = b4a.alloc(0)

module.exports = class Handshake {
  constructor(isInitiator, keyPair, remotePublicKey, pattern) {
    this.isInitiator = isInitiator
    this.keyPair = keyPair
    this.noise = new Noise(pattern, isInitiator, keyPair, { curve })
    this.noise.initialise(EMPTY, remotePublicKey)
    this.destroyed = false
  }

  static keyPair(seed) {
    const publicKey = b4a.alloc(32)
    const secretKey = b4a.alloc(64)
    if (seed) sodium.crypto_sign_seed_keypair(publicKey, secretKey, seed)
    else sodium.crypto_sign_keypair(publicKey, secretKey)
    return { publicKey, secretKey }
  }

  recv(data) {
    try {
      this.noise.recv(data)
      if (this.noise.complete) return this._return(null)
      return this.send()
    } catch {
      this.destroy()
      return null
    }
  }

  // note that the data returned here is framed so we don't have to do an extra copy
  // when sending it...
  send() {
    try {
      const data = this.noise.send()
      const wrap = b4a.allocUnsafe(data.byteLength + 3)

      writeUint24le(data.byteLength, wrap)
      wrap.set(data, 3)

      return this._return(wrap)
    } catch {
      this.destroy()
      return null
    }
  }

  destroy() {
    if (this.destroyed) return
    this.destroyed = true
  }

  _return(data) {
    const tx = this.noise.complete ? b4a.toBuffer(this.noise.tx) : null
    const rx = this.noise.complete ? b4a.toBuffer(this.noise.rx) : null
    const hash = this.noise.complete ? b4a.toBuffer(this.noise.hash) : null
    const remotePublicKey = this.noise.complete ? b4a.toBuffer(this.noise.rs) : null

    return {
      data,
      remotePublicKey,
      hash,
      tx,
      rx
    }
  }
}

function writeUint24le(n, buf) {
  buf[0] = n & 255
  buf[1] = (n >>> 8) & 255
  buf[2] = (n >>> 16) & 255
}
{
  "name": "@hyperswarm/secret-stream",
  "version": "6.9.1",
  "description": "Secret stream backed by Noise and libsodium's secretstream",
  "main": "index.js",
  "files": [
    "index.js",
    "lib/**.js"
  ],
  "dependencies": {
    "b4a": "^1.1.0",
    "hypercore-crypto": "^3.3.1",
    "noise-curve-ed": "^2.0.1",
    "noise-handshake": "^4.0.0",
    "sodium-secretstream": "^1.1.0",
    "sodium-universal": "^5.0.0",
    "streamx": "^2.14.0",
    "timeout-refresh": "^2.0.0",
    "unslab": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "udx-native": "^1.13.2"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check .",
    "test": "brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/hyperswarm-secret-stream.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/hyperswarm-secret-stream/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperswarm-secret-stream"
}
{
  "name": "@ipld/dag-cbor",
  "version": "9.2.7",
  "description": "JS implementation of DAG-CBOR",
  "author": "Rod <rod@vagg.org> (http://r.va.gg/)",
  "license": "Apache-2.0 OR MIT",
  "homepage": "https://github.com/ipld/js-dag-cbor#readme",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/ipld/js-dag-cbor.git"
  },
  "bugs": {
    "url": "https://github.com/ipld/js-dag-cbor/issues"
  },
  "publishConfig": {
    "access": "public",
    "provenance": true
  },
  "keywords": [
    "ipfs",
    "ipld",
    "multiformats"
  ],
  "type": "module",
  "types": "./dist/src/index.d.ts",
  "typesVersions": {
    "*": {
      "*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ],
      "src/*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ]
    }
  },
  "files": [
    "src",
    "dist",
    "!dist/test",
    "!**/*.tsbuildinfo"
  ],
  "exports": {
    ".": {
      "types": "./dist/src/index.d.ts",
      "import": "./src/index.js",
      "module-sync": "./src/index.js"
    }
  },
  "release": {
    "branches": [
      "master"
    ],
    "plugins": [
      [
        "@semantic-release/commit-analyzer",
        {
          "preset": "conventionalcommits",
          "releaseRules": [
            {
              "breaking": true,
              "release": "major"
            },
            {
              "revert": true,
              "release": "patch"
            },
            {
              "type": "feat",
              "release": "minor"
            },
            {
              "type": "fix",
              "release": "patch"
            },
            {
              "type": "docs",
              "release": "patch"
            },
            {
              "type": "test",
              "release": "patch"
            },
            {
              "type": "deps",
              "release": "patch"
            },
            {
              "scope": "no-release",
              "release": false
            }
          ]
        }
      ],
      [
        "@semantic-release/release-notes-generator",
        {
          "preset": "conventionalcommits",
          "presetConfig": {
            "types": [
              {
                "type": "feat",
                "section": "Features"
              },
              {
                "type": "fix",
                "section": "Bug Fixes"
              },
              {
                "type": "chore",
                "section": "Trivial Changes"
              },
              {
                "type": "docs",
                "section": "Documentation"
              },
              {
                "type": "deps",
                "section": "Dependencies"
              },
              {
                "type": "test",
                "section": "Tests"
              }
            ]
          }
        }
      ],
      "@semantic-release/changelog",
      "@semantic-release/npm",
      "@semantic-release/github",
      [
        "@semantic-release/git",
        {
          "assets": [
            "CHANGELOG.md",
            "package.json"
          ]
        }
      ]
    ]
  },
  "scripts": {
    "clean": "aegir clean",
    "lint": "aegir lint",
    "build": "aegir build",
    "release": "aegir release",
    "test": "npm run lint && aegir test",
    "test:ts": "npm run test --prefix test/ts-use",
    "test:node": "aegir test -t node --cov",
    "test:chrome": "aegir test -t browser --cov",
    "test:chrome-webworker": "aegir test -t webworker",
    "test:firefox": "aegir test -t browser -- --browser firefox",
    "test:firefox-webworker": "aegir test -t webworker -- --browser firefox",
    "test:electron-main": "aegir test -t electron-main",
    "dep-check": "aegir dep-check"
  },
  "dependencies": {
    "cborg": "^5.0.1",
    "multiformats": "^13.1.0"
  },
  "devDependencies": {
    "@ipld/garbage": "^6.0.0",
    "aegir": "^48.0.1"
  }
}
import * as cborg from 'cborg'
import { CID } from 'multiformats/cid'

// https://github.com/ipfs/go-ipfs/issues/3570#issuecomment-273931692
const CID_CBOR_TAG = 42

/**
 * @template T
 * @typedef {import('multiformats/codecs/interface').ByteView<T>} ByteView
 */

/**
 * @template T
 * @typedef {import('multiformats/codecs/interface').ArrayBufferView<T>} ArrayBufferView
 */

/**
 * @template T
 * @param {ByteView<T> | ArrayBufferView<T>} buf
 * @returns {ByteView<T>}
 */
export function toByteView (buf) {
  if (buf instanceof ArrayBuffer) {
    return new Uint8Array(buf, 0, buf.byteLength)
  }

  return buf
}

/**
 * cidEncoder will receive all Objects during encode, it needs to filter out
 * anything that's not a CID and return `null` for that so it's encoded as
 * normal.
 *
 * @param {any} obj
 * @returns {cborg.Token[]|null}
 */
function cidEncoder (obj) {
  if (obj.asCID !== obj && obj['/'] !== obj.bytes) {
    return null // any other kind of object
  }
  const cid = CID.asCID(obj)
  /* c8 ignore next 4 */
  // very unlikely case, and it'll probably throw a recursion error in cborg
  if (!cid) {
    return null
  }
  const bytes = new Uint8Array(cid.bytes.byteLength + 1)
  bytes.set(cid.bytes, 1) // prefix is 0x00, for historical reasons
  return [
    new cborg.Token(cborg.Type.tag, CID_CBOR_TAG),
    new cborg.Token(cborg.Type.bytes, bytes)
  ]
}

// eslint-disable-next-line jsdoc/require-returns-check
/**
 * Intercept all `undefined` values from an object walk and reject the entire
 * object if we find one.
 *
 * @returns {null}
 */
function undefinedEncoder () {
  throw new Error('`undefined` is not supported by the IPLD Data Model and cannot be encoded')
}

/**
 * Intercept all `number` values from an object walk and reject the entire
 * object if we find something that doesn't fit the IPLD data model (NaN &
 * Infinity).
 *
 * @param {number} num
 * @returns {null}
 */
function numberEncoder (num) {
  if (Number.isNaN(num)) {
    throw new Error('`NaN` is not supported by the IPLD Data Model and cannot be encoded')
  }
  if (num === Infinity || num === -Infinity) {
    throw new Error('`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded')
  }
  return null
}

/**
 * @param {Map<any, any>} map
 * @returns {null}
 */
function mapEncoder (map) {
  for (const key of map.keys()) {
    if (typeof key !== 'string' || key.length === 0) {
      throw new Error('Non-string Map keys are not supported by the IPLD Data Model and cannot be encoded')
    }
  }
  return null
}

const _encodeOptions = {
  float64: true,
  typeEncoders: {
    Map: mapEncoder,
    Object: cidEncoder,
    undefined: undefinedEncoder,
    number: numberEncoder
  }
}

export const encodeOptions = {
  ..._encodeOptions,
  typeEncoders: {
    ..._encodeOptions.typeEncoders
  }
}

/**
 * @param {import('cborg').TagDecodeControl} decode
 * @returns {CID}
 */
function cidDecoder (decode) {
  const bytes = /** @type {Uint8Array} */ (decode())
  if (bytes[0] !== 0) {
    throw new Error('Invalid CID for CBOR tag 42; expected leading 0x00')
  }
  return CID.decode(bytes.subarray(1)) // ignore leading 0x00
}

const _decodeOptions = {
  allowIndefinite: false,
  coerceUndefinedToNull: true,
  allowNaN: false,
  allowInfinity: false,
  allowBigInt: true, // this will lead to BigInt for ints outside of
  // safe-integer range, which may surprise users
  strict: true,
  useMaps: false,
  rejectDuplicateMapKeys: true,
  /** @type {{ [tagNumber: number]: import('cborg').TagDecoder }} */
  tags: { [CID_CBOR_TAG]: cidDecoder }
}

export const decodeOptions = {
  ..._decodeOptions,
  tags: { ..._decodeOptions.tags }
}

export const name = 'dag-cbor'
export const code = 0x71

/**
 * @template T
 * @param {T} node
 * @returns {ByteView<T>}
 */
export const encode = (node) => cborg.encode(node, _encodeOptions)

/**
 * @template T
 * @param {ByteView<T> | ArrayBufferView<T>} data
 * @returns {T}
 */
export const decode = (data) => cborg.decode(toByteView(data), _decodeOptions)
// Minimal CAR v1 codec — bare-safe, dependency-light replacement for @ipld/car.
//
// CAR v1 is a trivial container: varint(headerLen) ++ dag-cbor({version:1, roots:[…]})
// then, per block, varint(len) ++ CIDbytes ++ blockBytes. We only need whole-buffer
// read/write (no streaming, no file I/O), so this is ~40 lines of pure JS over
// multiformats' CID (byte-exact with @ipld/car — verified by the repo tests + the
// @atproto/repo conformance reader). Drops @ipld/car (which imports `fs`/streams and
// won't load under Bare).
//
// ⚠️ LIMITATIONS vs @ipld/car (tracked in memory: bare-car-limitations). Fine for our
// current use (whole-buffer, CARv1, OUR-OWN trusted output); add the feature before the
// gate it guards:
//   - No streaming — whole CAR is buffered in memory. GATE: large repos (getRepo of a
//     big repo could be GBs). Add an async-iterator read/write path.
//   - No untrusted-input hardening — readCar trusts varints/lengths/CIDs. GATE: reading
//     UNTRUSTED CARs (com.atproto.repo.importRepo, ingress bridge). Add bounds/overflow/
//     truncation checks + duplicate-CID handling before then.
//   - CARv1 only (no CARv2/index). atproto is CARv1, so no gate today.
// Fully-featured path: grow this file at each gate, OR extract a standalone bare-native
// `bare-car` package (the holepunch ecosystem lacks one — a real contribution).

import { CID } from 'multiformats/cid'
import * as dagCbor from '@ipld/dag-cbor'

function varintEncode (n) {
  const out = []
  while (n >= 0x80) { out.push((n & 0x7f) | 0x80); n >>>= 7 }
  out.push(n)
  return Uint8Array.from(out)
}

function varintDecode (bytes, offset) {
  let n = 0; let shift = 0; let i = offset
  for (;;) {
    const b = bytes[i++]
    n |= (b & 0x7f) << shift
    if ((b & 0x80) === 0) break
    shift += 7
  }
  return [n >>> 0, i]
}

// Serialise { root, blocks } to CAR bytes. `blocks` is an iterable of { cid, bytes }.
export async function writeCar (rootCid, blocks) {
  const header = dagCbor.encode({ version: 1, roots: [rootCid] })
  const parts = [Buffer.from(varintEncode(header.length)), Buffer.from(header)]
  for (const { cid, bytes } of blocks) {
    const cidBytes = cid.bytes
    const body = new Uint8Array(cidBytes.length + bytes.length)
    body.set(cidBytes, 0)
    body.set(bytes, cidBytes.length)
    parts.push(Buffer.from(varintEncode(body.length)), Buffer.from(body))
  }
  return Buffer.concat(parts)
}

// Read a CAR into { roots, blocks } where blocks maps cid-string -> { cid, bytes }.
export async function readCar (carBytes) {
  const bytes = carBytes instanceof Uint8Array ? carBytes : new Uint8Array(carBytes)
  let [hlen, off] = varintDecode(bytes, 0)
  const header = dagCbor.decode(bytes.subarray(off, off + hlen))
  off += hlen
  const blocks = new Map()
  while (off < bytes.length) {
    const [blen, bodyStart] = varintDecode(bytes, off)
    const end = bodyStart + blen
    const [cid, rest] = CID.decodeFirst(bytes.subarray(bodyStart, end))
    blocks.set(cid.toString(), { cid, bytes: rest })
    off = end
  }
  return { roots: header.roots, blocks }
}
// atproto block CIDs — CIDv1, dag-cbor codec (0x71), sha2-256 multihash (0x12).
// Every block in a repo (commit, MST node, record) is content-addressed this way,
// so computeCid(dag-cbor(block)) IS the block's identity. This is the anchor for
// byte-exact fidelity: if our re-encoded bytes hash to the same CID the reference
// produced, our encoding is byte-identical.

import { CID } from 'multiformats/cid'
import * as Digest from 'multiformats/hashes/digest'
import { sha256 as nobleSha256 } from '@noble/hashes/sha2'
import * as dagCbor from '@ipld/dag-cbor'
import * as raw from 'multiformats/codecs/raw'

// raw block bytes -> CID. Uses noble's pure-JS sha256 (same as the sync path) rather
// than multiformats' `crypto.subtle` path — identical CID, and no WebCrypto dependency
// (so it loads + runs under Bare, which has no crypto.subtle).
export async function cidForBytes (bytes) {
  return cidForBytesSync(bytes)
}

// Synchronous variant — needed by the recursive MST build. Same result as
// cidForBytes (CIDv1 / dag-cbor 0x71 / sha2-256 0x12), just without the async
// WebCrypto digest.
export function cidForBytesSync (bytes) {
  const digest = Digest.create(0x12, nobleSha256(bytes)) // 0x12 = sha2-256 multihash code
  return CID.createV1(dagCbor.code, digest)
}

// BLOB CID — CIDv1, RAW codec (0x55), sha2-256. atproto blobs (images/avatars) are
// content-addressed with the raw codec (opaque bytes), NOT dag-cbor. This is the CID that
// goes in a blob ref ({$type:'blob', ref:{$link:<this>}, mimeType, size}) and the key
// com.atproto.sync.getBlob serves by.
export function cidForBlobSync (bytes) {
  const digest = Digest.create(0x12, nobleSha256(bytes))
  return CID.createV1(raw.code, digest)
}

// a JS value -> its canonical dag-cbor bytes + CID
export async function cidForValue (value) {
  const bytes = dagCbor.encode(value)
  return { bytes, cid: await cidForBytes(bytes) }
}
// atproto repo commit — sign + verify.
//
// A commit is { did, version: 3, data: <MST root CID>, rev, prev, sig }. The
// signature is ECDSA-secp256k1 (low-S) over sha256(dag-cbor(unsignedCommit)), stored
// as a raw 64-byte CBOR byte string (NOT base64url — that's the did:plc genesis).
// The relay validates this sig against the DID doc's verificationMethod.

import * as dagCbor from '@ipld/dag-cbor'
import { sha256 as nobleSha256 } from '@noble/hashes/sha2'
import { secp256k1 } from '@noble/curves/secp256k1'
import { cidForBytesSync } from './cid.js'

export const REPO_VERSION = 3

// The unsigned commit (everything the signature covers).
export function unsignedCommit ({ did, rev, data, prev = null }) {
  return { did, version: REPO_VERSION, data, rev, prev }
}

// Sign an unsigned commit -> signed commit with `sig` (64 raw bytes).
export function signCommit (unsigned, privateKey) {
  const hash = nobleSha256(dagCbor.encode(unsigned))
  const sig = secp256k1.sign(hash, privateKey, { lowS: true }).toCompactRawBytes()
  return { ...unsigned, sig }
}

export function commitCid (signedCommit) {
  return cidForBytesSync(dagCbor.encode(signedCommit))
}

// Verify a signed commit against a compressed secp256k1 pubkey (33 bytes).
export function verifyCommit (signedCommit, publicKey) {
  const { sig, ...unsigned } = signedCommit
  const hash = nobleSha256(dagCbor.encode(unsigned))
  return secp256k1.verify(sig, hash, publicKey, { lowS: true })
}
// atproto MST — WRITE path (slice 2).
//
// A faithful port of millipds's `atmst` (mst/node.py + node_wrangler.py) — the exact
// code that produced our golden CAR. Byte-exactness is verified two ways: rebuilding
// the golden repo's MST, and matching atmst's own root CIDs for a multi-height tree
// (build + delete oracles). See test/mst-write.test.js.
//
// Node shape (interleaved): subtrees[0], (keys[0],vals[0]), subtrees[1], … ,subtrees[n].
// key layer = leading-zero BITS of sha256(key), // 2 (fanout 4).

import * as dagCbor from '@ipld/dag-cbor'
import { sha256 as nobleSha256 } from '@noble/hashes/sha2'
import { cidForBytesSync } from './cid.js'

const cidEq = (a, b) => (a === null || b === null) ? a === b : a.equals(b)
const replaceAt = (arr, i, v) => { const c = arr.slice(); c[i] = v; return c }
const insertAt = (arr, i, v) => arr.slice(0, i).concat([v], arr.slice(i))
const removeAt = (arr, i) => arr.slice(0, i).concat(arr.slice(i + 1))

export function keyHeight (key) {
  const h = nobleSha256(Buffer.from(key, 'utf8')) // 32 bytes
  let zeros = 0
  for (const byte of h) {
    if (byte === 0) { zeros += 8; continue }
    zeros += Math.clz32(byte) - 24 // leading zero bits within this byte
    break
  }
  return zeros >> 1 // // 2
}

export class MSTNode {
  constructor (keys, vals, subtrees) {
    this.keys = keys // [string]
    this.vals = vals // [CID]
    this.subtrees = subtrees // [CID|null], length keys.length + 1
  }

  static empty () { return new MSTNode([], [], [null]) }

  isEmpty () { return this.keys.length === 0 && this.subtrees.length === 1 && this.subtrees[0] === null }

  serialise () {
    const e = []
    let prevKey = Buffer.alloc(0)
    for (let i = 0; i < this.keys.length; i++) {
      const keyBytes = Buffer.from(this.keys[i], 'utf8')
      const max = Math.min(prevKey.length, keyBytes.length)
      let p = 0
      while (p < max && prevKey[p] === keyBytes[p]) p++
      e.push({ k: keyBytes.subarray(p), p, t: this.subtrees[i + 1], v: this.vals[i] })
      prevKey = keyBytes
    }
    return dagCbor.encode({ e, l: this.subtrees[0] }) // dag-cbor canonicalises map key order
  }

  cid () { return cidForBytesSync(this.serialise()) }

  toOptional () { return this.isEmpty() ? null : this.cid() }

  gteIndex (key) { let i = 0; while (i < this.keys.length && key > this.keys[i]) i++; return i }

  height () {
    if (this.keys.length) return keyHeight(this.keys[0])
    if (this.subtrees[0] === null) return 0
    return null // indeterminate (empty intermediate node)
  }

  static deserialise (bytes) {
    const cbor = dagCbor.decode(bytes)
    const subtrees = [cbor.l]
    const keys = []
    const vals = []
    let prevKey = Buffer.alloc(0)
    for (const e of cbor.e) {
      const suffix = Buffer.from(e.k)
      const thisKey = Buffer.concat([prevKey.subarray(0, e.p), suffix])
      keys.push(thisKey.toString('utf8'))
      vals.push(e.v)
      subtrees.push(e.t)
      prevKey = thisKey
    }
    return new MSTNode(keys, vals, subtrees)
  }
}

// In-memory node store — maps CID string -> { cid, bytes }. get(null) returns the
// (stored) empty node, matching atmst NodeStore.get_node(None).
export class NodeStore {
  constructor () { this.blocks = new Map() }

  storedNode (node) {
    const bytes = node.serialise()
    const cid = cidForBytesSync(bytes)
    this.blocks.set(cid.toString(), { cid, bytes })
    return node
  }

  getNode (cid) {
    if (cid === null || cid === undefined) return this.storedNode(MSTNode.empty())
    const b = this.blocks.get(cid.toString())
    if (!b) throw new Error(`missing MST node ${cid}`)
    return MSTNode.deserialise(b.bytes)
  }
}

export class NodeWrangler {
  constructor (ns) { this.ns = ns }

  putRecord (rootCid, key, val) {
    const root = this.ns.getNode(rootCid)
    if (root.isEmpty()) return this._putHere(root, key, val).cid()
    return this._putRecursive(root, key, val, keyHeight(key), root.height()).cid()
  }

  delRecord (rootCid, key) {
    const root = this.ns.getNode(rootCid)
    const afterDel = this._deleteRecursive(root, key, keyHeight(key), root.height())
    return this.ns.getNode(this._squashTop(afterDel)).cid()
  }

  _putHere (node, key, val) {
    const i = node.gteIndex(key)
    if (i < node.keys.length && node.keys[i] === key) {
      if (cidEq(node.vals[i], val)) return node
      return this.ns.storedNode(new MSTNode(node.keys.slice(), replaceAt(node.vals, i, val), node.subtrees.slice()))
    }
    const [lsub, rsub] = this._splitOnKey(node.subtrees[i], key)
    return this.ns.storedNode(new MSTNode(
      insertAt(node.keys, i, key),
      insertAt(node.vals, i, val),
      node.subtrees.slice(0, i).concat([lsub, rsub], node.subtrees.slice(i + 1))
    ))
  }

  _putRecursive (node, key, val, keyH, treeH) {
    if (keyH > treeH) { // grow the tree upward
      return this.ns.storedNode(this._putRecursive(
        this.ns.storedNode(new MSTNode([], [], [node.cid()])),
        key, val, keyH, treeH + 1
      ))
    }
    if (keyH < treeH) { // descend
      const i = node.gteIndex(key)
      return this.ns.storedNode(new MSTNode(
        node.keys.slice(), node.vals.slice(),
        replaceAt(node.subtrees, i, this._putRecursive(this.ns.getNode(node.subtrees[i]), key, val, keyH, treeH - 1).cid())
      ))
    }
    return this._putHere(node, key, val) // keyH === treeH
  }

  _splitOnKey (nodeCid, key) {
    if (nodeCid === null || nodeCid === undefined) return [null, null]
    const node = this.ns.getNode(nodeCid)
    const i = node.gteIndex(key)
    const [lsub, rsub] = this._splitOnKey(node.subtrees[i], key)
    const left = this.ns.storedNode(new MSTNode(node.keys.slice(0, i), node.vals.slice(0, i), node.subtrees.slice(0, i).concat([lsub]))).toOptional()
    const right = this.ns.storedNode(new MSTNode(node.keys.slice(i), node.vals.slice(i), [rsub].concat(node.subtrees.slice(i + 1)))).toOptional()
    return [left, right]
  }

  _squashTop (nodeCid) {
    const node = this.ns.getNode(nodeCid)
    if (node.keys.length) return nodeCid
    if (node.subtrees[0] === null) return nodeCid
    return this._squashTop(node.subtrees[0])
  }

  _deleteRecursive (node, key, keyH, treeH) {
    if (keyH > treeH) return node.toOptional()
    let i = node.gteIndex(key)
    if (keyH < treeH) {
      if (node.subtrees[i] === null) return node.toOptional()
      return this.ns.storedNode(new MSTNode(
        node.keys.slice(), node.vals.slice(),
        replaceAt(node.subtrees, i, this._deleteRecursive(this.ns.getNode(node.subtrees[i]), key, keyH, treeH - 1))
      )).toOptional()
    }
    i = node.gteIndex(key)
    if (i === node.keys.length || node.keys[i] !== key) return node.toOptional()
    return this.ns.storedNode(new MSTNode(
      removeAt(node.keys, i), removeAt(node.vals, i),
      node.subtrees.slice(0, i).concat([this._merge(node.subtrees[i], node.subtrees[i + 1])], node.subtrees.slice(i + 2))
    )).toOptional()
  }

  _merge (leftCid, rightCid) {
    if (leftCid === null) return rightCid
    if (rightCid === null) return leftCid
    const left = this.ns.getNode(leftCid)
    const right = this.ns.getNode(rightCid)
    return this.ns.storedNode(new MSTNode(
      left.keys.concat(right.keys), left.vals.concat(right.vals),
      left.subtrees.slice(0, -1).concat([this._merge(left.subtrees[left.subtrees.length - 1], right.subtrees[0])], right.subtrees.slice(1))
    )).toOptional()
  }
}

// Build an MST from records [{ key, value: CID }] (any order). Returns
// { root: CID, ns: NodeStore }. ns.blocks holds every node created; use
// reachableBlocks(ns, root) for just the live set (CAR output).
export function buildMst (records) {
  const ns = new NodeStore()
  const w = new NodeWrangler(ns)
  let root = ns.storedNode(MSTNode.empty()).cid()
  for (const { key, value } of records) root = w.putRecord(root, key, value)
  return { root, ns, wrangler: w }
}

// BFS the live MST nodes reachable from root (for CAR block sets).
export function reachableBlocks (ns, rootCid) {
  const out = new Map()
  const stack = [rootCid]
  while (stack.length) {
    const cid = stack.pop()
    if (cid === null || cid === undefined) continue
    const key = cid.toString()
    if (out.has(key)) continue
    const b = ns.blocks.get(key)
    if (!b) throw new Error(`missing node ${key}`)
    out.set(key, b)
    const node = MSTNode.deserialise(b.bytes)
    for (const t of node.subtrees) if (t) stack.push(t)
  }
  return out
}

// ---- Firehose MST-inversion proof (slice 3b) ----
//
// A #commit's `blocks` CAR must be a MINIMAL, self-contained proof of the
// old→new transition — not the whole tree (that would trip a relay's `tooBig`).
// This ports millipds `repo_ops.py:apply_writes` step 2b + `atmst` proof.py:
//   blocks = created | deletion_proof_cids | inductive_proof_nodes  (+ new records)
// where `inductive_proof_nodes` = every MST node READ while replaying the ops
// backward from the new root, which must reproduce the old (prevData) root.
// The prior record CIDs travel in each op's `prev` (like millipds), so a cold
// relay can invert with no old-tree state of its own.

// A NodeStore overlay: writes land in an in-memory upper layer (NOT logged);
// reads that fall through to `lower` are recorded in `.gets`. Mirrors millipds's
// OverlayBlockStore(MemoryBlockStore, LoggingBlockStoreWrapper(bs)).
export class OverlayNodeStore {
  constructor (lower) { this.lower = lower; this.upper = new Map(); this.gets = new Set() }

  storedNode (node) {
    const bytes = node.serialise()
    const cid = cidForBytesSync(bytes)
    this.upper.set(cid.toString(), { cid, bytes })
    return node
  }

  getNode (cid) {
    if (cid === null || cid === undefined) return MSTNode.empty()
    const k = cid.toString()
    const u = this.upper.get(k)
    if (u) return MSTNode.deserialise(u.bytes)
    this.gets.add(k) // a read of a pre-existing node — part of the inductive proof
    return this.lower.getNode(cid)
  }
}

// Follow the search path for `key` from `rootCid`, collecting every node visited.
// Returns { value: CID|null, proof: Set<cidStr> }. value===null ⇒ exclusion proof;
// value!==null ⇒ inclusion proof. Port of atmst find_rpath_and_build_proof.
export function findRpathProof (ns, rootCid, key) {
  const proof = new Set()
  let cid = rootCid
  while (cid !== null && cid !== undefined) {
    const node = ns.getNode(cid)
    proof.add(cid.toString())
    const i = node.gteIndex(key)
    if (i < node.keys.length && node.keys[i] === key) return { value: node.vals[i], proof }
    cid = node.subtrees[i] // descend the subtree left of the first key >= target
  }
  return { value: null, proof }
}

// Build a NodeStore holding exactly the given blocks (cid-string -> { cid, bytes }).
export function nodeStoreFromBlocks (blocks) {
  const ns = new NodeStore()
  for (const [k, v] of blocks) ns.blocks.set(k, v)
  return ns
}

// Compute the minimal firehose block set for a single commit's ops.
//   oldRecords / newRecords : [{ key, value: CID }] — the record sets BEFORE/AFTER.
//   ops : [{ action:'create'|'update'|'delete', path, cid: CID|null, prev: CID|null }]
// Returns { blocks: Map<cidStr,{cid,bytes}>, dataCid, oldRoot } — MST nodes only
// (record + commit blocks are added by the caller). Throws if the backward replay
// does not reproduce the old root (i.e. the proof would be invalid).
export function firehoseProofBlocks ({ oldRecords, newRecords, ops }) {
  const oldB = buildMst(oldRecords)
  const newB = buildMst(newRecords)
  const oldRoot = oldB.root
  const newRoot = newB.root

  const oldSet = reachableBlocks(oldB.ns, oldRoot)
  const newSet = reachableBlocks(newB.ns, newRoot)

  // combined store holds every node of BOTH trees (proof reads span both)
  const combined = new NodeStore()
  for (const [k, v] of oldSet) combined.blocks.set(k, v)
  for (const [k, v] of newSet) combined.blocks.set(k, v)

  const proofCids = new Set()

  // created: new-tree nodes not present in the old tree
  for (const k of newSet.keys()) if (!oldSet.has(k)) proofCids.add(k)

  // deletion proofs: for each delete, the exclusion-proof path in the NEW tree
  for (const op of ops) {
    if (op.action !== 'delete') continue
    const { value, proof } = findRpathProof(combined, newRoot, op.path)
    if (value !== null) throw new Error(`delete proof: ${op.path} still present in new tree`)
    for (const c of proof) proofCids.add(c)
  }

  // inductive proof: replay ops backward from newRoot; every node read is required.
  const overlay = new OverlayNodeStore(combined)
  const w = new NodeWrangler(overlay)
  let inv = newRoot
  for (let i = ops.length - 1; i >= 0; i--) {
    const op = ops[i]
    if (op.action === 'create') {
      inv = w.delRecord(inv, op.path)
    } else { // update | delete → restore the prior value
      if (op.prev === null || op.prev === undefined) throw new Error(`inversion: ${op.action} ${op.path} missing prev`)
      inv = w.putRecord(inv, op.path, op.prev)
    }
  }
  if (!inv.equals(oldRoot)) throw new Error('inversion proof failed: backward replay did not reproduce prevData root')
  for (const k of overlay.gets) proofCids.add(k)

  const blocks = new Map()
  for (const k of proofCids) blocks.set(k, combined.blocks.get(k))
  return { blocks, dataCid: newRoot, oldRoot }
}
// atproto repo — READ path (slice 1).
//
// A repo is a CAR whose root is a signed commit; the commit's `data` CID points at
// the root of a Merkle Search Tree (MST) of records. This module reads a CAR, walks
// the MST, and — most importantly — VERIFIES byte-exact fidelity by re-encoding every
// block and checking its CID. Writing/mutating the MST is slice 2.

import * as dagCbor from '@ipld/dag-cbor'
import { cidForBytes, cidForBytesSync } from './cid.js'
import { buildMst, reachableBlocks } from './mst.js'
import { unsignedCommit, signCommit, commitCid } from './commit.js'
import { readCar, writeCar } from './car.js'

// CAR read/write moved to the bare-safe minimal codec in ./car.js (was @ipld/car).
export { readCar, writeCar }

export function getBlock (car, cid) {
  const b = car.blocks.get(cid.toString())
  if (!b) throw new Error(`missing block ${cid}`)
  return b
}

export function decodeBlock (car, cid) {
  return dagCbor.decode(getBlock(car, cid).bytes)
}

// The signed commit at the CAR root.
export function loadCommit (car) {
  if (car.roots.length !== 1) throw new Error(`expected 1 root, got ${car.roots.length}`)
  const commit = decodeBlock(car, car.roots[0])
  if (!commit || !commit.did || commit.data === undefined) throw new Error('root is not a commit')
  return { cid: car.roots[0], value: commit }
}

// Walk the MST in key order, yielding { key, value: recordCid }. MST node shape:
//   { l: CID|null, e: [ { p: int, k: bytes, v: CID, t: CID|null } ] }
// keys are prefix-compressed against the previous key in the SAME node.
export function * walkMst (car, rootCid, _prevKey = '') {
  const node = decodeBlock(car, rootCid)
  if (!node || !Array.isArray(node.e)) throw new Error(`not an MST node: ${rootCid}`)
  if (node.l) yield * walkMst(car, node.l)
  let prev = ''
  for (const e of node.e) {
    const suffix = Buffer.from(e.k).toString('utf8')
    const key = prev.slice(0, e.p) + suffix
    prev = key
    yield { key, value: e.v }
    if (e.t) yield * walkMst(car, e.t)
  }
}

// All records as { key, cid, value } in key order.
export function listRecords (car) {
  const commit = loadCommit(car)
  const out = []
  for (const { key, value } of walkMst(car, commit.value.data)) {
    out.push({ key, cid: value, value: decodeBlock(car, value) })
  }
  return out
}

// Byte-exact fidelity check: re-encode every block and confirm its CID is unchanged.
// Also confirms the commit's data CID and every MST value CID resolve to a present
// block. Returns { blocks, records, ok, mismatches }.
export async function verifyRepo (car) {
  const mismatches = []
  for (const [cidStr, { cid, bytes }] of car.blocks) {
    // re-encode: decode then canonical-encode; must reproduce the exact bytes + CID
    const reencoded = dagCbor.encode(dagCbor.decode(bytes))
    const sameBytes = Buffer.from(reencoded).equals(Buffer.from(bytes))
    const recomputed = await cidForBytes(reencoded)
    if (!sameBytes || !recomputed.equals(cid)) {
      mismatches.push({ cid: cidStr, sameBytes, recomputed: recomputed.toString() })
    }
  }
  const commit = loadCommit(car)
  getBlock(car, commit.value.data) // MST root must be present
  const records = listRecords(car)
  for (const r of records) getBlock(car, r.cid) // each record block present
  return { blocks: car.blocks.size, records: records.length, ok: mismatches.length === 0, mismatches }
}

// ---- WRITE path (slice 3) ----

// Originate a full atproto repo from records. Each record is
// { collection, rkey, record } (or { key, value }). Returns the CAR bytes plus the
// commit/data CIDs. `privateKey` is the atproto secp256k1 signing key.
export async function createRepo ({ records, did, rev, privateKey }) {
  const recordBlocks = new Map()
  const mstRecords = []
  for (const r of records) {
    const key = r.key !== undefined ? r.key : `${r.collection}/${r.rkey}`
    const value = r.record !== undefined ? r.record : r.value
    const bytes = dagCbor.encode(value)
    const cid = cidForBytesSync(bytes)
    recordBlocks.set(cid.toString(), { cid, bytes })
    mstRecords.push({ key, value: cid })
  }
  const { root: dataCid, ns } = buildMst(mstRecords)
  const mstBlocks = reachableBlocks(ns, dataCid)

  const signed = signCommit(unsignedCommit({ did, rev, data: dataCid }), privateKey)
  const cCid = commitCid(signed)
  const commitBytes = dagCbor.encode(signed)

  const blocks = [{ cid: cCid, bytes: commitBytes }, ...mstBlocks.values(), ...recordBlocks.values()]
  const carBytes = await writeCar(cCid, blocks)
  return { carBytes, commitCid: cCid, dataCid, signedCommit: signed }
}
{
  "name": "@ipld/dag-cbor",
  "version": "9.2.7",
  "description": "JS implementation of DAG-CBOR",
  "author": "Rod <rod@vagg.org> (http://r.va.gg/)",
  "license": "Apache-2.0 OR MIT",
  "homepage": "https://github.com/ipld/js-dag-cbor#readme",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/ipld/js-dag-cbor.git"
  },
  "bugs": {
    "url": "https://github.com/ipld/js-dag-cbor/issues"
  },
  "publishConfig": {
    "access": "public",
    "provenance": true
  },
  "keywords": [
    "ipfs",
    "ipld",
    "multiformats"
  ],
  "type": "module",
  "types": "./dist/src/index.d.ts",
  "typesVersions": {
    "*": {
      "*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ],
      "src/*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ]
    }
  },
  "files": [
    "src",
    "dist",
    "!dist/test",
    "!**/*.tsbuildinfo"
  ],
  "exports": {
    ".": {
      "types": "./dist/src/index.d.ts",
      "import": "./src/index.js",
      "module-sync": "./src/index.js"
    }
  },
  "release": {
    "branches": [
      "master"
    ],
    "plugins": [
      [
        "@semantic-release/commit-analyzer",
        {
          "preset": "conventionalcommits",
          "releaseRules": [
            {
              "breaking": true,
              "release": "major"
            },
            {
              "revert": true,
              "release": "patch"
            },
            {
              "type": "feat",
              "release": "minor"
            },
            {
              "type": "fix",
              "release": "patch"
            },
            {
              "type": "docs",
              "release": "patch"
            },
            {
              "type": "test",
              "release": "patch"
            },
            {
              "type": "deps",
              "release": "patch"
            },
            {
              "scope": "no-release",
              "release": false
            }
          ]
        }
      ],
      [
        "@semantic-release/release-notes-generator",
        {
          "preset": "conventionalcommits",
          "presetConfig": {
            "types": [
              {
                "type": "feat",
                "section": "Features"
              },
              {
                "type": "fix",
                "section": "Bug Fixes"
              },
              {
                "type": "chore",
                "section": "Trivial Changes"
              },
              {
                "type": "docs",
                "section": "Documentation"
              },
              {
                "type": "deps",
                "section": "Dependencies"
              },
              {
                "type": "test",
                "section": "Tests"
              }
            ]
          }
        }
      ],
      "@semantic-release/changelog",
      "@semantic-release/npm",
      "@semantic-release/github",
      [
        "@semantic-release/git",
        {
          "assets": [
            "CHANGELOG.md",
            "package.json"
          ]
        }
      ]
    ]
  },
  "scripts": {
    "clean": "aegir clean",
    "lint": "aegir lint",
    "build": "aegir build",
    "release": "aegir release",
    "test": "npm run lint && aegir test",
    "test:ts": "npm run test --prefix test/ts-use",
    "test:node": "aegir test -t node --cov",
    "test:chrome": "aegir test -t browser --cov",
    "test:chrome-webworker": "aegir test -t webworker",
    "test:firefox": "aegir test -t browser -- --browser firefox",
    "test:firefox-webworker": "aegir test -t webworker -- --browser firefox",
    "test:electron-main": "aegir test -t electron-main",
    "dep-check": "aegir dep-check"
  },
  "dependencies": {
    "cborg": "^5.0.1",
    "multiformats": "^13.1.0"
  },
  "devDependencies": {
    "@ipld/garbage": "^6.0.0",
    "aegir": "^48.0.1"
  }
}
import * as cborg from 'cborg'
import { CID } from 'multiformats/cid'

// https://github.com/ipfs/go-ipfs/issues/3570#issuecomment-273931692
const CID_CBOR_TAG = 42

/**
 * @template T
 * @typedef {import('multiformats/codecs/interface').ByteView<T>} ByteView
 */

/**
 * @template T
 * @typedef {import('multiformats/codecs/interface').ArrayBufferView<T>} ArrayBufferView
 */

/**
 * @template T
 * @param {ByteView<T> | ArrayBufferView<T>} buf
 * @returns {ByteView<T>}
 */
export function toByteView (buf) {
  if (buf instanceof ArrayBuffer) {
    return new Uint8Array(buf, 0, buf.byteLength)
  }

  return buf
}

/**
 * cidEncoder will receive all Objects during encode, it needs to filter out
 * anything that's not a CID and return `null` for that so it's encoded as
 * normal.
 *
 * @param {any} obj
 * @returns {cborg.Token[]|null}
 */
function cidEncoder (obj) {
  if (obj.asCID !== obj && obj['/'] !== obj.bytes) {
    return null // any other kind of object
  }
  const cid = CID.asCID(obj)
  /* c8 ignore next 4 */
  // very unlikely case, and it'll probably throw a recursion error in cborg
  if (!cid) {
    return null
  }
  const bytes = new Uint8Array(cid.bytes.byteLength + 1)
  bytes.set(cid.bytes, 1) // prefix is 0x00, for historical reasons
  return [
    new cborg.Token(cborg.Type.tag, CID_CBOR_TAG),
    new cborg.Token(cborg.Type.bytes, bytes)
  ]
}

// eslint-disable-next-line jsdoc/require-returns-check
/**
 * Intercept all `undefined` values from an object walk and reject the entire
 * object if we find one.
 *
 * @returns {null}
 */
function undefinedEncoder () {
  throw new Error('`undefined` is not supported by the IPLD Data Model and cannot be encoded')
}

/**
 * Intercept all `number` values from an object walk and reject the entire
 * object if we find something that doesn't fit the IPLD data model (NaN &
 * Infinity).
 *
 * @param {number} num
 * @returns {null}
 */
function numberEncoder (num) {
  if (Number.isNaN(num)) {
    throw new Error('`NaN` is not supported by the IPLD Data Model and cannot be encoded')
  }
  if (num === Infinity || num === -Infinity) {
    throw new Error('`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded')
  }
  return null
}

/**
 * @param {Map<any, any>} map
 * @returns {null}
 */
function mapEncoder (map) {
  for (const key of map.keys()) {
    if (typeof key !== 'string' || key.length === 0) {
      throw new Error('Non-string Map keys are not supported by the IPLD Data Model and cannot be encoded')
    }
  }
  return null
}

const _encodeOptions = {
  float64: true,
  typeEncoders: {
    Map: mapEncoder,
    Object: cidEncoder,
    undefined: undefinedEncoder,
    number: numberEncoder
  }
}

export const encodeOptions = {
  ..._encodeOptions,
  typeEncoders: {
    ..._encodeOptions.typeEncoders
  }
}

/**
 * @param {import('cborg').TagDecodeControl} decode
 * @returns {CID}
 */
function cidDecoder (decode) {
  const bytes = /** @type {Uint8Array} */ (decode())
  if (bytes[0] !== 0) {
    throw new Error('Invalid CID for CBOR tag 42; expected leading 0x00')
  }
  return CID.decode(bytes.subarray(1)) // ignore leading 0x00
}

const _decodeOptions = {
  allowIndefinite: false,
  coerceUndefinedToNull: true,
  allowNaN: false,
  allowInfinity: false,
  allowBigInt: true, // this will lead to BigInt for ints outside of
  // safe-integer range, which may surprise users
  strict: true,
  useMaps: false,
  rejectDuplicateMapKeys: true,
  /** @type {{ [tagNumber: number]: import('cborg').TagDecoder }} */
  tags: { [CID_CBOR_TAG]: cidDecoder }
}

export const decodeOptions = {
  ..._decodeOptions,
  tags: { ..._decodeOptions.tags }
}

export const name = 'dag-cbor'
export const code = 0x71

/**
 * @template T
 * @param {T} node
 * @returns {ByteView<T>}
 */
export const encode = (node) => cborg.encode(node, _encodeOptions)

/**
 * @template T
 * @param {ByteView<T> | ArrayBufferView<T>} data
 * @returns {T}
 */
export const decode = (data) => cborg.decode(toByteView(data), _decodeOptions)
/**
 * Utilities for short weierstrass curves, combined with noble-hashes.
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { weierstrass } from "./abstract/weierstrass.js";
/** connects noble-curves to noble-hashes */
export function getHash(hash) {
    return { hash };
}
/** @deprecated use new `weierstrass()` and `ecdsa()` methods */
export function createCurve(curveDef, defHash) {
    const create = (hash) => weierstrass({ ...curveDef, hash: hash });
    return { ...create(defHash), create };
}
//# sourceMappingURL=_shortw_utils.js.map/**
 * Methods for elliptic curve multiplication by scalars.
 * Contains wNAF, pippenger.
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { bitLen, bitMask, validateObject } from "../utils.js";
import { Field, FpInvertBatch, nLength, validateField } from "./modular.js";
const _0n = BigInt(0);
const _1n = BigInt(1);
export function negateCt(condition, item) {
    const neg = item.negate();
    return condition ? neg : item;
}
/**
 * Takes a bunch of Projective Points but executes only one
 * inversion on all of them. Inversion is very slow operation,
 * so this improves performance massively.
 * Optimization: converts a list of projective points to a list of identical points with Z=1.
 */
export function normalizeZ(c, points) {
    const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
    return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
}
function validateW(W, bits) {
    if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
        throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);
}
function calcWOpts(W, scalarBits) {
    validateW(W, scalarBits);
    const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero
    const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero
    const maxNumber = 2 ** W; // W=8 256
    const mask = bitMask(W); // W=8 255 == mask 0b11111111
    const shiftBy = BigInt(W); // W=8 8
    return { windows, windowSize, mask, maxNumber, shiftBy };
}
function calcOffsets(n, window, wOpts) {
    const { windowSize, mask, maxNumber, shiftBy } = wOpts;
    let wbits = Number(n & mask); // extract W bits.
    let nextN = n >> shiftBy; // shift number by W bits.
    // What actually happens here:
    // const highestBit = Number(mask ^ (mask >> 1n));
    // let wbits2 = wbits - 1; // skip zero
    // if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);
    // split if bits > max: +224 => 256-32
    if (wbits > windowSize) {
        // we skip zero, which means instead of `>= size-1`, we do `> size`
        wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.
        nextN += _1n; // +256 (carry)
    }
    const offsetStart = window * windowSize;
    const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero
    const isZero = wbits === 0; // is current window slice a 0?
    const isNeg = wbits < 0; // is current window slice negative?
    const isNegF = window % 2 !== 0; // fake random statement for noise
    const offsetF = offsetStart; // fake offset for noise
    return { nextN, offset, isZero, isNeg, isNegF, offsetF };
}
function validateMSMPoints(points, c) {
    if (!Array.isArray(points))
        throw new Error('array expected');
    points.forEach((p, i) => {
        if (!(p instanceof c))
            throw new Error('invalid point at index ' + i);
    });
}
function validateMSMScalars(scalars, field) {
    if (!Array.isArray(scalars))
        throw new Error('array of scalars expected');
    scalars.forEach((s, i) => {
        if (!field.isValid(s))
            throw new Error('invalid scalar at index ' + i);
    });
}
// Since points in different groups cannot be equal (different object constructor),
// we can have single place to store precomputes.
// Allows to make points frozen / immutable.
const pointPrecomputes = new WeakMap();
const pointWindowSizes = new WeakMap();
function getW(P) {
    // To disable precomputes:
    // return 1;
    return pointWindowSizes.get(P) || 1;
}
function assert0(n) {
    if (n !== _0n)
        throw new Error('invalid wNAF');
}
/**
 * Elliptic curve multiplication of Point by scalar. Fragile.
 * Table generation takes **30MB of ram and 10ms on high-end CPU**,
 * but may take much longer on slow devices. Actual generation will happen on
 * first call of `multiply()`. By default, `BASE` point is precomputed.
 *
 * Scalars should always be less than curve order: this should be checked inside of a curve itself.
 * Creates precomputation tables for fast multiplication:
 * - private scalar is split by fixed size windows of W bits
 * - every window point is collected from window's table & added to accumulator
 * - since windows are different, same point inside tables won't be accessed more than once per calc
 * - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)
 * - +1 window is neccessary for wNAF
 * - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication
 *
 * @todo Research returning 2d JS array of windows, instead of a single window.
 * This would allow windows to be in different memory locations
 */
export class wNAF {
    // Parametrized with a given Point class (not individual point)
    constructor(Point, bits) {
        this.BASE = Point.BASE;
        this.ZERO = Point.ZERO;
        this.Fn = Point.Fn;
        this.bits = bits;
    }
    // non-const time multiplication ladder
    _unsafeLadder(elm, n, p = this.ZERO) {
        let d = elm;
        while (n > _0n) {
            if (n & _1n)
                p = p.add(d);
            d = d.double();
            n >>= _1n;
        }
        return p;
    }
    /**
     * Creates a wNAF precomputation window. Used for caching.
     * Default window size is set by `utils.precompute()` and is equal to 8.
     * Number of precomputed points depends on the curve size:
     * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
     * - 𝑊 is the window size
     * - 𝑛 is the bitlength of the curve order.
     * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
     * @param point Point instance
     * @param W window size
     * @returns precomputed point tables flattened to a single array
     */
    precomputeWindow(point, W) {
        const { windows, windowSize } = calcWOpts(W, this.bits);
        const points = [];
        let p = point;
        let base = p;
        for (let window = 0; window < windows; window++) {
            base = p;
            points.push(base);
            // i=1, bc we skip 0
            for (let i = 1; i < windowSize; i++) {
                base = base.add(p);
                points.push(base);
            }
            p = base.double();
        }
        return points;
    }
    /**
     * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
     * More compact implementation:
     * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
     * @returns real and fake (for const-time) points
     */
    wNAF(W, precomputes, n) {
        // Scalar should be smaller than field order
        if (!this.Fn.isValid(n))
            throw new Error('invalid scalar');
        // Accumulators
        let p = this.ZERO;
        let f = this.BASE;
        // This code was first written with assumption that 'f' and 'p' will never be infinity point:
        // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,
        // there is negate now: it is possible that negated element from low value
        // would be the same as high element, which will create carry into next window.
        // It's not obvious how this can fail, but still worth investigating later.
        const wo = calcWOpts(W, this.bits);
        for (let window = 0; window < wo.windows; window++) {
            // (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise
            const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
            n = nextN;
            if (isZero) {
                // bits are 0: add garbage to fake point
                // Important part for const-time getPublicKey: add random "noise" point to f.
                f = f.add(negateCt(isNegF, precomputes[offsetF]));
            }
            else {
                // bits are 1: add to result point
                p = p.add(negateCt(isNeg, precomputes[offset]));
            }
        }
        assert0(n);
        // Return both real and fake points: JIT won't eliminate f.
        // At this point there is a way to F be infinity-point even if p is not,
        // which makes it less const-time: around 1 bigint multiply.
        return { p, f };
    }
    /**
     * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
     * @param acc accumulator point to add result of multiplication
     * @returns point
     */
    wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
        const wo = calcWOpts(W, this.bits);
        for (let window = 0; window < wo.windows; window++) {
            if (n === _0n)
                break; // Early-exit, skip 0 value
            const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
            n = nextN;
            if (isZero) {
                // Window bits are 0: skip processing.
                // Move to next window.
                continue;
            }
            else {
                const item = precomputes[offset];
                acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM
            }
        }
        assert0(n);
        return acc;
    }
    getPrecomputes(W, point, transform) {
        // Calculate precomputes on a first run, reuse them after
        let comp = pointPrecomputes.get(point);
        if (!comp) {
            comp = this.precomputeWindow(point, W);
            if (W !== 1) {
                // Doing transform outside of if brings 15% perf hit
                if (typeof transform === 'function')
                    comp = transform(comp);
                pointPrecomputes.set(point, comp);
            }
        }
        return comp;
    }
    cached(point, scalar, transform) {
        const W = getW(point);
        return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
    }
    unsafe(point, scalar, transform, prev) {
        const W = getW(point);
        if (W === 1)
            return this._unsafeLadder(point, scalar, prev); // For W=1 ladder is ~x2 faster
        return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
    }
    // We calculate precomputes for elliptic curve point multiplication
    // using windowed method. This specifies window size and
    // stores precomputed values. Usually only base point would be precomputed.
    createCache(P, W) {
        validateW(W, this.bits);
        pointWindowSizes.set(P, W);
        pointPrecomputes.delete(P);
    }
    hasCache(elm) {
        return getW(elm) !== 1;
    }
}
/**
 * Endomorphism-specific multiplication for Koblitz curves.
 * Cost: 128 dbl, 0-256 adds.
 */
export function mulEndoUnsafe(Point, point, k1, k2) {
    let acc = point;
    let p1 = Point.ZERO;
    let p2 = Point.ZERO;
    while (k1 > _0n || k2 > _0n) {
        if (k1 & _1n)
            p1 = p1.add(acc);
        if (k2 & _1n)
            p2 = p2.add(acc);
        acc = acc.double();
        k1 >>= _1n;
        k2 >>= _1n;
    }
    return { p1, p2 };
}
/**
 * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).
 * 30x faster vs naive addition on L=4096, 10x faster than precomputes.
 * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.
 * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.
 * @param c Curve Point constructor
 * @param fieldN field over CURVE.N - important that it's not over CURVE.P
 * @param points array of L curve points
 * @param scalars array of L scalars (aka secret keys / bigints)
 */
export function pippenger(c, fieldN, points, scalars) {
    // If we split scalars by some window (let's say 8 bits), every chunk will only
    // take 256 buckets even if there are 4096 scalars, also re-uses double.
    // TODO:
    // - https://eprint.iacr.org/2024/750.pdf
    // - https://tches.iacr.org/index.php/TCHES/article/view/10287
    // 0 is accepted in scalars
    validateMSMPoints(points, c);
    validateMSMScalars(scalars, fieldN);
    const plength = points.length;
    const slength = scalars.length;
    if (plength !== slength)
        throw new Error('arrays of points and scalars must have equal length');
    // if (plength === 0) throw new Error('array must be of length >= 2');
    const zero = c.ZERO;
    const wbits = bitLen(BigInt(plength));
    let windowSize = 1; // bits
    if (wbits > 12)
        windowSize = wbits - 3;
    else if (wbits > 4)
        windowSize = wbits - 2;
    else if (wbits > 0)
        windowSize = 2;
    const MASK = bitMask(windowSize);
    const buckets = new Array(Number(MASK) + 1).fill(zero); // +1 for zero array
    const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;
    let sum = zero;
    for (let i = lastBits; i >= 0; i -= windowSize) {
        buckets.fill(zero);
        for (let j = 0; j < slength; j++) {
            const scalar = scalars[j];
            const wbits = Number((scalar >> BigInt(i)) & MASK);
            buckets[wbits] = buckets[wbits].add(points[j]);
        }
        let resI = zero; // not using this will do small speed-up, but will lose ct
        // Skip first bucket, because it is zero
        for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {
            sumI = sumI.add(buckets[j]);
            resI = resI.add(sumI);
        }
        sum = sum.add(resI);
        if (i !== 0)
            for (let j = 0; j < windowSize; j++)
                sum = sum.double();
    }
    return sum;
}
/**
 * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).
 * @param c Curve Point constructor
 * @param fieldN field over CURVE.N - important that it's not over CURVE.P
 * @param points array of L curve points
 * @returns function which multiplies points with scaars
 */
export function precomputeMSMUnsafe(c, fieldN, points, windowSize) {
    /**
     * Performance Analysis of Window-based Precomputation
     *
     * Base Case (256-bit scalar, 8-bit window):
     * - Standard precomputation requires:
     *   - 31 additions per scalar × 256 scalars = 7,936 ops
     *   - Plus 255 summary additions = 8,191 total ops
     *   Note: Summary additions can be optimized via accumulator
     *
     * Chunked Precomputation Analysis:
     * - Using 32 chunks requires:
     *   - 255 additions per chunk
     *   - 256 doublings
     *   - Total: (255 × 32) + 256 = 8,416 ops
     *
     * Memory Usage Comparison:
     * Window Size | Standard Points | Chunked Points
     * ------------|-----------------|---------------
     *     4-bit   |     520         |      15
     *     8-bit   |    4,224        |     255
     *    10-bit   |   13,824        |   1,023
     *    16-bit   |  557,056        |  65,535
     *
     * Key Advantages:
     * 1. Enables larger window sizes due to reduced memory overhead
     * 2. More efficient for smaller scalar counts:
     *    - 16 chunks: (16 × 255) + 256 = 4,336 ops
     *    - ~2x faster than standard 8,191 ops
     *
     * Limitations:
     * - Not suitable for plain precomputes (requires 256 constant doublings)
     * - Performance degrades with larger scalar counts:
     *   - Optimal for ~256 scalars
     *   - Less efficient for 4096+ scalars (Pippenger preferred)
     */
    validateW(windowSize, fieldN.BITS);
    validateMSMPoints(points, c);
    const zero = c.ZERO;
    const tableSize = 2 ** windowSize - 1; // table size (without zero)
    const chunks = Math.ceil(fieldN.BITS / windowSize); // chunks of item
    const MASK = bitMask(windowSize);
    const tables = points.map((p) => {
        const res = [];
        for (let i = 0, acc = p; i < tableSize; i++) {
            res.push(acc);
            acc = acc.add(p);
        }
        return res;
    });
    return (scalars) => {
        validateMSMScalars(scalars, fieldN);
        if (scalars.length > points.length)
            throw new Error('array of scalars must be smaller than array of points');
        let res = zero;
        for (let i = 0; i < chunks; i++) {
            // No need to double if accumulator is still zero.
            if (res !== zero)
                for (let j = 0; j < windowSize; j++)
                    res = res.double();
            const shiftBy = BigInt(chunks * windowSize - (i + 1) * windowSize);
            for (let j = 0; j < scalars.length; j++) {
                const n = scalars[j];
                const curr = Number((n >> shiftBy) & MASK);
                if (!curr)
                    continue; // skip zero scalars chunks
                res = res.add(tables[j][curr - 1]);
            }
        }
        return res;
    };
}
// TODO: remove
/** @deprecated */
export function validateBasic(curve) {
    validateField(curve.Fp);
    validateObject(curve, {
        n: 'bigint',
        h: 'bigint',
        Gx: 'field',
        Gy: 'field',
    }, {
        nBitLength: 'isSafeInteger',
        nByteLength: 'isSafeInteger',
    });
    // Set defaults
    return Object.freeze({
        ...nLength(curve.n, curve.nBitLength),
        ...curve,
        ...{ p: curve.Fp.ORDER },
    });
}
function createField(order, field, isLE) {
    if (field) {
        if (field.ORDER !== order)
            throw new Error('Field.ORDER must match order: Fp == p, Fn == n');
        validateField(field);
        return field;
    }
    else {
        return Field(order, { isLE });
    }
}
/** Validates CURVE opts and creates fields */
export function _createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
    if (FpFnLE === undefined)
        FpFnLE = type === 'edwards';
    if (!CURVE || typeof CURVE !== 'object')
        throw new Error(`expected valid ${type} CURVE object`);
    for (const p of ['p', 'n', 'h']) {
        const val = CURVE[p];
        if (!(typeof val === 'bigint' && val > _0n))
            throw new Error(`CURVE.${p} must be positive bigint`);
    }
    const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);
    const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
    const _b = type === 'weierstrass' ? 'b' : 'd';
    const params = ['Gx', 'Gy', 'a', _b];
    for (const p of params) {
        // @ts-ignore
        if (!Fp.isValid(CURVE[p]))
            throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
    }
    CURVE = Object.freeze(Object.assign({}, CURVE));
    return { CURVE, Fp, Fn };
}
//# sourceMappingURL=curve.js.mapimport { _validateObject, abytes, bytesToNumberBE, concatBytes, isBytes, isHash, utf8ToBytes, } from "../utils.js";
import { FpInvertBatch, mod } from "./modular.js";
// Octet Stream to Integer. "spec" implementation of os2ip is 2.5x slower vs bytesToNumberBE.
const os2ip = bytesToNumberBE;
// Integer to Octet Stream (numberToBytesBE)
function i2osp(value, length) {
    anum(value);
    anum(length);
    if (value < 0 || value >= 1 << (8 * length))
        throw new Error('invalid I2OSP input: ' + value);
    const res = Array.from({ length }).fill(0);
    for (let i = length - 1; i >= 0; i--) {
        res[i] = value & 0xff;
        value >>>= 8;
    }
    return new Uint8Array(res);
}
function strxor(a, b) {
    const arr = new Uint8Array(a.length);
    for (let i = 0; i < a.length; i++) {
        arr[i] = a[i] ^ b[i];
    }
    return arr;
}
function anum(item) {
    if (!Number.isSafeInteger(item))
        throw new Error('number expected');
}
function normDST(DST) {
    if (!isBytes(DST) && typeof DST !== 'string')
        throw new Error('DST must be Uint8Array or string');
    return typeof DST === 'string' ? utf8ToBytes(DST) : DST;
}
/**
 * Produces a uniformly random byte string using a cryptographic hash function H that outputs b bits.
 * [RFC 9380 5.3.1](https://www.rfc-editor.org/rfc/rfc9380#section-5.3.1).
 */
export function expand_message_xmd(msg, DST, lenInBytes, H) {
    abytes(msg);
    anum(lenInBytes);
    DST = normDST(DST);
    // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3
    if (DST.length > 255)
        DST = H(concatBytes(utf8ToBytes('H2C-OVERSIZE-DST-'), DST));
    const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H;
    const ell = Math.ceil(lenInBytes / b_in_bytes);
    if (lenInBytes > 65535 || ell > 255)
        throw new Error('expand_message_xmd: invalid lenInBytes');
    const DST_prime = concatBytes(DST, i2osp(DST.length, 1));
    const Z_pad = i2osp(0, r_in_bytes);
    const l_i_b_str = i2osp(lenInBytes, 2); // len_in_bytes_str
    const b = new Array(ell);
    const b_0 = H(concatBytes(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));
    b[0] = H(concatBytes(b_0, i2osp(1, 1), DST_prime));
    for (let i = 1; i <= ell; i++) {
        const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime];
        b[i] = H(concatBytes(...args));
    }
    const pseudo_random_bytes = concatBytes(...b);
    return pseudo_random_bytes.slice(0, lenInBytes);
}
/**
 * Produces a uniformly random byte string using an extendable-output function (XOF) H.
 * 1. The collision resistance of H MUST be at least k bits.
 * 2. H MUST be an XOF that has been proved indifferentiable from
 *    a random oracle under a reasonable cryptographic assumption.
 * [RFC 9380 5.3.2](https://www.rfc-editor.org/rfc/rfc9380#section-5.3.2).
 */
export function expand_message_xof(msg, DST, lenInBytes, k, H) {
    abytes(msg);
    anum(lenInBytes);
    DST = normDST(DST);
    // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3
    // DST = H('H2C-OVERSIZE-DST-' || a_very_long_DST, Math.ceil((lenInBytes * k) / 8));
    if (DST.length > 255) {
        const dkLen = Math.ceil((2 * k) / 8);
        DST = H.create({ dkLen }).update(utf8ToBytes('H2C-OVERSIZE-DST-')).update(DST).digest();
    }
    if (lenInBytes > 65535 || DST.length > 255)
        throw new Error('expand_message_xof: invalid lenInBytes');
    return (H.create({ dkLen: lenInBytes })
        .update(msg)
        .update(i2osp(lenInBytes, 2))
        // 2. DST_prime = DST || I2OSP(len(DST), 1)
        .update(DST)
        .update(i2osp(DST.length, 1))
        .digest());
}
/**
 * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F.
 * [RFC 9380 5.2](https://www.rfc-editor.org/rfc/rfc9380#section-5.2).
 * @param msg a byte string containing the message to hash
 * @param count the number of elements of F to output
 * @param options `{DST: string, p: bigint, m: number, k: number, expand: 'xmd' | 'xof', hash: H}`, see above
 * @returns [u_0, ..., u_(count - 1)], a list of field elements.
 */
export function hash_to_field(msg, count, options) {
    _validateObject(options, {
        p: 'bigint',
        m: 'number',
        k: 'number',
        hash: 'function',
    });
    const { p, k, m, hash, expand, DST } = options;
    if (!isHash(options.hash))
        throw new Error('expected valid hash');
    abytes(msg);
    anum(count);
    const log2p = p.toString(2).length;
    const L = Math.ceil((log2p + k) / 8); // section 5.1 of ietf draft link above
    const len_in_bytes = count * m * L;
    let prb; // pseudo_random_bytes
    if (expand === 'xmd') {
        prb = expand_message_xmd(msg, DST, len_in_bytes, hash);
    }
    else if (expand === 'xof') {
        prb = expand_message_xof(msg, DST, len_in_bytes, k, hash);
    }
    else if (expand === '_internal_pass') {
        // for internal tests only
        prb = msg;
    }
    else {
        throw new Error('expand must be "xmd" or "xof"');
    }
    const u = new Array(count);
    for (let i = 0; i < count; i++) {
        const e = new Array(m);
        for (let j = 0; j < m; j++) {
            const elm_offset = L * (j + i * m);
            const tv = prb.subarray(elm_offset, elm_offset + L);
            e[j] = mod(os2ip(tv), p);
        }
        u[i] = e;
    }
    return u;
}
export function isogenyMap(field, map) {
    // Make same order as in spec
    const coeff = map.map((i) => Array.from(i).reverse());
    return (x, y) => {
        const [xn, xd, yn, yd] = coeff.map((val) => val.reduce((acc, i) => field.add(field.mul(acc, x), i)));
        // 6.6.3
        // Exceptional cases of iso_map are inputs that cause the denominator of
        // either rational function to evaluate to zero; such cases MUST return
        // the identity point on E.
        const [xd_inv, yd_inv] = FpInvertBatch(field, [xd, yd], true);
        x = field.mul(xn, xd_inv); // xNum / xDen
        y = field.mul(y, field.mul(yn, yd_inv)); // y * (yNum / yDev)
        return { x, y };
    };
}
export const _DST_scalar = utf8ToBytes('HashToScalar-');
/** Creates hash-to-curve methods from EC Point and mapToCurve function. See {@link H2CHasher}. */
export function createHasher(Point, mapToCurve, defaults) {
    if (typeof mapToCurve !== 'function')
        throw new Error('mapToCurve() must be defined');
    function map(num) {
        return Point.fromAffine(mapToCurve(num));
    }
    function clear(initial) {
        const P = initial.clearCofactor();
        if (P.equals(Point.ZERO))
            return Point.ZERO; // zero will throw in assert
        P.assertValidity();
        return P;
    }
    return {
        defaults,
        hashToCurve(msg, options) {
            const opts = Object.assign({}, defaults, options);
            const u = hash_to_field(msg, 2, opts);
            const u0 = map(u[0]);
            const u1 = map(u[1]);
            return clear(u0.add(u1));
        },
        encodeToCurve(msg, options) {
            const optsDst = defaults.encodeDST ? { DST: defaults.encodeDST } : {};
            const opts = Object.assign({}, defaults, optsDst, options);
            const u = hash_to_field(msg, 1, opts);
            const u0 = map(u[0]);
            return clear(u0);
        },
        /** See {@link H2CHasher} */
        mapToCurve(scalars) {
            if (!Array.isArray(scalars))
                throw new Error('expected array of bigints');
            for (const i of scalars)
                if (typeof i !== 'bigint')
                    throw new Error('expected array of bigints');
            return clear(map(scalars));
        },
        // hash_to_scalar can produce 0: https://www.rfc-editor.org/errata/eid8393
        // RFC 9380, draft-irtf-cfrg-bbs-signatures-08
        hashToScalar(msg, options) {
            // @ts-ignore
            const N = Point.Fn.ORDER;
            const opts = Object.assign({}, defaults, { p: N, m: 1, DST: _DST_scalar }, options);
            return hash_to_field(msg, 1, opts)[0][0];
        },
    };
}
//# sourceMappingURL=hash-to-curve.js.map/**
 * Utils for modular division and fields.
 * Field over 11 is a finite (Galois) field is integer number operations `mod 11`.
 * There is no division: it is replaced by modular multiplicative inverse.
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { _validateObject, anumber, bitMask, bytesToNumberBE, bytesToNumberLE, ensureBytes, numberToBytesBE, numberToBytesLE, } from "../utils.js";
// prettier-ignore
const _0n = BigInt(0), _1n = BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3);
// prettier-ignore
const _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5), _7n = /* @__PURE__ */ BigInt(7);
// prettier-ignore
const _8n = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9), _16n = /* @__PURE__ */ BigInt(16);
// Calculates a modulo b
export function mod(a, b) {
    const result = a % b;
    return result >= _0n ? result : b + result;
}
/**
 * Efficiently raise num to power and do modular division.
 * Unsafe in some contexts: uses ladder, so can expose bigint bits.
 * @example
 * pow(2n, 6n, 11n) // 64n % 11n == 9n
 */
export function pow(num, power, modulo) {
    return FpPow(Field(modulo), num, power);
}
/** Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)` */
export function pow2(x, power, modulo) {
    let res = x;
    while (power-- > _0n) {
        res *= res;
        res %= modulo;
    }
    return res;
}
/**
 * Inverses number over modulo.
 * Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).
 */
export function invert(number, modulo) {
    if (number === _0n)
        throw new Error('invert: expected non-zero number');
    if (modulo <= _0n)
        throw new Error('invert: expected positive modulus, got ' + modulo);
    // Fermat's little theorem "CT-like" version inv(n) = n^(m-2) mod m is 30x slower.
    let a = mod(number, modulo);
    let b = modulo;
    // prettier-ignore
    let x = _0n, y = _1n, u = _1n, v = _0n;
    while (a !== _0n) {
        // JIT applies optimization if those two lines follow each other
        const q = b / a;
        const r = b % a;
        const m = x - u * q;
        const n = y - v * q;
        // prettier-ignore
        b = a, a = r, x = u, y = v, u = m, v = n;
    }
    const gcd = b;
    if (gcd !== _1n)
        throw new Error('invert: does not exist');
    return mod(x, modulo);
}
function assertIsSquare(Fp, root, n) {
    if (!Fp.eql(Fp.sqr(root), n))
        throw new Error('Cannot find square root');
}
// Not all roots are possible! Example which will throw:
// const NUM =
// n = 72057594037927816n;
// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));
function sqrt3mod4(Fp, n) {
    const p1div4 = (Fp.ORDER + _1n) / _4n;
    const root = Fp.pow(n, p1div4);
    assertIsSquare(Fp, root, n);
    return root;
}
function sqrt5mod8(Fp, n) {
    const p5div8 = (Fp.ORDER - _5n) / _8n;
    const n2 = Fp.mul(n, _2n);
    const v = Fp.pow(n2, p5div8);
    const nv = Fp.mul(n, v);
    const i = Fp.mul(Fp.mul(nv, _2n), v);
    const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
    assertIsSquare(Fp, root, n);
    return root;
}
// Based on RFC9380, Kong algorithm
// prettier-ignore
function sqrt9mod16(P) {
    const Fp_ = Field(P);
    const tn = tonelliShanks(P);
    const c1 = tn(Fp_, Fp_.neg(Fp_.ONE)); //  1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F
    const c2 = tn(Fp_, c1); //  2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F
    const c3 = tn(Fp_, Fp_.neg(c1)); //  3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F
    const c4 = (P + _7n) / _16n; //  4. c4 = (q + 7) / 16        # Integer arithmetic
    return (Fp, n) => {
        let tv1 = Fp.pow(n, c4); //  1. tv1 = x^c4
        let tv2 = Fp.mul(tv1, c1); //  2. tv2 = c1 * tv1
        const tv3 = Fp.mul(tv1, c2); //  3. tv3 = c2 * tv1
        const tv4 = Fp.mul(tv1, c3); //  4. tv4 = c3 * tv1
        const e1 = Fp.eql(Fp.sqr(tv2), n); //  5.  e1 = (tv2^2) == x
        const e2 = Fp.eql(Fp.sqr(tv3), n); //  6.  e2 = (tv3^2) == x
        tv1 = Fp.cmov(tv1, tv2, e1); //  7. tv1 = CMOV(tv1, tv2, e1)  # Select tv2 if (tv2^2) == x
        tv2 = Fp.cmov(tv4, tv3, e2); //  8. tv2 = CMOV(tv4, tv3, e2)  # Select tv3 if (tv3^2) == x
        const e3 = Fp.eql(Fp.sqr(tv2), n); //  9.  e3 = (tv2^2) == x
        const root = Fp.cmov(tv1, tv2, e3); // 10.  z = CMOV(tv1, tv2, e3)   # Select sqrt from tv1 & tv2
        assertIsSquare(Fp, root, n);
        return root;
    };
}
/**
 * Tonelli-Shanks square root search algorithm.
 * 1. https://eprint.iacr.org/2012/685.pdf (page 12)
 * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks
 * @param P field order
 * @returns function that takes field Fp (created from P) and number n
 */
export function tonelliShanks(P) {
    // Initialization (precomputation).
    // Caching initialization could boost perf by 7%.
    if (P < _3n)
        throw new Error('sqrt is not defined for small field');
    // Factor P - 1 = Q * 2^S, where Q is odd
    let Q = P - _1n;
    let S = 0;
    while (Q % _2n === _0n) {
        Q /= _2n;
        S++;
    }
    // Find the first quadratic non-residue Z >= 2
    let Z = _2n;
    const _Fp = Field(P);
    while (FpLegendre(_Fp, Z) === 1) {
        // Basic primality test for P. After x iterations, chance of
        // not finding quadratic non-residue is 2^x, so 2^1000.
        if (Z++ > 1000)
            throw new Error('Cannot find square root: probably non-prime P');
    }
    // Fast-path; usually done before Z, but we do "primality test".
    if (S === 1)
        return sqrt3mod4;
    // Slow-path
    // TODO: test on Fp2 and others
    let cc = _Fp.pow(Z, Q); // c = z^Q
    const Q1div2 = (Q + _1n) / _2n;
    return function tonelliSlow(Fp, n) {
        if (Fp.is0(n))
            return n;
        // Check if n is a quadratic residue using Legendre symbol
        if (FpLegendre(Fp, n) !== 1)
            throw new Error('Cannot find square root');
        // Initialize variables for the main loop
        let M = S;
        let c = Fp.mul(Fp.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp
        let t = Fp.pow(n, Q); // t = n^Q, first guess at the fudge factor
        let R = Fp.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root
        // Main loop
        // while t != 1
        while (!Fp.eql(t, Fp.ONE)) {
            if (Fp.is0(t))
                return Fp.ZERO; // if t=0 return R=0
            let i = 1;
            // Find the smallest i >= 1 such that t^(2^i) ≡ 1 (mod P)
            let t_tmp = Fp.sqr(t); // t^(2^1)
            while (!Fp.eql(t_tmp, Fp.ONE)) {
                i++;
                t_tmp = Fp.sqr(t_tmp); // t^(2^2)...
                if (i === M)
                    throw new Error('Cannot find square root');
            }
            // Calculate the exponent for b: 2^(M - i - 1)
            const exponent = _1n << BigInt(M - i - 1); // bigint is important
            const b = Fp.pow(c, exponent); // b = 2^(M - i - 1)
            // Update variables
            M = i;
            c = Fp.sqr(b); // c = b^2
            t = Fp.mul(t, c); // t = (t * b^2)
            R = Fp.mul(R, b); // R = R*b
        }
        return R;
    };
}
/**
 * Square root for a finite field. Will try optimized versions first:
 *
 * 1. P ≡ 3 (mod 4)
 * 2. P ≡ 5 (mod 8)
 * 3. P ≡ 9 (mod 16)
 * 4. Tonelli-Shanks algorithm
 *
 * Different algorithms can give different roots, it is up to user to decide which one they want.
 * For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).
 */
export function FpSqrt(P) {
    // P ≡ 3 (mod 4) => √n = n^((P+1)/4)
    if (P % _4n === _3n)
        return sqrt3mod4;
    // P ≡ 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf
    if (P % _8n === _5n)
        return sqrt5mod8;
    // P ≡ 9 (mod 16) => Kong algorithm, page 11 of https://eprint.iacr.org/2012/685.pdf (algorithm 4)
    if (P % _16n === _9n)
        return sqrt9mod16(P);
    // Tonelli-Shanks algorithm
    return tonelliShanks(P);
}
// Little-endian check for first LE bit (last BE bit);
export const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n;
// prettier-ignore
const FIELD_FIELDS = [
    'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',
    'eql', 'add', 'sub', 'mul', 'pow', 'div',
    'addN', 'subN', 'mulN', 'sqrN'
];
export function validateField(field) {
    const initial = {
        ORDER: 'bigint',
        MASK: 'bigint',
        BYTES: 'number',
        BITS: 'number',
    };
    const opts = FIELD_FIELDS.reduce((map, val) => {
        map[val] = 'function';
        return map;
    }, initial);
    _validateObject(field, opts);
    // const max = 16384;
    // if (field.BYTES < 1 || field.BYTES > max) throw new Error('invalid field');
    // if (field.BITS < 1 || field.BITS > 8 * max) throw new Error('invalid field');
    return field;
}
// Generic field functions
/**
 * Same as `pow` but for Fp: non-constant-time.
 * Unsafe in some contexts: uses ladder, so can expose bigint bits.
 */
export function FpPow(Fp, num, power) {
    if (power < _0n)
        throw new Error('invalid exponent, negatives unsupported');
    if (power === _0n)
        return Fp.ONE;
    if (power === _1n)
        return num;
    let p = Fp.ONE;
    let d = num;
    while (power > _0n) {
        if (power & _1n)
            p = Fp.mul(p, d);
        d = Fp.sqr(d);
        power >>= _1n;
    }
    return p;
}
/**
 * Efficiently invert an array of Field elements.
 * Exception-free. Will return `undefined` for 0 elements.
 * @param passZero map 0 to 0 (instead of undefined)
 */
export function FpInvertBatch(Fp, nums, passZero = false) {
    const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : undefined);
    // Walk from first to last, multiply them by each other MOD p
    const multipliedAcc = nums.reduce((acc, num, i) => {
        if (Fp.is0(num))
            return acc;
        inverted[i] = acc;
        return Fp.mul(acc, num);
    }, Fp.ONE);
    // Invert last element
    const invertedAcc = Fp.inv(multipliedAcc);
    // Walk from last to first, multiply them by inverted each other MOD p
    nums.reduceRight((acc, num, i) => {
        if (Fp.is0(num))
            return acc;
        inverted[i] = Fp.mul(acc, inverted[i]);
        return Fp.mul(acc, num);
    }, invertedAcc);
    return inverted;
}
// TODO: remove
export function FpDiv(Fp, lhs, rhs) {
    return Fp.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, Fp.ORDER) : Fp.inv(rhs));
}
/**
 * Legendre symbol.
 * Legendre constant is used to calculate Legendre symbol (a | p)
 * which denotes the value of a^((p-1)/2) (mod p).
 *
 * * (a | p) ≡ 1    if a is a square (mod p), quadratic residue
 * * (a | p) ≡ -1   if a is not a square (mod p), quadratic non residue
 * * (a | p) ≡ 0    if a ≡ 0 (mod p)
 */
export function FpLegendre(Fp, n) {
    // We can use 3rd argument as optional cache of this value
    // but seems unneeded for now. The operation is very fast.
    const p1mod2 = (Fp.ORDER - _1n) / _2n;
    const powered = Fp.pow(n, p1mod2);
    const yes = Fp.eql(powered, Fp.ONE);
    const zero = Fp.eql(powered, Fp.ZERO);
    const no = Fp.eql(powered, Fp.neg(Fp.ONE));
    if (!yes && !zero && !no)
        throw new Error('invalid Legendre symbol result');
    return yes ? 1 : zero ? 0 : -1;
}
// This function returns True whenever the value x is a square in the field F.
export function FpIsSquare(Fp, n) {
    const l = FpLegendre(Fp, n);
    return l === 1;
}
// CURVE.n lengths
export function nLength(n, nBitLength) {
    // Bit size, byte size of CURVE.n
    if (nBitLength !== undefined)
        anumber(nBitLength);
    const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;
    const nByteLength = Math.ceil(_nBitLength / 8);
    return { nBitLength: _nBitLength, nByteLength };
}
/**
 * Creates a finite field. Major performance optimizations:
 * * 1. Denormalized operations like mulN instead of mul.
 * * 2. Identical object shape: never add or remove keys.
 * * 3. `Object.freeze`.
 * Fragile: always run a benchmark on a change.
 * Security note: operations don't check 'isValid' for all elements for performance reasons,
 * it is caller responsibility to check this.
 * This is low-level code, please make sure you know what you're doing.
 *
 * Note about field properties:
 * * CHARACTERISTIC p = prime number, number of elements in main subgroup.
 * * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.
 *
 * @param ORDER field order, probably prime, or could be composite
 * @param bitLen how many bits the field consumes
 * @param isLE (default: false) if encoding / decoding should be in little-endian
 * @param redef optional faster redefinitions of sqrt and other methods
 */
export function Field(ORDER, bitLenOrOpts, // TODO: use opts only in v2?
isLE = false, opts = {}) {
    if (ORDER <= _0n)
        throw new Error('invalid field: expected ORDER > 0, got ' + ORDER);
    let _nbitLength = undefined;
    let _sqrt = undefined;
    let modFromBytes = false;
    let allowedLengths = undefined;
    if (typeof bitLenOrOpts === 'object' && bitLenOrOpts != null) {
        if (opts.sqrt || isLE)
            throw new Error('cannot specify opts in two arguments');
        const _opts = bitLenOrOpts;
        if (_opts.BITS)
            _nbitLength = _opts.BITS;
        if (_opts.sqrt)
            _sqrt = _opts.sqrt;
        if (typeof _opts.isLE === 'boolean')
            isLE = _opts.isLE;
        if (typeof _opts.modFromBytes === 'boolean')
            modFromBytes = _opts.modFromBytes;
        allowedLengths = _opts.allowedLengths;
    }
    else {
        if (typeof bitLenOrOpts === 'number')
            _nbitLength = bitLenOrOpts;
        if (opts.sqrt)
            _sqrt = opts.sqrt;
    }
    const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, _nbitLength);
    if (BYTES > 2048)
        throw new Error('invalid field: expected ORDER of <= 2048 bytes');
    let sqrtP; // cached sqrtP
    const f = Object.freeze({
        ORDER,
        isLE,
        BITS,
        BYTES,
        MASK: bitMask(BITS),
        ZERO: _0n,
        ONE: _1n,
        allowedLengths: allowedLengths,
        create: (num) => mod(num, ORDER),
        isValid: (num) => {
            if (typeof num !== 'bigint')
                throw new Error('invalid field element: expected bigint, got ' + typeof num);
            return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible
        },
        is0: (num) => num === _0n,
        // is valid and invertible
        isValidNot0: (num) => !f.is0(num) && f.isValid(num),
        isOdd: (num) => (num & _1n) === _1n,
        neg: (num) => mod(-num, ORDER),
        eql: (lhs, rhs) => lhs === rhs,
        sqr: (num) => mod(num * num, ORDER),
        add: (lhs, rhs) => mod(lhs + rhs, ORDER),
        sub: (lhs, rhs) => mod(lhs - rhs, ORDER),
        mul: (lhs, rhs) => mod(lhs * rhs, ORDER),
        pow: (num, power) => FpPow(f, num, power),
        div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),
        // Same as above, but doesn't normalize
        sqrN: (num) => num * num,
        addN: (lhs, rhs) => lhs + rhs,
        subN: (lhs, rhs) => lhs - rhs,
        mulN: (lhs, rhs) => lhs * rhs,
        inv: (num) => invert(num, ORDER),
        sqrt: _sqrt ||
            ((n) => {
                if (!sqrtP)
                    sqrtP = FpSqrt(ORDER);
                return sqrtP(f, n);
            }),
        toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),
        fromBytes: (bytes, skipValidation = true) => {
            if (allowedLengths) {
                if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
                    throw new Error('Field.fromBytes: expected ' + allowedLengths + ' bytes, got ' + bytes.length);
                }
                const padded = new Uint8Array(BYTES);
                // isLE add 0 to right, !isLE to the left.
                padded.set(bytes, isLE ? 0 : padded.length - bytes.length);
                bytes = padded;
            }
            if (bytes.length !== BYTES)
                throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);
            let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
            if (modFromBytes)
                scalar = mod(scalar, ORDER);
            if (!skipValidation)
                if (!f.isValid(scalar))
                    throw new Error('invalid field element: outside of range 0..ORDER');
            // NOTE: we don't validate scalar here, please use isValid. This done such way because some
            // protocol may allow non-reduced scalar that reduced later or changed some other way.
            return scalar;
        },
        // TODO: we don't need it here, move out to separate fn
        invertBatch: (lst) => FpInvertBatch(f, lst),
        // We can't move this out because Fp6, Fp12 implement it
        // and it's unclear what to return in there.
        cmov: (a, b, c) => (c ? b : a),
    });
    return Object.freeze(f);
}
// Generic random scalar, we can do same for other fields if via Fp2.mul(Fp2.ONE, Fp2.random)?
// This allows unsafe methods like ignore bias or zero. These unsafe, but often used in different protocols (if deterministic RNG).
// which mean we cannot force this via opts.
// Not sure what to do with randomBytes, we can accept it inside opts if wanted.
// Probably need to export getMinHashLength somewhere?
// random(bytes?: Uint8Array, unsafeAllowZero = false, unsafeAllowBias = false) {
//   const LEN = !unsafeAllowBias ? getMinHashLength(ORDER) : BYTES;
//   if (bytes === undefined) bytes = randomBytes(LEN); // _opts.randomBytes?
//   const num = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
//   // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0
//   const reduced = unsafeAllowZero ? mod(num, ORDER) : mod(num, ORDER - _1n) + _1n;
//   return reduced;
// },
export function FpSqrtOdd(Fp, elm) {
    if (!Fp.isOdd)
        throw new Error("Field doesn't have isOdd");
    const root = Fp.sqrt(elm);
    return Fp.isOdd(root) ? root : Fp.neg(root);
}
export function FpSqrtEven(Fp, elm) {
    if (!Fp.isOdd)
        throw new Error("Field doesn't have isOdd");
    const root = Fp.sqrt(elm);
    return Fp.isOdd(root) ? Fp.neg(root) : root;
}
/**
 * "Constant-time" private key generation utility.
 * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field).
 * Which makes it slightly more biased, less secure.
 * @deprecated use `mapKeyToField` instead
 */
export function hashToPrivateScalar(hash, groupOrder, isLE = false) {
    hash = ensureBytes('privateHash', hash);
    const hashLen = hash.length;
    const minLen = nLength(groupOrder).nByteLength + 8;
    if (minLen < 24 || hashLen < minLen || hashLen > 1024)
        throw new Error('hashToPrivateScalar: expected ' + minLen + '-1024 bytes of input, got ' + hashLen);
    const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash);
    return mod(num, groupOrder - _1n) + _1n;
}
/**
 * Returns total number of bytes consumed by the field element.
 * For example, 32 bytes for usual 256-bit weierstrass curve.
 * @param fieldOrder number of field elements, usually CURVE.n
 * @returns byte length of field
 */
export function getFieldBytesLength(fieldOrder) {
    if (typeof fieldOrder !== 'bigint')
        throw new Error('field order must be bigint');
    const bitLength = fieldOrder.toString(2).length;
    return Math.ceil(bitLength / 8);
}
/**
 * Returns minimal amount of bytes that can be safely reduced
 * by field order.
 * Should be 2^-128 for 128-bit curve such as P256.
 * @param fieldOrder number of field elements, usually CURVE.n
 * @returns byte length of target hash
 */
export function getMinHashLength(fieldOrder) {
    const length = getFieldBytesLength(fieldOrder);
    return length + Math.ceil(length / 2);
}
/**
 * "Constant-time" private key generation utility.
 * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF
 * and convert them into private scalar, with the modulo bias being negligible.
 * Needs at least 48 bytes of input for 32-byte private key.
 * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/
 * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final
 * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5
 * @param hash hash output from SHA3 or a similar function
 * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)
 * @param isLE interpret hash bytes as LE num
 * @returns valid private scalar
 */
export function mapHashToField(key, fieldOrder, isLE = false) {
    const len = key.length;
    const fieldLen = getFieldBytesLength(fieldOrder);
    const minLen = getMinHashLength(fieldOrder);
    // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.
    if (len < 16 || len < minLen || len > 1024)
        throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);
    const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);
    // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0
    const reduced = mod(num, fieldOrder - _1n) + _1n;
    return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
}
//# sourceMappingURL=modular.js.map/**
 * Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.
 *
 * ### Design rationale for types
 *
 * * Interaction between classes from different curves should fail:
 *   `k256.Point.BASE.add(p256.Point.BASE)`
 * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime
 * * Different calls of `curve()` would return different classes -
 *   `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,
 *   it won't affect others
 *
 * TypeScript can't infer types for classes created inside a function. Classes is one instance
 * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create
 * unique type for every function call.
 *
 * We can use generic types via some param, like curve opts, but that would:
 *     1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)
 *     which is hard to debug.
 *     2. Params can be generic and we can't enforce them to be constant value:
 *     if somebody creates curve from non-constant params,
 *     it would be allowed to interact with other curves with non-constant params
 *
 * @todo https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { hmac as nobleHmac } from '@noble/hashes/hmac.js';
import { ahash } from '@noble/hashes/utils';
import { _validateObject, _abool2 as abool, _abytes2 as abytes, aInRange, bitLen, bitMask, bytesToHex, bytesToNumberBE, concatBytes, createHmacDrbg, ensureBytes, hexToBytes, inRange, isBytes, memoized, numberToHexUnpadded, randomBytes as randomBytesWeb, } from "../utils.js";
import { _createCurveFields, mulEndoUnsafe, negateCt, normalizeZ, pippenger, wNAF, } from "./curve.js";
import { Field, FpInvertBatch, getMinHashLength, mapHashToField, nLength, validateField, } from "./modular.js";
// We construct basis in such way that den is always positive and equals n, but num sign depends on basis (not on secret value)
const divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n) / den;
/**
 * Splits scalar for GLV endomorphism.
 */
export function _splitEndoScalar(k, basis, n) {
    // Split scalar into two such that part is ~half bits: `abs(part) < sqrt(N)`
    // Since part can be negative, we need to do this on point.
    // TODO: verifyScalar function which consumes lambda
    const [[a1, b1], [a2, b2]] = basis;
    const c1 = divNearest(b2 * k, n);
    const c2 = divNearest(-b1 * k, n);
    // |k1|/|k2| is < sqrt(N), but can be negative.
    // If we do `k1 mod N`, we'll get big scalar (`> sqrt(N)`): so, we do cheaper negation instead.
    let k1 = k - c1 * a1 - c2 * a2;
    let k2 = -c1 * b1 - c2 * b2;
    const k1neg = k1 < _0n;
    const k2neg = k2 < _0n;
    if (k1neg)
        k1 = -k1;
    if (k2neg)
        k2 = -k2;
    // Double check that resulting scalar less than half bits of N: otherwise wNAF will fail.
    // This should only happen on wrong basises. Also, math inside is too complex and I don't trust it.
    const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n; // Half bits of N
    if (k1 < _0n || k1 >= MAX_NUM || k2 < _0n || k2 >= MAX_NUM) {
        throw new Error('splitScalar (endomorphism): failed, k=' + k);
    }
    return { k1neg, k1, k2neg, k2 };
}
function validateSigFormat(format) {
    if (!['compact', 'recovered', 'der'].includes(format))
        throw new Error('Signature format must be "compact", "recovered", or "der"');
    return format;
}
function validateSigOpts(opts, def) {
    const optsn = {};
    for (let optName of Object.keys(def)) {
        // @ts-ignore
        optsn[optName] = opts[optName] === undefined ? def[optName] : opts[optName];
    }
    abool(optsn.lowS, 'lowS');
    abool(optsn.prehash, 'prehash');
    if (optsn.format !== undefined)
        validateSigFormat(optsn.format);
    return optsn;
}
export class DERErr extends Error {
    constructor(m = '') {
        super(m);
    }
}
/**
 * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:
 *
 *     [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]
 *
 * Docs: https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/, https://luca.ntop.org/Teaching/Appunti/asn1.html
 */
export const DER = {
    // asn.1 DER encoding utils
    Err: DERErr,
    // Basic building block is TLV (Tag-Length-Value)
    _tlv: {
        encode: (tag, data) => {
            const { Err: E } = DER;
            if (tag < 0 || tag > 256)
                throw new E('tlv.encode: wrong tag');
            if (data.length & 1)
                throw new E('tlv.encode: unpadded data');
            const dataLen = data.length / 2;
            const len = numberToHexUnpadded(dataLen);
            if ((len.length / 2) & 128)
                throw new E('tlv.encode: long form length too big');
            // length of length with long form flag
            const lenLen = dataLen > 127 ? numberToHexUnpadded((len.length / 2) | 128) : '';
            const t = numberToHexUnpadded(tag);
            return t + lenLen + len + data;
        },
        // v - value, l - left bytes (unparsed)
        decode(tag, data) {
            const { Err: E } = DER;
            let pos = 0;
            if (tag < 0 || tag > 256)
                throw new E('tlv.encode: wrong tag');
            if (data.length < 2 || data[pos++] !== tag)
                throw new E('tlv.decode: wrong tlv');
            const first = data[pos++];
            const isLong = !!(first & 128); // First bit of first length byte is flag for short/long form
            let length = 0;
            if (!isLong)
                length = first;
            else {
                // Long form: [longFlag(1bit), lengthLength(7bit), length (BE)]
                const lenLen = first & 127;
                if (!lenLen)
                    throw new E('tlv.decode(long): indefinite length not supported');
                if (lenLen > 4)
                    throw new E('tlv.decode(long): byte length is too big'); // this will overflow u32 in js
                const lengthBytes = data.subarray(pos, pos + lenLen);
                if (lengthBytes.length !== lenLen)
                    throw new E('tlv.decode: length bytes not complete');
                if (lengthBytes[0] === 0)
                    throw new E('tlv.decode(long): zero leftmost byte');
                for (const b of lengthBytes)
                    length = (length << 8) | b;
                pos += lenLen;
                if (length < 128)
                    throw new E('tlv.decode(long): not minimal encoding');
            }
            const v = data.subarray(pos, pos + length);
            if (v.length !== length)
                throw new E('tlv.decode: wrong value length');
            return { v, l: data.subarray(pos + length) };
        },
    },
    // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
    // since we always use positive integers here. It must always be empty:
    // - add zero byte if exists
    // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
    _int: {
        encode(num) {
            const { Err: E } = DER;
            if (num < _0n)
                throw new E('integer: negative integers are not allowed');
            let hex = numberToHexUnpadded(num);
            // Pad with zero byte if negative flag is present
            if (Number.parseInt(hex[0], 16) & 0b1000)
                hex = '00' + hex;
            if (hex.length & 1)
                throw new E('unexpected DER parsing assertion: unpadded hex');
            return hex;
        },
        decode(data) {
            const { Err: E } = DER;
            if (data[0] & 128)
                throw new E('invalid signature integer: negative');
            if (data[0] === 0x00 && !(data[1] & 128))
                throw new E('invalid signature integer: unnecessary leading zero');
            return bytesToNumberBE(data);
        },
    },
    toSig(hex) {
        // parse DER signature
        const { Err: E, _int: int, _tlv: tlv } = DER;
        const data = ensureBytes('signature', hex);
        const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);
        if (seqLeftBytes.length)
            throw new E('invalid signature: left bytes after parsing');
        const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);
        const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);
        if (sLeftBytes.length)
            throw new E('invalid signature: left bytes after parsing');
        return { r: int.decode(rBytes), s: int.decode(sBytes) };
    },
    hexFromSig(sig) {
        const { _tlv: tlv, _int: int } = DER;
        const rs = tlv.encode(0x02, int.encode(sig.r));
        const ss = tlv.encode(0x02, int.encode(sig.s));
        const seq = rs + ss;
        return tlv.encode(0x30, seq);
    },
};
// Be friendly to bad ECMAScript parsers by not using bigint literals
// prettier-ignore
const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4);
export function _normFnElement(Fn, key) {
    const { BYTES: expected } = Fn;
    let num;
    if (typeof key === 'bigint') {
        num = key;
    }
    else {
        let bytes = ensureBytes('private key', key);
        try {
            num = Fn.fromBytes(bytes);
        }
        catch (error) {
            throw new Error(`invalid private key: expected ui8a of size ${expected}, got ${typeof key}`);
        }
    }
    if (!Fn.isValidNot0(num))
        throw new Error('invalid private key: out of range [1..N-1]');
    return num;
}
/**
 * Creates weierstrass Point constructor, based on specified curve options.
 *
 * @example
```js
const opts = {
  p: BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff'),
  n: BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551'),
  h: BigInt(1),
  a: BigInt('0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc'),
  b: BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b'),
  Gx: BigInt('0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296'),
  Gy: BigInt('0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5'),
};
const p256_Point = weierstrass(opts);
```
 */
export function weierstrassN(params, extraOpts = {}) {
    const validated = _createCurveFields('weierstrass', params, extraOpts);
    const { Fp, Fn } = validated;
    let CURVE = validated.CURVE;
    const { h: cofactor, n: CURVE_ORDER } = CURVE;
    _validateObject(extraOpts, {}, {
        allowInfinityPoint: 'boolean',
        clearCofactor: 'function',
        isTorsionFree: 'function',
        fromBytes: 'function',
        toBytes: 'function',
        endo: 'object',
        wrapPrivateKey: 'boolean',
    });
    const { endo } = extraOpts;
    if (endo) {
        // validateObject(endo, { beta: 'bigint', splitScalar: 'function' });
        if (!Fp.is0(CURVE.a) || typeof endo.beta !== 'bigint' || !Array.isArray(endo.basises)) {
            throw new Error('invalid endo: expected "beta": bigint and "basises": array');
        }
    }
    const lengths = getWLengths(Fp, Fn);
    function assertCompressionIsSupported() {
        if (!Fp.isOdd)
            throw new Error('compression is not supported: Field does not have .isOdd()');
    }
    // Implements IEEE P1363 point encoding
    function pointToBytes(_c, point, isCompressed) {
        const { x, y } = point.toAffine();
        const bx = Fp.toBytes(x);
        abool(isCompressed, 'isCompressed');
        if (isCompressed) {
            assertCompressionIsSupported();
            const hasEvenY = !Fp.isOdd(y);
            return concatBytes(pprefix(hasEvenY), bx);
        }
        else {
            return concatBytes(Uint8Array.of(0x04), bx, Fp.toBytes(y));
        }
    }
    function pointFromBytes(bytes) {
        abytes(bytes, undefined, 'Point');
        const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths; // e.g. for 32-byte: 33, 65
        const length = bytes.length;
        const head = bytes[0];
        const tail = bytes.subarray(1);
        // No actual validation is done here: use .assertValidity()
        if (length === comp && (head === 0x02 || head === 0x03)) {
            const x = Fp.fromBytes(tail);
            if (!Fp.isValid(x))
                throw new Error('bad point: is not on curve, wrong x');
            const y2 = weierstrassEquation(x); // y² = x³ + ax + b
            let y;
            try {
                y = Fp.sqrt(y2); // y = y² ^ (p+1)/4
            }
            catch (sqrtError) {
                const err = sqrtError instanceof Error ? ': ' + sqrtError.message : '';
                throw new Error('bad point: is not on curve, sqrt error' + err);
            }
            assertCompressionIsSupported();
            const isYOdd = Fp.isOdd(y); // (y & _1n) === _1n;
            const isHeadOdd = (head & 1) === 1; // ECDSA-specific
            if (isHeadOdd !== isYOdd)
                y = Fp.neg(y);
            return { x, y };
        }
        else if (length === uncomp && head === 0x04) {
            // TODO: more checks
            const L = Fp.BYTES;
            const x = Fp.fromBytes(tail.subarray(0, L));
            const y = Fp.fromBytes(tail.subarray(L, L * 2));
            if (!isValidXY(x, y))
                throw new Error('bad point: is not on curve');
            return { x, y };
        }
        else {
            throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);
        }
    }
    const encodePoint = extraOpts.toBytes || pointToBytes;
    const decodePoint = extraOpts.fromBytes || pointFromBytes;
    function weierstrassEquation(x) {
        const x2 = Fp.sqr(x); // x * x
        const x3 = Fp.mul(x2, x); // x² * x
        return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b); // x³ + a * x + b
    }
    // TODO: move top-level
    /** Checks whether equation holds for given x, y: y² == x³ + ax + b */
    function isValidXY(x, y) {
        const left = Fp.sqr(y); // y²
        const right = weierstrassEquation(x); // x³ + ax + b
        return Fp.eql(left, right);
    }
    // Validate whether the passed curve params are valid.
    // Test 1: equation y² = x³ + ax + b should work for generator point.
    if (!isValidXY(CURVE.Gx, CURVE.Gy))
        throw new Error('bad curve params: generator point');
    // Test 2: discriminant Δ part should be non-zero: 4a³ + 27b² != 0.
    // Guarantees curve is genus-1, smooth (non-singular).
    const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n), _4n);
    const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));
    if (Fp.is0(Fp.add(_4a3, _27b2)))
        throw new Error('bad curve params: a or b');
    /** Asserts coordinate is valid: 0 <= n < Fp.ORDER. */
    function acoord(title, n, banZero = false) {
        if (!Fp.isValid(n) || (banZero && Fp.is0(n)))
            throw new Error(`bad point coordinate ${title}`);
        return n;
    }
    function aprjpoint(other) {
        if (!(other instanceof Point))
            throw new Error('ProjectivePoint expected');
    }
    function splitEndoScalarN(k) {
        if (!endo || !endo.basises)
            throw new Error('no endo');
        return _splitEndoScalar(k, endo.basises, Fn.ORDER);
    }
    // Memoized toAffine / validity check. They are heavy. Points are immutable.
    // Converts Projective point to affine (x, y) coordinates.
    // Can accept precomputed Z^-1 - for example, from invertBatch.
    // (X, Y, Z) ∋ (x=X/Z, y=Y/Z)
    const toAffineMemo = memoized((p, iz) => {
        const { X, Y, Z } = p;
        // Fast-path for normalized points
        if (Fp.eql(Z, Fp.ONE))
            return { x: X, y: Y };
        const is0 = p.is0();
        // If invZ was 0, we return zero point. However we still want to execute
        // all operations, so we replace invZ with a random number, 1.
        if (iz == null)
            iz = is0 ? Fp.ONE : Fp.inv(Z);
        const x = Fp.mul(X, iz);
        const y = Fp.mul(Y, iz);
        const zz = Fp.mul(Z, iz);
        if (is0)
            return { x: Fp.ZERO, y: Fp.ZERO };
        if (!Fp.eql(zz, Fp.ONE))
            throw new Error('invZ was invalid');
        return { x, y };
    });
    // NOTE: on exception this will crash 'cached' and no value will be set.
    // Otherwise true will be return
    const assertValidMemo = memoized((p) => {
        if (p.is0()) {
            // (0, 1, 0) aka ZERO is invalid in most contexts.
            // In BLS, ZERO can be serialized, so we allow it.
            // (0, 0, 0) is invalid representation of ZERO.
            if (extraOpts.allowInfinityPoint && !Fp.is0(p.Y))
                return;
            throw new Error('bad point: ZERO');
        }
        // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`
        const { x, y } = p.toAffine();
        if (!Fp.isValid(x) || !Fp.isValid(y))
            throw new Error('bad point: x or y not field elements');
        if (!isValidXY(x, y))
            throw new Error('bad point: equation left != right');
        if (!p.isTorsionFree())
            throw new Error('bad point: not in prime-order subgroup');
        return true;
    });
    function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) {
        k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);
        k1p = negateCt(k1neg, k1p);
        k2p = negateCt(k2neg, k2p);
        return k1p.add(k2p);
    }
    /**
     * Projective Point works in 3d / projective (homogeneous) coordinates:(X, Y, Z) ∋ (x=X/Z, y=Y/Z).
     * Default Point works in 2d / affine coordinates: (x, y).
     * We're doing calculations in projective, because its operations don't require costly inversion.
     */
    class Point {
        /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
        constructor(X, Y, Z) {
            this.X = acoord('x', X);
            this.Y = acoord('y', Y, true);
            this.Z = acoord('z', Z);
            Object.freeze(this);
        }
        static CURVE() {
            return CURVE;
        }
        /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
        static fromAffine(p) {
            const { x, y } = p || {};
            if (!p || !Fp.isValid(x) || !Fp.isValid(y))
                throw new Error('invalid affine point');
            if (p instanceof Point)
                throw new Error('projective point not allowed');
            // (0, 0) would've produced (0, 0, 1) - instead, we need (0, 1, 0)
            if (Fp.is0(x) && Fp.is0(y))
                return Point.ZERO;
            return new Point(x, y, Fp.ONE);
        }
        static fromBytes(bytes) {
            const P = Point.fromAffine(decodePoint(abytes(bytes, undefined, 'point')));
            P.assertValidity();
            return P;
        }
        static fromHex(hex) {
            return Point.fromBytes(ensureBytes('pointHex', hex));
        }
        get x() {
            return this.toAffine().x;
        }
        get y() {
            return this.toAffine().y;
        }
        /**
         *
         * @param windowSize
         * @param isLazy true will defer table computation until the first multiplication
         * @returns
         */
        precompute(windowSize = 8, isLazy = true) {
            wnaf.createCache(this, windowSize);
            if (!isLazy)
                this.multiply(_3n); // random number
            return this;
        }
        // TODO: return `this`
        /** A point on curve is valid if it conforms to equation. */
        assertValidity() {
            assertValidMemo(this);
        }
        hasEvenY() {
            const { y } = this.toAffine();
            if (!Fp.isOdd)
                throw new Error("Field doesn't support isOdd");
            return !Fp.isOdd(y);
        }
        /** Compare one point to another. */
        equals(other) {
            aprjpoint(other);
            const { X: X1, Y: Y1, Z: Z1 } = this;
            const { X: X2, Y: Y2, Z: Z2 } = other;
            const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
            const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
            return U1 && U2;
        }
        /** Flips point to one corresponding to (x, -y) in Affine coordinates. */
        negate() {
            return new Point(this.X, Fp.neg(this.Y), this.Z);
        }
        // Renes-Costello-Batina exception-free doubling formula.
        // There is 30% faster Jacobian formula, but it is not complete.
        // https://eprint.iacr.org/2015/1060, algorithm 3
        // Cost: 8M + 3S + 3*a + 2*b3 + 15add.
        double() {
            const { a, b } = CURVE;
            const b3 = Fp.mul(b, _3n);
            const { X: X1, Y: Y1, Z: Z1 } = this;
            let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore
            let t0 = Fp.mul(X1, X1); // step 1
            let t1 = Fp.mul(Y1, Y1);
            let t2 = Fp.mul(Z1, Z1);
            let t3 = Fp.mul(X1, Y1);
            t3 = Fp.add(t3, t3); // step 5
            Z3 = Fp.mul(X1, Z1);
            Z3 = Fp.add(Z3, Z3);
            X3 = Fp.mul(a, Z3);
            Y3 = Fp.mul(b3, t2);
            Y3 = Fp.add(X3, Y3); // step 10
            X3 = Fp.sub(t1, Y3);
            Y3 = Fp.add(t1, Y3);
            Y3 = Fp.mul(X3, Y3);
            X3 = Fp.mul(t3, X3);
            Z3 = Fp.mul(b3, Z3); // step 15
            t2 = Fp.mul(a, t2);
            t3 = Fp.sub(t0, t2);
            t3 = Fp.mul(a, t3);
            t3 = Fp.add(t3, Z3);
            Z3 = Fp.add(t0, t0); // step 20
            t0 = Fp.add(Z3, t0);
            t0 = Fp.add(t0, t2);
            t0 = Fp.mul(t0, t3);
            Y3 = Fp.add(Y3, t0);
            t2 = Fp.mul(Y1, Z1); // step 25
            t2 = Fp.add(t2, t2);
            t0 = Fp.mul(t2, t3);
            X3 = Fp.sub(X3, t0);
            Z3 = Fp.mul(t2, t1);
            Z3 = Fp.add(Z3, Z3); // step 30
            Z3 = Fp.add(Z3, Z3);
            return new Point(X3, Y3, Z3);
        }
        // Renes-Costello-Batina exception-free addition formula.
        // There is 30% faster Jacobian formula, but it is not complete.
        // https://eprint.iacr.org/2015/1060, algorithm 1
        // Cost: 12M + 0S + 3*a + 3*b3 + 23add.
        add(other) {
            aprjpoint(other);
            const { X: X1, Y: Y1, Z: Z1 } = this;
            const { X: X2, Y: Y2, Z: Z2 } = other;
            let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore
            const a = CURVE.a;
            const b3 = Fp.mul(CURVE.b, _3n);
            let t0 = Fp.mul(X1, X2); // step 1
            let t1 = Fp.mul(Y1, Y2);
            let t2 = Fp.mul(Z1, Z2);
            let t3 = Fp.add(X1, Y1);
            let t4 = Fp.add(X2, Y2); // step 5
            t3 = Fp.mul(t3, t4);
            t4 = Fp.add(t0, t1);
            t3 = Fp.sub(t3, t4);
            t4 = Fp.add(X1, Z1);
            let t5 = Fp.add(X2, Z2); // step 10
            t4 = Fp.mul(t4, t5);
            t5 = Fp.add(t0, t2);
            t4 = Fp.sub(t4, t5);
            t5 = Fp.add(Y1, Z1);
            X3 = Fp.add(Y2, Z2); // step 15
            t5 = Fp.mul(t5, X3);
            X3 = Fp.add(t1, t2);
            t5 = Fp.sub(t5, X3);
            Z3 = Fp.mul(a, t4);
            X3 = Fp.mul(b3, t2); // step 20
            Z3 = Fp.add(X3, Z3);
            X3 = Fp.sub(t1, Z3);
            Z3 = Fp.add(t1, Z3);
            Y3 = Fp.mul(X3, Z3);
            t1 = Fp.add(t0, t0); // step 25
            t1 = Fp.add(t1, t0);
            t2 = Fp.mul(a, t2);
            t4 = Fp.mul(b3, t4);
            t1 = Fp.add(t1, t2);
            t2 = Fp.sub(t0, t2); // step 30
            t2 = Fp.mul(a, t2);
            t4 = Fp.add(t4, t2);
            t0 = Fp.mul(t1, t4);
            Y3 = Fp.add(Y3, t0);
            t0 = Fp.mul(t5, t4); // step 35
            X3 = Fp.mul(t3, X3);
            X3 = Fp.sub(X3, t0);
            t0 = Fp.mul(t3, t1);
            Z3 = Fp.mul(t5, Z3);
            Z3 = Fp.add(Z3, t0); // step 40
            return new Point(X3, Y3, Z3);
        }
        subtract(other) {
            return this.add(other.negate());
        }
        is0() {
            return this.equals(Point.ZERO);
        }
        /**
         * Constant time multiplication.
         * Uses wNAF method. Windowed method may be 10% faster,
         * but takes 2x longer to generate and consumes 2x memory.
         * Uses precomputes when available.
         * Uses endomorphism for Koblitz curves.
         * @param scalar by which the point would be multiplied
         * @returns New point
         */
        multiply(scalar) {
            const { endo } = extraOpts;
            if (!Fn.isValidNot0(scalar))
                throw new Error('invalid scalar: out of range'); // 0 is invalid
            let point, fake; // Fake point is used to const-time mult
            const mul = (n) => wnaf.cached(this, n, (p) => normalizeZ(Point, p));
            /** See docs for {@link EndomorphismOpts} */
            if (endo) {
                const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);
                const { p: k1p, f: k1f } = mul(k1);
                const { p: k2p, f: k2f } = mul(k2);
                fake = k1f.add(k2f);
                point = finishEndo(endo.beta, k1p, k2p, k1neg, k2neg);
            }
            else {
                const { p, f } = mul(scalar);
                point = p;
                fake = f;
            }
            // Normalize `z` for both points, but return only real one
            return normalizeZ(Point, [point, fake])[0];
        }
        /**
         * Non-constant-time multiplication. Uses double-and-add algorithm.
         * It's faster, but should only be used when you don't care about
         * an exposed secret key e.g. sig verification, which works over *public* keys.
         */
        multiplyUnsafe(sc) {
            const { endo } = extraOpts;
            const p = this;
            if (!Fn.isValid(sc))
                throw new Error('invalid scalar: out of range'); // 0 is valid
            if (sc === _0n || p.is0())
                return Point.ZERO;
            if (sc === _1n)
                return p; // fast-path
            if (wnaf.hasCache(this))
                return this.multiply(sc);
            if (endo) {
                const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);
                const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2); // 30% faster vs wnaf.unsafe
                return finishEndo(endo.beta, p1, p2, k1neg, k2neg);
            }
            else {
                return wnaf.unsafe(p, sc);
            }
        }
        multiplyAndAddUnsafe(Q, a, b) {
            const sum = this.multiplyUnsafe(a).add(Q.multiplyUnsafe(b));
            return sum.is0() ? undefined : sum;
        }
        /**
         * Converts Projective point to affine (x, y) coordinates.
         * @param invertedZ Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch
         */
        toAffine(invertedZ) {
            return toAffineMemo(this, invertedZ);
        }
        /**
         * Checks whether Point is free of torsion elements (is in prime subgroup).
         * Always torsion-free for cofactor=1 curves.
         */
        isTorsionFree() {
            const { isTorsionFree } = extraOpts;
            if (cofactor === _1n)
                return true;
            if (isTorsionFree)
                return isTorsionFree(Point, this);
            return wnaf.unsafe(this, CURVE_ORDER).is0();
        }
        clearCofactor() {
            const { clearCofactor } = extraOpts;
            if (cofactor === _1n)
                return this; // Fast-path
            if (clearCofactor)
                return clearCofactor(Point, this);
            return this.multiplyUnsafe(cofactor);
        }
        isSmallOrder() {
            // can we use this.clearCofactor()?
            return this.multiplyUnsafe(cofactor).is0();
        }
        toBytes(isCompressed = true) {
            abool(isCompressed, 'isCompressed');
            this.assertValidity();
            return encodePoint(Point, this, isCompressed);
        }
        toHex(isCompressed = true) {
            return bytesToHex(this.toBytes(isCompressed));
        }
        toString() {
            return `<Point ${this.is0() ? 'ZERO' : this.toHex()}>`;
        }
        // TODO: remove
        get px() {
            return this.X;
        }
        get py() {
            return this.X;
        }
        get pz() {
            return this.Z;
        }
        toRawBytes(isCompressed = true) {
            return this.toBytes(isCompressed);
        }
        _setWindowSize(windowSize) {
            this.precompute(windowSize);
        }
        static normalizeZ(points) {
            return normalizeZ(Point, points);
        }
        static msm(points, scalars) {
            return pippenger(Point, Fn, points, scalars);
        }
        static fromPrivateKey(privateKey) {
            return Point.BASE.multiply(_normFnElement(Fn, privateKey));
        }
    }
    // base / generator point
    Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
    // zero / infinity / identity point
    Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); // 0, 1, 0
    // math field
    Point.Fp = Fp;
    // scalar field
    Point.Fn = Fn;
    const bits = Fn.BITS;
    const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);
    Point.BASE.precompute(8); // Enable precomputes. Slows down first publicKey computation by 20ms.
    return Point;
}
// Points start with byte 0x02 when y is even; otherwise 0x03
function pprefix(hasEvenY) {
    return Uint8Array.of(hasEvenY ? 0x02 : 0x03);
}
/**
 * Implementation of the Shallue and van de Woestijne method for any weierstrass curve.
 * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular.
 * b = True and y = sqrt(u / v) if (u / v) is square in F, and
 * b = False and y = sqrt(Z * (u / v)) otherwise.
 * @param Fp
 * @param Z
 * @returns
 */
export function SWUFpSqrtRatio(Fp, Z) {
    // Generic implementation
    const q = Fp.ORDER;
    let l = _0n;
    for (let o = q - _1n; o % _2n === _0n; o /= _2n)
        l += _1n;
    const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1.
    // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<.
    // 2n ** c1 == 2n << (c1-1)
    const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n);
    const _2n_pow_c1 = _2n_pow_c1_1 * _2n;
    const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1)  # Integer arithmetic
    const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2            # Integer arithmetic
    const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1                # Integer arithmetic
    const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1)                  # Integer arithmetic
    const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2
    const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2)
    let sqrtRatio = (u, v) => {
        let tv1 = c6; // 1. tv1 = c6
        let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4
        let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2
        tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v
        let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3
        tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3
        tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2
        tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v
        tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u
        let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2
        tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5
        let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1
        tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7
        tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1
        tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR)
        tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR)
        // 17. for i in (c1, c1 - 1, ..., 2):
        for (let i = c1; i > _1n; i--) {
            let tv5 = i - _2n; // 18.    tv5 = i - 2
            tv5 = _2n << (tv5 - _1n); // 19.    tv5 = 2^tv5
            let tvv5 = Fp.pow(tv4, tv5); // 20.    tv5 = tv4^tv5
            const e1 = Fp.eql(tvv5, Fp.ONE); // 21.    e1 = tv5 == 1
            tv2 = Fp.mul(tv3, tv1); // 22.    tv2 = tv3 * tv1
            tv1 = Fp.mul(tv1, tv1); // 23.    tv1 = tv1 * tv1
            tvv5 = Fp.mul(tv4, tv1); // 24.    tv5 = tv4 * tv1
            tv3 = Fp.cmov(tv2, tv3, e1); // 25.    tv3 = CMOV(tv2, tv3, e1)
            tv4 = Fp.cmov(tvv5, tv4, e1); // 26.    tv4 = CMOV(tv5, tv4, e1)
        }
        return { isValid: isQR, value: tv3 };
    };
    if (Fp.ORDER % _4n === _3n) {
        // sqrt_ratio_3mod4(u, v)
        const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4     # Integer arithmetic
        const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z)
        sqrtRatio = (u, v) => {
            let tv1 = Fp.sqr(v); // 1. tv1 = v^2
            const tv2 = Fp.mul(u, v); // 2. tv2 = u * v
            tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2
            let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1
            y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2
            const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2
            const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v
            const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u
            let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR)
            return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2
        };
    }
    // No curves uses that
    // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8
    return sqrtRatio;
}
/**
 * Simplified Shallue-van de Woestijne-Ulas Method
 * https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2
 */
export function mapToCurveSimpleSWU(Fp, opts) {
    validateField(Fp);
    const { A, B, Z } = opts;
    if (!Fp.isValid(A) || !Fp.isValid(B) || !Fp.isValid(Z))
        throw new Error('mapToCurveSimpleSWU: invalid opts');
    const sqrtRatio = SWUFpSqrtRatio(Fp, Z);
    if (!Fp.isOdd)
        throw new Error('Field does not have .isOdd()');
    // Input: u, an element of F.
    // Output: (x, y), a point on E.
    return (u) => {
        // prettier-ignore
        let tv1, tv2, tv3, tv4, tv5, tv6, x, y;
        tv1 = Fp.sqr(u); // 1.  tv1 = u^2
        tv1 = Fp.mul(tv1, Z); // 2.  tv1 = Z * tv1
        tv2 = Fp.sqr(tv1); // 3.  tv2 = tv1^2
        tv2 = Fp.add(tv2, tv1); // 4.  tv2 = tv2 + tv1
        tv3 = Fp.add(tv2, Fp.ONE); // 5.  tv3 = tv2 + 1
        tv3 = Fp.mul(tv3, B); // 6.  tv3 = B * tv3
        tv4 = Fp.cmov(Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7.  tv4 = CMOV(Z, -tv2, tv2 != 0)
        tv4 = Fp.mul(tv4, A); // 8.  tv4 = A * tv4
        tv2 = Fp.sqr(tv3); // 9.  tv2 = tv3^2
        tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2
        tv5 = Fp.mul(tv6, A); // 11. tv5 = A * tv6
        tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5
        tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3
        tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4
        tv5 = Fp.mul(tv6, B); // 15. tv5 = B * tv6
        tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5
        x = Fp.mul(tv1, tv3); // 17.   x = tv1 * tv3
        const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6)
        y = Fp.mul(tv1, u); // 19.   y = tv1 * u  -> Z * u^3 * y1
        y = Fp.mul(y, value); // 20.   y = y * y1
        x = Fp.cmov(x, tv3, isValid); // 21.   x = CMOV(x, tv3, is_gx1_square)
        y = Fp.cmov(y, value, isValid); // 22.   y = CMOV(y, y1, is_gx1_square)
        const e1 = Fp.isOdd(u) === Fp.isOdd(y); // 23.  e1 = sgn0(u) == sgn0(y)
        y = Fp.cmov(Fp.neg(y), y, e1); // 24.   y = CMOV(-y, y, e1)
        const tv4_inv = FpInvertBatch(Fp, [tv4], true)[0];
        x = Fp.mul(x, tv4_inv); // 25.   x = x / tv4
        return { x, y };
    };
}
function getWLengths(Fp, Fn) {
    return {
        secretKey: Fn.BYTES,
        publicKey: 1 + Fp.BYTES,
        publicKeyUncompressed: 1 + 2 * Fp.BYTES,
        publicKeyHasPrefix: true,
        signature: 2 * Fn.BYTES,
    };
}
/**
 * Sometimes users only need getPublicKey, getSharedSecret, and secret key handling.
 * This helper ensures no signature functionality is present. Less code, smaller bundle size.
 */
export function ecdh(Point, ecdhOpts = {}) {
    const { Fn } = Point;
    const randomBytes_ = ecdhOpts.randomBytes || randomBytesWeb;
    const lengths = Object.assign(getWLengths(Point.Fp, Fn), { seed: getMinHashLength(Fn.ORDER) });
    function isValidSecretKey(secretKey) {
        try {
            return !!_normFnElement(Fn, secretKey);
        }
        catch (error) {
            return false;
        }
    }
    function isValidPublicKey(publicKey, isCompressed) {
        const { publicKey: comp, publicKeyUncompressed } = lengths;
        try {
            const l = publicKey.length;
            if (isCompressed === true && l !== comp)
                return false;
            if (isCompressed === false && l !== publicKeyUncompressed)
                return false;
            return !!Point.fromBytes(publicKey);
        }
        catch (error) {
            return false;
        }
    }
    /**
     * Produces cryptographically secure secret key from random of size
     * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.
     */
    function randomSecretKey(seed = randomBytes_(lengths.seed)) {
        return mapHashToField(abytes(seed, lengths.seed, 'seed'), Fn.ORDER);
    }
    /**
     * Computes public key for a secret key. Checks for validity of the secret key.
     * @param isCompressed whether to return compact (default), or full key
     * @returns Public key, full when isCompressed=false; short when isCompressed=true
     */
    function getPublicKey(secretKey, isCompressed = true) {
        return Point.BASE.multiply(_normFnElement(Fn, secretKey)).toBytes(isCompressed);
    }
    function keygen(seed) {
        const secretKey = randomSecretKey(seed);
        return { secretKey, publicKey: getPublicKey(secretKey) };
    }
    /**
     * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.
     */
    function isProbPub(item) {
        if (typeof item === 'bigint')
            return false;
        if (item instanceof Point)
            return true;
        const { secretKey, publicKey, publicKeyUncompressed } = lengths;
        if (Fn.allowedLengths || secretKey === publicKey)
            return undefined;
        const l = ensureBytes('key', item).length;
        return l === publicKey || l === publicKeyUncompressed;
    }
    /**
     * ECDH (Elliptic Curve Diffie Hellman).
     * Computes shared public key from secret key A and public key B.
     * Checks: 1) secret key validity 2) shared key is on-curve.
     * Does NOT hash the result.
     * @param isCompressed whether to return compact (default), or full key
     * @returns shared public key
     */
    function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {
        if (isProbPub(secretKeyA) === true)
            throw new Error('first arg must be private key');
        if (isProbPub(publicKeyB) === false)
            throw new Error('second arg must be public key');
        const s = _normFnElement(Fn, secretKeyA);
        const b = Point.fromHex(publicKeyB); // checks for being on-curve
        return b.multiply(s).toBytes(isCompressed);
    }
    const utils = {
        isValidSecretKey,
        isValidPublicKey,
        randomSecretKey,
        // TODO: remove
        isValidPrivateKey: isValidSecretKey,
        randomPrivateKey: randomSecretKey,
        normPrivateKeyToScalar: (key) => _normFnElement(Fn, key),
        precompute(windowSize = 8, point = Point.BASE) {
            return point.precompute(windowSize, false);
        },
    };
    return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point, utils, lengths });
}
/**
 * Creates ECDSA signing interface for given elliptic curve `Point` and `hash` function.
 * We need `hash` for 2 features:
 * 1. Message prehash-ing. NOT used if `sign` / `verify` are called with `prehash: false`
 * 2. k generation in `sign`, using HMAC-drbg(hash)
 *
 * ECDSAOpts are only rarely needed.
 *
 * @example
 * ```js
 * const p256_Point = weierstrass(...);
 * const p256_sha256 = ecdsa(p256_Point, sha256);
 * const p256_sha224 = ecdsa(p256_Point, sha224);
 * const p256_sha224_r = ecdsa(p256_Point, sha224, { randomBytes: (length) => { ... } });
 * ```
 */
export function ecdsa(Point, hash, ecdsaOpts = {}) {
    ahash(hash);
    _validateObject(ecdsaOpts, {}, {
        hmac: 'function',
        lowS: 'boolean',
        randomBytes: 'function',
        bits2int: 'function',
        bits2int_modN: 'function',
    });
    const randomBytes = ecdsaOpts.randomBytes || randomBytesWeb;
    const hmac = ecdsaOpts.hmac ||
        ((key, ...msgs) => nobleHmac(hash, key, concatBytes(...msgs)));
    const { Fp, Fn } = Point;
    const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;
    const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);
    const defaultSigOpts = {
        prehash: false,
        lowS: typeof ecdsaOpts.lowS === 'boolean' ? ecdsaOpts.lowS : false,
        format: undefined, //'compact' as ECDSASigFormat,
        extraEntropy: false,
    };
    const defaultSigOpts_format = 'compact';
    function isBiggerThanHalfOrder(number) {
        const HALF = CURVE_ORDER >> _1n;
        return number > HALF;
    }
    function validateRS(title, num) {
        if (!Fn.isValidNot0(num))
            throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);
        return num;
    }
    function validateSigLength(bytes, format) {
        validateSigFormat(format);
        const size = lengths.signature;
        const sizer = format === 'compact' ? size : format === 'recovered' ? size + 1 : undefined;
        return abytes(bytes, sizer, `${format} signature`);
    }
    /**
     * ECDSA signature with its (r, s) properties. Supports compact, recovered & DER representations.
     */
    class Signature {
        constructor(r, s, recovery) {
            this.r = validateRS('r', r); // r in [1..N-1];
            this.s = validateRS('s', s); // s in [1..N-1];
            if (recovery != null)
                this.recovery = recovery;
            Object.freeze(this);
        }
        static fromBytes(bytes, format = defaultSigOpts_format) {
            validateSigLength(bytes, format);
            let recid;
            if (format === 'der') {
                const { r, s } = DER.toSig(abytes(bytes));
                return new Signature(r, s);
            }
            if (format === 'recovered') {
                recid = bytes[0];
                format = 'compact';
                bytes = bytes.subarray(1);
            }
            const L = Fn.BYTES;
            const r = bytes.subarray(0, L);
            const s = bytes.subarray(L, L * 2);
            return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);
        }
        static fromHex(hex, format) {
            return this.fromBytes(hexToBytes(hex), format);
        }
        addRecoveryBit(recovery) {
            return new Signature(this.r, this.s, recovery);
        }
        recoverPublicKey(messageHash) {
            const FIELD_ORDER = Fp.ORDER;
            const { r, s, recovery: rec } = this;
            if (rec == null || ![0, 1, 2, 3].includes(rec))
                throw new Error('recovery id invalid');
            // ECDSA recovery is hard for cofactor > 1 curves.
            // In sign, `r = q.x mod n`, and here we recover q.x from r.
            // While recovering q.x >= n, we need to add r+n for cofactor=1 curves.
            // However, for cofactor>1, r+n may not get q.x:
            // r+n*i would need to be done instead where i is unknown.
            // To easily get i, we either need to:
            // a. increase amount of valid recid values (4, 5...); OR
            // b. prohibit non-prime-order signatures (recid > 1).
            const hasCofactor = CURVE_ORDER * _2n < FIELD_ORDER;
            if (hasCofactor && rec > 1)
                throw new Error('recovery id is ambiguous for h>1 curve');
            const radj = rec === 2 || rec === 3 ? r + CURVE_ORDER : r;
            if (!Fp.isValid(radj))
                throw new Error('recovery id 2 or 3 invalid');
            const x = Fp.toBytes(radj);
            const R = Point.fromBytes(concatBytes(pprefix((rec & 1) === 0), x));
            const ir = Fn.inv(radj); // r^-1
            const h = bits2int_modN(ensureBytes('msgHash', messageHash)); // Truncate hash
            const u1 = Fn.create(-h * ir); // -hr^-1
            const u2 = Fn.create(s * ir); // sr^-1
            // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1). unsafe is fine: there is no private data.
            const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));
            if (Q.is0())
                throw new Error('point at infinify');
            Q.assertValidity();
            return Q;
        }
        // Signatures should be low-s, to prevent malleability.
        hasHighS() {
            return isBiggerThanHalfOrder(this.s);
        }
        toBytes(format = defaultSigOpts_format) {
            validateSigFormat(format);
            if (format === 'der')
                return hexToBytes(DER.hexFromSig(this));
            const r = Fn.toBytes(this.r);
            const s = Fn.toBytes(this.s);
            if (format === 'recovered') {
                if (this.recovery == null)
                    throw new Error('recovery bit must be present');
                return concatBytes(Uint8Array.of(this.recovery), r, s);
            }
            return concatBytes(r, s);
        }
        toHex(format) {
            return bytesToHex(this.toBytes(format));
        }
        // TODO: remove
        assertValidity() { }
        static fromCompact(hex) {
            return Signature.fromBytes(ensureBytes('sig', hex), 'compact');
        }
        static fromDER(hex) {
            return Signature.fromBytes(ensureBytes('sig', hex), 'der');
        }
        normalizeS() {
            return this.hasHighS() ? new Signature(this.r, Fn.neg(this.s), this.recovery) : this;
        }
        toDERRawBytes() {
            return this.toBytes('der');
        }
        toDERHex() {
            return bytesToHex(this.toBytes('der'));
        }
        toCompactRawBytes() {
            return this.toBytes('compact');
        }
        toCompactHex() {
            return bytesToHex(this.toBytes('compact'));
        }
    }
    // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.
    // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.
    // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.
    // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors
    const bits2int = ecdsaOpts.bits2int ||
        function bits2int_def(bytes) {
            // Our custom check "just in case", for protection against DoS
            if (bytes.length > 8192)
                throw new Error('input is too large');
            // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)
            // for some cases, since bytes.length * 8 is not actual bitLength.
            const num = bytesToNumberBE(bytes); // check for == u8 done here
            const delta = bytes.length * 8 - fnBits; // truncate to nBitLength leftmost bits
            return delta > 0 ? num >> BigInt(delta) : num;
        };
    const bits2int_modN = ecdsaOpts.bits2int_modN ||
        function bits2int_modN_def(bytes) {
            return Fn.create(bits2int(bytes)); // can't use bytesToNumberBE here
        };
    // Pads output with zero as per spec
    const ORDER_MASK = bitMask(fnBits);
    /** Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. */
    function int2octets(num) {
        // IMPORTANT: the check ensures working for case `Fn.BYTES != Fn.BITS * 8`
        aInRange('num < 2^' + fnBits, num, _0n, ORDER_MASK);
        return Fn.toBytes(num);
    }
    function validateMsgAndHash(message, prehash) {
        abytes(message, undefined, 'message');
        return prehash ? abytes(hash(message), undefined, 'prehashed message') : message;
    }
    /**
     * Steps A, D of RFC6979 3.2.
     * Creates RFC6979 seed; converts msg/privKey to numbers.
     * Used only in sign, not in verify.
     *
     * Warning: we cannot assume here that message has same amount of bytes as curve order,
     * this will be invalid at least for P521. Also it can be bigger for P224 + SHA256.
     */
    function prepSig(message, privateKey, opts) {
        if (['recovered', 'canonical'].some((k) => k in opts))
            throw new Error('sign() legacy options not supported');
        const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);
        message = validateMsgAndHash(message, prehash); // RFC6979 3.2 A: h1 = H(m)
        // We can't later call bits2octets, since nested bits2int is broken for curves
        // with fnBits % 8 !== 0. Because of that, we unwrap it here as int2octets call.
        // const bits2octets = (bits) => int2octets(bits2int_modN(bits))
        const h1int = bits2int_modN(message);
        const d = _normFnElement(Fn, privateKey); // validate secret key, convert to bigint
        const seedArgs = [int2octets(d), int2octets(h1int)];
        // extraEntropy. RFC6979 3.6: additional k' (optional).
        if (extraEntropy != null && extraEntropy !== false) {
            // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')
            // gen random bytes OR pass as-is
            const e = extraEntropy === true ? randomBytes(lengths.secretKey) : extraEntropy;
            seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes
        }
        const seed = concatBytes(...seedArgs); // Step D of RFC6979 3.2
        const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash!
        // Converts signature params into point w r/s, checks result for validity.
        // To transform k => Signature:
        // q = k⋅G
        // r = q.x mod n
        // s = k^-1(m + rd) mod n
        // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to
        // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:
        // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT
        function k2sig(kBytes) {
            // RFC 6979 Section 3.2, step 3: k = bits2int(T)
            // Important: all mod() calls here must be done over N
            const k = bits2int(kBytes); // mod n, not mod p
            if (!Fn.isValidNot0(k))
                return; // Valid scalars (including k) must be in 1..N-1
            const ik = Fn.inv(k); // k^-1 mod n
            const q = Point.BASE.multiply(k).toAffine(); // q = k⋅G
            const r = Fn.create(q.x); // r = q.x mod n
            if (r === _0n)
                return;
            const s = Fn.create(ik * Fn.create(m + r * d)); // Not using blinding here, see comment above
            if (s === _0n)
                return;
            let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n)
            let normS = s;
            if (lowS && isBiggerThanHalfOrder(s)) {
                normS = Fn.neg(s); // if lowS was passed, ensure s is always
                recovery ^= 1; // // in the bottom half of N
            }
            return new Signature(r, normS, recovery); // use normS, not s
        }
        return { seed, k2sig };
    }
    /**
     * Signs message hash with a secret key.
     *
     * ```
     * sign(m, d) where
     *   k = rfc6979_hmac_drbg(m, d)
     *   (x, y) = G × k
     *   r = x mod n
     *   s = (m + dr) / k mod n
     * ```
     */
    function sign(message, secretKey, opts = {}) {
        message = ensureBytes('message', message);
        const { seed, k2sig } = prepSig(message, secretKey, opts); // Steps A, D of RFC6979 3.2.
        const drbg = createHmacDrbg(hash.outputLen, Fn.BYTES, hmac);
        const sig = drbg(seed, k2sig); // Steps B, C, D, E, F, G
        return sig;
    }
    function tryParsingSig(sg) {
        // Try to deduce format
        let sig = undefined;
        const isHex = typeof sg === 'string' || isBytes(sg);
        const isObj = !isHex &&
            sg !== null &&
            typeof sg === 'object' &&
            typeof sg.r === 'bigint' &&
            typeof sg.s === 'bigint';
        if (!isHex && !isObj)
            throw new Error('invalid signature, expected Uint8Array, hex string or Signature instance');
        if (isObj) {
            sig = new Signature(sg.r, sg.s);
        }
        else if (isHex) {
            try {
                sig = Signature.fromBytes(ensureBytes('sig', sg), 'der');
            }
            catch (derError) {
                if (!(derError instanceof DER.Err))
                    throw derError;
            }
            if (!sig) {
                try {
                    sig = Signature.fromBytes(ensureBytes('sig', sg), 'compact');
                }
                catch (error) {
                    return false;
                }
            }
        }
        if (!sig)
            return false;
        return sig;
    }
    /**
     * Verifies a signature against message and public key.
     * Rejects lowS signatures by default: see {@link ECDSAVerifyOpts}.
     * Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:
     *
     * ```
     * verify(r, s, h, P) where
     *   u1 = hs^-1 mod n
     *   u2 = rs^-1 mod n
     *   R = u1⋅G + u2⋅P
     *   mod(R.x, n) == r
     * ```
     */
    function verify(signature, message, publicKey, opts = {}) {
        const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);
        publicKey = ensureBytes('publicKey', publicKey);
        message = validateMsgAndHash(ensureBytes('message', message), prehash);
        if ('strict' in opts)
            throw new Error('options.strict was renamed to lowS');
        const sig = format === undefined
            ? tryParsingSig(signature)
            : Signature.fromBytes(ensureBytes('sig', signature), format);
        if (sig === false)
            return false;
        try {
            const P = Point.fromBytes(publicKey);
            if (lowS && sig.hasHighS())
                return false;
            const { r, s } = sig;
            const h = bits2int_modN(message); // mod n, not mod p
            const is = Fn.inv(s); // s^-1 mod n
            const u1 = Fn.create(h * is); // u1 = hs^-1 mod n
            const u2 = Fn.create(r * is); // u2 = rs^-1 mod n
            const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2)); // u1⋅G + u2⋅P
            if (R.is0())
                return false;
            const v = Fn.create(R.x); // v = r.x mod n
            return v === r;
        }
        catch (e) {
            return false;
        }
    }
    function recoverPublicKey(signature, message, opts = {}) {
        const { prehash } = validateSigOpts(opts, defaultSigOpts);
        message = validateMsgAndHash(message, prehash);
        return Signature.fromBytes(signature, 'recovered').recoverPublicKey(message).toBytes();
    }
    return Object.freeze({
        keygen,
        getPublicKey,
        getSharedSecret,
        utils,
        lengths,
        Point,
        sign,
        verify,
        recoverPublicKey,
        Signature,
        hash,
    });
}
/** @deprecated use `weierstrass` in newer releases */
export function weierstrassPoints(c) {
    const { CURVE, curveOpts } = _weierstrass_legacy_opts_to_new(c);
    const Point = weierstrassN(CURVE, curveOpts);
    return _weierstrass_new_output_to_legacy(c, Point);
}
function _weierstrass_legacy_opts_to_new(c) {
    const CURVE = {
        a: c.a,
        b: c.b,
        p: c.Fp.ORDER,
        n: c.n,
        h: c.h,
        Gx: c.Gx,
        Gy: c.Gy,
    };
    const Fp = c.Fp;
    let allowedLengths = c.allowedPrivateKeyLengths
        ? Array.from(new Set(c.allowedPrivateKeyLengths.map((l) => Math.ceil(l / 2))))
        : undefined;
    const Fn = Field(CURVE.n, {
        BITS: c.nBitLength,
        allowedLengths: allowedLengths,
        modFromBytes: c.wrapPrivateKey,
    });
    const curveOpts = {
        Fp,
        Fn,
        allowInfinityPoint: c.allowInfinityPoint,
        endo: c.endo,
        isTorsionFree: c.isTorsionFree,
        clearCofactor: c.clearCofactor,
        fromBytes: c.fromBytes,
        toBytes: c.toBytes,
    };
    return { CURVE, curveOpts };
}
function _ecdsa_legacy_opts_to_new(c) {
    const { CURVE, curveOpts } = _weierstrass_legacy_opts_to_new(c);
    const ecdsaOpts = {
        hmac: c.hmac,
        randomBytes: c.randomBytes,
        lowS: c.lowS,
        bits2int: c.bits2int,
        bits2int_modN: c.bits2int_modN,
    };
    return { CURVE, curveOpts, hash: c.hash, ecdsaOpts };
}
export function _legacyHelperEquat(Fp, a, b) {
    /**
     * y² = x³ + ax + b: Short weierstrass curve formula. Takes x, returns y².
     * @returns y²
     */
    function weierstrassEquation(x) {
        const x2 = Fp.sqr(x); // x * x
        const x3 = Fp.mul(x2, x); // x² * x
        return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x³ + a * x + b
    }
    return weierstrassEquation;
}
function _weierstrass_new_output_to_legacy(c, Point) {
    const { Fp, Fn } = Point;
    function isWithinCurveOrder(num) {
        return inRange(num, _1n, Fn.ORDER);
    }
    const weierstrassEquation = _legacyHelperEquat(Fp, c.a, c.b);
    return Object.assign({}, {
        CURVE: c,
        Point: Point,
        ProjectivePoint: Point,
        normPrivateKeyToScalar: (key) => _normFnElement(Fn, key),
        weierstrassEquation,
        isWithinCurveOrder,
    });
}
function _ecdsa_new_output_to_legacy(c, _ecdsa) {
    const Point = _ecdsa.Point;
    return Object.assign({}, _ecdsa, {
        ProjectivePoint: Point,
        CURVE: Object.assign({}, c, nLength(Point.Fn.ORDER, Point.Fn.BITS)),
    });
}
// _ecdsa_legacy
export function weierstrass(c) {
    const { CURVE, curveOpts, hash, ecdsaOpts } = _ecdsa_legacy_opts_to_new(c);
    const Point = weierstrassN(CURVE, curveOpts);
    const signs = ecdsa(Point, hash, ecdsaOpts);
    return _ecdsa_new_output_to_legacy(c, signs);
}
//# sourceMappingURL=weierstrass.js.map{
  "type": "module",
  "sideEffects": false
}
/**
 * SECG secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).
 *
 * Belongs to Koblitz curves: it has efficiently-computable GLV endomorphism ψ,
 * check out {@link EndomorphismOpts}. Seems to be rigid (not backdoored).
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { sha256 } from '@noble/hashes/sha2.js';
import { randomBytes } from '@noble/hashes/utils.js';
import { createCurve } from "./_shortw_utils.js";
import { createHasher, isogenyMap, } from "./abstract/hash-to-curve.js";
import { Field, mapHashToField, mod, pow2 } from "./abstract/modular.js";
import { _normFnElement, mapToCurveSimpleSWU, } from "./abstract/weierstrass.js";
import { bytesToNumberBE, concatBytes, ensureBytes, inRange, numberToBytesBE, utf8ToBytes, } from "./utils.js";
// Seems like generator was produced from some seed:
// `Point.BASE.multiply(Point.Fn.inv(2n, N)).toAffine().x`
// // gives short x 0x3b78ce563f89a0ed9414f5aa28ad0d96d6795f9c63n
const secp256k1_CURVE = {
    p: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'),
    n: BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'),
    h: BigInt(1),
    a: BigInt(0),
    b: BigInt(7),
    Gx: BigInt('0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'),
    Gy: BigInt('0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8'),
};
const secp256k1_ENDO = {
    beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),
    basises: [
        [BigInt('0x3086d221a7d46bcde86c90e49284eb15'), -BigInt('0xe4437ed6010e88286f547fa90abfe4c3')],
        [BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'), BigInt('0x3086d221a7d46bcde86c90e49284eb15')],
    ],
};
const _0n = /* @__PURE__ */ BigInt(0);
const _1n = /* @__PURE__ */ BigInt(1);
const _2n = /* @__PURE__ */ BigInt(2);
/**
 * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.
 * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]
 */
function sqrtMod(y) {
    const P = secp256k1_CURVE.p;
    // prettier-ignore
    const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
    // prettier-ignore
    const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
    const b2 = (y * y * y) % P; // x^3, 11
    const b3 = (b2 * b2 * y) % P; // x^7
    const b6 = (pow2(b3, _3n, P) * b3) % P;
    const b9 = (pow2(b6, _3n, P) * b3) % P;
    const b11 = (pow2(b9, _2n, P) * b2) % P;
    const b22 = (pow2(b11, _11n, P) * b11) % P;
    const b44 = (pow2(b22, _22n, P) * b22) % P;
    const b88 = (pow2(b44, _44n, P) * b44) % P;
    const b176 = (pow2(b88, _88n, P) * b88) % P;
    const b220 = (pow2(b176, _44n, P) * b44) % P;
    const b223 = (pow2(b220, _3n, P) * b3) % P;
    const t1 = (pow2(b223, _23n, P) * b22) % P;
    const t2 = (pow2(t1, _6n, P) * b2) % P;
    const root = pow2(t2, _2n, P);
    if (!Fpk1.eql(Fpk1.sqr(root), y))
        throw new Error('Cannot find square root');
    return root;
}
const Fpk1 = Field(secp256k1_CURVE.p, { sqrt: sqrtMod });
/**
 * secp256k1 curve, ECDSA and ECDH methods.
 *
 * Field: `2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n`
 *
 * @example
 * ```js
 * import { secp256k1 } from '@noble/curves/secp256k1';
 * const { secretKey, publicKey } = secp256k1.keygen();
 * const msg = new TextEncoder().encode('hello');
 * const sig = secp256k1.sign(msg, secretKey);
 * const isValid = secp256k1.verify(sig, msg, publicKey) === true;
 * ```
 */
export const secp256k1 = createCurve({ ...secp256k1_CURVE, Fp: Fpk1, lowS: true, endo: secp256k1_ENDO }, sha256);
// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.
// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki
/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */
const TAGGED_HASH_PREFIXES = {};
function taggedHash(tag, ...messages) {
    let tagP = TAGGED_HASH_PREFIXES[tag];
    if (tagP === undefined) {
        const tagH = sha256(utf8ToBytes(tag));
        tagP = concatBytes(tagH, tagH);
        TAGGED_HASH_PREFIXES[tag] = tagP;
    }
    return sha256(concatBytes(tagP, ...messages));
}
// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03
const pointToBytes = (point) => point.toBytes(true).slice(1);
const Pointk1 = /* @__PURE__ */ (() => secp256k1.Point)();
const hasEven = (y) => y % _2n === _0n;
// Calculate point, scalar and bytes
function schnorrGetExtPubKey(priv) {
    const { Fn, BASE } = Pointk1;
    const d_ = _normFnElement(Fn, priv);
    const p = BASE.multiply(d_); // P = d'⋅G; 0 < d' < n check is done inside
    const scalar = hasEven(p.y) ? d_ : Fn.neg(d_);
    return { scalar, bytes: pointToBytes(p) };
}
/**
 * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.
 * @returns valid point checked for being on-curve
 */
function lift_x(x) {
    const Fp = Fpk1;
    if (!Fp.isValidNot0(x))
        throw new Error('invalid x: Fail if x ≥ p');
    const xx = Fp.create(x * x);
    const c = Fp.create(xx * x + BigInt(7)); // Let c = x³ + 7 mod p.
    let y = Fp.sqrt(c); // Let y = c^(p+1)/4 mod p. Same as sqrt().
    // Return the unique point P such that x(P) = x and
    // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.
    if (!hasEven(y))
        y = Fp.neg(y);
    const p = Pointk1.fromAffine({ x, y });
    p.assertValidity();
    return p;
}
const num = bytesToNumberBE;
/**
 * Create tagged hash, convert it to bigint, reduce modulo-n.
 */
function challenge(...args) {
    return Pointk1.Fn.create(num(taggedHash('BIP0340/challenge', ...args)));
}
/**
 * Schnorr public key is just `x` coordinate of Point as per BIP340.
 */
function schnorrGetPublicKey(secretKey) {
    return schnorrGetExtPubKey(secretKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G)
}
/**
 * Creates Schnorr signature as per BIP340. Verifies itself before returning anything.
 * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous.
 */
function schnorrSign(message, secretKey, auxRand = randomBytes(32)) {
    const { Fn } = Pointk1;
    const m = ensureBytes('message', message);
    const { bytes: px, scalar: d } = schnorrGetExtPubKey(secretKey); // checks for isWithinCurveOrder
    const a = ensureBytes('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array
    const t = Fn.toBytes(d ^ num(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a)
    const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m)
    // Let k' = int(rand) mod n. Fail if k' = 0. Let R = k'⋅G
    const { bytes: rx, scalar: k } = schnorrGetExtPubKey(rand);
    const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.
    const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n).
    sig.set(rx, 0);
    sig.set(Fn.toBytes(Fn.create(k + e * d)), 32);
    // If Verify(bytes(P), m, sig) (see below) returns failure, abort
    if (!schnorrVerify(sig, m, px))
        throw new Error('sign: Invalid signature produced');
    return sig;
}
/**
 * Verifies Schnorr signature.
 * Will swallow errors & return false except for initial type validation of arguments.
 */
function schnorrVerify(signature, message, publicKey) {
    const { Fn, BASE } = Pointk1;
    const sig = ensureBytes('signature', signature, 64);
    const m = ensureBytes('message', message);
    const pub = ensureBytes('publicKey', publicKey, 32);
    try {
        const P = lift_x(num(pub)); // P = lift_x(int(pk)); fail if that fails
        const r = num(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r ≥ p.
        if (!inRange(r, _1n, secp256k1_CURVE.p))
            return false;
        const s = num(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n.
        if (!inRange(s, _1n, secp256k1_CURVE.n))
            return false;
        // int(challenge(bytes(r)||bytes(P)||m))%n
        const e = challenge(Fn.toBytes(r), pointToBytes(P), m);
        // R = s⋅G - e⋅P, where -eP == (n-e)P
        const R = BASE.multiplyUnsafe(s).add(P.multiplyUnsafe(Fn.neg(e)));
        const { x, y } = R.toAffine();
        // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r.
        if (R.is0() || !hasEven(y) || x !== r)
            return false;
        return true;
    }
    catch (error) {
        return false;
    }
}
/**
 * Schnorr signatures over secp256k1.
 * https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki
 * @example
 * ```js
 * import { schnorr } from '@noble/curves/secp256k1';
 * const { secretKey, publicKey } = schnorr.keygen();
 * // const publicKey = schnorr.getPublicKey(secretKey);
 * const msg = new TextEncoder().encode('hello');
 * const sig = schnorr.sign(msg, secretKey);
 * const isValid = schnorr.verify(sig, msg, publicKey);
 * ```
 */
export const schnorr = /* @__PURE__ */ (() => {
    const size = 32;
    const seedLength = 48;
    const randomSecretKey = (seed = randomBytes(seedLength)) => {
        return mapHashToField(seed, secp256k1_CURVE.n);
    };
    // TODO: remove
    secp256k1.utils.randomSecretKey;
    function keygen(seed) {
        const secretKey = randomSecretKey(seed);
        return { secretKey, publicKey: schnorrGetPublicKey(secretKey) };
    }
    return {
        keygen,
        getPublicKey: schnorrGetPublicKey,
        sign: schnorrSign,
        verify: schnorrVerify,
        Point: Pointk1,
        utils: {
            randomSecretKey: randomSecretKey,
            randomPrivateKey: randomSecretKey,
            taggedHash,
            // TODO: remove
            lift_x,
            pointToBytes,
            numberToBytesBE,
            bytesToNumberBE,
            mod,
        },
        lengths: {
            secretKey: size,
            publicKey: size,
            publicKeyHasPrefix: false,
            signature: size * 2,
            seed: seedLength,
        },
    };
})();
const isoMap = /* @__PURE__ */ (() => isogenyMap(Fpk1, [
    // xNum
    [
        '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7',
        '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581',
        '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262',
        '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c',
    ],
    // xDen
    [
        '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b',
        '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14',
        '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1
    ],
    // yNum
    [
        '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c',
        '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3',
        '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931',
        '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84',
    ],
    // yDen
    [
        '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b',
        '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573',
        '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f',
        '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1
    ],
].map((i) => i.map((j) => BigInt(j)))))();
const mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fpk1, {
    A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),
    B: BigInt('1771'),
    Z: Fpk1.create(BigInt('-11')),
}))();
/** Hashing / encoding to secp256k1 points / field. RFC 9380 methods. */
export const secp256k1_hasher = /* @__PURE__ */ (() => createHasher(secp256k1.Point, (scalars) => {
    const { x, y } = mapSWU(Fpk1.create(scalars[0]));
    return isoMap(x, y);
}, {
    DST: 'secp256k1_XMD:SHA-256_SSWU_RO_',
    encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_',
    p: Fpk1.ORDER,
    m: 1,
    k: 128,
    expand: 'xmd',
    hash: sha256,
}))();
/** @deprecated use `import { secp256k1_hasher } from '@noble/curves/secp256k1.js';` */
export const hashToCurve = /* @__PURE__ */ (() => secp256k1_hasher.hashToCurve)();
/** @deprecated use `import { secp256k1_hasher } from '@noble/curves/secp256k1.js';` */
export const encodeToCurve = /* @__PURE__ */ (() => secp256k1_hasher.encodeToCurve)();
//# sourceMappingURL=secp256k1.js.map/**
 * Hex, bytes and number utilities.
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { abytes as abytes_, bytesToHex as bytesToHex_, concatBytes as concatBytes_, hexToBytes as hexToBytes_, isBytes as isBytes_, } from '@noble/hashes/utils.js';
export { abytes, anumber, bytesToHex, bytesToUtf8, concatBytes, hexToBytes, isBytes, randomBytes, utf8ToBytes, } from '@noble/hashes/utils.js';
const _0n = /* @__PURE__ */ BigInt(0);
const _1n = /* @__PURE__ */ BigInt(1);
export function abool(title, value) {
    if (typeof value !== 'boolean')
        throw new Error(title + ' boolean expected, got ' + value);
}
// tmp name until v2
export function _abool2(value, title = '') {
    if (typeof value !== 'boolean') {
        const prefix = title && `"${title}"`;
        throw new Error(prefix + 'expected boolean, got type=' + typeof value);
    }
    return value;
}
// tmp name until v2
/** Asserts something is Uint8Array. */
export function _abytes2(value, length, title = '') {
    const bytes = isBytes_(value);
    const len = value?.length;
    const needsLen = length !== undefined;
    if (!bytes || (needsLen && len !== length)) {
        const prefix = title && `"${title}" `;
        const ofLen = needsLen ? ` of length ${length}` : '';
        const got = bytes ? `length=${len}` : `type=${typeof value}`;
        throw new Error(prefix + 'expected Uint8Array' + ofLen + ', got ' + got);
    }
    return value;
}
// Used in weierstrass, der
export function numberToHexUnpadded(num) {
    const hex = num.toString(16);
    return hex.length & 1 ? '0' + hex : hex;
}
export function hexToNumber(hex) {
    if (typeof hex !== 'string')
        throw new Error('hex string expected, got ' + typeof hex);
    return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian
}
// BE: Big Endian, LE: Little Endian
export function bytesToNumberBE(bytes) {
    return hexToNumber(bytesToHex_(bytes));
}
export function bytesToNumberLE(bytes) {
    abytes_(bytes);
    return hexToNumber(bytesToHex_(Uint8Array.from(bytes).reverse()));
}
export function numberToBytesBE(n, len) {
    return hexToBytes_(n.toString(16).padStart(len * 2, '0'));
}
export function numberToBytesLE(n, len) {
    return numberToBytesBE(n, len).reverse();
}
// Unpadded, rarely used
export function numberToVarBytesBE(n) {
    return hexToBytes_(numberToHexUnpadded(n));
}
/**
 * Takes hex string or Uint8Array, converts to Uint8Array.
 * Validates output length.
 * Will throw error for other types.
 * @param title descriptive title for an error e.g. 'secret key'
 * @param hex hex string or Uint8Array
 * @param expectedLength optional, will compare to result array's length
 * @returns
 */
export function ensureBytes(title, hex, expectedLength) {
    let res;
    if (typeof hex === 'string') {
        try {
            res = hexToBytes_(hex);
        }
        catch (e) {
            throw new Error(title + ' must be hex string or Uint8Array, cause: ' + e);
        }
    }
    else if (isBytes_(hex)) {
        // Uint8Array.from() instead of hash.slice() because node.js Buffer
        // is instance of Uint8Array, and its slice() creates **mutable** copy
        res = Uint8Array.from(hex);
    }
    else {
        throw new Error(title + ' must be hex string or Uint8Array');
    }
    const len = res.length;
    if (typeof expectedLength === 'number' && len !== expectedLength)
        throw new Error(title + ' of length ' + expectedLength + ' expected, got ' + len);
    return res;
}
// Compares 2 u8a-s in kinda constant time
export function equalBytes(a, b) {
    if (a.length !== b.length)
        return false;
    let diff = 0;
    for (let i = 0; i < a.length; i++)
        diff |= a[i] ^ b[i];
    return diff === 0;
}
/**
 * Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,
 * and Buffer#slice creates mutable copy. Never use Buffers!
 */
export function copyBytes(bytes) {
    return Uint8Array.from(bytes);
}
/**
 * Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols
 * Should be safe to use for things expected to be ASCII.
 * Returns exact same result as utf8ToBytes for ASCII or throws.
 */
export function asciiToBytes(ascii) {
    return Uint8Array.from(ascii, (c, i) => {
        const charCode = c.charCodeAt(0);
        if (c.length !== 1 || charCode > 127) {
            throw new Error(`string contains non-ASCII character "${ascii[i]}" with code ${charCode} at position ${i}`);
        }
        return charCode;
    });
}
/**
 * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
 */
// export const utf8ToBytes: typeof utf8ToBytes_ = utf8ToBytes_;
/**
 * Converts bytes to string using UTF8 encoding.
 * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'
 */
// export const bytesToUtf8: typeof bytesToUtf8_ = bytesToUtf8_;
// Is positive bigint
const isPosBig = (n) => typeof n === 'bigint' && _0n <= n;
export function inRange(n, min, max) {
    return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
}
/**
 * Asserts min <= n < max. NOTE: It's < max and not <= max.
 * @example
 * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)
 */
export function aInRange(title, n, min, max) {
    // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?
    // consider P=256n, min=0n, max=P
    // - a for min=0 would require -1:          `inRange('x', x, -1n, P)`
    // - b would commonly require subtraction:  `inRange('x', x, 0n, P - 1n)`
    // - our way is the cleanest:               `inRange('x', x, 0n, P)
    if (!inRange(n, min, max))
        throw new Error('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);
}
// Bit operations
/**
 * Calculates amount of bits in a bigint.
 * Same as `n.toString(2).length`
 * TODO: merge with nLength in modular
 */
export function bitLen(n) {
    let len;
    for (len = 0; n > _0n; n >>= _1n, len += 1)
        ;
    return len;
}
/**
 * Gets single bit at position.
 * NOTE: first bit position is 0 (same as arrays)
 * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`
 */
export function bitGet(n, pos) {
    return (n >> BigInt(pos)) & _1n;
}
/**
 * Sets single bit at position.
 */
export function bitSet(n, pos, value) {
    return n | ((value ? _1n : _0n) << BigInt(pos));
}
/**
 * Calculate mask for N bits. Not using ** operator with bigints because of old engines.
 * Same as BigInt(`0b${Array(i).fill('1').join('')}`)
 */
export const bitMask = (n) => (_1n << BigInt(n)) - _1n;
/**
 * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
 * @returns function that will call DRBG until 2nd arg returns something meaningful
 * @example
 *   const drbg = createHmacDRBG<Key>(32, 32, hmac);
 *   drbg(seed, bytesToKey); // bytesToKey must return Key or undefined
 */
export function createHmacDrbg(hashLen, qByteLen, hmacFn) {
    if (typeof hashLen !== 'number' || hashLen < 2)
        throw new Error('hashLen must be a number');
    if (typeof qByteLen !== 'number' || qByteLen < 2)
        throw new Error('qByteLen must be a number');
    if (typeof hmacFn !== 'function')
        throw new Error('hmacFn must be a function');
    // Step B, Step C: set hashLen to 8*ceil(hlen/8)
    const u8n = (len) => new Uint8Array(len); // creates Uint8Array
    const u8of = (byte) => Uint8Array.of(byte); // another shortcut
    let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
    let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same
    let i = 0; // Iterations counter, will throw when over 1000
    const reset = () => {
        v.fill(1);
        k.fill(0);
        i = 0;
    };
    const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)
    const reseed = (seed = u8n(0)) => {
        // HMAC-DRBG reseed() function. Steps D-G
        k = h(u8of(0x00), seed); // k = hmac(k || v || 0x00 || seed)
        v = h(); // v = hmac(k || v)
        if (seed.length === 0)
            return;
        k = h(u8of(0x01), seed); // k = hmac(k || v || 0x01 || seed)
        v = h(); // v = hmac(k || v)
    };
    const gen = () => {
        // HMAC-DRBG generate() function
        if (i++ >= 1000)
            throw new Error('drbg: tried 1000 values');
        let len = 0;
        const out = [];
        while (len < qByteLen) {
            v = h();
            const sl = v.slice();
            out.push(sl);
            len += v.length;
        }
        return concatBytes_(...out);
    };
    const genUntil = (seed, pred) => {
        reset();
        reseed(seed); // Steps D-G
        let res = undefined; // Step H: grind until k is in [1..n-1]
        while (!(res = pred(gen())))
            reseed();
        reset();
        return res;
    };
    return genUntil;
}
// Validating curves and fields
const validatorFns = {
    bigint: (val) => typeof val === 'bigint',
    function: (val) => typeof val === 'function',
    boolean: (val) => typeof val === 'boolean',
    string: (val) => typeof val === 'string',
    stringOrUint8Array: (val) => typeof val === 'string' || isBytes_(val),
    isSafeInteger: (val) => Number.isSafeInteger(val),
    array: (val) => Array.isArray(val),
    field: (val, object) => object.Fp.isValid(val),
    hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),
};
// type Record<K extends string | number | symbol, T> = { [P in K]: T; }
export function validateObject(object, validators, optValidators = {}) {
    const checkField = (fieldName, type, isOptional) => {
        const checkVal = validatorFns[type];
        if (typeof checkVal !== 'function')
            throw new Error('invalid validator function');
        const val = object[fieldName];
        if (isOptional && val === undefined)
            return;
        if (!checkVal(val, object)) {
            throw new Error('param ' + String(fieldName) + ' is invalid. Expected ' + type + ', got ' + val);
        }
    };
    for (const [fieldName, type] of Object.entries(validators))
        checkField(fieldName, type, false);
    for (const [fieldName, type] of Object.entries(optValidators))
        checkField(fieldName, type, true);
    return object;
}
// validate type tests
// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };
// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!
// // Should fail type-check
// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });
// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });
// const z3 = validateObject(o, { test: 'boolean', z: 'bug' });
// const z4 = validateObject(o, { a: 'boolean', z: 'bug' });
export function isHash(val) {
    return typeof val === 'function' && Number.isSafeInteger(val.outputLen);
}
export function _validateObject(object, fields, optFields = {}) {
    if (!object || typeof object !== 'object')
        throw new Error('expected valid options object');
    function checkField(fieldName, expectedType, isOpt) {
        const val = object[fieldName];
        if (isOpt && val === undefined)
            return;
        const current = typeof val;
        if (current !== expectedType || val === null)
            throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
    }
    Object.entries(fields).forEach(([k, v]) => checkField(k, v, false));
    Object.entries(optFields).forEach(([k, v]) => checkField(k, v, true));
}
/**
 * throws not implemented error
 */
export const notImplemented = () => {
    throw new Error('not implemented');
};
/**
 * Memoizes (caches) computation result.
 * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.
 */
export function memoized(fn) {
    const map = new WeakMap();
    return (arg, ...args) => {
        const val = map.get(arg);
        if (val !== undefined)
            return val;
        const computed = fn(arg, ...args);
        map.set(arg, computed);
        return computed;
    };
}
//# sourceMappingURL=utils.js.map/**
 * Internal Merkle-Damgard hash utils.
 * @module
 */
import { Hash, abytes, aexists, aoutput, clean, createView, toBytes } from "./utils.js";
/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */
export function setBigUint64(view, byteOffset, value, isLE) {
    if (typeof view.setBigUint64 === 'function')
        return view.setBigUint64(byteOffset, value, isLE);
    const _32n = BigInt(32);
    const _u32_max = BigInt(0xffffffff);
    const wh = Number((value >> _32n) & _u32_max);
    const wl = Number(value & _u32_max);
    const h = isLE ? 4 : 0;
    const l = isLE ? 0 : 4;
    view.setUint32(byteOffset + h, wh, isLE);
    view.setUint32(byteOffset + l, wl, isLE);
}
/** Choice: a ? b : c */
export function Chi(a, b, c) {
    return (a & b) ^ (~a & c);
}
/** Majority function, true if any two inputs is true. */
export function Maj(a, b, c) {
    return (a & b) ^ (a & c) ^ (b & c);
}
/**
 * Merkle-Damgard hash construction base class.
 * Could be used to create MD5, RIPEMD, SHA1, SHA2.
 */
export class HashMD extends Hash {
    constructor(blockLen, outputLen, padOffset, isLE) {
        super();
        this.finished = false;
        this.length = 0;
        this.pos = 0;
        this.destroyed = false;
        this.blockLen = blockLen;
        this.outputLen = outputLen;
        this.padOffset = padOffset;
        this.isLE = isLE;
        this.buffer = new Uint8Array(blockLen);
        this.view = createView(this.buffer);
    }
    update(data) {
        aexists(this);
        data = toBytes(data);
        abytes(data);
        const { view, buffer, blockLen } = this;
        const len = data.length;
        for (let pos = 0; pos < len;) {
            const take = Math.min(blockLen - this.pos, len - pos);
            // Fast path: we have at least one block in input, cast it to view and process
            if (take === blockLen) {
                const dataView = createView(data);
                for (; blockLen <= len - pos; pos += blockLen)
                    this.process(dataView, pos);
                continue;
            }
            buffer.set(data.subarray(pos, pos + take), this.pos);
            this.pos += take;
            pos += take;
            if (this.pos === blockLen) {
                this.process(view, 0);
                this.pos = 0;
            }
        }
        this.length += data.length;
        this.roundClean();
        return this;
    }
    digestInto(out) {
        aexists(this);
        aoutput(out, this);
        this.finished = true;
        // Padding
        // We can avoid allocation of buffer for padding completely if it
        // was previously not allocated here. But it won't change performance.
        const { buffer, view, blockLen, isLE } = this;
        let { pos } = this;
        // append the bit '1' to the message
        buffer[pos++] = 0b10000000;
        clean(this.buffer.subarray(pos));
        // we have less than padOffset left in buffer, so we cannot put length in
        // current block, need process it and pad again
        if (this.padOffset > blockLen - pos) {
            this.process(view, 0);
            pos = 0;
        }
        // Pad until full block byte with zeros
        for (let i = pos; i < blockLen; i++)
            buffer[i] = 0;
        // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that
        // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.
        // So we just write lowest 64 bits of that value.
        setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
        this.process(view, 0);
        const oview = createView(out);
        const len = this.outputLen;
        // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT
        if (len % 4)
            throw new Error('_sha2: outputLen should be aligned to 32bit');
        const outLen = len / 4;
        const state = this.get();
        if (outLen > state.length)
            throw new Error('_sha2: outputLen bigger than state');
        for (let i = 0; i < outLen; i++)
            oview.setUint32(4 * i, state[i], isLE);
    }
    digest() {
        const { buffer, outputLen } = this;
        this.digestInto(buffer);
        const res = buffer.slice(0, outputLen);
        this.destroy();
        return res;
    }
    _cloneInto(to) {
        to || (to = new this.constructor());
        to.set(...this.get());
        const { blockLen, buffer, length, finished, destroyed, pos } = this;
        to.destroyed = destroyed;
        to.finished = finished;
        to.length = length;
        to.pos = pos;
        if (length % blockLen)
            to.buffer.set(buffer);
        return to;
    }
    clone() {
        return this._cloneInto();
    }
}
/**
 * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.
 * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.
 */
/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */
export const SHA256_IV = /* @__PURE__ */ Uint32Array.from([
    0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
]);
/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */
export const SHA224_IV = /* @__PURE__ */ Uint32Array.from([
    0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,
]);
/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */
export const SHA384_IV = /* @__PURE__ */ Uint32Array.from([
    0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,
    0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,
]);
/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */
export const SHA512_IV = /* @__PURE__ */ Uint32Array.from([
    0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,
    0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,
]);
//# sourceMappingURL=_md.js.map/**
 * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.
 * @todo re-check https://issues.chromium.org/issues/42212588
 * @module
 */
const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
const _32n = /* @__PURE__ */ BigInt(32);
function fromBig(n, le = false) {
    if (le)
        return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };
    return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
}
function split(lst, le = false) {
    const len = lst.length;
    let Ah = new Uint32Array(len);
    let Al = new Uint32Array(len);
    for (let i = 0; i < len; i++) {
        const { h, l } = fromBig(lst[i], le);
        [Ah[i], Al[i]] = [h, l];
    }
    return [Ah, Al];
}
const toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);
// for Shift in [0, 32)
const shrSH = (h, _l, s) => h >>> s;
const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
// Right rotate for Shift in [1, 32)
const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));
const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
// Right rotate for Shift in (32, 64), NOTE: 32 is special case.
const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));
const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));
// Right rotate for shift===32 (just swaps l&h)
const rotr32H = (_h, l) => l;
const rotr32L = (h, _l) => h;
// Left rotate for Shift in [1, 32)
const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));
const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));
// Left rotate for Shift in (32, 64), NOTE: 32 is special case.
const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));
const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));
// JS uses 32-bit signed integers for bitwise operations which means we cannot
// simple take carry out of low bit sum by shift, we need to use division.
function add(Ah, Al, Bh, Bl) {
    const l = (Al >>> 0) + (Bl >>> 0);
    return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };
}
// Addition with more than 2 elements
const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;
const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;
const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;
// prettier-ignore
export { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig };
// prettier-ignore
const u64 = {
    fromBig, split, toBig,
    shrSH, shrSL,
    rotrSH, rotrSL, rotrBH, rotrBL,
    rotr32H, rotr32L,
    rotlSH, rotlSL, rotlBH, rotlBL,
    add, add3L, add3H, add4L, add4H, add5H, add5L,
};
export default u64;
//# sourceMappingURL=_u64.js.mapexport const crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;
//# sourceMappingURL=crypto.js.map/**
 * HMAC: RFC2104 message authentication code.
 * @module
 */
import { abytes, aexists, ahash, clean, Hash, toBytes } from "./utils.js";
export class HMAC extends Hash {
    constructor(hash, _key) {
        super();
        this.finished = false;
        this.destroyed = false;
        ahash(hash);
        const key = toBytes(_key);
        this.iHash = hash.create();
        if (typeof this.iHash.update !== 'function')
            throw new Error('Expected instance of class which extends utils.Hash');
        this.blockLen = this.iHash.blockLen;
        this.outputLen = this.iHash.outputLen;
        const blockLen = this.blockLen;
        const pad = new Uint8Array(blockLen);
        // blockLen can be bigger than outputLen
        pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
        for (let i = 0; i < pad.length; i++)
            pad[i] ^= 0x36;
        this.iHash.update(pad);
        // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone
        this.oHash = hash.create();
        // Undo internal XOR && apply outer XOR
        for (let i = 0; i < pad.length; i++)
            pad[i] ^= 0x36 ^ 0x5c;
        this.oHash.update(pad);
        clean(pad);
    }
    update(buf) {
        aexists(this);
        this.iHash.update(buf);
        return this;
    }
    digestInto(out) {
        aexists(this);
        abytes(out, this.outputLen);
        this.finished = true;
        this.iHash.digestInto(out);
        this.oHash.update(out);
        this.oHash.digestInto(out);
        this.destroy();
    }
    digest() {
        const out = new Uint8Array(this.oHash.outputLen);
        this.digestInto(out);
        return out;
    }
    _cloneInto(to) {
        // Create new instance without calling constructor since key already in state and we don't know it.
        to || (to = Object.create(Object.getPrototypeOf(this), {}));
        const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
        to = to;
        to.finished = finished;
        to.destroyed = destroyed;
        to.blockLen = blockLen;
        to.outputLen = outputLen;
        to.oHash = oHash._cloneInto(to.oHash);
        to.iHash = iHash._cloneInto(to.iHash);
        return to;
    }
    clone() {
        return this._cloneInto();
    }
    destroy() {
        this.destroyed = true;
        this.oHash.destroy();
        this.iHash.destroy();
    }
}
/**
 * HMAC: RFC2104 message authentication code.
 * @param hash - function that would be used e.g. sha256
 * @param key - message key
 * @param message - message data
 * @example
 * import { hmac } from '@noble/hashes/hmac';
 * import { sha256 } from '@noble/hashes/sha2';
 * const mac1 = hmac(sha256, 'key', 'message');
 */
export const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
hmac.create = (hash, key) => new HMAC(hash, key);
//# sourceMappingURL=hmac.js.map{
  "type": "module",
  "sideEffects": false,
  "browser": {
    "node:crypto": false
  },
  "node": {
    "./crypto": "./esm/cryptoNode.js"
  }
}
/**
 * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.
 * SHA256 is the fastest hash implementable in JS, even faster than Blake3.
 * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and
 * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).
 * @module
 */
import { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from "./_md.js";
import * as u64 from "./_u64.js";
import { clean, createHasher, rotr } from "./utils.js";
/**
 * Round constants:
 * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)
 */
// prettier-ignore
const SHA256_K = /* @__PURE__ */ Uint32Array.from([
    0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
    0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
    0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
    0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
    0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
    0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
    0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
    0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
]);
/** Reusable temporary buffer. "W" comes straight from spec. */
const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
export class SHA256 extends HashMD {
    constructor(outputLen = 32) {
        super(64, outputLen, 8, false);
        // We cannot use array here since array allows indexing by variable
        // which means optimizer/compiler cannot use registers.
        this.A = SHA256_IV[0] | 0;
        this.B = SHA256_IV[1] | 0;
        this.C = SHA256_IV[2] | 0;
        this.D = SHA256_IV[3] | 0;
        this.E = SHA256_IV[4] | 0;
        this.F = SHA256_IV[5] | 0;
        this.G = SHA256_IV[6] | 0;
        this.H = SHA256_IV[7] | 0;
    }
    get() {
        const { A, B, C, D, E, F, G, H } = this;
        return [A, B, C, D, E, F, G, H];
    }
    // prettier-ignore
    set(A, B, C, D, E, F, G, H) {
        this.A = A | 0;
        this.B = B | 0;
        this.C = C | 0;
        this.D = D | 0;
        this.E = E | 0;
        this.F = F | 0;
        this.G = G | 0;
        this.H = H | 0;
    }
    process(view, offset) {
        // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array
        for (let i = 0; i < 16; i++, offset += 4)
            SHA256_W[i] = view.getUint32(offset, false);
        for (let i = 16; i < 64; i++) {
            const W15 = SHA256_W[i - 15];
            const W2 = SHA256_W[i - 2];
            const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);
            const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);
            SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;
        }
        // Compression function main loop, 64 rounds
        let { A, B, C, D, E, F, G, H } = this;
        for (let i = 0; i < 64; i++) {
            const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
            const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
            const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
            const T2 = (sigma0 + Maj(A, B, C)) | 0;
            H = G;
            G = F;
            F = E;
            E = (D + T1) | 0;
            D = C;
            C = B;
            B = A;
            A = (T1 + T2) | 0;
        }
        // Add the compressed chunk to the current hash value
        A = (A + this.A) | 0;
        B = (B + this.B) | 0;
        C = (C + this.C) | 0;
        D = (D + this.D) | 0;
        E = (E + this.E) | 0;
        F = (F + this.F) | 0;
        G = (G + this.G) | 0;
        H = (H + this.H) | 0;
        this.set(A, B, C, D, E, F, G, H);
    }
    roundClean() {
        clean(SHA256_W);
    }
    destroy() {
        this.set(0, 0, 0, 0, 0, 0, 0, 0);
        clean(this.buffer);
    }
}
export class SHA224 extends SHA256 {
    constructor() {
        super(28);
        this.A = SHA224_IV[0] | 0;
        this.B = SHA224_IV[1] | 0;
        this.C = SHA224_IV[2] | 0;
        this.D = SHA224_IV[3] | 0;
        this.E = SHA224_IV[4] | 0;
        this.F = SHA224_IV[5] | 0;
        this.G = SHA224_IV[6] | 0;
        this.H = SHA224_IV[7] | 0;
    }
}
// SHA2-512 is slower than sha256 in js because u64 operations are slow.
// Round contants
// First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409
// prettier-ignore
const K512 = /* @__PURE__ */ (() => u64.split([
    '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',
    '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',
    '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',
    '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',
    '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',
    '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',
    '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',
    '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',
    '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',
    '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',
    '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',
    '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',
    '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',
    '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',
    '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',
    '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',
    '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',
    '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',
    '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',
    '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'
].map(n => BigInt(n))))();
const SHA512_Kh = /* @__PURE__ */ (() => K512[0])();
const SHA512_Kl = /* @__PURE__ */ (() => K512[1])();
// Reusable temporary buffers
const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
export class SHA512 extends HashMD {
    constructor(outputLen = 64) {
        super(128, outputLen, 16, false);
        // We cannot use array here since array allows indexing by variable
        // which means optimizer/compiler cannot use registers.
        // h -- high 32 bits, l -- low 32 bits
        this.Ah = SHA512_IV[0] | 0;
        this.Al = SHA512_IV[1] | 0;
        this.Bh = SHA512_IV[2] | 0;
        this.Bl = SHA512_IV[3] | 0;
        this.Ch = SHA512_IV[4] | 0;
        this.Cl = SHA512_IV[5] | 0;
        this.Dh = SHA512_IV[6] | 0;
        this.Dl = SHA512_IV[7] | 0;
        this.Eh = SHA512_IV[8] | 0;
        this.El = SHA512_IV[9] | 0;
        this.Fh = SHA512_IV[10] | 0;
        this.Fl = SHA512_IV[11] | 0;
        this.Gh = SHA512_IV[12] | 0;
        this.Gl = SHA512_IV[13] | 0;
        this.Hh = SHA512_IV[14] | 0;
        this.Hl = SHA512_IV[15] | 0;
    }
    // prettier-ignore
    get() {
        const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
        return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
    }
    // prettier-ignore
    set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
        this.Ah = Ah | 0;
        this.Al = Al | 0;
        this.Bh = Bh | 0;
        this.Bl = Bl | 0;
        this.Ch = Ch | 0;
        this.Cl = Cl | 0;
        this.Dh = Dh | 0;
        this.Dl = Dl | 0;
        this.Eh = Eh | 0;
        this.El = El | 0;
        this.Fh = Fh | 0;
        this.Fl = Fl | 0;
        this.Gh = Gh | 0;
        this.Gl = Gl | 0;
        this.Hh = Hh | 0;
        this.Hl = Hl | 0;
    }
    process(view, offset) {
        // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array
        for (let i = 0; i < 16; i++, offset += 4) {
            SHA512_W_H[i] = view.getUint32(offset);
            SHA512_W_L[i] = view.getUint32((offset += 4));
        }
        for (let i = 16; i < 80; i++) {
            // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)
            const W15h = SHA512_W_H[i - 15] | 0;
            const W15l = SHA512_W_L[i - 15] | 0;
            const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);
            const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);
            // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)
            const W2h = SHA512_W_H[i - 2] | 0;
            const W2l = SHA512_W_L[i - 2] | 0;
            const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);
            const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);
            // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];
            const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
            const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
            SHA512_W_H[i] = SUMh | 0;
            SHA512_W_L[i] = SUMl | 0;
        }
        let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
        // Compression function main loop, 80 rounds
        for (let i = 0; i < 80; i++) {
            // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)
            const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);
            const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);
            //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
            const CHIh = (Eh & Fh) ^ (~Eh & Gh);
            const CHIl = (El & Fl) ^ (~El & Gl);
            // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]
            // prettier-ignore
            const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
            const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
            const T1l = T1ll | 0;
            // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)
            const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);
            const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);
            const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);
            const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);
            Hh = Gh | 0;
            Hl = Gl | 0;
            Gh = Fh | 0;
            Gl = Fl | 0;
            Fh = Eh | 0;
            Fl = El | 0;
            ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
            Dh = Ch | 0;
            Dl = Cl | 0;
            Ch = Bh | 0;
            Cl = Bl | 0;
            Bh = Ah | 0;
            Bl = Al | 0;
            const All = u64.add3L(T1l, sigma0l, MAJl);
            Ah = u64.add3H(All, T1h, sigma0h, MAJh);
            Al = All | 0;
        }
        // Add the compressed chunk to the current hash value
        ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
        ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
        ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
        ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
        ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
        ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
        ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
        ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
        this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
    }
    roundClean() {
        clean(SHA512_W_H, SHA512_W_L);
    }
    destroy() {
        clean(this.buffer);
        this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
    }
}
export class SHA384 extends SHA512 {
    constructor() {
        super(48);
        this.Ah = SHA384_IV[0] | 0;
        this.Al = SHA384_IV[1] | 0;
        this.Bh = SHA384_IV[2] | 0;
        this.Bl = SHA384_IV[3] | 0;
        this.Ch = SHA384_IV[4] | 0;
        this.Cl = SHA384_IV[5] | 0;
        this.Dh = SHA384_IV[6] | 0;
        this.Dl = SHA384_IV[7] | 0;
        this.Eh = SHA384_IV[8] | 0;
        this.El = SHA384_IV[9] | 0;
        this.Fh = SHA384_IV[10] | 0;
        this.Fl = SHA384_IV[11] | 0;
        this.Gh = SHA384_IV[12] | 0;
        this.Gl = SHA384_IV[13] | 0;
        this.Hh = SHA384_IV[14] | 0;
        this.Hl = SHA384_IV[15] | 0;
    }
}
/**
 * Truncated SHA512/256 and SHA512/224.
 * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as "intermediary" IV of SHA512/t.
 * Then t hashes string to produce result IV.
 * See `test/misc/sha2-gen-iv.js`.
 */
/** SHA512/224 IV */
const T224_IV = /* @__PURE__ */ Uint32Array.from([
    0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,
    0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,
]);
/** SHA512/256 IV */
const T256_IV = /* @__PURE__ */ Uint32Array.from([
    0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,
    0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,
]);
export class SHA512_224 extends SHA512 {
    constructor() {
        super(28);
        this.Ah = T224_IV[0] | 0;
        this.Al = T224_IV[1] | 0;
        this.Bh = T224_IV[2] | 0;
        this.Bl = T224_IV[3] | 0;
        this.Ch = T224_IV[4] | 0;
        this.Cl = T224_IV[5] | 0;
        this.Dh = T224_IV[6] | 0;
        this.Dl = T224_IV[7] | 0;
        this.Eh = T224_IV[8] | 0;
        this.El = T224_IV[9] | 0;
        this.Fh = T224_IV[10] | 0;
        this.Fl = T224_IV[11] | 0;
        this.Gh = T224_IV[12] | 0;
        this.Gl = T224_IV[13] | 0;
        this.Hh = T224_IV[14] | 0;
        this.Hl = T224_IV[15] | 0;
    }
}
export class SHA512_256 extends SHA512 {
    constructor() {
        super(32);
        this.Ah = T256_IV[0] | 0;
        this.Al = T256_IV[1] | 0;
        this.Bh = T256_IV[2] | 0;
        this.Bl = T256_IV[3] | 0;
        this.Ch = T256_IV[4] | 0;
        this.Cl = T256_IV[5] | 0;
        this.Dh = T256_IV[6] | 0;
        this.Dl = T256_IV[7] | 0;
        this.Eh = T256_IV[8] | 0;
        this.El = T256_IV[9] | 0;
        this.Fh = T256_IV[10] | 0;
        this.Fl = T256_IV[11] | 0;
        this.Gh = T256_IV[12] | 0;
        this.Gl = T256_IV[13] | 0;
        this.Hh = T256_IV[14] | 0;
        this.Hl = T256_IV[15] | 0;
    }
}
/**
 * SHA2-256 hash function from RFC 4634.
 *
 * It is the fastest JS hash, even faster than Blake3.
 * To break sha256 using birthday attack, attackers need to try 2^128 hashes.
 * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
 */
export const sha256 = /* @__PURE__ */ createHasher(() => new SHA256());
/** SHA2-224 hash function from RFC 4634 */
export const sha224 = /* @__PURE__ */ createHasher(() => new SHA224());
/** SHA2-512 hash function from RFC 4634. */
export const sha512 = /* @__PURE__ */ createHasher(() => new SHA512());
/** SHA2-384 hash function from RFC 4634. */
export const sha384 = /* @__PURE__ */ createHasher(() => new SHA384());
/**
 * SHA2-512/256 "truncated" hash function, with improved resistance to length extension attacks.
 * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).
 */
export const sha512_256 = /* @__PURE__ */ createHasher(() => new SHA512_256());
/**
 * SHA2-512/224 "truncated" hash function, with improved resistance to length extension attacks.
 * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).
 */
export const sha512_224 = /* @__PURE__ */ createHasher(() => new SHA512_224());
//# sourceMappingURL=sha2.js.map/**
 * Utilities for hex, bytes, CSPRNG.
 * @module
 */
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
// node.js versions earlier than v19 don't declare it in global scope.
// For node.js, package.json#exports field mapping rewrites import
// from `crypto` to `cryptoNode`, which imports native module.
// Makes the utils un-importable in browsers without a bundler.
// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.
import { crypto } from '@noble/hashes/crypto';
/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */
export function isBytes(a) {
    return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
}
/** Asserts something is positive integer. */
export function anumber(n) {
    if (!Number.isSafeInteger(n) || n < 0)
        throw new Error('positive integer expected, got ' + n);
}
/** Asserts something is Uint8Array. */
export function abytes(b, ...lengths) {
    if (!isBytes(b))
        throw new Error('Uint8Array expected');
    if (lengths.length > 0 && !lengths.includes(b.length))
        throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);
}
/** Asserts something is hash */
export function ahash(h) {
    if (typeof h !== 'function' || typeof h.create !== 'function')
        throw new Error('Hash should be wrapped by utils.createHasher');
    anumber(h.outputLen);
    anumber(h.blockLen);
}
/** Asserts a hash instance has not been destroyed / finished */
export function aexists(instance, checkFinished = true) {
    if (instance.destroyed)
        throw new Error('Hash instance has been destroyed');
    if (checkFinished && instance.finished)
        throw new Error('Hash#digest() has already been called');
}
/** Asserts output is properly-sized byte array */
export function aoutput(out, instance) {
    abytes(out);
    const min = instance.outputLen;
    if (out.length < min) {
        throw new Error('digestInto() expects output buffer of length at least ' + min);
    }
}
/** Cast u8 / u16 / u32 to u8. */
export function u8(arr) {
    return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
}
/** Cast u8 / u16 / u32 to u32. */
export function u32(arr) {
    return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
}
/** Zeroize a byte array. Warning: JS provides no guarantees. */
export function clean(...arrays) {
    for (let i = 0; i < arrays.length; i++) {
        arrays[i].fill(0);
    }
}
/** Create DataView of an array for easy byte-level manipulation. */
export function createView(arr) {
    return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
}
/** The rotate right (circular right shift) operation for uint32 */
export function rotr(word, shift) {
    return (word << (32 - shift)) | (word >>> shift);
}
/** The rotate left (circular left shift) operation for uint32 */
export function rotl(word, shift) {
    return (word << shift) | ((word >>> (32 - shift)) >>> 0);
}
/** Is current platform little-endian? Most are. Big-Endian platform: IBM */
export const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();
/** The byte swap operation for uint32 */
export function byteSwap(word) {
    return (((word << 24) & 0xff000000) |
        ((word << 8) & 0xff0000) |
        ((word >>> 8) & 0xff00) |
        ((word >>> 24) & 0xff));
}
/** Conditionally byte swap if on a big-endian platform */
export const swap8IfBE = isLE
    ? (n) => n
    : (n) => byteSwap(n);
/** @deprecated */
export const byteSwapIfBE = swap8IfBE;
/** In place byte swap for Uint32Array */
export function byteSwap32(arr) {
    for (let i = 0; i < arr.length; i++) {
        arr[i] = byteSwap(arr[i]);
    }
    return arr;
}
export const swap32IfBE = isLE
    ? (u) => u
    : byteSwap32;
// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex
const hasHexBuiltin = /* @__PURE__ */ (() => 
// @ts-ignore
typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();
// Array where index 0xf0 (240) is mapped to string 'f0'
const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
/**
 * Convert byte array to hex string. Uses built-in function, when available.
 * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
 */
export function bytesToHex(bytes) {
    abytes(bytes);
    // @ts-ignore
    if (hasHexBuiltin)
        return bytes.toHex();
    // pre-caching improves the speed 6x
    let hex = '';
    for (let i = 0; i < bytes.length; i++) {
        hex += hexes[bytes[i]];
    }
    return hex;
}
// We use optimized technique to convert hex string to byte array
const asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
function asciiToBase16(ch) {
    if (ch >= asciis._0 && ch <= asciis._9)
        return ch - asciis._0; // '2' => 50-48
    if (ch >= asciis.A && ch <= asciis.F)
        return ch - (asciis.A - 10); // 'B' => 66-(65-10)
    if (ch >= asciis.a && ch <= asciis.f)
        return ch - (asciis.a - 10); // 'b' => 98-(97-10)
    return;
}
/**
 * Convert hex string to byte array. Uses built-in function, when available.
 * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
 */
export function hexToBytes(hex) {
    if (typeof hex !== 'string')
        throw new Error('hex string expected, got ' + typeof hex);
    // @ts-ignore
    if (hasHexBuiltin)
        return Uint8Array.fromHex(hex);
    const hl = hex.length;
    const al = hl / 2;
    if (hl % 2)
        throw new Error('hex string expected, got unpadded hex of length ' + hl);
    const array = new Uint8Array(al);
    for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
        const n1 = asciiToBase16(hex.charCodeAt(hi));
        const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
        if (n1 === undefined || n2 === undefined) {
            const char = hex[hi] + hex[hi + 1];
            throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
        }
        array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163
    }
    return array;
}
/**
 * There is no setImmediate in browser and setTimeout is slow.
 * Call of async fn will return Promise, which will be fullfiled only on
 * next scheduler queue processing step and this is exactly what we need.
 */
export const nextTick = async () => { };
/** Returns control to thread each 'tick' ms to avoid blocking. */
export async function asyncLoop(iters, tick, cb) {
    let ts = Date.now();
    for (let i = 0; i < iters; i++) {
        cb(i);
        // Date.now() is not monotonic, so in case if clock goes backwards we return return control too
        const diff = Date.now() - ts;
        if (diff >= 0 && diff < tick)
            continue;
        await nextTick();
        ts += diff;
    }
}
/**
 * Converts string to bytes using UTF8 encoding.
 * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])
 */
export function utf8ToBytes(str) {
    if (typeof str !== 'string')
        throw new Error('string expected');
    return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
}
/**
 * Converts bytes to string using UTF8 encoding.
 * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'
 */
export function bytesToUtf8(bytes) {
    return new TextDecoder().decode(bytes);
}
/**
 * Normalizes (non-hex) string or Uint8Array to Uint8Array.
 * Warning: when Uint8Array is passed, it would NOT get copied.
 * Keep in mind for future mutable operations.
 */
export function toBytes(data) {
    if (typeof data === 'string')
        data = utf8ToBytes(data);
    abytes(data);
    return data;
}
/**
 * Helper for KDFs: consumes uint8array or string.
 * When string is passed, does utf8 decoding, using TextDecoder.
 */
export function kdfInputToBytes(data) {
    if (typeof data === 'string')
        data = utf8ToBytes(data);
    abytes(data);
    return data;
}
/** Copies several Uint8Arrays into one. */
export function concatBytes(...arrays) {
    let sum = 0;
    for (let i = 0; i < arrays.length; i++) {
        const a = arrays[i];
        abytes(a);
        sum += a.length;
    }
    const res = new Uint8Array(sum);
    for (let i = 0, pad = 0; i < arrays.length; i++) {
        const a = arrays[i];
        res.set(a, pad);
        pad += a.length;
    }
    return res;
}
export function checkOpts(defaults, opts) {
    if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')
        throw new Error('options should be object or undefined');
    const merged = Object.assign(defaults, opts);
    return merged;
}
/** For runtime check if class implements interface */
export class Hash {
}
/** Wraps hash function, creating an interface on top of it */
export function createHasher(hashCons) {
    const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
    const tmp = hashCons();
    hashC.outputLen = tmp.outputLen;
    hashC.blockLen = tmp.blockLen;
    hashC.create = () => hashCons();
    return hashC;
}
export function createOptHasher(hashCons) {
    const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();
    const tmp = hashCons({});
    hashC.outputLen = tmp.outputLen;
    hashC.blockLen = tmp.blockLen;
    hashC.create = (opts) => hashCons(opts);
    return hashC;
}
export function createXOFer(hashCons) {
    const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();
    const tmp = hashCons({});
    hashC.outputLen = tmp.outputLen;
    hashC.blockLen = tmp.blockLen;
    hashC.create = (opts) => hashCons(opts);
    return hashC;
}
export const wrapConstructor = createHasher;
export const wrapConstructorWithOpts = createOptHasher;
export const wrapXOFConstructorWithOpts = createXOFer;
/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */
export function randomBytes(bytesLength = 32) {
    if (crypto && typeof crypto.getRandomValues === 'function') {
        return crypto.getRandomValues(new Uint8Array(bytesLength));
    }
    // Legacy Node.js compatibility
    if (crypto && typeof crypto.randomBytes === 'function') {
        return Uint8Array.from(crypto.randomBytes(bytesLength));
    }
    throw new Error('crypto.getRandomValues must be defined');
}
//# sourceMappingURL=utils.js.mapimport { encode, encodeInto, objectToTokens, rfc8949EncodeOptions } from './lib/encode.js'
import { decode, decodeFirst, Tokeniser, tokensToObject } from './lib/decode.js'
import { Tagged } from './lib/tagged.js'
import { Token, Type } from './lib/token.js'

/**
 * Export the types that were present in the original manual cborg.d.ts
 * @typedef {import('./interface.js').TagDecodeControl} TagDecodeControl
 * @typedef {import('./interface.js').TagDecoder} TagDecoder
 * There was originally just `TypeEncoder` so don't break types by renaming or not exporting
 * @typedef {import('./interface.js').OptionalTypeEncoder} TypeEncoder
 * @typedef {import('./interface.js').DecodeOptions} DecodeOptions
 * @typedef {import('./interface.js').EncodeOptions} EncodeOptions
 */

export {
  decode,
  decodeFirst,
  Tokeniser as Tokenizer,
  tokensToObject,
  encode,
  encodeInto,
  objectToTokens,
  rfc8949EncodeOptions,
  Tagged,
  Token,
  Type
}
/* globals BigInt */

import { Token, Type } from './token.js'
import { decodeErrPrefix, assertEnoughData } from './common.js'

export const uintBoundaries = [24, 256, 65536, 4294967296, BigInt('18446744073709551616')]

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number}
 */
export function readUint8 (data, offset, options) {
  assertEnoughData(data, offset, 1)
  const value = data[offset]
  if (options.strict === true && value < uintBoundaries[0]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  return value
}

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number}
 */
export function readUint16 (data, offset, options) {
  assertEnoughData(data, offset, 2)
  const value = (data[offset] << 8) | data[offset + 1]
  if (options.strict === true && value < uintBoundaries[1]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  return value
}

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number}
 */
export function readUint32 (data, offset, options) {
  assertEnoughData(data, offset, 4)
  const value = (data[offset] * 16777216 /* 2 ** 24 */) + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]
  if (options.strict === true && value < uintBoundaries[2]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  return value
}

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number|bigint}
 */
export function readUint64 (data, offset, options) {
  // assume BigInt, convert back to Number if within safe range
  assertEnoughData(data, offset, 8)
  const hi = (data[offset] * 16777216 /* 2 ** 24 */) + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]
  const lo = (data[offset + 4] * 16777216 /* 2 ** 24 */) + (data[offset + 5] << 16) + (data[offset + 6] << 8) + data[offset + 7]
  const value = (BigInt(hi) << BigInt(32)) + BigInt(lo)
  if (options.strict === true && value < uintBoundaries[3]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  if (value <= Number.MAX_SAFE_INTEGER) {
    return Number(value)
  }
  if (options.allowBigInt === true) {
    return value
  }
  throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`)
}

/* not required thanks to quick[] list
const oneByteTokens = new Array(24).fill(0).map((v, i) => new Token(Type.uint, i, 1))
export function decodeUintCompact (data, pos, minor, options) {
  return oneByteTokens[minor]
}
*/

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint8 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint8(data, pos + 1, options), 2)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint16 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint16(data, pos + 1, options), 3)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint32 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint32(data, pos + 1, options), 5)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint64 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint64(data, pos + 1, options), 9)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeUint (writer, token) {
  return encodeUintValue(writer, 0, token.value)
}

/**
 * @param {ByteWriter} writer
 * @param {number} major
 * @param {number|bigint} uint
 */
export function encodeUintValue (writer, major, uint) {
  if (uint < uintBoundaries[0]) {
    const nuint = Number(uint)
    // pack into one byte, minor=0, additional=value
    writer.push([major | nuint])
  } else if (uint < uintBoundaries[1]) {
    const nuint = Number(uint)
    // pack into two byte, minor=0, additional=24
    writer.push([major | 24, nuint])
  } else if (uint < uintBoundaries[2]) {
    const nuint = Number(uint)
    // pack into three byte, minor=0, additional=25
    writer.push([major | 25, nuint >>> 8, nuint & 0xff])
  } else if (uint < uintBoundaries[3]) {
    const nuint = Number(uint)
    // pack into five byte, minor=0, additional=26
    writer.push([major | 26, (nuint >>> 24) & 0xff, (nuint >>> 16) & 0xff, (nuint >>> 8) & 0xff, nuint & 0xff])
  } else {
    const buint = BigInt(uint)
    if (buint < uintBoundaries[4]) {
      // pack into nine byte, minor=0, additional=27
      const set = [major | 27, 0, 0, 0, 0, 0, 0, 0]
      // simulate bitwise above 32 bits
      let lo = Number(buint & BigInt(0xffffffff))
      let hi = Number(buint >> BigInt(32) & BigInt(0xffffffff))
      set[8] = lo & 0xff
      lo = lo >> 8
      set[7] = lo & 0xff
      lo = lo >> 8
      set[6] = lo & 0xff
      lo = lo >> 8
      set[5] = lo & 0xff
      set[4] = hi & 0xff
      hi = hi >> 8
      set[3] = hi & 0xff
      hi = hi >> 8
      set[2] = hi & 0xff
      hi = hi >> 8
      set[1] = hi & 0xff
      writer.push(set)
    } else {
      throw new Error(`${decodeErrPrefix} encountered BigInt larger than allowable range`)
    }
  }
}

/**
 * @param {Token} token
 * @returns {number}
 */
encodeUint.encodedSize = function encodedSize (token) {
  return encodeUintValue.encodedSize(token.value)
}

/**
 * @param {number} uint
 * @returns {number}
 */
encodeUintValue.encodedSize = function encodedSize (uint) {
  if (uint < uintBoundaries[0]) {
    return 1
  }
  if (uint < uintBoundaries[1]) {
    return 2
  }
  if (uint < uintBoundaries[2]) {
    return 3
  }
  if (uint < uintBoundaries[3]) {
    return 5
  }
  return 9
}

/**
 * @param {Token} tok1
 * @param {Token} tok2
 * @returns {number}
 */
encodeUint.compareTokens = function compareTokens (tok1, tok2) {
  return tok1.value < tok2.value ? -1 : tok1.value > tok2.value ? 1 : 0
}
/* eslint-env es2020 */

import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import { decodeErrPrefix } from './common.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint8 (data, pos, _minor, options) {
  return new Token(Type.negint, -1 - uint.readUint8(data, pos + 1, options), 2)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint16 (data, pos, _minor, options) {
  return new Token(Type.negint, -1 - uint.readUint16(data, pos + 1, options), 3)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint32 (data, pos, _minor, options) {
  return new Token(Type.negint, -1 - uint.readUint32(data, pos + 1, options), 5)
}

const neg1b = BigInt(-1)
const pos1b = BigInt(1)

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint64 (data, pos, _minor, options) {
  const int = uint.readUint64(data, pos + 1, options)
  if (typeof int !== 'bigint') {
    const value = -1 - int
    if (value >= Number.MIN_SAFE_INTEGER) {
      return new Token(Type.negint, value, 9)
    }
  }
  if (options.allowBigInt !== true) {
    throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`)
  }
  return new Token(Type.negint, neg1b - BigInt(int), 9)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeNegint (writer, token) {
  const negint = token.value
  const unsigned = (typeof negint === 'bigint' ? (negint * neg1b - pos1b) : (negint * -1 - 1))
  uint.encodeUintValue(writer, token.type.majorEncoded, unsigned)
}

/**
 * @param {Token} token
 * @returns {number}
 */
encodeNegint.encodedSize = function encodedSize (token) {
  const negint = token.value
  const unsigned = (typeof negint === 'bigint' ? (negint * neg1b - pos1b) : (negint * -1 - 1))
  // handled by quickEncode, we shouldn't get here but it's included for completeness
  if (unsigned < uint.uintBoundaries[0]) {
    return 1
  }
  if (unsigned < uint.uintBoundaries[1]) {
    return 2
  }
  if (unsigned < uint.uintBoundaries[2]) {
    return 3
  }
  if (unsigned < uint.uintBoundaries[3]) {
    return 5
  }
  return 9
}

/**
 * @param {Token} tok1
 * @param {Token} tok2
 * @returns {number}
 */
encodeNegint.compareTokens = function compareTokens (tok1, tok2) {
  // opposite of the uint comparison since we store the uint version in bytes
  return tok1.value < tok2.value ? 1 : tok1.value > tok2.value ? -1 : 0
}
import { Token, Type } from './token.js'
import { assertEnoughData, decodeErrPrefix } from './common.js'
import * as uint from './0uint.js'
import { compare, fromString } from './byte-utils.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} prefix
 * @param {number} length
 * @returns {Token}
 */
function toToken (data, pos, prefix, length) {
  assertEnoughData(data, pos, prefix + length)
  const buf = data.slice(pos + prefix, pos + prefix + length)
  return new Token(Type.bytes, buf, prefix + length)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeBytesCompact (data, pos, minor, _options) {
  return toToken(data, pos, 1, minor)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer bytes lengths not supported`)
  }
  return toToken(data, pos, 9, l)
}

/**
 * `encodedBytes` allows for caching when we do a byte version of a string
 * for key sorting purposes
 * @param {Token} token
 * @returns {Uint8Array}
 */
function tokenBytes (token) {
  if (token.encodedBytes === undefined) {
    token.encodedBytes = Type.equals(token.type, Type.string) ? fromString(token.value) : token.value
  }
  // @ts-ignore c'mon
  return token.encodedBytes
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeBytes (writer, token) {
  const bytes = tokenBytes(token)
  uint.encodeUintValue(writer, token.type.majorEncoded, bytes.length)
  writer.push(bytes)
}

/**
 * @param {Token} token
 * @returns {number}
 */
encodeBytes.encodedSize = function encodedSize (token) {
  const bytes = tokenBytes(token)
  return uint.encodeUintValue.encodedSize(bytes.length) + bytes.length
}

/**
 * @param {Token} tok1
 * @param {Token} tok2
 * @returns {number}
 */
encodeBytes.compareTokens = function compareTokens (tok1, tok2) {
  return compareBytes(tokenBytes(tok1), tokenBytes(tok2))
}

/**
 * @param {Uint8Array} b1
 * @param {Uint8Array} b2
 * @returns {number}
 */
export function compareBytes (b1, b2) {
  return b1.length < b2.length ? -1 : b1.length > b2.length ? 1 : compare(b1, b2)
}
import { Token, Type } from './token.js'
import { assertEnoughData, decodeErrPrefix } from './common.js'
import * as uint from './0uint.js'
import { encodeBytes } from './2bytes.js'

const textDecoder = new TextDecoder()

// Threshold for ASCII fast-path vs TextDecoder. Short ASCII strings (common for
// map keys) are faster to decode with a simple loop than TextDecoder overhead.
const ASCII_THRESHOLD = 32

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * Decode UTF-8 bytes to string. For short ASCII strings (common case for map keys),
 * a simple loop is faster than TextDecoder.
 * @param {Uint8Array} bytes
 * @param {number} start
 * @param {number} end
 * @returns {string}
 */
function toStr (bytes, start, end) {
  const len = end - start
  if (len < ASCII_THRESHOLD) {
    let str = ''
    for (let i = start; i < end; i++) {
      const c = bytes[i]
      if (c & 0x80) { // non-ASCII, fall back to TextDecoder
        return textDecoder.decode(bytes.subarray(start, end))
      }
      str += String.fromCharCode(c)
    }
    return str
  }
  return textDecoder.decode(bytes.subarray(start, end))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} prefix
 * @param {number} length
 * @param {DecodeOptions} options
 * @returns {Token}
 */
function toToken (data, pos, prefix, length, options) {
  const totLength = prefix + length
  assertEnoughData(data, pos, totLength)
  const tok = new Token(Type.string, toStr(data, pos + prefix, pos + totLength), totLength)
  if (options.retainStringBytes === true) {
    tok.byteValue = data.slice(pos + prefix, pos + totLength)
  }
  return tok
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeStringCompact (data, pos, minor, options) {
  return toToken(data, pos, 1, minor, options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options), options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options), options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options), options)
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer string lengths not supported`)
  }
  return toToken(data, pos, 9, l, options)
}

export const encodeString = encodeBytes
import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import { decodeErrPrefix } from './common.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} prefix
 * @param {number} length
 * @returns {Token}
 */
function toToken (_data, _pos, prefix, length) {
  return new Token(Type.array, length, prefix)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeArrayCompact (data, pos, minor, _options) {
  return toToken(data, pos, 1, minor)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer array lengths not supported`)
  }
  return toToken(data, pos, 9, l)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArrayIndefinite (data, pos, _minor, options) {
  if (options.allowIndefinite === false) {
    throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)
  }
  return toToken(data, pos, 1, Infinity)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeArray (writer, token) {
  uint.encodeUintValue(writer, Type.array.majorEncoded, token.value)
}

// using an array as a map key, are you sure about this? we can only sort
// by map length here, it's up to the encoder to decide to look deeper
encodeArray.compareTokens = uint.encodeUint.compareTokens

/**
 * @param {Token} token
 * @returns {number}
 */
encodeArray.encodedSize = function encodedSize (token) {
  return uint.encodeUintValue.encodedSize(token.value)
}
import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import { decodeErrPrefix } from './common.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} prefix
 * @param {number} length
 * @returns {Token}
 */
function toToken (_data, _pos, prefix, length) {
  return new Token(Type.map, length, prefix)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeMapCompact (data, pos, minor, _options) {
  return toToken(data, pos, 1, minor)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer map lengths not supported`)
  }
  return toToken(data, pos, 9, l)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMapIndefinite (data, pos, _minor, options) {
  if (options.allowIndefinite === false) {
    throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)
  }
  return toToken(data, pos, 1, Infinity)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeMap (writer, token) {
  uint.encodeUintValue(writer, Type.map.majorEncoded, token.value)
}

// using a map as a map key, are you sure about this? we can only sort
// by map length here, it's up to the encoder to decide to look deeper
encodeMap.compareTokens = uint.encodeUint.compareTokens

/**
 * @param {Token} token
 * @returns {number}
 */
encodeMap.encodedSize = function encodedSize (token) {
  return uint.encodeUintValue.encodedSize(token.value)
}
import { Token, Type } from './token.js'
import * as uint from './0uint.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeTagCompact (_data, _pos, minor, _options) {
  return new Token(Type.tag, minor, 1)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag8 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint8(data, pos + 1, options), 2)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag16 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint16(data, pos + 1, options), 3)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag32 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint32(data, pos + 1, options), 5)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag64 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint64(data, pos + 1, options), 9)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeTag (writer, token) {
  uint.encodeUintValue(writer, Type.tag.majorEncoded, token.value)
}

encodeTag.compareTokens = uint.encodeUint.compareTokens

/**
 * @param {Token} token
 * @returns {number}
 */
encodeTag.encodedSize = function encodedSize (token) {
  return uint.encodeUintValue.encodedSize(token.value)
}
// TODO: shift some of the bytes logic to bytes-utils so we can use Buffer
// where possible

import { Token, Type } from './token.js'
import { decodeErrPrefix } from './common.js'
import { encodeUint } from './0uint.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 * @typedef {import('../interface.js').EncodeOptions} EncodeOptions
 */

export const MINOR_FALSE = 20
export const MINOR_TRUE = 21
export const MINOR_NULL = 22
export const MINOR_UNDEFINED = 23

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUndefined (_data, _pos, _minor, options) {
  if (options.allowUndefined === false) {
    throw new Error(`${decodeErrPrefix} undefined values are not supported`)
  } else if (options.coerceUndefinedToNull === true) {
    return new Token(Type.null, null, 1)
  }
  return new Token(Type.undefined, undefined, 1)
}

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBreak (_data, _pos, _minor, options) {
  if (options.allowIndefinite === false) {
    throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)
  }
  return new Token(Type.break, undefined, 1)
}

/**
 * @param {number} value
 * @param {number} bytes
 * @param {DecodeOptions} options
 * @returns {Token}
 */
function createToken (value, bytes, options) {
  if (options) {
    if (options.allowNaN === false && Number.isNaN(value)) {
      throw new Error(`${decodeErrPrefix} NaN values are not supported`)
    }
    if (options.allowInfinity === false && (value === Infinity || value === -Infinity)) {
      throw new Error(`${decodeErrPrefix} Infinity values are not supported`)
    }
  }
  return new Token(Type.float, value, bytes)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeFloat16 (data, pos, _minor, options) {
  return createToken(readFloat16(data, pos + 1), 3, options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeFloat32 (data, pos, _minor, options) {
  return createToken(readFloat32(data, pos + 1), 5, options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeFloat64 (data, pos, _minor, options) {
  return createToken(readFloat64(data, pos + 1), 9, options)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 * @param {EncodeOptions} options
 */
export function encodeFloat (writer, token, options) {
  const float = token.value

  if (float === false) {
    writer.push([Type.float.majorEncoded | MINOR_FALSE])
  } else if (float === true) {
    writer.push([Type.float.majorEncoded | MINOR_TRUE])
  } else if (float === null) {
    writer.push([Type.float.majorEncoded | MINOR_NULL])
  } else if (float === undefined) {
    writer.push([Type.float.majorEncoded | MINOR_UNDEFINED])
  } else {
    let decoded
    let success = false
    if (!options || options.float64 !== true) {
      encodeFloat16(float)
      decoded = readFloat16(ui8a, 1)
      if (float === decoded || Number.isNaN(float)) {
        ui8a[0] = 0xf9
        writer.push(ui8a.slice(0, 3))
        success = true
      } else {
        encodeFloat32(float)
        decoded = readFloat32(ui8a, 1)
        if (float === decoded) {
          ui8a[0] = 0xfa
          writer.push(ui8a.slice(0, 5))
          success = true
        }
      }
    }
    if (!success) {
      encodeFloat64(float)
      decoded = readFloat64(ui8a, 1)
      ui8a[0] = 0xfb
      writer.push(ui8a.slice(0, 9))
    }
  }
}

/**
 * @param {Token} token
 * @param {EncodeOptions} options
 * @returns {number}
 */
encodeFloat.encodedSize = function encodedSize (token, options) {
  const float = token.value

  if (float === false || float === true || float === null || float === undefined) {
    return 1
  }

  if (!options || options.float64 !== true) {
    encodeFloat16(float)
    let decoded = readFloat16(ui8a, 1)
    if (float === decoded || Number.isNaN(float)) {
      return 3
    }
    encodeFloat32(float)
    decoded = readFloat32(ui8a, 1)
    if (float === decoded) {
      return 5
    }
  }
  return 9
}

const buffer = new ArrayBuffer(9)
const dataView = new DataView(buffer, 1)
const ui8a = new Uint8Array(buffer, 0)

/**
 * @param {number} inp
 */
function encodeFloat16 (inp) {
  if (inp === Infinity) {
    dataView.setUint16(0, 0x7c00, false)
  } else if (inp === -Infinity) {
    dataView.setUint16(0, 0xfc00, false)
  } else if (Number.isNaN(inp)) {
    dataView.setUint16(0, 0x7e00, false)
  } else {
    dataView.setFloat32(0, inp)
    const valu32 = dataView.getUint32(0)
    const exponent = (valu32 & 0x7f800000) >> 23
    const mantissa = valu32 & 0x7fffff

    if (exponent === 0xff) {
      // too big, Infinity, but this should be hard (impossible?) to trigger
      dataView.setUint16(0, 0x7c00, false)
    } else if (exponent === 0x00) {
      // 0.0, -0.0 and subnormals, shouldn't be possible to get here because 0.0 should be counted as an int
      // Use valu32 for sign bit since bitwise ops on floats lose -0 sign
      dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | (mantissa >> 13), false)
    } else { // standard numbers
      // chunks of logic here borrowed from https://github.com/PJK/libcbor/blob/c78f437182533e3efa8d963ff4b945bb635c2284/src/cbor/encoding.c#L127
      const logicalExponent = exponent - 127
      // Now we know that 2^exponent <= 0 logically
      if (logicalExponent < -24) {
        /* No unambiguous representation exists, this float is not a half float
          and is too small to be represented using a half, round off to zero.
          Consistent with the reference implementation. */
        // should be difficult (impossible?) to get here in JS
        dataView.setUint16(0, 0)
      } else if (logicalExponent < -14) {
        /* Offset the remaining decimal places by shifting the significand, the
          value is lost. This is an implementation decision that works around the
          absence of standard half-float in the language. */
        dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | /* sign bit */ (1 << (24 + logicalExponent)), false)
      } else {
        dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | ((logicalExponent + 15) << 10) | (mantissa >> 13), false)
      }
    }
  }
}

/**
 * @param {Uint8Array} ui8a
 * @param {number} pos
 * @returns {number}
 */
function readFloat16 (ui8a, pos) {
  if (ui8a.length - pos < 2) {
    throw new Error(`${decodeErrPrefix} not enough data for float16`)
  }

  const half = (ui8a[pos] << 8) + ui8a[pos + 1]
  if (half === 0x7c00) {
    return Infinity
  }
  if (half === 0xfc00) {
    return -Infinity
  }
  if (half === 0x7e00) {
    return NaN
  }
  const exp = (half >> 10) & 0x1f
  const mant = half & 0x3ff
  let val
  if (exp === 0) {
    val = mant * (2 ** -24)
  } else if (exp !== 31) {
    val = (mant + 1024) * (2 ** (exp - 25))
  } else {
    // may not be possible to get here
    val = mant === 0 ? Infinity : NaN
  }
  return (half & 0x8000) ? -val : val
}

/**
 * @param {number} inp
 */
function encodeFloat32 (inp) {
  dataView.setFloat32(0, inp, false)
}

/**
 * @param {Uint8Array} ui8a
 * @param {number} pos
 * @returns {number}
 */
function readFloat32 (ui8a, pos) {
  if (ui8a.length - pos < 4) {
    throw new Error(`${decodeErrPrefix} not enough data for float32`)
  }
  const offset = (ui8a.byteOffset || 0) + pos
  return new DataView(ui8a.buffer, offset, 4).getFloat32(0, false)
}

/**
 * @param {number} inp
 */
function encodeFloat64 (inp) {
  dataView.setFloat64(0, inp, false)
}

/**
 * @param {Uint8Array} ui8a
 * @param {number} pos
 * @returns {number}
 */
function readFloat64 (ui8a, pos) {
  if (ui8a.length - pos < 8) {
    throw new Error(`${decodeErrPrefix} not enough data for float64`)
  }
  const offset = (ui8a.byteOffset || 0) + pos
  return new DataView(ui8a.buffer, offset, 8).getFloat64(0, false)
}

/**
 * @param {Token} _tok1
 * @param {Token} _tok2
 * @returns {number}
 */
encodeFloat.compareTokens = encodeUint.compareTokens
/*
encodeFloat.compareTokens = function compareTokens (_tok1, _tok2) {
  return _tok1
  throw new Error(`${encodeErrPrefix} cannot use floats as map keys`)
}
*/
/**
 * Bl is a list of byte chunks, similar to https://github.com/rvagg/bl but for
 * writing rather than reading.
 * A Bl object accepts set() operations for individual bytes and copyTo() for
 * inserting byte arrays. These write operations don't automatically increment
 * the internal cursor so its "length" won't be changed. Instead, increment()
 * must be called to extend its length to cover the inserted data.
 * The toBytes() call will convert all internal memory to a single Uint8Array of
 * the correct length, truncating any data that is stored but hasn't been
 * included by an increment().
 * get() can retrieve a single byte.
 * All operations (except toBytes()) take an "offset" argument that will perform
 * the write at the offset _from the current cursor_. For most operations this
 * will be `0` to write at the current cursor position but it can be ahead of
 * the current cursor. Negative offsets probably work but are untested.
 */

// TODO: ipjs doesn't support this, only for test files: https://github.com/mikeal/ipjs/blob/master/src/package/testFile.js#L39
import { alloc, concat, slice } from './byte-utils.js'

// the ts-ignores in this file are almost all for the `Uint8Array|number[]` duality that exists
// for perf reasons. Consider better approaches to this or removing it entirely, it is quite
// risky because of some assumptions about small chunks === number[] and everything else === Uint8Array.

const defaultChunkSize = 256

export class Bl {
  /**
   * @param {number} [chunkSize]
   */
  constructor (chunkSize = defaultChunkSize) {
    this.chunkSize = chunkSize
    /** @type {number} */
    this.cursor = 0
    /** @type {number} */
    this.maxCursor = -1
    /** @type {(Uint8Array|number[])[]} */
    this.chunks = []
    // keep the first chunk around if we can to save allocations for future encodes
    /** @type {Uint8Array|number[]|null} */
    this._initReuseChunk = null
  }

  reset () {
    this.cursor = 0
    this.maxCursor = -1
    if (this.chunks.length) {
      this.chunks = []
    }
    if (this._initReuseChunk !== null) {
      this.chunks.push(this._initReuseChunk)
      this.maxCursor = this._initReuseChunk.length - 1
    }
  }

  /**
   * @param {Uint8Array|number[]} bytes
   */
  push (bytes) {
    let topChunk = this.chunks[this.chunks.length - 1]
    const newMax = this.cursor + bytes.length
    if (newMax <= this.maxCursor + 1) {
      // we have at least one chunk and we can fit these bytes into that chunk
      const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1
      // @ts-ignore
      topChunk.set(bytes, chunkPos)
    } else {
      // can't fit it in
      if (topChunk) {
        // trip the last chunk to `cursor` if we need to
        const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1
        if (chunkPos < topChunk.length) {
          // @ts-ignore
          this.chunks[this.chunks.length - 1] = topChunk.subarray(0, chunkPos)
          this.maxCursor = this.cursor - 1
        }
      }
      if (bytes.length < 64 && bytes.length < this.chunkSize) {
        // make a new chunk and copy the new one into it
        topChunk = alloc(this.chunkSize)
        this.chunks.push(topChunk)
        this.maxCursor += topChunk.length
        if (this._initReuseChunk === null) {
          this._initReuseChunk = topChunk
        }
        // @ts-ignore
        topChunk.set(bytes, 0)
      } else {
        // push the new bytes in as its own chunk
        this.chunks.push(bytes)
        this.maxCursor += bytes.length
      }
    }
    this.cursor += bytes.length
  }

  /**
   * @param {boolean} [reset]
   * @returns {Uint8Array}
   */
  toBytes (reset = false) {
    let byts
    if (this.chunks.length === 1) {
      const chunk = this.chunks[0]
      if (reset && this.cursor > chunk.length / 2) {
        // @ts-ignore
        byts = this.cursor === chunk.length ? chunk : chunk.subarray(0, this.cursor)
        this._initReuseChunk = null
        this.chunks = []
      } else {
        // @ts-ignore
        byts = slice(chunk, 0, this.cursor)
      }
    } else {
      // @ts-ignore
      byts = concat(this.chunks, this.cursor)
    }
    if (reset) {
      this.reset()
    }
    return byts
  }
}

/**
 * U8Bl is a buffer list that writes directly to a user-provided Uint8Array.
 * It provides the same interface as Bl but writes to a fixed destination.
 */
export class U8Bl {
  /**
   * @param {Uint8Array} dest
   */
  constructor (dest) {
    this.dest = dest
    /** @type {number} */
    this.cursor = 0
    // chunks is for interface compatibility with Bl - encode.js checks chunks.length
    // as a sanity check for pre-calculated sizes. For U8Bl this is always [dest].
    /** @type {Uint8Array[]} */
    this.chunks = [dest]
  }

  reset () {
    this.cursor = 0
  }

  /**
   * @param {Uint8Array|number[]} bytes
   */
  push (bytes) {
    if (this.cursor + bytes.length > this.dest.length) {
      throw new Error('write out of bounds, destination buffer is too small')
    }
    this.dest.set(bytes, this.cursor)
    this.cursor += bytes.length
  }

  /**
   * @param {boolean} [reset]
   * @returns {Uint8Array}
   */
  toBytes (reset = false) {
    const byts = this.dest.subarray(0, this.cursor)
    if (reset) {
      this.reset()
    }
    return byts
  }
}
// Use Uint8Array directly in the browser, use Buffer in Node.js but don't
// speak its name directly to avoid bundlers pulling in the `Buffer` polyfill

// @ts-ignore
export const useBuffer = globalThis.process &&
  // @ts-ignore
  !globalThis.process.browser &&
  // @ts-ignore
  globalThis.Buffer &&
  // @ts-ignore
  typeof globalThis.Buffer.isBuffer === 'function'

const textEncoder = new TextEncoder()

/**
 * @param {Uint8Array} buf
 * @returns {boolean}
 */
function isBuffer (buf) {
  // @ts-ignore
  return useBuffer && globalThis.Buffer.isBuffer(buf)
}

/**
 * @param {Uint8Array|number[]} buf
 * @returns {Uint8Array}
 */
export function asU8A (buf) {
  if (!(buf instanceof Uint8Array)) {
    return Uint8Array.from(buf)
  }
  return isBuffer(buf) ? new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength) : buf
}

// Threshold for manual UTF-8 encoding vs native methods.
// Node.js Buffer.from: crossover ~24 chars
// Browser TextEncoder: crossover ~200 chars
const FROM_STRING_THRESHOLD_BUFFER = 24
const FROM_STRING_THRESHOLD_TEXTENCODER = 200

export const fromString = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {string} string
     */
    (string) => {
      return string.length >= FROM_STRING_THRESHOLD_BUFFER
        ? // eslint-disable-line operator-linebreak
      // @ts-ignore
        globalThis.Buffer.from(string)
        : utf8ToBytes(string)
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {string} string
     */
    (string) => {
      return string.length >= FROM_STRING_THRESHOLD_TEXTENCODER ? textEncoder.encode(string) : utf8ToBytes(string)
    }

/**
 * Buffer variant not fast enough for what we need
 * @param {number[]} arr
 * @returns {Uint8Array}
 */
export const fromArray = (arr) => {
  return Uint8Array.from(arr)
}

export const slice = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} bytes
     * @param {number} start
     * @param {number} end
     */
    // Buffer.slice() returns a view, not a copy, so we need special handling
    (bytes, start, end) => {
      if (isBuffer(bytes)) {
        return new Uint8Array(bytes.subarray(start, end))
      }
      return bytes.slice(start, end)
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} bytes
     * @param {number} start
     * @param {number} end
     */
    (bytes, start, end) => {
      return bytes.slice(start, end)
    }

export const concat = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array[]} chunks
     * @param {number} length
     * @returns {Uint8Array}
     */
    (chunks, length) => {
      // might get a stray plain Array here
      chunks = chunks.map((c) => c instanceof Uint8Array
        ? c
        : // eslint-disable-line operator-linebreak
        // @ts-ignore
        globalThis.Buffer.from(c))
      // @ts-ignore
      return asU8A(globalThis.Buffer.concat(chunks, length))
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array[]} chunks
     * @param {number} length
     * @returns {Uint8Array}
     */
    (chunks, length) => {
      const out = new Uint8Array(length)
      let off = 0
      for (let b of chunks) {
        if (off + b.length > out.length) {
          // final chunk that's bigger than we need
          b = b.subarray(0, out.length - off)
        }
        out.set(b, off)
        off += b.length
      }
      return out
    }

export const alloc = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {number} size
     * @returns {Uint8Array}
     */
    (size) => {
      // we always write over the contents we expose so this should be safe
      // @ts-ignore
      return globalThis.Buffer.allocUnsafe(size)
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {number} size
     * @returns {Uint8Array}
     */
    (size) => {
      return new Uint8Array(size)
    }

export const toHex = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} d
     * @returns {string}
     */
    (d) => {
      if (typeof d === 'string') {
        return d
      }
      // @ts-ignore
      return globalThis.Buffer.from(toBytes(d)).toString('hex')
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} d
     * @returns {string}
     */
    (d) => {
      if (typeof d === 'string') {
        return d
      }
      // @ts-ignore not smart enough to figure this out
      return Array.prototype.reduce.call(toBytes(d), (p, c) => `${p}${c.toString(16).padStart(2, '0')}`, '')
    }

export const fromHex = useBuffer
  ? // eslint-disable-line operator-linebreak
  /**
   * @param {string|Uint8Array} hex
   * @returns {Uint8Array}
   */
    (hex) => {
      if (hex instanceof Uint8Array) {
        return hex
      }
      // @ts-ignore
      return globalThis.Buffer.from(hex, 'hex')
    }
  : // eslint-disable-line operator-linebreak
  /**
   * @param {string|Uint8Array} hex
   * @returns {Uint8Array}
   */
    (hex) => {
      if (hex instanceof Uint8Array) {
        return hex
      }
      if (!hex.length) {
        return new Uint8Array(0)
      }
      return new Uint8Array(hex.split('')
        .map((/** @type {string} */ c, /** @type {number} */ i, /** @type {string[]} */ d) => i % 2 === 0 ? `0x${c}${d[i + 1]}` : '')
        .filter(Boolean)
        .map((/** @type {string} */ e) => parseInt(e, 16)))
    }

/**
 * @param {Uint8Array|ArrayBuffer|ArrayBufferView} obj
 * @returns {Uint8Array}
 */
function toBytes (obj) {
  if (obj instanceof Uint8Array && obj.constructor.name === 'Uint8Array') {
    return obj
  }
  if (obj instanceof ArrayBuffer) {
    return new Uint8Array(obj)
  }
  if (ArrayBuffer.isView(obj)) {
    return new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength)
  }
  throw new Error('Unknown type, must be binary type')
}

/**
 * @param {Uint8Array} b1
 * @param {Uint8Array} b2
 * @returns {number}
 */
export function compare (b1, b2) {
  if (isBuffer(b1) && isBuffer(b2)) {
    // probably not possible to get here in the current API
    // @ts-ignore Buffer
    return b1.compare(b2)
  }
  for (let i = 0; i < b1.length; i++) {
    if (b1[i] === b2[i]) {
      continue
    }
    return b1[i] < b2[i] ? -1 : 1
  }
  return 0
}

// The below code is taken from https://github.com/google/closure-library/blob/8598d87242af59aac233270742c8984e2b2bdbe0/closure/goog/crypt/crypt.js#L117-L143
// Licensed Apache-2.0.

/**
 * @param {string} str
 * @returns {number[]}
 */
function utf8ToBytes (str) {
  const out = []
  let p = 0
  for (let i = 0; i < str.length; i++) {
    let c = str.charCodeAt(i)
    if (c < 128) {
      out[p++] = c
    } else if (c < 2048) {
      out[p++] = (c >> 6) | 192
      out[p++] = (c & 63) | 128
    } else if (
      ((c & 0xFC00) === 0xD800) && (i + 1) < str.length &&
      ((str.charCodeAt(i + 1) & 0xFC00) === 0xDC00)) {
      // Surrogate Pair
      c = 0x10000 + ((c & 0x03FF) << 10) + (str.charCodeAt(++i) & 0x03FF)
      out[p++] = (c >> 18) | 240
      out[p++] = ((c >> 12) & 63) | 128
      out[p++] = ((c >> 6) & 63) | 128
      out[p++] = (c & 63) | 128
    } else {
      if ((c >= 0xD800) && (c <= 0xDFFF)) {
        c = 0xFFFD // Unpaired Surrogate
      }
      out[p++] = (c >> 12) | 224
      out[p++] = ((c >> 6) & 63) | 128
      out[p++] = (c & 63) | 128
    }
  }
  return out
}

// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
const MAX_ARGUMENTS_LENGTH = 0x1000

/**
 * @param {number[]} codePoints
 * @returns {string}
 */
export function decodeCodePointsArray (codePoints) {
  const len = codePoints.length
  if (len <= MAX_ARGUMENTS_LENGTH) {
    return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  }
  // Decode in chunks to avoid "call stack size exceeded".
  let res = ''
  let i = 0
  while (i < len) {
    res += String.fromCharCode.apply(
      String,
      codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
    )
  }
  return res
}
const decodeErrPrefix = 'CBOR decode error:'
const encodeErrPrefix = 'CBOR encode error:'

const uintMinorPrefixBytes = []
uintMinorPrefixBytes[23] = 1
uintMinorPrefixBytes[24] = 2
uintMinorPrefixBytes[25] = 3
uintMinorPrefixBytes[26] = 5
uintMinorPrefixBytes[27] = 9

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} need
 */
function assertEnoughData (data, pos, need) {
  if (data.length - pos < need) {
    throw new Error(`${decodeErrPrefix} not enough data for type`)
  }
}

export {
  decodeErrPrefix,
  encodeErrPrefix,
  uintMinorPrefixBytes,
  assertEnoughData
}
import { decodeErrPrefix } from './common.js'
import { Type } from './token.js'
import { jump, quick } from './jump.js'
import { asU8A } from './byte-utils.js'

/**
 * @typedef {import('./token.js').Token} Token
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 * @typedef {import('../interface.js').DecodeTokenizer} DecodeTokenizer
 * @typedef {import('../interface.js').TagDecodeControl} TagDecodeControl
 */

const defaultDecodeOptions = {
  strict: false,
  allowIndefinite: true,
  allowUndefined: true,
  allowBigInt: true
}

/**
 * @implements {DecodeTokenizer}
 */
class Tokeniser {
  /**
   * @param {Uint8Array} data
   * @param {DecodeOptions} options
   */
  constructor (data, options = {}) {
    this._pos = 0
    this.data = data
    this.options = options
  }

  pos () {
    return this._pos
  }

  done () {
    return this._pos >= this.data.length
  }

  next () {
    const byt = this.data[this._pos]
    let token = quick[byt]
    if (token === undefined) {
      const decoder = jump[byt]
      // if we're here then there's something wrong with our jump or quick lists!
      if (!decoder) {
        throw new Error(`${decodeErrPrefix} no decoder for major type ${byt >>> 5} (byte 0x${byt.toString(16).padStart(2, '0')})`)
      }
      const minor = byt & 31
      token = decoder(this.data, this._pos, minor, this.options)
    }
    // @ts-ignore we get to assume encodedLength is set (crossing fingers slightly)
    this._pos += token.encodedLength
    return token
  }
}

const DONE = Symbol.for('DONE')
const BREAK = Symbol.for('BREAK')

/**
 * @param {Token} token
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {any|BREAK|DONE}
 */
function tokenToArray (token, tokeniser, options) {
  const arr = []
  for (let i = 0; i < token.value; i++) {
    const value = tokensToObject(tokeniser, options)
    if (value === BREAK) {
      if (token.value === Infinity) {
        // normal end to indefinite length array
        break
      }
      throw new Error(`${decodeErrPrefix} got unexpected break to lengthed array`)
    }
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} found array but not enough entries (got ${i}, expected ${token.value})`)
    }
    arr[i] = value
  }
  return arr
}

/**
 * @param {Token} token
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {any|BREAK|DONE}
 */
function tokenToMap (token, tokeniser, options) {
  const useMaps = options.useMaps === true
  const rejectDuplicateMapKeys = options.rejectDuplicateMapKeys === true
  const obj = useMaps ? undefined : {}
  const m = useMaps ? new Map() : undefined
  for (let i = 0; i < token.value; i++) {
    const key = tokensToObject(tokeniser, options)
    if (key === BREAK) {
      if (token.value === Infinity) {
        // normal end to indefinite length map
        break
      }
      throw new Error(`${decodeErrPrefix} got unexpected break to lengthed map`)
    }
    if (key === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no key], expected ${token.value})`)
    }
    if (!useMaps && typeof key !== 'string') {
      throw new Error(`${decodeErrPrefix} non-string keys not supported (got ${typeof key})`)
    }
    if (rejectDuplicateMapKeys) {
      // @ts-ignore
      if ((useMaps && m.has(key)) || (!useMaps && Object.hasOwn(obj, key))) {
        throw new Error(`${decodeErrPrefix} found repeat map key "${key}"`)
      }
    }
    const value = tokensToObject(tokeniser, options)
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no value], expected ${token.value})`)
    }
    if (useMaps) {
      // @ts-ignore TODO reconsider this .. maybe needs to be strict about key types
      m.set(key, value)
    } else {
      // @ts-ignore TODO reconsider this .. maybe needs to be strict about key types
      obj[key] = value
    }
  }
  // @ts-ignore c'mon man
  return useMaps ? m : obj
}

/**
 * Generator that yields [key, value] entries from a CBOR map token.
 * Used by tag decoders that need to preserve key types (e.g., Tag 259 Map).
 * @param {Token} token - The map token
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {Generator<[any, any], void, unknown>}
 */
function * tokenToMapEntries (token, tokeniser, options) {
  for (let i = 0; i < token.value; i++) {
    const key = tokensToObject(tokeniser, options)
    if (key === BREAK) {
      if (token.value === Infinity) {
        // normal end to indefinite length map
        break
      }
      throw new Error(`${decodeErrPrefix} got unexpected break to lengthed map`)
    }
    if (key === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no key], expected ${token.value})`)
    }
    const value = tokensToObject(tokeniser, options)
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no value], expected ${token.value})`)
    }
    yield [key, value]
  }
}

/**
 * Creates a TagDecodeControl object for tag decoders.
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {TagDecodeControl}
 */
function createTagDecodeControl (tokeniser, options) {
  let called = false

  /**
   * @type {TagDecodeControl}
   */
  const decode = function () {
    if (called) {
      throw new Error(`${decodeErrPrefix} tag decode() may only be called once`)
    }
    called = true
    const value = tokensToObject(tokeniser, options)
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} tag content missing`)
    }
    if (value === BREAK) {
      throw new Error(`${decodeErrPrefix} got unexpected break in tag content`)
    }
    return value
  }

  decode.entries = function () {
    if (called) {
      throw new Error(`${decodeErrPrefix} tag decode() may only be called once`)
    }
    called = true

    // Get the next token and ensure it's a map
    const token = tokeniser.next()
    if (!Type.equals(token.type, Type.map)) {
      throw new Error(`${decodeErrPrefix} entries() requires map content, got ${token.type.name}`)
    }

    // Collect all entries into an array (ensures full content consumption)
    const entries = []
    for (const entry of tokenToMapEntries(token, tokeniser, options)) {
      entries.push(entry)
    }
    return entries
  }

  // For internal tracking
  Object.defineProperty(decode, '_called', {
    get () { return called },
    enumerable: false
  })

  return decode
}

/**
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {any|BREAK|DONE}
 */
function tokensToObject (tokeniser, options) {
  // should we support array as an argument?
  // check for tokenIter[Symbol.iterator] and replace tokenIter with what that returns?
  if (tokeniser.done()) {
    return DONE
  }

  const token = tokeniser.next()

  if (Type.equals(token.type, Type.break)) {
    return BREAK
  }

  if (token.type.terminal) {
    return token.value
  }

  if (Type.equals(token.type, Type.array)) {
    return tokenToArray(token, tokeniser, options)
  }

  if (Type.equals(token.type, Type.map)) {
    return tokenToMap(token, tokeniser, options)
  }

  if (Type.equals(token.type, Type.tag)) {
    if (options.tags && typeof options.tags[token.value] === 'function') {
      const decodeControl = createTagDecodeControl(tokeniser, options)
      const result = options.tags[token.value](decodeControl)
      if (!decodeControl._called) {
        throw new Error(`${decodeErrPrefix} tag decoder must call decode() or entries()`)
      }
      return result
    }
    throw new Error(`${decodeErrPrefix} tag not supported (${token.value})`)
  }
  throw new Error('unsupported')
}

/**
 * @param {Uint8Array} data
 * @param {DecodeOptions} [options]
 * @returns {[any, Uint8Array]}
 */
function decodeFirst (data, options) {
  if (!(data instanceof Uint8Array)) {
    throw new Error(`${decodeErrPrefix} data to decode must be a Uint8Array`)
  }
  options = Object.assign({}, defaultDecodeOptions, options)
  // Convert Buffer to plain Uint8Array for faster slicing in decode path
  const u8aData = asU8A(data)
  const tokeniser = options.tokenizer || new Tokeniser(u8aData, options)
  const decoded = tokensToObject(tokeniser, options)
  if (decoded === DONE) {
    throw new Error(`${decodeErrPrefix} did not find any content to decode`)
  }
  if (decoded === BREAK) {
    throw new Error(`${decodeErrPrefix} got unexpected break`)
  }
  return [decoded, data.subarray(tokeniser.pos())]
}

/**
 * @param {Uint8Array} data
 * @param {DecodeOptions} [options]
 * @returns {any}
 */
function decode (data, options) {
  const [decoded, remainder] = decodeFirst(data, options)
  if (remainder.length > 0) {
    throw new Error(`${decodeErrPrefix} too many terminals, data makes no sense`)
  }
  return decoded
}

export { Tokeniser, tokensToObject, decode, decodeFirst }
import { is } from './is.js'
import { Token, Type } from './token.js'
import { Bl, U8Bl } from './bl.js'
import { encodeErrPrefix } from './common.js'
import { quickEncodeToken } from './jump.js'
import { asU8A, compare, fromString } from './byte-utils.js'

import { encodeUint, encodeUintValue } from './0uint.js'
import { encodeNegint } from './1negint.js'
import { encodeBytes } from './2bytes.js'
import { encodeString } from './3string.js'
import { encodeArray } from './4array.js'
import { encodeMap } from './5map.js'
import { encodeTag } from './6tag.js'
import { encodeFloat, MINOR_FALSE, MINOR_TRUE, MINOR_NULL, MINOR_UNDEFINED } from './7float.js'

/**
 * @typedef {import('../interface.js').EncodeOptions} EncodeOptions
 * @typedef {import('../interface.js').OptionalTypeEncoder} OptionalTypeEncoder
 * @typedef {import('../interface.js').Reference} Reference
 * @typedef {import('../interface.js').StrictTypeEncoder} StrictTypeEncoder
 * @typedef {import('../interface.js').TokenTypeEncoder} TokenTypeEncoder
 * @typedef {import('../interface.js').TokenOrNestedTokens} TokenOrNestedTokens
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 */

/** @type {EncodeOptions} */
const defaultEncodeOptions = {
  float64: false,
  mapSorter,
  quickEncodeToken
}

/** @type {EncodeOptions} */
export const rfc8949EncodeOptions = Object.freeze({
  mapSorter: rfc8949MapSorter,
  quickEncodeToken
})

/** @returns {TokenTypeEncoder[]} */
export function makeCborEncoders () {
  const encoders = []
  encoders[Type.uint.major] = encodeUint
  encoders[Type.negint.major] = encodeNegint
  encoders[Type.bytes.major] = encodeBytes
  encoders[Type.string.major] = encodeString
  encoders[Type.array.major] = encodeArray
  encoders[Type.map.major] = encodeMap
  encoders[Type.tag.major] = encodeTag
  encoders[Type.float.major] = encodeFloat
  return encoders
}

const cborEncoders = makeCborEncoders()

const defaultWriter = new Bl()

/** @implements {Reference} */
class Ref {
  /**
   * @param {object|any[]} obj
   * @param {Reference|undefined} parent
   */
  constructor (obj, parent) {
    this.obj = obj
    this.parent = parent
  }

  /**
   * @param {object|any[]} obj
   * @returns {boolean}
   */
  includes (obj) {
    /** @type {Reference|undefined} */
    let p = this
    do {
      if (p.obj === obj) {
        return true
      }
    } while (p = p.parent) // eslint-disable-line
    return false
  }

  /**
   * @param {Reference|undefined} stack
   * @param {object|any[]} obj
   * @returns {Reference}
   */
  static createCheck (stack, obj) {
    if (stack && stack.includes(obj)) {
      throw new Error(`${encodeErrPrefix} object contains circular references`)
    }
    return new Ref(obj, stack)
  }
}

const simpleTokens = {
  null: new Token(Type.null, null),
  undefined: new Token(Type.undefined, undefined),
  true: new Token(Type.true, true),
  false: new Token(Type.false, false),
  emptyArray: new Token(Type.array, 0),
  emptyMap: new Token(Type.map, 0)
}

/** @type {{[typeName: string]: StrictTypeEncoder}} */
const typeEncoders = {
  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  number (obj, _typ, _options, _refStack) {
    if (!Number.isInteger(obj) || !Number.isSafeInteger(obj)) {
      return new Token(Type.float, obj)
    } else if (obj >= 0) {
      return new Token(Type.uint, obj)
    } else {
      return new Token(Type.negint, obj)
    }
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  bigint (obj, _typ, _options, _refStack) {
    if (obj >= BigInt(0)) {
      return new Token(Type.uint, obj)
    } else {
      return new Token(Type.negint, obj)
    }
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  Uint8Array (obj, _typ, _options, _refStack) {
    return new Token(Type.bytes, obj)
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  string (obj, _typ, _options, _refStack) {
    return new Token(Type.string, obj)
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  boolean (obj, _typ, _options, _refStack) {
    return obj ? simpleTokens.true : simpleTokens.false
  },

  /**
   * @param {any} _obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  null (_obj, _typ, _options, _refStack) {
    return simpleTokens.null
  },

  /**
   * @param {any} _obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  undefined (_obj, _typ, _options, _refStack) {
    return simpleTokens.undefined
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  ArrayBuffer (obj, _typ, _options, _refStack) {
    return new Token(Type.bytes, new Uint8Array(obj))
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  DataView (obj, _typ, _options, _refStack) {
    return new Token(Type.bytes, new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength))
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} options
   * @param {Reference} [refStack]
   * @returns {TokenOrNestedTokens}
   */
  Array (obj, _typ, options, refStack) {
    if (!obj.length) {
      if (options.addBreakTokens === true) {
        return [simpleTokens.emptyArray, new Token(Type.break)]
      }
      return simpleTokens.emptyArray
    }
    refStack = Ref.createCheck(refStack, obj)
    const entries = []
    let i = 0
    for (const e of obj) {
      entries[i++] = objectToTokens(e, options, refStack)
    }
    if (options.addBreakTokens) {
      return [new Token(Type.array, obj.length), entries, new Token(Type.break)]
    }
    return [new Token(Type.array, obj.length), entries]
  },

  /**
   * @param {any} obj
   * @param {string} typ
   * @param {EncodeOptions} options
   * @param {Reference} [refStack]
   * @returns {TokenOrNestedTokens}
   */
  Object (obj, typ, options, refStack) {
    // could be an Object or a Map
    const isMap = typ !== 'Object'
    // it's slightly quicker to use Object.keys() than Object.entries()
    const keys = isMap ? obj.keys() : Object.keys(obj)
    const maxLength = isMap ? obj.size : keys.length

    /** @type {undefined | [TokenOrNestedTokens, TokenOrNestedTokens][]} */
    let entries

    if (maxLength) {
      // Pre-allocate the array with the expected size
      entries = new Array(maxLength)
      refStack = Ref.createCheck(refStack, obj)
      const skipUndefined = !isMap && options.ignoreUndefinedProperties

      let i = 0
      for (const key of keys) {
        const value = isMap ? obj.get(key) : obj[key]
        if (skipUndefined && value === undefined) {
          continue
        }
        entries[i++] = [
          objectToTokens(key, options, refStack),
          objectToTokens(value, options, refStack)
        ]
      }

      // Truncate only if properties were skipped
      if (i < maxLength) {
        entries.length = i
      }
    }

    if (!entries?.length) {
      if (options.addBreakTokens === true) {
        return [simpleTokens.emptyMap, new Token(Type.break)]
      }
      return simpleTokens.emptyMap
    }

    sortMapEntries(entries, options)
    if (options.addBreakTokens) {
      return [new Token(Type.map, entries.length), entries, new Token(Type.break)]
    }
    return [new Token(Type.map, entries.length), entries]
  },

  /**
   * Encode a `Tagged` wrapper as a CBOR tag header followed by the encoded
   * form of the wrapped value. The value is recursively tokenised through
   * `objectToTokens()` so any registered `typeEncoders` apply to it.
   *
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} options
   * @param {Reference} [refStack]
   * @returns {TokenOrNestedTokens}
   */
  Tagged (obj, _typ, options, refStack) {
    return [
      new Token(Type.tag, obj.tag),
      objectToTokens(obj.value, options, refStack)
    ]
  }
}

typeEncoders.Map = typeEncoders.Object
typeEncoders.Buffer = typeEncoders.Uint8Array
for (const typ of 'Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64'.split(' ')) {
  typeEncoders[`${typ}Array`] = typeEncoders.DataView
}

/**
 * @param {any} obj
 * @param {EncodeOptions} [options]
 * @param {Reference} [refStack]
 * @returns {TokenOrNestedTokens}
 */
function objectToTokens (obj, options = {}, refStack) {
  const typ = is(obj)
  const customTypeEncoder = (options && options.typeEncoders && /** @type {OptionalTypeEncoder} */ options.typeEncoders[typ]) || typeEncoders[typ]
  if (typeof customTypeEncoder === 'function') {
    const tokens = customTypeEncoder(obj, typ, options, refStack)
    if (tokens != null) {
      return tokens
    }
  }
  const typeEncoder = typeEncoders[typ]
  if (!typeEncoder) {
    throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`)
  }
  return typeEncoder(obj, typ, options, refStack)
}

/*
CBOR key sorting is a mess.

The canonicalisation recommendation from https://tools.ietf.org/html/rfc7049#section-3.9
includes the wording:

> The keys in every map must be sorted lowest value to highest.
> Sorting is performed on the bytes of the representation of the key
> data items without paying attention to the 3/5 bit splitting for
> major types.
> ...
>  *  If two keys have different lengths, the shorter one sorts
      earlier;
>  *  If two keys have the same length, the one with the lower value
      in (byte-wise) lexical order sorts earlier.

1. It is not clear what "bytes of the representation of the key" means: is it
   the CBOR representation, or the binary representation of the object itself?
   Consider the int and uint difference here.
2. It is not clear what "without paying attention to" means: do we include it
   and compare on that? Or do we omit the special prefix byte, (mostly) treating
   the key in its plain binary representation form.

The FIDO 2.0: Client To Authenticator Protocol spec takes the original CBOR
wording and clarifies it according to their understanding.
https://fidoalliance.org/specs/fido-v2.0-rd-20170927/fido-client-to-authenticator-protocol-v2.0-rd-20170927.html#message-encoding

> The keys in every map must be sorted lowest value to highest. Sorting is
> performed on the bytes of the representation of the key data items without
> paying attention to the 3/5 bit splitting for major types. The sorting rules
> are:
>  * If the major types are different, the one with the lower value in numerical
>    order sorts earlier.
>  * If two keys have different lengths, the shorter one sorts earlier;
>  * If two keys have the same length, the one with the lower value in
>    (byte-wise) lexical order sorts earlier.

Some other implementations, such as borc, do a full encode then do a
length-first, byte-wise-second comparison:
https://github.com/dignifiedquire/borc/blob/b6bae8b0bcde7c3976b0f0f0957208095c392a36/src/encoder.js#L358
https://github.com/dignifiedquire/borc/blob/b6bae8b0bcde7c3976b0f0f0957208095c392a36/src/utils.js#L143-L151

This has the benefit of being able to easily handle arbitrary keys, including
complex types (maps and arrays).

We'll opt for the FIDO approach, since it affords some efficies since we don't
need a full encode of each key to determine order and can defer to the types
to determine how to most efficiently order their values (i.e. int and uint
ordering can be done on the numbers, no need for byte-wise, for example).

Recommendation: stick to single key types or you'll get into trouble, and prefer
string keys because it's much simpler that way.
*/

/**
 * @param {TokenOrNestedTokens[]} entries
 * @param {EncodeOptions} options
 */
function sortMapEntries (entries, options) {
  if (options.mapSorter) {
    entries.sort(options.mapSorter)
  }
}

/**
 * @param {(Token|Token[])[]} e1
 * @param {(Token|Token[])[]} e2
 * @returns {number}
 */
function mapSorter (e1, e2) {
  // the key position ([0]) could have a single token or an array
  // almost always it'll be a single token but complex key might get involved
  const keyToken1 = Array.isArray(e1[0]) ? e1[0][0] : e1[0]
  const keyToken2 = Array.isArray(e2[0]) ? e2[0][0] : e2[0]

  // different key types
  if (keyToken1.type !== keyToken2.type) {
    return keyToken1.type.compare(keyToken2.type)
  }

  const major = keyToken1.type.major
  // TODO: handle case where cmp === 0 but there are more keyToken e. complex type)
  const tcmp = cborEncoders[major].compareTokens(keyToken1, keyToken2)
  if (tcmp === 0) {
    // duplicate key or complex type where the first token matched,
    // i.e. a map or array and we're only comparing the opening token
    console.warn('WARNING: complex key types used, CBOR key sorting guarantees are gone')
  }
  return tcmp
}

/**
 * @typedef {Token & { _keyBytes?: Uint8Array }} TokenEx
 *
 * @param {(Token|Token[])[]} e1
 * @param {(Token|Token[])[]} e2
 * @returns {number}
 */
function rfc8949MapSorter (e1, e2) {
  if (e1[0] instanceof Token && e2[0] instanceof Token) {
    const t1 = /** @type {TokenEx} */ (e1[0])
    const t2 = /** @type {TokenEx} */ (e2[0])

    if (!t1._keyBytes) {
      t1._keyBytes = encodeRfc8949(t1.value)
    }

    if (!t2._keyBytes) {
      t2._keyBytes = encodeRfc8949(t2.value)
    }

    return compare(t1._keyBytes, t2._keyBytes)
  }

  throw new Error('rfc8949MapSorter: complex key types are not supported yet')
}

/**
 * @param {any} data
 * @returns {Uint8Array}
 */
function encodeRfc8949 (data) {
  return encodeCustom(data, cborEncoders, rfc8949EncodeOptions)
}

/**
 * @param {ByteWriter} writer
 * @param {TokenOrNestedTokens} tokens
 * @param {TokenTypeEncoder[]} encoders
 * @param {EncodeOptions} options
 */
function tokensToEncoded (writer, tokens, encoders, options) {
  if (Array.isArray(tokens)) {
    for (const token of tokens) {
      tokensToEncoded(writer, token, encoders, options)
    }
  } else {
    encoders[tokens.type.major](writer, tokens, options)
  }
}

// CBOR major type prefixes, cached from Type for hot path performance
const MAJOR_UINT = Type.uint.majorEncoded
const MAJOR_NEGINT = Type.negint.majorEncoded
const MAJOR_BYTES = Type.bytes.majorEncoded
const MAJOR_STRING = Type.string.majorEncoded
const MAJOR_ARRAY = Type.array.majorEncoded

// Simple value bytes (CBOR major type 7 + minor value)
const SIMPLE_FALSE = Type.float.majorEncoded | MINOR_FALSE
const SIMPLE_TRUE = Type.float.majorEncoded | MINOR_TRUE
const SIMPLE_NULL = Type.float.majorEncoded | MINOR_NULL
const SIMPLE_UNDEFINED = Type.float.majorEncoded | MINOR_UNDEFINED

const neg1b = BigInt(-1)
const pos1b = BigInt(1)

/**
 * Check if direct encoding can be used for the given options.
 * Direct encoding bypasses token creation for most values.
 * @param {EncodeOptions} options
 * @returns {boolean}
 */
function canDirectEncode (options) {
  // Cannot use direct encode with addBreakTokens (needs special break token handling).
  // Direct encode checks typeEncoders per-value, falling back to tokens as needed.
  // Maps fall back to token-based encoding for efficient key sorting.
  return options.addBreakTokens !== true
}

/**
 * Direct encode a value to the writer, bypassing token creation for most types.
 * Falls back to token-based encoding for custom type encoders.
 * @param {ByteWriter} writer
 * @param {any} data
 * @param {EncodeOptions} options
 * @param {Reference|undefined} refStack
 */
function directEncode (writer, data, options, refStack) {
  const typ = is(data)

  // Check for custom encoder for THIS specific type
  const customEncoder = options.typeEncoders && options.typeEncoders[typ]
  if (customEncoder) {
    const tokens = customEncoder(data, typ, options, refStack)
    if (tokens != null) {
      // Custom encoder returned tokens, serialize immediately
      tokensToEncoded(writer, tokens, cborEncoders, options)
      return
    }
    // Custom encoder returned null, fall through to default handling
  }

  // Direct encode based on type
  switch (typ) {
    case 'null':
      writer.push([SIMPLE_NULL])
      return

    case 'undefined':
      writer.push([SIMPLE_UNDEFINED])
      return

    case 'boolean':
      writer.push([data ? SIMPLE_TRUE : SIMPLE_FALSE])
      return

    case 'number':
      if (!Number.isInteger(data) || !Number.isSafeInteger(data)) {
        // Float, use token encoder for complex float encoding
        encodeFloat(writer, new Token(Type.float, data), options)
      } else if (data >= 0) {
        encodeUintValue(writer, MAJOR_UINT, data)
      } else {
        // Negative integer
        encodeUintValue(writer, MAJOR_NEGINT, data * -1 - 1)
      }
      return

    case 'bigint':
      if (data >= BigInt(0)) {
        encodeUintValue(writer, MAJOR_UINT, data)
      } else {
        encodeUintValue(writer, MAJOR_NEGINT, data * neg1b - pos1b)
      }
      return

    case 'string': {
      const bytes = fromString(data)
      encodeUintValue(writer, MAJOR_STRING, bytes.length)
      writer.push(bytes)
      return
    }

    case 'Uint8Array':
      encodeUintValue(writer, MAJOR_BYTES, data.length)
      writer.push(data)
      return

    case 'Array':
      if (!data.length) {
        writer.push([MAJOR_ARRAY]) // Empty array: 0x80
        return
      }
      refStack = Ref.createCheck(refStack, data)
      encodeUintValue(writer, MAJOR_ARRAY, data.length)
      for (const elem of data) {
        directEncode(writer, elem, options, refStack)
      }
      return

    case 'Object':
    case 'Map':
      // Maps require key sorting, use token-based encoding for efficiency
      // (pre-encoding all keys for sorting is expensive)
      {
        const tokens = typeEncoders.Object(data, typ, options, refStack)
        tokensToEncoded(writer, tokens, cborEncoders, options)
      }
      return

    default:
    // Fall back to token-based encoding for other types (DataView, TypedArrays, etc.)
    {
      const typeEncoder = typeEncoders[typ]
      if (!typeEncoder) {
        throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`)
      }
      const tokens = typeEncoder(data, typ, options, refStack)
      tokensToEncoded(writer, tokens, cborEncoders, options)
    }
  }
}

/**
 * @param {any} data
 * @param {TokenTypeEncoder[]} encoders
 * @param {EncodeOptions} options
 * @param {Uint8Array} [destination]
 * @returns {Uint8Array}
 */
function encodeCustom (data, encoders, options, destination) {
  // arg ordering is different to encodeInto for backward compatibility
  const hasDest = destination instanceof Uint8Array
  let writeTo = hasDest ? new U8Bl(destination) : defaultWriter

  const tokens = objectToTokens(data, options)
  if (!Array.isArray(tokens) && options.quickEncodeToken) {
    const quickBytes = options.quickEncodeToken(tokens)
    if (quickBytes) {
      if (hasDest) {
        // Copy quick bytes into destination buffer
        writeTo.push(quickBytes)
        return writeTo.toBytes()
      }
      return quickBytes
    }
    const encoder = encoders[tokens.type.major]
    if (encoder.encodedSize) {
      const size = encoder.encodedSize(tokens, options)
      if (!hasDest) {
        writeTo = new Bl(size)
      }
      encoder(writeTo, tokens, options)
      // this would be a problem with encodedSize() functions
      if (writeTo.chunks.length !== 1) {
        throw new Error(`Unexpected error: pre-calculated length for ${tokens} was wrong`)
      }
      return hasDest ? writeTo.toBytes() : asU8A(writeTo.chunks[0])
    }
  }
  writeTo.reset()
  tokensToEncoded(writeTo, tokens, encoders, options)
  return writeTo.toBytes(true)
}

/**
 * @param {any} data
 * @param {EncodeOptions} [options]
 * @returns {Uint8Array}
 */
function encode (data, options) {
  options = Object.assign({}, defaultEncodeOptions, options)

  // Use direct encode path when possible
  if (canDirectEncode(options)) {
    defaultWriter.reset()
    directEncode(defaultWriter, data, options, undefined)
    return defaultWriter.toBytes(true)
  }

  return encodeCustom(data, cborEncoders, options)
}

/**
 * @param {any} data
 * @param {Uint8Array} destination
 * @param {EncodeOptions} [options]
 * @returns {{ written: number }}
 */
function encodeInto (data, destination, options) {
  options = Object.assign({}, defaultEncodeOptions, options)

  // Use direct encode path when possible
  if (canDirectEncode(options)) {
    const writer = new U8Bl(destination)
    directEncode(writer, data, options, undefined)
    return { written: writer.toBytes().length }
  }

  const result = encodeCustom(data, cborEncoders, options, destination)
  return { written: result.length }
}

export { objectToTokens, encode, encodeCustom, encodeInto, Ref }
// This is an unfortunate replacement for @sindresorhus/is that we need to
// re-implement for performance purposes. In particular the is.observable()
// check is expensive, and unnecessary for our purposes. The values returned
// are compatible with @sindresorhus/is, however.

// Types that reach getObjectType() - excludes types with fast-paths above:
// primitives (typeof), Array (isArray), Uint8Array (instanceof), plain Object (constructor)
const objectTypeNames = [
  'Object', // for Object.create(null) and other non-plain objects
  'RegExp',
  'Date',
  'Error',
  'Map',
  'Set',
  'WeakMap',
  'WeakSet',
  'ArrayBuffer',
  'SharedArrayBuffer',
  'DataView',
  'Promise',
  'URL',
  'HTMLElement',
  'Int8Array',
  'Uint8ClampedArray',
  'Int16Array',
  'Uint16Array',
  'Int32Array',
  'Uint32Array',
  'Float32Array',
  'Float64Array',
  'BigInt64Array',
  'BigUint64Array',
  'Tagged'
]

/**
 * @param {any} value
 * @returns {string}
 */
export function is (value) {
  if (value === null) {
    return 'null'
  }
  if (value === undefined) {
    return 'undefined'
  }
  if (value === true || value === false) {
    return 'boolean'
  }
  const typeOf = typeof value
  if (typeOf === 'string' || typeOf === 'number' || typeOf === 'bigint' || typeOf === 'symbol') {
    return typeOf
  }
  if (typeOf === 'function') {
    return 'Function'
  }
  if (Array.isArray(value)) {
    return 'Array'
  }
  // Also catches Node.js Buffer which extends Uint8Array
  if (value instanceof Uint8Array) {
    return 'Uint8Array'
  }
  // Fast path for plain objects (most common case after primitives/arrays/bytes)
  if (value.constructor === Object) {
    return 'Object'
  }
  const objectType = getObjectType(value)
  if (objectType) {
    return objectType
  }
  return 'Object'
}

/**
 * @param {any} value
 * @returns {string|undefined}
 */
function getObjectType (value) {
  const objectTypeName = Object.prototype.toString.call(value).slice(8, -1)
  if (objectTypeNames.includes(objectTypeName)) {
    return objectTypeName
  }
  return undefined
}
import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import * as negint from './1negint.js'
import * as bytes from './2bytes.js'
import * as string from './3string.js'
import * as array from './4array.js'
import * as map from './5map.js'
import * as tag from './6tag.js'
import * as float from './7float.js'
import { decodeErrPrefix } from './common.js'
import { fromArray } from './byte-utils.js'

/**
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 */
function invalidMinor (data, pos, minor) {
  throw new Error(`${decodeErrPrefix} encountered invalid minor (${minor}) for major ${data[pos] >>> 5}`)
}

/**
 * @param {string} msg
 * @returns {()=>any}
 */
function errorer (msg) {
  return () => { throw new Error(`${decodeErrPrefix} ${msg}`) }
}

/** @type {((data:Uint8Array, pos:number, minor:number, options?:DecodeOptions) => any)[]} */
export const jump = []

// unsigned integer, 0x00..0x17 (0..23)
for (let i = 0; i <= 0x17; i++) {
  jump[i] = invalidMinor // uint.decodeUintCompact, handled by quick[]
}
jump[0x18] = uint.decodeUint8 // unsigned integer, one-byte uint8_t follows
jump[0x19] = uint.decodeUint16 // unsigned integer, two-byte uint16_t follows
jump[0x1a] = uint.decodeUint32 // unsigned integer, four-byte uint32_t follows
jump[0x1b] = uint.decodeUint64 // unsigned integer, eight-byte uint64_t follows
jump[0x1c] = invalidMinor
jump[0x1d] = invalidMinor
jump[0x1e] = invalidMinor
jump[0x1f] = invalidMinor
// negative integer, -1-0x00..-1-0x17 (-1..-24)
for (let i = 0x20; i <= 0x37; i++) {
  jump[i] = invalidMinor // negintDecode, handled by quick[]
}
jump[0x38] = negint.decodeNegint8 // negative integer, -1-n one-byte uint8_t for n follows
jump[0x39] = negint.decodeNegint16 // negative integer, -1-n two-byte uint16_t for n follows
jump[0x3a] = negint.decodeNegint32 // negative integer, -1-n four-byte uint32_t for follows
jump[0x3b] = negint.decodeNegint64 // negative integer, -1-n eight-byte uint64_t for follows
jump[0x3c] = invalidMinor
jump[0x3d] = invalidMinor
jump[0x3e] = invalidMinor
jump[0x3f] = invalidMinor
// byte string, 0x00..0x17 bytes follow
for (let i = 0x40; i <= 0x57; i++) {
  jump[i] = bytes.decodeBytesCompact
}
jump[0x58] = bytes.decodeBytes8 // byte string, one-byte uint8_t for n, and then n bytes follow
jump[0x59] = bytes.decodeBytes16 // byte string, two-byte uint16_t for n, and then n bytes follow
jump[0x5a] = bytes.decodeBytes32 // byte string, four-byte uint32_t for n, and then n bytes follow
jump[0x5b] = bytes.decodeBytes64 // byte string, eight-byte uint64_t for n, and then n bytes follow
jump[0x5c] = invalidMinor
jump[0x5d] = invalidMinor
jump[0x5e] = invalidMinor
jump[0x5f] = errorer('indefinite length bytes/strings are not supported') // byte string, byte strings follow, terminated by "break"
// UTF-8 string 0x00..0x17 bytes follow
for (let i = 0x60; i <= 0x77; i++) {
  jump[i] = string.decodeStringCompact
}
jump[0x78] = string.decodeString8 // UTF-8 string, one-byte uint8_t for n, and then n bytes follow
jump[0x79] = string.decodeString16 // UTF-8 string, two-byte uint16_t for n, and then n bytes follow
jump[0x7a] = string.decodeString32 // UTF-8 string, four-byte uint32_t for n, and then n bytes follow
jump[0x7b] = string.decodeString64 // UTF-8 string, eight-byte uint64_t for n, and then n bytes follow
jump[0x7c] = invalidMinor
jump[0x7d] = invalidMinor
jump[0x7e] = invalidMinor
jump[0x7f] = errorer('indefinite length bytes/strings are not supported') // UTF-8 strings follow, terminated by "break"
// array, 0x00..0x17 data items follow
for (let i = 0x80; i <= 0x97; i++) {
  jump[i] = array.decodeArrayCompact
}
jump[0x98] = array.decodeArray8 // array, one-byte uint8_t for n, and then n data items follow
jump[0x99] = array.decodeArray16 // array, two-byte uint16_t for n, and then n data items follow
jump[0x9a] = array.decodeArray32 // array, four-byte uint32_t for n, and then n data items follow
jump[0x9b] = array.decodeArray64 // array, eight-byte uint64_t for n, and then n data items follow
jump[0x9c] = invalidMinor
jump[0x9d] = invalidMinor
jump[0x9e] = invalidMinor
jump[0x9f] = array.decodeArrayIndefinite // array, data items follow, terminated by "break"
// map, 0x00..0x17 pairs of data items follow
for (let i = 0xa0; i <= 0xb7; i++) {
  jump[i] = map.decodeMapCompact
}
jump[0xb8] = map.decodeMap8 // map, one-byte uint8_t for n, and then n pairs of data items follow
jump[0xb9] = map.decodeMap16 // map, two-byte uint16_t for n, and then n pairs of data items follow
jump[0xba] = map.decodeMap32 // map, four-byte uint32_t for n, and then n pairs of data items follow
jump[0xbb] = map.decodeMap64 // map, eight-byte uint64_t for n, and then n pairs of data items follow
jump[0xbc] = invalidMinor
jump[0xbd] = invalidMinor
jump[0xbe] = invalidMinor
jump[0xbf] = map.decodeMapIndefinite // map, pairs of data items follow, terminated by "break"
// tags
for (let i = 0xc0; i <= 0xd7; i++) {
  jump[i] = tag.decodeTagCompact
}
jump[0xd8] = tag.decodeTag8
jump[0xd9] = tag.decodeTag16
jump[0xda] = tag.decodeTag32
jump[0xdb] = tag.decodeTag64
jump[0xdc] = invalidMinor
jump[0xdd] = invalidMinor
jump[0xde] = invalidMinor
jump[0xdf] = invalidMinor
// 0xe0..0xf3 simple values, unsupported
for (let i = 0xe0; i <= 0xf3; i++) {
  jump[i] = errorer('simple values are not supported')
}
jump[0xf4] = invalidMinor // false, handled by quick[]
jump[0xf5] = invalidMinor // true, handled by quick[]
jump[0xf6] = invalidMinor // null, handled by quick[]
jump[0xf7] = float.decodeUndefined // undefined
jump[0xf8] = errorer('simple values are not supported') // simple value, one byte follows, unsupported
jump[0xf9] = float.decodeFloat16 // half-precision float (two-byte IEEE 754)
jump[0xfa] = float.decodeFloat32 // single-precision float (four-byte IEEE 754)
jump[0xfb] = float.decodeFloat64 // double-precision float (eight-byte IEEE 754)
jump[0xfc] = invalidMinor
jump[0xfd] = invalidMinor
jump[0xfe] = invalidMinor
jump[0xff] = float.decodeBreak // "break" stop code

/** @type {Token[]} */
export const quick = []
// ints <24
for (let i = 0; i < 24; i++) {
  quick[i] = new Token(Type.uint, i, 1)
}
// negints >= -24
for (let i = -1; i >= -24; i--) {
  quick[31 - i] = new Token(Type.negint, i, 1)
}
// empty bytes
quick[0x40] = new Token(Type.bytes, new Uint8Array(0), 1)
// empty string
quick[0x60] = new Token(Type.string, '', 1)
// empty list
quick[0x80] = new Token(Type.array, 0, 1)
// empty map
quick[0xa0] = new Token(Type.map, 0, 1)
// false
quick[0xf4] = new Token(Type.false, false, 1)
// true
quick[0xf5] = new Token(Type.true, true, 1)
// null
quick[0xf6] = new Token(Type.null, null, 1)

/**
 * @param {Token} token
 * @returns {Uint8Array|undefined}
 */
export function quickEncodeToken (token) {
  switch (token.type) {
    case Type.false:
      return fromArray([0xf4])
    case Type.true:
      return fromArray([0xf5])
    case Type.null:
      return fromArray([0xf6])
    case Type.bytes:
      if (!token.value.length) {
        return fromArray([0x40])
      }
      return
    case Type.string:
      if (token.value === '') {
        return fromArray([0x60])
      }
      return
    case Type.array:
      if (token.value === 0) {
        return fromArray([0x80])
      }
      // shouldn't be possible if this were called when there was only one token
      return
    case Type.map:
      if (token.value === 0) {
        return fromArray([0xa0])
      }
      // shouldn't be possible if this were called when there was only one token
      return
    case Type.uint:
      if (token.value < 24) {
        return fromArray([Number(token.value)])
      }
      return
    case Type.negint:
      if (token.value >= -24) {
        return fromArray([31 - Number(token.value)])
      }
  }
}
/**
 * @typedef {import('../interface.js').TagDecodeControl} TagDecodeControl
 * @typedef {(decode: TagDecodeControl) => Tagged} TaggedTagDecoder
 */

/**
 * A wrapper class for representing a CBOR tag with an arbitrary nested value.
 *
 * `Tagged` is a symmetric primitive: it can be passed to `encode()` to emit
 * a CBOR tag header followed by the encoded form of `value`, and it can be
 * returned from a tag decoder (via `Tagged.decoder(tag)` or `Tagged.preserve()`)
 * to round-trip a tag through decode without losing the tag number.
 *
 * Use `Tagged` for one-off tag handling where defining a dedicated
 * `typeEncoders` entry and tag decoder pair would be heavyweight, e.g. when
 * wrapping a structure in a single application-specific tag (COSE, dCBOR
 * envelopes, etc.).
 *
 * For systematic mapping of a JS type to a tag (e.g. CID -> tag 42), prefer
 * a dedicated `typeEncoders` entry instead.
 */
export class Tagged {
  /**
   * @param {number} tag - CBOR tag number, a non-negative integer
   * @param {any} value - The value to be tagged; encoded recursively
   */
  constructor (tag, value) {
    if (typeof tag !== 'number' || !Number.isInteger(tag) || tag < 0) {
      throw new TypeError('Tagged: tag must be a non-negative integer')
    }
    this.tag = tag
    this.value = value
  }

  /**
   * Build a tag decoder for use in `decode()`'s `tags` option that returns the
   * decoded content wrapped in a `Tagged` instance, preserving the tag number
   * for the caller to inspect.
   *
   * @param {number} tag - The CBOR tag number this decoder will be registered for
   * @returns {TaggedTagDecoder}
   *
   * @example
   * import { decode, Tagged } from 'cborg'
   * const value = decode(bytes, { tags: { 16: Tagged.decoder(16) } })
   * // value instanceof Tagged; value.tag === 16
   */
  static decoder (tag) {
    return (decode) => new Tagged(tag, decode())
  }

  /**
   * Build a `tags` option for `decode()` that wraps each listed tag number in
   * a `Tagged` instance, preserving those tags through decode without
   * registering a dedicated decoder per tag.
   *
   * @param {...number} tagNumbers - One or more CBOR tag numbers to preserve
   * @returns {{[tagNumber: number]: TaggedTagDecoder}}
   *
   * @example
   * import { decode, Tagged } from 'cborg'
   * const value = decode(bytes, { tags: Tagged.preserve(16, 96) })
   */
  static preserve (...tagNumbers) {
    /** @type {{[tagNumber: number]: TaggedTagDecoder}} */
    const tags = {}
    for (const tag of tagNumbers) {
      tags[tag] = Tagged.decoder(tag)
    }
    return tags
  }
}

// Symbol.toStringTag so the internal `is()` type detection returns 'Tagged'
// for instances, allowing the default Tagged typeEncoder to match.
Object.defineProperty(Tagged.prototype, Symbol.toStringTag, {
  value: 'Tagged'
})
class Type {
  /**
   * @param {number} major
   * @param {string} name
   * @param {boolean} terminal
   */
  constructor (major, name, terminal) {
    this.major = major
    this.majorEncoded = major << 5
    this.name = name
    this.terminal = terminal
  }

  toString () {
    return `Type[${this.major}].${this.name}`
  }

  /**
   * @param {Type} typ
   * @returns {number}
   */
  compare (typ) {
    return this.major < typ.major ? -1 : this.major > typ.major ? 1 : 0
  }

  /**
   * Check equality between two Type instances. Safe to use across different
   * copies of the Type class (e.g., when bundlers duplicate the module).
   * (major, name) uniquely identifies a Type; terminal is implied by these.
   * @param {Type} a
   * @param {Type} b
   * @returns {boolean}
   */
  static equals (a, b) {
    return a === b || (a.major === b.major && a.name === b.name)
  }
}

// convert to static fields when better supported
Type.uint = new Type(0, 'uint', true)
Type.negint = new Type(1, 'negint', true)
Type.bytes = new Type(2, 'bytes', true)
Type.string = new Type(3, 'string', true)
Type.array = new Type(4, 'array', false)
Type.map = new Type(5, 'map', false)
Type.tag = new Type(6, 'tag', false) // terminal?
Type.float = new Type(7, 'float', true)
Type.false = new Type(7, 'false', true)
Type.true = new Type(7, 'true', true)
Type.null = new Type(7, 'null', true)
Type.undefined = new Type(7, 'undefined', true)
Type.break = new Type(7, 'break', true)
// Type.indefiniteLength = new Type(0, 'indefiniteLength', true)

class Token {
  /**
   * @param {Type} type
   * @param {any} [value]
   * @param {number} [encodedLength]
   */
  constructor (type, value, encodedLength) {
    this.type = type
    this.value = value
    this.encodedLength = encodedLength
    /** @type {Uint8Array|undefined} */
    this.encodedBytes = undefined
    /** @type {Uint8Array|undefined} */
    this.byteValue = undefined
  }

  toString () {
    return `Token[${this.type}].${this.value}`
  }
}

export { Type, Token }
{
  "name": "cborg",
  "version": "5.1.6",
  "description": "Fast CBOR with a focus on strictness",
  "main": "cborg.js",
  "type": "module",
  "bin": {
    "cborg": "lib/bin.js"
  },
  "scripts": {
    "lint": "standard *.js lib/*.js test/*.js",
    "build": "npm run build:types",
    "build:types": "tsc --build",
    "prepublishOnly": "npm run build",
    "test:node": "mocha test/test-*.js",
    "test:node-bin": "mocha test/node-test-bin.js",
    "test:browser": "polendina --cleanup test/test-*.js",
    "test": "npm run lint && npm run build && npm run test:node && npm run test:node-bin && npm run test:browser",
    "test:ci": "npm run test"
  },
  "repository": {
    "type": "git",
    "url": "git@github.com:rvagg/cborg.git"
  },
  "keywords": [
    "cbor"
  ],
  "author": "Rod <rod@vagg.org> (http://r.va.gg/)",
  "license": "Apache-2.0",
  "devDependencies": {
    "@semantic-release/changelog": "^6.0.3",
    "@semantic-release/commit-analyzer": "^13.0.1",
    "@semantic-release/git": "^10.0.1",
    "@semantic-release/github": "^12.0.6",
    "@semantic-release/npm": "^13.1.5",
    "@semantic-release/release-notes-generator": "^14.1.0",
    "@types/chai": "^5.2.3",
    "@types/mocha": "^10.0.10",
    "@types/node": "^26.0.1",
    "chai": "^6.2.2",
    "conventional-changelog-conventionalcommits": "^10.0.0",
    "ipld-garbage": "^5.0.0",
    "mocha": "^11.7.5",
    "polendina": "^3.2.20",
    "semantic-release": "^25.0.3",
    "standard": "^17.1.2",
    "typescript": "^6.0.2"
  },
  "exports": {
    ".": {
      "import": "./cborg.js",
      "types": "./types/cborg.d.ts"
    },
    "./length": {
      "import": "./lib/length.js",
      "types": "./types/lib/length.d.ts"
    },
    "./taglib": {
      "import": "./lib/taglib.js",
      "types": "./types/lib/taglib.d.ts"
    },
    "./json": {
      "import": "./lib/json/json.js",
      "types": "./types/lib/json/json.d.ts"
    },
    "./extended": {
      "import": "./lib/extended/extended.js",
      "types": "./types/lib/extended/extended.d.ts"
    },
    "./interface": {
      "types": "./types/interface.d.ts"
    }
  },
  "types": "cborg.d.ts",
  "typesVersions": {
    "*": {
      "json": [
        "types/lib/json/json.d.ts"
      ],
      "length": [
        "types/lib/length.d.ts"
      ],
      "*": [
        "types/*"
      ],
      "types/*": [
        "types/*"
      ]
    }
  },
  "release": {
    "branches": [
      "master"
    ],
    "plugins": [
      [
        "@semantic-release/commit-analyzer",
        {
          "preset": "conventionalcommits",
          "releaseRules": [
            {
              "breaking": true,
              "release": "major"
            },
            {
              "revert": true,
              "release": "patch"
            },
            {
              "type": "feat",
              "release": "minor"
            },
            {
              "type": "fix",
              "release": "patch"
            },
            {
              "type": "chore",
              "release": "patch"
            },
            {
              "type": "docs",
              "release": "patch"
            },
            {
              "type": "test",
              "release": "patch"
            },
            {
              "scope": "no-release",
              "release": false
            }
          ]
        }
      ],
      [
        "@semantic-release/release-notes-generator",
        {
          "preset": "conventionalcommits",
          "presetConfig": {
            "types": [
              {
                "type": "feat",
                "section": "Features"
              },
              {
                "type": "fix",
                "section": "Bug Fixes"
              },
              {
                "type": "chore",
                "section": "Trivial Changes"
              },
              {
                "type": "docs",
                "section": "Trivial Changes"
              },
              {
                "type": "test",
                "section": "Tests"
              }
            ]
          }
        }
      ],
      "@semantic-release/changelog",
      "@semantic-release/npm",
      "@semantic-release/github",
      "@semantic-release/git"
    ]
  }
}
import { coerce } from '../bytes.js';
import basex from '../vendor/base-x.js';
/**
 * Class represents both BaseEncoder and MultibaseEncoder meaning it
 * can be used to encode to multibase or base encode without multibase
 * prefix.
 */
class Encoder {
    name;
    prefix;
    baseEncode;
    constructor(name, prefix, baseEncode) {
        this.name = name;
        this.prefix = prefix;
        this.baseEncode = baseEncode;
    }
    encode(bytes) {
        if (bytes instanceof Uint8Array) {
            return `${this.prefix}${this.baseEncode(bytes)}`;
        }
        else {
            throw Error('Unknown type, must be binary type');
        }
    }
}
/**
 * Class represents both BaseDecoder and MultibaseDecoder so it could be used
 * to decode multibases (with matching prefix) or just base decode strings
 * with corresponding base encoding.
 */
class Decoder {
    name;
    prefix;
    baseDecode;
    prefixCodePoint;
    constructor(name, prefix, baseDecode) {
        this.name = name;
        this.prefix = prefix;
        const prefixCodePoint = prefix.codePointAt(0);
        /* c8 ignore next 3 */
        if (prefixCodePoint === undefined) {
            throw new Error('Invalid prefix character');
        }
        this.prefixCodePoint = prefixCodePoint;
        this.baseDecode = baseDecode;
    }
    decode(text) {
        if (typeof text === 'string') {
            if (text.codePointAt(0) !== this.prefixCodePoint) {
                throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);
            }
            return this.baseDecode(text.slice(this.prefix.length));
        }
        else {
            throw Error('Can only multibase decode strings');
        }
    }
    or(decoder) {
        return or(this, decoder);
    }
}
class ComposedDecoder {
    decoders;
    constructor(decoders) {
        this.decoders = decoders;
    }
    or(decoder) {
        return or(this, decoder);
    }
    decode(input) {
        const prefix = input[0];
        const decoder = this.decoders[prefix];
        if (decoder != null) {
            return decoder.decode(input);
        }
        else {
            throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);
        }
    }
}
export function or(left, right) {
    return new ComposedDecoder({
        ...(left.decoders ?? { [left.prefix]: left }),
        ...(right.decoders ?? { [right.prefix]: right })
    });
}
export class Codec {
    name;
    prefix;
    baseEncode;
    baseDecode;
    encoder;
    decoder;
    constructor(name, prefix, baseEncode, baseDecode) {
        this.name = name;
        this.prefix = prefix;
        this.baseEncode = baseEncode;
        this.baseDecode = baseDecode;
        this.encoder = new Encoder(name, prefix, baseEncode);
        this.decoder = new Decoder(name, prefix, baseDecode);
    }
    encode(input) {
        return this.encoder.encode(input);
    }
    decode(input) {
        return this.decoder.decode(input);
    }
}
export function from({ name, prefix, encode, decode }) {
    return new Codec(name, prefix, encode, decode);
}
export function baseX({ name, prefix, alphabet }) {
    const { encode, decode } = basex(alphabet, name);
    return from({
        prefix,
        name,
        encode,
        decode: (text) => coerce(decode(text))
    });
}
function decode(string, alphabetIdx, bitsPerChar, name) {
    // Count the padding bytes:
    let end = string.length;
    while (string[end - 1] === '=') {
        --end;
    }
    // Allocate the output:
    const out = new Uint8Array((end * bitsPerChar / 8) | 0);
    // Parse the data:
    let bits = 0; // Number of bits currently in the buffer
    let buffer = 0; // Bits waiting to be written out, MSB first
    let written = 0; // Next byte to write
    for (let i = 0; i < end; ++i) {
        // Read one character from the string:
        const value = alphabetIdx[string[i]];
        if (value === undefined) {
            throw new SyntaxError(`Non-${name} character`);
        }
        // Append the bits to the buffer:
        buffer = (buffer << bitsPerChar) | value;
        bits += bitsPerChar;
        // Write out some bits if the buffer has a byte's worth:
        if (bits >= 8) {
            bits -= 8;
            out[written++] = 0xff & (buffer >> bits);
        }
    }
    // Verify that we have received just enough bits:
    if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {
        throw new SyntaxError('Unexpected end of data');
    }
    return out;
}
function encode(data, alphabet, bitsPerChar) {
    const pad = alphabet[alphabet.length - 1] === '=';
    const mask = (1 << bitsPerChar) - 1;
    let out = '';
    let bits = 0; // Number of bits currently in the buffer
    let buffer = 0; // Bits waiting to be written out, MSB first
    for (let i = 0; i < data.length; ++i) {
        // Slurp data into the buffer:
        buffer = (buffer << 8) | data[i];
        bits += 8;
        // Write out as much as we can:
        while (bits > bitsPerChar) {
            bits -= bitsPerChar;
            out += alphabet[mask & (buffer >> bits)];
        }
    }
    // Partial character:
    if (bits !== 0) {
        out += alphabet[mask & (buffer << (bitsPerChar - bits))];
    }
    // Add padding characters until we hit a byte boundary:
    if (pad) {
        while (((out.length * bitsPerChar) & 7) !== 0) {
            out += '=';
        }
    }
    return out;
}
function createAlphabetIdx(alphabet) {
    // Build the character lookup table:
    const alphabetIdx = {};
    for (let i = 0; i < alphabet.length; ++i) {
        alphabetIdx[alphabet[i]] = i;
    }
    return alphabetIdx;
}
/**
 * RFC4648 Factory
 */
export function rfc4648({ name, prefix, bitsPerChar, alphabet }) {
    const alphabetIdx = createAlphabetIdx(alphabet);
    return from({
        prefix,
        name,
        encode(input) {
            return encode(input, alphabet, bitsPerChar);
        },
        decode(input) {
            return decode(input, alphabetIdx, bitsPerChar, name);
        }
    });
}
//# sourceMappingURL=base.js.mapimport { rfc4648 } from './base.js';
export const base32 = rfc4648({
    prefix: 'b',
    name: 'base32',
    alphabet: 'abcdefghijklmnopqrstuvwxyz234567',
    bitsPerChar: 5
});
export const base32upper = rfc4648({
    prefix: 'B',
    name: 'base32upper',
    alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',
    bitsPerChar: 5
});
export const base32pad = rfc4648({
    prefix: 'c',
    name: 'base32pad',
    alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',
    bitsPerChar: 5
});
export const base32padupper = rfc4648({
    prefix: 'C',
    name: 'base32padupper',
    alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',
    bitsPerChar: 5
});
export const base32hex = rfc4648({
    prefix: 'v',
    name: 'base32hex',
    alphabet: '0123456789abcdefghijklmnopqrstuv',
    bitsPerChar: 5
});
export const base32hexupper = rfc4648({
    prefix: 'V',
    name: 'base32hexupper',
    alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',
    bitsPerChar: 5
});
export const base32hexpad = rfc4648({
    prefix: 't',
    name: 'base32hexpad',
    alphabet: '0123456789abcdefghijklmnopqrstuv=',
    bitsPerChar: 5
});
export const base32hexpadupper = rfc4648({
    prefix: 'T',
    name: 'base32hexpadupper',
    alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',
    bitsPerChar: 5
});
export const base32z = rfc4648({
    prefix: 'h',
    name: 'base32z',
    alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',
    bitsPerChar: 5
});
//# sourceMappingURL=base32.js.mapimport { baseX } from './base.js';
export const base36 = baseX({
    prefix: 'k',
    name: 'base36',
    alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'
});
export const base36upper = baseX({
    prefix: 'K',
    name: 'base36upper',
    alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
});
//# sourceMappingURL=base36.js.mapimport { baseX } from './base.js';
export const base58btc = baseX({
    name: 'base58btc',
    prefix: 'z',
    alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
});
export const base58flickr = baseX({
    name: 'base58flickr',
    prefix: 'Z',
    alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'
});
//# sourceMappingURL=base58.js.mapexport const empty = new Uint8Array(0);
export function toHex(d) {
    return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '');
}
export function fromHex(hex) {
    const hexes = hex.match(/../g);
    return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty;
}
export function equals(aa, bb) {
    if (aa === bb) {
        return true;
    }
    if (aa.byteLength !== bb.byteLength) {
        return false;
    }
    for (let ii = 0; ii < aa.byteLength; ii++) {
        if (aa[ii] !== bb[ii]) {
            return false;
        }
    }
    return true;
}
export function coerce(o) {
    if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') {
        return o;
    }
    if (o instanceof ArrayBuffer) {
        return new Uint8Array(o);
    }
    if (ArrayBuffer.isView(o)) {
        return new Uint8Array(o.buffer, o.byteOffset, o.byteLength);
    }
    throw new Error('Unknown type, must be binary type');
}
export function isBinary(o) {
    return o instanceof ArrayBuffer || ArrayBuffer.isView(o);
}
export function fromString(str) {
    return new TextEncoder().encode(str);
}
export function toString(b) {
    return new TextDecoder().decode(b);
}
//# sourceMappingURL=bytes.js.mapimport { base32 } from './bases/base32.js';
import { base36 } from './bases/base36.js';
import { base58btc } from './bases/base58.js';
import { coerce } from './bytes.js';
import * as Digest from './hashes/digest.js';
import * as varint from './varint.js';
// This way TS will also expose all the types from module
export * from './link/interface.js';
export function format(link, base) {
    const { bytes, version } = link;
    switch (version) {
        case 0:
            return toStringV0(bytes, baseCache(link), base ?? base58btc.encoder);
        default:
            return toStringV1(bytes, baseCache(link), (base ?? base32.encoder));
    }
}
export function toJSON(link) {
    return {
        '/': format(link)
    };
}
export function fromJSON(json) {
    return CID.parse(json['/']);
}
const cache = new WeakMap();
function baseCache(cid) {
    const baseCache = cache.get(cid);
    if (baseCache == null) {
        const baseCache = new Map();
        cache.set(cid, baseCache);
        return baseCache;
    }
    return baseCache;
}
export class CID {
    code;
    version;
    multihash;
    bytes;
    '/';
    /**
     * @param version - Version of the CID
     * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
     * @param multihash - (Multi)hash of the of the content.
     */
    constructor(version, code, multihash, bytes) {
        this.code = code;
        this.version = version;
        this.multihash = multihash;
        this.bytes = bytes;
        // flag to serializers that this is a CID and
        // should be treated specially
        this['/'] = bytes;
    }
    /**
     * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`
     * please either use `CID.asCID(cid)` or switch to new signalling mechanism
     *
     * @deprecated
     */
    get asCID() {
        return this;
    }
    // ArrayBufferView
    get byteOffset() {
        return this.bytes.byteOffset;
    }
    // ArrayBufferView
    get byteLength() {
        return this.bytes.byteLength;
    }
    toV0() {
        switch (this.version) {
            case 0: {
                return this;
            }
            case 1: {
                const { code, multihash } = this;
                if (code !== DAG_PB_CODE) {
                    throw new Error('Cannot convert a non dag-pb CID to CIDv0');
                }
                // sha2-256
                if (multihash.code !== SHA_256_CODE) {
                    throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0');
                }
                return (CID.createV0(multihash));
            }
            default: {
                throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);
            }
        }
    }
    toV1() {
        switch (this.version) {
            case 0: {
                const { code, digest } = this.multihash;
                const multihash = Digest.create(code, digest);
                return (CID.createV1(this.code, multihash));
            }
            case 1: {
                return this;
            }
            default: {
                throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);
            }
        }
    }
    equals(other) {
        return CID.equals(this, other);
    }
    static equals(self, other) {
        const unknown = other;
        return (unknown != null &&
            self.code === unknown.code &&
            self.version === unknown.version &&
            Digest.equals(self.multihash, unknown.multihash));
    }
    toString(base) {
        return format(this, base);
    }
    toJSON() {
        return { '/': format(this) };
    }
    link() {
        return this;
    }
    [Symbol.toStringTag] = 'CID';
    // Legacy
    [Symbol.for('nodejs.util.inspect.custom')]() {
        return `CID(${this.toString()})`;
    }
    /**
     * Takes any input `value` and returns a `CID` instance if it was
     * a `CID` otherwise returns `null`. If `value` is instanceof `CID`
     * it will return value back. If `value` is not instance of this CID
     * class, but is compatible CID it will return new instance of this
     * `CID` class. Otherwise returns null.
     *
     * This allows two different incompatible versions of CID library to
     * co-exist and interop as long as binary interface is compatible.
     */
    static asCID(input) {
        if (input == null) {
            return null;
        }
        const value = input;
        if (value instanceof CID) {
            // If value is instance of CID then we're all set.
            return value;
        }
        else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {
            // If value isn't instance of this CID class but `this.asCID === this` or
            // `value['/'] === value.bytes` is true it is CID instance coming from a
            // different implementation (diff version or duplicate). In that case we
            // rebase it to this `CID` implementation so caller is guaranteed to get
            // instance with expected API.
            const { version, code, multihash, bytes } = value;
            return new CID(version, code, multihash, bytes ?? encodeCID(version, code, multihash.bytes));
        }
        else if (value[cidSymbol] === true) {
            // If value is a CID from older implementation that used to be tagged via
            // symbol we still rebase it to the this `CID` implementation by
            // delegating that to a constructor.
            const { version, multihash, code } = value;
            const digest = Digest.decode(multihash);
            return CID.create(version, code, digest);
        }
        else {
            // Otherwise value is not a CID (or an incompatible version of it) in
            // which case we return `null`.
            return null;
        }
    }
    /**
     * @param version - Version of the CID
     * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
     * @param digest - (Multi)hash of the of the content.
     */
    static create(version, code, digest) {
        if (typeof code !== 'number') {
            throw new Error('String codecs are no longer supported');
        }
        if (!(digest.bytes instanceof Uint8Array)) {
            throw new Error('Invalid digest');
        }
        switch (version) {
            case 0: {
                if (code !== DAG_PB_CODE) {
                    throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);
                }
                else {
                    return new CID(version, code, digest, digest.bytes);
                }
            }
            case 1: {
                const bytes = encodeCID(version, code, digest.bytes);
                return new CID(version, code, digest, bytes);
            }
            default: {
                throw new Error('Invalid version');
            }
        }
    }
    /**
     * Simplified version of `create` for CIDv0.
     */
    static createV0(digest) {
        return CID.create(0, DAG_PB_CODE, digest);
    }
    /**
     * Simplified version of `create` for CIDv1.
     *
     * @param code - Content encoding format code.
     * @param digest - Multihash of the content.
     */
    static createV1(code, digest) {
        return CID.create(1, code, digest);
    }
    /**
     * Decoded a CID from its binary representation. The byte array must contain
     * only the CID with no additional bytes.
     *
     * An error will be thrown if the bytes provided do not contain a valid
     * binary representation of a CID.
     */
    static decode(bytes) {
        const [cid, remainder] = CID.decodeFirst(bytes);
        if (remainder.length !== 0) {
            throw new Error('Incorrect length');
        }
        return cid;
    }
    /**
     * Decoded a CID from its binary representation at the beginning of a byte
     * array.
     *
     * Returns an array with the first element containing the CID and the second
     * element containing the remainder of the original byte array. The remainder
     * will be a zero-length byte array if the provided bytes only contained a
     * binary CID representation.
     */
    static decodeFirst(bytes) {
        const specs = CID.inspectBytes(bytes);
        const prefixSize = specs.size - specs.multihashSize;
        const multihashBytes = coerce(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));
        if (multihashBytes.byteLength !== specs.multihashSize) {
            throw new Error('Incorrect length');
        }
        const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);
        const digest = new Digest.Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);
        const cid = specs.version === 0
            ? CID.createV0(digest)
            : CID.createV1(specs.codec, digest);
        return [cid, bytes.subarray(specs.size)];
    }
    /**
     * Inspect the initial bytes of a CID to determine its properties.
     *
     * Involves decoding up to 4 varints. Typically this will require only 4 to 6
     * bytes but for larger multicodec code values and larger multihash digest
     * lengths these varints can be quite large. It is recommended that at least
     * 10 bytes be made available in the `initialBytes` argument for a complete
     * inspection.
     */
    static inspectBytes(initialBytes) {
        let offset = 0;
        const next = () => {
            const [i, length] = varint.decode(initialBytes.subarray(offset));
            offset += length;
            return i;
        };
        let version = next();
        let codec = DAG_PB_CODE;
        if (version === 18) {
            // CIDv0
            version = 0;
            offset = 0;
        }
        else {
            codec = next();
        }
        if (version !== 0 && version !== 1) {
            throw new RangeError(`Invalid CID version ${version}`);
        }
        const prefixSize = offset;
        const multihashCode = next(); // multihash code
        const digestSize = next(); // multihash length
        const size = offset + digestSize;
        const multihashSize = size - prefixSize;
        return { version, codec, multihashCode, digestSize, multihashSize, size };
    }
    /**
     * Takes cid in a string representation and creates an instance. If `base`
     * decoder is not provided will use a default from the configuration. It will
     * throw an error if encoding of the CID is not compatible with supplied (or
     * a default decoder).
     */
    static parse(source, base) {
        const [prefix, bytes] = parseCIDtoBytes(source, base);
        const cid = CID.decode(bytes);
        if (cid.version === 0 && source[0] !== 'Q') {
            throw Error('Version 0 CID string must not include multibase prefix');
        }
        // Cache string representation to avoid computing it on `this.toString()`
        baseCache(cid).set(prefix, source);
        return cid;
    }
}
function parseCIDtoBytes(source, base) {
    switch (source[0]) {
        // CIDv0 is parsed differently
        case 'Q': {
            const decoder = base ?? base58btc;
            return [
                base58btc.prefix,
                decoder.decode(`${base58btc.prefix}${source}`)
            ];
        }
        case base58btc.prefix: {
            const decoder = base ?? base58btc;
            return [base58btc.prefix, decoder.decode(source)];
        }
        case base32.prefix: {
            const decoder = base ?? base32;
            return [base32.prefix, decoder.decode(source)];
        }
        case base36.prefix: {
            const decoder = base ?? base36;
            return [base36.prefix, decoder.decode(source)];
        }
        default: {
            if (base == null) {
                throw Error('To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided');
            }
            return [source[0], base.decode(source)];
        }
    }
}
function toStringV0(bytes, cache, base) {
    const { prefix } = base;
    if (prefix !== base58btc.prefix) {
        throw Error(`Cannot string encode V0 in ${base.name} encoding`);
    }
    const cid = cache.get(prefix);
    if (cid == null) {
        const cid = base.encode(bytes).slice(1);
        cache.set(prefix, cid);
        return cid;
    }
    else {
        return cid;
    }
}
function toStringV1(bytes, cache, base) {
    const { prefix } = base;
    const cid = cache.get(prefix);
    if (cid == null) {
        const cid = base.encode(bytes);
        cache.set(prefix, cid);
        return cid;
    }
    else {
        return cid;
    }
}
const DAG_PB_CODE = 0x70;
const SHA_256_CODE = 0x12;
function encodeCID(version, code, multihash) {
    const codeOffset = varint.encodingLength(version);
    const hashOffset = codeOffset + varint.encodingLength(code);
    const bytes = new Uint8Array(hashOffset + multihash.byteLength);
    varint.encodeTo(version, bytes, 0);
    varint.encodeTo(code, bytes, codeOffset);
    bytes.set(multihash, hashOffset);
    return bytes;
}
const cidSymbol = Symbol.for('@ipld/js-cid/CID');
//# sourceMappingURL=cid.js.mapimport { coerce } from '../bytes.js';
export const name = 'raw';
export const code = 0x55;
export function encode(node) {
    return coerce(node);
}
export function decode(data) {
    return coerce(data);
}
//# sourceMappingURL=raw.js.mapimport { coerce, equals as equalBytes } from '../bytes.js';
import * as varint from '../varint.js';
/**
 * Creates a multihash digest.
 */
export function create(code, digest) {
    const size = digest.byteLength;
    const sizeOffset = varint.encodingLength(code);
    const digestOffset = sizeOffset + varint.encodingLength(size);
    const bytes = new Uint8Array(digestOffset + size);
    varint.encodeTo(code, bytes, 0);
    varint.encodeTo(size, bytes, sizeOffset);
    bytes.set(digest, digestOffset);
    return new Digest(code, size, digest, bytes);
}
/**
 * Turns bytes representation of multihash digest into an instance.
 */
export function decode(multihash) {
    const bytes = coerce(multihash);
    const [code, sizeOffset] = varint.decode(bytes);
    const [size, digestOffset] = varint.decode(bytes.subarray(sizeOffset));
    const digest = bytes.subarray(sizeOffset + digestOffset);
    if (digest.byteLength !== size) {
        throw new Error('Incorrect length');
    }
    return new Digest(code, size, digest, bytes);
}
export function equals(a, b) {
    if (a === b) {
        return true;
    }
    else {
        const data = b;
        return (a.code === data.code &&
            a.size === data.size &&
            data.bytes instanceof Uint8Array &&
            equalBytes(a.bytes, data.bytes));
    }
}
/**
 * Represents a multihash digest which carries information about the
 * hashing algorithm and an actual hash digest.
 */
export class Digest {
    code;
    size;
    digest;
    bytes;
    /**
     * Creates a multihash digest.
     */
    constructor(code, size, digest, bytes) {
        this.code = code;
        this.size = size;
        this.digest = digest;
        this.bytes = bytes;
    }
}
/**
 * Used to check that the passed multihash has the passed code
 */
export function hasCode(digest, code) {
    return digest.code === code;
}
//# sourceMappingURL=digest.js.mapexport {};
//# sourceMappingURL=interface.js.mapimport varint from './vendor/varint.js';
export function decode(data, offset = 0) {
    const code = varint.decode(data, offset);
    return [code, varint.decode.bytes];
}
export function encodeTo(int, target, offset = 0) {
    varint.encode(int, target, offset);
    return target;
}
export function encodingLength(int) {
    return varint.encodingLength(int);
}
//# sourceMappingURL=varint.js.map/* eslint-disable */
// base-x encoding / decoding
// Copyright (c) 2018 base-x contributors
// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)
// Distributed under the MIT software license, see the accompanying
// file LICENSE or http://www.opensource.org/licenses/mit-license.php.
/**
 * @param {string} ALPHABET
 * @param {any} name
 */
function base(ALPHABET, name) {
    if (ALPHABET.length >= 255) {
        throw new TypeError('Alphabet too long');
    }
    var BASE_MAP = new Uint8Array(256);
    for (var j = 0; j < BASE_MAP.length; j++) {
        BASE_MAP[j] = 255;
    }
    for (var i = 0; i < ALPHABET.length; i++) {
        var x = ALPHABET.charAt(i);
        var xc = x.charCodeAt(0);
        if (BASE_MAP[xc] !== 255) {
            throw new TypeError(x + ' is ambiguous');
        }
        BASE_MAP[xc] = i;
    }
    var BASE = ALPHABET.length;
    var LEADER = ALPHABET.charAt(0);
    var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up
    var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up
    /**
     * @param {any[] | Iterable<number>} source
     */
    function encode(source) {
        // @ts-ignore
        if (source instanceof Uint8Array)
            ;
        else if (ArrayBuffer.isView(source)) {
            source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
        }
        else if (Array.isArray(source)) {
            source = Uint8Array.from(source);
        }
        if (!(source instanceof Uint8Array)) {
            throw new TypeError('Expected Uint8Array');
        }
        if (source.length === 0) {
            return '';
        }
        // Skip & count leading zeroes.
        var zeroes = 0;
        var length = 0;
        var pbegin = 0;
        var pend = source.length;
        while (pbegin !== pend && source[pbegin] === 0) {
            pbegin++;
            zeroes++;
        }
        // Allocate enough space in big-endian base58 representation.
        var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;
        var b58 = new Uint8Array(size);
        // Process the bytes.
        while (pbegin !== pend) {
            var carry = source[pbegin];
            // Apply "b58 = b58 * 256 + ch".
            var i = 0;
            for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {
                carry += (256 * b58[it1]) >>> 0;
                b58[it1] = (carry % BASE) >>> 0;
                carry = (carry / BASE) >>> 0;
            }
            if (carry !== 0) {
                throw new Error('Non-zero carry');
            }
            length = i;
            pbegin++;
        }
        // Skip leading zeroes in base58 result.
        var it2 = size - length;
        while (it2 !== size && b58[it2] === 0) {
            it2++;
        }
        // Translate the result into a string.
        var str = LEADER.repeat(zeroes);
        for (; it2 < size; ++it2) {
            str += ALPHABET.charAt(b58[it2]);
        }
        return str;
    }
    /**
     * @param {string | string[]} source
     */
    function decodeUnsafe(source) {
        if (typeof source !== 'string') {
            throw new TypeError('Expected String');
        }
        if (source.length === 0) {
            return new Uint8Array();
        }
        var psz = 0;
        // Skip leading spaces.
        if (source[psz] === ' ') {
            return;
        }
        // Skip and count leading '1's.
        var zeroes = 0;
        var length = 0;
        while (source[psz] === LEADER) {
            zeroes++;
            psz++;
        }
        // Allocate enough space in big-endian base256 representation.
        var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.
        var b256 = new Uint8Array(size);
        // Process the characters.
        while (source[psz]) {
            // Decode character
            var carry = BASE_MAP[source.charCodeAt(psz)];
            // Invalid character
            if (carry === 255) {
                return;
            }
            var i = 0;
            for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {
                carry += (BASE * b256[it3]) >>> 0;
                b256[it3] = (carry % 256) >>> 0;
                carry = (carry / 256) >>> 0;
            }
            if (carry !== 0) {
                throw new Error('Non-zero carry');
            }
            length = i;
            psz++;
        }
        // Skip trailing spaces.
        if (source[psz] === ' ') {
            return;
        }
        // Skip leading zeroes in b256.
        var it4 = size - length;
        while (it4 !== size && b256[it4] === 0) {
            it4++;
        }
        var vch = new Uint8Array(zeroes + (size - it4));
        var j = zeroes;
        while (it4 !== size) {
            vch[j++] = b256[it4++];
        }
        return vch;
    }
    /**
     * @param {string | string[]} string
     */
    function decode(string) {
        var buffer = decodeUnsafe(string);
        if (buffer) {
            return buffer;
        }
        throw new Error(`Non-${name} character`);
    }
    return {
        encode: encode,
        decodeUnsafe: decodeUnsafe,
        decode: decode
    };
}
var src = base;
var _brrp__multiformats_scope_baseX = src;
export default _brrp__multiformats_scope_baseX;
//# sourceMappingURL=base-x.js.map/* eslint-disable */
var encode_1 = encode;
var MSB = 0x80, REST = 0x7F, MSBALL = ~REST, INT = Math.pow(2, 31);
/**
 * @param {number} num
 * @param {number[]} out
 * @param {number} offset
 */
function encode(num, out, offset) {
    out = out || [];
    offset = offset || 0;
    var oldOffset = offset;
    while (num >= INT) {
        out[offset++] = (num & 0xFF) | MSB;
        num /= 128;
    }
    while (num & MSBALL) {
        out[offset++] = (num & 0xFF) | MSB;
        num >>>= 7;
    }
    out[offset] = num | 0;
    // @ts-ignore
    encode.bytes = offset - oldOffset + 1;
    return out;
}
var decode = read;
var MSB$1 = 0x80, REST$1 = 0x7F;
/**
 * @param {string | any[]} buf
 * @param {number} offset
 */
function read(buf, offset) {
    var res = 0, offset = offset || 0, shift = 0, counter = offset, b, l = buf.length;
    do {
        if (counter >= l) {
            // @ts-ignore
            read.bytes = 0;
            throw new RangeError('Could not decode varint');
        }
        b = buf[counter++];
        res += shift < 28
            ? (b & REST$1) << shift
            : (b & REST$1) * Math.pow(2, shift);
        shift += 7;
    } while (b >= MSB$1);
    // @ts-ignore
    read.bytes = counter - offset;
    return res;
}
var N1 = Math.pow(2, 7);
var N2 = Math.pow(2, 14);
var N3 = Math.pow(2, 21);
var N4 = Math.pow(2, 28);
var N5 = Math.pow(2, 35);
var N6 = Math.pow(2, 42);
var N7 = Math.pow(2, 49);
var N8 = Math.pow(2, 56);
var N9 = Math.pow(2, 63);
var length = function (/** @type {number} */ value) {
    return (value < N1 ? 1
        : value < N2 ? 2
            : value < N3 ? 3
                : value < N4 ? 4
                    : value < N5 ? 5
                        : value < N6 ? 6
                            : value < N7 ? 7
                                : value < N8 ? 8
                                    : value < N9 ? 9
                                        : 10);
};
var varint = {
    encode: encode_1,
    decode: decode,
    encodingLength: length
};
var _brrp_varint = varint;
export default _brrp_varint;
//# sourceMappingURL=varint.js.map{
  "name": "multiformats",
  "version": "13.4.2",
  "description": "Interface for multihash, multicodec, multibase and CID",
  "author": "Mikeal Rogers <mikeal.rogers@gmail.com> (https://www.mikealrogers.com/)",
  "license": "Apache-2.0 OR MIT",
  "homepage": "https://github.com/multiformats/js-multiformats#readme",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/multiformats/js-multiformats.git"
  },
  "bugs": {
    "url": "https://github.com/multiformats/js-multiformats/issues"
  },
  "publishConfig": {
    "access": "public",
    "provenance": true
  },
  "keywords": [
    "ipfs",
    "ipld",
    "multiformats"
  ],
  "type": "module",
  "types": "./dist/src/index.d.ts",
  "typesVersions": {
    "*": {
      "*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ],
      "src/*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ]
    }
  },
  "files": [
    "src",
    "dist",
    "!dist/test",
    "!**/*.tsbuildinfo"
  ],
  "exports": {
    ".": {
      "types": "./dist/src/index.d.ts",
      "import": "./dist/src/index.js"
    },
    "./bases/base10": {
      "types": "./dist/src/bases/base10.d.ts",
      "import": "./dist/src/bases/base10.js"
    },
    "./bases/base16": {
      "types": "./dist/src/bases/base16.d.ts",
      "import": "./dist/src/bases/base16.js"
    },
    "./bases/base2": {
      "types": "./dist/src/bases/base2.d.ts",
      "import": "./dist/src/bases/base2.js"
    },
    "./bases/base256emoji": {
      "types": "./dist/src/bases/base256emoji.d.ts",
      "import": "./dist/src/bases/base256emoji.js"
    },
    "./bases/base32": {
      "types": "./dist/src/bases/base32.d.ts",
      "import": "./dist/src/bases/base32.js"
    },
    "./bases/base36": {
      "types": "./dist/src/bases/base36.d.ts",
      "import": "./dist/src/bases/base36.js"
    },
    "./bases/base58": {
      "types": "./dist/src/bases/base58.d.ts",
      "import": "./dist/src/bases/base58.js"
    },
    "./bases/base64": {
      "types": "./dist/src/bases/base64.d.ts",
      "import": "./dist/src/bases/base64.js"
    },
    "./bases/base8": {
      "types": "./dist/src/bases/base8.d.ts",
      "import": "./dist/src/bases/base8.js"
    },
    "./bases/identity": {
      "types": "./dist/src/bases/identity.d.ts",
      "import": "./dist/src/bases/identity.js"
    },
    "./bases/interface": {
      "types": "./dist/src/bases/interface.d.ts",
      "import": "./dist/src/bases/interface.js"
    },
    "./basics": {
      "types": "./dist/src/basics.d.ts",
      "import": "./dist/src/basics.js"
    },
    "./block": {
      "types": "./dist/src/block.d.ts",
      "import": "./dist/src/block.js"
    },
    "./block/interface": {
      "types": "./dist/src/block/interface.d.ts",
      "import": "./dist/src/block/interface.js"
    },
    "./bytes": {
      "types": "./dist/src/bytes.d.ts",
      "import": "./dist/src/bytes.js"
    },
    "./cid": {
      "types": "./dist/src/cid.d.ts",
      "import": "./dist/src/cid.js"
    },
    "./codecs/interface": {
      "types": "./dist/src/codecs/interface.d.ts",
      "import": "./dist/src/codecs/interface.js"
    },
    "./codecs/json": {
      "types": "./dist/src/codecs/json.d.ts",
      "import": "./dist/src/codecs/json.js"
    },
    "./codecs/raw": {
      "types": "./dist/src/codecs/raw.d.ts",
      "import": "./dist/src/codecs/raw.js"
    },
    "./hashes/digest": {
      "types": "./dist/src/hashes/digest.d.ts",
      "import": "./dist/src/hashes/digest.js"
    },
    "./hashes/hasher": {
      "types": "./dist/src/hashes/hasher.d.ts",
      "import": "./dist/src/hashes/hasher.js"
    },
    "./hashes/identity": {
      "types": "./dist/src/hashes/identity.d.ts",
      "import": "./dist/src/hashes/identity.js"
    },
    "./hashes/interface": {
      "types": "./dist/src/hashes/interface.d.ts",
      "import": "./dist/src/hashes/interface.js"
    },
    "./hashes/sha1": {
      "types": "./dist/types/src/hashes/sha1.d.ts",
      "browser": "./dist/src/hashes/sha1-browser.js",
      "import": "./dist/src/hashes/sha1.js"
    },
    "./hashes/sha2": {
      "types": "./dist/src/hashes/sha2.d.ts",
      "browser": "./dist/src/hashes/sha2-browser.js",
      "import": "./dist/src/hashes/sha2.js"
    },
    "./interface": {
      "types": "./dist/src/interface.d.ts",
      "import": "./dist/src/interface.js"
    },
    "./link": {
      "types": "./dist/src/link.d.ts",
      "import": "./dist/src/link.js"
    },
    "./link/interface": {
      "types": "./dist/src/link/interface.d.ts",
      "import": "./dist/src/link/interface.js"
    },
    "./traversal": {
      "types": "./dist/src/traversal.d.ts",
      "import": "./dist/src/traversal.js"
    }
  },
  "eslintConfig": {
    "extends": "ipfs",
    "parserOptions": {
      "project": true,
      "sourceType": "module"
    }
  },
  "release": {
    "branches": [
      "master"
    ],
    "plugins": [
      [
        "@semantic-release/commit-analyzer",
        {
          "preset": "conventionalcommits",
          "releaseRules": [
            {
              "breaking": true,
              "release": "major"
            },
            {
              "revert": true,
              "release": "patch"
            },
            {
              "type": "feat",
              "release": "minor"
            },
            {
              "type": "fix",
              "release": "patch"
            },
            {
              "type": "docs",
              "release": "patch"
            },
            {
              "type": "test",
              "release": "patch"
            },
            {
              "type": "deps",
              "release": "patch"
            },
            {
              "scope": "no-release",
              "release": false
            }
          ]
        }
      ],
      [
        "@semantic-release/release-notes-generator",
        {
          "preset": "conventionalcommits",
          "presetConfig": {
            "types": [
              {
                "type": "feat",
                "section": "Features"
              },
              {
                "type": "fix",
                "section": "Bug Fixes"
              },
              {
                "type": "chore",
                "section": "Trivial Changes"
              },
              {
                "type": "docs",
                "section": "Documentation"
              },
              {
                "type": "deps",
                "section": "Dependencies"
              },
              {
                "type": "test",
                "section": "Tests"
              }
            ]
          }
        }
      ],
      "@semantic-release/changelog",
      "@semantic-release/npm",
      "@semantic-release/github",
      [
        "@semantic-release/git",
        {
          "assets": [
            "CHANGELOG.md",
            "package.json"
          ]
        }
      ]
    ]
  },
  "scripts": {
    "clean": "aegir clean",
    "lint": "aegir lint",
    "build": "aegir build",
    "release": "aegir release",
    "docs": "aegir docs",
    "test": "npm run lint && npm run test:node && npm run test:chrome",
    "test:node": "aegir test -t node --cov",
    "test:chrome": "aegir test -t browser --cov",
    "test:chrome-webworker": "aegir test -t webworker",
    "test:firefox": "aegir test -t browser -- --browser firefox",
    "test:firefox-webworker": "aegir test -t webworker -- --browser firefox",
    "test:electron-main": "aegir test -t electron-main"
  },
  "devDependencies": {
    "@stablelib/sha256": "^2.0.0",
    "@stablelib/sha512": "^2.0.0",
    "@types/node": "^25.0.0",
    "aegir": "^47.0.7",
    "buffer": "^6.0.3",
    "cids": "^1.1.9",
    "crypto-hash": "^4.0.0"
  },
  "aegir": {
    "test": {
      "target": [
        "node",
        "browser"
      ]
    }
  },
  "browser": {
    "./hashes/sha1": "./dist/src/hashes/sha1-browser.js",
    "./dist/src/hashes/sha1.js": "./dist/src/hashes/sha1-browser.js",
    "./hashes/sha2": "./dist/src/hashes/sha2-browser.js",
    "./dist/src/hashes/sha2.js": "./dist/src/hashes/sha2-browser.js"
  }
}
{
  "name": "atproto-repo",
  "version": "0.0.1",
  "description": "Byte-exact atproto repo layer — CAR + DAG-CBOR + CID + MST — over Hypercore-friendly primitives. Verified against real relay-accepted repos.",
  "type": "module",
  "main": "lib/repo.js",
  "scripts": {
    "test": "brittle-node test/*.test.js",
    "postinstall": "node scripts/bare-deps.mjs"
  },
  "dependencies": {
    "@ipld/car": "^5.4.0",
    "@ipld/dag-cbor": "^9.2.1",
    "@noble/curves": "^1.9.7",
    "@noble/hashes": "^1.5.0",
    "multiformats": "^13.3.0"
  },
  "devDependencies": {
    "atproto-identity": "file:../atproto-identity",
    "brittle": "^4.0.2"
  }
}
function isBuffer(value) {
  return Buffer.isBuffer(value) || value instanceof Uint8Array
}

function isEncoding(encoding) {
  return Buffer.isEncoding(encoding)
}

function alloc(size, fill, encoding) {
  return Buffer.alloc(size, fill, encoding)
}

function allocUnsafe(size) {
  return Buffer.allocUnsafe(size)
}

function allocUnsafeSlow(size) {
  return Buffer.allocUnsafeSlow(size)
}

function byteLength(string, encoding) {
  return Buffer.byteLength(string, encoding)
}

function compare(a, b) {
  return Buffer.compare(a, b)
}

function concat(buffers, totalLength) {
  return Buffer.concat(buffers, totalLength)
}

function copy(source, target, targetStart, start, end) {
  return toBuffer(source).copy(target, targetStart, start, end)
}

function equals(a, b) {
  return toBuffer(a).equals(b)
}

function fill(buffer, value, offset, end, encoding) {
  return toBuffer(buffer).fill(value, offset, end, encoding)
}

function from(value, encodingOrOffset, length) {
  return Buffer.from(value, encodingOrOffset, length)
}

function includes(buffer, value, byteOffset, encoding) {
  return toBuffer(buffer).includes(value, byteOffset, encoding)
}

function indexOf(buffer, value, byfeOffset, encoding) {
  return toBuffer(buffer).indexOf(value, byfeOffset, encoding)
}

function lastIndexOf(buffer, value, byteOffset, encoding) {
  return toBuffer(buffer).lastIndexOf(value, byteOffset, encoding)
}

function swap16(buffer) {
  return toBuffer(buffer).swap16()
}

function swap32(buffer) {
  return toBuffer(buffer).swap32()
}

function swap64(buffer) {
  return toBuffer(buffer).swap64()
}

function toBuffer(buffer) {
  if (Buffer.isBuffer(buffer)) return buffer
  return Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

function toString(buffer, encoding, start, end) {
  return toBuffer(buffer).toString(encoding, start, end)
}

function write(buffer, string, offset, length, encoding) {
  return toBuffer(buffer).write(string, offset, length, encoding)
}

function readDoubleBE(buffer, offset) {
  return toBuffer(buffer).readDoubleBE(offset)
}

function readDoubleLE(buffer, offset) {
  return toBuffer(buffer).readDoubleLE(offset)
}

function readFloatBE(buffer, offset) {
  return toBuffer(buffer).readFloatBE(offset)
}

function readFloatLE(buffer, offset) {
  return toBuffer(buffer).readFloatLE(offset)
}

function readInt32BE(buffer, offset) {
  return toBuffer(buffer).readInt32BE(offset)
}

function readInt32LE(buffer, offset) {
  return toBuffer(buffer).readInt32LE(offset)
}

function readUInt32BE(buffer, offset) {
  return toBuffer(buffer).readUInt32BE(offset)
}

function readUInt32LE(buffer, offset) {
  return toBuffer(buffer).readUInt32LE(offset)
}

function writeDoubleBE(buffer, value, offset) {
  return toBuffer(buffer).writeDoubleBE(value, offset)
}

function writeDoubleLE(buffer, value, offset) {
  return toBuffer(buffer).writeDoubleLE(value, offset)
}

function writeFloatBE(buffer, value, offset) {
  return toBuffer(buffer).writeFloatBE(value, offset)
}

function writeFloatLE(buffer, value, offset) {
  return toBuffer(buffer).writeFloatLE(value, offset)
}

function writeInt32BE(buffer, value, offset) {
  return toBuffer(buffer).writeInt32BE(value, offset)
}

function writeInt32LE(buffer, value, offset) {
  return toBuffer(buffer).writeInt32LE(value, offset)
}

function writeUInt32BE(buffer, value, offset) {
  return toBuffer(buffer).writeUInt32BE(value, offset)
}

function writeUInt32LE(buffer, value, offset) {
  return toBuffer(buffer).writeUInt32LE(value, offset)
}

module.exports = {
  isBuffer,
  isEncoding,
  alloc,
  allocUnsafe,
  allocUnsafeSlow,
  byteLength,
  compare,
  concat,
  copy,
  equals,
  fill,
  from,
  includes,
  indexOf,
  lastIndexOf,
  swap16,
  swap32,
  swap64,
  toBuffer,
  toString,
  write,
  readDoubleBE,
  readDoubleLE,
  readFloatBE,
  readFloatLE,
  readInt32BE,
  readInt32LE,
  readUInt32BE,
  readUInt32LE,
  writeDoubleBE,
  writeDoubleLE,
  writeFloatBE,
  writeFloatLE,
  writeInt32BE,
  writeInt32LE,
  writeUInt32BE,
  writeUInt32LE
}
{
  "name": "b4a",
  "version": "1.8.1",
  "description": "Bridging the gap between buffers and typed arrays",
  "exports": {
    "./package": "./package.json",
    ".": {
      "react-native": "./react-native.js",
      "browser": "./browser.js",
      "default": "./index.js"
    }
  },
  "files": [
    "browser.js",
    "index.js",
    "react-native.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:bare && npm run test:node",
    "test:bare": "brittle-bare --coverage test.mjs",
    "test:node": "brittle-node --coverage test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/b4a.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/b4a/issues"
  },
  "homepage": "https://github.com/holepunchto/b4a#readme",
  "devDependencies": {
    "brittle": "^3.5.2",
    "lunte": "^1.7.0",
    "nanobench": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "react-native-b4a": "*"
  },
  "peerDependenciesMeta": {
    "react-native-b4a": {
      "optional": true
    }
  }
}
const ESC = '\x1b'
const CSI = ESC + '['
const SGR = (n) => CSI + n + 'm'

exports.constants = {
  ESC,
  CSI,
  SGR
}

// https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_(Control_Sequence_Introducer)_sequences

exports.cursorHide = CSI + '?25l'
exports.cursorShow = CSI + '?25h'

exports.cursorUp = function cursorUp(n = 1) {
  return CSI + n + 'A'
}

exports.cursorDown = function cursorDown(n = 1) {
  return CSI + n + 'B'
}

exports.cursorForward = function cursorForward(n = 1) {
  return CSI + n + 'C'
}

exports.cursorBack = function cursorBack(n = 1) {
  return CSI + n + 'D'
}

exports.cursorNextLine = function cursorNextLine(n = 1) {
  return CSI + n + 'E'
}

exports.cursorPreviousLine = function cursorPreviousLine(n = 1) {
  return CSI + n + 'F'
}

exports.cursorPosition = function cursorPosition(column, row = 0) {
  if (row === 0) return CSI + (column + 1) + 'G'

  return CSI + (row + 1) + ';' + (column + 1) + 'H'
}

exports.eraseDisplayEnd = CSI + 'J'
exports.eraseDisplayStart = CSI + '1J'
exports.eraseDisplay = CSI + '2J'
exports.eraseLineEnd = CSI + 'K'
exports.eraseLineStart = CSI + '1K'
exports.eraseLine = CSI + '2K'

exports.scrollUp = function scrollUp(n = 1) {
  return CSI + n + 'S'
}

exports.scrollDown = function scrollDown(n = 1) {
  return CSI + n + 'T'
}

// https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_(Select_Graphic_Rendition)_parameters

exports.modifierReset = SGR(0)
exports.modifierBold = SGR(1)
exports.modifierDim = SGR(2)
exports.modifierItalic = SGR(3)
exports.modifierUnderline = SGR(4)
exports.modifierNormal = SGR(22)
exports.modifierNotItalic = SGR(23)
exports.modifierNotUnderline = SGR(24)

// https://en.wikipedia.org/wiki/ANSI_escape_code#Colors

exports.colorBlack = SGR(30)
exports.colorRed = SGR(31)
exports.colorGreen = SGR(32)
exports.colorYellow = SGR(33)
exports.colorBlue = SGR(34)
exports.colorMagenta = SGR(35)
exports.colorCyan = SGR(36)
exports.colorWhite = SGR(37)
exports.colorDefault = SGR(39)
exports.colorBrightBlack = SGR(90)
exports.colorBrightRed = SGR(91)
exports.colorBrightGreen = SGR(92)
exports.colorBrightYellow = SGR(93)
exports.colorBrightBlue = SGR(94)
exports.colorBrightMagenta = SGR(95)
exports.colorBrightCyan = SGR(96)
exports.colorBrightWhite = SGR(97)
{
  "name": "bare-ansi-escapes",
  "version": "2.2.3",
  "description": "Parse and produce ANSI escape sequences",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./key-decoder": {
      "types": "./key-decoder.d.ts",
      "default": "./key-decoder.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "key-decoder.js",
    "key-decoder.d.ts"
  ],
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-ansi-escapes.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-ansi-escapes/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-ansi-escapes#readme",
  "dependencies": {
    "bare-stream": "^2.6.5"
  },
  "devDependencies": {
    "bare-buffer": "^3.0.2",
    "brittle": "^3.3.2",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  },
  "peerDependencies": {
    "bare-buffer": "*"
  },
  "peerDependenciesMeta": {
    "bare-buffer": {
      "optional": true
    }
  }
}
const inspect = require('bare-inspect')

class AssertionError extends Error {
  constructor(opts = {}) {
    let { message = null, actual, expected, operator } = opts

    if (message === null) {
      message = `${inspect(actual)} ${operator} ${inspect(expected)}`
    }

    super(message)

    this.actual = actual
    this.expected = expected
    this.operator = operator
  }

  get name() {
    return 'AssertionError'
  }

  get code() {
    'ASSERTION'
  }
}

function assertFail(opts, fn) {
  if (opts.message instanceof Error) throw opts.message

  const err = new AssertionError(opts)

  if (Error.captureStackTrace) Error.captureStackTrace(err, fn)

  throw err
}

module.exports = exports = function assert(actual, message) {
  if (actual) return

  assertFail({ message, actual, expected: true, operator: '==' }, assert)
}

exports.AssertionError = AssertionError

exports.fail = function fail(message) {
  if (message === undefined) message = 'Failed'

  assertFail({ message, operator: 'fail' }, fail)
}

exports.ok = function ok(actual, message) {
  if (actual) return

  assertFail({ message, actual, expected: true, operator: '==' }, ok)
}

exports.notOk = function ok(actual, message) {
  if (!actual) return

  assertFail({ message, actual, expected: false, operator: '==' }, ok)
}

exports.equal = function equal(actual, expected, message) {
  if (actual == expected || (actual !== actual && expected !== expected)) {
    return
  }

  assertFail({ message, actual, expected, operator: '==' }, equal)
}

exports.notEqual = function notEqual(actual, expected, message) {
  if (actual != expected && (actual === actual || expected === expected)) {
    return
  }

  assertFail({ message, actual, expected, operator: '!=' }, notEqual)
}

exports.strictEqual = function strictEqual(actual, expected, message) {
  if (Object.is(actual, expected)) return

  assertFail(
    { message, actual, expected, operator: 'strictEqual' },
    strictEqual
  )
}

exports.notStrictEqual = function notStrictEqual(actual, expected, message) {
  if (!Object.is(actual, expected)) return

  assertFail(
    { message, actual, expected, operator: 'notStrictEqual' },
    notStrictEqual
  )
}
{
  "name": "bare-assert",
  "version": "1.2.0",
  "description": "Assertion library for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts"
  ],
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-assert.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-assert/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-assert#readme",
  "dependencies": {
    "bare-inspect": "^3.1.2"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  }
}
const errors = require('./lib/errors')

class EventListener {
  constructor() {
    this.list = []
    this.count = 0
  }

  append(ctx, name, fn, once) {
    this.count++
    ctx.emit('newListener', name, fn) // Emit BEFORE adding
    this.list.push([fn, once])
  }

  prepend(ctx, name, fn, once) {
    this.count++
    ctx.emit('newListener', name, fn) // Emit BEFORE adding
    this.list.unshift([fn, once])
  }

  remove(ctx, name, fn) {
    for (let i = 0, n = this.list.length; i < n; i++) {
      const l = this.list[i]

      if (l[0] === fn) {
        this.list.splice(i, 1)

        if (this.count === 1) delete ctx._events[name]

        ctx.emit('removeListener', name, fn) // Emit AFTER removing

        this.count--
        return
      }
    }
  }

  removeAll(ctx, name) {
    const list = [...this.list]
    this.list = []

    if (this.count === list.length) delete ctx._events[name]

    for (let i = list.length - 1; i >= 0; i--) {
      ctx.emit('removeListener', name, list[i][0]) // Emit AFTER removing
    }

    this.count -= list.length
  }

  emit(ctx, name, ...args) {
    const list = [...this.list]

    for (let i = 0, n = list.length; i < n; i++) {
      const l = list[i]

      if (l[1] === true) this.remove(ctx, name, l[0])

      Reflect.apply(l[0], ctx, args)
    }

    return list.length > 0
  }
}

function appendListener(ctx, name, fn, once) {
  if (ctx._events === undefined) ctx._events = Object.create(null)
  const e = ctx._events[name] || (ctx._events[name] = new EventListener())
  e.append(ctx, name, fn, once)
  return ctx
}

function prependListener(ctx, name, fn, once) {
  if (ctx._events === undefined) ctx._events = Object.create(null)
  const e = ctx._events[name] || (ctx._events[name] = new EventListener())
  e.prepend(ctx, name, fn, once)
  return ctx
}

function removeListener(ctx, name, fn) {
  if (ctx._events === undefined) return ctx
  const e = ctx._events[name]
  if (e !== undefined) e.remove(ctx, name, fn)
  return ctx
}

function throwUnhandledError(...args) {
  let err

  if (args.length > 0) err = args[0]

  if (err instanceof Error === false) err = errors.UNHANDLED_ERROR(err)

  if (Error.captureStackTrace) {
    Error.captureStackTrace(err, exports.prototype.emit)
  }

  queueMicrotask(() => {
    throw err
  })
}

module.exports = exports = class EventEmitter {
  constructor() {
    this._events = Object.create(null)
  }

  addListener(name, fn) {
    return appendListener(this, name, fn, false)
  }

  addOnceListener(name, fn) {
    return appendListener(this, name, fn, true)
  }

  prependListener(name, fn) {
    return prependListener(this, name, fn, false)
  }

  prependOnceListener(name, fn) {
    return prependListener(this, name, fn, true)
  }

  removeListener(name, fn) {
    return removeListener(this, name, fn)
  }

  on(name, fn) {
    return appendListener(this, name, fn, false)
  }

  once(name, fn) {
    return appendListener(this, name, fn, true)
  }

  off(name, fn) {
    return removeListener(this, name, fn)
  }

  emit(name, ...args) {
    if (name === 'error' && this._events !== undefined && this._events.error === undefined) {
      throwUnhandledError(...args)
    }

    if (this._events === undefined) return false
    const e = this._events[name]
    return e === undefined ? false : e.emit(this, name, ...args)
  }

  listeners(name) {
    if (this._events === undefined) return []
    const e = this._events[name]
    return e === undefined ? [] : [...e.list]
  }

  rawListeners(name) {
    if (this._events === undefined) return []
    const e = this._events[name]
    return e === undefined ? [] : e.list.map((l) => l[0])
  }

  eventNames() {
    if (this._events === undefined) return []
    return Reflect.ownKeys(this._events)
  }

  listenerCount(name) {
    if (this._events === undefined) return 0
    const e = this._events[name]
    return e === undefined ? 0 : e.list.length
  }

  getMaxListeners() {
    return EventEmitter.defaultMaxListeners
  }

  setMaxListeners(n) {}

  removeAllListeners(name) {
    if (arguments.length === 0) {
      for (const key of Reflect.ownKeys(this._events)) {
        if (key === 'removeListener') continue
        this.removeAllListeners(key)
      }
      this.removeAllListeners('removeListener')
    } else {
      const e = this._events[name]
      if (e !== undefined) e.removeAll(this, name)
    }
    return this
  }
}

exports.EventEmitter = exports

exports.errors = errors

exports.defaultMaxListeners = 10

exports.on = function on(emitter, name, opts = {}) {
  const { signal } = opts

  if (signal && signal.aborted) {
    throw errors.OPERATION_ABORTED(signal.reason)
  }

  let error = null
  let done = false

  const events = []
  const promises = []

  if (name !== 'error') emitter.on('error', onerror)

  if (signal) signal.addEventListener('abort', onabort)

  emitter.on(name, onevent)

  return {
    next() {
      if (events.length) {
        return Promise.resolve({ value: events.shift(), done: false })
      }

      if (error) {
        const err = error

        error = null

        return Promise.reject(err)
      }

      if (done) return onclose()

      return new Promise((resolve, reject) => promises.push({ resolve, reject }))
    },

    return() {
      return onclose()
    },

    throw(err) {
      return onerror(err)
    },

    [Symbol.asyncIterator]() {
      return this
    }
  }

  function onevent(...args) {
    if (promises.length) {
      promises.shift().resolve({ value: args, done: false })
    } else {
      events.push(args)
    }
  }

  function onerror(err) {
    emitter.off(name, onevent).off('error', onerror)

    if (promises.length) {
      promises.shift().reject(err)
    } else {
      error = err
    }

    return Promise.resolve({ done: true })
  }

  function onabort() {
    signal.removeEventListener('abort', onabort)

    onerror(errors.OPERATION_ABORTED(signal.reason))
  }

  function onclose() {
    emitter.off(name, onevent)

    if (name !== 'error') emitter.off('error', onerror)

    if (signal) signal.removeEventListener('abort', onabort)

    done = true

    if (promises.length) promises.shift().resolve({ done: true })

    return Promise.resolve({ done: true })
  }
}

exports.once = function once(emitter, name, opts = {}) {
  const { signal } = opts

  if (signal && signal.aborted) {
    return Promise.reject(errors.OPERATION_ABORTED(signal.reason))
  }

  return new Promise((resolve, reject) => {
    if (name !== 'error') emitter.on('error', onerror)

    if (signal) signal.addEventListener('abort', onabort)

    emitter.once(name, onevent)

    function onevent(...args) {
      if (name !== 'error') emitter.off('error', onerror)

      if (signal) signal.removeEventListener('abort', onabort)

      resolve(args)
    }

    function onerror(err) {
      emitter.off(name, onevent)

      if (name !== 'error') emitter.off('error', onerror)

      reject(err)
    }

    function onabort() {
      signal.removeEventListener('abort', onabort)

      onerror(errors.OPERATION_ABORTED(signal.reason))
    }
  })
}

exports.forward = function forward(from, to, names, opts = {}) {
  if (typeof names === 'string') names = [names]

  const { emit = to.emit.bind(to) } = opts

  const listeners = names.map(
    (name) =>
      function onevent(...args) {
        emit(name, ...args)
      }
  )

  to.on('newListener', (name) => {
    const i = names.indexOf(name)

    if (i !== -1 && to.listenerCount(name) === 0) {
      from.on(name, listeners[i])
    }
  }).on('removeListener', (name) => {
    const i = names.indexOf(name)

    if (i !== -1 && to.listenerCount(name) === 0) {
      from.off(name, listeners[i])
    }
  })
}

exports.listenerCount = function listenerCount(emitter, name) {
  return emitter.listenerCount(name)
}

exports.getMaxListeners = function getMaxListeners(emitter) {
  if (typeof emitter.getMaxListeners === 'function') {
    return emitter.getMaxListeners()
  }

  return exports.defaultMaxListeners
}

exports.setMaxListeners = function setMaxListeners(n, ...emitters) {
  if (emitters.length === 0) exports.defaultMaxListeners = n
  else {
    for (const emitter of emitters) {
      if (typeof emitter.setMaxListeners === 'function') {
        emitter.setMaxListeners(n)
      }
    }
  }
}
module.exports = class EventEmitterError extends Error {
  constructor(msg, code, fn = EventEmitterError, opts) {
    super(`${code}: ${msg}`, opts)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'EventEmitterError'
  }

  static OPERATION_ABORTED(cause, msg = 'Operation aborted') {
    return new EventEmitterError(msg, 'OPERATION_ABORTED', EventEmitterError.OPERATION_ABORTED, {
      cause
    })
  }

  static UNHANDLED_ERROR(cause, msg = 'Unhandled error') {
    return new EventEmitterError(msg, 'UNHANDLED_ERROR', EventEmitterError.UNHANDLED_ERROR, {
      cause
    })
  }
}
{
  "name": "bare-events",
  "version": "2.9.1",
  "description": "Event emitters for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    },
    "./web": {
      "types": "./web.d.ts",
      "default": "./web.js"
    },
    "./errors": "./lib/errors.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "global.js",
    "global.d.ts",
    "web.js",
    "web.d.ts",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:bare && npm run test:node",
    "test:bare": "brittle-bare --coverage test.js",
    "test:node": "brittle-node --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-events.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-events/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-events#readme",
  "devDependencies": {
    "bare-abort-controller": "^1.0.0",
    "brittle": "^3.3.2",
    "lunte": "^1.8.0",
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^2.0.0",
    "uncaughts": "^1.1.1"
  },
  "peerDependencies": {
    "bare-abort-controller": "*"
  },
  "peerDependenciesMeta": {
    "bare-abort-controller": {
      "optional": true
    }
  }
}
module.exports = require.addon()
const FIFO = require('fast-fifo')
const EventEmitter = require('bare-events')
const path = require('bare-path')
const { isURL, fileURLToPath } = require('bare-url')
const { Readable, Writable } = require('bare-stream')
const binding = require('./binding')
const constants = require('./lib/constants')
const FileError = require('./lib/errors')

const isWindows = Bare.platform === 'win32'

exports.constants = constants

class FileRequest {
  static borrow() {
    if (this._free.length > 0) return this._free.pop()
    return new FileRequest()
  }

  static return(req) {
    if (this._free.length < 32) this._free.push(req.reset())
    else req.destroy()
  }

  constructor() {
    this._reset()
    this._handle = binding.requestInit(this, this._onresult)
  }

  get handle() {
    return this._handle
  }

  retain(value) {
    this._retain = value // Tie the lifetime of `value` to the lifetime of `this`
  }

  reset() {
    if (this._handle === null) return this

    binding.requestReset(this._handle)

    this._reset()

    return this
  }

  destroy() {
    if (this._handle === null) return this

    binding.requestDestroy(this._handle)

    this._reset()
    this._handle = null

    return this
  }

  then(resolve, reject) {
    return this._promise.then(resolve, reject)
  }

  return() {
    if (this._handle === null) return this

    FileRequest.return(this)

    return this
  }

  _reset() {
    this._promise = new Promise((resolve, reject) => {
      this._resolve = resolve
      this._reject = reject
    })
    this._retain = null
  }

  _onresult(err, status) {
    if (err) this._reject(err)
    else this._resolve(status)
  }
}

FileRequest._free = []

function ok(result, cb) {
  if (typeof result === 'function') {
    cb = result
    result = undefined
  }

  if (cb) cb(null, result)
  else return result
}

function fail(err, cb) {
  if (cb) cb(err)
  else throw err
}

function done(err, result, cb) {
  if (typeof result === 'function') {
    cb = result
    result = undefined
  }

  if (err) fail(err, cb)
  else return ok(result, cb)
}

async function open(filepath, flags = 'r', mode = 0o666, cb) {
  if (typeof flags === 'function') {
    cb = flags
    flags = 'r'
    mode = 0o666
  } else if (typeof mode === 'function') {
    cb = mode
    mode = 0o666
  }

  if (typeof flags === 'string') flags = toFlags(flags)
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let fd
  let err = null
  try {
    binding.open(req.handle, filepath, flags, mode)

    fd = await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'open',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, fd, cb)
}

function openSync(filepath, flags = 'r', mode = 0o666) {
  if (typeof flags === 'string') flags = toFlags(flags)
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    return binding.openSync(req.handle, filepath, flags, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'open',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function close(fd, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.close(req.handle, fd)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'close', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function closeSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.closeSync(req.handle, fd)
  } catch (e) {
    throw new FileError(e.message, { operation: 'close', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function access(filepath, mode = constants.F_OK, cb) {
  if (typeof mode === 'function') {
    cb = mode
    mode = constants.F_OK
  }

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.access(req.handle, filepath, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'access',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function accessSync(filepath, mode = constants.F_OK) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.accessSync(req.handle, filepath, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'access',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function exists(filepath, cb) {
  let ok = true
  try {
    await access(filepath)
  } catch {
    ok = false
  }

  return done(null, ok, cb)
}

function existsSync(filepath) {
  try {
    accessSync(filepath)
  } catch {
    return false
  }

  return true
}

async function read(fd, buffer, offset = 0, len = buffer.byteLength - offset, pos = -1, cb) {
  if (typeof offset === 'function') {
    cb = offset
    offset = 0
    len = buffer.byteLength
    pos = -1
  } else if (typeof len === 'function') {
    cb = len
    len = buffer.byteLength - offset
    pos = -1
  } else if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.read(req.handle, fd, buffer, offset, len, pos)

    req.retain(buffer)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'read', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function readSync(fd, buffer, offset = 0, len = buffer.byteLength - offset, pos = -1) {
  const req = FileRequest.borrow()

  try {
    return binding.readSync(req.handle, fd, buffer, offset, len, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'read', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function readv(fd, buffers, pos = -1, cb) {
  if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.readv(req.handle, fd, buffers, pos)

    req.retain(buffers)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'readv', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function readvSync(fd, buffers, pos = -1) {
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  try {
    return binding.readvSync(req.handle, fd, buffers, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'readv', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function write(fd, data, offset, len, pos = -1, cb) {
  if (typeof data === 'string') {
    let encoding = len
    cb = pos
    pos = offset

    if (typeof pos === 'function') {
      cb = pos
      pos = -1
      encoding = 'utf8'
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = 'utf8'
    }

    if (typeof pos === 'string') {
      encoding = pos
      pos = -1
    }

    data = Buffer.from(data, encoding)
    offset = 0
    len = data.byteLength
  } else if (typeof offset === 'function') {
    cb = offset
    offset = 0
    len = data.byteLength
    pos = -1
  } else if (typeof len === 'function') {
    cb = len
    len = data.byteLength - offset
    pos = -1
  } else if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof offset !== 'number') offset = 0
  if (typeof len !== 'number') len = data.byteLength - offset
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.write(req.handle, fd, data, offset, len, pos)

    req.retain(data)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'write', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function writeSync(fd, data, offset, len, pos = -1) {
  if (typeof data === 'string') {
    let encoding = len
    pos = offset

    if (typeof pos === 'string') {
      encoding = pos
      pos = -1
    }

    data = Buffer.from(data, encoding)
    offset = 0
    len = data.byteLength
  }

  if (typeof offset !== 'number') offset = 0
  if (typeof len !== 'number') len = data.byteLength - offset
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  try {
    return binding.writeSync(req.handle, fd, data, offset, len, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'write', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function writev(fd, buffers, pos = -1, cb) {
  if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.writev(req.handle, fd, buffers, pos)

    req.retain(buffers)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'writev', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function writevSync(fd, buffers, pos = -1) {
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  try {
    return binding.writevSync(req.handle, fd, buffers, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'writev', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function stat(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.stat(req.handle, filepath)

    await req

    st = new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'stat', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function statSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.statSync(req.handle, filepath)

    return new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'stat', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function lstat(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.lstat(req.handle, filepath)

    await req

    st = new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'lstat', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function lstatSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.lstatSync(req.handle, filepath)

    return new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'lstat', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function fstat(fd, cb) {
  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.fstat(req.handle, fd)

    await req

    st = new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'fstat', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function fstatSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.fstatSync(req.handle, fd)

    return new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'fstat', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function statfs(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.statfs(req.handle, filepath)

    await req

    st = new StatFs(...binding.requestResultStatfs(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'statfs', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function statfsSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.statfsSync(req.handle, filepath)

    return new StatFs(...binding.requestResultStatfs(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'statfs', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function ftruncate(fd, len = 0, cb) {
  if (typeof len === 'function') {
    cb = len
    len = 0
  }

  if (typeof len !== 'number') len = 0

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.ftruncate(req.handle, fd, len)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'ftruncate', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function ftruncateSync(fd, len = 0) {
  if (typeof len !== 'number') len = 0

  const req = FileRequest.borrow()

  try {
    binding.ftruncateSync(req.handle, fd, len)
  } catch (e) {
    throw new FileError(e.message, { operation: 'ftruncate', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function truncate(filepath, len, cb) {
  let fd = -1
  let err

  try {
    fd = await open(filepath, 'r+')

    await ftruncate(fd, len)
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) await close(fd)
  }

  return done(err, cb)
}

function truncateSync(filepath, len) {
  let fd = -1
  let err

  try {
    fd = openSync(filepath, 'r+')

    ftruncateSync(fd, len)
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) closeSync(fd)
  }
}

async function chmod(filepath, mode, cb) {
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.chmod(req.handle, filepath, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'chmod',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function chmodSync(filepath, mode) {
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.chmodSync(req.handle, filepath, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'chmod',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function fchmod(fd, mode, cb) {
  if (typeof mode === 'string') mode = toMode(mode)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fchmod(req.handle, fd, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fchmod', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fchmodSync(fd, mode) {
  if (typeof mode === 'string') mode = toMode(mode)

  const req = FileRequest.borrow()

  try {
    binding.fchmodSync(req.handle, fd, mode)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fchmod', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function chown(filepath, uid, gid, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.chown(req.handle, filepath, uid, gid)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'chown', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function chownSync(filepath, uid, gid) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.chownSync(req.handle, filepath, uid, gid)
  } catch (e) {
    throw new FileError(e.message, { operation: 'chownSync', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function lchown(filepath, uid, gid, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.lchown(req.handle, filepath, uid, gid)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'lchown', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function lchownSync(filepath, uid, gid) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.lchownSync(req.handle, filepath, uid, gid)
  } catch (e) {
    throw new FileError(e.message, { operation: 'lchownSync', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function fchown(fd, uid, gid, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fchown(req.handle, fd, uid, gid)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fchown', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fchownSync(fd, uid, gid) {
  const req = FileRequest.borrow()

  try {
    binding.fchownSync(req.handle, fd, uid, gid)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fchownSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function utimes(filepath, atime, mtime, cb) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.utimes(req.handle, filepath, atime, mtime)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'utimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function utimesSync(filepath, atime, mtime) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.utimesSync(req.handle, filepath, atime, mtime)
  } catch (e) {
    throw new FileError(e.message, { operation: 'utimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function lutimes(filepath, atime, mtime, cb) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.lutimes(req.handle, filepath, atime, mtime)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'lutimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function lutimesSync(filepath, atime, mtime) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.lutimesSync(req.handle, filepath, atime, mtime)
  } catch (e) {
    throw new FileError(e.message, { operation: 'lutimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function futimes(fd, atime, mtime, cb) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.futimes(req.handle, fd, atime, mtime)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'futimes', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function futimesSync(fd, atime, mtime) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  const req = FileRequest.borrow()

  try {
    binding.futimesSync(req.handle, fd, atime, mtime)
  } catch (e) {
    throw new FileError(e.message, { operation: 'futimesSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function link(src, dst, cb) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.link(req.handle, src, dst)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'link', code: e.code, path: src, destination: dst })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function linkSync(src, dst) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  try {
    binding.linkSync(req.handle, src, dst)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'linkSync',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }
}

async function mkdir(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = { mode: 0o777 }
  }

  if (typeof opts === 'number') opts = { mode: opts }
  else if (!opts) opts = {}

  const mode = typeof opts.mode === 'number' ? opts.mode : 0o777

  filepath = toNamespacedPath(filepath)

  if (opts.recursive) {
    let err = null
    try {
      try {
        await mkdir(filepath, { mode })
      } catch (err) {
        if (err.code !== 'ENOENT') {
          if (!(await stat(filepath)).isDirectory()) throw err
        } else {
          while (filepath.endsWith(path.sep)) filepath = filepath.slice(0, -1)
          const i = filepath.lastIndexOf(path.sep)
          if (i <= 0) throw err

          await mkdir(filepath.slice(0, i), { mode, recursive: true })

          try {
            await mkdir(filepath, { mode })
          } catch (err) {
            if (!(await stat(filepath)).isDirectory()) throw err
          }
        }
      }
    } catch (e) {
      err = e
    }

    return done(err, cb)
  }

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.mkdir(req.handle, filepath, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'mkdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function mkdirSync(filepath, opts) {
  if (typeof opts === 'number') opts = { mode: opts }
  else if (!opts) opts = {}

  const mode = typeof opts.mode === 'number' ? opts.mode : 0o777

  filepath = toNamespacedPath(filepath)

  if (opts.recursive) {
    try {
      mkdirSync(filepath, { mode })
    } catch (err) {
      if (err.code !== 'ENOENT') {
        if (!statSync(filepath).isDirectory()) throw err
      } else {
        while (filepath.endsWith(path.sep)) filepath = filepath.slice(0, -1)
        const i = filepath.lastIndexOf(path.sep)
        if (i <= 0) throw err

        mkdirSync(filepath.slice(0, i), { mode, recursive: true })

        try {
          mkdirSync(filepath, { mode })
        } catch (err) {
          if (!statSync(filepath).isDirectory()) throw err
        }
      }
    }

    return
  }

  const req = FileRequest.borrow()

  try {
    binding.mkdirSync(req.handle, filepath, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'mkdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function mkdtemp(prefix, cb) {
  prefix = toNamespacedPath(prefix)

  const req = FileRequest.borrow()

  let res
  let err = null
  try {
    binding.mkdtemp(req.handle, prefix + 'XXXXXX')

    await req

    res = binding.requestResultPath(req.handle)
  } catch (e) {
    err = new FileError(e.message, { operation: 'mkdtemp', code: e.code, path: prefix })
  } finally {
    req.return()
  }

  return done(err, res, cb)
}

function mkdtempSync(prefix) {
  prefix = toNamespacedPath(prefix)

  const req = FileRequest.borrow()

  try {
    binding.mkdtempSync(req.handle, prefix + 'XXXXXX')

    return binding.requestResultPath(req.handle)
  } catch (e) {
    throw new FileError(e.message, { operation: 'mkdtempSync', code: e.code, path: prefix })
  } finally {
    req.return()
  }
}

async function rmdir(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.rmdir(req.handle, filepath)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'rmdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function rmdirSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.rmdirSync(req.handle, filepath)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'rmdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function rm(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  let err = null
  try {
    const st = await lstat(filepath)

    if (st.isDirectory()) {
      if (opts.recursive) {
        try {
          await rmdir(filepath)
        } catch (err) {
          if (err.code !== 'ENOTEMPTY') throw err

          const files = await readdir(filepath)

          for (const file of files) {
            await rm(filepath + path.sep + file, opts)
          }

          await rmdir(filepath)
        }
      } else {
        throw new FileError('is a directory', {
          operation: 'rm',
          code: 'EISDIR',
          path: filepath
        })
      }
    } else {
      await unlink(filepath)
    }
  } catch (e) {
    if (e.code !== 'ENOENT' || !opts.force) err = e
  }

  return done(err, cb)
}

function rmSync(filepath, opts) {
  if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  try {
    const st = lstatSync(filepath)

    if (st.isDirectory()) {
      if (opts.recursive) {
        try {
          rmdirSync(filepath)
        } catch (err) {
          if (err.code !== 'ENOTEMPTY') throw err

          const files = readdirSync(filepath)

          for (const file of files) {
            rmSync(filepath + path.sep + file, opts)
          }

          rmdirSync(filepath)
        }
      } else {
        throw new FileError('is a directory', {
          operation: 'rm',
          code: 'EISDIR',
          path: filepath
        })
      }
    } else {
      unlinkSync(filepath)
    }
  } catch (err) {
    if (err.code !== 'ENOENT' || !opts.force) throw err
  }
}

async function unlink(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.unlink(req.handle, filepath)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'unlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function unlinkSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.unlinkSync(req.handle, filepath)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'unlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function rename(src, dst, cb) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.rename(req.handle, src, dst)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'rename',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function renameSync(src, dst) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  try {
    binding.renameSync(req.handle, src, dst)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'rename',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }
}

async function copyFile(src, dst, mode = 0, cb) {
  if (typeof mode === 'function') {
    cb = mode
    mode = 0
  }

  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.copyfile(req.handle, src, dst, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'copyfile',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function copyFileSync(src, dst, mode = 0) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  try {
    binding.copyfileSync(req.handle, src, dst, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'copyfile',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }
}

async function cp(src, dst, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (!opts) opts = {}

  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  let err = null
  try {
    const st = await lstat(src)

    if (st.isDirectory()) {
      if (opts.recursive !== true) {
        throw new FileError('is a directory', { operation: 'cp', code: 'EISDIR', path: src })
      }

      try {
        await lstat(dst)
      } catch (e) {
        if (e.code !== 'ENOENT') throw e

        await mkdir(dst, { mode: st.mode, recursive: true })
      }

      const dir = await opendir(src)
      for await (const { name } of dir) {
        await cp(path.join(src, name), path.join(dst, name), opts)
      }
    } else if (st.isFile()) {
      await copyFile(src, dst)
      await chmod(dst, st.mode)
    }
  } catch (e) {
    err = e
  }

  return done(err, cb)
}

function cpSync(src, dst, opts = {}) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const st = lstatSync(src)

  if (st.isDirectory()) {
    if (opts.recursive !== true) {
      throw new FileError('is a directory', { operation: 'cp', code: 'EISDIR', path: src })
    }

    try {
      lstatSync(dst)
    } catch (e) {
      if (e.code !== 'ENOENT') throw e

      mkdirSync(dst, { mode: st.mode, recursive: true })
    }

    const dir = opendirSync(src)
    for (const { name } of dir) {
      cpSync(path.join(src, name), path.join(dst, name), opts)
    }
  } else if (st.isFile()) {
    copyFileSync(src, dst)
    chmodSync(dst, st.mode)
  }
}

async function realpath(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let res
  let err = null
  try {
    binding.realpath(req.handle, filepath)

    await req

    res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'realpath',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, res, cb)
}

function realpathSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.realpathSync(req.handle, filepath)

    let res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)

    return res
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'realpath',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function readlink(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let res
  let err = null
  try {
    binding.readlink(req.handle, filepath)

    await req

    res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'readlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, res, cb)
}

function readlinkSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.readlinkSync(req.handle, filepath)

    let res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)

    return res
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'readlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function fsync(fd, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fsync(req.handle, fd)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fsync', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fsyncSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.fsyncSync(req.handle, fd)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fsyncSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function fdatasync(fd, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fdatasync(req.handle, fd)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fdatasync', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fdatasyncSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.fdatasyncSync(req.handle, fd)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fdatasyncSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

function normalizeSymlinkTarget(target, type, filepath) {
  if (isWindows) {
    if (type === constants.UV_FS_SYMLINK_JUNCTION) target = path.resolve(filepath, '..', target)

    if (path.isAbsolute(target)) return path.toNamespacedPath(target)

    return target.replace(/\//g, path.sep)
  }

  return target
}

async function symlink(target, filepath, type, cb) {
  if (typeof type === 'function') {
    cb = type
    type = null
  }

  filepath = toNamespacedPath(filepath)

  if (typeof type === 'string') {
    switch (type) {
      case 'dir':
        type = constants.UV_FS_SYMLINK_DIR
        break
      case 'junction':
        type = constants.UV_FS_SYMLINK_JUNCTION
        break
      case 'file':
      default:
        type = 0
        break
    }
  } else if (typeof type !== 'number') {
    if (isWindows) {
      target = path.resolve(filepath, '..', target)

      try {
        type = (await stat(target)).isDirectory()
          ? constants.UV_FS_SYMLINK_DIR
          : constants.UV_FS_SYMLINK_JUNCTION
      } catch {
        type = 0
      }
    } else {
      type = 0
    }
  }

  target = normalizeSymlinkTarget(target, type, filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.symlink(req.handle, target, filepath, type)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'symlink',
      code: e.code,
      path: target,
      destination: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function symlinkSync(target, filepath, type) {
  filepath = toNamespacedPath(filepath)

  if (typeof type === 'string') {
    switch (type) {
      case 'dir':
        type = constants.UV_FS_SYMLINK_DIR
        break
      case 'junction':
        type = constants.UV_FS_SYMLINK_JUNCTION
        break
      case 'file':
      default:
        type = 0
        break
    }
  } else if (typeof type !== 'number') {
    if (isWindows) {
      target = path.resolve(filepath, '..', target)

      try {
        type = statSync(target).isDirectory()
          ? constants.UV_FS_SYMLINK_DIR
          : constants.UV_FS_SYMLINK_JUNCTION
      } catch {
        type = 0
      }
    } else {
      type = 0
    }
  }

  target = normalizeSymlinkTarget(target, type, filepath)

  const req = FileRequest.borrow()

  try {
    binding.symlinkSync(req.handle, target, filepath, type)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'symlink',
      code: e.code,
      path: target,
      destination: filepath
    })
  } finally {
    req.return()
  }
}

async function opendir(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let dir
  let err = null
  try {
    binding.opendir(req.handle, filepath)

    await req

    dir = new Dir(filepath, binding.requestResultDir(req.handle), opts)
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'opendir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, dir, cb)
}

function opendirSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.opendirSync(req.handle, filepath)

    return new Dir(filepath, binding.requestResultDir(req.handle), opts)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'opendir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function readdir(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { withFileTypes = false, recursive = false } = opts

  filepath = toNamespacedPath(filepath)

  const queue = [filepath]
  let result = []
  let err = null
  try {
    while (queue.length !== 0) {
      const dir = await opendir(queue.pop())

      for await (const entry of dir) {
        const entryPath = path.join(entry.parentPath, entry.name)

        if (withFileTypes) {
          result.push(entry)
        } else {
          result.push(path.relative(filepath, entryPath))
        }

        if (recursive && entry.isDirectory()) queue.push(entryPath)
      }
    }
  } catch (e) {
    result = []
    err = e
  }

  return done(err, result, cb)
}

function readdirSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { withFileTypes = false, recursive = false } = opts

  filepath = toNamespacedPath(filepath)

  const queue = [filepath]
  const result = []

  while (queue.length !== 0) {
    const dir = opendirSync(queue.pop(), opts)

    for (const entry of dir) {
      const entryPath = path.join(entry.parentPath, entry.name)

      if (withFileTypes) {
        result.push(entry)
      } else {
        result.push(path.relative(filepath, entryPath))
      }

      if (recursive && entry.isDirectory()) queue.push(entryPath)
    }
  }

  return result
}

async function readFile(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'buffer' } = opts

  let fd = -1
  let buffer = null
  let err = null
  try {
    fd = await open(filepath, opts.flag || 'r')

    const st = await fstat(fd)

    let len = 0

    if (st.size === 0) {
      const buffers = []

      while (true) {
        buffer = Buffer.allocUnsafe(8192)
        const r = await read(fd, buffer)
        len += r
        if (r === 0) break
        buffers.push(buffer.subarray(0, r))
      }

      buffer = Buffer.concat(buffers)
    } else {
      buffer = Buffer.allocUnsafe(st.size)

      while (true) {
        const r = await read(fd, len ? buffer.subarray(len) : buffer)
        len += r
        if (r === 0 || len === buffer.byteLength) break
      }

      if (len !== buffer.byteLength) buffer = buffer.subarray(0, len)
    }

    if (encoding !== 'buffer') buffer = buffer.toString(encoding)
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) await close(fd)
  }

  return done(err, buffer, cb)
}

function readFileSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'buffer' } = opts

  let fd = -1
  try {
    fd = openSync(filepath, opts.flag || 'r')

    const st = fstatSync(fd)

    let buffer
    let len = 0

    if (st.size === 0) {
      const buffers = []

      while (true) {
        buffer = Buffer.allocUnsafe(8192)
        const r = readSync(fd, buffer)
        len += r
        if (r === 0) break
        buffers.push(buffer.subarray(0, r))
      }

      buffer = Buffer.concat(buffers)
    } else {
      buffer = Buffer.allocUnsafe(st.size)

      while (true) {
        const r = readSync(fd, len ? buffer.subarray(len) : buffer)
        len += r
        if (r === 0 || len === buffer.byteLength) break
      }

      if (len !== buffer.byteLength) buffer = buffer.subarray(0, len)
    }

    if (encoding !== 'buffer') buffer = buffer.toString(encoding)

    return buffer
  } finally {
    if (fd !== -1) closeSync(fd)
  }
}

async function writeFile(filepath, data, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (typeof data === 'string') data = Buffer.from(data, opts.encoding)

  let fd = -1
  let len = 0
  let err = null
  try {
    fd = await open(filepath, opts.flag || 'w', opts.mode || 0o666)

    while (true) {
      len += await write(fd, len ? data.subarray(len) : data)
      if (len === data.byteLength) break
    }
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) await close(fd)
  }

  return done(err, len, cb)
}

function writeFileSync(filepath, data, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (typeof data === 'string') data = Buffer.from(data, opts.encoding)

  let fd = -1
  try {
    fd = openSync(filepath, opts.flag || 'w', opts.mode || 0o666)

    let len = 0

    while (true) {
      len += writeSync(fd, len ? data.subarray(len) : data)
      if (len === data.byteLength) break
    }
  } finally {
    if (fd !== -1) closeSync(fd)
  }
}

function appendFile(filepath, data, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (!opts.flag) opts = { ...opts, flag: 'a' }

  return writeFile(filepath, data, opts, cb)
}

function appendFileSync(filepath, data, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (!opts.flag) opts = { ...opts, flag: 'a' }

  return writeFileSync(filepath, data, opts)
}

function watch(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  return new Watcher(filepath, opts, cb)
}

class Stats {
  constructor(
    dev,
    mode,
    nlink,
    uid,
    gid,
    rdev,
    blksize,
    ino,
    size,
    blocks,
    atimeMs,
    mtimeMs,
    ctimeMs,
    birthtimeMs
  ) {
    this.dev = dev
    this.mode = mode
    this.nlink = nlink
    this.uid = uid
    this.gid = gid
    this.rdev = rdev
    this.blksize = blksize
    this.ino = ino
    this.size = size
    this.blocks = blocks
    this.atimeMs = atimeMs
    this.mtimeMs = mtimeMs
    this.ctimeMs = ctimeMs
    this.birthtimeMs = birthtimeMs
    this.atime = new Date(atimeMs)
    this.mtime = new Date(mtimeMs)
    this.ctime = new Date(ctimeMs)
    this.birthtime = new Date(birthtimeMs)
  }

  isDirectory() {
    return (this.mode & constants.S_IFMT) === constants.S_IFDIR
  }

  isFile() {
    return (this.mode & constants.S_IFMT) === constants.S_IFREG
  }

  isBlockDevice() {
    return (this.mode & constants.S_IFMT) === constants.S_IFBLK
  }

  isCharacterDevice() {
    return (this.mode & constants.S_IFMT) === constants.S_IFCHR
  }

  isFIFO() {
    return (this.mode & constants.S_IFMT) === constants.S_IFIFO
  }

  isSymbolicLink() {
    return (this.mode & constants.S_IFMT) === constants.S_IFLNK
  }

  isSocket() {
    return (this.mode & constants.S_IFMT) === constants.S_IFSOCK
  }
}

class StatFs {
  constructor(type, bsize, blocks, bfree, bavail, files, ffree) {
    this.type = type
    this.bsize = bsize
    this.blocks = blocks
    this.bfree = bfree
    this.bavail = bavail
    this.files = files
    this.ffree = ffree
  }
}

class Dir {
  constructor(path, handle, opts = {}) {
    const { encoding = 'utf8', bufferSize = 32 } = opts

    this.path = path

    this._encoding = encoding
    this._capacity = bufferSize
    this._buffer = new FIFO()
    this._ended = false
    this._handle = handle
  }

  async read(cb) {
    if (this._buffer.length) return ok(this._buffer.shift(), cb)
    if (this._ended) return ok(null, cb)

    const req = FileRequest.borrow()

    let entries
    let err = null
    try {
      req.retain(binding.readdir(req.handle, this._handle, this._capacity))

      await req

      entries = binding.requestResultDirents(req.handle)
    } catch (e) {
      err = new FileError(e.message, {
        operation: 'readdir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    if (err) return fail(err, cb)

    if (entries.length === 0) {
      this._ended = true

      return ok(null, cb)
    }

    for (const entry of entries) {
      let name = Buffer.from(entry.name)

      if (this._encoding !== 'buffer') name = name.toString(this._encoding)

      this._buffer.push(new Dirent(this.path, name, entry.type))
    }

    return ok(this._buffer.shift(), cb)
  }

  readSync() {
    if (this._buffer.length) return this._buffer.shift()
    if (this._ended) return null

    const req = FileRequest.borrow()

    let entries
    try {
      req.retain(binding.readdirSync(req.handle, this._handle, this._capacity))

      entries = binding.requestResultDirents(req.handle)
    } catch (e) {
      throw new FileError(e.message, {
        operation: 'readdir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    if (entries.length === 0) {
      this._ended = true

      return null
    }

    for (const entry of entries) {
      let name = Buffer.from(entry.name)

      if (this._encoding !== 'buffer') name = name.toString(this._encoding)

      this._buffer.push(new Dirent(this.path, name, entry.type))
    }

    return this._buffer.shift()
  }

  async close(cb) {
    const req = FileRequest.borrow()

    let err = null
    try {
      binding.closedir(req.handle, this._handle)

      await req
    } catch (e) {
      err = new FileError(e.message, {
        operation: 'closedir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    this._handle = null

    return done(err, cb)
  }

  closeSync() {
    const req = FileRequest.borrow()

    try {
      binding.closedirSync(req.handle, this._handle)
    } catch (e) {
      throw new FileError(e.message, {
        operation: 'closedir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    this._handle = null
  }

  [Symbol.dispose]() {
    this.closeSync()
  }

  async [Symbol.asyncDispose]() {
    await this.close()
  }

  *[Symbol.iterator]() {
    while (true) {
      const entry = this.readSync()
      if (entry === null) break
      yield entry
    }

    this.closeSync()
  }

  async *[Symbol.asyncIterator]() {
    while (true) {
      const entry = await this.read()
      if (entry === null) break
      yield entry
    }

    await this.close()
  }
}

class Dirent {
  constructor(parentPath, name, type) {
    this.parentPath = parentPath
    this.name = name
    this.type = type
  }

  isFile() {
    return this.type === constants.UV_DIRENT_FILE
  }

  isDirectory() {
    return this.type === constants.UV_DIRENT_DIR
  }

  isSymbolicLink() {
    return this.type === constants.UV_DIRENT_LINK
  }

  isFIFO() {
    return this.type === constants.UV_DIRENT_FIFO
  }

  isSocket() {
    return this.type === constants.UV_DIRENT_SOCKET
  }

  isCharacterDevice() {
    return this.type === constants.UV_DIRENT_CHAR
  }

  isBlockDevice() {
    return this.type === constants.UV_DIRENT_BLOCK
  }
}

class FileReadStream extends Readable {
  constructor(path, opts = {}) {
    const { eagerOpen = true } = opts

    super({ eagerOpen, ...opts })

    this.path = path
    this.fd = typeof opts.fd === 'number' ? opts.fd : -1
    this.flags = opts.flags || 'r'
    this.mode = opts.mode || 0o666

    this._offset = opts.start || 0
    this._missing = 0

    if (opts.length) {
      this._missing = opts.length
    } else if (typeof opts.end === 'number') {
      this._missing = opts.end - this._offset + 1
    } else {
      this._missing = -1
    }
  }

  async _open(cb) {
    let err

    if (this.fd === -1) {
      err = null
      try {
        this.fd = await open(this.path, this.flags, this.mode)
      } catch (e) {
        err = e
      }

      if (err) return cb(err)
    }

    let st
    err = null
    try {
      st = await fstat(this.fd)
    } catch (e) {
      err = e
    }

    if (err) return cb(err)

    if (this._missing === -1) this._missing = st.size

    if (st.size < this._offset) {
      this._offset = st.size
      this._missing = 0
    } else if (st.size < this._offset + this._missing) {
      this._missing = st.size - this._offset
    }

    cb(null)
  }

  async _read(size) {
    if (this._missing <= 0) return this.push(null)

    const data = Buffer.allocUnsafe(Math.min(this._missing, size))

    let len
    let err = null
    try {
      len = await read(this.fd, data, 0, data.byteLength, this._offset)
    } catch (e) {
      err = e
    }

    if (err) return this.destroy(err)

    if (len === 0) return this.push(null)

    if (this._missing < len) len = this._missing

    this._missing -= len
    this._offset += len

    this.push(data.subarray(0, len))
  }

  async _destroy(err, cb) {
    if (this.fd === -1) return cb(err)

    try {
      await close(this.fd)
    } catch (e) {
      err = err || e
    }

    cb(err)
  }
}

class FileWriteStream extends Writable {
  constructor(path, opts = {}) {
    const { eagerOpen = true } = opts

    super({ eagerOpen, ...opts })

    this.path = path
    this.fd = typeof opts.fd === 'number' ? opts.fd : -1
    this.flags = opts.flags || 'w'
    this.mode = opts.mode || 0o666
  }

  async _open(cb) {
    if (this.fd !== -1) return cb(null)

    let err = null
    try {
      this.fd = await open(this.path, this.flags, this.mode)
    } catch (e) {
      err = e
    }

    cb(err)
  }

  async _writev(batch, cb) {
    let err = null
    try {
      await writev(
        this.fd,
        batch.map(({ chunk }) => chunk)
      )
    } catch (e) {
      err = e
    }

    cb(err)
  }

  async _destroy(err, cb) {
    if (this.fd === -1) return cb(err)

    try {
      await close(this.fd)
    } catch (e) {
      err = err || e
    }

    cb(err)
  }
}

class Watcher extends EventEmitter {
  constructor(path, opts, onchange) {
    if (typeof opts === 'function') {
      onchange = opts
      opts = {}
    }

    if (!opts) opts = {}

    const { persistent = true, recursive = false, encoding = 'utf8' } = opts

    super()

    this._closed = false
    this._encoding = encoding
    this._handle = binding.watcherInit(path, recursive, this, this._onevent, this._onclose)

    if (!persistent) this.unref()

    if (onchange) this.on('change', onchange)
  }

  close() {
    if (this._closed) return
    this._closed = true

    binding.watcherClose(this._handle)
  }

  ref() {
    if (this._handle) binding.watcherRef(this._handle)
    return this
  }

  unref() {
    if (this._handle) binding.watcherUnref(this._handle)
    return this
  }

  [Symbol.asyncIterator]() {
    const buffer = []
    let done = false
    let error = null
    let next = null

    this.on('change', (eventType, filename) => {
      if (next) {
        next.resolve({ done: false, value: { eventType, filename } })
        next = null
      } else {
        buffer.push({ eventType, filename })
      }
    })
      .on('error', (err) => {
        done = true
        error = err

        if (next) {
          next.reject(error)
          next = null
        }
      })
      .on('close', () => {
        done = true

        if (next) {
          next.resolve({ done })
          next = null
        }
      })

    return {
      next: () =>
        new Promise((resolve, reject) => {
          if (error) return reject(error)

          if (buffer.length) return resolve({ done: false, value: buffer.shift() })

          if (done) return resolve({ done })

          next = { resolve, reject }
        })
    }
  }

  _onevent(err, events, filename) {
    if (err) {
      this.close()
      this.emit('error', err)
    } else {
      const path =
        this._encoding === 'buffer'
          ? Buffer.from(filename)
          : Buffer.from(filename).toString(this._encoding)

      if (events & binding.UV_RENAME) {
        this.emit('change', 'rename', path)
      }

      if (events & binding.UV_CHANGE) {
        this.emit('change', 'change', path)
      }
    }
  }

  _onclose() {
    this._handle = null

    this.emit('close')
  }
}

exports.access = access
exports.appendFile = appendFile
exports.chmod = chmod
exports.chown = chown
exports.close = close
exports.copyFile = copyFile
exports.cp = cp
exports.exists = exists
exports.fchmod = fchmod
exports.fchown = fchown
exports.fdatasync = fdatasync
exports.fstat = fstat
exports.fsync = fsync
exports.ftruncate = ftruncate
exports.futimes = futimes
exports.lchown = lchown
exports.lutimes = lutimes
exports.link = link
exports.lstat = lstat
exports.mkdir = mkdir
exports.mkdtemp = mkdtemp
exports.open = open
exports.opendir = opendir
exports.read = read
exports.readFile = readFile
exports.readdir = readdir
exports.readlink = readlink
exports.readv = readv
exports.realpath = realpath
exports.rename = rename
exports.rm = rm
exports.rmdir = rmdir
exports.stat = stat
exports.statfs = statfs
exports.symlink = symlink
exports.truncate = truncate
exports.unlink = unlink
exports.utimes = utimes
exports.watch = watch
exports.write = write
exports.writeFile = writeFile
exports.writev = writev

exports.accessSync = accessSync
exports.appendFileSync = appendFileSync
exports.chmodSync = chmodSync
exports.chownSync = chownSync
exports.closeSync = closeSync
exports.copyFileSync = copyFileSync
exports.cpSync = cpSync
exports.existsSync = existsSync
exports.fchmodSync = fchmodSync
exports.fchownSync = fchownSync
exports.fdatasyncSync = fdatasyncSync
exports.fstatSync = fstatSync
exports.fsyncSync = fsyncSync
exports.ftruncateSync = ftruncateSync
exports.futimesSync = futimesSync
exports.lchownSync = lchownSync
exports.lutimesSync = lutimesSync
exports.linkSync = linkSync
exports.lstatSync = lstatSync
exports.mkdirSync = mkdirSync
exports.mkdtempSync = mkdtempSync
exports.openSync = openSync
exports.opendirSync = opendirSync
exports.readFileSync = readFileSync
exports.readSync = readSync
exports.readdirSync = readdirSync
exports.readlinkSync = readlinkSync
exports.readvSync = readvSync
exports.realpathSync = realpathSync
exports.renameSync = renameSync
exports.rmSync = rmSync
exports.rmdirSync = rmdirSync
exports.statSync = statSync
exports.statfsSync = statfsSync
exports.symlinkSync = symlinkSync
exports.truncateSync = truncateSync
exports.unlinkSync = unlinkSync
exports.utimesSync = utimesSync
exports.writeFileSync = writeFileSync
exports.writeSync = writeSync
exports.writevSync = writevSync

exports.promises = require('./promises')

exports.Stats = Stats
exports.StatFs = StatFs
exports.Dir = Dir
exports.Dirent = Dirent
exports.Watcher = Watcher

exports.ReadStream = FileReadStream

exports.createReadStream = function createReadStream(path, opts) {
  return new FileReadStream(path, opts)
}

exports.WriteStream = FileWriteStream

exports.createWriteStream = function createWriteStream(path, opts) {
  return new FileWriteStream(path, opts)
}

function toNamespacedPath(filepath) {
  if (typeof filepath !== 'string') {
    if (isURL(filepath)) filepath = fileURLToPath(filepath)
    else filepath = filepath.toString()
  }

  return path.toNamespacedPath(filepath)
}

function toFlags(flags) {
  switch (flags) {
    case 'r':
      return constants.O_RDONLY
    case 'rs': // Fall through.
    case 'sr':
      return constants.O_RDONLY | constants.O_SYNC
    case 'r+':
      return constants.O_RDWR
    case 'rs+': // Fall through.
    case 'sr+':
      return constants.O_RDWR | constants.O_SYNC

    case 'w':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_WRONLY
    case 'wx': // Fall through.
    case 'xw':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_WRONLY | constants.O_EXCL

    case 'w+':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_RDWR
    case 'wx+': // Fall through.
    case 'xw+':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_RDWR | constants.O_EXCL

    case 'a':
      return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY
    case 'ax': // Fall through.
    case 'xa':
      return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY | constants.O_EXCL
    case 'as': // Fall through.
    case 'sa':
      return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY | constants.O_SYNC

    case 'a+':
      return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR
    case 'ax+': // Fall through.
    case 'xa+':
      return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR | constants.O_EXCL
    case 'as+': // Fall through.
    case 'sa+':
      return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR | constants.O_SYNC
    default:
      return 0
  }
}

function toMode(mode) {
  return parseInt(mode, 8)
}
const binding = require('../binding')

module.exports = {
  O_RDWR: binding.O_RDWR,
  O_RDONLY: binding.O_RDONLY,
  O_WRONLY: binding.O_WRONLY,
  O_CREAT: binding.O_CREAT,
  O_TRUNC: binding.O_TRUNC,
  O_APPEND: binding.O_APPEND,

  F_OK: binding.F_OK || 0,
  R_OK: binding.R_OK || 0,
  W_OK: binding.W_OK || 0,
  X_OK: binding.X_OK || 0,

  S_IFMT: binding.S_IFMT,
  S_IFREG: binding.S_IFREG,
  S_IFDIR: binding.S_IFDIR,
  S_IFCHR: binding.S_IFCHR,
  S_IFLNK: binding.S_IFLNK,
  S_IFBLK: binding.S_IFBLK || 0,
  S_IFIFO: binding.S_IFIFO || 0,
  S_IFSOCK: binding.S_IFSOCK || 0,

  S_IRUSR: binding.S_IRUSR || 0,
  S_IWUSR: binding.S_IWUSR || 0,
  S_IXUSR: binding.S_IXUSR || 0,
  S_IRGRP: binding.S_IRGRP || 0,
  S_IWGRP: binding.S_IWGRP || 0,
  S_IXGRP: binding.S_IXGRP || 0,
  S_IROTH: binding.S_IROTH || 0,
  S_IWOTH: binding.S_IWOTH || 0,
  S_IXOTH: binding.S_IXOTH || 0,

  UV_DIRENT_UNKNOWN: binding.UV_DIRENT_UNKNOWN,
  UV_DIRENT_FILE: binding.UV_DIRENT_FILE,
  UV_DIRENT_DIR: binding.UV_DIRENT_DIR,
  UV_DIRENT_LINK: binding.UV_DIRENT_LINK,
  UV_DIRENT_FIFO: binding.UV_DIRENT_FIFO,
  UV_DIRENT_SOCKET: binding.UV_DIRENT_SOCKET,
  UV_DIRENT_CHAR: binding.UV_DIRENT_CHAR,
  UV_DIRENT_BLOCK: binding.UV_DIRENT_BLOCK,

  COPYFILE_EXCL: binding.UV_FS_COPYFILE_EXCL,
  COPYFILE_FICLONE: binding.UV_FS_COPYFILE_FICLONE,
  COPYFILE_FICLONE_FORCE: binding.UV_FS_COPYFILE_FICLONE_FORCE,
  UV_FS_SYMLINK_DIR: binding.UV_FS_SYMLINK_DIR,
  UV_FS_SYMLINK_JUNCTION: binding.UV_FS_SYMLINK_JUNCTION
}
const os = require('bare-os')

module.exports = class FileError extends Error {
  constructor(msg, opts = {}) {
    const { code, operation = null, path = null, destination = null, fd = -1 } = opts

    if (operation !== null) msg += describe(operation, opts)

    super(`${code}: ${msg}`)

    this.code = code

    if (operation !== null) this.operation = operation
    if (path !== null) this.path = path
    if (destination !== null) this.destination = destination
    if (fd !== -1) this.fd = fd
  }

  get name() {
    return 'FileError'
  }

  // For Node.js compatibility
  get errno() {
    return os.constants.errnos[this.code]
  }

  // For Node.js compatibility
  get syscall() {
    return this.operation
  }

  // For Node.js compatibility
  get dest() {
    return this.destination
  }
}

function describe(operation, opts) {
  const { path = null, destination = null, fd = -1 } = opts

  let result = `, ${operation}`

  if (path !== null) {
    result += ` ${JSON.stringify(path)}`

    if (destination !== null) {
      result += ` -> ${JSON.stringify(destination)}`
    }
  } else if (fd !== -1) {
    result += ` ${fd}`
  }

  return result
}
{
  "name": "bare-fs",
  "version": "4.7.3",
  "description": "Native file system operations for Bare",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./promises": {
      "types": "./promises.d.ts",
      "default": "./promises.js"
    },
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "promises.js",
    "promises.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-fs.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-fs/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-fs#readme",
  "engines": {
    "bare": ">=1.16.0"
  },
  "dependencies": {
    "bare-events": "^2.5.4",
    "bare-path": "^3.0.0",
    "bare-stream": "^2.6.4",
    "bare-url": "^2.2.2",
    "fast-fifo": "^1.3.2"
  },
  "devDependencies": {
    "bare-buffer": "^3.0.2",
    "bare-crypto": "^1.11.2",
    "brittle": "^3.1.1",
    "cmake-bare": "^1.1.7",
    "lunte": "^1.6.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "bare-buffer": "*"
  },
  "peerDependenciesMeta": {
    "bare-buffer": {
      "optional": true
    }
  }
}
const EventEmitter = require('bare-events')
const fs = require('.')

class FileHandle extends EventEmitter {
  constructor(fd) {
    super()

    this.fd = fd
  }

  async close() {
    await fs.close(this.fd)

    this.fd = -1
    this.emit('close')
  }

  async read(buffer, ...args) {
    return {
      bytesRead: await fs.read(this.fd, buffer, ...args),
      buffer
    }
  }

  async readv(buffers, ...args) {
    return {
      bytesRead: await fs.readv(this.fd, buffers, ...args),
      buffers
    }
  }

  async write(buffer, ...args) {
    return {
      bytesWritten: await fs.write(this.fd, buffer, ...args),
      buffer
    }
  }

  async writev(buffers, ...args) {
    return {
      bytesWritten: await fs.writev(this.fd, buffers, ...args),
      buffers
    }
  }

  async stat() {
    return fs.fstat(this.fd)
  }

  async chmod(mode) {
    await fs.fchmod(this.fd, mode)
  }

  async chown(uid, gid) {
    await fs.fchown(this.fd, uid, gid)
  }

  async datasync() {
    return fs.fdatasync(this.fd)
  }

  async sync() {
    return fs.fsync(this.fd)
  }

  async truncate(len) {
    await fs.ftruncate(this.fd, len)
  }

  async utimes(atime, mtime) {
    await fs.futimes(this.fd, atime, mtime)
  }

  createReadStream(opts) {
    return fs.createReadStream(null, { ...opts, fd: this.fd })
  }

  createWriteStream(opts) {
    return fs.createWriteStream(null, { ...opts, fd: this.fd })
  }

  async [Symbol.asyncDispose]() {
    await this.close()
  }
}

exports.open = async function open(filepath, flags, mode) {
  return new FileHandle(await fs.open(filepath, flags, mode))
}

exports.access = fs.access
exports.appendFile = fs.appendFile
exports.chmod = fs.chmod
exports.chown = fs.chown
exports.constants = fs.constants
exports.copyFile = fs.copyFile
exports.cp = fs.cp
exports.lchown = fs.lchown
exports.lutimes = fs.lutimes
exports.link = fs.link
exports.lstat = fs.lstat
exports.mkdir = fs.mkdir
exports.mkdtemp = fs.mkdtemp
exports.opendir = fs.opendir
exports.readFile = fs.readFile
exports.readdir = fs.readdir
exports.readlink = fs.readlink
exports.realpath = fs.realpath
exports.rename = fs.rename
exports.rm = fs.rm
exports.rmdir = fs.rmdir
exports.stat = fs.stat
exports.statfs = fs.statfs
exports.truncate = fs.truncate
exports.symlink = fs.symlink
exports.unlink = fs.unlink
exports.utimes = fs.utimes
exports.watch = fs.watch
exports.writeFile = fs.writeFile
module.exports = require.addon()
const ansiEscapes = require('bare-ansi-escapes')
const getType = require('bare-type')
const binding = require('./binding')

const PLAIN_KEY = /^[a-zA-Z_][a-zA-Z_0-9]*$/

const defaultDepth = 2
const defaultBreakLength = 80
const defaultMaxArrayLength = 40

module.exports = exports = function inspect(value, opts = {}) {
  const {
    colors = false,
    depth = defaultDepth,
    breakLength = defaultBreakLength,
    stylize = defaultStylize(colors)
  } = opts

  const references = new InspectRefMap()

  const tree = inspectValue(value, 0, {
    colors,
    depth,
    breakLength,
    stylize,
    references
  })

  return tree.toString()
}

exports.styles = {
  bigint: ansiEscapes.colorYellow,
  boolean: ansiEscapes.colorYellow,
  date: ansiEscapes.colorMagenta,
  module: ansiEscapes.modifierUnderline,
  name: ansiEscapes.modifierReset,
  null: ansiEscapes.modifierBold,
  number: ansiEscapes.colorYellow,
  regexp: ansiEscapes.colorRed,
  special: ansiEscapes.colorCyan,
  string: ansiEscapes.colorGreen,
  symbol: ansiEscapes.colorGreen,
  undefined: ansiEscapes.colorBrightBlack
}

const styles = exports.styles

function defaultStylize(colors) {
  return function stylize(value, style) {
    const color = colors && styles[style]

    if (color) return color + value + ansiEscapes.modifierReset

    return value
  }
}

class InspectRefMap {
  constructor() {
    this.refs = new WeakMap()
    this.ids = new WeakMap()
    this.nextId = 1
  }

  has(object) {
    return this.refs.has(object)
  }

  get(object) {
    return this.refs.get(object) || null
  }

  set(object, ref) {
    this.refs.set(object, ref)
  }

  id(object) {
    let id = this.ids.get(object)
    if (id) return id

    id = this.nextId++
    this.ids.set(object, id)

    return id
  }
}

class InspectNode {
  constructor(depth, length, opts) {
    const { breakLength = defaultBreakLength, breakAlways = false } = opts

    this.depth = depth
    this.length = length
    this.breakLength = breakLength
    this.breakAlways = breakAlways
  }

  pad(n, string) {
    return string.padStart(n, ' ')
  }

  indent(n, string) {
    return '  '.repeat(n) + string
  }
}

class InspectRef extends InspectNode {
  constructor(depth, opts) {
    super(depth, '[circular *]'.length, opts)

    this.refs = opts.references
    this.count = 0
    this.circular = false
    this.color = opts.colors && styles.special
  }

  get id() {
    return this.refs.id(this)
  }

  increment() {
    return ++this.count
  }

  decrement() {
    return --this.count
  }

  toString(opts = {}) {
    const { offset = 0, pad = 0, indent = 0 } = opts

    let value = this.pad(pad, '[circular *' + this.id + ']')

    if (this.color) value = this.color + value + ansiEscapes.modifierReset

    return offset ? value : this.indent(indent, value)
  }
}

class InspectLeaf extends InspectNode {
  constructor(value, color, depth, opts) {
    const length = value.length

    if (value.includes('\n')) {
      value = value.replaceAll('\n', '\n' + '  '.repeat(depth))

      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.value = value
    this.color = opts.colors && color
  }

  toString(opts = {}) {
    const { offset = 0, pad = 0, indent = 0 } = opts

    let value = this.pad(pad, this.value)

    if (this.color) value = this.color + value + ansiEscapes.modifierReset

    return offset ? value : this.indent(indent, value)
  }
}

class InspectPair extends InspectNode {
  constructor(delim, left, right, depth, opts) {
    const length = left.length + delim.length + right.length

    if (left.breakAlways || right.breakAlways) {
      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.delim = delim
    this.left = left
    this.right = right
  }

  toString(opts = {}) {
    const { indent = 0 } = opts

    return this.indent(
      indent,
      this.left +
        this.delim +
        this.right.toString({
          indent,
          offset: this.left.length + this.delim.length
        })
    )
  }
}

class InspectSuspension extends InspectNode {
  constructor(overflow, depth, opts) {
    const label = `... ${overflow} more`

    super(depth, label.length, opts)

    this.label = label
  }

  toString(opts = {}) {
    const { indent = 0 } = opts

    return this.indent(indent, this.label)
  }
}

class InspectSequence extends InspectNode {
  constructor(header, footer, delim, values, ref, depth, opts) {
    const { tabulate = false } = opts

    const length =
      (ref.circular ? '<ref *>'.length + 1 : 0) +
      header.length +
      values.reduce(
        (length, value, i) =>
          length + value.length + (i === 0 ? 0 : delim.length),
        0
      ) +
      footer.length

    if (values.some((value) => value.breakAlways)) {
      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.header = header
    this.footer = footer
    this.delim = delim
    this.values = values
    this.ref = ref
    this.tabulate = tabulate
  }

  toString(opts = {}) {
    const { offset = 0, indent = 0 } = opts

    const split =
      this.breakAlways ||
      (this.values.length &&
        (offset + this.length > this.breakLength ||
          indent * 2 + this.length > this.breakLength))

    let header = this.header

    if (this.ref.circular) {
      header = '<ref *' + this.ref.id + '> ' + header
    }

    if (this.values.length === 0) {
      header = header.trimEnd()
    }

    if (offset === 0) {
      header = this.indent(indent, header)
    }

    if (split) {
      header = header.trimEnd() + '\n'
    }

    let string = header

    let columns = 1
    let pad = 0

    if (this.tabulate) {
      const widest = this.values.reduce(
        (length, value) =>
          value.breakAlways ? length : Math.max(length, value.length),
        0
      )

      if (widest) {
        columns = Math.max(
          columns,
          Math.floor(
            (this.breakLength - indent * 2) / (widest + this.delim.length)
          )
        )

        if (columns > 1) pad = widest
      }
    }

    for (let i = 0, n = this.values.length, offset = 0; i < n; i++) {
      const value = this.values[i]

      if (split) {
        let part

        if (i % columns === 0 || value.breakAlways) {
          part = value.toString({ indent: indent + 1, pad })
        } else {
          part = value.toString({ pad })
        }

        string += part

        if (i < n - 1) {
          if (i % columns === columns - 1 || this.values[i + 1].breakAlways) {
            string += this.delim.trimEnd() + '\n'
          } else {
            string += this.delim
          }
        }
      } else {
        if (i > 0) string += this.delim

        string += value.toString({ offset })

        offset += value.length
      }
    }

    let footer = this.footer

    if (this.values.length === 0) {
      footer = footer.trimStart()
    }

    if (split) {
      string += '\n' + this.indent(indent, footer.trimStart())
    } else {
      string += footer
    }

    return string
  }
}

function inspectValue(value, depth, opts) {
  const type = getType(value)

  if (type.isUndefined()) return inspectUndefined(depth, opts)
  if (type.isNull()) return inspectNull(depth, opts)
  if (type.isBoolean()) return inspectBoolean(value, depth, opts)
  if (type.isNumber()) return inspectNumber(value, depth, opts)
  if (type.isBigInt()) return inspectBigInt(value, depth, opts)
  if (type.isString()) return inspectString(value, depth, opts)
  if (type.isSymbol()) return inspectSymbol(value, depth, opts)
  if (type.isObject()) return inspectObject(type, value, depth, opts)
  if (type.isFunction()) return inspectFunction(type, value, depth, opts)
  if (type.isExternal()) return inspectExternal(value, opts, opts)
}

function inspectUndefined(depth, opts) {
  return new InspectLeaf('undefined', styles.undefined, depth, opts)
}

function inspectNull(depth, opts) {
  return new InspectLeaf('null', styles.null, depth, opts)
}

function inspectBoolean(value, depth, opts) {
  return new InspectLeaf(value.toString(), styles.boolean, depth, opts)
}

function inspectNumber(value, depth, opts) {
  let string

  if (Object.is(value, -0)) {
    string = '-0'
  } else {
    string = value.toString(10)
  }

  return new InspectLeaf(string, styles.number, depth, opts)
}

function inspectBigInt(value, depth, opts) {
  return new InspectLeaf(value.toString(10) + 'n', styles.bigint, depth, opts)
}

const STRING_ESCAPES =
  /[\ud800-\udbff][\udc00-\udfff]|[\u0000-\u001f'\\\ud800-\udfff]/g

function inspectString(value, depth, opts) {
  // https://tc39.es/ecma262/multipage/structured-data.html#sec-quotejsonstring
  const string = value.replace(STRING_ESCAPES, (match) => {
    if (match.length === 2) return match

    switch (match) {
      case "'":
        return "\\'"
      case '\\':
        return '\\\\'
      case '\b':
        return '\\b'
      case '\t':
        return '\\t'
      case '\n':
        return '\\n'
      case '\f':
        return '\\f'
      case '\r':
        return '\\r'
      default:
        return '\\u' + match.charCodeAt(0).toString(16).padStart(4, '0')
    }
  })

  return new InspectLeaf("'" + string + "'", styles.string, depth, opts)
}

function inspectSymbol(value, depth, opts) {
  return new InspectLeaf(value.toString(), styles.symbol, depth, opts)
}

function inspectKey(value, depth, opts) {
  if (PLAIN_KEY.test(value)) {
    return new InspectLeaf(value, null, depth, opts)
  } else {
    return inspectValue(value, depth, opts)
  }
}

function inspectObject(type, object, depth, opts) {
  const refs = opts.references

  let ref = refs.get(object)
  if (ref === null) {
    ref = new InspectRef(depth, opts)
    refs.set(object, ref)
  } else if (ref.count) {
    ref.circular = true
    return ref
  }

  const maxDepth = typeof opts.depth === 'number' ? opts.depth : Infinity

  if (maxDepth < depth) {
    const constructor = object.constructor

    return new InspectLeaf(
      '[' +
        (constructor && constructor.name ? constructor.name : 'Object') +
        ']',
      styles.special,
      depth,
      opts
    )
  }

  const inspect =
    object[Symbol.for('bare.inspect')] ||
    object[Symbol.for('nodejs.util.inspect.custom')]

  if (typeof inspect === 'function') {
    const value = inspect.call(
      object,
      typeof opts.depth === 'number' ? opts.depth - depth : null,
      {
        colors: opts.colors,
        breakLength: opts.breakLength,
        stylize: opts.stylize
      },
      exports
    )

    if (typeof value === 'object' && value !== null) {
      refs.set(value, ref)
    }

    if (typeof value !== 'string') {
      return inspectValue(value, depth, opts)
    }

    return new InspectLeaf(value, null, depth, opts)
  }

  if (type.isArray()) return inspectArray(object, ref, depth, opts)
  if (type.isDate()) return inspectDate(object, ref, depth, opts)
  if (type.isRegExp()) return inspectRegExp(object, ref, depth, opts)
  if (type.isError()) return inspectError(object, ref, depth, opts)
  if (type.isPromise()) return inspectPromise(object, ref, depth, opts)
  if (type.isMap()) return inspectMap(object, ref, depth, opts)
  if (type.isSet()) return inspectSet(object, ref, depth, opts)
  if (type.isWeakMap()) return inspectWeakMap(object, ref, depth, opts)
  if (type.isWeakSet()) return inspectWeakSet(object, ref, depth, opts)
  if (type.isWeakRef()) return inspectWeakRef(object, ref, depth, opts)
  if (type.isArrayBuffer()) return inspectArrayBuffer(object, ref, depth, opts)
  if (type.isSharedArrayBuffer())
    return inspectSharedArrayBuffer(object, ref, depth, opts)
  if (type.isTypedArray()) return inspectTypedArray(object, ref, depth, opts)
  if (type.isDataView()) return inspectDataView(object, ref, depth, opts)

  ref.increment()

  const values = []

  for (const key in object) {
    if (key === 'constructor') continue

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(object[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  let header = '{ '

  const tag = object[Symbol.toStringTag]

  if (tag) header = '[' + tag + '] ' + header

  if (object.constructor) {
    const name = object.constructor.name

    if (name && name !== 'Object') {
      header = object.constructor.name + ' ' + header
    }
  }

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectArray(array, ref, depth, opts) {
  const { maxArrayLength = defaultMaxArrayLength } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxArrayLength, 0)

  for (let i = 0, n = array.length; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(array.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(inspectValue(array[i], depth + 1, opts))
  }

  for (const key of binding.getOwnNonIndexPropertyNames(array)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(array[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  let header = '[ '

  if (array.constructor.name !== 'Array') {
    header = array.constructor.name + '(' + array.length + ') ' + header
  }

  return new InspectSequence(header, ' ]', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectDate(date, ref, depth, opts) {
  return new InspectLeaf(date.toISOString(), styles.date, depth, opts)
}

function inspectRegExp(regExp, ref, depth, opts) {
  return new InspectLeaf(regExp.toString(), styles.regexp, depth, opts)
}

function inspectError(error, ref, depth, opts) {
  let header

  if ('stack' in error) {
    header = error.stack

    if (depth > 0) {
      header = header.replaceAll('\n', '\n' + '  '.repeat(depth))
    }
  } else {
    header = error.toString()
  }

  const builtins = ['cause']

  if (error.name === 'AggregateError') {
    builtins.push('errors')
  } else if (error.name === 'SuppressedError') {
    builtins.push('error', 'suppressed')
  }

  const values = []

  for (const key of builtins) {
    if (key in error === false) continue

    values.push(
      new InspectPair(
        ': ',
        new InspectLeaf('[' + key + ']', null, depth + 1, opts),
        inspectValue(error[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key in error) {
    if (key === 'constructor' || builtins.includes(key)) continue

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(error[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  if (values.length === 0) return new InspectLeaf(header, null, depth, opts)

  return new InspectSequence(
    header + ' {',
    ' }',
    ', ',
    values,
    ref,
    depth,
    opts
  )
}

function inspectPromise(promise, ref, depth, opts) {
  ref.increment()

  const state = binding.getPromiseState(promise)

  const values = []

  switch (state) {
    case 0: // Pending
      values.push(new InspectLeaf('<pending>', styles.special, depth, opts))
      break

    case 1: // Fulfilled
      values.push(inspectValue(binding.getPromiseResult(promise), depth, opts))
      break

    case 2: // Rejected
      values.push(
        new InspectLeaf('<rejected>', styles.special, depth, opts),
        inspectValue(binding.getPromiseResult(promise), depth, opts)
      )
  }

  ref.decrement()

  const header = promise.constructor.name + ' { '

  return new InspectSequence(header, ' }', ' ', values, ref, depth, opts)
}

function inspectMap(map, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxMapLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = maxMapLength

  for (const entry of map) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(map.size - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )
      break
    }

    values.push(
      new InspectPair(
        ' => ',
        inspectValue(entry[0], depth + 1, opts),
        inspectValue(entry[1], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key in map) {
    if (key === 'constructor') continue

    const value = inspectValue(map[key], depth + 1, opts)

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        value,
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = map.constructor.name + '(' + map.size + ') { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectSet(set, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxSetLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = maxSetLength

  for (const entry of set) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(set.size - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )
      break
    }

    values.push(inspectValue(entry, depth + 1, opts))
  }

  for (const key in set) {
    if (key === 'constructor') continue

    const value = inspectValue(set[key], depth + 1, opts)

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        value,
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = set.constructor.name + '(' + set.size + ') { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectWeakMap(weakMap, ref, depth, opts) {
  const header = weakMap.constructor.name + ' { '

  return new InspectSequence(
    header,
    ' }',
    ' ',
    [new InspectLeaf('<items unknown>', styles.special, depth + 1, opts)],
    ref,
    depth,
    opts
  )
}

function inspectWeakSet(weakSet, ref, depth, opts) {
  const header = weakSet.constructor.name + ' { '

  return new InspectSequence(
    header,
    ' }',
    ' ',
    [new InspectLeaf('<items unknown>', styles.special, depth + 1, opts)],
    ref,
    depth,
    opts
  )
}

function inspectWeakRef(weakRef, ref, depth, opts) {
  const target = weakRef.deref()

  let value

  if (target === undefined) {
    value = new InspectLeaf('<cleared>', styles.special, depth + 1, opts)
  } else {
    value = inspectValue(target, depth + 1, opts)
  }

  const header = weakRef.constructor.name + ' { '

  return new InspectSequence(header, ' }', ' ', [value], ref, depth, opts)
}

function inspectArrayBuffer(arrayBuffer, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(arrayBuffer[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = arrayBuffer.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectSharedArrayBuffer(sharedArrayBuffer, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(sharedArrayBuffer[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = sharedArrayBuffer.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectTypedArray(typedArray, ref, depth, opts) {
  if (Buffer.isBuffer(typedArray)) {
    return inspectBuffer(typedArray, ref, depth, opts)
  }

  const {
    maxArrayLength = defaultMaxArrayLength,
    maxTypedArrayLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxTypedArrayLength, 0)

  for (let i = 0, n = typedArray.length; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(typedArray.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(inspectValue(typedArray[i], depth + 1, opts))
  }

  for (const key of binding.getOwnNonIndexPropertyNames(typedArray)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(typedArray[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = typedArray.constructor.name + '(' + typedArray.length + ') [ '

  return new InspectSequence(header, ' ]', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectBuffer(buffer, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxBufferLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxBufferLength, 0)

  for (let i = 0, n = buffer.byteLength; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(buffer.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(
      new InspectLeaf(
        buffer[i].toString(16).padStart(2, '0'),
        null,
        depth + 1,
        opts
      )
    )
  }

  for (const key of binding.getOwnNonIndexPropertyNames(buffer)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(buffer[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  return new InspectSequence('<Buffer ', '>', ' ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectDataView(dataView, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength', 'byteOffset', 'buffer']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(dataView[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key of binding.getOwnNonIndexPropertyNames(dataView)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(dataView[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = dataView.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectFunction(type, fn, depth, opts) {
  if (fn.toString().startsWith('class')) return inspectClass(fn, depth, opts)

  let tag = 'function'

  if (type.isGeneratorFunction()) tag = 'generator ' + tag
  if (type.isAsyncFunction()) tag = 'async ' + tag

  return new InspectLeaf(
    '[' + tag + ' ' + (fn.name ? fn.name : '(anonymous)') + ']',
    styles.special,
    depth,
    opts
  )
}

function inspectClass(ctor, depth, opts) {
  return new InspectLeaf(
    '[class ' + (ctor.name ? ctor.name : '(anonymous)') + ']',
    styles.special,
    depth,
    opts
  )
}

function inspectExternal(external, depth, opts) {
  return new InspectLeaf(
    '[external 0x' + binding.getExternal(external).toString(16) + ']',
    styles.special,
    depth,
    opts
  )
}
{
  "name": "bare-inspect",
  "version": "3.1.4",
  "description": "Inspect objects as strings for debugging",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-inspect.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-inspect/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-inspect#readme",
  "engines": {
    "bare": ">=1.18.0"
  },
  "dependencies": {
    "bare-ansi-escapes": "^2.1.0",
    "bare-type": "^1.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
module.exports = require.addon()
const binding = require('./binding')
const errors = require('./lib/errors')
const constants = require('./lib/constants')

exports.constants = constants
exports.errors = errors

exports.EOL = binding.platform === 'win32' ? '\r\n' : '\n'

exports.devNull = binding.platform === 'win32' ? '\\\\.\\nul' : '/dev/null'

exports.platform = function platform() {
  return binding.platform
}

exports.arch = function arch() {
  return binding.arch
}

exports.type = function type() {
  return binding.type()
}

exports.version = function version() {
  return binding.version()
}

exports.release = function release() {
  return binding.release()
}

exports.machine = function machine() {
  return binding.machine()
}

exports.execPath = function execPath() {
  return binding.execPath()
}

exports.pid = function pid() {
  return binding.pid()
}

exports.ppid = function ppid() {
  return binding.ppid()
}

exports.cwd = function cwd() {
  return binding.cwd()
}

exports.chdir = function chdir(dir) {
  validateString(dir, 'Directory')

  binding.chdir(dir)
}

exports.tmpdir = function tmpdir() {
  return binding.tmpdir()
}

exports.homedir = function homedir() {
  return binding.homedir()
}

exports.hostname = function hostname() {
  return binding.hostname()
}

exports.userInfo = function userInfo(uid) {
  if (uid !== undefined) validateInteger(uid, 'User ID')

  return binding.userInfo(uid)
}

exports.groupInfo = function groupInfo(gid) {
  if (gid !== undefined) validateInteger(gid, 'Group ID')

  return binding.groupInfo(gid)
}

exports.networkInterfaces = function networkInterfaces() {
  const result = {}

  for (const entry of binding.networkInterfaces()) {
    const { name, ...properties } = entry

    if (result[name]) result[name].push(properties)
    else result[name] = [properties]
  }

  return result
}

exports.kill = function kill(pid, signal = constants.signals.SIGTERM) {
  validateInteger(pid, 'Process ID')

  if (typeof signal === 'string') {
    if (signal in constants.signals === false) {
      throw errors.UNKNOWN_SIGNAL('Unknown signal: ' + signal)
    }

    signal = constants.signals[signal]
  } else {
    validateInteger(signal, 'Signal')
  }

  binding.kill(pid, signal)
}

exports.endianness = function endianness() {
  return binding.isLittleEndian ? 'LE' : 'BE'
}

exports.availableParallelism = function availableParallelism() {
  return binding.availableParallelism()
}

exports.cpuUsage = function cpuUsage(previous) {
  const current = binding.cpuUsage()

  if (previous) {
    return {
      user: current.user - previous.user,
      system: current.system - previous.system
    }
  }

  return current
}

exports.threadCpuUsage = function threadCpuUsage(previous) {
  const current = binding.threadCpuUsage()

  if (previous) {
    return {
      user: current.user - previous.user,
      system: current.system - previous.system
    }
  }

  return current
}

exports.resourceUsage = function resourceUsage() {
  return binding.resourceUsage()
}

exports.memoryUsage = function memoryUsage() {
  return binding.memoryUsage()
}

exports.freemem = function freemem() {
  return binding.freemem()
}

exports.totalmem = function totalmem() {
  return binding.totalmem()
}

exports.availableMemory = function availableMemory() {
  return binding.availableMemory()
}

exports.constrainedMemory = function constrainedMemory() {
  return binding.constrainedMemory()
}

exports.uptime = function uptime() {
  return binding.uptime()
}

exports.loadavg = function loadavg() {
  return binding.loadavg()
}

exports.cpus = function cpus() {
  return binding.cpus()
}

exports.getProcessTitle = function getProcessTitle() {
  return binding.getProcessTitle()
}

exports.setProcessTitle = function setProcessTitle(title) {
  if (typeof title !== 'string') title = title.toString()

  if (title.length >= 256) {
    throw errors.TITLE_OVERFLOW('Process title is too long')
  }

  binding.setProcessTitle(title)
}

exports.getPriority = function getPriority(pid = 0) {
  validateInteger(pid, 'Process ID')

  return binding.getPriority(pid)
}

exports.setPriority = function setPriority(pid, priority) {
  if (priority === undefined) {
    priority = pid
    pid = 0
  }

  validateInteger(pid, 'Process ID')
  validateInteger(priority, 'Priority')

  binding.setPriority(pid, priority)
}

exports.getEnvKeys = function getEnvKeys() {
  return binding.getEnvKeys()
}

exports.getEnv = function getEnv(name) {
  validateString(name, 'Name')

  return binding.getEnv(name)
}

exports.hasEnv = function hasEnv(name) {
  validateString(name, 'Name')

  return binding.hasEnv(name)
}

exports.setEnv = function setEnv(name, value) {
  validateString(name, 'Name')
  validateString(value, 'Value')

  binding.setEnv(name, value)
}

exports.unsetEnv = function unsetEnv(name) {
  validateString(name, 'Name')

  binding.unsetEnv(name)
}

function validateString(value, name) {
  if (typeof value !== 'string') {
    throw new TypeError(`${name} must be a string. Received type ${typeof value} (${value})`)
  }
}

function validateInteger(value, name) {
  if (!Number.isInteger(value)) {
    throw new TypeError(`${name} must be an integer. Received type ${typeof value} (${value})`)
  }
}
const binding = require('../binding')

module.exports = {
  signals: binding.signals,
  errnos: binding.errnos,
  priority: binding.priority
}
module.exports = class OSError extends Error {
  constructor(msg, fn = OSError, code = fn.name) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'OSError'
  }

  static UNKNOWN_SIGNAL(msg) {
    return new OSError(msg, OSError.UNKNOWN_SIGNAL)
  }

  static TITLE_OVERFLOW(msg) {
    return new OSError(msg, OSError.TITLE_OVERFLOW)
  }
}
{
  "name": "bare-os",
  "version": "3.9.3",
  "description": "Operating system utilities for Bare",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    },
    "./errors": {
      "types": "./lib/errors.d.ts",
      "default": "./lib/errors.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-os.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-os/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-os#readme",
  "engines": {
    "bare": ">=1.14.0"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "cmake-bare": "^1.1.6",
    "lunte": "^1.6.0",
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
// This export SHOULD NOT be shortened in any way as having the full
// `module.exports = require(...)` statement is crucial for synthesizing
// ESM exports.

if (Bare.platform === 'win32') {
  module.exports = require('./lib/win32')
} else {
  module.exports = require('./lib/posix')
}
module.exports = {
  CHAR_UPPERCASE_A: 0x41,
  CHAR_LOWERCASE_A: 0x61,
  CHAR_UPPERCASE_Z: 0x5a,
  CHAR_LOWERCASE_Z: 0x7a,
  CHAR_DOT: 0x2e,
  CHAR_FORWARD_SLASH: 0x2f,
  CHAR_BACKWARD_SLASH: 0x5c,
  CHAR_COLON: 0x3a,
  CHAR_QUESTION_MARK: 0x3f
}
const os = require('bare-os')

const { normalizeString } = require('./shared')
const { CHAR_DOT, CHAR_FORWARD_SLASH } = require('./constants')

function isPosixPathSeparator(code) {
  return code === CHAR_FORWARD_SLASH
}

exports.win32 = require('./win32')
exports.posix = exports

exports.sep = '/'
exports.delimiter = ':'

exports.resolve = function resolve(...args) {
  let resolvedPath = ''
  let resolvedAbsolute = false

  for (let i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) {
    const path = i >= 0 ? args[i] : os.cwd()

    if (path.length === 0) {
      continue
    }

    resolvedPath = `${path}/${resolvedPath}`
    resolvedAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH
  }

  resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute, '/', isPosixPathSeparator)

  if (resolvedAbsolute) {
    return `/${resolvedPath}`
  }

  return resolvedPath.length > 0 ? resolvedPath : '.'
}

exports.normalize = function normalize(path) {
  if (path.length === 0) return '.'

  const isAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH
  const trailingSeparator = path.charCodeAt(path.length - 1) === CHAR_FORWARD_SLASH

  path = normalizeString(path, !isAbsolute, '/', isPosixPathSeparator)

  if (path.length === 0) {
    if (isAbsolute) return '/'
    return trailingSeparator ? './' : '.'
  }

  if (trailingSeparator) path += '/'

  return isAbsolute ? `/${path}` : path
}

exports.isAbsolute = function isAbsolute(path) {
  return path.length > 0 && path.charCodeAt(0) === CHAR_FORWARD_SLASH
}

exports.join = function join(...args) {
  if (args.length === 0) return '.'
  let joined
  for (let i = 0; i < args.length; ++i) {
    const arg = args[i]
    if (arg.length > 0) {
      if (joined === undefined) joined = arg
      else joined += `/${arg}`
    }
  }
  if (joined === undefined) return '.'
  return exports.normalize(joined)
}

exports.relative = function relative(from, to) {
  if (from === to) return ''

  from = exports.resolve(from)
  to = exports.resolve(to)

  if (from === to) return ''

  const fromStart = 1
  const fromEnd = from.length
  const fromLen = fromEnd - fromStart
  const toStart = 1
  const toLen = to.length - toStart

  const length = fromLen < toLen ? fromLen : toLen
  let lastCommonSep = -1
  let i = 0
  for (; i < length; i++) {
    const fromCode = from.charCodeAt(fromStart + i)
    if (fromCode !== to.charCodeAt(toStart + i)) {
      break
    } else if (fromCode === CHAR_FORWARD_SLASH) {
      lastCommonSep = i
    }
  }
  if (i === length) {
    if (toLen > length) {
      if (to.charCodeAt(toStart + i) === CHAR_FORWARD_SLASH) {
        return to.substring(toStart + i + 1)
      }
      if (i === 0) {
        return to.substring(toStart + i)
      }
    } else if (fromLen > length) {
      if (from.charCodeAt(fromStart + i) === CHAR_FORWARD_SLASH) {
        lastCommonSep = i
      } else if (i === 0) {
        lastCommonSep = 0
      }
    }
  }

  let out = ''
  for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
    if (i === fromEnd || from.charCodeAt(i) === CHAR_FORWARD_SLASH) {
      out += out.length === 0 ? '..' : '/..'
    }
  }

  return `${out}${to.substring(toStart + lastCommonSep)}`
}

exports.toNamespacedPath = function toNamespacedPath(path) {
  return path
}

exports.dirname = function dirname(path) {
  if (path.length === 0) return '.'
  const hasRoot = path.charCodeAt(0) === CHAR_FORWARD_SLASH
  let end = -1
  let matchedSlash = true
  for (let i = path.length - 1; i >= 1; --i) {
    if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) {
      if (!matchedSlash) {
        end = i
        break
      }
    } else {
      matchedSlash = false
    }
  }

  if (end === -1) return hasRoot ? '/' : '.'
  if (hasRoot && end === 1) return '//'
  return path.substring(0, end)
}

exports.basename = function basename(path, suffix) {
  let start = 0
  let end = -1
  let matchedSlash = true

  if (suffix !== undefined && suffix.length > 0 && suffix.length <= path.length) {
    if (suffix === path) {
      return ''
    }
    let extIdx = suffix.length - 1
    let firstNonSlashEnd = -1
    for (let i = path.length - 1; i >= 0; --i) {
      const code = path.charCodeAt(i)
      if (code === CHAR_FORWARD_SLASH) {
        if (!matchedSlash) {
          start = i + 1
          break
        }
      } else {
        if (firstNonSlashEnd === -1) {
          matchedSlash = false
          firstNonSlashEnd = i + 1
        }
        if (extIdx >= 0) {
          if (code === suffix.charCodeAt(extIdx)) {
            if (--extIdx === -1) {
              end = i
            }
          } else {
            extIdx = -1
            end = firstNonSlashEnd
          }
        }
      }
    }

    if (start === end) end = firstNonSlashEnd
    else if (end === -1) end = path.length
    return path.substring(start, end)
  }

  for (let i = path.length - 1; i >= 0; --i) {
    if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) {
      if (!matchedSlash) {
        start = i + 1
        break
      }
    } else if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
  }

  if (end === -1) return ''
  return path.substring(start, end)
}

exports.extname = function extname(path) {
  let startDot = -1
  let startPart = 0
  let end = -1
  let matchedSlash = true
  let preDotState = 0
  for (let i = path.length - 1; i >= 0; --i) {
    const code = path.charCodeAt(i)
    if (code === CHAR_FORWARD_SLASH) {
      if (!matchedSlash) {
        startPart = i + 1
        break
      }
      continue
    }
    if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
    if (code === CHAR_DOT) {
      if (startDot === -1) startDot = i
      else if (preDotState !== 1) preDotState = 1
    } else if (startDot !== -1) {
      preDotState = -1
    }
  }

  if (
    startDot === -1 ||
    end === -1 ||
    preDotState === 0 ||
    (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1)
  ) {
    return ''
  }
  return path.substring(startDot, end)
}
const { CHAR_DOT, CHAR_FORWARD_SLASH } = require('./constants')

exports.normalizeString = function normalizeString(
  path,
  allowAboveRoot,
  separator,
  isPathSeparator
) {
  let res = ''
  let lastSegmentLength = 0
  let lastSlash = -1
  let dots = 0
  let code = 0
  for (let i = 0; i <= path.length; ++i) {
    if (i < path.length) {
      code = path.charCodeAt(i)
    } else if (isPathSeparator(code)) {
      break
    } else {
      code = CHAR_FORWARD_SLASH
    }

    if (isPathSeparator(code)) {
      if (lastSlash === i - 1 || dots === 1);
      else if (dots === 2) {
        if (
          res.length < 2 ||
          lastSegmentLength !== 2 ||
          res.charCodeAt(res.length - 1) !== CHAR_DOT ||
          res.charCodeAt(res.length - 2) !== CHAR_DOT
        ) {
          if (res.length > 2) {
            const lastSlashIndex = res.lastIndexOf(separator)
            if (lastSlashIndex === -1) {
              res = ''
              lastSegmentLength = 0
            } else {
              res = res.substring(0, lastSlashIndex)
              lastSegmentLength = res.length - 1 - res.lastIndexOf(separator)
            }
            lastSlash = i
            dots = 0
            continue
          } else if (res.length !== 0) {
            res = ''
            lastSegmentLength = 0
            lastSlash = i
            dots = 0
            continue
          }
        }
        if (allowAboveRoot) {
          res += res.length > 0 ? `${separator}..` : '..'
          lastSegmentLength = 2
        }
      } else {
        if (res.length > 0) {
          res += `${separator}${path.substring(lastSlash + 1, i)}`
        } else {
          res = path.substring(lastSlash + 1, i)
        }
        lastSegmentLength = i - lastSlash - 1
      }
      lastSlash = i
      dots = 0
    } else if (code === CHAR_DOT && dots !== -1) {
      ++dots
    } else {
      dots = -1
    }
  }
  return res
}
const os = require('bare-os')

const { normalizeString } = require('./shared')
const {
  CHAR_UPPERCASE_A,
  CHAR_LOWERCASE_A,
  CHAR_UPPERCASE_Z,
  CHAR_LOWERCASE_Z,
  CHAR_DOT,
  CHAR_FORWARD_SLASH,
  CHAR_BACKWARD_SLASH,
  CHAR_COLON,
  CHAR_QUESTION_MARK
} = require('./constants')

function isWindowsPathSeparator(code) {
  return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH
}

function isWindowsDeviceRoot(code) {
  return (
    (code >= CHAR_UPPERCASE_A && code <= CHAR_UPPERCASE_Z) ||
    (code >= CHAR_LOWERCASE_A && code <= CHAR_LOWERCASE_Z)
  )
}

exports.posix = require('./posix')
exports.win32 = exports

exports.sep = '\\'
exports.delimiter = ';'

exports.resolve = function resolve(...args) {
  let resolvedDevice = ''
  let resolvedTail = ''
  let resolvedAbsolute = false

  for (let i = args.length - 1; i >= -1; i--) {
    let path
    if (i >= 0) {
      path = args[i]

      if (path.length === 0) continue
    } else if (resolvedDevice.length === 0) {
      path = os.cwd()
    } else {
      path = os.getEnv(`=${resolvedDevice}`) || os.cwd()

      if (
        path === undefined ||
        (path.substring(0, 2).toLowerCase() !== resolvedDevice.toLowerCase() &&
          path.charCodeAt(2) === CHAR_BACKWARD_SLASH)
      ) {
        path = `${resolvedDevice}\\`
      }
    }

    const len = path.length
    let rootEnd = 0
    let device = ''
    let isAbsolute = false
    const code = path.charCodeAt(0)

    if (len === 1) {
      if (isWindowsPathSeparator(code)) {
        rootEnd = 1
        isAbsolute = true
      }
    } else if (isWindowsPathSeparator(code)) {
      isAbsolute = true

      if (isWindowsPathSeparator(path.charCodeAt(1))) {
        let j = 2
        let last = j
        while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
          j++
        }
        if (j < len && j !== last) {
          const firstPart = path.substring(last, j)
          last = j
          while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
            j++
          }
          if (j < len && j !== last) {
            last = j
            while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
              j++
            }
            if (j === len || j !== last) {
              device = `\\\\${firstPart}\\${path.substring(last, j)}`
              rootEnd = j
            }
          }
        }
      } else {
        rootEnd = 1
      }
    } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
      device = path.substring(0, 2)
      rootEnd = 2
      if (len > 2 && isWindowsPathSeparator(path.charCodeAt(2))) {
        isAbsolute = true
        rootEnd = 3
      }
    }

    if (device.length > 0) {
      if (resolvedDevice.length > 0) {
        if (device.toLowerCase() !== resolvedDevice.toLowerCase()) {
          continue
        }
      } else {
        resolvedDevice = device
      }
    }

    if (resolvedAbsolute) {
      if (resolvedDevice.length > 0) {
        break
      }
    } else {
      resolvedTail = `${path.substring(rootEnd)}\\${resolvedTail}`
      resolvedAbsolute = isAbsolute
      if (isAbsolute && resolvedDevice.length > 0) {
        break
      }
    }
  }

  resolvedTail = normalizeString(resolvedTail, !resolvedAbsolute, '\\', isWindowsPathSeparator)

  return resolvedAbsolute
    ? `${resolvedDevice}\\${resolvedTail}`
    : `${resolvedDevice}${resolvedTail}` || '.'
}

exports.normalize = function normalize(path) {
  const len = path.length
  if (len === 0) return '.'
  let rootEnd = 0
  let device
  let isAbsolute = false
  const code = path.charCodeAt(0)

  if (len === 1) {
    return code === CHAR_FORWARD_SLASH ? '\\' : path
  }

  if (isWindowsPathSeparator(code)) {
    isAbsolute = true

    if (isWindowsPathSeparator(path.charCodeAt(1))) {
      let j = 2
      let last = j
      while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
        j++
      }
      if (j < len && j !== last) {
        const firstPart = path.substring(last, j)
        last = j
        while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
          j++
        }
        if (j < len && j !== last) {
          last = j
          while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
            j++
          }
          if (j === len) {
            return `\\\\${firstPart}\\${path.substring(last)}\\`
          }
          if (j !== last) {
            device = `\\\\${firstPart}\\${path.substring(last, j)}`
            rootEnd = j
          }
        }
      }
    } else {
      rootEnd = 1
    }
  } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
    device = path.substring(0, 2)
    rootEnd = 2
    if (len > 2 && isWindowsPathSeparator(path.charCodeAt(2))) {
      isAbsolute = true
      rootEnd = 3
    }
  }

  let tail =
    rootEnd < len
      ? normalizeString(path.substring(rootEnd), !isAbsolute, '\\', isWindowsPathSeparator)
      : ''
  if (tail.length === 0 && !isAbsolute) {
    tail = '.'
  }
  if (tail.length > 0 && isWindowsPathSeparator(path.charCodeAt(len - 1))) {
    tail += '\\'
  }
  if (device === undefined) {
    return isAbsolute ? `\\${tail}` : tail
  }
  return isAbsolute ? `${device}\\${tail}` : `${device}${tail}`
}

exports.isAbsolute = function isAbsolute(path) {
  const len = path.length
  if (len === 0) return false

  const code = path.charCodeAt(0)

  return (
    isWindowsPathSeparator(code) ||
    (len > 2 &&
      isWindowsDeviceRoot(code) &&
      path.charCodeAt(1) === CHAR_COLON &&
      isWindowsPathSeparator(path.charCodeAt(2)))
  )
}

exports.join = function join(...args) {
  if (args.length === 0) return '.'

  let joined
  let firstPart
  for (let i = 0; i < args.length; ++i) {
    const arg = args[i]
    if (arg.length > 0) {
      if (joined === undefined) joined = firstPart = arg
      else joined += `\\${arg}`
    }
  }

  if (joined === undefined) return '.'

  let needsReplace = true
  let slashCount = 0
  if (isWindowsPathSeparator(firstPart.charCodeAt(0))) {
    ++slashCount
    const firstLen = firstPart.length
    if (firstLen > 1 && isWindowsPathSeparator(firstPart.charCodeAt(1))) {
      ++slashCount
      if (firstLen > 2) {
        if (isWindowsPathSeparator(firstPart.charCodeAt(2))) {
          ++slashCount
        } else {
          needsReplace = false
        }
      }
    }
  }
  if (needsReplace) {
    while (slashCount < joined.length && isWindowsPathSeparator(joined.charCodeAt(slashCount))) {
      slashCount++
    }

    if (slashCount >= 2) {
      joined = `\\${joined.substring(slashCount)}`
    }
  }

  return exports.normalize(joined)
}

exports.relative = function relative(from, to) {
  if (from === to) return ''

  const fromOrig = exports.resolve(from)
  const toOrig = exports.resolve(to)

  if (fromOrig === toOrig) return ''

  from = fromOrig.toLowerCase()
  to = toOrig.toLowerCase()

  if (from === to) return ''

  let fromStart = 0
  while (fromStart < from.length && from.charCodeAt(fromStart) === CHAR_BACKWARD_SLASH) {
    fromStart++
  }
  let fromEnd = from.length
  while (fromEnd - 1 > fromStart && from.charCodeAt(fromEnd - 1) === CHAR_BACKWARD_SLASH) {
    fromEnd--
  }
  const fromLen = fromEnd - fromStart

  let toStart = 0
  while (toStart < to.length && to.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) {
    toStart++
  }
  let toEnd = to.length
  while (toEnd - 1 > toStart && to.charCodeAt(toEnd - 1) === CHAR_BACKWARD_SLASH) {
    toEnd--
  }
  const toLen = toEnd - toStart

  const length = fromLen < toLen ? fromLen : toLen
  let lastCommonSep = -1
  let i = 0
  for (; i < length; i++) {
    const fromCode = from.charCodeAt(fromStart + i)
    if (fromCode !== to.charCodeAt(toStart + i)) {
      break
    } else if (fromCode === CHAR_BACKWARD_SLASH) {
      lastCommonSep = i
    }
  }

  if (i !== length) {
    if (lastCommonSep === -1) return toOrig
  } else {
    if (toLen > length) {
      if (to.charCodeAt(toStart + i) === CHAR_BACKWARD_SLASH) {
        return toOrig.substring(toStart + i + 1)
      }
      if (i === 2) {
        return toOrig.substring(toStart + i)
      }
    }
    if (fromLen > length) {
      if (from.charCodeAt(fromStart + i) === CHAR_BACKWARD_SLASH) {
        lastCommonSep = i
      } else if (i === 2) {
        lastCommonSep = 3
      }
    }
    if (lastCommonSep === -1) lastCommonSep = 0
  }

  let out = ''
  for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
    if (i === fromEnd || from.charCodeAt(i) === CHAR_BACKWARD_SLASH) {
      out += out.length === 0 ? '..' : '\\..'
    }
  }

  toStart += lastCommonSep

  if (out.length > 0) {
    return `${out}${toOrig.substring(toStart, toEnd)}`
  }
  if (toOrig.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) {
    ++toStart
  }
  return toOrig.substring(toStart, toEnd)
}

exports.toNamespacedPath = function toNamespacedPath(path) {
  if (path.length === 0) return path

  const resolvedPath = exports.resolve(path)

  if (resolvedPath.length <= 2) return path

  if (resolvedPath.charCodeAt(0) === CHAR_BACKWARD_SLASH) {
    if (resolvedPath.charCodeAt(1) === CHAR_BACKWARD_SLASH) {
      const code = resolvedPath.charCodeAt(2)
      if (code !== CHAR_QUESTION_MARK && code !== CHAR_DOT) {
        return `\\\\?\\UNC\\${resolvedPath.substring(2)}`
      }
    }
  } else if (
    isWindowsDeviceRoot(resolvedPath.charCodeAt(0)) &&
    resolvedPath.charCodeAt(1) === CHAR_COLON &&
    resolvedPath.charCodeAt(2) === CHAR_BACKWARD_SLASH
  ) {
    return `\\\\?\\${resolvedPath}`
  }

  return path
}

exports.dirname = function dirname(path) {
  const len = path.length
  if (len === 0) return '.'
  let rootEnd = -1
  let offset = 0
  const code = path.charCodeAt(0)

  if (len === 1) {
    return isWindowsPathSeparator(code) ? path : '.'
  }

  if (isWindowsPathSeparator(code)) {
    rootEnd = offset = 1

    if (isWindowsPathSeparator(path.charCodeAt(1))) {
      let j = 2
      let last = j
      while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
        j++
      }
      if (j < len && j !== last) {
        last = j
        while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
          j++
        }
        if (j < len && j !== last) {
          last = j
          while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
            j++
          }
          if (j === len) {
            return path
          }
          if (j !== last) {
            rootEnd = offset = j + 1
          }
        }
      }
    }
  } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
    rootEnd = len > 2 && isWindowsPathSeparator(path.charCodeAt(2)) ? 3 : 2
    offset = rootEnd
  }

  let end = -1
  let matchedSlash = true
  for (let i = len - 1; i >= offset; --i) {
    if (isWindowsPathSeparator(path.charCodeAt(i))) {
      if (!matchedSlash) {
        end = i
        break
      }
    } else {
      matchedSlash = false
    }
  }

  if (end === -1) {
    if (rootEnd === -1) return '.'

    end = rootEnd
  }
  return path.substring(0, end)
}

exports.basename = function basename(path, suffix) {
  let start = 0
  let end = -1
  let matchedSlash = true

  if (
    path.length >= 2 &&
    isWindowsDeviceRoot(path.charCodeAt(0)) &&
    path.charCodeAt(1) === CHAR_COLON
  ) {
    start = 2
  }

  if (suffix !== undefined && suffix.length > 0 && suffix.length <= path.length) {
    if (suffix === path) return ''
    let extIdx = suffix.length - 1
    let firstNonSlashEnd = -1
    for (let i = path.length - 1; i >= start; --i) {
      const code = path.charCodeAt(i)
      if (isWindowsPathSeparator(code)) {
        if (!matchedSlash) {
          start = i + 1
          break
        }
      } else {
        if (firstNonSlashEnd === -1) {
          matchedSlash = false
          firstNonSlashEnd = i + 1
        }
        if (extIdx >= 0) {
          if (code === suffix.charCodeAt(extIdx)) {
            if (--extIdx === -1) {
              end = i
            }
          } else {
            extIdx = -1
            end = firstNonSlashEnd
          }
        }
      }
    }

    if (start === end) end = firstNonSlashEnd
    else if (end === -1) end = path.length
    return path.substring(start, end)
  }
  for (let i = path.length - 1; i >= start; --i) {
    if (isWindowsPathSeparator(path.charCodeAt(i))) {
      if (!matchedSlash) {
        start = i + 1
        break
      }
    } else if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
  }

  if (end === -1) return ''
  return path.substring(start, end)
}

exports.extname = function extname(path) {
  let start = 0
  let startDot = -1
  let startPart = 0
  let end = -1
  let matchedSlash = true
  let preDotState = 0

  if (
    path.length >= 2 &&
    path.charCodeAt(1) === CHAR_COLON &&
    isWindowsDeviceRoot(path.charCodeAt(0))
  ) {
    start = startPart = 2
  }

  for (let i = path.length - 1; i >= start; --i) {
    const code = path.charCodeAt(i)
    if (isWindowsPathSeparator(code)) {
      if (!matchedSlash) {
        startPart = i + 1
        break
      }
      continue
    }
    if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
    if (code === CHAR_DOT) {
      if (startDot === -1) startDot = i
      else if (preDotState !== 1) preDotState = 1
    } else if (startDot !== -1) {
      preDotState = -1
    }
  }

  if (
    startDot === -1 ||
    end === -1 ||
    preDotState === 0 ||
    (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1)
  ) {
    return ''
  }
  return path.substring(startDot, end)
}
{
  "name": "bare-path",
  "version": "3.0.1",
  "description": "Path manipulation library for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./posix": "./lib/posix.js",
    "./win32": "./lib/win32.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "lib",
    "NOTICE"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-path.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-path/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-path#readme",
  "dependencies": {
    "bare-os": "^3.0.1"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "lunte": "^1.8.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
const b4a = require('b4a')
const stream = require('streamx')
const { ReadableStream, WritableStream } = require('./web')

const defaultEncoding = 'utf8'

module.exports = exports = stream.Stream

exports.pipeline = stream.pipeline

exports.isStream = stream.isStream
exports.isEnding = stream.isEnding
exports.isEnded = stream.isEnded
exports.isFinishing = stream.isFinishing
exports.isFinished = stream.isFinished
exports.isDisturbed = stream.isDisturbed

exports.isErrored = function isErrored(stream) {
  return exports.getStreamError(stream) !== null
}

exports.isReadable = function isReadable(stream) {
  return stream.readable && !stream.destroying && !exports.isEnded(stream)
}

exports.isWritable = function isWritable(stream) {
  return stream.writable && !stream.destroying && !exports.isFinishing(stream)
}

exports.getStreamError = stream.getStreamError

exports.addAbortSignal = function addAbortSignal(signal, stream) {
  function onAbort() {
    stream.destroy(signal.reason)
  }

  if (signal.aborted) onAbort()
  else signal.addEventListener('abort', onAbort)

  return stream
}

exports.Stream = exports

exports.Readable = class Readable extends stream.Readable {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthReadable: null,
      map: null,
      mapReadable: null
    })

    if (this._construct) this._open = this._construct

    if (this._read !== stream.Readable.prototype._read) {
      this._read = read.bind(this, this._read)
    }

    if (this._destroy !== stream.Stream.prototype._destroy) {
      this._destroy = destroy.bind(this, this._destroy)
    }
  }

  get closed() {
    return !exports.isReadable(this)
  }

  get errored() {
    return stream.getStreamError(this)
  }

  push(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    return super.push(chunk)
  }

  unshift(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    super.unshift(chunk)
  }

  static fromWeb(readableStream, opts = {}) {
    const stream = readableStream._stream

    if (opts.encoding) stream.setEncoding(opts.encoding)
    if (opts.signal) exports.addAbortSignal(opts.signal, stream)

    return stream
  }

  static toWeb(readable, opts = {}) {
    return new ReadableStream(readable, opts.strategy)
  }

  async [Symbol.asyncDispose]() {
    if (!this.destroyed) this.destroy()

    await new Promise((resolve) => exports.finished(this, resolve))
  }
}

exports.Writable = class Writable extends stream.Writable {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthWritable,
      map: null,
      mapWritable: null
    })

    if (this._construct) this._open = this._construct

    if (this._write !== stream.Writable.prototype._write) {
      this._write = write.bind(this, this._write)
    }

    if (this._destroy !== stream.Stream.prototype._destroy) {
      this._destroy = destroy.bind(this, this._destroy)
    }
  }

  get closed() {
    return !exports.isWritable(this)
  }

  get errored() {
    return stream.getStreamError(this)
  }

  write(chunk, encoding, cb) {
    if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result = super.write({ chunk, encoding })

    if (cb) stream.Writable.drained(this).then(() => cb(null), cb)

    return result
  }

  end(chunk, encoding, cb) {
    if (typeof chunk === 'function') {
      cb = chunk
      chunk = null
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    } else {
      encoding = 'buffer'
    }

    const result =
      chunk !== undefined && chunk !== null ? super.end({ chunk, encoding }) : super.end()

    if (cb) this.once('finish', () => cb(null))

    return result
  }

  static fromWeb(writableStream, opts = {}) {
    const stream = writableStream._stream

    if (opts.signal) exports.addAbortSignal(opts.signal, stream)

    return stream
  }

  static toWeb(writable) {
    return new WritableStream(writable)
  }

  async [Symbol.asyncDispose]() {
    if (!this.destroyed) this.destroy()

    await new Promise((resolve) => exports.finished(this, resolve))
  }
}

exports.Duplex = class Duplex extends stream.Duplex {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthReadable: null,
      byteLengthWritable,
      map: null,
      mapReadable: null,
      mapWritable: null
    })

    if (this._construct) this._open = this._construct

    if (this._read !== stream.Readable.prototype._read) {
      this._read = read.bind(this, this._read)
    }

    if (this._write !== stream.Duplex.prototype._write) {
      this._write = write.bind(this, this._write)
    }

    if (this._destroy !== stream.Stream.prototype._destroy) {
      this._destroy = destroy.bind(this, this._destroy)
    }
  }

  push(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    return super.push(chunk)
  }

  unshift(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    super.unshift(chunk)
  }

  write(chunk, encoding, cb) {
    if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result = super.write({ chunk, encoding })

    if (cb) stream.Writable.drained(this).then(() => cb(null), cb)

    return result
  }

  end(chunk, encoding, cb) {
    if (typeof chunk === 'function') {
      cb = chunk
      chunk = null
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result =
      chunk !== undefined && chunk !== null ? super.end({ chunk, encoding }) : super.end()

    if (cb) this.once('finish', () => cb(null))

    return result
  }

  static fromWeb({ readable: readableStream, writable: writableStream }, opts) {
    const readable = exports.Readable.fromWeb(readableStream, opts)
    const writable = exports.Writable.fromWeb(writableStream, opts)

    const duplex = new exports.Duplex({
      write(data, encoding, cb) {
        writable.write(data, encoding, cb)
      }
    })

    readable
      .on('data', (data) => duplex.push(data))
      .on('end', () => duplex.push(null))
      .on('error', (err) => duplex.destroy(err))

    writable.on('finish', () => duplex.end()).on('error', (err) => duplex.destroy(err))

    return duplex
  }

  static toWeb(duplex) {
    const readableStream = exports.Readable.toWeb(duplex)
    const writableStream = exports.Writable.toWeb(duplex)

    return { readable: readableStream, writable: writableStream }
  }
}

class DuplexSide extends exports.Duplex {
  constructor(opts) {
    super(opts)

    this._otherSide = null
    this._cb = null
  }

  _read() {
    const cb = this._cb
    if (!cb) return

    this._cb = null
    cb()
  }

  _write(chunk, encoding, cb) {
    this._otherSide.push(chunk, encoding)
    this._otherSide._cb = cb
  }

  _final(cb) {
    this._otherSide.on('end', cb)
    this._otherSide.push(null)
  }
}

exports.duplexPair = function duplexPair(opts) {
  const sideA = new DuplexSide(opts)
  const sideB = new DuplexSide(opts)

  sideA._otherSide = sideB
  sideB._otherSide = sideA

  return [sideA, sideB]
}

exports.Transform = class Transform extends stream.Transform {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthReadable: null,
      byteLengthWritable,
      map: null,
      mapReadable: null,
      mapWritable: null
    })

    if (this._transform !== stream.Transform.prototype._transform) {
      this._transform = transform.bind(this, this._transform)
    } else {
      this._transform = passthrough
    }
  }

  push(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    return super.push(chunk)
  }

  unshift(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    super.unshift(chunk)
  }

  write(chunk, encoding, cb) {
    if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result = super.write({ chunk, encoding })

    if (cb) stream.Writable.drained(this).then(() => cb(null), cb)

    return result
  }

  end(chunk, encoding, cb) {
    if (typeof chunk === 'function') {
      cb = chunk
      chunk = null
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result =
      chunk !== undefined && chunk !== null ? super.end({ chunk, encoding }) : super.end()

    if (cb) this.once('finish', () => cb(null))

    return result
  }
}

exports.PassThrough = class PassThrough extends exports.Transform {}

exports.finished = function finished(stream, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (!opts) opts = {}

  const { cleanup = false } = opts

  const done = () => {
    cb(exports.getStreamError(stream, { all: true }))

    if (cleanup) detach()
  }

  const detach = () => {
    stream.off('close', done)
    stream.off('error', noop)
  }

  if (stream.destroyed) {
    done()
  } else {
    stream.on('close', done)
    stream.on('error', noop)
  }

  return detach
}

function read(read, cb) {
  read.call(this, 65536)

  cb(null)
}

function write(write, data, cb) {
  write.call(this, data.chunk, data.encoding, cb)
}

function transform(transform, data, cb) {
  transform.call(this, data.chunk, data.encoding, cb)
}

function destroy(destroy, cb) {
  destroy.call(this, exports.getStreamError(this), cb)
}

function passthrough(data, cb) {
  cb(null, data.chunk)
}

function byteLengthWritable(data) {
  return data.chunk.byteLength
}

function noop() {}
{
  "name": "bare-stream",
  "version": "2.13.3",
  "description": "Streaming data for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./promises": "./promises.js",
    "./web": {
      "types": "./web.d.ts",
      "default": "./web.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "promises.js",
    "web.js",
    "web.d.ts",
    "global.js",
    "global.d.ts"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-stream.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-stream/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-stream#readme",
  "dependencies": {
    "b4a": "^1.8.1",
    "streamx": "^2.25.0",
    "teex": "^1.0.1"
  },
  "devDependencies": {
    "bare-abort-controller": "^1.1.0",
    "bare-buffer": "^3.0.0",
    "bare-events": "^2.5.4",
    "brittle": "^3.5.2",
    "lunte": "^1.6.0",
    "prettier": "^3.3.3",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "bare-abort-controller": "*",
    "bare-buffer": "*",
    "bare-events": "*"
  },
  "peerDependenciesMeta": {
    "bare-abort-controller": {
      "optional": true
    },
    "bare-buffer": {
      "optional": true
    },
    "bare-events": {
      "optional": true
    }
  }
}
const { Readable, Writable, Transform, getStreamError, isStreamx, isDisturbed } = require('streamx')
const tee = require('teex')

const readableKind = Symbol.for('bare.stream.readable.kind')
const writableKind = Symbol.for('bare.stream.writable.kind')
const transformKind = Symbol.for('bare.stream.transform.kind')

// https://streams.spec.whatwg.org/#readablestreamdefaultreader
exports.ReadableStreamDefaultReader = class ReadableStreamDefaultReader {
  constructor(stream) {
    this._stream = stream
    this._stream._stream.once('close', onclose).once('error', onerror)

    const closed = Promise.withResolvers()

    // Avoid unhandled exceptions
    closed.promise.catch(noop)

    this._closed = closed

    function onclose() {
      closed.resolve()
    }

    function onerror(err) {
      closed.reject(err)
    }
  }

  get closed() {
    return this._closed.promise
  }

  read() {
    const stream = this._stream._stream

    return new Promise((resolve, reject) => {
      const err = getStreamError(stream)

      if (err) return reject(err)

      if (stream.destroyed) {
        return resolve({ value: undefined, done: true })
      }

      const value = stream.read()

      if (value !== null) {
        return resolve({ value, done: false })
      }

      stream.once('readable', onreadable).once('close', onclose).once('error', onerror)

      function onreadable() {
        const value = stream.read()

        ondone(null, value === null ? { value: undefined, done: true } : { value, done: false })
      }

      function onclose() {
        ondone(null, { value: undefined, done: true })
      }

      function onerror(err) {
        ondone(err, null)
      }

      function ondone(err, value) {
        stream.off('readable', onreadable).off('close', onclose).off('error', onerror)

        if (err) reject(err)
        else resolve(value)
      }
    })
  }

  releaseLock() {
    this._closed.reject(new TypeError('Reader was released'))
    this._stream._releaseLock()
    this._stream = null
  }

  cancel(reason = new TypeError('Stream was cancelled')) {
    const stream = this._stream._stream

    if (stream.destroyed) return Promise.resolve()

    return new Promise((resolve) =>
      stream.once('close', resolve).once('error', noop).destroy(reason)
    )
  }
}

// https://streams.spec.whatwg.org/#readablestreamdefaultcontroller
exports.ReadableStreamDefaultController = class ReadableStreamDefaultController {
  constructor(stream) {
    this._stream = stream
  }

  get desiredSize() {
    const stream = this._stream._stream

    return stream._readableState.highWaterMark - stream._readableState.buffered
  }

  enqueue(data) {
    this._stream._stream.push(data)
  }

  close() {
    this._stream._stream.push(null)
  }

  error(err) {
    this._stream._stream.destroy(err)
  }
}

// https://streams.spec.whatwg.org/#readablestream
class ReadableStream {
  static get [readableKind]() {
    return 0 // Compatibility version
  }

  static from(iterable) {
    return new ReadableStream(Readable.from(iterable))
  }

  constructor(underlyingSource = {}, queuingStrategy) {
    if (isStreamx(underlyingSource)) {
      this._stream = underlyingSource
    } else {
      if (queuingStrategy === undefined) {
        queuingStrategy = new exports.CountQueuingStrategy()
      }

      const { start, pull, cancel } = underlyingSource
      const { highWaterMark = 1, size = defaultSize } = queuingStrategy

      this._stream = new Readable({ highWaterMark, byteLength: size })

      const controller = new exports.ReadableStreamDefaultController(this)

      try {
        let starting = Promise.resolve()

        if (start) starting = forwardError(start.call(this, controller), controller)

        if (pull) {
          this._stream._read = this._read.bind(this, starting, pull.bind(this, controller))
        }

        if (cancel) {
          this._stream.once('error', cancel.bind(this))
        }
      } catch (err) {
        controller.error(err)
      }
    }

    this._reader = null
  }

  get [readableKind]() {
    return ReadableStream[readableKind]
  }

  get locked() {
    return this._reader !== null
  }

  getReader() {
    if (this.locked) throw new TypeError('Stream is locked')

    this._reader = new exports.ReadableStreamDefaultReader(this)

    return this._reader
  }

  cancel(reason = new TypeError('Stream was cancelled')) {
    const stream = this._stream

    if (stream.destroyed) return Promise.resolve()

    if (this.locked) return Promise.reject(new TypeError('Stream is locked'))

    return new Promise((resolve) =>
      stream.once('close', resolve).once('error', noop).destroy(reason)
    )
  }

  tee() {
    const [a, b] = tee(this._stream)

    return [new ReadableStream(a), new ReadableStream(b)]
  }

  pipeTo(destination) {
    return new Promise((resolve, reject) =>
      this._stream.pipe(destination._stream, (err) => {
        err ? reject(err) : resolve()
      })
    )
  }

  [Symbol.asyncIterator]() {
    return this._stream[Symbol.asyncIterator]()
  }

  _releaseLock() {
    this._reader = null
  }

  async _read(starting, pull, cb) {
    await starting

    let err = null
    try {
      await pull()
    } catch (e) {
      err = e
    }
    cb(err)
  }
}

function defaultSize() {
  return 1
}

exports.ReadableStream = ReadableStream

// https://streams.spec.whatwg.org/#countqueuingstrategy
exports.CountQueuingStrategy = class CountQueuingStrategy {
  constructor(opts = {}) {
    const { highWaterMark = 1 } = opts

    this.highWaterMark = highWaterMark
  }

  size(chunk) {
    return 1
  }
}

// https://streams.spec.whatwg.org/#bytelengthqueuingstrategy
exports.ByteLengthQueuingStrategy = class ByteLengthQueuingStrategy {
  constructor(opts = {}) {
    const { highWaterMark = 16384 } = opts

    this.highWaterMark = highWaterMark
  }

  size(chunk) {
    return chunk.byteLength
  }
}

exports.isReadableStream = function isReadableStream(value) {
  if (value instanceof ReadableStream) return true

  return (
    typeof value === 'object' &&
    value !== null &&
    value[readableKind] === ReadableStream[readableKind]
  )
}

// https://streams.spec.whatwg.org/#readablestream-errored
exports.isReadableStreamErrored = function isReadableStreamErrored(stream) {
  return getStreamError(stream._stream) !== null
}

// https://streams.spec.whatwg.org/#is-readable-stream-disturbed
exports.isReadableStreamDisturbed = function isReadableStreamDisturbed(stream) {
  return isDisturbed(stream._stream)
}

// https://streams.spec.whatwg.org/#writablestreamdefaultwriter
exports.WritableStreamDefaultWriter = class WritableStreamDefaultWriter {
  constructor(stream) {
    this._stream = stream
    this._stream._stream.once('close', onclose).once('error', onerror)

    const closed = Promise.withResolvers()

    // Avoid unhandled exceptions
    closed.promise.catch(noop)

    this._closed = closed

    function onclose() {
      closed.resolve()
    }

    function onerror(err) {
      closed.reject(err)
    }
  }

  get desiredSize() {
    const stream = this._stream._stream

    return stream._writableState.highWaterMark - stream._writableState.buffered
  }

  get closed() {
    return this._closed.promise
  }

  get ready() {
    const stream = this._stream._stream

    if (getStreamError(stream)) return Promise.reject()

    return Writable.drained(stream).then()
  }

  async write(chunk) {
    const stream = this._stream._stream

    let err = getStreamError(stream)
    if (err) return Promise.reject(err)

    stream.write(chunk)

    await Writable.drained(stream)

    err = getStreamError(stream)
    if (err) return Promise.reject(err)
  }

  releaseLock() {
    this._closed.reject(new TypeError('Writer was released'))
    this._stream._releaseLock()
    this._stream = null
  }

  close() {
    const stream = this._stream._stream

    if (stream.destroyed) return Promise.resolve()

    return new Promise((resolve) => stream.once('close', resolve).end())
  }

  abort(reason = new TypeError('Stream was aborted')) {
    const stream = this._stream._stream

    if (stream.destroyed) return Promise.resolve()

    return new Promise((resolve) => stream.once('close', resolve).destroy(reason))
  }
}

// https://streams.spec.whatwg.org/#writablestreamdefaultcontroller
exports.WritableStreamDefaultController = class WritableStreamDefaultController {
  constructor(stream) {
    this._stream = stream
  }

  error(err) {
    this._stream._stream.destroy(err)
  }
}

// https://streams.spec.whatwg.org/#writablestream
class WritableStream {
  static get [writableKind]() {
    return 0 // Compatibility version
  }

  constructor(underlyingSink = {}, queuingStrategy = {}) {
    if (isStreamx(underlyingSink)) {
      this._stream = underlyingSink
    } else {
      if (queuingStrategy === undefined) {
        queuingStrategy = new exports.CountQueuingStrategy()
      }

      const { start, write, close, abort } = underlyingSink
      const { highWaterMark = 1, size = defaultSize } = queuingStrategy

      this._stream = new Writable({ highWaterMark, byteLength: size })

      const controller = new exports.WritableStreamDefaultController(this)

      this._controller = controller

      try {
        let starting = Promise.resolve()

        if (start) starting = forwardError(start.call(this, controller), controller)

        if (write) {
          this._stream._write = this._write.bind(this, starting, write.bind(this))
        }

        if (close) {
          this._stream._destroy = this._destroy.bind(this, close.call(this))
        }

        if (abort) {
          this._stream.once('error', abort.bind(this))
        }
      } catch (err) {
        controller.error(err)
      }
    }

    this._writer = null
  }

  get [writableKind]() {
    return WritableStream[writableKind]
  }

  get locked() {
    return this._writer !== null
  }

  getWriter() {
    if (this.locked) throw new TypeError('Stream is locked')

    this._writer = new exports.WritableStreamDefaultWriter(this)

    return this._writer
  }

  abort(reason = new TypeError('Stream was aborted')) {
    if (this._stream.destroyed) return Promise.resolve()

    if (this.locked) return Promise.reject(new TypeError('Stream is locked'))

    return new Promise((resolve) => this._stream.once('close', resolve).destroy(reason))
  }

  close() {
    if (this._stream.destroyed) return Promise.resolve()

    if (this.locked) return Promise.reject(new TypeError('Stream is locked'))

    return new Promise((resolve) => this._stream.once('close', resolve).end())
  }

  _releaseLock() {
    this._writer = null
  }

  async _write(starting, write, data, cb) {
    await starting

    let err = null
    try {
      await write(data, this._controller)
    } catch (e) {
      err = e
    }
    cb(err)
  }

  async _destroy(closing, cb) {
    let err = null
    try {
      await closing
    } catch (e) {
      err = e
    }
    cb(err)
  }
}

exports.WritableStream = WritableStream

exports.isWritableStream = function isWritableStream(value) {
  if (value instanceof WritableStream) return true

  return (
    typeof value === 'object' &&
    value !== null &&
    value[writableKind] === WritableStream[writableKind]
  )
}

// https://streams.spec.whatwg.org/#transformstreamdefaultcontroller
exports.TransformStreamDefaultController = class TransformStreamDefaultController {
  constructor(stream) {
    this._stream = stream
  }

  get desiredSize() {
    const stream = this._stream._stream

    return stream._readableState.highWaterMark - stream._readableState.buffered
  }

  enqueue(data) {
    this._stream._stream.push(data)
  }

  error(err) {
    this._stream._stream.destroy(err)
  }

  terminate() {
    const stream = this._stream._stream

    stream.push(null)
    stream.destroy(new TypeError('Stream has been terminated'))
  }
}

// https://streams.spec.whatwg.org/#transformstream
class TransformStream {
  static get [transformKind]() {
    return 0 // Compatibility version
  }

  constructor(transformer = {}, writableStrategy = {}, readableStrategy = {}) {
    if (isStreamx(transformer)) {
      this._stream = transformer
    } else {
      const { start, transform, flush } = transformer

      this._stream = new Transform({ ...writableStrategy, ...readableStrategy })

      const controller = new exports.TransformStreamDefaultController(this)

      this._controller = controller

      try {
        let starting = Promise.resolve()

        if (start) starting = forwardError(start.call(this, controller), controller)

        if (transform) {
          this._stream._transform = this._transform.bind(this, starting, transform.bind(this))
        }

        if (flush) {
          this._stream._flush = this._flush.bind(this, flush.call(this, this._controller))
        }
      } catch (err) {
        controller.error(err)
      }
    }

    this._writable = new WritableStream(this._stream)
    this._readable = new ReadableStream(this._stream)
  }

  get [transformKind]() {
    return TransformStream[transformKind]
  }

  get writable() {
    return this._writable
  }

  get readable() {
    return this._readable
  }

  async _transform(starting, transform, data, cb) {
    await starting

    let err = null
    try {
      await transform(data, this._controller)
    } catch (e) {
      err = e
    }
    cb(err)
  }

  async _flush(flush, cb) {
    let err = null
    try {
      await flush
    } catch (e) {
      err = e
    }
    cb(err)
  }
}

exports.TransformStream = TransformStream

exports.isTransformStream = function isTransformStream(value) {
  if (value instanceof TransformStream) return true

  return (
    typeof value === 'object' &&
    value !== null &&
    value[transformKind] === TransformStream[transformKind]
  )
}

async function forwardError(promise, controller) {
  try {
    await promise
  } catch (err) {
    controller.error(err)
  }
}

function noop() {}
module.exports = require.addon()
const binding = require('./binding')

const t = binding.constants

class Type {
  constructor(type) {
    this._type = type
  }

  isUndefined() {
    return this._type === t.UNDEFINED
  }

  isNull() {
    return this._type === t.NULL
  }

  isBoolean() {
    return this._type === t.BOOLEAN
  }

  isNumber() {
    return (this._type & 0xff) === t.NUMBER
  }

  isInt32() {
    return (this._type & (0xff | t.INT32)) === (t.NUMBER | t.INT32)
  }

  isUint32() {
    return (this._type & (0xff | t.UINT32)) === (t.NUMBER | t.UINT32)
  }

  isString() {
    return this._type === t.STRING
  }

  isSymbol() {
    return this._type === t.SYMBOL
  }

  isObject() {
    return (this._type & 0xff) === t.OBJECT
  }

  isArray() {
    return this._type === (t.OBJECT | t.ARRAY)
  }

  isArguments() {
    return this._type === (t.OBJECT | t.ARGUMENTS)
  }

  isDate() {
    return this._type === (t.OBJECT | t.DATE)
  }

  isRegExp() {
    return this._type === (t.OBJECT | t.REGEXP)
  }

  isError() {
    return this._type === (t.OBJECT | t.ERROR)
  }

  isPromise() {
    return this._type === (t.OBJECT | t.PROMISE)
  }

  isProxy() {
    return this._type === (t.OBJECT | t.PROXY)
  }

  isGenerator() {
    return this._type === (t.OBJECT | t.GENERATOR)
  }

  isMap() {
    return this._type === (t.OBJECT | t.MAP)
  }

  isSet() {
    return this._type === (t.OBJECT | t.SET)
  }

  isWeakMap() {
    return this._type === (t.OBJECT | t.WEAK_MAP)
  }

  isWeakSet() {
    return this._type === (t.OBJECT | t.WEAK_SET)
  }

  isWeakRef() {
    return this._type === (t.OBJECT | t.WEAK_REF)
  }

  isArrayBuffer() {
    return this._type === (t.OBJECT | t.ARRAYBUFFER)
  }

  isSharedArrayBuffer() {
    return this._type === (t.OBJECT | t.SHAREDARRAYBUFFER)
  }

  isTypedArray() {
    return (this._type & 0xffff) === (t.OBJECT | t.TYPEDARRAY)
  }

  isInt8Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT8ARRAY)
  }

  isUint8Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT8ARRAY)
  }

  isUint8ClampedArray() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT8CLAMPEDARRAY)
  }

  isInt16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT16ARRAY)
  }

  isUint16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT16ARRAY)
  }

  isInt32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT32ARRAY)
  }

  isUint32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT32ARRAY)
  }

  isFloat16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT16ARRAY)
  }

  isFloat32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT32ARRAY)
  }

  isFloat64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT64ARRAY)
  }

  isBigInt64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.BIGINT64ARRAY)
  }

  isBigUint64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.BIGUINT64ARRAY)
  }

  isDataView() {
    return this._type === (t.OBJECT | t.DATAVIEW)
  }

  isModuleNamespace() {
    return this._type === (t.OBJECT | t.MODULE_NAMESPACE)
  }

  isFunction() {
    return (this._type & 0xff) === t.FUNCTION
  }

  isAsyncFunction() {
    return (
      (this._type & (0xff | t.ASYNC_FUNCTION)) ===
      (t.FUNCTION | t.ASYNC_FUNCTION)
    )
  }

  isGeneratorFunction() {
    return (
      (this._type & (0xff | t.GENERATOR_FUNCTION)) ===
      (t.FUNCTION | t.GENERATOR_FUNCTION)
    )
  }

  isExternal() {
    return this._type === t.EXTERNAL
  }

  isBigInt() {
    return this._type === t.BIGINT
  }
}

module.exports = exports = function type(value) {
  switch (typeof value) {
    case 'undefined':
      return new Type(t.UNDEFINED)
    case 'boolean':
      return new Type(t.BOOLEAN)
    case 'number':
      return new Type(
        Number.isSafeInteger(value) ? binding.type(value) : t.NUMBER
      )
    case 'string':
      return new Type(t.STRING)
    case 'symbol':
      return new Type(t.SYMBOL)
    case 'object':
      return new Type(value === null ? t.NULL : binding.type(value))
    case 'function':
      return new Type(binding.type(value))
    case 'bigint':
      return new Type(t.BIGINT)
  }
}

exports.createTag = function createTag(...components) {
  const tag = new Uint32Array(4)
  for (let i = 0; i < 4; i++) tag[i] = components[i] || 0
  return tag
}

exports.addTag = function addTag(object, tag) {
  binding.addTag(object, tag)
}

exports.checkTag = function checkTag(object, tag) {
  return binding.checkTag(object, tag)
}
{
  "name": "bare-type",
  "version": "1.1.0",
  "description": "Cross-realm type predicates for Bare",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-type.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-type/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-type#readme",
  "engines": {
    "bare": ">=1.2.0"
  },
  "devDependencies": {
    "brittle": "^3.4.0",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
module.exports = require.addon()
const path = require('bare-path')
const binding = require('./binding')
const errors = require('./lib/errors')
const URLSearchParams = require('./lib/url-search-params')

const kind = Symbol.for('bare.url.kind')

const isWindows = Bare.platform === 'win32'

class URL {
  static get [kind]() {
    return 0 // Compatibility version
  }

  constructor(input, base, opts = {}) {
    if (arguments.length === 0) throw errors.INVALID_URL()

    input = String(input)

    if (base !== undefined) base = String(base)

    this._components = new Uint32Array(8)

    this._parse(input, base, opts.throw !== false)

    if (this._href) this._params = new URLSearchParams(this.search, this)
  }

  get [kind]() {
    return URL[kind]
  }

  // https://url.spec.whatwg.org/#dom-url-href

  get href() {
    return this._href
  }

  set href(value) {
    this._update(value)

    this._params._parse(this.search)
  }

  // https://url.spec.whatwg.org/#dom-url-protocol

  get protocol() {
    return this._slice(0, this._components[0]) + ':'
  }

  set protocol(value) {
    this._update(this._replace(value.replace(/:+$/, ''), 0, this._components[0]))
  }

  // https://url.spec.whatwg.org/#dom-url-username

  get username() {
    return this._slice(this._components[0] + 3 /* :// */, this._components[1])
  }

  set username(value) {
    if (cannotHaveCredentialsOrPort(this)) {
      return
    }

    if (this.username === '') value += '@'

    this._update(this._replace(value, this._components[0] + 3 /* :// */, this._components[1]))
  }

  // https://url.spec.whatwg.org/#dom-url-password

  get password() {
    return this._href.slice(this._components[1] + 1 /* : */, this._components[2] - 1 /* @ */)
  }

  set password(value) {
    if (cannotHaveCredentialsOrPort(this)) {
      return
    }

    let start = this._components[1] + 1 /* : */
    let end = this._components[2] - 1 /* @ */

    if (this.password === '') {
      value = ':' + value
      start--
    }

    if (this.username === '') {
      value += '@'
      end++
    }

    this._update(this._replace(value, start, end))
  }

  // https://url.spec.whatwg.org/#dom-url-host

  get host() {
    return this._slice(this._components[2], this._components[5])
  }

  set host(value) {
    if (hasOpaquePath(this)) {
      return
    }

    this._update(
      this._replace(value, this._components[2], this._components[value.includes(':') ? 5 : 3])
    )
  }

  // https://url.spec.whatwg.org/#dom-url-hostname

  get hostname() {
    return this._slice(this._components[2], this._components[3])
  }

  set hostname(value) {
    if (hasOpaquePath(this)) {
      return
    }

    this._update(this._replace(value, this._components[2], this._components[3]))
  }

  // https://url.spec.whatwg.org/#dom-url-port

  get port() {
    return this._slice(this._components[3] + 1 /* : */, this._components[5])
  }

  set port(value) {
    if (cannotHaveCredentialsOrPort(this)) {
      return
    }

    let start = this._components[3] + 1 /* : */

    if (this.port === '') {
      value = ':' + value
      start--
    }

    this._update(this._replace(value, start, this._components[5]))
  }

  // https://url.spec.whatwg.org/#dom-url-pathname

  get pathname() {
    return this._slice(this._components[5], this._components[6] - 1 /* ? */)
  }

  set pathname(value) {
    if (hasOpaquePath(this)) {
      return
    }

    if (value[0] !== '/' && value[0] !== '\\') {
      value = '/' + value
    }

    this._update(this._replace(value, this._components[5], this._components[6] - 1 /* ? */))
  }

  // https://url.spec.whatwg.org/#dom-url-search

  get search() {
    return this._slice(this._components[6] - 1 /* ? */, this._components[7] - 1 /* # */)
  }

  set search(value) {
    if (value && value[0] !== '?') value = '?' + value

    this._update(
      this._replace(value, this._components[6] - 1 /* ? */, this._components[7] - 1 /* # */)
    )

    this._params._parse(this.search)
  }

  // https://url.spec.whatwg.org/#dom-url-searchparams

  get searchParams() {
    return this._params
  }

  // https://url.spec.whatwg.org/#dom-url-hash

  get hash() {
    return this._slice(this._components[7] - 1 /* # */)
  }

  set hash(value) {
    if (value && value[0] !== '#') value = '#' + value

    this._update(this._replace(value, this._components[7] - 1 /* # */))
  }

  toString() {
    return this._href
  }

  toJSON() {
    return this._href
  }

  [Symbol.for('bare.inspect')]() {
    return {
      __proto__: { constructor: URL },

      href: this.href,
      protocol: this.protocol,
      username: this.username,
      password: this.password,
      host: this.host,
      hostname: this.hostname,
      port: this.port,
      pathname: this.pathname,
      search: this.search,
      searchParams: this.searchParams,
      hash: this.hash
    }
  }

  _slice(start, end = this._href.length) {
    return this._href.slice(start, end)
  }

  _replace(replacement, start, end = this._href.length) {
    return this._slice(0, start) + replacement + this._slice(end)
  }

  _parse(input, base, shouldThrow) {
    try {
      this._href = binding.parse(
        String(input),
        base ? String(base) : null,
        this._components,
        shouldThrow
      )
    } catch (err) {
      if (err instanceof TypeError) throw err

      throw errors.INVALID_URL(`Invalid URL '${input}'`, input)
    }
  }

  _update(input) {
    try {
      this._parse(input, null, true)
    } catch (err) {
      if (err instanceof TypeError) throw err
    }
  }
}

module.exports = exports = URL

// https://url.spec.whatwg.org/#url-opaque-path
function hasOpaquePath(url) {
  return url.pathname[0] !== '/'
}

// https://url.spec.whatwg.org/#cannot-have-a-username-password-port
function cannotHaveCredentialsOrPort(url) {
  return url.hostname === '' || url.protocol === 'file:'
}

exports.URL = URL
exports.URLSearchParams = URLSearchParams

exports.errors = errors

exports.isURL = function isURL(value) {
  if (value instanceof URL) return true

  return typeof value === 'object' && value !== null && value[kind] === URL[kind]
}

exports.isURLSearchParams = URLSearchParams.isURLSearchParams

// https://url.spec.whatwg.org/#dom-url-parse
exports.parse = function parse(input, base) {
  const url = new URL(input, base, { throw: false })
  return url._href ? url : null
}

// https://url.spec.whatwg.org/#dom-url-canparse
exports.canParse = function canParse(input, base) {
  return binding.canParse(String(input), base ? String(base) : null)
}

exports.fileURLToPath = function fileURLToPath(url) {
  if (typeof url === 'string') {
    url = new URL(url)
  }

  if (url.protocol !== 'file:') {
    throw errors.INVALID_URL_SCHEME('The URL must use the file: protocol')
  }

  if (isWindows) {
    if (/%2f|%5c/i.test(url.pathname)) {
      throw errors.INVALID_FILE_URL_PATH(
        'The file: URL path must not include encoded \\ or / characters'
      )
    }
  } else {
    if (url.hostname) {
      throw errors.INVALID_FILE_URL_HOST("The file: URL host must be 'localhost' or empty")
    }

    if (/%2f/i.test(url.pathname)) {
      throw errors.INVALID_FILE_URL_PATH('The file: URL path must not include encoded / characters')
    }
  }

  if (/%00/i.test(url.pathname)) {
    throw errors.INVALID_FILE_URL_PATH('The file: URL path must not include encoded NUL characters')
  }

  const pathname = path.normalize(decodeURIComponent(url.pathname))

  if (isWindows) {
    if (url.hostname) return '\\\\' + url.hostname + pathname

    const letter = pathname.charCodeAt(1) | 0x20

    if (letter < 0x61 /* a */ || letter > 0x7a /* z */ || pathname.charCodeAt(2) !== 0x3a /* : */) {
      throw errors.INVALID_FILE_URL_PATH('The file: URL path must be absolute')
    }

    return pathname.slice(1)
  }

  return pathname
}

exports.pathToFileURL = function pathToFileURL(pathname) {
  let resolved = path.resolve(pathname)

  if (pathname[pathname.length - 1] === '/') {
    resolved += '/'
  } else if (isWindows && pathname[pathname.length - 1] === '\\') {
    resolved += '\\'
  }

  resolved = resolved
    .replaceAll('%', '%25') // Must be first
    .replaceAll('#', '%23')
    .replaceAll('?', '%3f')
    .replaceAll('\n', '%0a')
    .replaceAll('\r', '%0d')
    .replaceAll('\t', '%09')

  if (!isWindows) {
    resolved = resolved.replaceAll('\\', '%5c')
  }

  return new URL('file:' + resolved)
}

exports.format = function format(parts) {
  const { protocol, auth, host, hostname, port, pathname, search, query, hash, slashes } = parts

  let result = ''

  if (typeof protocol === 'string') {
    result += protocol

    if (protocol[protocol.length - 1] !== ':') {
      result += ':'
    }

    if (slashes === true || /https?|ftp|gopher|file/.test(protocol)) {
      result += '//'
    }
  }

  if (typeof auth === 'string') {
    if (host || hostname) result += auth + '@'
  }

  if (typeof host === 'string') result += host
  else {
    result += hostname

    if (port) result += ':' + port
  }

  if (typeof pathname === 'string' && pathname !== '') {
    if (pathname[0] !== '/') result += '/'
    result += pathname
  }

  if (typeof search === 'string') {
    if (search[0] !== '?') result += '?'
    result += search
  } else if (typeof query === 'object' && query !== null) {
    result += '?' + new URLSearchParams(query)
  }

  if (typeof hash === 'string') {
    if (hash[0] !== '#') result += '#'
    result += hash
  }

  return result
}
module.exports = class URLError extends Error {
  constructor(msg, fn = URLError, code = fn.name) {
    super(`${code}: ${msg}`)

    this.code = code

    if (Error.captureStackTrace) Error.captureStackTrace(this, fn)
  }

  get name() {
    return 'URLError'
  }

  static INVALID_URL(msg, input) {
    const err = new URLError(msg, URLError.INVALID_URL)

    err.input = input

    return err
  }

  static INVALID_URL_SCHEME(msg = 'Invalid URL') {
    return new URLError(msg, URLError.INVALID_URL_SCHEME)
  }

  static INVALID_FILE_URL_HOST(msg = 'Invalid file: URL host') {
    return new URLError(msg, URLError.INVALID_FILE_URL_HOST)
  }

  static INVALID_FILE_URL_PATH(msg = 'Invalid file: URL path') {
    return new URLError(msg, URLError.INVALID_FILE_URL_PATH)
  }
}
const kind = Symbol.for('bare.url.search-params.kind')

class URLSearchParams {
  static _urls = new WeakMap()

  static get [kind]() {
    return 0 // Compatibility version
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-urlsearchparams
  constructor(init, url = null) {
    this._params = new Map()

    if (url) URLSearchParams._urls.set(this, url)

    if (typeof init === 'string') {
      this._parse(init)
    } else if (init) {
      for (const [name, value] of typeof init[Symbol.iterator] === 'function'
        ? init
        : Object.entries(init)) {
        this.append(name, value)
      }
    }
  }

  get [kind]() {
    return URLSearchParams[kind]
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-size
  get size() {
    return this._params.length
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-append
  append(name, value = null) {
    if (value === null) return

    let list = this._params.get(name)

    if (list === undefined) {
      list = []
      this._params.set(name, list)
    }

    list.push(value)

    this._update()
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-delete
  delete(name, value = null) {
    if (value === null) this._params.delete(name)
    else {
      let list = this._params.get(name)

      if (list === undefined) return

      list = list.filter((found) => found !== value)

      if (list.length === 0) this._params.delete(name)
      else this._params.set(name, list)
    }

    this._update()
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-get
  get(name) {
    const list = this._params.get(name)

    if (list === undefined) return null

    return list[0]
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-getall
  getAll(name) {
    const list = this._params.get(name)

    if (list === undefined) return []

    return Array.from(list)
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-has
  has(name, value = null) {
    const list = this._params.get(name)

    if (list === undefined) return false

    if (value === null) return true

    return list.includes(value)
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-set
  set(name, value = null) {
    if (value === null) this._params.delete(name)
    else this._params.set(name, [value])

    this._update()
  }

  toString() {
    return this._serialize()
  }

  toJSON() {
    return [...this]
  }

  *[Symbol.iterator]() {
    for (const [name, values] of this._params) {
      for (const value of values) yield [name, value]
    }
  }

  [Symbol.for('bare.inspect')]() {
    const object = {
      __proto__: { constructor: URLSearchParams }
    }

    for (const [name, values] of this._params) {
      if (values.length === 1) object[name] = values[0]
      else object[name] = values
    }

    return object
  }

  // https://url.spec.whatwg.org/#concept-urlsearchparams-update
  _update() {
    const url = URLSearchParams._urls.get(this)

    if (url === undefined) return

    url.search = this._serialize()
  }

  // https://url.spec.whatwg.org/#concept-urlencoded-parser
  _parse(input) {
    if (input[0] === '?') input = input.substring(1)

    this._params = new Map()

    for (let sequence of input.split('&')) {
      if (sequence.length === 0) continue

      sequence = sequence.replace(/\+/g, ' ')

      let i = sequence.indexOf('=')
      if (i === -1) i = sequence.length

      const name = decodeURIComponent(sequence.substring(0, i))
      const value = decodeURIComponent(sequence.substring(i + 1, sequence.length))

      let list = this._params.get(name)

      if (list === undefined) {
        list = []
        this._params.set(name, list)
      }

      list.push(value)
    }
  }

  // https://url.spec.whatwg.org/#concept-urlencoded-serializer
  _serialize() {
    let output = ''

    for (let [name, values] of this._params) {
      name = encodeURIComponent(name)

      for (const value of values) {
        if (output) output += '&'

        output += name + '=' + encodeURIComponent(value)
      }
    }

    return output
  }
}

module.exports = exports = URLSearchParams

exports.isURLSearchParams = function isURLSearchParams(value) {
  if (value instanceof URLSearchParams) return true

  return typeof value === 'object' && value !== null && value[kind] === URLSearchParams[kind]
}
{
  "name": "bare-url",
  "version": "2.4.5",
  "description": "WHATWG URL implementation for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "global.js",
    "global.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-url.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-url/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-url",
  "dependencies": {
    "bare-path": "^3.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "cmake-bare": "^1.1.6",
    "cmake-fetch": "^1.0.0",
    "lunte": "^1.6.0",
    "prettier": "^3.3.3",
    "prettier-config-holepunch": "^2.0.0"
  }
}
const FACTOR = new Uint16Array(8)

function factor4096 (i, n) {
  while (n > 0) {
    const f = i & 4095
    FACTOR[--n] = f
    i = (i - f) / 4096
  }
  return FACTOR
}

module.exports = class BigSparseArray {
  constructor () {
    this.tiny = new TinyArray()
    this.maxLength = 4096
    this.factor = 1
  }

  set (index, val) {
    if (val !== undefined) {
      while (index >= this.maxLength) {
        this.maxLength *= 4096
        this.factor++
        if (!this.tiny.isEmptyish()) {
          const t = new TinyArray()
          t.set(0, this.tiny)
          this.tiny = t
        }
      }
    }

    const f = factor4096(index, this.factor)
    const last = this.factor - 1

    let tiny = this.tiny
    for (let i = 0; i < last; i++) {
      const next = tiny.get(f[i])
      if (next === undefined) {
        if (val === undefined) return
        tiny = tiny.set(f[i], new TinyArray())
      } else {
        tiny = next
      }
    }

    return tiny.set(f[last], val)
  }

  get (index) {
    if (index >= this.maxLength) return

    const f = factor4096(index, this.factor)
    const last = this.factor - 1

    let tiny = this.tiny
    for (let i = 0; i < last; i++) {
      tiny = tiny.get(f[i])
      if (tiny === undefined) return
    }

    return tiny.get(f[last])
  }
}

class TinyArray {
  constructor () {
    this.s = 0
    this.b = new Array(1)
    this.f = new Uint16Array(1)
  }

  isEmptyish () {
    return this.b.length === 1 && this.b[0] === undefined
  }

  get (i) {
    if (this.s === 12) return this.b[i]
    const f = i >>> this.s
    const r = i & (this.b.length - 1)
    return this.f[r] === f ? this.b[r] : undefined
  }

  set (i, v) {
    while (this.s !== 12) {
      const f = i >>> this.s
      const r = i & (this.b.length - 1)
      const o = this.b[r]

      if (o === undefined || f === this.f[r]) {
        this.b[r] = v
        this.f[r] = f
        return v
      }

      this.grow()
    }

    this.b[i] = v
    return v
  }

  grow () {
    const os = this.s
    const ob = this.b
    const of = this.f

    this.s += 4
    this.b = new Array(this.b.length << 4)
    this.f = this.s === 12 ? null : new Uint8Array(this.b.length)

    const m = this.b.length - 1

    for (let or = 0; or < ob.length; or++) {
      if (ob[or] === undefined) continue

      const i = of[or] << os | or
      const f = i >>> this.s
      const r = i & m

      this.b[r] = ob[or]
      if (this.s !== 12) this.f[r] = f
    }
  }
}
{
  "name": "big-sparse-array",
  "version": "1.0.3",
  "description": "A sparse array optimised for low memory whilst still being fast",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "brittle": "^3.1.1",
    "standard": "^16.0.3"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/big-sparse-array.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/big-sparse-array/issues"
  },
  "homepage": "https://github.com/mafintosh/big-sparse-array"
}
import { encode, encodeInto, objectToTokens, rfc8949EncodeOptions } from './lib/encode.js'
import { decode, decodeFirst, Tokeniser, tokensToObject } from './lib/decode.js'
import { Tagged } from './lib/tagged.js'
import { Token, Type } from './lib/token.js'

/**
 * Export the types that were present in the original manual cborg.d.ts
 * @typedef {import('./interface.js').TagDecodeControl} TagDecodeControl
 * @typedef {import('./interface.js').TagDecoder} TagDecoder
 * There was originally just `TypeEncoder` so don't break types by renaming or not exporting
 * @typedef {import('./interface.js').OptionalTypeEncoder} TypeEncoder
 * @typedef {import('./interface.js').DecodeOptions} DecodeOptions
 * @typedef {import('./interface.js').EncodeOptions} EncodeOptions
 */

export {
  decode,
  decodeFirst,
  Tokeniser as Tokenizer,
  tokensToObject,
  encode,
  encodeInto,
  objectToTokens,
  rfc8949EncodeOptions,
  Tagged,
  Token,
  Type
}
/* globals BigInt */

import { Token, Type } from './token.js'
import { decodeErrPrefix, assertEnoughData } from './common.js'

export const uintBoundaries = [24, 256, 65536, 4294967296, BigInt('18446744073709551616')]

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number}
 */
export function readUint8 (data, offset, options) {
  assertEnoughData(data, offset, 1)
  const value = data[offset]
  if (options.strict === true && value < uintBoundaries[0]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  return value
}

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number}
 */
export function readUint16 (data, offset, options) {
  assertEnoughData(data, offset, 2)
  const value = (data[offset] << 8) | data[offset + 1]
  if (options.strict === true && value < uintBoundaries[1]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  return value
}

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number}
 */
export function readUint32 (data, offset, options) {
  assertEnoughData(data, offset, 4)
  const value = (data[offset] * 16777216 /* 2 ** 24 */) + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]
  if (options.strict === true && value < uintBoundaries[2]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  return value
}

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number|bigint}
 */
export function readUint64 (data, offset, options) {
  // assume BigInt, convert back to Number if within safe range
  assertEnoughData(data, offset, 8)
  const hi = (data[offset] * 16777216 /* 2 ** 24 */) + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]
  const lo = (data[offset + 4] * 16777216 /* 2 ** 24 */) + (data[offset + 5] << 16) + (data[offset + 6] << 8) + data[offset + 7]
  const value = (BigInt(hi) << BigInt(32)) + BigInt(lo)
  if (options.strict === true && value < uintBoundaries[3]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  if (value <= Number.MAX_SAFE_INTEGER) {
    return Number(value)
  }
  if (options.allowBigInt === true) {
    return value
  }
  throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`)
}

/* not required thanks to quick[] list
const oneByteTokens = new Array(24).fill(0).map((v, i) => new Token(Type.uint, i, 1))
export function decodeUintCompact (data, pos, minor, options) {
  return oneByteTokens[minor]
}
*/

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint8 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint8(data, pos + 1, options), 2)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint16 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint16(data, pos + 1, options), 3)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint32 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint32(data, pos + 1, options), 5)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint64 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint64(data, pos + 1, options), 9)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeUint (writer, token) {
  return encodeUintValue(writer, 0, token.value)
}

/**
 * @param {ByteWriter} writer
 * @param {number} major
 * @param {number|bigint} uint
 */
export function encodeUintValue (writer, major, uint) {
  if (uint < uintBoundaries[0]) {
    const nuint = Number(uint)
    // pack into one byte, minor=0, additional=value
    writer.push([major | nuint])
  } else if (uint < uintBoundaries[1]) {
    const nuint = Number(uint)
    // pack into two byte, minor=0, additional=24
    writer.push([major | 24, nuint])
  } else if (uint < uintBoundaries[2]) {
    const nuint = Number(uint)
    // pack into three byte, minor=0, additional=25
    writer.push([major | 25, nuint >>> 8, nuint & 0xff])
  } else if (uint < uintBoundaries[3]) {
    const nuint = Number(uint)
    // pack into five byte, minor=0, additional=26
    writer.push([major | 26, (nuint >>> 24) & 0xff, (nuint >>> 16) & 0xff, (nuint >>> 8) & 0xff, nuint & 0xff])
  } else {
    const buint = BigInt(uint)
    if (buint < uintBoundaries[4]) {
      // pack into nine byte, minor=0, additional=27
      const set = [major | 27, 0, 0, 0, 0, 0, 0, 0]
      // simulate bitwise above 32 bits
      let lo = Number(buint & BigInt(0xffffffff))
      let hi = Number(buint >> BigInt(32) & BigInt(0xffffffff))
      set[8] = lo & 0xff
      lo = lo >> 8
      set[7] = lo & 0xff
      lo = lo >> 8
      set[6] = lo & 0xff
      lo = lo >> 8
      set[5] = lo & 0xff
      set[4] = hi & 0xff
      hi = hi >> 8
      set[3] = hi & 0xff
      hi = hi >> 8
      set[2] = hi & 0xff
      hi = hi >> 8
      set[1] = hi & 0xff
      writer.push(set)
    } else {
      throw new Error(`${decodeErrPrefix} encountered BigInt larger than allowable range`)
    }
  }
}

/**
 * @param {Token} token
 * @returns {number}
 */
encodeUint.encodedSize = function encodedSize (token) {
  return encodeUintValue.encodedSize(token.value)
}

/**
 * @param {number} uint
 * @returns {number}
 */
encodeUintValue.encodedSize = function encodedSize (uint) {
  if (uint < uintBoundaries[0]) {
    return 1
  }
  if (uint < uintBoundaries[1]) {
    return 2
  }
  if (uint < uintBoundaries[2]) {
    return 3
  }
  if (uint < uintBoundaries[3]) {
    return 5
  }
  return 9
}

/**
 * @param {Token} tok1
 * @param {Token} tok2
 * @returns {number}
 */
encodeUint.compareTokens = function compareTokens (tok1, tok2) {
  return tok1.value < tok2.value ? -1 : tok1.value > tok2.value ? 1 : 0
}
/* eslint-env es2020 */

import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import { decodeErrPrefix } from './common.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint8 (data, pos, _minor, options) {
  return new Token(Type.negint, -1 - uint.readUint8(data, pos + 1, options), 2)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint16 (data, pos, _minor, options) {
  return new Token(Type.negint, -1 - uint.readUint16(data, pos + 1, options), 3)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint32 (data, pos, _minor, options) {
  return new Token(Type.negint, -1 - uint.readUint32(data, pos + 1, options), 5)
}

const neg1b = BigInt(-1)
const pos1b = BigInt(1)

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint64 (data, pos, _minor, options) {
  const int = uint.readUint64(data, pos + 1, options)
  if (typeof int !== 'bigint') {
    const value = -1 - int
    if (value >= Number.MIN_SAFE_INTEGER) {
      return new Token(Type.negint, value, 9)
    }
  }
  if (options.allowBigInt !== true) {
    throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`)
  }
  return new Token(Type.negint, neg1b - BigInt(int), 9)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeNegint (writer, token) {
  const negint = token.value
  const unsigned = (typeof negint === 'bigint' ? (negint * neg1b - pos1b) : (negint * -1 - 1))
  uint.encodeUintValue(writer, token.type.majorEncoded, unsigned)
}

/**
 * @param {Token} token
 * @returns {number}
 */
encodeNegint.encodedSize = function encodedSize (token) {
  const negint = token.value
  const unsigned = (typeof negint === 'bigint' ? (negint * neg1b - pos1b) : (negint * -1 - 1))
  // handled by quickEncode, we shouldn't get here but it's included for completeness
  if (unsigned < uint.uintBoundaries[0]) {
    return 1
  }
  if (unsigned < uint.uintBoundaries[1]) {
    return 2
  }
  if (unsigned < uint.uintBoundaries[2]) {
    return 3
  }
  if (unsigned < uint.uintBoundaries[3]) {
    return 5
  }
  return 9
}

/**
 * @param {Token} tok1
 * @param {Token} tok2
 * @returns {number}
 */
encodeNegint.compareTokens = function compareTokens (tok1, tok2) {
  // opposite of the uint comparison since we store the uint version in bytes
  return tok1.value < tok2.value ? 1 : tok1.value > tok2.value ? -1 : 0
}
import { Token, Type } from './token.js'
import { assertEnoughData, decodeErrPrefix } from './common.js'
import * as uint from './0uint.js'
import { compare, fromString } from './byte-utils.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} prefix
 * @param {number} length
 * @returns {Token}
 */
function toToken (data, pos, prefix, length) {
  assertEnoughData(data, pos, prefix + length)
  const buf = data.slice(pos + prefix, pos + prefix + length)
  return new Token(Type.bytes, buf, prefix + length)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeBytesCompact (data, pos, minor, _options) {
  return toToken(data, pos, 1, minor)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer bytes lengths not supported`)
  }
  return toToken(data, pos, 9, l)
}

/**
 * `encodedBytes` allows for caching when we do a byte version of a string
 * for key sorting purposes
 * @param {Token} token
 * @returns {Uint8Array}
 */
function tokenBytes (token) {
  if (token.encodedBytes === undefined) {
    token.encodedBytes = Type.equals(token.type, Type.string) ? fromString(token.value) : token.value
  }
  // @ts-ignore c'mon
  return token.encodedBytes
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeBytes (writer, token) {
  const bytes = tokenBytes(token)
  uint.encodeUintValue(writer, token.type.majorEncoded, bytes.length)
  writer.push(bytes)
}

/**
 * @param {Token} token
 * @returns {number}
 */
encodeBytes.encodedSize = function encodedSize (token) {
  const bytes = tokenBytes(token)
  return uint.encodeUintValue.encodedSize(bytes.length) + bytes.length
}

/**
 * @param {Token} tok1
 * @param {Token} tok2
 * @returns {number}
 */
encodeBytes.compareTokens = function compareTokens (tok1, tok2) {
  return compareBytes(tokenBytes(tok1), tokenBytes(tok2))
}

/**
 * @param {Uint8Array} b1
 * @param {Uint8Array} b2
 * @returns {number}
 */
export function compareBytes (b1, b2) {
  return b1.length < b2.length ? -1 : b1.length > b2.length ? 1 : compare(b1, b2)
}
import { Token, Type } from './token.js'
import { assertEnoughData, decodeErrPrefix } from './common.js'
import * as uint from './0uint.js'
import { encodeBytes } from './2bytes.js'

const textDecoder = new TextDecoder()

// Threshold for ASCII fast-path vs TextDecoder. Short ASCII strings (common for
// map keys) are faster to decode with a simple loop than TextDecoder overhead.
const ASCII_THRESHOLD = 32

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * Decode UTF-8 bytes to string. For short ASCII strings (common case for map keys),
 * a simple loop is faster than TextDecoder.
 * @param {Uint8Array} bytes
 * @param {number} start
 * @param {number} end
 * @returns {string}
 */
function toStr (bytes, start, end) {
  const len = end - start
  if (len < ASCII_THRESHOLD) {
    let str = ''
    for (let i = start; i < end; i++) {
      const c = bytes[i]
      if (c & 0x80) { // non-ASCII, fall back to TextDecoder
        return textDecoder.decode(bytes.subarray(start, end))
      }
      str += String.fromCharCode(c)
    }
    return str
  }
  return textDecoder.decode(bytes.subarray(start, end))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} prefix
 * @param {number} length
 * @param {DecodeOptions} options
 * @returns {Token}
 */
function toToken (data, pos, prefix, length, options) {
  const totLength = prefix + length
  assertEnoughData(data, pos, totLength)
  const tok = new Token(Type.string, toStr(data, pos + prefix, pos + totLength), totLength)
  if (options.retainStringBytes === true) {
    tok.byteValue = data.slice(pos + prefix, pos + totLength)
  }
  return tok
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeStringCompact (data, pos, minor, options) {
  return toToken(data, pos, 1, minor, options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options), options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options), options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options), options)
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer string lengths not supported`)
  }
  return toToken(data, pos, 9, l, options)
}

export const encodeString = encodeBytes
import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import { decodeErrPrefix } from './common.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} prefix
 * @param {number} length
 * @returns {Token}
 */
function toToken (_data, _pos, prefix, length) {
  return new Token(Type.array, length, prefix)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeArrayCompact (data, pos, minor, _options) {
  return toToken(data, pos, 1, minor)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer array lengths not supported`)
  }
  return toToken(data, pos, 9, l)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArrayIndefinite (data, pos, _minor, options) {
  if (options.allowIndefinite === false) {
    throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)
  }
  return toToken(data, pos, 1, Infinity)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeArray (writer, token) {
  uint.encodeUintValue(writer, Type.array.majorEncoded, token.value)
}

// using an array as a map key, are you sure about this? we can only sort
// by map length here, it's up to the encoder to decide to look deeper
encodeArray.compareTokens = uint.encodeUint.compareTokens

/**
 * @param {Token} token
 * @returns {number}
 */
encodeArray.encodedSize = function encodedSize (token) {
  return uint.encodeUintValue.encodedSize(token.value)
}
import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import { decodeErrPrefix } from './common.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} prefix
 * @param {number} length
 * @returns {Token}
 */
function toToken (_data, _pos, prefix, length) {
  return new Token(Type.map, length, prefix)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeMapCompact (data, pos, minor, _options) {
  return toToken(data, pos, 1, minor)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer map lengths not supported`)
  }
  return toToken(data, pos, 9, l)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMapIndefinite (data, pos, _minor, options) {
  if (options.allowIndefinite === false) {
    throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)
  }
  return toToken(data, pos, 1, Infinity)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeMap (writer, token) {
  uint.encodeUintValue(writer, Type.map.majorEncoded, token.value)
}

// using a map as a map key, are you sure about this? we can only sort
// by map length here, it's up to the encoder to decide to look deeper
encodeMap.compareTokens = uint.encodeUint.compareTokens

/**
 * @param {Token} token
 * @returns {number}
 */
encodeMap.encodedSize = function encodedSize (token) {
  return uint.encodeUintValue.encodedSize(token.value)
}
import { Token, Type } from './token.js'
import * as uint from './0uint.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeTagCompact (_data, _pos, minor, _options) {
  return new Token(Type.tag, minor, 1)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag8 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint8(data, pos + 1, options), 2)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag16 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint16(data, pos + 1, options), 3)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag32 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint32(data, pos + 1, options), 5)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag64 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint64(data, pos + 1, options), 9)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeTag (writer, token) {
  uint.encodeUintValue(writer, Type.tag.majorEncoded, token.value)
}

encodeTag.compareTokens = uint.encodeUint.compareTokens

/**
 * @param {Token} token
 * @returns {number}
 */
encodeTag.encodedSize = function encodedSize (token) {
  return uint.encodeUintValue.encodedSize(token.value)
}
// TODO: shift some of the bytes logic to bytes-utils so we can use Buffer
// where possible

import { Token, Type } from './token.js'
import { decodeErrPrefix } from './common.js'
import { encodeUint } from './0uint.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 * @typedef {import('../interface.js').EncodeOptions} EncodeOptions
 */

export const MINOR_FALSE = 20
export const MINOR_TRUE = 21
export const MINOR_NULL = 22
export const MINOR_UNDEFINED = 23

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUndefined (_data, _pos, _minor, options) {
  if (options.allowUndefined === false) {
    throw new Error(`${decodeErrPrefix} undefined values are not supported`)
  } else if (options.coerceUndefinedToNull === true) {
    return new Token(Type.null, null, 1)
  }
  return new Token(Type.undefined, undefined, 1)
}

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBreak (_data, _pos, _minor, options) {
  if (options.allowIndefinite === false) {
    throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)
  }
  return new Token(Type.break, undefined, 1)
}

/**
 * @param {number} value
 * @param {number} bytes
 * @param {DecodeOptions} options
 * @returns {Token}
 */
function createToken (value, bytes, options) {
  if (options) {
    if (options.allowNaN === false && Number.isNaN(value)) {
      throw new Error(`${decodeErrPrefix} NaN values are not supported`)
    }
    if (options.allowInfinity === false && (value === Infinity || value === -Infinity)) {
      throw new Error(`${decodeErrPrefix} Infinity values are not supported`)
    }
  }
  return new Token(Type.float, value, bytes)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeFloat16 (data, pos, _minor, options) {
  return createToken(readFloat16(data, pos + 1), 3, options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeFloat32 (data, pos, _minor, options) {
  return createToken(readFloat32(data, pos + 1), 5, options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeFloat64 (data, pos, _minor, options) {
  return createToken(readFloat64(data, pos + 1), 9, options)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 * @param {EncodeOptions} options
 */
export function encodeFloat (writer, token, options) {
  const float = token.value

  if (float === false) {
    writer.push([Type.float.majorEncoded | MINOR_FALSE])
  } else if (float === true) {
    writer.push([Type.float.majorEncoded | MINOR_TRUE])
  } else if (float === null) {
    writer.push([Type.float.majorEncoded | MINOR_NULL])
  } else if (float === undefined) {
    writer.push([Type.float.majorEncoded | MINOR_UNDEFINED])
  } else {
    let decoded
    let success = false
    if (!options || options.float64 !== true) {
      encodeFloat16(float)
      decoded = readFloat16(ui8a, 1)
      if (float === decoded || Number.isNaN(float)) {
        ui8a[0] = 0xf9
        writer.push(ui8a.slice(0, 3))
        success = true
      } else {
        encodeFloat32(float)
        decoded = readFloat32(ui8a, 1)
        if (float === decoded) {
          ui8a[0] = 0xfa
          writer.push(ui8a.slice(0, 5))
          success = true
        }
      }
    }
    if (!success) {
      encodeFloat64(float)
      decoded = readFloat64(ui8a, 1)
      ui8a[0] = 0xfb
      writer.push(ui8a.slice(0, 9))
    }
  }
}

/**
 * @param {Token} token
 * @param {EncodeOptions} options
 * @returns {number}
 */
encodeFloat.encodedSize = function encodedSize (token, options) {
  const float = token.value

  if (float === false || float === true || float === null || float === undefined) {
    return 1
  }

  if (!options || options.float64 !== true) {
    encodeFloat16(float)
    let decoded = readFloat16(ui8a, 1)
    if (float === decoded || Number.isNaN(float)) {
      return 3
    }
    encodeFloat32(float)
    decoded = readFloat32(ui8a, 1)
    if (float === decoded) {
      return 5
    }
  }
  return 9
}

const buffer = new ArrayBuffer(9)
const dataView = new DataView(buffer, 1)
const ui8a = new Uint8Array(buffer, 0)

/**
 * @param {number} inp
 */
function encodeFloat16 (inp) {
  if (inp === Infinity) {
    dataView.setUint16(0, 0x7c00, false)
  } else if (inp === -Infinity) {
    dataView.setUint16(0, 0xfc00, false)
  } else if (Number.isNaN(inp)) {
    dataView.setUint16(0, 0x7e00, false)
  } else {
    dataView.setFloat32(0, inp)
    const valu32 = dataView.getUint32(0)
    const exponent = (valu32 & 0x7f800000) >> 23
    const mantissa = valu32 & 0x7fffff

    if (exponent === 0xff) {
      // too big, Infinity, but this should be hard (impossible?) to trigger
      dataView.setUint16(0, 0x7c00, false)
    } else if (exponent === 0x00) {
      // 0.0, -0.0 and subnormals, shouldn't be possible to get here because 0.0 should be counted as an int
      // Use valu32 for sign bit since bitwise ops on floats lose -0 sign
      dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | (mantissa >> 13), false)
    } else { // standard numbers
      // chunks of logic here borrowed from https://github.com/PJK/libcbor/blob/c78f437182533e3efa8d963ff4b945bb635c2284/src/cbor/encoding.c#L127
      const logicalExponent = exponent - 127
      // Now we know that 2^exponent <= 0 logically
      if (logicalExponent < -24) {
        /* No unambiguous representation exists, this float is not a half float
          and is too small to be represented using a half, round off to zero.
          Consistent with the reference implementation. */
        // should be difficult (impossible?) to get here in JS
        dataView.setUint16(0, 0)
      } else if (logicalExponent < -14) {
        /* Offset the remaining decimal places by shifting the significand, the
          value is lost. This is an implementation decision that works around the
          absence of standard half-float in the language. */
        dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | /* sign bit */ (1 << (24 + logicalExponent)), false)
      } else {
        dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | ((logicalExponent + 15) << 10) | (mantissa >> 13), false)
      }
    }
  }
}

/**
 * @param {Uint8Array} ui8a
 * @param {number} pos
 * @returns {number}
 */
function readFloat16 (ui8a, pos) {
  if (ui8a.length - pos < 2) {
    throw new Error(`${decodeErrPrefix} not enough data for float16`)
  }

  const half = (ui8a[pos] << 8) + ui8a[pos + 1]
  if (half === 0x7c00) {
    return Infinity
  }
  if (half === 0xfc00) {
    return -Infinity
  }
  if (half === 0x7e00) {
    return NaN
  }
  const exp = (half >> 10) & 0x1f
  const mant = half & 0x3ff
  let val
  if (exp === 0) {
    val = mant * (2 ** -24)
  } else if (exp !== 31) {
    val = (mant + 1024) * (2 ** (exp - 25))
  } else {
    // may not be possible to get here
    val = mant === 0 ? Infinity : NaN
  }
  return (half & 0x8000) ? -val : val
}

/**
 * @param {number} inp
 */
function encodeFloat32 (inp) {
  dataView.setFloat32(0, inp, false)
}

/**
 * @param {Uint8Array} ui8a
 * @param {number} pos
 * @returns {number}
 */
function readFloat32 (ui8a, pos) {
  if (ui8a.length - pos < 4) {
    throw new Error(`${decodeErrPrefix} not enough data for float32`)
  }
  const offset = (ui8a.byteOffset || 0) + pos
  return new DataView(ui8a.buffer, offset, 4).getFloat32(0, false)
}

/**
 * @param {number} inp
 */
function encodeFloat64 (inp) {
  dataView.setFloat64(0, inp, false)
}

/**
 * @param {Uint8Array} ui8a
 * @param {number} pos
 * @returns {number}
 */
function readFloat64 (ui8a, pos) {
  if (ui8a.length - pos < 8) {
    throw new Error(`${decodeErrPrefix} not enough data for float64`)
  }
  const offset = (ui8a.byteOffset || 0) + pos
  return new DataView(ui8a.buffer, offset, 8).getFloat64(0, false)
}

/**
 * @param {Token} _tok1
 * @param {Token} _tok2
 * @returns {number}
 */
encodeFloat.compareTokens = encodeUint.compareTokens
/*
encodeFloat.compareTokens = function compareTokens (_tok1, _tok2) {
  return _tok1
  throw new Error(`${encodeErrPrefix} cannot use floats as map keys`)
}
*/
/**
 * Bl is a list of byte chunks, similar to https://github.com/rvagg/bl but for
 * writing rather than reading.
 * A Bl object accepts set() operations for individual bytes and copyTo() for
 * inserting byte arrays. These write operations don't automatically increment
 * the internal cursor so its "length" won't be changed. Instead, increment()
 * must be called to extend its length to cover the inserted data.
 * The toBytes() call will convert all internal memory to a single Uint8Array of
 * the correct length, truncating any data that is stored but hasn't been
 * included by an increment().
 * get() can retrieve a single byte.
 * All operations (except toBytes()) take an "offset" argument that will perform
 * the write at the offset _from the current cursor_. For most operations this
 * will be `0` to write at the current cursor position but it can be ahead of
 * the current cursor. Negative offsets probably work but are untested.
 */

// TODO: ipjs doesn't support this, only for test files: https://github.com/mikeal/ipjs/blob/master/src/package/testFile.js#L39
import { alloc, concat, slice } from './byte-utils.js'

// the ts-ignores in this file are almost all for the `Uint8Array|number[]` duality that exists
// for perf reasons. Consider better approaches to this or removing it entirely, it is quite
// risky because of some assumptions about small chunks === number[] and everything else === Uint8Array.

const defaultChunkSize = 256

export class Bl {
  /**
   * @param {number} [chunkSize]
   */
  constructor (chunkSize = defaultChunkSize) {
    this.chunkSize = chunkSize
    /** @type {number} */
    this.cursor = 0
    /** @type {number} */
    this.maxCursor = -1
    /** @type {(Uint8Array|number[])[]} */
    this.chunks = []
    // keep the first chunk around if we can to save allocations for future encodes
    /** @type {Uint8Array|number[]|null} */
    this._initReuseChunk = null
  }

  reset () {
    this.cursor = 0
    this.maxCursor = -1
    if (this.chunks.length) {
      this.chunks = []
    }
    if (this._initReuseChunk !== null) {
      this.chunks.push(this._initReuseChunk)
      this.maxCursor = this._initReuseChunk.length - 1
    }
  }

  /**
   * @param {Uint8Array|number[]} bytes
   */
  push (bytes) {
    let topChunk = this.chunks[this.chunks.length - 1]
    const newMax = this.cursor + bytes.length
    if (newMax <= this.maxCursor + 1) {
      // we have at least one chunk and we can fit these bytes into that chunk
      const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1
      // @ts-ignore
      topChunk.set(bytes, chunkPos)
    } else {
      // can't fit it in
      if (topChunk) {
        // trip the last chunk to `cursor` if we need to
        const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1
        if (chunkPos < topChunk.length) {
          // @ts-ignore
          this.chunks[this.chunks.length - 1] = topChunk.subarray(0, chunkPos)
          this.maxCursor = this.cursor - 1
        }
      }
      if (bytes.length < 64 && bytes.length < this.chunkSize) {
        // make a new chunk and copy the new one into it
        topChunk = alloc(this.chunkSize)
        this.chunks.push(topChunk)
        this.maxCursor += topChunk.length
        if (this._initReuseChunk === null) {
          this._initReuseChunk = topChunk
        }
        // @ts-ignore
        topChunk.set(bytes, 0)
      } else {
        // push the new bytes in as its own chunk
        this.chunks.push(bytes)
        this.maxCursor += bytes.length
      }
    }
    this.cursor += bytes.length
  }

  /**
   * @param {boolean} [reset]
   * @returns {Uint8Array}
   */
  toBytes (reset = false) {
    let byts
    if (this.chunks.length === 1) {
      const chunk = this.chunks[0]
      if (reset && this.cursor > chunk.length / 2) {
        // @ts-ignore
        byts = this.cursor === chunk.length ? chunk : chunk.subarray(0, this.cursor)
        this._initReuseChunk = null
        this.chunks = []
      } else {
        // @ts-ignore
        byts = slice(chunk, 0, this.cursor)
      }
    } else {
      // @ts-ignore
      byts = concat(this.chunks, this.cursor)
    }
    if (reset) {
      this.reset()
    }
    return byts
  }
}

/**
 * U8Bl is a buffer list that writes directly to a user-provided Uint8Array.
 * It provides the same interface as Bl but writes to a fixed destination.
 */
export class U8Bl {
  /**
   * @param {Uint8Array} dest
   */
  constructor (dest) {
    this.dest = dest
    /** @type {number} */
    this.cursor = 0
    // chunks is for interface compatibility with Bl - encode.js checks chunks.length
    // as a sanity check for pre-calculated sizes. For U8Bl this is always [dest].
    /** @type {Uint8Array[]} */
    this.chunks = [dest]
  }

  reset () {
    this.cursor = 0
  }

  /**
   * @param {Uint8Array|number[]} bytes
   */
  push (bytes) {
    if (this.cursor + bytes.length > this.dest.length) {
      throw new Error('write out of bounds, destination buffer is too small')
    }
    this.dest.set(bytes, this.cursor)
    this.cursor += bytes.length
  }

  /**
   * @param {boolean} [reset]
   * @returns {Uint8Array}
   */
  toBytes (reset = false) {
    const byts = this.dest.subarray(0, this.cursor)
    if (reset) {
      this.reset()
    }
    return byts
  }
}
// Use Uint8Array directly in the browser, use Buffer in Node.js but don't
// speak its name directly to avoid bundlers pulling in the `Buffer` polyfill

// @ts-ignore
export const useBuffer = globalThis.process &&
  // @ts-ignore
  !globalThis.process.browser &&
  // @ts-ignore
  globalThis.Buffer &&
  // @ts-ignore
  typeof globalThis.Buffer.isBuffer === 'function'

const textEncoder = new TextEncoder()

/**
 * @param {Uint8Array} buf
 * @returns {boolean}
 */
function isBuffer (buf) {
  // @ts-ignore
  return useBuffer && globalThis.Buffer.isBuffer(buf)
}

/**
 * @param {Uint8Array|number[]} buf
 * @returns {Uint8Array}
 */
export function asU8A (buf) {
  if (!(buf instanceof Uint8Array)) {
    return Uint8Array.from(buf)
  }
  return isBuffer(buf) ? new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength) : buf
}

// Threshold for manual UTF-8 encoding vs native methods.
// Node.js Buffer.from: crossover ~24 chars
// Browser TextEncoder: crossover ~200 chars
const FROM_STRING_THRESHOLD_BUFFER = 24
const FROM_STRING_THRESHOLD_TEXTENCODER = 200

export const fromString = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {string} string
     */
    (string) => {
      return string.length >= FROM_STRING_THRESHOLD_BUFFER
        ? // eslint-disable-line operator-linebreak
      // @ts-ignore
        globalThis.Buffer.from(string)
        : utf8ToBytes(string)
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {string} string
     */
    (string) => {
      return string.length >= FROM_STRING_THRESHOLD_TEXTENCODER ? textEncoder.encode(string) : utf8ToBytes(string)
    }

/**
 * Buffer variant not fast enough for what we need
 * @param {number[]} arr
 * @returns {Uint8Array}
 */
export const fromArray = (arr) => {
  return Uint8Array.from(arr)
}

export const slice = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} bytes
     * @param {number} start
     * @param {number} end
     */
    // Buffer.slice() returns a view, not a copy, so we need special handling
    (bytes, start, end) => {
      if (isBuffer(bytes)) {
        return new Uint8Array(bytes.subarray(start, end))
      }
      return bytes.slice(start, end)
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} bytes
     * @param {number} start
     * @param {number} end
     */
    (bytes, start, end) => {
      return bytes.slice(start, end)
    }

export const concat = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array[]} chunks
     * @param {number} length
     * @returns {Uint8Array}
     */
    (chunks, length) => {
      // might get a stray plain Array here
      chunks = chunks.map((c) => c instanceof Uint8Array
        ? c
        : // eslint-disable-line operator-linebreak
        // @ts-ignore
        globalThis.Buffer.from(c))
      // @ts-ignore
      return asU8A(globalThis.Buffer.concat(chunks, length))
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array[]} chunks
     * @param {number} length
     * @returns {Uint8Array}
     */
    (chunks, length) => {
      const out = new Uint8Array(length)
      let off = 0
      for (let b of chunks) {
        if (off + b.length > out.length) {
          // final chunk that's bigger than we need
          b = b.subarray(0, out.length - off)
        }
        out.set(b, off)
        off += b.length
      }
      return out
    }

export const alloc = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {number} size
     * @returns {Uint8Array}
     */
    (size) => {
      // we always write over the contents we expose so this should be safe
      // @ts-ignore
      return globalThis.Buffer.allocUnsafe(size)
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {number} size
     * @returns {Uint8Array}
     */
    (size) => {
      return new Uint8Array(size)
    }

export const toHex = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} d
     * @returns {string}
     */
    (d) => {
      if (typeof d === 'string') {
        return d
      }
      // @ts-ignore
      return globalThis.Buffer.from(toBytes(d)).toString('hex')
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} d
     * @returns {string}
     */
    (d) => {
      if (typeof d === 'string') {
        return d
      }
      // @ts-ignore not smart enough to figure this out
      return Array.prototype.reduce.call(toBytes(d), (p, c) => `${p}${c.toString(16).padStart(2, '0')}`, '')
    }

export const fromHex = useBuffer
  ? // eslint-disable-line operator-linebreak
  /**
   * @param {string|Uint8Array} hex
   * @returns {Uint8Array}
   */
    (hex) => {
      if (hex instanceof Uint8Array) {
        return hex
      }
      // @ts-ignore
      return globalThis.Buffer.from(hex, 'hex')
    }
  : // eslint-disable-line operator-linebreak
  /**
   * @param {string|Uint8Array} hex
   * @returns {Uint8Array}
   */
    (hex) => {
      if (hex instanceof Uint8Array) {
        return hex
      }
      if (!hex.length) {
        return new Uint8Array(0)
      }
      return new Uint8Array(hex.split('')
        .map((/** @type {string} */ c, /** @type {number} */ i, /** @type {string[]} */ d) => i % 2 === 0 ? `0x${c}${d[i + 1]}` : '')
        .filter(Boolean)
        .map((/** @type {string} */ e) => parseInt(e, 16)))
    }

/**
 * @param {Uint8Array|ArrayBuffer|ArrayBufferView} obj
 * @returns {Uint8Array}
 */
function toBytes (obj) {
  if (obj instanceof Uint8Array && obj.constructor.name === 'Uint8Array') {
    return obj
  }
  if (obj instanceof ArrayBuffer) {
    return new Uint8Array(obj)
  }
  if (ArrayBuffer.isView(obj)) {
    return new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength)
  }
  throw new Error('Unknown type, must be binary type')
}

/**
 * @param {Uint8Array} b1
 * @param {Uint8Array} b2
 * @returns {number}
 */
export function compare (b1, b2) {
  if (isBuffer(b1) && isBuffer(b2)) {
    // probably not possible to get here in the current API
    // @ts-ignore Buffer
    return b1.compare(b2)
  }
  for (let i = 0; i < b1.length; i++) {
    if (b1[i] === b2[i]) {
      continue
    }
    return b1[i] < b2[i] ? -1 : 1
  }
  return 0
}

// The below code is taken from https://github.com/google/closure-library/blob/8598d87242af59aac233270742c8984e2b2bdbe0/closure/goog/crypt/crypt.js#L117-L143
// Licensed Apache-2.0.

/**
 * @param {string} str
 * @returns {number[]}
 */
function utf8ToBytes (str) {
  const out = []
  let p = 0
  for (let i = 0; i < str.length; i++) {
    let c = str.charCodeAt(i)
    if (c < 128) {
      out[p++] = c
    } else if (c < 2048) {
      out[p++] = (c >> 6) | 192
      out[p++] = (c & 63) | 128
    } else if (
      ((c & 0xFC00) === 0xD800) && (i + 1) < str.length &&
      ((str.charCodeAt(i + 1) & 0xFC00) === 0xDC00)) {
      // Surrogate Pair
      c = 0x10000 + ((c & 0x03FF) << 10) + (str.charCodeAt(++i) & 0x03FF)
      out[p++] = (c >> 18) | 240
      out[p++] = ((c >> 12) & 63) | 128
      out[p++] = ((c >> 6) & 63) | 128
      out[p++] = (c & 63) | 128
    } else {
      if ((c >= 0xD800) && (c <= 0xDFFF)) {
        c = 0xFFFD // Unpaired Surrogate
      }
      out[p++] = (c >> 12) | 224
      out[p++] = ((c >> 6) & 63) | 128
      out[p++] = (c & 63) | 128
    }
  }
  return out
}

// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
const MAX_ARGUMENTS_LENGTH = 0x1000

/**
 * @param {number[]} codePoints
 * @returns {string}
 */
export function decodeCodePointsArray (codePoints) {
  const len = codePoints.length
  if (len <= MAX_ARGUMENTS_LENGTH) {
    return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  }
  // Decode in chunks to avoid "call stack size exceeded".
  let res = ''
  let i = 0
  while (i < len) {
    res += String.fromCharCode.apply(
      String,
      codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
    )
  }
  return res
}
const decodeErrPrefix = 'CBOR decode error:'
const encodeErrPrefix = 'CBOR encode error:'

const uintMinorPrefixBytes = []
uintMinorPrefixBytes[23] = 1
uintMinorPrefixBytes[24] = 2
uintMinorPrefixBytes[25] = 3
uintMinorPrefixBytes[26] = 5
uintMinorPrefixBytes[27] = 9

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} need
 */
function assertEnoughData (data, pos, need) {
  if (data.length - pos < need) {
    throw new Error(`${decodeErrPrefix} not enough data for type`)
  }
}

export {
  decodeErrPrefix,
  encodeErrPrefix,
  uintMinorPrefixBytes,
  assertEnoughData
}
import { decodeErrPrefix } from './common.js'
import { Type } from './token.js'
import { jump, quick } from './jump.js'
import { asU8A } from './byte-utils.js'

/**
 * @typedef {import('./token.js').Token} Token
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 * @typedef {import('../interface.js').DecodeTokenizer} DecodeTokenizer
 * @typedef {import('../interface.js').TagDecodeControl} TagDecodeControl
 */

const defaultDecodeOptions = {
  strict: false,
  allowIndefinite: true,
  allowUndefined: true,
  allowBigInt: true
}

/**
 * @implements {DecodeTokenizer}
 */
class Tokeniser {
  /**
   * @param {Uint8Array} data
   * @param {DecodeOptions} options
   */
  constructor (data, options = {}) {
    this._pos = 0
    this.data = data
    this.options = options
  }

  pos () {
    return this._pos
  }

  done () {
    return this._pos >= this.data.length
  }

  next () {
    const byt = this.data[this._pos]
    let token = quick[byt]
    if (token === undefined) {
      const decoder = jump[byt]
      // if we're here then there's something wrong with our jump or quick lists!
      if (!decoder) {
        throw new Error(`${decodeErrPrefix} no decoder for major type ${byt >>> 5} (byte 0x${byt.toString(16).padStart(2, '0')})`)
      }
      const minor = byt & 31
      token = decoder(this.data, this._pos, minor, this.options)
    }
    // @ts-ignore we get to assume encodedLength is set (crossing fingers slightly)
    this._pos += token.encodedLength
    return token
  }
}

const DONE = Symbol.for('DONE')
const BREAK = Symbol.for('BREAK')

/**
 * @param {Token} token
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {any|BREAK|DONE}
 */
function tokenToArray (token, tokeniser, options) {
  const arr = []
  for (let i = 0; i < token.value; i++) {
    const value = tokensToObject(tokeniser, options)
    if (value === BREAK) {
      if (token.value === Infinity) {
        // normal end to indefinite length array
        break
      }
      throw new Error(`${decodeErrPrefix} got unexpected break to lengthed array`)
    }
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} found array but not enough entries (got ${i}, expected ${token.value})`)
    }
    arr[i] = value
  }
  return arr
}

/**
 * @param {Token} token
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {any|BREAK|DONE}
 */
function tokenToMap (token, tokeniser, options) {
  const useMaps = options.useMaps === true
  const rejectDuplicateMapKeys = options.rejectDuplicateMapKeys === true
  const obj = useMaps ? undefined : {}
  const m = useMaps ? new Map() : undefined
  for (let i = 0; i < token.value; i++) {
    const key = tokensToObject(tokeniser, options)
    if (key === BREAK) {
      if (token.value === Infinity) {
        // normal end to indefinite length map
        break
      }
      throw new Error(`${decodeErrPrefix} got unexpected break to lengthed map`)
    }
    if (key === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no key], expected ${token.value})`)
    }
    if (!useMaps && typeof key !== 'string') {
      throw new Error(`${decodeErrPrefix} non-string keys not supported (got ${typeof key})`)
    }
    if (rejectDuplicateMapKeys) {
      // @ts-ignore
      if ((useMaps && m.has(key)) || (!useMaps && Object.hasOwn(obj, key))) {
        throw new Error(`${decodeErrPrefix} found repeat map key "${key}"`)
      }
    }
    const value = tokensToObject(tokeniser, options)
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no value], expected ${token.value})`)
    }
    if (useMaps) {
      // @ts-ignore TODO reconsider this .. maybe needs to be strict about key types
      m.set(key, value)
    } else {
      // @ts-ignore TODO reconsider this .. maybe needs to be strict about key types
      obj[key] = value
    }
  }
  // @ts-ignore c'mon man
  return useMaps ? m : obj
}

/**
 * Generator that yields [key, value] entries from a CBOR map token.
 * Used by tag decoders that need to preserve key types (e.g., Tag 259 Map).
 * @param {Token} token - The map token
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {Generator<[any, any], void, unknown>}
 */
function * tokenToMapEntries (token, tokeniser, options) {
  for (let i = 0; i < token.value; i++) {
    const key = tokensToObject(tokeniser, options)
    if (key === BREAK) {
      if (token.value === Infinity) {
        // normal end to indefinite length map
        break
      }
      throw new Error(`${decodeErrPrefix} got unexpected break to lengthed map`)
    }
    if (key === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no key], expected ${token.value})`)
    }
    const value = tokensToObject(tokeniser, options)
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no value], expected ${token.value})`)
    }
    yield [key, value]
  }
}

/**
 * Creates a TagDecodeControl object for tag decoders.
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {TagDecodeControl}
 */
function createTagDecodeControl (tokeniser, options) {
  let called = false

  /**
   * @type {TagDecodeControl}
   */
  const decode = function () {
    if (called) {
      throw new Error(`${decodeErrPrefix} tag decode() may only be called once`)
    }
    called = true
    const value = tokensToObject(tokeniser, options)
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} tag content missing`)
    }
    if (value === BREAK) {
      throw new Error(`${decodeErrPrefix} got unexpected break in tag content`)
    }
    return value
  }

  decode.entries = function () {
    if (called) {
      throw new Error(`${decodeErrPrefix} tag decode() may only be called once`)
    }
    called = true

    // Get the next token and ensure it's a map
    const token = tokeniser.next()
    if (!Type.equals(token.type, Type.map)) {
      throw new Error(`${decodeErrPrefix} entries() requires map content, got ${token.type.name}`)
    }

    // Collect all entries into an array (ensures full content consumption)
    const entries = []
    for (const entry of tokenToMapEntries(token, tokeniser, options)) {
      entries.push(entry)
    }
    return entries
  }

  // For internal tracking
  Object.defineProperty(decode, '_called', {
    get () { return called },
    enumerable: false
  })

  return decode
}

/**
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {any|BREAK|DONE}
 */
function tokensToObject (tokeniser, options) {
  // should we support array as an argument?
  // check for tokenIter[Symbol.iterator] and replace tokenIter with what that returns?
  if (tokeniser.done()) {
    return DONE
  }

  const token = tokeniser.next()

  if (Type.equals(token.type, Type.break)) {
    return BREAK
  }

  if (token.type.terminal) {
    return token.value
  }

  if (Type.equals(token.type, Type.array)) {
    return tokenToArray(token, tokeniser, options)
  }

  if (Type.equals(token.type, Type.map)) {
    return tokenToMap(token, tokeniser, options)
  }

  if (Type.equals(token.type, Type.tag)) {
    if (options.tags && typeof options.tags[token.value] === 'function') {
      const decodeControl = createTagDecodeControl(tokeniser, options)
      const result = options.tags[token.value](decodeControl)
      if (!decodeControl._called) {
        throw new Error(`${decodeErrPrefix} tag decoder must call decode() or entries()`)
      }
      return result
    }
    throw new Error(`${decodeErrPrefix} tag not supported (${token.value})`)
  }
  throw new Error('unsupported')
}

/**
 * @param {Uint8Array} data
 * @param {DecodeOptions} [options]
 * @returns {[any, Uint8Array]}
 */
function decodeFirst (data, options) {
  if (!(data instanceof Uint8Array)) {
    throw new Error(`${decodeErrPrefix} data to decode must be a Uint8Array`)
  }
  options = Object.assign({}, defaultDecodeOptions, options)
  // Convert Buffer to plain Uint8Array for faster slicing in decode path
  const u8aData = asU8A(data)
  const tokeniser = options.tokenizer || new Tokeniser(u8aData, options)
  const decoded = tokensToObject(tokeniser, options)
  if (decoded === DONE) {
    throw new Error(`${decodeErrPrefix} did not find any content to decode`)
  }
  if (decoded === BREAK) {
    throw new Error(`${decodeErrPrefix} got unexpected break`)
  }
  return [decoded, data.subarray(tokeniser.pos())]
}

/**
 * @param {Uint8Array} data
 * @param {DecodeOptions} [options]
 * @returns {any}
 */
function decode (data, options) {
  const [decoded, remainder] = decodeFirst(data, options)
  if (remainder.length > 0) {
    throw new Error(`${decodeErrPrefix} too many terminals, data makes no sense`)
  }
  return decoded
}

export { Tokeniser, tokensToObject, decode, decodeFirst }
import { is } from './is.js'
import { Token, Type } from './token.js'
import { Bl, U8Bl } from './bl.js'
import { encodeErrPrefix } from './common.js'
import { quickEncodeToken } from './jump.js'
import { asU8A, compare, fromString } from './byte-utils.js'

import { encodeUint, encodeUintValue } from './0uint.js'
import { encodeNegint } from './1negint.js'
import { encodeBytes } from './2bytes.js'
import { encodeString } from './3string.js'
import { encodeArray } from './4array.js'
import { encodeMap } from './5map.js'
import { encodeTag } from './6tag.js'
import { encodeFloat, MINOR_FALSE, MINOR_TRUE, MINOR_NULL, MINOR_UNDEFINED } from './7float.js'

/**
 * @typedef {import('../interface.js').EncodeOptions} EncodeOptions
 * @typedef {import('../interface.js').OptionalTypeEncoder} OptionalTypeEncoder
 * @typedef {import('../interface.js').Reference} Reference
 * @typedef {import('../interface.js').StrictTypeEncoder} StrictTypeEncoder
 * @typedef {import('../interface.js').TokenTypeEncoder} TokenTypeEncoder
 * @typedef {import('../interface.js').TokenOrNestedTokens} TokenOrNestedTokens
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 */

/** @type {EncodeOptions} */
const defaultEncodeOptions = {
  float64: false,
  mapSorter,
  quickEncodeToken
}

/** @type {EncodeOptions} */
export const rfc8949EncodeOptions = Object.freeze({
  mapSorter: rfc8949MapSorter,
  quickEncodeToken
})

/** @returns {TokenTypeEncoder[]} */
export function makeCborEncoders () {
  const encoders = []
  encoders[Type.uint.major] = encodeUint
  encoders[Type.negint.major] = encodeNegint
  encoders[Type.bytes.major] = encodeBytes
  encoders[Type.string.major] = encodeString
  encoders[Type.array.major] = encodeArray
  encoders[Type.map.major] = encodeMap
  encoders[Type.tag.major] = encodeTag
  encoders[Type.float.major] = encodeFloat
  return encoders
}

const cborEncoders = makeCborEncoders()

const defaultWriter = new Bl()

/** @implements {Reference} */
class Ref {
  /**
   * @param {object|any[]} obj
   * @param {Reference|undefined} parent
   */
  constructor (obj, parent) {
    this.obj = obj
    this.parent = parent
  }

  /**
   * @param {object|any[]} obj
   * @returns {boolean}
   */
  includes (obj) {
    /** @type {Reference|undefined} */
    let p = this
    do {
      if (p.obj === obj) {
        return true
      }
    } while (p = p.parent) // eslint-disable-line
    return false
  }

  /**
   * @param {Reference|undefined} stack
   * @param {object|any[]} obj
   * @returns {Reference}
   */
  static createCheck (stack, obj) {
    if (stack && stack.includes(obj)) {
      throw new Error(`${encodeErrPrefix} object contains circular references`)
    }
    return new Ref(obj, stack)
  }
}

const simpleTokens = {
  null: new Token(Type.null, null),
  undefined: new Token(Type.undefined, undefined),
  true: new Token(Type.true, true),
  false: new Token(Type.false, false),
  emptyArray: new Token(Type.array, 0),
  emptyMap: new Token(Type.map, 0)
}

/** @type {{[typeName: string]: StrictTypeEncoder}} */
const typeEncoders = {
  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  number (obj, _typ, _options, _refStack) {
    if (!Number.isInteger(obj) || !Number.isSafeInteger(obj)) {
      return new Token(Type.float, obj)
    } else if (obj >= 0) {
      return new Token(Type.uint, obj)
    } else {
      return new Token(Type.negint, obj)
    }
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  bigint (obj, _typ, _options, _refStack) {
    if (obj >= BigInt(0)) {
      return new Token(Type.uint, obj)
    } else {
      return new Token(Type.negint, obj)
    }
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  Uint8Array (obj, _typ, _options, _refStack) {
    return new Token(Type.bytes, obj)
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  string (obj, _typ, _options, _refStack) {
    return new Token(Type.string, obj)
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  boolean (obj, _typ, _options, _refStack) {
    return obj ? simpleTokens.true : simpleTokens.false
  },

  /**
   * @param {any} _obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  null (_obj, _typ, _options, _refStack) {
    return simpleTokens.null
  },

  /**
   * @param {any} _obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  undefined (_obj, _typ, _options, _refStack) {
    return simpleTokens.undefined
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  ArrayBuffer (obj, _typ, _options, _refStack) {
    return new Token(Type.bytes, new Uint8Array(obj))
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  DataView (obj, _typ, _options, _refStack) {
    return new Token(Type.bytes, new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength))
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} options
   * @param {Reference} [refStack]
   * @returns {TokenOrNestedTokens}
   */
  Array (obj, _typ, options, refStack) {
    if (!obj.length) {
      if (options.addBreakTokens === true) {
        return [simpleTokens.emptyArray, new Token(Type.break)]
      }
      return simpleTokens.emptyArray
    }
    refStack = Ref.createCheck(refStack, obj)
    const entries = []
    let i = 0
    for (const e of obj) {
      entries[i++] = objectToTokens(e, options, refStack)
    }
    if (options.addBreakTokens) {
      return [new Token(Type.array, obj.length), entries, new Token(Type.break)]
    }
    return [new Token(Type.array, obj.length), entries]
  },

  /**
   * @param {any} obj
   * @param {string} typ
   * @param {EncodeOptions} options
   * @param {Reference} [refStack]
   * @returns {TokenOrNestedTokens}
   */
  Object (obj, typ, options, refStack) {
    // could be an Object or a Map
    const isMap = typ !== 'Object'
    // it's slightly quicker to use Object.keys() than Object.entries()
    const keys = isMap ? obj.keys() : Object.keys(obj)
    const maxLength = isMap ? obj.size : keys.length

    /** @type {undefined | [TokenOrNestedTokens, TokenOrNestedTokens][]} */
    let entries

    if (maxLength) {
      // Pre-allocate the array with the expected size
      entries = new Array(maxLength)
      refStack = Ref.createCheck(refStack, obj)
      const skipUndefined = !isMap && options.ignoreUndefinedProperties

      let i = 0
      for (const key of keys) {
        const value = isMap ? obj.get(key) : obj[key]
        if (skipUndefined && value === undefined) {
          continue
        }
        entries[i++] = [
          objectToTokens(key, options, refStack),
          objectToTokens(value, options, refStack)
        ]
      }

      // Truncate only if properties were skipped
      if (i < maxLength) {
        entries.length = i
      }
    }

    if (!entries?.length) {
      if (options.addBreakTokens === true) {
        return [simpleTokens.emptyMap, new Token(Type.break)]
      }
      return simpleTokens.emptyMap
    }

    sortMapEntries(entries, options)
    if (options.addBreakTokens) {
      return [new Token(Type.map, entries.length), entries, new Token(Type.break)]
    }
    return [new Token(Type.map, entries.length), entries]
  },

  /**
   * Encode a `Tagged` wrapper as a CBOR tag header followed by the encoded
   * form of the wrapped value. The value is recursively tokenised through
   * `objectToTokens()` so any registered `typeEncoders` apply to it.
   *
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} options
   * @param {Reference} [refStack]
   * @returns {TokenOrNestedTokens}
   */
  Tagged (obj, _typ, options, refStack) {
    return [
      new Token(Type.tag, obj.tag),
      objectToTokens(obj.value, options, refStack)
    ]
  }
}

typeEncoders.Map = typeEncoders.Object
typeEncoders.Buffer = typeEncoders.Uint8Array
for (const typ of 'Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64'.split(' ')) {
  typeEncoders[`${typ}Array`] = typeEncoders.DataView
}

/**
 * @param {any} obj
 * @param {EncodeOptions} [options]
 * @param {Reference} [refStack]
 * @returns {TokenOrNestedTokens}
 */
function objectToTokens (obj, options = {}, refStack) {
  const typ = is(obj)
  const customTypeEncoder = (options && options.typeEncoders && /** @type {OptionalTypeEncoder} */ options.typeEncoders[typ]) || typeEncoders[typ]
  if (typeof customTypeEncoder === 'function') {
    const tokens = customTypeEncoder(obj, typ, options, refStack)
    if (tokens != null) {
      return tokens
    }
  }
  const typeEncoder = typeEncoders[typ]
  if (!typeEncoder) {
    throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`)
  }
  return typeEncoder(obj, typ, options, refStack)
}

/*
CBOR key sorting is a mess.

The canonicalisation recommendation from https://tools.ietf.org/html/rfc7049#section-3.9
includes the wording:

> The keys in every map must be sorted lowest value to highest.
> Sorting is performed on the bytes of the representation of the key
> data items without paying attention to the 3/5 bit splitting for
> major types.
> ...
>  *  If two keys have different lengths, the shorter one sorts
      earlier;
>  *  If two keys have the same length, the one with the lower value
      in (byte-wise) lexical order sorts earlier.

1. It is not clear what "bytes of the representation of the key" means: is it
   the CBOR representation, or the binary representation of the object itself?
   Consider the int and uint difference here.
2. It is not clear what "without paying attention to" means: do we include it
   and compare on that? Or do we omit the special prefix byte, (mostly) treating
   the key in its plain binary representation form.

The FIDO 2.0: Client To Authenticator Protocol spec takes the original CBOR
wording and clarifies it according to their understanding.
https://fidoalliance.org/specs/fido-v2.0-rd-20170927/fido-client-to-authenticator-protocol-v2.0-rd-20170927.html#message-encoding

> The keys in every map must be sorted lowest value to highest. Sorting is
> performed on the bytes of the representation of the key data items without
> paying attention to the 3/5 bit splitting for major types. The sorting rules
> are:
>  * If the major types are different, the one with the lower value in numerical
>    order sorts earlier.
>  * If two keys have different lengths, the shorter one sorts earlier;
>  * If two keys have the same length, the one with the lower value in
>    (byte-wise) lexical order sorts earlier.

Some other implementations, such as borc, do a full encode then do a
length-first, byte-wise-second comparison:
https://github.com/dignifiedquire/borc/blob/b6bae8b0bcde7c3976b0f0f0957208095c392a36/src/encoder.js#L358
https://github.com/dignifiedquire/borc/blob/b6bae8b0bcde7c3976b0f0f0957208095c392a36/src/utils.js#L143-L151

This has the benefit of being able to easily handle arbitrary keys, including
complex types (maps and arrays).

We'll opt for the FIDO approach, since it affords some efficies since we don't
need a full encode of each key to determine order and can defer to the types
to determine how to most efficiently order their values (i.e. int and uint
ordering can be done on the numbers, no need for byte-wise, for example).

Recommendation: stick to single key types or you'll get into trouble, and prefer
string keys because it's much simpler that way.
*/

/**
 * @param {TokenOrNestedTokens[]} entries
 * @param {EncodeOptions} options
 */
function sortMapEntries (entries, options) {
  if (options.mapSorter) {
    entries.sort(options.mapSorter)
  }
}

/**
 * @param {(Token|Token[])[]} e1
 * @param {(Token|Token[])[]} e2
 * @returns {number}
 */
function mapSorter (e1, e2) {
  // the key position ([0]) could have a single token or an array
  // almost always it'll be a single token but complex key might get involved
  const keyToken1 = Array.isArray(e1[0]) ? e1[0][0] : e1[0]
  const keyToken2 = Array.isArray(e2[0]) ? e2[0][0] : e2[0]

  // different key types
  if (keyToken1.type !== keyToken2.type) {
    return keyToken1.type.compare(keyToken2.type)
  }

  const major = keyToken1.type.major
  // TODO: handle case where cmp === 0 but there are more keyToken e. complex type)
  const tcmp = cborEncoders[major].compareTokens(keyToken1, keyToken2)
  if (tcmp === 0) {
    // duplicate key or complex type where the first token matched,
    // i.e. a map or array and we're only comparing the opening token
    console.warn('WARNING: complex key types used, CBOR key sorting guarantees are gone')
  }
  return tcmp
}

/**
 * @typedef {Token & { _keyBytes?: Uint8Array }} TokenEx
 *
 * @param {(Token|Token[])[]} e1
 * @param {(Token|Token[])[]} e2
 * @returns {number}
 */
function rfc8949MapSorter (e1, e2) {
  if (e1[0] instanceof Token && e2[0] instanceof Token) {
    const t1 = /** @type {TokenEx} */ (e1[0])
    const t2 = /** @type {TokenEx} */ (e2[0])

    if (!t1._keyBytes) {
      t1._keyBytes = encodeRfc8949(t1.value)
    }

    if (!t2._keyBytes) {
      t2._keyBytes = encodeRfc8949(t2.value)
    }

    return compare(t1._keyBytes, t2._keyBytes)
  }

  throw new Error('rfc8949MapSorter: complex key types are not supported yet')
}

/**
 * @param {any} data
 * @returns {Uint8Array}
 */
function encodeRfc8949 (data) {
  return encodeCustom(data, cborEncoders, rfc8949EncodeOptions)
}

/**
 * @param {ByteWriter} writer
 * @param {TokenOrNestedTokens} tokens
 * @param {TokenTypeEncoder[]} encoders
 * @param {EncodeOptions} options
 */
function tokensToEncoded (writer, tokens, encoders, options) {
  if (Array.isArray(tokens)) {
    for (const token of tokens) {
      tokensToEncoded(writer, token, encoders, options)
    }
  } else {
    encoders[tokens.type.major](writer, tokens, options)
  }
}

// CBOR major type prefixes, cached from Type for hot path performance
const MAJOR_UINT = Type.uint.majorEncoded
const MAJOR_NEGINT = Type.negint.majorEncoded
const MAJOR_BYTES = Type.bytes.majorEncoded
const MAJOR_STRING = Type.string.majorEncoded
const MAJOR_ARRAY = Type.array.majorEncoded

// Simple value bytes (CBOR major type 7 + minor value)
const SIMPLE_FALSE = Type.float.majorEncoded | MINOR_FALSE
const SIMPLE_TRUE = Type.float.majorEncoded | MINOR_TRUE
const SIMPLE_NULL = Type.float.majorEncoded | MINOR_NULL
const SIMPLE_UNDEFINED = Type.float.majorEncoded | MINOR_UNDEFINED

const neg1b = BigInt(-1)
const pos1b = BigInt(1)

/**
 * Check if direct encoding can be used for the given options.
 * Direct encoding bypasses token creation for most values.
 * @param {EncodeOptions} options
 * @returns {boolean}
 */
function canDirectEncode (options) {
  // Cannot use direct encode with addBreakTokens (needs special break token handling).
  // Direct encode checks typeEncoders per-value, falling back to tokens as needed.
  // Maps fall back to token-based encoding for efficient key sorting.
  return options.addBreakTokens !== true
}

/**
 * Direct encode a value to the writer, bypassing token creation for most types.
 * Falls back to token-based encoding for custom type encoders.
 * @param {ByteWriter} writer
 * @param {any} data
 * @param {EncodeOptions} options
 * @param {Reference|undefined} refStack
 */
function directEncode (writer, data, options, refStack) {
  const typ = is(data)

  // Check for custom encoder for THIS specific type
  const customEncoder = options.typeEncoders && options.typeEncoders[typ]
  if (customEncoder) {
    const tokens = customEncoder(data, typ, options, refStack)
    if (tokens != null) {
      // Custom encoder returned tokens, serialize immediately
      tokensToEncoded(writer, tokens, cborEncoders, options)
      return
    }
    // Custom encoder returned null, fall through to default handling
  }

  // Direct encode based on type
  switch (typ) {
    case 'null':
      writer.push([SIMPLE_NULL])
      return

    case 'undefined':
      writer.push([SIMPLE_UNDEFINED])
      return

    case 'boolean':
      writer.push([data ? SIMPLE_TRUE : SIMPLE_FALSE])
      return

    case 'number':
      if (!Number.isInteger(data) || !Number.isSafeInteger(data)) {
        // Float, use token encoder for complex float encoding
        encodeFloat(writer, new Token(Type.float, data), options)
      } else if (data >= 0) {
        encodeUintValue(writer, MAJOR_UINT, data)
      } else {
        // Negative integer
        encodeUintValue(writer, MAJOR_NEGINT, data * -1 - 1)
      }
      return

    case 'bigint':
      if (data >= BigInt(0)) {
        encodeUintValue(writer, MAJOR_UINT, data)
      } else {
        encodeUintValue(writer, MAJOR_NEGINT, data * neg1b - pos1b)
      }
      return

    case 'string': {
      const bytes = fromString(data)
      encodeUintValue(writer, MAJOR_STRING, bytes.length)
      writer.push(bytes)
      return
    }

    case 'Uint8Array':
      encodeUintValue(writer, MAJOR_BYTES, data.length)
      writer.push(data)
      return

    case 'Array':
      if (!data.length) {
        writer.push([MAJOR_ARRAY]) // Empty array: 0x80
        return
      }
      refStack = Ref.createCheck(refStack, data)
      encodeUintValue(writer, MAJOR_ARRAY, data.length)
      for (const elem of data) {
        directEncode(writer, elem, options, refStack)
      }
      return

    case 'Object':
    case 'Map':
      // Maps require key sorting, use token-based encoding for efficiency
      // (pre-encoding all keys for sorting is expensive)
      {
        const tokens = typeEncoders.Object(data, typ, options, refStack)
        tokensToEncoded(writer, tokens, cborEncoders, options)
      }
      return

    default:
    // Fall back to token-based encoding for other types (DataView, TypedArrays, etc.)
    {
      const typeEncoder = typeEncoders[typ]
      if (!typeEncoder) {
        throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`)
      }
      const tokens = typeEncoder(data, typ, options, refStack)
      tokensToEncoded(writer, tokens, cborEncoders, options)
    }
  }
}

/**
 * @param {any} data
 * @param {TokenTypeEncoder[]} encoders
 * @param {EncodeOptions} options
 * @param {Uint8Array} [destination]
 * @returns {Uint8Array}
 */
function encodeCustom (data, encoders, options, destination) {
  // arg ordering is different to encodeInto for backward compatibility
  const hasDest = destination instanceof Uint8Array
  let writeTo = hasDest ? new U8Bl(destination) : defaultWriter

  const tokens = objectToTokens(data, options)
  if (!Array.isArray(tokens) && options.quickEncodeToken) {
    const quickBytes = options.quickEncodeToken(tokens)
    if (quickBytes) {
      if (hasDest) {
        // Copy quick bytes into destination buffer
        writeTo.push(quickBytes)
        return writeTo.toBytes()
      }
      return quickBytes
    }
    const encoder = encoders[tokens.type.major]
    if (encoder.encodedSize) {
      const size = encoder.encodedSize(tokens, options)
      if (!hasDest) {
        writeTo = new Bl(size)
      }
      encoder(writeTo, tokens, options)
      // this would be a problem with encodedSize() functions
      if (writeTo.chunks.length !== 1) {
        throw new Error(`Unexpected error: pre-calculated length for ${tokens} was wrong`)
      }
      return hasDest ? writeTo.toBytes() : asU8A(writeTo.chunks[0])
    }
  }
  writeTo.reset()
  tokensToEncoded(writeTo, tokens, encoders, options)
  return writeTo.toBytes(true)
}

/**
 * @param {any} data
 * @param {EncodeOptions} [options]
 * @returns {Uint8Array}
 */
function encode (data, options) {
  options = Object.assign({}, defaultEncodeOptions, options)

  // Use direct encode path when possible
  if (canDirectEncode(options)) {
    defaultWriter.reset()
    directEncode(defaultWriter, data, options, undefined)
    return defaultWriter.toBytes(true)
  }

  return encodeCustom(data, cborEncoders, options)
}

/**
 * @param {any} data
 * @param {Uint8Array} destination
 * @param {EncodeOptions} [options]
 * @returns {{ written: number }}
 */
function encodeInto (data, destination, options) {
  options = Object.assign({}, defaultEncodeOptions, options)

  // Use direct encode path when possible
  if (canDirectEncode(options)) {
    const writer = new U8Bl(destination)
    directEncode(writer, data, options, undefined)
    return { written: writer.toBytes().length }
  }

  const result = encodeCustom(data, cborEncoders, options, destination)
  return { written: result.length }
}

export { objectToTokens, encode, encodeCustom, encodeInto, Ref }
// This is an unfortunate replacement for @sindresorhus/is that we need to
// re-implement for performance purposes. In particular the is.observable()
// check is expensive, and unnecessary for our purposes. The values returned
// are compatible with @sindresorhus/is, however.

// Types that reach getObjectType() - excludes types with fast-paths above:
// primitives (typeof), Array (isArray), Uint8Array (instanceof), plain Object (constructor)
const objectTypeNames = [
  'Object', // for Object.create(null) and other non-plain objects
  'RegExp',
  'Date',
  'Error',
  'Map',
  'Set',
  'WeakMap',
  'WeakSet',
  'ArrayBuffer',
  'SharedArrayBuffer',
  'DataView',
  'Promise',
  'URL',
  'HTMLElement',
  'Int8Array',
  'Uint8ClampedArray',
  'Int16Array',
  'Uint16Array',
  'Int32Array',
  'Uint32Array',
  'Float32Array',
  'Float64Array',
  'BigInt64Array',
  'BigUint64Array',
  'Tagged'
]

/**
 * @param {any} value
 * @returns {string}
 */
export function is (value) {
  if (value === null) {
    return 'null'
  }
  if (value === undefined) {
    return 'undefined'
  }
  if (value === true || value === false) {
    return 'boolean'
  }
  const typeOf = typeof value
  if (typeOf === 'string' || typeOf === 'number' || typeOf === 'bigint' || typeOf === 'symbol') {
    return typeOf
  }
  if (typeOf === 'function') {
    return 'Function'
  }
  if (Array.isArray(value)) {
    return 'Array'
  }
  // Also catches Node.js Buffer which extends Uint8Array
  if (value instanceof Uint8Array) {
    return 'Uint8Array'
  }
  // Fast path for plain objects (most common case after primitives/arrays/bytes)
  if (value.constructor === Object) {
    return 'Object'
  }
  const objectType = getObjectType(value)
  if (objectType) {
    return objectType
  }
  return 'Object'
}

/**
 * @param {any} value
 * @returns {string|undefined}
 */
function getObjectType (value) {
  const objectTypeName = Object.prototype.toString.call(value).slice(8, -1)
  if (objectTypeNames.includes(objectTypeName)) {
    return objectTypeName
  }
  return undefined
}
import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import * as negint from './1negint.js'
import * as bytes from './2bytes.js'
import * as string from './3string.js'
import * as array from './4array.js'
import * as map from './5map.js'
import * as tag from './6tag.js'
import * as float from './7float.js'
import { decodeErrPrefix } from './common.js'
import { fromArray } from './byte-utils.js'

/**
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 */
function invalidMinor (data, pos, minor) {
  throw new Error(`${decodeErrPrefix} encountered invalid minor (${minor}) for major ${data[pos] >>> 5}`)
}

/**
 * @param {string} msg
 * @returns {()=>any}
 */
function errorer (msg) {
  return () => { throw new Error(`${decodeErrPrefix} ${msg}`) }
}

/** @type {((data:Uint8Array, pos:number, minor:number, options?:DecodeOptions) => any)[]} */
export const jump = []

// unsigned integer, 0x00..0x17 (0..23)
for (let i = 0; i <= 0x17; i++) {
  jump[i] = invalidMinor // uint.decodeUintCompact, handled by quick[]
}
jump[0x18] = uint.decodeUint8 // unsigned integer, one-byte uint8_t follows
jump[0x19] = uint.decodeUint16 // unsigned integer, two-byte uint16_t follows
jump[0x1a] = uint.decodeUint32 // unsigned integer, four-byte uint32_t follows
jump[0x1b] = uint.decodeUint64 // unsigned integer, eight-byte uint64_t follows
jump[0x1c] = invalidMinor
jump[0x1d] = invalidMinor
jump[0x1e] = invalidMinor
jump[0x1f] = invalidMinor
// negative integer, -1-0x00..-1-0x17 (-1..-24)
for (let i = 0x20; i <= 0x37; i++) {
  jump[i] = invalidMinor // negintDecode, handled by quick[]
}
jump[0x38] = negint.decodeNegint8 // negative integer, -1-n one-byte uint8_t for n follows
jump[0x39] = negint.decodeNegint16 // negative integer, -1-n two-byte uint16_t for n follows
jump[0x3a] = negint.decodeNegint32 // negative integer, -1-n four-byte uint32_t for follows
jump[0x3b] = negint.decodeNegint64 // negative integer, -1-n eight-byte uint64_t for follows
jump[0x3c] = invalidMinor
jump[0x3d] = invalidMinor
jump[0x3e] = invalidMinor
jump[0x3f] = invalidMinor
// byte string, 0x00..0x17 bytes follow
for (let i = 0x40; i <= 0x57; i++) {
  jump[i] = bytes.decodeBytesCompact
}
jump[0x58] = bytes.decodeBytes8 // byte string, one-byte uint8_t for n, and then n bytes follow
jump[0x59] = bytes.decodeBytes16 // byte string, two-byte uint16_t for n, and then n bytes follow
jump[0x5a] = bytes.decodeBytes32 // byte string, four-byte uint32_t for n, and then n bytes follow
jump[0x5b] = bytes.decodeBytes64 // byte string, eight-byte uint64_t for n, and then n bytes follow
jump[0x5c] = invalidMinor
jump[0x5d] = invalidMinor
jump[0x5e] = invalidMinor
jump[0x5f] = errorer('indefinite length bytes/strings are not supported') // byte string, byte strings follow, terminated by "break"
// UTF-8 string 0x00..0x17 bytes follow
for (let i = 0x60; i <= 0x77; i++) {
  jump[i] = string.decodeStringCompact
}
jump[0x78] = string.decodeString8 // UTF-8 string, one-byte uint8_t for n, and then n bytes follow
jump[0x79] = string.decodeString16 // UTF-8 string, two-byte uint16_t for n, and then n bytes follow
jump[0x7a] = string.decodeString32 // UTF-8 string, four-byte uint32_t for n, and then n bytes follow
jump[0x7b] = string.decodeString64 // UTF-8 string, eight-byte uint64_t for n, and then n bytes follow
jump[0x7c] = invalidMinor
jump[0x7d] = invalidMinor
jump[0x7e] = invalidMinor
jump[0x7f] = errorer('indefinite length bytes/strings are not supported') // UTF-8 strings follow, terminated by "break"
// array, 0x00..0x17 data items follow
for (let i = 0x80; i <= 0x97; i++) {
  jump[i] = array.decodeArrayCompact
}
jump[0x98] = array.decodeArray8 // array, one-byte uint8_t for n, and then n data items follow
jump[0x99] = array.decodeArray16 // array, two-byte uint16_t for n, and then n data items follow
jump[0x9a] = array.decodeArray32 // array, four-byte uint32_t for n, and then n data items follow
jump[0x9b] = array.decodeArray64 // array, eight-byte uint64_t for n, and then n data items follow
jump[0x9c] = invalidMinor
jump[0x9d] = invalidMinor
jump[0x9e] = invalidMinor
jump[0x9f] = array.decodeArrayIndefinite // array, data items follow, terminated by "break"
// map, 0x00..0x17 pairs of data items follow
for (let i = 0xa0; i <= 0xb7; i++) {
  jump[i] = map.decodeMapCompact
}
jump[0xb8] = map.decodeMap8 // map, one-byte uint8_t for n, and then n pairs of data items follow
jump[0xb9] = map.decodeMap16 // map, two-byte uint16_t for n, and then n pairs of data items follow
jump[0xba] = map.decodeMap32 // map, four-byte uint32_t for n, and then n pairs of data items follow
jump[0xbb] = map.decodeMap64 // map, eight-byte uint64_t for n, and then n pairs of data items follow
jump[0xbc] = invalidMinor
jump[0xbd] = invalidMinor
jump[0xbe] = invalidMinor
jump[0xbf] = map.decodeMapIndefinite // map, pairs of data items follow, terminated by "break"
// tags
for (let i = 0xc0; i <= 0xd7; i++) {
  jump[i] = tag.decodeTagCompact
}
jump[0xd8] = tag.decodeTag8
jump[0xd9] = tag.decodeTag16
jump[0xda] = tag.decodeTag32
jump[0xdb] = tag.decodeTag64
jump[0xdc] = invalidMinor
jump[0xdd] = invalidMinor
jump[0xde] = invalidMinor
jump[0xdf] = invalidMinor
// 0xe0..0xf3 simple values, unsupported
for (let i = 0xe0; i <= 0xf3; i++) {
  jump[i] = errorer('simple values are not supported')
}
jump[0xf4] = invalidMinor // false, handled by quick[]
jump[0xf5] = invalidMinor // true, handled by quick[]
jump[0xf6] = invalidMinor // null, handled by quick[]
jump[0xf7] = float.decodeUndefined // undefined
jump[0xf8] = errorer('simple values are not supported') // simple value, one byte follows, unsupported
jump[0xf9] = float.decodeFloat16 // half-precision float (two-byte IEEE 754)
jump[0xfa] = float.decodeFloat32 // single-precision float (four-byte IEEE 754)
jump[0xfb] = float.decodeFloat64 // double-precision float (eight-byte IEEE 754)
jump[0xfc] = invalidMinor
jump[0xfd] = invalidMinor
jump[0xfe] = invalidMinor
jump[0xff] = float.decodeBreak // "break" stop code

/** @type {Token[]} */
export const quick = []
// ints <24
for (let i = 0; i < 24; i++) {
  quick[i] = new Token(Type.uint, i, 1)
}
// negints >= -24
for (let i = -1; i >= -24; i--) {
  quick[31 - i] = new Token(Type.negint, i, 1)
}
// empty bytes
quick[0x40] = new Token(Type.bytes, new Uint8Array(0), 1)
// empty string
quick[0x60] = new Token(Type.string, '', 1)
// empty list
quick[0x80] = new Token(Type.array, 0, 1)
// empty map
quick[0xa0] = new Token(Type.map, 0, 1)
// false
quick[0xf4] = new Token(Type.false, false, 1)
// true
quick[0xf5] = new Token(Type.true, true, 1)
// null
quick[0xf6] = new Token(Type.null, null, 1)

/**
 * @param {Token} token
 * @returns {Uint8Array|undefined}
 */
export function quickEncodeToken (token) {
  switch (token.type) {
    case Type.false:
      return fromArray([0xf4])
    case Type.true:
      return fromArray([0xf5])
    case Type.null:
      return fromArray([0xf6])
    case Type.bytes:
      if (!token.value.length) {
        return fromArray([0x40])
      }
      return
    case Type.string:
      if (token.value === '') {
        return fromArray([0x60])
      }
      return
    case Type.array:
      if (token.value === 0) {
        return fromArray([0x80])
      }
      // shouldn't be possible if this were called when there was only one token
      return
    case Type.map:
      if (token.value === 0) {
        return fromArray([0xa0])
      }
      // shouldn't be possible if this were called when there was only one token
      return
    case Type.uint:
      if (token.value < 24) {
        return fromArray([Number(token.value)])
      }
      return
    case Type.negint:
      if (token.value >= -24) {
        return fromArray([31 - Number(token.value)])
      }
  }
}
/**
 * @typedef {import('../interface.js').TagDecodeControl} TagDecodeControl
 * @typedef {(decode: TagDecodeControl) => Tagged} TaggedTagDecoder
 */

/**
 * A wrapper class for representing a CBOR tag with an arbitrary nested value.
 *
 * `Tagged` is a symmetric primitive: it can be passed to `encode()` to emit
 * a CBOR tag header followed by the encoded form of `value`, and it can be
 * returned from a tag decoder (via `Tagged.decoder(tag)` or `Tagged.preserve()`)
 * to round-trip a tag through decode without losing the tag number.
 *
 * Use `Tagged` for one-off tag handling where defining a dedicated
 * `typeEncoders` entry and tag decoder pair would be heavyweight, e.g. when
 * wrapping a structure in a single application-specific tag (COSE, dCBOR
 * envelopes, etc.).
 *
 * For systematic mapping of a JS type to a tag (e.g. CID -> tag 42), prefer
 * a dedicated `typeEncoders` entry instead.
 */
export class Tagged {
  /**
   * @param {number} tag - CBOR tag number, a non-negative integer
   * @param {any} value - The value to be tagged; encoded recursively
   */
  constructor (tag, value) {
    if (typeof tag !== 'number' || !Number.isInteger(tag) || tag < 0) {
      throw new TypeError('Tagged: tag must be a non-negative integer')
    }
    this.tag = tag
    this.value = value
  }

  /**
   * Build a tag decoder for use in `decode()`'s `tags` option that returns the
   * decoded content wrapped in a `Tagged` instance, preserving the tag number
   * for the caller to inspect.
   *
   * @param {number} tag - The CBOR tag number this decoder will be registered for
   * @returns {TaggedTagDecoder}
   *
   * @example
   * import { decode, Tagged } from 'cborg'
   * const value = decode(bytes, { tags: { 16: Tagged.decoder(16) } })
   * // value instanceof Tagged; value.tag === 16
   */
  static decoder (tag) {
    return (decode) => new Tagged(tag, decode())
  }

  /**
   * Build a `tags` option for `decode()` that wraps each listed tag number in
   * a `Tagged` instance, preserving those tags through decode without
   * registering a dedicated decoder per tag.
   *
   * @param {...number} tagNumbers - One or more CBOR tag numbers to preserve
   * @returns {{[tagNumber: number]: TaggedTagDecoder}}
   *
   * @example
   * import { decode, Tagged } from 'cborg'
   * const value = decode(bytes, { tags: Tagged.preserve(16, 96) })
   */
  static preserve (...tagNumbers) {
    /** @type {{[tagNumber: number]: TaggedTagDecoder}} */
    const tags = {}
    for (const tag of tagNumbers) {
      tags[tag] = Tagged.decoder(tag)
    }
    return tags
  }
}

// Symbol.toStringTag so the internal `is()` type detection returns 'Tagged'
// for instances, allowing the default Tagged typeEncoder to match.
Object.defineProperty(Tagged.prototype, Symbol.toStringTag, {
  value: 'Tagged'
})
class Type {
  /**
   * @param {number} major
   * @param {string} name
   * @param {boolean} terminal
   */
  constructor (major, name, terminal) {
    this.major = major
    this.majorEncoded = major << 5
    this.name = name
    this.terminal = terminal
  }

  toString () {
    return `Type[${this.major}].${this.name}`
  }

  /**
   * @param {Type} typ
   * @returns {number}
   */
  compare (typ) {
    return this.major < typ.major ? -1 : this.major > typ.major ? 1 : 0
  }

  /**
   * Check equality between two Type instances. Safe to use across different
   * copies of the Type class (e.g., when bundlers duplicate the module).
   * (major, name) uniquely identifies a Type; terminal is implied by these.
   * @param {Type} a
   * @param {Type} b
   * @returns {boolean}
   */
  static equals (a, b) {
    return a === b || (a.major === b.major && a.name === b.name)
  }
}

// convert to static fields when better supported
Type.uint = new Type(0, 'uint', true)
Type.negint = new Type(1, 'negint', true)
Type.bytes = new Type(2, 'bytes', true)
Type.string = new Type(3, 'string', true)
Type.array = new Type(4, 'array', false)
Type.map = new Type(5, 'map', false)
Type.tag = new Type(6, 'tag', false) // terminal?
Type.float = new Type(7, 'float', true)
Type.false = new Type(7, 'false', true)
Type.true = new Type(7, 'true', true)
Type.null = new Type(7, 'null', true)
Type.undefined = new Type(7, 'undefined', true)
Type.break = new Type(7, 'break', true)
// Type.indefiniteLength = new Type(0, 'indefiniteLength', true)

class Token {
  /**
   * @param {Type} type
   * @param {any} [value]
   * @param {number} [encodedLength]
   */
  constructor (type, value, encodedLength) {
    this.type = type
    this.value = value
    this.encodedLength = encodedLength
    /** @type {Uint8Array|undefined} */
    this.encodedBytes = undefined
    /** @type {Uint8Array|undefined} */
    this.byteValue = undefined
  }

  toString () {
    return `Token[${this.type}].${this.value}`
  }
}

export { Type, Token }
{
  "name": "cborg",
  "version": "5.1.6",
  "description": "Fast CBOR with a focus on strictness",
  "main": "cborg.js",
  "type": "module",
  "bin": {
    "cborg": "lib/bin.js"
  },
  "scripts": {
    "lint": "standard *.js lib/*.js test/*.js",
    "build": "npm run build:types",
    "build:types": "tsc --build",
    "prepublishOnly": "npm run build",
    "test:node": "mocha test/test-*.js",
    "test:node-bin": "mocha test/node-test-bin.js",
    "test:browser": "polendina --cleanup test/test-*.js",
    "test": "npm run lint && npm run build && npm run test:node && npm run test:node-bin && npm run test:browser",
    "test:ci": "npm run test"
  },
  "repository": {
    "type": "git",
    "url": "git@github.com:rvagg/cborg.git"
  },
  "keywords": [
    "cbor"
  ],
  "author": "Rod <rod@vagg.org> (http://r.va.gg/)",
  "license": "Apache-2.0",
  "devDependencies": {
    "@semantic-release/changelog": "^6.0.3",
    "@semantic-release/commit-analyzer": "^13.0.1",
    "@semantic-release/git": "^10.0.1",
    "@semantic-release/github": "^12.0.6",
    "@semantic-release/npm": "^13.1.5",
    "@semantic-release/release-notes-generator": "^14.1.0",
    "@types/chai": "^5.2.3",
    "@types/mocha": "^10.0.10",
    "@types/node": "^26.0.1",
    "chai": "^6.2.2",
    "conventional-changelog-conventionalcommits": "^10.0.0",
    "ipld-garbage": "^5.0.0",
    "mocha": "^11.7.5",
    "polendina": "^3.2.20",
    "semantic-release": "^25.0.3",
    "standard": "^17.1.2",
    "typescript": "^6.0.2"
  },
  "exports": {
    ".": {
      "import": "./cborg.js",
      "types": "./types/cborg.d.ts"
    },
    "./length": {
      "import": "./lib/length.js",
      "types": "./types/lib/length.d.ts"
    },
    "./taglib": {
      "import": "./lib/taglib.js",
      "types": "./types/lib/taglib.d.ts"
    },
    "./json": {
      "import": "./lib/json/json.js",
      "types": "./types/lib/json/json.d.ts"
    },
    "./extended": {
      "import": "./lib/extended/extended.js",
      "types": "./types/lib/extended/extended.d.ts"
    },
    "./interface": {
      "types": "./types/interface.d.ts"
    }
  },
  "types": "cborg.d.ts",
  "typesVersions": {
    "*": {
      "json": [
        "types/lib/json/json.d.ts"
      ],
      "length": [
        "types/lib/length.d.ts"
      ],
      "*": [
        "types/*"
      ],
      "types/*": [
        "types/*"
      ]
    }
  },
  "release": {
    "branches": [
      "master"
    ],
    "plugins": [
      [
        "@semantic-release/commit-analyzer",
        {
          "preset": "conventionalcommits",
          "releaseRules": [
            {
              "breaking": true,
              "release": "major"
            },
            {
              "revert": true,
              "release": "patch"
            },
            {
              "type": "feat",
              "release": "minor"
            },
            {
              "type": "fix",
              "release": "patch"
            },
            {
              "type": "chore",
              "release": "patch"
            },
            {
              "type": "docs",
              "release": "patch"
            },
            {
              "type": "test",
              "release": "patch"
            },
            {
              "scope": "no-release",
              "release": false
            }
          ]
        }
      ],
      [
        "@semantic-release/release-notes-generator",
        {
          "preset": "conventionalcommits",
          "presetConfig": {
            "types": [
              {
                "type": "feat",
                "section": "Features"
              },
              {
                "type": "fix",
                "section": "Bug Fixes"
              },
              {
                "type": "chore",
                "section": "Trivial Changes"
              },
              {
                "type": "docs",
                "section": "Trivial Changes"
              },
              {
                "type": "test",
                "section": "Tests"
              }
            ]
          }
        }
      ],
      "@semantic-release/changelog",
      "@semantic-release/npm",
      "@semantic-release/github",
      "@semantic-release/git"
    ]
  }
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
const b4a = require('b4a')
const Hypercore = require('hypercore')
const ReadyResource = require('ready-resource')
const sodium = require('sodium-universal')
const crypto = require('hypercore-crypto')
const ID = require('hypercore-id-encoding')
const { isAndroid } = require('which-runtime')
const { STORAGE_EMPTY, ASSERTION } = require('hypercore-errors')

const auditStore = require('./lib/audit.js')
const GroupNotifyHandle = require('./lib/notify.js')

const [NS] = crypto.namespace('corestore', 1)
const DEFAULT_NAMESPACE = b4a.alloc(32) // This is meant to be 32 0-bytes

class StreamTracker {
  constructor() {
    this.records = []
  }

  add(stream, isExternal) {
    const record = { index: 0, stream, isExternal }
    record.index = this.records.push(record) - 1
    return record
  }

  remove(record) {
    const popped = this.records.pop()
    if (popped === record) return
    this.records[(popped.index = record.index)] = popped
  }

  attachAll(core) {
    for (let i = 0; i < this.records.length; i++) {
      const record = this.records[i]
      const muxer = record.stream.noiseStream.userData
      if (!core.replicator.attached(muxer)) core.replicator.attachTo(muxer)
    }
  }

  destroy() {
    // reverse is safer cause we delete mb
    for (let i = this.records.length - 1; i >= 0; i--) {
      const record = this.records[i]
      if (!record.isExternal) record.stream.destroy()
    }
  }
}

class SessionTracker {
  constructor() {
    this.map = new Map()
  }

  get size() {
    return this.map.size
  }

  get(id) {
    const existing = this.map.get(id)
    if (existing !== undefined) return existing
    const fresh = []
    this.map.set(id, fresh)
    return fresh
  }

  gc(id) {
    this.map.delete(id)
  }

  list(id) {
    return id ? this.map.get(id) || [] : [...this]
  }

  *[Symbol.iterator]() {
    for (const sessions of this.map.values()) {
      yield* sessions[Symbol.iterator]()
    }
  }
}

class CoreTracker {
  constructor() {
    this.map = new Map()
    this.watching = []

    this._gcing = new Set()
    this._gcInterval = null
    this._gcCycleBound = this._gcCycle.bind(this)
  }

  get size() {
    return this.map.size
  }

  watch(store) {
    if (store.watchIndex !== -1) return
    store.watchIndex = this.watching.push(store) - 1
  }

  unwatch(store) {
    if (store.watchIndex === -1) return
    const head = this.watching.pop()
    if (head !== store) this.watching[(head.watchIndex = store.watchIndex)] = head
    store.watchIndex = -1
  }

  resume(id) {
    const core = this.map.get(id)

    if (!core) return null

    // signal back that we have a closing one stored
    if (core.closing) return core

    if (core.gc) {
      this._gcing.delete(core)
      if (this._gcing.size === 0) this._stopGC()
      core.gc = 0
    }

    return core
  }

  opened(id) {
    const core = this.map.get(id)
    return !!(core && core.opened && !core.closing)
  }

  get(id) {
    // we allow you do call this from the outside, so support normal buffers also
    if (b4a.isBuffer(id)) id = b4a.toString(id, 'hex')
    const core = this.map.get(id)
    if (!core || core.closing) return null
    return core
  }

  set(id, core) {
    this.map.set(id, core)
    if (this.watching.length > 0) this._emit(core)
  }

  _emit(core) {
    for (let i = this.watching.length - 1; i >= 0; i--) {
      const store = this.watching[i]
      for (const fn of store.watchers) fn(core)
    }
  }

  _gc(core) {
    const id = toHex(core.discoveryKey)
    if (this.map.get(id) === core) this.map.delete(id)
  }

  _gcCycle() {
    for (const core of this._gcing) {
      if (++core.gc < 4) continue
      const gc = this._gc.bind(this, core)
      core.close().then(gc, gc)
      this._gcing.delete(core)
    }

    if (this._gcing.size === 0) this._stopGC()
  }

  gc(core) {
    core.gc = 1 // first strike
    this._gcing.add(core)
    if (this._gcing.size === 1) this._startGC()
  }

  _stopGC() {
    clearInterval(this._gcInterval)
    this._gcInterval = null
  }

  _startGC() {
    if (this._gcInterval) return
    this._gcInterval = setInterval(this._gcCycleBound, 2000)
    if (this._gcInterval.unref) this._gcInterval.unref()
  }

  close() {
    this._stopGC()
    this._gcing.clear()

    const all = []
    for (const core of this.map.values()) {
      core.onidle = noop // no reentry
      all.push(core.close())
    }
    this.map.clear()

    return Promise.all(all)
  }

  *[Symbol.iterator]() {
    for (const core of this.map.values()) {
      if (!core.closing) yield core
    }
  }
}

class FindingPeers {
  constructor() {
    this.count = 0
    this.pending = []
    this.destroyed = false
  }

  add(core) {
    if (this.count === 0) return
    this.pending.push(core.findingPeers())
  }

  inc(sessions) {
    if (this.destroyed || ++this.count !== 1) return

    for (const core of sessions) {
      this.pending.push(core.findingPeers())
    }
  }

  dec(sessions) {
    if (this.destroyed || --this.count !== 0) return
    while (this.pending.length > 0) this.pending.pop()()
  }

  destroy() {
    this.destroyed = true
    while (this.pending.length > 0) this.pending.pop()()
  }
}

class Corestore extends ReadyResource {
  constructor(storage, opts = {}) {
    super()

    this.root = opts.root || null
    this.storage = this.root
      ? this.root.storage
      : Hypercore.defaultStorage(storage, {
          id: opts.id,
          allowBackup: opts.allowBackup,
          readOnly: opts.readOnly,
          wait: opts.wait
        })
    this.streamTracker = this.root ? this.root.streamTracker : new StreamTracker()
    this.cores = this.root ? this.root.cores : new CoreTracker()
    this.sessions = new SessionTracker()
    this.corestores = this.root ? this.root.corestores : new Set()
    this.readOnly = opts.writable === false || !!opts.readOnly
    this.globalCache = this.root ? this.root.globalCache : opts.globalCache || null
    this.primaryKey = this.root ? this.root.primaryKey : opts.primaryKey || null
    this.ns = opts.namespace || DEFAULT_NAMESPACE
    this.manifestVersion = opts.manifestVersion || 1
    this.shouldSuspend = isAndroid ? !!opts.suspend : opts.suspend !== false
    this.active = opts.active !== false

    this.watchers = null
    this.watchIndex = -1

    this._groupNotifiers = new Map() // group notifications
    this._findingPeers = null // here for legacy
    this._ongcBound = this._ongc.bind(this)
    this._onGroupActiveBound = this._onGroupActive.bind(this)

    if (opts.primaryKey && !this.root && !opts.unsafe) {
      throw ASSERTION(
        'Passing the primary key is unsafe unless you know what you are doing. Set unsafe: true to acknowledge that'
      )
    }

    this.ready().catch(noop)
  }

  watch(fn) {
    if (this.watchers === null) {
      this.watchers = new Set()
      this.cores.watch(this)
    }

    this.watchers.add(fn)
  }

  unwatch(fn) {
    if (this.watchers === null) return

    this.watchers.delete(fn)

    if (this.watchers.size === 0) {
      this.watchers = null
      this.cores.unwatch(this)
    }
  }

  _onGroupActive(topic, update) {
    this.emit('group-active', topic, update)

    const topicHex = b4a.toString(topic, 'hex')
    const handles = this._groupNotifiers.get(topicHex)
    if (!handles) return
    for (const handle of handles) handle.emit('update', update)
  }

  notifyGroup(topic) {
    const topicHex = b4a.toString(topic, 'hex')
    let handles = this._groupNotifiers.get(topicHex)

    if (!handles) {
      handles = []
      this._groupNotifiers.set(topicHex, handles)
    }

    const handle = new GroupNotifyHandle(this, topic)
    const length = handles.push(handle)
    handle.index = length - 1

    return handle
  }

  _removeGroupNotify(handle) {
    if (handle.index === -1) return

    const topicHex = b4a.toString(handle._topic, 'hex')
    const handles = this._groupNotifiers.get(topicHex)
    if (!handles) return

    const popped = handles.pop()
    if (popped !== handle) handles[(popped.index = handle.index)] = popped
    if (handles.length === 0) this._groupNotifiers.delete(topicHex)
    handle.index = -1
  }

  findingPeers() {
    if (this._findingPeers === null) this._findingPeers = new FindingPeers()
    this._findingPeers.inc(this.sessions)
    let done = false
    return () => {
      if (done || !this._findingPeers) return
      done = true
      this._findingPeers.dec(this.sessions)
    }
  }

  audit(opts = {}) {
    return auditStore(this, opts)
  }

  async suspend({ log = noop } = {}) {
    await log('Flushing db...')
    // If readOnly we don't need to flush
    if (!this.storage.readOnly) {
      await this.storage.db.flush()
      await log('Flusing db completed')
    }
    if (!this.shouldSuspend) return
    await log('Suspending db...')
    await this.storage.suspend({ log })
    await log('Suspending db completed')
  }

  resume() {
    return this.storage.resume()
  }

  session(opts) {
    this._maybeClosed()
    const root = this.root || this
    return new Corestore(null, {
      manifestVersion: this.manifestVersion,
      ...opts,
      root
    })
  }

  namespace(name, opts) {
    return this.session({
      ...opts,
      namespace: generateNamespace(this.ns, name)
    })
  }

  list(namespace) {
    return this.storage.createDiscoveryKeyStream(namespace)
  }

  getAuth(discoveryKey) {
    return this.storage.getAuth(discoveryKey)
  }

  _ongc(session) {
    if (session.sessions.length === 0) this.sessions.gc(session.id)
  }

  async _getOrSetSeed() {
    const seed = await this.storage.getSeed()
    if (seed !== null) return seed
    return await this.storage.setSeed(this.primaryKey || crypto.randomBytes(32))
  }

  async _open() {
    if (this.root !== null) {
      this.corestores.add(this)
      if (this.root.opened === false) await this.root.ready()
      this.primaryKey = this.root.primaryKey
      return
    }

    const primaryKey = await this._getOrSetSeed()

    if (this.primaryKey === null) {
      this.primaryKey = primaryKey
      return
    }

    if (!b4a.equals(primaryKey, this.primaryKey)) {
      throw new Error('Another corestore is stored here')
    }
  }

  async _close() {
    const closing = []
    const hanging = [...this.sessions]
    for (const sess of hanging) closing.push(sess.close())

    if (this.watchers !== null) {
      this.cores.unwatch(this)
      this.watchers = null
    }

    if (this._findingPeers !== null) {
      this._findingPeers.destroy()
      this._findingPeers = null
    }

    if (this.root !== null) {
      await Promise.all(closing)
      this.corestores.delete(this)
      return
    }

    for (const store of this.corestores) {
      closing.push(store.close())
    }

    await Promise.all(closing)

    await this.cores.close()
    await this.storage.close()
  }

  async _attachMaybe(muxer, discoveryKey) {
    if (this.opened === false) await this.ready()
    if (
      !this.cores.opened(toHex(discoveryKey)) &&
      !(await this.storage.hasCore(discoveryKey, { ifMigrated: true }))
    ) {
      return
    }
    if (this.closing) return

    const core = this._openCore(discoveryKey, { createIfMissing: false })

    if (!core) return
    if (!core.opened) await core.ready()

    if (!core.replicator.attached(muxer)) {
      core.replicator.attachTo(muxer)
    }

    core.checkIfIdle()
  }

  _shouldReplicate(core, muxer) {
    return (
      core.replicator.downloading && !core.replicator.attached(muxer) && core.opened && this.active
    )
  }

  replicate(isInitiator, opts) {
    this._maybeClosed()

    const isExternal = isStream(isInitiator)
    const stream = Hypercore.createProtocolStream(isInitiator, {
      ...opts,
      ondiscoverykey: (discoveryKey) => {
        if (this.closing) return
        const muxer = stream.noiseStream.userData
        return this._attachMaybe(muxer, discoveryKey)
      }
    })

    if (this.cores.size > 0) {
      const muxer = stream.noiseStream.userData
      const uncork = muxer.uncork.bind(muxer)
      muxer.cork()

      for (const core of this.cores) {
        if (!this._shouldReplicate(core, muxer)) {
          continue
        }
        core.replicator.attachTo(muxer)
      }

      stream.noiseStream.opened.then(uncork)
    }

    const record = this.streamTracker.add(stream, isExternal)
    stream.once('close', () => this.streamTracker.remove(record))
    return stream
  }

  _maybeClosed() {
    if (this.closing || (this.root !== null && this.root.closing)) {
      throw new Error('Corestore is closed')
    }
  }

  async staticify(core, opts) {
    if (!this.opened) await this.ready()
    if (!core.opened) await core.ready()

    const rx = core.state.storage.read()

    const headPromise = rx.getHead()
    const authPromise = rx.getAuth()

    rx.tryFlush()

    const [head, auth] = await Promise.all([headPromise, authPromise])
    if (!head || head.length === 0) throw new Error('Core must have data')

    const prologue = {
      length: head.length,
      hash: head.rootHash
    }

    const manifest = {
      version: 1,
      hash: auth.manifest.hash,
      quorum: 0,
      signers: [],
      prologue
    }

    const c = {
      key: null,
      discoveryKey: null,
      manifest,
      core: core.state.storage.core
    }

    c.key = Hypercore.key(c.manifest)
    c.discoveryKey = Hypercore.discoveryKey(c.key)

    await this.storage.createCore(c)

    const staticCore = this.get({ ...opts, key: c.key })
    await staticCore.ready()
    return staticCore
  }

  get(opts) {
    this._maybeClosed()

    if (b4a.isBuffer(opts) || typeof opts === 'string') opts = { key: opts }
    if (!opts) opts = {}

    const conf = {
      preload: null,
      sessions: null,
      ongc: null,
      core: null,
      active: opts.active !== false,
      encryption: opts.encryption || null,
      encryptionKey: opts.encryptionKey || null, // back compat, should remove
      isBlockKey: !!opts.isBlockKey, // back compat, should remove
      valueEncoding: opts.valueEncoding || null,
      exclusive: !!opts.exclusive,
      manifest: opts.manifest || null,
      keyPair: opts.keyPair || null,
      onwait: opts.onwait || null,
      pushOnly: opts.pushOnly === true,
      wait: opts.wait !== false,
      timeout: opts.timeout || 0,
      draft: !!opts.draft,
      writable: opts.writable === undefined && this.readOnly ? false : opts.writable
    }

    // name requires us to rt to storage + ready, so needs preload
    // same goes if user has defined async preload obvs
    if (opts.name || opts.preload) {
      conf.preload = this._preload(opts)
      return this._makeSession(conf)
    }

    if (opts.discoveryKey && !opts.key && !opts.manifest) {
      conf.preload = this._preloadCheckIfExists(opts)
      return this._makeSession(conf)
    }

    // if not not we can sync create it, which just is easier for the
    // upstream user in terms of guarantees (key is there etc etc)
    const core = this._openCore(null, opts)

    conf.core = core
    conf.sessions = this.sessions.get(core.id)
    conf.ongc = this._ongcBound

    return this._makeSession(conf)
  }

  _makeSession(conf) {
    const session = new Hypercore(null, null, conf)

    if (this._findingPeers !== null) this._findingPeers.add(session)
    return session
  }

  async createKeyPair(name, ns = this.ns) {
    if (this.opened === false) await this.ready()
    return createKeyPair(this.primaryKey, ns, name)
  }

  async _preloadCheckIfExists(opts) {
    const has = await this.storage.hasCore(opts.discoveryKey)
    if (!has) throw STORAGE_EMPTY('No Hypercore is stored here')
    return this._preload(opts)
  }

  async _preload(opts) {
    if (opts.preload) opts = { ...opts, ...(await opts.preload) }
    if (this.opened === false) await this.ready()

    const discoveryKey = opts.name
      ? await this.storage.getAlias({ name: opts.name, namespace: this.ns })
      : null
    this._maybeClosed()

    const core = this._openCore(discoveryKey, opts)

    return {
      core,
      sessions: this.sessions.get(core.id),
      ongc: this._ongcBound,
      manifest: opts.manifest || null,
      encryption: opts.encryption || null,
      encryptionKey: opts.encryptionKey || null, // back compat, should remove
      isBlockKey: !!opts.isBlockKey // back compat, should remove
    }
  }

  _auth(discoveryKey, opts) {
    const result = {
      keyPair: null,
      key: null,
      discoveryKey,
      manifest: null,
      group: null
    }

    if (opts.name) {
      result.keyPair = createKeyPair(this.primaryKey, this.ns, opts.name)
    } else if (opts.keyPair) {
      result.keyPair = opts.keyPair
    }

    if (opts.manifest) {
      result.manifest = opts.manifest
    } else if (result.keyPair && !result.discoveryKey) {
      result.manifest = {
        version: this.manifestVersion,
        signers: [{ publicKey: result.keyPair.publicKey }]
      }
    }

    if (opts.group) {
      result.group = opts.group
    }

    if (opts.key) result.key = ID.decode(opts.key)
    else if (result.manifest) result.key = Hypercore.key(result.manifest)

    if (result.discoveryKey) return result

    if (opts.discoveryKey) result.discoveryKey = ID.decode(opts.discoveryKey)
    else if (result.key) result.discoveryKey = crypto.discoveryKey(result.key)
    else throw new Error('Could not derive discovery from input')

    return result
  }

  _openCore(discoveryKey, opts) {
    const auth = this._auth(discoveryKey, opts)

    const id = toHex(auth.discoveryKey)
    const existing = this.cores.resume(id, auth.group)
    if (existing && !existing.closing) return existing

    const core = Hypercore.createCore(this.storage, {
      preopen: existing && existing.opened ? existing.closing : null, // always wait for the prev one to close first in any case...
      eagerUpgrade: true,
      notDownloadingLinger: opts.notDownloadingLinger,
      allowFork: opts.allowFork !== false,
      allowPush: !!opts.allowPush,
      inflightRange: opts.inflightRange,
      compat: false, // no compat for now :)
      force: opts.force,
      createIfMissing: opts.createIfMissing,
      discoveryKey: auth.discoveryKey,
      overwrite: opts.overwrite,
      key: auth.key,
      keyPair: auth.keyPair,
      legacy: opts.legacy,
      manifest: auth.manifest,
      group: auth.group,
      globalCache: opts.globalCache || this.globalCache || null,
      alias: opts.name ? { name: opts.name, namespace: this.ns } : null
    })

    core.onidle = () => {
      this.cores.gc(core)
    }

    core.ongroupupdate = this._onGroupActiveBound

    core.replicator.ondownloading = () => {
      if (this.active) this.streamTracker.attachAll(core)
    }

    this.cores.set(id, core)
    return core
  }
}

module.exports = Corestore

function isStream(s) {
  return typeof s === 'object' && s && typeof s.pipe === 'function'
}

function generateNamespace(namespace, name) {
  if (!b4a.isBuffer(name)) name = b4a.from(name)
  const out = b4a.allocUnsafeSlow(32)
  sodium.crypto_generichash_batch(out, [namespace, name])
  return out
}

function deriveSeed(primaryKey, namespace, name) {
  if (!b4a.isBuffer(name)) name = b4a.from(name)
  const out = b4a.alloc(32)
  sodium.crypto_generichash_batch(out, [NS, namespace, name], primaryKey)
  return out
}

function createKeyPair(primaryKey, namespace, name) {
  const seed = deriveSeed(primaryKey, namespace, name)
  const buf = b4a.alloc(sodium.crypto_sign_PUBLICKEYBYTES + sodium.crypto_sign_SECRETKEYBYTES)
  const keyPair = {
    publicKey: buf.subarray(0, sodium.crypto_sign_PUBLICKEYBYTES),
    secretKey: buf.subarray(sodium.crypto_sign_PUBLICKEYBYTES)
  }
  sodium.crypto_sign_seed_keypair(keyPair.publicKey, keyPair.secretKey, seed)
  return keyPair
}

function noop() {}

function toHex(discoveryKey) {
  return b4a.toString(discoveryKey, 'hex')
}
module.exports = async function* audit(store, { dryRun = false } = {}) {
  for await (const { discoveryKey, core } of store.storage.createCoreStream()) {
    if (core.version < 1) continue // not migrated, ignore

    const c = store.get({ discoveryKey, active: false })
    await c.ready()

    yield { discoveryKey, key: c.key, audit: await c.core.audit({ dryRun }) }

    try {
      await c.close()
    } catch {
      // ignore if failed, we are auditing...
    }
  }
}
const { EventEmitter } = require('events')
const { Readable } = require('streamx')

class GroupNotifyHandle extends EventEmitter {
  constructor(store, topic) {
    super()
    this._store = store
    this._topic = topic
    this.index = -1
  }

  updates(opts) {
    return Readable.deferred(async () => {
      const groupId = await this._store.storage.getGroup(this._topic).catch(noop)
      if (groupId === null) return null
      return this._store.storage.createGroupUpdateStream(groupId, opts)
    })
  }

  destroy() {
    this._store._removeGroupNotify(this)
  }
}

module.exports = GroupNotifyHandle

function noop() {}
{
  "name": "corestore",
  "version": "7.11.0",
  "description": "A Hypercore factory that simplifies managing collections of cores.",
  "main": "index.js",
  "files": [
    "index.js",
    "lib/*"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "dependencies": {
    "b4a": "^1.6.7",
    "bare-events": "^2.8.3",
    "hypercore": "^11.32.0",
    "hypercore-crypto": "^3.4.2",
    "hypercore-errors": "^1.4.0",
    "hypercore-id-encoding": "^1.3.0",
    "ready-resource": "^1.1.1",
    "sodium-universal": "^5.0.1",
    "streamx": "^2.26.0",
    "which-runtime": "^1.2.1"
  },
  "devDependencies": {
    "brittle": "^3.7.0",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "rache": "^1.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "test": "npm run test:node && npm run test:bare",
    "test:bare": "brittle-bare --coverage test/all.js",
    "lint": "prettier --check . && lunte",
    "test:node": "brittle-node --coverage test/all.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/corestore.git"
  },
  "author": "Holepunch Inc",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/corestore/issues"
  },
  "homepage": "https://github.com/holepunchto/corestore"
}
const fs = require('fs')
const path = require('path')
const fsx = require('fs-native-extensions')
const b4a = require('b4a')
const ReadyResource = require('ready-resource')
const FDLock = require('fd-lock')

const PLATFORM = global.Bare ? global.Bare.platform : global.process.platform
const IS_WIN = PLATFORM === 'win32'
const IS_LINUX = PLATFORM === 'linux'
const MODIFIED_SLACK = 5000
const EMPTY = b4a.alloc(0)
const ATTR = IS_LINUX ? 'user.device-file' : 'device-file'

const nl = IS_WIN ? '\r\n' : '\n'

class DeviceFile extends ReadyResource {
  constructor(filename, { create = true, wait = false, lock = wait, data = {} } = {}) {
    super()

    this.filename = filename
    this.data = data
    this.lock = null

    this._create = create
    this._wait = wait
    this._lock = lock
  }

  async _open() {
    if (await verifyDeviceFile(this)) return
    if (!this._create) throwDeviceFileError('No device file present', false)
    await writeDeviceFile(this)
  }

  static async validate(filename, data) {
    const file = new DeviceFile(filename, { create: false, wait: false, data })
    try {
      await verifyDeviceFile(file)
    } catch (err) {
      if (err.fatal && err.code === 'DEVICE_FILE') return false
      throw err
    }
    return true
  }

  transfer() {
    return this.lock ? this.lock.transfer() : -1
  }

  async _close() {
    if (this.lock) await this.lock.close()
  }

  async suspend() {
    if (!this.opened) await this.ready()
    if (this.lock) await this.lock.suspend()
  }

  async resume() {
    if (!this.opened) await this.ready()
    if (this.lock) await this.lock.resume()
  }
}

module.exports = DeviceFile

async function writeDeviceFile(device) {
  let s = ''

  for (const [key, value] of Object.entries(device.data)) {
    if (value === null) continue
    s += key + '=' + value + nl
  }

  await fs.promises.mkdir(path.dirname(device.filename), { recursive: true })

  const fd = await open(device.filename, 'w')

  device.lock = device._lock ? new FDLock(fd, { wait: device._wait }) : null

  if (device.lock) {
    try {
      await device.lock.ready()
    } catch (err) {
      await device.lock.close()
      throw err
    }
  }

  const st = await fstat(fd)

  const created = Date.now()

  s += 'device/platform=' + PLATFORM + nl
  s += 'device/inode=' + st.ino + nl
  s += 'device/created=' + created + nl

  if (await setAttr(fd, ATTR, b4a.from('original'))) {
    s += 'device/attribute=original' + nl
  }

  await write(fd, b4a.from(s))

  if (!device.lock) await close(fd)
}

async function verifyDeviceFile(device) {
  let fd = 0

  try {
    fd = await open(device.filename, 'r+')
  } catch (e) {
    fd = 0
  }

  if (fd === 0) return false

  device.lock = device._lock ? new FDLock(fd, { wait: device._wait }) : null

  if (device.lock) {
    try {
      await device.lock.ready()
    } catch (err) {
      await device.lock.close()
      throw err
    }
  }

  const buf = await read(fd)
  const result = {}

  const s = b4a.toString(buf).trim().split('\n')

  let inode = 0
  let created = 0
  let attr = ''
  let platform = ''

  for (const ln of s) {
    const i = ln.indexOf('=')
    if (i === -1) continue

    const k = ln.slice(0, i).trim()
    const v = ln.slice(i + 1).trim()

    switch (k) {
      case 'device/platform':
        platform = v
        break
      case 'device/inode':
        inode = Number(v)
        break
      case 'device/created':
        created = Number(v)
        break
      case 'device/attribute':
        attr = v
        break
      default:
        result[k] = v
        break
    }
  }

  for (const [k, v] of Object.entries(device.data)) {
    if (v === null) continue
    if (result[k] === undefined) continue // allow upserts
    if (result[k] !== '' + v) {
      await teardown()
      throwDeviceFileError(`Invalid device file, ${k} has changed. Was ${result[k]}, is ${v}`, true)
    }
  }

  const st = await fstat(fd)
  const at = await getAttr(fd, ATTR)

  const sameAttr = b4a.toString(at || EMPTY) === attr
  const modified = Math.max(st.mtime.getTime(), st.birthtime.getTime())

  if (platform && platform !== PLATFORM) {
    await teardown()
    throwDeviceFileError('Invalid device file, was made on different platform', true)
  }

  if (!sameAttr) {
    await teardown()
    throwDeviceFileError('Invalid device file, was moved unsafely', true)
  }

  if (st.ino !== inode || (created && Math.abs(modified - created) >= MODIFIED_SLACK)) {
    await teardown()
    throwDeviceFileError('Invalid device file, was modified', true)
  }

  if (!device.lock) await close(fd)

  device.data = result
  return true

  async function teardown() {
    if (device.lock) await device.lock.close()
    else await close(fd)
  }
}

async function getAttr(fd, name) {
  try {
    return await fsx.getAttr(fd, name)
  } catch {
    return null
  }
}

async function setAttr(fd, name, value) {
  try {
    await fsx.setAttr(fd, name, value)
    return true
  } catch {
    return false
  }
}

function fstat(fd) {
  return new Promise((resolve, reject) => {
    fs.fstat(fd, (err, st) => {
      if (err) reject(err)
      resolve(st)
    })
  })
}

function close(fd) {
  return new Promise((resolve, reject) => {
    fs.close(fd, (err, st) => {
      if (err) reject(err)
      resolve(st)
    })
  })
}

function write(fd, buf) {
  return new Promise((resolve, reject) => {
    let offset = 0

    onwrite(null, 0)

    function onwrite(err, wrote) {
      if (err) return reject(err)
      if (offset === buf.byteLength) return resolve()
      offset += wrote
      fs.write(fd, buf, offset, buf.byteLength - offset, offset, onwrite)
    }
  })
}

function read(fd) {
  const buf = b4a.allocUnsafe(4096)

  return new Promise((resolve, reject) => {
    let offset = 0

    fs.read(fd, buf, 0, buf.byteLength, 0, onread)

    function onread(err, read) {
      if (err) return reject(err)
      if (read === 0) return resolve(buf.subarray(0, offset))
      offset += read
      fs.read(fd, buf, offset, buf.byteLength - offset, offset, onread)
    }
  })
}

function open(filename, flags) {
  return new Promise((resolve, reject) => {
    fs.open(filename, flags, (err, fd) => {
      if (err) reject(err)
      resolve(fd)
    })
  })
}

function throwDeviceFileError(message, fatal) {
  const err = new Error(message)
  err.code = 'DEVICE_FILE'
  err.fatal = fatal
  throw err
}
{
  "name": "device-file",
  "version": "2.3.1",
  "description": "Device only file",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.6.7",
    "bare-fs": "^4.0.1",
    "bare-path": "^3.0.0",
    "fd-lock": "^2.1.0",
    "fs-native-extensions": "^1.4.0",
    "ready-resource": "^1.2.0"
  },
  "devDependencies": {
    "brittle": "^3.13.1",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node --coverage test.js",
    "test:bare": "brittle-bare --coverage test.js"
  },
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    }
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/device-file.git"
  },
  "author": "Holepunch Inc",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/device-file/issues"
  },
  "homepage": "https://github.com/holepunchto/device-file"
}
module.exports = require('bare-events')
{
  "name": "events-universal",
  "version": "1.0.1",
  "description": "Universal wrapper for the Node.js events module",
  "exports": {
    "./package": "./package.json",
    ".": {
      "bare": "./bare.js",
      "react-native": "./react-native.js",
      "default": "./default.js"
    }
  },
  "files": [
    "index.js",
    "default.js",
    "bare.js",
    "react-native.js"
  ],
  "scripts": {
    "test": "prettier . --check"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/events-universal.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/events-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/events-universal#readme",
  "dependencies": {
    "bare-events": "^2.7.0"
  },
  "devDependencies": {
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^1.0.0"
  }
}
module.exports = class FixedFIFO {
  constructor (hwm) {
    if (!(hwm > 0) || ((hwm - 1) & hwm) !== 0) throw new Error('Max size for a FixedFIFO should be a power of two')
    this.buffer = new Array(hwm)
    this.mask = hwm - 1
    this.top = 0
    this.btm = 0
    this.next = null
  }

  clear () {
    this.top = this.btm = 0
    this.next = null
    this.buffer.fill(undefined)
  }

  push (data) {
    if (this.buffer[this.top] !== undefined) return false
    this.buffer[this.top] = data
    this.top = (this.top + 1) & this.mask
    return true
  }

  shift () {
    const last = this.buffer[this.btm]
    if (last === undefined) return undefined
    this.buffer[this.btm] = undefined
    this.btm = (this.btm + 1) & this.mask
    return last
  }

  peek () {
    return this.buffer[this.btm]
  }

  isEmpty () {
    return this.buffer[this.btm] === undefined
  }
}
const FixedFIFO = require('./fixed-size')

module.exports = class FastFIFO {
  constructor (hwm) {
    this.hwm = hwm || 16
    this.head = new FixedFIFO(this.hwm)
    this.tail = this.head
    this.length = 0
  }

  clear () {
    this.head = this.tail
    this.head.clear()
    this.length = 0
  }

  push (val) {
    this.length++
    if (!this.head.push(val)) {
      const prev = this.head
      this.head = prev.next = new FixedFIFO(2 * this.head.buffer.length)
      this.head.push(val)
    }
  }

  shift () {
    if (this.length !== 0) this.length--
    const val = this.tail.shift()
    if (val === undefined && this.tail.next) {
      const next = this.tail.next
      this.tail.next = null
      this.tail = next
      return this.tail.shift()
    }

    return val
  }

  peek () {
    const val = this.tail.peek()
    if (val === undefined && this.tail.next) return this.tail.next.peek()
    return val
  }

  isEmpty () {
    return this.length === 0
  }
}
{
  "name": "fast-fifo",
  "version": "1.3.2",
  "description": "A fast fifo implementation similar to the one powering nextTick in Node.js core",
  "main": "index.js",
  "files": [
    "./index.js",
    "./fixed-size.js"
  ],
  "dependencies": {},
  "devDependencies": {
    "standard": "^17.1.0",
    "brittle": "^3.3.2"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/fast-fifo.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/fast-fifo/issues"
  },
  "homepage": "https://github.com/mafintosh/fast-fifo"
}
const fs = require('fs')
const fsx = require('fs-native-extensions')
const onexit = require('resource-on-exit')
const ReadyResource = require('ready-resource')

module.exports = class FDLock extends ReadyResource {
  constructor(fd, opts = {}) {
    const { wait = false } = opts

    super()

    this._fd = fd
    this._wait = wait
    this._locked = false

    onexit.add(this, closeSync)
  }

  get locked() {
    return this._locked
  }

  async _open() {
    try {
      await this._resume()
    } catch (err) {
      onexit.remove(this)
      await close(this)
      throw err
    }
  }

  async _close() {
    onexit.remove(this)
    await close(this)
    this._locked = false
  }

  transfer() {
    const fd = this._fd
    if (fd === -1) throw new Error('Lock has already been transferred')
    this._fd = -1
    onexit.remove(this)
    return fd
  }

  async suspend() {
    if (!this.opened) await this.ready()
    return this._suspend()
  }

  async _suspend() {
    if (this._fd === -1 || this._locked === false) return
    fsx.unlock(this._fd)
    this._locked = false
  }

  async resume() {
    if (!this.opened) await this.ready()
    return this._resume()
  }

  async _resume() {
    if (this._fd === -1 || this._locked === true) return
    if (this._wait) await fsx.waitForLock(this._fd)
    else if (!fsx.tryLock(this._fd)) {
      throw new Error('File descriptor could not be locked')
    }
    this._locked = true
  }
}

function close(lock) {
  const fd = lock._fd
  if (fd === -1) return
  lock._fd = -1
  return new Promise((resolve) => fs.close(fd, () => resolve()))
}

function closeSync(lock) {
  const fd = lock._fd
  if (fd === -1) return
  lock._fd = -1
  lock._locked = false
  try {
    fs.closeSync(fd)
  } catch {}
}
{
  "name": "fd-lock",
  "version": "2.2.0",
  "description": "Stateful file descriptor locks for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": "./index.js"
  },
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    }
  },
  "files": [
    "index.js"
  ],
  "scripts": {
    "test": "npm run lint && npm run test:bare && npm run test:node",
    "test:bare": "bare test.js",
    "test:node": "node test.js",
    "lint": "prettier --check .",
    "format": "prettier --write ."
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/fd-lock.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/fd-lock/issues"
  },
  "homepage": "https://github.com/holepunchto/fd-lock#readme",
  "dependencies": {
    "bare-fs": "^4.5.0",
    "fs-native-extensions": "^1.4.4",
    "ready-resource": "^1.2.0",
    "resource-on-exit": "^1.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
exports.fullRoots = function (index, result) {
  if (index & 1) throw new Error('You can only look up roots for depth(0) blocks')
  if (!result) result = []

  index /= 2

  let offset = 0
  let factor = 1

  while (true) {
    if (!index) return result
    while (factor * 2 <= index) factor *= 2
    result.push(offset + factor - 1)
    offset = offset + 2 * factor
    index -= factor
    factor = 1
  }
}

exports.futureRoots = function (index, result) {
  if (index & 1) throw new Error('You can only look up future roots for depth(0) blocks')
  if (!result) result = []

  let factor = 1

  // make first root
  while (factor * 2 <= index) factor *= 2

  // full factor of 2 - done
  if (factor * 2 - 2 === index) return result

  let pos = factor / 2 - 1

  // while its not a full tree
  while ((pos + factor / 2 - 1) !== index) {
    pos += factor

    // read too far, to to left child
    while ((pos + factor / 2 - 1) > index) {
      factor /= 2
      pos -= factor / 2
    }

    // the "gap" is a future root
    result.push(pos - factor / 2)
  }

  return result
}

exports.patch = function (from, to) {
  if (from === 0 || from >= to) return []

  const roots = exports.fullRoots(from)
  const target = exports.fullRoots(to)

  // first find the first root that is different

  let i = 0
  for (; i < target.length; i++) {
    if (i >= roots.length || roots[i] !== target[i]) break
  }

  const patch = []

  if (i < roots.length) {
    // now we need to grow the newest root until it hits the diff one
    let prev = roots.length - 1

    const ite = exports.iterator(roots[prev--])

    while (ite.index !== target[i]) {
      ite.sibling()

      if (prev >= 0 && ite.index === roots[prev]) {
        prev--
      } else {
        patch.push(ite.index)
      }

      patch.push(ite.parent())
    }

    i++ // patched to next root, so inc
  }

  // include the rest

  for (; i < target.length; i++) patch.push(target[i])

  return patch
}

exports.depth = function (index) {
  let depth = 0

  index += 1
  while (!(index & 1)) {
    depth++
    index = rightShift(index)
  }

  return depth
}

exports.sibling = function (index, depth) {
  if (!depth) depth = exports.depth(index)
  const offset = exports.offset(index, depth)

  return exports.index(depth, offset & 1 ? offset - 1 : offset + 1)
}

exports.parent = function (index, depth) {
  if (!depth) depth = exports.depth(index)
  const offset = exports.offset(index, depth)

  return exports.index(depth + 1, rightShift(offset))
}

exports.leftChild = function (index, depth) {
  if (!(index & 1)) return -1
  if (!depth) depth = exports.depth(index)
  return exports.index(depth - 1, exports.offset(index, depth) * 2)
}

exports.rightChild = function (index, depth) {
  if (!(index & 1)) return -1
  if (!depth) depth = exports.depth(index)
  return exports.index(depth - 1, 1 + (exports.offset(index, depth) * 2))
}

exports.children = function (index, depth) {
  if (!(index & 1)) return null

  if (!depth) depth = exports.depth(index)
  const offset = exports.offset(index, depth) * 2

  return [
    exports.index(depth - 1, offset),
    exports.index(depth - 1, offset + 1)
  ]
}

exports.leftSpan = function (index, depth) {
  if (!(index & 1)) return index
  if (!depth) depth = exports.depth(index)
  return exports.offset(index, depth) * twoPow(depth + 1)
}

exports.rightSpan = function (index, depth) {
  if (!(index & 1)) return index
  if (!depth) depth = exports.depth(index)
  return (exports.offset(index, depth) + 1) * twoPow(depth + 1) - 2
}

exports.nextLeaf = function (index) {
  let factor = 1
  let r = index

  while ((r & 1) === 1) {
    r = (r - 1) / 2
    factor *= 2
  }

  return index + factor + 1
}

exports.count = function (index, depth) {
  if (!(index & 1)) return 1
  if (!depth) depth = exports.depth(index)
  return twoPow(depth + 1) - 1
}

exports.countLeaves = function (index) {
  return (exports.count(index) + 1) / 2
}

exports.spans = function (index, depth) {
  if (!(index & 1)) return [index, index]
  if (!depth) depth = exports.depth(index)

  const offset = exports.offset(index, depth)
  const width = twoPow(depth + 1)

  return [offset * width, (offset + 1) * width - 2]
}

exports.index = function (depth, offset) {
  return (1 + 2 * offset) * twoPow(depth) - 1
}

exports.offset = function (index, depth) {
  if (!(index & 1)) return index / 2
  if (!depth) depth = exports.depth(index)

  return ((index + 1) / twoPow(depth) - 1) / 2
}

exports.iterator = function (index) {
  const ite = new Iterator()
  ite.seek(index || 0)
  return ite
}

function twoPow (n) {
  return n < 31 ? 1 << n : ((1 << 30) * (1 << (n - 30)))
}

function rightShift (n) {
  return (n - (n & 1)) / 2
}

function Iterator () {
  this.index = 0
  this.offset = 0
  this.factor = 0
}

Iterator.prototype.seek = function (index) {
  this.index = index
  if (this.index & 1) {
    this.offset = exports.offset(index)
    this.factor = twoPow(exports.depth(index) + 1)
  } else {
    this.offset = index / 2
    this.factor = 2
  }
}

Iterator.prototype.isLeft = function () {
  return (this.offset & 1) === 0
}

Iterator.prototype.isRight = function () {
  return (this.offset & 1) === 1
}

Iterator.prototype.isRoot = function (length) {
  const currentLength = 1 + (this.index + this.factor / 2 - 1) / 2
  if (length < currentLength) return false

  const factor = this.factor * 2
  const index = (this.offset & 1)
    ? this.index - this.factor / 2
    : this.index + this.factor / 2

  const parentLength = 1 + (index + factor / 2 - 1) / 2
  return parentLength > length
}

Iterator.prototype.contains = function (index) {
  return index > this.index
    ? index < (this.index + this.factor / 2)
    : index < this.index
      ? index > (this.index - this.factor / 2)
      : true
}

Iterator.prototype.prev = function () {
  if (!this.offset) return this.index
  this.offset--
  this.index -= this.factor
  return this.index
}

Iterator.prototype.next = function () {
  this.offset++
  this.index += this.factor
  return this.index
}

Iterator.prototype.count = function () {
  if (!(this.index & 1)) return 1
  return this.factor - 1
}

Iterator.prototype.countLeaves = function () {
  return (this.count() + 1) / 2
}

Iterator.prototype.sibling = function () {
  return this.isLeft() ? this.next() : this.prev()
}

Iterator.prototype.parent = function () {
  if (this.offset & 1) {
    this.index -= this.factor / 2
    this.offset = (this.offset - 1) / 2
  } else {
    this.index += this.factor / 2
    this.offset /= 2
  }
  this.factor *= 2
  return this.index
}

Iterator.prototype.leftSpan = function () {
  this.index = this.index - this.factor / 2 + 1
  this.offset = this.index / 2
  this.factor = 2
  return this.index
}

Iterator.prototype.peekLeftSpan = function () {
  return this.index - this.factor / 2 + 1
}

Iterator.prototype.rightSpan = function () {
  this.index = this.index + this.factor / 2 - 1
  this.offset = this.index / 2
  this.factor = 2
  return this.index
}

Iterator.prototype.peekRightSpan = function () {
  return this.index + this.factor / 2 - 1
}

Iterator.prototype.leftChild = function () {
  if (this.factor === 2) return this.index
  this.factor /= 2
  this.index -= this.factor / 2
  this.offset *= 2
  return this.index
}

Iterator.prototype.rightChild = function () {
  if (this.factor === 2) return this.index
  this.factor /= 2
  this.index += this.factor / 2
  this.offset = 2 * this.offset + 1
  return this.index
}

Iterator.prototype.nextTree = function () {
  this.index = this.index + this.factor / 2 + 1
  this.offset = this.index / 2
  this.factor = 2
  return this.index
}

Iterator.prototype.prevTree = function () {
  if (!this.offset) {
    this.index = 0
    this.factor = 2
  } else {
    this.index = this.index - this.factor / 2 - 1
    this.offset = this.index / 2
    this.factor = 2
  }
  return this.index
}

Iterator.prototype.fullRoot = function (index) {
  if (index <= this.index || (this.index & 1) > 0) return false
  while (index > this.index + this.factor + this.factor / 2) {
    this.index += this.factor / 2
    this.factor *= 2
    this.offset /= 2
  }
  return true
}
{
  "name": "flat-tree",
  "version": "1.13.0",
  "description": "A series of functions to map a binary tree to a list",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {},
  "devDependencies": {
    "brittle": "^3.3.2",
    "standard": "^17.1.0"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/flat-tree.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/flat-tree/issues"
  },
  "homepage": "https://github.com/mafintosh/flat-tree"
}
require.addon = require('require-addon')

module.exports = require.addon('.', __filename)
const { isWindows } = require('which-runtime')
const binding = require('./binding')

function onwork(err, result) {
  if (err) this.reject(err)
  else this.resolve(result)
}

exports.tryLock = function tryLock(fd, offset = 0, length = 0, opts = {}) {
  if (typeof offset === 'object') {
    opts = offset
    offset = 0
  }

  if (typeof length === 'object') {
    opts = length
    length = 0
  }

  if (typeof opts !== 'object' || opts === null) {
    opts = {}
  }

  try {
    binding.tryLock(fd, offset, length, opts.shared !== true)
  } catch (err) {
    if (err.code === 'EAGAIN') return false
    throw err
  }

  return true
}

exports.waitForLock = function waitForLock(fd, offset = 0, length = 0, opts = {}) {
  if (typeof offset === 'object') {
    opts = offset
    offset = 0
  }

  if (typeof length === 'object') {
    opts = length
    length = 0
  }

  if (typeof opts !== 'object' || opts === null) {
    opts = {}
  }

  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.waitForLock(fd, offset, length, opts.shared !== true, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.waitForLockSync = function waitForLockSync(fd, offset = 0, length = 0, opts = {}) {
  if (typeof offset === 'object') {
    opts = offset
    offset = 0
  }

  if (typeof length === 'object') {
    opts = length
    length = 0
  }

  if (typeof opts !== 'object' || opts === null) {
    opts = {}
  }

  binding.waitForLockSync(fd, offset, length, opts.shared !== true)
}

exports.tryDowngradeLock = function tryDowngradeLock(fd, offset = 0, length = 0) {
  try {
    binding.tryDowngradeLock(fd, offset, length)
  } catch (err) {
    if (err.code === 'EAGAIN') return false
    throw err
  }

  return true
}

exports.waitForDowngradeLock = function downgradeLock(fd, offset = 0, length = 0) {
  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.waitForDowngradeLock(fd, offset, length, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.waitForDowngradeLockSync = function waitForDowngradeLockSync(fd, offset = 0, length = 0) {
  binding.waitForDowngradeLockSync(fd, offset, length)
}

exports.tryUpgradeLock = function tryUpgradeLock(fd, offset = 0, length = 0) {
  try {
    binding.tryUpgradeLock(fd, offset, length)
  } catch (err) {
    if (err.code === 'EAGAIN') return false
    throw err
  }

  return true
}

exports.waitForUpgradeLock = function upgradeLock(fd, offset = 0, length = 0) {
  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.waitForUpgradeLock(fd, offset, length, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.waitForUpgradeLockSync = function waitForUpgradeLockSync(fd, offset = 0, length = 0) {
  binding.waitForUpgradeLockSync(fd, offset, length)
}

exports.unlock = function unlock(fd, offset = 0, length = 0) {
  binding.unlock(fd, offset, length)
}

exports.trim = function trim(fd, offset, length) {
  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.trim(fd, offset, length, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.trimSync = function trimSync(fd, offset, length) {
  binding.trimSync(fd, offset, length)
}

exports.sparse = function sparse(fd) {
  // Short circuit on everything but Windows
  if (!isWindows) return Promise.resolve()

  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.sparse(fd, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.sparseSync = function sparseSync(fd) {
  // Short circuit on everything but Windows
  if (!isWindows) return

  binding.sparseSync(fd)
}

exports.swap = function swap(from, to) {
  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.swap(from, to, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.swapSync = function swapSync(from, to) {
  binding.swapSync(from, to)
}

exports.getAttr = function getAttr(fd, name) {
  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.getAttr(fd, name, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise.then((buffer) => (buffer === null ? null : Buffer.from(buffer)))
}

exports.getAttrSync = function getAttrSync(fd, name) {
  const buffer = binding.getAttrSync(fd, name)
  return buffer === null ? null : Buffer.from(buffer)
}

exports.setAttr = function setAttr(fd, name, value, encoding) {
  if (typeof value === 'string') value = Buffer.from(value, encoding)

  const req = {
    value,
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.setAttr(
      fd,
      name,
      value.buffer,
      value.byteOffset,
      value.byteLength,
      req,
      onwork
    )
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.setAttrSync = function setAttrSync(fd, name, value, encoding) {
  if (typeof value === 'string') value = Buffer.from(value, encoding)

  binding.setAttrSync(fd, name, value.buffer, value.byteOffset, value.byteLength)
}

exports.removeAttr = function removeAttr(fd, name) {
  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.removeAttr(fd, name, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.removeAttrSync = function removeAttrSync(fd, name) {
  binding.removeAttrSync(fd, name)
}

exports.listAttrs = function listAttrs(fd) {
  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.listAttrs(fd, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.listAttrsSync = function listAttrsSync(fd) {
  return binding.listAttrsSync(fd)
}
{
  "name": "fs-native-extensions",
  "version": "1.5.0",
  "description": "Native file system extensions for advanced file operations",
  "main": "index.js",
  "files": [
    "index.js",
    "macros.h",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "include",
    "src",
    "prebuilds"
  ],
  "imports": {
    "child_process": {
      "bare": "bare-subprocess",
      "default": "child_process"
    },
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "fs/*": {
      "bare": "bare-fs/*",
      "default": "fs/*"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    }
  },
  "addon": true,
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:bare": "brittle-bare --coverage test.js",
    "test:node": "brittle-node --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/fs-native-extensions.git"
  },
  "author": "Kasper Isager Dalsgarð <kasper@funktionel.co>",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/fs-native-extensions/issues"
  },
  "homepage": "https://github.com/holepunchto/fs-native-extensions#readme",
  "dependencies": {
    "require-addon": "^1.1.0",
    "which-runtime": "^1.2.0"
  },
  "devDependencies": {
    "bare-compat-napi": "^1.3.8",
    "bare-fs": "^4.4.4",
    "bare-path": "^3.0.0",
    "bare-subprocess": "^4.0.5",
    "brittle": "^3.1.1",
    "cmake-bare": "^1.1.10",
    "cmake-fetch": "^1.4.7",
    "cmake-napi": "^1.0.5",
    "cmake-npm": "^1.1.0",
    "lunte": "^1.6.0",
    "minimist": "^1.2.6",
    "prettier": "^3.5.3",
    "prettier-config-holepunch": "^2.0.0",
    "test-tmp": "^1.2.1"
  }
}
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const b4a = require('b4a')

// https://en.wikipedia.org/wiki/Merkle_tree#Second_preimage_attack
const LEAF_TYPE = b4a.from([0])
const PARENT_TYPE = b4a.from([1])
const ROOT_TYPE = b4a.from([2])

const HYPERCORE = b4a.from('hypercore')

exports.keyPair = function (seed) {
  // key pairs might stay around for a while, so better not to use a default slab to avoid retaining it completely
  const slab = b4a.allocUnsafeSlow(
    sodium.crypto_sign_PUBLICKEYBYTES + sodium.crypto_sign_SECRETKEYBYTES
  )
  const publicKey = slab.subarray(0, sodium.crypto_sign_PUBLICKEYBYTES)
  const secretKey = slab.subarray(sodium.crypto_sign_PUBLICKEYBYTES)

  if (seed) sodium.crypto_sign_seed_keypair(publicKey, secretKey, seed)
  else sodium.crypto_sign_keypair(publicKey, secretKey)

  return {
    publicKey,
    secretKey
  }
}

exports.validateKeyPair = function (keyPair) {
  const pk = b4a.allocUnsafe(sodium.crypto_sign_PUBLICKEYBYTES)
  sodium.crypto_sign_ed25519_sk_to_pk(pk, keyPair.secretKey)
  return b4a.equals(pk, keyPair.publicKey)
}

exports.sign = function (message, secretKey) {
  // Dedicated slab for the signature, to avoid retaining unneeded mem and for security
  const signature = b4a.allocUnsafeSlow(sodium.crypto_sign_BYTES)
  sodium.crypto_sign_detached(signature, message, secretKey)
  return signature
}

exports.verify = function (message, signature, publicKey) {
  if (signature.byteLength !== sodium.crypto_sign_BYTES) return false
  if (publicKey.byteLength !== sodium.crypto_sign_PUBLICKEYBYTES) return false
  return sodium.crypto_sign_verify_detached(signature, message, publicKey)
}

exports.encrypt = function (message, publicKey) {
  const ciphertext = b4a.alloc(message.byteLength + sodium.crypto_box_SEALBYTES)
  sodium.crypto_box_seal(ciphertext, message, publicKey)
  return ciphertext
}

exports.decrypt = function (ciphertext, keyPair) {
  if (ciphertext.byteLength < sodium.crypto_box_SEALBYTES) return null

  const plaintext = b4a.alloc(ciphertext.byteLength - sodium.crypto_box_SEALBYTES)

  if (!sodium.crypto_box_seal_open(plaintext, ciphertext, keyPair.publicKey, keyPair.secretKey)) {
    return null
  }

  return plaintext
}

exports.encryptionKeyPair = function (seed) {
  const publicKey = b4a.alloc(sodium.crypto_box_PUBLICKEYBYTES)
  const secretKey = b4a.alloc(sodium.crypto_box_SECRETKEYBYTES)

  if (seed) {
    sodium.crypto_box_seed_keypair(publicKey, secretKey, seed)
  } else {
    sodium.crypto_box_keypair(publicKey, secretKey)
  }

  return {
    publicKey,
    secretKey
  }
}

exports.data = function (data) {
  const out = b4a.allocUnsafe(32)

  sodium.crypto_generichash_batch(out, [LEAF_TYPE, c.encode(c.uint64, data.byteLength), data])

  return out
}

exports.parent = function (a, b) {
  if (a.index > b.index) {
    const tmp = a
    a = b
    b = tmp
  }

  const out = b4a.allocUnsafe(32)

  sodium.crypto_generichash_batch(out, [
    PARENT_TYPE,
    c.encode(c.uint64, a.size + b.size),
    a.hash,
    b.hash
  ])

  return out
}

exports.tree = function (roots, out) {
  const buffers = new Array(3 * roots.length + 1)
  let j = 0

  buffers[j++] = ROOT_TYPE

  for (let i = 0; i < roots.length; i++) {
    const r = roots[i]
    buffers[j++] = r.hash
    buffers[j++] = c.encode(c.uint64, r.index)
    buffers[j++] = c.encode(c.uint64, r.size)
  }

  if (!out) out = b4a.allocUnsafe(32)
  sodium.crypto_generichash_batch(out, buffers)
  return out
}

exports.hash = function (data, out) {
  if (!out) out = b4a.allocUnsafe(32)
  if (!Array.isArray(data)) data = [data]

  sodium.crypto_generichash_batch(out, data)

  return out
}

exports.randomBytes = function (n) {
  const buf = b4a.allocUnsafe(n)
  sodium.randombytes_buf(buf)
  return buf
}

exports.discoveryKey = function (key) {
  if (!key || key.byteLength !== 32) throw new Error('Must pass a 32 byte buffer')
  // Discovery keys might stay around for a while, so better not to use slab memory (for better gc)
  const digest = b4a.allocUnsafeSlow(32)
  sodium.crypto_generichash(digest, HYPERCORE, key)
  return digest
}

if (sodium.sodium_free) {
  exports.free = function (secureBuf) {
    if (secureBuf.secure) sodium.sodium_free(secureBuf)
  }
} else {
  exports.free = function () {}
}

exports.namespace = function (name, count) {
  const ids = typeof count === 'number' ? range(count) : count

  // Namespaces are long-lived, so better to use a dedicated slab
  const buf = b4a.allocUnsafeSlow(32 * ids.length)

  const list = new Array(ids.length)

  // ns is ephemeral, so default slab
  const ns = b4a.allocUnsafe(33)
  sodium.crypto_generichash(ns.subarray(0, 32), typeof name === 'string' ? b4a.from(name) : name)

  for (let i = 0; i < list.length; i++) {
    list[i] = buf.subarray(32 * i, 32 * i + 32)
    ns[32] = ids[i]
    sodium.crypto_generichash(list[i], ns)
  }

  return list
}

function range(count) {
  const arr = new Array(count)
  for (let i = 0; i < count; i++) arr[i] = i
  return arr
}
{
  "name": "hypercore-crypto",
  "version": "3.7.0",
  "description": "The crypto primitives used in hypercore, extracted into a separate module",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.6.6",
    "compact-encoding": "^3.0.0",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "brittle": "^3.5.0",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/hypercore-crypto.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/hypercore-crypto/issues"
  },
  "homepage": "https://github.com/mafintosh/hypercore-crypto"
}
const IdEnc = require('hypercore-id-encoding')

module.exports = class HypercoreError extends Error {
  constructor (msg, code, fn = HypercoreError, discoveryKey = null) {
    if (discoveryKey) msg = `${msg} (discovery key: ${IdEnc.normalize(discoveryKey)})`
    super(`${code}: ${msg}`)

    this.code = code
    this.discoveryKey = discoveryKey

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name () {
    return 'HypercoreError'
  }

  static ASSERTION (msg, discoveryKey = null) { // ERR_ASSERTION is picked up by safety-catch also
    return new HypercoreError(msg, 'ERR_ASSERTION', HypercoreError.ASSERT, discoveryKey)
  }

  static BAD_ARGUMENT (msg, discoveryKey = null) {
    return new HypercoreError(msg, 'BAD_ARGUMENT', HypercoreError.BAD_ARGUMENT, discoveryKey)
  }

  static STORAGE_EMPTY (msg, discoveryKey = null) {
    return new HypercoreError(msg, 'STORAGE_EMPTY', HypercoreError.STORAGE_EMPTY, discoveryKey)
  }

  static STORAGE_CONFLICT (msg, discoveryKey = null) {
    return new HypercoreError(msg, 'STORAGE_CONFLICT', HypercoreError.STORAGE_CONFLICT, discoveryKey)
  }

  static INVALID_SIGNATURE (msg, discoveryKey = null) {
    return new HypercoreError(msg, 'INVALID_SIGNATURE', HypercoreError.INVALID_SIGNATURE, discoveryKey)
  }

  static INVALID_CAPABILITY (msg, discoveryKey = null) {
    return new HypercoreError(msg, 'INVALID_CAPABILITY', HypercoreError.INVALID_CAPABILITY, discoveryKey)
  }

  static INVALID_CHECKSUM (msg = 'Invalid checksum', discoveryKey = null) {
    return new HypercoreError(msg, 'INVALID_CHECKSUM', HypercoreError.INVALID_CHECKSUM, discoveryKey)
  }

  static INVALID_OPERATION (msg, discoveryKey = null) {
    return new HypercoreError(msg, 'INVALID_OPERATION', HypercoreError.INVALID_OPERATION, discoveryKey)
  }

  static INVALID_PROOF (msg = 'Proof not verifiable', discoveryKey = null) {
    return new HypercoreError(msg, 'INVALID_PROOF', HypercoreError.INVALID_PROOF, discoveryKey)
  }

  static BLOCK_NOT_AVAILABLE (msg = 'Block is not available', discoveryKey = null) {
    return new HypercoreError(msg, 'BLOCK_NOT_AVAILABLE', HypercoreError.BLOCK_NOT_AVAILABLE, discoveryKey)
  }

  static SNAPSHOT_NOT_AVAILABLE (msg = 'Snapshot is not available', discoveryKey = null) {
    return new HypercoreError(msg, 'SNAPSHOT_NOT_AVAILABLE', HypercoreError.SNAPSHOT_NOT_AVAILABLE, discoveryKey)
  }

  static REQUEST_CANCELLED (msg = 'Request was cancelled', discoveryKey = null) {
    return new HypercoreError(msg, 'REQUEST_CANCELLED', HypercoreError.REQUEST_CANCELLED, discoveryKey)
  }

  static REQUEST_TIMEOUT (msg = 'Request timed out', discoveryKey = null) {
    return new HypercoreError(msg, 'REQUEST_TIMEOUT', HypercoreError.REQUEST_TIMEOUT, discoveryKey)
  }

  static SESSION_NOT_WRITABLE (msg = 'Session is not writable', discoveryKey = null) {
    return new HypercoreError(msg, 'SESSION_NOT_WRITABLE', HypercoreError.SESSION_NOT_WRITABLE, discoveryKey)
  }

  static SESSION_CLOSED (msg = 'Session is closed', discoveryKey = null) {
    return new HypercoreError(msg, 'SESSION_CLOSED', HypercoreError.SESSION_CLOSED, discoveryKey)
  }

  static BATCH_UNFLUSHED (msg = 'Batch not yet flushed', discoveryKey = null) {
    return new HypercoreError(msg, 'BATCH_UNFLUSHED', HypercoreError.BATCH_UNFLUSHED, discoveryKey)
  }

  static BATCH_ALREADY_EXISTS (msg = 'Batch already exists', discoveryKey = null) {
    return new HypercoreError(msg, 'BATCH_ALREADY_EXISTS', HypercoreError.BATCH_ALREADY_EXISTS, discoveryKey)
  }

  static BATCH_ALREADY_FLUSHED (msg = 'Batch has already been flushed', discoveryKey = null) {
    return new HypercoreError(msg, 'BATCH_ALREADY_FLUSHED', HypercoreError.BATCH_ALREADY_FLUSHED, discoveryKey)
  }

  static OPLOG_CORRUPT (msg = 'Oplog file appears corrupt or out of date', discoveryKey = null) {
    return new HypercoreError(msg, 'OPLOG_CORRUPT', HypercoreError.OPLOG_CORRUPT, discoveryKey)
  }

  static OPLOG_HEADER_OVERFLOW (msg = 'Oplog header exceeds page size', discoveryKey = null) {
    return new HypercoreError(msg, 'OPLOG_HEADER_OVERFLOW', HypercoreError.OPLOG_HEADER_OVERFLOW, discoveryKey)
  }

  static INVALID_OPLOG_VERSION (msg = 'Invalid header version', discoveryKey = null) {
    return new HypercoreError(msg, 'INVALID_OPLOG_VERSION', HypercoreError.INVALID_OPLOG_VERSION, discoveryKey)
  }

  static WRITE_FAILED (msg = 'Write to storage failed', discoveryKey = null) {
    return new HypercoreError(msg, 'WRITE_FAILED', HypercoreError.WRITE_FAILED, discoveryKey)
  }

  static DECODING_ERROR (msg = 'Decoding error', discoveryKey = null) {
    return new HypercoreError(msg, 'DECODING_ERROR', HypercoreError.DECODING_ERROR, discoveryKey)
  }

  static SESSION_MOVED (msg = 'Session moved', discoveryKey = null) {
    return new HypercoreError(msg, 'SESSION_MOVED', HypercoreError.SESSION_MOVED, discoveryKey)
  }
}
{
  "name": "hypercore-errors",
  "version": "1.5.0",
  "description": "Hypercore errors",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/hypercore-errors.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/hypercore-errors/issues"
  },
  "homepage": "https://github.com/holepunchto/hypercore-errors#readme",
  "devDependencies": {
    "b4a": "^1.6.7",
    "brittle": "^3.1.3",
    "standard": "^17.0.0"
  },
  "dependencies": {
    "hypercore-id-encoding": "^1.3.0"
  }
}
const z32 = require('z32')
const b4a = require('b4a')

module.exports = {
  encode,
  decode,
  normalize,
  isValid
}

function encode (key) {
  if (!b4a.isBuffer(key)) throw new Error('Key must be a Buffer')
  if (key.byteLength !== 32) throw new Error('Key must be 32-bytes long')
  return z32.encode(key)
}

function decode (id) {
  if (b4a.isBuffer(id)) {
    if (id.byteLength !== 32) throw new Error('ID must be 32-bytes long')
    return id
  }
  if (typeof id === 'string') {
    if (id.startsWith('pear://')) id = id.slice(7).split('/')[0]
    if (id.length === 52) return z32.decode(id)
    if (id.length === 64) {
      const buf = b4a.from(id, 'hex')
      if (buf.byteLength === 32) return buf
    }
  }
  throw new Error('Invalid Hypercore key')
}

function normalize (any) {
  return encode(decode(any))
}

function isValid (any) {
  try {
    decode(any)
    return true
  } catch {
    return false
  }
}
{
  "name": "hypercore-id-encoding",
  "version": "1.3.0",
  "description": "Convert Hypercore keys to/from z-base32 or hex",
  "main": "index.js",
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.5.3",
    "z32": "^1.0.0"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "hypercore": "^10.0.0",
    "random-access-memory": "^6.0.0",
    "standard": "^17.1.0"
  },
  "license": "Apache-2.0",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/hypercore-id-encoding.git"
  },
  "keywords": [],
  "author": "",
  "bugs": {
    "url": "https://github.com/holepunchto/hypercore-id-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/hypercore-id-encoding#readme"
}
function headLegacyMap(m) {
  return {
    version: 2, // version bumped from 1
    cores: m.allocated.cores,
    datas: m.allocated.datas,
    groups: 0,
    seed: m.seed,
    defaultDiscoveryKey: m.defaultDiscoveryKey
  }
}

module.exports = {
  headLegacyMap
}
// This file is autogenerated by the hyperschema compiler
// Schema Version: 2
/* eslint-disable camelcase */
/* eslint-disable quotes */
/* eslint-disable space-before-function-paren */

const { c } = require('hyperschema/runtime')
const external0 = require('../../external.js')

const VERSION = 2

// eslint-disable-next-line no-unused-vars
let version = VERSION

// @corestore/allocated
const encoding0 = {
  preencode(state, m) {
    c.uint.preencode(state, m.cores)
    c.uint.preencode(state, m.datas)
  },
  encode(state, m) {
    c.uint.encode(state, m.cores)
    c.uint.encode(state, m.datas)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const r1 = c.uint.decode(state)

    return {
      cores: r0,
      datas: r1
    }
  }
}

// @corestore/head-v1
const encoding1 = {
  preencode(state, m) {
    state.end++ // max flag is 4 so always one byte

    if (m.allocated) encoding0.preencode(state, m.allocated)
    if (m.seed) c.fixed32.preencode(state, m.seed)
    if (m.defaultDiscoveryKey) c.fixed32.preencode(state, m.defaultDiscoveryKey)
  },
  encode(state, m) {
    const flags = (m.allocated ? 1 : 0) | (m.seed ? 2 : 0) | (m.defaultDiscoveryKey ? 4 : 0)

    c.uint.encode(state, flags)

    if (m.allocated) encoding0.encode(state, m.allocated)
    if (m.seed) c.fixed32.encode(state, m.seed)
    if (m.defaultDiscoveryKey) c.fixed32.encode(state, m.defaultDiscoveryKey)
  },
  decode(state) {
    const v = c.uint.decode(state)
    const flags = c.uint.decode(state)

    return {
      version: v,
      allocated: (flags & 1) !== 0 ? encoding0.decode(state) : null,
      seed: (flags & 2) !== 0 ? c.fixed32.decode(state) : null,
      defaultDiscoveryKey: (flags & 4) !== 0 ? c.fixed32.decode(state) : null
    }
  }
}

// @corestore/head-v2
const encoding2 = {
  preencode(state, m) {
    c.uint.preencode(state, m.cores)
    c.uint.preencode(state, m.datas)
    c.uint.preencode(state, m.groups)
    state.end++ // max flag is 2 so always one byte

    if (m.seed) c.fixed32.preencode(state, m.seed)
    if (m.defaultDiscoveryKey) c.fixed32.preencode(state, m.defaultDiscoveryKey)
  },
  encode(state, m) {
    const flags = (m.seed ? 1 : 0) | (m.defaultDiscoveryKey ? 2 : 0)

    c.uint.encode(state, m.cores)
    c.uint.encode(state, m.datas)
    c.uint.encode(state, m.groups)
    c.uint.encode(state, flags)

    if (m.seed) c.fixed32.encode(state, m.seed)
    if (m.defaultDiscoveryKey) c.fixed32.encode(state, m.defaultDiscoveryKey)
  },
  decode(state) {
    const v = c.uint.decode(state)
    const r0 = c.uint.decode(state)
    const r1 = c.uint.decode(state)
    const r2 = c.uint.decode(state)
    const flags = c.uint.decode(state)

    return {
      version: v,
      cores: r0,
      datas: r1,
      groups: r2,
      seed: (flags & 1) !== 0 ? c.fixed32.decode(state) : null,
      defaultDiscoveryKey: (flags & 2) !== 0 ? c.fixed32.decode(state) : null
    }
  }
}

// @corestore/head
const encoding3 = {
  preencode(state, m) {
    c.uint.preencode(state, m.version)
    switch (m.version) {
      case 0:
      case 1:
        encoding1.preencode(state, m)
        break
      case 2:
        encoding2.preencode(state, m)
        break
      default:
        throw new Error('Unsupported version')
    }
  },
  encode(state, m) {
    c.uint.encode(state, m.version)
    switch (m.version) {
      case 0:
      case 1:
        encoding1.encode(state, m)
        break
      case 2:
        encoding2.encode(state, m)
        break
      default:
        throw new Error('Unsupported version')
    }
  },
  decode(state) {
    const start = state.start
    const v = c.uint.decode(state)
    state.start = start
    switch (v) {
      case 0:
      case 1: {
        const decoded = encoding1.decode(state)
        const map = external0.headLegacyMap
        return map(decoded)
      }
      case 2: {
        const decoded = encoding2.decode(state)
        return decoded
      }
      default:
        throw new Error('Unsupported version')
    }
  }
}

// @corestore/alias
const encoding4 = {
  preencode(state, m) {
    c.string.preencode(state, m.name)
    c.fixed32.preencode(state, m.namespace)
  },
  encode(state, m) {
    c.string.encode(state, m.name)
    c.fixed32.encode(state, m.namespace)
  },
  decode(state) {
    const r0 = c.string.decode(state)
    const r1 = c.fixed32.decode(state)

    return {
      name: r0,
      namespace: r1
    }
  }
}

// @corestore/core
const encoding5 = {
  preencode(state, m) {
    c.uint.preencode(state, m.version)
    c.uint.preencode(state, m.corePointer)
    c.uint.preencode(state, m.dataPointer)
    state.end++ // max flag is 1 so always one byte

    if (m.alias) encoding4.preencode(state, m.alias)
  },
  encode(state, m) {
    const flags = m.alias ? 1 : 0

    c.uint.encode(state, m.version)
    c.uint.encode(state, m.corePointer)
    c.uint.encode(state, m.dataPointer)
    c.uint.encode(state, flags)

    if (m.alias) encoding4.encode(state, m.alias)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const r1 = c.uint.decode(state)
    const r2 = c.uint.decode(state)
    const flags = c.uint.decode(state)

    return {
      version: r0,
      corePointer: r1,
      dataPointer: r2,
      alias: (flags & 1) !== 0 ? encoding4.decode(state) : null
    }
  }
}

const encoding6_enum = {
  blake2b: 'blake2b'
}

// @core/hashes enum
const encoding6 = {
  preencode(state, m) {
    state.end++ // max enum is 0 so always one byte
  },
  encode(state, m) {
    switch (m) {
      case 'blake2b':
        c.uint.encode(state, 0)
        break
      default:
        throw new Error('Unknown enum')
    }
  },
  decode(state) {
    switch (c.uint.decode(state)) {
      case 0:
        return 'blake2b'
      default:
        return null
    }
  }
}

const encoding7_enum = {
  ed25519: 'ed25519'
}

// @core/signatures enum
const encoding7 = {
  preencode(state, m) {
    state.end++ // max enum is 0 so always one byte
  },
  encode(state, m) {
    switch (m) {
      case 'ed25519':
        c.uint.encode(state, 0)
        break
      default:
        throw new Error('Unknown enum')
    }
  },
  decode(state) {
    switch (c.uint.decode(state)) {
      case 0:
        return 'ed25519'
      default:
        return null
    }
  }
}

// @core/tree-node
const encoding8 = {
  preencode(state, m) {
    c.uint.preencode(state, m.index)
    c.uint.preencode(state, m.size)
    c.fixed32.preencode(state, m.hash)
  },
  encode(state, m) {
    c.uint.encode(state, m.index)
    c.uint.encode(state, m.size)
    c.fixed32.encode(state, m.hash)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const r1 = c.uint.decode(state)
    const r2 = c.fixed32.decode(state)

    return {
      index: r0,
      size: r1,
      hash: r2
    }
  }
}

// @core/signer
const encoding9 = {
  preencode(state, m) {
    encoding7.preencode(state, m.signature)
    c.fixed32.preencode(state, m.namespace)
    c.fixed32.preencode(state, m.publicKey)
  },
  encode(state, m) {
    encoding7.encode(state, m.signature)
    c.fixed32.encode(state, m.namespace)
    c.fixed32.encode(state, m.publicKey)
  },
  decode(state) {
    const r0 = encoding7.decode(state)
    const r1 = c.fixed32.decode(state)
    const r2 = c.fixed32.decode(state)

    return {
      signature: r0,
      namespace: r1,
      publicKey: r2
    }
  }
}

// @core/prologue
const encoding10 = {
  preencode(state, m) {
    c.fixed32.preencode(state, m.hash)
    c.uint.preencode(state, m.length)
  },
  encode(state, m) {
    c.fixed32.encode(state, m.hash)
    c.uint.encode(state, m.length)
  },
  decode(state) {
    const r0 = c.fixed32.decode(state)
    const r1 = c.uint.decode(state)

    return {
      hash: r0,
      length: r1
    }
  }
}

// @core/manifest.signers
const encoding11_4 = c.array(encoding9)
// @core/manifest.linked
const encoding11_6 = c.array(c.fixed32)

// @core/manifest
const encoding11 = {
  preencode(state, m) {
    c.uint.preencode(state, m.version)
    state.end++ // max flag is 8 so always one byte
    encoding6.preencode(state, m.hash)
    c.uint.preencode(state, m.quorum)
    encoding11_4.preencode(state, m.signers)

    if (m.prologue) encoding10.preencode(state, m.prologue)
    if (m.linked) encoding11_6.preencode(state, m.linked)
    if (m.userData) c.buffer.preencode(state, m.userData)
  },
  encode(state, m) {
    const flags =
      (m.allowPatch ? 1 : 0) | (m.prologue ? 2 : 0) | (m.linked ? 4 : 0) | (m.userData ? 8 : 0)

    c.uint.encode(state, m.version)
    c.uint.encode(state, flags)
    encoding6.encode(state, m.hash)
    c.uint.encode(state, m.quorum)
    encoding11_4.encode(state, m.signers)

    if (m.prologue) encoding10.encode(state, m.prologue)
    if (m.linked) encoding11_6.encode(state, m.linked)
    if (m.userData) c.buffer.encode(state, m.userData)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const flags = c.uint.decode(state)

    return {
      version: r0,
      hash: encoding6.decode(state),
      quorum: c.uint.decode(state),
      allowPatch: (flags & 1) !== 0,
      signers: encoding11_4.decode(state),
      prologue: (flags & 2) !== 0 ? encoding10.decode(state) : null,
      linked: (flags & 4) !== 0 ? encoding11_6.decode(state) : null,
      userData: (flags & 8) !== 0 ? c.buffer.decode(state) : null
    }
  }
}

// @core/keyPair
const encoding12 = {
  preencode(state, m) {
    c.buffer.preencode(state, m.publicKey)
    c.optionalBuffer.preencode(state, m.secretKey)
  },
  encode(state, m) {
    c.buffer.encode(state, m.publicKey)
    c.optionalBuffer.encode(state, m.secretKey)
  },
  decode(state) {
    const r0 = c.buffer.decode(state)
    const r1 = c.optionalBuffer.decode(state)

    return {
      publicKey: r0,
      secretKey: r1
    }
  }
}

// @core/group
const encoding13 = {
  preencode(state, m) {
    state.end++ // max flag is 2 so always one byte

    if (m.key) c.fixed32.preencode(state, m.key)
    if (m.pointer) c.uint.preencode(state, m.pointer)
  },
  encode(state, m) {
    const flags = (m.key ? 1 : 0) | (m.pointer ? 2 : 0)

    c.uint.encode(state, flags)

    if (m.key) c.fixed32.encode(state, m.key)
    if (m.pointer) c.uint.encode(state, m.pointer)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      key: (flags & 1) !== 0 ? c.fixed32.decode(state) : null,
      pointer: (flags & 2) !== 0 ? c.uint.decode(state) : 0
    }
  }
}

// @core/auth.manifest
const encoding14_2 = c.frame(encoding11)

// @core/auth
const encoding14 = {
  preencode(state, m) {
    c.fixed32.preencode(state, m.key)
    c.fixed32.preencode(state, m.discoveryKey)
    state.end++ // max flag is 4 so always one byte

    if (m.manifest) encoding14_2.preencode(state, m.manifest)
    if (m.keyPair) encoding12.preencode(state, m.keyPair)
    if (m.encryptionKey) c.buffer.preencode(state, m.encryptionKey)
  },
  encode(state, m) {
    const flags = (m.manifest ? 1 : 0) | (m.keyPair ? 2 : 0) | (m.encryptionKey ? 4 : 0)

    c.fixed32.encode(state, m.key)
    c.fixed32.encode(state, m.discoveryKey)
    c.uint.encode(state, flags)

    if (m.manifest) encoding14_2.encode(state, m.manifest)
    if (m.keyPair) encoding12.encode(state, m.keyPair)
    if (m.encryptionKey) c.buffer.encode(state, m.encryptionKey)
  },
  decode(state) {
    const r0 = c.fixed32.decode(state)
    const r1 = c.fixed32.decode(state)
    const flags = c.uint.decode(state)

    return {
      key: r0,
      discoveryKey: r1,
      manifest: (flags & 1) !== 0 ? encoding14_2.decode(state) : null,
      keyPair: (flags & 2) !== 0 ? encoding12.decode(state) : null,
      encryptionKey: (flags & 4) !== 0 ? c.buffer.decode(state) : null
    }
  }
}

// @core/head
const encoding15 = {
  preencode(state, m) {
    c.uint.preencode(state, m.fork)
    c.uint.preencode(state, m.length)
    c.fixed32.preencode(state, m.rootHash)
    c.optionalBuffer.preencode(state, m.signature)
    state.end++ // max flag is 1 so always one byte

    if (version >= 2 && m.timestamp) c.uint64.preencode(state, m.timestamp)
  },
  encode(state, m) {
    const flags = version >= 2 && m.timestamp ? 1 : 0

    c.uint.encode(state, m.fork)
    c.uint.encode(state, m.length)
    c.fixed32.encode(state, m.rootHash)
    c.optionalBuffer.encode(state, m.signature)
    c.uint.encode(state, flags)

    if (version >= 2 && m.timestamp) c.uint64.encode(state, m.timestamp)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const r1 = c.uint.decode(state)
    const r2 = c.fixed32.decode(state)
    const r3 = c.optionalBuffer.decode(state)
    const flags = state.start < state.end ? c.uint.decode(state) : 0

    return {
      fork: r0,
      length: r1,
      rootHash: r2,
      signature: r3,
      timestamp: version >= 2 && (flags & 1) !== 0 ? c.uint64.decode(state) : 0
    }
  }
}

// @core/hints
const encoding16 = {
  preencode(state, m) {
    state.end++ // max flag is 4 so always one byte

    if (m.contiguousLength) c.uint.preencode(state, m.contiguousLength)
    if (m.remoteContiguousLength) c.uint.preencode(state, m.remoteContiguousLength)
    if (m.recovering) c.uint.preencode(state, m.recovering)
  },
  encode(state, m) {
    const flags =
      (m.contiguousLength ? 1 : 0) | (m.remoteContiguousLength ? 2 : 0) | (m.recovering ? 4 : 0)

    c.uint.encode(state, flags)

    if (m.contiguousLength) c.uint.encode(state, m.contiguousLength)
    if (m.remoteContiguousLength) c.uint.encode(state, m.remoteContiguousLength)
    if (m.recovering) c.uint.encode(state, m.recovering)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      contiguousLength: (flags & 1) !== 0 ? c.uint.decode(state) : 0,
      remoteContiguousLength: (flags & 2) !== 0 ? c.uint.decode(state) : 0,
      recovering: (flags & 4) !== 0 ? c.uint.decode(state) : 0
    }
  }
}

// @core/session
const encoding17 = {
  preencode(state, m) {
    c.string.preencode(state, m.name)
    c.uint.preencode(state, m.dataPointer)
  },
  encode(state, m) {
    c.string.encode(state, m.name)
    c.uint.encode(state, m.dataPointer)
  },
  decode(state) {
    const r0 = c.string.decode(state)
    const r1 = c.uint.decode(state)

    return {
      name: r0,
      dataPointer: r1
    }
  }
}

// @core/sessions
const encoding18 = c.array(encoding17)

// @core/dependency
const encoding19 = {
  preencode(state, m) {
    c.uint.preencode(state, m.dataPointer)
    c.uint.preencode(state, m.length)
  },
  encode(state, m) {
    c.uint.encode(state, m.dataPointer)
    c.uint.encode(state, m.length)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const r1 = c.uint.decode(state)

    return {
      dataPointer: r0,
      length: r1
    }
  }
}

function setVersion(v) {
  version = v
}

function encode(name, value, v = VERSION) {
  version = v
  return c.encode(getEncoding(name), value)
}

function decode(name, buffer, v = VERSION) {
  version = v
  return c.decode(getEncoding(name), buffer)
}

function getEnum(name) {
  switch (name) {
    case '@core/hashes':
      return encoding6_enum
    case '@core/signatures':
      return encoding7_enum
    default:
      throw new Error('Enum not found ' + name)
  }
}

function getEncoding(name) {
  switch (name) {
    case '@corestore/allocated':
      return encoding0
    case '@corestore/head-v1':
      return encoding1
    case '@corestore/head-v2':
      return encoding2
    case '@corestore/head':
      return encoding3
    case '@corestore/alias':
      return encoding4
    case '@corestore/core':
      return encoding5
    case '@core/hashes':
      return encoding6
    case '@core/signatures':
      return encoding7
    case '@core/tree-node':
      return encoding8
    case '@core/signer':
      return encoding9
    case '@core/prologue':
      return encoding10
    case '@core/manifest':
      return encoding11
    case '@core/keyPair':
      return encoding12
    case '@core/group':
      return encoding13
    case '@core/auth':
      return encoding14
    case '@core/head':
      return encoding15
    case '@core/hints':
      return encoding16
    case '@core/session':
      return encoding17
    case '@core/sessions':
      return encoding18
    case '@core/dependency':
      return encoding19
    default:
      throw new Error('Encoder not found ' + name)
  }
}

function getStruct(name, v = VERSION) {
  const enc = getEncoding(name)
  return {
    preencode(state, m) {
      version = v
      enc.preencode(state, m)
    },
    encode(state, m) {
      version = v
      enc.encode(state, m)
    },
    decode(state) {
      version = v
      return enc.decode(state)
    }
  }
}

const resolveStruct = getStruct // compat

module.exports = {
  resolveStruct,
  getStruct,
  getEnum,
  getEncoding,
  encode,
  decode,
  setVersion,
  version
}
const RocksDB = require('rocksdb-native')
const rrp = require('resolve-reject-promise')
const ScopeLock = require('scope-lock')
const DeviceFile = require('device-file')
const path = require('path')
const fs = require('fs')
const Xache = require('xache')

const View = require('./lib/view.js')

const VERSION = 2
const COLUMN_FAMILY = 'corestore'

const { store, core } = require('./lib/keys.js')

const { CorestoreRX, CorestoreTX, CoreTX, CoreRX } = require('./lib/tx.js')

const {
  createCoreStream,
  createAliasStream,
  createDiscoveryKeyStream,
  createBlockStream,
  createBitfieldStream,
  createUserDataStream,
  createTreeNodeStream,
  createMarkStream,
  createLocalStream,
  createGroupUpdateStream
} = require('./lib/streams.js')

const EMPTY = new View()

class Atom {
  constructor(db) {
    this.db = db
    this.view = new View()
    this.flushedPromise = null
    this.flushing = false
    this.preflushes = []
    this.flushes = []
  }

  preflush(fn) {
    this.preflushes.push(fn)
  }

  onflush(fn) {
    this.flushes.push(fn)
  }

  flushed() {
    if (!this.flushing) return Promise.resolve()
    if (this.flushedPromise !== null) return this.flushedPromise.promise
    this.flushedPromise = rrp()
    return this.flushedPromise.promise
  }

  _resolve() {
    const f = this.flushedPromise
    this.flushedPromise = null
    f.resolve()
  }

  async flush() {
    if (this.flushing) throw new Error('Atom already flushing')
    this.flushing = true

    try {
      const plen = this.preflushes.length
      for (let i = 0; i < plen; i++) this.preflushes[i]()

      await View.flush(this.view.changes, this.db)

      const promises = []
      const len = this.flushes.length // in case of reentry
      for (let i = 0; i < len; i++) promises.push(this.flushes[i]())

      await Promise.all(promises)
    } finally {
      this.view.reset()
      this.flushing = false
      if (this.flushedPromise !== null) this._resolve()
    }
  }
}

class HypercoreStorage {
  constructor(store, db, treeCache, core, view, atom) {
    this.store = store
    this.db = db
    this.core = core
    this.view = view
    this.atom = atom

    this.view.readStart()
    this.treeCache = treeCache
  }

  get readOnly() {
    return this.store.readOnly
  }

  get dependencies() {
    return this.core.dependencies
  }

  getDependencyLength() {
    return this.core.dependencies.length
      ? this.core.dependencies[this.core.dependencies.length - 1].length
      : -1
  }

  getDependency(length) {
    for (let i = this.core.dependencies.length - 1; i >= 0; i--) {
      const dep = this.core.dependencies[i]
      if (dep.length < length) return dep
    }

    return null
  }

  setDependencyHead(dep) {
    if (dep === null) {
      this.core.dependencies = []
      return
    }

    const deps = this.core.dependencies

    for (let i = deps.length - 1; i >= 0; i--) {
      const d = deps[i]

      if (d.dataPointer !== dep.dataPointer) continue

      // check if nothing changed
      if (d.length === dep.length && i === deps.length - 1) return

      this.core = {
        corePointer: this.core.corePointer,
        dataPointer: this.core.dataPointer,
        dependencies: deps.slice(0, i + 1)
      }

      this.core.dependencies[i] = {
        dataPointer: dep.dataPointer,
        length: dep.length
      }
      return // updated head so done
    }

    this.core.dependencies = [
      {
        dataPointer: dep.dataPointer,
        length: dep.length
      }
    ]
  }

  // TODO: this might have to be async if the dependents have changed, but prop ok for now
  updateDependencyLength(length, truncated) {
    const deps = this.core.dependencies

    const i = this.findDependencyIndex(length, truncated)
    if (i === -1) throw new Error('Dependency not found')

    this.core = {
      corePointer: this.core.corePointer,
      dataPointer: this.core.dataPointer,
      dependencies: deps.slice(0, i + 1)
    }

    if (this.core.dependencies[i].length !== length) {
      this.core.dependencies[i] = {
        dataPointer: deps[i].dataPointer,
        length
      }
    }
  }

  findDependencyIndex(length, truncated) {
    const deps = this.core.dependencies

    if (truncated) {
      for (let i = 0; i < deps.length; i++) {
        if (deps[i].length >= length) return i
      }

      return -1
    }

    for (let i = deps.length - 1; i >= 0; i--) {
      if (deps[i].length <= length) return i
    }

    return -1
  }

  get snapshotted() {
    return this.db._snapshot !== null
  }

  snapshot() {
    return new HypercoreStorage(
      this.store,
      this.db.snapshot(),
      this.treeCache,
      this.core,
      this.view.snapshot(),
      this.atom
    )
  }

  compact() {
    return Promise.all([
      this.db.compactRange(core.core(this.core.corePointer), core.core(this.core.corePointer)),
      this.db.compactRange(core.data(this.core.dataPointer), core.data(this.core.dataPointer))
    ])
  }

  atomize(atom) {
    if (this.atom && this.atom !== atom) {
      throw new Error('Cannot atomize and atomized session with a new atom')
    }

    return new HypercoreStorage(
      this.store,
      this.db.session(),
      this.treeCache,
      this.core,
      atom.view,
      atom
    )
  }

  createAtom() {
    return this.store.createAtom()
  }

  createBlockStream(opts) {
    return createBlockStream(this.core, this.db, this.view, opts)
  }

  createTreeNodeStream(opts) {
    return createTreeNodeStream(this.core, this.db, this.view, opts)
  }

  createBitfieldStream(opts) {
    return createBitfieldStream(this.core, this.db, this.view, opts)
  }

  createUserDataStream(opts) {
    return createUserDataStream(this.core, this.db, this.view, opts)
  }

  createMarkStream(opts) {
    return createMarkStream(this.core, this.db, this.view, opts)
  }

  createLocalStream(opts) {
    return createLocalStream(this.core, this.db, this.view, opts)
  }

  async resumeSession(name) {
    const rx = this.read()
    const existingSessionsPromise = rx.getSessions()

    rx.tryFlush()
    const existingSessions = await existingSessionsPromise

    const sessions = existingSessions || []
    const session = getSession(sessions, name, false)

    if (session === null) return null

    const core = {
      corePointer: this.core.corePointer,
      dataPointer: session.dataPointer,
      dependencies: []
    }

    const coreRx = new CoreRX(core, this.db, this.view, this.treeCache, this.store.stats, -1)

    const dependencyPromise = coreRx.getDependency()
    coreRx.tryFlush()

    const dependency = await dependencyPromise
    if (dependency) core.dependencies = this._addDependency(dependency)

    return new HypercoreStorage(
      this.store,
      this.db.session(),
      this.treeCache,
      core,
      this.atom ? this.view : new View(),
      this.atom
    )
  }

  async createSession(name, head) {
    const rx = this.read()

    const existingSessionsPromise = rx.getSessions()
    const existingHeadPromise = rx.getHead()

    rx.tryFlush()

    const [existingSessions, existingHead] = await Promise.all([
      existingSessionsPromise,
      existingHeadPromise
    ])
    if (head === null) head = existingHead

    if (existingHead !== null && head.length > existingHead.length) {
      throw new Error('Invalid head passed, ahead of core')
    }

    const sessions = existingSessions || []
    const session = getSession(sessions, name, true)
    const fresh = session.dataPointer === -1

    if (fresh) {
      session.dataPointer = await this.store._allocData()
    }

    const tx = this.write()

    tx.setSessions(sessions)

    const length = head === null ? 0 : head.length
    const core = {
      corePointer: this.core.corePointer,
      dataPointer: session.dataPointer,
      dependencies: this._addDependency({
        dataPointer: this.core.dataPointer,
        length
      })
    }

    const coreTx = new CoreTX(core, this.db, tx.view, tx.changes)

    if (length > 0) coreTx.setHead(head)
    coreTx.setDependency(core.dependencies[core.dependencies.length - 1])

    if (!fresh) {
      // nuke all existing state...
      coreTx.deleteBlockRange(0, -1)
      coreTx.deleteTreeNodeRange(0, -1)
      coreTx.deleteBitfieldPageRange(0, -1)
    }

    await tx.flush()

    return new HypercoreStorage(
      this.store,
      this.db.session(),
      this.treeCache,
      core,
      this.atom ? this.view : new View(),
      this.atom
    )
  }

  async createAtomicSession(atom, head) {
    const length = head === null ? 0 : head.length
    const core = {
      corePointer: this.core.corePointer,
      dataPointer: this.core.dataPointer,
      dependencies: this._addDependency(null)
    }

    const coreTx = new CoreTX(core, this.db, atom.view, [])

    if (length > 0) coreTx.setHead(head)

    await coreTx.flush()

    return this.atomize(atom)
  }

  _addDependency(dep) {
    const deps = []

    for (let i = 0; i < this.core.dependencies.length; i++) {
      const d = this.core.dependencies[i]

      if (dep !== null && d.length > dep.length) {
        if (d.dataPointer !== dep.dataPointer) {
          deps.push({ dataPointer: d.dataPointer, length: dep.length })
        }
        return deps
      }

      deps.push(d)
    }

    if (
      dep !== null &&
      (deps.length === 0 || deps[deps.length - 1].dataPointer !== dep.dataPointer)
    ) {
      deps.push(dep)
    }
    return deps
  }

  async deleteSessions() {
    const rx = this.read()
    const existingSessionsPromise = rx.getSessions()
    rx.tryFlush()

    const existingSessions = await existingSessionsPromise

    // Remove batches
    const coreTx = this.write()
    coreTx.setSessions([]) // Clear sessions record
    await coreTx.flush()

    const tx = this.db.write({ autoDestroy: true })

    for (const { dataPointer } of existingSessions) {
      const start = core.data(dataPointer)
      const end = core.data(dataPointer + 1)
      tx.tryDeleteRange(start, end)
    }

    await tx.flush()
  }

  read(fork = -1) {
    let treeCache = null
    if (!this.atom) treeCache = this.treeCache

    return new CoreRX(this.core, this.db, this.view, treeCache, this.store.stats, fork)
  }

  write() {
    return new CoreTX(this.core, this.db, this.atom ? this.view : null, [])
  }

  close() {
    if (this.view !== null) {
      this.view.readStop()
      this.view = null
    }

    return this.db.close()
  }

  static async export(ptr, db, { batches = false } = {}) {
    const rx = new CoreRX(ptr, db, EMPTY, null, null, -1)

    const core = {
      head: null,
      auth: null,
      sessions: [],
      data: null
    }

    const sessionsPromise = rx.getSessions()
    const headPromise = rx.getHead()
    const authPromise = rx.getAuth()

    rx.tryFlush()

    const [sessions, head, auth] = await Promise.all([sessionsPromise, headPromise, authPromise])

    core.head = head
    core.auth = { ...auth, keyPair: null }
    if (sessions) core.sessions = sessions.map((s) => s.name)

    const data = []

    data.push(exportData(ptr, db))

    if (batches) {
      for (const { dataPointer } of sessions) {
        data.push(exportData({ dataPointer, dependencies: [] }, db))
      }
    }

    core.data = await Promise.all(data)

    return core
  }

  static isParentStorage(storage, parent) {
    const last = getLastDependency(storage)
    return !!last && last.dataPointer === parent.core.dataPointer
  }
}

class CorestoreStorage {
  constructor(db, opts = {}) {
    const storage = typeof db === 'string' ? db : null

    this.bootstrap = storage !== null
    this.path = storage !== null ? storage : path.join(db.path, '..')
    this.alwaysRecover = !!opts.alwaysRecover
    this.readOnly = !!opts.readOnly
    this.allowBackup = !!opts.allowBackup
    this.deviceFile = null
    this.wait = !!opts.wait

    // tmp sync fix for simplicty since not super deployed yet
    if (this.bootstrap && !this.readOnly) tmpFixStorage(this.path)

    this.id = opts.id || null
    this.view = null
    this.enters = 0
    this.lock = new ScopeLock()
    this.flushing = null
    this.version = 0
    this.migrating = null

    if ((this.bootstrap && !this.readOnly && !this.allowBackup) || this.wait) {
      const corestoreFile = path.join(this.path, 'CORESTORE')

      this.deviceFile = new DeviceFile(corestoreFile, {
        lock: true,
        wait: this.wait,
        data: { id: this.id }
      })
    }

    const dbPath = path.join(this.path, 'db')

    this.stats = {
      treeCache: {
        hits: 0,
        misses: 0,
        parallel: 0,
        skips: 0
      }
    }
    this.rocks = storage === null ? db : new RocksDB(dbPath, { ...opts, lock: this.deviceFile })
    this.db = createColumnFamily(this.rocks, opts)

    const { treeCache = { maxSize: 8192 } } = opts
    this.treeCache = new Xache(treeCache)
  }

  get opened() {
    return this.db.opened
  }

  get closed() {
    return this.db.closed
  }

  async ready() {
    if (this.version === 0) await this._migrateStore()
    return this.db.ready()
  }

  compact(opts) {
    return this.db.compactRange(opts)
  }

  async audit() {
    for await (const { core } of this.createCoreStream()) {
      const coreRx = new CoreRX(core, this.db, EMPTY, this.treeCache, this.stats, -1)
      const authPromise = coreRx.getAuth()

      coreRx.tryFlush()

      const auth = await authPromise

      if (!auth.manifest || auth.manifest.version > 0) continue
      if (auth.manifest.linked === null) continue

      auth.manifest.linked = null
      const coreTx = new CoreTX(core, this.db, null, [])
      coreTx.setAuth(auth)
      await coreTx.flush()
    }
  }

  async deleteCore(ptr) {
    const rx = new CoreRX(ptr, this.db, EMPTY, this.treeCache, this.stats, -1)

    const authPromise = rx.getAuth()
    const sessionsPromise = rx.getSessions()

    rx.tryFlush()

    const auth = await authPromise
    const sessions = await sessionsPromise

    // no core stored here
    if (!auth) return

    const tx = this.db.write({ autoDestroy: true })

    tx.tryDelete(store.core(auth.discoveryKey))

    // clear core
    const start = core.core(ptr.corePointer)
    const end = core.core(ptr.corePointer + 1)
    tx.tryDeleteRange(start, end)

    if (sessions) {
      for (const { dataPointer } of sessions) {
        const start = core.data(dataPointer)
        const end = core.data(dataPointer + 1)
        tx.tryDeleteRange(start, end)
      }
    }

    return tx.flush()
  }

  static isCoreStorage(db) {
    return isCorestoreStorage(db)
  }

  static from(db) {
    if (isCorestoreStorage(db)) return db
    return new this(db)
  }

  async _flush() {
    while (this.enters > 0) {
      await this.lock.lock()
      await this.lock.unlock()
    }
  }

  async _maybeRecover(view) {
    const r = path.join(this.db.path, 'RECOVERING')
    if (!(await fileExists(r))) return
    await this.setRecovering(view)
    await fs.promises.unlink(r)
  }

  _maybeRecoverLater(err) {
    if (!shouldRecover(err) && !this.alwaysRecover) return
    fs.writeFileSync(path.join(this.db.path, 'RECOVERING'), '')
    for (const file of fs.readdirSync(this.db.path)) {
      if (file.endsWith('.log')) fs.unlinkSync(path.join(this.db.path, file))
    }
  }

  // runs pre any other mutation and read
  async _migrateStore() {
    const view = await this._enter()

    try {
      if (this.version === VERSION) return

      await this._preopen

      try {
        await this.db.ready()
      } catch (err) {
        this._maybeRecoverLater(err)
        throw err
      }

      await this._maybeRecover(view)

      const rx = new CorestoreRX(this.db, view)
      const headPromise = rx.getHead()

      rx.tryFlush()
      const head = await headPromise

      const version = head === null ? 0 : head.version
      if (version === VERSION) {
        this.version = VERSION
        return
      }

      const target = { version: VERSION, dryRun: false }

      switch (version) {
        case 0: {
          await require('./migrations/0').store(this, target)
          break
        }
        case 1: {
          // implicit migration on write
          break
        }
        default: {
          throw new Error(
            'Unsupported version: ' + version + ' - you should probably upgrade your dependencies'
          )
        }
      }

      this.version = VERSION
    } finally {
      await this._exit()
    }
  }

  // runs pre the core is returned to the user
  async _migrateCore(core, discoveryKey, version, locked) {
    const view = locked ? this.view : await this._enter()
    try {
      if (version === VERSION) return

      const target = { version: VERSION, dryRun: false }

      switch (version) {
        case 0: {
          await require('./migrations/0').core(core, target)
          break
        }
        case 1: {
          await require('./migrations/1').core(core, target)
          break
        }
        default: {
          throw new Error(
            'Unsupported version: ' + version + ' - you should probably upgrade your dependencies'
          )
        }
      }

      if (locked === false) return

      // if its locked, then move the core state into the memview
      // in case the core is reopened from the memview, pre flush

      const rx = new CorestoreRX(this.db, EMPTY)
      const tx = new CorestoreTX(view)

      const corePromise = rx.getCore(discoveryKey)
      rx.tryFlush()

      tx.putCore(discoveryKey, await corePromise)
      tx.apply()
    } finally {
      if (!locked) await this._exit()
    }
  }

  async _enter() {
    this.enters++
    await this.lock.lock()
    if (this.view === null) this.view = new View()
    return this.view
  }

  async _exit() {
    this.enters--

    if (this.flushing === null) this.flushing = rrp()
    const flushed = this.flushing.promise

    if (this.enters === 0 || this.view.size() > 128) {
      try {
        await View.flush(this.view.changes, this.db)
        this.flushing.resolve()
      } catch (err) {
        this.flushing.reject(err)
      } finally {
        this.flushing = null
        this.view = null
      }
    }

    this.lock.unlock()
    return flushed
  }

  // when used with core catches this isnt transactional for simplicity, HOWEVER, its just a number
  // so worth the tradeoff
  async _allocData() {
    let dataPointer = 0

    const view = await this._enter()
    const tx = new CorestoreTX(view)

    try {
      const head = await this._getHead(view)

      dataPointer = head.datas++

      tx.setHead(head)
      tx.apply()
    } finally {
      await this._exit()
    }

    return dataPointer
  }

  // exposes here so migrations can easily access the head in an init state
  async _getHead(view) {
    const rx = new CorestoreRX(this.db, view)
    const headPromise = rx.getHead()
    rx.tryFlush()

    const head = await headPromise
    return head === null ? initStoreHead() : head
  }

  createAtom() {
    return new Atom(this.db)
  }

  async flush() {
    await this.rocks.flush()
  }

  async close() {
    if (this.db.closed) return
    await this._flush()
    await this.db.close()
    await this.rocks.close()
    this.treeCache.destroy()
    if (this.deviceFile) await this.deviceFile.close()
  }

  async clear() {
    if (this.version === 0) await this._migrateStore()

    const view = await this._enter()
    const tx = new CorestoreTX(view)

    tx.clear()
    tx.apply()

    await this._exit()
  }

  createCoreStream() {
    // TODO: be nice to run the mgiration here also, but too much plumbing atm
    return createCoreStream(this.db, EMPTY)
  }

  createAliasStream(namespace) {
    // TODO: be nice to run the mgiration here also, but too much plumbing atm
    return createAliasStream(this.db, EMPTY, namespace)
  }

  createDiscoveryKeyStream(namespace) {
    return createDiscoveryKeyStream(this.db, EMPTY, namespace)
  }

  createGroupUpdateStream(group, { since, reverse } = {}) {
    return createGroupUpdateStream(this.db, EMPTY, group, { gte: since, reverse })
  }

  async getAlias(alias) {
    if (this.version === 0) await this._migrateStore()

    const rx = new CorestoreRX(this.db, EMPTY)
    const discoveryKeyPromise = rx.getCoreByAlias(alias)
    rx.tryFlush()
    return discoveryKeyPromise
  }

  async getSeed() {
    if (this.version === 0) await this._migrateStore()

    const rx = new CorestoreRX(this.db, EMPTY)
    const headPromise = rx.getHead()

    rx.tryFlush()

    const head = await headPromise
    return head === null ? null : head.seed
  }

  async getGroup(topic) {
    if (this.version === 0) await this._migrateStore()

    const rx = new CorestoreRX(this.db, EMPTY)
    const groupPromise = rx.getGroup(topic)
    rx.tryFlush()
    return groupPromise
  }

  async setSeed(seed, { overwrite = true } = {}) {
    if (this.version === 0) await this._migrateStore()

    const view = await this._enter()
    const tx = new CorestoreTX(view)

    try {
      const rx = new CorestoreRX(this.db, view)
      const headPromise = rx.getHead()

      rx.tryFlush()

      const head = (await headPromise) || initStoreHead()

      if (head.seed === null || overwrite) head.seed = seed
      tx.setHead(head)
      tx.apply()

      return head.seed
    } finally {
      await this._exit()
    }
  }

  async setRecovering(view = null) {
    const recovering = Date.now()
    let keys = []

    for await (const data of this.createDiscoveryKeyStream()) {
      keys.push(data)
      if (keys.length > 16 * 1024) {
        await this._flushRecovering(recovering, view, keys)
        keys = []
      }
    }

    if (keys.length) await this._flushRecovering(recovering, view, keys)
  }

  async _flushRecovering(recovering, view, keys) {
    const own = !view
    if (own) view = await this._enter()
    const tx = new CorestoreTX(view)

    try {
      const infos = await this._getInfos(keys, { auth: false, head: false, hints: true })
      for (const inf of infos) {
        tx.setCoreHints(inf.core, { ...inf.hints, recovering })
      }
      tx.apply()
    } finally {
      if (own) await this._exit()
    }
  }

  async getDefaultDiscoveryKey() {
    if (this.version === 0) await this._migrateStore()

    const rx = new CorestoreRX(this.db, EMPTY)
    const headPromise = rx.getHead()

    rx.tryFlush()

    const head = await headPromise
    return head === null ? null : head.defaultDiscoveryKey
  }

  async setDefaultDiscoveryKey(discoveryKey, { overwrite = true } = {}) {
    if (this.version === 0) await this._migrateStore()

    const view = await this._enter()
    const tx = new CorestoreTX(view)

    try {
      const rx = new CorestoreRX(this.db, view)
      const headPromise = rx.getHead()

      rx.tryFlush()

      const head = (await headPromise) || initStoreHead()

      if (head.defaultDiscoveryKey === null || overwrite) head.defaultDiscoveryKey = discoveryKey
      tx.setHead(head)
      tx.apply()

      return head.defaultDiscoveryKey
    } finally {
      await this._exit()
    }
  }

  async hasCore(discoveryKey, { ifMigrated = false } = {}) {
    if (this.version === 0) await this._migrateStore()

    const rx = new CorestoreRX(this.db, EMPTY)
    const promise = rx.getCore(discoveryKey)

    rx.tryFlush()

    const core = await promise

    if (core === null) return false
    if (core.version === 0 && ifMigrated) return false

    return true
  }

  async getAuth(discoveryKey) {
    if (this.version === 0) await this._migrateStore()

    const rx = new CorestoreRX(this.db, EMPTY)
    const corePromise = rx.getCore(discoveryKey)

    rx.tryFlush()

    const core = await corePromise
    if (core === null) return null

    const read = this.db.read({ autoDestroy: true })
    const authPromise = CoreRX.getAuth(read, core)

    read.tryFlush()

    return authPromise
  }

  async getInfo(discoveryKey, opts) {
    return (await this.getInfos([discoveryKey], opts))[0]
  }

  async getInfos(discoveryKeys, opts) {
    if (this.version === 0) await this._migrateStore()
    return this._getInfos(discoveryKeys, opts)
  }

  async _getInfos(discoveryKeys, { auth = true, head = true, hints = true } = {}) {
    const rx = new CorestoreRX(this.db, EMPTY)
    const corePromises = new Array(discoveryKeys.length)

    for (let i = 0; i < discoveryKeys.length; i++) {
      corePromises[i] = rx.getCore(discoveryKeys[i])
    }

    rx.tryFlush()

    const cores = await Promise.all(corePromises)
    const read = this.db.read({ autoDestroy: true })

    const resultPromises = new Array(cores.length)

    for (let i = 0; i < cores.length; i++) {
      resultPromises[i] = cores[i]
        ? getInfoFromBatch(read, cores[i], discoveryKeys[i], auth, head, hints)
        : null
    }

    read.tryFlush()

    return Promise.all(resultPromises)
  }

  async suspend({ log = noop } = {}) {
    await log('Suspending hypercore storage...')
    await this.db.suspend()
    await log('db suspended')
    if (this.deviceFile) {
      await log('suspend deviceFile')
      await this.deviceFile.suspend()
      await log('deviceFile suspended')
    }
  }

  async resume() {
    if (this.deviceFile) await this.deviceFile.resume()
    await this.db.resume()
  }

  async resumeCore(discoveryKey) {
    if (this.version === 0) await this._migrateStore()

    if (!discoveryKey) {
      discoveryKey = await this.getDefaultDiscoveryKey()
      if (!discoveryKey) return null
    }

    const rx = new CorestoreRX(this.db, EMPTY)
    const corePromise = rx.getCore(discoveryKey)

    rx.tryFlush()
    const core = await corePromise

    if (core === null) return null
    return this._resumeFromPointers(EMPTY, discoveryKey, false, core)
  }

  async export(discoveryKey, opts) {
    const rx = new CorestoreRX(this.db, EMPTY)
    const corePromise = rx.getCore(discoveryKey)

    rx.tryFlush()
    const core = await corePromise
    if (core === null) return null

    let { dataPointer, corePointer } = core

    const ptr = { corePointer, dataPointer, dependencies: [] }

    while (true) {
      const rx = new CoreRX(
        { dataPointer, corePointer: 0, dependencies: [] },
        this.db,
        EMPTY,
        this.treeCache,
        this.stats,
        -1
      )
      const dependencyPromise = rx.getDependency()
      rx.tryFlush()
      const dependency = await dependencyPromise
      if (!dependency) break
      ptr.dependencies.push(dependency)
      dataPointer = dependency.dataPointer
    }

    const session = this.db.session()
    try {
      return await HypercoreStorage.export(ptr, session, opts)
    } finally {
      await session.close()
    }
  }

  async _resumeFromPointers(view, discoveryKey, create, { version, corePointer, dataPointer }) {
    const core = { corePointer, dataPointer, dependencies: [] }

    while (true) {
      const rx = new CoreRX(
        { dataPointer, corePointer: 0, dependencies: [] },
        this.db,
        view,
        this.treeCache,
        this.stats,
        -1
      )
      const dependencyPromise = rx.getDependency()
      rx.tryFlush()
      const dependency = await dependencyPromise
      if (!dependency) break
      core.dependencies.push(dependency)
      dataPointer = dependency.dataPointer
    }

    const result = new HypercoreStorage(this, this.db.session(), this.treeCache, core, EMPTY, null)

    if (version < VERSION) await this._migrateCore(result, discoveryKey, version, create)
    return result
  }

  // not allowed to throw validation errors as its a shared tx!
  async _create(
    view,
    { key, manifest, keyPair, encryptionKey, discoveryKey, alias, userData, core: ptrs }
  ) {
    const rx = new CorestoreRX(this.db, view)
    const tx = new CorestoreTX(view)

    const corePromise = rx.getCore(discoveryKey)
    const headPromise = rx.getHead()

    rx.tryFlush()

    let [core, head] = await Promise.all([corePromise, headPromise])
    if (core) return this._resumeFromPointers(view, discoveryKey, true, core)

    if (head === null) head = initStoreHead()
    if (head.defaultDiscoveryKey === null) head.defaultDiscoveryKey = discoveryKey

    const corePointer = ptrs ? ptrs.corePointer : head.cores++
    const dataPointer = ptrs ? ptrs.dataPointer : head.datas++

    core = { version: VERSION, corePointer, dataPointer, alias }

    tx.setHead(head)
    tx.putCore(discoveryKey, core)
    if (alias) tx.putCoreByAlias(alias, discoveryKey)

    const ptr = { corePointer, dataPointer, dependencies: [] }
    const ctx = new CoreTX(ptr, this.db, view, tx.changes)

    ctx.setAuth({
      key,
      discoveryKey,
      manifest,
      keyPair,
      encryptionKey
    })

    if (userData) {
      for (const { key, value } of userData) {
        ctx.putUserData(key, value)
      }
    }

    tx.apply()

    return new HypercoreStorage(this, this.db.session(), this.treeCache, ptr, EMPTY, null)
  }

  async createCore(data) {
    if (this.version === 0) await this._migrateStore()

    const view = await this._enter()

    try {
      return await this._create(view, data)
    } finally {
      await this._exit()
    }
  }

  // not allowed to throw validation errors as its a shared tx!
  async _createGroup(view, topic) {
    const rx = new CorestoreRX(this.db, view)
    const tx = new CorestoreTX(view)

    const groupPromise = rx.getGroup(topic)
    const headPromise = rx.getHead()

    rx.tryFlush()

    let group = await groupPromise
    if (group !== null) {
      return {
        key: topic,
        pointer: group
      }
    }

    let head = await headPromise
    if (head === null) head = initStoreHead()

    group = head.groups++

    tx.putGroup(topic, group)
    tx.setHead(head)
    tx.apply()

    return {
      key: topic,
      pointer: group
    }
  }

  async createGroup(topic) {
    if (this.version === 0) await this._migrateStore()

    const view = await this._enter()

    try {
      return await this._createGroup(view, topic)
    } finally {
      await this._exit()
    }
  }

  static isParentStorage(storage, parent) {
    return HypercoreStorage.isParentStorage(storage, parent)
  }
}

module.exports = CorestoreStorage

function initStoreHead() {
  return {
    version: 0, // cause we wanna run the migration
    datas: 0,
    cores: 0,
    groups: 0,
    seed: null,
    defaultDiscoveryKey: null
  }
}

function getSession(sessions, name, alloc) {
  for (let i = 0; i < sessions.length; i++) {
    if (sessions[i].name === name) return sessions[i]
  }

  if (!alloc) return null

  const result = { name, dataPointer: -1 }
  sessions.push(result)
  return result
}

function isCorestoreStorage(s) {
  return typeof s === 'object' && !!s && typeof s.setDefaultDiscoveryKey === 'function'
}

function createColumnFamily(db, opts = {}) {
  const {
    tableCacheIndexAndFilterBlocks = true,
    blockCache = true,
    optimizeFiltersForMemory = false,
    blobFileSize = 256 * 1024 * 1024,
    blobGarbageCollectionAgeCutOff = 0.25,
    blobGarbageCollectionForceThreshold = 1.0
  } = opts

  const col = new RocksDB.ColumnFamily(COLUMN_FAMILY, {
    enableBlobFiles: true,
    minBlobSize: 4096,
    blobFileSize,
    enableBlobGarbageCollection: true,
    tableBlockSize: 8192,
    tableCacheIndexAndFilterBlocks,
    tableFormatVersion: 6,
    optimizeFiltersForMemory,
    blockCache,
    blobGarbageCollectionAgeCutOff,
    blobGarbageCollectionForceThreshold
  })

  return db.columnFamily(col)
}

function getLastDependency(storage) {
  return storage.dependencies.length ? storage.dependencies[storage.dependencies.length - 1] : null
}

// TODO: remove in like 3-6 mo
function tmpFixStorage(p) {
  // if CORESTORE file is written, new format
  if (fs.existsSync(path.join(p, 'CORESTORE'))) return

  let files = []

  try {
    files = fs.readdirSync(p)
  } catch {}

  const notRocks = new Set([
    'CORESTORE',
    'primary-key',
    'cores',
    'app-preferences',
    'cache',
    'preferences.json',
    'db',
    'clone',
    'core',
    'notifications'
  ])

  for (const f of files) {
    if (notRocks.has(f)) continue

    try {
      fs.mkdirSync(path.join(p, 'db'))
    } catch {}

    fs.renameSync(path.join(p, f), path.join(p, 'db', f))
  }
}

async function exportData(ptr, db, opts) {
  // just need dataPointer
  const reads = [
    toArray(createBlockStream(ptr, db, EMPTY, opts)),
    toArray(createTreeNodeStream(ptr, db, EMPTY, opts)),
    toArray(createBitfieldStream(ptr, db, EMPTY, opts))
  ]

  const [blocks, tree, bitfield] = await Promise.all(reads)

  return {
    blocks,
    tree,
    bitfield
  }
}

async function toArray(stream) {
  const all = []
  for await (const e of stream) all.push(e)
  return all
}

async function fileExists(path) {
  try {
    await fs.promises.stat(path)
    return true
  } catch {
    return false
  }
}

function shouldRecover(err) {
  return err.message.toLowerCase().indexOf('sequence number is being set backwards') > -1
}

function noop() {}

async function getInfoFromBatch(db, c, discoveryKey, getAuth, getHead, getHints) {
  const authPromise = getAuth ? CoreRX.getAuth(db, c) : null
  const headPromise = getHead ? CoreRX.getHead(db, c) : null
  const hintsPromise = getHints ? CoreRX.getHints(db, c) : null

  // ensure no uncaughts
  if (authPromise) authPromise.catch(noop)
  if (headPromise) headPromise.catch(noop)
  if (hintsPromise) hintsPromise.catch(noop)

  return {
    discoveryKey,
    core: c,
    auth: await authPromise,
    head: await headPromise,
    hints: await hintsPromise
  }
}
const { Readable, getStreamError } = require('streamx')
const { core } = require('./keys')

module.exports = class BlockStream extends Readable {
  constructor(core, db, updates, start, end, reverse) {
    super()

    this.core = core
    this.db = db
    this.updates = updates
    this.start = start
    this.end = end
    this.reverse = reverse === true

    this._drained = true
    this._consumed = 0
    this._stream = null
    this._oncloseBound = this._onclose.bind(this)
    this._maybeDrainBound = this._maybeDrain.bind(this)

    this._update()
  }

  _update() {
    if (this._consumed > this.core.dependencies.length) return

    const deps = this.core.dependencies
    const index = this._findDependencyIndex(deps)

    const curr = index < deps.length ? deps[index] : null
    const prev = index > 0 && index - 1 < deps.length ? deps[index - 1] : null

    const start = prev && prev.length > this.start ? prev.length : this.start
    const end = curr && (this.end === -1 || curr.length < this.end) ? curr.length : this.end

    const ptr = curr ? curr.dataPointer : this.core.dataPointer

    this._makeStream(core.block(ptr, start), core.block(ptr, end))
  }

  _findDependencyIndex(deps) {
    if (!this.reverse) return this._consumed++

    let i = deps.length - this._consumed++
    while (i > 0) {
      if (deps[i - 1].length <= this.end) return i
      i--
      this._consumed++
    }

    return 0
  }

  _predestroy() {
    if (this._stream !== null) this._stream.destroy()
  }

  _read(cb) {
    this._drained = this._onreadable()
    cb(null)
  }

  _maybeDrain() {
    if (this._drained === true) return
    this._drained = this._onreadable()
  }

  _onreadable() {
    if (this._stream === null) {
      this.push(null)
      return true
    }

    let data = this._stream.read()

    if (data === null) return false

    do {
      this.push(data)
      data = this._stream.read()
    } while (data !== null)

    return true
  }

  _onclose() {
    if (this.destroying) return

    const err = getStreamError(this._stream)

    if (err !== null) {
      this.destroy(err)
      return
    }

    // empty the current stream
    if (this._onreadable() === true) this._drained = true

    this._stream = null

    this._update()
    this._maybeDrain()
  }

  _makeStream(start, end) {
    this._stream = this.updates.iterator(this.db, start, end, this.reverse)
    this._stream.on('readable', this._maybeDrainBound)
    this._stream.on('error', noop)
    this._stream.on('close', this._oncloseBound)
  }
}

function noop() {}
const { Readable } = require('streamx')

// used for returned a stream that just errors (during read during teardown)

module.exports = class CloseErrorStream extends Readable {
  constructor(err) {
    super()
    this.error = err
  }

  _open(cb) {
    cb(this.error)
  }
}
const { UINT, STRING } = require('index-encoder')
const c = require('compact-encoding')
const b4a = require('b4a')

const TL_HEAD = 0
const TL_CORE_BY_DKEY = 1
const TL_CORE_BY_ALIAS = 2
const TL_CORE = 3
const TL_DATA = 4
const TL_GROUP_BY_TOPIC = 5
const TL_GROUP = 6

const TL_END = TL_GROUP + 1

const CORE_AUTH = 0
const CORE_SESSIONS = 1
const CORE_GROUP = 2

const DATA_HEAD = 0
const DATA_DEPENDENCY = 1
const DATA_HINTS = 2
const DATA_BLOCK = 3
const DATA_TREE = 4
const DATA_BITFIELD = 5
const DATA_USER_DATA = 6
const DATA_LOCAL = 7
const DATA_MARK = 8

const slab = { buffer: b4a.allocUnsafe(65536), start: 0, end: 0 }

const store = {}
const core = {}
const group = {}

store.clear = function () {
  const state = alloc()
  let start = state.start
  UINT.encode(state, 0)
  const a = state.buffer.subarray(start, state.start)
  start = state.start
  UINT.encode(state, TL_END)
  const b = state.buffer.subarray(start, state.start)
  return [a, b]
}

store.head = function () {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_HEAD)
  return state.buffer.subarray(start, state.start)
}

store.core = function (discoveryKey) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE_BY_DKEY)
  c.fixed32.encode(state, discoveryKey)
  return state.buffer.subarray(start, state.start)
}

store.coreStart = function () {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE_BY_DKEY)
  return state.buffer.subarray(start, state.start)
}

store.coreEnd = function () {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE_BY_DKEY + 1)
  return state.buffer.subarray(start, state.start)
}

store.coreByAlias = function ({ namespace, name }) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE_BY_ALIAS)
  c.fixed32.encode(state, namespace)
  STRING.encode(state, name)
  return state.buffer.subarray(start, state.start)
}

store.coreByAliasStart = function (namespace) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE_BY_ALIAS)
  if (namespace) c.fixed32.encode(state, namespace)
  return state.buffer.subarray(start, state.start)
}

store.coreByAliasEnd = function (namespace) {
  const state = alloc()
  const start = state.start

  if (namespace) {
    UINT.encode(state, TL_CORE_BY_ALIAS)
    c.fixed32.encode(state, namespace)
    state.buffer[state.start++] = 0xff
  } else {
    UINT.encode(state, TL_CORE_BY_ALIAS + 1)
  }

  return state.buffer.subarray(start, state.start)
}

store.alias = function (buffer) {
  const state = { buffer, start: 0, end: buffer.byteLength }
  UINT.decode(state) // ns
  const namespace = c.fixed32.decode(state)
  const name = STRING.decode(state)
  return { namespace, name }
}

store.discoveryKey = function (buffer) {
  const state = { buffer, start: 0, end: buffer.byteLength }
  UINT.decode(state) // ns
  return c.fixed32.decode(state)
}

core.core = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE)
  UINT.encode(state, ptr)
  return state.buffer.subarray(start, state.start)
}

core.data = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  return state.buffer.subarray(start, state.start)
}

core.auth = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE)
  UINT.encode(state, ptr)
  UINT.encode(state, CORE_AUTH)
  return state.buffer.subarray(start, state.start)
}

core.group = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE)
  UINT.encode(state, ptr)
  UINT.encode(state, CORE_GROUP)
  return state.buffer.subarray(start, state.start)
}

core.sessions = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE)
  UINT.encode(state, ptr)
  UINT.encode(state, CORE_SESSIONS)
  return state.buffer.subarray(start, state.start)
}

core.head = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_HEAD)
  return state.buffer.subarray(start, state.start)
}

core.dependency = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_DEPENDENCY)
  return state.buffer.subarray(start, state.start)
}

core.hints = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_HINTS)
  return state.buffer.subarray(start, state.start)
}

core.block = function (ptr, index) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_BLOCK)
  UINT.encode(state, index)
  return state.buffer.subarray(start, state.start)
}

core.tree = function (ptr, index) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_TREE)
  UINT.encode(state, index)
  return state.buffer.subarray(start, state.start)
}

core.bitfield = function (ptr, index, type) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_BITFIELD)
  UINT.encode(state, index)
  UINT.encode(state, type)
  return state.buffer.subarray(start, state.start)
}

core.userData = function (ptr, key) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_USER_DATA)
  STRING.encode(state, key)
  return state.buffer.subarray(start, state.start)
}

core.userDataEnd = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_USER_DATA + 1)
  return state.buffer.subarray(start, state.start)
}

core.mark = function (ptr, index) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_MARK)
  UINT.encode(state, index)
  return state.buffer.subarray(start, state.start)
}

core.local = function (ptr, key) {
  if (key.byteLength > 2048) {
    throw new Error('local keys has an upper limit of 2048 bytes atm')
  }

  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_LOCAL)

  state.buffer.set(key, state.start)
  state.start += key.byteLength
  return state.buffer.subarray(start, state.start)
}

core.localEnd = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_LOCAL + 1)
  return state.buffer.subarray(start, state.start)
}

core.blockIndex = function (buffer) {
  const state = { buffer, start: 0, end: buffer.byteLength }
  UINT.decode(state) // ns
  UINT.decode(state) // ptr
  UINT.decode(state) // type
  return UINT.decode(state)
}

core.bitfieldIndexAndType = function (buffer) {
  const state = { buffer, start: 0, end: buffer.byteLength }
  UINT.decode(state) // ns
  UINT.decode(state) // ptr
  UINT.decode(state) // type
  return [UINT.decode(state), UINT.decode(state)]
}

core.userDataKey = function (buffer) {
  const state = { buffer, start: 0, end: buffer.byteLength }
  UINT.decode(state) // ns
  UINT.decode(state) // ptr
  UINT.decode(state) // type
  return STRING.decode(state)
}

core.markKey = function (buffer) {
  const state = { buffer, start: 0, end: buffer.byteLength }
  UINT.decode(state) // ns
  UINT.decode(state) // ptr
  UINT.decode(state) // type
  return UINT.decode(state)
}

core.localKey = function (buffer) {
  const state = { buffer, start: 0, end: buffer.byteLength }
  UINT.decode(state) // ns
  UINT.decode(state) // ptr
  UINT.decode(state) // type
  return state.buffer.subarray(state.start, state.end)
}

group.topic = function (topic) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_GROUP_BY_TOPIC)
  c.fixed32.encode(state, topic)
  return state.buffer.subarray(start, state.start)
}

group.entry = function (group, timestamp, ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_GROUP)
  UINT.encode(state, group)
  c.uint64be.encode(state, timestamp)
  UINT.encode(state, ptr)
  return state.buffer.subarray(start, state.start)
}

module.exports = { store, core, group }

function alloc() {
  if (slab.buffer.byteLength - slab.start < 4096) {
    slab.buffer = b4a.allocUnsafe(slab.buffer.byteLength)
    slab.start = 0
  }
  return slab
}
const b4a = require('b4a')
const BlockDependencyStream = require('./block-dependency-stream.js')
const { core, store, group } = require('./keys.js')
const schema = require('../encoding/spec/hyperschema')

const CORESTORE_CORE = schema.getEncoding('@corestore/core')
const CORE_TREE_NODE = schema.getEncoding('@core/tree-node')
const EMPTY = b4a.alloc(0)

module.exports = {
  createBlockStream,
  createBitfieldStream,
  createUserDataStream,
  createCoreStream,
  createAliasStream,
  createDiscoveryKeyStream,
  createTreeNodeStream,
  createMarkStream,
  createLocalStream,
  createGroupUpdateStream
}

function createCoreStream(db, view) {
  const start = store.coreStart()
  const end = store.coreEnd()

  const ite = view.iterator(db, start, end, false)

  ite._readableState.map = mapCore
  return ite
}

function createDiscoveryKeyStream(db, view, namespace) {
  const start = namespace ? store.coreByAliasStart(namespace) : store.coreStart()
  const end = namespace ? store.coreByAliasEnd(namespace) : store.coreEnd()

  const ite = view.iterator(db, start, end, false)

  ite._readableState.map = namespace ? mapNamespaceDiscoveryKeys : mapAllDiscoveryKeys
  return ite
}

function createAliasStream(db, view, namespace) {
  const start = store.coreByAliasStart(namespace)
  const end = store.coreByAliasEnd(namespace)

  const ite = view.iterator(db, start, end, false)

  ite._readableState.map = mapAlias
  return ite
}

function createGroupUpdateStream(db, view, groupID, { gte = 0, reverse = true } = {}) {
  const start = group.entry(groupID, gte, 0)
  const end = group.entry(groupID + 1, 0, 0)

  const ite = view.iterator(db, start, end, reverse)

  ite._readableState.map = mapGroupUpdate
  return ite
}

function createBlockIterator(ptr, db, view, start, end, reverse) {
  if (ptr.dependencies.length > 0) {
    return new BlockDependencyStream(ptr, db, view, start, end, reverse)
  }

  const s = core.block(ptr.dataPointer, start)
  const e = core.block(ptr.dataPointer, end === -1 ? Infinity : end)
  return view.iterator(db, s, e, reverse)
}

function createBlockStream(
  ptr,
  db,
  view,
  { gt = -1, gte = gt + 1, lte = -1, lt = lte === -1 ? -1 : lte + 1, reverse = false } = {}
) {
  const ite = createBlockIterator(ptr, db, view, gte, lt, reverse)

  ite._readableState.map = mapBlock
  return ite
}

function createBitfieldStream(
  ptr,
  db,
  view,
  { gt = -1, gte = gt + 1, lte = -1, lt = lte === -1 ? -1 : lte + 1, reverse = false } = {}
) {
  const s = core.bitfield(ptr.dataPointer, gte, 0)
  const e = core.bitfield(ptr.dataPointer, lt === -1 ? Infinity : lt, 0)
  const ite = view.iterator(db, s, e, false)

  ite._readableState.map = mapBitfield
  return ite
}

// NOTE: this does not do dependency lookups atm
function createTreeNodeStream(
  ptr,
  db,
  view,
  { gt = -1, gte = gt + 1, lte = -1, lt = lte === -1 ? -1 : lte + 1, reverse = false } = {}
) {
  const s = core.tree(ptr.dataPointer, gte, 0)
  const e = core.tree(ptr.dataPointer, lt === -1 ? Infinity : lt, 0)
  const ite = view.iterator(db, s, e, false)

  ite._readableState.map = mapTreeNode
  return ite
}

function createUserDataStream(
  ptr,
  db,
  view,
  { gt = null, gte = '', lte = null, lt = null, reverse = false } = {}
) {
  if (gt !== null || lte !== null) {
    throw new Error('gt and lte not yet supported for user data streams')
  }

  const s = core.userData(ptr.dataPointer, gte)
  const e = lt === null ? core.userDataEnd(ptr.dataPointer) : core.userData(ptr.dataPointer, lt)
  const ite = view.iterator(db, s, e, false)

  ite._readableState.map = mapUserData
  return ite
}

function createMarkStream(
  ptr,
  db,
  view,
  { gt = -1, gte = gt + 1, lte = -1, lt = lte === -1 ? -1 : lte + 1, reverse = false } = {}
) {
  const s = core.mark(ptr.dataPointer, gte)
  const e = core.mark(ptr.dataPointer, lt === -1 ? Infinity : lt)
  const ite = view.iterator(db, s, e, reverse)

  ite._readableState.map = mapMark
  return ite
}

function createLocalStream(
  ptr,
  db,
  view,
  { gt = null, gte = EMPTY, lte = null, lt = null, reverse = false } = {}
) {
  if (gt !== null || lte !== null) throw new Error('gt and lte not yet supported for local streams')

  const s = core.local(ptr.dataPointer, gte)
  const e = lt === null ? core.localEnd(ptr.dataPointer) : core.local(ptr.dataPointer, lt)
  const ite = view.iterator(db, s, e, false)

  ite._readableState.map = mapLocal
  return ite
}

function mapBitfield(data) {
  const [index, type] = core.bitfieldIndexAndType(data.key)
  if (type !== 0) return null // ignore for now
  return { index, page: data.value }
}

function mapMark(data) {
  const index = core.markKey(data.key)
  return { index, page: data.value }
}

function mapLocal(data) {
  const key = core.localKey(data.key)
  return { key, value: data.value }
}

function mapGroupUpdate(data) {
  return data.value
}

function mapUserData(data) {
  const key = core.userDataKey(data.key)
  return { key, value: data.value }
}

function mapCore(data) {
  const discoveryKey = store.discoveryKey(data.key)
  const core = CORESTORE_CORE.decode({
    start: 0,
    end: data.value.byteLength,
    buffer: data.value
  })
  return { discoveryKey, core }
}

function mapAllDiscoveryKeys(data) {
  return store.discoveryKey(data.key)
}

function mapNamespaceDiscoveryKeys(data) {
  return data.value
}

function mapAlias(data) {
  const alias = store.alias(data.key)
  return { alias, discoveryKey: data.value }
}

function mapBlock(data) {
  return { index: core.blockIndex(data.key), value: data.value }
}

function mapTreeNode(data) {
  return CORE_TREE_NODE.decode({
    start: 0,
    end: data.value.byteLength,
    buffer: data.value
  })
}
const b4a = require('b4a')
const c = require('compact-encoding')
const flat = require('flat-tree')

const schema = require('../encoding/spec/hyperschema')
const { store, core, group } = require('./keys.js')
const View = require('./view.js')

const CORESTORE_HEAD = schema.getEncoding('@corestore/head')
const CORESTORE_CORE = schema.getEncoding('@corestore/core')
const CORESTORE_GROUP = c.uint

const CORE_AUTH = schema.getEncoding('@core/auth')
const CORE_GROUP = schema.getEncoding('@core/group')
const CORE_SESSIONS = schema.getEncoding('@core/sessions')
const CORE_HEAD = schema.getEncoding('@core/head')
const CORE_TREE_NODE = schema.getEncoding('@core/tree-node')
const CORE_DEPENDENCY = schema.getEncoding('@core/dependency')
const CORE_HINTS = schema.getEncoding('@core/hints')

class CoreTX {
  constructor(core, db, view, changes) {
    if (db.snapshotted) throw new Error('Cannot open core tx on snapshot')
    this.core = core
    this.db = db
    this.view = view
    this.changes = changes
  }

  setAuth(auth) {
    this.changes.push([core.auth(this.core.corePointer), encode(CORE_AUTH, auth), null])
  }

  setSessions(sessions) {
    this.changes.push([core.sessions(this.core.corePointer), encode(CORE_SESSIONS, sessions), null])
  }

  setHead(head) {
    this.changes.push([core.head(this.core.dataPointer), encode(CORE_HEAD, head), null])
  }

  deleteHead() {
    this.changes.push([core.head(this.core.dataPointer), null, null])
  }

  setDependency(dep) {
    this.changes.push([core.dependency(this.core.dataPointer), encode(CORE_DEPENDENCY, dep), null])
  }

  setGroup(group) {
    this.changes.push([core.group(this.core.dataPointer), encode(CORE_GROUP, group), null])
  }

  deleteGroup() {
    this.changes.push([core.group(this.core.dataPointer), null, null])
  }

  setHints(hints) {
    this.changes.push([core.hints(this.core.dataPointer), encode(CORE_HINTS, hints), null])
  }

  putBlock(index, data) {
    this.changes.push([core.block(this.core.dataPointer, index), data, null])
  }

  deleteBlock(index) {
    this.changes.push([core.block(this.core.dataPointer, index), null, null])
  }

  deleteBlockRange(start, end) {
    this.changes.push([
      core.block(this.core.dataPointer, start),
      null,
      core.block(this.core.dataPointer, end === -1 ? Infinity : end)
    ])
  }

  putBitfieldPage(index, data) {
    this.changes.push([core.bitfield(this.core.dataPointer, index, 0), data, null])
  }

  deleteBitfieldPage(index) {
    this.changes.push([core.bitfield(this.core.dataPointer, index, 0), null, null])
  }

  deleteBitfieldPageRange(start, end) {
    this.changes.push([
      core.bitfield(this.core.dataPointer, start, 0),
      null,
      core.bitfield(this.core.dataPointer, end === -1 ? Infinity : end, 0)
    ])
  }

  putTreeNode(node) {
    this.changes.push([
      core.tree(this.core.dataPointer, node.index),
      encode(CORE_TREE_NODE, node),
      null
    ])
  }

  deleteTreeNode(index) {
    this.changes.push([core.tree(this.core.dataPointer, index), null, null])
  }

  deleteTreeNodeRange(start, end) {
    this.changes.push([
      core.tree(this.core.dataPointer, start),
      null,
      core.tree(this.core.dataPointer, end === -1 ? Infinity : end)
    ])
  }

  putUserData(key, value) {
    const buffer = typeof value === 'string' ? b4a.from(value) : value
    this.changes.push([core.userData(this.core.dataPointer, key), buffer, null])
  }

  deleteUserData(key) {
    this.changes.push([core.userData(this.core.dataPointer, key), null, null])
  }

  putMark(index, data) {
    this.changes.push([core.mark(this.core.dataPointer, index), data, null])
  }

  deleteMark(index) {
    this.changes.push([core.mark(this.core.dataPointer, index), null, null])
  }

  deleteMarkRange(start, end) {
    this.changes.push([
      core.mark(this.core.dataPointer, start),
      null,
      core.mark(this.core.dataPointer, end === -1 ? Infinity : end)
    ])
  }

  putLocal(key, value) {
    this.changes.push([core.local(this.core.dataPointer, key), value, null])
  }

  deleteLocal(key) {
    this.changes.push([core.local(this.core.dataPointer, key), null, null])
  }

  deleteLocalRange(start, end) {
    this.changes.push([
      core.local(this.core.dataPointer, start),
      null,
      end === null ? core.localEnd(this.core.dataPointer) : core.local(this.core.dataPointer, end)
    ])
  }

  putGroupUpdate(groupPtr, timestamp, key) {
    this.changes.push([group.entry(groupPtr, timestamp, this.core.corePointer), key, null])
  }

  deleteGroupUpdate(groupPtr, timestamp) {
    this.changes.push([group.entry(groupPtr, timestamp, this.core.corePointer), null, null])
  }

  flush() {
    const changes = this.changes
    if (changes === null) return Promise.resolve(!this.view)

    this.changes = null

    if (this.view) {
      this.view.apply(changes)
      return Promise.resolve(false)
    }

    return View.flush(changes, this.db)
  }
}

class CoreRX {
  constructor(core, db, view, treeCache, stats, fork) {
    this.core = core
    this.read = db.read({ autoDestroy: true })
    this.view = view
    this.treeCache = treeCache
    this.fork = fork
    this.stats = stats

    view.readStart()
  }

  static async getAuth(db, c) {
    return decode(CORE_AUTH, await db.get(core.auth(c.corePointer)))
  }

  async getAuth() {
    return decode(CORE_AUTH, await this.view.get(this.read, core.auth(this.core.corePointer)))
  }

  async getSessions() {
    return decode(
      CORE_SESSIONS,
      await this.view.get(this.read, core.sessions(this.core.corePointer))
    )
  }

  static async getHead(db, c) {
    return decode(CORE_HEAD, await db.get(core.head(c.dataPointer)))
  }

  async getHead() {
    return decode(CORE_HEAD, await this.view.get(this.read, core.head(this.core.dataPointer)))
  }

  async getDependency() {
    return decode(
      CORE_DEPENDENCY,
      await this.view.get(this.read, core.dependency(this.core.dataPointer))
    )
  }

  async getGroup() {
    return await decode(
      CORE_GROUP,
      await this.view.get(this.read, core.group(this.core.corePointer))
    )
  }

  static async getHints(db, c) {
    return decode(CORE_HINTS, await db.get(core.hints(c.dataPointer)))
  }

  async getHints() {
    return decode(CORE_HINTS, await this.view.get(this.read, core.hints(this.core.dataPointer)))
  }

  getBlock(index) {
    const dep = findBlockDependency(this.core.dependencies, index)
    const data = dep === null ? this.core.dataPointer : dep.dataPointer
    return this.view.get(this.read, core.block(data, index))
  }

  getBitfieldPage(index) {
    return this.view.get(this.read, core.bitfield(this.core.dataPointer, index, 0))
  }

  async _resolveTreeCache(key, promise, entry) {
    try {
      const value = decode(CORE_TREE_NODE, await promise)
      const cached = this.treeCache.get(key)

      // preflight is gone; no-op
      if (cached !== entry) return value

      if (value !== null) {
        // replace cached entry with value
        this.treeCache.set(key, { pending: null, value })
      } else {
        // discard non-existing values
        this.treeCache.delete(key)
      }

      return value
    } catch (err) {
      // cleanup
      const cached = this.treeCache.get(key)
      if (cached === entry) {
        this.treeCache.delete(key)
      }

      throw err
    }
  }

  async getTreeNode(index) {
    const dep = findTreeDependency(this.core.dependencies, index)
    const data = dep === null ? this.core.dataPointer : dep.dataPointer

    if (!this.treeCache || this.fork < 0) {
      if (this.stats !== null) this.stats.treeCache.skips++
      // no-cache
      return decode(CORE_TREE_NODE, await this.view.get(this.read, core.tree(data, index)))
    }

    const key = `${data}:${index}:${this.fork}`
    let entry = this.treeCache.get(key)
    if (entry) {
      if (entry.pending) {
        if (this.stats !== null) this.stats.treeCache.parallel++
        return entry.pending
      }

      if (this.stats !== null) this.stats.treeCache.hits++
      return entry.value
    }

    if (this.stats !== null) this.stats.treeCache.misses++

    const promise = this.view.get(this.read, core.tree(data, index))
    entry = { pending: null, value: null }
    entry.pending = this._resolveTreeCache(key, promise, entry)
    this.treeCache.set(key, entry)

    return entry.pending
  }

  async hasTreeNode(index) {
    return (await this.getTreeNode(index)) !== null
  }

  getUserData(key) {
    return this.view.get(this.read, core.userData(this.core.dataPointer, key))
  }

  getMark(index) {
    return this.view.get(this.read, core.mark(this.core.dataPointer, index))
  }

  getLocal(key) {
    return this.view.get(this.read, core.local(this.core.dataPointer, key))
  }

  tryFlush() {
    this.read.tryFlush()
    this._free()
  }

  destroy() {
    this.read.destroy()
    this._free()
  }

  _free() {
    if (this.view === null) return
    this.view.readStop()
    this.view = null
  }
}

class CorestoreTX {
  constructor(view) {
    this.view = view
    this.changes = []
  }

  setHead(head) {
    this.changes.push([store.head(), encode(CORESTORE_HEAD, head), null])
  }

  setCoreHints(c, hints) {
    this.changes.push([core.hints(c.dataPointer), encode(CORE_HINTS, hints), null])
  }

  putCore(discoveryKey, ptr) {
    this.changes.push([store.core(discoveryKey), encode(CORESTORE_CORE, ptr), null])
  }

  putCoreByAlias(alias, discoveryKey) {
    this.changes.push([store.coreByAlias(alias), discoveryKey, null])
  }

  putGroup(topic, groupPtr) {
    this.changes.push([group.topic(topic), encode(CORESTORE_GROUP, groupPtr), null])
  }

  deleteGroup(topic) {
    this.changes.push([group.topic(topic), null, null])
  }

  clear() {
    const [start, end] = store.clear()
    this.changes.push([start, null, end])
  }

  apply() {
    if (this.changes === null) return
    this.view.apply(this.changes)
    this.changes = null
  }
}

class CorestoreRX {
  constructor(db, view) {
    this.read = db.read({ autoDestroy: true })
    this.view = view

    view.readStart()
  }

  async getHeadRaw(db) {
    return await this.view.get(this.read, store.head())
  }

  async getHead() {
    return decode(CORESTORE_HEAD, await this.view.get(this.read, store.head()))
  }

  async getCore(discoveryKey) {
    return decode(CORESTORE_CORE, await this.view.get(this.read, store.core(discoveryKey)))
  }

  getCoreByAlias(alias) {
    return this.view.get(this.read, store.coreByAlias(alias))
  }

  async getGroup(topic) {
    return decode(CORESTORE_GROUP, await this.view.get(this.read, group.topic(topic)))
  }

  tryFlush() {
    this.read.tryFlush()
    this._free()
  }

  destroy() {
    this.read.destroy()
    this._free()
  }

  _free() {
    if (this.view === null) return
    this.view.readStop()
    this.view = null
  }
}

module.exports = { CorestoreTX, CorestoreRX, CoreTX, CoreRX }

function findBlockDependency(dependencies, index) {
  for (let i = 0; i < dependencies.length; i++) {
    const dep = dependencies[i]
    if (index < dep.length) return dep
  }

  return null
}

function findTreeDependency(dependencies, index) {
  for (let i = 0; i < dependencies.length; i++) {
    const dep = dependencies[i]
    if (flat.rightSpan(index) <= (dep.length - 1) * 2) return dep
  }

  return null
}

function decode(enc, buffer) {
  if (buffer === null) return null
  return enc.decode({ start: 0, end: buffer.byteLength, buffer })
}

function encode(enc, m) {
  // TODO: use fancy slab for small messages
  const state = { start: 0, end: 0, buffer: null }
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}
const { Readable, getStreamError } = require('streamx')
const CloseErrorStream = require('./close-error-stream.js')
const b4a = require('b4a')

class OverlayStream extends Readable {
  constructor(stream, start, end, reverse, changes, cleared) {
    super()

    this.start = start
    this.end = end
    this.reverse = reverse
    this.changes = changes
    this.cleared = cleared
    this.change = 0
    this.range = 0

    this._stream = stream
    this._drained = false

    this._stream.on('readable', this._drainMaybe.bind(this))
    this._stream.on('error', noop)
    this._stream.on('close', this._onclose.bind(this))
  }

  _drainMaybe() {
    if (this._drained === true) return
    this._drained = this._onreadable()
  }

  _onclose() {
    if (this.destroying) return

    const err = getStreamError(this._stream)

    if (err !== null) {
      this.destroy(err)
      return
    }

    while (this.change < this.changes.length) {
      const c = this.changes[this.change++]
      const key = c[0]
      const value = c[1]

      if (value !== null && this._inRange(key)) this.push({ key, value })
    }

    this.push(null)
    this._stream = null
  }

  _onreadable() {
    let data = this._stream.read()
    if (data === null) return false

    let drained = false

    do {
      if (this._push(data) === true) drained = true
      data = this._stream.read()
    } while (data !== null)

    return drained
  }

  _read(cb) {
    this._drained = this._onreadable()
    cb(null)
  }

  _predestroy() {
    this._stream.destroy()
  }

  _push(entry) {
    const key = entry.key

    while (this.range < this.cleared.length) {
      const c = this.cleared[this.range]

      // we moved past the range
      if (this.reverse ? b4a.compare(key, c[0]) < 0 : b4a.compare(c[2], key) <= 0) {
        this.range++
        continue
      }

      // we didnt move past and are in, drop
      if (b4a.compare(c[0], key) <= 0 && b4a.compare(key, c[2]) < 0) {
        return false
      }

      break
    }

    let updated = false

    while (this.change < this.changes.length) {
      const c = this.changes[this.change]
      const key = c[0]
      const value = typeof c[1] === 'string' ? b4a.from(c[1]) : c[1]
      const cmp = b4a.compare(key, entry.key)

      // same value, if not deleted, return new one
      if (cmp === 0) {
        this.change++
        if (value === null || this._inRange(key) === false) return updated
        this.push({ key, value })
        return true
      }

      // we moved past the change, push it
      if (this.reverse ? cmp > 0 : cmp < 0) {
        this.change++
        if (value === null || this._inRange(key) === false) continue
        this.push({ key, value })
        updated = true
        continue
      }

      this.push(entry)
      return true
    }

    this.push(entry)
    return true
  }

  _inRange(key) {
    return b4a.compare(this.start, key) <= 0 && b4a.compare(key, this.end) < 0
  }
}

class Overlay {
  constructor() {
    this.indexed = 0
    this.changes = null
    this.cleared = null
    this.reverse = false
  }

  update(view, reverse) {
    if (view.indexed === this.indexed) return

    const changes = view.map === null ? [] : [...view.map.values()]
    const cleared = view.cleared === null ? [] : view.cleared.slice(0)

    const cmp = reverse ? cmpChangeReverse : cmpChange

    changes.sort(cmp)
    cleared.sort(cmp)

    this.indexed = view.indexed
    this.changes = changes
    this.cleared = cleared
    this.reverse = reverse
  }

  createStream(stream, start, end, reverse) {
    return new OverlayStream(
      stream,
      start,
      end,
      reverse,
      this.reverse === reverse ? this.changes : reverseArray(this.changes),
      this.reverse === reverse ? this.cleared : reverseArray(this.cleared)
    )
  }
}

class View {
  constructor() {
    this.map = null
    this.indexed = 0
    this.changes = null
    this.cleared = null
    this.overlay = null
    this.snap = null
    this.readers = 0
  }

  snapshot() {
    if (this._attached()) return this.snap.snapshot()

    const snap = new View()

    snap.map = this.map
    snap.indexed = this.indexed
    snap.changes = this.changes
    snap.cleared = this.cleared

    if (this._frozen()) return snap

    this.readers++
    snap.snap = this

    return snap
  }

  readStart() {
    if (this.snap !== null) this.readers++
  }

  readStop() {
    if (this.snap !== null && --this.readers === 0) this.snap.readers--
  }

  size() {
    return this.changes === null ? 0 : this.changes.length
  }

  updated() {
    return this.changes === null
  }

  get(read, key) {
    return this.changes === null ? read.get(key) : this._indexAndGet(read, key)
  }

  reset() {
    this.indexed = 0
    this.snap = this.map = this.changes = this.cleared = this.overlay = null
  }

  iterator(db, start, end, reverse) {
    if (dbClosing(db)) return new CloseErrorStream(new Error('RocksDB session is closed'))

    const stream = db.iterator({ gte: start, lt: end, reverse })
    if (this.changes === null) return stream

    this._index()

    if (this.overlay === null) this.overlay = new Overlay()
    this.overlay.update(this, reverse)
    return this.overlay.createStream(stream, start, end, reverse)
  }

  _indexAndGet(read, key) {
    this._index()
    const change = this.map.get(b4a.toString(key, 'hex'))

    if (change === undefined) {
      return this.cleared === null ? read.get(key) : this._readAndMaybeDrop(read, key)
    }

    return Promise.resolve(change[1])
  }

  async _readAndMaybeDrop(read, key) {
    const cleared = this.cleared // in case its cleared
    const value = await read.get(key)
    if (value === null) return null

    for (let i = 0; i < cleared.length; i++) {
      const c = cleared[i]
      // check if in range
      if (b4a.compare(c[0], key) <= 0 && b4a.compare(key, c[2]) < 0) return null
    }

    return value
  }

  _attached() {
    return this.snap !== null && this.changes === this.snap.changes
  }

  _frozen() {
    return this.changes === null || (this.snap !== null && this.changes !== this.snap.changes)
  }

  _index() {
    // if we are a snap and we are still attached (ie no mutations), simply copy the refs
    if (this._attached()) {
      this.snap._index()
      this.map = this.snap.map
      this.cleared = this.snap.cleared
      this.indexed = this.snap.indexed
      return
    }

    if (this.map === null) this.map = new Map()
    if (this.changes.length === this.indexed) return

    while (this.indexed < this.changes.length) {
      const c = this.changes[this.indexed++]

      if (c[2] === null) this.map.set(b4a.toString(c[0], 'hex'), c)
      else this._indexRange(c)
    }
  }

  _indexRange(range) {
    const s = b4a.toString(range[0], 'hex')
    const e = b4a.toString(range[2], 'hex')

    for (const [key, c] of this.map) {
      if (s <= key && key < e) this.map.set(key, [c[0], null, null])
    }

    if (this.cleared === null) this.cleared = []
    this.cleared.push(range)
  }

  apply(changes) {
    if (this.snap !== null) throw new Error('Illegal to push changes to a snapshot')

    if (this.readers !== 0 && this.changes !== null) {
      this.changes = this.changes.slice(0)
      this.cleared = this.cleared === null ? null : this.cleared.slice(0)
      this.map = this.map === null ? null : new Map([...this.map])
    }

    if (this.changes === null) {
      this.changes = changes
      return
    }

    for (let i = 0; i < changes.length; i++) {
      this.changes.push(changes[i])
    }
  }

  static async flush(changes, db) {
    if (changes === null) return true

    const w = db.write({ autoDestroy: true })

    for (const [start, value, end] of changes) {
      if (end !== null) w.tryDeleteRange(start, end)
      else if (value !== null) w.tryPut(start, value)
      else w.tryDelete(start)
    }

    await w.flush()

    return true
  }
}

module.exports = View

function cmpChange(a, b) {
  const c = b4a.compare(a[0], b[0])
  return c === 0 ? b4a.compare(a[2], b[2]) : c
}

function cmpChangeReverse(a, b) {
  return cmpChange(b, a)
}

function noop() {}

function reverseArray(list) {
  const r = new Array(list.length)
  for (let i = 0; i < list.length; i++) r[r.length - 1 - i] = list[i]
  return r
}

// TODO: expose from rocks instead
function dbClosing(db) {
  return db._state.closing || db._index === -1
}
const fs = require('fs')
const path = require('path')
const { Readable } = require('streamx')
const b4a = require('b4a')
const flat = require('flat-tree')
const crypto = require('hypercore-crypto')
const c = require('compact-encoding')
const m = require('./messages.js')
const View = require('../../lib/view.js')
const { CorestoreTX, CoreTX, CorestoreRX } = require('../../lib/tx.js')

const EMPTY_NODE = b4a.alloc(40)
const EMPTY_PAGE = b4a.alloc(4096)

let TREE_01_SKIP = null
let TREE_04_SKIP = null
let TREE_16_SKIP = null

class CoreListStream extends Readable {
  constructor (storage) {
    super()

    this.storage = storage
    this.stack = []
  }

  async _open (cb) {
    for (const a of await readdir(path.join(this.storage, 'cores'))) {
      for (const b of await readdir(path.join(this.storage, 'cores', a))) {
        for (const dkey of await readdir(path.join(this.storage, 'cores', a, b))) {
          this.stack.push(path.join(this.storage, 'cores', a, b, dkey))
        }
      }
    }

    cb(null)
  }

  async _read (cb) {
    while (true) {
      const next = this.stack.pop()
      if (!next) {
        this.push(null)
        break
      }

      const oplog = path.join(next, 'oplog')
      const result = await readOplog(oplog)
      if (!result) continue

      this.push(result)
      break
    }

    cb(null)
  }
}

function decodeOplogHeader (state) {
  c.uint32.decode(state) // cksum, ignore for now

  const l = c.uint32.decode(state)
  const length = l >> 2
  const headerBit = l & 1
  const partialBit = l & 2

  if (state.end - state.start < length) return null

  const end = state.start + length
  const result = { header: headerBit, partial: partialBit !== 0, byteLength: length + 8, message: null }

  try {
    result.message = m.oplog.header.decode({ start: state.start, end, buffer: state.buffer })
  } catch {
    return null
  }

  state.start = end
  return result
}

function decodeOplogEntry (state) {
  if (state.end - state.start < 8) return null

  c.uint32.decode(state) // cksum, ignore for now

  const l = c.uint32.decode(state)
  const length = l >>> 2
  const headerBit = l & 1
  const partialBit = l & 2

  if (state.end - state.start < length) return null

  const end = state.start + length

  const result = { header: headerBit, partial: partialBit !== 0, byteLength: length + 8, message: null }

  try {
    result.message = m.oplog.entry.decode({ start: state.start, end, buffer: state.buffer })
  } catch {
    return null
  }

  state.start = end

  return result
}

module.exports = { store, core }

async function store (storage, { version, dryRun = true, gc = true }) {
  const stream = new CoreListStream(storage.path)
  const view = new View()

  const tx = new CorestoreTX(view)
  const head = await storage._getHead(view)
  const primaryKeyFile = path.join(storage.path, 'primary-key')

  const primaryKey = await readFile(primaryKeyFile)

  if (!head.seed) head.seed = primaryKey

  for await (const data of stream) {
    const key = data.header.key
    const discoveryKey = crypto.discoveryKey(data.header.key)
    const files = getFiles(data.path)

    if (head.defaultDiscoveryKey === null) head.defaultDiscoveryKey = discoveryKey

    const core = {
      version: 0, // need later migration
      corePointer: head.allocated.cores++,
      dataPointer: head.allocated.datas++,
      alias: null
    }

    const ptr = { version: 0, corePointer: core.corePointer, dataPointer: core.dataPointer, dependencies: [] }
    const ctx = new CoreTX(ptr, storage.db, view, [])
    const userData = new Map()
    const treeNodes = new Map()

    const auth = {
      key,
      discoveryKey,
      manifest: data.header.manifest,
      keyPair: data.header.keyPair,
      encryptionKey: null
    }

    const tree = {
      length: 0,
      fork: 0,
      rootHash: null,
      signature: null
    }

    if (data.header.tree && data.header.tree.length) {
      tree.length = data.header.tree.length
      tree.fork = data.header.tree.fork
      tree.rootHash = data.header.tree.rootHash
      tree.signature = data.header.tree.signature
    }

    for (const { key, value } of data.header.userData) {
      userData.set(key, value)
    }

    for (const e of data.entries) {
      if (e.userData) userData.set(e.userData.key, e.userData.value)

      if (e.treeNodes) {
        for (const node of e.treeNodes) {
          treeNodes.set(node.index, node)
          ctx.putTreeNode(node)
        }
      }

      if (e.treeUpgrade) {
        if (e.treeUpgrade.ancestors !== tree.length) {
          throw new Error('Unflushed truncations not migrate-able atm')
        }

        tree.length = e.treeUpgrade.length
        tree.fork = e.treeUpgrade.fork
        tree.rootHash = null
        tree.signature = e.treeUpgrade.signature
      }
    }

    if (userData.has('corestore/name') && userData.has('corestore/namespace')) {
      core.alias = {
        name: b4a.toString(userData.get('corestore/name')),
        namespace: userData.get('corestore/namespace')
      }
      userData.delete('corestore/name')
      userData.delete('corestore/namespace')
    }

    for (const [key, value] of userData) {
      ctx.putUserData(key, value)
    }

    ctx.setAuth(auth)

    const getTreeNode = (index) => (treeNodes.get(index) || getTreeNodeFromFile(files.tree, index))

    if (tree.length) {
      if (tree.rootHash === null) tree.rootHash = crypto.tree(await getRoots(tree.length, getTreeNode))
      ctx.setHead(tree)
    }

    tx.putCore(discoveryKey, core)
    if (core.alias) tx.putCoreByAlias(core.alias, discoveryKey)

    await ctx.flush()
  }

  head.version = version
  tx.setHead(head)
  tx.apply()

  if (dryRun) return

  await View.flush(view.changes, storage.db)

  if (gc) await rm(primaryKeyFile)
}

class BlockSlicer {
  constructor (filename) {
    this.stream = fs.createReadStream(filename)
    this.closed = new Promise(resolve => this.stream.once('close', resolve))
    this.offset = 0
    this.overflow = null
  }

  async take (offset, size) {
    let buffer = null
    if (offset < this.offset) throw new Error('overread')

    while (true) {
      let data = null

      if (this.overflow) {
        data = this.overflow
        this.overflow = null
      } else {
        data = this.stream.read()

        if (!data) {
          await new Promise(resolve => this.stream.once('readable', resolve))
          continue
        }
      }

      let chunk = null

      if (this.offset === offset || buffer) {
        chunk = data
      } else if (this.offset + data.byteLength > offset) {
        chunk = data.subarray(offset - this.offset)
      }

      this.offset += data.byteLength
      if (!chunk) continue

      if (buffer) buffer = b4a.concat([buffer, chunk])
      else buffer = chunk

      if (buffer.byteLength < size) continue

      const result = buffer.subarray(0, size)
      this.overflow = size === buffer.byteLength ? null : buffer.subarray(result.byteLength)
      this.offset -= (this.overflow ? this.overflow.byteLength : 0)
      return result
    }
  }

  close () {
    this.stream.on('error', noop)
    this.stream.destroy()
    return this.closed
  }
}

class TreeSlicer {
  constructor () {
    this.buffer = null
    this.offset = 0
  }

  get size () {
    return this.buffer === null ? 0 : this.buffer.byteLength
  }

  push (data) {
    if (this.buffer === null) this.buffer = data
    else this.buffer = b4a.concat([this.buffer, data])
    this.offset += data.byteLength
  }

  skip () {
    let skipped = 0

    if (TREE_01_SKIP === null) {
      TREE_16_SKIP = b4a.alloc(16 * 40 * 100)
      TREE_04_SKIP = TREE_16_SKIP.subarray(0, 4 * 40 * 100)
      TREE_01_SKIP = TREE_16_SKIP.subarray(0, 1 * 40 * 100)
    }

    while (true) {
      if (this.buffer.byteLength >= TREE_16_SKIP.byteLength) {
        if (b4a.equals(this.buffer.subarray(0, TREE_16_SKIP.byteLength), TREE_16_SKIP)) {
          this.buffer = this.buffer.subarray(TREE_16_SKIP.byteLength)
          skipped += 1600
          continue
        }
      }

      if (this.buffer.byteLength >= TREE_04_SKIP.byteLength) {
        if (b4a.equals(this.buffer.subarray(0, TREE_04_SKIP.byteLength), TREE_04_SKIP)) {
          this.buffer = this.buffer.subarray(TREE_04_SKIP.byteLength)
          skipped += 400
          continue
        }
      }

      if (this.buffer.byteLength >= TREE_01_SKIP.byteLength) {
        if (b4a.equals(this.buffer.subarray(0, TREE_01_SKIP.byteLength), TREE_01_SKIP)) {
          this.buffer = this.buffer.subarray(TREE_01_SKIP.byteLength)
          skipped += 100
          continue
        }
      }
      break
    }

    return skipped
  }

  take () {
    const len = 40

    if (len <= this.size) {
      const chunk = this.buffer.subarray(0, len)
      this.buffer = this.buffer.subarray(len)
      return chunk
    }

    return null
  }
}

async function core (core, { version, dryRun = true, gc = true }) {
  if (dryRun) return // dryRun mode not supported atm

  const rx = core.read()

  const promises = [rx.getAuth(), rx.getHead()]
  rx.tryFlush()

  const [auth, head] = await Promise.all(promises)

  if (!auth) return

  const dk = b4a.toString(auth.discoveryKey, 'hex')
  const files = getFiles(path.join(core.store.path, 'cores', dk.slice(0, 2), dk.slice(2, 4), dk))

  if (head === null || head.length === 0) {
    await commitCoreMigration(auth, core, version)
    if (gc) await runGC()
    return // no data
  }

  const oplog = await readOplog(files.oplog)
  if (!oplog) {
    const writable = !!auth.keyPair

    if (writable) {
      throw new Error('No oplog available writable core for ' + files.oplog + ', length = ' + (head ? head.length : 0))
    }

    // if not writable, just nuke it to recover, some bad state happened here, prop corruption from earlier versions
    const w = core.write()

    w.deleteBlockRange(0, -1)
    w.deleteTreeNodeRange(0, -1)
    w.deleteBitfieldPageRange(0, -1)
    w.deleteHead()

    await w.flush()

    await commitCoreMigration(auth, core, version)
    if (gc) await runGC()
    return // no data
  }

  const treeData = new TreeSlicer()

  let treeIndex = 0

  if (await exists(files.tree)) {
    for await (const data of fs.createReadStream(files.tree)) {
      treeData.push(data)

      let write = null

      while (true) {
        const skip = treeData.skip()
        treeIndex += skip

        const buf = treeData.take()
        if (buf === null) break

        const index = treeIndex++
        if (b4a.equals(buf, EMPTY_NODE)) continue

        if (write === null) write = core.write()
        write.putTreeNode(decodeTreeNode(index, buf))
      }

      if (write !== null) await write.flush()
    }
  }

  const buf = []
  if (await exists(files.bitfield)) {
    for await (const data of fs.createReadStream(files.bitfield)) {
      buf.push(data)
    }
  }

  let bitfield = b4a.concat(buf)
  if (bitfield.byteLength & 4095) bitfield = b4a.concat([bitfield, b4a.alloc(4096 - (bitfield.byteLength & 4095))])

  const pages = new Map()
  const headerBits = new Map()

  const roots = await getRootsFromStorage(core, head.length)

  for (const e of oplog.entries) {
    if (!e.bitfield) continue

    for (let i = 0; i < e.bitfield.length; i++) {
      headerBits.set(i + e.bitfield.start, !e.bitfield.drop)
    }
  }

  let batch = []

  const cache = new Map()
  const blocks = new BlockSlicer(files.data)

  for (const index of allBits(bitfield)) {
    if (headerBits.get(index) === false) continue
    if (index >= head.length) continue

    setBitInPage(index)

    batch.push(index)
    if (batch.length < 1024) continue

    await writeBlocksBatch()
    continue
  }

  if (batch.length) await writeBlocksBatch()

  await blocks.close()

  const w = core.write()

  for (const [index, bit] of headerBits) {
    if (!bit) continue
    if (index >= head.length) continue

    setBitInPage(index)

    const blk = await getBlockFromFile(files.data, core, index, roots, cache)
    w.putBlock(index, blk)
  }

  for (const [index, page] of pages) {
    w.putBitfieldPage(index, b4a.from(page.buffer, page.byteOffset, page.byteLength))
  }

  await w.flush()

  let contiguousLength = 0
  for await (const data of core.createBlockStream()) {
    if (data.index === contiguousLength) contiguousLength++
    else break
  }

  if (contiguousLength) {
    const w = core.write()
    w.setHints({ contiguousLength })
    await w.flush()
  }

  await commitCoreMigration(auth, core, version)

  if (gc) await runGC()

  async function runGC () {
    await rm(files.path)
    await rmdir(path.join(files.path, '..'))
    await rmdir(path.join(files.path, '../..'))
    await rmdir(path.join(core.store.path, 'cores'))
  }

  function setBitInPage (index) {
    const n = index & 32767
    const p = (index - n) / 32768

    let page = pages.get(p)

    if (!page) {
      page = new Uint32Array(1024)
      pages.set(p, page)
    }

    const o = n & 31
    const b = (n - o) / 32
    const v = 1 << o

    page[b] |= v
  }

  async function writeBlocksBatch () {
    const read = core.read()
    const promises = []
    for (const index of batch) promises.push(getByteRangeFromStorage(read, 2 * index, roots, cache))
    read.tryFlush()

    const r = await Promise.all(promises)
    const tx = core.write()

    for (let i = 0; i < r.length; i++) {
      const index = batch[i]
      const [offset, size] = r[i]

      const blk = await blocks.take(offset, size)
      tx.putBlock(index, blk)
    }

    batch = []
    if (cache.size > 16384) cache.clear()

    await tx.flush()
  }
}

async function commitCoreMigration (auth, core, version) {
  const view = new View()
  const rx = new CorestoreRX(core.db, view)

  const storeCorePromise = rx.getCore(auth.discoveryKey)
  rx.tryFlush()

  const storeCore = await storeCorePromise

  storeCore.version = version

  const tx = new CorestoreTX(view)

  tx.putCore(auth.discoveryKey, storeCore)
  tx.apply()

  await View.flush(view.changes, core.db)
}

async function getBlockFromFile (file, core, index, roots, cache) {
  const rx = core.read()
  const promise = getByteRangeFromStorage(rx, 2 * index, roots, cache)
  rx.tryFlush()
  const [offset, size] = await promise

  return new Promise(function (resolve) {
    readAll(file, size, offset, function (err, buf) {
      if (err) return resolve(null)
      resolve(buf)
    })
  })
}

function getFiles (dir) {
  return {
    path: dir,
    oplog: path.join(dir, 'oplog'),
    data: path.join(dir, 'data'),
    tree: path.join(dir, 'tree'),
    bitfield: path.join(dir, 'bitfield')
  }
}

async function getRootsFromStorage (core, length) {
  const all = []
  const rx = core.read()
  for (const index of flat.fullRoots(2 * length)) {
    all.push(rx.getTreeNode(index))
  }
  rx.tryFlush()
  return Promise.all(all)
}

async function getRoots (length, getTreeNode) {
  const all = []
  for (const index of flat.fullRoots(2 * length)) {
    all.push(await getTreeNode(index))
  }
  return all
}

function getCached (read, cache, index) {
  if (cache.has(index)) return cache.get(index)
  const p = read.getTreeNode(index)
  cache.set(index, p)
  return p
}

async function getByteRangeFromStorage (read, index, roots, cache) {
  const promises = [getCached(read, cache, index), getByteOffsetFromStorage(read, index, roots, cache)]
  const [node, offset] = await Promise.all(promises)
  if (!node) throw new Error('Node not found during migration: ' + index)
  return [offset, node.size]
}

async function getByteOffsetFromStorage (rx, index, roots, cache) {
  if (index === 0) return 0
  if ((index & 1) === 1) index = flat.leftSpan(index)

  let head = 0
  let offset = 0

  for (const node of roots) { // all async ticks happen once we find the root so safe
    head += 2 * ((node.index - head) + 1)

    if (index >= head) {
      offset += node.size
      continue
    }

    const ite = flat.iterator(node.index)
    const promises = []

    while (ite.index !== index) {
      if (index < ite.index) {
        ite.leftChild()
      } else {
        promises.push(getCached(rx, cache, ite.leftChild()))
        ite.sibling()
      }
    }

    const nodes = await Promise.all(promises)
    for (const node of nodes) offset += node.size

    return offset
  }

  throw new Error('Failed to find offset')
}

function decodeTreeNode (index, buf) {
  return { index, size: c.decode(c.uint64, buf), hash: buf.subarray(8) }
}

async function getTreeNodeFromFile (file, index) {
  return new Promise(function (resolve) {
    readAll(file, 40, index * 40, function (err, buf) {
      if (err) return resolve(null)
      resolve(decodeTreeNode(index, buf))
    })
  })
}

function readAll (filename, length, pos, cb) {
  const buf = b4a.alloc(length)

  fs.open(filename, 'r', function (err, fd) {
    if (err) return cb(err)

    let offset = 0

    fs.read(fd, buf, offset, buf.byteLength, pos, function loop (err, read) {
      if (err) return done(err)
      if (read === 0) return done(new Error('Partial read'))
      offset += read
      if (offset === buf.byteLength) return done(null, buf)
      fs.read(fd, offset, buf.byteLength - offset, buf, pos + offset, loop)
    })

    function done (err, value) {
      fs.close(fd, () => cb(err, value))
    }
  })
}

async function readdir (dir) {
  try {
    return await fs.promises.readdir(dir)
  } catch {
    return []
  }
}

async function exists (file) {
  try {
    await fs.promises.stat(file)
    return true
  } catch {
    return false
  }
}

async function readFile (file) {
  try {
    return await fs.promises.readFile(file)
  } catch {
    return null
  }
}

async function rm (dir) {
  try {
    await fs.promises.rm(dir, { recursive: true })
  } catch {}
}

async function rmdir (dir) {
  try {
    await fs.promises.rmdir(dir)
  } catch {}
}

function * allBits (buffer) {
  for (let i = 0; i < buffer.byteLength; i += EMPTY_PAGE.byteLength) {
    const page = buffer.subarray(i, i + EMPTY_NODE.byteLength)
    if (b4a.equals(page, EMPTY_PAGE)) continue

    const view = new Uint32Array(page.buffer, page.byteOffset, EMPTY_PAGE.byteLength / 4)

    for (let j = 0; j < view.length; j++) {
      const n = view[j]
      if (n === 0) continue

      for (let k = 0; k < 32; k++) {
        const m = 1 << k
        if (n & m) yield i * 8 + j * 32 + k
      }
    }
  }
}

function readOplog (oplog) {
  return new Promise(function (resolve) {
    fs.readFile(oplog, function (err, buffer) {
      if (err) return resolve(null)

      const state = { start: 0, end: buffer.byteLength, buffer }
      const headers = [1, 0]

      const h1 = decodeOplogHeader(state)
      state.start = 4096

      const h2 = decodeOplogHeader(state)
      state.start = 4096 * 2

      if (!h1 && !h2) return resolve(null)

      if (h1 && !h2) {
        headers[0] = h1.header
        headers[1] = h1.header
      } else if (!h1 && h2) {
        headers[0] = (h2.header + 1) & 1
        headers[1] = h2.header
      } else {
        headers[0] = h1.header
        headers[1] = h2.header
      }

      const header = (headers[0] + headers[1]) & 1
      const result = { path: path.dirname(oplog), header: null, entries: [] }
      const decoded = []

      result.header = header ? h2.message : h1.message

      if (result.header.external) {
        fs.readFile(path.join(oplog, '../header'), function (err, buffer) {
          if (err) return resolve(null)
          const start = result.header.external.start
          const end = start + result.header.external.length
          result.header = m.oplog.header.decode({ buffer, start, end })
          finish()
        })
        return
      }

      finish()

      function finish () {
        while (true) {
          const entry = decodeOplogEntry(state)
          if (!entry) break
          if (entry.header !== header) break

          decoded.push(entry)
        }

        while (decoded.length > 0 && decoded[decoded.length - 1].partial) decoded.pop()

        for (const e of decoded) {
          result.entries.push(e.message)
        }

        resolve(result)
      }
    })
  })
}

function noop () {}
// needed here for compat, copied from old hypercore, do not change this

const c = require('compact-encoding')
const b4a = require('b4a')

const EMPTY = b4a.alloc(0)
const DEFAULT_NAMESPACE = b4a.from('4144eea531e483d54e0c14f4ca68e0644f355343ff6fcb0f005200e12cd747cb', 'hex')

const hashes = {
  preencode (state, m) {
    state.end++ // small uint
  },
  encode (state, m) {
    if (m === 'blake2b') {
      c.uint.encode(state, 0)
      return
    }

    throw new Error('Unknown hash: ' + m)
  },
  decode (state) {
    const n = c.uint.decode(state)
    if (n === 0) return 'blake2b'
    throw new Error('Unknown hash id: ' + n)
  }
}

const signatures = {
  preencode (state, m) {
    state.end++ // small uint
  },
  encode (state, m) {
    if (m === 'ed25519') {
      c.uint.encode(state, 0)
      return
    }

    throw new Error('Unknown signature: ' + m)
  },
  decode (state) {
    const n = c.uint.decode(state)
    if (n === 0) return 'ed25519'
    throw new Error('Unknown signature id: ' + n)
  }
}

const signer = {
  preencode (state, m) {
    signatures.preencode(state, m.signature)
    c.fixed32.preencode(state, m.namespace)
    c.fixed32.preencode(state, m.publicKey)
  },
  encode (state, m) {
    signatures.encode(state, m.signature)
    c.fixed32.encode(state, m.namespace)
    c.fixed32.encode(state, m.publicKey)
  },
  decode (state) {
    return {
      signature: signatures.decode(state),
      namespace: c.fixed32.decode(state),
      publicKey: c.fixed32.decode(state)
    }
  }
}

const signerArray = c.array(signer)

const prologue = {
  preencode (state, p) {
    c.fixed32.preencode(state, p.hash)
    c.uint.preencode(state, p.length)
  },
  encode (state, p) {
    c.fixed32.encode(state, p.hash)
    c.uint.encode(state, p.length)
  },
  decode (state) {
    return {
      hash: c.fixed32.decode(state),
      length: c.uint.decode(state)
    }
  }
}

const manifestv0 = {
  preencode (state, m) {
    hashes.preencode(state, m.hash)
    state.end++ // type

    if (m.prologue && m.signers.length === 0) {
      c.fixed32.preencode(state, m.prologue.hash)
      return
    }

    if (m.quorum === 1 && m.signers.length === 1 && !m.allowPatch) {
      signer.preencode(state, m.signers[0])
    } else {
      state.end++ // flags
      c.uint.preencode(state, m.quorum)
      signerArray.preencode(state, m.signers)
    }
  },
  encode (state, m) {
    hashes.encode(state, m.hash)

    if (m.prologue && m.signers.length === 0) {
      c.uint.encode(state, 0)
      c.fixed32.encode(state, m.prologue.hash)
      return
    }

    if (m.quorum === 1 && m.signers.length === 1 && !m.allowPatch) {
      c.uint.encode(state, 1)
      signer.encode(state, m.signers[0])
    } else {
      c.uint.encode(state, 2)
      c.uint.encode(state, m.allowPatch ? 1 : 0)
      c.uint.encode(state, m.quorum)
      signerArray.encode(state, m.signers)
    }
  },
  decode (state) {
    const hash = hashes.decode(state)
    const type = c.uint.decode(state)

    if (type > 2) throw new Error('Unknown type: ' + type)

    if (type === 0) {
      return {
        version: 0,
        hash,
        allowPatch: false,
        quorum: 0,
        signers: [],
        prologue: {
          hash: c.fixed32.decode(state),
          length: 0
        }
      }
    }

    if (type === 1) {
      return {
        version: 0,
        hash,
        allowPatch: false,
        quorum: 1,
        signers: [signer.decode(state)],
        prologue: null
      }
    }

    const flags = c.uint.decode(state)

    return {
      version: 0,
      hash,
      allowPatch: (flags & 1) !== 0,
      quorum: c.uint.decode(state),
      signers: signerArray.decode(state),
      prologue: null
    }
  }
}

const manifest = exports.manifest = {
  preencode (state, m) {
    state.end++ // version
    if (m.version === 0) return manifestv0.preencode(state, m)

    state.end++ // flags
    hashes.preencode(state, m.hash)

    c.uint.preencode(state, m.quorum)
    signerArray.preencode(state, m.signers)
    if (m.prologue) prologue.preencode(state, m.prologue)
  },
  encode (state, m) {
    c.uint.encode(state, m.version)
    if (m.version === 0) return manifestv0.encode(state, m)

    c.uint.encode(state, (m.allowPatch ? 1 : 0) | (m.prologue ? 2 : 0) | (m.unencrypted ? 4 : 0))
    hashes.encode(state, m.hash)

    c.uint.encode(state, m.quorum)
    signerArray.encode(state, m.signers)
    if (m.prologue) prologue.encode(state, m.prologue)
  },
  decode (state) {
    const v = c.uint.decode(state)
    if (v === 0) return manifestv0.decode(state)
    if (v !== 1) throw new Error('Unknown version: ' + v)

    const flags = c.uint.decode(state)
    const hash = hashes.decode(state)
    const quorum = c.uint.decode(state)
    const signers = signerArray.decode(state)
    const unencrypted = (flags & 4) !== 0

    return {
      version: 1,
      hash,
      allowPatch: (flags & 1) !== 0,
      quorum,
      signers,
      prologue: (flags & 2) === 0 ? null : prologue.decode(state),
      unencrypted
    }
  }
}

const node = {
  preencode (state, n) {
    c.uint.preencode(state, n.index)
    c.uint.preencode(state, n.size)
    c.fixed32.preencode(state, n.hash)
  },
  encode (state, n) {
    c.uint.encode(state, n.index)
    c.uint.encode(state, n.size)
    c.fixed32.encode(state, n.hash)
  },
  decode (state) {
    return {
      index: c.uint.decode(state),
      size: c.uint.decode(state),
      hash: c.fixed32.decode(state)
    }
  }
}

const nodeArray = c.array(node)

const wire = exports.wire = {}

wire.handshake = {
  preencode (state, m) {
    c.uint.preencode(state, 1)
    c.fixed32.preencode(state, m.capability)
  },
  encode (state, m) {
    c.uint.encode(state, m.seeks ? 1 : 0)
    c.fixed32.encode(state, m.capability)
  },
  decode (state) {
    const flags = c.uint.decode(state)
    return {
      seeks: (flags & 1) !== 0,
      capability: c.fixed32.decode(state)
    }
  }
}

const requestBlock = {
  preencode (state, b) {
    c.uint.preencode(state, b.index)
    c.uint.preencode(state, b.nodes)
  },
  encode (state, b) {
    c.uint.encode(state, b.index)
    c.uint.encode(state, b.nodes)
  },
  decode (state) {
    return {
      index: c.uint.decode(state),
      nodes: c.uint.decode(state)
    }
  }
}

const requestSeek = {
  preencode (state, s) {
    c.uint.preencode(state, s.bytes)
    c.uint.preencode(state, s.padding)
  },
  encode (state, s) {
    c.uint.encode(state, s.bytes)
    c.uint.encode(state, s.padding)
  },
  decode (state) {
    return {
      bytes: c.uint.decode(state),
      padding: c.uint.decode(state)
    }
  }
}

const requestUpgrade = {
  preencode (state, u) {
    c.uint.preencode(state, u.start)
    c.uint.preencode(state, u.length)
  },
  encode (state, u) {
    c.uint.encode(state, u.start)
    c.uint.encode(state, u.length)
  },
  decode (state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

wire.request = {
  preencode (state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.id)
    c.uint.preencode(state, m.fork)

    if (m.block) requestBlock.preencode(state, m.block)
    if (m.hash) requestBlock.preencode(state, m.hash)
    if (m.seek) requestSeek.preencode(state, m.seek)
    if (m.upgrade) requestUpgrade.preencode(state, m.upgrade)
    if (m.priority) c.uint.preencode(state, m.priority)
  },
  encode (state, m) {
    const flags = (m.block ? 1 : 0) | (m.hash ? 2 : 0) | (m.seek ? 4 : 0) | (m.upgrade ? 8 : 0) | (m.manifest ? 16 : 0) | (m.priority ? 32 : 0)

    c.uint.encode(state, flags)
    c.uint.encode(state, m.id)
    c.uint.encode(state, m.fork)

    if (m.block) requestBlock.encode(state, m.block)
    if (m.hash) requestBlock.encode(state, m.hash)
    if (m.seek) requestSeek.encode(state, m.seek)
    if (m.upgrade) requestUpgrade.encode(state, m.upgrade)
    if (m.priority) c.uint.encode(state, m.priority)
  },
  decode (state) {
    const flags = c.uint.decode(state)

    return {
      id: c.uint.decode(state),
      fork: c.uint.decode(state),
      block: flags & 1 ? requestBlock.decode(state) : null,
      hash: flags & 2 ? requestBlock.decode(state) : null,
      seek: flags & 4 ? requestSeek.decode(state) : null,
      upgrade: flags & 8 ? requestUpgrade.decode(state) : null,
      manifest: (flags & 16) !== 0,
      priority: flags & 32 ? c.uint.decode(state) : 0
    }
  }
}

wire.cancel = {
  preencode (state, m) {
    c.uint.preencode(state, m.request)
  },
  encode (state, m) {
    c.uint.encode(state, m.request)
  },
  decode (state, m) {
    return {
      request: c.uint.decode(state)
    }
  }
}

const dataUpgrade = {
  preencode (state, u) {
    c.uint.preencode(state, u.start)
    c.uint.preencode(state, u.length)
    nodeArray.preencode(state, u.nodes)
    nodeArray.preencode(state, u.additionalNodes)
    c.optionalBuffer.preencode(state, u.signature)
  },
  encode (state, u) {
    c.uint.encode(state, u.start)
    c.uint.encode(state, u.length)
    nodeArray.encode(state, u.nodes)
    nodeArray.encode(state, u.additionalNodes)
    c.optionalBuffer.encode(state, u.signature)
  },
  decode (state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state),
      nodes: nodeArray.decode(state),
      additionalNodes: nodeArray.decode(state),
      signature: c.optionalBuffer.decode(state)
    }
  }
}

const dataSeek = {
  preencode (state, s) {
    c.uint.preencode(state, s.bytes)
    nodeArray.preencode(state, s.nodes)
  },
  encode (state, s) {
    c.uint.encode(state, s.bytes)
    nodeArray.encode(state, s.nodes)
  },
  decode (state) {
    return {
      bytes: c.uint.decode(state),
      nodes: nodeArray.decode(state)
    }
  }
}

const dataBlock = {
  preencode (state, b) {
    c.uint.preencode(state, b.index)
    c.optionalBuffer.preencode(state, b.value)
    nodeArray.preencode(state, b.nodes)
  },
  encode (state, b) {
    c.uint.encode(state, b.index)
    c.optionalBuffer.encode(state, b.value)
    nodeArray.encode(state, b.nodes)
  },
  decode (state) {
    return {
      index: c.uint.decode(state),
      value: c.optionalBuffer.decode(state) || EMPTY,
      nodes: nodeArray.decode(state)
    }
  }
}

const dataHash = {
  preencode (state, b) {
    c.uint.preencode(state, b.index)
    nodeArray.preencode(state, b.nodes)
  },
  encode (state, b) {
    c.uint.encode(state, b.index)
    nodeArray.encode(state, b.nodes)
  },
  decode (state) {
    return {
      index: c.uint.decode(state),
      nodes: nodeArray.decode(state)
    }
  }
}

wire.data = {
  preencode (state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.request)
    c.uint.preencode(state, m.fork)

    if (m.block) dataBlock.preencode(state, m.block)
    if (m.hash) dataHash.preencode(state, m.hash)
    if (m.seek) dataSeek.preencode(state, m.seek)
    if (m.upgrade) dataUpgrade.preencode(state, m.upgrade)
    if (m.manifest) manifest.preencode(state, m.manifest)
  },
  encode (state, m) {
    const flags = (m.block ? 1 : 0) | (m.hash ? 2 : 0) | (m.seek ? 4 : 0) | (m.upgrade ? 8 : 0) | (m.manifest ? 16 : 0)

    c.uint.encode(state, flags)
    c.uint.encode(state, m.request)
    c.uint.encode(state, m.fork)

    if (m.block) dataBlock.encode(state, m.block)
    if (m.hash) dataHash.encode(state, m.hash)
    if (m.seek) dataSeek.encode(state, m.seek)
    if (m.upgrade) dataUpgrade.encode(state, m.upgrade)
    if (m.manifest) manifest.encode(state, m.manifest)
  },
  decode (state) {
    const flags = c.uint.decode(state)

    return {
      request: c.uint.decode(state),
      fork: c.uint.decode(state),
      block: flags & 1 ? dataBlock.decode(state) : null,
      hash: flags & 2 ? dataHash.decode(state) : null,
      seek: flags & 4 ? dataSeek.decode(state) : null,
      upgrade: flags & 8 ? dataUpgrade.decode(state) : null,
      manifest: flags & 16 ? manifest.decode(state) : null
    }
  }
}

wire.noData = {
  preencode (state, m) {
    c.uint.preencode(state, m.request)
  },
  encode (state, m) {
    c.uint.encode(state, m.request)
  },
  decode (state, m) {
    return {
      request: c.uint.decode(state)
    }
  }
}

wire.want = {
  preencode (state, m) {
    c.uint.preencode(state, m.start)
    c.uint.preencode(state, m.length)
  },
  encode (state, m) {
    c.uint.encode(state, m.start)
    c.uint.encode(state, m.length)
  },
  decode (state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

wire.unwant = {
  preencode (state, m) {
    c.uint.preencode(state, m.start)
    c.uint.preencode(state, m.length)
  },
  encode (state, m) {
    c.uint.encode(state, m.start)
    c.uint.encode(state, m.length)
  },
  decode (state, m) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

wire.range = {
  preencode (state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.start)
    if (m.length !== 1) c.uint.preencode(state, m.length)
  },
  encode (state, m) {
    c.uint.encode(state, (m.drop ? 1 : 0) | (m.length === 1 ? 2 : 0))
    c.uint.encode(state, m.start)
    if (m.length !== 1) c.uint.encode(state, m.length)
  },
  decode (state) {
    const flags = c.uint.decode(state)

    return {
      drop: (flags & 1) !== 0,
      start: c.uint.decode(state),
      length: (flags & 2) !== 0 ? 1 : c.uint.decode(state)
    }
  }
}

wire.bitfield = {
  preencode (state, m) {
    c.uint.preencode(state, m.start)
    c.uint32array.preencode(state, m.bitfield)
  },
  encode (state, m) {
    c.uint.encode(state, m.start)
    c.uint32array.encode(state, m.bitfield)
  },
  decode (state, m) {
    return {
      start: c.uint.decode(state),
      bitfield: c.uint32array.decode(state)
    }
  }
}

wire.sync = {
  preencode (state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.fork)
    c.uint.preencode(state, m.length)
    c.uint.preencode(state, m.remoteLength)
  },
  encode (state, m) {
    c.uint.encode(state, (m.canUpgrade ? 1 : 0) | (m.uploading ? 2 : 0) | (m.downloading ? 4 : 0) | (m.hasManifest ? 8 : 0))
    c.uint.encode(state, m.fork)
    c.uint.encode(state, m.length)
    c.uint.encode(state, m.remoteLength)
  },
  decode (state) {
    const flags = c.uint.decode(state)

    return {
      fork: c.uint.decode(state),
      length: c.uint.decode(state),
      remoteLength: c.uint.decode(state),
      canUpgrade: (flags & 1) !== 0,
      uploading: (flags & 2) !== 0,
      downloading: (flags & 4) !== 0,
      hasManifest: (flags & 8) !== 0
    }
  }
}

wire.reorgHint = {
  preencode (state, m) {
    c.uint.preencode(state, m.from)
    c.uint.preencode(state, m.to)
    c.uint.preencode(state, m.ancestors)
  },
  encode (state, m) {
    c.uint.encode(state, m.from)
    c.uint.encode(state, m.to)
    c.uint.encode(state, m.ancestors)
  },
  decode (state) {
    return {
      from: c.uint.encode(state),
      to: c.uint.encode(state),
      ancestors: c.uint.encode(state)
    }
  }
}

wire.extension = {
  preencode (state, m) {
    c.string.preencode(state, m.name)
    c.raw.preencode(state, m.message)
  },
  encode (state, m) {
    c.string.encode(state, m.name)
    c.raw.encode(state, m.message)
  },
  decode (state) {
    return {
      name: c.string.decode(state),
      message: c.raw.decode(state)
    }
  }
}

const keyValue = {
  preencode (state, p) {
    c.string.preencode(state, p.key)
    c.optionalBuffer.preencode(state, p.value)
  },
  encode (state, p) {
    c.string.encode(state, p.key)
    c.optionalBuffer.encode(state, p.value)
  },
  decode (state) {
    return {
      key: c.string.decode(state),
      value: c.optionalBuffer.decode(state)
    }
  }
}

const treeUpgrade = {
  preencode (state, u) {
    c.uint.preencode(state, u.fork)
    c.uint.preencode(state, u.ancestors)
    c.uint.preencode(state, u.length)
    c.optionalBuffer.preencode(state, u.signature)
  },
  encode (state, u) {
    c.uint.encode(state, u.fork)
    c.uint.encode(state, u.ancestors)
    c.uint.encode(state, u.length)
    c.optionalBuffer.encode(state, u.signature)
  },
  decode (state) {
    return {
      fork: c.uint.decode(state),
      ancestors: c.uint.decode(state),
      length: c.uint.decode(state),
      signature: c.optionalBuffer.decode(state)
    }
  }
}

const bitfieldUpdate = { // TODO: can maybe be folded into a HAVE later on with the most recent spec
  preencode (state, b) {
    state.end++ // flags
    c.uint.preencode(state, b.start)
    c.uint.preencode(state, b.length)
  },
  encode (state, b) {
    state.buffer[state.start++] = b.drop ? 1 : 0
    c.uint.encode(state, b.start)
    c.uint.encode(state, b.length)
  },
  decode (state) {
    const flags = c.uint.decode(state)
    return {
      drop: (flags & 1) !== 0,
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

const oplog = exports.oplog = {}

oplog.entry = {
  preencode (state, m) {
    state.end++ // flags
    if (m.userData) keyValue.preencode(state, m.userData)
    if (m.treeNodes) nodeArray.preencode(state, m.treeNodes)
    if (m.treeUpgrade) treeUpgrade.preencode(state, m.treeUpgrade)
    if (m.bitfield) bitfieldUpdate.preencode(state, m.bitfield)
  },
  encode (state, m) {
    const s = state.start++
    let flags = 0

    if (m.userData) {
      flags |= 1
      keyValue.encode(state, m.userData)
    }
    if (m.treeNodes) {
      flags |= 2
      nodeArray.encode(state, m.treeNodes)
    }
    if (m.treeUpgrade) {
      flags |= 4
      treeUpgrade.encode(state, m.treeUpgrade)
    }
    if (m.bitfield) {
      flags |= 8
      bitfieldUpdate.encode(state, m.bitfield)
    }

    state.buffer[s] = flags
  },
  decode (state) {
    const flags = c.uint.decode(state)
    return {
      userData: (flags & 1) !== 0 ? keyValue.decode(state) : null,
      treeNodes: (flags & 2) !== 0 ? nodeArray.decode(state) : null,
      treeUpgrade: (flags & 4) !== 0 ? treeUpgrade.decode(state) : null,
      bitfield: (flags & 8) !== 0 ? bitfieldUpdate.decode(state) : null
    }
  }
}

const keyPair = {
  preencode (state, kp) {
    c.optionalBuffer.preencode(state, kp.publicKey)
    c.optionalBuffer.preencode(state, kp.secretKey)
  },
  encode (state, kp) {
    c.optionalBuffer.encode(state, kp.publicKey)
    c.optionalBuffer.encode(state, kp.secretKey)
  },
  decode (state) {
    return {
      publicKey: c.optionalBuffer.decode(state),
      secretKey: c.optionalBuffer.decode(state)
    }
  }
}

const reorgHint = {
  preencode (state, r) {
    c.uint.preencode(state, r.from)
    c.uint.preencode(state, r.to)
    c.uint.preencode(state, r.ancestors)
  },
  encode (state, r) {
    c.uint.encode(state, r.from)
    c.uint.encode(state, r.to)
    c.uint.encode(state, r.ancestors)
  },
  decode (state) {
    return {
      from: c.uint.decode(state),
      to: c.uint.decode(state),
      ancestors: c.uint.decode(state)
    }
  }
}

const reorgHintArray = c.array(reorgHint)

const hints = {
  preencode (state, h) {
    reorgHintArray.preencode(state, h.reorgs)
    c.uint.preencode(state, h.contiguousLength)
  },
  encode (state, h) {
    reorgHintArray.encode(state, h.reorgs)
    c.uint.encode(state, h.contiguousLength)
  },
  decode (state) {
    return {
      reorgs: reorgHintArray.decode(state),
      contiguousLength: state.start < state.end ? c.uint.decode(state) : 0
    }
  }
}

const treeHeader = {
  preencode (state, t) {
    c.uint.preencode(state, t.fork)
    c.uint.preencode(state, t.length)
    c.optionalBuffer.preencode(state, t.rootHash)
    c.optionalBuffer.preencode(state, t.signature)
  },
  encode (state, t) {
    c.uint.encode(state, t.fork)
    c.uint.encode(state, t.length)
    c.optionalBuffer.encode(state, t.rootHash)
    c.optionalBuffer.encode(state, t.signature)
  },
  decode (state) {
    return {
      fork: c.uint.decode(state),
      length: c.uint.decode(state),
      rootHash: c.optionalBuffer.decode(state),
      signature: c.optionalBuffer.decode(state)
    }
  }
}

const types = {
  preencode (state, t) {
    c.string.preencode(state, t.tree)
    c.string.preencode(state, t.bitfield)
    c.string.preencode(state, t.signer)
  },
  encode (state, t) {
    c.string.encode(state, t.tree)
    c.string.encode(state, t.bitfield)
    c.string.encode(state, t.signer)
  },
  decode (state) {
    return {
      tree: c.string.decode(state),
      bitfield: c.string.decode(state),
      signer: c.string.decode(state)
    }
  }
}

const externalHeader = {
  preencode (state, m) {
    c.uint.preencode(state, m.start)
    c.uint.preencode(state, m.length)
  },
  encode (state, m) {
    c.uint.encode(state, m.start)
    c.uint.encode(state, m.length)
  },
  decode (state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

const keyValueArray = c.array(keyValue)

oplog.header = {
  preencode (state, h) {
    state.end += 2 // version + flags
    if (h.external) {
      externalHeader.preencode(state, h.external)
      return
    }
    c.fixed32.preencode(state, h.key)
    if (h.manifest) manifest.preencode(state, h.manifest)
    if (h.keyPair) keyPair.preencode(state, h.keyPair)
    keyValueArray.preencode(state, h.userData)
    treeHeader.preencode(state, h.tree)
    hints.preencode(state, h.hints)
  },
  encode (state, h) {
    c.uint.encode(state, 1)
    if (h.external) {
      c.uint.encode(state, 1) // ONLY set the first big for clarity
      externalHeader.encode(state, h.external)
      return
    }
    c.uint.encode(state, (h.manifest ? 2 : 0) | (h.keyPair ? 4 : 0))
    c.fixed32.encode(state, h.key)
    if (h.manifest) manifest.encode(state, h.manifest)
    if (h.keyPair) keyPair.encode(state, h.keyPair)
    keyValueArray.encode(state, h.userData)
    treeHeader.encode(state, h.tree)
    hints.encode(state, h.hints)
  },
  decode (state) {
    const version = c.uint.decode(state)

    if (version > 1) {
      throw new Error('Invalid header version. Expected <= 1, got ' + version)
    }

    if (version === 0) {
      const old = {
        types: types.decode(state),
        userData: keyValueArray.decode(state),
        tree: treeHeader.decode(state),
        signer: keyPair.decode(state),
        hints: hints.decode(state)
      }

      return {
        external: null,
        key: old.signer.publicKey,
        manifest: {
          version: 0,
          hash: old.types.tree,
          allowPatch: false,
          quorum: 1,
          signers: [{
            signature: old.types.signer,
            namespace: DEFAULT_NAMESPACE,
            publicKey: old.signer.publicKey
          }],
          prologue: null
        },
        keyPair: old.signer.secretKey ? old.signer : null,
        userData: old.userData,
        tree: old.tree,
        hints: old.hints
      }
    }

    const flags = c.uint.decode(state)

    if (flags & 1) {
      return {
        external: externalHeader.decode(state),
        key: null,
        manifest: null,
        keyPair: null,
        userData: null,
        tree: null,
        hints: null
      }
    }

    return {
      external: null,
      key: c.fixed32.decode(state),
      manifest: (flags & 2) !== 0 ? manifest.decode(state) : null,
      keyPair: (flags & 4) !== 0 ? keyPair.decode(state) : null,
      userData: keyValueArray.decode(state),
      tree: treeHeader.decode(state),
      hints: hints.decode(state)
    }
  }
}

const uintArray = c.array(c.uint)

const multisigInput = {
  preencode (state, inp) {
    c.uint.preencode(state, inp.signer)
    c.fixed64.preencode(state, inp.signature)
    c.uint.preencode(state, inp.patch)
  },
  encode (state, inp) {
    c.uint.encode(state, inp.signer)
    c.fixed64.encode(state, inp.signature)
    c.uint.encode(state, inp.patch)
  },
  decode (state) {
    return {
      signer: c.uint.decode(state),
      signature: c.fixed64.decode(state),
      patch: c.uint.decode(state)
    }
  }
}

const patchEncodingv0 = {
  preencode (state, n) {
    c.uint.preencode(state, n.start)
    c.uint.preencode(state, n.length)
    uintArray.preencode(state, n.nodes)
  },
  encode (state, n) {
    c.uint.encode(state, n.start)
    c.uint.encode(state, n.length)
    uintArray.encode(state, n.nodes)
  },
  decode (state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state),
      nodes: uintArray.decode(state)
    }
  }
}

const multisigInputv0 = {
  preencode (state, n) {
    state.end++
    c.uint.preencode(state, n.signer)
    c.fixed64.preencode(state, n.signature)
    if (n.patch) patchEncodingv0.preencode(state, n.patch)
  },
  encode (state, n) {
    c.uint.encode(state, n.patch ? 1 : 0)
    c.uint.encode(state, n.signer)
    c.fixed64.encode(state, n.signature)
    if (n.patch) patchEncodingv0.encode(state, n.patch)
  },
  decode (state) {
    const flags = c.uint.decode(state)
    return {
      signer: c.uint.decode(state),
      signature: c.fixed64.decode(state),
      patch: (flags & 1) ? patchEncodingv0.decode(state) : null
    }
  }
}

const multisigInputArrayv0 = c.array(multisigInputv0)
const multisigInputArray = c.array(multisigInput)

const compactNode = {
  preencode (state, n) {
    c.uint.preencode(state, n.index)
    c.uint.preencode(state, n.size)
    c.fixed32.preencode(state, n.hash)
  },
  encode (state, n) {
    c.uint.encode(state, n.index)
    c.uint.encode(state, n.size)
    c.fixed32.encode(state, n.hash)
  },
  decode (state) {
    return {
      index: c.uint.decode(state),
      size: c.uint.decode(state),
      hash: c.fixed32.decode(state)
    }
  }
}

const compactNodeArray = c.array(compactNode)

exports.multiSignaturev0 = {
  preencode (state, s) {
    multisigInputArrayv0.preencode(state, s.proofs)
    compactNodeArray.preencode(state, s.patch)
  },
  encode (state, s) {
    multisigInputArrayv0.encode(state, s.proofs)
    compactNodeArray.encode(state, s.patch)
  },
  decode (state) {
    return {
      proofs: multisigInputArrayv0.decode(state),
      patch: compactNodeArray.decode(state)
    }
  }
}

exports.multiSignature = {
  preencode (state, s) {
    multisigInputArray.preencode(state, s.proofs)
    compactNodeArray.preencode(state, s.patch)
  },
  encode (state, s) {
    multisigInputArray.encode(state, s.proofs)
    compactNodeArray.encode(state, s.patch)
  },
  decode (state) {
    return {
      proofs: multisigInputArray.decode(state),
      patch: compactNodeArray.decode(state)
    }
  }
}
const c = require('compact-encoding')
const schema = require('../../encoding/spec/hyperschema')
const { core: coreKey } = require('../../lib/keys.js')
const View = require('../../lib/view.js')

const CORE_AUTH = schema.getEncoding('@core/auth')

const { CorestoreRX, CorestoreTX } = require('../../lib/tx.js')

async function core (core, { version, dryRun = false } = {}) {
  if (dryRun) return // dryRun mode not supported atm

  const rx = core.db.read({ autoDestroy: true })
  const storedAuthPromise = rx.get(coreKey.auth(core.core.corePointer))

  rx.tryFlush()

  const storedAuth = await storedAuthPromise
  if (!storedAuth) return

  const auth = c.decode(CORE_AUTH, storedAuth)
  await commitCoreMigration(auth, core, version)
}

module.exports = { core }

async function commitCoreMigration (auth, core, version) {
  const view = new View()
  const rx = new CorestoreRX(core.db, view)

  const storeCorePromise = rx.getCore(auth.discoveryKey)
  rx.tryFlush()

  const storeCore = await storeCorePromise

  storeCore.version = version

  const tx = new CorestoreTX(view)
  tx.putCore(auth.discoveryKey, storeCore)
  tx.apply()

  await View.flush(view.changes, core.db)
}
{
  "name": "hypercore-storage",
  "version": "3.2.0",
  "main": "index.js",
  "files": [
    "index.js",
    "lib/*.js",
    "encoding/*",
    "migrations/0/*.js",
    "migrations/1/*.js"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:bare": "brittle-bare test/all.js",
    "test:generate": "brittle -r test/all.js test/*.js",
    "test:node": "brittle-node test/all.js"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "description": "Storage engine for Hypercore",
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "fs/*": {
      "bare": "bare-fs/*",
      "default": "fs/*"
    },
    "os": {
      "bare": "bare-os",
      "default": "os"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    }
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/hypercore-storage.git"
  },
  "bugs": {
    "url": "https://github.com/holepunchto/hypercore-storage/issues"
  },
  "homepage": "https://github.com/holepunchto/hypercore-storage#readme",
  "dependencies": {
    "b4a": "^1.6.7",
    "bare-path": "^3.0.0",
    "compact-encoding": "^3.1.0",
    "device-file": "^2.1.2",
    "flat-tree": "^1.12.1",
    "hypercore-crypto": "^3.4.2",
    "hyperschema": "^1.21.0",
    "index-encoder": "^3.3.2",
    "resolve-reject-promise": "^1.0.0",
    "rocksdb-native": "^3.11.0",
    "scope-lock": "^1.2.4",
    "streamx": "^2.21.1",
    "xache": "^1.2.1"
  },
  "devDependencies": {
    "bare-os": "^3.9.1",
    "brittle": "^3.7.0",
    "hypercore-storage-2.9.0": "npm:hypercore-storage@^2.9.0",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "test-tmp": "^1.3.1"
  }
}
const { EventEmitter } = require('events')
const isOptions = require('is-options')
const crypto = require('hypercore-crypto')
const CoreStorage = require('hypercore-storage')
const c = require('compact-encoding')
const b4a = require('b4a')
const NoiseSecretStream = require('@hyperswarm/secret-stream')
const Protomux = require('protomux')
const id = require('hypercore-id-encoding')
const safetyCatch = require('safety-catch')
const unslab = require('unslab')
const flat = require('flat-tree')
const assert = require('nanoassert')

const { SMALL_WANTS } = require('./lib/feature-flags')
const { UPDATE_COMPAT } = require('./lib/wants')
const MarkBitfield = require('./lib/mark-bitfield')

const inspect = require('./lib/inspect')
const Core = require('./lib/core')
const Info = require('./lib/info')
const Download = require('./lib/download')
const DefaultEncryption = require('./lib/default-encryption')
const caps = require('./lib/caps')
const Replicator = require('./lib/replicator')
const { manifestHash, createManifest } = require('./lib/verifier')
const { ReadStream, WriteStream, ByteStream } = require('./lib/streams')
const { MerkleTree } = require('./lib/merkle-tree')
const { proof, verify } = require('./lib/fully-remote-proof')
const {
  ASSERTION,
  BAD_ARGUMENT,
  SESSION_CLOSED,
  SESSION_MOVED,
  SESSION_NOT_WRITABLE,
  SNAPSHOT_NOT_AVAILABLE,
  DECODING_ERROR,
  REQUEST_CANCELLED
} = require('hypercore-errors')

// Hypercore actually does not have any notion of max/min block sizes
// but we enforce 15mb to ensure smooth replication (each block is transmitted atomically)
const MAX_SUGGESTED_BLOCK_SIZE = 15 * 1024 * 1024

class Hypercore extends EventEmitter {
  constructor(storage, key, opts) {
    super()

    if (isOptions(storage) && !storage.db) {
      opts = storage
      storage = null
      key = opts.key || null
    } else if (isOptions(key)) {
      opts = key
      key = opts.key || null
    }

    if (key && typeof key === 'string') key = id.decode(key)
    if (!opts) opts = {}

    if (!storage) storage = opts.storage

    this.core = null
    this.state = null
    this.encryption = null
    this.extensions = new Map()

    this.valueEncoding = null
    this.encodeBatch = null
    this.activeRequests = []
    this.sessions = null
    this.ongc = null

    this.keyPair = opts.keyPair || null
    this.readable = true
    this.writable = false
    this.exclusive = false
    this.opened = false
    this.closed = false
    this.weak = !!opts.weak
    this.snapshotted = !!opts.snapshot
    this.onseq = opts.onseq || null
    this.onwait = opts.onwait || null
    this.wait = opts.wait !== false
    this.timeout = opts.timeout || 0
    this.preload = null
    this.closing = null
    this.opening = null

    this._readonly = opts.writable === false
    this._preappend = preappend.bind(this)
    this._snapshot = null
    this._findingPeers = 0
    this._active = opts.weak ? !!opts.active : opts.active !== false

    this.waits = 0

    // Mark & Sweep GC
    this._marking = false
    this._marks = null

    this._sessionIndex = -1
    this._stateIndex = -1 // maintained by session state
    this._monitorIndex = -1 // maintained by replication state

    this.opening = this._open(storage, key, opts)
    this.opening.catch(safetyCatch)

    this.on('newListener', maybeAddMonitor)
  }

  [Symbol.for('nodejs.util.inspect.custom')](depth, opts) {
    return inspect(this, depth, opts)
  }

  static MAX_SUGGESTED_BLOCK_SIZE = MAX_SUGGESTED_BLOCK_SIZE

  static DefaultEncryption = DefaultEncryption

  static SMALL_WANTS = SMALL_WANTS

  static enable(flag) {
    const enableCompat = (flag & SMALL_WANTS) === 0
    UPDATE_COMPAT(enableCompat)
  }

  static setRecoveryPeers(peers) {
    Core.setRecoveryPeers(peers)
  }

  static key(manifest, { compat, version, namespace } = {}) {
    if (b4a.isBuffer(manifest)) {
      manifest = { version, signers: [{ publicKey: manifest, namespace }] }
    }
    return compat ? manifest.signers[0].publicKey : manifestHash(createManifest(manifest))
  }

  static discoveryKey(key) {
    return crypto.discoveryKey(key)
  }

  static blockEncryptionKey(key, encryptionKey) {
    return DefaultEncryption.blockEncryptionKey(key, encryptionKey)
  }

  static getProtocolMuxer(stream) {
    return stream.noiseStream.userData
  }

  static createCore(storage, opts) {
    return new Core(Hypercore.defaultStorage(storage), { autoClose: false, ...opts })
  }

  static createProtocolStream(isInitiator, opts = {}) {
    let outerStream = Protomux.isProtomux(isInitiator)
      ? isInitiator.stream
      : isStream(isInitiator)
        ? isInitiator
        : opts.stream

    let noiseStream = null

    if (outerStream) {
      noiseStream = outerStream.noiseStream
    } else {
      noiseStream = new NoiseSecretStream(isInitiator, null, opts)
      outerStream = noiseStream.rawStream
    }
    if (!noiseStream) throw BAD_ARGUMENT('Invalid stream', this.discoveryKey)

    if (!noiseStream.userData) {
      const protocol = Protomux.from(noiseStream)

      if (opts.keepAlive !== false && noiseStream.keepAlive === 0) {
        noiseStream.setKeepAlive(5000)
      }
      noiseStream.userData = protocol
    }

    if (opts.ondiscoverykey) {
      const ondiscoverykey = createDiscoveryKeyHandler(opts.ondiscoverykey)
      noiseStream.userData.pair({ protocol: 'hypercore/alpha' }, ondiscoverykey)
    }

    return outerStream
  }

  static defaultStorage(storage, opts = {}) {
    if (CoreStorage.isCoreStorage(storage)) return storage

    const directory = storage
    return new CoreStorage(directory, opts)
  }

  static clearRequests(session, err) {
    Replicator.clearRequests(session, err)
  }

  static destroyRequests(session, err) {
    if (isRequestsDestroyed(session)) return
    Replicator.clearRequests(session, err)
    session.push(null) // mark as dead
  }

  static async treeHashFromStorage(session, length = session.length) {
    const roots = await MerkleTree.getRoots(session.state, length)
    return crypto.tree(roots)
  }

  snapshot(opts) {
    return this.session({ ...opts, snapshot: true })
  }

  compact() {
    return this.core.compact()
  }

  session(opts = {}) {
    if (this.closing) {
      // This makes the closing logic a lot easier. If this turns out to be a problem
      // in practice, open an issue and we'll try to make a solution for it.
      throw SESSION_CLOSED('Cannot make sessions on a closing core', this.discoveryKey)
    }
    if (opts.checkout !== undefined && !opts.name && !opts.atom) {
      throw ASSERTION('Checkouts are only supported on atoms or named sessions', this.discoveryKey)
    }

    const wait = opts.wait === false ? false : this.wait
    const writable = opts.writable === undefined ? !this._readonly : opts.writable === true
    const onwait = opts.onwait === undefined ? this.onwait : opts.onwait
    const onseq = opts.onseq === undefined ? this.onseq : opts.onseq
    const timeout = opts.timeout === undefined ? this.timeout : opts.timeout
    const weak = opts.weak === undefined ? this.weak : opts.weak
    const marking = this._marking
    const marks = this._marks
    const Clz = opts.class || Hypercore
    const s = new Clz(null, this.key, {
      ...opts,
      wait,
      onwait,
      onseq,
      timeout,
      writable,
      weak,
      parent: this
    })
    s._marking = marking
    s._marks = marks

    return s
  }

  async setEncryptionKey(key, opts) {
    if (!this.opened) await this.opening
    const encryption = this._getEncryptionProvider({ key, block: !!(opts && opts.block) })
    return this.setEncryption(encryption)
  }

  async setEncryption(encryption) {
    if (!this.opened) await this.opening

    if (encryption === null) {
      this.encryption = encryption
      return
    }

    if (!isEncryptionProvider(encryption)) {
      throw ASSERTION('Provider does not satisfy HypercoreEncryption interface', this.discoveryKey)
    }

    this.encryption = encryption
  }

  async setGroup(topic) {
    if (!this.opened) await this.opening
    return this.core.setGroup(topic)
  }

  setKeyPair(keyPair) {
    this.keyPair = keyPair
  }

  setActive(bool) {
    const active = !!bool
    if (active === this._active || this.closing) return
    this._active = active
    if (!this.opened) return
    this.core.replicator.updateActivity(this._active ? 1 : -1)
  }

  async _open(storage, key, opts) {
    const preload = opts.preload || (opts.parent && opts.parent.preload)

    if (preload) {
      this.sessions = [] // in case someone looks at it like with peers
      this.preload = preload
      opts = { ...opts, ...(await this.preload) }
      this.preload = null
    }

    const parent = opts.parent || null
    const core = opts.core || (parent && parent.core)
    const sessions = opts.sessions || (parent && parent.sessions)
    const ongc = opts.ongc || (parent && parent.ongc)

    if (core) this.core = core
    if (ongc) this.ongc = ongc
    if (sessions) this.sessions = sessions

    if (this.sessions === null) this.sessions = []
    this._sessionIndex = this.sessions.push(this) - 1

    if (this.core === null) initOnce(this, storage, key, opts)
    if (this._monitorIndex === -2) this.core.addMonitor(this)

    try {
      await this._openSession(opts)
    } catch (err) {
      if (this.core.autoClose && this.core.hasSession() === false) await this.core.close()

      if (this.exclusive) this.core.unlockExclusive()

      this.core.removeMonitor(this)
      this._removeSession()

      if (this.state !== null) this.state.removeSession(this)

      this.closed = true
      this.emit('close')
      throw err
    }

    // Setup automatic recovery if in repair mode
    if (this.core._repairMode) {
      const recoverTreeNodeFromPeersBound = this.recoverTreeNodeFromPeers.bind(this)
      this.once('repaired', () => {
        this.off('peer-add', recoverTreeNodeFromPeersBound)
      })
      this.on('peer-add', recoverTreeNodeFromPeersBound)
    }

    this.emit('ready')

    // if we are a weak session the core might have closed...
    if (this.core.closing) this.close().catch(safetyCatch)
  }

  _removeSession() {
    if (this._sessionIndex === -1) return
    const head = this.sessions.pop()
    if (head !== this) this.sessions[(head._sessionIndex = this._sessionIndex)] = head
    this._sessionIndex = -1
    if (this.ongc !== null) this.ongc(this)
  }

  async _openSession(opts) {
    if (this.core.opened === false) await this.core.ready()

    if (this.keyPair === null) this.keyPair = opts.keyPair || this.core.header.keyPair

    const parent = opts.parent || null
    if (parent && parent.encryption) this.encryption = parent.encryption

    const e = getEncryptionOption(opts)
    if (!this.encryption) this.encryption = this._getEncryptionProvider(e)

    this.writable = this._isWritable()

    if (opts.valueEncoding) {
      this.valueEncoding = c.from(opts.valueEncoding)
    }
    if (opts.encodeBatch) {
      this.encodeBatch = opts.encodeBatch
    }

    // one session sets for pushOnly for all
    if (opts.pushOnly === true) {
      this.core.replicator.setPushOnly(true)
    }

    if (parent) {
      if (parent._stateIndex === -1) await parent.ready()
      if (!this.keyPair) this.keyPair = parent.keyPair

      const ps = parent.state

      if (ps) {
        const shouldSnapshot = this.snapshotted && !ps.isSnapshot()
        this.state = shouldSnapshot ? await ps.snapshot() : ps.ref()
      }

      if (this.snapshotted && this.core && !this._snapshot) {
        this._updateSnapshot()
      }
    }

    if (opts.exclusive && opts.writable !== false) {
      this.exclusive = true
      await this.core.lockExclusive()
    }

    const parentState = parent ? parent.state : this.core.state
    const checkout = opts.checkout === undefined ? -1 : opts.checkout
    const state = this.state

    if (opts.atom) {
      this.state = await parentState.createSession(null, false, opts.atom)
      if (state) state.unref()
    } else if (opts.name) {
      // todo: need to make named sessions safe before ready
      // atm we always copy the state in passCapabilities
      this.state = await parentState.createSession(opts.name, !!opts.overwrite, null)
      if (state) state.unref() // ref'ed above in setup session
    }

    if (this.state && checkout !== -1) {
      if (!opts.name && !opts.atom) {
        throw ASSERTION('Checkouts must be named or atomized', this.discoveryKey)
      }
      if (checkout > this.state.length) {
        throw ASSERTION(
          `Invalid checkout ${checkout} for ${opts.name}, length is ${this.state.length}`,
          this.discoveryKey
        )
      }
      if (this.state.prologue && checkout < this.state.prologue.length) {
        throw ASSERTION(
          `Invalid checkout ${checkout} for ${opts.name}, prologue length is ${this.state.prologue.length}`,
          this.discoveryKey
        )
      }
      if (checkout < this.state.length) await this.state.truncate(checkout, this.fork)
    }

    if (this.state === null) {
      this.state = this.core.state.ref()
    }

    this.writable = this._isWritable()

    if (this.snapshotted && this.core) this._updateSnapshot()

    this.state.addSession(this)
    // TODO: we need to rework the core reference flow, as the state and session do not always agree now due to moveTo
    this.core = this.state.core // in case it was wrong...

    if (opts.userData) {
      const tx = this.state.storage.write()
      for (const [key, value] of Object.entries(opts.userData)) {
        tx.putUserData(key, value)
      }
      await tx.flush()
    }

    if (opts.manifest && !this.core.header.manifest) {
      await this.core.setManifest(createManifest(opts.manifest))
    }

    this.core.replicator.updateActivity(this._active ? 1 : 0)

    this.opened = true
  }

  get replicator() {
    return this.core === null ? null : this.core.replicator
  }

  _getSnapshot() {
    return {
      length: this.state.length,
      byteLength: this.state.byteLength,
      fork: this.state.fork
    }
  }

  _updateSnapshot() {
    const prev = this._snapshot
    const next = (this._snapshot = this._getSnapshot())

    if (!prev) return true
    return prev.length !== next.length || prev.fork !== next.fork
  }

  _isWritable() {
    if (this._readonly) return false
    if (this.state && !this.state.isDefault()) return true
    return !!(this.keyPair && this.keyPair.secretKey)
  }

  close({ error } = {}) {
    if (this.closing) return this.closing

    this.closing = this._close(error || null)
    return this.closing
  }

  clearRequests(activeRequests, error) {
    if (!activeRequests.length) return
    if (this.core) this.core.replicator.clearRequests(activeRequests, error)
  }

  async _close(error) {
    if (this.opened === false) {
      try {
        await this.opening
      } catch (err) {
        if (!this.closed) throw err
      }
    }

    if (this.closed === true) return

    this.core.removeMonitor(this)
    this.state.removeSession(this)
    this._removeSession()

    this.readable = false
    this.writable = false
    this.opened = false

    const gc = []
    for (const ext of this.extensions.values()) {
      if (ext.session === this) gc.push(ext)
    }
    for (const ext of gc) ext.destroy()

    this.core.replicator.findingPeers -= this._findingPeers
    this.core.replicator.clearRequests(this.activeRequests, error)
    this.core.replicator.updateActivity(this._active ? -1 : 0)

    this._findingPeers = 0

    this.state.unref()

    if (this.exclusive) this.core.unlockExclusive()

    if (this.core.hasSession()) {
      // emit "fake" close as this is a session
      this.closed = true
      this.emit('close')
      return
    }

    if (this.core.autoClose) await this.core.close()

    this.closed = true
    this.emit('close')
  }

  async commit(session, opts) {
    await this.ready()
    await session.ready()

    return this.state.commit(session.state, { keyPair: this.keyPair, ...opts })
  }

  replicate(isInitiator, opts = {}) {
    // Only limitation here is that ondiscoverykey doesn't work atm when passing a muxer directly,
    // because it doesn't really make a lot of sense.
    if (Protomux.isProtomux(isInitiator)) return this._attachToMuxer(isInitiator)

    // if same stream is passed twice, ignore the 2nd one before we make sessions etc
    if (isStream(isInitiator) && this._isAttached(isInitiator)) return isInitiator

    const protocolStream = Hypercore.createProtocolStream(isInitiator, opts)
    const noiseStream = protocolStream.noiseStream
    const protocol = noiseStream.userData

    this._attachToMuxer(protocol)

    return protocolStream
  }

  _isAttached(stream) {
    return (
      stream.userData &&
      this.core &&
      this.core.replicator &&
      this.core.replicator.attached(stream.userData)
    )
  }

  _attachToMuxer(mux) {
    if (this.opened) {
      this.core.replicator.attachTo(mux)
    } else {
      this.opening.then(() => this.core.replicator.attachTo(mux), mux.destroy.bind(mux))
    }

    return mux
  }

  get id() {
    return this.core === null ? null : this.core.id
  }

  get key() {
    return this.core === null ? null : this.core.key
  }

  get discoveryKey() {
    return this.core === null ? null : this.core.discoveryKey
  }

  get manifest() {
    return this.core === null ? null : this.core.manifest
  }

  get length() {
    if (this._snapshot) return this._snapshot.length
    return this.opened === false ? 0 : this.state.length
  }

  get signedLength() {
    return this.opened === false ? 0 : this.state.signedLength()
  }

  /**
   * Deprecated. Use `const { byteLength } = await core.info()`.
   */
  get byteLength() {
    if (this.opened === false) return 0
    if (this._snapshot) return this._snapshot.byteLength
    return this.state.byteLength - this.state.length * this.padding
  }

  get remoteContiguousLength() {
    if (this.opened === false) return 0
    return Math.min(this.core.state.length, this.core.header.hints.remoteContiguousLength)
  }

  get contiguousLength() {
    if (this.opened === false) return 0
    return Math.min(this.core.state.length, this.core.header.hints.contiguousLength)
  }

  get contiguousByteLength() {
    return 0
  }

  get fork() {
    if (this.opened === false) return 0
    return this.state.fork
  }

  get padding() {
    if (this.encryption && this.key && this.manifest) {
      return this.encryption.padding(this.core, this.length)
    }

    return 0
  }

  get peers() {
    return this.opened === false ? [] : this.core.replicator.peers
  }

  get globalCache() {
    return this.opened === false ? null : this.core.globalCache
  }

  get recovering() {
    return this.opened === false ? 0 : this.core.header.hints.recovering
  }

  ready() {
    return this.opening
  }

  async recover() {
    if (this.opened === false) await this.opening
    return this.state.waitForRecovery()
  }

  async setUserData(key, value) {
    if (this.opened === false) await this.opening
    const existing = await this.getUserData(key)
    if (existing && b4a.isBuffer(value) && b4a.equals(existing, value)) return
    await this.state.setUserData(key, value)
  }

  async getUserData(key) {
    if (this.opened === false) await this.opening
    const batch = this.state.storage.read()
    const p = batch.getUserData(key)
    batch.tryFlush()
    return p
  }

  transferSession(core) {
    // todo: validate we can move

    if (this.weak === false) {
      this.core.activeSessions--
      core.activeSessions++
    }

    if (this._monitorIndex >= 0) {
      this.core.removeMonitor(this)
      core.addMonitor(this)
    }

    const old = this.core

    this.core = core

    old.replicator.clearRequests(this.activeRequests, SESSION_MOVED())

    this.emit('migrate', this.key)
  }

  findingPeers() {
    this._findingPeers++
    if (this.core !== null && !this.closing) this.core.replicator.findingPeers++

    let once = true

    return () => {
      if (this.closing || !once) return
      once = false
      this._findingPeers--
      if (this.core !== null && --this.core.replicator.findingPeers === 0) {
        this.core.replicator.queueUpdateAll()
      }
    }
  }

  async info(opts) {
    if (this.opened === false) await this.opening

    return Info.from(this, opts)
  }

  async update(opts) {
    if (this.opened === false) await this.opening
    if (this.closing !== null) return false
    if (this.snapshotted) return false

    if (this.writable && (!opts || opts.force !== true)) return false

    const remoteWait = this._shouldWait(opts, this.core.replicator.findingPeers > 0)

    let upgraded = false

    if (await this.core.replicator.applyPendingReorg()) {
      upgraded = true
    }

    if (!upgraded && remoteWait) {
      const activeRequests = (opts && opts.activeRequests) || this.activeRequests
      if (isRequestsDestroyed(activeRequests)) throw REQUEST_CANCELLED()

      const req = this.core.replicator.addUpgrade(activeRequests)

      try {
        upgraded = await req.promise
      } catch (err) {
        if (isSessionMoved(err)) return this.update(opts)
        throw err
      }
    }

    if (!upgraded) return false
    return true
  }

  async seek(bytes, opts) {
    if (this.opened === false) await this.opening
    if (!isValidIndex(bytes)) throw ASSERTION('seek is invalid', this.discoveryKey)

    const activeRequests = (opts && opts.activeRequests) || this.activeRequests
    if (isRequestsDestroyed(activeRequests)) throw REQUEST_CANCELLED()

    if (this.encryption && !this.core.manifest) {
      const req = this.replicator.addUpgrade(activeRequests)
      try {
        await req.promise
      } catch (err) {
        if (isSessionMoved(err)) return this.seek(bytes, opts)
        throw err
      }
    }

    const s = MerkleTree.seek(this.state, bytes, this.padding)

    const offset = await s.update()
    if (offset) return offset

    if (this.closing !== null) {
      throw SESSION_CLOSED('cannot seek on a closed session', this.discoveryKey)
    }

    if (!this._shouldWait(opts, this.wait)) return null

    if (isRequestsDestroyed(activeRequests)) throw REQUEST_CANCELLED()
    const req = this.core.replicator.addSeek(activeRequests, s)

    const timeout = opts && opts.timeout !== undefined ? opts.timeout : this.timeout
    if (timeout) req.context.setTimeout(req, timeout)

    try {
      return await req.promise
    } catch (err) {
      if (isSessionMoved(err)) return this.seek(bytes, opts)
      throw err
    }
  }

  async has(start, end = start + 1) {
    if (this.opened === false) await this.opening
    if (!isValidIndex(start) || !isValidIndex(end)) {
      throw ASSERTION('has range is invalid', this.discoveryKey)
    }

    if (this.state.isDefault()) {
      if (end === start + 1) return this.core.bitfield.get(start)

      const i = this.core.bitfield.firstUnset(start)
      return i === -1 || i >= end
    }

    if (end === start + 1) {
      const rx = this.state.storage.read()
      const block = rx.getBlock(start)
      rx.tryFlush()

      return (await block) !== null
    }

    let count = 0

    const stream = this.state.storage.createBlockStream({ gte: start, lt: end })
    for await (const block of stream) {
      if (block === null) return false
      count++
    }

    return count === end - start
  }

  async get(index, opts) {
    if (this.opened === false) await this.opening
    if (!isValidIndex(index)) throw ASSERTION('block index is invalid', this.discoveryKey)

    if (this.closing !== null) {
      throw SESSION_CLOSED('cannot get on a closed session', this.discoveryKey)
    }

    const encoding =
      (opts && opts.valueEncoding && c.from(opts.valueEncoding)) || this.valueEncoding

    if (this.onseq !== null) this.onseq(index, this)
    if (this._marking) await this.markBlock(index)

    const req = this._get(index, opts)

    let block = await req
    if (!block) return null

    if (opts && opts.raw) return block

    if (this.encryption && (!opts || opts.decrypt !== false)) {
      // Copy the block as it might be shared with other sessions.
      block = b4a.from(block)

      await this.encryption.decrypt(index, block, this.core)
    }

    return this._decode(encoding, block, index)
  }

  async clear(start, end = start + 1, opts) {
    if (this.opened === false) await this.opening
    if (this.closing !== null) {
      throw SESSION_CLOSED('cannot clear on a closed session', this.discoveryKey)
    }

    if (typeof end === 'object') {
      opts = end
      end = start + 1
    }

    if (!isValidIndex(start) || !isValidIndex(end)) {
      throw ASSERTION('clear range is invalid', this.discoveryKey)
    }

    const cleared = opts && opts.diff ? { blocks: 0 } : null

    if (start >= end) return cleared
    if (start >= this.length) return cleared

    await this.state.clear(start, end, cleared)

    return cleared
  }

  async purge() {
    await this._closeAllSessions(null)
    await this.core.purge()
  }

  async _get(index, opts) {
    const block = await readBlock(this.state.storage.read(), index)

    if (block !== null) return block

    if (this.closing !== null) {
      throw SESSION_CLOSED('cannot get on a closed session', this.discoveryKey)
    }

    // snapshot should check if core has block
    if (this._snapshot !== null) {
      checkSnapshot(this, index)
      const coreBlock = await readBlock(this.core.state.storage.read(), index)

      checkSnapshot(this, index)
      if (coreBlock !== null) return coreBlock
    }

    // lets check the bitfield to see if we got it during the above async calls
    // this is the last resort before replication, so always safe.
    if (this.core.bitfield.get(index)) {
      const coreBlock = await readBlock(this.state.storage.read(), index)
      // TODO: this should not be needed, only needed atm in case we are doing a moveTo during this (we should fix)
      if (coreBlock !== null) return coreBlock
    }

    if (!this._shouldWait(opts, this.wait)) return null

    this.waits++
    if (opts && opts.onwait) opts.onwait(index, this)
    if (this.onwait) this.onwait(index, this)

    const activeRequests = (opts && opts.activeRequests) || this.activeRequests
    if (isRequestsDestroyed(activeRequests)) throw REQUEST_CANCELLED()

    const force = opts ? opts.force === true : false
    const req = this.core.replicator.addBlock(activeRequests, index, force)
    req.snapshot = index < this.length

    const timeout = opts && opts.timeout !== undefined ? opts.timeout : this.timeout
    if (timeout) req.context.setTimeout(req, timeout)

    let replicatedBlock = null

    try {
      replicatedBlock = await req.promise
    } catch (err) {
      if (isSessionMoved(err)) return this._get(index, opts)
      throw err
    }

    if (this._snapshot !== null) checkSnapshot(this, index)
    return maybeUnslab(replicatedBlock)
  }

  _shouldWait(opts, defaultValue) {
    if (opts) {
      if (opts.wait === false) return false
      if (opts.wait === true) return true
    }
    return defaultValue
  }

  _setupMarks() {
    if (this._marks === null) {
      const storage = this.snapshotted ? this.core.state.storage : this.state.storage
      this._marks = new MarkBitfield(storage)
    }
  }

  async markBlock(start, end = start + 1) {
    if (this.opened === false) await this.opening

    this._setupMarks()

    // TODO support as single rocks batch
    const setPromises = []
    for (let i = start; i < end; i++) {
      setPromises.push(this._marks.set(i, true))
    }

    return Promise.all(setPromises)
  }

  async clearMarkings() {
    if (this.opened === false) await this.opening

    this._setupMarks()

    await this._marks.clear()
    this._marks = null
  }

  async startMarking() {
    if (this._marking) {
      throw ASSERTION("Hypercore cannot be gc'ed when already in gc mode", this.discoveryKey)
    }
    if (this.state && this.state.name) {
      throw ASSERTION("Hypercore cannot be gc'ed when a named session", this.discoveryKey)
    }
    if (this.state && this.state.storage.atom) {
      throw ASSERTION("Hypercore cannot be gc'ed when an atomic session", this.discoveryKey)
    }
    if (this.opened === false) await this.opening
    await this.clearMarkings()

    this._marking = true
  }

  async sweep({ batchSize = 1000 } = {}) {
    if (this.opened === false) await this.opening

    assert(!this.snapshotted, 'Cannot sweep a snapshot')

    // No marks - load from storage
    this._setupMarks()

    let clearing = []
    let prevIndex = this.length
    for await (const index of this._marks.createMarkStream({ reverse: true })) {
      if (index + 1 === prevIndex) {
        prevIndex = index
        continue
      }
      clearing.push(this.clear(index + 1, prevIndex))
      if (clearing.length >= batchSize) {
        await Promise.all(clearing)
        clearing = []
      }
      prevIndex = index
    }
    // Clear range from the very start if not marked
    if (prevIndex > 0) clearing.push(this.clear(0, prevIndex))
    await Promise.all(clearing)

    this._marking = false
    await this.clearMarkings()
  }

  createReadStream(opts) {
    return new ReadStream(this, opts)
  }

  createWriteStream() {
    return new WriteStream(this)
  }

  createByteStream(opts) {
    return new ByteStream(this, opts)
  }

  download(range) {
    return new Download(this, range)
  }

  // TODO: get rid of this / deprecate it?
  undownload(range) {
    range.destroy(null)
  }

  // TODO: get rid of this / deprecate it?
  cancel(request) {
    // Do nothing for now
  }

  async truncate(newLength = 0, opts = {}) {
    if (this.opened === false) await this.opening
    if (this.closing) throw SESSION_CLOSED('Cannot append to a closed session', this.discoveryKey)

    const {
      fork = this.state.fork + 1,
      keyPair = this.keyPair,
      signature = null
    } = typeof opts === 'number' ? { fork: opts } : opts

    const isDefault = this.state === this.core.state
    const writable = !this._readonly && !!(signature || (keyPair && keyPair.secretKey))
    if (isDefault && writable === false && (newLength > 0 || fork !== this.state.fork)) {
      throw SESSION_NOT_WRITABLE('cannot append to a non-writable core', this.discoveryKey)
    }

    await this.state.truncate(newLength, fork, { keyPair, signature })

    // TODO: Should propagate from an event triggered by the oplog
    if (this.state === this.core.state) this.core.replicator.updateAll()
  }

  async append(blocks, opts = {}) {
    if (this.opened === false) await this.opening
    if (this.closing) throw SESSION_CLOSED('Cannot append to a closed session', this.discoveryKey)

    const isDefault = this.state === this.core.state
    const defaultKeyPair = this.state.name === null ? this.keyPair : null

    const { keyPair = defaultKeyPair, signature = null, maxLength, postappend = null } = opts
    const writable =
      !isDefault || !!signature || !!(keyPair && keyPair.secretKey) || opts.writable === true

    if (this._readonly || writable === false) {
      throw SESSION_NOT_WRITABLE('cannot append to a readonly core', this.discoveryKey)
    }

    blocks = Array.isArray(blocks) ? blocks : [blocks]

    const preappend = this.encryption && this._preappend

    const buffers = this.encodeBatch !== null ? this.encodeBatch(blocks) : new Array(blocks.length)

    if (this.encodeBatch === null) {
      for (let i = 0; i < blocks.length; i++) {
        buffers[i] = this._encode(this.valueEncoding, blocks[i])
      }
    }
    for (const b of buffers) {
      if (b.byteLength > MAX_SUGGESTED_BLOCK_SIZE) {
        throw BAD_ARGUMENT(
          'Appended block exceeds the maximum suggested block size',
          this.discoveryKey
        )
      }
    }

    return this.state.append(buffers, { keyPair, signature, preappend, postappend, maxLength })
  }

  async signable(length = -1, fork = -1) {
    if (this.opened === false) await this.opening
    if (length === -1) length = this.length
    if (fork === -1) fork = this.fork

    return caps.treeSignable(this.key, await this.treeHash(length), length, fork)
  }

  async treeHash(length = -1) {
    if (this.opened === false) await this.opening
    if (length === -1) length = this.length
    if (length > 0 && !(await this.has(length - 1))) await this.get(length - 1)

    const roots = await MerkleTree.getRoots(this.state, length)
    return crypto.tree(roots)
  }

  async missingNodes(index) {
    if (this.opened === false) await this.opening
    return await MerkleTree.missingNodes(this.core.state, 2 * index, this.core.state.length)
  }

  async proof(opts) {
    if (this.opened === false) await this.opening
    const rx = this.state.storage.read()
    const proofPromise = MerkleTree.proof(this.state, rx, opts)
    const blockPromise = opts && opts.block ? rx.getBlock(opts.block.index) : null
    rx.tryFlush()
    const [proof, block] = await Promise.all([proofPromise, blockPromise])
    const settled = await proof.settle()
    if (block) settled.block.value = block
    return settled
  }

  async applyProof(proof, from) {
    if (this.opened === false) await this.opening
    return this.core.verify(proof, from)
  }

  async verifyFullyRemote(proof) {
    if (this.opened === false) await this.opening
    const batch = await MerkleTree.verifyFullyRemote(this.state, proof)
    await this.core._verifyBatchUpgrade(batch, proof.manifest)
    return batch
  }

  generateRemoteProofForTreeNode(treeNodeIndex) {
    const blockProofIndex = flat.rightSpan(treeNodeIndex) / 2
    return proof(this, {
      index: blockProofIndex,
      // + 1 to length so the block is included
      upgrade: { start: 0, length: blockProofIndex + 1 }
    })
  }

  async recoverFromRemoteProof(remoteProof) {
    this.core.replicator.setPushOnly(true)
    this.core._repairMode = true

    await this.core.state.mutex.lock()

    try {
      const p = await verify(this.core.db, remoteProof)
      if (!p) return false

      const tx = this.core.storage.write()
      for (const node of p.proof.upgrade.nodes) {
        tx.putTreeNode(node)
      }
      await tx.flush()

      const succeed = p.proof.upgrade.nodes.length !== 0
      if (succeed) {
        this.core.replicator.setPushOnly(false)
      }
      return succeed
    } finally {
      this.core.state.mutex.unlock()
    }
  }

  recoverTreeNodeFromPeers() {
    this.core.replicator.setPushOnly(true)

    for (const peer of this.core.replicator.peers) {
      const req = {
        id: 0,
        fork: this.fork,
        upgrade: {
          start: 0,
          length: this.length
        }
      }
      peer.wireRequest.send(req)
    }
  }

  registerExtension(name, handlers = {}) {
    if (this.extensions.has(name)) {
      const ext = this.extensions.get(name)
      ext.handlers = handlers
      ext.encoding = c.from(handlers.encoding || c.buffer)
      ext.session = this
      return ext
    }

    const ext = {
      name,
      handlers,
      encoding: c.from(handlers.encoding || c.buffer),
      session: this,
      send(message, peer) {
        const buffer = c.encode(this.encoding, message)
        peer.extension(name, buffer)
      },
      broadcast(message) {
        const buffer = c.encode(this.encoding, message)
        for (const peer of this.session.peers) {
          peer.extension(name, buffer)
        }
      },
      destroy() {
        for (const peer of this.session.peers) {
          if (peer.extensions.get(name) === ext) peer.extensions.delete(name)
        }
        this.session.extensions.delete(name)
      },
      _onmessage(state, peer) {
        const m = this.encoding.decode(state)
        if (this.handlers.onmessage) this.handlers.onmessage(m, peer)
      }
    }

    this.extensions.set(name, ext)

    if (this.core === null) this._monitorIndex = -2
    else this.core.addMonitor(this)

    for (const peer of this.peers) {
      peer.extensions.set(name, ext)
    }

    return ext
  }

  _encode(enc, val) {
    const state = { start: this.padding, end: this.padding, buffer: null }

    if (b4a.isBuffer(val)) {
      if (state.start === 0) return val
      state.end += val.byteLength
    } else if (enc) {
      enc.preencode(state, val)
    } else {
      val = b4a.from(val)
      if (state.start === 0) return val
      state.end += val.byteLength
    }

    state.buffer = b4a.allocUnsafe(state.end)

    if (enc) enc.encode(state, val)
    else state.buffer.set(val, state.start)

    return state.buffer
  }

  _decode(enc, block, index) {
    if (this.encryption) block = block.subarray(this.encryption.padding(this.core, index))
    try {
      if (enc) return c.decode(enc, block)
    } catch (err) {
      throw DECODING_ERROR(err.message, this.discoveryKey)
    }
    return block
  }

  _getEncryptionProvider(e) {
    if (isEncryptionProvider(e)) return e
    if (!e || !e.key) return null
    return new DefaultEncryption(e.key, this.key, { block: e.block, compat: this.core.compat })
  }
}

module.exports = Hypercore

function isStream(s) {
  return typeof s === 'object' && s && typeof s.pipe === 'function'
}

async function preappend(blocks) {
  const offset = this.state.length
  const fork = this.state.encryptionFork

  for (let i = 0; i < blocks.length; i++) {
    await this.encryption.encrypt(offset + i, blocks[i], fork, this.core)
  }
}

function isValidIndex(index) {
  return index === 0 || index > 0
}

function maybeUnslab(block) {
  // Unslab only when it takes up less then half the slab
  return block !== null && 2 * block.byteLength < block.buffer.byteLength ? unslab(block) : block
}

function checkSnapshot(snapshot, index) {
  if (index >= snapshot.state.snapshotCompatLength) {
    throw SNAPSHOT_NOT_AVAILABLE(
      `snapshot at index ${index} not available (max compat length ${snapshot.state.snapshotCompatLength})`,
      snapshot.discoveryKey
    )
  }
}

function readBlock(rx, index) {
  const promise = rx.getBlock(index)
  rx.tryFlush()
  return promise
}

function initOnce(session, storage, key, opts) {
  if (storage === null) storage = opts.storage || null
  if (key === null) key = opts.key || null

  session.core = new Core(Hypercore.defaultStorage(storage), {
    preopen: opts.preopen,
    eagerUpgrade: opts.eagerUpgrade !== false,
    notDownloadingLinger: opts.notDownloadingLinger,
    allowFork: opts.allowFork !== false,
    allowPush: !!opts.allowPush,
    pushOnly: !!opts.pushOnly,
    alwaysLatestBlock: !!opts.allowLatestBlock,
    inflightRange: opts.inflightRange,
    compat: opts.compat === true,
    force: opts.force,
    createIfMissing: opts.createIfMissing,
    discoveryKey: opts.discoveryKey,
    overwrite: opts.overwrite,
    key,
    keyPair: opts.keyPair,
    legacy: opts.legacy,
    manifest: opts.manifest,
    group: opts.group,
    globalCache: opts.globalCache || null // session is a temp option, not to be relied on unless you know what you are doing (no semver guarantees)
  })
}

function maybeAddMonitor(name) {
  if (name === 'append' || name === 'truncate') return
  if (this._monitorIndex >= 0 || this.closing) return

  if (this.core === null) {
    this._monitorIndex = -2
  } else {
    this.core.addMonitor(this)
  }
}

function isSessionMoved(err) {
  return err.code === 'SESSION_MOVED'
}

function getEncryptionOption(opts) {
  // old style, supported for now but will go away
  if (opts.encryptionKey) return { key: opts.encryptionKey, block: !!opts.isBlockKey }
  if (!opts.encryption) return null
  return b4a.isBuffer(opts.encryption) ? { key: opts.encryption } : opts.encryption
}

function isEncryptionProvider(e) {
  return e && isFunction(e.padding) && isFunction(e.encrypt) && isFunction(e.decrypt)
}

function isFunction(fn) {
  return !!fn && typeof fn === 'function'
}

function createDiscoveryKeyHandler(fn) {
  return ondiscoverykey
  function ondiscoverykey(id) {
    if (!id || id.byteLength !== 32) throw BAD_ARGUMENT('Invalid discovery key')
    return fn(id)
  }
}

function isRequestsDestroyed(activeRequests) {
  // TODO: move this to an object instead so we can store a property in next major
  return activeRequests.length > 0 && activeRequests[0] === null
}
const crypto = require('hypercore-crypto')
const flat = require('flat-tree')
const b4a = require('b4a')
const { MerkleTree } = require('./merkle-tree')

module.exports = async function auditCore(
  core,
  { tree = true, blocks = true, bitfield = true, dryRun = false } = {}
) {
  const length = core.state.length
  const stats = {
    treeNodes: 0,
    blocks: 0,
    bits: 0,
    droppedTreeNodes: 0,
    droppedBlocks: 0,
    droppedBits: 0,
    corrupt: false
  }

  // audit the tree
  if (tree) {
    let tx = null

    const roots = await MerkleTree.getRootsFromStorage(core.state.storage, length)
    const stack = []

    for (const r of roots) {
      if (r === null) {
        if (!dryRun) {
          const storage = core.state.storage
          await storage.store.deleteCore(storage.core)
          return null
        }

        stats.corrupt = true
      }

      stack.push(r)
    }

    stats.treeNodes += roots.length

    while (stack.length > 0) {
      const node = stack.pop()

      if ((node.index & 1) === 0) continue

      const [left, right] = flat.children(node.index)

      const rx = core.state.storage.read()
      const leftNodePromise = rx.getTreeNode(left)
      const rightNodePromise = rx.getTreeNode(right)

      rx.tryFlush()

      const [leftNode, rightNode] = await Promise.all([leftNodePromise, rightNodePromise])

      if (isBadTree(node, leftNode, rightNode)) {
        if (!tx && !stats.corrupt) tx = core.state.storage.write()
        const [l, r] = flat.spans(node.index)
        tx.deleteTreeNodeRange(l, r + 1)
        stats.droppedTreeNodes++
        continue
      }

      if (!leftNode) continue

      stats.treeNodes += 2
      stack.push(leftNode, rightNode)
    }

    if (tx && !dryRun) await tx.flush()
  }

  // audit the blocks
  if (blocks) {
    let tx = null

    for await (const block of core.state.storage.createBlockStream()) {
      if (!core.bitfield.get(block.index)) {
        if (!tx && !stats.corrupt) tx = core.state.storage.write()
        tx.deleteBlock(block.index)
        stats.droppedBlocks++
      }

      const rx = core.state.storage.read()
      const treeNodePromise = rx.getTreeNode(2 * block.index)

      rx.tryFlush()

      const treeNode = await treeNodePromise

      if (isBadBlock(treeNode, block.value)) {
        if (!tx && !stats.corrupt) tx = core.state.storage.write()
        tx.deleteBlock(block.index)
        stats.droppedBlocks++
        continue
      }

      stats.blocks++
    }

    if (tx && !dryRun) await tx.flush()
  }

  if (bitfield) {
    let tx = null

    for (const index of allBits(core.bitfield)) {
      const rx = core.state.storage.read()
      const blockPromise = rx.getBlock(index)

      rx.tryFlush()

      const block = await blockPromise
      if (!block) {
        stats.droppedBits++
        if (dryRun) continue

        if (!tx && !stats.corrupt) tx = core.state.storage.write()

        core.bitfield.set(index, false)

        const page = core.bitfield.getBitfield(index)
        if (page.bitfield) tx.putBitfieldPage(page.index, page.bitfield)
        else tx.deleteBitfieldPage(page.index)
        continue
      }

      stats.bits++
    }

    if (tx && !dryRun) await tx.flush()
  }

  return stats
}

function isBadBlock(node, block) {
  if (!node) return true
  const hash = crypto.data(block)
  return !b4a.equals(hash, node.hash) || node.size !== block.byteLength
}

function isBadTree(parent, left, right) {
  if (!left && !right) return false
  if (!left || !right) return true
  const hash = crypto.parent(left, right)
  return !b4a.equals(hash, parent.hash) || parent.size !== left.size + right.size
}

function* allBits(bitfield) {
  let i = 0
  if (bitfield.get(0)) yield 0
  while (true) {
    i = bitfield.findFirst(true, i + 1)
    if (i === -1) break
    yield i
  }
}
const b4a = require('b4a')
const quickbit = require('./compat').quickbit

module.exports = class BitInterlude {
  constructor() {
    this.ranges = []
  }

  contiguousLength(from) {
    for (const r of this.ranges) {
      if (r.start > from) break
      if (!r.value && r.start <= from) return r.start
    }

    // TODO: be smarter
    while (this.get(from) === true) from++
    return from
  }

  get(index) {
    let start = 0
    let end = this.ranges.length

    while (start < end) {
      const mid = (start + end) >> 1
      const r = this.ranges[mid]

      if (index < r.start) {
        end = mid
        continue
      }

      if (index >= r.end) {
        if (mid === start) break
        start = mid
        continue
      }

      return r.value
    }

    return false
  }

  setRange(start, end, value) {
    if (start === end) return

    let r = null

    for (let i = 0; i < this.ranges.length; i++) {
      r = this.ranges[i]

      // if already inside, stop
      if (r.start <= start && end <= r.end) {
        if (value === r.value) return

        const ranges = mergeRanges(r, { start, end, value })
        this.ranges.splice(i, 1, ...ranges)

        return
      }

      // we wanna overun the interval
      if (start > r.end) {
        continue
      }

      // we overran but this interval is ending after us, move it back
      if (end >= r.start && end <= r.end) {
        r.start = r.value === value ? start : end
        if (r.value !== value) this.ranges.splice(i, 0, { start, end, value })
        return
      }

      // we overran but our start is contained in this interval, move start back
      if (start >= r.start && start <= r.end) {
        if (r.value !== value) {
          r.end = start // Crop current comparison

          // If there's a next range
          if (this.ranges.length - 1 > i) {
            const next = this.ranges[i + 1]
            // If the same, go next
            if (next.value === value) continue
            // Else we overlap so update next range
            if (next.start < end) next.start = end
          }

          this.ranges.splice(++i, 0, { start, end, value })
          return
        }

        start = r.start
      }

      let remove = 0

      for (let j = i; j < this.ranges.length; j++) {
        const n = this.ranges[j]
        if (n.start > end || n.value !== value) break
        if (n.start <= end && n.end > end) end = n.end
        remove++
      }

      this.ranges.splice(i, remove, { start, end, value })
      return
    }

    if (r !== null) {
      if (start <= r.end && end > r.end) {
        r.end = end
        return
      }

      // we never
      if (r.end > start) return
    }

    this.ranges.push({ start, end, value })
  }

  flush(tx, bitfield) {
    if (!this.ranges.length) return []

    let index = this.ranges[0].start
    const final = this.ranges[this.ranges.length - 1].end

    let i = 0

    while (index < final) {
      const page = bitfield.getBitfield(index) // read only
      const pageIndex = page ? page.index : bitfield.getPageIndex(index)

      const buf = b4a.allocUnsafe(bitfield.getPageByteLength())

      if (page) {
        const src = page.bitfield // Uint32Array
        buf.set(b4a.from(src.buffer, src.byteOffset, src.byteLength), 0)
      } else {
        b4a.fill(buf, 0)
      }

      const last = (pageIndex + 1) * (buf.byteLength << 3)
      const offset = pageIndex * (buf.byteLength << 3)

      let hasValue = false

      while (i < this.ranges.length) {
        const { start, end, value } = this.ranges[i]

        if (!hasValue && value) hasValue = true

        const from = start < index ? index : start
        const to = end < last ? end : last

        quickbit.fill(buf, value, from - offset, to - offset)

        index = to

        if (to === last) break

        i++
      }

      if (page || hasValue) tx.putBitfieldPage(pageIndex, buf)
    }

    return this.ranges
  }
}

function mergeRanges(a, b) {
  const ranges = []
  if (a.start < b.start) ranges.push({ start: a.start, end: b.start, value: a.value })
  ranges.push({ start: b.start, end: b.end, value: b.value })
  if (b.end < a.end) ranges.push({ start: b.end, end: a.end, value: a.value })

  return ranges
}
const BigSparseArray = require('big-sparse-array')
const b4a = require('b4a')
const quickbit = require('./compat').quickbit

const BITS_PER_PAGE = 32768
const BYTES_PER_PAGE = BITS_PER_PAGE / 8
const WORDS_PER_PAGE = BYTES_PER_PAGE / 4
const BITS_PER_SEGMENT = 2097152
const BYTES_PER_SEGMENT = BITS_PER_SEGMENT / 8
const WORDS_PER_SEGMENT = BYTES_PER_SEGMENT / 4
const INITIAL_WORDS_PER_SEGMENT = 1024
const PAGES_PER_SEGMENT = BITS_PER_SEGMENT / BITS_PER_PAGE
const SEGMENT_GROWTH_FACTOR = 4

class BitfieldPage {
  constructor(index, segment) {
    this.index = index
    this.offset = index * BYTES_PER_PAGE - segment.offset
    this.bitfield = null
    this.segment = segment

    segment.add(this)
  }

  get tree() {
    return this.segment.tree
  }

  get(index, dirty) {
    return quickbit.get(this.bitfield, index)
  }

  set(index, val) {
    if (quickbit.set(this.bitfield, index, val)) {
      this.tree.update(this.offset * 8 + index)
    }
  }

  setRange(start, end, val) {
    quickbit.fill(this.bitfield, val, start, end)

    let i = Math.floor(start / 128)
    const n = i + Math.ceil((end - start) / 128)

    while (i <= n) this.tree.update(this.offset * 8 + i++ * 128)
  }

  findFirst(val, position) {
    return quickbit.findFirst(this.bitfield, val, position)
  }

  findLast(val, position) {
    return quickbit.findLast(this.bitfield, val, position)
  }

  count(start, length, val) {
    const end = start + length

    let i = start
    let c = 0

    while (length > 0) {
      const l = this.findFirst(val, i)
      if (l === -1 || l >= end) return c

      const h = this.findFirst(!val, l + 1)
      if (h === -1 || h >= end) return c + end - l

      c += h - l
      length -= h - i
      i = h
    }

    return c
  }
}

class BitfieldSegment {
  constructor(index, bitfield) {
    this.index = index
    this.offset = index * BYTES_PER_SEGMENT
    this.tree = quickbit.Index.from(bitfield, BYTES_PER_SEGMENT)
    this.pages = new Array(PAGES_PER_SEGMENT)
  }

  get bitfield() {
    return this.tree.field
  }

  add(page) {
    const i = page.index - this.index * PAGES_PER_SEGMENT
    this.pages[i] = page

    const start = i * WORDS_PER_PAGE
    const end = start + WORDS_PER_PAGE

    if (end >= this.bitfield.length) this.reallocate(end)

    page.bitfield = this.bitfield.subarray(start, end)
  }

  reallocate(length) {
    let target = this.bitfield.length
    while (target < length) target *= SEGMENT_GROWTH_FACTOR

    const bitfield = new Uint32Array(target)
    bitfield.set(this.bitfield)

    this.tree = quickbit.Index.from(bitfield, BYTES_PER_SEGMENT)

    for (let i = 0; i < this.pages.length; i++) {
      const page = this.pages[i]
      if (!page) continue

      const start = i * WORDS_PER_PAGE
      const end = start + WORDS_PER_PAGE

      page.bitfield = bitfield.subarray(start, end)
    }
  }

  findFirst(val, position) {
    position = this.tree.skipFirst(!val, position)

    let j = position & (BITS_PER_PAGE - 1)
    let i = (position - j) / BITS_PER_PAGE

    if (i >= PAGES_PER_SEGMENT) return -1

    while (i < this.pages.length) {
      const p = this.pages[i]

      let index = -1

      if (p) index = p.findFirst(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_PAGE + index

      j = 0
      i++
    }

    return -1
  }

  findLast(val, position) {
    position = this.tree.skipLast(!val, position)

    let j = position & (BITS_PER_PAGE - 1)
    let i = (position - j) / BITS_PER_PAGE

    if (i >= PAGES_PER_SEGMENT) return -1

    while (i >= 0) {
      const p = this.pages[i]

      let index = -1

      if (p) index = p.findLast(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_PAGE + index

      j = BITS_PER_PAGE - 1
      i--
    }

    return -1
  }
}

module.exports = class Bitfield {
  static BITS_PER_PAGE = BITS_PER_PAGE
  static BYTES_PER_PAGE = BYTES_PER_PAGE

  constructor(buffer) {
    this.resumed = !!(buffer && buffer.byteLength >= 0)

    this._pages = new BigSparseArray()
    this._segments = new BigSparseArray()

    const view = this.resumed
      ? new Uint32Array(buffer.buffer, buffer.byteOffset, Math.floor(buffer.byteLength / 4))
      : new Uint32Array(INITIAL_WORDS_PER_SEGMENT)

    for (let i = 0; i < view.length; i += WORDS_PER_SEGMENT) {
      let bitfield = view.subarray(i, i + WORDS_PER_SEGMENT)
      let length = WORDS_PER_SEGMENT

      if (i === 0) {
        length = INITIAL_WORDS_PER_SEGMENT
        while (length < bitfield.length) length *= SEGMENT_GROWTH_FACTOR
      }

      if (bitfield.length !== length) {
        const copy = new Uint32Array(length)
        copy.set(bitfield, 0)
        bitfield = copy
      }

      const segment = new BitfieldSegment(i / WORDS_PER_SEGMENT, bitfield)
      this._segments.set(segment.index, segment)

      for (let j = 0; j < bitfield.length; j += WORDS_PER_PAGE) {
        const page = new BitfieldPage((i + j) / WORDS_PER_PAGE, segment)
        this._pages.set(page.index, page)
      }
    }
  }

  static from(bitfield) {
    return new Bitfield(bitfield.toBuffer(bitfield._pages.maxLength * BITS_PER_PAGE))
  }

  toBuffer(length) {
    const pages = Math.ceil(length / BITS_PER_PAGE)
    const buffer = b4a.allocUnsafe(pages * BYTES_PER_PAGE)

    for (let i = 0; i < pages; i++) {
      const page = this._pages.get(i)
      const offset = i * BYTES_PER_PAGE

      if (page) {
        const buf = b4a.from(
          page.bitfield.buffer,
          page.bitfield.byteOffset,
          page.bitfield.byteLength
        )

        buffer.set(buf, offset)
      } else {
        buffer.fill(0, offset, offset + BYTES_PER_PAGE)
      }
    }

    return buffer
  }

  getBitfield(index) {
    const i = this.getPageIndex(index)

    const p = this._pages.get(i)
    return p || null
  }

  merge(bitfield, length) {
    let i = 0

    while (i < length) {
      const start = bitfield.firstSet(i)
      if (start === -1) break

      i = bitfield.firstUnset(start)

      if (i === -1 || i > length) i = length

      this.setRange(start, i, true)

      if (i >= length) break
    }
  }

  get(index) {
    const j = index & (BITS_PER_PAGE - 1)
    const i = (index - j) / BITS_PER_PAGE

    const p = this._pages.get(i)

    return p ? p.get(j) : false
  }

  getPageByteLength() {
    return BYTES_PER_PAGE
  }

  getPageIndex(index) {
    const j = index & (BITS_PER_PAGE - 1)
    return (index - j) / BITS_PER_PAGE
  }

  getPage(index, create) {
    const i = this.getPageIndex(index)

    let p = this._pages.get(i)

    if (p) return p

    if (!create) return null

    const k = Math.floor(i / PAGES_PER_SEGMENT)
    const s =
      this._segments.get(k) ||
      this._segments.set(
        k,
        new BitfieldSegment(
          k,
          new Uint32Array(k === 0 ? INITIAL_WORDS_PER_SEGMENT : WORDS_PER_SEGMENT)
        )
      )

    p = this._pages.set(i, new BitfieldPage(i, s))

    return p
  }

  set(index, val) {
    const j = index & (BITS_PER_PAGE - 1)
    const i = (index - j) / BITS_PER_PAGE

    let p = this._pages.get(i)

    if (!p && val) {
      const k = Math.floor(i / PAGES_PER_SEGMENT)
      const s =
        this._segments.get(k) ||
        this._segments.set(
          k,
          new BitfieldSegment(
            k,
            new Uint32Array(k === 0 ? INITIAL_WORDS_PER_SEGMENT : WORDS_PER_SEGMENT)
          )
        )

      p = this._pages.set(i, new BitfieldPage(i, s))
    }

    if (p) p.set(j, val)
  }

  setRange(start, end, val) {
    let j = start & (BITS_PER_PAGE - 1)
    let i = (start - j) / BITS_PER_PAGE

    while (start < end) {
      let p = this._pages.get(i)

      if (!p && val) {
        const k = Math.floor(i / PAGES_PER_SEGMENT)
        const s =
          this._segments.get(k) ||
          this._segments.set(
            k,
            new BitfieldSegment(
              k,
              new Uint32Array(k === 0 ? INITIAL_WORDS_PER_SEGMENT : WORDS_PER_SEGMENT)
            )
          )

        p = this._pages.set(i, new BitfieldPage(i, s))
      }

      const offset = i * BITS_PER_PAGE
      const last = Math.min(end - offset, BITS_PER_PAGE)
      const range = last - j

      if (p) p.setRange(j, last, val)

      j = 0
      i++
      start += range
    }
  }

  findFirst(val, position) {
    let j = position & (BITS_PER_SEGMENT - 1)
    let i = (position - j) / BITS_PER_SEGMENT

    while (i < this._segments.maxLength) {
      const s = this._segments.get(i)

      let index = -1

      if (s) index = s.findFirst(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_SEGMENT + index

      j = 0
      i++
    }

    return val ? -1 : this._segments.maxLength * BITS_PER_SEGMENT
  }

  firstSet(position) {
    return this.findFirst(true, position)
  }

  firstUnset(position) {
    return this.findFirst(false, position)
  }

  findLast(val, position) {
    let j = position & (BITS_PER_SEGMENT - 1)
    let i = (position - j) / BITS_PER_SEGMENT

    while (i >= 0) {
      const s = this._segments.get(i)

      let index = -1

      if (s) index = s.findLast(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_SEGMENT + index

      j = BITS_PER_SEGMENT - 1
      i--
    }

    return -1
  }

  lastSet(position) {
    return this.findLast(true, position)
  }

  lastUnset(position) {
    return this.findLast(false, position)
  }

  hasUnset(start, length) {
    const end = start + length

    let j = start & (BITS_PER_SEGMENT - 1)
    let i = (start - j) / BITS_PER_SEGMENT

    while (i < this._segments.maxLength) {
      const s = this._segments.get(i)
      const index = s ? s.findFirst(false, j) : j
      if (index !== -1) return i * BITS_PER_SEGMENT + index < end

      j = 0
      i++

      if (i * BITS_PER_SEGMENT >= end) return false
    }

    return true
  }

  hasSet(start, length) {
    const end = start + length

    let j = start & (BITS_PER_SEGMENT - 1)
    let i = (start - j) / BITS_PER_SEGMENT

    while (i < this._segments.maxLength) {
      const s = this._segments.get(i)

      let index = -1

      if (s) index = s.findFirst(true, j)

      if (index !== -1) return i * BITS_PER_SEGMENT + index < end

      j = 0
      i++

      if (i * BITS_PER_SEGMENT >= end) return false
    }

    return false
  }

  count(start, length, val) {
    let j = start & (BITS_PER_PAGE - 1)
    let i = (start - j) / BITS_PER_PAGE
    let c = 0

    while (length > 0) {
      const p = this._pages.get(i)

      const end = Math.min(j + length, BITS_PER_PAGE)
      const range = end - j

      if (p) c += p.count(j, range, val)
      else if (!val) c += range

      j = 0
      i++
      length -= range
    }

    return c
  }

  countSet(start, length) {
    return this.count(start, length, true)
  }

  countUnset(start, length) {
    return this.count(start, length, false)
  }

  *want(start, length) {
    if (start & 31) {
      const d = start & 31
      start -= d
      length += d
    }

    let j = start & (BITS_PER_SEGMENT - 1)
    let i = (start - j) / BITS_PER_SEGMENT

    while (length > 0) {
      const s = this._segments.get(i)

      if (s) {
        let end = Math.min(j + length, BITS_PER_SEGMENT)
        if (end & 31) end += 32 - (end & 31)

        yield {
          start: i * BITS_PER_SEGMENT + j,
          bitfield: s.bitfield.subarray(j / 32, end / 32)
        }
      }

      j = 0
      i++
      length -= BITS_PER_SEGMENT
    }
  }

  clear(tx) {
    return tx.deleteBitfieldPageRange(0, -1)
  }

  onupdate(ranges) {
    for (const { start, end, value } of ranges) {
      this.setRange(start, end, value)
    }
  }

  static async open(storage, length) {
    if (length === 0) return new Bitfield(storage, null)

    const pages = Math.ceil(length / BITS_PER_PAGE)
    const buffer = b4a.alloc(pages * BYTES_PER_PAGE)
    const stream = storage.createBitfieldStream({ lt: pages })

    for await (const { index, page } of stream) {
      buffer.set(page, index * BYTES_PER_PAGE)
    }

    return new Bitfield(buffer)
  }
}
const crypto = require('hypercore-crypto')
const sodium = require('sodium-universal')
const b4a = require('b4a')
const c = require('compact-encoding')

// TODO: rename this to "crypto" and move everything hashing related etc in here
// Also lets move the tree stuff from hypercore-crypto here

const [
  TREE,
  REPLICATE_INITIATOR,
  REPLICATE_RESPONDER,
  MANIFEST,
  DEFAULT_NAMESPACE,
  DEFAULT_ENCRYPTION
] = crypto.namespace('hypercore', 6)

exports.MANIFEST = MANIFEST
exports.DEFAULT_NAMESPACE = DEFAULT_NAMESPACE
exports.DEFAULT_ENCRYPTION = DEFAULT_ENCRYPTION

exports.replicate = function (isInitiator, key, handshakeHash) {
  const out = b4a.allocUnsafe(32)
  sodium.crypto_generichash_batch(
    out,
    [isInitiator ? REPLICATE_INITIATOR : REPLICATE_RESPONDER, key],
    handshakeHash
  )
  return out
}

exports.treeSignable = function (manifestHash, treeHash, length, fork) {
  const state = { start: 0, end: 112, buffer: b4a.allocUnsafe(112) }
  c.fixed32.encode(state, TREE)
  c.fixed32.encode(state, manifestHash)
  c.fixed32.encode(state, treeHash)
  c.uint64.encode(state, length)
  c.uint64.encode(state, fork)
  return state.buffer
}

exports.treeSignableCompat = function (hash, length, fork, noHeader) {
  const end = noHeader ? 48 : 80
  const state = { start: 0, end, buffer: b4a.allocUnsafe(end) }
  if (!noHeader) c.fixed32.encode(state, TREE) // ultra legacy mode, kill in future major
  c.fixed32.encode(state, hash)
  c.uint64.encode(state, length)
  c.uint64.encode(state, fork)
  return state.buffer
}
// Export the appropriate version of `quickbit-universal` as the plain import
// may resolve to an older version in some environments
let quickbit = require('quickbit-universal')
if (
  typeof quickbit.findFirst !== 'function' ||
  typeof quickbit.findLast !== 'function' ||
  typeof quickbit.clear !== 'function'
) {
  // This should always load the fallback from the locally installed version
  quickbit = require('quickbit-universal/fallback')
}
exports.quickbit = quickbit
const crypto = require('hypercore-crypto')
const flat = require('flat-tree')
const b4a = require('b4a')
const quickbit = require('quickbit-universal')
const Bitfield = require('./bitfield')

const MAX_BATCH_USED = 4 * 1024 * 1024
const MIN_BATCH_USED = 512 * 1024

// just in its own file as its a bit involved

module.exports = copyPrologue

async function copyPrologue(src, dst) {
  const prologue = dst.header.manifest.prologue

  if (src.length < prologue.length || prologue.length === 0) return

  const stack = []
  const roots = flat.fullRoots(prologue.length * 2)
  const batch = { roots, first: true, last: false, contig: 0, used: 0, tree: [], blocks: [] }

  for (let i = 0; i < roots.length; i++) {
    const node = roots[i]
    batch.tree.push(node)
    stack.push(node)
  }

  let lastPage = -1
  let lastBlock = -1

  for await (const data of src.storage.createBlockStream({
    gte: 0,
    lt: prologue.length,
    reverse: true
  })) {
    if (walkTree(stack, data.index * 2, batch) === false) {
      throw new Error('Missing block or tree node for ' + data.index)
    }

    batch.contig = data.index + 1 === lastBlock ? batch.contig + 1 : 1
    lastBlock = data.index

    const page = getBitfieldPage(data.index)
    batch.blocks.push(data)

    if (lastPage !== page) batch.used += 4096
    batch.used += Math.max(data.value.byteLength, 128) // 128 is just a sanity number to avoid mega batches

    // always safe to partially flush so we do that ondemand to reduce memory usage...
    if ((batch.used >= MIN_BATCH_USED && page !== lastPage) || batch.used >= MAX_BATCH_USED) {
      await flushBatch(prologue, src, dst, batch)
    }

    lastPage = page
  }

  if (lastBlock !== 0) batch.contig = 0

  batch.last = true
  await flushBatch(prologue, src, dst, batch)
}

async function flushBatch(prologue, src, dst, batch) {
  const nodePromises = []

  const srcReader = src.storage.read()
  for (const index of batch.tree) {
    nodePromises.push(srcReader.getTreeNode(index))
  }
  srcReader.tryFlush()

  const nodes = await Promise.all(nodePromises)

  const pagePromises = []
  const dstReader = dst.storage.read()

  const headPromise = batch.first ? dstReader.getHead() : null
  if (headPromise) headPromise.catch(noop)

  let lastPage = -1
  for (const { index } of batch.blocks) {
    const page = getBitfieldPage(index)
    if (page === lastPage) continue
    lastPage = page
    pagePromises.push(dstReader.getBitfieldPage(page))
  }

  dstReader.tryFlush()

  const pages = await Promise.all(pagePromises)
  const head = headPromise === null ? null : await headPromise
  const userData = []

  // reads done!

  if (batch.first) {
    const roots = nodes.slice(0, batch.roots.length)

    for (const node of roots) {
      if (!node) throw new Error('Missing nodes for prologue hash')
    }

    const treeHash = crypto.tree(roots)
    if (!b4a.equals(treeHash, prologue.hash)) throw new Error('Prologue does not match source')
  }

  if (batch.first) {
    for await (const data of src.storage.createUserDataStream()) userData.push(data)
  }

  for (let i = 0; i < pages.length; i++) {
    if (!pages[i]) pages[i] = b4a.alloc(4096)
  }

  const tx = dst.storage.write()

  for (const node of nodes) tx.putTreeNode(node)

  lastPage = -1
  let pageIndex = -1

  for (const { index, value } of batch.blocks) {
    const page = getBitfieldPage(index)

    if (page !== lastPage) {
      lastPage = page
      pageIndex++
      // queue the page now, we mutate it below but its the same ref
      tx.putBitfieldPage(pageIndex, pages[pageIndex])
    }

    const pageBuffer = pages[pageIndex]
    quickbit.set(pageBuffer, getBitfieldOffset(index), true)
    tx.putBlock(index, value)
  }

  for (const { key, value } of userData) {
    tx.putUserData(key, value)
  }

  let upgraded = batch.first && !head
  if (upgraded) {
    tx.setHead(prologueToTree(prologue))
  }

  await tx.flush()

  if (upgraded) {
    const roots = nodes.slice(0, batch.roots.length)
    dst.state.setRoots(roots)
    dst.header.tree = prologueToTree(prologue)
  }

  if (userData.length > 0) {
    dst.header.userData = userData.concat(dst.header.userData)
  }

  if (batch.contig) {
    // TODO: we need to persist this somehow
    dst.header.hints.contiguousLength = batch.contig
  }

  let start = 0
  let length = 0

  // update in memory bitfield
  for (const { index } of batch.blocks) {
    if (start === 0 || start - 1 === index) {
      length++
    } else {
      if (length > 0) signalReplicator(dst, upgraded, start, length)
      upgraded = false
      length = 1
    }

    start = index
    dst.bitfield.set(index, true)
  }

  if (length > 0) signalReplicator(dst, upgraded, start, length)

  // unlink
  batch.tree = []
  batch.blocks = []
  batch.first = false
  batch.used = 0
}

function signalReplicator(core, upgraded, start, length) {
  if (upgraded) {
    core.replicator.cork()
    core.replicator.onhave(start, length, false)
    core.replicator.onupgrade()
    core.replicator.uncork()
  } else {
    core.replicator.onhave(start, length, false)
  }
}

function prologueToTree(prologue) {
  return {
    fork: 0,
    length: prologue.length,
    rootHash: prologue.hash,
    signature: null
  }
}

function getBitfieldPage(index) {
  return Math.floor(index / Bitfield.BITS_PER_PAGE)
}

function getBitfieldOffset(index) {
  return index & (Bitfield.BITS_PER_PAGE - 1)
}

function walkTree(stack, target, batch) {
  while (stack.length > 0) {
    const node = stack.pop()

    if ((node & 1) === 0) {
      if (node === target) return true
      continue
    }

    const ite = flat.iterator(node)
    if (!ite.contains(target)) continue

    while ((ite.index & 1) !== 0) {
      const left = ite.leftChild()
      const right = ite.sibling() // is right child

      batch.tree.push(left, right)

      if (ite.contains(target)) stack.push(left)
      else ite.sibling()
    }

    if (ite.index === target) return true
  }

  return false
}

function noop() {}
const crypto = require('hypercore-crypto')
const b4a = require('b4a')
const unslab = require('unslab')
const z32 = require('z32')
const Mutex = require('./mutex')
const { MerkleTree, ReorgBatch } = require('./merkle-tree')
const BitInterlude = require('./bit-interlude')
const Bitfield = require('./bitfield')
const RemoteBitfield = require('./remote-bitfield')
const {
  BAD_ARGUMENT,
  STORAGE_EMPTY,
  STORAGE_CONFLICT,
  INVALID_SIGNATURE,
  INVALID_CHECKSUM
} = require('hypercore-errors')
const Verifier = require('./verifier')
const audit = require('./audit')
const copyPrologue = require('./copy-prologue')
const SessionState = require('./session-state')
const Replicator = require('./replicator')

module.exports = class Core {
  constructor(db, opts = {}) {
    this.db = db
    this.storage = null
    this.replicator = new Replicator(this, opts)
    this.sessionStates = []
    this.monitors = []
    this.activeSessions = 0
    this.gc = 0 // corestore uses this to main a gc strike pool

    this.id = opts.key ? z32.encode(opts.key) : null
    this.key = opts.key || null
    this.discoveryKey = opts.discoveryKey || (opts.key && crypto.discoveryKey(opts.key)) || null
    this.manifest = null
    this.opening = null
    this.closing = null
    this.exclusive = null

    this.preupdate = null
    this.header = null
    this.compat = false
    this.bitfield = null
    this.verifier = null
    this.truncating = 0
    this.skipBitfield = null
    this.globalCache = opts.globalCache || null
    this.autoClose = opts.autoClose !== false
    this.onidle = noop
    this.ongroupupdate = noop

    this.state = null
    this.opened = false
    this.destroyed = false
    this.closed = false

    this.hintsChanged = false
    this.remoteContiguousLengthChanged = false

    this._bitfield = null
    this._verifies = null
    this._verifiesFlushed = null
    this._legacy = !!opts.legacy
    this._repairMode = false

    this.opening = this._open(opts)
    this.opening.catch(noop)
  }

  static setRecoveryPeers(peers) {
    SessionState.RECOVERY_PEERS = peers
  }

  ready() {
    return this.opening
  }

  addMonitor(s) {
    if (s._monitorIndex >= 0) return
    s._monitorIndex = this.monitors.push(s) - 1
  }

  removeMonitor(s) {
    if (s._monitorIndex < 0) return
    const head = this.monitors.pop()
    if (head !== s) this.monitors[(head._monitorIndex = s._monitorIndex)] = head
    s._monitorIndex = -1
  }

  emitRemoteContiguousLength() {
    if (!this.remoteContiguousLengthChanged) return
    this.remoteContiguousLengthChanged = false

    const length = this.header.hints.remoteContiguousLength

    for (let i = this.monitors.length - 1; i >= 0; i--) {
      this.monitors[i].emit('remote-contiguous-length', length)
    }
  }

  emitManifest() {
    for (let i = this.monitors.length - 1; i >= 0; i--) {
      this.monitors[i].emit('manifest')
    }
  }

  createUserDataStream(opts, session = this.state) {
    return session.storage.createUserDataStream(opts)
  }

  allSessions() {
    const sessions = []
    for (const state of this.sessionStates) {
      if (state.sessions.length) sessions.push(...state.sessions)
    }
    return sessions
  }

  hasSession() {
    return this.activeSessions !== 0
  }

  compact() {
    const compacting = []
    for (const s of this.sessionStates) {
      compacting.push(s.storage.compact())
    }
    return Promise.all(compacting)
  }

  checkIfIdle() {
    if (!this.opened || this.destroyed === true || this.hasSession() === true) return
    if (this.replicator.idle() === false) return
    if (this.state === null || this.state.mutex.idle() === false) return
    this.onidle()
  }

  async lockExclusive() {
    if (this.exclusive === null) this.exclusive = new Mutex()
    await this.exclusive.lock()
  }

  unlockExclusive() {
    if (this.exclusive !== null) this.exclusive.unlock()
  }

  async _open(opts) {
    try {
      await this._tryOpen(opts)
    } catch (err) {
      this.onidle()
      throw err
    }

    this.opened = true
  }

  async _tryOpen(opts) {
    if (opts.preopen) await opts.preopen // just a hook to allow exclusive access here...

    let storage = await this.db.resumeCore(this.discoveryKey)

    let overwrite = opts.overwrite === true

    const force = opts.force === true
    const createIfMissing = opts.createIfMissing !== false
    // kill this flag soon
    const legacy = !!opts.legacy

    // default to true for now if no manifest is provided
    let compat = opts.compat === true || (opts.compat !== false && !opts.manifest)

    let header = storage ? parseHeader(await getCoreInfo(storage)) : null

    const hadManifest = !!header && !!header.manifest && !!header.key
    const hadKeyPair = !!header && !!header.keyPair

    if (force && opts.key && header && !b4a.equals(header.key, opts.key)) {
      overwrite = true
    }

    if (!header && opts.discoveryKey && !(opts.key || opts.manifest)) {
      throw STORAGE_EMPTY('No Hypercore is stored here', this.discoveryKey)
    }

    if (!header || overwrite) {
      if (!createIfMissing) {
        throw STORAGE_EMPTY('No Hypercore is stored here', this.discoveryKey)
      }

      if (compat) {
        if (opts.key && opts.keyPair && !b4a.equals(opts.key, opts.keyPair.publicKey)) {
          throw BAD_ARGUMENT('Key must match publicKey when in compat mode', this.discoveryKey)
        }
      }

      const keyPair = opts.keyPair || (opts.key ? null : crypto.keyPair())

      const defaultManifest =
        !opts.manifest &&
        (!!opts.compat || !opts.key || !!(keyPair && b4a.equals(opts.key, keyPair.publicKey)))
      const manifest = defaultManifest
        ? Verifier.defaultSignerManifest(opts.key || keyPair.publicKey)
        : Verifier.createManifest(opts.manifest)

      header = {
        key: opts.key || (compat ? manifest.signers[0].publicKey : Verifier.manifestHash(manifest)),
        manifest,
        keyPair: keyPair
          ? { publicKey: keyPair.publicKey, secretKey: keyPair.secretKey || null }
          : null,
        frozen: false,
        tree: {
          fork: 0,
          length: 0,
          rootHash: null,
          signature: null,
          timestamp: 0
        },
        group: null,
        hints: {
          reorgs: [],
          contiguousLength: 0,
          remoteContiguousLength: 0,
          recovering: 0
        }
      }

      const discoveryKey = opts.discoveryKey || crypto.discoveryKey(header.key)

      storage = await this.db.createCore({
        key: header.key,
        manifest,
        keyPair,
        frozen: false,
        discoveryKey,
        userData: opts.userData || [],
        alias: opts.alias || null
      })
    }

    // unslab the long lived buffers to avoid keeping the slab alive
    header.key = unslab(header.key)

    if (header.tree) {
      header.tree.rootHash = unslab(header.tree.rootHash)
      header.tree.signature = unslab(header.tree.signature)
    }

    if (header.keyPair) {
      header.keyPair.publicKey = unslab(header.keyPair.publicKey)
      header.keyPair.secretKey = unslab(header.keyPair.secretKey)
    }

    if (header.keyPair) {
      header.keyPair.publicKey = unslab(header.keyPair.publicKey)
      header.keyPair.secretKey = unslab(header.keyPair.secretKey)
    }

    if (opts.manifest) {
      // if we provide a manifest and no key, verify that the stored key is the same
      if (
        !opts.key &&
        !Verifier.isValidManifest(header.key, Verifier.createManifest(opts.manifest))
      ) {
        throw STORAGE_CONFLICT('Manifest does not hash to provided key', this.discoveryKey)
      }

      if (!header.manifest) header.manifest = opts.manifest
    }

    if (opts.key && !b4a.equals(header.key, opts.key)) {
      throw STORAGE_CONFLICT('Another Hypercore is stored here', this.discoveryKey)
    }

    // if we signalled compat, but already now this core isn't disable it
    if (compat && header.manifest && !Verifier.isCompat(header.key, header.manifest)) {
      compat = false
    } else if (!compat && header.manifest && Verifier.isCompat(header.key, header.manifest)) {
      compat = true
    }

    const prologue = header.manifest ? header.manifest.prologue : null

    const bitfield = await Bitfield.open(storage, header.tree.length)

    const treeInfo = {
      fork: header.tree.fork,
      length: header.tree.length,
      signature: header.tree.signature,
      roots: await maybeGetRootsFromStorage(storage, header.tree.length),
      prologue
    }

    this._repairMode = !treeInfo.roots.length && treeInfo.length && !overwrite
    // Set push only mode if in repair mode
    if (this._repairMode) {
      this.replicator.setPushOnly(true)
    }

    if (opts.group) {
      if (!header.group) header.group = await this.db.createGroup(opts.group)
      else if (!b4a.equals(header.group.key, opts.group)) {
        throw STORAGE_CONFLICT(
          'Core is already register to group: ' + b4a.toString(header.group.key, 'hex')
        )
      }

      const tx = storage.write()
      tx.setGroup(header.group)
      await tx.flush()
    }

    if (overwrite) {
      const tx = storage.write()
      tx.deleteTreeNodeRange(0, -1)
      tx.deleteBlockRange(0, -1)
      bitfield.clear(tx)
      await tx.flush()
    }

    const len = bitfield.findFirst(false, header.hints.contiguousLength)
    if (header.hints.contiguousLength !== len && !storage.readOnly) {
      header.hints.contiguousLength = len
      const tx = storage.write()
      tx.setHints(header.hints)
      await tx.flush()
    }

    // to unslab
    if (header.manifest) {
      header.manifest = Verifier.createManifest(header.manifest)
      if (!hadManifest || (header.keyPair && !hadKeyPair)) {
        const tx = storage.write()
        tx.setAuth({
          key: header.key,
          discoveryKey: crypto.discoveryKey(header.key),
          manifest: header.manifest,
          keyPair: header.keyPair
        })
        await tx.flush()
      }
    }

    const verifier = header.manifest
      ? new Verifier(header.key, header.manifest, { crypto, legacy })
      : null

    this.storage = storage
    this.header = header
    this.compat = compat
    this.bitfield = bitfield
    this.verifier = verifier
    this.state = new SessionState(this, null, storage, treeInfo, null)

    if (this.key === null) this.key = this.header.key
    if (this.discoveryKey === null) this.discoveryKey = crypto.discoveryKey(this.key)
    if (this.id === null) this.id = z32.encode(this.key)
    if (this.manifest === null) this.manifest = this.header.manifest
  }

  async audit(opts) {
    await this.state.mutex.lock()

    try {
      return await audit(this, opts)
    } finally {
      this.state._unlock()
    }
  }

  async setGroup(group) {
    await this.state.mutex.lock()
    try {
      if (!this.header.group) this.header.group = await this.db.createGroup(group)
      else if (!b4a.equals(this.header.group.key, group)) {
        throw STORAGE_CONFLICT(
          'Core is already register to group: ' + b4a.toString(this.header.group.key, 'hex')
        )
      }

      const tx = this.storage.write()
      tx.setGroup(this.header.group)
      await tx.flush()
    } finally {
      this.state.mutex.unlock()
    }
  }

  async setManifest(manifest) {
    await this.state.mutex.lock()

    try {
      if (manifest && this.header.manifest === null) {
        if (!Verifier.isValidManifest(this.header.key, manifest)) {
          throw INVALID_CHECKSUM('Manifest hash does not match', this.discoveryKey)
        }

        const tx = this.state.createWriteBatch()
        this._setManifest(tx, Verifier.createManifest(manifest), null)
        await this.state.flush()
      }
    } finally {
      this.state._unlock()
    }
  }

  _setManifest(tx, manifest, keyPair) {
    if (!manifest && b4a.equals(keyPair.publicKey, this.header.key)) {
      manifest = Verifier.defaultSignerManifest(this.header.key)
    }
    if (!manifest) return

    const verifier = new Verifier(this.header.key, manifest, { legacy: this._legacy })

    if (verifier.prologue) this.state.prologue = Object.assign({}, verifier.prologue)

    this.manifest = this.header.manifest = manifest

    tx.setAuth({
      key: this.header.key,
      discoveryKey: this.discoveryKey,
      manifest,
      keyPair: this.header.keyPair
      // TODO: encryptionKey?
    })

    this.compat = verifier.compat
    this.verifier = verifier

    this.replicator.onupgrade()
    this.emitManifest()
  }

  async copyPrologue(src) {
    await this.state.mutex.lock()

    try {
      await src.mutex.lock()
    } catch (err) {
      this.state.mutex.unlock()
      throw err
    }

    try {
      await copyPrologue(src, this)
    } finally {
      src.mutex.unlock()
      this.state.mutex.unlock()
      this.checkIfIdle()
    }
  }

  flushed() {
    return this.state.flushed()
  }

  async _validateCommit(state, treeLength) {
    if (this.state.length > state.length) {
      return false // TODO: partial commit and truncation possible in the future
    }

    if (this.state.length > treeLength) {
      for (const root of this.state.roots) {
        const batchRoot = await MerkleTree.get(state, root.index)
        if (batchRoot.size !== root.size || !b4a.equals(batchRoot.hash, root.hash)) {
          return false
        }
      }
    }

    if (this.verifier === null) {
      return false // easier to assert than upsert
    }

    return true
  }

  _verifyBatchUpgrade(batch, manifest) {
    if (!this.header.manifest) {
      // compat, drop at some point
      if (!manifest) manifest = Verifier.defaultSignerManifest(this.header.key)

      if (
        !manifest ||
        !(
          Verifier.isValidManifest(this.header.key, manifest) ||
          Verifier.isCompat(this.header.key, manifest)
        )
      ) {
        throw INVALID_SIGNATURE('Proof contains an invalid manifest', this.discoveryKey) // TODO: proper error type
      }
    }

    const verifier =
      this.verifier ||
      new Verifier(this.header.key, Verifier.createManifest(manifest), { legacy: this._legacy })

    if (!verifier.verify(batch, batch.signature)) {
      throw INVALID_SIGNATURE('Proof contains an invalid signature', this.discoveryKey)
    }

    return manifest
  }

  async _verifyExclusive({ batch, bitfield, value, manifest }) {
    manifest = this._verifyBatchUpgrade(batch, manifest)

    if (
      !(await this.state._verifyBlock(
        batch,
        bitfield,
        value,
        this.header.manifest ? null : manifest
      ))
    ) {
      return false
    }

    if (!batch.upgraded && bitfield) {
      this.replicator.onhave(bitfield.start, bitfield.length, bitfield.drop)
    }

    return true
  }

  async _verifyShared() {
    if (!this._verifies.length) return false

    await this.state.mutex.lock()

    const tx = this.state.createWriteBatch()

    const verifies = this._verifies
    this._verifies = null
    this._verified = null

    try {
      for (const { batch, bitfield, value } of verifies) {
        if (!batch.commitable()) continue

        if (bitfield) {
          tx.putBlock(bitfield.start, value)
        }
      }

      const bits = new BitInterlude()

      for (let i = 0; i < verifies.length; i++) {
        const { batch, bitfield, manifest } = verifies[i]

        if (!batch.commitable()) {
          verifies[i] = null // signal that we cannot commit this one
          continue
        }

        if (bitfield) {
          bits.setRange(bitfield.start, bitfield.start + 1, true)
        }

        // if we got a manifest AND its strictly a non compat one, lets store it
        if (manifest && this.header.manifest === null) {
          if (!Verifier.isValidManifest(this.header.key, manifest)) {
            throw INVALID_CHECKSUM('Manifest hash does not match', this.discoveryKey)
          }
          this._setManifest(tx, manifest, null)
        }

        if (batch.commitable()) batch.commit(tx)
      }

      const ranges = bits.flush(tx, this.bitfield)

      await this.state.flush()

      for (const { start, end, value } of ranges) {
        this._setBitfieldRanges(start, end, value)
      }

      for (let i = 0; i < verifies.length; i++) {
        const bitfield = verifies[i] && verifies[i].bitfield
        if (bitfield) {
          this.updateContiguousLength(bitfield)
          this.replicator.onhave(bitfield.start, bitfield.length, bitfield.drop)
        }
      }

      if (this.hintsChanged) await this.flushHints()
    } finally {
      this.state._clearActiveBatch()
      this.state.mutex.unlock()
    }

    return verifies[0] !== null
  }

  async flushHints() {
    if (!this.hintsChanged) return
    this.hintsChanged = false // we unset this immediately as a "debounce"

    const tx = this.state.storage.write()

    tx.setHints({
      contiguousLength: this.header.hints.contiguousLength,
      remoteContiguousLength: this.header.hints.remoteContiguousLength,
      recovering: this.header.hints.recovering
    })

    await tx.flush()
  }

  async checkConflict(proof, from) {
    if (this.state.length < proof.upgrade.length || proof.fork !== this.state.fork) {
      // out of date this proof - ignore for now
      return false
    }

    // sanity check -> no manifest, no way to verify
    if (!this.header.manifest) {
      return false
    }

    const batch = MerkleTree.verifyFullyRemote(this.state, proof)

    try {
      this._verifyBatchUpgrade(batch, proof.manifest)
    } catch {
      return true
    }

    const roots = await maybeGetRootsFromStorage(this.storage, proof.upgrade.length)
    const remoteTreeHash = crypto.tree(proof.upgrade.nodes)
    const localTreeHash = crypto.tree(roots)

    try {
      const rx = this.state.storage.read()
      const treeProofPromise = MerkleTree.proof(this.state, rx, {
        block: null,
        hash: null,
        seek: null,
        upgrade: {
          start: 0,
          length: proof.upgrade.length
        }
      })

      rx.tryFlush()

      const treeProof = await treeProofPromise

      const verifyBatch = MerkleTree.verifyFullyRemote(this.state, await treeProof.settle())
      this._verifyBatchUpgrade(verifyBatch, this.header.manifest)
    } catch (err) {
      if (err.code !== 'INVALID_OPERATION') return true

      return !(await this._repairTreeNodes(proof))
    }

    // both proofs are valid, now check if they forked
    if (b4a.equals(localTreeHash, remoteTreeHash)) return false

    await this.state.mutex.lock()

    try {
      const tx = this.state.createWriteBatch()

      this.header.frozen = true

      tx.setAuth({
        key: this.header.key,
        discoveryKey: this.discoveryKey,
        manifest: this.header.manifest,
        keyPair: this.header.keyPair,
        frozen: true
      })

      await this.state.flush()
    } finally {
      this.state.mutex.unlock()
    }

    // tmp log so we can see these
    const id = b4a.toString(this.discoveryKey, 'hex')
    console.log(
      '[hypercore] conflict detected in ' +
        id +
        ' (writable=' +
        !!this.header.keyPair +
        ',quorum=' +
        this.header.manifest.quorum +
        ')'
    )
    await this._onconflict(proof)
    return true
  }

  async _repairTreeNodes(proof) {
    if (!this._repairMode) return false

    await this.state.mutex.lock()

    for (let i = this.monitors.length - 1; i >= 0; i--) {
      this.monitors[i].emit('repairing', proof)
    }

    try {
      const batch = MerkleTree.verifyFullyRemote(this.state, proof)
      this._verifyBatchUpgrade(batch, proof.manifest)
    } catch {
      this.state.mutex.unlock()
      for (let i = this.monitors.length - 1; i >= 0; i--) {
        this.monitors[i].emit('repair-failed')
      }
      return false
    }

    // Attempt to repair local merkle tree with remote roots
    const atom = this.storage.createAtom()
    const atomized = this.storage.atomize(atom)
    const tx = atomized.write()
    for (const node of proof.upgrade.nodes) {
      tx.putTreeNode(node)
    }
    await tx.flush()

    // Try local proof again
    try {
      const rx = atomized.read()
      const treeProofPromise = MerkleTree.proof(this.state, rx, {
        block: null,
        hash: null,
        seek: null,
        upgrade: {
          start: 0,
          length: proof.upgrade.length
        }
      })

      rx.tryFlush()

      const treeProof = await treeProofPromise

      const verifyBatch = MerkleTree.verifyFullyRemote(this.state, await treeProof.settle())
      this._verifyBatchUpgrade(verifyBatch, this.header.manifest)
    } catch (err) {
      this.state.mutex.unlock()
      for (let i = this.monitors.length - 1; i >= 0; i--) {
        this.monitors[i].emit('repair-failed')
      }
      return false
    }

    await atom.flush()

    for (let i = this.monitors.length - 1; i >= 0; i--) {
      this.monitors[i].emit('repaired', proof)
    }
    this.replicator.setPushOnly(false)
    this.state.mutex.unlock()
    return true
  }

  async verifyReorg(proof) {
    const batch = new ReorgBatch(this.state)
    await MerkleTree.reorg(this.state, proof, batch)
    const manifest = this._verifyBatchUpgrade(batch, proof.manifest)

    if (manifest && !this.header.manifest) {
      await this.state.mutex.lock()
      try {
        if (manifest && this.header.manifest === null) {
          const tx = this.state.createWriteBatch()
          this._setManifest(tx, Verifier.createManifest(manifest), null)
          await this.state.flush()
        }
      } finally {
        this.state._unlock()
      }
    }

    return batch
  }

  async verify(proof, from) {
    // We cannot apply "other forks" atm.
    // We should probably still try and they are likely super similar for non upgrades
    // but this is easy atm (and the above layer will just retry)
    if (proof.fork !== this.state.fork) return false

    const batch = await MerkleTree.verify(this.state, proof)

    if (batch.upgraded && batch.length <= this.state.length) {
      await batch.downgrade()
    }

    if (!batch.commitable()) {
      return false
    }

    const value = (proof.block && proof.block.value) || null
    const op = {
      batch,
      bitfield: value && { drop: false, start: proof.block.index, length: 1 },
      value,
      manifest: proof.manifest,
      from
    }

    if (batch.upgraded) {
      return this._verifyExclusive(op)
    }

    if (this._verifies !== null) {
      const verifies = this._verifies
      const i = verifies.push(op)
      await this._verified
      return verifies[i] !== null
    }

    this._verifies = [op]
    this._verified = this._verifyShared()

    return this._verified
  }

  async reorg(batch) {
    if (!batch.commitable()) return false

    this.truncating++

    try {
      await this.state.reorg(batch)
    } finally {
      this.truncating--
    }

    return true
  }

  openSkipBitfield() {
    if (this.skipBitfield !== null) return this.skipBitfield
    this.skipBitfield = new RemoteBitfield()
    const buf = this.bitfield.toBuffer(this.state.length)
    const bitfield = new Uint32Array(buf.buffer, buf.byteOffset, buf.byteLength / 4)
    this.skipBitfield.insert(0, bitfield)
    return this.skipBitfield
  }

  _setBitfieldRanges(start, end, value) {
    this.bitfield.setRange(start, end, value)
    if (this.skipBitfield !== null) this.skipBitfield.setRange(start, end, value)
  }

  close() {
    if (!this.closing) this.closing = this._close()
    return this.closing
  }

  updateContiguousLength(bitfield) {
    const contig = updateContigBatch(this.header.hints.contiguousLength, bitfield, this.bitfield)

    if (contig.length !== -1 && contig.length !== this.header.hints.contiguousLength) {
      this.header.hints.contiguousLength = contig.length
      this.hintsChanged = true
    }
  }

  updateRemoteContiguousLength(length) {
    this.header.hints.remoteContiguousLength = length
    this.hintsChanged = true
    this.remoteContiguousLengthChanged = true
  }

  onappend(tree, bitfield) {
    this.header.tree = tree

    if (!bitfield) {
      this.replicator.onupgrade()
      return
    }

    this.replicator.cork()

    const { start, length, drop } = bitfield

    this._setBitfieldRanges(start, start + length, true)
    this.updateContiguousLength({ start, length, drop: false })

    this.replicator.onupgrade()
    this.replicator.onhave(start, length, drop)
    this.replicator.uncork()
  }

  ontruncate(tree, { start, length }) {
    if (tree) this.header.tree = tree

    this.replicator.cork()

    this.replicator.ontruncate(start, length)
    this.replicator.onhave(start, length, true)
    this.replicator.onupgrade()
    this.replicator.uncork()

    for (const sessionState of this.sessionStates) {
      if (start < sessionState.snapshotCompatLength) sessionState.snapshotCompatLength = start
    }

    this._setBitfieldRanges(start, start + length, false)
    this.updateContiguousLength({ start, length, drop: true })
  }

  async _onconflict(proof) {
    await this.replicator.onconflict()

    for (let i = this.monitors.length - 1; i >= 0; i--) {
      const s = this.monitors[i]
      s.emit('conflict', proof.upgrade.length, proof.fork, proof)
    }

    const err = new Error('Two conflicting signatures exist for length ' + proof.upgrade.length)
    await this.closeAllSessions(err)
  }

  async closeAllSessions(err) {
    // this.sessions modifies itself when a session closes
    // This way we ensure we indeed iterate over all sessions
    const sessions = this.allSessions()

    const all = []
    for (const s of sessions) all.push(s.close({ error: err, force: false })) // force false or else infinite recursion
    await Promise.allSettled(all)
  }

  async destroy() {
    if (this.destroyed === true) return
    this.destroyed = true

    if (this.hasSession() === true) throw new Error('Cannot destroy while sessions are open')

    const weakSessions = this.allSessions()

    if (this.replicator) this.replicator.destroy()
    if (this.state) await this.state.close()

    // close all pending weak sessions...
    for (const s of weakSessions) s.close().catch(noop)
  }

  async _close() {
    if (this.opened === false) await this.opening
    if (this.hasSession() === true) throw new Error('Cannot close while sessions are open')

    if (this.replicator) await this.replicator.close()

    await this.destroy()
    if (this.autoClose) await this.storage.store.close()

    this.closed = true
  }
}

function updateContigBatch(start, upd, bitfield) {
  const end = upd.start + upd.length

  let c = start

  if (upd.drop) {
    // If we dropped a block in the current contig range, "downgrade" it
    if (c > upd.start) {
      c = upd.start
    }
  } else {
    if (c <= end && c >= upd.start) {
      c = end
      while (bitfield.get(c)) c++
    }
  }

  if (c === start) {
    return {
      length: -1
    }
  }

  if (c > start) {
    return {
      length: c
    }
  }

  return {
    length: c
  }
}

function getDefaultTree() {
  return {
    fork: 0,
    length: 0,
    rootHash: null,
    signature: null,
    timestamp: 0
  }
}

function parseHeader(info) {
  if (!info) return null

  return {
    key: info.key,
    manifest: info.manifest,
    external: null,
    keyPair: info.keyPair,
    tree: info.head || getDefaultTree(),
    group: info.group,
    hints: {
      reorgs: [],
      contiguousLength: info.hints ? info.hints.contiguousLength : 0,
      remoteContiguousLength: info.hints ? info.hints.remoteContiguousLength : 0,
      recovering: info.hints ? info.hints.recovering : 0
    }
  }
}

async function maybeGetRootsFromStorage(storage, length) {
  try {
    return length ? await MerkleTree.getRootsFromStorage(storage, length) : []
  } catch (err) {
    if (err.code !== 'INVALID_OPERATION') throw err
    // If INVALID_OPERATION, a root is likely missing so load empty roots to try to recover
    return []
  }
}

function noop() {}

async function getCoreInfo(storage) {
  const r = storage.read()

  const auth = r.getAuth()
  const head = r.getHead()
  const hints = r.getHints()
  const group = r.getGroup()

  r.tryFlush()

  const [authInfo, headInfo, hintsInfo, groupInfo] = await Promise.all([auth, head, hints, group])
  return {
    ...authInfo,
    head: headInfo,
    hints: hintsInfo,
    group: groupInfo
  }
}
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const b4a = require('b4a')
const { DEFAULT_ENCRYPTION } = require('./caps')

const nonce = b4a.alloc(sodium.crypto_stream_NONCEBYTES)

module.exports = class DefaultEncryption {
  static PADDING = 8

  constructor(encryptionKey, hypercoreKey, opts = {}) {
    this.key = encryptionKey
    this.compat = opts.compat === true

    const keys = DefaultEncryption.deriveKeys(encryptionKey, hypercoreKey, opts)

    this.blockKey = keys.block
    this.blindingKey = keys.blinding
  }

  static deriveKeys(encryptionKey, hypercoreKey, { block = false, compat = false } = {}) {
    const subKeys = b4a.alloc(2 * sodium.crypto_stream_KEYBYTES)

    const blockKey = block ? encryptionKey : subKeys.subarray(0, sodium.crypto_stream_KEYBYTES)
    const blindingKey = subKeys.subarray(sodium.crypto_stream_KEYBYTES)

    if (!block) {
      if (compat) {
        sodium.crypto_generichash_batch(blockKey, [encryptionKey], hypercoreKey)
      } else {
        sodium.crypto_generichash_batch(blockKey, [DEFAULT_ENCRYPTION, hypercoreKey, encryptionKey])
      }
    }

    sodium.crypto_generichash(blindingKey, blockKey)

    return {
      blinding: blindingKey,
      block: blockKey
    }
  }

  static blockEncryptionKey(hypercoreKey, encryptionKey) {
    const blockKey = b4a.alloc(sodium.crypto_stream_KEYBYTES)
    sodium.crypto_generichash_batch(blockKey, [DEFAULT_ENCRYPTION, hypercoreKey, encryptionKey])
    return blockKey
  }

  static encrypt(index, block, fork, blockKey, blindingKey) {
    const padding = block.subarray(0, DefaultEncryption.PADDING)
    block = block.subarray(DefaultEncryption.PADDING)

    c.uint64.encode({ start: 0, end: 8, buffer: padding }, fork)
    c.uint64.encode({ start: 0, end: 8, buffer: nonce }, index)

    // Zero out any previous padding.
    nonce.fill(0, 8, 8 + padding.byteLength)

    // Blind the fork ID, possibly risking reusing the nonce on a reorg of the
    // Hypercore. This is fine as the blinding is best-effort and the latest
    // fork ID shared on replication anyway.
    sodium.crypto_stream_xor(padding, padding, nonce, blindingKey)

    nonce.set(padding, 8)

    // The combination of a (blinded) fork ID and a block index is unique for a
    // given Hypercore and is therefore a valid nonce for encrypting the block.
    sodium.crypto_stream_xor(block, block, nonce, blockKey)
  }

  static decrypt(index, block, blockKey) {
    const padding = block.subarray(0, DefaultEncryption.PADDING)
    block = block.subarray(DefaultEncryption.PADDING)

    c.uint64.encode({ start: 0, end: 8, buffer: nonce }, index)

    nonce.set(padding, 8)

    // Decrypt the block using the blinded fork ID.
    sodium.crypto_stream_xor(block, block, nonce, blockKey)
  }

  encrypt(index, block, fork, core) {
    if (core.compat !== this.compat) this._reload(core)
    return DefaultEncryption.encrypt(index, block, fork, this.blockKey, this.blindingKey)
  }

  decrypt(index, block, core) {
    if (core.compat !== this.compat) this._reload(core)
    return DefaultEncryption.decrypt(index, block, this.blockKey)
  }

  padding() {
    return DefaultEncryption.PADDING
  }

  _reload(core) {
    const block = b4a.equals(this.key, this.blockKey)
    const keys = DefaultEncryption.deriveKeys(this.key, core.key, { block, compat: core.compat })

    this.blockKey = keys.blockKey
    this.blindingKey = keys.blindingKey
  }
}
module.exports = class Download {
  constructor(session, range) {
    this.session = session
    this.range = range
    this.request = null
    this.opened = false
    this.opening = this._open()
    this.opening.catch(noop)
  }

  ready() {
    return this.opening
  }

  async _open() {
    if (this.session.opened === false) await this.session.opening
    this._download()
    this.opened = true
  }

  async done() {
    await this.ready()

    try {
      return await this.request.promise
    } catch (err) {
      if (isSessionMoved(err)) return this._download()
      throw err
    }
  }

  _download() {
    const activeRequests = (this.range && this.range.activeRequests) || this.session.activeRequests
    this.request = this.session.core.replicator.addRange(activeRequests, this.range)
    this.request.promise.catch(noop)
    return this.request.promise
  }

  /**
   * Deprecated. Use `range.done()`.
   */
  downloaded() {
    return this.done()
  }

  destroy() {
    this._destroyBackground().catch(noop)
  }

  async _destroyBackground() {
    if (this.opened === false) await this.ready()
    if (this.request.context) this.request.context.detach(this.request)
  }
}

function noop() {}

function isSessionMoved(err) {
  return err.code === 'SESSION_MOVED'
}
module.exports = {
  SMALL_WANTS: 1
}
// this helper is for fully remote proofs, is like in a push notification where no other context exists

const { MerkleTree } = require('./merkle-tree.js')
const messages = require('./messages.js')
const b4a = require('b4a')
const c = require('compact-encoding')
const crypto = require('hypercore-crypto')
const flat = require('flat-tree')

class SlimSession {
  constructor(storage, auth, head, roots) {
    this.fork = head ? head.fork : 0
    this.roots = roots
    this.length = head ? head.length : 0
    this.signature = head ? head.signature : null
    this.ancestors = this.length
    this.byteLength = 0
    this.prologue = auth.manifest.prologue
    this.storage = storage

    for (let i = 0; i < roots.length; i++) this.byteLength += roots[i].size
  }
}

module.exports = { verify, proof }

async function verify(storage, buffer, { referrer = null } = {}) {
  const state = { buffer, start: 0, end: buffer.byteLength }

  const discoveryKey = c.fixed32.decode(state)
  const proof = messages.wire.data.decode(state)

  const result = {
    key: null,
    discoveryKey,
    newer: true,
    length: 0,
    proof,
    block: null
  }

  const core = await storage.resumeCore(discoveryKey)
  if (core === null) return null

  let rx = core.read()
  const authPromise = rx.getAuth()
  const headPromise = rx.getHead()
  const referrerPromise = rx.getUserData('referrer')

  rx.tryFlush()

  const [auth, head, ref] = await Promise.all([authPromise, headPromise, referrerPromise])

  if (auth === null) return null

  if (referrer && (!ref || !b4a.equals(ref, referrer))) return null

  rx = core.read()

  const rootPromises = []

  for (const index of flat.fullRoots(head ? 2 * head.length : 0)) {
    rootPromises.push(rx.getTreeNode(index))
  }

  rx.tryFlush()

  let roots = await Promise.all(rootPromises)
  if (roots.some(isNull)) roots = []

  const length = head ? head.length : 0

  if (!auth.manifest || !auth.manifest.signers.length) return null

  const batch = await MerkleTree.verifyFullyRemote(new SlimSession(core, auth, head, roots), proof)
  const publicKey = auth.manifest.signers[0].publicKey

  let signable = null
  let signature = null

  if (auth.manifest.version === 0) {
    signable = batch.signable(auth.manifest.signers[0].namespace)
    signature = batch.signature
  } else {
    if (batch.signature[0] !== 1) return null
    if (batch.signature[1] !== 0) return null

    signable = batch.signable(auth.key)
    signature = batch.signature.subarray(2, 66)
  }

  if (!crypto.verify(signable, signature, publicKey)) {
    return null
  }

  result.key = auth.key
  result.discoveryKey = discoveryKey
  result.newer = batch.length > length
  result.length = batch.length
  result.block = proof.block

  return result
}

async function proof(sender, { index, block = null, upgrade = null } = {}) {
  const proof = await sender.proof({
    block: block ? { index, nodes: 0 } : null,
    upgrade: upgrade ? upgrade : { start: 0, length: sender.length }
  })

  if (block) proof.block.value = block
  proof.manifest = sender.core.header.manifest

  const state = { buffer: null, start: 0, end: 0 }
  const data = { request: 0, ...proof }

  c.fixed32.preencode(state, sender.discoveryKey)
  messages.wire.data.preencode(state, data)

  state.buffer = b4a.allocUnsafe(state.end)

  c.fixed32.encode(state, sender.discoveryKey)
  messages.wire.data.encode(state, data)

  return state.buffer
}

function isNull(x) {
  return x === null
}
const TICKS = 16

module.exports = class HotswapQueue {
  constructor() {
    this.priorities = [[], [], []]
  }

  *pick(peer) {
    for (let i = 0; i < this.priorities.length; i++) {
      // try first one more than second one etc etc
      let ticks = (this.priorities.length - i) * TICKS
      const queue = this.priorities[i]

      for (let j = 0; j < queue.length; j++) {
        const r = j + Math.floor(Math.random() * queue.length - j)
        const a = queue[j]
        const b = queue[r]

        if (r !== j) {
          queue[(b.hotswap.index = j)] = b
          queue[(a.hotswap.index = r)] = a
        }

        if (hasInflight(b, peer)) continue

        yield b

        if (--ticks <= 0) break
      }
    }
  }

  add(block) {
    if (block.hotswap !== null) this.remove(block)
    if (block.inflight.length === 0 || block.inflight.length >= 3) return

    // TODO: also use other stuff to determine queue prio
    const queue = this.priorities[block.inflight.length - 1]

    const index = queue.push(block) - 1
    block.hotswap = { ref: this, queue, index }
  }

  remove(block) {
    const hotswap = block.hotswap
    if (hotswap === null) return

    block.hotswap = null
    const head = hotswap.queue.pop()
    if (head === block) return
    hotswap.queue[(head.hotswap.index = hotswap.index)] = head
  }
}

function hasInflight(block, peer) {
  for (let j = 0; j < block.inflight.length; j++) {
    if (block.inflight[j].peer === peer) return true
  }
  return false
}
module.exports = class Info {
  constructor(opts = {}) {
    this.key = opts.key
    this.discoveryKey = opts.discoveryKey
    this.length = opts.length || 0
    this.contiguousLength = opts.contiguousLength || 0
    this.byteLength = opts.byteLength || 0
    this.fork = opts.fork || 0
    this.padding = opts.padding || 0
    this.storage = opts.storage || null
  }

  static async from(session, opts = {}) {
    return new Info({
      key: session.key,
      discoveryKey: session.discoveryKey,
      length: session.length,
      contiguousLength: session.contiguousLength,
      byteLength: session.byteLength,
      fork: session.fork,
      padding: session.padding,
      storage: opts.storage ? await this.storage(session) : null
    })
  }

  static async storage(session) {
    const { oplog, tree, blocks, bitfield } = session.core
    try {
      return {
        oplog: await Info.bytesUsed(oplog.storage),
        tree: await Info.bytesUsed(tree.storage),
        blocks: await Info.bytesUsed(blocks.storage),
        bitfield: await Info.bytesUsed(bitfield.storage)
      }
    } catch {
      return null
    }
  }

  static bytesUsed(file) {
    return new Promise((resolve, reject) => {
      file.stat((err, st) => {
        if (err) {
          resolve(0) // prob just file not found (TODO, improve)
        } else if (typeof st.blocks !== 'number') {
          reject(new Error('cannot determine bytes used'))
        } else {
          resolve(st.blocks * 512)
        }
      })
    })
  }
}
const b4a = require('b4a')

module.exports = function (core, depth, opts) {
  let indent = ''
  if (typeof opts.indentationLvl === 'number') {
    while (indent.length < opts.indentationLvl) indent += ' '
  }

  let peers = ''
  const min = Math.min(core.peers.length, 5)

  for (let i = 0; i < min; i++) {
    const peer = core.peers[i]

    peers += `${indent}    Peer(\n`
    peers += `${indent}      remotePublicKey: ${opts.stylize(toHex(peer.remotePublicKey), 'string')}\n`
    peers += `${indent}      remoteLength: ${opts.stylize(peer.remoteLength, 'number')}\n`
    peers += `${indent}      remoteFork: ${opts.stylize(peer.remoteFork, 'number')}\n`
    peers += `${indent}      remoteCanUpgrade: ${opts.stylize(peer.remoteCanUpgrade, 'boolean')}\n`
    peers += `${indent}    )\n`
  }

  if (core.peers.length > 5) {
    peers += `${indent}  ... and ${core.peers.length - 5} more\n`
  }

  if (peers) peers = `[\n${peers}${indent}  ]`
  else peers = `[ ${opts.stylize(0, 'number')} ]`

  return (
    `${core.constructor.name}(\n` +
    `${indent}  id: ${opts.stylize(core.id, 'string')}\n` +
    `${indent}  key: ${opts.stylize(toHex(core.key), 'string')}\n` +
    `${indent}  discoveryKey: ${opts.stylize(toHex(core.discoveryKey), 'string')}\n` +
    `${indent}  opened: ${opts.stylize(core.opened, 'boolean')}\n` +
    `${indent}  closed: ${opts.stylize(core.closed, 'boolean')}\n` +
    `${indent}  snapshotted: ${opts.stylize(core.snapshotted, 'boolean')}\n` +
    `${indent}  writable: ${opts.stylize(core.writable, 'boolean')}\n` +
    `${indent}  length: ${opts.stylize(core.length, 'number')}\n` +
    `${indent}  fork: ${opts.stylize(core.fork, 'number')}\n` +
    `${indent}  sessions: [ ${opts.stylize(core.sessions.length, 'number')} ]\n` +
    `${indent}  activeRequests: [ ${opts.stylize(core.activeRequests.length, 'number')} ]\n` +
    `${indent}  peers: ${peers}\n` +
    `${indent})`
  )
}

function toHex(buf) {
  return buf && b4a.toString(buf, 'hex')
}
const BigSparseArray = require('big-sparse-array')
const { Transform } = require('streamx')
const quickbit = require('./compat').quickbit
const b4a = require('b4a')

const BITS_PER_PAGE = 32768
const BYTES_PER_PAGE = BITS_PER_PAGE / 8

class MarkPage {
  constructor() {
    this.bitfield = null
    this.loaded = new Promise((resolve) => {
      this.load = resolve
    })
  }

  setBitfield(bitfield) {
    this.bitfield = bitfield
    this.load()
  }

  get(index) {
    return quickbit.get(this.bitfield, index)
  }

  set(index, val) {
    quickbit.set(this.bitfield, index, val)
  }
}

module.exports = class MarkBitfield {
  static BITS_PER_PAGE = BITS_PER_PAGE
  static BYTES_PER_PAGE = BYTES_PER_PAGE

  constructor(storage) {
    this.storage = storage
    this._pages = new BigSparseArray()
  }

  async loadPage(pageIndex) {
    const p = this._pages.set(pageIndex, new MarkPage())
    const rx = this.storage.read()
    const pageBuf = rx.getMark(pageIndex)
    rx.tryFlush()
    const bitfield = (await pageBuf) ?? b4a.alloc(BYTES_PER_PAGE)
    await p.setBitfield(bitfield)
    return p
  }

  async get(index) {
    const j = index & (BITS_PER_PAGE - 1)
    const i = (index - j) / BITS_PER_PAGE

    let p = this._pages.get(i)
    if (!p) p = await this.loadPage(i)

    return p.get(j)
  }

  async set(index, val) {
    const j = index & (BITS_PER_PAGE - 1)
    const i = (index - j) / BITS_PER_PAGE

    let p = this._pages.get(i)

    if (!p && val) p = await this.loadPage(i)

    if (p) {
      await p.loaded
      p.set(j, val)
      const tx = this.storage.write()
      tx.putMark(i, p.bitfield)
      await tx.flush()
    }
  }

  async clear() {
    const tx = this.storage.write()
    tx.deleteMarkRange(0, -1)
    await tx.flush()
    this._pages = new BigSparseArray()
  }

  createMarkStream({ reverse = false } = {}) {
    return this.storage.createMarkStream({ reverse }).pipe(
      new Transform({
        transform({ index, page }, cb) {
          let bitIndex = reverse
            ? quickbit.findLast(page, true, BITS_PER_PAGE)
            : quickbit.findFirst(page, true, 0)
          while (bitIndex !== -1) {
            const blockIndex = index * BITS_PER_PAGE + bitIndex
            this.push(blockIndex)

            // Account for `bitIndex` being either causing infinite loop
            if (bitIndex === 0 && reverse) break

            bitIndex = reverse
              ? quickbit.findLast(page, true, bitIndex - 1)
              : quickbit.findFirst(page, true, bitIndex + 1)
          }

          cb(null)
        }
      })
    )
  }
}
const flat = require('flat-tree')
const crypto = require('hypercore-crypto')
const b4a = require('b4a')
const unslab = require('unslab')
const caps = require('./caps')
const {
  INVALID_PROOF,
  INVALID_CHECKSUM,
  INVALID_OPERATION,
  BAD_ARGUMENT,
  ASSERTION
} = require('hypercore-errors')

class NodeQueue {
  constructor(nodes, extra = null) {
    this.i = 0
    this.nodes = nodes
    this.extra = extra
    this.length = nodes.length + (this.extra === null ? 0 : 1)
  }

  shift(index) {
    if (this.extra !== null && this.extra.index === index) {
      const node = this.extra
      this.extra = null
      this.length--
      return node
    }

    if (this.i >= this.nodes.length) {
      throw INVALID_OPERATION('Expected node ' + index + ', got (nil)')
    }

    const node = this.nodes[this.i++]
    if (node.index !== index) {
      throw INVALID_OPERATION('Expected node ' + index + ', got node ' + node.index)
    }

    this.length--
    return node
  }
}

class MerkleTreeBatch {
  constructor(session) {
    this.fork = session.fork
    this.roots = [...session.roots]
    this.length = session.length
    this.signature = session.signature
    this.ancestors = session.length
    this.byteLength = session.byteLength
    this.prologue = session.prologue
    this.hashCached = null

    this.committed = false
    this.truncated = false
    this.treeLength = session.length
    this.treeFork = session.fork
    this.storage = session.storage
    this.session = session
    this.nodes = []
    this.upgraded = false
  }

  checkout(length, additionalRoots) {
    const roots = []
    let r = 0

    const head = 2 * length - 2
    const gaps = new Set()
    const all = new Map()

    // additional roots is so the original roots can be passed (we mutate the array in appendRoot)
    if (additionalRoots) {
      for (const node of additionalRoots) all.set(node.index, node)
    }

    for (const node of this.nodes) all.set(node.index, node)

    for (const index of flat.fullRoots(head + 2)) {
      const left = flat.leftSpan(index)
      if (left !== 0) gaps.add(left - 1)

      if (r < this.roots.length && this.roots[r].index === index) {
        roots.push(this.roots[r++])
        continue
      }
      const node = all.get(index)
      if (!node) throw new BAD_ARGUMENT('root missing for given length')
      roots.push(node)
    }

    this.roots = roots
    this.length = length
    this.byteLength = totalSize(roots)
    this.hashCached = null
    this.signature = null

    for (let i = 0; i < this.nodes.length; i++) {
      const index = this.nodes[i].index
      if (index <= head && !gaps.has(index)) continue
      const last = this.nodes.pop()
      if (i < this.nodes.length) this.nodes[i--] = last
    }
  }

  prune(length) {
    if (length === 0) return

    const head = 2 * length - 2
    const gaps = new Set()

    // TODO: make a function for this in flat-tree
    for (const index of flat.fullRoots(head + 2)) {
      const left = flat.leftSpan(index)
      if (left !== 0) gaps.add(left - 1)
    }

    for (let i = 0; i < this.nodes.length; i++) {
      const index = this.nodes[i].index
      if (index > head || gaps.has(index)) continue
      const last = this.nodes.pop()
      if (i < this.nodes.length) this.nodes[i--] = last
    }
  }

  clone() {
    const b = new MerkleTreeBatch(this.session)

    b.fork = this.fork
    b.roots = [...this.roots]
    b.length = this.length
    b.byteLength = this.byteLength
    b.signature = this.signature
    b.treeLength = this.treeLength
    b.treeFork = this.treeFork
    b.tree = this.tree
    b.nodes = [...this.nodes]
    b.upgraded = this.upgraded

    return b
  }

  hash() {
    if (this.hashCached === null) this.hashCached = unslab(crypto.tree(this.roots))
    return this.hashCached
  }

  signable(manifestHash) {
    return caps.treeSignable(manifestHash, this.hash(), this.length, this.fork)
  }

  signableCompat(noHeader) {
    return caps.treeSignableCompat(this.hash(), this.length, this.fork, noHeader)
  }

  get(index) {
    if (index >= this.length * 2) {
      return null
    }

    for (const n of this.nodes) {
      if (n.index === index) return n
    }

    return getTreeNodeFromStorage(this.session.storage, index)
  }

  // deprecated, use sssion proof instead
  proof(batch, { block, hash, seek, upgrade }) {
    return generateProof(this.session, batch, block, hash, seek, upgrade)
  }

  verifyUpgrade(proof) {
    const unverified = verifyTree(proof, this.nodes)

    if (!proof.upgrade) throw INVALID_OPERATION('Expected upgrade proof')

    return verifyUpgrade(proof, unverified, this)
  }

  addNodesUnsafe(nodes) {
    for (let i = 0; i < nodes.length; i++) {
      this.nodes.push(nodes[i])
    }
  }

  append(buf) {
    const head = this.length * 2
    const ite = flat.iterator(head)
    const node = blockNode(head, buf)

    this.appendRoot(node, ite)
  }

  appendRoot(node, ite) {
    node = unslabNode(node)
    this.hashCached = null
    this.upgraded = true
    this.length += ite.factor / 2
    this.byteLength += node.size
    this.roots.push(node)
    this.nodes.push(node)

    while (this.roots.length > 1) {
      const a = this.roots[this.roots.length - 1]
      const b = this.roots[this.roots.length - 2]

      // TODO: just have a peek sibling instead? (pretty sure it's always the left sib as well)
      if (ite.sibling() !== b.index) {
        ite.sibling() // unset so it always points to last root
        break
      }

      const node = unslabNode(parentNode(ite.parent(), a, b))
      this.nodes.push(node)
      this.roots.pop()
      this.roots.pop()
      this.roots.push(node)
    }
  }

  commitable() {
    return (
      this.treeFork === this.session.fork &&
      (this.upgraded
        ? this.treeLength === this.session.length
        : this.treeLength <= this.session.length)
    )
  }

  commit(tx) {
    if (tx === undefined) throw INVALID_OPERATION('No database batch was passed')

    if (this.session.core._repairMode) {
      throw ASSERTION('Cannot commit while repair mode is on')
    }

    if (!this.commitable()) {
      throw INVALID_OPERATION('Tree was modified during batch, refusing to commit')
    }

    if (this.upgraded) this._commitUpgrade(tx)

    for (let i = 0; i < this.nodes.length; i++) {
      const node = this.nodes[i]
      tx.putTreeNode(node)
    }

    this.committed = true

    return this
  }

  _commitUpgrade(tx) {
    // TODO: If easy to detect, we should refuse an trunc+append here without a fork id
    // change. Will only happen on user error so mostly to prevent that.

    if (this.ancestors < this.treeLength) {
      tx.deleteTreeNodeRange(this.ancestors * 2, this.treeLength * 2)

      if (this.ancestors > 0) {
        const head = this.ancestors * 2
        const ite = flat.iterator(head - 2)

        while (true) {
          if (ite.contains(head) && ite.index < head) {
            tx.deleteTreeNode(ite.index)
          }
          if (ite.offset === 0) break
          ite.parent()
        }

        this.truncated = true
      }
    }
  }

  seek(bytes, padding) {
    return new ByteSeeker(this, this, bytes, padding)
  }

  byteRange(index) {
    const rx = this.storage.read()
    const range = getByteRange(this, index, rx)
    rx.tryFlush()

    return range
  }

  byteOffset(index) {
    if (index === 2 * this.length) return this.byteLength

    const rx = this.storage.read()
    const offset = getByteOffset(this, index, rx)
    rx.tryFlush()

    return offset
  }

  async downgrade() {
    if (!this.upgraded) return true

    const rx = this.storage.read()
    const nodePromises = []

    for (const r of this.roots) {
      nodePromises.push(rx.getTreeNode(r.index))
    }

    rx.tryFlush()

    const nodes = await Promise.all(nodePromises)

    for (let i = 0; i < this.roots.length; i++) {
      const root = this.roots[i]
      const node = nodes[i]

      if (!node) return false
      if (!b4a.equals(node.hash, root.hash)) return false
    }

    this.upgraded = false
    return true
  }

  async restore(length) {
    if (length === this.length) return this

    const roots = unslabNodes(await MerkleTree.getRootsFromStorage(this.storage, length))

    this.roots = roots
    this.length = length
    this.byteLength = totalSize(roots)
    this.ancestors = length

    for (const node of roots) this.byteLength += node.size

    return this
  }
}

class ReorgBatch extends MerkleTreeBatch {
  constructor(session) {
    super(session)

    this.roots = []
    this.length = 0
    this.byteLength = 0
    this.diff = null
    this.ancestors = 0
    // We set upgraded because reorgs are signed so hit will
    // hit the same code paths (like the treeLength check in commit)
    this.upgraded = true
    this.want = {
      nodes: 0,
      start: 0,
      end: 0
    }
  }

  get finished() {
    return this.want === null
  }

  update(proof) {
    if (this.want === null) return true

    const nodes = []
    const root = verifyTree(proof, nodes)

    if (root === null || !b4a.equals(root.hash, this.diff.hash)) return false

    this.nodes.push(...nodes)
    return this._update(nodes)
  }

  async _update(nodes) {
    const n = new Map()
    for (const node of nodes) n.set(node.index, node)

    let diff = null
    const ite = flat.iterator(this.diff.index)
    const startingDiff = this.diff

    while ((ite.index & 1) !== 0) {
      const left = n.get(ite.leftChild())
      if (!left) break

      const existing = await getTreeNodeFromStorage(this.session.storage, left.index)
      if (!existing || !b4a.equals(existing.hash, left.hash)) {
        diff = left
      } else {
        diff = n.get(ite.sibling())
      }
    }

    if ((this.diff.index & 1) === 0) return true
    if (diff === null) return false
    if (startingDiff !== this.diff) return false

    return this._updateDiffRoot(diff)
  }

  _updateDiffRoot(diff) {
    if (this.want === null) return true

    const spans = flat.spans(diff.index)
    const start = spans[0] / 2
    const end = Math.min(this.treeLength, spans[1] / 2 + 1)
    const len = end - start

    this.ancestors = start
    this.diff = diff

    if ((diff.index & 1) === 0 || this.want.start >= this.treeLength || len <= 0) {
      this.want = null
      return true
    }

    this.want.start = start
    this.want.end = end
    this.want.nodes = log2(spans[1] - spans[0] + 2) - 1

    return false
  }
}

class ByteSeeker {
  constructor(session, bytes, padding = 0) {
    this.session = session
    this.bytes = bytes
    this.padding = padding

    const size = session.byteLength - session.length * padding

    this.start = bytes >= size ? session.length : 0
    this.end = bytes < size ? session.length : 0
  }

  async _seek(bytes) {
    if (!bytes) return [0, 0]

    for (const node of this.session.roots) {
      // all async ticks happen once we find the root so safe
      const size = getUnpaddedSize(node, this.padding, null)

      if (bytes === size) return [flat.rightSpan(node.index) + 2, 0]
      if (bytes > size) {
        bytes -= size
        continue
      }

      const ite = flat.iterator(node.index)

      while ((ite.index & 1) !== 0) {
        const l = await getTreeNodeFromStorage(this.session.storage, ite.leftChild())

        if (l) {
          const size = getUnpaddedSize(l, this.padding, ite)

          if (size === bytes) return [ite.rightSpan() + 2, 0]
          if (size > bytes) continue
          bytes -= size
          ite.sibling()
        } else {
          ite.parent()
          return [ite.index, bytes]
        }
      }

      return [ite.index, bytes]
    }

    return null
  }

  async update() {
    // TODO: combine _seek and this, much simpler
    const res = await this._seek(this.bytes)
    if (!res) return null
    if ((res[0] & 1) === 0) return [res[0] / 2, res[1]]

    const span = flat.spans(res[0])
    this.start = span[0] / 2
    this.end = span[1] / 2 + 1

    return null
  }
}

class TreeProof {
  constructor(session, block, hash, seek, upgrade) {
    this.fork = session.fork
    this.signature = session.signature

    this.block = block
    this.hash = hash
    this.seek = seek
    this.upgrade = upgrade

    this.pending = {
      node: null,
      seek: null,
      upgrade: null,
      additionalUpgrade: null
    }
  }

  async settle() {
    const result = {
      fork: this.fork,
      block: null,
      hash: null,
      seek: null,
      upgrade: null,
      manifest: null
    }

    const [pNode, pSeek, pUpgrade, pAdditional] = await settleProof(this.pending)

    if (this.block) {
      if (pNode === null) throw INVALID_OPERATION('Invalid block request')
      result.block = {
        index: this.block.index,
        value: null, // populated upstream, alloc it here for simplicity
        nodes: pNode
      }
    } else if (this.hash) {
      if (pNode === null) throw INVALID_OPERATION('Invalid block request')
      result.hash = {
        index: this.hash.index,
        nodes: pNode
      }
    }

    if (this.seek && pSeek !== null) {
      result.seek = {
        bytes: this.seek.bytes,
        nodes: pSeek
      }
    }

    if (this.upgrade) {
      result.upgrade = {
        start: this.upgrade.start,
        length: this.upgrade.length,
        nodes: pUpgrade,
        additionalNodes: pAdditional || [],
        signature: this.signature
      }
    }

    return result
  }
}

class MerkleTree {
  static hash(s) {
    return unslab(crypto.tree(s.roots))
  }

  static signable(s, namespace) {
    return caps.treeSignable(namespace, MerkleTree.hash(s), s.length, s.fork)
  }

  static size(roots) {
    return totalSize(roots)
  }

  static span(roots) {
    return totalSpan(roots)
  }

  static getRoots(session, length) {
    return MerkleTree.getRootsFromStorage(session.storage, length)
  }

  static getRootsFromStorage(storage, length) {
    const indexes = flat.fullRoots(2 * length)
    const roots = new Array(indexes.length)
    const rx = storage.read()

    for (let i = 0; i < indexes.length; i++) {
      roots[i] = getTreeNodeOrError(rx, indexes[i])
    }

    rx.tryFlush()

    return Promise.all(roots)
  }

  static async upgradeable(session, length) {
    const indexes = flat.fullRoots(2 * length)
    const roots = new Array(indexes.length)
    const rx = session.storage.read()

    for (let i = 0; i < indexes.length; i++) {
      roots[i] = rx.getTreeNode(indexes[i])
    }

    rx.tryFlush()

    for (const node of await Promise.all(roots)) {
      if (node === null) return false
    }

    return true
  }

  static seek(session, bytes, padding) {
    return new ByteSeeker(session, bytes, padding)
  }

  static get(session, index) {
    return getTreeNodeFromStorage(session.storage, index)
  }

  static async truncate(session, length, batch, fork = batch.fork) {
    const head = length * 2
    const fullRoots = flat.fullRoots(head)

    for (let i = 0; i < fullRoots.length; i++) {
      const root = fullRoots[i]
      if (i < batch.roots.length && batch.roots[i].index === root) continue

      while (batch.roots.length > i) batch.roots.pop()
      batch.roots.push(unslabNode(await getTreeNodeFromStorageOrError(session.storage, root)))
    }

    while (batch.roots.length > fullRoots.length) {
      batch.roots.pop()
    }

    batch.fork = fork
    batch.length = length
    batch.ancestors = length
    batch.byteLength = totalSize(batch.roots)
    batch.upgraded = true

    return batch
  }

  static async reorg(session, proof, batch) {
    let unverified = null

    if (proof.block || proof.hash || proof.seek) {
      unverified = verifyTree(proof, batch.nodes)
    }

    if (!verifyUpgrade(proof, unverified, batch)) {
      throw INVALID_PROOF('Fork proof not verifiable')
    }

    for (const root of batch.roots) {
      const existing = await getTreeNodeFromStorage(session.storage, root.index)
      if (existing && b4a.equals(existing.hash, root.hash)) continue
      batch._updateDiffRoot(root)
      break
    }

    if (batch.diff !== null) {
      await batch._update(batch.nodes)
    } else {
      batch.want = null
      batch.ancestors = batch.length
    }

    return batch
  }

  static verifyFullyRemote(session, proof) {
    // TODO: impl this less hackishly
    const batch = new MerkleTreeBatch(session)

    batch.fork = proof.fork
    batch.roots = []
    batch.length = 0
    batch.ancestors = 0
    batch.byteLength = 0

    let unverified = verifyTree(proof, batch.nodes)

    if (proof.upgrade) {
      if (verifyUpgrade(proof, unverified, batch)) {
        unverified = null
      }
    }

    return batch
  }

  static async verify(session, proof) {
    const batch = new MerkleTreeBatch(session)

    let unverified = verifyTree(proof, batch.nodes)

    if (proof.upgrade) {
      if (verifyUpgrade(proof, unverified, batch)) {
        unverified = null
      }
    }

    if (unverified) {
      const verified = await getTreeNodeFromStorageOrError(session.storage, unverified.index)
      if (!b4a.equals(verified.hash, unverified.hash)) {
        throw INVALID_CHECKSUM('Invalid checksum at node ' + unverified.index)
      }
    }

    return batch
  }

  static proof(session, rx, { block, hash, seek, upgrade }) {
    return generateProof(session, rx, block, hash, seek, upgrade)
  }

  static maxMissingNodes(index, length) {
    const head = 2 * length
    const ite = flat.iterator(index)

    // See iterator.rightSpan()
    const iteRightSpan = ite.index + ite.factor / 2 - 1
    // If the index is not in the current tree, we do not know how many missing nodes there are...
    if (iteRightSpan >= head) return 0

    for (const r of flat.fullRoots(head)) {
      if (r === index) return 0
    }

    // need missing nodes not inclusive of index
    ite.parent()

    let cnt = 0
    while (!ite.contains(head)) {
      cnt++
      ite.parent()
    }

    return cnt
  }

  static async missingNodes(session, index, length) {
    const head = 2 * length
    const ite = flat.iterator(index)

    // See iterator.rightSpan()
    const iteRightSpan = ite.index + ite.factor / 2 - 1
    // If the index is not in the current tree, we do not know how many missing nodes there are...
    if (iteRightSpan >= head) return 0

    let cnt = 0
    // TODO: we could prop use a read batch here and do this in blocks of X for perf
    while (!ite.contains(head) && !(await hasTreeNode(session.storage, ite.index))) {
      cnt++
      if (cnt >= 1024) {
        throw ASSERTION('Bad arguments to missingNodes index=' + index + ' at length=' + length)
      }
      ite.parent()
    }

    return cnt
  }

  static byteOffset(session, index) {
    return getByteOffsetSession(session, index, null)
  }

  static byteRange(session, index) {
    const rx = session.storage.read()
    const offset = getByteOffsetSession(session, index, rx)
    const size = getNodeSize(index, rx)
    rx.tryFlush()
    return Promise.all([offset, size])
  }

  static upgradeLength(proof) {
    const extra = proof.additionalNodes

    if (extra.length) {
      const last = extra[extra.length - 1]
      const index = flat.rightSpan(last.index)
      return index / 2 + 1
    }

    return proof.start + proof.length
  }
}

module.exports = {
  MerkleTreeBatch,
  ReorgBatch,
  MerkleTree
}

async function getNodeSize(index, rx) {
  return (await getTreeNodeOrError(rx, index)).size
}

async function getByteOffsetSession(session, index, rx) {
  if (index === 2 * session.length) return session.byteLength

  const treeNodes =
    rx === null
      ? await getByteOffsetBatchFlush(session.roots, index, session.storage.read())
      : await getByteOffsetBatch(session.roots, index, rx)

  let offset = 0
  for (const node of treeNodes) offset += node.size

  return offset
}

async function getByteOffset(tree, index, rx) {
  if (index === 2 * tree.length) return tree.byteLength

  const treeNodes = await getByteOffsetBatch(tree.roots, index, rx)

  let offset = 0
  for (const node of treeNodes) offset += node.size

  return offset
}

function getByteOffsetBatchFlush(roots, index, rx) {
  const treeNodes = getByteOffsetBatch(roots, index, rx)
  rx.tryFlush()
  return treeNodes
}

function getByteOffsetBatch(roots, index, rx) {
  if ((index & 1) === 1) index = flat.leftSpan(index)

  let head = 0
  let cnt = 0

  const promises = []

  for (const node of roots) {
    // all async ticks happen once we find the root so safe
    head += 2 * (node.index - head + 1)

    if (index >= head) {
      promises.push(node.size)
      continue
    }

    const ite = flat.iterator(node.index)

    while (ite.index !== index) {
      if (++cnt >= 1024) throw ASSERTION('Bad getByteOffsetSession index=' + index)

      if (index < ite.index) {
        ite.leftChild()
      } else {
        promises.push(getTreeNodeOrError(rx, ite.leftChild()))
        ite.sibling()
      }
    }

    return Promise.all(promises)
  }

  throw ASSERTION('Failed to find offset')
}

function getByteRange(tree, index, rx) {
  const head = 2 * tree.length
  if (((index & 1) === 0 ? index : flat.rightSpan(index)) >= head) {
    throw BAD_ARGUMENT('Index is out of bounds')
  }

  const offset = getByteOffset(tree, index, rx)
  const size = getNodeSize(index, rx)

  return Promise.all([offset, size])
}

// All the methods needed for proof verification

function verifyTree({ block, hash, seek }, nodes) {
  const untrustedNode = block
    ? { index: 2 * block.index, value: block.value, nodes: block.nodes }
    : hash
      ? { index: hash.index, value: null, nodes: hash.nodes }
      : null

  if (untrustedNode === null && (!seek || !seek.nodes.length)) return null

  let root = null

  if (seek && seek.nodes.length) {
    const ite = flat.iterator(seek.nodes[0].index)
    const q = new NodeQueue(seek.nodes)

    root = q.shift(ite.index)
    nodes.push(root)

    while (q.length > 0) {
      const node = q.shift(ite.sibling())

      root = parentNode(ite.parent(), root, node)
      nodes.push(node)
      nodes.push(root)
    }
  }

  if (untrustedNode === null) return root

  const ite = flat.iterator(untrustedNode.index)
  const blockHash = untrustedNode.value && blockNode(ite.index, untrustedNode.value)

  const q = new NodeQueue(untrustedNode.nodes, root)

  root = blockHash || q.shift(ite.index)
  nodes.push(root)

  while (q.length > 0) {
    const node = q.shift(ite.sibling())

    root = parentNode(ite.parent(), root, node)
    nodes.push(node)
    nodes.push(root)
  }

  return root
}

function verifyUpgrade({ fork, upgrade }, blockRoot, batch) {
  const prologue = batch.prologue

  if (prologue) {
    const { start, length } = upgrade
    if (start < prologue.length && (start !== 0 || length < prologue.length)) {
      throw INVALID_PROOF('Upgrade does not satisfy prologue')
    }
  }

  const q = new NodeQueue(upgrade.nodes, blockRoot)

  let grow = batch.roots.length > 0
  let i = 0

  const to = 2 * (upgrade.start + upgrade.length)
  const ite = flat.iterator(0)

  for (; ite.fullRoot(to); ite.nextTree()) {
    if (i < batch.roots.length && batch.roots[i].index === ite.index) {
      i++
      continue
    }

    if (grow) {
      grow = false
      const root = ite.index
      if (i < batch.roots.length) {
        ite.seek(batch.roots[batch.roots.length - 1].index)
        while (ite.index !== root) {
          batch.appendRoot(q.shift(ite.sibling()), ite)
        }
        continue
      }
    }

    batch.appendRoot(q.shift(ite.index), ite)
  }

  if (prologue && batch.length === prologue.length) {
    if (!b4a.equals(prologue.hash, batch.hash())) {
      throw INVALID_PROOF('Invalid hash')
    }
  }

  const extra = upgrade.additionalNodes

  ite.seek(batch.roots[batch.roots.length - 1].index)
  i = 0

  while (i < extra.length && extra[i].index === ite.sibling()) {
    batch.appendRoot(extra[i++], ite)
  }

  while (i < extra.length) {
    const node = extra[i++]

    while (node.index !== ite.index) {
      if (ite.factor === 2) throw INVALID_OPERATION('Unexpected node: ' + node.index)
      ite.leftChild()
    }

    batch.appendRoot(node, ite)
    ite.sibling()
  }

  batch.signature = unslab(upgrade.signature)
  batch.fork = fork

  return q.extra === null
}

async function seekFromHead(session, head, bytes, padding) {
  const roots = flat.fullRoots(head)

  for (let i = 0; i < roots.length; i++) {
    const root = roots[i]
    const node = await getTreeNodeFromStorage(session.storage, root)
    const size = getUnpaddedSize(node, padding, null)

    if (bytes === size) return root
    if (bytes > size) {
      bytes -= size
      continue
    }

    return seekTrustedTree(session, root, bytes, padding)
  }

  return head
}

// trust that bytes are within the root tree and find the block at bytes

async function seekTrustedTree(session, root, bytes, padding) {
  if (!bytes) return root

  const ite = flat.iterator(root)
  let cnt = 0

  while ((ite.index & 1) !== 0) {
    if (++cnt >= 1024) throw ASSERTION('Bad seekTrusted bytes=' + bytes + ', paddding=' + padding)
    const l = await getTreeNodeFromStorage(session.storage, ite.leftChild())

    if (l) {
      const size = getUnpaddedSize(l, padding, ite)
      if (size === bytes) return ite.index
      if (size > bytes) continue
      bytes -= size
      ite.sibling()
    } else {
      ite.parent()
      return ite.index
    }
  }

  return ite.index
}

// try to find the block at bytes without trusting that is *is* within the root passed

async function seekUntrustedTree(session, root, bytes, padding) {
  const offset =
    (await getByteOffsetSession(session, root, null)) -
    (padding ? (padding * flat.leftSpan(root)) / 2 : 0)

  if (offset > bytes) throw INVALID_OPERATION('Invalid seek')
  if (offset === bytes) return root

  bytes -= offset

  const node = await getTreeNodeFromStorageOrError(session.storage, root)

  if (getUnpaddedSize(node, padding, null) <= bytes) throw INVALID_OPERATION('Invalid seek')

  return seekTrustedTree(session, root, bytes, padding)
}

// Below is proof production, ie, construct proofs to verify a request
// Note, that all these methods are sync as we can statically infer which nodes
// are needed for the remote to verify given they arguments they passed us

function seekProof(session, rx, seekRoot, root, p) {
  const ite = flat.iterator(seekRoot)
  let cnt = 0

  p.seek = []
  p.seek.push(getTreeNodeOrError(rx, ite.index))

  while (ite.index !== root) {
    if (++cnt >= 1024) throw ASSERTION('Bad seekProof seekRoot=' + seekRoot + ', root=' + root)
    ite.sibling()
    p.seek.push(getTreeNodeOrError(rx, ite.index))
    ite.parent()
  }
}

function blockAndSeekProof(session, rx, node, seek, seekRoot, root, p) {
  if (!node) return seekProof(session, rx, seekRoot, root, p)

  const ite = flat.iterator(node.index)
  let cnt = 0

  p.node = []
  if (!node.value) p.node.push(getTreeNodeOrError(rx, ite.index))

  while (ite.index !== root) {
    if (++cnt >= 1024) {
      throw ASSERTION('Bad blockAndSeekProof seekRoot=' + seekRoot + ', root=' + root)
    }
    ite.sibling()

    if (seek && ite.contains(seekRoot) && ite.index !== seekRoot) {
      seekProof(session, rx, seekRoot, ite.index, p)
    } else {
      p.node.push(getTreeNodeOrError(rx, ite.index))
    }

    ite.parent()
  }
}

function upgradeProof(session, rx, node, seek, from, to, subTree, p) {
  if (from === 0) p.upgrade = []

  for (const ite = flat.iterator(0); ite.fullRoot(to); ite.nextTree()) {
    // check if they already have the node
    if (ite.index + ite.factor / 2 < from) continue

    // connect existing tree
    if (p.upgrade === null && ite.contains(from - 2)) {
      p.upgrade = []

      const root = ite.index
      const target = from - 2
      let cnt = 0

      ite.seek(target)

      while (ite.index !== root) {
        if (++cnt >= 1024) throw ASSERTION('Bad upgradeProof target=' + target + ', root=' + root)

        ite.sibling()
        if (ite.index > target) {
          if (p.node === null && p.seek === null && ite.contains(subTree)) {
            blockAndSeekProof(session, rx, node, seek, subTree, ite.index, p)
          } else {
            p.upgrade.push(getTreeNodeOrError(rx, ite.index))
          }
        }
        ite.parent()
      }

      continue
    }

    if (p.upgrade === null) {
      p.upgrade = []
    }

    // if the subtree included is a child of this tree, include that one
    // instead of a dup node
    if (p.node === null && p.seek === null && ite.contains(subTree)) {
      blockAndSeekProof(session, rx, node, seek, subTree, ite.index, p)
      continue
    }

    // add root (can be optimised since the root might be in tree.roots)
    p.upgrade.push(getTreeNodeOrError(rx, ite.index))
  }
}

function additionalUpgradeProof(session, rx, from, to, p) {
  if (from === 0) p.additionalUpgrade = []

  for (const ite = flat.iterator(0); ite.fullRoot(to); ite.nextTree()) {
    // check if they already have the node
    if (ite.index + ite.factor / 2 < from) continue

    // connect existing tree
    if (p.additionalUpgrade === null && ite.contains(from - 2)) {
      p.additionalUpgrade = []

      const root = ite.index
      const target = from - 2
      let cnt = 0

      ite.seek(target)

      while (ite.index !== root) {
        if (++cnt >= 1024) {
          throw ASSERTION(
            'Bad arguments to additionalUpgradeProof root=' + root + ' target=' + target
          )
        }
        ite.sibling()
        if (ite.index > target) {
          p.additionalUpgrade.push(getTreeNodeOrError(rx, ite.index))
        }
        ite.parent()
      }

      continue
    }

    if (p.additionalUpgrade === null) {
      p.additionalUpgrade = []
    }

    // add root (can be optimised since the root is in tree.roots)
    p.additionalUpgrade.push(getTreeNodeOrError(rx, ite.index))
  }
}

function nodesToRoot(index, nodes, head) {
  const ite = flat.iterator(index)

  for (let i = 0; i < nodes; i++) {
    ite.parent()
    if (ite.contains(head)) throw INVALID_OPERATION('Nodes is out of bounds')
  }

  return ite.index
}

function totalSize(nodes) {
  let s = 0
  for (const node of nodes) s += node.size
  return s
}

function totalSpan(nodes) {
  let s = 0
  for (const node of nodes) s += 2 * (node.index - s + 1)
  return s
}

function blockNode(index, value) {
  return { index, size: value.byteLength, hash: crypto.data(value) }
}

function parentNode(index, a, b) {
  return { index, size: a.size + b.size, hash: crypto.parent(a, b) }
}

function log2(n) {
  let res = 1

  while (n > 2) {
    n /= 2
    res++
  }

  return res
}

function normalizeIndexed(block, hash) {
  if (block) {
    return {
      value: true,
      index: block.index * 2,
      nodes: block.nodes,
      lastIndex: block.index
    }
  }
  if (hash) {
    return {
      value: false,
      index: hash.index,
      nodes: hash.nodes,
      lastIndex: flat.rightSpan(hash.index) / 2
    }
  }
  return null
}

async function getTreeNodeOrError(rx, index) {
  const node = await rx.getTreeNode(index)
  if (node === null) {
    throw INVALID_OPERATION('Expected tree node ' + index + ' from storage, got (nil)')
  }
  return node
}

function getTreeNodeFromStorageOrError(storage, index) {
  const rx = storage.read()
  const p = getTreeNodeOrError(rx, index)
  rx.tryFlush()
  return p
}

function getTreeNodeFromStorage(storage, index) {
  const rx = storage.read()
  const node = rx.getTreeNode(index)
  rx.tryFlush()
  return node
}

function hasTreeNode(storage, index) {
  const rx = storage.read()
  const has = rx.hasTreeNode(index)
  rx.tryFlush()
  return has
}

async function settleProof(p) {
  const result = [
    p.node && Promise.all(p.node),
    p.seek && Promise.all(p.seek),
    p.upgrade && Promise.all(p.upgrade),
    p.additionalUpgrade && Promise.all(p.additionalUpgrade)
  ]

  try {
    return await Promise.all(result)
  } catch (err) {
    if (p.node) await Promise.allSettled(p.node)
    if (p.seek) await Promise.allSettled(p.seek)
    if (p.upgrade) await Promise.allSettled(p.upgrade)
    if (p.additionalUpgrade) await Promise.allSettled(p.additionalUpgrade)
    throw err
  }
}

// tree can be either the merkle tree or a merkle tree batch
async function generateProof(session, rx, block, hash, seek, upgrade) {
  // Important that this does not throw inbetween making the promise arrays
  // and finalise being called, otherwise there will be lingering promises in the background

  if (session.prologue && upgrade) {
    upgrade.start = upgrade.start < session.prologue.length ? 0 : upgrade.start
    upgrade.length =
      upgrade.start < session.prologue.length ? session.prologue.length : upgrade.length
  }

  const head = 2 * session.length
  const from = upgrade ? upgrade.start * 2 : 0
  const to = upgrade ? from + upgrade.length * 2 : head
  const node = normalizeIndexed(block, hash)

  // can't do anything as we have no data...
  if (head === 0) return new TreeProof(session, null, null, null, null)

  if (from >= to || to > head) {
    throw INVALID_OPERATION('Invalid upgrade')
  }
  if (seek && upgrade && node !== null && node.index >= from) {
    throw INVALID_OPERATION('Cannot both do a seek and block/hash request when upgrading')
  }

  let subTree = head

  const p = new TreeProof(session, block, hash, seek, upgrade)

  if (node !== null && (!upgrade || node.lastIndex < upgrade.start)) {
    subTree = nodesToRoot(node.index, node.nodes, to)
    const seekRoot = seek
      ? await seekUntrustedTree(session, subTree, seek.bytes, seek.padding)
      : head
    blockAndSeekProof(session, rx, node, seek, seekRoot, subTree, p.pending)
  } else if ((node || seek) && upgrade) {
    subTree = seek ? await seekFromHead(session, to, seek.bytes, seek.padding) : node.index
  }

  if (upgrade) {
    upgradeProof(session, rx, node, seek, from, to, subTree, p.pending)
    if (head > to) additionalUpgradeProof(session, rx, to, head, p.pending)
  }

  return p
}

function getUnpaddedSize(node, padding, ite) {
  return padding === 0
    ? node.size
    : node.size - padding * (ite ? ite.countLeaves() : flat.countLeaves(node.index))
}

function unslabNodes(nodes) {
  for (const node of nodes) unslabNode(node)
  return nodes
}

function unslabNode(node) {
  if (node === null) return node
  node.hash = unslab(node.hash)
  return node
}
const c = require('compact-encoding')
const { DEFAULT_NAMESPACE } = require('./caps')
const { INVALID_OPLOG_VERSION } = require('hypercore-errors')
const unslab = require('unslab')

const MANIFEST_PATCH = 0b00000001
const MANIFEST_PROLOGUE = 0b00000010
const MANIFEST_LINKED = 0b00000100
const MANIFEST_USER_DATA = 0b00001000

const hashes = {
  preencode(state, m) {
    state.end++ // small uint
  },
  encode(state, m) {
    if (m === 'blake2b') {
      c.uint.encode(state, 0)
      return
    }

    throw new Error('Unknown hash: ' + m)
  },
  decode(state) {
    const n = c.uint.decode(state)
    if (n === 0) return 'blake2b'
    throw new Error('Unknown hash id: ' + n)
  }
}

const signatures = {
  preencode(state, m) {
    state.end++ // small uint
  },
  encode(state, m) {
    if (m === 'ed25519') {
      c.uint.encode(state, 0)
      return
    }

    throw new Error('Unknown signature: ' + m)
  },
  decode(state) {
    const n = c.uint.decode(state)
    if (n === 0) return 'ed25519'
    throw new Error('Unknown signature id: ' + n)
  }
}

const signer = {
  preencode(state, m) {
    signatures.preencode(state, m.signature)
    c.fixed32.preencode(state, m.namespace)
    c.fixed32.preencode(state, m.publicKey)
  },
  encode(state, m) {
    signatures.encode(state, m.signature)
    c.fixed32.encode(state, m.namespace)
    c.fixed32.encode(state, m.publicKey)
  },
  decode(state) {
    return {
      signature: signatures.decode(state),
      namespace: c.fixed32.decode(state),
      publicKey: c.fixed32.decode(state)
    }
  }
}

const signerArray = c.array(signer)

const prologue = {
  preencode(state, p) {
    c.fixed32.preencode(state, p.hash)
    c.uint.preencode(state, p.length)
  },
  encode(state, p) {
    c.fixed32.encode(state, p.hash)
    c.uint.encode(state, p.length)
  },
  decode(state) {
    return {
      hash: c.fixed32.decode(state),
      length: c.uint.decode(state)
    }
  }
}

const manifestv0 = {
  preencode(state, m) {
    hashes.preencode(state, m.hash)
    state.end++ // type

    if (m.prologue && m.signers.length === 0) {
      c.fixed32.preencode(state, m.prologue.hash)
      return
    }

    if (m.quorum === 1 && m.signers.length === 1 && !m.allowPatch) {
      signer.preencode(state, m.signers[0])
    } else {
      state.end++ // flags
      c.uint.preencode(state, m.quorum)
      signerArray.preencode(state, m.signers)
    }
  },
  encode(state, m) {
    hashes.encode(state, m.hash)

    if (m.prologue && m.signers.length === 0) {
      c.uint.encode(state, 0)
      c.fixed32.encode(state, m.prologue.hash)
      return
    }

    if (m.quorum === 1 && m.signers.length === 1 && !m.allowPatch) {
      c.uint.encode(state, 1)
      signer.encode(state, m.signers[0])
    } else {
      c.uint.encode(state, 2)
      c.uint.encode(state, m.allowPatch ? 1 : 0)
      c.uint.encode(state, m.quorum)
      signerArray.encode(state, m.signers)
    }
  },
  decode(state) {
    const hash = hashes.decode(state)
    const type = c.uint.decode(state)

    if (type > 2) throw new Error('Unknown type: ' + type)

    if (type === 0) {
      return {
        version: 0,
        hash,
        allowPatch: false,
        quorum: 0,
        signers: [],
        prologue: {
          hash: c.fixed32.decode(state),
          length: 0
        },
        linked: null,
        userData: null
      }
    }

    if (type === 1) {
      return {
        version: 0,
        hash,
        allowPatch: false,
        quorum: 1,
        signers: [signer.decode(state)],
        prologue: null,
        linked: null,
        userData: null
      }
    }

    const flags = c.uint.decode(state)

    return {
      version: 0,
      hash,
      allowPatch: (flags & 1) !== 0,
      quorum: c.uint.decode(state),
      signers: signerArray.decode(state),
      prologue: null,
      linked: null,
      userData: null
    }
  }
}

const fixed32Array = c.array(c.fixed32)

const manifest = (exports.manifest = {
  preencode(state, m) {
    state.end++ // version

    if (m.version === 0) return manifestv0.preencode(state, m)

    state.end++ // flags
    hashes.preencode(state, m.hash)

    c.uint.preencode(state, m.quorum)
    signerArray.preencode(state, m.signers)

    if (m.prologue) prologue.preencode(state, m.prologue)
    if (m.linked) fixed32Array.preencode(state, m.linked)
    if (m.userData) c.buffer.preencode(state, m.userData)
  },
  encode(state, m) {
    c.uint.encode(state, m.version)

    if (m.version === 0) return manifestv0.encode(state, m)

    let flags = 0
    if (m.allowPatch) flags |= MANIFEST_PATCH
    if (m.prologue) flags |= MANIFEST_PROLOGUE
    if (m.linked) flags |= MANIFEST_LINKED
    if (m.userData) flags |= MANIFEST_USER_DATA

    c.uint.encode(state, flags)
    hashes.encode(state, m.hash)

    c.uint.encode(state, m.quorum)
    signerArray.encode(state, m.signers)

    if (m.prologue) prologue.encode(state, m.prologue)
    if (m.linked) fixed32Array.encode(state, m.linked)
    if (m.userData) c.buffer.encode(state, m.userData)
  },
  decode(state) {
    const version = c.uint.decode(state)

    if (version === 0) return manifestv0.decode(state)
    if (version > 2) throw new Error('Unknown version: ' + version)

    const flags = c.uint.decode(state)
    const hash = hashes.decode(state)
    const quorum = c.uint.decode(state)
    const signers = signerArray.decode(state)

    const hasPatch = (flags & MANIFEST_PATCH) !== 0
    const hasPrologue = (flags & MANIFEST_PROLOGUE) !== 0
    const hasLinked = (flags & MANIFEST_LINKED) !== 0
    const hasUserData = (flags & MANIFEST_USER_DATA) !== 0

    return {
      version,
      hash,
      allowPatch: hasPatch,
      quorum,
      signers,
      prologue: hasPrologue ? prologue.decode(state) : null,
      linked: hasLinked ? fixed32Array.decode(state) : null,
      userData: hasUserData ? c.buffer.decode(state) : null
    }
  }
})

const node = {
  preencode(state, n) {
    c.uint.preencode(state, n.index)
    c.uint.preencode(state, n.size)
    c.fixed32.preencode(state, n.hash)
  },
  encode(state, n) {
    c.uint.encode(state, n.index)
    c.uint.encode(state, n.size)
    c.fixed32.encode(state, n.hash)
  },
  decode(state) {
    return {
      index: c.uint.decode(state),
      size: c.uint.decode(state),
      hash: c.fixed32.decode(state)
    }
  }
}

const nodeArray = c.array(node)

const wire = (exports.wire = {})

wire.handshake = {
  preencode(state, m) {
    c.uint.preencode(state, 1)
    c.fixed32.preencode(state, m.capability)
  },
  encode(state, m) {
    c.uint.encode(state, m.seeks ? 1 : 0)
    c.fixed32.encode(state, m.capability)
  },
  decode(state) {
    const flags = c.uint.decode(state)
    return {
      seeks: (flags & 1) !== 0,
      capability: unslab(c.fixed32.decode(state))
    }
  }
}

const requestBlock = {
  preencode(state, b) {
    c.uint.preencode(state, b.index)
    c.uint.preencode(state, b.nodes)
  },
  encode(state, b) {
    c.uint.encode(state, b.index)
    c.uint.encode(state, b.nodes)
  },
  decode(state) {
    return {
      index: c.uint.decode(state),
      nodes: c.uint.decode(state)
    }
  }
}

const requestSeek = {
  preencode(state, s) {
    c.uint.preencode(state, s.bytes)
    c.uint.preencode(state, s.padding)
  },
  encode(state, s) {
    c.uint.encode(state, s.bytes)
    c.uint.encode(state, s.padding)
  },
  decode(state) {
    return {
      bytes: c.uint.decode(state),
      padding: c.uint.decode(state)
    }
  }
}

const requestUpgrade = {
  preencode(state, u) {
    c.uint.preencode(state, u.start)
    c.uint.preencode(state, u.length)
  },
  encode(state, u) {
    c.uint.encode(state, u.start)
    c.uint.encode(state, u.length)
  },
  decode(state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

wire.request = {
  preencode(state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.id)
    c.uint.preencode(state, m.fork)

    if (m.block) requestBlock.preencode(state, m.block)
    if (m.hash) requestBlock.preencode(state, m.hash)
    if (m.seek) requestSeek.preencode(state, m.seek)
    if (m.upgrade) requestUpgrade.preencode(state, m.upgrade)
    if (m.priority) c.uint.preencode(state, m.priority)
  },
  encode(state, m) {
    const flags =
      (m.block ? 1 : 0) |
      (m.hash ? 2 : 0) |
      (m.seek ? 4 : 0) |
      (m.upgrade ? 8 : 0) |
      (m.manifest ? 16 : 0) |
      (m.priority ? 32 : 0)

    c.uint.encode(state, flags)
    c.uint.encode(state, m.id)
    c.uint.encode(state, m.fork)

    if (m.block) requestBlock.encode(state, m.block)
    if (m.hash) requestBlock.encode(state, m.hash)
    if (m.seek) requestSeek.encode(state, m.seek)
    if (m.upgrade) requestUpgrade.encode(state, m.upgrade)
    if (m.priority) c.uint.encode(state, m.priority)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      id: c.uint.decode(state),
      fork: c.uint.decode(state),
      block: flags & 1 ? requestBlock.decode(state) : null,
      hash: flags & 2 ? requestBlock.decode(state) : null,
      seek: flags & 4 ? requestSeek.decode(state) : null,
      upgrade: flags & 8 ? requestUpgrade.decode(state) : null,
      manifest: (flags & 16) !== 0,
      priority: flags & 32 ? c.uint.decode(state) : 0
    }
  }
}

wire.cancel = {
  preencode(state, m) {
    c.uint.preencode(state, m.request)
  },
  encode(state, m) {
    c.uint.encode(state, m.request)
  },
  decode(state, m) {
    return {
      request: c.uint.decode(state)
    }
  }
}

const dataUpgrade = {
  preencode(state, u) {
    c.uint.preencode(state, u.start)
    c.uint.preencode(state, u.length)
    nodeArray.preencode(state, u.nodes)
    nodeArray.preencode(state, u.additionalNodes)
    c.optionalBuffer.preencode(state, u.signature)
  },
  encode(state, u) {
    c.uint.encode(state, u.start)
    c.uint.encode(state, u.length)
    nodeArray.encode(state, u.nodes)
    nodeArray.encode(state, u.additionalNodes)
    c.optionalBuffer.encode(state, u.signature)
  },
  decode(state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state),
      nodes: nodeArray.decode(state),
      additionalNodes: nodeArray.decode(state),
      signature: c.optionalBuffer.decode(state)
    }
  }
}

const dataSeek = {
  preencode(state, s) {
    c.uint.preencode(state, s.bytes)
    nodeArray.preencode(state, s.nodes)
  },
  encode(state, s) {
    c.uint.encode(state, s.bytes)
    nodeArray.encode(state, s.nodes)
  },
  decode(state) {
    return {
      bytes: c.uint.decode(state),
      nodes: nodeArray.decode(state)
    }
  }
}

const dataBlock = {
  preencode(state, b) {
    c.uint.preencode(state, b.index)
    c.buffer.preencode(state, b.value)
    nodeArray.preencode(state, b.nodes)
  },
  encode(state, b) {
    c.uint.encode(state, b.index)
    c.buffer.encode(state, b.value)
    nodeArray.encode(state, b.nodes)
  },
  decode(state) {
    return {
      index: c.uint.decode(state),
      value: c.buffer.decode(state),
      nodes: nodeArray.decode(state)
    }
  }
}

const dataHash = {
  preencode(state, b) {
    c.uint.preencode(state, b.index)
    nodeArray.preencode(state, b.nodes)
  },
  encode(state, b) {
    c.uint.encode(state, b.index)
    nodeArray.encode(state, b.nodes)
  },
  decode(state) {
    return {
      index: c.uint.decode(state),
      nodes: nodeArray.decode(state)
    }
  }
}

wire.data = {
  preencode(state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.request)
    c.uint.preencode(state, m.fork)

    if (m.block) dataBlock.preencode(state, m.block)
    if (m.hash) dataHash.preencode(state, m.hash)
    if (m.seek) dataSeek.preencode(state, m.seek)
    if (m.upgrade) dataUpgrade.preencode(state, m.upgrade)
    if (m.manifest) manifest.preencode(state, m.manifest)
  },
  encode(state, m) {
    const flags =
      (m.block ? 1 : 0) |
      (m.hash ? 2 : 0) |
      (m.seek ? 4 : 0) |
      (m.upgrade ? 8 : 0) |
      (m.manifest ? 16 : 0)

    c.uint.encode(state, flags)
    c.uint.encode(state, m.request)
    c.uint.encode(state, m.fork)

    if (m.block) dataBlock.encode(state, m.block)
    if (m.hash) dataHash.encode(state, m.hash)
    if (m.seek) dataSeek.encode(state, m.seek)
    if (m.upgrade) dataUpgrade.encode(state, m.upgrade)
    if (m.manifest) manifest.encode(state, m.manifest)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      request: c.uint.decode(state),
      fork: c.uint.decode(state),
      block: flags & 1 ? dataBlock.decode(state) : null,
      hash: flags & 2 ? dataHash.decode(state) : null,
      seek: flags & 4 ? dataSeek.decode(state) : null,
      upgrade: flags & 8 ? dataUpgrade.decode(state) : null,
      manifest: flags & 16 ? manifest.decode(state) : null
    }
  }
}

wire.noData = {
  preencode(state, m) {
    c.uint.preencode(state, m.request)
    c.uint.preencode(state, m.reason ? 1 : 0)
    if (m.reason) c.uint.preencode(state, m.reason)
  },
  encode(state, m) {
    c.uint.encode(state, m.request)
    c.uint.encode(state, m.reason ? 1 : 0)
    if (m.reason) c.uint.encode(state, m.reason)
  },
  decode(state, m) {
    const request = c.uint.decode(state)
    const flags = state.start < state.end ? c.uint.decode(state) : 0
    return {
      request,
      reason: flags & 1 ? c.uint.decode(state) : 0
    }
  }
}

// TODO: we should move to having these have a handle like in data, easier since they
// allocate state in practice
wire.want = {
  preencode(state, m) {
    c.uint.preencode(state, m.start)
    c.uint.preencode(state, m.length)

    const flags = m.any ? 1 : 0
    if (flags !== 0) c.uint.preencode(state, flags)
  },
  encode(state, m) {
    c.uint.encode(state, m.start)
    c.uint.encode(state, m.length)

    const flags = m.any ? 1 : 0
    if (flags !== 0) c.uint.encode(state, flags)
  },
  decode(state) {
    const start = c.uint.decode(state)
    const length = c.uint.decode(state)
    const flags = state.start < state.end ? c.uint.decode(state) : 0

    return {
      start,
      length,
      any: (flags & 1) !== 0
    }
  }
}

wire.unwant = {
  preencode(state, m) {
    c.uint.preencode(state, m.start)
    c.uint.preencode(state, m.length)

    const flags = m.any ? 1 : 0
    if (flags !== 0) c.uint.preencode(state, flags)
  },
  encode(state, m) {
    c.uint.encode(state, m.start)
    c.uint.encode(state, m.length)

    const flags = m.any ? 1 : 0
    if (flags !== 0) c.uint.encode(state, flags)
  },
  decode(state, m) {
    const start = c.uint.decode(state)
    const length = c.uint.decode(state)
    const flags = state.start < state.end ? c.uint.decode(state) : 0

    return {
      start,
      length,
      any: (flags & 1) !== 0
    }
  }
}

wire.range = {
  preencode(state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.start)
    if (m.length !== 1) c.uint.preencode(state, m.length)
  },
  encode(state, m) {
    c.uint.encode(state, (m.drop ? 1 : 0) | (m.length === 1 ? 2 : 0))
    c.uint.encode(state, m.start)
    if (m.length !== 1) c.uint.encode(state, m.length)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      drop: (flags & 1) !== 0,
      start: c.uint.decode(state),
      length: (flags & 2) !== 0 ? 1 : c.uint.decode(state)
    }
  }
}

wire.bitfield = {
  preencode(state, m) {
    c.uint.preencode(state, m.start)
    c.uint32array.preencode(state, m.bitfield)
  },
  encode(state, m) {
    c.uint.encode(state, m.start)
    c.uint32array.encode(state, m.bitfield)
  },
  decode(state, m) {
    return {
      start: c.uint.decode(state),
      bitfield: c.uint32array.decode(state)
    }
  }
}

wire.sync = {
  preencode(state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.fork)
    c.uint.preencode(state, m.length)
    c.uint.preencode(state, m.remoteLength)
  },
  encode(state, m) {
    c.uint.encode(
      state,
      (m.canUpgrade ? 1 : 0) |
        (m.uploading ? 2 : 0) |
        (m.downloading ? 4 : 0) |
        (m.hasManifest ? 8 : 0) |
        (m.allowPush ? 16 : 0)
    )
    c.uint.encode(state, m.fork)
    c.uint.encode(state, m.length)
    c.uint.encode(state, m.remoteLength)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      fork: c.uint.decode(state),
      length: c.uint.decode(state),
      remoteLength: c.uint.decode(state),
      canUpgrade: (flags & 1) !== 0,
      uploading: (flags & 2) !== 0,
      downloading: (flags & 4) !== 0,
      hasManifest: (flags & 8) !== 0,
      allowPush: (flags & 16) !== 0
    }
  }
}

wire.reorgHint = {
  preencode(state, m) {
    c.uint.preencode(state, m.from)
    c.uint.preencode(state, m.to)
    c.uint.preencode(state, m.ancestors)
  },
  encode(state, m) {
    c.uint.encode(state, m.from)
    c.uint.encode(state, m.to)
    c.uint.encode(state, m.ancestors)
  },
  decode(state) {
    return {
      from: c.uint.decode(state),
      to: c.uint.decode(state),
      ancestors: c.uint.decode(state)
    }
  }
}

wire.extension = {
  preencode(state, m) {
    c.string.preencode(state, m.name)
    c.raw.preencode(state, m.message)
  },
  encode(state, m) {
    c.string.encode(state, m.name)
    c.raw.encode(state, m.message)
  },
  decode(state) {
    return {
      name: c.string.decode(state),
      message: c.raw.decode(state)
    }
  }
}

const keyValue = {
  preencode(state, p) {
    c.string.preencode(state, p.key)
    c.buffer.preencode(state, p.value)
  },
  encode(state, p) {
    c.string.encode(state, p.key)
    c.buffer.encode(state, p.value)
  },
  decode(state) {
    return {
      key: c.string.decode(state),
      value: c.buffer.decode(state)
    }
  }
}

const treeUpgrade = {
  preencode(state, u) {
    c.uint.preencode(state, u.fork)
    c.uint.preencode(state, u.ancestors)
    c.uint.preencode(state, u.length)
    c.buffer.preencode(state, u.signature)
  },
  encode(state, u) {
    c.uint.encode(state, u.fork)
    c.uint.encode(state, u.ancestors)
    c.uint.encode(state, u.length)
    c.buffer.encode(state, u.signature)
  },
  decode(state) {
    return {
      fork: c.uint.decode(state),
      ancestors: c.uint.decode(state),
      length: c.uint.decode(state),
      signature: c.buffer.decode(state)
    }
  }
}

const bitfieldUpdate = {
  // TODO: can maybe be folded into a HAVE later on with the most recent spec
  preencode(state, b) {
    state.end++ // flags
    c.uint.preencode(state, b.start)
    c.uint.preencode(state, b.length)
  },
  encode(state, b) {
    state.buffer[state.start++] = b.drop ? 1 : 0
    c.uint.encode(state, b.start)
    c.uint.encode(state, b.length)
  },
  decode(state) {
    const flags = c.uint.decode(state)
    return {
      drop: (flags & 1) !== 0,
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

const oplog = (exports.oplog = {})

oplog.entry = {
  preencode(state, m) {
    state.end++ // flags
    if (m.userData) keyValue.preencode(state, m.userData)
    if (m.treeNodes) nodeArray.preencode(state, m.treeNodes)
    if (m.treeUpgrade) treeUpgrade.preencode(state, m.treeUpgrade)
    if (m.bitfield) bitfieldUpdate.preencode(state, m.bitfield)
  },
  encode(state, m) {
    const s = state.start++
    let flags = 0

    if (m.userData) {
      flags |= 1
      keyValue.encode(state, m.userData)
    }
    if (m.treeNodes) {
      flags |= 2
      nodeArray.encode(state, m.treeNodes)
    }
    if (m.treeUpgrade) {
      flags |= 4
      treeUpgrade.encode(state, m.treeUpgrade)
    }
    if (m.bitfield) {
      flags |= 8
      bitfieldUpdate.encode(state, m.bitfield)
    }

    state.buffer[s] = flags
  },
  decode(state) {
    const flags = c.uint.decode(state)
    return {
      userData: (flags & 1) !== 0 ? keyValue.decode(state) : null,
      treeNodes: (flags & 2) !== 0 ? nodeArray.decode(state) : null,
      treeUpgrade: (flags & 4) !== 0 ? treeUpgrade.decode(state) : null,
      bitfield: (flags & 8) !== 0 ? bitfieldUpdate.decode(state) : null
    }
  }
}

const keyPair = {
  preencode(state, kp) {
    c.buffer.preencode(state, kp.publicKey)
    c.buffer.preencode(state, kp.secretKey)
  },
  encode(state, kp) {
    c.buffer.encode(state, kp.publicKey)
    c.buffer.encode(state, kp.secretKey)
  },
  decode(state) {
    return {
      publicKey: c.buffer.decode(state),
      secretKey: c.buffer.decode(state)
    }
  }
}

const reorgHint = {
  preencode(state, r) {
    c.uint.preencode(state, r.from)
    c.uint.preencode(state, r.to)
    c.uint.preencode(state, r.ancestors)
  },
  encode(state, r) {
    c.uint.encode(state, r.from)
    c.uint.encode(state, r.to)
    c.uint.encode(state, r.ancestors)
  },
  decode(state) {
    return {
      from: c.uint.decode(state),
      to: c.uint.decode(state),
      ancestors: c.uint.decode(state)
    }
  }
}

const reorgHintArray = c.array(reorgHint)

const hints = {
  preencode(state, h) {
    reorgHintArray.preencode(state, h.reorgs)
    c.uint.preencode(state, h.contiguousLength)
  },
  encode(state, h) {
    reorgHintArray.encode(state, h.reorgs)
    c.uint.encode(state, h.contiguousLength)
  },
  decode(state) {
    return {
      reorgs: reorgHintArray.decode(state),
      contiguousLength: state.start < state.end ? c.uint.decode(state) : 0
    }
  }
}

const treeHeader = {
  preencode(state, t) {
    c.uint.preencode(state, t.fork)
    c.uint.preencode(state, t.length)
    c.buffer.preencode(state, t.rootHash)
    c.buffer.preencode(state, t.signature)
  },
  encode(state, t) {
    c.uint.encode(state, t.fork)
    c.uint.encode(state, t.length)
    c.buffer.encode(state, t.rootHash)
    c.buffer.encode(state, t.signature)
  },
  decode(state) {
    return {
      fork: c.uint.decode(state),
      length: c.uint.decode(state),
      rootHash: c.buffer.decode(state),
      signature: c.buffer.decode(state)
    }
  }
}

const types = {
  preencode(state, t) {
    c.string.preencode(state, t.tree)
    c.string.preencode(state, t.bitfield)
    c.string.preencode(state, t.signer)
  },
  encode(state, t) {
    c.string.encode(state, t.tree)
    c.string.encode(state, t.bitfield)
    c.string.encode(state, t.signer)
  },
  decode(state) {
    return {
      tree: c.string.decode(state),
      bitfield: c.string.decode(state),
      signer: c.string.decode(state)
    }
  }
}

const externalHeader = {
  preencode(state, m) {
    c.uint.preencode(state, m.start)
    c.uint.preencode(state, m.length)
  },
  encode(state, m) {
    c.uint.encode(state, m.start)
    c.uint.encode(state, m.length)
  },
  decode(state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

const keyValueArray = c.array(keyValue)

oplog.header = {
  preencode(state, h) {
    state.end += 2 // version + flags
    if (h.external) {
      externalHeader.preencode(state, h.external)
      return
    }
    c.fixed32.preencode(state, h.key)
    if (h.manifest) manifest.preencode(state, h.manifest)
    if (h.keyPair) keyPair.preencode(state, h.keyPair)
    keyValueArray.preencode(state, h.userData)
    treeHeader.preencode(state, h.tree)
    hints.preencode(state, h.hints)
  },
  encode(state, h) {
    c.uint.encode(state, 1)
    if (h.external) {
      c.uint.encode(state, 1) // ONLY set the first big for clarity
      externalHeader.encode(state, h.external)
      return
    }
    c.uint.encode(state, (h.manifest ? 2 : 0) | (h.keyPair ? 4 : 0))
    c.fixed32.encode(state, h.key)
    if (h.manifest) manifest.encode(state, h.manifest)
    if (h.keyPair) keyPair.encode(state, h.keyPair)
    keyValueArray.encode(state, h.userData)
    treeHeader.encode(state, h.tree)
    hints.encode(state, h.hints)
  },
  decode(state) {
    const version = c.uint.decode(state)

    if (version > 1) {
      throw INVALID_OPLOG_VERSION('Invalid header version. Expected <= 1, got ' + version)
    }

    if (version === 0) {
      const old = {
        types: types.decode(state),
        userData: keyValueArray.decode(state),
        tree: treeHeader.decode(state),
        signer: keyPair.decode(state),
        hints: hints.decode(state)
      }

      return {
        external: null,
        key: old.signer.publicKey,
        manifest: {
          version: 0,
          hash: old.types.tree,
          allowPatch: false,
          quorum: 1,
          signers: [
            {
              signature: old.types.signer,
              namespace: DEFAULT_NAMESPACE,
              publicKey: old.signer.publicKey
            }
          ],
          prologue: null,
          linked: null,
          userData: null
        },
        keyPair: old.signer.secretKey ? old.signer : null,
        userData: old.userData,
        tree: old.tree,
        hints: old.hints
      }
    }

    const flags = c.uint.decode(state)

    if (flags & 1) {
      return {
        external: externalHeader.decode(state),
        key: null,
        manifest: null,
        keyPair: null,
        userData: null,
        tree: null,
        hints: null
      }
    }

    return {
      external: null,
      key: c.fixed32.decode(state),
      manifest: (flags & 2) !== 0 ? manifest.decode(state) : null,
      keyPair: (flags & 4) !== 0 ? keyPair.decode(state) : null,
      userData: keyValueArray.decode(state),
      tree: treeHeader.decode(state),
      hints: hints.decode(state)
    }
  }
}

const uintArray = c.array(c.uint)

const multisigInput = {
  preencode(state, inp) {
    c.uint.preencode(state, inp.signer)
    c.fixed64.preencode(state, inp.signature)
    c.uint.preencode(state, inp.patch)
  },
  encode(state, inp) {
    c.uint.encode(state, inp.signer)
    c.fixed64.encode(state, inp.signature)
    c.uint.encode(state, inp.patch)
  },
  decode(state) {
    return {
      signer: c.uint.decode(state),
      signature: c.fixed64.decode(state),
      patch: c.uint.decode(state)
    }
  }
}

const patchEncodingv0 = {
  preencode(state, n) {
    c.uint.preencode(state, n.start)
    c.uint.preencode(state, n.length)
    uintArray.preencode(state, n.nodes)
  },
  encode(state, n) {
    c.uint.encode(state, n.start)
    c.uint.encode(state, n.length)
    uintArray.encode(state, n.nodes)
  },
  decode(state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state),
      nodes: uintArray.decode(state)
    }
  }
}

const multisigInputv0 = {
  preencode(state, n) {
    state.end++
    c.uint.preencode(state, n.signer)
    c.fixed64.preencode(state, n.signature)
    if (n.patch) patchEncodingv0.preencode(state, n.patch)
  },
  encode(state, n) {
    c.uint.encode(state, n.patch ? 1 : 0)
    c.uint.encode(state, n.signer)
    c.fixed64.encode(state, n.signature)
    if (n.patch) patchEncodingv0.encode(state, n.patch)
  },
  decode(state) {
    const flags = c.uint.decode(state)
    return {
      signer: c.uint.decode(state),
      signature: c.fixed64.decode(state),
      patch: flags & 1 ? patchEncodingv0.decode(state) : null
    }
  }
}

const multisigInputArrayv0 = c.array(multisigInputv0)
const multisigInputArray = c.array(multisigInput)

const compactNode = {
  preencode(state, n) {
    c.uint.preencode(state, n.index)
    c.uint.preencode(state, n.size)
    c.fixed32.preencode(state, n.hash)
  },
  encode(state, n) {
    c.uint.encode(state, n.index)
    c.uint.encode(state, n.size)
    c.fixed32.encode(state, n.hash)
  },
  decode(state) {
    return {
      index: c.uint.decode(state),
      size: c.uint.decode(state),
      hash: c.fixed32.decode(state)
    }
  }
}

const compactNodeArray = c.array(compactNode)

exports.multiSignaturev0 = {
  preencode(state, s) {
    multisigInputArrayv0.preencode(state, s.proofs)
    compactNodeArray.preencode(state, s.patch)
  },
  encode(state, s) {
    multisigInputArrayv0.encode(state, s.proofs)
    compactNodeArray.encode(state, s.patch)
  },
  decode(state) {
    return {
      proofs: multisigInputArrayv0.decode(state),
      patch: compactNodeArray.decode(state)
    }
  }
}

exports.multiSignature = {
  preencode(state, s) {
    multisigInputArray.preencode(state, s.proofs)
    compactNodeArray.preencode(state, s.patch)
  },
  encode(state, s) {
    multisigInputArray.encode(state, s.proofs)
    compactNodeArray.encode(state, s.patch)
  },
  decode(state) {
    return {
      proofs: multisigInputArray.decode(state),
      patch: compactNodeArray.decode(state)
    }
  }
}
const c = require('compact-encoding')
const b4a = require('b4a')
const flat = require('flat-tree')
const { MerkleTree } = require('./merkle-tree')
const { multiSignature, multiSignaturev0 } = require('./messages')

module.exports = {
  assemblev0,
  assemble,
  inflatev0,
  inflate,
  partialSignature,
  signableLength
}

function inflatev0(data) {
  return c.decode(multiSignaturev0, data)
}

function inflate(data) {
  return c.decode(multiSignature, data)
}

async function partialSignature(
  core,
  signer,
  from,
  to = core.state.length,
  signature = core.state.signature
) {
  if (from > core.state.length) return null
  const nodes = to <= from ? null : await upgradeNodes(core, from, to)

  if (signature.byteLength !== 64) {
    signature = c.decode(multiSignature, signature).proofs[0].signature
  }

  return {
    signer,
    signature,
    patch: nodes ? to - from : 0,
    nodes
  }
}

async function upgradeNodes(core, from, to) {
  const rx = core.state.storage.read()
  let p = null
  try {
    p = await MerkleTree.proof(core.state, rx, { upgrade: { start: from, length: to - from } })
  } catch (err) {
    rx.destroy()
    throw err
  }
  rx.tryFlush()
  return (await p.settle()).upgrade.nodes
}

function signableLength(lengths, quorum) {
  if (quorum <= 0) quorum = 1
  if (quorum > lengths.length) return 0

  return lengths.sort(cmp)[quorum - 1]
}

function cmp(a, b) {
  return b - a
}

function assemblev0(inputs) {
  const proofs = []
  const patch = []

  for (const u of inputs) {
    proofs.push(compressProof(u, patch))
  }

  return c.encode(multiSignaturev0, { proofs, patch })
}

function assemble(inputs) {
  const proofs = []
  const patch = []
  const seen = new Set()

  for (const u of inputs) {
    if (u.nodes) {
      for (const node of u.nodes) {
        if (seen.has(node.index)) continue
        seen.add(node.index)
        patch.push(node)
      }
    }

    proofs.push({
      signer: u.signer,
      signature: u.signature,
      patch: u.patch
    })
  }

  return c.encode(multiSignature, { proofs, patch })
}

function compareNode(a, b) {
  if (a.index !== b.index) return false
  if (a.size !== b.size) return false
  return b4a.equals(a.hash, b.hash)
}

function compressProof(proof, nodes) {
  return {
    signer: proof.signer,
    signature: proof.signature,
    patch: proof.patch ? compressUpgrade(proof, nodes) : null
  }
}

function compressUpgrade(p, nodes) {
  const u = {
    start: flat.rightSpan(p.nodes[p.nodes.length - 1].index) / 2 + 1,
    length: p.patch,
    nodes: []
  }

  for (const node of p.nodes) {
    let present = false
    for (let i = 0; i < nodes.length; i++) {
      if (!compareNode(nodes[i], node)) continue

      u.nodes.push(i)
      present = true
      break
    }

    if (present) continue
    u.nodes.push(nodes.push(node) - 1)
  }

  return u
}
module.exports = class Mutex {
  constructor() {
    this.locked = false
    this.destroyed = false

    this._destroying = null
    this._destroyError = null
    this._queue = []
    this._enqueue = (resolve, reject) => this._queue.push([resolve, reject])
  }

  idle() {
    return this._queue.length === 0 && this.locked === false
  }

  lock() {
    if (this.destroyed) {
      return Promise.reject(this._destroyError || new Error('Mutex has been destroyed'))
    }
    if (this.locked) return new Promise(this._enqueue)
    this.locked = true
    return Promise.resolve()
  }

  unlock() {
    if (!this._queue.length) {
      this.locked = false
      return
    }
    this._queue.shift()[0]()
  }

  destroy(err) {
    if (!this._destroying) {
      this._destroying = this.locked ? this.lock().catch(() => {}) : Promise.resolve()
    }

    this.destroyed = true
    if (err) this._destroyError = err

    if (err) {
      while (this._queue.length) this._queue.shift()[1](err)
    }

    return this._destroying
  }
}
const FIFO = require('fast-fifo')

module.exports = class ReceiverQueue {
  constructor() {
    this.queue = new FIFO()
    this.priority = []
    this.requests = new Map()
    this.length = 0
  }

  push(req) {
    // TODO: use a heap at some point if we wanna support multiple prios
    if (req.priority > 0) this.priority.push(req)
    else this.queue.push(req)

    this.requests.set(req.id, req)
    this.length++
  }

  shift() {
    while (this.priority.length > 0) {
      const msg = this.priority.pop()
      const req = this._processRequest(msg)
      if (req !== null) return req
    }

    while (this.queue.length > 0) {
      const msg = this.queue.shift()
      const req = this._processRequest(msg)
      if (req !== null) return req
    }

    return null
  }

  _processRequest(req) {
    if (req.block || req.hash || req.seek || req.upgrade || req.manifest) {
      this.requests.delete(req.id)
      this.length--
      return req
    }

    return null
  }

  clear() {
    this.queue.clear()
    this.priority = []
    this.length = 0
    this.requests.clear()
  }

  delete(id) {
    const req = this.requests.get(id)
    if (!req) return

    req.block = null
    req.hash = null
    req.seek = null
    req.upgrade = null
    req.manifest = false

    this.requests.delete(id)
    this.length--

    if (this.length === 0) {
      this.queue.clear()
      this.priority = []
    }
  }
}
const BigSparseArray = require('big-sparse-array')
const quickbit = require('./compat').quickbit

const BITS_PER_PAGE = 32768
const BYTES_PER_PAGE = BITS_PER_PAGE / 8
const WORDS_PER_PAGE = BYTES_PER_PAGE / 4
const BITS_PER_SEGMENT = 2097152
const BYTES_PER_SEGMENT = BITS_PER_SEGMENT / 8
const PAGES_PER_SEGMENT = BITS_PER_SEGMENT / BITS_PER_PAGE

class RemoteBitfieldPage {
  constructor(index, bitfield, segment) {
    this.index = index
    this.offset = index * BYTES_PER_PAGE - segment.offset
    this.bitfield = bitfield
    this.segment = segment

    segment.add(this)
  }

  get tree() {
    return this.segment.tree
  }

  get(index) {
    return quickbit.get(this.bitfield, index)
  }

  set(index, val) {
    if (quickbit.set(this.bitfield, index, val)) {
      this.tree.update(this.offset * 8 + index)
    }
  }

  setRange(start, end, val) {
    quickbit.fill(this.bitfield, val, start, end)

    let i = Math.floor(start / 128)
    const n = i + Math.ceil((end - start) / 128)

    while (i <= n) this.tree.update(this.offset * 8 + i++ * 128)
  }

  findFirst(val, position) {
    return quickbit.findFirst(this.bitfield, val, position)
  }

  findLast(val, position) {
    return quickbit.findLast(this.bitfield, val, position)
  }

  insert(start, bitfield) {
    this.bitfield.set(bitfield, start / 32)
    this.segment.refresh()
  }

  clear(start, bitfield) {
    quickbit.clear(this.bitfield, { field: bitfield, offset: start })
  }
}

class RemoteBitfieldSegment {
  constructor(index) {
    this.index = index
    this.offset = index * BYTES_PER_SEGMENT
    this.tree = quickbit.Index.from([], BYTES_PER_SEGMENT)
    this.pages = new Array(PAGES_PER_SEGMENT)
    this.pagesLength = 0
  }

  get chunks() {
    return this.tree.chunks
  }

  refresh() {
    this.tree = quickbit.Index.from(this.tree.chunks, BYTES_PER_SEGMENT)
  }

  add(page) {
    const pageIndex = page.index - this.index * PAGES_PER_SEGMENT
    if (pageIndex >= this.pagesLength) this.pagesLength = pageIndex + 1

    this.pages[pageIndex] = page

    const chunk = { field: page.bitfield, offset: page.offset }

    this.chunks.push(chunk)

    for (let i = this.chunks.length - 2; i >= 0; i--) {
      const prev = this.chunks[i]
      if (prev.offset <= chunk.offset) break
      this.chunks[i] = chunk
      this.chunks[i + 1] = prev
    }
  }

  findFirst(val, position) {
    position = this.tree.skipFirst(!val, position)

    let j = position & (BITS_PER_PAGE - 1)
    let i = (position - j) / BITS_PER_PAGE

    if (i >= PAGES_PER_SEGMENT) return -1

    while (i < this.pagesLength) {
      const p = this.pages[i]

      let index = -1

      if (p) index = p.findFirst(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_PAGE + index

      j = 0
      i++
    }

    return val || this.pagesLength === PAGES_PER_SEGMENT ? -1 : this.pagesLength * BITS_PER_PAGE
  }

  findLast(val, position) {
    position = this.tree.skipLast(!val, position)

    let j = position & (BITS_PER_PAGE - 1)
    let i = (position - j) / BITS_PER_PAGE

    if (i >= PAGES_PER_SEGMENT) return -1

    while (i >= 0) {
      const p = this.pages[i]

      let index = -1

      if (p) index = p.findLast(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_PAGE + index

      j = BITS_PER_PAGE - 1
      i--
    }

    return -1
  }
}

module.exports = class RemoteBitfield {
  static BITS_PER_PAGE = BITS_PER_PAGE
  static BITS_PER_SEGMENT = BITS_PER_SEGMENT

  constructor() {
    this._pages = new BigSparseArray()
    this._segments = new BigSparseArray()
    this._maxSegments = 0
  }

  getBitfield(index) {
    const j = index & (BITS_PER_PAGE - 1)
    const i = (index - j) / BITS_PER_PAGE

    const p = this._pages.get(i)
    return p || null
  }

  get(index) {
    const j = index & (BITS_PER_PAGE - 1)
    const i = (index - j) / BITS_PER_PAGE

    const p = this._pages.get(i)

    return p ? p.get(j) : false
  }

  set(index, val) {
    const j = index & (BITS_PER_PAGE - 1)
    const i = (index - j) / BITS_PER_PAGE

    let p = this._pages.get(i)

    if (!p && val) {
      const k = Math.floor(i / PAGES_PER_SEGMENT)
      const s = this._segments.get(k) || this._segments.set(k, new RemoteBitfieldSegment(k))
      if (this._maxSegments <= k) this._maxSegments = k + 1

      p = this._pages.set(i, new RemoteBitfieldPage(i, new Uint32Array(WORDS_PER_PAGE), s))
    }

    if (p) p.set(j, val)
  }

  setRange(start, end, val) {
    let j = start & (BITS_PER_PAGE - 1)
    let i = (start - j) / BITS_PER_PAGE

    while (start < end) {
      let p = this._pages.get(i)

      if (!p && val) {
        const k = Math.floor(i / PAGES_PER_SEGMENT)
        const s = this._segments.get(k) || this._segments.set(k, new RemoteBitfieldSegment(k))
        if (this._maxSegments <= k) this._maxSegments = k + 1

        p = this._pages.set(i, new RemoteBitfieldPage(i, new Uint32Array(WORDS_PER_PAGE), s))
      }

      const offset = i * BITS_PER_PAGE
      const last = Math.min(end - offset, BITS_PER_PAGE)
      const range = last - j

      if (p) p.setRange(j, last, val)

      j = 0
      i++
      start += range
    }
  }

  findFirst(val, position) {
    let j = position & (BITS_PER_SEGMENT - 1)
    let i = (position - j) / BITS_PER_SEGMENT

    while (i < this._maxSegments) {
      const s = this._segments.get(i)

      let index = -1

      if (s) index = s.findFirst(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_SEGMENT + index

      j = 0
      i++
    }

    // For the val === false case, we always return at least
    // the 'position', also if nothing was found
    return val ? -1 : Math.max(position, this._maxSegments * BITS_PER_SEGMENT)
  }

  firstSet(position) {
    return this.findFirst(true, position)
  }

  firstUnset(position) {
    return this.findFirst(false, position)
  }

  findLast(val, position) {
    let j = position & (BITS_PER_SEGMENT - 1)
    let i = (position - j) / BITS_PER_SEGMENT

    while (i >= 0) {
      const s = this._segments.get(i)

      let index = -1

      if (s) index = s.findLast(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_SEGMENT + index

      j = BITS_PER_SEGMENT - 1
      i--
    }

    return -1
  }

  lastSet(position) {
    return this.findLast(true, position)
  }

  lastUnset(position) {
    return this.findLast(false, position)
  }

  insert(start, bitfield) {
    if (start % 32 !== 0) return false

    let length = bitfield.byteLength * 8

    let j = start & (BITS_PER_PAGE - 1)
    let i = (start - j) / BITS_PER_PAGE

    while (length > 0) {
      let p = this._pages.get(i)

      if (!p) {
        const k = Math.floor(i / PAGES_PER_SEGMENT)
        const s = this._segments.get(k) || this._segments.set(k, new RemoteBitfieldSegment(k))
        if (this._maxSegments <= k) this._maxSegments = k + 1

        p = this._pages.set(i, new RemoteBitfieldPage(i, new Uint32Array(WORDS_PER_PAGE), s))
      }

      const end = Math.min(j + length, BITS_PER_PAGE)
      const range = end - j

      p.insert(j, bitfield.subarray(0, range / 32))

      bitfield = bitfield.subarray(range / 32)

      j = 0
      i++
      length -= range
    }

    return true
  }

  clear(start, bitfield) {
    if (start % 32 !== 0) return false

    let length = bitfield.byteLength * 8

    let j = start & (BITS_PER_PAGE - 1)
    let i = (start - j) / BITS_PER_PAGE

    while (length > 0) {
      let p = this._pages.get(i)

      if (!p) {
        const k = Math.floor(i / PAGES_PER_SEGMENT)
        const s = this._segments.get(k) || this._segments.set(k, new RemoteBitfieldSegment(k))
        if (this._maxSegments <= k) this._maxSegments = k + 1

        p = this._pages.set(i, new RemoteBitfieldPage(i, new Uint32Array(WORDS_PER_PAGE), s))
      }

      const end = Math.min(j + length, BITS_PER_PAGE)
      const range = end - j

      p.clear(j, bitfield.subarray(0, range / 32))

      bitfield = bitfield.subarray(range / 32)

      j = 0
      i++
      length -= range
    }

    return true
  }
}
/* DEV DOCS
  Every hypercore has one Replicator object managing its connections to other peers.
  There is one Peer object per peer connected to the Hypercore.
  Hypercores do not know about other hypercores, so when a peer is connected to multiple cores, there exists one Peer object per core.

  Hypercore indicates block should be downloaded through methods like Replicator.addRange or Replicator.addBlock
  Hypercore calls Replicator.updateActivity every time a hypercore session opens/closes
  Replicator.updateActivity ensures the Hypercore is downloading blocks as expected
  Replicator keeps track of:
    - Which blocks need to be downloaded (Replicator._blocks)
    - Which blocks currently have inflight requests (Replicator._inflight)

  Blocks are requested from remote peers by Peer objects. The flow is:
    - The replicator's updatePeer method gets called
    - The replicator detects whether the Peer can accept more requests (for example by checking if it's maxed out on inflight blocks)
    - The replicator then tells the Peer what to request (e.g. Peer_requestRange or Peer._requestBlock methods)

  The Peer object is responsible for tracking
    - Which blocks does the Peer have available (tracked in remoteBitfield)
    - Which blocks are you actively looking for from this peer (tracked in missingBlocks)
    - How many blocks are currently inflight (tracked in inflight)
  The Peer uses this information to decide which blocks to request from the peer in response to _requestRange requests and the like.
*/

const b4a = require('b4a')
const safetyCatch = require('safety-catch')
const RandomIterator = require('random-array-iterator')
const flatTree = require('flat-tree')
const Mutex = require('./mutex')
const ReceiverQueue = require('./receiver-queue')
const HotswapQueue = require('./hotswap-queue')
const RemoteBitfield = require('./remote-bitfield')
const { MerkleTree } = require('./merkle-tree')
const w = require('./wants')
const { LocalWants, RemoteWants } = w
const {
  REQUEST_CANCELLED,
  REQUEST_TIMEOUT,
  INVALID_CAPABILITY,
  SNAPSHOT_NOT_AVAILABLE,
  ASSERTION
} = require('hypercore-errors')
const m = require('./messages')
const caps = require('./caps')

const DEFAULT_MAX_INFLIGHT = [16, 512]
const SCALE_LATENCY = 50
const NOT_DOWNLOADING_SLACK = (20000 + Math.random() * 20000) | 0
const MAX_PEERS_UPGRADE = 3
const LAST_BLOCKS = 256
const MAX_RANGES = 64
const MIN_PEER_UPDATE_ALL = 40

const NOT_AVAILABLE = 1
const INVALID_REQUEST = 2
const MAX_INVALID_REQUESTS = 64
const MAX_BACKOFFS = MAX_INVALID_REQUESTS / 2

const PRIORITY = {
  NORMAL: 0,
  HIGH: 1,
  VERY_HIGH: 2,
  CANCELLED: 255 // reserved to mark cancellation
}

class Attachable {
  constructor(replicator) {
    this.replicator = replicator
    this.resolved = false
    this.processing = false
    this.refs = []
    this.wants = null
  }

  addWant(w) {
    if (this.wants === null) this.wants = new Set()
    this.wants.add(w)
  }

  removeWant(w) {
    if (this.wants === null) return
    this.wants.delete(w)
  }

  attach(session) {
    const r = {
      context: this,
      session,
      sindex: 0,
      rindex: 0,
      snapshot: true,
      resolve: null,
      reject: null,
      promise: null,
      timeout: null
    }

    r.sindex = session.push(r) - 1
    r.rindex = this.refs.push(r) - 1
    r.promise = new Promise((resolve, reject) => {
      r.resolve = resolve
      r.reject = reject
    })

    return r
  }

  detach(r, err = null) {
    if (r.context !== this) return false

    this._detach(r)
    this._cancel(r, err)
    this.gc()

    return true
  }

  _detach(r) {
    const rh = this.refs.pop()
    const sh = r.session.pop()

    if (r.rindex < this.refs.length) this.refs[(rh.rindex = r.rindex)] = rh
    if (r.sindex < r.session.length) r.session[(sh.sindex = r.sindex)] = sh

    destroyRequestTimeout(r)
    r.context = null

    return r
  }

  gc() {
    if (this.refs.length > 0 || this.processing) return
    this._unref()

    if (this.wants === null) return

    const wants = this.wants
    this.wants = null

    let update = null

    for (const w of wants) {
      if (w.any) {
        const removed = w.wants.removeAnyRange(w.start, w.length, this)
        if (!removed) continue
        if (update === null) update = new Set()
        update.add(w.wants.peer)
        // TODO: should also use a free list for simplicity
        w.wants.peer.wireUnwant.send(removed)
        continue
      }

      if (w.wants.removeBatch(w.start, this)) {
        if (update === null) update = new Set()
        update.add(w.wants.peer)
      }
    }

    if (update === null) return
    for (const peer of update) {
      this.replicator.updatePeer(peer)
    }
  }

  processed() {
    this.processing = false
    this.gc()
  }

  _cancel(r, err) {
    r.reject(err || REQUEST_CANCELLED())
  }

  _unref() {
    // overwrite me
  }

  resolve(val) {
    this.resolved = true
    while (this.refs.length > 0) {
      this._detach(this.refs[this.refs.length - 1]).resolve(val)
    }
    this.gc()
  }

  reject(err) {
    this.resolved = true
    while (this.refs.length > 0) {
      this._detach(this.refs[this.refs.length - 1]).reject(err)
    }
    this.gc()
  }

  setTimeout(r, ms) {
    destroyRequestTimeout(r)
    r.timeout = setTimeout(onrequesttimeout, ms, r)
  }
}

class BlockRequest extends Attachable {
  constructor(replicator, tracker, index, priority, force) {
    super(replicator)

    this.index = index
    this.priority = priority
    this.inflight = []
    this.queued = false
    this.hotswap = null
    this.tracker = tracker
    this.force = force
  }

  _unref() {
    if (this.resolved) return
    this.queued = false

    for (const req of this.inflight) {
      req.peer._cancelRequest(req)
    }

    this.tracker.remove(this.index)
    removeHotswap(this)
  }
}

class RangeBatchRequest extends Attachable {
  constructor(replicator, batch) {
    super(replicator)

    this.batch = batch
    this.index = 0
  }
}

class RangeRequest extends Attachable {
  constructor(replicator, ranges, start, end, linear, blocks) {
    super(replicator)

    this.start = start
    this.end = end
    this.linear = linear
    this.blocks = blocks
    this.ranges = ranges
    this.batches = []

    ranges.push(this)

    if (this.end === -1) {
      this.replicator._alwaysLatestBlock++
    }

    // As passed by the user, immut
    this.userStart = start
    this.userEnd = end
  }

  addBatch(batch) {
    for (let i = 0; i < this.batches.length; i++) {
      const b = this.batches[i]
      if (b.batch === batch) return false
    }
    const b = new RangeBatchRequest(this.replicator, batch)
    b.index = this.batches.length
    this.batches.push(b)
    return true
  }

  removeBatch(batch) {
    const head = this.batches.pop()

    if (head !== batch) {
      head.index = batch.index
      this.batches[head.index] = head
    }

    batch.gc()
  }

  _unref() {
    const rangeIndex = this.ranges.indexOf(this)
    if (rangeIndex === -1) return

    const h = this.ranges.pop()
    if (h !== this) {
      this.ranges[rangeIndex] = h
    }

    if (this.end === -1) {
      this.replicator._alwaysLatestBlock--
    }

    while (this.batches.length) {
      this.batches.pop().gc()
    }
  }

  _cancel(r) {
    r.resolve(false)
  }
}

class UpgradeRequest extends Attachable {
  constructor(replicator, fork, length) {
    super(replicator)

    this.fork = fork
    this.length = length
    this.inflight = []
  }

  _unref() {
    if (this.resolved) return
    if (this.replicator.eagerUpgrade === true || this.inflight.length > 0) return
    this.replicator._upgrade = null
  }

  _cancel(r) {
    r.resolve(false)
  }
}

class SeekRequest extends Attachable {
  constructor(replicator, seeks, seeker) {
    super(replicator)

    this.seeker = seeker
    this.inflight = []
    this.seeks = seeks
  }

  _unref() {
    if (this.resolved) return
    if (this.inflight.length > 0) return
    const i = this.seeks.indexOf(this)
    if (i === -1) return
    const h = this.seeks.pop()
    if (i < this.seeks.length) this.seeks[i] = h
  }
}

class ForkRequest extends Attachable {
  constructor(replicator, fork) {
    super(replicator)
    this.fork = fork
    this.inflight = []
    this.batch = null
  }
}

class InflightTracker {
  constructor() {
    this._requests = []
    this._free = []
    this._active = 0
  }

  get idle() {
    return this._active === 0
  }

  *[Symbol.iterator]() {
    for (const req of this._requests) {
      if (req !== null) yield req
    }
  }

  add(req) {
    const id = this._free.length ? this._free.pop() : this._requests.push(null)
    req.id = id
    this._requests[id - 1] = req
    this._active++
    return req
  }

  get(id) {
    return id <= this._requests.length ? this._requests[id - 1] : null
  }

  remove(id, roundtrip) {
    if (id > this._requests.length) return
    if (this._requests[id - 1]) this._active--
    this._requests[id - 1] = null
    if (roundtrip === true) this._free.push(id)
  }

  reusable(id) {
    this._free.push(id)
  }
}

class BlockTracker {
  constructor(replicator) {
    this._replicator = replicator
    this._map = new Map()
  }

  [Symbol.iterator]() {
    return this._map.values()
  }

  isEmpty() {
    return this._map.size === 0
  }

  has(index) {
    return this._map.has(index)
  }

  get(index) {
    return this._map.get(index) || null
  }

  add(index, priority, force) {
    let b = this._map.get(index)
    if (b) return b

    b = new BlockRequest(this._replicator, this, index, priority, force)
    this._map.set(index, b)

    return b
  }

  remove(index) {
    const b = this.get(index)
    this._map.delete(index)
    return b
  }
}

class RoundtripQueue {
  constructor() {
    this.queue = []
    this.tick = 0
  }

  clear() {
    const ids = new Array(this.queue.length)
    for (let i = 0; i < ids.length; i++) {
      ids[i] = this.queue[i][1]
    }

    this.queue = []

    return ids
  }

  add(id) {
    this.queue.push([++this.tick, id])
  }

  flush(tick) {
    let flushed = null

    for (let i = 0; i < this.queue.length; i++) {
      if (this.queue[i][0] > tick) break
      if (flushed === null) flushed = []
      flushed.push(this.queue[i][1])
    }

    if (flushed !== null) this.queue.splice(0, flushed.length)
    return flushed
  }
}

class ProofRequest {
  constructor(msg, proof, block, manifest) {
    this.msg = msg
    this.proof = proof
    this.block = block
    this.manifest = manifest
  }

  async fulfill() {
    if (this.proof === null) return null

    const [proof, block] = await Promise.all([this.proof.settle(), this.block])

    if (this.manifest) proof.manifest = this.manifest
    if (!block && proof.block) return null

    if (block) proof.block.value = block
    return proof
  }
}

class Peer {
  constructor(replicator, protomux, channel, inflightRange) {
    this.core = replicator.core
    this.replicator = replicator
    this.stream = protomux.stream
    this.protomux = protomux
    this.remotePublicKey = this.stream.remotePublicKey
    this.remoteSupportsSeeks = false
    this.inflightRange = inflightRange
    this.fullyDownloadedSignaled = 0

    this.paused = false
    this.removed = false

    this.channel = channel
    this.channel.userData = this

    this.wireSync = this.channel.messages[0]
    this.wireRequest = this.channel.messages[1]
    this.wireCancel = this.channel.messages[2]
    this.wireData = this.channel.messages[3]
    this.wireNoData = this.channel.messages[4]
    this.wireWant = this.channel.messages[5]
    this.wireUnwant = this.channel.messages[6]
    this.wireBitfield = this.channel.messages[7]
    this.wireRange = this.channel.messages[8]
    this.wireExtension = this.channel.messages[9]

    // Same stats as replicator, but for this specific peer
    this.stats = {
      wireSync: { tx: 0, rx: 0 },
      wireRequest: { tx: 0, rx: 0 },
      wireCancel: { tx: 0, rx: 0 },
      wireData: { tx: 0, rx: 0 },
      wireWant: { tx: 0, rx: 0 },
      wireUnwant: { tx: 0, rx: 0 },
      wireBitfield: { tx: 0, rx: 0 },
      wireRange: { tx: 0, rx: 0 },
      wireExtension: { tx: 0, rx: 0 },
      hotswaps: 0,
      invalidData: 0,
      invalidRequests: 0,
      backoffs: 0,
      notAvailableBackoffs: 0
    }

    this.receiverQueue = new ReceiverQueue()
    this.receiverBusy = false

    // most often not used, so made on demand
    this.roundtripQueue = null

    this.inflight = 0
    this.dataProcessing = 0

    this.canUpgrade = true

    this.needsSync = false
    this.syncsProcessing = 0
    this.lastUpgradableLength = 0
    this.lastUpgradableFork = 0

    this._remoteContiguousLength = 0

    // TODO: tweak pipelining so that data sent BEFORE remoteOpened is not cap verified!
    // we might wanna tweak that with some crypto, ie use the cap to encrypt it...
    // or just be aware of that, to only push non leaky data

    this.remoteOpened = false
    this.remoteBitfield = new RemoteBitfield()
    this.missingBlocks = new RemoteBitfield()

    this.pushedLength = 0

    this.remoteFork = 0
    this.remoteLength = 0
    this.remoteCanUpgrade = false
    this.remoteUploading = true
    this.remoteDownloading = true
    this.remoteSynced = false
    this.remoteHasManifest = false
    this.remoteAllowPush = false
    this.remoteRequests = new Map()

    this.segmentsWanted = new Set()
    this.broadcastedNonSparse = false

    this.wants = new LocalWants(this)
    this.remoteWants = new RemoteWants(this)

    this.lengthAcked = 0

    this.extensions = new Map()
    this.lastExtensionSent = ''
    this.lastExtensionRecv = ''

    replicator._ifAvailable++
    replicator._active++
  }

  get remoteContiguousLength() {
    return this.remoteBitfield.findFirst(false, this._remoteContiguousLength)
  }

  getMaxInflight() {
    const stream = this.stream.rawStream
    if (!stream.udx) return Math.min(this.inflightRange[1], this.inflightRange[0] * 3)

    const scale =
      stream.rtt <= SCALE_LATENCY
        ? 1
        : (stream.rtt / SCALE_LATENCY) * Math.min(1, 2 / this.replicator.peers.length)
    return Math.max(
      this.inflightRange[0],
      Math.round(Math.min(this.inflightRange[1], this.inflightRange[0] * scale))
    )
  }

  getMaxHotswapInflight() {
    const inf = this.getMaxInflight()
    return Math.max(16, inf / 2)
  }

  signalUpgrade() {
    if (this._shouldUpdateCanUpgrade() === true) this._updateCanUpgradeAndSync()
    else this.sendSync()
  }

  _markInflight(index) {
    this.missingBlocks.set(index, false)
  }

  broadcastRange(start, length, drop) {
    if (!this.isActive()) return

    if (drop) this._unclearLocalRange(start, length)
    else this._clearLocalRange(start, length)

    const fullyContig = this.core.header.hints.contiguousLength === this.core.state.length

    if (start + LAST_BLOCKS < this.core.state.length && !drop && !fullyContig) {
      if (!this.remoteWants.hasRange(start, length)) return
    }

    let force = false
    if (fullyContig && !drop) {
      start = 0
      length = this.core.state.length

      // Always send the broadcast when we switch from sparse to fully contiguous, so remote knows too
      if (this.fullyDownloadedSignaled < length) {
        this.fullyDownloadedSignaled = length
        force = true
      }
    }

    // TODO: consider also adding early-returns on the drop===true case
    if (!force && !drop) {
      // No need to broadcast if the remote already has this range

      if (this._remoteContiguousLength >= start + length) return

      if (length === 1) {
        if (this.remoteBitfield.get(start)) return
      } else {
        if (this.remoteBitfield.firstUnset(start) >= start + length) return
      }
    }

    this.wireRange.send({
      drop,
      start,
      length
    })
    incrementTx(this.stats.wireRange, this.replicator.stats.wireRange)
  }

  extension(name, message) {
    this.wireExtension.send({ name: name === this.lastExtensionSent ? '' : name, message })
    incrementTx(this.stats.wireExtension, this.replicator.stats.wireExtension)
    this.lastExtensionSent = name
  }

  onextension(message) {
    const name = message.name || this.lastExtensionRecv
    this.lastExtensionRecv = name
    const ext = this.extensions.get(name)
    if (ext) {
      ext._onmessage({ start: 0, end: message.message.byteLength, buffer: message.message }, this)
    }
  }

  sendSync() {
    // Skip syncs if in repair mode
    if (this.core._repairMode) return

    if (this.syncsProcessing !== 0) {
      this.needsSync = true
      return
    }

    if (this.core.state.fork !== this.remoteFork) {
      this.canUpgrade = false
    }

    this.needsSync = false

    this.wireSync.send({
      fork: this.core.state.fork,
      length: this.core.state.length,
      remoteLength: this.core.state.fork === this.remoteFork ? this.remoteLength : 0,
      canUpgrade: this.canUpgrade,
      uploading: true,
      downloading: this.replicator.isDownloading(),
      hasManifest: !!this.core.header.manifest && this.core.compat === false,
      allowPush: this.replicator.isAllowingPush()
    })
    incrementTx(this.stats.wireSync, this.replicator.stats.wireSync)
  }

  onopen({ seeks, capability }) {
    const expected = caps.replicate(
      this.stream.isInitiator === false,
      this.core.key,
      this.stream.handshakeHash
    )

    if (b4a.equals(capability, expected) !== true) {
      // TODO: change this to a rejection instead, less leakage
      throw INVALID_CAPABILITY('Remote sent an invalid replication capability')
    }

    if (this.remoteOpened === true) return
    this.remoteOpened = true
    this.remoteSupportsSeeks = seeks

    this.protomux.cork()

    this.sendSync()

    const contig = Math.min(this.core.state.length, this.core.header.hints.contiguousLength)
    if (contig > 0) {
      this.broadcastRange(0, contig, false)

      if (contig === this.core.state.length) {
        this.broadcastedNonSparse = true
      }
    }

    this.replicator._ifAvailable--
    this.replicator._addPeer(this)

    this.protomux.uncork()

    this.core.checkIfIdle()
  }

  onclose(isRemote) {
    // we might have signalled to the remote that we are done (ie not downloading) and the remote might agree on that
    // if that happens, the channel might be closed by the remote. if so just renegotiate it.
    // TODO: add a CLOSE_REASON to mux to we can make this cleaner...
    const reopen =
      isRemote === true &&
      this.remoteOpened === true &&
      this.remoteDownloading === false &&
      this.remoteUploading === true &&
      this.replicator.downloading === true

    if (this.remoteOpened === false) {
      this.replicator._ifAvailable--
      this.replicator.queueUpdateAll()
      return
    }

    this.remoteOpened = false
    this.removed = true
    this.remoteRequests.clear() // cancel all
    this.receiverQueue.clear()

    if (this.roundtripQueue !== null) {
      for (const id of this.roundtripQueue.clear()) this.replicator._inflight.reusable(id)
    }

    this.replicator._removePeer(this)

    if (reopen) {
      this.replicator._makePeer(this.protomux)
    }
  }

  closeIfIdle() {
    if (this.remoteDownloading === false && this.replicator.isDownloading() === false) {
      // idling, shut it down...
      this.channel.close()
      return true
    }

    return false
  }

  async onsync(msg) {
    const {
      fork,
      length,
      remoteLength,
      canUpgrade,
      uploading,
      downloading,
      hasManifest,
      allowPush
    } = msg

    const lengthChanged = length !== this.remoteLength
    const sameFork = fork === this.core.state.fork

    this.remoteSynced = true
    this.remoteFork = fork
    this.remoteLength = length
    this.remoteCanUpgrade = canUpgrade
    this.remoteUploading = uploading
    this.remoteDownloading = downloading
    this.remoteHasManifest = hasManifest
    this.remoteAllowPush = allowPush

    if (this.closeIfIdle()) return

    this.lengthAcked = sameFork ? remoteLength : 0
    this.syncsProcessing++

    this.replicator._updateFork(this)

    if (this.remoteLength > this.core.state.length && this.lengthAcked === this.core.state.length) {
      if (this.replicator._addUpgradeMaybe() !== null) this._update()
    }

    const upgrade =
      lengthChanged === false || sameFork === false
        ? this.canUpgrade && sameFork
        : await this._canUpgrade(length, fork)

    if (length === this.remoteLength && fork === this.core.state.fork) {
      this.canUpgrade = upgrade
      if (upgrade) {
        this.lastUpgradableFork = fork
        this.lastUpgradableLength = length
      }
    }

    if (--this.syncsProcessing !== 0) return // ie not latest

    if (
      this.needsSync === true ||
      (this.core.state.fork === this.remoteFork && this.core.state.length > this.remoteLength)
    ) {
      this.signalUpgrade()
    }

    this._update()
  }

  _shouldUpdateCanUpgrade() {
    return (
      this.core.state.fork === this.remoteFork &&
      this.core.state.length > this.remoteLength &&
      this.canUpgrade === false &&
      this.syncsProcessing === 0
    )
  }

  async _updateCanUpgradeAndSync() {
    const { length, fork } = this.core.state

    const remoteLength = this.remoteLength
    const remoteFork = this.remoteFork
    const canUpgrade = await this._canUpgrade(this.remoteLength, this.remoteFork)

    if (
      this.syncsProcessing > 0 ||
      length !== this.core.state.length ||
      fork !== this.core.state.fork
    ) {
      return
    }
    if (remoteLength !== this.remoteLength || remoteFork !== this.remoteFork) {
      return
    }
    if (canUpgrade === this.canUpgrade) {
      return
    }

    this.canUpgrade = canUpgrade
    if (canUpgrade) {
      this.lastUpgradableLength = this.remoteLength
      this.lastUpgradableFork = this.remoteFork
    }

    this.sendSync()
  }

  // Safe to call in the background - never fails
  async _canUpgrade(remoteLength, remoteFork) {
    if (remoteFork !== this.core.state.fork) return false

    if (remoteLength === 0) return true
    if (remoteLength >= this.core.state.length) return false

    try {
      // Rely on caching to make sure this is cheap...
      const canUpgrade = await MerkleTree.upgradeable(this.core.state, remoteLength)

      if (remoteFork !== this.core.state.fork) return false

      return canUpgrade
    } catch {
      return false
    }
  }

  async _getProof(batch, msg, pushing) {
    let block = null

    if (msg.block) {
      const index = msg.block.index

      if (!pushing && (msg.fork !== this.core.state.fork || !this.core.bitfield.get(index))) {
        return new ProofRequest(msg, null, null, null)
      }

      block = batch.getBlock(index)
      block.catch(noop)
    }

    const manifest = msg.manifest && !this.core.compat ? this.core.header.manifest : null

    try {
      const proof = await MerkleTree.proof(this.core.state, batch, msg)
      return new ProofRequest(msg, proof, block, manifest)
    } catch (err) {
      batch.destroy()

      this.replicator._oninvalidrequest(err, msg, this)

      if (this.stats.invalidRequests >= MAX_INVALID_REQUESTS) throw err

      await backoff(this.stats.invalidRequests)
      return null
    }
  }

  async onrequest(msg) {
    const size = this.remoteRequests.size
    this.remoteRequests.set(msg.id, msg)

    // if size didnt change -> id overwrite -> old one is deleted, cancel current and re-add
    if (size === this.remoteRequests.size) {
      this._cancel(msg.id)
      this.remoteRequests.set(msg.id, msg)
    }

    if (!this.protomux.drained || this.receiverQueue.length) {
      this.receiverQueue.push(msg)
      return
    }

    if (this.replicator.destroyed) return

    await this._handleRequest(msg)
  }

  oncancel(msg) {
    this._cancel(msg.request)
  }

  _cancel(id) {
    this.remoteRequests.delete(id)
    this.receiverQueue.delete(id)
  }

  ondrain() {
    return this._handleRequests()
  }

  async _handleRequests() {
    if (this.receiverBusy || this.replicator.destroyed) return
    this.receiverBusy = true
    this.protomux.cork()

    while (
      this.remoteOpened &&
      this.protomux.drained &&
      this.receiverQueue.length > 0 &&
      !this.removed
    ) {
      const msg = this.receiverQueue.shift()
      await this._handleRequest(msg)
    }

    this.protomux.uncork()
    this.receiverBusy = false
  }

  async push(index) {
    if (!this.remoteAllowPush) return
    if (!this.remoteDownloading) return
    if (this.core.state.length <= index) return
    if (this.core.state.fork !== this.remoteFork) return
    if (this.remoteBitfield.get(index)) return

    const msg = {
      id: 0,
      fork: this.core.state.fork,
      block: null,
      hash: null,
      seek: null,
      upgrade: null,
      manifest: this.remoteLength === 0,
      priority: 0
    }

    await this.replicator._txLock.lock()
    try {
      const remoteLength = Math.max(this.remoteLength, this.pushedLength)

      msg.block = {
        index,
        nodes: MerkleTree.maxMissingNodes(2 * index, remoteLength)
      }

      if (index >= remoteLength) {
        msg.upgrade = {
          start: remoteLength,
          length: this.core.state.length - remoteLength
        }
      }

      let req = null
      const batch = this.core.storage.read()
      try {
        req = await this._getProof(batch, msg, true)
      } catch (err) {
        this.replicator._oninvalidrequest(err, msg, this)
        return
      }

      if (req === null) return
      batch.tryFlush()

      await this._fulfillRequest(req, true)
    } finally {
      this.replicator._txLock.unlock()
    }
  }

  async _handleRequest(msg) {
    const locked = !!msg.upgrade && this.remoteAllowPush

    if (locked) {
      // ensure contig push proofs
      await this.replicator._txLock.lock()
      const end = msg.upgrade.start + msg.upgrade.length

      if (this.pushedLength < end) {
        msg.upgrade.start = this.pushedLength
        msg.upgrade.length = end - this.pushedLength
      }
    }

    try {
      const batch = this.core.storage.read()

      // TODO: could still be answerable if (index, fork) is an ancestor of the current fork
      const req =
        msg.fork === this.core.state.fork
          ? await this._getProof(batch, msg, false)
          : new ProofRequest(msg, null, null, null)

      if (req === null) {
        this.wireNoData.send({ request: msg.id, reason: INVALID_REQUEST })
        return
      }

      batch.tryFlush()

      await this._fulfillRequest(req, false)
    } finally {
      if (locked) this.replicator._txLock.unlock()
    }
  }

  async _fulfillRequest(req, pushing) {
    if (this.core._repairMode) {
      // if cancelled do not reply
      if (this.remoteRequests.get(req.msg.id) !== req.msg) {
        return
      }

      // sync from now on, so safe to delete from the map
      this.remoteRequests.delete(req.msg.id)

      // If cutting off the fulfillment, ensure promise is caught.
      // While repairing merkle tree nodes can be `nil` so can throw.
      req.fulfill().catch(safetyCatch)
      return
    }

    const proof = await req.fulfill()

    if (!pushing) {
      // if cancelled do not reply
      if (this.remoteRequests.get(req.msg.id) !== req.msg) {
        return
      }

      // sync from now on, so safe to delete from the map
      this.remoteRequests.delete(req.msg.id)
    } else if (!this.remoteAllowPush) {
      // if pushing but remote disabled it, just drop it
      return
    }

    if (!this.isActive() && proof.block !== null) {
      return
    }

    if (proof === null) {
      if (req.msg.manifest && this.core.header.manifest) {
        const manifest = this.core.header.manifest
        this.wireData.send({
          request: req.msg.id,
          fork: this.core.state.fork,
          block: null,
          hash: null,
          seek: null,
          upgrade: null,
          manifest
        })
        incrementTx(this.stats.wireData, this.replicator.stats.wireData)
        return
      }

      this.wireNoData.send({ request: req.msg.id, reason: NOT_AVAILABLE })
      return
    }

    if (proof.block !== null) {
      this.replicator._onupload(proof.block.index, proof.block.value.byteLength, this)
    }

    if (proof.upgrade) {
      const remoteLength = MerkleTree.upgradeLength(proof.upgrade)
      if (remoteLength > this.pushedLength) this.pushedLength = remoteLength
    }

    this.wireData.send({
      request: req.msg.id,
      fork: req.msg.fork,
      block: proof.block,
      hash: proof.hash,
      seek: proof.seek,
      upgrade: proof.upgrade,
      manifest: proof.manifest
    })
    incrementTx(this.stats.wireData, this.replicator.stats.wireData)
  }

  _cancelRequest(req) {
    if (req.priority === PRIORITY.CANCELLED) return
    // mark as cancelled also and avoid re-entry
    req.priority = PRIORITY.CANCELLED

    this.inflight--
    this.replicator._requestDone(req.id, false)

    // clear inflight state
    if (isBlockRequest(req)) this.replicator._unmarkInflight(req.block.index)
    if (isUpgradeRequest(req)) this.replicator._clearInflightUpgrade(req)

    if (this.roundtripQueue === null) this.roundtripQueue = new RoundtripQueue()
    this.roundtripQueue.add(req.id)
    this.wireCancel.send({ request: req.id })
    incrementTx(this.stats.wireCancel, this.replicator.stats.wireCancel)
  }

  _checkIfConflict() {
    this.paused = true

    const length = Math.min(this.core.state.length, this.remoteLength)
    if (length === 0) return // pause and ignore

    this.wireRequest.send({
      id: 0, // TODO: use an more explicit id for this eventually...
      fork: this.remoteFork,
      block: null,
      hash: null,
      seek: null,
      upgrade: {
        start: 0,
        length
      }
    })

    incrementTx(this.stats.wireRequest, this.replicator.stats.wireRequest)
  }

  _unmarkInflightBlockRequest(req, data) {
    if (isBlockRequest(req)) this.replicator._unmarkInflight(req.block.index)
    else if (data.block && !req) this.replicator._unmarkInflight(data.block.index)
  }

  async ondata(data) {
    if (data.request !== 0 && !data.upgrade) return this._handleData(data)

    await this.replicator._rxLock.lock()
    try {
      await this._handleData(data)
    } finally {
      this.replicator._rxLock.unlock()
    }
  }

  async _handleData(data) {
    // always allow a fork conflict proof to be sent
    if (data.request === 0 && data.upgrade && data.upgrade.start === 0) {
      if (await this.core.checkConflict(data, this)) return
      this.paused = false
    }

    const req = data.request > 0 ? this.replicator._inflight.get(data.request) : null
    const reorg = data.fork > this.core.state.fork

    // no push atm, TODO: check if this satisfies another pending request
    // allow reorg pushes tho as those are not written to storage so we'll take all the help we can get
    if (req === null && reorg === false && !this.replicator.allowPush) {
      return
    }

    // Skip accepting data if in repair mode to avoid corruption
    if (this.core._repairMode) {
      this.replicator._onnodata(this, req, NOT_AVAILABLE)
      return
    }

    if (req === null && reorg === false && data.block) {
      // mark this as inflight to avoid parallel requests
      this.replicator._markInflight(data.block.index)
    }

    if (req !== null) {
      if (req.peer !== this) return
      this._onrequestroundtrip(req)
    }

    try {
      if (reorg === true) return await this.replicator._onreorgdata(this, req, data)
    } catch (err) {
      safetyCatch(err)
      this._unmarkInflightBlockRequest(req, data)

      this.paused = true
      this.replicator._oninvaliddata(err, req, data, this)
      return
    }

    this.dataProcessing++
    if (isBlockRequest(req)) this.replicator._markProcessing(req.block.index)

    try {
      if (!this.replicator._matchingRequest(req, data) || !(await this.core.verify(data, this))) {
        this.replicator._onnodata(this, req, 0)
        return
      }
    } catch (err) {
      safetyCatch(err)
      this._unmarkInflightBlockRequest(req, data)

      if (err.code === 'WRITE_FAILED') {
        // For example, we don't want to keep pulling data when storage is full
        // TODO: notify the user somehow
        this.paused = true
        return
      }

      if (this.core.closed && !isCriticalError(err)) return

      if (err.code !== 'INVALID_OPERATION') {
        // might be a fork, verify
        this._checkIfConflict()
      }

      // if push mode, we MIGHT get an occasional bad message
      // no need to mega bail for that. TODO: rate limit instead as a general thing
      if (!this.replicator.allowPush) {
        this.paused = true
      }

      this.replicator._onnodata(this, req, 0)
      this.replicator._oninvaliddata(err, req, data, this)
      return
    } finally {
      if (isBlockRequest(req)) this.replicator._markProcessed(req.block.index)
      this.dataProcessing--
    }

    this.replicator._ondata(this, req, data)

    if (this._shouldUpdateCanUpgrade() === true) {
      this._updateCanUpgradeAndSync()
    }
  }

  onnodata({ request, reason }) {
    const req = request > 0 ? this.replicator._inflight.get(request) : null

    if (req === null || req.peer !== this) {
      this.replicator.queueUpdateAll()
      return
    }

    this._onrequestroundtrip(req)
    this.replicator._onnodata(this, req, reason)
  }

  _onrequestroundtrip(req) {
    if (req.priority === PRIORITY.CANCELLED) return
    // to avoid re-entry we also just mark it as cancelled
    req.priority = PRIORITY.CANCELLED

    this.inflight--
    this.replicator._requestDone(req.id, true)
    if (this.roundtripQueue === null) return
    const flushed = this.roundtripQueue.flush(req.rt)
    if (flushed === null) return
    for (const id of flushed) this.replicator._inflight.reusable(id)
  }

  onwant(range) {
    if (!this.remoteWants.add(range)) return
    this.replicator._onwant(this, range.start, range.length, range.any)
  }

  onunwant(range) {
    this.remoteWants.remove(range)
  }

  onbitfield({ start, bitfield }) {
    if (start < this._remoteContiguousLength) this._remoteContiguousLength = start // bitfield is always the truth
    this.remoteBitfield.insert(start, bitfield)
    this.missingBlocks.insert(start, bitfield)
    this._clearLocalRange(start, bitfield.byteLength * 8)
    this._update()
  }

  _clearLocalRange(start, length) {
    const bitfield = this.core.skipBitfield === null ? this.core.bitfield : this.core.skipBitfield

    if (length === 1) {
      this.missingBlocks.set(start, this._remoteHasBlock(start) && !bitfield.get(start))
      return
    }

    const contig = Math.min(this.core.state.length, this.core.header.hints.contiguousLength)

    if (start + length < contig) {
      this.missingBlocks.setRange(start, contig, false)
      return
    }

    const rem = start & 32767
    if (rem > 0) {
      start -= rem
      length += rem
    }

    const end = start + Math.min(length, this.core.state.length)
    while (start < end) {
      const local = bitfield.getBitfield(start)

      if (local && local.bitfield) {
        this.missingBlocks.clear(start, local.bitfield)
      }

      start += 32768
    }
  }

  _resetMissingBlock(index) {
    const bitfield = this.core.skipBitfield === null ? this.core.bitfield : this.core.skipBitfield
    this.missingBlocks.set(index, this._remoteHasBlock(index) && !bitfield.get(index))
  }

  _unclearLocalRange(start, length) {
    if (length === 1) {
      this._resetMissingBlock(start)
      return
    }

    const rem = start & (RemoteBitfield.BITS_PER_SEGMENT - 1)
    if (rem > 0) {
      start -= rem
      length += rem
    }

    const fixedStart = start

    const end = start + Math.min(length, this.remoteLength)
    while (start < end) {
      const remote = this.remoteBitfield.getBitfield(start)
      if (remote && remote.bitfield) {
        this.missingBlocks.insert(start, remote.bitfield)
      }

      start += RemoteBitfield.BITS_PER_SEGMENT
    }

    this._clearLocalRange(fixedStart, length)
  }

  async onrange({ drop, start, length }) {
    const has = drop === false

    if (drop === true && start < this._remoteContiguousLength) {
      this._remoteContiguousLength = start
    }

    if (start === 0 && drop === false) {
      if (length > this._remoteContiguousLength) {
        this._remoteContiguousLength = length
        if (
          this.remoteFork === this.core.state.fork &&
          length > this.core.header.hints.remoteContiguousLength
        ) {
          this.core.updateRemoteContiguousLength(length)
        }
      }
    } else if (length === 1) {
      const bitfield = this.core.skipBitfield === null ? this.core.bitfield : this.core.skipBitfield
      this.remoteBitfield.set(start, has)
      this.missingBlocks.set(start, has && !bitfield.get(start))
    } else {
      const rangeStart = this.remoteBitfield.findFirst(!has, start)
      const rangeEnd = length + start

      if (rangeStart !== -1 && rangeStart < rangeEnd) {
        this.remoteBitfield.setRange(rangeStart, rangeEnd, has)
        this.missingBlocks.setRange(rangeStart, rangeEnd, has)
        if (has) this._clearLocalRange(rangeStart, rangeEnd - rangeStart)
      }
    }

    if (this.core.hintsChanged) await this.core.flushHints()
    if (drop === false) this._update()

    this.core.emitRemoteContiguousLength()
  }

  onreorghint() {
    // TODO
  }

  _update() {
    // TODO: if this is in a batch or similar it would be better to defer it
    // we could do that with nextTick/microtick mb? (combined with a property on the session to signal read buffer mb)
    this.replicator.updatePeer(this)
  }

  async _onconflict() {
    this.protomux.cork()
    if (this.remoteLength > 0 && this.core.state.fork === this.remoteFork) {
      await this.onrequest({
        id: 0,
        fork: this.core.state.fork,
        block: null,
        hash: null,
        seek: null,
        upgrade: {
          start: 0,
          length: Math.min(this.core.state.length, this.remoteLength)
        }
      })
    }
    this.channel.close()
    this.protomux.uncork()
  }

  _makeRequest(needsUpgrade, priority, minLength) {
    if (needsUpgrade === true && this.replicator._shouldUpgrade(this) === false) {
      return null
    }

    // ensure that the remote has signalled they have the length we request
    if (this.remoteLength < minLength) {
      return null
    }

    if (needsUpgrade === false && this.replicator._autoUpgrade(this) === true) {
      needsUpgrade = true
    }

    return {
      peer: this,
      rt: this.roundtripQueue === null ? 0 : this.roundtripQueue.tick,
      id: 0,
      fork: this.remoteFork,
      block: null,
      hash: null,
      seek: null,
      upgrade:
        needsUpgrade === false
          ? null
          : { start: this.core.state.length, length: this.remoteLength - this.core.state.length },
      // remote manifest check can be removed eventually...
      manifest: this.core.header.manifest === null && this.remoteHasManifest === true,
      priority,
      timestamp: Date.now(),
      elapsed: 0
    }
  }

  _requestManifest() {
    const req = this._makeRequest(false, 0, 0)
    if (req === null) return

    this._send(req)
  }

  _includeLastBlock() {
    if (this.replicator._alwaysLatestBlock === 0) return null

    const index = this.remoteLength - 1

    // only valid if its an OOB get
    if (index < this.core.state.length) return null

    // do the normal checks
    if (!this._remoteHasBlock(index)) return null
    if (!this._canRequest(index, false)) return null

    // atm we only ever do one upgrade request in parallel, if that changes
    // then we should add some check here for inflights to avoid over requesting
    const b = this.replicator._blocks.add(index, PRIORITY.NORMAL, false)
    return b
  }

  _requestUpgrade(u) {
    if (this.replicator.pushOnly) return false

    const req = this._makeRequest(true, 0, 0)
    if (req === null) return false

    const b = this._includeLastBlock()

    if (b) this._sendBlockRequest(req, b)
    else this._send(req)

    return true
  }

  _requestSeek(s) {
    // if replicator is updating the seeks etc, bail and wait for it to drain
    if (this.replicator._updatesPending > 0) return false
    if (this.replicator.pushOnly) return false

    const { length, fork } = this.core.state

    if (fork !== this.remoteFork) return false

    if (s.seeker.start >= length) {
      const req = this._makeRequest(true, 0, 0)

      // We need an upgrade for the seek, if non can be provided, skip
      if (req === null) return false

      req.seek = this.remoteSupportsSeeks
        ? { bytes: s.seeker.bytes, padding: s.seeker.padding }
        : null

      s.inflight.push(req)
      this._send(req)

      return true
    }

    const len = s.seeker.end - s.seeker.start
    const off = s.seeker.start + Math.floor(Math.random() * len)

    for (let i = 0; i < len; i++) {
      let index = off + i
      if (index > s.seeker.end) index -= len

      if (this._remoteHasBlock(index) === false) continue
      if (this.core.bitfield.get(index) === true) continue
      if (!this._canRequest(index, false)) continue

      // Check if this block is currently inflight - if so pick another
      const b = this.replicator._blocks.get(index)
      if (b !== null && b.inflight.length > 0) continue

      // Block is not inflight, but we only want the hash, check if that is inflight
      const h = this.replicator._hashes.add(index, PRIORITY.NORMAL, false)
      if (h.inflight.length > 0) continue

      const req = this._makeRequest(false, h.priority, index + 1)
      if (req === null) continue

      const nodes = flatTree.depth(s.seeker.start + s.seeker.end - 1)

      req.hash = { index: 2 * index, nodes }
      req.seek = this.remoteSupportsSeeks
        ? { bytes: s.seeker.bytes, padding: s.seeker.padding }
        : null

      s.inflight.push(req)
      h.inflight.push(req)
      this._send(req)

      return true
    }

    this._maybeWantAnyRange(s.seeker.start, len, s)
    return false
  }

  _canRequest(index, force) {
    if (!(index >= 0)) throw ASSERTION('bad index to _canRequest: ' + index)

    if (!force && this.replicator.pushOnly) {
      return false
    }

    if (this.remoteLength >= this.core.state.length) {
      return true
    }

    if (index < this.lastUpgradableLength && this.lastUpgradableFork === this.core.state.fork) {
      return true
    }

    if (this.canUpgrade && this.syncsProcessing === 0) {
      return true
    }

    return false
  }

  _remoteHasBlock(index) {
    return index < this._remoteContiguousLength || this.remoteBitfield.get(index) === true
  }

  _sendBlockRequest(req, b) {
    if (this.core._repairMode) return

    req.block = { index: b.index, nodes: 0 }
    this.replicator._markInflight(b.index)

    b.inflight.push(req)
    this.replicator.hotswaps.add(b)
    this._send(req)
  }

  _requestBlock(b) {
    const { length, fork } = this.core.state

    if (this._remoteHasBlock(b.index) === false || fork !== this.remoteFork) {
      if (!this.core.bitfield.get(b.index)) this._maybeWant(b.index, b)
      return false
    }

    if (!this._canRequest(b.index, b.force)) return false

    const req = this._makeRequest(b.index >= length, b.priority, b.index + 1)
    if (req === null) return false

    this._sendBlockRequest(req, b)

    return true
  }

  _maybeWant(index, handle) {
    if (index < this.remoteContiguousLength) return

    const res = this.wants.add(index, handle)
    if (!res) return

    const batch = res.want && res.unwant
    if (batch) this.protomux.cork()

    if (res.unwant) {
      this.wireUnwant.send(res.unwant)
      incrementTx(this.stats.wireUnwant, this.replicator.stats.wireUnwant)
    }
    if (res.want) {
      this.wireWant.send(res.want)
      incrementTx(this.stats.wireWant, this.replicator.stats.wireWant)
    }

    if (batch) this.protomux.uncork()
  }

  _maybeWantAnyRange(start, length, handle) {
    if (handle.wants) {
      for (const w of handle.wants) {
        if ((w.start !== start || w.length !== length) && w.any) {
          const req = this.wants.removeAnyRange(w.start, w.length, handle)
          if (req) this.wireUnwant.send(req)
        }
      }
    }

    if (start + length <= this.remoteContiguousLength) return

    const req = this.wants.addAnyRange(start, length, handle)
    if (req) this.wireWant.send(req)
  }

  _requestRangeBlock(index, length) {
    if (this.core.bitfield.get(index) === true || !this._canRequest(index, false)) return false

    const b = this.replicator._blocks.add(index, PRIORITY.NORMAL, false)
    if (b.inflight.length > 0) {
      this.missingBlocks.set(index, false) // in case we missed some states just set them ondemand, nbd
      return false
    }

    const req = this._makeRequest(index >= length, b.priority, index + 1)

    // If the request cannot be satisfied, dealloc the block request if no one is subscribed to it
    if (req === null) {
      b.gc()
      return false
    }

    this._sendBlockRequest(req, b)

    // Don't think this will ever happen, as the pending queue is drained before the range queue
    // but doesn't hurt to check this explicitly here also.
    if (b.queued) b.queued = false
    return true
  }

  _findNext(i) {
    if (i < this._remoteContiguousLength) {
      if (this.core.skipBitfield === null) this.replicator._openSkipBitfield()
      i = this.core.skipBitfield.findFirst(false, i)
      if (i < this._remoteContiguousLength && i > -1) return i
      i = this._remoteContiguousLength
    }

    return this.missingBlocks.findFirst(true, i)
  }

  _addRangeBatch(r, offset, end) {
    const { WANT_BATCH } = w
    while (offset < end) {
      const next = this.core.bitfield.findFirst(false, offset)
      if (next === -1 || next >= end) return false

      const b = (next - (next & (WANT_BATCH - 1))) / WANT_BATCH

      if (r.addBatch(b)) return true

      offset = (b + 1) * WANT_BATCH
    }

    return false
  }

  _populateRangeBatches(r) {
    const { WANT_BATCH } = w
    for (let i = r.batches.length - 1; i >= 0; i--) {
      const b = r.batches[i]
      const minStart = b.batch * WANT_BATCH
      const maxEnd = minStart + WANT_BATCH

      const start = Math.max(r.start, minStart)
      const end = Math.min(r.end === -1 ? maxEnd : r.end, maxEnd)

      if (start < end && this.core.bitfield.hasUnset(start, end - start)) continue

      r.removeBatch(b)
    }

    while (r.batches.length < 3) {
      const end = r.end === -1 ? this.core.state.length : r.end
      if (end <= r.start) return

      const len = end - r.start
      const off = r.start + (r.linear ? 0 : Math.floor(Math.random() * len))

      if (!this._addRangeBatch(r, off, end) && !this._addRangeBatch(r, r.start, end)) break
    }
  }

  _requestRangeBatch(start, end, length) {
    let tries = this.inflight

    do {
      start = this._findNext(start)
      if (start === -1 || start >= end) break

      if (this._requestRangeBlock(start, length)) return true
      start++
    } while (tries-- > 0)

    return false
  }

  _getValidEnd(maxEnd) {
    // if we can upgrade the remote, or the remote is ahead, then all the remotes blocks are valid
    // otherwise truncate to the last length the remote has acked for us
    const maxLocalLength =
      this.canUpgrade || this.remoteLength >= this.core.state.length
        ? this.core.state.length
        : this.core.state.fork === this.lastUpgradableFork
          ? Math.min(this.lastUpgradableLength, this.core.state.length)
          : 0

    return Math.min(
      maxLocalLength,
      Math.min(maxEnd === -1 ? this.remoteLength : maxEnd, this.remoteLength)
    )
  }

  _requestRange(r) {
    const { WANT_BATCH } = w
    if (this.syncsProcessing > 0) return false

    const { length, fork } = this.core.state

    if (r.blocks) {
      for (let i = r.start; i < r.end; i++) {
        const index = r.blocks[i]
        const has = index < this._remoteContiguousLength || this.missingBlocks.get(index) === true
        if (has === true && this._requestRangeBlock(index, length)) return true
        this._maybeWant(index, r)
      }

      return false
    }

    this._populateRangeBatches(r)

    const end = this._getValidEnd(r.end)

    if (end <= r.start || fork !== this.remoteFork) return false

    for (let i = 0; i < r.batches.length; i++) {
      const b = r.batches[i]

      const batchStart = Math.max(b.batch * WANT_BATCH, r.start)
      const batchEnd = Math.min((b.batch + 1) * WANT_BATCH, end)
      const len = batchEnd - batchStart
      const off = batchStart + (r.linear ? 0 : Math.floor(Math.random() * len))

      if (
        this._requestRangeBatch(off, end, length) ||
        this._requestRangeBatch(batchStart, off, length)
      ) {
        return true
      }

      this._maybeWant(batchStart, b)
    }

    // Here we should consider making an OOB request (ie if the remote says they have a newer block)
    // but the upgrade code already does that, so no big deal for now

    return false
  }

  _requestForkProof(f) {
    if (!this.remoteLength) return
    if (this.replicator.pushOnly) return

    const req = this._makeRequest(false, 0, 0)
    if (req === null) return

    req.upgrade = { start: 0, length: this.remoteLength }
    req.manifest = !this.core.header.manifest

    f.inflight.push(req)
    this._send(req)
  }

  _requestForkRange(f) {
    if (f.fork !== this.remoteFork || f.batch.want === null) return false
    if (this.replicator.pushOnly) return false

    const end = Math.min(f.batch.want.end, this.remoteLength)
    if (end < f.batch.want.start) return false

    const len = end - f.batch.want.start
    const off = f.batch.want.start + Math.floor(Math.random() * len)

    for (let i = 0; i < len; i++) {
      let index = off + i
      if (index >= end) index -= len

      if (this._remoteHasBlock(index) === false) continue

      const req = this._makeRequest(false, 0, 0)
      if (req === null) return false

      req.hash = { index: 2 * index, nodes: f.batch.want.nodes }

      f.inflight.push(req)
      this._send(req)

      return true
    }

    this._maybeWantAnyRange(f.batch.want.start, len, f)
    return false
  }

  isActive() {
    if (this.paused || this.removed || this.core.header.frozen) return false
    return true
  }

  async _send(req) {
    const fork = this.core.state.fork

    this.inflight++
    this.replicator._inflight.add(req)

    if (req.upgrade !== null && req.fork === fork) {
      const u = this.replicator._addUpgrade()
      u.inflight.push(req)
    }

    try {
      if (req.block !== null && req.fork === fork) {
        req.block.nodes = await MerkleTree.missingNodes(
          this.core.state,
          2 * req.block.index,
          this.core.state.length
        )
        if (req.priority === PRIORITY.CANCELLED) return
      }
      if (req.hash !== null && req.fork === fork && req.hash.nodes === 0) {
        req.hash.nodes = await MerkleTree.missingNodes(
          this.core.state,
          req.hash.index,
          this.core.state.length
        )
        if (req.priority === PRIORITY.CANCELLED) return

        // nodes === 0, we already have it, bail
        if (req.hash.nodes === 0 && (req.hash.index & 1) === 0) {
          this.inflight--
          this.replicator._resolveHashLocally(this, req)
          return
        }
      }
    } catch (err) {
      this.stream.destroy(err)
      return
    }

    this.wireRequest.send(req)
    incrementTx(this.stats.wireRequest, this.replicator.stats.wireRequest)
  }
}

module.exports = class Replicator {
  static Peer = Peer // hack to be able to access Peer from outside this module

  constructor(
    core,
    {
      notDownloadingLinger = NOT_DOWNLOADING_SLACK,
      eagerUpgrade = true,
      allowFork = true,
      allowPush = false,
      alwaysLatestBlock = false,
      inflightRange = null
    } = {}
  ) {
    this.core = core
    this.eagerUpgrade = eagerUpgrade
    this.allowFork = allowFork
    this.allowPush = allowPush
    this.ondownloading = null // optional external hook for monitoring downloading status
    this.peers = []
    this.findingPeers = 0 // updatable from the outside
    this.destroyed = false
    this.downloading = false
    this.pushOnly = false
    this.activeSessions = 0

    this.hotswaps = new HotswapQueue()
    this.inflightRange = inflightRange || DEFAULT_MAX_INFLIGHT

    // Note: nodata and unwant not currently tracked
    // tx = transmitted, rx = received
    this.stats = {
      wireSync: { tx: 0, rx: 0 },
      wireRequest: { tx: 0, rx: 0 },
      wireCancel: { tx: 0, rx: 0 },
      wireData: { tx: 0, rx: 0 },
      wireWant: { tx: 0, rx: 0 },
      wireUnwant: { tx: 0, rx: 0 },
      wireBitfield: { tx: 0, rx: 0 },
      wireRange: { tx: 0, rx: 0 },
      wireExtension: { tx: 0, rx: 0 },
      hotswaps: 0,
      invalidData: 0,
      invalidRequests: 0,
      backoffs: 0,
      notAvailableBackoffs: 0
    }

    this._attached = new Set()
    this._inflight = new InflightTracker()
    this._blocks = new BlockTracker(this)
    this._hashes = new BlockTracker(this)

    this._alwaysLatestBlock = alwaysLatestBlock ? 1 : 0
    this._queued = []

    this._seeks = []
    this._upgrade = null
    this._reorgs = []
    this._ranges = []

    this._rxLock = new Mutex()
    this._txLock = new Mutex()

    this._hadPeers = false
    this._active = 0
    this._ifAvailable = 0
    this._updatesPending = 0
    this._applyingReorg = null
    this._manifestPeer = null
    this._notDownloadingLinger = notDownloadingLinger
    this._notDownloadingTimer = null

    this._updateAllBump = null
    this._updateAllBound = this.updateAll.bind(this)

    const self = this
    this._onstreamclose = onstreamclose

    function onstreamclose() {
      self.detachFrom(this.userData)
    }
  }

  setInflightRange(min, max) {
    const def = this.inflightRange
    this.inflightRange = [min, max]
    for (const peer of this.peers) {
      if (peer.inflightRange !== def) continue
      peer.inflightRange = this.inflightRange
    }
  }

  updateActivity(inc, session) {
    this.activeSessions += inc
    this.setDownloading(this.activeSessions !== 0, session)
  }

  isDownloading() {
    return this.downloading || !this._inflight.idle
  }

  async push(index) {
    const all = []
    for (const peer of this.peers) {
      all.push(peer.push(index))
    }
    await Promise.all(all)
  }

  setAllowPush(allowPush) {
    if (allowPush === this.allowPush) return
    this.allowPush = allowPush
    for (const peer of this.peers) peer.sendSync()
  }

  isAllowingPush() {
    if (!this.allowPush) return false
    if (this._notDownloadingTimer) return false
    return this.downloading
  }

  setPushOnly(pushOnly) {
    if (pushOnly === this.pushOnly) return
    this.pushOnly = pushOnly
  }

  setDownloading(downloading) {
    const allowPush = this.isAllowingPush()
    const linger = this._notDownloadingLinger

    if (this._notDownloadingTimer) {
      clearTimeout(this._notDownloadingTimer)
      this._notDownloadingTimer = null
    }

    if (this.destroyed) return

    if (downloading || linger === 0) {
      if (!this._setDownloadingNow(downloading)) this.signalAllowPush(allowPush)
      return
    }

    this._notDownloadingTimer = setTimeout(setNotDownloadingLater, linger, this)
    if (this._notDownloadingTimer.unref) this._notDownloadingTimer.unref()
    this.signalAllowPush(allowPush)
  }

  signalAllowPush(allowPush) {
    if (allowPush === this.isAllowingPush()) return
    for (const peer of this.peers) peer.signalUpgrade()
  }

  _setDownloadingNow(downloading) {
    this._notDownloadingTimer = null

    if (this.downloading === downloading) return false
    this.downloading = downloading

    if (!downloading && this.isDownloading()) return false

    for (const peer of this.peers) peer.signalUpgrade()

    if (downloading) {
      // restart channel if needed...
      for (const protomux of this._attached) {
        if (!protomux.stream.handshakeHash) continue
        if (protomux.opened({ protocol: 'hypercore/alpha', id: this.core.discoveryKey })) continue
        this._makePeer(protomux, true)
      }
    } else {
      for (const peer of this.peers) peer.closeIfIdle()
    }

    if (this.ondownloading !== null && downloading) this.ondownloading()
    return true
  }

  cork() {
    for (const peer of this.peers) peer.protomux.cork()
  }

  uncork() {
    for (const peer of this.peers) peer.protomux.uncork()
  }

  // Called externally when a range of new blocks has been processed/removed
  onhave(start, length, drop = false) {
    for (const peer of this.peers) peer.broadcastRange(start, length, drop)
  }

  // Called externally when a truncation upgrade has been processed
  ontruncate(newLength, truncated) {
    const notify = []

    for (const blk of this._blocks) {
      if (blk.index < newLength) continue
      notify.push(blk)
    }

    for (const blk of notify) {
      for (const r of blk.refs) {
        if (r.snapshot === false) continue
        blk.detach(r, SNAPSHOT_NOT_AVAILABLE())
      }
    }

    for (const peer of this.peers) {
      peer.fullyDownloadedSignaled = Math.min(newLength, peer.fullyDownloadedSignaled)
      peer._unclearLocalRange(newLength, truncated)
    }
  }

  // Called externally when a upgrade has been processed
  onupgrade() {
    for (const peer of this.peers) peer.signalUpgrade()
    if (this._blocks.isEmpty() === false) this._resolveBlocksLocally()
    if (this._upgrade !== null) this._resolveUpgradeRequest(null)
    if (!this._blocks.isEmpty() || this._ranges.length !== 0 || this._seeks.length !== 0) {
      this._updateNonPrimary(true)
    }
  }

  // Called externally when a conflict has been detected and verified
  async onconflict() {
    const all = []
    for (const peer of this.peers) {
      all.push(peer._onconflict())
    }
    await Promise.allSettled(all)
  }

  async applyPendingReorg() {
    if (this._applyingReorg !== null) {
      await this._applyingReorg
      return true
    }

    for (let i = this._reorgs.length - 1; i >= 0; i--) {
      const f = this._reorgs[i]
      if (f.batch !== null && f.batch.finished) {
        await this._applyReorg(f)
        return true
      }
    }

    return false
  }

  addUpgrade(session) {
    if (this._upgrade !== null) {
      const ref = this._upgrade.attach(session)
      this._checkUpgradeIfAvailable()
      return ref
    }

    const ref = this._addUpgrade().attach(session)

    this.queueUpdateAll()

    return ref
  }

  addBlock(session, index, force) {
    const b = this._blocks.add(index, PRIORITY.HIGH, force)
    const ref = b.attach(session)

    this._queueBlock(b)
    this.queueUpdateAll()

    return ref
  }

  addSeek(session, seeker) {
    const s = new SeekRequest(this, this._seeks, seeker)
    const ref = s.attach(session)

    this._seeks.push(s)
    this.queueUpdateAll()

    return ref
  }

  addRange(
    session,
    { start = 0, end = -1, length = toLength(start, end), blocks = null, linear = false } = {}
  ) {
    if (blocks !== null) {
      // if using blocks, start, end just acts as frames around the blocks array
      start = 0
      end = length = blocks.length
    }

    const r = new RangeRequest(
      this,
      this._ranges,
      start,
      length === -1 ? -1 : start + length,
      linear,
      blocks
    )

    const ref = r.attach(session)

    // Trigger this to see if this is already resolved...
    // Also auto compresses the range based on local bitfield
    clampRange(this.core, r)

    if (r.end !== -1 && r.start >= r.end) {
      this._resolveRangeRequest(r)
      return ref
    }

    this.queueUpdateAll()

    return ref
  }

  cancel(ref) {
    ref.context.detach(ref, null)
  }

  static clearRequests(session, err) {
    if (session.length === 0) return
    if (session.length === 1 && session[0] === null) return

    const updated = new Set()

    while (session.length > 0) {
      const ref = session[session.length - 1]
      updated.add(ref.context.replicator)
      ref.context.detach(ref, err)
    }

    for (const replicator of updated) {
      replicator.queueUpdateAll()
    }
  }

  clearRequests(session, err = null) {
    let cleared = false
    while (session.length > 0) {
      const ref = session[session.length - 1]
      ref.context.detach(ref, err)
      cleared = true
    }

    if (cleared) this.queueUpdateAll()
  }

  _matchingRequest(req, data) {
    if (this.allowPush) {
      return true
    }
    if (data.block !== null && (req.block === null || req.block.index !== data.block.index)) {
      return false
    }
    if (data.hash !== null && (req.hash === null || req.hash.index !== data.hash.index)) {
      return false
    }
    if (data.seek !== null && (req.seek === null || req.seek.bytes !== data.seek.bytes)) {
      return false
    }
    if (data.upgrade !== null && req.upgrade === null) {
      return false
    }
    return req.fork === data.fork
  }

  _addUpgradeMaybe() {
    return this.eagerUpgrade === true ? this._addUpgrade() : this._upgrade
  }

  // TODO: this function is OVER called atm, at each updatePeer/updateAll
  // instead its more efficient to only call it when the conditions in here change - ie on sync/add/remove peer
  // Do this when we have more tests.
  _checkUpgradeIfAvailable() {
    if (this._ifAvailable > 0 && this.peers.length < MAX_PEERS_UPGRADE) return
    if (this._upgrade === null || this._upgrade.refs.length === 0) return
    if (this._hadPeers === false && this.findingPeers > 0) return

    const maxPeers = Math.min(this.peers.length, MAX_PEERS_UPGRADE)

    // check if a peer can upgrade us

    for (let i = 0; i < maxPeers; i++) {
      const peer = this.peers[i]

      if (peer.remoteSynced === false) return

      if (this.core.state.length === 0 && peer.remoteLength > 0) return

      if (peer.remoteLength <= this._upgrade.length || peer.remoteFork !== this._upgrade.fork) {
        continue
      }

      if (peer.syncsProcessing > 0) return

      if (peer.lengthAcked !== this.core.state.length && peer.remoteFork === this.core.state.fork) {
        return
      }

      if (peer.remoteCanUpgrade === true) return
    }

    // check if reorgs in progress...

    if (this._applyingReorg !== null) return

    // TODO: we prob should NOT wait for inflight reorgs here, seems better to just resolve the upgrade
    // and then apply the reorg on the next call in case it's slow - needs some testing in practice

    for (let i = 0; i < this._reorgs.length; i++) {
      const r = this._reorgs[i]
      if (r.inflight.length > 0) return
    }

    // if something is inflight, wait for that first
    if (this._upgrade.inflight.length > 0) return

    // nothing to do, indicate no update avail

    const u = this._upgrade
    this._upgrade = null
    u.resolve(false)
  }

  _addUpgrade() {
    if (this._upgrade !== null) return this._upgrade

    // TODO: needs a reorg: true/false flag to indicate if the user requested a reorg
    this._upgrade = new UpgradeRequest(this, this.core.state.fork, this.core.state.length)

    return this._upgrade
  }

  _addReorg(fork, peer) {
    if (this.allowFork === false) return null

    // TODO: eager gc old reorgs from the same peer
    // not super important because they'll get gc'ed when the request finishes
    // but just spam the remote can do ...

    for (const f of this._reorgs) {
      if (f.fork > fork && f.batch !== null) return null
      if (f.fork === fork) return f
    }

    const f = new ForkRequest(this, fork)

    this._reorgs.push(f)

    // maintain sorted by fork
    let i = this._reorgs.length - 1
    while (i > 0 && this._reorgs[i - 1].fork > fork) {
      this._reorgs[i] = this._reorgs[i - 1]
      this._reorgs[--i] = f
    }

    return f
  }

  _shouldUpgrade(peer) {
    if (this._upgrade !== null && this._upgrade.inflight.length > 0) return false
    return (
      peer.remoteCanUpgrade === true &&
      peer.remoteLength > this.core.state.length &&
      peer.lengthAcked === this.core.state.length
    )
  }

  _autoUpgrade(peer) {
    return (
      this._upgrade !== null &&
      peer.remoteFork === this.core.state.fork &&
      this._shouldUpgrade(peer)
    )
  }

  _addPeer(peer) {
    this._hadPeers = true
    this.peers.push(peer)
    this.updatePeer(peer)
    this._onpeerupdate(true, peer)
  }

  _requestDone(id, roundtrip) {
    this._inflight.remove(id, roundtrip)
    if (this.isDownloading() === true) return
    for (const peer of this.peers) peer.signalUpgrade()
  }

  _removePeer(peer) {
    this.peers.splice(this.peers.indexOf(peer), 1)
    peer.wants.destroy()

    if (this._manifestPeer === peer) this._manifestPeer = null

    let inflight = false
    for (const req of this._inflight) {
      if (req.peer !== peer) continue
      inflight = true
      this._inflight.remove(req.id, true)
      this._clearRequest(peer, req)
    }

    this._onpeerupdate(false, peer)
    if (inflight) {
      this.queueUpdateAll()
    } else {
      this._checkUpgradeIfAvailable()
    }
  }

  _queueBlock(b) {
    if (b.inflight.length > 0 || b.queued === true) return
    b.queued = true
    this._queued.push(b)
  }

  _resolveHashLocally(peer, req) {
    this._requestDone(req.id, false)
    this._resolveBlockRequest(this._hashes, req.hash.index / 2, null, req)
    this.updatePeer(peer)
  }

  // Runs in the background - not allowed to throw
  async _resolveBlocksLocally() {
    // TODO: check if fork compat etc. Requires that we pass down truncation info

    const clear = []
    const blocks = []

    const reader = this.core.storage.read()
    for (const b of this._blocks) {
      if (this.core.bitfield.get(b.index) === false) continue
      blocks.push(this._resolveLocalBlock(b, reader, clear))
    }
    reader.tryFlush()

    await Promise.all(blocks)

    if (!clear.length) return

    // Currently the block tracker does not support deletes during iteration, so we make
    // sure to clear them afterwards.
    for (const b of clear) {
      this._blocks.remove(b.index)
      removeHotswap(b)
    }
  }

  async _resolveLocalBlock(b, reader, resolved) {
    try {
      b.resolve(await reader.getBlock(b.index))
    } catch (err) {
      b.reject(err)
      return
    }

    resolved.push(b)
  }

  _resolveBlockRequest(tracker, index, value, req) {
    const b = tracker.remove(index)
    if (b === null) return false

    removeInflight(b.inflight, req)
    removeHotswap(b)
    b.queued = false

    b.resolve(value)

    if (b.inflight.length > 0) {
      // if anything is still inflight, cancel it
      for (let i = b.inflight.length - 1; i >= 0; i--) {
        const req = b.inflight[i]
        req.peer._cancelRequest(req)
      }
    }

    return true
  }

  _resolveUpgradeRequest(req) {
    if (req !== null) removeInflight(this._upgrade.inflight, req)

    if (
      this.core.state.length === this._upgrade.length &&
      this.core.state.fork === this._upgrade.fork
    ) {
      return false
    }

    const u = this._upgrade
    this._upgrade = null
    u.resolve(true)

    return true
  }

  _resolveRangeRequest(req) {
    req.resolve(true)
    req.gc()
  }

  _clearInflightBlock(tracker, req) {
    const isBlock = tracker === this._blocks
    const index = isBlock === true ? req.block.index : req.hash.index / 2
    const b = tracker.get(index)

    if (b === null || removeInflight(b.inflight, req) === false) return

    if (removeHotswap(b) === true && b.inflight.length > 0) {
      this.hotswaps.add(b)
    }

    if (b.refs.length > 0 && isBlock === true) {
      this._queueBlock(b)
      return
    }

    b.gc()
  }

  _clearInflightUpgrade(req) {
    if (this._upgrade === null || removeInflight(this._upgrade.inflight, req) === false) return
    this._upgrade.gc()
  }

  _clearInflightSeeks(req) {
    for (const s of this._seeks) {
      if (removeInflight(s.inflight, req) === false) continue
      s.gc()
    }
  }

  _clearInflightReorgs(req) {
    for (const r of this._reorgs) {
      removeInflight(r.inflight, req)
    }
  }

  _clearOldReorgs(fork) {
    for (let i = 0; i < this._reorgs.length; i++) {
      const f = this._reorgs[i]
      if (f.fork >= fork) continue
      if (i === this._reorgs.length - 1) this._reorgs.pop()
      else this._reorgs[i] = this._reorgs.pop()
      i--
    }
  }

  // "slow" updates here - async but not allowed to ever throw
  async _updateNonPrimary(updateAll) {
    // Check if running, if so skip it and the running one will issue another update for us (debounce)
    while (++this._updatesPending === 1) {
      let len = Math.min(MAX_RANGES, this._ranges.length)

      for (let i = 0; i < len; i++) {
        const r = this._ranges[i]

        clampRange(this.core, r)

        if (r.end !== -1 && r.start >= r.end) {
          this._resolveRangeRequest(r)
          i--
          if (len > this._ranges.length) len--
          if (this._ranges.length === MAX_RANGES) updateAll = true
        }
      }

      for (let i = 0; i < this._seeks.length; i++) {
        const s = this._seeks[i]

        let err = null
        let res = null

        try {
          res = await s.seeker.update()
        } catch (error) {
          err = error
        }

        if (!res && !err) continue

        if (i < this._seeks.length - 1) this._seeks[i] = this._seeks.pop()
        else this._seeks.pop()

        i--

        if (err) s.reject(err)
        else s.resolve(res)
      }

      // No additional updates scheduled - break
      if (--this._updatesPending === 0) break
      // Debounce the additional updates - continue
      this._updatesPending = 0
    }

    if (this._inflight.idle || updateAll) this.queueUpdateAll()
  }

  _clearRequest(peer, req) {
    if (req.block !== null) {
      this._clearInflightBlock(this._blocks, req)
      this._unmarkInflight(req.block.index)
    }

    if (req.hash !== null) {
      this._clearInflightBlock(this._hashes, req)
    }

    if (req.upgrade !== null && this._upgrade !== null) {
      this._clearInflightUpgrade(req)
    }

    if (this._seeks.length > 0) {
      this._clearInflightSeeks(req)
    }

    if (this._reorgs.length > 0) {
      this._clearInflightReorgs(req)
    }
  }

  _onnodata(peer, req, reason) {
    if (reason === NOT_AVAILABLE) {
      peer.stats.notAvailableBackoffs++
      this.stats.notAvailableBackoffs++

      if (peer.stats.notAvailableBackoffs >= MAX_BACKOFFS) {
        peer.paused = true
      }
    }

    if (reason === INVALID_REQUEST) {
      peer.stats.backoffs++
      this.stats.backoffs++

      if (peer.stats.backoffs >= MAX_BACKOFFS) {
        peer.paused = true
      }
    }

    if (req) {
      this._clearRequest(peer, req)
    }

    this.queueUpdateAll()
  }

  _openSkipBitfield() {
    // technically the skip bitfield gets bits cleared if .clear() is called
    // also which might be in inflight also, but that just results in that section being overcalled shortly
    // worst case, so ok for now

    const bitfield = this.core.openSkipBitfield()

    for (const req of this._inflight) {
      if (req.block) bitfield.set(req.block.index, true) // skip
    }
  }

  _markProcessing(index) {
    const b = this._blocks.get(index)
    if (b) {
      b.processing = true
      return
    }

    const h = this._hashes.get(index)
    if (h) h.processing = true
  }

  _markProcessed(index) {
    const b = this._blocks.get(index)
    if (b) return b.processed()

    const h = this._hashes.get(index)
    if (h) h.processed()
  }

  _markInflight(index) {
    if (this.core.skipBitfield !== null) this.core.skipBitfield.set(index, true)
    for (const peer of this.peers) peer._markInflight(index)
  }

  _unmarkInflight(index) {
    if (this.core.skipBitfield !== null) {
      this.core.skipBitfield.set(index, this.core.bitfield.get(index))
    }
    for (const peer of this.peers) peer._resetMissingBlock(index)
  }

  _ondata(peer, req, data) {
    if (req) {
      req.elapsed = Date.now() - req.timestamp
    }

    if (data.block !== null) {
      this._resolveBlockRequest(this._blocks, data.block.index, data.block.value, req)
      this._ondownload(data.block.index, data.block.value.byteLength, peer, req)
    }

    if (data.hash !== null && (data.hash.index & 1) === 0) {
      this._resolveBlockRequest(this._hashes, data.hash.index / 2, null, req)
    }

    if (this._upgrade !== null) {
      this._resolveUpgradeRequest(req)
    }

    if (this._seeks.length > 0) {
      this._clearInflightSeeks(req)
    }

    if (this._reorgs.length > 0) {
      this._clearInflightReorgs(req)
    }

    if (this._manifestPeer === peer && this.core.header.manifest !== null) {
      this._manifestPeer = null
    }

    if (this._seeks.length > 0 || this._ranges.length > 0) {
      this._updateNonPrimary(this._seeks.length > 0)
    }

    this.updatePeer(peer)
  }

  _onwant(peer, start, length, any) {
    if (!peer.isActive()) return

    const contig = Math.min(this.core.state.length, this.core.header.hints.contiguousLength)

    if (start + length < contig || this.core.state.length === contig || (any && start < contig)) {
      peer.wireRange.send({
        drop: false,
        start: 0,
        length: contig
      })
      incrementTx(peer.stats.wireRange, this.stats.wireRange)
      return
    }

    length = Math.min(length, this.core.state.length - start)

    if (any) {
      const bit = this.core.bitfield.firstSet(start)
      if (bit > -1 && bit < start + length) {
        peer.wireRange.send({
          drop: false,
          start: bit,
          length: 1
        })
      }
      return
    }

    for (const msg of this.core.bitfield.want(start, length)) {
      peer.wireBitfield.send(msg)
      incrementTx(peer.stats.wireBitfield, this.stats.wireBitfield)
    }
  }

  async _onreorgdata(peer, req, data) {
    const newBatch = data.upgrade && (await this.core.verifyReorg(data))
    const f = this._addReorg(data.fork, peer)

    if (f === null) {
      this.queueUpdateAll()
      return
    }

    removeInflight(f.inflight, req)

    if (f.batch) {
      await f.batch.update(data)
    } else if (data.upgrade) {
      f.batch = newBatch

      // Remove "older" reorgs in progress as we just verified this one.
      this._clearOldReorgs(f.fork)
    }

    if (f.batch && f.batch.finished) {
      if (this._addUpgradeMaybe() !== null) {
        await this._applyReorg(f)
      }
    }

    this.queueUpdateAll()
  }

  // Never throws, allowed to run in the background
  async _applyReorg(f) {
    // TODO: more optimal here to check if potentially a better reorg
    // is available, ie higher fork, and request that one first.
    // This will request that one after this finishes, which is fine, but we
    // should investigate the complexity in going the other way

    const u = this._upgrade
    const old = this._reorgs

    this._reorgs = [] // clear all as the nodes are against the old tree - easier
    this._applyingReorg = this.core.reorg(f.batch, null) // TODO: null should be the first/last peer?

    try {
      await this._applyingReorg
    } catch (err) {
      this._upgrade = null
      u.reject(err)
    }

    this._applyingReorg = null

    if (this._upgrade !== null) {
      this._resolveUpgradeRequest(null)
    }

    for (const peer of this.peers) this._updateFork(peer)

    // TODO: all the remaining is a tmp workaround until we have a flag/way for ANY_FORK
    for (const r of this._ranges) {
      r.start = r.userStart
      r.end = r.userEnd
    }

    for (const f of old) f.resolve()
    f.resolve()

    this.queueUpdateAll()
  }

  _maybeUpdate() {
    return this._upgrade !== null && this._upgrade.inflight.length === 0
  }

  _maybeRequestManifest() {
    return this.core.header.manifest === null && this._manifestPeer === null
  }

  _updateFork(peer) {
    if (
      this._applyingReorg !== null ||
      this.allowFork === false ||
      peer.remoteFork <= this.core.state.fork
    ) {
      return false
    }

    const f = this._addReorg(peer.remoteFork, peer)

    // TODO: one per peer is better
    if (f !== null && f.batch === null && f.inflight.length === 0) {
      return peer._requestForkProof(f)
    }

    return false
  }

  _updateHotswap(peer) {
    const maxHotswaps = peer.getMaxHotswapInflight()
    if (!peer.isActive() || peer.inflight >= maxHotswaps) return

    for (const b of this.hotswaps.pick(peer)) {
      if (peer._requestBlock(b) === false) continue
      peer.stats.hotswaps++
      peer.replicator.stats.hotswaps++
      if (peer.inflight >= maxHotswaps) break
    }
  }

  _updatePeer(peer) {
    if (!peer.isActive() || peer.inflight >= peer.getMaxInflight() || !peer.remoteUploading) {
      return false
    }

    // Eagerly request the manifest even if the remote length is 0. If not 0 we'll get as part of the upgrade request...
    if (
      this._maybeRequestManifest() === true &&
      peer.remoteLength === 0 &&
      peer.remoteHasManifest === true
    ) {
      this._manifestPeer = peer
      peer._requestManifest()
    }

    for (const s of this._seeks) {
      if (s.inflight.length > 0) continue // TODO: one per peer is better
      if (peer._requestSeek(s) === true) {
        return true
      }
    }

    // Implied that any block in the queue should be requested, no matter how many inflights
    const blks = new RandomIterator(this._queued)

    for (const b of blks) {
      if (b.queued === false || peer._requestBlock(b) === true) {
        b.queued = false
        blks.dequeue()
        return true
      }
    }

    return false
  }

  _updatePeerNonPrimary(peer) {
    if (!peer.isActive() || peer.inflight >= peer.getMaxInflight() || !peer.remoteUploading) {
      return false
    }

    const ranges = new RandomIterator(this._ranges)
    let tried = 0

    for (const r of ranges) {
      if (peer._requestRange(r) === true) {
        return true
      }
      if (++tried >= MAX_RANGES) break
    }

    // Iterate from newest fork to oldest fork...
    for (let i = this._reorgs.length - 1; i >= 0; i--) {
      const f = this._reorgs[i]
      if (f.batch !== null && f.inflight.length === 0 && peer._requestForkRange(f) === true) {
        return true
      }
    }

    if (this._maybeUpdate() === true && peer._requestUpgrade(this._upgrade) === true) {
      return true
    }

    return false
  }

  updatePeer(peer) {
    // Quick shortcut to wait for flushing reorgs - not needed but less waisted requests
    if (this._applyingReorg !== null) return

    while (this._updatePeer(peer) === true);
    while (this._updatePeerNonPrimary(peer) === true);

    if (this.peers.length > 1 && this._blocks.isEmpty() === false) {
      this._updateHotswap(peer)
    }

    this._checkUpgradeIfAvailable()
  }

  updateSubset() {
    return this.updateAll(false)
  }

  updateAll(all = true) {
    // Clear queued scan if a full scan
    if (this._updateAllBump !== null && all) {
      clearTimeout(this._updateAllBump)
      this._updateAllBump = null
    }

    // Quick shortcut to wait for flushing reorgs - not needed but less waisted requests
    if (this._applyingReorg !== null) return

    const peers = new RandomIterator(this.peers)

    const limit = all ? peers.length : MIN_PEER_UPDATE_ALL
    let tried = 0
    for (const peer of peers) {
      tried++
      if (this._updatePeer(peer) === true) {
        peers.requeue()
      }
      if (tried >= limit) break
    }

    // Check if we can skip the non primary check fully
    if (this._maybeUpdate() === false && this._ranges.length === 0 && this._reorgs.length === 0) {
      this._checkUpgradeIfAvailable()
      return
    }

    tried = 0
    for (const peer of peers.restart()) {
      tried++
      if (this._updatePeerNonPrimary(peer) === true) {
        peers.requeue()
      }
      if (tried >= limit) break
    }

    this._checkUpgradeIfAvailable()
  }

  getUpdateAllDelay(peers) {
    return Math.min(3000, Math.max(100, (peers.length - MIN_PEER_UPDATE_ALL) * 5))
  }

  queueUpdateAll() {
    if (this.peers.length < MIN_PEER_UPDATE_ALL) return this.updateAll()

    // Immediately scan subset
    this.updateSubset()

    // Schedule full scan
    if (this._updateAllBump !== null) return //skip if already scheduled
    this._updateAllBump = setTimeout(this._updateAllBound, this.getUpdateAllDelay(this.peers))
  }

  onpeerdestroy() {
    if (--this._active === 0) this.core.checkIfIdle()
  }

  attached(protomux) {
    return this._attached.has(protomux)
  }

  attachTo(protomux) {
    if (this.core.closed) return

    const makePeer = this._makePeer.bind(this, protomux)

    this._attached.add(protomux)
    protomux.pair({ protocol: 'hypercore/alpha', id: this.core.discoveryKey }, makePeer)
    protomux.stream.setMaxListeners(0)
    protomux.stream.on('close', this._onstreamclose)

    this._ifAvailable++
    this._active++

    protomux.stream.opened.then((opened) => {
      this._ifAvailable--
      this._active--

      if (opened && !this.destroyed) makePeer()
      this._checkUpgradeIfAvailable()

      this.core.checkIfIdle()
    })
  }

  detachFrom(protomux) {
    if (this._attached.delete(protomux)) {
      protomux.stream.removeListener('close', this._onstreamclose)
      protomux.unpair({ protocol: 'hypercore/alpha', id: this.core.discoveryKey })
    }
  }

  idle() {
    return this.peers.length === 0 && this._active === 0
  }

  close() {
    const waiting = []

    for (const peer of this.peers) {
      waiting.push(peer.channel.fullyClosed())
    }

    this.destroy()
    return Promise.all(waiting)
  }

  destroy() {
    if (this.destroyed) return
    this.destroyed = true

    if (this._notDownloadingTimer) {
      clearTimeout(this._notDownloadingTimer)
      this._notDownloadingTimer = null
    }

    if (this._updateAllBump) {
      clearTimeout(this._updateAllBump)
      this._updateAllBump = null
    }

    while (this.peers.length) {
      const peer = this.peers[this.peers.length - 1]
      this.detachFrom(peer.protomux)
      peer.channel.close() // peer is removed from array in onclose
    }

    for (const protomux of this._attached) {
      this.detachFrom(protomux)
    }
  }

  _makePeer(protomux) {
    const replicator = this
    if (protomux.opened({ protocol: 'hypercore/alpha', id: this.core.discoveryKey })) {
      return onnochannel()
    }

    const channel = protomux.createChannel({
      userData: null,
      protocol: 'hypercore/alpha',
      aliases: ['hypercore'],
      id: this.core.discoveryKey,
      handshake: m.wire.handshake,
      messages: [
        { encoding: m.wire.sync, onmessage: onwiresync },
        { encoding: m.wire.request, onmessage: onwirerequest },
        { encoding: m.wire.cancel, onmessage: onwirecancel },
        { encoding: m.wire.data, onmessage: onwiredata },
        { encoding: m.wire.noData, onmessage: onwirenodata },
        { encoding: m.wire.want, onmessage: onwirewant },
        { encoding: m.wire.unwant, onmessage: onwireunwant },
        { encoding: m.wire.bitfield, onmessage: onwirebitfield },
        { encoding: m.wire.range, onmessage: onwirerange },
        { encoding: m.wire.extension, onmessage: onwireextension }
      ],
      onopen: onwireopen,
      onclose: onwireclose,
      ondrain: onwiredrain,
      ondestroy: onwiredestroy
    })

    if (channel === null) return onnochannel()

    const peer = new Peer(replicator, protomux, channel, this.inflightRange)
    const stream = protomux.stream

    peer.channel.open({
      seeks: true,
      capability: caps.replicate(stream.isInitiator, this.core.key, stream.handshakeHash)
    })

    return true

    function onnochannel() {
      return false
    }
  }

  _onpeerupdate(added, peer) {
    const name = added ? 'peer-add' : 'peer-remove'
    const sessions = this.core.monitors

    for (let i = sessions.length - 1; i >= 0; i--) {
      sessions[i].emit(name, peer)

      if (added) {
        for (const ext of sessions[i].extensions.values()) {
          peer.extensions.set(ext.name, ext)
        }
      }
    }
  }

  _ondownload(index, byteLength, from, req) {
    const sessions = this.core.monitors

    for (let i = sessions.length - 1; i >= 0; i--) {
      const s = sessions[i]
      s.emit('download', index, byteLength - s.padding, from, req)
    }
  }

  _onupload(index, byteLength, from) {
    const sessions = this.core.monitors

    for (let i = sessions.length - 1; i >= 0; i--) {
      const s = sessions[i]
      s.emit('upload', index, byteLength - s.padding, from)
    }
  }

  _oninvaliddata(err, req, res, from) {
    const sessions = this.core.monitors

    this.stats.invalidData++
    from.stats.invalidData++
    for (let i = 0; i < sessions.length; i++) {
      sessions[i].emit('verification-error', err, req, res, from)
    }
  }

  _oninvalidrequest(err, req, from) {
    const sessions = this.core.monitors

    from.stats.invalidRequests++
    this.stats.invalidRequests++
    for (let i = 0; i < sessions.length; i++) {
      sessions[i].emit('invalid-request', err, req, from)
    }
  }
}

function removeHotswap(block) {
  if (block.hotswap === null) return false
  block.hotswap.ref.remove(block)
  return true
}

function removeInflight(inf, req) {
  const i = inf.indexOf(req)
  if (i === -1) return false
  if (i < inf.length - 1) inf[i] = inf.pop()
  else inf.pop()
  return true
}

function toLength(start, end) {
  return end === -1 ? -1 : end < start ? 0 : end - start
}

function clampRange(core, r) {
  if (r.blocks === null) {
    const start = core.bitfield.firstUnset(r.start)

    if (r.end === -1) r.start = start === -1 ? core.state.length : start
    else if (start === -1 || start >= r.end) r.start = r.end
    else {
      r.start = start

      const end = core.bitfield.lastUnset(r.end - 1)

      if (end === -1 || start >= end + 1) r.end = r.start
      else r.end = end + 1
    }
  } else {
    while (r.start < r.end && core.bitfield.get(r.blocks[r.start])) r.start++
    while (r.start < r.end && core.bitfield.get(r.blocks[r.end - 1])) r.end--
  }
}

function onrequesttimeout(req) {
  if (req.context) req.context.detach(req, REQUEST_TIMEOUT())
}

function destroyRequestTimeout(req) {
  if (req.timeout !== null) {
    clearTimeout(req.timeout)
    req.timeout = null
  }
}

function isCriticalError(err) {
  // TODO: expose .critical or similar on the hypercore errors that are critical (if all not are)
  return err.name === 'HypercoreError'
}

function onwireopen(m, c) {
  return c.userData.onopen(m)
}

function onwireclose(isRemote, c) {
  return c.userData.onclose(isRemote)
}

function onwiredestroy(c) {
  c.userData.replicator.onpeerdestroy()
}

function onwiredrain(c) {
  return c.userData.ondrain()
}

function onwiresync(m, c) {
  incrementRx(c.userData.stats.wireSync, c.userData.replicator.stats.wireSync)
  return c.userData.onsync(m)
}

function onwirerequest(m, c) {
  incrementRx(c.userData.stats.wireRequest, c.userData.replicator.stats.wireRequest)
  return c.userData.onrequest(m)
}

function onwirecancel(m, c) {
  incrementRx(c.userData.stats.wireCancel, c.userData.replicator.stats.wireCancel)
  return c.userData.oncancel(m)
}

function onwiredata(m, c) {
  incrementRx(c.userData.stats.wireData, c.userData.replicator.stats.wireData)
  return c.userData.ondata(m)
}

function onwirenodata(m, c) {
  return c.userData.onnodata(m)
}

function onwirewant(m, c) {
  incrementRx(c.userData.stats.wireWant, c.userData.replicator.stats.wireWant)
  return c.userData.onwant(m)
}

function onwireunwant(m, c) {
  return c.userData.onunwant(m)
}

function onwirebitfield(m, c) {
  incrementRx(c.userData.stats.wireBitfield, c.userData.replicator.stats.wireBitfield)
  return c.userData.onbitfield(m)
}

function onwirerange(m, c) {
  incrementRx(c.userData.stats.wireRange, c.userData.replicator.stats.wireRange)
  return c.userData.onrange(m)
}

function onwireextension(m, c) {
  incrementRx(c.userData.stats.wireExtension, c.userData.replicator.stats.wireExtension)
  return c.userData.onextension(m)
}

function setNotDownloadingLater(repl, session) {
  repl._setDownloadingNow(false, session)
}

function isBlockRequest(req) {
  return req !== null && req.block !== null
}

function isUpgradeRequest(req) {
  return req !== null && req.upgrade !== null
}

function incrementTx(stats1, stats2) {
  stats1.tx++
  stats2.tx++
}

function incrementRx(stats1, stats2) {
  stats1.rx++
  stats2.rx++
}

function noop() {}

function backoff(times) {
  const sleep = times < 2 ? 200 : times < 5 ? 500 : times < 40 ? 1000 : 5000
  return new Promise((resolve) => setTimeout(resolve, sleep))
}
const crypto = require('hypercore-crypto')
const b4a = require('b4a')
const assert = require('nanoassert')
const flat = require('flat-tree')
const quickbit = require('quickbit-universal')
const HypercoreStorage = require('hypercore-storage')

const {
  INVALID_OPERATION,
  INVALID_SIGNATURE,
  ASSERTION,
  SESSION_CLOSED,
  SESSION_NOT_WRITABLE
} = require('hypercore-errors')

const Mutex = require('./mutex')
const Bitfield = require('./bitfield')
const { MerkleTree, MerkleTreeBatch } = require('./merkle-tree')

class SessionState {
  constructor(core, parent, storage, treeInfo, name) {
    this.core = core
    this.index = this.core.sessionStates.push(this) - 1

    this.storage = storage
    this.name = name
    this.sessions = []

    // small hack to close old storages as late as possible.
    // TODO: add a read lock so we can avoid that
    this.lingers = null

    this.parent = parent
    this.atomized = null
    this.mutex = new Mutex()

    // merkle state
    this.roots = treeInfo.roots.length ? treeInfo.roots : []
    this.fork = treeInfo.fork || 0
    this.length = this.roots.length ? MerkleTree.span(this.roots) / 2 : treeInfo.length
    this.byteLength = MerkleTree.size(this.roots)
    this.prologue = treeInfo.prologue || null
    this.signature = treeInfo.signature || null

    this.snapshotCompatLength = this.isSnapshot()
      ? Math.min(this.length, this.core.state.length)
      : -1
    this.lastTruncation = null
    this.groupUpdated = false

    this.active = 0

    this._activeTx = null
    this._pendingBitfield = null

    this.ref()
  }

  static RECOVERY_PEERS = null

  isSnapshot() {
    return this.storage.snapshotted
  }

  isDefault() {
    return this.core.state === this || this.isAtomicDefault()
  }

  isAtomicDefault() {
    return !!this.storage.atom && !!this.parent && this.parent.isDefault()
  }

  createTreeBatch() {
    return new MerkleTreeBatch(this)
  }

  addSession(s) {
    if (s._stateIndex !== -1) return
    s._stateIndex = this.sessions.push(s) - 1
    if (s.weak === false) this.core.activeSessions++
  }

  removeSession(s) {
    if (s._stateIndex === -1) return
    const head = this.sessions.pop()
    if (head !== s) this.sessions[(head._stateIndex = s._stateIndex)] = head
    s._stateIndex = -1
    if (s.weak === false) this.core.activeSessions--
    this.core.checkIfIdle()
  }

  flushedLength() {
    if (this.isDefault() || this.isSnapshot()) return this.length
    const deps = this.storage.dependencies
    if (deps.length) return deps[deps.length - 1].length
    return 0
  }

  signedLength() {
    const l = Math.min(this.flushedLength(), this.core.state.length)
    return this.isSnapshot() && l > this.snapshotCompatLength ? this.snapshotCompatLength : l
  }

  unref() {
    if (--this.active > 0) return
    this.close().catch(noop) // technically async, but only for the last db session
  }

  ref() {
    this.active++
    return this
  }

  hash() {
    return MerkleTree.hash(this)
  }

  setRoots(roots) {
    this.roots = roots
    this.length = MerkleTree.span(roots) / 2
    this.byteLength = MerkleTree.size(roots)
  }

  get encryptionFork() {
    return this.core.header.tree.fork
  }

  async _updateSnapshotStorage(storage) {
    if (!this.atomized || !this.atomized.flushing) return this.treeInfo()
    while (this.atomized.flushing) await this.atomized.flushed()

    let rx = storage.read()
    const headPromise = rx.getHead()
    const authPromise = rx.getAuth()
    const depPromise = rx.getDependency()

    rx.tryFlush()
    const [head, auth, dep] = await Promise.all([headPromise, authPromise, depPromise])

    storage.setDependencyHead(dep)

    const fork = head ? head.fork : 0
    const length = head ? head.length : 0

    rx = storage.read()
    const rootPromises = []
    for (const r of flat.fullRoots(length * 2)) {
      rootPromises.push(rx.getTreeNode(r))
    }

    rx.tryFlush()

    const roots = await Promise.all(rootPromises)

    // dbl check if we are hitting an regression from earler
    for (const root of roots) {
      if (root === null) {
        throw new Error(
          'Bad snapshot from atomized session, id = ' +
            this.core.id +
            ' length = ' +
            length +
            ' fork = ' +
            fork
        )
      }
    }

    return {
      fork,
      roots,
      length,
      prologue: auth.manifest && auth.manifest.prologue,
      signature: head && head.signature
    }
  }

  treeInfo() {
    return {
      fork: this.fork,
      roots: this.roots.slice(),
      length: this.length,
      prologue: this.prologue,
      signature: this.signature
    }
  }

  async close() {
    if (this.index === -1) return

    this.active = 0
    this.mutex.destroy(new Error('Closed')).catch(noop)
    if (this.parent && this.parent.atomized) this.parent.atomized = null

    const closing = this.storage.close()

    const head = this.core.sessionStates.pop()
    if (head !== this) this.core.sessionStates[(head.index = this.index)] = head

    this.index = -1
    this.core.checkIfIdle()

    if (this.lingers !== null) {
      for (const storage of this.lingers) await storage.close()
    }

    return closing
  }

  async snapshot() {
    const storage = this.storage.snapshot()
    const treeInfo = await this._updateSnapshotStorage(storage)

    return new SessionState(this.core, null, storage, treeInfo, this.name)
  }

  updateDependency(tx, length) {
    const dependency = updateDependency(this, length, false)
    if (dependency) tx.setDependency(dependency)
    return dependency
  }

  updateGroupIndex(tx, tree) {
    const { pointer } = this.core.header.group

    tx.deleteGroupUpdate(pointer, this.core.header.tree.timestamp)
    tx.putGroupUpdate(pointer, tree.timestamp, this.core.header.key)

    this.groupUpdated = true
  }

  _clearActiveBatch() {
    this._activeTx = null
  }

  createWriteBatch() {
    assert(!this._activeTx && !this.storage.snapshotted)

    this._activeTx = this.storage.write()
    return this._activeTx
  }

  _unlock() {
    this._clearActiveBatch()
    this.mutex.unlock()
    this.core.checkIfIdle()
  }

  _flushHooks() {
    if (!this.groupUpdated) return
    this.groupUpdated = false
    this.core.ongroupupdate(this.core.header.group.key, {
      key: this.core.key,
      length: this.length,
      fork: this.fork
    })
  }

  async flush() {
    const tx = this._activeTx
    this._activeTx = null

    try {
      if (!(await tx.flush())) return false
    } finally {
      this._clearActiveBatch()
    }

    this.lastTruncation = null
    return true
  }

  _precommit(state) {
    assert(
      state.parent === this && state.storage.core.dataPointer === this.storage.core.dataPointer,
      'Atomic state must flush to parent'
    )
  }

  async _commit() {
    await this.mutex.lock()

    try {
      const bitfield = this._pendingBitfield
      this._pendingBitfield = null
      this.lastTruncation = null
      await this.parent._oncommit(this, bitfield)
    } finally {
      this.mutex.unlock()
    }
  }

  async _oncommit(src, bitfield) {
    await this.mutex.lock()

    try {
      const currLength = this.length

      // load dependency into memory
      const rx = this.storage.read()
      const dependencyPromise = rx.getDependency()

      rx.tryFlush()

      const dependency = await dependencyPromise

      this.fork = src.fork
      this.length = src.length
      this.byteLength = src.byteLength
      this.roots = src.roots.slice()
      this.signature = src.signature

      const tree = {
        fork: this.fork,
        length: this.length,
        rootHash: this.hash(),
        signature: this.signature,
        timestamp: Date.now()
      }

      if (this.isDefault() && this.core.header.group) {
        const tx = this.createWriteBatch()
        this.updateGroupIndex(tx, tree)
        await this.flush()
        this._flushHooks()
      }

      if (dependency) this.storage.setDependencyHead(dependency)

      const b = bitfield

      if (b && b.truncated && b.start < currLength) {
        this.ontruncate(tree, b.start, currLength, true)
        if (!b || b.appends === 0) return
      }

      const append = b ? { start: b.start, length: b.appends, drop: false } : null

      this.onappend(tree, append, true)

      if (this.core.hintsChanged && this.isDefault()) await this.core.flushHints()
    } finally {
      this._unlock()
    }
  }

  async setUserData(key, value) {
    await this.mutex.lock()

    try {
      const tx = this.createWriteBatch()
      tx.putUserData(key, value)

      return await this.flush()
    } finally {
      this._unlock()
    }
  }

  async _verifyBlock(batch, bitfield, value, manifest, from) {
    await this.mutex.lock()

    try {
      if (batch.upgraded && batch.length <= this.length) {
        await batch.downgrade()
      }

      if (!batch.commitable()) {
        return false
      }

      if (this.core.preupdate !== null) {
        await this.core.preupdate(batch, this.core.header.key)
      }

      const tx = this.createWriteBatch()

      if (bitfield) {
        tx.putBlock(bitfield.start, value)
      }

      if (bitfield && this.isDefault()) {
        await storeBitfieldRange(this.storage, tx, bitfield.start, bitfield.start + 1, true)
      }

      if (manifest) this.core._setManifest(tx, manifest, null)

      assert(batch.commitable(), 'Should still be commitable')
      batch.commit(tx)

      const head = {
        fork: batch.fork,
        length: batch.length,
        rootHash: batch.hash(),
        signature: batch.signature,
        timestamp: Date.now()
      }

      if (batch.upgraded) {
        tx.setHead(head)

        if (this.core.header.group) {
          this.updateGroupIndex(tx, head)
        }
      }

      const flushed = await this.flush()

      if (batch.upgraded) {
        this.roots = batch.roots
        this.length = batch.length
        this.byteLength = batch.byteLength
        this.fork = batch.fork
        this.signature = batch.signature

        this.onappend(head, bitfield, flushed)
      }

      if (this.core.hintsChanged && this.isDefault()) await this.core.flushHints()
    } finally {
      this._unlock()
    }

    return true
  }

  async truncate(length, fork, { signature, keyPair } = {}) {
    if (!keyPair && this.isDefault()) keyPair = this.core.header.keyPair

    await this.mutex.lock()

    try {
      if (this.prologue && length < this.prologue.length) {
        throw INVALID_OPERATION('Truncation breaks prologue', this.core.discoveryKey)
      }
      if (length > this.length) {
        throw INVALID_OPERATION(
          'Not a truncation, ' + length + ' must be less or equal to ' + this.length,
          this.core.discoveryKey
        )
      }

      const batch = this.createTreeBatch()
      await MerkleTree.truncate(this, length, batch, fork)

      if (signature) {
        batch.signature = signature
        this.core._verifyBatchUpgrade(batch)
      } else if (keyPair) {
        batch.signature = this.core.verifier.sign(batch, keyPair)
      }

      const tx = this.createWriteBatch()

      // upsert compat manifest
      if (this.core.verifier === null && keyPair) this.core._setManifest(tx, null, keyPair)

      const { dependency, tree, roots } = await this._truncate(tx, batch)

      for (const sessionState of this.core.sessionStates) {
        if (
          sessionState.isSnapshot() &&
          sessionState.name === this.name &&
          length < sessionState.snapshotCompatLength
        ) {
          sessionState.snapshotCompatLength = length
        }
      }

      const flushed = await this.flush()

      this.fork = tree.fork
      this.length = tree.length
      this.byteLength = MerkleTree.size(roots)
      this.roots = roots
      this.signature = tree.signature

      if (dependency) this.storage.setDependencyHead(dependency)

      this.ontruncate(tree, tree.length, batch.treeLength, flushed)

      if (this.core.hintsChanged && this.isDefault()) await this.core.flushHints()
    } finally {
      this._unlock()
    }
  }

  async reorg(batch) {
    await this.mutex.lock()

    const storage = this.createWriteBatch()

    try {
      if (!batch.commitable()) return false

      const { dependency, tree } = await this._truncate(storage, batch)

      const flushed = await this.flush()

      this.fork = batch.fork
      this.length = batch.length
      this.byteLength = batch.byteLength
      this.roots = batch.roots
      this.signature = batch.signature

      if (dependency) this.storage.setDependencyHead(dependency)

      this.ontruncate(tree, batch.ancestors, batch.treeLength, flushed)

      if (this.core.hintsChanged && this.isDefault()) await this.core.flushHints()
    } finally {
      this._unlock()
    }
  }

  async _truncate(storage, batch) {
    storage.deleteBlockRange(batch.ancestors, batch.treeLength)

    assert(batch.commitable(), 'Batch must be commitable')

    const tree = {
      fork: batch.fork,
      length: batch.length,
      rootHash: batch.hash(),
      signature: batch.signature,
      timestamp: Date.now()
    }

    if (this.isDefault() && this.core.header.group) {
      this.updateGroupIndex(storage, tree)
    }

    storage.setHead(tree)
    batch.commit(storage)

    const truncated = batch.length < this.flushedLength()
    const dependency = truncated ? updateDependency(this, batch.length, true) : null

    if (dependency) storage.setDependency(dependency)

    if (this.isDefault()) {
      await storeBitfieldRange(this.storage, storage, batch.ancestors, batch.treeLength, false)
      if (batch.ancestors < this.core.header.hints.contiguousLength) {
        this.core.header.hints.remoteContiguousLength = Math.min(
          batch.length,
          this.core.header.hints.remoteContiguousLength
        )
        storage.setHints({
          contiguousLength: batch.ancestors,
          remoteContiguousLength: this.core.header.hints.remoteContiguousLength
        })
      }
    }

    return { dependency, tree, roots: batch.roots }
  }

  async clear(start, end, cleared) {
    await this.mutex.lock()

    try {
      const tx = this.createWriteBatch()

      const ite = flat.iterator(start * 2)
      while (!isRootIndex(ite.index, this.roots)) {
        const a = ite.index
        const b = ite.sibling()
        ite.parent()

        const [left, right] = flat.spans(b)
        const s = left / 2
        const e = right / 2 + 1
        const has = s <= start && e <= end ? false : this.core.bitfield.hasSet(s, e - s)
        if (has) break

        tx.deleteTreeNode(a)
        tx.deleteTreeNode(b)
      }

      if (this.isDefault()) {
        await storeBitfieldRange(this.storage, tx, start, end, false)
        if (start < this.core.header.hints.contiguousLength) {
          tx.setHints({
            contiguousLength: start,
            remoteContiguousLength: this.core.header.hints.remoteContiguousLength
          })
        }
      }

      if (end - start === 1) tx.deleteBlock(start)
      else tx.deleteBlockRange(start, end)

      const dependency = start < this.flushedLength() ? updateDependency(this, start, true) : null

      const flushed = await this.flush()

      if (dependency) this.storage.setDependencyHead(dependency)

      // todo: atomic event handle
      if (this.isDefault() && flushed) {
        const length = end - start

        this.core.updateContiguousLength({ start, length, drop: true })
        this.core._setBitfieldRanges(start, end, false)
        this.core.replicator.onhave(start, length, true)

        if (this.core.hintsChanged) await this.core.flushHints()
      }
    } finally {
      this._unlock()
    }
  }

  // simple tool to wait for other peers to catch us up
  async waitForRecovery() {
    const length = this.length
    const replicator = this.core.replicator

    while (!this.closing) {
      let peers = getRecoveryPeers(replicator.peers)

      if (peers.length < 1) {
        await new Promise((resolve) => setTimeout(resolve, 5000))
        continue
      }

      let restart = false

      for (let i = 0; i < 32; i++) {
        await new Promise((resolve) => setTimeout(resolve, 250))

        peers = getRecoveryPeers(replicator.peers)

        if (this.closing || !validateRecoveryPeers(peers, this.length)) {
          restart = true
          break
        }
      }

      if (restart) continue

      if (this.length !== length) {
        throw SESSION_NOT_WRITABLE('core recovered during append')
      }

      this.core.header.hints.recovering = 0
      this.core.hintsChanged = true

      await this.mutex.lock()
      try {
        await this.core.flushHints()
        return
      } finally {
        this.mutex.unlock()
      }
    }

    throw SESSION_CLOSED('Cannot recover a closed session', this.discoveryKey)
  }

  async append(values, { signature, keyPair, preappend, postappend, maxLength = -1 } = {}) {
    if (!keyPair && this.isDefault()) keyPair = this.core.header.keyPair

    if (this.isDefault() && this.core.header.hints.recovering) await this.waitForRecovery()

    await this.mutex.lock()

    try {
      if (maxLength >= 0 && this.length + values.length > maxLength) {
        return { length: this.length, byteLength: this.byteLength }
      }

      const tx = this.createWriteBatch()

      // upsert compat manifest
      if (this.core.verifier === null && keyPair) this.core._setManifest(tx, null, keyPair)

      if (preappend) await preappend(values)

      if (!values.length) {
        await this.flush()
        return { length: this.length, byteLength: this.byteLength }
      }

      const batch = this.createTreeBatch()
      for (const val of values) batch.append(val)

      // only multisig can have prologue so signature is always present
      if (this.prologue && batch.length < this.prologue.length) {
        throw INVALID_OPERATION('Append is not consistent with prologue', this.core.discoveryKey)
      }

      if (signature) {
        batch.signature = signature
        this.core._verifyBatchUpgrade(batch)
      } else if (keyPair) {
        batch.signature = this.core.verifier.sign(batch, keyPair)
      }

      batch.commit(tx)

      const tree = {
        fork: batch.fork,
        length: batch.length,
        rootHash: batch.hash(),
        signature: batch.signature,
        timestamp: Date.now()
      }

      tx.setHead(tree)

      if (this.isDefault()) {
        await storeBitfieldRange(this.storage, tx, batch.ancestors, batch.length, true)
        if (this.length === this.core.header.hints.contiguousLength) {
          tx.setHints({
            contiguousLength: this.length + values.length,
            remoteContiguousLength: this.core.header.hints.remoteContiguousLength
          })
        }

        if (this.core.header.group) {
          this.updateGroupIndex(tx, tree)
        }
      }

      for (let i = 0; i < values.length; i++) {
        tx.putBlock(this.length + i, values[i])
      }

      const bitfield = {
        drop: false,
        start: batch.ancestors,
        length: values.length
      }

      const flushed = await this.flush()

      this.fork = batch.fork
      this.roots = batch.roots
      this.length = batch.length
      this.byteLength = batch.byteLength
      this.signature = batch.signature

      if (postappend) await postappend(values)

      this.onappend(tree, bitfield, flushed)

      if (this.core.hintsChanged && this.isDefault()) await this.core.flushHints()

      return { length: this.length, byteLength: this.byteLength }
    } finally {
      this._unlock()
    }
  }

  onappend(tree, bitfield, flushed) {
    if (!flushed) this._updateBitfield(bitfield)
    else if (this.isDefault()) this.core.onappend(tree, bitfield)

    for (let i = this.sessions.length - 1; i >= 0; i--) {
      this.sessions[i].emit('append')
    }

    this._flushHooks()
  }

  ontruncate(tree, to, from, flushed) {
    const bitfield = { start: to, length: from - to, drop: true }

    this.lastTruncation = { from, to }

    if (!flushed) this._updateBitfield(bitfield)
    else if (this.isDefault()) this.core.ontruncate(tree, bitfield)

    for (const sessionState of this.core.sessionStates) {
      if (
        sessionState.isSnapshot() &&
        sessionState.name === this.name &&
        to < sessionState.snapshotCompatLength
      ) {
        sessionState.snapshotCompatLength = to
      }
    }

    for (let i = this.sessions.length - 1; i >= 0; i--) {
      this.sessions[i].emit('truncate', to, tree.fork)
    }

    this._flushHooks()
  }

  _updateBitfield(bitfield, flushed) {
    if (!bitfield) return

    const p = this._pendingBitfield
    const b = bitfield

    if (b.drop) {
      // truncation must be from end
      if (p && b.start + b.length !== p.start + p.appends) {
        throw INVALID_OPERATION('Atomic truncations must be contiguous', this.core.discoveryKey)
      }

      // actual truncation
      if (p === null || b.start < p.start) {
        this._pendingBitfield = { truncated: true, start: b.start, appends: 0 }
        return
      }

      // just clearing batch data
      p.appends = b.start - p.start

      // we cleared the current batch
      if (p.appends === 0) this._pendingBitfield = null

      return
    }

    if (p === null) {
      this._pendingBitfield = { truncated: false, start: b.start, appends: b.length }
      return
    }

    if (b.start !== p.start + p.appends) {
      throw INVALID_OPERATION('Atomic operations must be contiguous', this.core.discoveryKey)
    }

    p.appends += b.length
  }

  async catchup(length) {
    assert(!this.isDefault(), 'Cannot catchup signed state') // TODO: make this check better

    await this.mutex.lock()

    try {
      const origLength = this.length

      let sharedLength = 0
      for (let i = this.storage.dependencies.length - 1; i >= 0; i--) {
        const dep = this.storage.dependencies[i]
        if (dep.dataPointer === this.core.state.storage.core.dataPointer) {
          sharedLength = dep.length
          break
        }
      }

      const tx = this.createWriteBatch()
      const rx = this.core.state.storage.read()
      const rootPromises = []

      for (const root of flat.fullRoots(length * 2)) {
        rootPromises.push(rx.getTreeNode(root))
      }

      rx.tryFlush()

      const roots = await Promise.all(rootPromises)
      const truncating = sharedLength < origLength

      for (const node of roots) {
        if (node === null) {
          throw INVALID_OPERATION(
            'Invalid catchup length, tree nodes not available',
            this.core.discoveryKey
          )
        }
      }

      const fork = truncating ? this.fork + 1 : this.fork

      // overwrite it atm, TODO: keep what we can connect to the tree
      tx.deleteBlockRange(0, -1)
      tx.deleteTreeNodeRange(0, -1)
      tx.deleteBitfieldPageRange(0, -1)

      const tree = {
        fork,
        length,
        rootHash: crypto.tree(roots),
        signature: null,
        timestamp: Date.now()
      }

      // never default state so do not update group index
      tx.setHead(tree)

      // prop a better way to do this
      const dep = updateDependency(this, sharedLength, true)
      dep.length = length

      tx.setDependency(dep)

      const flushed = await this.flush()

      this.storage.setDependencyHead(dep)

      this.fork = tree.fork
      this.roots = roots
      this.length = tree.length
      this.byteLength = MerkleTree.size(roots)

      if (truncating) this.ontruncate(tree, sharedLength, origLength, flushed)
      if (sharedLength < length) this.onappend(tree, null, flushed)

      if (this.core.hintsChanged && this.isDefault()) await this.core.flushHints()
    } finally {
      this._unlock()
    }
  }

  async _overwrite(source, fork, length, treeLength, signature) {
    const blockPromises = []
    const treePromises = []
    const rootPromises = []

    const rx = source.storage.read()

    for (const root of flat.fullRoots(length * 2)) {
      rootPromises.push(rx.getTreeNode(root))
    }

    for (const index of flat.patch(treeLength * 2, length * 2)) {
      treePromises.push(rx.getTreeNode(index))
    }

    for (let i = treeLength; i < length; i++) {
      treePromises.push(rx.getTreeNode(i * 2))
      treePromises.push(rx.getTreeNode(i * 2 + 1))
      blockPromises.push(rx.getBlock(i))
    }

    rx.tryFlush()

    const [blocks, nodes, roots] = await Promise.all([
      Promise.all(blockPromises),
      Promise.all(treePromises),
      Promise.all(rootPromises)
    ])

    if (this.core.destroyed) throw new Error('Core destroyed')

    if (signature) {
      const batch = this.createTreeBatch()
      batch.roots = roots
      batch.length = length

      if (!this.core.verifier.verify(batch, signature)) {
        throw INVALID_SIGNATURE(
          'Signature is not valid over committed tree',
          this.core.discoveryKey
        )
      }
    }

    const tx = this.createWriteBatch()

    // truncate existing tree
    if (treeLength < this.length) {
      tx.deleteBlockRange(treeLength, this.length)
    }

    for (const root of roots) tx.putTreeNode(root)

    // no nodes will be copied in shallow mode
    for (const node of nodes) {
      if (node !== null) tx.putTreeNode(node)
    }

    for (let i = 0; i < blocks.length; i++) {
      assert(blocks[i] !== null, 'has block')
      tx.putBlock(i + treeLength, blocks[i])
    }

    const totalLength = Math.max(length, this.length)

    if (totalLength > treeLength) {
      const firstPage = getBitfieldPage(treeLength)
      const lastPage = getBitfieldPage(totalLength - 1)

      const srx = this.storage.read()
      const bitfieldPagePromise = srx.getBitfieldPage(firstPage)
      srx.tryFlush()

      const bitfieldPage = await bitfieldPagePromise

      let index = treeLength

      for (let i = firstPage; i <= lastPage; i++) {
        const page = b4a.alloc(Bitfield.BYTES_PER_PAGE)
        tx.putBitfieldPage(i, page)

        // copy existing bits in
        if (i === firstPage && bitfieldPage) page.set(bitfieldPage)

        if (index < length) {
          index = fillBitfieldPage(page, index, length, i, true)
          if (index < length) continue
        }

        if (index < this.length) {
          index = fillBitfieldPage(page, index, this.length, i, false)
        }
      }
    }

    const tree = {
      fork,
      length,
      rootHash: crypto.tree(roots),
      signature,
      timestamp: Date.now()
    }

    if (this.isDefault() && this.core.header.group) {
      this.updateGroupIndex(tx, tree)
    }

    const upgraded = treeLength < this.length || this.length < length || tree.fork !== this.fork

    if (upgraded) tx.setHead(tree)

    const flushed = await this.flush()

    this.fork = tree.fork
    this.roots = roots
    this.length = length
    this.byteLength = MerkleTree.size(roots)
    this.signature = signature

    return { tree, flushed }
  }

  static isParent(state, parent) {
    // atomic batches have parent set
    if (state.parent && state.parent === parent) return true

    return HypercoreStorage.isParentStorage(state.storage, parent.storage)
  }

  async commit(state, { signature, keyPair, length = state.length, treeLength = -1 } = {}) {
    assert(
      this.isDefault() || (this.parent && this.parent.isDefault()),
      'Can only commit into default state'
    )

    assert(SessionState.isParent(state, this), 'Cannot commit across cores')

    if (this.core._repairMode) {
      throw ASSERTION('Cannot commit while repair mode is on')
    }

    if (this.core.header.hints.recovering) await this.waitForRecovery()

    let srcLocked = false
    await this.mutex.lock()

    try {
      await state.mutex.lock()
      srcLocked = true

      if (treeLength === -1) treeLength = state.flushedLength()

      if (!(await this.core._validateCommit(state, treeLength))) return null
      if (this.length > length) return null

      if (this.length < length && !signature) {
        if (!keyPair) keyPair = this.core.header.keyPair
        const batch = state.createTreeBatch()
        if (length !== batch.length) await batch.restore(length)
        signature = this.core.verifier.sign(batch, keyPair)
      }

      const { tree, flushed } = await this._overwrite(
        state,
        this.fork,
        length,
        treeLength,
        signature
      )

      // gc blocks from source
      if (treeLength < length) {
        const tx = state.createWriteBatch()

        tx.deleteBlockRange(treeLength, length)
        const dependency = state.updateDependency(tx, length)

        await state.flush(tx)

        if (dependency) state.storage.setDependencyHead(dependency)
      }

      const bitfield = { start: treeLength, length: length - treeLength, drop: false }
      this.onappend(tree, bitfield, flushed)

      return {
        length: this.length,
        byteLength: this.byteLength
      }
    } finally {
      if (srcLocked) state._unlock()
      this._unlock()
    }
  }

  async _getTreeHeadAt(length) {
    if (length === null) return this.treeInfo()

    const head = getDefaultTree()

    head.length = length

    const roots = await MerkleTree.getRootsFromStorage(this.storage, length)
    const rootHash = crypto.tree(roots)

    head.fork = this.fork
    head.rootHash = rootHash

    if (length === this.length) head.signature = this.signature

    return head
  }

  _moveToCore(core, truncated, appended) {
    const head = this.core.sessionStates.pop()
    if (head !== this) this.core.sessionStates[(head.index = this.index)] = head

    this.core = core
    this.index = this.core.sessionStates.push(this) - 1

    for (let i = this.sessions.length - 1; i >= 0; i--) {
      const s = this.sessions[i]
      const manifest = s.manifest
      s.transferSession(this.core)
      if (!manifest && s.manifest) s.emit('manifest')
      if (truncated) s.emit('truncate', truncated.to, truncated.fork)
      if (appended) s.emit('append')
    }
  }

  async moveTo(core, length) {
    const state = core.state

    await this.mutex.lock()

    try {
      // if (state.storage && (await state.storage.resumeSession(this.name)) !== null) {
      //   throw STORAGE_CONFLICT('Batch has already been created')
      // }

      const treeLength = this.length

      let truncated = null
      let appended = false

      if (!this.isSnapshot()) {
        if (this.lingers === null) this.lingers = []
        this.lingers.push(this.storage)

        const resumed = await state.storage.resumeSession(this.name)

        const truncation = length < this.length ? await truncateAndFlush(this, length) : null
        const treeInfo = truncation
          ? truncation.tree
          : resumed
            ? null
            : await state._getTreeHeadAt(this.length)

        const fork = truncation ? this.fork + 1 : this.fork

        // todo: validate treeInfo

        let storage = null

        if (resumed) {
          storage = resumed
        } else {
          treeInfo.fork = fork
          storage = await state.storage.createSession(this.name, treeInfo)
        }

        const roots = await MerkleTree.getRootsFromStorage(storage, length)

        this.storage = storage
        this.prologue = state.prologue
        this.fork = fork
        this.length = length
        this.byteLength = MerkleTree.size(roots)
        this.roots = roots

        if (truncation) {
          const { dependency } = truncation

          if (dependency) this.storage.setDependencyHead(dependency)
          truncated = { to: treeLength, fork }
        }

        if (this.length > treeLength) {
          appended = true
        }
      }

      for (let i = this.core.sessionStates.length - 1; i >= 0; i--) {
        const state = this.core.sessionStates[i]
        if (state === this) continue
        if (state.name === this.name) state._moveToCore(core.core)
      }

      this._moveToCore(core.core, truncated, appended)
    } finally {
      this._unlock()
    }
  }

  async createSession(name, overwrite, atom) {
    await this.mutex.lock()

    try {
      let storage = null
      let treeInfo = null

      if (!atom && !overwrite && this.storage) {
        storage = await this.storage.resumeSession(name)

        if (storage !== null) treeInfo = (await getCoreHead(storage)) || getDefaultTree()
      }

      const length = treeInfo ? treeInfo.length : this.length

      if (storage === null) {
        treeInfo = await this._getTreeHeadAt(length)

        if (atom) {
          storage = await this.storage.createAtomicSession(atom, treeInfo)
        } else {
          storage = await this.storage.createSession(name, treeInfo)
        }
      }

      if (this.atomized && atom) {
        throw new Error('Session already atomized')
      }

      const head = {
        fork: this.fork,
        roots:
          length === this.length
            ? this.roots.slice()
            : await MerkleTree.getRootsFromStorage(storage, length),
        length,
        prologue: this.prologue,
        signature: length === this.length ? this.signature : null
      }

      const state = new SessionState(
        this.core,
        atom ? this : null,
        storage,
        head,
        atom ? this.name : name
      )

      if (atom) {
        this.atomized = atom
        atom.preflush(this._precommit.bind(this, state))
        atom.onflush(state._commit.bind(state))
      }

      return state
    } finally {
      this._unlock()
    }
  }
}

module.exports = SessionState

function noop() {}

function getBitfieldPage(index) {
  return Math.floor(index / Bitfield.BITS_PER_PAGE)
}

function fillBitfieldPage(page, start, end, pageIndex, value) {
  const offset = pageIndex * Bitfield.BITS_PER_PAGE
  const max = offset + Bitfield.BITS_PER_PAGE

  const index = max < end ? max : end

  const from = start - offset
  const to = index - offset

  quickbit.fill(page, value, from, to)

  return index
}

async function storeBitfieldRange(storage, tx, from, to, value) {
  if (from >= to) return

  const firstPage = getBitfieldPage(from)
  const lastPage = getBitfieldPage(to - 1)

  let index = from

  const rx = storage.read()

  const promises = []
  for (let i = firstPage; i <= lastPage; i++) {
    promises.push(rx.getBitfieldPage(i))
  }

  rx.tryFlush()

  const pages = await Promise.all(promises)
  const cnt = lastPage - firstPage + 1

  for (let i = 0; i < cnt; i++) {
    const pageIndex = i + firstPage
    if (!pages[i]) pages[i] = b4a.alloc(Bitfield.BYTES_PER_PAGE)

    index = fillBitfieldPage(pages[i], index, to, pageIndex, value)
    tx.putBitfieldPage(pageIndex, pages[i])
  }
}

async function truncateAndFlush(s, length) {
  const batch = s.createTreeBatch()
  await MerkleTree.truncate(s, length, batch, s.fork)
  const tx = s.createWriteBatch()

  const info = await s._truncate(tx, batch)
  const flushed = await s.flush()

  return {
    tree: info.tree,
    roots: info.roots,
    dependency: info.dependency,
    flushed
  }
}

function updateDependency(state, length, truncated) {
  const i = state.storage.findDependencyIndex(length, truncated)
  if (i === -1) return null // skip default state and overlays of default

  return {
    dataPointer: state.storage.dependencies[i].dataPointer,
    length
  }
}

function getDefaultTree() {
  return {
    fork: 0,
    length: 0,
    rootHash: null,
    signature: null
  }
}

function getCoreHead(storage) {
  const b = storage.read()
  const p = b.getHead()
  b.tryFlush()
  return p
}

function isRootIndex(index, roots) {
  for (const node of roots) {
    if (node.index === index) return true
  }

  return false
}

function getRecoveryPeers(peers) {
  if (!SessionState.RECOVERY_PEERS) return peers

  const actual = []

  for (const p of peers) {
    for (const r of SessionState.RECOVERY_PEERS) {
      if (b4a.equals(p.remotePublicKey, r)) {
        actual.push(p)
        break
      }
    }
  }

  return actual
}

function validateRecoveryPeers(peers, length) {
  if (peers.length < 1) return false

  for (const p of peers) {
    if (p.remoteLength > length) return false
    if (p.remoteLength === 0 && !p.remoteSynced) return false
  }

  return true
}
const { Writable, Readable } = require('streamx')

class ReadStream extends Readable {
  constructor(core, opts = {}) {
    super()

    this.core = core
    this.start = opts.start || 0
    this.end = typeof opts.end === 'number' ? opts.end : -1
    this.snapshot = !opts.live && opts.snapshot !== false
    this.live = this.end === -1 ? !!opts.live : false
    this.wait = typeof opts.wait === 'boolean' ? opts.wait : this.core.wait
    this.timeout = opts.timeout || core.timeout
  }

  _open(cb) {
    this._openP().then(cb, cb)
  }

  _read(cb) {
    this._readP().then(cb, cb)
  }

  async _openP() {
    if (this.end === -1) await this.core.update()
    else await this.core.ready()
    if (this.snapshot && this.end === -1) this.end = this.core.length
  }

  async _readP() {
    const end = this.live ? -1 : this.end === -1 ? this.core.length : this.end
    if (end >= 0 && this.start >= end) {
      this.push(null)
      return
    }

    this.push(await this.core.get(this.start++, { wait: this.wait, timeout: this.timeout }))
  }
}

exports.ReadStream = ReadStream

class WriteStream extends Writable {
  constructor(core) {
    super()
    this.core = core
  }

  _writev(batch, cb) {
    this._writevP(batch).then(cb, cb)
  }

  async _writevP(batch) {
    await this.core.append(batch)
  }
}

exports.WriteStream = WriteStream

class ByteStream extends Readable {
  constructor(core, opts = {}) {
    super()

    this._core = core
    this._index = 0
    this._range = null

    this._byteOffset = opts.byteOffset || 0
    this._byteLength = typeof opts.byteLength === 'number' ? opts.byteLength : -1
    this._prefetch = typeof opts.prefetch === 'number' ? opts.prefetch : 32

    this._applyOffset = this._byteOffset > 0
  }

  _open(cb) {
    this._openp().then(cb, cb)
  }

  _read(cb) {
    this._readp().then(cb, cb)
  }

  async _openp() {
    if (this._byteLength === -1) {
      await this._core.update()
      this._byteLength = Math.max(this._core.byteLength - this._byteOffset, 0)
    }
  }

  async _readp() {
    let data = null

    if (this._byteLength === 0) {
      this.push(null)
      return
    }

    let relativeOffset = 0

    if (this._applyOffset) {
      this._applyOffset = false

      const [block, byteOffset] = await this._core.seek(this._byteOffset)

      this._index = block
      relativeOffset = byteOffset
    }

    this._predownload(this._index + 1)
    data = await this._core.get(this._index++, { valueEncoding: 'binary' })

    if (relativeOffset > 0) data = data.subarray(relativeOffset)

    if (data.byteLength > this._byteLength) data = data.subarray(0, this._byteLength)
    this._byteLength -= data.byteLength

    this.push(data)
    if (this._byteLength === 0) this.push(null)
  }

  _predownload(index) {
    if (this._range) this._range.destroy()
    this._range = this._core.download({ start: index, end: index + this._prefetch, linear: true })
  }

  _destroy(cb) {
    if (this._range) this._range.destroy()
    cb(null)
  }
}

exports.ByteStream = ByteStream
const crypto = require('hypercore-crypto')
const b4a = require('b4a')
const c = require('compact-encoding')
const flat = require('flat-tree')
const { BAD_ARGUMENT } = require('hypercore-errors')
const unslab = require('unslab')

const m = require('./messages')
const multisig = require('./multisig')
const caps = require('./caps')

class Signer {
  constructor(
    manifestHash,
    version,
    index,
    { signature = 'ed25519', publicKey, namespace = caps.DEFAULT_NAMESPACE } = {}
  ) {
    if (!publicKey) throw BAD_ARGUMENT('public key is required for a signer')
    if (signature !== 'ed25519') throw BAD_ARGUMENT('Only Ed25519 signatures are supported')

    this.manifestHash = manifestHash
    this.version = version
    this.signer = index
    this.signature = signature
    this.publicKey = publicKey
    this.namespace = namespace
  }

  _ctx() {
    return this.version === 0 ? this.namespace : this.manifestHash
  }

  verify(batch, signature) {
    return crypto.verify(batch.signable(this._ctx()), signature, this.publicKey)
  }

  sign(batch, keyPair) {
    return crypto.sign(batch.signable(this._ctx()), keyPair.secretKey)
  }
}

class CompatSigner extends Signer {
  constructor(index, signer, legacy) {
    super(null, 0, index, signer)
    this.legacy = legacy
  }

  verify(batch, signature) {
    return crypto.verify(batch.signableCompat(this.legacy), signature, this.publicKey)
  }

  sign(batch, keyPair) {
    return crypto.sign(batch.signableCompat(this.legacy), keyPair.secretKey)
  }
}

module.exports = class Verifier {
  constructor(
    manifestHash,
    manifest,
    { compat = isCompat(manifestHash, manifest), legacy = false } = {}
  ) {
    const self = this

    this.manifestHash = manifestHash
    this.compat = compat || manifest === null
    this.version = this.compat ? 0 : typeof manifest.version === 'number' ? manifest.version : 1
    this.hash = manifest.hash || 'blake2b'
    this.allowPatch = !this.compat && !!manifest.allowPatch
    this.quorum = this.compat ? 1 : defaultQuorum(manifest)

    this.signers = manifest.signers ? manifest.signers.map(createSigner) : []
    this.prologue = this.compat ? null : manifest.prologue || null

    function createSigner(signer, index) {
      return self.compat
        ? new CompatSigner(index, signer, legacy)
        : new Signer(manifestHash, self.version, index, signer)
    }
  }

  _verifyCompat(batch, signature) {
    if (!signature) return false

    if (this.compat || (!this.allowPatch && this.signers.length === 1)) {
      return !!signature && this.signers[0].verify(batch, signature)
    }

    return this._verifyMulti(batch, signature)
  }

  _inflate(signature) {
    if (this.version >= 1) return multisig.inflate(signature)
    const { proofs, patch } = multisig.inflatev0(signature)

    return {
      proofs: proofs.map(proofToVersion1),
      patch
    }
  }

  _verifyMulti(batch, signature) {
    if (!signature || this.quorum === 0) return false

    const { proofs, patch } = this._inflate(signature)
    if (proofs.length < this.quorum) return false

    const tried = new Uint8Array(this.signers.length)
    const nodes = this.allowPatch && patch.length ? toMap(patch) : null

    for (let i = 0; i < this.quorum; i++) {
      const inp = proofs[i]

      let tree = batch

      if (inp.patch && this.allowPatch) {
        tree = batch.clone()

        const upgrade = generateUpgrade(nodes, batch.length, inp.patch)
        const proof = {
          fork: tree.fork,
          block: null,
          hash: null,
          seek: null,
          upgrade,
          manifest: null
        }

        try {
          if (!tree.verifyUpgrade(proof)) return false
        } catch {
          return false
        }
      }

      if (inp.signer >= this.signers.length || tried[inp.signer]) return false
      tried[inp.signer] = 1

      const s = this.signers[inp.signer]
      if (!s.verify(tree, inp.signature)) return false
    }

    return true
  }

  verify(batch, signature) {
    if (this.version === 0) {
      return this._verifyCompat(batch, signature)
    }

    if (this.prologue !== null && batch.length <= this.prologue.length) {
      return batch.length === this.prologue.length && b4a.equals(batch.hash(), this.prologue.hash)
    }

    return this._verifyMulti(batch, signature)
  }

  // TODO: better api for this that is more ... multisig-ey
  sign(batch, keyPair) {
    if (!keyPair || !keyPair.secretKey) throw BAD_ARGUMENT('No key pair was passed')

    for (const s of this.signers) {
      if (b4a.equals(s.publicKey, keyPair.publicKey)) {
        const signature = s.sign(batch, keyPair)
        if (this.signers.length !== 1 || this.version === 0) return signature
        return this.assemble([{ signer: 0, signature, patch: 0, nodes: null }])
      }
    }

    throw BAD_ARGUMENT('Public key is not a declared signer')
  }

  assemble(inputs) {
    return this.version === 0 ? multisig.assemblev0(inputs) : multisig.assemble(inputs)
  }

  static manifestHash(manifest) {
    return manifestHash(manifest)
  }

  static encodeManifest(manifest) {
    return c.encode(m.manifest, manifest)
  }

  static decodeManifest(manifest) {
    return c.decode(m.manifest, manifest)
  }

  static defaultSignerManifest(publicKey) {
    return {
      version: 1,
      hash: 'blake2b',
      allowPatch: false,
      quorum: 1,
      signers: [
        {
          signature: 'ed25519',
          namespace: caps.DEFAULT_NAMESPACE,
          publicKey
        }
      ],
      prologue: null,
      linked: null,
      userData: null
    }
  }

  static fromManifest(manifest, opts) {
    const m = this.createManifest(manifest)
    return new this(manifestHash(m), m, opts)
  }

  static createManifest(inp) {
    if (!inp) return null

    if (inp.quorum && inp.quorum < 0) throw BAD_ARGUMENT('Quorum cannot be negative')
    if (inp.quorum && inp.signers && inp.quorum > inp.signers.length) {
      throw BAD_ARGUMENT('Quorum should not be higher than the number of signers')
    }

    const manifest = {
      version: getManifestVersion(inp), // defaults to v1
      hash: 'blake2b',
      allowPatch: !!inp.allowPatch,
      quorum: defaultQuorum(inp),
      signers: inp.signers ? inp.signers.map(parseSigner) : [],
      prologue: null,
      linked: null,
      userData: inp.userData || null
    }

    if (inp.hash && inp.hash !== 'blake2b') throw BAD_ARGUMENT('Only Blake2b hashes are supported')

    if (inp.prologue) {
      if (
        !(b4a.isBuffer(inp.prologue.hash) && inp.prologue.hash.byteLength === 32) ||
        !(inp.prologue.length >= 0)
      ) {
        throw BAD_ARGUMENT('Invalid prologue')
      }

      manifest.prologue = inp.prologue
      manifest.prologue.hash = unslab(manifest.prologue.hash)
    }

    if (manifest.userData !== null && manifest.version < 2) {
      throw BAD_ARGUMENT('Invalid field: userData')
    }

    if (inp.linked && inp.linked.length) {
      if (manifest.version < 2) throw BAD_ARGUMENT('Invalid field: linked')

      for (const key of inp.linked) {
        if (!(b4a.isBuffer(key) && key.byteLength === 32)) {
          throw BAD_ARGUMENT('Invalid key')
        }
      }

      manifest.linked = inp.linked
    }

    return manifest
  }

  static isValidManifest(key, manifest) {
    return b4a.equals(key, manifestHash(manifest))
  }

  static isCompat(key, manifest) {
    return isCompat(key, manifest)
  }

  static sign(manifest, batch, keyPair, opts) {
    return Verifier.fromManifest(manifest, opts).sign(batch, keyPair)
  }
}

function toMap(nodes) {
  const m = new Map()
  for (const node of nodes) m.set(node.index, node)
  return m
}

function isCompat(key, manifest) {
  return !!(
    manifest &&
    manifest.signers.length === 1 &&
    b4a.equals(key, manifest.signers[0].publicKey)
  )
}

function defaultQuorum(man) {
  if (typeof man.quorum === 'number') return man.quorum
  if (!man.signers || !man.signers.length) return 0
  return (man.signers.length >> 1) + 1
}

function generateUpgrade(patch, start, length) {
  const upgrade = { start, length, nodes: null, additionalNodes: [], signature: null }

  const from = start * 2
  const to = from + length * 2

  for (const ite = flat.iterator(0); ite.fullRoot(to); ite.nextTree()) {
    if (ite.index + ite.factor / 2 < from) continue

    if (upgrade.nodes === null && ite.contains(from - 2)) {
      upgrade.nodes = []

      const root = ite.index
      const target = from - 2

      ite.seek(target)

      while (ite.index !== root) {
        ite.sibling()
        if (ite.index > target) upgrade.nodes.push(patch.get(ite.index))
        ite.parent()
      }

      continue
    }

    if (upgrade.nodes === null) upgrade.nodes = []
    upgrade.nodes.push(patch.get(ite.index))
  }

  if (upgrade.nodes === null) upgrade.nodes = []
  return upgrade
}

function parseSigner(signer) {
  validateSigner(signer)
  return {
    signature: 'ed25519',
    namespace: unslab(signer.namespace || caps.DEFAULT_NAMESPACE),
    publicKey: unslab(signer.publicKey)
  }
}

function validateSigner(signer) {
  if (!signer || !signer.publicKey) throw BAD_ARGUMENT('Signer missing public key')
  if (signer.signature && signer.signature !== 'ed25519') {
    throw BAD_ARGUMENT('Only Ed25519 signatures are supported')
  }
}

function manifestHash(manifest) {
  const state = { start: 0, end: 32, buffer: null }
  m.manifest.preencode(state, manifest)
  state.buffer = b4a.allocUnsafe(state.end)
  c.raw.encode(state, caps.MANIFEST)
  m.manifest.encode(state, manifest)
  return crypto.hash(state.buffer)
}

function proofToVersion1(proof) {
  return {
    signer: proof.signer,
    signature: proof.signature,
    patch: proof.patch ? proof.patch.length : 0
  }
}

function getManifestVersion(inp) {
  if (typeof inp.version === 'number') return inp.version
  if (inp.linked && inp.linked.length) return 2
  if (inp.userData) return 2
  return 1
}
let COMPAT = true
let BATCH_UINTS = COMPAT ? 65536 : 128
let BATCH_BYTES = BATCH_UINTS * 4
let BATCH = BATCH_BYTES * 8 // in bits
const MAX_REMOTE_BATCHES = 4
const MAX_RANGE = 8 * 256 * 1024
const MIN_RANGE = 32 // 4bit ints
const MAX = 512
const MAX_ANY = 16

class LocalWants {
  constructor(peer) {
    this.destroyed = false
    this.peer = peer
    this.wants = new Map()
    this.free = new Set()
    this.any = null
  }

  add(index, handle) {
    const b = (index - (index & (BATCH - 1))) / BATCH
    return this.addBatch(b, handle)
  }

  addAnyRange(start, length, handle) {
    if (this.destroyed) return null
    if (this.any === null) this.any = []

    if (COMPAT) {
      let r = start & (BATCH - 1)
      start -= r
      length += r
      r = length & (BATCH - 1)
      if (r) length = length - r + BATCH
    }

    for (let i = 0; i < this.any.length; i++) {
      const w = this.any[i]
      if (w.start === start && w.length === length) {
        w.handles.add(handle)
        handle.addWant(w)
        return null
      }
    }

    const w = { wants: this, start, length, any: true, handles: new Set([handle]) }
    this.any.push(w)
    handle.addWant(w)

    return { start, length, any: !COMPAT }
  }

  removeAnyRange(start, length, handle) {
    if (this.any === null) return null

    for (let i = 0; i < this.any.length; i++) {
      const w = this.any[i]
      if (w.start !== start || w.length !== length) continue

      w.handles.delete(handle)
      handle.removeWant(w)
      if (w.handles.size > 0) return null

      const head = this.any.pop()
      if (head !== w) this.any[i] = head
      return { start, length, any: !COMPAT }
    }

    return null
  }

  addBatch(index, handle) {
    if (this.destroyed) return null
    let w = this.wants.get(index)

    if (w) {
      const size = w.handles.size
      w.handles.add(handle)
      if (w.handles.size !== size) {
        handle.addWant(w)
      }
      return null
    }

    // start here is the batch number for simplicity....
    w = { wants: this, start: index, length: 0, any: false, handles: new Set([handle]) }

    if (this.free.has(index)) {
      this.free.delete(index)
      this.wants.set(index, w)
      handle.addWant(w)
      return null
    }

    let unwant = null
    if (this.wants.size + this.free.size === MAX) {
      if (this.free.size === 0) {
        return null
      }
      unwant = this._unwant()
    }

    this.wants.set(index, w)
    handle.addWant(w)

    return {
      want: { start: index * BATCH, length: BATCH, any: false },
      unwant
    }
  }

  remove(index, handle) {
    const b = (index - (index & (BATCH - 1))) / BATCH
    return this.removeBatch(b, handle)
  }

  removeBatch(index, handle) {
    if (this.destroyed) return false

    const w = this.wants.get(index)
    if (!w) {
      return false
    }

    w.handles.delete(handle)
    handle.removeWant(w)

    if (w.handles.size === 0) {
      this.free.add(index)
      this.wants.delete(index)
      return this.free.size === 1 && this.wants.size === MAX - 1
    }

    return false
  }

  destroy() {
    if (this.destroyed) return
    this.destroyed = true

    for (const w of this.wants.values()) {
      for (const handle of w.handles) {
        handle.removeWant(w)
      }
    }

    this.wants.clear()
  }

  _unwant() {
    for (const index of this.free) {
      this.free.delete(index)
      return { start: index * BATCH, length: BATCH, any: false }
    }
    return null
  }
}

class RemoteWants {
  constructor() {
    this.any = null
    this.all = false
    this.size = 0
    this.batches = []
  }

  hasAny(start, length) {
    for (let i = 0; i < this.any.length; i++) {
      const a = this.any[i]
      const e = start + length
      const end = a.start + a.length

      if (a.start <= start && start < end) return true
      if (a.start < e && e <= end) return true
    }

    return this.all
  }

  hasRange(start, length) {
    if (this.any !== null && this.hasAny(start, length)) return true
    if (length === 1) return this.has(start)

    let smallest = -1

    for (let i = 0; i < this.batches.length; i++) {
      const b = this.batches[i]
      if (b.length < smallest || smallest === -1) smallest = b.length
    }

    if (smallest === -1) return this.all

    const r = start & (smallest - 1)
    const end = start + length

    let max = 3

    for (let i = start - r; i < end; i += smallest) {
      if (max-- === 0) return true // just to save work
      if (this.has(i)) return true
    }

    return this.all
  }

  has(index) {
    for (let i = 0; i < this.batches.length; i++) {
      const b = this.batches[i]
      const block = (index - (index & (b.length - 1))) / b.length
      if (b.ranges.has(block)) return true
    }

    return this.all
  }

  add(range) {
    if (range.any) {
      if (this.any === null) this.any = []
      if (this.any.length < MAX_ANY) this.any.push(range)
      else this.all = true
      return true
    }

    if (range.length > MAX_RANGE) return false

    if (!validateBatchRange(range)) {
      this.all = true
      return true
    }

    if (this.size >= MAX) {
      this.all = true
      return true
    }

    for (let i = 0; i < this.batches.length; i++) {
      const b = this.batches[i]
      if (b.length === range.length) {
        b.ranges.add(range.start / range.length)
        this.size++
        return true
      }
    }

    if (this.batches.length >= MAX_REMOTE_BATCHES) {
      this.all = true
      return true
    }

    this.batches.push({
      length: range.length,
      ranges: new Set([range.start / range.length])
    })
    this.size++

    return true
  }

  remove(range) {
    if (range.any) {
      if (this.any === null) return false

      for (let i = 0; i < this.any.length; i++) {
        const a = this.any[i]

        if (a.start === range.start && a.length === range.length) {
          const head = this.any.pop()
          if (head !== a) this.any[i] = head
          return true
        }
      }

      return false
    }

    if (!validateBatchRange(range)) return false

    for (let i = 0; i < this.batches.length; i++) {
      const b = this.batches[i]
      if (b.length !== range.length) continue

      const size = b.ranges.size
      b.ranges.delete(range.start / range.length)
      if (b.ranges.size !== size) this.size--

      if (b.ranges.size === 0) {
        const head = this.batches.pop()
        if (head !== b) this.batches[i] = head
      }

      return true
    }

    return false
  }
}

function UPDATE_COMPAT(isCompat) {
  COMPAT = isCompat
  BATCH_UINTS = COMPAT ? 65536 : 128
  BATCH_BYTES = BATCH_UINTS * 4
  BATCH = BATCH_BYTES * 8 // in bits
  exports.WANT_BATCH = BATCH
}

exports.LocalWants = LocalWants
exports.RemoteWants = RemoteWants
exports.WANT_BATCH = BATCH
exports.UPDATE_COMPAT = UPDATE_COMPAT

function validateBatchRange(range) {
  if (range.length > MAX_RANGE || range.length < MIN_RANGE) {
    return false
  }
  // check if power of two
  if ((range.length & (range.length - 1)) !== 0) {
    return false
  }
  // start must be a multiple of the length
  if (range.start & (range.length - 1)) {
    return false
  }

  return true
}
{
  "name": "hypercore",
  "version": "11.33.5",
  "description": "Hypercore is a secure, distributed append-only log",
  "main": "index.js",
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "brittle test/all.js",
    "test:bare": "bare test/all.js",
    "test:generate": "brittle -r test/all.js test/*.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/hypercore.git"
  },
  "contributors": [
    {
      "name": "Mathias Buus",
      "email": "mathiasbuus@gmail.com",
      "url": "https://mafinto.sh"
    },
    {
      "name": "Andrew Osheroff",
      "email": "andrewosh@gmail.com",
      "url": "https://andrewosh.com"
    }
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/hypercore/issues"
  },
  "homepage": "https://github.com/holepunchto/hypercore#readme",
  "files": [
    "index.js",
    "errors.js",
    "messages.js",
    "lib/**.js"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "dependencies": {
    "@hyperswarm/secret-stream": "^6.0.0",
    "b4a": "^1.1.0",
    "bare-events": "^2.2.0",
    "big-sparse-array": "^1.0.3",
    "compact-encoding": "^3.0.0",
    "fast-fifo": "^1.3.0",
    "flat-tree": "^1.9.0",
    "hypercore-crypto": "^3.2.1",
    "hypercore-errors": "^1.5.0",
    "hypercore-id-encoding": "^1.2.0",
    "hypercore-storage": "^3.0.0",
    "is-options": "^1.0.1",
    "nanoassert": "^2.0.0",
    "protomux": "^3.5.0",
    "quickbit-universal": "^2.2.0",
    "random-array-iterator": "^1.0.0",
    "safety-catch": "^1.0.1",
    "sodium-universal": "^5.0.1",
    "streamx": "^2.12.4",
    "unslab": "^1.3.0",
    "z32": "^1.0.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "debugging-stream": "^3.1.0",
    "hyperswarm": "^4.3.6",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "rache": "^1.0.0",
    "range-parser": "^1.2.1",
    "resolve-reject-promise": "^1.1.0",
    "speedometer": "^1.1.0",
    "test-tmp": "^1.0.2",
    "tiny-byte-size": "^1.1.0",
    "udx-native": "^1.6.1",
    "uncaughts": "^1.1.0"
  }
}
{
  "name": "hyperschema",
  "version": "1.21.0",
  "description": "Create registries of declarative compact-encoding schemas",
  "files": [
    "lib/*.js",
    "builder.mjs",
    "builder.cjs",
    "runtime.mjs",
    "runtime.cjs",
    "primitives.mjs",
    "primitives.cjs"
  ],
  "exports": {
    "./package": "./package.json",
    ".": {
      "import": "./builder.mjs",
      "default": "./builder.cjs"
    },
    "./runtime": {
      "import": "./runtime.mjs",
      "default": "./runtime.cjs"
    },
    "./primitives": {
      "import": "./primitives.mjs",
      "default": "./primitives.cjs"
    }
  },
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    }
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test/index.js",
    "test:bare": "prettier . --check && bare test/index.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/hyperschema.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/hyperschema/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperschema#readme",
  "dependencies": {
    "bare-fs": "^4.0.1",
    "compact-encoding": "^3.0.0",
    "generate-object-property": "^2.0.0",
    "generate-string": "^1.0.1"
  },
  "devDependencies": {
    "brittle": "^3.7.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "test-tmp": "^1.3.0"
  }
}
module.exports = {
  c: require('compact-encoding')
}
const b4a = require('b4a')

const EMPTY = b4a.alloc(0)
const MAX = b4a.from([0xff])
const BUFFER = {}

BUFFER.preencode = function (state, buf) {
  if (buf === null) buf = EMPTY

  let i = 0
  let extra = 3

  while ((i = b4a.indexOf(buf, 0x00, i)) > -1) {
    i++
    extra++
  }

  state.end += buf.byteLength + extra
}

BUFFER.encode = function (state, buf) {
  if (buf === null) buf = EMPTY

  state.buffer[state.start++] = 0x00

  let prev = 0
  let i = 0

  while ((i = b4a.indexOf(buf, 0x00, i)) > -1) {
    const slice = buf.subarray(prev, ++i)

    state.buffer.set(slice, state.start)
    state.start += slice.byteLength
    state.buffer[state.start++] = 0x02
    prev = i
  }

  const slice = buf.subarray(prev)

  state.buffer.set(slice, state.start)
  state.start += slice.byteLength

  state.buffer[state.start++] = 0x00
  state.buffer[state.start++] = 0x01
}

BUFFER.decode = function (state) {
  if (state.start >= state.end) throw new Error('Out of bounds')
  if (state.buffer[state.start++] !== 0x00) {
    throw new Error('Invalid start of string')
  }

  let escaped = null

  let prev = state.start
  let i = state.start

  while ((i = b4a.indexOf(state.buffer, 0x00, i)) > -1) {
    const next = ++i < state.end ? state.buffer[i] : 0x00

    i++

    if (next === 0x01) {
      break
    }

    if (next === 0x02) {
      if (escaped === null) escaped = []
      escaped.push(state.buffer.subarray(prev, i - 1))
      prev = i
      continue
    }

    throw new Error('Unknown value in terminator')
  }

  if (i === -1) {
    throw new Error('No terminator found')
  }

  state.start = i
  const last = state.buffer.subarray(prev, i - 2)
  if (escaped === null) return last

  escaped.push(last)
  return b4a.concat(escaped)
}

// TODO: can be optimised a lot

const STRING = {}

STRING.preencode = function (state, str) {
  BUFFER.preencode(state, b4a.from(str || ''))
}

STRING.encode = function (state, str) {
  BUFFER.encode(state, b4a.from(str || ''))
}

STRING.decode = function (state, str) {
  return b4a.toString(BUFFER.decode(state))
}

const UINT = {}

UINT.preencode = function (state, n) {
  state.end += n <= 0xfb ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : n === Infinity ? 1 : 9
}

UINT.encode = function (state, n) {
  if (n === Infinity) {
    state.buffer[state.start++] = 0xff
    return
  }

  if (n <= 0xfb) {
    state.buffer[state.start++] = n
    return
  }

  if (n <= 0xffff) {
    state.buffer[state.start++] = 0xfc
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
    return
  }

  if (n <= 0xffffffff) {
    state.buffer[state.start++] = 0xfd
    encodeUint32(state, n)
    return
  }

  if (Number.isSafeInteger(n)) {
    state.buffer[state.start++] = 0xfe

    const r = Math.floor(n / 0x100000000)
    encodeUint32(state, r)
    encodeUint32(state, n)
    return
  }

  throw new Error('Invalid number ' + n)
}

UINT.decode = function (state) {
  if (state.start >= state.end) throw new Error('Out of bounds')

  const a = state.buffer[state.start++]

  if (a <= 0xfb) return a

  if (a === 0xfc) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] * 0x100 + state.buffer[state.start++]
  }

  if (a === 0xfd) {
    return decodeUint32(state)
  }

  if (a === 0xfe) {
    return decodeUint32(state) * 0x100000000 + decodeUint32(state)
  }

  return Infinity
}

const INT = {}

INT.preencode = function (state, n) {
  // One asymmetric condition
  if (n >= -0xff && n < 0) {
    state.end += 2
    return
  }
  n = Math.abs(n)
  state.end += n <= 0xf6 ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : n === Infinity ? 1 : 9
}

INT.encode = function (state, n) {
  if (n === Infinity) {
    state.buffer[state.start++] = 0xff
    return
  }

  if (n === -Infinity) {
    state.buffer[state.start++] = 0x00
    return
  }

  // Negative 64 bit
  if (n < -0xffffffff) {
    if (!Number.isSafeInteger(n)) throw new Error('Invalid number ' + n)
    state.buffer[state.start++] = 0x01

    const r = Math.floor(-n / 0x100000000)
    encodeUint32(state, -r + 0xffffffff)
    encodeUint32(state, -(-n % 0x100000000) + 0xffffffff)
    return
  }

  // Negative 32 bit
  if (n < -0xffff) {
    state.buffer[state.start++] = 0x02

    n += 0xffffffff
    encodeUint32(state, n)
    return
  }

  // Negative 16bit
  if (n < -0xff) {
    state.buffer[state.start++] = 0x03

    n += 0xffff
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
    return
  }

  // Negative 8bit
  if (n < 0) {
    state.buffer[state.start++] = 0x04

    n += 0xff
    state.buffer[state.start++] = n
    return
  }

  // Remainder of 8bit space for positive int
  if (n <= 0xf6) {
    state.buffer[state.start++] = n + 0x05
    return
  }

  // Positive 16bit
  if (n <= 0xffff) {
    state.buffer[state.start++] = 0xfc
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
    return
  }

  // Positive 32bit
  if (n <= 0xffffffff) {
    state.buffer[state.start++] = 0xfd
    encodeUint32(state, n)
    return
  }

  // Positive 64bit
  if (Number.isSafeInteger(n)) {
    state.buffer[state.start++] = 0xfe

    const r = Math.floor(n / 0x100000000)
    encodeUint32(state, r)
    encodeUint32(state, n)
    return
  }

  throw new Error('Invalid number ' + n)
}

INT.decode = function (state) {
  if (state.start >= state.end) throw new Error('Out of bounds')

  const a = state.buffer[state.start++]

  if (a === 0x00) return -Infinity

  if (a === 0x01) {
    // Split (2^64 - 1) into its 32 bit components
    // r * 0x100000000 + n - (2^64 - 1)
    // r * 0x100000000 + n - (0xffffffff * 0x100000000) - 0xffffffff
    // (r - 0xffffffff) * 0x100000000 + n - 0xffffffff
    return (decodeUint32(state) - 0xffffffff) * 0x100000000 + decodeUint32(state) - 0xffffffff
  }

  if (a === 0x02) {
    return decodeUint32(state) - 0xffffffff
  }

  if (a === 0x03) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] * 0x100 + state.buffer[state.start++] - 0xffff
  }

  if (a === 0x04) return state.buffer[state.start++] - 0xff

  if (a <= 0xfb) return a - 0x05

  if (a === 0xfc) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] * 0x100 + state.buffer[state.start++]
  }

  if (a === 0xfd) {
    return decodeUint32(state)
  }

  if (a === 0xfe) {
    return decodeUint32(state) * 0x100000000 + decodeUint32(state)
  }

  return Infinity
}

const DATE = {}

DATE.preencode = (state, d) => INT.preencode(state, d.getTime())
DATE.encode = (state, d) => INT.encode(state, d.getTime())
DATE.decode = (state) => new Date(INT.decode(state))

const BOOL = {}

BOOL.preencode = (state, b) => UINT.preencode(state, b ? 1 : 0)
BOOL.encode = (state, b) => UINT.encode(state, b ? 1 : 0)
BOOL.decode = (state) => !!UINT.decode(state)

module.exports = class IndexEncoder {
  constructor(encodings, { prefix = -1 } = {}) {
    this.encodings = encodings
    this.prefix = prefix
  }

  static BUFFER = BUFFER
  static STRING = STRING
  static UINT = UINT
  static INT = INT
  static DATE = DATE
  static BOOL = BOOL

  static lookup(c) {
    switch (c) {
      case 'uint':
        return UINT
      case 'uint8':
        return UINT
      case 'uint16':
        return UINT
      case 'uint24':
        return UINT
      case 'uint32':
        return UINT
      case 'uint40':
        return UINT
      case 'uint48':
        return UINT
      case 'uint56':
        return UINT
      case 'uint64':
        return UINT
      case 'int':
        return INT
      case 'int8':
        return INT
      case 'int16':
        return INT
      case 'int24':
        return INT
      case 'int32':
        return INT
      case 'int40':
        return INT
      case 'int48':
        return INT
      case 'int56':
        return INT
      case 'int64':
        return INT
      case 'string':
        return STRING
      case 'utf8':
        return STRING
      case 'ascii':
        return STRING
      case 'hex':
        return STRING
      case 'base64':
        return STRING
      case 'fixed32':
        return BUFFER
      case 'fixed64':
        return BUFFER
      case 'buffer':
        return BUFFER
      case 'date':
        return DATE
      case 'bool':
        return BOOL
    }

    throw new Error('Unknown type')
  }

  encode(keys) {
    return this._encode(keys, false)
  }

  _encode(keys, terminate) {
    if (b4a.isBuffer(keys)) return keys

    const state = { start: 0, end: 0, buffer: null }

    if (this.prefix !== -1) UINT.preencode(state, this.prefix)
    for (let i = 0; i < keys.length; i++) {
      this.encodings[i].preencode(state, keys[i])
    }

    if (terminate && keys.length < this.encodings.length) {
      state.end++
    }

    state.buffer = b4a.allocUnsafe(state.end)

    if (this.prefix !== -1) UINT.encode(state, this.prefix)
    for (let i = 0; i < keys.length; i++) {
      this.encodings[i].encode(state, keys[i])
    }

    if (terminate && keys.length < this.encodings.length) {
      state.buffer[state.start++] = MAX[0]
    }

    return state.buffer
  }

  decode(buffer) {
    const state = { start: 0, end: buffer.byteLength, buffer }
    const result = []

    if (this.prefix !== -1) UINT.decode(state)
    for (const enc of this.encodings) {
      const key = state.start < state.end ? enc.decode(state) : enc === UINT ? 0 : null
      result.push(key)
    }

    return result
  }

  encodeRange({ gt, gte, lt, lte }) {
    const range = {
      gt: gt && this._encode(gt, true),
      gte: gte && this._encode(gte, false),
      lt: lt && this._encode(lt, false),
      lte: lte && this._encode(lte, true)
    }

    if (this.prefix !== -1) {
      if (!gt && !gte) range.gte = encodeUint(this.prefix)
      if (!lt && !lte) range.lt = encodeUint(this.prefix + 1)
    }

    return range
  }
}

function encodeUint(n) {
  const state = { start: 0, end: 0, buffer: null }
  UINT.preencode(state, n)
  state.buffer = b4a.allocUnsafe(state.end)
  UINT.encode(state, n)
  return state.buffer
}

function encodeUint32(state, n) {
  state.buffer[state.start++] = n >>> 24
  state.buffer[state.start++] = n >>> 16
  state.buffer[state.start++] = n >>> 8
  state.buffer[state.start++] = n
}

function decodeUint32(state) {
  if (state.end - state.start < 4) throw new Error('Out of bounds')
  return (
    state.buffer[state.start++] * 0x1000000 +
    state.buffer[state.start++] * 0x10000 +
    state.buffer[state.start++] * 0x100 +
    state.buffer[state.start++]
  )
}
{
  "name": "index-encoder",
  "version": "3.5.0",
  "description": "Encode multiple values into sorted keys",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.6.4"
  },
  "devDependencies": {
    "brittle": "^3.2.1",
    "hyperbee": "^2.10.5",
    "hypercore": "^11.0.0",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/index-encoder.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/index-encoder/issues"
  },
  "homepage": "https://github.com/holepunchto/index-encoder"
}
const b4a = require('b4a')

module.exports = function isOptions (opts) {
  return typeof opts === 'object' && opts && !b4a.isBuffer(opts)
}
{
  "name": "is-options",
  "version": "1.0.2",
  "description": "Easily check if input is an options map",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.1.1"
  },
  "devDependencies": {
    "standard": "^11.0.1",
    "tape": "^4.9.0"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/is-options.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/is-options/issues"
  },
  "homepage": "https://github.com/mafintosh/is-options"
}
import { coerce } from '../bytes.js';
import basex from '../vendor/base-x.js';
/**
 * Class represents both BaseEncoder and MultibaseEncoder meaning it
 * can be used to encode to multibase or base encode without multibase
 * prefix.
 */
class Encoder {
    name;
    prefix;
    baseEncode;
    constructor(name, prefix, baseEncode) {
        this.name = name;
        this.prefix = prefix;
        this.baseEncode = baseEncode;
    }
    encode(bytes) {
        if (bytes instanceof Uint8Array) {
            return `${this.prefix}${this.baseEncode(bytes)}`;
        }
        else {
            throw Error('Unknown type, must be binary type');
        }
    }
}
/**
 * Class represents both BaseDecoder and MultibaseDecoder so it could be used
 * to decode multibases (with matching prefix) or just base decode strings
 * with corresponding base encoding.
 */
class Decoder {
    name;
    prefix;
    baseDecode;
    prefixCodePoint;
    constructor(name, prefix, baseDecode) {
        this.name = name;
        this.prefix = prefix;
        const prefixCodePoint = prefix.codePointAt(0);
        /* c8 ignore next 3 */
        if (prefixCodePoint === undefined) {
            throw new Error('Invalid prefix character');
        }
        this.prefixCodePoint = prefixCodePoint;
        this.baseDecode = baseDecode;
    }
    decode(text) {
        if (typeof text === 'string') {
            if (text.codePointAt(0) !== this.prefixCodePoint) {
                throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);
            }
            return this.baseDecode(text.slice(this.prefix.length));
        }
        else {
            throw Error('Can only multibase decode strings');
        }
    }
    or(decoder) {
        return or(this, decoder);
    }
}
class ComposedDecoder {
    decoders;
    constructor(decoders) {
        this.decoders = decoders;
    }
    or(decoder) {
        return or(this, decoder);
    }
    decode(input) {
        const prefix = input[0];
        const decoder = this.decoders[prefix];
        if (decoder != null) {
            return decoder.decode(input);
        }
        else {
            throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);
        }
    }
}
export function or(left, right) {
    return new ComposedDecoder({
        ...(left.decoders ?? { [left.prefix]: left }),
        ...(right.decoders ?? { [right.prefix]: right })
    });
}
export class Codec {
    name;
    prefix;
    baseEncode;
    baseDecode;
    encoder;
    decoder;
    constructor(name, prefix, baseEncode, baseDecode) {
        this.name = name;
        this.prefix = prefix;
        this.baseEncode = baseEncode;
        this.baseDecode = baseDecode;
        this.encoder = new Encoder(name, prefix, baseEncode);
        this.decoder = new Decoder(name, prefix, baseDecode);
    }
    encode(input) {
        return this.encoder.encode(input);
    }
    decode(input) {
        return this.decoder.decode(input);
    }
}
export function from({ name, prefix, encode, decode }) {
    return new Codec(name, prefix, encode, decode);
}
export function baseX({ name, prefix, alphabet }) {
    const { encode, decode } = basex(alphabet, name);
    return from({
        prefix,
        name,
        encode,
        decode: (text) => coerce(decode(text))
    });
}
function decode(string, alphabetIdx, bitsPerChar, name) {
    // Count the padding bytes:
    let end = string.length;
    while (string[end - 1] === '=') {
        --end;
    }
    // Allocate the output:
    const out = new Uint8Array((end * bitsPerChar / 8) | 0);
    // Parse the data:
    let bits = 0; // Number of bits currently in the buffer
    let buffer = 0; // Bits waiting to be written out, MSB first
    let written = 0; // Next byte to write
    for (let i = 0; i < end; ++i) {
        // Read one character from the string:
        const value = alphabetIdx[string[i]];
        if (value === undefined) {
            throw new SyntaxError(`Non-${name} character`);
        }
        // Append the bits to the buffer:
        buffer = (buffer << bitsPerChar) | value;
        bits += bitsPerChar;
        // Write out some bits if the buffer has a byte's worth:
        if (bits >= 8) {
            bits -= 8;
            out[written++] = 0xff & (buffer >> bits);
        }
    }
    // Verify that we have received just enough bits:
    if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {
        throw new SyntaxError('Unexpected end of data');
    }
    return out;
}
function encode(data, alphabet, bitsPerChar) {
    const pad = alphabet[alphabet.length - 1] === '=';
    const mask = (1 << bitsPerChar) - 1;
    let out = '';
    let bits = 0; // Number of bits currently in the buffer
    let buffer = 0; // Bits waiting to be written out, MSB first
    for (let i = 0; i < data.length; ++i) {
        // Slurp data into the buffer:
        buffer = (buffer << 8) | data[i];
        bits += 8;
        // Write out as much as we can:
        while (bits > bitsPerChar) {
            bits -= bitsPerChar;
            out += alphabet[mask & (buffer >> bits)];
        }
    }
    // Partial character:
    if (bits !== 0) {
        out += alphabet[mask & (buffer << (bitsPerChar - bits))];
    }
    // Add padding characters until we hit a byte boundary:
    if (pad) {
        while (((out.length * bitsPerChar) & 7) !== 0) {
            out += '=';
        }
    }
    return out;
}
function createAlphabetIdx(alphabet) {
    // Build the character lookup table:
    const alphabetIdx = {};
    for (let i = 0; i < alphabet.length; ++i) {
        alphabetIdx[alphabet[i]] = i;
    }
    return alphabetIdx;
}
/**
 * RFC4648 Factory
 */
export function rfc4648({ name, prefix, bitsPerChar, alphabet }) {
    const alphabetIdx = createAlphabetIdx(alphabet);
    return from({
        prefix,
        name,
        encode(input) {
            return encode(input, alphabet, bitsPerChar);
        },
        decode(input) {
            return decode(input, alphabetIdx, bitsPerChar, name);
        }
    });
}
//# sourceMappingURL=base.js.mapimport { rfc4648 } from './base.js';
export const base32 = rfc4648({
    prefix: 'b',
    name: 'base32',
    alphabet: 'abcdefghijklmnopqrstuvwxyz234567',
    bitsPerChar: 5
});
export const base32upper = rfc4648({
    prefix: 'B',
    name: 'base32upper',
    alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',
    bitsPerChar: 5
});
export const base32pad = rfc4648({
    prefix: 'c',
    name: 'base32pad',
    alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',
    bitsPerChar: 5
});
export const base32padupper = rfc4648({
    prefix: 'C',
    name: 'base32padupper',
    alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',
    bitsPerChar: 5
});
export const base32hex = rfc4648({
    prefix: 'v',
    name: 'base32hex',
    alphabet: '0123456789abcdefghijklmnopqrstuv',
    bitsPerChar: 5
});
export const base32hexupper = rfc4648({
    prefix: 'V',
    name: 'base32hexupper',
    alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',
    bitsPerChar: 5
});
export const base32hexpad = rfc4648({
    prefix: 't',
    name: 'base32hexpad',
    alphabet: '0123456789abcdefghijklmnopqrstuv=',
    bitsPerChar: 5
});
export const base32hexpadupper = rfc4648({
    prefix: 'T',
    name: 'base32hexpadupper',
    alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',
    bitsPerChar: 5
});
export const base32z = rfc4648({
    prefix: 'h',
    name: 'base32z',
    alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',
    bitsPerChar: 5
});
//# sourceMappingURL=base32.js.mapimport { baseX } from './base.js';
export const base36 = baseX({
    prefix: 'k',
    name: 'base36',
    alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'
});
export const base36upper = baseX({
    prefix: 'K',
    name: 'base36upper',
    alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
});
//# sourceMappingURL=base36.js.mapimport { baseX } from './base.js';
export const base58btc = baseX({
    name: 'base58btc',
    prefix: 'z',
    alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
});
export const base58flickr = baseX({
    name: 'base58flickr',
    prefix: 'Z',
    alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'
});
//# sourceMappingURL=base58.js.mapexport const empty = new Uint8Array(0);
export function toHex(d) {
    return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '');
}
export function fromHex(hex) {
    const hexes = hex.match(/../g);
    return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty;
}
export function equals(aa, bb) {
    if (aa === bb) {
        return true;
    }
    if (aa.byteLength !== bb.byteLength) {
        return false;
    }
    for (let ii = 0; ii < aa.byteLength; ii++) {
        if (aa[ii] !== bb[ii]) {
            return false;
        }
    }
    return true;
}
export function coerce(o) {
    if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') {
        return o;
    }
    if (o instanceof ArrayBuffer) {
        return new Uint8Array(o);
    }
    if (ArrayBuffer.isView(o)) {
        return new Uint8Array(o.buffer, o.byteOffset, o.byteLength);
    }
    throw new Error('Unknown type, must be binary type');
}
export function isBinary(o) {
    return o instanceof ArrayBuffer || ArrayBuffer.isView(o);
}
export function fromString(str) {
    return new TextEncoder().encode(str);
}
export function toString(b) {
    return new TextDecoder().decode(b);
}
//# sourceMappingURL=bytes.js.mapimport { base32 } from './bases/base32.js';
import { base36 } from './bases/base36.js';
import { base58btc } from './bases/base58.js';
import { coerce } from './bytes.js';
import * as Digest from './hashes/digest.js';
import * as varint from './varint.js';
// This way TS will also expose all the types from module
export * from './link/interface.js';
export function format(link, base) {
    const { bytes, version } = link;
    switch (version) {
        case 0:
            return toStringV0(bytes, baseCache(link), base ?? base58btc.encoder);
        default:
            return toStringV1(bytes, baseCache(link), (base ?? base32.encoder));
    }
}
export function toJSON(link) {
    return {
        '/': format(link)
    };
}
export function fromJSON(json) {
    return CID.parse(json['/']);
}
const cache = new WeakMap();
function baseCache(cid) {
    const baseCache = cache.get(cid);
    if (baseCache == null) {
        const baseCache = new Map();
        cache.set(cid, baseCache);
        return baseCache;
    }
    return baseCache;
}
export class CID {
    code;
    version;
    multihash;
    bytes;
    '/';
    /**
     * @param version - Version of the CID
     * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
     * @param multihash - (Multi)hash of the of the content.
     */
    constructor(version, code, multihash, bytes) {
        this.code = code;
        this.version = version;
        this.multihash = multihash;
        this.bytes = bytes;
        // flag to serializers that this is a CID and
        // should be treated specially
        this['/'] = bytes;
    }
    /**
     * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`
     * please either use `CID.asCID(cid)` or switch to new signalling mechanism
     *
     * @deprecated
     */
    get asCID() {
        return this;
    }
    // ArrayBufferView
    get byteOffset() {
        return this.bytes.byteOffset;
    }
    // ArrayBufferView
    get byteLength() {
        return this.bytes.byteLength;
    }
    toV0() {
        switch (this.version) {
            case 0: {
                return this;
            }
            case 1: {
                const { code, multihash } = this;
                if (code !== DAG_PB_CODE) {
                    throw new Error('Cannot convert a non dag-pb CID to CIDv0');
                }
                // sha2-256
                if (multihash.code !== SHA_256_CODE) {
                    throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0');
                }
                return (CID.createV0(multihash));
            }
            default: {
                throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);
            }
        }
    }
    toV1() {
        switch (this.version) {
            case 0: {
                const { code, digest } = this.multihash;
                const multihash = Digest.create(code, digest);
                return (CID.createV1(this.code, multihash));
            }
            case 1: {
                return this;
            }
            default: {
                throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);
            }
        }
    }
    equals(other) {
        return CID.equals(this, other);
    }
    static equals(self, other) {
        const unknown = other;
        return (unknown != null &&
            self.code === unknown.code &&
            self.version === unknown.version &&
            Digest.equals(self.multihash, unknown.multihash));
    }
    toString(base) {
        return format(this, base);
    }
    toJSON() {
        return { '/': format(this) };
    }
    link() {
        return this;
    }
    [Symbol.toStringTag] = 'CID';
    // Legacy
    [Symbol.for('nodejs.util.inspect.custom')]() {
        return `CID(${this.toString()})`;
    }
    /**
     * Takes any input `value` and returns a `CID` instance if it was
     * a `CID` otherwise returns `null`. If `value` is instanceof `CID`
     * it will return value back. If `value` is not instance of this CID
     * class, but is compatible CID it will return new instance of this
     * `CID` class. Otherwise returns null.
     *
     * This allows two different incompatible versions of CID library to
     * co-exist and interop as long as binary interface is compatible.
     */
    static asCID(input) {
        if (input == null) {
            return null;
        }
        const value = input;
        if (value instanceof CID) {
            // If value is instance of CID then we're all set.
            return value;
        }
        else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {
            // If value isn't instance of this CID class but `this.asCID === this` or
            // `value['/'] === value.bytes` is true it is CID instance coming from a
            // different implementation (diff version or duplicate). In that case we
            // rebase it to this `CID` implementation so caller is guaranteed to get
            // instance with expected API.
            const { version, code, multihash, bytes } = value;
            return new CID(version, code, multihash, bytes ?? encodeCID(version, code, multihash.bytes));
        }
        else if (value[cidSymbol] === true) {
            // If value is a CID from older implementation that used to be tagged via
            // symbol we still rebase it to the this `CID` implementation by
            // delegating that to a constructor.
            const { version, multihash, code } = value;
            const digest = Digest.decode(multihash);
            return CID.create(version, code, digest);
        }
        else {
            // Otherwise value is not a CID (or an incompatible version of it) in
            // which case we return `null`.
            return null;
        }
    }
    /**
     * @param version - Version of the CID
     * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
     * @param digest - (Multi)hash of the of the content.
     */
    static create(version, code, digest) {
        if (typeof code !== 'number') {
            throw new Error('String codecs are no longer supported');
        }
        if (!(digest.bytes instanceof Uint8Array)) {
            throw new Error('Invalid digest');
        }
        switch (version) {
            case 0: {
                if (code !== DAG_PB_CODE) {
                    throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);
                }
                else {
                    return new CID(version, code, digest, digest.bytes);
                }
            }
            case 1: {
                const bytes = encodeCID(version, code, digest.bytes);
                return new CID(version, code, digest, bytes);
            }
            default: {
                throw new Error('Invalid version');
            }
        }
    }
    /**
     * Simplified version of `create` for CIDv0.
     */
    static createV0(digest) {
        return CID.create(0, DAG_PB_CODE, digest);
    }
    /**
     * Simplified version of `create` for CIDv1.
     *
     * @param code - Content encoding format code.
     * @param digest - Multihash of the content.
     */
    static createV1(code, digest) {
        return CID.create(1, code, digest);
    }
    /**
     * Decoded a CID from its binary representation. The byte array must contain
     * only the CID with no additional bytes.
     *
     * An error will be thrown if the bytes provided do not contain a valid
     * binary representation of a CID.
     */
    static decode(bytes) {
        const [cid, remainder] = CID.decodeFirst(bytes);
        if (remainder.length !== 0) {
            throw new Error('Incorrect length');
        }
        return cid;
    }
    /**
     * Decoded a CID from its binary representation at the beginning of a byte
     * array.
     *
     * Returns an array with the first element containing the CID and the second
     * element containing the remainder of the original byte array. The remainder
     * will be a zero-length byte array if the provided bytes only contained a
     * binary CID representation.
     */
    static decodeFirst(bytes) {
        const specs = CID.inspectBytes(bytes);
        const prefixSize = specs.size - specs.multihashSize;
        const multihashBytes = coerce(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));
        if (multihashBytes.byteLength !== specs.multihashSize) {
            throw new Error('Incorrect length');
        }
        const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);
        const digest = new Digest.Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);
        const cid = specs.version === 0
            ? CID.createV0(digest)
            : CID.createV1(specs.codec, digest);
        return [cid, bytes.subarray(specs.size)];
    }
    /**
     * Inspect the initial bytes of a CID to determine its properties.
     *
     * Involves decoding up to 4 varints. Typically this will require only 4 to 6
     * bytes but for larger multicodec code values and larger multihash digest
     * lengths these varints can be quite large. It is recommended that at least
     * 10 bytes be made available in the `initialBytes` argument for a complete
     * inspection.
     */
    static inspectBytes(initialBytes) {
        let offset = 0;
        const next = () => {
            const [i, length] = varint.decode(initialBytes.subarray(offset));
            offset += length;
            return i;
        };
        let version = next();
        let codec = DAG_PB_CODE;
        if (version === 18) {
            // CIDv0
            version = 0;
            offset = 0;
        }
        else {
            codec = next();
        }
        if (version !== 0 && version !== 1) {
            throw new RangeError(`Invalid CID version ${version}`);
        }
        const prefixSize = offset;
        const multihashCode = next(); // multihash code
        const digestSize = next(); // multihash length
        const size = offset + digestSize;
        const multihashSize = size - prefixSize;
        return { version, codec, multihashCode, digestSize, multihashSize, size };
    }
    /**
     * Takes cid in a string representation and creates an instance. If `base`
     * decoder is not provided will use a default from the configuration. It will
     * throw an error if encoding of the CID is not compatible with supplied (or
     * a default decoder).
     */
    static parse(source, base) {
        const [prefix, bytes] = parseCIDtoBytes(source, base);
        const cid = CID.decode(bytes);
        if (cid.version === 0 && source[0] !== 'Q') {
            throw Error('Version 0 CID string must not include multibase prefix');
        }
        // Cache string representation to avoid computing it on `this.toString()`
        baseCache(cid).set(prefix, source);
        return cid;
    }
}
function parseCIDtoBytes(source, base) {
    switch (source[0]) {
        // CIDv0 is parsed differently
        case 'Q': {
            const decoder = base ?? base58btc;
            return [
                base58btc.prefix,
                decoder.decode(`${base58btc.prefix}${source}`)
            ];
        }
        case base58btc.prefix: {
            const decoder = base ?? base58btc;
            return [base58btc.prefix, decoder.decode(source)];
        }
        case base32.prefix: {
            const decoder = base ?? base32;
            return [base32.prefix, decoder.decode(source)];
        }
        case base36.prefix: {
            const decoder = base ?? base36;
            return [base36.prefix, decoder.decode(source)];
        }
        default: {
            if (base == null) {
                throw Error('To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided');
            }
            return [source[0], base.decode(source)];
        }
    }
}
function toStringV0(bytes, cache, base) {
    const { prefix } = base;
    if (prefix !== base58btc.prefix) {
        throw Error(`Cannot string encode V0 in ${base.name} encoding`);
    }
    const cid = cache.get(prefix);
    if (cid == null) {
        const cid = base.encode(bytes).slice(1);
        cache.set(prefix, cid);
        return cid;
    }
    else {
        return cid;
    }
}
function toStringV1(bytes, cache, base) {
    const { prefix } = base;
    const cid = cache.get(prefix);
    if (cid == null) {
        const cid = base.encode(bytes);
        cache.set(prefix, cid);
        return cid;
    }
    else {
        return cid;
    }
}
const DAG_PB_CODE = 0x70;
const SHA_256_CODE = 0x12;
function encodeCID(version, code, multihash) {
    const codeOffset = varint.encodingLength(version);
    const hashOffset = codeOffset + varint.encodingLength(code);
    const bytes = new Uint8Array(hashOffset + multihash.byteLength);
    varint.encodeTo(version, bytes, 0);
    varint.encodeTo(code, bytes, codeOffset);
    bytes.set(multihash, hashOffset);
    return bytes;
}
const cidSymbol = Symbol.for('@ipld/js-cid/CID');
//# sourceMappingURL=cid.js.mapimport { coerce, equals as equalBytes } from '../bytes.js';
import * as varint from '../varint.js';
/**
 * Creates a multihash digest.
 */
export function create(code, digest) {
    const size = digest.byteLength;
    const sizeOffset = varint.encodingLength(code);
    const digestOffset = sizeOffset + varint.encodingLength(size);
    const bytes = new Uint8Array(digestOffset + size);
    varint.encodeTo(code, bytes, 0);
    varint.encodeTo(size, bytes, sizeOffset);
    bytes.set(digest, digestOffset);
    return new Digest(code, size, digest, bytes);
}
/**
 * Turns bytes representation of multihash digest into an instance.
 */
export function decode(multihash) {
    const bytes = coerce(multihash);
    const [code, sizeOffset] = varint.decode(bytes);
    const [size, digestOffset] = varint.decode(bytes.subarray(sizeOffset));
    const digest = bytes.subarray(sizeOffset + digestOffset);
    if (digest.byteLength !== size) {
        throw new Error('Incorrect length');
    }
    return new Digest(code, size, digest, bytes);
}
export function equals(a, b) {
    if (a === b) {
        return true;
    }
    else {
        const data = b;
        return (a.code === data.code &&
            a.size === data.size &&
            data.bytes instanceof Uint8Array &&
            equalBytes(a.bytes, data.bytes));
    }
}
/**
 * Represents a multihash digest which carries information about the
 * hashing algorithm and an actual hash digest.
 */
export class Digest {
    code;
    size;
    digest;
    bytes;
    /**
     * Creates a multihash digest.
     */
    constructor(code, size, digest, bytes) {
        this.code = code;
        this.size = size;
        this.digest = digest;
        this.bytes = bytes;
    }
}
/**
 * Used to check that the passed multihash has the passed code
 */
export function hasCode(digest, code) {
    return digest.code === code;
}
//# sourceMappingURL=digest.js.mapexport {};
//# sourceMappingURL=interface.js.mapimport varint from './vendor/varint.js';
export function decode(data, offset = 0) {
    const code = varint.decode(data, offset);
    return [code, varint.decode.bytes];
}
export function encodeTo(int, target, offset = 0) {
    varint.encode(int, target, offset);
    return target;
}
export function encodingLength(int) {
    return varint.encodingLength(int);
}
//# sourceMappingURL=varint.js.map/* eslint-disable */
// base-x encoding / decoding
// Copyright (c) 2018 base-x contributors
// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)
// Distributed under the MIT software license, see the accompanying
// file LICENSE or http://www.opensource.org/licenses/mit-license.php.
/**
 * @param {string} ALPHABET
 * @param {any} name
 */
function base(ALPHABET, name) {
    if (ALPHABET.length >= 255) {
        throw new TypeError('Alphabet too long');
    }
    var BASE_MAP = new Uint8Array(256);
    for (var j = 0; j < BASE_MAP.length; j++) {
        BASE_MAP[j] = 255;
    }
    for (var i = 0; i < ALPHABET.length; i++) {
        var x = ALPHABET.charAt(i);
        var xc = x.charCodeAt(0);
        if (BASE_MAP[xc] !== 255) {
            throw new TypeError(x + ' is ambiguous');
        }
        BASE_MAP[xc] = i;
    }
    var BASE = ALPHABET.length;
    var LEADER = ALPHABET.charAt(0);
    var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up
    var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up
    /**
     * @param {any[] | Iterable<number>} source
     */
    function encode(source) {
        // @ts-ignore
        if (source instanceof Uint8Array)
            ;
        else if (ArrayBuffer.isView(source)) {
            source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
        }
        else if (Array.isArray(source)) {
            source = Uint8Array.from(source);
        }
        if (!(source instanceof Uint8Array)) {
            throw new TypeError('Expected Uint8Array');
        }
        if (source.length === 0) {
            return '';
        }
        // Skip & count leading zeroes.
        var zeroes = 0;
        var length = 0;
        var pbegin = 0;
        var pend = source.length;
        while (pbegin !== pend && source[pbegin] === 0) {
            pbegin++;
            zeroes++;
        }
        // Allocate enough space in big-endian base58 representation.
        var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;
        var b58 = new Uint8Array(size);
        // Process the bytes.
        while (pbegin !== pend) {
            var carry = source[pbegin];
            // Apply "b58 = b58 * 256 + ch".
            var i = 0;
            for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {
                carry += (256 * b58[it1]) >>> 0;
                b58[it1] = (carry % BASE) >>> 0;
                carry = (carry / BASE) >>> 0;
            }
            if (carry !== 0) {
                throw new Error('Non-zero carry');
            }
            length = i;
            pbegin++;
        }
        // Skip leading zeroes in base58 result.
        var it2 = size - length;
        while (it2 !== size && b58[it2] === 0) {
            it2++;
        }
        // Translate the result into a string.
        var str = LEADER.repeat(zeroes);
        for (; it2 < size; ++it2) {
            str += ALPHABET.charAt(b58[it2]);
        }
        return str;
    }
    /**
     * @param {string | string[]} source
     */
    function decodeUnsafe(source) {
        if (typeof source !== 'string') {
            throw new TypeError('Expected String');
        }
        if (source.length === 0) {
            return new Uint8Array();
        }
        var psz = 0;
        // Skip leading spaces.
        if (source[psz] === ' ') {
            return;
        }
        // Skip and count leading '1's.
        var zeroes = 0;
        var length = 0;
        while (source[psz] === LEADER) {
            zeroes++;
            psz++;
        }
        // Allocate enough space in big-endian base256 representation.
        var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.
        var b256 = new Uint8Array(size);
        // Process the characters.
        while (source[psz]) {
            // Decode character
            var carry = BASE_MAP[source.charCodeAt(psz)];
            // Invalid character
            if (carry === 255) {
                return;
            }
            var i = 0;
            for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {
                carry += (BASE * b256[it3]) >>> 0;
                b256[it3] = (carry % 256) >>> 0;
                carry = (carry / 256) >>> 0;
            }
            if (carry !== 0) {
                throw new Error('Non-zero carry');
            }
            length = i;
            psz++;
        }
        // Skip trailing spaces.
        if (source[psz] === ' ') {
            return;
        }
        // Skip leading zeroes in b256.
        var it4 = size - length;
        while (it4 !== size && b256[it4] === 0) {
            it4++;
        }
        var vch = new Uint8Array(zeroes + (size - it4));
        var j = zeroes;
        while (it4 !== size) {
            vch[j++] = b256[it4++];
        }
        return vch;
    }
    /**
     * @param {string | string[]} string
     */
    function decode(string) {
        var buffer = decodeUnsafe(string);
        if (buffer) {
            return buffer;
        }
        throw new Error(`Non-${name} character`);
    }
    return {
        encode: encode,
        decodeUnsafe: decodeUnsafe,
        decode: decode
    };
}
var src = base;
var _brrp__multiformats_scope_baseX = src;
export default _brrp__multiformats_scope_baseX;
//# sourceMappingURL=base-x.js.map/* eslint-disable */
var encode_1 = encode;
var MSB = 0x80, REST = 0x7F, MSBALL = ~REST, INT = Math.pow(2, 31);
/**
 * @param {number} num
 * @param {number[]} out
 * @param {number} offset
 */
function encode(num, out, offset) {
    out = out || [];
    offset = offset || 0;
    var oldOffset = offset;
    while (num >= INT) {
        out[offset++] = (num & 0xFF) | MSB;
        num /= 128;
    }
    while (num & MSBALL) {
        out[offset++] = (num & 0xFF) | MSB;
        num >>>= 7;
    }
    out[offset] = num | 0;
    // @ts-ignore
    encode.bytes = offset - oldOffset + 1;
    return out;
}
var decode = read;
var MSB$1 = 0x80, REST$1 = 0x7F;
/**
 * @param {string | any[]} buf
 * @param {number} offset
 */
function read(buf, offset) {
    var res = 0, offset = offset || 0, shift = 0, counter = offset, b, l = buf.length;
    do {
        if (counter >= l) {
            // @ts-ignore
            read.bytes = 0;
            throw new RangeError('Could not decode varint');
        }
        b = buf[counter++];
        res += shift < 28
            ? (b & REST$1) << shift
            : (b & REST$1) * Math.pow(2, shift);
        shift += 7;
    } while (b >= MSB$1);
    // @ts-ignore
    read.bytes = counter - offset;
    return res;
}
var N1 = Math.pow(2, 7);
var N2 = Math.pow(2, 14);
var N3 = Math.pow(2, 21);
var N4 = Math.pow(2, 28);
var N5 = Math.pow(2, 35);
var N6 = Math.pow(2, 42);
var N7 = Math.pow(2, 49);
var N8 = Math.pow(2, 56);
var N9 = Math.pow(2, 63);
var length = function (/** @type {number} */ value) {
    return (value < N1 ? 1
        : value < N2 ? 2
            : value < N3 ? 3
                : value < N4 ? 4
                    : value < N5 ? 5
                        : value < N6 ? 6
                            : value < N7 ? 7
                                : value < N8 ? 8
                                    : value < N9 ? 9
                                        : 10);
};
var varint = {
    encode: encode_1,
    decode: decode,
    encodingLength: length
};
var _brrp_varint = varint;
export default _brrp_varint;
//# sourceMappingURL=varint.js.map{
  "name": "multiformats",
  "version": "13.4.2",
  "description": "Interface for multihash, multicodec, multibase and CID",
  "author": "Mikeal Rogers <mikeal.rogers@gmail.com> (https://www.mikealrogers.com/)",
  "license": "Apache-2.0 OR MIT",
  "homepage": "https://github.com/multiformats/js-multiformats#readme",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/multiformats/js-multiformats.git"
  },
  "bugs": {
    "url": "https://github.com/multiformats/js-multiformats/issues"
  },
  "publishConfig": {
    "access": "public",
    "provenance": true
  },
  "keywords": [
    "ipfs",
    "ipld",
    "multiformats"
  ],
  "type": "module",
  "types": "./dist/src/index.d.ts",
  "typesVersions": {
    "*": {
      "*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ],
      "src/*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ]
    }
  },
  "files": [
    "src",
    "dist",
    "!dist/test",
    "!**/*.tsbuildinfo"
  ],
  "exports": {
    ".": {
      "types": "./dist/src/index.d.ts",
      "import": "./dist/src/index.js"
    },
    "./bases/base10": {
      "types": "./dist/src/bases/base10.d.ts",
      "import": "./dist/src/bases/base10.js"
    },
    "./bases/base16": {
      "types": "./dist/src/bases/base16.d.ts",
      "import": "./dist/src/bases/base16.js"
    },
    "./bases/base2": {
      "types": "./dist/src/bases/base2.d.ts",
      "import": "./dist/src/bases/base2.js"
    },
    "./bases/base256emoji": {
      "types": "./dist/src/bases/base256emoji.d.ts",
      "import": "./dist/src/bases/base256emoji.js"
    },
    "./bases/base32": {
      "types": "./dist/src/bases/base32.d.ts",
      "import": "./dist/src/bases/base32.js"
    },
    "./bases/base36": {
      "types": "./dist/src/bases/base36.d.ts",
      "import": "./dist/src/bases/base36.js"
    },
    "./bases/base58": {
      "types": "./dist/src/bases/base58.d.ts",
      "import": "./dist/src/bases/base58.js"
    },
    "./bases/base64": {
      "types": "./dist/src/bases/base64.d.ts",
      "import": "./dist/src/bases/base64.js"
    },
    "./bases/base8": {
      "types": "./dist/src/bases/base8.d.ts",
      "import": "./dist/src/bases/base8.js"
    },
    "./bases/identity": {
      "types": "./dist/src/bases/identity.d.ts",
      "import": "./dist/src/bases/identity.js"
    },
    "./bases/interface": {
      "types": "./dist/src/bases/interface.d.ts",
      "import": "./dist/src/bases/interface.js"
    },
    "./basics": {
      "types": "./dist/src/basics.d.ts",
      "import": "./dist/src/basics.js"
    },
    "./block": {
      "types": "./dist/src/block.d.ts",
      "import": "./dist/src/block.js"
    },
    "./block/interface": {
      "types": "./dist/src/block/interface.d.ts",
      "import": "./dist/src/block/interface.js"
    },
    "./bytes": {
      "types": "./dist/src/bytes.d.ts",
      "import": "./dist/src/bytes.js"
    },
    "./cid": {
      "types": "./dist/src/cid.d.ts",
      "import": "./dist/src/cid.js"
    },
    "./codecs/interface": {
      "types": "./dist/src/codecs/interface.d.ts",
      "import": "./dist/src/codecs/interface.js"
    },
    "./codecs/json": {
      "types": "./dist/src/codecs/json.d.ts",
      "import": "./dist/src/codecs/json.js"
    },
    "./codecs/raw": {
      "types": "./dist/src/codecs/raw.d.ts",
      "import": "./dist/src/codecs/raw.js"
    },
    "./hashes/digest": {
      "types": "./dist/src/hashes/digest.d.ts",
      "import": "./dist/src/hashes/digest.js"
    },
    "./hashes/hasher": {
      "types": "./dist/src/hashes/hasher.d.ts",
      "import": "./dist/src/hashes/hasher.js"
    },
    "./hashes/identity": {
      "types": "./dist/src/hashes/identity.d.ts",
      "import": "./dist/src/hashes/identity.js"
    },
    "./hashes/interface": {
      "types": "./dist/src/hashes/interface.d.ts",
      "import": "./dist/src/hashes/interface.js"
    },
    "./hashes/sha1": {
      "types": "./dist/types/src/hashes/sha1.d.ts",
      "browser": "./dist/src/hashes/sha1-browser.js",
      "import": "./dist/src/hashes/sha1.js"
    },
    "./hashes/sha2": {
      "types": "./dist/src/hashes/sha2.d.ts",
      "browser": "./dist/src/hashes/sha2-browser.js",
      "import": "./dist/src/hashes/sha2.js"
    },
    "./interface": {
      "types": "./dist/src/interface.d.ts",
      "import": "./dist/src/interface.js"
    },
    "./link": {
      "types": "./dist/src/link.d.ts",
      "import": "./dist/src/link.js"
    },
    "./link/interface": {
      "types": "./dist/src/link/interface.d.ts",
      "import": "./dist/src/link/interface.js"
    },
    "./traversal": {
      "types": "./dist/src/traversal.d.ts",
      "import": "./dist/src/traversal.js"
    }
  },
  "eslintConfig": {
    "extends": "ipfs",
    "parserOptions": {
      "project": true,
      "sourceType": "module"
    }
  },
  "release": {
    "branches": [
      "master"
    ],
    "plugins": [
      [
        "@semantic-release/commit-analyzer",
        {
          "preset": "conventionalcommits",
          "releaseRules": [
            {
              "breaking": true,
              "release": "major"
            },
            {
              "revert": true,
              "release": "patch"
            },
            {
              "type": "feat",
              "release": "minor"
            },
            {
              "type": "fix",
              "release": "patch"
            },
            {
              "type": "docs",
              "release": "patch"
            },
            {
              "type": "test",
              "release": "patch"
            },
            {
              "type": "deps",
              "release": "patch"
            },
            {
              "scope": "no-release",
              "release": false
            }
          ]
        }
      ],
      [
        "@semantic-release/release-notes-generator",
        {
          "preset": "conventionalcommits",
          "presetConfig": {
            "types": [
              {
                "type": "feat",
                "section": "Features"
              },
              {
                "type": "fix",
                "section": "Bug Fixes"
              },
              {
                "type": "chore",
                "section": "Trivial Changes"
              },
              {
                "type": "docs",
                "section": "Documentation"
              },
              {
                "type": "deps",
                "section": "Dependencies"
              },
              {
                "type": "test",
                "section": "Tests"
              }
            ]
          }
        }
      ],
      "@semantic-release/changelog",
      "@semantic-release/npm",
      "@semantic-release/github",
      [
        "@semantic-release/git",
        {
          "assets": [
            "CHANGELOG.md",
            "package.json"
          ]
        }
      ]
    ]
  },
  "scripts": {
    "clean": "aegir clean",
    "lint": "aegir lint",
    "build": "aegir build",
    "release": "aegir release",
    "docs": "aegir docs",
    "test": "npm run lint && npm run test:node && npm run test:chrome",
    "test:node": "aegir test -t node --cov",
    "test:chrome": "aegir test -t browser --cov",
    "test:chrome-webworker": "aegir test -t webworker",
    "test:firefox": "aegir test -t browser -- --browser firefox",
    "test:firefox-webworker": "aegir test -t webworker -- --browser firefox",
    "test:electron-main": "aegir test -t electron-main"
  },
  "devDependencies": {
    "@stablelib/sha256": "^2.0.0",
    "@stablelib/sha512": "^2.0.0",
    "@types/node": "^25.0.0",
    "aegir": "^47.0.7",
    "buffer": "^6.0.3",
    "cids": "^1.1.9",
    "crypto-hash": "^4.0.0"
  },
  "aegir": {
    "test": {
      "target": [
        "node",
        "browser"
      ]
    }
  },
  "browser": {
    "./hashes/sha1": "./dist/src/hashes/sha1-browser.js",
    "./dist/src/hashes/sha1.js": "./dist/src/hashes/sha1-browser.js",
    "./hashes/sha2": "./dist/src/hashes/sha2-browser.js",
    "./dist/src/hashes/sha2.js": "./dist/src/hashes/sha2-browser.js"
  }
}
module.exports = assert

class AssertionError extends Error {}
AssertionError.prototype.name = 'AssertionError'

/**
 * Minimal assert function
 * @param  {any} t Value to check if falsy
 * @param  {string=} m Optional assertion error message
 * @throws {AssertionError}
 */
function assert (t, m) {
  if (!t) {
    var err = new AssertionError(m)
    if (Error.captureStackTrace) Error.captureStackTrace(err, assert)
    throw err
  }
}
{
  "name": "nanoassert",
  "version": "2.0.0",
  "description": "Nanoscale assertion module",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "tape": "^4.9.1"
  },
  "scripts": {
    "test": "tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/emilbayes/nanoassert.git"
  },
  "keywords": [
    "assert",
    "unassert",
    "power-assert",
    "tiny",
    "nano",
    "pico"
  ],
  "author": "Emil Bay <github@tixz.dk>",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/emilbayes/nanoassert/issues"
  },
  "homepage": "https://github.com/emilbayes/nanoassert#readme"
}
/* eslint-disable camelcase */
const sodium = require('sodium-universal')
const assert = require('nanoassert')
const b4a = require('b4a')

const DHLEN = sodium.crypto_scalarmult_ed25519_BYTES
const PKLEN = sodium.crypto_scalarmult_ed25519_BYTES
const SCALARLEN = sodium.crypto_scalarmult_ed25519_BYTES
const SKLEN = sodium.crypto_sign_SECRETKEYBYTES
const ALG = 'Ed25519'

module.exports = {
  DHLEN,
  PKLEN,
  SCALARLEN,
  SKLEN,
  ALG,
  name: ALG,
  generateKeyPair,
  dh
}

function generateKeyPair (privKey) {
  if (privKey) return generateSeedKeyPair(privKey.subarray(0, 32))

  const keyPair = {}
  keyPair.secretKey = b4a.alloc(SKLEN)
  keyPair.publicKey = b4a.alloc(PKLEN)

  sodium.crypto_sign_keypair(keyPair.publicKey, keyPair.secretKey)
  return keyPair
}

function generateSeedKeyPair (seed) {
  const keyPair = {}
  keyPair.secretKey = b4a.alloc(SKLEN)
  keyPair.publicKey = b4a.alloc(PKLEN)

  sodium.crypto_sign_seed_keypair(keyPair.publicKey, keyPair.secretKey, seed)
  return keyPair
}

function dh (publicKey, { scalar, secretKey }) {
  // tweaked keys expose scalar directly
  if (!scalar) {
    assert(secretKey.byteLength === SKLEN)

    // libsodium stores seed not actual scalar
    const sk = b4a.alloc(64)
    sodium.crypto_hash_sha512(sk, secretKey.subarray(0, 32))
    sk[0] &= 248
    sk[31] &= 127
    sk[31] |= 64

    scalar = sk.subarray(0, 32)
  }

  assert(scalar.byteLength === SCALARLEN)
  assert(publicKey.byteLength === PKLEN)

  const output = b4a.alloc(DHLEN)

  // we clamp if necessary above
  sodium.crypto_scalarmult_ed25519_noclamp(
    output,
    scalar,
    publicKey
  )

  return output
}
{
  "name": "noise-curve-ed",
  "version": "2.1.0",
  "description": "Ed25519 elliptic curve operations for [`noise-handshake`](https://github.com/chm-diederichs/noise-handshake)",
  "main": "index.js",
  "scripts": {
    "test": "npx standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/chm-diederichs/noise-curve-ed.git"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/chm-diederichs/noise-curve-ed/issues"
  },
  "homepage": "https://github.com/chm-diederichs/noise-curve-ed#readme",
  "dependencies": {
    "b4a": "^1.1.0",
    "nanoassert": "^2.0.0",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "noise-handshake": "^3.0.0",
    "standard": "^16.0.3",
    "tape": "^5.2.2"
  }
}
const sodium = require('sodium-universal')
const b4a = require('b4a')

module.exports = class CipherState {
  constructor (key) {
    this.key = key || null
    this.nonce = 0
    this.CIPHER_ALG = 'ChaChaPoly'
  }

  initialiseKey (key) {
    this.key = key
    this.nonce = 0
  }

  setNonce (nonce) {
    this.nonce = nonce
  }

  encrypt (plaintext, ad) {
    if (!this.hasKey) return plaintext
    if (!ad) ad = b4a.alloc(0)

    const ciphertext = encryptWithAD(this.key, this.nonce, ad, plaintext)
    if (ciphertext.length > 65535) throw new Error(`ciphertext length of ${ciphertext.length} exceeds maximum Noise message length of 65535`)
    this.nonce++

    return ciphertext
  }

  decrypt (ciphertext, ad) {
    if (!this.hasKey) return ciphertext
    if (!ad) ad = b4a.alloc(0)
    if (ciphertext.length > 65535) throw new Error(`ciphertext length of ${ciphertext.length} exceeds maximum Noise message length of 65535`)

    const plaintext = decryptWithAD(this.key, this.nonce, ad, ciphertext)
    this.nonce++

    return plaintext
  }

  get hasKey () {
    return this.key !== null
  }

  _clear () {
    sodium.sodium_memzero(this.key)
    this.key = null
    this.nonce = null
  }

  static get MACBYTES () {
    return 16
  }

  static get NONCEBYTES () {
    return 8
  }

  static get KEYBYTES () {
    return 32
  }
}

function encryptWithAD (key, counter, additionalData, plaintext) {
  // for our purposes, additionalData will always be a pubkey so we encode from hex
  if (!b4a.isBuffer(additionalData)) additionalData = b4a.from(additionalData, 'hex')
  if (!b4a.isBuffer(plaintext)) plaintext = b4a.from(plaintext, 'hex')

  const nonce = b4a.alloc(sodium.crypto_aead_chacha20poly1305_ietf_NPUBBYTES)
  const view = new DataView(nonce.buffer, nonce.byteOffset, nonce.byteLength)
  view.setUint32(4, counter, true)

  const ciphertext = b4a.alloc(plaintext.byteLength + sodium.crypto_aead_chacha20poly1305_ietf_ABYTES)

  sodium.crypto_aead_chacha20poly1305_ietf_encrypt(ciphertext, plaintext, additionalData, null, nonce, key)
  return ciphertext
}

function decryptWithAD (key, counter, additionalData, ciphertext) {
  // for our purposes, additionalData will always be a pubkey so we encode from hex
  if (!b4a.isBuffer(additionalData)) additionalData = b4a.from(additionalData, 'hex')
  if (!b4a.isBuffer(ciphertext)) ciphertext = b4a.from(ciphertext, 'hex')

  const nonce = b4a.alloc(sodium.crypto_aead_chacha20poly1305_ietf_NPUBBYTES)
  const view = new DataView(nonce.buffer, nonce.byteOffset, nonce.byteLength)
  view.setUint32(4, counter, true)

  const plaintext = b4a.alloc(ciphertext.byteLength - sodium.crypto_aead_chacha20poly1305_ietf_ABYTES)

  sodium.crypto_aead_chacha20poly1305_ietf_decrypt(plaintext, null, ciphertext, additionalData, nonce, key)
  return plaintext
}
/* eslint-disable camelcase */
const {
  crypto_kx_SEEDBYTES,
  crypto_kx_keypair,
  crypto_kx_seed_keypair,
  crypto_scalarmult_BYTES,
  crypto_scalarmult_SCALARBYTES,
  crypto_scalarmult,
  crypto_scalarmult_base
} = require('sodium-universal')

const assert = require('nanoassert')
const b4a = require('b4a')

const DHLEN = crypto_scalarmult_BYTES
const PKLEN = crypto_scalarmult_BYTES
const SKLEN = crypto_scalarmult_SCALARBYTES
const SEEDLEN = crypto_kx_SEEDBYTES
const ALG = '25519'

module.exports = {
  DHLEN,
  PKLEN,
  SKLEN,
  SEEDLEN,
  ALG,
  generateKeyPair,
  generateSeedKeyPair,
  dh
}

function generateKeyPair (privKey) {
  const keyPair = {}

  keyPair.secretKey = privKey || b4a.alloc(SKLEN)
  keyPair.publicKey = b4a.alloc(PKLEN)

  if (privKey) {
    crypto_scalarmult_base(keyPair.publicKey, keyPair.secretKey)
  } else {
    crypto_kx_keypair(keyPair.publicKey, keyPair.secretKey)
  }

  return keyPair
}

function generateSeedKeyPair (seed) {
  assert(seed.byteLength === SKLEN)

  const keyPair = {}
  keyPair.secretKey = b4a.alloc(SKLEN)
  keyPair.publicKey = b4a.alloc(PKLEN)

  crypto_kx_seed_keypair(keyPair.publicKey, keyPair.secretKey, seed)
  return keyPair
}

function dh (publicKey, { secretKey }) {
  assert(secretKey.byteLength === SKLEN)
  assert(publicKey.byteLength === PKLEN)

  const output = b4a.alloc(DHLEN)

  crypto_scalarmult(
    output,
    secretKey,
    publicKey
  )

  return output
}
const hmacBlake2b = require('./hmac')
const b4a = require('b4a')

const HASHLEN = 64

module.exports = {
  hkdf,
  HASHLEN
}

// HMAC-based Extract-and-Expand KDF
// https://www.ietf.org/rfc/rfc5869.txt

function hkdf (salt, inputKeyMaterial, info = '', length = 2 * HASHLEN) {
  const pseudoRandomKey = hkdfExtract(salt, inputKeyMaterial)
  return hkdfExpand(pseudoRandomKey, info, length)
}

function hkdfExtract (salt, inputKeyMaterial) {
  const hmac = b4a.alloc(HASHLEN)
  return hmacDigest(hmac, salt, inputKeyMaterial)
}

function hkdfExpand (key, info, length) {
  // Put in dedicated slab to avoid keeping shared slab from being gc'ed
  const buffer = b4a.allocUnsafeSlow(length)

  const infoBuf = b4a.from(info)
  let prev = infoBuf

  const result = []
  for (let i = 0; i < length; i += HASHLEN) {
    const pos = b4a.from([(i / HASHLEN) + 1])

    const out = buffer.subarray(i, i + HASHLEN)
    result.push(out)

    prev = hmacDigest(out, key, [prev, infoBuf, pos])
  }

  return result
}

function hmacDigest (out, key, input) {
  hmacBlake2b(out, input, key)
  return out
}
/* eslint-disable camelcase */
const b4a = require('b4a')
const { sodium_memzero, crypto_generichash, crypto_generichash_batch } = require('sodium-universal')

const HASHLEN = 64
const BLOCKLEN = 128
const scratch = b4a.alloc(BLOCKLEN * 3)
const HMACKey = scratch.subarray(BLOCKLEN * 0, BLOCKLEN * 1)
const OuterKeyPad = scratch.subarray(BLOCKLEN * 1, BLOCKLEN * 2)
const InnerKeyPad = scratch.subarray(BLOCKLEN * 2, BLOCKLEN * 3)

// Post-fill is done in the cases where someone caught an exception that
// happened before we were able to clear data at the end

module.exports = function hmac (out, batch, key) {
  if (key.byteLength > BLOCKLEN) {
    crypto_generichash(HMACKey.subarray(0, HASHLEN), key)
    sodium_memzero(HMACKey.subarray(HASHLEN))
  } else {
    // Covers key <= BLOCKLEN
    HMACKey.set(key)
    sodium_memzero(HMACKey.subarray(key.byteLength))
  }

  for (let i = 0; i < HMACKey.byteLength; i++) {
    OuterKeyPad[i] = 0x5c ^ HMACKey[i]
    InnerKeyPad[i] = 0x36 ^ HMACKey[i]
  }
  sodium_memzero(HMACKey)

  crypto_generichash_batch(out, [InnerKeyPad].concat(batch))
  sodium_memzero(InnerKeyPad)
  crypto_generichash_batch(out, [OuterKeyPad, out])
  sodium_memzero(OuterKeyPad)
}

module.exports.BYTES = HASHLEN
module.exports.KEYBYTES = BLOCKLEN
const assert = require('nanoassert')
const b4a = require('b4a')

const SymmetricState = require('./symmetric-state')
const { HASHLEN } = require('./hkdf')

const PRESHARE_IS = Symbol('initiator static key preshared')
const PRESHARE_RS = Symbol('responder static key preshared')

const TOK_PSK = Symbol('psk')

const TOK_S = Symbol('s')
const TOK_E = Symbol('e')

const TOK_ES = Symbol('es')
const TOK_SE = Symbol('se')
const TOK_EE = Symbol('ee')
const TOK_SS = Symbol('ss')

const HANDSHAKES = Object.freeze({
  NN: [
    [TOK_E],
    [TOK_E, TOK_EE]
  ],
  NNpsk0: [
    [TOK_PSK, TOK_E],
    [TOK_E, TOK_EE]
  ],
  XX: [
    [TOK_E],
    [TOK_E, TOK_EE, TOK_S, TOK_ES],
    [TOK_S, TOK_SE]
  ],
  XXpsk0: [
    [TOK_PSK, TOK_E],
    [TOK_E, TOK_EE, TOK_S, TOK_ES],
    [TOK_S, TOK_SE]
  ],
  IK: [
    PRESHARE_RS,
    [TOK_E, TOK_ES, TOK_S, TOK_SS],
    [TOK_E, TOK_EE, TOK_SE]
  ],
  XK: [
    PRESHARE_RS,
    [TOK_E, TOK_ES],
    [TOK_E, TOK_EE],
    [TOK_S, TOK_SE]
  ]
})

class Writer {
  constructor () {
    this.size = 0
    this.buffers = []
  }

  push (b) {
    this.size += b.byteLength
    this.buffers.push(b)
  }

  end () {
    const all = b4a.alloc(this.size)
    let offset = 0
    for (const b of this.buffers) {
      all.set(b, offset)
      offset += b.byteLength
    }
    return all
  }
}

class Reader {
  constructor (buf) {
    this.offset = 0
    this.buffer = buf
  }

  shift (n) {
    const start = this.offset
    const end = this.offset += n
    if (end > this.buffer.byteLength) throw new Error('Insufficient bytes')
    return this.buffer.subarray(start, end)
  }

  end () {
    return this.shift(this.buffer.byteLength - this.offset)
  }
}

module.exports = class NoiseState extends SymmetricState {
  constructor (pattern, initiator, staticKeypair, opts = {}) {
    super(opts)

    this.s = staticKeypair || this.curve.generateKeyPair()
    this.e = null

    this.psk = null
    if (opts && opts.psk) this.psk = opts.psk

    this.re = null
    this.rs = null

    this.pattern = pattern
    this.handshake = HANDSHAKES[this.pattern].slice()

    this.isPskHandshake = !!this.psk && hasPskToken(this.handshake)

    this.protocol = b4a.from([
      'Noise',
      this.pattern,
      this.DH_ALG,
      this.CIPHER_ALG,
      'BLAKE2b'
    ].join('_'))

    this.initiator = initiator
    this.complete = false

    this.rx = null
    this.tx = null
    this.hash = null
  }

  initialise (prologue, remoteStatic) {
    if (this.protocol.byteLength <= HASHLEN) this.digest.set(this.protocol)
    else this.mixHash(this.protocol)

    this.chainingKey = b4a.from(this.digest)

    this.mixHash(prologue)

    while (!Array.isArray(this.handshake[0])) {
      const message = this.handshake.shift()

      // handshake steps should be as arrays, only
      // preshare tokens are provided otherwise
      assert(message === PRESHARE_RS || message === PRESHARE_IS,
        'Unexpected pattern')

      const takeRemoteKey = this.initiator
        ? message === PRESHARE_RS
        : message === PRESHARE_IS

      if (takeRemoteKey) this.rs = remoteStatic

      const key = takeRemoteKey ? this.rs : this.s.publicKey
      assert(key != null, 'Remote pubkey required')

      this.mixHash(key)
    }
  }

  final () {
    const [k1, k2] = this.split()

    this.tx = this.initiator ? k1 : k2
    this.rx = this.initiator ? k2 : k1

    this.complete = true
    this.hash = this.getHandshakeHash()

    this._clear()
  }

  recv (buf) {
    const r = new Reader(buf)

    for (const pattern of this.handshake.shift()) {
      switch (pattern) {
        case TOK_PSK :
          this.mixKeyAndHash(this.psk)
          break

        case TOK_E :
          this.re = r.shift(this.curve.PKLEN)
          this.mixHash(this.re)
          if (this.isPskHandshake) this.mixKeyNormal(this.re)
          break

        case TOK_S : {
          const klen = this.hasKey ? this.curve.PKLEN + 16 : this.curve.PKLEN
          this.rs = this.decryptAndHash(r.shift(klen))
          break
        }

        case TOK_EE :
        case TOK_ES :
        case TOK_SE :
        case TOK_SS : {
          const useStatic = keyPattern(pattern, this.initiator)

          const localKey = useStatic.local ? this.s : this.e
          const remoteKey = useStatic.remote ? this.rs : this.re

          this.mixKey(remoteKey, localKey)
          break
        }

        default :
          throw new Error('Unexpected message')
      }
    }

    const payload = this.decryptAndHash(r.end())

    if (!this.handshake.length) this.final()
    return payload
  }

  send (payload = b4a.alloc(0)) {
    const w = new Writer()

    for (const pattern of this.handshake.shift()) {
      switch (pattern) {
        case TOK_PSK :
          this.mixKeyAndHash(this.psk)
          break

        case TOK_E :
          if (this.e === null) this.e = this.curve.generateKeyPair()
          this.mixHash(this.e.publicKey)
          if (this.isPskHandshake) this.mixKeyNormal(this.e.publicKey)
          w.push(this.e.publicKey)
          break

        case TOK_S :
          w.push(this.encryptAndHash(this.s.publicKey))
          break

        case TOK_ES :
        case TOK_SE :
        case TOK_EE :
        case TOK_SS : {
          const useStatic = keyPattern(pattern, this.initiator)

          const localKey = useStatic.local ? this.s : this.e
          const remoteKey = useStatic.remote ? this.rs : this.re

          this.mixKey(remoteKey, localKey)
          break
        }

        default :
          throw new Error('Unexpected message')
      }
    }

    w.push(this.encryptAndHash(payload))
    const response = w.end()

    if (!this.handshake.length) this.final()
    return response
  }

  _clear () {
    super._clear()

    this.e.secretKey.fill(0)
    this.e.publicKey.fill(0)

    this.re.fill(0)

    this.e = null
    this.re = null
  }
}

function keyPattern (pattern, initiator) {
  const ret = {
    local: false,
    remote: false
  }

  switch (pattern) {
    case TOK_EE:
      return ret

    case TOK_ES:
      ret.local ^= !initiator
      ret.remote ^= initiator
      return ret

    case TOK_SE:
      ret.local ^= initiator
      ret.remote ^= !initiator
      return ret

    case TOK_SS:
      ret.local ^= 1
      ret.remote ^= 1
      return ret
  }
}

function hasPskToken (handshake) {
  return handshake.some(x => {
    return Array.isArray(x) && x.indexOf(TOK_PSK) !== -1
  })
}
{
  "name": "noise-handshake",
  "version": "4.2.0",
  "description": "Noise protocol handshake",
  "main": "noise.js",
  "files": [
    "*.js"
  ],
  "scripts": {
    "test": "standard && brittle test/*.js"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/noise-handshake.git"
  },
  "dependencies": {
    "b4a": "^1.1.0",
    "nanoassert": "^2.0.0",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "noise-protocol": "chm-diederichs/noise-protocol.git#xx-ephemeral-key",
    "standard": "^16.0.3"
  }
}
const sodium = require('sodium-universal')
const assert = require('nanoassert')
const b4a = require('b4a')
const CipherState = require('./cipher')
const curve = require('./dh')
const { HASHLEN, hkdf } = require('./hkdf')

module.exports = class SymmetricState extends CipherState {
  constructor (opts = {}) {
    super()

    this.curve = opts.curve || curve
    this.digest = b4a.alloc(HASHLEN)
    this.chainingKey = null
    this.offset = 0

    this.DH_ALG = this.curve.ALG
  }

  mixHash (data) {
    accumulateDigest(this.digest, data)
  }

  mixKeyAndHash (key) {
    const [ck, tempH, tempK] = hkdf(this.chainingKey, key, '', 3 * HASHLEN)
    this.chainingKey = ck
    this.mixHash(tempH)
    this.initialiseKey(tempK.subarray(0, 32))
  }

  mixKeyNormal (key) {
    const [ck, tempK] = hkdf(this.chainingKey, key)
    this.chainingKey = ck
    this.initialiseKey(tempK.subarray(0, 32))
  }

  mixKey (remoteKey, localKey) {
    const dh = this.curve.dh(remoteKey, localKey)
    const hkdfResult = hkdf(this.chainingKey, dh)
    this.chainingKey = hkdfResult[0]
    this.initialiseKey(hkdfResult[1].subarray(0, 32))
  }

  encryptAndHash (plaintext) {
    const ciphertext = this.encrypt(plaintext, this.digest)
    accumulateDigest(this.digest, ciphertext)
    return ciphertext
  }

  decryptAndHash (ciphertext) {
    const plaintext = this.decrypt(ciphertext, this.digest)
    accumulateDigest(this.digest, ciphertext)
    return plaintext
  }

  getHandshakeHash (out) {
    if (!out) return this.getHandshakeHash(b4a.alloc(HASHLEN))
    assert(out.byteLength === HASHLEN, `output must be ${HASHLEN} bytes`)

    out.set(this.digest)
    return out
  }

  split () {
    const res = hkdf(this.chainingKey, b4a.alloc(0))
    return res.map(k => k.subarray(0, 32))
  }

  _clear () {
    super._clear()

    sodium.sodium_memzero(this.digest)
    sodium.sodium_memzero(this.chainingKey)

    this.digest = null
    this.chainingKey = null
    this.offset = null

    this.curve = null
  }

  static get alg () {
    return CipherState.alg + '_BLAKE2b'
  }
}

function accumulateDigest (digest, input) {
  const toHash = b4a.concat([digest, input])
  sodium.crypto_generichash(digest, toHash)
}
const b4a = require('b4a')
const c = require('compact-encoding')
const queueTick = require('queue-tick')
const safetyCatch = require('safety-catch')
const unslab = require('unslab')

const MAX_BUFFERED = 32768
const MAX_BACKLOG = Infinity // TODO: impl "open" backpressure
const MAX_BATCH = 8 * 1024 * 1024

class Channel {
  constructor(
    mux,
    info,
    userData,
    protocol,
    aliases,
    id,
    handshake,
    messages,
    onopen,
    onclose,
    ondestroy,
    ondrain
  ) {
    this.userData = userData
    this.protocol = protocol
    this.aliases = aliases
    this.id = id
    this.handshake = null
    this.messages = []

    this.opened = false
    this.closed = false
    this.destroyed = false

    this.onopen = onopen
    this.onclose = onclose
    this.ondestroy = ondestroy
    this.ondrain = ondrain

    this._handshake = handshake
    this._mux = mux
    this._info = info
    this._localId = 0
    this._remoteId = 0
    this._active = 0
    this._extensions = null

    this._decBound = this._dec.bind(this)
    this._decAndDestroyBound = this._decAndDestroy.bind(this)

    this._openedPromise = null
    this._openedResolve = null

    this._destroyedPromise = null
    this._destroyedResolve = null

    for (const m of messages) this.addMessage(m)
  }

  get drained() {
    return this._mux.drained
  }

  fullyOpened() {
    if (this.opened) return Promise.resolve(true)
    if (this.closed) return Promise.resolve(false)
    if (this._openedPromise) return this._openedPromise

    this._openedPromise = new Promise((resolve) => {
      this._openedResolve = resolve
    })
    return this._openedPromise
  }

  fullyClosed() {
    if (this.destroyed) return Promise.resolve()
    if (this._destroyedPromise) return this._destroyedPromise

    this._destroyedPromise = new Promise((resolve) => {
      this._destroyedResolve = resolve
    })
    return this._destroyedPromise
  }

  open(handshake) {
    const id = this._mux._free.length > 0 ? this._mux._free.pop() : this._mux._local.push(null) - 1

    this._info.opened++
    this._info.lastChannel = this
    this._localId = id + 1
    this._mux._local[id] = this

    if (this._remoteId === 0) {
      this._info.outgoing.push(this._localId)
    }

    const state = { buffer: null, start: 2, end: 2 }

    c.uint.preencode(state, this._localId)
    c.string.preencode(state, this.protocol)
    c.optionalBuffer.preencode(state, this.id)
    if (this._handshake) this._handshake.preencode(state, handshake)

    state.buffer = this._mux._alloc(state.end)

    state.buffer[0] = 0
    state.buffer[1] = 1
    c.uint.encode(state, this._localId)
    c.string.encode(state, this.protocol)
    c.optionalBuffer.encode(state, this.id)
    if (this._handshake) this._handshake.encode(state, handshake)

    this._mux._write0(state.buffer)
  }

  _dec() {
    if (--this._active === 0 && this.closed === true) this._destroy()
  }

  _decAndDestroy(err) {
    this._dec()
    this._mux._safeDestroy(err)
  }

  _fullyOpenSoon() {
    this._mux._remote[this._remoteId - 1].session = this
    queueTick(this._fullyOpenOrDestroy.bind(this))
  }

  _fullyOpenOrDestroy() {
    try {
      this._fullyOpen()
    } catch (err) {
      this._mux._safeDestroyBound(err)
    }
  }

  _fullyOpen() {
    if (this.opened === true || this.closed === true) return

    const remote = this._mux._remote[this._remoteId - 1]

    this.handshake = this._handshake ? this._handshake.decode(remote.state) : null
    this._track(this.onopen(this.handshake, this))

    remote.session = this
    remote.state = null
    if (remote.pending !== null) this._drain(remote)
    if (this._mux._destroying === true) return

    this.opened = true
    this._resolveOpen(true)
  }

  _resolveOpen(opened) {
    if (this._openedResolve !== null) {
      this._openedResolve(opened)
      this._openedResolve = this._openedPromise = null
    }
  }

  _resolveDestroyed() {
    if (this._destroyedResolve !== null) {
      this._destroyedResolve()
      this._destroyedResolve = this._destroyedPromise = null
    }
  }

  _drain(remote) {
    for (let i = 0; i < remote.pending.length; i++) {
      const p = remote.pending[i]
      this._mux._buffered -= byteSize(p.state)
      this._recv(p.type, p.state)
      if (this._mux._destroying === true) return
    }

    remote.pending = null
    this._mux._resumeMaybe()
  }

  _track(p) {
    if (isPromise(p) === true) {
      this._active++
      return p.then(this._decBound, this._decAndDestroyBound)
    }

    return null
  }

  _close(isRemote) {
    if (this.closed === true) return
    this.closed = true

    this._info.opened--
    if (this._info.lastChannel === this) this._info.lastChannel = null

    if (this._remoteId > 0) {
      this._mux._remote[this._remoteId - 1] = null
      this._remoteId = 0
      // If remote has acked, we can reuse the local id now
      // otherwise, we need to wait for the "ack" to arrive
      this._mux._free.push(this._localId - 1)
    }

    this._mux._local[this._localId - 1] = null
    this._localId = 0

    this._mux._gc(this._info)
    this._track(this.onclose(isRemote, this))

    if (this._active === 0) this._destroy()

    this._resolveOpen(false)
  }

  _destroy() {
    if (this.destroyed === true) return
    this.destroyed = true
    this._track(this.ondestroy(this))
    this._resolveDestroyed()
  }

  _recv(type, state) {
    if (type < this.messages.length) {
      const m = this.messages[type]
      const p = m.recv(state, this)
      if (m.autoBatch === true) return p
    }
    return null
  }

  cork() {
    this._mux.cork()
  }

  uncork() {
    this._mux.uncork()
  }

  close() {
    if (this.closed === true) return

    const state = { buffer: null, start: 2, end: 2 }

    c.uint.preencode(state, this._localId)

    state.buffer = this._mux._alloc(state.end)

    state.buffer[0] = 0
    state.buffer[1] = 3
    c.uint.encode(state, this._localId)

    this._close(false)
    this._mux._write0(state.buffer)
  }

  addMessage(opts) {
    if (!opts) return this._skipMessage()

    const type = this.messages.length
    const autoBatch = opts.autoBatch !== false
    const encoding = opts.encoding || c.raw
    const onmessage = opts.onmessage || noop

    const s = this
    const typeLen = encodingLength(c.uint, type)

    const m = {
      type,
      autoBatch,
      encoding,
      onmessage,
      recv(state, session) {
        return session._track(m.onmessage(encoding.decode(state), session))
      },
      send(m, session = s) {
        if (session.closed === true) return false

        const mux = session._mux
        const state = { buffer: null, start: 0, end: typeLen }

        if (mux._batch !== null) {
          encoding.preencode(state, m)
          state.buffer = mux._alloc(state.end)

          c.uint.encode(state, type)
          encoding.encode(state, m)

          mux._pushBatch(session._localId, state.buffer)
          return true
        }

        c.uint.preencode(state, session._localId)
        encoding.preencode(state, m)

        state.buffer = mux._alloc(state.end)

        c.uint.encode(state, session._localId)
        c.uint.encode(state, type)
        encoding.encode(state, m)

        mux.drained = mux.stream.write(state.buffer)

        return mux.drained
      }
    }

    this.messages.push(m)

    return m
  }

  _skipMessage() {
    const type = this.messages.length
    const m = {
      type,
      encoding: c.raw,
      onmessage: noop,
      recv(state, session) {},
      send(m, session) {}
    }

    this.messages.push(m)
    return m
  }
}

module.exports = class Protomux {
  constructor(stream, { alloc } = {}) {
    if (stream.userData === null) stream.userData = this

    this.isProtomux = true
    this.stream = stream
    this.corked = 0
    this.drained = true

    this._alloc =
      alloc || (typeof stream.alloc === 'function' ? stream.alloc.bind(stream) : b4a.allocUnsafe)
    this._safeDestroyBound = this._safeDestroy.bind(this)
    this._uncorkBound = this.uncork.bind(this)

    this._remoteBacklog = 0
    this._buffered = 0
    this._paused = false
    this._remote = []
    this._local = []
    this._free = []
    this._batch = null
    this._batchState = null

    this._infos = new Map()
    this._notify = new Map()
    // stream.destroyed flips asynchronously on streamx-based transports.
    this._destroying = false

    this.stream.on('data', this._ondata.bind(this))
    this.stream.on('drain', this._ondrain.bind(this))
    this.stream.on('end', this._onend.bind(this))
    this.stream.on('error', noop) // we handle this in "close"
    this.stream.on('close', this._shutdown.bind(this))
  }

  static from(stream, opts) {
    if (stream.userData && stream.userData.isProtomux) return stream.userData
    if (stream.isProtomux) return stream
    return new this(stream, opts)
  }

  static isProtomux(mux) {
    return typeof mux === 'object' && mux.isProtomux === true
  }

  *[Symbol.iterator]() {
    for (const session of this._local) {
      if (session !== null) yield session
    }
  }

  isIdle() {
    return this._local.length === this._free.length
  }

  cork() {
    if (++this.corked === 1) {
      this._batch = []
      this._batchState = { buffer: null, start: 0, end: 1 }
    }
  }

  uncork() {
    if (--this.corked === 0) {
      this._sendBatch(this._batch, this._batchState)
      this._batch = null
      this._batchState = null
    }
  }

  getLastChannel({ protocol, id = null }) {
    const key = toKey(protocol, id)
    const info = this._infos.get(key)
    if (info) return info.lastChannel
    return null
  }

  pair({ protocol, id = null }, notify) {
    this._notify.set(toKey(protocol, id), notify)
  }

  unpair({ protocol, id = null }) {
    this._notify.delete(toKey(protocol, id))
  }

  opened({ protocol, id = null }) {
    const key = toKey(protocol, id)
    const info = this._infos.get(key)
    return info ? info.opened > 0 : false
  }

  createChannel({
    userData = null,
    protocol,
    aliases = [],
    id = null,
    unique = true,
    handshake = null,
    messages = [],
    onopen = noop,
    onclose = noop,
    ondestroy = noop,
    ondrain = noop
  }) {
    if (this.stream.destroyed) return null

    const info = this._get(protocol, id, aliases)
    if (unique && info.opened > 0) return null

    if (info.incoming.length === 0) {
      return new Channel(
        this,
        info,
        userData,
        protocol,
        aliases,
        id,
        handshake,
        messages,
        onopen,
        onclose,
        ondestroy,
        ondrain
      )
    }

    this._remoteBacklog--

    const remoteId = info.incoming.shift()
    const r = this._remote[remoteId - 1]
    if (r === null) return null

    const session = new Channel(
      this,
      info,
      userData,
      protocol,
      aliases,
      id,
      handshake,
      messages,
      onopen,
      onclose,
      ondestroy,
      ondrain
    )

    session._remoteId = remoteId
    session._fullyOpenSoon()

    return session
  }

  _pushBatch(localId, buffer) {
    if (this._batchState.end >= MAX_BATCH) {
      this._sendBatch(this._batch, this._batchState)
      this._batch = []
      this._batchState = { buffer: null, start: 0, end: 1 }
    }

    if (this._batch.length === 0 || this._batch[this._batch.length - 1].localId !== localId) {
      this._batchState.end++
      c.uint.preencode(this._batchState, localId)
    }
    c.buffer.preencode(this._batchState, buffer)
    this._batch.push({ localId, buffer })
  }

  _sendBatch(batch, state) {
    if (batch.length === 0) return

    let prev = batch[0].localId

    state.buffer = this._alloc(state.end)
    state.buffer[state.start++] = 0
    state.buffer[state.start++] = 0

    c.uint.encode(state, prev)

    for (let i = 0; i < batch.length; i++) {
      const b = batch[i]
      if (prev !== b.localId) {
        state.buffer[state.start++] = 0
        c.uint.encode(state, (prev = b.localId))
      }
      c.buffer.encode(state, b.buffer)
    }

    this.drained = this.stream.write(state.buffer)
  }

  _get(protocol, id, aliases = []) {
    const key = toKey(protocol, id)

    let info = this._infos.get(key)
    if (info) return info

    info = {
      key,
      protocol,
      aliases: [],
      id,
      pairing: 0,
      opened: 0,
      incoming: [],
      outgoing: [],
      lastChannel: null
    }
    this._infos.set(key, info)

    for (const alias of aliases) {
      const key = toKey(alias, id)
      info.aliases.push(key)

      this._infos.set(key, info)
    }

    return info
  }

  _gc(info) {
    if (info.opened === 0 && info.outgoing.length === 0 && info.incoming.length === 0) {
      this._infos.delete(info.key)

      for (const alias of info.aliases) this._infos.delete(alias)
    }
  }

  _ondata(buffer) {
    if (buffer.byteLength === 0) return // ignore empty frames...
    try {
      const state = { buffer, start: 0, end: buffer.byteLength }
      this._decode(c.uint.decode(state), state)
    } catch (err) {
      this._safeDestroy(err)
    }
  }

  _ondrain() {
    this.drained = true

    for (const s of this._local) {
      if (s !== null) s._track(s.ondrain(s))
    }
  }

  _onend() {
    // TODO: support half open mode for the users who wants that here
    this.stream.end()
  }

  _decode(remoteId, state) {
    const type = c.uint.decode(state)

    if (remoteId === 0) {
      return this._oncontrolsession(type, state)
    }

    const r = remoteId <= this._remote.length ? this._remote[remoteId - 1] : null

    // if the channel is closed ignore - could just be a pipeline message...
    if (r === null) return null

    if (r.pending !== null) {
      this._bufferMessage(r, type, state)
      return null
    }

    return r.session._recv(type, state)
  }

  _oncontrolsession(type, state) {
    switch (type) {
      case 0:
        this._onbatch(state)
        break

      case 1:
        // return the promise back up as this has sideeffects so we can batch reply
        return this._onopensession(state)

      case 2:
        this._onrejectsession(state)
        break

      case 3:
        this._onclosesession(state)
        break
    }

    return null
  }

  _bufferMessage(r, type, { buffer, start, end }) {
    const state = { buffer, start, end } // copy
    r.pending.push({ type, state })
    this._buffered += byteSize(state)
    this._pauseMaybe()
  }

  _pauseMaybe() {
    if (this._paused === true || this._buffered <= MAX_BUFFERED) return
    this._paused = true
    this.stream.pause()
  }

  _resumeMaybe() {
    if (this._paused === false || this._buffered > MAX_BUFFERED) return
    this._paused = false
    this.stream.resume()
  }

  _onbatch(state) {
    const end = state.end
    let remoteId = c.uint.decode(state)

    let waiting = null

    while (state.end > state.start) {
      const len = c.uint.decode(state)
      if (len === 0) {
        remoteId = c.uint.decode(state)
        continue
      }
      state.end = state.start + len
      // if batch contains more than one message, cork it so we reply back with a batch
      if (end !== state.end && waiting === null) {
        waiting = []
        this.cork()
      }
      const p = this._decode(remoteId, state)
      if (waiting !== null && p !== null) waiting.push(p)
      state.start = state.end
      state.end = end
    }

    if (waiting !== null) {
      // the waiting promises are not allowed to throw but we destroy the stream in case we are wrong
      Promise.all(waiting).then(this._uncorkBound, this._safeDestroyBound)
    }
  }

  _onopensession(state) {
    const remoteId = c.uint.decode(state)
    const protocol = c.string.decode(state)
    const id = unslab(c.optionalBuffer.decode(state))

    // remote tried to open the control session - auto reject for now
    // as we can use as an explicit control protocol declaration if we need to
    if (remoteId === 0) {
      this._rejectSession(0)
      return null
    }

    const rid = remoteId - 1
    const info = this._get(protocol, id)

    // allow the remote to grow the ids by one
    if (this._remote.length === rid) {
      this._remote.push(null)
    }

    if (rid >= this._remote.length || this._remote[rid] !== null) {
      throw new Error('Invalid open message')
    }

    if (info.outgoing.length > 0) {
      const localId = info.outgoing.shift()
      const session = this._local[localId - 1]

      if (session === null) {
        // we already closed the channel - ignore
        this._free.push(localId - 1)
        return null
      }

      this._remote[rid] = { state, pending: null, session: null }

      session._remoteId = remoteId
      session._fullyOpen()
      return null
    }

    const copyState = { buffer: state.buffer, start: state.start, end: state.end }
    this._remote[rid] = { state: copyState, pending: [], session: null }

    if (++this._remoteBacklog > MAX_BACKLOG) {
      throw new Error('Remote exceeded backlog')
    }

    info.pairing++
    info.incoming.push(remoteId)

    return this._requestSession(protocol, id, info).catch(this._safeDestroyBound)
  }

  _onrejectsession(state) {
    const localId = c.uint.decode(state)

    // TODO: can be done smarter...
    for (const info of this._infos.values()) {
      const i = info.outgoing.indexOf(localId)
      if (i === -1) continue

      info.outgoing.splice(i, 1)

      const session = this._local[localId - 1]

      this._free.push(localId - 1)
      if (session !== null) session._close(true)

      this._gc(info)
      return
    }

    throw new Error('Invalid reject message')
  }

  _onclosesession(state) {
    const remoteId = c.uint.decode(state)

    if (remoteId === 0) return // ignore

    const rid = remoteId - 1
    const r = rid < this._remote.length ? this._remote[rid] : null

    if (r === null) return

    if (r.session !== null) r.session._close(true)
  }

  async _requestSession(protocol, id, info) {
    const notify = this._notify.get(toKey(protocol, id)) || this._notify.get(toKey(protocol, null))

    if (notify) await notify(id)

    if (--info.pairing > 0) return

    while (info.incoming.length > 0) {
      this._rejectSession(info, info.incoming.shift())
    }

    this._gc(info)
  }

  _rejectSession(info, remoteId) {
    if (remoteId > 0) {
      const r = this._remote[remoteId - 1]

      if (r.pending !== null) {
        for (let i = 0; i < r.pending.length; i++) {
          this._buffered -= byteSize(r.pending[i].state)
        }
      }

      this._remote[remoteId - 1] = null
      this._resumeMaybe()
    }

    const state = { buffer: null, start: 2, end: 2 }

    c.uint.preencode(state, remoteId)

    state.buffer = this._alloc(state.end)

    state.buffer[0] = 0
    state.buffer[1] = 2
    c.uint.encode(state, remoteId)

    this._write0(state.buffer)
  }

  _write0(buffer) {
    if (this._batch !== null) {
      this._pushBatch(0, buffer.subarray(1))
      return
    }

    this.drained = this.stream.write(buffer)
  }

  destroy(err) {
    this._destroying = true
    this.stream.destroy(err)
  }

  _safeDestroy(err) {
    safetyCatch(err)
    this._destroying = true
    this.stream.destroy(err)
  }

  _shutdown() {
    this._destroying = true
    for (const s of this._local) {
      if (s !== null) s._close(true)
    }
  }
}

function noop() {}

function toKey(protocol, id) {
  return protocol + '##' + (id ? b4a.toString(id, 'hex') : '')
}

function byteSize(state) {
  return 512 + (state.end - state.start)
}

function isPromise(p) {
  return !!(p && typeof p.then === 'function')
}

function encodingLength(enc, val) {
  const state = { buffer: null, start: 0, end: 0 }
  enc.preencode(state, val)
  return state.end
}
{
  "name": "protomux",
  "version": "3.11.0",
  "description": "Multiplex multiple message oriented protocols over a stream",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.3.1",
    "compact-encoding": "^3.0.0",
    "queue-tick": "^1.0.0",
    "safety-catch": "^1.0.1",
    "unslab": "^1.3.0"
  },
  "devDependencies": {
    "@hyperswarm/secret-stream": "^6.0.0",
    "brittle": "^3.0.0",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/protomux.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/protomux/issues"
  },
  "homepage": "https://github.com/holepunchto/protomux"
}
{
  "name": "queue-tick",
  "version": "1.0.1",
  "description": "Next tick shim that prefers process.nextTick over queueMicrotask for compat",
  "main": "./process-next-tick.js",
  "browser": "./queue-microtask.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^16.0.3",
    "tape": "^5.3.1"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/queue-tick.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/queue-tick/issues"
  },
  "homepage": "https://github.com/mafintosh/queue-tick"
}
module.exports = (typeof process !== 'undefined' && typeof process.nextTick === 'function')
  ? process.nextTick.bind(process)
  : require('./queue-microtask')
module.exports = typeof queueMicrotask === 'function' ? queueMicrotask : (fn) => Promise.resolve().then(fn)
require.addon = require('require-addon')

module.exports = require.addon('.', __filename)
const binding = require('./binding')

exports.get = function get(field, bit) {
  const n = field.byteLength * 8

  if (bit < 0) bit += n
  if (bit < 0 || bit >= n) return false

  return binding.quickbit_napi_get(toBuffer(field), bit) !== 0
}

exports.set = function set(field, bit, value = true) {
  const n = field.byteLength * 8

  if (bit < 0) bit += n
  if (bit < 0 || bit >= n) return false

  return binding.quickbit_napi_set(toBuffer(field), bit, value ? 1 : 0) !== 0
}

exports.fill = function fill(
  field,
  value,
  start = 0,
  end = field.byteLength * 8
) {
  const n = field.byteLength * 8

  if (start < 0) start += n
  if (end < 0) end += n
  if (start < 0 || start >= field.byteLength * 8 || start >= end) return field

  binding.quickbit_napi_fill(toBuffer(field), value ? 1 : 0, start, end)
  return field
}

exports.clear = function clear(field, ...chunks) {
  binding.quickbit_napi_clear(toBuffer(field), chunks.map(toBufferChunk))
}

exports.findFirst = function findFirst(field, value, position = 0) {
  const n = field.byteLength * 8

  if (position < 0) position += n
  if (position < 0) position = 0
  if (position >= n) return -1

  return binding.quickbit_napi_find_first(
    toBuffer(field),
    value ? 1 : 0,
    position
  )
}

exports.findLast = function findLast(
  field,
  value,
  position = field.byteLength * 8 - 1
) {
  const n = field.byteLength * 8

  if (position < 0) position += n
  if (position < 0) return -1
  if (position >= n) position = n - 1

  return binding.quickbit_napi_find_last(
    toBuffer(field),
    value ? 1 : 0,
    position
  )
}

function toBuffer(field) {
  if (field.BYTES_PER_ELEMENT === 1) return field
  return new Uint8Array(field.buffer, field.byteOffset, field.byteLength)
}

function toBufferChunk(chunk) {
  return { field: toBuffer(chunk.field), offset: chunk.offset }
}

class Index {
  static from(fieldOrChunks, byteLength = -1) {
    if (Array.isArray(fieldOrChunks)) {
      return new SparseIndex(fieldOrChunks, byteLength)
    } else {
      return new DenseIndex(fieldOrChunks, byteLength)
    }
  }

  constructor(byteLength) {
    this._byteLength = byteLength
    this.handle = Buffer.allocUnsafe(binding.sizeof_quickbit_index_t)
  }

  get byteLength() {
    return this._byteLength
  }

  skipFirst(value, position = 0) {
    const n = this.byteLength * 8

    if (position < 0) position += n
    if (position < 0) position = 0
    if (position >= n) return n - 1

    return binding.quickbit_napi_skip_first(
      this.handle,
      this.byteLength,
      value ? 1 : 0,
      position
    )
  }

  skipLast(value, position = this.byteLength * 8 - 1) {
    const n = this.byteLength * 8

    if (position < 0) position += n
    if (position < 0) return 0
    if (position >= n) position = n - 1

    return binding.quickbit_napi_skip_last(
      this.handle,
      this.byteLength,
      value ? 1 : 0,
      position
    )
  }
}

exports.Index = Index

class DenseIndex extends Index {
  constructor(field, byteLength) {
    super(byteLength)
    this.field = field

    binding.quickbit_napi_index_init(this.handle, toBuffer(this.field))
  }

  get byteLength() {
    if (this._byteLength !== -1) return this._byteLength
    return this.field.byteLength
  }

  update(bit) {
    const n = this.byteLength * 8

    if (bit < 0) bit += n
    if (bit < 0 || bit >= n) return false

    return (
      binding.quickbit_napi_index_update(
        this.handle,
        toBuffer(this.field),
        bit
      ) !== 0
    )
  }
}

function selectChunk(chunks, offset) {
  for (let i = 0; i < chunks.length; i++) {
    const next = chunks[i]

    const start = next.offset
    const end = next.offset + next.field.byteLength

    if (offset >= start && offset + 16 <= end) {
      return next
    }
  }

  return null
}

class SparseIndex extends Index {
  constructor(chunks, byteLength) {
    super(byteLength)
    this.chunks = chunks

    binding.quickbit_napi_index_init_sparse(
      this.handle,
      this.chunks.map(toBufferChunk)
    )
  }

  get byteLength() {
    if (this._byteLength !== -1) return this._byteLength
    const last = this.chunks[this.chunks.length - 1]
    return last ? last.offset + last.field.byteLength : 0
  }

  update(bit) {
    const n = this.byteLength * 8

    if (bit < 0) bit += n
    if (bit < 0 || bit >= n) return false

    const j = Math.floor(bit / 128)

    const offset = j * 16

    const chunk = selectChunk(this.chunks, offset)

    if (chunk === null) return false

    return (
      binding.quickbit_napi_index_update_sparse(
        this.handle,
        toBuffer(chunk.field),
        chunk.offset,
        bit
      ) !== 0
    )
  }
}
{
  "name": "quickbit-native",
  "version": "2.4.8",
  "description": "libquickbit JavaScript bindings for Node.js",
  "main": "index.js",
  "files": [
    "index.js",
    "macros.h",
    "binding.cc",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "npm run lint && npm run test:bare && npm run test:node",
    "test:bare": "bare test.mjs",
    "test:node": "node test.mjs",
    "lint": "prettier . --check"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/quickbit-native.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/quickbit-native/issues"
  },
  "homepage": "https://github.com/holepunchto/quickbit-native#readme",
  "dependencies": {
    "require-addon": "^1.1.0"
  },
  "devDependencies": {
    "b4a": "^1.6.7",
    "bare-compat-napi": "^1.3.2",
    "brittle": "^3.1.0",
    "cmake-bare": "^1.1.7",
    "cmake-fetch": "^1.1.0",
    "cmake-napi": "^1.0.2",
    "prettier": "^3.5.3",
    "prettier-config-standard": "^7.0.0"
  }
}
const simdle = require('simdle-universal')

const INDEX_LEN = (16 /* root */ + 128 * 16 /* children */) * 2

const get = exports.get = function get (field, bit) {
  const n = field.byteLength * 8

  if (bit < 0) bit += n
  if (bit < 0 || bit >= n) return false

  const m = field.BYTES_PER_ELEMENT * 8

  const offset = bit & (m - 1)
  const i = (bit - offset) / m

  return (field[i] & (1 << offset)) !== 0
}

const set = exports.set = function set (field, bit, value = true) {
  const n = field.byteLength * 8

  if (bit < 0) bit += n
  if (bit < 0 || bit >= n) return false

  const m = field.BYTES_PER_ELEMENT * 8

  const offset = bit & (m - 1)
  const i = (bit - offset) / m
  const mask = 1 << offset

  if (value) {
    if ((field[i] & mask) !== 0) return false
  } else {
    if ((field[i] & mask) === 0) return false
  }

  field[i] ^= mask

  return true
}

exports.fill = function fill (field, value, start = 0, end = field.byteLength * 8) {
  const n = field.byteLength * 8

  if (start < 0) start += n
  if (end < 0) end += n
  if (start < 0 || start >= field.byteLength * 8 || start >= end) return field

  const m = field.BYTES_PER_ELEMENT * 8

  let i, j

  {
    const offset = start & (m - 1)
    i = (start - offset) / m

    if (offset !== 0) {
      let shift = m - offset
      if (end - start < shift) shift = end - start

      const mask = ((1 << shift) - 1) << offset

      if (value) field[i] |= mask
      else field[i] &= ~mask

      i++
    }
  }

  {
    const offset = end & (m - 1)
    j = (end - offset) / m

    if (offset !== 0 && j >= i) {
      const mask = (1 << offset) - 1

      if (value) field[j] |= mask
      else field[j] &= ~mask
    }
  }

  if (i < j) field.fill(value ? (2 ** m) - 1 : 0, i, j)

  return field
}

exports.clear = function clear (field, ...chunks) {
  const n = field.byteLength

  for (const chunk of chunks) {
    if (chunk.offset >= n) continue

    const m = chunk.field.byteLength

    let i = chunk.offset
    let j = 0

    while (((i & 15) !== 0 || (j & 15) !== 0) && i < n && j < m) {
      field[i] = field[i] & ~chunk.field[j]
      i++
      j++
    }

    if (i + 15 < n && j + 15 < m) {
      const len = Math.min(n - (n & 15) - i, m - (m & 15) - j)

      simdle.clear(field.subarray(i, i + len), chunk.field.subarray(j, j + len), field.subarray(i, i + len))
    }

    while (i < n && j < m) {
      field[i] = field[i] & ~chunk.field[j]
      i++
      j++
    }
  }
}

function bitOffset (bit, offset) {
  return !bit ? offset : (INDEX_LEN * 8 / 2) + offset
}

function byteOffset (bit, offset) {
  return !bit ? offset : (INDEX_LEN / 2) + offset
}

exports.findFirst = function findFirst (field, value, position = 0) {
  const n = field.byteLength * 8

  if (position < 0) position += n
  if (position < 0) position = 0
  if (position >= n) return -1

  value = !!value

  for (let i = position; i < n; i++) {
    if (get(field, i) === value) return i
  }

  return -1
}

exports.findLast = function findLast (field, value, position = field.byteLength * 8 - 1) {
  const n = field.byteLength * 8

  if (position < 0) position += n
  if (position < 0) return -1
  if (position >= n) position = n - 1

  value = !!value

  for (let i = position; i >= 0; i--) {
    if (get(field, i) === value) return i
  }

  return -1
}

const Index = exports.Index = class Index {
  static from (fieldOrChunks, byteLength = -1) {
    if (Array.isArray(fieldOrChunks)) {
      return new SparseIndex(fieldOrChunks, byteLength)
    } else {
      return new DenseIndex(fieldOrChunks, byteLength)
    }
  }

  constructor (byteLength) {
    this._byteLength = byteLength
    this.handle = new Uint32Array(INDEX_LEN / 4)
  }

  get byteLength () {
    return this._byteLength
  }

  skipFirst (value, position = 0) {
    const n = this.byteLength * 8

    if (position < 0) position += n
    if (position < 0) position = 0
    if (position >= n) return n - 1

    let i = Math.floor(position / 16384)

    if (i > 127) return position

    while (i <= 127 && get(this.handle, bitOffset(value, i))) {
      i++
    }

    if (i === 128) return n - 1

    let k = i * 16384
    let j = 0

    if (position > k) j = Math.floor((position - k) / 128)

    while (j <= 127 && get(this.handle, bitOffset(value, i * 128 + j + 128))) {
      j++
      k += 128
    }

    if (j === 128 && i !== 127) return this.skipFirst(value, (i + 1) * 16384)

    if (k > position) position = k

    return position < n ? position : n - 1
  }

  skipLast (value, position = this.byteLength * 8 - 1) {
    const n = this.byteLength * 8

    if (position < 0) position += n
    if (position < 0) return 0
    if (position >= n) position = n - 1

    let i = Math.floor(position / 16384)

    if (i > 127) return position

    while (i >= 0 && get(this.handle, bitOffset(value, i))) {
      i--
    }

    if (i === -1) return 0

    let k = ((i + 1) * 16384) - 1
    let j = 127

    if (position < k) j = 128 - Math.ceil((k - position) / 128)

    while (j >= 0 && get(this.handle, bitOffset(value, i * 128 + j + 128))) {
      j--
      k -= 128
    }

    if (j === -1 && i !== 0) return this.skipLast(value, i * 16384 - 1)

    if (k < position) position = k

    return position
  }
}

class DenseIndex extends Index {
  constructor (field, byteLength) {
    super(byteLength)
    this.field = field

    const m = field.BYTES_PER_ELEMENT

    for (let i = 0; i < 128; i++) {
      for (let j = 0; j < 128; j++) {
        const offset = (i * 128 + j) * 16
        let allz = true
        let allo = false

        if (offset + 16 <= this.field.byteLength) {
          const vec = this.field.subarray(offset / m, (offset + 16) / m)

          allz = simdle.allz(vec)
          allo = simdle.allo(vec)
        }

        const k = i * 128 + 128 + j

        set(this.handle, bitOffset(false, k), allz)
        set(this.handle, bitOffset(true, k), allo)
      }

      {
        const offset = byteOffset(false, i * 16 + 16) / 4
        const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

        set(this.handle, bitOffset(false, i), allo)
      }

      {
        const offset = byteOffset(true, i * 16 + 16) / 4
        const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

        set(this.handle, bitOffset(true, i), allo)
      }
    }
  }

  get byteLength () {
    if (this._byteLength !== -1) return this._byteLength
    return this.field.byteLength
  }

  update (bit) {
    const n = this.byteLength * 8

    if (bit < 0) bit += n
    if (bit < 0 || bit >= n) return false

    const m = this.field.BYTES_PER_ELEMENT

    const i = Math.floor(bit / 16384)
    const j = Math.floor(bit / 128)

    const offset = (j * 16) / m
    const vec = this.field.subarray(offset, offset + (16 / m))

    const allz = simdle.allz(vec)
    const allo = simdle.allo(vec)

    let changed = false

    if (set(this.handle, bitOffset(false, 128 + j), allz)) {
      changed = true

      const offset = byteOffset(false, i * 16 + 16) / 4
      const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

      set(this.handle, bitOffset(false, i), allo)
    }

    if (set(this.handle, bitOffset(true, 128 + j), allo)) {
      changed = true

      const offset = byteOffset(true, i * 16 + 16) / 4
      const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

      set(this.handle, bitOffset(true, i), allo)
    }

    return changed
  }
}

function selectChunk (chunks, offset) {
  for (let i = 0; i < chunks.length; i++) {
    const next = chunks[i]

    const start = next.offset
    const end = next.offset + next.field.byteLength

    if (offset >= start && offset + 16 <= end) {
      return next
    }
  }

  return null
}

class SparseIndex extends Index {
  constructor (chunks, byteLength) {
    super(byteLength)
    this.chunks = chunks

    for (let i = 0; i < 128; i++) {
      for (let j = 0; j < 128; j++) {
        const offset = (i * 128 + j) * 16
        let allz = true
        let allo = false

        const chunk = selectChunk(this.chunks, offset)

        if (chunk !== null) {
          const m = chunk.field.BYTES_PER_ELEMENT

          const vec = chunk.field.subarray((offset - chunk.offset) / m, (offset - chunk.offset + 16) / m)

          allz = simdle.allz(vec)
          allo = simdle.allo(vec)
        }

        const k = i * 128 + 128 + j

        set(this.handle, bitOffset(false, k), allz)
        set(this.handle, bitOffset(true, k), allo)
      }

      {
        const offset = byteOffset(false, i * 16 + 16) / 4
        const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

        set(this.handle, bitOffset(false, i), allo)
      }

      {
        const offset = byteOffset(true, i * 16 + 16) / 4
        const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

        set(this.handle, bitOffset(true, i), allo)
      }
    }
  }

  get byteLength () {
    if (this._byteLength !== -1) return this._byteLength
    const last = this.chunks[this.chunks.length - 1]
    return last ? last.offset + last.field.byteLength : 0
  }

  update (bit) {
    const n = this.byteLength * 8

    if (bit < 0) bit += n
    if (bit < 0 || bit >= n) return false

    const i = Math.floor(bit / 16384)
    const j = Math.floor(bit / 128)

    const offset = j * 16

    const chunk = selectChunk(this.chunks, offset)

    if (chunk === null) return false

    const m = chunk.field.BYTES_PER_ELEMENT

    const vec = chunk.field.subarray((offset - chunk.offset) / m, (offset - chunk.offset + 16) / m)

    const allz = simdle.allz(vec)
    const allo = simdle.allo(vec)

    let changed = false

    if (set(this.handle, bitOffset(false, 128 + j), allz)) {
      changed = true

      const offset = byteOffset(false, i * 16 + 16) / 4
      const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

      set(this.handle, bitOffset(false, i), allo)
    }

    if (set(this.handle, bitOffset(true, 128 + j), allo)) {
      changed = true

      const offset = byteOffset(true, i * 16 + 16) / 4
      const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

      set(this.handle, bitOffset(true, i), allo)
    }

    return changed
  }
}
const fallback = require('./fallback')

try {
  const native = require('quickbit-native')

  // These functions are faster in JavaScript
  exports.get = fallback.get
  exports.set = fallback.set
  exports.fill = fallback.fill

  // These functions are faster in C
  exports.clear = native.clear
  exports.findFirst = native.findFirst
  exports.findLast = native.findLast
  exports.Index = native.Index
} catch {
  module.exports = fallback
}
{
  "name": "quickbit-universal",
  "version": "2.2.0",
  "description": "Universal wrapper for libquickbit with a JavaScript fallback",
  "main": "index.js",
  "files": [
    "fallback.js",
    "index.js"
  ],
  "browser": {
    "./index.js": "./fallback.js"
  },
  "scripts": {
    "test": "standard && brittle test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/quickbit-universal.git"
  },
  "author": "Kasper Isager Dalsgarð <kasper@funktionel.co>",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/holepunchto/quickbit-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/quickbit-universal#readme",
  "dependencies": {
    "b4a": "^1.6.0",
    "simdle-universal": "^1.1.0"
  },
  "optionalDependencies": {
    "quickbit-native": "^2.2.0"
  },
  "devDependencies": {
    "brittle": "^3.1.0",
    "standard": "^17.0.0"
  }
}
module.exports = class RandomArrayIterator {
  constructor (values) {
    this.values = values
    this.start = 0
    this.length = this.values.length
  }

  next () {
    if (this.length === 0) {
      if (this.start === 0) return { done: true, value: undefined }
      this.length = this.start
      this.start = 0
    }

    const i = this.start + ((Math.random() * this.length) | 0)
    const j = this.start + --this.length
    const value = this.values[i]

    this.values[i] = this.values[j]
    this.values[j] = value

    return { done: false, value }
  }

  dequeue () {
    this.values[this.start + this.length] = this.values[this.values.length - 1]
    this.values.pop()
  }

  requeue () {
    const i = this.start + this.length
    const value = this.values[i]
    this.values[i] = this.values[this.start]
    this.values[this.start++] = value
  }

  restart () {
    this.start = 0
    this.length = this.values.length
    return this
  }

  [Symbol.iterator] () {
    return this
  }
}
{
  "name": "random-array-iterator",
  "version": "1.0.0",
  "description": "An iterator to iterate an array in random order with controls to requeue or dequeue elements during the iteration",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^16.0.3",
    "tape": "^5.0.1"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/random-array-iterator.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/random-array-iterator/issues"
  },
  "homepage": "https://github.com/mafintosh/random-array-iterator"
}
const EventEmitter = require('events')

module.exports = class ReadyResource extends EventEmitter {
  constructor () {
    super()

    this.opening = null
    this.closing = null

    this.opened = false
    this.closed = false
  }

  ready () {
    if (this.opening !== null) return this.opening
    this.opening = open(this)
    return this.opening
  }

  close () {
    if (this.closing !== null) return this.closing
    this.closing = close(this)
    return this.closing
  }

  async _open () {
    // add impl here
  }

  async _close () {
    // add impl here
  }
}

async function open (self) {
  // open after close
  if (self.closing !== null) return

  try {
    await self._open()
  } catch (err) {
    self.close() // safe to run in bg
    throw err
  }

  self.opened = true
  self.emit('ready')
}

async function close (self) {
  try {
    if (self.opened === false && self.opening !== null) await self.opening
  } catch {
    // ignore errors on closing
  }
  if (self.opened === true || self.opening === null) await self._close()
  self.closed = true
  self.emit('close')
}
{
  "name": "ready-resource",
  "version": "1.2.0",
  "description": "Modern single resource management",
  "main": "index.js",
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "types": "index.d.ts",
  "files": [
    "index.js",
    "index.d.ts"
  ],
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "devDependencies": {
    "brittle": "^3.1.0",
    "standard": "^17.0.0"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/ready-resource.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/ready-resource/issues"
  },
  "homepage": "https://github.com/holepunchto/ready-resource",
  "dependencies": {
    "bare-events": "^2.2.0"
  }
}
module.exports = class RefCounter {
  constructor() {
    this.count = 0

    this._onidle = null
    this._idle = null
  }

  isIdle() {
    return this.count === 0
  }

  idle() {
    if (this.count === 0) return Promise.resolve()
    if (this._idle !== null) return this._idle

    this._idle = new Promise((resolve) => {
      this._onidle = resolve
    })

    return this._idle
  }

  inc() {
    this.count++
  }

  dec() {
    if (--this.count > 0) return

    if (this._onidle !== null) {
      const resolve = this._onidle
      this._idle = null
      this._onidle = null
      resolve()
    }
  }
}
{
  "name": "refcounter",
  "version": "1.0.0",
  "description": "Simple refcounter",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {},
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/refcounter.git"
  },
  "author": "Holepunch Inc",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/refcounter/issues"
  },
  "homepage": "https://github.com/holepunchto/refcounter"
}
module.exports = require.addon.bind(require)
{
  "name": "require-addon",
  "version": "1.2.0",
  "description": "Import native addons across JavaScript runtimes",
  "exports": {
    "./package": "./package.json",
    ".": {
      "bare": "./lib/bare.js",
      "node": "./lib/node.js",
      "default": "./lib/default.js"
    }
  },
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    },
    "url": {
      "bare": "bare-url",
      "default": "url"
    }
  },
  "files": [
    "lib"
  ],
  "scripts": {
    "test": "npm run lint && npm run test:bare && npm run test:node",
    "test:bare": "bare test.js",
    "test:node": "node test.js",
    "lint": "prettier --check .",
    "format": "prettier --write ."
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/require-addon.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/require-addon/issues"
  },
  "homepage": "https://github.com/holepunchto/require-addon#readme",
  "engines": {
    "bare": ">=1.10.0"
  },
  "dependencies": {
    "bare-addon-resolve": "^1.3.0"
  },
  "devDependencies": {
    "bare-bundle": "^1.8.1",
    "bare-bundle-evaluate": "^1.1.0",
    "bare-fs": "^4.0.0",
    "bare-path": "^3.0.0",
    "bare-url": "^2.1.0",
    "brittle": "^3.7.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
let tmpResolve = null
let tmpReject = null

if (Promise.withResolvers) {
  module.exports = Promise.withResolvers.bind(Promise)
} else {
  module.exports = function resolveRejectPromise () {
    const promise = new Promise(setTmp)
    const result = { promise, resolve: tmpResolve, reject: tmpReject }
    tmpResolve = tmpReject = null
    return result
  }
}

function setTmp (resolve, reject) {
  tmpResolve = resolve
  tmpReject = reject
}
{
  "name": "resolve-reject-promise",
  "version": "1.1.0",
  "description": "Create an inverted promise with no function allocs",
  "main": "index.js",
  "scripts": {
    "test": "standard"
  },
  "devDependencies": {
    "standard": "^17.1.2"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/resolve-reject-promise.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/resolve-reject-promise/issues"
  },
  "homepage": "https://github.com/mafintosh/resolve-reject-promise"
}
const resources = new Map()

exports.add = function(resource, teardown) {
  resources.set(resource, teardown)
}

exports.remove = function(resource) {
  resources.delete(resource)
}

if (global.Bare) global.Bare.on('exit', run)
else global.process.on('exit', run)

function run() {
  for (const [resource, teardown] of resources) {
    teardown(resource)
  }
}
{
  "name": "resource-on-exit",
  "version": "1.0.0",
  "description": "Register sync teardown handlers for a resource",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {},
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/bare-teardown.git"
  },
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-teardown/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-teardown"
}
require.addon = require('require-addon')

module.exports = require.addon('.', __filename)
const ColumnFamily = require('./lib/column-family')
const Iterator = require('./lib/iterator')
const Snapshot = require('./lib/snapshot')
const State = require('./lib/state')
const { BloomFilterPolicy, RibbonFilterPolicy } = require('./lib/filter-policy')
const constants = require('./lib/constants')

class RocksDB {
  constructor(path, opts = {}) {
    const {
      columnFamily,
      state = new State(this, path, opts),
      snapshot = null,
      keyEncoding = null,
      valueEncoding = null
    } = opts

    this._state = state
    this._snapshot = snapshot
    this._columnFamily = state.getColumnFamily(columnFamily)
    this._keyEncoding = keyEncoding
    this._valueEncoding = valueEncoding
    this._index = -1

    this._state.addSession(this)
  }

  get opened() {
    return this._state.opened
  }

  get closed() {
    return this.isRoot() ? this._state.closed : this._index === -1
  }

  get path() {
    return this._state.path
  }

  get stats() {
    return this._state.stats
  }

  get snapshotted() {
    return this._snapshot !== null
  }

  get defaultColumnFamily() {
    return this._columnFamily
  }

  session({
    columnFamily = this._columnFamily,
    snapshot = this._snapshot !== null,
    keyEncoding = this._keyEncoding,
    valueEncoding = this._valueEncoding
  } = {}) {
    maybeClosed(this)

    return new RocksDB(null, {
      state: this._state,
      columnFamily,
      snapshot: snapshot ? this._snapshot || new Snapshot(this._state) : null,
      keyEncoding,
      valueEncoding
    })
  }

  columnFamily(name, opts) {
    return this.session({ ...opts, columnFamily: name })
  }

  snapshot() {
    return this.session({ snapshot: true })
  }

  isRoot() {
    return this === this._state.db
  }

  ready() {
    return this._state.ready()
  }

  async close({ force } = {}) {
    if (!this._state.opened) await this._state.ready()

    if (this._index !== -1) this._state.removeSession(this)

    if (force) {
      while (this._state.sessions.length > 0) {
        await this._state.sessions[this._state.sessions.length - 1].close()
      }
    }

    return this.isRoot() ? this._state.close() : Promise.resolve()
  }

  suspend() {
    maybeClosed(this)

    return this._state.suspend()
  }

  resume() {
    maybeClosed(this)

    return this._state.resume()
  }

  isIdle() {
    return this._state.handles.isIdle()
  }

  idle() {
    return this._state.handles.idle()
  }

  iterator(range, opts) {
    maybeClosed(this)

    return new Iterator(this, { ...range, ...opts })
  }

  async *keys(range, opts) {
    for await (const { key } of this.iterator(range, {
      ...opts,
      values: false
    })) {
      yield key
    }
  }

  async peek(range, opts) {
    for await (const value of this.iterator({ ...range, ...opts, limit: 1 })) {
      return value
    }

    return null
  }

  read(opts) {
    maybeClosed(this)

    return this._state.createReadBatch(this, opts)
  }

  write(opts) {
    maybeClosed(this)

    return this._state.createWriteBatch(this, opts)
  }

  flush(opts) {
    maybeClosed(this)

    return this._state.flush(this, opts)
  }

  async get(key, opts) {
    const batch = this.read({ ...opts, capacity: 1, autoDestroy: true })
    const value = batch.get(key)
    batch.tryFlush()
    return value
  }

  async put(key, value, opts) {
    const batch = this.write({ ...opts, capacity: 1, autoDestroy: true })
    batch.tryPut(key, value)
    await batch.flush()
  }

  async delete(key, opts) {
    const batch = this.write({ ...opts, capacity: 1, autoDestroy: true })
    batch.tryDelete(key)
    await batch.flush()
  }

  async deleteRange(start, end, opts) {
    const batch = this.write({ ...opts, capacity: 1, autoDestroy: true })
    batch.tryDeleteRange(start, end)
    await batch.flush()
  }

  async compact(opts = {}) {
    maybeClosed(this)

    await this._state.compact(this, opts)
  }

  async compactRange(start = null, end = null, opts = {}) {
    if (typeof end === 'object' && end !== null) {
      opts = end
      end = null
    } else if (typeof start === 'object' && start !== null) {
      opts = start
      start = null
      end = null
    }

    await this._state.compactRange(this, start, end, opts)
  }

  async approximateSize(start, end, opts = {}) {
    return this._state.approximateSize(this, start, end, opts)
  }

  async currentWalFile() {
    maybeClosed(this)

    return this._state.currentWalFile()
  }

  async getStatsLevel() {
    maybeClosed(this)

    return this._state.getStatsLevel()
  }

  async setStatsLevel(level) {
    maybeClosed(this)

    await this._state.setStatsLevel(level)
  }

  async getProperty(name) {
    maybeClosed(this)

    return this._state.getProperty(name)
  }

  _ref() {
    if (this._snapshot) this._snapshot.ref()
    this._state.handles.inc()
  }

  _unref() {
    if (this._snapshot) this._snapshot.unref()
    this._state.handles.dec()
  }

  diagnostics() {
    return this._state.diagnostics()
  }
}

module.exports = exports = RocksDB

exports.constants = constants

exports.ColumnFamily = ColumnFamily
exports.BloomFilterPolicy = BloomFilterPolicy
exports.RibbonFilterPolicy = RibbonFilterPolicy

function maybeClosed(db) {
  if (db._state.closing || db._index === -1) throw new Error('RocksDB session is closed')
}
const c = require('compact-encoding')
const binding = require('../binding')

const empty = Buffer.alloc(0)
const resolved = Promise.resolve()

class RocksDBBatch {
  constructor(db, opts = {}) {
    const { capacity = 8, autoDestroy = false } = opts

    db._ref()

    this._db = db
    this._destroyed = false
    this._capacity = capacity
    this._operations = []
    this._promises = []

    this._enqueuePromise = this._enqueuePromise.bind(this)

    this._request = null
    this._resolve = null
    this._reject = null

    this._handle = null
    this._buffer = null
    this._autoDestroy = autoDestroy
    this._stats = null

    this._resetStats()

    if (db._state.opened === true) this.ready()
  }

  _reuse(db, opts = {}) {
    const { autoDestroy = false } = opts

    db._ref()

    this._db = db
    this._destroyed = false
    this._autoDestroy = autoDestroy
  }

  _onfinished(err) {
    const resolve = this._resolve
    const reject = this._reject

    if (this._request) this._db._state.io.dec()

    this._operations = []
    this._promises = []
    this._request = null
    this._resolve = null
    this._reject = null

    this._resetStats()

    if (this._autoDestroy === true) this.destroy()

    if (reject !== null && err) reject(err)
    else if (resolve !== null) resolve()
  }

  _resize() {
    if (this._operations.length <= this._capacity) return false

    while (this._operations.length > this._capacity) {
      this._capacity *= 2
    }

    return true
  }

  async ready() {
    if (this._handle !== null) return

    if (this._db._state.opened === false) await this._db._state.ready()

    this._init()
  }

  destroy() {
    if (this._request) throw new Error('Request in progress')
    if (this._destroyed) return

    this._destroyed = true

    if (this._promises.length) this._abort()

    this._db._unref()
    this._onfree()
  }

  _onfree() {
    this._resetStats()
    this._db._state.freeBatch(this, false)
    this._db = null
  }

  _abort() {
    for (let i = 0; i < this._promises.length; i++) {
      const promise = this._promises[i]
      if (promise !== null) promise.reject(new Error('Batch is destroyed'))
    }

    this._onfinished(new Error('Batch is destroyed'))
  }

  _resetStats() {}

  async flush() {
    if (this._request) throw new Error('Request in progress')
    if (this._destroyed) throw new Error('Batch is destroyed')

    this._request = new Promise((resolve, reject) => {
      this._resolve = resolve
      this._reject = reject
    })

    this._flush()

    return this._request
  }

  tryFlush() {
    if (this._request) throw new Error('Request in progress')
    if (this._destroyed) throw new Error('Batch is destroyed')

    this._request = resolved

    this._flush()
  }

  async _flush() {
    if (this._handle === null) await this.ready()

    this._db._state.io.inc()

    if (this._db._state.resumed !== null) {
      const resumed = await this._db._state.resumed.promise

      if (!resumed) {
        if (this._destroyed) {
          this._db._state.io.dec()
        } else {
          this._destroyed = true
          this._abort()
          this._db._unref()
        }
      }
    }
  }

  _enqueuePromise(resolve, reject) {
    this._promises.push({ resolve, reject })
  }

  _encodeKey(k) {
    if (this._db._keyEncoding) return c.encode(this._db._keyEncoding, k)
    if (typeof k === 'string') return Buffer.from(k)
    return k
  }

  _encodeValue(v) {
    if (this._db._valueEncoding) return c.encode(this._db._valueEncoding, v)
    if (v === null) return empty
    if (typeof v === 'string') return Buffer.from(v)
    return v
  }

  _decodeValue(b) {
    if (this._db._valueEncoding) return c.decode(this._db._valueEncoding, b)
    return b
  }
}

exports.ReadBatch = class RocksDBReadBatch extends RocksDBBatch {
  constructor(db, opts = {}) {
    super(db, opts)

    const { asyncIO = false, fillCache = true } = opts

    this._asyncIO = asyncIO
    this._fillCache = fillCache
  }

  _init() {
    this._handle = binding.readInit()
    this._buffer = binding.readBuffer(this._handle, this._capacity)
  }

  _resize() {
    if (super._resize() && this._handle !== null) {
      this._buffer = binding.readBuffer(this._handle, this._capacity)
    }
  }

  async _flush() {
    await super._flush()

    if (this._destroyed) return

    try {
      binding.read(
        this._db._state._handle,
        this._handle,
        this._operations,
        this._db._snapshot ? this._db._snapshot._handle : undefined,
        this._asyncIO,
        this._fillCache,
        this,
        this._onread
      )
    } catch (err) {
      this._db._state.io.dec()
      throw err
    }

    this._db._state.stats.gets += this._stats.gets
    this._db._state.stats.readBatches++
  }

  _onread(errs, values) {
    let applied = true

    for (let i = 0, n = this._promises.length; i < n; i++) {
      const err = errs[i]
      if (err) applied = false

      const promise = this._promises[i]
      if (promise === null) continue

      if (err) promise.reject(err)
      else promise.resolve(values[i] ? this._decodeValue(Buffer.from(values[i])) : null)
    }

    this._onfinished(applied ? null : new AggregateError(errs, 'Batch was not applied'))
  }

  _resetStats() {
    this._stats = { gets: 0 }
  }

  get(key) {
    if (this._request) throw new Error('Request already in progress')
    this._stats.gets++

    const promise = new Promise(this._enqueuePromise)

    this._operations.push(new RocksDBGet(this._encodeKey(key), this._db._columnFamily))

    this._resize()

    return promise
  }
}

exports.WriteBatch = class RocksDBWriteBatch extends RocksDBBatch {
  _init() {
    this._handle = binding.writeInit()
    this._buffer = binding.writeBuffer(this._handle, this._capacity)
  }

  _resize() {
    if (super._resize() && this._handle !== null) {
      this._buffer = binding.writeBuffer(this._handle, this._capacity)
    }
  }

  _onfree() {
    this._resetStats()
    this._db._state.freeBatch(this, true)
    this._db = null
  }

  async _flush() {
    await super._flush()

    if (this._destroyed) return

    try {
      binding.write(this._db._state._handle, this._handle, this._operations, this, this._onwrite)
    } catch (err) {
      this._db._state.io.dec()
      throw err
    }

    this._db._state.stats.puts += this._stats.puts
    this._db._state.stats.deletes += this._stats.deletes
    this._db._state.stats.rangeDeletes += this._stats.rangeDeletes
    this._db._state.stats.writeBatches++
  }

  _onwrite(err) {
    const applied = !err

    for (let i = 0, n = this._promises.length; i < n; i++) {
      const promise = this._promises[i]
      if (promise === null) continue

      if (err) promise.reject(err)
      else promise.resolve()
    }

    this._onfinished(applied ? null : new Error('Batch was not applied', { cause: err }))
  }

  _resetStats() {
    this._stats = { puts: 0, deletes: 0, rangeDeletes: 0 }
  }

  put(key, value) {
    if (this._request) throw new Error('Request already in progress')
    this._stats.puts++

    const promise = new Promise(this._enqueuePromise)

    this._operations.push(
      new RocksDBPut(this._encodeKey(key), this._encodeValue(value), this._db._columnFamily)
    )

    this._resize()

    return promise
  }

  tryPut(key, value) {
    if (this._request) throw new Error('Request already in progress')
    this._stats.puts++

    this._operations.push(
      new RocksDBPut(this._encodeKey(key), this._encodeValue(value), this._db._columnFamily)
    )

    this._promises.push(null)

    this._resize()
  }

  delete(key) {
    if (this._request) throw new Error('Request already in progress')
    this._stats.deletes++

    const promise = new Promise(this._enqueuePromise)

    this._operations.push(new RocksDBDelete(this._encodeKey(key), this._db._columnFamily))

    this._resize()

    return promise
  }

  tryDelete(key) {
    if (this._request) throw new Error('Request already in progress')
    this._stats.deletes++

    this._operations.push(new RocksDBDelete(this._encodeKey(key), this._db._columnFamily))

    this._promises.push(null)

    this._resize()
  }

  deleteRange(start, end) {
    if (this._request) throw new Error('Request already in progress')
    this._stats.rangeDeletes++

    const promise = new Promise(this._enqueuePromise)

    this._operations.push(
      new RocksDBDeleteRange(this._encodeKey(start), this._encodeKey(end), this._db._columnFamily)
    )

    this._resize()

    return promise
  }

  tryDeleteRange(start, end) {
    if (this._request) throw new Error('Request already in progress')
    this._stats.rangeDeletes++

    this._operations.push(
      new RocksDBDeleteRange(this._encodeKey(start), this._encodeKey(end), this._db._columnFamily)
    )

    this._promises.push(null)

    this._resize()
  }
}

class RocksDBGet {
  constructor(key, columnFamily) {
    this.key = key
    this.columnFamily = columnFamily._handle
  }

  get type() {
    return binding.GET
  }
}

class RocksDBPut {
  constructor(key, value, columnFamily) {
    this.key = key
    this.value = value
    this.columnFamily = columnFamily._handle
  }

  get type() {
    return binding.PUT
  }
}

class RocksDBDelete {
  constructor(key, columnFamily) {
    this.key = key
    this.columnFamily = columnFamily._handle
  }

  get type() {
    return binding.DELETE
  }
}

class RocksDBDeleteRange {
  constructor(start, end, columnFamily) {
    this.start = start
    this.end = end
    this.columnFamily = columnFamily._handle
  }

  get type() {
    return binding.DELETE_RANGE
  }
}
const binding = require('../binding')
const constants = require('./constants')
const { BloomFilterPolicy } = require('./filter-policy')

class RocksDBColumnFamily {
  constructor(name, opts = {}) {
    const {
      // Blob options
      enableBlobFiles = false,
      minBlobSize = 0,
      blobFileSize = 0,
      enableBlobGarbageCollection = true,
      // Block table options
      tableBlockSize = 8192,
      tableCacheIndexAndFilterBlocks = true,
      tableFormatVersion = 6,
      optimizeFiltersForMemory = false,
      blockCache = true,
      filterPolicy = new BloomFilterPolicy(10),
      topLevelIndexPinningTier = constants.pinningTier.ALL,
      partitionPinningTier = constants.pinningTier.ALL,
      unpartitionedPinningTier = constants.pinningTier.ALL,
      optimizeFiltersForHits = false,
      numLevels = 7,
      maxWriteBufferNumber = 2,
      blobGarbageCollectionAgeCutOff = 0.25,
      blobGarbageCollectionForceThreshold = 1.0
    } = opts

    this._name = name
    this._flushing = null
    this._options = {
      enableBlobFiles,
      minBlobSize,
      blobFileSize,
      enableBlobGarbageCollection,
      tableBlockSize,
      tableCacheIndexAndFilterBlocks,
      tableFormatVersion,
      optimizeFiltersForMemory,
      blockCache,
      filterPolicy,
      topLevelIndexPinningTier,
      partitionPinningTier,
      unpartitionedPinningTier,
      optimizeFiltersForHits,
      numLevels,
      maxWriteBufferNumber,
      blobGarbageCollectionAgeCutOff,
      blobGarbageCollectionForceThreshold
    }

    const filterPolicyArguments = [0, 0, 0]

    if (filterPolicy !== null) {
      filterPolicyArguments[0] = filterPolicy.type

      switch (filterPolicy.type) {
        case 1: // Bloom filter policy
          filterPolicyArguments[1] = filterPolicy.bitsPerKey
          break
        case 2: // Ribbon filter policy
          filterPolicyArguments[1] = filterPolicy.bloomEquivalentBitsPerKey
          filterPolicyArguments[2] = filterPolicy.bloomBeforeLevel

          break
      }
    }

    this._handle = binding.columnFamilyInit(
      name,
      enableBlobFiles,
      minBlobSize,
      blobFileSize,
      enableBlobGarbageCollection,
      tableBlockSize,
      tableCacheIndexAndFilterBlocks,
      tableFormatVersion,
      optimizeFiltersForMemory,
      blockCache === false,
      ...filterPolicyArguments,
      topLevelIndexPinningTier,
      partitionPinningTier,
      unpartitionedPinningTier,
      optimizeFiltersForHits,
      numLevels,
      maxWriteBufferNumber,
      blobGarbageCollectionAgeCutOff,
      blobGarbageCollectionForceThreshold
    )
  }

  cloneSettings(name) {
    return new RocksDBColumnFamily(name, this._options)
  }

  get name() {
    return this._name
  }

  destroy() {
    if (this._handle === null) return

    binding.columnFamilyDestroy(this._handle)

    this._handle = null
  }
}

module.exports = RocksDBColumnFamily
module.exports = {
  pinningTier: {
    NONE: 0,
    FLUSHED_AND_SIMILAR: 1,
    ALL: 2
  },
  garbageCollectionPolicy: {
    DEFAULT: 0,
    FORCE: 1,
    DISABLE: 2
  },
  bottommostLevelCompaction: {
    NONE: 0,
    SKIP: 1,
    FORCE: 2
  },
  walRecoveryMode: {
    TOLERATE_CORRUPTED_TAIL_RECORDS: 0,
    ABSOLUTE_CONSISTENCY: 1,
    POINT_IN_TIME: 2,
    SKIP_ANY_CORRUPTED_RECORDS: 3
  },
  statsLevel: {
    DISABLE_ALL: 0,
    EXCEPT_HISTOGRAM_OR_TIMERS: 1,
    EXCEPT_TIMERS: 2,
    EXCEPT_DETAILED_TIMERS: 3,
    EXCEPT_TIME_FOR_MUTEX: 4,
    ALL: 5
  },
  walFileType: {
    ARCHIVED: 0,
    ALIVE: 1
  }
}
exports.BloomFilterPolicy = class RocksDBBloomFilterPolicy {
  get type() {
    return 1
  }

  constructor(bitsPerKey) {
    this.bitsPerKey = bitsPerKey
  }
}

exports.RibbonFilterPolicy = class RocksDBRibbonFilterPolicy {
  get type() {
    return 2
  }

  constructor(bloomEquivalentBitsPerKey, bloomBeforeLevel = 0) {
    this.bloomEquivalentBitsPerKey = bloomEquivalentBitsPerKey
    this.bloomBeforeLevel = bloomBeforeLevel
  }
}
const { Readable } = require('streamx')
const c = require('compact-encoding')
const binding = require('../binding')

const empty = Buffer.alloc(0)

module.exports = class RocksDBIterator extends Readable {
  constructor(db, opts = {}) {
    const {
      gt = null,
      gte = null,
      lt = null,
      lte = null,
      reverse = false,
      values = true,
      limit = Infinity,
      capacity = 8
    } = opts

    super()

    db._ref()

    this._db = db

    this._gt = gt ? this._encodeKey(gt) : empty
    this._gte = gte ? this._encodeKey(gte) : empty
    this._lt = lt ? this._encodeKey(lt) : empty
    this._lte = lte ? this._encodeKey(lte) : empty

    this._reverse = reverse
    this._values = values
    this._limit = limit < 0 ? Infinity : limit
    this._capacity = capacity
    this._opened = false

    this._pendingOpen = null
    this._pendingRead = null
    this._pendingDestroy = null

    this._buffer = null
    this._handle = null

    if (this._db._state.opened === true) this.ready()
  }

  _onopen(err) {
    const cb = this._pendingOpen
    this._pendingOpen = null
    this._opened = true
    this._db._state.io.dec()
    cb(err)
  }

  _onread(err, keys, values) {
    const cb = this._pendingRead
    this._pendingRead = null
    this._db._state.io.dec()
    if (err) return cb(err)

    const n = keys.length

    this._limit -= n

    for (let i = 0; i < n; i++) {
      this.push({
        key: this._decodeKey(Buffer.from(keys[i])),
        value: this._values ? this._decodeValue(Buffer.from(values[i])) : null
      })
    }

    if (n < this._capacity) this.push(null)

    cb(null)
  }

  _onclose(err) {
    const cb = this._pendingDestroy
    this._pendingDestroy = null
    this._db._state.io.dec()
    this._db._unref()
    cb(err)
  }

  _resize() {
    if (this._handle !== null) {
      this._buffer = binding.iteratorBuffer(this._handle, this._capacity)
    }
  }

  async ready() {
    if (this._handle !== null) return

    if (this._db._state.opened === false) await this._db._state.ready()

    this._init()
  }

  _init() {
    this._handle = binding.iteratorInit()
    this._buffer = binding.iteratorBuffer(this._handle, this._capacity)
  }

  async _open(cb) {
    await this.ready()

    this._db._state.io.inc()

    if (this._db._state.resumed !== null) {
      const resumed = await this._db._state.resumed.promise

      if (!resumed) {
        this._db._state.io.dec()

        return cb(new Error('RocksDB session is closed'))
      }
    }

    this._pendingOpen = cb

    try {
      binding.iteratorOpen(
        this._db._state._handle,
        this._handle,
        this._db._columnFamily._handle,
        this._gt,
        this._gte,
        this._lt,
        this._lte,
        this._reverse,
        !this._values, // Keys only
        this._db._snapshot ? this._db._snapshot._handle : undefined,
        this,
        this._onopen,
        this._onclose,
        this._onread
      )
    } catch (err) {
      this._db._state.io.dec()

      cb(err)
    }
  }

  async _read(cb) {
    this._db._state.io.inc()

    if (this._db._state.resumed !== null) {
      const resumed = await this._db._state.resumed.promise

      if (!resumed) {
        this._db._state.io.dec()

        return cb(new Error('RocksDB session is closed'))
      }
    }

    this._pendingRead = cb

    try {
      binding.iteratorRead(this._handle, Math.min(this._capacity, this._limit))
    } catch (err) {
      this._db._state.io.dec()

      cb(err)
    }
  }

  async _destroy(cb) {
    await this.ready()

    this._db._state.io.inc()

    if (this._opened === false) {
      this._db._state.io.dec()
      this._db._unref()

      return cb(null)
    }

    this._pendingDestroy = cb

    try {
      binding.iteratorClose(this._handle)
    } catch (err) {
      this._db._state.io.dec()
      this._db._unref()

      cb(err)
    }
  }

  _encodeKey(k) {
    if (this._db._keyEncoding !== null) return c.encode(this._db._keyEncoding, k)
    if (typeof k === 'string') return Buffer.from(k)
    return k
  }

  _decodeKey(b) {
    if (this._db._keyEncoding !== null) return c.decode(this._db._keyEncoding, b)
    return b
  }

  _decodeValue(b) {
    if (this._db._valueEncoding !== null) return c.decode(this._db._valueEncoding, b)
    return b
  }
}
const binding = require('../binding')

module.exports = class RocksDBSnapshot {
  constructor(state) {
    this._state = state

    this._handle = null
    this._refs = 0

    if (state.deferSnapshotInit === false) this._init()
  }

  _init() {
    this._handle = binding.snapshotCreate(this._state._handle)
  }

  ref() {
    this._refs++
  }

  unref() {
    if (--this._refs > 0) return

    if (this._handle === null) return

    binding.snapshotDestroy(this._handle)

    this._handle = null
  }
}
const ReadyResource = require('ready-resource')
const RefCounter = require('refcounter')
const rrp = require('resolve-reject-promise')
const SignalPromise = require('signal-promise')
const c = require('compact-encoding')
const { ReadBatch, WriteBatch } = require('./batch')
const ColumnFamily = require('./column-family')
const binding = require('../binding')
const constants = require('./constants')

const MAX_BATCH_REUSE = 64
const empty = Buffer.alloc(0)

module.exports = class RocksDBState extends ReadyResource {
  constructor(db, path, opts) {
    super()

    const {
      columnFamily = new ColumnFamily('default', opts),
      columnFamilies = [],
      readOnly = false,
      createIfMissing = true,
      createMissingColumnFamilies = true,
      maxBackgroundJobs = 6,
      bytesPerSync = 1048576,
      maxOpenFiles = -1,
      useDirectReads = false,
      avoidUnnecessaryBlockingIO = false,
      skipStatsUpdateOnOpen = false,
      useDirectIOForFlushAndCompaction = false,
      maxFileOpeningThreads = 16,
      lock = null,
      walRecoveryMode = constants.walRecoveryMode.POINT_IN_TIME,
      bestEffortsRecovery = false,
      enableStatistics = false,
      statsLevel = constants.statsLevel.EXCEPT_HISTOGRAM_OR_TIMERS,
      walTtlSeconds = 0,
      walSizeLimitMegabytes = 0,
      avoidFlushDuringShutdown = false,
      walFilterPrefixes = []
    } = opts

    this.path = path
    this.db = db
    this.handles = new RefCounter()
    this.io = new RefCounter()
    this.sessions = []
    this.columnFamilies = [columnFamily]
    this.deferSnapshotInit = true
    this.resumed = null
    this.stats = {
      gets: 0,
      puts: 0,
      deletes: 0,
      rangeDeletes: 0,
      readBatches: 0,
      writeBatches: 0
    }

    this._suspended = false
    this._suspending = false
    this._updating = false
    this._updatingSignal = new SignalPromise()
    this._columnsFlushed = false
    this._lock = lock
    this._readBatches = []
    this._writeBatches = []

    for (const columnFamily of columnFamilies) {
      this.columnFamilies.push(
        typeof columnFamily === 'string' ? new ColumnFamily(columnFamily, opts) : columnFamily
      )
    }

    this._handle = binding.init(
      readOnly,
      createIfMissing,
      createMissingColumnFamilies,
      maxBackgroundJobs,
      bytesPerSync,
      maxOpenFiles,
      useDirectReads,
      avoidUnnecessaryBlockingIO,
      skipStatsUpdateOnOpen,
      useDirectIOForFlushAndCompaction,
      maxFileOpeningThreads,
      walRecoveryMode,
      bestEffortsRecovery,
      enableStatistics,
      statsLevel,
      walTtlSeconds,
      walSizeLimitMegabytes,
      avoidFlushDuringShutdown,
      walFilterPrefixes.map(encodePrefix)
    )
  }

  createReadBatch(db, opts) {
    if (this._readBatches.length === 0) return new ReadBatch(db, opts)
    const batch = this._readBatches.pop()
    batch._reuse(db, opts)
    return batch
  }

  createWriteBatch(db, opts) {
    if (this._writeBatches.length === 0) return new WriteBatch(db, opts)
    const batch = this._writeBatches.pop()
    batch._reuse(db, opts)
    return batch
  }

  freeBatch(batch, writable) {
    if (batch._capacity > 16) return
    const queue = writable ? this._writeBatches : this._readBatches
    if (queue.length >= MAX_BATCH_REUSE) return
    queue.push(batch)
  }

  addSession(db) {
    db._index = this.sessions.push(db) - 1
    if (db._snapshot) db._snapshot.ref()
  }

  removeSession(db) {
    const head = this.sessions.pop()
    if (head !== db) this.sessions[(head._index = db._index)] = head
    db._index = -1
    if (db._snapshot) db._snapshot.unref()
  }

  upsertColumnFamily(c) {
    if (typeof c === 'string') {
      let col = this.getColumnFamilyByName(c)
      if (col) return col
      col = this.columnFamilies[0].cloneSettings(c)
      this.columnFamilies.push(col)
      return col
    }

    if (this.columnFamilies.includes(c)) return c
    this.columnFamilies.push(c)
    return c
  }

  getColumnFamily(c) {
    if (!c) return this.columnFamilies[0]
    if (!this._columnsFlushed) return this.upsertColumnFamily(c)

    if (typeof c !== 'string') return c

    const col = this.getColumnFamilyByName(c)
    if (col === null) throw new Error('Unknown column family')
    return col
  }

  getColumnFamilyByName(name) {
    for (const col of this.columnFamilies) {
      if (col.name === name) return col
    }
    return null
  }

  async _open() {
    await Promise.resolve() // Allow column families to populate if on-demand

    if (this._lock) await this._lock.ready()

    const req = { resolve: null, reject: null, handle: null }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    this._columnsFlushed = true

    const lock = this._lock === null ? -1 : this._lock.transfer()

    req.handle = binding.open(
      this._handle,
      this,
      this.path,
      this.columnFamilies.map((c) => c._handle),
      lock,
      req,
      onopen
    )

    await promise

    this.deferSnapshotInit = false

    for (const session of this.sessions) {
      if (session._snapshot) session._snapshot._init()
    }

    function onopen(err) {
      if (err) req.reject(err)
      else req.resolve()
    }
  }

  async _close() {
    while (this._updating) await this._updatingSignal.wait()
    if (this.resumed) this.resumed.resolve(false)

    while (!this.io.isIdle()) await this.io.idle()
    while (!this.handles.isIdle()) await this.handles.idle()

    while (this.sessions.length > 0) {
      await this.sessions[this.sessions.length - 1].close()
    }

    for (const columnFamily of this.columnFamilies) columnFamily.destroy()

    const req = { resolve: null, reject: null, handle: null }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    req.handle = binding.close(this._handle, req, onclose)

    try {
      await promise
    } finally {
      if (this._lock) await this._lock.close()
    }

    function onclose(err) {
      if (err) req.reject(err)
      else req.resolve()
    }
  }

  async flush(db, opts) {
    if (this.opened === false) await this.ready()

    this.io.inc()

    if (this.resumed !== null) {
      const resumed = await this.resumed.promise

      if (!resumed) {
        this.io.dec()

        throw new Error('RocksDB session is closed')
      }
    }

    const req = { resolve: null, reject: null, handle: null }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    try {
      req.handle = binding.flush(this._handle, db._columnFamily._handle, req, onflush)

      await promise
    } finally {
      this.io.dec()
    }

    function onflush(err) {
      if (err) req.reject(err)
      else req.resolve()
    }
  }

  suspend() {
    this._suspending = true
    return this.update()
  }

  resume() {
    this._suspending = false
    return this.update()
  }

  async update() {
    while (this._updating) await this._updatingSignal.wait()
    if (this._suspending === this._suspended || this.closing) return
    this._updating = true
    try {
      if (this._suspending) await this._suspend()
      else await this._resume()
    } finally {
      this._updating = false
      this._updatingSignal.notify()
    }
  }

  async _suspend() {
    if (this._suspended === true) return

    while (!this.io.isIdle()) await this.io.idle()

    this.io.inc()
    this.resumed = rrp()

    const req = { resolve: null, reject: null, handle: null }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    try {
      req.handle = binding.suspend(this._handle, req, onsuspend)

      await promise

      this._suspended = true
    } finally {
      this.io.dec()
    }

    function onsuspend(err) {
      if (err) req.reject(err)
      else req.resolve()
    }
  }

  async _resume() {
    if (this._suspended === false) return

    const req = { resolve: null, reject: null, handle: null }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    req.handle = binding.resume(this._handle, req, onresume)

    await promise

    this._suspended = false

    const resumed = this.resumed
    this.resumed = null
    resumed.resolve(true)

    function onresume(err) {
      if (err) req.reject(err)
      else req.resolve()
    }
  }

  async compact(db, opts) {
    if (this.opened === false) await this.ready()

    this.io.inc()

    const {
      exclusive = false,
      blobGarbageCollectionPolicy = constants.garbageCollectionPolicy.DEFAULT,
      blobGarbageCollectionAgeCutoff = 0.25,
      bottommostLevelCompaction = constants.bottommostLevelCompaction.NONE
    } = opts

    const req = { resolve: null, reject: null, handle: null }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    try {
      req.handle = binding.compact(
        this._handle,
        db._columnFamily._handle,
        exclusive,
        blobGarbageCollectionPolicy,
        blobGarbageCollectionAgeCutoff,
        bottommostLevelCompaction,
        req,
        oncompact
      )

      await promise
    } finally {
      this.io.dec()
    }

    function oncompact(err) {
      if (err) req.reject(err)
      else req.resolve()
    }
  }

  async compactRange(db, start, end, opts) {
    if (this.opened === false) await this.ready()

    this.io.inc()

    const {
      exclusive = false,
      blobGarbageCollectionPolicy = constants.garbageCollectionPolicy.DEFAULT,
      blobGarbageCollectionAgeCutoff = 0.25,
      bottommostLevelCompaction = constants.bottommostLevelCompaction.NONE
    } = opts

    start = this._encodeKey(start)
    end = this._encodeKey(end)

    const req = { resolve: null, reject: null, handle: null, start, end }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    try {
      req.handle = binding.compactRange(
        this._handle,
        db._columnFamily._handle,
        start,
        end,
        exclusive,
        blobGarbageCollectionPolicy,
        blobGarbageCollectionAgeCutoff,
        bottommostLevelCompaction,
        req,
        oncompactrange
      )

      await promise
    } finally {
      this.io.dec()
    }

    function oncompactrange(err) {
      if (err) req.reject(err)
      else req.resolve()
    }
  }

  async approximateSize(db, start, end, opts) {
    if (this.opened === false) await this.ready()

    this.io.inc()

    const { includeMemtables = false, includeFiles = true, filesSizeErrorMargin = -1 } = opts

    start = this._encodeKey(start)
    end = this._encodeKey(end)

    const req = { resolve: null, reject: null, handle: null, start, end }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    try {
      req.handle = binding.approximateSize(
        this._handle,
        db._columnFamily._handle,
        start,
        end,
        includeMemtables,
        includeFiles,
        filesSizeErrorMargin,
        req,
        onapproximatesize
      )

      return await promise
    } finally {
      this.io.dec()
    }

    function onapproximatesize(err, result) {
      if (err) req.reject(err)
      else req.resolve(result)
    }
  }

  async currentWalFile() {
    if (this.opened === false) await this.ready()

    this.io.inc()

    const req = { resolve: null, reject: null, handle: null }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    try {
      req.handle = binding.currentWalFile(this._handle, req, oncurrentwalfile)

      return await promise
    } finally {
      this.io.dec()
    }

    function oncurrentwalfile(err, path, number, type, startSequence, size) {
      if (err) req.reject(err)
      else req.resolve({ path, number, type, startSequence, size })
    }
  }

  async getStatsLevel() {
    if (this.opened === false) await this.ready()

    return binding.statsLevelGet(this._handle)
  }

  async setStatsLevel(level) {
    if (this.opened === false) await this.ready()

    binding.statsLevelSet(this._handle, level)
  }

  async getProperty(name) {
    if (this.opened === false) await this.ready()

    return binding.propertyGet(this._handle, name)
  }

  _encodeKey(k) {
    if (this.db._keyEncoding) return c.encode(this.db._keyEncoding, k)
    if (typeof k === 'string') return Buffer.from(k)
    if (k === null) return empty
    return k
  }

  diagnostics() {
    return {
      suspended: this._suspended,
      suspending: this._suspending,
      updating: this._updating,
      resumedPending: this.resumed !== null,
      io: this.io.count,
      handles: this.handles.count,
      sessions: this.sessions.length
    }
  }
}

function encodePrefix(prefix) {
  if (typeof prefix === 'string') return Buffer.from(prefix)
  return prefix
}
{
  "name": "rocksdb-native",
  "version": "3.17.2",
  "description": "librocksdb bindings for JavaScript",
  "exports": {
    ".": "./index.js",
    "./package": "./package.json"
  },
  "imports": {
    "crypto": {
      "bare": "bare-crypto",
      "default": "crypto"
    },
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    }
  },
  "files": [
    "index.js",
    "binding.cc",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds",
    "!prebuilds/android-*/**/*.node"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:bare && npm run test:node",
    "test:bare": "brittle-bare --coverage test.js",
    "test:node": "brittle-node --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/rocksdb-native.git"
  },
  "author": "Holepunch Inc",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/rocksdb-native/issues"
  },
  "homepage": "https://github.com/holepunchto/rocksdb-native",
  "engines": {
    "bare": ">=1.16.0"
  },
  "dependencies": {
    "compact-encoding": "^3.0.0",
    "ready-resource": "^1.0.0",
    "refcounter": "^1.0.0",
    "require-addon": "^1.0.2",
    "resolve-reject-promise": "^1.1.0",
    "signal-promise": "^1.0.3",
    "streamx": "^2.16.1"
  },
  "devDependencies": {
    "bare-compat-napi": "^1.3.0",
    "bare-crypto": "^1.12.0",
    "bare-fs": "^4.5.0",
    "bare-path": "^3.0.0",
    "brittle": "^3.5.0",
    "cmake-bare": "^1.1.14",
    "cmake-fetch": "^1.0.1",
    "cmake-napi": "^1.0.6",
    "fd-lock": "^2.0.0",
    "lunte": "^1.8.0",
    "paparam": "^1.9.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = safetyCatch

function isActuallyUncaught (err) {
  if (!err) return false
  return err instanceof TypeError ||
    err instanceof SyntaxError ||
    err instanceof ReferenceError ||
    err instanceof EvalError ||
    err instanceof RangeError ||
    err instanceof URIError ||
    err.code === 'ERR_ASSERTION' ||
    err.name === 'AssertionError'
}

function throwErrorNT (err) {
  queueMicrotask(() => { throw err })
}

function safetyCatch (err) {
  if (isActuallyUncaught(err)) {
    throwErrorNT(err)
    throw err
  }
}
{
  "name": "safety-catch",
  "version": "1.0.3",
  "description": "Small module that makes sure your catch, caught an actual error and not a programming mistake or assertion",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {},
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/safety-catch.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/safety-catch/issues"
  },
  "homepage": "https://github.com/mafintosh/safety-catch"
}
let tmpResolve = null

module.exports = class ScopeLock {
  constructor ({ debounce = false } = {}) {
    this.debounce = debounce
    this.waiting = []
    this.locked = false
    this.skip = 0
    this.destroyed = false
  }

  flush () {
    if (this.locked === false && this.waiting.length === 0) return Promise.resolve(this.destroyed === false)

    const promise = new Promise(setTmpResolve)
    const resolve = tmpResolve

    tmpResolve = null
    this.waiting.push({ lock: false, resolve })

    return promise
  }

  destroy () {
    this.destroyed = true
  }

  lock () {
    const promise = new Promise(setTmpResolve)
    const resolve = tmpResolve

    tmpResolve = null

    if (this.locked === true) {
      this.waiting.push({ lock: true, resolve })
      return promise
    }

    if (this.destroyed === true) {
      resolve(false)
      return promise
    }

    this.locked = true
    resolve(true)

    return promise
  }

  unlock () {
    if (this.destroyed === true) {
      for (let i = 0; i < this.waiting.length; i++) {
        this.waiting[i].resolve(false)
      }
      this.waiting = []
      this.skip = 0
      this.locked = false
      return
    }

    if (this.skip !== 0) {
      for (let i = 0; i < this.skip; i++) {
        const { lock, resolve } = this.waiting[i]
        resolve(lock === false)
      }

      this.waiting = this.waiting.slice(this.skip)
      this.skip = 0
    }

    while (this.waiting.length > 0 && this.waiting[0].lock === false) {
      this.waiting.shift().resolve(true)
    }

    if (this.waiting.length === 0) {
      this.locked = false
      return
    }

    const { resolve } = this.waiting.shift()
    if (this.debounce === true) this.skip = this.waiting.length

    resolve(true)
  }
}

function setTmpResolve (resolve) {
  tmpResolve = resolve
}
{
  "name": "scope-lock",
  "version": "1.2.4",
  "description": "Some concurrency semantics around entering scopes",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "devDependencies": {
    "brittle": "^3.7.0",
    "standard": "^17.1.2"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/scope-lock.git"
  },
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/scope-lock/issues"
  },
  "homepage": "https://github.com/holepunchto/scope-lock"
}
module.exports = class Signal {
  constructor () {
    this._resolve = null
    this._reject = null
    this._promise = null
    this._bind = bind.bind(this)
    this._onerror = clear.bind(this)
    this._onsuccess = clear.bind(this, null)
    this._timers = new Set()
  }

  wait (max) {
    if (!this._promise) {
      this._promise = new Promise(this._bind)
      this._promise.then(this._onsuccess).catch(this._onerror)
    }
    if (max) return this._sleep(max)
    return this._promise
  }

  _sleep (max) {
    const s = new Promise((resolve, reject) => {
      const done = () => {
        this._timers.delete(state)
        resolve(true)
      }
      const id = setTimeout(done, max)
      const state = { id, resolve, reject }
      this._timers.add(state)
    })

    return s
  }

  notify (err) {
    if (!this._promise) return
    const resolve = this._resolve
    const reject = this._reject
    this._promise = null
    if (err) reject(err)
    else resolve(true)
  }
}

function clear (err) {
  for (const { id, resolve, reject } of this._timers) {
    clearTimeout(id)
    if (err) reject(err)
    else resolve(true)
  }
  this._timers.clear()
}

function bind (resolve, reject) {
  this._resolve = resolve
  this._reject = reject
}
{
  "name": "signal-promise",
  "version": "1.0.3",
  "description": "Simple wait/notify promise with optional max wait time",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {},
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/signal-promise.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/signal-promise/issues"
  },
  "homepage": "https://github.com/mafintosh/signal-promise"
}
require.addon = require('require-addon')

module.exports = require.addon('.', __filename)
const binding = require('./binding')
const b4a = require('b4a')

function predicate(u8, u16, u32) {
  return function predicate(buf) {
    if (buf.byteLength % 16 !== 0) {
      throw new Error('Buffer length must be a multiple of 16')
    }

    const n = buf.BYTES_PER_ELEMENT

    if (n === 1) return u8(buf)
    if (n === 2) return u16(buf)
    return u32(buf)
  }
}

function unary(u8, u16, u32) {
  return function unary(buf, result = b4a.allocUnsafe(buf.byteLength)) {
    if (buf.byteLength % 16 !== 0) {
      throw new Error('Buffer length must be a multiple of 16')
    }

    if (buf.byteLength !== result.byteLength) {
      throw new Error('Length of result buffer is insufficient')
    }

    const n = buf.BYTES_PER_ELEMENT

    if (n === 1) u8(buf, result)
    else if (n === 2) u16(buf, result)
    else u32(buf, result)

    return result
  }
}

function binary(u8, u16, u32) {
  return function binary(a, b, result = b4a.allocUnsafe(a.byteLength)) {
    if (a.byteLength % 16 !== 0) {
      throw new Error('Buffer length must be a multiple of 16')
    }

    if (a.byteLength !== b.byteLength || a.byteLength !== result.byteLength) {
      throw new Error('Buffers must be the same length')
    }

    const n = a.BYTES_PER_ELEMENT

    if (n === 1) u8(a, b, result)
    else if (n === 2) u16(a, b, result)
    else u32(a, b, result)

    return result
  }
}

function reduce(u8, u16, u32) {
  return function reduce(buf) {
    if (buf.byteLength % 16 !== 0) {
      throw new Error('Buffer length must be a multiple of 16')
    }

    const n = buf.BYTES_PER_ELEMENT

    if (n === 1) return u8(buf)
    if (n === 2) return u16(buf)
    return u32(buf)
  }
}

exports.allo = predicate(
  binding.simdle_native_allo_v128_u8,
  binding.simdle_native_allo_v128_u16,
  binding.simdle_native_allo_v128_u32
)

exports.allz = predicate(
  binding.simdle_native_allz_v128_u8,
  binding.simdle_native_allz_v128_u16,
  binding.simdle_native_allz_v128_u32
)

exports.and = binary(
  binding.simdle_native_and_v128_u8,
  binding.simdle_native_and_v128_u16,
  binding.simdle_native_and_v128_u32
)

exports.clear = binary(
  binding.simdle_native_clear_v128_u8,
  binding.simdle_native_clear_v128_u16,
  binding.simdle_native_clear_v128_u32
)

exports.clo = unary(
  binding.simdle_native_clo_v128_u8,
  binding.simdle_native_clo_v128_u16,
  binding.simdle_native_clo_v128_u32
)

exports.clz = unary(
  binding.simdle_native_clz_v128_u8,
  binding.simdle_native_clz_v128_u16,
  binding.simdle_native_clz_v128_u32
)

exports.cnt = unary(
  binding.simdle_native_cnt_v128_u8,
  binding.simdle_native_cnt_v128_u16,
  binding.simdle_native_cnt_v128_u32
)

exports.cto = unary(
  binding.simdle_native_cto_v128_u8,
  binding.simdle_native_cto_v128_u16,
  binding.simdle_native_cto_v128_u32
)

exports.ctz = unary(
  binding.simdle_native_ctz_v128_u8,
  binding.simdle_native_ctz_v128_u16,
  binding.simdle_native_ctz_v128_u32
)

exports.not = unary(
  binding.simdle_native_not_v128_u8,
  binding.simdle_native_not_v128_u16,
  binding.simdle_native_not_v128_u32
)

exports.or = binary(
  binding.simdle_native_or_v128_u8,
  binding.simdle_native_or_v128_u16,
  binding.simdle_native_or_v128_u32
)

exports.sum = reduce(
  binding.simdle_native_sum_v128_u8,
  binding.simdle_native_sum_v128_u16,
  binding.simdle_native_sum_v128_u32
)

exports.xor = binary(
  binding.simdle_native_xor_v128_u8,
  binding.simdle_native_xor_v128_u16,
  binding.simdle_native_xor_v128_u32
)
{
  "name": "simdle-native",
  "version": "1.3.9",
  "description": "libsimdle JavaScript bindings for Node.js",
  "main": "index.js",
  "files": [
    "index.js",
    "binding.cc",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check .",
    "test": "npm run lint && npm run test:bare && npm run test:node",
    "test:bare": "bare test.mjs",
    "test:node": "node test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/simdle-native.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/simdle-native/issues"
  },
  "homepage": "https://github.com/holepunchto/simdle-native#readme",
  "dependencies": {
    "b4a": "^1.6.0",
    "require-addon": "^1.1.0"
  },
  "devDependencies": {
    "bare-compat-napi": "^1.3.2",
    "brittle": "^3.1.0",
    "cmake-bare": "^1.1.7",
    "cmake-fetch": "^1.1.0",
    "cmake-napi": "^1.0.2",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  }
}
const b4a = require('b4a')
const scalar = require('./scalar')

function view (buf, n) {
  if (n === buf.BYTES_PER_ELEMENT) return buf

  let TypedArray

  if (n === 1) TypedArray = Uint8Array
  else if (n === 2) TypedArray = Uint16Array
  else TypedArray = Uint32Array

  return new TypedArray(buf.buffer, buf.byteOffset, buf.byteLength / n)
}

function unary (u8, u16 = u8, u32 = u16) {
  return function unary (buf, result = b4a.allocUnsafe(buf.byteLength)) {
    if (buf.byteLength % 16 !== 0) {
      throw new Error('Buffer length must be a multiple of 16')
    }

    if (buf.byteLength !== result.byteLength) {
      throw new Error('Length of result buffer is insufficient')
    }

    const n = buf.BYTES_PER_ELEMENT

    if (n === 1) u8(buf, view(result, n))
    else if (n === 2) u16(buf, view(result, n))
    else u32(buf, view(result, n))

    return result
  }
}

function binary (u8, u16 = u8, u32 = u16) {
  return function binary (a, b, result = b4a.allocUnsafe(a.byteLength)) {
    if (a.byteLength % 16 !== 0) {
      throw new Error('Buffer length must be a multiple of 16')
    }

    if (a.byteLength !== b.byteLength || a.byteLength !== result.byteLength) {
      throw new Error('Buffers must be the same length')
    }

    const n = a.BYTES_PER_ELEMENT

    if (n === 1) u8(a, b, view(result, n))
    else if (n === 2) u16(a, b, view(result, n))
    else u32(a, b, view(result, n))

    return result
  }
}

function reduce (u8, u16 = u8, u32 = u16) {
  return function reduce (buf) {
    if (buf.byteLength % 16 !== 0) {
      throw new Error('Buffer length must be a multiple of 16')
    }

    const n = buf.BYTES_PER_ELEMENT

    if (n === 1) return u8(buf)
    if (n === 2) return u16(buf)
    return u32(buf)
  }
}

exports.allo = function allo (buf) {
  if (buf.byteLength % 16 !== 0) {
    throw new Error('Buffer length must be a multiple of 16')
  }

  const m = 2 ** (buf.BYTES_PER_ELEMENT * 8) - 1

  for (let i = 0, n = buf.length; i < n; i++) {
    if (buf[i] !== m) return false
  }

  return true
}

exports.allz = function allz (buf) {
  if (buf.byteLength % 16 !== 0) {
    throw new Error('Buffer length must be a multiple of 16')
  }

  for (let i = 0, n = buf.length; i < n; i++) {
    if (buf[i] !== 0) return false
  }

  return true
}

exports.and = binary(
  (a, b, result) => {
    for (let i = 0, n = result.length; i < n; i++) {
      result[i] = a[i] & b[i]
    }
  }
)

exports.clear = binary(
  (a, b, result) => {
    for (let i = 0, n = result.length; i < n; i++) {
      result[i] = a[i] & ~b[i]
    }
  }
)

exports.clo = unary(
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = 24 - scalar.clo(buf[i])
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = 16 - scalar.clo(buf[i])
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = scalar.clo(buf[i])
    }
  }
)

exports.clz = unary(
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = 24 - scalar.clz(buf[i])
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = 16 - scalar.clz(buf[i])
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = scalar.clz(buf[i])
    }
  }
)

exports.cnt = unary(
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = scalar.cnt(buf[i]) & 0xff
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = scalar.cnt(buf[i]) & 0xffff
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = scalar.cnt(buf[i])
    }
  }
)

exports.cto = unary(
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = Math.min(scalar.cto(buf[i]), 8)
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = Math.min(scalar.cto(buf[i]), 16)
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = scalar.cto(buf[i])
    }
  }
)

exports.ctz = unary(
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = Math.min(scalar.ctz(buf[i]), 8)
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = Math.min(scalar.ctz(buf[i]), 16)
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = scalar.ctz(buf[i])
    }
  }
)

exports.not = unary(
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = ~buf[i]
    }
  }
)

exports.or = binary(
  (a, b, result) => {
    for (let i = 0, n = result.length; i < n; i++) {
      result[i] = a[i] | b[i]
    }
  }
)

exports.sum = reduce(
  (buf) => {
    let result = 0n

    for (let i = 0, n = buf.length; i < n; i++) {
      result += BigInt(buf[i])
    }

    return result
  }
)

exports.xor = binary(
  (a, b, result) => {
    for (let i = 0, n = result.length; i < n; i++) {
      result[i] = a[i] ^ b[i]
    }
  }
)
try {
  module.exports = require('simdle-native')
} catch {
  module.exports = require('./fallback')
}
{
  "name": "simdle-universal",
  "version": "1.1.2",
  "description": "Universal wrapper for libsimdle with a JavaScript fallback",
  "main": "index.js",
  "files": [
    "fallback.js",
    "index.js",
    "scalar.js"
  ],
  "browser": {
    "./index.js": "./fallback.js"
  },
  "scripts": {
    "test": "standard && brittle test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/simdle-universal.git"
  },
  "author": "Kasper Isager Dalsgarð <kasper@funktionel.co>",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/holepunchto/simdle-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/simdle-universal#readme",
  "dependencies": {
    "b4a": "^1.6.0"
  },
  "optionalDependencies": {
    "simdle-native": "^1.1.1"
  },
  "devDependencies": {
    "brittle": "^3.1.0",
    "standard": "^17.0.0"
  }
}
const clz = exports.clz = function clz (n) {
  return Math.clz32(n)
}

exports.clo = function clo (n) {
  return clz(~n)
}

const ctz = exports.ctz = function ctz (n) {
  return 32 - (n === 0 ? 0 : (clz(n & -n) + 1))
}

exports.cto = function cto (n) {
  return ctz(~n)
}

exports.cnt = function cnt (n) {
  n = n - ((n >>> 1) & 0x55555555)
  n = (n & 0x33333333) + ((n >>> 2) & 0x33333333)
  n = (n + (n >>> 4)) & 0x0f0f0f0f
  n = (n * 0x01010101) >>> 24
  return n
}
require.addon = require('require-addon')
module.exports = require.addon('.', __filename)
const assert = require('assert')
const binding = require('./binding')
const { isNode } = require('which-runtime')

const OPTIONAL = Buffer.from(new ArrayBuffer(0))

module.exports = exports = { ...binding }

// memory

exports.sodium_memzero = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  binding.sodium_memzero(buf)
}

exports.sodium_mlock = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  const res = binding.sodium_mlock(buf)

  if (res !== 0) throw new Error('memory lock failed')
}

exports.sodium_munlock = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  const res = binding.sodium_munlock(buf)

  if (res !== 0) throw new Error('memory unlock failed')
}

exports.sodium_malloc = function (size) {
  assert(size >= 0, 'invalid size')

  const buf = Buffer.from(binding.sodium_malloc(size))
  buf.secure = true
  return buf
}

exports.sodium_free = function (buf) {
  if (!buf || !buf.secure) return

  binding.sodium_free(buf.buffer)
}

exports.sodium_mprotect_noaccess = function (buf) {
  const res = binding.sodium_mprotect_noaccess(buf.buffer)

  if (res !== 0) throw new Error('failed to lock buffer')
}

exports.sodium_mprotect_readonly = function (buf) {
  const res = binding.sodium_mprotect_readonly(buf.buffer)

  if (res !== 0) throw new Error('failed to unlock buffer')
}

exports.sodium_mprotect_readwrite = function (buf) {
  const res = binding.sodium_mprotect_readwrite(buf.buffer)

  if (res !== 0) throw new Error('failed to unlock buffer')
}

// crypto_randombytes

exports.randombytes_buf = function (buffer) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')

  binding.randombytes_buf(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

exports.randombytes_buf_deterministic = function (buffer, seed) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    seed.byteLength === binding.randombytes_SEEDBYTES,
    "seed must be 'randombytes_SEEDBYTES' bytes"
  )

  binding.randombytes_buf_deterministic(
    buffer.buffer,
    buffer.byteOffset,
    buffer.byteLength,

    seed.buffer,
    seed.byteOffset,
    seed.byteLength
  )
}

// sodium_helpers

exports.sodium_memcmp = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  return binding.sodium_memcmp(a, b)
}

exports.sodium_add = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  binding.sodium_add(a, b)
}

exports.sodium_sub = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  binding.sodium_sub(a, b)
}

exports.sodium_compare = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  return binding.sodium_compare(a, b)
}

exports.sodium_is_zero = function (buffer, length) {
  if (length === undefined) length = buffer.byteLength

  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(length >= 0 && length <= buffer.byteLength, 'invalid length')

  return binding.sodium_is_zero(buffer, length)
}

exports.sodium_pad = function (buffer, unpaddedBuflen, blockSize) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(unpaddedBuflen <= buffer.byteLength, 'unpadded length cannot exceed buffer length')
  assert(blockSize <= buffer.byteLength, 'block size cannot exceed buffer length')
  assert(blockSize >= 1, 'block size must be at least 1 byte')
  assert(
    buffer.byteLength >= unpaddedBuflen + (blockSize - (unpaddedBuflen % blockSize)),
    'buf not long enough'
  )

  return binding.sodium_pad(buffer, unpaddedBuflen, blockSize)
}

exports.sodium_unpad = function (buffer, paddedBuflen, blockSize) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(paddedBuflen <= buffer.byteLength, 'unpadded length cannot exceed buffer length')
  assert(blockSize <= buffer.byteLength, 'block size cannot exceed buffer length')
  assert(blockSize >= 1, 'block size must be at least 1 byte')

  return binding.sodium_unpad(buffer, paddedBuflen, blockSize)
}

// crypto_sign

exports.crypto_sign_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )
  assert(
    seed.byteLength === binding.crypto_sign_SEEDBYTES,
    "seed must be 'crypto_sign_SEEDBYTES' bytes"
  )

  const res = binding.crypto_sign_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign = function (sm, m, sk) {
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sm.byteLength === binding.crypto_sign_BYTES + m.byteLength,
    "sm must be 'm.byteLength + crypto_sign_BYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign(sm, m, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_open = function (m, sm, pk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sm.byteLength >= binding.crypto_sign_BYTES,
    "sm must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    m.byteLength === sm.byteLength - binding.crypto_sign_BYTES,
    "m must be 'sm.byteLength - crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_open(m, sm, pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_open = function (m, sm, pk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sm.byteLength >= binding.crypto_sign_BYTES,
    "sm must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    m.byteLength === sm.byteLength - binding.crypto_sign_BYTES,
    "m must be 'sm.byteLength - crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  return binding.crypto_sign_open(m, sm, pk)
}

exports.crypto_sign_detached = function (sig, m, sk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(sig.byteLength === binding.crypto_sign_BYTES, "sig must be 'crypto_sign_BYTES' bytes")
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_detached(sig, m, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_verify_detached = function (sig, m, pk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sig.byteLength >= binding.crypto_sign_BYTES,
    "sig must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  return binding.crypto_sign_verify_detached(
    sig.buffer,
    sig.byteOffset,
    sig.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    pk.buffer,
    pk.byteOffset,
    pk.byteLength
  )
}

exports.crypto_sign_ed25519_sk_to_pk = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_sk_to_pk(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_ed25519_pk_to_curve25519 = function (x25519pk, ed25519pk) {
  assert(ArrayBuffer.isView(x25519pk), 'x25519pk must be a typed array')
  assert(ArrayBuffer.isView(ed25519pk), 'ed25519pk must be a typed array')
  assert(
    x25519pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "x25519pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    ed25519pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "ed25519pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_pk_to_curve25519(x25519pk, ed25519pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_ed25519_sk_to_curve25519 = function (x25519sk, ed25519sk) {
  assert(ArrayBuffer.isView(x25519sk), 'x25519sk must be a typed array')
  assert(ArrayBuffer.isView(ed25519sk), 'ed25519sk must be a typed array')
  assert(
    x25519sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "x25519sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const edLen = ed25519sk.byteLength

  assert(
    edLen === binding.crypto_sign_SECRETKEYBYTES || edLen === binding.crypto_box_SECRETKEYBYTES,
    "ed25519sk must be 'crypto_sign_SECRETKEYBYTES' or 'crypto_sign_SECRETKEYBYTES - crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_sk_to_curve25519(x25519sk, ed25519sk)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_box

exports.crypto_box_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    seed.byteLength === binding.crypto_box_SEEDBYTES,
    "seed must be 'crypto_box_SEEDBYTES' bytes"
  )

  const res = binding.crypto_box_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_easy = function (c, m, n, pk, sk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength === m.byteLength + exports.crypto_box_MACBYTES,
    "c must be 'm.byteLength + crypto_box_MACBYTES' bytes"
  )
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_easy(c, m, n, pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_detached = function (c, mac, m, n, pk, sk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(mac.byteLength === exports.crypto_box_MACBYTES, "mac must be 'crypto_box_MACBYTES' bytes")
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_detached(c, mac, m, n, pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_open_easy = function (m, c, n, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength >= exports.crypto_box_MACBYTES,
    "c must be at least 'crypto_box_MACBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - exports.crypto_box_MACBYTES,
    "m must be 'c.byteLength - crypto_box_MACBYTES' bytes"
  )
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_open_easy(m, c, n, pk, sk)
}

exports.crypto_box_open_detached = function (m, c, mac, n, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(mac.byteLength === exports.crypto_box_MACBYTES, "mac must be 'crypto_box_MACBYTES' bytes")
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_open_detached(m, c, mac, n, pk, sk)
}

exports.crypto_box_seal = function (c, m, pk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    c.byteLength === m.byteLength + exports.crypto_box_SEALBYTES,
    "c must be 'm.byteLength + crypto_box_SEALBYTES' bytes"
  )
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_box_seal(c, m, pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_seal_open = function (m, c, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength >= exports.crypto_box_SEALBYTES,
    "c must be at least 'crypto_box_SEALBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - exports.crypto_box_SEALBYTES,
    "m must be 'c.byteLength - crypto_box_SEALBYTES' bytes"
  )
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_seal_open(
    m.buffer,
    m.byteOffset,
    m.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    pk.buffer,
    pk.byteOffset,
    pk.byteLength,

    sk.buffer,
    sk.byteOffset,
    sk.byteLength
  )
}

// crypto_secretbox

exports.crypto_secretbox_easy = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_secretbox_MACBYTES,
    "c must be 'm.byteLength + crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretbox_easy(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretbox_open_easy = function (m, c, n, k) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    c.byteLength >= binding.crypto_secretbox_MACBYTES,
    "c must be at least 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - binding.crypto_secretbox_MACBYTES,
    "m must be 'c.byteLength - crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  return binding.crypto_secretbox_open_easy(m, c, n, k)
}

exports.crypto_secretbox_detached = function (c, mac, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    mac.byteLength === binding.crypto_secretbox_MACBYTES,
    "mac must be 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretbox_detached(c, mac, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretbox_open_detached = function (m, c, mac, n, k) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(
    mac.byteLength === binding.crypto_secretbox_MACBYTES,
    "mac must be 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  return binding.crypto_secretbox_open_detached(m, c, mac, n, k)
}

// crypto_generichash

exports.crypto_generichash = function (output, input, key) {
  if (!key) key = OPTIONAL

  assert(ArrayBuffer.isView(output), 'output must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    output.byteLength >= binding.crypto_generichash_BYTES_MIN &&
      output.byteLength <= binding.crypto_generichash_BYTES_MAX,
    'output must be between crypto_generichash_BYTES_MIN and crypto_generichash_BYTES_MAX bytes'
  )

  if (key !== OPTIONAL) {
    assert(ArrayBuffer.isView(key), 'key must be a typed array')
    assert(
      key.byteLength >= binding.crypto_generichash_KEYBYTES_MIN &&
        key.byteLength <= binding.crypto_generichash_KEYBYTES_MAX,
      'key must be between crypto_generichash_KEYBYTES_MIN and crypto_generichash_KEYBYTES_MAX bytes'
    )
  }

  const res = binding.crypto_generichash(
    output.buffer,
    output.byteOffset,
    output.byteLength,

    input.buffer,
    input.byteOffset,
    input.byteLength,

    key.buffer,
    key.byteOffset,
    key.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_batch = function (output, batch, key) {
  assert(ArrayBuffer.isView(output), 'output must be a typed array')

  if (isNode || batch.length < 4) {
    const res = binding.crypto_generichash_batch(output, batch, !!key, key || OPTIONAL)
    if (res !== 0) throw new Error('status: ' + res)
  } else {
    const state = Buffer.alloc(binding.crypto_generichash_STATEBYTES)

    exports.crypto_generichash_init(state, key, output.byteLength)

    for (const buf of batch) {
      exports.crypto_generichash_update(state, buf)
    }

    exports.crypto_generichash_final(state, output)
  }
}

exports.crypto_generichash_keygen = function (key) {
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(
    key.byteLength === binding.crypto_generichash_KEYBYTES,
    "key must be 'crypto_generichash_KEYBYTES' bytes"
  )

  const res = binding.crypto_generichash_keygen(key.buffer, key.byteOffset, key.byteLength)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_init = function (state, key, outputLength) {
  if (!key) key = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_init(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    key.buffer,
    key.byteOffset,
    key.byteLength,

    outputLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_update(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    input.buffer,
    input.byteOffset,
    input.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_final = function (state, output) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(output), 'output must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_final(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    output.buffer,
    output.byteOffset,
    output.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

// secretstream

exports.crypto_secretstream_xchacha20poly1305_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  binding.crypto_secretstream_xchacha20poly1305_keygen(k.buffer, k.byteOffset, k.byteLength)
}

exports.crypto_secretstream_xchacha20poly1305_init_push = function (state, header, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(header), 'header must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    header.byteLength === binding.crypto_secretstream_xchacha20poly1305_HEADERBYTES,
    "header must be 'crypto_secretstream_xchacha20poly1305_HEADERBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_init_push(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    header.buffer,
    header.byteOffset,
    header.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretstream_xchacha20poly1305_init_pull = function (state, header, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(header), 'header must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    header.byteLength === binding.crypto_secretstream_xchacha20poly1305_HEADERBYTES,
    "header must be 'crypto_secretstream_xchacha20poly1305_HEADERBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_init_pull(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    header.buffer,
    header.byteOffset,
    header.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretstream_xchacha20poly1305_push = function (state, c, m, ad, tag) {
  if (!ad) ad = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    c.byteLength === m.byteLength + binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "c must be 'm.byteLength + crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_push(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    ad.buffer,
    ad.byteOffset,
    ad.byteLength,

    tag
  )

  if (res < 0) throw new Error('push failed')

  return res
}

exports.crypto_secretstream_xchacha20poly1305_pull = function (state, m, tag, c, ad) {
  if (!ad) ad = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(tag), 'tag must be a typed array')
  assert(tag.byteLength === 1, 'tag must be 1 byte')

  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    c.byteLength >= binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "c must be at least 'crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "m must be 'c.byteLength - crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_pull(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    tag.buffer,
    tag.byteOffset,
    tag.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    ad.buffer,
    ad.byteOffset,
    ad.byteLength
  )

  if (res < 0) throw new Error('pull failed')

  return res
}

exports.crypto_secretstream_xchacha20poly1305_rekey = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )

  binding.crypto_secretstream_xchacha20poly1305_rekey(
    state.buffer,
    state.byteOffset,
    state.byteLength
  )
}

// crypto_stream

exports.crypto_stream = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xor(
    c.buffer,
    c.byteOffset,
    c.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    n.buffer,
    n.byteOffset,
    n.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_auth

exports.crypto_auth = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(out.byteLength === binding.crypto_auth_BYTES, "out must be 'crypto_auth_BYTES' bytes")
  assert(k.byteLength === binding.crypto_auth_KEYBYTES, "k must be 'crypto_auth_KEYBYTES' bytes")

  const res = binding.crypto_auth(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_auth_verify = function (h, input, k) {
  assert(ArrayBuffer.isView(h), 'h must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(h.byteLength === binding.crypto_auth_BYTES, "h must be 'crypto_auth_BYTES' bytes")
  assert(k.byteLength === binding.crypto_auth_KEYBYTES, "k must be 'crypto_auth_KEYBYTES' bytes")

  return binding.crypto_auth_verify(h, input, k)
}

// crypto_onetimeauth

exports.crypto_onetimeauth = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    out.byteLength === binding.crypto_onetimeauth_BYTES,
    "out must be 'crypto_onetimeauth_BYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_init = function (state, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_init(state, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )
  assert(
    out.byteLength === binding.crypto_onetimeauth_BYTES,
    "out must be 'crypto_onetimeauth_BYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_verify = function (h, input, k) {
  assert(ArrayBuffer.isView(h), 'h must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    h.byteLength === binding.crypto_onetimeauth_BYTES,
    "h must be 'crypto_onetimeauth_BYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  return binding.crypto_onetimeauth_verify(h, input, k)
}

// crypto_pwhash

exports.crypto_pwhash = function (out, passwd, salt, opslimit, memlimit, alg) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_BYTES_MIN,
    "out must be at least 'crypto_pwhash_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_BYTES_MAX,
    "out must be at most 'crypto_pwhash_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_SALTBYTES,
    "salt must be 'crypto_pwhash_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )
  assert(alg >= 1 && alg <= 2, 'alg must be either Argon2i 1.3 or Argon2id 1.3')

  const res = binding.crypto_pwhash(out, passwd, salt, opslimit, memlimit, alg)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_async = function (
  out,
  passwd,
  salt,
  opslimit,
  memlimit,
  alg,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_BYTES_MIN,
    "out must be at least 'crypto_pwhash_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_BYTES_MAX,
    "out must be at most 'crypto_pwhash_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_SALTBYTES,
    "salt must be 'crypto_pwhash_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )
  assert(alg >= 1 && alg <= 2, 'alg must be either Argon2i 1.3 or Argon2id 1.3')

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    opslimit,
    memlimit,
    alg,

    done
  )

  return promise
}

exports.crypto_pwhash_str = function (out, passwd, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_STRBYTES,
    "out must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(typeof opslimit === 'number', 'opslimit must be a number')
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(typeof memlimit === 'number', 'memlimit must be a number')
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_str(out, passwd, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_str_async = function (out, passwd, opslimit, memlimit, callback = undefined) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_STRBYTES,
    "out must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(typeof opslimit === 'number', 'opslimit must be a number')
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(typeof memlimit === 'number', 'memlimit must be a number')
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_str_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_str_verify = function (str, passwd) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )

  return binding.crypto_pwhash_str_verify(str, passwd)
}

exports.crypto_pwhash_str_verify_async = function (str, passwd, callback = undefined) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  const [done, promise] = checkStatus(callback, true)

  binding.crypto_pwhash_str_verify_async(
    str.buffer,
    str.byteOffset,
    str.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    done
  )

  return promise
}

exports.crypto_pwhash_str_needs_rehash = function (str, opslimit, memlimit) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  return binding.crypto_pwhash_str_needs_rehash(str, opslimit, memlimit)
}

exports.crypto_pwhash_scryptsalsa208sha256 = function (out, passwd, salt, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MIN,
    "out must be at least 'crypto_pwhash_scryptsalsa208sha256_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MAX,
    "out must be at most 'crypto_pwhash_scryptsalsa208sha256_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_SALTBYTES,
    "salt must be 'crypto_pwhash_scryptsalsa208sha256_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_scryptsalsa208sha256(out, passwd, salt, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_scryptsalsa208sha256_async = function (
  out,
  passwd,
  salt,
  opslimit,
  memlimit,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MIN,
    "out must be at least 'crypto_pwhash_scryptsalsa208sha256_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MAX,
    "out must be at most 'crypto_pwhash_scryptsalsa208sha256_BYTES_MAX' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    salt.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_SALTBYTES,
    "salt must be 'crypto_pwhash_scryptsalsa208sha256_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_scryptsalsa208sha256_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str_async = function (
  out,
  passwd,
  opslimit,
  memlimit,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "out must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_scryptsalsa208sha256_str_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str = function (out, passwd, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "out must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_scryptsalsa208sha256_str(out, passwd, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_scryptsalsa208sha256_str_verify_async = function (
  str,
  passwd,
  callback = undefined
) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  const [done, promise] = checkStatus(callback, true)

  binding.crypto_pwhash_scryptsalsa208sha256_str_verify_async(
    str.buffer,
    str.byteOffset,
    str.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str_verify = function (str, passwd) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  return binding.crypto_pwhash_scryptsalsa208sha256_str_verify(str, passwd)
}

exports.crypto_pwhash_scryptsalsa208sha256_str_needs_rehash = function (str, opslimit, memlimit) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  return binding.crypto_pwhash_scryptsalsa208sha256_str_needs_rehash(str, opslimit, memlimit)
}

// crypto_kx

exports.crypto_kx_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "pk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "sk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    pk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "pk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "sk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    seed.byteLength === binding.crypto_kx_SEEDBYTES,
    "seed must be 'crypto_kx_SEEDBYTES' bytes"
  )

  const res = binding.crypto_kx_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_client_session_keys = function (rx, tx, clientPk, clientSk, serverPk) {
  if (!rx) rx = undefined
  if (!tx) tx = undefined

  assert(rx || tx, 'at least one session key must be specified')

  if (rx) {
    assert(ArrayBuffer.isView(rx), 'rx must be a typed array')
    assert(
      rx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "rx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  if (tx) {
    assert(ArrayBuffer.isView(tx), 'tx must be a typed array')
    assert(
      tx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "tx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  assert(ArrayBuffer.isView(clientPk), 'clientPk must be a typed array')
  assert(ArrayBuffer.isView(clientSk), 'clientSk must be a typed array')
  assert(ArrayBuffer.isView(serverPk), 'serverPk must be a typed array')
  assert(
    clientPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "clientPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    clientSk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "clientSk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    serverPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "serverPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_client_session_keys(rx, tx, clientPk, clientSk, serverPk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_server_session_keys = function (rx, tx, serverPk, serverSk, clientPk) {
  if (!rx) rx = undefined
  if (!tx) tx = undefined

  assert(rx || tx, 'at least one session key must be specified')

  if (rx) {
    assert(ArrayBuffer.isView(rx), 'rx must be a typed array')
    assert(
      rx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "rx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  if (tx) {
    assert(ArrayBuffer.isView(tx), 'tx must be a typed array')
    assert(
      tx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "tx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  assert(ArrayBuffer.isView(serverPk), 'serverPk must be a typed array')
  assert(ArrayBuffer.isView(serverSk), 'serverSk must be a typed array')
  assert(ArrayBuffer.isView(clientPk), 'clientPk must be a typed array')
  assert(
    serverPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "serverPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    serverSk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "serverSk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    clientPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "clientPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_server_session_keys(rx, tx, serverPk, serverSk, clientPk)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_scalarmult

exports.crypto_scalarmult_base = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_BYTES,
    "q must be 'crypto_scalarmult_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_SCALARBYTES,
    "n must be 'crypto_scalarmult_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_base(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_BYTES,
    "q must be 'crypto_scalarmult_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_SCALARBYTES,
    "n must be 'crypto_scalarmult_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_BYTES,
    "p must be 'crypto_scalarmult_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_base = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_base(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519 = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "p must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_is_valid_point = function (p) {
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )

  return binding.crypto_core_ed25519_is_valid_point(p)
}

exports.crypto_core_ed25519_from_uniform = function (p, r) {
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_UNIFORMBYTES,
    "r must be 'crypto_core_ed25519_UNIFORMBYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_from_uniform(p, r)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_base_noclamp = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_base_noclamp(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_noclamp = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "p must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_noclamp(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_core

exports.crypto_core_ed25519_add = function (r, p, q) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_BYTES,
    "r must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_core_ed25519_BYTES,
    "q must be 'crypto_core_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_add(r, p, q)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_sub = function (r, p, q) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_BYTES,
    "r must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_core_ed25519_BYTES,
    "q must be 'crypto_core_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_sub(r, p, q)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_scalar_random = function (r) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "r must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_random(r)
}

exports.crypto_core_ed25519_scalar_reduce = function (r, s) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "r must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_NONREDUCEDSCALARBYTES,
    "s must be 'crypto_core_ed25519_NONREDUCEDSCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_reduce(r, s)
}

exports.crypto_core_ed25519_scalar_invert = function (recip, s) {
  assert(ArrayBuffer.isView(recip), 'recip must be a typed array')
  assert(
    recip.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "recip must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_invert(recip, s)
}

exports.crypto_core_ed25519_scalar_negate = function (neg, s) {
  assert(ArrayBuffer.isView(neg), 'neg must be a typed array')
  assert(
    neg.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "neg must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_negate(neg, s)
}

exports.crypto_core_ed25519_scalar_complement = function (comp, s) {
  assert(ArrayBuffer.isView(comp), 'comp must be a typed array')
  assert(
    comp.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "comp must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_complement(comp, s)
}

exports.crypto_core_ed25519_scalar_add = function (z, x, y) {
  assert(ArrayBuffer.isView(z), 'z must be a typed array')
  assert(
    z.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "z must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(x), 'x must be a typed array')
  assert(
    x.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "x must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(y), 'y must be a typed array')
  assert(
    y.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "y must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_add(z, x, y)
}

exports.crypto_core_ed25519_scalar_sub = function (z, x, y) {
  assert(ArrayBuffer.isView(z), 'z must be a typed array')
  assert(
    z.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "z must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(x), 'x must be a typed array')
  assert(
    x.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "x must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(y), 'y must be a typed array')
  assert(
    y.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "y must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_sub(z, x, y)
}

// crypto_shorthash

exports.crypto_shorthash = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_shorthash_BYTES,
    "out must be 'crypto_shorthash_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_shorthash_KEYBYTES,
    "k must be 'crypto_shorthash_KEYBYTES' bytes"
  )

  const res = binding.crypto_shorthash(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_kdf

exports.crypto_kdf_keygen = function (key) {
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(key.byteLength === binding.crypto_kdf_KEYBYTES, "key must be 'crypto_kdf_KEYBYTES' bytes")

  binding.crypto_kdf_keygen(key)
}

exports.crypto_kdf_derive_from_key = function (subkey, subkeyId, ctx, key) {
  assert(ArrayBuffer.isView(subkey), 'subkey must be a typed array')
  assert(
    subkey.byteLength >= binding.crypto_kdf_BYTES_MIN,
    "subkey must be at least 'crypto_kdf_BYTES_MIN' bytes"
  )
  assert(
    subkey.byteLength <= binding.crypto_kdf_BYTES_MAX,
    "subkey must be at most 'crypto_kdf_BYTES_MAX' bytes"
  )
  assert(ArrayBuffer.isView(ctx), 'ctx must be a typed array')
  assert(
    ctx.byteLength === binding.crypto_kdf_CONTEXTBYTES,
    "ctx must be 'crypto_kdf_CONTEXTBYTES' bytes"
  )
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(key.byteLength === binding.crypto_kdf_KEYBYTES, "key must be 'crypto_kdf_KEYBYTES' bytes")

  const res = binding.crypto_kdf_derive_from_key(subkey, subkeyId, ctx, key)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_hash

exports.crypto_hash = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(out.byteLength === binding.crypto_hash_BYTES, "out must be 'crypto_hash_BYTES' bytes")

  const res = binding.crypto_hash(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256 = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha256_BYTES,
    "out must be 'crypto_hash_sha256_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha256(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_init = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_init(state)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha256_BYTES,
    "out must be 'crypto_hash_sha256_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512 = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha512_BYTES,
    "out must be 'crypto_hash_sha512_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha512(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_init = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_init(state)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha512_BYTES,
    "out must be 'crypto_hash_sha512_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_aead

exports.crypto_aead_xchacha20poly1305_ietf_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  binding.crypto_aead_xchacha20poly1305_ietf_keygen(k)
}

exports.crypto_aead_xchacha20poly1305_ietf_encrypt = function (c, m, ad, nsec, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "c must be 'm.byteLength + crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(c.byteLength <= 0xffffffff, 'c.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_encrypt(c, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_decrypt = function (m, nsec, c, ad, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "m must be 'c.byteLength - crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(m.byteLength <= 0xffffffff, 'm.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_decrypt(m, c, ad, npub, k)

  if (res < 0) throw new Error('could not verify data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_encrypt_detached = function (
  c,
  mac,
  m,
  ad,
  nsec,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_encrypt_detached(c, mac, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_decrypt_detached = function (
  m,
  nsec,
  c,
  mac,
  ad,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_decrypt_detached(m, c, mac, ad, npub, k)

  if (res !== 0) throw new Error('could not verify data')
}

exports.crypto_aead_chacha20poly1305_ietf_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  binding.crypto_aead_chacha20poly1305_ietf_keygen(k)
}

exports.crypto_aead_chacha20poly1305_ietf_encrypt = function (c, m, ad, nsec, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "c must be 'm.byteLength + crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(c.byteLength <= 0xffffffff, 'c.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_encrypt(c, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_decrypt = function (m, nsec, c, ad, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "m must be 'c.byteLength - crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(m.byteLength <= 0xffffffff, 'm.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_decrypt(m, c, ad, npub, k)

  if (res < 0) throw new Error('could not verify data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_encrypt_detached = function (
  c,
  mac,
  m,
  ad,
  nsec,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_encrypt_detached(c, mac, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_decrypt_detached = function (
  m,
  nsec,
  c,
  mac,
  ad,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_decrypt_detached(m, c, mac, ad, npub, k)

  if (res !== 0) throw new Error('could not verify data')
}

// crypto_stream

exports.crypto_stream_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  binding.crypto_stream_xor_wrap_init(state, n, k)
}

exports.crypto_stream_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_xor_wrap_update(state, c, m)
}

exports.crypto_stream_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_xor_wrap_final(state)
}

exports.crypto_stream_chacha20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  binding.crypto_stream_chacha20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_chacha20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_chacha20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_chacha20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_chacha20_xor_wrap_final(state)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  binding.crypto_stream_chacha20_ietf_xor_wrap_init(state, n, k)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_chacha20_ietf_xor_wrap_update(state, c, m)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_chacha20_ietf_xor_wrap_final(state)
}

exports.crypto_stream_xchacha20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  binding.crypto_stream_xchacha20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_xchacha20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_xchacha20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_xchacha20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_xchacha20_xor_wrap_final(state)
}

exports.crypto_stream_salsa20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  binding.crypto_stream_salsa20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_salsa20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_salsa20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_salsa20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_salsa20_xor_wrap_final(state)
}

// experimental

exports.extension_tweak_ed25519_base = function (n, p, ns) {
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.extension_tweak_ed25519_BYTES,
    "p must be 'extension_tweak_ed25519_BYTES' bytes"
  )

  binding.extension_tweak_ed25519_base(n, p, ns)
}

exports.extension_tweak_ed25519_sign_detached = function (sig, m, scalar, pk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(sig.byteLength === binding.crypto_sign_BYTES, "sig must be 'crypto_sign_BYTES' bytes")
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  if (pk) {
    assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
    assert(
      pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
      "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
    )
  }

  const res = binding.extension_tweak_ed25519_sign_detached(sig, m, scalar, pk)

  if (res !== 0) throw new Error('failed to compute signature')
}

exports.extension_tweak_ed25519_sk_to_scalar = function (n, sk) {
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  binding.extension_tweak_ed25519_sk_to_scalar(n, sk)
}

exports.extension_tweak_ed25519_scalar = function (scalarOut, scalar, ns) {
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_scalar(scalarOut, scalar, ns)
}

exports.extension_tweak_ed25519_pk = function (tpk, pk, ns) {
  assert(ArrayBuffer.isView(tpk), 'tpk must be a typed array')
  assert(
    tpk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "tpk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_pk(tpk, pk, ns)

  if (res !== 0) throw new Error('failed to tweak public key')
}

exports.extension_tweak_ed25519_keypair = function (pk, scalarOut, scalarIn, ns) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.extension_tweak_ed25519_BYTES,
    "pk must be 'extension_tweak_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarIn), 'scalarIn must be a typed array')
  assert(
    scalarIn.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarIn must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_keypair(pk, scalarOut, scalarIn, ns)
}

exports.extension_tweak_ed25519_scalar_add = function (scalarOut, scalar, n) {
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_scalar_add(scalarOut, scalar, n)
}

exports.extension_tweak_ed25519_pk_add = function (tpk, pk, p) {
  assert(ArrayBuffer.isView(tpk), 'tpk must be a typed array')
  assert(
    tpk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "tpk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "p must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_pk_add(tpk, pk, p)

  if (res !== 0) throw new Error('failed to add tweak to public key')
}

exports.extension_tweak_ed25519_keypair_add = function (pk, scalarOut, scalarIn, tweak) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.extension_tweak_ed25519_BYTES,
    "pk must be 'extension_tweak_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarIn), 'scalarIn must be a typed array')
  assert(
    scalarIn.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarIn must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(tweak), 'tweak must be a typed array')
  assert(
    tweak.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "tweak must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_keypair_add(pk, scalarOut, scalarIn, tweak)

  if (res !== 0) throw new Error('failed to add tweak to keypair')
}

exports.extension_pbkdf2_sha512_async = function (out, passwd, salt, iter, outlen, callback) {
  assert(
    iter >= binding.extension_pbkdf2_sha512_ITERATIONS_MIN,
    "iter must be at least 'extension_pbkdf2_sha512_ITERATIONS_MIN'"
  )
  assert(
    outlen <= binding.extension_pbkdf2_sha512_BYTES_MAX,
    "outlen must be at most 'extension_pbkdf2_sha512_BYTES_MAX'"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(out.byteLength >= outlen, "out must be at least 'outlen' bytes")
  assert(out.byteLength > 0, 'out must not be empty')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(salt.byteLength > 0, 'salt must not be empty')

  const [done, promise] = checkStatus(callback)

  binding.extension_pbkdf2_sha512_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    iter,
    outlen,

    done
  )

  return promise
}

exports.extension_pbkdf2_sha512 = function (out, passwd, salt, iter, outlen) {
  assert(
    iter >= binding.extension_pbkdf2_sha512_ITERATIONS_MIN,
    "iter must be at least 'extension_pbkdf2_sha512_ITERATIONS_MIN'"
  )
  assert(
    outlen <= binding.extension_pbkdf2_sha512_BYTES_MAX,
    "outlen must be at most 'extension_pbkdf2_sha512_BYTES_MAX'"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(out.byteLength >= outlen, "out must be at least 'outlen' bytes")
  assert(out.byteLength > 0, 'out must not be empty')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(salt.byteLength > 0, 'salt must not be empty')

  const res = binding.extension_pbkdf2_sha512(out, passwd, salt, iter, outlen)

  if (res !== 0) throw new Error('failed to add tweak to public key')
}

function checkStatus(callback, booleanResult = false) {
  let done, promise

  if (typeof callback === 'function') {
    done = function (status) {
      if (booleanResult) callback(null, status === 0)
      else if (status === 0) callback(null)
      else callback(new Error('status: ' + status))
    }
  } else {
    promise = new Promise(function (resolve, reject) {
      done = function (status) {
        if (booleanResult) resolve(status === 0)
        else if (status === 0) resolve()
        else reject(new Error('status: ' + status))
      }
    })
  }

  return [done, promise]
}
{
  "name": "sodium-native",
  "version": "5.1.0",
  "description": "Low level bindings for libsodium",
  "main": "index.js",
  "files": [
    "index.js",
    "binding.cc",
    "binding.js",
    "extensions",
    "prebuilds",
    "CMakeLists.txt"
  ],
  "imports": {
    "assert": {
      "bare": "bare-assert",
      "node": "assert"
    }
  },
  "addon": true,
  "dependencies": {
    "bare-assert": "^1.2.0",
    "require-addon": "^1.1.0",
    "which-runtime": "^1.2.1"
  },
  "devDependencies": {
    "bare-compat-napi": "^1.3.5",
    "brittle": "^3.16.2",
    "cmake-bare": "^1.6.1",
    "cmake-fetch": "^1.4.3",
    "cmake-napi": "^1.2.1",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "test": "prettier . --check && npm run test:node && npm run test:bare",
    "test:node": "node test/all.js",
    "test:bare": "bare test/all.js"
  },
  "standard": {
    "ignore": [
      "/test/fixtures/*.js"
    ]
  },
  "engines": {
    "bare": ">=1.16.0"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sodium-native.git"
  },
  "contributors": [
    "Emil Bay <github@tixz.dk> (http://bayes.dk)",
    "Mathias Buus <mathiasbuus@gmail.com> (https://mafinto.sh)",
    "Christophe Diederichs <chm-diederichs@hyperdivision.dk>"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/sodium-native/issues"
  },
  "homepage": "https://github.com/holepunchto/sodium-native"
}
const sodium = require('sodium-universal')
const b4a = require('b4a')

const ABYTES = sodium.crypto_secretstream_xchacha20poly1305_ABYTES
const TAG_MESSAGE = sodium.crypto_secretstream_xchacha20poly1305_TAG_MESSAGE
const TAG_FINAL = sodium.crypto_secretstream_xchacha20poly1305_TAG_FINAL
const STATEBYTES = sodium.crypto_secretstream_xchacha20poly1305_STATEBYTES
const HEADERBYTES = sodium.crypto_secretstream_xchacha20poly1305_HEADERBYTES
const KEYBYTES = sodium.crypto_secretstream_xchacha20poly1305_KEYBYTES
const TAG_FINAL_BYTE = b4a.isBuffer(TAG_FINAL) ? TAG_FINAL[0] : TAG_FINAL

const EMPTY = b4a.alloc(0)
const TAG = b4a.alloc(1)

class Push {
  constructor (key, state = b4a.allocUnsafeSlow(STATEBYTES), header = b4a.allocUnsafeSlow(HEADERBYTES)) {
    if (!TAG_FINAL) throw new Error('JavaScript sodium version needs to support crypto_secretstream_xchacha20poly')

    this.key = key
    this.state = state
    this.header = header

    sodium.crypto_secretstream_xchacha20poly1305_init_push(this.state, this.header, this.key)
  }

  next (message, cipher = b4a.allocUnsafe(message.byteLength + ABYTES)) {
    sodium.crypto_secretstream_xchacha20poly1305_push(this.state, cipher, message, null, TAG_MESSAGE)
    return cipher
  }

  final (message = EMPTY, cipher = b4a.allocUnsafe(ABYTES)) {
    sodium.crypto_secretstream_xchacha20poly1305_push(this.state, cipher, message, null, TAG_FINAL)
    return cipher
  }
}

class Pull {
  constructor (key, state = b4a.allocUnsafeSlow(STATEBYTES)) {
    if (!TAG_FINAL) throw new Error('JavaScript sodium version needs to support crypto_secretstream_xchacha20poly')

    this.key = key
    this.state = state
    this.final = false
  }

  init (header) {
    sodium.crypto_secretstream_xchacha20poly1305_init_pull(this.state, header, this.key)
  }

  next (cipher, message = b4a.allocUnsafe(cipher.byteLength - ABYTES)) {
    sodium.crypto_secretstream_xchacha20poly1305_pull(this.state, message, TAG, cipher, null)
    this.final = TAG[0] === TAG_FINAL_BYTE
    return message
  }
}

function keygen (buf = b4a.alloc(KEYBYTES)) {
  sodium.crypto_secretstream_xchacha20poly1305_keygen(buf)
  return buf
}

module.exports = {
  keygen,
  KEYBYTES,
  ABYTES,
  STATEBYTES,
  HEADERBYTES,
  Push,
  Pull
}
{
  "name": "sodium-secretstream",
  "version": "1.2.0",
  "description": "Wraps libsodiums secretstream in a higher level abstraction",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.1.1",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "standard": "^17.0.0"
  },
  "scripts": {
    "test": "standard"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/sodium-secretstream.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/sodium-secretstream/issues"
  },
  "homepage": "https://github.com/mafintosh/sodium-secretstream"
}
module.exports = require('sodium-native')
{
  "name": "sodium-universal",
  "version": "5.0.1",
  "description": "Universal wrapper for sodium-javascript and sodium-native working in Node.js and the Browser",
  "main": "index.js",
  "dependencies": {
    "sodium-native": "^5.0.1"
  },
  "peerDependencies": {
    "sodium-javascript": "~0.8.0"
  },
  "peerDependenciesMeta": {
    "sodium-javascript": {
      "optional": true
    }
  },
  "scripts": {
    "prepublish": "./build-scripts/generate.js"
  },
  "browser": {
    "sodium-native": "sodium-javascript"
  },
  "browserify": {
    "transform": [
      "./build-scripts/transform.js"
    ]
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sodium-universal.git"
  },
  "keywords": [
    "libsodium",
    "sodium",
    "sodium-native",
    "sodium-javascript",
    "browserify"
  ],
  "contributors": [
    "Emil Bay <github@tixz.dk> (http://bayes.dk)",
    "Mathias Buus <mathiasbuus@gmail.com> (https://mafinto.sh)",
    "Christophe Diederichs <chm-diederichs@hyperdivision.dk>"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/sodium-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/sodium-universal#readme"
}
const { EventEmitter } = require('events-universal')
const FIFO = require('fast-fifo')
const TextDecoder = require('text-decoder')

const StreamError = require('./lib/errors.js')

// if we do a future major, expect queue microtask to be there always, for now a bit defensive
const qmt =
  typeof queueMicrotask === 'undefined' ? (fn) => global.process.nextTick(fn) : queueMicrotask

// 29 bits used total (4 from shared, 14 from read, and 11 from write)
const MAX = (1 << 29) - 1

// Shared state
const OPENING = 0b0001
const PREDESTROYING = 0b0010
const DESTROYING = 0b0100
const DESTROYED = 0b1000

const NOT_OPENING = MAX ^ OPENING
const NOT_PREDESTROYING = MAX ^ PREDESTROYING

// Read state (4 bit offset from shared state)
const READ_ACTIVE = 0b00000000000001 << 4
const READ_UPDATING = 0b00000000000010 << 4
const READ_PRIMARY = 0b00000000000100 << 4
const READ_QUEUED = 0b00000000001000 << 4
const READ_RESUMED = 0b00000000010000 << 4
const READ_PIPE_DRAINED = 0b00000000100000 << 4
const READ_ENDING = 0b00000001000000 << 4
const READ_EMIT_DATA = 0b00000010000000 << 4
const READ_EMIT_READABLE = 0b00000100000000 << 4
const READ_EMITTED_READABLE = 0b00001000000000 << 4
const READ_DONE = 0b00010000000000 << 4
const READ_NEXT_TICK = 0b00100000000000 << 4
const READ_NEEDS_PUSH = 0b01000000000000 << 4
const READ_READ_AHEAD = 0b10000000000000 << 4

// Combined read state
const READ_FLOWING = READ_RESUMED | READ_PIPE_DRAINED
const READ_ACTIVE_AND_NEEDS_PUSH = READ_ACTIVE | READ_NEEDS_PUSH
const READ_PRIMARY_AND_ACTIVE = READ_PRIMARY | READ_ACTIVE
const READ_EMIT_READABLE_AND_QUEUED = READ_EMIT_READABLE | READ_QUEUED
const READ_RESUMED_READ_AHEAD = READ_RESUMED | READ_READ_AHEAD

const READ_NOT_ACTIVE = MAX ^ READ_ACTIVE
const READ_NON_PRIMARY = MAX ^ READ_PRIMARY
const READ_NON_PRIMARY_AND_PUSHED = MAX ^ (READ_PRIMARY | READ_NEEDS_PUSH)
const READ_PUSHED = MAX ^ READ_NEEDS_PUSH
const READ_PAUSED = MAX ^ READ_RESUMED
const READ_NOT_QUEUED = MAX ^ (READ_QUEUED | READ_EMITTED_READABLE)
const READ_NOT_ENDING = MAX ^ READ_ENDING
const READ_PIPE_NOT_DRAINED = MAX ^ READ_FLOWING
const READ_NOT_NEXT_TICK = MAX ^ READ_NEXT_TICK
const READ_NOT_UPDATING = MAX ^ READ_UPDATING
const READ_NO_READ_AHEAD = MAX ^ READ_READ_AHEAD
const READ_PAUSED_NO_READ_AHEAD = MAX ^ READ_RESUMED_READ_AHEAD

// Write state (18 bit offset, 4 bit offset from shared state and 14 from read state)
const WRITE_ACTIVE = 0b00000000001 << 18
const WRITE_UPDATING = 0b00000000010 << 18
const WRITE_PRIMARY = 0b00000000100 << 18
const WRITE_QUEUED = 0b00000001000 << 18
const WRITE_UNDRAINED = 0b00000010000 << 18
const WRITE_DONE = 0b00000100000 << 18
const WRITE_EMIT_DRAIN = 0b00001000000 << 18
const WRITE_NEXT_TICK = 0b00010000000 << 18
const WRITE_WRITING = 0b00100000000 << 18
const WRITE_FINISHING = 0b01000000000 << 18
const WRITE_CORKED = 0b10000000000 << 18

const WRITE_NOT_ACTIVE = MAX ^ (WRITE_ACTIVE | WRITE_WRITING)
const WRITE_NON_PRIMARY = MAX ^ WRITE_PRIMARY
const WRITE_NOT_FINISHING = MAX ^ (WRITE_ACTIVE | WRITE_FINISHING)
const WRITE_DRAINED = MAX ^ WRITE_UNDRAINED
const WRITE_NOT_QUEUED = MAX ^ WRITE_QUEUED
const WRITE_NOT_NEXT_TICK = MAX ^ WRITE_NEXT_TICK
const WRITE_NOT_UPDATING = MAX ^ WRITE_UPDATING
const WRITE_NOT_CORKED = MAX ^ WRITE_CORKED

// Combined shared state
const ACTIVE = READ_ACTIVE | WRITE_ACTIVE
const NOT_ACTIVE = MAX ^ ACTIVE
const DONE = READ_DONE | WRITE_DONE
const DESTROY_STATUS = DESTROYING | DESTROYED | PREDESTROYING
const OPEN_STATUS = DESTROY_STATUS | OPENING
const AUTO_DESTROY = DESTROY_STATUS | DONE
const NON_PRIMARY = WRITE_NON_PRIMARY & READ_NON_PRIMARY
const ACTIVE_OR_TICKING = WRITE_NEXT_TICK | READ_NEXT_TICK
const TICKING = ACTIVE_OR_TICKING & NOT_ACTIVE
const IS_OPENING = OPEN_STATUS | TICKING

// Combined shared state and read state
const READ_PRIMARY_STATUS = OPEN_STATUS | READ_ENDING | READ_DONE
const READ_STATUS = OPEN_STATUS | READ_DONE | READ_QUEUED
const READ_ENDING_STATUS = OPEN_STATUS | READ_ENDING | READ_QUEUED
const READ_READABLE_STATUS = OPEN_STATUS | READ_EMIT_READABLE | READ_QUEUED | READ_EMITTED_READABLE
const SHOULD_NOT_READ =
  OPEN_STATUS | READ_ACTIVE | READ_ENDING | READ_DONE | READ_NEEDS_PUSH | READ_READ_AHEAD
const READ_BACKPRESSURE_STATUS = DESTROY_STATUS | READ_ENDING | READ_DONE
const READ_UPDATE_SYNC_STATUS = READ_UPDATING | OPEN_STATUS | READ_NEXT_TICK | READ_PRIMARY
const READ_NEXT_TICK_OR_OPENING = READ_NEXT_TICK | OPENING

// Combined write state
const WRITE_PRIMARY_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_DONE
const WRITE_QUEUED_AND_UNDRAINED = WRITE_QUEUED | WRITE_UNDRAINED
const WRITE_QUEUED_AND_ACTIVE = WRITE_QUEUED | WRITE_ACTIVE
const WRITE_DRAIN_STATUS = WRITE_QUEUED | WRITE_UNDRAINED | OPEN_STATUS | WRITE_ACTIVE
const WRITE_STATUS = OPEN_STATUS | WRITE_ACTIVE | WRITE_QUEUED | WRITE_CORKED
const WRITE_PRIMARY_AND_ACTIVE = WRITE_PRIMARY | WRITE_ACTIVE
const WRITE_ACTIVE_AND_WRITING = WRITE_ACTIVE | WRITE_WRITING
const WRITE_FINISHING_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_QUEUED_AND_ACTIVE | WRITE_DONE
const WRITE_BACKPRESSURE_STATUS = WRITE_UNDRAINED | DESTROY_STATUS | WRITE_FINISHING | WRITE_DONE
const WRITE_UPDATE_SYNC_STATUS = WRITE_UPDATING | OPEN_STATUS | WRITE_NEXT_TICK | WRITE_PRIMARY
const WRITE_DROP_DATA = WRITE_FINISHING | WRITE_DONE | DESTROY_STATUS

const asyncIterator = Symbol.asyncIterator || Symbol('asyncIterator')

class WritableState {
  constructor(
    stream,
    { highWaterMark = 16384, map = null, mapWritable, byteLength, byteLengthWritable } = {}
  ) {
    this.stream = stream
    this.queue = new FIFO()
    this.highWaterMark = highWaterMark
    this.buffered = 0
    this.error = null
    this.pipeline = null
    this.drains = null // if we add more seldomly used helpers we might them into a subobject so its a single ptr
    this.byteLength = byteLengthWritable || byteLength || defaultByteLength
    this.map = mapWritable || map
    this.afterWrite = afterWrite.bind(this)
    this.afterUpdateNextTick = updateWriteNT.bind(this)
  }

  get ending() {
    return (this.stream._duplexState & WRITE_FINISHING) !== 0
  }

  get ended() {
    return (this.stream._duplexState & WRITE_DONE) !== 0
  }

  push(data) {
    if ((this.stream._duplexState & WRITE_DROP_DATA) !== 0) return false
    if (this.map !== null) data = this.map(data)

    this.buffered += this.byteLength(data)
    this.queue.push(data)

    if (this.buffered < this.highWaterMark) {
      this.stream._duplexState |= WRITE_QUEUED
      return true
    }

    this.stream._duplexState |= WRITE_QUEUED_AND_UNDRAINED
    return false
  }

  shift() {
    const data = this.queue.shift()

    this.buffered -= this.byteLength(data)
    if (this.buffered === 0) this.stream._duplexState &= WRITE_NOT_QUEUED

    return data
  }

  end(data) {
    if (typeof data === 'function') {
      this.stream.once('finish', data)
    } else if (data !== undefined && data !== null) {
      this.push(data)
    }

    this.stream._duplexState = (this.stream._duplexState | WRITE_FINISHING) & WRITE_NON_PRIMARY
  }

  autoBatch(data, cb) {
    const buffer = []
    const stream = this.stream

    buffer.push(data)
    while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED_AND_ACTIVE) {
      buffer.push(stream._writableState.shift())
    }

    if ((stream._duplexState & OPEN_STATUS) !== 0) return cb(null)
    stream._writev(buffer, cb)
  }

  update() {
    const stream = this.stream

    stream._duplexState |= WRITE_UPDATING

    do {
      while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED) {
        const data = this.shift()
        stream._duplexState |= WRITE_ACTIVE_AND_WRITING
        stream._write(data, this.afterWrite)
      }

      if ((stream._duplexState & WRITE_PRIMARY_AND_ACTIVE) === 0) this.updateNonPrimary()
    } while (this.continueUpdate() === true)

    stream._duplexState &= WRITE_NOT_UPDATING
  }

  updateNonPrimary() {
    const stream = this.stream

    if ((stream._duplexState & WRITE_FINISHING_STATUS) === WRITE_FINISHING) {
      stream._duplexState = stream._duplexState | WRITE_ACTIVE
      stream._final(afterFinal.bind(this))
      return
    }

    if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
      if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
        stream._duplexState |= ACTIVE
        stream._destroy(afterDestroy.bind(this))
      }
      return
    }

    if ((stream._duplexState & IS_OPENING) === OPENING) {
      stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING
      stream._open(afterOpen.bind(this))
    }
  }

  continueUpdate() {
    if ((this.stream._duplexState & WRITE_NEXT_TICK) === 0) return false
    this.stream._duplexState &= WRITE_NOT_NEXT_TICK
    return true
  }

  updateCallback() {
    if ((this.stream._duplexState & WRITE_UPDATE_SYNC_STATUS) === WRITE_PRIMARY) {
      this.update()
    } else {
      this.updateNextTick()
    }
  }

  updateNextTick() {
    if ((this.stream._duplexState & WRITE_NEXT_TICK) !== 0) return
    this.stream._duplexState |= WRITE_NEXT_TICK
    if ((this.stream._duplexState & WRITE_UPDATING) === 0) qmt(this.afterUpdateNextTick)
  }
}

class ReadableState {
  constructor(
    stream,
    { highWaterMark = 16384, map = null, mapReadable, byteLength, byteLengthReadable } = {}
  ) {
    this.stream = stream
    this.queue = new FIFO()
    this.highWaterMark = highWaterMark === 0 ? 1 : highWaterMark
    this.buffered = 0
    this.readAhead = highWaterMark > 0
    this.error = null
    this.pipeline = null
    this.byteLength = byteLengthReadable || byteLength || defaultByteLength
    this.map = mapReadable || map
    this.pipeTo = null
    this.afterRead = afterRead.bind(this)
    this.afterUpdateNextTick = updateReadNT.bind(this)
  }

  get ending() {
    return (this.stream._duplexState & READ_ENDING) !== 0
  }

  get ended() {
    return (this.stream._duplexState & READ_DONE) !== 0
  }

  pipe(pipeTo, cb) {
    if (this.pipeTo !== null) throw StreamError.BAD_ARGUMENT('Can only pipe to one destination')
    if (typeof cb !== 'function') cb = null

    this.stream._duplexState |= READ_PIPE_DRAINED
    this.pipeTo = pipeTo
    this.pipeline = new Pipeline(this.stream, pipeTo, cb)

    if (cb) this.stream.on('error', noop) // We already error handle this so supress crashes

    if (isStreamx(pipeTo)) {
      pipeTo._writableState.pipeline = this.pipeline
      if (cb) pipeTo.on('error', noop) // We already error handle this so supress crashes
      pipeTo.on('finish', this.pipeline.finished.bind(this.pipeline)) // TODO: just call finished from pipeTo itself
    } else {
      const onerror = this.pipeline.done.bind(this.pipeline, pipeTo)
      const onclose = this.pipeline.done.bind(this.pipeline, pipeTo, null) // onclose has a weird bool arg
      pipeTo.on('error', onerror)
      pipeTo.on('close', onclose)
      pipeTo.on('finish', this.pipeline.finished.bind(this.pipeline))
    }

    pipeTo.on('drain', afterDrain.bind(this))
    this.stream.emit('piping', pipeTo)
    pipeTo.emit('pipe', this.stream)
  }

  push(data) {
    const stream = this.stream

    if (data === null) {
      this.highWaterMark = 0
      stream._duplexState = (stream._duplexState | READ_ENDING) & READ_NON_PRIMARY_AND_PUSHED
      return false
    }

    if (this.map !== null) {
      data = this.map(data)
      if (data === null) {
        stream._duplexState &= READ_PUSHED
        return this.buffered < this.highWaterMark
      }
    }

    this.buffered += this.byteLength(data)
    this.queue.push(data)

    stream._duplexState = (stream._duplexState | READ_QUEUED) & READ_PUSHED

    return this.buffered < this.highWaterMark
  }

  shift() {
    const data = this.queue.shift()

    this.buffered -= this.byteLength(data)
    if (this.buffered === 0) {
      this.stream._duplexState &= READ_NOT_QUEUED
    }

    return data
  }

  unshift(data) {
    const pending = [this.map !== null ? this.map(data) : data]
    while (this.buffered > 0) pending.push(this.shift())

    for (let i = 0; i < pending.length - 1; i++) {
      const data = pending[i]
      this.buffered += this.byteLength(data)
      this.queue.push(data)
    }

    this.push(pending[pending.length - 1])
  }

  read() {
    const stream = this.stream

    if ((stream._duplexState & READ_STATUS) === READ_QUEUED) {
      const data = this.shift()

      if (this.pipeTo !== null && this.pipeTo.write(data) === false) {
        stream._duplexState &= READ_PIPE_NOT_DRAINED
      }

      if ((stream._duplexState & READ_EMIT_DATA) !== 0) {
        stream.emit('data', data)
      }

      return data
    }

    if (this.readAhead === false) {
      stream._duplexState |= READ_READ_AHEAD
      this.updateNextTick()
    }

    return null
  }

  drain() {
    const stream = this.stream

    while (
      (stream._duplexState & READ_STATUS) === READ_QUEUED &&
      (stream._duplexState & READ_FLOWING) !== 0
    ) {
      const data = this.shift()

      if (this.pipeTo !== null && this.pipeTo.write(data) === false) {
        stream._duplexState &= READ_PIPE_NOT_DRAINED
      }

      if ((stream._duplexState & READ_EMIT_DATA) !== 0) {
        stream.emit('data', data)
      }
    }
  }

  update() {
    const stream = this.stream

    stream._duplexState |= READ_UPDATING

    do {
      this.drain()

      while (
        this.buffered < this.highWaterMark &&
        (stream._duplexState & SHOULD_NOT_READ) === READ_READ_AHEAD
      ) {
        stream._duplexState |= READ_ACTIVE_AND_NEEDS_PUSH
        stream._read(this.afterRead)
        this.drain()
      }

      if ((stream._duplexState & READ_READABLE_STATUS) === READ_EMIT_READABLE_AND_QUEUED) {
        stream._duplexState |= READ_EMITTED_READABLE
        stream.emit('readable')
      }

      if ((stream._duplexState & READ_PRIMARY_AND_ACTIVE) === 0) {
        this.updateNonPrimary()
      }
    } while (this.continueUpdate() === true)

    stream._duplexState &= READ_NOT_UPDATING
  }

  updateNonPrimary() {
    const stream = this.stream

    if ((stream._duplexState & READ_ENDING_STATUS) === READ_ENDING) {
      stream._duplexState = (stream._duplexState | READ_DONE) & READ_NOT_ENDING
      stream.emit('end')

      if ((stream._duplexState & AUTO_DESTROY) === DONE) {
        stream._duplexState |= DESTROYING
      }

      if (this.pipeTo !== null) {
        this.pipeTo.end()
      }
    }

    if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
      if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
        stream._duplexState |= ACTIVE
        stream._destroy(afterDestroy.bind(this))
      }
      return
    }

    if ((stream._duplexState & IS_OPENING) === OPENING) {
      stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING
      stream._open(afterOpen.bind(this))
    }
  }

  continueUpdate() {
    if ((this.stream._duplexState & READ_NEXT_TICK) === 0) return false
    this.stream._duplexState &= READ_NOT_NEXT_TICK
    return true
  }

  updateCallback() {
    if ((this.stream._duplexState & READ_UPDATE_SYNC_STATUS) === READ_PRIMARY) {
      this.update()
    } else {
      this.updateNextTick()
    }
  }

  updateNextTickIfOpen() {
    if ((this.stream._duplexState & READ_NEXT_TICK_OR_OPENING) !== 0) return
    this.stream._duplexState |= READ_NEXT_TICK
    if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick)
  }

  updateNextTick() {
    if ((this.stream._duplexState & READ_NEXT_TICK) !== 0) return
    this.stream._duplexState |= READ_NEXT_TICK
    if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick)
  }
}

class TransformState {
  constructor(stream) {
    this.data = null
    this.afterTransform = afterTransform.bind(stream)
    this.afterFinal = null
  }
}

class Pipeline {
  constructor(src, dst, cb) {
    this.from = src
    this.to = dst
    this.afterPipe = cb
    this.error = null
    this.pipeToFinished = false
  }

  finished() {
    this.pipeToFinished = true
  }

  done(stream, err) {
    if (err) this.error = err

    if (stream === this.to) {
      this.to = null

      if (this.from !== null) {
        if ((this.from._duplexState & READ_DONE) === 0 || !this.pipeToFinished) {
          this.from.destroy(this.error || StreamError.PREMATURE_CLOSE('Writable stream closed'))
        }
        return
      }
    }

    if (stream === this.from) {
      this.from = null

      if (this.to !== null) {
        if ((stream._duplexState & READ_DONE) === 0) {
          this.to.destroy(this.error || StreamError.PREMATURE_CLOSE('Readable stream closed'))
        }
        return
      }
    }

    if (this.afterPipe !== null) this.afterPipe(this.error)
    this.to = this.from = this.afterPipe = null
  }
}

function afterDrain() {
  this.stream._duplexState |= READ_PIPE_DRAINED
  this.updateCallback()
}

function afterFinal(err) {
  const stream = this.stream
  if (err) stream.destroy(err)

  if ((stream._duplexState & DESTROY_STATUS) === 0) {
    stream._duplexState |= WRITE_DONE
    stream.emit('finish')
  }

  if ((stream._duplexState & AUTO_DESTROY) === DONE) {
    stream._duplexState |= DESTROYING
  }

  stream._duplexState &= WRITE_NOT_FINISHING

  // no need to wait the extra tick here, so we short circuit that
  if ((stream._duplexState & WRITE_UPDATING) === 0) {
    this.update()
  } else {
    this.updateNextTick()
  }
}

function afterDestroy(err) {
  const stream = this.stream

  if (!err && !StreamError.isStreamDestroyed(this.error)) err = this.error
  if (err) stream.emit('error', err)

  stream._duplexState |= DESTROYED
  stream.emit('close')

  const rs = stream._readableState
  const ws = stream._writableState

  if (rs !== null && rs.pipeline !== null) {
    rs.pipeline.done(stream, err)
  }

  if (ws !== null) {
    while (ws.drains !== null && ws.drains.length > 0) {
      ws.drains.shift().resolve(false)
    }

    if (ws.pipeline !== null) {
      ws.pipeline.done(stream, err)
    }
  }
}

function afterWrite(err) {
  const stream = this.stream

  if (err) stream.destroy(err)
  stream._duplexState &= WRITE_NOT_ACTIVE

  if (this.drains !== null) tickDrains(this.drains)

  if ((stream._duplexState & WRITE_DRAIN_STATUS) === WRITE_UNDRAINED) {
    stream._duplexState &= WRITE_DRAINED

    if ((stream._duplexState & WRITE_EMIT_DRAIN) === WRITE_EMIT_DRAIN) {
      stream.emit('drain')
    }
  }

  this.updateCallback()
}

function afterRead(err) {
  if (err) this.stream.destroy(err)
  this.stream._duplexState &= READ_NOT_ACTIVE

  if (this.readAhead === false && (this.stream._duplexState & READ_RESUMED) === 0) {
    this.stream._duplexState &= READ_NO_READ_AHEAD
  }

  this.updateCallback()
}

function updateReadNT() {
  if ((this.stream._duplexState & READ_UPDATING) === 0) {
    this.stream._duplexState &= READ_NOT_NEXT_TICK
    this.update()
  }
}

function updateWriteNT() {
  if ((this.stream._duplexState & WRITE_UPDATING) === 0) {
    this.stream._duplexState &= WRITE_NOT_NEXT_TICK
    this.update()
  }
}

function tickDrains(drains) {
  for (let i = 0; i < drains.length; i++) {
    // drains.writes are monotonic, so if one is 0 its always the first one
    if (--drains[i].writes === 0) {
      drains.shift().resolve(true)
      i--
    }
  }
}

function afterOpen(err) {
  const stream = this.stream

  if (err) stream.destroy(err)

  if ((stream._duplexState & DESTROYING) === 0) {
    if ((stream._duplexState & READ_PRIMARY_STATUS) === 0) {
      stream._duplexState |= READ_PRIMARY
    }

    if ((stream._duplexState & WRITE_PRIMARY_STATUS) === 0) {
      stream._duplexState |= WRITE_PRIMARY
    }

    stream.emit('open')
  }

  stream._duplexState &= NOT_ACTIVE

  if (stream._writableState !== null) {
    stream._writableState.updateCallback()
  }

  if (stream._readableState !== null) {
    stream._readableState.updateCallback()
  }
}

function afterTransform(err, data) {
  if (data !== undefined && data !== null) this.push(data)
  this._writableState.afterWrite(err)
}

function newListener(name) {
  if (this._readableState !== null) {
    if (name === 'data') {
      this._duplexState |= READ_EMIT_DATA | READ_RESUMED_READ_AHEAD
      this._readableState.updateNextTick()
    }
    if (name === 'readable') {
      this._duplexState |= READ_EMIT_READABLE
      this._readableState.updateNextTick()
    }
  }

  if (this._writableState !== null) {
    if (name === 'drain') {
      this._duplexState |= WRITE_EMIT_DRAIN
      this._writableState.updateNextTick()
    }
  }
}

class Stream extends EventEmitter {
  constructor(opts) {
    super()

    this._duplexState = 0
    this._readableState = null
    this._writableState = null

    if (opts) {
      if (opts.open) this._open = opts.open
      if (opts.destroy) this._destroy = opts.destroy
      if (opts.predestroy) this._predestroy = opts.predestroy
      if (opts.signal) opts.signal.addEventListener('abort', abort.bind(this))
    }

    this.on('newListener', newListener)
  }

  _open(cb) {
    cb(null)
  }

  _destroy(cb) {
    cb(null)
  }

  _predestroy() {
    // does nothing
  }

  get readable() {
    return this._readableState !== null ? true : undefined
  }

  get writable() {
    return this._writableState !== null ? true : undefined
  }

  get destroyed() {
    return (this._duplexState & DESTROYED) !== 0
  }

  get destroying() {
    return (this._duplexState & DESTROY_STATUS) !== 0
  }

  destroy(err) {
    if ((this._duplexState & DESTROY_STATUS) === 0) {
      if (!err) err = StreamError.STREAM_DESTROYED()
      this._duplexState = (this._duplexState | DESTROYING) & NON_PRIMARY

      if (this._readableState !== null) {
        this._readableState.highWaterMark = 0
        this._readableState.error = err
      }

      if (this._writableState !== null) {
        this._writableState.highWaterMark = 0
        this._writableState.error = err
      }

      this._duplexState |= PREDESTROYING
      this._predestroy()
      this._duplexState &= NOT_PREDESTROYING

      if (this._readableState !== null) {
        this._readableState.updateNextTick()
      }

      if (this._writableState !== null) {
        this._writableState.updateNextTick()
      }
    }
  }
}

class Readable extends Stream {
  constructor(opts) {
    super(opts)

    this._duplexState |= OPENING | WRITE_DONE | READ_READ_AHEAD
    this._readableState = new ReadableState(this, opts)

    if (opts) {
      if (this._readableState.readAhead === false) this._duplexState &= READ_NO_READ_AHEAD
      if (opts.read) this._read = opts.read
      if (opts.eagerOpen) this._readableState.updateNextTick()
      if (opts.encoding) this.setEncoding(opts.encoding)
    }
  }

  static deferred(fn, opts) {
    const out = new PassThrough(opts)

    fn()
      .then((src) => {
        if (src === null) return out.end()
        if (out.destroying) return
        pipeline(src, out, noop)
      })
      .catch((err) => out.destroy(err))

    return out
  }

  setEncoding(encoding) {
    const dec = new TextDecoder(encoding)
    const map = this._readableState.map || echo
    this._readableState.map = mapOrSkip
    return this

    function mapOrSkip(data) {
      const next = dec.push(data)
      return next === '' && (data.byteLength !== 0 || dec.remaining > 0) ? null : map(next)
    }
  }

  _read(cb) {
    cb(null)
  }

  pipe(dest, cb) {
    this._readableState.updateNextTick()
    this._readableState.pipe(dest, cb)
    return dest
  }

  read() {
    this._readableState.updateNextTick()
    return this._readableState.read()
  }

  push(data) {
    this._readableState.updateNextTickIfOpen()
    return this._readableState.push(data)
  }

  unshift(data) {
    this._readableState.updateNextTickIfOpen()
    return this._readableState.unshift(data)
  }

  resume() {
    this._duplexState |= READ_RESUMED_READ_AHEAD
    this._readableState.updateNextTick()
    return this
  }

  pause() {
    this._duplexState &=
      this._readableState.readAhead === false ? READ_PAUSED_NO_READ_AHEAD : READ_PAUSED
    return this
  }

  static _fromAsyncIterator(ite, opts) {
    let destroy

    const rs = new Readable({
      ...opts,
      read(cb) {
        ite.next().then(push).then(cb.bind(null, null)).catch(cb)
      },
      predestroy() {
        destroy = ite.return()
      },
      destroy(cb) {
        if (!destroy) return cb(null)
        destroy.then(cb.bind(null, null)).catch(cb)
      }
    })

    return rs

    function push(data) {
      if (data.done) rs.push(null)
      else rs.push(data.value)
    }
  }

  static from(data, opts) {
    if (isReadStreamx(data)) return data
    if (data[asyncIterator]) return this._fromAsyncIterator(data[asyncIterator](), opts)
    if (!Array.isArray(data)) data = data === undefined ? [] : [data]

    let i = 0
    return new Readable({
      ...opts,
      read(cb) {
        this.push(i === data.length ? null : data[i++])
        cb(null)
      }
    })
  }

  static isBackpressured(rs) {
    return (
      (rs._duplexState & READ_BACKPRESSURE_STATUS) !== 0 ||
      rs._readableState.buffered >= rs._readableState.highWaterMark
    )
  }

  static isPaused(rs) {
    return (rs._duplexState & READ_RESUMED) === 0
  }

  [asyncIterator]() {
    const stream = this

    let error = null
    let promiseResolve = null
    let promiseReject = null

    this.on('error', (err) => {
      error = err
    })
    this.on('readable', onreadable)
    this.on('close', onclose)

    return {
      [asyncIterator]() {
        return this
      },
      next() {
        return new Promise(function (resolve, reject) {
          promiseResolve = resolve
          promiseReject = reject
          const data = stream.read()
          if (data !== null) ondata(data)
          else if ((stream._duplexState & DESTROYED) !== 0) ondata(null)
        })
      },
      return() {
        return destroy(null)
      },
      throw(err) {
        return destroy(err)
      }
    }

    function onreadable() {
      if (promiseResolve !== null) ondata(stream.read())
    }

    function onclose() {
      if (promiseResolve !== null) ondata(null)
    }

    function ondata(data) {
      if (promiseReject === null) return
      if (error) {
        promiseReject(error)
      } else if (data === null && (stream._duplexState & READ_DONE) === 0) {
        promiseReject(StreamError.STREAM_DESTROYED())
      } else {
        promiseResolve({ value: data, done: data === null })
      }
      promiseReject = promiseResolve = null
    }

    function destroy(err) {
      stream.destroy(err)
      return new Promise((resolve, reject) => {
        if (stream._duplexState & DESTROYED) return resolve({ value: undefined, done: true })
        stream.once('close', function () {
          if (err) reject(err)
          else resolve({ value: undefined, done: true })
        })
      })
    }
  }
}

class Writable extends Stream {
  constructor(opts) {
    super(opts)

    this._duplexState |= OPENING | READ_DONE
    this._writableState = new WritableState(this, opts)

    if (opts) {
      if (opts.writev) this._writev = opts.writev
      if (opts.write) this._write = opts.write
      if (opts.final) this._final = opts.final
      if (opts.eagerOpen) this._writableState.updateNextTick()
    }
  }

  cork() {
    this._duplexState |= WRITE_CORKED
  }

  uncork() {
    this._duplexState &= WRITE_NOT_CORKED
    this._writableState.updateNextTick()
  }

  _writev(batch, cb) {
    cb(null)
  }

  _write(data, cb) {
    this._writableState.autoBatch(data, cb)
  }

  _final(cb) {
    cb(null)
  }

  static isBackpressured(ws) {
    return (ws._duplexState & WRITE_BACKPRESSURE_STATUS) !== 0
  }

  static drained(ws) {
    if (ws.destroyed) return Promise.resolve(false)

    const state = ws._writableState
    const pending = isWritev(ws) ? Math.min(1, state.queue.length) : state.queue.length
    const writes = pending + (ws._duplexState & WRITE_WRITING ? 1 : 0)
    if (writes === 0) return Promise.resolve(true)

    if (state.drains === null) state.drains = []
    return new Promise((resolve) => {
      state.drains.push({ writes, resolve })
    })
  }

  write(data) {
    this._writableState.updateNextTick()
    return this._writableState.push(data)
  }

  end(data) {
    this._writableState.updateNextTick()
    this._writableState.end(data)
    return this
  }
}

class Duplex extends Readable {
  // and Writable
  constructor(opts) {
    super(opts)

    this._duplexState = OPENING | (this._duplexState & READ_READ_AHEAD)
    this._writableState = new WritableState(this, opts)

    if (opts) {
      if (opts.writev) this._writev = opts.writev
      if (opts.write) this._write = opts.write
      if (opts.final) this._final = opts.final
    }
  }

  cork() {
    this._duplexState |= WRITE_CORKED
  }

  uncork() {
    this._duplexState &= WRITE_NOT_CORKED
    this._writableState.updateNextTick()
  }

  _writev(batch, cb) {
    cb(null)
  }

  _write(data, cb) {
    this._writableState.autoBatch(data, cb)
  }

  _final(cb) {
    cb(null)
  }

  write(data) {
    this._writableState.updateNextTick()
    return this._writableState.push(data)
  }

  end(data) {
    this._writableState.updateNextTick()
    this._writableState.end(data)
    return this
  }
}

class Transform extends Duplex {
  constructor(opts) {
    super(opts)
    this._transformState = new TransformState(this)

    if (opts) {
      if (opts.transform) this._transform = opts.transform
      if (opts.flush) this._flush = opts.flush
    }
  }

  _write(data, cb) {
    if (this._readableState.buffered >= this._readableState.highWaterMark) {
      this._transformState.data = data
    } else {
      this._transform(data, this._transformState.afterTransform)
    }
  }

  _read(cb) {
    if (this._transformState.data !== null) {
      const data = this._transformState.data
      this._transformState.data = null
      cb(null)
      this._transform(data, this._transformState.afterTransform)
    } else {
      cb(null)
    }
  }

  destroy(err) {
    super.destroy(err)
    if (this._transformState.data !== null) {
      this._transformState.data = null
      this._transformState.afterTransform()
    }
  }

  _transform(data, cb) {
    cb(null, data)
  }

  _flush(cb) {
    cb(null)
  }

  _final(cb) {
    this._transformState.afterFinal = cb
    this._flush(transformAfterFlush.bind(this))
  }
}

class PassThrough extends Transform {}

function transformAfterFlush(err, data) {
  const cb = this._transformState.afterFinal
  if (err) return cb(err)

  if (data !== null && data !== undefined) this.push(data)
  this.push(null)
  cb(null)
}

function pipelinePromise(...streams) {
  return new Promise((resolve, reject) => {
    return pipeline(...streams, (err) => {
      if (err) return reject(err)
      resolve()
    })
  })
}

function pipeline(stream, ...streams) {
  const all = Array.isArray(stream) ? [...stream, ...streams] : [stream, ...streams]
  const done = all.length && typeof all[all.length - 1] === 'function' ? all.pop() : null

  if (all.length < 2) throw StreamError.BAD_ARGUMENT('Pipeline requires at least 2 streams')

  let src = all[0]
  let dest = null
  let error = null

  for (let i = 1; i < all.length; i++) {
    dest = all[i]

    if (isStreamx(src)) {
      src.pipe(dest, onerror)
    } else {
      errorHandle(src, true, i > 1, onerror)
      src.pipe(dest)
    }

    src = dest
  }

  if (done) {
    let fin = false

    const autoDestroy =
      isStreamx(dest) || !!(dest._writableState && dest._writableState.autoDestroy)

    dest.on('error', (err) => {
      if (error === null) error = err
    })

    dest.on('finish', () => {
      fin = true
      if (!autoDestroy) done(error)
    })

    if (autoDestroy) {
      dest.on('close', () => done(error || (fin ? null : StreamError.PREMATURE_CLOSE())))
    }
  }

  return dest

  function errorHandle(s, rd, wr, onerror) {
    s.on('error', onerror)
    s.on('close', onclose)

    function onclose() {
      if (rd && s._readableState && !s._readableState.ended) {
        return onerror(StreamError.PREMATURE_CLOSE())
      }
      if (wr && s._writableState && !s._writableState.ended) {
        return onerror(StreamError.PREMATURE_CLOSE())
      }
    }
  }

  function onerror(err) {
    if (!err || error) return
    error = err

    for (const s of all) {
      s.destroy(err)
    }
  }
}

function echo(s) {
  return s
}

function isStream(stream) {
  return !!stream._readableState || !!stream._writableState
}

function isStreamx(stream) {
  return typeof stream._duplexState === 'number' && isStream(stream)
}

function isEnding(stream) {
  return !!stream._readableState && stream._readableState.ending
}

function isEnded(stream) {
  return !!stream._readableState && stream._readableState.ended
}

function isFinishing(stream) {
  return !!stream._writableState && stream._writableState.ending
}

function isFinished(stream) {
  return !!stream._writableState && stream._writableState.ended
}

function getStreamError(stream, opts = {}) {
  const err =
    (stream._readableState && stream._readableState.error) ||
    (stream._writableState && stream._writableState.error)

  // avoid implicit errors by default
  return !opts.all && StreamError.isStreamDestroyed(err) ? null : err
}

function isReadStreamx(stream) {
  return isStreamx(stream) && stream.readable
}

function isDisturbed(stream) {
  return (
    (stream._duplexState & OPENING) !== OPENING ||
    (stream._duplexState & DESTROYING) === DESTROYING ||
    (stream._duplexState & ACTIVE_OR_TICKING) !== 0
  )
}

function isTypedArray(data) {
  return typeof data === 'object' && data !== null && typeof data.byteLength === 'number'
}

function defaultByteLength(data) {
  return isTypedArray(data) ? data.byteLength : 1024
}

function noop() {}

function abort() {
  this.destroy(StreamError.ABORTED())
}

function isWritev(s) {
  return s._writev !== Writable.prototype._writev && s._writev !== Duplex.prototype._writev
}

module.exports = {
  pipeline,
  pipelinePromise,
  isStream,
  isStreamx,
  isEnding,
  isEnded,
  isFinishing,
  isFinished,
  isDisturbed,
  getStreamError,
  Stream,
  Writable,
  Readable,
  Duplex,
  Transform,
  // Export PassThrough for compatibility with Node.js core's stream module
  PassThrough
}
module.exports = class StreamError extends Error {
  constructor(msg, code, fn = StreamError) {
    super(msg)

    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  static isStreamDestroyed(err) {
    return err && err.code === 'STREAM_DESTROYED'
  }

  static isPrematureClose(err) {
    return err && err.code === 'PREMATURE_CLOSE'
  }

  static isAborted(err) {
    return err && err.code === 'ABORTED'
  }

  static isBadArgument(err) {
    return err && err.code === 'BAD_ARGUMENT'
  }

  get name() {
    return 'StreamError'
  }

  static STREAM_DESTROYED() {
    return new StreamError('Stream was destroyed', 'STREAM_DESTROYED', StreamError.STREAM_DESTROYED)
  }

  static PREMATURE_CLOSE(msg = 'Premature close') {
    return new StreamError(msg, 'PREMATURE_CLOSE', StreamError.PREMATURE_CLOSE)
  }

  static ABORTED() {
    return new StreamError('Stream aborted', 'ABORTED', StreamError.ABORTED)
  }

  static BAD_ARGUMENT(msg = 'Bad argument') {
    return new StreamError(msg, 'BAD_ARGUMENT', StreamError.BAD_ARGUMENT)
  }
}
{
  "name": "streamx",
  "version": "2.28.0",
  "description": "An iteration of the Node.js core streams with a series of improvements",
  "main": "index.js",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./errors": {
      "types": "./lib/errors.d.ts",
      "default": "./lib/errors"
    }
  },
  "dependencies": {
    "events-universal": "^1.0.0",
    "fast-fifo": "^1.3.2",
    "text-decoder": "^1.1.0"
  },
  "devDependencies": {
    "b4a": "^1.6.6",
    "brittle": "^3.1.1",
    "end-of-stream": "^1.4.4",
    "lunte": "^1.8.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "runtime.d.ts",
    "lib"
  ],
  "scripts": {
    "format": "prettier . --write",
    "test": "brittle test/all.js && brittle-bare test/all.js",
    "lint": "prettier . --check && lunte"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/streamx.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/streamx/issues"
  },
  "homepage": "https://github.com/mafintosh/streamx"
}
const { Readable } = require('streamx')

module.exports = function (s, forks = 2) {
  const streams = new Array(forks)
  const status = new Array(forks).fill(true)

  let ended = false

  for (let i = 0; i < forks; i++) {
    streams[i] = new Readable({
      read (cb) {
        const check = !status[i]
        status[i] = true
        if (check && allReadable()) s.resume()
        cb(null)
      }
    })
  }

  s.on('end', function () {
    ended = true
    for (const stream of streams) stream.push(null)
  })

  s.on('error', function (err) {
    for (const stream of streams) stream.destroy(err)
  })

  s.on('close', function () {
    if (ended) return
    for (const stream of streams) stream.destroy()
  })

  s.on('data', function (data) {
    let needsPause = false
    for (let i = 0; i < streams.length; i++) {
      if (!(status[i] = streams[i].push(data))) {
        needsPause = true
      }
    }
    if (needsPause) s.pause()
  })

  return streams

  function allReadable () {
    for (let j = 0; j < status.length; j++) {
      if (!status[j]) return false
    }
    return true
  }
}
{
  "name": "teex",
  "version": "1.0.1",
  "description": "Turn a readable stream into multiple readable streamx streams",
  "main": "index.js",
  "dependencies": {
    "streamx": "^2.12.5"
  },
  "devDependencies": {
    "standard": "^14.3.4",
    "tape": "^5.0.1"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/teex.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/teex/issues"
  },
  "homepage": "https://github.com/mafintosh/teex"
}
const PassThroughDecoder = require('./lib/pass-through-decoder')
const UTF8Decoder = require('./lib/utf8-decoder')

module.exports = class TextDecoder {
  constructor(encoding = 'utf8') {
    this.encoding = normalizeEncoding(encoding)

    switch (this.encoding) {
      case 'utf8':
        this.decoder = new UTF8Decoder()
        break
      case 'utf16le':
      case 'base64':
        throw new Error('Unsupported encoding: ' + this.encoding)
      default:
        this.decoder = new PassThroughDecoder(this.encoding)
    }
  }

  get remaining() {
    return this.decoder.remaining
  }

  push(data) {
    if (typeof data === 'string') return data
    return this.decoder.decode(data)
  }

  // For Node.js compatibility
  write(data) {
    return this.push(data)
  }

  end(data) {
    let result = ''
    if (data) result = this.push(data)
    result += this.decoder.flush()
    return result
  }
}

function normalizeEncoding(encoding) {
  encoding = encoding.toLowerCase()

  switch (encoding) {
    case 'utf8':
    case 'utf-8':
      return 'utf8'
    case 'ucs2':
    case 'ucs-2':
    case 'utf16le':
    case 'utf-16le':
      return 'utf16le'
    case 'latin1':
    case 'binary':
      return 'latin1'
    case 'base64':
    case 'ascii':
    case 'hex':
      return encoding
    default:
      throw new Error('Unknown encoding: ' + encoding)
  }
}
const b4a = require('b4a')

module.exports = class PassThroughDecoder {
  constructor(encoding) {
    this.encoding = encoding
  }

  get remaining() {
    return 0
  }

  decode(data) {
    return b4a.toString(data, this.encoding)
  }

  flush() {
    return ''
  }
}
const b4a = require('b4a')

/**
 * https://encoding.spec.whatwg.org/#utf-8-decoder
 */
module.exports = class UTF8Decoder {
  constructor() {
    this._reset()
  }

  get remaining() {
    return this.bytesSeen
  }

  decode(data) {
    if (data.byteLength === 0) return ''

    if (this.bytesNeeded === 0 && trailingIncomplete(data, 0) === 0) {
      this.bytesSeen = trailingBytesSeen(data)
      return b4a.toString(data, 'utf8')
    }

    let result = ''
    let start = 0

    if (this.bytesNeeded > 0) {
      while (start < data.byteLength) {
        const byte = data[start]

        if (byte < this.lowerBoundary || byte > this.upperBoundary) {
          result += '\ufffd'
          this._reset()
          break
        }

        this.lowerBoundary = 0x80
        this.upperBoundary = 0xbf
        this.codePoint = (this.codePoint << 6) | (byte & 0x3f)
        this.bytesSeen++
        start++

        if (this.bytesSeen === this.bytesNeeded) {
          result += String.fromCodePoint(this.codePoint)
          this._reset()
          break
        }
      }

      if (this.bytesNeeded > 0) return result
    }

    const trailing = trailingIncomplete(data, start)
    const end = data.byteLength - trailing

    if (end > start) result += b4a.toString(data, 'utf8', start, end)

    for (let i = end; i < data.byteLength; i++) {
      const byte = data[i]

      if (this.bytesNeeded === 0) {
        if (byte <= 0x7f) {
          this.bytesSeen = 0
          result += String.fromCharCode(byte)
        } else if (byte >= 0xc2 && byte <= 0xdf) {
          this.bytesNeeded = 2
          this.bytesSeen = 1
          this.codePoint = byte & 0x1f
        } else if (byte >= 0xe0 && byte <= 0xef) {
          if (byte === 0xe0) this.lowerBoundary = 0xa0
          else if (byte === 0xed) this.upperBoundary = 0x9f
          this.bytesNeeded = 3
          this.bytesSeen = 1
          this.codePoint = byte & 0xf
        } else if (byte >= 0xf0 && byte <= 0xf4) {
          if (byte === 0xf0) this.lowerBoundary = 0x90
          else if (byte === 0xf4) this.upperBoundary = 0x8f
          this.bytesNeeded = 4
          this.bytesSeen = 1
          this.codePoint = byte & 0x7
        } else {
          this.bytesSeen = 1
          result += '\ufffd'
        }

        continue
      }

      if (byte < this.lowerBoundary || byte > this.upperBoundary) {
        result += '\ufffd'
        i--
        this._reset()

        continue
      }

      this.lowerBoundary = 0x80
      this.upperBoundary = 0xbf

      this.codePoint = (this.codePoint << 6) | (byte & 0x3f)
      this.bytesSeen++

      if (this.bytesSeen === this.bytesNeeded) {
        result += String.fromCodePoint(this.codePoint)
        this._reset()
      }
    }

    return result
  }

  flush() {
    const result = this.bytesNeeded > 0 ? '\ufffd' : ''
    this._reset()
    return result
  }

  _reset() {
    this.codePoint = 0
    this.bytesNeeded = 0
    this.bytesSeen = 0
    this.lowerBoundary = 0x80
    this.upperBoundary = 0xbf
  }
}

function trailingIncomplete(data, start) {
  const len = data.byteLength
  if (len <= start) return 0

  const limit = Math.max(start, len - 4)

  let i = len - 1
  while (i > limit && (data[i] & 0xc0) === 0x80) i--

  if (i < start) return 0

  const byte = data[i]

  let needed
  if (byte <= 0x7f) return 0
  if (byte >= 0xc2 && byte <= 0xdf) needed = 2
  else if (byte >= 0xe0 && byte <= 0xef) needed = 3
  else if (byte >= 0xf0 && byte <= 0xf4) needed = 4
  else return 0

  const available = len - i
  return available < needed ? available : 0
}

function trailingBytesSeen(data) {
  const len = data.byteLength
  if (len === 0) return 0

  const last = data[len - 1]

  if (last <= 0x7f) return 0
  if ((last & 0xc0) !== 0x80) return 1

  const limit = Math.max(0, len - 4)

  let i = len - 2
  while (i >= limit && (data[i] & 0xc0) === 0x80) i--

  if (i < 0) return 1

  const first = data[i]

  let needed
  if (first >= 0xc2 && first <= 0xdf) needed = 2
  else if (first >= 0xe0 && first <= 0xef) needed = 3
  else if (first >= 0xf0 && first <= 0xf4) needed = 4
  else return 1

  if (len - i !== needed) return 1

  if (needed >= 3) {
    const second = data[i + 1]
    if (first === 0xe0 && second < 0xa0) return 1
    if (first === 0xed && second > 0x9f) return 1
    if (first === 0xf0 && second < 0x90) return 1
    if (first === 0xf4 && second > 0x8f) return 1
  }

  return 0
}
{
  "name": "text-decoder",
  "version": "1.2.7",
  "description": "Streaming text decoder that preserves multibyte Unicode characters",
  "exports": {
    "./package": "./package.json",
    ".": "./index.js"
  },
  "files": [
    "index.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/text-decoder.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/text-decoder/issues"
  },
  "homepage": "https://github.com/holepunchto/text-decoder#readme",
  "dependencies": {
    "b4a": "^1.6.4"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  }
}
module.exports = class TimerBrowser {
  constructor (ms, fn, ctx = null, interval = false) {
    this.ms = ms
    this.ontimeout = fn
    this.context = ctx || null
    this.interval = interval
    this.done = false

    this._timer = interval
      ? setInterval(callInterval, ms, this)
      : setTimeout(callTimeout, ms, this)
  }

  unref () {}

  ref () {}

  refresh () {
    if (this.done) return

    if (this.interval) {
      clearInterval(this._timer)
      this._timer = setInterval(callInterval, this.ms, this)
    } else {
      clearTimeout(this._timer)
      this._timer = setTimeout(callTimeout, this.ms, this)
    }
  }

  destroy () {
    this.done = true
    this.ontimeout = null

    if (this.interval) clearInterval(this._timer)
    else clearTimeout(this._timer)
  }

  static once (ms, fn, ctx) {
    return new this(ms, fn, ctx, false)
  }

  static on (ms, fn, ctx) {
    return new this(ms, fn, ctx, true)
  }
}

function callTimeout (self) {
  self.done = true
  self.ontimeout.call(self.context)
}

function callInterval (self) {
  self.ontimeout.call(self.context)
}
module.exports = isNode()
  ? require('./node')
  : require('./browser')

function isNode () {
  const to = setTimeout(function () {}, 1000)
  clearTimeout(to)
  return !!to.refresh
}
module.exports = class Timer {
  constructor (ms, fn, ctx = null, interval = false) {
    this.ms = ms
    this.ontimeout = fn
    this.context = ctx
    this.interval = interval
    this.done = false

    this._timer = interval
      ? setInterval(callInterval, ms, this)
      : setTimeout(callTimeout, ms, this)
  }

  unref () {
    this._timer.unref()
  }

  ref () {
    this._timer.ref()
  }

  refresh () {
    if (this.done !== true) this._timer.refresh()
  }

  destroy () {
    this.done = true
    this.ontimeout = null
    if (this.interval) clearInterval(this._timer)
    else clearTimeout(this._timer)
  }

  static once (ms, fn, ctx) {
    return new this(ms, fn, ctx, false)
  }

  static on (ms, fn, ctx) {
    return new this(ms, fn, ctx, true)
  }
}

function callTimeout (self) {
  self.done = true
  self.ontimeout.call(self.context)
}

function callInterval (self) {
  self.ontimeout.call(self.context)
}
{
  "name": "timeout-refresh",
  "version": "2.0.1",
  "description": "Efficiently refresh a timer",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^16.0.4",
    "tape": "^5.5.2"
  },
  "browser": "./browser.js",
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/timeout-refresh.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/timeout-refresh/issues"
  },
  "homepage": "https://github.com/mafintosh/timeout-refresh"
}
const b4a = require('b4a')

unslab.all = all
unslab.is = is

module.exports = unslab

function unslab (buf) {
  if (buf === null || buf.buffer.byteLength === buf.byteLength) return buf
  const copy = b4a.allocUnsafeSlow(buf.byteLength)
  copy.set(buf, 0)
  return copy
}

function is (buf) {
  return buf.buffer.byteLength !== buf.byteLength
}

function all (list) {
  let size = 0
  for (let i = 0; i < list.length; i++) {
    const buf = list[i]
    size += buf === null || buf.buffer.byteLength === buf.byteLength ? 0 : buf.byteLength
  }

  const copy = b4a.allocUnsafeSlow(size)
  const result = new Array(list.length)

  let offset = 0
  for (let i = 0; i < list.length; i++) {
    let buf = list[i]

    if (buf !== null && buf.buffer.byteLength !== buf.byteLength) {
      copy.set(buf, offset)
      buf = copy.subarray(offset, offset += buf.byteLength)
    }

    result[i] = buf
  }

  return result
}
{
  "name": "unslab",
  "version": "1.3.0",
  "description": "Unslab some slab'ed buffers",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.6.6"
  },
  "devDependencies": {
    "brittle": "^3.5.2",
    "standard": "^17.1.0"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/unslab.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/unslab/issues"
  },
  "homepage": "https://github.com/holepunchto/unslab"
}
const { runtime, platform, arch, version } =
  typeof Bare !== 'undefined'
    ? {
        runtime: 'bare',
        platform: global.Bare.platform,
        arch: global.Bare.arch,
        version: global.Bare.version
      }
    : typeof process !== 'undefined'
      ? {
          runtime: 'node',
          platform: global.process.platform,
          arch: global.process.arch,
          version: global.process.version
        }
      : typeof Window !== 'undefined'
        ? { runtime: 'browser', platform: 'unknown', arch: 'unknown', version: 'unknown' }
        : { runtime: 'unknown', platform: 'unknown', arch: 'unknown', version: 'unknown' }

exports.runtime = runtime
exports.version = version
exports.platform = platform
exports.arch = arch
exports.isBare = runtime === 'bare'
exports.isBareKit = exports.isBare && typeof BareKit !== 'undefined'
exports.isPear = typeof Pear !== 'undefined'
exports.isNode = runtime === 'node'
exports.isBrowser = runtime === 'browser'
exports.isWindows = platform === 'win32'
exports.isLinux = platform === 'linux'
exports.isMac = platform === 'darwin'
exports.isIOS = platform === 'ios' || platform === 'ios-simulator'
exports.isAndroid = platform === 'android'
exports.isElectron = typeof process !== 'undefined' && !!global.process.versions?.electron
exports.isElectronRenderer = exports.isElectron && global.process.type === 'renderer'
exports.isElectronWorker = exports.isElectron && global.process.type === 'worker'
{
  "name": "which-runtime",
  "version": "1.4.0",
  "description": "Detect if you are in Bare or Node and which os etc",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte .",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/which-runtime.git"
  },
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/which-runtime/issues"
  },
  "homepage": "https://github.com/holepunchto/which-runtime",
  "devDependencies": {
    "brittle": "^3.0.0",
    "lunte": "^1.4.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = class MaxCache {
  constructor({ maxSize, maxAge, createMap, ongc }) {
    this.maxSize = maxSize
    this.maxAge = maxAge
    this.ongc = ongc || null

    this._createMap = createMap || defaultCreateMap
    this._latest = this._createMap()
    this._oldest = this._createMap()
    this._retained = this._createMap()
    this._gced = false
    this._interval = null

    if (this.maxAge > 0 && this.maxAge < Infinity) {
      const tick = Math.ceil((2 / 3) * this.maxAge)
      this._interval = setInterval(this._gcAuto.bind(this), tick)
      if (this._interval.unref) this._interval.unref()
    }
  }

  get size() {
    return this._latest.size + this._oldest.size + this._retained.size
  }

  *[Symbol.iterator]() {
    for (const it of [this._latest, this._oldest, this._retained]) {
      yield* it
    }
  }

  *keys() {
    for (const it of [this._latest, this._oldest, this._retained]) {
      yield* it.keys()
    }
  }

  *values() {
    for (const it of [this._latest, this._oldest, this._retained]) {
      yield* it.values()
    }
  }

  destroy() {
    this.clear()
    clearInterval(this._interval)
    this._interval = null
  }

  clear() {
    this._gced = true
    this._latest.clear()
    this._oldest.clear()
    this._retained.clear()
  }

  set(k, v) {
    if (this._retained.has(k)) return this
    this._latest.set(k, v)
    this._oldest.delete(k) || this._retained.delete(k)
    if (this._latest.size >= this.maxSize) this._gc()
    return this
  }

  retain(k, v) {
    this._retained.set(k, v)
    this._latest.delete(k) || this._oldest.delete(k)
    return this
  }

  delete(k) {
    return (
      this._latest.delete(k) ||
      this._oldest.delete(k) ||
      this._retained.delete(k)
    )
  }

  has(k) {
    return this._latest.has(k) || this._oldest.has(k) || this._retained.has(k)
  }

  get(k) {
    if (this._latest.has(k)) {
      return this._latest.get(k)
    }

    if (this._oldest.has(k)) {
      const v = this._oldest.get(k)
      this._latest.set(k, v)
      this._oldest.delete(k)
      return v
    }

    if (this._retained.has(k)) {
      return this._retained.get(k)
    }

    return null
  }

  _gcAuto() {
    if (!this._gced) this._gc()
    this._gced = false
  }

  _gc() {
    this._gced = true
    if (this.ongc !== null && this._oldest.size > 0) this.ongc(this._oldest)
    this._oldest = this._latest
    this._latest = this._createMap()
  }
}

function defaultCreateMap() {
  return new Map()
}
{
  "name": "xache",
  "version": "1.3.0",
  "description": "Yet another auto expiring, max sizable cache",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "devDependencies": {
    "brittle": "^3.3.2",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "test": "prettier --check . && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/xache.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/xache/issues"
  },
  "homepage": "https://github.com/mafintosh/xache"
}
const b4a = require('b4a')

const ALPHABET = 'ybndrfg8ejkmcpqxot1uwisza345h769'
const MIN = 0x31 // 1
const MAX = 0x7a // z
const REVERSE = new Int8Array(1 + MAX - MIN)

REVERSE.fill(-1)

for (let i = 0; i < ALPHABET.length; i++) {
  const v = ALPHABET.charCodeAt(i) - MIN
  REVERSE[v] = i
}

exports.encode = encode
exports.decode = decode
exports.ALPHABET = ALPHABET

function decode (s, out) {
  let pb = 0
  let ps = 0

  const r = s.length & 7
  const q = (s.length - r) / 8

  if (!out) out = b4a.allocUnsafe(Math.ceil(s.length * 5 / 8))

  // 0 5 2 7 4 1 6 3 (+5 mod 8)
  for (let i = 0; i < q; i++) {
    const a = quintet(s, ps++)
    const b = quintet(s, ps++)
    const c = quintet(s, ps++)
    const d = quintet(s, ps++)
    const e = quintet(s, ps++)
    const f = quintet(s, ps++)
    const g = quintet(s, ps++)
    const h = quintet(s, ps++)

    out[pb++] = (a << 3) | (b >>> 2)
    out[pb++] = ((b & 0b11) << 6) | (c << 1) | (d >>> 4)
    out[pb++] = ((d & 0b1111) << 4) | (e >>> 1)
    out[pb++] = ((e & 0b1) << 7) | (f << 2) | (g >>> 3)
    out[pb++] = ((g & 0b111) << 5) | h
  }

  if (r === 0) return out.subarray(0, pb)

  const a = quintet(s, ps++)
  const b = quintet(s, ps++)

  out[pb++] = (a << 3) | (b >>> 2)

  if (r <= 2) return out.subarray(0, pb)

  const c = quintet(s, ps++)
  const d = quintet(s, ps++)

  out[pb++] = ((b & 0b11) << 6) | (c << 1) | (d >>> 4)

  if (r <= 4) return out.subarray(0, pb)

  const e = quintet(s, ps++)

  out[pb++] = ((d & 0b1111) << 4) | (e >>> 1)

  if (r <= 5) return out.subarray(0, pb)

  const f = quintet(s, ps++)
  const g = quintet(s, ps++)

  out[pb++] = ((e & 0b1) << 7) | (f << 2) | (g >>> 3)

  if (r <= 7) return out.subarray(0, pb)

  const h = quintet(s, ps++)

  out[pb++] = ((g & 0b111) << 5) | h

  return out.subarray(0, pb)
}

function encode (buf) {
  if (typeof buf === 'string') buf = b4a.from(buf)

  const max = buf.byteLength * 8

  let s = ''

  for (let p = 0; p < max; p += 5) {
    const i = p >>> 3
    const j = p & 7

    if (j <= 3) {
      s += ALPHABET[(buf[i] >>> (3 - j)) & 0b11111]
      continue
    }

    const of = j - 3
    const h = (buf[i] << of) & 0b11111
    const l = (i >= buf.byteLength ? 0 : buf[i + 1]) >>> (8 - of)

    s += ALPHABET[h | l]
  }

  return s
}

function quintet (s, i) {
  if (i > s.length) {
    return 0
  }

  const v = s.charCodeAt(i)

  if (v < MIN || v > MAX) {
    throw Error('Invalid character in base32 input: "' + s[i] + '" at position ' + i)
  }

  const bits = REVERSE[v - MIN]

  if (bits === -1) {
    throw Error('Invalid character in base32 input: "' + s[i] + '" at position ' + i)
  }

  return bits
}
{
  "name": "z32",
  "version": "1.1.0",
  "description": "Encode & decode z-base32",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.5.3"
  },
  "devDependencies": {
    "base-x": "^4.0.0",
    "base32": "0.0.7",
    "brittle": "^3.1.3",
    "nanobench": "^3.0.0",
    "rfc4648": "^1.5.2",
    "standard": "^17.0.0"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/z32.git"
  },
  "scripts": {
    "test": "standard && brittle test.js",
    "bench": "node benchmark.js"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/z32/issues"
  },
  "homepage": "https://github.com/mafintosh/z32"
}
{
  "name": "atproto-store",
  "version": "0.0.25",
  "description": "Holepunch-native atproto repo store — records in a classic Hyperbee (collection/rkey -> DAG-CBOR). The P2P home; the atproto-repo module is the bridge serializer over it.",
  "type": "module",
  "main": "lib/repo-store.js",
  "scripts": {
    "test": "brittle-node test/*.test.js"
  },
  "dependencies": {
    "atproto-repo": "file:../atproto-repo",
    "@ipld/dag-cbor": "^9.2.1",
    "b4a": "^1.6.0",
    "corestore": "^7.4.0",
    "hyperbee": "^2.20.0",
    "random-access-memory": "^6.2.0",
    "bare-fs": "^4.7.3",
    "bare-path": "^3.0.1"
  },
  "devDependencies": {
    "brittle": "^4.0.2"
  },
  "imports": {
    "#node:fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "#node:path": {
      "bare": "bare-path",
      "default": "path"
    }
  },
  "overrides": {
    "rocksdb-native": "3.17.2",
    "hypercore-storage": "3.2.0"
  }
}
function isBuffer(value) {
  return Buffer.isBuffer(value) || value instanceof Uint8Array
}

function isEncoding(encoding) {
  return Buffer.isEncoding(encoding)
}

function alloc(size, fill, encoding) {
  return Buffer.alloc(size, fill, encoding)
}

function allocUnsafe(size) {
  return Buffer.allocUnsafe(size)
}

function allocUnsafeSlow(size) {
  return Buffer.allocUnsafeSlow(size)
}

function byteLength(string, encoding) {
  return Buffer.byteLength(string, encoding)
}

function compare(a, b) {
  return Buffer.compare(a, b)
}

function concat(buffers, totalLength) {
  return Buffer.concat(buffers, totalLength)
}

function copy(source, target, targetStart, start, end) {
  return toBuffer(source).copy(target, targetStart, start, end)
}

function equals(a, b) {
  return toBuffer(a).equals(b)
}

function fill(buffer, value, offset, end, encoding) {
  return toBuffer(buffer).fill(value, offset, end, encoding)
}

function from(value, encodingOrOffset, length) {
  return Buffer.from(value, encodingOrOffset, length)
}

function includes(buffer, value, byteOffset, encoding) {
  return toBuffer(buffer).includes(value, byteOffset, encoding)
}

function indexOf(buffer, value, byfeOffset, encoding) {
  return toBuffer(buffer).indexOf(value, byfeOffset, encoding)
}

function lastIndexOf(buffer, value, byteOffset, encoding) {
  return toBuffer(buffer).lastIndexOf(value, byteOffset, encoding)
}

function swap16(buffer) {
  return toBuffer(buffer).swap16()
}

function swap32(buffer) {
  return toBuffer(buffer).swap32()
}

function swap64(buffer) {
  return toBuffer(buffer).swap64()
}

function toBuffer(buffer) {
  if (Buffer.isBuffer(buffer)) return buffer
  return Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

function toString(buffer, encoding, start, end) {
  return toBuffer(buffer).toString(encoding, start, end)
}

function write(buffer, string, offset, length, encoding) {
  return toBuffer(buffer).write(string, offset, length, encoding)
}

function readDoubleBE(buffer, offset) {
  return toBuffer(buffer).readDoubleBE(offset)
}

function readDoubleLE(buffer, offset) {
  return toBuffer(buffer).readDoubleLE(offset)
}

function readFloatBE(buffer, offset) {
  return toBuffer(buffer).readFloatBE(offset)
}

function readFloatLE(buffer, offset) {
  return toBuffer(buffer).readFloatLE(offset)
}

function readInt32BE(buffer, offset) {
  return toBuffer(buffer).readInt32BE(offset)
}

function readInt32LE(buffer, offset) {
  return toBuffer(buffer).readInt32LE(offset)
}

function readUInt32BE(buffer, offset) {
  return toBuffer(buffer).readUInt32BE(offset)
}

function readUInt32LE(buffer, offset) {
  return toBuffer(buffer).readUInt32LE(offset)
}

function writeDoubleBE(buffer, value, offset) {
  return toBuffer(buffer).writeDoubleBE(value, offset)
}

function writeDoubleLE(buffer, value, offset) {
  return toBuffer(buffer).writeDoubleLE(value, offset)
}

function writeFloatBE(buffer, value, offset) {
  return toBuffer(buffer).writeFloatBE(value, offset)
}

function writeFloatLE(buffer, value, offset) {
  return toBuffer(buffer).writeFloatLE(value, offset)
}

function writeInt32BE(buffer, value, offset) {
  return toBuffer(buffer).writeInt32BE(value, offset)
}

function writeInt32LE(buffer, value, offset) {
  return toBuffer(buffer).writeInt32LE(value, offset)
}

function writeUInt32BE(buffer, value, offset) {
  return toBuffer(buffer).writeUInt32BE(value, offset)
}

function writeUInt32LE(buffer, value, offset) {
  return toBuffer(buffer).writeUInt32LE(value, offset)
}

module.exports = {
  isBuffer,
  isEncoding,
  alloc,
  allocUnsafe,
  allocUnsafeSlow,
  byteLength,
  compare,
  concat,
  copy,
  equals,
  fill,
  from,
  includes,
  indexOf,
  lastIndexOf,
  swap16,
  swap32,
  swap64,
  toBuffer,
  toString,
  write,
  readDoubleBE,
  readDoubleLE,
  readFloatBE,
  readFloatLE,
  readInt32BE,
  readInt32LE,
  readUInt32BE,
  readUInt32LE,
  writeDoubleBE,
  writeDoubleLE,
  writeFloatBE,
  writeFloatLE,
  writeInt32BE,
  writeInt32LE,
  writeUInt32BE,
  writeUInt32LE
}
{
  "name": "b4a",
  "version": "1.8.1",
  "description": "Bridging the gap between buffers and typed arrays",
  "exports": {
    "./package": "./package.json",
    ".": {
      "react-native": "./react-native.js",
      "browser": "./browser.js",
      "default": "./index.js"
    }
  },
  "files": [
    "browser.js",
    "index.js",
    "react-native.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:bare && npm run test:node",
    "test:bare": "brittle-bare --coverage test.mjs",
    "test:node": "brittle-node --coverage test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/b4a.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/b4a/issues"
  },
  "homepage": "https://github.com/holepunchto/b4a#readme",
  "devDependencies": {
    "brittle": "^3.5.2",
    "lunte": "^1.7.0",
    "nanobench": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "react-native-b4a": "*"
  },
  "peerDependenciesMeta": {
    "react-native-b4a": {
      "optional": true
    }
  }
}
module.exports = require.addon()
const binding = require('./binding')

module.exports = binding.abort
{
  "name": "bare-abort",
  "version": "2.0.13",
  "description": "Cause abnormal program termination and generate a crash report",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-abort.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-abort/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-abort#readme",
  "devDependencies": {
    "cmake-bare": "^1.1.7",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  }
}
const ESC = '\x1b'
const CSI = ESC + '['
const SGR = (n) => CSI + n + 'm'

exports.constants = {
  ESC,
  CSI,
  SGR
}

// https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_(Control_Sequence_Introducer)_sequences

exports.cursorHide = CSI + '?25l'
exports.cursorShow = CSI + '?25h'

exports.cursorUp = function cursorUp(n = 1) {
  return CSI + n + 'A'
}

exports.cursorDown = function cursorDown(n = 1) {
  return CSI + n + 'B'
}

exports.cursorForward = function cursorForward(n = 1) {
  return CSI + n + 'C'
}

exports.cursorBack = function cursorBack(n = 1) {
  return CSI + n + 'D'
}

exports.cursorNextLine = function cursorNextLine(n = 1) {
  return CSI + n + 'E'
}

exports.cursorPreviousLine = function cursorPreviousLine(n = 1) {
  return CSI + n + 'F'
}

exports.cursorPosition = function cursorPosition(column, row = 0) {
  if (row === 0) return CSI + (column + 1) + 'G'

  return CSI + (row + 1) + ';' + (column + 1) + 'H'
}

exports.eraseDisplayEnd = CSI + 'J'
exports.eraseDisplayStart = CSI + '1J'
exports.eraseDisplay = CSI + '2J'
exports.eraseLineEnd = CSI + 'K'
exports.eraseLineStart = CSI + '1K'
exports.eraseLine = CSI + '2K'

exports.scrollUp = function scrollUp(n = 1) {
  return CSI + n + 'S'
}

exports.scrollDown = function scrollDown(n = 1) {
  return CSI + n + 'T'
}

// https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_(Select_Graphic_Rendition)_parameters

exports.modifierReset = SGR(0)
exports.modifierBold = SGR(1)
exports.modifierDim = SGR(2)
exports.modifierItalic = SGR(3)
exports.modifierUnderline = SGR(4)
exports.modifierNormal = SGR(22)
exports.modifierNotItalic = SGR(23)
exports.modifierNotUnderline = SGR(24)

// https://en.wikipedia.org/wiki/ANSI_escape_code#Colors

exports.colorBlack = SGR(30)
exports.colorRed = SGR(31)
exports.colorGreen = SGR(32)
exports.colorYellow = SGR(33)
exports.colorBlue = SGR(34)
exports.colorMagenta = SGR(35)
exports.colorCyan = SGR(36)
exports.colorWhite = SGR(37)
exports.colorDefault = SGR(39)
exports.colorBrightBlack = SGR(90)
exports.colorBrightRed = SGR(91)
exports.colorBrightGreen = SGR(92)
exports.colorBrightYellow = SGR(93)
exports.colorBrightBlue = SGR(94)
exports.colorBrightMagenta = SGR(95)
exports.colorBrightCyan = SGR(96)
exports.colorBrightWhite = SGR(97)
{
  "name": "bare-ansi-escapes",
  "version": "2.2.3",
  "description": "Parse and produce ANSI escape sequences",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./key-decoder": {
      "types": "./key-decoder.d.ts",
      "default": "./key-decoder.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "key-decoder.js",
    "key-decoder.d.ts"
  ],
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-ansi-escapes.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-ansi-escapes/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-ansi-escapes#readme",
  "dependencies": {
    "bare-stream": "^2.6.5"
  },
  "devDependencies": {
    "bare-buffer": "^3.0.2",
    "brittle": "^3.3.2",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  },
  "peerDependencies": {
    "bare-buffer": "*"
  },
  "peerDependenciesMeta": {
    "bare-buffer": {
      "optional": true
    }
  }
}
const inspect = require('bare-inspect')

class AssertionError extends Error {
  constructor(opts = {}) {
    let { message = null, actual, expected, operator } = opts

    if (message === null) {
      message = `${inspect(actual)} ${operator} ${inspect(expected)}`
    }

    super(message)

    this.actual = actual
    this.expected = expected
    this.operator = operator
  }

  get name() {
    return 'AssertionError'
  }

  get code() {
    'ASSERTION'
  }
}

function assertFail(opts, fn) {
  if (opts.message instanceof Error) throw opts.message

  const err = new AssertionError(opts)

  if (Error.captureStackTrace) Error.captureStackTrace(err, fn)

  throw err
}

module.exports = exports = function assert(actual, message) {
  if (actual) return

  assertFail({ message, actual, expected: true, operator: '==' }, assert)
}

exports.AssertionError = AssertionError

exports.fail = function fail(message) {
  if (message === undefined) message = 'Failed'

  assertFail({ message, operator: 'fail' }, fail)
}

exports.ok = function ok(actual, message) {
  if (actual) return

  assertFail({ message, actual, expected: true, operator: '==' }, ok)
}

exports.notOk = function ok(actual, message) {
  if (!actual) return

  assertFail({ message, actual, expected: false, operator: '==' }, ok)
}

exports.equal = function equal(actual, expected, message) {
  if (actual == expected || (actual !== actual && expected !== expected)) {
    return
  }

  assertFail({ message, actual, expected, operator: '==' }, equal)
}

exports.notEqual = function notEqual(actual, expected, message) {
  if (actual != expected && (actual === actual || expected === expected)) {
    return
  }

  assertFail({ message, actual, expected, operator: '!=' }, notEqual)
}

exports.strictEqual = function strictEqual(actual, expected, message) {
  if (Object.is(actual, expected)) return

  assertFail(
    { message, actual, expected, operator: 'strictEqual' },
    strictEqual
  )
}

exports.notStrictEqual = function notStrictEqual(actual, expected, message) {
  if (!Object.is(actual, expected)) return

  assertFail(
    { message, actual, expected, operator: 'notStrictEqual' },
    notStrictEqual
  )
}
{
  "name": "bare-assert",
  "version": "1.2.0",
  "description": "Assertion library for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts"
  ],
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-assert.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-assert/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-assert#readme",
  "dependencies": {
    "bare-inspect": "^3.1.2"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  }
}
module.exports = require.addon()
const constants = require('./lib/constants')
const ascii = require('./lib/ascii')
const base64 = require('./lib/base64')
const base64url = require('./lib/base64url')
const hex = require('./lib/hex')
const utf8 = require('./lib/utf8')
const utf16le = require('./lib/utf16le')
const latin1 = require('./lib/latin1')
const binding = require('./binding')

const kind = Symbol.for('bare.buffer.kind')

let poolSize = 0

module.exports = exports = class Buffer extends Uint8Array {
  static get [kind]() {
    return 0 // Compatibility version
  }

  static get poolSize() {
    return poolSize
  }

  static set poolSize(value) {
    poolSize = Math.max(0, value)
  }

  constructor(arrayBuffer, offset, length, opts = {}) {
    if (typeof arrayBuffer === 'number') {
      opts = offset || {}

      const { uninitialized = false } = opts

      offset = 0
      length = arrayBuffer

      if (length > constants.MAX_LENGTH) {
        throw new RangeError(`Buffer length must be at most ${constants.MAX_LENGTH}`)
      }

      arrayBuffer = uninitialized ? binding.allocUnsafe(length) : binding.alloc(length)
    } else {
      if (length > constants.MAX_LENGTH) {
        throw new RangeError(`Buffer length must be at most ${constants.MAX_LENGTH}`)
      }

      if (typeof offset === 'object' && offset !== null) {
        opts = offset
        offset = 0
        length = arrayBuffer.byteLength
      } else if (typeof length === 'length' && length !== null) {
        opts = length
        length = arrayBuffer.byteLength - offset
      }
    }

    super(arrayBuffer, offset, length)
  }

  get [kind]() {
    return Buffer[kind]
  }

  copy(target, targetStart = 0, sourceStart = 0, sourceEnd = this.byteLength) {
    let source = this

    if (targetStart < 0) targetStart = 0
    if (targetStart >= target.byteLength) return 0

    const targetLength = target.byteLength - targetStart

    if (sourceStart < 0) sourceStart = 0
    if (sourceStart >= source.byteLength) return 0

    if (sourceEnd <= sourceStart) return 0
    if (sourceEnd > source.byteLength) sourceEnd = source.byteLength

    if (sourceEnd - sourceStart > targetLength) {
      sourceEnd = sourceStart + targetLength
    }

    const sourceLength = sourceEnd - sourceStart

    if (source === target) {
      target.copyWithin(targetStart, sourceStart, sourceEnd)
    } else {
      if (sourceStart !== 0 || sourceEnd !== source.byteLength) {
        source = source.subarray(sourceStart, sourceEnd)
      }

      target.set(source, targetStart)
    }

    return sourceLength
  }

  equals(target) {
    const source = this

    if (source === target) return true
    if (source.byteLength !== target.byteLength) return false

    return (
      binding.compare(
        source.buffer,
        source.byteOffset,
        source.byteLength,
        target.buffer,
        target.byteOffset,
        target.byteLength
      ) === 0
    )
  }

  compare(
    target,
    targetStart = 0,
    targetEnd = target.byteLength,
    sourceStart = 0,
    sourceEnd = this.byteLength
  ) {
    let source = this

    if (source === target) return 0

    if (arguments.length > 1) {
      if (targetStart < 0) targetStart = 0
      if (targetStart > target.byteLength) targetStart = target.byteLength

      if (targetEnd < targetStart) targetEnd = targetStart
      if (targetEnd > target.byteLength) targetEnd = target.byteLength

      if (sourceStart < 0) sourceStart = 0
      if (sourceStart > source.byteLength) sourceStart = source.byteLength

      if (sourceEnd < sourceStart) sourceEnd = sourceStart
      if (sourceEnd > source.byteLength) sourceEnd = source.byteLength

      if (sourceStart !== 0 || sourceEnd !== source.byteLength) {
        source = source.subarray(sourceStart, sourceEnd)
      }

      if (targetStart !== 0 || targetEnd !== target.byteLength) {
        target = target.subarray(targetStart, targetEnd)
      }
    }

    return binding.compare(
      source.buffer,
      source.byteOffset,
      source.byteLength,
      target.buffer,
      target.byteOffset,
      target.byteLength
    )
  }

  fill(value, offset = 0, end = this.byteLength, encoding = 'utf8') {
    if (typeof value === 'string') {
      if (typeof offset === 'string') {
        // fill(string, encoding)
        encoding = offset
        offset = 0
        end = this.byteLength
      } else if (typeof end === 'string') {
        // fill(string, offset, encoding)
        encoding = end
        end = this.byteLength
      }
    } else if (typeof value === 'number') {
      value = value & 0xff
    } else if (typeof value === 'boolean') {
      value = +value
    }

    if (offset < 0) offset = 0
    if (offset >= this.byteLength) return this

    if (end <= offset) return this
    if (end > this.byteLength) end = this.byteLength

    if (typeof value === 'number') return super.fill(value, offset, end)

    if (typeof value === 'string') value = exports.from(value, encoding)

    const length = value.byteLength

    for (let i = 0, n = end - offset; i < n; ++i) {
      this[i + offset] = value[i % length]
    }

    return this
  }

  includes(value, offset, encoding) {
    return this.indexOf(value, offset, encoding) !== -1
  }

  indexOf(value, offset = 0, encoding) {
    if (typeof value === 'boolean') value = +value

    if (typeof value === 'number') {
      return super.indexOf(value & 0xff, offset)
    }

    return bidirectionalIndexOf(this, value, offset, encoding, true /* first */)
  }

  lastIndexOf(value, offset = this.byteLength - 1, encoding) {
    if (typeof value === 'boolean') value = +value

    if (typeof value === 'number') {
      return super.lastIndexOf(value & 0xff, offset)
    }

    return bidirectionalIndexOf(this, value, offset, encoding, false /* last */)
  }

  swap16() {
    const length = this.byteLength

    if (length % 2 !== 0) {
      throw new RangeError('Buffer size must be a multiple of 16-bits')
    }

    for (let i = 0; i < length; i += 2) swap(this, i, i + 1)

    return this
  }

  swap32() {
    const length = this.byteLength

    if (length % 4 !== 0) {
      throw new RangeError('Buffer size must be a multiple of 32-bits')
    }

    for (let i = 0; i < length; i += 4) {
      swap(this, i, i + 3)
      swap(this, i + 1, i + 2)
    }

    return this
  }

  swap64() {
    const length = this.byteLength

    if (length % 8 !== 0) {
      throw new RangeError('Buffer size must be a multiple of 64-bits')
    }

    for (let i = 0; i < length; i += 8) {
      swap(this, i, i + 7)
      swap(this, i + 1, i + 6)
      swap(this, i + 2, i + 5)
      swap(this, i + 3, i + 4)
    }

    return this
  }

  toString(encoding = 'utf8', start = 0, end = this.byteLength) {
    // toString()
    if (arguments.length === 0) return utf8.toString(this)

    // toString(encoding)
    if (arguments.length === 1) return codecFor(encoding).toString(this)

    if (start < 0) start = 0
    if (start >= this.byteLength) return ''

    if (end <= start) return ''
    if (end > this.byteLength) end = this.byteLength

    let buffer = this

    if (start !== 0 || end !== this.byteLength) {
      buffer = buffer.subarray(start, end)
    }

    return codecFor(encoding).toString(buffer)
  }

  toJSON() {
    return Array.from(this)
  }

  write(string, offset = 0, length = this.byteLength - offset, encoding = 'utf8') {
    // write(string)
    if (arguments.length === 1) return utf8.write(this, string)

    if (typeof offset === 'string') {
      // write(string, encoding)
      encoding = offset
      offset = 0
      length = this.byteLength
    } else if (typeof length === 'string') {
      // write(string, offset, encoding)
      encoding = length
      length = this.byteLength - offset
    }

    length = Math.min(length, exports.byteLength(string, encoding))

    let start = offset
    if (start < 0) start = 0
    if (start >= this.byteLength) return 0

    let end = offset + length
    if (end <= start) return 0
    if (end > this.byteLength) end = this.byteLength

    let buffer = this

    if (start !== 0 || end !== this.byteLength) {
      buffer = buffer.subarray(start, end)
    }

    return codecFor(encoding).write(buffer, string)
  }

  readBigInt64BE(offset = 0) {
    return viewOf(this).getBigInt64(offset, false)
  }
  readBigInt64LE(offset = 0) {
    return viewOf(this).getBigInt64(offset, true)
  }

  readBigUint64BE(offset = 0) {
    return viewOf(this).getBigUint64(offset, false)
  }
  readBigUint64LE(offset = 0) {
    return viewOf(this).getBigUint64(offset, true)
  }

  readDoubleBE(offset = 0) {
    return viewOf(this).getFloat64(offset, false)
  }
  readDoubleLE(offset = 0) {
    return viewOf(this).getFloat64(offset, true)
  }

  readFloatBE(offset = 0) {
    return viewOf(this).getFloat32(offset, false)
  }
  readFloatLE(offset = 0) {
    return viewOf(this).getFloat32(offset, true)
  }

  readInt8(offset = 0) {
    return viewOf(this).getInt8(offset)
  }

  readInt16BE(offset = 0) {
    return viewOf(this).getInt16(offset, false)
  }
  readInt16LE(offset = 0) {
    return viewOf(this).getInt16(offset, true)
  }

  readInt32BE(offset = 0) {
    return viewOf(this).getInt32(offset, false)
  }
  readInt32LE(offset = 0) {
    return viewOf(this).getInt32(offset, true)
  }

  readIntBE(offset, byteLength) {
    if (byteLength === 6) return readInt48BE(viewOf(this), offset)
    if (byteLength === 5) return readInt40BE(viewOf(this), offset)
    if (byteLength === 3) return readInt24BE(viewOf(this), offset)
    if (byteLength === 4) return this.readInt32BE(offset)
    if (byteLength === 2) return this.readInt16BE(offset)
    if (byteLength === 1) return this.readInt8(offset)
    throw new RangeError(`Byte length must be between 1 and 6`)
  }

  readIntLE(offset, byteLength) {
    if (byteLength === 6) return readInt48LE(viewOf(this), offset)
    if (byteLength === 5) return readInt40LE(viewOf(this), offset)
    if (byteLength === 3) return readInt24LE(viewOf(this), offset)
    if (byteLength === 4) return this.readInt32LE(offset)
    if (byteLength === 2) return this.readInt16LE(offset)
    if (byteLength === 1) return this.readInt8(offset)
    throw new RangeError(`Byte length must be between 1 and 6`)
  }

  readUint8(offset = 0) {
    return viewOf(this).getUint8(offset)
  }

  readUint16BE(offset = 0) {
    return viewOf(this).getUint16(offset, false)
  }
  readUint16LE(offset = 0) {
    return viewOf(this).getUint16(offset, true)
  }

  readUint32BE(offset = 0) {
    return viewOf(this).getUint32(offset, false)
  }
  readUint32LE(offset = 0) {
    return viewOf(this).getUint32(offset, true)
  }

  readUintBE(offset, byteLength) {
    if (byteLength === 6) return readUint48BE(viewOf(this), offset)
    if (byteLength === 5) return readUint40BE(viewOf(this), offset)
    if (byteLength === 3) return readUint24BE(viewOf(this), offset)
    if (byteLength === 4) return this.readUint32BE(offset)
    if (byteLength === 2) return this.readUint16BE(offset)
    if (byteLength === 1) return this.readUint8(offset)
    throw new RangeError(`Byte length must be between 1 and 6`)
  }

  readUintLE(offset, byteLength) {
    if (byteLength === 6) return readUint48LE(viewOf(this), offset)
    if (byteLength === 5) return readUint40LE(viewOf(this), offset)
    if (byteLength === 3) return readUint24LE(viewOf(this), offset)
    if (byteLength === 4) return this.readUint32LE(offset)
    if (byteLength === 2) return this.readUint16LE(offset)
    if (byteLength === 1) return this.readUint8(offset)
    throw new RangeError(`Byte length must be between 1 and 6`)
  }

  readBigUInt64BE(...args) {
    return this.readBigUint64BE(...args)
  }
  readBigUInt64LE(...args) {
    return this.readBigUint64LE(...args)
  }

  readUInt8(...args) {
    return this.readUint8(...args)
  }

  readUInt16BE(...args) {
    return this.readUint16BE(...args)
  }
  readUInt16LE(...args) {
    return this.readUint16LE(...args)
  }

  readUInt32BE(...args) {
    return this.readUint32BE(...args)
  }
  readUInt32LE(...args) {
    return this.readUint32LE(...args)
  }

  readUIntBE(...args) {
    return this.readUintBE(...args)
  }
  readUIntLE(...args) {
    return this.readUintLE(...args)
  }

  writeBigInt64BE(value, offset = 0) {
    viewOf(this).setBigInt64(offset, value, false)
    return offset + 8
  }
  writeBigInt64LE(value, offset = 0) {
    viewOf(this).setBigInt64(offset, value, true)
    return offset + 8
  }

  writeBigUint64BE(value, offset = 0) {
    viewOf(this).setBigUint64(offset, value, false)
    return offset + 8
  }
  writeBigUint64LE(value, offset = 0) {
    viewOf(this).setBigUint64(offset, value, true)
    return offset + 8
  }

  writeDoubleBE(value, offset = 0) {
    viewOf(this).setFloat64(offset, value, false)
    return offset + 8
  }
  writeDoubleLE(value, offset = 0) {
    viewOf(this).setFloat64(offset, value, true)
    return offset + 8
  }

  writeFloatBE(value, offset = 0) {
    viewOf(this).setFloat32(offset, value, false)
    return offset + 4
  }
  writeFloatLE(value, offset = 0) {
    viewOf(this).setFloat32(offset, value, true)
    return offset + 4
  }

  writeInt8(value, offset = 0) {
    viewOf(this).setInt8(offset, value)
    return offset + 1
  }

  writeInt16BE(value, offset = 0) {
    viewOf(this).setInt16(offset, value, false)
    return offset + 2
  }
  writeInt16LE(value, offset = 0) {
    viewOf(this).setInt16(offset, value, true)
    return offset + 2
  }

  writeInt32BE(value, offset = 0) {
    viewOf(this).setInt32(offset, value, false)
    return offset + 4
  }
  writeInt32LE(value, offset = 0) {
    viewOf(this).setInt32(offset, value, true)
    return offset + 4
  }

  writeIntBE(value, offset, byteLength) {
    if (byteLength === 6) return writeInt48BE(value, viewOf(this), offset)
    if (byteLength === 5) return writeInt40BE(value, viewOf(this), offset)
    if (byteLength === 3) return writeInt24BE(value, viewOf(this), offset)
    if (byteLength === 4) return this.writeInt32BE(value, offset)
    if (byteLength === 2) return this.writeInt16BE(value, offset)
    if (byteLength === 1) return this.writeInt8(value, offset)
    throw new RangeError(`Byte length must be between 1 and 6`)
  }

  writeIntLE(value, offset, byteLength) {
    if (byteLength === 6) return writeInt48LE(value, viewOf(this), offset)
    if (byteLength === 5) return writeInt40LE(value, viewOf(this), offset)
    if (byteLength === 3) return writeInt24LE(value, viewOf(this), offset)
    if (byteLength === 4) return this.writeInt32LE(value, offset)
    if (byteLength === 2) return this.writeInt16LE(value, offset)
    if (byteLength === 1) return this.writeInt8(value, offset)
    throw new RangeError(`Byte length must be between 1 and 6`)
  }

  writeUint8(value, offset = 0) {
    viewOf(this).setUint8(offset, value, true)
    return offset + 1
  }

  writeUint16BE(value, offset = 0) {
    viewOf(this).setUint16(offset, value, false)
    return offset + 2
  }
  writeUint16LE(value, offset = 0) {
    viewOf(this).setUint16(offset, value, true)
    return offset + 2
  }

  writeUint32LE(value, offset = 0) {
    viewOf(this).setUint32(offset, value, true)
    return offset + 4
  }
  writeUint32BE(value, offset = 0) {
    viewOf(this).setUint32(offset, value, false)
    return offset + 4
  }

  writeUintBE(value, offset, byteLength) {
    if (byteLength === 6) return writeUint48BE(value, viewOf(this), offset)
    if (byteLength === 5) return writeUint40BE(value, viewOf(this), offset)
    if (byteLength === 3) return writeUint24BE(value, viewOf(this), offset)
    if (byteLength === 4) return this.writeUint32BE(value, offset)
    if (byteLength === 2) return this.writeUint16BE(value, offset)
    if (byteLength === 1) return this.writeUint8(value, offset)
    throw new RangeError(`Byte length must be between 1 and 6`)
  }

  writeUintLE(value, offset, byteLength) {
    if (byteLength === 6) return writeUint48LE(value, viewOf(this), offset)
    if (byteLength === 5) return writeUint40LE(value, viewOf(this), offset)
    if (byteLength === 3) return writeUint24LE(value, viewOf(this), offset)
    if (byteLength === 4) return this.writeUint32LE(value, offset)
    if (byteLength === 2) return this.writeUint16LE(value, offset)
    if (byteLength === 1) return this.writeUint8(value, offset)
    throw new RangeError(`Byte length must be between 1 and 6`)
  }

  writeBigUInt64BE(...args) {
    return this.writeBigUint64BE(...args)
  }
  writeBigUInt64LE(...args) {
    return this.writeBigUint64LE(...args)
  }

  writeUInt8(...args) {
    return this.writeUint8(...args)
  }

  writeUInt16BE(...args) {
    return this.writeUint16BE(...args)
  }
  writeUInt16LE(...args) {
    return this.writeUint16LE(...args)
  }

  writeUInt32BE(...args) {
    return this.writeUint32BE(...args)
  }
  writeUInt32LE(...args) {
    return this.writeUint32LE(...args)
  }

  writeUIntBE(...args) {
    return this.writeUintBE(...args)
  }
  writeUIntLE(...args) {
    return this.writeUintLE(...args)
  }
}

const Buffer = exports

exports.Buffer = Buffer // For Node.js compatibility

exports.constants = constants

const codecs = Object.create(null)

codecs.ascii = ascii
codecs.base64 = base64
codecs.base64url = base64url
codecs.hex = hex
codecs.utf8 = codecs['utf-8'] = utf8
codecs.utf16le = codecs.ucs2 = codecs['utf-16le'] = codecs['ucs-2'] = utf16le
codecs.latin1 = codecs.binary = latin1

function codecFor(encoding = 'utf8') {
  if (encoding in codecs) return codecs[encoding]

  encoding = encoding.toLowerCase()

  if (encoding in codecs) return codecs[encoding]

  throw new Error(`Unknown encoding '${encoding}'`)
}

const views = new WeakMap()

function viewOf(buffer) {
  let view = views.get(buffer)
  if (view === undefined) {
    view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength)
    views.set(buffer, view)
  }
  return view
}

exports.isBuffer = function isBuffer(value) {
  if (value instanceof Buffer) return true

  return typeof value === 'object' && value !== null && value[kind] === Buffer[kind]
}

exports.isEncoding = function isEncoding(encoding) {
  try {
    codecFor(encoding)
    return true
  } catch {
    return false
  }
}

exports.isASCII = function isASCII(buffer) {
  return ascii.validate(buffer)
}

// for Node.js compatibily
exports.isAscii = exports.isASCII

exports.isUTF8 = function isUTF8(buffer) {
  return utf8.validate(buffer)
}

// for Node.js compatibility
exports.isUtf8 = exports.isUTF8

exports.alloc = function alloc(size, fill, encoding) {
  const buffer = new Buffer(size)
  if (fill !== undefined) buffer.fill(fill, 0, buffer.byteLength, encoding)
  return buffer
}

exports.allocUnsafe = function allocUnsafe(size) {
  return new Buffer(size, { uninitialized: true })
}

exports.allocUnsafeSlow = function allocUnsafeSlow(size) {
  return exports.allocUnsafe(size)
}

exports.byteLength = function byteLength(string, encoding) {
  if (typeof string === 'string') {
    return codecFor(encoding).byteLength(string)
  }

  return string.byteLength
}

exports.compare = function compare(a, b) {
  return binding.compare(a.buffer, a.byteOffset, a.byteLength, b.buffer, b.byteOffset, b.byteLength)
}

exports.concat = function concat(buffers, length) {
  if (length === undefined) {
    length = buffers.reduce((length, buffer) => length + buffer.byteLength, 0)
  }

  const result = new Buffer(length)

  for (let i = 0, n = buffers.length, offset = 0; i < n; i++) {
    const buffer = buffers[i]

    if (offset + buffer.byteLength > result.byteLength) {
      result.set(buffer.subarray(0, result.byteLength - offset), offset)
      return result
    }

    result.set(buffer, offset)
    offset += buffer.byteLength
  }

  return result
}

exports.coerce = function coerce(buffer) {
  if (exports.isBuffer(buffer)) return buffer
  return new Buffer(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

exports.copyBytesFrom = function copyBytesFrom(view, offset = 0, length = view.length - offset) {
  if (offset + length > view.length) {
    throw new RangeError('View length is out of range')
  }

  if (offset !== 0 || length !== view.length) {
    view = view.subarray(offset, offset + length)
  }

  return new Buffer(view.buffer.slice(view.byteOffset, view.byteOffset + view.byteLength))
}

exports.from = function from(value, encodingOrOffset, length) {
  // from(string, encoding)
  if (typeof value === 'string') return fromString(value, encodingOrOffset)

  // from(array)
  if (Array.isArray(value)) return fromArray(value)

  // from(buffer)
  if (ArrayBuffer.isView(value)) return fromBuffer(value)

  // from(arrayBuffer[, offset[, length]])
  return fromArrayBuffer(value, encodingOrOffset, length)
}

function fromString(string, encoding) {
  const codec = codecFor(encoding)
  const buffer = new Buffer(codec.byteLength(string))
  codec.write(buffer, string)
  return buffer
}

function fromArray(array) {
  const buffer = new Buffer(array.length)
  buffer.set(array)
  return buffer
}

function fromBuffer(buffer) {
  const copy = new Buffer(buffer.byteLength)
  copy.set(buffer)
  return copy
}

function fromArrayBuffer(arrayBuffer, offset, length) {
  return new Buffer(arrayBuffer, offset, length)
}

function bidirectionalIndexOf(buffer, value, offset, encoding, first) {
  if (buffer.byteLength === 0) return -1

  if (typeof offset === 'string') {
    encoding = offset
    offset = 0
  } else if (offset === undefined) {
    offset = first ? 0 : buffer.byteLength - 1
  } else if (offset < 0) {
    offset += buffer.byteLength
  }

  if (offset >= buffer.byteLength) {
    if (first) return -1
    else offset = buffer.byteLength - 1
  } else if (offset < 0) {
    if (first) offset = 0
    else return -1
  }

  if (typeof value === 'string') value = exports.from(value, encoding)

  if (value.byteLength === 0) return -1

  if (first) {
    let foundIndex = -1

    for (let i = offset; i < buffer.byteLength; i++) {
      if (buffer[i] === value[foundIndex === -1 ? 0 : i - foundIndex]) {
        if (foundIndex === -1) foundIndex = i
        if (i - foundIndex + 1 === value.byteLength) return foundIndex
      } else {
        if (foundIndex !== -1) i -= i - foundIndex
        foundIndex = -1
      }
    }
  } else {
    if (offset + value.byteLength > buffer.byteLength) {
      offset = buffer.byteLength - value.byteLength
    }

    for (let i = offset; i >= 0; i--) {
      let found = true

      for (let j = 0; j < value.byteLength; j++) {
        if (buffer[i + j] !== value[j]) {
          found = false
          break
        }
      }

      if (found) return i
    }
  }

  return -1
}

function swap(buffer, n, m) {
  const i = buffer[n]
  buffer[n] = buffer[m]
  buffer[m] = i
}

exports.atob = function atob(data) {
  return Buffer.from(data, 'base64').toString('latin1')
}

exports.btoa = function btoa(data) {
  if (typeof data !== 'string') data = String(data)

  return Buffer.from(data, 'latin1').toString('base64')
}

exports.transcode = function transcode(buffer, from, to) {
  return Buffer.from(buffer.toString(from), to)
}

function readInt48BE(view, offset) {
  const hi = view.getUint16(offset, false)
  const lo = view.getUint32(offset + 2, false)
  let value = lo + hi * 0x100000000
  if (hi & 0x8000) value -= 0x1000000000000
  return value
}

function readInt48LE(view, offset) {
  const lo = view.getUint32(offset, true)
  const hi = view.getUint16(offset + 4, true)
  let value = lo + hi * 0x100000000
  if (hi & 0x8000) value -= 0x1000000000000
  return value
}

function readInt40BE(view, offset) {
  const hi = view.getUint8(offset)
  const lo = view.getUint32(offset + 1, false)
  let value = lo + hi * 0x100000000
  if (hi & 0x80) value -= 0x10000000000
  return value
}

function readInt40LE(view, offset) {
  const lo = view.getUint32(offset, true)
  const hi = view.getUint8(offset + 4)
  let value = lo + hi * 0x100000000
  if (hi & 0x80) value -= 0x10000000000
  return value
}

function readInt24BE(view, offset) {
  const value =
    (view.getUint8(offset) << 16) | (view.getUint8(offset + 1) << 8) | view.getUint8(offset + 2)
  return value & 0x800000 ? value - 0x1000000 : value
}

function readInt24LE(view, offset) {
  const value =
    view.getUint8(offset) | (view.getUint8(offset + 1) << 8) | (view.getUint8(offset + 2) << 16)
  return value & 0x800000 ? value - 0x1000000 : value
}

function readUint48BE(view, offset) {
  const hi = view.getUint16(offset, false)
  const lo = view.getUint32(offset + 2, false)
  return lo + hi * 0x100000000
}

function readUint48LE(view, offset) {
  const lo = view.getUint32(offset, true)
  const hi = view.getUint16(offset + 4, true)
  return lo + hi * 0x100000000
}

function readUint40BE(view, offset) {
  const hi = view.getUint8(offset)
  const lo = view.getUint32(offset + 1, false)
  return lo + hi * 0x100000000
}

function readUint40LE(view, offset) {
  const lo = view.getUint32(offset, true)
  const hi = view.getUint8(offset + 4)
  return lo + hi * 0x100000000
}

function readUint24BE(view, offset) {
  return (
    (view.getUint8(offset) << 16) | (view.getUint8(offset + 1) << 8) | view.getUint8(offset + 2)
  )
}

function readUint24LE(view, offset) {
  return (
    view.getUint8(offset) | (view.getUint8(offset + 1) << 8) | (view.getUint8(offset + 2) << 16)
  )
}

function writeInt48BE(value, view, offset) {
  if (value < 0) value += 0x1000000000000
  const hi = Math.floor(value / 0x100000000)
  const lo = value >>> 0
  view.setUint16(offset, hi, false)
  view.setUint32(offset + 2, lo, false)
  return offset + 6
}

function writeInt48LE(value, view, offset) {
  if (value < 0) value += 0x1000000000000
  const hi = Math.floor(value / 0x100000000)
  const lo = value >>> 0
  view.setUint32(offset, lo, true)
  view.setUint16(offset + 4, hi, true)
  return offset + 6
}

function writeInt40BE(value, view, offset) {
  if (value < 0) value += 0x10000000000
  const hi = Math.floor(value / 0x100000000)
  const lo = value >>> 0
  view.setUint8(offset, hi)
  view.setUint32(offset + 1, lo, false)
  return offset + 5
}

function writeInt40LE(value, view, offset) {
  if (value < 0) value += 0x10000000000
  const hi = Math.floor(value / 0x100000000)
  const lo = value >>> 0
  view.setUint32(offset, lo, true)
  view.setUint8(offset + 4, hi)
  return offset + 5
}

function writeInt24BE(value, view, offset) {
  if (value < 0) value += 0x1000000
  view.setUint8(offset, (value >> 16) & 0xff)
  view.setUint8(offset + 1, (value >> 8) & 0xff)
  view.setUint8(offset + 2, value & 0xff)
  return offset + 3
}

function writeInt24LE(value, view, offset) {
  if (value < 0) value += 0x1000000
  view.setUint8(offset, value & 0xff)
  view.setUint8(offset + 1, (value >> 8) & 0xff)
  view.setUint8(offset + 2, (value >> 16) & 0xff)
  return offset + 3
}

function writeUint48BE(value, view, offset) {
  const hi = Math.floor(value / 0x100000000)
  const lo = value >>> 0
  view.setUint16(offset, hi, false)
  view.setUint32(offset + 2, lo, false)
  return offset + 6
}

function writeUint48LE(value, view, offset) {
  const hi = Math.floor(value / 0x100000000)
  const lo = value >>> 0
  view.setUint32(offset, lo, true)
  view.setUint16(offset + 4, hi, true)
  return offset + 6
}

function writeUint40BE(value, view, offset) {
  const hi = Math.floor(value / 0x100000000)
  const lo = value >>> 0
  view.setUint8(offset, hi)
  view.setUint32(offset + 1, lo, false)
  return offset + 5
}

function writeUint40LE(value, view, offset) {
  const hi = Math.floor(value / 0x100000000)
  const lo = value >>> 0
  view.setUint32(offset, lo, true)
  view.setUint8(offset + 4, hi)
  return offset + 5
}

function writeUint24BE(value, view, offset) {
  view.setUint8(offset, (value >> 16) & 0xff)
  view.setUint8(offset + 1, (value >> 8) & 0xff)
  view.setUint8(offset + 2, value & 0xff)
  return offset + 3
}

function writeUint24LE(value, view, offset) {
  view.setUint8(offset, value & 0xff)
  view.setUint8(offset + 1, (value >> 8) & 0xff)
  view.setUint8(offset + 2, (value >> 16) & 0xff)
  return offset + 3
}
const binding = require('../binding')

exports.byteLength = function byteLength(string) {
  return string.length
}

exports.toString = function toString(buffer) {
  const len = buffer.byteLength

  let result = ''

  for (let i = 0; i < len; i++) {
    result += String.fromCharCode(buffer[i] & 0x7f)
  }

  return result
}

exports.write = function write(buffer, string) {
  const len = buffer.byteLength

  for (let i = 0; i < len; i++) {
    buffer[i] = string.charCodeAt(i)
  }

  return len
}

exports.validate = function validate(buffer) {
  return binding.validateAscii(buffer.buffer, buffer.byteLength)
}
const binding = require('../binding')

exports.byteLength = function byteLength(string) {
  let len = string.length

  if (string.charCodeAt(len - 1) === 0x3d) len--
  if (len > 1 && string.charCodeAt(len - 1) === 0x3d) len--

  return (len * 3) >>> 2
}

exports.toString = function toString(buffer) {
  return binding.toStringBase64(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

exports.write = function write(buffer, string) {
  return binding.writeBase64(buffer.buffer, buffer.byteOffset, buffer.byteLength, string)
}
const binding = require('../binding')

exports.byteLength = function byteLength(string) {
  let len = string.length

  if (string.charCodeAt(len - 1) === 0x3d) len--
  if (len > 1 && string.charCodeAt(len - 1) === 0x3d) len--

  return (len * 3) >>> 2
}

exports.toString = function toString(buffer) {
  return binding.toStringBase64URL(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

exports.write = function write(buffer, string) {
  return binding.writeBase64(buffer.buffer, buffer.byteOffset, buffer.byteLength, string)
}
const binding = require('../binding')

module.exports = binding.constants
const binding = require('../binding')

exports.byteLength = function byteLength(string) {
  return string.length >>> 1
}

exports.toString = function toString(buffer) {
  return binding.toStringHex(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

exports.write = function write(buffer, string) {
  return binding.writeHex(buffer.buffer, buffer.byteOffset, buffer.byteLength, string)
}
const binding = require('../binding')

exports.byteLength = function byteLength(string) {
  return string.length
}

exports.toString = function toString(buffer) {
  return binding.toStringLatin1(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

exports.write = function write(buffer, string) {
  return binding.writeLatin1(buffer.buffer, buffer.byteOffset, buffer.byteLength, string)
}
const binding = require('../binding')

exports.byteLength = function byteLength(string) {
  return string.length * 2
}

exports.toString = function toString(buffer) {
  return binding.toStringUTF16LE(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

exports.write = function write(buffer, string) {
  return binding.writeUTF16LE(buffer.buffer, buffer.byteOffset, buffer.byteLength, string)
}
const binding = require('../binding')

exports.byteLength = function byteLength(string) {
  return binding.byteLengthUTF8(string)
}

exports.toString = function toString(buffer) {
  return binding.toStringUTF8(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

exports.write = function write(buffer, string) {
  return binding.writeUTF8(buffer.buffer, buffer.byteOffset, buffer.byteLength, string)
}

exports.validate = function validate(buffer) {
  return binding.validateUTF8(buffer.buffer, buffer.byteLength)
}
{
  "name": "bare-buffer",
  "version": "3.6.2",
  "description": "Native buffers for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    },
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "global.js",
    "global.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-buffer.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-buffer/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-buffer#readme",
  "engines": {
    "bare": ">=1.20.0"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "cmake-bare": "^1.1.6",
    "cmake-fetch": "^1.0.0",
    "lunte": "^1.8.0",
    "prettier": "^3.3.3",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = require.addon()
const constants = require('./lib/constants')
const Hash = require('./lib/hash')
const Hmac = require('./lib/hmac')
const { Cipheriv, Decipheriv } = require('./lib/cipher')
const { randomBytes, randomFill, randomUUID } = require('./lib/random')
const pbkdf2 = require('./lib/pbkdf2')
const { generateKeyPair } = require('./lib/key')
const { sign, verify } = require('./lib/signature')
const { timingSafeEqual } = require('./lib/timing')

exports.constants = constants

exports.Hash = Hash

exports.createHash = function createHash(algorithm, opts) {
  return new Hash(algorithm, opts)
}

exports.Hmac = Hmac

exports.createHmac = function createHmac(algorithm, key, opts) {
  return new Hmac(algorithm, key, opts)
}

exports.Cipheriv = Cipheriv

exports.createCipheriv = function createCipheriv(algorithm, key, iv, opts) {
  return new Cipheriv(algorithm, key, iv, opts)
}

exports.Decipheriv = Decipheriv

exports.createDecipheriv = function createDecipheriv(algorithm, key, iv, opts) {
  return new Decipheriv(algorithm, key, iv, opts)
}

exports.randomBytes = randomBytes

exports.randomFill = randomFill

// For Node.js compatibility
exports.randomFillSync = function randomFillSync(buffer, offset, size) {
  return exports.randomFill(buffer, offset, size)
}

exports.randomUUID = randomUUID

exports.pbkdf2 = pbkdf2

// For Node.js compatibility
exports.pbkdf2Sync = function pbkdf2Sync(password, salt, iterations, keylen, digest) {
  return exports.pbkdf2(password, salt, iterations, keylen, digest)
}

exports.generateKeyPair = generateKeyPair

exports.sign = sign

exports.verify = verify

exports.timingSafeEqual = timingSafeEqual

// For Node.js compatibility
exports.webcrypto = require('./web')
const { Transform } = require('bare-stream')
const assert = require('bare-assert')
const binding = require('../binding')
const constants = require('./constants')

const {
  cipher: {
    AES128ECB,
    AES128CBC,
    AES128CTR,
    AES128OFB,
    AES256ECB,
    AES256CBC,
    AES256CTR,
    AES256OFB,
    AES128GCM,
    AES256GCM,
    CHACHA20POLY1305,
    XCHACHA20POLY1305
  }
} = constants

class CryptoCipher {
  constructor(algorithm, key, iv, encrypt, opts = {}) {
    const { encoding = 'utf8' } = opts

    if (typeof key === 'string') key = Buffer.from(key, encoding)
    if (typeof iv === 'string') iv = Buffer.from(iv, encoding)

    assert(ArrayBuffer.isView(key))
    assert(ArrayBuffer.isView(iv))

    if (key.byteLength !== binding.cipherKeyLength(algorithm)) {
      throw new RangeError('Invalid key length')
    }

    if (iv.byteLength !== binding.cipherIVLength(algorithm)) {
      throw new RangeError('Invalid iv length')
    }

    this._finalized = false

    binding.cipherInit(
      this,
      algorithm,
      key.buffer,
      key.byteOffset,
      key.byteLength,
      iv.buffer,
      iv.byteOffset,
      iv.byteLength,
      encrypt
    )
  }

  update(data, inputEncoding = 'utf8', outputEncoding) {
    if (this._finalized) {
      throw new Error('Cipher has already been finalized')
    }

    if (typeof data === 'string') data = Buffer.from(data, inputEncoding)

    assert(ArrayBuffer.isView(data))

    const out = new ArrayBuffer(data.byteLength + binding.cipherBlockSize(this))

    const written = binding.cipherUpdate(this, data.buffer, data.byteOffset, data.byteLength, out)

    const result = Buffer.from(out, 0, written)

    return outputEncoding ? result.toString(outputEncoding) : result
  }

  final(outputEncoding) {
    if (this._finalized) {
      throw new Error('Cipher has already been finalized')
    }

    const out = new ArrayBuffer(binding.cipherBlockSize(this))

    const written = binding.cipherFinal(this, out)

    this._finalized = true

    const result = Buffer.from(out, 0, written)

    return outputEncoding ? result.toString(outputEncoding) : result
  }

  setAutoPadding(pad) {
    if (this._finalized) {
      throw new Error('Cipher has already been finalized')
    }

    binding.cipherSetPadding(this, pad)
  }
}

class CryptoAuthenticatedCipher {
  constructor(algorithm, key, nonce, opts = {}) {
    const { encoding = 'utf8', authTagLength = 16 } = opts

    if (typeof key === 'string') key = Buffer.from(key, encoding)
    if (typeof nonce === 'string') nonce = Buffer.from(nonce, encoding)

    assert(ArrayBuffer.isView(key))
    assert(ArrayBuffer.isView(nonce))

    if (key.byteLength !== binding.aeadKeyLength(algorithm)) {
      throw new RangeError('Invalid key length')
    }

    if (nonce.byteLength !== binding.aeadNonceLength(algorithm)) {
      throw new RangeError('Invalid nonce length')
    }

    if (authTagLength !== 12 && authTagLength !== 14 && authTagLength !== 16) {
      throw new RangeError('Invalid authentication tag length')
    }

    this._buffer = []
    this._nonce = nonce
    this._authTag = null
    this._authTagLength = authTagLength
    this._additionalData = null
    this._finalized = false

    binding.aeadInit(this, algorithm, key.buffer, key.byteOffset, key.byteLength, authTagLength)
  }

  update(data, inputEncoding = 'utf8', outputEncoding) {
    if (typeof data === 'string') data = Buffer.from(data, inputEncoding)

    assert(ArrayBuffer.isView(data))

    this._buffer.push(data)

    return outputEncoding ? '' : Buffer.alloc(0)
  }

  setAAD(buffer, opts = {}) {
    const { encoding = 'utf8' } = opts

    if (typeof buffer === 'string') buffer = Buffer.from(buffer, encoding)

    assert(ArrayBuffer.isView(buffer))

    this._additionalData = buffer
  }

  getAuthTag() {
    return this._authTag
  }

  setAuthTag(authTag, encoding) {
    if (typeof authTag === 'string') authTag = Buffer.from(authTag, encoding)

    assert(ArrayBuffer.isView(authTag))

    this._authTag = authTag
  }
}

class CryptoAuthenticatedSeal extends CryptoAuthenticatedCipher {
  final(outputEncoding) {
    if (this._finalized) {
      throw new Error('Cipher has already been finalized')
    }

    const data = this._buffer.length === 1 ? this._buffer[0] : Buffer.concat(this._buffer)

    const nonce = this._nonce
    const ad = this._additionalData || Buffer.alloc(0)

    const out = new ArrayBuffer(data.byteLength + binding.aeadMaxOverhead(this))

    const written = binding.aeadSeal(
      this,
      data.buffer,
      data.byteOffset,
      data.byteLength,
      nonce.buffer,
      nonce.byteOffset,
      nonce.byteLength,
      ad.buffer,
      ad.byteOffset,
      ad.byteLength,
      out
    )

    this._finalized = true

    const cipherLength = written - this._authTagLength

    this._authTag = Buffer.from(out, cipherLength)

    const result = Buffer.from(out, 0, cipherLength)

    return outputEncoding ? result.toString(outputEncoding) : result
  }
}

class CryptoAuthenticatedOpen extends CryptoAuthenticatedCipher {
  final(outputEncoding) {
    if (this._finalized) {
      throw new Error('Decipher has already been finalized')
    }

    this._buffer.push(this._authTag)

    const data = Buffer.concat(this._buffer)

    const nonce = this._nonce
    const ad = this._additionalData || Buffer.alloc(0)

    const out = new ArrayBuffer(data.byteLength)

    const written = binding.aeadOpen(
      this,
      data.buffer,
      data.byteOffset,
      data.byteLength,
      nonce.buffer,
      nonce.byteOffset,
      nonce.byteLength,
      ad.buffer,
      ad.byteOffset,
      ad.byteLength,
      out
    )

    this._finalized = true

    const result = Buffer.from(out, 0, written)

    return outputEncoding ? result.toString(outputEncoding) : result
  }
}

exports.Cipheriv = class CryptoCipheriv extends Transform {
  constructor(algorithm, key, iv, opts = {}) {
    super(opts)

    algorithm = constants.toCipher(algorithm)

    switch (algorithm) {
      case AES128ECB:
      case AES128CBC:
      case AES128CTR:
      case AES128OFB:
      case AES256ECB:
      case AES256CBC:
      case AES256CTR:
      case AES256OFB:
        this._cipher = new CryptoCipher(algorithm, key, iv, true, opts)
        break

      case AES128GCM:
      case AES256GCM:
      case CHACHA20POLY1305:
      case XCHACHA20POLY1305:
        this._cipher = new CryptoAuthenticatedSeal(algorithm, key, iv, opts)
        break
    }
  }

  update(data, inputEncoding, outputEncoding) {
    return this._cipher.update(data, inputEncoding, outputEncoding)
  }

  final(outputEncoding) {
    return this._cipher.final(outputEncoding)
  }

  setAutoPadding(pad) {
    this._cipher.setAutoPadding(pad)

    return this
  }

  setAAD(buffer, opts) {
    this._cipher.setAAD(buffer, opts)

    return this
  }

  getAuthTag() {
    return this._cipher.getAuthTag()
  }

  _transform(data, encoding, cb) {
    this.push(this.update(data))

    cb(null)
  }

  _flush(cb) {
    this.push(this.final())

    cb(null)
  }
}

exports.Decipheriv = class CryptoDeipheriv extends Transform {
  constructor(algorithm, key, iv, opts = {}) {
    super(opts)

    algorithm = constants.toCipher(algorithm)

    switch (algorithm) {
      case AES128ECB:
      case AES128CBC:
      case AES128CTR:
      case AES128OFB:
      case AES256ECB:
      case AES256CBC:
      case AES256CTR:
      case AES256OFB:
        this._cipher = new CryptoCipher(algorithm, key, iv, false, opts)
        break

      case AES128GCM:
      case AES256GCM:
      case CHACHA20POLY1305:
      case XCHACHA20POLY1305:
        this._cipher = new CryptoAuthenticatedOpen(algorithm, key, iv, opts)
        break
    }
  }

  update(data, inputEncoding, outputEncoding) {
    return this._cipher.update(data, inputEncoding, outputEncoding)
  }

  final(outputEncoding) {
    return this._cipher.final(outputEncoding)
  }

  setAutoPadding(pad) {
    this._cipher.setAutoPadding(pad)

    return this
  }

  setAAD(buffer, opts) {
    this._cipher.setAAD(buffer, opts)

    return this
  }

  setAuthTag(authTag, encoding) {
    this._cipher.setAuthTag(authTag, encoding)

    return this
  }

  _transform(data, encoding, cb) {
    this.push(this.update(data))

    cb(null)
  }

  _flush(cb) {
    this.push(this.final())

    cb(null)
  }
}
const { fail } = require('bare-assert')
const binding = require('../binding')
const errors = require('./errors')

module.exports = exports = {
  hash: {
    MD5: binding.MD5,
    SHA1: binding.SHA1,
    SHA256: binding.SHA256,
    SHA384: binding.SHA384,
    SHA512: binding.SHA512,
    BLAKE2B256: binding.BLAKE2B256,
    RIPEMD160: binding.RIPEMD160
  },
  signature: {
    ED25519: binding.ED25519
  },
  cipher: {
    AES128ECB: binding.AES128ECB,
    AES128CBC: binding.AES128CBC,
    AES128CTR: binding.AES128CTR,
    AES128OFB: binding.AES128OFB,
    AES256ECB: binding.AES256ECB,
    AES256CBC: binding.AES256CBC,
    AES256CTR: binding.AES256CTR,
    AES256OFB: binding.AES256OFB,
    AES128GCM: binding.AES128GCM,
    AES256GCM: binding.AES256GCM,
    CHACHA20POLY1305: binding.CHACHA20POLY1305,
    XCHACHA20POLY1305: binding.XCHACHA20POLY1305
  },
  keyType: {
    ED25519: binding.ED25519
  }
}

exports.toHash = function toHash(hash) {
  if (typeof hash === 'number' && !isNaN(hash)) return hash

  if (typeof hash === 'string') {
    hash = hash.replace(/-/g, '')

    if (hash in exports.hash === false) {
      hash = hash.toUpperCase()

      if (hash in exports.hash === false) {
        throw errors.UNKNOWN_HASH(`Unknown hash '${hash}'`)
      }
    }

    return exports.hash[hash]
  }

  fail(`Hash must be a number or string. Received ${isNaN(hash) ? 'NaN' : typeof hash} (${hash})`)
}

exports.toCipher = function toCiper(cipher) {
  if (typeof cipher === 'number' && !isNaN(cipher)) return cipher

  if (typeof cipher === 'string') {
    cipher = cipher.replace(/-/g, '')

    if (cipher in exports.cipher === false) {
      cipher = cipher.toUpperCase()

      if (cipher in exports.cipher === false) {
        throw errors.UNKNOWN_CIPHER(`Unknown cipher '${cipher}'`)
      }
    }

    return exports.cipher[cipher]
  }

  fail(
    `Cipher must be a number or string. Received ${isNaN(cipher) ? 'NaN' : typeof cipher} (${cipher})`
  )
}

exports.toKeyType = function toKeyType(type) {
  if (typeof type === 'number' && !isNaN(type)) return type

  if (typeof type === 'string') {
    type = type.replace(/-/g, '')

    if (type in exports.keyType === false) {
      type = type.toUpperCase()

      if (type in exports.keyType === false) {
        throw errors.UNKNOWN_KEY_TYPE(`Unknown key type '${type}'`)
      }
    }

    return exports.keyType[type]
  }

  fail(
    `Key type must be a number or string. Received ${isNaN(type) ? 'NaN' : typeof type} (${type})`
  )
}
module.exports = class CryptoError extends Error {
  constructor(msg, fn = CryptoError, code = fn.name) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'CryptoError'
  }

  static UNKNOWN_HASH(msg) {
    return new CryptoError(msg, CryptoError.UNKNOWN_HASH)
  }

  static UNKNOWN_CIPHER(msg) {
    return new CryptoError(msg, CryptoError.UNKNOWN_CIPHER)
  }

  static UNKNOWN_KEY_TYPE(msg) {
    return new CryptoError(msg, CryptoError.UNKNOWN_KEY_TYPE)
  }

  static INVALID_ACCESS(msg) {
    return new CryptoError(msg, CryptoError.INVALID_ACCESS)
  }

  static INVALID_DATA(msg) {
    return new CryptoError(msg, CryptoError.INVALID_DATA)
  }

  static OPERATION_ERROR(msg) {
    return new CryptoError(msg, CryptoError.OPERATION_ERROR)
  }

  static NOT_SUPPORTED(msg) {
    return new CryptoError(msg, CryptoError.NOT_SUPPORTED)
  }
}
const { Transform } = require('bare-stream')
const assert = require('bare-assert')
const binding = require('../binding')
const constants = require('./constants')

const {
  hash: { RIPEMD160 }
} = constants

class CryptoDigest {
  constructor(algorithm) {
    this._handle = binding.digestInit(algorithm)
  }

  update(data) {
    if (this._handle === null) {
      throw new Error('Digest has already been finalized')
    }

    binding.digestUpdate(this._handle, data.buffer, data.byteOffset, data.byteLength)
  }

  final() {
    if (this._handle === null) {
      throw new Error('Digest has already been finalized')
    }

    const result = Buffer.from(binding.digestFinal(this._handle))
    this._handle = null
    return result
  }
}

class CryptoRIPEMD160Digest {
  constructor() {
    this._handle = binding.ripemd160Init()
  }

  update(data) {
    if (this._handle === null) {
      throw new Error('Digest has already been finalized')
    }

    binding.ripemd160Update(this._handle, data.buffer, data.byteOffset, data.byteLength)
  }

  final() {
    if (this._handle === null) {
      throw new Error('Digest has already been finalized')
    }

    const result = Buffer.from(binding.ripemd160Final(this._handle))
    this._handle = null
    return result
  }
}

module.exports = class CryptoHash extends Transform {
  constructor(algorithm, opts = {}) {
    super(opts)

    algorithm = constants.toHash(algorithm)

    switch (algorithm) {
      case RIPEMD160:
        this._digest = new CryptoRIPEMD160Digest()
        break

      default:
        this._digest = new CryptoDigest(algorithm)
        break
    }
  }

  update(data, encoding = 'utf8') {
    if (typeof data === 'string') data = Buffer.from(data, encoding)

    assert(ArrayBuffer.isView(data))

    this._digest.update(data)

    return this
  }

  digest(encoding) {
    const digest = this._digest.final()

    return encoding && encoding !== 'buffer' ? digest.toString(encoding) : digest
  }

  _transform(data, encoding, cb) {
    this.update(data)

    cb(null)
  }

  _flush(cb) {
    this.push(this.digest())

    cb(null)
  }
}
const { Transform } = require('bare-stream')
const assert = require('bare-assert')
const binding = require('../binding')
const constants = require('./constants')

module.exports = class CryptoHmac extends Transform {
  constructor(algorithm, key, opts = {}) {
    super(opts)

    const { encoding = 'utf8' } = opts

    if (typeof key === 'string') key = Buffer.from(key, encoding)

    assert(ArrayBuffer.isView(key))

    this._finalized = false

    binding.hmacInit(this, constants.toHash(algorithm), key.buffer, key.byteOffset, key.byteLength)
  }

  update(data, encoding = 'utf8') {
    if (this._finalized) {
      throw new Error('Hmac has already been finalized')
    }

    if (typeof data === 'string') data = Buffer.from(data, encoding)

    assert(ArrayBuffer.isView(data))

    binding.hmacUpdate(this, data.buffer, data.byteOffset, data.byteLength)

    return this
  }

  digest(encoding) {
    if (this._finalized) {
      throw new Error('Hmac has already been finalized')
    }

    const digest = Buffer.from(binding.hmacFinal(this))
    this._finalized = true

    return encoding && encoding !== 'buffer' ? digest.toString(encoding) : digest
  }

  _transform(data, encoding, cb) {
    this.update(data)

    cb(null)
  }

  _flush(cb) {
    this.push(this.digest())

    cb(null)
  }
}
const binding = require('../binding')
const constants = require('./constants')

const {
  keyType: { ED25519 }
} = constants

class CryptoKey {
  constructor(keyType) {
    this._keyType = keyType
  }

  get type() {
    throw new Error('Not implemented')
  }

  get destroyed() {
    return false
  }

  export() {
    throw new Error('Not implemented')
  }

  destroy() {}

  [Symbol.dispose]() {
    this.destroy()
  }
}

exports.Key = CryptoKey

class CryptoEd25519Key extends CryptoKey {
  constructor(key = null) {
    super(ED25519)

    this._destroyed = false

    if (key === null) {
      binding.keyInit(this, new ArrayBuffer(0), 0, 0)
    } else if (ArrayBuffer.isView(key)) {
      binding.keyInit(this, key.buffer, key.byteOffset, key.byteLength)
    } else {
      binding.keyInit(this, key, 0, key.byteLength)
    }
  }

  get asymmetricKeyType() {
    return 'ed25519'
  }

  get destroyed() {
    return this._destroyed
  }

  export() {
    if (this._destroyed) {
      throw new Error('Key has been destroyed')
    }

    return Buffer.from(binding.keyExport(this))
  }

  destroy() {
    if (this._destroyed) return

    binding.keyDestroy(this)

    this._destroyed = true
  }
}

class CryptoEd25519PublicKey extends CryptoEd25519Key {
  get type() {
    return 'public'
  }
}

exports.Ed25519PublicKey = CryptoEd25519PublicKey

class CryptoEd25519PrivateKey extends CryptoEd25519Key {
  get type() {
    return 'private'
  }
}

exports.Ed25519PrivateKey = CryptoEd25519PrivateKey

class CryptoSecretKey extends CryptoKey {
  constructor(key) {
    super()

    this._destroyed = false

    if (ArrayBuffer.isView(key)) {
      binding.keyInit(this, key.buffer, key.byteOffset, key.byteLength)
    } else {
      binding.keyInit(this, key, 0, key.byteLength)
    }
  }

  get type() {
    return 'secret'
  }

  get destroyed() {
    return this._destroyed
  }

  export() {
    if (this._destroyed) {
      throw new Error('Key has been destroyed')
    }

    return Buffer.from(binding.keyExport(this))
  }

  destroy() {
    if (this._destroyed) return

    binding.keyDestroy(this)

    this._destroyed = true
  }
}

exports.SecretKey = CryptoSecretKey

exports.generateKeyPair = function generateKeyPair(type) {
  type = constants.toKeyType(type)

  switch (type) {
    case ED25519: {
      const publicKey = new CryptoEd25519PublicKey()
      const privateKey = new CryptoEd25519PrivateKey()

      binding.ed25519GenerateKeypair(publicKey, privateKey)

      return { publicKey, privateKey }
    }
  }
}
const assert = require('bare-assert')
const binding = require('../binding')
const constants = require('./constants')

module.exports = function pbkdf2(password, salt, iterations, keylen, digest, cb) {
  assert(typeof iterations === 'number' && !isNaN(iterations))

  if (iterations < 1 || iterations > 0xffffffff) {
    throw new RangeError('Invalid iterations')
  }

  assert(typeof keylen === 'number' && !isNaN(keylen))

  if (keylen < 1 || keylen > 0x7fffffff) {
    throw new RangeError('Invalid key length')
  }

  if (typeof password === 'string') password = Buffer.from(password)
  if (typeof salt === 'string') salt = Buffer.from(salt)

  assert(ArrayBuffer.isView(password))
  assert(ArrayBuffer.isView(salt))

  const buffer = Buffer.from(
    binding.pbkdf2(
      password.buffer,
      password.byteOffset,
      password.byteLength,
      salt.buffer,
      salt.byteOffset,
      salt.byteLength,
      iterations,
      constants.toHash(digest),
      keylen
    )
  )

  if (cb) queueMicrotask(() => cb(null, buffer))
  else return buffer
}
const assert = require('bare-assert')
const binding = require('../binding')

exports.randomBytes = function randomBytes(size, cb) {
  assert(typeof size === 'number' && !isNaN(size))

  const buffer = Buffer.allocUnsafe(size)
  exports.randomFill(buffer)
  if (cb) queueMicrotask(() => cb(null, buffer))
  else return buffer
}

exports.randomFill = function randomFill(buffer, offset, size, cb) {
  if (typeof offset === 'function') {
    cb = offset
    offset = undefined
  } else if (typeof size === 'function') {
    cb = size
    size = undefined
  }

  assert(buffer instanceof ArrayBuffer || ArrayBuffer.isView(buffer))
  assert(size === undefined || (typeof size === 'number' && !isNaN(size)))
  assert(offset === undefined || (typeof offset === 'number' && !isNaN(offset)))

  const elementSize = buffer.BYTES_PER_ELEMENT || 1

  if (offset === undefined) offset = 0
  else offset *= elementSize

  if (size === undefined) size = buffer.byteLength - offset
  else size *= elementSize

  if (offset < 0 || offset > buffer.byteLength) {
    throw new RangeError('offset is out of range')
  }

  if (size < 0 || size > buffer.byteLength) {
    throw new RangeError('size is out of range')
  }

  if (offset + size > buffer.byteLength) {
    throw new RangeError('offset + size is out of range')
  }

  let arraybuffer

  if (ArrayBuffer.isView(buffer)) {
    offset += buffer.byteOffset
    arraybuffer = buffer.buffer
  } else {
    arraybuffer = buffer
  }

  binding.randomFill(arraybuffer, offset, size)

  if (cb) queueMicrotask(() => cb(null, buffer))
  else return buffer
}

exports.randomUUID = function randomUUID() {
  const uuid = exports.randomBytes(16)

  uuid[6] = (uuid[6] & 0x0f) | 0x40
  uuid[8] = (uuid[8] & 0x3f) | 0x80

  return (
    uuid.subarray(0, 4).toString('hex') +
    '-' +
    uuid.subarray(4, 6).toString('hex') +
    '-' +
    uuid.subarray(6, 8).toString('hex') +
    '-' +
    uuid.subarray(8, 10).toString('hex') +
    '-' +
    uuid.subarray(10, 16).toString('hex')
  )
}
const assert = require('bare-assert')
const binding = require('../binding')
const { Key } = require('./key')
const constants = require('./constants')

const {
  keyType: { ED25519 }
} = constants

exports.sign = function sign(algorithm, data, key) {
  assert(data instanceof ArrayBuffer || ArrayBuffer.isView(data))

  if (ArrayBuffer.isView(data)) {
    data = Buffer.coerce(data)
  } else {
    data = Buffer.from(data)
  }

  assert(key instanceof Key)

  switch (key._keyType) {
    case ED25519:
      return Buffer.from(binding.ed25519Sign(data.buffer, data.byteOffset, data.byteLength, key))
  }
}

exports.verify = function verify(algorithm, data, key, signature) {
  assert(data instanceof ArrayBuffer || ArrayBuffer.isView(data))

  if (ArrayBuffer.isView(data)) {
    data = Buffer.coerce(data)
  } else {
    data = Buffer.from(data)
  }

  assert(signature instanceof ArrayBuffer || ArrayBuffer.isView(signature))

  if (ArrayBuffer.isView(signature)) {
    signature = Buffer.coerce(signature)
  } else {
    signature = Buffer.from(signature)
  }

  assert(key instanceof Key)

  switch (key._keyType) {
    case ED25519:
      assert(signature.byteLength === 64)

      return binding.ed25519Verify(
        data.buffer,
        data.byteOffset,
        data.byteLength,
        signature.buffer,
        signature.byteOffset,
        key
      )
  }
}
const assert = require('bare-assert')
const binding = require('../binding')

exports.timingSafeEqual = function timingSafeEqual(a, b) {
  assert(a instanceof ArrayBuffer || ArrayBuffer.isView(a))
  assert(b instanceof ArrayBuffer || ArrayBuffer.isView(b))

  let aBuffer, aOffset
  if (ArrayBuffer.isView(a)) {
    aBuffer = a.buffer
    aOffset = a.byteOffset
  } else {
    aBuffer = a
    aOffset = 0
  }

  let bBuffer, bOffset
  if (ArrayBuffer.isView(b)) {
    bBuffer = b.buffer
    bOffset = b.byteOffset
  } else {
    bBuffer = b
    bOffset = 0
  }

  return binding.timingSafeEqual(aBuffer, aOffset, a.byteLength, bBuffer, bOffset, b.byteLength)
}
const crypto = require('../../..')
const binding = require('../../../binding')
const errors = require('../../errors')
const { Ed25519PublicKey, Ed25519PrivateKey } = require('../../key')
const CryptoKey = require('../crypto-key')

// https://w3c.github.io/webcrypto/#ed25519

// https://w3c.github.io/webcrypto/#ed25519-operations-sign
exports.sign = function sign(algorithm, key, data) {
  if (key.type !== 'private') {
    throw errors.INVALID_ACCESS('Must pass private key for Ed25519 signing')
  }

  const signature = crypto.sign(null, data, key._handle)

  return signature.buffer.slice(0, signature.byteLength)
}

// https://w3c.github.io/webcrypto/#ed25519-operations-verify
exports.verify = function verify(algorithm, key, signature, data) {
  if (key.type !== 'public') {
    throw errors.INVALID_ACCESS('Must pass public key for Ed25519 verification')
  }

  return crypto.verify(null, data, key._handle, signature)
}

// https://w3c.github.io/webcrypto/#ed25519-operations-generate-key
exports.generateKey = function generateKey(algorithm, extractable, usages) {
  for (const usage of usages) {
    if (usage !== 'sign' && usage !== 'verify') {
      throw new SyntaxError(
        `Usage '${usage}' cannot be used for the Ed25519 generateKey() operation`
      )
    }
  }

  const keys = crypto.generateKeyPair('ed25519')

  algorithm = { name: 'Ed25519' }

  return {
    publicKey: new CryptoKey('public', true, algorithm, ['verify'], keys.publicKey),
    privateKey: new CryptoKey('private', extractable, algorithm, ['sign'], keys.privateKey)
  }
}

// https://w3c.github.io/webcrypto/#ed25519-operations-import-key
exports.importKey = function importKey(format, keyData, algorithm, extractable, usages) {
  switch (format) {
    case 'spki': {
      for (const usage of usages) {
        if (usage !== 'verify') {
          throw new SyntaxError(
            `Usage '${usage}' cannot be used for the Ed25519 importKey() operation`
          )
        }
      }

      const publicKey = new Ed25519PublicKey()

      binding.ed25519FromSPKI(publicKey, keyData.buffer, keyData.byteOffset, keyData.byteLength)

      return new CryptoKey(
        'public',
        extractable,
        {
          name: 'Ed25519'
        },
        usages,
        publicKey
      )
    }
    case 'pkcs8': {
      for (const usage of usages) {
        if (usage !== 'sign') {
          throw new SyntaxError(
            `Usage '${usage}' cannot be used for the Ed25519 importKey() operation`
          )
        }
      }

      const privateKey = new Ed25519PrivateKey()

      binding.ed25519FromPKCS8(privateKey, keyData.buffer, keyData.byteOffset, keyData.byteLength)

      return new CryptoKey(
        'private',
        extractable,
        {
          name: 'Ed25519'
        },
        usages,
        privateKey
      )
    }
    case 'raw':
      for (const usage of usages) {
        if (usage !== 'verify') {
          throw new SyntaxError(
            `Usage '${usage}' cannot be used for the Ed25519 importKey() operation`
          )
        }
      }

      if (keyData.byteLength * 8 !== 256) {
        throw errors.INVALID_DATA('Key must be 256 bits')
      }

      return new CryptoKey(
        'public',
        extractable,
        {
          name: 'Ed25519'
        },
        usages,
        new Ed25519PublicKey(keyData.buffer)
      )
    case 'jwk': {
      const jwk = keyData

      if ('d' in jwk) {
        if (usages.some((usage) => usage !== 'sign')) {
          throw new SyntaxError('JWK must be valid for signing')
        }
      } else {
        if (usages.some((usage) => usage !== 'verify')) {
          throw new SyntaxError('JWK must be valid for verification')
        }
      }

      if (jwk.kty !== 'OKP') {
        throw errors.INVALID_DATA('JWK key must be an octet key-pair')
      }

      if (jwk.crv !== 'Ed25519') {
        throw errors.INVALID_DATA('JWK must use the Ed25519 curve')
      }

      if ('alg' in jwk && jwk.alg !== 'Ed25519' && jwk.alg !== 'EdDSA') {
        throw errors.INVALID_DATA('JWK must use the Ed25519 curve')
      }

      if (usages.length && 'use' in jwk && jwk.use !== 'sig') {
        throw errors.INVALID_DATA('JWK cannot be used for signatures')
      }

      if ('ext' in jwk && jwk.ext !== extractable && extractable) {
        throw errors.INVALID_DATA('JWK is not extractable')
      }

      if ('d' in jwk) {
        const key = Buffer.concat([
          Buffer.from(jwk.d, 'base64url'),
          Buffer.from(jwk.x, 'base64url')
        ])

        if (key.byteLength * 8 !== 512) {
          throw errors.INVALID_DATA('Key must be 512 bits')
        }

        const handle = new Ed25519PrivateKey(key.buffer)

        key.fill(0)

        return new CryptoKey(
          'private',
          extractable,
          {
            name: 'Ed25519'
          },
          usages,
          handle
        )
      }

      const key = Buffer.from(jwk.x, 'base64url')

      if (key.byteLength * 8 !== 256) {
        throw errors.INVALID_DATA('Key must be 256 bits')
      }

      return new CryptoKey(
        'public',
        extractable,
        {
          name: 'Ed25519'
        },
        usages,
        new Ed25519PublicKey(key.buffer)
      )
    }
    default:
      throw errors.NOT_SUPPORTED(
        `Format '${format}' cannot be used for the Ed25519 importKey() operation`
      )
  }
}

// https://w3c.github.io/webcrypto/#ed25519-operations-export-key
exports.exportKey = function exportKey(format, key) {
  const data = key._handle

  switch (format) {
    case 'spki':
      if (key.type !== 'public') {
        throw errors.INVALID_ACCESS(
          `Key of type '${key.type}' cannot be used for the Ed25519 exportKey() operation`
        )
      }

      return binding.ed25519ToSPKI(data)
    case 'pkcs8':
      if (key.type !== 'private') {
        throw errors.INVALID_ACCESS(
          `Key of type '${key.type}' cannot be used for the Ed25519 exportKey() operation`
        )
      }

      return binding.ed25519ToPKCS8(data)
    case 'raw': {
      if (key.type !== 'public') {
        throw errors.INVALID_ACCESS(
          `Key of type '${key.type}' cannot be used for the Ed25519 exportKey() operation`
        )
      }

      return data.export().buffer
    }
    case 'jwk': {
      const buffer = data.export()

      if (key.type === 'private') {
        const d = buffer.subarray(0, 32).toString('base64url')
        const x = buffer.subarray(32).toString('base64url')

        return {
          kty: 'OKP',
          alg: 'Ed25519',
          crv: 'Ed25519',
          x,
          d,
          key_ops: key.usages,
          ext: key.extractable
        }
      }

      return {
        kty: 'OKP',
        alg: 'Ed25519',
        crv: 'Ed25519',
        x: buffer.toString('base64url'),
        key_ops: key.usages,
        ext: key.extractable
      }
    }
    default:
      throw errors.NOT_SUPPORTED(
        `Format '${format}' cannot be used for the HMAC exportKey() operation`
      )
  }
}
const crypto = require('../../..')
const errors = require('../../errors')
const { SecretKey } = require('../../key')
const CryptoKey = require('../crypto-key')

// https://w3c.github.io/webcrypto/#hmac

// https://w3c.github.io/webcrypto/#hmac-operations-sign
exports.sign = function sign(algorithm, key, data) {
  const material = key._handle.export()

  const digest = crypto.createHmac(key.algorithm.hash.name, material).update(data).digest()

  return digest.buffer.slice(0, digest.byteLength)
}

// https://w3c.github.io/webcrypto/#hmac-operations-verify
exports.verify = function verify(algorithm, key, signature, data) {
  const material = key._handle.export()

  const digest = crypto.createHmac(key.algorithm.hash.name, material).update(data).digest()

  if (ArrayBuffer.isView(signature)) {
    signature = Buffer.coerce(signature)
  } else {
    signature = Buffer.from(signature)
  }

  if (signature.byteLength !== digest.byteLength) return false

  return crypto.timingSafeEqual(signature, digest)
}

// https://w3c.github.io/webcrypto/#hmac-operations-generate-key
exports.generateKey = function generateKey(algorithm, extractable, usages) {
  for (const usage of usages) {
    if (usage !== 'sign' && usage !== 'verify') {
      throw new SyntaxError(`Usage '${usage}' cannot be used for the HMAC generateKey() operation`)
    }
  }

  const length = exports.getKeyLength(algorithm)

  let hash = algorithm.hash

  if (typeof hash === 'string') hash = { name: hash }

  const key = crypto.randomBytes(length / 8)

  const handle = new SecretKey(key)

  key.fill(0)

  return new CryptoKey(
    'secret',
    extractable,
    {
      name: 'HMAC',
      length,
      hash: {
        name: hash.name.toUpperCase()
      }
    },
    usages,
    handle
  )
}

// https://w3c.github.io/webcrypto/#hmac-operations-import-key
exports.importKey = function importKey(format, keyData, algorithm, extractable, usages) {
  for (const usage of usages) {
    if (usage !== 'sign' && usage !== 'verify') {
      throw new SyntaxError(`Invalid usage ${usage}`)
    }
  }

  let hash = algorithm.hash

  if (typeof hash === 'string') hash = { name: hash }

  let data
  let owned = false

  switch (format) {
    case 'raw':
      data = keyData
      break
    case 'jwk': {
      const jwk = keyData

      if (jwk.kty !== 'oct') {
        throw errors.INVALID_DATA('JWK key must be an octet sequence')
      }

      data = Buffer.from(jwk.k, 'base64url')
      owned = true

      switch (hash.name.toLowerCase()) {
        case 'sha-1':
          if (jwk.alg === 'HS1') break
          else throw errors.INVALID_DATA('Invalid JWK key algorithm')
        case 'sha-256':
          if (jwk.alg === 'HS256') break
          else throw errors.INVALID_DATA('Invalid JWK key algorithm')
        case 'sha-384':
          if (jwk.alg === 'HS384') break
          else throw errors.INVALID_DATA('Invalid JWK key algorithm')
        case 'sha-512':
          if (jwk.alg === 'HS512') break
          else throw errors.INVALID_DATA('Invalid JWK key algorithm')
      }

      if (usages.length && 'use' in jwk && jwk.use !== 'sign') {
        throw errors.INVALID_DATA('JWK cannot be used for signing')
      }

      if ('ext' in jwk && jwk.ext !== extractable && extractable) {
        throw errors.INVALID_DATA('JWK is not extractable')
      }
      break
    }
    default:
      throw errors.NOT_SUPPORTED(
        `Format '${format}' cannot be used for the HMAC importKey() operation`
      )
  }

  const length = data.byteLength * 8

  if (length === 0) {
    throw errors.INVALID_DATA('Key cannot be empty')
  }

  const handle = new SecretKey(data)

  if (owned) data.fill(0)

  return new CryptoKey(
    'secret',
    extractable,
    {
      name: 'HMAC',
      length,
      hash: {
        name: hash.name.toUpperCase()
      }
    },
    usages,
    handle
  )
}

// https://w3c.github.io/webcrypto/#hmac-operations-export-key
exports.exportKey = function exportKey(format, key) {
  const data = key._handle.export()

  switch (format) {
    case 'raw':
      return data.buffer.slice(0, data.byteLength)
    case 'jwk': {
      const jwk = {
        kty: 'oct',
        k: data.toString('base64url'),
        alg: null,
        key_ops: key.usages,
        ext: key.extractable
      }

      switch (key.algorithm.hash.name) {
        case 'SHA-1':
          jwk.alg = 'HS1'
          break
        case 'SHA-256':
          jwk.alg = 'HS256'
          break
        case 'SHA-384':
          jwk.alg = 'HS384'
          break
        case 'SHA-512':
          jwk.alg = 'HS512'
          break
      }

      return jwk
    }
    default:
      throw errors.NOT_SUPPORTED(
        `Format '${format}' cannot be used for the HMAC exportKey() operation`
      )
  }
}

// https://w3c.github.io/webcrypto/#hmac-operations-get-key-length
exports.getKeyLength = function getKeyLength(algorithm) {
  const { length } = algorithm

  let { hash } = algorithm

  if (hash !== null && typeof hash === 'object') hash = hash.name

  if (length === undefined) {
    if (hash === 'SHA-1' || hash === 'SHA-256') return 512
    if (hash === 'SHA-384' || hash === 'SHA-512') return 1024

    throw errors.OPERATION_ERROR(`Invalid hash '${hash}'`)
  }

  if (length === 0) {
    throw errors.OPERATION_ERROR(`Invalid length ${length}`)
  }

  return length
}
const crypto = require('../../..')
const errors = require('../../errors')
const { SecretKey } = require('../../key')
const CryptoKey = require('../crypto-key')

// https://w3c.github.io/webcrypto/#pbkdf2

// https://w3c.github.io/webcrypto/#pbkdf2-operations-derive-bits
exports.deriveBits = function deriveBits(algorithm, key, length) {
  if (length === undefined || length % 8) {
    throw errors.OPERATION_ERROR('Length must be multiple of 8')
  }

  if (algorithm.iterations === 0) {
    throw errors.OPERATION_ERROR('Iterations must be non-0')
  }

  if (length === 0) {
    return new ArrayBuffer(0)
  }

  let hash = algorithm.hash

  if (typeof hash === 'string') hash = { name: hash }

  const material = key._handle.export()

  const result = crypto.pbkdf2(
    material,
    algorithm.salt,
    algorithm.iterations,
    length / 8,
    hash.name
  )

  return result.buffer
}

// https://w3c.github.io/webcrypto/#pbkdf2-operations-import-key
exports.importKey = function importKey(format, keyData, algorithm, extractable, usages) {
  if (format !== 'raw') {
    throw errors.NOT_SUPPORTED(
      `Format '${format}' cannot be used for the PBKDF2 importKey() operation`
    )
  }

  for (const usage of usages) {
    if (usage !== 'deriveKey' && usage !== 'deriveBits') {
      throw new SyntaxError(`Invalid usage ${usage}`)
    }
  }

  if (extractable) {
    throw new SyntaxError('Extractable must be false')
  }

  return new CryptoKey(
    'secret',
    extractable,
    {
      name: 'PBKDF2'
    },
    usages,
    new SecretKey(keyData)
  )
}
const crypto = require('../../..')

// https://w3c.github.io/webcrypto/#sha

// https://w3c.github.io/webcrypto/#sha-operations-digest
exports.digest = function digest(name, data) {
  const digest = crypto.createHash(name).update(data).digest()

  return digest.buffer.slice(0, digest.byteLength)
}
// https://w3c.github.io/webcrypto/#cryptokey-interface
module.exports = class CryptoKey {
  constructor(type, extractable, algorithm, usages, handle = null) {
    this._type = type
    this._extractable = extractable
    this._algorithm = algorithm
    this._usages = usages
    this._handle = handle
  }

  // https://w3c.github.io/webcrypto/#dom-cryptokey-type
  get type() {
    return this._type
  }

  // https://w3c.github.io/webcrypto/#dom-cryptokey-extractable
  get extractable() {
    return this._extractable
  }

  // https://w3c.github.io/webcrypto/#dom-cryptokey-algorithm
  get algorithm() {
    return this._algorithm
  }

  // https://w3c.github.io/webcrypto/#dom-cryptokey-usages
  get usages() {
    return this._usages
  }

  get destroyed() {
    return this._handle === null
  }

  destroy() {
    if (this._handle === null) return

    this._handle.destroy()

    this._handle = null
  }

  [Symbol.dispose]() {
    this.destroy()
  }

  [Symbol.for('bare.inspect')]() {
    return {
      __proto__: { constructor: CryptoKey },

      type: this.type,
      extractable: this.extractable,
      algorithm: this.algorithm,
      usages: this.usages
    }
  }
}
{
  "name": "bare-crypto",
  "version": "1.15.3",
  "description": "Cryptographic primitives for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./web": {
      "types": "./web.d.ts",
      "default": "./web.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    },
    "./constants": "./lib/constants.js",
    "./errors": "./lib/errors.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "web.js",
    "web.d.ts",
    "global.js",
    "global.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-crypto.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-crypto/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-crypto#readme",
  "dependencies": {
    "bare-assert": "^1.2.0",
    "bare-stream": "^2.6.3"
  },
  "devDependencies": {
    "bare-buffer": "^3.0.1",
    "brittle": "^3.5.0",
    "cmake-bare": "^1.1.6",
    "cmake-fetch": "^1.0.0",
    "lunte": "^1.7.0",
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "bare-buffer": "*"
  },
  "peerDependenciesMeta": {
    "bare-buffer": {
      "optional": true
    }
  }
}
const crypto = require('.')
const errors = require('./lib/errors')
const CryptoKey = require('./lib/web/crypto-key')
const hmac = require('./lib/web/algorithm/hmac')
const pbkdf2 = require('./lib/web/algorithm/pbkdf2')
const ed25519 = require('./lib/web/algorithm/ed25519')
const sha = require('./lib/web/algorithm/sha')

exports.CryptoKey = CryptoKey

// https://w3c.github.io/webcrypto/#Crypto-method-getRandomValues
exports.getRandomValues = function getRandomValues(array) {
  return crypto.randomFillSync(array)
}

// https://w3c.github.io/webcrypto/#dfn-Crypto-method-randomUUID
exports.randomUUID = crypto.randomUUID

// https://w3c.github.io/webcrypto/#subtlecrypto-interface
exports.SubtleCrypto = class SubtleCrypto {
  // https://w3c.github.io/webcrypto/#SubtleCrypto-method-generateKey
  async generateKey(algorithm, extractable, usages) {
    if (typeof algorithm === 'string') algorithm = { name: algorithm }

    switch (algorithm.name.toLowerCase()) {
      case 'hmac':
        return hmac.generateKey(algorithm, extractable, usages)
      case 'ed25519':
        return ed25519.generateKey(algorithm, extractable, usages)
      default:
        throw errors.NOT_SUPPORTED(
          `Algorithm '${algorithm.name}' does not support the generateKey() operation`
        )
    }
  }

  // https://w3c.github.io/webcrypto/#SubtleCrypto-method-importKey
  async importKey(format, keyData, algorithm, extractable, usages) {
    if (typeof algorithm === 'string') algorithm = { name: algorithm }

    switch (format) {
      case 'raw':
      case 'pkcs8':
      case 'spki':
        if (ArrayBuffer.isView(keyData)) {
          keyData = Buffer.from(keyData)
        } else {
          keyData = Buffer.from(keyData.slice())
        }
        break
    }

    switch (algorithm.name.toLowerCase()) {
      case 'hmac':
        return hmac.importKey(format, keyData, algorithm, extractable, usages)
      case 'ed25519':
        return ed25519.importKey(format, keyData, algorithm, extractable, usages)
      case 'pbkdf2':
        return pbkdf2.importKey(format, keyData, algorithm, extractable, usages)
      default:
        throw errors.NOT_SUPPORTED(
          `Algorithm '${algorithm.name}' does not support the importKey() operation`
        )
    }
  }

  // https://w3c.github.io/webcrypto/#SubtleCrypto-method-exportKey
  async exportKey(format, key) {
    if (!key.extractable) {
      throw errors.INVALID_ACCESS('Key is not extractable')
    }

    switch (key.algorithm.name.toLowerCase()) {
      case 'hmac':
        return hmac.exportKey(format, key)
      case 'ed25519':
        return ed25519.exportKey(format, key)
      default:
        throw errors.NOT_SUPPORTED(
          `Algorithm '${key.algorithm.name}' does not support the exportKey() operation`
        )
    }
  }

  // https://w3c.github.io/webcrypto/#SubtleCrypto-method-sign
  async sign(algorithm, key, data) {
    if (typeof algorithm === 'string') algorithm = { name: algorithm }

    if (algorithm.name.toLowerCase() !== key.algorithm.name.toLowerCase()) {
      throw errors.INVALID_ACCESS(`Algorithm '${algorithm.name}' does not match key'`)
    }

    if (!key.usages.includes('sign')) {
      throw errors.INVALID_ACCESS('Key cannot be used for signing')
    }

    switch (algorithm.name.toLowerCase()) {
      case 'hmac':
        return hmac.sign(algorithm, key, data)
      case 'ed25519':
        return ed25519.sign(algorithm, key, data)
      default:
        throw errors.NOT_SUPPORTED(
          `Algorithm '${algorithm.name}' does not support the sign() operation`
        )
    }
  }

  // https://w3c.github.io/webcrypto/#SubtleCrypto-method-verify
  async verify(algorithm, key, signature, data) {
    if (typeof algorithm === 'string') algorithm = { name: algorithm }

    if (algorithm.name.toLowerCase() !== key.algorithm.name.toLowerCase()) {
      throw errors.INVALID_ACCESS(`Algorithm '${algorithm.name}' does not match key'`)
    }

    if (!key.usages.includes('verify')) {
      throw errors.INVALID_ACCESS('Key cannot be used for verification')
    }

    switch (algorithm.name.toLowerCase()) {
      case 'hmac':
        return hmac.verify(algorithm, key, signature, data)
      case 'ed25519':
        return ed25519.verify(algorithm, key, signature, data)
      default:
        throw errors.NOT_SUPPORTED(
          `Algorithm '${algorithm.name}' does not support the verify() operation`
        )
    }
  }

  // https://w3c.github.io/webcrypto/#SubtleCrypto-method-deriveBits
  async deriveBits(algorithm, key, length) {
    if (typeof algorithm === 'string') algorithm = { name: algorithm }

    if (algorithm.name.toLowerCase() !== key.algorithm.name.toLowerCase()) {
      throw errors.INVALID_ACCESS(`Algorithm '${algorithm.name}' does not match key'`)
    }

    if (!key.usages.includes('deriveBits')) {
      throw errors.INVALID_ACCESS('Key cannot be used to derive bits')
    }

    switch (algorithm.name.toLowerCase()) {
      case 'pbkdf2':
        return pbkdf2.deriveBits(algorithm, key, length)
      default:
        throw errors.NOT_SUPPORTED(
          `Algorithm '${algorithm.name}' does not support the deriveBits() operation`
        )
    }
  }

  // https://w3c.github.io/webcrypto/#SubtleCrypto-method-deriveKey
  async deriveKey(algorithm, baseKey, derivedKeyType, extractable, usages) {
    if (typeof algorithm === 'string') algorithm = { name: algorithm }

    if (typeof derivedKeyType === 'string') {
      derivedKeyType = { name: derivedKeyType }
    }

    if (algorithm.name.toLowerCase() !== baseKey.algorithm.name.toLowerCase()) {
      throw errors.INVALID_ACCESS(`Algorithm '${algorithm.name}' does not match key'`)
    }

    if (!baseKey.usages.includes('deriveKey')) {
      throw errors.INVALID_ACCESS('Key cannot be used to derive key')
    }

    let length

    switch (derivedKeyType.name.toLowerCase()) {
      case 'hmac':
        length = hmac.getKeyLength(derivedKeyType)
        break
      default:
        throw errors.NOT_SUPPORTED(
          `Algorithm '${derivedKeyType.name}' does not support the getKeyLength() operation`
        )
    }

    let secret

    switch (algorithm.name.toLowerCase()) {
      case 'pbkdf2':
        secret = pbkdf2.deriveBits(algorithm, baseKey, length)
        break
      default:
        throw errors.NOT_SUPPORTED(
          `Algorithm '${algorithm.name}' does not support the deriveBits() operation`
        )
    }

    return this.importKey('raw', secret, derivedKeyType, extractable, usages)
  }

  // https://w3c.github.io/webcrypto/#SubtleCrypto-method-digest
  async digest(algorithm, data) {
    if (typeof algorithm === 'string') algorithm = { name: algorithm }

    switch (algorithm.name.toLowerCase()) {
      case 'sha-1':
        return sha.digest(crypto.constants.hash.SHA1, data)
      case 'sha-256':
        return sha.digest(crypto.constants.hash.SHA256, data)
      case 'sha-384':
        return sha.digest(crypto.constants.hash.SHA384, data)
      case 'sha-512':
        return sha.digest(crypto.constants.hash.SHA512, data)
      default:
        throw errors.NOT_SUPPORTED(
          `Algorithm '${algorithm.name}' does not support the digest() operation`
        )
    }
  }
}

exports.subtle = new exports.SubtleCrypto()

// https://w3c.github.io/webcrypto/#crypto-interface
exports.Crypto = class Crypto {
  get subtle() {
    return exports.subtle
  }

  getRandomValues(array) {
    return exports.getRandomValues(array)
  }

  randomUUID() {
    return exports.randomUUID()
  }
}
module.exports = require.addon()
const binding = require('./binding')

exports.Resolver = class DNSResolver {
  constructor() {
    this._handle = binding.initResolver()
  }

  resolveTxt(hostname, cb = noop) {
    binding.resolveTxt(this._handle, hostname, cb, this)
  }

  destroy() {
    binding.destroyResolver(this._handle)
    this._handle = null
  }

  static global = new this()
}

function onlookup(err, addresses) {
  const req = this

  if (err) return req.cb(err, null, 0)

  const { address, family } = addresses[0]

  return req.cb(null, address, family)
}

function onlookupall(err, addresses) {
  const req = this

  if (err) return req.cb(err, null)

  return req.cb(null, addresses)
}

exports.lookup = function lookup(hostname, opts = {}, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  let { family = 0, all = false } = opts

  if (typeof family === 'string') {
    switch (family) {
      case 'IPv4':
        family = 4
        break
      case 'IPv6':
        family = 6
        break
      default:
        family = 0
    }
  }

  const req = {
    cb,
    handle: null
  }

  req.handle = binding.lookup(
    hostname,
    family || 0,
    all,
    req,
    all ? onlookupall : onlookup
  )
}

exports.resolveTxt = function resolveTxt(hostname, cb) {
  exports.Resolver.global.resolveTxt(hostname, cb)
}

function noop() {}
{
  "name": "bare-dns",
  "version": "2.1.4",
  "description": "Domain name resolution for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-dns.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-dns/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-dns",
  "engines": {
    "bare": ">=1.7.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "cmake-bare": "^1.1.6",
    "cmake-fetch": "^1.3.0",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
const os = require('bare-os')

module.exports = new Proxy(Object.create(null), {
  ownKeys(target) {
    return os.getEnvKeys()
  },

  get(target, property) {
    if (typeof property !== 'string') return

    return os.getEnv(property)
  },

  has(target, property) {
    if (typeof property !== 'string') return false

    return os.hasEnv(property)
  },

  set(target, property, value) {
    if (typeof property !== 'string') return

    const type = typeof value

    if (type !== 'string' && type !== 'number' && type !== 'boolean') {
      throw new Error('Environment variable must be of type string, number, or boolean')
    }

    value = String(value)

    os.setEnv(property, value)

    return true
  },

  deleteProperty(target, property) {
    if (typeof property !== 'string') return

    os.unsetEnv(property)
  },

  getOwnPropertyDescriptor(target, property) {
    return {
      value: this.get(target, property),
      enumerable: true,
      configurable: true,
      writable: true
    }
  }
})
{
  "name": "bare-env",
  "version": "3.0.1",
  "description": "Environment variable support for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-env.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-env/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-env#readme",
  "dependencies": {
    "bare-os": "^3.0.1"
  },
  "devDependencies": {
    "brittle": "^3.2.1",
    "lunte": "^1.8.3",
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
const errors = require('./lib/errors')

class EventListener {
  constructor() {
    this.list = []
    this.count = 0
  }

  append(ctx, name, fn, once) {
    this.count++
    ctx.emit('newListener', name, fn) // Emit BEFORE adding
    this.list.push([fn, once])
  }

  prepend(ctx, name, fn, once) {
    this.count++
    ctx.emit('newListener', name, fn) // Emit BEFORE adding
    this.list.unshift([fn, once])
  }

  remove(ctx, name, fn) {
    for (let i = 0, n = this.list.length; i < n; i++) {
      const l = this.list[i]

      if (l[0] === fn) {
        this.list.splice(i, 1)

        if (this.count === 1) delete ctx._events[name]

        ctx.emit('removeListener', name, fn) // Emit AFTER removing

        this.count--
        return
      }
    }
  }

  removeAll(ctx, name) {
    const list = [...this.list]
    this.list = []

    if (this.count === list.length) delete ctx._events[name]

    for (let i = list.length - 1; i >= 0; i--) {
      ctx.emit('removeListener', name, list[i][0]) // Emit AFTER removing
    }

    this.count -= list.length
  }

  emit(ctx, name, ...args) {
    const list = [...this.list]

    for (let i = 0, n = list.length; i < n; i++) {
      const l = list[i]

      if (l[1] === true) this.remove(ctx, name, l[0])

      Reflect.apply(l[0], ctx, args)
    }

    return list.length > 0
  }
}

function appendListener(ctx, name, fn, once) {
  if (ctx._events === undefined) ctx._events = Object.create(null)
  const e = ctx._events[name] || (ctx._events[name] = new EventListener())
  e.append(ctx, name, fn, once)
  return ctx
}

function prependListener(ctx, name, fn, once) {
  if (ctx._events === undefined) ctx._events = Object.create(null)
  const e = ctx._events[name] || (ctx._events[name] = new EventListener())
  e.prepend(ctx, name, fn, once)
  return ctx
}

function removeListener(ctx, name, fn) {
  if (ctx._events === undefined) return ctx
  const e = ctx._events[name]
  if (e !== undefined) e.remove(ctx, name, fn)
  return ctx
}

function throwUnhandledError(...args) {
  let err

  if (args.length > 0) err = args[0]

  if (err instanceof Error === false) err = errors.UNHANDLED_ERROR(err)

  if (Error.captureStackTrace) {
    Error.captureStackTrace(err, exports.prototype.emit)
  }

  queueMicrotask(() => {
    throw err
  })
}

module.exports = exports = class EventEmitter {
  constructor() {
    this._events = Object.create(null)
  }

  addListener(name, fn) {
    return appendListener(this, name, fn, false)
  }

  addOnceListener(name, fn) {
    return appendListener(this, name, fn, true)
  }

  prependListener(name, fn) {
    return prependListener(this, name, fn, false)
  }

  prependOnceListener(name, fn) {
    return prependListener(this, name, fn, true)
  }

  removeListener(name, fn) {
    return removeListener(this, name, fn)
  }

  on(name, fn) {
    return appendListener(this, name, fn, false)
  }

  once(name, fn) {
    return appendListener(this, name, fn, true)
  }

  off(name, fn) {
    return removeListener(this, name, fn)
  }

  emit(name, ...args) {
    if (name === 'error' && this._events !== undefined && this._events.error === undefined) {
      throwUnhandledError(...args)
    }

    if (this._events === undefined) return false
    const e = this._events[name]
    return e === undefined ? false : e.emit(this, name, ...args)
  }

  listeners(name) {
    if (this._events === undefined) return []
    const e = this._events[name]
    return e === undefined ? [] : [...e.list]
  }

  rawListeners(name) {
    if (this._events === undefined) return []
    const e = this._events[name]
    return e === undefined ? [] : e.list.map((l) => l[0])
  }

  eventNames() {
    if (this._events === undefined) return []
    return Reflect.ownKeys(this._events)
  }

  listenerCount(name) {
    if (this._events === undefined) return 0
    const e = this._events[name]
    return e === undefined ? 0 : e.list.length
  }

  getMaxListeners() {
    return EventEmitter.defaultMaxListeners
  }

  setMaxListeners(n) {}

  removeAllListeners(name) {
    if (arguments.length === 0) {
      for (const key of Reflect.ownKeys(this._events)) {
        if (key === 'removeListener') continue
        this.removeAllListeners(key)
      }
      this.removeAllListeners('removeListener')
    } else {
      const e = this._events[name]
      if (e !== undefined) e.removeAll(this, name)
    }
    return this
  }
}

exports.EventEmitter = exports

exports.errors = errors

exports.defaultMaxListeners = 10

exports.on = function on(emitter, name, opts = {}) {
  const { signal } = opts

  if (signal && signal.aborted) {
    throw errors.OPERATION_ABORTED(signal.reason)
  }

  let error = null
  let done = false

  const events = []
  const promises = []

  if (name !== 'error') emitter.on('error', onerror)

  if (signal) signal.addEventListener('abort', onabort)

  emitter.on(name, onevent)

  return {
    next() {
      if (events.length) {
        return Promise.resolve({ value: events.shift(), done: false })
      }

      if (error) {
        const err = error

        error = null

        return Promise.reject(err)
      }

      if (done) return onclose()

      return new Promise((resolve, reject) => promises.push({ resolve, reject }))
    },

    return() {
      return onclose()
    },

    throw(err) {
      return onerror(err)
    },

    [Symbol.asyncIterator]() {
      return this
    }
  }

  function onevent(...args) {
    if (promises.length) {
      promises.shift().resolve({ value: args, done: false })
    } else {
      events.push(args)
    }
  }

  function onerror(err) {
    emitter.off(name, onevent).off('error', onerror)

    if (promises.length) {
      promises.shift().reject(err)
    } else {
      error = err
    }

    return Promise.resolve({ done: true })
  }

  function onabort() {
    signal.removeEventListener('abort', onabort)

    onerror(errors.OPERATION_ABORTED(signal.reason))
  }

  function onclose() {
    emitter.off(name, onevent)

    if (name !== 'error') emitter.off('error', onerror)

    if (signal) signal.removeEventListener('abort', onabort)

    done = true

    if (promises.length) promises.shift().resolve({ done: true })

    return Promise.resolve({ done: true })
  }
}

exports.once = function once(emitter, name, opts = {}) {
  const { signal } = opts

  if (signal && signal.aborted) {
    return Promise.reject(errors.OPERATION_ABORTED(signal.reason))
  }

  return new Promise((resolve, reject) => {
    if (name !== 'error') emitter.on('error', onerror)

    if (signal) signal.addEventListener('abort', onabort)

    emitter.once(name, onevent)

    function onevent(...args) {
      if (name !== 'error') emitter.off('error', onerror)

      if (signal) signal.removeEventListener('abort', onabort)

      resolve(args)
    }

    function onerror(err) {
      emitter.off(name, onevent)

      if (name !== 'error') emitter.off('error', onerror)

      reject(err)
    }

    function onabort() {
      signal.removeEventListener('abort', onabort)

      onerror(errors.OPERATION_ABORTED(signal.reason))
    }
  })
}

exports.forward = function forward(from, to, names, opts = {}) {
  if (typeof names === 'string') names = [names]

  const { emit = to.emit.bind(to) } = opts

  const listeners = names.map(
    (name) =>
      function onevent(...args) {
        emit(name, ...args)
      }
  )

  to.on('newListener', (name) => {
    const i = names.indexOf(name)

    if (i !== -1 && to.listenerCount(name) === 0) {
      from.on(name, listeners[i])
    }
  }).on('removeListener', (name) => {
    const i = names.indexOf(name)

    if (i !== -1 && to.listenerCount(name) === 0) {
      from.off(name, listeners[i])
    }
  })
}

exports.listenerCount = function listenerCount(emitter, name) {
  return emitter.listenerCount(name)
}

exports.getMaxListeners = function getMaxListeners(emitter) {
  if (typeof emitter.getMaxListeners === 'function') {
    return emitter.getMaxListeners()
  }

  return exports.defaultMaxListeners
}

exports.setMaxListeners = function setMaxListeners(n, ...emitters) {
  if (emitters.length === 0) exports.defaultMaxListeners = n
  else {
    for (const emitter of emitters) {
      if (typeof emitter.setMaxListeners === 'function') {
        emitter.setMaxListeners(n)
      }
    }
  }
}
module.exports = class EventEmitterError extends Error {
  constructor(msg, code, fn = EventEmitterError, opts) {
    super(`${code}: ${msg}`, opts)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'EventEmitterError'
  }

  static OPERATION_ABORTED(cause, msg = 'Operation aborted') {
    return new EventEmitterError(msg, 'OPERATION_ABORTED', EventEmitterError.OPERATION_ABORTED, {
      cause
    })
  }

  static UNHANDLED_ERROR(cause, msg = 'Unhandled error') {
    return new EventEmitterError(msg, 'UNHANDLED_ERROR', EventEmitterError.UNHANDLED_ERROR, {
      cause
    })
  }
}
{
  "name": "bare-events",
  "version": "2.9.1",
  "description": "Event emitters for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    },
    "./web": {
      "types": "./web.d.ts",
      "default": "./web.js"
    },
    "./errors": "./lib/errors.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "global.js",
    "global.d.ts",
    "web.js",
    "web.d.ts",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:bare && npm run test:node",
    "test:bare": "brittle-bare --coverage test.js",
    "test:node": "brittle-node --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-events.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-events/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-events#readme",
  "devDependencies": {
    "bare-abort-controller": "^1.0.0",
    "brittle": "^3.3.2",
    "lunte": "^1.8.0",
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^2.0.0",
    "uncaughts": "^1.1.1"
  },
  "peerDependencies": {
    "bare-abort-controller": "*"
  },
  "peerDependenciesMeta": {
    "bare-abort-controller": {
      "optional": true
    }
  }
}
const fetch = require('.')

global.fetch = fetch
global.Request = fetch.Request
global.Response = fetch.Response
global.Headers = fetch.Headers
const http = require('bare-http1')
const https = require('bare-https')
const { ReadableStream } = require('bare-stream/web')
const Request = require('./lib/request')
const Response = require('./lib/response')
const ResponseStream = require('./lib/response-stream')
const Headers = require('./lib/headers')
const errors = require('./lib/errors')

// https://fetch.spec.whatwg.org/#dom-global-fetch
module.exports = exports = function fetch(input, init = {}) {
  let resolve
  let reject

  const promise = new Promise((res, rej) => {
    resolve = res
    reject = rej
  })

  const response = new Response()

  process(input)

  return promise

  async function process(input, origin = null) {
    let request
    try {
      request = new Request(input, init)
    } catch (err) {
      return reject(err)
    }

    if (request.signal) {
      if (request.signal.aborted) return abort(reject, request, response)

      request.signal.addEventListener('abort', (event) => abort(reject, request, response))
    }

    if (response._urls.length > 20) {
      return reject(errors.TOO_MANY_REDIRECTS('Redirect count exceeded'))
    }

    if (origin && !isSameOrigin(request._url, origin)) {
      request.headers.delete('authorization')
    }

    let protocol

    if (request._url.protocol === 'http:') {
      protocol = http
    } else if (request._url.protocol === 'https:') {
      protocol = https
    } else {
      return reject(errors.UNKNOWN_PROTOCOL(`Unknown protocol '${request._url.protocol}'`))
    }

    response._urls.push(request._url)

    if (!request._headers.has('user-agent')) {
      request._headers.set('user-agent', `Bare/${Bare.version.substring(1)}`)
    }

    if (!request._headers.has('content-type') && request._type) {
      request._headers.set('content-type', request._type)
    }

    const agent = request._agent || protocol.globalAgent

    while (agent.suspended) await agent.resumed

    const req = protocol.request(
      request._url,
      {
        agent,
        method: request._method,
        headers: Object.fromEntries(request._headers)
      },
      (res) => {
        req.off('close', onclose)

        if (request.signal && request.signal.aborted) {
          res.resume()

          return abort(reject, request, response)
        }

        if (res.headers.location && isRedirectStatus(res.statusCode)) {
          res.resume()

          let url
          try {
            url = new URL(res.headers.location, request._url)
          } catch (err) {
            return reject(errors.INVALID_URL('Invalid URL', err))
          }

          return process(url, request._url)
        }

        response._body = new ReadableStream(new ResponseStream(res))
        response._status = res.statusCode
        response._statusText = res.statusMessage

        for (const [name, value] of Object.entries(res.headers)) {
          response._headers.set(name, value)
        }

        resolve(response)
      }
    )

    req.on('error', onerror).on('close', onclose)

    try {
      if (request._body) {
        for await (const data of request._body) req.write(data)
      }

      req.end()
    } catch (err) {
      req.destroy(err)
    }

    function onerror(err) {
      req.off('close', onclose)

      reject(errors.NETWORK_ERROR('Network error', err))
    }

    function onclose() {
      onerror(http.errors.CONNECTION_LOST())
    }
  }
}

exports.Request = Request
exports.Response = Response
exports.Headers = Headers

// https://fetch.spec.whatwg.org/#redirect-status
function isRedirectStatus(status) {
  return status === 301 || status === 302 || status === 303 || status === 307 || status === 308
}

// https://html.spec.whatwg.org/multipage/browsers.html#same-origin
function isSameOrigin(a, b) {
  return a.protocol === b.protocol && a.host === b.host
}

// https://fetch.spec.whatwg.org/#abort-fetch
function abort(reject, req, res) {
  const { reason } = req.signal

  if (req._body !== null) req._body.cancel(reason)
  if (res._body !== null) res._body.cancel(reason)

  reject(reason)
}
const { ReadableStream, isReadableStream, isReadableStreamDisturbed } = require('bare-stream/web')
const { isURLSearchParams } = require('bare-url')
const { FormData, File, isFormData, isBlob } = require('bare-form-data')
const Headers = require('./headers')
const errors = require('./errors')

const empty = Buffer.from(new ArrayBuffer(0))

// https://fetch.spec.whatwg.org/#body-mixin
module.exports = exports = class Body {
  constructor(body = null, type = null) {
    if (isReadableStream(body)) {
      if (isReadableStreamDisturbed(body) || body.locked) {
        throw errors.BODY_UNUSABLE('Body has already been consumed')
      }
    } else {
      if (typeof body === 'string') body = Buffer.from(body)
      else if (isFormData(body)) body = FormData.toBlob(body)
      else if (isURLSearchParams(body)) {
        body = body.toString()
        type = 'application/x-www-form-urlencoded;charset=UTF-8'
      }

      if (isBlob(body)) {
        type = body.type || null
        body = body.stream()
      } else if (body !== null) {
        if (ArrayBuffer.isView(body)) {
          body = Buffer.from(body.buffer, body.byteOffset, body.byteLength)
        } else {
          body = Buffer.from(body)
        }

        body = new ReadableStream({
          start(controller) {
            controller.enqueue(body)
            controller.close()
          }
        })
      }
    }

    this._type = type
    this._body = body
  }

  // https://fetch.spec.whatwg.org/#dom-body-body
  get body() {
    return this._body
  }

  // https://fetch.spec.whatwg.org/#dom-body-bodyused
  get bodyUsed() {
    return this._body !== null && isReadableStreamDisturbed(this._body)
  }

  async buffer() {
    if (this._body === null) return empty

    if (Body.isUnusable(this)) {
      throw errors.BODY_UNUSABLE('Body has already been consumed')
    }

    const chunks = []
    let length = 0

    for await (const chunk of this._body) {
      chunks.push(chunk)
      length += chunk.byteLength
    }

    const result = Buffer.from(new ArrayBuffer(length))
    let offset = 0

    for (const chunk of chunks) {
      result.set(chunk, offset)
      offset += chunk.byteLength
    }

    return result
  }

  // https://fetch.spec.whatwg.org/#dom-body-bytes
  async bytes() {
    return this.buffer()
  }

  // https://fetch.spec.whatwg.org/#dom-body-arraybuffer
  async arrayBuffer() {
    return (await this.buffer()).buffer
  }

  // https://fetch.spec.whatwg.org/#dom-body-text
  async text() {
    return (await this.buffer()).toString()
  }

  // https://fetch.spec.whatwg.org/#dom-body-json
  async json() {
    return JSON.parse(await this.text())
  }

  // https://fetch.spec.whatwg.org/#dom-body-formdata
  async formData() {
    const mimeType = getMIMEType(this)

    // 1.
    if (mimeType !== null && mimeType.type === 'multipart' && mimeType.subtype === 'form-data') {
      const body = await this.text()
      const boundary = mimeType.parameters.get('boundary')

      if (boundary === undefined) {
        throw errors.INVALID_FORM_DATA('Missing boundary parameter')
      }

      return parseMultipart(body, boundary)
    }

    // 2.
    if (
      mimeType !== null &&
      mimeType.type === 'application' &&
      mimeType.subtype === 'x-www-form-urlencoded'
    ) {
      const body = await this.text()
      const formData = new FormData()

      for (const [name, value] of new URLSearchParams(body)) {
        formData.append(name, value)
      }

      return formData
    }

    // 3.
    throw errors.INVALID_FORM_DATA('Could not parse content as form data')
  }
}

// https://fetch.spec.whatwg.org/#body-unusable
exports.isUnusable = function isUsable(body) {
  return body._body !== null && (isReadableStreamDisturbed(body._body) || body._body.locked)
}

// https://fetch.spec.whatwg.org/#concept-body-clone
exports.clone = function clone(body) {
  if (body._body === null) return null

  const [out1, out2] = body._body.tee()

  body._body = out1

  return out2
}

// https://fetch.spec.whatwg.org/#concept-body-mime-type
function getMIMEType(body) {
  const headers = body._headers

  if (headers === undefined) return null

  return Headers.extractMIMEType(headers)
}

// https://www.rfc-editor.org/rfc/rfc7578
// https://www.rfc-editor.org/rfc/rfc2046#section-5.1
function parseMultipart(input, boundary) {
  const formData = new FormData()

  const delimiter = `\r\n--${boundary}`
  const close = `\r\n--${boundary}--`

  let start = input.indexOf(`--${boundary}`)
  if (start === -1) return formData

  start += `--${boundary}`.length

  while (true) {
    if (input.startsWith('--', start)) break
    if (input.startsWith('\r\n', start)) start += 2

    let end = input.indexOf(delimiter, start)
    if (end === -1) end = input.indexOf(close, start)
    if (end === -1) break

    const part = input.slice(start, end)

    const headerEnd = part.indexOf('\r\n\r\n')
    if (headerEnd === -1) {
      start = end + delimiter.length
      continue
    }

    const headerSection = part.slice(0, headerEnd)
    const body = part.slice(headerEnd + 4)

    const contentDisposition = { name: null, filename: null }
    let contentType = null

    for (const line of headerSection.split('\r\n')) {
      const colon = line.indexOf(':')
      if (colon === -1) continue

      const name = line.slice(0, colon).trim().toLowerCase()
      const value = line.slice(colon + 1).trim()

      if (name === 'content-disposition') {
        contentDisposition.name = getParameter(value, 'name')
        contentDisposition.filename = getParameter(value, 'filename')
      } else if (name === 'content-type') {
        contentType = value
      }
    }

    if (contentDisposition.name === null) {
      start = end + delimiter.length
      continue
    }

    if (contentDisposition.filename !== null) {
      const file = new File([body], contentDisposition.filename, {
        type: contentType || 'application/octet-stream'
      })

      formData.append(contentDisposition.name, file)
    } else {
      formData.append(contentDisposition.name, body)
    }

    start = end + delimiter.length
  }

  return formData
}

function getParameter(header, name) {
  const pattern = new RegExp(`${name}="([^"]*)"|${name}=([^;\\s]*)`, 'i')

  const match = header.match(pattern)
  if (match === null) return null

  return match[1] !== undefined ? match[1] : match[2]
}
module.exports = class FetchError extends Error {
  constructor(msg, fn = FetchError, code = fn.name, opts = {}) {
    if (typeof code === 'object' && code !== null) {
      opts = code
      code = fn.name
    }

    super(`${code}: ${msg}`, opts)

    this.code = code

    if (Error.captureStackTrace) Error.captureStackTrace(this, fn)
  }

  get name() {
    return 'FetchError'
  }

  static INVALID_URL(msg, cause) {
    return new FetchError(msg, FetchError.INVALID_URL, { cause })
  }

  static NETWORK_ERROR(msg, cause) {
    return new FetchError(msg, FetchError.NETWORK_ERROR, { cause })
  }

  static TOO_MANY_REDIRECTS(msg) {
    return new FetchError(msg, FetchError.TOO_MANY_REDIRECTS)
  }

  static UNKNOWN_PROTOCOL(msg) {
    return new FetchError(msg, FetchError.UNKNOWN_PROTOCOL)
  }

  static BODY_UNUSABLE(msg) {
    return new FetchError(msg, FetchError.BODY_UNUSABLE)
  }

  static INVALID_FORM_DATA(msg) {
    return new FetchError(msg, FetchError.INVALID_FORM_DATA)
  }

  static INVALID_HEADER_NAME(msg) {
    return new FetchError(msg, FetchError.INVALID_HEADER_NAME)
  }

  static INVALID_HEADER_VALUE(msg) {
    return new FetchError(msg, FetchError.INVALID_HEADER_VALUE)
  }
}
const MIME = require('bare-mime')

const errors = require('./errors')

const NUL = 0x00
const LF = 0x0a
const CR = 0x0d

// https://www.rfc-editor.org/rfc/rfc9110.html#section-5.6.2
const TOKEN_BYTES = Buffer.from([
  // 0x00-0x1f (control characters) + 0x20 (space)
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  // 0x21-0x41: ! " # $ % & ' ( ) * + , - . / 0-9 : ; < = > ? @ A
  1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1,
  // 0x42-0x62: B-Z [ \ ] ^ _ ` a b
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1,
  // 0x63-0x7f: c-z { | } ~ DEL
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0
])

function isTokenByte(b) {
  return b < TOKEN_BYTES.length && TOKEN_BYTES[b] === 1
}

function isFieldByte(b) {
  return b !== NUL && b !== LF && b !== CR
}

// https://fetch.spec.whatwg.org/#header-name
function validateName(name) {
  if (name.length === 0) {
    throw errors.INVALID_HEADER_NAME(`Header name must not be empty`)
  }

  for (let i = 0, n = name.length; i < n; i++) {
    if (!isTokenByte(name.charCodeAt(i))) {
      throw errors.INVALID_HEADER_NAME(`Invalid header name '${name}'`)
    }
  }
}

// https://fetch.spec.whatwg.org/#header-value
function validateValue(name, value) {
  for (let i = 0, n = value.length; i < n; i++) {
    if (!isFieldByte(value.charCodeAt(i))) {
      throw errors.INVALID_HEADER_VALUE(`Invalid header value for '${name}'`)
    }
  }
}

// https://fetch.spec.whatwg.org/#headers-class
module.exports = exports = class Headers {
  // https://fetch.spec.whatwg.org/#dom-headers
  constructor(init) {
    this._headers = new Map()

    if (init) {
      for (const [key, value] of typeof init[Symbol.iterator] === 'function'
        ? init
        : Object.entries(init)) {
        this.append(key, value)
      }
    }
  }

  // https://fetch.spec.whatwg.org/#dom-headers-append
  append(name, value) {
    value = value.trim()

    validateName(name)
    validateValue(name, value)

    name = name.toLowerCase()

    let list = this._headers.get(name)

    if (list === undefined) {
      list = []
      this._headers.set(name, list)
    }

    list.push(value)
  }

  // https://fetch.spec.whatwg.org/#dom-headers-delete
  delete(name) {
    name = name.toLowerCase()

    this._headers.delete(name)
  }

  // https://fetch.spec.whatwg.org/#dom-headers-get
  get(name) {
    name = name.toLowerCase()

    const list = this._headers.get(name)

    if (list === undefined) return null

    return list.join(', ')
  }

  // https://fetch.spec.whatwg.org/#dom-headers-has
  has(name) {
    name = name.toLowerCase()

    return this._headers.has(name)
  }

  // https://fetch.spec.whatwg.org/#dom-headers-set
  set(name, value) {
    value = value.trim()

    validateName(name)
    validateValue(name, value)

    name = name.toLowerCase()

    this._headers.set(name, [value])
  }

  // https://webidl.spec.whatwg.org/#idl-iterable
  entries() {
    return this[Symbol.iterator]()
  }

  // https://webidl.spec.whatwg.org/#idl-iterable
  *keys() {
    for (const [name] of this) {
      yield name
    }
  }

  // https://webidl.spec.whatwg.org/#idl-iterable
  *values() {
    for (const [, value] of this) {
      yield value
    }
  }

  // https://webidl.spec.whatwg.org/#idl-iterable
  forEach(callback, thisArg) {
    for (const [name, value] of this) {
      callback.call(thisArg, value, name, this)
    }
  }

  *[Symbol.iterator]() {
    const names = [...this._headers.keys()].sort()

    for (const name of names) {
      yield [name, this.get(name)]
    }
  }
}

// https://fetch.spec.whatwg.org/#concept-header-extract-mime-type
exports.extractMIMEType = function extractMIMEType(headers) {
  // 1.
  const contentType = headers.get('content-type')

  // 2.
  if (contentType === null) return null

  // 3.
  const values = getDecodeSplit(contentType)

  // 4.
  let mimeType = null

  // 5.
  for (const value of values) {
    const parsed = MIME.parse(value)

    if (parsed !== null) {
      mimeType = parsed
    }
  }

  // 6.
  return mimeType
}

// https://fetch.spec.whatwg.org/#concept-header-list-get-decode-split
function getDecodeSplit(value) {
  const values = []
  let current = ''
  let position = 0

  while (position < value.length) {
    if (value[position] === '"') {
      current += value[position++]

      while (position < value.length) {
        if (value[position] === '\\' && position + 1 < value.length) {
          current += value[position++]
          current += value[position++]
        } else if (value[position] === '"') {
          current += value[position++]
          break
        } else {
          current += value[position++]
        }
      }
    } else if (value[position] === ',') {
      values.push(current.trim())
      current = ''
      position++
    } else {
      current += value[position++]
    }
  }

  values.push(current.trim())

  return values
}
const { isURL } = require('bare-url')
const Body = require('./body')
const Headers = require('./headers')
const errors = require('./errors')

// https://fetch.spec.whatwg.org/#request-class
module.exports = class Request extends Body {
  // https://fetch.spec.whatwg.org/#dom-request
  constructor(input, init = {}) {
    let url
    try {
      if (isURL(input)) {
        url = input
        input = {}
      } else if (typeof input === 'string') {
        url = new URL(input)
        input = {}
      } else {
        url = new URL(input.url)
      }
    } catch (err) {
      throw errors.INVALID_URL('Invalid URL', err)
    }

    const {
      body = input.body || null,
      method = input.method || 'GET',
      headers = input.headers,
      signal = null,
      agent = input.agent || null
    } = init

    super(body)

    this._url = url
    this._method = /^(delete|get|head|options|post|put)$/i.test(method)
      ? method.toUpperCase()
      : method
    this._headers = new Headers(headers)
    this._signal = signal
    this._agent = agent
  }

  // https://fetch.spec.whatwg.org/#dom-request-url
  get url() {
    return this._url.href
  }

  // https://fetch.spec.whatwg.org/#dom-request-method
  get method() {
    return this._method
  }

  // https://fetch.spec.whatwg.org/#dom-request-headers
  get headers() {
    return this._headers
  }

  // https://fetch.spec.whatwg.org/#dom-request-signal
  get signal() {
    return this._signal
  }

  // https://fetch.spec.whatwg.org/#dom-request-clone
  clone() {
    if (Body.isUnusable(this)) throw errors.BODY_UNUSABLE('Body has already been consumed')

    return new Request(this, { body: Body.clone(this) })
  }
}
const { Readable } = require('bare-stream')
const { Gunzip, Deflate } = require('bare-zlib')

module.exports = class ResponseStream extends Readable {
  constructor(response) {
    super()

    this._response = response
    this._response.socket.unref()

    const encoding = response.headers['content-encoding']

    switch (encoding) {
      case 'gzip':
        this._decoder = new Gunzip()
        break
      case 'deflate':
        this._decoder = new Deflate()
        break
      default:
        this._decoder = null
    }
  }

  _open(cb) {
    if (this._response.socket) this._response.socket.ref()

    const stream = this._decoder ? this._response.pipe(this._decoder) : this._response

    stream
      .on('data', this._ondata.bind(this))
      .on('end', this._onend.bind(this))
      .on('error', this._onerror.bind(this))

    cb(null)
  }

  _read() {
    this._response.resume()
  }

  _predestroy() {
    this._response.destroy()
  }

  _ondata(data) {
    if (this.push(data) === false) {
      this._response.pause()
    }
  }

  _onend() {
    this.push(null)
  }

  _onerror(err) {
    this.destroy(err)
  }
}
const Body = require('./body')
const Headers = require('./headers')
const errors = require('./errors')

// https://fetch.spec.whatwg.org/#response-class
module.exports = class Response extends Body {
  // https://fetch.spec.whatwg.org/#dom-response
  constructor(body = null, init = {}) {
    const { status = 200, statusText = '', headers } = init

    super(body)

    this._urls = []
    this._status = status
    this._statusText = statusText
    this._headers = new Headers(headers)
  }

  // https://fetch.spec.whatwg.org/#dom-response-url
  get url() {
    return this._urls.length === 0 ? null : this._urls[this._urls.length - 1].href
  }

  // https://fetch.spec.whatwg.org/#dom-response-redirected
  get redirected() {
    return this._urls.length > 1
  }

  // https://fetch.spec.whatwg.org/#dom-response-status
  get status() {
    return this._status
  }

  // https://fetch.spec.whatwg.org/#dom-response-ok
  get ok() {
    return this._status >= 200 && this._status <= 299
  }

  // https://fetch.spec.whatwg.org/#dom-response-statustext
  get statusText() {
    return this._statusText
  }

  // https://fetch.spec.whatwg.org/#dom-response-headers
  get headers() {
    return this._headers
  }

  // https://fetch.spec.whatwg.org/#dom-response-clone
  clone() {
    if (Body.isUnusable(this)) throw errors.BODY_UNUSABLE('Body has already been consumed')

    return new Response(Body.clone(this), this)
  }
}
{
  "name": "bare-fetch",
  "version": "3.0.1",
  "description": "WHATWG Fetch implementation for Bare",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    },
    "./errors": {
      "types": "./lib/errors.d.ts",
      "default": "./lib/errors.js"
    },
    "./body": {
      "types": "./lib/body.d.ts",
      "default": "./lib/body.js"
    },
    "./request": {
      "types": "./lib/request.d.ts",
      "default": "./lib/request.js"
    },
    "./response": {
      "types": "./lib/response.d.ts",
      "default": "./lib/response.js"
    },
    "./headers": {
      "types": "./lib/headers.d.ts",
      "default": "./lib/headers.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "global.js",
    "global.d.ts",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-fetch.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-fetch/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-fetch#readme",
  "dependencies": {
    "bare-form-data": "^1.2.0",
    "bare-http1": "^4.5.2",
    "bare-https": "^3.0.0",
    "bare-mime": "^1.0.0",
    "bare-stream": "^2.9.1",
    "bare-url": "^2.4.0",
    "bare-zlib": "^1.3.0"
  },
  "devDependencies": {
    "bare-abort-controller": "^1.0.1",
    "bare-buffer": "^3.0.2",
    "brittle": "^3.3.0",
    "listen-async": "^1.0.0",
    "lunte": "^1.6.0",
    "prettier": "^3.3.3",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "bare-abort-controller": "*",
    "bare-buffer": "*"
  },
  "peerDependenciesMeta": {
    "bare-abort-controller": {
      "optional": true
    },
    "bare-buffer": {
      "optional": true
    }
  }
}
const { ReadableStream } = require('bare-stream/web')
const { isBuffer } = require('bare-buffer')
const errors = require('./lib/errors')

class FormData {
  constructor() {
    this._entries = []
  }

  append(name, value, filename) {
    if (typeof value !== 'string') {
      if (!isFile(value) || filename) {
        value = new File([value], filename || 'blob', { type: value.type })
      }
    }

    this._entries.push([name, value])
  }

  delete(name) {
    this._entries = this._entries.filter((entry) => entry[0] !== name)
  }

  get(name) {
    const entry = this._entries.find((entry) => entry[0] === name)

    return entry ? entry[1] : null
  }

  getAll(name) {
    const entries = []

    for (const entry of this._entries) {
      if (entry[0] === name) entries.push(entry[1])
    }

    return entries
  }

  has(name) {
    return this._entries.findIndex((entry) => entry[0] === name) !== -1
  }

  set(name, value, filename) {
    this.delete(name)
    this.append(name, value, filename)
  }

  [Symbol.iterator]() {
    return this._entries[Symbol.iterator]()
  }

  [Symbol.for('bare.inspect')]() {
    return {
      __proto__: { constructor: FormData },

      entries: this._entries
    }
  }
}

module.exports = exports = FormData

exports.FormData = FormData

function isFormData(value) {
  return value instanceof FormData
}

exports.isFormData = isFormData

class Blob {
  // https://w3c.github.io/FileAPI/#dom-blob-blob
  constructor(parts, options = {}) {
    const { type = '' } = options

    this._bytes = processBlobParts(parts)
    this._type = type
  }

  // https://w3c.github.io/FileAPI/#dfn-size
  get size() {
    return this._bytes.byteLength
  }

  // https://w3c.github.io/FileAPI/#dfn-type
  get type() {
    return this._type
  }

  // https://w3c.github.io/FileAPI/#stream-method-algo
  stream() {
    const bytes = this._bytes

    return new ReadableStream({
      start(controller) {
        controller.enqueue(bytes)
        controller.close()
      }
    })
  }

  async buffer() {
    return Buffer.from(this._bytes)
  }

  // https://w3c.github.io/FileAPI/#bytes-method-algo
  async bytes() {
    return this.buffer()
  }

  // https://w3c.github.io/FileAPI/#arraybuffer-method-algo
  async arrayBuffer() {
    const buffer = new ArrayBuffer(this._bytes.byteLength)
    new Uint8Array(buffer).set(this._bytes)
    return buffer
  }

  // https://w3c.github.io/FileAPI/#text-method-algo
  async text() {
    return this._bytes.toString()
  }

  [Symbol.for('bare.inspect')]() {
    return {
      __proto__: { constructor: Blob },

      size: this.size,
      type: this.type
    }
  }
}

exports.Blob = Blob

function isBlob(value) {
  return value instanceof Blob
}

exports.isBlob = Blob.isBlob = isBlob

class File extends Blob {
  // https://w3c.github.io/FileAPI/#dom-file-file
  constructor(parts, name, options = {}) {
    const { lastModified = Date.now() } = options

    super(parts, options)

    this._name = name
    this._lastModified = lastModified
  }

  // https://w3c.github.io/FileAPI/#dfn-name
  get name() {
    return this._name
  }

  // https://w3c.github.io/FileAPI/#dfn-lastModified
  get lastModified() {
    return this._lastModified
  }

  [Symbol.for('bare.inspect')]() {
    return {
      __proto__: { constructor: File },

      size: this.size,
      type: this.type,
      name: this.name,
      lastModified: this.lastModified
    }
  }
}

exports.File = File

function isFile(value) {
  return value instanceof File
}

exports.isFile = File.isFile = isFile

// https://w3c.github.io/FileAPI/#process-blob-parts
function processBlobParts(parts) {
  const chunks = []

  for (const part of parts) {
    if (typeof part === 'string') {
      const buffer = Buffer.from(part)
      if (parts.length === 1) return buffer
      chunks.push(buffer)
    } else if (isBlob(part)) {
      chunks.push(part._bytes)
    } else if (isBuffer(part)) {
      chunks.push(part)
    } else if (ArrayBuffer.isView(part)) {
      chunks.push(Buffer.from(part.buffer, part.byteOffset, part.byteLength))
    } else {
      chunks.push(Buffer.from(part))
    }
  }

  return Buffer.concat(chunks)
}

function toBlob(formData, mimeType = 'multipart/form-data') {
  switch (mimeType) {
    case 'multipart/form-data':
      return toMultipartBlob(formData)
    default:
      throw errors.INVALID_MIME_TYPE(`Invalid MIME type '${mimeType}'`)
  }
}

exports.toBlob = toBlob

function escape(value) {
  return value.replace(/\n/g, '%0A').replace(/\r/g, '%0D').replace(/"/g, '%22')
}

function normalizeLinefeeds(value) {
  return value.replace(/\r?\n|\r/g, '\r\n')
}

const linefeed = Buffer.from('\r\n')

// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#multipart/form-data-encoding-algorithm
function toMultipartBlob(formData) {
  const boundary = Math.random().toString(16).slice(2, 18).padStart(16, '0')

  const prefix = `--${boundary}\r\nContent-Disposition: form-data`

  const parts = []

  for (const [name, value] of formData) {
    if (typeof value === 'string') {
      const chunk = Buffer.from(
        prefix +
          `; name="${escape(normalizeLinefeeds(name))}"` +
          `\r\n\r\n${normalizeLinefeeds(value)}\r\n`
      )

      parts.push(chunk)
    } else {
      const chunk = Buffer.from(
        prefix +
          `; name="${escape(normalizeLinefeeds(name))}"` +
          `; filename="${escape(value.name)}"` +
          `\r\nContent-Type: ${value.type || 'application/octet-stream'}\r\n\r\n`
      )

      parts.push(chunk, value, linefeed)
    }
  }

  parts.push(Buffer.from(`--${boundary}--\r\n`))

  return new Blob(parts, {
    type: 'multipart/form-data; boundary=' + boundary
  })
}
module.exports = class FormDataError extends Error {
  constructor(msg, code, fn = FormDataError) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'FormDataError'
  }

  static INVALID_MIME_TYPE(msg) {
    return new FormDataError(msg, 'INVALID_MIME_TYPE', FormDataError.INVALID_MIME_TYPE)
  }
}
{
  "name": "bare-form-data",
  "version": "1.2.2",
  "description": "Form data support for Bare",
  "exports": {
    "./package": "./package.json",
    ".": "./index.js",
    "./global": "./global.js",
    "./errors": "./lib/errors.js"
  },
  "files": [
    "index.js",
    "global.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-form-data.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-form-data/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-form-data#readme",
  "dependencies": {
    "bare-buffer": "^3.6.0",
    "bare-stream": "^2.6.5"
  },
  "devDependencies": {
    "brittle": "^3.3.0",
    "lunte": "^1.7.0",
    "prettier": "^3.3.3",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = require.addon()
const FIFO = require('fast-fifo')
const EventEmitter = require('bare-events')
const path = require('bare-path')
const { isURL, fileURLToPath } = require('bare-url')
const { Readable, Writable } = require('bare-stream')
const binding = require('./binding')
const constants = require('./lib/constants')
const FileError = require('./lib/errors')

const isWindows = Bare.platform === 'win32'

exports.constants = constants

class FileRequest {
  static borrow() {
    if (this._free.length > 0) return this._free.pop()
    return new FileRequest()
  }

  static return(req) {
    if (this._free.length < 32) this._free.push(req.reset())
    else req.destroy()
  }

  constructor() {
    this._reset()
    this._handle = binding.requestInit(this, this._onresult)
  }

  get handle() {
    return this._handle
  }

  retain(value) {
    this._retain = value // Tie the lifetime of `value` to the lifetime of `this`
  }

  reset() {
    if (this._handle === null) return this

    binding.requestReset(this._handle)

    this._reset()

    return this
  }

  destroy() {
    if (this._handle === null) return this

    binding.requestDestroy(this._handle)

    this._reset()
    this._handle = null

    return this
  }

  then(resolve, reject) {
    return this._promise.then(resolve, reject)
  }

  return() {
    if (this._handle === null) return this

    FileRequest.return(this)

    return this
  }

  _reset() {
    this._promise = new Promise((resolve, reject) => {
      this._resolve = resolve
      this._reject = reject
    })
    this._retain = null
  }

  _onresult(err, status) {
    if (err) this._reject(err)
    else this._resolve(status)
  }
}

FileRequest._free = []

function ok(result, cb) {
  if (typeof result === 'function') {
    cb = result
    result = undefined
  }

  if (cb) cb(null, result)
  else return result
}

function fail(err, cb) {
  if (cb) cb(err)
  else throw err
}

function done(err, result, cb) {
  if (typeof result === 'function') {
    cb = result
    result = undefined
  }

  if (err) fail(err, cb)
  else return ok(result, cb)
}

async function open(filepath, flags = 'r', mode = 0o666, cb) {
  if (typeof flags === 'function') {
    cb = flags
    flags = 'r'
    mode = 0o666
  } else if (typeof mode === 'function') {
    cb = mode
    mode = 0o666
  }

  if (typeof flags === 'string') flags = toFlags(flags)
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let fd
  let err = null
  try {
    binding.open(req.handle, filepath, flags, mode)

    fd = await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'open',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, fd, cb)
}

function openSync(filepath, flags = 'r', mode = 0o666) {
  if (typeof flags === 'string') flags = toFlags(flags)
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    return binding.openSync(req.handle, filepath, flags, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'open',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function close(fd, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.close(req.handle, fd)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'close', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function closeSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.closeSync(req.handle, fd)
  } catch (e) {
    throw new FileError(e.message, { operation: 'close', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function access(filepath, mode = constants.F_OK, cb) {
  if (typeof mode === 'function') {
    cb = mode
    mode = constants.F_OK
  }

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.access(req.handle, filepath, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'access',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function accessSync(filepath, mode = constants.F_OK) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.accessSync(req.handle, filepath, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'access',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function exists(filepath, cb) {
  let ok = true
  try {
    await access(filepath)
  } catch {
    ok = false
  }

  return done(null, ok, cb)
}

function existsSync(filepath) {
  try {
    accessSync(filepath)
  } catch {
    return false
  }

  return true
}

async function read(fd, buffer, offset = 0, len = buffer.byteLength - offset, pos = -1, cb) {
  if (typeof offset === 'function') {
    cb = offset
    offset = 0
    len = buffer.byteLength
    pos = -1
  } else if (typeof len === 'function') {
    cb = len
    len = buffer.byteLength - offset
    pos = -1
  } else if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.read(req.handle, fd, buffer, offset, len, pos)

    req.retain(buffer)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'read', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function readSync(fd, buffer, offset = 0, len = buffer.byteLength - offset, pos = -1) {
  const req = FileRequest.borrow()

  try {
    return binding.readSync(req.handle, fd, buffer, offset, len, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'read', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function readv(fd, buffers, pos = -1, cb) {
  if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.readv(req.handle, fd, buffers, pos)

    req.retain(buffers)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'readv', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function readvSync(fd, buffers, pos = -1) {
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  try {
    return binding.readvSync(req.handle, fd, buffers, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'readv', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function write(fd, data, offset, len, pos = -1, cb) {
  if (typeof data === 'string') {
    let encoding = len
    cb = pos
    pos = offset

    if (typeof pos === 'function') {
      cb = pos
      pos = -1
      encoding = 'utf8'
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = 'utf8'
    }

    if (typeof pos === 'string') {
      encoding = pos
      pos = -1
    }

    data = Buffer.from(data, encoding)
    offset = 0
    len = data.byteLength
  } else if (typeof offset === 'function') {
    cb = offset
    offset = 0
    len = data.byteLength
    pos = -1
  } else if (typeof len === 'function') {
    cb = len
    len = data.byteLength - offset
    pos = -1
  } else if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof offset !== 'number') offset = 0
  if (typeof len !== 'number') len = data.byteLength - offset
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.write(req.handle, fd, data, offset, len, pos)

    req.retain(data)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'write', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function writeSync(fd, data, offset, len, pos = -1) {
  if (typeof data === 'string') {
    let encoding = len
    pos = offset

    if (typeof pos === 'string') {
      encoding = pos
      pos = -1
    }

    data = Buffer.from(data, encoding)
    offset = 0
    len = data.byteLength
  }

  if (typeof offset !== 'number') offset = 0
  if (typeof len !== 'number') len = data.byteLength - offset
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  try {
    return binding.writeSync(req.handle, fd, data, offset, len, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'write', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function writev(fd, buffers, pos = -1, cb) {
  if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.writev(req.handle, fd, buffers, pos)

    req.retain(buffers)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'writev', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function writevSync(fd, buffers, pos = -1) {
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  try {
    return binding.writevSync(req.handle, fd, buffers, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'writev', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function stat(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.stat(req.handle, filepath)

    await req

    st = new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'stat', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function statSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.statSync(req.handle, filepath)

    return new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'stat', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function lstat(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.lstat(req.handle, filepath)

    await req

    st = new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'lstat', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function lstatSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.lstatSync(req.handle, filepath)

    return new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'lstat', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function fstat(fd, cb) {
  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.fstat(req.handle, fd)

    await req

    st = new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'fstat', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function fstatSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.fstatSync(req.handle, fd)

    return new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'fstat', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function statfs(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.statfs(req.handle, filepath)

    await req

    st = new StatFs(...binding.requestResultStatfs(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'statfs', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function statfsSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.statfsSync(req.handle, filepath)

    return new StatFs(...binding.requestResultStatfs(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'statfs', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function ftruncate(fd, len = 0, cb) {
  if (typeof len === 'function') {
    cb = len
    len = 0
  }

  if (typeof len !== 'number') len = 0

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.ftruncate(req.handle, fd, len)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'ftruncate', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function ftruncateSync(fd, len = 0) {
  if (typeof len !== 'number') len = 0

  const req = FileRequest.borrow()

  try {
    binding.ftruncateSync(req.handle, fd, len)
  } catch (e) {
    throw new FileError(e.message, { operation: 'ftruncate', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function truncate(filepath, len, cb) {
  let fd = -1
  let err

  try {
    fd = await open(filepath, 'r+')

    await ftruncate(fd, len)
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) await close(fd)
  }

  return done(err, cb)
}

function truncateSync(filepath, len) {
  let fd = -1
  let err

  try {
    fd = openSync(filepath, 'r+')

    ftruncateSync(fd, len)
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) closeSync(fd)
  }
}

async function chmod(filepath, mode, cb) {
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.chmod(req.handle, filepath, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'chmod',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function chmodSync(filepath, mode) {
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.chmodSync(req.handle, filepath, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'chmod',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function fchmod(fd, mode, cb) {
  if (typeof mode === 'string') mode = toMode(mode)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fchmod(req.handle, fd, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fchmod', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fchmodSync(fd, mode) {
  if (typeof mode === 'string') mode = toMode(mode)

  const req = FileRequest.borrow()

  try {
    binding.fchmodSync(req.handle, fd, mode)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fchmod', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function chown(filepath, uid, gid, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.chown(req.handle, filepath, uid, gid)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'chown', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function chownSync(filepath, uid, gid) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.chownSync(req.handle, filepath, uid, gid)
  } catch (e) {
    throw new FileError(e.message, { operation: 'chownSync', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function lchown(filepath, uid, gid, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.lchown(req.handle, filepath, uid, gid)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'lchown', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function lchownSync(filepath, uid, gid) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.lchownSync(req.handle, filepath, uid, gid)
  } catch (e) {
    throw new FileError(e.message, { operation: 'lchownSync', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function fchown(fd, uid, gid, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fchown(req.handle, fd, uid, gid)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fchown', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fchownSync(fd, uid, gid) {
  const req = FileRequest.borrow()

  try {
    binding.fchownSync(req.handle, fd, uid, gid)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fchownSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function utimes(filepath, atime, mtime, cb) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.utimes(req.handle, filepath, atime, mtime)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'utimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function utimesSync(filepath, atime, mtime) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.utimesSync(req.handle, filepath, atime, mtime)
  } catch (e) {
    throw new FileError(e.message, { operation: 'utimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function lutimes(filepath, atime, mtime, cb) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.lutimes(req.handle, filepath, atime, mtime)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'lutimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function lutimesSync(filepath, atime, mtime) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.lutimesSync(req.handle, filepath, atime, mtime)
  } catch (e) {
    throw new FileError(e.message, { operation: 'lutimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function futimes(fd, atime, mtime, cb) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.futimes(req.handle, fd, atime, mtime)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'futimes', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function futimesSync(fd, atime, mtime) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  const req = FileRequest.borrow()

  try {
    binding.futimesSync(req.handle, fd, atime, mtime)
  } catch (e) {
    throw new FileError(e.message, { operation: 'futimesSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function link(src, dst, cb) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.link(req.handle, src, dst)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'link', code: e.code, path: src, destination: dst })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function linkSync(src, dst) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  try {
    binding.linkSync(req.handle, src, dst)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'linkSync',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }
}

async function mkdir(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = { mode: 0o777 }
  }

  if (typeof opts === 'number') opts = { mode: opts }
  else if (!opts) opts = {}

  const mode = typeof opts.mode === 'number' ? opts.mode : 0o777

  filepath = toNamespacedPath(filepath)

  if (opts.recursive) {
    let err = null
    try {
      try {
        await mkdir(filepath, { mode })
      } catch (err) {
        if (err.code !== 'ENOENT') {
          if (!(await stat(filepath)).isDirectory()) throw err
        } else {
          while (filepath.endsWith(path.sep)) filepath = filepath.slice(0, -1)
          const i = filepath.lastIndexOf(path.sep)
          if (i <= 0) throw err

          await mkdir(filepath.slice(0, i), { mode, recursive: true })

          try {
            await mkdir(filepath, { mode })
          } catch (err) {
            if (!(await stat(filepath)).isDirectory()) throw err
          }
        }
      }
    } catch (e) {
      err = e
    }

    return done(err, cb)
  }

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.mkdir(req.handle, filepath, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'mkdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function mkdirSync(filepath, opts) {
  if (typeof opts === 'number') opts = { mode: opts }
  else if (!opts) opts = {}

  const mode = typeof opts.mode === 'number' ? opts.mode : 0o777

  filepath = toNamespacedPath(filepath)

  if (opts.recursive) {
    try {
      mkdirSync(filepath, { mode })
    } catch (err) {
      if (err.code !== 'ENOENT') {
        if (!statSync(filepath).isDirectory()) throw err
      } else {
        while (filepath.endsWith(path.sep)) filepath = filepath.slice(0, -1)
        const i = filepath.lastIndexOf(path.sep)
        if (i <= 0) throw err

        mkdirSync(filepath.slice(0, i), { mode, recursive: true })

        try {
          mkdirSync(filepath, { mode })
        } catch (err) {
          if (!statSync(filepath).isDirectory()) throw err
        }
      }
    }

    return
  }

  const req = FileRequest.borrow()

  try {
    binding.mkdirSync(req.handle, filepath, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'mkdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function mkdtemp(prefix, cb) {
  prefix = toNamespacedPath(prefix)

  const req = FileRequest.borrow()

  let res
  let err = null
  try {
    binding.mkdtemp(req.handle, prefix + 'XXXXXX')

    await req

    res = binding.requestResultPath(req.handle)
  } catch (e) {
    err = new FileError(e.message, { operation: 'mkdtemp', code: e.code, path: prefix })
  } finally {
    req.return()
  }

  return done(err, res, cb)
}

function mkdtempSync(prefix) {
  prefix = toNamespacedPath(prefix)

  const req = FileRequest.borrow()

  try {
    binding.mkdtempSync(req.handle, prefix + 'XXXXXX')

    return binding.requestResultPath(req.handle)
  } catch (e) {
    throw new FileError(e.message, { operation: 'mkdtempSync', code: e.code, path: prefix })
  } finally {
    req.return()
  }
}

async function rmdir(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.rmdir(req.handle, filepath)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'rmdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function rmdirSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.rmdirSync(req.handle, filepath)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'rmdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function rm(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  let err = null
  try {
    const st = await lstat(filepath)

    if (st.isDirectory()) {
      if (opts.recursive) {
        try {
          await rmdir(filepath)
        } catch (err) {
          if (err.code !== 'ENOTEMPTY') throw err

          const files = await readdir(filepath)

          for (const file of files) {
            await rm(filepath + path.sep + file, opts)
          }

          await rmdir(filepath)
        }
      } else {
        throw new FileError('is a directory', {
          operation: 'rm',
          code: 'EISDIR',
          path: filepath
        })
      }
    } else {
      await unlink(filepath)
    }
  } catch (e) {
    if (e.code !== 'ENOENT' || !opts.force) err = e
  }

  return done(err, cb)
}

function rmSync(filepath, opts) {
  if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  try {
    const st = lstatSync(filepath)

    if (st.isDirectory()) {
      if (opts.recursive) {
        try {
          rmdirSync(filepath)
        } catch (err) {
          if (err.code !== 'ENOTEMPTY') throw err

          const files = readdirSync(filepath)

          for (const file of files) {
            rmSync(filepath + path.sep + file, opts)
          }

          rmdirSync(filepath)
        }
      } else {
        throw new FileError('is a directory', {
          operation: 'rm',
          code: 'EISDIR',
          path: filepath
        })
      }
    } else {
      unlinkSync(filepath)
    }
  } catch (err) {
    if (err.code !== 'ENOENT' || !opts.force) throw err
  }
}

async function unlink(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.unlink(req.handle, filepath)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'unlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function unlinkSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.unlinkSync(req.handle, filepath)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'unlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function rename(src, dst, cb) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.rename(req.handle, src, dst)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'rename',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function renameSync(src, dst) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  try {
    binding.renameSync(req.handle, src, dst)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'rename',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }
}

async function copyFile(src, dst, mode = 0, cb) {
  if (typeof mode === 'function') {
    cb = mode
    mode = 0
  }

  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.copyfile(req.handle, src, dst, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'copyfile',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function copyFileSync(src, dst, mode = 0) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  try {
    binding.copyfileSync(req.handle, src, dst, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'copyfile',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }
}

async function cp(src, dst, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (!opts) opts = {}

  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  let err = null
  try {
    const st = await lstat(src)

    if (st.isDirectory()) {
      if (opts.recursive !== true) {
        throw new FileError('is a directory', { operation: 'cp', code: 'EISDIR', path: src })
      }

      try {
        await lstat(dst)
      } catch (e) {
        if (e.code !== 'ENOENT') throw e

        await mkdir(dst, { mode: st.mode, recursive: true })
      }

      const dir = await opendir(src)
      for await (const { name } of dir) {
        await cp(path.join(src, name), path.join(dst, name), opts)
      }
    } else if (st.isFile()) {
      await copyFile(src, dst)
      await chmod(dst, st.mode)
    }
  } catch (e) {
    err = e
  }

  return done(err, cb)
}

function cpSync(src, dst, opts = {}) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const st = lstatSync(src)

  if (st.isDirectory()) {
    if (opts.recursive !== true) {
      throw new FileError('is a directory', { operation: 'cp', code: 'EISDIR', path: src })
    }

    try {
      lstatSync(dst)
    } catch (e) {
      if (e.code !== 'ENOENT') throw e

      mkdirSync(dst, { mode: st.mode, recursive: true })
    }

    const dir = opendirSync(src)
    for (const { name } of dir) {
      cpSync(path.join(src, name), path.join(dst, name), opts)
    }
  } else if (st.isFile()) {
    copyFileSync(src, dst)
    chmodSync(dst, st.mode)
  }
}

async function realpath(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let res
  let err = null
  try {
    binding.realpath(req.handle, filepath)

    await req

    res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'realpath',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, res, cb)
}

function realpathSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.realpathSync(req.handle, filepath)

    let res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)

    return res
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'realpath',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function readlink(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let res
  let err = null
  try {
    binding.readlink(req.handle, filepath)

    await req

    res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'readlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, res, cb)
}

function readlinkSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.readlinkSync(req.handle, filepath)

    let res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)

    return res
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'readlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function fsync(fd, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fsync(req.handle, fd)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fsync', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fsyncSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.fsyncSync(req.handle, fd)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fsyncSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function fdatasync(fd, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fdatasync(req.handle, fd)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fdatasync', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fdatasyncSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.fdatasyncSync(req.handle, fd)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fdatasyncSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

function normalizeSymlinkTarget(target, type, filepath) {
  if (isWindows) {
    if (type === constants.UV_FS_SYMLINK_JUNCTION) target = path.resolve(filepath, '..', target)

    if (path.isAbsolute(target)) return path.toNamespacedPath(target)

    return target.replace(/\//g, path.sep)
  }

  return target
}

async function symlink(target, filepath, type, cb) {
  if (typeof type === 'function') {
    cb = type
    type = null
  }

  filepath = toNamespacedPath(filepath)

  if (typeof type === 'string') {
    switch (type) {
      case 'dir':
        type = constants.UV_FS_SYMLINK_DIR
        break
      case 'junction':
        type = constants.UV_FS_SYMLINK_JUNCTION
        break
      case 'file':
      default:
        type = 0
        break
    }
  } else if (typeof type !== 'number') {
    if (isWindows) {
      target = path.resolve(filepath, '..', target)

      try {
        type = (await stat(target)).isDirectory()
          ? constants.UV_FS_SYMLINK_DIR
          : constants.UV_FS_SYMLINK_JUNCTION
      } catch {
        type = 0
      }
    } else {
      type = 0
    }
  }

  target = normalizeSymlinkTarget(target, type, filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.symlink(req.handle, target, filepath, type)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'symlink',
      code: e.code,
      path: target,
      destination: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function symlinkSync(target, filepath, type) {
  filepath = toNamespacedPath(filepath)

  if (typeof type === 'string') {
    switch (type) {
      case 'dir':
        type = constants.UV_FS_SYMLINK_DIR
        break
      case 'junction':
        type = constants.UV_FS_SYMLINK_JUNCTION
        break
      case 'file':
      default:
        type = 0
        break
    }
  } else if (typeof type !== 'number') {
    if (isWindows) {
      target = path.resolve(filepath, '..', target)

      try {
        type = statSync(target).isDirectory()
          ? constants.UV_FS_SYMLINK_DIR
          : constants.UV_FS_SYMLINK_JUNCTION
      } catch {
        type = 0
      }
    } else {
      type = 0
    }
  }

  target = normalizeSymlinkTarget(target, type, filepath)

  const req = FileRequest.borrow()

  try {
    binding.symlinkSync(req.handle, target, filepath, type)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'symlink',
      code: e.code,
      path: target,
      destination: filepath
    })
  } finally {
    req.return()
  }
}

async function opendir(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let dir
  let err = null
  try {
    binding.opendir(req.handle, filepath)

    await req

    dir = new Dir(filepath, binding.requestResultDir(req.handle), opts)
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'opendir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, dir, cb)
}

function opendirSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.opendirSync(req.handle, filepath)

    return new Dir(filepath, binding.requestResultDir(req.handle), opts)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'opendir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function readdir(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { withFileTypes = false, recursive = false } = opts

  filepath = toNamespacedPath(filepath)

  const queue = [filepath]
  let result = []
  let err = null
  try {
    while (queue.length !== 0) {
      const dir = await opendir(queue.pop())

      for await (const entry of dir) {
        const entryPath = path.join(entry.parentPath, entry.name)

        if (withFileTypes) {
          result.push(entry)
        } else {
          result.push(path.relative(filepath, entryPath))
        }

        if (recursive && entry.isDirectory()) queue.push(entryPath)
      }
    }
  } catch (e) {
    result = []
    err = e
  }

  return done(err, result, cb)
}

function readdirSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { withFileTypes = false, recursive = false } = opts

  filepath = toNamespacedPath(filepath)

  const queue = [filepath]
  const result = []

  while (queue.length !== 0) {
    const dir = opendirSync(queue.pop(), opts)

    for (const entry of dir) {
      const entryPath = path.join(entry.parentPath, entry.name)

      if (withFileTypes) {
        result.push(entry)
      } else {
        result.push(path.relative(filepath, entryPath))
      }

      if (recursive && entry.isDirectory()) queue.push(entryPath)
    }
  }

  return result
}

async function readFile(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'buffer' } = opts

  let fd = -1
  let buffer = null
  let err = null
  try {
    fd = await open(filepath, opts.flag || 'r')

    const st = await fstat(fd)

    let len = 0

    if (st.size === 0) {
      const buffers = []

      while (true) {
        buffer = Buffer.allocUnsafe(8192)
        const r = await read(fd, buffer)
        len += r
        if (r === 0) break
        buffers.push(buffer.subarray(0, r))
      }

      buffer = Buffer.concat(buffers)
    } else {
      buffer = Buffer.allocUnsafe(st.size)

      while (true) {
        const r = await read(fd, len ? buffer.subarray(len) : buffer)
        len += r
        if (r === 0 || len === buffer.byteLength) break
      }

      if (len !== buffer.byteLength) buffer = buffer.subarray(0, len)
    }

    if (encoding !== 'buffer') buffer = buffer.toString(encoding)
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) await close(fd)
  }

  return done(err, buffer, cb)
}

function readFileSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'buffer' } = opts

  let fd = -1
  try {
    fd = openSync(filepath, opts.flag || 'r')

    const st = fstatSync(fd)

    let buffer
    let len = 0

    if (st.size === 0) {
      const buffers = []

      while (true) {
        buffer = Buffer.allocUnsafe(8192)
        const r = readSync(fd, buffer)
        len += r
        if (r === 0) break
        buffers.push(buffer.subarray(0, r))
      }

      buffer = Buffer.concat(buffers)
    } else {
      buffer = Buffer.allocUnsafe(st.size)

      while (true) {
        const r = readSync(fd, len ? buffer.subarray(len) : buffer)
        len += r
        if (r === 0 || len === buffer.byteLength) break
      }

      if (len !== buffer.byteLength) buffer = buffer.subarray(0, len)
    }

    if (encoding !== 'buffer') buffer = buffer.toString(encoding)

    return buffer
  } finally {
    if (fd !== -1) closeSync(fd)
  }
}

async function writeFile(filepath, data, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (typeof data === 'string') data = Buffer.from(data, opts.encoding)

  let fd = -1
  let len = 0
  let err = null
  try {
    fd = await open(filepath, opts.flag || 'w', opts.mode || 0o666)

    while (true) {
      len += await write(fd, len ? data.subarray(len) : data)
      if (len === data.byteLength) break
    }
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) await close(fd)
  }

  return done(err, len, cb)
}

function writeFileSync(filepath, data, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (typeof data === 'string') data = Buffer.from(data, opts.encoding)

  let fd = -1
  try {
    fd = openSync(filepath, opts.flag || 'w', opts.mode || 0o666)

    let len = 0

    while (true) {
      len += writeSync(fd, len ? data.subarray(len) : data)
      if (len === data.byteLength) break
    }
  } finally {
    if (fd !== -1) closeSync(fd)
  }
}

function appendFile(filepath, data, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (!opts.flag) opts = { ...opts, flag: 'a' }

  return writeFile(filepath, data, opts, cb)
}

function appendFileSync(filepath, data, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (!opts.flag) opts = { ...opts, flag: 'a' }

  return writeFileSync(filepath, data, opts)
}

function watch(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  return new Watcher(filepath, opts, cb)
}

class Stats {
  constructor(
    dev,
    mode,
    nlink,
    uid,
    gid,
    rdev,
    blksize,
    ino,
    size,
    blocks,
    atimeMs,
    mtimeMs,
    ctimeMs,
    birthtimeMs
  ) {
    this.dev = dev
    this.mode = mode
    this.nlink = nlink
    this.uid = uid
    this.gid = gid
    this.rdev = rdev
    this.blksize = blksize
    this.ino = ino
    this.size = size
    this.blocks = blocks
    this.atimeMs = atimeMs
    this.mtimeMs = mtimeMs
    this.ctimeMs = ctimeMs
    this.birthtimeMs = birthtimeMs
    this.atime = new Date(atimeMs)
    this.mtime = new Date(mtimeMs)
    this.ctime = new Date(ctimeMs)
    this.birthtime = new Date(birthtimeMs)
  }

  isDirectory() {
    return (this.mode & constants.S_IFMT) === constants.S_IFDIR
  }

  isFile() {
    return (this.mode & constants.S_IFMT) === constants.S_IFREG
  }

  isBlockDevice() {
    return (this.mode & constants.S_IFMT) === constants.S_IFBLK
  }

  isCharacterDevice() {
    return (this.mode & constants.S_IFMT) === constants.S_IFCHR
  }

  isFIFO() {
    return (this.mode & constants.S_IFMT) === constants.S_IFIFO
  }

  isSymbolicLink() {
    return (this.mode & constants.S_IFMT) === constants.S_IFLNK
  }

  isSocket() {
    return (this.mode & constants.S_IFMT) === constants.S_IFSOCK
  }
}

class StatFs {
  constructor(type, bsize, blocks, bfree, bavail, files, ffree) {
    this.type = type
    this.bsize = bsize
    this.blocks = blocks
    this.bfree = bfree
    this.bavail = bavail
    this.files = files
    this.ffree = ffree
  }
}

class Dir {
  constructor(path, handle, opts = {}) {
    const { encoding = 'utf8', bufferSize = 32 } = opts

    this.path = path

    this._encoding = encoding
    this._capacity = bufferSize
    this._buffer = new FIFO()
    this._ended = false
    this._handle = handle
  }

  async read(cb) {
    if (this._buffer.length) return ok(this._buffer.shift(), cb)
    if (this._ended) return ok(null, cb)

    const req = FileRequest.borrow()

    let entries
    let err = null
    try {
      req.retain(binding.readdir(req.handle, this._handle, this._capacity))

      await req

      entries = binding.requestResultDirents(req.handle)
    } catch (e) {
      err = new FileError(e.message, {
        operation: 'readdir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    if (err) return fail(err, cb)

    if (entries.length === 0) {
      this._ended = true

      return ok(null, cb)
    }

    for (const entry of entries) {
      let name = Buffer.from(entry.name)

      if (this._encoding !== 'buffer') name = name.toString(this._encoding)

      this._buffer.push(new Dirent(this.path, name, entry.type))
    }

    return ok(this._buffer.shift(), cb)
  }

  readSync() {
    if (this._buffer.length) return this._buffer.shift()
    if (this._ended) return null

    const req = FileRequest.borrow()

    let entries
    try {
      req.retain(binding.readdirSync(req.handle, this._handle, this._capacity))

      entries = binding.requestResultDirents(req.handle)
    } catch (e) {
      throw new FileError(e.message, {
        operation: 'readdir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    if (entries.length === 0) {
      this._ended = true

      return null
    }

    for (const entry of entries) {
      let name = Buffer.from(entry.name)

      if (this._encoding !== 'buffer') name = name.toString(this._encoding)

      this._buffer.push(new Dirent(this.path, name, entry.type))
    }

    return this._buffer.shift()
  }

  async close(cb) {
    const req = FileRequest.borrow()

    let err = null
    try {
      binding.closedir(req.handle, this._handle)

      await req
    } catch (e) {
      err = new FileError(e.message, {
        operation: 'closedir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    this._handle = null

    return done(err, cb)
  }

  closeSync() {
    const req = FileRequest.borrow()

    try {
      binding.closedirSync(req.handle, this._handle)
    } catch (e) {
      throw new FileError(e.message, {
        operation: 'closedir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    this._handle = null
  }

  [Symbol.dispose]() {
    this.closeSync()
  }

  async [Symbol.asyncDispose]() {
    await this.close()
  }

  *[Symbol.iterator]() {
    while (true) {
      const entry = this.readSync()
      if (entry === null) break
      yield entry
    }

    this.closeSync()
  }

  async *[Symbol.asyncIterator]() {
    while (true) {
      const entry = await this.read()
      if (entry === null) break
      yield entry
    }

    await this.close()
  }
}

class Dirent {
  constructor(parentPath, name, type) {
    this.parentPath = parentPath
    this.name = name
    this.type = type
  }

  isFile() {
    return this.type === constants.UV_DIRENT_FILE
  }

  isDirectory() {
    return this.type === constants.UV_DIRENT_DIR
  }

  isSymbolicLink() {
    return this.type === constants.UV_DIRENT_LINK
  }

  isFIFO() {
    return this.type === constants.UV_DIRENT_FIFO
  }

  isSocket() {
    return this.type === constants.UV_DIRENT_SOCKET
  }

  isCharacterDevice() {
    return this.type === constants.UV_DIRENT_CHAR
  }

  isBlockDevice() {
    return this.type === constants.UV_DIRENT_BLOCK
  }
}

class FileReadStream extends Readable {
  constructor(path, opts = {}) {
    const { eagerOpen = true } = opts

    super({ eagerOpen, ...opts })

    this.path = path
    this.fd = typeof opts.fd === 'number' ? opts.fd : -1
    this.flags = opts.flags || 'r'
    this.mode = opts.mode || 0o666

    this._offset = opts.start || 0
    this._missing = 0

    if (opts.length) {
      this._missing = opts.length
    } else if (typeof opts.end === 'number') {
      this._missing = opts.end - this._offset + 1
    } else {
      this._missing = -1
    }
  }

  async _open(cb) {
    let err

    if (this.fd === -1) {
      err = null
      try {
        this.fd = await open(this.path, this.flags, this.mode)
      } catch (e) {
        err = e
      }

      if (err) return cb(err)
    }

    let st
    err = null
    try {
      st = await fstat(this.fd)
    } catch (e) {
      err = e
    }

    if (err) return cb(err)

    if (this._missing === -1) this._missing = st.size

    if (st.size < this._offset) {
      this._offset = st.size
      this._missing = 0
    } else if (st.size < this._offset + this._missing) {
      this._missing = st.size - this._offset
    }

    cb(null)
  }

  async _read(size) {
    if (this._missing <= 0) return this.push(null)

    const data = Buffer.allocUnsafe(Math.min(this._missing, size))

    let len
    let err = null
    try {
      len = await read(this.fd, data, 0, data.byteLength, this._offset)
    } catch (e) {
      err = e
    }

    if (err) return this.destroy(err)

    if (len === 0) return this.push(null)

    if (this._missing < len) len = this._missing

    this._missing -= len
    this._offset += len

    this.push(data.subarray(0, len))
  }

  async _destroy(err, cb) {
    if (this.fd === -1) return cb(err)

    try {
      await close(this.fd)
    } catch (e) {
      err = err || e
    }

    cb(err)
  }
}

class FileWriteStream extends Writable {
  constructor(path, opts = {}) {
    const { eagerOpen = true } = opts

    super({ eagerOpen, ...opts })

    this.path = path
    this.fd = typeof opts.fd === 'number' ? opts.fd : -1
    this.flags = opts.flags || 'w'
    this.mode = opts.mode || 0o666
  }

  async _open(cb) {
    if (this.fd !== -1) return cb(null)

    let err = null
    try {
      this.fd = await open(this.path, this.flags, this.mode)
    } catch (e) {
      err = e
    }

    cb(err)
  }

  async _writev(batch, cb) {
    let err = null
    try {
      await writev(
        this.fd,
        batch.map(({ chunk }) => chunk)
      )
    } catch (e) {
      err = e
    }

    cb(err)
  }

  async _destroy(err, cb) {
    if (this.fd === -1) return cb(err)

    try {
      await close(this.fd)
    } catch (e) {
      err = err || e
    }

    cb(err)
  }
}

class Watcher extends EventEmitter {
  constructor(path, opts, onchange) {
    if (typeof opts === 'function') {
      onchange = opts
      opts = {}
    }

    if (!opts) opts = {}

    const { persistent = true, recursive = false, encoding = 'utf8' } = opts

    super()

    this._closed = false
    this._encoding = encoding
    this._handle = binding.watcherInit(path, recursive, this, this._onevent, this._onclose)

    if (!persistent) this.unref()

    if (onchange) this.on('change', onchange)
  }

  close() {
    if (this._closed) return
    this._closed = true

    binding.watcherClose(this._handle)
  }

  ref() {
    if (this._handle) binding.watcherRef(this._handle)
    return this
  }

  unref() {
    if (this._handle) binding.watcherUnref(this._handle)
    return this
  }

  [Symbol.asyncIterator]() {
    const buffer = []
    let done = false
    let error = null
    let next = null

    this.on('change', (eventType, filename) => {
      if (next) {
        next.resolve({ done: false, value: { eventType, filename } })
        next = null
      } else {
        buffer.push({ eventType, filename })
      }
    })
      .on('error', (err) => {
        done = true
        error = err

        if (next) {
          next.reject(error)
          next = null
        }
      })
      .on('close', () => {
        done = true

        if (next) {
          next.resolve({ done })
          next = null
        }
      })

    return {
      next: () =>
        new Promise((resolve, reject) => {
          if (error) return reject(error)

          if (buffer.length) return resolve({ done: false, value: buffer.shift() })

          if (done) return resolve({ done })

          next = { resolve, reject }
        })
    }
  }

  _onevent(err, events, filename) {
    if (err) {
      this.close()
      this.emit('error', err)
    } else {
      const path =
        this._encoding === 'buffer'
          ? Buffer.from(filename)
          : Buffer.from(filename).toString(this._encoding)

      if (events & binding.UV_RENAME) {
        this.emit('change', 'rename', path)
      }

      if (events & binding.UV_CHANGE) {
        this.emit('change', 'change', path)
      }
    }
  }

  _onclose() {
    this._handle = null

    this.emit('close')
  }
}

exports.access = access
exports.appendFile = appendFile
exports.chmod = chmod
exports.chown = chown
exports.close = close
exports.copyFile = copyFile
exports.cp = cp
exports.exists = exists
exports.fchmod = fchmod
exports.fchown = fchown
exports.fdatasync = fdatasync
exports.fstat = fstat
exports.fsync = fsync
exports.ftruncate = ftruncate
exports.futimes = futimes
exports.lchown = lchown
exports.lutimes = lutimes
exports.link = link
exports.lstat = lstat
exports.mkdir = mkdir
exports.mkdtemp = mkdtemp
exports.open = open
exports.opendir = opendir
exports.read = read
exports.readFile = readFile
exports.readdir = readdir
exports.readlink = readlink
exports.readv = readv
exports.realpath = realpath
exports.rename = rename
exports.rm = rm
exports.rmdir = rmdir
exports.stat = stat
exports.statfs = statfs
exports.symlink = symlink
exports.truncate = truncate
exports.unlink = unlink
exports.utimes = utimes
exports.watch = watch
exports.write = write
exports.writeFile = writeFile
exports.writev = writev

exports.accessSync = accessSync
exports.appendFileSync = appendFileSync
exports.chmodSync = chmodSync
exports.chownSync = chownSync
exports.closeSync = closeSync
exports.copyFileSync = copyFileSync
exports.cpSync = cpSync
exports.existsSync = existsSync
exports.fchmodSync = fchmodSync
exports.fchownSync = fchownSync
exports.fdatasyncSync = fdatasyncSync
exports.fstatSync = fstatSync
exports.fsyncSync = fsyncSync
exports.ftruncateSync = ftruncateSync
exports.futimesSync = futimesSync
exports.lchownSync = lchownSync
exports.lutimesSync = lutimesSync
exports.linkSync = linkSync
exports.lstatSync = lstatSync
exports.mkdirSync = mkdirSync
exports.mkdtempSync = mkdtempSync
exports.openSync = openSync
exports.opendirSync = opendirSync
exports.readFileSync = readFileSync
exports.readSync = readSync
exports.readdirSync = readdirSync
exports.readlinkSync = readlinkSync
exports.readvSync = readvSync
exports.realpathSync = realpathSync
exports.renameSync = renameSync
exports.rmSync = rmSync
exports.rmdirSync = rmdirSync
exports.statSync = statSync
exports.statfsSync = statfsSync
exports.symlinkSync = symlinkSync
exports.truncateSync = truncateSync
exports.unlinkSync = unlinkSync
exports.utimesSync = utimesSync
exports.writeFileSync = writeFileSync
exports.writeSync = writeSync
exports.writevSync = writevSync

exports.promises = require('./promises')

exports.Stats = Stats
exports.StatFs = StatFs
exports.Dir = Dir
exports.Dirent = Dirent
exports.Watcher = Watcher

exports.ReadStream = FileReadStream

exports.createReadStream = function createReadStream(path, opts) {
  return new FileReadStream(path, opts)
}

exports.WriteStream = FileWriteStream

exports.createWriteStream = function createWriteStream(path, opts) {
  return new FileWriteStream(path, opts)
}

function toNamespacedPath(filepath) {
  if (typeof filepath !== 'string') {
    if (isURL(filepath)) filepath = fileURLToPath(filepath)
    else filepath = filepath.toString()
  }

  return path.toNamespacedPath(filepath)
}

function toFlags(flags) {
  switch (flags) {
    case 'r':
      return constants.O_RDONLY
    case 'rs': // Fall through.
    case 'sr':
      return constants.O_RDONLY | constants.O_SYNC
    case 'r+':
      return constants.O_RDWR
    case 'rs+': // Fall through.
    case 'sr+':
      return constants.O_RDWR | constants.O_SYNC

    case 'w':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_WRONLY
    case 'wx': // Fall through.
    case 'xw':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_WRONLY | constants.O_EXCL

    case 'w+':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_RDWR
    case 'wx+': // Fall through.
    case 'xw+':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_RDWR | constants.O_EXCL

    case 'a':
      return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY
    case 'ax': // Fall through.
    case 'xa':
      return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY | constants.O_EXCL
    case 'as': // Fall through.
    case 'sa':
      return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY | constants.O_SYNC

    case 'a+':
      return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR
    case 'ax+': // Fall through.
    case 'xa+':
      return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR | constants.O_EXCL
    case 'as+': // Fall through.
    case 'sa+':
      return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR | constants.O_SYNC
    default:
      return 0
  }
}

function toMode(mode) {
  return parseInt(mode, 8)
}
const binding = require('../binding')

module.exports = {
  O_RDWR: binding.O_RDWR,
  O_RDONLY: binding.O_RDONLY,
  O_WRONLY: binding.O_WRONLY,
  O_CREAT: binding.O_CREAT,
  O_TRUNC: binding.O_TRUNC,
  O_APPEND: binding.O_APPEND,

  F_OK: binding.F_OK || 0,
  R_OK: binding.R_OK || 0,
  W_OK: binding.W_OK || 0,
  X_OK: binding.X_OK || 0,

  S_IFMT: binding.S_IFMT,
  S_IFREG: binding.S_IFREG,
  S_IFDIR: binding.S_IFDIR,
  S_IFCHR: binding.S_IFCHR,
  S_IFLNK: binding.S_IFLNK,
  S_IFBLK: binding.S_IFBLK || 0,
  S_IFIFO: binding.S_IFIFO || 0,
  S_IFSOCK: binding.S_IFSOCK || 0,

  S_IRUSR: binding.S_IRUSR || 0,
  S_IWUSR: binding.S_IWUSR || 0,
  S_IXUSR: binding.S_IXUSR || 0,
  S_IRGRP: binding.S_IRGRP || 0,
  S_IWGRP: binding.S_IWGRP || 0,
  S_IXGRP: binding.S_IXGRP || 0,
  S_IROTH: binding.S_IROTH || 0,
  S_IWOTH: binding.S_IWOTH || 0,
  S_IXOTH: binding.S_IXOTH || 0,

  UV_DIRENT_UNKNOWN: binding.UV_DIRENT_UNKNOWN,
  UV_DIRENT_FILE: binding.UV_DIRENT_FILE,
  UV_DIRENT_DIR: binding.UV_DIRENT_DIR,
  UV_DIRENT_LINK: binding.UV_DIRENT_LINK,
  UV_DIRENT_FIFO: binding.UV_DIRENT_FIFO,
  UV_DIRENT_SOCKET: binding.UV_DIRENT_SOCKET,
  UV_DIRENT_CHAR: binding.UV_DIRENT_CHAR,
  UV_DIRENT_BLOCK: binding.UV_DIRENT_BLOCK,

  COPYFILE_EXCL: binding.UV_FS_COPYFILE_EXCL,
  COPYFILE_FICLONE: binding.UV_FS_COPYFILE_FICLONE,
  COPYFILE_FICLONE_FORCE: binding.UV_FS_COPYFILE_FICLONE_FORCE,
  UV_FS_SYMLINK_DIR: binding.UV_FS_SYMLINK_DIR,
  UV_FS_SYMLINK_JUNCTION: binding.UV_FS_SYMLINK_JUNCTION
}
const binding = require('../binding')

module.exports = class FileError extends Error {
  constructor(msg, opts = {}) {
    const { code, operation = null, path = null, destination = null, fd = -1 } = opts

    if (operation !== null) msg += describe(operation, opts)

    super(`${code}: ${msg}`)

    this.code = code

    if (operation !== null) this.operation = operation
    if (path !== null) this.path = path
    if (destination !== null) this.destination = destination
    if (fd !== -1) this.fd = fd
  }

  get name() {
    return 'FileError'
  }

  // For Node.js compatibility
  get errno() {
    return binding.errnos[this.code]
  }

  // For Node.js compatibility
  get syscall() {
    return this.operation
  }

  // For Node.js compatibility
  get dest() {
    return this.destination
  }
}

function describe(operation, opts) {
  const { path = null, destination = null, fd = -1 } = opts

  let result = `, ${operation}`

  if (path !== null) {
    result += ` ${JSON.stringify(path)}`

    if (destination !== null) {
      result += ` -> ${JSON.stringify(destination)}`
    }
  } else if (fd !== -1) {
    result += ` ${fd}`
  }

  return result
}
{
  "name": "bare-fs",
  "version": "4.7.4",
  "description": "Native file system operations for Bare",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./promises": {
      "types": "./promises.d.ts",
      "default": "./promises.js"
    },
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "promises.js",
    "promises.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-fs.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-fs/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-fs#readme",
  "engines": {
    "bare": ">=1.16.0"
  },
  "dependencies": {
    "bare-events": "^2.5.4",
    "bare-path": "^3.0.0",
    "bare-stream": "^2.6.4",
    "bare-url": "^2.2.2",
    "fast-fifo": "^1.3.2"
  },
  "devDependencies": {
    "bare-buffer": "^3.0.2",
    "bare-crypto": "^1.11.2",
    "brittle": "^3.1.1",
    "cmake-bare": "^1.1.7",
    "lunte": "^1.6.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "bare-buffer": "*"
  },
  "peerDependenciesMeta": {
    "bare-buffer": {
      "optional": true
    }
  }
}
const EventEmitter = require('bare-events')
const fs = require('.')

class FileHandle extends EventEmitter {
  constructor(fd) {
    super()

    this.fd = fd
  }

  async close() {
    await fs.close(this.fd)

    this.fd = -1
    this.emit('close')
  }

  async read(buffer, ...args) {
    return {
      bytesRead: await fs.read(this.fd, buffer, ...args),
      buffer
    }
  }

  async readv(buffers, ...args) {
    return {
      bytesRead: await fs.readv(this.fd, buffers, ...args),
      buffers
    }
  }

  async write(buffer, ...args) {
    return {
      bytesWritten: await fs.write(this.fd, buffer, ...args),
      buffer
    }
  }

  async writev(buffers, ...args) {
    return {
      bytesWritten: await fs.writev(this.fd, buffers, ...args),
      buffers
    }
  }

  async stat() {
    return fs.fstat(this.fd)
  }

  async chmod(mode) {
    await fs.fchmod(this.fd, mode)
  }

  async chown(uid, gid) {
    await fs.fchown(this.fd, uid, gid)
  }

  async datasync() {
    return fs.fdatasync(this.fd)
  }

  async sync() {
    return fs.fsync(this.fd)
  }

  async truncate(len) {
    await fs.ftruncate(this.fd, len)
  }

  async utimes(atime, mtime) {
    await fs.futimes(this.fd, atime, mtime)
  }

  createReadStream(opts) {
    return fs.createReadStream(null, { ...opts, fd: this.fd })
  }

  createWriteStream(opts) {
    return fs.createWriteStream(null, { ...opts, fd: this.fd })
  }

  async [Symbol.asyncDispose]() {
    await this.close()
  }
}

exports.open = async function open(filepath, flags, mode) {
  return new FileHandle(await fs.open(filepath, flags, mode))
}

exports.access = fs.access
exports.appendFile = fs.appendFile
exports.chmod = fs.chmod
exports.chown = fs.chown
exports.constants = fs.constants
exports.copyFile = fs.copyFile
exports.cp = fs.cp
exports.lchown = fs.lchown
exports.lutimes = fs.lutimes
exports.link = fs.link
exports.lstat = fs.lstat
exports.mkdir = fs.mkdir
exports.mkdtemp = fs.mkdtemp
exports.opendir = fs.opendir
exports.readFile = fs.readFile
exports.readdir = fs.readdir
exports.readlink = fs.readlink
exports.realpath = fs.realpath
exports.rename = fs.rename
exports.rm = fs.rm
exports.rmdir = fs.rmdir
exports.stat = fs.stat
exports.statfs = fs.statfs
exports.truncate = fs.truncate
exports.symlink = fs.symlink
exports.unlink = fs.unlink
exports.utimes = fs.utimes
exports.watch = fs.watch
exports.writeFile = fs.writeFile
module.exports = require.addon()
const binding = require('./binding')

module.exports = exports = function hrtime(past) {
  let now = binding.hrtime()

  if (past) now -= BigInt(past[0]) * 1000000000n + BigInt(past[1])

  return [Number(now / 1000000000n), Number(now % 1000000000n)]
}

exports.bigint = function hrtime() {
  return binding.hrtime()
}
{
  "name": "bare-hrtime",
  "version": "2.1.1",
  "description": "High-resolution timers for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-hrtime.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-hrtime/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-hrtime#readme",
  "devDependencies": {
    "brittle": "^3.2.1",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  }
}
const errors = require('./lib/errors')

const constants = {
  REQUEST: 1,
  RESPONSE: 2,
  DATA: 3,
  END: 4
}

const TAB = 0x09
const LF = 0x0a
const CR = 0x0d
const SP = 0x20
const ZERO = 0x30
const NINE = 0x39
const UPPER_A = 0x41
const UPPER_F = 0x46
const UPPER_Z = 0x5a
const LOWER_A = 0x61
const LOWER_F = 0x66
const COLON = 0x3a

const MAX_CHUNK_SIZE_LENGTH = 16

// Header states
const FIRST_TOKEN = 0
const REQUEST_URL = 1
const REQUEST_VERSION = 2
const STATUS_CODE = 3
const STATUS_REASON = 4
const FIRST_LINE_LF = 5
const HEADER_START = 6
const HEADER_NAME = 7
const HEADER_VALUE_WS = 8
const HEADER_VALUE = 9
const HEADER_LINE_LF = 10
const HEADER_END_LF = 11

// Body states
const BODY = 12
const CHUNK_SIZE = 13
const CHUNK_SIZE_LF = 14
const CHUNK_DATA = 15
const CHUNK_EXTENSION = 16

// Trailing states
const LAST_CHUNK_LF = 17
const TRAILER_CR = 18
const TRAILER_LF = 19

module.exports = exports = class HTTPParser {
  constructor(opts = {}) {
    const { maxHeaderSize = 16384, maxHeadersCount = 2000 } = opts

    this._maxHeaderSize = maxHeaderSize
    this._maxHeadersCount = maxHeadersCount
    this._state = FIRST_TOKEN
    this._buffer = []
    this._bufferIndex = 0
    this._byteIndex = 0
    this._buffered = 0
    this._accumulator = []

    this._isResponse = false
    this._method = ''
    this._url = ''
    this._version = ''
    this._code = 0
    this._reason = ''

    this._headerName = ''
    this._headers = Object.create(null)
    this._headerCount = 0
    this._headerSize = 0

    this._remaining = 0
  }

  *push(data, encoding) {
    if (typeof data === 'string') data = Buffer.from(data, encoding)

    this._buffer.push(data)
    this._buffered += data.byteLength

    yield* this._parse()

    this._compact()
  }

  end() {
    const buffers = this._buffer
    const bufferIndex = this._bufferIndex
    const byteIndex = this._byteIndex

    this._buffer = []
    this._bufferIndex = 0
    this._byteIndex = 0
    this._buffered = 0

    if (bufferIndex >= buffers.length) return Buffer.alloc(0)

    buffers[bufferIndex] = buffers[bufferIndex].subarray(byteIndex)

    const remaining = buffers.slice(bufferIndex)

    if (remaining.length === 0) return Buffer.alloc(0)
    if (remaining.length === 1) return remaining[0]

    return Buffer.concat(remaining)
  }

  _compact() {
    if (this._bufferIndex > 0) {
      this._buffer = this._buffer.slice(this._bufferIndex)
      this._bufferIndex = 0
    }

    if (this._byteIndex > 0 && this._buffer.length > 0) {
      this._buffer[0] = this._buffer[0].subarray(this._byteIndex)
      this._byteIndex = 0
    }
  }

  _consume(n) {
    this._buffered -= n

    const current = this._buffer[this._bufferIndex]

    if (this._byteIndex + n <= current.byteLength) {
      const slice = current.subarray(this._byteIndex, this._byteIndex + n)

      this._byteIndex += n

      if (this._byteIndex >= current.byteLength) {
        this._bufferIndex++
        this._byteIndex = 0
      }

      return slice
    }

    const result = Buffer.allocUnsafe(n)

    let written = 0

    while (written < n) {
      const buffer = this._buffer[this._bufferIndex]
      const available = buffer.byteLength - this._byteIndex
      const take = Math.min(available, n - written)

      buffer.copy(result, written, this._byteIndex, this._byteIndex + take)

      written += take

      this._byteIndex += take

      if (this._byteIndex >= buffer.byteLength) {
        this._bufferIndex++
        this._byteIndex = 0
      }
    }

    return result
  }

  _buildString() {
    const string = String.fromCharCode.apply(null, this._accumulator)

    this._accumulator = []

    return string
  }

  _checkHeaderSize() {
    if (++this._headerSize > this._maxHeaderSize) {
      throw errors.INVALID_MESSAGE('Header exceeds limit of ' + this._maxHeaderSize + ' bytes')
    }
  }

  _storeHeader(name, value) {
    let end = value.length

    while (end > 0 && (value.charCodeAt(end - 1) === SP || value.charCodeAt(end - 1) === TAB)) {
      end--
    }

    if (end < value.length) value = value.substring(0, end)

    this._headerCount++

    if (this._headerCount > this._maxHeadersCount) {
      throw errors.INVALID_MESSAGE('Header count exceeds limit of ' + this._maxHeadersCount)
    }

    switch (name) {
      case '__proto__':
      case 'constructor':
      case 'prototype':
        throw errors.INVALID_HEADER("Unsafe header name '" + name + "'")

      case 'host':
      case 'content-length':
      case 'transfer-encoding':
        if (name in this._headers) {
          throw errors.INVALID_HEADER("Duplicate header '" + name + "'")
        }

        this._headers[name] = value
        break

      default: {
        const delimiter = name === 'cookie' ? '; ' : ', '

        if (name in this._headers) {
          this._headers[name] += delimiter + value
        } else {
          this._headers[name] = value
        }
      }
    }
  }

  *_parse() {
    while (true) {
      if (this._state === BODY) {
        if (this._buffered === 0) return

        const available = Math.min(this._buffered, this._remaining)
        const data = this._consume(available)

        this._remaining -= available

        const ended = this._remaining === 0

        if (ended) this._state = FIRST_TOKEN

        yield { type: constants.DATA, data }

        if (ended) yield { type: constants.END }

        continue
      }

      if (this._state === CHUNK_DATA) {
        if (this._buffered < this._remaining) return

        const consumed = this._consume(this._remaining)

        if (consumed[this._remaining - 2] !== CR || consumed[this._remaining - 1] !== LF) {
          throw errors.INVALID_MESSAGE('Expected CRLF after chunk data')
        }

        const data = consumed.subarray(0, this._remaining - 2)

        this._remaining = 0
        this._state = CHUNK_SIZE

        yield { type: constants.DATA, data }

        continue
      }

      if (this._buffered === 0) return

      const byte = this._buffer[this._bufferIndex][this._byteIndex++]

      this._buffered--

      if (this._byteIndex >= this._buffer[this._bufferIndex].byteLength) {
        this._bufferIndex++
        this._byteIndex = 0
      }

      switch (this._state) {
        case FIRST_TOKEN: {
          this._checkHeaderSize()

          if (byte === SP) {
            const token = this._buildString()

            if (token.length === 0) throw errors.INVALID_MESSAGE()

            this._isResponse = token.startsWith('HTTP/')

            if (this._isResponse) {
              if (token !== 'HTTP/1.0' && token !== 'HTTP/1.1') {
                throw errors.INVALID_MESSAGE()
              }

              this._version = token
              this._state = STATUS_CODE
            } else {
              this._method = token
              this._state = REQUEST_URL
            }
          } else if (byte === CR) {
            throw errors.INVALID_MESSAGE()
          } else if (isTokenByte(byte)) {
            this._accumulator.push(byte)
          } else if (
            byte === 0x2f &&
            this._accumulator.length === 4 &&
            this._accumulator[0] === 0x48 &&
            this._accumulator[1] === 0x54 &&
            this._accumulator[2] === 0x54 &&
            this._accumulator[3] === 0x50
          ) {
            this._accumulator.push(byte)
          } else {
            throw errors.INVALID_MESSAGE()
          }

          break
        }

        case REQUEST_URL: {
          this._checkHeaderSize()

          if (byte === SP) {
            this._url = this._buildString()

            if (this._url.length === 0) throw errors.INVALID_MESSAGE()

            this._state = REQUEST_VERSION
          } else if (byte === CR) {
            throw errors.INVALID_MESSAGE()
          } else if (byte >= 0x21 && byte !== 0x7f) {
            this._accumulator.push(byte)
          } else {
            throw errors.INVALID_MESSAGE()
          }

          break
        }

        case REQUEST_VERSION: {
          this._checkHeaderSize()

          if (byte === CR) {
            this._version = this._buildString()

            if (this._version !== 'HTTP/1.0' && this._version !== 'HTTP/1.1') {
              throw errors.INVALID_MESSAGE()
            }

            this._state = FIRST_LINE_LF
          } else if (byte >= 0x21 && byte !== 0x7f) {
            this._accumulator.push(byte)
          } else {
            throw errors.INVALID_MESSAGE()
          }

          break
        }

        case STATUS_CODE: {
          this._checkHeaderSize()

          if (byte === SP) {
            if (this._accumulator.length === 0) throw errors.INVALID_MESSAGE()

            let code = 0

            for (let i = 0, n = this._accumulator.length; i < n; i++) {
              code = code * 10 + this._accumulator[i]
            }

            this._accumulator = []

            if (code < 100 || code > 999) throw errors.INVALID_MESSAGE()

            this._code = code
            this._state = STATUS_REASON
          } else if (byte >= ZERO && byte <= NINE) {
            this._accumulator.push(byte - ZERO)
          } else {
            throw errors.INVALID_MESSAGE()
          }

          break
        }

        case STATUS_REASON: {
          this._checkHeaderSize()

          if (byte === CR) {
            this._reason = this._buildString()
            this._state = FIRST_LINE_LF
          } else if (isFieldByte(byte)) {
            this._accumulator.push(byte)
          } else {
            throw errors.INVALID_MESSAGE()
          }

          break
        }

        case FIRST_LINE_LF: {
          if (byte !== LF) throw errors.INVALID_MESSAGE()

          this._headers = Object.create(null)
          this._headerCount = 0
          this._state = HEADER_START

          break
        }

        case HEADER_START: {
          this._checkHeaderSize()

          if (byte === CR) {
            this._state = HEADER_END_LF
          } else if (byte !== COLON && isTokenByte(byte)) {
            this._accumulator.push(byte >= UPPER_A && byte <= UPPER_Z ? byte + 0x20 : byte)
            this._state = HEADER_NAME
          } else {
            throw errors.INVALID_HEADER()
          }

          break
        }

        case HEADER_NAME: {
          this._checkHeaderSize()

          if (byte === COLON) {
            this._headerName = this._buildString()
            this._state = HEADER_VALUE_WS
          } else if (byte !== COLON && isTokenByte(byte)) {
            this._accumulator.push(byte >= UPPER_A && byte <= UPPER_Z ? byte + 0x20 : byte)
          } else {
            throw errors.INVALID_HEADER()
          }

          break
        }

        case HEADER_VALUE_WS: {
          this._checkHeaderSize()

          if (byte === SP || byte === TAB) break

          if (byte === CR) {
            this._storeHeader(this._headerName, '')
            this._headerName = ''
            this._state = HEADER_LINE_LF

            break
          }

          if (!isFieldByte(byte)) throw errors.INVALID_HEADER()

          this._accumulator.push(byte)
          this._state = HEADER_VALUE

          break
        }

        case HEADER_VALUE: {
          this._checkHeaderSize()

          if (byte === CR) {
            this._storeHeader(this._headerName, this._buildString())
            this._headerName = ''
            this._state = HEADER_LINE_LF
          } else if (isFieldByte(byte)) {
            this._accumulator.push(byte)
          } else {
            throw errors.INVALID_HEADER()
          }

          break
        }

        case HEADER_LINE_LF: {
          if (byte !== LF) throw errors.INVALID_HEADER()

          this._state = HEADER_START

          break
        }

        case HEADER_END_LF: {
          if (byte !== LF) throw errors.INVALID_MESSAGE()

          const headers = { ...this._headers }

          if (this._isResponse) {
            yield {
              type: constants.RESPONSE,
              version: this._version,
              code: this._code,
              reason: this._reason,
              headers
            }
          } else {
            if (this._version === 'HTTP/1.1' && !('host' in headers)) {
              throw errors.INVALID_HEADER("Header 'Host' is missing")
            }

            yield {
              type: constants.REQUEST,
              version: this._version,
              method: this._method,
              url: this._url,
              headers
            }
          }

          const transferEncoding = headers['transfer-encoding']
          const contentLength = headers['content-length']

          if (transferEncoding) {
            const encodings = transferEncoding.split(',')

            let chunkedCount = 0

            for (let i = 0, n = encodings.length; i < n; i++) {
              if (encodings[i].trim().toLowerCase() === 'chunked') chunkedCount++
            }

            const lastEncoding = encodings[encodings.length - 1].trim().toLowerCase()

            if (lastEncoding !== 'chunked') {
              throw errors.INVALID_MESSAGE("'Transfer-Encoding' must end with 'chunked'")
            }

            if (chunkedCount > 1) {
              throw errors.INVALID_MESSAGE(
                "'chunked' must not appear more than once in 'Transfer-Encoding'"
              )
            }

            if (contentLength) {
              throw errors.INVALID_MESSAGE(
                "Conflicting 'Content-Length' and 'Transfer-Encoding' headers"
              )
            }

            this._state = CHUNK_SIZE
            this._headerSize = 0

            continue
          }

          if (contentLength) {
            if (contentLength.length === 0) throw errors.INVALID_CONTENT_LENGTH()

            let length = 0

            for (let i = 0, n = contentLength.length; i < n; i++) {
              const c = contentLength.charCodeAt(i)

              if (c < ZERO || c > NINE) throw errors.INVALID_CONTENT_LENGTH()

              length = length * 10 + (c - ZERO)
            }

            if (!Number.isSafeInteger(length) || length < 0) {
              throw errors.INVALID_CONTENT_LENGTH()
            }

            if (length === 0) {
              this._state = FIRST_TOKEN
              this._headerSize = 0

              yield { type: constants.END }
            } else {
              this._state = BODY
              this._remaining = length
              this._headerSize = 0
            }
          } else {
            this._state = FIRST_TOKEN
            this._headerSize = 0

            yield { type: constants.END }
          }

          break
        }

        case CHUNK_SIZE: {
          if (byte === CR || byte === 0x3b) {
            if (this._accumulator.length === 0) throw errors.INVALID_CHUNK_LENGTH()

            let length = 0

            for (let i = 0, n = this._accumulator.length; i < n; i++) {
              length = length * 16 + this._accumulator[i]
            }

            this._accumulator = []

            if (!Number.isSafeInteger(length)) throw errors.INVALID_CHUNK_LENGTH()

            if (byte === 0x3b) {
              this._remaining = length
              this._state = CHUNK_EXTENSION
            } else if (length === 0) {
              this._state = LAST_CHUNK_LF
            } else {
              this._remaining = length + 2
              this._state = CHUNK_SIZE_LF
            }
          } else if (isHex(byte)) {
            if (this._accumulator.length >= MAX_CHUNK_SIZE_LENGTH) {
              throw errors.INVALID_CHUNK_LENGTH()
            }

            this._accumulator.push(hexValue(byte))
          } else {
            throw errors.INVALID_CHUNK_LENGTH()
          }

          break
        }

        case CHUNK_EXTENSION: {
          this._checkHeaderSize()

          if (byte === CR) {
            if (this._remaining === 0) {
              this._state = LAST_CHUNK_LF
            } else {
              this._remaining += 2
              this._state = CHUNK_SIZE_LF
            }
          } else if (!isFieldByte(byte)) {
            throw errors.INVALID_CHUNK_LENGTH()
          }

          break
        }

        case CHUNK_SIZE_LF: {
          if (byte !== LF) throw errors.INVALID_CHUNK_LENGTH()

          this._state = CHUNK_DATA

          break
        }

        case LAST_CHUNK_LF: {
          if (byte !== LF) throw errors.INVALID_CHUNK_LENGTH()

          this._state = TRAILER_CR

          break
        }

        case TRAILER_CR: {
          if (byte !== CR) throw errors.INVALID_MESSAGE()

          this._state = TRAILER_LF

          break
        }

        case TRAILER_LF: {
          if (byte !== LF) throw errors.INVALID_MESSAGE()

          this._state = FIRST_TOKEN
          this._headerSize = 0

          yield { type: constants.END }

          break
        }

        default:
          throw errors.INVALID_MESSAGE()
      }
    }
  }
}

exports.constants = constants

const TOKEN_BYTES = Buffer.from([
  // 0x00-0x1f (control characters) + 0x20 (space)
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  // 0x21-0x41: ! " # $ % & ' ( ) * + , - . / 0-9 : ; < = > ? @ A
  1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1,
  // 0x42-0x62: B-Z [ \ ] ^ _ ` a b
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1,
  // 0x63-0x7f: c-z { | } ~ DEL
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0
])

function isTokenByte(b) {
  return TOKEN_BYTES[b] === 1
}

function isFieldByte(b) {
  return b === TAB || (b >= 0x20 && b <= 0x7e)
}

function isHex(b) {
  return (
    (b >= ZERO && b <= NINE) || (b >= UPPER_A && b <= UPPER_F) || (b >= LOWER_A && b <= LOWER_F)
  )
}

function hexValue(b) {
  if (b >= ZERO && b <= NINE) return b - ZERO
  if (b >= UPPER_A && b <= UPPER_F) return b - UPPER_A + 10
  return b - LOWER_A + 10
}
module.exports = class HTTPParserError extends Error {
  constructor(msg, fn = HTTPParserError, code = fn.name) {
    super(`${code}: ${msg}`)

    this.code = code

    if (Error.captureStackTrace) Error.captureStackTrace(this, fn)
  }

  get name() {
    return 'HTTPParserError'
  }

  static INVALID_MESSAGE(msg = 'Invalid HTTP message') {
    return new HTTPParserError(msg, HTTPParserError.INVALID_MESSAGE)
  }

  static INVALID_HEADER(msg = 'Invalid HTTP header') {
    return new HTTPParserError(msg, HTTPParserError.INVALID_HEADER)
  }

  static INVALID_CONTENT_LENGTH(msg = 'Invalid HTTP Content-Length') {
    return new HTTPParserError(msg, HTTPParserError.INVALID_CONTENT_LENGTH)
  }

  static INVALID_CHUNK_LENGTH(msg = 'Invalid HTTP chunk length') {
    return new HTTPParserError(msg, HTTPParserError.INVALID_CHUNK_LENGTH)
  }
}
{
  "name": "bare-http-parser",
  "version": "1.1.5",
  "description": "Streaming HTTP request and response parser for Bare",
  "exports": {
    "./package": "./package.json",
    ".": "./index.js",
    "./errors": "./lib/errors.js"
  },
  "files": [
    "index.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-http-parser.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-http-parser/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-http-parser#readme",
  "devDependencies": {
    "brittle": "^3.3.0",
    "lunte": "^1.8.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  }
}
exports.IncomingMessage = require('./lib/incoming-message')
exports.OutgoingMessage = require('./lib/outgoing-message')

exports.Agent = require('./lib/agent')
exports.globalAgent = exports.Agent.global

exports.Server = require('./lib/server')
exports.ServerResponse = require('./lib/server-response')
exports.ServerConnection = require('./lib/server-connection')

exports.ClientRequest = require('./lib/client-request')
exports.ClientConnection = require('./lib/client-connection')

exports.constants = require('./lib/constants')
exports.errors = require('./lib/errors')

exports.METHODS = Object.values(exports.constants.method) // For Node.js compatibility
exports.STATUS_CODES = exports.constants.status // For Node.js compatibility

exports.createServer = function createServer(opts, onrequest) {
  return new exports.Server(opts, onrequest)
}

exports.request = function request(url, opts, onresponse) {
  if (typeof opts === 'function') {
    onresponse = opts
    opts = {}
  }

  if (typeof url === 'string') url = new URL(url)

  if (isURL(url)) {
    opts = opts ? { ...url, ...opts } : { ...url }

    opts.host = url.hostname
    opts.path = url.pathname + url.search
    opts.port = url.port ? parseInt(url.port, 10) : defaultPort(url)
  } else {
    opts = url ? { ...url } : {}

    // For Node.js compatibility
    opts.host = opts.hostname || opts.host
    opts.port = typeof opts.port === 'string' ? parseInt(opts.port, 10) : opts.port
  }

  return new exports.ClientRequest(opts, onresponse)
}

exports.get = function get(url, opts, onresponse) {
  const req = exports.request(url, opts, onresponse)
  req.end()
  return req
}

// https://url.spec.whatwg.org/#default-port
function defaultPort(url) {
  switch (url.protocol) {
    case 'ftp:':
      return 21
    case 'http:':
    case 'ws:':
      return 80
    case 'https:':
    case 'wss:':
      return 443
  }

  return null
}

// https://url.spec.whatwg.org/#api
function isURL(url) {
  return (
    url !== null &&
    typeof url === 'object' &&
    typeof url.protocol === 'string' &&
    typeof url.hostname === 'string' &&
    typeof url.pathname === 'string' &&
    typeof url.search === 'string'
  )
}
const EventEmitter = require('bare-events')
const tcp = require('bare-tcp')
const HTTPClientConnection = require('./client-connection')
const errors = require('./errors')

class HTTPSocketSet {
  constructor() {
    this._sockets = new Map()
    this._size = 0
  }

  get size() {
    return this._size
  }

  add(name, socket) {
    const sockets = this._sockets.get(name)

    this._size++

    if (sockets === undefined) this._sockets.set(name, [socket])
    else sockets.push(socket)
  }

  pop(name) {
    const sockets = this._sockets.get(name)
    if (sockets === undefined || sockets.length === 0) return null

    this._size--

    const last = sockets.pop()

    if (sockets.length === 0) this._sockets.delete(name)

    return last
  }

  delete(name, socket) {
    const sockets = this._sockets.get(name)
    if (sockets === undefined) return

    const i = sockets.indexOf(socket)
    if (i === -1) return

    this._size--

    const last = sockets.pop()
    if (last !== socket) sockets[i] = last

    if (sockets.length === 0) this._sockets.delete(name)
  }

  *sockets() {
    for (const sockets of this._sockets.values()) {
      yield* sockets
    }
  }

  *[Symbol.iterator]() {
    for (const [name, sockets] of this._sockets) {
      for (const socket of sockets) yield [name, socket]
    }
  }
}

class HTTPAgent extends EventEmitter {
  constructor(opts = {}) {
    super()

    const { keepAlive = false, keepAliveMsecs = 1000, defaultPort = 80 } = opts

    this._suspended = false
    this._resuming = null

    this._sockets = new HTTPSocketSet()
    this._freeSockets = new HTTPSocketSet()

    this._keepAlive = typeof keepAlive === 'number' ? keepAlive : keepAlive ? keepAliveMsecs : -1
    this._defaultPort = defaultPort

    this._opts = { ...opts }
  }

  get suspended() {
    return this._suspended
  }

  get resumed() {
    return this._resuming ? this._resuming.promise : null
  }

  get sockets() {
    return this._sockets.sockets()
  }

  get freeSockets() {
    return this._freeSockets.sockets()
  }

  get defaultPort() {
    return this._defaultPort
  }

  createConnection(opts) {
    if (this._suspended) throw errors.AGENT_SUSPENDED()

    return tcp.createConnection(opts)
  }

  reuseSocket(socket, req) {
    socket.ref()
  }

  keepSocketAlive(socket) {
    if (this._keepAlive === -1) return false

    socket.setKeepAlive(true, this._keepAlive)
    socket.unref()

    return true
  }

  getName(opts) {
    return `${opts.host}:${opts.port}`
  }

  addRequest(req, opts) {
    opts = { ...opts, ...this._opts }

    const name = this.getName(opts)

    let socket = this._freeSockets.pop(name)

    if (socket) this.reuseSocket(socket, req)
    else {
      const agent = this

      socket = this.createConnection(opts)

      socket
        .on('error', noop) // someone needs to handle it
        .on('free', onfree)
        .on('end', onremove)
        .on('finish', onremove)
        .on('close', onremove)
        .on('timeout', ontimeout)

      function onfree() {
        if (socket.destroyed) return

        if (agent.keepSocketAlive(socket)) {
          agent._freeSockets.add(name, socket)
        } else {
          socket.end()
        }

        agent.emit('free', socket)
      }

      function onremove() {
        socket.off('free', onfree)

        agent._sockets.delete(name, socket)
        agent._freeSockets.delete(name, socket)

        if (agent._sockets.size === 0) HTTPAgent._agents.delete(agent)
      }

      function ontimeout() {
        socket.destroy()

        agent._freeSockets.delete(name, socket)
      }
    }

    if (this._sockets.size === 0) HTTPAgent._agents.add(this)

    this._sockets.add(name, socket)

    req._socket = socket

    const connection = HTTPClientConnection.from(socket, opts)

    connection._req = req
  }

  suspend() {
    if (this._suspended) return

    this._resuming = Promise.withResolvers()
    this._suspended = true

    this.destroy()
  }

  resume() {
    if (this._resuming === null) return

    this._resuming.resolve()
    this._resuming = null
    this._suspended = false
  }

  destroy() {
    for (const socket of this._sockets.sockets()) socket.destroy()
  }

  static _agents = new Set()

  static _onidle() {
    for (const agent of this._agents) {
      agent.destroy()
    }
  }
}

HTTPAgent.global = new HTTPAgent({ keepAlive: 1000, timeout: 5000 })

module.exports = HTTPAgent

Bare.on('idle', HTTPAgent._onidle.bind(HTTPAgent))

function noop() {}
const HTTPParser = require('bare-http-parser')
const HTTPIncomingMessage = require('./incoming-message')
const errors = require('./errors')

const {
  constants: { RESPONSE, DATA, END }
} = HTTPParser

const EMPTY = Buffer.alloc(0)

module.exports = class HTTPClientConnection {
  static _connections = new WeakMap()

  static for(socket) {
    return this._connections.get(socket) || null
  }

  static from(socket, opts) {
    return this.for(socket) || new this(socket, opts)
  }

  constructor(socket, opts = {}) {
    const { IncomingMessage = HTTPIncomingMessage } = opts

    this._socket = socket

    this._req = null
    this._res = null

    this._IncomingMessage = IncomingMessage

    this._parser = new HTTPParser()
    this._idle = true

    this._onerror = this._onerror.bind(this)
    this._onclose = this._onclose.bind(this)
    this._onend = this._onend.bind(this)
    this._ondata = this._ondata.bind(this)
    this._ondrain = this._ondrain.bind(this)
    this._ontimeout = this._ontimeout.bind(this)

    socket
      .on('error', this._onerror)
      .on('close', this._onclose)
      .on('end', this._onend)
      .on('data', this._ondata)
      .on('drain', this._ondrain)
      .on('timeout', this._ontimeout)

    HTTPClientConnection._connections.set(socket, this)
  }

  get socket() {
    return this._socket
  }

  get req() {
    return this._req
  }

  get res() {
    return this._res
  }

  get idle() {
    return this._idle
  }

  _onerror(err) {
    if (this._req) this._req.destroy(err)
  }

  _onclose() {
    if (this._req) this._req.destroy()
  }

  _onend() {
    if (this._req) this._req.destroy(errors.CONNECTION_LOST())
  }

  _ondata(data) {
    this._idle = false

    try {
      for (const op of this._parser.push(data)) {
        switch (op.type) {
          case RESPONSE:
            this._req.on('close', () => {
              this._req = null
            })

            this._res = new this._IncomingMessage(this._socket, {
              headers: op.headers,
              statusCode: op.code,
              statusMessage: op.reason
            })

            this._res.on('close', () => {
              this._res = null
              this._idle = true

              this._socket.emit('free')
            })

            if (op.headers.connection && op.headers.connection.toLowerCase() === 'upgrade') {
              return this._onupgrade(this._parser.end())
            }

            this._req.emit('response', this._res)
            break

          case DATA:
            this._res.push(op.data)
            break

          case END:
            if (this._res) {
              this._res._socket = null
              this._res.push(null)
            }

            if (this._req) {
              this._req._socket = null
              this._req.destroy()
            }
            break
        }
      }
    } catch (err) {
      this._socket.destroy(err)
    }
  }

  _onupgrade(data) {
    this._detach()

    const res = this._res
    const req = this._req

    res._upgrade = req._upgrade = true

    const upgraded = req.emit('upgrade', res, this._socket, data || EMPTY)

    res.push(null)
    req.destroy()

    if (!upgraded) this._socket.destroy()
  }

  _ontimeout() {
    if (this._req) this._req.emit('timeout')
  }

  _ondrain() {
    if (this._req) this._req._continueWrite()
  }

  _detach() {
    this._socket
      .off('error', this._onerror)
      .off('close', this._onclose)
      .off('end', this._onend)
      .off('data', this._ondata)
      .off('drain', this._ondrain)
      .off('timeout', this._ontimeout)

    HTTPClientConnection._connections.delete(this._socket)
  }
}
const HTTPAgent = require('./agent')
const HTTPOutgoingMessage = require('./outgoing-message')
const validate = require('./validate')

const CHUNK_DELIMITER = Buffer.from('\r\n')
const CHUNK_TERMINATOR = Buffer.from('0\r\n\r\n')

module.exports = class HTTPClientRequest extends HTTPOutgoingMessage {
  constructor(opts = {}, onresponse = null) {
    if (typeof opts === 'function') {
      onresponse = opts
      opts = {}
    }

    opts = opts ? { ...opts } : {}

    const agent = opts.agent === false ? new HTTPAgent() : opts.agent || HTTPAgent.global
    const method = opts.method || 'GET'
    const path = opts.path || '/'
    const defaultPort = opts.defaultPort || (agent && agent.defaultPort) || 80
    const host = (opts.host = opts.host || 'localhost')
    const port = (opts.port = opts.port || defaultPort)
    const headers = { host: hostHeader(host, port, defaultPort), ...opts.headers }

    validate.validateMethod(method)
    validate.validatePath(path)

    for (const name of Object.keys(headers)) {
      const n = name.toLowerCase()

      validate.validateHeaderName(n)
      validate.validateHeaderValue(n, headers[name])
    }

    super()

    agent.addRequest(this, opts)

    this._headers = headers
    this._method = method
    this._path = path

    this._chunked = method !== 'GET' && method !== 'HEAD'

    this._pendingWrite = null
    this._pendingFinal = null

    if (onresponse) this.once('response', onresponse)
  }

  get method() {
    return this._method
  }

  get path() {
    return this._path
  }

  // For Node.js compatibility
  abort() {
    return this.destroy()
  }

  _header() {
    validate.validateMethod(this._method)
    validate.validatePath(this._path)

    let h = `${this._method} ${this._path} HTTP/1.1\r\n`

    let upgrade = false

    for (const name of Object.keys(this._headers)) {
      const n = name.toLowerCase()
      const v = this._headers[name]

      validate.validateHeaderName(n)
      validate.validateHeaderValue(n, v)

      if (n === 'content-length') this._chunked = false
      if (n === 'connection' && v && v.toLowerCase() === 'upgrade') upgrade = true

      h += `${httpCase(n)}: ${v}\r\n`
    }

    if (upgrade) this._chunked = false

    if (this._chunked) h += 'Transfer-Encoding: chunked\r\n'

    h += '\r\n'

    return h
  }

  _write(data, encoding, cb) {
    if (this._headersSent === false) this.flushHeaders()

    if (this._chunked) {
      this._socket.write(Buffer.from(data.byteLength.toString(16)))
      this._socket.write(CHUNK_DELIMITER)
    }

    let flushed = this._socket.write(data)

    if (this._chunked) flushed = this._socket.write(CHUNK_DELIMITER)

    if (flushed) cb(null)
    else this._pendingWrite = cb
  }

  _final(cb) {
    if (this._headersSent === false) this.flushHeaders()

    if (this._chunked) this._socket.write(CHUNK_TERMINATOR)

    this._pendingFinal = cb
  }

  _predestroy() {
    super._predestroy()

    this._continueWrite()
    this._continueFinal()
  }

  _continueWrite() {
    if (this._pendingWrite === null) return
    const cb = this._pendingWrite
    this._pendingWrite = null
    cb(null)
  }

  _continueFinal() {
    if (this._pendingFinal === null) return
    const cb = this._pendingFinal
    this._pendingFinal = null
    cb(null)
  }
}

function httpCase(n) {
  let s = ''
  for (const part of n.split('-')) {
    s += (s ? '-' : '') + part.slice(0, 1).toUpperCase() + part.slice(1)
  }
  return s
}

function hostHeader(host, port, defaultPort) {
  const i = host.indexOf(':')

  if (i !== -1 && host.includes(':', i + 1) && host.charCodeAt(0) !== 91 /* [ */) {
    host = `[${host}]`
  }

  if (port && +port !== defaultPort) {
    host += ':' + port
  }

  return host
}
module.exports = {
  method: {
    GET: 'GET',
    HEAD: 'HEAD',
    POST: 'POST',
    PUT: 'PUT',
    DELETE: 'DELETE',
    CONNECT: 'CONNECT',
    OPTIONS: 'OPTIONS',
    TRACE: 'TRACE',
    PATCH: 'PATCH'
  },
  status: {
    100: 'Continue',
    101: 'Switching Protocols',
    102: 'Processing',
    103: 'Early Hints',
    200: 'OK',
    201: 'Created',
    202: 'Accepted',
    203: 'Non-Authoritative Information',
    204: 'No Content',
    205: 'Reset Content',
    206: 'Partial Content',
    207: 'Multi-Status',
    208: 'Already Reported',
    226: 'IM Used',
    300: 'Multiple Choices',
    301: 'Moved Permanently',
    302: 'Found',
    303: 'See Other',
    304: 'Not Modified',
    305: 'Use Proxy',
    307: 'Temporary Redirect',
    308: 'Permanent Redirect',
    400: 'Bad Request',
    401: 'Unauthorized',
    402: 'Payment Required',
    403: 'Forbidden',
    404: 'Not Found',
    405: 'Method Not Allowed',
    406: 'Not Acceptable',
    407: 'Proxy Authentication Required',
    408: 'Request Timeout',
    409: 'Conflict',
    410: 'Gone',
    411: 'Length Required',
    412: 'Precondition Failed',
    413: 'Payload Too Large',
    414: 'URI Too Long',
    415: 'Unsupported Media Type',
    416: 'Range Not Satisfiable',
    417: 'Expectation Failed',
    418: "I'm a Teapot",
    421: 'Misdirected Request',
    422: 'Unprocessable Entity',
    423: 'Locked',
    424: 'Failed Dependency',
    425: 'Too Early',
    426: 'Upgrade Required',
    428: 'Precondition Required',
    429: 'Too Many Requests',
    431: 'Request Header Fields Too Large',
    451: 'Unavailable For Legal Reasons',
    500: 'Internal Server Error',
    501: 'Not Implemented',
    502: 'Bad Gateway',
    503: 'Service Unavailable',
    504: 'Gateway Timeout',
    505: 'HTTP Version Not Supported',
    506: 'Variant Also Negotiates',
    507: 'Insufficient Storage',
    508: 'Loop Detected',
    509: 'Bandwidth Limit Exceeded',
    510: 'Not Extended',
    511: 'Network Authentication Required'
  }
}
module.exports = class HTTPError extends Error {
  constructor(msg, fn = HTTPError, code = fn.name) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'HTTPError'
  }

  static NOT_IMPLEMENTED(msg = 'Method not implemented') {
    return new HTTPError(msg, HTTPError.NOT_IMPLEMENTED)
  }

  static CONNECTION_LOST(msg = 'Socket hung up') {
    return new HTTPError(msg, HTTPError.CONNECTION_LOST)
  }

  static AGENT_SUSPENDED(msg = 'Agent is suspended') {
    return new HTTPError(msg, HTTPError.AGENT_SUSPENDED)
  }

  static INVALID_HEADER_NAME(msg = 'Invalid header name') {
    return new HTTPError(msg, HTTPError.INVALID_HEADER_NAME)
  }

  static INVALID_HEADER_VALUE(msg = 'Invalid header value') {
    return new HTTPError(msg, HTTPError.INVALID_HEADER_VALUE)
  }
}
const { Readable } = require('bare-stream')

module.exports = class HTTPIncomingMessage extends Readable {
  constructor(socket = null, opts = {}) {
    super()

    this._socket = socket
    this._upgrade = false
    this._headers = opts.headers || {}

    // Server options
    this._method = opts.method || ''
    this._url = opts.url || ''

    // Client options
    this._statusCode = opts.statusCode || 0
    this._statusMessage = opts.statusMessage || ''
  }

  get socket() {
    return this._socket
  }

  get upgrade() {
    return this._upgrade
  }

  get headers() {
    return this._headers
  }

  set headers(value) {
    this._headers = value
  }

  get method() {
    return this._method
  }

  set method(value) {
    this._method = value
  }

  get url() {
    return this._url
  }

  set url(value) {
    this._url = value
  }

  get statusCode() {
    return this._statusCode
  }

  set statusCode(value) {
    this._statusCode = value
  }

  get statusMessage() {
    return this._statusMessage
  }

  set statusMessage(value) {
    this._statusMessage = value
  }

  get httpVersion() {
    return '1.1'
  }

  getHeader(name) {
    return this._headers[name.toLowerCase()]
  }

  getHeaders() {
    return { ...this._headers }
  }

  hasHeader(name) {
    return name.toLowerCase() in this._headers
  }

  setTimeout(ms, ontimeout) {
    if (ontimeout) this.once('timeout', ontimeout)

    this._socket.setTimeout(ms)

    return this
  }

  _predestroy() {
    if (this._upgrade === false && this._socket !== null) this._socket.destroy()
  }
}
const { Writable } = require('bare-stream')
const errors = require('./errors')
const validate = require('./validate')

module.exports = class HTTPOutgoingMessage extends Writable {
  constructor(socket = null) {
    super()

    this._socket = socket
    this._upgrade = false
    this._headersSent = false
    this._headers = {}
  }

  get socket() {
    return this._socket
  }

  get upgrade() {
    return this._upgrade
  }

  get headersSent() {
    return this._headersSent
  }

  get headers() {
    return this._headers
  }

  set headers(value) {
    if (value) {
      for (const name of Object.keys(value)) {
        const n = name.toLowerCase()

        validate.validateHeaderName(n)
        validate.validateHeaderValue(n, value[name])
      }
    }

    this._headers = value
  }

  getHeader(name) {
    return this._headers[name.toLowerCase()]
  }

  getHeaders() {
    return { ...this._headers }
  }

  hasHeader(name) {
    return name.toLowerCase() in this._headers
  }

  setHeader(name, value) {
    const n = name.toLowerCase()

    validate.validateHeaderName(n)
    validate.validateHeaderValue(n, value)

    this._headers[n] = value
  }

  flushHeaders() {
    if (this._headersSent === true || this._socket === null) return

    this._socket.write(Buffer.from(this._header()))
    this._headersSent = true
  }

  setTimeout(ms, ontimeout) {
    if (ontimeout) this.once('timeout', ontimeout)

    this._socket.setTimeout(ms)

    return this
  }

  _header() {
    throw errors.NOT_IMPLEMENTED()
  }

  _predestroy() {
    if (this._upgrade === false && this._socket !== null) this._socket.destroy()
  }
}
const { isEnded, isFinished, getStreamError } = require('bare-stream')
const HTTPParser = require('bare-http-parser')
const HTTPIncomingMessage = require('./incoming-message')
const HTTPServerResponse = require('./server-response')

const {
  constants: { REQUEST, DATA, END }
} = HTTPParser

const EMPTY = Buffer.alloc(0)

module.exports = class HTTPServerConnection {
  static _connections = new WeakMap()

  static for(socket) {
    return this._connections.get(socket) || null
  }

  constructor(server, socket, opts = {}) {
    const { IncomingMessage = HTTPIncomingMessage, ServerResponse = HTTPServerResponse } = opts

    this._server = server
    this._socket = socket

    this._req = null
    this._res = null

    this._IncomingMessage = IncomingMessage
    this._ServerResponse = ServerResponse

    this._parser = new HTTPParser()
    this._idle = true

    this._onclose = this._onclose.bind(this)
    this._ondata = this._ondata.bind(this)
    this._ondrain = this._ondrain.bind(this)
    this._ontimeout = this._ontimeout.bind(this)

    socket
      .on('error', noop)
      .on('close', this._onclose)
      .on('data', this._ondata)
      .on('drain', this._ondrain)
      .on('timeout', this._ontimeout)

    HTTPServerConnection._connections.set(socket, this)

    if (this._server.timeout) socket.setTimeout(this._server.timeout)
  }

  get server() {
    return this._server
  }

  get socket() {
    return this._socket
  }

  get req() {
    return this._req
  }

  get res() {
    return this._res
  }

  get idle() {
    return this._idle
  }

  _onclose() {
    if (this._req && !isEnded(this._req)) this._req.destroy()
    if (this._res && !isFinished(this._res)) this._res.destroy()

    const err = getStreamError(this._socket)
    if (err) this._socket.destroy(err)
  }

  _ondata(data) {
    this._idle = false

    try {
      for (const op of this._parser.push(data)) {
        switch (op.type) {
          case REQUEST:
            this._req = new this._IncomingMessage(this._socket, {
              headers: op.headers,
              method: op.method,
              url: op.url
            })

            this._req.on('close', () => {
              this._req = null

              this._idle = true

              if (this._server.closing) this._socket.destroy()
            })

            // Eagerly open the request stream
            this._req.resume()
            this._req.pause()

            if (op.headers.connection && op.headers.connection.toLowerCase() === 'upgrade') {
              return this._onupgrade(this._parser.end())
            }

            this._res = new this._ServerResponse(this._socket, this._req)

            this._res.on('close', () => {
              this._res = null
            })

            this._server.emit('request', this._req, this._res)
            break

          case DATA:
            this._req.push(op.data)
            break

          case END:
            if (this._req) {
              this._req._socket = null
              this._req.push(null)
            }
            break
        }
      }
    } catch (err) {
      this._socket.destroy(err)
    }
  }

  _onupgrade(data) {
    this._detach()

    const req = this._req

    req._upgrade = true

    const upgraded = this._server.emit('upgrade', req, this._socket, data || EMPTY)

    req.push(null)

    if (!upgraded) this._socket.destroy()
  }

  _ontimeout() {
    const reqTimeout = this._req && this._req.emit('timeout')
    const resTimeout = this._res && this._res.emit('timeout')
    const serverTimeout = this._server.emit('timeout', this._socket)

    if (!reqTimeout && !resTimeout && !serverTimeout) this._socket.destroy()
  }

  _ondrain() {
    if (this._res) this._res._continueWrite()
  }

  _detach() {
    this._socket
      .off('error', noop)
      .off('close', this._onclose)
      .off('data', this._ondata)
      .off('drain', this._ondrain)
      .off('timeout', this._ontimeout)

    HTTPServerConnection._connections.delete(this._socket)
  }
}

function noop() {}
const { isFinishing } = require('bare-stream')
const HTTPOutgoingMessage = require('./outgoing-message')
const constants = require('./constants')
const validate = require('./validate')

const CHUNK_DELIMITER = Buffer.from('\r\n')
const CHUNK_TERMINATOR = Buffer.from('0\r\n\r\n')

module.exports = class HTTPServerResponse extends HTTPOutgoingMessage {
  constructor(socket, req) {
    super(socket)

    this._req = req

    this._statusCode = 200
    this._statusMessage = null

    this._chunked = true
    this._close = req.headers.connection === 'close'
    this._onlyHeaders = req.method === 'HEAD'

    this._pendingWrite = null
  }

  get req() {
    return this._req
  }

  get statusCode() {
    return this._statusCode
  }

  set statusCode(value) {
    this._statusCode = value
  }

  get statusMessage() {
    return this._statusMessage
  }

  set statusMessage(value) {
    validate.validateStatusMessage(value)

    this._statusMessage = value
  }

  writeHead(statusCode, statusMessage = null, headers = {}) {
    if (typeof statusMessage === 'object' && statusMessage !== null) {
      headers = statusMessage
      statusMessage = null
    }

    if (statusMessage !== null) validate.validateStatusMessage(statusMessage)

    if (headers) {
      for (const name of Object.keys(headers)) {
        const n = name.toLowerCase()

        validate.validateHeaderName(n)
        validate.validateHeaderValue(n, headers[name])
      }
    }

    this._statusCode = statusCode
    this._statusMessage = statusMessage || null

    if (headers) this._headers = { ...this._headers, ...headers }
  }

  _header() {
    const statusMessage =
      this._statusMessage === null ? constants.status[this._statusCode] : this._statusMessage

    validate.validateStatusMessage(statusMessage)

    let h = 'HTTP/1.1 ' + this._statusCode + ' ' + statusMessage + '\r\n'

    for (const name of Object.keys(this._headers)) {
      const n = name.toLowerCase()
      const v = this._headers[name]

      validate.validateHeaderName(n)
      validate.validateHeaderValue(n, v)

      if (n === 'content-length') this._chunked = false
      if (n === 'connection' && v && v.toLowerCase() === 'close') this._close = true

      h += httpCase(n) + ': ' + v + '\r\n'
    }

    if (this._chunked) h += 'Transfer-Encoding: chunked\r\n'

    h += '\r\n'

    return h
  }

  _write(data, encoding, cb) {
    if (this._headersSent === false) {
      if (isFinishing(this)) {
        this.setHeader(
          'Content-Length',
          (data.byteLength + this._writableState.buffered).toString()
        )
      }

      this.flushHeaders()
    }

    if (this._onlyHeaders === true) return cb(null)

    if (this._chunked) {
      this._socket.write(Buffer.from(data.byteLength.toString(16)))
      this._socket.write(CHUNK_DELIMITER)
    }

    let flushed = this._socket.write(data)

    if (this._chunked) flushed = this._socket.write(CHUNK_DELIMITER)

    if (flushed) cb(null)
    else this._pendingWrite = cb
  }

  _final(cb) {
    if (this._headersSent === false) {
      this.setHeader('Content-Length', '0')
      this.flushHeaders()
    }

    if (this._chunked && this._onlyHeaders === false) this._socket.write(CHUNK_TERMINATOR)

    if (this._close) this._socket.end()

    cb(null)
  }

  _predestroy() {
    super._predestroy()

    this._req.destroy()

    this._continueWrite()
  }

  _continueWrite() {
    if (this._pendingWrite === null) return
    const cb = this._pendingWrite
    this._pendingWrite = null
    cb(null)
  }
}

function httpCase(n) {
  let s = ''
  for (const part of n.split('-')) {
    s += (s ? '-' : '') + part.slice(0, 1).toUpperCase() + part.slice(1)
  }
  return s
}
const TCPServer = require('bare-tcp').Server
const HTTPServerConnection = require('./server-connection')

module.exports = class HTTPServer extends TCPServer {
  constructor(opts = {}, onrequest) {
    if (typeof opts === 'function') {
      onrequest = opts
      opts = {}
    }

    super({ allowHalfOpen: false })

    this._timeout = 0

    this.on('connection', (socket) => {
      new HTTPServerConnection(this, socket, opts)
    })

    if (onrequest) this.on('request', onrequest)
  }

  get timeout() {
    return this._timeout || undefined // For Node.js compatibility
  }

  setTimeout(ms = 0, ontimeout) {
    if (ontimeout) this.on('timeout', ontimeout)

    this._timeout = ms

    return this
  }

  close(onclose) {
    super.close(onclose)

    for (const socket of this.connections) {
      const connection = HTTPServerConnection.for(socket)

      if (connection === null || connection.idle) {
        socket.destroy()
      }
    }

    return this
  }
}
const errors = require('./errors')

// RFC 7230 token = 1*tchar
const TOKEN_RE = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/

// Reject characters that would terminate or split the current line
const VALUE_INVALID_RE = /[\r\n\0]/

// Reject control chars and whitespace in the request-target
const PATH_INVALID_RE = /[\r\n\0\s]/

exports.validateHeaderName = function (name) {
  if (typeof name !== 'string' || !TOKEN_RE.test(name)) {
    throw errors.INVALID_HEADER_NAME(`Invalid header name: ${JSON.stringify(name)}`)
  }
}

exports.validateHeaderValue = function (name, value) {
  if (value === undefined || value === null) return
  if (VALUE_INVALID_RE.test(String(value))) {
    throw errors.INVALID_HEADER_VALUE(
      `Invalid character in header value for ${JSON.stringify(name)}`
    )
  }
}

exports.validateStatusMessage = function (value) {
  if (value === undefined || value === null) return
  if (VALUE_INVALID_RE.test(String(value))) {
    throw errors.INVALID_HEADER_VALUE('Invalid character in status message')
  }
}

exports.validatePath = function (value) {
  if (typeof value !== 'string' || value.length === 0 || PATH_INVALID_RE.test(value)) {
    throw errors.INVALID_HEADER_VALUE(`Invalid character in request path: ${JSON.stringify(value)}`)
  }
}

exports.validateMethod = function (value) {
  if (typeof value !== 'string' || !TOKEN_RE.test(value)) {
    throw errors.INVALID_HEADER_NAME(`Invalid HTTP method: ${JSON.stringify(value)}`)
  }
}
{
  "name": "bare-http1",
  "version": "4.5.7",
  "description": "Native HTTP/1 library for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    },
    "./errors": {
      "types": "./lib/errors.d.ts",
      "default": "./lib/errors.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-http1.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-http1/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-http1#readme",
  "dependencies": {
    "bare-events": "^2.6.0",
    "bare-http-parser": "^1.1.1",
    "bare-stream": "^2.10.0",
    "bare-tcp": "^2.2.0"
  },
  "devDependencies": {
    "bare-buffer": "^3.0.2",
    "bare-url": "^2.1.3",
    "brittle": "^3.3.0",
    "lunte": "^1.6.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "bare-buffer": "*",
    "bare-url": "*"
  },
  "peerDependenciesMeta": {
    "bare-buffer": {
      "optional": true
    },
    "bare-url": {
      "optional": true
    }
  }
}
exports.Agent = require('./lib/agent')
exports.globalAgent = exports.Agent.global

exports.Server = require('./lib/server')

exports.ClientRequest = require('./lib/client-request')

exports.createServer = function createServer(opts, onrequest) {
  return new exports.Server(opts, onrequest)
}

exports.request = function request(url, opts, onresponse) {
  if (typeof opts === 'function') {
    onresponse = opts
    opts = {}
  }

  if (typeof url === 'string') url = new URL(url)

  if (isURL(url)) {
    opts = opts ? { ...url, ...opts } : { ...url }

    opts.host = url.hostname
    opts.path = url.pathname + url.search
    opts.port = url.port ? parseInt(url.port, 10) : defaultPort(url)
  } else {
    opts = url ? { ...url } : {}

    // For Node.js compatibility
    opts.host = opts.hostname || opts.host
    opts.port = typeof opts.port === 'string' ? parseInt(opts.port, 10) : opts.port
  }

  return new exports.ClientRequest(opts, onresponse)
}

// https://url.spec.whatwg.org/#default-port
function defaultPort(url) {
  switch (url.protocol) {
    case 'ftp:':
      return 21
    case 'http:':
    case 'ws:':
      return 80
    case 'https:':
    case 'wss:':
      return 443
  }

  return null
}

// https://url.spec.whatwg.org/#api
function isURL(url) {
  return (
    url !== null &&
    typeof url === 'object' &&
    typeof url.protocol === 'string' &&
    typeof url.hostname === 'string' &&
    typeof url.pathname === 'string' &&
    typeof url.search === 'string'
  )
}
const HTTPAgent = require('bare-http1').Agent
const HTTPSSocket = require('./socket')

class HTTPSAgent extends HTTPAgent {
  constructor(opts = {}) {
    super({ defaultPort: 443, ...opts })
  }

  createConnection(opts) {
    return new HTTPSSocket(super.createConnection(opts), opts)
  }
}

HTTPSAgent.global = new HTTPSAgent({ keepAlive: 1000, timeout: 5000 })

module.exports = HTTPSAgent
const HTTPClientRequest = require('bare-http1').ClientRequest
const HTTPSAgent = require('./agent')

module.exports = class HTTPSClientRequest extends HTTPClientRequest {
  constructor(opts = {}, onresponse = null) {
    if (typeof opts === 'function') {
      onresponse = opts
      opts = {}
    }

    opts = opts ? { ...opts } : {}

    opts.agent = opts.agent === false ? new HTTPSAgent() : opts.agent || HTTPSAgent.global

    super(opts, onresponse)
  }
}
const TCPServer = require('bare-tcp').Server
const HTTPServerConnection = require('bare-http1').ServerConnection
const HTTPSSocket = require('./socket')

module.exports = class HTTPSServer extends TCPServer {
  constructor(opts = {}, onrequest) {
    if (typeof opts === 'function') {
      onrequest = opts
      opts = {}
    }

    super({ allowHalfOpen: false })

    this._timeout = 0

    this.on('connection', (socket) => {
      new HTTPServerConnection(this, new HTTPSSocket(socket, { ...opts, isServer: true }), opts)
    })

    if (onrequest) this.on('request', onrequest)
  }

  get timeout() {
    return this._timeout || undefined // For Node.js compatibility
  }

  setTimeout(ms = 0, ontimeout) {
    if (ontimeout) this.on('timeout', ontimeout)

    this._timeout = ms

    return this
  }

  close(onclose) {
    super.close(onclose)

    for (const socket of this.connections) {
      const connection = HTTPServerConnection.for(socket)

      if (connection === null || connection.idle) {
        socket.destroy()
      }
    }

    return this
  }
}
const TLSSocket = require('bare-tls').Socket

module.exports = class HTTPSSocket extends TLSSocket {
  setKeepAlive(...args) {
    this.socket.setKeepAlive(...args)

    return this
  }

  setNoDelay(...args) {
    this.socket.setNoDelay(...args)

    return this
  }

  setTimeout(...args) {
    this.socket.setTimeout(...args)

    return this
  }

  ref() {
    this.socket.ref()

    return this
  }

  unref() {
    this.socket.unref()

    return this
  }
}
{
  "name": "bare-https",
  "version": "3.0.0",
  "description": "HTTPS library for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-https.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-https/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-https#readme",
  "dependencies": {
    "bare-http1": "^4.4.0",
    "bare-tcp": "^2.2.0",
    "bare-tls": "^3.0.0"
  },
  "devDependencies": {
    "bare-fs": "^4.0.0",
    "brittle": "^3.3.0",
    "lunte": "^1.7.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = require.addon()
const ansiEscapes = require('bare-ansi-escapes')
const getType = require('bare-type')
const binding = require('./binding')

const PLAIN_KEY = /^[a-zA-Z_][a-zA-Z_0-9]*$/

const defaultDepth = 2
const defaultBreakLength = 80
const defaultMaxArrayLength = 40

module.exports = exports = function inspect(value, opts = {}) {
  const {
    colors = false,
    depth = defaultDepth,
    breakLength = defaultBreakLength,
    stylize = defaultStylize(colors)
  } = opts

  const references = new InspectRefMap()

  const tree = inspectValue(value, 0, {
    colors,
    depth,
    breakLength,
    stylize,
    references
  })

  return tree.toString()
}

exports.styles = {
  bigint: ansiEscapes.colorYellow,
  boolean: ansiEscapes.colorYellow,
  date: ansiEscapes.colorMagenta,
  module: ansiEscapes.modifierUnderline,
  name: ansiEscapes.modifierReset,
  null: ansiEscapes.modifierBold,
  number: ansiEscapes.colorYellow,
  regexp: ansiEscapes.colorRed,
  special: ansiEscapes.colorCyan,
  string: ansiEscapes.colorGreen,
  symbol: ansiEscapes.colorGreen,
  undefined: ansiEscapes.colorBrightBlack
}

const styles = exports.styles

function defaultStylize(colors) {
  return function stylize(value, style) {
    const color = colors && styles[style]

    if (color) return color + value + ansiEscapes.modifierReset

    return value
  }
}

class InspectRefMap {
  constructor() {
    this.refs = new WeakMap()
    this.ids = new WeakMap()
    this.nextId = 1
  }

  has(object) {
    return this.refs.has(object)
  }

  get(object) {
    return this.refs.get(object) || null
  }

  set(object, ref) {
    this.refs.set(object, ref)
  }

  id(object) {
    let id = this.ids.get(object)
    if (id) return id

    id = this.nextId++
    this.ids.set(object, id)

    return id
  }
}

class InspectNode {
  constructor(depth, length, opts) {
    const { breakLength = defaultBreakLength, breakAlways = false } = opts

    this.depth = depth
    this.length = length
    this.breakLength = breakLength
    this.breakAlways = breakAlways
  }

  pad(n, string) {
    return string.padStart(n, ' ')
  }

  indent(n, string) {
    return '  '.repeat(n) + string
  }
}

class InspectRef extends InspectNode {
  constructor(depth, opts) {
    super(depth, '[circular *]'.length, opts)

    this.refs = opts.references
    this.count = 0
    this.circular = false
    this.color = opts.colors && styles.special
  }

  get id() {
    return this.refs.id(this)
  }

  increment() {
    return ++this.count
  }

  decrement() {
    return --this.count
  }

  toString(opts = {}) {
    const { offset = 0, pad = 0, indent = 0 } = opts

    let value = this.pad(pad, '[circular *' + this.id + ']')

    if (this.color) value = this.color + value + ansiEscapes.modifierReset

    return offset ? value : this.indent(indent, value)
  }
}

class InspectLeaf extends InspectNode {
  constructor(value, color, depth, opts) {
    const length = value.length

    if (value.includes('\n')) {
      value = value.replaceAll('\n', '\n' + '  '.repeat(depth))

      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.value = value
    this.color = opts.colors && color
  }

  toString(opts = {}) {
    const { offset = 0, pad = 0, indent = 0 } = opts

    let value = this.pad(pad, this.value)

    if (this.color) value = this.color + value + ansiEscapes.modifierReset

    return offset ? value : this.indent(indent, value)
  }
}

class InspectPair extends InspectNode {
  constructor(delim, left, right, depth, opts) {
    const length = left.length + delim.length + right.length

    if (left.breakAlways || right.breakAlways) {
      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.delim = delim
    this.left = left
    this.right = right
  }

  toString(opts = {}) {
    const { indent = 0 } = opts

    return this.indent(
      indent,
      this.left +
        this.delim +
        this.right.toString({
          indent,
          offset: this.left.length + this.delim.length
        })
    )
  }
}

class InspectSuspension extends InspectNode {
  constructor(overflow, depth, opts) {
    const label = `... ${overflow} more`

    super(depth, label.length, opts)

    this.label = label
  }

  toString(opts = {}) {
    const { indent = 0 } = opts

    return this.indent(indent, this.label)
  }
}

class InspectSequence extends InspectNode {
  constructor(header, footer, delim, values, ref, depth, opts) {
    const { tabulate = false } = opts

    const length =
      (ref.circular ? '<ref *>'.length + 1 : 0) +
      header.length +
      values.reduce(
        (length, value, i) =>
          length + value.length + (i === 0 ? 0 : delim.length),
        0
      ) +
      footer.length

    if (values.some((value) => value.breakAlways)) {
      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.header = header
    this.footer = footer
    this.delim = delim
    this.values = values
    this.ref = ref
    this.tabulate = tabulate
  }

  toString(opts = {}) {
    const { offset = 0, indent = 0 } = opts

    const split =
      this.breakAlways ||
      (this.values.length &&
        (offset + this.length > this.breakLength ||
          indent * 2 + this.length > this.breakLength))

    let header = this.header

    if (this.ref.circular) {
      header = '<ref *' + this.ref.id + '> ' + header
    }

    if (this.values.length === 0) {
      header = header.trimEnd()
    }

    if (offset === 0) {
      header = this.indent(indent, header)
    }

    if (split) {
      header = header.trimEnd() + '\n'
    }

    let string = header

    let columns = 1
    let pad = 0

    if (this.tabulate) {
      const widest = this.values.reduce(
        (length, value) =>
          value.breakAlways ? length : Math.max(length, value.length),
        0
      )

      if (widest) {
        columns = Math.max(
          columns,
          Math.floor(
            (this.breakLength - indent * 2) / (widest + this.delim.length)
          )
        )

        if (columns > 1) pad = widest
      }
    }

    for (let i = 0, n = this.values.length, offset = 0; i < n; i++) {
      const value = this.values[i]

      if (split) {
        let part

        if (i % columns === 0 || value.breakAlways) {
          part = value.toString({ indent: indent + 1, pad })
        } else {
          part = value.toString({ pad })
        }

        string += part

        if (i < n - 1) {
          if (i % columns === columns - 1 || this.values[i + 1].breakAlways) {
            string += this.delim.trimEnd() + '\n'
          } else {
            string += this.delim
          }
        }
      } else {
        if (i > 0) string += this.delim

        string += value.toString({ offset })

        offset += value.length
      }
    }

    let footer = this.footer

    if (this.values.length === 0) {
      footer = footer.trimStart()
    }

    if (split) {
      string += '\n' + this.indent(indent, footer.trimStart())
    } else {
      string += footer
    }

    return string
  }
}

function inspectValue(value, depth, opts) {
  const type = getType(value)

  if (type.isUndefined()) return inspectUndefined(depth, opts)
  if (type.isNull()) return inspectNull(depth, opts)
  if (type.isBoolean()) return inspectBoolean(value, depth, opts)
  if (type.isNumber()) return inspectNumber(value, depth, opts)
  if (type.isBigInt()) return inspectBigInt(value, depth, opts)
  if (type.isString()) return inspectString(value, depth, opts)
  if (type.isSymbol()) return inspectSymbol(value, depth, opts)
  if (type.isObject()) return inspectObject(type, value, depth, opts)
  if (type.isFunction()) return inspectFunction(type, value, depth, opts)
  if (type.isExternal()) return inspectExternal(value, opts, opts)
}

function inspectUndefined(depth, opts) {
  return new InspectLeaf('undefined', styles.undefined, depth, opts)
}

function inspectNull(depth, opts) {
  return new InspectLeaf('null', styles.null, depth, opts)
}

function inspectBoolean(value, depth, opts) {
  return new InspectLeaf(value.toString(), styles.boolean, depth, opts)
}

function inspectNumber(value, depth, opts) {
  let string

  if (Object.is(value, -0)) {
    string = '-0'
  } else {
    string = value.toString(10)
  }

  return new InspectLeaf(string, styles.number, depth, opts)
}

function inspectBigInt(value, depth, opts) {
  return new InspectLeaf(value.toString(10) + 'n', styles.bigint, depth, opts)
}

const STRING_ESCAPES =
  /[\ud800-\udbff][\udc00-\udfff]|[\u0000-\u001f'\\\ud800-\udfff]/g

function inspectString(value, depth, opts) {
  // https://tc39.es/ecma262/multipage/structured-data.html#sec-quotejsonstring
  const string = value.replace(STRING_ESCAPES, (match) => {
    if (match.length === 2) return match

    switch (match) {
      case "'":
        return "\\'"
      case '\\':
        return '\\\\'
      case '\b':
        return '\\b'
      case '\t':
        return '\\t'
      case '\n':
        return '\\n'
      case '\f':
        return '\\f'
      case '\r':
        return '\\r'
      default:
        return '\\u' + match.charCodeAt(0).toString(16).padStart(4, '0')
    }
  })

  return new InspectLeaf("'" + string + "'", styles.string, depth, opts)
}

function inspectSymbol(value, depth, opts) {
  return new InspectLeaf(value.toString(), styles.symbol, depth, opts)
}

function inspectKey(value, depth, opts) {
  if (PLAIN_KEY.test(value)) {
    return new InspectLeaf(value, null, depth, opts)
  } else {
    return inspectValue(value, depth, opts)
  }
}

function inspectObject(type, object, depth, opts) {
  const refs = opts.references

  let ref = refs.get(object)
  if (ref === null) {
    ref = new InspectRef(depth, opts)
    refs.set(object, ref)
  } else if (ref.count) {
    ref.circular = true
    return ref
  }

  const maxDepth = typeof opts.depth === 'number' ? opts.depth : Infinity

  if (maxDepth < depth) {
    const constructor = object.constructor

    return new InspectLeaf(
      '[' +
        (constructor && constructor.name ? constructor.name : 'Object') +
        ']',
      styles.special,
      depth,
      opts
    )
  }

  const inspect =
    object[Symbol.for('bare.inspect')] ||
    object[Symbol.for('nodejs.util.inspect.custom')]

  if (typeof inspect === 'function') {
    const value = inspect.call(
      object,
      typeof opts.depth === 'number' ? opts.depth - depth : null,
      {
        colors: opts.colors,
        breakLength: opts.breakLength,
        stylize: opts.stylize
      },
      exports
    )

    if (typeof value === 'object' && value !== null) {
      refs.set(value, ref)
    }

    if (typeof value !== 'string') {
      return inspectValue(value, depth, opts)
    }

    return new InspectLeaf(value, null, depth, opts)
  }

  if (type.isArray()) return inspectArray(object, ref, depth, opts)
  if (type.isDate()) return inspectDate(object, ref, depth, opts)
  if (type.isRegExp()) return inspectRegExp(object, ref, depth, opts)
  if (type.isError()) return inspectError(object, ref, depth, opts)
  if (type.isPromise()) return inspectPromise(object, ref, depth, opts)
  if (type.isMap()) return inspectMap(object, ref, depth, opts)
  if (type.isSet()) return inspectSet(object, ref, depth, opts)
  if (type.isWeakMap()) return inspectWeakMap(object, ref, depth, opts)
  if (type.isWeakSet()) return inspectWeakSet(object, ref, depth, opts)
  if (type.isWeakRef()) return inspectWeakRef(object, ref, depth, opts)
  if (type.isArrayBuffer()) return inspectArrayBuffer(object, ref, depth, opts)
  if (type.isSharedArrayBuffer())
    return inspectSharedArrayBuffer(object, ref, depth, opts)
  if (type.isTypedArray()) return inspectTypedArray(object, ref, depth, opts)
  if (type.isDataView()) return inspectDataView(object, ref, depth, opts)

  ref.increment()

  const values = []

  for (const key in object) {
    if (key === 'constructor') continue

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(object[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  let header = '{ '

  const tag = object[Symbol.toStringTag]

  if (tag) header = '[' + tag + '] ' + header

  if (object.constructor) {
    const name = object.constructor.name

    if (name && name !== 'Object') {
      header = object.constructor.name + ' ' + header
    }
  }

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectArray(array, ref, depth, opts) {
  const { maxArrayLength = defaultMaxArrayLength } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxArrayLength, 0)

  for (let i = 0, n = array.length; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(array.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(inspectValue(array[i], depth + 1, opts))
  }

  for (const key of binding.getOwnNonIndexPropertyNames(array)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(array[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  let header = '[ '

  if (array.constructor.name !== 'Array') {
    header = array.constructor.name + '(' + array.length + ') ' + header
  }

  return new InspectSequence(header, ' ]', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectDate(date, ref, depth, opts) {
  return new InspectLeaf(date.toISOString(), styles.date, depth, opts)
}

function inspectRegExp(regExp, ref, depth, opts) {
  return new InspectLeaf(regExp.toString(), styles.regexp, depth, opts)
}

function inspectError(error, ref, depth, opts) {
  let header

  if ('stack' in error) {
    header = error.stack

    if (depth > 0) {
      header = header.replaceAll('\n', '\n' + '  '.repeat(depth))
    }
  } else {
    header = error.toString()
  }

  const builtins = ['cause']

  if (error.name === 'AggregateError') {
    builtins.push('errors')
  } else if (error.name === 'SuppressedError') {
    builtins.push('error', 'suppressed')
  }

  const values = []

  for (const key of builtins) {
    if (key in error === false) continue

    values.push(
      new InspectPair(
        ': ',
        new InspectLeaf('[' + key + ']', null, depth + 1, opts),
        inspectValue(error[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key in error) {
    if (key === 'constructor' || builtins.includes(key)) continue

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(error[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  if (values.length === 0) return new InspectLeaf(header, null, depth, opts)

  return new InspectSequence(
    header + ' {',
    ' }',
    ', ',
    values,
    ref,
    depth,
    opts
  )
}

function inspectPromise(promise, ref, depth, opts) {
  ref.increment()

  const state = binding.getPromiseState(promise)

  const values = []

  switch (state) {
    case 0: // Pending
      values.push(new InspectLeaf('<pending>', styles.special, depth, opts))
      break

    case 1: // Fulfilled
      values.push(inspectValue(binding.getPromiseResult(promise), depth, opts))
      break

    case 2: // Rejected
      values.push(
        new InspectLeaf('<rejected>', styles.special, depth, opts),
        inspectValue(binding.getPromiseResult(promise), depth, opts)
      )
  }

  ref.decrement()

  const header = promise.constructor.name + ' { '

  return new InspectSequence(header, ' }', ' ', values, ref, depth, opts)
}

function inspectMap(map, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxMapLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = maxMapLength

  for (const entry of map) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(map.size - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )
      break
    }

    values.push(
      new InspectPair(
        ' => ',
        inspectValue(entry[0], depth + 1, opts),
        inspectValue(entry[1], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key in map) {
    if (key === 'constructor') continue

    const value = inspectValue(map[key], depth + 1, opts)

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        value,
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = map.constructor.name + '(' + map.size + ') { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectSet(set, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxSetLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = maxSetLength

  for (const entry of set) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(set.size - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )
      break
    }

    values.push(inspectValue(entry, depth + 1, opts))
  }

  for (const key in set) {
    if (key === 'constructor') continue

    const value = inspectValue(set[key], depth + 1, opts)

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        value,
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = set.constructor.name + '(' + set.size + ') { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectWeakMap(weakMap, ref, depth, opts) {
  const header = weakMap.constructor.name + ' { '

  return new InspectSequence(
    header,
    ' }',
    ' ',
    [new InspectLeaf('<items unknown>', styles.special, depth + 1, opts)],
    ref,
    depth,
    opts
  )
}

function inspectWeakSet(weakSet, ref, depth, opts) {
  const header = weakSet.constructor.name + ' { '

  return new InspectSequence(
    header,
    ' }',
    ' ',
    [new InspectLeaf('<items unknown>', styles.special, depth + 1, opts)],
    ref,
    depth,
    opts
  )
}

function inspectWeakRef(weakRef, ref, depth, opts) {
  const target = weakRef.deref()

  let value

  if (target === undefined) {
    value = new InspectLeaf('<cleared>', styles.special, depth + 1, opts)
  } else {
    value = inspectValue(target, depth + 1, opts)
  }

  const header = weakRef.constructor.name + ' { '

  return new InspectSequence(header, ' }', ' ', [value], ref, depth, opts)
}

function inspectArrayBuffer(arrayBuffer, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(arrayBuffer[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = arrayBuffer.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectSharedArrayBuffer(sharedArrayBuffer, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(sharedArrayBuffer[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = sharedArrayBuffer.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectTypedArray(typedArray, ref, depth, opts) {
  if (Buffer.isBuffer(typedArray)) {
    return inspectBuffer(typedArray, ref, depth, opts)
  }

  const {
    maxArrayLength = defaultMaxArrayLength,
    maxTypedArrayLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxTypedArrayLength, 0)

  for (let i = 0, n = typedArray.length; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(typedArray.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(inspectValue(typedArray[i], depth + 1, opts))
  }

  for (const key of binding.getOwnNonIndexPropertyNames(typedArray)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(typedArray[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = typedArray.constructor.name + '(' + typedArray.length + ') [ '

  return new InspectSequence(header, ' ]', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectBuffer(buffer, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxBufferLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxBufferLength, 0)

  for (let i = 0, n = buffer.byteLength; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(buffer.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(
      new InspectLeaf(
        buffer[i].toString(16).padStart(2, '0'),
        null,
        depth + 1,
        opts
      )
    )
  }

  for (const key of binding.getOwnNonIndexPropertyNames(buffer)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(buffer[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  return new InspectSequence('<Buffer ', '>', ' ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectDataView(dataView, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength', 'byteOffset', 'buffer']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(dataView[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key of binding.getOwnNonIndexPropertyNames(dataView)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(dataView[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = dataView.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectFunction(type, fn, depth, opts) {
  if (fn.toString().startsWith('class')) return inspectClass(fn, depth, opts)

  let tag = 'function'

  if (type.isGeneratorFunction()) tag = 'generator ' + tag
  if (type.isAsyncFunction()) tag = 'async ' + tag

  return new InspectLeaf(
    '[' + tag + ' ' + (fn.name ? fn.name : '(anonymous)') + ']',
    styles.special,
    depth,
    opts
  )
}

function inspectClass(ctor, depth, opts) {
  return new InspectLeaf(
    '[class ' + (ctor.name ? ctor.name : '(anonymous)') + ']',
    styles.special,
    depth,
    opts
  )
}

function inspectExternal(external, depth, opts) {
  return new InspectLeaf(
    '[external 0x' + binding.getExternal(external).toString(16) + ']',
    styles.special,
    depth,
    opts
  )
}
{
  "name": "bare-inspect",
  "version": "3.1.4",
  "description": "Inspect objects as strings for debugging",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-inspect.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-inspect/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-inspect#readme",
  "engines": {
    "bare": ">=1.18.0"
  },
  "dependencies": {
    "bare-ansi-escapes": "^2.1.0",
    "bare-type": "^1.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
class MIME {
  constructor(type, subtype, parameters = new Map()) {
    this._type = type
    this._subtype = subtype
    this._parameters = parameters
  }

  // https://mimesniff.spec.whatwg.org/#type
  get type() {
    return this._type
  }

  // https://mimesniff.spec.whatwg.org/#subtype
  get subtype() {
    return this._subtype
  }

  // https://mimesniff.spec.whatwg.org/#parameters
  get parameters() {
    return this._parameters
  }
}

module.exports = exports = MIME

// https://mimesniff.spec.whatwg.org/#parse-a-mime-type
exports.parse = function parse(input) {
  // 1.
  input = input.replace(httpWhitespaceLeadingAndTrailing, '')

  // 2.
  let position = 0

  // 3.
  let type = ''

  while (position < input.length && input[position] !== '/') {
    type += input[position++]
  }

  // 4.
  if (type === '' || !isHTTPTokenCodePoints(type)) return null

  // 5.
  if (position >= input.length) return null

  // 6.
  position++

  // 7.
  let subtype = ''

  while (position < input.length && input[position] !== ';') {
    subtype += input[position++]
  }

  // 8.
  subtype = subtype.replace(httpWhitespaceTrailing, '')

  // 9.
  if (subtype === '' || !isHTTPTokenCodePoints(subtype)) return null

  // 10.
  const mimeType = new MIME(type.toLowerCase(), subtype.toLowerCase())

  // 11.
  while (position < input.length) {
    // 11.1.
    position++

    // 11.2.
    while (position < input.length && httpWhitespace.test(input[position])) {
      position++
    }

    // 11.3.
    let parameterName = ''

    while (position < input.length && input[position] !== ';' && input[position] !== '=') {
      parameterName += input[position++]
    }

    // 11.4.
    parameterName = parameterName.toLowerCase()

    // 11.5.
    if (position < input.length && input[position] === ';') continue

    // 11.6.
    if (position >= input.length) break

    // 11.7.
    position++

    // 11.8.
    let parameterValue

    // 11.9.
    if (position < input.length && input[position] === '"') {
      // 11.9.1.
      parameterValue = collectHTTPQuotedString(input, position)
      position = parameterValue.position
      parameterValue = parameterValue.value

      // 11.9.2.
      while (position < input.length && input[position] !== ';') {
        position++
      }
    } else {
      // 11.10.
      parameterValue = ''

      while (position < input.length && input[position] !== ';') {
        parameterValue += input[position++]
      }

      // 11.10.1.
      parameterValue = parameterValue.replace(httpWhitespaceTrailing, '')

      // 11.10.2.
      if (parameterValue === '') continue
    }

    // 11.11.
    if (
      parameterName !== '' &&
      isHTTPTokenCodePoints(parameterName) &&
      isHTTPQuotedStringTokenCodePoints(parameterValue) &&
      !mimeType._parameters.has(parameterName)
    ) {
      mimeType._parameters.set(parameterName, parameterValue)
    }
  }

  // 12.
  return mimeType
}

// https://fetch.spec.whatwg.org/#http-whitespace
const httpWhitespace = /[\t\n\r ]/
const httpWhitespaceLeadingAndTrailing = /^[\t\n\r ]+|[\t\n\r ]+$/g
const httpWhitespaceTrailing = /[\t\n\r ]+$/

// https://mimesniff.spec.whatwg.org/#http-token-code-point
const httpTokenCodePoints = /^[!#$%&'*+\-.^_`|~A-Za-z0-9]+$/

// https://mimesniff.spec.whatwg.org/#http-quoted-string-token-code-point
const httpQuotedStringTokenCodePoints = /^[\t\x20-\x7e\x80-\xff]*$/

function isHTTPTokenCodePoints(s) {
  return httpTokenCodePoints.test(s)
}

function isHTTPQuotedStringTokenCodePoints(s) {
  return httpQuotedStringTokenCodePoints.test(s)
}

// https://fetch.spec.whatwg.org/#collect-an-http-quoted-string
function collectHTTPQuotedString(input, position) {
  let value = ''

  position++

  while (true) {
    while (position < input.length && input[position] !== '"' && input[position] !== '\\') {
      value += input[position++]
    }

    if (position >= input.length) break

    const quoteOrBackslash = input[position++]

    if (quoteOrBackslash === '\\') {
      if (position >= input.length) {
        value += '\\'
        break
      }
      value += input[position++]
    } else {
      break
    }
  }

  return { value, position }
}
{
  "name": "bare-mime",
  "version": "1.0.0",
  "description": "MIME type parsing for Bare",
  "exports": {
    "./package": "./package.json",
    ".": "./index.js"
  },
  "files": [
    "index.js"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-mime.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-mime/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-mime#readme",
  "devDependencies": {
    "brittle": "^3.3.0",
    "lunte": "^1.6.0",
    "prettier": "^3.3.3",
    "prettier-config-holepunch": "^2.0.0"
  }
}
const EventEmitter = require('bare-events')
const { Duplex } = require('bare-stream')
const tcp = require('bare-tcp')
const pipe = require('bare-pipe')
const constants = require('./lib/constants')

const defaultReadBufferSize = 65536

exports.Socket = class NetSocket extends Duplex {
  constructor(opts = {}) {
    const {
      readBufferSize = defaultReadBufferSize,
      allowHalfOpen = false,
      eagerOpen = false
    } = opts

    super({ eagerOpen, allowHalfOpen })

    this._type = 0
    this._state = 0
    this._socket = null

    this._opts = { readBufferSize, allowHalfOpen, eagerOpen }

    this._pendingOpen = null
    this._pendingWrite = null
    this._pendingFinal = null
    this._pendingDestroy = null
  }

  get connecting() {
    return this._socket !== null && this._socket.connecting
  }

  get pending() {
    return this._socket === null || this._socket.pending
  }

  get timeout() {
    return this._socket === null ? undefined : this._socket.timeout
  }

  get readyState() {
    return this._socket === null ? 'opening' : this._socket.readyState
  }

  get localAddress() {
    return this._socket === null ? undefined : this._socket.localAddress
  }

  get localPort() {
    return this._socket === null ? undefined : this._socket.localPort
  }

  get localFamily() {
    return this._socket === null ? undefined : this._socket.localFamily
  }

  get remoteAddress() {
    return this._socket === null ? undefined : this._socket.remoteAddress
  }

  get remotePort() {
    return this._socket === null ? undefined : this._socket.remotePort
  }

  get remoteFamily() {
    return this._socket === null ? undefined : this._socket.remoteFamily
  }

  connect(...args) {
    let opts = {}
    let onconnect

    if (typeof args[0] === 'string') {
      // connect(path[, onconnect])
      opts.path = args[0]
      onconnect = args[1]
    } else if (typeof args[0] === 'number') {
      // connect(port[, host][, onconnect])
      opts.port = args[0]

      if (typeof args[1] === 'function') {
        onconnect = args[1]
      } else {
        opts.host = args[1]
        onconnect = args[2]
      }
    } else {
      // connect(opts[, onconnect])
      opts = args[0] || {}
      onconnect = args[1]
    }

    opts = { ...opts, ...this._opts }

    if (opts.path) {
      this._attach(constants.type.IPC, pipe.createConnection(opts))
    } else {
      this._attach(constants.type.TCP, tcp.createConnection(opts))
    }

    if (onconnect) this.once('connect', onconnect)

    return this
  }

  setKeepAlive(...args) {
    if (this._socket !== null) this._socket.setKeepAlive(...args)
    return this
  }

  setNoDelay(...args) {
    if (this._socket !== null) this._socket.setNoDelay(...args)
    return this
  }

  setTimeout(...args) {
    if (this._socket !== null) this._socket.setTimeout(...args)
    return this
  }

  ref() {
    this._state &= ~constants.state.UNREFED
    if (this._socket !== null) this._socket.ref()
    return this
  }

  unref() {
    this._state |= constants.state.UNREFED
    if (this._socket !== null) this._socket.unref()
    return this
  }

  _attach(type, socket) {
    this._type = type
    this._socket = socket

    this._socket
      .on('connect', this._onconnect.bind(this))
      .on('timeout', this._ontimeout.bind(this))
      .on('error', this._onerror.bind(this))
      .on('data', this._ondata.bind(this))
      .on('end', this._onend.bind(this))
      .on('finish', this._onfinish.bind(this))
      .on('drain', this._ondrain.bind(this))
      .on('close', this._onclose.bind(this))

    if (this._state & constants.state.UNREFED) this._socket.unref()

    this._continueOpen()

    return this
  }

  _open(cb) {
    if (this._socket !== null) return cb(null)
    this._pendingOpen = cb
  }

  _write(data, encoding, cb) {
    if (this._socket.write(data)) return cb(null)
    this._pendingWrite = cb
  }

  _final(cb) {
    this._socket.end()
    this._pendingFinal = cb
  }

  _destroy(err, cb) {
    if (this._socket === null || this._socket.destroyed) return cb(null)

    this._socket.destroy(err)
    this._pendingDestroy = cb
  }

  _onconnect() {
    this.emit('connect')
  }

  _ontimeout() {
    this.emit('timeout')
  }

  _onerror(err) {
    this.destroy(err)
  }

  _ondata(data) {
    this.push(data)
  }

  _onend() {
    this.push(null)
  }

  _onfinish() {
    this._continueFinal()
  }

  _ondrain() {
    this._continueWrite()
  }

  _onclose() {
    this._continueWrite()
    this._continueFinal()

    if (this._pendingDestroy) this._continueDestroy()
    else this.destroy()
  }

  _continueOpen() {
    if (this._pendingOpen === null) return
    const cb = this._pendingOpen
    this._pendingOpen = null
    cb(null)
  }

  _continueWrite() {
    if (this._pendingWrite === null) return
    const cb = this._pendingWrite
    this._pendingWrite = null
    cb(null)
  }

  _continueFinal() {
    if (this._pendingFinal === null) return
    const cb = this._pendingFinal
    this._pendingFinal = null
    cb(null)
  }

  _continueDestroy() {
    if (this._pendingDestroy === null) return
    const cb = this._pendingDestroy
    this._pendingDestroy = null
    cb(null)
  }
}

exports.Server = class NetServer extends EventEmitter {
  constructor(opts = {}, onconnection) {
    if (typeof opts === 'function') {
      onconnection = opts
      opts = {}
    }

    super()

    const {
      readBufferSize = defaultReadBufferSize,
      allowHalfOpen = false,
      pauseOnConnect = false
    } = opts

    this._type = 0
    this._state = 0
    this._server = null

    this._opts = { readBufferSize, allowHalfOpen, pauseOnConnect }

    if (onconnection) this.on('connection', onconnection)
  }

  get listening() {
    return this._server !== null && this._server.listening
  }

  address() {
    return this._server === null ? null : this._server.address()
  }

  listen(...args) {
    let opts = {}
    let onlistening

    if (typeof args[0] === 'string') {
      // listen(path[, backlog][, onlistening])
      opts.path = args[0]

      if (typeof args[1] === 'function') {
        onlistening = args[1]
      } else {
        opts.backlog = args[1]
        onlistening = args[2]
      }
    } else {
      // listen([port[, host[, backlog]]][, onlistening])
      if (typeof args[0] === 'function') {
        onlistening = args[0]
      } else {
        opts.port = args[0]

        if (typeof args[1] === 'function') {
          onlistening = args[1]
        } else {
          opts.host = args[1]

          if (typeof args[2] === 'function') {
            onlistening = args[2]
          } else {
            opts.backlog = args[2]
            onlistening = args[3]
          }
        }
      }
    }

    opts = { ...opts, ...this._opts }

    if (opts.path) {
      this._attach(constants.type.IPC, pipe.createServer(opts))
    } else {
      this._attach(constants.type.TCP, tcp.createServer(opts))
    }

    this._server.listen(opts)

    if (onlistening) this.once('listening', onlistening)

    return this
  }

  close(onclose) {
    if (onclose) this.once('close', onclose)
    this._server.close()
    return this
  }

  ref() {
    this._state &= ~constants.state.UNREFED
    if (this._server !== null) this._server.ref()
    return this
  }

  unref() {
    this._state |= constants.state.UNREFED
    if (this._server !== null) this._server.unref()
    return this
  }

  _attach(type, server) {
    this._type = type
    this._server = server

    this._server
      .on('listening', this._onlistening.bind(this))
      .on('connection', this._onconnection.bind(this))
      .on('error', this._onerror.bind(this))
      .on('close', this._onclose.bind(this))

    if (this._state & constants.state.UNREFED) this._server.unref()

    return this
  }

  _onlistening() {
    this.emit('listening')
  }

  _onconnection(socket) {
    this.emit('connection', new exports.Socket(this._opts)._attach(this._type, socket))
  }

  _onerror(err) {
    this.emit('error', err)
  }

  _onclose() {
    this.emit('close')
  }
}

exports.constants = constants

exports.isIP = tcp.isIP
exports.isIPv4 = tcp.isIPv4
exports.isIPv6 = tcp.isIPv6

exports.createConnection = function createConnection(...args) {
  let opts = {}
  let onconnect

  if (typeof args[0] === 'string') {
    // createConnection(path[, onconnect])
    opts.path = args[0]
    onconnect = args[1]
  } else if (typeof args[0] === 'number') {
    // createConnection(port[, host][, onconnect])
    opts.port = args[0]

    if (typeof args[1] === 'function') {
      onconnect = args[1]
    } else {
      opts.host = args[1]
      onconnect = args[2]
    }
  } else {
    // createConnection(opts[, onconnect])
    opts = args[0] || {}
    onconnect = args[1]
  }

  return new exports.Socket(opts).connect(opts, onconnect)
}

// For Node.js compatibility
exports.connect = exports.createConnection

exports.createServer = function createServer(opts, onconnection) {
  return new exports.Server(opts, onconnection)
}
module.exports = {
  type: {
    TCP: 1,
    IPC: 2
  },
  state: {
    UNREFED: 0x1
  }
}
{
  "name": "bare-net",
  "version": "2.3.2",
  "description": "TCP and IPC servers and clients for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-net.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-net/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-net#readme",
  "dependencies": {
    "bare-events": "^2.2.2",
    "bare-pipe": "^4.0.0",
    "bare-stream": "^2.0.0",
    "bare-tcp": "^2.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.0",
    "lunte": "^1.8.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = require.addon()
const binding = require('./binding')
const errors = require('./lib/errors')
const constants = require('./lib/constants')

exports.constants = constants
exports.errors = errors

exports.EOL = binding.platform === 'win32' ? '\r\n' : '\n'

exports.devNull = binding.platform === 'win32' ? '\\\\.\\nul' : '/dev/null'

exports.platform = function platform() {
  return binding.platform
}

exports.arch = function arch() {
  return binding.arch
}

exports.type = function type() {
  return binding.type()
}

exports.version = function version() {
  return binding.version()
}

exports.release = function release() {
  return binding.release()
}

exports.machine = function machine() {
  return binding.machine()
}

exports.execPath = function execPath() {
  return binding.execPath()
}

exports.pid = function pid() {
  return binding.pid()
}

exports.ppid = function ppid() {
  return binding.ppid()
}

exports.cwd = function cwd() {
  return binding.cwd()
}

exports.chdir = function chdir(dir) {
  validateString(dir, 'Directory')

  binding.chdir(dir)
}

exports.tmpdir = function tmpdir() {
  return binding.tmpdir()
}

exports.homedir = function homedir() {
  return binding.homedir()
}

exports.hostname = function hostname() {
  return binding.hostname()
}

exports.userInfo = function userInfo(uid) {
  if (uid !== undefined) validateInteger(uid, 'User ID')

  return binding.userInfo(uid)
}

exports.groupInfo = function groupInfo(gid) {
  if (gid !== undefined) validateInteger(gid, 'Group ID')

  return binding.groupInfo(gid)
}

exports.networkInterfaces = function networkInterfaces() {
  const result = {}

  for (const entry of binding.networkInterfaces()) {
    const { name, ...properties } = entry

    if (result[name]) result[name].push(properties)
    else result[name] = [properties]
  }

  return result
}

exports.kill = function kill(pid, signal = constants.signals.SIGTERM) {
  validateInteger(pid, 'Process ID')

  if (typeof signal === 'string') {
    if (signal in constants.signals === false) {
      throw errors.UNKNOWN_SIGNAL('Unknown signal: ' + signal)
    }

    signal = constants.signals[signal]
  } else {
    validateInteger(signal, 'Signal')
  }

  binding.kill(pid, signal)
}

exports.endianness = function endianness() {
  return binding.isLittleEndian ? 'LE' : 'BE'
}

exports.availableParallelism = function availableParallelism() {
  return binding.availableParallelism()
}

exports.cpuUsage = function cpuUsage(previous) {
  const current = binding.cpuUsage()

  if (previous) {
    return {
      user: current.user - previous.user,
      system: current.system - previous.system
    }
  }

  return current
}

exports.threadCpuUsage = function threadCpuUsage(previous) {
  const current = binding.threadCpuUsage()

  if (previous) {
    return {
      user: current.user - previous.user,
      system: current.system - previous.system
    }
  }

  return current
}

exports.resourceUsage = function resourceUsage() {
  return binding.resourceUsage()
}

exports.memoryUsage = function memoryUsage() {
  return binding.memoryUsage()
}

exports.freemem = function freemem() {
  return binding.freemem()
}

exports.totalmem = function totalmem() {
  return binding.totalmem()
}

exports.availableMemory = function availableMemory() {
  return binding.availableMemory()
}

exports.constrainedMemory = function constrainedMemory() {
  return binding.constrainedMemory()
}

exports.uptime = function uptime() {
  return binding.uptime()
}

exports.loadavg = function loadavg() {
  return binding.loadavg()
}

exports.cpus = function cpus() {
  return binding.cpus()
}

exports.getProcessTitle = function getProcessTitle() {
  return binding.getProcessTitle()
}

exports.setProcessTitle = function setProcessTitle(title) {
  if (typeof title !== 'string') title = title.toString()

  if (title.length >= 256) {
    throw errors.TITLE_OVERFLOW('Process title is too long')
  }

  binding.setProcessTitle(title)
}

exports.getPriority = function getPriority(pid = 0) {
  validateInteger(pid, 'Process ID')

  return binding.getPriority(pid)
}

exports.setPriority = function setPriority(pid, priority) {
  if (priority === undefined) {
    priority = pid
    pid = 0
  }

  validateInteger(pid, 'Process ID')
  validateInteger(priority, 'Priority')

  binding.setPriority(pid, priority)
}

exports.getEnvKeys = function getEnvKeys() {
  return binding.getEnvKeys()
}

exports.getEnv = function getEnv(name) {
  validateString(name, 'Name')

  return binding.getEnv(name)
}

exports.hasEnv = function hasEnv(name) {
  validateString(name, 'Name')

  return binding.hasEnv(name)
}

exports.setEnv = function setEnv(name, value) {
  validateString(name, 'Name')
  validateString(value, 'Value')

  binding.setEnv(name, value)
}

exports.unsetEnv = function unsetEnv(name) {
  validateString(name, 'Name')

  binding.unsetEnv(name)
}

function validateString(value, name) {
  if (typeof value !== 'string') {
    throw new TypeError(`${name} must be a string. Received type ${typeof value} (${value})`)
  }
}

function validateInteger(value, name) {
  if (!Number.isInteger(value)) {
    throw new TypeError(`${name} must be an integer. Received type ${typeof value} (${value})`)
  }
}
const binding = require('../binding')

module.exports = {
  signals: binding.signals,
  errnos: binding.errnos,
  priority: binding.priority
}
module.exports = class OSError extends Error {
  constructor(msg, fn = OSError, code = fn.name) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'OSError'
  }

  static UNKNOWN_SIGNAL(msg) {
    return new OSError(msg, OSError.UNKNOWN_SIGNAL)
  }

  static TITLE_OVERFLOW(msg) {
    return new OSError(msg, OSError.TITLE_OVERFLOW)
  }
}
{
  "name": "bare-os",
  "version": "3.9.3",
  "description": "Operating system utilities for Bare",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    },
    "./errors": {
      "types": "./lib/errors.d.ts",
      "default": "./lib/errors.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-os.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-os/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-os#readme",
  "engines": {
    "bare": ">=1.14.0"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "cmake-bare": "^1.1.6",
    "lunte": "^1.6.0",
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = require.addon()
// This export SHOULD NOT be shortened in any way as having the full
// `module.exports = require(...)` statement is crucial for synthesizing
// ESM exports.

if (Bare.platform === 'win32') {
  module.exports = require('./lib/win32')
} else {
  module.exports = require('./lib/posix')
}
module.exports = {
  CHAR_UPPERCASE_A: 0x41,
  CHAR_LOWERCASE_A: 0x61,
  CHAR_UPPERCASE_Z: 0x5a,
  CHAR_LOWERCASE_Z: 0x7a,
  CHAR_DOT: 0x2e,
  CHAR_FORWARD_SLASH: 0x2f,
  CHAR_BACKWARD_SLASH: 0x5c,
  CHAR_COLON: 0x3a,
  CHAR_QUESTION_MARK: 0x3f
}
const binding = require('../binding')

const { normalizeString, validateString } = require('./shared')
const { CHAR_DOT, CHAR_FORWARD_SLASH } = require('./constants')

function isPosixPathSeparator(code) {
  return code === CHAR_FORWARD_SLASH
}

exports.win32 = require('./win32')
exports.posix = exports

exports.sep = '/'
exports.delimiter = ':'

exports.resolve = function resolve(...args) {
  let resolvedPath = ''
  let resolvedAbsolute = false

  for (let i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) {
    const path = i >= 0 ? args[i] : binding.cwd()

    if (i >= 0) validateString(path, `paths[${i}]`)

    if (path.length === 0) {
      continue
    }

    resolvedPath = `${path}/${resolvedPath}`
    resolvedAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH
  }

  resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute, '/', isPosixPathSeparator)

  if (resolvedAbsolute) {
    return `/${resolvedPath}`
  }

  return resolvedPath.length > 0 ? resolvedPath : '.'
}

exports.normalize = function normalize(path) {
  validateString(path, 'path')

  if (path.length === 0) return '.'

  const isAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH
  const trailingSeparator = path.charCodeAt(path.length - 1) === CHAR_FORWARD_SLASH

  path = normalizeString(path, !isAbsolute, '/', isPosixPathSeparator)

  if (path.length === 0) {
    if (isAbsolute) return '/'
    return trailingSeparator ? './' : '.'
  }

  if (trailingSeparator) path += '/'

  return isAbsolute ? `/${path}` : path
}

exports.isAbsolute = function isAbsolute(path) {
  validateString(path, 'path')

  return path.length > 0 && path.charCodeAt(0) === CHAR_FORWARD_SLASH
}

exports.join = function join(...args) {
  if (args.length === 0) return '.'
  let joined
  for (let i = 0; i < args.length; ++i) {
    const arg = args[i]
    validateString(arg, 'path')
    if (arg.length > 0) {
      if (joined === undefined) joined = arg
      else joined += `/${arg}`
    }
  }
  if (joined === undefined) return '.'
  return exports.normalize(joined)
}

exports.relative = function relative(from, to) {
  validateString(from, 'from')
  validateString(to, 'to')

  if (from === to) return ''

  from = exports.resolve(from)
  to = exports.resolve(to)

  if (from === to) return ''

  const fromStart = 1
  const fromEnd = from.length
  const fromLen = fromEnd - fromStart
  const toStart = 1
  const toLen = to.length - toStart

  const length = fromLen < toLen ? fromLen : toLen
  let lastCommonSep = -1
  let i = 0
  for (; i < length; i++) {
    const fromCode = from.charCodeAt(fromStart + i)
    if (fromCode !== to.charCodeAt(toStart + i)) {
      break
    } else if (fromCode === CHAR_FORWARD_SLASH) {
      lastCommonSep = i
    }
  }
  if (i === length) {
    if (toLen > length) {
      if (to.charCodeAt(toStart + i) === CHAR_FORWARD_SLASH) {
        return to.substring(toStart + i + 1)
      }
      if (i === 0) {
        return to.substring(toStart + i)
      }
    } else if (fromLen > length) {
      if (from.charCodeAt(fromStart + i) === CHAR_FORWARD_SLASH) {
        lastCommonSep = i
      } else if (i === 0) {
        lastCommonSep = 0
      }
    }
  }

  let out = ''
  for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
    if (i === fromEnd || from.charCodeAt(i) === CHAR_FORWARD_SLASH) {
      out += out.length === 0 ? '..' : '/..'
    }
  }

  return `${out}${to.substring(toStart + lastCommonSep)}`
}

exports.toNamespacedPath = function toNamespacedPath(path) {
  return path
}

exports.dirname = function dirname(path) {
  validateString(path, 'path')

  if (path.length === 0) return '.'
  const hasRoot = path.charCodeAt(0) === CHAR_FORWARD_SLASH
  let end = -1
  let matchedSlash = true
  for (let i = path.length - 1; i >= 1; --i) {
    if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) {
      if (!matchedSlash) {
        end = i
        break
      }
    } else {
      matchedSlash = false
    }
  }

  if (end === -1) return hasRoot ? '/' : '.'
  if (hasRoot && end === 1) return '//'
  return path.substring(0, end)
}

exports.basename = function basename(path, suffix) {
  if (suffix !== undefined) validateString(suffix, 'suffix')
  validateString(path, 'path')

  let start = 0
  let end = -1
  let matchedSlash = true

  if (suffix !== undefined && suffix.length > 0 && suffix.length <= path.length) {
    if (suffix === path) {
      return ''
    }
    let extIdx = suffix.length - 1
    let firstNonSlashEnd = -1
    for (let i = path.length - 1; i >= 0; --i) {
      const code = path.charCodeAt(i)
      if (code === CHAR_FORWARD_SLASH) {
        if (!matchedSlash) {
          start = i + 1
          break
        }
      } else {
        if (firstNonSlashEnd === -1) {
          matchedSlash = false
          firstNonSlashEnd = i + 1
        }
        if (extIdx >= 0) {
          if (code === suffix.charCodeAt(extIdx)) {
            if (--extIdx === -1) {
              end = i
            }
          } else {
            extIdx = -1
            end = firstNonSlashEnd
          }
        }
      }
    }

    if (start === end) end = firstNonSlashEnd
    else if (end === -1) end = path.length
    return path.substring(start, end)
  }

  for (let i = path.length - 1; i >= 0; --i) {
    if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) {
      if (!matchedSlash) {
        start = i + 1
        break
      }
    } else if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
  }

  if (end === -1) return ''
  return path.substring(start, end)
}

exports.extname = function extname(path) {
  validateString(path, 'path')

  let startDot = -1
  let startPart = 0
  let end = -1
  let matchedSlash = true
  let preDotState = 0
  for (let i = path.length - 1; i >= 0; --i) {
    const code = path.charCodeAt(i)
    if (code === CHAR_FORWARD_SLASH) {
      if (!matchedSlash) {
        startPart = i + 1
        break
      }
      continue
    }
    if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
    if (code === CHAR_DOT) {
      if (startDot === -1) startDot = i
      else if (preDotState !== 1) preDotState = 1
    } else if (startDot !== -1) {
      preDotState = -1
    }
  }

  if (
    startDot === -1 ||
    end === -1 ||
    preDotState === 0 ||
    (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1)
  ) {
    return ''
  }
  return path.substring(startDot, end)
}
const { CHAR_DOT, CHAR_FORWARD_SLASH } = require('./constants')

exports.validateString = function validateString(value, name) {
  if (typeof value !== 'string') {
    throw new TypeError(
      `The "${name}" argument must be of type string. Received type ${typeof value}`
    )
  }
}

exports.normalizeString = function normalizeString(
  path,
  allowAboveRoot,
  separator,
  isPathSeparator
) {
  let res = ''
  let lastSegmentLength = 0
  let lastSlash = -1
  let dots = 0
  let code = 0
  for (let i = 0; i <= path.length; ++i) {
    if (i < path.length) {
      code = path.charCodeAt(i)
    } else if (isPathSeparator(code)) {
      break
    } else {
      code = CHAR_FORWARD_SLASH
    }

    if (isPathSeparator(code)) {
      if (lastSlash === i - 1 || dots === 1);
      else if (dots === 2) {
        if (
          res.length < 2 ||
          lastSegmentLength !== 2 ||
          res.charCodeAt(res.length - 1) !== CHAR_DOT ||
          res.charCodeAt(res.length - 2) !== CHAR_DOT
        ) {
          if (res.length > 2) {
            const lastSlashIndex = res.lastIndexOf(separator)
            if (lastSlashIndex === -1) {
              res = ''
              lastSegmentLength = 0
            } else {
              res = res.substring(0, lastSlashIndex)
              lastSegmentLength = res.length - 1 - res.lastIndexOf(separator)
            }
            lastSlash = i
            dots = 0
            continue
          } else if (res.length !== 0) {
            res = ''
            lastSegmentLength = 0
            lastSlash = i
            dots = 0
            continue
          }
        }
        if (allowAboveRoot) {
          res += res.length > 0 ? `${separator}..` : '..'
          lastSegmentLength = 2
        }
      } else {
        if (res.length > 0) {
          res += `${separator}${path.substring(lastSlash + 1, i)}`
        } else {
          res = path.substring(lastSlash + 1, i)
        }
        lastSegmentLength = i - lastSlash - 1
      }
      lastSlash = i
      dots = 0
    } else if (code === CHAR_DOT && dots !== -1) {
      ++dots
    } else {
      dots = -1
    }
  }
  return res
}
const binding = require('../binding')

const { normalizeString, validateString } = require('./shared')
const {
  CHAR_UPPERCASE_A,
  CHAR_LOWERCASE_A,
  CHAR_UPPERCASE_Z,
  CHAR_LOWERCASE_Z,
  CHAR_DOT,
  CHAR_FORWARD_SLASH,
  CHAR_BACKWARD_SLASH,
  CHAR_COLON,
  CHAR_QUESTION_MARK
} = require('./constants')

function isWindowsPathSeparator(code) {
  return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH
}

function isWindowsDeviceRoot(code) {
  return (
    (code >= CHAR_UPPERCASE_A && code <= CHAR_UPPERCASE_Z) ||
    (code >= CHAR_LOWERCASE_A && code <= CHAR_LOWERCASE_Z)
  )
}

exports.posix = require('./posix')
exports.win32 = exports

exports.sep = '\\'
exports.delimiter = ';'

exports.resolve = function resolve(...args) {
  let resolvedDevice = ''
  let resolvedTail = ''
  let resolvedAbsolute = false

  for (let i = args.length - 1; i >= -1; i--) {
    let path
    if (i >= 0) {
      path = args[i]

      validateString(path, `paths[${i}]`)

      if (path.length === 0) continue
    } else if (resolvedDevice.length === 0) {
      path = binding.cwd()
    } else {
      path = binding.cwd(resolvedDevice)

      if (
        path === undefined ||
        (path.substring(0, 2).toLowerCase() !== resolvedDevice.toLowerCase() &&
          path.charCodeAt(2) === CHAR_BACKWARD_SLASH)
      ) {
        path = `${resolvedDevice}\\`
      }
    }

    const len = path.length
    let rootEnd = 0
    let device = ''
    let isAbsolute = false
    const code = path.charCodeAt(0)

    if (len === 1) {
      if (isWindowsPathSeparator(code)) {
        rootEnd = 1
        isAbsolute = true
      }
    } else if (isWindowsPathSeparator(code)) {
      isAbsolute = true

      if (isWindowsPathSeparator(path.charCodeAt(1))) {
        let j = 2
        let last = j
        while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
          j++
        }
        if (j < len && j !== last) {
          const firstPart = path.substring(last, j)
          last = j
          while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
            j++
          }
          if (j < len && j !== last) {
            last = j
            while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
              j++
            }
            if (j === len || j !== last) {
              device = `\\\\${firstPart}\\${path.substring(last, j)}`
              rootEnd = j
            }
          }
        }
      } else {
        rootEnd = 1
      }
    } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
      device = path.substring(0, 2)
      rootEnd = 2
      if (len > 2 && isWindowsPathSeparator(path.charCodeAt(2))) {
        isAbsolute = true
        rootEnd = 3
      }
    }

    if (device.length > 0) {
      if (resolvedDevice.length > 0) {
        if (device.toLowerCase() !== resolvedDevice.toLowerCase()) {
          continue
        }
      } else {
        resolvedDevice = device
      }
    }

    if (resolvedAbsolute) {
      if (resolvedDevice.length > 0) {
        break
      }
    } else {
      resolvedTail = `${path.substring(rootEnd)}\\${resolvedTail}`
      resolvedAbsolute = isAbsolute
      if (isAbsolute && resolvedDevice.length > 0) {
        break
      }
    }
  }

  resolvedTail = normalizeString(resolvedTail, !resolvedAbsolute, '\\', isWindowsPathSeparator)

  return resolvedAbsolute
    ? `${resolvedDevice}\\${resolvedTail}`
    : `${resolvedDevice}${resolvedTail}` || '.'
}

exports.normalize = function normalize(path) {
  validateString(path, 'path')

  const len = path.length
  if (len === 0) return '.'
  let rootEnd = 0
  let device
  let isAbsolute = false
  const code = path.charCodeAt(0)

  if (len === 1) {
    return code === CHAR_FORWARD_SLASH ? '\\' : path
  }

  if (isWindowsPathSeparator(code)) {
    isAbsolute = true

    if (isWindowsPathSeparator(path.charCodeAt(1))) {
      let j = 2
      let last = j
      while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
        j++
      }
      if (j < len && j !== last) {
        const firstPart = path.substring(last, j)
        last = j
        while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
          j++
        }
        if (j < len && j !== last) {
          last = j
          while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
            j++
          }
          if (j === len) {
            return `\\\\${firstPart}\\${path.substring(last)}\\`
          }
          if (j !== last) {
            device = `\\\\${firstPart}\\${path.substring(last, j)}`
            rootEnd = j
          }
        }
      }
    } else {
      rootEnd = 1
    }
  } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
    device = path.substring(0, 2)
    rootEnd = 2
    if (len > 2 && isWindowsPathSeparator(path.charCodeAt(2))) {
      isAbsolute = true
      rootEnd = 3
    }
  }

  let tail =
    rootEnd < len
      ? normalizeString(path.substring(rootEnd), !isAbsolute, '\\', isWindowsPathSeparator)
      : ''
  if (tail.length === 0 && !isAbsolute) {
    tail = '.'
  }
  if (tail.length > 0 && isWindowsPathSeparator(path.charCodeAt(len - 1))) {
    tail += '\\'
  }
  if (device === undefined) {
    return isAbsolute ? `\\${tail}` : tail
  }
  return isAbsolute ? `${device}\\${tail}` : `${device}${tail}`
}

exports.isAbsolute = function isAbsolute(path) {
  validateString(path, 'path')

  const len = path.length
  if (len === 0) return false

  const code = path.charCodeAt(0)

  return (
    isWindowsPathSeparator(code) ||
    (len > 2 &&
      isWindowsDeviceRoot(code) &&
      path.charCodeAt(1) === CHAR_COLON &&
      isWindowsPathSeparator(path.charCodeAt(2)))
  )
}

exports.join = function join(...args) {
  if (args.length === 0) return '.'

  let joined
  let firstPart
  for (let i = 0; i < args.length; ++i) {
    const arg = args[i]
    validateString(arg, 'path')
    if (arg.length > 0) {
      if (joined === undefined) joined = firstPart = arg
      else joined += `\\${arg}`
    }
  }

  if (joined === undefined) return '.'

  let needsReplace = true
  let slashCount = 0
  if (isWindowsPathSeparator(firstPart.charCodeAt(0))) {
    ++slashCount
    const firstLen = firstPart.length
    if (firstLen > 1 && isWindowsPathSeparator(firstPart.charCodeAt(1))) {
      ++slashCount
      if (firstLen > 2) {
        if (isWindowsPathSeparator(firstPart.charCodeAt(2))) {
          ++slashCount
        } else {
          needsReplace = false
        }
      }
    }
  }
  if (needsReplace) {
    while (slashCount < joined.length && isWindowsPathSeparator(joined.charCodeAt(slashCount))) {
      slashCount++
    }

    if (slashCount >= 2) {
      joined = `\\${joined.substring(slashCount)}`
    }
  }

  return exports.normalize(joined)
}

exports.relative = function relative(from, to) {
  validateString(from, 'from')
  validateString(to, 'to')

  if (from === to) return ''

  const fromOrig = exports.resolve(from)
  const toOrig = exports.resolve(to)

  if (fromOrig === toOrig) return ''

  from = fromOrig.toLowerCase()
  to = toOrig.toLowerCase()

  if (from === to) return ''

  let fromStart = 0
  while (fromStart < from.length && from.charCodeAt(fromStart) === CHAR_BACKWARD_SLASH) {
    fromStart++
  }
  let fromEnd = from.length
  while (fromEnd - 1 > fromStart && from.charCodeAt(fromEnd - 1) === CHAR_BACKWARD_SLASH) {
    fromEnd--
  }
  const fromLen = fromEnd - fromStart

  let toStart = 0
  while (toStart < to.length && to.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) {
    toStart++
  }
  let toEnd = to.length
  while (toEnd - 1 > toStart && to.charCodeAt(toEnd - 1) === CHAR_BACKWARD_SLASH) {
    toEnd--
  }
  const toLen = toEnd - toStart

  const length = fromLen < toLen ? fromLen : toLen
  let lastCommonSep = -1
  let i = 0
  for (; i < length; i++) {
    const fromCode = from.charCodeAt(fromStart + i)
    if (fromCode !== to.charCodeAt(toStart + i)) {
      break
    } else if (fromCode === CHAR_BACKWARD_SLASH) {
      lastCommonSep = i
    }
  }

  if (i !== length) {
    if (lastCommonSep === -1) return toOrig
  } else {
    if (toLen > length) {
      if (to.charCodeAt(toStart + i) === CHAR_BACKWARD_SLASH) {
        return toOrig.substring(toStart + i + 1)
      }
      if (i === 2) {
        return toOrig.substring(toStart + i)
      }
    }
    if (fromLen > length) {
      if (from.charCodeAt(fromStart + i) === CHAR_BACKWARD_SLASH) {
        lastCommonSep = i
      } else if (i === 2) {
        lastCommonSep = 3
      }
    }
    if (lastCommonSep === -1) lastCommonSep = 0
  }

  let out = ''
  for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
    if (i === fromEnd || from.charCodeAt(i) === CHAR_BACKWARD_SLASH) {
      out += out.length === 0 ? '..' : '\\..'
    }
  }

  toStart += lastCommonSep

  if (out.length > 0) {
    return `${out}${toOrig.substring(toStart, toEnd)}`
  }
  if (toOrig.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) {
    ++toStart
  }
  return toOrig.substring(toStart, toEnd)
}

exports.toNamespacedPath = function toNamespacedPath(path) {
  if (typeof path !== 'string' || path.length === 0) return path

  const resolvedPath = exports.resolve(path)

  if (resolvedPath.length <= 2) return path

  if (resolvedPath.charCodeAt(0) === CHAR_BACKWARD_SLASH) {
    if (resolvedPath.charCodeAt(1) === CHAR_BACKWARD_SLASH) {
      const code = resolvedPath.charCodeAt(2)
      if (code !== CHAR_QUESTION_MARK && code !== CHAR_DOT) {
        return `\\\\?\\UNC\\${resolvedPath.substring(2)}`
      }
    }
  } else if (
    isWindowsDeviceRoot(resolvedPath.charCodeAt(0)) &&
    resolvedPath.charCodeAt(1) === CHAR_COLON &&
    resolvedPath.charCodeAt(2) === CHAR_BACKWARD_SLASH
  ) {
    return `\\\\?\\${resolvedPath}`
  }

  return path
}

exports.dirname = function dirname(path) {
  validateString(path, 'path')

  const len = path.length
  if (len === 0) return '.'
  let rootEnd = -1
  let offset = 0
  const code = path.charCodeAt(0)

  if (len === 1) {
    return isWindowsPathSeparator(code) ? path : '.'
  }

  if (isWindowsPathSeparator(code)) {
    rootEnd = offset = 1

    if (isWindowsPathSeparator(path.charCodeAt(1))) {
      let j = 2
      let last = j
      while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
        j++
      }
      if (j < len && j !== last) {
        last = j
        while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
          j++
        }
        if (j < len && j !== last) {
          last = j
          while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
            j++
          }
          if (j === len) {
            return path
          }
          if (j !== last) {
            rootEnd = offset = j + 1
          }
        }
      }
    }
  } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
    rootEnd = len > 2 && isWindowsPathSeparator(path.charCodeAt(2)) ? 3 : 2
    offset = rootEnd
  }

  let end = -1
  let matchedSlash = true
  for (let i = len - 1; i >= offset; --i) {
    if (isWindowsPathSeparator(path.charCodeAt(i))) {
      if (!matchedSlash) {
        end = i
        break
      }
    } else {
      matchedSlash = false
    }
  }

  if (end === -1) {
    if (rootEnd === -1) return '.'

    end = rootEnd
  }
  return path.substring(0, end)
}

exports.basename = function basename(path, suffix) {
  if (suffix !== undefined) validateString(suffix, 'suffix')
  validateString(path, 'path')

  let start = 0
  let end = -1
  let matchedSlash = true

  if (
    path.length >= 2 &&
    isWindowsDeviceRoot(path.charCodeAt(0)) &&
    path.charCodeAt(1) === CHAR_COLON
  ) {
    start = 2
  }

  if (suffix !== undefined && suffix.length > 0 && suffix.length <= path.length) {
    if (suffix === path) return ''
    let extIdx = suffix.length - 1
    let firstNonSlashEnd = -1
    for (let i = path.length - 1; i >= start; --i) {
      const code = path.charCodeAt(i)
      if (isWindowsPathSeparator(code)) {
        if (!matchedSlash) {
          start = i + 1
          break
        }
      } else {
        if (firstNonSlashEnd === -1) {
          matchedSlash = false
          firstNonSlashEnd = i + 1
        }
        if (extIdx >= 0) {
          if (code === suffix.charCodeAt(extIdx)) {
            if (--extIdx === -1) {
              end = i
            }
          } else {
            extIdx = -1
            end = firstNonSlashEnd
          }
        }
      }
    }

    if (start === end) end = firstNonSlashEnd
    else if (end === -1) end = path.length
    return path.substring(start, end)
  }
  for (let i = path.length - 1; i >= start; --i) {
    if (isWindowsPathSeparator(path.charCodeAt(i))) {
      if (!matchedSlash) {
        start = i + 1
        break
      }
    } else if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
  }

  if (end === -1) return ''
  return path.substring(start, end)
}

exports.extname = function extname(path) {
  validateString(path, 'path')

  let start = 0
  let startDot = -1
  let startPart = 0
  let end = -1
  let matchedSlash = true
  let preDotState = 0

  if (
    path.length >= 2 &&
    path.charCodeAt(1) === CHAR_COLON &&
    isWindowsDeviceRoot(path.charCodeAt(0))
  ) {
    start = startPart = 2
  }

  for (let i = path.length - 1; i >= start; --i) {
    const code = path.charCodeAt(i)
    if (isWindowsPathSeparator(code)) {
      if (!matchedSlash) {
        startPart = i + 1
        break
      }
      continue
    }
    if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
    if (code === CHAR_DOT) {
      if (startDot === -1) startDot = i
      else if (preDotState !== 1) preDotState = 1
    } else if (startDot !== -1) {
      preDotState = -1
    }
  }

  if (
    startDot === -1 ||
    end === -1 ||
    preDotState === 0 ||
    (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1)
  ) {
    return ''
  }
  return path.substring(startDot, end)
}
{
  "name": "bare-path",
  "version": "3.1.1",
  "description": "Path manipulation library for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./posix": "./lib/posix.js",
    "./win32": "./lib/win32.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds",
    "NOTICE"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-path.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-path/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-path#readme",
  "devDependencies": {
    "brittle": "^3.3.2",
    "cmake-bare": "^1.1.6",
    "lunte": "^1.8.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = require.addon()
const EventEmitter = require('bare-events')
const { Duplex } = require('bare-stream')
const binding = require('./binding')
const constants = require('./lib/constants')
const errors = require('./lib/errors')

const defaultReadBufferSize = 65536
const empty = Buffer.alloc(0)

const ipcHandle = Symbol.for('bare.ipc.handle')
const ipcAccept = Symbol.for('bare.ipc.accept')

module.exports = exports = class Pipe extends Duplex {
  constructor(path, opts = {}) {
    if (typeof path === 'object' && path !== null) {
      opts = path
      path = null
    }

    const {
      readBufferSize = defaultReadBufferSize,
      allowHalfOpen = true,
      eagerOpen = true,
      ipc = false
    } = opts

    super({ eagerOpen })

    this._state = 0

    this._allowHalfOpen = allowHalfOpen
    this._ipc = ipc

    this._fd = -1
    this._path = null

    this._pendingOpen = null
    this._pendingWrite = null
    this._pendingWriteBatch = null
    this._pendingWriteSegments = null
    this._pendingWriteIdx = 0
    this._pendingFinal = null
    this._pendingDestroy = null

    this._handleQueue = []
    this._handleQueueSize = 0

    this._buffer = Buffer.alloc(readBufferSize)

    this._handle = binding.init(
      this._buffer,
      ipc,
      this,
      noop,
      this._onconnect,
      this._onwrite,
      this._onfinal,
      this._onread,
      this._onhandle,
      this._onclose
    )

    if (typeof path === 'number') {
      this.open(path)
    } else if (typeof path === 'string') {
      this.connect(path)
    }
  }

  get connecting() {
    return (this._state & constants.state.CONNECTING) !== 0
  }

  get pending() {
    return (this._state & constants.state.CONNECTED) === 0
  }

  get readyState() {
    if (this._state & constants.state.READABLE && this._state & constants.state.WRITABLE) {
      return 'open'
    }

    if (this._state & constants.state.READABLE) {
      return 'readOnly'
    }

    if (this._state & constants.state.WRITABLE) {
      return 'writeOnly'
    }

    return 'opening'
  }

  get [ipcHandle]() {
    return this._handle
  }

  open(fd, opts = {}, onconnect) {
    if (typeof opts === 'function') {
      onconnect = opts
      opts = {}
    }

    if (typeof fd === 'object' && fd !== null) {
      opts = fd || {}
      fd = opts.fd
    }

    try {
      const status = binding.open(this._handle, fd)

      this._state |= constants.state.CONNECTED
      this._fd = fd

      if (status & binding.READABLE) {
        this._state |= constants.state.READABLE
      } else {
        this.push(null)
      }

      if (status & binding.WRITABLE) {
        this._state |= constants.state.WRITABLE
      } else {
        this.end()
      }

      if (onconnect) this.once('connect', onconnect)

      queueMicrotask(() => this.emit('connect'))
    } catch (err) {
      queueMicrotask(() => {
        if (this._pendingOpen) this._pendingOpen(err)
        else this.destroy(err)
      })
    }

    return this
  }

  connect(path, opts = {}, onconnect) {
    if (this._state & constants.state.CONNECTING || this._state & constants.state.CONNECTED) {
      throw errors.PIPE_ALREADY_CONNECTED('Pipe is already connected')
    }

    this._state |= constants.state.CONNECTING

    if (typeof opts === 'function') {
      onconnect = opts
      opts = {}
    }

    if (typeof path === 'object' && path !== null) {
      opts = path || {}
      path = opts.path
    }

    try {
      binding.connect(this._handle, path)

      this._path = path

      if (onconnect) this.once('connect', onconnect)
    } catch (err) {
      queueMicrotask(() => {
        if (this._pendingOpen) this._pendingOpen(err)
        else this.destroy(err)
      })
    }

    return this
  }

  write(chunk, encoding, handle, cb) {
    if (typeof encoding === 'function') {
      cb = encoding
      encoding = undefined
      handle = null
    } else if (typeof encoding === 'object' && encoding !== null) {
      if (typeof handle === 'function') cb = handle
      handle = encoding
      encoding = undefined
    } else if (typeof handle === 'function') {
      cb = handle
      handle = null
    }

    if (handle) this._handleQueueSize++

    this._handleQueue.push(handle || null)

    if (encoding) return super.write(chunk, encoding, cb)

    return super.write(chunk, cb)
  }

  accept(target) {
    const handle = target[ipcHandle]

    if (handle === undefined) {
      throw errors.INVALID_IPC_TARGET('Target does not implement the IPC handle protocol')
    }

    binding.accept(this._handle, handle)

    if (typeof target[ipcAccept] === 'function') target[ipcAccept]()

    return target
  }

  ref() {
    binding.ref(this._handle)

    return this
  }

  unref() {
    binding.unref(this._handle)

    return this
  }

  [ipcAccept]() {
    this._onaccept()
  }

  _open(cb) {
    if (this._state & constants.state.CONNECTED) return cb(null)

    this._pendingOpen = cb
  }

  _read() {
    if ((this._state & constants.state.READING) === 0) {
      this._state |= constants.state.READING

      binding.resume(this._handle)
    }
  }

  _writev(batch, cb) {
    this._pendingWrite = cb
    this._pendingWriteBatch = batch

    if (this._handleQueueSize === 0) {
      this._handleQueue = []
      this._pendingWriteSegments = null

      try {
        binding.writev(
          this._handle,
          batch.map(({ chunk }) => chunk),
          null
        )
      } catch (err) {
        this._continueWrite(err)
      }
      return
    }

    const handles = this._handleQueue.splice(0, batch.length)

    // Fill any holes in the batch for messages that don't carry a handle. Each
    // message that does carry a handle decrements the handle queue size.
    for (let i = 0; i < batch.length; i++) {
      if (handles[i] === undefined) handles[i] = null
      else if (handles[i] !== null) this._handleQueueSize--
    }

    const segments = []

    let i = 0
    while (i < batch.length) {
      if (handles[i] !== null) {
        segments.push({ chunks: [batch[i]], handle: handles[i] })
        i++
      } else {
        const start = i
        while (i < batch.length && handles[i] === null) i++
        segments.push({ chunks: batch.slice(start, i), handle: null })
      }
    }

    this._pendingWriteSegments = segments
    this._pendingWriteIdx = 0

    this._writeNextSegment()
  }

  _writeNextSegment() {
    const segment = this._pendingWriteSegments[this._pendingWriteIdx]

    const chunks = []
    for (let i = 0; i < segment.chunks.length; i++) {
      chunks.push(segment.chunks[i].chunk)
    }

    let sendHandle = null
    if (segment.handle !== null) sendHandle = segment.handle[ipcHandle]

    try {
      binding.writev(this._handle, chunks, sendHandle)
    } catch (err) {
      this._continueWrite(err)
    }
  }

  _final(cb) {
    if (this._state & constants.state.READABLE && this._state & constants.state.WRITABLE) {
      this._pendingFinal = cb

      binding.end(this._handle)
    } else {
      cb(null)
    }
  }

  _predestroy() {
    if (this._state & constants.state.CLOSING) return
    this._state |= constants.state.CLOSING

    binding.close(this._handle)
  }

  _destroy(err, cb) {
    if (this._state & constants.state.CLOSING) return cb(err)
    this._state |= constants.state.CLOSING

    this._pendingDestroy = cb

    binding.close(this._handle)
  }

  _continueOpen(err) {
    if (this._pendingOpen === null) return
    const cb = this._pendingOpen
    this._pendingOpen = null
    cb(err)
  }

  _continueWrite(err) {
    if (this._pendingWrite === null) return

    if (this._pendingWriteSegments === null) {
      const cb = this._pendingWrite
      this._pendingWrite = null
      this._pendingWriteBatch = null
      cb(err)
      return
    }

    this._pendingWriteIdx++

    if (err === null && this._pendingWriteIdx < this._pendingWriteSegments.length) {
      this._writeNextSegment()
      return
    }

    const cb = this._pendingWrite
    this._pendingWrite = null
    this._pendingWriteBatch = null
    this._pendingWriteSegments = null
    this._pendingWriteIdx = 0
    cb(err)
  }

  _continueFinal(err) {
    if (this._pendingFinal === null) return
    const cb = this._pendingFinal
    this._pendingFinal = null
    cb(err)
  }

  _continueDestroy() {
    if (this._pendingDestroy === null) return
    const cb = this._pendingDestroy
    this._pendingDestroy = null
    cb(null)
  }

  _onconnect(err) {
    if (err) {
      if (this._pendingOpen) this._continueOpen(err)
      else this.destroy(err)
      return
    }

    this._state |= constants.state.CONNECTED | constants.state.READABLE | constants.state.WRITABLE
    this._state &= ~constants.state.CONNECTING
    this._continueOpen()

    this.emit('connect')
  }

  _onaccept() {
    this._state |= constants.state.CONNECTED | constants.state.READABLE | constants.state.WRITABLE
    this._continueOpen()
  }

  _onread(err, read) {
    if (err) {
      this.destroy(err)
      return
    }

    if (read === 0) {
      this.push(null)
      if (this._allowHalfOpen === false) this.end()
      return
    }

    const copy = Buffer.allocUnsafe(read)
    copy.set(this._buffer.subarray(0, read))

    if (this.push(copy) === false && this.destroying === false) {
      this._state &= ~constants.state.READING

      binding.pause(this._handle)
    }
  }

  _onhandle(type) {
    this.emit('handle', type)
  }

  _onwrite(err) {
    this._continueWrite(err)
  }

  _onfinal(err) {
    this._continueFinal(err === null || err.code === 'ENOTCONN' ? null : err)
  }

  _onclose() {
    this._continueDestroy()
  }

  _onspawn(readable, writable) {
    this._state |= constants.state.CONNECTED

    if (readable) {
      this._state |= constants.state.READABLE
    } else {
      this.push(null)
    }

    if (writable) {
      this._state |= constants.state.WRITABLE
    } else {
      this.end()
    }

    this._continueOpen()
  }
}

exports.Pipe = exports

exports.pipe = function pipe() {
  return binding.pipe()
}

exports.Server = class PipeServer extends EventEmitter {
  constructor(opts = {}, onconnection) {
    if (typeof opts === 'function') {
      onconnection = opts
      opts = {}
    }

    super()

    const {
      readBufferSize = defaultReadBufferSize,
      allowHalfOpen = true,
      pauseOnConnect = false,
      ipc = false
    } = opts

    this._state = 0

    this._readBufferSize = readBufferSize
    this._allowHalfOpen = allowHalfOpen
    this._pauseOnConnect = pauseOnConnect
    this._ipc = ipc

    this._path = null
    this._connections = new Set()

    this._error = null
    this._handle = null

    if (onconnection) this.on('connection', onconnection)
  }

  get listening() {
    return (this._state & constants.state.BOUND) !== 0
  }

  address() {
    if ((this._state & constants.state.BOUND) === 0) {
      return null
    }

    return this._path
  }

  listen(path, backlog = 511, opts = {}, onlistening) {
    if (this._state & constants.state.BINDING || this._state & constants.state.BOUND) {
      throw errors.SERVER_ALREADY_LISTENING('Server is already listening')
    }

    if (this._state & constants.state.CLOSING) {
      throw errors.SERVER_IS_CLOSED('Server is closed')
    }

    this._state |= constants.state.BINDING

    if (typeof backlog === 'function') {
      onlistening = backlog
      backlog = 511
    } else if (typeof opts === 'function') {
      onlistening = opts
      opts = {}
    }

    if (typeof path === 'object' && path !== null) {
      opts = path || {}
      path = opts.path
      backlog = opts.backlog || 511
    }

    this._handle = binding.init(
      empty,
      this._ipc,
      this,
      this._onconnection,
      noop,
      noop,
      noop,
      noop,
      noop,
      this._onclose
    )

    if (this._state & constants.state.UNREFED) binding.unref(this._handle)

    try {
      binding.bind(this._handle, path, backlog)

      this._path = path
      this._state |= constants.state.BOUND
      this._state &= ~constants.state.BINDING

      if (onlistening) this.once('listening', onlistening)

      queueMicrotask(() => this.emit('listening'))
    } catch (err) {
      this._error = err

      binding.close(this._handle)
    }

    return this
  }

  close(onclose) {
    if (onclose) this.once('close', onclose)

    if (this._state & constants.state.CLOSING) return
    this._state |= constants.state.CLOSING

    this._closeMaybe()

    return this
  }

  ref() {
    this._state &= ~constants.state.UNREFED

    if (this._handle !== null) binding.ref(this._handle)

    return this
  }

  unref() {
    this._state |= constants.state.UNREFED

    if (this._handle !== null) binding.unref(this._handle)

    return this
  }

  _closeMaybe() {
    if (this._state & constants.state.CLOSING && this._connections.size === 0) {
      if (this._handle !== null) binding.close(this._handle)
      else queueMicrotask(() => this.emit('close'))
    }
  }

  _onconnection(err) {
    if (err) {
      this.emit('error', err)
      return
    }

    if (this._state & constants.state.CLOSING) return

    const pipe = new exports.Pipe({
      readBufferSize: this._readBufferSize,
      allowHalfOpen: this._allowHalfOpen,
      eagerOpen: !this._pauseOnConnect,
      ipc: this._ipc
    })

    try {
      binding.accept(this._handle, pipe._handle)

      pipe._path = this._path
      pipe._onaccept()

      this._connections.add(pipe)

      pipe.on('close', () => {
        this._connections.delete(pipe)
        this._closeMaybe()
      })

      this.emit('connection', pipe)
    } catch (err) {
      pipe.destroy()

      throw err
    }
  }

  _onclose() {
    const err = this._error

    this._state &= ~constants.state.BINDING
    this._error = null
    this._handle = null

    if (err) this.emit('error', err)
    else this.emit('close')
  }
}

exports.constants = constants
exports.errors = errors

exports.createConnection = function createConnection(path, opts, onconnect) {
  if (typeof opts === 'function') {
    onconnect = opts
    opts = {}
  }

  if (typeof path === 'object' && path !== null) {
    opts = path || {}
    path = opts.path
  }

  return new exports.Pipe(opts).connect(path, opts, onconnect)
}

exports.createServer = function createServer(opts, onconnection) {
  return new exports.Server(opts, onconnection)
}

function noop() {}
const binding = require('../binding')

module.exports = {
  state: {
    CONNECTING: 0x1,
    CONNECTED: 0x2,
    BINDING: 0x4,
    BOUND: 0x8,
    READING: 0x10,
    CLOSING: 0x20,
    READABLE: 0x40,
    WRITABLE: 0x80,
    UNREFED: 0x100
  },
  handle: {
    NAMED_PIPE: binding.UV_NAMED_PIPE,
    TCP: binding.UV_TCP,
    UDP: binding.UV_UDP
  }
}
module.exports = class PipeError extends Error {
  constructor(msg, fn = PipeError, code = fn.name) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'PipeError'
  }

  static PIPE_ALREADY_CONNECTED(msg) {
    return new PipeError(msg, PipeError.PIPE_ALREADY_CONNECTED)
  }

  static SERVER_ALREADY_LISTENING(msg) {
    return new PipeError(msg, PipeError.SERVER_ALREADY_LISTENING)
  }

  static SERVER_IS_CLOSED(msg) {
    return new PipeError(msg, PipeError.SERVER_IS_CLOSED)
  }

  static INVALID_IPC_TARGET(msg) {
    return new PipeError(msg, PipeError.INVALID_IPC_TARGET)
  }
}
{
  "name": "bare-pipe",
  "version": "4.2.2",
  "description": "Native I/O pipes for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    },
    "./errors": {
      "types": "./lib/errors.d.ts",
      "default": "./lib/errors.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-pipe.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-pipe/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-pipe#readme",
  "engines": {
    "bare": ">=1.16.0"
  },
  "dependencies": {
    "bare-events": "^2.0.0",
    "bare-stream": "^2.0.0"
  },
  "devDependencies": {
    "bare-path": "^3.0.0",
    "bare-tcp": "^2.4.1",
    "brittle": "^3.2.1",
    "cmake-bare": "^1.1.6",
    "lunte": "^1.8.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  }
}
{
  "name": "bare-posix",
  "version": "1.0.1",
  "description": "POSIX-specific bindings for Bare",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "android": "./unsupported.js",
      "win32": "./unsupported.js",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "unsupported.js",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-posix.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-posix/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-posix#readme",
  "devDependencies": {
    "brittle": "^3.19.1",
    "cmake-bare": "^1.7.7",
    "lunte": "^1.6.0",
    "prettier": "^3.8.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
exports.getgid = function getgid() {
  return -1
}

exports.setgid = function setgid() {
  throw new Error('Platform not supported')
}

exports.getegid = function getegid() {
  return -1
}

exports.setegid = function setgid() {
  throw new Error('Platform not supported')
}

exports.getuid = function getuid() {
  return -1
}

exports.setuid = function setgid() {
  throw new Error('Platform not supported')
}

exports.geteuid = function geteuid() {
  return -1
}

exports.seteuid = function setgid() {
  throw new Error('Platform not supported')
}

exports.getgroups = function getgroups() {
  return []
}

exports.getgrnam = function getgrnam() {
  return null
}

exports.getpwnam = function getpwnam() {
  return null
}
const abort = require('bare-abort')
const EventEmitter = require('bare-events')
const Signal = require('bare-signals')
const os = require('bare-os')
const env = require('bare-env')
const hrtime = require('bare-hrtime')
const stdio = require('bare-stdio')
const posix = require('bare-posix')

class Process extends EventEmitter {
  constructor() {
    super()

    this._startTime = hrtime.bigint()

    EventEmitter.forward(Bare, this, [
      'uncaughtException',
      'unhandledRejection',
      'beforeExit',
      'exit',
      'suspend',
      'wakeup',
      'idle',
      'resume'
    ])

    const signals = new Signal.Emitter()

    signals.unref()

    EventEmitter.forward(signals, this, Object.keys(os.constants.signals))
  }

  get stdin() {
    return stdio.in
  }

  get stdout() {
    return stdio.out
  }

  get stderr() {
    return stdio.err
  }

  get platform() {
    return os.platform()
  }

  get arch() {
    return os.arch()
  }

  get title() {
    return os.getProcessTitle()
  }

  set title(title) {
    os.setProcessTitle(title)
  }

  get pid() {
    return os.pid()
  }

  get ppid() {
    return os.ppid()
  }

  get argv() {
    return Bare.argv
  }

  get execArgv() {
    return []
  }

  get execPath() {
    return os.execPath()
  }

  get exitCode() {
    return Bare.exitCode
  }

  set exitCode(code) {
    Bare.exitCode = code
  }

  get version() {
    return Bare.version
  }

  get versions() {
    return Bare.versions
  }

  get env() {
    return env
  }

  get hrtime() {
    return hrtime
  }

  abort() {
    abort()
  }

  exit(code) {
    Bare.exit(code)
  }

  suspend() {
    Bare.suspend()
  }

  resume() {
    Bare.resume()
  }

  cwd() {
    return os.cwd()
  }

  chdir(directory) {
    os.chdir(directory)
  }

  kill(pid, signal) {
    os.kill(pid, signal)
  }

  uptime() {
    return Number(hrtime.bigint() - this._startTime) / 1e9
  }

  cpuUsage(previous) {
    return os.cpuUsage(previous)
  }

  threadCpuUsage(previous) {
    return os.threadCpuUsage(previous)
  }

  resourceUsage() {
    return os.resourceUsage()
  }

  availableMemory() {
    return os.availableMemory()
  }

  constrainedMemory() {
    return os.constrainedMemory()
  }

  memoryUsage() {
    return os.memoryUsage()
  }

  getgid() {
    return posix.getgid()
  }

  setgid(id) {
    return posix.setgid(id)
  }

  getegid() {
    return posix.getegid()
  }

  setegid(id) {
    return posix.setegid(id)
  }

  getuid() {
    return posix.getuid()
  }

  setuid(id) {
    return posix.setuid(id)
  }

  geteuid() {
    return posix.geteuid()
  }

  seteuid(id) {
    return posix.seteuid(id)
  }

  getgroups() {
    return posix.getgroups()
  }

  nextTick(cb, ...args) {
    queueMicrotask(cb.bind(null, ...args))
  }

  [Symbol.for('bare.inspect')]() {
    return {
      __proto__: { constructor: Process },

      platform: this.platform,
      arch: this.arch,
      title: this.title,
      pid: this.pid,
      ppid: this.ppid,
      argv: this.argv,
      execPath: this.execPath,
      exitCode: this.exitCode,
      version: this.version,
      versions: this.versions,
      env: this.env
    }
  }
}

module.exports = new Process()
{
  "name": "bare-process",
  "version": "4.5.1",
  "description": "Node.js-compatible process control for Bare",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "global.js",
    "global.d.ts"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-process.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-process/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-process#readme",
  "dependencies": {
    "bare-abort": "^2.0.13",
    "bare-env": "^3.0.0",
    "bare-events": "^2.3.1",
    "bare-hrtime": "^2.0.0",
    "bare-os": "^3.7.1",
    "bare-posix": "^1.0.1",
    "bare-signals": "^5.0.0",
    "bare-stdio": "^1.0.1"
  },
  "devDependencies": {
    "brittle": "^3.2.1",
    "lunte": "^1.6.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = require.addon()
const EventEmitter = require('bare-events')
const binding = require('./binding')
const errors = require('./lib/errors')

const signals = binding.signals

module.exports = exports = class Signal extends EventEmitter {
  constructor(signum) {
    super()

    if (typeof signum === 'string') {
      if (signum in signals === false) {
        throw errors.UNKNOWN_SIGNAL(`Unknown signal '${signum}'`)
      }

      signum = signals[signum]
    }

    this._signum = signum
    this._closing = null
    this._handle = binding.init(this, this._onsignal, this._onclose)
  }

  start() {
    if (this._closing) throw errors.SIGNAL_CLOSED('Signal is closed')
    binding.start(this._handle, this._signum)
    return this
  }

  stop() {
    if (this._closing) return this
    binding.stop(this._handle)
    return this
  }

  ref() {
    if (this._closing) return this
    binding.ref(this._handle)
    return this
  }

  unref() {
    if (this._closing) return this
    binding.unref(this._handle)
    return this
  }

  close() {
    if (this._closing) return this._closing
    this._closing = EventEmitter.once(this, 'close')

    binding.close(this._handle)

    return this._closing
  }

  _onsignal() {
    this.emit('signal', this._signum)
  }

  _onclose() {
    this._handle = null

    this.emit('close')
  }
}

exports.Emitter = require('./lib/emitter')

exports.constants = signals
exports.errors = errors
const EventEmitter = require('bare-events')
const Signal = require('..')

module.exports = class SignalEmitter extends EventEmitter {
  constructor() {
    super()

    this._signals = new Map()
    this._unrefed = false

    this.on('newListener', this._onnewlistener).on('removeListener', this._onremovelistener)
  }

  ref() {
    this._unrefed = false
    for (const signal of this._signals.values()) signal.ref()
    return this
  }

  unref() {
    this._unrefed = true
    for (const signal of this._signals.values()) signal.unref()
    return this
  }

  _onnewlistener(name) {
    if (name === 'newListener' || name === 'removeListener') return

    if (this.listenerCount(name) === 0) {
      const signal = new Signal(name)

      signal.on('signal', this._onsignal.bind(this, name)).start()

      if (this._unrefed) signal.unref()

      this._signals.set(name, signal)
    }
  }

  _onremovelistener(name) {
    if (name === 'newListener' || name === 'removeListener') return

    if (this.listenerCount(name) === 0) {
      const signal = this._signals.get(name)

      if (this._unrefed) signal.ref()

      signal.close()

      this._signals.delete(name)
    }
  }

  _onsignal(name) {
    this.emit(name, name, Signal.constants[name])
  }
}
module.exports = class SignalError extends Error {
  constructor(msg, fn = SignalError, code = fn.name) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'SignalError'
  }

  static UNKNOWN_SIGNAL(msg) {
    return new SignalError(msg, SignalError.UNKNOWN_SIGNAL)
  }

  static SIGNAL_CLOSED(msg) {
    return new SignalError(msg, SignalError.SIGNAL_CLOSED)
  }
}
{
  "name": "bare-signals",
  "version": "5.0.0",
  "description": "Native signal handling for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./errors": "./lib/errors.js",
    "./emitter": "./lib/emitter.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-signals.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-signals/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-signals#readme",
  "engines": {
    "bare": ">=1.7.0"
  },
  "dependencies": {
    "bare-events": "^2.5.3"
  },
  "devDependencies": {
    "bare-os": "^3.3.1",
    "brittle": "^3.2.1",
    "cmake-bare": "^1.1.6",
    "lunte": "^1.8.3",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = require.addon()
const fs = require('bare-fs')
const tty = require('bare-tty')
const Pipe = require('bare-pipe')
const binding = require('./binding')

const { TTY, NAMED_PIPE } = binding

class IO {
  constructor() {
    this._in = null
    this._out = null
    this._err = null
  }

  get in() {
    if (this._in === null) {
      switch (binding.guessType(0)) {
        case TTY:
          this._in = new tty.ReadStream(0)
          break
        case NAMED_PIPE:
          this._in = new Pipe(0, { eagerOpen: false })
          break
        default:
          this._in = fs.createReadStream(null, { fd: 0, eagerOpen: false })
      }
    }

    return this._in
  }

  get out() {
    if (this._out === null) {
      switch (binding.guessType(1)) {
        case TTY:
          this._out = new tty.WriteStream(1)
          break
        case NAMED_PIPE:
          this._out = new Pipe(1, { eagerOpen: false })
          this._out.unref()
          break
        default:
          this._out = fs.createWriteStream(null, { fd: 1, eagerOpen: false })
      }
    }

    return this._out
  }

  get err() {
    if (this._err === null) {
      switch (binding.guessType(2)) {
        case TTY:
          this._err = new tty.WriteStream(2)
          break
        case NAMED_PIPE:
          this._err = new Pipe(2, { eagerOpen: false })
          this._err.unref()
          break
        default:
          this._err = fs.createWriteStream(null, { fd: 2, eagerOpen: false })
      }
    }

    return this._err
  }
}

module.exports = new IO()
{
  "name": "bare-stdio",
  "version": "1.0.3",
  "description": "Standard input/output streams for Bare",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-stdio.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-stdio/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-stdio#readme",
  "dependencies": {
    "bare-fs": "^4.5.2",
    "bare-pipe": "^4.1.5",
    "bare-tty": "^5.0.3"
  },
  "devDependencies": {
    "bare-os": "^3.6.2",
    "bare-path": "^3.0.0",
    "bare-subprocess": "^6.0.0",
    "brittle": "^3.19.1",
    "cmake-bare": "^1.7.7",
    "lunte": "^1.4.0",
    "prettier": "^3.8.1",
    "prettier-config-holepunch": "^2.0.0",
    "tt-native": "^1.1.1"
  }
}
const b4a = require('b4a')
const stream = require('streamx')
const { ReadableStream, WritableStream } = require('./web')

const defaultEncoding = 'utf8'

module.exports = exports = stream.Stream

exports.pipeline = stream.pipeline

exports.isStream = stream.isStream
exports.isEnding = stream.isEnding
exports.isEnded = stream.isEnded
exports.isFinishing = stream.isFinishing
exports.isFinished = stream.isFinished
exports.isDisturbed = stream.isDisturbed

exports.isErrored = function isErrored(stream) {
  return exports.getStreamError(stream) !== null
}

exports.isReadable = function isReadable(stream) {
  return stream.readable && !stream.destroying && !exports.isEnded(stream)
}

exports.isWritable = function isWritable(stream) {
  return stream.writable && !stream.destroying && !exports.isFinishing(stream)
}

exports.getStreamError = stream.getStreamError

exports.addAbortSignal = function addAbortSignal(signal, stream) {
  function onAbort() {
    stream.destroy(signal.reason)
  }

  if (signal.aborted) onAbort()
  else signal.addEventListener('abort', onAbort)

  return stream
}

exports.Stream = exports

exports.Readable = class Readable extends stream.Readable {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthReadable: null,
      map: null,
      mapReadable: null
    })

    if (this._construct) this._open = this._construct

    if (this._read !== stream.Readable.prototype._read) {
      this._read = read.bind(this, this._read)
    }

    if (this._destroy !== stream.Stream.prototype._destroy) {
      this._destroy = destroy.bind(this, this._destroy)
    }
  }

  get closed() {
    return !exports.isReadable(this)
  }

  get errored() {
    return stream.getStreamError(this)
  }

  push(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    return super.push(chunk)
  }

  unshift(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    super.unshift(chunk)
  }

  static fromWeb(readableStream, opts = {}) {
    const stream = readableStream._stream

    if (opts.encoding) stream.setEncoding(opts.encoding)
    if (opts.signal) exports.addAbortSignal(opts.signal, stream)

    return stream
  }

  static toWeb(readable, opts = {}) {
    return new ReadableStream(readable, opts.strategy)
  }

  async [Symbol.asyncDispose]() {
    if (!this.destroyed) this.destroy()

    await new Promise((resolve) => exports.finished(this, resolve))
  }
}

exports.Writable = class Writable extends stream.Writable {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthWritable,
      map: null,
      mapWritable: null
    })

    if (this._construct) this._open = this._construct

    if (this._write !== stream.Writable.prototype._write) {
      this._write = write.bind(this, this._write)
    }

    if (this._destroy !== stream.Stream.prototype._destroy) {
      this._destroy = destroy.bind(this, this._destroy)
    }
  }

  get closed() {
    return !exports.isWritable(this)
  }

  get errored() {
    return stream.getStreamError(this)
  }

  write(chunk, encoding, cb) {
    if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result = super.write({ chunk, encoding })

    if (cb) stream.Writable.drained(this).then(() => cb(null), cb)

    return result
  }

  end(chunk, encoding, cb) {
    if (typeof chunk === 'function') {
      cb = chunk
      chunk = null
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    } else {
      encoding = 'buffer'
    }

    const result =
      chunk !== undefined && chunk !== null ? super.end({ chunk, encoding }) : super.end()

    if (cb) this.once('finish', () => cb(null))

    return result
  }

  static fromWeb(writableStream, opts = {}) {
    const stream = writableStream._stream

    if (opts.signal) exports.addAbortSignal(opts.signal, stream)

    return stream
  }

  static toWeb(writable) {
    return new WritableStream(writable)
  }

  async [Symbol.asyncDispose]() {
    if (!this.destroyed) this.destroy()

    await new Promise((resolve) => exports.finished(this, resolve))
  }
}

exports.Duplex = class Duplex extends stream.Duplex {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthReadable: null,
      byteLengthWritable,
      map: null,
      mapReadable: null,
      mapWritable: null
    })

    if (this._construct) this._open = this._construct

    if (this._read !== stream.Readable.prototype._read) {
      this._read = read.bind(this, this._read)
    }

    if (this._write !== stream.Duplex.prototype._write) {
      this._write = write.bind(this, this._write)
    }

    if (this._destroy !== stream.Stream.prototype._destroy) {
      this._destroy = destroy.bind(this, this._destroy)
    }
  }

  push(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    return super.push(chunk)
  }

  unshift(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    super.unshift(chunk)
  }

  write(chunk, encoding, cb) {
    if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result = super.write({ chunk, encoding })

    if (cb) stream.Writable.drained(this).then(() => cb(null), cb)

    return result
  }

  end(chunk, encoding, cb) {
    if (typeof chunk === 'function') {
      cb = chunk
      chunk = null
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result =
      chunk !== undefined && chunk !== null ? super.end({ chunk, encoding }) : super.end()

    if (cb) this.once('finish', () => cb(null))

    return result
  }

  static fromWeb({ readable: readableStream, writable: writableStream }, opts) {
    const readable = exports.Readable.fromWeb(readableStream, opts)
    const writable = exports.Writable.fromWeb(writableStream, opts)

    const duplex = new exports.Duplex({
      write(data, encoding, cb) {
        writable.write(data, encoding, cb)
      }
    })

    readable
      .on('data', (data) => duplex.push(data))
      .on('end', () => duplex.push(null))
      .on('error', (err) => duplex.destroy(err))

    writable.on('finish', () => duplex.end()).on('error', (err) => duplex.destroy(err))

    return duplex
  }

  static toWeb(duplex) {
    const readableStream = exports.Readable.toWeb(duplex)
    const writableStream = exports.Writable.toWeb(duplex)

    return { readable: readableStream, writable: writableStream }
  }
}

class DuplexSide extends exports.Duplex {
  constructor(opts) {
    super(opts)

    this._otherSide = null
    this._cb = null
  }

  _read() {
    const cb = this._cb
    if (!cb) return

    this._cb = null
    cb()
  }

  _write(chunk, encoding, cb) {
    this._otherSide.push(chunk, encoding)
    this._otherSide._cb = cb
  }

  _final(cb) {
    this._otherSide.on('end', cb)
    this._otherSide.push(null)
  }
}

exports.duplexPair = function duplexPair(opts) {
  const sideA = new DuplexSide(opts)
  const sideB = new DuplexSide(opts)

  sideA._otherSide = sideB
  sideB._otherSide = sideA

  return [sideA, sideB]
}

exports.Transform = class Transform extends stream.Transform {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthReadable: null,
      byteLengthWritable,
      map: null,
      mapReadable: null,
      mapWritable: null
    })

    if (this._transform !== stream.Transform.prototype._transform) {
      this._transform = transform.bind(this, this._transform)
    } else {
      this._transform = passthrough
    }
  }

  push(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    return super.push(chunk)
  }

  unshift(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    super.unshift(chunk)
  }

  write(chunk, encoding, cb) {
    if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result = super.write({ chunk, encoding })

    if (cb) stream.Writable.drained(this).then(() => cb(null), cb)

    return result
  }

  end(chunk, encoding, cb) {
    if (typeof chunk === 'function') {
      cb = chunk
      chunk = null
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result =
      chunk !== undefined && chunk !== null ? super.end({ chunk, encoding }) : super.end()

    if (cb) this.once('finish', () => cb(null))

    return result
  }
}

exports.PassThrough = class PassThrough extends exports.Transform {}

exports.finished = function finished(stream, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (!opts) opts = {}

  const { cleanup = false } = opts

  const done = () => {
    cb(exports.getStreamError(stream, { all: true }))

    if (cleanup) detach()
  }

  const detach = () => {
    stream.off('close', done)
    stream.off('error', noop)
  }

  if (stream.destroyed) {
    done()
  } else {
    stream.on('close', done)
    stream.on('error', noop)
  }

  return detach
}

function read(read, cb) {
  read.call(this, 65536)

  cb(null)
}

function write(write, data, cb) {
  write.call(this, data.chunk, data.encoding, cb)
}

function transform(transform, data, cb) {
  transform.call(this, data.chunk, data.encoding, cb)
}

function destroy(destroy, cb) {
  destroy.call(this, exports.getStreamError(this), cb)
}

function passthrough(data, cb) {
  cb(null, data.chunk)
}

function byteLengthWritable(data) {
  return data.chunk.byteLength
}

function noop() {}
{
  "name": "bare-stream",
  "version": "2.13.3",
  "description": "Streaming data for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./promises": "./promises.js",
    "./web": {
      "types": "./web.d.ts",
      "default": "./web.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "promises.js",
    "web.js",
    "web.d.ts",
    "global.js",
    "global.d.ts"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-stream.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-stream/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-stream#readme",
  "dependencies": {
    "b4a": "^1.8.1",
    "streamx": "^2.25.0",
    "teex": "^1.0.1"
  },
  "devDependencies": {
    "bare-abort-controller": "^1.1.0",
    "bare-buffer": "^3.0.0",
    "bare-events": "^2.5.4",
    "brittle": "^3.5.2",
    "lunte": "^1.6.0",
    "prettier": "^3.3.3",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "bare-abort-controller": "*",
    "bare-buffer": "*",
    "bare-events": "*"
  },
  "peerDependenciesMeta": {
    "bare-abort-controller": {
      "optional": true
    },
    "bare-buffer": {
      "optional": true
    },
    "bare-events": {
      "optional": true
    }
  }
}
const { Readable, Writable, Transform, getStreamError, isStreamx, isDisturbed } = require('streamx')
const tee = require('teex')

const readableKind = Symbol.for('bare.stream.readable.kind')
const writableKind = Symbol.for('bare.stream.writable.kind')
const transformKind = Symbol.for('bare.stream.transform.kind')

// https://streams.spec.whatwg.org/#readablestreamdefaultreader
exports.ReadableStreamDefaultReader = class ReadableStreamDefaultReader {
  constructor(stream) {
    this._stream = stream
    this._stream._stream.once('close', onclose).once('error', onerror)

    const closed = Promise.withResolvers()

    // Avoid unhandled exceptions
    closed.promise.catch(noop)

    this._closed = closed

    function onclose() {
      closed.resolve()
    }

    function onerror(err) {
      closed.reject(err)
    }
  }

  get closed() {
    return this._closed.promise
  }

  read() {
    const stream = this._stream._stream

    return new Promise((resolve, reject) => {
      const err = getStreamError(stream)

      if (err) return reject(err)

      if (stream.destroyed) {
        return resolve({ value: undefined, done: true })
      }

      const value = stream.read()

      if (value !== null) {
        return resolve({ value, done: false })
      }

      stream.once('readable', onreadable).once('close', onclose).once('error', onerror)

      function onreadable() {
        const value = stream.read()

        ondone(null, value === null ? { value: undefined, done: true } : { value, done: false })
      }

      function onclose() {
        ondone(null, { value: undefined, done: true })
      }

      function onerror(err) {
        ondone(err, null)
      }

      function ondone(err, value) {
        stream.off('readable', onreadable).off('close', onclose).off('error', onerror)

        if (err) reject(err)
        else resolve(value)
      }
    })
  }

  releaseLock() {
    this._closed.reject(new TypeError('Reader was released'))
    this._stream._releaseLock()
    this._stream = null
  }

  cancel(reason = new TypeError('Stream was cancelled')) {
    const stream = this._stream._stream

    if (stream.destroyed) return Promise.resolve()

    return new Promise((resolve) =>
      stream.once('close', resolve).once('error', noop).destroy(reason)
    )
  }
}

// https://streams.spec.whatwg.org/#readablestreamdefaultcontroller
exports.ReadableStreamDefaultController = class ReadableStreamDefaultController {
  constructor(stream) {
    this._stream = stream
  }

  get desiredSize() {
    const stream = this._stream._stream

    return stream._readableState.highWaterMark - stream._readableState.buffered
  }

  enqueue(data) {
    this._stream._stream.push(data)
  }

  close() {
    this._stream._stream.push(null)
  }

  error(err) {
    this._stream._stream.destroy(err)
  }
}

// https://streams.spec.whatwg.org/#readablestream
class ReadableStream {
  static get [readableKind]() {
    return 0 // Compatibility version
  }

  static from(iterable) {
    return new ReadableStream(Readable.from(iterable))
  }

  constructor(underlyingSource = {}, queuingStrategy) {
    if (isStreamx(underlyingSource)) {
      this._stream = underlyingSource
    } else {
      if (queuingStrategy === undefined) {
        queuingStrategy = new exports.CountQueuingStrategy()
      }

      const { start, pull, cancel } = underlyingSource
      const { highWaterMark = 1, size = defaultSize } = queuingStrategy

      this._stream = new Readable({ highWaterMark, byteLength: size })

      const controller = new exports.ReadableStreamDefaultController(this)

      try {
        let starting = Promise.resolve()

        if (start) starting = forwardError(start.call(this, controller), controller)

        if (pull) {
          this._stream._read = this._read.bind(this, starting, pull.bind(this, controller))
        }

        if (cancel) {
          this._stream.once('error', cancel.bind(this))
        }
      } catch (err) {
        controller.error(err)
      }
    }

    this._reader = null
  }

  get [readableKind]() {
    return ReadableStream[readableKind]
  }

  get locked() {
    return this._reader !== null
  }

  getReader() {
    if (this.locked) throw new TypeError('Stream is locked')

    this._reader = new exports.ReadableStreamDefaultReader(this)

    return this._reader
  }

  cancel(reason = new TypeError('Stream was cancelled')) {
    const stream = this._stream

    if (stream.destroyed) return Promise.resolve()

    if (this.locked) return Promise.reject(new TypeError('Stream is locked'))

    return new Promise((resolve) =>
      stream.once('close', resolve).once('error', noop).destroy(reason)
    )
  }

  tee() {
    const [a, b] = tee(this._stream)

    return [new ReadableStream(a), new ReadableStream(b)]
  }

  pipeTo(destination) {
    return new Promise((resolve, reject) =>
      this._stream.pipe(destination._stream, (err) => {
        err ? reject(err) : resolve()
      })
    )
  }

  [Symbol.asyncIterator]() {
    return this._stream[Symbol.asyncIterator]()
  }

  _releaseLock() {
    this._reader = null
  }

  async _read(starting, pull, cb) {
    await starting

    let err = null
    try {
      await pull()
    } catch (e) {
      err = e
    }
    cb(err)
  }
}

function defaultSize() {
  return 1
}

exports.ReadableStream = ReadableStream

// https://streams.spec.whatwg.org/#countqueuingstrategy
exports.CountQueuingStrategy = class CountQueuingStrategy {
  constructor(opts = {}) {
    const { highWaterMark = 1 } = opts

    this.highWaterMark = highWaterMark
  }

  size(chunk) {
    return 1
  }
}

// https://streams.spec.whatwg.org/#bytelengthqueuingstrategy
exports.ByteLengthQueuingStrategy = class ByteLengthQueuingStrategy {
  constructor(opts = {}) {
    const { highWaterMark = 16384 } = opts

    this.highWaterMark = highWaterMark
  }

  size(chunk) {
    return chunk.byteLength
  }
}

exports.isReadableStream = function isReadableStream(value) {
  if (value instanceof ReadableStream) return true

  return (
    typeof value === 'object' &&
    value !== null &&
    value[readableKind] === ReadableStream[readableKind]
  )
}

// https://streams.spec.whatwg.org/#readablestream-errored
exports.isReadableStreamErrored = function isReadableStreamErrored(stream) {
  return getStreamError(stream._stream) !== null
}

// https://streams.spec.whatwg.org/#is-readable-stream-disturbed
exports.isReadableStreamDisturbed = function isReadableStreamDisturbed(stream) {
  return isDisturbed(stream._stream)
}

// https://streams.spec.whatwg.org/#writablestreamdefaultwriter
exports.WritableStreamDefaultWriter = class WritableStreamDefaultWriter {
  constructor(stream) {
    this._stream = stream
    this._stream._stream.once('close', onclose).once('error', onerror)

    const closed = Promise.withResolvers()

    // Avoid unhandled exceptions
    closed.promise.catch(noop)

    this._closed = closed

    function onclose() {
      closed.resolve()
    }

    function onerror(err) {
      closed.reject(err)
    }
  }

  get desiredSize() {
    const stream = this._stream._stream

    return stream._writableState.highWaterMark - stream._writableState.buffered
  }

  get closed() {
    return this._closed.promise
  }

  get ready() {
    const stream = this._stream._stream

    if (getStreamError(stream)) return Promise.reject()

    return Writable.drained(stream).then()
  }

  async write(chunk) {
    const stream = this._stream._stream

    let err = getStreamError(stream)
    if (err) return Promise.reject(err)

    stream.write(chunk)

    await Writable.drained(stream)

    err = getStreamError(stream)
    if (err) return Promise.reject(err)
  }

  releaseLock() {
    this._closed.reject(new TypeError('Writer was released'))
    this._stream._releaseLock()
    this._stream = null
  }

  close() {
    const stream = this._stream._stream

    if (stream.destroyed) return Promise.resolve()

    return new Promise((resolve) => stream.once('close', resolve).end())
  }

  abort(reason = new TypeError('Stream was aborted')) {
    const stream = this._stream._stream

    if (stream.destroyed) return Promise.resolve()

    return new Promise((resolve) => stream.once('close', resolve).destroy(reason))
  }
}

// https://streams.spec.whatwg.org/#writablestreamdefaultcontroller
exports.WritableStreamDefaultController = class WritableStreamDefaultController {
  constructor(stream) {
    this._stream = stream
  }

  error(err) {
    this._stream._stream.destroy(err)
  }
}

// https://streams.spec.whatwg.org/#writablestream
class WritableStream {
  static get [writableKind]() {
    return 0 // Compatibility version
  }

  constructor(underlyingSink = {}, queuingStrategy = {}) {
    if (isStreamx(underlyingSink)) {
      this._stream = underlyingSink
    } else {
      if (queuingStrategy === undefined) {
        queuingStrategy = new exports.CountQueuingStrategy()
      }

      const { start, write, close, abort } = underlyingSink
      const { highWaterMark = 1, size = defaultSize } = queuingStrategy

      this._stream = new Writable({ highWaterMark, byteLength: size })

      const controller = new exports.WritableStreamDefaultController(this)

      this._controller = controller

      try {
        let starting = Promise.resolve()

        if (start) starting = forwardError(start.call(this, controller), controller)

        if (write) {
          this._stream._write = this._write.bind(this, starting, write.bind(this))
        }

        if (close) {
          this._stream._destroy = this._destroy.bind(this, close.call(this))
        }

        if (abort) {
          this._stream.once('error', abort.bind(this))
        }
      } catch (err) {
        controller.error(err)
      }
    }

    this._writer = null
  }

  get [writableKind]() {
    return WritableStream[writableKind]
  }

  get locked() {
    return this._writer !== null
  }

  getWriter() {
    if (this.locked) throw new TypeError('Stream is locked')

    this._writer = new exports.WritableStreamDefaultWriter(this)

    return this._writer
  }

  abort(reason = new TypeError('Stream was aborted')) {
    if (this._stream.destroyed) return Promise.resolve()

    if (this.locked) return Promise.reject(new TypeError('Stream is locked'))

    return new Promise((resolve) => this._stream.once('close', resolve).destroy(reason))
  }

  close() {
    if (this._stream.destroyed) return Promise.resolve()

    if (this.locked) return Promise.reject(new TypeError('Stream is locked'))

    return new Promise((resolve) => this._stream.once('close', resolve).end())
  }

  _releaseLock() {
    this._writer = null
  }

  async _write(starting, write, data, cb) {
    await starting

    let err = null
    try {
      await write(data, this._controller)
    } catch (e) {
      err = e
    }
    cb(err)
  }

  async _destroy(closing, cb) {
    let err = null
    try {
      await closing
    } catch (e) {
      err = e
    }
    cb(err)
  }
}

exports.WritableStream = WritableStream

exports.isWritableStream = function isWritableStream(value) {
  if (value instanceof WritableStream) return true

  return (
    typeof value === 'object' &&
    value !== null &&
    value[writableKind] === WritableStream[writableKind]
  )
}

// https://streams.spec.whatwg.org/#transformstreamdefaultcontroller
exports.TransformStreamDefaultController = class TransformStreamDefaultController {
  constructor(stream) {
    this._stream = stream
  }

  get desiredSize() {
    const stream = this._stream._stream

    return stream._readableState.highWaterMark - stream._readableState.buffered
  }

  enqueue(data) {
    this._stream._stream.push(data)
  }

  error(err) {
    this._stream._stream.destroy(err)
  }

  terminate() {
    const stream = this._stream._stream

    stream.push(null)
    stream.destroy(new TypeError('Stream has been terminated'))
  }
}

// https://streams.spec.whatwg.org/#transformstream
class TransformStream {
  static get [transformKind]() {
    return 0 // Compatibility version
  }

  constructor(transformer = {}, writableStrategy = {}, readableStrategy = {}) {
    if (isStreamx(transformer)) {
      this._stream = transformer
    } else {
      const { start, transform, flush } = transformer

      this._stream = new Transform({ ...writableStrategy, ...readableStrategy })

      const controller = new exports.TransformStreamDefaultController(this)

      this._controller = controller

      try {
        let starting = Promise.resolve()

        if (start) starting = forwardError(start.call(this, controller), controller)

        if (transform) {
          this._stream._transform = this._transform.bind(this, starting, transform.bind(this))
        }

        if (flush) {
          this._stream._flush = this._flush.bind(this, flush.call(this, this._controller))
        }
      } catch (err) {
        controller.error(err)
      }
    }

    this._writable = new WritableStream(this._stream)
    this._readable = new ReadableStream(this._stream)
  }

  get [transformKind]() {
    return TransformStream[transformKind]
  }

  get writable() {
    return this._writable
  }

  get readable() {
    return this._readable
  }

  async _transform(starting, transform, data, cb) {
    await starting

    let err = null
    try {
      await transform(data, this._controller)
    } catch (e) {
      err = e
    }
    cb(err)
  }

  async _flush(flush, cb) {
    let err = null
    try {
      await flush
    } catch (e) {
      err = e
    }
    cb(err)
  }
}

exports.TransformStream = TransformStream

exports.isTransformStream = function isTransformStream(value) {
  if (value instanceof TransformStream) return true

  return (
    typeof value === 'object' &&
    value !== null &&
    value[transformKind] === TransformStream[transformKind]
  )
}

async function forwardError(promise, controller) {
  try {
    await promise
  } catch (err) {
    controller.error(err)
  }
}

function noop() {}
module.exports = require.addon()
const EventEmitter = require('bare-events')
const { Duplex } = require('bare-stream')
const dns = require('bare-dns')
const binding = require('./binding')
const constants = require('./lib/constants')
const errors = require('./lib/errors')
const ip = require('./lib/ip')

const defaultReadBufferSize = 65536
const empty = Buffer.alloc(0)

const ipcHandle = Symbol.for('bare.ipc.handle')
const ipcAccept = Symbol.for('bare.ipc.accept')

exports.Socket = class TCPSocket extends Duplex {
  constructor(opts = {}) {
    const { readBufferSize = defaultReadBufferSize, allowHalfOpen = true, eagerOpen = true } = opts

    super({ eagerOpen })

    this._state = 0

    this._allowHalfOpen = allowHalfOpen

    this._keepAlive = 0
    this._keepAliveInitialDelay = 0
    this._noDelay = 0

    this._localAddress = null
    this._remoteAddress = null

    this._pendingOpen = null
    this._pendingWrite = null
    this._pendingWriteBatch = null
    this._pendingFinal = null
    this._pendingDestroy = null

    this._timer = null
    this._timeout = 0

    this._buffer = Buffer.alloc(readBufferSize)

    this._addresses = null
    this._errors = null

    this._handle = binding.init(
      this._buffer,
      this,
      noop,
      this._onconnect,
      this._onreset,
      this._onread,
      this._onwrite,
      this._onfinal,
      this._onclose
    )
  }

  get connecting() {
    return (this._state & constants.state.CONNECTING) !== 0
  }

  get pending() {
    return (this._state & constants.state.CONNECTED) === 0
  }

  get timeout() {
    return this._timeout || undefined // For Node.js compatibility
  }

  get readyState() {
    if (this._state & constants.state.CONNECTED) {
      return 'open'
    }

    return 'opening'
  }

  get localAddress() {
    if (this._localAddress) return this._localAddress.address
  }

  get localFamily() {
    if (this._localAddress) return `IPv${this._localAddress.family}`
  }

  get localPort() {
    if (this._localAddress) return this._localAddress.port
  }

  get remoteAddress() {
    if (this._remoteAddress) return this._remoteAddress.address
  }

  get remoteFamily() {
    if (this._remoteAddress) return `IPv${this._remoteAddress.family}`
  }

  get remotePort() {
    if (this._remoteAddress) return this._remoteAddress.port
  }

  get [ipcHandle]() {
    return this._handle
  }

  connect(port, host = 'localhost', opts = {}, onconnect) {
    if (this._state & constants.state.CONNECTING || this._state & constants.state.CONNECTED) {
      throw errors.SOCKET_ALREADY_CONNECTED('Socket is already connected')
    }

    if (typeof host === 'function') {
      onconnect = host
      host = 'localhost'
    } else if (typeof opts === 'function') {
      onconnect = opts
      opts = {}
    }

    let family = 0

    if (typeof port === 'object' && port !== null) {
      opts = port || {}
      port = opts.port || 0
      host = opts.host || 'localhost'
      family = opts.family || 0
    }

    if (!host) host = 'localhost'

    validatePort(port)

    this._state |= constants.state.CONNECTING

    const {
      lookup = dns.lookup,
      hints,
      keepAlive = false,
      keepAliveInitialDelay = 0,
      noDelay = false,
      timeout
    } = opts

    const type = ip.isIP(host)

    if (type === 0) {
      lookup(host, { all: true, family, hints }, (err, addresses) => {
        if (this._state & constants.state.CLOSING) return

        this._state &= ~constants.state.CONNECTING

        if (err || addresses.length === 0) {
          if (!err) {
            err = new Error(`No address found for host "${host}"`)
            err.code = 'ENOTFOUND'
          }

          this.emit('lookup', err, null, 0, host)

          if (this._pendingOpen) this._continueOpen(err)
          else this.destroy(err)
          return
        }

        for (const { address, family } of addresses) {
          this.emit('lookup', null, address, family, host)
        }

        const [{ address, family }, ...rest] = addresses

        if (rest.length > 0) {
          this._addresses = rest.map(({ address, family }) => [
            port,
            address,
            { ...opts, family },
            onconnect
          ])

          this._errors = []
        }

        this.connect(port, address, { ...opts, family }, onconnect)
      })

      return this
    }

    family = type

    try {
      binding.connect(this._handle, port, host, family)

      if (keepAlive) {
        this._keepAlive = keepAlive
        this._keepAliveInitialDelay = keepAliveInitialDelay
      }
      if (noDelay) this._noDelay = noDelay
      if (timeout) this.setTimeout(timeout)

      if (onconnect) this.once('connect', onconnect)
    } catch (err) {
      queueMicrotask(() => {
        if (this._pendingOpen) this._pendingOpen(err)
        else this.destroy(err)
      })
    }

    return this
  }

  open(fd, opts = {}, onconnect) {
    if (typeof opts === 'function') {
      onconnect = opts
      opts = {}
    }

    if (typeof fd === 'object' && fd !== null) {
      opts = fd
      fd = opts.fd
    }

    try {
      binding.open(this._handle, fd)

      this._state |= constants.state.CONNECTED

      if (onconnect) this.once('connect', onconnect)

      queueMicrotask(() => this.emit('connect'))
    } catch (err) {
      queueMicrotask(() => {
        if (this._pendingOpen) this._pendingOpen(err)
        else this.destroy(err)
      })
    }

    return this
  }

  setKeepAlive(enable = false, delay = 0) {
    if (typeof enable === 'number') {
      delay = enable
      enable = false
    }

    delay = Math.floor(delay / 1000)

    if (delay === 0) enable = false

    binding.keepalive(this._handle, enable, delay)

    return this
  }

  setNoDelay(enable = true) {
    binding.nodelay(this._handle, enable)

    return this
  }

  setTimeout(ms, ontimeout) {
    if (ms === 0) {
      clearTimeout(this._timer)

      this._timer = null
    } else {
      if (ontimeout) this.once('timeout', ontimeout)

      this._timer = setTimeout(() => this.emit('timeout'), ms)
      this._timer.unref()
    }

    this._timeout = ms

    return this
  }

  ref() {
    binding.ref(this._handle)

    return this
  }

  unref() {
    binding.unref(this._handle)

    return this
  }

  [ipcAccept]() {
    this._onaccept()
  }

  _open(cb) {
    if (this._state & constants.state.CONNECTED) return cb(null)

    this._pendingOpen = cb
  }

  _read() {
    if ((this._state & constants.state.READING) === 0) {
      this._state |= constants.state.READING

      binding.resume(this._handle)
    }
  }

  _writev(batch, cb) {
    this._pendingWrite = cb
    this._pendingWriteBatch = batch

    try {
      binding.writev(
        this._handle,
        batch.map(({ chunk }) => chunk)
      )
    } catch (err) {
      this._continueWrite(err)
    }
  }

  _final(cb) {
    this._pendingFinal = cb

    binding.end(this._handle)
  }

  _predestroy() {
    if (this._state & constants.state.CLOSING) return
    this._state |= constants.state.CLOSING

    binding.close(this._handle)
  }

  _destroy(err, cb) {
    if (this._state & constants.state.CLOSING) return cb(err)
    this._state |= constants.state.CLOSING

    this._pendingDestroy = cb

    binding.close(this._handle)
  }

  _continueOpen(err) {
    if (this._pendingOpen === null) return
    const cb = this._pendingOpen
    this._pendingOpen = null
    cb(err)
  }

  _continueWrite(err) {
    if (this._pendingWrite === null) return
    const cb = this._pendingWrite
    this._pendingWrite = null
    this._pendingWriteBatch = null
    cb(err)
  }

  _continueFinal(err) {
    if (this._pendingFinal === null) return
    const cb = this._pendingFinal
    this._pendingFinal = null
    cb(err)
  }

  _continueDestroy() {
    if (this._pendingDestroy === null) return
    const cb = this._pendingDestroy
    this._pendingDestroy = null
    cb(null)
  }

  _reset() {
    this._state = 0

    this._localAddress = null
    this._remoteAddress = null

    binding.reset(this._handle)
  }

  _onconnect(err) {
    if (err) {
      if (this._addresses !== null) {
        this._errors.push(err)

        if (this._addresses.length > 0) return this._reset()

        err = this._errors.length === 1 ? this._errors[0] : new AggregateError(this._errors)
      }

      if (this._pendingOpen) this._continueOpen(err)
      else this.destroy(err)
      return
    }

    if (this._keepAlive) this.setKeepAlive(this._keepAlive, this._keepAliveInitialDelay)
    if (this._noDelay) this.setNoDelay()

    this._localAddress = binding.address(this._handle, true)
    this._remoteAddress = binding.address(this._handle, false)

    this._state |= constants.state.CONNECTED
    this._state &= ~constants.state.CONNECTING
    this._continueOpen()

    this.emit('connect')
  }

  _onaccept() {
    try {
      this._localAddress = binding.address(this._handle, true)
    } catch {
      this._localAddress = null
    }

    try {
      this._remoteAddress = binding.address(this._handle, false)
    } catch {
      this._remoteAddress = null
    }

    this._state |= constants.state.CONNECTED
    this._continueOpen()
  }

  _onreset(err) {
    if (err) {
      this._errors.push(err)
      this.destroy(this._errors.length === 1 ? this._errors[0] : new AggregateError(this._errors))
      return
    }

    this.connect(...this._addresses.shift())
  }

  _onread(err, read) {
    if (this._timer) this._timer.refresh()

    if (err) {
      this.destroy(err)
      return
    }

    if (read === 0) {
      this.push(null)
      if (this._allowHalfOpen === false) this.end()
      return
    }

    const copy = Buffer.allocUnsafe(read)
    copy.set(this._buffer.subarray(0, read))

    if (this.push(copy) === false && this.destroying === false) {
      this._state &= ~constants.state.READING

      binding.pause(this._handle)
    }
  }

  _onwrite(err) {
    if (this._timer) this._timer.refresh()

    this._continueWrite(err)
  }

  _onfinal(err) {
    this._continueFinal(err)
  }

  _onclose() {
    clearTimeout(this._timer)

    this._continueOpen()
    this._continueDestroy()
  }
}

exports.Server = class TCPServer extends EventEmitter {
  constructor(opts = {}, onconnection) {
    if (typeof opts === 'function') {
      onconnection = opts
      opts = {}
    }

    super()

    const {
      readBufferSize = defaultReadBufferSize,
      allowHalfOpen = true,
      keepAlive = false,
      keepAliveInitialDelay = 0,
      noDelay = false,
      pauseOnConnect = false,
      maxConnections = Infinity
    } = opts

    this._state = 0

    this._readBufferSize = readBufferSize
    this._allowHalfOpen = allowHalfOpen
    this._keepAlive = keepAlive
    this._keepAliveInitialDelay = keepAliveInitialDelay
    this._noDelay = noDelay
    this._pauseOnConnect = pauseOnConnect
    this._maxConnections = maxConnections

    this._address = null
    this._connections = new Set()

    this._error = null
    this._handle = null

    if (onconnection) this.on('connection', onconnection)
  }

  get listening() {
    return (this._state & constants.state.BOUND) !== 0
  }

  get closing() {
    return (this._state & constants.state.CLOSING) !== 0
  }

  get connections() {
    return this._connections
  }

  get maxConnections() {
    return this._maxConnections
  }

  set maxConnections(value) {
    this._maxConnections = value
  }

  address() {
    if ((this._state & constants.state.BOUND) === 0) return null

    const { address, family, port } = this._address

    return { address, family: `IPv${family}`, port }
  }

  listen(port = 0, host = 'localhost', backlog = 511, opts = {}, onlistening) {
    if (this._state & constants.state.BINDING || this._state & constants.state.BOUND) {
      throw errors.SERVER_ALREADY_LISTENING('Server is already listening')
    }

    if (this._state & constants.state.CLOSING) {
      throw errors.SERVER_IS_CLOSED('Server is closed')
    }

    if (typeof port === 'function') {
      onlistening = port
      port = 0
    } else if (typeof host === 'function') {
      onlistening = host
      host = 'localhost'
    } else if (typeof backlog === 'function') {
      onlistening = backlog
      backlog = 511
    } else if (typeof opts === 'function') {
      onlistening = opts
      opts = {}
    }

    let family = 0

    if (typeof port === 'object' && port !== null) {
      opts = port || {}
      port = opts.port || 0
      host = opts.host || 'localhost'
      family = opts.family || 0
      backlog = opts.backlog || 511
    }

    if (!host) host = 'localhost'
    if (!backlog) backlog = 511

    validatePort(port)

    this._state |= constants.state.BINDING

    const { lookup = dns.lookup, hints } = opts

    const type = ip.isIP(host)

    if (type === 0) {
      lookup(host, { family, hints }, (err, address, family) => {
        if (this._state & constants.state.CLOSING) return

        this.emit('lookup', err, address, family, host)

        this._state &= ~constants.state.BINDING

        if (err) return this.emit('error', err)

        this.listen(port, address, backlog, { ...opts, family }, onlistening)
      })

      return this
    }

    family = type

    this._handle = binding.init(
      empty,
      this,
      this._onconnection,
      noop,
      noop,
      noop,
      noop,
      noop,
      this._onclose
    )

    if (this._state & constants.state.UNREFED) binding.unref(this._handle)

    try {
      binding.bind(this._handle, port, host, backlog, family)

      this._address = binding.address(this._handle, true)

      this._state |= constants.state.BOUND
      this._state &= ~constants.state.BINDING

      if (onlistening) this.once('listening', onlistening)

      queueMicrotask(() => this.emit('listening'))
    } catch (err) {
      this._error = err

      binding.close(this._handle)
    }

    return this
  }

  close(onclose) {
    if (onclose) this.once('close', onclose)

    if (this._state & constants.state.CLOSING) return this
    this._state |= constants.state.CLOSING

    this._closeMaybe()

    return this
  }

  ref() {
    this._state &= ~constants.state.UNREFED

    if (this._handle !== null) binding.ref(this._handle)

    return this
  }

  unref() {
    this._state |= constants.state.UNREFED

    if (this._handle !== null) binding.unref(this._handle)

    return this
  }

  _closeMaybe() {
    if (this._state & constants.state.CLOSING && this._connections.size === 0) {
      if (this._handle !== null) binding.close(this._handle)
      else queueMicrotask(() => this.emit('close'))
    }
  }

  _onconnection(err) {
    if (err) {
      this.emit('error', err)
      return
    }

    if (this._state & constants.state.CLOSING) return

    const overLimit = this._connections.size >= this._maxConnections

    const socket = new exports.Socket({
      readBufferSize: overLimit ? 0 : this._readBufferSize,
      allowHalfOpen: this._allowHalfOpen,
      eagerOpen: !this._pauseOnConnect
    })

    try {
      binding.accept(this._handle, socket._handle)

      socket._onaccept()

      if (overLimit) {
        const info = {
          localAddress: socket.localAddress,
          localPort: socket.localPort,
          localFamily: socket.localFamily,
          remoteAddress: socket.remoteAddress,
          remotePort: socket.remotePort,
          remoteFamily: socket.remoteFamily
        }

        socket.destroy()

        this.emit('drop', info)
        return
      }

      this._connections.add(socket)

      if (this._keepAlive) socket.setKeepAlive(this._keepAlive, this._keepAliveInitialDelay)
      if (this._noDelay) socket.setNoDelay()

      socket.on('close', () => {
        this._connections.delete(socket)
        this._closeMaybe()
      })

      this.emit('connection', socket)
    } catch (err) {
      socket.destroy()

      this.emit('error', err)
    }
  }

  _onclose() {
    const err = this._error

    this._state &= ~constants.state.BINDING
    this._error = null
    this._handle = null
    this._address = null

    if (err) this.emit('error', err)
    else this.emit('close')
  }
}

exports.constants = constants
exports.errors = errors

exports.isIP = ip.isIP
exports.isIPv4 = ip.isIPv4
exports.isIPv6 = ip.isIPv6

exports.createConnection = function createConnection(port, host, opts, onconnect) {
  if (typeof host === 'function') {
    onconnect = host
    host = 'localhost'
  } else if (typeof opts === 'function') {
    onconnect = opts
    opts = {}
  }

  if (typeof port === 'object' && port !== null) {
    opts = port || {}
    port = opts.port || 0
    host = opts.host || 'localhost'
  }

  return new exports.Socket(opts).connect(port, host, opts, onconnect)
}

// For Node.js compatibility
exports.connect = exports.createConnection

exports.createServer = function createServer(opts, onconnection) {
  return new exports.Server(opts, onconnection)
}

exports.socketpair = function socketpair() {
  return binding.socketpair()
}

function validatePort(port) {
  if (typeof port !== 'number') {
    throw errors.INVALID_PORT(`Port must be a number, got ${typeof port}`)
  }

  if (!Number.isInteger(port) || port < 0 || port > 0xffff) {
    throw errors.INVALID_PORT(`Port must be an integer between 0 and 65535, got ${port}`)
  }
}

function noop() {}
module.exports = {
  state: {
    CONNECTING: 0x1,
    CONNECTED: 0x2,
    BINDING: 0x4,
    BOUND: 0x8,
    READING: 0x10,
    CLOSING: 0x20,
    UNREFED: 0x40
  }
}
module.exports = class TCPError extends Error {
  constructor(msg, fn = TCPError, code = fn.name) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'TCPError'
  }

  static SOCKET_ALREADY_CONNECTED(msg) {
    return new TCPError(msg, TCPError.SOCKET_ALREADY_CONNECTED)
  }

  static SERVER_ALREADY_LISTENING(msg) {
    return new TCPError(msg, TCPError.SERVER_ALREADY_LISTENING)
  }

  static SERVER_IS_CLOSED(msg) {
    return new TCPError(msg, TCPError.SERVER_IS_CLOSED)
  }

  static INVALID_HOST(msg = 'Unrecognizable host format') {
    return new TCPError(msg, TCPError.INVALID_HOST)
  }

  static INVALID_PORT(msg) {
    return new TCPError(msg, TCPError.INVALID_PORT)
  }
}
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

const v4Seg = '(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])'
const v4Str = `(${v4Seg}[.]){3}${v4Seg}`
const IPv4Pattern = new RegExp(`^${v4Str}$`)

const v6Seg = '(?:[0-9a-fA-F]{1,4})'
const IPv6Pattern = new RegExp(
  '^(' +
    `(?:${v6Seg}:){7}(?:${v6Seg}|:)|` +
    `(?:${v6Seg}:){6}(?:${v4Str}|:${v6Seg}|:)|` +
    `(?:${v6Seg}:){5}(?::${v4Str}|(:${v6Seg}){1,2}|:)|` +
    `(?:${v6Seg}:){4}(?:(:${v6Seg}){0,1}:${v4Str}|(:${v6Seg}){1,3}|:)|` +
    `(?:${v6Seg}:){3}(?:(:${v6Seg}){0,2}:${v4Str}|(:${v6Seg}){1,4}|:)|` +
    `(?:${v6Seg}:){2}(?:(:${v6Seg}){0,3}:${v4Str}|(:${v6Seg}){1,5}|:)|` +
    `(?:${v6Seg}:){1}(?:(:${v6Seg}){0,4}:${v4Str}|(:${v6Seg}){1,6}|:)|` +
    `(?::((?::${v6Seg}){0,5}:${v4Str}|(?::${v6Seg}){1,7}|:))` +
    ')(%[0-9a-zA-Z-.:]{1,})?$'
)

const isIPv4 = (exports.isIPv4 = function isIPv4(host) {
  return IPv4Pattern.test(host)
})

const isIPv6 = (exports.isIPv6 = function isIPv6(host) {
  return IPv6Pattern.test(host)
})

exports.isIP = function isIP(host) {
  if (isIPv4(host)) return 4
  if (isIPv6(host)) return 6
  return 0
}
{
  "name": "bare-tcp",
  "version": "2.5.2",
  "description": "Native TCP sockets for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./constants": "./lib/constants.js",
    "./errors": "./lib/errors.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-tcp.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-tcp/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-tcp#readme",
  "engines": {
    "bare": ">=1.16.0"
  },
  "dependencies": {
    "bare-dns": "^2.0.4",
    "bare-events": "^2.5.4",
    "bare-stream": "^2.6.4"
  },
  "devDependencies": {
    "bare-pipe": "^4.1.5",
    "brittle": "^3.5.0",
    "cmake-bare": "^1.1.6",
    "lunte": "^1.6.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "bare-pipe": "*"
  },
  "peerDependenciesMeta": {
    "bare-pipe": {
      "optional": true
    }
  }
}
module.exports = require.addon()
const { Duplex, Writable } = require('bare-stream')
const binding = require('./binding')
const constants = require('./lib/constants')
const errors = require('./lib/errors')

const defaultReadBufferSize = 65536

const context = binding.context()

exports.Socket = class TLSSocket extends Duplex {
  constructor(socket, opts = {}) {
    const {
      isServer = false,
      cert = null,
      key = null,
      host = null,
      rejectUnauthorized = true,
      ca = null,
      alpnProtocols = null,
      eagerOpen = true,
      allowHalfOpen = true,
      readBufferSize = defaultReadBufferSize
    } = opts

    if (!isServer && rejectUnauthorized && !host) {
      throw new TypeError("'host' is required for client sockets when 'rejectUnauthorized' is true")
    }

    super({ eagerOpen })

    this._state = 0

    this._socket = socket
    this._allowHalfOpen = allowHalfOpen

    this._pendingOpen = null
    this._pendingWrite = null
    this._pendingDestroy = null

    this._reading = Buffer.alloc(readBufferSize)
    this._buffer = []
    this._buffered = 0

    this._ondata = this._ondata.bind(this)
    this._ondrain = this._ondrain.bind(this)
    this._onend = this._onend.bind(this)
    this._onclose = this._onclose.bind(this)
    this._onerror = this._onerror.bind(this)

    socket.on('close', this._onclose).on('error', this._onerror)

    let alpn = null

    if (alpnProtocols && alpnProtocols.length > 0) {
      const parts = []

      for (const protocol of alpnProtocols) {
        const encoded = Buffer.from(protocol)

        if (encoded.byteLength === 0 || encoded.byteLength > 255) {
          throw new RangeError('ALPN protocol name must be 1-255 bytes')
        }

        parts.push(Buffer.of(encoded.byteLength), encoded)
      }

      alpn = Buffer.concat(parts)
    }

    try {
      this._handle = binding.init(
        context,
        isServer,
        cert,
        key,
        host,
        rejectUnauthorized,
        ca,
        alpn,
        this,
        this._onread,
        this._onwrite
      )
    } catch (err) {
      this._handle = null

      this.destroy(err)
    }
  }

  get socket() {
    return this._socket
  }

  get encrypted() {
    return true
  }

  get alpnProtocol() {
    return this._handle ? binding.alpnProtocol(this._handle) : null
  }

  _onconnect() {
    this._state |= constants.state.CONNECTED

    this.emit('connect')

    const cb = this._pendingOpen
    this._pendingOpen = null
    cb(null)
  }

  _ondata(data) {
    this._buffer.push(data)
    this._buffered += data.byteLength

    while (this._buffered > 0) {
      if (this._state & constants.state.CONNECTED) {
        let read
        try {
          read = binding.read(this._handle, this._reading)
        } catch (err) {
          return this.destroy(errors.from(err))
        }

        if (read < 0) break

        if (read === 0) {
          this.push(null)
          if (this._allowHalfOpen === false) this.end()
          return
        }

        const copy = Buffer.allocUnsafe(read)
        copy.set(this._reading.subarray(0, read))

        this.push(copy)
      } else {
        try {
          if (binding.handshake(this._handle)) this._onconnect()
          else break
        } catch (err) {
          err = errors.from(err)

          // Defer so any alert the handshake wrote to the underlying socket
          // gets a chance to flush before we tear it down.
          queueMicrotask(() => {
            if (this._pendingOpen) {
              const cb = this._pendingOpen
              this._pendingOpen = null
              cb(err)
            } else {
              this.destroy(err)
            }
          })
          return
        }
      }
    }
  }

  _ondrain() {
    if (this._pendingWrite === null) return
    const cb = this._pendingWrite
    this._pendingWrite = null
    cb(null)
  }

  _onend() {
    this.push(null)
  }

  _onclose() {
    this._socket.off('close', this._onclose).off('error', this._onerror)

    if (this._pendingDestroy) {
      const cb = this._pendingDestroy
      this._pendingDestroy = null
      cb()
    }
  }

  _onerror(err) {
    if (this._pendingOpen) {
      const cb = this._pendingOpen
      this._pendingOpen = null
      cb(err)
    } else if (this._pendingDestroy) {
      const cb = this._pendingDestroy
      this._pendingDestroy = null
      cb(err)
    } else {
      this.destroy(err)
    }
  }

  _onread(data) {
    if (this._buffered < data.byteLength) return 0

    let offset = 0
    let remaining = data.byteLength

    while (remaining > 0) {
      const chunk = this._buffer[0]

      if (chunk.byteLength <= remaining) {
        data.set(chunk, offset)

        offset += chunk.byteLength
        remaining -= chunk.byteLength

        this._buffer.shift()
      } else {
        data.set(chunk.subarray(0, remaining), offset)

        this._buffer[0] = chunk.subarray(remaining)

        remaining = 0
      }
    }

    this._buffered -= data.byteLength

    return data.byteLength
  }

  _onwrite(data) {
    this._socket.write(Buffer.from(data.slice()))

    return data.byteLength
  }

  _attach() {
    if (this._state & constants.state.ATTACHED) return
    this._state |= constants.state.ATTACHED

    this._socket.on('data', this._ondata).on('drain', this._ondrain).on('end', this._onend)
  }

  _detach() {
    if (!(this._state & constants.state.ATTACHED)) return
    this._state &= ~constants.state.ATTACHED

    this._socket.off('data', this._ondata).off('drain', this._ondrain).off('end', this._onend)
  }

  _open(cb) {
    this._pendingOpen = cb
    this._attach()

    try {
      if (binding.handshake(this._handle)) this._onconnect()
    } catch (err) {
      this._pendingOpen = null

      cb(errors.from(err))
    }
  }

  _write(data, encoding, cb) {
    try {
      binding.write(this._handle, data)

      if (Writable.isBackpressured(this._socket)) {
        this._pendingWrite = cb
      } else {
        cb(null)
      }
    } catch (err) {
      this._pendingWrite = null

      cb(errors.from(err))
    }
  }

  _final(cb) {
    try {
      binding.shutdown(this._handle)

      cb(null)
    } catch (err) {
      cb(err)
    }

    this._socket.end()
  }

  _predestroy() {
    if (this._handle) {
      this._detach()

      binding.destroy(this._handle)
      this._handle = null
    }

    this._socket.destroy()
  }

  _destroy(err, cb) {
    if (this._handle) {
      this._detach()

      binding.destroy(this._handle)
      this._handle = null
    }

    if (err) this._socket.destroy()

    if (this._socket.destroyed) cb(err)
    else this._pendingDestroy = cb
  }
}

exports.TLSSocket = exports.Socket // For Node.js compatibility

exports.constants = constants
exports.errors = errors

const net = require('./net')

exports.createConnection = net.createConnection
exports.createServer = net.createServer

// For Node.js compatibility
exports.connect = exports.createConnection
module.exports = {
  state: {
    CONNECTED: 0x1,
    ATTACHED: 0x2
  }
}
module.exports = class TLSError extends Error {
  constructor(msg, code, fn = TLSError) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'TLSError'
  }

  static from(err) {
    return new TLSError(err.message, err.code, TLSError.from)
  }
}
const EventEmitter = require('bare-events')
const net = require('bare-net')
const tls = require('bare-tls')

class TLSNetSocket extends tls.Socket {
  ref() {
    this.socket.ref()
  }

  unref() {
    this.socket.unref()
  }
}

class TLSNetServer extends EventEmitter {
  constructor(opts = {}, onconnection) {
    if (typeof opts === 'function') {
      onconnection = opts
      opts = {}
    }

    const {
      cert = null,
      key = null,
      host = null,
      rejectUnauthorized = true,
      ca = null,
      alpnProtocols = null,
      eagerOpen = true,
      allowHalfOpen = true
    } = opts

    super()

    this._opts = {
      cert,
      key,
      host,
      rejectUnauthorized,
      ca,
      alpnProtocols,
      eagerOpen,
      allowHalfOpen
    }

    this._server = net.createServer(opts)
    this._server
      .on('listening', this._onlistening.bind(this))
      .on('connection', this._onconnection.bind(this))
      .on('error', this._onerror.bind(this))
      .on('close', this._onclose.bind(this))

    if (onconnection) this.on('connection', onconnection)
  }

  get listening() {
    return this._server.listening
  }

  address() {
    return this._server.address()
  }

  listen(...args) {
    this._server.listen(...args)
    return this
  }

  close(onclose) {
    if (onclose) this.once('close', onclose)
    this._server.close()
  }

  ref() {
    this._server.ref()
  }

  unref() {
    this._server.unref()
  }

  _onlistening() {
    this.emit('listening')
  }

  _onconnection(socket) {
    this.emit('connection', new TLSNetSocket(socket, { ...this._opts, isServer: true }))
  }

  _onerror(err) {
    this.emit('error', err)
  }

  _onclose() {
    this.emit('close')
  }
}

exports.createConnection = function createConnection(...args) {
  let opts = {}
  let onconnect

  if (typeof args[0] === 'string') {
    // createConnection(path[, onconnect])
    opts.path = args[0]
    onconnect = args[1]
  } else if (typeof args[0] === 'number') {
    // createConnection(port[, host][, onconnect])
    opts.port = args[0]

    if (typeof args[1] === 'function') {
      onconnect = args[1]
    } else {
      opts.host = args[1]
      onconnect = args[2]
    }
  } else {
    // createConnection(opts[, onconnect])
    opts = args[0] || {}
    onconnect = args[1]
  }

  if (!opts.host && !opts.path) opts.host = 'localhost'

  return new TLSNetSocket(net.createConnection(opts, onconnect), opts)
}

exports.createServer = function createServer(opts, onconnection) {
  return new TLSNetServer(opts, onconnection)
}
{
  "name": "bare-tls",
  "version": "3.1.7",
  "description": "Transport Layer Security (TLS) streams for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    },
    "./errors": {
      "types": "./lib/errors.d.ts",
      "default": "./lib/errors.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "net.js",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-tls.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-tls/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-tls#readme",
  "engines": {
    "bare": ">=1.7.0"
  },
  "dependencies": {
    "bare-net": "^2.0.1",
    "bare-stream": "^2.6.4"
  },
  "devDependencies": {
    "bare-events": "^2.6.0",
    "bare-fs": "^4.0.2",
    "brittle": "^3.1.1",
    "cmake-bare": "^1.1.6",
    "cmake-fetch": "^1.0.0",
    "lunte": "^1.6.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = require.addon()
const { Readable, Writable } = require('bare-stream')
const Signal = require('bare-signals')
const binding = require('./binding')
const constants = require('./lib/constants')

const defaultReadBufferSize = 65536
const empty = Buffer.alloc(0)

exports.ReadStream = class TTYReadStream extends Readable {
  constructor(fd, opts = {}) {
    super()

    const { readBufferSize = defaultReadBufferSize, allowHalfOpen = true } = opts

    this._fd = fd
    this._state = 0
    this._allowHalfOpen = allowHalfOpen
    this._buffer = Buffer.alloc(readBufferSize)

    this._pendingDestroy = null

    this._handle = binding.init(fd, this._buffer, this, noop, this._onread, this._onclose)
  }

  get fd() {
    return this._fd
  }

  get isTTY() {
    return true
  }

  setMode(mode) {
    binding.setMode(this._handle, mode)
    return this
  }

  setRawMode(enabled) {
    return this.setMode(enabled ? constants.mode.RAW : constants.mode.NORMAL)
  }

  _read() {
    if ((this._state & constants.state.READING) === 0) {
      this._state |= constants.state.READING

      binding.resume(this._handle)
    }
  }

  _predestroy() {
    if (this._state & constants.state.CLOSING) return
    this._state |= constants.state.CLOSING

    binding.close(this._handle)
  }

  _destroy(err, cb) {
    if (this._state & constants.state.CLOSING) return cb(err)
    this._state |= constants.state.CLOSING

    this._pendingDestroy = cb

    binding.close(this._handle)
  }

  _continueDestroy() {
    if (this._pendingDestroy === null) return
    const cb = this._pendingDestroy
    this._pendingDestroy = null
    cb(null)
  }

  _onread(err, read) {
    if (err) {
      this.destroy(err)
      return
    }

    if (read === 0) {
      this.push(null)
      if (this._allowHalfOpen === false) this.end()
      return
    }

    const copy = Buffer.allocUnsafe(read)
    copy.set(this._buffer.subarray(0, read))

    if (this.push(copy) === false && this.destroying === false) {
      this._state &= ~constants.state.READING

      binding.pause(this._handle)
    }
  }

  _onclose() {
    this._handle = null

    this._continueDestroy()
  }
}

exports.WriteStream = class TTYWriteStream extends Writable {
  constructor(fd, opts = {}) {
    super()

    this._fd = fd
    this._state = 0
    this._size = null

    this._pendingWrite = null
    this._pendingWriteBatch = null
    this._pendingDestroy = null

    this._handle = binding.init(fd, empty, this, this._onwrite, noop, this._onclose)

    this._size = this.getWindowSize()

    if (TTYWriteStream._streams.size === 0) TTYWriteStream._resize.start()

    TTYWriteStream._streams.add(this)
  }

  get fd() {
    return this._fd
  }

  get isTTY() {
    return true
  }

  get columns() {
    return this._size[0]
  }

  get rows() {
    return this._size[1]
  }

  getWindowSize() {
    return binding.getWindowSize(this._handle)
  }

  _writev(batch, cb) {
    this._pendingWrite = cb
    this._pendingWriteBatch = batch

    try {
      binding.writev(
        this._handle,
        batch.map(({ chunk }) => chunk)
      )
    } catch (err) {
      this._continueWrite(err)
    }
  }

  _predestroy() {
    if (this._state & constants.state.CLOSING) return
    this._state |= constants.state.CLOSING

    binding.close(this._handle)

    TTYWriteStream._streams.delete(this)

    if (TTYWriteStream._streams.size === 0) TTYWriteStream._resize.stop()
  }

  _destroy(err, cb) {
    if (this._state & constants.state.CLOSING) return cb(err)
    this._state |= constants.state.CLOSING

    this._pendingDestroy = cb

    binding.close(this._handle)

    TTYWriteStream._streams.delete(this)

    if (TTYWriteStream._streams.size === 0) TTYWriteStream._resize.stop()
  }

  _continueWrite(err) {
    if (this._pendingWrite === null) return
    const cb = this._pendingWrite
    this._pendingWrite = null
    this._pendingWriteBatch = null
    cb(err)
  }

  _continueDestroy() {
    if (this._pendingDestroy === null) return
    const cb = this._pendingDestroy
    this._pendingDestroy = null
    cb(null)
  }

  _onwrite(err) {
    this._continueWrite(err)
  }

  _onclose() {
    this._handle = null

    this._continueDestroy()
  }

  _onresize() {
    this._size = this.getWindowSize()

    this.emit('resize')
  }

  static _streams = new Set()

  static _resize = new Signal('SIGWINCH')
}

exports.constants = constants

exports.isTTY = binding.isTTY

exports.isatty = exports.isTTY // For Node.js compatibility

exports.WriteStream._resize
  .on('signal', () => {
    for (const stream of exports.WriteStream._streams) {
      stream._onresize()
    }
  })
  .unref()

function noop() {}
const binding = require('../binding')

module.exports = exports = {
  mode: {
    NORMAL: binding.MODE_NORMAL,
    RAW: binding.MODE_RAW,
    IO: binding.MODE_IO || 0
  },

  state: {
    READING: 0x1,
    CLOSING: 0x2
  }
}

/** @deprecated Use `mode.NORMAL` */
exports.MODE_NORMAL = exports.mode.NORMAL
/** @deprecated Use `mode.RAW` */
exports.MODE_RAW = exports.mode.RAW
/** @deprecated Use `mode.IO` */
exports.MODE_IO = exports.mode.IO
{
  "name": "bare-tty",
  "version": "5.1.2",
  "description": "Native TTY streams for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./constants": "./lib/constants.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-tty.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-tty/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-tty#readme",
  "engines": {
    "bare": ">=1.16.0"
  },
  "dependencies": {
    "bare-events": "^2.2.0",
    "bare-signals": "^5.0.0",
    "bare-stream": "^2.0.0"
  },
  "devDependencies": {
    "brittle": "^3.2.1",
    "cmake-bare": "^1.1.6",
    "lunte": "^1.8.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = require.addon()
const binding = require('./binding')

const t = binding.constants

class Type {
  constructor(type) {
    this._type = type
  }

  isUndefined() {
    return this._type === t.UNDEFINED
  }

  isNull() {
    return this._type === t.NULL
  }

  isBoolean() {
    return this._type === t.BOOLEAN
  }

  isNumber() {
    return (this._type & 0xff) === t.NUMBER
  }

  isInt32() {
    return (this._type & (0xff | t.INT32)) === (t.NUMBER | t.INT32)
  }

  isUint32() {
    return (this._type & (0xff | t.UINT32)) === (t.NUMBER | t.UINT32)
  }

  isString() {
    return this._type === t.STRING
  }

  isSymbol() {
    return this._type === t.SYMBOL
  }

  isObject() {
    return (this._type & 0xff) === t.OBJECT
  }

  isArray() {
    return this._type === (t.OBJECT | t.ARRAY)
  }

  isArguments() {
    return this._type === (t.OBJECT | t.ARGUMENTS)
  }

  isDate() {
    return this._type === (t.OBJECT | t.DATE)
  }

  isRegExp() {
    return this._type === (t.OBJECT | t.REGEXP)
  }

  isError() {
    return this._type === (t.OBJECT | t.ERROR)
  }

  isPromise() {
    return this._type === (t.OBJECT | t.PROMISE)
  }

  isProxy() {
    return this._type === (t.OBJECT | t.PROXY)
  }

  isGenerator() {
    return this._type === (t.OBJECT | t.GENERATOR)
  }

  isMap() {
    return this._type === (t.OBJECT | t.MAP)
  }

  isSet() {
    return this._type === (t.OBJECT | t.SET)
  }

  isWeakMap() {
    return this._type === (t.OBJECT | t.WEAK_MAP)
  }

  isWeakSet() {
    return this._type === (t.OBJECT | t.WEAK_SET)
  }

  isWeakRef() {
    return this._type === (t.OBJECT | t.WEAK_REF)
  }

  isArrayBuffer() {
    return this._type === (t.OBJECT | t.ARRAYBUFFER)
  }

  isSharedArrayBuffer() {
    return this._type === (t.OBJECT | t.SHAREDARRAYBUFFER)
  }

  isTypedArray() {
    return (this._type & 0xffff) === (t.OBJECT | t.TYPEDARRAY)
  }

  isInt8Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT8ARRAY)
  }

  isUint8Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT8ARRAY)
  }

  isUint8ClampedArray() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT8CLAMPEDARRAY)
  }

  isInt16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT16ARRAY)
  }

  isUint16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT16ARRAY)
  }

  isInt32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT32ARRAY)
  }

  isUint32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT32ARRAY)
  }

  isFloat16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT16ARRAY)
  }

  isFloat32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT32ARRAY)
  }

  isFloat64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT64ARRAY)
  }

  isBigInt64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.BIGINT64ARRAY)
  }

  isBigUint64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.BIGUINT64ARRAY)
  }

  isDataView() {
    return this._type === (t.OBJECT | t.DATAVIEW)
  }

  isModuleNamespace() {
    return this._type === (t.OBJECT | t.MODULE_NAMESPACE)
  }

  isFunction() {
    return (this._type & 0xff) === t.FUNCTION
  }

  isAsyncFunction() {
    return (
      (this._type & (0xff | t.ASYNC_FUNCTION)) ===
      (t.FUNCTION | t.ASYNC_FUNCTION)
    )
  }

  isGeneratorFunction() {
    return (
      (this._type & (0xff | t.GENERATOR_FUNCTION)) ===
      (t.FUNCTION | t.GENERATOR_FUNCTION)
    )
  }

  isExternal() {
    return this._type === t.EXTERNAL
  }

  isBigInt() {
    return this._type === t.BIGINT
  }
}

module.exports = exports = function type(value) {
  switch (typeof value) {
    case 'undefined':
      return new Type(t.UNDEFINED)
    case 'boolean':
      return new Type(t.BOOLEAN)
    case 'number':
      return new Type(
        Number.isSafeInteger(value) ? binding.type(value) : t.NUMBER
      )
    case 'string':
      return new Type(t.STRING)
    case 'symbol':
      return new Type(t.SYMBOL)
    case 'object':
      return new Type(value === null ? t.NULL : binding.type(value))
    case 'function':
      return new Type(binding.type(value))
    case 'bigint':
      return new Type(t.BIGINT)
  }
}

exports.createTag = function createTag(...components) {
  const tag = new Uint32Array(4)
  for (let i = 0; i < 4; i++) tag[i] = components[i] || 0
  return tag
}

exports.addTag = function addTag(object, tag) {
  binding.addTag(object, tag)
}

exports.checkTag = function checkTag(object, tag) {
  return binding.checkTag(object, tag)
}
{
  "name": "bare-type",
  "version": "1.1.0",
  "description": "Cross-realm type predicates for Bare",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-type.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-type/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-type#readme",
  "engines": {
    "bare": ">=1.2.0"
  },
  "devDependencies": {
    "brittle": "^3.4.0",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
module.exports = require.addon()
const path = require('bare-path')
const binding = require('./binding')
const errors = require('./lib/errors')
const URLSearchParams = require('./lib/url-search-params')

const kind = Symbol.for('bare.url.kind')

const isWindows = Bare.platform === 'win32'

class URL {
  static get [kind]() {
    return 0 // Compatibility version
  }

  constructor(input, base, opts = {}) {
    if (arguments.length === 0) throw errors.INVALID_URL()

    input = String(input)

    if (base !== undefined) base = String(base)

    this._components = new Uint32Array(8)

    this._parse(input, base, opts.throw !== false)

    if (this._href) this._params = new URLSearchParams(this.search, this)
  }

  get [kind]() {
    return URL[kind]
  }

  // https://url.spec.whatwg.org/#dom-url-href

  get href() {
    return this._href
  }

  set href(value) {
    this._update(value)

    this._params._parse(this.search)
  }

  // https://url.spec.whatwg.org/#dom-url-protocol

  get protocol() {
    return this._slice(0, this._components[0]) + ':'
  }

  set protocol(value) {
    this._update(this._replace(value.replace(/:+$/, ''), 0, this._components[0]))
  }

  // https://url.spec.whatwg.org/#dom-url-username

  get username() {
    return this._slice(this._components[0] + 3 /* :// */, this._components[1])
  }

  set username(value) {
    if (cannotHaveCredentialsOrPort(this)) {
      return
    }

    if (this.username === '') value += '@'

    this._update(this._replace(value, this._components[0] + 3 /* :// */, this._components[1]))
  }

  // https://url.spec.whatwg.org/#dom-url-password

  get password() {
    return this._href.slice(this._components[1] + 1 /* : */, this._components[2] - 1 /* @ */)
  }

  set password(value) {
    if (cannotHaveCredentialsOrPort(this)) {
      return
    }

    let start = this._components[1] + 1 /* : */
    let end = this._components[2] - 1 /* @ */

    if (this.password === '') {
      value = ':' + value
      start--
    }

    if (this.username === '') {
      value += '@'
      end++
    }

    this._update(this._replace(value, start, end))
  }

  // https://url.spec.whatwg.org/#dom-url-host

  get host() {
    return this._slice(this._components[2], this._components[5])
  }

  set host(value) {
    if (hasOpaquePath(this)) {
      return
    }

    this._update(
      this._replace(value, this._components[2], this._components[value.includes(':') ? 5 : 3])
    )
  }

  // https://url.spec.whatwg.org/#dom-url-hostname

  get hostname() {
    return this._slice(this._components[2], this._components[3])
  }

  set hostname(value) {
    if (hasOpaquePath(this)) {
      return
    }

    this._update(this._replace(value, this._components[2], this._components[3]))
  }

  // https://url.spec.whatwg.org/#dom-url-port

  get port() {
    return this._slice(this._components[3] + 1 /* : */, this._components[5])
  }

  set port(value) {
    if (cannotHaveCredentialsOrPort(this)) {
      return
    }

    let start = this._components[3] + 1 /* : */

    if (this.port === '') {
      value = ':' + value
      start--
    }

    this._update(this._replace(value, start, this._components[5]))
  }

  // https://url.spec.whatwg.org/#dom-url-pathname

  get pathname() {
    return this._slice(this._components[5], this._components[6] - 1 /* ? */)
  }

  set pathname(value) {
    if (hasOpaquePath(this)) {
      return
    }

    if (value[0] !== '/' && value[0] !== '\\') {
      value = '/' + value
    }

    this._update(this._replace(value, this._components[5], this._components[6] - 1 /* ? */))
  }

  // https://url.spec.whatwg.org/#dom-url-search

  get search() {
    return this._slice(this._components[6] - 1 /* ? */, this._components[7] - 1 /* # */)
  }

  set search(value) {
    if (value && value[0] !== '?') value = '?' + value

    this._update(
      this._replace(value, this._components[6] - 1 /* ? */, this._components[7] - 1 /* # */)
    )

    this._params._parse(this.search)
  }

  // https://url.spec.whatwg.org/#dom-url-searchparams

  get searchParams() {
    return this._params
  }

  // https://url.spec.whatwg.org/#dom-url-hash

  get hash() {
    return this._slice(this._components[7] - 1 /* # */)
  }

  set hash(value) {
    if (value && value[0] !== '#') value = '#' + value

    this._update(this._replace(value, this._components[7] - 1 /* # */))
  }

  toString() {
    return this._href
  }

  toJSON() {
    return this._href
  }

  [Symbol.for('bare.inspect')]() {
    return {
      __proto__: { constructor: URL },

      href: this.href,
      protocol: this.protocol,
      username: this.username,
      password: this.password,
      host: this.host,
      hostname: this.hostname,
      port: this.port,
      pathname: this.pathname,
      search: this.search,
      searchParams: this.searchParams,
      hash: this.hash
    }
  }

  _slice(start, end = this._href.length) {
    return this._href.slice(start, end)
  }

  _replace(replacement, start, end = this._href.length) {
    return this._slice(0, start) + replacement + this._slice(end)
  }

  _parse(input, base, shouldThrow) {
    try {
      this._href = binding.parse(
        String(input),
        base ? String(base) : null,
        this._components,
        shouldThrow
      )
    } catch (err) {
      if (err instanceof TypeError) throw err

      throw errors.INVALID_URL(`Invalid URL '${input}'`, input)
    }
  }

  _update(input) {
    try {
      this._parse(input, null, true)
    } catch (err) {
      if (err instanceof TypeError) throw err
    }
  }
}

module.exports = exports = URL

// https://url.spec.whatwg.org/#url-opaque-path
function hasOpaquePath(url) {
  return url.pathname[0] !== '/'
}

// https://url.spec.whatwg.org/#cannot-have-a-username-password-port
function cannotHaveCredentialsOrPort(url) {
  return url.hostname === '' || url.protocol === 'file:'
}

exports.URL = URL
exports.URLSearchParams = URLSearchParams

exports.errors = errors

exports.isURL = function isURL(value) {
  if (value instanceof URL) return true

  return typeof value === 'object' && value !== null && value[kind] === URL[kind]
}

exports.isURLSearchParams = URLSearchParams.isURLSearchParams

// https://url.spec.whatwg.org/#dom-url-parse
exports.parse = function parse(input, base) {
  const url = new URL(input, base, { throw: false })
  return url._href ? url : null
}

// https://url.spec.whatwg.org/#dom-url-canparse
exports.canParse = function canParse(input, base) {
  return binding.canParse(String(input), base ? String(base) : null)
}

exports.fileURLToPath = function fileURLToPath(url) {
  if (typeof url === 'string') {
    url = new URL(url)
  }

  if (url.protocol !== 'file:') {
    throw errors.INVALID_URL_SCHEME('The URL must use the file: protocol')
  }

  if (isWindows) {
    if (/%2f|%5c/i.test(url.pathname)) {
      throw errors.INVALID_FILE_URL_PATH(
        'The file: URL path must not include encoded \\ or / characters'
      )
    }
  } else {
    if (url.hostname) {
      throw errors.INVALID_FILE_URL_HOST("The file: URL host must be 'localhost' or empty")
    }

    if (/%2f/i.test(url.pathname)) {
      throw errors.INVALID_FILE_URL_PATH('The file: URL path must not include encoded / characters')
    }
  }

  if (/%00/i.test(url.pathname)) {
    throw errors.INVALID_FILE_URL_PATH('The file: URL path must not include encoded NUL characters')
  }

  const pathname = path.normalize(decodeURIComponent(url.pathname))

  if (isWindows) {
    if (url.hostname) return '\\\\' + url.hostname + pathname

    const letter = pathname.charCodeAt(1) | 0x20

    if (letter < 0x61 /* a */ || letter > 0x7a /* z */ || pathname.charCodeAt(2) !== 0x3a /* : */) {
      throw errors.INVALID_FILE_URL_PATH('The file: URL path must be absolute')
    }

    return pathname.slice(1)
  }

  return pathname
}

exports.pathToFileURL = function pathToFileURL(pathname) {
  let resolved = path.resolve(pathname)

  if (pathname[pathname.length - 1] === '/') {
    resolved += '/'
  } else if (isWindows && pathname[pathname.length - 1] === '\\') {
    resolved += '\\'
  }

  resolved = resolved
    .replaceAll('%', '%25') // Must be first
    .replaceAll('#', '%23')
    .replaceAll('?', '%3f')
    .replaceAll('\n', '%0a')
    .replaceAll('\r', '%0d')
    .replaceAll('\t', '%09')

  if (!isWindows) {
    resolved = resolved.replaceAll('\\', '%5c')
  }

  return new URL('file:' + resolved)
}

exports.format = function format(parts) {
  const { protocol, auth, host, hostname, port, pathname, search, query, hash, slashes } = parts

  let result = ''

  if (typeof protocol === 'string') {
    result += protocol

    if (protocol[protocol.length - 1] !== ':') {
      result += ':'
    }

    if (slashes === true || /https?|ftp|gopher|file/.test(protocol)) {
      result += '//'
    }
  }

  if (typeof auth === 'string') {
    if (host || hostname) result += auth + '@'
  }

  if (typeof host === 'string') result += host
  else {
    result += hostname

    if (port) result += ':' + port
  }

  if (typeof pathname === 'string' && pathname !== '') {
    if (pathname[0] !== '/') result += '/'
    result += pathname
  }

  if (typeof search === 'string') {
    if (search[0] !== '?') result += '?'
    result += search
  } else if (typeof query === 'object' && query !== null) {
    result += '?' + new URLSearchParams(query)
  }

  if (typeof hash === 'string') {
    if (hash[0] !== '#') result += '#'
    result += hash
  }

  return result
}
module.exports = class URLError extends Error {
  constructor(msg, fn = URLError, code = fn.name) {
    super(`${code}: ${msg}`)

    this.code = code

    if (Error.captureStackTrace) Error.captureStackTrace(this, fn)
  }

  get name() {
    return 'URLError'
  }

  static INVALID_URL(msg, input) {
    const err = new URLError(msg, URLError.INVALID_URL)

    err.input = input

    return err
  }

  static INVALID_URL_SCHEME(msg = 'Invalid URL') {
    return new URLError(msg, URLError.INVALID_URL_SCHEME)
  }

  static INVALID_FILE_URL_HOST(msg = 'Invalid file: URL host') {
    return new URLError(msg, URLError.INVALID_FILE_URL_HOST)
  }

  static INVALID_FILE_URL_PATH(msg = 'Invalid file: URL path') {
    return new URLError(msg, URLError.INVALID_FILE_URL_PATH)
  }
}
const kind = Symbol.for('bare.url.search-params.kind')

class URLSearchParams {
  static _urls = new WeakMap()

  static get [kind]() {
    return 0 // Compatibility version
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-urlsearchparams
  constructor(init, url = null) {
    this._params = new Map()

    if (url) URLSearchParams._urls.set(this, url)

    if (typeof init === 'string') {
      this._parse(init)
    } else if (init) {
      for (const [name, value] of typeof init[Symbol.iterator] === 'function'
        ? init
        : Object.entries(init)) {
        this.append(name, value)
      }
    }
  }

  get [kind]() {
    return URLSearchParams[kind]
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-size
  get size() {
    return this._params.length
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-append
  append(name, value = null) {
    if (value === null) return

    let list = this._params.get(name)

    if (list === undefined) {
      list = []
      this._params.set(name, list)
    }

    list.push(value)

    this._update()
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-delete
  delete(name, value = null) {
    if (value === null) this._params.delete(name)
    else {
      let list = this._params.get(name)

      if (list === undefined) return

      list = list.filter((found) => found !== value)

      if (list.length === 0) this._params.delete(name)
      else this._params.set(name, list)
    }

    this._update()
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-get
  get(name) {
    const list = this._params.get(name)

    if (list === undefined) return null

    return list[0]
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-getall
  getAll(name) {
    const list = this._params.get(name)

    if (list === undefined) return []

    return Array.from(list)
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-has
  has(name, value = null) {
    const list = this._params.get(name)

    if (list === undefined) return false

    if (value === null) return true

    return list.includes(value)
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-set
  set(name, value = null) {
    if (value === null) this._params.delete(name)
    else this._params.set(name, [value])

    this._update()
  }

  toString() {
    return this._serialize()
  }

  toJSON() {
    return [...this]
  }

  *[Symbol.iterator]() {
    for (const [name, values] of this._params) {
      for (const value of values) yield [name, value]
    }
  }

  [Symbol.for('bare.inspect')]() {
    const object = {
      __proto__: { constructor: URLSearchParams }
    }

    for (const [name, values] of this._params) {
      if (values.length === 1) object[name] = values[0]
      else object[name] = values
    }

    return object
  }

  // https://url.spec.whatwg.org/#concept-urlsearchparams-update
  _update() {
    const url = URLSearchParams._urls.get(this)

    if (url === undefined) return

    url.search = this._serialize()
  }

  // https://url.spec.whatwg.org/#concept-urlencoded-parser
  _parse(input) {
    if (input[0] === '?') input = input.substring(1)

    this._params = new Map()

    for (let sequence of input.split('&')) {
      if (sequence.length === 0) continue

      sequence = sequence.replace(/\+/g, ' ')

      let i = sequence.indexOf('=')
      if (i === -1) i = sequence.length

      const name = decodeURIComponent(sequence.substring(0, i))
      const value = decodeURIComponent(sequence.substring(i + 1, sequence.length))

      let list = this._params.get(name)

      if (list === undefined) {
        list = []
        this._params.set(name, list)
      }

      list.push(value)
    }
  }

  // https://url.spec.whatwg.org/#concept-urlencoded-serializer
  _serialize() {
    let output = ''

    for (let [name, values] of this._params) {
      name = encodeURIComponent(name)

      for (const value of values) {
        if (output) output += '&'

        output += name + '=' + encodeURIComponent(value)
      }
    }

    return output
  }
}

module.exports = exports = URLSearchParams

exports.isURLSearchParams = function isURLSearchParams(value) {
  if (value instanceof URLSearchParams) return true

  return typeof value === 'object' && value !== null && value[kind] === URLSearchParams[kind]
}
{
  "name": "bare-url",
  "version": "2.4.5",
  "description": "WHATWG URL implementation for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "global.js",
    "global.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-url.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-url/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-url",
  "dependencies": {
    "bare-path": "^3.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "cmake-bare": "^1.1.6",
    "cmake-fetch": "^1.0.0",
    "lunte": "^1.6.0",
    "prettier": "^3.3.3",
    "prettier-config-holepunch": "^2.0.0"
  }
}
exports.Server = require('./lib/server')
exports.Socket = require('./lib/socket')
exports.EOL = '\r\n'
exports.EOF = exports.EOL.repeat(2)

exports.GUID = Buffer.from('258EAFA5-E914-47DA-95CA-C5AB0DC85B11')

// https://datatracker.ietf.org/doc/html/rfc6455#section-11.8
exports.opcode = {
  CONTINUATION: 0x0,
  TEXT: 0x1,
  BINARY: 0x2,
  CLOSE: 0x8,
  PING: 0x9,
  PONG: 0xa
}

// https://datatracker.ietf.org/doc/html/rfc6455#section-7.4.1
exports.status = {
  PROTOCOL_ERROR: 1002,
  MESSAGE_TOO_LARGE: 1009
}
const { status } = require('./constants')

module.exports = class WebSocketError extends Error {
  constructor(msg, code, status, fn = WebSocketError, cause) {
    super(`${code}: ${msg}`, { cause })
    this.code = code
    this.status = status

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'WebSocketError'
  }

  static NETWORK_ERROR(msg, cause) {
    return new WebSocketError(msg, 'NETWORK_ERROR', 0, WebSocketError.NETWORK_ERROR, cause)
  }

  static NOT_CONNECTED(msg = 'Socket is not connected') {
    return new WebSocketError(msg, 'NOT_CONNECTED', 0, WebSocketError.NOT_CONNECTED)
  }

  static UNEXPECTED_RSV1(msg = 'RSV1 must be unset') {
    return new WebSocketError(
      msg,
      'UNEXPECTED_RSV1',
      status.PROTOCOL_ERROR,
      WebSocketError.UNEXPECTED_RSV1
    )
  }

  static UNEXPECTED_RSV2(msg = 'RSV2 must be unset') {
    return new WebSocketError(
      msg,
      'UNEXPECTED_RSV2',
      status.PROTOCOL_ERROR,
      WebSocketError.UNEXPECTED_RSV2
    )
  }

  static UNEXPECTED_RSV3(msg = 'RSV3 must be unset') {
    return new WebSocketError(
      msg,
      'UNEXPECTED_RSV3',
      status.PROTOCOL_ERROR,
      WebSocketError.UNEXPECTED_RSV3
    )
  }

  static EXPECTED_MASK(msg = 'MASK must be set') {
    return new WebSocketError(
      msg,
      'EXPECTED_MASK',
      status.PROTOCOL_ERROR,
      WebSocketError.EXPECTED_MASK
    )
  }

  static UNEXPECTED_MASK(msg = 'MASK must be unset') {
    return new WebSocketError(
      msg,
      'UNEXPECTED_MASK',
      status.PROTOCOL_ERROR,
      WebSocketError.UNEXPECTED_MASK
    )
  }

  static EXPECTED_CONTINUATION(msg = 'Expected a continuation frame') {
    return new WebSocketError(
      msg,
      'EXPECTED_CONTINUATION',
      status.PROTOCOL_ERROR,
      WebSocketError.EXPECTED_CONTINUATION
    )
  }

  static UNEXPECTED_CONTINUATION(msg = 'Unexpected continuation frame') {
    return new WebSocketError(
      msg,
      'UNEXPECTED_CONTINUATION',
      status.PROTOCOL_ERROR,
      WebSocketError.UNEXPECTED_CONTINUATION
    )
  }

  static UNEXPECTED_CONTROL(msg = 'Unexpected control frame') {
    return new WebSocketError(
      msg,
      'UNEXPECTED_CONTROL',
      status.PROTOCOL_ERROR,
      WebSocketError.UNEXPECTED_CONTROL
    )
  }

  static INVALID_ENCODING(msg = 'Invalid encoding') {
    return new WebSocketError(
      msg,
      'INVALID_ENCODING',
      status.PROTOCOL_ERROR,
      WebSocketError.INVALID_ENCODING
    )
  }

  static INVALID_UPGRADE_HEADER(msg = 'Invalid Upgrade header') {
    return new WebSocketError(
      msg,
      'INVALID_UPGRADE_HEADER',
      status.PROTOCOL_ERROR,
      WebSocketError.INVALID_UPGRADE_HEADER
    )
  }

  static INVALID_VERSION_HEADER(msg = 'Invalid Sec-WebSocket-Version header') {
    return new WebSocketError(
      msg,
      'INVALID_VERSION_HEADER',
      status.PROTOCOL_ERROR,
      WebSocketError.INVALID_VERSION_HEADER
    )
  }

  static INVALID_KEY_HEADER(msg = 'Invalid Sec-WebSocket-Key header') {
    return new WebSocketError(
      msg,
      'INVALID_KEY_HEADER',
      status.PROTOCOL_ERROR,
      WebSocketError.INVALID_KEY_HEADER
    )
  }

  static INVALID_ACCEPT_HEADER(msg = 'Invalid Sec-WebSocket-Accept header') {
    return new WebSocketError(
      msg,
      'INVALID_ACCEPT_HEADER',
      status.PROTOCOL_ERROR,
      WebSocketError.INVALID_ACCEPT_HEADER
    )
  }

  static INVALID_OPCODE(msg = 'Invalid opcode') {
    return new WebSocketError(
      msg,
      'INVALID_OPCODE',
      status.PROTOCOL_ERROR,
      WebSocketError.INVALID_OPCODE
    )
  }

  static INVALID_PAYLOAD_LENGTH(msg = 'Invalid payload length') {
    return new WebSocketError(
      msg,
      'INVALID_PAYLOAD_LENGTH',
      status.MESSAGE_TOO_LARGE,
      WebSocketError.INVALID_PAYLOAD_LENGTH
    )
  }

  static INCOMPLETE_FRAME(msg = 'Incomplete frame', length = -1) {
    return new WebSocketError(msg, 'INCOMPLETE_FRAME', length, WebSocketError.INCOMPLETE_FRAME)
  }
}
const crypto = require('bare-crypto')
const errors = require('./errors')

const EMPTY = Buffer.alloc(0)

const FIN = 0b10000000
const RSV1 = 0b01000000
const RSV2 = 0b00100000
const RSV3 = 0b00010000
const OPCODE = 0b00001111
const MASK = 0b10000000
const LENGTH = 0b01111111

// https://datatracker.ietf.org/doc/html/rfc6455#section-5
module.exports = exports = class Frame {
  constructor(opcode, payload = EMPTY, opts = {}) {
    if (payload && !Buffer.isBuffer(payload)) {
      opts = payload
      payload = EMPTY
    }

    const { fin = true, rsv1 = false, rsv2 = false, rsv3 = false, mask = null } = opts

    this.fin = fin
    this.rsv1 = rsv1
    this.rsv2 = rsv2
    this.rsv3 = rsv3
    this.opcode = opcode
    this.mask = mask
    this.payload = payload
  }

  toBuffer() {
    const state = { start: 0, end: 0, buffer: null }

    Frame.preencode(state, this)

    state.buffer = Buffer.allocUnsafe(state.end)

    Frame.encode(state, this)

    return state.buffer
  }
}

const Frame = exports

exports.preencode = function preencode(state, f) {
  let i = state.end

  i++

  const length = f.payload.length

  if (length <= 0x7d) i++
  else {
    if (length <= 0xffff) i += 3
    else i += 9
  }

  if (f.mask) i += 4

  i += length

  state.end = i
}

exports.encode = function encode(state, f) {
  const b = state.buffer

  let i = state.start

  const v = new DataView(b.buffer, b.byteOffset, b.byteLength)

  b[i] = f.opcode & OPCODE

  if (f.fin) b[i] |= FIN
  if (f.rsv1) b[i] |= RSV1
  if (f.rsv1) b[i] |= RSV2
  if (f.rsv1) b[i] |= RSV3

  i++

  b[i] = f.mask ? MASK : 0

  const length = f.payload.length

  if (length <= 0x7d) b[i++] |= length
  else {
    if (length <= 0xffff) {
      b[i++] |= 0x7e

      v.setUint16(i, length, false)

      i += 2
    } else {
      b[i++] |= 0x7f

      const high = Math.floor(length / 0x100000000)

      v.setUint32(i, high, false)

      i += 4

      const low = length & 0xffffffff

      v.setUint32(i, low, false)

      i += 4
    }
  }

  if (f.mask) {
    crypto.randomFill(f.mask, 0, 4)

    b.set(f.mask, i)

    i += 4

    for (let j = 0; j < length; j++) {
      b[i + j] = f.payload[j] ^ f.mask[j & 3]
    }
  } else {
    b.set(f.payload, i)
  }

  i += length

  state.start = i
}

exports.decode = function decode(state) {
  const s = state.start
  const b = state.buffer

  let i = s
  let n = b.byteLength

  if (n < 2) throw errors.INCOMPLETE_FRAME()

  const view = new DataView(b.buffer, b.byteOffset, b.byteLength)

  const fin = !!(b[i] & FIN)

  const rsv1 = !!(b[i] & RSV1)
  const rsv2 = !!(b[i] & RSV2)
  const rsv3 = !!(b[i] & RSV3)

  const opcode = b[i] & OPCODE

  i++
  n--

  const masked = !!(b[i] & MASK)

  let length = b[i] & LENGTH

  i++
  n--

  if (length === 0x7e) {
    if (n < 2) throw errors.INCOMPLETE_FRAME()

    length = view.getUint16(i, false)

    i += 2
    n -= 2
  } else if (length === 0x7f) {
    if (n < 8) throw errors.INCOMPLETE_FRAME()

    const high = view.getUint32(i, false)

    if (high >= 0x200000) throw errors.INVALID_PAYLOAD_LENGTH()

    i += 4
    n -= 4

    const low = view.getUint32(i, false)

    i += 4
    n -= 4

    length = high * 0x100000000 + low
  }

  let mask = null

  if (masked) {
    if (n < 4) throw errors.INCOMPLETE_FRAME()

    mask = b.subarray(i, i + 4)

    i += 4
    n -= 4
  }

  if (n < length) {
    throw errors.INCOMPLETE_FRAME('Incomplete frame', i - s + length)
  }

  const payload = b.subarray(i, i + length)

  i += length
  n -= length

  if (mask) {
    for (let i = 0; i < length; i++) {
      payload[i] ^= mask[i & 3]
    }
  }

  state.start = i

  return new Frame(opcode, payload, { fin, rsv1, rsv2, rsv3, mask })
}
const EventEmitter = require('bare-events')
const http = require('bare-http1')
const https = require('bare-https')
const crypto = require('bare-crypto')
const { GUID, EOL, EOF } = require('./constants')
const errors = require('./errors')
const WebSocket = require('./socket')

const EMPTY = Buffer.alloc(0)

const KEY = /^[+/0-9A-Za-z]{22}==$/

module.exports = exports = class WebSocketServer extends EventEmitter {
  constructor(opts = {}, onconnection) {
    if (typeof opts === 'function') {
      onconnection = opts
      opts = {}
    }

    super()

    const createServer = opts.secure ? https.createServer : http.createServer

    const {
      server = createServer(opts, this._onrequest.bind(this)).listen(
        opts,
        this._onlistening.bind(this)
      )
    } = opts

    this._server = server

    this._server.on('upgrade', this._onupgrade.bind(this))

    if (onconnection) this.on('connection', onconnection)
  }

  get listening() {
    return this._server.listening
  }

  address() {
    return this._server.address()
  }

  close(cb) {
    this._server.close(cb)

    return this
  }

  ref() {
    this._server.ref()

    return this
  }

  unref() {
    this._server.unref()

    return this
  }

  _onlistening() {
    this.emit('listening')
  }

  _onrequest(req, res) {
    const body = http.constants.status[426]

    res.writeHead(426, {
      'Content-Type': 'text/plain',
      'Content-Length': body.length
    })

    res.end(body)
  }

  _onupgrade(req, socket, head) {
    exports.handshake(req, socket, head, (err) => {
      if (err) return socket.destroy(err)

      this.emit('connection', new WebSocket({ socket, isServer: true }), req)
    })
  }
}

// https://datatracker.ietf.org/doc/html/rfc6455#section-4.2
exports.handshake = function handshake(req, socket = req.socket, head = EMPTY, cb) {
  if (typeof socket === 'function') {
    cb = socket
    socket = req.socket
    head = EMPTY
  } else if (typeof head === 'function') {
    cb = head
    head = EMPTY
  }

  if (req.headers.upgrade.toLowerCase() !== 'websocket') {
    return cb(errors.INVALID_UPGRADE_HEADER())
  }

  const version = +req.headers['sec-websocket-version']

  if (version !== 8 && version !== 13) {
    return cb(errors.INVALID_VERSION_HEADER())
  }

  const key = req.headers['sec-websocket-key']

  if (!key || !KEY.test(key)) {
    return cb(errors.INVALID_KEY_HEADER())
  }

  const digest = crypto.createHash('sha1').update(key).update(GUID).digest('base64')

  socket.write(
    'HTTP/1.1 101 Web Socket Protocol Handshake' +
      EOL +
      'Upgrade: WebSocket' +
      EOL +
      'Connection: Upgrade' +
      EOL +
      `Sec-WebSocket-Accept: ${digest}` +
      EOF
  )

  if (head.byteLength) socket.unshift(head)

  cb(null)
}
const { Duplex } = require('bare-stream')
const http = require('bare-http1')
const https = require('bare-https')
const crypto = require('bare-crypto')
const { GUID, opcode } = require('./constants')
const errors = require('./errors')
const Frame = require('./frame')

const CLOSE = new Frame(opcode.CLOSE).toBuffer()

module.exports = exports = class WebSocket extends Duplex {
  constructor(url, opts = {}) {
    if (typeof url === 'string') url = new URL(url)

    if (isURL(url)) {
      opts = opts ? { ...opts } : {}

      opts.host = url.hostname
      opts.path = url.pathname + url.search
      opts.port = url.port ? parseInt(url.port, 10) : defaultPort(url)
      opts.secure = url.protocol === 'https:' || url.protocol === 'wss:'
    } else {
      opts = url ? { ...url } : {}

      // For Node.js compatibility
      opts.host = opts.hostname || opts.host
      opts.port = typeof opts.port === 'string' ? parseInt(opts.port, 10) : opts.port
    }

    const { isServer = false, socket = null } = opts

    super({ eagerOpen: true })

    this._socket = null
    this._isServer = isServer
    this._mask = isServer ? null : Buffer.allocUnsafe(4)
    this._fragments = []

    this._pendingOpen = null
    this._pendingWrite = null

    this._buffer = []
    this._buffered = 0
    this._frame = -1

    if (socket !== null) this._attach(socket)
    else this._connect(opts)
  }

  ping(data) {
    if (this._socket === null) throw errors.NOT_CONNECTED()

    if (typeof data === 'string') data = Buffer.from(data)

    this._socket.write(new Frame(opcode.PING, data, { mask: this._mask }).toBuffer())
  }

  pong(data) {
    if (this._socket === null) throw errors.NOT_CONNECTED()

    if (typeof data === 'string') data = Buffer.from(data)

    this._socket.write(new Frame(opcode.PONG, data, { mask: this._mask }).toBuffer())
  }

  _attach(socket) {
    this._socket = socket

    this._socket
      .on('error', this._onerror.bind(this))
      .on('close', this._onclose.bind(this))
      .on('data', this._ondata.bind(this))
      .on('drain', this._ondrain.bind(this))
  }

  _connect(opts) {
    const request = opts.secure ? https.request : http.request

    const req = request(opts)

    exports.handshake(req, (err) => {
      const cb = this._pendingOpen
      this._pendingOpen = null

      if (err) req.socket.destroy()
      else this._attach(req.socket)

      cb(err)
    })
  }

  _onerror(err) {
    this.destroy(err)
  }

  _onclose() {
    this.destroy()
  }

  _ondata(data) {
    this._buffer.push(data)
    this._buffered += data.byteLength

    while (this._frame === -1 || this._frame <= this._buffered) {
      const buffer = this._buffer.length === 1 ? this._buffer[0] : Buffer.concat(this._buffer)

      this._buffer = [buffer]

      const state = { start: 0, end: buffer.length, buffer }

      try {
        this._onframe(Frame.decode(state))
      } catch (err) {
        if (err.code === 'INCOMPLETE_FRAME') this._frame = err.status
        else this.destroy(err)
        return
      }

      this._buffered -= state.start
      this._buffer = this._buffered > 0 ? [buffer.subarray(state.start)] : []
      this._frame = -1
    }
  }

  _onframe(frame) {
    if (frame.rsv1) throw errors.UNEXPECTED_RSV1()

    if (frame.rsv2) throw errors.UNEXPECTED_RSV2()

    if (frame.rsv3) throw errors.UNEXPECTED_RSV3()

    if (frame.payload.length > 0 && !frame.mask === this._isServer) {
      throw this._isServer ? errors.EXPECTED_MASK() : errors.UNEXPECTED_MASK()
    }

    if (frame.fin === false) {
      if (this._fragments.push(frame) === 1) {
        // First frame
        if (frame.opcode === opcode.CONTINUATION) {
          throw errors.UNEXPECTED_CONTINUATION()
        }

        if (frame.opcode >= opcode.CLOSE) {
          throw errors.UNEXPECTED_CONTROL()
        }

        return
      }

      if (frame.opcode !== opcode.CONTINUATION) {
        throw errors.EXPECTED_CONTINUATION()
      }

      return
    }

    switch (frame.opcode) {
      case opcode.CLOSE:
        this.push(null)
        this.end()
        return

      case opcode.PING:
        this.pong(frame.payload)
        this.emit('ping', frame.payload)
        return

      case opcode.PONG:
        this.emit('pong', frame.payload)
        return

      case opcode.CONTINUATION: {
        if (this._fragments.length === 0) throw errors.UNEXPECTED_CONTINUATION()

        frame.opcode = this._fragments[0].opcode

        const payloads = this._fragments.map((frame) => frame.payload)

        payloads.push(frame.payload)

        frame.payload = Buffer.concat(payloads)

        this._fragments = []

        break
      }

      default:
        if (this._fragments.length > 0) throw errors.EXPECTED_CONTINUATION()
    }

    switch (frame.opcode) {
      case opcode.TEXT:
      case opcode.BINARY:
        this.push(frame.payload)
        break

      default:
        throw errors.INVALID_OPCODE()
    }
  }

  _ondrain() {
    if (this._pendingWrite === null) return
    const cb = this._pendingWrite
    this._pendingWrite = null
    cb(null)
  }

  _open(cb) {
    if (this._socket === null) this._pendingOpen = cb
    else cb(null)
  }

  _write(data, encoding, cb) {
    if (encoding !== 'buffer' && encoding !== 'utf8') {
      return cb(errors.INVALID_ENCODING())
    }

    const frame = new Frame(encoding === 'buffer' ? opcode.BINARY : opcode.TEXT, data, {
      mask: this._mask
    })

    if (this._socket.write(frame.toBuffer())) cb(null)
    else this._pendingWrite = cb
  }

  _final(cb) {
    this._socket.end(CLOSE)
    cb(null)
  }

  _predestroy() {
    if (!this._socket) return
    this._socket.destroy()
  }
}

// https://datatracker.ietf.org/doc/html/rfc6455#section-4.1
exports.handshake = function handshake(req, cb) {
  const key = crypto.randomBytes(16).toString('base64')

  req.headers = {
    ...req.headers,
    Connection: 'Upgrade',
    Upgrade: 'websocket',
    'Sec-WebSocket-Version': 13,
    'Sec-WebSocket-Key': key
  }

  req.on('upgrade', (res, socket, head) => {
    if (res.headers.upgrade.toLowerCase() !== 'websocket') {
      return cb(errors.INVALID_UPGRADE_HEADER())
    }

    const digest = crypto.createHash('sha1').update(key).update(GUID).digest('base64')

    if (res.headers['sec-websocket-accept'] !== digest) {
      return cb(errors.INVALID_ACCEPT_HEADER())
    }

    if (head.byteLength) socket.unshift(head)

    cb(null)
  })

  req.on('error', (err) => {
    cb(errors.NETWORK_ERROR('Network error', err))
  })

  req.end()
}

// https://url.spec.whatwg.org/#default-port
function defaultPort(url) {
  switch (url.protocol) {
    case 'ftp:':
      return 21
    case 'http:':
    case 'ws:':
      return 80
    case 'https:':
    case 'wss:':
      return 443
  }

  return null
}

// https://url.spec.whatwg.org/#api
function isURL(url) {
  return (
    url !== null &&
    typeof url === 'object' &&
    typeof url.protocol === 'string' &&
    typeof url.hostname === 'string' &&
    typeof url.pathname === 'string' &&
    typeof url.search === 'string'
  )
}
{
  "name": "bare-ws",
  "version": "3.0.0",
  "description": "WebSocket library for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    },
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    },
    "./errors": {
      "types": "./lib/errors.d.ts",
      "default": "./lib/errors.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "global.js",
    "global.d.ts",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-ws.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-ws/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-ws#readme",
  "dependencies": {
    "bare-crypto": "^1.2.0",
    "bare-events": "^2.3.1",
    "bare-http1": "^4.0.0",
    "bare-https": "^3.0.0",
    "bare-stream": "^2.1.2"
  },
  "devDependencies": {
    "bare-buffer": "^3.0.2",
    "bare-fs": "^4.0.0",
    "bare-url": "^2.1.3",
    "brittle": "^3.3.0",
    "lunte": "^1.7.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "bare-buffer": "*",
    "bare-url": "*"
  },
  "peerDependenciesMeta": {
    "bare-buffer": {
      "optional": true
    },
    "bare-url": {
      "optional": true
    }
  }
}
module.exports = require.addon()
const { Transform, Writable } = require('bare-stream')
const binding = require('./binding')
const constants = require('./lib/constants')
const errors = require('./lib/errors')

exports.constants = constants
exports.errors = errors

const MAX_OUTPUT_LENGTH = (Buffer.constants && Buffer.constants.MAX_LENGTH) || 0x100000000

class ZlibState {
  constructor(mode, opts = {}) {
    const {
      flush = constants.Z_NO_FLUSH,
      finishFlush = constants.Z_FINISH,
      chunkSize = constants.Z_DEFAULT_CHUNK,
      level = constants.Z_DEFAULT_LEVEL,
      windowBits = constants.Z_DEFAULT_WINDOWBITS,
      memLevel = constants.Z_DEFAULT_MEMLEVEL,
      strategy = constants.Z_DEFAULT_STRATEGY,
      maxOutputLength = MAX_OUTPUT_LENGTH
    } = opts

    this._mode = mode

    this._flushMode = flush
    this._finishFlushMode = finishFlush
    this._allocations = []

    this._maxOutputLength = maxOutputLength
    this._outputLength = 0

    this._buffer = Buffer.allocUnsafe(chunkSize)

    this._handle = binding.init(
      this._mode,
      this._buffer,
      level,
      windowBits,
      memLevel,
      strategy,
      this,
      this._onalloc,
      this._onfree
    )
  }

  _onalloc(size) {
    const buffer = Buffer.allocUnsafe(size)

    const view = new Uint32Array(buffer.buffer, buffer.byteOffset, buffer.byteLength / 4)

    view[0] = this._allocations.push(view) - 1

    return buffer
  }

  _onfree(id) {
    const last = this._allocations.pop()

    if (last[0] !== id) {
      this._allocations[(last[0] = id)] = last
    }
  }

  reset() {
    this._outputLength = 0

    binding.reset(this._handle)
  }

  *transform(data) {
    binding.load(this._handle, data)

    let available
    do {
      try {
        available = binding.transform(this._handle, this._flushMode)
      } catch (err) {
        throw errors[err.code](err.message)
      }

      const read = this._buffer.length - available

      if (read) {
        this._outputLength += read

        if (this._outputLength > this._maxOutputLength) {
          throw errors.LIMIT_EXCEEDED(
            `Output length exceeded maxOutputLength of ${this._maxOutputLength} bytes`
          )
        }

        const copy = Buffer.allocUnsafe(read)
        copy.set(this._buffer.subarray(0, read))

        yield copy
      }
    } while (available === 0)
  }

  *flush() {
    let available
    do {
      try {
        available = binding.transform(this._handle, this._finishFlushMode)
      } catch (err) {
        throw errors[err.code](err.message)
      }

      const read = this._buffer.length - available

      if (read) {
        this._outputLength += read

        if (this._outputLength > this._maxOutputLength) {
          throw errors.LIMIT_EXCEEDED(
            `Output length exceeded maxOutputLength of ${this._maxOutputLength} bytes`
          )
        }

        const copy = Buffer.allocUnsafe(read)
        copy.set(this._buffer.subarray(0, read))

        yield copy
      }
    } while (available === 0)

    try {
      binding.end(this._handle)
    } catch (err) {
      throw errors[err.code](err.message)
    }

    this._handle = null
  }
}

class ZlibStream extends Transform {
  constructor(mode, opts = {}) {
    const { flush, ...streamOpts } = opts

    super(streamOpts)

    this._state = new ZlibState(mode, opts)
  }

  async flush(mode = constants.Z_FULL_FLUSH, cb) {
    if (typeof mode === 'function') {
      cb = mode
      mode = constants.Z_FULL_FLUSH
    }

    const previousMode = this._state._flushMode

    this._state._flushMode = mode

    await Writable.drained(this)

    this._state._flushMode = previousMode

    if (cb) cb(null) // For Node.js compatibility
  }

  reset() {
    if (this._state === null) {
      throw errors.STREAM_CLOSED('Stream has already closed')
    }

    this._state.reset()
  }

  _transform(data, encoding, cb) {
    let err = null

    try {
      for (const chunk of this._state.transform(data)) {
        this.push(chunk)
      }
    } catch (e) {
      err = e
    }

    cb(err)
  }

  _flush(cb) {
    let err = null

    try {
      for (const chunk of this._state.flush()) {
        this.push(chunk)
      }
    } catch (e) {
      err = e
    }

    this._state = null

    cb(err)
  }
}

function readAsBuffer(stream, buffer, cb) {
  const chunks = []

  stream.on('data', ondata).on('end', onend).on('error', onerror).end(buffer)

  function ondata(chunk) {
    chunks.push(chunk)
  }

  function onend() {
    cb(null, chunks.length === 1 ? chunks[0] : Buffer.concat(chunks))
  }

  function onerror(err) {
    stream.off('end', onend)
    cb(err)
  }
}

function transformToBuffer(mode, buffer, opts) {
  if (typeof buffer === 'string') buffer = Buffer.from(buffer)

  const state = new ZlibState(mode, opts)
  const chunks = []

  for (const chunk of state.transform(buffer)) {
    chunks.push(chunk)
  }

  for (const chunk of state.flush()) {
    chunks.push(chunk)
  }

  return chunks.length === 1 ? chunks[0] : Buffer.concat(chunks)
}

exports.Deflate = class ZlibDeflateStream extends ZlibStream {
  constructor(opts) {
    super(binding.DEFLATE, opts)
  }
}

exports.createDeflate = function createDeflate(opts) {
  return new exports.Deflate(opts)
}

exports.deflate = function deflate(buffer, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  readAsBuffer(new exports.Deflate(opts), buffer, cb)
}

exports.deflateSync = function deflateSync(buffer, opts) {
  return transformToBuffer(binding.DEFLATE, buffer, opts)
}

exports.Inflate = class ZlibInflateStream extends ZlibStream {
  constructor(opts) {
    super(binding.INFLATE, opts)
  }
}

exports.createInflate = function createInflate(opts) {
  return new exports.Inflate(opts)
}

exports.inflate = function inflate(buffer, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  readAsBuffer(new exports.Inflate(opts), buffer, cb)
}

exports.inflateSync = function inflateSync(buffer, opts) {
  return transformToBuffer(binding.INFLATE, buffer, opts)
}

exports.DeflateRaw = class ZlibDeflateRawStream extends ZlibStream {
  constructor(opts) {
    super(binding.DEFLATE_RAW, opts)
  }
}

exports.createDeflateRaw = function createDeflateRaw(opts) {
  return new exports.DeflateRaw(opts)
}

exports.deflateRaw = function deflateRaw(buffer, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  readAsBuffer(new exports.DeflateRaw(opts), buffer, cb)
}

exports.deflateRawSync = function deflateRawSync(buffer, opts) {
  return transformToBuffer(binding.DEFLATE_RAW, buffer, opts)
}

exports.InflateRaw = class ZlibInflateRawStream extends ZlibStream {
  constructor(opts) {
    super(binding.INFLATE_RAW, opts)
  }
}

exports.createInflateRaw = function createInflateRaw(opts) {
  return new exports.InflateRaw(opts)
}

exports.inflateRaw = function inflateRaw(buffer, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  readAsBuffer(new exports.InflateRaw(opts), buffer, cb)
}

exports.inflateRawSync = function inflateRawSync(buffer, opts) {
  return transformToBuffer(binding.INFLATE_RAW, buffer, opts)
}

exports.Gzip = class ZlibGzipStream extends ZlibStream {
  constructor(opts) {
    super(binding.GZIP, opts)
  }
}

exports.createGzip = function createGzip(opts) {
  return new exports.Gzip(opts)
}

exports.gzip = function gzip(buffer, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  readAsBuffer(new exports.Gzip(opts), buffer, cb)
}

exports.gzipSync = function gzipSync(buffer, opts) {
  return transformToBuffer(binding.GZIP, buffer, opts)
}

exports.Gunzip = class ZlibGunzipStream extends ZlibStream {
  constructor(opts) {
    super(binding.GUNZIP, opts)
  }
}

exports.createGunzip = function createGunzip(opts) {
  return new exports.Gunzip(opts)
}

exports.gunzip = function gunzip(buffer, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  readAsBuffer(new exports.Gunzip(opts), buffer, cb)
}

exports.gunzipSync = function gunzipSync(buffer, opts) {
  return transformToBuffer(binding.GUNZIP, buffer, opts)
}
const binding = require('../binding')

module.exports = binding.constants
module.exports = class ZlibError extends Error {
  constructor(msg, code, fn = ZlibError) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'ZlibError'
  }

  static STREAM_CLOSED(msg) {
    return new ZlibError(msg, 'STREAM_CLOSED', ZlibError.STREAM_CLOSED)
  }

  static STREAM_ERROR(msg) {
    return new ZlibError(msg, 'STREAM_ERROR', ZlibError.STREAM_ERROR)
  }

  static DATA_ERROR(msg) {
    return new ZlibError(msg, 'DATA_ERROR', ZlibError.DATA_ERROR)
  }

  static MEM_ERROR(msg) {
    return new ZlibError(msg, 'MEM_ERROR', ZlibError.MEM_ERROR)
  }

  static BUF_ERROR(msg) {
    return new ZlibError(msg, 'BUF_ERROR', ZlibError.BUF_ERROR)
  }

  static VERSION_ERROR(msg) {
    return new ZlibError(msg, 'VERSION_ERROR', ZlibError.VERSION_ERROR)
  }

  static UNKNOWN_ERROR(msg) {
    return new ZlibError(msg, 'UNKNOWN_ERROR', ZlibError.UNKNOWN_ERROR)
  }

  static LIMIT_EXCEEDED(msg) {
    return new ZlibError(msg, 'LIMIT_EXCEEDED', ZlibError.LIMIT_EXCEEDED)
  }
}
{
  "name": "bare-zlib",
  "version": "1.4.1",
  "description": "Stream-based zlib bindings for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    },
    "./errors": {
      "types": "./lib/errors.d.ts",
      "default": "./lib/errors.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-zlib.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-zlib/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-zlib",
  "dependencies": {
    "bare-stream": "^2.0.0"
  },
  "devDependencies": {
    "bare-fs": "^3.0.0",
    "brittle": "^3.5.0",
    "cmake-bare": "^1.1.7",
    "cmake-fetch": "^1.0.0",
    "lunte": "^1.6.0",
    "prettier": "^3.5.3",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "bare-buffer": "*"
  },
  "peerDependenciesMeta": {
    "bare-buffer": {
      "optional": true
    }
  }
}
const FACTOR = new Uint16Array(8)

function factor4096 (i, n) {
  while (n > 0) {
    const f = i & 4095
    FACTOR[--n] = f
    i = (i - f) / 4096
  }
  return FACTOR
}

module.exports = class BigSparseArray {
  constructor () {
    this.tiny = new TinyArray()
    this.maxLength = 4096
    this.factor = 1
  }

  set (index, val) {
    if (val !== undefined) {
      while (index >= this.maxLength) {
        this.maxLength *= 4096
        this.factor++
        if (!this.tiny.isEmptyish()) {
          const t = new TinyArray()
          t.set(0, this.tiny)
          this.tiny = t
        }
      }
    }

    const f = factor4096(index, this.factor)
    const last = this.factor - 1

    let tiny = this.tiny
    for (let i = 0; i < last; i++) {
      const next = tiny.get(f[i])
      if (next === undefined) {
        if (val === undefined) return
        tiny = tiny.set(f[i], new TinyArray())
      } else {
        tiny = next
      }
    }

    return tiny.set(f[last], val)
  }

  get (index) {
    if (index >= this.maxLength) return

    const f = factor4096(index, this.factor)
    const last = this.factor - 1

    let tiny = this.tiny
    for (let i = 0; i < last; i++) {
      tiny = tiny.get(f[i])
      if (tiny === undefined) return
    }

    return tiny.get(f[last])
  }
}

class TinyArray {
  constructor () {
    this.s = 0
    this.b = new Array(1)
    this.f = new Uint16Array(1)
  }

  isEmptyish () {
    return this.b.length === 1 && this.b[0] === undefined
  }

  get (i) {
    if (this.s === 12) return this.b[i]
    const f = i >>> this.s
    const r = i & (this.b.length - 1)
    return this.f[r] === f ? this.b[r] : undefined
  }

  set (i, v) {
    while (this.s !== 12) {
      const f = i >>> this.s
      const r = i & (this.b.length - 1)
      const o = this.b[r]

      if (o === undefined || f === this.f[r]) {
        this.b[r] = v
        this.f[r] = f
        return v
      }

      this.grow()
    }

    this.b[i] = v
    return v
  }

  grow () {
    const os = this.s
    const ob = this.b
    const of = this.f

    this.s += 4
    this.b = new Array(this.b.length << 4)
    this.f = this.s === 12 ? null : new Uint8Array(this.b.length)

    const m = this.b.length - 1

    for (let or = 0; or < ob.length; or++) {
      if (ob[or] === undefined) continue

      const i = of[or] << os | or
      const f = i >>> this.s
      const r = i & m

      this.b[r] = ob[or]
      if (this.s !== 12) this.f[r] = f
    }
  }
}
{
  "name": "big-sparse-array",
  "version": "1.0.3",
  "description": "A sparse array optimised for low memory whilst still being fast",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "brittle": "^3.1.1",
    "standard": "^16.0.3"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/big-sparse-array.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/big-sparse-array/issues"
  },
  "homepage": "https://github.com/mafintosh/big-sparse-array"
}
const b4a = require('b4a')

function byteLength (size) {
  return Math.ceil(size / 8)
}

function get (buffer, bit) {
  const n = buffer.BYTES_PER_ELEMENT * 8

  const offset = bit & (n - 1)
  const i = (bit - offset) / n

  return (buffer[i] & (1 << offset)) !== 0
}

function set (buffer, bit, value = true) {
  const n = buffer.BYTES_PER_ELEMENT * 8

  const offset = bit & (n - 1)
  const i = (bit - offset) / n
  const mask = 1 << offset

  if (value) {
    if ((buffer[i] & mask) !== 0) return false
  } else {
    if ((buffer[i] & mask) === 0) return false
  }

  buffer[i] ^= mask
  return true
}

function setRange (buffer, start, end, value = true) {
  const n = buffer.BYTES_PER_ELEMENT * 8

  let remaining = end - start
  let offset = start & (n - 1)
  let i = (start - offset) / n

  let changed = false

  while (remaining > 0) {
    const mask = (2 ** Math.min(remaining, n - offset) - 1) << offset

    if (value) {
      if ((buffer[i] & mask) !== mask) {
        buffer[i] |= mask
        changed = true
      }
    } else {
      if ((buffer[i] & mask) !== 0) {
        buffer[i] &= ~mask
        changed = true
      }
    }

    remaining -= n - offset
    offset = 0
    i++
  }

  return changed
}

function fill (buffer, value, start = 0, end = buffer.byteLength * 8) {
  const n = buffer.BYTES_PER_ELEMENT * 8
  let i, j

  {
    const offset = start & (n - 1)
    i = (start - offset) / n

    if (offset !== 0) {
      const mask = (2 ** Math.min(n - offset, end - start) - 1) << offset

      if (value) buffer[i] |= mask
      else buffer[i] &= ~mask

      i++
    }
  }

  {
    const offset = end & (n - 1)
    j = (end - offset) / n

    if (offset !== 0 && j >= i) {
      const mask = (2 ** offset) - 1

      if (value) buffer[j] |= mask
      else buffer[j] &= ~mask
    }
  }

  return buffer.fill(value ? (2 ** n) - 1 : 0, i, j)
}

function toggle (buffer, bit) {
  const n = buffer.BYTES_PER_ELEMENT * 8

  const offset = bit & (n - 1)
  const i = (bit - offset) / n
  const mask = 1 << offset

  buffer[i] ^= mask
  return (buffer[i] & mask) !== 0
}

function remove (buffer, bit) {
  return set(buffer, bit, false)
}

function removeRange (buffer, start, end) {
  return setRange(buffer, start, end, false)
}

function indexOf (buffer, value, position = 0) {
  for (let i = position, n = buffer.byteLength * 8; i < n; i++) {
    if (get(buffer, i) === value) return i
  }

  return -1
}

function lastIndexOf (buffer, value, position = buffer.byteLength * 8 - 1) {
  for (let i = position; i >= 0; i--) {
    if (get(buffer, i) === value) return i
  }

  return -1
}

function of (...bits) {
  return from(bits)
}

function from (bits) {
  const buffer = b4a.alloc(byteLength(bits.length))
  for (let i = 0; i < bits.length; i++) set(buffer, i, bits[i])
  return buffer
}

function * iterator (buffer) {
  for (let i = 0, n = buffer.byteLength * 8; i < n; i++) yield get(buffer, i)
}

module.exports = {
  byteLength,
  get,
  set,
  setRange,
  fill,
  toggle,
  remove,
  removeRange,
  indexOf,
  lastIndexOf,
  of,
  from,
  iterator
}
{
  "name": "bits-to-bytes",
  "version": "1.3.0",
  "description": "Functions for doing bit manipulation of typed arrays",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "scripts": {
    "test": "standard && brittle test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bits-to-bytes.git"
  },
  "author": "Kasper Isager Dalsgarð <kasper@funktionel.co>",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/holepunchto/bits-to-bytes/issues"
  },
  "homepage": "https://github.com/holepunchto/bits-to-bytes#readme",
  "dependencies": {
    "b4a": "^1.5.0"
  },
  "devDependencies": {
    "brittle": "^2.3.1",
    "standard": "^17.0.0"
  }
}
const { EventEmitter } = require('events')
const sodium = require('sodium-universal')
const crypto = require('hypercore-crypto')
const b4a = require('b4a')
const c = require('compact-encoding')

const {
  Invite,
  ResponsePayload,
  InviteRequest,
  InviteResponse,
  InviteData,
  InviteReceipt,
  PersistedRequest,
  AuthData
} = require('./lib/messages')

const {
  PAIRING_REJECTED,
  INVITE_USED,
  INVITE_EXPIRED
} = require('./lib/errors')

const [
  NS_SIGNATURE,
  NS_TOKEN,
  NS_INVITE_ID,
  NS_REQUEST_ID,
  NS_SESSION,
  NS_SESSION_KEY,
  NS_ENCRYPT,
  NS_NONCE
] = crypto.namespace('blind-pairing', 8)

class CandidateRequest extends EventEmitter {
  constructor(invite, userData, opts = {}) {
    super()

    if (b4a.isBuffer(invite)) {
      invite = c.decode(Invite, invite)
    }

    this.discoveryKey = invite.discoveryKey
    this.seed = invite.seed

    this.keyPair = crypto.keyPair(this.seed)
    this.inviteId = deriveInviteId(this.keyPair.publicKey)
    this.userData = userData

    this.token = deriveToken(this.keyPair.publicKey, userData)
    this.session = opts.session || createSessionToken(this.token)
    this.id = deriveRequestId(this.session)

    this.payload = createAuth(this.userData, this.keyPair, this.session)

    this._encoded = null

    // set in reply
    this.auth = null
  }

  static from(buf) {
    const info = c.decode(PersistedRequest, buf)
    const { seed, discoveryKey, userData } = info
    const request = new CandidateRequest({ discoveryKey, seed }, userData)

    // clear completed request
    if (info.key) {
      request.key = info.key
      request.token = null
      request.payload = null
    }

    return request
  }

  handleResponse(payload) {
    if (b4a.isBuffer(payload)) {
      payload = this._decodeResponse(payload)
    }

    try {
      this._openResponse(payload)
    } catch (err) {
      this.emit('rejected', err)
      return null
    }

    this._onAccept()

    return this.auth
  }

  _openResponse(payload) {
    try {
      const response = openReply(
        payload,
        this.payload.session,
        this.keyPair.publicKey
      )
      this.response = c.decode(ResponsePayload, response)
    } catch (e) {
      throw new Error('Could not decrypt reply.')
    }

    const { status, key, encryptionKey, additional } = this.response

    if (status !== 0) {
      switch (status) {
        case 1:
          throw PAIRING_REJECTED()

        case 2:
          throw INVITE_USED()

        case 3:
          throw INVITE_EXPIRED()
      }
    }

    if (b4a.compare(crypto.discoveryKey(key), this.discoveryKey)) {
      throw new Error('Invite response does not match discoveryKey')
    }

    if (
      additional &&
      !crypto.verify(
        additional.data,
        additional.signature,
        this.keyPair.publicKey
      )
    ) {
      throw new Error('Additional data failed verification')
    }

    this.auth = {
      key,
      encryptionKey,
      data: additional ? additional.data : null
    }
  }

  _onAccept() {
    this.emit('accepted', this.auth)
    this.destroy()
  }

  _decodeResponse(buf) {
    try {
      const { payload } = c.decode(InviteResponse, buf)
      return payload
    } catch {
      throw new Error('Could not decode response.')
    }
  }

  destroy() {
    this.token = null
    this.payload = null

    this.emit('destroyed')
  }

  encode() {
    if (!this._encoded) this._encoded = c.encode(InviteRequest, this)
    return this._encoded
  }
}

class MemberRequest {
  constructor(inviteId, requestData) {
    this.inviteId = inviteId
    this.requestData = requestData

    this._opened = false
    this._confirmed = false
    this._denied = false

    // set by transport
    this.discoveryKey = null

    // set in open
    this.publicKey = null
    this.userData = null
    this.session = null
    this.id = null
    this.receipt = null

    // set in confirm/respond
    this._payload = null
    this.response = null
  }

  static from(req) {
    if (b4a.isBuffer(req)) {
      return MemberRequest.from(c.decode(InviteRequest, req))
    }

    return new MemberRequest(req.inviteId, req.payload)
  }

  confirm({ key, encryptionKey, additional }) {
    if (this._confirmed || this._denied || !this._opened) return
    this._confirmed = true

    const payload = c.encode(ResponsePayload, {
      status: 0,
      key,
      encryptionKey,
      additional
    })
    this._payload = createReply(payload, this.session, this.publicKey)

    this._respond()
  }

  deny({ status = 1 } = {}) {
    if (this._confirmed || this._denied) return
    this._denied = true

    if (!status) return

    const payload = c.encode(ResponsePayload, {
      status,
      key: null,
      encryptionKey: null,
      additional: null
    })
    this._payload = createReply(payload, this.session, this.publicKey)

    this._respond()
  }

  respond() {
    return {
      id: this.id,
      payload: this._payload
    }
  }

  _respond() {
    this.response = c.encode(InviteResponse, this.respond())
  }

  open(publicKey) {
    if (this._opened && b4a.equals(this.publicKey, publicKey))
      return this.userData

    try {
      this.receipt = openAuth(this.requestData, publicKey)
      const { userData, session } = c.decode(InviteReceipt, this.receipt)

      this.userData = userData
      this.session = session
      this.token = deriveToken(publicKey, userData)
      this.id = deriveRequestId(this.session)
    } catch (e) {
      throw new Error('Failed to open invite with provided key')
    }

    this.publicKey = publicKey
    this._opened = true

    return this.userData
  }
}

module.exports.CandidateRequest = CandidateRequest
module.exports.MemberRequest = MemberRequest
module.exports.createInvite = createInvite
module.exports.decodeInvite = decodeInvite
module.exports.verifyReceipt = verifyReceipt
module.exports.createReceipt = createReceipt
module.exports.Invite = Invite

function createReceipt(invite, userData) {
  const req = new CandidateRequest(invite, userData) // yolo, refactor
  const receipt = openAuth(req.payload, req.keyPair.publicKey)
  return { id: deriveInviteId(req.keyPair.publicKey), receipt }
}

function verifyReceipt(receipt, publicKey) {
  if (b4a.isBuffer(receipt)) {
    receipt = c.decode(InviteReceipt, receipt)
  }

  const { session, signature, userData } = receipt
  const signData = c.encode(AuthData, { userData, session })

  if (!verifySignature(signData, signature, publicKey)) return null

  return userData
}

function deriveInviteId(publicKey) {
  return crypto.hash([NS_INVITE_ID, publicKey])
}

function deriveKey(publicKey) {
  const out = b4a.allocUnsafe(
    sodium.crypto_aead_xchacha20poly1305_ietf_KEYBYTES
  )
  return crypto.hash([NS_ENCRYPT, publicKey], out)
}

function deriveNonce(publicKey, sessionToken) {
  const out = b4a.allocUnsafe(
    sodium.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES
  )
  return crypto.hash([NS_NONCE, publicKey, sessionToken], out)
}

function deriveToken(publicKey, userData) {
  return crypto.hash([NS_TOKEN, publicKey, userData])
}

function createSessionToken(token) {
  return crypto.hash([NS_SESSION, token])
}

function deriveRequestId(sessionToken) {
  return crypto.hash([NS_REQUEST_ID, sessionToken])
}

function createInvite(key, opts = {}) {
  const {
    discoveryKey = crypto.discoveryKey(key),
    expires = 0,
    seed = crypto.randomBytes(32),
    sensitive = false,
    data,
    testInvitation = false,
    additionalNodes
  } = opts

  const keyPair = crypto.keyPair(seed)
  const additional = data
    ? {
        data,
        signature: crypto.sign(data, keyPair.secretKey)
      }
    : null

  return {
    id: deriveInviteId(keyPair.publicKey),
    invite: c.encode(Invite, {
      seed,
      discoveryKey,
      expires,
      sensitive,
      testInvitation,
      additionalNodes
    }),
    seed,
    publicKey: keyPair.publicKey,
    additional,
    discoveryKey,
    expires,
    sensitive,
    testInvitation
  }
}

function decodeInvite(invite) {
  const data = c.decode(Invite, invite)
  return {
    id: deriveInviteId(crypto.keyPair(data.seed).publicKey),
    ...data
  }
}

function encrypt(data, nonce, secretKey) {
  const output = b4a.allocUnsafe(
    data.byteLength + sodium.crypto_aead_xchacha20poly1305_ietf_ABYTES
  )
  sodium.crypto_aead_xchacha20poly1305_ietf_encrypt(
    output,
    data,
    nonce,
    null,
    nonce,
    secretKey
  )
  return output
}

function decrypt(data, nonce, secretKey) {
  const output = b4a.allocUnsafe(
    data.byteLength - sodium.crypto_aead_xchacha20poly1305_ietf_ABYTES
  )
  sodium.crypto_aead_xchacha20poly1305_ietf_decrypt(
    output,
    null,
    data,
    nonce,
    nonce,
    secretKey
  )
  return output
}

function createAuth(userData, invitationKeyPair, session) {
  const secret = deriveKey(invitationKeyPair.publicKey)

  const nonce = deriveNonce(invitationKeyPair.publicKey, session)
  const signData = c.encode(AuthData, { userData, session })
  const signature = createSignature(signData, invitationKeyPair.secretKey)

  const inviteData = c.encode(InviteData, { userData, signature })
  const data = encrypt(inviteData, nonce, secret)

  return {
    session,
    data
  }
}

function openAuth(payload, invitationKey) {
  const secret = deriveKey(invitationKey)

  const { session, data } = payload

  const nonce = deriveNonce(invitationKey, session)

  let plaintext
  try {
    plaintext = decrypt(data, nonce, secret)
  } catch {
    // todo stronger check
    throw new Error('Decryption failed.')
  }

  const { userData, signature } = c.decode(InviteData, plaintext)
  const receipt = { session, signature, userData }

  if (!verifyReceipt(receipt, invitationKey)) {
    throw new Error('Invalid reply')
  }

  return c.encode(InviteReceipt, { session, signature, userData })
}

function createReply(payload, sessionToken, invitationKey) {
  const sessionKey = crypto.hash([NS_SESSION_KEY, invitationKey, sessionToken])
  const secret = deriveKey(sessionKey)
  const nonce = deriveNonce(sessionKey, sessionToken)

  return encrypt(payload, nonce, secret)
}

function openReply(data, sessionToken, invitationKey) {
  const sessionKey = crypto.hash([NS_SESSION_KEY, invitationKey, sessionToken])
  const secret = deriveKey(sessionKey)
  const nonce = deriveNonce(sessionKey, sessionToken)

  return decrypt(data, nonce, secret)
}

function createSignature(data, secretKey) {
  const signature = b4a.allocUnsafe(sodium.crypto_sign_BYTES)
  const namespaced = b4a.allocUnsafe(32 + data.byteLength)

  namespaced.set(NS_SIGNATURE, 0)
  namespaced.set(data, 32)

  sodium.crypto_sign_detached(signature, namespaced, secretKey)

  return signature
}

function verifySignature(data, signature, publicKey) {
  const namespaced = b4a.allocUnsafe(32 + data.byteLength)

  namespaced.set(NS_SIGNATURE, 0)
  namespaced.set(data, 32)

  return sodium.crypto_sign_verify_detached(signature, namespaced, publicKey)
}
module.exports = class PairingError extends Error {
  constructor(msg, code, fn = PairingError) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'PairingError'
  }

  static PAIRING_REJECTED(msg = 'Pairing was rejected') {
    return new PairingError(
      msg,
      'PAIRING_REJECTED',
      PairingError.PAIRING_REJECTED
    )
  }

  static INVITE_USED(msg = 'Invite has been used') {
    return new PairingError(msg, 'INVITE_USED', PairingError.INVITE_USED)
  }

  static INVITE_EXPIRED(msg = 'Invite has expireds') {
    return new PairingError(msg, 'INVITE_EXPIRED', PairingError.INVITE_EXPIRED)
  }
}
const { isBogon } = require('bogon')
const c = require('compact-encoding')

const DHTNodes = c.array(c.ipv4Address)

const Invite = {
  preencode(state, i) {
    state.end++ // version
    state.end++ // flags
    c.fixed32.preencode(state, i.seed)
    if (i.discoveryKey) c.fixed32.preencode(state, i.discoveryKey)
    if (i.expires) c.uint32.preencode(state, Math.floor(i.expires / 1000)) // store as secs
    if (i.additionalNodes && Array.isArray(i.additionalNodes))
      DHTNodes.preencode(
        state,
        i.additionalNodes.filter((node) => !isBogon(node.host))
      )
  },
  encode(state, i) {
    c.uint.encode(state, 1) // version
    c.uint.encode(
      state,
      (i.discoveryKey ? 1 : 0) |
        (i.expires ? 2 : 0) |
        (i.sensitive ? 4 : 0) |
        (i.testInvitation ? 8 : 0) |
        (i.additionalNodes && Array.isArray(i.additionalNodes) ? 16 : 0)
    )
    c.fixed32.encode(state, i.seed)
    if (i.discoveryKey) c.fixed32.encode(state, i.discoveryKey)
    if (i.expires) c.uint32.encode(state, Math.floor(i.expires / 1000))
    if (i.additionalNodes && Array.isArray(i.additionalNodes))
      DHTNodes.encode(
        state,
        i.additionalNodes.filter((node) => !isBogon(node.host))
      )
  },
  decode(state) {
    const version = c.uint.decode(state)
    if (version !== 1) {
      throw new Error('Unknown invite version')
    }

    const flags = c.uint.decode(state)

    return {
      seed: c.fixed32.decode(state),
      discoveryKey: flags & 1 ? c.fixed32.decode(state) : null,
      expires: flags & 2 ? c.uint32.decode(state) * 1000 : 0,
      sensitive: (flags & 4) !== 0,
      testInvitation: (flags & 8) !== 0,
      additionalNodes: flags & 16 ? DHTNodes.decode(state) : null
    }
  }
}

const RequestPayload = {
  preencode(state, p) {
    c.optionalBuffer.preencode(state, p.session)
    c.optionalBuffer.preencode(state, p.data)
  },
  encode(state, p) {
    c.optionalBuffer.encode(state, p.session)
    c.optionalBuffer.encode(state, p.data)
  },
  decode(state) {
    return {
      session: c.optionalBuffer.decode(state),
      data: c.optionalBuffer.decode(state)
    }
  }
}

const ResponseStatus = c.uint

const AdditionalData = {
  preencode(state, m) {
    c.optionalBuffer.preencode(state, m.data)
    c.fixed64.preencode(state, m.signature)
  },
  encode(state, m) {
    c.optionalBuffer.encode(state, m.data)
    c.fixed64.encode(state, m.signature)
  },
  decode(state) {
    return {
      data: c.optionalBuffer.decode(state),
      signature: c.fixed64.decode(state)
    }
  }
}

const ResponsePayload = {
  preencode(state, p) {
    ResponseStatus.preencode(state, p.status)
    if (p.status !== 0) return

    let flags = 0
    if (p.encryptionKey) flags |= 1
    if (p.additional) flags |= 2
    c.uint.preencode(state, flags) // flags

    c.fixed32.preencode(state, p.key)
    if (p.encryptionKey) c.fixed32.preencode(state, p.encryptionKey)
    if (p.additional) AdditionalData.preencode(state, p.additional)
  },
  encode(state, p) {
    ResponseStatus.encode(state, p.status)
    if (p.status !== 0) return

    let flags = 0
    if (p.encryptionKey) flags |= 1
    if (p.additional) flags |= 2
    c.uint.encode(state, flags)

    c.fixed32.encode(state, p.key)
    if (p.encryptionKey) c.fixed32.encode(state, p.encryptionKey)
    if (p.additional) AdditionalData.encode(state, p.additional)
  },
  decode(state) {
    const status = ResponseStatus.decode(state)

    if (status !== 0) {
      return {
        status,
        key: null,
        encryptionKey: null,
        additional: null
      }
    }

    const flags = c.uint.decode(state)
    const key = c.fixed32.decode(state)
    const encryptionKey = (flags & 1) !== 0 ? c.fixed32.decode(state) : null
    const additional = (flags & 2) !== 0 ? AdditionalData.decode(state) : null

    return {
      status: 0,
      key,
      encryptionKey,
      additional
    }
  }
}

const InviteRequest = {
  preencode(state, i) {
    c.fixed32.preencode(state, i.inviteId)
    RequestPayload.preencode(state, i.payload)
  },
  encode(state, i) {
    c.fixed32.encode(state, i.inviteId)
    RequestPayload.encode(state, i.payload)
  },
  decode(state) {
    return {
      inviteId: c.fixed32.decode(state),
      payload: RequestPayload.decode(state)
    }
  }
}

const InviteResponse = {
  preencode(state, i) {
    c.fixed32.preencode(state, i.id)
    c.optionalBuffer.preencode(state, i.payload)
  },
  encode(state, i) {
    c.fixed32.encode(state, i.id)
    c.optionalBuffer.encode(state, i.payload)
  },
  decode(state) {
    return {
      id: c.fixed32.decode(state),
      payload: c.optionalBuffer.decode(state)
    }
  }
}

const InviteData = {
  preencode(state, i) {
    c.fixed64.preencode(state, i.signature)
    c.optionalBuffer.preencode(state, i.userData)
  },
  encode(state, i) {
    c.fixed64.encode(state, i.signature)
    c.optionalBuffer.encode(state, i.userData)
  },
  decode(state) {
    return {
      signature: c.fixed64.decode(state),
      userData: c.optionalBuffer.decode(state)
    }
  }
}

const InviteReceipt = {
  preencode(state, i) {
    c.fixed32.preencode(state, i.session)
    c.fixed64.preencode(state, i.signature)
    c.optionalBuffer.preencode(state, i.userData)
  },
  encode(state, i) {
    c.fixed32.encode(state, i.session)
    c.fixed64.encode(state, i.signature)
    c.optionalBuffer.encode(state, i.userData)
  },
  decode(state) {
    return {
      session: c.fixed32.decode(state),
      signature: c.fixed64.decode(state),
      userData: c.optionalBuffer.decode(state)
    }
  }
}

const AuthData = {
  preencode(state, i) {
    c.optionalBuffer.preencode(state, i.session)
    c.optionalBuffer.preencode(state, i.userData)
  },
  encode(state, i) {
    c.optionalBuffer.encode(state, i.session)
    c.optionalBuffer.encode(state, i.userData)
  },
  decode(state) {
    return {
      session: c.optionalBuffer.decode(state),
      userData: c.optionalBuffer.decode(state)
    }
  }
}

module.exports = {
  Invite,
  ResponsePayload,
  InviteRequest,
  InviteResponse,
  InviteData,
  InviteReceipt,
  AuthData
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "blind-pairing-core",
  "version": "2.10.1",
  "description": "Core blind pairing module",
  "main": "index.js",
  "files": [
    "index.js",
    "lib/**.js"
  ],
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test/*.js"
  },
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/blind-pairing-core.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/blind-pairing-core/issues"
  },
  "homepage": "https://github.com/holepunchto/blind-pairing-core#readme",
  "dependencies": {
    "b4a": "^1.6.4",
    "bare-events": "^2.5.0",
    "bogon": "^1.1.0",
    "compact-encoding": "^3.0.0",
    "hypercore-crypto": "^3.4.0",
    "sodium-universal": "^5.0.1",
    "tiny-buffer-map": "^1.1.1"
  },
  "devDependencies": {
    "brittle": "^3.2.1",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  }
}
const EventEmitter = require('events')
const Protomux = require('protomux')
const { Readable } = require('streamx')
const sodium = require('sodium-universal')
const b4a = require('b4a')
const c = require('compact-encoding')
const bitfield = require('compact-encoding-bitfield')
const bits = require('bits-to-bytes')
const errors = require('./lib/errors')

exports.Server = class BlindRelayServer extends EventEmitter {
  constructor(opts = {}) {
    super()

    const { createStream } = opts

    this._createStream = createStream
    this._pairing = new Map()
    this._activePairingRefs = new Map()
    this._sessions = new Set()
    this.stats = createStats()
  }

  get sessions() {
    return this._sessions[Symbol.iterator]()
  }

  accept(stream, opts) {
    const session = new BlindRelaySession(this, stream, opts)

    this._sessions.add(session)
    this.stats.sessions.accepted++

    return session
  }

  async close() {
    const ending = []

    for (const session of this._sessions) {
      ending.push(session.end())
    }

    await Promise.all(ending)

    this._pairing.clear()
  }

  _trackActiveLink(keyString) {
    const refs = this._activePairingRefs.get(keyString) || 0

    if (refs === 0) this.stats.pairings.active++

    this._activePairingRefs.set(keyString, refs + 1)
  }

  _untrackActiveLink(keyString) {
    const refs = this._activePairingRefs.get(keyString)

    if (refs === undefined) return

    if (refs === 1) {
      this._activePairingRefs.delete(keyString)
      this.stats.pairings.active--
    } else {
      this._activePairingRefs.set(keyString, refs - 1)
    }
  }
}

class BlindRelaySession extends EventEmitter {
  constructor(server, stream, opts = {}) {
    super()

    const { id, handshake, handshakeEncoding } = opts

    this._server = server
    this._mux = Protomux.from(stream)

    this._channel = this._mux.createChannel({
      protocol: 'blind-relay',
      id,
      handshake: handshake ? handshakeEncoding || c.raw : null,
      onopen: this._onopen.bind(this),
      onclose: this._onclose.bind(this),
      ondestroy: this._ondestroy.bind(this)
    })

    this._pair = this._channel.addMessage({
      encoding: m.pair,
      onmessage: this._onpair.bind(this)
    })

    this._unpair = this._channel.addMessage({
      encoding: m.unpair,
      onmessage: this._onunpair.bind(this)
    })

    this._ending = null
    this._destroyed = false
    this._error = null
    this._pairing = new Set()
    this._links = new Map()

    this._onerror = (err) => {
      this._server.stats.streams.errors++
      this.emit('error', err)
    }

    this._channel.open(handshake)
  }

  get closed() {
    return this._channel.closed
  }

  get mux() {
    return this._mux
  }

  get stream() {
    return this._mux.stream
  }

  _onopen() {
    this._server.stats.sessions.opened++
    this.emit('open')
  }

  _onclose() {
    this._ending = Promise.resolve()

    const err = this._error || errors.CHANNEL_CLOSED()
    this._server.stats.pairings.cancelled += this._pairing.size

    for (const token of this._pairing) {
      if (this._server._pairing.delete(token.toString('hex'))) {
        this._server.stats.pairings.pending--
      }
    }

    for (const link of this._links.values()) {
      link.destroy(err)
    }

    this._pairing.clear()
    this._links.clear()

    this._server._sessions.delete(this)
    this._server.stats.sessions.closed++

    this.emit('close')
  }

  _ondestroy() {
    this._destroyed = true
    this.emit('destroy')
  }

  _onpair({ isInitiator, token, id: remoteId }) {
    const keyString = token.toString('hex')

    let pair = this._server._pairing.get(keyString)

    if (pair === undefined) {
      pair = new BlindRelayPair(token)
      this._server._pairing.set(keyString, pair)
      this._server.stats.pairings.pending++
    } else if (pair.links[+isInitiator]) return

    this._pairing.add(keyString)
    this._server.stats.pairings.requested++

    pair.links[+isInitiator] = new BlindRelayLink(this, isInitiator, remoteId)

    if (!pair.paired) return

    this._server._pairing.delete(keyString)
    this._server.stats.pairings.pending--
    this._server.stats.pairings.matched++

    // 1st pass: Create the raw streams needed for each end of the link.
    for (const link of pair.links) {
      link.createStream()
    }

    // 2nd pass: Connect the raw streams and set up handlers.
    for (const link of pair.links) {
      link.remote = pair.remote(link.isInitiator)
      link.activate(keyString)
    }

    // 3rd pass: Let either end of the link know the streams were set up.
    for (const { isInitiator, session, remoteId, stream } of pair.links) {
      session._pair.send({
        isInitiator,
        token,
        id: stream.id,
        seq: 0
      })

      session._endMaybe()

      session.emit('pair', isInitiator, token, stream, remoteId)
    }
  }

  _onunpair({ token }) {
    const keyString = token.toString('hex')

    const pair = this._server._pairing.get(keyString)

    if (pair) {
      for (const link of pair.links) {
        if (link) link.session._pairing.delete(keyString)
      }

      this._server._pairing.delete(keyString)
      this._server.stats.pairings.pending--
      this._server.stats.pairings.cancelled++
      return
    }

    const link = this._links.get(keyString)

    if (link) {
      link.destroyPair(errors.PAIRING_CANCELLED())
      this._server.stats.pairings.cancelled++
    }
  }

  cork() {
    this._channel.cork()
  }

  uncork() {
    this._channel.uncork()
  }

  async end() {
    if (this._ending) return this._ending

    this._ending = EventEmitter.once(this, 'close')
    this._endMaybe()

    return this._ending
  }

  _endMaybe() {
    if (this._ending && this._pairing.size === 0) {
      this._channel.close()
    }
  }

  destroy(err) {
    if (this._destroyed) return
    this._destroyed = true

    this._error = err || errors.CHANNEL_DESTROYED()
    this._channel.close()
  }
}

class BlindRelayPair {
  constructor(token) {
    this.token = token
    this.links = [null, null]
  }

  get paired() {
    return this.links[0] !== null && this.links[1] !== null
  }

  remote(isInitiator) {
    return this.links[isInitiator ? 0 : 1]
  }
}

class BlindRelayLink {
  constructor(session, isInitiator, remoteId) {
    this.session = session
    this.isInitiator = isInitiator
    this.remoteId = remoteId
    this.stream = null
    this.remote = null
    this.keyString = null
    this._onclose = null
  }

  createStream() {
    if (this.stream) return

    this.stream = this.session._server._createStream({
      firewall: this._onfirewall.bind(this)
    })
  }

  activate(keyString) {
    const stream = this.stream

    this.keyString = keyString
    this._onclose = () => {
      if (this.stream !== stream) return

      this.stream = null
      unlink(this)
      this.session._links.delete(keyString)
      this.session._server._untrackActiveLink(keyString)
      this.session._server.stats.streams.closed++
    }

    stream.on('error', this.session._onerror).on('close', this._onclose).relayTo(this.remote.stream)

    this.session._pairing.delete(keyString)
    this.session._links.set(keyString, this)
    this.session._server._trackActiveLink(keyString)
    this.session._server.stats.streams.opened++
  }

  destroy(err) {
    const stream = this.stream

    if (!stream) return

    this.stream = null

    stream.off('close', this._onclose)
    this._onclose = null

    stream.off('error', this.session._onerror)
    unlink(this)
    this.session._links.delete(this.keyString)
    this.session._server._untrackActiveLink(this.keyString)
    this.session._server.stats.streams.closed++
    stream.on('error', noop).destroy(err)
  }

  destroyPair(err) {
    const remote = this.remote

    this.destroy(err)
    if (remote) remote.destroy(err)
  }

  _onfirewall(socket, port, host) {
    this.stream.connect(socket, this.remoteId, port, host)

    return false
  }
}

exports.Client = class BlindRelayClient extends EventEmitter {
  static _clients = new WeakMap()

  static from(stream, opts) {
    let client = this._clients.get(stream)
    if (client) return client
    client = new this(stream, opts)
    this._clients.set(stream, client)
    return client
  }

  constructor(stream, opts = {}) {
    super()

    const { id, handshake, handshakeEncoding } = opts

    this._mux = Protomux.from(stream)

    this._channel = this._mux.createChannel({
      protocol: 'blind-relay',
      id,
      handshake: handshake ? handshakeEncoding || c.raw : null,
      onopen: this._onopen.bind(this),
      onclose: this._onclose.bind(this),
      ondestroy: this._ondestroy.bind(this)
    })

    this._pair = this._channel.addMessage({
      encoding: m.pair,
      onmessage: this._onpair.bind(this)
    })

    this._unpair = this._channel.addMessage({
      encoding: m.unpair
    })

    this._ending = false
    this._destroyed = false
    this._error = null
    this._requests = new Map()

    this._channel.open(handshake)
  }

  get closed() {
    return this._channel.closed
  }

  get mux() {
    return this._mux
  }

  get stream() {
    return this._mux.stream
  }

  get requests() {
    return this._requests.values()
  }

  _onopen() {
    this.emit('open')
  }

  _onclose() {
    this._ending = Promise.resolve()

    const err = this._error || errors.CHANNEL_CLOSED()

    for (const request of this._requests.values()) {
      request.destroy(err)
    }

    this._requests.clear()

    this.constructor._clients.delete(this.stream)

    this.emit('close')
  }

  _ondestroy() {
    this._destroyed = true
    this.emit('destroy')
  }

  _onpair({ isInitiator, token, id: remoteId }) {
    const request = this._requests.get(token.toString('hex'))

    if (request === undefined || request.isInitiator !== isInitiator) return

    request.push(remoteId)
    request.push(null)

    this.emit('pair', request.isInitiator, request.token, request.stream, remoteId)
  }

  pair(isInitiator, token, stream) {
    if (this._destroyed) throw errors.CHANNEL_DESTROYED()

    const keyString = token.toString('hex')

    if (this._requests.has(keyString)) throw errors.ALREADY_PAIRING()

    const request = new BlindRelayRequest(this, isInitiator, token, stream)

    this._requests.set(keyString, request)

    return request
  }

  unpair(token) {
    if (this._destroyed) throw errors.CHANNEL_DESTROYED()

    const request = this._requests.get(token.toString('hex'))

    if (request) request.destroy(errors.PAIRING_CANCELLED())

    this._unpair.send({ token })
  }

  cork() {
    this._channel.cork()
  }

  uncork() {
    this._channel.uncork()
  }

  async end() {
    if (this._ending) return this._ending

    this._ending = EventEmitter.once(this, 'close')
    this._endMaybe()

    return this._ending
  }

  _endMaybe() {
    if (this._ending && this._requests.size === 0) {
      this._channel.close()
    }
  }

  destroy(err) {
    if (this._destroyed) return
    this._destroyed = true

    this._error = err || errors.CHANNEL_DESTROYED()
    this._channel.close()
  }
}

class BlindRelayRequest extends Readable {
  constructor(client, isInitiator, token, stream) {
    super()

    this.client = client
    this.isInitiator = isInitiator
    this.token = token
    this.stream = stream
  }

  _open(cb) {
    if (this.client._destroyed) return cb(errors.CHANNEL_DESTROYED())

    this.client._pair.send({
      isInitiator: this.isInitiator,
      token: this.token,
      id: this.stream.id,
      seq: 0
    })

    cb(null)
  }

  _destroy(cb) {
    this.client._requests.delete(this.token.toString('hex'))

    cb(null)

    this.client._endMaybe()
  }
}

exports.token = function token(buf = b4a.allocUnsafe(32)) {
  sodium.randombytes_buf(buf)
  return buf
}

function noop() {}

function unlink(link) {
  const remote = link.remote

  link.remote = null

  if (remote && remote.remote === link) {
    remote.remote = null
  }
}

function createStats() {
  const stats = {
    sessions: {
      accepted: 0,
      opened: 0,
      closed: 0,
      get active() {
        return this.accepted - this.closed
      }
    },
    pairings: {
      requested: 0,
      matched: 0,
      cancelled: 0,
      pending: 0,
      active: 0
    },
    streams: {
      opened: 0,
      closed: 0,
      errors: 0,
      get active() {
        return this.opened - this.closed
      }
    }
  }

  return stats
}

const m = (exports.messages = {})

const flags = bitfield(7)

m.pair = {
  preencode(state, m) {
    flags.preencode(state)
    c.fixed32.preencode(state, m.token)
    c.uint.preencode(state, m.id)
    c.uint.preencode(state, m.seq)
  },
  encode(state, m) {
    flags.encode(state, bits.of(m.isInitiator))
    c.fixed32.encode(state, m.token)
    c.uint.encode(state, m.id)
    c.uint.encode(state, m.seq)
  },
  decode(state) {
    const [isInitiator] = bits.iterator(flags.decode(state))

    return {
      isInitiator,
      token: c.fixed32.decode(state),
      id: c.uint.decode(state),
      seq: c.uint.decode(state)
    }
  }
}

m.unpair = {
  preencode(state, m) {
    flags.preencode(state)
    c.fixed32.preencode(state, m.token)
  },
  encode(state, m) {
    flags.encode(state, bits.of())
    c.fixed32.encode(state, m.token)
  },
  decode(state) {
    flags.decode(state)

    return {
      token: c.fixed32.decode(state)
    }
  }
}
module.exports = class BlindRelayError extends Error {
  constructor(msg, code, fn = BlindRelayError) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'BlindRelayError'
  }

  static DUPLICATE_CHANNEL(msg = 'Duplicate channel') {
    return new BlindRelayError(msg, 'DUPLICATE_CHANNEL', BlindRelayError.DUPLICATE_CHANNEL)
  }

  static CHANNEL_CLOSED(msg = 'Channel closed') {
    return new BlindRelayError(msg, 'CHANNEL_CLOSED', BlindRelayError.CHANNEL_CLOSED)
  }

  static CHANNEL_DESTROYED(msg = 'Channel destroyed') {
    return new BlindRelayError(msg, 'CHANNEL_DESTROYED', BlindRelayError.CHANNEL_DESTROYED)
  }

  static ALREADY_PAIRING(msg = 'Already pairing') {
    return new BlindRelayError(msg, 'ALREADY_PAIRING', BlindRelayError.ALREADY_PAIRING)
  }

  static PAIRING_CANCELLED(msg = 'Pairing cancelled') {
    return new BlindRelayError(msg, 'PAIRING_CANCELLED', BlindRelayError.PAIRING_CANCELLED)
  }
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "blind-relay",
  "version": "1.6.1",
  "description": "Blind relay for UDX over Protomux channels",
  "main": "index.js",
  "files": [
    "index.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:bare",
    "test:bare": "brittle-bare --coverage test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/blind-relay.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/blind-relay/issues"
  },
  "homepage": "https://github.com/holepunchto/blind-relay#readme",
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "dependencies": {
    "b4a": "^1.6.4",
    "bare-events": "^2.2.0",
    "bits-to-bytes": "^1.3.0",
    "compact-encoding": "^3.0.0",
    "compact-encoding-bitfield": "^1.0.0",
    "protomux": "^3.5.1",
    "sodium-universal": "^5.0.0",
    "streamx": "^2.15.1"
  },
  "devDependencies": {
    "brittle": "^3.2.1",
    "hyperdht": "^6.6.1",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "udx-native": "^1.6.1"
  }
}
// https://ipinfo.io/bogon

const b4a = require('b4a')
const c = require('compact-encoding')

module.exports = exports = function isBogon (ip) {
  return isBogonIP(ensureBuffer(ip))
}

exports.isBogon = exports

exports.isPrivate = function isPrivate (ip) {
  return isPrivateIP(ensureBuffer(ip))
}

exports.isReserved = function isReserved (ip) {
  return isReservedIP(ensureBuffer(ip))
}

function isBogonIP (ip) {
  return isPrivateIP(ip) || isReservedIP(ip)
}

function isPrivateIP (ip) {
  return ip.byteLength === 4 ? isPrivateIPv4(ip) : false // IPv6 has no private IPs
}

function isPrivateIPv4 (ip) {
  return (
    // 10.0.0.0/8  Private-use networks
    (ip[0] === 10) ||
    // 100.64.0.0/10 Carrier-grade NAT
    (ip[0] === 100 && ip[1] >= 64 && ip[1] <= 127) ||
    // 127.0.0.0/8 Loopback + Name collision occurrence (127.0.53.53)
    (ip[0] === 127) ||
    // 169.254.0.0/16  Link local
    (ip[0] === 169 && ip[1] === 254) ||
    // 172.16.0.0/12 Private-use networks
    (ip[0] === 172 && ip[1] >= 16 && ip[1] <= 31) ||
    // 192.168.0.0/16  Private-use networks
    (ip[0] === 192 && ip[1] === 168)
  )
}

function isReservedIP (ip) {
  return ip.byteLength === 4 ? isReservedIPv4(ip) : isReservedIPv6(ip)
}

function isReservedIPv4 (ip) {
  return (
    // 0.0.0.0/8 "This" network
    (ip[0] === 0) ||
    // 192.0.0.0/24  IETF protocol assignments
    (ip[0] === 192 && ip[1] === 0 && ip[2] === 0) ||
    // 192.0.2.0/24  TEST-NET-1
    (ip[0] === 192 && ip[1] === 0 && ip[2] === 2) ||
    // 198.18.0.0/15 Network interconnect device benchmark testing
    (ip[0] === 198 && ip[1] >= 18 && ip[1] <= 19) ||
    // 198.51.100.0/24 TEST-NET-2
    (ip[0] === 198 && ip[1] === 51 && ip[2] === 100) ||
    // 203.0.113.0/24  TEST-NET-3
    (ip[0] === 203 && ip[1] === 0 && ip[2] === 113) ||
    // 224.0.0.0/4 Multicast
    (ip[0] >= 224 && ip[0] <= 239) ||
    // 240.0.0.0/4 Reserved for future use
    (ip[0] >= 240) ||
    // 255.255.255.255/32
    (ip[0] === 255 && ip[1] === 255 && ip[2] === 255 && ip[3] === 255)
  )
}

function isReservedIPv6 (ip) {
  return (
    // ::/128 Node-scope unicast unspecified address
    // ::1/128 Node-scope unicast loopback address
    (
      ip[0] === 0 && ip[1] === 0 && ip[2] === 0 && ip[3] === 0 && ip[4] === 0 &&
      ip[5] === 0 && ip[6] === 0 && ip[7] === 0 && ip[8] === 0 && ip[9] === 0 &&
      ip[10] === 0 && ip[11] === 0 && ip[12] === 0 && ip[13] === 0 && ip[14] === 0 &&
      ip[15] <= 1
    ) ||
    // ::ffff:0:0/96 IPv4-mapped addresses
    // ::/96 IPv4-compatible addresses
    (
      ip[0] === 0 && ip[1] === 0 && ip[2] === 0 && ip[3] === 0 && ip[4] === 0 &&
      ip[5] === 0 && ip[6] === 0 && ip[7] === 0 && ip[8] === 0 && ip[9] === 0 &&
      (ip[10] === 0 || ip[10] === 0xff) &&
      (ip[11] === 0 || ip[11] === 0xff)
    ) ||
    // 100::/64 Remotely triggered black hole addresses
    (ip[0] === 0x01 && ip[1] === 0 && ip[2] === 0 && ip[3] === 0 && ip[4] === 0 && ip[5] === 0 && ip[6] === 0 && ip[7] === 0) ||
    // 2001:10::/28 Overlay routable cryptographic hash identifiers (ORCHID)
    (ip[0] === 0x20 && ip[1] === 0x01 && ip[2] === 0 && ip[3] >= 0x10 && ip[3] <= 0x1f) ||
    // 2001:20::/28 Overlay routable cryptographic hash identifiers version 2 (ORCHIDv2)
    (ip[0] === 0x20 && ip[1] === 0x01 && ip[2] === 0 && ip[3] >= 0x20 && ip[3] <= 0x2f) ||
    // 2001:db8::/32 Documentation prefix
    (ip[0] === 0x20 && ip[1] === 0x01 && ip[2] === 0x0d && ip[3] === 0xb8) ||
    // fc00::/7 Unique local addresses (ULA)
    (ip[0] >= 0xfc && ip[0] <= 0xfd) ||
    // fe80::/10 Link-local unicast
    (ip[0] === 0xfe && ip[1] >= 0x80 && ip[1] <= 0xbf) ||
    // ff00::/8 Multicast
    (ip[0] === 0xff)
  )
}

const state = c.state(0, 0, b4a.allocUnsafe(1 /* family */ + 16))

function ensureBuffer (ip) {
  if (b4a.isBuffer(ip)) return ip

  c.ip.preencode(state, ip)
  c.ip.encode(state, ip)

  const buffer = state.buffer.subarray(1 /* family */, state.end)

  state.start = 0
  state.end = 0

  return buffer
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "bogon",
  "version": "1.3.0",
  "description": "Check if an IP is a bogon",
  "main": "index.js",
  "scripts": {
    "test": "standard && brittle test.mjs"
  },
  "dependencies": {
    "compact-encoding": "^3.0.0",
    "compact-encoding-net": "^1.2.0"
  },
  "devDependencies": {
    "brittle": "^3.0.4",
    "nanobench": "^2.1.1",
    "standard": "^17.0.0"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/bogon.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/bogon/issues"
  },
  "homepage": "https://github.com/mafintosh/bogon"
}
import { encode, encodeInto, objectToTokens, rfc8949EncodeOptions } from './lib/encode.js'
import { decode, decodeFirst, Tokeniser, tokensToObject } from './lib/decode.js'
import { Tagged } from './lib/tagged.js'
import { Token, Type } from './lib/token.js'

/**
 * Export the types that were present in the original manual cborg.d.ts
 * @typedef {import('./interface.js').TagDecodeControl} TagDecodeControl
 * @typedef {import('./interface.js').TagDecoder} TagDecoder
 * There was originally just `TypeEncoder` so don't break types by renaming or not exporting
 * @typedef {import('./interface.js').OptionalTypeEncoder} TypeEncoder
 * @typedef {import('./interface.js').DecodeOptions} DecodeOptions
 * @typedef {import('./interface.js').EncodeOptions} EncodeOptions
 */

export {
  decode,
  decodeFirst,
  Tokeniser as Tokenizer,
  tokensToObject,
  encode,
  encodeInto,
  objectToTokens,
  rfc8949EncodeOptions,
  Tagged,
  Token,
  Type
}
/* globals BigInt */

import { Token, Type } from './token.js'
import { decodeErrPrefix, assertEnoughData } from './common.js'

export const uintBoundaries = [24, 256, 65536, 4294967296, BigInt('18446744073709551616')]

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number}
 */
export function readUint8 (data, offset, options) {
  assertEnoughData(data, offset, 1)
  const value = data[offset]
  if (options.strict === true && value < uintBoundaries[0]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  return value
}

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number}
 */
export function readUint16 (data, offset, options) {
  assertEnoughData(data, offset, 2)
  const value = (data[offset] << 8) | data[offset + 1]
  if (options.strict === true && value < uintBoundaries[1]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  return value
}

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number}
 */
export function readUint32 (data, offset, options) {
  assertEnoughData(data, offset, 4)
  const value = (data[offset] * 16777216 /* 2 ** 24 */) + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]
  if (options.strict === true && value < uintBoundaries[2]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  return value
}

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number|bigint}
 */
export function readUint64 (data, offset, options) {
  // assume BigInt, convert back to Number if within safe range
  assertEnoughData(data, offset, 8)
  const hi = (data[offset] * 16777216 /* 2 ** 24 */) + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]
  const lo = (data[offset + 4] * 16777216 /* 2 ** 24 */) + (data[offset + 5] << 16) + (data[offset + 6] << 8) + data[offset + 7]
  const value = (BigInt(hi) << BigInt(32)) + BigInt(lo)
  if (options.strict === true && value < uintBoundaries[3]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  if (value <= Number.MAX_SAFE_INTEGER) {
    return Number(value)
  }
  if (options.allowBigInt === true) {
    return value
  }
  throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`)
}

/* not required thanks to quick[] list
const oneByteTokens = new Array(24).fill(0).map((v, i) => new Token(Type.uint, i, 1))
export function decodeUintCompact (data, pos, minor, options) {
  return oneByteTokens[minor]
}
*/

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint8 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint8(data, pos + 1, options), 2)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint16 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint16(data, pos + 1, options), 3)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint32 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint32(data, pos + 1, options), 5)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint64 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint64(data, pos + 1, options), 9)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeUint (writer, token) {
  return encodeUintValue(writer, 0, token.value)
}

/**
 * @param {ByteWriter} writer
 * @param {number} major
 * @param {number|bigint} uint
 */
export function encodeUintValue (writer, major, uint) {
  if (uint < uintBoundaries[0]) {
    const nuint = Number(uint)
    // pack into one byte, minor=0, additional=value
    writer.push([major | nuint])
  } else if (uint < uintBoundaries[1]) {
    const nuint = Number(uint)
    // pack into two byte, minor=0, additional=24
    writer.push([major | 24, nuint])
  } else if (uint < uintBoundaries[2]) {
    const nuint = Number(uint)
    // pack into three byte, minor=0, additional=25
    writer.push([major | 25, nuint >>> 8, nuint & 0xff])
  } else if (uint < uintBoundaries[3]) {
    const nuint = Number(uint)
    // pack into five byte, minor=0, additional=26
    writer.push([major | 26, (nuint >>> 24) & 0xff, (nuint >>> 16) & 0xff, (nuint >>> 8) & 0xff, nuint & 0xff])
  } else {
    const buint = BigInt(uint)
    if (buint < uintBoundaries[4]) {
      // pack into nine byte, minor=0, additional=27
      const set = [major | 27, 0, 0, 0, 0, 0, 0, 0]
      // simulate bitwise above 32 bits
      let lo = Number(buint & BigInt(0xffffffff))
      let hi = Number(buint >> BigInt(32) & BigInt(0xffffffff))
      set[8] = lo & 0xff
      lo = lo >> 8
      set[7] = lo & 0xff
      lo = lo >> 8
      set[6] = lo & 0xff
      lo = lo >> 8
      set[5] = lo & 0xff
      set[4] = hi & 0xff
      hi = hi >> 8
      set[3] = hi & 0xff
      hi = hi >> 8
      set[2] = hi & 0xff
      hi = hi >> 8
      set[1] = hi & 0xff
      writer.push(set)
    } else {
      throw new Error(`${decodeErrPrefix} encountered BigInt larger than allowable range`)
    }
  }
}

/**
 * @param {Token} token
 * @returns {number}
 */
encodeUint.encodedSize = function encodedSize (token) {
  return encodeUintValue.encodedSize(token.value)
}

/**
 * @param {number} uint
 * @returns {number}
 */
encodeUintValue.encodedSize = function encodedSize (uint) {
  if (uint < uintBoundaries[0]) {
    return 1
  }
  if (uint < uintBoundaries[1]) {
    return 2
  }
  if (uint < uintBoundaries[2]) {
    return 3
  }
  if (uint < uintBoundaries[3]) {
    return 5
  }
  return 9
}

/**
 * @param {Token} tok1
 * @param {Token} tok2
 * @returns {number}
 */
encodeUint.compareTokens = function compareTokens (tok1, tok2) {
  return tok1.value < tok2.value ? -1 : tok1.value > tok2.value ? 1 : 0
}
/* eslint-env es2020 */

import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import { decodeErrPrefix } from './common.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint8 (data, pos, _minor, options) {
  return new Token(Type.negint, -1 - uint.readUint8(data, pos + 1, options), 2)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint16 (data, pos, _minor, options) {
  return new Token(Type.negint, -1 - uint.readUint16(data, pos + 1, options), 3)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint32 (data, pos, _minor, options) {
  return new Token(Type.negint, -1 - uint.readUint32(data, pos + 1, options), 5)
}

const neg1b = BigInt(-1)
const pos1b = BigInt(1)

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint64 (data, pos, _minor, options) {
  const int = uint.readUint64(data, pos + 1, options)
  if (typeof int !== 'bigint') {
    const value = -1 - int
    if (value >= Number.MIN_SAFE_INTEGER) {
      return new Token(Type.negint, value, 9)
    }
  }
  if (options.allowBigInt !== true) {
    throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`)
  }
  return new Token(Type.negint, neg1b - BigInt(int), 9)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeNegint (writer, token) {
  const negint = token.value
  const unsigned = (typeof negint === 'bigint' ? (negint * neg1b - pos1b) : (negint * -1 - 1))
  uint.encodeUintValue(writer, token.type.majorEncoded, unsigned)
}

/**
 * @param {Token} token
 * @returns {number}
 */
encodeNegint.encodedSize = function encodedSize (token) {
  const negint = token.value
  const unsigned = (typeof negint === 'bigint' ? (negint * neg1b - pos1b) : (negint * -1 - 1))
  // handled by quickEncode, we shouldn't get here but it's included for completeness
  if (unsigned < uint.uintBoundaries[0]) {
    return 1
  }
  if (unsigned < uint.uintBoundaries[1]) {
    return 2
  }
  if (unsigned < uint.uintBoundaries[2]) {
    return 3
  }
  if (unsigned < uint.uintBoundaries[3]) {
    return 5
  }
  return 9
}

/**
 * @param {Token} tok1
 * @param {Token} tok2
 * @returns {number}
 */
encodeNegint.compareTokens = function compareTokens (tok1, tok2) {
  // opposite of the uint comparison since we store the uint version in bytes
  return tok1.value < tok2.value ? 1 : tok1.value > tok2.value ? -1 : 0
}
import { Token, Type } from './token.js'
import { assertEnoughData, decodeErrPrefix } from './common.js'
import * as uint from './0uint.js'
import { compare, fromString } from './byte-utils.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} prefix
 * @param {number} length
 * @returns {Token}
 */
function toToken (data, pos, prefix, length) {
  assertEnoughData(data, pos, prefix + length)
  const buf = data.slice(pos + prefix, pos + prefix + length)
  return new Token(Type.bytes, buf, prefix + length)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeBytesCompact (data, pos, minor, _options) {
  return toToken(data, pos, 1, minor)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer bytes lengths not supported`)
  }
  return toToken(data, pos, 9, l)
}

/**
 * `encodedBytes` allows for caching when we do a byte version of a string
 * for key sorting purposes
 * @param {Token} token
 * @returns {Uint8Array}
 */
function tokenBytes (token) {
  if (token.encodedBytes === undefined) {
    token.encodedBytes = Type.equals(token.type, Type.string) ? fromString(token.value) : token.value
  }
  // @ts-ignore c'mon
  return token.encodedBytes
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeBytes (writer, token) {
  const bytes = tokenBytes(token)
  uint.encodeUintValue(writer, token.type.majorEncoded, bytes.length)
  writer.push(bytes)
}

/**
 * @param {Token} token
 * @returns {number}
 */
encodeBytes.encodedSize = function encodedSize (token) {
  const bytes = tokenBytes(token)
  return uint.encodeUintValue.encodedSize(bytes.length) + bytes.length
}

/**
 * @param {Token} tok1
 * @param {Token} tok2
 * @returns {number}
 */
encodeBytes.compareTokens = function compareTokens (tok1, tok2) {
  return compareBytes(tokenBytes(tok1), tokenBytes(tok2))
}

/**
 * @param {Uint8Array} b1
 * @param {Uint8Array} b2
 * @returns {number}
 */
export function compareBytes (b1, b2) {
  return b1.length < b2.length ? -1 : b1.length > b2.length ? 1 : compare(b1, b2)
}
import { Token, Type } from './token.js'
import { assertEnoughData, decodeErrPrefix } from './common.js'
import * as uint from './0uint.js'
import { encodeBytes } from './2bytes.js'

const textDecoder = new TextDecoder()

// Threshold for ASCII fast-path vs TextDecoder. Short ASCII strings (common for
// map keys) are faster to decode with a simple loop than TextDecoder overhead.
const ASCII_THRESHOLD = 32

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * Decode UTF-8 bytes to string. For short ASCII strings (common case for map keys),
 * a simple loop is faster than TextDecoder.
 * @param {Uint8Array} bytes
 * @param {number} start
 * @param {number} end
 * @returns {string}
 */
function toStr (bytes, start, end) {
  const len = end - start
  if (len < ASCII_THRESHOLD) {
    let str = ''
    for (let i = start; i < end; i++) {
      const c = bytes[i]
      if (c & 0x80) { // non-ASCII, fall back to TextDecoder
        return textDecoder.decode(bytes.subarray(start, end))
      }
      str += String.fromCharCode(c)
    }
    return str
  }
  return textDecoder.decode(bytes.subarray(start, end))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} prefix
 * @param {number} length
 * @param {DecodeOptions} options
 * @returns {Token}
 */
function toToken (data, pos, prefix, length, options) {
  const totLength = prefix + length
  assertEnoughData(data, pos, totLength)
  const tok = new Token(Type.string, toStr(data, pos + prefix, pos + totLength), totLength)
  if (options.retainStringBytes === true) {
    tok.byteValue = data.slice(pos + prefix, pos + totLength)
  }
  return tok
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeStringCompact (data, pos, minor, options) {
  return toToken(data, pos, 1, minor, options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options), options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options), options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options), options)
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer string lengths not supported`)
  }
  return toToken(data, pos, 9, l, options)
}

export const encodeString = encodeBytes
import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import { decodeErrPrefix } from './common.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} prefix
 * @param {number} length
 * @returns {Token}
 */
function toToken (_data, _pos, prefix, length) {
  return new Token(Type.array, length, prefix)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeArrayCompact (data, pos, minor, _options) {
  return toToken(data, pos, 1, minor)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer array lengths not supported`)
  }
  return toToken(data, pos, 9, l)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArrayIndefinite (data, pos, _minor, options) {
  if (options.allowIndefinite === false) {
    throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)
  }
  return toToken(data, pos, 1, Infinity)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeArray (writer, token) {
  uint.encodeUintValue(writer, Type.array.majorEncoded, token.value)
}

// using an array as a map key, are you sure about this? we can only sort
// by map length here, it's up to the encoder to decide to look deeper
encodeArray.compareTokens = uint.encodeUint.compareTokens

/**
 * @param {Token} token
 * @returns {number}
 */
encodeArray.encodedSize = function encodedSize (token) {
  return uint.encodeUintValue.encodedSize(token.value)
}
import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import { decodeErrPrefix } from './common.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} prefix
 * @param {number} length
 * @returns {Token}
 */
function toToken (_data, _pos, prefix, length) {
  return new Token(Type.map, length, prefix)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeMapCompact (data, pos, minor, _options) {
  return toToken(data, pos, 1, minor)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer map lengths not supported`)
  }
  return toToken(data, pos, 9, l)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMapIndefinite (data, pos, _minor, options) {
  if (options.allowIndefinite === false) {
    throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)
  }
  return toToken(data, pos, 1, Infinity)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeMap (writer, token) {
  uint.encodeUintValue(writer, Type.map.majorEncoded, token.value)
}

// using a map as a map key, are you sure about this? we can only sort
// by map length here, it's up to the encoder to decide to look deeper
encodeMap.compareTokens = uint.encodeUint.compareTokens

/**
 * @param {Token} token
 * @returns {number}
 */
encodeMap.encodedSize = function encodedSize (token) {
  return uint.encodeUintValue.encodedSize(token.value)
}
import { Token, Type } from './token.js'
import * as uint from './0uint.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeTagCompact (_data, _pos, minor, _options) {
  return new Token(Type.tag, minor, 1)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag8 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint8(data, pos + 1, options), 2)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag16 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint16(data, pos + 1, options), 3)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag32 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint32(data, pos + 1, options), 5)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag64 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint64(data, pos + 1, options), 9)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeTag (writer, token) {
  uint.encodeUintValue(writer, Type.tag.majorEncoded, token.value)
}

encodeTag.compareTokens = uint.encodeUint.compareTokens

/**
 * @param {Token} token
 * @returns {number}
 */
encodeTag.encodedSize = function encodedSize (token) {
  return uint.encodeUintValue.encodedSize(token.value)
}
// TODO: shift some of the bytes logic to bytes-utils so we can use Buffer
// where possible

import { Token, Type } from './token.js'
import { decodeErrPrefix } from './common.js'
import { encodeUint } from './0uint.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 * @typedef {import('../interface.js').EncodeOptions} EncodeOptions
 */

export const MINOR_FALSE = 20
export const MINOR_TRUE = 21
export const MINOR_NULL = 22
export const MINOR_UNDEFINED = 23

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUndefined (_data, _pos, _minor, options) {
  if (options.allowUndefined === false) {
    throw new Error(`${decodeErrPrefix} undefined values are not supported`)
  } else if (options.coerceUndefinedToNull === true) {
    return new Token(Type.null, null, 1)
  }
  return new Token(Type.undefined, undefined, 1)
}

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBreak (_data, _pos, _minor, options) {
  if (options.allowIndefinite === false) {
    throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)
  }
  return new Token(Type.break, undefined, 1)
}

/**
 * @param {number} value
 * @param {number} bytes
 * @param {DecodeOptions} options
 * @returns {Token}
 */
function createToken (value, bytes, options) {
  if (options) {
    if (options.allowNaN === false && Number.isNaN(value)) {
      throw new Error(`${decodeErrPrefix} NaN values are not supported`)
    }
    if (options.allowInfinity === false && (value === Infinity || value === -Infinity)) {
      throw new Error(`${decodeErrPrefix} Infinity values are not supported`)
    }
  }
  return new Token(Type.float, value, bytes)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeFloat16 (data, pos, _minor, options) {
  return createToken(readFloat16(data, pos + 1), 3, options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeFloat32 (data, pos, _minor, options) {
  return createToken(readFloat32(data, pos + 1), 5, options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeFloat64 (data, pos, _minor, options) {
  return createToken(readFloat64(data, pos + 1), 9, options)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 * @param {EncodeOptions} options
 */
export function encodeFloat (writer, token, options) {
  const float = token.value

  if (float === false) {
    writer.push([Type.float.majorEncoded | MINOR_FALSE])
  } else if (float === true) {
    writer.push([Type.float.majorEncoded | MINOR_TRUE])
  } else if (float === null) {
    writer.push([Type.float.majorEncoded | MINOR_NULL])
  } else if (float === undefined) {
    writer.push([Type.float.majorEncoded | MINOR_UNDEFINED])
  } else {
    let decoded
    let success = false
    if (!options || options.float64 !== true) {
      encodeFloat16(float)
      decoded = readFloat16(ui8a, 1)
      if (float === decoded || Number.isNaN(float)) {
        ui8a[0] = 0xf9
        writer.push(ui8a.slice(0, 3))
        success = true
      } else {
        encodeFloat32(float)
        decoded = readFloat32(ui8a, 1)
        if (float === decoded) {
          ui8a[0] = 0xfa
          writer.push(ui8a.slice(0, 5))
          success = true
        }
      }
    }
    if (!success) {
      encodeFloat64(float)
      decoded = readFloat64(ui8a, 1)
      ui8a[0] = 0xfb
      writer.push(ui8a.slice(0, 9))
    }
  }
}

/**
 * @param {Token} token
 * @param {EncodeOptions} options
 * @returns {number}
 */
encodeFloat.encodedSize = function encodedSize (token, options) {
  const float = token.value

  if (float === false || float === true || float === null || float === undefined) {
    return 1
  }

  if (!options || options.float64 !== true) {
    encodeFloat16(float)
    let decoded = readFloat16(ui8a, 1)
    if (float === decoded || Number.isNaN(float)) {
      return 3
    }
    encodeFloat32(float)
    decoded = readFloat32(ui8a, 1)
    if (float === decoded) {
      return 5
    }
  }
  return 9
}

const buffer = new ArrayBuffer(9)
const dataView = new DataView(buffer, 1)
const ui8a = new Uint8Array(buffer, 0)

/**
 * @param {number} inp
 */
function encodeFloat16 (inp) {
  if (inp === Infinity) {
    dataView.setUint16(0, 0x7c00, false)
  } else if (inp === -Infinity) {
    dataView.setUint16(0, 0xfc00, false)
  } else if (Number.isNaN(inp)) {
    dataView.setUint16(0, 0x7e00, false)
  } else {
    dataView.setFloat32(0, inp)
    const valu32 = dataView.getUint32(0)
    const exponent = (valu32 & 0x7f800000) >> 23
    const mantissa = valu32 & 0x7fffff

    if (exponent === 0xff) {
      // too big, Infinity, but this should be hard (impossible?) to trigger
      dataView.setUint16(0, 0x7c00, false)
    } else if (exponent === 0x00) {
      // 0.0, -0.0 and subnormals, shouldn't be possible to get here because 0.0 should be counted as an int
      // Use valu32 for sign bit since bitwise ops on floats lose -0 sign
      dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | (mantissa >> 13), false)
    } else { // standard numbers
      // chunks of logic here borrowed from https://github.com/PJK/libcbor/blob/c78f437182533e3efa8d963ff4b945bb635c2284/src/cbor/encoding.c#L127
      const logicalExponent = exponent - 127
      // Now we know that 2^exponent <= 0 logically
      if (logicalExponent < -24) {
        /* No unambiguous representation exists, this float is not a half float
          and is too small to be represented using a half, round off to zero.
          Consistent with the reference implementation. */
        // should be difficult (impossible?) to get here in JS
        dataView.setUint16(0, 0)
      } else if (logicalExponent < -14) {
        /* Offset the remaining decimal places by shifting the significand, the
          value is lost. This is an implementation decision that works around the
          absence of standard half-float in the language. */
        dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | /* sign bit */ (1 << (24 + logicalExponent)), false)
      } else {
        dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | ((logicalExponent + 15) << 10) | (mantissa >> 13), false)
      }
    }
  }
}

/**
 * @param {Uint8Array} ui8a
 * @param {number} pos
 * @returns {number}
 */
function readFloat16 (ui8a, pos) {
  if (ui8a.length - pos < 2) {
    throw new Error(`${decodeErrPrefix} not enough data for float16`)
  }

  const half = (ui8a[pos] << 8) + ui8a[pos + 1]
  if (half === 0x7c00) {
    return Infinity
  }
  if (half === 0xfc00) {
    return -Infinity
  }
  if (half === 0x7e00) {
    return NaN
  }
  const exp = (half >> 10) & 0x1f
  const mant = half & 0x3ff
  let val
  if (exp === 0) {
    val = mant * (2 ** -24)
  } else if (exp !== 31) {
    val = (mant + 1024) * (2 ** (exp - 25))
  } else {
    // may not be possible to get here
    val = mant === 0 ? Infinity : NaN
  }
  return (half & 0x8000) ? -val : val
}

/**
 * @param {number} inp
 */
function encodeFloat32 (inp) {
  dataView.setFloat32(0, inp, false)
}

/**
 * @param {Uint8Array} ui8a
 * @param {number} pos
 * @returns {number}
 */
function readFloat32 (ui8a, pos) {
  if (ui8a.length - pos < 4) {
    throw new Error(`${decodeErrPrefix} not enough data for float32`)
  }
  const offset = (ui8a.byteOffset || 0) + pos
  return new DataView(ui8a.buffer, offset, 4).getFloat32(0, false)
}

/**
 * @param {number} inp
 */
function encodeFloat64 (inp) {
  dataView.setFloat64(0, inp, false)
}

/**
 * @param {Uint8Array} ui8a
 * @param {number} pos
 * @returns {number}
 */
function readFloat64 (ui8a, pos) {
  if (ui8a.length - pos < 8) {
    throw new Error(`${decodeErrPrefix} not enough data for float64`)
  }
  const offset = (ui8a.byteOffset || 0) + pos
  return new DataView(ui8a.buffer, offset, 8).getFloat64(0, false)
}

/**
 * @param {Token} _tok1
 * @param {Token} _tok2
 * @returns {number}
 */
encodeFloat.compareTokens = encodeUint.compareTokens
/*
encodeFloat.compareTokens = function compareTokens (_tok1, _tok2) {
  return _tok1
  throw new Error(`${encodeErrPrefix} cannot use floats as map keys`)
}
*/
/**
 * Bl is a list of byte chunks, similar to https://github.com/rvagg/bl but for
 * writing rather than reading.
 * A Bl object accepts set() operations for individual bytes and copyTo() for
 * inserting byte arrays. These write operations don't automatically increment
 * the internal cursor so its "length" won't be changed. Instead, increment()
 * must be called to extend its length to cover the inserted data.
 * The toBytes() call will convert all internal memory to a single Uint8Array of
 * the correct length, truncating any data that is stored but hasn't been
 * included by an increment().
 * get() can retrieve a single byte.
 * All operations (except toBytes()) take an "offset" argument that will perform
 * the write at the offset _from the current cursor_. For most operations this
 * will be `0` to write at the current cursor position but it can be ahead of
 * the current cursor. Negative offsets probably work but are untested.
 */

// TODO: ipjs doesn't support this, only for test files: https://github.com/mikeal/ipjs/blob/master/src/package/testFile.js#L39
import { alloc, concat, slice } from './byte-utils.js'

/**
 * @typedef {import('../interface.js').ByteView} ByteView
 * @typedef {import('../interface.js').AllocatedByteView} AllocatedByteView
 */

// the ts-ignores in this file are almost all for the `Uint8Array|number[]` duality that exists
// for perf reasons. Consider better approaches to this or removing it entirely, it is quite
// risky because of some assumptions about small chunks === number[] and everything else === Uint8Array.

const defaultChunkSize = 256

export class Bl {
  /**
   * @param {number} [chunkSize]
   */
  constructor (chunkSize = defaultChunkSize) {
    this.chunkSize = chunkSize
    /** @type {number} */
    this.cursor = 0
    /** @type {number} */
    this.maxCursor = -1
    /** @type {(ByteView|number[])[]} */
    this.chunks = []
    // keep the first chunk around if we can to save allocations for future encodes
    /** @type {ByteView|number[]|null} */
    this._initReuseChunk = null
  }

  reset () {
    this.cursor = 0
    this.maxCursor = -1
    if (this.chunks.length) {
      this.chunks = []
    }
    if (this._initReuseChunk !== null) {
      this.chunks.push(this._initReuseChunk)
      this.maxCursor = this._initReuseChunk.length - 1
    }
  }

  /**
   * @param {ByteView|number[]} bytes
   */
  push (bytes) {
    let topChunk = this.chunks[this.chunks.length - 1]
    const newMax = this.cursor + bytes.length
    if (newMax <= this.maxCursor + 1) {
      // we have at least one chunk and we can fit these bytes into that chunk
      const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1
      // @ts-ignore
      topChunk.set(bytes, chunkPos)
    } else {
      // can't fit it in
      if (topChunk) {
        // trip the last chunk to `cursor` if we need to
        const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1
        if (chunkPos < topChunk.length) {
          // @ts-ignore
          this.chunks[this.chunks.length - 1] = topChunk.subarray(0, chunkPos)
          this.maxCursor = this.cursor - 1
        }
      }
      if (bytes.length < 64 && bytes.length < this.chunkSize) {
        // make a new chunk and copy the new one into it
        topChunk = alloc(this.chunkSize)
        this.chunks.push(topChunk)
        this.maxCursor += topChunk.length
        if (this._initReuseChunk === null) {
          this._initReuseChunk = topChunk
        }
        // @ts-ignore
        topChunk.set(bytes, 0)
      } else {
        // push the new bytes in as its own chunk
        this.chunks.push(bytes)
        this.maxCursor += bytes.length
      }
    }
    this.cursor += bytes.length
  }

  /**
   * @param {boolean} [reset]
   * @returns {AllocatedByteView}
   */
  toBytes (reset = false) {
    let byts
    if (this.chunks.length === 1) {
      const chunk = this.chunks[0]
      if (reset && this.cursor > chunk.length / 2) {
        // @ts-ignore
        byts = this.cursor === chunk.length ? chunk : chunk.subarray(0, this.cursor)
        this._initReuseChunk = null
        this.chunks = []
      } else {
        // @ts-ignore
        byts = slice(chunk, 0, this.cursor)
      }
    } else {
      // @ts-ignore
      byts = concat(this.chunks, this.cursor)
    }
    if (reset) {
      this.reset()
    }
    return byts
  }
}

/**
 * U8Bl is a buffer list that writes directly to a user-provided Uint8Array.
 * It provides the same interface as Bl but writes to a fixed destination.
 * @template {ArrayBufferLike} T
 */
export class U8Bl {
  /**
   * @param {Uint8Array<T>} dest
   */
  constructor (dest) {
    this.dest = dest
    /** @type {number} */
    this.cursor = 0
    // chunks is for interface compatibility with Bl - encode.js checks chunks.length
    // as a sanity check for pre-calculated sizes. For U8Bl this is always [dest].
    /** @type {Array<Uint8Array<T>>} */
    this.chunks = [dest]
  }

  reset () {
    this.cursor = 0
  }

  /**
   * @param {ByteView|number[]} bytes
   */
  push (bytes) {
    if (this.cursor + bytes.length > this.dest.length) {
      throw new Error('write out of bounds, destination buffer is too small')
    }
    this.dest.set(bytes, this.cursor)
    this.cursor += bytes.length
  }

  /**
   * @param {boolean} [reset]
   * @returns {Uint8Array<T>}
   */
  toBytes (reset = false) {
    const byts = this.dest.subarray(0, this.cursor)
    if (reset) {
      this.reset()
    }
    return byts
  }
}
// Use Uint8Array directly in the browser, use Buffer in Node.js but don't
// speak its name directly to avoid bundlers pulling in the `Buffer` polyfill

// @ts-ignore
export const useBuffer = globalThis.process &&
  // @ts-ignore
  !globalThis.process.browser &&
  // @ts-ignore
  globalThis.Buffer &&
  // @ts-ignore
  typeof globalThis.Buffer.isBuffer === 'function'

const textEncoder = new TextEncoder()

/**
 * @typedef {import('../interface.js').ByteView} ByteView
 * @typedef {import('../interface.js').AllocatedByteView} AllocatedByteView
 */

/**
 * @param {Uint8Array} buf
 * @returns {boolean}
 */
function isBuffer (buf) {
  // @ts-ignore
  return useBuffer && globalThis.Buffer.isBuffer(buf)
}

/**
 * @param {ByteView|number[]} buf
 * @returns {ByteView}
 */
export function asU8A (buf) {
  if (!(buf instanceof Uint8Array)) {
    return Uint8Array.from(buf)
  }
  return isBuffer(buf) ? new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength) : buf
}

// Threshold for manual UTF-8 encoding vs native methods.
// Node.js Buffer.from: crossover ~24 chars
// Browser TextEncoder: crossover ~200 chars
const FROM_STRING_THRESHOLD_BUFFER = 24
const FROM_STRING_THRESHOLD_TEXTENCODER = 200

export const fromString = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {string} string
     */
    (string) => {
      return string.length >= FROM_STRING_THRESHOLD_BUFFER
        ? // eslint-disable-line operator-linebreak
      // @ts-ignore
        globalThis.Buffer.from(string)
        : utf8ToBytes(string)
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {string} string
     */
    (string) => {
      return string.length >= FROM_STRING_THRESHOLD_TEXTENCODER ? textEncoder.encode(string) : utf8ToBytes(string)
    }

/**
 * Buffer variant not fast enough for what we need
 * @param {number[]} arr
 * @returns {AllocatedByteView}
 */
export const fromArray = (arr) => {
  return Uint8Array.from(arr)
}

export const slice = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} bytes
     * @param {number} start
     * @param {number} end
     */
    // Buffer.slice() returns a view, not a copy, so we need special handling
    (bytes, start, end) => {
      if (isBuffer(bytes)) {
        return new Uint8Array(bytes.subarray(start, end))
      }
      return bytes.slice(start, end)
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} bytes
     * @param {number} start
     * @param {number} end
     */
    (bytes, start, end) => {
      return bytes.slice(start, end)
    }

export const concat = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {ByteView[]} chunks
     * @param {number} length
     * @returns {AllocatedByteView}
     */
    (chunks, length) => {
      // might get a stray plain Array here
      chunks = chunks.map((c) => c instanceof Uint8Array
        ? c
        : // eslint-disable-line operator-linebreak
        // @ts-ignore
        globalThis.Buffer.from(c))
      // @ts-ignore
      return /** @type {AllocatedByteView} */ (asU8A(globalThis.Buffer.concat(chunks, length)))
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {ByteView[]} chunks
     * @param {number} length
     * @returns {AllocatedByteView}
     */
    (chunks, length) => {
      const out = new Uint8Array(length)
      let off = 0
      for (let b of chunks) {
        if (off + b.length > out.length) {
          // final chunk that's bigger than we need
          b = b.subarray(0, out.length - off)
        }
        out.set(b, off)
        off += b.length
      }
      return out
    }

export const alloc = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {number} size
     * @returns {AllocatedByteView}
     */
    (size) => {
      // we always write over the contents we expose so this should be safe
      // @ts-ignore
      return globalThis.Buffer.allocUnsafe(size)
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {number} size
     * @returns {AllocatedByteView}
     */
    (size) => {
      return new Uint8Array(size)
    }

export const toHex = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} d
     * @returns {string}
     */
    (d) => {
      if (typeof d === 'string') {
        return d
      }
      // @ts-ignore
      return globalThis.Buffer.from(toBytes(d)).toString('hex')
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} d
     * @returns {string}
     */
    (d) => {
      if (typeof d === 'string') {
        return d
      }
      // @ts-ignore not smart enough to figure this out
      return Array.prototype.reduce.call(toBytes(d), (p, c) => `${p}${c.toString(16).padStart(2, '0')}`, '')
    }

export const fromHex = useBuffer
  ? // eslint-disable-line operator-linebreak
  /**
   * @param {string|ByteView} hex
   * @returns {ByteView}
   */
    (hex) => {
      if (hex instanceof Uint8Array) {
        return hex
      }
      // @ts-ignore
      return globalThis.Buffer.from(hex, 'hex')
    }
  : // eslint-disable-line operator-linebreak
  /**
   * @param {string|ByteView} hex
   * @returns {ByteView}
   */
    (hex) => {
      if (hex instanceof Uint8Array) {
        return hex
      }
      if (!hex.length) {
        return new Uint8Array(0)
      }
      return new Uint8Array(hex.split('')
        .map((/** @type {string} */ c, /** @type {number} */ i, /** @type {string[]} */ d) => i % 2 === 0 ? `0x${c}${d[i + 1]}` : '')
        .filter(Boolean)
        .map((/** @type {string} */ e) => parseInt(e, 16)))
    }

/**
 * @param {Uint8Array|ArrayBuffer|ArrayBufferView} obj
 * @returns {Uint8Array}
 */
function toBytes (obj) {
  if (obj instanceof Uint8Array && obj.constructor.name === 'Uint8Array') {
    return obj
  }
  if (obj instanceof ArrayBuffer) {
    return new Uint8Array(obj)
  }
  if (ArrayBuffer.isView(obj)) {
    return new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength)
  }
  throw new Error('Unknown type, must be binary type')
}

/**
 * @param {Uint8Array} b1
 * @param {Uint8Array} b2
 * @returns {number}
 */
export function compare (b1, b2) {
  if (isBuffer(b1) && isBuffer(b2)) {
    // probably not possible to get here in the current API
    // @ts-ignore Buffer
    return b1.compare(b2)
  }
  for (let i = 0; i < b1.length; i++) {
    if (b1[i] === b2[i]) {
      continue
    }
    return b1[i] < b2[i] ? -1 : 1
  }
  return 0
}

// The below code is taken from https://github.com/google/closure-library/blob/8598d87242af59aac233270742c8984e2b2bdbe0/closure/goog/crypt/crypt.js#L117-L143
// Licensed Apache-2.0.

/**
 * @param {string} str
 * @returns {number[]}
 */
function utf8ToBytes (str) {
  const out = []
  let p = 0
  for (let i = 0; i < str.length; i++) {
    let c = str.charCodeAt(i)
    if (c < 128) {
      out[p++] = c
    } else if (c < 2048) {
      out[p++] = (c >> 6) | 192
      out[p++] = (c & 63) | 128
    } else if (
      ((c & 0xFC00) === 0xD800) && (i + 1) < str.length &&
      ((str.charCodeAt(i + 1) & 0xFC00) === 0xDC00)) {
      // Surrogate Pair
      c = 0x10000 + ((c & 0x03FF) << 10) + (str.charCodeAt(++i) & 0x03FF)
      out[p++] = (c >> 18) | 240
      out[p++] = ((c >> 12) & 63) | 128
      out[p++] = ((c >> 6) & 63) | 128
      out[p++] = (c & 63) | 128
    } else {
      if ((c >= 0xD800) && (c <= 0xDFFF)) {
        c = 0xFFFD // Unpaired Surrogate
      }
      out[p++] = (c >> 12) | 224
      out[p++] = ((c >> 6) & 63) | 128
      out[p++] = (c & 63) | 128
    }
  }
  return out
}

// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
const MAX_ARGUMENTS_LENGTH = 0x1000

/**
 * @param {number[]} codePoints
 * @returns {string}
 */
export function decodeCodePointsArray (codePoints) {
  const len = codePoints.length
  if (len <= MAX_ARGUMENTS_LENGTH) {
    return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  }
  // Decode in chunks to avoid "call stack size exceeded".
  let res = ''
  let i = 0
  while (i < len) {
    res += String.fromCharCode.apply(
      String,
      codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
    )
  }
  return res
}
const decodeErrPrefix = 'CBOR decode error:'
const encodeErrPrefix = 'CBOR encode error:'

const uintMinorPrefixBytes = []
uintMinorPrefixBytes[23] = 1
uintMinorPrefixBytes[24] = 2
uintMinorPrefixBytes[25] = 3
uintMinorPrefixBytes[26] = 5
uintMinorPrefixBytes[27] = 9

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} need
 */
function assertEnoughData (data, pos, need) {
  if (data.length - pos < need) {
    throw new Error(`${decodeErrPrefix} not enough data for type`)
  }
}

export {
  decodeErrPrefix,
  encodeErrPrefix,
  uintMinorPrefixBytes,
  assertEnoughData
}
import { decodeErrPrefix } from './common.js'
import { Type } from './token.js'
import { jump, quick } from './jump.js'
import { asU8A } from './byte-utils.js'

/**
 * @typedef {import('./token.js').Token} Token
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 * @typedef {import('../interface.js').DecodeTokenizer} DecodeTokenizer
 * @typedef {import('../interface.js').TagDecodeControl} TagDecodeControl
 */

const defaultDecodeOptions = {
  strict: false,
  allowIndefinite: true,
  allowUndefined: true,
  allowBigInt: true
}

/**
 * @implements {DecodeTokenizer}
 */
class Tokeniser {
  /**
   * @param {Uint8Array} data
   * @param {DecodeOptions} options
   */
  constructor (data, options = {}) {
    this._pos = 0
    this.data = data
    this.options = options
  }

  pos () {
    return this._pos
  }

  done () {
    return this._pos >= this.data.length
  }

  next () {
    const byt = this.data[this._pos]
    let token = quick[byt]
    if (token === undefined) {
      const decoder = jump[byt]
      // if we're here then there's something wrong with our jump or quick lists!
      if (!decoder) {
        throw new Error(`${decodeErrPrefix} no decoder for major type ${byt >>> 5} (byte 0x${byt.toString(16).padStart(2, '0')})`)
      }
      const minor = byt & 31
      token = decoder(this.data, this._pos, minor, this.options)
    }
    // @ts-ignore we get to assume encodedLength is set (crossing fingers slightly)
    this._pos += token.encodedLength
    return token
  }
}

const DONE = Symbol.for('DONE')
const BREAK = Symbol.for('BREAK')

/**
 * @param {Token} token
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {any|BREAK|DONE}
 */
function tokenToArray (token, tokeniser, options) {
  const arr = []
  for (let i = 0; i < token.value; i++) {
    const value = tokensToObject(tokeniser, options)
    if (value === BREAK) {
      if (token.value === Infinity) {
        // normal end to indefinite length array
        break
      }
      throw new Error(`${decodeErrPrefix} got unexpected break to lengthed array`)
    }
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} found array but not enough entries (got ${i}, expected ${token.value})`)
    }
    arr[i] = value
  }
  return arr
}

/**
 * @param {Token} token
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {any|BREAK|DONE}
 */
function tokenToMap (token, tokeniser, options) {
  const useMaps = options.useMaps === true
  const rejectDuplicateMapKeys = options.rejectDuplicateMapKeys === true
  const obj = useMaps ? undefined : {}
  const m = useMaps ? new Map() : undefined
  for (let i = 0; i < token.value; i++) {
    const key = tokensToObject(tokeniser, options)
    if (key === BREAK) {
      if (token.value === Infinity) {
        // normal end to indefinite length map
        break
      }
      throw new Error(`${decodeErrPrefix} got unexpected break to lengthed map`)
    }
    if (key === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no key], expected ${token.value})`)
    }
    if (!useMaps && typeof key !== 'string') {
      throw new Error(`${decodeErrPrefix} non-string keys not supported (got ${typeof key})`)
    }
    if (rejectDuplicateMapKeys) {
      // @ts-ignore
      if ((useMaps && m.has(key)) || (!useMaps && Object.hasOwn(obj, key))) {
        throw new Error(`${decodeErrPrefix} found repeat map key "${key}"`)
      }
    }
    const value = tokensToObject(tokeniser, options)
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no value], expected ${token.value})`)
    }
    if (useMaps) {
      // @ts-ignore TODO reconsider this .. maybe needs to be strict about key types
      m.set(key, value)
    } else {
      // @ts-ignore TODO reconsider this .. maybe needs to be strict about key types
      obj[key] = value
    }
  }
  // @ts-ignore c'mon man
  return useMaps ? m : obj
}

/**
 * Generator that yields [key, value] entries from a CBOR map token.
 * Used by tag decoders that need to preserve key types (e.g., Tag 259 Map).
 * @param {Token} token - The map token
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {Generator<[any, any], void, unknown>}
 */
function * tokenToMapEntries (token, tokeniser, options) {
  for (let i = 0; i < token.value; i++) {
    const key = tokensToObject(tokeniser, options)
    if (key === BREAK) {
      if (token.value === Infinity) {
        // normal end to indefinite length map
        break
      }
      throw new Error(`${decodeErrPrefix} got unexpected break to lengthed map`)
    }
    if (key === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no key], expected ${token.value})`)
    }
    const value = tokensToObject(tokeniser, options)
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no value], expected ${token.value})`)
    }
    yield [key, value]
  }
}

/**
 * Creates a TagDecodeControl object for tag decoders.
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {TagDecodeControl}
 */
function createTagDecodeControl (tokeniser, options) {
  let called = false

  /**
   * @type {TagDecodeControl}
   */
  const decode = function () {
    if (called) {
      throw new Error(`${decodeErrPrefix} tag decode() may only be called once`)
    }
    called = true
    const value = tokensToObject(tokeniser, options)
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} tag content missing`)
    }
    if (value === BREAK) {
      throw new Error(`${decodeErrPrefix} got unexpected break in tag content`)
    }
    return value
  }

  decode.entries = function () {
    if (called) {
      throw new Error(`${decodeErrPrefix} tag decode() may only be called once`)
    }
    called = true

    // Get the next token and ensure it's a map
    const token = tokeniser.next()
    if (!Type.equals(token.type, Type.map)) {
      throw new Error(`${decodeErrPrefix} entries() requires map content, got ${token.type.name}`)
    }

    // Collect all entries into an array (ensures full content consumption)
    const entries = []
    for (const entry of tokenToMapEntries(token, tokeniser, options)) {
      entries.push(entry)
    }
    return entries
  }

  // For internal tracking
  Object.defineProperty(decode, '_called', {
    get () { return called },
    enumerable: false
  })

  return decode
}

/**
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {any|BREAK|DONE}
 */
function tokensToObject (tokeniser, options) {
  // should we support array as an argument?
  // check for tokenIter[Symbol.iterator] and replace tokenIter with what that returns?
  if (tokeniser.done()) {
    return DONE
  }

  const token = tokeniser.next()

  if (Type.equals(token.type, Type.break)) {
    return BREAK
  }

  if (token.type.terminal) {
    return token.value
  }

  if (Type.equals(token.type, Type.array)) {
    return tokenToArray(token, tokeniser, options)
  }

  if (Type.equals(token.type, Type.map)) {
    return tokenToMap(token, tokeniser, options)
  }

  if (Type.equals(token.type, Type.tag)) {
    if (options.tags && typeof options.tags[token.value] === 'function') {
      const decodeControl = createTagDecodeControl(tokeniser, options)
      const result = options.tags[token.value](decodeControl)
      if (!decodeControl._called) {
        throw new Error(`${decodeErrPrefix} tag decoder must call decode() or entries()`)
      }
      return result
    }
    throw new Error(`${decodeErrPrefix} tag not supported (${token.value})`)
  }
  throw new Error('unsupported')
}

/**
 * @param {Uint8Array} data
 * @param {DecodeOptions} [options]
 * @returns {[any, Uint8Array]}
 */
function decodeFirst (data, options) {
  if (!(data instanceof Uint8Array)) {
    throw new Error(`${decodeErrPrefix} data to decode must be a Uint8Array`)
  }
  options = Object.assign({}, defaultDecodeOptions, options)
  // Convert Buffer to plain Uint8Array for faster slicing in decode path
  const u8aData = asU8A(data)
  const tokeniser = options.tokenizer || new Tokeniser(u8aData, options)
  const decoded = tokensToObject(tokeniser, options)
  if (decoded === DONE) {
    throw new Error(`${decodeErrPrefix} did not find any content to decode`)
  }
  if (decoded === BREAK) {
    throw new Error(`${decodeErrPrefix} got unexpected break`)
  }
  return [decoded, data.subarray(tokeniser.pos())]
}

/**
 * @param {Uint8Array} data
 * @param {DecodeOptions} [options]
 * @returns {any}
 */
function decode (data, options) {
  const [decoded, remainder] = decodeFirst(data, options)
  if (remainder.length > 0) {
    throw new Error(`${decodeErrPrefix} too many terminals, data makes no sense`)
  }
  return decoded
}

export { Tokeniser, tokensToObject, decode, decodeFirst }
import { is } from './is.js'
import { Token, Type } from './token.js'
import { Bl, U8Bl } from './bl.js'
import { encodeErrPrefix } from './common.js'
import { quickEncodeToken } from './jump.js'
import { asU8A, compare, fromString } from './byte-utils.js'

import { encodeUint, encodeUintValue } from './0uint.js'
import { encodeNegint } from './1negint.js'
import { encodeBytes } from './2bytes.js'
import { encodeString } from './3string.js'
import { encodeArray } from './4array.js'
import { encodeMap } from './5map.js'
import { encodeTag } from './6tag.js'
import { encodeFloat, MINOR_FALSE, MINOR_TRUE, MINOR_NULL, MINOR_UNDEFINED } from './7float.js'

/**
 * @typedef {import('../interface.js').EncodeOptions} EncodeOptions
 * @typedef {import('../interface.js').OptionalTypeEncoder} OptionalTypeEncoder
 * @typedef {import('../interface.js').Reference} Reference
 * @typedef {import('../interface.js').StrictTypeEncoder} StrictTypeEncoder
 * @typedef {import('../interface.js').TokenTypeEncoder} TokenTypeEncoder
 * @typedef {import('../interface.js').TokenOrNestedTokens} TokenOrNestedTokens
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').ByteView} ByteView
 * @typedef {import('../interface.js').AllocatedByteView} AllocatedByteView
 */

/** @type {EncodeOptions} */
const defaultEncodeOptions = {
  float64: false,
  mapSorter,
  quickEncodeToken
}

/** @type {EncodeOptions} */
export const rfc8949EncodeOptions = Object.freeze({
  mapSorter: rfc8949MapSorter,
  quickEncodeToken
})

/** @returns {TokenTypeEncoder[]} */
export function makeCborEncoders () {
  const encoders = []
  encoders[Type.uint.major] = encodeUint
  encoders[Type.negint.major] = encodeNegint
  encoders[Type.bytes.major] = encodeBytes
  encoders[Type.string.major] = encodeString
  encoders[Type.array.major] = encodeArray
  encoders[Type.map.major] = encodeMap
  encoders[Type.tag.major] = encodeTag
  encoders[Type.float.major] = encodeFloat
  return encoders
}

const cborEncoders = makeCborEncoders()

const defaultWriter = new Bl()

/** @implements {Reference} */
class Ref {
  /**
   * @param {object|any[]} obj
   * @param {Reference|undefined} parent
   */
  constructor (obj, parent) {
    this.obj = obj
    this.parent = parent
  }

  /**
   * @param {object|any[]} obj
   * @returns {boolean}
   */
  includes (obj) {
    /** @type {Reference|undefined} */
    let p = this
    do {
      if (p.obj === obj) {
        return true
      }
    } while (p = p.parent) // eslint-disable-line
    return false
  }

  /**
   * @param {Reference|undefined} stack
   * @param {object|any[]} obj
   * @returns {Reference}
   */
  static createCheck (stack, obj) {
    if (stack && stack.includes(obj)) {
      throw new Error(`${encodeErrPrefix} object contains circular references`)
    }
    return new Ref(obj, stack)
  }
}

const simpleTokens = {
  null: new Token(Type.null, null),
  undefined: new Token(Type.undefined, undefined),
  true: new Token(Type.true, true),
  false: new Token(Type.false, false),
  emptyArray: new Token(Type.array, 0),
  emptyMap: new Token(Type.map, 0)
}

/** @type {{[typeName: string]: StrictTypeEncoder}} */
const typeEncoders = {
  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  number (obj, _typ, _options, _refStack) {
    if (!Number.isInteger(obj) || !Number.isSafeInteger(obj)) {
      return new Token(Type.float, obj)
    } else if (obj >= 0) {
      return new Token(Type.uint, obj)
    } else {
      return new Token(Type.negint, obj)
    }
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  bigint (obj, _typ, _options, _refStack) {
    if (obj >= BigInt(0)) {
      return new Token(Type.uint, obj)
    } else {
      return new Token(Type.negint, obj)
    }
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  Uint8Array (obj, _typ, _options, _refStack) {
    return new Token(Type.bytes, obj)
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  string (obj, _typ, _options, _refStack) {
    return new Token(Type.string, obj)
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  boolean (obj, _typ, _options, _refStack) {
    return obj ? simpleTokens.true : simpleTokens.false
  },

  /**
   * @param {any} _obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  null (_obj, _typ, _options, _refStack) {
    return simpleTokens.null
  },

  /**
   * @param {any} _obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  undefined (_obj, _typ, _options, _refStack) {
    return simpleTokens.undefined
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  ArrayBuffer (obj, _typ, _options, _refStack) {
    return new Token(Type.bytes, new Uint8Array(obj))
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  DataView (obj, _typ, _options, _refStack) {
    return new Token(Type.bytes, new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength))
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} options
   * @param {Reference} [refStack]
   * @returns {TokenOrNestedTokens}
   */
  Array (obj, _typ, options, refStack) {
    if (!obj.length) {
      if (options.addBreakTokens === true) {
        return [simpleTokens.emptyArray, new Token(Type.break)]
      }
      return simpleTokens.emptyArray
    }
    refStack = Ref.createCheck(refStack, obj)
    const entries = []
    let i = 0
    for (const e of obj) {
      entries[i++] = objectToTokens(e, options, refStack)
    }
    if (options.addBreakTokens) {
      return [new Token(Type.array, obj.length), entries, new Token(Type.break)]
    }
    return [new Token(Type.array, obj.length), entries]
  },

  /**
   * @param {any} obj
   * @param {string} typ
   * @param {EncodeOptions} options
   * @param {Reference} [refStack]
   * @returns {TokenOrNestedTokens}
   */
  Object (obj, typ, options, refStack) {
    // could be an Object or a Map
    const isMap = typ !== 'Object'
    // it's slightly quicker to use Object.keys() than Object.entries()
    const keys = isMap ? obj.keys() : Object.keys(obj)
    const maxLength = isMap ? obj.size : keys.length

    /** @type {undefined | [TokenOrNestedTokens, TokenOrNestedTokens][]} */
    let entries

    if (maxLength) {
      // Pre-allocate the array with the expected size
      entries = new Array(maxLength)
      refStack = Ref.createCheck(refStack, obj)
      const skipUndefined = !isMap && options.ignoreUndefinedProperties

      let i = 0
      for (const key of keys) {
        const value = isMap ? obj.get(key) : obj[key]
        if (skipUndefined && value === undefined) {
          continue
        }
        entries[i++] = [
          objectToTokens(key, options, refStack),
          objectToTokens(value, options, refStack)
        ]
      }

      // Truncate only if properties were skipped
      if (i < maxLength) {
        entries.length = i
      }
    }

    if (!entries?.length) {
      if (options.addBreakTokens === true) {
        return [simpleTokens.emptyMap, new Token(Type.break)]
      }
      return simpleTokens.emptyMap
    }

    sortMapEntries(entries, options)
    if (options.addBreakTokens) {
      return [new Token(Type.map, entries.length), entries, new Token(Type.break)]
    }
    return [new Token(Type.map, entries.length), entries]
  },

  /**
   * Encode a `Tagged` wrapper as a CBOR tag header followed by the encoded
   * form of the wrapped value. The value is recursively tokenised through
   * `objectToTokens()` so any registered `typeEncoders` apply to it.
   *
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} options
   * @param {Reference} [refStack]
   * @returns {TokenOrNestedTokens}
   */
  Tagged (obj, _typ, options, refStack) {
    return [
      new Token(Type.tag, obj.tag),
      objectToTokens(obj.value, options, refStack)
    ]
  }
}

typeEncoders.Map = typeEncoders.Object
typeEncoders.Buffer = typeEncoders.Uint8Array
for (const typ of 'Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64'.split(' ')) {
  typeEncoders[`${typ}Array`] = typeEncoders.DataView
}

/**
 * @param {any} obj
 * @param {EncodeOptions} [options]
 * @param {Reference} [refStack]
 * @returns {TokenOrNestedTokens}
 */
function objectToTokens (obj, options = {}, refStack) {
  const typ = is(obj)
  const customTypeEncoder = (options && options.typeEncoders && /** @type {OptionalTypeEncoder} */ options.typeEncoders[typ]) || typeEncoders[typ]
  if (typeof customTypeEncoder === 'function') {
    const tokens = customTypeEncoder(obj, typ, options, refStack)
    if (tokens != null) {
      return tokens
    }
  }
  const typeEncoder = typeEncoders[typ]
  if (!typeEncoder) {
    throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`)
  }
  return typeEncoder(obj, typ, options, refStack)
}

/*
CBOR key sorting is a mess.

The canonicalisation recommendation from https://tools.ietf.org/html/rfc7049#section-3.9
includes the wording:

> The keys in every map must be sorted lowest value to highest.
> Sorting is performed on the bytes of the representation of the key
> data items without paying attention to the 3/5 bit splitting for
> major types.
> ...
>  *  If two keys have different lengths, the shorter one sorts
      earlier;
>  *  If two keys have the same length, the one with the lower value
      in (byte-wise) lexical order sorts earlier.

1. It is not clear what "bytes of the representation of the key" means: is it
   the CBOR representation, or the binary representation of the object itself?
   Consider the int and uint difference here.
2. It is not clear what "without paying attention to" means: do we include it
   and compare on that? Or do we omit the special prefix byte, (mostly) treating
   the key in its plain binary representation form.

The FIDO 2.0: Client To Authenticator Protocol spec takes the original CBOR
wording and clarifies it according to their understanding.
https://fidoalliance.org/specs/fido-v2.0-rd-20170927/fido-client-to-authenticator-protocol-v2.0-rd-20170927.html#message-encoding

> The keys in every map must be sorted lowest value to highest. Sorting is
> performed on the bytes of the representation of the key data items without
> paying attention to the 3/5 bit splitting for major types. The sorting rules
> are:
>  * If the major types are different, the one with the lower value in numerical
>    order sorts earlier.
>  * If two keys have different lengths, the shorter one sorts earlier;
>  * If two keys have the same length, the one with the lower value in
>    (byte-wise) lexical order sorts earlier.

Some other implementations, such as borc, do a full encode then do a
length-first, byte-wise-second comparison:
https://github.com/dignifiedquire/borc/blob/b6bae8b0bcde7c3976b0f0f0957208095c392a36/src/encoder.js#L358
https://github.com/dignifiedquire/borc/blob/b6bae8b0bcde7c3976b0f0f0957208095c392a36/src/utils.js#L143-L151

This has the benefit of being able to easily handle arbitrary keys, including
complex types (maps and arrays).

We'll opt for the FIDO approach, since it affords some efficies since we don't
need a full encode of each key to determine order and can defer to the types
to determine how to most efficiently order their values (i.e. int and uint
ordering can be done on the numbers, no need for byte-wise, for example).

Recommendation: stick to single key types or you'll get into trouble, and prefer
string keys because it's much simpler that way.
*/

/**
 * @param {TokenOrNestedTokens[]} entries
 * @param {EncodeOptions} options
 */
function sortMapEntries (entries, options) {
  if (options.mapSorter) {
    entries.sort(options.mapSorter)
  }
}

/**
 * @param {(Token|Token[])[]} e1
 * @param {(Token|Token[])[]} e2
 * @returns {number}
 */
function mapSorter (e1, e2) {
  // the key position ([0]) could have a single token or an array
  // almost always it'll be a single token but complex key might get involved
  const keyToken1 = Array.isArray(e1[0]) ? e1[0][0] : e1[0]
  const keyToken2 = Array.isArray(e2[0]) ? e2[0][0] : e2[0]

  // different key types
  if (keyToken1.type !== keyToken2.type) {
    return keyToken1.type.compare(keyToken2.type)
  }

  const major = keyToken1.type.major
  // TODO: handle case where cmp === 0 but there are more keyToken e. complex type)
  const tcmp = cborEncoders[major].compareTokens(keyToken1, keyToken2)
  if (tcmp === 0) {
    // duplicate key or complex type where the first token matched,
    // i.e. a map or array and we're only comparing the opening token
    console.warn('WARNING: complex key types used, CBOR key sorting guarantees are gone')
  }
  return tcmp
}

/**
 * @typedef {Token & { _keyBytes?: AllocatedByteView }} TokenEx
 *
 * @param {(Token|Token[])[]} e1
 * @param {(Token|Token[])[]} e2
 * @returns {number}
 */
function rfc8949MapSorter (e1, e2) {
  if (e1[0] instanceof Token && e2[0] instanceof Token) {
    const t1 = /** @type {TokenEx} */ (e1[0])
    const t2 = /** @type {TokenEx} */ (e2[0])

    if (!t1._keyBytes) {
      t1._keyBytes = encodeRfc8949(t1.value)
    }

    if (!t2._keyBytes) {
      t2._keyBytes = encodeRfc8949(t2.value)
    }

    return compare(t1._keyBytes, t2._keyBytes)
  }

  throw new Error('rfc8949MapSorter: complex key types are not supported yet')
}

/**
 * @param {any} data
 * @returns {AllocatedByteView}
 */
function encodeRfc8949 (data) {
  return encodeCustom(data, cborEncoders, rfc8949EncodeOptions)
}

/**
 * @param {ByteWriter} writer
 * @param {TokenOrNestedTokens} tokens
 * @param {TokenTypeEncoder[]} encoders
 * @param {EncodeOptions} options
 */
function tokensToEncoded (writer, tokens, encoders, options) {
  if (Array.isArray(tokens)) {
    for (const token of tokens) {
      tokensToEncoded(writer, token, encoders, options)
    }
  } else {
    encoders[tokens.type.major](writer, tokens, options)
  }
}

// CBOR major type prefixes, cached from Type for hot path performance
const MAJOR_UINT = Type.uint.majorEncoded
const MAJOR_NEGINT = Type.negint.majorEncoded
const MAJOR_BYTES = Type.bytes.majorEncoded
const MAJOR_STRING = Type.string.majorEncoded
const MAJOR_ARRAY = Type.array.majorEncoded

// Simple value bytes (CBOR major type 7 + minor value)
const SIMPLE_FALSE = Type.float.majorEncoded | MINOR_FALSE
const SIMPLE_TRUE = Type.float.majorEncoded | MINOR_TRUE
const SIMPLE_NULL = Type.float.majorEncoded | MINOR_NULL
const SIMPLE_UNDEFINED = Type.float.majorEncoded | MINOR_UNDEFINED

const neg1b = BigInt(-1)
const pos1b = BigInt(1)

/**
 * Check if direct encoding can be used for the given options.
 * Direct encoding bypasses token creation for most values.
 * @param {EncodeOptions} options
 * @returns {boolean}
 */
function canDirectEncode (options) {
  // Cannot use direct encode with addBreakTokens (needs special break token handling).
  // Direct encode checks typeEncoders per-value, falling back to tokens as needed.
  // Maps fall back to token-based encoding for efficient key sorting.
  return options.addBreakTokens !== true
}

/**
 * Direct encode a value to the writer, bypassing token creation for most types.
 * Falls back to token-based encoding for custom type encoders.
 * @param {ByteWriter} writer
 * @param {any} data
 * @param {EncodeOptions} options
 * @param {Reference|undefined} refStack
 */
function directEncode (writer, data, options, refStack) {
  const typ = is(data)

  // Check for custom encoder for THIS specific type
  const customEncoder = options.typeEncoders && options.typeEncoders[typ]
  if (customEncoder) {
    const tokens = customEncoder(data, typ, options, refStack)
    if (tokens != null) {
      // Custom encoder returned tokens, serialize immediately
      tokensToEncoded(writer, tokens, cborEncoders, options)
      return
    }
    // Custom encoder returned null, fall through to default handling
  }

  // Direct encode based on type
  switch (typ) {
    case 'null':
      writer.push([SIMPLE_NULL])
      return

    case 'undefined':
      writer.push([SIMPLE_UNDEFINED])
      return

    case 'boolean':
      writer.push([data ? SIMPLE_TRUE : SIMPLE_FALSE])
      return

    case 'number':
      if (!Number.isInteger(data) || !Number.isSafeInteger(data)) {
        // Float, use token encoder for complex float encoding
        encodeFloat(writer, new Token(Type.float, data), options)
      } else if (data >= 0) {
        encodeUintValue(writer, MAJOR_UINT, data)
      } else {
        // Negative integer
        encodeUintValue(writer, MAJOR_NEGINT, data * -1 - 1)
      }
      return

    case 'bigint':
      if (data >= BigInt(0)) {
        encodeUintValue(writer, MAJOR_UINT, data)
      } else {
        encodeUintValue(writer, MAJOR_NEGINT, data * neg1b - pos1b)
      }
      return

    case 'string': {
      const bytes = fromString(data)
      encodeUintValue(writer, MAJOR_STRING, bytes.length)
      writer.push(bytes)
      return
    }

    case 'Uint8Array':
      encodeUintValue(writer, MAJOR_BYTES, data.length)
      writer.push(data)
      return

    case 'Array':
      if (!data.length) {
        writer.push([MAJOR_ARRAY]) // Empty array: 0x80
        return
      }
      refStack = Ref.createCheck(refStack, data)
      encodeUintValue(writer, MAJOR_ARRAY, data.length)
      for (const elem of data) {
        directEncode(writer, elem, options, refStack)
      }
      return

    case 'Object':
    case 'Map':
      // Maps require key sorting, use token-based encoding for efficiency
      // (pre-encoding all keys for sorting is expensive)
      {
        const tokens = typeEncoders.Object(data, typ, options, refStack)
        tokensToEncoded(writer, tokens, cborEncoders, options)
      }
      return

    default:
    // Fall back to token-based encoding for other types (DataView, TypedArrays, etc.)
    {
      const typeEncoder = typeEncoders[typ]
      if (!typeEncoder) {
        throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`)
      }
      const tokens = typeEncoder(data, typ, options, refStack)
      tokensToEncoded(writer, tokens, cborEncoders, options)
    }
  }
}

/**
 * @template {ArrayBufferLike} T
 * @overload
 * @param {any} data
 * @param {TokenTypeEncoder[]} encoders
 * @param {EncodeOptions} options
 * @param {Uint8Array<T>} destination
 * @returns {Uint8Array<T>}
 */
/**
 * @overload
 * @param {any} data
 * @param {TokenTypeEncoder[]} encoders
 * @param {EncodeOptions} options
 * @returns {AllocatedByteView}
 */
/**
 * @param {any} data
 * @param {TokenTypeEncoder[]} encoders
 * @param {EncodeOptions} options
 * @param {ByteView} [destination]
 * @returns {ByteView}
 */
function encodeCustom (data, encoders, options, destination) {
  // arg ordering is different to encodeInto for backward compatibility
  const hasDest = destination instanceof Uint8Array
  let writeTo = hasDest ? new U8Bl(destination) : defaultWriter

  const tokens = objectToTokens(data, options)
  if (!Array.isArray(tokens) && options.quickEncodeToken) {
    const quickBytes = options.quickEncodeToken(tokens)
    if (quickBytes) {
      if (hasDest) {
        // Copy quick bytes into destination buffer
        writeTo.push(quickBytes)
        return writeTo.toBytes()
      }
      return quickBytes
    }
    const encoder = encoders[tokens.type.major]
    if (encoder.encodedSize) {
      const size = encoder.encodedSize(tokens, options)
      if (!hasDest) {
        writeTo = new Bl(size)
      }
      encoder(writeTo, tokens, options)
      // this would be a problem with encodedSize() functions
      if (writeTo.chunks.length !== 1) {
        throw new Error(`Unexpected error: pre-calculated length for ${tokens} was wrong`)
      }
      return hasDest ? writeTo.toBytes() : asU8A(writeTo.chunks[0])
    }
  }
  writeTo.reset()
  tokensToEncoded(writeTo, tokens, encoders, options)
  return writeTo.toBytes(true)
}

/**
 * @param {any} data
 * @param {EncodeOptions} [options]
 * @returns {AllocatedByteView}
 */
function encode (data, options) {
  options = Object.assign({}, defaultEncodeOptions, options)

  // Use direct encode path when possible
  if (canDirectEncode(options)) {
    defaultWriter.reset()
    directEncode(defaultWriter, data, options, undefined)
    return defaultWriter.toBytes(true)
  }

  return encodeCustom(data, cborEncoders, options)
}

/**
 * @template {ArrayBufferLike} T
 * @param {any} data
 * @param {Uint8Array<T>} destination
 * @param {EncodeOptions} [options]
 * @returns {{ written: number }}
 */
function encodeInto (data, destination, options) {
  options = Object.assign({}, defaultEncodeOptions, options)

  // Use direct encode path when possible
  if (canDirectEncode(options)) {
    const writer = new U8Bl(destination)
    directEncode(writer, data, options, undefined)
    return { written: writer.toBytes().length }
  }

  const result = encodeCustom(data, cborEncoders, options, destination)
  return { written: result.length }
}

export { objectToTokens, encode, encodeCustom, encodeInto, Ref }
// This is an unfortunate replacement for @sindresorhus/is that we need to
// re-implement for performance purposes. In particular the is.observable()
// check is expensive, and unnecessary for our purposes. The values returned
// are compatible with @sindresorhus/is, however.

// Types that reach getObjectType() - excludes types with fast-paths above:
// primitives (typeof), Array (isArray), Uint8Array (instanceof), plain Object (constructor)
const objectTypeNames = [
  'Object', // for Object.create(null) and other non-plain objects
  'RegExp',
  'Date',
  'Error',
  'Map',
  'Set',
  'WeakMap',
  'WeakSet',
  'ArrayBuffer',
  'SharedArrayBuffer',
  'DataView',
  'Promise',
  'URL',
  'HTMLElement',
  'Int8Array',
  'Uint8ClampedArray',
  'Int16Array',
  'Uint16Array',
  'Int32Array',
  'Uint32Array',
  'Float32Array',
  'Float64Array',
  'BigInt64Array',
  'BigUint64Array',
  'Tagged'
]

/**
 * @param {any} value
 * @returns {string}
 */
export function is (value) {
  if (value === null) {
    return 'null'
  }
  if (value === undefined) {
    return 'undefined'
  }
  if (value === true || value === false) {
    return 'boolean'
  }
  const typeOf = typeof value
  if (typeOf === 'string' || typeOf === 'number' || typeOf === 'bigint' || typeOf === 'symbol') {
    return typeOf
  }
  if (typeOf === 'function') {
    return 'Function'
  }
  if (Array.isArray(value)) {
    return 'Array'
  }
  // Also catches Node.js Buffer which extends Uint8Array
  if (value instanceof Uint8Array) {
    return 'Uint8Array'
  }
  // Fast path for plain objects (most common case after primitives/arrays/bytes)
  if (value.constructor === Object) {
    return 'Object'
  }
  const objectType = getObjectType(value)
  if (objectType) {
    return objectType
  }
  return 'Object'
}

/**
 * @param {any} value
 * @returns {string|undefined}
 */
function getObjectType (value) {
  const objectTypeName = Object.prototype.toString.call(value).slice(8, -1)
  if (objectTypeNames.includes(objectTypeName)) {
    return objectTypeName
  }
  return undefined
}
import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import * as negint from './1negint.js'
import * as bytes from './2bytes.js'
import * as string from './3string.js'
import * as array from './4array.js'
import * as map from './5map.js'
import * as tag from './6tag.js'
import * as float from './7float.js'
import { decodeErrPrefix } from './common.js'
import { fromArray } from './byte-utils.js'

/**
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 * @typedef {import('../interface.js').AllocatedByteView} AllocatedByteView
 */

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 */
function invalidMinor (data, pos, minor) {
  throw new Error(`${decodeErrPrefix} encountered invalid minor (${minor}) for major ${data[pos] >>> 5}`)
}

/**
 * @param {string} msg
 * @returns {()=>any}
 */
function errorer (msg) {
  return () => { throw new Error(`${decodeErrPrefix} ${msg}`) }
}

/** @type {((data:Uint8Array, pos:number, minor:number, options?:DecodeOptions) => any)[]} */
export const jump = []

// unsigned integer, 0x00..0x17 (0..23)
for (let i = 0; i <= 0x17; i++) {
  jump[i] = invalidMinor // uint.decodeUintCompact, handled by quick[]
}
jump[0x18] = uint.decodeUint8 // unsigned integer, one-byte uint8_t follows
jump[0x19] = uint.decodeUint16 // unsigned integer, two-byte uint16_t follows
jump[0x1a] = uint.decodeUint32 // unsigned integer, four-byte uint32_t follows
jump[0x1b] = uint.decodeUint64 // unsigned integer, eight-byte uint64_t follows
jump[0x1c] = invalidMinor
jump[0x1d] = invalidMinor
jump[0x1e] = invalidMinor
jump[0x1f] = invalidMinor
// negative integer, -1-0x00..-1-0x17 (-1..-24)
for (let i = 0x20; i <= 0x37; i++) {
  jump[i] = invalidMinor // negintDecode, handled by quick[]
}
jump[0x38] = negint.decodeNegint8 // negative integer, -1-n one-byte uint8_t for n follows
jump[0x39] = negint.decodeNegint16 // negative integer, -1-n two-byte uint16_t for n follows
jump[0x3a] = negint.decodeNegint32 // negative integer, -1-n four-byte uint32_t for follows
jump[0x3b] = negint.decodeNegint64 // negative integer, -1-n eight-byte uint64_t for follows
jump[0x3c] = invalidMinor
jump[0x3d] = invalidMinor
jump[0x3e] = invalidMinor
jump[0x3f] = invalidMinor
// byte string, 0x00..0x17 bytes follow
for (let i = 0x40; i <= 0x57; i++) {
  jump[i] = bytes.decodeBytesCompact
}
jump[0x58] = bytes.decodeBytes8 // byte string, one-byte uint8_t for n, and then n bytes follow
jump[0x59] = bytes.decodeBytes16 // byte string, two-byte uint16_t for n, and then n bytes follow
jump[0x5a] = bytes.decodeBytes32 // byte string, four-byte uint32_t for n, and then n bytes follow
jump[0x5b] = bytes.decodeBytes64 // byte string, eight-byte uint64_t for n, and then n bytes follow
jump[0x5c] = invalidMinor
jump[0x5d] = invalidMinor
jump[0x5e] = invalidMinor
jump[0x5f] = errorer('indefinite length bytes/strings are not supported') // byte string, byte strings follow, terminated by "break"
// UTF-8 string 0x00..0x17 bytes follow
for (let i = 0x60; i <= 0x77; i++) {
  jump[i] = string.decodeStringCompact
}
jump[0x78] = string.decodeString8 // UTF-8 string, one-byte uint8_t for n, and then n bytes follow
jump[0x79] = string.decodeString16 // UTF-8 string, two-byte uint16_t for n, and then n bytes follow
jump[0x7a] = string.decodeString32 // UTF-8 string, four-byte uint32_t for n, and then n bytes follow
jump[0x7b] = string.decodeString64 // UTF-8 string, eight-byte uint64_t for n, and then n bytes follow
jump[0x7c] = invalidMinor
jump[0x7d] = invalidMinor
jump[0x7e] = invalidMinor
jump[0x7f] = errorer('indefinite length bytes/strings are not supported') // UTF-8 strings follow, terminated by "break"
// array, 0x00..0x17 data items follow
for (let i = 0x80; i <= 0x97; i++) {
  jump[i] = array.decodeArrayCompact
}
jump[0x98] = array.decodeArray8 // array, one-byte uint8_t for n, and then n data items follow
jump[0x99] = array.decodeArray16 // array, two-byte uint16_t for n, and then n data items follow
jump[0x9a] = array.decodeArray32 // array, four-byte uint32_t for n, and then n data items follow
jump[0x9b] = array.decodeArray64 // array, eight-byte uint64_t for n, and then n data items follow
jump[0x9c] = invalidMinor
jump[0x9d] = invalidMinor
jump[0x9e] = invalidMinor
jump[0x9f] = array.decodeArrayIndefinite // array, data items follow, terminated by "break"
// map, 0x00..0x17 pairs of data items follow
for (let i = 0xa0; i <= 0xb7; i++) {
  jump[i] = map.decodeMapCompact
}
jump[0xb8] = map.decodeMap8 // map, one-byte uint8_t for n, and then n pairs of data items follow
jump[0xb9] = map.decodeMap16 // map, two-byte uint16_t for n, and then n pairs of data items follow
jump[0xba] = map.decodeMap32 // map, four-byte uint32_t for n, and then n pairs of data items follow
jump[0xbb] = map.decodeMap64 // map, eight-byte uint64_t for n, and then n pairs of data items follow
jump[0xbc] = invalidMinor
jump[0xbd] = invalidMinor
jump[0xbe] = invalidMinor
jump[0xbf] = map.decodeMapIndefinite // map, pairs of data items follow, terminated by "break"
// tags
for (let i = 0xc0; i <= 0xd7; i++) {
  jump[i] = tag.decodeTagCompact
}
jump[0xd8] = tag.decodeTag8
jump[0xd9] = tag.decodeTag16
jump[0xda] = tag.decodeTag32
jump[0xdb] = tag.decodeTag64
jump[0xdc] = invalidMinor
jump[0xdd] = invalidMinor
jump[0xde] = invalidMinor
jump[0xdf] = invalidMinor
// 0xe0..0xf3 simple values, unsupported
for (let i = 0xe0; i <= 0xf3; i++) {
  jump[i] = errorer('simple values are not supported')
}
jump[0xf4] = invalidMinor // false, handled by quick[]
jump[0xf5] = invalidMinor // true, handled by quick[]
jump[0xf6] = invalidMinor // null, handled by quick[]
jump[0xf7] = float.decodeUndefined // undefined
jump[0xf8] = errorer('simple values are not supported') // simple value, one byte follows, unsupported
jump[0xf9] = float.decodeFloat16 // half-precision float (two-byte IEEE 754)
jump[0xfa] = float.decodeFloat32 // single-precision float (four-byte IEEE 754)
jump[0xfb] = float.decodeFloat64 // double-precision float (eight-byte IEEE 754)
jump[0xfc] = invalidMinor
jump[0xfd] = invalidMinor
jump[0xfe] = invalidMinor
jump[0xff] = float.decodeBreak // "break" stop code

/** @type {Token[]} */
export const quick = []
// ints <24
for (let i = 0; i < 24; i++) {
  quick[i] = new Token(Type.uint, i, 1)
}
// negints >= -24
for (let i = -1; i >= -24; i--) {
  quick[31 - i] = new Token(Type.negint, i, 1)
}
// empty bytes
quick[0x40] = new Token(Type.bytes, new Uint8Array(0), 1)
// empty string
quick[0x60] = new Token(Type.string, '', 1)
// empty list
quick[0x80] = new Token(Type.array, 0, 1)
// empty map
quick[0xa0] = new Token(Type.map, 0, 1)
// false
quick[0xf4] = new Token(Type.false, false, 1)
// true
quick[0xf5] = new Token(Type.true, true, 1)
// null
quick[0xf6] = new Token(Type.null, null, 1)

/**
 * @param {Token} token
 * @returns {AllocatedByteView|undefined}
 */
export function quickEncodeToken (token) {
  switch (token.type) {
    case Type.false:
      return fromArray([0xf4])
    case Type.true:
      return fromArray([0xf5])
    case Type.null:
      return fromArray([0xf6])
    case Type.bytes:
      if (!token.value.length) {
        return fromArray([0x40])
      }
      return
    case Type.string:
      if (token.value === '') {
        return fromArray([0x60])
      }
      return
    case Type.array:
      if (token.value === 0) {
        return fromArray([0x80])
      }
      // shouldn't be possible if this were called when there was only one token
      return
    case Type.map:
      if (token.value === 0) {
        return fromArray([0xa0])
      }
      // shouldn't be possible if this were called when there was only one token
      return
    case Type.uint:
      if (token.value < 24) {
        return fromArray([Number(token.value)])
      }
      return
    case Type.negint:
      if (token.value >= -24) {
        return fromArray([31 - Number(token.value)])
      }
  }
}
/**
 * @typedef {import('../interface.js').TagDecodeControl} TagDecodeControl
 * @typedef {(decode: TagDecodeControl) => Tagged} TaggedTagDecoder
 */

/**
 * A wrapper class for representing a CBOR tag with an arbitrary nested value.
 *
 * `Tagged` is a symmetric primitive: it can be passed to `encode()` to emit
 * a CBOR tag header followed by the encoded form of `value`, and it can be
 * returned from a tag decoder (via `Tagged.decoder(tag)` or `Tagged.preserve()`)
 * to round-trip a tag through decode without losing the tag number.
 *
 * Use `Tagged` for one-off tag handling where defining a dedicated
 * `typeEncoders` entry and tag decoder pair would be heavyweight, e.g. when
 * wrapping a structure in a single application-specific tag (COSE, dCBOR
 * envelopes, etc.).
 *
 * For systematic mapping of a JS type to a tag (e.g. CID -> tag 42), prefer
 * a dedicated `typeEncoders` entry instead.
 */
export class Tagged {
  /**
   * @param {number} tag - CBOR tag number, a non-negative integer
   * @param {any} value - The value to be tagged; encoded recursively
   */
  constructor (tag, value) {
    if (typeof tag !== 'number' || !Number.isInteger(tag) || tag < 0) {
      throw new TypeError('Tagged: tag must be a non-negative integer')
    }
    this.tag = tag
    this.value = value
  }

  /**
   * Build a tag decoder for use in `decode()`'s `tags` option that returns the
   * decoded content wrapped in a `Tagged` instance, preserving the tag number
   * for the caller to inspect.
   *
   * @param {number} tag - The CBOR tag number this decoder will be registered for
   * @returns {TaggedTagDecoder}
   *
   * @example
   * import { decode, Tagged } from 'cborg'
   * const value = decode(bytes, { tags: { 16: Tagged.decoder(16) } })
   * // value instanceof Tagged; value.tag === 16
   */
  static decoder (tag) {
    return (decode) => new Tagged(tag, decode())
  }

  /**
   * Build a `tags` option for `decode()` that wraps each listed tag number in
   * a `Tagged` instance, preserving those tags through decode without
   * registering a dedicated decoder per tag.
   *
   * @param {...number} tagNumbers - One or more CBOR tag numbers to preserve
   * @returns {{[tagNumber: number]: TaggedTagDecoder}}
   *
   * @example
   * import { decode, Tagged } from 'cborg'
   * const value = decode(bytes, { tags: Tagged.preserve(16, 96) })
   */
  static preserve (...tagNumbers) {
    /** @type {{[tagNumber: number]: TaggedTagDecoder}} */
    const tags = {}
    for (const tag of tagNumbers) {
      tags[tag] = Tagged.decoder(tag)
    }
    return tags
  }
}

// Symbol.toStringTag so the internal `is()` type detection returns 'Tagged'
// for instances, allowing the default Tagged typeEncoder to match.
Object.defineProperty(Tagged.prototype, Symbol.toStringTag, {
  value: 'Tagged'
})
class Type {
  /**
   * @param {number} major
   * @param {string} name
   * @param {boolean} terminal
   */
  constructor (major, name, terminal) {
    this.major = major
    this.majorEncoded = major << 5
    this.name = name
    this.terminal = terminal
  }

  toString () {
    return `Type[${this.major}].${this.name}`
  }

  /**
   * @param {Type} typ
   * @returns {number}
   */
  compare (typ) {
    return this.major < typ.major ? -1 : this.major > typ.major ? 1 : 0
  }

  /**
   * Check equality between two Type instances. Safe to use across different
   * copies of the Type class (e.g., when bundlers duplicate the module).
   * (major, name) uniquely identifies a Type; terminal is implied by these.
   * @param {Type} a
   * @param {Type} b
   * @returns {boolean}
   */
  static equals (a, b) {
    return a === b || (a.major === b.major && a.name === b.name)
  }
}

// convert to static fields when better supported
Type.uint = new Type(0, 'uint', true)
Type.negint = new Type(1, 'negint', true)
Type.bytes = new Type(2, 'bytes', true)
Type.string = new Type(3, 'string', true)
Type.array = new Type(4, 'array', false)
Type.map = new Type(5, 'map', false)
Type.tag = new Type(6, 'tag', false) // terminal?
Type.float = new Type(7, 'float', true)
Type.false = new Type(7, 'false', true)
Type.true = new Type(7, 'true', true)
Type.null = new Type(7, 'null', true)
Type.undefined = new Type(7, 'undefined', true)
Type.break = new Type(7, 'break', true)
// Type.indefiniteLength = new Type(0, 'indefiniteLength', true)

class Token {
  /**
   * @param {Type} type
   * @param {any} [value]
   * @param {number} [encodedLength]
   */
  constructor (type, value, encodedLength) {
    this.type = type
    this.value = value
    this.encodedLength = encodedLength
    /** @type {Uint8Array|undefined} */
    this.encodedBytes = undefined
    /** @type {Uint8Array|undefined} */
    this.byteValue = undefined
  }

  toString () {
    return `Token[${this.type}].${this.value}`
  }
}

export { Type, Token }
{
  "name": "cborg",
  "version": "5.1.7",
  "description": "Fast CBOR with a focus on strictness",
  "main": "cborg.js",
  "type": "module",
  "bin": {
    "cborg": "lib/bin.js"
  },
  "scripts": {
    "lint": "standard *.js lib/*.js test/*.js",
    "build": "npm run build:types",
    "build:types": "tsc --build",
    "prepublishOnly": "npm run build",
    "test:node": "mocha test/test-*.js",
    "test:node-bin": "mocha test/node-test-bin.js",
    "test:browser": "polendina --cleanup test/test-*.js",
    "test": "npm run lint && npm run build && npm run test:node && npm run test:node-bin && npm run test:browser",
    "test:ci": "npm run test"
  },
  "repository": {
    "type": "git",
    "url": "git@github.com:rvagg/cborg.git"
  },
  "keywords": [
    "cbor"
  ],
  "author": "Rod <rod@vagg.org> (http://r.va.gg/)",
  "license": "Apache-2.0",
  "devDependencies": {
    "@semantic-release/changelog": "^6.0.3",
    "@semantic-release/commit-analyzer": "^13.0.1",
    "@semantic-release/git": "^10.0.1",
    "@semantic-release/github": "^12.0.6",
    "@semantic-release/npm": "^13.1.5",
    "@semantic-release/release-notes-generator": "^14.1.0",
    "@types/chai": "^5.2.3",
    "@types/mocha": "^10.0.10",
    "@types/node": "^26.0.1",
    "chai": "^6.2.2",
    "conventional-changelog-conventionalcommits": "^10.0.0",
    "ipld-garbage": "^5.0.0",
    "mocha": "^11.7.5",
    "polendina": "^3.2.20",
    "semantic-release": "^25.0.3",
    "standard": "^17.1.2",
    "typescript": "^6.0.2"
  },
  "exports": {
    ".": {
      "import": "./cborg.js",
      "types": "./types/cborg.d.ts"
    },
    "./length": {
      "import": "./lib/length.js",
      "types": "./types/lib/length.d.ts"
    },
    "./taglib": {
      "import": "./lib/taglib.js",
      "types": "./types/lib/taglib.d.ts"
    },
    "./json": {
      "import": "./lib/json/json.js",
      "types": "./types/lib/json/json.d.ts"
    },
    "./extended": {
      "import": "./lib/extended/extended.js",
      "types": "./types/lib/extended/extended.d.ts"
    },
    "./interface": {
      "types": "./types/interface.d.ts"
    }
  },
  "types": "cborg.d.ts",
  "typesVersions": {
    "*": {
      "json": [
        "types/lib/json/json.d.ts"
      ],
      "length": [
        "types/lib/length.d.ts"
      ],
      "*": [
        "types/*"
      ],
      "types/*": [
        "types/*"
      ]
    }
  },
  "release": {
    "branches": [
      "master"
    ],
    "plugins": [
      [
        "@semantic-release/commit-analyzer",
        {
          "preset": "conventionalcommits",
          "releaseRules": [
            {
              "breaking": true,
              "release": "major"
            },
            {
              "revert": true,
              "release": "patch"
            },
            {
              "type": "feat",
              "release": "minor"
            },
            {
              "type": "fix",
              "release": "patch"
            },
            {
              "type": "chore",
              "release": "patch"
            },
            {
              "type": "docs",
              "release": "patch"
            },
            {
              "type": "test",
              "release": "patch"
            },
            {
              "scope": "no-release",
              "release": false
            }
          ]
        }
      ],
      [
        "@semantic-release/release-notes-generator",
        {
          "preset": "conventionalcommits",
          "presetConfig": {
            "types": [
              {
                "type": "feat",
                "section": "Features"
              },
              {
                "type": "fix",
                "section": "Bug Fixes"
              },
              {
                "type": "chore",
                "section": "Trivial Changes"
              },
              {
                "type": "docs",
                "section": "Trivial Changes"
              },
              {
                "type": "test",
                "section": "Tests"
              }
            ]
          }
        }
      ],
      "@semantic-release/changelog",
      "@semantic-release/npm",
      "@semantic-release/github",
      "@semantic-release/git"
    ]
  }
}
const b4a = require('b4a')

module.exports = codecs

codecs.ascii = createString('ascii')
codecs.utf8 = createString('utf-8')
codecs.hex = createString('hex')
codecs.base64 = createString('base64')
codecs.ucs2 = createString('ucs2')
codecs.utf16le = createString('utf16le')
codecs.ndjson = createJSON(true)
codecs.json = createJSON(false)
codecs.binary = {
  name: 'binary',
  encode: function encodeBinary (obj) {
    return typeof obj === 'string'
      ? b4a.from(obj, 'utf-8')
      : b4a.toBuffer(obj)
  },
  decode: function decodeBinary (buf) {
    return b4a.toBuffer(buf)
  }
}

function isCompactEncoding (c) {
  return !!(c.encode && c.decode && c.preencode)
}

function fromCompactEncoding (c) {
  return {
    name: 'compact-encoding',
    encode: function encodeWithCompact (value) {
      const state = { start: 0, end: 0, buffer: null, cache: null }
      c.preencode(state, value)
      state.buffer = b4a.allocUnsafe(state.end)
      c.encode(state, value)
      return state.buffer
    },
    decode: function decodeWithCompact (buffer) {
      return c.decode({ start: 0, end: buffer.byteLength, buffer, cache: null })
    }
  }
}

function codecs (fmt, fallback) {
  if (typeof fmt === 'object' && fmt) {
    return isCompactEncoding(fmt) ? fromCompactEncoding(fmt) : fmt
  }

  switch (fmt) {
    case 'ndjson': return codecs.ndjson
    case 'json': return codecs.json
    case 'ascii': return codecs.ascii
    case 'utf-8':
    case 'utf8': return codecs.utf8
    case 'hex': return codecs.hex
    case 'base64': return codecs.base64
    case 'ucs-2':
    case 'ucs2': return codecs.ucs2
    case 'utf16-le':
    case 'utf16le': return codecs.utf16le
  }

  return fallback !== undefined ? fallback : codecs.binary
}

function createJSON (newline) {
  return {
    name: newline ? 'ndjson' : 'json',
    encode: newline ? encodeNDJSON : encodeJSON,
    decode: function decodeJSON (buf) {
      return JSON.parse(b4a.toString(buf))
    }
  }

  function encodeJSON (val) {
    return b4a.from(JSON.stringify(val))
  }

  function encodeNDJSON (val) {
    return b4a.from(JSON.stringify(val) + '\n')
  }
}

function createString (type) {
  return {
    name: type,
    encode: function encodeString (val) {
      if (typeof val !== 'string') val = val.toString()
      return b4a.from(val, type)
    },
    decode: function decodeString (buf) {
      return b4a.toString(buf, type)
    }
  }
}
{
  "name": "codecs",
  "version": "3.1.0",
  "description": "Create an binary encoder/decoder for json, utf-8 or custom types",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.6.3"
  },
  "devDependencies": {
    "brittle": "^3.2.1",
    "compact-encoding": "^2.11.0",
    "standard": "^17.0.0"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/codecs.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/codecs/issues"
  },
  "homepage": "https://github.com/mafintosh/codecs"
}
const c = require('compact-encoding')

module.exports = function bitfield(length) {
  if (length > 64) {
    throw new RangeError('Bitfield cannot be larger than 64 bits')
  }

  let byteLength
  if (length < 8) byteLength = 1
  else if (length <= 16) byteLength = 2
  else if (length <= 32) byteLength = 4
  else byteLength = 8

  return {
    preencode(state) {
      state.end++ // Length byte, used for data when byteLength === 1

      if (byteLength === 1);
      else if (byteLength === 2) c.uint16.preencode(state)
      else if (byteLength === 4) c.uint32.preencode(state)
      else c.uint64.preencode(state)
    },

    encode(state, b) {
      if (byteLength === 1);
      else if (byteLength === 2) c.uint8.encode(state, 0xfd)
      else if (byteLength === 4) c.uint8.encode(state, 0xfe)
      else c.uint8.encode(state, 0xff)

      if (typeof b === 'number') {
        if (byteLength === 1) c.uint8.encode(state, b)
        else if (byteLength === 2) c.uint16.encode(state, b)
        else if (byteLength === 4) c.uint32.encode(state, b)
        else c.uint64.encode(state, b)
      } else {
        state.buffer.set(b, state.start)

        if (b.byteLength < byteLength) {
          // Zero-fill the rest of the byte length.
          state.buffer.fill(
            0,
            state.start + b.byteLength,
            state.start + byteLength
          )
        }

        state.start += byteLength
      }
    },

    decode(state) {
      const byte = state.buffer[state.start]

      let byteLength
      if (byte <= 0xfc) byteLength = 1
      else if (byte === 0xfd) byteLength = 2
      else if (byte === 0xfe) byteLength = 4
      else byteLength = 8

      if (byteLength > 1) state.start++ // Skip the length byte

      if (state.end - state.start < byteLength) throw new Error('Out of bounds')

      const b = state.buffer.subarray(state.start, (state.start += byteLength))

      return length <= 8 ? b.subarray(0, 1) : b
    }
  }
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "compact-encoding-bitfield",
  "version": "1.1.0",
  "description": "Compact codec for bitfields",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node --coverage test.mjs",
    "test:bare": "brittle-bare --coverage test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/compact-encoding/compact-encoding-bitfield.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/compact-encoding/compact-encoding-bitfield/issues"
  },
  "homepage": "https://github.com/compact-encoding/compact-encoding-bitfield#readme",
  "imports": {
    "util": {
      "bare": "bare-utils",
      "default": "util"
    }
  },
  "dependencies": {
    "compact-encoding": "^3.0.0"
  },
  "devDependencies": {
    "bare-utils": "^1.5.1",
    "brittle": "^3.1.0",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  }
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return uint24.decode(state) + 0x1000000 * uint32.decode(state)
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return uint32.decode(state) + 0x100000000 * uint32.decode(state)
  }
})

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "2.19.2",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    if (b.byteLength === 0) return null
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
const b4a = require('b4a')
const Hypercore = require('hypercore')
const ReadyResource = require('ready-resource')
const sodium = require('sodium-universal')
const crypto = require('hypercore-crypto')
const ID = require('hypercore-id-encoding')
const { isAndroid } = require('which-runtime')
const { STORAGE_EMPTY, ASSERTION } = require('hypercore-errors')

const auditStore = require('./lib/audit.js')
const GroupNotifyHandle = require('./lib/notify.js')

const [NS] = crypto.namespace('corestore', 1)
const DEFAULT_NAMESPACE = b4a.alloc(32) // This is meant to be 32 0-bytes

class StreamTracker {
  constructor() {
    this.records = []
  }

  add(stream, isExternal) {
    const record = { index: 0, stream, isExternal }
    record.index = this.records.push(record) - 1
    return record
  }

  remove(record) {
    const popped = this.records.pop()
    if (popped === record) return
    this.records[(popped.index = record.index)] = popped
  }

  attachAll(core) {
    for (let i = 0; i < this.records.length; i++) {
      const record = this.records[i]
      const muxer = record.stream.noiseStream.userData
      if (!core.replicator.attached(muxer)) core.replicator.attachTo(muxer)
    }
  }

  destroy() {
    // reverse is safer cause we delete mb
    for (let i = this.records.length - 1; i >= 0; i--) {
      const record = this.records[i]
      if (!record.isExternal) record.stream.destroy()
    }
  }
}

class SessionTracker {
  constructor() {
    this.map = new Map()
  }

  get size() {
    return this.map.size
  }

  get(id) {
    const existing = this.map.get(id)
    if (existing !== undefined) return existing
    const fresh = []
    this.map.set(id, fresh)
    return fresh
  }

  gc(id) {
    this.map.delete(id)
  }

  list(id) {
    return id ? this.map.get(id) || [] : [...this]
  }

  *[Symbol.iterator]() {
    for (const sessions of this.map.values()) {
      yield* sessions[Symbol.iterator]()
    }
  }
}

class CoreTracker {
  constructor() {
    this.map = new Map()
    this.watching = []

    this._gcing = new Set()
    this._gcInterval = null
    this._gcCycleBound = this._gcCycle.bind(this)
  }

  get size() {
    return this.map.size
  }

  watch(store) {
    if (store.watchIndex !== -1) return
    store.watchIndex = this.watching.push(store) - 1
  }

  unwatch(store) {
    if (store.watchIndex === -1) return
    const head = this.watching.pop()
    if (head !== store) this.watching[(head.watchIndex = store.watchIndex)] = head
    store.watchIndex = -1
  }

  resume(id) {
    const core = this.map.get(id)

    if (!core) return null

    // signal back that we have a closing one stored
    if (core.closing) return core

    if (core.gc) {
      this._gcing.delete(core)
      if (this._gcing.size === 0) this._stopGC()
      core.gc = 0
    }

    return core
  }

  opened(id) {
    const core = this.map.get(id)
    return !!(core && core.opened && !core.closing)
  }

  get(id) {
    // we allow you do call this from the outside, so support normal buffers also
    if (b4a.isBuffer(id)) id = b4a.toString(id, 'hex')
    const core = this.map.get(id)
    if (!core || core.closing) return null
    return core
  }

  set(id, core) {
    this.map.set(id, core)
    if (this.watching.length > 0) this._emit(core)
  }

  _emit(core) {
    for (let i = this.watching.length - 1; i >= 0; i--) {
      const store = this.watching[i]
      for (const fn of store.watchers) fn(core)
    }
  }

  _gc(core) {
    const id = toHex(core.discoveryKey)
    if (this.map.get(id) === core) this.map.delete(id)
  }

  _gcCycle() {
    for (const core of this._gcing) {
      if (++core.gc < 4) continue
      const gc = this._gc.bind(this, core)
      core.close().then(gc, gc)
      this._gcing.delete(core)
    }

    if (this._gcing.size === 0) this._stopGC()
  }

  gc(core) {
    core.gc = 1 // first strike
    this._gcing.add(core)
    if (this._gcing.size === 1) this._startGC()
  }

  _stopGC() {
    clearInterval(this._gcInterval)
    this._gcInterval = null
  }

  _startGC() {
    if (this._gcInterval) return
    this._gcInterval = setInterval(this._gcCycleBound, 2000)
    if (this._gcInterval.unref) this._gcInterval.unref()
  }

  close() {
    this._stopGC()
    this._gcing.clear()

    const all = []
    for (const core of this.map.values()) {
      core.onidle = noop // no reentry
      all.push(core.close())
    }
    this.map.clear()

    return Promise.all(all)
  }

  *[Symbol.iterator]() {
    for (const core of this.map.values()) {
      if (!core.closing) yield core
    }
  }
}

class FindingPeers {
  constructor() {
    this.count = 0
    this.pending = []
    this.destroyed = false
  }

  add(core) {
    if (this.count === 0) return
    this.pending.push(core.findingPeers())
  }

  inc(sessions) {
    if (this.destroyed || ++this.count !== 1) return

    for (const core of sessions) {
      this.pending.push(core.findingPeers())
    }
  }

  dec(sessions) {
    if (this.destroyed || --this.count !== 0) return
    while (this.pending.length > 0) this.pending.pop()()
  }

  destroy() {
    this.destroyed = true
    while (this.pending.length > 0) this.pending.pop()()
  }
}

class Corestore extends ReadyResource {
  constructor(storage, opts = {}) {
    super()

    this.root = opts.root || null
    this.storage = this.root
      ? this.root.storage
      : Hypercore.defaultStorage(storage, {
          id: opts.id,
          allowBackup: opts.allowBackup,
          readOnly: opts.readOnly,
          wait: opts.wait
        })
    this.streamTracker = this.root ? this.root.streamTracker : new StreamTracker()
    this.cores = this.root ? this.root.cores : new CoreTracker()
    this.sessions = new SessionTracker()
    this.corestores = this.root ? this.root.corestores : new Set()
    this.readOnly = opts.writable === false || !!opts.readOnly
    this.globalCache = this.root ? this.root.globalCache : opts.globalCache || null
    this.primaryKey = this.root ? this.root.primaryKey : opts.primaryKey || null
    this.ns = opts.namespace || DEFAULT_NAMESPACE
    this.manifestVersion = opts.manifestVersion || 1
    this.shouldSuspend = isAndroid ? !!opts.suspend : opts.suspend !== false
    this.active = opts.active !== false

    this.watchers = null
    this.watchIndex = -1

    this._groupNotifiers = new Map() // group notifications
    this._findingPeers = null // here for legacy
    this._ongcBound = this._ongc.bind(this)
    this._onGroupActiveBound = this._onGroupActive.bind(this)

    if (opts.primaryKey && !this.root && !opts.unsafe) {
      throw ASSERTION(
        'Passing the primary key is unsafe unless you know what you are doing. Set unsafe: true to acknowledge that'
      )
    }

    this.ready().catch(noop)
  }

  watch(fn) {
    if (this.watchers === null) {
      this.watchers = new Set()
      this.cores.watch(this)
    }

    this.watchers.add(fn)
  }

  unwatch(fn) {
    if (this.watchers === null) return

    this.watchers.delete(fn)

    if (this.watchers.size === 0) {
      this.watchers = null
      this.cores.unwatch(this)
    }
  }

  _onGroupActive(topic, update) {
    this.emit('group-active', topic, update)

    const topicHex = b4a.toString(topic, 'hex')
    const handles = this._groupNotifiers.get(topicHex)
    if (!handles) return
    for (const handle of handles) handle.emit('update', update)
  }

  notifyGroup(topic) {
    const topicHex = b4a.toString(topic, 'hex')
    let handles = this._groupNotifiers.get(topicHex)

    if (!handles) {
      handles = []
      this._groupNotifiers.set(topicHex, handles)
    }

    const handle = new GroupNotifyHandle(this, topic)
    const length = handles.push(handle)
    handle.index = length - 1

    return handle
  }

  _removeGroupNotify(handle) {
    if (handle.index === -1) return

    const topicHex = b4a.toString(handle._topic, 'hex')
    const handles = this._groupNotifiers.get(topicHex)
    if (!handles) return

    const popped = handles.pop()
    if (popped !== handle) handles[(popped.index = handle.index)] = popped
    if (handles.length === 0) this._groupNotifiers.delete(topicHex)
    handle.index = -1
  }

  findingPeers() {
    if (this._findingPeers === null) this._findingPeers = new FindingPeers()
    this._findingPeers.inc(this.sessions)
    let done = false
    return () => {
      if (done || !this._findingPeers) return
      done = true
      this._findingPeers.dec(this.sessions)
    }
  }

  audit(opts = {}) {
    return auditStore(this, opts)
  }

  async suspend({ log = noop } = {}) {
    await log('Flushing db...')
    // If readOnly we don't need to flush
    if (!this.storage.readOnly) {
      await this.storage.db.flush()
      await log('Flusing db completed')
    }
    if (!this.shouldSuspend) return
    await log('Suspending db...')
    await this.storage.suspend({ log })
    await log('Suspending db completed')
  }

  resume() {
    return this.storage.resume()
  }

  session(opts) {
    this._maybeClosed()
    const root = this.root || this
    return new Corestore(null, {
      manifestVersion: this.manifestVersion,
      ...opts,
      root
    })
  }

  namespace(name, opts) {
    return this.session({
      ...opts,
      namespace: generateNamespace(this.ns, name)
    })
  }

  list(namespace) {
    return this.storage.createDiscoveryKeyStream(namespace)
  }

  getAuth(discoveryKey) {
    return this.storage.getAuth(discoveryKey)
  }

  _ongc(session) {
    if (session.sessions.length === 0) this.sessions.gc(session.id)
  }

  async _getOrSetSeed() {
    const seed = await this.storage.getSeed()
    if (seed !== null) return seed
    return await this.storage.setSeed(this.primaryKey || crypto.randomBytes(32))
  }

  async _open() {
    if (this.root !== null) {
      this.corestores.add(this)
      if (this.root.opened === false) await this.root.ready()
      this.primaryKey = this.root.primaryKey
      return
    }

    const primaryKey = await this._getOrSetSeed()

    if (this.primaryKey === null) {
      this.primaryKey = primaryKey
      return
    }

    if (!b4a.equals(primaryKey, this.primaryKey)) {
      throw new Error('Another corestore is stored here')
    }
  }

  async _close() {
    const closing = []
    const hanging = [...this.sessions]
    for (const sess of hanging) closing.push(sess.close())

    if (this.watchers !== null) {
      this.cores.unwatch(this)
      this.watchers = null
    }

    if (this._findingPeers !== null) {
      this._findingPeers.destroy()
      this._findingPeers = null
    }

    if (this.root !== null) {
      await Promise.all(closing)
      this.corestores.delete(this)
      return
    }

    for (const store of this.corestores) {
      closing.push(store.close())
    }

    await Promise.all(closing)

    await this.cores.close()
    await this.storage.close()
  }

  async _attachMaybe(muxer, discoveryKey) {
    if (this.opened === false) await this.ready()
    if (
      !this.cores.opened(toHex(discoveryKey)) &&
      !(await this.storage.hasCore(discoveryKey, { ifMigrated: true }))
    ) {
      return
    }
    if (this.closing) return

    const core = this._openCore(discoveryKey, { createIfMissing: false })

    if (!core) return
    if (!core.opened) await core.ready()

    if (!core.replicator.attached(muxer)) {
      core.replicator.attachTo(muxer)
    }

    core.checkIfIdle()
  }

  _shouldReplicate(core, muxer) {
    return (
      core.replicator.downloading && !core.replicator.attached(muxer) && core.opened && this.active
    )
  }

  replicate(isInitiator, opts) {
    this._maybeClosed()

    const isExternal = isStream(isInitiator)
    const stream = Hypercore.createProtocolStream(isInitiator, {
      ...opts,
      ondiscoverykey: (discoveryKey) => {
        if (this.closing) return
        const muxer = stream.noiseStream.userData
        return this._attachMaybe(muxer, discoveryKey)
      }
    })

    if (this.cores.size > 0) {
      const muxer = stream.noiseStream.userData
      const uncork = muxer.uncork.bind(muxer)
      muxer.cork()

      for (const core of this.cores) {
        if (!this._shouldReplicate(core, muxer)) {
          continue
        }
        core.replicator.attachTo(muxer)
      }

      stream.noiseStream.opened.then(uncork)
    }

    const record = this.streamTracker.add(stream, isExternal)
    stream.once('close', () => this.streamTracker.remove(record))
    return stream
  }

  _maybeClosed() {
    if (this.closing || (this.root !== null && this.root.closing)) {
      throw new Error('Corestore is closed')
    }
  }

  async staticify(core, opts) {
    if (!this.opened) await this.ready()
    if (!core.opened) await core.ready()

    const rx = core.state.storage.read()

    const headPromise = rx.getHead()
    const authPromise = rx.getAuth()

    rx.tryFlush()

    const [head, auth] = await Promise.all([headPromise, authPromise])
    if (!head || head.length === 0) throw new Error('Core must have data')

    const prologue = {
      length: head.length,
      hash: head.rootHash
    }

    const manifest = {
      version: 1,
      hash: auth.manifest.hash,
      quorum: 0,
      signers: [],
      prologue
    }

    const c = {
      key: null,
      discoveryKey: null,
      manifest,
      core: core.state.storage.core
    }

    c.key = Hypercore.key(c.manifest)
    c.discoveryKey = Hypercore.discoveryKey(c.key)

    await this.storage.createCore(c)

    const staticCore = this.get({ ...opts, key: c.key })
    await staticCore.ready()
    return staticCore
  }

  get(opts) {
    this._maybeClosed()

    if (b4a.isBuffer(opts) || typeof opts === 'string') opts = { key: opts }
    if (!opts) opts = {}

    const conf = {
      preload: null,
      sessions: null,
      ongc: null,
      core: null,
      active: opts.active !== false,
      encryption: opts.encryption || null,
      encryptionKey: opts.encryptionKey || null, // back compat, should remove
      isBlockKey: !!opts.isBlockKey, // back compat, should remove
      valueEncoding: opts.valueEncoding || null,
      exclusive: !!opts.exclusive,
      manifest: opts.manifest || null,
      keyPair: opts.keyPair || null,
      onwait: opts.onwait || null,
      pushOnly: opts.pushOnly === true,
      wait: opts.wait !== false,
      timeout: opts.timeout || 0,
      draft: !!opts.draft,
      writable: opts.writable === undefined && this.readOnly ? false : opts.writable
    }

    // name requires us to rt to storage + ready, so needs preload
    // same goes if user has defined async preload obvs
    if (opts.name || opts.preload) {
      conf.preload = this._preload(opts)
      return this._makeSession(conf)
    }

    if (opts.discoveryKey && !opts.key && !opts.manifest) {
      conf.preload = this._preloadCheckIfExists(opts)
      return this._makeSession(conf)
    }

    // if not not we can sync create it, which just is easier for the
    // upstream user in terms of guarantees (key is there etc etc)
    const core = this._openCore(null, opts)

    conf.core = core
    conf.sessions = this.sessions.get(core.id)
    conf.ongc = this._ongcBound

    return this._makeSession(conf)
  }

  _makeSession(conf) {
    const session = new Hypercore(null, null, conf)

    if (this._findingPeers !== null) this._findingPeers.add(session)
    return session
  }

  async createKeyPair(name, ns = this.ns) {
    if (this.opened === false) await this.ready()
    return createKeyPair(this.primaryKey, ns, name)
  }

  async _preloadCheckIfExists(opts) {
    const has = await this.storage.hasCore(opts.discoveryKey)
    if (!has) throw STORAGE_EMPTY('No Hypercore is stored here')
    return this._preload(opts)
  }

  async _preload(opts) {
    if (opts.preload) opts = { ...opts, ...(await opts.preload) }
    if (this.opened === false) await this.ready()

    const discoveryKey = opts.name
      ? await this.storage.getAlias({ name: opts.name, namespace: this.ns })
      : null
    this._maybeClosed()

    const core = this._openCore(discoveryKey, opts)

    return {
      core,
      sessions: this.sessions.get(core.id),
      ongc: this._ongcBound,
      manifest: opts.manifest || null,
      encryption: opts.encryption || null,
      encryptionKey: opts.encryptionKey || null, // back compat, should remove
      isBlockKey: !!opts.isBlockKey // back compat, should remove
    }
  }

  _auth(discoveryKey, opts) {
    const result = {
      keyPair: null,
      key: null,
      discoveryKey,
      manifest: null,
      group: null
    }

    if (opts.name) {
      result.keyPair = createKeyPair(this.primaryKey, this.ns, opts.name)
    } else if (opts.keyPair) {
      result.keyPair = opts.keyPair
    }

    if (opts.manifest) {
      result.manifest = opts.manifest
    } else if (result.keyPair && !result.discoveryKey) {
      result.manifest = {
        version: this.manifestVersion,
        signers: [{ publicKey: result.keyPair.publicKey }]
      }
    }

    if (opts.group) {
      result.group = opts.group
    }

    if (opts.key) result.key = ID.decode(opts.key)
    else if (result.manifest) result.key = Hypercore.key(result.manifest)

    if (result.discoveryKey) return result

    if (opts.discoveryKey) result.discoveryKey = ID.decode(opts.discoveryKey)
    else if (result.key) result.discoveryKey = crypto.discoveryKey(result.key)
    else throw new Error('Could not derive discovery from input')

    return result
  }

  _openCore(discoveryKey, opts) {
    const auth = this._auth(discoveryKey, opts)

    const id = toHex(auth.discoveryKey)
    const existing = this.cores.resume(id, auth.group)
    if (existing && !existing.closing) return existing

    const core = Hypercore.createCore(this.storage, {
      preopen: existing && existing.opened ? existing.closing : null, // always wait for the prev one to close first in any case...
      eagerUpgrade: true,
      notDownloadingLinger: opts.notDownloadingLinger,
      allowFork: opts.allowFork !== false,
      allowPush: !!opts.allowPush,
      inflightRange: opts.inflightRange,
      compat: false, // no compat for now :)
      force: opts.force,
      createIfMissing: opts.createIfMissing,
      discoveryKey: auth.discoveryKey,
      overwrite: opts.overwrite,
      key: auth.key,
      keyPair: auth.keyPair,
      legacy: opts.legacy,
      manifest: auth.manifest,
      group: auth.group,
      globalCache: opts.globalCache || this.globalCache || null,
      alias: opts.name ? { name: opts.name, namespace: this.ns } : null
    })

    core.onidle = () => {
      this.cores.gc(core)
    }

    core.ongroupupdate = this._onGroupActiveBound

    core.replicator.ondownloading = () => {
      if (this.active) this.streamTracker.attachAll(core)
    }

    this.cores.set(id, core)
    return core
  }
}

module.exports = Corestore

function isStream(s) {
  return typeof s === 'object' && s && typeof s.pipe === 'function'
}

function generateNamespace(namespace, name) {
  if (!b4a.isBuffer(name)) name = b4a.from(name)
  const out = b4a.allocUnsafeSlow(32)
  sodium.crypto_generichash_batch(out, [namespace, name])
  return out
}

function deriveSeed(primaryKey, namespace, name) {
  if (!b4a.isBuffer(name)) name = b4a.from(name)
  const out = b4a.alloc(32)
  sodium.crypto_generichash_batch(out, [NS, namespace, name], primaryKey)
  return out
}

function createKeyPair(primaryKey, namespace, name) {
  const seed = deriveSeed(primaryKey, namespace, name)
  const buf = b4a.alloc(sodium.crypto_sign_PUBLICKEYBYTES + sodium.crypto_sign_SECRETKEYBYTES)
  const keyPair = {
    publicKey: buf.subarray(0, sodium.crypto_sign_PUBLICKEYBYTES),
    secretKey: buf.subarray(sodium.crypto_sign_PUBLICKEYBYTES)
  }
  sodium.crypto_sign_seed_keypair(keyPair.publicKey, keyPair.secretKey, seed)
  return keyPair
}

function noop() {}

function toHex(discoveryKey) {
  return b4a.toString(discoveryKey, 'hex')
}
module.exports = async function* audit(store, { dryRun = false } = {}) {
  for await (const { discoveryKey, core } of store.storage.createCoreStream()) {
    if (core.version < 1) continue // not migrated, ignore

    const c = store.get({ discoveryKey, active: false })
    await c.ready()

    yield { discoveryKey, key: c.key, audit: await c.core.audit({ dryRun }) }

    try {
      await c.close()
    } catch {
      // ignore if failed, we are auditing...
    }
  }
}
const { EventEmitter } = require('events')
const { Readable } = require('streamx')

class GroupNotifyHandle extends EventEmitter {
  constructor(store, topic) {
    super()
    this._store = store
    this._topic = topic
    this.index = -1
  }

  updates(opts) {
    return Readable.deferred(async () => {
      const groupId = await this._store.storage.getGroup(this._topic).catch(noop)
      if (groupId === null) return null
      return this._store.storage.createGroupUpdateStream(groupId, opts)
    })
  }

  destroy() {
    this._store._removeGroupNotify(this)
  }
}

module.exports = GroupNotifyHandle

function noop() {}
{
  "name": "corestore",
  "version": "7.11.0",
  "description": "A Hypercore factory that simplifies managing collections of cores.",
  "main": "index.js",
  "files": [
    "index.js",
    "lib/*"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "dependencies": {
    "b4a": "^1.6.7",
    "bare-events": "^2.8.3",
    "hypercore": "^11.32.0",
    "hypercore-crypto": "^3.4.2",
    "hypercore-errors": "^1.4.0",
    "hypercore-id-encoding": "^1.3.0",
    "ready-resource": "^1.1.1",
    "sodium-universal": "^5.0.1",
    "streamx": "^2.26.0",
    "which-runtime": "^1.2.1"
  },
  "devDependencies": {
    "brittle": "^3.7.0",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "rache": "^1.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "test": "npm run test:node && npm run test:bare",
    "test:bare": "brittle-bare --coverage test/all.js",
    "lint": "prettier --check . && lunte",
    "test:node": "brittle-node --coverage test/all.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/corestore.git"
  },
  "author": "Holepunch Inc",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/corestore/issues"
  },
  "homepage": "https://github.com/holepunchto/corestore"
}
module.exports = function debounce (worker, context = null) {
  debounced.running = null
  return debounced

  async function debounced () {
    if (debounced.running !== null) {
      try {
        await debounced.running
      } catch (_) {
        // ignore - do not fail on old errors
      }
    }

    // another "thread" beat us to it, just piggy pack on that one
    if (debounced.running !== null) return debounced.running

    debounced.running = worker.call(context)

    try {
      return await debounced.running
    } finally {
      debounced.running = null
    }
  }
}
{
  "name": "debounceify",
  "version": "1.1.0",
  "description": "Tiny async debouncer",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^16.0.3",
    "tape": "^5.1.1"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/debounceify.git"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/debounceify/issues"
  },
  "homepage": "https://github.com/mafintosh/debounceify"
}
const fs = require('fs')
const path = require('path')
const fsx = require('fs-native-extensions')
const b4a = require('b4a')
const ReadyResource = require('ready-resource')
const FDLock = require('fd-lock')

const PLATFORM = global.Bare ? global.Bare.platform : global.process.platform
const IS_WIN = PLATFORM === 'win32'
const IS_LINUX = PLATFORM === 'linux'
const MODIFIED_SLACK = 5000
const EMPTY = b4a.alloc(0)
const ATTR = IS_LINUX ? 'user.device-file' : 'device-file'

const nl = IS_WIN ? '\r\n' : '\n'

class DeviceFile extends ReadyResource {
  constructor(filename, { create = true, wait = false, lock = wait, data = {} } = {}) {
    super()

    this.filename = filename
    this.data = data
    this.lock = null

    this._create = create
    this._wait = wait
    this._lock = lock
  }

  async _open() {
    if (await verifyDeviceFile(this)) return
    if (!this._create) throwDeviceFileError('No device file present', false)
    await writeDeviceFile(this)
  }

  static async validate(filename, data) {
    const file = new DeviceFile(filename, { create: false, wait: false, data })
    try {
      await verifyDeviceFile(file)
    } catch (err) {
      if (err.fatal && err.code === 'DEVICE_FILE') return false
      throw err
    }
    return true
  }

  transfer() {
    return this.lock ? this.lock.transfer() : -1
  }

  async _close() {
    if (this.lock) await this.lock.close()
  }

  async suspend() {
    if (!this.opened) await this.ready()
    if (this.lock) await this.lock.suspend()
  }

  async resume() {
    if (!this.opened) await this.ready()
    if (this.lock) await this.lock.resume()
  }
}

module.exports = DeviceFile

async function writeDeviceFile(device) {
  let s = ''

  for (const [key, value] of Object.entries(device.data)) {
    if (value === null) continue
    s += key + '=' + value + nl
  }

  await fs.promises.mkdir(path.dirname(device.filename), { recursive: true })

  const fd = await open(device.filename, 'w')

  device.lock = device._lock ? new FDLock(fd, { wait: device._wait }) : null

  if (device.lock) {
    try {
      await device.lock.ready()
    } catch (err) {
      await device.lock.close()
      throw err
    }
  }

  const st = await fstat(fd)

  const created = Date.now()

  s += 'device/platform=' + PLATFORM + nl
  s += 'device/inode=' + st.ino + nl
  s += 'device/created=' + created + nl

  if (await setAttr(fd, ATTR, b4a.from('original'))) {
    s += 'device/attribute=original' + nl
  }

  await write(fd, b4a.from(s))

  if (!device.lock) await close(fd)
}

async function verifyDeviceFile(device) {
  let fd = 0

  try {
    fd = await open(device.filename, 'r+')
  } catch (e) {
    fd = 0
  }

  if (fd === 0) return false

  device.lock = device._lock ? new FDLock(fd, { wait: device._wait }) : null

  if (device.lock) {
    try {
      await device.lock.ready()
    } catch (err) {
      await device.lock.close()
      throw err
    }
  }

  const buf = await read(fd)
  const result = {}

  const s = b4a.toString(buf).trim().split('\n')

  let inode = 0
  let created = 0
  let attr = ''
  let platform = ''

  for (const ln of s) {
    const i = ln.indexOf('=')
    if (i === -1) continue

    const k = ln.slice(0, i).trim()
    const v = ln.slice(i + 1).trim()

    switch (k) {
      case 'device/platform':
        platform = v
        break
      case 'device/inode':
        inode = Number(v)
        break
      case 'device/created':
        created = Number(v)
        break
      case 'device/attribute':
        attr = v
        break
      default:
        result[k] = v
        break
    }
  }

  for (const [k, v] of Object.entries(device.data)) {
    if (v === null) continue
    if (result[k] === undefined) continue // allow upserts
    if (result[k] !== '' + v) {
      await teardown()
      throwDeviceFileError(`Invalid device file, ${k} has changed. Was ${result[k]}, is ${v}`, true)
    }
  }

  const st = await fstat(fd)
  const at = await getAttr(fd, ATTR)

  const sameAttr = b4a.toString(at || EMPTY) === attr
  const modified = Math.max(st.mtime.getTime(), st.birthtime.getTime())

  if (platform && platform !== PLATFORM) {
    await teardown()
    throwDeviceFileError('Invalid device file, was made on different platform', true)
  }

  if (!sameAttr) {
    await teardown()
    throwDeviceFileError('Invalid device file, was moved unsafely', true)
  }

  if (st.ino !== inode || (created && Math.abs(modified - created) >= MODIFIED_SLACK)) {
    await teardown()
    throwDeviceFileError('Invalid device file, was modified', true)
  }

  if (!device.lock) await close(fd)

  device.data = result
  return true

  async function teardown() {
    if (device.lock) await device.lock.close()
    else await close(fd)
  }
}

async function getAttr(fd, name) {
  try {
    return await fsx.getAttr(fd, name)
  } catch {
    return null
  }
}

async function setAttr(fd, name, value) {
  try {
    await fsx.setAttr(fd, name, value)
    return true
  } catch {
    return false
  }
}

function fstat(fd) {
  return new Promise((resolve, reject) => {
    fs.fstat(fd, (err, st) => {
      if (err) reject(err)
      resolve(st)
    })
  })
}

function close(fd) {
  return new Promise((resolve, reject) => {
    fs.close(fd, (err, st) => {
      if (err) reject(err)
      resolve(st)
    })
  })
}

function write(fd, buf) {
  return new Promise((resolve, reject) => {
    let offset = 0

    onwrite(null, 0)

    function onwrite(err, wrote) {
      if (err) return reject(err)
      if (offset === buf.byteLength) return resolve()
      offset += wrote
      fs.write(fd, buf, offset, buf.byteLength - offset, offset, onwrite)
    }
  })
}

function read(fd) {
  const buf = b4a.allocUnsafe(4096)

  return new Promise((resolve, reject) => {
    let offset = 0

    fs.read(fd, buf, 0, buf.byteLength, 0, onread)

    function onread(err, read) {
      if (err) return reject(err)
      if (read === 0) return resolve(buf.subarray(0, offset))
      offset += read
      fs.read(fd, buf, offset, buf.byteLength - offset, offset, onread)
    }
  })
}

function open(filename, flags) {
  return new Promise((resolve, reject) => {
    fs.open(filename, flags, (err, fd) => {
      if (err) reject(err)
      resolve(fd)
    })
  })
}

function throwDeviceFileError(message, fatal) {
  const err = new Error(message)
  err.code = 'DEVICE_FILE'
  err.fatal = fatal
  throw err
}
{
  "name": "device-file",
  "version": "2.3.1",
  "description": "Device only file",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.6.7",
    "bare-fs": "^4.0.1",
    "bare-path": "^3.0.0",
    "fd-lock": "^2.1.0",
    "fs-native-extensions": "^1.4.0",
    "ready-resource": "^1.2.0"
  },
  "devDependencies": {
    "brittle": "^3.13.1",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node --coverage test.js",
    "test:bare": "brittle-bare --coverage test.js"
  },
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    }
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/device-file.git"
  },
  "author": "Holepunch Inc",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/device-file/issues"
  },
  "homepage": "https://github.com/holepunchto/device-file"
}
const { EventEmitter } = require('events')
const Table = require('kademlia-routing-table')
const TOS = require('time-ordered-set')
const UDX = require('udx-native')
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const NatSampler = require('nat-sampler')
const b4a = require('b4a')
const NetworkHealth = require('./lib/health')
const IO = require('./lib/io')
const Query = require('./lib/query')
const Session = require('./lib/session')
const peer = require('./lib/peer')
const { UNKNOWN_COMMAND, INVALID_TOKEN } = require('./lib/errors')
const { PING, PING_NAT, FIND_NODE, DOWN_HINT, DELAYED_PING } = require('./lib/commands')

const TMP = b4a.allocUnsafe(32)
const TICK_INTERVAL = 5000
const SLEEPING_INTERVAL = 3 * TICK_INTERVAL
const STABLE_TICKS = 240 // if nothing major bad happens in ~20mins we can consider this node stable (if nat is friendly)
const MORE_STABLE_TICKS = 3 * STABLE_TICKS
const REFRESH_TICKS = 60 // refresh every ~5min when idle
const RECENT_NODE = 12 // we've heard from a node less than 1min ago
const OLD_NODE = 360 // if an node has been around more than 30 min we consider it old

const DEFAULTS = {
  concurrency: 10,
  maxWindow: IO.DEFAULT_MAX_WINDOW,
  maxPingDelay: 10_000
}

class DHT extends EventEmitter {
  constructor(opts = {}) {
    super()

    this.bootstrapNodes = opts.bootstrap === false ? [] : (opts.bootstrap || []).map(parseNode)
    this.table = new Table(randomBytes(32))
    this.nodes = new TOS()
    this.udx = opts.udx || new UDX()
    this.io = new IO(this.table, this.udx, {
      ...opts,
      onrequest: this._onrequest.bind(this),
      onresponse: this._onresponse.bind(this),
      ontimeout: this._ontimeout.bind(this)
    })
    this.health = new NetworkHealth(this)

    this.concurrency = opts.concurrency || DEFAULTS.concurrency
    this.maxPingDelay = opts.maxPingDelay || DEFAULTS.maxPingDelay
    this.bootstrapped = false
    this.ephemeral = true
    this.firewalled = this.io.firewalled
    this.adaptive = typeof opts.ephemeral !== 'boolean' && opts.adaptive !== false
    this.destroyed = false
    this.suspended = false
    this.online = true
    this.degraded = false
    this.stats = {
      queries: { active: 0, total: 0 },
      requests: this.io.stats.requests,
      commands: {
        ping: this.io.stats.commands[PING],
        pingNat: this.io.stats.commands[PING_NAT],
        findNode: this.io.stats.commands[FIND_NODE],
        downHint: this.io.stats.commands[DOWN_HINT]
      }
    }

    this._nat = new NatSampler()
    this._quickFirewall = opts.quickFirewall !== false
    this._forcePersistent = opts.ephemeral === false
    this._repinging = 0
    this._checks = 0
    this._tick = randomOffset(100) // make sure to random offset all the network ticks
    this._refreshTicks = randomOffset(REFRESH_TICKS)
    this._stableTicks = this.adaptive ? STABLE_TICKS : 0
    this._tickInterval = setInterval(this._ontick.bind(this), TICK_INTERVAL)
    this._lastTick = Date.now()
    this._lastHost = null
    this._filterNode = opts.filterNode || opts.addNode || null // opts.addNode is deprecating, use opts.filterNode instead
    this._onrow = (row) => row.on('full', (node) => this._onfullrow(node, row))
    this._nonePersistentSamples = []
    this._bootstrapping = this._bootstrap()
    this._bootstrapping.catch(noop)
    this._sendDownHints = opts.sendDownHints !== false
    this._downHintsRateLimit =
      opts.downHintsRateLimit !== undefined ? opts.downHintsRateLimit : 10 * 5
    this._downHintsSentPerTick = 0
    this._pendingTimers = new Set()

    this.table.on('row', this._onrow)

    this.io.networkInterfaces.on('change', (interfaces) => this._onnetworkchange(interfaces))

    if (opts.nodes) {
      for (let i = opts.nodes.length - 1; i >= 0; i--) {
        this.addNode(opts.nodes[i])
      }
    }
  }

  static DEFAULTS = DEFAULTS

  static bootstrapper(port, host, opts) {
    if (!port) throw new Error('Port is required')
    if (!host) throw new Error('Host is required')
    if (host === '0.0.0.0' || host === '::') throw new Error('Invalid host')
    if (!UDX.isIPv4(host)) throw new Error('Host must be a IPv4 address')

    const dht = new this({
      port,
      ephemeral: false,
      firewalled: false,
      anyPort: false,
      bootstrap: [],
      ...opts
    })
    dht._nat.add(host, port)
    return dht
  }

  get id() {
    return this.ephemeral ? null : this.table.id
  }

  get host() {
    return this._nat.host
  }

  get port() {
    return this._nat.port
  }

  get randomized() {
    return this._nat.host !== null && this._nat.port === 0
  }

  get socket() {
    return this.firewalled ? this.io.clientSocket : this.io.serverSocket
  }

  get config() {
    return {
      concurrency: this.concurrency,
      maxWindow: this.io.congestion._maxWindow,
      randomPunchInterval: this._randomPunchInterval,
      connectionKeepAlive: this.connectionKeepAlive,
      sendDownHints: this._sendDownHints,
      downHintsRateLimit: this._downHintsRateLimit
    }
  }

  onmessage(socket, buf, rinfo) {
    if (buf.byteLength > 1) this.io.onmessage(socket, buf, rinfo)
  }

  bind() {
    return this.io.bind()
  }

  async suspend({ log = noop } = {}) {
    log('Suspending waiting for io bind...')
    await this.io.bind()
    log('Done, continuing')
    if (this.suspended || this.destroyed) return
    this.suspended = true
    clearInterval(this._tickInterval)
    log('Done, suspending io')
    await this.io.suspend({ log })
    log('Done, dht suspended')
    this.emit('suspend')
  }

  async resume({ log = noop } = {}) {
    if (!this.suspended || this.destroyed) return
    this.suspended = false
    this._tickInterval = setInterval(this._ontick.bind(this), TICK_INTERVAL)
    this._onwakeup()
    log('Resuming io')
    await this.io.resume()
    log('Done, dht resumed')
    this.io.networkInterfaces.on('change', (interfaces) => this._onnetworkchange(interfaces))
    this.refresh()
    this.emit('resume')
  }

  address() {
    const socket = this.socket
    return socket ? socket.address() : null
  }

  localAddress() {
    if (!this.io.serverSocket) return null

    return {
      host: localIP(this.udx),
      port: this.io.serverSocket.address().port
    }
  }

  remoteAddress() {
    if (!this.host) return null
    if (!this.port) return null
    if (this.firewalled) return null
    if (!this.io.serverSocket) return null

    const port = this.io.serverSocket.address().port
    if (port !== this.port) return null

    return {
      host: this.host,
      port
    }
  }

  addNode({ host, port }) {
    this._addNode({
      id: peer.id(host, port),
      port,
      host,
      token: null,
      to: null,
      sampled: 0,
      added: this._tick,
      pinged: 0,
      seen: 0,
      downHints: 0,
      prev: null,
      next: null
    })
  }

  toArray(opts) {
    const limit = opts && opts.limit
    if (limit === 0) return []
    return this.nodes.toArray({ limit, reverse: true }).map(({ host, port }) => ({ host, port }))
  }

  async fullyBootstrapped() {
    return this._bootstrapping
  }

  ready() {
    // Deprecating, use fullyBootstrapped instead (removed on next major)
    return this.fullyBootstrapped()
  }

  findNode(target, opts) {
    if (this.destroyed) throw new Error('Node destroyed')
    this._refreshTicks = REFRESH_TICKS
    return new Query(this, target, true, FIND_NODE, null, opts)
  }

  query({ target, command, value }, opts) {
    if (this.destroyed) throw new Error('Node destroyed')
    this._refreshTicks = REFRESH_TICKS
    return new Query(this, target, false, command, value || null, opts)
  }

  ping({ host, port }, opts) {
    let value = null

    if (opts && opts.size && opts.size > 0) value = b4a.alloc(opts.size)

    const req = this.io.createRequest(
      { id: null, host, port },
      null,
      true,
      PING,
      null,
      value,
      (opts && opts.session) || null,
      opts && opts.ttl
    )
    return this._requestToPromise(req, opts)
  }

  delayedPing({ host, port }, delayMs, opts) {
    if (delayMs > this.maxPingDelay) {
      throw new Error(`Delay exceeds max delay: ${this.maxPingDelay}ms`)
    }

    const value = b4a.allocUnsafe(4)
    c.uint32.encode({ start: 0, end: 4, buffer: value }, delayMs)

    const req = this.io.createRequest(
      { id: null, host, port },
      null,
      true,
      DELAYED_PING,
      null,
      value,
      (opts && opts.session) || null,
      opts && opts.ttl
    )
    // add 1 second to the timeout to account for network overhead
    req.timeout = delayMs + 1_000
    return this._requestToPromise(req, opts)
  }

  async rttStats() {
    const stats = {
      successes: 0,
      errors: 0,
      responses: {
        avgRtt: 0,
        errors: 0,
        avgCloserNodes: 0
      },
      closestReplies: {
        avgRtt: 0,
        errors: 0,
        avgCloserNodes: 0
      }
    }

    if (this.nodes.latest) {
      const q = this.findNode(this.nodes.latest.id)

      let responseCount = 0
      let closestCount = 0

      for await (const msg of q) {
        stats.responses.avgRtt += msg.rtt
        stats.responses.errors += msg.error
        stats.responses.avgCloserNodes += msg.closerNodes?.length || 0
        responseCount++
      }
      stats.responses.avgRtt /= responseCount
      stats.responses.avgCloserNodes /= responseCount

      for await (const msg of q.closestReplies) {
        stats.closestReplies.avgRtt += msg.rtt
        stats.closestReplies.errors += msg.error
        stats.closestReplies.avgCloserNodes += msg.closerNodes?.length || 0
        closestCount++
      }
      stats.closestReplies.avgRtt /= closestCount
      stats.closestReplies.avgCloserNodes /= closestCount

      stats.successes = q.successes
      stats.errors = q.errors
    }

    return stats
  }

  request({ token = null, command, target = null, value = null }, { host, port }, opts) {
    const req = this.io.createRequest(
      { id: null, host, port },
      token,
      false,
      command,
      target,
      value,
      (opts && opts.session) || null,
      opts && opts.ttl
    )
    return this._requestToPromise(req, opts)
  }

  session() {
    return new Session(this)
  }

  _requestToPromise(req, opts) {
    if (req === null) return Promise.reject(new Error('Node destroyed'))

    if (opts && opts.socket) req.socket = opts.socket
    if (opts && opts.retry === false) req.retries = 0

    return new Promise((resolve, reject) => {
      req.onresponse = resolve
      req.onerror = reject
      req.send()
    })
  }

  async _bootstrap() {
    const self = this

    await Promise.resolve() // wait a tick, so apis can be used from the outside
    await this.io.bind()

    this.emit('listening')

    // TODO: some papers describe more advanced ways of bootstrapping - we should prob look into that

    let first = this.firewalled && this._quickFirewall && !this._forcePersistent
    let testNat = false

    const onlyFirewall = !this._forcePersistent

    for (let i = 0; i < 2; i++) {
      await this._backgroundQuery(this.table.id).on('data', ondata).finished()

      if (this.bootstrapped || (!testNat && !this._forcePersistent)) break
      if (!(await this._updateNetworkState(onlyFirewall))) break
    }

    if (this.bootstrapped) return
    this.bootstrapped = true

    this.emit('ready')

    function ondata(data) {
      // Simple QUICK nat heuristic.
      // If we get ONE positive nat ping before the bootstrap query finishes
      // then we always to a nat test, no matter if we are adaptive...
      // This should be expanded in the future to try more than one node etc, not always hit the first etc
      // If this fails, then nbd, as the onstable hook will pick it up later.

      if (!first) return
      first = false

      const value = b4a.allocUnsafe(2)
      c.uint16.encode({ start: 0, end: 2, buffer: value }, self.io.serverSocket.address().port)

      self._request(
        data.from,
        false,
        true,
        PING_NAT,
        null,
        value,
        null,
        () => {
          testNat = true
        },
        noop
      )
    }
  }

  refresh() {
    const node = this.table.random()
    this._backgroundQuery(node ? node.id : this.table.id).on('error', noop)
  }

  async destroy() {
    const emitClose = !this.destroyed
    this.destroyed = true
    clearInterval(this._tickInterval)
    for (const timer of this._pendingTimers) {
      clearTimeout(timer)
    }
    await this.io.destroy()
    if (emitClose) this.emit('close')
  }

  _request(to, force, internal, command, target, value, session, onresponse, onerror) {
    if (internal && !this._sendDownHints && command === DOWN_HINT) return null
    const req = this.io.createRequest(to, null, internal, command, target, value, session)
    if (req === null) return null

    req.onresponse = onresponse
    req.onerror = onerror
    req.send(force)

    return req
  }

  _natAdd(host, port) {
    const prevHost = this._nat.host
    const prevPort = this._nat.port

    this._nat.add(host, port)

    if (prevHost === this._nat.host && prevPort === this._nat.port) return

    this.emit('nat-update', this._nat.host, this._nat.port)
  }

  // we don't check that this is a bootstrap node but we limit the sample size to very few nodes, so fine
  _sampleBootstrapMaybe(from, to) {
    if (this._nonePersistentSamples.length >= Math.max(1, this.bootstrapNodes.length)) return
    const id = from.host + ':' + from.port
    if (this._nonePersistentSamples.indexOf(id) > -1) return
    this._nonePersistentSamples.push(id)
    this._natAdd(to.host, to.port)
  }

  _addNodeFromNetwork(sample, from, to) {
    if (this._filterNode !== null && !this._filterNode(from)) {
      return
    }

    if (from.id === null) {
      this._sampleBootstrapMaybe(from, to)
      return
    }

    const oldNode = this.table.get(from.id)

    // refresh it, if we've seen this before
    if (oldNode) {
      if (sample && (oldNode.sampled === 0 || this._tick - oldNode.sampled >= OLD_NODE)) {
        oldNode.to = to
        oldNode.sampled = this._tick
        this._natAdd(to.host, to.port)
      }

      oldNode.pinged = oldNode.seen = this._tick
      this.nodes.add(oldNode)
      return
    }

    this._addNode({
      id: from.id,
      port: from.port,
      host: from.host,
      to,
      sampled: 0,
      added: this._tick,
      pinged: this._tick, // last time we interacted with them
      seen: this._tick, // last time we heard from them
      downHints: 0,
      prev: null,
      next: null
    })
  }

  _addNode(node) {
    if (this.nodes.has(node) || b4a.equals(node.id, this.table.id)) return

    node.added = node.pinged = node.seen = this._tick

    if (!this.table.add(node)) return
    this.nodes.add(node)

    if (node.to && node.sampled === 0) {
      node.sampled = this._tick
      this._natAdd(node.to.host, node.to.port)
    }

    this.emit('add-node', node)
  }

  _removeStaleNode(node, lastSeen) {
    if (node.seen <= lastSeen) this._removeNode(node)
  }

  _removeNode(node) {
    if (!this.nodes.has(node)) return

    this.table.remove(node.id)
    this.nodes.remove(node)

    this.emit('remove-node', node)
  }

  _onwakeup() {
    this._tick += 2 * OLD_NODE // bump the tick enough that everything appears old.
    this._tick += 8 - (this._tick & 7) - 2 // triggers a series of pings in two ticks
    this._stableTicks = MORE_STABLE_TICKS
    this._refreshTicks = 1 // triggers a refresh next tick (allow network time to wake up also)
    this._lastHost = null // clear network cache check
    this.health.reset()

    if (this.adaptive) {
      // TODO: re-enable this as soon as we find out why this is over triggering in some edge cases
      // this.firewalled = true
      // this.io.firewalled = true

      if (!this.ephemeral) {
        this.ephemeral = true
        this.io.ephemeral = true
        this.emit('ephemeral')
      }
    }

    this.emit('wakeup')
  }

  _onfullrow(newNode, row) {
    if (!this.bootstrapped || this._repinging >= 3) return

    let oldest = null
    for (const node of row.nodes) {
      if (node.pinged === this._tick) continue
      if (
        oldest === null ||
        oldest.pinged > node.pinged ||
        (oldest.pinged === node.pinged && oldest.added > node.added)
      ) {
        oldest = node
      }
    }

    if (oldest === null) return
    if (this._tick - oldest.pinged < RECENT_NODE && this._tick - oldest.added > OLD_NODE) return

    this._repingAndSwap(newNode, oldest)
  }

  _onnetworkchange(interfaces) {
    this.emit('network-change', interfaces)
    this.emit('network-update')
  }

  _repingAndSwap(newNode, oldNode) {
    const self = this
    const lastSeen = oldNode.seen

    oldNode.pinged = this._tick

    this._repinging++
    this._request(
      { id: null, host: oldNode.host, port: oldNode.port },
      false,
      true,
      PING,
      null,
      null,
      null,
      onsuccess,
      onswap
    )

    function onsuccess(m) {
      if (oldNode.seen <= lastSeen) return onswap()
      self._repinging--
    }

    function onswap(e) {
      self._repinging--
      self._removeNode(oldNode)
      self._addNode(newNode)
    }
  }

  _onrequest(req, external) {
    if (req.from.id !== null) {
      this._addNodeFromNetwork(!external, req.from, req.to)
    }

    if (req.internal) {
      switch (req.command) {
        // standard keep alive call
        case PING: {
          req.sendReply(0, null, false, false)
          return
        }
        case DELAYED_PING: {
          this._ondelayedping(req)
          return
        }
        // check if the other side can receive a message to their other socket
        case PING_NAT: {
          if (req.value === null || req.value.byteLength < 2) return
          const port = c.uint16.decode({ start: 0, end: 2, buffer: req.value })
          if (port === 0) return
          req.from.port = port
          req.sendReply(0, null, false, false)
          return
        }
        // empty dht reply back
        case FIND_NODE: {
          if (!req.target) return
          req.sendReply(0, null, false, true)
          return
        }
        // "this is node you sent me is down" - let's try to ping it
        case DOWN_HINT: {
          if (req.value === null || req.value.byteLength < 6) return
          if (this._checks < 10) {
            sodium.crypto_generichash(TMP, req.value.subarray(0, 6))
            const node = this.table.get(TMP)
            if (node && (node.pinged < this._tick || node.downHints === 0)) {
              node.downHints++
              this._check(node)
            }
          }
          req.sendReply(0, null, false, false)
          return
        }
      }

      req.sendReply(UNKNOWN_COMMAND, null, false, req.target !== null)
      return
    }

    // ask the user to handle it or reply back with a bad command
    if (this.onrequest(req) === false) {
      req.sendReply(UNKNOWN_COMMAND, null, false, req.target !== null)
    }
  }

  onrequest(req) {
    return this.emit('request', req)
  }

  _ondelayedping(req) {
    if (req.value === null || req.value.byteLength < 4) return
    const delayMs = c.uint32.decode({ start: 0, end: 4, buffer: req.value })
    if (delayMs > this.maxPingDelay) return
    const timer = setTimeout(() => {
      if (this.destroyed) return
      this._pendingTimers.delete(timer)
      req.sendReply(0, null, false, false)
    }, delayMs)
    this._pendingTimers.add(timer)
  }

  _onresponse(res, external) {
    this._addNodeFromNetwork(!external, res.from, res.to)
  }

  _ontimeout(req) {
    if (!req.to.id) return
    const node = this.table.get(req.to.id)
    if (node) this._removeNode(node)
  }

  _pingSome() {
    let cnt = this.io.inflight.length > 2 ? 3 : 5
    let oldest = this.nodes.oldest

    // tiny dht, pinged the bootstrap again
    if (!oldest) {
      this.refresh()
      return
    }

    // we've recently pinged the oldest one, so only trigger a couple of repings
    if (this._tick - oldest.pinged < RECENT_NODE) {
      cnt = 2
    }

    while (cnt--) {
      if (!oldest || this._tick === oldest.pinged) continue
      this._check(oldest)
      oldest = oldest.next
    }
  }

  _check(node) {
    node.pinged = this._tick

    const lastSeen = node.seen
    const onresponse = () => {
      this._checks--
      this._removeStaleNode(node, lastSeen)
    }
    const onerror = () => {
      this._checks--
      this._removeNode(node)
    }

    this._checks++
    this._request(
      { id: null, host: node.host, port: node.port },
      false,
      true,
      PING,
      null,
      null,
      null,
      onresponse,
      onerror
    )
  }

  _ontick() {
    const time = Date.now()

    if (time - this._lastTick > SLEEPING_INTERVAL && this.suspended === false) {
      this._onwakeup()
    } else {
      this._tick++
    }

    this._lastTick = time

    if (!this.bootstrapped || this.suspended) return

    if (this.adaptive && this.ephemeral && --this._stableTicks <= 0) {
      if (this._lastHost === this._nat.host) {
        // do not recheck the same network...
        this._stableTicks = MORE_STABLE_TICKS
      } else {
        this._updateNetworkState() // the promise returned here never fails so just ignore it
      }
    }

    if ((this._tick & 7) === 0) {
      this._pingSome()
    }

    if (
      ((this._tick & 63) === 0 && this.nodes.length < this.table.k) ||
      --this._refreshTicks <= 0
    ) {
      this.refresh()
    }

    this._downHintsSentPerTick = 0
    this.health.update()
  }

  async _updateNetworkState(onlyFirewall = false) {
    if (!this.ephemeral) return false
    if (onlyFirewall && !this.firewalled) return false

    const { host, port } = this._nat

    if (!onlyFirewall) {
      // remember what host we checked and reset the counter
      this._stableTicks = MORE_STABLE_TICKS
      this._lastHost = host
    }

    // check if we have a consistent host and port
    if (host === null || port === 0) {
      return false
    }

    const natSampler = this.firewalled ? new NatSampler() : this._nat

    // ask remote nodes to ping us on our server socket to see if we have the port open
    const firewalled = this.firewalled && (await this._checkIfFirewalled(natSampler))
    if (firewalled) return false

    this.firewalled = this.io.firewalled = false

    // incase it's called in parallel for some reason, or if our nat status somehow changed
    if (!this.ephemeral || host !== this._nat.host || port !== this._nat.port) return false
    // if the firewall probe returned a different host / non consistent port, bail as well
    if (natSampler.host !== host || natSampler.port === 0) return false

    const id = peer.id(natSampler.host, natSampler.port)

    if (!onlyFirewall) {
      this.ephemeral = this.io.ephemeral = false
    }

    if (natSampler !== this._nat) {
      const prevHost = this._nat.host
      const prevPort = this._nat.port

      this._nonePersistentSamples = []
      this._nat = natSampler

      if (prevHost !== this._nat.host || prevPort !== this._nat.port) {
        this.emit('nat-update', this._nat.host, this._nat.port)
      }
    }

    // TODO: we should make this a bit more defensive in terms of using more
    // resources to make sure that the new routing table contains as many alive nodes
    // as possible, vs blindly copying them over...

    // all good! copy over the old routing table to the new one
    if (!b4a.equals(this.table.id, id)) {
      const nodes = this.table.toArray()

      this.table = this.io.table = new Table(id)

      for (const node of nodes) {
        if (b4a.equals(node.id, id)) continue
        if (!this.table.add(node)) this.nodes.remove(node)
      }

      this.table.on('row', this._onrow)

      // we need to rebootstrap/refresh since we updated our id
      if (this.bootstrapped) this.refresh()
    }

    if (!this.ephemeral) {
      this.emit('persistent')
    }

    return true
  }

  async *_resolveBootstrapNodes() {
    for (let { host, port } of this.bootstrapNodes) {
      let doLookup = false

      if (host.indexOf('@') === -1) {
        doLookup = true
      } else {
        const [suggestedIP, fallbackHost] = host.split('@')
        try {
          await this.ping({ host: suggestedIP, port })
          host = suggestedIP
        } catch {
          host = fallbackHost
          doLookup = true
        }
      }

      if (doLookup) {
        try {
          host = UDX.isIPv4(host) ? host : (await this.udx.lookup(host, { family: 4 })).host
        } catch {
          continue
        }
      }

      yield {
        id: peer.id(host, port),
        host,
        port
      }
    }
  }

  async _addBootstrapNodes(nodes) {
    for await (const node of this._resolveBootstrapNodes()) {
      nodes.push(node)
    }
  }

  async _checkIfFirewalled(natSampler = new NatSampler()) {
    const nodes = []
    for (let node = this.nodes.latest; node && nodes.length < 5; node = node.prev) {
      nodes.push(node)
    }

    if (nodes.length < 5) await this._addBootstrapNodes(nodes)
    // if no nodes are available, including bootstrappers - bail
    if (nodes.length === 0) return true

    const hosts = new Set()
    const value = b4a.allocUnsafe(2)

    c.uint16.encode({ start: 0, end: 2, buffer: value }, this.io.serverSocket.address().port)

    // double check they actually came on the server socket...
    this.io.serverSocket.on('message', onmessage)

    const pongs = await requestAll(this, true, PING_NAT, value, nodes)

    let count = 0
    for (const res of pongs) {
      if (hosts.has(res.from.host)) {
        count++
        natSampler.add(res.to.host, res.to.port)
      }
    }

    this.io.serverSocket.removeListener('message', onmessage)

    // if we got no or very few replies, consider it a fluke
    if (count < (nodes.length >= 5 ? 3 : 1)) return true

    // check that the server socket has the same ip as the client socket
    if (natSampler.host === null || this._nat.host !== natSampler.host) return true

    // check that the local port of the server socket is the same as the remote port
    // TODO: we might want a flag to opt out of this heuristic for specific remapped port servers
    if (natSampler.port === 0 || natSampler.port !== this.io.serverSocket.address().port) {
      return true
    }

    return false

    function onmessage(_, { host }) {
      hosts.add(host)
    }
  }

  _backgroundQuery(target) {
    this._refreshTicks = REFRESH_TICKS

    const backgroundCon = Math.min(this.concurrency, Math.max(2, (this.concurrency / 8) | 0))
    const q = new Query(this, target, true, FIND_NODE, null, {
      concurrency: backgroundCon
    })

    q.on('data', () => {
      // yield to other traffic
      q.concurrency = this.io.inflight.length < 3 ? this.concurrency : backgroundCon
    })

    return q
  }

  // called by health
  _online() {
    if (this.online && !this.degraded) return
    this.online = true
    this.degraded = false
    this.emit('network-update')
  }

  // called by health
  _degraded() {
    if (this.degraded) return
    this.online = true
    this.degraded = true
    this.emit('network-update')
  }

  // called by health
  _offline() {
    if (!this.online) return
    this.online = false
    this.degraded = false
    this.emit('network-update')
  }
}

DHT.OK = 0
DHT.ERROR_UNKNOWN_COMMAND = UNKNOWN_COMMAND
DHT.ERROR_INVALID_TOKEN = INVALID_TOKEN

module.exports = DHT

function localIP(udx, family = 4) {
  let host = null

  for (const n of udx.networkInterfaces()) {
    if (n.family !== family || n.internal) continue

    // mac really likes en0, mb a better way but this shouldnt be bad anywhere so return now
    if (n.name === 'en0') return n.host

    // otherwise pick the first non internal host (let the loop continue in case we see en0)
    if (host === null) host = n.host
  }

  return host || (family === 4 ? '127.0.0.1' : '::1')
}

function parseNode(s) {
  if (typeof s === 'object') return s
  if (typeof s === 'number') return { host: '127.0.0.1', port: s }
  const [host, port] = s.split(':')
  if (!port) throw new Error('Bootstrap node format is host:port')

  return {
    host,
    port: Number(port)
  }
}

function randomBytes(n) {
  const b = b4a.alloc(n)
  sodium.randombytes_buf(b)
  return b
}

function randomOffset(n) {
  return n - ((Math.random() * 0.5 * n) | 0)
}

function requestAll(dht, internal, command, value, nodes) {
  let missing = nodes.length
  const replies = []

  return new Promise((resolve) => {
    for (const node of nodes) {
      const req = dht._request(
        node,
        false,
        internal,
        command,
        null,
        value,
        null,
        onsuccess,
        onerror
      )
      if (!req) return resolve(replies)
    }

    function onsuccess(res) {
      replies.push(res)
      if (--missing === 0) resolve(replies)
    }

    function onerror() {
      if (--missing === 0) resolve(replies)
    }
  })
}

function noop() {}
exports.PING = 0
exports.PING_NAT = 1
exports.FIND_NODE = 2
exports.DOWN_HINT = 3
exports.DELAYED_PING = 4
module.exports = class DHTError extends Error {
  constructor(msg, code, fn = DHTError) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'DHTError'
  }

  static UNKNOWN_COMMAND = 1
  static INVALID_TOKEN = 2

  static REQUEST_TIMEOUT(msg = 'Request timed out') {
    return new DHTError(msg, 'REQUEST_TIMEOUT', DHTError.REQUEST_TIMEOUT)
  }

  static REQUEST_DESTROYED(msg = 'Request destroyed') {
    return new DHTError(msg, 'REQUEST_DESTROYED', DHTError.REQUEST_DESTROYED)
  }

  static IO_SUSPENDED(msg = 'I/O suspended') {
    return new DHTError(msg, 'IO_SUSPENDED', DHTError.IO_SUSPENDED)
  }
}
const MAX_HEALTH_WINDOW = 4
const OFFLINE_THRESHOLD = 2
const IDLE_THRESHOLD = 4
const DEGRADED_TIMEOUT_RATE_THRESHOLD = 0.5

module.exports = class NetworkHealth {
  constructor(dht) {
    this._dht = dht
    this._window = []
    this._head = -1
    this._offlineTicks = 0
    this._degradedTicks = 0
    this._healthyTicks = 0
    this.online = true
    this.degraded = false
  }

  get oldest() {
    return this._window[this._tail]
  }

  get previous() {
    return this._window[(this._head - 1 + MAX_HEALTH_WINDOW) % MAX_HEALTH_WINDOW]
  }

  get newest() {
    return this._window[this._head]
  }

  get responses() {
    if (!this.newest || !this.previous) return 0
    return this.newest.responses - this.previous.responses
  }

  get timeouts() {
    if (!this.newest || !this.previous) return 0
    return this.newest.timeouts - this.previous.timeouts
  }

  get timeoutsRate() {
    if (this.timeouts === 0) return 0
    return this.timeouts / (this.responses + this.timeouts)
  }

  get cold() {
    return this._window.length < MAX_HEALTH_WINDOW
  }

  get idle() {
    return this.responses + this.timeouts < IDLE_THRESHOLD
  }

  get stats() {
    return {
      online: this.online,
      degraded: this.degraded,
      cold: this.cold,
      idle: this.idle,
      responses: this.responses,
      timeouts: this.timeouts,
      timeoutsRate: this.timeoutsRate
    }
  }

  get _tail() {
    return (this._head + 1) % MAX_HEALTH_WINDOW
  }

  reset() {
    this._window = []
    this._head = -1
    this._offlineTicks = 0
    this._degradedTicks = 0
    this._healthyTicks = 0
    this.online = true
    this.degraded = false
    this._dht._online()
  }

  update() {
    // update counters before dropping oldest
    if (this.oldest?.degraded) this._degradedTicks--
    else if (this.oldest?.degraded === false) this._healthyTicks--

    // move window
    this._head = this._tail
    this._window[this._head] = {
      responses: this._dht.stats.requests.responses,
      timeouts: this._dht.stats.requests.timeouts
    }

    // skip state changes
    if (this.cold || this.idle) return

    // update newest
    this.newest.offline = this.responses === 0
    this.newest.degraded =
      !this.newest.offline && this.timeoutsRate > DEGRADED_TIMEOUT_RATE_THRESHOLD

    // update counters
    if (this.newest.offline) this._offlineTicks++
    else {
      this._offlineTicks = 0
      if (this.newest.degraded) this._degradedTicks++
      else this._healthyTicks++
    }

    // check online/offline
    if (!this.newest.offline) this.online = true
    else if (this._offlineTicks >= OFFLINE_THRESHOLD) this.online = false

    // check degraded
    if (!this.online || this._healthyTicks === MAX_HEALTH_WINDOW) this.degraded = false
    else if (this._degradedTicks === MAX_HEALTH_WINDOW) this.degraded = true

    // fire events
    if (this.online && !this.degraded) this._dht._online()
    else if (this.degraded) this._dht._degraded()
    else this._dht._offline()
  }
}
const FIFO = require('fast-fifo')
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const b4a = require('b4a')
const AdaptiveTimeout = require('adaptive-timeout')
const peer = require('./peer')
const { INVALID_TOKEN, REQUEST_TIMEOUT, REQUEST_DESTROYED, IO_SUSPENDED } = require('./errors')

const VERSION = 0b11
const RESPONSE_ID = (0b0001 << 4) | VERSION
const REQUEST_ID = (0b0000 << 4) | VERSION
const EMPTY_ARRAY = []
const MAX_WINDOW = 80

module.exports = class IO {
  constructor(
    table,
    udx,
    {
      maxWindow = MAX_WINDOW,
      port = 0,
      host = '0.0.0.0',
      anyPort = true,
      firewalled = true,
      onrequest,
      onresponse = noop,
      ontimeout = noop,
      adaptiveTimeout
    } = {}
  ) {
    this.table = table
    this.udx = udx
    this.inflight = []
    this.clientSocket = null
    this.serverSocket = null
    this.firewalled = firewalled !== false
    this.ephemeral = true
    this.congestion = new CongestionWindow(maxWindow)
    this.networkInterfaces = udx.watchNetworkInterfaces()
    this.suspended = false

    this.stats = {
      requests: {
        active: 0,
        total: 0,
        responses: 0,
        timeouts: 0,
        retries: 0
      },
      commands: [
        { tx: 0, rx: 0 }, // tx = transmitted, rx = received
        { tx: 0, rx: 0 },
        { tx: 0, rx: 0 },
        { tx: 0, rx: 0 }
      ]
    }

    this.onrequest = onrequest
    this.onresponse = onresponse
    this.ontimeout = ontimeout

    this._pending = new FIFO()
    this._rotateSecrets = 10
    this._tid = (Math.random() * 65536) | 0
    this._secrets = null
    this._drainInterval = null
    this._destroying = null
    this._binding = null

    // port can be a number or a range [start, to]
    this.portRange = port.length ? port : port === 0 ? [0, 0] : [port, port + 5]

    this._host = host
    this._anyPort = anyPort !== false
    this._boundServerPort = 0
    this._boundClientPort = 0

    this._adt = adaptiveTimeout ? new AdaptiveTimeout(adaptiveTimeout) : null
  }

  static DEFAULT_MAX_WINDOW = MAX_WINDOW

  onmessage(socket, buffer, { host, port }) {
    if (buffer.byteLength < 2 || !(port > 0 && port < 65536) || this.suspended === true) return

    const from = { id: null, host, port }
    const state = { start: 1, end: buffer.byteLength, buffer }
    const expectedSocket = this.firewalled ? this.clientSocket : this.serverSocket
    const external = socket !== expectedSocket

    if (buffer[0] === REQUEST_ID) {
      const req = Request.decode(this, socket, from, state)
      if (req === null) return
      if (
        req.token !== null &&
        !b4a.equals(req.token, this.token(req.from, 1)) &&
        !b4a.equals(req.token, this.token(req.from, 0))
      ) {
        req.error(INVALID_TOKEN, { token: true })
        return
      }
      this.onrequest(req, external)
      return
    }

    if (buffer[0] === RESPONSE_ID) {
      const res = decodeReply(from, state)
      if (res === null) return

      for (let i = 0; i < this.inflight.length; i++) {
        const req = this.inflight[i]
        if (req.tid !== res.tid) continue

        res.rtt = Date.now() - req._timestamp

        if (this._adt && req.sent <= 2) {
          this._adt.put(`${req.to.host}:${req.to.port}`, res.rtt)
        }

        if (i === this.inflight.length - 1) this.inflight.pop()
        else this.inflight[i] = this.inflight.pop()

        if (req.session) req.session._detach(req)

        // TODO: Auto retry here if errors.INVALID_TOKEN is returned?

        if (req._timeout) {
          clearTimeout(req._timeout)
          req._timeout = null
        }

        this.congestion.recv()

        if (req.internal && req.command < this.stats.commands.length) {
          this.stats.commands[req.command].rx++
        }

        this.stats.requests.active--
        this.stats.requests.responses++

        this.onresponse(res, external)
        req.onresponse(res, req)
        break
      }
    }
  }

  token(addr, i) {
    if (this._secrets === null) {
      const buf = b4a.alloc(64)
      this._secrets = [buf.subarray(0, 32), buf.subarray(32, 64)]
      sodium.randombytes_buf(this._secrets[0])
      sodium.randombytes_buf(this._secrets[1])
    }

    const token = b4a.allocUnsafe(32)
    sodium.crypto_generichash(token, b4a.from(addr.host), this._secrets[i])
    return token
  }

  async destroy() {
    if (this._destroying) return this._destroying
    this._destroying = this._destroy()
    return this._destroying
  }

  async _destroy() {
    // simplifies timing to await the bind here also, although it might be unneeded
    await this.bind()
    await this._clear(false)
  }

  async _clear(suspended) {
    if (this._drainInterval) {
      clearInterval(this._drainInterval)
      this._drainInterval = null
    }

    while (this.inflight.length) {
      const req = this.inflight.pop()
      if (req._timeout) clearTimeout(req._timeout)
      req._timeout = null
      req.destroyed = true

      if (req.session) req.session._detach(req)

      this.congestion.recv()
      this.stats.requests.active--

      req.onerror(suspended ? IO_SUSPENDED() : REQUEST_DESTROYED(), req)
    }

    await Promise.allSettled([this.serverSocket.close(), this.clientSocket.close()])

    this.networkInterfaces.destroy()
  }

  async suspend() {
    this.suspended = true
    await this._clear(true)

    this.congestion.clear()

    if (this._drainInterval) {
      clearInterval(this._drainInterval)
      this._drainInterval = null
    }
  }

  async _rebind(binding) {
    if (binding) await binding
    if (this._destroying) return this._destroying
    await this._bindSockets()
    this.networkInterfaces = this.udx.watchNetworkInterfaces()
  }

  resume() {
    this.suspended = false
    const binding = this._binding
    this._binding = this._rebind(binding)
    return this._binding
  }

  bind() {
    if (this._binding) return this._binding
    this._binding = this._bindSockets()
    return this._binding
  }

  async _bindSockets() {
    const serverSocket = this.udx.createSocket()

    const candidatePorts = []

    // Retrying previous port always has precedence
    if (this._boundServerPort) candidatePorts.push(this._boundServerPort)

    for (let i = this.portRange[0]; i < this.portRange[1]; i++) candidatePorts.push(i)

    for (const port of candidatePorts) {
      if (serverSocket.bound) break

      try {
        serverSocket.bind(port, this._host)
      } catch (err) {
        if (!this._anyPort) {
          await serverSocket.close()
          throw err
        }
      }
    }

    if (!serverSocket.bound) {
      try {
        serverSocket.bind(0, this._host)
      } catch (err) {
        await serverSocket.close()
        throw err
      }
    }

    const clientSocket = this.udx.createSocket()

    try {
      clientSocket.bind(this._boundClientPort || 0, this._host)
    } catch {
      try {
        clientSocket.bind(0, this._host)
      } catch (err) {
        await serverSocket.close()
        await clientSocket.close()
        throw err
      }
    }

    this._boundServerPort = serverSocket.address().port
    this._boundClientPort = clientSocket.address().port

    this.clientSocket = clientSocket
    this.serverSocket = serverSocket

    this.serverSocket.on('message', this.onmessage.bind(this, this.serverSocket))
    this.clientSocket.on('message', this.onmessage.bind(this, this.clientSocket))

    if (this._drainInterval === null) {
      this._drainInterval = setInterval(this._drain.bind(this), 750)
      if (this._drainInterval.unref) this._drainInterval.unref()
    }

    for (const req of this.inflight) {
      if (!req.socket) req.socket = this.firewalled ? this.clientSocket : this.serverSocket
      req.sent = 0
      req.send(false)
    }
  }

  _drain() {
    if (this._secrets !== null && --this._rotateSecrets === 0) {
      this._rotateSecrets = 10
      const tmp = this._secrets[0]
      this._secrets[0] = this._secrets[1]
      this._secrets[1] = tmp
      sodium.crypto_generichash(tmp, tmp)
    }

    this.congestion.drain()

    while (!this.congestion.isFull()) {
      const p = this._pending.shift()
      if (p === undefined) return
      p._sendNow()
    }
  }

  createRequest(to, token, internal, command, target, value, session, ttl) {
    if (this._destroying !== null) return null

    if (this._tid === 65536) this._tid = 0

    const tid = this._tid++
    const socket = this.firewalled ? this.clientSocket : this.serverSocket

    const req = new Request(
      this,
      socket,
      tid,
      null,
      to,
      token,
      internal,
      command,
      target,
      value,
      session,
      ttl || 0
    )
    this.inflight.push(req)
    if (session) session._attach(req)

    if (internal && command < this.stats.commands.length) {
      this.stats.commands[command].tx++
    }

    this.stats.requests.active++
    this.stats.requests.total++

    return req
  }
}

class Request {
  constructor(io, socket, tid, from, to, token, internal, command, target, value, session, ttl) {
    this.socket = socket
    this.tid = tid
    this.from = from
    this.to = to
    this.token = token
    this.command = command
    this.target = target
    this.value = value
    this.internal = internal
    this.session = session
    this.ttl = ttl
    this.index = -1
    this.sent = 0
    this.retries = 3
    this.destroyed = false
    this.timeout = 0

    this.oncycle = noop
    this.onerror = noop
    this.onresponse = noop

    this._buffer = null
    this._io = io
    this._timeout = null
    this._timestamp = Date.now()
  }

  static decode(io, socket, from, state) {
    try {
      const flags = c.uint.decode(state)
      const tid = c.uint16.decode(state)
      const to = peer.ipv4.decode(state)
      const id = flags & 1 ? c.fixed32.decode(state) : null
      const token = flags & 2 ? c.fixed32.decode(state) : null
      const internal = (flags & 4) !== 0
      const command = c.uint.decode(state)
      const target = flags & 8 ? c.fixed32.decode(state) : null
      const value = flags & 16 ? c.buffer.decode(state) : null

      if (id !== null) from.id = validateId(id, from)

      return new Request(
        io,
        socket,
        tid,
        from,
        to,
        token,
        internal,
        command,
        target,
        value,
        null,
        0
      )
    } catch {
      return null
    }
  }

  reply(value, opts = {}) {
    const socket = opts.socket || this.socket
    const to = opts.to || this.from
    this._sendReply(0, value || null, opts.token !== false, opts.closerNodes !== false, to, socket)
  }

  error(code, opts = {}) {
    const socket = opts.socket || this.socket
    const to = opts.to || this.from
    this._sendReply(code, null, opts.token === true, opts.closerNodes !== false, to, socket)
  }

  relay(value, to, opts) {
    const socket = (opts && opts.socket) || this.socket
    const buffer = this._encodeRequest(null, value, to, socket)
    socket.trySend(buffer, to.port, to.host, this.ttl)
  }

  send(force = false) {
    if (this.destroyed) return

    if (this.socket === null) return
    if (this._buffer === null) {
      this._buffer = this._encodeRequest(this.token, this.value, this.to, this.socket)
    }

    if (!force && this._io.congestion.isFull()) {
      this._io._pending.push(this)
      return
    }

    this._sendNow()
  }

  sendReply(error, value, token, hasCloserNodes) {
    this._sendReply(error, value, token, hasCloserNodes, this.from, this.socket, null)
  }

  _sendNow() {
    if (this.destroyed) return
    this.sent++
    this._io.congestion.send()
    this.socket.trySend(this._buffer, this.to.port, this.to.host, this.ttl)
    if (this._timeout) clearTimeout(this._timeout)
    const value =
      this.timeout || this._io._adt?.get(`${this.to.host}:${this.to.port}`, this.sent) || 1000
    this._timeout = setTimeout(oncycle, value, this)
  }

  destroy(err) {
    if (this.destroyed) return
    this.destroyed = true

    if (this._timeout) {
      clearTimeout(this._timeout)
      this._timeout = null
    }

    const i = this._io.inflight.indexOf(this)
    if (i === -1) return

    if (i === this._io.inflight.length - 1) this._io.inflight.pop()
    else this._io.inflight[i] = this._io.inflight.pop()

    if (this.session) this.session._detach(this)

    this._io.stats.requests.active--
    this._io.congestion.recv()

    this.onerror(err || REQUEST_DESTROYED(), this)
  }

  _sendReply(error, value, token, hasCloserNodes, from, socket) {
    if (socket === null || this.destroyed) return

    const id = this._io.ephemeral === false && socket === this._io.serverSocket
    const closerNodes =
      this.target !== null && hasCloserNodes ? this._io.table.closest(this.target) : EMPTY_ARRAY
    const state = { start: 0, end: 1 + 1 + 6 + 2, buffer: null } // (type | version) + flags + to + tid

    if (id) state.end += 32
    if (token) state.end += 32
    if (closerNodes.length > 0) peer.ipv4Array.preencode(state, closerNodes)
    if (error > 0) c.uint.preencode(state, error)
    if (value) c.buffer.preencode(state, value)

    state.buffer = b4a.allocUnsafe(state.end)
    state.buffer[state.start++] = RESPONSE_ID
    state.buffer[state.start++] =
      (id ? 1 : 0) |
      (token ? 2 : 0) |
      (closerNodes.length > 0 ? 4 : 0) |
      (error > 0 ? 8 : 0) |
      (value ? 16 : 0)

    c.uint16.encode(state, this.tid)
    peer.ipv4.encode(state, from)

    if (id) c.fixed32.encode(state, this._io.table.id)
    if (token) c.fixed32.encode(state, this._io.token(from, 1))
    if (closerNodes.length > 0) peer.ipv4Array.encode(state, closerNodes)
    if (error > 0) c.uint.encode(state, error)
    if (value) c.buffer.encode(state, value)

    socket.trySend(state.buffer, from.port, from.host, this.ttl)
  }

  _encodeRequest(token, value, to, socket) {
    const id = this._io.ephemeral === false && socket === this._io.serverSocket
    const state = { start: 0, end: 1 + 1 + 6 + 2, buffer: null } // (type | version) + flags + to + tid

    if (id) state.end += 32
    if (token) state.end += 32

    c.uint.preencode(state, this.command)

    if (this.target) state.end += 32
    if (value) c.buffer.preencode(state, value)

    state.buffer = b4a.allocUnsafe(state.end)
    state.buffer[state.start++] = REQUEST_ID
    state.buffer[state.start++] =
      (id ? 1 : 0) |
      (token ? 2 : 0) |
      (this.internal ? 4 : 0) |
      (this.target ? 8 : 0) |
      (value ? 16 : 0)

    c.uint16.encode(state, this.tid)
    peer.ipv4.encode(state, to)

    if (id) c.fixed32.encode(state, this._io.table.id)
    if (token) c.fixed32.encode(state, token)

    c.uint.encode(state, this.command)

    if (this.target) c.fixed32.encode(state, this.target)
    if (value) c.buffer.encode(state, value)

    return state.buffer
  }
}

class CongestionWindow {
  constructor(maxWindow) {
    this._i = 0
    this._total = 0
    this._window = [0, 0, 0, 0]
    this._maxWindow = maxWindow
  }

  clear() {
    this._i = 0
    this._total = 0
    this._window = [0, 0, 0, 0]
  }

  isFull() {
    return this._total >= 2 * this._maxWindow || this._window[this._i] >= this._maxWindow
  }

  recv() {
    if (this._window[this._i] > 0) {
      this._window[this._i]--
      this._total--
    }
  }

  send() {
    this._total++
    this._window[this._i]++
  }

  drain() {
    this._i = (this._i + 1) & 3
    this._total -= this._window[this._i]
    this._window[this._i] = 0 // clear oldest
  }
}

function noop() {}

function oncycle(req) {
  req._timeout = null
  req.oncycle(req)
  if (req.sent > req.retries) {
    req._io.stats.requests.timeouts++
    req.destroy(REQUEST_TIMEOUT())
    req._io.ontimeout(req)
  } else {
    req._io.stats.requests.retries++
    req.send()
  }
}

function decodeReply(from, state) {
  try {
    const flags = c.uint.decode(state)
    const tid = c.uint16.decode(state)
    const to = peer.ipv4.decode(state)
    const id = flags & 1 ? c.fixed32.decode(state) : null
    const token = flags & 2 ? c.fixed32.decode(state) : null
    const closerNodes = flags & 4 ? peer.ipv4Array.decode(state) : null
    const error = flags & 8 ? c.uint.decode(state) : 0
    const value = flags & 16 ? c.buffer.decode(state) : null

    if (id !== null) from.id = validateId(id, from)

    return { tid, rtt: 0, from, to, token, closerNodes, error, value }
  } catch {
    return null
  }
}

function validateId(id, from) {
  const expected = peer.id(from.host, from.port)
  return b4a.equals(expected, id) ? expected : null
}
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const b4a = require('b4a')

const ipv4 = {
  ...c.ipv4Address,
  decode(state) {
    const ip = c.ipv4Address.decode(state)
    return {
      id: null, // populated by the callee
      host: ip.host,
      port: ip.port
    }
  }
}

module.exports = { id, ipv4, ipv4Array: c.array(ipv4) }

function id(host, port, out = b4a.allocUnsafeSlow(32)) {
  const addr = out.subarray(0, 6)
  ipv4.encode({ start: 0, end: 6, buffer: addr }, { host, port })
  sodium.crypto_generichash(out, addr)
  return out
}
const { Readable, getStreamError } = require('streamx')
const b4a = require('b4a')
const peer = require('./peer')
const { DOWN_HINT } = require('./commands')

const DONE = []
const DOWN = []

module.exports = class Query extends Readable {
  constructor(dht, target, internal, command, value, opts = {}) {
    super()

    dht.stats.queries.total++
    dht.stats.queries.active++

    this.force = !!opts.force
    this.dht = dht
    this.k = this.dht.table.k
    this.target = target
    this.internal = internal
    this.command = command
    this.value = value
    this.errors = 0
    this.successes = 0
    this.concurrency = opts.concurrency || this.dht.concurrency
    this.inflight = 0
    this.map = opts.map || defaultMap
    this.retries =
      opts.retries === 0 ? 0 : opts.retries || (this.internal && command === DOWN_HINT ? 3 : 5)
    this.closestReplies = []

    this._slow = 0
    this._slowdown = false
    this._seen = new Map()
    this._pending = []
    this._fromTable = false
    this._commit = opts.commit === true ? autoCommit : opts.commit || null
    this._commiting = false
    this._session = opts.session || dht.session()
    this._autoDestroySession = !opts.session
    this._onlyClosestNodes = false

    this._onvisitbound = this._onvisit.bind(this)
    this._onerrorbound = this._onerror.bind(this)
    this._oncyclebound = this._oncycle.bind(this)

    const nodes = opts.nodes || opts.closestNodes
    const replies = opts.replies || opts.closestReplies

    // add them reverse as we pop below
    if (nodes) {
      for (let i = nodes.length - 1; i >= 0; i--) {
        const node = nodes[i]
        this._addPending(
          {
            id: node.id || peer.id(node.host, node.port),
            host: node.host,
            port: node.port
          },
          null
        )
      }
    } else if (replies) {
      for (let i = replies.length - 1; i >= 0; i--) {
        this._addPending(replies[i].from, null)
      }
    }

    if (opts.onlyClosestNodes) this._onlyClosestNodes = true
  }

  get closestNodes() {
    const nodes = new Array(this.closestReplies.length)

    for (let i = 0; i < nodes.length; i++) {
      nodes[i] = this.closestReplies[i].from
    }

    return nodes
  }

  finished() {
    return new Promise((resolve, reject) => {
      if (this.destroyed) {
        const error = getStreamError(this)
        if (error) reject(error)
        else resolve()
        return
      }

      const self = this
      let error = null

      this.resume()
      this.on('error', onerror)
      this.on('close', onclose)

      function onclose() {
        self.removeListener('error', onerror)
        self.removeListener('close', onclose)
        if (error) reject(error)
        else resolve()
      }

      function onerror(err) {
        error = err
      }
    })
  }

  _addFromTable() {
    if (this._pending.length >= this.k) return
    this._fromTable = true

    const closest = this.dht.table.closest(this.target, this.k - this._pending.length)

    for (const node of closest) {
      this._addPending({ id: node.id, host: node.host, port: node.port }, null)
    }
  }

  async _open(cb) {
    this._addFromTable()
    if (this._pending.length >= this.k) return cb(null)

    for await (const node of this.dht._resolveBootstrapNodes()) {
      this._addPending(node, null)
    }

    cb(null)
  }

  _isCloser(id) {
    return (
      this.closestReplies.length < this.k ||
      this._compare(id, this.closestReplies[this.closestReplies.length - 1].from.id) < 0
    )
  }

  _addPending(node, ref) {
    if (this._onlyClosestNodes) return false

    const addr = node.host + ':' + node.port
    const refs = this._seen.get(addr)
    const isCloser = this._isCloser(node.id)

    if (refs === DONE) {
      return isCloser
    }

    if (refs === DOWN) {
      if (ref) this._downHint(ref, node)
      return isCloser
    }

    if (refs) {
      if (ref !== null) refs.push(ref)
      return isCloser
    }

    if (!isCloser) {
      return false
    }

    this._seen.set(addr, ref === null ? [] : [ref])
    this._pending.push(node)

    return true
  }

  _read(cb) {
    this._readMore()
    cb(null)
  }

  _readMore() {
    if (this.destroying || this._commiting) return

    const concurrency = (this._slowdown ? 3 : this.concurrency) + this._slow

    while (this.inflight < concurrency && this._pending.length > 0) {
      const next = this._pending.pop()
      if (next && next.id && !this._isCloser(next.id)) continue
      this._visit(next)
    }

    // if reusing closest nodes, slow down after the first readMore tick to allow
    // the closest node a chance to reply before going broad to question more
    if (!this._fromTable && this.successes === 0 && this.errors === 0) {
      this._slowdown = true
    }

    if (this._pending.length > 0) return

    // if no inflight OR all the queries we are waiting on are marked as slow and we have a full result.
    if (
      this.inflight === 0 ||
      (this._slow === this.inflight && this.closestReplies.length >= this.k)
    ) {
      // if more than 3/4 failed and we only used cached nodes, try again from the routing table
      if (!this._fromTable && this.successes < this.k / 4) {
        this._addFromTable()
        this._readMore()
        return
      }

      this._flush()
    }
  }

  _flush() {
    if (this._commiting) return
    this._commiting = true

    if (this._commit === null) {
      this.push(null)
      return
    }

    const p = []
    for (const m of this.closestReplies) p.push(this._commit(m, this.dht, this))
    this._endAfterCommit(p)
  }

  _endAfterCommit(ps) {
    if (!ps.length) {
      this.destroy(new Error('Too few nodes responded'))
      return
    }

    const self = this

    let pending = ps.length
    let success = 0

    for (const p of ps) p.then(ondone, onerror)

    function ondone() {
      success++
      if (--pending === 0) self.push(null)
    }

    function onerror(err) {
      if (--pending > 0) return
      if (success) self.push(null)
      else self.destroy(err)
    }
  }

  _dec(req) {
    if (req.oncycle === noop) {
      this._slow--
    } else {
      req.oncycle = noop
    }
    this.inflight--
  }

  _onvisit(m, req) {
    this._dec(req)

    const addr = req.to.host + ':' + req.to.port
    this._seen.set(addr, DONE)

    if (this._commiting) return

    if (m.error === 0) this.successes++
    else this.errors++

    if (m.error === 0 && m.from.id !== null && this._isCloser(m.from.id)) this._pushClosest(m)

    if (m.closerNodes !== null) {
      for (const node of m.closerNodes) {
        node.id = peer.id(node.host, node.port)
        if (this.dht._filterNode !== null && !this.dht._filterNode(node)) continue
        if (b4a.equals(node.id, this.dht.table.id)) continue
        // TODO: we could continue here instead of breaking to ensure that one of the nodes in the closer list
        // is later marked as DOWN that we gossip that back
        if (!this._addPending(node, m.from)) break
      }
    }

    if (!this._fromTable && this.successes + this.errors >= this.concurrency) {
      this._slowdown = false
    }

    if (m.error !== 0) {
      this._readMore()
      return
    }

    const data = this.map(m)
    if (!data || this.push(data) !== false) {
      this._readMore()
    }
  }

  _onerror(err, req) {
    const addr = req.to.host + ':' + req.to.port
    const refs = this._seen.get(addr)

    if (err.code === 'REQUEST_TIMEOUT') {
      this._seen.set(addr, DOWN)
      for (const node of refs) this._downHint(node, req.to)
    }

    this._dec(req)
    this.errors++
    this._readMore()
  }

  _oncycle(req) {
    req.oncycle = noop
    this._slow++
    this._readMore()
  }

  _downHint(node, down) {
    // Check rate limit
    if (
      this.dht._downHintsRateLimit !== -1 &&
      this.dht._downHintsSentPerTick >= this.dht._downHintsRateLimit
    ) {
      return null
    }

    this.dht._downHintsSentPerTick++

    const state = { start: 0, end: 6, buffer: b4a.allocUnsafe(6) }
    peer.ipv4.encode(state, down)
    this.dht._request(node, false, true, DOWN_HINT, null, state.buffer, this._session, noop, noop)
  }

  _pushClosest(m) {
    this.closestReplies.push(m)
    for (let i = this.closestReplies.length - 2; i >= 0; i--) {
      const prev = this.closestReplies[i]
      const cmp = this._compare(prev.from.id, m.from.id)
      // if sorted, done!
      if (cmp < 0) break
      // if dup, splice it out (rare)
      if (cmp === 0) {
        this.closestReplies.splice(i + 1, 1)
        break
      }
      // swap and continue down
      this.closestReplies[i + 1] = prev
      this.closestReplies[i] = m
    }
    if (this.closestReplies.length > this.k) this.closestReplies.pop()
  }

  _compare(a, b) {
    for (let i = 0; i < a.length; i++) {
      if (a[i] === b[i]) continue
      const t = this.target[i]
      return (t ^ a[i]) - (t ^ b[i])
    }
    return 0
  }

  _visit(to) {
    this.inflight++

    const req = this.dht._request(
      to,
      this.force,
      this.internal,
      this.command,
      this.target,
      this.value,
      this._session,
      this._onvisitbound,
      this._onerrorbound
    )
    if (req === null) {
      this.destroy(new Error('Node was destroyed'))
      return
    }
    req.retries = this.retries
    req.oncycle = this._oncyclebound
    if (this.force) req.retries = 0
  }

  _destroy(cb) {
    this.dht.stats.queries.active--
    if (this._autoDestroySession) this._session.destroy()
    cb(null)
  }
}

function autoCommit(reply, dht, query) {
  if (!reply.token) return Promise.reject(new Error('No token received for closest node'))
  return dht.request(
    {
      token: reply.token,
      target: query.target,
      command: query.command,
      value: query.value
    },
    reply.from
  )
}

function defaultMap(m) {
  return m
}

function noop() {}
module.exports = class Session {
  constructor(dht) {
    this.dht = dht
    this.inflight = []
  }

  _attach(req) {
    req.index = this.inflight.push(req) - 1
  }

  _detach(req) {
    const i = req.index
    if (i === -1) return
    req.index = -1

    if (i === this.inflight.length - 1) this.inflight.pop()
    else {
      const req = (this.inflight[i] = this.inflight.pop())
      req.index = i
    }
  }

  query({ target, command, value }, opts = {}) {
    return this.dht.query({ target, command, value }, { ...opts, session: this })
  }

  request({ token, command, target, value }, { host, port }, opts = {}) {
    return this.dht.request(
      { token, command, target, value },
      { host, port },
      { ...opts, session: this }
    )
  }

  ping({ host, port }, opts = {}) {
    return this.dht.ping({ host, port }, { ...opts, session: this })
  }

  destroy(err) {
    while (this.inflight.length) {
      const req = this.inflight[0]
      // prevent destroyed requests from contributing to congestion counts
      this.dht.io.congestion.recv()
      req.destroy(err)
    }
  }
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "dht-rpc",
  "version": "6.27.0",
  "description": "Make RPC calls over a Kademlia based DHT",
  "main": "index.js",
  "files": [
    "index.js",
    "lib/*.js"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "dependencies": {
    "adaptive-timeout": "^1.0.1",
    "b4a": "^1.6.1",
    "bare-events": "^2.2.0",
    "compact-encoding": "^3.0.0",
    "compact-encoding-net": "^1.2.0",
    "fast-fifo": "^1.1.0",
    "kademlia-routing-table": "^1.0.1",
    "nat-sampler": "^1.0.1",
    "sodium-universal": "^5.0.0",
    "streamx": "^2.13.2",
    "time-ordered-set": "^2.0.0",
    "udx-native": "^1.5.3"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "test-suspend": "^1.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "test": "npm run test:node && npm run test:bare",
    "test:bare": "brittle-bare --coverage test.js",
    "lint": "prettier --check . && lunte",
    "test:node": "brittle-node --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/dht-rpc.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/dht-rpc/issues"
  },
  "homepage": "https://github.com/holepunchto/dht-rpc#"
}
module.exports = require('bare-events')
{
  "name": "events-universal",
  "version": "1.0.1",
  "description": "Universal wrapper for the Node.js events module",
  "exports": {
    "./package": "./package.json",
    ".": {
      "bare": "./bare.js",
      "react-native": "./react-native.js",
      "default": "./default.js"
    }
  },
  "files": [
    "index.js",
    "default.js",
    "bare.js",
    "react-native.js"
  ],
  "scripts": {
    "test": "prettier . --check"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/events-universal.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/events-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/events-universal#readme",
  "dependencies": {
    "bare-events": "^2.7.0"
  },
  "devDependencies": {
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^1.0.0"
  }
}
module.exports = class FixedFIFO {
  constructor (hwm) {
    if (!(hwm > 0) || ((hwm - 1) & hwm) !== 0) throw new Error('Max size for a FixedFIFO should be a power of two')
    this.buffer = new Array(hwm)
    this.mask = hwm - 1
    this.top = 0
    this.btm = 0
    this.next = null
  }

  clear () {
    this.top = this.btm = 0
    this.next = null
    this.buffer.fill(undefined)
  }

  push (data) {
    if (this.buffer[this.top] !== undefined) return false
    this.buffer[this.top] = data
    this.top = (this.top + 1) & this.mask
    return true
  }

  shift () {
    const last = this.buffer[this.btm]
    if (last === undefined) return undefined
    this.buffer[this.btm] = undefined
    this.btm = (this.btm + 1) & this.mask
    return last
  }

  peek () {
    return this.buffer[this.btm]
  }

  isEmpty () {
    return this.buffer[this.btm] === undefined
  }
}
const FixedFIFO = require('./fixed-size')

module.exports = class FastFIFO {
  constructor (hwm) {
    this.hwm = hwm || 16
    this.head = new FixedFIFO(this.hwm)
    this.tail = this.head
    this.length = 0
  }

  clear () {
    this.head = this.tail
    this.head.clear()
    this.length = 0
  }

  push (val) {
    this.length++
    if (!this.head.push(val)) {
      const prev = this.head
      this.head = prev.next = new FixedFIFO(2 * this.head.buffer.length)
      this.head.push(val)
    }
  }

  shift () {
    if (this.length !== 0) this.length--
    const val = this.tail.shift()
    if (val === undefined && this.tail.next) {
      const next = this.tail.next
      this.tail.next = null
      this.tail = next
      return this.tail.shift()
    }

    return val
  }

  peek () {
    const val = this.tail.peek()
    if (val === undefined && this.tail.next) return this.tail.next.peek()
    return val
  }

  isEmpty () {
    return this.length === 0
  }
}
{
  "name": "fast-fifo",
  "version": "1.3.2",
  "description": "A fast fifo implementation similar to the one powering nextTick in Node.js core",
  "main": "index.js",
  "files": [
    "./index.js",
    "./fixed-size.js"
  ],
  "dependencies": {},
  "devDependencies": {
    "standard": "^17.1.0",
    "brittle": "^3.3.2"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/fast-fifo.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/fast-fifo/issues"
  },
  "homepage": "https://github.com/mafintosh/fast-fifo"
}
// favela-community — co-owned, plaintext community rooms for Favela.
// The community protocol (schema) + the CommunityRoom class (owner/mod/keyless-reader roles) + a
// keyless read-manager. Shared by favela-web (read), favela-cli / a full-node (write), and hpp.
export { communitySchema, isDid } from './lib/schema.js'
export { CommunityRoom, CommunityRooms } from './lib/community-room.js'
export { CommunityDiscovery } from './lib/discovery.js'
export { FeedRegistry, FeedRegistries } from './lib/feed-registry.js'
export { feedRegistrySchema, feedKey, FEED_PREFIX } from './lib/feed-schema.js'
// CommunityRoom — a co-owned, plaintext community room on a hyper-rooms Autobase.
//
// One class, three roles:
//   - OWNER  (create): genesis writer + sole indexer; manages membership + admits other mods.
//   - MOD    (open + admitted): a co-writer; appends membership/moderation ops after being addWritered.
//   - READER (openReadonly): KEYLESS — opens by the room's PUBLIC bootstrapKey, holds no key, never a
//     writer; replicates and derives the roster. This is favela-web's path.
//
// Membership + moderation linearize into a plaintext Hyperbee view (schema.js). Posts are NOT here — they
// live in each member's own signed repo. See schema.js for the "why plaintext" rationale.
//
// hyper-rooms `Room` is imported by SUBPATH (not the barrel) to skip its room-pairing → blind-pairing dep,
// which the read/write paths here don't use (mod admission is key-exchange, below).
import { Room } from 'hyper-rooms/lib/room.js'
import { communitySchema, isDid, DEFAULT_CURATION } from './schema.js'

const MEMBER = 'member:'
const BANNED = 'banned:'
const META = 'meta:'
const normKey = (k) => (typeof k === 'string' ? k.toLowerCase() : k)

export class CommunityRoom {
  constructor (room) { this._room = room }

  // OWNER — create a fresh community room. This peer is the genesis writer AND the sole indexer (N=1, the
  // safe default per the autobase quorum rule — never auto-grow to N=2). Optionally set the name and the
  // community's atproto DID (see communityDid below).
  static async create (corestore, { namespace = 'community', name = null, did = null, curator = null, params = {} } = {}) {
    const room = new Room(corestore, { schema: communitySchema, bootstrapKey: null, namespace })
    await room.ready()
    const cr = new CommunityRoom(room)
    if (name) await cr.setMeta('name', name)
    if (did) await cr.setMeta('did', did)
    if (curator) await cr.setCuration(curator, params)
    return cr
  }

  // MOD — open an EXISTING room to co-write. Becomes writable only AFTER the owner addMods this peer's
  // localKey (call waitWritable() to block until then). Until admitted it can still READ.
  static async open (corestore, roomKey, { namespace } = {}) {
    const key = normKey(roomKey)
    if (!/^[0-9a-f]{64}$/.test(String(key))) throw new Error('roomKey must be a 32-byte hex bootstrap key')
    const room = new Room(corestore, { schema: communitySchema, bootstrapKey: key, namespace: namespace || `community:${key}` })
    await room.ready()
    return new CommunityRoom(room)
  }

  // READER — keyless read-only open (semantically identical to open(); named for intent). favela-web uses
  // this: it never calls a write method, so it is never admitted and holds no key.
  static openReadonly (corestore, roomKey, opts) { return CommunityRoom.open(corestore, roomKey, opts) }

  // ── identity / replication surface ──
  get key () { return this._room.keyHex }              // PUBLIC bootstrap key — share to invite mods/readers
  get localKey () { return this._room.localKeyHex }    // THIS peer's writer key — give to the owner for addMod
  get discoveryKey () { return this._room.discoveryKey }
  get writable () { return this._room.writable }
  get corestore () { return this._room.corestore }
  get base () { return this._room.base }
  get view () { return this._room.view }

  async update () { await this._room.base.update() }
  async close () { await this._room.close() }

  // Block until this peer has been admitted as a writer (autopass whenWritable pattern). Returns false on
  // timeout. A mod calls this after handing its localKey to the owner, before writing.
  waitWritable ({ timeout = 30000 } = {}) {
    const base = this._room.base
    if (base.writable) return Promise.resolve(true)
    return new Promise((resolve) => {
      let done = false
      const finish = (v) => { if (done) return; done = true; base.off('update', check); clearTimeout(timer); resolve(v) }
      const check = () => { if (base.writable) finish(true) }
      const timer = setTimeout(() => finish(false), timeout)
      base.on('update', check)
    })
  }

  // ── reads (keyless-safe) ──
  async members () {
    await this._room.base.update()
    const banned = new Set()
    for await (const { key } of this._room.view.createReadStream({ gte: BANNED, lt: BANNED + '\xff' })) banned.add(key.slice(BANNED.length))
    const out = []
    for await (const { key } of this._room.view.createReadStream({ gte: MEMBER, lt: MEMBER + '\xff' })) {
      const did = key.slice(MEMBER.length)
      if (!banned.has(did)) out.push(did)
    }
    return out
  }

  async isBanned (did) { await this._room.base.update(); return !!(await this._room.view.get(BANNED + did)) }

  // The community's atproto DID (meta:did) — the CO-OWNED identity that owns/signs this community's
  // app.bsky.feed.generator + app.bsky.labeler.service records and its com.atproto.label labels (the
  // lens export, spec/lens-export.md §3). It is a SEPARATE substrate from this room: the DID is a
  // co-owned hyper-proto-peer (StateBase admins + Lease + Signer/LabelRoom = the multiswarm-PDS pattern);
  // this room is the keyless MEMBER roster. The room's MODS are the DID's admin/signer set — one attested
  // group surfaced two ways (mods here; StateBase device-writers there). Returns null until set at create
  // or via setDid. Keyless-safe (a plain meta read).
  async communityDid () { return (await this.meta()).did || null }

  // Owner/mod: bind (or rebind) the community's atproto DID. Written like any meta op, so it linearizes +
  // replicates to keyless readers. Set once at create normally; this is for late-binding / migration.
  async setDid (did) { this._assertWritable('setDid'); this._assertDid(did); await this.setMeta('did', did) }

  // The curation CONTRACT — { curator, params } — the mutable rule for HOW this community's feed selects
  // posts (roster / subject / rules / custom), which favela-web's curator registry runs to drive
  // getFeedSkeleton (architecture.md "Feeds are curation functions"). THREE distinct substrates, don't
  // conflate: the ROSTER is WHO (members()), the DID is the signing identity (communityDid()), the CURATION
  // is HOW (here). Defaults to roster curation (the historical implicit behavior) until set, so pre-curation
  // rooms keep working with NO migration. Keyless-safe (a plain view read) and bsky-neutral (it only affects
  // which app.bsky.feed.post URIs the feed returns; bsky never sees the curator).
  async curation () {
    await this._room.base.update()
    const node = await this._room.view.get('curation')
    return (node && node.value) || { ...DEFAULT_CURATION }
  }

  // Owner/mod: set (or change) the curation contract. Mutable — an autobase op, so it linearizes + replicates
  // to keyless readers like any other. curator = any non-empty string (a built-in name or a custom curator
  // id — the schema is curator-agnostic); params = that curator's config object.
  async setCuration (curator, params = {}) {
    this._assertWritable('setCuration')
    if (typeof curator !== 'string' || !curator) throw new Error('setCuration requires a curator name')
    if (params != null && (typeof params !== 'object' || Array.isArray(params))) throw new Error('setCuration params must be an object')
    await this._room.append({ type: 'set-curation', curator, params: params || {} })
  }

  async meta () {
    await this._room.base.update()
    const m = {}
    for await (const { key, value } of this._room.view.createReadStream({ gte: META, lt: META + '\xff' })) m[key.slice(META.length)] = value && value.value
    return m
  }

  // The co-writers (mods) — { userId, role, writerKey, addedBy, addedAt }. role 'owner' = indexer.
  async mods () { return this._room.listWriters() }

  // ── writes (mods; throw if not admitted) ──
  async addMember (did, { by = null } = {}) { this._assertWritable('addMember'); this._assertDid(did); await this._room.append({ type: 'add-member', did, by, at: Date.now() }) }
  async removeMember (did) { this._assertWritable('removeMember'); this._assertDid(did); await this._room.append({ type: 'remove-member', did }) }
  async ban (did, { by = null } = {}) { this._assertWritable('ban'); this._assertDid(did); await this._room.append({ type: 'ban', did, by, at: Date.now() }) }
  async unban (did) { this._assertWritable('unban'); this._assertDid(did); await this._room.append({ type: 'unban', did }) }
  async setMeta (key, value) { this._assertWritable('setMeta'); await this._room.append({ type: 'set-meta', key, value }) }

  // ── admission (owner adds a co-writer) ──
  // Add another mod as a co-writer. role 'writer' (DEFAULT) = a plain writer (indexer:false) — the SAFE
  // choice: the owner stays the sole indexer (N=1), so the mod's ops still linearize (owner acks via
  // ackInterval) without risking the N=2 quorum trap. role 'owner' promotes to INDEXER — only do this to
  // reach an ODD indexer count ≥3 (a real anchor), NEVER as the 2nd indexer (see addIndexer's warning).
  async addMod (writerKeyHex, { role = 'writer', userId = null, addedBy = null } = {}) {
    this._assertWritable('addMod')
    if (!/^[0-9a-f]{64}$/i.test(String(writerKeyHex))) throw new Error('addMod requires the mod\'s 64-hex localKey')
    if (!['owner', 'writer', 'mirror'].includes(role)) throw new Error('role must be owner, writer, or mirror')
    await this._room.addWriter(userId || String(writerKeyHex).toLowerCase(), { writerKey: String(writerKeyHex).toLowerCase(), role, addedBy })
  }

  // Promote a co-writer to INDEXER (consensus participant). ⚠ AUTOBASE QUORUM: majority = floor(N/2)+1, so
  // N=2 DEADLOCKS if either indexer drops (autobase forbids 2→1). Only grow the indexer set to an ODD count
  // ≥3 on independent, always-on boxes (e.g. an anchor). This helper is the explicit, eyes-open path.
  async addIndexer (writerKeyHex, { userId = null, addedBy = null } = {}) {
    return this.addMod(writerKeyHex, { role: 'owner', userId, addedBy })
  }

  async removeMod (userId) { this._assertWritable('removeMod'); await this._room.removeWriter(userId) }

  _assertWritable (op) { if (!this._room.writable) throw new Error(`${op}: not a writer — this peer holds no key / has not been admitted (favela-web is keyless by design)`) }
  _assertDid (did) { if (!isDid(did)) throw new Error('a valid did is required') }
}

// ── read-manager (favela-web server) ───────────────────────────
// Opens + maintains a KEYLESS read replica per community room on a shared corestore + swarm, and answers
// members(roomKey). This is the `Communities.resolve` source for co-owned communities: the server wires
// `resolve = (community) => communityRooms.members(community.roomKey)`.
export class CommunityRooms {
  constructor (corestore, swarm) {
    this._store = corestore
    this._swarm = swarm
    this._rooms = new Map() // roomKeyHex -> Promise<CommunityRoom>
    // Replicate our corestore (all opened room replicas) on every swarm connection. Joining a room's
    // discoveryKey only DISCOVERS peers — without this the connection forms but no cores flow and the
    // roster never syncs. corestore.replicate muxes over the connection (composes with other consumers of
    // a shared swarm, e.g. favela-web's DidPeer router). Errors are swallowed (peer resets on close).
    if (swarm) swarm.on('connection', (conn) => { conn.on('error', () => {}); this._store.replicate(conn) })
  }

  room (roomKeyHex) {
    const key = normKey(roomKeyHex)
    if (this._rooms.has(key)) return this._rooms.get(key)
    const p = (async () => {
      const cr = await CommunityRoom.openReadonly(this._store, key)
      if (this._swarm) this._swarm.join(cr.discoveryKey, { client: true, server: true })
      return cr
    })().catch((e) => { this._rooms.delete(key); throw e }) // don't cache a failed open
    this._rooms.set(key, p)
    return p
  }

  async members (roomKeyHex) { return (await this.room(roomKeyHex)).members() }
  async meta (roomKeyHex) { return (await this.room(roomKeyHex)).meta() }
  async communityDid (roomKeyHex) { return (await this.room(roomKeyHex)).communityDid() }
  async curation (roomKeyHex) { return (await this.room(roomKeyHex)).curation() }

  // Watch one room's roster for changes. onChange(memberDids[]) fires (debounced) on every linearized-view
  // advance — i.e. whenever a member add/remove/ban replicates in — PLUS once immediately as a baseline.
  // This is the roster-watcher a keyless consumer (favela-web) uses to index members added AFTER it started,
  // with no restart: the same `base.on('update')` signal waitWritable relies on, which fires on replication.
  // Runs are serialized (never re-entrant) and coalesced (a change during a run re-fires once after). Errors
  // from onChange are swallowed — a flaky consumer must never break replication. Returns an async unwatch fn.
  async watch (roomKeyHex, onChange, { debounceMs = 300 } = {}) {
    const cr = await this.room(roomKeyHex)
    const base = cr.base
    let timer = null
    let running = false
    let pending = false
    const run = async () => {
      if (running) { pending = true; return }
      running = true
      try { await onChange(await cr.members()) } catch {}
      running = false
      if (pending) { pending = false; schedule() }
    }
    const schedule = () => { clearTimeout(timer); timer = setTimeout(run, debounceMs) }
    base.on('update', schedule)
    schedule() // baseline: index the current roster now
    return async () => { clearTimeout(timer); base.off('update', schedule) }
  }

  async close () {
    for (const p of this._rooms.values()) { try { await (await p).close() } catch {} }
    this._rooms.clear()
  }
}

export default { CommunityRoom, CommunityRooms }
// discovery.js — DHT name/topic discovery for community rooms.
//
// A community room is identified by its public bootstrapKey (roomKey) — but that's 64 hex chars nobody
// wants to paste. Discovery lets an owner PUBLISH a room under a human NAME (+ optional topics) so peers
// RESOLVE the name to the roomKey, then read the room keylessly (CommunityRooms) as usual.
//
// Mirrors keet-daemon's topic-announce pattern — a mutable DHT metadata record + dht.announce on a
// name/topic key, discovered via dht.lookup → mutableGet — but free of keet-core coupling: it needs only
// a HyperDHT (swarm.dht). Nothing is stored locally; the DHT IS the registry.
//
//   announce:  mutablePut(recordKeyPair, {roomKey,name,topics}) + announce(labelKey, recordKeyPair) per label
//   discover:  lookup(labelKey) → peer pubkeys → mutableGet(pk) → {roomKey,…}  (dedup, newest ts per room)
//
// Trust model (DHT-registry, same as keet's topic-announce): the record keypair is DERIVED FROM the room's
// PUBLIC roomKey, so every announcer of the same room writes the SAME mutable record (idempotent refresh),
// and only a peer that already knows the roomKey (= the keyless-read capability) can publish/refresh it.
// The name/topic LABELS are open — a squatter could announce their own room under a popular name; the
// roomKey is the real capability, so treat discovery as a hint, not an authorization. Private/invite-only
// communities simply don't announce (DESIGN step 4).
import crypto from 'hypercore-crypto'
import b4a from 'b4a'

const LABEL_PREFIX = 'favela:community:label:'   // name/topic → DHT lookup target
const RECORD_PREFIX = 'favela:community:record:' // roomKey → mutable-record keypair seed

const norm = (s) => String(s || '').toLowerCase().trim()
const isRoomKey = (k) => /^[0-9a-f]{64}$/i.test(String(k))

export class CommunityDiscovery {
  // dht: a HyperDHT (e.g. `hyperswarm.dht`). No corestore, no storage — records live on the DHT.
  constructor (dht) {
    if (!dht) throw new Error('CommunityDiscovery requires a HyperDHT (e.g. swarm.dht)')
    this._dht = dht
    this._announced = new Map() // roomKey -> { keyPair, targets: [Buffer] }
  }

  _labelKey (s) { return crypto.hash(b4a.from(LABEL_PREFIX + norm(s))) }
  _recordKeyPair (roomKey) { return crypto.keyPair(crypto.hash(b4a.from(RECORD_PREFIX + norm(roomKey)))) }

  // Publish a room under a NAME (+ optional topics). Idempotent per roomKey (refreshes the same record +
  // re-announces). Returns { roomKey, labels } — the normalized labels it announced on.
  async announce ({ roomKey, name = '', description = '', topics = [] } = {}) {
    if (!isRoomKey(roomKey)) throw new Error('announce requires a 64-hex roomKey')
    const nName = norm(name)
    const nTopics = (Array.isArray(topics) ? topics : []).map(norm).filter(Boolean)
    const labels = [...new Set([nName, ...nTopics].filter(Boolean))]
    if (!labels.length) throw new Error('announce requires a name or at least one topic')
    const keyPair = this._recordKeyPair(roomKey)
    const value = b4a.from(JSON.stringify({
      roomKey: norm(roomKey), name: nName, description: String(description || ''), topics: nTopics, ts: Date.now()
    }))
    await this._dht.mutablePut(keyPair, value, { seq: Math.floor(Date.now() / 1000) })
    const targets = []
    for (const label of labels) {
      const target = this._labelKey(label)
      await this._dht.announce(target, keyPair, []).finished()
      targets.push(target)
    }
    this._announced.set(norm(roomKey), { keyPair, targets })
    return { ok: true, roomKey: norm(roomKey), labels }
  }

  // Stop advertising a room (drops the announces; the mutable record ages out). No-op if not announced here.
  async unannounce (roomKey) {
    const entry = this._announced.get(norm(roomKey))
    if (!entry) return { ok: true }
    for (const target of entry.targets) { try { await this._dht.unannounce(target, entry.keyPair) } catch {} }
    this._announced.delete(norm(roomKey))
    return { ok: true }
  }

  // Discover rooms published under a name or topic. Returns [{ roomKey, name, description, topics, ts }] —
  // deduped by roomKey (newest ts wins); a label collision (two rooms same name) yields multiple entries.
  async discover (query) {
    const target = this._labelKey(query)
    const best = new Map() // roomKey -> record
    const seenPk = new Set()
    for await (const res of this._dht.lookup(target)) {
      for (const peer of (res.peers || [])) {
        const pkHex = b4a.toString(peer.publicKey, 'hex')
        if (seenPk.has(pkHex)) continue
        seenPk.add(pkHex)
        try {
          const rec = await this._dht.mutableGet(peer.publicKey, { latest: true })
          if (!rec || !rec.value) continue
          const meta = JSON.parse(b4a.toString(rec.value))
          if (!isRoomKey(meta.roomKey)) continue
          const prev = best.get(meta.roomKey)
          if (!prev || (meta.ts || 0) > (prev.ts || 0)) best.set(meta.roomKey, meta)
        } catch {}
      }
    }
    return [...best.values()]
  }

  // Resolve a NAME to a single roomKey (newest match), or null if none found.
  async resolve (name) {
    const rooms = await this.discover(name)
    return rooms.length ? rooms[0].roomKey : null
  }
}

export default CommunityDiscovery
// FeedRegistry — the watched, co-ownable list of feeds (favela-web/spec/community-ux.md). One class, three
// roles (same shape as CommunityRoom):
//   - OWNER  (create): genesis writer + sole indexer; publishes/removes feed entries.
//   - MOD    (open + admitted): a co-writer, admitted by the owner (addMod) — so a registry can be co-owned.
//   - READER (openReadonly): KEYLESS — opens by the PUBLIC bootstrapKey, holds no key, never a writer;
//     replicates + lists + WATCHES. This is the reactor path (favela-web / membrane / hpp / blind-relay).
//
// Entries linearize into a plaintext Hyperbee view (feed-schema.js). It is the source of truth: the mint
// writes an entry; the reactors watch it and serve/front/index/seed the feed with no per-feed config.
//
// hyper-rooms `Room` is imported by SUBPATH (skips the room-pairing/blind-pairing dep the read/write paths
// here don't use — mod admission is key-exchange, below), matching CommunityRoom.
import { Room } from 'hyper-rooms/lib/room.js'
import { feedRegistrySchema, isDid, isRkey, FEED_PREFIX } from './feed-schema.js'

const normKey = (k) => (typeof k === 'string' ? k.toLowerCase() : k)

export class FeedRegistry {
  constructor (room) { this._room = room }

  // OWNER — create a fresh registry. This peer is the genesis writer AND the sole indexer (N=1, the safe
  // default per the autobase quorum rule — never auto-grow to N=2). Grow indexers only via addIndexer.
  static async create (corestore, { namespace = 'feed-registry', name = null } = {}) {
    const room = new Room(corestore, { schema: feedRegistrySchema, bootstrapKey: null, namespace })
    await room.ready()
    const fr = new FeedRegistry(room)
    if (name) await fr._room.append({ type: 'set-meta', key: 'name', value: name }).catch(() => {})
    return fr
  }

  // MOD — open an EXISTING registry to co-write. Writable only AFTER the owner addMods this peer's localKey
  // (waitWritable blocks until then). Until admitted it can still READ.
  static async open (corestore, roomKey, { namespace } = {}) {
    const key = normKey(roomKey)
    if (!/^[0-9a-f]{64}$/.test(String(key))) throw new Error('roomKey must be a 32-byte hex bootstrap key')
    const room = new Room(corestore, { schema: feedRegistrySchema, bootstrapKey: key, namespace: namespace || `feed-registry:${key}` })
    await room.ready()
    return new FeedRegistry(room)
  }

  // READER — keyless read-only open (semantically identical to open(); named for intent). The reactors use
  // this: they never call a write method, so are never admitted and hold no key.
  static openReadonly (corestore, roomKey, opts) { return FeedRegistry.open(corestore, roomKey, opts) }

  // ── identity / replication surface ──
  get key () { return this._room.keyHex }              // PUBLIC bootstrap key — share to reactors/co-mods
  get localKey () { return this._room.localKeyHex }    // THIS peer's writer key — give to the owner for addMod
  get discoveryKey () { return this._room.discoveryKey }
  get writable () { return this._room.writable }
  get corestore () { return this._room.corestore }
  get base () { return this._room.base }
  get view () { return this._room.view }

  async update () { await this._room.base.update() }
  async close () { await this._room.close() }

  // Block until this peer has been admitted as a writer (autopass whenWritable pattern). Returns false on
  // timeout. A mod calls this after handing its localKey to the owner, before writing.
  waitWritable ({ timeout = 30000 } = {}) {
    const base = this._room.base
    if (base.writable) return Promise.resolve(true)
    return new Promise((resolve) => {
      let done = false
      const finish = (v) => { if (done) return; done = true; base.off('update', check); clearTimeout(timer); resolve(v) }
      const check = () => { if (base.writable) finish(true) }
      const timer = setTimeout(() => finish(false), timeout)
      base.on('update', check)
    })
  }

  // ── reads (keyless-safe) ──
  // Every registered feed, as the stored entry objects { did, rkey, name, curator, params, roomKey, handle,
  // createdBy, at }. This is what a reactor iterates: index / front / serve / seed each.
  async feeds () {
    await this._room.base.update()
    const out = []
    for await (const { value } of this._room.view.createReadStream({ gte: FEED_PREFIX, lt: FEED_PREFIX + '\xff' })) out.push(value)
    return out
  }

  async feed (did, rkey) {
    await this._room.base.update()
    const node = await this._room.view.get(`${FEED_PREFIX}${did}/${rkey}`)
    return (node && node.value) || null
  }

  // ── writes (owner/mods; throw if not admitted) ──
  // Publish (or update — last-writer-wins on the key) a feed. did = the repo that HOLDS the feed record
  // (your own hpp for a light feed, or a co-owned community DID). curator/params = the contract favela-web
  // runs; roomKey = the roster CommunityRoom (only for community/roster feeds). Idempotent per (did, rkey).
  async addFeed ({ did, rkey, name = null, curator, params = {}, roomKey = null, handle = null, by = null } = {}) {
    this._assertWritable('addFeed')
    if (!isDid(did)) throw new Error('addFeed requires a valid did (the feed record home repo)')
    if (!isRkey(rkey)) throw new Error('addFeed requires a valid rkey')
    if (typeof curator !== 'string' || !curator) throw new Error('addFeed requires a curator name')
    if (params != null && (typeof params !== 'object' || Array.isArray(params))) throw new Error('addFeed params must be an object')
    await this._room.append({ type: 'add-feed', did, rkey, name, curator, params: params || {}, roomKey, handle, by, at: Date.now() })
  }

  async removeFeed (did, rkey) {
    this._assertWritable('removeFeed')
    if (!isDid(did) || !isRkey(rkey)) throw new Error('removeFeed requires a valid did + rkey')
    await this._room.append({ type: 'remove-feed', did, rkey })
  }

  // ── admission (owner adds a co-writer) — same model + warnings as CommunityRoom.addMod ──
  // Default role 'writer' = a plain writer (non-indexer, the SAFE topology: owner stays sole indexer N=1, so
  // the mod's ops still linearize via ackInterval without the N=2 quorum trap). role 'owner' promotes to
  // INDEXER — only to reach an ODD indexer count ≥3 on independent always-on boxes.
  async addMod (writerKeyHex, { role = 'writer', userId = null, addedBy = null } = {}) {
    this._assertWritable('addMod')
    if (!/^[0-9a-f]{64}$/i.test(String(writerKeyHex))) throw new Error('addMod requires the mod\'s 64-hex localKey')
    if (!['owner', 'writer', 'mirror'].includes(role)) throw new Error('role must be owner, writer, or mirror')
    await this._room.addWriter(userId || String(writerKeyHex).toLowerCase(), { writerKey: String(writerKeyHex).toLowerCase(), role, addedBy })
  }

  async removeMod (userId) { this._assertWritable('removeMod'); await this._room.removeWriter(userId) }

  _assertWritable (op) { if (!this._room.writable) throw new Error(`${op}: not a writer — this peer holds no key / has not been admitted (reactors are keyless by design)`) }
}

// ── read-manager (reactors) ─────────────────────────────────────
// Opens + maintains a KEYLESS read replica of a registry on a shared corestore + swarm, answers feeds(), and
// WATCHES for changes. This is the reactor primitive: favela-web / membrane / hpp / blind-relay each wrap a
// FeedRegistries and react to onChange(feeds[]) — index / front / serve / seed the new feed. No per-feed config.
export class FeedRegistries {
  constructor (corestore, swarm) {
    this._store = corestore
    this._swarm = swarm
    this._registries = new Map() // roomKeyHex -> Promise<FeedRegistry>
    // Replicate our corestore on every swarm connection (joining a discoveryKey only DISCOVERS; without
    // this the connection forms but no cores flow and the list never syncs). Mirrors CommunityRooms.
    if (swarm) swarm.on('connection', (conn) => { conn.on('error', () => {}); this._store.replicate(conn) })
  }

  registry (roomKeyHex) {
    const key = normKey(roomKeyHex)
    if (this._registries.has(key)) return this._registries.get(key)
    const p = (async () => {
      const fr = await FeedRegistry.openReadonly(this._store, key)
      if (this._swarm) this._swarm.join(fr.discoveryKey, { client: true, server: true })
      return fr
    })().catch((e) => { this._registries.delete(key); throw e })
    this._registries.set(key, p)
    return p
  }

  async feeds (roomKeyHex) { return (await this.registry(roomKeyHex)).feeds() }

  // Watch a registry for changes. onChange(feeds[]) fires (debounced) on every linearized-view advance — i.e.
  // whenever a feed add/remove replicates in — PLUS once immediately as a baseline. This is what a reactor
  // uses to pick up feeds published AFTER it started, with NO restart. Serialized + coalesced; onChange
  // errors are swallowed (a flaky reactor must never break replication). Returns an async unwatch fn.
  async watch (roomKeyHex, onChange, { debounceMs = 300 } = {}) {
    const fr = await this.registry(roomKeyHex)
    const base = fr.base
    let timer = null
    let running = false
    let pending = false
    const run = async () => {
      if (running) { pending = true; return }
      running = true
      try { await onChange(await fr.feeds()) } catch {}
      running = false
      if (pending) { pending = false; schedule() }
    }
    const schedule = () => { clearTimeout(timer); timer = setTimeout(run, debounceMs) }
    base.on('update', schedule)
    schedule() // baseline: emit the current feed set now
    return async () => { clearTimeout(timer); base.off('update', schedule) }
  }

  async close () {
    for (const p of this._registries.values()) { try { await (await p).close() } catch {} }
    this._registries.clear()
  }
}

export default { FeedRegistry, FeedRegistries }
// The FEED REGISTRY protocol — the op contract for a watched list of feeds, as a hyper-rooms schema. This
// is the single source of truth that makes "a feed exists" one durable P2P fact everyone reacts to
// (favela-web/spec/community-ux.md): the mint writes an entry; favela-web (index), the membrane (front +
// requestCrawl), the multi-DID hpp (serve co-owned ones), and the blind-relay (seed) all keyless-READ +
// WATCH it — no per-feed config, no restart. Plaintext by design (feed identities are PUBLIC — a did + rkey
// + curation contract; never a secret).
//
// A feed is the PRIMITIVE (a community is just the roster-curated, co-owned kind): { curator, params } + a
// HOME repo (`did`) that holds the app.bsky.feed.generator record. For a light/arbitrary feed `did` is the
// creator's OWN hpp repo (no new DID); for a community it's the co-owned DID. `roomKey` is present only for
// roster-type feeds (the audience CommunityRoom favela-web reads).
//
// Domain ops (writer ops add-writer/remove-writer are handled by hyper-rooms Room itself):
//   add-feed {did,rkey,name,curator,params,roomKey?,handle?} → feed:<did>/<rkey>
//   remove-feed {did,rkey}                                   → del feed:<did>/<rkey>
//
// apply is DETERMINISTIC — reads only fields carried in the op (op.at/op.by set at append time), never
// Date.now()/randomness (Autobase replays apply on every boot + reorg).
import { jsonSchema } from 'hyper-rooms/lib/json-schema.js'

export const isDid = (d) => typeof d === 'string' && /^did:[a-z]+:/.test(d)
// rkey syntax = [A-Za-z0-9._~-], 1–512, not "."/".."; keep it simple + safe for the `feed:<did>/<rkey>` key.
export const isRkey = (r) => typeof r === 'string' && r.length > 0 && r.length <= 512 && /^[A-Za-z0-9._~-]+$/.test(r) && r !== '.' && r !== '..'
const isPlainObject = (o) => o != null && typeof o === 'object' && !Array.isArray(o)

export const FEED_PREFIX = 'feed:'
export const feedKey = (did, rkey) => `${FEED_PREFIX}${did}/${rkey}`

export const feedRegistrySchema = jsonSchema({
  validate (op) {
    if (op.type === 'add-feed') {
      if (!isDid(op.did)) throw new Error('add-feed requires a valid did (the feed record home repo)')
      if (!isRkey(op.rkey)) throw new Error('add-feed requires a valid rkey')
      if (typeof op.curator !== 'string' || !op.curator) throw new Error('add-feed requires a curator name')
      if (op.params != null && !isPlainObject(op.params)) throw new Error('add-feed params must be an object')
      if (op.roomKey != null && !/^[0-9a-f]{64}$/i.test(String(op.roomKey))) throw new Error('add-feed roomKey must be a 32-byte hex key')
    }
    if (op.type === 'remove-feed') {
      if (!isDid(op.did) || !isRkey(op.rkey)) throw new Error('remove-feed requires a valid did + rkey')
    }
  },
  async apply (batch, op, host) {
    switch (op.type) {
      case 'add-feed':
        await batch.put(feedKey(op.did, op.rkey), {
          did: op.did,
          rkey: op.rkey,
          name: op.name || op.rkey,
          curator: op.curator,
          params: op.params || {},
          roomKey: op.roomKey ? String(op.roomKey).toLowerCase() : null,
          handle: op.handle || null,
          createdBy: op.by || null,
          at: op.at || null
        })
        break
      case 'remove-feed':
        await batch.del(feedKey(op.did, op.rkey))
        break
    }
  }
})

export default feedRegistrySchema
// The community protocol — the op contract for a co-owned community room, as a hyper-rooms schema.
// Shared by the READ layer (favela-web / favela-native open the room keylessly and derive the roster) and
// the WRITE layer (mods' hpp / full-node / CLI append ops). Plaintext by design (keyless-read ⊥ encryption;
// the room holds only PUBLIC metadata — member DIDs + moderation — never posts or private messages).
//
// Domain ops (writer ops add-writer/remove-writer are handled by hyper-rooms Room itself):
//   add-member {did}     → member:<did>           (the roster)
//   remove-member {did}  → del member:<did>
//   ban {did}            → banned:<did> + del member:<did>   (moderation; excluded from the roster)
//   unban {did}          → del banned:<did>
//   set-meta {key,value} → meta:<key>             (name / description / …)
//   set-curation {curator,params} → curation      (the curation CONTRACT — HOW the feed selects posts)
//
// apply is DETERMINISTIC — it reads only fields carried in the op (op.at/op.by, set at append time), never
// Date.now()/randomness (Autobase replays apply on every boot + reorg).
import { jsonSchema } from 'hyper-rooms/lib/json-schema.js'

export const isDid = (d) => typeof d === 'string' && /^did:[a-z]+:/.test(d)

// The built-in curator names favela-web resolves NATIVELY. The schema stays curator-AGNOSTIC (any non-empty
// string is a valid curator) so a community can name a custom/sandboxed curator with NO schema change
// (architecture.md "Feeds are curation functions"). These are just the ones with a native implementation.
// The curation contract is bsky-NEUTRAL: it only decides WHICH posts a feed returns; bsky sees the resulting
// app.bsky.feed.post at-uris, never the curator.
export const BUILTIN_CURATORS = ['roster', 'subject', 'rules']
// Default for a room that has never set a curation contract = pure roster curation (the historical implicit
// behavior). So pre-curation rooms keep working with NO migration — never break persistent state.
export const DEFAULT_CURATION = { curator: 'roster', params: {} }
const isPlainObject = (o) => o != null && typeof o === 'object' && !Array.isArray(o)

export const communitySchema = jsonSchema({
  validate (op) {
    if (['add-member', 'remove-member', 'ban', 'unban'].includes(op.type) && !isDid(op.did)) {
      throw new Error(`${op.type} requires a valid did`)
    }
    if (op.type === 'set-meta' && typeof op.key !== 'string') throw new Error('set-meta requires a key')
    if (op.type === 'set-curation') {
      if (typeof op.curator !== 'string' || !op.curator) throw new Error('set-curation requires a curator name')
      if (op.params != null && !isPlainObject(op.params)) throw new Error('set-curation params must be an object')
    }
  },
  async apply (batch, op, host) {
    switch (op.type) {
      case 'add-member':
        await batch.put(`member:${op.did}`, { did: op.did, addedBy: op.by || null, at: op.at || null })
        break
      case 'remove-member':
        await batch.del(`member:${op.did}`)
        break
      case 'ban':
        await batch.del(`member:${op.did}`)
        await batch.put(`banned:${op.did}`, { by: op.by || null, at: op.at || null })
        break
      case 'unban':
        await batch.del(`banned:${op.did}`)
        break
      case 'set-meta':
        await batch.put(`meta:${op.key}`, { value: op.value })
        break
      case 'set-curation':
        // single record (no prefix) — sorts before every prefix scan (member:/banned:/meta:), so it is
        // never swept into a roster/meta read. Stored as the payload directly; curation() reads node.value.
        await batch.put('curation', { curator: op.curator, params: op.params || {} })
        break
    }
  }
})

export default communitySchema
function isBuffer(value) {
  return Buffer.isBuffer(value) || value instanceof Uint8Array
}

function isEncoding(encoding) {
  return Buffer.isEncoding(encoding)
}

function alloc(size, fill, encoding) {
  return Buffer.alloc(size, fill, encoding)
}

function allocUnsafe(size) {
  return Buffer.allocUnsafe(size)
}

function allocUnsafeSlow(size) {
  return Buffer.allocUnsafeSlow(size)
}

function byteLength(string, encoding) {
  return Buffer.byteLength(string, encoding)
}

function compare(a, b) {
  return Buffer.compare(a, b)
}

function concat(buffers, totalLength) {
  return Buffer.concat(buffers, totalLength)
}

function copy(source, target, targetStart, start, end) {
  return toBuffer(source).copy(target, targetStart, start, end)
}

function equals(a, b) {
  return toBuffer(a).equals(b)
}

function fill(buffer, value, offset, end, encoding) {
  return toBuffer(buffer).fill(value, offset, end, encoding)
}

function from(value, encodingOrOffset, length) {
  return Buffer.from(value, encodingOrOffset, length)
}

function includes(buffer, value, byteOffset, encoding) {
  return toBuffer(buffer).includes(value, byteOffset, encoding)
}

function indexOf(buffer, value, byfeOffset, encoding) {
  return toBuffer(buffer).indexOf(value, byfeOffset, encoding)
}

function lastIndexOf(buffer, value, byteOffset, encoding) {
  return toBuffer(buffer).lastIndexOf(value, byteOffset, encoding)
}

function swap16(buffer) {
  return toBuffer(buffer).swap16()
}

function swap32(buffer) {
  return toBuffer(buffer).swap32()
}

function swap64(buffer) {
  return toBuffer(buffer).swap64()
}

function toBuffer(buffer) {
  if (Buffer.isBuffer(buffer)) return buffer
  return Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

function toString(buffer, encoding, start, end) {
  return toBuffer(buffer).toString(encoding, start, end)
}

function write(buffer, string, offset, length, encoding) {
  return toBuffer(buffer).write(string, offset, length, encoding)
}

function readDoubleBE(buffer, offset) {
  return toBuffer(buffer).readDoubleBE(offset)
}

function readDoubleLE(buffer, offset) {
  return toBuffer(buffer).readDoubleLE(offset)
}

function readFloatBE(buffer, offset) {
  return toBuffer(buffer).readFloatBE(offset)
}

function readFloatLE(buffer, offset) {
  return toBuffer(buffer).readFloatLE(offset)
}

function readInt32BE(buffer, offset) {
  return toBuffer(buffer).readInt32BE(offset)
}

function readInt32LE(buffer, offset) {
  return toBuffer(buffer).readInt32LE(offset)
}

function readUInt32BE(buffer, offset) {
  return toBuffer(buffer).readUInt32BE(offset)
}

function readUInt32LE(buffer, offset) {
  return toBuffer(buffer).readUInt32LE(offset)
}

function writeDoubleBE(buffer, value, offset) {
  return toBuffer(buffer).writeDoubleBE(value, offset)
}

function writeDoubleLE(buffer, value, offset) {
  return toBuffer(buffer).writeDoubleLE(value, offset)
}

function writeFloatBE(buffer, value, offset) {
  return toBuffer(buffer).writeFloatBE(value, offset)
}

function writeFloatLE(buffer, value, offset) {
  return toBuffer(buffer).writeFloatLE(value, offset)
}

function writeInt32BE(buffer, value, offset) {
  return toBuffer(buffer).writeInt32BE(value, offset)
}

function writeInt32LE(buffer, value, offset) {
  return toBuffer(buffer).writeInt32LE(value, offset)
}

function writeUInt32BE(buffer, value, offset) {
  return toBuffer(buffer).writeUInt32BE(value, offset)
}

function writeUInt32LE(buffer, value, offset) {
  return toBuffer(buffer).writeUInt32LE(value, offset)
}

module.exports = {
  isBuffer,
  isEncoding,
  alloc,
  allocUnsafe,
  allocUnsafeSlow,
  byteLength,
  compare,
  concat,
  copy,
  equals,
  fill,
  from,
  includes,
  indexOf,
  lastIndexOf,
  swap16,
  swap32,
  swap64,
  toBuffer,
  toString,
  write,
  readDoubleBE,
  readDoubleLE,
  readFloatBE,
  readFloatLE,
  readInt32BE,
  readInt32LE,
  readUInt32BE,
  readUInt32LE,
  writeDoubleBE,
  writeDoubleLE,
  writeFloatBE,
  writeFloatLE,
  writeInt32BE,
  writeInt32LE,
  writeUInt32BE,
  writeUInt32LE
}
{
  "name": "b4a",
  "version": "1.8.1",
  "description": "Bridging the gap between buffers and typed arrays",
  "exports": {
    "./package": "./package.json",
    ".": {
      "react-native": "./react-native.js",
      "browser": "./browser.js",
      "default": "./index.js"
    }
  },
  "files": [
    "browser.js",
    "index.js",
    "react-native.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:bare && npm run test:node",
    "test:bare": "brittle-bare --coverage test.mjs",
    "test:node": "brittle-node --coverage test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/b4a.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/b4a/issues"
  },
  "homepage": "https://github.com/holepunchto/b4a#readme",
  "devDependencies": {
    "brittle": "^3.5.2",
    "lunte": "^1.7.0",
    "nanobench": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "react-native-b4a": "*"
  },
  "peerDependenciesMeta": {
    "react-native-b4a": {
      "optional": true
    }
  }
}
const ESC = '\x1b'
const CSI = ESC + '['
const SGR = (n) => CSI + n + 'm'

exports.constants = {
  ESC,
  CSI,
  SGR
}

// https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_(Control_Sequence_Introducer)_sequences

exports.cursorHide = CSI + '?25l'
exports.cursorShow = CSI + '?25h'

exports.cursorUp = function cursorUp(n = 1) {
  return CSI + n + 'A'
}

exports.cursorDown = function cursorDown(n = 1) {
  return CSI + n + 'B'
}

exports.cursorForward = function cursorForward(n = 1) {
  return CSI + n + 'C'
}

exports.cursorBack = function cursorBack(n = 1) {
  return CSI + n + 'D'
}

exports.cursorNextLine = function cursorNextLine(n = 1) {
  return CSI + n + 'E'
}

exports.cursorPreviousLine = function cursorPreviousLine(n = 1) {
  return CSI + n + 'F'
}

exports.cursorPosition = function cursorPosition(column, row = 0) {
  if (row === 0) return CSI + (column + 1) + 'G'

  return CSI + (row + 1) + ';' + (column + 1) + 'H'
}

exports.eraseDisplayEnd = CSI + 'J'
exports.eraseDisplayStart = CSI + '1J'
exports.eraseDisplay = CSI + '2J'
exports.eraseLineEnd = CSI + 'K'
exports.eraseLineStart = CSI + '1K'
exports.eraseLine = CSI + '2K'

exports.scrollUp = function scrollUp(n = 1) {
  return CSI + n + 'S'
}

exports.scrollDown = function scrollDown(n = 1) {
  return CSI + n + 'T'
}

// https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_(Select_Graphic_Rendition)_parameters

exports.modifierReset = SGR(0)
exports.modifierBold = SGR(1)
exports.modifierDim = SGR(2)
exports.modifierItalic = SGR(3)
exports.modifierUnderline = SGR(4)
exports.modifierNormal = SGR(22)
exports.modifierNotItalic = SGR(23)
exports.modifierNotUnderline = SGR(24)

// https://en.wikipedia.org/wiki/ANSI_escape_code#Colors

exports.colorBlack = SGR(30)
exports.colorRed = SGR(31)
exports.colorGreen = SGR(32)
exports.colorYellow = SGR(33)
exports.colorBlue = SGR(34)
exports.colorMagenta = SGR(35)
exports.colorCyan = SGR(36)
exports.colorWhite = SGR(37)
exports.colorDefault = SGR(39)
exports.colorBrightBlack = SGR(90)
exports.colorBrightRed = SGR(91)
exports.colorBrightGreen = SGR(92)
exports.colorBrightYellow = SGR(93)
exports.colorBrightBlue = SGR(94)
exports.colorBrightMagenta = SGR(95)
exports.colorBrightCyan = SGR(96)
exports.colorBrightWhite = SGR(97)
{
  "name": "bare-ansi-escapes",
  "version": "2.2.3",
  "description": "Parse and produce ANSI escape sequences",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./key-decoder": {
      "types": "./key-decoder.d.ts",
      "default": "./key-decoder.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "key-decoder.js",
    "key-decoder.d.ts"
  ],
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-ansi-escapes.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-ansi-escapes/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-ansi-escapes#readme",
  "dependencies": {
    "bare-stream": "^2.6.5"
  },
  "devDependencies": {
    "bare-buffer": "^3.0.2",
    "brittle": "^3.3.2",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  },
  "peerDependencies": {
    "bare-buffer": "*"
  },
  "peerDependenciesMeta": {
    "bare-buffer": {
      "optional": true
    }
  }
}
const inspect = require('bare-inspect')

class AssertionError extends Error {
  constructor(opts = {}) {
    let { message = null, actual, expected, operator } = opts

    if (message === null) {
      message = `${inspect(actual)} ${operator} ${inspect(expected)}`
    }

    super(message)

    this.actual = actual
    this.expected = expected
    this.operator = operator
  }

  get name() {
    return 'AssertionError'
  }

  get code() {
    'ASSERTION'
  }
}

function assertFail(opts, fn) {
  if (opts.message instanceof Error) throw opts.message

  const err = new AssertionError(opts)

  if (Error.captureStackTrace) Error.captureStackTrace(err, fn)

  throw err
}

module.exports = exports = function assert(actual, message) {
  if (actual) return

  assertFail({ message, actual, expected: true, operator: '==' }, assert)
}

exports.AssertionError = AssertionError

exports.fail = function fail(message) {
  if (message === undefined) message = 'Failed'

  assertFail({ message, operator: 'fail' }, fail)
}

exports.ok = function ok(actual, message) {
  if (actual) return

  assertFail({ message, actual, expected: true, operator: '==' }, ok)
}

exports.notOk = function ok(actual, message) {
  if (!actual) return

  assertFail({ message, actual, expected: false, operator: '==' }, ok)
}

exports.equal = function equal(actual, expected, message) {
  if (actual == expected || (actual !== actual && expected !== expected)) {
    return
  }

  assertFail({ message, actual, expected, operator: '==' }, equal)
}

exports.notEqual = function notEqual(actual, expected, message) {
  if (actual != expected && (actual === actual || expected === expected)) {
    return
  }

  assertFail({ message, actual, expected, operator: '!=' }, notEqual)
}

exports.strictEqual = function strictEqual(actual, expected, message) {
  if (Object.is(actual, expected)) return

  assertFail(
    { message, actual, expected, operator: 'strictEqual' },
    strictEqual
  )
}

exports.notStrictEqual = function notStrictEqual(actual, expected, message) {
  if (!Object.is(actual, expected)) return

  assertFail(
    { message, actual, expected, operator: 'notStrictEqual' },
    notStrictEqual
  )
}
{
  "name": "bare-assert",
  "version": "1.2.0",
  "description": "Assertion library for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts"
  ],
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-assert.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-assert/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-assert#readme",
  "dependencies": {
    "bare-inspect": "^3.1.2"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  }
}
module.exports = require.addon()
const ansiEscapes = require('bare-ansi-escapes')
const getType = require('bare-type')
const binding = require('./binding')

const PLAIN_KEY = /^[a-zA-Z_][a-zA-Z_0-9]*$/

const defaultDepth = 2
const defaultBreakLength = 80
const defaultMaxArrayLength = 40

module.exports = exports = function inspect(value, opts = {}) {
  const {
    colors = false,
    depth = defaultDepth,
    breakLength = defaultBreakLength,
    stylize = defaultStylize(colors)
  } = opts

  const references = new InspectRefMap()

  const tree = inspectValue(value, 0, {
    colors,
    depth,
    breakLength,
    stylize,
    references
  })

  return tree.toString()
}

exports.styles = {
  bigint: ansiEscapes.colorYellow,
  boolean: ansiEscapes.colorYellow,
  date: ansiEscapes.colorMagenta,
  module: ansiEscapes.modifierUnderline,
  name: ansiEscapes.modifierReset,
  null: ansiEscapes.modifierBold,
  number: ansiEscapes.colorYellow,
  regexp: ansiEscapes.colorRed,
  special: ansiEscapes.colorCyan,
  string: ansiEscapes.colorGreen,
  symbol: ansiEscapes.colorGreen,
  undefined: ansiEscapes.colorBrightBlack
}

const styles = exports.styles

function defaultStylize(colors) {
  return function stylize(value, style) {
    const color = colors && styles[style]

    if (color) return color + value + ansiEscapes.modifierReset

    return value
  }
}

class InspectRefMap {
  constructor() {
    this.refs = new WeakMap()
    this.ids = new WeakMap()
    this.nextId = 1
  }

  has(object) {
    return this.refs.has(object)
  }

  get(object) {
    return this.refs.get(object) || null
  }

  set(object, ref) {
    this.refs.set(object, ref)
  }

  id(object) {
    let id = this.ids.get(object)
    if (id) return id

    id = this.nextId++
    this.ids.set(object, id)

    return id
  }
}

class InspectNode {
  constructor(depth, length, opts) {
    const { breakLength = defaultBreakLength, breakAlways = false } = opts

    this.depth = depth
    this.length = length
    this.breakLength = breakLength
    this.breakAlways = breakAlways
  }

  pad(n, string) {
    return string.padStart(n, ' ')
  }

  indent(n, string) {
    return '  '.repeat(n) + string
  }
}

class InspectRef extends InspectNode {
  constructor(depth, opts) {
    super(depth, '[circular *]'.length, opts)

    this.refs = opts.references
    this.count = 0
    this.circular = false
    this.color = opts.colors && styles.special
  }

  get id() {
    return this.refs.id(this)
  }

  increment() {
    return ++this.count
  }

  decrement() {
    return --this.count
  }

  toString(opts = {}) {
    const { offset = 0, pad = 0, indent = 0 } = opts

    let value = this.pad(pad, '[circular *' + this.id + ']')

    if (this.color) value = this.color + value + ansiEscapes.modifierReset

    return offset ? value : this.indent(indent, value)
  }
}

class InspectLeaf extends InspectNode {
  constructor(value, color, depth, opts) {
    const length = value.length

    if (value.includes('\n')) {
      value = value.replaceAll('\n', '\n' + '  '.repeat(depth))

      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.value = value
    this.color = opts.colors && color
  }

  toString(opts = {}) {
    const { offset = 0, pad = 0, indent = 0 } = opts

    let value = this.pad(pad, this.value)

    if (this.color) value = this.color + value + ansiEscapes.modifierReset

    return offset ? value : this.indent(indent, value)
  }
}

class InspectPair extends InspectNode {
  constructor(delim, left, right, depth, opts) {
    const length = left.length + delim.length + right.length

    if (left.breakAlways || right.breakAlways) {
      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.delim = delim
    this.left = left
    this.right = right
  }

  toString(opts = {}) {
    const { indent = 0 } = opts

    return this.indent(
      indent,
      this.left +
        this.delim +
        this.right.toString({
          indent,
          offset: this.left.length + this.delim.length
        })
    )
  }
}

class InspectSuspension extends InspectNode {
  constructor(overflow, depth, opts) {
    const label = `... ${overflow} more`

    super(depth, label.length, opts)

    this.label = label
  }

  toString(opts = {}) {
    const { indent = 0 } = opts

    return this.indent(indent, this.label)
  }
}

class InspectSequence extends InspectNode {
  constructor(header, footer, delim, values, ref, depth, opts) {
    const { tabulate = false } = opts

    const length =
      (ref.circular ? '<ref *>'.length + 1 : 0) +
      header.length +
      values.reduce(
        (length, value, i) =>
          length + value.length + (i === 0 ? 0 : delim.length),
        0
      ) +
      footer.length

    if (values.some((value) => value.breakAlways)) {
      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.header = header
    this.footer = footer
    this.delim = delim
    this.values = values
    this.ref = ref
    this.tabulate = tabulate
  }

  toString(opts = {}) {
    const { offset = 0, indent = 0 } = opts

    const split =
      this.breakAlways ||
      (this.values.length &&
        (offset + this.length > this.breakLength ||
          indent * 2 + this.length > this.breakLength))

    let header = this.header

    if (this.ref.circular) {
      header = '<ref *' + this.ref.id + '> ' + header
    }

    if (this.values.length === 0) {
      header = header.trimEnd()
    }

    if (offset === 0) {
      header = this.indent(indent, header)
    }

    if (split) {
      header = header.trimEnd() + '\n'
    }

    let string = header

    let columns = 1
    let pad = 0

    if (this.tabulate) {
      const widest = this.values.reduce(
        (length, value) =>
          value.breakAlways ? length : Math.max(length, value.length),
        0
      )

      if (widest) {
        columns = Math.max(
          columns,
          Math.floor(
            (this.breakLength - indent * 2) / (widest + this.delim.length)
          )
        )

        if (columns > 1) pad = widest
      }
    }

    for (let i = 0, n = this.values.length, offset = 0; i < n; i++) {
      const value = this.values[i]

      if (split) {
        let part

        if (i % columns === 0 || value.breakAlways) {
          part = value.toString({ indent: indent + 1, pad })
        } else {
          part = value.toString({ pad })
        }

        string += part

        if (i < n - 1) {
          if (i % columns === columns - 1 || this.values[i + 1].breakAlways) {
            string += this.delim.trimEnd() + '\n'
          } else {
            string += this.delim
          }
        }
      } else {
        if (i > 0) string += this.delim

        string += value.toString({ offset })

        offset += value.length
      }
    }

    let footer = this.footer

    if (this.values.length === 0) {
      footer = footer.trimStart()
    }

    if (split) {
      string += '\n' + this.indent(indent, footer.trimStart())
    } else {
      string += footer
    }

    return string
  }
}

function inspectValue(value, depth, opts) {
  const type = getType(value)

  if (type.isUndefined()) return inspectUndefined(depth, opts)
  if (type.isNull()) return inspectNull(depth, opts)
  if (type.isBoolean()) return inspectBoolean(value, depth, opts)
  if (type.isNumber()) return inspectNumber(value, depth, opts)
  if (type.isBigInt()) return inspectBigInt(value, depth, opts)
  if (type.isString()) return inspectString(value, depth, opts)
  if (type.isSymbol()) return inspectSymbol(value, depth, opts)
  if (type.isObject()) return inspectObject(type, value, depth, opts)
  if (type.isFunction()) return inspectFunction(type, value, depth, opts)
  if (type.isExternal()) return inspectExternal(value, opts, opts)
}

function inspectUndefined(depth, opts) {
  return new InspectLeaf('undefined', styles.undefined, depth, opts)
}

function inspectNull(depth, opts) {
  return new InspectLeaf('null', styles.null, depth, opts)
}

function inspectBoolean(value, depth, opts) {
  return new InspectLeaf(value.toString(), styles.boolean, depth, opts)
}

function inspectNumber(value, depth, opts) {
  let string

  if (Object.is(value, -0)) {
    string = '-0'
  } else {
    string = value.toString(10)
  }

  return new InspectLeaf(string, styles.number, depth, opts)
}

function inspectBigInt(value, depth, opts) {
  return new InspectLeaf(value.toString(10) + 'n', styles.bigint, depth, opts)
}

const STRING_ESCAPES =
  /[\ud800-\udbff][\udc00-\udfff]|[\u0000-\u001f'\\\ud800-\udfff]/g

function inspectString(value, depth, opts) {
  // https://tc39.es/ecma262/multipage/structured-data.html#sec-quotejsonstring
  const string = value.replace(STRING_ESCAPES, (match) => {
    if (match.length === 2) return match

    switch (match) {
      case "'":
        return "\\'"
      case '\\':
        return '\\\\'
      case '\b':
        return '\\b'
      case '\t':
        return '\\t'
      case '\n':
        return '\\n'
      case '\f':
        return '\\f'
      case '\r':
        return '\\r'
      default:
        return '\\u' + match.charCodeAt(0).toString(16).padStart(4, '0')
    }
  })

  return new InspectLeaf("'" + string + "'", styles.string, depth, opts)
}

function inspectSymbol(value, depth, opts) {
  return new InspectLeaf(value.toString(), styles.symbol, depth, opts)
}

function inspectKey(value, depth, opts) {
  if (PLAIN_KEY.test(value)) {
    return new InspectLeaf(value, null, depth, opts)
  } else {
    return inspectValue(value, depth, opts)
  }
}

function inspectObject(type, object, depth, opts) {
  const refs = opts.references

  let ref = refs.get(object)
  if (ref === null) {
    ref = new InspectRef(depth, opts)
    refs.set(object, ref)
  } else if (ref.count) {
    ref.circular = true
    return ref
  }

  const maxDepth = typeof opts.depth === 'number' ? opts.depth : Infinity

  if (maxDepth < depth) {
    const constructor = object.constructor

    return new InspectLeaf(
      '[' +
        (constructor && constructor.name ? constructor.name : 'Object') +
        ']',
      styles.special,
      depth,
      opts
    )
  }

  const inspect =
    object[Symbol.for('bare.inspect')] ||
    object[Symbol.for('nodejs.util.inspect.custom')]

  if (typeof inspect === 'function') {
    const value = inspect.call(
      object,
      typeof opts.depth === 'number' ? opts.depth - depth : null,
      {
        colors: opts.colors,
        breakLength: opts.breakLength,
        stylize: opts.stylize
      },
      exports
    )

    if (typeof value === 'object' && value !== null) {
      refs.set(value, ref)
    }

    if (typeof value !== 'string') {
      return inspectValue(value, depth, opts)
    }

    return new InspectLeaf(value, null, depth, opts)
  }

  if (type.isArray()) return inspectArray(object, ref, depth, opts)
  if (type.isDate()) return inspectDate(object, ref, depth, opts)
  if (type.isRegExp()) return inspectRegExp(object, ref, depth, opts)
  if (type.isError()) return inspectError(object, ref, depth, opts)
  if (type.isPromise()) return inspectPromise(object, ref, depth, opts)
  if (type.isMap()) return inspectMap(object, ref, depth, opts)
  if (type.isSet()) return inspectSet(object, ref, depth, opts)
  if (type.isWeakMap()) return inspectWeakMap(object, ref, depth, opts)
  if (type.isWeakSet()) return inspectWeakSet(object, ref, depth, opts)
  if (type.isWeakRef()) return inspectWeakRef(object, ref, depth, opts)
  if (type.isArrayBuffer()) return inspectArrayBuffer(object, ref, depth, opts)
  if (type.isSharedArrayBuffer())
    return inspectSharedArrayBuffer(object, ref, depth, opts)
  if (type.isTypedArray()) return inspectTypedArray(object, ref, depth, opts)
  if (type.isDataView()) return inspectDataView(object, ref, depth, opts)

  ref.increment()

  const values = []

  for (const key in object) {
    if (key === 'constructor') continue

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(object[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  let header = '{ '

  const tag = object[Symbol.toStringTag]

  if (tag) header = '[' + tag + '] ' + header

  if (object.constructor) {
    const name = object.constructor.name

    if (name && name !== 'Object') {
      header = object.constructor.name + ' ' + header
    }
  }

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectArray(array, ref, depth, opts) {
  const { maxArrayLength = defaultMaxArrayLength } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxArrayLength, 0)

  for (let i = 0, n = array.length; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(array.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(inspectValue(array[i], depth + 1, opts))
  }

  for (const key of binding.getOwnNonIndexPropertyNames(array)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(array[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  let header = '[ '

  if (array.constructor.name !== 'Array') {
    header = array.constructor.name + '(' + array.length + ') ' + header
  }

  return new InspectSequence(header, ' ]', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectDate(date, ref, depth, opts) {
  return new InspectLeaf(date.toISOString(), styles.date, depth, opts)
}

function inspectRegExp(regExp, ref, depth, opts) {
  return new InspectLeaf(regExp.toString(), styles.regexp, depth, opts)
}

function inspectError(error, ref, depth, opts) {
  let header

  if ('stack' in error) {
    header = error.stack

    if (depth > 0) {
      header = header.replaceAll('\n', '\n' + '  '.repeat(depth))
    }
  } else {
    header = error.toString()
  }

  const builtins = ['cause']

  if (error.name === 'AggregateError') {
    builtins.push('errors')
  } else if (error.name === 'SuppressedError') {
    builtins.push('error', 'suppressed')
  }

  const values = []

  for (const key of builtins) {
    if (key in error === false) continue

    values.push(
      new InspectPair(
        ': ',
        new InspectLeaf('[' + key + ']', null, depth + 1, opts),
        inspectValue(error[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key in error) {
    if (key === 'constructor' || builtins.includes(key)) continue

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(error[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  if (values.length === 0) return new InspectLeaf(header, null, depth, opts)

  return new InspectSequence(
    header + ' {',
    ' }',
    ', ',
    values,
    ref,
    depth,
    opts
  )
}

function inspectPromise(promise, ref, depth, opts) {
  ref.increment()

  const state = binding.getPromiseState(promise)

  const values = []

  switch (state) {
    case 0: // Pending
      values.push(new InspectLeaf('<pending>', styles.special, depth, opts))
      break

    case 1: // Fulfilled
      values.push(inspectValue(binding.getPromiseResult(promise), depth, opts))
      break

    case 2: // Rejected
      values.push(
        new InspectLeaf('<rejected>', styles.special, depth, opts),
        inspectValue(binding.getPromiseResult(promise), depth, opts)
      )
  }

  ref.decrement()

  const header = promise.constructor.name + ' { '

  return new InspectSequence(header, ' }', ' ', values, ref, depth, opts)
}

function inspectMap(map, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxMapLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = maxMapLength

  for (const entry of map) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(map.size - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )
      break
    }

    values.push(
      new InspectPair(
        ' => ',
        inspectValue(entry[0], depth + 1, opts),
        inspectValue(entry[1], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key in map) {
    if (key === 'constructor') continue

    const value = inspectValue(map[key], depth + 1, opts)

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        value,
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = map.constructor.name + '(' + map.size + ') { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectSet(set, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxSetLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = maxSetLength

  for (const entry of set) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(set.size - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )
      break
    }

    values.push(inspectValue(entry, depth + 1, opts))
  }

  for (const key in set) {
    if (key === 'constructor') continue

    const value = inspectValue(set[key], depth + 1, opts)

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        value,
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = set.constructor.name + '(' + set.size + ') { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectWeakMap(weakMap, ref, depth, opts) {
  const header = weakMap.constructor.name + ' { '

  return new InspectSequence(
    header,
    ' }',
    ' ',
    [new InspectLeaf('<items unknown>', styles.special, depth + 1, opts)],
    ref,
    depth,
    opts
  )
}

function inspectWeakSet(weakSet, ref, depth, opts) {
  const header = weakSet.constructor.name + ' { '

  return new InspectSequence(
    header,
    ' }',
    ' ',
    [new InspectLeaf('<items unknown>', styles.special, depth + 1, opts)],
    ref,
    depth,
    opts
  )
}

function inspectWeakRef(weakRef, ref, depth, opts) {
  const target = weakRef.deref()

  let value

  if (target === undefined) {
    value = new InspectLeaf('<cleared>', styles.special, depth + 1, opts)
  } else {
    value = inspectValue(target, depth + 1, opts)
  }

  const header = weakRef.constructor.name + ' { '

  return new InspectSequence(header, ' }', ' ', [value], ref, depth, opts)
}

function inspectArrayBuffer(arrayBuffer, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(arrayBuffer[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = arrayBuffer.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectSharedArrayBuffer(sharedArrayBuffer, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(sharedArrayBuffer[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = sharedArrayBuffer.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectTypedArray(typedArray, ref, depth, opts) {
  if (Buffer.isBuffer(typedArray)) {
    return inspectBuffer(typedArray, ref, depth, opts)
  }

  const {
    maxArrayLength = defaultMaxArrayLength,
    maxTypedArrayLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxTypedArrayLength, 0)

  for (let i = 0, n = typedArray.length; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(typedArray.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(inspectValue(typedArray[i], depth + 1, opts))
  }

  for (const key of binding.getOwnNonIndexPropertyNames(typedArray)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(typedArray[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = typedArray.constructor.name + '(' + typedArray.length + ') [ '

  return new InspectSequence(header, ' ]', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectBuffer(buffer, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxBufferLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxBufferLength, 0)

  for (let i = 0, n = buffer.byteLength; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(buffer.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(
      new InspectLeaf(
        buffer[i].toString(16).padStart(2, '0'),
        null,
        depth + 1,
        opts
      )
    )
  }

  for (const key of binding.getOwnNonIndexPropertyNames(buffer)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(buffer[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  return new InspectSequence('<Buffer ', '>', ' ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectDataView(dataView, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength', 'byteOffset', 'buffer']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(dataView[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key of binding.getOwnNonIndexPropertyNames(dataView)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(dataView[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = dataView.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectFunction(type, fn, depth, opts) {
  if (fn.toString().startsWith('class')) return inspectClass(fn, depth, opts)

  let tag = 'function'

  if (type.isGeneratorFunction()) tag = 'generator ' + tag
  if (type.isAsyncFunction()) tag = 'async ' + tag

  return new InspectLeaf(
    '[' + tag + ' ' + (fn.name ? fn.name : '(anonymous)') + ']',
    styles.special,
    depth,
    opts
  )
}

function inspectClass(ctor, depth, opts) {
  return new InspectLeaf(
    '[class ' + (ctor.name ? ctor.name : '(anonymous)') + ']',
    styles.special,
    depth,
    opts
  )
}

function inspectExternal(external, depth, opts) {
  return new InspectLeaf(
    '[external 0x' + binding.getExternal(external).toString(16) + ']',
    styles.special,
    depth,
    opts
  )
}
{
  "name": "bare-inspect",
  "version": "3.1.4",
  "description": "Inspect objects as strings for debugging",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-inspect.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-inspect/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-inspect#readme",
  "engines": {
    "bare": ">=1.18.0"
  },
  "dependencies": {
    "bare-ansi-escapes": "^2.1.0",
    "bare-type": "^1.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
module.exports = require.addon()
const binding = require('./binding')

const t = binding.constants

class Type {
  constructor(type) {
    this._type = type
  }

  isUndefined() {
    return this._type === t.UNDEFINED
  }

  isNull() {
    return this._type === t.NULL
  }

  isBoolean() {
    return this._type === t.BOOLEAN
  }

  isNumber() {
    return (this._type & 0xff) === t.NUMBER
  }

  isInt32() {
    return (this._type & (0xff | t.INT32)) === (t.NUMBER | t.INT32)
  }

  isUint32() {
    return (this._type & (0xff | t.UINT32)) === (t.NUMBER | t.UINT32)
  }

  isString() {
    return this._type === t.STRING
  }

  isSymbol() {
    return this._type === t.SYMBOL
  }

  isObject() {
    return (this._type & 0xff) === t.OBJECT
  }

  isArray() {
    return this._type === (t.OBJECT | t.ARRAY)
  }

  isArguments() {
    return this._type === (t.OBJECT | t.ARGUMENTS)
  }

  isDate() {
    return this._type === (t.OBJECT | t.DATE)
  }

  isRegExp() {
    return this._type === (t.OBJECT | t.REGEXP)
  }

  isError() {
    return this._type === (t.OBJECT | t.ERROR)
  }

  isPromise() {
    return this._type === (t.OBJECT | t.PROMISE)
  }

  isProxy() {
    return this._type === (t.OBJECT | t.PROXY)
  }

  isGenerator() {
    return this._type === (t.OBJECT | t.GENERATOR)
  }

  isMap() {
    return this._type === (t.OBJECT | t.MAP)
  }

  isSet() {
    return this._type === (t.OBJECT | t.SET)
  }

  isWeakMap() {
    return this._type === (t.OBJECT | t.WEAK_MAP)
  }

  isWeakSet() {
    return this._type === (t.OBJECT | t.WEAK_SET)
  }

  isWeakRef() {
    return this._type === (t.OBJECT | t.WEAK_REF)
  }

  isArrayBuffer() {
    return this._type === (t.OBJECT | t.ARRAYBUFFER)
  }

  isSharedArrayBuffer() {
    return this._type === (t.OBJECT | t.SHAREDARRAYBUFFER)
  }

  isTypedArray() {
    return (this._type & 0xffff) === (t.OBJECT | t.TYPEDARRAY)
  }

  isInt8Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT8ARRAY)
  }

  isUint8Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT8ARRAY)
  }

  isUint8ClampedArray() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT8CLAMPEDARRAY)
  }

  isInt16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT16ARRAY)
  }

  isUint16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT16ARRAY)
  }

  isInt32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT32ARRAY)
  }

  isUint32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT32ARRAY)
  }

  isFloat16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT16ARRAY)
  }

  isFloat32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT32ARRAY)
  }

  isFloat64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT64ARRAY)
  }

  isBigInt64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.BIGINT64ARRAY)
  }

  isBigUint64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.BIGUINT64ARRAY)
  }

  isDataView() {
    return this._type === (t.OBJECT | t.DATAVIEW)
  }

  isModuleNamespace() {
    return this._type === (t.OBJECT | t.MODULE_NAMESPACE)
  }

  isFunction() {
    return (this._type & 0xff) === t.FUNCTION
  }

  isAsyncFunction() {
    return (
      (this._type & (0xff | t.ASYNC_FUNCTION)) ===
      (t.FUNCTION | t.ASYNC_FUNCTION)
    )
  }

  isGeneratorFunction() {
    return (
      (this._type & (0xff | t.GENERATOR_FUNCTION)) ===
      (t.FUNCTION | t.GENERATOR_FUNCTION)
    )
  }

  isExternal() {
    return this._type === t.EXTERNAL
  }

  isBigInt() {
    return this._type === t.BIGINT
  }
}

module.exports = exports = function type(value) {
  switch (typeof value) {
    case 'undefined':
      return new Type(t.UNDEFINED)
    case 'boolean':
      return new Type(t.BOOLEAN)
    case 'number':
      return new Type(
        Number.isSafeInteger(value) ? binding.type(value) : t.NUMBER
      )
    case 'string':
      return new Type(t.STRING)
    case 'symbol':
      return new Type(t.SYMBOL)
    case 'object':
      return new Type(value === null ? t.NULL : binding.type(value))
    case 'function':
      return new Type(binding.type(value))
    case 'bigint':
      return new Type(t.BIGINT)
  }
}

exports.createTag = function createTag(...components) {
  const tag = new Uint32Array(4)
  for (let i = 0; i < 4; i++) tag[i] = components[i] || 0
  return tag
}

exports.addTag = function addTag(object, tag) {
  binding.addTag(object, tag)
}

exports.checkTag = function checkTag(object, tag) {
  return binding.checkTag(object, tag)
}
{
  "name": "bare-type",
  "version": "1.1.0",
  "description": "Cross-realm type predicates for Bare",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-type.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-type/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-type#readme",
  "engines": {
    "bare": ">=1.2.0"
  },
  "devDependencies": {
    "brittle": "^3.4.0",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
/**
 * jsonSchema — helper to build a Room schema from a single apply function
 *
 * Most domain schemas (issues, orgs, todos) just want JSON encoding +
 * a switch in the apply function. This helper saves them from defining
 * encodeOp/decodeOp/validateOp boilerplate.
 *
 * Usage:
 *
 *   import { jsonSchema } from 'hyper-rooms'
 *
 *   const todosSchema = jsonSchema({
 *     async apply (batch, op, host) {
 *       if (op.type === 'add-todo') {
 *         await batch.put(`todo:${op.id}`, { text: op.text, done: false })
 *       }
 *     },
 *     // optional: validate ops before encoding
 *     validate (op) {
 *       if (op.type === 'add-todo' && !op.text) throw new Error('text required')
 *     }
 *   })
 *
 *   const room = new Room(corestore, { schema: todosSchema })
 */

import b4a from 'b4a'

export function jsonSchema ({ apply, validate } = {}) {
  if (typeof apply !== 'function') {
    throw new Error('jsonSchema requires an apply function')
  }

  return {
    encodeOp (op) {
      return b4a.from(JSON.stringify(op), 'utf8')
    },

    decodeOp (buf) {
      const str = b4a.toString(buf, 'utf8')
      return JSON.parse(str)
    },

    validateOp (op) {
      if (!op || typeof op !== 'object') throw new Error('op must be an object')
      if (typeof op.type !== 'string') throw new Error('op.type must be a string')
      if (validate) validate(op)
    },

    apply
  }
}
/**
 * Room — multiwriter substrate built on Autobase + Hyperbee view.
 *
 * Extracted from the duplicated patterns in packages/hyper-issues and
 * packages/hyper-orgs. Both modules had nearly identical Autobase setup,
 * Hyperbee view, and writer-management apply logic — the only difference
 * was their domain-specific ops.
 *
 * `Room` handles:
 *   - Autobase + Hyperbee view boilerplate
 *   - Generic writer-management ops (add-writer, remove-writer)
 *   - Op encode/decode delegation to a pluggable schema
 *   - Single-writer or multi-writer (Autobase handles both)
 *
 * Schemas plug in by providing:
 *   - encodeOp(op) → Buffer
 *   - decodeOp(buf) → op object
 *   - validateOp(op) → throws on invalid
 *   - apply(batch, op, host) → mutates the Hyperbee batch
 *
 * The schema's apply is called for every NON-writer op. Writer ops are
 * handled by Room itself.
 *
 * Usage:
 *
 *   import { Room } from 'hyper-rooms'
 *
 *   const room = new Room(corestore, {
 *     schema: myIssuesSchema,
 *     namespace: 'project-x',
 *     bootstrapKey: existingKey || null  // null = create new room
 *   })
 *   await room.ready()
 *
 *   // Append a domain op (validated by schema, applied to view)
 *   await room.append({ type: 'create-issue', id: 1, title: 'Bug' })
 *
 *   // Read the view directly
 *   const issue = await room.view.get('issue:1')
 *
 *   // Add a writer (other process holds writerKey from their local hypercore)
 *   await room.addWriter('alice', { writerKey: aliceLocalKeyHex, role: 'writer' })
 *
 *   // Replicate via Hyperswarm
 *   swarm.on('connection', (conn) => room.corestore.replicate(conn))
 */

import Autobase from 'autobase'
import Hyperbee from 'hyperbee'
import Hypercore from 'hypercore'
import ReadyResource from 'ready-resource'
import b4a from 'b4a'
import crypto from 'hypercore-crypto'

/**
 * Sign a writer-rotation vouch: the voucher (an existing writer) signs the NEW
 * writer key, authorizing its admission via the doorbell (see Room.requestWriter
 * / _applyRequestWriter). Returns the signature hex.
 * @param {string} newWriterKeyHex - the new local writer key being vouched for
 * @param {Buffer} voucherSecretKey - the existing writer's hypercore secret key
 */
export function signWriterVouch (newWriterKeyHex, voucherSecretKey) {
  return b4a.toString(crypto.sign(b4a.from(newWriterKeyHex, 'hex'), voucherSecretKey), 'hex')
}

export class Room extends ReadyResource {
  /**
   * @param {Corestore} corestore - parent corestore (will be namespaced)
   * @param {object} opts
   * @param {object} opts.schema - { encodeOp, decodeOp, validateOp, apply }
   * @param {string} [opts.namespace='room'] - corestore namespace for isolation
   * @param {Buffer|string|null} [opts.bootstrapKey=null] - existing room key, null = create new
   * @param {string} [opts.viewName='view'] - hyperbee core name within the namespace
   */
  constructor (corestore, opts = {}) {
    super()
    if (!opts.schema) throw new Error('Room requires a schema')
    this._validateSchema(opts.schema)

    this._schema = opts.schema
    this._namespace = opts.namespace || 'room'
    this._viewName = opts.viewName || 'view'
    this._corestore = corestore.namespace(this._namespace)
    this._bootstrapKey = this._normalizeKey(opts.bootstrapKey)

    // Canonical multi-writer Autobase config — see hyper-identity/identity-registry.js
    // for full rationale. optimistic+ackInterval+ackThreshold = keet pattern.
    this._base = new Autobase(this._corestore, this._bootstrapKey, {
      open: (store) => {
        const core = store.get(this._viewName, { valueEncoding: 'json' })
        return new Hyperbee(core, {
          keyEncoding: 'utf-8',
          valueEncoding: 'json'
        })
      },
      apply: this._apply.bind(this),
      valueEncoding: 'binary',
      optimistic: true,
      ackInterval: 1000,
      ackThreshold: 4
    })

    // Resilience (pear-git #3): autobase routes any drain/apply failure through
    // _onError → emit('error'). With NO 'error' listener, EventEmitter re-throws,
    // so ONE broken tracker SIGABRTs the whole daemon — crash-looping and taking
    // every other repo down. A standalone peer hits this when its stale local
    // state can't reconcile a manifest migration that happened in the group,
    // whereas full-replica mirrors never do (they take the finished picture).
    // Attach handlers so a broken tracker is ISOLATED + observable instead of
    // fatal — matching keet's room-autobase 'error'/'warning' handlers. Consumers
    // react to the re-emitted 'base-error' (Increment 2: fresh-namespace re-sync).
    // Custom event names never throw when unlistened, so re-emitting is safe.
    this._baseError = null
    this._base.on('error', (err) => {
      this._baseError = err
      try {
        // eslint-disable-next-line no-console
        console.error('[hyper-rooms] tracker autobase error (ns=' + this._namespace + '): ' + (err && err.message ? err.message : err))
      } catch {}
      this.emit('base-error', err)
    })
    this._base.on('warning', (err) => {
      try {
        // eslint-disable-next-line no-console
        console.error('[hyper-rooms] tracker autobase warning (ns=' + this._namespace + '): ' + (err && err.message ? err.message : err))
      } catch {}
      this.emit('base-warning', err)
    })
  }

  // ── Lifecycle ────────────────────────────────────────────────

  async _open () {
    await this._base.ready()
  }

  async _close () {
    await this._base.close()
  }

  // ── Properties ───────────────────────────────────────────────

  /** Bootstrap key (Autobase root). Share this to invite mirrors / readers. */
  get key () { return this._base.key }
  get keyHex () { return this._base.key ? b4a.toString(this._base.key, 'hex') : null }
  get discoveryKey () { return this._base.discoveryKey }

  /** Local writer key (this peer's Hypercore). Share THIS for addWriter on the inviter. */
  get localKey () { return this._base.local ? this._base.local.key : null }
  get localKeyHex () { return this._base.local ? b4a.toString(this._base.local.key, 'hex') : null }

  /** True if this peer can append ops. */
  get writable () { return this._base.writable }

  /**
   * The autobase error that isolated this room, if any (resilience, #3).
   * Non-null once the tracker's autobase has emitted 'error' (e.g. a stale
   * local state that couldn't reconcile a group manifest migration). A consumer
   * treats a non-null value as "this tracker is broken — re-sync it fresh".
   */
  get errored () { return this._baseError }

  /** Read-only access to the Hyperbee view. */
  get view () { return this._base.view }

  /** The corestore (namespaced). For replication via swarm. */
  get corestore () { return this._corestore }

  /** Underlying Autobase (escape hatch). */
  get base () { return this._base }

  // ── Op append (writer side) ──────────────────────────────────

  /**
   * Append a domain op to the room. The schema validates and encodes it.
   * Writer ops (add-writer / remove-writer) should NOT be appended via this
   * method — use addWriter() / removeWriter() instead.
   *
   * @param {object} op - the op object (will be validated by the schema)
   */
  async append (op) {
    if (op && (op.type === 'add-writer' || op.type === 'remove-writer')) {
      throw new Error('Use addWriter() / removeWriter() for writer ops')
    }
    this._schema.validateOp(op)
    const encoded = this._schema.encodeOp(op)
    await this._base.append(encoded)
  }

  // ── Writer management ────────────────────────────────────────

  /**
   * Append an add-writer op. The new peer must already have its OWN local
   * Hypercore in some other corestore — pass the hex key of that local core.
   *
   * Roles:
   *   - 'owner'  → indexer = true (full Autobase indexer)
   *   - 'writer' → indexer = false (can append, doesn't index)
   *   - 'mirror' → metadata only, NOT registered as a writer (read-only mirror)
   *
   * @param {string} userId - opaque identifier for the writer
   * @param {object} opts
   * @param {string} opts.writerKey - hex of the writer's local Hypercore key
   * @param {'owner'|'writer'|'mirror'} [opts.role='writer']
   * @param {string} [opts.addedBy] - who added this writer (for audit trail)
   */
  async addWriter (userId, opts = {}) {
    const { writerKey, role = 'writer', addedBy = null } = opts
    if (!writerKey) throw new Error('addWriter requires opts.writerKey (hex)')
    if (!['owner', 'writer', 'mirror'].includes(role)) {
      throw new Error('role must be owner, writer, or mirror')
    }

    const op = {
      type: 'add-writer',
      userId,
      writerKey,
      role,
      addedBy,
      timestamp: Date.now()
    }
    await this._base.append(this._schema.encodeOp(op))
  }

  /**
   * DOORBELL: a not-yet-admitted peer requests admission of its own new writer
   * key, proving authorization by a VOUCH from an existing writer key (keet's
   * proof-gated-optimistic admission, using the writer set as the authorization
   * record). Used when an existing writer ROTATES its key (e.g. forceResync
   * re-join into a fresh corestore): the peer signs its NEW key with its OLD
   * (still-admitted) writer key. apply (_applyRequestWriter) admits ONLY if the
   * vouch verifies AND the voucher is a current writer — and only ever as a
   * PLAIN writer (never indexer/owner: no self-escalation).
   *
   * Appended OPTIMISTICALLY so a not-yet-writable peer can ring it; it carries
   * only the proof (no content), so nothing is lost if no indexer admits it.
   *
   * autobase writer keys are MANIFEST keys, not raw signing keys, so the vouch
   * carries the voucher's raw SIGNER publicKey; apply recomputes the manifest
   * key from it (`Hypercore.key({signers:[{publicKey}]})`) to bind it back to a
   * current writer.
   *
   * @param {object} opts
   * @param {string} opts.newWriterKey    - this peer's new local writer key (hex)
   * @param {string} opts.voucherSignerKey - the voucher writer's raw signer publicKey (hex);
   *                                         from `oldRoom.base.local.keyPair.publicKey`
   * @param {string} opts.voucherSig      - signWriterVouch(newWriterKey, voucherSignerSecretKey)
   * @param {string} [opts.userId]        - writer-set label (default = newWriterKey)
   */
  async requestWriter (opts = {}) {
    const { newWriterKey, voucherSignerKey, voucherSig, userId } = opts
    if (!newWriterKey) throw new Error('requestWriter requires newWriterKey (hex)')
    if (!voucherSignerKey || !voucherSig) throw new Error('requestWriter requires voucherSignerKey + voucherSig')
    const op = {
      type: 'request-writer',
      userId: userId || newWriterKey,
      newWriterKey,
      voucherSignerKey,
      voucherSig,
      timestamp: Date.now()
    }
    await this._base.append(this._schema.encodeOp(op), { optimistic: true })
  }

  /**
   * Append a remove-writer op for the given userId.
   * @param {string} userId
   */
  async removeWriter (userId) {
    const op = {
      type: 'remove-writer',
      userId,
      timestamp: Date.now()
    }
    await this._base.append(this._schema.encodeOp(op))
  }

  /**
   * List all writers in the view.
   * @returns {Promise<Array<{ userId, role, writerKey, addedBy, addedAt }>>}
   */
  async listWriters () {
    const out = []
    for await (const entry of this._base.view.createReadStream({
      gte: 'writer:',
      lt: 'writer:\xff'
    })) {
      out.push({
        userId: entry.key.slice('writer:'.length),
        ...entry.value
      })
    }
    return out
  }

  /**
   * Get a specific writer by userId.
   */
  async getWriter (userId) {
    const entry = await this._base.view.get(`writer:${userId}`)
    return entry ? entry.value : null
  }

  // ── Apply function (called by Autobase) ──────────────────────

  async _apply (nodes, view, host) {
    const batch = view.batch()

    for (const node of nodes) {
      let op
      try {
        op = this._schema.decodeOp(node.value)
      } catch (err) {
        // Invalid op — skip silently to keep apply deterministic
        continue
      }

      // Generic writer ops. `node` is passed through so the apply can see WHO
      // authored the op — authorization for writer-set changes lives here, not
      // at the RPC that happened to produce them (org #15).
      if (op.type === 'add-writer') {
        await this._applyAddWriter(batch, op, host, node)
        continue
      }
      if (op.type === 'remove-writer') {
        await this._applyRemoveWriter(batch, op, host, node)
        continue
      }
      if (op.type === 'request-writer') {
        await this._applyRequestWriter(view, batch, op, host)
        continue
      }

      // Schema-specific ops
      try {
        await this._schema.apply(batch, op, host)
      } catch (err) {
        // Don't throw inside apply — log and continue.
        // (apply must be deterministic; an exception would corrupt state.)
        // eslint-disable-next-line no-console
        console.error('[Room] schema.apply error:', err.message)
      }
    }

    await batch.flush()
  }

  /**
   * Is the op's author a current INDEXER of this room? (org #15)
   *
   * Autobase hands every apply node a `from` — the authoring writer's core —
   * so the writer set can be authorized from inside apply, which is the only
   * place that works: apply runs on ops that arrive by REPLICATION, not just
   * on ops that came through some RPC, so a gate on the RPC (pear-git-v3's
   * requireAdmin on repo-add-writer) cannot bind an op appended directly to
   * the base by an existing writer.
   *
   * Indexers are autobase's own trust root — the quorum that signs the
   * linearized view — so "author is an indexer" is the same authority the
   * room already relies on, not a new concept layered on top.
   *
   * Genesis: before any indexer is recorded, the room's creator is the only
   * possible author and there is nobody to authorize against, so allow.
   */
  _authorIsIndexer (host, node) {
    const author = node && node.from && node.from.key
    if (!author) return false

    const system = host && host.system
    const indexers = system && Array.isArray(system.indexers) ? system.indexers : []
    if (indexers.length === 0) return true

    for (const idx of indexers) {
      if (idx && idx.key && b4a.equals(idx.key, author)) return true
    }
    return false
  }

  // Refusals are LOGGED, never silent. A writer-set change that stops applying
  // is otherwise indistinguishable from replication lag, and this gate is new
  // behaviour on a substrate that hyper-issues and hyper-orgs both build on.
  _refuseWriterOp (kind, op, node) {
    const author = node && node.from && node.from.key
    // eslint-disable-next-line no-console
    console.error('[hyper-rooms] refused ' + kind + ' (ns=' + this._namespace + '): author ' +
      (author ? b4a.toString(author, 'hex').slice(0, 16) : 'unknown') +
      ' is not a current indexer; userId=' + (op && op.userId))
  }

  /**
   * Apply an add-writer op. (org #15)
   *
   * This used to honour ANY add-writer op that appeared in the linearized log,
   * with no check on who authored it — and `indexer: op.role === 'owner'` took
   * the role straight from the op. So an existing plain writer could append
   * `{type:'add-writer', role:'owner'}` for its own key and promote ITSELF to
   * indexer, bypassing the requireAdmin on the RPC entirely.
   *
   * That was worse than a permissions issue: changing the indexer set migrates
   * the autobase manifest, which is precisely what poisons standalone-peer
   * trackers (pear-git #3), so it doubled as a denial of service on the room.
   *
   * Now the author must be a current indexer. Note this leaves promotion in
   * the hands of existing indexers — which is what `pgh org set-auth --level
   * owner` and `pgh repo grant-writer` already are — while removing the
   * self-service path a plain writer had.
   */
  async _applyAddWriter (batch, op, host, node) {
    if (!this._authorIsIndexer(host, node)) {
      this._refuseWriterOp('add-writer', op, node)
      return
    }

    await batch.put(`writer:${op.userId}`, {
      role: op.role,
      writerKey: op.writerKey || null,
      addedBy: op.addedBy || null,
      addedAt: op.timestamp || Date.now()
    })

    if (op.writerKey && op.role !== 'mirror') {
      try {
        await host.addWriter(b4a.from(op.writerKey, 'hex'), {
          indexer: op.role === 'owner'
        })
      } catch (err) {
        // eslint-disable-next-line no-console
        console.error('[Room] host.addWriter failed:', err.message)
      }
    }
  }

  // DOORBELL apply (see requestWriter). Deterministic, proof-gated: admit
  // op.newWriterKey ONLY if (1) op.voucherSig is a valid signature of
  // op.newWriterKey by op.voucherKey, AND (2) op.voucherKey is a CURRENT
  // non-mirror writer in this room. Authorizes a key ROTATION by an existing
  // writer; grants a PLAIN writer only (never indexer). Silently no-ops on a
  // bad proof — a forged/unauthorized request admits nothing.
  async _applyRequestWriter (view, batch, op, host) {
    const { newWriterKey, voucherSignerKey, voucherSig } = op
    if (!newWriterKey || !voucherSignerKey || !voucherSig) return

    // (1) verify the vouch signature over the new key by the raw signer key
    let sigOk = false
    try {
      sigOk = crypto.verify(
        b4a.from(newWriterKey, 'hex'),
        b4a.from(voucherSig, 'hex'),
        b4a.from(voucherSignerKey, 'hex')
      )
    } catch { sigOk = false }
    if (!sigOk) return

    // (2) bind the signer to a writer key: recompute the default single-signer
    // MANIFEST key from the signer publicKey (autobase writer keys are manifests,
    // not raw keys). A non-default manifest simply won't match → safe rejection.
    let voucherKey
    try {
      voucherKey = b4a.toString(Hypercore.key({ signers: [{ publicKey: b4a.from(voucherSignerKey, 'hex') }] }), 'hex')
    } catch { return }

    // (3) that manifest key must be a current, non-mirror writer in this room
    let voucherIsWriter = false
    try {
      for await (const entry of view.createReadStream({ gte: 'writer:', lt: 'writer:\xff' })) {
        const v = entry.value
        if (v && v.writerKey === voucherKey && v.role !== 'mirror') { voucherIsWriter = true; break }
      }
    } catch { voucherIsWriter = false }
    if (!voucherIsWriter) return

    // Admit — PLAIN writer only (no self-escalation to indexer/owner).
    const userId = op.userId || newWriterKey
    await batch.put(`writer:${userId}`, {
      role: 'writer',
      writerKey: newWriterKey,
      addedBy: 'doorbell:' + voucherKey.slice(0, 16),
      addedAt: op.timestamp || 0
    })
    try {
      await host.addWriter(b4a.from(newWriterKey, 'hex'), { indexer: false })
    } catch (err) {
      // eslint-disable-next-line no-console
      console.error('[Room] doorbell addWriter failed:', err.message)
    }
  }

  // Same authorization as add-writer (org #15). Not named in the issue, but it
  // is the same defect on the same writer set: ungated, any writer could evict
  // any other writer — including an indexer — by appending one op. Gating only
  // the add side would have left the room removable by a plain writer.
  async _applyRemoveWriter (batch, op, host, node) {
    if (!this._authorIsIndexer(host, node)) {
      this._refuseWriterOp('remove-writer', op, node)
      return
    }

    const existing = await batch.get(`writer:${op.userId}`)
    if (!existing) return

    await batch.del(`writer:${op.userId}`)

    if (existing.value.writerKey) {
      try {
        await host.removeWriter(b4a.from(existing.value.writerKey, 'hex'))
      } catch (err) {
        // eslint-disable-next-line no-console
        console.error('[Room] host.removeWriter failed:', err.message)
      }
    }
  }

  // ── Helpers ──────────────────────────────────────────────────

  _normalizeKey (key) {
    if (!key) return null
    return typeof key === 'string' ? b4a.from(key, 'hex') : key
  }

  _validateSchema (schema) {
    const required = ['encodeOp', 'decodeOp', 'validateOp', 'apply']
    for (const fn of required) {
      if (typeof schema[fn] !== 'function') {
        throw new Error(`Schema missing required function: ${fn}`)
      }
    }
  }
}
const { Pull, Push, HEADERBYTES, KEYBYTES, ABYTES } = require('sodium-secretstream')
const sodium = require('sodium-universal')
const crypto = require('hypercore-crypto')
const { Duplex, Writable, getStreamError } = require('streamx')
const b4a = require('b4a')
const Timeout = require('timeout-refresh')
const unslab = require('unslab')
const Bridge = require('./lib/bridge')
const Handshake = require('./lib/handshake')

const IDHEADERBYTES = HEADERBYTES + 32
const [NS_INITIATOR, NS_RESPONDER, NS_SEND] = crypto.namespace('hyperswarm/secret-stream', 3)
const MAX_ATOMIC_WRITE = 256 * 256 * 256 - 1

module.exports = class NoiseSecretStream extends Duplex {
  constructor(isInitiator, rawStream, opts = {}) {
    super({ mapWritable: toBuffer })

    if (typeof isInitiator !== 'boolean') {
      throw new Error('isInitiator should be a boolean')
    }

    this.noiseStream = this
    this.isInitiator = isInitiator
    this.rawStream = null

    this.publicKey = opts.publicKey || null
    this.remotePublicKey = opts.remotePublicKey || null
    this.handshakeHash = null
    this.connected = false
    this.keepAlive = opts.keepAlive || 0
    this.timeout = 0
    this.enableSend = opts.enableSend !== false

    // pointer for upstream to set data here if they want
    this.userData = null

    let openedDone = null
    this.opened = new Promise((resolve) => {
      openedDone = resolve
    })

    this.rawBytesWritten = 0
    this.rawBytesRead = 0

    // metadata used by 'hyperdht'
    this.relay = null
    this.puncher = null

    // unwrapped raw stream
    this._rawStream = null

    // handshake state
    this._handshake = null
    this._handshakePattern = opts.pattern || null
    this._handshakeDone = null

    // message parsing state
    this._state = 0
    this._len = 0
    this._tmp = 1
    this._message = null

    this._openedDone = openedDone
    this._startDone = null
    this._drainDone = null
    this._outgoingPlain = null
    this._outgoingWrapped = null
    this._utp = null
    this._setup = true
    this._ended = 2
    this._encrypt = null
    this._decrypt = null
    this._timeoutTimer = null
    this._keepAliveTimer = null
    this._sendState = null

    if (opts.autoStart !== false) this.start(rawStream, opts)

    // wiggle it to trigger open immediately (TODO add streamx option for this)
    this.resume()
    this.pause()
  }

  static keyPair(seed) {
    return Handshake.keyPair(seed)
  }

  static id(handshakeHash, isInitiator, id) {
    return streamId(handshakeHash, isInitiator, id)
  }

  setTimeout(ms) {
    if (!ms) ms = 0

    this._clearTimeout()
    this.timeout = ms

    if (!ms || this.rawStream === null) return

    this._timeoutTimer = Timeout.once(ms, destroyTimeout, this)
    this._timeoutTimer.unref()
  }

  setKeepAlive(ms) {
    if (!ms) ms = 0

    this._clearKeepAlive()

    this.keepAlive = ms

    if (!ms || this.rawStream === null) return

    this._keepAliveTimer = Timeout.on(ms, sendKeepAlive, this)
    this._keepAliveTimer.unref()
  }

  sendKeepAlive() {
    const empty = this.alloc(0)
    this.write(empty)
  }

  start(rawStream, opts = {}) {
    if (rawStream) {
      this.rawStream = rawStream
      this._rawStream = rawStream
      if (typeof this.rawStream.setContentSize === 'function') {
        this._utp = rawStream
      }
    } else {
      this.rawStream = new Bridge(this)
      this._rawStream = this.rawStream.reverse
    }

    this.rawStream.on('error', this._onrawerror.bind(this))
    this.rawStream.on('close', this._onrawclose.bind(this))

    this._startHandshake(opts.handshake, opts.keyPair || null)
    this._continueOpen(null)

    if (this.destroying) return

    if (opts.data) this._onrawdata(opts.data)
    if (opts.ended) this._onrawend()

    if (this.keepAlive > 0 && this._keepAliveTimer === null) {
      this.setKeepAlive(this.keepAlive)
    }

    if (this.timeout > 0 && this._timeoutTimer === null) {
      this.setTimeout(this.timeout)
    }
  }

  async flush() {
    if ((await this.opened) === false) return false
    if ((await Writable.drained(this)) === false) return false
    if (this.destroying) return false

    if (this.rawStream !== null && this.rawStream.flush) {
      return await this.rawStream.flush()
    }

    return true
  }

  _continueOpen(err) {
    if (err) this.destroy(err)
    if (this._startDone === null) return
    const done = this._startDone
    this._startDone = null
    this._open(done)
  }

  _onkeypairpromise(p) {
    const self = this
    const cont = this._continueOpen.bind(this)

    p.then(onkeypair, cont)

    function onkeypair(kp) {
      self._onkeypair(kp)
      cont(null)
    }
  }

  _onkeypair(keyPair) {
    const pattern = this._handshakePattern || 'XX'
    const remotePublicKey = this.remotePublicKey

    this._handshake = new Handshake(this.isInitiator, keyPair, remotePublicKey, pattern)
    this.publicKey = this._handshake.keyPair.publicKey
  }

  _startHandshake(handshake, keyPair) {
    if (handshake) {
      const { tx, rx, hash, publicKey, remotePublicKey } = handshake
      this._setupSecretStream(tx, rx, hash, publicKey, remotePublicKey)
      return
    }

    if (!keyPair) keyPair = Handshake.keyPair()

    if (typeof keyPair.then === 'function') {
      this._onkeypairpromise(keyPair)
    } else {
      this._onkeypair(keyPair)
    }
  }

  _onrawerror(err) {
    this.destroy(err)
  }

  _onrawclose() {
    if (this._ended !== 0) this.destroy()
  }

  _onrawdata(data) {
    let offset = 0

    if (this._timeoutTimer !== null) {
      this._timeoutTimer.refresh()
    }

    do {
      switch (this._state) {
        case 0: {
          while (this._tmp !== 0x1000000 && offset < data.byteLength) {
            const v = data[offset++]
            this._len += this._tmp * v
            this._tmp *= 256
          }

          if (this._tmp === 0x1000000) {
            this._tmp = 0
            this._state = 1
            const unprocessed = data.byteLength - offset
            if (unprocessed < this._len && this._utp !== null)
              this._utp.setContentSize(this._len - unprocessed)
          }

          break
        }

        case 1: {
          const missing = this._len - this._tmp
          const end = missing + offset

          if (this._message === null && end <= data.byteLength) {
            this._message = data.subarray(offset, end)
            offset += missing
            this._incoming()
            break
          }

          const unprocessed = data.byteLength - offset

          if (this._message === null) {
            this._message = b4a.allocUnsafe(this._len)
          }

          b4a.copy(data, this._message, this._tmp, offset)
          this._tmp += unprocessed

          if (end <= data.byteLength) {
            offset += missing
            this._incoming()
          } else {
            offset += unprocessed
          }

          break
        }
      }
    } while (offset < data.byteLength && !this.destroying)
  }

  _onrawend() {
    this._ended--
    this.push(null)
  }

  _onrawdrain() {
    const drain = this._drainDone
    if (drain === null) return
    this._drainDone = null
    drain()
  }

  _read(cb) {
    this.rawStream.resume()
    cb(null)
  }

  _incoming() {
    const message = this._message

    this._state = 0
    this._len = 0
    this._tmp = 1
    this._message = null

    if (this._setup === true) {
      if (this._handshake) {
        this._onhandshakert(this._handshake.recv(message))
      } else {
        if (message.byteLength !== IDHEADERBYTES) {
          this.destroy(new Error('Invalid header message received'))
          return
        }

        const remoteId = message.subarray(0, 32)
        const expectedId = streamId(this.handshakeHash, !this.isInitiator)
        const header = message.subarray(32)

        if (!b4a.equals(expectedId, remoteId)) {
          this.destroy(new Error('Invalid header received'))
          return
        }

        this._decrypt.init(header)
        this._setup = false // setup is now done
      }
      return
    }

    if (message.byteLength < ABYTES) {
      this.destroy(new Error('Invalid message received'))
      return
    }

    this.rawBytesRead += message.byteLength

    const plain = message.subarray(1, message.byteLength - ABYTES + 1)

    try {
      this._decrypt.next(message, plain)
    } catch (err) {
      this.destroy(err)
      return
    }

    // If keep alive is selective, eat the empty buffers (ie assume the other side has it enabled also)
    if (plain.byteLength === 0 && this.keepAlive !== 0) return

    if (this.push(plain) === false) {
      this.rawStream.pause()
    }
  }

  _onhandshakert(h) {
    if (this._handshakeDone === null) return

    if (h !== null) {
      if (h.data) this._rawStream.write(h.data)
      if (!h.tx) return
    }

    const done = this._handshakeDone
    const publicKey = this._handshake.keyPair.publicKey

    this._handshakeDone = null
    this._handshake = null

    if (h === null) return done(new Error('Noise handshake failed'))

    this._setupSecretStream(h.tx, h.rx, h.hash, publicKey, h.remotePublicKey)
    this._resolveOpened(true)
    done(null)
  }

  _setupSecretStream(tx, rx, handshakeHash, publicKey, remotePublicKey) {
    const buf = b4a.allocUnsafeSlow(3 + IDHEADERBYTES)
    writeUint24le(IDHEADERBYTES, buf)

    this._encrypt = new Push(unslab(tx.subarray(0, KEYBYTES)), undefined, buf.subarray(3 + 32))
    this._decrypt = new Pull(unslab(rx.subarray(0, KEYBYTES)))

    this.publicKey = publicKey
    this.remotePublicKey = remotePublicKey
    this.handshakeHash = handshakeHash

    const id = buf.subarray(3, 3 + 32)
    streamId(handshakeHash, this.isInitiator, id)

    // initialize secretbox state for unordered messages
    this._setupSecretSend(handshakeHash)

    this.emit('handshake')
    // if rawStream is a bridge, also emit it there
    if (this.rawStream !== this._rawStream) this.rawStream.emit('handshake')

    if (this.destroying) return

    this._rawStream.write(buf)
  }

  _setupSecretSend(handshakeHash) {
    this._sendState = b4a.allocUnsafeSlow(32 + 32 + 8 + 8)
    const encrypt = this._sendState.subarray(0, 32) // secrets
    const decrypt = this._sendState.subarray(32, 64)
    const counter = this._sendState.subarray(64, 72) // nonce
    const initial = this._sendState.subarray(72)

    const inputs = this.isInitiator
      ? [
          [NS_INITIATOR, NS_SEND],
          [NS_RESPONDER, NS_SEND]
        ]
      : [
          [NS_RESPONDER, NS_SEND],
          [NS_INITIATOR, NS_SEND]
        ]

    sodium.crypto_generichash_batch(encrypt, inputs[0], handshakeHash)
    sodium.crypto_generichash_batch(decrypt, inputs[1], handshakeHash)

    sodium.randombytes_buf(initial)
    counter.set(initial)
  }

  _open(cb) {
    // no autostart or no handshake yet
    if (this._rawStream === null || (this._handshake === null && this._encrypt === null)) {
      this._startDone = cb
      return
    }

    this._rawStream.on('data', this._onrawdata.bind(this))
    this._rawStream.on('end', this._onrawend.bind(this))
    this._rawStream.on('drain', this._onrawdrain.bind(this))

    if (this.enableSend) this._rawStream.on('message', this._onmessage.bind(this))

    if (this._encrypt !== null) {
      this._resolveOpened(true)
      return cb(null)
    }

    this._handshakeDone = cb

    if (this.isInitiator) this._onhandshakert(this._handshake.send())
  }

  _predestroy() {
    if (this.rawStream) {
      const error = getStreamError(this)
      this.rawStream.destroy(error)
    }

    if (this._startDone !== null) {
      const done = this._startDone
      this._startDone = null
      done(new Error('Stream destroyed'))
    }

    if (this._handshakeDone !== null) {
      const done = this._handshakeDone
      this._handshakeDone = null
      done(new Error('Stream destroyed'))
    }

    if (this._drainDone !== null) {
      const done = this._drainDone
      this._drainDone = null
      done(new Error('Stream destroyed'))
    }
  }

  _write(data, cb) {
    let wrapped = this._outgoingWrapped

    if (data !== this._outgoingPlain) {
      wrapped = b4a.allocUnsafe(data.byteLength + 3 + ABYTES)
      wrapped.set(data, 4)
    } else {
      this._outgoingWrapped = this._outgoingPlain = null
    }

    if (wrapped.byteLength - 3 > MAX_ATOMIC_WRITE) {
      return cb(
        new Error(
          'Message is too large for an atomic write. Max size is ' + MAX_ATOMIC_WRITE + ' bytes.'
        )
      )
    }
    this.rawBytesWritten += wrapped.byteLength

    writeUint24le(wrapped.byteLength - 3, wrapped)
    // offset 4 so we can do it in-place
    this._encrypt.next(wrapped.subarray(4, 4 + data.byteLength), wrapped.subarray(3))

    if (this._keepAliveTimer !== null) this._keepAliveTimer.refresh()

    if (this._rawStream.write(wrapped) === false) {
      this._drainDone = cb
    } else {
      cb(null)
    }
  }

  _final(cb) {
    this._clearKeepAlive()
    this._ended--
    this._rawStream.end()
    cb(null)
  }

  _resolveOpened(val) {
    if (this._openedDone === null) return
    const opened = this._openedDone
    this._openedDone = null
    opened(val)
    if (!val) return
    this.connected = true
    this.emit('connect')
  }

  _clearTimeout() {
    if (this._timeoutTimer === null) return
    this._timeoutTimer.destroy()
    this._timeoutTimer = null
    this.timeout = 0
  }

  _clearKeepAlive() {
    if (this._keepAliveTimer === null) return
    this._keepAliveTimer.destroy()
    this._keepAliveTimer = null
    this.keepAlive = 0
  }

  _destroy(cb) {
    this._clearKeepAlive()
    this._clearTimeout()
    this._resolveOpened(false)
    cb(null)
  }

  _boxMessage(buffer) {
    const MB = sodium.crypto_secretbox_MACBYTES // 16
    const NB = sodium.crypto_secretbox_NONCEBYTES // 24

    const counter = this._sendState.subarray(64, 72)
    sodium.sodium_increment(counter)
    if (b4a.equals(counter, this._sendState.subarray(72))) {
      this.destroy(new Error('udp send nonce exchausted'))
      return
    }

    const secret = this._sendState.subarray(0, 32)
    const envelope = b4a.allocUnsafe(8 + MB + buffer.byteLength)
    const nonce = envelope.subarray(0, NB)
    const ciphertext = envelope.subarray(8)

    b4a.fill(nonce, 0) // pad suffix
    nonce.set(counter)

    sodium.crypto_secretbox_easy(ciphertext, buffer, nonce, secret)
    return envelope
  }

  send(buffer) {
    if (!this._sendState) return
    if (!this.rawStream?.send) return // udx-stream expected

    const message = this._boxMessage(buffer)
    return this.rawStream.send(message)
  }

  trySend(buffer) {
    if (!this._sendState) return
    if (!this.rawStream?.trySend) return // udx-stream expected

    const message = this._boxMessage(buffer)
    this.rawStream.trySend(message)
  }

  _onmessage(buffer) {
    if (!this._sendState) return // messages before handshake are dropped

    const MB = sodium.crypto_secretbox_MACBYTES // 16
    const NB = sodium.crypto_secretbox_NONCEBYTES // 24

    if (buffer.byteLength < NB) return // Invalid message

    const nonce = b4a.allocUnsafe(NB)
    b4a.fill(nonce, 0)
    nonce.set(buffer.subarray(0, 8))

    const secret = this._sendState.subarray(32, 64)
    const ciphertext = buffer.subarray(8)
    const plain = buffer.subarray(8, buffer.byteLength - MB)

    if (ciphertext.byteLength < MB) return // invalid message

    const success = sodium.crypto_secretbox_open_easy(plain, ciphertext, nonce, secret)

    if (success) this.emit('message', plain)
  }

  alloc(len) {
    const buf = b4a.allocUnsafe(len + 3 + ABYTES)
    this._outgoingWrapped = buf
    this._outgoingPlain = buf.subarray(4, buf.byteLength - ABYTES + 1)
    return this._outgoingPlain
  }

  toJSON() {
    return {
      isInitiator: this.isInitiator,
      publicKey: this.publicKey && b4a.toString(this.publicKey, 'hex'),
      remotePublicKey: this.remotePublicKey && b4a.toString(this.remotePublicKey, 'hex'),
      connected: this.connected,
      destroying: this.destroying,
      destroyed: this.destroyed,
      rawStream: this.rawStream && this.rawStream.toJSON ? this.rawStream.toJSON() : null
    }
  }
}

function writeUint24le(n, buf) {
  buf[0] = n & 255
  buf[1] = (n >>> 8) & 255
  buf[2] = (n >>> 16) & 255
}

function streamId(handshakeHash, isInitiator, out = b4a.allocUnsafe(32)) {
  sodium.crypto_generichash(out, isInitiator ? NS_INITIATOR : NS_RESPONDER, handshakeHash)
  return out
}

function toBuffer(data) {
  return typeof data === 'string' ? b4a.from(data) : data
}

function destroyTimeout() {
  this.destroy(new Error('Stream timed out'))
}

function sendKeepAlive() {
  const empty = this.alloc(0)
  this.write(empty)
}
const { Duplex, Writable } = require('streamx')

class ReversePassThrough extends Duplex {
  constructor(s) {
    super()
    this._stream = s
    this._ondrain = null
  }

  _write(data, cb) {
    if (this._stream.push(data) === false) {
      this._stream._ondrain = cb
    } else {
      cb(null)
    }
  }

  _final(cb) {
    this._stream.push(null)
    cb(null)
  }

  _read(cb) {
    const ondrain = this._ondrain
    this._ondrain = null
    if (ondrain) ondrain()
    cb(null)
  }
}

module.exports = class Bridge extends Duplex {
  constructor(noiseStream) {
    super()

    this.noiseStream = noiseStream

    this._ondrain = null
    this.reverse = new ReversePassThrough(this)
  }

  get publicKey() {
    return this.noiseStream.publicKey
  }

  get remotePublicKey() {
    return this.noiseStream.remotePublicKey
  }

  get handshakeHash() {
    return this.noiseStream.handshakeHash
  }

  flush() {
    return Writable.drained(this)
  }

  _read(cb) {
    const ondrain = this._ondrain
    this._ondrain = null
    if (ondrain) ondrain()
    cb(null)
  }

  _write(data, cb) {
    if (this.reverse.push(data) === false) {
      this.reverse._ondrain = cb
    } else {
      cb(null)
    }
  }

  _final(cb) {
    this.reverse.push(null)
    cb(null)
  }
}
const sodium = require('sodium-universal')
const curve = require('noise-curve-ed')
const Noise = require('noise-handshake')
const b4a = require('b4a')

const EMPTY = b4a.alloc(0)

module.exports = class Handshake {
  constructor(isInitiator, keyPair, remotePublicKey, pattern) {
    this.isInitiator = isInitiator
    this.keyPair = keyPair
    this.noise = new Noise(pattern, isInitiator, keyPair, { curve })
    this.noise.initialise(EMPTY, remotePublicKey)
    this.destroyed = false
  }

  static keyPair(seed) {
    const publicKey = b4a.alloc(32)
    const secretKey = b4a.alloc(64)
    if (seed) sodium.crypto_sign_seed_keypair(publicKey, secretKey, seed)
    else sodium.crypto_sign_keypair(publicKey, secretKey)
    return { publicKey, secretKey }
  }

  recv(data) {
    try {
      this.noise.recv(data)
      if (this.noise.complete) return this._return(null)
      return this.send()
    } catch {
      this.destroy()
      return null
    }
  }

  // note that the data returned here is framed so we don't have to do an extra copy
  // when sending it...
  send() {
    try {
      const data = this.noise.send()
      const wrap = b4a.allocUnsafe(data.byteLength + 3)

      writeUint24le(data.byteLength, wrap)
      wrap.set(data, 3)

      return this._return(wrap)
    } catch {
      this.destroy()
      return null
    }
  }

  destroy() {
    if (this.destroyed) return
    this.destroyed = true
  }

  _return(data) {
    const tx = this.noise.complete ? b4a.toBuffer(this.noise.tx) : null
    const rx = this.noise.complete ? b4a.toBuffer(this.noise.rx) : null
    const hash = this.noise.complete ? b4a.toBuffer(this.noise.hash) : null
    const remotePublicKey = this.noise.complete ? b4a.toBuffer(this.noise.rs) : null

    return {
      data,
      remotePublicKey,
      hash,
      tx,
      rx
    }
  }
}

function writeUint24le(n, buf) {
  buf[0] = n & 255
  buf[1] = (n >>> 8) & 255
  buf[2] = (n >>> 16) & 255
}
{
  "name": "@hyperswarm/secret-stream",
  "version": "6.9.1",
  "description": "Secret stream backed by Noise and libsodium's secretstream",
  "main": "index.js",
  "files": [
    "index.js",
    "lib/**.js"
  ],
  "dependencies": {
    "b4a": "^1.1.0",
    "hypercore-crypto": "^3.3.1",
    "noise-curve-ed": "^2.0.1",
    "noise-handshake": "^4.0.0",
    "sodium-secretstream": "^1.1.0",
    "sodium-universal": "^5.0.0",
    "streamx": "^2.14.0",
    "timeout-refresh": "^2.0.0",
    "unslab": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "udx-native": "^1.13.2"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check .",
    "test": "brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/hyperswarm-secret-stream.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/hyperswarm-secret-stream/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperswarm-secret-stream"
}
const c = require('compact-encoding')
const IndexEncoder = require('index-encoder')

const Checkout = {
  preencode(state, m) {
    c.fixed32.preencode(state, m.key)
    c.uint.preencode(state, m.length)
  },
  encode(state, m) {
    c.fixed32.encode(state, m.key)
    c.uint.encode(state, m.length)
  },
  decode(state) {
    return {
      key: c.fixed32.decode(state),
      length: c.uint.decode(state)
    }
  }
}

const Clock = c.array(Checkout)

const IndexCheckpoint = {
  preencode(state, m) {
    c.fixed64.preencode(state, m.signature)
    c.uint.preencode(state, m.length)
  },
  encode(state, m) {
    c.fixed64.encode(state, m.signature)
    c.uint.encode(state, m.length)
  },
  decode(state) {
    return {
      signature: c.fixed64.decode(state),
      length: c.uint.decode(state)
    }
  }
}

const KeyV0 = {
  preencode(state, m) {
    c.fixed32.preencode(state, m.key)
  },
  encode(state, m) {
    c.fixed32.encode(state, m.key)
  },
  decode(state) {
    return {
      key: c.fixed32.decode(state),
      length: -1
    }
  }
}

const KeysV0 = c.array(KeyV0)

const WakeupV0 = {
  preencode(state, m) {
    c.uint.preencode(state, 0) // version
    c.uint.preencode(state, m.type)

    if (m.type === 1) {
      KeysV0.preencode(state, m.writers)
    }
  },
  encode(state, m) {
    c.uint.encode(state, 0) // version
    c.uint.encode(state, m.type)

    if (m.type === 1) {
      KeysV0.encode(state, m.writers)
    }
  },
  decode(state) {
    const v = c.uint.decode(state)
    if (v !== 0) throw new Error('Unsupported version: ' + v)

    const type = c.uint.decode(state)
    const m = { version: 0, type, writers: null }

    if (m.type === 1) {
      m.writers = KeysV0.decode(state)
    }

    return m
  }
}

const Wakeup = {
  preencode(state, m) {
    if (m.version === 0) return WakeupV0.preencode(state, m)

    c.uint.preencode(state, 1) // version
    c.uint.preencode(state, m.type)

    if (m.type === 1) {
      Clock.preencode(state, m.writers)
    }
  },
  encode(state, m) {
    if (m.version === 0) return WakeupV0.encode(state, m)

    c.uint.encode(state, 1) // version
    c.uint.encode(state, m.type)

    if (m.type === 1) {
      Clock.encode(state, m.writers)
    }
  },
  decode(state) {
    const start = state.start
    const v = c.uint.decode(state)

    if (v > 1) throw new Error('Unsupported version: ' + v)

    if (v === 0) {
      state.start = start
      return WakeupV0.decode(state)
    }

    const type = c.uint.decode(state)
    const m = { version: 1, type, writers: null }

    if (m.type === 1) {
      m.writers = Clock.decode(state)
    }

    return m
  }
}

const BootRecordV0 = {
  preencode() {
    throw new Error('version 0 records cannot be encoded')
  },
  encode() {
    throw new Error('version 0 records cannot be encoded')
  },
  decode(state) {
    const indexed = Checkout.decode(state)
    const heads = Clock.decode(state)

    // one cause initial recover is not ff recovery
    return {
      version: 0,
      key: indexed.key,
      systemLength: indexed.length,
      indexersUpdated: false,
      fastForwarding: false,
      recoveries: 1,
      migrating: false,
      heads
    }
  }
}

const Checkpointer = {
  preencode(state, idx) {
    c.uint.preencode(state, idx.checkpointer)
    if (idx.checkpoint !== null) IndexCheckpoint.preencode(state, idx.checkpoint)
  },
  encode(state, idx) {
    c.uint.encode(state, idx.checkpointer)
    if (idx.checkpoint !== null) IndexCheckpoint.encode(state, idx.checkpoint)
  },
  decode(state) {
    const checkpointer = c.uint.decode(state)
    const checkpoint = checkpointer ? null : IndexCheckpoint.decode(state)

    return {
      checkpointer,
      checkpoint
    }
  }
}

const CheckpointerArray = c.array(Checkpointer)

const Indexer = {
  preencode(state, m) {
    c.uint.preencode(state, m.signature)
    c.fixed32.preencode(state, m.namespace)
    c.fixed32.preencode(state, m.publicKey)
  },
  encode(state, m) {
    c.uint.encode(state, m.signature)
    c.fixed32.encode(state, m.namespace)
    c.fixed32.encode(state, m.publicKey)
  },
  decode(state) {
    return {
      signature: c.uint.decode(state),
      namespace: c.fixed32.decode(state),
      publicKey: c.fixed32.decode(state)
    }
  }
}

const Indexers = c.array(Indexer)

const DigestV0 = {
  preencode(state, m) {
    c.uint.preencode(state, m.pointer)
    if (m.pointer === 0) {
      Indexers.preencode(state, m.indexers)
    }
  },
  encode(state, m) {
    c.uint.encode(state, m.pointer)
    if (m.pointer === 0) {
      Indexers.encode(state, m.indexers)
    }
  },
  decode(state) {
    const pointer = c.uint.decode(state)
    return {
      pointer,
      indexers: pointer === 0 ? Indexers.decode(state) : null
    }
  }
}

const Digest = {
  preencode(state, m) {
    c.uint.preencode(state, m.pointer)
    if (m.pointer === 0) {
      c.fixed32.preencode(state, m.key)
    }
  },
  encode(state, m) {
    c.uint.encode(state, m.pointer)
    if (m.pointer === 0) {
      c.fixed32.encode(state, m.key)
    }
  },
  decode(state) {
    const pointer = c.uint.decode(state)
    return {
      pointer,
      key: pointer === 0 ? c.fixed32.decode(state) : null
    }
  }
}

const Node = {
  preencode(state, m) {
    Clock.preencode(state, m.heads)
    c.uint.preencode(state, m.batch)
    c.buffer.preencode(state, m.value)
  },
  encode(state, m) {
    Clock.encode(state, m.heads)
    c.uint.encode(state, m.batch)
    c.buffer.encode(state, m.value)
  },
  decode(state, m) {
    return {
      heads: Clock.decode(state),
      batch: c.uint.decode(state),
      value: c.buffer.decode(state)
    }
  }
}

const Additional = {
  preencode(state, m) {
    c.uint.preencode(state, m.pointer)
    if (m.pointer === 0) {
      AdditionalData.preencode(state, m.data)
    }
  },
  encode(state, m) {
    c.uint.encode(state, m.pointer)
    if (m.pointer === 0) {
      AdditionalData.encode(state, m.data)
    }
  },
  decode(state) {
    const pointer = c.uint.decode(state)
    return {
      pointer,
      data: pointer === 0 ? AdditionalData.decode(state) : null
    }
  }
}

const AdditionalData = {
  preencode(state, m) {
    c.uint.preencode(state, 0)
  },
  encode(state, m) {
    c.uint.encode(state, 0) // empty for now, for the future
  },
  decode(state) {
    const flags = c.uint.decode(state)
    return {
      encryptionId: flags & 1 ? c.fixed32.decode(state) : null, // to help validate the encryption key used
      abi: flags & 2 ? c.uint.decode(state) : 0
    }
  }
}

const OplogMessageV1 = {
  preencode(state, m) {
    throw new Error('Encoding not supported')
  },
  encode(state, m) {
    throw new Error('Encoding not supported')
  },
  decode(state) {
    const maxSupportedVersion = c.uint.decode(state)

    const flags = c.uint.decode(state)

    const isCheckpointer = (flags & 1) !== 0

    const chk = isCheckpointer ? CheckpointerArray.decode(state) : null
    const digest = isCheckpointer ? Digest.decode(state) : null

    const node = Node.decode(state)

    return {
      version: 1,
      maxSupportedVersion,
      digest,
      checkpoint: chk ? { system: chk[0], encryption: null, user: chk.slice(1) } : null,
      optimistic: (flags & 2) !== 0,
      node
    }
  }
}

const OplogMessageV0 = {
  preencode(state, m) {
    throw new Error('Encoding not supported')
  },
  encode(state, m) {
    throw new Error('Encoding not supported')
  },
  decode(state) {
    const flags = c.uint.decode(state)

    const isCheckpointer = (flags & 1) !== 0

    if (isCheckpointer) DigestV0.decode(state)
    const chk = isCheckpointer ? CheckpointerArray.decode(state) : null
    const node = Node.decode(state)
    Additional.decode(state)
    const maxSupportedVersion = state.start < state.end ? c.uint.decode(state) : 0

    return {
      version: 0,
      maxSupportedVersion,
      digest: null,
      checkpoint: chk ? { system: chk[0], encryption: null, user: chk.slice(1) } : null,
      optimistic: null,
      node
    }
  }
}

// prefix 0 is reserved for future manifest
const LINEARIZER_PREFIX = 1

const LinearizerKey = {
  preencode(state, seq) {
    IndexEncoder.UINT.preencode(state, LINEARIZER_PREFIX)
    IndexEncoder.UINT.preencode(state, seq)
  },
  encode(state, seq) {
    IndexEncoder.UINT.encode(state, LINEARIZER_PREFIX)
    IndexEncoder.UINT.encode(state, seq)
  },
  decode(state) {
    IndexEncoder.UINT.decode(state)
    return IndexEncoder.UINT.decode(state)
  }
}

function infoLegacyMap(info) {
  return {
    version: info.version,
    members: info.members,
    pendingIndexers: info.pendingIndexers,
    indexers: info.indexers,
    heads: info.heads,
    views: info.views,
    encryptionLength: 0,
    entropy: null
  }
}

module.exports = {
  Wakeup,
  BootRecordV0,
  OplogMessageV0,
  OplogMessageV1,
  LinearizerKey,
  infoLegacyMap
}
// This file is autogenerated by the hyperschema compiler
// Schema Version: 1
/* eslint-disable camelcase */
/* eslint-disable quotes */

const { c } = require('hyperschema/runtime')
const external0 = require('../../legacy.js')

const VERSION = 1

// eslint-disable-next-line no-unused-vars
let version = VERSION

// @autobase/checkout
const encoding0 = {
  preencode(state, m) {
    c.fixed32.preencode(state, m.key)
    c.uint.preencode(state, m.length)
  },
  encode(state, m) {
    c.fixed32.encode(state, m.key)
    c.uint.encode(state, m.length)
  },
  decode(state) {
    const r0 = c.fixed32.decode(state)
    const r1 = c.uint.decode(state)

    return {
      key: r0,
      length: r1
    }
  }
}

// @autobase/clock
const encoding1 = c.array(encoding0)

// @autobase/index-checkpoint
const encoding2 = {
  preencode(state, m) {
    c.fixed64.preencode(state, m.signature)
    c.uint.preencode(state, m.length)
  },
  encode(state, m) {
    c.fixed64.encode(state, m.signature)
    c.uint.encode(state, m.length)
  },
  decode(state) {
    const r0 = c.fixed64.decode(state)
    const r1 = c.uint.decode(state)

    return {
      signature: r0,
      length: r1
    }
  }
}

const encoding3 = external0.Wakeup

const encoding4 = external0.BootRecordV0

// @autobase/boot-record-raw
const encoding5 = {
  preencode(state, m) {
    c.fixed32.preencode(state, m.key)
    c.uint.preencode(state, m.systemLength)
    state.end++ // max flag is 4 so always one byte

    if (m.recoveries) c.uint.preencode(state, m.recoveries)
  },
  encode(state, m) {
    const flags = (m.indexersUpdated ? 1 : 0) | (m.fastForwarding ? 2 : 0) | (m.recoveries ? 4 : 0)

    c.fixed32.encode(state, m.key)
    c.uint.encode(state, m.systemLength)
    c.uint.encode(state, flags)

    if (m.recoveries) c.uint.encode(state, m.recoveries)
  },
  decode(state, version) {
    if (version === undefined) version = c.uint.decode(state)
    const r0 = c.fixed32.decode(state)
    const r1 = c.uint.decode(state)
    const flags = c.uint.decode(state)

    return {
      version,
      key: r0,
      systemLength: r1,
      indexersUpdated: (flags & 1) !== 0,
      fastForwarding: (flags & 2) !== 0,
      recoveries: (flags & 4) !== 0 ? c.uint.decode(state) : 0
    }
  }
}

// @autobase/boot-record
const encoding6 = {
  preencode(state, m) {
    c.uint.preencode(state, m.version)
    switch (m.version) {
      case 0:
        encoding4.preencode(state, m)
        break
      case 1:
      case 2:
      case 3:
        encoding5.preencode(state, m)
        break
      default:
        throw new Error('Unsupported version')
    }
  },
  encode(state, m) {
    c.uint.encode(state, m.version)
    switch (m.version) {
      case 0:
        encoding4.encode(state, m)
        break
      case 1:
      case 2:
      case 3:
        encoding5.encode(state, m)
        break
      default:
        throw new Error('Unsupported version')
    }
  },
  decode(state) {
    const version = c.uint.decode(state)
    switch (version) {
      case 0: {
        const decoded = encoding4.decode(state, version)
        return decoded
      }
      case 1:
      case 2:
      case 3: {
        const decoded = encoding5.decode(state, version)
        return decoded
      }
      default:
        throw new Error('Unsupported version')
    }
  }
}

// @autobase/checkpointer
const encoding7 = {
  preencode(state, m) {
    state.end++ // max flag is 2 so always one byte

    if (m.checkpointer) c.uint.preencode(state, m.checkpointer)
    if (m.checkpoint) encoding2.preencode(state, m.checkpoint)
  },
  encode(state, m) {
    const flags = (m.checkpointer ? 1 : 0) | (m.checkpoint ? 2 : 0)

    c.uint.encode(state, flags)

    if (m.checkpointer) c.uint.encode(state, m.checkpointer)
    if (m.checkpoint) encoding2.encode(state, m.checkpoint)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      checkpointer: (flags & 1) !== 0 ? c.uint.decode(state) : 0,
      checkpoint: (flags & 2) !== 0 ? encoding2.decode(state) : null
    }
  }
}

// @autobase/checkpoint.user
const encoding8_2 = c.array(encoding7)

// @autobase/checkpoint
const encoding8 = {
  preencode(state, m) {
    state.end++ // max flag is 4 so always one byte

    if (m.system) encoding7.preencode(state, m.system)
    if (m.encryption) encoding7.preencode(state, m.encryption)
    if (m.user) encoding8_2.preencode(state, m.user)
  },
  encode(state, m) {
    const flags = (m.system ? 1 : 0) | (m.encryption ? 2 : 0) | (m.user ? 4 : 0)

    c.uint.encode(state, flags)

    if (m.system) encoding7.encode(state, m.system)
    if (m.encryption) encoding7.encode(state, m.encryption)
    if (m.user) encoding8_2.encode(state, m.user)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      system: (flags & 1) !== 0 ? encoding7.decode(state) : null,
      encryption: (flags & 2) !== 0 ? encoding7.decode(state) : null,
      user: (flags & 4) !== 0 ? encoding8_2.decode(state) : null
    }
  }
}

// @autobase/digest
const encoding9 = {
  preencode(state, m) {
    state.end++ // max flag is 2 so always one byte

    if (m.pointer) c.uint.preencode(state, m.pointer)
    if (m.key) c.fixed32.preencode(state, m.key)
  },
  encode(state, m) {
    const flags = (m.pointer ? 1 : 0) | (m.key ? 2 : 0)

    c.uint.encode(state, flags)

    if (m.pointer) c.uint.encode(state, m.pointer)
    if (m.key) c.fixed32.encode(state, m.key)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      pointer: (flags & 1) !== 0 ? c.uint.decode(state) : 0,
      key: (flags & 2) !== 0 ? c.fixed32.decode(state) : null
    }
  }
}

// @autobase/node
const encoding10 = {
  preencode(state, m) {
    encoding1.preencode(state, m.heads)
    c.uint.preencode(state, m.batch)
    c.buffer.preencode(state, m.value)
  },
  encode(state, m) {
    encoding1.encode(state, m.heads)
    c.uint.encode(state, m.batch)
    c.buffer.encode(state, m.value)
  },
  decode(state) {
    const r0 = encoding1.decode(state)
    const r1 = c.uint.decode(state)
    const r2 = c.buffer.decode(state)

    return {
      heads: r0,
      batch: r1,
      value: r2
    }
  }
}

// @autobase/trace.system
const encoding11_0 = c.array(c.uint)
// @autobase/trace.encryption
const encoding11_1 = encoding11_0

// @autobase/trace
const encoding11 = {
  preencode(state, m) {
    encoding11_0.preencode(state, m.system)
    encoding11_1.preencode(state, m.encryption)
    encoding11_2.preencode(state, m.user)
  },
  encode(state, m) {
    encoding11_0.encode(state, m.system)
    encoding11_1.encode(state, m.encryption)
    encoding11_2.encode(state, m.user)
  },
  decode(state) {
    const r0 = encoding11_0.decode(state)
    const r1 = encoding11_1.decode(state)
    const r2 = encoding11_2.decode(state)

    return {
      system: r0,
      encryption: r1,
      user: r2
    }
  }
}

const encoding12 = external0.OplogMessageV0

const encoding13 = external0.OplogMessageV1

// @autobase/oplog-message-v2.checkpoint
const encoding14_1 = c.frame(encoding8)
// @autobase/oplog-message-v2.digest
const encoding14_2 = c.frame(encoding9)
// @autobase/oplog-message-v2.trace
const encoding14_4 = c.frame(encoding11)

// @autobase/oplog-message-v2
const encoding14 = {
  preencode(state, m) {
    encoding10.preencode(state, m.node)
    state.end++ // max flag is 8 so always one byte

    if (m.checkpoint) encoding14_1.preencode(state, m.checkpoint)
    if (m.digest) encoding14_2.preencode(state, m.digest)
    if (m.trace) encoding14_4.preencode(state, m.trace)
  },
  encode(state, m) {
    const flags =
      (m.checkpoint ? 1 : 0) | (m.digest ? 2 : 0) | (m.optimistic ? 4 : 0) | (m.trace ? 8 : 0)

    encoding10.encode(state, m.node)
    c.uint.encode(state, flags)

    if (m.checkpoint) encoding14_1.encode(state, m.checkpoint)
    if (m.digest) encoding14_2.encode(state, m.digest)
    if (m.trace) encoding14_4.encode(state, m.trace)
  },
  decode(state, version) {
    if (version === undefined) version = c.uint.decode(state)
    const r0 = encoding10.decode(state)
    const flags = c.uint.decode(state)

    return {
      version,
      node: r0,
      checkpoint: (flags & 1) !== 0 ? encoding14_1.decode(state) : null,
      digest: (flags & 2) !== 0 ? encoding14_2.decode(state) : null,
      optimistic: (flags & 4) !== 0,
      trace: (flags & 8) !== 0 ? encoding14_4.decode(state) : null
    }
  }
}

// @autobase/oplog-message
const encoding15 = {
  preencode(state, m) {
    c.uint.preencode(state, m.version)
    switch (m.version) {
      case 0:
        encoding12.preencode(state, m)
        break
      case 1:
        encoding13.preencode(state, m)
        break
      case 2:
        encoding14.preencode(state, m)
        break
      default:
        throw new Error('Unsupported version')
    }
  },
  encode(state, m) {
    c.uint.encode(state, m.version)
    switch (m.version) {
      case 0:
        encoding12.encode(state, m)
        break
      case 1:
        encoding13.encode(state, m)
        break
      case 2:
        encoding14.encode(state, m)
        break
      default:
        throw new Error('Unsupported version')
    }
  },
  decode(state) {
    const version = c.uint.decode(state)
    switch (version) {
      case 0: {
        const decoded = encoding12.decode(state, version)
        return decoded
      }
      case 1: {
        const decoded = encoding13.decode(state, version)
        return decoded
      }
      case 2: {
        const decoded = encoding14.decode(state, version)
        return decoded
      }
      default:
        throw new Error('Unsupported version')
    }
  }
}

// @autobase/info-v1.pendingIndexers
const encoding16_1 = c.array(c.fixed32)

// @autobase/info-v1
const encoding16 = {
  preencode(state, m) {
    c.uint.preencode(state, m.members)
    encoding16_1.preencode(state, m.pendingIndexers)
    encoding1.preencode(state, m.indexers)
    encoding1.preencode(state, m.heads)
    encoding1.preencode(state, m.views)
  },
  encode(state, m) {
    c.uint.encode(state, m.members)
    encoding16_1.encode(state, m.pendingIndexers)
    encoding1.encode(state, m.indexers)
    encoding1.encode(state, m.heads)
    encoding1.encode(state, m.views)
  },
  decode(state, version) {
    if (version === undefined) version = c.uint.decode(state)
    const r0 = c.uint.decode(state)
    const r1 = encoding16_1.decode(state)
    const r2 = encoding1.decode(state)
    const r3 = encoding1.decode(state)
    const r4 = encoding1.decode(state)

    return {
      version,
      members: r0,
      pendingIndexers: r1,
      indexers: r2,
      heads: r3,
      views: r4
    }
  }
}

// @autobase/info-v2.pendingIndexers
const encoding17_1 = encoding16_1

// @autobase/info-v2
const encoding17 = {
  preencode(state, m) {
    c.uint.preencode(state, m.members)
    encoding17_1.preencode(state, m.pendingIndexers)
    encoding1.preencode(state, m.indexers)
    encoding1.preencode(state, m.heads)
    encoding1.preencode(state, m.views)
    c.uint.preencode(state, m.encryptionLength)
    state.end++ // max flag is 1 so always one byte

    if (m.entropy) c.fixed32.preencode(state, m.entropy)
  },
  encode(state, m) {
    const flags = m.entropy ? 1 : 0

    c.uint.encode(state, m.members)
    encoding17_1.encode(state, m.pendingIndexers)
    encoding1.encode(state, m.indexers)
    encoding1.encode(state, m.heads)
    encoding1.encode(state, m.views)
    c.uint.encode(state, m.encryptionLength)
    c.uint.encode(state, flags)

    if (m.entropy) c.fixed32.encode(state, m.entropy)
  },
  decode(state, version) {
    if (version === undefined) version = c.uint.decode(state)
    const r0 = c.uint.decode(state)
    const r1 = encoding17_1.decode(state)
    const r2 = encoding1.decode(state)
    const r3 = encoding1.decode(state)
    const r4 = encoding1.decode(state)
    const r5 = c.uint.decode(state)
    const flags = c.uint.decode(state)

    return {
      version,
      members: r0,
      pendingIndexers: r1,
      indexers: r2,
      heads: r3,
      views: r4,
      encryptionLength: r5,
      entropy: (flags & 1) !== 0 ? c.fixed32.decode(state) : null
    }
  }
}

// @autobase/info
const encoding18 = {
  preencode(state, m) {
    c.uint.preencode(state, m.version)
    switch (m.version) {
      case 0:
      case 1:
        encoding16.preencode(state, m)
        break
      case 2:
        encoding17.preencode(state, m)
        break
      default:
        throw new Error('Unsupported version')
    }
  },
  encode(state, m) {
    c.uint.encode(state, m.version)
    switch (m.version) {
      case 0:
      case 1:
        encoding16.encode(state, m)
        break
      case 2:
        encoding17.encode(state, m)
        break
      default:
        throw new Error('Unsupported version')
    }
  },
  decode(state) {
    const version = c.uint.decode(state)
    switch (version) {
      case 0:
      case 1: {
        const decoded = encoding16.decode(state, version)
        const map = external0.infoLegacyMap
        return map(decoded)
      }
      case 2: {
        const decoded = encoding17.decode(state, version)
        return decoded
      }
      default:
        throw new Error('Unsupported version')
    }
  }
}

// @autobase/member
const encoding19 = {
  preencode(state, m) {
    state.end++ // max flag is 2 so always one byte
    c.uint.preencode(state, m.length)
  },
  encode(state, m) {
    const flags = (m.isIndexer ? 1 : 0) | (m.isRemoved ? 2 : 0)

    c.uint.encode(state, flags)
    c.uint.encode(state, m.length)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      isIndexer: (flags & 1) !== 0,
      isRemoved: (flags & 2) !== 0,
      length: c.uint.decode(state)
    }
  }
}

const encoding20 = external0.LinearizerKey

// @autobase/linearizer-update
const encoding21 = {
  preencode(state, m) {
    c.fixed32.preencode(state, m.key)
    c.uint.preencode(state, m.length)
    c.uint.preencode(state, m.batch)
    c.uint.preencode(state, m.systemLength)
    state.end++ // max flag is 1 so always one byte
  },
  encode(state, m) {
    const flags = m.indexers ? 1 : 0

    c.fixed32.encode(state, m.key)
    c.uint.encode(state, m.length)
    c.uint.encode(state, m.batch)
    c.uint.encode(state, m.systemLength)
    c.uint.encode(state, flags)
  },
  decode(state) {
    const r0 = c.fixed32.decode(state)
    const r1 = c.uint.decode(state)
    const r2 = c.uint.decode(state)
    const r3 = c.uint.decode(state)
    const flags = c.uint.decode(state)

    return {
      key: r0,
      length: r1,
      batch: r2,
      systemLength: r3,
      indexers: (flags & 1) !== 0
    }
  }
}

// @autobase/encryption-descriptor
const encoding22 = {
  preencode(state, m) {
    c.uint.preencode(state, m.type)
    c.buffer.preencode(state, m.payload)
  },
  encode(state, m) {
    c.uint.encode(state, m.type)
    c.buffer.encode(state, m.payload)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const r1 = c.buffer.decode(state)

    return {
      type: r0,
      payload: r1
    }
  }
}

// @autobase/manifest-data
const encoding23 = {
  preencode(state, m) {
    c.uint.preencode(state, m.version)
    state.end++ // max flag is 2 so always one byte

    if (m.legacyBlocks) c.uint.preencode(state, m.legacyBlocks)
    if (m.namespace) c.fixed32.preencode(state, m.namespace)
  },
  encode(state, m) {
    const flags = (m.legacyBlocks ? 1 : 0) | (m.namespace ? 2 : 0)

    c.uint.encode(state, m.version)
    c.uint.encode(state, flags)

    if (m.legacyBlocks) c.uint.encode(state, m.legacyBlocks)
    if (m.namespace) c.fixed32.encode(state, m.namespace)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const flags = c.uint.decode(state)

    return {
      version: r0,
      legacyBlocks: (flags & 1) !== 0 ? c.uint.decode(state) : 0,
      namespace: (flags & 2) !== 0 ? c.fixed32.decode(state) : null
    }
  }
}

// @autobase/user-view-trace.blocks
const encoding24_1 = encoding11_0

// @autobase/user-view-trace
const encoding24 = {
  preencode(state, m) {
    c.uint.preencode(state, m.view)
    encoding24_1.preencode(state, m.blocks)
  },
  encode(state, m) {
    c.uint.encode(state, m.view)
    encoding24_1.encode(state, m.blocks)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const r1 = encoding24_1.decode(state)

    return {
      view: r0,
      blocks: r1
    }
  }
}

// @autobase/trace.user, deferred due to recusive use
const encoding11_2 = c.array(encoding24)

function setVersion(v) {
  version = v
}

function encode(name, value, v = VERSION) {
  version = v
  return c.encode(getEncoding(name), value)
}

function decode(name, buffer, v = VERSION) {
  version = v
  return c.decode(getEncoding(name), buffer)
}

function getEnum(name) {
  switch (name) {
    default:
      throw new Error('Enum not found ' + name)
  }
}

function getEncoding(name) {
  switch (name) {
    case '@autobase/checkout':
      return encoding0
    case '@autobase/clock':
      return encoding1
    case '@autobase/index-checkpoint':
      return encoding2
    case '@autobase/wakeup':
      return encoding3
    case '@autobase/boot-record-v0':
      return encoding4
    case '@autobase/boot-record-raw':
      return encoding5
    case '@autobase/boot-record':
      return encoding6
    case '@autobase/checkpointer':
      return encoding7
    case '@autobase/checkpoint':
      return encoding8
    case '@autobase/digest':
      return encoding9
    case '@autobase/node':
      return encoding10
    case '@autobase/trace':
      return encoding11
    case '@autobase/oplog-message-v0':
      return encoding12
    case '@autobase/oplog-message-v1':
      return encoding13
    case '@autobase/oplog-message-v2':
      return encoding14
    case '@autobase/oplog-message':
      return encoding15
    case '@autobase/info-v1':
      return encoding16
    case '@autobase/info-v2':
      return encoding17
    case '@autobase/info':
      return encoding18
    case '@autobase/member':
      return encoding19
    case '@autobase/linearizer-key':
      return encoding20
    case '@autobase/linearizer-update':
      return encoding21
    case '@autobase/encryption-descriptor':
      return encoding22
    case '@autobase/manifest-data':
      return encoding23
    case '@autobase/user-view-trace':
      return encoding24
    default:
      throw new Error('Encoder not found ' + name)
  }
}

function getStruct(name, v = VERSION) {
  const enc = getEncoding(name)
  return {
    preencode(state, m) {
      version = v
      enc.preencode(state, m)
    },
    encode(state, m) {
      version = v
      enc.encode(state, m)
    },
    decode(state) {
      version = v
      return enc.decode(state)
    }
  }
}

const resolveStruct = getStruct // compat

module.exports = {
  resolveStruct,
  getStruct,
  getEnum,
  getEncoding,
  encode,
  decode,
  setVersion,
  version
}
const b4a = require('b4a')
const ReadyResource = require('ready-resource')
const debounceify = require('debounceify')
const c = require('compact-encoding')
const safetyCatch = require('safety-catch')
const hypercoreId = require('hypercore-id-encoding')
const assert = require('nanoassert')
const SignalPromise = require('signal-promise')
const CoreCoupler = require('core-coupler')
const ProtomuxWakeup = require('protomux-wakeup')
const rrp = require('resolve-reject-promise')
const Hypercore = require('hypercore')
const ScopeLock = require('scope-lock')
const encryptionEncoding = require('encryption-encoding')

const LocalState = require('./lib/local-state.js')
const Linearizer = require('./lib/linearizer.js')
const SystemView = require('./lib/system.js')
const { EncryptionView } = require('./lib/encryption.js')
const UpdateChanges = require('./lib/updates.js')
const messages = require('./lib/messages.js')
const Timer = require('./lib/timer.js')
const Writer = require('./lib/writer.js')
const { encodeValue, decodeValue } = require('./lib/values.js')
const ActiveWriters = require('./lib/active-writers.js')
const AutoWakeup = require('./lib/wakeup.js')

const FastForward = require('./lib/fast-forward.js')
const AutoStore = require('./lib/store.js')
const ApplyState = require('./lib/apply-state.js')
const AppendBatch = require('./lib/append-batch.js')
const { PublicApplyCalls } = require('./lib/apply-calls.js')
const boot = require('./lib/boot.js')
const { MAX_AUTOBASE_VERSION, BOOT_RECORD_VERSION } = require('./lib/caps.js')

const inspect = Symbol.for('nodejs.util.inspect.custom')
const INTERRUPT = new Error('Apply interrupted')
const BINARY_ENCODING = c.from('binary')

const RECOVERIES = 3

// default is to automatically ack
const DEFAULT_ACK_INTERVAL = 10_000
const DEFAULT_ACK_THRESHOLD = 4

const REMOTE_ADD_BATCH = 64
const REMOTE_ADD_BATCH_SANITY = 4096
const MIN_FF_WAIT = 300_000 // wait at least 5min before attempting to ff again after failure

class WakeupHandler {
  constructor(base, discoveryKey) {
    this.active = true
    this.discoveryKey = discoveryKey
    this.base = base
  }

  onpeeractive(peer, session) {
    this.base._bumpWakeupPeer(peer)
  }

  onlookup(req, peer, session) {
    const wakeup = this.base._getWakeup()
    if (wakeup.length === 0) return
    session.announce(peer, wakeup)
  }

  onannounce(wakeup, peer, session) {
    if (this.base.isFastForwarding()) {
      this.base._needsWakeupRequest = true
      return
    }
    this.base.hintWakeup(wakeup)
  }
}

module.exports = class Autobase extends ReadyResource {
  constructor(store, bootstrap, handlers = {}) {
    if (Array.isArray(bootstrap)) bootstrap = bootstrap[0] // TODO: just a quick compat, lets remove soon

    if (bootstrap && typeof bootstrap !== 'string' && !b4a.isBuffer(bootstrap)) {
      handlers = bootstrap
      bootstrap = null
    }

    super()

    const key = bootstrap ? toKey(bootstrap) : null

    this.id = null
    this.key = key
    this.discoveryKey = null
    this.backoff = handlers.backoff || null

    this.keyPair = null
    this.valueEncoding = c.from(handlers.valueEncoding || 'binary')
    this.store = store
    this.globalCache = store.globalCache || null
    this.migrated = false

    this.encrypted = handlers.encrypted || !!handlers.encryptionKey
    this.encrypt = !!handlers.encrypt
    this.encryptionKey = null
    this.encryption = null
    this.blindEncryption = handlers.blindEncryption || null

    this.activeBatch = null // maintained by the append-batch

    this.local = null
    this.localWriter = null
    this.isIndexer = false

    this.activeWriters = new ActiveWriters()
    this.linearizer = null
    this.updating = false

    this.nukeTip = !!handlers.nukeTip

    this.wakeupOwner = !handlers.wakeup
    this.wakeupCapability = null
    this.wakeupProtocol = handlers.wakeup || new ProtomuxWakeup()
    this.wakeupSession = null

    this._primaryBootstrap = null

    this.fastForwardEnabled = handlers.fastForward !== false
    this.fastForwarding = null
    this.fastForwardTo = null
    this.fastForwardFailedAt = 0
    this.fastForwardMinimum = FastForward.MINIMUM

    this.bigBatches = !!handlers.bigBatches

    this._bootstrapWriters = [] // might contain dups, but thats ok
    this._bootstrapWritersChanged = false

    this._flushSignal = new SignalPromise()
    this._flushing = 0

    this._checkWriters = []
    this._optimistic = -1
    this._appended = 0
    this._appending = null
    this._wakeup = new AutoWakeup(this)
    this._wakeupHints = new Map()
    this._wakeupPeerBound = this._wakeupPeer.bind(this)
    this._coupler = null

    this._updateLocalCore = null
    this._lock = new ScopeLock()

    this._needsWakeupRequest = false
    this._needsWakeup = true
    this._needsWakeupHeads = true

    this._updates = []
    this._handlers = handlers || {}
    this._warn = emitWarning.bind(this)
    this._lastError = null

    this._draining = false
    this._writable = null
    this._advancing = null
    this._interrupting = false
    this._caughtup = false

    this.paused = false

    this._bump = debounceify(() => {
      this._advancing = this._advance()
      return this._advancing
    })

    this._onremotewriterchangeBound = this._onremotewriterchange.bind(this)
    this._onlocalwriterchangeBound = this._onlocalwriterchange.bind(this)

    this._preopen = null

    this._hasOpen = !!this._handlers.open
    this._hasApply = !!this._handlers.apply
    this._hasOptimisticApply = !!this._handlers.optimistic
    this._hasUpdate = !!this._handlers.update
    this._hasClose = !!this._handlers.close

    this._viewStore = new AutoStore(this)
    this._applyState = null

    this.view = null
    this.core = null
    this.version = -1
    this.interrupted = null
    this.recoveries = RECOVERIES

    const { ackInterval = DEFAULT_ACK_INTERVAL, ackThreshold = DEFAULT_ACK_THRESHOLD } = handlers

    this._ackInterval = ackInterval
    this._ackThreshold = ackThreshold
    this._ackTickThreshold = ackThreshold
    this._ackTick = 0

    this._ackTimer = null
    this._acking = false

    this._waiting = new SignalPromise()

    this.view = this._hasOpen
      ? this._handlers.open(this._viewStore, new PublicApplyCalls(this))
      : null
    this.core = this._viewStore.get({ name: '_system' })

    if (this.fastForwardEnabled && isObject(handlers.fastForward)) {
      this._runFastForward(
        new FastForward(this, handlers.fastForward.key, { verified: false })
      ).catch(noop)
    }

    this.ready().catch(safetyCatch)
  }

  [inspect](depth, opts) {
    let indent = ''
    if (typeof opts.indentationLvl === 'number') {
      while (indent.length < opts.indentationLvl) indent += ' '
    }

    return indent + 'Autobase { ... }'
  }

  // just compat, use .key
  get bootstrap() {
    return this.key
  }

  // TODO: compat, will be removed
  get bootstraps() {
    return [this.bootstrap]
  }

  get appending() {
    return this._appending !== null && this._appending.length > 0
  }

  get writable() {
    return this.localWriter !== null && !this.localWriter.isRemoved
  }

  get ackable() {
    return this.localWriter !== null && this.localWriter.isActiveIndexer
  }

  get signedLength() {
    return this.core.signedLength
  }

  get indexedLength() {
    return this._applyState ? this._applyState.indexedLength : 0
  }

  get length() {
    return this.core.length
  }

  get flushing() {
    return this._flushing > 0
  }

  hash() {
    return this.core.treeHash()
  }

  // deprecated, use .core.key
  getSystemKey() {
    return this.core.key
  }

  get system() {
    return this._applyState && this._applyState.system
  }

  // deprecated
  async getIndexedInfo() {
    if (this.opened === false) await this.ready()
    return (
      this._applyState && this._applyState.system.getIndexedInfo(this._applyState.indexedLength)
    )
  }

  _isActiveIndexer() {
    return this.localWriter ? this.localWriter.isActiveIndexer : false
  }

  replicate(isInitiator, opts) {
    const stream = this.store.replicate(isInitiator, opts)
    this.wakeupProtocol.addStream(stream)
    return stream
  }

  heads() {
    if (!this._applyState || !this._applyState.opened) return []
    const nodes = new Array(this._applyState.system.heads.length)
    for (let i = 0; i < this._applyState.system.heads.length; i++)
      nodes[i] = this._applyState.system.heads[i]
    return nodes.sort(compareNodes)
  }

  async export() {
    const exporting = [this.store.storage.export(this.local.discoveryKey), this._viewStore.export()]

    const [local, views] = await Promise.all(exporting)

    return {
      local,
      views
    }
  }

  hintWakeup(hints) {
    if (!Array.isArray(hints)) hints = [hints]
    for (const { key, length } of hints) {
      const hex = b4a.toString(key, 'hex')
      const prev = this._wakeupHints.get(hex)
      if (!prev || length === -1 || prev < length) this._wakeupHints.set(hex, length)
    }
    this._queueBump()
  }

  setBigBatches(bool = true) {
    this.bigBatches = bool
  }

  _queueBump() {
    this._bump().catch(safetyCatch)
  }

  async _runPreOpen() {
    if (this._handlers.wait) await this._handlers.wait()

    await this.store.ready()

    this.keyPair = (await this._handlers.keyPair) || null

    if (this._handlers.encryptionKey !== null) {
      this.encryptionKey = await this._handlers.encryptionKey
    }

    const result = await boot(this.store, this.key, {
      encryptionKey: this.encryptionKey,
      encrypt: this.encrypt,
      keyPair: this.keyPair,
      blindEncryption: this.blindEncryption
    })

    this._primaryBootstrap = result.bootstrap
    this.local = result.local

    this.key = result.bootstrap.key
    this.discoveryKey = result.bootstrap.discoveryKey
    this.id = result.bootstrap.id

    this.encryptionKey = result.encryptionKey

    if (this.encrypted) {
      assert(this.encryptionKey !== null, 'Encryption key is expected')
    }

    if (this.encryptionKey) {
      this.encryption = new EncryptionView(this, null)

      this.local.setEncryption(this.getWriterEncryption())
      this._primaryBootstrap.setEncryption(this.getWriterEncryption())
    }

    if (this.nukeTip) await this._nukeTip()

    this.local.on('append', this._onlocalwriterchangeBound)

    this.wakeupCapability = (await this._handlers.wakeupCapability) || {
      key: this.key,
      discoveryKey: this.discoveryKey
    }
    this.setWakeup(this.wakeupCapability.key, this.wakeupCapability.discoveryKey)
  }

  async _nukeTipBatch(key, length) {
    const core = this.store.get({ key, active: false })
    await core.ready()

    const batch = core.session({ name: 'batch' })
    await batch.ready()
    if (batch.length > length) await batch.truncate(length)
    await batch.close()

    await core.close()
  }

  // TODO: not atomic atm, so more of a (very useful) debug helper
  async _nukeTip() {
    const pointer = await this.local.getUserData('autobase/boot')
    if (!pointer) return

    const boot = c.decode(messages.BootRecord, pointer)

    await LocalState.clear(this.local)

    await this._nukeTipBatch(boot.key, boot.systemLength)

    const core = this.store.get({ key: boot.key, active: false, encryption: null })
    const encCore = await EncryptionView.setSystemEncryption(this, core)

    const batch = core.session({ name: 'batch' })
    await batch.ready()

    const info = await SystemView.getIndexedInfo(batch, boot.systemLength)
    await batch.close()

    for (const view of info.views) {
      // ensure any views ref'ed by system are consistent as well
      await this._nukeTipBatch(view.key, view.length)
    }

    if (boot.heads) this.hintWakeup(boot.heads)
    if (this.local.length) this.hintWakeup([{ key: this.local.key, length: this.local.length }])

    await core.close()
    if (encCore) await encCore.close()
  }

  _bumpWakeupPeer(peer) {
    if (this._coupler) this._coupler.update(peer.stream)
  }

  async _rotateLocalWriter(newLocal) {
    assert(!this.appending, 'Cannot rotate a newLocal writer if an append is in progress')

    const oldLocal = this.local

    if (this._applyState) await this._applyState.close()

    this.local = newLocal
    this.local.on('append', this._onlocalwriterchangeBound)

    this.localWriter = null
    this._updateLocalCore = null

    const store = this._viewStore.atomize()

    const local = store.getLocal()
    await local.ready()

    await LocalState.moveTo(oldLocal, local)

    await local.setUserData('referrer', this.key)
    if (this.encryptionKey) {
      if (this.blindEncryption) {
        const encrypted = await encryptionEncoding.encrypt(
          this.encryptionKey,
          this.blindEncryption.encrypt
        )
        await local.setUserData('autobase/blind-encryption', encrypted)
      } else {
        await local.setUserData('autobase/encryption', this.encryptionKey)
      }
    }

    await store.flush()
    await store.close()

    await this._primaryBootstrap.setUserData('autobase/local', local.key)

    await this._clearWriters()
    await oldLocal.close()

    // done, soft reboot

    await this._viewStore.updateLocal()

    await this._clearWriters()

    this._applyState = new ApplyState(this)
    await this._applyState.ready()
    await this._makeLinearizerFromViewState()

    this._caughtup = false

    this._rebooted()

    this.emit('rotate-local-writer')
  }

  async setLocal(key, { keyPair } = {}) {
    if (!this.opened) await this.ready()

    const manifest = keyPair
      ? { version: this.store.manifestVersion, signers: [{ publicKey: keyPair.publicKey }] }
      : null
    if (!key) key = Hypercore.key(manifest)
    // If the keys are the same, no need to rotate
    if (b4a.equals(key, this.local.key)) return

    const encryption = this.encryptionKey ? this.getWriterEncryption() : null

    const local = this.store.get({
      key,
      manifest,
      active: false,
      exclusive: true,
      encryption,
      valueEncoding: messages.OplogMessage
    })
    await local.ready()

    this._updateLocalCore = local

    let runs = 0
    while (!this._interrupting && this.appending && runs++ < 16) await this.update()
    await this._bump()
  }

  setWakeup(cap, discoveryKey) {
    if (this.wakeupSession) this.wakeupSession.destroy()
    if (!discoveryKey && b4a.equals(cap, this.key)) discoveryKey = this.discoveryKey
    this.wakeupSession = this.wakeupProtocol.session(
      cap,
      new WakeupHandler(this, discoveryKey || null)
    )

    // incase this session has active peers already, bump the coupler
    for (const peer of this.wakeupSession.peers) {
      if (peer.active) this._bumpWakeupPeer(peer)
    }
  }

  async _getMigrationPointer(key, length) {
    const core = this.store.get({ key, active: false, encryption: null })
    const encCore = await EncryptionView.setSystemEncryption(this, core)

    const min = core.manifest && core.manifest.prologue ? core.manifest.prologue.length : 0

    for (let i = length - 1; i >= min; i--) {
      if (!(await core.has(i))) continue

      const sys = new SystemView(core, { checkout: i + 1 })
      await sys.ready()

      let good = true

      for (const v of sys.views) {
        const vc = this.store.get({ key: v.key, active: false })
        await vc.ready()
        if (vc.length < v.length) good = false
        await vc.close()
      }

      await sys.close()
      if (!good) continue

      return i + 1
    }

    await core.close()
    if (encCore) await encCore.close()

    return min
  }

  // migrating from 6 -> latest
  async _migrate6(key, length) {
    const core = this.store.get({ key, active: false })
    await core.ready()
    const batch = core.session({ name: 'batch', overwrite: true, checkout: length })
    await batch.ready()
    await batch.close()
    await core.close()
  }

  // called by view-store for bootstrapping
  async _getSystemInfo() {
    const boot = await this._getBootRecord()
    if (!boot.key) return null

    const migrated = !!boot.heads
    const indexedLength = boot.systemLength

    if (migrated) {
      // ensure system batch is consistent on initial migration
      await this._migrate6(boot.key, indexedLength)
    }

    const core = this.store.get({ key: boot.key, encryption: null, active: false })
    await core.ready()

    const batch = core.session({ name: 'batch' })
    const encCore = await EncryptionView.setSystemEncryption(this, batch)

    await batch.ready()
    if (encCore) await encCore.ready()

    const info = await SystemView.getIndexedInfo(batch, indexedLength)

    if (encCore) await encCore.close()
    await batch.close()
    await core.close()

    if (info.version > MAX_AUTOBASE_VERSION) {
      throw new Error('Autobase upgrade required.')
    }

    // just compat
    if (migrated) {
      this.migrated = true

      for (const view of info.views) {
        // ensure any views ref'ed by system are consistent as well
        await this._migrate6(view.key, view.length)
      }

      if (boot.heads) this.hintWakeup(boot.heads)
      if (this.local.length) this.hintWakeup([{ key: this.local.key, length: this.local.length }])
    }

    return {
      key: boot.key,
      indexers: info.indexers,
      views: info.views,
      entropy: info.entropy
    }
  }

  // called by the apply state for bootstrapping
  async _getBootRecord() {
    await this._preopen

    const pointer = await this.local.getUserData('autobase/boot')

    const boot = pointer
      ? c.decode(messages.BootRecord, pointer)
      : {
          version: BOOT_RECORD_VERSION,
          key: null,
          systemLength: 0,
          indexersUpdated: false,
          fastForwarding: false,
          recoveries: RECOVERIES,
          heads: null
        }

    if (boot.heads) {
      const len = await this._getMigrationPointer(boot.key, boot.systemLength)
      if (len !== boot.systemLength)
        this._warn(
          new Error(
            'Invalid pointer in migration, correcting (' + len + ' vs ' + boot.systemLength + ')'
          )
        )
      boot.systemLength = len
    }

    return boot
  }

  static async getBootRecord(store, key) {
    const result = await boot(store, key, { exclusive: false })
    await result.bootstrap.close()
    await result.local.close()
    return result.boot
  }

  _interrupt(reason) {
    assert(!!this._applyState.applying, 'Interrupt is only allowed in apply')
    this._interrupting = true
    if (reason) this.interrupted = reason
    throw INTERRUPT
  }

  async flush() {
    if (this._flushing === 0) return
    return this._flushSignal.wait()
  }

  async advance() {
    if (this.opened === false) await this.ready()
    await this._advancing
  }

  recouple() {
    if (this._coupler) this._coupler.destroy()
    const core = this._viewStore.getSystemCore()
    this._coupler = new CoreCoupler(core, this._wakeupPeerBound)
  }

  _updateBootstrapWriters() {
    const writers = this.linearizer.getBootstrapWriters()

    // first clear all, but without applying it for churn reasons
    for (const writer of this._bootstrapWriters) {
      writer.isBootstrap = false
      writer.isCoupled = false
    }

    // all passed are bootstraps
    for (const writer of writers) {
      writer.isCoupled = true
      writer.setBootstrap(true)
    }

    // reset activity on old ones, all should be in sync now
    for (const writer of this._bootstrapWriters) {
      if (writer.isBootstrap === false) writer.setBootstrap(false)
    }

    this._bootstrapWriters = writers
    this._bootstrapWritersChanged = false
  }

  async _openLinearizer() {
    if (this._applyState.system.bootstrapping) {
      await this._makeLinearizer(null)
      this._bootstrapLinearizer()
      return
    }

    await this._makeLinearizerFromViewState()
  }

  async _catchupApplyState() {
    if (await this._applyState.shouldMigrate()) {
      await this._migrate()
    } else if (!(await this._applyState.catchup(this.linearizer))) {
      return false
    }

    this._caughtup = true
    return true
  }

  async _open() {
    this._preopen = this._runPreOpen()
    await this._preopen

    if (this.closing) return

    this._applyState = new ApplyState(this)

    try {
      await this._applyState.ready()
    } catch (err) {
      if (this.closing) return

      try {
        await this._applyState.close()
      } catch {}

      try {
        await this.core.ready()
      } catch {}

      this._applyState = null
      if (this.closing) return

      throw err
    }

    try {
      await this._openLinearizer()
      await this.core.ready()
      await this._wakeup.ready()
    } catch (err) {
      if (this.closing) return
      throw err
    }

    if (this.core.length - this._applyState.indexedLength > this._ackTickThreshold) {
      this._ackTick = this._ackTickThreshold
    }
    if (this.localWriter && this._ackInterval) {
      this._startAckTimer()
    }

    this._updateBootstrapWriters()

    this.recouple()
    this._queueFastForward()

    // queue a full bump that handles wakeup etc (not legal to wait for that here)
    this._queueBump()
  }

  async _close() {
    await this.flush() // flush all pending non network io
    this._interrupting = true
    await Promise.resolve() // defer one tick

    if (this.wakeupSession) this.wakeupSession.destroy()
    if (this.wakeupOwner) this.wakeupProtocol.destroy()

    if (this.fastForwarding) await this.fastForwarding.close()

    if (this._coupler) this._coupler.destroy()
    this._coupler = null
    this._waiting.notify(null)

    await this.activeWriters.clear()

    const closing = this._advancing ? this._advancing.catch(safetyCatch) : null

    await this._clearWriters()
    if (this._primaryBootstrap) await this._primaryBootstrap.close()
    await this.local.close()

    if (this._ackTimer) {
      this._ackTimer.stop()
      await this._ackTimer.flush()
    }

    await this._wakeup.close()

    if (this._hasClose) await this._handlers.close(this.view)
    if (this._applyState) await this._applyState.close()

    await this._viewStore.close()
    await this.core.close()
    await this.store.close()

    if (this._writable) this._writable.resolve(false)

    await closing
  }

  getLastError() {
    return this._lastError
  }

  _onError(err) {
    if (this.closing) return

    this._lastError = err

    if (err === INTERRUPT) {
      this.emit('interrupt', this.interrupted)
      this.emit('update')
      return
    }

    this.close().catch(safetyCatch)

    // if no one is listening we should crash! we cannot rely on the EE here
    // as this is wrapped in a promise so instead of nextTick throw it
    if (ReadyResource.listenerCount(this, 'error') === 0) {
      crashSoon(err)
      return
    }

    this.emit('error', err)
  }

  async _closeWriter(w) {
    this.activeWriters.delete(w)
    await w.close()
  }

  async _gcWriters() {
    // just return early, why not
    if (this._checkWriters.length === 0) return

    while (this._checkWriters.length > 0) {
      const w = this._checkWriters.pop()

      // doesnt hurt
      w.updateActivity()

      if (!w.flushed()) continue

      const unqueued = this._wakeup.unqueue(w.core.key, w.core.length)

      if (!unqueued || w.isActiveIndexer) continue
      if (this.localWriter === w) continue

      await this._closeWriter(w)
    }

    await this._wakeup.flush()
  }

  _startAckTimer() {
    if (this._ackTimer) return
    this._ackTimer = new Timer(this._backgroundAck.bind(this), this._ackInterval)
    this._bumpAckTimer()
  }

  _bumpAckTimer() {
    if (!this._ackTimer) return
    this._ackTimer.bump()
  }

  async update() {
    if (this.opened === false) await this.ready()

    try {
      await this._bump()
      if (this._acking) await this._bump() // if acking just rebump incase it was triggered from above...
    } catch (err) {
      if (this._interrupting) return
      throw err
    }
  }

  // runs in bg, not allowed to throw
  // TODO: refactor so this only moves the writer affected to a updated set
  async _onremotewriterchange() {
    this._bumpAckTimer()

    try {
      await this._bump()
    } catch {}
  }

  _onlocalwriterchange() {
    if (!this.localWriter || this.localWriter.isRemoved) this._queueBump()
  }

  _onwakeup() {
    this._needsWakeup = true
    this._queueBump()
  }

  isFastForwarding() {
    if (this.fastForwardTo !== null) return true
    return this.fastForwardEnabled && this.fastForwarding !== null
  }

  _backgroundAck() {
    return this.ack(true)
  }

  async ack(bg = false) {
    if (this.opened === false) await this.ready()
    if (this.localWriter === null || this._acking || this._interrupting || this._appending !== null)
      return

    if (this._applyState === null) {
      try {
        await this._bump()
      } catch {}
      if (this._applyState === null || this._interrupting) return
    }

    const applyState = this._applyState
    if (applyState.opened === false) await applyState.ready()

    const isPendingIndexer = applyState.isLocalPendingIndexer()

    // if no one is waiting for our index manifest, wait for FF before pushing an ack
    if ((!isPendingIndexer && this.isFastForwarding()) || this._interrupting) return

    const isIndexer = applyState.isLocalIndexer() || isPendingIndexer
    if (!isIndexer) return

    this._acking = true

    try {
      await this._bump()
    } catch (err) {
      if (!this._interrupting) throw err
    }

    if (this._interrupting || !this.localWriter || this.localWriter.closed) {
      this._acking = false
      return
    }

    // avoid lumping acks together due to the bump wait here
    if (this._ackTimer && bg) await this._ackTimer.asapStandalone()
    if (this._interrupting || applyState.closing) {
      this._acking = false
      return
    }

    const alwaysWrite = isPendingIndexer || (await applyState.shouldWrite())
    if (this._interrupting || applyState.closing) {
      this._acking = false
      return
    }

    const hasPendingIndexers = applyState.system.indexers.length > this.linearizer.indexers.length

    if (alwaysWrite || this.linearizer.shouldAck(this.localWriter, hasPendingIndexers)) {
      try {
        if (this.localWriter && !this.localWriter.closed) await this.append(null)
      } catch (err) {
        if (!this._interrupting) throw err
      }
    }

    if (!this._interrupting) {
      this._updateAckThreshold()
      this._bumpAckTimer()
    }

    this._acking = false
  }

  views() {
    if (this._applyState) return this._applyState.store.listViews()
    return this._viewStore.listViews()
  }

  batch() {
    return new AppendBatch(this)
  }

  async append(value, opts) {
    if (this.opened === false) await this.ready()
    if (this._advancing !== null) await this._advancing
    while (this.activeBatch) await this.activeBatch.flushed()
    return this._appendBatch(value, opts)
  }

  async _appendBatch(value, opts) {
    if (this._interrupting) throw new Error('Autobase is closing')
    if (value && this.valueEncoding !== BINARY_ENCODING)
      value = normalize(this.valueEncoding, value)

    const optimistic = !!opts && !!opts.optimistic && !!value

    // we wanna allow acks so interdexers can flush
    if (
      !optimistic &&
      (this.localWriter === null || (this.localWriter.isRemoved && value !== null))
    ) {
      throw new Error('Not writable')
    }

    if (this._appending === null) this._appending = []

    let len = 0
    if (Array.isArray(value)) {
      for (const v of value) len = this._append(v)
    } else {
      len = this._append(value)
    }

    const localLength = this.local.length

    if (optimistic) this._optimistic = this._appending.length - 1
    const target = this._appended + this._appending.length

    // await in case append is in current tick
    if (this._advancing) await this._advancing

    let runs = 0

    // bump until we've flushed the nodes
    while (this._appended < target && !this._interrupting) {
      await this._bump()
      // safety
      if (runs++ >= 16 && this.localWriter && this.localWriter.idle()) break
    }

    if (this._advancing) await this._advancing
    if (this._interrupting) throw new Error('Autobase is closing')

    return localLength + len
  }

  _append(value) {
    // if prev value is an ack that hasnt been flushed, skip it
    if (this._appending.length > 0) {
      if (value === null) return this._appending.length
      if (this._appending[this._appending.length - 1] === null) {
        this._appending.pop()
      }
    }
    return this._appending.push(value)
  }

  static decodeValue(value, opts) {
    return decodeValue(value, opts)
  }

  static encodeValue(value, opts) {
    return encodeValue(value, opts)
  }

  static async getLocalKey(store, opts = {}) {
    const core = opts.keyPair
      ? store.get({ ...opts, active: false })
      : store.get({ ...opts, name: 'local', active: false })
    await core.ready()
    const key = core.key
    await core.close()
    return key
  }

  static getLocalCore(store, handlers, encryptionKey) {
    const encryption = !encryptionKey ? null : { key: encryptionKey }
    const opts = {
      ...handlers,
      compat: false,
      active: false,
      exclusive: true,
      valueEncoding: messages.OplogMessage,
      encryption
    }
    return opts.keyPair ? store.get(opts) : store.get({ ...opts, name: 'local' })
  }

  static async getUserData(core) {
    const view = await core.getUserData('autobase/view')

    return {
      referrer: await core.getUserData('referrer'),
      view: view ? b4a.toString(view) : null
    }
  }

  static async isAutobase(core, opts = {}) {
    const block = await core.get(0, opts)
    if (!block) throw new Error('Core is empty.')
    if (!b4a.isBuffer(block)) return isAutobaseMessage(block)

    try {
      const m = c.decode(messages.OplogMessage, block)
      return isAutobaseMessage(m)
    } catch {
      return false
    }
  }

  // no guarantees where the user data is stored, just that its associated with the base
  async setUserData(key, val) {
    await this._preopen
    const core = this._primaryBootstrap === null ? this.local : this._primaryBootstrap

    await core.setUserData(key, val)
  }

  async getUserData(key) {
    await this._preopen
    const core = this._primaryBootstrap === null ? this.local : this._primaryBootstrap

    return await core.getUserData(key)
  }

  _needsLocalWriter() {
    return this.localWriter === null || this.localWriter.closed
  }

  // no guarantees about writer.isActiveIndexer property here
  async _getWriterByKey(key, len, seen, allowGC, isAdded, system) {
    assert(this._draining === true || (this.opening && !this.opened) || this._optimistic > -1)

    await this._lock.lock()

    if (this._interrupting) {
      this._lock.unlock()
      throw new Error('Autobase is closing')
    }

    try {
      let w = this.activeWriters.get(key)

      const alreadyActive = !!w
      const sys = system || this._applyState.system
      const writerInfo = await sys.get(key)

      if (len === -1) {
        if (!allowGC && writerInfo === null) {
          if (w) w.isRemoved = !isAdded
          return null
        }

        len = writerInfo === null ? 0 : writerInfo.length
      }

      const isActive = writerInfo !== null && (isAdded || !writerInfo.isRemoved)
      const isRemoved = !isActive

      if (w) {
        w.isRemoved = isRemoved
      } else {
        w = this._makeWriter(key, len, isActive, isRemoved)
        if (!w) return null
      }

      if (isRemoved && sys.bootstrapping && b4a.equals(w.core.key, this.key)) {
        w.isRemoved = false
      }

      if (this._isLocalCore(w.core) && this._needsLocalWriter()) {
        this._setLocalWriter(w)
      }

      w.seen(seen)

      if (alreadyActive) return w

      await w.ready()

      if (this._isLocalCore(w.core) && this._needsLocalWriter()) {
        this._setLocalWriter(w)
      }

      if (allowGC && w.flushed()) {
        this._wakeup.unqueue(key, len)
        if (w !== this.localWriter) {
          await w.close()
          return w
        }
      }

      this.activeWriters.add(w)
      this._checkWriters.push(w)

      assert(w.opened)
      assert(!w.closed)

      w.updateActivity()
      return w
    } finally {
      this._lock.unlock()
    }
  }

  _updateAll() {
    const p = []
    for (const w of this.activeWriters) p.push(w.update(null).catch(safetyCatch))
    return Promise.all(p)
  }

  getWriterEncryption() {
    if (!this.encryptionKey) return null
    return this.encryption.getWriterEncryption()
  }

  _makeWriterCore(key) {
    if (this.closing) throw new Error('Autobase is closing')
    if (this._interrupting) throw INTERRUPT()

    const local = b4a.equals(key, this.local.key)
    const encryption = this.getWriterEncryption()

    const core = local
      ? this.local.session({ valueEncoding: messages.OplogMessage, encryption, active: false })
      : this.store.get({
          key,
          compat: false,
          writable: false,
          valueEncoding: messages.OplogMessage,
          encryption,
          active: false
        })

    return core
  }

  _makeWriter(key, length, isActive, isRemoved) {
    const core = this._makeWriterCore(key)
    const w = new Writer(this, core, length, isRemoved)

    if (this._isLocalCore(core)) {
      if (isActive) this._setLocalWriter(w) // only set active writer
      return w
    }

    core.on('append', this._onremotewriterchangeBound)
    core.on('download', this._onremotewriterchangeBound)
    core.on('manifest', this._onremotewriterchangeBound)

    return w
  }

  _updateLinearizer(indexers, heads) {
    // only current active indexers are reset to true below
    for (const w of this.activeWriters) w.isActiveIndexer = false
    if (this.localWriter) this.localWriter.isActiveIndexer = false

    for (const writer of indexers) writer.isActiveIndexer = true

    if (this._isActiveIndexer() && !this.isIndexer) {
      this._setLocalIndexer()
    } else if (!this._isActiveIndexer() && this.isIndexer) {
      this._clearLocalIndexer()
    }

    this.linearizer = new Linearizer(indexers, { heads, writers: this.activeWriters })

    this._updateAckThreshold()
  }

  async _updateLocalWriter(sys) {
    if (this.localWriter !== null && !this.localWriter.closed) return
    await this._getWriterByKey(this.local.key, -1, 0, true, false, sys)
  }

  async _bootstrapLinearizer() {
    const bootstrap = this._makeWriter(this.key, 0, true, false)

    this.activeWriters.add(bootstrap)
    this._checkWriters.push(bootstrap)
    await bootstrap.ready()
    this._ensureWakeup(bootstrap)

    this._updateLinearizer([bootstrap], [])
  }

  async _makeLinearizer(sys) {
    if (sys === null) {
      return this._bootstrapLinearizer()
    }

    if (this.opened || (await sys.hasLocal(this.local.key))) {
      await this._updateLocalWriter(sys)
    }

    const indexers = []

    for (const head of sys.indexers) {
      const writer = await this._getWriterByKey(head.key, head.length, 0, false, false, sys)
      indexers.push(writer)
    }

    if (!this._isActiveIndexer()) {
      for (const key of sys.pendingIndexers) {
        if (b4a.equals(key, this.local.key)) {
          this._setLocalIndexer()
          break
        }
      }
    }

    this._updateLinearizer(indexers, sys.heads)

    for (const { key, length } of sys.heads) {
      await this._getWriterByKey(key, length, 0, false, false, sys)
    }
  }

  async _clearWriters() {
    await this.activeWriters.clear()
    if (this.localWriter !== null) await this.localWriter.close()
    this._checkWriters = []
  }

  async _moveTo() {
    assert(this._applyState.closed)
    for (const ref of this._viewStore.byName.values()) {
      if (!ref.moveTo) continue
      const [batch, next] = ref.moveTo
      ref.moveTo = null
      await ref.batch.state.moveTo(batch, batch.length)
      await batch.close()
      ref.migrated(this, next)
    }
  }

  async _makeLinearizerFromViewState() {
    const sys = await this._applyState.getIndexedSystem()
    await this._makeLinearizer(sys)
    await sys.close()
  }

  async _runForceFastForward() {
    await this.core.ready()
    if (this.closing) return
    const rec = this._applyState ? await this._applyState.recoverAt() : null
    await this._runFastForward(
      new FastForward(this, this.core.key, { force: true, length: rec ? rec.length : 0 })
    )
  }

  // general repair method for trying to recover
  async repair() {
    await this.forceFastForward()
  }

  async forceFastForward() {
    if (this.isFastForwarding()) return
    await this._runForceFastForward()
    await this.update()
  }

  async _applyFastForward() {
    if (
      !this.fastForwardTo.force &&
      this.fastForwardTo.length < this.core.length + this.fastForwardTo.minimum
    ) {
      this.fastForwardTo = null
      this._updateActivity()
      // still not worth it
      return
    }

    const changes = this._hasUpdate ? new UpdateChanges(this) : null
    if (changes) changes.track(this._applyState)

    // close existing state
    if (this._applyState) await this._applyState.close()

    const { key, length, views, indexers, manifestVersion, entropy } = this.fastForwardTo

    const from = this.core.signedLength
    const ffed = new Set()

    this._flushing++
    try {
      const store = this._viewStore.atomize()

      const systemRef = await this._viewStore.findViewByKey(key, indexers, manifestVersion, entropy)
      const migrated = !b4a.equals(key, systemRef.core.key)

      ffed.add(systemRef)

      if (migrated) {
        await this._applyFastForwardMigration(systemRef, { key, length })
      } else {
        await systemRef.catchup(store.atom, length)
      }

      for (const v of views) {
        const ref = await this._viewStore.findViewByKey(v.key, indexers, manifestVersion, entropy)
        if (!ref) continue // unknown, view ignored

        const migrated = !b4a.equals(ref.core.key, v.key)

        ffed.add(ref)

        if (migrated) {
          await this._applyFastForwardMigration(ref, v)
        } else {
          await ref.catchup(store.atom, v.length)
        }
      }

      if (ffed.size !== store.getViewCount()) {
        for (const ref of store.getViews()) {
          if (ffed.has(ref)) continue
          await ref.catchup(store.atom, 0) // its gone
        }
      }

      // migrate zero length cores
      if (migrated) {
        const manifests = await this._viewStore.getIndexerManifests(indexers)

        for (const [name, ref] of this._viewStore.byName) {
          if (ffed.has(ref)) continue
          await this._migrateView(manifests, null, name, 0, manifestVersion, entropy, [], null)
        }
      }

      const value = c.encode(messages.BootRecord, {
        version: BOOT_RECORD_VERSION,
        key,
        systemLength: length,
        indexersUpdated: false,
        fastForwarding: true,
        recoveries: RECOVERIES
      })

      const local = store.getLocal()
      await local.ready()
      await local.setUserData('autobase/boot', value)

      await LocalState.clear(local)

      await store.flush()
      await store.close()
    } finally {
      if (--this._flushing === 0) this._flushSignal.notify()
    }

    for (const ref of this._viewStore.byName.values()) await ref.release()

    this.recoveries = RECOVERIES
    this.fastForwardTo = null
    this._queueFastForward()

    await this._clearWriters()
    await this._moveTo()
    const to = this.core.signedLength

    if (changes) changes.finalise()

    this._applyState = new ApplyState(this)
    await this._applyState.ready()

    if (changes) await this._handlers.update(this._applyState.view, changes)

    if (await this._applyState.shouldMigrate()) {
      await this._migrate()
    } else {
      await this._makeLinearizerFromViewState()
      await this._applyState.catchup(this.linearizer)
    }

    if (!this.localWriter || this.localWriter.closed) {
      await this._updateLocalWriter(this._applyState.system)
    }

    this._caughtup = true

    this._rebooted()
    this.emit('fast-forward', to, from)
  }

  // TODO: not atomic in regards to the ff, fix that
  async _applyFastForwardMigration(ref, v) {
    await ref.batch.ready()

    const next = this.store.get(v.key)
    await next.ready()

    const prologue = next.manifest && next.manifest.prologue

    if (prologue && prologue.length > 0 && ref.core.length >= prologue.length) {
      try {
        await next.core.copyPrologue(ref.core.state)
      } catch {
        // we might be missing some nodes for this, just ignore, only an optimisation
      }
    }

    const batch = next.session({ name: 'batch', overwrite: true, checkout: v.length })
    await batch.ready()

    // remake the batch, reset from our prologue in case it replicated inbetween
    // TODO: we should really have an HC function for this

    ref.moveTo = [batch, next]
  }

  async _migrateView(
    indexerManifests,
    source,
    name,
    indexedLength,
    manifestVersion,
    entropy,
    linked,
    manifestData
  ) {
    const ref = this._viewStore.byName.get(name)
    await ref.batch.ready()

    const prologue =
      indexedLength === 0
        ? null
        : { length: indexedLength, hash: await source.treeHash(indexedLength) }

    if (manifestData === null && ref.core.manifest.userData !== null) {
      manifestData = ref.core.manifest.userData
    }

    const next = this._viewStore.getViewCore(
      indexerManifests,
      name,
      prologue,
      manifestVersion,
      entropy,
      linked,
      manifestData
    )
    await next.ready()

    if (indexedLength > 0) {
      await next.core.copyPrologue(source.state)
    }

    // remake the batch, reset from our prologue in case it replicated inbetween
    // TODO: we should really have an HC function for this
    const batch = next.session({ name: 'batch', overwrite: true, checkout: indexedLength })
    await batch.ready()

    if (source !== null) {
      while (batch.length < source.length) {
        await batch.append(await source.get(batch.length))
      }
    }

    ref.moveTo = [batch, next]

    return ref
  }

  async _premigrate() {
    this._flushing++
    try {
      const length = this._applyState.indexedLength
      const system = this._applyState.system

      const info = await system.getIndexedInfo(length)
      const indexerManifests = await this._viewStore.getIndexerManifests(info.indexers)

      const { views, systemView, encryptionView } = this._applyState

      const manifestVersion = this._applyState.system.core.manifest.version

      for (const view of views) {
        const v = this._applyState.getViewFromSystem(view, info)
        const indexedLength = v ? v.length : 0

        const ref = this._viewStore.getViewByName(view.name)
        const source = ref.getCore()
        await source.ready()

        await this._migrateView(
          indexerManifests,
          source,
          view.name,
          indexedLength,
          manifestVersion,
          info.entropy,
          null,
          null
        )
      }

      const source = encryptionView.ref.getCore()
      await source.ready()

      const enc = await this._migrateView(
        indexerManifests,
        source,
        '_encryption',
        info.encryptionLength,
        manifestVersion,
        info.entropy,
        null,
        null
      )

      const linked = [enc.core.key]

      const sysCore = systemView.ref.getCore()
      const ref = await this._migrateView(
        indexerManifests,
        sysCore,
        '_system',
        length,
        manifestVersion,
        info.entropy,
        linked,
        null,
        null
      )

      const sysKey = ref.getNextKey()
      if (sysKey === null) {
        throw new Error('Migration failed, expected core to be moved')
      }

      return sysKey
    } finally {
      if (--this._flushing === 0) this._flushSignal.notify()
    }
  }

  async _migrate() {
    return this._reboot(await this._premigrate())
  }

  async _reboot(key) {
    await this._clearWriters()
    await this._makeLinearizerFromViewState()

    await this._applyState.finalize(key)
    await this._moveTo()

    this._applyState = new ApplyState(this)

    await this._applyState.ready()
    await this._applyState.catchup(this.linearizer)

    // end soft shutdown

    this._queueFastForward()

    this._rebooted()
  }

  _rebooted() {
    this.recouple()
    this._updateActivity()

    this.emit('reboot')

    // ensure we re-evalute our state
    this._bootstrapWritersChanged = true
    this._needsWakeup = true

    this.updating = true
    this._queueBump()
  }

  _setLocalWriter(w) {
    this.localWriter = w
    if (this._ackInterval) this._startAckTimer()
  }

  _unsetLocalWriter() {
    if (!this.localWriter) return

    this._closeWriter(this.localWriter)
    if (this.localWriter.isActiveIndexer) this._clearLocalIndexer()

    this.localWriter = null
  }

  _setLocalIndexer() {
    assert(this.localWriter !== null)

    this.isIndexer = true
    this.emit('is-indexer')
  }

  _clearLocalIndexer() {
    assert(this.localWriter !== null)

    if (this._ackTimer) this._ackTimer.stop()

    this.isIndexer = false
    this._ackTimer = null

    this.emit('is-non-indexer')
  }

  _isLocalCore(core) {
    return core.writable && core.id === this.local.id
  }

  _addLocalHeads() {
    // not writable atm, will prop be writable in a subsequent bump tho
    if (!this.localWriter || this.localWriter.closed) return null
    // safety, localwriter is still processing, should prop be an assertion
    if (!this.localWriter.idle()) return null

    const length = this._optimistic === -1 ? this._appending.length : this._optimistic || 1

    const nodes = new Array(length)
    for (let i = 0; i < length; i++) {
      const heads = this.linearizer.getHeads()
      const deps = new Set(this.linearizer.heads)
      const batch = length - i
      const value = this._appending[i]

      const node = this.localWriter.append(value, heads, batch, deps, this._optimistic === 0)

      this.linearizer.addHead(node)
      nodes[i] = node
    }

    return nodes
  }

  _flushLocalHeads(length) {
    this._appending = length === this._appending.length ? null : this._appending.slice(length)
    this._appended += length

    if (this._optimistic > -1 && this._optimistic < length) this._optimistic = -1
  }

  async _addRemoteHeads() {
    let added = 0

    while (
      added < REMOTE_ADD_BATCH ||
      (this.bigBatches && !this._indexersIdle() && added < REMOTE_ADD_BATCH_SANITY)
    ) {
      await this._updateAll()

      let advanced = 0

      for (const w of this.activeWriters) {
        let node = w.advance()
        if (node === null) continue

        advanced += node.batch

        while (true) {
          this.linearizer.addHead(node)
          if (node.batch === 1) break
          node = w.advance()
        }
      }

      if (advanced === 0) {
        if (this.bigBatches && !this._indexersIdle() && (await this._waitForIndexers())) continue
        break
      }

      added += advanced
    }

    return added
  }

  async _waitForIndexers() {
    const promises = []

    for (const w of this.linearizer.indexers) {
      if (w.idle()) continue
      if (await w.core.has(w.length)) continue
      promises.push(w.core.get(w.length, { timeout: 3000 }))
    }

    for (const result of await Promise.allSettled(promises)) {
      if (result.status !== 'rejected') return true
    }

    return false
  }

  _indexersIdle() {
    for (const w of this.linearizer.indexers) {
      if (!w.idle()) return false
    }
    return true
  }

  async _drain() {
    const writable = this.writable

    while (!this._interrupting && !this.paused) {
      if (this.local.recovering) {
        try {
          await this.local.recover()
        } catch {
          await this._runForceFastForward()
        }
        continue
      }

      if (this.fastForwardTo !== null) {
        await this._applyFastForward()
        continue // revaluate conditions...
      }

      // we defer this to post ready so its not blocking reading the views
      if (this._caughtup === false) {
        // if the catchup fails, just force ff it to recover, less user pain
        if (!(await this._catchupApplyState())) {
          await this._runForceFastForward()
        }
        continue
      }

      const remoteAdded = await this._addRemoteHeads()
      const localNodes = this._appending !== null ? this._addLocalHeads() : null

      if (this._interrupting) return

      if (remoteAdded > 0 || localNodes !== null) {
        this.updating = true
      }

      const u = this.linearizer.update()
      const update = u
        ? await this._applyState.update(u, localNodes)
        : { reboot: false, migrated: false }

      if (localNodes) this._flushLocalHeads(localNodes.length)

      if (!update.reboot) {
        if (this._applyState.shouldFlush()) {
          await this._applyState.flush()
          this.updating = true
        }

        if (this._checkWriters.length > 0) {
          await this._gcWriters()
          continue // rerun the update loop as a writer might have been added
        }
        if (remoteAdded >= REMOTE_ADD_BATCH) continue
        break
      }

      await this._gcWriters()
      await this._reboot(this._applyState.key)
    }

    // emit state changes post drain
    if (writable !== this.writable) {
      if (this.writable && this._writable) this._writable.resolve(true)
      this.emit(writable ? 'unwritable' : 'writable')
    }
  }

  _wakeupPeer(stream) {
    if (!this.wakeupSession) return
    const wakeup = this._getWakeup()
    if (wakeup.length === 0) return
    this.wakeupSession.announceByStream(stream, wakeup)
  }

  _getWakeup() {
    const writers = []

    for (const w of this.activeWriters) {
      if (w.isActiveIndexer || w.flushed()) continue
      writers.push({ key: w.core.key, length: w.length })
    }

    return writers
  }

  async _wakeupWriter(key, length) {
    this._ensureWakeup(await this._getWriterByKey(key, -1, length, true, false, null))
  }

  // ensure wakeup on an existing writer (the writer calls this in addition to above)
  _ensureWakeup(w) {
    if (w === null || w.isBootstrap === true) return
    w.setBootstrap(true) // even if turn false at end of drain, hypercore makes them linger a bit so no churn
    this._bootstrapWriters.push(w)
    this._bootstrapWritersChanged = true
  }

  async _drainWakeup() {
    const promises = []

    // warmup all the below gets
    if (this._needsWakeup) {
      for (const { key, length } of this._wakeup) {
        const w = this.activeWriters.get(key)
        if (w) {
          if (w.length < length) w.seen(length)
          continue
        }
        promises.push(this._applyState.system.get(key))
      }

      if (this._needsWakeupHeads) {
        for (const { key } of await this._applyState.system.heads) {
          if (this.activeWriters.has(key)) continue
          promises.push(this._applyState.system.get(key))
        }
      }
    }
    for (const [hex, length] of this._wakeupHints) {
      const key = b4a.from(hex, 'hex')
      if (length !== -1) {
        const w = this.activeWriters.get(key)
        if (w) {
          if (w.length < length) w.seen(length)
          continue
        }
      }
      promises.push(this._applyState.system.get(key))
    }

    await Promise.allSettled(promises)

    if (this._needsWakeup === true) {
      this._needsWakeup = false

      for (const { key, length } of this._wakeup) {
        if (this.activeWriters.has(key)) continue
        await this._wakeupWriter(key, length)
      }

      if (this._needsWakeupHeads === true) {
        this._needsWakeupHeads = false

        for (const { key } of await this._applyState.system.heads) {
          if (this.activeWriters.has(key)) continue
          await this._wakeupWriter(key, 0)
        }
      }
    }

    for (const [hex, length] of this._wakeupHints) {
      const key = b4a.from(hex, 'hex')
      if (this.activeWriters.has(key)) continue
      if (length !== -1) {
        const info = await this._applyState.system.get(key)
        if (info && length <= info.length) continue // stale hint
      }
      await this._wakeupWriter(key, length === -1 ? 0 : length)
    }

    this._wakeupHints.clear()
  }

  pause() {
    this.paused = true
  }

  resume() {
    this.paused = false
    this._queueBump()
  }

  waitForWritable() {
    if (this.writable) return Promise.resolve(true)
    if (!this._writable) this._writable = rrp()
    return this._writable.promise
  }

  async _drainWithInterupt() {
    while (true) {
      try {
        await this._drain()
        return
      } catch (err) {
        if (this.closing || !this.fastForwardTo) throw err
        if (Date.now() - this.fastForwardFailedAt < MIN_FF_WAIT) throw err
        this.fastForwardFailedAt = Date.now()
        // if an FF is enabled retry
      }
    }
  }

  async _advance() {
    if (this.opened === false) await this.ready()
    if (this.paused || this._interrupting) return

    this._draining = true

    if (this._updateLocalCore !== null) {
      await this._rotateLocalWriter(this._updateLocalCore)
    }

    const local = this.local.length

    try {
      await this._drainWithInterupt()

      // must run post drain so the linearizer is caught up
      if (this._caughtup && (this._needsWakeup === true || this._wakeupHints.size > 0))
        await this._drainWakeup()

      // check if we should update local writer
      if (!this.localWriter || this.localWriter.closed) {
        await this._updateLocalWriter(this._applyState.system)
      }

      this._draining = false
    } catch (err) {
      this._onError(err)
      return
    }

    if (this._interrupting) return

    if (this.localWriter && !this.localWriter.closed) {
      if (this._applyState.isLocalPendingIndexer()) this.ack().catch(noop)
      else if (this._triggerAckAsap()) this._ackTimer.asap()
    }

    // keep bootstraps in sync with linearizer
    if (this.updating === true || this._bootstrapWritersChanged === true) {
      this._updateBootstrapWriters()
    }

    if (this.updating === true) {
      this.updating = false

      if (local !== this.local.length) this._resetAckTick()
      else this._ackTick++

      if (!this._interrupting) this.emit('update')
      this._waiting.notify(null)
    }

    if (!this._interrupting) await this._gcWriters()
  }

  _triggerAckAsap() {
    if (!this._ackTimer) return false

    // flush if threshold is reached and we are not already acking
    if (this._ackTickThreshold && !this._acking && this._ackTick >= this._ackTickThreshold) {
      if (this._ackTimer) {
        for (const w of this.linearizer.indexers) {
          if (w.core.length > w.length) return false // wait for the normal ack cycle in this case
        }
      }

      return true
    }

    return false
  }

  _queueFastForward() {
    if (!this.core.opened) return
    // should have a better way to get this
    const latestSignedLength = this.core.core.state.length

    if (!this.fastForwardEnabled || this.fastForwarding !== null || this._interrupting) return

    if (latestSignedLength - this.core.length < this.fastForwardMinimum) return
    if (this.fastForwardTo !== null) return
    if (Date.now() - this.fastForwardFailedAt < MIN_FF_WAIT) return

    this._runFastForward(
      new FastForward(this, this.core.key, { minimum: this.fastForwardMinimum })
    ).catch(noop)
  }

  _queueStaticFastForward(key) {
    if (!this.fastForwardEnabled || this.fastForwarding !== null || this._interrupting) return
    if (this.fastForwardTo !== null) return
    if (Date.now() - this.fastForwardFailedAt < MIN_FF_WAIT) return

    this._runFastForward(new FastForward(this, key, { verified: false })).catch(noop)
  }

  _updateActivity() {
    this.activeWriters.updateActivity()
    if (this._applyState) {
      if (this.isFastForwarding()) this._applyState.pause()
      else this._applyState.resume()
    }

    // in case we ignored wakeups case we were fast forwarding, request them now if not
    if (this._needsWakeupRequest && !this.isFastForwarding() && this.wakeupSession) {
      this._needsWakeupRequest = false

      this.wakeupSession.broadcastLookup({})
    }
  }

  _preferFastForward() {
    this.fastForwardMinimum = 1
    this._queueFastForward()
  }

  _postApply() {
    this.fastForwardMinimum = FastForward.MINIMUM
  }

  async _runFastForward(ff) {
    this.fastForwarding = ff

    this._updateActivity()

    const result = await ff.upgrade()
    await ff.close()

    if (this.fastForwarding === ff) this.fastForwarding = null

    if (!result) {
      if (ff.failed) this.fastForwardFailedAt = Date.now()
      else this._queueFastForward()
      this._updateActivity()
      return
    }

    this.fastForwardFailedAt = 0
    this.fastForwardTo = result

    if (this._applyState && this._applyState.applying && this.fastForwardMinimum === 1) {
      await this._applyState.close()
    }

    this._bumpAckTimer()
    this._queueBump()
  }

  // triggered from apply
  async _addWriter(key, sys) {
    // just compat for old version
    assert(!!this._applyState.applying, 'System changes are only allowed in apply')

    const writer =
      (await this._getWriterByKey(key, -1, 0, false, true, sys)) ||
      this._makeWriter(key, 0, true, false)
    await writer.ready()

    if (!this.activeWriters.has(key)) {
      this.activeWriters.add(writer)
      this._checkWriters.push(writer)
      this._ensureWakeup(writer)
    }

    // fetch any nodes needed for dependents
    this._queueBump()
  }

  // triggered from apply
  _removeWriter(key) {
    // just compat for old version
    const w = this.activeWriters.get(key)
    if (w) w.isRemoved = true

    this._queueBump()
  }

  removeable(key) {
    return this._applyState ? this._applyState.removeable(key) : false
  }

  _updateAckThreshold() {
    if (this._ackThreshold === 0) return
    if (this._ackTimer) this._ackTimer.bau()
    this._ackTick = 0
    this._ackTickThreshold = random2over1(this.linearizer.indexers.length * this._ackThreshold)
  }

  _resetAckTick() {
    this._ackTick = 0
    if (this._ackTimer) this._ackTimer.bau()
  }

  _shiftWriter(w) {
    w.shift()
    if (w.flushed()) this._checkWriters.push(w)
  }
}

function toKey(k) {
  return b4a.isBuffer(k) ? k : hypercoreId.decode(k)
}

function isAutobaseMessage(msg) {
  return msg.checkpoint ? msg.checkpoint.length > 0 : msg.checkpoint === null
}

function compareNodes(a, b) {
  return b4a.compare(a.key, b.key)
}

function random2over1(n) {
  return Math.floor(n + Math.random() * n)
}

function noop() {}

function crashSoon(err) {
  queueMicrotask(() => {
    throw err
  })
  throw err
}

function isObject(obj) {
  return typeof obj === 'object' && obj !== null
}

function emitWarning(err) {
  safetyCatch(err)
  this.emit('warning', err)
}

function normalize(valueEncoding, value) {
  const state = { buffer: null, start: 0, end: 0 }
  valueEncoding.preencode(state, value)
  state.buffer = b4a.allocUnsafe(state.end)
  valueEncoding.encode(state, value)
  state.start = 0
  return valueEncoding.decode(state)
}
const b4a = require('b4a')

module.exports = class ActiveWriters {
  constructor() {
    this.map = new Map()
  }

  get size() {
    return this.map.size
  }

  [Symbol.iterator]() {
    return this.map.values()
  }

  get(key) {
    return this.map.get(b4a.toString(key, 'hex')) || null
  }

  has(key) {
    return this.get(key) !== null
  }

  add(writer) {
    this.map.set(b4a.toString(writer.core.key, 'hex'), writer)
  }

  delete(writer) {
    this.map.delete(b4a.toString(writer.core.key, 'hex'))
  }

  updateActivity() {
    for (const w of this.map.values()) w.updateActivity()
  }

  clear() {
    const p = []
    for (const w of this.map.values()) p.push(w.close())
    this.map.clear()

    return Promise.all(p)
  }
}
const SignalPromise = require('signal-promise')

module.exports = class AppendBatch {
  constructor(base) {
    this.base = base
    this.blocks = []
    this.closed = false
    this.flushing = false
    this._flushed = null
  }

  async _acquire() {
    while (this.base.activeBatch !== null && this.base.activeBatch !== this)
      await this.base.activeBatch.flushed()
    this.base.activeBatch = this
  }

  async append(value) {
    if (this.base.opened === false) await this.base.ready()
    if (this.base._advancing !== null) await this.base._advancing

    if (this.closed) throw new Error('Batch is closed')
    if (this.base.activeBatch !== this) await this._acquire()
    if (this.closed) throw new Error('Batch is closed')

    this.blocks.push(value)
    return this.base.local.length + this.blocks.length
  }

  async flush() {
    if (this.closed) throw new Error('Batch is closed')
    if (this.flushing) return this.flushed()
    this.flushing = true
    if (this.blocks.length) await this.base._appendBatch(this.blocks)
    return this.close()
  }

  flushed() {
    if (this.closed) return Promise.resolve()
    if (this._flushed) return this._flushed.wait()
    this._flushed = new SignalPromise()
    return this._flushed.wait()
  }

  close() {
    if (this.base.activeBatch !== this) return
    this.base.activeBatch = null
    this.closed = true
    if (this._flushed) this._flushed.notify(null)
  }
}
class PublicApplyCalls {
  constructor(base) {
    this.base = base
    this.internal = false
  }

  get discoveryKey() {
    return this.base.discoveryKey
  }

  get key() {
    return this.base.key
  }

  get id() {
    return this.base.id
  }

  async addWriter() {
    throw new Error('Not allowed on the public view')
  }

  async ackWriter() {
    throw new Error('Not allowed on the public view')
  }

  async removeWriter() {
    throw new Error('Not allowed on the public view')
  }

  preferFastForward() {
    throw new Error('Not allowed on the public view')
  }

  interrupt() {
    throw new Error('Not allowed on the public view')
  }

  removeable() {
    throw new Error('Not allowed on the public view')
  }

  fork() {
    throw new Error('Not allowed on the public view')
  }

  anchor() {
    throw new Error('Not allowed on the public view')
  }
}

class PrivateApplyCalls extends PublicApplyCalls {
  constructor(state) {
    super(state.base)
    this.state = state
    this.internal = true
  }

  get system() {
    return this.state.system
  }

  async addWriter(key, { indexer = true, isIndexer = indexer } = {}) {
    // just compat for old version
    await this.state.system.add(key, { isIndexer })
    await this.base._addWriter(key, this.state.system)
  }

  async ackWriter(key) {
    await this.state.system.ack(key)
  }

  async removeWriter(key) {
    // just compat for old version
    if (!this.state.removeable(key)) {
      throw new Error('Not allowed to remove the last indexer')
    }

    await this.state.system.remove(key)
    this.base._removeWriter(key)
  }

  preferFastForward() {
    this.base._preferFastForward()
  }

  interrupt(reason) {
    this.base._interrupt(reason)
  }

  removeable(key) {
    return this.state.removeable(key)
  }

  async fork(indexerKeys, system) {
    if (!(await this.state.validateFork(indexerKeys, system))) return false

    const indexers = indexerKeys.map(toIndexer)

    this.state.pendingFork = { indexers, length: system.length }

    return true
  }

  async createAnchor() {
    return await this.state.createAnchor()
  }
}

module.exports = { PublicApplyCalls, PrivateApplyCalls }

function toIndexer(key) {
  return { key, length: 0 } // length is not used, just for api compat
}
const ReadyResource = require('ready-resource')
const assert = require('nanoassert')
const c = require('compact-encoding')
const crypto = require('hypercore-crypto')
const b4a = require('b4a')
const safetyCatch = require('safety-catch')
const Hypercore = require('hypercore')

const { partialSignature } = require('hypercore/lib/multisig.js')

const SystemView = require('./system.js')
const { AutobaseEncryption, EncryptionView } = require('./encryption.js')
const UpdateChanges = require('./updates.js')
const messages = require('./messages.js')
const { PrivateApplyCalls } = require('./apply-calls.js')
const { encodeValue } = require('./values.js')
const Fork = require('./fork.js')
const LocalState = require('./local-state.js')
const { OPLOG_VERSION, BOOT_RECORD_VERSION } = require('./caps.js')

// todo: expose this as an option
const SHOULD_SIGN_THRESHOLD = 0

class CheckpointCore {
  constructor(view, core, signer, paused) {
    this.view = view
    this.core = core
    this.signer = signer
    this.length = 0
    this.digest = null
    this.signatures = { system: null, encryption: null, user: [] }
    this.closed = false
    this.paused = paused
  }

  pause() {
    this.paused = true
  }

  resume() {
    if (!this.paused) return
    this.paused = false
    this.updateBackground()
  }

  async update() {
    if (await this.updateCheckpoints()) await this.view.maybeSigned()
  }

  async updateCheckpoints() {
    if (this.core.length <= this.length || this.closed || this.paused) return false

    const length = this.core.length
    const value = await this.core.get(length - 1)

    if (length <= this.length || this.closed || !value.digest || this.paused) return false

    const [digest, checkpoints] = await Promise.all([
      this._inflateDigest(length, value.digest),
      this._inflateAllCheckpoints(length, value.checkpoint)
    ])

    if (length <= this.length || this.closed || !digest || !checkpoints || this.paused) return false
    for (let i = 0; i < checkpoints.length; i++) {
      if (checkpoints[i] === null) return false
    }

    this.length = length
    this.digest = digest
    this.signatures = checkpoints

    return true
  }

  updateBackground() {
    return this.update().catch(safetyCatch)
  }

  updateInternalSignatures(length, signatures) {
    this.signatures.system = updateSignature(length, signatures.system, this.signatures.system)
    this.signatures.encryption = updateSignature(
      length,
      signatures.encryption,
      this.signatures.encryption
    )
  }

  updateUserSignatures(length, signatures) {
    this.signatures.user = updateSignatures(length, signatures, this.signatures.user)
  }

  makeCheckpoints(length) {
    return {
      system: makeCheckpoint(length, this.signatures.system),
      encryption: makeCheckpoint(length, this.signatures.encryption),
      user: makeCheckpoints(length, this.signatures.user)
    }
  }

  makeDigest(length, key) {
    if (this.digest && (this.digest.key === key || b4a.equals(this.digest.key, key))) {
      return { key: null, pointer: length - this.digest.at }
    }
    this.digest = { key, at: length }
    return { key, pointer: 0 }
  }

  async ready() {
    await this.core.ready()
    this.core.on('append', this.updateBackground.bind(this))
    if (this.core.writable) await this.updateCheckpoints()
    this.updateBackground()
  }

  signedLength() {
    return this.signatures.system ? this.signatures.system.length : 0
  }

  close() {
    this.closed = true
    return this.core.close()
  }

  async _inflateDigest(length, dig) {
    if (!dig) return null

    if (dig.pointer === 0) {
      return { key: dig.key, at: length }
    }

    const len = length - dig.pointer

    if (this.digest && len === this.digest.at) return this.digest
    if (len <= 0) return null

    const { digest } = await this.core.get(len - 1)
    if (!digest || !digest.key) return null

    return { key: digest.key, at: len }
  }

  _sameSignatures(b, a) {
    return (
      sameSignature(a.system, b.system) &&
      sameSignature(a.encryption, b.encryption) &&
      sameSignatures(a.user, b.user)
    )
  }

  async _inflateAllCheckpoints(length, checkpoints) {
    if (!checkpoints) return { system: null, encryption: null, user: [] }
    if (this._sameSignatures(checkpoints, this.signatures)) return this.signatures

    const system = this._inflateSystemCheckpoint(checkpoints.system, length)
    const encryption = this._inflateEncryptionCheckpoint(checkpoints.encryption, length)

    const user = checkpoints.user ? new Array(checkpoints.user.length) : []

    for (let i = 0; i < user.length; i++) {
      const chk = checkpoints.user[i]
      user[i] = this._inflateUserCheckpoint(chk, i, length)
    }

    const [systemCheckpoint, encryptionCheckpoint, userCheckpoints] = await Promise.all([
      system,
      encryption,
      Promise.all(user)
    ])

    return {
      system: systemCheckpoint,
      encryption: encryptionCheckpoint,
      user: userCheckpoints
    }
  }

  async _inflateSystemCheckpoint(chk, coreLength) {
    if (chk.checkpoint) {
      const { signature, length } = chk.checkpoint
      return { signature, length, at: coreLength }
    }

    const len = coreLength - chk.checkpointer
    if (this.signatures.system && this.signatures.system.at === len) {
      return this.signatures.system
    }

    if (len <= 0) return null

    const { checkpoint } = await this.core.get(len - 1)
    if (!checkpoint || !checkpoint.system || !checkpoint.system.checkpoint) return null

    const { signature, length } = checkpoint.system.checkpoint
    return { signature, length, at: len }
  }

  async _inflateEncryptionCheckpoint(chk, coreLength) {
    if (!chk) return { length: 0, signature: null, at: 0 }

    if (chk.checkpoint) {
      const { signature, length } = chk.checkpoint
      return { signature, length, at: coreLength }
    }

    const len = coreLength - chk.checkpointer
    if (this.signatures.encryption && this.signatures.encryption.at === len) {
      return this.signatures.encryption
    }

    if (len <= 0) return null

    const { checkpoint } = await this.core.get(len - 1)
    if (!checkpoint || !checkpoint.encryption || !checkpoint.encryption.checkpoint) return null

    const { signature, length } = checkpoint.encryption.checkpoint
    return { signature, length, at: len }
  }

  async _inflateUserCheckpoint(chk, i, coreLength) {
    if (chk.checkpoint) {
      const { signature, length } = chk.checkpoint
      return { signature, length, at: coreLength }
    }

    const len = coreLength - chk.checkpointer
    if (i < this.signatures.user.length && this.signatures.user[i].at === len) {
      return this.signatures.user[i]
    }

    if (len <= 0) return null

    const { checkpoint } = await this.core.get(len - 1)
    if (!checkpoint || i >= checkpoint.user.length || !checkpoint.user[i].checkpoint) return null

    const { signature, length } = checkpoint.user[i].checkpoint
    return { signature, length, at: len }
  }
}

module.exports = class ApplyState extends ReadyResource {
  constructor(base) {
    super()

    this.base = base
    this.encryption = this.base.encryption
    this.valueEncoding = base.valueEncoding
    this.store = base._viewStore.atomize()
    this.key = null
    this.system = null
    this.view = null
    this.views = []
    this.systemView = null
    this.encryptionView = null
    this.hostcalls = null
    this.changes = base._hasUpdate ? new UpdateChanges(base) : null

    this.updates = []

    this.local = null
    this.localState = null

    this.fastForwarding = false
    this.indexersUpdated = false
    this.quorum = 0
    this.needsIndexedLengthUpdate = false
    this.interrupted = false
    this.applying = null
    this.applyBatch = null

    this.localCheckpoint = null
    this.localIndexer = false

    this.systemUpgrade = null

    this.checkpoints = []
    this.pendingViews = null
    this.pendingFork = null
    this.dirty = false
  }

  shouldFlush() {
    return this.dirty
  }

  async shouldWrite() {
    if (!this.localIndexer || !this.localCheckpoint || !this.localCheckpoint.core.opened) {
      return false
    }

    const info = await this.system.getIndexedInfo(this.indexedLength)
    if (!info.views.length) return false

    const { encryption, user } = this.localCheckpoint.signatures

    // todo: does this condition hold for soft-fork?
    if (info.views.length > user.length) return true

    for (let i = 0; i < info.views.length; i++) {
      if (user[i].length + SHOULD_SIGN_THRESHOLD < info.views[i].length) return true
    }

    // always flush encryption signature
    if (info.encryptionLength !== 0) {
      if (!encryption || encryption.length < info.encryptionLength) return true
    }

    return false
  }

  get indexedLength() {
    return this.systemView ? this.systemView.indexedLength : 0
  }

  get systemRef() {
    return this.systemView ? this.systemView.ref : null
  }

  async validateFork(indexerKeys, system) {
    if (!b4a.equals(system.key, this.system.core.key)) return false
    if (this.pendingIndexedLength() < system.length) return false
    for (const key of indexerKeys) {
      const info = await this.system.get(key)

      // writer should be active and we need manifest
      if (!info || !info.length || info.isRemoved) return false
    }
    return true
  }

  async shouldMigrate() {
    if (!this.fastForwarding && !this.indexersUpdated) return false
    if (this.system.indexers.length === 0) return false // genesis

    // sanity, prefer migration
    if (!this.system.core.manifest || !this.system.core.manifest.signers) return true

    // easy mode
    if (this.system.indexers.length !== this.system.core.manifest.signers.length) {
      return true
    }

    const manifests = await this.store.getIndexerManifests(this.system.indexers)

    for (let i = 0; i < this.system.core.manifest.signers.length; i++) {
      const { publicKey } = this.system.core.manifest.signers[i]
      if (!b4a.equals(publicKey, manifests[i].signers[0].publicKey)) return true
    }

    return false
  }

  isLocalPendingIndexer() {
    if (this.system.pendingIndexers.length === 0) return false
    const key = this.base.local.key
    for (const k of this.system.pendingIndexers) {
      if (b4a.equals(k, key)) return !b4a.equals(this.base.key, key) && this.base.local.length === 0
    }
    return false
  }

  removeable(key) {
    if (this.system.indexers.length !== 1) return true
    return !b4a.equals(this.system.indexers[0].key, key)
  }

  isLocalIndexer() {
    return !!this.localCheckpoint
  }

  _createCheckpointCore(key, active, signer, paused) {
    const encryption = this.base.getWriterEncryption(key)

    const session = this.base.store.get({
      key,
      valueEncoding: messages.OplogMessage,
      encryption,
      active
    })

    return new CheckpointCore(this, session, signer, paused)
  }

  async _openInternalView(name, indexedLength) {
    const core = this.store.get({ name })
    await core.ready()
    await core.setUserData('referrer', this.base.key)
    await core.setUserData('autobase/view', b4a.from(name))

    const ref = this.store.getViewByName(name)

    return { ref, core, indexedLength }
  }

  async _open() {
    try {
      await this._boot()
    } catch (err) {
      if (isViewCorruption(err)) {
        for (const v of this.store.opened) {
          await v.core.ready()
          await v.core.state.storage.deleteSessions()
        }
        if (this.systemView) {
          const core = this.systemView.ref.core
          await core.ready()
          await core.state.storage.deleteSessions()
        }
        if (this.encryptionView) {
          const core = this.encryptionView.ref.core
          await core.ready()
          await core.state.storage.deleteSessions()
        }

        await LocalState.clear(this.base.local)
      }

      await this._free()
      throw err
    }
  }

  async _boot() {
    const boot = await this.base._getBootRecord()

    this.systemView = await this._openInternalView('_system', boot.systemLength)
    this.encryptionView = await this._openInternalView('_encryption', -1)

    const sysCore = this.systemView.core
    if (sysCore.manifest.version >= 2) {
      if (this.encryption !== null) await this.encryption.reload(this.encryptionView.core)
    }

    const system = new SystemView(sysCore)
    await system.ready()

    // reset so we dont track _system or _encryption
    this.store.opened = []

    this.hostcalls = new PrivateApplyCalls(this)
    const view = this.base._hasOpen ? this.base._handlers.open(this.store, this.hostcalls) : null

    this.view = view
    this.system = system

    // ensure all are ready
    for (const v of this.store.opened) await v.atomicBatch.ready()

    this.key = system.core.key

    this.fastForwarding = boot.fastForwarding
    this.indexersUpdated = boot.indexersUpdated
    this.quorum = sysCore.manifest ? sysCore.manifest.quorum : 0

    const added = new Set()

    for (let i = 0; i < system.views.length; i++) {
      const { key, length } = system.views[i]
      const v = await this.store.findViewByKey(
        key,
        system.indexers,
        sysCore.manifest.version,
        system.entropy
      )

      if (v === null) {
        this.views.push({ name: null, key, length, core: null, ref: null, mappedIndex: i })
        continue
      }

      await v.atomicBatch.ready()
      await v.core.setUserData('referrer', this.base.key)
      await v.core.setUserData('autobase/view', b4a.from(v.name))

      this.views.push({ name: v.name, key, length, core: v.atomicBatch, ref: v, mappedIndex: i })

      added.add(v)
    }

    for (const v of this.store.opened) {
      if (added.has(v)) continue
      const core = v.atomicBatch

      this.views.push({
        name: v.name,
        key: core.key,
        length: core.length,
        core,
        ref: v,
        mappedIndex: -1
      })
    }

    this.local = this.store.getLocal()
    await this.local.ready()

    this.localState = new LocalState(this.local)

    let isLocalIndexer = false

    const paused = this.base.isFastForwarding()
    const inf = await this.system.getIndexedInfo()

    for (let i = 0; i < inf.indexers.length; i++) {
      const idx = inf.indexers[i]
      const chk = this._createCheckpointCore(idx.key, true, i, paused)
      await chk.ready()
      this.checkpoints.push(chk)
      if (b4a.equals(idx.key, this.base.local.key)) isLocalIndexer = true
    }

    const shouldSign = this.quorum > 0 && isLocalIndexer

    if (shouldSign) {
      this.localIndexer = true
      await this._startLocalCheckpoint()
    }

    await this._refreshWriters()

    // deferred
    this.maybeSigned().catch(noop)
  }

  async _startLocalCheckpoint() {
    for (const chk of this.checkpoints) {
      if (chk.core.id === this.base.local.id) {
        this.localCheckpoint = chk
        return
      }
    }

    this.localCheckpoint = this._createCheckpointCore(this.base.local.key, false, 0, false)
    await this.localCheckpoint.ready()
  }

  interrupt() {
    this.interrupted = true
    this.pause()
  }

  pause() {
    for (const chk of this.checkpoints) {
      if (chk !== this.localCheckpoint) chk.pause()
    }
  }

  resume() {
    for (const chk of this.checkpoints) {
      if (chk !== this.localCheckpoint) chk.resume()
    }
  }

  _checkSystemUpgrade() {
    if (this.systemUpgrade) return

    const tally = new Map()

    for (const chk of this.checkpoints) {
      if (chk.signedLength() <= this.system.core.signedLength) continue
      if (!chk.digest) continue

      const id = b4a.toString(chk.digest.key, 'hex')
      const cnt = (tally.get(id) || 0) + 1

      if (cnt >= this.quorum) {
        this.systemUpgrade = chk.digest.key
        this.base._queueStaticFastForward(this.systemUpgrade)
        return
      }

      tally.set(id, cnt)
    }
  }

  mapIndexToView(index) {
    for (const { mappedIndex, ref } of this.views) {
      if (mappedIndex === index) return ref
    }
  }

  async maybeSigned() {
    if (this.opened === false) await this.ready()
    if (this.interrupted) return

    const thres = this.checkpoints.length - this.quorum
    if (thres < 0 || this.checkpoints.length <= thres) return

    this.checkpoints.sort(cmpCheckpoints)

    const signableLength = this.checkpoints[thres].signedLength()
    if (signableLength <= this.system.core.signedLength) return

    const expected = this.system.core.key

    if (signableLength > this.indexedLength) {
      if (!b4a.equals(expected, this.checkpoints[thres].digest.key)) this._checkSystemUpgrade()
      this.needsIndexedLengthUpdate = true
      return
    }

    for (let i = thres; i < this.checkpoints.length; i++) {
      const chk = this.checkpoints[i]
      // we must agree on what the system is obvs
      if (!b4a.equals(expected, chk.digest.key)) {
        this._checkSystemUpgrade()
        return
      }
      // if we dont have the indexed state ourself, then no way for us to verify / patch
      if (!chk.signatures.system || chk.signatures.system.length > this.indexedLength) {
        this.needsIndexedLengthUpdate = true
        return
      }
    }

    this.needsIndexedLengthUpdate = false

    const chk = []
    for (let i = thres; i < this.checkpoints.length; i++) {
      chk.push({ signer: this.checkpoints[i].signer, signatures: this.checkpoints[i].signatures })
    }

    const { system } = this.checkpoints[thres].signatures

    await this._assembleMultisig(system.length, chk)
  }

  async _assembleMultisig(signableLength, checkpoints) {
    const views = new Array(this.views.length + 2) // +2 is system + encryption

    const sys = await this.system.getIndexedInfo(signableLength)

    if (this.interrupted) return

    if (this.pendingViews && this.pendingViews[0].length >= signableLength) {
      return
    }

    views[0] = createCheckpointSignature(signableLength, this.systemView, checkpoints.length)

    if (sys.encryptionLength) {
      views[1] = createCheckpointSignature(
        sys.encryptionLength,
        this.encryptionView,
        checkpoints.length
      )
    }

    const offset = 2 // system + encryption

    for (let i = offset; i < views.length; i++) {
      const view = this.views[i - offset]
      const core = view.core

      const v = this.getViewFromSystem(view, sys)
      const length = v ? v.length : 0

      if (!core || length <= core.signedLength) continue

      const viewIndex = view.mappedIndex + offset
      views[viewIndex] = createCheckpointSignature(length, view, checkpoints.length)
    }

    for (let i = 0; i < checkpoints.length; i++) {
      addCheckpointSignatures(views, checkpoints, i)
    }

    const promises = []
    for (const view of views) {
      if (!view) continue

      for (let i = 0; i < view.signatures.length; i++) {
        promises.push(setPartialSignature(view, i))
      }
    }

    await Promise.all(promises)

    // check that the state still looks good, couple replicate inbetween...
    for (const v of views) {
      if (!v) continue

      for (let i = 0; i < v.signatures.length; i++) {
        if (!v.partials[i]) return
      }
    }

    if (this.interrupted) return

    if (this.pendingViews && this.pendingViews[0].length >= signableLength) {
      return
    }
    // skipped system for whatever reason...
    if (!views[0]) return

    this.pendingViews = views
    this.dirty = true

    // TODO: only needed if not updating, wont crash so keeping for now, just less efficient
    this.base._queueBump()
  }

  _close() {
    if (this.interrupted) return
    return this._free()
  }

  async _free() {
    this.interrupted = true
    if (this.applying) this._postApply()
    for (const chk of this.checkpoints) await chk.close()
    if (this.localCheckpoint) await this.localCheckpoint.close()
    if (this.view && this.base._hasClose) await this.base._handlers.close(this.view)
    if (this.system) await this.system.close()

    const promises = []
    for (const v of this.views) {
      if (v.ref) promises.push(v.ref.release())
    }

    if (this.systemView) promises.push(this.systemView.ref.release())
    if (this.encryptionView) promises.push(this.encryptionView.ref.release())

    await Promise.all(promises)
    await this.store.close()
  }

  _pushUpdate(u) {
    u.version = 1
    u.seq = this.updates.length === 0 ? 0 : this.updates[this.updates.length - 1].seq + 1
    u.systemLength = this.systemView.core.length
    this.updates.push(u)
    this.localState.insertUpdate(u)
  }

  async catchup(linearizer) {
    if (!this.opened) await this.ready()
    if (!this.system.heads.length) return true

    const writers = new Map()

    // load linearizer...
    const updates = await this.localState.listUpdates()
    const sys = await this.system.checkout(this.indexedLength)

    for (const node of updates) {
      const hex = b4a.toString(node.key, 'hex')

      let w = writers.get(hex)

      if (w === undefined) {
        // TODO: we actually have all the writer info already but our current methods make it hard to reuse that
        w = await this.base._getWriterByKey(node.key, -1, 0, true, false, sys)
        writers.set(hex, w)
      }

      if (w.length >= node.length) {
        this.base._warn(new Error('Update expects writer to be consumed here'))
        return false
      }

      while (w.length < node.length) {
        await w.update(sys)

        const next = w.advance()
        if (!next) {
          this.base._warn(new Error('Node must exist for catchup'))
          return false
        }

        linearizer.addHead(next)
      }
    }

    await sys.close()

    this.updates = updates

    if (this.indexersUpdated) {
      this.indexersUpdated = false
      // if we updated the indexers, invalidate all the internal state and reapply it
      await this.truncate(this.indexedLength)
      await this._rollbackViews()

      if (this.tx === null) this.tx = this.local.state.storage.write()

      while (
        this.updates.length > 0 &&
        this.updates[this.updates.length - 1].systemLength >= this.indexedLength
      ) {
        const u = this.updates.pop()
        this.localState.deleteUpdate(u)
      }
    } else {
      // otherwise we know the internal state is correct, so we carry on
      linearizer.update()
    }

    // must refresh the writers here so isRemoved is up to date
    await this._refreshWriters()
    return true
  }

  async getIndexedSystem() {
    if (this.opened === false) await this.ready()

    const indexedLength = this.pendingFork ? this.pendingFork.length : this.indexedLength

    const sys = await this.system.checkout(indexedLength)
    await sys.ready()
    return sys
  }

  getViewFromSystem(view, sys = this.system) {
    if (view.mappedIndex === -1 || view.mappedIndex >= sys.views.length) return null
    return sys.views[view.mappedIndex]
  }

  async recoverAt() {
    if (!this.systemRef) await this.ready()

    await this.systemRef.core.ready()

    const lt = this.systemRef.core.core.state.length

    for await (const { length, info } of SystemView.flushes(this.systemRef.core.session(), {
      reverse: true,
      lt
    })) {
      let consistent = true

      for (let i = 0; i < info.views.length; i++) {
        if (i >= this.views.length) continue
        if (!b4a.equals(info.views[i].key, this.views[i].key)) continue

        if (info.views[i].length > this.views[i].core.core.state.length) {
          consistent = false
          break
        }
      }

      if (consistent) {
        return {
          length,
          force: true,
          key: this.system.core.key,
          indexers: info.indexers,
          views: info.views
        }
      }
    }

    return null
  }

  bootstrap() {
    return this.system.add(this.base.key, { isIndexer: true, isPending: false })
  }

  async undo(popped) {
    if (!popped) return

    let indexersUpdated = false
    while (popped > 0) {
      const u = this.updates.pop()
      this.localState.deleteUpdate(u)
      popped -= u.batch
      if (u.indexers) indexersUpdated = true
    }

    const u = this.updates.length === 0 ? null : this.updates[this.updates.length - 1]
    const systemLength = u ? u.systemLength : this.indexedLength

    await this.truncate(systemLength)
    if (indexersUpdated) await this._rollbackViews()
  }

  async truncate(systemLength) {
    if (this.opened === false) await this.ready()
    if (systemLength === this.system.core.length) return

    await this.system.core.truncate(systemLength)

    const migrated = await this.system.update()

    if (this.encryptionView.core.length !== this.system.encryptionLength) {
      await this.encryptionView.core.truncate(this.system.encryptionLength)
    }

    for (const view of this.views) {
      if (!view.core) continue

      const v = this.getViewFromSystem(view)

      if (v && view.core.length === v.length) continue
      if (v === null) view.mappedIndex = -1 // unmap

      await view.core.truncate(v ? v.length : 0)
    }

    if (!migrated) return

    await this._refreshWriters()
    await this._rollbackViews()
  }

  async _refreshWriters() {
    // TODO: add the seq at which we updated the state to the writer instance.
    // then we know if it was truncated out without the lookup, meaning faster truncations
    for (const w of this.base.activeWriters) {
      const data = await this.system.get(w.core.key)
      const bootstrapper = this.system.core.length === 0 && b4a.equals(w.core.key, this.base.key)
      const isRemoved = data ? data.isRemoved : !bootstrapper
      w.isRemoved = isRemoved
    }
  }

  async _updateSystem() {
    if (!(await this.system.update())) return
    await this._refreshWriters()
    await this._rollbackViews()
  }

  async _signViewCore(core, length) {
    const s = await core.signable(length, 0)
    const signature = crypto.sign(s, this.base.local.keyPair.secretKey)
    return { signature, length }
  }

  async _signInternalViewCores(sys) {
    return {
      system: await this._signViewCore(this.systemView.core, this.systemView.indexedLength),
      encryption: await this._signViewCore(this.encryptionView.core, sys.encryptionLength)
    }
  }

  async _signUserViewCores(sys) {
    const promises = new Array(sys.views.length)

    for (let i = 0; i < this.views.length; i++) {
      const view = this.views[i]

      const v = this.getViewFromSystem(view, sys)
      const indexedLength = v ? v.length : 0

      if (!indexedLength) continue

      const viewIndex = view.mappedIndex
      promises[viewIndex] = this._signViewCore(view.ref.atomicBatch, indexedLength)
    }

    return Promise.all(promises)
  }

  async finalize(key) {
    this.localState.setBootRecord({
      version: BOOT_RECORD_VERSION,
      key,
      systemLength: this.systemView.indexedLength,
      indexersUpdated: true,
      fastForwarding: false,
      recoveries: this.base.recoveries
    })

    await this.localState.flush()

    await this.store.flush()
    await this.close()
  }

  async _flush(localNodes) {
    if (localNodes) await this._appendLocalNodes(localNodes)

    if (this.localCheckpoint) {
      // we have to flush here so the chkpoint can update
      // could run the checkpoint on the batch but also no big dead
      // as the "should we sign" check is rerun on boot...
      await this.store.flush()
      await this.localCheckpoint.update()
    }

    this.localState.setBootRecord({
      version: BOOT_RECORD_VERSION,
      key: this.key,
      systemLength: this.systemView.indexedLength,
      indexersUpdated: false,
      fastForwarding: false,
      recoveries: this.base.recoveries
    })

    await this.localState.flush()

    if (this.pendingViews) {
      const views = this.pendingViews
      this.pendingViews = null

      for (let i = views.length - 1; i >= 0; i--) {
        const v = views[i]
        if (!v || v.length <= v.core.signedLength) continue
        const signature = v.core.core.verifier.assemble(v.partials)
        try {
          await v.ref.commit(this.store.atom, v.length, signature)
        } catch (err) {
          if (isAssertion(err)) {
            throw err
          }

          // TODO: we should prevalidate all signatures instead of during commit so it can be all or nothing, just slighly
          // friendlier ux. missing hc api for that
          if (!this.base.closing) this.base._warn(err)
          break
        }
      }
    }

    await this.store.flush()

    this.fastForwarding = false
    if (this.pendingViews === null) this.dirty = false
  }

  _indexUpdates(indexed) {
    let shift = 0
    while (indexed > 0) indexed -= this.updates[shift++].batch

    const last = this.updates[shift - 1]

    this.systemView.indexedLength = last.systemLength

    for (let i = 0; i < shift; i++) this.localState.deleteUpdate(this.updates[i])
    this.updates.splice(0, shift)

    if (!this.needsIndexedLengthUpdate) return
    this.maybeSigned().catch(noop)
  }

  pendingIndexedLength() {
    let indexed = this.applying.indexed.length
    if (!this.applying || !this.updates.length || !indexed) return this.indexedLength

    let pos = 0
    while (indexed > 0 && pos < this.updates.length) {
      indexed -= this.updates[pos++].batch
    }

    const last = this.updates[pos - 1]
    return last.systemLength
  }

  async _assertNode(node, batch) {
    // helpful dag helper, so kept here

    const v = (await this.system.get(node.writer.core.key)) || { length: 0, isRemoved: false }
    const expected = v.length + batch
    if (node.length === expected) return

    console.trace(
      'INVALID_INSERTION',
      'length=',
      node.length,
      'key=',
      node.writer.core.key,
      'local=',
      node.writer.core.writable,
      'batch=',
      batch,
      'dag=',
      v
    )

    process.exit(1)
  }

  _postApply() {
    this.applyBatch = this.applying = null
    this.base._postApply()
  }

  async _optimisticApply(u, node, indexed) {
    const checkpoint = this.system.checkpoint()

    this.system.addHead(node)

    const applyBatch = []
    const key = node.writer.core.key

    applyBatch.push({
      indexed,
      optimistic: true,
      from: node.writer.core,
      length: node.length,
      value: node.value,
      heads: node.actualHeads
    })

    const pre = await this.system.get(key)
    const preLength = pre ? pre.length : 0

    let failed = false

    this.applying = u
    this.applyBatch = applyBatch
    try {
      await this.base._handlers.apply(applyBatch, this.view, this.hostcalls)
    } catch (err) {
      if (this.base.closing) throw err
      failed = true
    }
    this._postApply()

    if (!failed) {
      const post = await this.system.get(key)
      // check if acked by addWriter/removeWriter/ackWriter
      if (!post || preLength === post.length) failed = true
    }

    if (!failed) {
      // technically we only need to to this is the writer was removed, but hey, tricky logic
      await this._refreshWriters()
      return true
    }

    // it failed! rollback...

    this.system.applyCheckpoint(checkpoint)

    if (this.encryptionView.core.length !== this.system.encryptionLength) {
      await this.encryptionView.core.truncate(this.system.encryptionLength)
    }

    for (const view of this.views) {
      const viewLength = view.core ? view.core.length : view.length
      const viewLookup = this.getViewFromSystem(view)
      const viewSystemLength = viewLookup ? viewLookup.length : 0
      if (viewSystemLength === viewLength) continue
      await view.core.truncate(viewSystemLength)
    }

    await this._refreshWriters()

    await this._rollbackViews()
    return false
  }

  _startTrace(node) {
    this.systemRef.tracer.start()
    this.encryptionView.ref.tracer.start()
    for (let i = 0; i < this.views.length; i++) this.views[i].ref.tracer.start()
  }

  _endTrace(node) {
    const trace = {
      system: this.systemRef.tracer.end(),
      encryption: this.encryptionView.ref.tracer.end(),
      user: []
    }

    for (let i = 0; i < this.views.length; i++) {
      const blocks = this.views[i].ref.tracer.end()
      if (blocks.length) trace.user.push({ view: i, blocks })
    }

    if (trace.system.length || trace.encryption.length || trace.user.length) node.trace = trace
  }

  async update(u, localNodes) {
    if (this.changes !== null) this.changes.track(this)

    let batch = 0
    let applyBatch = []
    let indexersUpdated = 0

    let j = 0
    let i = 0
    let forkedAt = -1

    while (i < Math.min(u.indexed.length, u.shared)) {
      const node = u.indexed[i++]

      if (node.batch > 1) continue
      this.base._shiftWriter(node.writer)

      const update = this.updates[j++]

      if (update.indexers) {
        indexersUpdated = i
        break
      }
    }

    if (u.undo) await this.undo(u.undo)

    if (this.system.bootstrapping) await this.bootstrap()

    await this._updateSystem()

    // Organize by view
    const warmupSystemView = []
    const warmupEncryptionView = []
    const warmupUserView = new Array(this.views.length)

    for (let k = u.shared; k < u.length; k++) {
      const indexed = k < u.indexed.length
      const node = indexed ? u.indexed[k] : u.tip[k - u.indexed.length]
      if (!node.trace) continue

      if (node.trace.system.length) warmupSystemView.push(...node.trace.system)
      if (node.trace.encryption.length) warmupEncryptionView.push(...node.trace.encryption)

      for (const trace of node.trace.user) {
        // Assert (as warning) that trace view should only be currently indexed views
        if (trace.view >= this.views.length) {
          console.warn(
            'Oplog block trace contains OOB view index',
            'trace view',
            trace.view,
            'views.length',
            this.views.length
          )
          continue
        }

        warmupUserView[trace.view] = warmupUserView[trace.view] || []
        warmupUserView[trace.view].push(...trace.blocks)
      }
    }

    // Request per view
    if (warmupSystemView.length) this.systemView.core.download({ blocks: warmupSystemView })
    if (warmupEncryptionView.length)
      this.encryptionView.core.download({ blocks: warmupEncryptionView })
    for (let k = 0; k < warmupUserView.length; k++) {
      const blocks = warmupUserView[k]
      if (!blocks) continue

      const view = this.views[k]
      view.core.download({ blocks })
    }

    for (i = u.shared; i < u.length; i++) {
      if (this.base.backoff !== null && this.base.backoff.backoff()) await this.base.backoff.wait()

      const indexed = i < u.indexed.length
      const node = indexed ? u.indexed[i] : u.tip[i - u.indexed.length]

      batch++

      if (node.writer.core.writable) this._startTrace(node)

      const optimist =
        node.writer.isRemoved &&
        node.optimistic &&
        batch === 1 &&
        this.base._hasOptimisticApply === true &&
        (await this._optimisticApply(u, node, indexed))

      if (!optimist) {
        if (node.writer.isRemoved && !node.writer.isActiveIndexer) {
          if (node.batch > 1) continue
          // in case someone is linking this node and they are not removed
          const u = {
            seq: 0,
            key: node.writer.core.key,
            length: node.length,
            batch,
            systemLength: 0,
            indexers: false
          }
          this._pushUpdate(u)
          batch = 0
          assert(applyBatch.length === 0, 'Apply batch should not have been modified')
          continue
        }

        // in prod we prop need to disable this assertion as its pretty expensive,
        // but it catches a lot of bugs, so here for debugs
        // await this._assertNode(node, batch)

        const deps = node.causalDependencies()

        // oldest -> newest
        for (let i = deps.length - 1; i >= 1; i--) {
          const d = deps[i]
          if (await this.system.linkable(d.writer.core.key, d.length)) {
            this.system.addHead(deps[i])
          }
        }

        this.system.addHead(deps[0])

        if (node.value !== null && !node.writer.isRemoved) {
          applyBatch.push({
            indexed,
            optimistic: false,
            from: node.writer.core,
            length: node.length,
            value: node.value,
            heads: node.actualHeads
          })
        }

        if (node.batch > 1) continue

        if (applyBatch.length && this.base._hasApply === true) {
          this.applying = u
          this.applyBatch = applyBatch
          await this.base._handlers.apply(applyBatch, this.view, this.hostcalls)
          if (forkedAt === -1 && this.pendingFork) forkedAt = i
          this._postApply()
        }
      }

      const update = {
        seq: 0,
        key: node.writer.core.key,
        length: node.length,
        batch,
        systemLength: 0,
        indexers: false
      }

      update.indexers = !!this.system.indexerUpdate

      if (this.system.indexerUpdate) await this._generateNextViews()

      await this.system.flush(this.views)
      await this.system.update()

      if (node.writer.core.writable) this._endTrace(node)

      batch = 0
      applyBatch = []

      this._pushUpdate(update)

      if (!indexed || indexersUpdated) continue

      this.base._shiftWriter(node.writer)

      if (update.indexers) {
        indexersUpdated = i + 1
      }
    }

    if (this.pendingFork) {
      const pending = this.pendingFork
      if (pending.length > this.indexedLength) this._indexUpdates(u.indexed.length)

      const fork = new Fork(this.base, this.store, this, pending)
      const forked = await fork.upgrade()

      if (!forked) throw new Error('Fork failed')

      await this._flush(localNodes)

      return {
        reboot: true,
        migrated: false
      }
    }

    if (u.indexed.length) {
      this._indexUpdates(indexersUpdated || u.indexed.length)
    }

    const migrated = indexersUpdated !== 0
    if (migrated) this.key = await this.base._premigrate()

    if (this.changes !== null) {
      this.changes.finalise()
      await this.base._handlers.update(this.view, this.changes)
    }

    await this._flush(localNodes)

    return {
      reboot: migrated,
      migrated
    }
  }

  flush() {
    return this._flush(null)
  }

  async _appendLocalNodes(localNodes) {
    if (localNodes.length === 0) return // just in case

    const blocks = new Array(localNodes.length)
    const local = this.local

    if (!local.opened) await local.ready()

    for (let i = 0; i < blocks.length; i++) {
      const { value, heads, batch, optimistic, trace } = localNodes[i]

      blocks[i] = {
        version: OPLOG_VERSION,
        maxSupportedVersion: this.base.maxSupportedVersion,
        checkpoint: null,
        digest: null,
        optimistic,
        node: {
          heads,
          batch,
          value: value === null ? null : c.encode(this.base.valueEncoding, value)
        },
        trace
      }
    }

    if (this.localIndexer) {
      const signedLength = this.localCheckpoint.signedLength()
      const local = this.local

      let signedAt = 0
      let internalSignatures = null
      let signatures = null

      if (this.indexedLength > signedLength) {
        const sys = await this.system.getIndexedInfo(this.indexedLength)
        internalSignatures = await this._signInternalViewCores(sys)
        signatures = await this._signUserViewCores(sys)
        signedAt = local.length + blocks.length
      }

      for (let i = 0; i < blocks.length; i++) {
        const length = local.length + i + 1
        if (length === signedAt) {
          this.localCheckpoint.updateInternalSignatures(length, internalSignatures)
          this.localCheckpoint.updateUserSignatures(length, signatures)
        }

        const blk = blocks[i]

        blk.checkpoint = this.localCheckpoint.makeCheckpoints(length)
        blk.digest = this.localCheckpoint.makeDigest(length, this.key)
      }
    } else {
      if (!this.localCheckpoint) await this._startLocalCheckpoint()

      for (let i = 0; i < blocks.length; i++) {
        const length = local.length + i + 1
        blocks[i].digest = this.localCheckpoint.makeDigest(length, this.key)
      }
    }

    await local.append(blocks)
  }

  async _rollbackViews() {
    // encryption view key is not in system so no need to handle here
    for (const view of this.views) {
      const v = this.getViewFromSystem(view)

      if (v) {
        view.key = v.key
      } else {
        await this._resetView(view)
      }
    }
  }

  async createAnchor() {
    const node = this.applyBatch[this.applyBatch.length - 1]
    const key = node.from.key
    const length = node.length

    const info = await this.system.get(key, { unflushed: true })

    if (!info || info.length < length) throw new Error('Anchor node is not in system')

    const state = { start: 0, end: 40, buffer: b4a.alloc(40) }
    c.fixed32.encode(state, key)
    c.uint64.encode(state, length)

    const namespace = crypto.hash(state.buffer)
    const manifestData = c.encode(messages.ManifestData, { version: 0, legacyBlocks: 0, namespace })

    const padding = this.encryption ? AutobaseEncryption.PADDING : 0
    const block = encodeValue(null, { heads: [{ key, length }], padding })
    if (this.encryption) await this.encryption.encryptAnchor(block, namespace)

    const root = { index: 0, size: block.byteLength, hash: crypto.data(block) }
    const hash = crypto.tree([root])
    const prologue = { hash, length: 1 }

    const core = this.store.createAnchorCore(prologue, manifestData)
    await core.ready()

    if (core.length === 0) await core.append(block, { writable: true, maxLength: 1 })

    await this.system.add(core.key, { isIndexer: false, length: 0 })
    await this.base._addWriter(core.key, this.system)

    const anchor = { key: core.key, length: core.length }

    await core.close()
    await this.base.hintWakeup(anchor)

    return anchor
  }

  async _resetView(view) {
    const manifests = await this.store.getIndexerManifests(this.system.indexers)

    const manifestData = view.core ? view.core.manifest.userData : null
    view.key = await this.store.createView(
      manifests,
      view.name,
      null,
      this.system.core.manifest.version,
      this.system.entropy,
      null,
      manifestData
    ) // will never be system so no linked
    view.length = 0
  }

  async _generateNextViews() {
    const sys = this.system

    // note, this is very state dependent so can ONLY be called at the exact time an indexer upgrade occurs
    const manifests = await this.store.getIndexerManifests(sys.indexers)
    const entropy = sys.version < 2 ? null : sys.getEntropy(sys.indexers, sys.flushLength())

    for (const v of this.views) {
      const manifestData = v.core ? v.core.manifest.userData : null

      const prologue = await getPrologue(v)
      const key = await this.store.createView(
        manifests,
        v.name,
        prologue,
        sys.core.manifest.version,
        entropy,
        null,
        manifestData
      )

      v.key = key
    }
  }
}

async function getPrologue(view) {
  const length = view.core ? view.core.length : view.length
  if (!length) return null

  const hash = await view.core.treeHash(length)

  return {
    hash,
    length
  }
}

function noop() {}

function cmpCheckpoints(a, b) {
  return a.signedLength() - b.signedLength()
}

function sameSignature(a, b) {
  if (!a || !b) return a === b
  return a.length === b.length
}

function sameSignatures(a, b) {
  if (!a || !b) return a === b
  if (a.length !== b.length) return false
  for (let i = 0; i < a.length; i++) {
    if (a[i].length !== b[i].length) return false
  }
  return true
}

function createCheckpointSignature(length, view, checkpoints) {
  return {
    length,
    core: view.core,
    ref: view.ref,
    signatures: new Array(checkpoints),
    partials: new Array(checkpoints)
  }
}

function addCheckpointSignatures(pending, checkpoints, index) {
  const { signer, signatures } = checkpoints[index]

  pending[0].signatures[index] = {
    signature: signatures.system.signature,
    length: signatures.system.length,
    signer
  }

  if (pending[1]) {
    pending[1].signatures[index] = {
      signature: signatures.encryption.signature,
      length: signatures.encryption.length,
      signer
    }
  }

  for (let i = 2; i < pending.length; i++) {
    if (!pending[i]) continue

    const { length, signature } = signatures.user[i - 2]

    pending[i].signatures[index] = {
      signature,
      length,
      signer
    }
  }
}

async function setPartialSignature(view, index) {
  const sig = view.signatures[index]
  if (sig.length < view.length && sig.length > 0) await view.core.get(sig.length - 1)

  view.partials[index] = await partialSignature(
    view.core,
    sig.signer,
    view.length,
    sig.length,
    sig.signature
  )
}

function updateSignature(length, sig, existing) {
  return sig ? { signature: sig.signature, length: sig.length, at: length } : existing
}

function updateSignatures(length, signatures, existing) {
  const updated = new Array(signatures.length)

  for (let i = 0; i < updated.length; i++) {
    updated[i] = updateSignature(length, signatures[i], i < existing.length ? existing[i] : null)
  }

  return updated
}

function makeCheckpoint(length, chk) {
  if (!chk) return null

  const checkpointer = length - chk.at

  return {
    checkpointer,
    checkpoint: checkpointer === 0 ? { signature: chk.signature, length: chk.length } : null
  }
}

function makeCheckpoints(length, signatures) {
  if (!signatures.length) return null

  const checkpoints = new Array(signatures.length)

  for (let i = 0; i < signatures.length; i++) {
    checkpoints[i] = makeCheckpoint(length, signatures[i])
  }

  return checkpoints
}

function isViewCorruption(err) {
  return err.code === 'INVALID_OPERATION'
}

function isAssertion(err) {
  return err.code === 'ERR_ASSERTION' || err.name === 'AssertionError'
}
const c = require('compact-encoding')
const encryptionEncoding = require('encryption-encoding')
const messages = require('./messages.js')

module.exports = async function boot(
  corestore,
  key,
  { encrypt, encryptionKey, keyPair, exclusive = true, blindEncryption } = {}
) {
  const result = {
    key: null,
    local: null,
    bootstrap: null,
    encryptionKey: null,
    boot: null
  }

  const manifest = keyPair
    ? { version: corestore.manifestVersion, signers: [{ publicKey: keyPair.publicKey }] }
    : null

  if (key) {
    result.key = key

    const bootstrap = corestore.get({ key, active: false, valueEncoding: messages.OplogMessage })
    await bootstrap.ready()

    const localKey = await bootstrap.getUserData('autobase/local')

    if (keyPair) {
      result.local = corestore.get({
        keyPair,
        active: false,
        exclusive,
        valueEncoding: messages.OplogMessage,
        manifest
      })
    } else {
      if (bootstrap.writable && !localKey) {
        result.local = bootstrap.session({
          active: false,
          exclusive,
          valueEncoding: messages.OplogMessage
        })
      } else {
        const local = localKey
          ? corestore.get({
              key: localKey,
              active: false,
              exclusive,
              valueEncoding: messages.OplogMessage
            })
          : corestore.get({
              name: 'local',
              active: false,
              exclusive,
              valueEncoding: messages.OplogMessage
            })

        await local.ready()
        result.local = local
      }
    }

    result.bootstrap = bootstrap
  } else {
    result.local = keyPair
      ? corestore.get({
          keyPair,
          manifest,
          active: false,
          exclusive,
          valueEncoding: messages.OplogMessage
        })
      : corestore.get({
          name: 'local',
          active: false,
          exclusive,
          valueEncoding: messages.OplogMessage
        })
    await result.local.ready()

    const key = await result.local.getUserData('referrer')
    if (key) {
      result.key = key
      result.bootstrap = corestore.get({ key, active: false, valueEncoding: messages.OplogMessage })
      await result.bootstrap.ready()
    } else {
      result.key = result.local.key
      result.bootstrap = result.local.session({
        active: false,
        valueEncoding: messages.OplogMessage
      })
      await result.bootstrap.setUserData('autobase/local', result.local.key)
    }
  }

  if (key || keyPair) {
    await result.bootstrap.setUserData('referrer', result.key)
    await result.bootstrap.setUserData('autobase/local', result.local.key)
    await result.local.setUserData('referrer', result.key)
  }

  const [encryptionKeyBuffer, encryptionKeyEncryptedBuffer, pointer] = await Promise.all([
    result.local.getUserData('autobase/encryption'),
    result.local.getUserData('autobase/blind-encryption'),
    result.local.getUserData('autobase/boot')
  ])

  if (pointer) {
    result.boot = c.decode(messages.BootRecord, pointer)
  }

  if (encryptionKeyBuffer) {
    // if not encoded, replace
    if (blindEncryption) {
      const encrypted = await encryptionEncoding.encrypt(
        encryptionKeyBuffer,
        blindEncryption.encrypt
      )
      await result.local.setUserData('autobase/blind-encryption', encrypted)
      await result.local.setUserData('autobase/encryption', null)
    }

    result.encryptionKey = encryptionKeyBuffer
  }

  if (encryptionKeyEncryptedBuffer) {
    const { value, rotated } = await encryptionEncoding.decrypt(
      encryptionKeyEncryptedBuffer,
      blindEncryption.decrypt
    )

    if (rotated) {
      const encrypted = await encryptionEncoding.encrypt(value, blindEncryption.encrypt)
      await result.local.setUserData('autobase/blind-encryption', encrypted)
    }

    result.encryptionKey = value
  }

  if (!result.encryptionKey && (encryptionKey || encrypt)) {
    if (!encryptionKey) {
      encryptionKey = (await corestore.createKeyPair('autobase/encryption')).secretKey.subarray(
        0,
        32
      )
    }

    if (blindEncryption) {
      const encrypted = await encryptionEncoding.encrypt(encryptionKey, blindEncryption.encrypt)
      await result.local.setUserData('autobase/blind-encryption', encrypted)
    } else {
      await result.bootstrap.setUserData('autobase/encryption', encryptionKey) // legacy support
      await result.local.setUserData('autobase/encryption', encryptionKey)
    }
    result.encryptionKey = encryptionKey
  }

  return result
}
const crypto = require('hypercore-crypto')

const OPLOG_VERSION = 2
const DEFAULT_AUTOBASE_VERSION = 1 // default
const MAX_AUTOBASE_VERSION = 2 // optional fork support
const BOOT_RECORD_VERSION = 3

const [NS_SIGNER_NAMESPACE, NS_VIEW_BLOCK_KEY, NS_HASH_KEY, NS_ENCRYPTION] = crypto.namespace(
  'autobase',
  4
)

module.exports = {
  OPLOG_VERSION,
  DEFAULT_AUTOBASE_VERSION,
  MAX_AUTOBASE_VERSION,
  BOOT_RECORD_VERSION,
  NS_SIGNER_NAMESPACE,
  NS_VIEW_BLOCK_KEY,
  NS_HASH_KEY,
  NS_ENCRYPTION
}
const BufferMap = require('tiny-buffer-map')

// This is basically just a Map atm, but leaving it as an abstraction for now
// in case we wanna optimize it for our exact usecase

module.exports = class Clock {
  constructor() {
    this.seen = new BufferMap()
  }

  get size() {
    return this.seen.size
  }

  has(key) {
    return this.seen.has(key)
  }

  includes(key, length) {
    return this.seen.has(key) && this.seen.get(key) >= length
  }

  get(key) {
    return this.seen.get(key) || 0
  }

  set(key, len) {
    this.seen.set(key, len)
    return len
  }

  add(clock) {
    for (const [key, l] of clock) {
      if (this.get(key) < l) this.set(key, l)
    }
  }

  [Symbol.iterator]() {
    return this.seen[Symbol.iterator]()
  }
}
const BufferMap = require('tiny-buffer-map')

const Clock = require('./clock.js')

const UNSEEN = 0
const NEWER = 1
const ACKED = 2

// Consensus machine for Autobase. Sort DAG nodes using
// vector clocks to determine a globally consistent view

module.exports = class Consensus {
  constructor(indexers) {
    this.merges = new Set()
    this.majority = (indexers.length >>> 1) + 1
    this.indexers = indexers
    this.removed = new Clock()
    this.updated = false

    this.writers = new BufferMap()
    for (const idx of this.indexers) {
      this.writers.set(idx.core.key, idx)
    }
  }

  addHead(node) {
    if (!node.writer.isActiveIndexer) return
    if (this._isMerge(node)) this.merges.add(node)
    this.updated = true
    return node
  }

  /* Indexer Only DAG methods */

  _tails(node, tails) {
    const tailSet = new Set()
    for (const t of tails) {
      if (node.clock.includes(t.writer.core.key, t.length)) tailSet.add(t)
    }

    return tailSet
  }

  _tailsAndMerges(node, tails) {
    const all = this._tails(node, tails)
    for (const m of this.merges) {
      if (m !== node && node.clock.includes(m.writer.core.key, m.length)) {
        all.add(m)
      }
    }
    return all
  }

  _isMerge(node) {
    if (!node.writer.isActiveIndexer) return false

    const deps = []

    for (const idx of this.indexers) {
      let seq = node.clock.get(idx.core.key) - 1

      if (idx === node.writer) seq--

      const head = idx.get(seq)
      if (!head || this.removed.includes(head.writer.core.key, head.length)) continue

      let isDep = true
      for (let i = 0; i < deps.length; i++) {
        const d = deps[i]
        if (d === head) continue

        if (d.clock.includes(head.writer.core.key, head.length)) {
          isDep = false
          break
        }

        if (head.clock.includes(d.writer.core.key, d.length)) {
          const popped = deps.pop()
          if (d === popped) continue
          deps[i--] = popped
        }
      }

      if (isDep) deps.push(head)
    }

    return deps.length > 1
  }

  _indexerTails() {
    const tails = new Set()
    for (const idx of this.indexers) {
      const length = this.removed.has(idx.core.key) ? this.removed.get(idx.core.key) : idx.indexed

      const head = idx.get(length)
      if (!head || this.removed.includes(head.writer.core.key, head.length)) continue

      let isTail = true
      for (const t of tails) {
        if (head.clock.includes(t.writer.core.key, t.length)) {
          isTail = false
          break
        }

        if (t.clock.includes(head.writer.core.key, head.length)) {
          tails.delete(t)
        }
      }

      if (isTail) tails.add(head)
    }

    return tails
  }

  // parent is newer if for any node in parent's view,
  // either node can see object or object can see node
  _strictlyNewer(object, parent) {
    if (!parent.clock.includes(object.writer.core.key, object.length)) return false

    for (const [key, latest] of parent.clock) {
      const oldest = this.removed.get(key)
      if (latest <= oldest) continue // check quickly if we removed it

      // get the NEXT node from the writer from the objects pov, adjust if its removed
      let length = object.clock.get(key)
      if (length <= oldest) length = oldest

      // sanity check, likely not needed as someone has checked this before, but it's free
      if (latest < length) return false

      // if the same, they have both seen it, continue
      if (latest === length) continue

      const writer = this.writers.get(key)

      // might not be in the removed set but the writer can tell us if it was indexed...
      const next = writer && writer.get(length >= writer.indexed ? length : writer.indexed)

      // no next, its been indexed, both seen it
      if (!next) continue

      // if the NEXT node has seen the object its fine - newer
      if (next.clock.includes(object.writer.core.key, object.length)) continue

      // otherwise the parent must also NOT have seen the next node
      if (latest < next.length) continue

      return false
    }

    return true
  }

  _acks(target) {
    const acks = target.writer.isActiveIndexer ? [target] : [] // TODO: can be cached on the target node in future (ie if we add one we dont have to check it again)

    for (const idx of this.indexers) {
      if (idx === target.writer) continue

      let next = target.clock.get(idx.core.key)
      if (next < idx.nodes.offset) next = idx.nodes.offset

      const nextIndexNode = idx.get(next >= idx.indexed ? next : idx.indexed)

      // no node - no ack
      if (!nextIndexNode) continue

      // if the next index node does not see the target, no ack
      if (!nextIndexNode.clock.includes(target.writer.core.key, target.length)) continue

      // if the next index node is not strictly newer, skip to avoid ambig...
      if (!this._strictlyNewer(target, nextIndexNode)) continue

      acks.push(nextIndexNode)
    }

    return acks
  }

  acksFromNode(target, view) {
    const acks = new Set()

    if (!view || !view.clock.includes(target.writer.core.key, target.length)) return acks

    acks.add(view.writer)

    for (const idx of this.indexers) {
      if (idx === view.writer) continue

      const length = view.clock.get(idx.core.key)
      if (!length) continue

      if (target.clock.includes(idx.core.key, length)) continue

      const head = idx.get(length - 1)
      if (!head) continue

      if (head.clock.includes(target.writer.core.key, target.length)) {
        acks.add(idx)
      }
    }

    return acks
  }

  _ackedAt(acks, parent) {
    let seen = 0
    let missing = acks.length

    for (const node of acks) {
      missing--

      if (!parent.clock.includes(node.writer.core.key, node.length)) {
        if (seen + missing < this.majority) return false
        continue
      }

      if (++seen >= this.majority) return true
    }

    return false
  }

  confirms(indexer, target, acks, length) {
    if (!length || this.removed.get(indexer.core.key) >= length) return UNSEEN
    // def feels like there is a smarter way of doing this part
    // ie we just wanna find a node from the indexer that is strictly newer than target
    // and seens a maj of the acks - thats it

    let jump = true
    let newer = true

    for (let i = length - 1; i >= 0; i--) {
      const head = indexer.get(i)
      if (head === null) return UNSEEN

      let seen = 0

      for (const node of acks) {
        // if (node.writer === indexer) continue
        if (!head.clock.includes(node.writer.core.key, node.length)) continue
        if (++seen >= this.majority) break
      }

      if (!newer && seen < this.majority) {
        break
      }

      if (!this._strictlyNewer(target, head)) {
        // all strictly newer nodes are clustered together so bisect until we find the cluster
        if (jump) {
          jump = false

          let t = length - 1
          let b = 0

          while (t > b) {
            const mid = (t + b) >>> 1
            const node = indexer.get(mid)

            if (
              node === null ||
              !node.clock.includes(target.writer.core.key, target.length) ||
              this._strictlyNewer(target, node)
            ) {
              b = mid + 1
            } else {
              t = mid - 1
            }
          }

          // + 2 in case we are off by one and the i--. its fine, just an optimisation
          if (b + 1 < i) i = b + 2
        }

        newer = false
        continue
      } else if (seen < this.majority) {
        return NEWER
      }

      return ACKED
    }

    return UNSEEN
  }

  _isConfirmed(target, parent = null) {
    const acks = this._acks(target)
    const confs = new Set()

    if (acks.length < this.majority) return false
    let allNewer = true

    for (const indexer of this.indexers) {
      const length = parent
        ? parent.writer === indexer
          ? parent.length - 1
          : parent.clock.get(indexer.core.key)
        : indexer.length

      const result = this.confirms(indexer, target, acks, length)

      if (result === ACKED) {
        confs.add(indexer)
        if (confs.size >= this.majority) {
          return true
        }
      }

      if (result === UNSEEN) allNewer = false
    }

    if (parent) return this._isConfirmableAt(target, parent, acks, confs)

    return allNewer
  }

  _isConfirmableAt(target, parent, acks, confs) {
    if (!this._ackedAt(acks, parent)) return false

    let potential = confs.size

    for (const indexer of this.indexers) {
      if (confs.has(indexer)) continue

      const length = parent.clock.get(indexer.core.key)
      const isSeen = target.clock.includes(indexer.core.key, length)

      // if the target has seen the latest node, it can freely be used to confirm the target later
      // otherwise, check if a newer node is strictly newer...
      if (!isSeen) {
        const head = indexer.get(length - 1)

        // the next indexer head HAS to be strictly newer - meaning the current one has to be also.
        if (
          head &&
          !this.removed.includes(head.writer.core.key, head.length) &&
          !this._strictlyNewer(target, head)
        ) {
          continue
        }
      }

      if (++potential >= this.majority) return true
    }

    return false
  }

  // this can get called multiple times for same node
  remove(node) {
    this.merges.delete(node)
    this.removed.set(node.writer.core.key, node.length)
    return node
  }

  shift() {
    if (!this.updated) return []

    const tails = this._indexerTails()

    for (const tail of tails) {
      if (this._isConfirmed(tail)) {
        return [this.remove(tail)]
      }
    }

    for (const merge of this.merges) {
      if (this._isConfirmed(merge)) {
        return this._yieldNext(merge, tails)
      }
    }

    this.updated = false
    return []
  }

  // yields next indexer node
  _yieldNext(node, tails) {
    // only stop when we find a tail
    while (!tails.has(node)) {
      let next = null

      // for merges check if one fork is confirmed
      for (const t of this._tailsAndMerges(node, tails)) {
        if (this._isConfirmed(t, node)) {
          next = t
          break
        }
      }

      if (next) {
        node = next
        continue
      }

      // otherwise yield all tails
      const tailSet = []
      for (const t of this._tails(node, tails)) {
        tailSet.push(this.remove(t))
      }

      return tailSet
    }

    return [this.remove(node)]
  }

  shouldAck(writer) {
    for (const t of this._indexerTails()) {
      if (t.writer === writer) continue
      if (this._shouldAckNode(t, writer)) return true
    }

    return false
  }

  _shouldAckNode(target, writer) {
    const head = writer.head()
    const next = target.clock.get(writer.core.key)
    const nextIndexNode = writer.get(next >= writer.indexed ? next : writer.indexed)

    // if we have no next node and we didn't write target then ack
    if (!nextIndexNode && writer !== target.writer) return true

    // shortcuts if we have next node
    if (nextIndexNode) {
      // if the next node does not see the target, should ack
      if (!nextIndexNode.clock.includes(target.writer.core.key, target.length)) {
        return !head.clock.includes(target.writer.core.key, target.length)
      }

      // if the next node is not strictly newer, no point acking
      if (!this._strictlyNewer(target, nextIndexNode)) return false
    }

    // now check if we can double confirm
    const acks = this._acks(target)

    // need enough to double confirm
    if (acks.length >= this.majority) {
      return this.confirms(writer, target, acks, writer.length) === UNSEEN
    }

    return false
  }
}
const HypercoreEncryption = require('hypercore/lib/default-encryption.js')
const sodium = require('sodium-universal')
const crypto = require('hypercore-crypto')
const c = require('compact-encoding')
const b4a = require('b4a')
const rrp = require('resolve-reject-promise')
const ReadyResource = require('ready-resource')

const SystemView = require('./system.js')
const { EncryptionDescriptor, ManifestData } = require('./messages.js')
const { NS_VIEW_BLOCK_KEY, NS_HASH_KEY, NS_ENCRYPTION } = require('./caps.js')

const nonce = b4a.alloc(sodium.crypto_stream_NONCEBYTES)
const hash = nonce.subarray(0, sodium.crypto_generichash_BYTES_MIN)

class AutobaseEncryption {
  static PADDING = 8

  constructor(encryption) {
    this.encryption = encryption

    this.compat = null
    this.keys = null
    this.keysById = new Map()
  }

  get id() {
    return this.keys ? this.keys.id : 0
  }

  padding() {
    return AutobaseEncryption.PADDING
  }

  isCompat() {
    return false
  }

  load(keys) {
    if (this.keys === null) this.keys = keys
  }

  async update(ctx) {
    if (this.id !== 0 && this.id === this.encryption.id) return
    const keys = await this.get(this.encryption.id, ctx)
    if (keys) this.keys = keys
  }

  async get(id, ctx) {
    if (this.keysById.has(id)) return this.keysById.get(id)

    const keys = await this.getKeys(id, ctx)
    this.keysById.set(id, keys)

    return keys
  }

  async getKeys(id, ctx) {
    const entropy = await this.encryption.get(id)
    if (!entropy) return null

    const block = this.blockKey(entropy, ctx)
    const hash = crypto.hash([NS_HASH_KEY, block])

    return {
      id,
      block,
      hash
    }
  }

  blockKey(entropy, ctx) {
    return this.encryption.blockKey(entropy, ctx)
  }

  async _ensureCompat(ctx) {
    if (!this.compat) this.compat = this.compatKeys(ctx)
  }

  compatKeys() {
    throw new Error('Compatibility method is not specified')
  }

  async encrypt(index, block, fork, ctx) {
    if (this.isCompat(ctx, index)) {
      this._ensureCompat(ctx)
      return HypercoreEncryption.encrypt(
        index,
        block,
        fork,
        this.compat.block,
        this.compat.blinding
      )
    }

    await this.update(ctx)

    encryptBlock(index, block, this.keys.id, this.keys.block, this.keys.hash)
  }

  async decrypt(index, block, ctx) {
    if (this.isCompat(ctx, index)) {
      this._ensureCompat(ctx)
      return HypercoreEncryption.decrypt(index, block, this.compat.block)
    }

    const padding = block.subarray(0, AutobaseEncryption.PADDING)
    block = block.subarray(AutobaseEncryption.PADDING)

    const type = padding[0]
    switch (type) {
      case 0:
        return block // unencrypted

      case 1:
        break

      default:
        throw new Error('Unrecognised encryption type')
    }

    const id = c.uint32.decode({ start: 4, end: 8, buffer: padding })

    const keys = await this.get(id, ctx)

    c.uint64.encode({ start: 0, end: 8, buffer: nonce }, index)
    nonce.set(padding, 8, 16)

    // Decrypt the block using the full nonce
    decrypt(block, nonce, keys.block)
  }
}

class ViewEncryption extends AutobaseEncryption {
  constructor(encryption, name) {
    super(encryption)
    this.name = name
  }

  isCompat(ctx, index) {
    if (ctx.manifest.version <= 1) return true
    if (!ctx.manifest.userData) return false
    const { legacyBlocks } = c.decode(ManifestData, ctx.manifest.userData)
    return index < legacyBlocks
  }

  compatKeys() {
    const { bootstrap, encryptionKey } = this.encryption.base
    const block = getCompatBlockKey(bootstrap, encryptionKey, this.name)
    return {
      block,
      blinding: crypto.hash(block)
    }
  }

  blockKey(entropy) {
    return getCompatBlockKey(this.encryption.base.bootstrap, entropy, this.name)
  }
}

class WriterEncryption extends AutobaseEncryption {
  isCompat(ctx) {
    return ctx.manifest.version <= 1
  }

  compatKeys(ctx) {
    return HypercoreEncryption.deriveKeys(this.encryption.base.encryptionKey, ctx.key)
  }

  blockKey(entropy, ctx) {
    if (ctx.manifest.userData) {
      const userData = c.decode(ManifestData, ctx.manifest.userData)
      if (userData.namespace !== null) {
        return this.encryption.blockKey(entropy, { key: userData.namespace })
      }
    }

    return this.encryption.blockKey(entropy, ctx)
  }
}

class EncryptionView extends ReadyResource {
  constructor(base, core) {
    super()

    this.base = base
    this.core = core || null

    this.sessions = new Map()

    this._initialising = null
  }

  async _open() {
    await this.initialised()
    await this.core.ready()
  }

  initialised() {
    if (this.core !== null) return this.core.ready()
    if (this._initialising) return this._initialising

    this._initialising = rrp()

    return this._initialising.promise
  }

  _close() {
    if (this._initialising) {
      this._initialising.reject(new Error('Encryption closed'))
      this._initialising = null
    }

    if (this.core) return this.core.close()
  }

  get bootstrapped() {
    return !!(this.core && this.core.length > 0)
  }

  get id() {
    return this.core ? this.core.length : 0
  }

  _createPayload(key) {
    return key
  }

  async reload(core) {
    if (this.core) await this.core.close()

    this.core = core
    await this.core.ready()

    if (this._initialising) {
      this._initialising.resolve()
      this._initialising = null
    }
  }

  unpack(type, payload) {
    if (type > 0) throw new Error('Unsupported version')
    return payload
  }

  async update(key) {
    const payload = await this._createPayload(key)
    const desc = { type: 0, payload }

    await this.core.append(c.encode(EncryptionDescriptor, desc))
  }

  async _preload() {
    await this.ready()
    return this.id()
  }

  getViewEncryption(name) {
    if (this.sessions.has(name)) return this.sessions.get(name)

    const encryption = new ViewEncryption(this, name)
    this.sessions.set(name, encryption)

    return encryption
  }

  getWriterEncryption() {
    return new WriterEncryption(this)
  }

  async encryptAnchor(block, namespace) {
    const entropy = await this.get(this.id)
    if (!entropy) return null

    const blockKey = this.blockKey(entropy, { key: namespace })
    const hashKey = crypto.hash([NS_HASH_KEY, block])

    encryptBlock(0, block, this.id, blockKey, hashKey)
  }

  blockKey(entropy, ctx) {
    return getBlockKey(this.base.bootstrap, this.base.encryptionKey, entropy, ctx.key)
  }

  async get(encryptionId) {
    if (encryptionId === 0) return SystemView.GENESIS_ENTROPY

    if (!this.core) await this.initialised()

    const index = encryptionId - 1
    const desc = await this.core.get(index)
    const { type, payload } = c.decode(EncryptionDescriptor, desc)

    const key = this.unpack(type, payload)
    return key
  }

  getSystemEncryption() {
    return this.getViewEncryption('_system')
  }

  static namespace(entropy) {
    return crypto.hash([NS_ENCRYPTION, entropy])
  }

  static getBlockKey(bootstrap, encryptionKey, entropy, hypercoreKey) {
    return getBlockKey(bootstrap, encryptionKey, entropy, hypercoreKey)
  }

  static getSystemEncryption(base, core) {
    const view = new EncryptionView(base, core)
    return view.getSystemEncryption()
  }

  static async setSystemEncryption(base, core, opts) {
    if (base.encryptionKey === null) return null

    await core.ready()
    if (core.manifest.version === 1) {
      const key = getCompatBlockKey(base.bootstrap, base.encryptionKey, '_system')
      return core.setEncryptionKey(key, { block: true })
    }

    if (!core.manifest.linked.length) {
      throw new Error('System manifest does not link encryption view')
    }

    const enc = base.store.get({ key: core.manifest.linked[0], active: false })
    const encryption = EncryptionView.getSystemEncryption(base, enc)

    await core.setEncryption(encryption, opts)

    return enc
  }
}

module.exports = {
  AutobaseEncryption,
  EncryptionView
}

function encrypt(block, nonce, key) {
  sodium.crypto_stream_xor(block, block, nonce, key)
}

function decrypt(block, nonce, key) {
  return encrypt(block, nonce, key) // symmetric
}

function getBlockKey(bootstrap, encryptionKey, entropy, hypercoreKey) {
  return (
    encryptionKey &&
    crypto.hash([NS_VIEW_BLOCK_KEY, bootstrap, encryptionKey, entropy, hypercoreKey])
  )
}

function getCompatBlockKey(bootstrap, encryptionKey, name) {
  if (typeof name === 'string') return getCompatBlockKey(bootstrap, encryptionKey, b4a.from(name))
  return encryptionKey && crypto.hash([NS_VIEW_BLOCK_KEY, bootstrap, encryptionKey, name])
}

function blockhash(block, padding, hashKey) {
  sodium.crypto_generichash(hash, block, hashKey)
  padding.set(hash.subarray(0, 8)) // copy first 8 bytes of hash
  hash.fill(0) // clear nonce buffer
}

function encryptBlock(index, block, id, blockKey, hashKey) {
  const padding = block.subarray(0, AutobaseEncryption.PADDING)
  block = block.subarray(AutobaseEncryption.PADDING)

  blockhash(block, padding, hashKey)
  c.uint32.encode({ start: 4, end: 8, buffer: padding }, id)

  c.uint64.encode({ start: 0, end: 8, buffer: nonce }, index)

  padding[0] = 1 // version in plaintext

  nonce.set(padding, 8, 16)

  // The combination of index, key id, fork id and block hash is very likely
  // to be unique for a given Hypercore and therefore our nonce is suitable
  encrypt(block, nonce, blockKey)
}
const rrp = require('resolve-reject-promise')
const safetyCatch = require('safety-catch')

const SystemView = require('./system.js')
const { EncryptionView } = require('./encryption.js')

const DEFAULT_OP_TIMEOUT = 5_000
const DEFAULT_MIN_FF = 16

module.exports = class FastForward {
  constructor(
    base,
    key,
    {
      timeout = DEFAULT_OP_TIMEOUT,
      verified = true,
      minimum = DEFAULT_MIN_FF,
      force = false,
      length = 0
    } = {}
  ) {
    this.base = base
    this.key = key
    this.timeout = timeout
    this.force = force
    this.core = base.store.get({ key, active: true, encryption: null })
    this.length = length
    this.views = []
    this.encryption = null
    this.entropy = null
    this.indexers = []
    this.minimum = minimum
    this.verified = verified
    this.waiting = new Set()
    this.cores = [this.core]
    this.system = null
    this.destroyed = false
    this.upgrading = null
    this.failed = false
  }

  static MINIMUM = DEFAULT_MIN_FF

  async upgrade() {
    try {
      if (!this.upgrading) this.upgrading = this._upgrade()

      if (!(await this.upgrading)) return null

      return {
        length: this.length,
        force: this.force,
        key: this.key,
        indexers: this.indexers,
        views: this.views,
        entropy: this.entropy,
        manifestVersion: this.core.manifest.version,
        minimum: this.minimum
      }
    } catch (err) {
      safetyCatch(err)
      this.failed = true
      return null
    } finally {
      await this.close()
    }
  }

  _waitForAppend(core) {
    if (core.length > 0) return Promise.resolve()

    const promise = rrp()
    const timeout = setTimeout(this.close.bind(this), this.timeout)
    const wait = { promise, timeout }

    this.waiting.add(wait)

    core.once('append', () => {
      this.waiting.delete(wait)
      clearTimeout(timeout)
      promise.resolve()
    })

    return promise.promise
  }

  _minLength() {
    return this.base.core.length + this.minimum
  }

  async _upgrade() {
    await this.core.ready()

    if (!this.verified) await this._waitForAppend(this.core)
    if (this.destroyed) return false

    if (this.core.manifest.linked) {
      const appends = []

      for (const key of this.core.manifest.linked) {
        const core = this.base.store.get({ key, active: true })
        this.cores.push(core)

        await core.ready()
        appends.push(this._waitForAppend(core))
      }

      await Promise.all(appends)
    }

    if (this.length === 0) this.length = this.core.length

    // note we use the persisted length here, as we might as well continue that work as thats ~ the same length
    if (!this.force && this.length < this._minLength()) return false
    if (this.length === 0) return false

    await this.core.get(this.length - 1, { timeout: this.timeout })
    await this.base.ready()

    if (this.destroyed) return false

    if (this.base.encryptionKey && !(await this._ensureEncryption())) return false
    if (this.destroyed) return false

    this.system = new SystemView(this.core, { checkout: this.length })
    await this.system.ready()
    if (this.destroyed) return false

    this.entropy = this.system.entropy

    if (this.core.manifest.version >= 2) {
      const linked = this.core.manifest.linked

      if (this.system.encryptionLength === 0 || linked === null || !linked.length) {
        return false
      }

      // technically diverges from system.views to include encryption here, but makes sense
      this.views.push({
        key: linked[0],
        length: this.system.encryptionLength
      })
    }

    const promises = []

    // ensure local key is locally available always
    promises.push(this.system.get(this.base.local.key, { timeout: this.timeout }))

    if (this.encryption && this.encryption.core) {
      promises.push(
        this.encryption.core.get(this.system.encryptionLength - 1, { timeout: this.timeout })
      )
    }

    for (const v of this.system.views) {
      this.views.push(v)
      const core = this.base.store.get({ key: v.key, active: true })
      this.cores.push(core)
      if (!v.length) continue // encryption view can be 0 length
      promises.push(core.get(v.length - 1, { timeout: this.timeout }))
    }

    for (const idx of this.system.indexers) {
      this.indexers.push(idx)
      if (idx.length === 0) continue // need to make sure we have manifest...
      const core = this.base.store.get({ key: idx.key, active: true })
      this.cores.push(core)
      promises.push(core.get(idx.length - 1, { timeout: this.timeout }))
      promises.push(this.system.get(idx.key, { timeout: this.timeout }))
    }

    for (const head of this.system.heads) {
      promises.push(this.system.get(head.key, { timeout: this.timeout }))
    }

    await Promise.all(promises)
    if (this.destroyed) return false

    return true
  }

  async _ensureEncryption() {
    // only need encryption if we migrated
    if (this.core.encryption !== null) return true

    const encCore = this.core.manifest.version <= 1 ? null : this.cores[1]

    // expects internal views to be loaded in order
    this.encryption = new EncryptionView(this.base, encCore)
    const encryption = this.encryption.getViewEncryption('_system')

    await this.core.setEncryption(encryption)

    return true
  }

  async close() {
    this.destroyed = true
    for (const { promise, timeout } of this.waiting) {
      clearTimeout(timeout)
      promise.resolve() // silently bail
    }
    if (this.system) await this.system.close()
    if (this.encryption) await this.encryption.close()
    for (const core of this.cores) await core.close()
    await this.core.close()
  }
}
const c = require('compact-encoding')

const SystemView = require('./system.js')
const { EncryptionView } = require('./encryption.js')
const { ManifestData } = require('./messages.js')

module.exports = class Fork {
  constructor(base, store, state, fork) {
    this.base = base
    this.store = store
    this.state = state
    this.indexers = fork.indexers
    this.length = fork.length
    this.system = null
    this.encryption = null
    this.manifests = null
    this.cores = []
  }

  async upgrade() {
    try {
      await this._upgrade()
      return true
    } catch {
      return false
    } finally {
      await this.close()
    }
  }

  async _upgrade() {
    this.manifests = await this.store.getIndexerManifests(this.indexers)

    this.system = new SystemView(await this._get('_system', this.length))
    this.encryption = new EncryptionView(this, await this._get('_encryption', -1))

    await this.system.ready()
    await this.encryption.ready()

    this.entropy = this.system.getEntropy(this.indexers, this.length)
    this.manifestVersion = Math.max(this.system.core.manifest.version, 2) // >= 2 to signal new encryption

    const views = []
    for (const view of this.state.views) {
      const v = this.getViewFromSystem(view, this.system)
      const indexedLength = v ? v.length : 0

      const session = await this._get(view.name, indexedLength)
      await session.ready()

      const next = await this.createView(view.name, session, null)
      await next.ready()

      await this._migrate(view.ref, next, view.core, indexedLength)

      // update key
      views.push({ key: next.key, length: indexedLength })
    }

    // internal views are explicitly migrated

    const entropy = EncryptionView.namespace(this.entropy)
    await this.encryption.update(entropy)

    const system = this.store.getViewByName('_system')
    const encryption = this.store.getViewByName('_encryption')

    const enc = await this.createView('_encryption', this.encryption.core, null)
    await enc.ready()

    await this._migrate(encryption, enc, this.encryption.core, this.encryption.core.length)

    await this.system.fork(this.indexers, this.manifests, this.encryption.core.length, views)

    const sys = await this.createView('_system', this.system.core, [enc.key])
    await sys.ready()

    await this._migrate(system, sys, this.system.core, this.system.core.length)
  }

  async createView(name, core, linked) {
    const prologue = await getPrologue(core)
    const manifestData = this._manifestData(core)

    return this.store.getViewCore(
      this.manifests,
      name,
      prologue,
      this.manifestVersion,
      this.entropy,
      linked,
      manifestData
    )
  }

  async _get(name, length) {
    const core = this.store.get({ name })
    this.cores.push(core)

    if (length !== -1) await core.truncate(length)

    return core
  }

  getViewFromSystem(view) {
    if (view.mappedIndex === -1 || view.mappedIndex >= this.system.views.length) return null
    return this.system.views[view.mappedIndex]
  }

  _manifestData(session) {
    if (session.manifest.version > 1) return session.manifest.userData
    return c.encode(ManifestData, { version: 0, legacyBlocks: session.length })
  }

  async _migrate(ref, next, source, length) {
    if (length > 0) {
      await next.core.copyPrologue(source.state)
    }

    // remake the batch, reset from our prologue in case it replicated inbetween
    // TODO: we should really have an HC function for this
    const batch = next.session({ name: 'batch', overwrite: true, checkout: length })
    await batch.ready()

    if (source !== null) {
      while (batch.length < source.length) {
        await batch.append(await source.get(batch.length))
      }
    }

    ref.moveTo = [batch, next]
  }

  async close() {
    this.destroyed = true
    if (this.system) await this.system.close()
    if (this.encryption) await this.encryption.close()
    for (const core of this.cores) await core.close()
  }
}

async function getPrologue(core) {
  if (!core.length) return null

  return {
    hash: await core.treeHash(),
    length: core.length
  }
}
const b4a = require('b4a')
const assert = require('nanoassert')

const Clock = require('./clock.js')
const Consensus = require('./consensus.js')
const Topolist = require('./topolist.js')

class Node {
  constructor(writer, length, value, heads, batch, dependencies, optimistic, trace) {
    this.writer = writer
    this.length = length
    this.value = value
    this.heads = heads
    this.actualHeads = heads.slice(0) // TODO: we should remove this and just not mutate heads...

    this.dependents = new Set()
    this.dependencies = dependencies
    this.index = 0 // used by topolist

    this.optimistic = optimistic && batch === 1 && !!value

    this.batch = batch
    this.dropped = 0
    this.trace = trace

    this.clock = new Clock()

    this.yielded = false
    this.yielding = false
  }

  isTail() {
    return this.dependencies.size === this.dropped
  }

  causalDependencies(idx) {
    const order = [this]
    const stack = [this]

    let visited = null

    while (stack.length > 0) {
      const node = stack.pop()
      for (const dep of node.dependencies) {
        if (!dep.writer.isRemoved || dep.writer.isActiveIndexer) continue

        // TODO: replace with "coloring" but ok for now, tiny set
        if (visited === null) visited = new Set()
        if (visited.has(dep)) continue
        visited.add(dep)

        stack.push(dep)
        order.push(dep)
      }
    }

    return order
  }

  clear() {
    this.clock = null
    this.dependents = null
    return this
  }

  reset() {
    this.yielded = false
    this.yielding = false
    for (const dep of this.dependents) dep.dependencies.add(this)
    this.dependents.clear()
  }

  active() {
    for (const dep of this.dependencies) {
      if (dep.yielded) {
        this.dependencies.delete(dep) // nodes might be yielded during buffering
      } else {
        dep.dependents.add(this)
        this.clock.add(dep.clock)
      }
    }

    if (this.writer.isActiveIndexer) this.clock.set(this.writer.core.key, this.length)
  }

  tieBreak(node) {
    return tieBreak(this, node)
  }

  hasDependency(dep) {
    for (const h of this.actualHeads) {
      if (sameNode(h, dep)) return true
    }
    return false
  }

  get ref() {
    return this.writer.core.key.toString('hex').slice(0, 2) + ':' + this.length
  }
}

module.exports = class Linearizer {
  constructor(indexers, { heads = [], writers = new Map() } = {}) {
    this.heads = new Set()
    this.tails = new Set()
    this.tip = new Topolist()
    this.size = 0 // useful for debugging
    this.updated = false
    this.indexersUpdated = false
    this.writers = writers

    this.consensus = new Consensus(indexers)
    this._initialHeads = heads.slice(0)
    this._strictlyAdded = null

    for (const { key, length } of heads) {
      this.consensus.removed.set(key, length)
    }
  }

  get indexers() {
    return this.consensus.indexers
  }

  static createNode(writer, length, value, heads, batch, dependencies, optimistic, trace) {
    return new Node(writer, length, value, heads, batch, dependencies, optimistic, trace)
  }

  // returns the global links of the dag, use this to link against the current state of the dag
  // TODO: rename to heads() and move the sets to _ props
  getHeads() {
    const heads = this._initialHeads.slice(0)
    for (const node of this.heads) heads.push({ key: node.writer.core.key, length: node.length })
    return heads
  }

  // TODO: might contain dups atm, nbd for how we use it, returns an array of writers you can "pull"
  // to get the full dag view at any time
  getBootstrapWriters() {
    const writers = []

    for (const head of this.heads) writers.push(head.writer)
    for (let i = 0; i < this.consensus.indexers.length; i++)
      writers.push(this.consensus.indexers[i])

    return writers
  }

  addHead(node) {
    node.active()

    // 99.99% of the time _initialHeads is empty...
    if (this._initialHeads.length > 0) this._updateInitialHeads(node)

    if (node.isTail()) {
      this.tails.add(node)
    }

    for (const head of this.heads) {
      if (node.hasDependency(head)) {
        this.heads.delete(head)
      }
    }

    this.tip.add(node)
    if (node.writer.isActiveIndexer) this.consensus.addHead(node)

    this.size++
    this.heads.add(node)

    this.updated = true

    return node
  }

  update() {
    if (!this.updated) return null
    this.updated = false

    // get the indexed nodes
    const indexed = []
    while (true) {
      const nodes = this.consensus.shift()
      if (!nodes.length) break

      this._yield(nodes, indexed)
    }

    return this.tip.flush(indexed)
  }

  _updateInitialHeads(node) {
    for (const head of node.actualHeads) {
      for (let i = 0; i < this._initialHeads.length; i++) {
        const { key, length } = this._initialHeads[i]
        if (length !== head.length || !b4a.equals(key, head.key)) continue
        this._initialHeads.splice(i--, 1)
      }
    }
  }

  /* Ack methods */

  shouldAck(writer, pending = false) {
    if (!writer || !writer.isActiveIndexer) return false

    // all indexers have to flushed to the dag before we ack as a quick "debounce"
    for (const w of this.indexers) {
      if (w.length !== w.available) return false
    }

    let isHead = false

    // if ANY head is not an indexer ack
    for (const head of this.heads) {
      if (!head.writer.isActiveIndexer) return true
      if (head.writer === writer) isHead = true
    }

    if (this.heads.size === 1 && isHead) {
      return false // never self-ack!
    }

    const visited = new Set()

    // check if there is non-null value
    let valueCheck = false

    for (const tail of this.tails) {
      if (pending || this._nonNull(tail, visited)) {
        valueCheck = true
        break
      }
    }

    if (!valueCheck) return false

    if (this.consensus.shouldAck(writer)) return true

    return this._shouldAckHeads(writer, pending)
  }

  // check if there is any value above this node
  _nonNull(target, visited) {
    const stack = [target]

    while (stack.length) {
      const node = stack.pop()

      if (visited.has(node)) continue
      if (node.value !== null) return true

      visited.add(node)

      for (const dep of node.dependents) {
        stack.push(dep)
      }
    }

    return false
  }

  // ack if any head is closer to confirming a value
  _shouldAckHeads(writer, pending) {
    const prev = writer.head()

    for (const head of this.heads) {
      // only check other writers heads
      if (head.writer === writer) continue

      const stack = [head]
      const visited = new Set()

      while (stack.length) {
        const node = stack.pop()

        if (visited.has(node)) continue
        visited.add(node)

        if (pending || node.value !== null) {
          const acks = this.consensus.acksFromNode(node, head)
          const prevAcks = this.consensus.acksFromNode(node, prev)

          // head sees more acks
          if (acks.size > prevAcks.size) return true

          for (const idx of acks) {
            // head sees acks that writer does not
            if (!prevAcks.has(idx)) return true
          }

          // both seen, no point going any further down
          if (prevAcks.size && acks.size) continue
        }

        stack.push(...node.dependencies)
      }
    }

    return false
  }

  /* Full DAG methods */

  _yield(nodes, indexed = []) {
    const offset = indexed.length
    const tails = []

    // determine which nodes are yielded
    while (nodes.length) {
      const node = nodes.pop()

      if (node.yielding) continue
      node.yielding = true

      if (node.isTail()) tails.push(node)

      nodes.push(...node.dependencies)
    }

    while (tails.length) {
      let tail = tails.pop()

      for (tail of this._removeBatch(tail)) {
        Topolist.add(tail, indexed, offset)
      }

      for (const dep of tail.dependents) {
        if (dep.isTail() && dep.yielding) tails.push(dep)
      }
    }

    return indexed
  }

  _isFutureTail(node) {
    let dropped = node.dropped

    // a tail has no unyielded dependencies
    for (const dep of node.dependencies) {
      if (dep.yielded) continue
      if (dropped === 0) return false
      dropped--
    }

    return true
  }

  _removeNode(node) {
    this.tails.delete(node)
    this.heads.delete(node)
    this.consensus.remove(node)

    // update the tailset
    for (const d of node.dependents) {
      if (d.yielding && d.dependencies.has(node))
        d.dropped++ // keep links for the indexed batch
      else d.dependencies.delete(node)
      if (this._isFutureTail(d)) this.tails.add(d)
    }

    node.yielded = true
    this.size--

    if (this.heads.size === 0) {
      // in case of a single writer the dag might drain immediately...
      this._initialHeads.push({ key: node.writer.core.key, length: node.length })
    }

    return node
  }

  _removeBatch(node) {
    const batch = [this._removeNode(node)]

    while (node.batch !== 1) {
      // its a batch!
      if (node.dependents.size === 0) {
        // bad batch node, auto correct
        const next = node.writer.get(node.length)
        if (next && next.batch === node.batch - 1) node.dependents.add(next)
      }

      assert(node.dependents.size === 1, 'Batch is linked partially, which is not allowed')

      node = getFirst(node.dependents)
      batch.push(this._removeNode(node))
    }

    return batch
  }
}

function tieBreak(a, b) {
  return Topolist.compare(a, b) < 0 // lowest key wis
}

function getFirst(set) {
  return set[Symbol.iterator]().next().value
}

function sameNode(a, b) {
  return b4a.equals(a.key, b.writer.core.key) && a.length === b.length
}
const c = require('compact-encoding')
const b4a = require('b4a')

const messages = require('./messages.js')

const GTE = b4a.from([messages.LINEARIZER_PREFIX])
const LT = b4a.from([messages.LINEARIZER_PREFIX + 1])

module.exports = class LocalState {
  constructor(core) {
    this.core = core
    this.tx = null
  }

  static clear(core) {
    const tx = core.state.storage.write()
    tx.deleteLocalRange(GTE, LT)
    return tx.flush()
  }

  static async moveTo(src, dst) {
    const boot = await src.getUserData('autobase/boot')
    const tx = dst.state.storage.write()

    tx.deleteLocalRange(GTE, LT)

    for await (const data of src.state.storage.createLocalStream({ gte: GTE, lt: LT })) {
      tx.putLocal(data.key, data.value)
    }

    tx.putUserData('autobase/boot', boot)

    await tx.flush()
  }

  setBootRecord(boot) {
    if (this.tx === null) this.tx = this.core.state.storage.write()

    this.tx.putUserData('autobase/boot', c.encode(messages.BootRecord, boot))
  }

  async listUpdates() {
    const updates = []

    for await (const data of this.core.state.storage.createLocalStream({ gte: GTE, lt: LT })) {
      const update = c.decode(messages.LinearizerUpdate, data.value)
      const seq = c.decode(messages.LinearizerKey, data.key)
      update.seq = seq
      updates.push(update)
    }

    return updates
  }

  clearUpdates() {
    if (this.tx === null) this.tx = this.core.state.storage.write()

    this.tx.deleteLocalRange(GTE, LT)
  }

  deleteUpdate(update) {
    if (this.tx === null) this.tx = this.core.state.storage.write()

    this.tx.deleteLocal(c.encode(messages.LinearizerKey, update.seq))
  }

  insertUpdate(update) {
    if (this.tx === null) this.tx = this.core.state.storage.write()

    this.tx.putLocal(
      c.encode(messages.LinearizerKey, update.seq),
      c.encode(messages.LinearizerUpdate, update)
    )
  }

  flush() {
    if (!this.tx) return Promise.resolve()

    const flushing = this.tx.flush()
    this.tx = null
    return flushing
  }
}
const schema = require('../encoding/spec/autobase')

module.exports = {
  Wakeup: schema.resolveStruct('@autobase/wakeup'),
  Clock: schema.resolveStruct('@autobase/clock'),
  Checkout: schema.resolveStruct('@autobase/checkout'),
  BootRecord: schema.resolveStruct('@autobase/boot-record'),
  OplogMessage: schema.resolveStruct('@autobase/oplog-message'),
  Checkpoint: schema.resolveStruct('@autobase/checkpoint'),
  Info: schema.resolveStruct('@autobase/info'),
  Member: schema.resolveStruct('@autobase/member'),
  ManifestData: schema.resolveStruct('@autobase/manifest-data'),
  LINEARIZER_PREFIX: 1,
  LinearizerKey: schema.resolveStruct('@autobase/linearizer-key'),
  LinearizerUpdate: schema.resolveStruct('@autobase/linearizer-update'),
  EncryptionDescriptor: schema.resolveStruct('@autobase/encryption-descriptor')
}
const DEFAULT_SIZE = 32

module.exports = class NodeBuffer {
  constructor(offset, hwm) {
    this.hwm = hwm || DEFAULT_SIZE
    this.defaultHwm = this.hwm
    this.mask = this.hwm - 1
    this.top = 0
    this.btm = 0
    this.buffer = new Array(this.hwm)
    this.offset = offset || 0
    this.length = this.offset
  }

  get size() {
    return this.length - this.offset
  }

  isEmpty() {
    return this.length === this.offset
  }

  isFull() {
    return this.size === this.buffer.length
  }

  grow() {
    this.hwm <<= 1

    const size = this.size
    const buffer = new Array(this.hwm)
    const mask = this.hwm - 1

    for (let i = 0; i < size; i++) {
      buffer[i] = this.buffer[(this.btm + i) & this.mask]
    }

    this.mask = mask
    this.top = size
    this.btm = 0
    this.buffer = buffer
  }

  push(data) {
    if (this.isFull()) this.grow()

    this.buffer[this.top] = data
    this.top = (this.top + 1) & this.mask

    return this.length++
  }

  shift() {
    if (this.isEmpty()) return null

    const last = this.buffer[this.btm]

    this.buffer[this.btm] = undefined
    this.btm = (this.btm + 1) & this.mask
    this.offset++

    // reset on empty
    if (this.isEmpty() && this.hwm !== this.defaultHwm) {
      this.buffer = new Array(this.defaultHwm)
      this.hwm = this.buffer.length
      this.mask = this.hwm - 1
      this.top = this.btm = 0
    }

    return last
  }

  get(seq) {
    if (seq < this.offset || seq >= this.length) return null
    return this.buffer[(this.btm + (seq - this.offset)) & this.mask]
  }
}
const b4a = require('b4a')
const c = require('compact-encoding')
const crypto = require('hypercore-crypto')
const Hypercore = require('hypercore')

const messages = require('./messages.js')

const DEFAULT_MANIFEST_VERSION = 1
const INDEX_VERSION = 1
const MAX_TRACE_PER_VIEW = 256

const EMPTY = b4a.alloc(0)

const [NS_SIGNER_NAMESPACE] = crypto.namespace('autobase', 1)

class ViewCore {
  constructor(name, core, base) {
    this.name = name
    this.core = null
    this.batch = null
    this.atomicBatch = null
    this.moveTo = null
    this.tracer = new Tracer()
    this.shared = 0

    this.ontruncate = (length) => {
      this.shared = Math.min(this.shared, length)
    }
    this.migrated(base, core)
  }

  getCore() {
    return this.atomicBatch || this.batch || this.core
  }

  migrated(base, core) {
    // TODO: close old core if present, for now we just close when the autobase is closed indirectly
    // atm its unsafe to do as moveTo has a bug due to a missing read lock in hc
    this.core = core

    if (this.name === '_system') {
      const ff = base._queueFastForward.bind(base)
      this.core.on('append', ff)
      this.core.ready().then(ff, ff)
    }
  }

  async matchesKey(key) {
    if (!this.core.opened) await this.core.ready()
    return b4a.equals(this.core.key, key)
  }

  async matchesNamespace(target) {
    if (!this.core.opened) await this.core.ready()

    if (this.core.manifest && this.core.manifest.signers.length > 0) {
      const ns = this.core.manifest.signers[0].namespace
      if (b4a.equals(ns, target)) return true
    }

    return false
  }

  getNextKey() {
    return this.moveTo ? this.moveTo[0].key : null
  }

  async commit(atom, length, signature) {
    // TODO: is this how its supposed be done atomic wise?
    await this.core.commit(this._getAtomicBatch(atom), { length, signature })
  }

  async release() {
    if (!this.atomicBatch) return
    await this.atomicBatch.ready()

    while (this.atomicBatch.state.sessions.length) {
      await this.atomicBatch.state.sessions[0].close()
    }

    await this.atomicBatch.close()
    this.atomicBatch = null
  }

  _getAtomicBatch(atom) {
    if (this.atomicBatch === null) {
      this.atomicBatch = this.batch.session({ atom, writable: true })
      this.atomicBatch.on('truncate', this.ontruncate)
    }

    return this.atomicBatch
  }

  async catchup(atom, length) {
    await this.release()
    const batch = this._getAtomicBatch(atom)
    await batch.ready()
    await batch.state.catchup(length)
  }

  createSession(atom, valueEncoding) {
    if (this.batch === null) {
      this.batch = this.core.session({ name: 'batch', writable: true })
      this.batch.on('truncate', this.ontruncate)
    }

    const s = atom
      ? this._getAtomicBatch(atom).session({
          valueEncoding,
          writable: true,
          onseq: this.tracer.onseq.bind(this.tracer)
        })
      : this.batch.session({ valueEncoding, writable: false })

    return s
  }
}

class Tracer {
  constructor() {
    this.enabled = false
    this.seen = new Set()
  }

  start() {
    this.enabled = true
    this.seen.clear()
  }

  end() {
    this.enabled = false
    return [...this.seen.values()]
  }

  onseq(seq, core) {
    if (!this.enabled) return
    if (this.seen.size >= MAX_TRACE_PER_VIEW) return
    if (seq >= core.signedLength) return

    this.seen.add(seq)
  }
}

class AutoStore {
  constructor(base, byName) {
    this.base = base
    this.store = base.store
    this.byName = byName || new Map()
    this.opened = []
    this.atom = null
    this.local = null
  }

  async close() {
    if (this.local) await this.local.close()
    for (const v of this.byName.values()) {
      await v.release()
    }
    if (this.atom) return
    for (const v of this.byName.values()) {
      if (v.core) await v.core.close()
      if (v.batch) await v.batch.close()
    }
  }

  async export() {
    const views = []

    for (const [name, value] of this.byName) {
      const core = await this.store.storage.export(value.core.discoveryKey, { batches: true })
      views.push({ name, core })
    }

    return views
  }

  atomize() {
    const store = new AutoStore(this.base, this.byName)
    store.atom = this.store.storage.createAtom()
    return store
  }

  async updateLocal() {
    if (!this.local) return
    await this.local.close()
    this.local = null
  }

  flush() {
    return this.atom ? this.atom.flush() : Promise.resolve()
  }

  get(opts, moreOpts) {
    if (typeof opts === 'string') opts = { name: opts }
    if (moreOpts) opts = { ...opts, ...moreOpts }

    const { name, valueEncoding = null } = opts

    if (!name) throw new Error('name is required')
    return this.getViewByName(name).createSession(this.atom, valueEncoding)
  }

  getViewByName(name) {
    let view = this.byName.get(name)

    if (!view) {
      const preload = this._preload(name)
      const core = this.base.store.get({ preload })
      view = new ViewCore(name, core, this.base)
      this.byName.set(name, view)
    }

    if (this.opened.indexOf(view) === -1) {
      this.opened.push(view)
    }

    return view
  }

  getLocal() {
    if (this.local !== null) return this.local

    this.local = this.base.local.session({
      atom: this.atom,
      valueEncoding: messages.OplogMessage,
      encryption: this.base.getWriterEncryption(this.base.local.key),
      active: false
    })

    return this.local
  }

  getViews() {
    return [...this.byName.values()]
  }

  getViewCount() {
    return this.byName.size
  }

  getSystemView() {
    return this.getViewByName('_system')
  }

  getSystemCore() {
    return this.getSystemView().core
  }

  getEncryption(name) {
    if (!this.base.encryptionKey) return null
    if (name === '_encryption') return null

    return this.base.encryption.getViewEncryption(name)
  }

  async getIndexerManifests(entries) {
    const manifests = []
    for (const { key } of entries) {
      const core = this.store.get({ key, active: false })
      await core.ready()
      if (!core.manifest) continue // danger but only for bootstrapping...
      manifests.push(core.manifest)
      await core.close()
    }
    return manifests
  }

  getViewCore(indexerManifests, name, prologue, manifestVersion, entropy, linked, manifestData) {
    const manifest = this._createManifest(
      indexerManifests,
      name,
      prologue,
      manifestVersion,
      entropy,
      linked,
      manifestData
    )

    return this.base.store.get({
      manifest,
      exclusive: false,
      encryption: this.getEncryption(name)
    })
  }

  listViews() {
    const views = []
    for (const [name, ref] of this.byName) {
      const core = ref.batch || ref.core
      views.push({ name, key: core.key, length: core.length, signedLength: core.signedLength })
    }
    return views
  }

  createAnchorCore(prologue, manifestData) {
    const manifest = {
      version: 2,
      hash: 'blake2b',
      prologue,
      allowPatch: false,
      quorum: 0,
      signers: [],
      userData: manifestData,
      linked: null
    }

    const core = this.store.get({
      manifest,
      active: false
    })

    return core
  }

  async createView(
    indexerManifests,
    name,
    prologue,
    manifestVersion,
    entropy,
    linked,
    manifestData
  ) {
    const manifest = this._createManifest(
      indexerManifests,
      name,
      prologue,
      manifestVersion,
      entropy,
      linked,
      manifestData
    )

    const core = this.store.get({
      key: Hypercore.key(manifest),
      manifest,
      active: false
    })

    await core.ready()
    const key = core.key

    await core.close()
    return key
  }

  async _preload(name) {
    await Promise.resolve()

    if (!this.base.opening) throw new Error('Autobase failed to open')
    await this.base._preopen

    const boot = (await this.base._getSystemInfo()) || {
      key: this.getBootstrapSystemKey(),
      indexers: [],
      views: [],
      entropy: null
    }
    const indexerManifests = await this.getIndexerManifests(boot.indexers)

    // no system, everything is fresh
    if (boot.indexers.length === 0) {
      return this._freshCorePreload(indexerManifests, name, boot.entropy)
    }

    // asking for the system, just return it, easy
    if (name === '_system') {
      return {
        key: boot.key,
        exclusive: false,
        encryption: this.getEncryption(name)
      }
    }

    if (name === '_encryption') {
      const core = this.getSystemCore()
      await core.ready()

      if (!core.manifest.linked) {
        return this._freshCorePreload(indexerManifests, name, boot.entropy)
      }

      return {
        key: core.manifest.linked[0],
        exclusive: false,
        encryption: null
      }
    }

    // infer which view
    const v = await this.findViewByName(indexerManifests, boot.views, name, boot.entropy)

    // new view, fresh
    if (v === null) {
      return this._freshCorePreload(indexerManifests, name, boot.entropy)
    }

    return {
      key: v.key,
      exclusive: false,
      encryption: this.getEncryption(name)
    }
  }

  _freshCorePreload(indexerManifests, name, entropy) {
    if (name === '_system') return this._freshSystemPreload(indexerManifests, entropy)

    return {
      manifest: this._createManifest(
        indexerManifests,
        name,
        null,
        DEFAULT_MANIFEST_VERSION,
        entropy,
        [],
        null
      ),
      exclusive: true,
      encryption: this.getEncryption(name)
    }
  }

  _freshSystemPreload(indexerManifests, entropy) {
    return {
      manifest: this._createSystemManifest(
        indexerManifests,
        null,
        DEFAULT_MANIFEST_VERSION,
        entropy,
        null
      ),
      exclusive: true,
      encryption: this.getEncryption('_system')
    }
  }

  _deriveStaticHash(name) {
    // key doesnt matter...
    return crypto.hash([this.base.key, b4a.from(name)])
  }

  _deriveNamespace(name, entropy) {
    const encryptionId = crypto.hash(this.base.encryptionKey || EMPTY)
    const version = c.encode(c.uint, INDEX_VERSION)
    const bootstrap = this.base.key

    return crypto.hash([
      NS_SIGNER_NAMESPACE,
      version,
      bootstrap,
      encryptionId,
      entropy,
      b4a.from(name)
    ])
  }

  async _getCoreManifest(key) {
    const core = this.store.get({ key, active: false })
    await core.ready()
    const manifest = core.manifest
    await core.close()
    return manifest
  }

  getBootstrapSystemKey() {
    return Hypercore.key(this._createSystemManifest([], null, DEFAULT_MANIFEST_VERSION, null))
  }

  async findViewByKey(key, indexers, manifestVersion, entropy) {
    for (const v of this.byName.values()) {
      if (await v.matchesKey(key)) return v
    }

    const manifest = await this._getCoreManifest(key)
    const target = manifest && manifest.signers.length ? manifest.signers[0].namespace : null

    if (target) {
      for (const v of this.byName.values()) {
        if (await v.matchesNamespace(target)) return v
      }
    }

    const indexerManifests = await this.getIndexerManifests(indexers)

    if (entropy === null) {
      entropy = indexerManifests[0].signers[0].namespace
    }

    if (target) {
      for (const v of this.byName.values()) {
        const namespace = this._deriveNamespace(v.name, entropy)
        if (b4a.equals(namespace, target)) return v
      }
    }

    // prob the empty prologue, we dont have manifest for those in FF if len=0
    for (const v of this.byName.values()) {
      const manifestData = v.core ? v.core.manifest.userData : null
      const manifest = this._createManifest(
        indexerManifests,
        v.name,
        null,
        manifestVersion,
        entropy,
        [],
        manifestData
      )
      const manifestKey = Hypercore.key(manifest)

      if (!b4a.equals(manifestKey, key)) continue

      // we didnt have the core! this is because it is empty, ensure its on disk
      const core = this.store.get({ key: manifestKey, manifest, active: false })
      await core.ready()
      await core.close()

      return v
    }

    return null
  }

  async findViewByName(indexerManifests, views, name, entropy) {
    if (indexerManifests.length === 0) return null

    if (entropy === null) entropy = indexerManifests[0].signers[0].namespace
    const namespace = this._deriveNamespace(name, entropy)

    for (const v of views) {
      const manifest = await this._getCoreManifest(v.key)
      if (manifest.signers.length === 0) continue

      const signer = manifest.signers[0]

      if (b4a.equals(signer.namespace, namespace)) return v
    }

    return null
  }

  _createManifest(indexerManifests, name, prologue, version, entropy, linked, manifestData) {
    if (!indexerManifests.length) {
      prologue = {
        hash: this._deriveStaticHash(name),
        length: 0
      }
    } else if (prologue && prologue.length === 0) {
      // just in case
      prologue = null
    }

    const signers = []

    if (indexerManifests.length && entropy === null) {
      entropy = indexerManifests[0].signers[0].namespace
    }

    for (const manifest of indexerManifests) {
      const signer = manifest.signers[0]

      signers.push({
        namespace: this._deriveNamespace(name, entropy),
        signature: 'ed25519',
        publicKey: signer.publicKey
      })
    }

    return {
      version,
      hash: 'blake2b',
      prologue,
      allowPatch: true,
      quorum: Math.min(signers.length, (signers.length >> 1) + 1),
      signers,
      userData: manifestData,
      linked: version > 1 ? linked : null
    }
  }

  _createSystemManifest(indexerManifests, prologue, version, entropy, manifestData) {
    if (prologue !== null) throw new Error('Can only derive fresh system core')

    const linked = []

    if (version > DEFAULT_MANIFEST_VERSION) {
      const encManifest = this._createManifest(
        indexerManifests,
        '_encryption',
        null,
        version,
        entropy,
        [],
        manifestData
      )
      linked.push(Hypercore.key(encManifest))
    }

    return this._createManifest(
      indexerManifests,
      '_system',
      null,
      version,
      entropy,
      linked,
      manifestData
    )
  }
}

module.exports = AutoStore
const Hyperbee = require('hyperbee')
const SubEncoder = require('sub-encoder')
const ReadyResource = require('ready-resource')
const b4a = require('b4a')
const c = require('compact-encoding')
const crypto = require('hypercore-crypto')

const { Info, Member } = require('./messages.js')
const { DEFAULT_AUTOBASE_VERSION } = require('./caps.js')

const subs = new SubEncoder()

const DIGEST = subs.sub(b4a.from([0]))
const MEMBERS = subs.sub(b4a.from([1]))

const INFO_KEY = DIGEST.encode('info')

const [GENESIS_ENTROPY, NS_ENTROPY] = crypto.namespace('autobase/entropy', 2)

module.exports = class SystemView extends ReadyResource {
  constructor(core, { checkout = 0, empty = false } = {}) {
    super()

    this.core = core

    // sessions is a workaround for batches not having sessions atm...
    this.db = new Hyperbee(core, {
      keyEncoding: 'binary',
      extension: false,
      checkout,
      sessions: typeof core.session === 'function'
    })

    this.version = DEFAULT_AUTOBASE_VERSION
    this.members = 0
    this.pendingIndexers = []
    this.indexers = []
    this.heads = []
    this.views = []
    this.encryptionLength = 0
    this.entropy = null

    this.indexerUpdate = false

    this._empty = empty
    this._fork = 0
    this._length = 0
    this._changes = []
    this._indexerMap = new Map()
    this._clockUpdates = new Map()
  }

  static GENESIS_ENTROPY = GENESIS_ENTROPY

  static async getIndexedInfo(core, length) {
    const sys = new this(core.session())

    try {
      return await sys.getIndexedInfo(length)
    } finally {
      await sys.close()
    }
  }

  static async *flushes(core, { reverse, lt = core.length, gte = 0, wait = true } = {}) {
    if (lt <= 0) return

    // ensure block
    await core.get(lt - 1)
    const sys = new SystemView(core)

    try {
      for await (const data of sys.db.createHistoryStream({ lt, gte, wait, reverse: true })) {
        if (!b4a.equals(data.key, INFO_KEY)) continue
        const info = c.decode(Info, data.value)
        yield { length: data.seq + 1, info }
      }
    } finally {
      await sys.close()
    }
  }

  get bootstrapping() {
    return this.members === 0
  }

  async checkout(length) {
    const checkout = new SystemView(this.core.session(), {
      checkout: length,
      empty: length === 0
    })

    await checkout.ready()

    return checkout
  }

  async _open() {
    // this should NEVER fail, if so we have a bug elsewhere (should always be consistent)
    const info = this._empty
      ? null
      : await this.db.get('info', {
          valueEncoding: Info,
          keyEncoding: DIGEST,
          update: false,
          wait: false
        })
    await this._reset(info)
  }

  async _close() {
    await this.db.close()
  }

  async getIndexedInfo(length = this.core.signedLength) {
    if (this.opened === false) await this.ready()

    if (length === this.core.length) {
      return {
        version: this.version,
        members: this.members,
        pendingIndexers: this.pendingIndexers,
        indexers: this.indexers,
        heads: this.heads,
        views: this.views,
        encryptionLength: this.encryptionLength,
        entropy: this.entropy
      }
    }

    const node = length === 0 ? null : await this.db.getBySeq(length - 1)
    if (node === null) {
      return {
        version: DEFAULT_AUTOBASE_VERSION,
        members: 0,
        pendingIndexers: [],
        indexers: [],
        heads: [],
        views: [],
        encryptionLength: 0,
        entropy: null
      }
    }

    return c.decode(Info, node.value)
  }

  static sameIndexers(a, b) {
    if (a.length !== b.length) return false

    for (let i = 0; i < a.length; i++) {
      if (!b4a.equals(a[i].key, b[i].core.key)) return false
    }

    return true
  }

  sameIndexers(indexers) {
    return SystemView.sameIndexers(this.indexers, indexers)
  }

  async history(since) {
    const checkout = this.db.checkout(since)
    const seen = new Map()

    const nodes = []
    const updates = []

    const checkoutNode = since === 0 ? null : await this.db.getBySeq(since - 1)

    let prevInfo = checkoutNode === null ? null : c.decode(Info, checkoutNode.value)
    let updateBatch = 0

    for await (const data of this.db.createHistoryStream({ gte: since })) {
      if (b4a.equals(data.key, INFO_KEY)) {
        const info = c.decode(Info, data.value)

        updates.push({
          batch: updateBatch,
          indexers: prevInfo === null || !sameIndexers(info, prevInfo),
          systemLength: data.seq + 1
        })

        prevInfo = info
        updateBatch = 0
        continue
      }

      const key = data.key.subarray(2)
      const hex = b4a.toString(key, 'hex')
      const len = c.decode(Member, data.value).length

      if (!seen.has(hex)) {
        const node = await checkout.get(data.key)
        if (node === null) {
          seen.set(hex, 0)
        } else {
          const { length } = c.decode(Member, node.value)
          seen.set(hex, length)
        }
      }

      const prev = seen.get(hex)
      const batch = len - prev
      seen.set(hex, len)

      if (batch === 0) continue

      updateBatch += batch

      if (nodes.length > 0) {
        const top = nodes[nodes.length - 1]
        if (b4a.equals(top.key, key)) {
          top.length = len
          top.batch += batch
          continue
        }
      }

      nodes.push({
        key,
        length: len,
        batch
      })
    }

    await checkout.close()

    return { updates, nodes }
  }

  async update() {
    if (this.opened === false) await this.ready()

    if (this._fork === this.core.fork && this._length === this.core.length) return false

    await this._reset(
      this._empty ? null : await this.db.get('info', { valueEncoding: Info, keyEncoding: DIGEST })
    )
    return true
  }

  async _reset(info) {
    this.version = info === null ? DEFAULT_AUTOBASE_VERSION : info.value.version
    this.members = info === null ? 0 : info.value.members
    this.pendingIndexers = info === null ? [] : info.value.pendingIndexers
    this.indexers = info === null ? [] : info.value.indexers
    this.heads = info === null ? [] : info.value.heads
    this.views = info === null ? [] : info.value.views
    this.encryptionLength = info === null ? 0 : info.value.encryptionLength
    this.entropy = info === null ? null : info.value.entropy

    this.indexerUpdate = false
    this._indexerMap.clear()
    this._clockUpdates.clear()
    this._length = this.core.length
    this._fork = this.core.fork
    this._changes = []

    for (const idx of this.indexers) {
      this._indexerMap.set(b4a.toString(idx.key, 'hex'), idx)
    }
  }

  // helper used by apply-state
  flushLength() {
    const header = this.core.length ? 0 : 1 // account for header

    let updates = this._changes.length + this._clockUpdates.size
    for (const { key } of this._changes) {
      const hex = b4a.toString(key, 'hex')
      if (this._clockUpdates.has(hex)) updates-- // shared are skipped
    }

    return header + this.core.length + updates + 1
  }

  async flush(views) {
    const batch = this.db.batch({ update: false })

    for (let i = 0; i < this._changes.length; i++) {
      const c = this._changes[i]
      if (this._clockUpdates.has(b4a.toString(c.key, 'hex'))) continue
      await batch.put(c.key, c.value, { valueEncoding: Member, keyEncoding: MEMBERS })
    }

    for (const [hex, length] of this._clockUpdates) {
      const isIndexer = this._indexerMap.get(hex) !== undefined
      const key = b4a.from(hex, 'hex')

      const info = await this._get(key, 0)

      const value = { isIndexer, isRemoved: info ? info.isRemoved : true, length }
      await batch.put(key, value, { valueEncoding: Member, keyEncoding: MEMBERS })
    }

    if (this.indexerUpdate) {
      this._refreshEntropy(this.core.length + batch.length + 1)
    }

    this._clockUpdates.clear()

    let maxIndex = -1
    for (const view of views) {
      if (view.mappedIndex > maxIndex) maxIndex = view.mappedIndex
    }

    while (this.views.length > maxIndex + 1) this.views.pop()

    for (const view of views) {
      const length = view.core ? view.core.length : view.length
      if (!length) continue

      const v = { key: view.key, length }

      if (view.mappedIndex !== -1) {
        this.views[view.mappedIndex] = v
      } else {
        view.mappedIndex = this.views.push(v) - 1
      }
    }

    const info = {
      version: this.version,
      members: this.members,
      pendingIndexers: this.pendingIndexers,
      indexers: this.indexers,
      heads: this.heads,
      views: this.views,
      encryptionLength: this.encryptionLength,
      entropy: this.entropy
    }

    await batch.put('info', info, { valueEncoding: Info, keyEncoding: DIGEST })
    await batch.flush()

    this._length = this.core.length // should be ok
    this._changes = []

    if (this.indexerUpdate) this.indexerUpdate = false
  }

  getEntropy(indexers, length) {
    return generateEntropy(indexers, length, this.entropy)
  }

  _refreshEntropy(length) {
    if (this.version < 2) return
    this.entropy = this.getEntropy(this.indexers, length)
  }

  checkpoint() {
    return {
      version: this.version,
      members: this.members,
      pendingIndexers: this.pendingIndexers.slice(0),
      indexers: cloneNodes(this.indexers),
      heads: cloneNodes(this.heads),
      views: cloneNodes(this.views),
      indexerUpdate: this.indexerUpdate,
      encryptionLength: this.encryptionLength,
      entropy: this.entropy ? b4a.from(this.entropy) : null,
      changes: this._changes.slice(0),
      clockUpdates: new Map([...this._clockUpdates])
    }
  }

  applyCheckpoint(checkpoint) {
    this.version = checkpoint.version
    this.members = checkpoint.members
    this.pendingIndexers = checkpoint.pendingIndexers
    this.indexers = checkpoint.indexers
    this.heads = checkpoint.heads
    this.views = checkpoint.views
    this.indexerUpdate = checkpoint.indexerUpdate
    this.encryptionLength = checkpoint.encryptionLength
    this.entropy = checkpoint.entropy

    this._changes = checkpoint.changes
    this._clockUpdates = checkpoint.clockUpdates

    this._indexerMap = new Map()
    for (const idx of this.indexers) {
      this._indexerMap.set(b4a.toString(idx.key, 'hex'), idx)
    }
  }

  addHead(node) {
    const h = { key: node.writer.core.key, length: node.length }

    for (let i = 0; i < this.heads.length; i++) {
      const head = this.heads[i]

      if (!hasDependency(node, head)) {
        if (!b4a.equals(node.writer.core.key, head.key)) continue

        // todo: remove in next major because bug was fixed here:
        // https://github.com/holepunchto/autobase-next/pull/237

        // filter out any bad heads introduced by a bug to
        // prevent inconsistencies being written to the oplog
        if (head.length > h.length) return false
      }

      const popped = this.heads.pop()
      if (popped !== head) this.heads[i--] = popped
    }

    this.heads.push(h)

    const hex = b4a.toString(h.key, 'hex')

    this._clockUpdates.set(hex, h.length)

    if (this.pendingIndexers.length > 0) {
      for (let i = 0; i < this.pendingIndexers.length; i++) {
        if (!b4a.equals(this.pendingIndexers[i], h.key)) continue
        this._updateIndexer(h.key, h.length, true, i)
        return true
      }
    }

    const idx = this._indexerMap.get(hex)
    if (idx !== undefined) {
      idx.length = h.length
    }

    return false
  }

  _updateIndexer(key, length, isIndexer, i) {
    const hex = b4a.toString(key, 'hex')

    if (!isIndexer) {
      const existing = this._indexerMap.get(hex)
      if (existing) {
        this.indexerUpdate = true
        this.indexers.splice(this.indexers.indexOf(existing), 1)
        this._indexerMap.delete(hex)
      }
      return
    }

    for (; i < this.pendingIndexers.length; i++) {
      if (b4a.equals(this.pendingIndexers[i], key)) {
        break
      }
    }

    if (length === 0) {
      if (i >= this.pendingIndexers.length) this.pendingIndexers.push(key)
      return
    }

    if (i < this.pendingIndexers.length) {
      const top = this.pendingIndexers.pop()
      if (i < this.pendingIndexers.length) this.pendingIndexers[i] = top
    }

    const idx = this._indexerMap.get(hex)

    if (idx === undefined) {
      const newIdx = { key, length }
      this._indexerMap.set(hex, newIdx)
      this.indexers.push(newIdx)

      // bootstrap is "silently" added so that initial views have no prologue
      if (!this.bootstrapping) this.indexerUpdate = true
    } else {
      idx.length = length
    }
  }

  _seenLength(key) {
    return this._clockUpdates.get(b4a.toString(key, 'hex')) || 0
  }

  async ack(key) {
    const value = await this._get(key, 0)
    const length = this._seenLength(key)
    if (value && value.length === length) return

    const isIndexer = value ? value.isIndexer : false
    const isRemoved = value ? value.isRemoved : true

    this._changes.push({ key, value: { isIndexer, isRemoved, length } })
  }

  async add(key, { isIndexer = false, length = this._seenLength(key) } = {}) {
    let value = null
    let found = false
    let changed = true

    for (let i = this._changes.length - 1; i >= 0; i--) {
      const c = this._changes[i]
      if (b4a.equals(key, c.key)) {
        value = c.value
        found = true
        break
      }
    }

    if (!found) {
      const node = await this.db.get(key, { valueEncoding: Member, keyEncoding: MEMBERS })

      if (node) {
        value = node.value
        found = true
      }
    }

    let wasTracked = false
    let wasIndexer = false

    if (found) {
      if (!value.isRemoved) wasTracked = true
      if (value.isIndexer) wasIndexer = true
      if (length < value.length) length = value.length
      if (value.length === length && value.isIndexer === isIndexer && value.isRemoved === false)
        changed = false
    }

    if (changed) {
      this._changes.push({ key, value: { isIndexer, isRemoved: false, length } })
    }

    if (!wasTracked) this.members++
    if (wasIndexer || isIndexer) this._updateIndexer(key, length, isIndexer, 0)
  }

  async remove(key) {
    let isIndexer = false

    for (const idx of this.indexers) {
      isIndexer = b4a.equals(idx.key, key)
      if (isIndexer) break
    }

    if (isIndexer) this._updateIndexer(key, null, false, 0)

    let value = null
    let found = false

    for (let i = this._changes.length - 1; i >= 0; i--) {
      const c = this._changes[i]
      if (b4a.equals(key, c.key)) {
        value = c.value
        found = true
        break
      }
    }

    if (!found) {
      const node = await this.db.get(key, { valueEncoding: Member, keyEncoding: MEMBERS })
      if (node) {
        value = node.value
        found = true
      }
    }

    const changed = !found || !value.isRemoved
    const wasTracked = found && !value.isRemoved
    const length = found ? value.length : 0

    if (changed) {
      this._changes.push({ key, value: { isIndexer: false, isRemoved: true, length } })
    }

    if (wasTracked) this.members--

    return isIndexer
  }

  async linkable(key, length) {
    const len = this._seenLength(key)
    if (len > 0) return length > len

    const info = await this._get(key, 0)
    const prevLength = info ? info.length : 0

    return length > prevLength
  }

  async has(key, opts) {
    // could be optimised...
    return (await this.get(key, opts)) !== null
  }

  async _get(key, timeout) {
    let value = null
    let found = false

    for (let i = this._changes.length - 1; i >= 0; i--) {
      const c = this._changes[i]
      if (b4a.equals(key, c.key)) {
        value = c.value
        found = true
        break
      }
    }

    if (!found) {
      const node = await this.db.get(key, { timeout, valueEncoding: Member, keyEncoding: MEMBERS })
      if (node) {
        value = node.value
        found = true
      }
    }

    return found ? value : null
  }

  async get(key, opts = {}) {
    if (this._empty) return null

    let value = await this._get(key, opts.timeout || 0)

    if (opts.unflushed) {
      const hex = b4a.toString(key, 'hex')

      for (let i = this._changes.length - 1; i >= 0; i--) {
        const c = this._changes[i]
        if (b4a.equals(c.key, key)) value = c.value
      }

      if (this._clockUpdates.has(hex)) value.length = this._clockUpdates.get(hex)
    }

    return opts.onlyActive !== false || !value.isRemoved ? value : null
  }

  async hasLocal(key) {
    if (this._empty) return false
    try {
      const node = await this.db.get(key, {
        valueEncoding: Member,
        keyEncoding: MEMBERS,
        update: false,
        wait: false
      })
      return node !== null
    } catch {
      return false
    }
  }

  async getLocalLength(key) {
    if (this._empty) return 0
    try {
      const node = await this.db.get(key, {
        valueEncoding: Member,
        keyEncoding: MEMBERS,
        update: false,
        wait: false
      })
      return node === null ? 0 : node.value.length
    } catch {
      return 0
    }
  }

  list() {
    // note, NOT safe to use during apply atm
    return this.db.createReadStream({
      valueEncoding: Member,
      keyEncoding: MEMBERS
    })
  }

  async isIndexed(key, length) {
    const co = this.db.checkout(this.core.indexedLength)
    try {
      const node = await co.get(key, { valueEncoding: Member, keyEncoding: MEMBERS })
      return node !== null && node.value.length >= length
    } finally {
      await co.close()
    }
  }

  async fork(indexers, manifests, encryptionLength, views) {
    this.indexers = []
    this.pendingIndexers = []
    this.views = views

    if (this.version < 2) this.version = 2 // bump to enable entropy

    for (const { key } of indexers) {
      // todo: probably need to check isRemoved etc
      const { length } = await this.get(key)
      this.indexers.push({ key, length })
    }

    this._refreshEntropy(this.core.length)

    const blocks = []

    // truncate needs to respect hypercore batch
    let truncate = this.core.length - 1
    for await (const data of this.db.createHistoryStream({ lt: truncate, reverse: true })) {
      if (b4a.equals(data.key, INFO_KEY)) {
        truncate = data.seq + 1
        break
      }

      blocks.push(data)
    }

    await this.core.truncate(truncate, this.core.fork)

    const batch = this.db.batch({ update: false })
    await batch.ready()

    for (const { key, value } of blocks) {
      await batch.put(key, value)
    }

    const info = {
      version: this.version,
      members: this.members,
      pendingIndexers: this.pendingIndexers,
      indexers: this.indexers,
      heads: this.heads,
      views: this.views,
      encryptionLength,
      entropy: this.entropy
    }

    await batch.put('info', info, { valueEncoding: Info, keyEncoding: DIGEST })
    await batch.flush()

    await this._reset(await this.db.get('info', { valueEncoding: Info, keyEncoding: DIGEST }))

    return truncate
  }
}

function hasDependency(node, dep) {
  for (const h of node.actualHeads) {
    if (sameNode(h, dep)) return true
  }
  return false
}

function sameNode(a, b) {
  return b4a.equals(a.key, b.key) && a.length === b.length
}

function sameIndexers(a, b) {
  if (a.views.length > 0 && b.views.length > 0) return b4a.equals(a.views[0].key, b.views[0].key)
  if (a.indexers.length !== b.indexers.length) return false

  for (let i = 0; i < a.indexers.length; i++) {
    if (!b4a.equals(a.indexers[i].key, b.indexers[i].key)) return false
  }

  return true
}

function cloneNodes(arr) {
  const c = []
  for (let i = 0; i < arr.length; i++) {
    c.push({ key: arr[i].key, length: arr[i].length })
  }
  return c
}

function generateEntropy(indexers, length, entropy) {
  const buffer = b4a.alloc(8 + 32 + indexers.length * 32)
  const state = { start: 0, end: buffer.byteLength, buffer }

  c.uint64.encode(state, length)
  c.fixed32.encode(state, entropy || GENESIS_ENTROPY)
  for (const { key } of indexers) c.fixed32.encode(state, key)

  return crypto.hash([NS_ENTROPY, buffer])
}
const safetyCatch = require('safety-catch')

const MAX_WAIT = 2 * 60 * 1000
const DEFAULT_INTERVAL = 10 * 1000

module.exports = class Timer {
  constructor(handler, interval, opts = {}) {
    this.handler = handler || noop
    this.interval = interval || DEFAULT_INTERVAL
    this.limit = opts.limit || MAX_WAIT

    this._executing = null

    this._limit = random2over1(this.limit)
    this._timer = null
    this._resolve = null
    this._start = 0
    this._stopped = false
    this._asap = false
    this._standalone = new Set()

    this._unref = opts.unref !== false
    this._timerCallback = this._executeBackground.bind(this)
  }

  _executeBackground() {
    this._executing = this._execute()
    this._executing.catch(safetyCatch) // make sure it doesnt crash in the bg
  }

  async _execute() {
    this._asap = false
    await this.handler()
    this._start = 0
    this._executing = null
    this.bump()
  }

  bump() {
    if (this._stopped || this._executing || this._asap) return

    if (!this._start) this._start = Date.now()
    else if (Date.now() - this._start > this._limit) return

    const interval = random2over1(this.interval)

    clearTimeout(this._timer)
    this._timer = setTimeout(this._timerCallback, interval)
    if (this._unref && this._timer.unref) this._timer.unref()
  }

  async trigger() {
    if (this._stopped) return
    if (this._executing) await this._executing
    if (this._stopped) return

    clearTimeout(this._timer)
    this._timer = null

    this._executeBackground()
    await this._executing
  }

  async flush() {
    if (this._executing) await this._executing
  }

  // business-as-usual
  bau() {
    if (!this._asap) return
    this._asap = false
    this.bump()
  }

  asap() {
    if (this._asap) return
    this._asap = true

    const interval = Math.floor((Math.random() * this.interval) / 3)
    clearTimeout(this._timer)
    this._timer = setTimeout(this._timerCallback, interval)
    if (this._unref && this._timer.unref) this._timer.unref()
  }

  stop() {
    if (this._timer) clearTimeout(this._timer)
    this._timer = null
    this._start = 0
    this._asap = false
    this._stopped = true

    for (const { timer, resolve } of this._standalone) {
      clearTimeout(timer)
      resolve()
    }

    this._standalone.clear()
  }

  asapStandalone() {
    const interval = Math.floor((Math.random() * this.interval) / 3)
    return new Promise((resolve) => {
      const ref = { timer: null, resolve }
      ref.timer = setTimeout(resolveStandalone, interval, ref, this._standalone)
      if (ref.timer.unref) ref.timer.unref()
      this._standalone.add(ref)
    })
  }

  unref() {
    if (this._timer && this._timer.unref) this._timer.unref()
  }
}

function resolveStandalone(ref, set) {
  set.delete(ref)
  ref.resolve()
}

// random value x between n <= x < 2n
function random2over1(n) {
  return Math.floor(n + Math.random() * n)
}

function noop() {}
const b4a = require('b4a')
const assert = require('nanoassert')

module.exports = class TopoList {
  constructor() {
    this.tip = []
    this.undo = 0
    this.shared = 0
  }

  static compare(a, b) {
    return cmp(a, b)
  }

  static add(node, indexed, offset) {
    addSorted(node, indexed, offset)
  }

  mark() {
    this.shared = this.tip.length
    this.undo = 0
  }

  // todo: bump to new api that just tracks undo
  flush(indexed = []) {
    if (indexed.length) this._applyIndexed(indexed)

    const u = {
      shared: this.shared,
      undo: this.undo,
      length: indexed.length + this.tip.length,
      indexed,
      tip: this.tip
    }

    this.mark()

    return u
  }

  print() {
    return this.tip.map((n) => n.writer.core.key.toString() + n.length)
  }

  _applyIndexed(nodes) {
    assert(nodes.length <= this.tip.length, 'Indexed batch cannot exceed tip')

    let shared = 0

    for (; shared < nodes.length; shared++) {
      if (this.tip[shared] !== nodes[shared]) break
    }

    // reordering
    if (shared < nodes.length) this._track(shared)

    const tip = []

    for (let i = shared; i < this.tip.length; i++) {
      const node = this.tip[i]
      if (node.yielded) continue
      const s = addSorted(node, tip, 0)
      if (s === tip.length - 1) continue
      this._track(shared + s)
    }

    this.tip = tip
  }

  add(node) {
    const shared = addSorted(node, this.tip, 0)
    this._track(shared)
  }

  _track(shared) {
    if (shared < this.shared) {
      this.undo += this.shared - shared
      this.shared = shared
    }
  }
}

function hasOptimisticDeps(node) {
  for (const d of node.dependencies) {
    if (d.optimistic) return true
  }
  return false
}

// this can be optimised to only return optimistic nodes that we will "touch" when moving down the node
function getOptimisticDeps(node, list) {
  const deps = new Set()
  const stack = [node]

  while (stack.length > 0) {
    const next = stack.pop()
    if (deps.has(next)) continue
    if (next.optimistic && next !== node) deps.add(next)
    for (const d of next.dependencies) {
      if (d.optimistic) stack.push(d)
    }
  }

  const result = []

  for (let i = list.length - 1; deps.size !== result.length && i >= 0; i--) {
    const n = list[i]
    if (deps.has(n)) result.push(n)
  }

  return result.reverse()
}

function addSortedOptimistic(node, list, offset) {
  const opt = getOptimisticDeps(node, list)
  const pos = new Uint32Array(opt.length)

  for (let i = 0; i < opt.length; i++) {
    const n = opt[i]
    pos[i] = n.index
    moveDown(n, list, offset)
  }

  moveDownAndUp(node, list, offset)

  for (let i = opt.length - 1; i >= 0; i--) {
    moveOptimisticUp(opt[i], list, offset)
  }

  let shared = node.index

  for (let i = 0; i < opt.length; i++) {
    const idx = pos[i]
    const n = opt[i]

    if (idx === n.index) continue

    if (idx < shared) shared = idx
    if (n.index < shared) shared = n.index
  }

  return shared
}

function addSorted(node, list, offset) {
  list.push(node)
  node.index = list.length - 1

  // "slow" path, 1% of nodes
  if (hasOptimisticDeps(node)) return addSortedOptimistic(node, list, offset)

  moveDownAndUp(node, list, offset)
  return node.index
}

function moveDown(node, list, offset) {
  while (node.index > offset) {
    const prev = list[node.index - 1]
    if (links(node, prev)) break
    list[(prev.index = node.index)] = prev
    list[--node.index] = node
  }
}

function moveOptimisticUp(node, list, offset) {
  // if optimistic move all the way up
  while (node.index < list.length - 1) {
    const next = list[node.index + 1]
    if (links(next, node)) break
    list[(next.index = node.index)] = next
    list[++node.index] = node
  }

  // stable sort in case multiple children
  while (node.index > offset) {
    const prev = list[node.index - 1]
    if (!prev.optimistic) break
    const c = cmp(prev, node)
    if (c <= 0) break
    list[(prev.index = node.index)] = prev
    list[--node.index] = node
  }
}

function moveNonOptimisticUp(node, list, offset) {
  // stable sort against next non optimistic node
  while (node.index < list.length - 1) {
    const next = list[node.index + 1]
    const c = cmpNonOptimistic(node, next, list)
    if (c <= 0) break
    list[(next.index = node.index)] = next
    list[++node.index] = node
  }
}

function moveDownAndUp(node, list, offset) {
  moveDown(node, list, offset)

  if (node.optimistic) moveOptimisticUp(node, list, offset)
  else moveNonOptimisticUp(node, list, offset)
}

function links(a, b) {
  if (b.dependents.has(a)) return true
  return a.length > 0 && b.length === a.length - 1 && a.writer === b.writer
}

function cmpNonOptimistic(a, b, list) {
  if (!b.optimistic) return cmp(a, b)

  for (let i = b.index + 1; i < list.length; i++) {
    const node = list[i]
    if (!node.optimistic) return cmp(a, node)
  }

  return -1
}

function cmp(a, b) {
  return links(b, a) ? -1 : cmpUnlinked(a, b)
}

function cmpUnlinked(a, b) {
  const c = b4a.compare(a.writer.core.key, b.writer.core.key)
  return c === 0 ? (a.length < b.length ? -1 : 1) : c
}
module.exports = class UpdateChanges {
  constructor(base) {
    this.base = base
    this.byName = new Map()
    this.tracking = null
  }

  get discoveryKey() {
    return this.base.discoveryKey
  }

  get key() {
    return this.base.key
  }

  get id() {
    return this.base.id
  }

  get system() {
    return this.base.system
  }

  track(state) {
    this.tracking = []
    this.byName.clear()

    if (!state) return

    for (const v of state.views) {
      if (v.ref) this._add(v.ref)
    }

    this._add(state.systemView.ref)
    this._add(state.encryptionView.ref)
  }

  _add(ref) {
    const from = ref.batch.length
    const inf = { ref, from }
    ref.shared = from
    this.tracking.push(inf)
  }

  finalise() {
    if (this.tracking === null) return

    for (const { ref, from } of this.tracking) {
      const core = ref.atomicBatch || ref.batch
      this.byName.set(ref.name, {
        from,
        to: core.length,
        shared: ref.shared
      })
    }

    this.tracking = null
  }

  get(name) {
    return this.byName.get(name)
  }
}
const crypto = require('hypercore-crypto')
const c = require('compact-encoding')
const b4a = require('b4a')

const { OPLOG_VERSION } = require('./caps.js')
const { OplogMessage } = require('./messages.js')
const { EncryptionView } = require('./encryption.js')

module.exports = {
  encodeValue,
  decodeValue
}

function encodeValue(value, opts = {}) {
  const state = { start: 0, end: 0, buffer: null }

  const message = {
    version: opts.version || OPLOG_VERSION,
    digest: null,
    checkpoint: null,
    optimistic: !!opts.optimistic,
    node: {
      heads: opts.heads || [],
      batch: 1,
      value
    }
  }

  OplogMessage.preencode(state, message)

  if (opts.padding) {
    state.start = opts.padding
    state.end += opts.padding
  }

  state.buffer = b4a.alloc(state.end)

  OplogMessage.encode(state, message)

  if (!opts.encrypted) return state.buffer

  if (!opts.optimistic) {
    throw new Error('Encoding an encrypted value is not supported')
  }

  const padding = b4a.alloc(16) // min hash length is 16
  crypto.hash(state.buffer, padding)
  padding[0] = 0

  return b4a.concat([padding.subarray(0, 8), state.buffer])
}

async function decodeValue(value, { autobase, encryptionKey, key, manifest, index = 0 } = {}) {
  if (encryptionKey) {
    const e = new EncryptionView({ encryptionKey, bootstrap: autobase })
    const w = e.getWriterEncryption()

    await w.decrypt(index, value, { key, manifest })
    value = value.subarray(8)
  }

  const op = c.decode(OplogMessage, value)
  return op.node.value
}
const b4a = require('b4a')
const c = require('compact-encoding')
const safetyCatch = require('safety-catch')
const ReadyResource = require('ready-resource')

const WakeupEntry = {
  preencode(state, m) {
    c.fixed32.preencode(state, m.key)
    c.uint.preencode(state, m.length)
  },
  encode(state, m) {
    c.fixed32.encode(state, m.key)
    c.uint.encode(state, m.length)
  },
  decode(state) {
    return {
      key: c.fixed32.decode(state),
      length: c.uint.decode(state)
    }
  }
}

module.exports = class AutoWakeup extends ReadyResource {
  constructor(base) {
    super()

    this.base = base
    this.flushing = null

    this._rootStore = this.base.store
    this._addBound = this.add.bind(this)
    this._preupdateBound = this._preupdate.bind(this)
    this._needsFlush = false
    this._map = new Map()
  }

  [Symbol.iterator]() {
    return this._map.values()
  }

  async _preupdate(batch, key) {
    this.queue(key, batch.length)
    await this.flush()
    this.base._onwakeup()
  }

  async _save() {
    const slab = b4a.allocUnsafe(8 + this._map.size * 40) // 32 + 8
    const state = { start: 0, end: 0, buffer: slab }

    c.uint.encode(state, this._map.size)
    for (const m of this._map.values()) WakeupEntry.encode(state, m)

    await this.base.local.setUserData('autobase/wakeup', slab.subarray(0, state.start))
  }

  async _load() {
    const buffer = await this.base.local.getUserData('autobase/wakeup')
    if (!buffer) return

    const state = { start: 0, end: buffer.byteLength, buffer }

    let len = c.uint.decode(state)
    while (len-- > 0) {
      const m = WakeupEntry.decode(state)
      this._map.set(b4a.toString(m.key, 'hex'), m)
    }
  }

  async _open() {
    await this._load()

    this._rootStore.watch(this._addBound)

    for (const core of this._rootStore.cores) {
      if (core.opened === false) await core.ready().catch(noop)
      if (!core.closing) this.add(core)
    }
  }

  async _close() {
    this._rootStore.unwatch(this._addBound)

    for (const core of this._rootStore.cores) {
      if (core.opened && !core.closing) this.remove(core)
    }

    this._map.clear()

    while (this.flushing) {
      try {
        await this.flushing
      } catch {}
    }
  }

  queue(key, length) {
    const hex = b4a.toString(key, 'hex')
    const m = this._map.get(hex)

    if (m && m.length > length) {
      return false
    }

    this._needsFlush = true
    this._map.set(hex, { key, length })

    return true
  }

  unqueue(key, length) {
    const hex = b4a.toString(key, 'hex')
    const m = this._map.get(hex)

    if (!m) return true
    if (m.length > length) return false

    this._needsFlush = true
    this._map.delete(hex)

    return true
  }

  async flush() {
    if (this.closing) throw new Error('Closing')

    // wait for someone
    if (this.flushing) await this.flushing

    // if another still active they flushed us
    if (this.flushing) return this.flushing

    if (this._needsFlush === false) return
    this._needsFlush = false

    try {
      this.flushing = this._save()
      return await this.flushing
    } finally {
      this.flushing = null
    }
  }

  add(core) {
    return this._add(core).catch(safetyCatch)
  }

  remove(core) {
    return this._remove(core)
  }

  async _add(core) {
    if (core.opened === false) await core.ready()
    if (core.closing) return false

    // local writer, no need
    if (core === this.base.local.core) return false

    const rx = core.storage.read()

    const referrerPromise = rx.getUserData('referrer')
    const viewPromise = rx.getUserData('autobase/view')

    rx.tryFlush()

    const [referrer, view] = await Promise.all([referrerPromise, viewPromise])
    if (view) return false

    if (referrer === null || !b4a.equals(referrer, this.base.key)) return false

    core.preupdate = this._preupdateBound

    return true
  }

  _remove(core) {
    if (core.preupdate !== this._preupdateBound) return false
    core.preupdate = null
    return true
  }
}

function noop() {}
const c = require('compact-encoding')
const b4a = require('b4a')
const ReadyResource = require('ready-resource')
const assert = require('nanoassert')
const SignalPromise = require('signal-promise')

const Linearizer = require('./linearizer.js')
const NodeBuffer = require('./node-buffer.js')

const MAX_PRELOAD = 4
const MAX_PREFETCH = 256

module.exports = class Writer extends ReadyResource {
  constructor(base, core, length, isRemoved) {
    super()

    this.base = base
    this.core = core
    this.isRemoved = isRemoved
    this.updated = false
    this.range = null
    this.nodes = new NodeBuffer(length)
    this.node = null
    this.isActive = false
    this.isCurrentlyCoupled = false
    this.isCoupled = false // maintained by updateBootstrapWriters
    this.isBootstrap = false // maintained by updateBootstrapWriters
    this.isActiveIndexer = false
    this.available = length
    this.length = length
    this.seenLength = 0
    this.recover = false
    this.frozen = false

    this.syncSignal = null
  }

  _pause() {
    if (!this.range) return
    this.range.destroy()
    this.range = null
  }

  _resume() {
    if (this.range) {
      // if we didnt fill up the preload buffer yet, do not commit to more work
      if (this.range.range.end === this.nodes.length + MAX_PREFETCH) return
      this.range.destroy()
    }
    this.range = this.core.download({
      start: this.nodes.length,
      end: this.nodes.length + MAX_PREFETCH,
      linear: true
    })
  }

  _updateCoupling() {
    if (!this.base._coupler || this.isCoupled === this.isCurrentlyCoupled) return

    if (this.isCurrentlyCoupled) this.base._coupler.remove(this.core)
    else this.base._coupler.add(this.core)

    this.isCurrentlyCoupled = this.isCoupled
  }

  _removeCouple() {
    if (this.base._coupler && !this.isCoupled && this.isCurrentlyCoupled) {
      this.isCurrentlyCoupled = false
      this.base._coupler.remove(this.core)
    }
  }

  updateActivity() {
    if (!this.core.opened) return

    if (this.seenLength > this.core.length || this.length < this.core.length || this.isBootstrap) {
      // if we have seen a later core, or if we are behind, or if bootstrap
      this.isActive = true
      this.core.setActive(true)
    } else if (this.length === this.core.length) {
      // things look steady
      this.isActive = false
      this.core.setActive(false)
    }

    this._updateCoupling()

    if (this.core.writable) return

    if (this.base.isFastForwarding() || !this.isActive) {
      this._pause()
    } else {
      this._resume()
    }
  }

  setBootstrap(bool) {
    this.isBootstrap = bool
    this.updateActivity()
  }

  seen(length) {
    if (length > this.seenLength) this.seenLength = length
    this.updateActivity()
  }

  waitForSynced() {
    if (this.core.length === this.length) return Promise.resolve()
    if (this.syncSignal === null) this.syncSignal = new SignalPromise()
    return this.syncSignal.wait()
  }

  async _open() {
    await this.core.ready()
    await this.core.setUserData('referrer', this.base.key)

    // base might be closing here
    if (this.base.closing) return

    // remove later
    this.recover = autoRecover(this.core)

    // add it again incase it wasn't readied before, only needed if this is the first time we set the referrer...
    await this.base._wakeup.add(this.core.core)

    this.updateActivity()

    if (this.core.length > this.length) this.base._queueBump()

    this.base.emit('writer', this)
  }

  _close() {
    if (this.syncSignal !== null) this.syncSignal.notify()
    return this.core.close()
  }

  get indexed() {
    return this.nodes.offset
  }

  idle() {
    return this.length === this.available && this.length === this.core.length && this.core.opened
  }

  flushed() {
    // TODO: prop a cleaner way to express this...
    return (
      this.seenLength <= this.length &&
      this.length === this.available &&
      this.length === this.core.length &&
      this.shiftable() === false &&
      !this.core.core.upgrading &&
      this.core.opened
    )
  }

  compare(writer) {
    return b4a.compare(this.core.key, writer.core.key)
  }

  head() {
    return this.nodes.get(this.length - 1)
  }

  advance() {
    if (this.syncSignal !== null && this.length + 1 === this.core.length) this.syncSignal.notify()
    return this.length < this.available ? this.nodes.get(this.length++) : null
  }

  shiftable() {
    return this.length > this.nodes.offset
  }

  shift() {
    if (this.shiftable() === false) return false

    let node = this._shiftAndClear()
    while (node.batch > 1) node = this._shiftAndClear()

    return true
  }

  get(seq) {
    return seq < this.length ? this.nodes.get(seq) : null
  }

  append(value, heads, batch, dependencies, optimistic) {
    const node = Linearizer.createNode(
      this,
      this.nodes.length + 1,
      value,
      heads,
      batch,
      dependencies,
      optimistic
    )

    node.actualHeads = node.heads.slice(0)

    this.nodes.push(node)
    this.available++
    this.length++

    return node
  }

  async update(boot) {
    if (this.opened === false) await this.ready()
    if (this.frozen) return false

    // if this is a boot node, DO NOT, preload as that will make it load
    // and reject nodes based on the tmp state of the system.
    // prop needs a better solution but this works for now
    const preload = boot ? 1 : MAX_PRELOAD

    while (this.available - this.length < preload) {
      // quick sanity check
      if (this.nodes.length === this.core.length || this.core.length === 0) break

      // load next node
      if (this.node === null && !(await this._loadNextNode())) break
      if (!(await this._ensureNodeDependencies(boot))) break

      if (this.recover) this.node.value = null

      this.nodes.push(this.node)
      if (this.node.batch === 1) this.available = this.nodes.length
      this.node = null
    }

    this.updateActivity()

    return this.length < this.available
  }

  _shiftAndClear() {
    const node = this.nodes.shift()
    node.clear()
    return node
  }

  async _loadNextNode() {
    const seq = this.nodes.length

    if (!(await this.core.has(seq))) return false

    try {
      const { node, optimistic, trace } = await this.core.get(seq, { wait: false })

      const value = node.value == null ? null : c.decode(this.base.valueEncoding, node.value)
      this.node = Linearizer.createNode(
        this,
        seq + 1,
        value,
        node.heads,
        node.batch,
        new Set(),
        optimistic,
        trace
      )
      return true
    } catch (err) {
      this.frozen = true
      throw err
    }
  }

  async _ensureNodeDependencies(boot) {
    while (this.node.dependencies.size < this.node.heads.length) {
      const rawHead = this.node.heads[this.node.dependencies.size]

      const headWriter = await this.base._getWriterByKey(
        rawHead.key,
        -1,
        rawHead.length,
        true,
        false,
        boot
      )

      if (headWriter !== this && (headWriter === null || headWriter.length < rawHead.length)) {
        if (!boot) this.base._ensureWakeup(headWriter)
        return false
      }

      let headNode = headWriter.nodes.get(rawHead.length - 1)

      // could be a stub node
      if (!headNode) {
        for (const node of this.base.linearizer.heads) {
          if (!compareHead(node, rawHead)) continue
          headNode = node
          break
        }
      }

      // TODO: generalise DAG validation and freeze the writer
      assert(!this.node.dependencies.has(headNode), 'Corrupted DAG')

      // TODO: better way to solve the stub check is to never mutate heads below
      if (headNode === null) {
        // already yielded
        this.node.heads.splice(this.node.dependencies.size, 1)
        continue
      }

      this.node.dependencies.add(headNode)
    }

    // always link previous node if it's not indexed
    const offset = this.node.length - 1
    if (offset > this.indexed) {
      this.node.dependencies.add(this.nodes.get(offset - 1))
    }

    return true
  }
}

function compareHead(node, head) {
  if (node.length !== head.length) return false
  return b4a.equals(node.writer.core.key, head.key)
}

// this is a list of peers we bugged in the btc and planb room.
// adding them here so migration can run, can be removed in a month or so from time of commit
// note, no security implications of this, we just null them out.

function autoRecover(core) {
  assert(core.opened)

  switch (core.id) {
    case 'ghrpexaboutdm46ombqho7mroxknassnntrxx3cubfux4qi6w6hy':
    case 'qoaanao71s4he1rcd197d336qepykk4467geo1uq8cwnzmpb786o':
    case 'fomhdxgn4j4tzjqy6y7iskhffimzokt7kraddyd8orcht3r8q61o':
    case 'd8f5taxxrit51apftoi38e5b86hb98cgfd7dfp3uo1uoh95qt49o':
    case 'objyf75uggsqpjcut69xdgj46ks8r71jjrq7oxdfsz95sstchkno':
      return true
  }

  return false
}
{
  "name": "autobase",
  "version": "7.27.3",
  "description": "A multiwriter data structure for Hypercore",
  "main": "index.js",
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test/all.js",
    "test:encrypted": "prettier . --check && brittle test/all.js --encrypt-all",
    "test:fixtures": "prettier . --check && brittle test/fixtures/tests/*.js",
    "test:bare": "bare test/all.js",
    "fuzz:generated": "brittle test/reference/fuzz/generated/*.js",
    "fuzz:main": "node test/fuzz/index.js",
    "fuzz": "node test/reference/fuzz/fuzz.js",
    "generate-fixtures": "node test/fixtures/generate/all.js"
  },
  "files": [
    "index.js",
    "lib/**",
    "encoding/**"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/autobase.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/autobase/issues"
  },
  "homepage": "https://github.com/holepunchto/autobase#readme",
  "dependencies": {
    "b4a": "^1.6.1",
    "bare-events": "^2.2.0",
    "compact-encoding": "^2.16.0",
    "core-coupler": "^2.0.0",
    "debounceify": "^1.0.0",
    "encryption-encoding": "^1.0.3",
    "hyperbee": "^2.22.0",
    "hypercore": "^11.27.12",
    "hypercore-crypto": "^3.4.0",
    "hypercore-id-encoding": "^1.2.0",
    "hyperschema": "^1.12.1",
    "index-encoder": "^3.3.2",
    "nanoassert": "^2.0.0",
    "protomux-wakeup": "^2.0.0",
    "ready-resource": "^1.0.0",
    "resolve-reject-promise": "^1.1.0",
    "safety-catch": "^1.0.2",
    "scope-lock": "^1.2.4",
    "signal-promise": "^1.0.3",
    "sodium-universal": "^5.0.1",
    "sub-encoder": "^2.1.1",
    "tiny-buffer-map": "^1.1.1"
  },
  "devDependencies": {
    "autobase-test-helpers": "^3.0.0",
    "blind-encryption-sodium": "^2.0.0",
    "brittle": "^3.1.1",
    "corestore": "^7.9.1",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "rache": "^1.0.0",
    "same-data": "^1.0.0",
    "task-backoff": "^1.0.0",
    "test-tmp": "^1.2.0",
    "uncaughts": "^1.1.0"
  },
  "standard": {
    "ignore": [
      "**/test/fuzz/generated/**",
      "**/test/reference/**",
      "example.mjs"
    ]
  }
}
function isBuffer(value) {
  return Buffer.isBuffer(value) || value instanceof Uint8Array
}

function isEncoding(encoding) {
  return Buffer.isEncoding(encoding)
}

function alloc(size, fill, encoding) {
  return Buffer.alloc(size, fill, encoding)
}

function allocUnsafe(size) {
  return Buffer.allocUnsafe(size)
}

function allocUnsafeSlow(size) {
  return Buffer.allocUnsafeSlow(size)
}

function byteLength(string, encoding) {
  return Buffer.byteLength(string, encoding)
}

function compare(a, b) {
  return Buffer.compare(a, b)
}

function concat(buffers, totalLength) {
  return Buffer.concat(buffers, totalLength)
}

function copy(source, target, targetStart, start, end) {
  return toBuffer(source).copy(target, targetStart, start, end)
}

function equals(a, b) {
  return toBuffer(a).equals(b)
}

function fill(buffer, value, offset, end, encoding) {
  return toBuffer(buffer).fill(value, offset, end, encoding)
}

function from(value, encodingOrOffset, length) {
  return Buffer.from(value, encodingOrOffset, length)
}

function includes(buffer, value, byteOffset, encoding) {
  return toBuffer(buffer).includes(value, byteOffset, encoding)
}

function indexOf(buffer, value, byfeOffset, encoding) {
  return toBuffer(buffer).indexOf(value, byfeOffset, encoding)
}

function lastIndexOf(buffer, value, byteOffset, encoding) {
  return toBuffer(buffer).lastIndexOf(value, byteOffset, encoding)
}

function swap16(buffer) {
  return toBuffer(buffer).swap16()
}

function swap32(buffer) {
  return toBuffer(buffer).swap32()
}

function swap64(buffer) {
  return toBuffer(buffer).swap64()
}

function toBuffer(buffer) {
  if (Buffer.isBuffer(buffer)) return buffer
  return Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

function toString(buffer, encoding, start, end) {
  return toBuffer(buffer).toString(encoding, start, end)
}

function write(buffer, string, offset, length, encoding) {
  return toBuffer(buffer).write(string, offset, length, encoding)
}

function readDoubleBE(buffer, offset) {
  return toBuffer(buffer).readDoubleBE(offset)
}

function readDoubleLE(buffer, offset) {
  return toBuffer(buffer).readDoubleLE(offset)
}

function readFloatBE(buffer, offset) {
  return toBuffer(buffer).readFloatBE(offset)
}

function readFloatLE(buffer, offset) {
  return toBuffer(buffer).readFloatLE(offset)
}

function readInt32BE(buffer, offset) {
  return toBuffer(buffer).readInt32BE(offset)
}

function readInt32LE(buffer, offset) {
  return toBuffer(buffer).readInt32LE(offset)
}

function readUInt32BE(buffer, offset) {
  return toBuffer(buffer).readUInt32BE(offset)
}

function readUInt32LE(buffer, offset) {
  return toBuffer(buffer).readUInt32LE(offset)
}

function writeDoubleBE(buffer, value, offset) {
  return toBuffer(buffer).writeDoubleBE(value, offset)
}

function writeDoubleLE(buffer, value, offset) {
  return toBuffer(buffer).writeDoubleLE(value, offset)
}

function writeFloatBE(buffer, value, offset) {
  return toBuffer(buffer).writeFloatBE(value, offset)
}

function writeFloatLE(buffer, value, offset) {
  return toBuffer(buffer).writeFloatLE(value, offset)
}

function writeInt32BE(buffer, value, offset) {
  return toBuffer(buffer).writeInt32BE(value, offset)
}

function writeInt32LE(buffer, value, offset) {
  return toBuffer(buffer).writeInt32LE(value, offset)
}

function writeUInt32BE(buffer, value, offset) {
  return toBuffer(buffer).writeUInt32BE(value, offset)
}

function writeUInt32LE(buffer, value, offset) {
  return toBuffer(buffer).writeUInt32LE(value, offset)
}

module.exports = {
  isBuffer,
  isEncoding,
  alloc,
  allocUnsafe,
  allocUnsafeSlow,
  byteLength,
  compare,
  concat,
  copy,
  equals,
  fill,
  from,
  includes,
  indexOf,
  lastIndexOf,
  swap16,
  swap32,
  swap64,
  toBuffer,
  toString,
  write,
  readDoubleBE,
  readDoubleLE,
  readFloatBE,
  readFloatLE,
  readInt32BE,
  readInt32LE,
  readUInt32BE,
  readUInt32LE,
  writeDoubleBE,
  writeDoubleLE,
  writeFloatBE,
  writeFloatLE,
  writeInt32BE,
  writeInt32LE,
  writeUInt32BE,
  writeUInt32LE
}
{
  "name": "b4a",
  "version": "1.8.0",
  "description": "Bridging the gap between buffers and typed arrays",
  "exports": {
    "./package": "./package.json",
    ".": {
      "react-native": "./react-native.js",
      "browser": "./browser.js",
      "default": "./index.js"
    }
  },
  "files": [
    "browser.js",
    "index.js",
    "react-native.js",
    "lib"
  ],
  "scripts": {
    "test": "npm run lint && npm run test:bare && npm run test:node",
    "test:bare": "bare test.mjs",
    "test:node": "node test.mjs",
    "lint": "prettier . --check"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/b4a.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/b4a/issues"
  },
  "homepage": "https://github.com/holepunchto/b4a#readme",
  "devDependencies": {
    "brittle": "^3.5.2",
    "nanobench": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "peerDependencies": {
    "react-native-b4a": "*"
  },
  "peerDependenciesMeta": {
    "react-native-b4a": {
      "optional": true
    }
  }
}
const ESC = '\x1b'
const CSI = ESC + '['
const SGR = (n) => CSI + n + 'm'

exports.constants = {
  ESC,
  CSI,
  SGR
}

// https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_(Control_Sequence_Introducer)_sequences

exports.cursorHide = CSI + '?25l'
exports.cursorShow = CSI + '?25h'

exports.cursorUp = function cursorUp(n = 1) {
  return CSI + n + 'A'
}

exports.cursorDown = function cursorDown(n = 1) {
  return CSI + n + 'B'
}

exports.cursorForward = function cursorForward(n = 1) {
  return CSI + n + 'C'
}

exports.cursorBack = function cursorBack(n = 1) {
  return CSI + n + 'D'
}

exports.cursorNextLine = function cursorNextLine(n = 1) {
  return CSI + n + 'E'
}

exports.cursorPreviousLine = function cursorPreviousLine(n = 1) {
  return CSI + n + 'F'
}

exports.cursorPosition = function cursorPosition(column, row = 0) {
  if (row === 0) return CSI + (column + 1) + 'G'

  return CSI + (row + 1) + ';' + (column + 1) + 'H'
}

exports.eraseDisplayEnd = CSI + 'J'
exports.eraseDisplayStart = CSI + '1J'
exports.eraseDisplay = CSI + '2J'
exports.eraseLineEnd = CSI + 'K'
exports.eraseLineStart = CSI + '1K'
exports.eraseLine = CSI + '2K'

exports.scrollUp = function scrollUp(n = 1) {
  return CSI + n + 'S'
}

exports.scrollDown = function scrollDown(n = 1) {
  return CSI + n + 'T'
}

// https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_(Select_Graphic_Rendition)_parameters

exports.modifierReset = SGR(0)
exports.modifierBold = SGR(1)
exports.modifierDim = SGR(2)
exports.modifierItalic = SGR(3)
exports.modifierUnderline = SGR(4)
exports.modifierNormal = SGR(22)
exports.modifierNotItalic = SGR(23)
exports.modifierNotUnderline = SGR(24)

// https://en.wikipedia.org/wiki/ANSI_escape_code#Colors

exports.colorBlack = SGR(30)
exports.colorRed = SGR(31)
exports.colorGreen = SGR(32)
exports.colorYellow = SGR(33)
exports.colorBlue = SGR(34)
exports.colorMagenta = SGR(35)
exports.colorCyan = SGR(36)
exports.colorWhite = SGR(37)
exports.colorDefault = SGR(39)
exports.colorBrightBlack = SGR(90)
exports.colorBrightRed = SGR(91)
exports.colorBrightGreen = SGR(92)
exports.colorBrightYellow = SGR(93)
exports.colorBrightBlue = SGR(94)
exports.colorBrightMagenta = SGR(95)
exports.colorBrightCyan = SGR(96)
exports.colorBrightWhite = SGR(97)
{
  "name": "bare-ansi-escapes",
  "version": "2.2.3",
  "description": "Parse and produce ANSI escape sequences",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./key-decoder": {
      "types": "./key-decoder.d.ts",
      "default": "./key-decoder.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "key-decoder.js",
    "key-decoder.d.ts"
  ],
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-ansi-escapes.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-ansi-escapes/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-ansi-escapes#readme",
  "dependencies": {
    "bare-stream": "^2.6.5"
  },
  "devDependencies": {
    "bare-buffer": "^3.0.2",
    "brittle": "^3.3.2",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  },
  "peerDependencies": {
    "bare-buffer": "*"
  },
  "peerDependenciesMeta": {
    "bare-buffer": {
      "optional": true
    }
  }
}
const inspect = require('bare-inspect')

class AssertionError extends Error {
  constructor(opts = {}) {
    let { message = null, actual, expected, operator } = opts

    if (message === null) {
      message = `${inspect(actual)} ${operator} ${inspect(expected)}`
    }

    super(message)

    this.actual = actual
    this.expected = expected
    this.operator = operator
  }

  get name() {
    return 'AssertionError'
  }

  get code() {
    'ASSERTION'
  }
}

function assertFail(opts, fn) {
  if (opts.message instanceof Error) throw opts.message

  const err = new AssertionError(opts)

  if (Error.captureStackTrace) Error.captureStackTrace(err, fn)

  throw err
}

module.exports = exports = function assert(actual, message) {
  if (actual) return

  assertFail({ message, actual, expected: true, operator: '==' }, assert)
}

exports.AssertionError = AssertionError

exports.fail = function fail(message) {
  if (message === undefined) message = 'Failed'

  assertFail({ message, operator: 'fail' }, fail)
}

exports.ok = function ok(actual, message) {
  if (actual) return

  assertFail({ message, actual, expected: true, operator: '==' }, ok)
}

exports.notOk = function ok(actual, message) {
  if (!actual) return

  assertFail({ message, actual, expected: false, operator: '==' }, ok)
}

exports.equal = function equal(actual, expected, message) {
  if (actual == expected || (actual !== actual && expected !== expected)) {
    return
  }

  assertFail({ message, actual, expected, operator: '==' }, equal)
}

exports.notEqual = function notEqual(actual, expected, message) {
  if (actual != expected && (actual === actual || expected === expected)) {
    return
  }

  assertFail({ message, actual, expected, operator: '!=' }, notEqual)
}

exports.strictEqual = function strictEqual(actual, expected, message) {
  if (Object.is(actual, expected)) return

  assertFail(
    { message, actual, expected, operator: 'strictEqual' },
    strictEqual
  )
}

exports.notStrictEqual = function notStrictEqual(actual, expected, message) {
  if (!Object.is(actual, expected)) return

  assertFail(
    { message, actual, expected, operator: 'notStrictEqual' },
    notStrictEqual
  )
}
{
  "name": "bare-assert",
  "version": "1.2.0",
  "description": "Assertion library for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts"
  ],
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-assert.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-assert/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-assert#readme",
  "dependencies": {
    "bare-inspect": "^3.1.2"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  }
}
const errors = require('./lib/errors')

class EventListener {
  constructor() {
    this.list = []
    this.count = 0
  }

  append(ctx, name, fn, once) {
    this.count++
    ctx.emit('newListener', name, fn) // Emit BEFORE adding
    this.list.push([fn, once])
  }

  prepend(ctx, name, fn, once) {
    this.count++
    ctx.emit('newListener', name, fn) // Emit BEFORE adding
    this.list.unshift([fn, once])
  }

  remove(ctx, name, fn) {
    for (let i = 0, n = this.list.length; i < n; i++) {
      const l = this.list[i]

      if (l[0] === fn) {
        this.list.splice(i, 1)

        if (this.count === 1) delete ctx._events[name]

        ctx.emit('removeListener', name, fn) // Emit AFTER removing

        this.count--
        return
      }
    }
  }

  removeAll(ctx, name) {
    const list = [...this.list]
    this.list = []

    if (this.count === list.length) delete ctx._events[name]

    for (let i = list.length - 1; i >= 0; i--) {
      ctx.emit('removeListener', name, list[i][0]) // Emit AFTER removing
    }

    this.count -= list.length
  }

  emit(ctx, name, ...args) {
    const list = [...this.list]

    for (let i = 0, n = list.length; i < n; i++) {
      const l = list[i]

      if (l[1] === true) this.remove(ctx, name, l[0])

      Reflect.apply(l[0], ctx, args)
    }

    return list.length > 0
  }
}

function appendListener(ctx, name, fn, once) {
  if (ctx._events === undefined) ctx._events = Object.create(null)
  const e = ctx._events[name] || (ctx._events[name] = new EventListener())
  e.append(ctx, name, fn, once)
  return ctx
}

function prependListener(ctx, name, fn, once) {
  if (ctx._events === undefined) ctx._events = Object.create(null)
  const e = ctx._events[name] || (ctx._events[name] = new EventListener())
  e.prepend(ctx, name, fn, once)
  return ctx
}

function removeListener(ctx, name, fn) {
  if (ctx._events === undefined) return ctx
  const e = ctx._events[name]
  if (e !== undefined) e.remove(ctx, name, fn)
  return ctx
}

function throwUnhandledError(...args) {
  let err

  if (args.length > 0) err = args[0]

  if (err instanceof Error === false) err = errors.UNHANDLED_ERROR(err)

  if (Error.captureStackTrace) {
    Error.captureStackTrace(err, exports.prototype.emit)
  }

  queueMicrotask(() => {
    throw err
  })
}

module.exports = exports = class EventEmitter {
  constructor() {
    this._events = Object.create(null)
  }

  addListener(name, fn) {
    return appendListener(this, name, fn, false)
  }

  addOnceListener(name, fn) {
    return appendListener(this, name, fn, true)
  }

  prependListener(name, fn) {
    return prependListener(this, name, fn, false)
  }

  prependOnceListener(name, fn) {
    return prependListener(this, name, fn, true)
  }

  removeListener(name, fn) {
    return removeListener(this, name, fn)
  }

  on(name, fn) {
    return appendListener(this, name, fn, false)
  }

  once(name, fn) {
    return appendListener(this, name, fn, true)
  }

  off(name, fn) {
    return removeListener(this, name, fn)
  }

  emit(name, ...args) {
    if (name === 'error' && this._events !== undefined && this._events.error === undefined) {
      throwUnhandledError(...args)
    }

    if (this._events === undefined) return false
    const e = this._events[name]
    return e === undefined ? false : e.emit(this, name, ...args)
  }

  listeners(name) {
    if (this._events === undefined) return []
    const e = this._events[name]
    return e === undefined ? [] : [...e.list]
  }

  listenerCount(name) {
    if (this._events === undefined) return 0
    const e = this._events[name]
    return e === undefined ? 0 : e.list.length
  }

  getMaxListeners() {
    return EventEmitter.defaultMaxListeners
  }

  setMaxListeners(n) {}

  removeAllListeners(name) {
    if (arguments.length === 0) {
      for (const key of Reflect.ownKeys(this._events)) {
        if (key === 'removeListener') continue
        this.removeAllListeners(key)
      }
      this.removeAllListeners('removeListener')
    } else {
      const e = this._events[name]
      if (e !== undefined) e.removeAll(this, name)
    }
    return this
  }
}

exports.EventEmitter = exports

exports.errors = errors

exports.defaultMaxListeners = 10

exports.on = function on(emitter, name, opts = {}) {
  const { signal } = opts

  if (signal && signal.aborted) {
    throw errors.OPERATION_ABORTED(signal.reason)
  }

  let error = null
  let done = false

  const events = []
  const promises = []

  if (name !== 'error') emitter.on('error', onerror)

  if (signal) signal.addEventListener('abort', onabort)

  emitter.on(name, onevent)

  return {
    next() {
      if (events.length) {
        return Promise.resolve({ value: events.shift(), done: false })
      }

      if (error) {
        const err = error

        error = null

        return Promise.reject(err)
      }

      if (done) return onclose()

      return new Promise((resolve, reject) => promises.push({ resolve, reject }))
    },

    return() {
      return onclose()
    },

    throw(err) {
      return onerror(err)
    },

    [Symbol.asyncIterator]() {
      return this
    }
  }

  function onevent(...args) {
    if (promises.length) {
      promises.shift().resolve({ value: args, done: false })
    } else {
      events.push(args)
    }
  }

  function onerror(err) {
    emitter.off(name, onevent).off('error', onerror)

    if (promises.length) {
      promises.shift().reject(err)
    } else {
      error = err
    }

    return Promise.resolve({ done: true })
  }

  function onabort() {
    signal.removeEventListener('abort', onabort)

    onerror(errors.OPERATION_ABORTED(signal.reason))
  }

  function onclose() {
    emitter.off(name, onevent)

    if (name !== 'error') emitter.off('error', onerror)

    if (signal) signal.removeEventListener('abort', onabort)

    done = true

    if (promises.length) promises.shift().resolve({ done: true })

    return Promise.resolve({ done: true })
  }
}

exports.once = function once(emitter, name, opts = {}) {
  const { signal } = opts

  if (signal && signal.aborted) {
    return Promise.reject(errors.OPERATION_ABORTED(signal.reason))
  }

  return new Promise((resolve, reject) => {
    if (name !== 'error') emitter.on('error', onerror)

    if (signal) signal.addEventListener('abort', onabort)

    emitter.once(name, onevent)

    function onevent(...args) {
      if (name !== 'error') emitter.off('error', onerror)

      if (signal) signal.removeEventListener('abort', onabort)

      resolve(args)
    }

    function onerror(err) {
      emitter.off(name, onevent)

      if (name !== 'error') emitter.off('error', onerror)

      reject(err)
    }

    function onabort() {
      signal.removeEventListener('abort', onabort)

      onerror(errors.OPERATION_ABORTED(signal.reason))
    }
  })
}

exports.forward = function forward(from, to, names, opts = {}) {
  if (typeof names === 'string') names = [names]

  const { emit = to.emit.bind(to) } = opts

  const listeners = names.map(
    (name) =>
      function onevent(...args) {
        emit(name, ...args)
      }
  )

  to.on('newListener', (name) => {
    const i = names.indexOf(name)

    if (i !== -1 && to.listenerCount(name) === 0) {
      from.on(name, listeners[i])
    }
  }).on('removeListener', (name) => {
    const i = names.indexOf(name)

    if (i !== -1 && to.listenerCount(name) === 0) {
      from.off(name, listeners[i])
    }
  })
}

exports.listenerCount = function listenerCount(emitter, name) {
  return emitter.listenerCount(name)
}

exports.getMaxListeners = function getMaxListeners(emitter) {
  if (typeof emitter.getMaxListeners === 'function') {
    return emitter.getMaxListeners()
  }

  return exports.defaultMaxListeners
}

exports.setMaxListeners = function setMaxListeners(n, ...emitters) {
  if (emitters.length === 0) exports.defaultMaxListeners = n
  else {
    for (const emitter of emitters) {
      if (typeof emitter.setMaxListeners === 'function') {
        emitter.setMaxListeners(n)
      }
    }
  }
}
module.exports = class EventEmitterError extends Error {
  constructor(msg, code, fn = EventEmitterError, opts) {
    super(`${code}: ${msg}`, opts)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'EventEmitterError'
  }

  static OPERATION_ABORTED(cause, msg = 'Operation aborted') {
    return new EventEmitterError(msg, 'OPERATION_ABORTED', EventEmitterError.OPERATION_ABORTED, {
      cause
    })
  }

  static UNHANDLED_ERROR(cause, msg = 'Unhandled error') {
    return new EventEmitterError(msg, 'UNHANDLED_ERROR', EventEmitterError.UNHANDLED_ERROR, {
      cause
    })
  }
}
{
  "name": "bare-events",
  "version": "2.8.2",
  "description": "Event emitters for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    },
    "./web": {
      "types": "./web.d.ts",
      "default": "./web.js"
    },
    "./errors": "./lib/errors.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "global.js",
    "global.d.ts",
    "web.js",
    "web.d.ts",
    "lib"
  ],
  "scripts": {
    "test": "npm run lint && npm run test:bare && npm run test:node",
    "test:bare": "bare test.js",
    "test:node": "node test.js",
    "lint": "prettier . --check"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-events.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-events/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-events#readme",
  "devDependencies": {
    "bare-abort-controller": "^1.0.0",
    "brittle": "^3.3.2",
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^2.0.0",
    "uncaughts": "^1.1.1"
  },
  "peerDependencies": {
    "bare-abort-controller": "*"
  },
  "peerDependenciesMeta": {
    "bare-abort-controller": {
      "optional": true
    }
  }
}
module.exports = require.addon()
const FIFO = require('fast-fifo')
const EventEmitter = require('bare-events')
const path = require('bare-path')
const { isURL, fileURLToPath } = require('bare-url')
const { Readable, Writable } = require('bare-stream')
const binding = require('./binding')
const constants = require('./lib/constants')
const FileError = require('./lib/errors')

const isWindows = Bare.platform === 'win32'

exports.constants = constants

class FileRequest {
  static borrow() {
    if (this._free.length > 0) return this._free.pop()
    return new FileRequest()
  }

  static return(req) {
    if (this._free.length < 32) this._free.push(req.reset())
    else req.destroy()
  }

  constructor() {
    this._reset()
    this._handle = binding.requestInit(this, this._onresult)
  }

  get handle() {
    return this._handle
  }

  retain(value) {
    this._retain = value // Tie the lifetime of `value` to the lifetime of `this`
  }

  reset() {
    if (this._handle === null) return this

    binding.requestReset(this._handle)

    this._reset()

    return this
  }

  destroy() {
    if (this._handle === null) return this

    binding.requestDestroy(this._handle)

    this._reset()
    this._handle = null

    return this
  }

  then(resolve, reject) {
    return this._promise.then(resolve, reject)
  }

  return() {
    if (this._handle === null) return this

    FileRequest.return(this)

    return this
  }

  _reset() {
    this._promise = new Promise((resolve, reject) => {
      this._resolve = resolve
      this._reject = reject
    })
    this._retain = null
  }

  _onresult(err, status) {
    if (err) this._reject(err)
    else this._resolve(status)
  }
}

FileRequest._free = []

function ok(result, cb) {
  if (typeof result === 'function') {
    cb = result
    result = undefined
  }

  if (cb) cb(null, result)
  else return result
}

function fail(err, cb) {
  if (cb) cb(err)
  else throw err
}

function done(err, result, cb) {
  if (typeof result === 'function') {
    cb = result
    result = undefined
  }

  if (err) fail(err, cb)
  else return ok(result, cb)
}

async function open(filepath, flags = 'r', mode = 0o666, cb) {
  if (typeof flags === 'function') {
    cb = flags
    flags = 'r'
    mode = 0o666
  } else if (typeof mode === 'function') {
    cb = mode
    mode = 0o666
  }

  if (typeof flags === 'string') flags = toFlags(flags)
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let fd
  let err = null
  try {
    binding.open(req.handle, filepath, flags, mode)

    fd = await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'open',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, fd, cb)
}

function openSync(filepath, flags = 'r', mode = 0o666) {
  if (typeof flags === 'string') flags = toFlags(flags)
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    return binding.openSync(req.handle, filepath, flags, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'open',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function close(fd, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.close(req.handle, fd)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'close', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function closeSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.closeSync(req.handle, fd)
  } catch (e) {
    throw new FileError(e.message, { operation: 'close', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function access(filepath, mode = constants.F_OK, cb) {
  if (typeof mode === 'function') {
    cb = mode
    mode = constants.F_OK
  }

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.access(req.handle, filepath, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'access',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function accessSync(filepath, mode = constants.F_OK) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.accessSync(req.handle, filepath, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'access',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function exists(filepath, cb) {
  let ok = true
  try {
    await access(filepath)
  } catch {
    ok = false
  }

  return done(null, ok, cb)
}

function existsSync(filepath) {
  try {
    accessSync(filepath)
  } catch {
    return false
  }

  return true
}

async function read(fd, buffer, offset = 0, len = buffer.byteLength - offset, pos = -1, cb) {
  if (typeof offset === 'function') {
    cb = offset
    offset = 0
    len = buffer.byteLength
    pos = -1
  } else if (typeof len === 'function') {
    cb = len
    len = buffer.byteLength - offset
    pos = -1
  } else if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.read(req.handle, fd, buffer, offset, len, pos)

    req.retain(buffer)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'read', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function readSync(fd, buffer, offset = 0, len = buffer.byteLength - offset, pos = -1) {
  const req = FileRequest.borrow()

  try {
    return binding.readSync(req.handle, fd, buffer, offset, len, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'read', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function readv(fd, buffers, pos = -1, cb) {
  if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.readv(req.handle, fd, buffers, pos)

    req.retain(buffers)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'readv', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function readvSync(fd, buffers, pos = -1) {
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  try {
    return binding.readvSync(req.handle, fd, buffers, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'readv', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function write(fd, data, offset, len, pos = -1, cb) {
  if (typeof data === 'string') {
    let encoding = len
    cb = pos
    pos = offset

    if (typeof pos === 'function') {
      cb = pos
      pos = -1
      encoding = 'utf8'
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = 'utf8'
    }

    if (typeof pos === 'string') {
      encoding = pos
      pos = -1
    }

    data = Buffer.from(data, encoding)
    offset = 0
    len = data.byteLength
  } else if (typeof offset === 'function') {
    cb = offset
    offset = 0
    len = data.byteLength
    pos = -1
  } else if (typeof len === 'function') {
    cb = len
    len = data.byteLength - offset
    pos = -1
  } else if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof offset !== 'number') offset = 0
  if (typeof len !== 'number') len = data.byteLength - offset
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.write(req.handle, fd, data, offset, len, pos)

    req.retain(data)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'write', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function writeSync(fd, data, offset, len, pos = -1) {
  if (typeof data === 'string') {
    let encoding = len
    pos = offset

    if (typeof pos === 'string') {
      encoding = pos
      pos = -1
    }

    data = Buffer.from(data, encoding)
    offset = 0
    len = data.byteLength
  }

  if (typeof offset !== 'number') offset = 0
  if (typeof len !== 'number') len = data.byteLength - offset
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  try {
    return binding.writeSync(req.handle, fd, data, offset, len, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'write', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function writev(fd, buffers, pos = -1, cb) {
  if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.writev(req.handle, fd, buffers, pos)

    req.retain(buffers)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'writev', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function writevSync(fd, buffers, pos = -1) {
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  try {
    return binding.writevSync(req.handle, fd, buffers, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'writev', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function stat(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.stat(req.handle, filepath)

    await req

    st = new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'stat', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function statSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.statSync(req.handle, filepath)

    return new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'stat', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function lstat(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.lstat(req.handle, filepath)

    await req

    st = new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'lstat', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function lstatSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.lstatSync(req.handle, filepath)

    return new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'lstat', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function fstat(fd, cb) {
  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.fstat(req.handle, fd)

    await req

    st = new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'fstat', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function fstatSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.fstatSync(req.handle, fd)

    return new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'fstat', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function statfs(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.statfs(req.handle, filepath)

    await req

    st = new StatFs(...binding.requestResultStatfs(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'statfs', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function statfsSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.statfsSync(req.handle, filepath)

    return new StatFs(...binding.requestResultStatfs(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'statfs', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function ftruncate(fd, len = 0, cb) {
  if (typeof len === 'function') {
    cb = len
    len = 0
  }

  if (typeof len !== 'number') len = 0

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.ftruncate(req.handle, fd, len)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'ftruncate', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function ftruncateSync(fd, len = 0) {
  if (typeof len !== 'number') len = 0

  const req = FileRequest.borrow()

  try {
    binding.ftruncateSync(req.handle, fd, len)
  } catch (e) {
    throw new FileError(e.message, { operation: 'ftruncate', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function truncate(filepath, len, cb) {
  let fd = -1
  let err

  try {
    fd = await open(filepath, 'r+')

    await ftruncate(fd, len)
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) await close(fd)
  }

  return done(err, cb)
}

function truncateSync(filepath, len) {
  let fd = -1
  let err

  try {
    fd = openSync(filepath, 'r+')

    ftruncateSync(fd, len)
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) closeSync(fd)
  }
}

async function chmod(filepath, mode, cb) {
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.chmod(req.handle, filepath, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'chmod',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function chmodSync(filepath, mode) {
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.chmodSync(req.handle, filepath, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'chmod',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function fchmod(fd, mode, cb) {
  if (typeof mode === 'string') mode = toMode(mode)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fchmod(req.handle, fd, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fchmod', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fchmodSync(fd, mode) {
  if (typeof mode === 'string') mode = toMode(mode)

  const req = FileRequest.borrow()

  try {
    binding.fchmodSync(req.handle, fd, mode)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fchmod', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function chown(filepath, uid, gid, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.chown(req.handle, filepath, uid, gid)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'chown', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function chownSync(filepath, uid, gid) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.chownSync(req.handle, filepath, uid, gid)
  } catch (e) {
    throw new FileError(e.message, { operation: 'chownSync', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function lchown(filepath, uid, gid, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.lchown(req.handle, filepath, uid, gid)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'lchown', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function lchownSync(filepath, uid, gid) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.lchownSync(req.handle, filepath, uid, gid)
  } catch (e) {
    throw new FileError(e.message, { operation: 'lchownSync', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function fchown(fd, uid, gid, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fchown(req.handle, fd, uid, gid)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fchown', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fchownSync(fd, uid, gid) {
  const req = FileRequest.borrow()

  try {
    binding.fchownSync(req.handle, fd, uid, gid)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fchownSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function utimes(filepath, atime, mtime, cb) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.utimes(req.handle, filepath, atime, mtime)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'utimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function utimesSync(filepath, atime, mtime) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.utimesSync(req.handle, filepath, atime, mtime)
  } catch (e) {
    throw new FileError(e.message, { operation: 'utimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function lutimes(filepath, atime, mtime, cb) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.lutimes(req.handle, filepath, atime, mtime)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'lutimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function lutimesSync(filepath, atime, mtime) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.lutimesSync(req.handle, filepath, atime, mtime)
  } catch (e) {
    throw new FileError(e.message, { operation: 'lutimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function futimes(fd, atime, mtime, cb) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.futimes(req.handle, fd, atime, mtime)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'futimes', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function futimesSync(fd, atime, mtime) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  const req = FileRequest.borrow()

  try {
    binding.futimesSync(req.handle, fd, atime, mtime)
  } catch (e) {
    throw new FileError(e.message, { operation: 'futimesSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function link(src, dst, cb) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.link(req.handle, src, dst)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'link', code: e.code, path: src, destination: dst })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function linkSync(src, dst) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  try {
    binding.linkSync(req.handle, src, dst)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'linkSync',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }
}

async function mkdir(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = { mode: 0o777 }
  }

  if (typeof opts === 'number') opts = { mode: opts }
  else if (!opts) opts = {}

  const mode = typeof opts.mode === 'number' ? opts.mode : 0o777

  filepath = toNamespacedPath(filepath)

  if (opts.recursive) {
    let err = null
    try {
      try {
        await mkdir(filepath, { mode })
      } catch (err) {
        if (err.code !== 'ENOENT') {
          if (!(await stat(filepath)).isDirectory()) throw err
        } else {
          while (filepath.endsWith(path.sep)) filepath = filepath.slice(0, -1)
          const i = filepath.lastIndexOf(path.sep)
          if (i <= 0) throw err

          await mkdir(filepath.slice(0, i), { mode, recursive: true })

          try {
            await mkdir(filepath, { mode })
          } catch (err) {
            if (!(await stat(filepath)).isDirectory()) throw err
          }
        }
      }
    } catch (e) {
      err = e
    }

    return done(err, cb)
  }

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.mkdir(req.handle, filepath, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'mkdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function mkdirSync(filepath, opts) {
  if (typeof opts === 'number') opts = { mode: opts }
  else if (!opts) opts = {}

  const mode = typeof opts.mode === 'number' ? opts.mode : 0o777

  filepath = toNamespacedPath(filepath)

  if (opts.recursive) {
    try {
      mkdirSync(filepath, { mode })
    } catch (err) {
      if (err.code !== 'ENOENT') {
        if (!statSync(filepath).isDirectory()) throw err
      } else {
        while (filepath.endsWith(path.sep)) filepath = filepath.slice(0, -1)
        const i = filepath.lastIndexOf(path.sep)
        if (i <= 0) throw err

        mkdirSync(filepath.slice(0, i), { mode, recursive: true })

        try {
          mkdirSync(filepath, { mode })
        } catch (err) {
          if (!statSync(filepath).isDirectory()) throw err
        }
      }
    }

    return
  }

  const req = FileRequest.borrow()

  try {
    binding.mkdirSync(req.handle, filepath, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'mkdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function mkdtemp(prefix, cb) {
  prefix = toNamespacedPath(prefix)

  const req = FileRequest.borrow()

  let res
  let err = null
  try {
    binding.mkdtemp(req.handle, prefix + 'XXXXXX')

    await req

    res = binding.requestResultPath(req.handle)
  } catch (e) {
    err = new FileError(e.message, { operation: 'mkdtemp', code: e.code, path: prefix })
  } finally {
    req.return()
  }

  return done(err, res, cb)
}

function mkdtempSync(prefix) {
  prefix = toNamespacedPath(prefix)

  const req = FileRequest.borrow()

  try {
    binding.mkdtempSync(req.handle, prefix + 'XXXXXX')

    return binding.requestResultPath(req.handle)
  } catch (e) {
    throw new FileError(e.message, { operation: 'mkdtempSync', code: e.code, path: prefix })
  } finally {
    req.return()
  }
}

async function rmdir(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.rmdir(req.handle, filepath)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'rmdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function rmdirSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.rmdirSync(req.handle, filepath)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'rmdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function rm(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  let err = null
  try {
    const st = await lstat(filepath)

    if (st.isDirectory()) {
      if (opts.recursive) {
        try {
          await rmdir(filepath)
        } catch (err) {
          if (err.code !== 'ENOTEMPTY') throw err

          const files = await readdir(filepath)

          for (const file of files) {
            await rm(filepath + path.sep + file, opts)
          }

          await rmdir(filepath)
        }
      } else {
        throw new FileError('is a directory', {
          operation: 'rm',
          code: 'EISDIR',
          path: filepath
        })
      }
    } else {
      await unlink(filepath)
    }
  } catch (e) {
    if (e.code !== 'ENOENT' || !opts.force) err = e
  }

  return done(err, cb)
}

function rmSync(filepath, opts) {
  if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  try {
    const st = lstatSync(filepath)

    if (st.isDirectory()) {
      if (opts.recursive) {
        try {
          rmdirSync(filepath)
        } catch (err) {
          if (err.code !== 'ENOTEMPTY') throw err

          const files = readdirSync(filepath)

          for (const file of files) {
            rmSync(filepath + path.sep + file, opts)
          }

          rmdirSync(filepath)
        }
      } else {
        throw new FileError('is a directory', {
          operation: 'rm',
          code: 'EISDIR',
          path: filepath
        })
      }
    } else {
      unlinkSync(filepath)
    }
  } catch (err) {
    if (err.code !== 'ENOENT' || !opts.force) throw err
  }
}

async function unlink(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.unlink(req.handle, filepath)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'unlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function unlinkSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.unlinkSync(req.handle, filepath)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'unlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function rename(src, dst, cb) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.rename(req.handle, src, dst)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'rename',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function renameSync(src, dst) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  try {
    binding.renameSync(req.handle, src, dst)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'rename',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }
}

async function copyFile(src, dst, mode = 0, cb) {
  if (typeof mode === 'function') {
    cb = mode
    mode = 0
  }

  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.copyfile(req.handle, src, dst, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'copyfile',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function copyFileSync(src, dst, mode = 0) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  try {
    binding.copyfileSync(req.handle, src, dst, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'copyfile',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }
}

async function cp(src, dst, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (!opts) opts = {}

  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  let err = null
  try {
    const st = await lstat(src)

    if (st.isDirectory()) {
      if (opts.recursive !== true) {
        throw new FileError('is a directory', { operation: 'cp', code: 'EISDIR', path: src })
      }

      try {
        await lstat(dst)
      } catch (e) {
        if (e.code !== 'ENOENT') throw e

        await mkdir(dst, { mode: st.mode, recursive: true })
      }

      const dir = await opendir(src)
      for await (const { name } of dir) {
        await cp(path.join(src, name), path.join(dst, name), opts)
      }
    } else if (st.isFile()) {
      await copyFile(src, dst)
      await chmod(dst, st.mode)
    }
  } catch (e) {
    err = e
  }

  return done(err, cb)
}

function cpSync(src, dst, opts = {}) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const st = lstatSync(src)

  if (st.isDirectory()) {
    if (opts.recursive !== true) {
      throw new FileError('is a directory', { operation: 'cp', code: 'EISDIR', path: src })
    }

    try {
      lstatSync(dst)
    } catch (e) {
      if (e.code !== 'ENOENT') throw e

      mkdirSync(dst, { mode: st.mode, recursive: true })
    }

    const dir = opendirSync(src)
    for (const { name } of dir) {
      cpSync(path.join(src, name), path.join(dst, name), opts)
    }
  } else if (st.isFile()) {
    copyFileSync(src, dst)
    chmodSync(dst, st.mode)
  }
}

async function realpath(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let res
  let err = null
  try {
    binding.realpath(req.handle, filepath)

    await req

    res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'realpath',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, res, cb)
}

function realpathSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.realpathSync(req.handle, filepath)

    let res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)

    return res
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'realpath',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function readlink(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let res
  let err = null
  try {
    binding.readlink(req.handle, filepath)

    await req

    res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'readlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, res, cb)
}

function readlinkSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.readlinkSync(req.handle, filepath)

    let res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)

    return res
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'readlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function fsync(fd, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fsync(req.handle, fd)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fsync', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fsyncSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.fsyncSync(req.handle, fd)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fsyncSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function fdatasync(fd, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fdatasync(req.handle, fd)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fdatasync', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fdatasyncSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.fdatasyncSync(req.handle, fd)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fdatasyncSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

function normalizeSymlinkTarget(target, type, filepath) {
  if (isWindows) {
    if (type === constants.UV_FS_SYMLINK_JUNCTION) target = path.resolve(filepath, '..', target)

    if (path.isAbsolute(target)) return path.toNamespacedPath(target)

    return target.replace(/\//g, path.sep)
  }

  return target
}

async function symlink(target, filepath, type, cb) {
  if (typeof type === 'function') {
    cb = type
    type = null
  }

  filepath = toNamespacedPath(filepath)

  if (typeof type === 'string') {
    switch (type) {
      case 'dir':
        type = constants.UV_FS_SYMLINK_DIR
        break
      case 'junction':
        type = constants.UV_FS_SYMLINK_JUNCTION
        break
      case 'file':
      default:
        type = 0
        break
    }
  } else if (typeof type !== 'number') {
    if (isWindows) {
      target = path.resolve(filepath, '..', target)

      try {
        type = (await stat(target)).isDirectory()
          ? constants.UV_FS_SYMLINK_DIR
          : constants.UV_FS_SYMLINK_JUNCTION
      } catch {
        type = 0
      }
    } else {
      type = 0
    }
  }

  target = normalizeSymlinkTarget(target, type, filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.symlink(req.handle, target, filepath, type)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'symlink',
      code: e.code,
      path: target,
      destination: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function symlinkSync(target, filepath, type) {
  filepath = toNamespacedPath(filepath)

  if (typeof type === 'string') {
    switch (type) {
      case 'dir':
        type = constants.UV_FS_SYMLINK_DIR
        break
      case 'junction':
        type = constants.UV_FS_SYMLINK_JUNCTION
        break
      case 'file':
      default:
        type = 0
        break
    }
  } else if (typeof type !== 'number') {
    if (isWindows) {
      target = path.resolve(filepath, '..', target)

      try {
        type = statSync(target).isDirectory()
          ? constants.UV_FS_SYMLINK_DIR
          : constants.UV_FS_SYMLINK_JUNCTION
      } catch {
        type = 0
      }
    } else {
      type = 0
    }
  }

  target = normalizeSymlinkTarget(target, type, filepath)

  const req = FileRequest.borrow()

  try {
    binding.symlinkSync(req.handle, target, filepath, type)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'symlink',
      code: e.code,
      path: target,
      destination: filepath
    })
  } finally {
    req.return()
  }
}

async function opendir(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let dir
  let err = null
  try {
    binding.opendir(req.handle, filepath)

    await req

    dir = new Dir(filepath, binding.requestResultDir(req.handle), opts)
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'opendir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, dir, cb)
}

function opendirSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.opendirSync(req.handle, filepath)

    return new Dir(filepath, binding.requestResultDir(req.handle), opts)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'opendir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function readdir(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { withFileTypes = false, recursive = false } = opts

  filepath = toNamespacedPath(filepath)

  const queue = [filepath]
  let result = []
  let err = null
  try {
    while (queue.length !== 0) {
      const dir = await opendir(queue.pop())

      for await (const entry of dir) {
        const entryPath = path.join(entry.parentPath, entry.name)

        if (withFileTypes) {
          result.push(entry)
        } else {
          result.push(path.relative(filepath, entryPath))
        }

        if (recursive && entry.isDirectory()) queue.push(entryPath)
      }
    }
  } catch (e) {
    result = []
    err = e
  }

  return done(err, result, cb)
}

function readdirSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { withFileTypes = false, recursive = false } = opts

  filepath = toNamespacedPath(filepath)

  const queue = [filepath]
  const result = []

  while (queue.length !== 0) {
    const dir = opendirSync(queue.pop(), opts)

    for (const entry of dir) {
      const entryPath = path.join(entry.parentPath, entry.name)

      if (withFileTypes) {
        result.push(entry)
      } else {
        result.push(path.relative(filepath, entryPath))
      }

      if (recursive && entry.isDirectory()) queue.push(entryPath)
    }
  }

  return result
}

async function readFile(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'buffer' } = opts

  let fd = -1
  let buffer = null
  let err = null
  try {
    fd = await open(filepath, opts.flag || 'r')

    const st = await fstat(fd)

    let len = 0

    if (st.size === 0) {
      const buffers = []

      while (true) {
        buffer = Buffer.allocUnsafe(8192)
        const r = await read(fd, buffer)
        len += r
        if (r === 0) break
        buffers.push(buffer.subarray(0, r))
      }

      buffer = Buffer.concat(buffers)
    } else {
      buffer = Buffer.allocUnsafe(st.size)

      while (true) {
        const r = await read(fd, len ? buffer.subarray(len) : buffer)
        len += r
        if (r === 0 || len === buffer.byteLength) break
      }

      if (len !== buffer.byteLength) buffer = buffer.subarray(0, len)
    }

    if (encoding !== 'buffer') buffer = buffer.toString(encoding)
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) await close(fd)
  }

  return done(err, buffer, cb)
}

function readFileSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'buffer' } = opts

  let fd = -1
  try {
    fd = openSync(filepath, opts.flag || 'r')

    const st = fstatSync(fd)

    let buffer
    let len = 0

    if (st.size === 0) {
      const buffers = []

      while (true) {
        buffer = Buffer.allocUnsafe(8192)
        const r = readSync(fd, buffer)
        len += r
        if (r === 0) break
        buffers.push(buffer.subarray(0, r))
      }

      buffer = Buffer.concat(buffers)
    } else {
      buffer = Buffer.allocUnsafe(st.size)

      while (true) {
        const r = readSync(fd, len ? buffer.subarray(len) : buffer)
        len += r
        if (r === 0 || len === buffer.byteLength) break
      }

      if (len !== buffer.byteLength) buffer = buffer.subarray(0, len)
    }

    if (encoding !== 'buffer') buffer = buffer.toString(encoding)

    return buffer
  } finally {
    if (fd !== -1) closeSync(fd)
  }
}

async function writeFile(filepath, data, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (typeof data === 'string') data = Buffer.from(data, opts.encoding)

  let fd = -1
  let len = 0
  let err = null
  try {
    fd = await open(filepath, opts.flag || 'w', opts.mode || 0o666)

    while (true) {
      len += await write(fd, len ? data.subarray(len) : data)
      if (len === data.byteLength) break
    }
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) await close(fd)
  }

  return done(err, len, cb)
}

function writeFileSync(filepath, data, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (typeof data === 'string') data = Buffer.from(data, opts.encoding)

  let fd = -1
  try {
    fd = openSync(filepath, opts.flag || 'w', opts.mode || 0o666)

    let len = 0

    while (true) {
      len += writeSync(fd, len ? data.subarray(len) : data)
      if (len === data.byteLength) break
    }
  } finally {
    if (fd !== -1) closeSync(fd)
  }
}

function appendFile(filepath, data, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (!opts.flag) opts = { ...opts, flag: 'a' }

  return writeFile(filepath, data, opts, cb)
}

function appendFileSync(filepath, data, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (!opts.flag) opts = { ...opts, flag: 'a' }

  return writeFileSync(filepath, data, opts)
}

function watch(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  return new Watcher(filepath, opts, cb)
}

class Stats {
  constructor(
    dev,
    mode,
    nlink,
    uid,
    gid,
    rdev,
    blksize,
    ino,
    size,
    blocks,
    atimeMs,
    mtimeMs,
    ctimeMs,
    birthtimeMs
  ) {
    this.dev = dev
    this.mode = mode
    this.nlink = nlink
    this.uid = uid
    this.gid = gid
    this.rdev = rdev
    this.blksize = blksize
    this.ino = ino
    this.size = size
    this.blocks = blocks
    this.atimeMs = atimeMs
    this.mtimeMs = mtimeMs
    this.ctimeMs = ctimeMs
    this.birthtimeMs = birthtimeMs
    this.atime = new Date(atimeMs)
    this.mtime = new Date(mtimeMs)
    this.ctime = new Date(ctimeMs)
    this.birthtime = new Date(birthtimeMs)
  }

  isDirectory() {
    return (this.mode & constants.S_IFMT) === constants.S_IFDIR
  }

  isFile() {
    return (this.mode & constants.S_IFMT) === constants.S_IFREG
  }

  isBlockDevice() {
    return (this.mode & constants.S_IFMT) === constants.S_IFBLK
  }

  isCharacterDevice() {
    return (this.mode & constants.S_IFMT) === constants.S_IFCHR
  }

  isFIFO() {
    return (this.mode & constants.S_IFMT) === constants.S_IFIFO
  }

  isSymbolicLink() {
    return (this.mode & constants.S_IFMT) === constants.S_IFLNK
  }

  isSocket() {
    return (this.mode & constants.S_IFMT) === constants.S_IFSOCK
  }
}

class StatFs {
  constructor(type, bsize, blocks, bfree, bavail, files, ffree) {
    this.type = type
    this.bsize = bsize
    this.blocks = blocks
    this.bfree = bfree
    this.bavail = bavail
    this.files = files
    this.ffree = ffree
  }
}

class Dir {
  constructor(path, handle, opts = {}) {
    const { encoding = 'utf8', bufferSize = 32 } = opts

    this.path = path

    this._encoding = encoding
    this._capacity = bufferSize
    this._buffer = new FIFO()
    this._ended = false
    this._handle = handle
  }

  async read(cb) {
    if (this._buffer.length) return ok(this._buffer.shift(), cb)
    if (this._ended) return ok(null, cb)

    const req = FileRequest.borrow()

    let entries
    let err = null
    try {
      req.retain(binding.readdir(req.handle, this._handle, this._capacity))

      await req

      entries = binding.requestResultDirents(req.handle)
    } catch (e) {
      err = new FileError(e.message, {
        operation: 'readdir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    if (err) return fail(err, cb)

    if (entries.length === 0) {
      this._ended = true

      return ok(null, cb)
    }

    for (const entry of entries) {
      let name = Buffer.from(entry.name)

      if (this._encoding !== 'buffer') name = name.toString(this._encoding)

      this._buffer.push(new Dirent(this.path, name, entry.type))
    }

    return ok(this._buffer.shift(), cb)
  }

  readSync() {
    if (this._buffer.length) return this._buffer.shift()
    if (this._ended) return null

    const req = FileRequest.borrow()

    let entries
    try {
      req.retain(binding.readdirSync(req.handle, this._handle, this._capacity))

      entries = binding.requestResultDirents(req.handle)
    } catch (e) {
      throw new FileError(e.message, {
        operation: 'readdir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    if (entries.length === 0) {
      this._ended = true

      return null
    }

    for (const entry of entries) {
      let name = Buffer.from(entry.name)

      if (this._encoding !== 'buffer') name = name.toString(this._encoding)

      this._buffer.push(new Dirent(this.path, name, entry.type))
    }

    return this._buffer.shift()
  }

  async close(cb) {
    const req = FileRequest.borrow()

    let err = null
    try {
      binding.closedir(req.handle, this._handle)

      await req
    } catch (e) {
      err = new FileError(e.message, {
        operation: 'closedir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    this._handle = null

    return done(err, cb)
  }

  closeSync() {
    const req = FileRequest.borrow()

    try {
      binding.closedirSync(req.handle, this._handle)
    } catch (e) {
      throw new FileError(e.message, {
        operation: 'closedir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    this._handle = null
  }

  [Symbol.dispose]() {
    this.closeSync()
  }

  async [Symbol.asyncDispose]() {
    await this.close()
  }

  *[Symbol.iterator]() {
    while (true) {
      const entry = this.readSync()
      if (entry === null) break
      yield entry
    }

    this.closeSync()
  }

  async *[Symbol.asyncIterator]() {
    while (true) {
      const entry = await this.read()
      if (entry === null) break
      yield entry
    }

    await this.close()
  }
}

class Dirent {
  constructor(parentPath, name, type) {
    this.parentPath = parentPath
    this.name = name
    this.type = type
  }

  isFile() {
    return this.type === constants.UV_DIRENT_FILE
  }

  isDirectory() {
    return this.type === constants.UV_DIRENT_DIR
  }

  isSymbolicLink() {
    return this.type === constants.UV_DIRENT_LINK
  }

  isFIFO() {
    return this.type === constants.UV_DIRENT_FIFO
  }

  isSocket() {
    return this.type === constants.UV_DIRENT_SOCKET
  }

  isCharacterDevice() {
    return this.type === constants.UV_DIRENT_CHAR
  }

  isBlockDevice() {
    return this.type === constants.UV_DIRENT_BLOCK
  }
}

class FileReadStream extends Readable {
  constructor(path, opts = {}) {
    const { eagerOpen = true } = opts

    super({ eagerOpen, ...opts })

    this.path = path
    this.fd = typeof opts.fd === 'number' ? opts.fd : -1
    this.flags = opts.flags || 'r'
    this.mode = opts.mode || 0o666

    this._offset = opts.start || 0
    this._missing = 0

    if (opts.length) {
      this._missing = opts.length
    } else if (typeof opts.end === 'number') {
      this._missing = opts.end - this._offset + 1
    } else {
      this._missing = -1
    }
  }

  async _open(cb) {
    let err

    if (this.fd === -1) {
      err = null
      try {
        this.fd = await open(this.path, this.flags, this.mode)
      } catch (e) {
        err = e
      }

      if (err) return cb(err)
    }

    let st
    err = null
    try {
      st = await fstat(this.fd)
    } catch (e) {
      err = e
    }

    if (err) return cb(err)

    if (this._missing === -1) this._missing = st.size

    if (st.size < this._offset) {
      this._offset = st.size
      this._missing = 0
    } else if (st.size < this._offset + this._missing) {
      this._missing = st.size - this._offset
    }

    cb(null)
  }

  async _read(size) {
    if (this._missing <= 0) return this.push(null)

    const data = Buffer.allocUnsafe(Math.min(this._missing, size))

    let len
    let err = null
    try {
      len = await read(this.fd, data, 0, data.byteLength, this._offset)
    } catch (e) {
      err = e
    }

    if (err) return this.destroy(err)

    if (len === 0) return this.push(null)

    if (this._missing < len) len = this._missing

    this._missing -= len
    this._offset += len

    this.push(data.subarray(0, len))
  }

  async _destroy(err, cb) {
    if (this.fd === -1) return cb(err)

    try {
      await close(this.fd)
    } catch (e) {
      err = err || e
    }

    cb(err)
  }
}

class FileWriteStream extends Writable {
  constructor(path, opts = {}) {
    const { eagerOpen = true } = opts

    super({ eagerOpen, ...opts })

    this.path = path
    this.fd = typeof opts.fd === 'number' ? opts.fd : -1
    this.flags = opts.flags || 'w'
    this.mode = opts.mode || 0o666
  }

  async _open(cb) {
    if (this.fd !== -1) return cb(null)

    let err = null
    try {
      this.fd = await open(this.path, this.flags, this.mode)
    } catch (e) {
      err = e
    }

    cb(err)
  }

  async _writev(batch, cb) {
    let err = null
    try {
      await writev(
        this.fd,
        batch.map(({ chunk }) => chunk)
      )
    } catch (e) {
      err = e
    }

    cb(err)
  }

  async _destroy(err, cb) {
    if (this.fd === -1) return cb(err)

    try {
      await close(this.fd)
    } catch (e) {
      err = err || e
    }

    cb(err)
  }
}

class Watcher extends EventEmitter {
  constructor(path, opts, onchange) {
    if (typeof opts === 'function') {
      onchange = opts
      opts = {}
    }

    if (!opts) opts = {}

    const { persistent = true, recursive = false, encoding = 'utf8' } = opts

    super()

    this._closed = false
    this._encoding = encoding
    this._handle = binding.watcherInit(path, recursive, this, this._onevent, this._onclose)

    if (!persistent) this.unref()

    if (onchange) this.on('change', onchange)
  }

  close() {
    if (this._closed) return
    this._closed = true

    binding.watcherClose(this._handle)
  }

  ref() {
    if (this._handle) binding.watcherRef(this._handle)
    return this
  }

  unref() {
    if (this._handle) binding.watcherUnref(this._handle)
    return this
  }

  [Symbol.asyncIterator]() {
    const buffer = []
    let done = false
    let error = null
    let next = null

    this.on('change', (eventType, filename) => {
      if (next) {
        next.resolve({ done: false, value: { eventType, filename } })
        next = null
      } else {
        buffer.push({ eventType, filename })
      }
    })
      .on('error', (err) => {
        done = true
        error = err

        if (next) {
          next.reject(error)
          next = null
        }
      })
      .on('close', () => {
        done = true

        if (next) {
          next.resolve({ done })
          next = null
        }
      })

    return {
      next: () =>
        new Promise((resolve, reject) => {
          if (error) return reject(error)

          if (buffer.length) return resolve({ done: false, value: buffer.shift() })

          if (done) return resolve({ done })

          next = { resolve, reject }
        })
    }
  }

  _onevent(err, events, filename) {
    if (err) {
      this.close()
      this.emit('error', err)
    } else {
      const path =
        this._encoding === 'buffer'
          ? Buffer.from(filename)
          : Buffer.from(filename).toString(this._encoding)

      if (events & binding.UV_RENAME) {
        this.emit('change', 'rename', path)
      }

      if (events & binding.UV_CHANGE) {
        this.emit('change', 'change', path)
      }
    }
  }

  _onclose() {
    this._handle = null

    this.emit('close')
  }
}

exports.access = access
exports.appendFile = appendFile
exports.chmod = chmod
exports.chown = chown
exports.close = close
exports.copyFile = copyFile
exports.cp = cp
exports.exists = exists
exports.fchmod = fchmod
exports.fchown = fchown
exports.fdatasync = fdatasync
exports.fstat = fstat
exports.fsync = fsync
exports.ftruncate = ftruncate
exports.futimes = futimes
exports.lchown = lchown
exports.lutimes = lutimes
exports.link = link
exports.lstat = lstat
exports.mkdir = mkdir
exports.mkdtemp = mkdtemp
exports.open = open
exports.opendir = opendir
exports.read = read
exports.readFile = readFile
exports.readdir = readdir
exports.readlink = readlink
exports.readv = readv
exports.realpath = realpath
exports.rename = rename
exports.rm = rm
exports.rmdir = rmdir
exports.stat = stat
exports.statfs = statfs
exports.symlink = symlink
exports.truncate = truncate
exports.unlink = unlink
exports.utimes = utimes
exports.watch = watch
exports.write = write
exports.writeFile = writeFile
exports.writev = writev

exports.accessSync = accessSync
exports.appendFileSync = appendFileSync
exports.chmodSync = chmodSync
exports.chownSync = chownSync
exports.closeSync = closeSync
exports.copyFileSync = copyFileSync
exports.cpSync = cpSync
exports.existsSync = existsSync
exports.fchmodSync = fchmodSync
exports.fchownSync = fchownSync
exports.fdatasyncSync = fdatasyncSync
exports.fstatSync = fstatSync
exports.fsyncSync = fsyncSync
exports.ftruncateSync = ftruncateSync
exports.futimesSync = futimesSync
exports.lchownSync = lchownSync
exports.lutimesSync = lutimesSync
exports.linkSync = linkSync
exports.lstatSync = lstatSync
exports.mkdirSync = mkdirSync
exports.mkdtempSync = mkdtempSync
exports.openSync = openSync
exports.opendirSync = opendirSync
exports.readFileSync = readFileSync
exports.readSync = readSync
exports.readdirSync = readdirSync
exports.readlinkSync = readlinkSync
exports.readvSync = readvSync
exports.realpathSync = realpathSync
exports.renameSync = renameSync
exports.rmSync = rmSync
exports.rmdirSync = rmdirSync
exports.statSync = statSync
exports.statfsSync = statfsSync
exports.symlinkSync = symlinkSync
exports.truncateSync = truncateSync
exports.unlinkSync = unlinkSync
exports.utimesSync = utimesSync
exports.writeFileSync = writeFileSync
exports.writeSync = writeSync
exports.writevSync = writevSync

exports.promises = require('./promises')

exports.Stats = Stats
exports.StatFs = StatFs
exports.Dir = Dir
exports.Dirent = Dirent
exports.Watcher = Watcher

exports.ReadStream = FileReadStream

exports.createReadStream = function createReadStream(path, opts) {
  return new FileReadStream(path, opts)
}

exports.WriteStream = FileWriteStream

exports.createWriteStream = function createWriteStream(path, opts) {
  return new FileWriteStream(path, opts)
}

function toNamespacedPath(filepath) {
  if (typeof filepath !== 'string') {
    if (isURL(filepath)) filepath = fileURLToPath(filepath)
    else filepath = filepath.toString()
  }

  return path.toNamespacedPath(filepath)
}

function toFlags(flags) {
  switch (flags) {
    case 'r':
      return constants.O_RDONLY
    case 'rs': // Fall through.
    case 'sr':
      return constants.O_RDONLY | constants.O_SYNC
    case 'r+':
      return constants.O_RDWR
    case 'rs+': // Fall through.
    case 'sr+':
      return constants.O_RDWR | constants.O_SYNC

    case 'w':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_WRONLY
    case 'wx': // Fall through.
    case 'xw':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_WRONLY | constants.O_EXCL

    case 'w+':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_RDWR
    case 'wx+': // Fall through.
    case 'xw+':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_RDWR | constants.O_EXCL

    case 'a':
      return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY
    case 'ax': // Fall through.
    case 'xa':
      return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY | constants.O_EXCL
    case 'as': // Fall through.
    case 'sa':
      return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY | constants.O_SYNC

    case 'a+':
      return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR
    case 'ax+': // Fall through.
    case 'xa+':
      return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR | constants.O_EXCL
    case 'as+': // Fall through.
    case 'sa+':
      return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR | constants.O_SYNC
    default:
      return 0
  }
}

function toMode(mode) {
  return parseInt(mode, 8)
}
const binding = require('../binding')

module.exports = {
  O_RDWR: binding.O_RDWR,
  O_RDONLY: binding.O_RDONLY,
  O_WRONLY: binding.O_WRONLY,
  O_CREAT: binding.O_CREAT,
  O_TRUNC: binding.O_TRUNC,
  O_APPEND: binding.O_APPEND,

  F_OK: binding.F_OK || 0,
  R_OK: binding.R_OK || 0,
  W_OK: binding.W_OK || 0,
  X_OK: binding.X_OK || 0,

  S_IFMT: binding.S_IFMT,
  S_IFREG: binding.S_IFREG,
  S_IFDIR: binding.S_IFDIR,
  S_IFCHR: binding.S_IFCHR,
  S_IFLNK: binding.S_IFLNK,
  S_IFBLK: binding.S_IFBLK || 0,
  S_IFIFO: binding.S_IFIFO || 0,
  S_IFSOCK: binding.S_IFSOCK || 0,

  S_IRUSR: binding.S_IRUSR || 0,
  S_IWUSR: binding.S_IWUSR || 0,
  S_IXUSR: binding.S_IXUSR || 0,
  S_IRGRP: binding.S_IRGRP || 0,
  S_IWGRP: binding.S_IWGRP || 0,
  S_IXGRP: binding.S_IXGRP || 0,
  S_IROTH: binding.S_IROTH || 0,
  S_IWOTH: binding.S_IWOTH || 0,
  S_IXOTH: binding.S_IXOTH || 0,

  UV_DIRENT_UNKNOWN: binding.UV_DIRENT_UNKNOWN,
  UV_DIRENT_FILE: binding.UV_DIRENT_FILE,
  UV_DIRENT_DIR: binding.UV_DIRENT_DIR,
  UV_DIRENT_LINK: binding.UV_DIRENT_LINK,
  UV_DIRENT_FIFO: binding.UV_DIRENT_FIFO,
  UV_DIRENT_SOCKET: binding.UV_DIRENT_SOCKET,
  UV_DIRENT_CHAR: binding.UV_DIRENT_CHAR,
  UV_DIRENT_BLOCK: binding.UV_DIRENT_BLOCK,

  COPYFILE_EXCL: binding.UV_FS_COPYFILE_EXCL,
  COPYFILE_FICLONE: binding.UV_FS_COPYFILE_FICLONE,
  COPYFILE_FICLONE_FORCE: binding.UV_FS_COPYFILE_FICLONE_FORCE,
  UV_FS_SYMLINK_DIR: binding.UV_FS_SYMLINK_DIR,
  UV_FS_SYMLINK_JUNCTION: binding.UV_FS_SYMLINK_JUNCTION
}
const binding = require('../binding')

module.exports = class FileError extends Error {
  constructor(msg, opts = {}) {
    const { code, operation = null, path = null, destination = null, fd = -1 } = opts

    if (operation !== null) msg += describe(operation, opts)

    super(`${code}: ${msg}`)

    this.code = code

    if (operation !== null) this.operation = operation
    if (path !== null) this.path = path
    if (destination !== null) this.destination = destination
    if (fd !== -1) this.fd = fd
  }

  get name() {
    return 'FileError'
  }

  // For Node.js compatibility
  get errno() {
    return binding.errnos[this.code]
  }

  // For Node.js compatibility
  get syscall() {
    return this.operation
  }

  // For Node.js compatibility
  get dest() {
    return this.destination
  }
}

function describe(operation, opts) {
  const { path = null, destination = null, fd = -1 } = opts

  let result = `, ${operation}`

  if (path !== null) {
    result += ` ${JSON.stringify(path)}`

    if (destination !== null) {
      result += ` -> ${JSON.stringify(destination)}`
    }
  } else if (fd !== -1) {
    result += ` ${fd}`
  }

  return result
}
{
  "name": "bare-fs",
  "version": "4.7.4",
  "description": "Native file system operations for Bare",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./promises": {
      "types": "./promises.d.ts",
      "default": "./promises.js"
    },
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "promises.js",
    "promises.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-fs.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-fs/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-fs#readme",
  "engines": {
    "bare": ">=1.16.0"
  },
  "dependencies": {
    "bare-events": "^2.5.4",
    "bare-path": "^3.0.0",
    "bare-stream": "^2.6.4",
    "bare-url": "^2.2.2",
    "fast-fifo": "^1.3.2"
  },
  "devDependencies": {
    "bare-buffer": "^3.0.2",
    "bare-crypto": "^1.11.2",
    "brittle": "^3.1.1",
    "cmake-bare": "^1.1.7",
    "lunte": "^1.6.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "bare-buffer": "*"
  },
  "peerDependenciesMeta": {
    "bare-buffer": {
      "optional": true
    }
  }
}
const EventEmitter = require('bare-events')
const fs = require('.')

class FileHandle extends EventEmitter {
  constructor(fd) {
    super()

    this.fd = fd
  }

  async close() {
    await fs.close(this.fd)

    this.fd = -1
    this.emit('close')
  }

  async read(buffer, ...args) {
    return {
      bytesRead: await fs.read(this.fd, buffer, ...args),
      buffer
    }
  }

  async readv(buffers, ...args) {
    return {
      bytesRead: await fs.readv(this.fd, buffers, ...args),
      buffers
    }
  }

  async write(buffer, ...args) {
    return {
      bytesWritten: await fs.write(this.fd, buffer, ...args),
      buffer
    }
  }

  async writev(buffers, ...args) {
    return {
      bytesWritten: await fs.writev(this.fd, buffers, ...args),
      buffers
    }
  }

  async stat() {
    return fs.fstat(this.fd)
  }

  async chmod(mode) {
    await fs.fchmod(this.fd, mode)
  }

  async chown(uid, gid) {
    await fs.fchown(this.fd, uid, gid)
  }

  async datasync() {
    return fs.fdatasync(this.fd)
  }

  async sync() {
    return fs.fsync(this.fd)
  }

  async truncate(len) {
    await fs.ftruncate(this.fd, len)
  }

  async utimes(atime, mtime) {
    await fs.futimes(this.fd, atime, mtime)
  }

  createReadStream(opts) {
    return fs.createReadStream(null, { ...opts, fd: this.fd })
  }

  createWriteStream(opts) {
    return fs.createWriteStream(null, { ...opts, fd: this.fd })
  }

  async [Symbol.asyncDispose]() {
    await this.close()
  }
}

exports.open = async function open(filepath, flags, mode) {
  return new FileHandle(await fs.open(filepath, flags, mode))
}

exports.access = fs.access
exports.appendFile = fs.appendFile
exports.chmod = fs.chmod
exports.chown = fs.chown
exports.constants = fs.constants
exports.copyFile = fs.copyFile
exports.cp = fs.cp
exports.lchown = fs.lchown
exports.lutimes = fs.lutimes
exports.link = fs.link
exports.lstat = fs.lstat
exports.mkdir = fs.mkdir
exports.mkdtemp = fs.mkdtemp
exports.opendir = fs.opendir
exports.readFile = fs.readFile
exports.readdir = fs.readdir
exports.readlink = fs.readlink
exports.realpath = fs.realpath
exports.rename = fs.rename
exports.rm = fs.rm
exports.rmdir = fs.rmdir
exports.stat = fs.stat
exports.statfs = fs.statfs
exports.truncate = fs.truncate
exports.symlink = fs.symlink
exports.unlink = fs.unlink
exports.utimes = fs.utimes
exports.watch = fs.watch
exports.writeFile = fs.writeFile
module.exports = require.addon()
const ansiEscapes = require('bare-ansi-escapes')
const getType = require('bare-type')
const binding = require('./binding')

const PLAIN_KEY = /^[a-zA-Z_][a-zA-Z_0-9]*$/

const defaultDepth = 2
const defaultBreakLength = 80
const defaultMaxArrayLength = 40

module.exports = exports = function inspect(value, opts = {}) {
  const {
    colors = false,
    depth = defaultDepth,
    breakLength = defaultBreakLength,
    stylize = defaultStylize(colors)
  } = opts

  const references = new InspectRefMap()

  const tree = inspectValue(value, 0, {
    colors,
    depth,
    breakLength,
    stylize,
    references
  })

  return tree.toString()
}

exports.styles = {
  bigint: ansiEscapes.colorYellow,
  boolean: ansiEscapes.colorYellow,
  date: ansiEscapes.colorMagenta,
  module: ansiEscapes.modifierUnderline,
  name: ansiEscapes.modifierReset,
  null: ansiEscapes.modifierBold,
  number: ansiEscapes.colorYellow,
  regexp: ansiEscapes.colorRed,
  special: ansiEscapes.colorCyan,
  string: ansiEscapes.colorGreen,
  symbol: ansiEscapes.colorGreen,
  undefined: ansiEscapes.colorBrightBlack
}

const styles = exports.styles

function defaultStylize(colors) {
  return function stylize(value, style) {
    const color = colors && styles[style]

    if (color) return color + value + ansiEscapes.modifierReset

    return value
  }
}

class InspectRefMap {
  constructor() {
    this.refs = new WeakMap()
    this.ids = new WeakMap()
    this.nextId = 1
  }

  has(object) {
    return this.refs.has(object)
  }

  get(object) {
    return this.refs.get(object) || null
  }

  set(object, ref) {
    this.refs.set(object, ref)
  }

  id(object) {
    let id = this.ids.get(object)
    if (id) return id

    id = this.nextId++
    this.ids.set(object, id)

    return id
  }
}

class InspectNode {
  constructor(depth, length, opts) {
    const { breakLength = defaultBreakLength, breakAlways = false } = opts

    this.depth = depth
    this.length = length
    this.breakLength = breakLength
    this.breakAlways = breakAlways
  }

  pad(n, string) {
    return string.padStart(n, ' ')
  }

  indent(n, string) {
    return '  '.repeat(n) + string
  }
}

class InspectRef extends InspectNode {
  constructor(depth, opts) {
    super(depth, '[circular *]'.length, opts)

    this.refs = opts.references
    this.count = 0
    this.circular = false
    this.color = opts.colors && styles.special
  }

  get id() {
    return this.refs.id(this)
  }

  increment() {
    return ++this.count
  }

  decrement() {
    return --this.count
  }

  toString(opts = {}) {
    const { offset = 0, pad = 0, indent = 0 } = opts

    let value = this.pad(pad, '[circular *' + this.id + ']')

    if (this.color) value = this.color + value + ansiEscapes.modifierReset

    return offset ? value : this.indent(indent, value)
  }
}

class InspectLeaf extends InspectNode {
  constructor(value, color, depth, opts) {
    const length = value.length

    if (value.includes('\n')) {
      value = value.replaceAll('\n', '\n' + '  '.repeat(depth))

      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.value = value
    this.color = opts.colors && color
  }

  toString(opts = {}) {
    const { offset = 0, pad = 0, indent = 0 } = opts

    let value = this.pad(pad, this.value)

    if (this.color) value = this.color + value + ansiEscapes.modifierReset

    return offset ? value : this.indent(indent, value)
  }
}

class InspectPair extends InspectNode {
  constructor(delim, left, right, depth, opts) {
    const length = left.length + delim.length + right.length

    if (left.breakAlways || right.breakAlways) {
      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.delim = delim
    this.left = left
    this.right = right
  }

  toString(opts = {}) {
    const { indent = 0 } = opts

    return this.indent(
      indent,
      this.left +
        this.delim +
        this.right.toString({
          indent,
          offset: this.left.length + this.delim.length
        })
    )
  }
}

class InspectSuspension extends InspectNode {
  constructor(overflow, depth, opts) {
    const label = `... ${overflow} more`

    super(depth, label.length, opts)

    this.label = label
  }

  toString(opts = {}) {
    const { indent = 0 } = opts

    return this.indent(indent, this.label)
  }
}

class InspectSequence extends InspectNode {
  constructor(header, footer, delim, values, ref, depth, opts) {
    const { tabulate = false } = opts

    const length =
      (ref.circular ? '<ref *>'.length + 1 : 0) +
      header.length +
      values.reduce(
        (length, value, i) =>
          length + value.length + (i === 0 ? 0 : delim.length),
        0
      ) +
      footer.length

    if (values.some((value) => value.breakAlways)) {
      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.header = header
    this.footer = footer
    this.delim = delim
    this.values = values
    this.ref = ref
    this.tabulate = tabulate
  }

  toString(opts = {}) {
    const { offset = 0, indent = 0 } = opts

    const split =
      this.breakAlways ||
      (this.values.length &&
        (offset + this.length > this.breakLength ||
          indent * 2 + this.length > this.breakLength))

    let header = this.header

    if (this.ref.circular) {
      header = '<ref *' + this.ref.id + '> ' + header
    }

    if (this.values.length === 0) {
      header = header.trimEnd()
    }

    if (offset === 0) {
      header = this.indent(indent, header)
    }

    if (split) {
      header = header.trimEnd() + '\n'
    }

    let string = header

    let columns = 1
    let pad = 0

    if (this.tabulate) {
      const widest = this.values.reduce(
        (length, value) =>
          value.breakAlways ? length : Math.max(length, value.length),
        0
      )

      if (widest) {
        columns = Math.max(
          columns,
          Math.floor(
            (this.breakLength - indent * 2) / (widest + this.delim.length)
          )
        )

        if (columns > 1) pad = widest
      }
    }

    for (let i = 0, n = this.values.length, offset = 0; i < n; i++) {
      const value = this.values[i]

      if (split) {
        let part

        if (i % columns === 0 || value.breakAlways) {
          part = value.toString({ indent: indent + 1, pad })
        } else {
          part = value.toString({ pad })
        }

        string += part

        if (i < n - 1) {
          if (i % columns === columns - 1 || this.values[i + 1].breakAlways) {
            string += this.delim.trimEnd() + '\n'
          } else {
            string += this.delim
          }
        }
      } else {
        if (i > 0) string += this.delim

        string += value.toString({ offset })

        offset += value.length
      }
    }

    let footer = this.footer

    if (this.values.length === 0) {
      footer = footer.trimStart()
    }

    if (split) {
      string += '\n' + this.indent(indent, footer.trimStart())
    } else {
      string += footer
    }

    return string
  }
}

function inspectValue(value, depth, opts) {
  const type = getType(value)

  if (type.isUndefined()) return inspectUndefined(depth, opts)
  if (type.isNull()) return inspectNull(depth, opts)
  if (type.isBoolean()) return inspectBoolean(value, depth, opts)
  if (type.isNumber()) return inspectNumber(value, depth, opts)
  if (type.isBigInt()) return inspectBigInt(value, depth, opts)
  if (type.isString()) return inspectString(value, depth, opts)
  if (type.isSymbol()) return inspectSymbol(value, depth, opts)
  if (type.isObject()) return inspectObject(type, value, depth, opts)
  if (type.isFunction()) return inspectFunction(type, value, depth, opts)
  if (type.isExternal()) return inspectExternal(value, opts, opts)
}

function inspectUndefined(depth, opts) {
  return new InspectLeaf('undefined', styles.undefined, depth, opts)
}

function inspectNull(depth, opts) {
  return new InspectLeaf('null', styles.null, depth, opts)
}

function inspectBoolean(value, depth, opts) {
  return new InspectLeaf(value.toString(), styles.boolean, depth, opts)
}

function inspectNumber(value, depth, opts) {
  let string

  if (Object.is(value, -0)) {
    string = '-0'
  } else {
    string = value.toString(10)
  }

  return new InspectLeaf(string, styles.number, depth, opts)
}

function inspectBigInt(value, depth, opts) {
  return new InspectLeaf(value.toString(10) + 'n', styles.bigint, depth, opts)
}

const STRING_ESCAPES =
  /[\ud800-\udbff][\udc00-\udfff]|[\u0000-\u001f'\\\ud800-\udfff]/g

function inspectString(value, depth, opts) {
  // https://tc39.es/ecma262/multipage/structured-data.html#sec-quotejsonstring
  const string = value.replace(STRING_ESCAPES, (match) => {
    if (match.length === 2) return match

    switch (match) {
      case "'":
        return "\\'"
      case '\\':
        return '\\\\'
      case '\b':
        return '\\b'
      case '\t':
        return '\\t'
      case '\n':
        return '\\n'
      case '\f':
        return '\\f'
      case '\r':
        return '\\r'
      default:
        return '\\u' + match.charCodeAt(0).toString(16).padStart(4, '0')
    }
  })

  return new InspectLeaf("'" + string + "'", styles.string, depth, opts)
}

function inspectSymbol(value, depth, opts) {
  return new InspectLeaf(value.toString(), styles.symbol, depth, opts)
}

function inspectKey(value, depth, opts) {
  if (PLAIN_KEY.test(value)) {
    return new InspectLeaf(value, null, depth, opts)
  } else {
    return inspectValue(value, depth, opts)
  }
}

function inspectObject(type, object, depth, opts) {
  const refs = opts.references

  let ref = refs.get(object)
  if (ref === null) {
    ref = new InspectRef(depth, opts)
    refs.set(object, ref)
  } else if (ref.count) {
    ref.circular = true
    return ref
  }

  const maxDepth = typeof opts.depth === 'number' ? opts.depth : Infinity

  if (maxDepth < depth) {
    const constructor = object.constructor

    return new InspectLeaf(
      '[' +
        (constructor && constructor.name ? constructor.name : 'Object') +
        ']',
      styles.special,
      depth,
      opts
    )
  }

  const inspect =
    object[Symbol.for('bare.inspect')] ||
    object[Symbol.for('nodejs.util.inspect.custom')]

  if (typeof inspect === 'function') {
    const value = inspect.call(
      object,
      typeof opts.depth === 'number' ? opts.depth - depth : null,
      {
        colors: opts.colors,
        breakLength: opts.breakLength,
        stylize: opts.stylize
      },
      exports
    )

    if (typeof value === 'object' && value !== null) {
      refs.set(value, ref)
    }

    if (typeof value !== 'string') {
      return inspectValue(value, depth, opts)
    }

    return new InspectLeaf(value, null, depth, opts)
  }

  if (type.isArray()) return inspectArray(object, ref, depth, opts)
  if (type.isDate()) return inspectDate(object, ref, depth, opts)
  if (type.isRegExp()) return inspectRegExp(object, ref, depth, opts)
  if (type.isError()) return inspectError(object, ref, depth, opts)
  if (type.isPromise()) return inspectPromise(object, ref, depth, opts)
  if (type.isMap()) return inspectMap(object, ref, depth, opts)
  if (type.isSet()) return inspectSet(object, ref, depth, opts)
  if (type.isWeakMap()) return inspectWeakMap(object, ref, depth, opts)
  if (type.isWeakSet()) return inspectWeakSet(object, ref, depth, opts)
  if (type.isWeakRef()) return inspectWeakRef(object, ref, depth, opts)
  if (type.isArrayBuffer()) return inspectArrayBuffer(object, ref, depth, opts)
  if (type.isSharedArrayBuffer())
    return inspectSharedArrayBuffer(object, ref, depth, opts)
  if (type.isTypedArray()) return inspectTypedArray(object, ref, depth, opts)
  if (type.isDataView()) return inspectDataView(object, ref, depth, opts)

  ref.increment()

  const values = []

  for (const key in object) {
    if (key === 'constructor') continue

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(object[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  let header = '{ '

  const tag = object[Symbol.toStringTag]

  if (tag) header = '[' + tag + '] ' + header

  if (object.constructor) {
    const name = object.constructor.name

    if (name && name !== 'Object') {
      header = object.constructor.name + ' ' + header
    }
  }

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectArray(array, ref, depth, opts) {
  const { maxArrayLength = defaultMaxArrayLength } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxArrayLength, 0)

  for (let i = 0, n = array.length; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(array.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(inspectValue(array[i], depth + 1, opts))
  }

  for (const key of binding.getOwnNonIndexPropertyNames(array)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(array[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  let header = '[ '

  if (array.constructor.name !== 'Array') {
    header = array.constructor.name + '(' + array.length + ') ' + header
  }

  return new InspectSequence(header, ' ]', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectDate(date, ref, depth, opts) {
  return new InspectLeaf(date.toISOString(), styles.date, depth, opts)
}

function inspectRegExp(regExp, ref, depth, opts) {
  return new InspectLeaf(regExp.toString(), styles.regexp, depth, opts)
}

function inspectError(error, ref, depth, opts) {
  let header

  if ('stack' in error) {
    header = error.stack

    if (depth > 0) {
      header = header.replaceAll('\n', '\n' + '  '.repeat(depth))
    }
  } else {
    header = error.toString()
  }

  const builtins = ['cause']

  if (error.name === 'AggregateError') {
    builtins.push('errors')
  } else if (error.name === 'SuppressedError') {
    builtins.push('error', 'suppressed')
  }

  const values = []

  for (const key of builtins) {
    if (key in error === false) continue

    values.push(
      new InspectPair(
        ': ',
        new InspectLeaf('[' + key + ']', null, depth + 1, opts),
        inspectValue(error[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key in error) {
    if (key === 'constructor' || builtins.includes(key)) continue

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(error[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  if (values.length === 0) return new InspectLeaf(header, null, depth, opts)

  return new InspectSequence(
    header + ' {',
    ' }',
    ', ',
    values,
    ref,
    depth,
    opts
  )
}

function inspectPromise(promise, ref, depth, opts) {
  ref.increment()

  const state = binding.getPromiseState(promise)

  const values = []

  switch (state) {
    case 0: // Pending
      values.push(new InspectLeaf('<pending>', styles.special, depth, opts))
      break

    case 1: // Fulfilled
      values.push(inspectValue(binding.getPromiseResult(promise), depth, opts))
      break

    case 2: // Rejected
      values.push(
        new InspectLeaf('<rejected>', styles.special, depth, opts),
        inspectValue(binding.getPromiseResult(promise), depth, opts)
      )
  }

  ref.decrement()

  const header = promise.constructor.name + ' { '

  return new InspectSequence(header, ' }', ' ', values, ref, depth, opts)
}

function inspectMap(map, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxMapLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = maxMapLength

  for (const entry of map) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(map.size - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )
      break
    }

    values.push(
      new InspectPair(
        ' => ',
        inspectValue(entry[0], depth + 1, opts),
        inspectValue(entry[1], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key in map) {
    if (key === 'constructor') continue

    const value = inspectValue(map[key], depth + 1, opts)

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        value,
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = map.constructor.name + '(' + map.size + ') { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectSet(set, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxSetLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = maxSetLength

  for (const entry of set) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(set.size - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )
      break
    }

    values.push(inspectValue(entry, depth + 1, opts))
  }

  for (const key in set) {
    if (key === 'constructor') continue

    const value = inspectValue(set[key], depth + 1, opts)

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        value,
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = set.constructor.name + '(' + set.size + ') { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectWeakMap(weakMap, ref, depth, opts) {
  const header = weakMap.constructor.name + ' { '

  return new InspectSequence(
    header,
    ' }',
    ' ',
    [new InspectLeaf('<items unknown>', styles.special, depth + 1, opts)],
    ref,
    depth,
    opts
  )
}

function inspectWeakSet(weakSet, ref, depth, opts) {
  const header = weakSet.constructor.name + ' { '

  return new InspectSequence(
    header,
    ' }',
    ' ',
    [new InspectLeaf('<items unknown>', styles.special, depth + 1, opts)],
    ref,
    depth,
    opts
  )
}

function inspectWeakRef(weakRef, ref, depth, opts) {
  const target = weakRef.deref()

  let value

  if (target === undefined) {
    value = new InspectLeaf('<cleared>', styles.special, depth + 1, opts)
  } else {
    value = inspectValue(target, depth + 1, opts)
  }

  const header = weakRef.constructor.name + ' { '

  return new InspectSequence(header, ' }', ' ', [value], ref, depth, opts)
}

function inspectArrayBuffer(arrayBuffer, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(arrayBuffer[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = arrayBuffer.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectSharedArrayBuffer(sharedArrayBuffer, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(sharedArrayBuffer[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = sharedArrayBuffer.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectTypedArray(typedArray, ref, depth, opts) {
  if (Buffer.isBuffer(typedArray)) {
    return inspectBuffer(typedArray, ref, depth, opts)
  }

  const {
    maxArrayLength = defaultMaxArrayLength,
    maxTypedArrayLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxTypedArrayLength, 0)

  for (let i = 0, n = typedArray.length; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(typedArray.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(inspectValue(typedArray[i], depth + 1, opts))
  }

  for (const key of binding.getOwnNonIndexPropertyNames(typedArray)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(typedArray[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = typedArray.constructor.name + '(' + typedArray.length + ') [ '

  return new InspectSequence(header, ' ]', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectBuffer(buffer, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxBufferLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxBufferLength, 0)

  for (let i = 0, n = buffer.byteLength; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(buffer.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(
      new InspectLeaf(
        buffer[i].toString(16).padStart(2, '0'),
        null,
        depth + 1,
        opts
      )
    )
  }

  for (const key of binding.getOwnNonIndexPropertyNames(buffer)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(buffer[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  return new InspectSequence('<Buffer ', '>', ' ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectDataView(dataView, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength', 'byteOffset', 'buffer']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(dataView[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key of binding.getOwnNonIndexPropertyNames(dataView)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(dataView[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = dataView.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectFunction(type, fn, depth, opts) {
  if (fn.toString().startsWith('class')) return inspectClass(fn, depth, opts)

  let tag = 'function'

  if (type.isGeneratorFunction()) tag = 'generator ' + tag
  if (type.isAsyncFunction()) tag = 'async ' + tag

  return new InspectLeaf(
    '[' + tag + ' ' + (fn.name ? fn.name : '(anonymous)') + ']',
    styles.special,
    depth,
    opts
  )
}

function inspectClass(ctor, depth, opts) {
  return new InspectLeaf(
    '[class ' + (ctor.name ? ctor.name : '(anonymous)') + ']',
    styles.special,
    depth,
    opts
  )
}

function inspectExternal(external, depth, opts) {
  return new InspectLeaf(
    '[external 0x' + binding.getExternal(external).toString(16) + ']',
    styles.special,
    depth,
    opts
  )
}
{
  "name": "bare-inspect",
  "version": "3.1.4",
  "description": "Inspect objects as strings for debugging",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-inspect.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-inspect/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-inspect#readme",
  "engines": {
    "bare": ">=1.18.0"
  },
  "dependencies": {
    "bare-ansi-escapes": "^2.1.0",
    "bare-type": "^1.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
module.exports = require.addon()
const binding = require('./binding')
const errors = require('./lib/errors')
const constants = require('./lib/constants')

exports.constants = constants

exports.EOL = binding.platform === 'win32' ? '\r\n' : '\n'

exports.devNull = binding.platform === 'win32' ? '\\\\.\\nul' : '/dev/null'

exports.platform = function platform() {
  return binding.platform
}

exports.arch = function arch() {
  return binding.arch
}

exports.type = binding.type
exports.version = binding.version
exports.release = binding.release
exports.machine = binding.machine
exports.execPath = binding.execPath
exports.pid = binding.pid
exports.ppid = binding.ppid
exports.cwd = binding.cwd
exports.chdir = binding.chdir
exports.tmpdir = binding.tmpdir
exports.homedir = binding.homedir
exports.hostname = binding.hostname
exports.userInfo = binding.userInfo

exports.networkInterfaces = function networkInterfaces() {
  const result = {}

  for (const entry of binding.networkInterfaces()) {
    const { name, ...properties } = entry

    if (result[name]) result[name].push(properties)
    else result[name] = [properties]
  }

  return result
}

exports.kill = function kill(pid, signal = constants.signals.SIGTERM) {
  if (typeof signal === 'string') {
    if (signal in constants.signals === false) {
      throw errors.UNKNOWN_SIGNAL('Unknown signal: ' + signal)
    }

    signal = constants.signals[signal]
  }

  binding.kill(pid, signal)
}

exports.endianness = function endianness() {
  return binding.isLittleEndian ? 'LE' : 'BE'
}

exports.availableParallelism = binding.availableParallelism

exports.cpuUsage = function cpuUsage(previous) {
  const current = binding.cpuUsage()

  if (previous) {
    return {
      user: current.user - previous.user,
      system: current.system - previous.system
    }
  }

  return current
}

exports.threadCpuUsage = function threadCpuUsage(previous) {
  const current = binding.threadCpuUsage()

  if (previous) {
    return {
      user: current.user - previous.user,
      system: current.system - previous.system
    }
  }

  return current
}

exports.resourceUsage = binding.resourceUsage
exports.memoryUsage = binding.memoryUsage
exports.freemem = binding.freemem
exports.totalmem = binding.totalmem
exports.availableMemory = binding.availableMemory
exports.constrainedMemory = binding.constrainedMemory
exports.uptime = binding.uptime
exports.loadavg = binding.loadavg
exports.cpus = binding.cpus

exports.getProcessTitle = binding.getProcessTitle

exports.setProcessTitle = function setProcessTitle(title) {
  if (typeof title !== 'string') title = title.toString()

  if (title.length >= 256) {
    throw errors.TITLE_OVERFLOW('Process title is too long')
  }

  binding.setProcessTitle(title)
}

exports.getPriority = function getPriority(pid = 0) {
  return binding.getPriority(pid)
}

exports.setPriority = function setPriority(pid, priority) {
  if (priority === undefined) {
    priority = pid
    pid = 0
  }

  binding.setPriority(pid, priority)
}

exports.getEnvKeys = binding.getEnvKeys
exports.getEnv = binding.getEnv
exports.hasEnv = binding.hasEnv
exports.setEnv = binding.setEnv
exports.unsetEnv = binding.unsetEnv
const binding = require('../binding')

module.exports = {
  signals: binding.signals,
  errnos: binding.errnos,
  priority: binding.priority
}
module.exports = class OSError extends Error {
  constructor(msg, code, fn = OSError) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'OSError'
  }

  static UNKNOWN_SIGNAL(msg) {
    return new OSError(msg, 'UNKNOWN_SIGNAL', OSError.UNKNOWN_SIGNAL)
  }

  static TITLE_OVERFLOW(msg) {
    return new OSError(msg, 'TITLE_OVERFLOW', OSError.TITLE_OVERFLOW)
  }
}
{
  "name": "bare-os",
  "version": "3.8.7",
  "description": "Operating system utilities for Javascript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./constants": "./lib/constants.js",
    "./errors": "./lib/errors.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-os.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-os/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-os#readme",
  "engines": {
    "bare": ">=1.14.0"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "cmake-bare": "^1.1.6",
    "lunte": "^1.6.0",
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
/* global Bare */

// This export SHOULD NOT be shortened in any way as having the full
// `module.exports = require(...)` statement is crucial for synthesizing
// ESM exports.

if (Bare.platform === 'win32') {
  module.exports = require('./lib/win32')
} else {
  module.exports = require('./lib/posix')
}
module.exports = {
  CHAR_UPPERCASE_A: 0x41,
  CHAR_LOWERCASE_A: 0x61,
  CHAR_UPPERCASE_Z: 0x5a,
  CHAR_LOWERCASE_Z: 0x7a,
  CHAR_DOT: 0x2e,
  CHAR_FORWARD_SLASH: 0x2f,
  CHAR_BACKWARD_SLASH: 0x5c,
  CHAR_COLON: 0x3a,
  CHAR_QUESTION_MARK: 0x3f
}
const os = require('bare-os')

const { normalizeString } = require('./shared')
const {
  CHAR_DOT,
  CHAR_FORWARD_SLASH
} = require('./constants')

function isPosixPathSeparator (code) {
  return code === CHAR_FORWARD_SLASH
}

exports.win32 = require('./win32')
exports.posix = exports

exports.sep = '/'
exports.delimiter = ':'

exports.resolve = function resolve (...args) {
  let resolvedPath = ''
  let resolvedAbsolute = false

  for (let i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) {
    const path = i >= 0 ? args[i] : os.cwd()

    if (path.length === 0) {
      continue
    }

    resolvedPath = `${path}/${resolvedPath}`
    resolvedAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH
  }

  resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute, '/', isPosixPathSeparator)

  if (resolvedAbsolute) {
    return `/${resolvedPath}`
  }

  return resolvedPath.length > 0 ? resolvedPath : '.'
}

exports.normalize = function normalize (path) {
  if (path.length === 0) return '.'

  const isAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH
  const trailingSeparator = path.charCodeAt(path.length - 1) === CHAR_FORWARD_SLASH

  path = normalizeString(path, !isAbsolute, '/', isPosixPathSeparator)

  if (path.length === 0) {
    if (isAbsolute) return '/'
    return trailingSeparator ? './' : '.'
  }

  if (trailingSeparator) path += '/'

  return isAbsolute ? `/${path}` : path
}

exports.isAbsolute = function isAbsolute (path) {
  return path.length > 0 && path.charCodeAt(0) === CHAR_FORWARD_SLASH
}

exports.join = function join (...args) {
  if (args.length === 0) return '.'
  let joined
  for (let i = 0; i < args.length; ++i) {
    const arg = args[i]
    if (arg.length > 0) {
      if (joined === undefined) joined = arg
      else joined += `/${arg}`
    }
  }
  if (joined === undefined) return '.'
  return exports.normalize(joined)
}

exports.relative = function relative (from, to) {
  if (from === to) return ''

  from = exports.resolve(from)
  to = exports.resolve(to)

  if (from === to) return ''

  const fromStart = 1
  const fromEnd = from.length
  const fromLen = fromEnd - fromStart
  const toStart = 1
  const toLen = to.length - toStart

  const length = (fromLen < toLen ? fromLen : toLen)
  let lastCommonSep = -1
  let i = 0
  for (; i < length; i++) {
    const fromCode = from.charCodeAt(fromStart + i)
    if (fromCode !== to.charCodeAt(toStart + i)) {
      break
    } else if (fromCode === CHAR_FORWARD_SLASH) {
      lastCommonSep = i
    }
  }
  if (i === length) {
    if (toLen > length) {
      if (to.charCodeAt(toStart + i) === CHAR_FORWARD_SLASH) {
        return to.substring(toStart + i + 1)
      }
      if (i === 0) {
        return to.substring(toStart + i)
      }
    } else if (fromLen > length) {
      if (from.charCodeAt(fromStart + i) === CHAR_FORWARD_SLASH) {
        lastCommonSep = i
      } else if (i === 0) {
        lastCommonSep = 0
      }
    }
  }

  let out = ''
  for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
    if (i === fromEnd || from.charCodeAt(i) === CHAR_FORWARD_SLASH) {
      out += out.length === 0 ? '..' : '/..'
    }
  }

  return `${out}${to.substring(toStart + lastCommonSep)}`
}

exports.toNamespacedPath = function toNamespacedPath (path) {
  return path
}

exports.dirname = function dirname (path) {
  if (path.length === 0) return '.'
  const hasRoot = path.charCodeAt(0) === CHAR_FORWARD_SLASH
  let end = -1
  let matchedSlash = true
  for (let i = path.length - 1; i >= 1; --i) {
    if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) {
      if (!matchedSlash) {
        end = i
        break
      }
    } else {
      matchedSlash = false
    }
  }

  if (end === -1) return hasRoot ? '/' : '.'
  if (hasRoot && end === 1) return '//'
  return path.substring(0, end)
}

exports.basename = function basename (path, suffix) {
  let start = 0
  let end = -1
  let matchedSlash = true

  if (suffix !== undefined && suffix.length > 0 && suffix.length <= path.length) {
    if (suffix === path) { return '' }
    let extIdx = suffix.length - 1
    let firstNonSlashEnd = -1
    for (let i = path.length - 1; i >= 0; --i) {
      const code = path.charCodeAt(i)
      if (code === CHAR_FORWARD_SLASH) {
        if (!matchedSlash) {
          start = i + 1
          break
        }
      } else {
        if (firstNonSlashEnd === -1) {
          matchedSlash = false
          firstNonSlashEnd = i + 1
        }
        if (extIdx >= 0) {
          if (code === suffix.charCodeAt(extIdx)) {
            if (--extIdx === -1) {
              end = i
            }
          } else {
            extIdx = -1
            end = firstNonSlashEnd
          }
        }
      }
    }

    if (start === end) end = firstNonSlashEnd
    else if (end === -1) end = path.length
    return path.substring(start, end)
  }

  for (let i = path.length - 1; i >= 0; --i) {
    if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) {
      if (!matchedSlash) {
        start = i + 1
        break
      }
    } else if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
  }

  if (end === -1) return ''
  return path.substring(start, end)
}

exports.extname = function extname (path) {
  let startDot = -1
  let startPart = 0
  let end = -1
  let matchedSlash = true
  let preDotState = 0
  for (let i = path.length - 1; i >= 0; --i) {
    const code = path.charCodeAt(i)
    if (code === CHAR_FORWARD_SLASH) {
      if (!matchedSlash) {
        startPart = i + 1
        break
      }
      continue
    }
    if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
    if (code === CHAR_DOT) {
      if (startDot === -1) startDot = i
      else if (preDotState !== 1) preDotState = 1
    } else if (startDot !== -1) {
      preDotState = -1
    }
  }

  if (startDot === -1 || end === -1 || preDotState === 0 || (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1)) {
    return ''
  }
  return path.substring(startDot, end)
}
const {
  CHAR_DOT,
  CHAR_FORWARD_SLASH
} = require('./constants')

exports.normalizeString = function normalizeString (path, allowAboveRoot, separator, isPathSeparator) {
  let res = ''
  let lastSegmentLength = 0
  let lastSlash = -1
  let dots = 0
  let code = 0
  for (let i = 0; i <= path.length; ++i) {
    if (i < path.length) {
      code = path.charCodeAt(i)
    } else if (isPathSeparator(code)) {
      break
    } else {
      code = CHAR_FORWARD_SLASH
    }

    if (isPathSeparator(code)) {
      if (lastSlash === i - 1 || dots === 1) ;
      else if (dots === 2) {
        if (res.length < 2 || lastSegmentLength !== 2 || res.charCodeAt(res.length - 1) !== CHAR_DOT || res.charCodeAt(res.length - 2) !== CHAR_DOT) {
          if (res.length > 2) {
            const lastSlashIndex = res.lastIndexOf(separator)
            if (lastSlashIndex === -1) {
              res = ''
              lastSegmentLength = 0
            } else {
              res = res.substring(0, lastSlashIndex)
              lastSegmentLength =
                res.length - 1 - res.lastIndexOf(separator)
            }
            lastSlash = i
            dots = 0
            continue
          } else if (res.length !== 0) {
            res = ''
            lastSegmentLength = 0
            lastSlash = i
            dots = 0
            continue
          }
        }
        if (allowAboveRoot) {
          res += res.length > 0 ? `${separator}..` : '..'
          lastSegmentLength = 2
        }
      } else {
        if (res.length > 0) {
          res += `${separator}${path.substring(lastSlash + 1, i)}`
        } else {
          res = path.substring(lastSlash + 1, i)
        }
        lastSegmentLength = i - lastSlash - 1
      }
      lastSlash = i
      dots = 0
    } else if (code === CHAR_DOT && dots !== -1) {
      ++dots
    } else {
      dots = -1
    }
  }
  return res
}
const os = require('bare-os')

const { normalizeString } = require('./shared')
const {
  CHAR_UPPERCASE_A,
  CHAR_LOWERCASE_A,
  CHAR_UPPERCASE_Z,
  CHAR_LOWERCASE_Z,
  CHAR_DOT,
  CHAR_FORWARD_SLASH,
  CHAR_BACKWARD_SLASH,
  CHAR_COLON,
  CHAR_QUESTION_MARK
} = require('./constants')

function isWindowsPathSeparator (code) {
  return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH
}

function isWindowsDeviceRoot (code) {
  return (code >= CHAR_UPPERCASE_A && code <= CHAR_UPPERCASE_Z) ||
         (code >= CHAR_LOWERCASE_A && code <= CHAR_LOWERCASE_Z)
}

exports.posix = require('./posix')
exports.win32 = exports

exports.sep = '\\'
exports.delimiter = ';'

exports.resolve = function resolve (...args) {
  let resolvedDevice = ''
  let resolvedTail = ''
  let resolvedAbsolute = false

  for (let i = args.length - 1; i >= -1; i--) {
    let path
    if (i >= 0) {
      path = args[i]

      if (path.length === 0) continue
    } else if (resolvedDevice.length === 0) {
      path = os.cwd()
    } else {
      path = os.getEnv(`=${resolvedDevice}`) || os.cwd()

      if (path === undefined || (path.substring(0, 2).toLowerCase() !== resolvedDevice.toLowerCase() && path.charCodeAt(2) === CHAR_BACKWARD_SLASH)) {
        path = `${resolvedDevice}\\`
      }
    }

    const len = path.length
    let rootEnd = 0
    let device = ''
    let isAbsolute = false
    const code = path.charCodeAt(0)

    if (len === 1) {
      if (isWindowsPathSeparator(code)) {
        rootEnd = 1
        isAbsolute = true
      }
    } else if (isWindowsPathSeparator(code)) {
      isAbsolute = true

      if (isWindowsPathSeparator(path.charCodeAt(1))) {
        let j = 2
        let last = j
        while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
          j++
        }
        if (j < len && j !== last) {
          const firstPart = path.substring(last, j)
          last = j
          while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
            j++
          }
          if (j < len && j !== last) {
            last = j
            while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
              j++
            }
            if (j === len || j !== last) {
              device = `\\\\${firstPart}\\${path.substring(last, j)}`
              rootEnd = j
            }
          }
        }
      } else {
        rootEnd = 1
      }
    } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
      device = path.substring(0, 2)
      rootEnd = 2
      if (len > 2 && isWindowsPathSeparator(path.charCodeAt(2))) {
        isAbsolute = true
        rootEnd = 3
      }
    }

    if (device.length > 0) {
      if (resolvedDevice.length > 0) {
        if (device.toLowerCase() !== resolvedDevice.toLowerCase()) { continue }
      } else {
        resolvedDevice = device
      }
    }

    if (resolvedAbsolute) {
      if (resolvedDevice.length > 0) { break }
    } else {
      resolvedTail = `${path.substring(rootEnd)}\\${resolvedTail}`
      resolvedAbsolute = isAbsolute
      if (isAbsolute && resolvedDevice.length > 0) {
        break
      }
    }
  }

  resolvedTail = normalizeString(resolvedTail, !resolvedAbsolute, '\\', isWindowsPathSeparator)

  return resolvedAbsolute ? `${resolvedDevice}\\${resolvedTail}` : `${resolvedDevice}${resolvedTail}` || '.'
}

exports.normalize = function normalize (path) {
  const len = path.length
  if (len === 0) return '.'
  let rootEnd = 0
  let device
  let isAbsolute = false
  const code = path.charCodeAt(0)

  if (len === 1) {
    return code === CHAR_FORWARD_SLASH ? '\\' : path
  }

  if (isWindowsPathSeparator(code)) {
    isAbsolute = true

    if (isWindowsPathSeparator(path.charCodeAt(1))) {
      let j = 2
      let last = j
      while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
        j++
      }
      if (j < len && j !== last) {
        const firstPart = path.substring(last, j)
        last = j
        while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
          j++
        }
        if (j < len && j !== last) {
          last = j
          while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
            j++
          }
          if (j === len) {
            return `\\\\${firstPart}\\${path.substring(last)}\\`
          }
          if (j !== last) {
            device = `\\\\${firstPart}\\${path.substring(last, j)}`
            rootEnd = j
          }
        }
      }
    } else {
      rootEnd = 1
    }
  } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
    device = path.substring(0, 2)
    rootEnd = 2
    if (len > 2 && isWindowsPathSeparator(path.charCodeAt(2))) {
      isAbsolute = true
      rootEnd = 3
    }
  }

  let tail = rootEnd < len ? normalizeString(path.substring(rootEnd), !isAbsolute, '\\', isWindowsPathSeparator) : ''
  if (tail.length === 0 && !isAbsolute) {
    tail = '.'
  }
  if (tail.length > 0 && isWindowsPathSeparator(path.charCodeAt(len - 1))) {
    tail += '\\'
  }
  if (device === undefined) {
    return isAbsolute ? `\\${tail}` : tail
  }
  return isAbsolute ? `${device}\\${tail}` : `${device}${tail}`
}

exports.isAbsolute = function isAbsolute (path) {
  const len = path.length
  if (len === 0) return false

  const code = path.charCodeAt(0)

  return isWindowsPathSeparator(code) || (len > 2 && isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON && isWindowsPathSeparator(path.charCodeAt(2)))
}

exports.join = function join (...args) {
  if (args.length === 0) return '.'

  let joined
  let firstPart
  for (let i = 0; i < args.length; ++i) {
    const arg = args[i]
    if (arg.length > 0) {
      if (joined === undefined) joined = firstPart = arg
      else joined += `\\${arg}`
    }
  }

  if (joined === undefined) return '.'

  let needsReplace = true
  let slashCount = 0
  if (isWindowsPathSeparator(firstPart.charCodeAt(0))) {
    ++slashCount
    const firstLen = firstPart.length
    if (firstLen > 1 && isWindowsPathSeparator(firstPart.charCodeAt(1))) {
      ++slashCount
      if (firstLen > 2) {
        if (isWindowsPathSeparator(firstPart.charCodeAt(2))) {
          ++slashCount
        } else {
          needsReplace = false
        }
      }
    }
  }
  if (needsReplace) {
    while (slashCount < joined.length && isWindowsPathSeparator(joined.charCodeAt(slashCount))) {
      slashCount++
    }

    if (slashCount >= 2) {
      joined = `\\${joined.substring(slashCount)}`
    }
  }

  return exports.normalize(joined)
}

exports.relative = function relative (from, to) {
  if (from === to) return ''

  const fromOrig = exports.resolve(from)
  const toOrig = exports.resolve(to)

  if (fromOrig === toOrig) return ''

  from = fromOrig.toLowerCase()
  to = toOrig.toLowerCase()

  if (from === to) return ''

  let fromStart = 0
  while (fromStart < from.length && from.charCodeAt(fromStart) === CHAR_BACKWARD_SLASH) {
    fromStart++
  }
  let fromEnd = from.length
  while (fromEnd - 1 > fromStart && from.charCodeAt(fromEnd - 1) === CHAR_BACKWARD_SLASH) {
    fromEnd--
  }
  const fromLen = fromEnd - fromStart

  let toStart = 0
  while (toStart < to.length && to.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) {
    toStart++
  }
  let toEnd = to.length
  while (toEnd - 1 > toStart && to.charCodeAt(toEnd - 1) === CHAR_BACKWARD_SLASH) {
    toEnd--
  }
  const toLen = toEnd - toStart

  const length = fromLen < toLen ? fromLen : toLen
  let lastCommonSep = -1
  let i = 0
  for (; i < length; i++) {
    const fromCode = from.charCodeAt(fromStart + i)
    if (fromCode !== to.charCodeAt(toStart + i)) {
      break
    } else if (fromCode === CHAR_BACKWARD_SLASH) {
      lastCommonSep = i
    }
  }

  if (i !== length) {
    if (lastCommonSep === -1) return toOrig
  } else {
    if (toLen > length) {
      if (to.charCodeAt(toStart + i) === CHAR_BACKWARD_SLASH) {
        return toOrig.substring(toStart + i + 1)
      }
      if (i === 2) {
        return toOrig.substring(toStart + i)
      }
    }
    if (fromLen > length) {
      if (from.charCodeAt(fromStart + i) === CHAR_BACKWARD_SLASH) {
        lastCommonSep = i
      } else if (i === 2) {
        lastCommonSep = 3
      }
    }
    if (lastCommonSep === -1) lastCommonSep = 0
  }

  let out = ''
  for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
    if (i === fromEnd || from.charCodeAt(i) === CHAR_BACKWARD_SLASH) {
      out += out.length === 0 ? '..' : '\\..'
    }
  }

  toStart += lastCommonSep

  if (out.length > 0) {
    return `${out}${toOrig.substring(toStart, toEnd)}`
  }
  if (toOrig.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) {
    ++toStart
  }
  return toOrig.substring(toStart, toEnd)
}

exports.toNamespacedPath = function toNamespacedPath (path) {
  if (path.length === 0) return path

  const resolvedPath = exports.resolve(path)

  if (resolvedPath.length <= 2) return path

  if (resolvedPath.charCodeAt(0) === CHAR_BACKWARD_SLASH) {
    if (resolvedPath.charCodeAt(1) === CHAR_BACKWARD_SLASH) {
      const code = resolvedPath.charCodeAt(2)
      if (code !== CHAR_QUESTION_MARK && code !== CHAR_DOT) {
        return `\\\\?\\UNC\\${resolvedPath.substring(2)}`
      }
    }
  } else if (
    isWindowsDeviceRoot(resolvedPath.charCodeAt(0)) &&
      resolvedPath.charCodeAt(1) === CHAR_COLON &&
      resolvedPath.charCodeAt(2) === CHAR_BACKWARD_SLASH
  ) {
    return `\\\\?\\${resolvedPath}`
  }

  return path
}

exports.dirname = function dirname (path) {
  const len = path.length
  if (len === 0) return '.'
  let rootEnd = -1
  let offset = 0
  const code = path.charCodeAt(0)

  if (len === 1) {
    return isWindowsPathSeparator(code) ? path : '.'
  }

  if (isWindowsPathSeparator(code)) {
    rootEnd = offset = 1

    if (isWindowsPathSeparator(path.charCodeAt(1))) {
      let j = 2
      let last = j
      while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
        j++
      }
      if (j < len && j !== last) {
        last = j
        while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
          j++
        }
        if (j < len && j !== last) {
          last = j
          while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
            j++
          }
          if (j === len) {
            return path
          }
          if (j !== last) {
            rootEnd = offset = j + 1
          }
        }
      }
    }
  } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
    rootEnd = len > 2 && isWindowsPathSeparator(path.charCodeAt(2)) ? 3 : 2
    offset = rootEnd
  }

  let end = -1
  let matchedSlash = true
  for (let i = len - 1; i >= offset; --i) {
    if (isWindowsPathSeparator(path.charCodeAt(i))) {
      if (!matchedSlash) {
        end = i
        break
      }
    } else {
      matchedSlash = false
    }
  }

  if (end === -1) {
    if (rootEnd === -1) return '.'

    end = rootEnd
  }
  return path.substring(0, end)
}

exports.basename = function basename (path, suffix) {
  let start = 0
  let end = -1
  let matchedSlash = true

  if (path.length >= 2 && isWindowsDeviceRoot(path.charCodeAt(0)) && path.charCodeAt(1) === CHAR_COLON) {
    start = 2
  }

  if (suffix !== undefined && suffix.length > 0 && suffix.length <= path.length) {
    if (suffix === path) return ''
    let extIdx = suffix.length - 1
    let firstNonSlashEnd = -1
    for (let i = path.length - 1; i >= start; --i) {
      const code = path.charCodeAt(i)
      if (isWindowsPathSeparator(code)) {
        if (!matchedSlash) {
          start = i + 1
          break
        }
      } else {
        if (firstNonSlashEnd === -1) {
          matchedSlash = false
          firstNonSlashEnd = i + 1
        }
        if (extIdx >= 0) {
          if (code === suffix.charCodeAt(extIdx)) {
            if (--extIdx === -1) {
              end = i
            }
          } else {
            extIdx = -1
            end = firstNonSlashEnd
          }
        }
      }
    }

    if (start === end) end = firstNonSlashEnd
    else if (end === -1) end = path.length
    return path.substring(start, end)
  }
  for (let i = path.length - 1; i >= start; --i) {
    if (isWindowsPathSeparator(path.charCodeAt(i))) {
      if (!matchedSlash) {
        start = i + 1
        break
      }
    } else if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
  }

  if (end === -1) return ''
  return path.substring(start, end)
}

exports.extname = function extname (path) {
  let start = 0
  let startDot = -1
  let startPart = 0
  let end = -1
  let matchedSlash = true
  let preDotState = 0

  if (path.length >= 2 && path.charCodeAt(1) === CHAR_COLON && isWindowsDeviceRoot(path.charCodeAt(0))) {
    start = startPart = 2
  }

  for (let i = path.length - 1; i >= start; --i) {
    const code = path.charCodeAt(i)
    if (isWindowsPathSeparator(code)) {
      if (!matchedSlash) {
        startPart = i + 1
        break
      }
      continue
    }
    if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
    if (code === CHAR_DOT) {
      if (startDot === -1) startDot = i
      else if (preDotState !== 1) preDotState = 1
    } else if (startDot !== -1) {
      preDotState = -1
    }
  }

  if (startDot === -1 || end === -1 || preDotState === 0 || (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1)) {
    return ''
  }
  return path.substring(startDot, end)
}
{
  "name": "bare-path",
  "version": "3.0.0",
  "description": "Path manipulation library for JavaScript",
  "exports": {
    ".": "./index.js",
    "./package": "./package.json",
    "./posix": "./lib/posix.js",
    "./win32": "./lib/win32.js"
  },
  "files": [
    "index.js",
    "lib",
    "NOTICE"
  ],
  "scripts": {
    "test": "standard && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-path.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-path/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-path#readme",
  "dependencies": {
    "bare-os": "^3.0.1"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "standard": "^17.0.0"
  }
}
const stream = require('streamx')
const { ReadableStream, WritableStream } = require('./web')

const defaultEncoding = 'utf8'

module.exports = exports = stream.Stream

exports.pipeline = stream.pipeline

exports.isStream = stream.isStream
exports.isEnding = stream.isEnding
exports.isEnded = stream.isEnded
exports.isFinishing = stream.isFinishing
exports.isFinished = stream.isFinished
exports.isDisturbed = stream.isDisturbed

exports.isErrored = function isErrored(stream) {
  return exports.getStreamError(stream) !== null
}

exports.isReadable = function isReadable(stream) {
  return stream.readable && !stream.destroying && !exports.isEnded(stream)
}

exports.isWritable = function isWritable(stream) {
  return stream.writable && !stream.destroying && !exports.isFinishing(stream)
}

exports.getStreamError = stream.getStreamError

exports.addAbortSignal = function addAbortSignal(signal, stream) {
  function onAbort() {
    stream.destroy(signal.reason)
  }

  if (signal.aborted) onAbort()
  else signal.addEventListener('abort', onAbort)

  return stream
}

exports.Stream = exports

exports.Readable = class Readable extends stream.Readable {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthReadable: null,
      map: null,
      mapReadable: null
    })

    if (this._construct) this._open = this._construct

    if (this._read !== stream.Readable.prototype._read) {
      this._read = read.bind(this, this._read)
    }

    if (this._destroy !== stream.Stream.prototype._destroy) {
      this._destroy = destroy.bind(this, this._destroy)
    }
  }

  get closed() {
    return !exports.isReadable(this)
  }

  get errored() {
    return stream.getStreamError(this)
  }

  push(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = Buffer.from(chunk, encoding || defaultEncoding)
    }

    return super.push(chunk)
  }

  unshift(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = Buffer.from(chunk, encoding || defaultEncoding)
    }

    super.unshift(chunk)
  }

  static fromWeb(readableStream, opts = {}) {
    const stream = readableStream._stream

    if (opts.encoding) stream.setEncoding(opts.encoding)
    if (opts.signal) exports.addAbortSignal(opts.signal, stream)

    return stream
  }

  static toWeb(readable, opts = {}) {
    return new ReadableStream(readable, opts.strategy)
  }

  async [Symbol.asyncDispose]() {
    if (!this.destroyed) this.destroy()

    await new Promise((resolve) => exports.finished(this, resolve))
  }
}

exports.Writable = class Writable extends stream.Writable {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthWritable,
      map: null,
      mapWritable: null
    })

    if (this._construct) this._open = this._construct

    if (this._write !== stream.Writable.prototype._write) {
      this._write = write.bind(this, this._write)
    }

    if (this._destroy !== stream.Stream.prototype._destroy) {
      this._destroy = destroy.bind(this, this._destroy)
    }
  }

  get closed() {
    return !exports.isWritable(this)
  }

  get errored() {
    return stream.getStreamError(this)
  }

  write(chunk, encoding, cb) {
    if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = Buffer.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result = super.write({ chunk, encoding })

    if (cb) stream.Writable.drained(this).then(() => cb(null), cb)

    return result
  }

  end(chunk, encoding, cb) {
    if (typeof chunk === 'function') {
      cb = chunk
      chunk = null
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = Buffer.from(chunk, encoding || defaultEncoding)
    } else {
      encoding = 'buffer'
    }

    const result =
      chunk !== undefined && chunk !== null ? super.end({ chunk, encoding }) : super.end()

    if (cb) this.once('finish', () => cb(null))

    return result
  }

  static fromWeb(writableStream, opts = {}) {
    const stream = writableStream._stream

    if (opts.signal) exports.addAbortSignal(opts.signal, stream)

    return stream
  }

  static toWeb(writable) {
    return new WritableStream(writable)
  }

  async [Symbol.asyncDispose]() {
    if (!this.destroyed) this.destroy()

    await new Promise((resolve) => exports.finished(this, resolve))
  }
}

exports.Duplex = class Duplex extends stream.Duplex {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthReadable: null,
      byteLengthWritable,
      map: null,
      mapReadable: null,
      mapWritable: null
    })

    if (this._construct) this._open = this._construct

    if (this._read !== stream.Readable.prototype._read) {
      this._read = read.bind(this, this._read)
    }

    if (this._write !== stream.Duplex.prototype._write) {
      this._write = write.bind(this, this._write)
    }

    if (this._destroy !== stream.Stream.prototype._destroy) {
      this._destroy = destroy.bind(this, this._destroy)
    }
  }

  push(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = Buffer.from(chunk, encoding || defaultEncoding)
    }

    return super.push(chunk)
  }

  unshift(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = Buffer.from(chunk, encoding || defaultEncoding)
    }

    super.unshift(chunk)
  }

  write(chunk, encoding, cb) {
    if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = Buffer.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result = super.write({ chunk, encoding })

    if (cb) stream.Writable.drained(this).then(() => cb(null), cb)

    return result
  }

  end(chunk, encoding, cb) {
    if (typeof chunk === 'function') {
      cb = chunk
      chunk = null
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = Buffer.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result =
      chunk !== undefined && chunk !== null ? super.end({ chunk, encoding }) : super.end()

    if (cb) this.once('finish', () => cb(null))

    return result
  }

  static fromWeb({ readable: readableStream, writable: writableStream }, opts) {
    const readable = exports.Readable.fromWeb(readableStream, opts)
    const writable = exports.Readable.fromWeb(writableStream, opts)

    const duplex = new exports.Duplex({
      write(data, encoding, cb) {
        writable.write(data, encoding, cb)
      }
    })

    readable
      .on('data', (data) => duplex.push(data))
      .on('end', () => duplex.push(null))
      .on('error', (err) => duplex.destroy(err))

    writable.on('finish', () => duplex.end()).on('error', (err) => duplex.destroy(err))

    return duplex
  }

  static toWeb(duplex) {
    const readableStream = exports.Readable.toWeb(duplex)
    const writableStream = exports.Writable.toWeb(duplex)

    return { readable: readableStream, writable: writableStream }
  }
}

class DuplexSide extends exports.Duplex {
  constructor(opts) {
    super(opts)

    this._otherSide = null
    this._cb = null
  }

  _read() {
    const cb = this._cb
    if (!cb) return

    this._cb = null
    cb()
  }

  _write(chunk, encoding, cb) {
    this._otherSide.push(chunk, encoding)
    this._otherSide._cb = cb
  }

  _final(cb) {
    this._otherSide.on('end', cb)
    this._otherSide.push(null)
  }
}

exports.duplexPair = function duplexPair(opts) {
  const sideA = new DuplexSide(opts)
  const sideB = new DuplexSide(opts)

  sideA._otherSide = sideB
  sideB._otherSide = sideA

  return [sideA, sideB]
}

exports.Transform = class Transform extends stream.Transform {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthReadable: null,
      byteLengthWritable,
      map: null,
      mapReadable: null,
      mapWritable: null
    })

    if (this._transform !== stream.Transform.prototype._transform) {
      this._transform = transform.bind(this, this._transform)
    } else {
      this._transform = passthrough
    }
  }

  push(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = Buffer.from(chunk, encoding || defaultEncoding)
    }

    return super.push(chunk)
  }

  unshift(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = Buffer.from(chunk, encoding || defaultEncoding)
    }

    super.unshift(chunk)
  }

  write(chunk, encoding, cb) {
    if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = Buffer.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result = super.write({ chunk, encoding })

    if (cb) stream.Writable.drained(this).then(() => cb(null), cb)

    return result
  }

  end(chunk, encoding, cb) {
    if (typeof chunk === 'function') {
      cb = chunk
      chunk = null
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = Buffer.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result =
      chunk !== undefined && chunk !== null ? super.end({ chunk, encoding }) : super.end()

    if (cb) this.once('finish', () => cb(null))

    return result
  }
}

exports.PassThrough = class PassThrough extends exports.Transform {}

exports.finished = function finished(stream, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (!opts) opts = {}

  const { cleanup = false } = opts

  const done = () => {
    cb(exports.getStreamError(stream, { all: true }))

    if (cleanup) detach()
  }

  const detach = () => {
    stream.off('close', done)
    stream.off('error', noop)
  }

  if (stream.destroyed) {
    done()
  } else {
    stream.on('close', done)
    stream.on('error', noop)
  }

  return detach
}

function read(read, cb) {
  read.call(this, 65536)

  cb(null)
}

function write(write, data, cb) {
  write.call(this, data.chunk, data.encoding, cb)
}

function transform(transform, data, cb) {
  transform.call(this, data.chunk, data.encoding, cb)
}

function destroy(destroy, cb) {
  destroy.call(this, exports.getStreamError(this), cb)
}

function passthrough(data, cb) {
  cb(null, data.chunk)
}

function byteLengthWritable(data) {
  return data.chunk.byteLength
}

function noop() {}
{
  "name": "bare-stream",
  "version": "2.13.0",
  "description": "Streaming data for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./promises": "./promises.js",
    "./web": {
      "types": "./web.d.ts",
      "default": "./web.js"
    },
    "./global": "./global.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "promises.js",
    "web.js",
    "web.d.ts",
    "global.js"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-stream.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-stream/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-stream#readme",
  "dependencies": {
    "streamx": "^2.25.0",
    "teex": "^1.0.1"
  },
  "devDependencies": {
    "bare-abort-controller": "^1.1.0",
    "bare-buffer": "^3.0.0",
    "bare-events": "^2.5.4",
    "brittle": "^3.5.2",
    "lunte": "^1.6.0",
    "prettier": "^3.3.3",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "bare-abort-controller": "*",
    "bare-buffer": "*",
    "bare-events": "*"
  },
  "peerDependenciesMeta": {
    "bare-abort-controller": {
      "optional": true
    },
    "bare-buffer": {
      "optional": true
    },
    "bare-events": {
      "optional": true
    }
  }
}
const { Readable, Writable, Transform, getStreamError, isStreamx, isDisturbed } = require('streamx')
const tee = require('teex')

const readableKind = Symbol.for('bare.stream.readable.kind')
const writableKind = Symbol.for('bare.stream.writable.kind')
const transformKind = Symbol.for('bare.stream.transform.kind')

// https://streams.spec.whatwg.org/#readablestreamdefaultreader
exports.ReadableStreamDefaultReader = class ReadableStreamDefaultReader {
  constructor(stream) {
    this._stream = stream
    this._stream._stream.once('close', onclose).once('error', onerror)

    const closed = Promise.withResolvers()

    // Avoid unhandled exceptions
    closed.promise.catch(noop)

    this._closed = closed

    function onclose() {
      closed.resolve()
    }

    function onerror(err) {
      closed.reject(err)
    }
  }

  get closed() {
    return this._closed.promise
  }

  read() {
    const stream = this._stream._stream

    return new Promise((resolve, reject) => {
      const err = getStreamError(stream)

      if (err) return reject(err)

      if (stream.destroyed) {
        return resolve({ value: undefined, done: true })
      }

      const value = stream.read()

      if (value !== null) {
        return resolve({ value, done: false })
      }

      stream.once('readable', onreadable).once('close', onclose).once('error', onerror)

      function onreadable() {
        const value = stream.read()

        ondone(null, value === null ? { value: undefined, done: true } : { value, done: false })
      }

      function onclose() {
        ondone(null, { value: undefined, done: true })
      }

      function onerror(err) {
        ondone(err, null)
      }

      function ondone(err, value) {
        stream.off('readable', onreadable).off('close', onclose).off('error', onerror)

        if (err) reject(err)
        else resolve(value)
      }
    })
  }

  releaseLock() {
    this._closed.reject(new TypeError('Reader was released'))
    this._stream._releaseLock()
    this._stream = null
  }

  cancel(reason = new TypeError('Stream was cancelled')) {
    const stream = this._stream._stream

    if (stream.destroyed) return Promise.resolve()

    return new Promise((resolve) =>
      stream.once('close', resolve).once('error', noop).destroy(reason)
    )
  }
}

// https://streams.spec.whatwg.org/#readablestreamdefaultcontroller
exports.ReadableStreamDefaultController = class ReadableStreamDefaultController {
  constructor(stream) {
    this._stream = stream
  }

  get desiredSize() {
    const stream = this._stream._stream

    return stream._readableState.highWaterMark - stream._readableState.buffered
  }

  enqueue(data) {
    this._stream._stream.push(data)
  }

  close() {
    this._stream._stream.push(null)
  }

  error(err) {
    this._stream._stream.destroy(err)
  }
}

// https://streams.spec.whatwg.org/#readablestream
class ReadableStream {
  static get [readableKind]() {
    return 0 // Compatibility version
  }

  static from(iterable) {
    return new ReadableStream(Readable.from(iterable))
  }

  constructor(underlyingSource = {}, queuingStrategy) {
    if (isStreamx(underlyingSource)) {
      this._stream = underlyingSource
    } else {
      if (queuingStrategy === undefined) {
        queuingStrategy = new exports.CountQueuingStrategy()
      }

      const { start, pull, cancel } = underlyingSource
      const { highWaterMark = 1, size = defaultSize } = queuingStrategy

      this._stream = new Readable({ highWaterMark, byteLength: size })

      const controller = new exports.ReadableStreamDefaultController(this)

      if (start) {
        this._stream._open = this._open.bind(this, start.call(this, controller))
      }

      if (pull) {
        this._stream._read = this._read.bind(this, pull.bind(this, controller))
      }

      if (cancel) {
        this._stream.once('error', cancel)
      }
    }

    this._reader = null
  }

  get [readableKind]() {
    return ReadableStream[readableKind]
  }

  get locked() {
    return this._reader !== null
  }

  getReader() {
    if (this.locked) throw new TypeError('Stream is locked')

    this._reader = new exports.ReadableStreamDefaultReader(this)

    return this._reader
  }

  cancel(reason = new TypeError('Stream was cancelled')) {
    const stream = this._stream

    if (stream.destroyed) return Promise.resolve()

    if (this.locked) return Promise.reject(new TypeError('Stream is locked'))

    return new Promise((resolve) =>
      stream.once('close', resolve).once('error', noop).destroy(reason)
    )
  }

  tee() {
    const [a, b] = tee(this._stream)

    return [new ReadableStream(a), new ReadableStream(b)]
  }

  pipeTo(destination) {
    return new Promise((resolve, reject) =>
      this._stream.pipe(destination._stream, (err) => {
        err ? reject(err) : resolve()
      })
    )
  }

  [Symbol.asyncIterator]() {
    return this._stream[Symbol.asyncIterator]()
  }

  _releaseLock() {
    this._reader = null
  }

  async _open(starting, cb) {
    let err = null
    try {
      await starting
    } catch (e) {
      err = e
    }
    cb(err)
  }

  async _read(pull, cb) {
    let err = null
    try {
      await pull()
    } catch (e) {
      err = e
    }
    cb(err)
  }
}

function defaultSize() {
  return 1
}

exports.ReadableStream = ReadableStream

// https://streams.spec.whatwg.org/#countqueuingstrategy
exports.CountQueuingStrategy = class CountQueuingStrategy {
  constructor(opts = {}) {
    const { highWaterMark = 1 } = opts

    this.highWaterMark = highWaterMark
  }

  size(chunk) {
    return 1
  }
}

// https://streams.spec.whatwg.org/#bytelengthqueuingstrategy
exports.ByteLengthQueuingStrategy = class ByteLengthQueuingStrategy {
  constructor(opts = {}) {
    const { highWaterMark = 16384 } = opts

    this.highWaterMark = highWaterMark
  }

  size(chunk) {
    return chunk.byteLength
  }
}

exports.isReadableStream = function isReadableStream(value) {
  if (value instanceof ReadableStream) return true

  return (
    typeof value === 'object' &&
    value !== null &&
    value[readableKind] === ReadableStream[readableKind]
  )
}

// https://streams.spec.whatwg.org/#readablestream-errored
exports.isReadableStreamErrored = function isReadableStreamErrored(stream) {
  return getStreamError(stream._stream) !== null
}

// https://streams.spec.whatwg.org/#is-readable-stream-disturbed
exports.isReadableStreamDisturbed = function isReadableStreamDisturbed(stream) {
  return isDisturbed(stream._stream)
}

// https://streams.spec.whatwg.org/#writablestreamdefaultwriter
exports.WritableStreamDefaultWriter = class WritableStreamDefaultWriter {
  constructor(stream) {
    this._stream = stream
    this._stream._stream.once('close', onclose).once('error', onerror)

    const closed = Promise.withResolvers()

    // Avoid unhandled exceptions
    closed.promise.catch(noop)

    this._closed = closed

    function onclose() {
      closed.resolve()
    }

    function onerror(err) {
      closed.reject(err)
    }
  }

  get desiredSize() {
    const stream = this._stream._stream

    return stream._writableState.highWaterMark - stream._writableState.buffered
  }

  get closed() {
    return this._closed.promise
  }

  get ready() {
    const stream = this._stream._stream

    if (getStreamError(stream)) return Promise.reject()

    return Writable.drained(stream).then()
  }

  async write(chunk) {
    const stream = this._stream._stream

    let err = getStreamError(stream)
    if (err) return Promise.reject(err)

    stream.write(chunk)

    await Writable.drained(stream)

    err = getStreamError(stream)
    if (err) return Promise.reject(err)
  }

  releaseLock() {
    this._closed.reject(new TypeError('Writer was released'))
    this._stream._releaseLock()
    this._stream = null
  }

  close() {
    const stream = this._stream._stream

    if (stream.destroyed) return Promise.resolve()

    return new Promise((resolve) => stream.once('close', resolve).end())
  }

  abort(reason = new TypeError('Stream was aborted')) {
    const stream = this._stream._stream

    if (stream.destroyed) return Promise.resolve()

    return new Promise((resolve) => stream.once('close', resolve).destroy(reason))
  }
}

// https://streams.spec.whatwg.org/#writablestreamdefaultcontroller
exports.WritableStreamDefaultController = class WritableStreamDefaultController {
  constructor(stream) {
    this._stream = stream
  }

  error(err) {
    this._stream._stream.destroy(err)
  }
}

// https://streams.spec.whatwg.org/#writablestream
class WritableStream {
  static get [writableKind]() {
    return 0 // Compatibility version
  }

  constructor(underlyingSink = {}, queuingStrategy = {}) {
    if (isStreamx(underlyingSink)) {
      this._stream = underlyingSink
    } else {
      if (queuingStrategy === undefined) {
        queuingStrategy = new exports.CountQueuingStrategy()
      }

      const { start, write, close, abort } = underlyingSink
      const { highWaterMark = 1, size = defaultSize } = queuingStrategy

      this._stream = new Writable({ highWaterMark, byteLength: size })

      this._controller = new exports.WritableStreamDefaultController(this)

      if (start) {
        this._stream._open = this._open.bind(this, start.call(this, this._controller))
      }

      if (write) {
        this._stream._write = this._write.bind(this, write)
      }

      if (close) {
        this._stream._destroy = this._destroy.bind(this, close.call(this))
      }

      if (abort) {
        this._stream.once('error', abort)
      }
    }

    this._writer = null
  }

  get [writableKind]() {
    return WritableStream[writableKind]
  }

  get locked() {
    return this._writer !== null
  }

  getWriter() {
    if (this.locked) throw new TypeError('Stream is locked')

    this._writer = new exports.WritableStreamDefaultWriter(this)

    return this._writer
  }

  abort(reason = new TypeError('Stream was aborted')) {
    if (this._stream.destroyed) return Promise.resolve()

    if (this.locked) return Promise.reject(new TypeError('Stream is locked'))

    return new Promise((resolve) => this._stream.once('close', resolve).destroy(reason))
  }

  close() {
    if (this._stream.destroyed) return Promise.resolve()

    if (this.locked) return Promise.reject(new TypeError('Stream is locked'))

    return new Promise((resolve) => this._stream.once('close', resolve).end())
  }

  _releaseLock() {
    this._writer = null
  }

  async _open(starting, cb) {
    let err = null
    try {
      await starting
    } catch (e) {
      err = e
    }
    cb(err)
  }

  async _write(write, data, cb) {
    let err = null
    try {
      await write(data, this._controller)
    } catch (e) {
      err = e
    }
    cb(err)
  }

  async _destroy(closing, cb) {
    let err = null
    try {
      await closing
    } catch (e) {
      err = e
    }
    cb(err)
  }
}

exports.WritableStream = WritableStream

exports.isWritableStream = function isWritableStream(value) {
  if (value instanceof WritableStream) return true

  return (
    typeof value === 'object' &&
    value !== null &&
    value[writableKind] === WritableStream[writableKind]
  )
}

// https://streams.spec.whatwg.org/#transformstreamdefaultcontroller
exports.TransformStreamDefaultController = class TransformStreamDefaultController {
  constructor(stream) {
    this._stream = stream
  }

  get desiredSize() {
    const stream = this._stream._stream

    return stream._readableState.highWaterMark - stream._readableState.buffered
  }

  enqueue(data) {
    this._stream._stream.push(data)
  }

  error(err) {
    this._stream._stream.destroy(err)
  }

  terminate() {
    const stream = this._stream._stream

    stream.push(null)
    stream.destroy(new TypeError('Stream has been terminated'))
  }
}

// https://streams.spec.whatwg.org/#transformstream
class TransformStream {
  static get [transformKind]() {
    return 0 // Compatibility version
  }

  constructor(transformer = {}, writableStrategy = {}, readableStrategy = {}) {
    if (isStreamx(transformer)) {
      this._stream = transformer
    } else {
      const { start, transform, flush } = transformer

      this._stream = new Transform({ ...writableStrategy, ...readableStrategy })

      this._controller = new exports.TransformStreamDefaultController(this)

      if (start) {
        this._stream._open = this._open.bind(this, start.call(this, this._controller))
      }

      if (transform) {
        this._stream._write = this._transform.bind(this, transform)
      }

      if (flush) {
        this._stream._flush = this._flush.bind(this, flush.call(this, this._controller))
      }
    }

    this._writable = new WritableStream(this._stream)
    this._readable = new ReadableStream(this._stream)
  }

  get [transformKind]() {
    return TransformStream[transformKind]
  }

  get writable() {
    return this._writable
  }

  get readable() {
    return this._readable
  }

  async _open(starting, cb) {
    let err = null
    try {
      await starting
    } catch (e) {
      err = e
    }
    cb(err)
  }

  async _transform(transform, data, cb) {
    let err = null
    try {
      await transform(data, this._controller)
    } catch (e) {
      err = e
    }
    cb(err)
  }

  async _flush(flush, cb) {
    let err = null
    try {
      await flush
    } catch (e) {
      err = e
    }
    cb(err)
  }
}

exports.TransformStream = TransformStream

exports.isTransformStream = function isTransformStream(value) {
  if (value instanceof TransformStream) return true

  return (
    typeof value === 'object' &&
    value !== null &&
    value[transformKind] === TransformStream[transformKind]
  )
}

function noop() {}
module.exports = require.addon()
const binding = require('./binding')

const t = binding.constants

class Type {
  constructor(type) {
    this._type = type
  }

  isUndefined() {
    return this._type === t.UNDEFINED
  }

  isNull() {
    return this._type === t.NULL
  }

  isBoolean() {
    return this._type === t.BOOLEAN
  }

  isNumber() {
    return (this._type & 0xff) === t.NUMBER
  }

  isInt32() {
    return (this._type & (0xff | t.INT32)) === (t.NUMBER | t.INT32)
  }

  isUint32() {
    return (this._type & (0xff | t.UINT32)) === (t.NUMBER | t.UINT32)
  }

  isString() {
    return this._type === t.STRING
  }

  isSymbol() {
    return this._type === t.SYMBOL
  }

  isObject() {
    return (this._type & 0xff) === t.OBJECT
  }

  isArray() {
    return this._type === (t.OBJECT | t.ARRAY)
  }

  isArguments() {
    return this._type === (t.OBJECT | t.ARGUMENTS)
  }

  isDate() {
    return this._type === (t.OBJECT | t.DATE)
  }

  isRegExp() {
    return this._type === (t.OBJECT | t.REGEXP)
  }

  isError() {
    return this._type === (t.OBJECT | t.ERROR)
  }

  isPromise() {
    return this._type === (t.OBJECT | t.PROMISE)
  }

  isProxy() {
    return this._type === (t.OBJECT | t.PROXY)
  }

  isGenerator() {
    return this._type === (t.OBJECT | t.GENERATOR)
  }

  isMap() {
    return this._type === (t.OBJECT | t.MAP)
  }

  isSet() {
    return this._type === (t.OBJECT | t.SET)
  }

  isWeakMap() {
    return this._type === (t.OBJECT | t.WEAK_MAP)
  }

  isWeakSet() {
    return this._type === (t.OBJECT | t.WEAK_SET)
  }

  isWeakRef() {
    return this._type === (t.OBJECT | t.WEAK_REF)
  }

  isArrayBuffer() {
    return this._type === (t.OBJECT | t.ARRAYBUFFER)
  }

  isSharedArrayBuffer() {
    return this._type === (t.OBJECT | t.SHAREDARRAYBUFFER)
  }

  isTypedArray() {
    return (this._type & 0xffff) === (t.OBJECT | t.TYPEDARRAY)
  }

  isInt8Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT8ARRAY)
  }

  isUint8Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT8ARRAY)
  }

  isUint8ClampedArray() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT8CLAMPEDARRAY)
  }

  isInt16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT16ARRAY)
  }

  isUint16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT16ARRAY)
  }

  isInt32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT32ARRAY)
  }

  isUint32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT32ARRAY)
  }

  isFloat16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT16ARRAY)
  }

  isFloat32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT32ARRAY)
  }

  isFloat64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT64ARRAY)
  }

  isBigInt64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.BIGINT64ARRAY)
  }

  isBigUint64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.BIGUINT64ARRAY)
  }

  isDataView() {
    return this._type === (t.OBJECT | t.DATAVIEW)
  }

  isModuleNamespace() {
    return this._type === (t.OBJECT | t.MODULE_NAMESPACE)
  }

  isFunction() {
    return (this._type & 0xff) === t.FUNCTION
  }

  isAsyncFunction() {
    return (
      (this._type & (0xff | t.ASYNC_FUNCTION)) ===
      (t.FUNCTION | t.ASYNC_FUNCTION)
    )
  }

  isGeneratorFunction() {
    return (
      (this._type & (0xff | t.GENERATOR_FUNCTION)) ===
      (t.FUNCTION | t.GENERATOR_FUNCTION)
    )
  }

  isExternal() {
    return this._type === t.EXTERNAL
  }

  isBigInt() {
    return this._type === t.BIGINT
  }
}

module.exports = exports = function type(value) {
  switch (typeof value) {
    case 'undefined':
      return new Type(t.UNDEFINED)
    case 'boolean':
      return new Type(t.BOOLEAN)
    case 'number':
      return new Type(
        Number.isSafeInteger(value) ? binding.type(value) : t.NUMBER
      )
    case 'string':
      return new Type(t.STRING)
    case 'symbol':
      return new Type(t.SYMBOL)
    case 'object':
      return new Type(value === null ? t.NULL : binding.type(value))
    case 'function':
      return new Type(binding.type(value))
    case 'bigint':
      return new Type(t.BIGINT)
  }
}

exports.createTag = function createTag(...components) {
  const tag = new Uint32Array(4)
  for (let i = 0; i < 4; i++) tag[i] = components[i] || 0
  return tag
}

exports.addTag = function addTag(object, tag) {
  binding.addTag(object, tag)
}

exports.checkTag = function checkTag(object, tag) {
  return binding.checkTag(object, tag)
}
{
  "name": "bare-type",
  "version": "1.1.0",
  "description": "Cross-realm type predicates for Bare",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-type.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-type/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-type#readme",
  "engines": {
    "bare": ">=1.2.0"
  },
  "devDependencies": {
    "brittle": "^3.4.0",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
module.exports = require.addon()
const path = require('bare-path')
const binding = require('./binding')
const errors = require('./lib/errors')
const URLSearchParams = require('./lib/url-search-params')

const kind = Symbol.for('bare.url.kind')

const isWindows = Bare.platform === 'win32'

class URL {
  static get [kind]() {
    return 0 // Compatibility version
  }

  constructor(input, base, opts = {}) {
    if (arguments.length === 0) throw errors.INVALID_URL()

    input = String(input)

    if (base !== undefined) base = String(base)

    this._components = new Uint32Array(8)

    this._parse(input, base, opts.throw !== false)

    if (this._href) this._params = new URLSearchParams(this.search, this)
  }

  get [kind]() {
    return URL[kind]
  }

  // https://url.spec.whatwg.org/#dom-url-href

  get href() {
    return this._href
  }

  set href(value) {
    this._update(value)

    this._params._parse(this.search)
  }

  // https://url.spec.whatwg.org/#dom-url-protocol

  get protocol() {
    return this._slice(0, this._components[0]) + ':'
  }

  set protocol(value) {
    this._update(this._replace(value.replace(/:+$/, ''), 0, this._components[0]))
  }

  // https://url.spec.whatwg.org/#dom-url-username

  get username() {
    return this._slice(this._components[0] + 3 /* :// */, this._components[1])
  }

  set username(value) {
    if (cannotHaveCredentialsOrPort(this)) {
      return
    }

    if (this.username === '') value += '@'

    this._update(this._replace(value, this._components[0] + 3 /* :// */, this._components[1]))
  }

  // https://url.spec.whatwg.org/#dom-url-password

  get password() {
    return this._href.slice(this._components[1] + 1 /* : */, this._components[2] - 1 /* @ */)
  }

  set password(value) {
    if (cannotHaveCredentialsOrPort(this)) {
      return
    }

    let start = this._components[1] + 1 /* : */
    let end = this._components[2] - 1 /* @ */

    if (this.password === '') {
      value = ':' + value
      start--
    }

    if (this.username === '') {
      value += '@'
      end++
    }

    this._update(this._replace(value, start, end))
  }

  // https://url.spec.whatwg.org/#dom-url-host

  get host() {
    return this._slice(this._components[2], this._components[5])
  }

  set host(value) {
    if (hasOpaquePath(this)) {
      return
    }

    this._update(
      this._replace(value, this._components[2], this._components[value.includes(':') ? 5 : 3])
    )
  }

  // https://url.spec.whatwg.org/#dom-url-hostname

  get hostname() {
    return this._slice(this._components[2], this._components[3])
  }

  set hostname(value) {
    if (hasOpaquePath(this)) {
      return
    }

    this._update(this._replace(value, this._components[2], this._components[3]))
  }

  // https://url.spec.whatwg.org/#dom-url-port

  get port() {
    return this._slice(this._components[3] + 1 /* : */, this._components[5])
  }

  set port(value) {
    if (cannotHaveCredentialsOrPort(this)) {
      return
    }

    let start = this._components[3] + 1 /* : */

    if (this.port === '') {
      value = ':' + value
      start--
    }

    this._update(this._replace(value, start, this._components[5]))
  }

  // https://url.spec.whatwg.org/#dom-url-pathname

  get pathname() {
    return this._slice(this._components[5], this._components[6] - 1 /* ? */)
  }

  set pathname(value) {
    if (hasOpaquePath(this)) {
      return
    }

    if (value[0] !== '/' && value[0] !== '\\') {
      value = '/' + value
    }

    this._update(this._replace(value, this._components[5], this._components[6] - 1 /* ? */))
  }

  // https://url.spec.whatwg.org/#dom-url-search

  get search() {
    return this._slice(this._components[6] - 1 /* ? */, this._components[7] - 1 /* # */)
  }

  set search(value) {
    if (value && value[0] !== '?') value = '?' + value

    this._update(
      this._replace(value, this._components[6] - 1 /* ? */, this._components[7] - 1 /* # */)
    )

    this._params._parse(this.search)
  }

  // https://url.spec.whatwg.org/#dom-url-searchparams

  get searchParams() {
    return this._params
  }

  // https://url.spec.whatwg.org/#dom-url-hash

  get hash() {
    return this._slice(this._components[7] - 1 /* # */)
  }

  set hash(value) {
    if (value && value[0] !== '#') value = '#' + value

    this._update(this._replace(value, this._components[7] - 1 /* # */))
  }

  toString() {
    return this._href
  }

  toJSON() {
    return this._href
  }

  [Symbol.for('bare.inspect')]() {
    return {
      __proto__: { constructor: URL },

      href: this.href,
      protocol: this.protocol,
      username: this.username,
      password: this.password,
      host: this.host,
      hostname: this.hostname,
      port: this.port,
      pathname: this.pathname,
      search: this.search,
      searchParams: this.searchParams,
      hash: this.hash
    }
  }

  _slice(start, end = this._href.length) {
    return this._href.slice(start, end)
  }

  _replace(replacement, start, end = this._href.length) {
    return this._slice(0, start) + replacement + this._slice(end)
  }

  _parse(input, base, shouldThrow) {
    try {
      this._href = binding.parse(
        String(input),
        base ? String(base) : null,
        this._components,
        shouldThrow
      )
    } catch (err) {
      if (err instanceof TypeError) throw err

      throw errors.INVALID_URL(`Invalid URL '${input}'`, input)
    }
  }

  _update(input) {
    try {
      this._parse(input, null, true)
    } catch (err) {
      if (err instanceof TypeError) throw err
    }
  }
}

module.exports = exports = URL

// https://url.spec.whatwg.org/#url-opaque-path
function hasOpaquePath(url) {
  return url.pathname[0] !== '/'
}

// https://url.spec.whatwg.org/#cannot-have-a-username-password-port
function cannotHaveCredentialsOrPort(url) {
  return url.hostname === '' || url.protocol === 'file:'
}

exports.URL = URL
exports.URLSearchParams = URLSearchParams

exports.errors = errors

exports.isURL = function isURL(value) {
  if (value instanceof URL) return true

  return typeof value === 'object' && value !== null && value[kind] === URL[kind]
}

exports.isURLSearchParams = URLSearchParams.isURLSearchParams

// https://url.spec.whatwg.org/#dom-url-parse
exports.parse = function parse(input, base) {
  const url = new URL(input, base, { throw: false })
  return url._href ? url : null
}

// https://url.spec.whatwg.org/#dom-url-canparse
exports.canParse = function canParse(input, base) {
  return binding.canParse(String(input), base ? String(base) : null)
}

exports.fileURLToPath = function fileURLToPath(url) {
  if (typeof url === 'string') {
    url = new URL(url)
  }

  if (url.protocol !== 'file:') {
    throw errors.INVALID_URL_SCHEME('The URL must use the file: protocol')
  }

  if (isWindows) {
    if (/%2f|%5c/i.test(url.pathname)) {
      throw errors.INVALID_FILE_URL_PATH(
        'The file: URL path must not include encoded \\ or / characters'
      )
    }
  } else {
    if (url.hostname) {
      throw errors.INVALID_FILE_URL_HOST("The file: URL host must be 'localhost' or empty")
    }

    if (/%2f/i.test(url.pathname)) {
      throw errors.INVALID_FILE_URL_PATH('The file: URL path must not include encoded / characters')
    }
  }

  const pathname = path.normalize(decodeURIComponent(url.pathname))

  if (isWindows) {
    if (url.hostname) return '\\\\' + url.hostname + pathname

    const letter = pathname.charCodeAt(1) | 0x20

    if (letter < 0x61 /* a */ || letter > 0x7a /* z */ || pathname.charCodeAt(2) !== 0x3a /* : */) {
      throw errors.INVALID_FILE_URL_PATH('The file: URL path must be absolute')
    }

    return pathname.slice(1)
  }

  return pathname
}

exports.pathToFileURL = function pathToFileURL(pathname) {
  let resolved = path.resolve(pathname)

  if (pathname[pathname.length - 1] === '/') {
    resolved += '/'
  } else if (isWindows && pathname[pathname.length - 1] === '\\') {
    resolved += '\\'
  }

  resolved = resolved
    .replaceAll('%', '%25') // Must be first
    .replaceAll('#', '%23')
    .replaceAll('?', '%3f')
    .replaceAll('\n', '%0a')
    .replaceAll('\r', '%0d')
    .replaceAll('\t', '%09')

  if (!isWindows) {
    resolved = resolved.replaceAll('\\', '%5c')
  }

  return new URL('file:' + resolved)
}

exports.format = function format(parts) {
  const { protocol, auth, host, hostname, port, pathname, search, query, hash, slashes } = parts

  let result = ''

  if (typeof protocol === 'string') {
    result += protocol

    if (protocol[protocol.length - 1] !== ':') {
      result += ':'
    }

    if (slashes === true || /https?|ftp|gopher|file/.test(protocol)) {
      result += '//'
    }
  }

  if (typeof auth === 'string') {
    if (host || hostname) result += auth + '@'
  }

  if (typeof host === 'string') result += host
  else {
    result += hostname

    if (port) result += ':' + port
  }

  if (typeof pathname === 'string' && pathname !== '') {
    if (pathname[0] !== '/') result += '/'
    result += pathname
  }

  if (typeof search === 'string') {
    if (search[0] !== '?') result += '?'
    result += search
  } else if (typeof query === 'object' && query !== null) {
    result += '?' + new URLSearchParams(query)
  }

  if (typeof hash === 'string') {
    if (hash[0] !== '#') result += '#'
    result += hash
  }

  return result
}
module.exports = class URLError extends Error {
  constructor(msg, fn = URLError, code = fn.name) {
    super(`${code}: ${msg}`)

    this.code = code

    if (Error.captureStackTrace) Error.captureStackTrace(this, fn)
  }

  get name() {
    return 'URLError'
  }

  static INVALID_URL(msg, input) {
    const err = new URLError(msg, URLError.INVALID_URL)

    err.input = input

    return err
  }

  static INVALID_URL_SCHEME(msg = 'Invalid URL') {
    return new URLError(msg, URLError.INVALID_URL_SCHEME)
  }

  static INVALID_FILE_URL_HOST(msg = 'Invalid file: URL host') {
    return new URLError(msg, URLError.INVALID_FILE_URL_HOST)
  }

  static INVALID_FILE_URL_PATH(msg = 'Invalid file: URL path') {
    return new URLError(msg, URLError.INVALID_FILE_URL_PATH)
  }
}
const kind = Symbol.for('bare.url.search-params.kind')

class URLSearchParams {
  static _urls = new WeakMap()

  static get [kind]() {
    return 0 // Compatibility version
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-urlsearchparams
  constructor(init, url = null) {
    this._params = new Map()

    if (url) URLSearchParams._urls.set(this, url)

    if (typeof init === 'string') {
      this._parse(init)
    } else if (init) {
      for (const [name, value] of typeof init[Symbol.iterator] === 'function'
        ? init
        : Object.entries(init)) {
        this.append(name, value)
      }
    }
  }

  get [kind]() {
    return URLSearchParams[kind]
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-size
  get size() {
    return this._params.length
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-append
  append(name, value = null) {
    if (value === null) return

    let list = this._params.get(name)

    if (list === undefined) {
      list = []
      this._params.set(name, list)
    }

    list.push(value)

    this._update()
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-delete
  delete(name, value = null) {
    if (value === null) this._params.delete(name)
    else {
      let list = this._params.get(name)

      if (list === undefined) return

      list = list.filter((found) => found !== value)

      if (list.length === 0) this._params.delete(name)
      else this._params.set(name, list)
    }

    this._update()
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-get
  get(name) {
    const list = this._params.get(name)

    if (list === undefined) return null

    return list[0]
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-getall
  getAll(name) {
    const list = this._params.get(name)

    if (list === undefined) return []

    return Array.from(list)
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-has
  has(name, value = null) {
    const list = this._params.get(name)

    if (list === undefined) return false

    if (value === null) return true

    return list.includes(value)
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-set
  set(name, value = null) {
    if (value === null) this._params.delete(name)
    else this._params.set(name, [value])

    this._update()
  }

  toString() {
    return this._serialize()
  }

  toJSON() {
    return [...this]
  }

  *[Symbol.iterator]() {
    for (const [name, values] of this._params) {
      for (const value of values) yield [name, value]
    }
  }

  [Symbol.for('bare.inspect')]() {
    const object = {
      __proto__: { constructor: URLSearchParams }
    }

    for (const [name, values] of this._params) {
      if (values.length === 1) object[name] = values[0]
      else object[name] = values
    }

    return object
  }

  // https://url.spec.whatwg.org/#concept-urlsearchparams-update
  _update() {
    const url = URLSearchParams._urls.get(this)

    if (url === undefined) return

    url.search = this._serialize()
  }

  // https://url.spec.whatwg.org/#concept-urlencoded-parser
  _parse(input) {
    if (input[0] === '?') input = input.substring(1)

    this._params = new Map()

    for (const sequence of input.split('&')) {
      if (sequence.length === 0) continue

      let i = sequence.indexOf('=')
      if (i === -1) i = sequence.length

      const name = decodeURIComponent(sequence.substring(0, i))
      const value = decodeURIComponent(sequence.substring(i + 1, sequence.length))

      let list = this._params.get(name)

      if (list === undefined) {
        list = []
        this._params.set(name, list)
      }

      list.push(value)
    }
  }

  // https://url.spec.whatwg.org/#concept-urlencoded-serializer
  _serialize() {
    let output = ''

    for (let [name, values] of this._params) {
      name = encodeURIComponent(name)

      for (const value of values) {
        if (output) output += '&'

        output += name + '=' + encodeURIComponent(value)
      }
    }

    return output
  }
}

module.exports = exports = URLSearchParams

exports.isURLSearchParams = function isURLSearchParams(value) {
  if (value instanceof URLSearchParams) return true

  return typeof value === 'object' && value !== null && value[kind] === URLSearchParams[kind]
}
{
  "name": "bare-url",
  "version": "2.4.0",
  "description": "WHATWG URL implementation for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "global.js",
    "global.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-url.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-url/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-url",
  "dependencies": {
    "bare-path": "^3.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "cmake-bare": "^1.1.6",
    "cmake-fetch": "^1.0.0",
    "prettier": "^3.3.3",
    "prettier-config-holepunch": "^2.0.0"
  }
}
const FACTOR = new Uint16Array(8)

function factor4096 (i, n) {
  while (n > 0) {
    const f = i & 4095
    FACTOR[--n] = f
    i = (i - f) / 4096
  }
  return FACTOR
}

module.exports = class BigSparseArray {
  constructor () {
    this.tiny = new TinyArray()
    this.maxLength = 4096
    this.factor = 1
  }

  set (index, val) {
    if (val !== undefined) {
      while (index >= this.maxLength) {
        this.maxLength *= 4096
        this.factor++
        if (!this.tiny.isEmptyish()) {
          const t = new TinyArray()
          t.set(0, this.tiny)
          this.tiny = t
        }
      }
    }

    const f = factor4096(index, this.factor)
    const last = this.factor - 1

    let tiny = this.tiny
    for (let i = 0; i < last; i++) {
      const next = tiny.get(f[i])
      if (next === undefined) {
        if (val === undefined) return
        tiny = tiny.set(f[i], new TinyArray())
      } else {
        tiny = next
      }
    }

    return tiny.set(f[last], val)
  }

  get (index) {
    if (index >= this.maxLength) return

    const f = factor4096(index, this.factor)
    const last = this.factor - 1

    let tiny = this.tiny
    for (let i = 0; i < last; i++) {
      tiny = tiny.get(f[i])
      if (tiny === undefined) return
    }

    return tiny.get(f[last])
  }
}

class TinyArray {
  constructor () {
    this.s = 0
    this.b = new Array(1)
    this.f = new Uint16Array(1)
  }

  isEmptyish () {
    return this.b.length === 1 && this.b[0] === undefined
  }

  get (i) {
    if (this.s === 12) return this.b[i]
    const f = i >>> this.s
    const r = i & (this.b.length - 1)
    return this.f[r] === f ? this.b[r] : undefined
  }

  set (i, v) {
    while (this.s !== 12) {
      const f = i >>> this.s
      const r = i & (this.b.length - 1)
      const o = this.b[r]

      if (o === undefined || f === this.f[r]) {
        this.b[r] = v
        this.f[r] = f
        return v
      }

      this.grow()
    }

    this.b[i] = v
    return v
  }

  grow () {
    const os = this.s
    const ob = this.b
    const of = this.f

    this.s += 4
    this.b = new Array(this.b.length << 4)
    this.f = this.s === 12 ? null : new Uint8Array(this.b.length)

    const m = this.b.length - 1

    for (let or = 0; or < ob.length; or++) {
      if (ob[or] === undefined) continue

      const i = of[or] << os | or
      const f = i >>> this.s
      const r = i & m

      this.b[r] = ob[or]
      if (this.s !== 12) this.f[r] = f
    }
  }
}
{
  "name": "big-sparse-array",
  "version": "1.0.3",
  "description": "A sparse array optimised for low memory whilst still being fast",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "brittle": "^3.1.1",
    "standard": "^16.0.3"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/big-sparse-array.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/big-sparse-array/issues"
  },
  "homepage": "https://github.com/mafintosh/big-sparse-array"
}
const b4a = require('b4a')

module.exports = codecs

codecs.ascii = createString('ascii')
codecs.utf8 = createString('utf-8')
codecs.hex = createString('hex')
codecs.base64 = createString('base64')
codecs.ucs2 = createString('ucs2')
codecs.utf16le = createString('utf16le')
codecs.ndjson = createJSON(true)
codecs.json = createJSON(false)
codecs.binary = {
  name: 'binary',
  encode: function encodeBinary (obj) {
    return typeof obj === 'string'
      ? b4a.from(obj, 'utf-8')
      : b4a.toBuffer(obj)
  },
  decode: function decodeBinary (buf) {
    return b4a.toBuffer(buf)
  }
}

function isCompactEncoding (c) {
  return !!(c.encode && c.decode && c.preencode)
}

function fromCompactEncoding (c) {
  return {
    name: 'compact-encoding',
    encode: function encodeWithCompact (value) {
      const state = { start: 0, end: 0, buffer: null, cache: null }
      c.preencode(state, value)
      state.buffer = b4a.allocUnsafe(state.end)
      c.encode(state, value)
      return state.buffer
    },
    decode: function decodeWithCompact (buffer) {
      return c.decode({ start: 0, end: buffer.byteLength, buffer, cache: null })
    }
  }
}

function codecs (fmt, fallback) {
  if (typeof fmt === 'object' && fmt) {
    return isCompactEncoding(fmt) ? fromCompactEncoding(fmt) : fmt
  }

  switch (fmt) {
    case 'ndjson': return codecs.ndjson
    case 'json': return codecs.json
    case 'ascii': return codecs.ascii
    case 'utf-8':
    case 'utf8': return codecs.utf8
    case 'hex': return codecs.hex
    case 'base64': return codecs.base64
    case 'ucs-2':
    case 'ucs2': return codecs.ucs2
    case 'utf16-le':
    case 'utf16le': return codecs.utf16le
  }

  return fallback !== undefined ? fallback : codecs.binary
}

function createJSON (newline) {
  return {
    name: newline ? 'ndjson' : 'json',
    encode: newline ? encodeNDJSON : encodeJSON,
    decode: function decodeJSON (buf) {
      return JSON.parse(b4a.toString(buf))
    }
  }

  function encodeJSON (val) {
    return b4a.from(JSON.stringify(val))
  }

  function encodeNDJSON (val) {
    return b4a.from(JSON.stringify(val) + '\n')
  }
}

function createString (type) {
  return {
    name: type,
    encode: function encodeString (val) {
      if (typeof val !== 'string') val = val.toString()
      return b4a.from(val, type)
    },
    decode: function decodeString (buf) {
      return b4a.toString(buf, type)
    }
  }
}
{
  "name": "codecs",
  "version": "3.1.0",
  "description": "Create an binary encoder/decoder for json, utf-8 or custom types",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.6.3"
  },
  "devDependencies": {
    "brittle": "^3.2.1",
    "compact-encoding": "^2.11.0",
    "standard": "^17.0.0"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/codecs.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/codecs/issues"
  },
  "homepage": "https://github.com/mafintosh/codecs"
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return uint24.decode(state) + 0x1000000 * uint32.decode(state)
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return uint32.decode(state) + 0x100000000 * uint32.decode(state)
  }
})

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "2.19.2",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    if (b.byteLength === 0) return null
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
const safetyCatch = require('safety-catch')

module.exports = class CoreCoupler {
  constructor (target, wakeup) {
    this.target = target
    this.wakeup = wakeup
    this.coupled = new Set()

    this._onpeeraddBound = this._onpeeradd.bind(this)
    this.target.on('peer-add', this._onpeeraddBound)
  }

  add (core) {
    const added = this.coupled.size
    this.coupled.add(core)
    if (added !== this.coupled.size) this._couple(core)
  }

  remove (core) {
    this.coupled.delete(core)
  }

  destroy () {
    this.target.off('peer-add', this._onpeeraddBound)
  }

  async update (stream) {
    const muxer = stream.userData
    if (!muxer) return

    try {
      if (!(await this._hasMuxer(this.target, muxer))) return

      let wakeup = null

      for (const core of this.coupled) {
        if (await this._hasMuxer(core, muxer)) continue
        if (wakeup === null) wakeup = []
        wakeup.push(core)
      }

      if (wakeup !== null) {
        this.wakeup(stream, wakeup)
      }
    } catch (err) {
      safetyCatch(err)
    }
  }

  async _couple (core) {
    try {
      let wakeup = null

      for (const peer of this.target.peers) {
        if (await this._hasPeer(core, peer)) continue
        if (wakeup === null) wakeup = []
        wakeup.push(peer)
      }

      if (wakeup !== null && this.coupled.has(core)) {
        for (const peer of wakeup) this.wakeup(peer.stream, [core])
      }
    } catch (err) {
      safetyCatch(err)
    }
  }

  async _onpeeradd (peer) {
    try {
      let wakeup = null

      for (const core of this.coupled) {
        if (await this._hasPeer(core, peer)) continue
        if (wakeup === null) wakeup = []
        wakeup.push(core)
      }

      if (wakeup !== null) {
        this.wakeup(peer.stream, wakeup)
      }
    } catch (err) {
      safetyCatch(err)
    }
  }

  _hasMuxer (core, muxer) {
    const ch = muxer.getLastChannel({ protocol: 'hypercore', id: core.discoveryKey })
    if (ch) return ch.fullyOpened()

    const cha = muxer.getLastChannel({ protocol: 'hypercore/alpha', id: core.discoveryKey })
    if (cha) return cha.fullyOpened()

    return Promise.resolve(false)
  }

  _hasPeer (core, peer) {
    return this._hasMuxer(core, peer.protomux)
  }
}
{
  "name": "core-coupler",
  "version": "2.0.0",
  "description": "Couple the peers of cores",
  "main": "index.js",
  "scripts": {
    "test": "standard"
  },
  "dependencies": {
    "safety-catch": "^1.0.2"
  },
  "devDependencies": {
    "corestore": "^6.18.2",
    "standard": "^17.1.0"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/core-coupler.git"
  },
  "author": "Holepunch Inc",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/core-coupler/issues"
  },
  "homepage": "https://github.com/holepunchto/core-coupler"
}
module.exports = function debounce (worker, context = null) {
  debounced.running = null
  return debounced

  async function debounced () {
    if (debounced.running !== null) {
      try {
        await debounced.running
      } catch (_) {
        // ignore - do not fail on old errors
      }
    }

    // another "thread" beat us to it, just piggy pack on that one
    if (debounced.running !== null) return debounced.running

    debounced.running = worker.call(context)

    try {
      return await debounced.running
    } finally {
      debounced.running = null
    }
  }
}
{
  "name": "debounceify",
  "version": "1.1.0",
  "description": "Tiny async debouncer",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^16.0.3",
    "tape": "^5.1.1"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/debounceify.git"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/debounceify/issues"
  },
  "homepage": "https://github.com/mafintosh/debounceify"
}
const fs = require('fs')
const path = require('path')
const fsx = require('fs-native-extensions')
const b4a = require('b4a')
const ReadyResource = require('ready-resource')
const FDLock = require('fd-lock')

const PLATFORM = global.Bare ? global.Bare.platform : global.process.platform
const IS_WIN = PLATFORM === 'win32'
const IS_LINUX = PLATFORM === 'linux'
const MODIFIED_SLACK = 5000
const EMPTY = b4a.alloc(0)
const ATTR = IS_LINUX ? 'user.device-file' : 'device-file'

const nl = IS_WIN ? '\r\n' : '\n'

class DeviceFile extends ReadyResource {
  constructor(filename, { create = true, wait = false, lock = wait, data = {} } = {}) {
    super()

    this.filename = filename
    this.data = data
    this.lock = null

    this._create = create
    this._wait = wait
    this._lock = lock
  }

  async _open() {
    if (await verifyDeviceFile(this)) return
    if (!this._create) throwDeviceFileError('No device file present', false)
    await writeDeviceFile(this)
  }

  static async validate(filename, data) {
    const file = new DeviceFile(filename, { create: false, wait: false, data })
    try {
      await verifyDeviceFile(file)
    } catch (err) {
      if (err.fatal && err.code === 'DEVICE_FILE') return false
      throw err
    }
    return true
  }

  transfer() {
    return this.lock ? this.lock.transfer() : -1
  }

  async _close() {
    if (this.lock) await this.lock.close()
  }

  async suspend() {
    if (!this.opened) await this.ready()
    if (this.lock) await this.lock.suspend()
  }

  async resume() {
    if (!this.opened) await this.ready()
    if (this.lock) await this.lock.resume()
  }
}

module.exports = DeviceFile

async function writeDeviceFile(device) {
  let s = ''

  for (const [key, value] of Object.entries(device.data)) {
    if (value === null) continue
    s += key + '=' + value + nl
  }

  await fs.promises.mkdir(path.dirname(device.filename), { recursive: true })

  const fd = await open(device.filename, 'w')

  device.lock = device._lock ? new FDLock(fd, { wait: device._wait }) : null

  if (device.lock) {
    try {
      await device.lock.ready()
    } catch (err) {
      await device.lock.close()
      throw err
    }
  }

  const st = await fstat(fd)

  const created = Date.now()

  s += 'device/platform=' + PLATFORM + nl
  s += 'device/inode=' + st.ino + nl
  s += 'device/created=' + created + nl

  if (await setAttr(fd, ATTR, b4a.from('original'))) {
    s += 'device/attribute=original' + nl
  }

  await write(fd, b4a.from(s))

  if (!device.lock) await close(fd)
}

async function verifyDeviceFile(device) {
  let fd = 0

  try {
    fd = await open(device.filename, 'r+')
  } catch (e) {
    fd = 0
  }

  if (fd === 0) return false

  device.lock = device._lock ? new FDLock(fd, { wait: device._wait }) : null

  if (device.lock) {
    try {
      await device.lock.ready()
    } catch (err) {
      await device.lock.close()
      throw err
    }
  }

  const buf = await read(fd)
  const result = {}

  const s = b4a.toString(buf).trim().split('\n')

  let inode = 0
  let created = 0
  let attr = ''
  let platform = ''

  for (const ln of s) {
    const i = ln.indexOf('=')
    if (i === -1) continue

    const k = ln.slice(0, i).trim()
    const v = ln.slice(i + 1).trim()

    switch (k) {
      case 'device/platform':
        platform = v
        break
      case 'device/inode':
        inode = Number(v)
        break
      case 'device/created':
        created = Number(v)
        break
      case 'device/attribute':
        attr = v
        break
      default:
        result[k] = v
        break
    }
  }

  for (const [k, v] of Object.entries(device.data)) {
    if (v === null) continue
    if (result[k] === undefined) continue // allow upserts
    if (result[k] !== '' + v) {
      await teardown()
      throwDeviceFileError(`Invalid device file, ${k} has changed. Was ${result[k]}, is ${v}`, true)
    }
  }

  const st = await fstat(fd)
  const at = await getAttr(fd, ATTR)

  const sameAttr = b4a.toString(at || EMPTY) === attr
  const modified = Math.max(st.mtime.getTime(), st.birthtime.getTime())

  if (platform && platform !== PLATFORM) {
    await teardown()
    throwDeviceFileError('Invalid device file, was made on different platform', true)
  }

  if (!sameAttr) {
    await teardown()
    throwDeviceFileError('Invalid device file, was moved unsafely', true)
  }

  if (st.ino !== inode || (created && Math.abs(modified - created) >= MODIFIED_SLACK)) {
    await teardown()
    throwDeviceFileError('Invalid device file, was modified', true)
  }

  if (!device.lock) await close(fd)

  device.data = result
  return true

  async function teardown() {
    if (device.lock) await device.lock.close()
    else await close(fd)
  }
}

async function getAttr(fd, name) {
  try {
    return await fsx.getAttr(fd, name)
  } catch {
    return null
  }
}

async function setAttr(fd, name, value) {
  try {
    await fsx.setAttr(fd, name, value)
    return true
  } catch {
    return false
  }
}

function fstat(fd) {
  return new Promise((resolve, reject) => {
    fs.fstat(fd, (err, st) => {
      if (err) reject(err)
      resolve(st)
    })
  })
}

function close(fd) {
  return new Promise((resolve, reject) => {
    fs.close(fd, (err, st) => {
      if (err) reject(err)
      resolve(st)
    })
  })
}

function write(fd, buf) {
  return new Promise((resolve, reject) => {
    let offset = 0

    onwrite(null, 0)

    function onwrite(err, wrote) {
      if (err) return reject(err)
      if (offset === buf.byteLength) return resolve()
      offset += wrote
      fs.write(fd, buf, offset, buf.byteLength - offset, offset, onwrite)
    }
  })
}

function read(fd) {
  const buf = b4a.allocUnsafe(4096)

  return new Promise((resolve, reject) => {
    let offset = 0

    fs.read(fd, buf, 0, buf.byteLength, 0, onread)

    function onread(err, read) {
      if (err) return reject(err)
      if (read === 0) return resolve(buf.subarray(0, offset))
      offset += read
      fs.read(fd, buf, offset, buf.byteLength - offset, offset, onread)
    }
  })
}

function open(filename, flags) {
  return new Promise((resolve, reject) => {
    fs.open(filename, flags, (err, fd) => {
      if (err) reject(err)
      resolve(fd)
    })
  })
}

function throwDeviceFileError(message, fatal) {
  const err = new Error(message)
  err.code = 'DEVICE_FILE'
  err.fatal = fatal
  throw err
}
{
  "name": "device-file",
  "version": "2.3.1",
  "description": "Device only file",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.6.7",
    "bare-fs": "^4.0.1",
    "bare-path": "^3.0.0",
    "fd-lock": "^2.1.0",
    "fs-native-extensions": "^1.4.0",
    "ready-resource": "^1.2.0"
  },
  "devDependencies": {
    "brittle": "^3.13.1",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node --coverage test.js",
    "test:bare": "brittle-bare --coverage test.js"
  },
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    }
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/device-file.git"
  },
  "author": "Holepunch Inc",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/device-file/issues"
  },
  "homepage": "https://github.com/holepunchto/device-file"
}
const { encode, decode } = require('./spec/hyperschema')

async function encrypt(data, cb) {
  const result = await cb(data)

  return encode('@encryption/encrypted-data', result)
}

async function decrypt(data, cb) {
  const decoded = decode('@encryption/encrypted-data', data)
  const decrypted = await cb(decoded)

  return decrypted
}

module.exports = { encrypt, decrypt }
{
  "name": "encryption-encoding",
  "version": "1.0.3",
  "description": "Compact encoding for versioned encrypted values with automatic string/buffer handling.",
  "main": "index.js",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    }
  },
  "files": [
    "package.json",
    "index.js",
    "index.d.ts",
    "spec"
  ],
  "keywords": [
    "pear",
    "p2p",
    "bare",
    "autobase",
    "encryption",
    "hyperschema"
  ],
  "devDependencies": {
    "b4a": "^1.7.3",
    "brittle": "^3.19.0",
    "lunte": "^1.2.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "sodium-universal": "^5.0.1"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && lunte && brittle-bare test/all.js",
    "lint": "lunte"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/encryption-encoding.git"
  },
  "author": "Holepunch Inc",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/encryption-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/encryption-encoding",
  "dependencies": {
    "hyperschema": "^1.19.0"
  }
}
// This file is autogenerated by the hyperschema compiler
// Schema Version: 1
/* eslint-disable camelcase */
/* eslint-disable quotes */
/* eslint-disable space-before-function-paren */

const { c } = require('hyperschema/runtime')

const VERSION = 1

// eslint-disable-next-line no-unused-vars
let version = VERSION

// @encryption/encrypted-data
const encoding0 = {
  preencode(state, m) {
    c.uint.preencode(state, m.type)
    c.buffer.preencode(state, m.value)
  },
  encode(state, m) {
    c.uint.encode(state, m.type)
    c.buffer.encode(state, m.value)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const r1 = c.buffer.decode(state)

    return {
      type: r0,
      value: r1
    }
  }
}

function setVersion(v) {
  version = v
}

function encode(name, value, v = VERSION) {
  version = v
  return c.encode(getEncoding(name), value)
}

function decode(name, buffer, v = VERSION) {
  version = v
  return c.decode(getEncoding(name), buffer)
}

function getEnum(name) {
  switch (name) {
    default:
      throw new Error('Enum not found ' + name)
  }
}

function getEncoding(name) {
  switch (name) {
    case '@encryption/encrypted-data':
      return encoding0
    default:
      throw new Error('Encoder not found ' + name)
  }
}

function getStruct(name, v = VERSION) {
  const enc = getEncoding(name)
  return {
    preencode(state, m) {
      version = v
      enc.preencode(state, m)
    },
    encode(state, m) {
      version = v
      enc.encode(state, m)
    },
    decode(state) {
      version = v
      return enc.decode(state)
    }
  }
}

const resolveStruct = getStruct // compat

module.exports = {
  resolveStruct,
  getStruct,
  getEnum,
  getEncoding,
  encode,
  decode,
  setVersion,
  version
}
module.exports = require('bare-events')
{
  "name": "events-universal",
  "version": "1.0.1",
  "description": "Universal wrapper for the Node.js events module",
  "exports": {
    "./package": "./package.json",
    ".": {
      "bare": "./bare.js",
      "react-native": "./react-native.js",
      "default": "./default.js"
    }
  },
  "files": [
    "index.js",
    "default.js",
    "bare.js",
    "react-native.js"
  ],
  "scripts": {
    "test": "prettier . --check"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/events-universal.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/events-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/events-universal#readme",
  "dependencies": {
    "bare-events": "^2.7.0"
  },
  "devDependencies": {
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^1.0.0"
  }
}
module.exports = class FixedFIFO {
  constructor (hwm) {
    if (!(hwm > 0) || ((hwm - 1) & hwm) !== 0) throw new Error('Max size for a FixedFIFO should be a power of two')
    this.buffer = new Array(hwm)
    this.mask = hwm - 1
    this.top = 0
    this.btm = 0
    this.next = null
  }

  clear () {
    this.top = this.btm = 0
    this.next = null
    this.buffer.fill(undefined)
  }

  push (data) {
    if (this.buffer[this.top] !== undefined) return false
    this.buffer[this.top] = data
    this.top = (this.top + 1) & this.mask
    return true
  }

  shift () {
    const last = this.buffer[this.btm]
    if (last === undefined) return undefined
    this.buffer[this.btm] = undefined
    this.btm = (this.btm + 1) & this.mask
    return last
  }

  peek () {
    return this.buffer[this.btm]
  }

  isEmpty () {
    return this.buffer[this.btm] === undefined
  }
}
const FixedFIFO = require('./fixed-size')

module.exports = class FastFIFO {
  constructor (hwm) {
    this.hwm = hwm || 16
    this.head = new FixedFIFO(this.hwm)
    this.tail = this.head
    this.length = 0
  }

  clear () {
    this.head = this.tail
    this.head.clear()
    this.length = 0
  }

  push (val) {
    this.length++
    if (!this.head.push(val)) {
      const prev = this.head
      this.head = prev.next = new FixedFIFO(2 * this.head.buffer.length)
      this.head.push(val)
    }
  }

  shift () {
    if (this.length !== 0) this.length--
    const val = this.tail.shift()
    if (val === undefined && this.tail.next) {
      const next = this.tail.next
      this.tail.next = null
      this.tail = next
      return this.tail.shift()
    }

    return val
  }

  peek () {
    const val = this.tail.peek()
    if (val === undefined && this.tail.next) return this.tail.next.peek()
    return val
  }

  isEmpty () {
    return this.length === 0
  }
}
{
  "name": "fast-fifo",
  "version": "1.3.2",
  "description": "A fast fifo implementation similar to the one powering nextTick in Node.js core",
  "main": "index.js",
  "files": [
    "./index.js",
    "./fixed-size.js"
  ],
  "dependencies": {},
  "devDependencies": {
    "standard": "^17.1.0",
    "brittle": "^3.3.2"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/fast-fifo.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/fast-fifo/issues"
  },
  "homepage": "https://github.com/mafintosh/fast-fifo"
}
const fs = require('fs')
const fsx = require('fs-native-extensions')
const onexit = require('resource-on-exit')
const ReadyResource = require('ready-resource')

module.exports = class FDLock extends ReadyResource {
  constructor(fd, opts = {}) {
    const { wait = false } = opts

    super()

    this._fd = fd
    this._wait = wait
    this._locked = false

    onexit.add(this, closeSync)
  }

  async _open() {
    try {
      await this._resume()
    } catch (err) {
      onexit.remove(this)
      await close(this)
      throw err
    }
  }

  async _close() {
    onexit.remove(this)
    await close(this)
  }

  transfer() {
    const fd = this._fd
    if (fd === -1) throw new Error('Lock has already been transferred')
    this._fd = -1
    onexit.remove(this)
    return fd
  }

  async suspend() {
    if (!this.opened) await this.ready()
    return this._suspend()
  }

  async _suspend() {
    if (this._fd === -1 || this._locked === false) return
    fsx.unlock(this._fd)
    this._locked = false
  }

  async resume() {
    if (!this.opened) await this.ready()
    return this._resume()
  }

  async _resume() {
    if (this._fd === -1 || this._locked === true) return
    if (this._wait) await fsx.waitForLock(this._fd)
    else if (!fsx.tryLock(this._fd)) {
      throw new Error('File descriptor could not be locked')
    }
    this._locked = true
  }
}

function close(lock) {
  const fd = lock._fd
  if (fd === -1) return
  lock._fd = -1
  return new Promise((resolve) => fs.close(fd, () => resolve()))
}

function closeSync(lock) {
  const fd = lock._fd
  if (fd === -1) return
  lock._fd = -1
  try {
    fs.closeSync(fd)
  } catch {}
}
{
  "name": "fd-lock",
  "version": "2.1.1",
  "description": "Stateful file descriptor locks for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": "./index.js"
  },
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    }
  },
  "files": [
    "index.js"
  ],
  "scripts": {
    "test": "npm run lint && npm run test:bare && npm run test:node",
    "test:bare": "bare test.js",
    "test:node": "node test.js",
    "lint": "prettier --check .",
    "format": "prettier --write ."
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/fd-lock.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/fd-lock/issues"
  },
  "homepage": "https://github.com/holepunchto/fd-lock#readme",
  "dependencies": {
    "bare-fs": "^4.5.0",
    "fs-native-extensions": "^1.4.4",
    "ready-resource": "^1.2.0",
    "resource-on-exit": "^1.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
exports.fullRoots = function (index, result) {
  if (index & 1) throw new Error('You can only look up roots for depth(0) blocks')
  if (!result) result = []

  index /= 2

  let offset = 0
  let factor = 1

  while (true) {
    if (!index) return result
    while (factor * 2 <= index) factor *= 2
    result.push(offset + factor - 1)
    offset = offset + 2 * factor
    index -= factor
    factor = 1
  }
}

exports.futureRoots = function (index, result) {
  if (index & 1) throw new Error('You can only look up future roots for depth(0) blocks')
  if (!result) result = []

  let factor = 1

  // make first root
  while (factor * 2 <= index) factor *= 2

  // full factor of 2 - done
  if (factor * 2 - 2 === index) return result

  let pos = factor / 2 - 1

  // while its not a full tree
  while ((pos + factor / 2 - 1) !== index) {
    pos += factor

    // read too far, to to left child
    while ((pos + factor / 2 - 1) > index) {
      factor /= 2
      pos -= factor / 2
    }

    // the "gap" is a future root
    result.push(pos - factor / 2)
  }

  return result
}

exports.patch = function (from, to) {
  if (from === 0 || from >= to) return []

  const roots = exports.fullRoots(from)
  const target = exports.fullRoots(to)

  // first find the first root that is different

  let i = 0
  for (; i < target.length; i++) {
    if (i >= roots.length || roots[i] !== target[i]) break
  }

  const patch = []

  if (i < roots.length) {
    // now we need to grow the newest root until it hits the diff one
    let prev = roots.length - 1

    const ite = exports.iterator(roots[prev--])

    while (ite.index !== target[i]) {
      ite.sibling()

      if (prev >= 0 && ite.index === roots[prev]) {
        prev--
      } else {
        patch.push(ite.index)
      }

      patch.push(ite.parent())
    }

    i++ // patched to next root, so inc
  }

  // include the rest

  for (; i < target.length; i++) patch.push(target[i])

  return patch
}

exports.depth = function (index) {
  let depth = 0

  index += 1
  while (!(index & 1)) {
    depth++
    index = rightShift(index)
  }

  return depth
}

exports.sibling = function (index, depth) {
  if (!depth) depth = exports.depth(index)
  const offset = exports.offset(index, depth)

  return exports.index(depth, offset & 1 ? offset - 1 : offset + 1)
}

exports.parent = function (index, depth) {
  if (!depth) depth = exports.depth(index)
  const offset = exports.offset(index, depth)

  return exports.index(depth + 1, rightShift(offset))
}

exports.leftChild = function (index, depth) {
  if (!(index & 1)) return -1
  if (!depth) depth = exports.depth(index)
  return exports.index(depth - 1, exports.offset(index, depth) * 2)
}

exports.rightChild = function (index, depth) {
  if (!(index & 1)) return -1
  if (!depth) depth = exports.depth(index)
  return exports.index(depth - 1, 1 + (exports.offset(index, depth) * 2))
}

exports.children = function (index, depth) {
  if (!(index & 1)) return null

  if (!depth) depth = exports.depth(index)
  const offset = exports.offset(index, depth) * 2

  return [
    exports.index(depth - 1, offset),
    exports.index(depth - 1, offset + 1)
  ]
}

exports.leftSpan = function (index, depth) {
  if (!(index & 1)) return index
  if (!depth) depth = exports.depth(index)
  return exports.offset(index, depth) * twoPow(depth + 1)
}

exports.rightSpan = function (index, depth) {
  if (!(index & 1)) return index
  if (!depth) depth = exports.depth(index)
  return (exports.offset(index, depth) + 1) * twoPow(depth + 1) - 2
}

exports.nextLeaf = function (index) {
  let factor = 1
  let r = index

  while ((r & 1) === 1) {
    r = (r - 1) / 2
    factor *= 2
  }

  return index + factor + 1
}

exports.count = function (index, depth) {
  if (!(index & 1)) return 1
  if (!depth) depth = exports.depth(index)
  return twoPow(depth + 1) - 1
}

exports.countLeaves = function (index) {
  return (exports.count(index) + 1) / 2
}

exports.spans = function (index, depth) {
  if (!(index & 1)) return [index, index]
  if (!depth) depth = exports.depth(index)

  const offset = exports.offset(index, depth)
  const width = twoPow(depth + 1)

  return [offset * width, (offset + 1) * width - 2]
}

exports.index = function (depth, offset) {
  return (1 + 2 * offset) * twoPow(depth) - 1
}

exports.offset = function (index, depth) {
  if (!(index & 1)) return index / 2
  if (!depth) depth = exports.depth(index)

  return ((index + 1) / twoPow(depth) - 1) / 2
}

exports.iterator = function (index) {
  const ite = new Iterator()
  ite.seek(index || 0)
  return ite
}

function twoPow (n) {
  return n < 31 ? 1 << n : ((1 << 30) * (1 << (n - 30)))
}

function rightShift (n) {
  return (n - (n & 1)) / 2
}

function Iterator () {
  this.index = 0
  this.offset = 0
  this.factor = 0
}

Iterator.prototype.seek = function (index) {
  this.index = index
  if (this.index & 1) {
    this.offset = exports.offset(index)
    this.factor = twoPow(exports.depth(index) + 1)
  } else {
    this.offset = index / 2
    this.factor = 2
  }
}

Iterator.prototype.isLeft = function () {
  return (this.offset & 1) === 0
}

Iterator.prototype.isRight = function () {
  return (this.offset & 1) === 1
}

Iterator.prototype.isRoot = function (length) {
  const currentLength = 1 + (this.index + this.factor / 2 - 1) / 2
  if (length < currentLength) return false

  const factor = this.factor * 2
  const index = (this.offset & 1)
    ? this.index - this.factor / 2
    : this.index + this.factor / 2

  const parentLength = 1 + (index + factor / 2 - 1) / 2
  return parentLength > length
}

Iterator.prototype.contains = function (index) {
  return index > this.index
    ? index < (this.index + this.factor / 2)
    : index < this.index
      ? index > (this.index - this.factor / 2)
      : true
}

Iterator.prototype.prev = function () {
  if (!this.offset) return this.index
  this.offset--
  this.index -= this.factor
  return this.index
}

Iterator.prototype.next = function () {
  this.offset++
  this.index += this.factor
  return this.index
}

Iterator.prototype.count = function () {
  if (!(this.index & 1)) return 1
  return this.factor - 1
}

Iterator.prototype.countLeaves = function () {
  return (this.count() + 1) / 2
}

Iterator.prototype.sibling = function () {
  return this.isLeft() ? this.next() : this.prev()
}

Iterator.prototype.parent = function () {
  if (this.offset & 1) {
    this.index -= this.factor / 2
    this.offset = (this.offset - 1) / 2
  } else {
    this.index += this.factor / 2
    this.offset /= 2
  }
  this.factor *= 2
  return this.index
}

Iterator.prototype.leftSpan = function () {
  this.index = this.index - this.factor / 2 + 1
  this.offset = this.index / 2
  this.factor = 2
  return this.index
}

Iterator.prototype.peekLeftSpan = function () {
  return this.index - this.factor / 2 + 1
}

Iterator.prototype.rightSpan = function () {
  this.index = this.index + this.factor / 2 - 1
  this.offset = this.index / 2
  this.factor = 2
  return this.index
}

Iterator.prototype.peekRightSpan = function () {
  return this.index + this.factor / 2 - 1
}

Iterator.prototype.leftChild = function () {
  if (this.factor === 2) return this.index
  this.factor /= 2
  this.index -= this.factor / 2
  this.offset *= 2
  return this.index
}

Iterator.prototype.rightChild = function () {
  if (this.factor === 2) return this.index
  this.factor /= 2
  this.index += this.factor / 2
  this.offset = 2 * this.offset + 1
  return this.index
}

Iterator.prototype.nextTree = function () {
  this.index = this.index + this.factor / 2 + 1
  this.offset = this.index / 2
  this.factor = 2
  return this.index
}

Iterator.prototype.prevTree = function () {
  if (!this.offset) {
    this.index = 0
    this.factor = 2
  } else {
    this.index = this.index - this.factor / 2 - 1
    this.offset = this.index / 2
    this.factor = 2
  }
  return this.index
}

Iterator.prototype.fullRoot = function (index) {
  if (index <= this.index || (this.index & 1) > 0) return false
  while (index > this.index + this.factor + this.factor / 2) {
    this.index += this.factor / 2
    this.factor *= 2
    this.offset /= 2
  }
  return true
}
{
  "name": "flat-tree",
  "version": "1.13.0",
  "description": "A series of functions to map a binary tree to a list",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {},
  "devDependencies": {
    "brittle": "^3.3.2",
    "standard": "^17.1.0"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/flat-tree.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/flat-tree/issues"
  },
  "homepage": "https://github.com/mafintosh/flat-tree"
}
require.addon = require('require-addon')

module.exports = require.addon('.', __filename)
const { isWindows } = require('which-runtime')
const binding = require('./binding')

function onwork(err, result) {
  if (err) this.reject(err)
  else this.resolve(result)
}

exports.tryLock = function tryLock(fd, offset = 0, length = 0, opts = {}) {
  if (typeof offset === 'object') {
    opts = offset
    offset = 0
  }

  if (typeof length === 'object') {
    opts = length
    length = 0
  }

  if (typeof opts !== 'object' || opts === null) {
    opts = {}
  }

  try {
    binding.tryLock(fd, offset, length, opts.shared !== true)
  } catch (err) {
    if (err.code === 'EAGAIN') return false
    throw err
  }

  return true
}

exports.waitForLock = function waitForLock(
  fd,
  offset = 0,
  length = 0,
  opts = {}
) {
  if (typeof offset === 'object') {
    opts = offset
    offset = 0
  }

  if (typeof length === 'object') {
    opts = length
    length = 0
  }

  if (typeof opts !== 'object' || opts === null) {
    opts = {}
  }

  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.waitForLock(
      fd,
      offset,
      length,
      opts.shared !== true,
      req,
      onwork
    )
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.tryDowngradeLock = function tryDowngradeLock(
  fd,
  offset = 0,
  length = 0
) {
  try {
    binding.tryDowngradeLock(fd, offset, length)
  } catch (err) {
    if (err.code === 'EAGAIN') return false
    throw err
  }

  return true
}

exports.waitForDowngradeLock = function downgradeLock(
  fd,
  offset = 0,
  length = 0
) {
  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.waitForDowngradeLock(fd, offset, length, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.tryUpgradeLock = function tryUpgradeLock(fd, offset = 0, length = 0) {
  try {
    binding.tryUpgradeLock(fd, offset, length)
  } catch (err) {
    if (err.code === 'EAGAIN') return false
    throw err
  }

  return true
}

exports.waitForUpgradeLock = function upgradeLock(fd, offset = 0, length = 0) {
  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.waitForUpgradeLock(fd, offset, length, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.unlock = function unlock(fd, offset = 0, length = 0) {
  binding.unlock(fd, offset, length)
}

exports.trim = function trim(fd, offset, length) {
  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.trim(fd, offset, length, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.sparse = function sparse(fd) {
  // Short circuit on everything but Windows
  if (!isWindows) return Promise.resolve()

  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.sparse(fd, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.swap = function swap(from, to) {
  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.swap(from, to, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.getAttr = function getAttr(fd, name) {
  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.getAttr(fd, name, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise.then((buffer) =>
    buffer === null ? null : Buffer.from(buffer)
  )
}

exports.setAttr = function setAttr(fd, name, value, encoding) {
  if (typeof value === 'string') value = Buffer.from(value, encoding)

  const req = {
    value,
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.setAttr(
      fd,
      name,
      value.buffer,
      value.byteOffset,
      value.byteLength,
      req,
      onwork
    )
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.removeAttr = function removeAttr(fd, name) {
  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.removeAttr(fd, name, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.listAttrs = function listAttrs(fd) {
  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.listAttrs(fd, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}
{
  "name": "fs-native-extensions",
  "version": "1.4.5",
  "description": "Native file system extensions for advanced file operations",
  "main": "index.js",
  "files": [
    "index.js",
    "macros.h",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "include",
    "src",
    "prebuilds"
  ],
  "imports": {
    "child_process": {
      "bare": "bare-subprocess",
      "default": "child_process"
    },
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "fs/*": {
      "bare": "bare-fs/*",
      "default": "fs/*"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    }
  },
  "addon": true,
  "scripts": {
    "test": "npm run lint && npm run test:bare && npm run test:node",
    "test:bare": "bare test.js",
    "test:node": "node test.js",
    "lint": "prettier . --check"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/fs-native-extensions.git"
  },
  "author": "Kasper Isager Dalsgarð <kasper@funktionel.co>",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/fs-native-extensions/issues"
  },
  "homepage": "https://github.com/holepunchto/fs-native-extensions#readme",
  "dependencies": {
    "require-addon": "^1.1.0",
    "which-runtime": "^1.2.0"
  },
  "devDependencies": {
    "bare-compat-napi": "^1.3.8",
    "bare-fs": "^4.4.4",
    "bare-path": "^3.0.0",
    "bare-subprocess": "^4.0.5",
    "brittle": "^3.1.1",
    "cmake-bare": "^1.1.10",
    "cmake-fetch": "^1.4.7",
    "cmake-napi": "^1.0.5",
    "cmake-npm": "^1.1.0",
    "minimist": "^1.2.6",
    "prettier": "^3.5.3",
    "prettier-config-standard": "^7.0.0",
    "test-tmp": "^1.2.1"
  }
}
const codecs = require('codecs')
const { Readable } = require('streamx')
const mutexify = require('mutexify/promise')
const b4a = require('b4a')
const safetyCatch = require('safety-catch')
const ReadyResource = require('ready-resource')
const debounce = require('debounceify')
const Rache = require('rache')
const rrp = require('resolve-reject-promise')

const { all: unslabAll } = require('unslab')

const RangeIterator = require('./iterators/range')
const HistoryIterator = require('./iterators/history')
const DiffIterator = require('./iterators/diff')
const LocalBlockIterator = require('./iterators/local')
const Extension = require('./lib/extension')
const { YoloIndex, Node, Header } = require('./lib/messages')
const { BLOCK_NOT_AVAILABLE, DECODING_ERROR } = require('hypercore-errors')

const T = 5
const MIN_KEYS = T - 1
const MAX_CHILDREN = MIN_KEYS * 2 + 1

const SEP = b4a.alloc(1)
const EMPTY = b4a.alloc(0)

class Key {
  constructor(seq, value) {
    this.seq = seq
    this.value = value
  }
}

class Child {
  constructor(seq, offset, value) {
    this.seq = seq
    this.offset = offset
    this.value = value
  }
}

class Cache {
  constructor(rache) {
    this.keys = rache
    this.length = 0
  }

  get(seq) {
    return this.keys.get(seq) || null
  }

  set(seq, key) {
    this.keys.set(seq, key)
    if (seq >= this.length) this.length = seq + 1
  }

  gc(length) {
    // if we need to "work" more than 128 ticks, just bust the cache...
    if (this.length - length > 128) {
      this.keys.clear()
    } else {
      for (let i = length; i < this.length; i++) {
        this.keys.delete(i)
      }
    }

    this.length = length
  }

  clear() {
    this.keys.clear()
  }
}

class Pointers {
  constructor(decoded) {
    this.levels = decoded.levels.map((l) => {
      const children = []
      const keys = []

      for (let i = 0; i < l.keys.length; i++) {
        keys.push(new Key(l.keys[i], null))
      }

      for (let i = 0; i < l.children.length; i += 2) {
        children.push(new Child(l.children[i], l.children[i + 1], null))
      }

      return { keys, children }
    })
  }

  get(i) {
    return this.levels[i]
  }

  hasKey(seq) {
    for (const lvl of this.levels) {
      for (const key of lvl.keys) {
        if (key.seq === seq) return true
      }
    }
    return false
  }
}

function inflate(entry) {
  if (entry.inflated === null) {
    entry.inflated = YoloIndex.decode(entry.index)
    entry.index = null
  }
  return new Pointers(entry.inflated)
}

function deflate(index) {
  const levels = index.map((l) => {
    const keys = []
    const children = []

    for (let i = 0; i < l.value.keys.length; i++) {
      keys.push(l.value.keys[i].seq)
    }

    for (let i = 0; i < l.value.children.length; i++) {
      children.push(l.value.children[i].seq, l.value.children[i].offset)
    }

    return { keys, children }
  })

  return YoloIndex.encode({ levels })
}

class TreeNode {
  constructor(block, keys, children, offset) {
    this.block = block
    this.offset = offset
    this.keys = keys
    this.children = children
    this.changed = false

    this.preload()
  }

  preload() {
    if (this.block === null) return

    const core = getBackingCore(this.block.tree.core)
    if (!core) return

    const bitfield = core.core.bitfield
    const blocks = []

    for (let i = 0; i < this.keys.length; i++) {
      const k = this.keys[i]
      if (k.value) continue
      if (k.seq >= core.signedLength || (bitfield && bitfield.get(k.seq))) continue
      blocks.push(k.seq)
    }
    for (let i = 0; i < this.children.length; i++) {
      const c = this.children[i]
      if (c.value) continue
      if (c.seq >= core.signedLength || (bitfield && bitfield.get(c.seq))) continue
      blocks.push(c.seq)
    }

    if (blocks.length) core.download({ blocks })
  }

  async insertKey(key, value, child, node, encoding, cas) {
    let s = 0
    let e = this.keys.length
    let c

    while (s < e) {
      const mid = (s + e) >> 1
      c = b4a.compare(key.value, await this.getKey(mid))

      if (c === 0) {
        if (cas) {
          const prev = await this.getKeyNode(mid)
          if (!(await cas(prev.final(encoding), node))) return true
        }
        if (!this.block.tree.tree.alwaysDuplicate) {
          const prev = await this.getKeyNode(mid)
          if (sameValue(prev.value, value)) return true
        }
        this.changed = true
        this.keys[mid] = key
        return true
      }

      if (c < 0) e = mid
      else s = mid + 1
    }

    const i = c < 0 ? e : s
    this.keys.splice(i, 0, key)
    if (child) this.children.splice(i + 1, 0, new Child(0, 0, child))
    this.changed = true

    return this.keys.length < MAX_CHILDREN
  }

  removeKey(index) {
    this.keys.splice(index, 1)
    if (this.children.length) {
      this.children[index + 1].seq = 0 // mark as freed
      this.children.splice(index + 1, 1)
    }
    this.changed = true
  }

  async siblings(parent) {
    for (let i = 0; i < parent.children.length; i++) {
      if (parent.children[i].value === this) {
        const [left, right] = await Promise.all([
          i ? parent.getChildNode(i - 1) : null,
          i < parent.children.length - 1 ? parent.getChildNode(i + 1) : null
        ])
        return { left, index: i, right }
      }
    }

    throw new Error('Bad parent')
  }

  merge(node, median) {
    this.changed = true
    this.keys.push(median)
    for (let i = 0; i < node.keys.length; i++) this.keys.push(node.keys[i])
    for (let i = 0; i < node.children.length; i++) this.children.push(node.children[i])
  }

  async split() {
    const len = this.keys.length >> 1
    const right = TreeNode.create(this.block)

    while (right.keys.length < len) right.keys.push(this.keys.pop())
    right.keys.reverse()

    await this.getKey(this.keys.length - 1) // make sure the median is loaded
    const median = this.keys.pop()

    if (this.children.length) {
      while (right.children.length < len + 1) right.children.push(this.children.pop())
      right.children.reverse()
    }

    this.changed = true

    return {
      left: this,
      median,
      right
    }
  }

  getKeyNode(index) {
    return this.block.tree.getBlock(this.keys[index].seq)
  }

  async getChildNode(index) {
    const child = this.children[index]
    if (child.value) return child.value
    const block =
      child.seq === this.block.seq ? this.block : await this.block.tree.getBlock(child.seq)
    return (child.value = block.getTreeNode(child.offset))
  }

  setKey(index, key) {
    this.keys[index] = key
    this.changed = true
  }

  async getKey(index) {
    const key = this.keys[index]
    if (key.value) return key.value
    const k = key.seq === this.block.seq ? this.block.key : await this.block.tree.getKey(key.seq)
    return (key.value = k)
  }

  indexChanges(index, seq) {
    const offset = index.push(null) - 1
    this.changed = false

    for (const child of this.children) {
      if (!child.value || !child.value.changed) continue
      child.seq = seq
      child.offset = child.value.indexChanges(index, seq)
      index[child.offset] = child
    }

    return offset
  }

  updateChildren(seq, block) {
    for (const child of this.children) {
      if (!child.value || child.seq !== seq) continue
      child.value.block = block
      child.value.updateChildren(seq, block)
    }
  }

  static create(block) {
    const node = new TreeNode(block, [], [], 0)
    node.changed = true
    return node
  }
}

class BlockEntry {
  constructor(seq, tree, entry) {
    this.seq = seq
    this.tree = tree
    this.index = null
    this.entry = entry
    this.key = entry.key
    this.value = entry.value
  }

  isTarget(key) {
    return b4a.equals(this.key, key)
  }

  inflate() {
    if (this.index === null) {
      this.index = inflate(this.entry)
    }
  }

  isDeletion() {
    if (this.value !== null) return false

    if (this.index === null) {
      this.index = inflate(this.entry)
    }

    return !this.index.hasKey(this.seq)
  }

  final(encoding) {
    return {
      seq: this.seq,
      key: encoding.key ? encoding.key.decode(this.key) : this.key,
      value: this.value && (encoding.value ? encoding.value.decode(this.value) : this.value)
    }
  }

  getTreeNode(offset) {
    if (this.index === null) {
      this.index = inflate(this.entry)
    }
    const entry = this.index.get(offset)
    return new TreeNode(this, entry.keys, entry.children, offset)
  }
}

class CacheLock {
  constructor() {
    this.map = new Map()
  }

  enter(seq) {
    const pending = this.map.get(seq)

    if (!pending) {
      this.map.set(seq, [])
      return Promise.resolve()
    }

    const { resolve, promise } = rrp()
    pending.push(resolve)
    return promise
  }

  exit(seq) {
    const pending = this.map.get(seq)
    if (!pending.length) {
      this.map.delete(seq)
      return
    }

    pending.pop()()
  }
}

class BatchEntry extends BlockEntry {
  constructor(seq, tree, key, value, index) {
    super(seq, tree, { key, value, index: null, inflated: null })
    this.pendingIndex = index
  }

  isTarget(key) {
    return false
  }

  getTreeNode(offset) {
    return this.pendingIndex[offset].value
  }
}

class Hyperbee extends ReadyResource {
  constructor(core, opts = {}) {
    super()
    // this.feed is now deprecated, and will be this.core going forward
    this.feed = core
    this.core = core

    this.keyEncoding = opts.keyEncoding ? codecs(opts.keyEncoding) : null
    this.valueEncoding = opts.valueEncoding ? codecs(opts.valueEncoding) : null
    this.extension = opts.extension !== false ? getExtension(this, opts) : null
    this.metadata = opts.metadata || null
    this.lock = opts.lock || mutexify()
    this.sep = opts.sep || SEP
    this.readonly = !!opts.readonly
    this.prefix = opts.prefix || null

    // In a future version, this should be false by default
    this.alwaysDuplicate = opts.alwaysDuplicate !== false

    this._unprefixedKeyEncoding = this.keyEncoding
    this._sub = !!this.prefix
    this._checkout = opts.checkout || 0
    this._view = !!opts._view

    this._onappendBound = this._view ? null : this._onappend.bind(this)
    this._ontruncateBound = this._view ? null : this._ontruncate.bind(this)
    this._watchers = this._onappendBound ? [] : null
    this._entryWatchers = this._onappendBound ? [] : null
    this._sessions = opts.sessions !== false

    this._keyCache = null
    this._nodeCache = null
    this._cacheLock = new CacheLock()

    this._batches = []

    if (this._watchers) {
      this.core.on('append', this._onappendBound)
      this.core.on('truncate', this._ontruncateBound)
    }

    if (this.prefix && opts._sub) {
      this.keyEncoding = prefixEncoding(this.prefix, this.keyEncoding)
    }

    this.ready().catch(safetyCatch)
  }

  async _open() {
    if (this.core.opened === false) await this.core.ready()
    // bump the internal ranges since the nodes are small
    if (this._watchers && this.core.replicator.setInflightRange) {
      this.core.replicator.setInflightRange(256, 512)
    }

    // snapshot
    if (this._checkout === -1) this._checkout = Math.max(1, this.core.length)

    const baseCache = Rache.from(this.core.globalCache)
    this._keyCache = new Cache(baseCache)
    this._nodeCache = new Cache(Rache.from(baseCache))
  }

  get version() {
    return Math.max(1, this._checkout || this.core.length)
  }

  get id() {
    return this.core.id
  }

  get key() {
    return this.core.key
  }

  get discoveryKey() {
    return this.core.discoveryKey
  }

  get writable() {
    return this.core.writable
  }

  get readable() {
    return this.core.readable
  }

  replicate(isInitiator, opts) {
    return this.core.replicate(isInitiator, opts)
  }

  update(opts) {
    return this.core.update(opts)
  }

  peek(range, opts) {
    return iteratorPeek(this.createRangeIterator(range, { ...opts, limit: 1 }))
  }

  createRangeIterator(range, opts = {}) {
    // backwards compat range arg
    opts = opts ? { ...opts, ...range } : range

    const extension = opts.extension === false && opts.limit !== 0 ? null : this.extension
    const keyEncoding = opts.keyEncoding ? codecs(opts.keyEncoding) : this.keyEncoding

    if (extension) {
      const { onseq, onwait } = opts
      let version = 0
      let next = 0

      opts = encRange(keyEncoding, {
        ...opts,
        sub: this._sub,
        onseq(seq) {
          if (!version) version = seq + 1
          if (next) next--
          if (onseq) onseq(seq)
        },
        onwait(seq) {
          if (!next) {
            next = Extension.BATCH_SIZE
            extension.iterator(ite.snapshot(version))
          }
          if (onwait) onwait(seq)
        }
      })
    } else {
      opts = encRange(keyEncoding, { ...opts, sub: this._sub })
    }

    const ite = new RangeIterator(
      new Batch(this, this._makeSnapshot(), null, false, opts),
      null,
      opts
    )
    return ite
  }

  createReadStream(range, opts) {
    const signal = (opts && opts.signal) || null
    return iteratorToStream(this.createRangeIterator(range, opts), signal)
  }

  createHistoryStream(opts) {
    const session = opts && opts.live ? this.core.session() : this._makeSnapshot()
    const signal = (opts && opts.signal) || null
    return iteratorToStream(
      new HistoryIterator(new Batch(this, session, null, false, opts), opts),
      signal
    )
  }

  createDiffStream(right, range, opts) {
    if (typeof right === 'number') right = this.checkout(Math.max(1, right), { reuseSession: true })

    // backwards compat range arg
    opts = opts ? { ...opts, ...range } : range

    const signal = (opts && opts.signal) || null

    const keyEncoding = opts && opts.keyEncoding ? codecs(opts.keyEncoding) : this.keyEncoding
    if (keyEncoding) opts = encRange(keyEncoding, { ...opts, sub: this._sub })

    let done
    let closing
    let ite

    const left = this

    const rs = new Readable({
      signal,
      eagerOpen: true,
      async open(cb) {
        try {
          if (right.opened === false) await right.ready()
          if (left.opened === false) await left.ready()
        } catch (err) {
          cb(err)
          return
        }

        if (closing) {
          cb(null)
          return
        }

        if (left.core.closing || right.core.closing) {
          cb(new Error('Bee closed'))
          return
        }

        const snapshot = right.version > left.version ? right._makeSnapshot() : left._makeSnapshot()

        done = cb
        ite = new DiffIterator(
          new Batch(left, snapshot, null, false, opts),
          new Batch(right, snapshot, null, false, opts),
          opts
        )
        ite.open().then(fin, fin)
      },
      read(cb) {
        done = cb
        ite.next().then(push, fin)
      },
      predestroy() {
        if (!ite) {
          closing = Promise.resolve()
        } else {
          closing = ite.close()
          closing.catch(noop)
        }
      },
      destroy(cb) {
        done = cb
        if (!closing) closing = ite.close()
        closing.then(fin, fin)
      }
    })

    return rs

    function fin(err) {
      done(err)
    }

    function push(val) {
      rs.push(val)
      done(null)
    }
  }

  get(key, opts) {
    const b = new Batch(this, this._makeSnapshot(), null, true, opts)
    return b.get(key)
  }

  getBySeq(seq, opts) {
    const b = new Batch(this, this._makeSnapshot(), null, true, opts)
    return b.getBySeq(seq)
  }

  put(key, value, opts) {
    const b = new Batch(this, this.core, null, true, opts)
    return b.put(key, value, opts)
  }

  batch(opts) {
    return new Batch(this, this.core, mutexify(), true, opts)
  }

  del(key, opts) {
    const b = new Batch(this, this.core, null, true, opts)
    return b.del(key, opts)
  }

  watch(range, opts) {
    if (!this._watchers) throw new Error('Can only watch the main bee instance')
    return new Watcher(this, range, opts)
  }

  async getAndWatch(key, opts) {
    if (!this._watchers) throw new Error('Can only watch the main bee instance')

    const watcher = new EntryWatcher(this, key, opts)
    await watcher._debouncedUpdate()

    if (this.closing) {
      await watcher.close()
      throw new Error('Bee closed')
    }

    return watcher
  }

  _onappend() {
    for (const watcher of this._watchers) {
      watcher._onappend()
    }

    for (const watcher of this._entryWatchers) {
      watcher._onappend()
    }
  }

  _ontruncate(length) {
    for (const watcher of this._watchers) {
      watcher._ontruncate()
    }

    for (const watcher of this._entryWatchers) {
      watcher._ontruncate()
    }

    this._nodeCache.gc(length)
    this._keyCache.gc(length)
  }

  _makeSnapshot() {
    if (this._sessions === false) return this.core
    // TODO: better if we could encapsulate this in hypercore in the future
    return this._checkout <= this.core.length || this._checkout <= 1
      ? this.core.snapshot()
      : this.core.session({ snapshot: false })
  }

  async clearUnlinked(options = {}) {
    await this.ready()

    const { gte = 0, lt = this.version - 1, batchSize = 4096, wait = true } = options
    const checkout = this.version

    let prev = this.batch({ wait: false, checkout: gte })
    let b = this.batch({ wait, checkout })

    const iteBatch = this.batch({ wait: false, checkout })
    const ite = new LocalBlockIterator(iteBatch, { gte, lt })
    await ite.open()

    let ticks = 0

    while (true) {
      const data = await ite.next()
      if (!data) break

      if (!(await isLinked(b, data))) {
        if (b.core.closing || this.core.closing || this.closing) break
        await this.core.clear(data.seq)
      }

      const prevNode = await prev.get(data.key, { finalize: false }).catch(toNull)

      if (prevNode && !(await isLinked(b, prevNode))) {
        if (b.core.closing || this.core.closing || this.closing) break
        await this.core.clear(prevNode.seq)
      }

      if (ticks++ >= batchSize) {
        ticks = 0
        await prev.close()
        await b.close()

        prev = this.batch({ wait: false, checkout: gte })
        b = this.batch({ wait, checkout })
      }
    }

    if (b.core.closing || this.core.closing || this.closing) throw new Error('Core is closed')

    await b.close()
    await prev.close()
    await ite.close()
    await iteBatch.close()

    return lt
  }

  checkout(version, opts = {}) {
    if (version === 0) version = 1

    // same as above, just checkout isn't set yet...
    const snap =
      opts.reuseSession || this._sessions === false
        ? this.core
        : version <= this.core.length || version <= 1
          ? this.core.snapshot()
          : this.core.session({ snapshot: false })

    return new Hyperbee(snap, {
      _view: true,
      _sub: false,
      prefix: this.prefix,
      sep: this.sep,
      lock: this.lock,
      checkout: version,
      keyEncoding: opts.keyEncoding || this.keyEncoding,
      valueEncoding: opts.valueEncoding || this.valueEncoding,
      extension: this.extension !== null ? this.extension : false
    })
  }

  snapshot(opts) {
    return this.checkout(
      this.core.opened === false || this._checkout <= 0 ? -1 : Math.max(1, this.version),
      opts
    )
  }

  sub(prefix, opts = {}) {
    let sep = opts.sep || this.sep
    if (!b4a.isBuffer(sep)) sep = b4a.from(sep)

    prefix = b4a.concat([this.prefix || EMPTY, b4a.from(prefix), sep])

    const valueEncoding = codecs(opts.valueEncoding || this.valueEncoding)
    const keyEncoding = codecs(opts.keyEncoding || this._unprefixedKeyEncoding)

    return new Hyperbee(this.core, {
      _view: true,
      _sub: true,
      prefix,
      sep: this.sep,
      lock: this.lock,
      checkout: this._checkout,
      valueEncoding,
      keyEncoding,
      extension: this.extension !== null ? this.extension : false,
      metadata: this.metadata
    })
  }

  async getHeader(opts) {
    const blk = await this.core.get(0, opts)
    try {
      return blk && Header.decode(blk)
    } catch {
      throw DECODING_ERROR()
    }
  }

  async _close() {
    if (!this._view) {
      if (this._keyCache) this._keyCache.clear()
      if (this._nodeCache) this._nodeCache.clear()
    }

    if (this._watchers) {
      this.core.off('append', this._onappendBound)
      this.core.off('truncate', this._ontruncateBound)

      while (this._watchers.length) {
        await this._watchers[this._watchers.length - 1].close()
      }
    }

    if (this._entryWatchers) {
      while (this._entryWatchers.length) {
        await this._entryWatchers[this._entryWatchers.length - 1].close()
      }
    }

    while (this._batches.length) {
      await this._batches[this._batches.length - 1].close()
    }

    return this.core.close()
  }

  static async isHyperbee(core, opts) {
    await core.ready()

    const blk0 = await core.get(0, opts)
    if (blk0 === null) throw BLOCK_NOT_AVAILABLE()

    try {
      return Header.decode(blk0).protocol === 'hyperbee'
    } catch (err) {
      // undecodable
      return false
    }
  }
}

class Batch {
  constructor(tree, core, batchLock, cache, options = {}) {
    this.tree = tree
    // this.feed is now deprecated, and will be this.core going forward
    this.feed = core
    this.core = core
    this.index = tree._batches.push(this) - 1
    this.blocks = cache ? new Map() : null
    this.autoFlush = !batchLock
    this.maxBlocksCached = options.maxBlocksCached || 128
    this.rootSeq = 0
    this.root = null
    this.length = 0
    this.checkout = options.checkout === undefined ? -1 : options.checkout
    this.options = options
    this.locked = null
    this.batchLock = batchLock
    this.onseq = this.options.onseq || noop
    this.appending = null
    this.isSnapshot = this.core !== this.tree.core
    this.shouldUpdate = this.options.update !== false
    this.updating = null
    this.encoding = {
      key: options.keyEncoding ? codecs(options.keyEncoding) : tree.keyEncoding,
      value: options.valueEncoding ? codecs(options.valueEncoding) : tree.valueEncoding
    }
  }

  async ready() {
    if (this.core.opened === false) await this.core.ready()
    if (this.tree.opened === false) await this.tree.ready()
  }

  async lock() {
    if (this.tree.readonly) throw new Error('Hyperbee is marked as read-only')
    if (this.locked === null) this.locked = await this.tree.lock()
  }

  get version() {
    if (this.checkout !== -1) return Math.max(1, this.checkout)
    return Math.max(1, this.tree._checkout || this.core.length + this.length)
  }

  async getRoot(ensureHeader) {
    await this.ready()
    if (ensureHeader) {
      if (this.core.length === 0 && this.core.writable && !this.tree.readonly) {
        await this.core.append(
          Header.encode({
            protocol: 'hyperbee',
            metadata: this.tree.metadata
          })
        )
      }
    }
    if (this.tree._checkout === 0 && this.checkout === -1 && this.shouldUpdate) {
      if (this.updating === null) this.updating = this.core.update()
      await this.updating
    }
    if (this.version < 2) return null
    return (await this.getBlock(this.version - 1)).getTreeNode(0)
  }

  async getKey(seq) {
    await this.tree._cacheLock.enter(seq)

    try {
      const k = this.core.fork === this.tree.core.fork ? this.tree._keyCache.get(seq) : null
      if (k !== null) return k
      const key = (await this._getBlock(seq)).key
      if (this.core.fork === this.tree.core.fork) this.tree._keyCache.set(seq, key)
      return key
    } finally {
      this.tree._cacheLock.exit(seq)
    }
  }

  async _getNode(seq) {
    const cached =
      this.tree._nodeCache !== null && this.core.fork === this.tree.core.fork
        ? this.tree._nodeCache.get(seq)
        : null
    if (cached !== null) return cached
    const entry = await this.core.get(seq, {
      ...this.options,
      valueEncoding: Node
    })
    if (entry === null) throw BLOCK_NOT_AVAILABLE()
    const wrap = copyEntry(entry)
    if (this.core.fork === this.tree.core.fork && this.tree._nodeCache !== null) {
      this.tree._nodeCache.set(seq, wrap)
    }
    return wrap
  }

  async getBlock(seq) {
    if (this.rootSeq === 0) this.rootSeq = seq
    await this.tree._cacheLock.enter(seq)

    try {
      return await this._getBlock(seq)
    } finally {
      this.tree._cacheLock.exit(seq)
    }
  }

  async _getBlock(seq) {
    let b = this.blocks && this.blocks.get(seq)
    if (b) return b
    this.onseq(seq)
    const entry = await this._getNode(seq)
    b = this.blocks && this.blocks.get(seq)
    if (b) return b
    b = new BlockEntry(seq, this, entry)
    if (this.blocks && this.blocks.size - this.length < this.maxBlocksCached) {
      this.blocks.set(seq, b)
    }
    return b
  }

  _onwait(key) {
    this.options.onwait = null
    this.tree.extension.get(this.rootSeq + 1, key)
  }

  _getEncoding(opts) {
    if (!opts) return this.encoding
    return {
      key: opts.keyEncoding ? codecs(opts.keyEncoding) : this.encoding.key,
      value: opts.valueEncoding ? codecs(opts.valueEncoding) : this.encoding.value
    }
  }

  peek(range, opts) {
    return iteratorPeek(this.createRangeIterator(range, { ...opts, limit: 1 }))
  }

  createRangeIterator(range, opts = {}) {
    // backwards compat range arg
    opts = opts ? { ...opts, ...range } : range

    const encoding = this._getEncoding(opts)
    return new RangeIterator(
      this,
      encoding,
      encRange(encoding.key, { ...opts, sub: this.tree._sub })
    )
  }

  createReadStream(range, opts) {
    const signal = (opts && opts.signal) || null
    return iteratorToStream(this.createRangeIterator(range, opts), signal)
  }

  async getBySeq(seq, opts) {
    const encoding = this._getEncoding(opts)

    try {
      const block = (await this.getBlock(seq)).final(encoding)
      return { key: block.key, value: block.value }
    } finally {
      await this._closeSnapshot()
    }
  }

  async get(key, opts) {
    const encoding = this._getEncoding(opts)
    const finalize = opts ? opts.finalize !== false : true

    try {
      return await this._get(key, encoding, finalize)
    } finally {
      await this._closeSnapshot()
    }
  }

  async _get(key, encoding, finalize) {
    key = enc(encoding.key, key)

    if (this.tree.extension !== null && this.options.extension !== false) {
      this.options.onwait = this._onwait.bind(this, key)
    }

    let node = await this.getRoot(false)
    if (!node) return null

    while (true) {
      if (node.block.isTarget(key)) {
        return node.block.isDeletion() ? null : finalize ? node.block.final(encoding) : node.block
      }

      let s = 0
      let e = node.keys.length
      let c

      while (s < e) {
        const mid = (s + e) >> 1

        c = b4a.compare(key, await node.getKey(mid))

        if (c === 0) {
          const block = await this.getBlock(node.keys[mid].seq)
          return finalize ? block.final(encoding) : block
        }

        if (c < 0) e = mid
        else s = mid + 1
      }

      if (!node.children.length) return null

      const i = c < 0 ? e : s
      node = await node.getChildNode(i)
    }
  }

  async links(key, seq) {
    let node = await this.getRoot(false)
    if (!node) return false

    if (node.block.seq === seq) return true

    while (true) {
      if (node.block.isTarget(key)) return false

      let s = 0
      let e = node.keys.length
      let c

      while (s < e) {
        const mid = (s + e) >> 1

        if (node.keys[mid].seq === seq) return true
        c = b4a.compare(key, await node.getKey(mid))

        if (c === 0) return false

        if (c < 0) e = mid
        else s = mid + 1
      }

      if (!node.children.length) return false

      const i = c < 0 ? e : s
      node = await node.getChildNode(i)
      if (node.block.seq === seq) return true
    }
  }

  async put(key, value, opts) {
    const release = this.batchLock ? await this.batchLock() : null

    const cas = (opts && opts.cas) || null
    const encoding = this._getEncoding(opts)

    if (!this.locked) await this.lock()
    if (!release) return this._put(key, value, encoding, cas)

    try {
      return await this._put(key, value, encoding, cas)
    } finally {
      release()
    }
  }

  async _put(key, value, encoding, cas) {
    const newNode = {
      seq: 0,
      key,
      value
    }
    key = enc(encoding.key, key)
    value = enc(encoding.value, value)

    const stack = []

    let root
    let node = (root = await this.getRoot(true))
    if (!node) node = root = TreeNode.create(null)

    const seq = (newNode.seq = this.core.length + this.length)
    const target = new Key(seq, key)

    while (node.children.length) {
      stack.push(node)
      node.changed = true // changed, but compressible

      let s = 0
      let e = node.keys.length
      let c

      while (s < e) {
        const mid = (s + e) >> 1
        c = b4a.compare(target.value, await node.getKey(mid))

        if (c === 0) {
          if (cas) {
            const prev = await node.getKeyNode(mid)
            if (!(await cas(prev.final(encoding), newNode))) return this._unlockMaybe()
          }
          if (!this.tree.alwaysDuplicate) {
            const prev = await node.getKeyNode(mid)
            if (sameValue(prev.value, value)) return this._unlockMaybe()
          }
          node.setKey(mid, target)
          return this._append(root, seq, key, value)
        }

        if (c < 0) e = mid
        else s = mid + 1
      }

      const i = c < 0 ? e : s
      node = await node.getChildNode(i)
    }

    let needsSplit = !(await node.insertKey(target, value, null, newNode, encoding, cas))
    if (!node.changed) return this._unlockMaybe()

    while (needsSplit) {
      const parent = stack.pop()
      const { median, right } = await node.split()

      if (parent) {
        needsSplit = !(await parent.insertKey(median, value, right, null, encoding, null))
        node = parent
      } else {
        root = TreeNode.create(node.block)
        root.changed = true
        root.keys.push(median)
        root.children.push(new Child(0, 0, node), new Child(0, 0, right))
        needsSplit = false
      }
    }

    return this._append(root, seq, key, value)
  }

  async del(key, opts) {
    const release = this.batchLock ? await this.batchLock() : null
    const cas = (opts && opts.cas) || null
    const encoding = this._getEncoding(opts)

    if (!this.locked) await this.lock()
    if (!release) return this._del(key, encoding, cas)

    try {
      return await this._del(key, encoding, cas)
    } finally {
      release()
    }
  }

  async _del(key, encoding, cas) {
    const delNode = {
      seq: 0,
      key,
      value: null
    }

    key = enc(encoding.key, key)

    const stack = []

    let node = await this.getRoot(true)
    if (!node) return this._unlockMaybe()

    const seq = (delNode.seq = this.core.length + this.length)

    while (true) {
      stack.push(node)

      let s = 0
      let e = node.keys.length
      let c

      while (s < e) {
        const mid = (s + e) >> 1
        c = b4a.compare(key, await node.getKey(mid))

        if (c === 0) {
          if (cas) {
            const prev = await node.getKeyNode(mid)
            if (!(await cas(prev.final(encoding), delNode))) return this._unlockMaybe()
          }
          if (node.children.length) await setKeyToNearestLeaf(node, mid, stack)
          else node.removeKey(mid)
          // we mark these as changed late, so we don't rewrite them if it is a 404
          for (const node of stack) node.changed = true
          return this._append(await rebalance(stack), seq, key, null)
        }

        if (c < 0) e = mid
        else s = mid + 1
      }

      if (!node.children.length) return this._unlockMaybe()

      const i = c < 0 ? e : s
      node = await node.getChildNode(i)
    }
  }

  async _closeSnapshot() {
    if (this.isSnapshot) {
      await this.core.close()
      this._finalize()
    }
  }

  async close() {
    if (this.isSnapshot) return this._closeSnapshot()

    this.root = null
    if (this.blocks) this.blocks.clear()
    this.length = 0
    this._unlock()
  }

  destroy() {
    // compat, remove later
    this.close().catch(noop)
  }

  toBlocks() {
    if (this.appending) return this.appending

    const batch = new Array(this.length)

    for (let i = 0; i < this.length; i++) {
      const seq = this.core.length + i
      const { pendingIndex, key, value } = this.blocks.get(seq)

      if (i < this.length - 1) {
        pendingIndex[0] = null
        let j = 0

        while (j < pendingIndex.length) {
          const idx = pendingIndex[j]
          if (idx !== null && idx.seq === seq) {
            idx.offset = j++
            continue
          }
          if (j === pendingIndex.length - 1) pendingIndex.pop()
          else pendingIndex[j] = pendingIndex.pop()
        }
      }

      batch[i] = Node.encode({
        key,
        value,
        index: deflate(pendingIndex)
      })
    }

    this.appending = batch
    return batch
  }

  flush() {
    if (!this.length) return this.close()

    const batch = this.toBlocks()

    this.root = null
    this.blocks.clear()
    this.length = 0

    return this._appendBatch(batch)
  }

  _unlockMaybe() {
    if (this.autoFlush) this._unlock()
  }

  _unlock() {
    const locked = this.locked
    this.locked = null
    if (locked !== null) locked()
    this._finalize()
  }

  _finalize() {
    // technically finalize can be called more than once, so here we just check if we already have been removed
    if (this.index >= this.tree._batches.length || this.tree._batches[this.index] !== this) return
    const top = this.tree._batches.pop()
    if (top === this) return
    top.index = this.index
    this.tree._batches[top.index] = top
  }

  _append(root, seq, key, value) {
    const index = []
    root.indexChanges(index, seq)
    index[0] = new Child(seq, 0, root)

    if (!this.autoFlush) {
      const block = new BatchEntry(seq, this, key, value, index)
      root.block = block
      this.root = root
      this.length++
      this.blocks.set(seq, block)

      root.updateChildren(seq, block)
      return
    }

    return this._appendBatch(
      Node.encode({
        key,
        value,
        index: deflate(index)
      })
    )
  }

  async _appendBatch(raw) {
    try {
      await this.core.append(raw)
    } finally {
      this._unlock()
    }
  }
}

class EntryWatcher extends ReadyResource {
  constructor(bee, key, opts = {}) {
    super()

    this.keyEncoding = opts.keyEncoding || bee.keyEncoding
    this.valueEncoding = opts.valueEncoding || bee.valueEncoding

    this.index = bee._entryWatchers.push(this) - 1
    this.bee = bee

    this.key = key
    this.node = null

    this._forceUpdate = false
    this._debouncedUpdate = debounce(this._processUpdate.bind(this))
  }

  _close() {
    const top = this.bee._entryWatchers.pop()
    if (top !== this) {
      top.index = this.index
      this.bee._entryWatchers[top.index] = top
    }
  }

  _onappend() {
    this._debouncedUpdate()
  }

  _ontruncate() {
    this._forceUpdate = true
    this._debouncedUpdate()
  }

  async _processUpdate() {
    const force = this._forceUpdate
    this._forceUpdate = false

    let newNode
    try {
      newNode = await this.bee.get(this.key, {
        keyEncoding: this.keyEncoding,
        valueEncoding: this.valueEncoding
      })
    } catch (e) {
      if (e.code === 'SNAPSHOT_NOT_AVAILABLE') {
        // There was a truncate event before the get resolved
        // So this handler will run again anyway
        return
      } else if (this.bee.closing) {
        this.close().catch(safetyCatch)
        return
      }
      this.emit('error', e)
      return
    }

    if (force || newNode?.seq !== this.node?.seq) {
      this.node = newNode
      this.emit('update')
    }
  }
}

class Watcher extends ReadyResource {
  constructor(bee, range, opts = {}) {
    super()

    this.keyEncoding = opts.keyEncoding || bee.keyEncoding
    this.valueEncoding = opts.valueEncoding || bee.valueEncoding
    this.index = bee._watchers.push(this) - 1
    this.bee = bee
    this.core = bee.core

    this.latestDiff = 0
    this.range = range
    this.map = opts.map || defaultWatchMap

    this.current = null
    this.previous = null
    this.currentMapped = null
    this.previousMapped = null
    this.stream = null

    this._lock = mutexify()
    this._flowing = false
    this._resolveOnChange = null
    this._differ = opts.differ || defaultDiffer
    this._eager = !!opts.eager
    this._onchange = opts.onchange || null

    this.on('newListener', autoFlowOnUpdate)

    this.ready().catch(safetyCatch)
  }

  async _consume() {
    if (this._flowing) return
    try {
      for await (const _ of this) {
      } // eslint-disable-line
    } catch {}
  }

  async _open() {
    await this.bee.ready()

    const opts = {
      keyEncoding: this.keyEncoding,
      valueEncoding: this.valueEncoding
    }

    // Point from which to start watching
    this.current = this._eager ? this.bee.checkout(1, opts) : this.bee.snapshot(opts)
    await this.current.ready()

    if (this._onchange) {
      if (this._eager) await this._onchange()
      this._consume()
    }
  }

  [Symbol.asyncIterator]() {
    this._flowing = true
    return this
  }

  _ontruncate() {
    this._onappend()
  }

  _onappend() {
    const resolve = this._resolveOnChange
    this._resolveOnChange = null
    if (resolve) resolve()
  }

  async _waitForChanges() {
    if (this.current.version < this.bee.version || this.closing) return

    await new Promise((resolve) => {
      this._resolveOnChange = resolve
    })
  }

  async next() {
    try {
      return await this._next()
    } catch (err) {
      if (this.closing) return { value: undefined, done: true }
      await this.close()
      throw err
    }
  }

  async _next() {
    const release = await this._lock()

    try {
      if (this.closing) return { value: undefined, done: true }

      if (!this.opened) await this.ready()

      while (true) {
        await this._waitForChanges()

        if (this.closing) return { value: undefined, done: true }

        await this._closePrevious()
        this.previous = this.current.snapshot()

        await this._closeCurrent()
        this.current = this.bee.snapshot({
          keyEncoding: this.keyEncoding,
          valueEncoding: this.valueEncoding
        })

        await this.current.ready()
        await this.previous.ready()

        if (this.current.core.fork !== this.previous.core.fork) {
          return await this._yield()
        }

        this.stream = this._differ(this.current, this.previous, this.range)

        try {
          for await (const data of this.stream) {
            // eslint-disable-line
            return await this._yield()
          }
        } finally {
          this.stream = null
        }
      }
    } finally {
      release()
    }
  }

  async _yield() {
    this.currentMapped = this.map(this.current)
    this.previousMapped = this.map(this.previous)

    if (this._onchange) {
      try {
        await this._onchange()
      } catch (err) {
        safetyCatch(err)
      }
    }

    this.emit('update')
    return { done: false, value: [this.currentMapped, this.previousMapped] }
  }

  async return() {
    await this.close()
    return { done: true }
  }

  async _close() {
    const top = this.bee._watchers.pop()
    if (top !== this) {
      top.index = this.index
      this.bee._watchers[top.index] = top
    }

    if (this.stream && !this.stream.destroying) {
      this.stream.destroy()
    }

    this._onappend() // Continue execution being closed

    await this._closeCurrent().catch(safetyCatch)
    await this._closePrevious().catch(safetyCatch)

    const release = await this._lock()
    release()
  }

  destroy() {
    return this.close()
  }

  async _closeCurrent() {
    if (this.currentMapped) await this.currentMapped.close()
    if (this.current) await this.current.close()
    this.current = this.currentMapped = null
  }

  async _closePrevious() {
    if (this.previousMapped) await this.previousMapped.close()
    if (this.previous) await this.previous.close()
    this.previous = this.previousMapped = null
  }
}

function autoFlowOnUpdate(name) {
  if (name === 'update') this._consume()
}

function defaultWatchMap(snapshot) {
  return snapshot
}

async function leafSize(node, goLeft) {
  while (node.children.length) node = await node.getChildNode(goLeft ? 0 : node.children.length - 1)
  return node.keys.length
}

async function setKeyToNearestLeaf(node, index, stack) {
  let [left, right] = await Promise.all([node.getChildNode(index), node.getChildNode(index + 1)])
  const [ls, rs] = await Promise.all([leafSize(left, false), leafSize(right, true)])

  if (ls < rs) {
    // if fewer leaves on the left
    stack.push(right)
    while (right.children.length) stack.push((right = right.children[0].value))
    node.keys[index] = right.keys.shift()
  } else {
    // if fewer leaves on the right
    stack.push(left)
    while (left.children.length) stack.push((left = left.children[left.children.length - 1].value))
    node.keys[index] = left.keys.pop()
  }
}

async function rebalance(stack) {
  const root = stack[0]

  while (stack.length > 1) {
    const node = stack.pop()
    const parent = stack[stack.length - 1]

    if (node.keys.length >= MIN_KEYS) return root

    let { left, index, right } = await node.siblings(parent)

    // maybe borrow from left sibling?
    if (left && left.keys.length > MIN_KEYS) {
      left.changed = true
      node.keys.unshift(parent.keys[index - 1])
      if (left.children.length) node.children.unshift(left.children.pop())
      parent.keys[index - 1] = left.keys.pop()
      return root
    }

    // maybe borrow from right sibling?
    if (right && right.keys.length > MIN_KEYS) {
      right.changed = true
      node.keys.push(parent.keys[index])
      if (right.children.length) node.children.push(right.children.shift())
      parent.keys[index] = right.keys.shift()
      return root
    }

    // merge node with another sibling
    if (left) {
      index--
      right = node
    } else {
      left = node
    }

    left.merge(right, parent.keys[index])
    parent.removeKey(index)
  }

  // check if the tree shrunk
  if (!root.keys.length && root.children.length) return root.getChildNode(0)
  return root
}

function iteratorToStream(ite, signal) {
  let done
  let closing

  const rs = new Readable({
    signal,
    open(cb) {
      done = cb
      ite.open().then(fin, fin)
    },
    read(cb) {
      done = cb
      ite.next().then(push, fin)
    },
    predestroy() {
      closing = ite.close()
      closing.catch(noop)
    },
    destroy(cb) {
      done = cb
      if (!closing) closing = ite.close()
      closing.then(fin, fin)
    }
  })

  return rs

  function fin(err) {
    done(err)
  }

  function push(val) {
    rs.push(val)
    done(null)
  }
}

async function iteratorPeek(ite) {
  try {
    await ite.open()
    return await ite.next()
  } finally {
    await ite.close()
  }
}

function encRange(e, opts) {
  if (!e) return opts

  if (e.encodeRange) {
    const r = e.encodeRange({
      gt: opts.gt,
      gte: opts.gte,
      lt: opts.lt,
      lte: opts.lte
    })
    opts.gt = r.gt
    opts.gte = r.gte
    opts.lt = r.lt
    opts.lte = r.lte
    return opts
  }

  if (opts.gt !== undefined) opts.gt = enc(e, opts.gt)
  if (opts.gte !== undefined) opts.gte = enc(e, opts.gte)
  if (opts.lt !== undefined) opts.lt = enc(e, opts.lt)
  if (opts.lte !== undefined) opts.lte = enc(e, opts.lte)
  if (opts.sub && !opts.gt && !opts.gte) opts.gt = enc(e, SEP)
  if (opts.sub && !opts.lt && !opts.lte) opts.lt = bump(enc(e, EMPTY))

  return opts
}

function bump(key) {
  // key should have been copied by enc above before hitting this
  key[key.length - 1]++
  return key
}

function enc(e, v) {
  if (v === undefined || v === null) return null
  if (e !== null) return e.encode(v)
  if (typeof v === 'string') return b4a.from(v)
  return v
}

function prefixEncoding(prefix, keyEncoding) {
  return {
    encode(key) {
      return b4a.concat([prefix, b4a.isBuffer(key) ? key : enc(keyEncoding, key)])
    },
    decode(key) {
      const sliced = key.slice(prefix.length, key.length)
      return keyEncoding ? keyEncoding.decode(sliced) : sliced
    }
  }
}

function copyEntry(entry) {
  let key = entry.key
  let value = entry.value
  let index = entry.index

  // key, value and index all refer to the same buffer (one hypercore block)
  // If together they are larger than half the buffer's byteLength,
  // this means that they got their own private slab (see Buffer.allocUnsafe docs)
  // so no need to unslab
  const size =
    key.byteLength +
    (value === null ? 0 : value.byteLength) +
    (index === null ? 0 : index.byteLength)
  if (2 * size < key.buffer.byteLength) {
    const [newKey, newValue, newIndex] = unslabAll([entry.key, entry.value, entry.index])
    key = newKey
    value = newValue
    index = newIndex
  }

  return {
    key,
    value,
    index,
    inflated: null
  }
}

function defaultDiffer(currentSnap, previousSnap, opts) {
  return currentSnap.createDiffStream(previousSnap, opts)
}

function toNull() {
  return null
}

function getBackingCore(core) {
  if (core.core) return core
  if (core.getBackingCore) return core.getBackingCore().session
  return null
}

function sameValue(a, b) {
  return a === b || (a !== null && b !== null && b4a.equals(a, b))
}

function noop() {}

function getExtension(db, opts) {
  if (opts.extension === false) return null
  if (opts.extension && opts.extension !== true) return opts.extension
  return Extension.register(db)
}

async function isLinked(batch, block) {
  const seq = block.seq
  block.inflate()

  const keys = [block.key]
  const wait = batch.options.wait

  for (const l of block.index.levels) {
    if (!l.keys.length) continue
    batch.options.wait = false
    try {
      keys.push(await batch.getKey(l.keys[0].seq))
    } catch {}
    batch.options.wait = wait
  }

  for (const k of keys) {
    if (await batch.links(k, seq)) return true
  }

  if (batch.core.closing) throw new Error('Core is closed')

  return false
}

module.exports = Hyperbee
const b4a = require('b4a')

class SubTree {
  constructor(node, parent) {
    this.node = node
    this.parent = parent

    this.isKey = node.children.length === 0
    this.i = this.isKey ? 1 : 0
    this.n = 0

    const child = this.isKey ? null : this.node.children[0]
    this.seq = child !== null ? child.seq : this.node.keys[0].seq
    this.offset = child !== null ? child.offset : 0
  }

  next() {
    this.i++
    this.isKey = (this.i & 1) === 1
    if (!this.isKey && !this.node.children.length) this.i++
    return this.update()
  }

  async bisect(key, incl) {
    let s = 0
    let e = this.node.keys.length
    let c

    while (s < e) {
      const mid = (s + e) >> 1
      c = cmp(key, await this.node.getKey(mid))

      if (c === 0) {
        if (incl) this.i = mid * 2 + 1
        else this.i = mid * 2 + (this.node.children.length ? 2 : 3)
        return true
      }

      if (c < 0) e = mid
      else s = mid + 1
    }

    const i = c < 0 ? e : s
    this.i = 2 * i + (this.node.children.length ? 0 : 1)
    return this.node.children.length === 0
  }

  update() {
    this.isKey = (this.i & 1) === 1
    this.n = this.i >> 1
    if (this.n >= (this.isKey ? this.node.keys.length : this.node.children.length)) return false
    const child = this.isKey ? null : this.node.children[this.n]
    this.seq = child !== null ? child.seq : this.node.keys[this.n].seq
    this.offset = child !== null ? child.offset : 0
    return true
  }

  async key() {
    return this.n < this.node.keys.length
      ? this.node.getKey(this.n)
      : this.parent && this.parent.key()
  }

  async compare(tree) {
    const [a, b] = await Promise.all([this.key(), tree.key()])
    return cmp(a, b)
  }
}

class TreeIterator {
  constructor(batch, opts) {
    this.batch = batch
    this.stack = []
    this.lt = opts.lt || opts.lte || null
    this.lte = !!opts.lte
    this.gt = opts.gt || opts.gte || null
    this.gte = !!opts.gte
    this.seeking = !!this.gt
    this.encoding = opts.encoding || batch.encoding
  }

  async open() {
    const node = await this.batch.getRoot(false)
    if (!node || !node.keys.length) return
    const tree = new SubTree(node, null)
    if (this.seeking && !(await this._seek(tree))) return
    this.stack.push(tree)
  }

  async _seek(tree) {
    const done = await tree.bisect(this.gt, this.gte)
    const oob = !tree.update()
    if (done || oob) {
      this.seeking = false
      if (oob) return false
    }
    return true
  }

  peek() {
    if (!this.stack.length) return null
    return this.stack[this.stack.length - 1]
  }

  skip() {
    if (!this.stack.length) return
    if (!this.stack[this.stack.length - 1].next()) this.stack.pop()
  }

  async nextKey() {
    let n = null
    while (this.stack.length && n === null) n = await this.next()
    if (n === null) return null
    if (!this.lt) return n.final(this.encoding)

    const c = cmp(n.key, this.lt)
    if (this.lte ? c <= 0 : c < 0) return n.final(this.encoding)
    this.stack = []
    return null
  }

  async next() {
    if (!this.stack.length) return null

    const top = this.stack[this.stack.length - 1]
    const { isKey, n, seq } = top

    if (!top.next()) {
      this.stack.pop()
    }

    if (isKey) {
      this.seeking = false
      return this.batch.getBlock(seq)
    }

    const child = await top.node.getChildNode(n)
    top.node.children[n] = null // unlink to save memory
    const tree = new SubTree(child, top)
    if (this.seeking && !(await this._seek(tree))) return null
    this.stack.push(tree)

    return null
  }

  close() {
    return this.batch._closeSnapshot()
  }
}

module.exports = class DiffIterator {
  constructor(left, right, opts = {}) {
    this.left = new TreeIterator(left, opts)
    this.right = new TreeIterator(right, opts)
    this.limit = typeof opts.limit === 'number' ? opts.limit : -1
  }

  async open() {
    await Promise.all([this.left.open(), this.right.open()])
  }

  async next() {
    if (this.limit === 0) return null
    const res = await this._next()
    if (!res || (res.left === null && res.right === null)) return null
    this.limit--
    return res
  }

  async _next() {
    const a = this.left
    const b = this.right

    while (true) {
      const [l, r] = await Promise.all([a.peek(), b.peek()])

      if (!l && !r) return null
      if (!l) return { left: null, right: await b.nextKey() }
      if (!r) return { left: await a.nextKey(), right: null }

      if (l.seq === r.seq && l.isKey === r.isKey && l.offset === r.offset) {
        a.skip()
        b.skip()
        continue
      }

      const c = await l.compare(r)

      if (l.isKey && !r.isKey) {
        await b.next()
        continue
      }

      if (!l.isKey && r.isKey) {
        await a.next()
        continue
      }

      if (l.isKey && r.isKey) {
        if (c === 0) return { left: await a.nextKey(), right: await b.nextKey() }
        if (c < 0) return { left: await a.nextKey(), right: null }
        return { left: null, right: await b.nextKey() }
      }

      if (c === 0) await Promise.all([a.next(), b.next()])
      else if (c < 0) await b.next()
      else await a.next()
    }
  }

  async close() {
    await Promise.all([this.left.close(), this.right.close()])
  }
}

function cmp(a, b) {
  if (!a) return b ? 1 : 0
  if (!b) return a ? -1 : 0
  return b4a.compare(a, b)
}
module.exports = class HistoryIterator {
  constructor(batch, opts = {}) {
    this.batch = batch
    this.options = opts
    this.live = !!opts.live
    this.gte = 0
    this.lt = 0
    this.reverse = !!opts.reverse
    this.limit = typeof opts.limit === 'number' ? opts.limit : -1
    this.encoding = opts.encoding || batch.encoding
    if (this.live && this.reverse) {
      throw new Error('Cannot have both live and reverse enabled')
    }
  }

  async open() {
    await this.batch.getRoot(false) // does the update dance
    this.gte = gte(this.options, this.batch.version)
    this.lt = this.live ? Infinity : lt(this.options, this.batch.version)
  }

  async next() {
    if (this.limit === 0) return null
    if (this.limit > 0) this.limit--

    if (this.gte >= this.lt) return null

    if (this.reverse) {
      if (this.lt <= 1) return null
      return final(await this.batch.getBlock(--this.lt), this.encoding)
    }

    return final(await this.batch.getBlock(this.gte++), this.encoding)
  }

  close() {
    return this.batch._closeSnapshot()
  }
}

function final(node, encoding) {
  const type = node.isDeletion() ? 'del' : 'put'
  return { type, ...node.final(encoding) }
}

function gte(opts, version) {
  if (opts.gt) return (opts.gt < 0 ? opts.gt + version : opts.gt) + 1
  const gte = opts.gte || opts.since || 1
  return gte < 0 ? gte + version : gte
}

function lt(opts, version) {
  if (opts.lte === 0 || opts.lt === 0 || opts.end === 0) return 0
  if (opts.lte) return (opts.lte < 0 ? opts.lte + version : opts.lte) + 1
  const lt = opts.lt || opts.end || version
  return lt < 0 ? lt + version : lt
}
module.exports = class LocalBlocksIterator {
  constructor(batch, opts = {}) {
    this.batch = batch
    this.options = opts
    this.gte = 0
    this.lt = 0
    this.limit = typeof opts.limit === 'number' ? opts.limit : -1
  }

  async open() {
    await this.batch.getRoot(false) // does the update dance
    this.gte = gte(this.options, this.batch.version)
    this.lt = lt(this.options, this.batch.version)
  }

  async next() {
    if (this.limit === 0) return null
    if (this.limit > 0) this.limit--

    while (this.gte < this.lt) {
      try {
        return await this.batch.getBlock(this.gte++)
      } catch {
        continue
      }
    }

    return null
  }

  close() {
    return this.batch._closeSnapshot()
  }
}

function gte(opts, version) {
  if (opts.gt) return (opts.gt < 0 ? opts.gt + version : opts.gt) + 1
  const gte = opts.gte || opts.since || 1
  return gte < 0 ? gte + version : gte
}

function lt(opts, version) {
  if (opts.lte === 0 || opts.lt === 0 || opts.end === 0) return 0
  if (opts.lte) return (opts.lte < 0 ? opts.lte + version : opts.lte) + 1
  const lt = opts.lt || opts.end || version
  return lt < 0 ? lt + version : lt
}
const b4a = require('b4a')

module.exports = class RangeIterator {
  constructor(batch, encoding, opts = {}) {
    this.batch = batch
    this.stack = []
    this.opened = false
    this.encoding = encoding || batch.encoding

    this._limit = typeof opts.limit === 'number' ? opts.limit : -1
    this._gIncl = !opts.gt
    this._gKey = opts.gt || opts.gte || null
    this._lIncl = !opts.lt
    this._lKey = opts.lt || opts.lte || null
    this._reverse = !!opts.reverse
    this._version = 0
    this._checkpoint = opts.checkpoint && opts.checkpoint.length ? opts.checkpoint : null
    this._nexting = false
    this._closed = false
  }

  snapshot(version = this.batch.version) {
    const checkpoint = []
    for (const s of this.stack) {
      let { node, i } = s
      if (this._nexting && s === this.stack[this.stack.length - 1]) {
        i = this._reverse ? i + 1 : i - 1
      }
      if (!node.block) continue
      if (i < 0) continue
      checkpoint.push(node.block.seq, node.offset, i)
    }

    return {
      version,
      gte: this._gIncl ? this._gKey : null,
      gt: this._gIncl ? null : this._gKey,
      lte: this._lIncl ? this._lKey : null,
      lt: this._lIncl ? null : this._lKey,
      limit: this._limit,
      reverse: this._reverse,
      ended: this.opened && !checkpoint.length,
      checkpoint: this.opened ? checkpoint : []
    }
  }

  async open() {
    await this._open()
    this.opened = true
  }

  async _open() {
    if (this._checkpoint) {
      for (let j = 0; j < this._checkpoint.length; j += 3) {
        const seq = this._checkpoint[j]
        const offset = this._checkpoint[j + 1]
        const i = this._checkpoint[j + 2]
        this.stack.push({
          node: (await this.batch.getBlock(seq)).getTreeNode(offset),
          i
        })
      }
      return
    }

    this._nexting = true

    let node = await this.batch.getRoot(false)
    if (!node) {
      this._nexting = false
      return
    }

    const incl = this._reverse ? this._lIncl : this._gIncl
    const start = this._reverse ? this._lKey : this._gKey

    if (!start) {
      this.stack.push({ node, i: this._reverse ? node.keys.length << 1 : 0 })
      this._nexting = false
      this._preloadQuery()
      return
    }

    while (true) {
      const entry = { node, i: this._reverse ? node.keys.length << 1 : 0 }

      let s = 0
      let e = node.keys.length
      let c

      while (s < e) {
        const mid = (s + e) >> 1
        c = b4a.compare(start, await node.getKey(mid))

        if (c === 0) {
          if (incl) entry.i = mid * 2 + 1
          else entry.i = mid * 2 + (this._reverse ? 0 : 2)
          this.stack.push(entry)
          this._nexting = false
          this._preloadQuery()
          return
        }

        if (c < 0) e = mid
        else s = mid + 1
      }

      const i = c < 0 ? e : s
      entry.i = 2 * i + (this._reverse ? -1 : 1)

      if (entry.i >= 0 && entry.i <= node.keys.length << 1) this.stack.push(entry)
      if (!node.children.length) {
        this._nexting = false
        this._preloadQuery()
        return
      }

      node = await node.getChildNode(i)
    }
  }

  _preloadQuery() {
    const max = { nodes: 0, max: 2048 }

    if (this._limit === -1 && !this._reverse && this.stack.length) {
      for (const s of this.stack) {
        const k = (s.i - (s.i & 1)) / 2
        this._preload(s.node, k + 1, this._lKey, max).catch(noop)
      }
    }
  }

  async _preload(node, i, end, max) {
    for (; i < node.keys.length; i++) {
      const key = node.keys[i]
      const block = await this.batch.getBlock(key.seq)
      if (this._closed) return
      const c = end ? b4a.compare(block.key, end) : -1
      if (c >= 0 || max.nodes >= max.max || i >= node.children.length) return
      max.nodes++
      const next = await node.getChildNode(i)
      if (this._closed) return
      this._preload(next, 0, end, max).catch(noop)
    }

    if (node.children.length && max.nodes < max.max) {
      const next = await node.getChildNode(node.children.length - 1)
      if (this._closed) return
      this._preload(next, 0, end, max).catch(noop)
    }
  }

  async next() {
    // TODO: this nexting flag is only needed if someone asks for a snapshot during
    // a lookup (ie the extension, pretty important...).
    // A better solution would be to refactor this so top.i is incremented eagerly
    // to get the current block instead of the way it is done now (++i vs i++)
    this._nexting = true

    const end = this._reverse ? this._gKey : this._lKey
    const incl = this._reverse ? this._gIncl : this._lIncl

    while (this.stack.length && (this._limit === -1 || this._limit > 0)) {
      const top = this.stack[this.stack.length - 1]
      const isKey = (top.i & 1) === 1
      const n = this._reverse ? (top.i < 0 ? top.node.keys.length : top.i-- >> 1) : top.i++ >> 1

      if (!isKey) {
        if (!top.node.children.length) continue
        const node = await top.node.getChildNode(n)
        if (top.node.block.seq < this.batch.core.length) {
          top.node.children[n].value = null // unlink it to save memory
        }
        this.stack.push({ i: this._reverse ? node.keys.length << 1 : 0, node })
        continue
      }

      if (n >= top.node.keys.length) {
        this.stack.pop()
        continue
      }

      const key = top.node.keys[n]
      const block = await this.batch.getBlock(key.seq)
      if (end) {
        const c = b4a.compare(block.key, end)
        if (c === 0 ? !incl : this._reverse ? c < 0 : c > 0) {
          this._limit = 0
          break
        }
      }
      if (this._limit > 0) this._limit--
      this._nexting = false
      return block.final(this.encoding)
    }

    this._nexting = false
    return null
  }

  close() {
    this._closed = true
    return this.batch._closeSnapshot()
  }
}

function noop() {}
const { Extension } = require('./messages')

// const MAX_ACTIVE = 32
const FLUSH_BATCH = 128
const MAX_PASSIVE_BATCH = 2048
const MAX_ACTIVE_BATCH = MAX_PASSIVE_BATCH + FLUSH_BATCH

class Batch {
  constructor(outgoing, from) {
    this.blocks = []
    this.start = 0
    this.end = 0
    this.outgoing = outgoing
    this.from = from
  }

  push(seq) {
    const len = this.blocks.push(seq)
    if (len === 1 || seq < this.start) this.start = seq
    if (len === 1 || seq >= this.end) this.end = seq + 1
    if (len >= FLUSH_BATCH) {
      this.send()
      this.clear()
    }
  }

  send() {
    if (!this.blocks.length) return
    this.outgoing.send(
      Extension.encode({
        cache: { blocks: this.blocks, start: this.start, end: this.end }
      }),
      this.from
    )
  }

  clear() {
    this.start = this.end = 0
    this.blocks = []
  }
}

class HyperbeeExtension {
  constructor(db) {
    this.encoding = null
    this.outgoing = null
    this.db = db
    this.active = 0
  }

  get(version, key) {
    this.outgoing.broadcast(Extension.encode({ get: { version, key } }))
  }

  iterator(snapshot) {
    if (snapshot.ended) return
    if (snapshot.limit === 0) return
    if (snapshot.limit === -1) snapshot.limit = 0
    this.outgoing.broadcast(Extension.encode({ iterator: snapshot }))
  }

  onmessage(buf, from) {
    // TODO: handle max active extension messages
    // this.active++

    const message = decode(buf)
    if (!message) return

    if (message.cache) this.oncache(message.cache, from)
    if (message.get) this.onget(message.get, from)
    if (message.iterator) this.oniterator(message.iterator, from)
  }

  oncache(message, from) {
    if (!message.blocks.length) return
    this.db.core.download(message)
  }

  onget(message, from) {
    if (!message.version || message.version > this.db.version) return

    const b = new Batch(this.outgoing, from)
    const db = this.db.checkout(message.version)

    db.get(message.key, {
      extension: false,
      wait: false,
      update: false,
      onseq
    }).then(done, done)

    function done() {
      db.close().catch(noop)
      b.send()
    }

    function onseq(seq) {
      b.push(seq)
    }
  }

  async oniterator(message, from) {
    if (!message.version || message.version > this.db.version) return

    const b = new Batch(this.outgoing, from)
    const seqs = new Set()

    let skip = message.checkpoint.length
    let work = 0

    const db = this.db.checkout(message.version)
    const ite = db.createRangeIterator({
      ...message,
      wait: false,
      extension: false,
      update: false,
      limit: message.limit === 0 ? -1 : message.limit,
      onseq(seq) {
        if (skip && skip--) return
        if (seqs.has(seq)) return
        work++
        seqs.add(seq)
        b.push(seq)
      }
    })

    try {
      await ite.open()
      // eslint-disable-next-line no-unmodified-loop-condition
      while (work < MAX_ACTIVE_BATCH) {
        if (!(await ite.next())) break
      }
    } catch (_) {
      // do nothing
    } finally {
      ite.close().catch(noop)
      db.close().catch(noop)
      b.send()
    }
  }

  static register(db) {
    const e = new this(db)
    e.outgoing = db.core.registerExtension('hyperbee', e)
    return e
  }
}

HyperbeeExtension.BATCH_SIZE = MAX_PASSIVE_BATCH

module.exports = HyperbeeExtension

function decode(buf) {
  try {
    return Extension.decode(buf)
  } catch (err) {
    return null
  }
}

function noop() {}
// This file is auto generated by the protocol-buffers compiler

/* eslint-disable quotes */
/* eslint-disable indent */
/* eslint-disable no-redeclare */
/* eslint-disable camelcase */
/* eslint-disable no-var */

// Remember to `npm install --save protocol-buffers-encodings`
var encodings = require('protocol-buffers-encodings')
var b4a = require('b4a')
var varint = encodings.varint
var skip = encodings.skip

var YoloIndex = exports.YoloIndex = {
  buffer: true,
  encodingLength: null,
  encode: null,
  decode: null
}

var Header = exports.Header = {
  buffer: true,
  encodingLength: null,
  encode: null,
  decode: null
}

var Node = exports.Node = {
  buffer: true,
  encodingLength: null,
  encode: null,
  decode: null
}

var Extension = exports.Extension = {
  buffer: true,
  encodingLength: null,
  encode: null,
  decode: null
}

defineYoloIndex()
defineHeader()
defineNode()
defineExtension()

function defineYoloIndex () {
  var Level = YoloIndex.Level = {
    buffer: true,
    encodingLength: null,
    encode: null,
    decode: null
  }

  defineLevel()

  function defineLevel () {
    Level.encodingLength = encodingLength
    Level.encode = encode
    Level.decode = decode

    function encodingLength (obj) {
      var length = 0
      if (defined(obj.keys)) {
        var packedLen = 0
        for (var i = 0; i < obj.keys.length; i++) {
          if (!defined(obj.keys[i])) continue
          var len = encodings.varint.encodingLength(obj.keys[i])
          packedLen += len
        }
        if (packedLen) {
          length += 1 + packedLen + varint.encodingLength(packedLen)
        }
      }
      if (defined(obj.children)) {
        var packedLen = 0
        for (var i = 0; i < obj.children.length; i++) {
          if (!defined(obj.children[i])) continue
          var len = encodings.varint.encodingLength(obj.children[i])
          packedLen += len
        }
        if (packedLen) {
          length += 1 + packedLen + varint.encodingLength(packedLen)
        }
      }
      return length
    }

    function encode (obj, buf, offset) {
      if (!offset) offset = 0
      if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
      var oldOffset = offset
      if (defined(obj.keys)) {
        var packedLen = 0
        for (var i = 0; i < obj.keys.length; i++) {
          if (!defined(obj.keys[i])) continue
          packedLen += encodings.varint.encodingLength(obj.keys[i])
        }
        if (packedLen) {
          buf[offset++] = 10
          varint.encode(packedLen, buf, offset)
          offset += varint.encode.bytes
        }
        for (var i = 0; i < obj.keys.length; i++) {
          if (!defined(obj.keys[i])) continue
          encodings.varint.encode(obj.keys[i], buf, offset)
          offset += encodings.varint.encode.bytes
        }
      }
      if (defined(obj.children)) {
        var packedLen = 0
        for (var i = 0; i < obj.children.length; i++) {
          if (!defined(obj.children[i])) continue
          packedLen += encodings.varint.encodingLength(obj.children[i])
        }
        if (packedLen) {
          buf[offset++] = 18
          varint.encode(packedLen, buf, offset)
          offset += varint.encode.bytes
        }
        for (var i = 0; i < obj.children.length; i++) {
          if (!defined(obj.children[i])) continue
          encodings.varint.encode(obj.children[i], buf, offset)
          offset += encodings.varint.encode.bytes
        }
      }
      encode.bytes = offset - oldOffset
      return buf
    }

    function decode (buf, offset, end) {
      if (!offset) offset = 0
      if (!end) end = buf.length
      if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
      var oldOffset = offset
      var obj = {
        keys: [],
        children: []
      }
      while (true) {
        if (end <= offset) {
          decode.bytes = offset - oldOffset
          return obj
        }
        var prefix = varint.decode(buf, offset)
        offset += varint.decode.bytes
        var tag = prefix >> 3
        switch (tag) {
          case 1:
          var packedEnd = varint.decode(buf, offset)
          offset += varint.decode.bytes
          packedEnd += offset
          while (offset < packedEnd) {
            obj.keys.push(encodings.varint.decode(buf, offset))
            offset += encodings.varint.decode.bytes
          }
          break
          case 2:
          var packedEnd = varint.decode(buf, offset)
          offset += varint.decode.bytes
          packedEnd += offset
          while (offset < packedEnd) {
            obj.children.push(encodings.varint.decode(buf, offset))
            offset += encodings.varint.decode.bytes
          }
          break
          default:
          offset = skip(prefix & 7, buf, offset)
        }
      }
    }
  }

  YoloIndex.encodingLength = encodingLength
  YoloIndex.encode = encode
  YoloIndex.decode = decode

  function encodingLength (obj) {
    var length = 0
    if (defined(obj.levels)) {
      for (var i = 0; i < obj.levels.length; i++) {
        if (!defined(obj.levels[i])) continue
        var len = Level.encodingLength(obj.levels[i])
        length += varint.encodingLength(len)
        length += 1 + len
      }
    }
    return length
  }

  function encode (obj, buf, offset) {
    if (!offset) offset = 0
    if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
    var oldOffset = offset
    if (defined(obj.levels)) {
      for (var i = 0; i < obj.levels.length; i++) {
        if (!defined(obj.levels[i])) continue
        buf[offset++] = 10
        varint.encode(Level.encodingLength(obj.levels[i]), buf, offset)
        offset += varint.encode.bytes
        Level.encode(obj.levels[i], buf, offset)
        offset += Level.encode.bytes
      }
    }
    encode.bytes = offset - oldOffset
    return buf
  }

  function decode (buf, offset, end) {
    if (!offset) offset = 0
    if (!end) end = buf.length
    if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
    var oldOffset = offset
    var obj = {
      levels: []
    }
    while (true) {
      if (end <= offset) {
        decode.bytes = offset - oldOffset
        return obj
      }
      var prefix = varint.decode(buf, offset)
      offset += varint.decode.bytes
      var tag = prefix >> 3
      switch (tag) {
        case 1:
        var len = varint.decode(buf, offset)
        offset += varint.decode.bytes
        obj.levels.push(Level.decode(buf, offset, offset + len))
        offset += Level.decode.bytes
        break
        default:
        offset = skip(prefix & 7, buf, offset)
      }
    }
  }
}

function defineHeader () {
  var Metadata = Header.Metadata = {
    buffer: true,
    encodingLength: null,
    encode: null,
    decode: null
  }

  defineMetadata()

  function defineMetadata () {
    Metadata.encodingLength = encodingLength
    Metadata.encode = encode
    Metadata.decode = decode

    function encodingLength (obj) {
      var length = 0
      if (defined(obj.contentFeed)) {
        var len = encodings.bytes.encodingLength(obj.contentFeed)
        length += 1 + len
      }
      if (defined(obj.userData)) {
        var len = encodings.bytes.encodingLength(obj.userData)
        length += 1 + len
      }
      return length
    }

    function encode (obj, buf, offset) {
      if (!offset) offset = 0
      if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
      var oldOffset = offset
      if (defined(obj.contentFeed)) {
        buf[offset++] = 10
        encodings.bytes.encode(obj.contentFeed, buf, offset)
        offset += encodings.bytes.encode.bytes
      }
      if (defined(obj.userData)) {
        buf[offset++] = 18
        encodings.bytes.encode(obj.userData, buf, offset)
        offset += encodings.bytes.encode.bytes
      }
      encode.bytes = offset - oldOffset
      return buf
    }

    function decode (buf, offset, end) {
      if (!offset) offset = 0
      if (!end) end = buf.length
      if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
      var oldOffset = offset
      var obj = {
        contentFeed: null,
        userData: null
      }
      while (true) {
        if (end <= offset) {
          decode.bytes = offset - oldOffset
          return obj
        }
        var prefix = varint.decode(buf, offset)
        offset += varint.decode.bytes
        var tag = prefix >> 3
        switch (tag) {
          case 1:
          obj.contentFeed = encodings.bytes.decode(buf, offset)
          offset += encodings.bytes.decode.bytes
          break
          case 2:
          obj.userData = encodings.bytes.decode(buf, offset)
          offset += encodings.bytes.decode.bytes
          break
          default:
          offset = skip(prefix & 7, buf, offset)
        }
      }
    }
  }

  Header.encodingLength = encodingLength
  Header.encode = encode
  Header.decode = decode

  function encodingLength (obj) {
    var length = 0
    if (!defined(obj.protocol)) throw new Error("protocol is required")
    var len = encodings.string.encodingLength(obj.protocol)
    length += 1 + len
    if (defined(obj.metadata)) {
      var len = Metadata.encodingLength(obj.metadata)
      length += varint.encodingLength(len)
      length += 1 + len
    }
    return length
  }

  function encode (obj, buf, offset) {
    if (!offset) offset = 0
    if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
    var oldOffset = offset
    if (!defined(obj.protocol)) throw new Error("protocol is required")
    buf[offset++] = 10
    encodings.string.encode(obj.protocol, buf, offset)
    offset += encodings.string.encode.bytes
    if (defined(obj.metadata)) {
      buf[offset++] = 18
      varint.encode(Metadata.encodingLength(obj.metadata), buf, offset)
      offset += varint.encode.bytes
      Metadata.encode(obj.metadata, buf, offset)
      offset += Metadata.encode.bytes
    }
    encode.bytes = offset - oldOffset
    return buf
  }

  function decode (buf, offset, end) {
    if (!offset) offset = 0
    if (!end) end = buf.length
    if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
    var oldOffset = offset
    var obj = {
      protocol: "",
      metadata: null
    }
    var found0 = false
    while (true) {
      if (end <= offset) {
        if (!found0) throw new Error("Decoded message is not valid")
        decode.bytes = offset - oldOffset
        return obj
      }
      var prefix = varint.decode(buf, offset)
      offset += varint.decode.bytes
      var tag = prefix >> 3
      switch (tag) {
        case 1:
        obj.protocol = encodings.string.decode(buf, offset)
        offset += encodings.string.decode.bytes
        found0 = true
        break
        case 2:
        var len = varint.decode(buf, offset)
        offset += varint.decode.bytes
        obj.metadata = Metadata.decode(buf, offset, offset + len)
        offset += Metadata.decode.bytes
        break
        default:
        offset = skip(prefix & 7, buf, offset)
      }
    }
  }
}

function defineNode () {
  Node.encodingLength = encodingLength
  Node.encode = encode
  Node.decode = decode

  function encodingLength (obj) {
    var length = 0
    if (!defined(obj.index)) throw new Error("index is required")
    var len = encodings.bytes.encodingLength(obj.index)
    length += 1 + len
    if (!defined(obj.key)) throw new Error("key is required")
    var len = encodings.bytes.encodingLength(obj.key)
    length += 1 + len
    if (defined(obj.value)) {
      var len = encodings.bytes.encodingLength(obj.value)
      length += 1 + len
    }
    return length
  }

  function encode (obj, buf, offset) {
    if (!offset) offset = 0
    if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
    var oldOffset = offset
    if (!defined(obj.index)) throw new Error("index is required")
    buf[offset++] = 10
    encodings.bytes.encode(obj.index, buf, offset)
    offset += encodings.bytes.encode.bytes
    if (!defined(obj.key)) throw new Error("key is required")
    buf[offset++] = 18
    encodings.bytes.encode(obj.key, buf, offset)
    offset += encodings.bytes.encode.bytes
    if (defined(obj.value)) {
      buf[offset++] = 26
      encodings.bytes.encode(obj.value, buf, offset)
      offset += encodings.bytes.encode.bytes
    }
    encode.bytes = offset - oldOffset
    return buf
  }

  function decode (buf, offset, end) {
    if (!offset) offset = 0
    if (!end) end = buf.length
    if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
    var oldOffset = offset
    var obj = {
      index: null,
      key: null,
      value: null
    }
    var found0 = false
    var found1 = false
    while (true) {
      if (end <= offset) {
        if (!found0 || !found1) throw new Error("Decoded message is not valid")
        decode.bytes = offset - oldOffset
        return obj
      }
      var prefix = varint.decode(buf, offset)
      offset += varint.decode.bytes
      var tag = prefix >> 3
      switch (tag) {
        case 1:
        obj.index = encodings.bytes.decode(buf, offset)
        offset += encodings.bytes.decode.bytes
        found0 = true
        break
        case 2:
        obj.key = encodings.bytes.decode(buf, offset)
        offset += encodings.bytes.decode.bytes
        found1 = true
        break
        case 3:
        obj.value = encodings.bytes.decode(buf, offset)
        offset += encodings.bytes.decode.bytes
        break
        default:
        offset = skip(prefix & 7, buf, offset)
      }
    }
  }
}

function defineExtension () {
  var Get = Extension.Get = {
    buffer: true,
    encodingLength: null,
    encode: null,
    decode: null
  }

  var Iterator = Extension.Iterator = {
    buffer: true,
    encodingLength: null,
    encode: null,
    decode: null
  }

  var Cache = Extension.Cache = {
    buffer: true,
    encodingLength: null,
    encode: null,
    decode: null
  }

  defineGet()
  defineIterator()
  defineCache()

  function defineGet () {
    Get.encodingLength = encodingLength
    Get.encode = encode
    Get.decode = decode

    function encodingLength (obj) {
      var length = 0
      if (defined(obj.version)) {
        var len = encodings.varint.encodingLength(obj.version)
        length += 1 + len
      }
      if (defined(obj.key)) {
        var len = encodings.bytes.encodingLength(obj.key)
        length += 1 + len
      }
      return length
    }

    function encode (obj, buf, offset) {
      if (!offset) offset = 0
      if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
      var oldOffset = offset
      if (defined(obj.version)) {
        buf[offset++] = 8
        encodings.varint.encode(obj.version, buf, offset)
        offset += encodings.varint.encode.bytes
      }
      if (defined(obj.key)) {
        buf[offset++] = 18
        encodings.bytes.encode(obj.key, buf, offset)
        offset += encodings.bytes.encode.bytes
      }
      encode.bytes = offset - oldOffset
      return buf
    }

    function decode (buf, offset, end) {
      if (!offset) offset = 0
      if (!end) end = buf.length
      if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
      var oldOffset = offset
      var obj = {
        version: 0,
        key: null
      }
      while (true) {
        if (end <= offset) {
          decode.bytes = offset - oldOffset
          return obj
        }
        var prefix = varint.decode(buf, offset)
        offset += varint.decode.bytes
        var tag = prefix >> 3
        switch (tag) {
          case 1:
          obj.version = encodings.varint.decode(buf, offset)
          offset += encodings.varint.decode.bytes
          break
          case 2:
          obj.key = encodings.bytes.decode(buf, offset)
          offset += encodings.bytes.decode.bytes
          break
          default:
          offset = skip(prefix & 7, buf, offset)
        }
      }
    }
  }

  function defineIterator () {
    Iterator.encodingLength = encodingLength
    Iterator.encode = encode
    Iterator.decode = decode

    function encodingLength (obj) {
      var length = 0
      if (defined(obj.version)) {
        var len = encodings.varint.encodingLength(obj.version)
        length += 1 + len
      }
      if (defined(obj.gte)) {
        var len = encodings.bytes.encodingLength(obj.gte)
        length += 1 + len
      }
      if (defined(obj.gt)) {
        var len = encodings.bytes.encodingLength(obj.gt)
        length += 1 + len
      }
      if (defined(obj.lte)) {
        var len = encodings.bytes.encodingLength(obj.lte)
        length += 1 + len
      }
      if (defined(obj.lt)) {
        var len = encodings.bytes.encodingLength(obj.lt)
        length += 1 + len
      }
      if (defined(obj.limit)) {
        var len = encodings.varint.encodingLength(obj.limit)
        length += 1 + len
      }
      if (defined(obj.reverse)) {
        var len = encodings.bool.encodingLength(obj.reverse)
        length += 1 + len
      }
      if (defined(obj.checkpoint)) {
        var packedLen = 0
        for (var i = 0; i < obj.checkpoint.length; i++) {
          if (!defined(obj.checkpoint[i])) continue
          var len = encodings.varint.encodingLength(obj.checkpoint[i])
          packedLen += len
        }
        if (packedLen) {
          length += 1 + packedLen + varint.encodingLength(packedLen)
        }
      }
      return length
    }

    function encode (obj, buf, offset) {
      if (!offset) offset = 0
      if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
      var oldOffset = offset
      if (defined(obj.version)) {
        buf[offset++] = 8
        encodings.varint.encode(obj.version, buf, offset)
        offset += encodings.varint.encode.bytes
      }
      if (defined(obj.gte)) {
        buf[offset++] = 18
        encodings.bytes.encode(obj.gte, buf, offset)
        offset += encodings.bytes.encode.bytes
      }
      if (defined(obj.gt)) {
        buf[offset++] = 26
        encodings.bytes.encode(obj.gt, buf, offset)
        offset += encodings.bytes.encode.bytes
      }
      if (defined(obj.lte)) {
        buf[offset++] = 34
        encodings.bytes.encode(obj.lte, buf, offset)
        offset += encodings.bytes.encode.bytes
      }
      if (defined(obj.lt)) {
        buf[offset++] = 42
        encodings.bytes.encode(obj.lt, buf, offset)
        offset += encodings.bytes.encode.bytes
      }
      if (defined(obj.limit)) {
        buf[offset++] = 48
        encodings.varint.encode(obj.limit, buf, offset)
        offset += encodings.varint.encode.bytes
      }
      if (defined(obj.reverse)) {
        buf[offset++] = 56
        encodings.bool.encode(obj.reverse, buf, offset)
        offset += encodings.bool.encode.bytes
      }
      if (defined(obj.checkpoint)) {
        var packedLen = 0
        for (var i = 0; i < obj.checkpoint.length; i++) {
          if (!defined(obj.checkpoint[i])) continue
          packedLen += encodings.varint.encodingLength(obj.checkpoint[i])
        }
        if (packedLen) {
          buf[offset++] = 66
          varint.encode(packedLen, buf, offset)
          offset += varint.encode.bytes
        }
        for (var i = 0; i < obj.checkpoint.length; i++) {
          if (!defined(obj.checkpoint[i])) continue
          encodings.varint.encode(obj.checkpoint[i], buf, offset)
          offset += encodings.varint.encode.bytes
        }
      }
      encode.bytes = offset - oldOffset
      return buf
    }

    function decode (buf, offset, end) {
      if (!offset) offset = 0
      if (!end) end = buf.length
      if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
      var oldOffset = offset
      var obj = {
        version: 0,
        gte: null,
        gt: null,
        lte: null,
        lt: null,
        limit: 0,
        reverse: false,
        checkpoint: []
      }
      while (true) {
        if (end <= offset) {
          decode.bytes = offset - oldOffset
          return obj
        }
        var prefix = varint.decode(buf, offset)
        offset += varint.decode.bytes
        var tag = prefix >> 3
        switch (tag) {
          case 1:
          obj.version = encodings.varint.decode(buf, offset)
          offset += encodings.varint.decode.bytes
          break
          case 2:
          obj.gte = encodings.bytes.decode(buf, offset)
          offset += encodings.bytes.decode.bytes
          break
          case 3:
          obj.gt = encodings.bytes.decode(buf, offset)
          offset += encodings.bytes.decode.bytes
          break
          case 4:
          obj.lte = encodings.bytes.decode(buf, offset)
          offset += encodings.bytes.decode.bytes
          break
          case 5:
          obj.lt = encodings.bytes.decode(buf, offset)
          offset += encodings.bytes.decode.bytes
          break
          case 6:
          obj.limit = encodings.varint.decode(buf, offset)
          offset += encodings.varint.decode.bytes
          break
          case 7:
          obj.reverse = encodings.bool.decode(buf, offset)
          offset += encodings.bool.decode.bytes
          break
          case 8:
          var packedEnd = varint.decode(buf, offset)
          offset += varint.decode.bytes
          packedEnd += offset
          while (offset < packedEnd) {
            obj.checkpoint.push(encodings.varint.decode(buf, offset))
            offset += encodings.varint.decode.bytes
          }
          break
          default:
          offset = skip(prefix & 7, buf, offset)
        }
      }
    }
  }

  function defineCache () {
    Cache.encodingLength = encodingLength
    Cache.encode = encode
    Cache.decode = decode

    function encodingLength (obj) {
      var length = 0
      if (!defined(obj.start)) throw new Error("start is required")
      var len = encodings.varint.encodingLength(obj.start)
      length += 1 + len
      if (!defined(obj.end)) throw new Error("end is required")
      var len = encodings.varint.encodingLength(obj.end)
      length += 1 + len
      if (defined(obj.blocks)) {
        var packedLen = 0
        for (var i = 0; i < obj.blocks.length; i++) {
          if (!defined(obj.blocks[i])) continue
          var len = encodings.varint.encodingLength(obj.blocks[i])
          packedLen += len
        }
        if (packedLen) {
          length += 1 + packedLen + varint.encodingLength(packedLen)
        }
      }
      return length
    }

    function encode (obj, buf, offset) {
      if (!offset) offset = 0
      if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
      var oldOffset = offset
      if (!defined(obj.start)) throw new Error("start is required")
      buf[offset++] = 8
      encodings.varint.encode(obj.start, buf, offset)
      offset += encodings.varint.encode.bytes
      if (!defined(obj.end)) throw new Error("end is required")
      buf[offset++] = 16
      encodings.varint.encode(obj.end, buf, offset)
      offset += encodings.varint.encode.bytes
      if (defined(obj.blocks)) {
        var packedLen = 0
        for (var i = 0; i < obj.blocks.length; i++) {
          if (!defined(obj.blocks[i])) continue
          packedLen += encodings.varint.encodingLength(obj.blocks[i])
        }
        if (packedLen) {
          buf[offset++] = 26
          varint.encode(packedLen, buf, offset)
          offset += varint.encode.bytes
        }
        for (var i = 0; i < obj.blocks.length; i++) {
          if (!defined(obj.blocks[i])) continue
          encodings.varint.encode(obj.blocks[i], buf, offset)
          offset += encodings.varint.encode.bytes
        }
      }
      encode.bytes = offset - oldOffset
      return buf
    }

    function decode (buf, offset, end) {
      if (!offset) offset = 0
      if (!end) end = buf.length
      if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
      var oldOffset = offset
      var obj = {
        start: 0,
        end: 0,
        blocks: []
      }
      var found0 = false
      var found1 = false
      while (true) {
        if (end <= offset) {
          if (!found0 || !found1) throw new Error("Decoded message is not valid")
          decode.bytes = offset - oldOffset
          return obj
        }
        var prefix = varint.decode(buf, offset)
        offset += varint.decode.bytes
        var tag = prefix >> 3
        switch (tag) {
          case 1:
          obj.start = encodings.varint.decode(buf, offset)
          offset += encodings.varint.decode.bytes
          found0 = true
          break
          case 2:
          obj.end = encodings.varint.decode(buf, offset)
          offset += encodings.varint.decode.bytes
          found1 = true
          break
          case 3:
          var packedEnd = varint.decode(buf, offset)
          offset += varint.decode.bytes
          packedEnd += offset
          while (offset < packedEnd) {
            obj.blocks.push(encodings.varint.decode(buf, offset))
            offset += encodings.varint.decode.bytes
          }
          break
          default:
          offset = skip(prefix & 7, buf, offset)
        }
      }
    }
  }

  Extension.encodingLength = encodingLength
  Extension.encode = encode
  Extension.decode = decode

  function encodingLength (obj) {
    var length = 0
    if (defined(obj.cache)) {
      var len = Cache.encodingLength(obj.cache)
      length += varint.encodingLength(len)
      length += 1 + len
    }
    if (defined(obj.get)) {
      var len = Get.encodingLength(obj.get)
      length += varint.encodingLength(len)
      length += 1 + len
    }
    if (defined(obj.iterator)) {
      var len = Iterator.encodingLength(obj.iterator)
      length += varint.encodingLength(len)
      length += 1 + len
    }
    return length
  }

  function encode (obj, buf, offset) {
    if (!offset) offset = 0
    if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
    var oldOffset = offset
    if (defined(obj.cache)) {
      buf[offset++] = 10
      varint.encode(Cache.encodingLength(obj.cache), buf, offset)
      offset += varint.encode.bytes
      Cache.encode(obj.cache, buf, offset)
      offset += Cache.encode.bytes
    }
    if (defined(obj.get)) {
      buf[offset++] = 18
      varint.encode(Get.encodingLength(obj.get), buf, offset)
      offset += varint.encode.bytes
      Get.encode(obj.get, buf, offset)
      offset += Get.encode.bytes
    }
    if (defined(obj.iterator)) {
      buf[offset++] = 26
      varint.encode(Iterator.encodingLength(obj.iterator), buf, offset)
      offset += varint.encode.bytes
      Iterator.encode(obj.iterator, buf, offset)
      offset += Iterator.encode.bytes
    }
    encode.bytes = offset - oldOffset
    return buf
  }

  function decode (buf, offset, end) {
    if (!offset) offset = 0
    if (!end) end = buf.length
    if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
    var oldOffset = offset
    var obj = {
      cache: null,
      get: null,
      iterator: null
    }
    while (true) {
      if (end <= offset) {
        decode.bytes = offset - oldOffset
        return obj
      }
      var prefix = varint.decode(buf, offset)
      offset += varint.decode.bytes
      var tag = prefix >> 3
      switch (tag) {
        case 1:
        var len = varint.decode(buf, offset)
        offset += varint.decode.bytes
        obj.cache = Cache.decode(buf, offset, offset + len)
        offset += Cache.decode.bytes
        break
        case 2:
        var len = varint.decode(buf, offset)
        offset += varint.decode.bytes
        obj.get = Get.decode(buf, offset, offset + len)
        offset += Get.decode.bytes
        break
        case 3:
        var len = varint.decode(buf, offset)
        offset += varint.decode.bytes
        obj.iterator = Iterator.decode(buf, offset, offset + len)
        offset += Iterator.decode.bytes
        break
        default:
        offset = skip(prefix & 7, buf, offset)
      }
    }
  }
}

function defined (val) {
  return val !== null && val !== undefined && (typeof val !== 'number' || !isNaN(val))
}
{
  "name": "hyperbee",
  "version": "2.27.3",
  "description": "An append-only B-tree running on a Hypercore.",
  "main": "index.js",
  "files": [
    "index.js",
    "lib/**.js",
    "iterators/**.js"
  ],
  "dependencies": {
    "b4a": "^1.6.0",
    "codecs": "^3.0.0",
    "debounceify": "^1.0.0",
    "hypercore-errors": "^1.0.0",
    "mutexify": "^1.4.0",
    "protocol-buffers-encodings": "^1.2.0",
    "rache": "^1.0.0",
    "ready-resource": "^1.0.0",
    "resolve-reject-promise": "^1.1.0",
    "safety-catch": "^1.0.2",
    "streamx": "^2.12.4",
    "unslab": "^1.2.0"
  },
  "devDependencies": {
    "bare-process": "^4.2.2",
    "brittle": "^3.1.0",
    "hypercore": "^11.0.0",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "protocol-buffers": "^4.2.0",
    "sub-encoder": "^1.0.6",
    "tree-to-string": "^1.1.1"
  },
  "imports": {
    "process": {
      "bare": "bare-process",
      "default": "process"
    }
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test/*.js",
    "test:bare": "brittle-bare test/*.js",
    "protobuf": "protocol-buffers schema.proto -o ./lib/messages.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/hyperbee.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/hyperbee/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperbee"
}
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const b4a = require('b4a')

// https://en.wikipedia.org/wiki/Merkle_tree#Second_preimage_attack
const LEAF_TYPE = b4a.from([0])
const PARENT_TYPE = b4a.from([1])
const ROOT_TYPE = b4a.from([2])

const HYPERCORE = b4a.from('hypercore')

exports.keyPair = function (seed) {
  // key pairs might stay around for a while, so better not to use a default slab to avoid retaining it completely
  const slab = b4a.allocUnsafeSlow(sodium.crypto_sign_PUBLICKEYBYTES + sodium.crypto_sign_SECRETKEYBYTES)
  const publicKey = slab.subarray(0, sodium.crypto_sign_PUBLICKEYBYTES)
  const secretKey = slab.subarray(sodium.crypto_sign_PUBLICKEYBYTES)

  if (seed) sodium.crypto_sign_seed_keypair(publicKey, secretKey, seed)
  else sodium.crypto_sign_keypair(publicKey, secretKey)

  return {
    publicKey,
    secretKey
  }
}

exports.validateKeyPair = function (keyPair) {
  const pk = b4a.allocUnsafe(sodium.crypto_sign_PUBLICKEYBYTES)
  sodium.crypto_sign_ed25519_sk_to_pk(pk, keyPair.secretKey)
  return b4a.equals(pk, keyPair.publicKey)
}

exports.sign = function (message, secretKey) {
  // Dedicated slab for the signature, to avoid retaining unneeded mem and for security
  const signature = b4a.allocUnsafeSlow(sodium.crypto_sign_BYTES)
  sodium.crypto_sign_detached(signature, message, secretKey)
  return signature
}

exports.verify = function (message, signature, publicKey) {
  if (signature.byteLength !== sodium.crypto_sign_BYTES) return false
  if (publicKey.byteLength !== sodium.crypto_sign_PUBLICKEYBYTES) return false
  return sodium.crypto_sign_verify_detached(signature, message, publicKey)
}

exports.encrypt = function (message, publicKey) {
  const ciphertext = b4a.alloc(message.byteLength + sodium.crypto_box_SEALBYTES)
  sodium.crypto_box_seal(ciphertext, message, publicKey)
  return ciphertext
}

exports.decrypt = function (ciphertext, keyPair) {
  if (ciphertext.byteLength < sodium.crypto_box_SEALBYTES) return null

  const plaintext = b4a.alloc(ciphertext.byteLength - sodium.crypto_box_SEALBYTES)

  if (!sodium.crypto_box_seal_open(plaintext, ciphertext, keyPair.publicKey, keyPair.secretKey)) {
    return null
  }

  return plaintext
}

exports.encryptionKeyPair = function (seed) {
  const publicKey = b4a.alloc(sodium.crypto_box_PUBLICKEYBYTES)
  const secretKey = b4a.alloc(sodium.crypto_box_SECRETKEYBYTES)

  if (seed) {
    sodium.crypto_box_seed_keypair(publicKey, secretKey, seed)
  } else {
    sodium.crypto_box_keypair(publicKey, secretKey)
  }

  return {
    publicKey,
    secretKey
  }
}

exports.data = function (data) {
  const out = b4a.allocUnsafe(32)

  sodium.crypto_generichash_batch(out, [
    LEAF_TYPE,
    c.encode(c.uint64, data.byteLength),
    data
  ])

  return out
}

exports.parent = function (a, b) {
  if (a.index > b.index) {
    const tmp = a
    a = b
    b = tmp
  }

  const out = b4a.allocUnsafe(32)

  sodium.crypto_generichash_batch(out, [
    PARENT_TYPE,
    c.encode(c.uint64, a.size + b.size),
    a.hash,
    b.hash
  ])

  return out
}

exports.tree = function (roots, out) {
  const buffers = new Array(3 * roots.length + 1)
  let j = 0

  buffers[j++] = ROOT_TYPE

  for (let i = 0; i < roots.length; i++) {
    const r = roots[i]
    buffers[j++] = r.hash
    buffers[j++] = c.encode(c.uint64, r.index)
    buffers[j++] = c.encode(c.uint64, r.size)
  }

  if (!out) out = b4a.allocUnsafe(32)
  sodium.crypto_generichash_batch(out, buffers)
  return out
}

exports.hash = function (data, out) {
  if (!out) out = b4a.allocUnsafe(32)
  if (!Array.isArray(data)) data = [data]

  sodium.crypto_generichash_batch(out, data)

  return out
}

exports.randomBytes = function (n) {
  const buf = b4a.allocUnsafe(n)
  sodium.randombytes_buf(buf)
  return buf
}

exports.discoveryKey = function (key) {
  if (!key || key.byteLength !== 32) throw new Error('Must pass a 32 byte buffer')
  // Discovery keys might stay around for a while, so better not to use slab memory (for better gc)
  const digest = b4a.allocUnsafeSlow(32)
  sodium.crypto_generichash(digest, HYPERCORE, key)
  return digest
}

if (sodium.sodium_free) {
  exports.free = function (secureBuf) {
    if (secureBuf.secure) sodium.sodium_free(secureBuf)
  }
} else {
  exports.free = function () {}
}

exports.namespace = function (name, count) {
  const ids = typeof count === 'number' ? range(count) : count

  // Namespaces are long-lived, so better to use a dedicated slab
  const buf = b4a.allocUnsafeSlow(32 * ids.length)

  const list = new Array(ids.length)

  // ns is emhemeral, so default slab
  const ns = b4a.allocUnsafe(33)
  sodium.crypto_generichash(ns.subarray(0, 32), typeof name === 'string' ? b4a.from(name) : name)

  for (let i = 0; i < list.length; i++) {
    list[i] = buf.subarray(32 * i, 32 * i + 32)
    ns[32] = ids[i]
    sodium.crypto_generichash(list[i], ns)
  }

  return list
}

function range (count) {
  const arr = new Array(count)
  for (let i = 0; i < count; i++) arr[i] = i
  return arr
}
{
  "name": "hypercore-crypto",
  "version": "3.6.1",
  "description": "The crypto primitives used in hypercore, extracted into a separate module",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.6.6",
    "compact-encoding": "^2.15.0",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "brittle": "^3.5.0",
    "standard": "^17.1.0"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/hypercore-crypto.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/hypercore-crypto/issues"
  },
  "homepage": "https://github.com/mafintosh/hypercore-crypto"
}
const IdEnc = require('hypercore-id-encoding')

module.exports = class HypercoreError extends Error {
  constructor (msg, code, fn = HypercoreError, discoveryKey = null) {
    if (discoveryKey) msg = `${msg} (discovery key: ${IdEnc.normalize(discoveryKey)})`
    super(`${code}: ${msg}`)

    this.code = code
    this.discoveryKey = discoveryKey

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name () {
    return 'HypercoreError'
  }

  static ASSERTION (msg, discoveryKey = null) { // ERR_ASSERTION is picked up by safety-catch also
    return new HypercoreError(msg, 'ERR_ASSERTION', HypercoreError.ASSERT, discoveryKey)
  }

  static BAD_ARGUMENT (msg, discoveryKey = null) {
    return new HypercoreError(msg, 'BAD_ARGUMENT', HypercoreError.BAD_ARGUMENT, discoveryKey)
  }

  static STORAGE_EMPTY (msg, discoveryKey = null) {
    return new HypercoreError(msg, 'STORAGE_EMPTY', HypercoreError.STORAGE_EMPTY, discoveryKey)
  }

  static STORAGE_CONFLICT (msg, discoveryKey = null) {
    return new HypercoreError(msg, 'STORAGE_CONFLICT', HypercoreError.STORAGE_CONFLICT, discoveryKey)
  }

  static INVALID_SIGNATURE (msg, discoveryKey = null) {
    return new HypercoreError(msg, 'INVALID_SIGNATURE', HypercoreError.INVALID_SIGNATURE, discoveryKey)
  }

  static INVALID_CAPABILITY (msg, discoveryKey = null) {
    return new HypercoreError(msg, 'INVALID_CAPABILITY', HypercoreError.INVALID_CAPABILITY, discoveryKey)
  }

  static INVALID_CHECKSUM (msg = 'Invalid checksum', discoveryKey = null) {
    return new HypercoreError(msg, 'INVALID_CHECKSUM', HypercoreError.INVALID_CHECKSUM, discoveryKey)
  }

  static INVALID_OPERATION (msg, discoveryKey = null) {
    return new HypercoreError(msg, 'INVALID_OPERATION', HypercoreError.INVALID_OPERATION, discoveryKey)
  }

  static INVALID_PROOF (msg = 'Proof not verifiable', discoveryKey = null) {
    return new HypercoreError(msg, 'INVALID_PROOF', HypercoreError.INVALID_PROOF, discoveryKey)
  }

  static BLOCK_NOT_AVAILABLE (msg = 'Block is not available', discoveryKey = null) {
    return new HypercoreError(msg, 'BLOCK_NOT_AVAILABLE', HypercoreError.BLOCK_NOT_AVAILABLE, discoveryKey)
  }

  static SNAPSHOT_NOT_AVAILABLE (msg = 'Snapshot is not available', discoveryKey = null) {
    return new HypercoreError(msg, 'SNAPSHOT_NOT_AVAILABLE', HypercoreError.SNAPSHOT_NOT_AVAILABLE, discoveryKey)
  }

  static REQUEST_CANCELLED (msg = 'Request was cancelled', discoveryKey = null) {
    return new HypercoreError(msg, 'REQUEST_CANCELLED', HypercoreError.REQUEST_CANCELLED, discoveryKey)
  }

  static REQUEST_TIMEOUT (msg = 'Request timed out', discoveryKey = null) {
    return new HypercoreError(msg, 'REQUEST_TIMEOUT', HypercoreError.REQUEST_TIMEOUT, discoveryKey)
  }

  static SESSION_NOT_WRITABLE (msg = 'Session is not writable', discoveryKey = null) {
    return new HypercoreError(msg, 'SESSION_NOT_WRITABLE', HypercoreError.SESSION_NOT_WRITABLE, discoveryKey)
  }

  static SESSION_CLOSED (msg = 'Session is closed', discoveryKey = null) {
    return new HypercoreError(msg, 'SESSION_CLOSED', HypercoreError.SESSION_CLOSED, discoveryKey)
  }

  static BATCH_UNFLUSHED (msg = 'Batch not yet flushed', discoveryKey = null) {
    return new HypercoreError(msg, 'BATCH_UNFLUSHED', HypercoreError.BATCH_UNFLUSHED, discoveryKey)
  }

  static BATCH_ALREADY_EXISTS (msg = 'Batch already exists', discoveryKey = null) {
    return new HypercoreError(msg, 'BATCH_ALREADY_EXISTS', HypercoreError.BATCH_ALREADY_EXISTS, discoveryKey)
  }

  static BATCH_ALREADY_FLUSHED (msg = 'Batch has already been flushed', discoveryKey = null) {
    return new HypercoreError(msg, 'BATCH_ALREADY_FLUSHED', HypercoreError.BATCH_ALREADY_FLUSHED, discoveryKey)
  }

  static OPLOG_CORRUPT (msg = 'Oplog file appears corrupt or out of date', discoveryKey = null) {
    return new HypercoreError(msg, 'OPLOG_CORRUPT', HypercoreError.OPLOG_CORRUPT, discoveryKey)
  }

  static OPLOG_HEADER_OVERFLOW (msg = 'Oplog header exceeds page size', discoveryKey = null) {
    return new HypercoreError(msg, 'OPLOG_HEADER_OVERFLOW', HypercoreError.OPLOG_HEADER_OVERFLOW, discoveryKey)
  }

  static INVALID_OPLOG_VERSION (msg = 'Invalid header version', discoveryKey = null) {
    return new HypercoreError(msg, 'INVALID_OPLOG_VERSION', HypercoreError.INVALID_OPLOG_VERSION, discoveryKey)
  }

  static WRITE_FAILED (msg = 'Write to storage failed', discoveryKey = null) {
    return new HypercoreError(msg, 'WRITE_FAILED', HypercoreError.WRITE_FAILED, discoveryKey)
  }

  static DECODING_ERROR (msg = 'Decoding error', discoveryKey = null) {
    return new HypercoreError(msg, 'DECODING_ERROR', HypercoreError.DECODING_ERROR, discoveryKey)
  }

  static SESSION_MOVED (msg = 'Session moved', discoveryKey = null) {
    return new HypercoreError(msg, 'SESSION_MOVED', HypercoreError.SESSION_MOVED, discoveryKey)
  }
}
{
  "name": "hypercore-errors",
  "version": "1.5.0",
  "description": "Hypercore errors",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/hypercore-errors.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/hypercore-errors/issues"
  },
  "homepage": "https://github.com/holepunchto/hypercore-errors#readme",
  "devDependencies": {
    "b4a": "^1.6.7",
    "brittle": "^3.1.3",
    "standard": "^17.0.0"
  },
  "dependencies": {
    "hypercore-id-encoding": "^1.3.0"
  }
}
const z32 = require('z32')
const b4a = require('b4a')

module.exports = {
  encode,
  decode,
  normalize,
  isValid
}

function encode (key) {
  if (!b4a.isBuffer(key)) throw new Error('Key must be a Buffer')
  if (key.byteLength !== 32) throw new Error('Key must be 32-bytes long')
  return z32.encode(key)
}

function decode (id) {
  if (b4a.isBuffer(id)) {
    if (id.byteLength !== 32) throw new Error('ID must be 32-bytes long')
    return id
  }
  if (typeof id === 'string') {
    if (id.startsWith('pear://')) id = id.slice(7).split('/')[0]
    if (id.length === 52) return z32.decode(id)
    if (id.length === 64) {
      const buf = b4a.from(id, 'hex')
      if (buf.byteLength === 32) return buf
    }
  }
  throw new Error('Invalid Hypercore key')
}

function normalize (any) {
  return encode(decode(any))
}

function isValid (any) {
  try {
    decode(any)
    return true
  } catch {
    return false
  }
}
{
  "name": "hypercore-id-encoding",
  "version": "1.3.0",
  "description": "Convert Hypercore keys to/from z-base32 or hex",
  "main": "index.js",
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.5.3",
    "z32": "^1.0.0"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "hypercore": "^10.0.0",
    "random-access-memory": "^6.0.0",
    "standard": "^17.1.0"
  },
  "license": "Apache-2.0",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/hypercore-id-encoding.git"
  },
  "keywords": [],
  "author": "",
  "bugs": {
    "url": "https://github.com/holepunchto/hypercore-id-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/hypercore-id-encoding#readme"
}
const RocksDB = require('rocksdb-native')
const rrp = require('resolve-reject-promise')
const ScopeLock = require('scope-lock')
const DeviceFile = require('device-file')
const path = require('path')
const fs = require('fs')
const View = require('./lib/view.js')

const VERSION = 1
const COLUMN_FAMILY = 'corestore'

const { store, core } = require('./lib/keys.js')

const { CorestoreRX, CorestoreTX, CoreTX, CoreRX } = require('./lib/tx.js')

const {
  createCoreStream,
  createAliasStream,
  createDiscoveryKeyStream,
  createBlockStream,
  createBitfieldStream,
  createUserDataStream,
  createTreeNodeStream,
  createMarkStream,
  createLocalStream
} = require('./lib/streams.js')

const EMPTY = new View()

class Atom {
  constructor(db) {
    this.db = db
    this.view = new View()
    this.flushedPromise = null
    this.flushing = false
    this.preflushes = []
    this.flushes = []
  }

  preflush(fn) {
    this.preflushes.push(fn)
  }

  onflush(fn) {
    this.flushes.push(fn)
  }

  flushed() {
    if (!this.flushing) return Promise.resolve()
    if (this.flushedPromise !== null) return this.flushedPromise.promise
    this.flushedPromise = rrp()
    return this.flushedPromise.promise
  }

  _resolve() {
    const f = this.flushedPromise
    this.flushedPromise = null
    f.resolve()
  }

  async flush() {
    if (this.flushing) throw new Error('Atom already flushing')
    this.flushing = true

    try {
      const plen = this.preflushes.length
      for (let i = 0; i < plen; i++) this.preflushes[i]()

      await View.flush(this.view.changes, this.db)

      const promises = []
      const len = this.flushes.length // in case of reentry
      for (let i = 0; i < len; i++) promises.push(this.flushes[i]())

      await Promise.all(promises)
    } finally {
      this.view.reset()
      this.flushing = false
      if (this.flushedPromise !== null) this._resolve()
    }
  }
}

class HypercoreStorage {
  constructor(store, db, core, view, atom) {
    this.store = store
    this.db = db
    this.core = core
    this.view = view
    this.atom = atom

    this.view.readStart()
  }

  get readOnly() {
    return this.store.readOnly
  }

  get dependencies() {
    return this.core.dependencies
  }

  getDependencyLength() {
    return this.core.dependencies.length
      ? this.core.dependencies[this.core.dependencies.length - 1].length
      : -1
  }

  getDependency(length) {
    for (let i = this.core.dependencies.length - 1; i >= 0; i--) {
      const dep = this.core.dependencies[i]
      if (dep.length < length) return dep
    }

    return null
  }

  setDependencyHead(dep) {
    if (dep === null) {
      this.core.dependencies = []
      return
    }

    const deps = this.core.dependencies

    for (let i = deps.length - 1; i >= 0; i--) {
      const d = deps[i]

      if (d.dataPointer !== dep.dataPointer) continue

      // check if nothing changed
      if (d.length === dep.length && i === deps.length - 1) return

      this.core = {
        corePointer: this.core.corePointer,
        dataPointer: this.core.dataPointer,
        dependencies: deps.slice(0, i + 1)
      }

      this.core.dependencies[i] = {
        dataPointer: dep.dataPointer,
        length: dep.length
      }
      return // updated head so done
    }

    this.core.dependencies = [
      {
        dataPointer: dep.dataPointer,
        length: dep.length
      }
    ]
  }

  // TODO: this might have to be async if the dependents have changed, but prop ok for now
  updateDependencyLength(length, truncated) {
    const deps = this.core.dependencies

    const i = this.findDependencyIndex(length, truncated)
    if (i === -1) throw new Error('Dependency not found')

    this.core = {
      corePointer: this.core.corePointer,
      dataPointer: this.core.dataPointer,
      dependencies: deps.slice(0, i + 1)
    }

    if (this.core.dependencies[i].length !== length) {
      this.core.dependencies[i] = {
        dataPointer: deps[i].dataPointer,
        length
      }
    }
  }

  findDependencyIndex(length, truncated) {
    const deps = this.core.dependencies

    if (truncated) {
      for (let i = 0; i < deps.length; i++) {
        if (deps[i].length >= length) return i
      }

      return -1
    }

    for (let i = deps.length - 1; i >= 0; i--) {
      if (deps[i].length <= length) return i
    }

    return -1
  }

  get snapshotted() {
    return this.db._snapshot !== null
  }

  snapshot() {
    return new HypercoreStorage(
      this.store,
      this.db.snapshot(),
      this.core,
      this.view.snapshot(),
      this.atom
    )
  }

  compact() {
    return Promise.all([
      this.db.compactRange(core.core(this.core.corePointer), core.core(this.core.corePointer)),
      this.db.compactRange(core.data(this.core.dataPointer), core.data(this.core.dataPointer))
    ])
  }

  atomize(atom) {
    if (this.atom && this.atom !== atom) {
      throw new Error('Cannot atomize and atomized session with a new atom')
    }
    return new HypercoreStorage(this.store, this.db.session(), this.core, atom.view, atom)
  }

  createAtom() {
    return this.store.createAtom()
  }

  createBlockStream(opts) {
    return createBlockStream(this.core, this.db, this.view, opts)
  }

  createTreeNodeStream(opts) {
    return createTreeNodeStream(this.core, this.db, this.view, opts)
  }

  createBitfieldStream(opts) {
    return createBitfieldStream(this.core, this.db, this.view, opts)
  }

  createUserDataStream(opts) {
    return createUserDataStream(this.core, this.db, this.view, opts)
  }

  createMarkStream(opts) {
    return createMarkStream(this.core, this.db, this.view, opts)
  }

  createLocalStream(opts) {
    return createLocalStream(this.core, this.db, this.view, opts)
  }

  async resumeSession(name) {
    const rx = this.read()
    const existingSessionsPromise = rx.getSessions()

    rx.tryFlush()
    const existingSessions = await existingSessionsPromise

    const sessions = existingSessions || []
    const session = getSession(sessions, name, false)

    if (session === null) return null

    const core = {
      corePointer: this.core.corePointer,
      dataPointer: session.dataPointer,
      dependencies: []
    }

    const coreRx = new CoreRX(core, this.db, this.view)

    const dependencyPromise = coreRx.getDependency()
    coreRx.tryFlush()

    const dependency = await dependencyPromise
    if (dependency) core.dependencies = this._addDependency(dependency)

    return new HypercoreStorage(
      this.store,
      this.db.session(),
      core,
      this.atom ? this.view : new View(),
      this.atom
    )
  }

  async createSession(name, head) {
    const rx = this.read()

    const existingSessionsPromise = rx.getSessions()
    const existingHeadPromise = rx.getHead()

    rx.tryFlush()

    const [existingSessions, existingHead] = await Promise.all([
      existingSessionsPromise,
      existingHeadPromise
    ])
    if (head === null) head = existingHead

    if (existingHead !== null && head.length > existingHead.length) {
      throw new Error('Invalid head passed, ahead of core')
    }

    const sessions = existingSessions || []
    const session = getSession(sessions, name, true)
    const fresh = session.dataPointer === -1

    if (fresh) {
      session.dataPointer = await this.store._allocData()
    }

    const tx = this.write()

    tx.setSessions(sessions)

    const length = head === null ? 0 : head.length
    const core = {
      corePointer: this.core.corePointer,
      dataPointer: session.dataPointer,
      dependencies: this._addDependency({
        dataPointer: this.core.dataPointer,
        length
      })
    }

    const coreTx = new CoreTX(core, this.db, tx.view, tx.changes)

    if (length > 0) coreTx.setHead(head)
    coreTx.setDependency(core.dependencies[core.dependencies.length - 1])

    if (!fresh) {
      // nuke all existing state...
      coreTx.deleteBlockRange(0, -1)
      coreTx.deleteTreeNodeRange(0, -1)
      coreTx.deleteBitfieldPageRange(0, -1)
    }

    await tx.flush()

    return new HypercoreStorage(
      this.store,
      this.db.session(),
      core,
      this.atom ? this.view : new View(),
      this.atom
    )
  }

  async createAtomicSession(atom, head) {
    const length = head === null ? 0 : head.length
    const core = {
      corePointer: this.core.corePointer,
      dataPointer: this.core.dataPointer,
      dependencies: this._addDependency(null)
    }

    const coreTx = new CoreTX(core, this.db, atom.view, [])

    if (length > 0) coreTx.setHead(head)

    await coreTx.flush()

    return this.atomize(atom)
  }

  _addDependency(dep) {
    const deps = []

    for (let i = 0; i < this.core.dependencies.length; i++) {
      const d = this.core.dependencies[i]

      if (dep !== null && d.length > dep.length) {
        if (d.dataPointer !== dep.dataPointer) {
          deps.push({ dataPointer: d.dataPointer, length: dep.length })
        }
        return deps
      }

      deps.push(d)
    }

    if (
      dep !== null &&
      (deps.length === 0 || deps[deps.length - 1].dataPointer !== dep.dataPointer)
    ) {
      deps.push(dep)
    }
    return deps
  }

  async deleteSessions() {
    const rx = this.read()
    const existingSessionsPromise = rx.getSessions()
    rx.tryFlush()

    const existingSessions = await existingSessionsPromise

    // Remove batches
    const coreTx = this.write()
    coreTx.setSessions([]) // Clear sessions record
    await coreTx.flush()

    const tx = this.db.write({ autoDestroy: true })

    for (const { dataPointer } of existingSessions) {
      const start = core.data(dataPointer)
      const end = core.data(dataPointer + 1)
      tx.tryDeleteRange(start, end)
    }

    await tx.flush()
  }

  read() {
    return new CoreRX(this.core, this.db, this.view)
  }

  write() {
    return new CoreTX(this.core, this.db, this.atom ? this.view : null, [])
  }

  close() {
    if (this.view !== null) {
      this.view.readStop()
      this.view = null
    }

    return this.db.close()
  }

  static async export(ptr, db, { batches = false } = {}) {
    const rx = new CoreRX(ptr, db, EMPTY)

    const core = {
      head: null,
      auth: null,
      sessions: [],
      data: null
    }

    const sessionsPromise = rx.getSessions()
    const headPromise = rx.getHead()
    const authPromise = rx.getAuth()

    rx.tryFlush()

    const [sessions, head, auth] = await Promise.all([sessionsPromise, headPromise, authPromise])

    core.head = head
    core.auth = { ...auth, keyPair: null }
    if (sessions) core.sessions = sessions.map((s) => s.name)

    const data = []

    data.push(exportData(ptr, db))

    if (batches) {
      for (const { dataPointer } of sessions) {
        data.push(exportData({ dataPointer, dependencies: [] }, db))
      }
    }

    core.data = await Promise.all(data)

    return core
  }

  static isParentStorage(storage, parent) {
    const last = getLastDependency(storage)
    return !!last && last.dataPointer === parent.core.dataPointer
  }
}

class CorestoreStorage {
  constructor(db, opts = {}) {
    const storage = typeof db === 'string' ? db : null

    this.bootstrap = storage !== null
    this.path = storage !== null ? storage : path.join(db.path, '..')
    this.alwaysRecover = !!opts.alwaysRecover
    this.readOnly = !!opts.readOnly
    this.allowBackup = !!opts.allowBackup
    this.deviceFile = null
    this.wait = !!opts.wait

    // tmp sync fix for simplicty since not super deployed yet
    if (this.bootstrap && !this.readOnly) tmpFixStorage(this.path)

    this.id = opts.id || null
    this.view = null
    this.enters = 0
    this.lock = new ScopeLock()
    this.flushing = null
    this.version = 0
    this.migrating = null

    if ((this.bootstrap && !this.readOnly && !this.allowBackup) || this.wait) {
      const corestoreFile = path.join(this.path, 'CORESTORE')

      this.deviceFile = new DeviceFile(corestoreFile, {
        lock: true,
        wait: this.wait,
        data: { id: this.id }
      })
    }

    const dbPath = path.join(this.path, 'db')

    this.rocks = storage === null ? db : new RocksDB(dbPath, { ...opts, lock: this.deviceFile })
    this.db = createColumnFamily(this.rocks, opts)
  }

  get opened() {
    return this.db.opened
  }

  get closed() {
    return this.db.closed
  }

  async ready() {
    if (this.version === 0) await this._migrateStore()
    return this.db.ready()
  }

  compact() {
    return this.db.compactRange()
  }

  async audit() {
    for await (const { core } of this.createCoreStream()) {
      const coreRx = new CoreRX(core, this.db, EMPTY)
      const authPromise = coreRx.getAuth()

      coreRx.tryFlush()

      const auth = await authPromise

      if (!auth.manifest || auth.manifest.version > 0) continue
      if (auth.manifest.linked === null) continue

      auth.manifest.linked = null
      const coreTx = new CoreTX(core, this.db, null, [])
      coreTx.setAuth(auth)
      await coreTx.flush()
    }
  }

  async deleteCore(ptr) {
    const rx = new CoreRX(ptr, this.db, EMPTY)

    const authPromise = rx.getAuth()
    const sessionsPromise = rx.getSessions()

    rx.tryFlush()

    const auth = await authPromise
    const sessions = await sessionsPromise

    // no core stored here
    if (!auth) return

    const tx = this.db.write({ autoDestroy: true })

    tx.tryDelete(store.core(auth.discoveryKey))

    // clear core
    const start = core.core(ptr.corePointer)
    const end = core.core(ptr.corePointer + 1)
    tx.tryDeleteRange(start, end)

    if (sessions) {
      for (const { dataPointer } of sessions) {
        const start = core.data(dataPointer)
        const end = core.data(dataPointer + 1)
        tx.tryDeleteRange(start, end)
      }
    }

    return tx.flush()
  }

  static isCoreStorage(db) {
    return isCorestoreStorage(db)
  }

  static from(db) {
    if (isCorestoreStorage(db)) return db
    return new this(db)
  }

  async _flush() {
    while (this.enters > 0) {
      await this.lock.lock()
      await this.lock.unlock()
    }
  }

  async _maybeRecover(view) {
    const r = path.join(this.db.path, 'RECOVERING')
    if (!(await fileExists(r))) return
    await this.setRecovering(view)
    await fs.promises.unlink(r)
  }

  _maybeRecoverLater(err) {
    if (!shouldRecover(err) && !this.alwaysRecover) return
    fs.writeFileSync(path.join(this.db.path, 'RECOVERING'), '')
    for (const file of fs.readdirSync(this.db.path)) {
      if (file.endsWith('.log')) fs.unlinkSync(path.join(this.db.path, file))
    }
  }

  // runs pre any other mutation and read
  async _migrateStore() {
    const view = await this._enter()

    try {
      if (this.version === VERSION) return

      await this._preopen

      try {
        await this.db.ready()
      } catch (err) {
        this._maybeRecoverLater(err)
        throw err
      }

      await this._maybeRecover(view)

      const rx = new CorestoreRX(this.db, view)
      const headPromise = rx.getHead()

      rx.tryFlush()
      const head = await headPromise

      const version = head === null ? 0 : head.version
      if (version === VERSION) {
        this.version = VERSION
        return
      }

      const target = { version: VERSION, dryRun: false }

      switch (version) {
        case 0: {
          await require('./migrations/0').store(this, target)
          break
        }
        default: {
          throw new Error(
            'Unsupported version: ' + version + ' - you should probably upgrade your dependencies'
          )
        }
      }

      this.version = VERSION
    } finally {
      await this._exit()
    }
  }

  // runs pre the core is returned to the user
  async _migrateCore(core, discoveryKey, version, locked) {
    const view = locked ? this.view : await this._enter()
    try {
      if (version === VERSION) return

      const target = { version: VERSION, dryRun: false }

      switch (version) {
        case 0: {
          await require('./migrations/0').core(core, target)
          break
        }
        default: {
          throw new Error(
            'Unsupported version: ' + version + ' - you should probably upgrade your dependencies'
          )
        }
      }

      if (locked === false) return

      // if its locked, then move the core state into the memview
      // in case the core is reopened from the memview, pre flush

      const rx = new CorestoreRX(this.db, EMPTY)
      const tx = new CorestoreTX(view)

      const corePromise = rx.getCore(discoveryKey)
      rx.tryFlush()

      tx.putCore(discoveryKey, await corePromise)
      tx.apply()
    } finally {
      if (!locked) await this._exit()
    }
  }

  async _enter() {
    this.enters++
    await this.lock.lock()
    if (this.view === null) this.view = new View()
    return this.view
  }

  async _exit() {
    this.enters--

    if (this.flushing === null) this.flushing = rrp()
    const flushed = this.flushing.promise

    if (this.enters === 0 || this.view.size() > 128) {
      try {
        await View.flush(this.view.changes, this.db)
        this.flushing.resolve()
      } catch (err) {
        this.flushing.reject(err)
      } finally {
        this.flushing = null
        this.view = null
      }
    }

    this.lock.unlock()
    return flushed
  }

  // when used with core catches this isnt transactional for simplicity, HOWEVER, its just a number
  // so worth the tradeoff
  async _allocData() {
    let dataPointer = 0

    const view = await this._enter()
    const tx = new CorestoreTX(view)

    try {
      const head = await this._getHead(view)

      dataPointer = head.allocated.datas++

      tx.setHead(head)
      tx.apply()
    } finally {
      await this._exit()
    }

    return dataPointer
  }

  // exposes here so migrations can easily access the head in an init state
  async _getHead(view) {
    const rx = new CorestoreRX(this.db, view)
    const headPromise = rx.getHead()
    rx.tryFlush()

    const head = await headPromise
    return head === null ? initStoreHead() : head
  }

  createAtom() {
    return new Atom(this.db)
  }

  async flush() {
    await this.rocks.flush()
  }

  async close() {
    if (this.db.closed) return
    await this._flush()
    await this.db.close()
    await this.rocks.close()
    if (this.deviceFile) await this.deviceFile.close()
  }

  async clear() {
    if (this.version === 0) await this._migrateStore()

    const view = await this._enter()
    const tx = new CorestoreTX(view)

    tx.clear()
    tx.apply()

    await this._exit()
  }

  createCoreStream() {
    // TODO: be nice to run the mgiration here also, but too much plumbing atm
    return createCoreStream(this.db, EMPTY)
  }

  createAliasStream(namespace) {
    // TODO: be nice to run the mgiration here also, but too much plumbing atm
    return createAliasStream(this.db, EMPTY, namespace)
  }

  createDiscoveryKeyStream(namespace) {
    return createDiscoveryKeyStream(this.db, EMPTY, namespace)
  }

  async getAlias(alias) {
    if (this.version === 0) await this._migrateStore()

    const rx = new CorestoreRX(this.db, EMPTY)
    const discoveryKeyPromise = rx.getCoreByAlias(alias)
    rx.tryFlush()
    return discoveryKeyPromise
  }

  async getSeed() {
    if (this.version === 0) await this._migrateStore()

    const rx = new CorestoreRX(this.db, EMPTY)
    const headPromise = rx.getHead()

    rx.tryFlush()

    const head = await headPromise
    return head === null ? null : head.seed
  }

  async setSeed(seed, { overwrite = true } = {}) {
    if (this.version === 0) await this._migrateStore()

    const view = await this._enter()
    const tx = new CorestoreTX(view)

    try {
      const rx = new CorestoreRX(this.db, view)
      const headPromise = rx.getHead()

      rx.tryFlush()

      const head = (await headPromise) || initStoreHead()

      if (head.seed === null || overwrite) head.seed = seed
      tx.setHead(head)
      tx.apply()

      return head.seed
    } finally {
      await this._exit()
    }
  }

  async setRecovering(view = null) {
    const recovering = Date.now()
    let keys = []

    for await (const data of this.createDiscoveryKeyStream()) {
      keys.push(data)
      if (keys.length > 16 * 1024) {
        await this._flushRecovering(recovering, view, keys)
        keys = []
      }
    }

    if (keys.length) await this._flushRecovering(recovering, view, keys)
  }

  async _flushRecovering(recovering, view, keys) {
    const own = !view
    if (own) view = await this._enter()
    const tx = new CorestoreTX(view)

    try {
      const infos = await this._getInfos(keys, { auth: false, head: false, hints: true })
      for (const inf of infos) {
        tx.setCoreHints(inf.core, { ...inf.hints, recovering })
      }
      tx.apply()
    } finally {
      if (own) await this._exit()
    }
  }

  async getDefaultDiscoveryKey() {
    if (this.version === 0) await this._migrateStore()

    const rx = new CorestoreRX(this.db, EMPTY)
    const headPromise = rx.getHead()

    rx.tryFlush()

    const head = await headPromise
    return head === null ? null : head.defaultDiscoveryKey
  }

  async setDefaultDiscoveryKey(discoveryKey, { overwrite = true } = {}) {
    if (this.version === 0) await this._migrateStore()

    const view = await this._enter()
    const tx = new CorestoreTX(view)

    try {
      const rx = new CorestoreRX(this.db, view)
      const headPromise = rx.getHead()

      rx.tryFlush()

      const head = (await headPromise) || initStoreHead()

      if (head.defaultDiscoveryKey === null || overwrite) head.defaultDiscoveryKey = discoveryKey
      tx.setHead(head)
      tx.apply()

      return head.defaultDiscoveryKey
    } finally {
      await this._exit()
    }
  }

  async hasCore(discoveryKey, { ifMigrated = false } = {}) {
    if (this.version === 0) await this._migrateStore()

    const rx = new CorestoreRX(this.db, EMPTY)
    const promise = rx.getCore(discoveryKey)

    rx.tryFlush()

    const core = await promise

    if (core === null) return false
    if (core.version !== VERSION && ifMigrated) return false

    return true
  }

  async getAuth(discoveryKey) {
    if (this.version === 0) await this._migrateStore()

    const rx = new CorestoreRX(this.db, EMPTY)
    const corePromise = rx.getCore(discoveryKey)

    rx.tryFlush()

    const core = await corePromise
    if (core === null) return null

    const read = this.db.read({ autoDestroy: true })
    const authPromise = CoreRX.getAuth(read, core)

    read.tryFlush()

    return authPromise
  }

  async getInfo(discoveryKey, opts) {
    return (await this.getInfos([discoveryKey], opts))[0]
  }

  async getInfos(discoveryKeys, opts) {
    if (this.version === 0) await this._migrateStore()
    return this._getInfos(discoveryKeys, opts)
  }

  async _getInfos(discoveryKeys, { auth = true, head = true, hints = true } = {}) {
    const rx = new CorestoreRX(this.db, EMPTY)
    const corePromises = new Array(discoveryKeys.length)

    for (let i = 0; i < discoveryKeys.length; i++) {
      corePromises[i] = rx.getCore(discoveryKeys[i])
    }

    rx.tryFlush()

    const cores = await Promise.all(corePromises)
    const read = this.db.read({ autoDestroy: true })

    const resultPromises = new Array(cores.length)

    for (let i = 0; i < cores.length; i++) {
      resultPromises[i] = cores[i]
        ? getInfoFromBatch(read, cores[i], discoveryKeys[i], auth, head, hints)
        : null
    }

    read.tryFlush()

    return Promise.all(resultPromises)
  }

  async suspend() {
    await this.db.suspend()
    if (this.deviceFile) await this.deviceFile.suspend()
  }

  async resume() {
    if (this.deviceFile) await this.deviceFile.resume()
    await this.db.resume()
  }

  async resumeCore(discoveryKey) {
    if (this.version === 0) await this._migrateStore()

    if (!discoveryKey) {
      discoveryKey = await this.getDefaultDiscoveryKey()
      if (!discoveryKey) return null
    }

    const rx = new CorestoreRX(this.db, EMPTY)
    const corePromise = rx.getCore(discoveryKey)

    rx.tryFlush()
    const core = await corePromise

    if (core === null) return null
    return this._resumeFromPointers(EMPTY, discoveryKey, false, core)
  }

  async export(discoveryKey, opts) {
    const rx = new CorestoreRX(this.db, EMPTY)
    const corePromise = rx.getCore(discoveryKey)

    rx.tryFlush()
    const core = await corePromise
    if (core === null) return null

    let { dataPointer, corePointer } = core

    const ptr = { corePointer, dataPointer, dependencies: [] }

    while (true) {
      const rx = new CoreRX({ dataPointer, corePointer: 0, dependencies: [] }, this.db, EMPTY)
      const dependencyPromise = rx.getDependency()
      rx.tryFlush()
      const dependency = await dependencyPromise
      if (!dependency) break
      ptr.dependencies.push(dependency)
      dataPointer = dependency.dataPointer
    }

    const session = this.db.session()
    try {
      return await HypercoreStorage.export(ptr, session, opts)
    } finally {
      await session.close()
    }
  }

  async _resumeFromPointers(view, discoveryKey, create, { version, corePointer, dataPointer }) {
    const core = { corePointer, dataPointer, dependencies: [] }

    while (true) {
      const rx = new CoreRX({ dataPointer, corePointer: 0, dependencies: [] }, this.db, view)
      const dependencyPromise = rx.getDependency()
      rx.tryFlush()
      const dependency = await dependencyPromise
      if (!dependency) break
      core.dependencies.push(dependency)
      dataPointer = dependency.dataPointer
    }

    const result = new HypercoreStorage(this, this.db.session(), core, EMPTY, null)

    if (version < VERSION) await this._migrateCore(result, discoveryKey, version, create)
    return result
  }

  // not allowed to throw validation errors as its a shared tx!
  async _create(
    view,
    { key, manifest, keyPair, encryptionKey, discoveryKey, alias, userData, core: ptrs }
  ) {
    const rx = new CorestoreRX(this.db, view)
    const tx = new CorestoreTX(view)

    const corePromise = rx.getCore(discoveryKey)
    const headPromise = rx.getHead()

    rx.tryFlush()

    let [core, head] = await Promise.all([corePromise, headPromise])
    if (core) return this._resumeFromPointers(view, discoveryKey, true, core)

    if (head === null) head = initStoreHead()
    if (head.defaultDiscoveryKey === null) head.defaultDiscoveryKey = discoveryKey

    const corePointer = ptrs ? ptrs.corePointer : head.allocated.cores++
    const dataPointer = ptrs ? ptrs.dataPointer : head.allocated.datas++

    core = { version: VERSION, corePointer, dataPointer, alias }

    tx.setHead(head)
    tx.putCore(discoveryKey, core)
    if (alias) tx.putCoreByAlias(alias, discoveryKey)

    const ptr = { corePointer, dataPointer, dependencies: [] }
    const ctx = new CoreTX(ptr, this.db, view, tx.changes)

    ctx.setAuth({
      key,
      discoveryKey,
      manifest,
      keyPair,
      encryptionKey
    })

    if (userData) {
      for (const { key, value } of userData) {
        ctx.putUserData(key, value)
      }
    }

    tx.apply()

    return new HypercoreStorage(this, this.db.session(), ptr, EMPTY, null)
  }

  async createCore(data) {
    if (this.version === 0) await this._migrateStore()

    const view = await this._enter()

    try {
      return await this._create(view, data)
    } finally {
      await this._exit()
    }
  }

  static isParentStorage(storage, parent) {
    return HypercoreStorage.isParentStorage(storage, parent)
  }
}

module.exports = CorestoreStorage

function initStoreHead() {
  return {
    version: 0, // cause we wanna run the migration
    allocated: {
      datas: 0,
      cores: 0
    },
    seed: null,
    defaultDiscoveryKey: null
  }
}

function getSession(sessions, name, alloc) {
  for (let i = 0; i < sessions.length; i++) {
    if (sessions[i].name === name) return sessions[i]
  }

  if (!alloc) return null

  const result = { name, dataPointer: -1 }
  sessions.push(result)
  return result
}

function isCorestoreStorage(s) {
  return typeof s === 'object' && !!s && typeof s.setDefaultDiscoveryKey === 'function'
}

function createColumnFamily(db, opts = {}) {
  const {
    tableCacheIndexAndFilterBlocks = true,
    blockCache = true,
    optimizeFiltersForMemory = false
  } = opts

  const col = new RocksDB.ColumnFamily(COLUMN_FAMILY, {
    enableBlobFiles: true,
    minBlobSize: 4096,
    blobFileSize: 256 * 1024 * 1024,
    enableBlobGarbageCollection: true,
    tableBlockSize: 8192,
    tableCacheIndexAndFilterBlocks,
    tableFormatVersion: 6,
    optimizeFiltersForMemory,
    blockCache
  })

  return db.columnFamily(col)
}

function getLastDependency(storage) {
  return storage.dependencies.length ? storage.dependencies[storage.dependencies.length - 1] : null
}

// TODO: remove in like 3-6 mo
function tmpFixStorage(p) {
  // if CORESTORE file is written, new format
  if (fs.existsSync(path.join(p, 'CORESTORE'))) return

  let files = []

  try {
    files = fs.readdirSync(p)
  } catch {}

  const notRocks = new Set([
    'CORESTORE',
    'primary-key',
    'cores',
    'app-preferences',
    'cache',
    'preferences.json',
    'db',
    'clone',
    'core',
    'notifications'
  ])

  for (const f of files) {
    if (notRocks.has(f)) continue

    try {
      fs.mkdirSync(path.join(p, 'db'))
    } catch {}

    fs.renameSync(path.join(p, f), path.join(p, 'db', f))
  }
}

async function exportData(ptr, db, opts) {
  // just need dataPointer
  const reads = [
    toArray(createBlockStream(ptr, db, EMPTY, opts)),
    toArray(createTreeNodeStream(ptr, db, EMPTY, opts)),
    toArray(createBitfieldStream(ptr, db, EMPTY, opts))
  ]

  const [blocks, tree, bitfield] = await Promise.all(reads)

  return {
    blocks,
    tree,
    bitfield
  }
}

async function toArray(stream) {
  const all = []
  for await (const e of stream) all.push(e)
  return all
}

async function fileExists(path) {
  try {
    await fs.promises.stat(path)
    return true
  } catch {
    return false
  }
}

function shouldRecover(err) {
  return err.message.toLowerCase().indexOf('sequence number is being set backwards') > -1
}

function noop() {}

async function getInfoFromBatch(db, c, discoveryKey, getAuth, getHead, getHints) {
  const authPromise = getAuth ? CoreRX.getAuth(db, c) : null
  const headPromise = getHead ? CoreRX.getHead(db, c) : null
  const hintsPromise = getHints ? CoreRX.getHints(db, c) : null

  // ensure no uncaughts
  if (authPromise) authPromise.catch(noop)
  if (headPromise) headPromise.catch(noop)
  if (hintsPromise) hintsPromise.catch(noop)

  return {
    discoveryKey,
    core: c,
    auth: await authPromise,
    head: await headPromise,
    hints: await hintsPromise
  }
}
const { Readable, getStreamError } = require('streamx')
const { core } = require('./keys')

module.exports = class BlockStream extends Readable {
  constructor(core, db, updates, start, end, reverse) {
    super()

    this.core = core
    this.db = db
    this.updates = updates
    this.start = start
    this.end = end
    this.reverse = reverse === true

    this._drained = true
    this._consumed = 0
    this._stream = null
    this._oncloseBound = this._onclose.bind(this)
    this._maybeDrainBound = this._maybeDrain.bind(this)

    this._update()
  }

  _update() {
    if (this._consumed > this.core.dependencies.length) return

    const deps = this.core.dependencies
    const index = this._findDependencyIndex(deps)

    const curr = index < deps.length ? deps[index] : null
    const prev = index > 0 && index - 1 < deps.length ? deps[index - 1] : null

    const start = prev && prev.length > this.start ? prev.length : this.start
    const end = curr && (this.end === -1 || curr.length < this.end) ? curr.length : this.end

    const ptr = curr ? curr.dataPointer : this.core.dataPointer

    this._makeStream(core.block(ptr, start), core.block(ptr, end))
  }

  _findDependencyIndex(deps) {
    if (!this.reverse) return this._consumed++

    let i = deps.length - this._consumed++
    while (i > 0) {
      if (deps[i - 1].length <= this.end) return i
      i--
      this._consumed++
    }

    return 0
  }

  _predestroy() {
    if (this._stream !== null) this._stream.destroy()
  }

  _read(cb) {
    this._drained = this._onreadable()
    cb(null)
  }

  _maybeDrain() {
    if (this._drained === true) return
    this._drained = this._onreadable()
  }

  _onreadable() {
    if (this._stream === null) {
      this.push(null)
      return true
    }

    let data = this._stream.read()

    if (data === null) return false

    do {
      this.push(data)
      data = this._stream.read()
    } while (data !== null)

    return true
  }

  _onclose() {
    if (this.destroying) return

    const err = getStreamError(this._stream)

    if (err !== null) {
      this.destroy(err)
      return
    }

    // empty the current stream
    if (this._onreadable() === true) this._drained = true

    this._stream = null

    this._update()
    this._maybeDrain()
  }

  _makeStream(start, end) {
    this._stream = this.updates.iterator(this.db, start, end, this.reverse)
    this._stream.on('readable', this._maybeDrainBound)
    this._stream.on('error', noop)
    this._stream.on('close', this._oncloseBound)
  }
}

function noop() {}
const { Readable } = require('streamx')

// used for returned a stream that just errors (during read during teardown)

module.exports = class CloseErrorStream extends Readable {
  constructor(err) {
    super()
    this.error = err
  }

  _open(cb) {
    cb(this.error)
  }
}
const { UINT, STRING } = require('index-encoder')
const c = require('compact-encoding')
const b4a = require('b4a')

const TL_HEAD = 0
const TL_CORE_BY_DKEY = 1
const TL_CORE_BY_ALIAS = 2
const TL_CORE = 3
const TL_DATA = 4

const TL_END = TL_DATA + 1

const CORE_AUTH = 0
const CORE_SESSIONS = 1

const DATA_HEAD = 0
const DATA_DEPENDENCY = 1
const DATA_HINTS = 2
const DATA_BLOCK = 3
const DATA_TREE = 4
const DATA_BITFIELD = 5
const DATA_USER_DATA = 6
const DATA_LOCAL = 7
const DATA_MARK = 8

const slab = { buffer: b4a.allocUnsafe(65536), start: 0, end: 0 }

const store = {}
const core = {}

store.clear = function () {
  const state = alloc()
  let start = state.start
  UINT.encode(state, 0)
  const a = state.buffer.subarray(start, state.start)
  start = state.start
  UINT.encode(state, TL_END)
  const b = state.buffer.subarray(start, state.start)
  return [a, b]
}

store.head = function () {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_HEAD)
  return state.buffer.subarray(start, state.start)
}

store.core = function (discoveryKey) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE_BY_DKEY)
  c.fixed32.encode(state, discoveryKey)
  return state.buffer.subarray(start, state.start)
}

store.coreStart = function () {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE_BY_DKEY)
  return state.buffer.subarray(start, state.start)
}

store.coreEnd = function () {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE_BY_DKEY + 1)
  return state.buffer.subarray(start, state.start)
}

store.coreByAlias = function ({ namespace, name }) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE_BY_ALIAS)
  c.fixed32.encode(state, namespace)
  STRING.encode(state, name)
  return state.buffer.subarray(start, state.start)
}

store.coreByAliasStart = function (namespace) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE_BY_ALIAS)
  if (namespace) c.fixed32.encode(state, namespace)
  return state.buffer.subarray(start, state.start)
}

store.coreByAliasEnd = function (namespace) {
  const state = alloc()
  const start = state.start

  if (namespace) {
    UINT.encode(state, TL_CORE_BY_ALIAS)
    c.fixed32.encode(state, namespace)
    state.buffer[state.start++] = 0xff
  } else {
    UINT.encode(state, TL_CORE_BY_ALIAS + 1)
  }

  return state.buffer.subarray(start, state.start)
}

store.alias = function (buffer) {
  const state = { buffer, start: 0, end: buffer.byteLength }
  UINT.decode(state) // ns
  const namespace = c.fixed32.decode(state)
  const name = STRING.decode(state)
  return { namespace, name }
}

store.discoveryKey = function (buffer) {
  const state = { buffer, start: 0, end: buffer.byteLength }
  UINT.decode(state) // ns
  return c.fixed32.decode(state)
}

core.core = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE)
  UINT.encode(state, ptr)
  return state.buffer.subarray(start, state.start)
}

core.data = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  return state.buffer.subarray(start, state.start)
}

core.auth = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE)
  UINT.encode(state, ptr)
  UINT.encode(state, CORE_AUTH)
  return state.buffer.subarray(start, state.start)
}

core.sessions = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE)
  UINT.encode(state, ptr)
  UINT.encode(state, CORE_SESSIONS)
  return state.buffer.subarray(start, state.start)
}

core.head = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_HEAD)
  return state.buffer.subarray(start, state.start)
}

core.dependency = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_DEPENDENCY)
  return state.buffer.subarray(start, state.start)
}

core.hints = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_HINTS)
  return state.buffer.subarray(start, state.start)
}

core.block = function (ptr, index) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_BLOCK)
  UINT.encode(state, index)
  return state.buffer.subarray(start, state.start)
}

core.tree = function (ptr, index) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_TREE)
  UINT.encode(state, index)
  return state.buffer.subarray(start, state.start)
}

core.bitfield = function (ptr, index, type) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_BITFIELD)
  UINT.encode(state, index)
  UINT.encode(state, type)
  return state.buffer.subarray(start, state.start)
}

core.userData = function (ptr, key) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_USER_DATA)
  STRING.encode(state, key)
  return state.buffer.subarray(start, state.start)
}

core.userDataEnd = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_USER_DATA + 1)
  return state.buffer.subarray(start, state.start)
}

core.mark = function (ptr, index) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_MARK)
  UINT.encode(state, index)
  return state.buffer.subarray(start, state.start)
}

core.local = function (ptr, key) {
  if (key.byteLength > 2048) {
    throw new Error('local keys has an upper limit of 2048 bytes atm')
  }

  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_LOCAL)

  state.buffer.set(key, state.start)
  state.start += key.byteLength
  return state.buffer.subarray(start, state.start)
}

core.localEnd = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_LOCAL + 1)
  return state.buffer.subarray(start, state.start)
}

core.blockIndex = function (buffer) {
  const state = { buffer, start: 0, end: buffer.byteLength }
  UINT.decode(state) // ns
  UINT.decode(state) // ptr
  UINT.decode(state) // type
  return UINT.decode(state)
}

core.bitfieldIndexAndType = function (buffer) {
  const state = { buffer, start: 0, end: buffer.byteLength }
  UINT.decode(state) // ns
  UINT.decode(state) // ptr
  UINT.decode(state) // type
  return [UINT.decode(state), UINT.decode(state)]
}

core.userDataKey = function (buffer) {
  const state = { buffer, start: 0, end: buffer.byteLength }
  UINT.decode(state) // ns
  UINT.decode(state) // ptr
  UINT.decode(state) // type
  return STRING.decode(state)
}

core.markKey = function (buffer) {
  const state = { buffer, start: 0, end: buffer.byteLength }
  UINT.decode(state) // ns
  UINT.decode(state) // ptr
  UINT.decode(state) // type
  return UINT.decode(state)
}

core.localKey = function (buffer) {
  const state = { buffer, start: 0, end: buffer.byteLength }
  UINT.decode(state) // ns
  UINT.decode(state) // ptr
  UINT.decode(state) // type
  return state.buffer.subarray(state.start, state.end)
}

module.exports = { store, core }

function alloc() {
  if (slab.buffer.byteLength - slab.start < 4096) {
    slab.buffer = b4a.allocUnsafe(slab.buffer.byteLength)
    slab.start = 0
  }
  return slab
}
const b4a = require('b4a')
const BlockDependencyStream = require('./block-dependency-stream.js')
const { core, store } = require('./keys.js')
const schema = require('../spec/hyperschema')

const CORESTORE_CORE = schema.getEncoding('@corestore/core')
const CORE_TREE_NODE = schema.getEncoding('@core/tree-node')
const EMPTY = b4a.alloc(0)

module.exports = {
  createBlockStream,
  createBitfieldStream,
  createUserDataStream,
  createCoreStream,
  createAliasStream,
  createDiscoveryKeyStream,
  createTreeNodeStream,
  createMarkStream,
  createLocalStream
}

function createCoreStream(db, view) {
  const start = store.coreStart()
  const end = store.coreEnd()

  const ite = view.iterator(db, start, end, false)

  ite._readableState.map = mapCore
  return ite
}

function createDiscoveryKeyStream(db, view, namespace) {
  const start = namespace ? store.coreByAliasStart(namespace) : store.coreStart()
  const end = namespace ? store.coreByAliasEnd(namespace) : store.coreEnd()

  const ite = view.iterator(db, start, end, false)

  ite._readableState.map = namespace ? mapNamespaceDiscoveryKeys : mapAllDiscoveryKeys
  return ite
}

function createAliasStream(db, view, namespace) {
  const start = store.coreByAliasStart(namespace)
  const end = store.coreByAliasEnd(namespace)

  const ite = view.iterator(db, start, end, false)

  ite._readableState.map = mapAlias
  return ite
}

function createBlockIterator(ptr, db, view, start, end, reverse) {
  if (ptr.dependencies.length > 0) {
    return new BlockDependencyStream(ptr, db, view, start, end, reverse)
  }

  const s = core.block(ptr.dataPointer, start)
  const e = core.block(ptr.dataPointer, end === -1 ? Infinity : end)
  return view.iterator(db, s, e, reverse)
}

function createBlockStream(
  ptr,
  db,
  view,
  { gt = -1, gte = gt + 1, lte = -1, lt = lte === -1 ? -1 : lte + 1, reverse = false } = {}
) {
  const ite = createBlockIterator(ptr, db, view, gte, lt, reverse)

  ite._readableState.map = mapBlock
  return ite
}

function createBitfieldStream(
  ptr,
  db,
  view,
  { gt = -1, gte = gt + 1, lte = -1, lt = lte === -1 ? -1 : lte + 1, reverse = false } = {}
) {
  const s = core.bitfield(ptr.dataPointer, gte, 0)
  const e = core.bitfield(ptr.dataPointer, lt === -1 ? Infinity : lt, 0)
  const ite = view.iterator(db, s, e, false)

  ite._readableState.map = mapBitfield
  return ite
}

// NOTE: this does not do dependency lookups atm
function createTreeNodeStream(
  ptr,
  db,
  view,
  { gt = -1, gte = gt + 1, lte = -1, lt = lte === -1 ? -1 : lte + 1, reverse = false } = {}
) {
  const s = core.tree(ptr.dataPointer, gte, 0)
  const e = core.tree(ptr.dataPointer, lt === -1 ? Infinity : lt, 0)
  const ite = view.iterator(db, s, e, false)

  ite._readableState.map = mapTreeNode
  return ite
}

function createUserDataStream(
  ptr,
  db,
  view,
  { gt = null, gte = '', lte = null, lt = null, reverse = false } = {}
) {
  if (gt !== null || lte !== null) {
    throw new Error('gt and lte not yet supported for user data streams')
  }

  const s = core.userData(ptr.dataPointer, gte)
  const e = lt === null ? core.userDataEnd(ptr.dataPointer) : core.userData(ptr.dataPointer, lt)
  const ite = view.iterator(db, s, e, false)

  ite._readableState.map = mapUserData
  return ite
}

function createMarkStream(
  ptr,
  db,
  view,
  { gt = -1, gte = gt + 1, lte = -1, lt = lte === -1 ? -1 : lte + 1, reverse = false } = {}
) {
  const s = core.mark(ptr.dataPointer, gte)
  const e = core.mark(ptr.dataPointer, lt === -1 ? Infinity : lt)
  const ite = view.iterator(db, s, e, reverse)

  ite._readableState.map = mapMark
  return ite
}

function createLocalStream(
  ptr,
  db,
  view,
  { gt = null, gte = EMPTY, lte = null, lt = null, reverse = false } = {}
) {
  if (gt !== null || lte !== null) throw new Error('gt and lte not yet supported for local streams')

  const s = core.local(ptr.dataPointer, gte)
  const e = lt === null ? core.localEnd(ptr.dataPointer) : core.local(ptr.dataPointer, lt)
  const ite = view.iterator(db, s, e, false)

  ite._readableState.map = mapLocal
  return ite
}

function mapBitfield(data) {
  const [index, type] = core.bitfieldIndexAndType(data.key)
  if (type !== 0) return null // ignore for now
  return { index, page: data.value }
}

function mapMark(data) {
  const index = core.markKey(data.key)
  return { index, page: data.value }
}

function mapLocal(data) {
  const key = core.localKey(data.key)
  return { key, value: data.value }
}

function mapUserData(data) {
  const key = core.userDataKey(data.key)
  return { key, value: data.value }
}

function mapCore(data) {
  const discoveryKey = store.discoveryKey(data.key)
  const core = CORESTORE_CORE.decode({
    start: 0,
    end: data.value.byteLength,
    buffer: data.value
  })
  return { discoveryKey, core }
}

function mapAllDiscoveryKeys(data) {
  return store.discoveryKey(data.key)
}

function mapNamespaceDiscoveryKeys(data) {
  return data.value
}

function mapAlias(data) {
  const alias = store.alias(data.key)
  return { alias, discoveryKey: data.value }
}

function mapBlock(data) {
  return { index: core.blockIndex(data.key), value: data.value }
}

function mapTreeNode(data) {
  return CORE_TREE_NODE.decode({
    start: 0,
    end: data.value.byteLength,
    buffer: data.value
  })
}
const schema = require('../spec/hyperschema')
const { store, core } = require('./keys.js')
const View = require('./view.js')
const b4a = require('b4a')
const flat = require('flat-tree')

const CORESTORE_HEAD = schema.getEncoding('@corestore/head')
const CORESTORE_CORE = schema.getEncoding('@corestore/core')

const CORE_AUTH = schema.getEncoding('@core/auth')
const CORE_SESSIONS = schema.getEncoding('@core/sessions')
const CORE_HEAD = schema.getEncoding('@core/head')
const CORE_TREE_NODE = schema.getEncoding('@core/tree-node')
const CORE_DEPENDENCY = schema.getEncoding('@core/dependency')
const CORE_HINTS = schema.getEncoding('@core/hints')

class CoreTX {
  constructor(core, db, view, changes) {
    if (db.snapshotted) throw new Error('Cannot open core tx on snapshot')
    this.core = core
    this.db = db
    this.view = view
    this.changes = changes
  }

  setAuth(auth) {
    this.changes.push([core.auth(this.core.corePointer), encode(CORE_AUTH, auth), null])
  }

  setSessions(sessions) {
    this.changes.push([core.sessions(this.core.corePointer), encode(CORE_SESSIONS, sessions), null])
  }

  setHead(head) {
    this.changes.push([core.head(this.core.dataPointer), encode(CORE_HEAD, head), null])
  }

  deleteHead() {
    this.changes.push([core.head(this.core.dataPointer), null, null])
  }

  setDependency(dep) {
    this.changes.push([core.dependency(this.core.dataPointer), encode(CORE_DEPENDENCY, dep), null])
  }

  setHints(hints) {
    this.changes.push([core.hints(this.core.dataPointer), encode(CORE_HINTS, hints), null])
  }

  putBlock(index, data) {
    this.changes.push([core.block(this.core.dataPointer, index), data, null])
  }

  deleteBlock(index) {
    this.changes.push([core.block(this.core.dataPointer, index), null, null])
  }

  deleteBlockRange(start, end) {
    this.changes.push([
      core.block(this.core.dataPointer, start),
      null,
      core.block(this.core.dataPointer, end === -1 ? Infinity : end)
    ])
  }

  putBitfieldPage(index, data) {
    this.changes.push([core.bitfield(this.core.dataPointer, index, 0), data, null])
  }

  deleteBitfieldPage(index) {
    this.changes.push([core.bitfield(this.core.dataPointer, index, 0), null, null])
  }

  deleteBitfieldPageRange(start, end) {
    this.changes.push([
      core.bitfield(this.core.dataPointer, start, 0),
      null,
      core.bitfield(this.core.dataPointer, end === -1 ? Infinity : end, 0)
    ])
  }

  putTreeNode(node) {
    this.changes.push([
      core.tree(this.core.dataPointer, node.index),
      encode(CORE_TREE_NODE, node),
      null
    ])
  }

  deleteTreeNode(index) {
    this.changes.push([core.tree(this.core.dataPointer, index), null, null])
  }

  deleteTreeNodeRange(start, end) {
    this.changes.push([
      core.tree(this.core.dataPointer, start),
      null,
      core.tree(this.core.dataPointer, end === -1 ? Infinity : end)
    ])
  }

  putUserData(key, value) {
    const buffer = typeof value === 'string' ? b4a.from(value) : value
    this.changes.push([core.userData(this.core.dataPointer, key), buffer, null])
  }

  deleteUserData(key) {
    this.changes.push([core.userData(this.core.dataPointer, key), null, null])
  }

  putMark(index, data) {
    this.changes.push([core.mark(this.core.dataPointer, index), data, null])
  }

  deleteMark(index) {
    this.changes.push([core.mark(this.core.dataPointer, index), null, null])
  }

  deleteMarkRange(start, end) {
    this.changes.push([
      core.mark(this.core.dataPointer, start),
      null,
      core.mark(this.core.dataPointer, end === -1 ? Infinity : end)
    ])
  }

  putLocal(key, value) {
    this.changes.push([core.local(this.core.dataPointer, key), value, null])
  }

  deleteLocal(key) {
    this.changes.push([core.local(this.core.dataPointer, key), null, null])
  }

  deleteLocalRange(start, end) {
    this.changes.push([
      core.local(this.core.dataPointer, start),
      null,
      end === null ? core.localEnd(this.core.dataPointer) : core.local(this.core.dataPointer, end)
    ])
  }

  flush() {
    const changes = this.changes
    if (changes === null) return Promise.resolve(!this.view)

    this.changes = null

    if (this.view) {
      this.view.apply(changes)
      return Promise.resolve(false)
    }

    return View.flush(changes, this.db)
  }
}

class CoreRX {
  constructor(core, db, view) {
    this.core = core
    this.read = db.read({ autoDestroy: true })
    this.view = view

    view.readStart()
  }

  static async getAuth(db, c) {
    return await decode(CORE_AUTH, await db.get(core.auth(c.corePointer)))
  }

  async getAuth() {
    return await decode(CORE_AUTH, await this.view.get(this.read, core.auth(this.core.corePointer)))
  }

  async getSessions() {
    return await decode(
      CORE_SESSIONS,
      await this.view.get(this.read, core.sessions(this.core.corePointer))
    )
  }

  static async getHead(db, c) {
    return await decode(CORE_HEAD, await db.get(core.head(c.dataPointer)))
  }

  async getHead() {
    return await decode(CORE_HEAD, await this.view.get(this.read, core.head(this.core.dataPointer)))
  }

  async getDependency() {
    return await decode(
      CORE_DEPENDENCY,
      await this.view.get(this.read, core.dependency(this.core.dataPointer))
    )
  }

  static async getHints(db, c) {
    return await decode(CORE_HINTS, await db.get(core.hints(c.dataPointer)))
  }

  async getHints() {
    return await decode(
      CORE_HINTS,
      await this.view.get(this.read, core.hints(this.core.dataPointer))
    )
  }

  getBlock(index) {
    const dep = findBlockDependency(this.core.dependencies, index)
    const data = dep === null ? this.core.dataPointer : dep.dataPointer
    return this.view.get(this.read, core.block(data, index))
  }

  getBitfieldPage(index) {
    return this.view.get(this.read, core.bitfield(this.core.dataPointer, index, 0))
  }

  async getTreeNode(index) {
    const dep = findTreeDependency(this.core.dependencies, index)
    const data = dep === null ? this.core.dataPointer : dep.dataPointer
    return decode(CORE_TREE_NODE, await this.view.get(this.read, core.tree(data, index)))
  }

  async hasTreeNode(index) {
    return (await this.getTreeNode(index)) !== null
  }

  getUserData(key) {
    return this.view.get(this.read, core.userData(this.core.dataPointer, key))
  }

  getMark(index) {
    return this.view.get(this.read, core.mark(this.core.dataPointer, index))
  }

  getLocal(key) {
    return this.view.get(this.read, core.local(this.core.dataPointer, key))
  }

  tryFlush() {
    this.read.tryFlush()
    this._free()
  }

  destroy() {
    this.read.destroy()
    this._free()
  }

  _free() {
    if (this.view === null) return
    this.view.readStop()
    this.view = null
  }
}

class CorestoreTX {
  constructor(view) {
    this.view = view
    this.changes = []
  }

  setHead(head) {
    this.changes.push([store.head(), encode(CORESTORE_HEAD, head), null])
  }

  setCoreHints(c, hints) {
    this.changes.push([core.hints(c.dataPointer), encode(CORE_HINTS, hints), null])
  }

  putCore(discoveryKey, ptr) {
    this.changes.push([store.core(discoveryKey), encode(CORESTORE_CORE, ptr), null])
  }

  putCoreByAlias(alias, discoveryKey) {
    this.changes.push([store.coreByAlias(alias), discoveryKey, null])
  }

  clear() {
    const [start, end] = store.clear()
    this.changes.push([start, null, end])
  }

  apply() {
    if (this.changes === null) return
    this.view.apply(this.changes)
    this.changes = null
  }
}

class CorestoreRX {
  constructor(db, view) {
    this.read = db.read({ autoDestroy: true })
    this.view = view

    view.readStart()
  }

  async getHead() {
    return decode(CORESTORE_HEAD, await this.view.get(this.read, store.head()))
  }

  async getCore(discoveryKey) {
    return decode(CORESTORE_CORE, await this.view.get(this.read, store.core(discoveryKey)))
  }

  getCoreByAlias(alias) {
    return this.view.get(this.read, store.coreByAlias(alias))
  }

  tryFlush() {
    this.read.tryFlush()
    this._free()
  }

  destroy() {
    this.read.destroy()
    this._free()
  }

  _free() {
    if (this.view === null) return
    this.view.readStop()
    this.view = null
  }
}

module.exports = { CorestoreTX, CorestoreRX, CoreTX, CoreRX }

function findBlockDependency(dependencies, index) {
  for (let i = 0; i < dependencies.length; i++) {
    const dep = dependencies[i]
    if (index < dep.length) return dep
  }

  return null
}

function findTreeDependency(dependencies, index) {
  for (let i = 0; i < dependencies.length; i++) {
    const dep = dependencies[i]
    if (flat.rightSpan(index) <= (dep.length - 1) * 2) return dep
  }

  return null
}

function decode(enc, buffer) {
  if (buffer === null) return null
  return enc.decode({ start: 0, end: buffer.byteLength, buffer })
}

function encode(enc, m) {
  // TODO: use fancy slab for small messages
  const state = { start: 0, end: 0, buffer: null }
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}
const { Readable, getStreamError } = require('streamx')
const CloseErrorStream = require('./close-error-stream.js')
const b4a = require('b4a')

class OverlayStream extends Readable {
  constructor(stream, start, end, reverse, changes, cleared) {
    super()

    this.start = start
    this.end = end
    this.reverse = reverse
    this.changes = changes
    this.cleared = cleared
    this.change = 0
    this.range = 0

    this._stream = stream
    this._drained = false

    this._stream.on('readable', this._drainMaybe.bind(this))
    this._stream.on('error', noop)
    this._stream.on('close', this._onclose.bind(this))
  }

  _drainMaybe() {
    if (this._drained === true) return
    this._drained = this._onreadable()
  }

  _onclose() {
    if (this.destroying) return

    const err = getStreamError(this._stream)

    if (err !== null) {
      this.destroy(err)
      return
    }

    while (this.change < this.changes.length) {
      const c = this.changes[this.change++]
      const key = c[0]
      const value = c[1]

      if (value !== null && this._inRange(key)) this.push({ key, value })
    }

    this.push(null)
    this._stream = null
  }

  _onreadable() {
    let data = this._stream.read()
    if (data === null) return false

    let drained = false

    do {
      if (this._push(data) === true) drained = true
      data = this._stream.read()
    } while (data !== null)

    return drained
  }

  _read(cb) {
    this._drained = this._onreadable()
    cb(null)
  }

  _predestroy() {
    this._stream.destroy()
  }

  _push(entry) {
    const key = entry.key

    while (this.range < this.cleared.length) {
      const c = this.cleared[this.range]

      // we moved past the range
      if (this.reverse ? b4a.compare(key, c[0]) < 0 : b4a.compare(c[2], key) <= 0) {
        this.range++
        continue
      }

      // we didnt move past and are in, drop
      if (b4a.compare(c[0], key) <= 0 && b4a.compare(key, c[2]) < 0) {
        return false
      }

      break
    }

    let updated = false

    while (this.change < this.changes.length) {
      const c = this.changes[this.change]
      const key = c[0]
      const value = typeof c[1] === 'string' ? b4a.from(c[1]) : c[1]
      const cmp = b4a.compare(key, entry.key)

      // same value, if not deleted, return new one
      if (cmp === 0) {
        this.change++
        if (value === null || this._inRange(key) === false) return updated
        this.push({ key, value })
        return true
      }

      // we moved past the change, push it
      if (this.reverse ? cmp > 0 : cmp < 0) {
        this.change++
        if (value === null || this._inRange(key) === false) continue
        this.push({ key, value })
        updated = true
        continue
      }

      this.push(entry)
      return true
    }

    this.push(entry)
    return true
  }

  _inRange(key) {
    return b4a.compare(this.start, key) <= 0 && b4a.compare(key, this.end) < 0
  }
}

class Overlay {
  constructor() {
    this.indexed = 0
    this.changes = null
    this.cleared = null
    this.reverse = false
  }

  update(view, reverse) {
    if (view.indexed === this.indexed) return

    const changes = view.map === null ? [] : [...view.map.values()]
    const cleared = view.cleared === null ? [] : view.cleared.slice(0)

    const cmp = reverse ? cmpChangeReverse : cmpChange

    changes.sort(cmp)
    cleared.sort(cmp)

    this.indexed = view.indexed
    this.changes = changes
    this.cleared = cleared
    this.reverse = reverse
  }

  createStream(stream, start, end, reverse) {
    return new OverlayStream(
      stream,
      start,
      end,
      reverse,
      this.reverse === reverse ? this.changes : reverseArray(this.changes),
      this.reverse === reverse ? this.cleared : reverseArray(this.cleared)
    )
  }
}

class View {
  constructor() {
    this.map = null
    this.indexed = 0
    this.changes = null
    this.cleared = null
    this.overlay = null
    this.snap = null
    this.readers = 0
  }

  snapshot() {
    if (this._attached()) return this.snap.snapshot()

    const snap = new View()

    snap.map = this.map
    snap.indexed = this.indexed
    snap.changes = this.changes
    snap.cleared = this.cleared

    if (this._frozen()) return snap

    this.readers++
    snap.snap = this

    return snap
  }

  readStart() {
    if (this.snap !== null) this.readers++
  }

  readStop() {
    if (this.snap !== null && --this.readers === 0) this.snap.readers--
  }

  size() {
    return this.changes === null ? 0 : this.changes.length
  }

  updated() {
    return this.changes === null
  }

  get(read, key) {
    return this.changes === null ? read.get(key) : this._indexAndGet(read, key)
  }

  reset() {
    this.indexed = 0
    this.snap = this.map = this.changes = this.cleared = this.overlay = null
  }

  iterator(db, start, end, reverse) {
    if (dbClosing(db)) return new CloseErrorStream(new Error('RocksDB session is closed'))

    const stream = db.iterator({ gte: start, lt: end, reverse })
    if (this.changes === null) return stream

    this._index()

    if (this.overlay === null) this.overlay = new Overlay()
    this.overlay.update(this, reverse)
    return this.overlay.createStream(stream, start, end, reverse)
  }

  _indexAndGet(read, key) {
    this._index()
    const change = this.map.get(b4a.toString(key, 'hex'))

    if (change === undefined) {
      return this.cleared === null ? read.get(key) : this._readAndMaybeDrop(read, key)
    }

    return Promise.resolve(change[1])
  }

  async _readAndMaybeDrop(read, key) {
    const cleared = this.cleared // in case its cleared
    const value = await read.get(key)
    if (value === null) return null

    for (let i = 0; i < cleared.length; i++) {
      const c = cleared[i]
      // check if in range
      if (b4a.compare(c[0], key) <= 0 && b4a.compare(key, c[2]) < 0) return null
    }

    return value
  }

  _attached() {
    return this.snap !== null && this.changes === this.snap.changes
  }

  _frozen() {
    return this.changes === null || (this.snap !== null && this.changes !== this.snap.changes)
  }

  _index() {
    // if we are a snap and we are still attached (ie no mutations), simply copy the refs
    if (this._attached()) {
      this.snap._index()
      this.map = this.snap.map
      this.cleared = this.snap.cleared
      this.indexed = this.snap.indexed
      return
    }

    if (this.map === null) this.map = new Map()
    if (this.changes.length === this.indexed) return

    while (this.indexed < this.changes.length) {
      const c = this.changes[this.indexed++]

      if (c[2] === null) this.map.set(b4a.toString(c[0], 'hex'), c)
      else this._indexRange(c)
    }
  }

  _indexRange(range) {
    const s = b4a.toString(range[0], 'hex')
    const e = b4a.toString(range[2], 'hex')

    for (const [key, c] of this.map) {
      if (s <= key && key < e) this.map.set(key, [c[0], null, null])
    }

    if (this.cleared === null) this.cleared = []
    this.cleared.push(range)
  }

  apply(changes) {
    if (this.snap !== null) throw new Error('Illegal to push changes to a snapshot')

    if (this.readers !== 0 && this.changes !== null) {
      this.changes = this.changes.slice(0)
      this.cleared = this.cleared === null ? null : this.cleared.slice(0)
      this.map = this.map === null ? null : new Map([...this.map])
    }

    if (this.changes === null) {
      this.changes = changes
      return
    }

    for (let i = 0; i < changes.length; i++) {
      this.changes.push(changes[i])
    }
  }

  static async flush(changes, db) {
    if (changes === null) return true

    const w = db.write({ autoDestroy: true })

    for (const [start, value, end] of changes) {
      if (end !== null) w.tryDeleteRange(start, end)
      else if (value !== null) w.tryPut(start, value)
      else w.tryDelete(start)
    }

    await w.flush()

    return true
  }
}

module.exports = View

function cmpChange(a, b) {
  const c = b4a.compare(a[0], b[0])
  return c === 0 ? b4a.compare(a[2], b[2]) : c
}

function cmpChangeReverse(a, b) {
  return cmpChange(b, a)
}

function noop() {}

function reverseArray(list) {
  const r = new Array(list.length)
  for (let i = 0; i < list.length; i++) r[r.length - 1 - i] = list[i]
  return r
}

// TODO: expose from rocks instead
function dbClosing(db) {
  return db._state.closing || db._index === -1
}
const fs = require('fs')
const path = require('path')
const { Readable } = require('streamx')
const b4a = require('b4a')
const flat = require('flat-tree')
const crypto = require('hypercore-crypto')
const c = require('compact-encoding')
const m = require('./messages.js')
const View = require('../../lib/view.js')
const { CorestoreTX, CoreTX, CorestoreRX } = require('../../lib/tx.js')

const EMPTY_NODE = b4a.alloc(40)
const EMPTY_PAGE = b4a.alloc(4096)

let TREE_01_SKIP = null
let TREE_04_SKIP = null
let TREE_16_SKIP = null

class CoreListStream extends Readable {
  constructor (storage) {
    super()

    this.storage = storage
    this.stack = []
  }

  async _open (cb) {
    for (const a of await readdir(path.join(this.storage, 'cores'))) {
      for (const b of await readdir(path.join(this.storage, 'cores', a))) {
        for (const dkey of await readdir(path.join(this.storage, 'cores', a, b))) {
          this.stack.push(path.join(this.storage, 'cores', a, b, dkey))
        }
      }
    }

    cb(null)
  }

  async _read (cb) {
    while (true) {
      const next = this.stack.pop()
      if (!next) {
        this.push(null)
        break
      }

      const oplog = path.join(next, 'oplog')
      const result = await readOplog(oplog)
      if (!result) continue

      this.push(result)
      break
    }

    cb(null)
  }
}

function decodeOplogHeader (state) {
  c.uint32.decode(state) // cksum, ignore for now

  const l = c.uint32.decode(state)
  const length = l >> 2
  const headerBit = l & 1
  const partialBit = l & 2

  if (state.end - state.start < length) return null

  const end = state.start + length
  const result = { header: headerBit, partial: partialBit !== 0, byteLength: length + 8, message: null }

  try {
    result.message = m.oplog.header.decode({ start: state.start, end, buffer: state.buffer })
  } catch {
    return null
  }

  state.start = end
  return result
}

function decodeOplogEntry (state) {
  if (state.end - state.start < 8) return null

  c.uint32.decode(state) // cksum, ignore for now

  const l = c.uint32.decode(state)
  const length = l >>> 2
  const headerBit = l & 1
  const partialBit = l & 2

  if (state.end - state.start < length) return null

  const end = state.start + length

  const result = { header: headerBit, partial: partialBit !== 0, byteLength: length + 8, message: null }

  try {
    result.message = m.oplog.entry.decode({ start: state.start, end, buffer: state.buffer })
  } catch {
    return null
  }

  state.start = end

  return result
}

module.exports = { store, core }

async function store (storage, { version, dryRun = true, gc = true }) {
  const stream = new CoreListStream(storage.path)
  const view = new View()

  const tx = new CorestoreTX(view)
  const head = await storage._getHead(view)
  const primaryKeyFile = path.join(storage.path, 'primary-key')

  const primaryKey = await readFile(primaryKeyFile)

  if (!head.seed) head.seed = primaryKey

  for await (const data of stream) {
    const key = data.header.key
    const discoveryKey = crypto.discoveryKey(data.header.key)
    const files = getFiles(data.path)

    if (head.defaultDiscoveryKey === null) head.defaultDiscoveryKey = discoveryKey

    const core = {
      version: 0, // need later migration
      corePointer: head.allocated.cores++,
      dataPointer: head.allocated.datas++,
      alias: null
    }

    const ptr = { version: 0, corePointer: core.corePointer, dataPointer: core.dataPointer, dependencies: [] }
    const ctx = new CoreTX(ptr, storage.db, view, [])
    const userData = new Map()
    const treeNodes = new Map()

    const auth = {
      key,
      discoveryKey,
      manifest: data.header.manifest,
      keyPair: data.header.keyPair,
      encryptionKey: null
    }

    const tree = {
      length: 0,
      fork: 0,
      rootHash: null,
      signature: null
    }

    if (data.header.tree && data.header.tree.length) {
      tree.length = data.header.tree.length
      tree.fork = data.header.tree.fork
      tree.rootHash = data.header.tree.rootHash
      tree.signature = data.header.tree.signature
    }

    for (const { key, value } of data.header.userData) {
      userData.set(key, value)
    }

    for (const e of data.entries) {
      if (e.userData) userData.set(e.userData.key, e.userData.value)

      if (e.treeNodes) {
        for (const node of e.treeNodes) {
          treeNodes.set(node.index, node)
          ctx.putTreeNode(node)
        }
      }

      if (e.treeUpgrade) {
        if (e.treeUpgrade.ancestors !== tree.length) {
          throw new Error('Unflushed truncations not migrate-able atm')
        }

        tree.length = e.treeUpgrade.length
        tree.fork = e.treeUpgrade.fork
        tree.rootHash = null
        tree.signature = e.treeUpgrade.signature
      }
    }

    if (userData.has('corestore/name') && userData.has('corestore/namespace')) {
      core.alias = {
        name: b4a.toString(userData.get('corestore/name')),
        namespace: userData.get('corestore/namespace')
      }
      userData.delete('corestore/name')
      userData.delete('corestore/namespace')
    }

    for (const [key, value] of userData) {
      ctx.putUserData(key, value)
    }

    ctx.setAuth(auth)

    const getTreeNode = (index) => (treeNodes.get(index) || getTreeNodeFromFile(files.tree, index))

    if (tree.length) {
      if (tree.rootHash === null) tree.rootHash = crypto.tree(await getRoots(tree.length, getTreeNode))
      ctx.setHead(tree)
    }

    tx.putCore(discoveryKey, core)
    if (core.alias) tx.putCoreByAlias(core.alias, discoveryKey)

    await ctx.flush()
  }

  head.version = version
  tx.setHead(head)
  tx.apply()

  if (dryRun) return

  await View.flush(view.changes, storage.db)

  if (gc) await rm(primaryKeyFile)
}

class BlockSlicer {
  constructor (filename) {
    this.stream = fs.createReadStream(filename)
    this.closed = new Promise(resolve => this.stream.once('close', resolve))
    this.offset = 0
    this.overflow = null
  }

  async take (offset, size) {
    let buffer = null
    if (offset < this.offset) throw new Error('overread')

    while (true) {
      let data = null

      if (this.overflow) {
        data = this.overflow
        this.overflow = null
      } else {
        data = this.stream.read()

        if (!data) {
          await new Promise(resolve => this.stream.once('readable', resolve))
          continue
        }
      }

      let chunk = null

      if (this.offset === offset || buffer) {
        chunk = data
      } else if (this.offset + data.byteLength > offset) {
        chunk = data.subarray(offset - this.offset)
      }

      this.offset += data.byteLength
      if (!chunk) continue

      if (buffer) buffer = b4a.concat([buffer, chunk])
      else buffer = chunk

      if (buffer.byteLength < size) continue

      const result = buffer.subarray(0, size)
      this.overflow = size === buffer.byteLength ? null : buffer.subarray(result.byteLength)
      this.offset -= (this.overflow ? this.overflow.byteLength : 0)
      return result
    }
  }

  close () {
    this.stream.on('error', noop)
    this.stream.destroy()
    return this.closed
  }
}

class TreeSlicer {
  constructor () {
    this.buffer = null
    this.offset = 0
  }

  get size () {
    return this.buffer === null ? 0 : this.buffer.byteLength
  }

  push (data) {
    if (this.buffer === null) this.buffer = data
    else this.buffer = b4a.concat([this.buffer, data])
    this.offset += data.byteLength
  }

  skip () {
    let skipped = 0

    if (TREE_01_SKIP === null) {
      TREE_16_SKIP = b4a.alloc(16 * 40 * 100)
      TREE_04_SKIP = TREE_16_SKIP.subarray(0, 4 * 40 * 100)
      TREE_01_SKIP = TREE_16_SKIP.subarray(0, 1 * 40 * 100)
    }

    while (true) {
      if (this.buffer.byteLength >= TREE_16_SKIP.byteLength) {
        if (b4a.equals(this.buffer.subarray(0, TREE_16_SKIP.byteLength), TREE_16_SKIP)) {
          this.buffer = this.buffer.subarray(TREE_16_SKIP.byteLength)
          skipped += 1600
          continue
        }
      }

      if (this.buffer.byteLength >= TREE_04_SKIP.byteLength) {
        if (b4a.equals(this.buffer.subarray(0, TREE_04_SKIP.byteLength), TREE_04_SKIP)) {
          this.buffer = this.buffer.subarray(TREE_04_SKIP.byteLength)
          skipped += 400
          continue
        }
      }

      if (this.buffer.byteLength >= TREE_01_SKIP.byteLength) {
        if (b4a.equals(this.buffer.subarray(0, TREE_01_SKIP.byteLength), TREE_01_SKIP)) {
          this.buffer = this.buffer.subarray(TREE_01_SKIP.byteLength)
          skipped += 100
          continue
        }
      }
      break
    }

    return skipped
  }

  take () {
    const len = 40

    if (len <= this.size) {
      const chunk = this.buffer.subarray(0, len)
      this.buffer = this.buffer.subarray(len)
      return chunk
    }

    return null
  }
}

async function core (core, { version, dryRun = true, gc = true }) {
  if (dryRun) return // dryRun mode not supported atm

  const rx = core.read()

  const promises = [rx.getAuth(), rx.getHead()]
  rx.tryFlush()

  const [auth, head] = await Promise.all(promises)

  if (!auth) return

  const dk = b4a.toString(auth.discoveryKey, 'hex')
  const files = getFiles(path.join(core.store.path, 'cores', dk.slice(0, 2), dk.slice(2, 4), dk))

  if (head === null || head.length === 0) {
    await commitCoreMigration(auth, core, version)
    if (gc) await runGC()
    return // no data
  }

  const oplog = await readOplog(files.oplog)
  if (!oplog) {
    const writable = !!auth.keyPair

    if (writable) {
      throw new Error('No oplog available writable core for ' + files.oplog + ', length = ' + (head ? head.length : 0))
    }

    // if not writable, just nuke it to recover, some bad state happened here, prop corruption from earlier versions
    const w = core.write()

    w.deleteBlockRange(0, -1)
    w.deleteTreeNodeRange(0, -1)
    w.deleteBitfieldPageRange(0, -1)
    w.deleteHead()

    await w.flush()

    await commitCoreMigration(auth, core, version)
    if (gc) await runGC()
    return // no data
  }

  const treeData = new TreeSlicer()

  let treeIndex = 0

  if (await exists(files.tree)) {
    for await (const data of fs.createReadStream(files.tree)) {
      treeData.push(data)

      let write = null

      while (true) {
        const skip = treeData.skip()
        treeIndex += skip

        const buf = treeData.take()
        if (buf === null) break

        const index = treeIndex++
        if (b4a.equals(buf, EMPTY_NODE)) continue

        if (write === null) write = core.write()
        write.putTreeNode(decodeTreeNode(index, buf))
      }

      if (write !== null) await write.flush()
    }
  }

  const buf = []
  if (await exists(files.bitfield)) {
    for await (const data of fs.createReadStream(files.bitfield)) {
      buf.push(data)
    }
  }

  let bitfield = b4a.concat(buf)
  if (bitfield.byteLength & 4095) bitfield = b4a.concat([bitfield, b4a.alloc(4096 - (bitfield.byteLength & 4095))])

  const pages = new Map()
  const headerBits = new Map()

  const roots = await getRootsFromStorage(core, head.length)

  for (const e of oplog.entries) {
    if (!e.bitfield) continue

    for (let i = 0; i < e.bitfield.length; i++) {
      headerBits.set(i + e.bitfield.start, !e.bitfield.drop)
    }
  }

  let batch = []

  const cache = new Map()
  const blocks = new BlockSlicer(files.data)

  for (const index of allBits(bitfield)) {
    if (headerBits.get(index) === false) continue
    if (index >= head.length) continue

    setBitInPage(index)

    batch.push(index)
    if (batch.length < 1024) continue

    await writeBlocksBatch()
    continue
  }

  if (batch.length) await writeBlocksBatch()

  await blocks.close()

  const w = core.write()

  for (const [index, bit] of headerBits) {
    if (!bit) continue
    if (index >= head.length) continue

    setBitInPage(index)

    const blk = await getBlockFromFile(files.data, core, index, roots, cache)
    w.putBlock(index, blk)
  }

  for (const [index, page] of pages) {
    w.putBitfieldPage(index, b4a.from(page.buffer, page.byteOffset, page.byteLength))
  }

  await w.flush()

  let contiguousLength = 0
  for await (const data of core.createBlockStream()) {
    if (data.index === contiguousLength) contiguousLength++
    else break
  }

  if (contiguousLength) {
    const w = core.write()
    w.setHints({ contiguousLength })
    await w.flush()
  }

  await commitCoreMigration(auth, core, version)

  if (gc) await runGC()

  async function runGC () {
    await rm(files.path)
    await rmdir(path.join(files.path, '..'))
    await rmdir(path.join(files.path, '../..'))
    await rmdir(path.join(core.store.path, 'cores'))
  }

  function setBitInPage (index) {
    const n = index & 32767
    const p = (index - n) / 32768

    let page = pages.get(p)

    if (!page) {
      page = new Uint32Array(1024)
      pages.set(p, page)
    }

    const o = n & 31
    const b = (n - o) / 32
    const v = 1 << o

    page[b] |= v
  }

  async function writeBlocksBatch () {
    const read = core.read()
    const promises = []
    for (const index of batch) promises.push(getByteRangeFromStorage(read, 2 * index, roots, cache))
    read.tryFlush()

    const r = await Promise.all(promises)
    const tx = core.write()

    for (let i = 0; i < r.length; i++) {
      const index = batch[i]
      const [offset, size] = r[i]

      const blk = await blocks.take(offset, size)
      tx.putBlock(index, blk)
    }

    batch = []
    if (cache.size > 16384) cache.clear()

    await tx.flush()
  }
}

async function commitCoreMigration (auth, core, version) {
  const view = new View()
  const rx = new CorestoreRX(core.db, view)

  const storeCorePromise = rx.getCore(auth.discoveryKey)
  rx.tryFlush()

  const storeCore = await storeCorePromise

  storeCore.version = version

  const tx = new CorestoreTX(view)

  tx.putCore(auth.discoveryKey, storeCore)
  tx.apply()

  await View.flush(view.changes, core.db)
}

async function getBlockFromFile (file, core, index, roots, cache) {
  const rx = core.read()
  const promise = getByteRangeFromStorage(rx, 2 * index, roots, cache)
  rx.tryFlush()
  const [offset, size] = await promise

  return new Promise(function (resolve) {
    readAll(file, size, offset, function (err, buf) {
      if (err) return resolve(null)
      resolve(buf)
    })
  })
}

function getFiles (dir) {
  return {
    path: dir,
    oplog: path.join(dir, 'oplog'),
    data: path.join(dir, 'data'),
    tree: path.join(dir, 'tree'),
    bitfield: path.join(dir, 'bitfield')
  }
}

async function getRootsFromStorage (core, length) {
  const all = []
  const rx = core.read()
  for (const index of flat.fullRoots(2 * length)) {
    all.push(rx.getTreeNode(index))
  }
  rx.tryFlush()
  return Promise.all(all)
}

async function getRoots (length, getTreeNode) {
  const all = []
  for (const index of flat.fullRoots(2 * length)) {
    all.push(await getTreeNode(index))
  }
  return all
}

function getCached (read, cache, index) {
  if (cache.has(index)) return cache.get(index)
  const p = read.getTreeNode(index)
  cache.set(index, p)
  return p
}

async function getByteRangeFromStorage (read, index, roots, cache) {
  const promises = [getCached(read, cache, index), getByteOffsetFromStorage(read, index, roots, cache)]
  const [node, offset] = await Promise.all(promises)
  if (!node) throw new Error('Node not found during migration: ' + index)
  return [offset, node.size]
}

async function getByteOffsetFromStorage (rx, index, roots, cache) {
  if (index === 0) return 0
  if ((index & 1) === 1) index = flat.leftSpan(index)

  let head = 0
  let offset = 0

  for (const node of roots) { // all async ticks happen once we find the root so safe
    head += 2 * ((node.index - head) + 1)

    if (index >= head) {
      offset += node.size
      continue
    }

    const ite = flat.iterator(node.index)
    const promises = []

    while (ite.index !== index) {
      if (index < ite.index) {
        ite.leftChild()
      } else {
        promises.push(getCached(rx, cache, ite.leftChild()))
        ite.sibling()
      }
    }

    const nodes = await Promise.all(promises)
    for (const node of nodes) offset += node.size

    return offset
  }

  throw new Error('Failed to find offset')
}

function decodeTreeNode (index, buf) {
  return { index, size: c.decode(c.uint64, buf), hash: buf.subarray(8) }
}

async function getTreeNodeFromFile (file, index) {
  return new Promise(function (resolve) {
    readAll(file, 40, index * 40, function (err, buf) {
      if (err) return resolve(null)
      resolve(decodeTreeNode(index, buf))
    })
  })
}

function readAll (filename, length, pos, cb) {
  const buf = b4a.alloc(length)

  fs.open(filename, 'r', function (err, fd) {
    if (err) return cb(err)

    let offset = 0

    fs.read(fd, buf, offset, buf.byteLength, pos, function loop (err, read) {
      if (err) return done(err)
      if (read === 0) return done(new Error('Partial read'))
      offset += read
      if (offset === buf.byteLength) return done(null, buf)
      fs.read(fd, offset, buf.byteLength - offset, buf, pos + offset, loop)
    })

    function done (err, value) {
      fs.close(fd, () => cb(err, value))
    }
  })
}

async function readdir (dir) {
  try {
    return await fs.promises.readdir(dir)
  } catch {
    return []
  }
}

async function exists (file) {
  try {
    await fs.promises.stat(file)
    return true
  } catch {
    return false
  }
}

async function readFile (file) {
  try {
    return await fs.promises.readFile(file)
  } catch {
    return null
  }
}

async function rm (dir) {
  try {
    await fs.promises.rm(dir, { recursive: true })
  } catch {}
}

async function rmdir (dir) {
  try {
    await fs.promises.rmdir(dir)
  } catch {}
}

function * allBits (buffer) {
  for (let i = 0; i < buffer.byteLength; i += EMPTY_PAGE.byteLength) {
    const page = buffer.subarray(i, i + EMPTY_NODE.byteLength)
    if (b4a.equals(page, EMPTY_PAGE)) continue

    const view = new Uint32Array(page.buffer, page.byteOffset, EMPTY_PAGE.byteLength / 4)

    for (let j = 0; j < view.length; j++) {
      const n = view[j]
      if (n === 0) continue

      for (let k = 0; k < 32; k++) {
        const m = 1 << k
        if (n & m) yield i * 8 + j * 32 + k
      }
    }
  }
}

function readOplog (oplog) {
  return new Promise(function (resolve) {
    fs.readFile(oplog, function (err, buffer) {
      if (err) return resolve(null)

      const state = { start: 0, end: buffer.byteLength, buffer }
      const headers = [1, 0]

      const h1 = decodeOplogHeader(state)
      state.start = 4096

      const h2 = decodeOplogHeader(state)
      state.start = 4096 * 2

      if (!h1 && !h2) return resolve(null)

      if (h1 && !h2) {
        headers[0] = h1.header
        headers[1] = h1.header
      } else if (!h1 && h2) {
        headers[0] = (h2.header + 1) & 1
        headers[1] = h2.header
      } else {
        headers[0] = h1.header
        headers[1] = h2.header
      }

      const header = (headers[0] + headers[1]) & 1
      const result = { path: path.dirname(oplog), header: null, entries: [] }
      const decoded = []

      result.header = header ? h2.message : h1.message

      if (result.header.external) {
        fs.readFile(path.join(oplog, '../header'), function (err, buffer) {
          if (err) return resolve(null)
          const start = result.header.external.start
          const end = start + result.header.external.length
          result.header = m.oplog.header.decode({ buffer, start, end })
          finish()
        })
        return
      }

      finish()

      function finish () {
        while (true) {
          const entry = decodeOplogEntry(state)
          if (!entry) break
          if (entry.header !== header) break

          decoded.push(entry)
        }

        while (decoded.length > 0 && decoded[decoded.length - 1].partial) decoded.pop()

        for (const e of decoded) {
          result.entries.push(e.message)
        }

        resolve(result)
      }
    })
  })
}

function noop () {}
// needed here for compat, copied from old hypercore, do not change this

const c = require('compact-encoding')
const b4a = require('b4a')

const EMPTY = b4a.alloc(0)
const DEFAULT_NAMESPACE = b4a.from('4144eea531e483d54e0c14f4ca68e0644f355343ff6fcb0f005200e12cd747cb', 'hex')

const hashes = {
  preencode (state, m) {
    state.end++ // small uint
  },
  encode (state, m) {
    if (m === 'blake2b') {
      c.uint.encode(state, 0)
      return
    }

    throw new Error('Unknown hash: ' + m)
  },
  decode (state) {
    const n = c.uint.decode(state)
    if (n === 0) return 'blake2b'
    throw new Error('Unknown hash id: ' + n)
  }
}

const signatures = {
  preencode (state, m) {
    state.end++ // small uint
  },
  encode (state, m) {
    if (m === 'ed25519') {
      c.uint.encode(state, 0)
      return
    }

    throw new Error('Unknown signature: ' + m)
  },
  decode (state) {
    const n = c.uint.decode(state)
    if (n === 0) return 'ed25519'
    throw new Error('Unknown signature id: ' + n)
  }
}

const signer = {
  preencode (state, m) {
    signatures.preencode(state, m.signature)
    c.fixed32.preencode(state, m.namespace)
    c.fixed32.preencode(state, m.publicKey)
  },
  encode (state, m) {
    signatures.encode(state, m.signature)
    c.fixed32.encode(state, m.namespace)
    c.fixed32.encode(state, m.publicKey)
  },
  decode (state) {
    return {
      signature: signatures.decode(state),
      namespace: c.fixed32.decode(state),
      publicKey: c.fixed32.decode(state)
    }
  }
}

const signerArray = c.array(signer)

const prologue = {
  preencode (state, p) {
    c.fixed32.preencode(state, p.hash)
    c.uint.preencode(state, p.length)
  },
  encode (state, p) {
    c.fixed32.encode(state, p.hash)
    c.uint.encode(state, p.length)
  },
  decode (state) {
    return {
      hash: c.fixed32.decode(state),
      length: c.uint.decode(state)
    }
  }
}

const manifestv0 = {
  preencode (state, m) {
    hashes.preencode(state, m.hash)
    state.end++ // type

    if (m.prologue && m.signers.length === 0) {
      c.fixed32.preencode(state, m.prologue.hash)
      return
    }

    if (m.quorum === 1 && m.signers.length === 1 && !m.allowPatch) {
      signer.preencode(state, m.signers[0])
    } else {
      state.end++ // flags
      c.uint.preencode(state, m.quorum)
      signerArray.preencode(state, m.signers)
    }
  },
  encode (state, m) {
    hashes.encode(state, m.hash)

    if (m.prologue && m.signers.length === 0) {
      c.uint.encode(state, 0)
      c.fixed32.encode(state, m.prologue.hash)
      return
    }

    if (m.quorum === 1 && m.signers.length === 1 && !m.allowPatch) {
      c.uint.encode(state, 1)
      signer.encode(state, m.signers[0])
    } else {
      c.uint.encode(state, 2)
      c.uint.encode(state, m.allowPatch ? 1 : 0)
      c.uint.encode(state, m.quorum)
      signerArray.encode(state, m.signers)
    }
  },
  decode (state) {
    const hash = hashes.decode(state)
    const type = c.uint.decode(state)

    if (type > 2) throw new Error('Unknown type: ' + type)

    if (type === 0) {
      return {
        version: 0,
        hash,
        allowPatch: false,
        quorum: 0,
        signers: [],
        prologue: {
          hash: c.fixed32.decode(state),
          length: 0
        }
      }
    }

    if (type === 1) {
      return {
        version: 0,
        hash,
        allowPatch: false,
        quorum: 1,
        signers: [signer.decode(state)],
        prologue: null
      }
    }

    const flags = c.uint.decode(state)

    return {
      version: 0,
      hash,
      allowPatch: (flags & 1) !== 0,
      quorum: c.uint.decode(state),
      signers: signerArray.decode(state),
      prologue: null
    }
  }
}

const manifest = exports.manifest = {
  preencode (state, m) {
    state.end++ // version
    if (m.version === 0) return manifestv0.preencode(state, m)

    state.end++ // flags
    hashes.preencode(state, m.hash)

    c.uint.preencode(state, m.quorum)
    signerArray.preencode(state, m.signers)
    if (m.prologue) prologue.preencode(state, m.prologue)
  },
  encode (state, m) {
    c.uint.encode(state, m.version)
    if (m.version === 0) return manifestv0.encode(state, m)

    c.uint.encode(state, (m.allowPatch ? 1 : 0) | (m.prologue ? 2 : 0) | (m.unencrypted ? 4 : 0))
    hashes.encode(state, m.hash)

    c.uint.encode(state, m.quorum)
    signerArray.encode(state, m.signers)
    if (m.prologue) prologue.encode(state, m.prologue)
  },
  decode (state) {
    const v = c.uint.decode(state)
    if (v === 0) return manifestv0.decode(state)
    if (v !== 1) throw new Error('Unknown version: ' + v)

    const flags = c.uint.decode(state)
    const hash = hashes.decode(state)
    const quorum = c.uint.decode(state)
    const signers = signerArray.decode(state)
    const unencrypted = (flags & 4) !== 0

    return {
      version: 1,
      hash,
      allowPatch: (flags & 1) !== 0,
      quorum,
      signers,
      prologue: (flags & 2) === 0 ? null : prologue.decode(state),
      unencrypted
    }
  }
}

const node = {
  preencode (state, n) {
    c.uint.preencode(state, n.index)
    c.uint.preencode(state, n.size)
    c.fixed32.preencode(state, n.hash)
  },
  encode (state, n) {
    c.uint.encode(state, n.index)
    c.uint.encode(state, n.size)
    c.fixed32.encode(state, n.hash)
  },
  decode (state) {
    return {
      index: c.uint.decode(state),
      size: c.uint.decode(state),
      hash: c.fixed32.decode(state)
    }
  }
}

const nodeArray = c.array(node)

const wire = exports.wire = {}

wire.handshake = {
  preencode (state, m) {
    c.uint.preencode(state, 1)
    c.fixed32.preencode(state, m.capability)
  },
  encode (state, m) {
    c.uint.encode(state, m.seeks ? 1 : 0)
    c.fixed32.encode(state, m.capability)
  },
  decode (state) {
    const flags = c.uint.decode(state)
    return {
      seeks: (flags & 1) !== 0,
      capability: c.fixed32.decode(state)
    }
  }
}

const requestBlock = {
  preencode (state, b) {
    c.uint.preencode(state, b.index)
    c.uint.preencode(state, b.nodes)
  },
  encode (state, b) {
    c.uint.encode(state, b.index)
    c.uint.encode(state, b.nodes)
  },
  decode (state) {
    return {
      index: c.uint.decode(state),
      nodes: c.uint.decode(state)
    }
  }
}

const requestSeek = {
  preencode (state, s) {
    c.uint.preencode(state, s.bytes)
    c.uint.preencode(state, s.padding)
  },
  encode (state, s) {
    c.uint.encode(state, s.bytes)
    c.uint.encode(state, s.padding)
  },
  decode (state) {
    return {
      bytes: c.uint.decode(state),
      padding: c.uint.decode(state)
    }
  }
}

const requestUpgrade = {
  preencode (state, u) {
    c.uint.preencode(state, u.start)
    c.uint.preencode(state, u.length)
  },
  encode (state, u) {
    c.uint.encode(state, u.start)
    c.uint.encode(state, u.length)
  },
  decode (state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

wire.request = {
  preencode (state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.id)
    c.uint.preencode(state, m.fork)

    if (m.block) requestBlock.preencode(state, m.block)
    if (m.hash) requestBlock.preencode(state, m.hash)
    if (m.seek) requestSeek.preencode(state, m.seek)
    if (m.upgrade) requestUpgrade.preencode(state, m.upgrade)
    if (m.priority) c.uint.preencode(state, m.priority)
  },
  encode (state, m) {
    const flags = (m.block ? 1 : 0) | (m.hash ? 2 : 0) | (m.seek ? 4 : 0) | (m.upgrade ? 8 : 0) | (m.manifest ? 16 : 0) | (m.priority ? 32 : 0)

    c.uint.encode(state, flags)
    c.uint.encode(state, m.id)
    c.uint.encode(state, m.fork)

    if (m.block) requestBlock.encode(state, m.block)
    if (m.hash) requestBlock.encode(state, m.hash)
    if (m.seek) requestSeek.encode(state, m.seek)
    if (m.upgrade) requestUpgrade.encode(state, m.upgrade)
    if (m.priority) c.uint.encode(state, m.priority)
  },
  decode (state) {
    const flags = c.uint.decode(state)

    return {
      id: c.uint.decode(state),
      fork: c.uint.decode(state),
      block: flags & 1 ? requestBlock.decode(state) : null,
      hash: flags & 2 ? requestBlock.decode(state) : null,
      seek: flags & 4 ? requestSeek.decode(state) : null,
      upgrade: flags & 8 ? requestUpgrade.decode(state) : null,
      manifest: (flags & 16) !== 0,
      priority: flags & 32 ? c.uint.decode(state) : 0
    }
  }
}

wire.cancel = {
  preencode (state, m) {
    c.uint.preencode(state, m.request)
  },
  encode (state, m) {
    c.uint.encode(state, m.request)
  },
  decode (state, m) {
    return {
      request: c.uint.decode(state)
    }
  }
}

const dataUpgrade = {
  preencode (state, u) {
    c.uint.preencode(state, u.start)
    c.uint.preencode(state, u.length)
    nodeArray.preencode(state, u.nodes)
    nodeArray.preencode(state, u.additionalNodes)
    c.buffer.preencode(state, u.signature)
  },
  encode (state, u) {
    c.uint.encode(state, u.start)
    c.uint.encode(state, u.length)
    nodeArray.encode(state, u.nodes)
    nodeArray.encode(state, u.additionalNodes)
    c.buffer.encode(state, u.signature)
  },
  decode (state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state),
      nodes: nodeArray.decode(state),
      additionalNodes: nodeArray.decode(state),
      signature: c.buffer.decode(state)
    }
  }
}

const dataSeek = {
  preencode (state, s) {
    c.uint.preencode(state, s.bytes)
    nodeArray.preencode(state, s.nodes)
  },
  encode (state, s) {
    c.uint.encode(state, s.bytes)
    nodeArray.encode(state, s.nodes)
  },
  decode (state) {
    return {
      bytes: c.uint.decode(state),
      nodes: nodeArray.decode(state)
    }
  }
}

const dataBlock = {
  preencode (state, b) {
    c.uint.preencode(state, b.index)
    c.buffer.preencode(state, b.value)
    nodeArray.preencode(state, b.nodes)
  },
  encode (state, b) {
    c.uint.encode(state, b.index)
    c.buffer.encode(state, b.value)
    nodeArray.encode(state, b.nodes)
  },
  decode (state) {
    return {
      index: c.uint.decode(state),
      value: c.buffer.decode(state) || EMPTY,
      nodes: nodeArray.decode(state)
    }
  }
}

const dataHash = {
  preencode (state, b) {
    c.uint.preencode(state, b.index)
    nodeArray.preencode(state, b.nodes)
  },
  encode (state, b) {
    c.uint.encode(state, b.index)
    nodeArray.encode(state, b.nodes)
  },
  decode (state) {
    return {
      index: c.uint.decode(state),
      nodes: nodeArray.decode(state)
    }
  }
}

wire.data = {
  preencode (state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.request)
    c.uint.preencode(state, m.fork)

    if (m.block) dataBlock.preencode(state, m.block)
    if (m.hash) dataHash.preencode(state, m.hash)
    if (m.seek) dataSeek.preencode(state, m.seek)
    if (m.upgrade) dataUpgrade.preencode(state, m.upgrade)
    if (m.manifest) manifest.preencode(state, m.manifest)
  },
  encode (state, m) {
    const flags = (m.block ? 1 : 0) | (m.hash ? 2 : 0) | (m.seek ? 4 : 0) | (m.upgrade ? 8 : 0) | (m.manifest ? 16 : 0)

    c.uint.encode(state, flags)
    c.uint.encode(state, m.request)
    c.uint.encode(state, m.fork)

    if (m.block) dataBlock.encode(state, m.block)
    if (m.hash) dataHash.encode(state, m.hash)
    if (m.seek) dataSeek.encode(state, m.seek)
    if (m.upgrade) dataUpgrade.encode(state, m.upgrade)
    if (m.manifest) manifest.encode(state, m.manifest)
  },
  decode (state) {
    const flags = c.uint.decode(state)

    return {
      request: c.uint.decode(state),
      fork: c.uint.decode(state),
      block: flags & 1 ? dataBlock.decode(state) : null,
      hash: flags & 2 ? dataHash.decode(state) : null,
      seek: flags & 4 ? dataSeek.decode(state) : null,
      upgrade: flags & 8 ? dataUpgrade.decode(state) : null,
      manifest: flags & 16 ? manifest.decode(state) : null
    }
  }
}

wire.noData = {
  preencode (state, m) {
    c.uint.preencode(state, m.request)
  },
  encode (state, m) {
    c.uint.encode(state, m.request)
  },
  decode (state, m) {
    return {
      request: c.uint.decode(state)
    }
  }
}

wire.want = {
  preencode (state, m) {
    c.uint.preencode(state, m.start)
    c.uint.preencode(state, m.length)
  },
  encode (state, m) {
    c.uint.encode(state, m.start)
    c.uint.encode(state, m.length)
  },
  decode (state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

wire.unwant = {
  preencode (state, m) {
    c.uint.preencode(state, m.start)
    c.uint.preencode(state, m.length)
  },
  encode (state, m) {
    c.uint.encode(state, m.start)
    c.uint.encode(state, m.length)
  },
  decode (state, m) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

wire.range = {
  preencode (state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.start)
    if (m.length !== 1) c.uint.preencode(state, m.length)
  },
  encode (state, m) {
    c.uint.encode(state, (m.drop ? 1 : 0) | (m.length === 1 ? 2 : 0))
    c.uint.encode(state, m.start)
    if (m.length !== 1) c.uint.encode(state, m.length)
  },
  decode (state) {
    const flags = c.uint.decode(state)

    return {
      drop: (flags & 1) !== 0,
      start: c.uint.decode(state),
      length: (flags & 2) !== 0 ? 1 : c.uint.decode(state)
    }
  }
}

wire.bitfield = {
  preencode (state, m) {
    c.uint.preencode(state, m.start)
    c.uint32array.preencode(state, m.bitfield)
  },
  encode (state, m) {
    c.uint.encode(state, m.start)
    c.uint32array.encode(state, m.bitfield)
  },
  decode (state, m) {
    return {
      start: c.uint.decode(state),
      bitfield: c.uint32array.decode(state)
    }
  }
}

wire.sync = {
  preencode (state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.fork)
    c.uint.preencode(state, m.length)
    c.uint.preencode(state, m.remoteLength)
  },
  encode (state, m) {
    c.uint.encode(state, (m.canUpgrade ? 1 : 0) | (m.uploading ? 2 : 0) | (m.downloading ? 4 : 0) | (m.hasManifest ? 8 : 0))
    c.uint.encode(state, m.fork)
    c.uint.encode(state, m.length)
    c.uint.encode(state, m.remoteLength)
  },
  decode (state) {
    const flags = c.uint.decode(state)

    return {
      fork: c.uint.decode(state),
      length: c.uint.decode(state),
      remoteLength: c.uint.decode(state),
      canUpgrade: (flags & 1) !== 0,
      uploading: (flags & 2) !== 0,
      downloading: (flags & 4) !== 0,
      hasManifest: (flags & 8) !== 0
    }
  }
}

wire.reorgHint = {
  preencode (state, m) {
    c.uint.preencode(state, m.from)
    c.uint.preencode(state, m.to)
    c.uint.preencode(state, m.ancestors)
  },
  encode (state, m) {
    c.uint.encode(state, m.from)
    c.uint.encode(state, m.to)
    c.uint.encode(state, m.ancestors)
  },
  decode (state) {
    return {
      from: c.uint.encode(state),
      to: c.uint.encode(state),
      ancestors: c.uint.encode(state)
    }
  }
}

wire.extension = {
  preencode (state, m) {
    c.string.preencode(state, m.name)
    c.raw.preencode(state, m.message)
  },
  encode (state, m) {
    c.string.encode(state, m.name)
    c.raw.encode(state, m.message)
  },
  decode (state) {
    return {
      name: c.string.decode(state),
      message: c.raw.decode(state)
    }
  }
}

const keyValue = {
  preencode (state, p) {
    c.string.preencode(state, p.key)
    c.buffer.preencode(state, p.value)
  },
  encode (state, p) {
    c.string.encode(state, p.key)
    c.buffer.encode(state, p.value)
  },
  decode (state) {
    return {
      key: c.string.decode(state),
      value: c.buffer.decode(state)
    }
  }
}

const treeUpgrade = {
  preencode (state, u) {
    c.uint.preencode(state, u.fork)
    c.uint.preencode(state, u.ancestors)
    c.uint.preencode(state, u.length)
    c.buffer.preencode(state, u.signature)
  },
  encode (state, u) {
    c.uint.encode(state, u.fork)
    c.uint.encode(state, u.ancestors)
    c.uint.encode(state, u.length)
    c.buffer.encode(state, u.signature)
  },
  decode (state) {
    return {
      fork: c.uint.decode(state),
      ancestors: c.uint.decode(state),
      length: c.uint.decode(state),
      signature: c.buffer.decode(state)
    }
  }
}

const bitfieldUpdate = { // TODO: can maybe be folded into a HAVE later on with the most recent spec
  preencode (state, b) {
    state.end++ // flags
    c.uint.preencode(state, b.start)
    c.uint.preencode(state, b.length)
  },
  encode (state, b) {
    state.buffer[state.start++] = b.drop ? 1 : 0
    c.uint.encode(state, b.start)
    c.uint.encode(state, b.length)
  },
  decode (state) {
    const flags = c.uint.decode(state)
    return {
      drop: (flags & 1) !== 0,
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

const oplog = exports.oplog = {}

oplog.entry = {
  preencode (state, m) {
    state.end++ // flags
    if (m.userData) keyValue.preencode(state, m.userData)
    if (m.treeNodes) nodeArray.preencode(state, m.treeNodes)
    if (m.treeUpgrade) treeUpgrade.preencode(state, m.treeUpgrade)
    if (m.bitfield) bitfieldUpdate.preencode(state, m.bitfield)
  },
  encode (state, m) {
    const s = state.start++
    let flags = 0

    if (m.userData) {
      flags |= 1
      keyValue.encode(state, m.userData)
    }
    if (m.treeNodes) {
      flags |= 2
      nodeArray.encode(state, m.treeNodes)
    }
    if (m.treeUpgrade) {
      flags |= 4
      treeUpgrade.encode(state, m.treeUpgrade)
    }
    if (m.bitfield) {
      flags |= 8
      bitfieldUpdate.encode(state, m.bitfield)
    }

    state.buffer[s] = flags
  },
  decode (state) {
    const flags = c.uint.decode(state)
    return {
      userData: (flags & 1) !== 0 ? keyValue.decode(state) : null,
      treeNodes: (flags & 2) !== 0 ? nodeArray.decode(state) : null,
      treeUpgrade: (flags & 4) !== 0 ? treeUpgrade.decode(state) : null,
      bitfield: (flags & 8) !== 0 ? bitfieldUpdate.decode(state) : null
    }
  }
}

const keyPair = {
  preencode (state, kp) {
    c.buffer.preencode(state, kp.publicKey)
    c.buffer.preencode(state, kp.secretKey)
  },
  encode (state, kp) {
    c.buffer.encode(state, kp.publicKey)
    c.buffer.encode(state, kp.secretKey)
  },
  decode (state) {
    return {
      publicKey: c.buffer.decode(state),
      secretKey: c.buffer.decode(state)
    }
  }
}

const reorgHint = {
  preencode (state, r) {
    c.uint.preencode(state, r.from)
    c.uint.preencode(state, r.to)
    c.uint.preencode(state, r.ancestors)
  },
  encode (state, r) {
    c.uint.encode(state, r.from)
    c.uint.encode(state, r.to)
    c.uint.encode(state, r.ancestors)
  },
  decode (state) {
    return {
      from: c.uint.decode(state),
      to: c.uint.decode(state),
      ancestors: c.uint.decode(state)
    }
  }
}

const reorgHintArray = c.array(reorgHint)

const hints = {
  preencode (state, h) {
    reorgHintArray.preencode(state, h.reorgs)
    c.uint.preencode(state, h.contiguousLength)
  },
  encode (state, h) {
    reorgHintArray.encode(state, h.reorgs)
    c.uint.encode(state, h.contiguousLength)
  },
  decode (state) {
    return {
      reorgs: reorgHintArray.decode(state),
      contiguousLength: state.start < state.end ? c.uint.decode(state) : 0
    }
  }
}

const treeHeader = {
  preencode (state, t) {
    c.uint.preencode(state, t.fork)
    c.uint.preencode(state, t.length)
    c.buffer.preencode(state, t.rootHash)
    c.buffer.preencode(state, t.signature)
  },
  encode (state, t) {
    c.uint.encode(state, t.fork)
    c.uint.encode(state, t.length)
    c.buffer.encode(state, t.rootHash)
    c.buffer.encode(state, t.signature)
  },
  decode (state) {
    return {
      fork: c.uint.decode(state),
      length: c.uint.decode(state),
      rootHash: c.buffer.decode(state),
      signature: c.buffer.decode(state)
    }
  }
}

const types = {
  preencode (state, t) {
    c.string.preencode(state, t.tree)
    c.string.preencode(state, t.bitfield)
    c.string.preencode(state, t.signer)
  },
  encode (state, t) {
    c.string.encode(state, t.tree)
    c.string.encode(state, t.bitfield)
    c.string.encode(state, t.signer)
  },
  decode (state) {
    return {
      tree: c.string.decode(state),
      bitfield: c.string.decode(state),
      signer: c.string.decode(state)
    }
  }
}

const externalHeader = {
  preencode (state, m) {
    c.uint.preencode(state, m.start)
    c.uint.preencode(state, m.length)
  },
  encode (state, m) {
    c.uint.encode(state, m.start)
    c.uint.encode(state, m.length)
  },
  decode (state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

const keyValueArray = c.array(keyValue)

oplog.header = {
  preencode (state, h) {
    state.end += 2 // version + flags
    if (h.external) {
      externalHeader.preencode(state, h.external)
      return
    }
    c.fixed32.preencode(state, h.key)
    if (h.manifest) manifest.preencode(state, h.manifest)
    if (h.keyPair) keyPair.preencode(state, h.keyPair)
    keyValueArray.preencode(state, h.userData)
    treeHeader.preencode(state, h.tree)
    hints.preencode(state, h.hints)
  },
  encode (state, h) {
    c.uint.encode(state, 1)
    if (h.external) {
      c.uint.encode(state, 1) // ONLY set the first big for clarity
      externalHeader.encode(state, h.external)
      return
    }
    c.uint.encode(state, (h.manifest ? 2 : 0) | (h.keyPair ? 4 : 0))
    c.fixed32.encode(state, h.key)
    if (h.manifest) manifest.encode(state, h.manifest)
    if (h.keyPair) keyPair.encode(state, h.keyPair)
    keyValueArray.encode(state, h.userData)
    treeHeader.encode(state, h.tree)
    hints.encode(state, h.hints)
  },
  decode (state) {
    const version = c.uint.decode(state)

    if (version > 1) {
      throw new Error('Invalid header version. Expected <= 1, got ' + version)
    }

    if (version === 0) {
      const old = {
        types: types.decode(state),
        userData: keyValueArray.decode(state),
        tree: treeHeader.decode(state),
        signer: keyPair.decode(state),
        hints: hints.decode(state)
      }

      return {
        external: null,
        key: old.signer.publicKey,
        manifest: {
          version: 0,
          hash: old.types.tree,
          allowPatch: false,
          quorum: 1,
          signers: [{
            signature: old.types.signer,
            namespace: DEFAULT_NAMESPACE,
            publicKey: old.signer.publicKey
          }],
          prologue: null
        },
        keyPair: old.signer.secretKey ? old.signer : null,
        userData: old.userData,
        tree: old.tree,
        hints: old.hints
      }
    }

    const flags = c.uint.decode(state)

    if (flags & 1) {
      return {
        external: externalHeader.decode(state),
        key: null,
        manifest: null,
        keyPair: null,
        userData: null,
        tree: null,
        hints: null
      }
    }

    return {
      external: null,
      key: c.fixed32.decode(state),
      manifest: (flags & 2) !== 0 ? manifest.decode(state) : null,
      keyPair: (flags & 4) !== 0 ? keyPair.decode(state) : null,
      userData: keyValueArray.decode(state),
      tree: treeHeader.decode(state),
      hints: hints.decode(state)
    }
  }
}

const uintArray = c.array(c.uint)

const multisigInput = {
  preencode (state, inp) {
    c.uint.preencode(state, inp.signer)
    c.fixed64.preencode(state, inp.signature)
    c.uint.preencode(state, inp.patch)
  },
  encode (state, inp) {
    c.uint.encode(state, inp.signer)
    c.fixed64.encode(state, inp.signature)
    c.uint.encode(state, inp.patch)
  },
  decode (state) {
    return {
      signer: c.uint.decode(state),
      signature: c.fixed64.decode(state),
      patch: c.uint.decode(state)
    }
  }
}

const patchEncodingv0 = {
  preencode (state, n) {
    c.uint.preencode(state, n.start)
    c.uint.preencode(state, n.length)
    uintArray.preencode(state, n.nodes)
  },
  encode (state, n) {
    c.uint.encode(state, n.start)
    c.uint.encode(state, n.length)
    uintArray.encode(state, n.nodes)
  },
  decode (state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state),
      nodes: uintArray.decode(state)
    }
  }
}

const multisigInputv0 = {
  preencode (state, n) {
    state.end++
    c.uint.preencode(state, n.signer)
    c.fixed64.preencode(state, n.signature)
    if (n.patch) patchEncodingv0.preencode(state, n.patch)
  },
  encode (state, n) {
    c.uint.encode(state, n.patch ? 1 : 0)
    c.uint.encode(state, n.signer)
    c.fixed64.encode(state, n.signature)
    if (n.patch) patchEncodingv0.encode(state, n.patch)
  },
  decode (state) {
    const flags = c.uint.decode(state)
    return {
      signer: c.uint.decode(state),
      signature: c.fixed64.decode(state),
      patch: (flags & 1) ? patchEncodingv0.decode(state) : null
    }
  }
}

const multisigInputArrayv0 = c.array(multisigInputv0)
const multisigInputArray = c.array(multisigInput)

const compactNode = {
  preencode (state, n) {
    c.uint.preencode(state, n.index)
    c.uint.preencode(state, n.size)
    c.fixed32.preencode(state, n.hash)
  },
  encode (state, n) {
    c.uint.encode(state, n.index)
    c.uint.encode(state, n.size)
    c.fixed32.encode(state, n.hash)
  },
  decode (state) {
    return {
      index: c.uint.decode(state),
      size: c.uint.decode(state),
      hash: c.fixed32.decode(state)
    }
  }
}

const compactNodeArray = c.array(compactNode)

exports.multiSignaturev0 = {
  preencode (state, s) {
    multisigInputArrayv0.preencode(state, s.proofs)
    compactNodeArray.preencode(state, s.patch)
  },
  encode (state, s) {
    multisigInputArrayv0.encode(state, s.proofs)
    compactNodeArray.encode(state, s.patch)
  },
  decode (state) {
    return {
      proofs: multisigInputArrayv0.decode(state),
      patch: compactNodeArray.decode(state)
    }
  }
}

exports.multiSignature = {
  preencode (state, s) {
    multisigInputArray.preencode(state, s.proofs)
    compactNodeArray.preencode(state, s.patch)
  },
  encode (state, s) {
    multisigInputArray.encode(state, s.proofs)
    compactNodeArray.encode(state, s.patch)
  },
  decode (state) {
    return {
      proofs: multisigInputArray.decode(state),
      patch: compactNodeArray.decode(state)
    }
  }
}
{
  "name": "hypercore-storage",
  "version": "2.8.0",
  "main": "index.js",
  "files": [
    "index.js",
    "lib/*.js",
    "spec/hyperschema/*.js",
    "migrations/0/*.js"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:bare": "brittle-bare test/all.js",
    "test:generate": "brittle -r test/all.js test/*.js",
    "test:node": "brittle-node test/all.js"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "description": "Storage engine for Hypercore",
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    }
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/hypercore-storage.git"
  },
  "bugs": {
    "url": "https://github.com/holepunchto/hypercore-storage/issues"
  },
  "homepage": "https://github.com/holepunchto/hypercore-storage#readme",
  "dependencies": {
    "b4a": "^1.6.7",
    "bare-fs": "^4.0.1",
    "bare-path": "^3.0.0",
    "compact-encoding": "^2.16.0",
    "device-file": "^2.1.2",
    "flat-tree": "^1.12.1",
    "hypercore-crypto": "^3.4.2",
    "hyperschema": "^1.7.0",
    "index-encoder": "^3.3.2",
    "resolve-reject-promise": "^1.0.0",
    "rocksdb-native": "^3.11.0",
    "scope-lock": "^1.2.4",
    "streamx": "^2.21.1"
  },
  "devDependencies": {
    "brittle": "^3.7.0",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "test-tmp": "^1.3.1"
  }
}
// This file is autogenerated by the hyperschema compiler
// Schema Version: 1
/* eslint-disable camelcase */
/* eslint-disable quotes */
/* eslint-disable space-before-function-paren */

const { c } = require('hyperschema/runtime')

const VERSION = 1

// eslint-disable-next-line no-unused-vars
let version = VERSION

// @corestore/allocated
const encoding0 = {
  preencode(state, m) {
    c.uint.preencode(state, m.cores)
    c.uint.preencode(state, m.datas)
  },
  encode(state, m) {
    c.uint.encode(state, m.cores)
    c.uint.encode(state, m.datas)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const r1 = c.uint.decode(state)

    return {
      cores: r0,
      datas: r1
    }
  }
}

// @corestore/head
const encoding1 = {
  preencode(state, m) {
    c.uint.preencode(state, m.version)
    state.end++ // max flag is 4 so always one byte

    if (m.allocated) encoding0.preencode(state, m.allocated)
    if (m.seed) c.fixed32.preencode(state, m.seed)
    if (m.defaultDiscoveryKey) c.fixed32.preencode(state, m.defaultDiscoveryKey)
  },
  encode(state, m) {
    const flags = (m.allocated ? 1 : 0) | (m.seed ? 2 : 0) | (m.defaultDiscoveryKey ? 4 : 0)

    c.uint.encode(state, m.version)
    c.uint.encode(state, flags)

    if (m.allocated) encoding0.encode(state, m.allocated)
    if (m.seed) c.fixed32.encode(state, m.seed)
    if (m.defaultDiscoveryKey) c.fixed32.encode(state, m.defaultDiscoveryKey)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const flags = c.uint.decode(state)

    return {
      version: r0,
      allocated: (flags & 1) !== 0 ? encoding0.decode(state) : null,
      seed: (flags & 2) !== 0 ? c.fixed32.decode(state) : null,
      defaultDiscoveryKey: (flags & 4) !== 0 ? c.fixed32.decode(state) : null
    }
  }
}

// @corestore/alias
const encoding2 = {
  preencode(state, m) {
    c.string.preencode(state, m.name)
    c.fixed32.preencode(state, m.namespace)
  },
  encode(state, m) {
    c.string.encode(state, m.name)
    c.fixed32.encode(state, m.namespace)
  },
  decode(state) {
    const r0 = c.string.decode(state)
    const r1 = c.fixed32.decode(state)

    return {
      name: r0,
      namespace: r1
    }
  }
}

// @corestore/core
const encoding3 = {
  preencode(state, m) {
    c.uint.preencode(state, m.version)
    c.uint.preencode(state, m.corePointer)
    c.uint.preencode(state, m.dataPointer)
    state.end++ // max flag is 1 so always one byte

    if (m.alias) encoding2.preencode(state, m.alias)
  },
  encode(state, m) {
    const flags = m.alias ? 1 : 0

    c.uint.encode(state, m.version)
    c.uint.encode(state, m.corePointer)
    c.uint.encode(state, m.dataPointer)
    c.uint.encode(state, flags)

    if (m.alias) encoding2.encode(state, m.alias)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const r1 = c.uint.decode(state)
    const r2 = c.uint.decode(state)
    const flags = c.uint.decode(state)

    return {
      version: r0,
      corePointer: r1,
      dataPointer: r2,
      alias: (flags & 1) !== 0 ? encoding2.decode(state) : null
    }
  }
}

const encoding4_enum = {
  blake2b: 'blake2b'
}

// @core/hashes enum
const encoding4 = {
  preencode (state, m) {
    state.end++ // max enum is 0 so always one byte
  },
  encode (state, m) {
    switch (m) {
      case 'blake2b':
        c.uint.encode(state, 0)
        break
      default:
        throw new Error('Unknown enum')
    }
  },
  decode (state) {
    switch (c.uint.decode(state)) {
      case 0:
        return 'blake2b'
      default: return null
    }
  }
}

const encoding5_enum = {
  ed25519: 'ed25519'
}

// @core/signatures enum
const encoding5 = {
  preencode (state, m) {
    state.end++ // max enum is 0 so always one byte
  },
  encode (state, m) {
    switch (m) {
      case 'ed25519':
        c.uint.encode(state, 0)
        break
      default:
        throw new Error('Unknown enum')
    }
  },
  decode (state) {
    switch (c.uint.decode(state)) {
      case 0:
        return 'ed25519'
      default: return null
    }
  }
}

// @core/tree-node
const encoding6 = {
  preencode(state, m) {
    c.uint.preencode(state, m.index)
    c.uint.preencode(state, m.size)
    c.fixed32.preencode(state, m.hash)
  },
  encode(state, m) {
    c.uint.encode(state, m.index)
    c.uint.encode(state, m.size)
    c.fixed32.encode(state, m.hash)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const r1 = c.uint.decode(state)
    const r2 = c.fixed32.decode(state)

    return {
      index: r0,
      size: r1,
      hash: r2
    }
  }
}

// @core/signer
const encoding7 = {
  preencode(state, m) {
    encoding5.preencode(state, m.signature)
    c.fixed32.preencode(state, m.namespace)
    c.fixed32.preencode(state, m.publicKey)
  },
  encode(state, m) {
    encoding5.encode(state, m.signature)
    c.fixed32.encode(state, m.namespace)
    c.fixed32.encode(state, m.publicKey)
  },
  decode(state) {
    const r0 = encoding5.decode(state)
    const r1 = c.fixed32.decode(state)
    const r2 = c.fixed32.decode(state)

    return {
      signature: r0,
      namespace: r1,
      publicKey: r2
    }
  }
}

// @core/prologue
const encoding8 = {
  preencode(state, m) {
    c.fixed32.preencode(state, m.hash)
    c.uint.preencode(state, m.length)
  },
  encode(state, m) {
    c.fixed32.encode(state, m.hash)
    c.uint.encode(state, m.length)
  },
  decode(state) {
    const r0 = c.fixed32.decode(state)
    const r1 = c.uint.decode(state)

    return {
      hash: r0,
      length: r1
    }
  }
}

// @core/manifest.signers
const encoding9_4 = c.array(encoding7)
// @core/manifest.linked
const encoding9_6 = c.array(c.fixed32)

// @core/manifest
const encoding9 = {
  preencode(state, m) {
    c.uint.preencode(state, m.version)
    state.end++ // max flag is 8 so always one byte
    encoding4.preencode(state, m.hash)
    c.uint.preencode(state, m.quorum)
    encoding9_4.preencode(state, m.signers)

    if (m.prologue) encoding8.preencode(state, m.prologue)
    if (m.linked) encoding9_6.preencode(state, m.linked)
    if (m.userData) c.buffer.preencode(state, m.userData)
  },
  encode(state, m) {
    const flags =
      (m.allowPatch ? 1 : 0) | (m.prologue ? 2 : 0) | (m.linked ? 4 : 0) | (m.userData ? 8 : 0)

    c.uint.encode(state, m.version)
    c.uint.encode(state, flags)
    encoding4.encode(state, m.hash)
    c.uint.encode(state, m.quorum)
    encoding9_4.encode(state, m.signers)

    if (m.prologue) encoding8.encode(state, m.prologue)
    if (m.linked) encoding9_6.encode(state, m.linked)
    if (m.userData) c.buffer.encode(state, m.userData)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const flags = c.uint.decode(state)

    return {
      version: r0,
      hash: encoding4.decode(state),
      quorum: c.uint.decode(state),
      allowPatch: (flags & 1) !== 0,
      signers: encoding9_4.decode(state),
      prologue: (flags & 2) !== 0 ? encoding8.decode(state) : null,
      linked: (flags & 4) !== 0 ? encoding9_6.decode(state) : null,
      userData: (flags & 8) !== 0 ? c.buffer.decode(state) : null
    }
  }
}

// @core/keyPair
const encoding10 = {
  preencode(state, m) {
    c.buffer.preencode(state, m.publicKey)
    c.buffer.preencode(state, m.secretKey)
  },
  encode(state, m) {
    c.buffer.encode(state, m.publicKey)
    c.buffer.encode(state, m.secretKey)
  },
  decode(state) {
    const r0 = c.buffer.decode(state)
    const r1 = c.buffer.decode(state)

    return {
      publicKey: r0,
      secretKey: r1
    }
  }
}

// @core/auth.manifest
const encoding11_2 = c.frame(encoding9)

// @core/auth
const encoding11 = {
  preencode(state, m) {
    c.fixed32.preencode(state, m.key)
    c.fixed32.preencode(state, m.discoveryKey)
    state.end++ // max flag is 4 so always one byte

    if (m.manifest) encoding11_2.preencode(state, m.manifest)
    if (m.keyPair) encoding10.preencode(state, m.keyPair)
    if (m.encryptionKey) c.buffer.preencode(state, m.encryptionKey)
  },
  encode(state, m) {
    const flags = (m.manifest ? 1 : 0) | (m.keyPair ? 2 : 0) | (m.encryptionKey ? 4 : 0)

    c.fixed32.encode(state, m.key)
    c.fixed32.encode(state, m.discoveryKey)
    c.uint.encode(state, flags)

    if (m.manifest) encoding11_2.encode(state, m.manifest)
    if (m.keyPair) encoding10.encode(state, m.keyPair)
    if (m.encryptionKey) c.buffer.encode(state, m.encryptionKey)
  },
  decode(state) {
    const r0 = c.fixed32.decode(state)
    const r1 = c.fixed32.decode(state)
    const flags = c.uint.decode(state)

    return {
      key: r0,
      discoveryKey: r1,
      manifest: (flags & 1) !== 0 ? encoding11_2.decode(state) : null,
      keyPair: (flags & 2) !== 0 ? encoding10.decode(state) : null,
      encryptionKey: (flags & 4) !== 0 ? c.buffer.decode(state) : null
    }
  }
}

// @core/head
const encoding12 = {
  preencode(state, m) {
    c.uint.preencode(state, m.fork)
    c.uint.preencode(state, m.length)
    c.fixed32.preencode(state, m.rootHash)
    c.buffer.preencode(state, m.signature)
  },
  encode(state, m) {
    c.uint.encode(state, m.fork)
    c.uint.encode(state, m.length)
    c.fixed32.encode(state, m.rootHash)
    c.buffer.encode(state, m.signature)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const r1 = c.uint.decode(state)
    const r2 = c.fixed32.decode(state)
    const r3 = c.buffer.decode(state)

    return {
      fork: r0,
      length: r1,
      rootHash: r2,
      signature: r3
    }
  }
}

// @core/hints
const encoding13 = {
  preencode(state, m) {
    state.end++ // max flag is 4 so always one byte

    if (m.contiguousLength) c.uint.preencode(state, m.contiguousLength)
    if (m.remoteContiguousLength) c.uint.preencode(state, m.remoteContiguousLength)
    if (m.recovering) c.uint.preencode(state, m.recovering)
  },
  encode(state, m) {
    const flags =
      (m.contiguousLength ? 1 : 0) | (m.remoteContiguousLength ? 2 : 0) | (m.recovering ? 4 : 0)

    c.uint.encode(state, flags)

    if (m.contiguousLength) c.uint.encode(state, m.contiguousLength)
    if (m.remoteContiguousLength) c.uint.encode(state, m.remoteContiguousLength)
    if (m.recovering) c.uint.encode(state, m.recovering)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      contiguousLength: (flags & 1) !== 0 ? c.uint.decode(state) : 0,
      remoteContiguousLength: (flags & 2) !== 0 ? c.uint.decode(state) : 0,
      recovering: (flags & 4) !== 0 ? c.uint.decode(state) : 0
    }
  }
}

// @core/session
const encoding14 = {
  preencode(state, m) {
    c.string.preencode(state, m.name)
    c.uint.preencode(state, m.dataPointer)
  },
  encode(state, m) {
    c.string.encode(state, m.name)
    c.uint.encode(state, m.dataPointer)
  },
  decode(state) {
    const r0 = c.string.decode(state)
    const r1 = c.uint.decode(state)

    return {
      name: r0,
      dataPointer: r1
    }
  }
}

// @core/sessions
const encoding15 = c.array(encoding14)

// @core/dependency
const encoding16 = {
  preencode(state, m) {
    c.uint.preencode(state, m.dataPointer)
    c.uint.preencode(state, m.length)
  },
  encode(state, m) {
    c.uint.encode(state, m.dataPointer)
    c.uint.encode(state, m.length)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const r1 = c.uint.decode(state)

    return {
      dataPointer: r0,
      length: r1
    }
  }
}

function setVersion(v) {
  version = v
}

function encode(name, value, v = VERSION) {
  version = v
  return c.encode(getEncoding(name), value)
}

function decode(name, buffer, v = VERSION) {
  version = v
  return c.decode(getEncoding(name), buffer)
}

function getEnum(name) {
  switch (name) {
    case '@core/hashes':
      return encoding4_enum
    case '@core/signatures':
      return encoding5_enum
    default:
      throw new Error('Enum not found ' + name)
  }
}

function getEncoding(name) {
  switch (name) {
    case '@corestore/allocated':
      return encoding0
    case '@corestore/head':
      return encoding1
    case '@corestore/alias':
      return encoding2
    case '@corestore/core':
      return encoding3
    case '@core/hashes':
      return encoding4
    case '@core/signatures':
      return encoding5
    case '@core/tree-node':
      return encoding6
    case '@core/signer':
      return encoding7
    case '@core/prologue':
      return encoding8
    case '@core/manifest':
      return encoding9
    case '@core/keyPair':
      return encoding10
    case '@core/auth':
      return encoding11
    case '@core/head':
      return encoding12
    case '@core/hints':
      return encoding13
    case '@core/session':
      return encoding14
    case '@core/sessions':
      return encoding15
    case '@core/dependency':
      return encoding16
    default:
      throw new Error('Encoder not found ' + name)
  }
}

function getStruct(name, v = VERSION) {
  const enc = getEncoding(name)
  return {
    preencode(state, m) {
      version = v
      enc.preencode(state, m)
    },
    encode(state, m) {
      version = v
      enc.encode(state, m)
    },
    decode(state) {
      version = v
      return enc.decode(state)
    }
  }
}

const resolveStruct = getStruct // compat

module.exports = {
  resolveStruct,
  getStruct,
  getEnum,
  getEncoding,
  encode,
  decode,
  setVersion,
  version
}
const { EventEmitter } = require('events')
const isOptions = require('is-options')
const crypto = require('hypercore-crypto')
const CoreStorage = require('hypercore-storage')
const c = require('compact-encoding')
const b4a = require('b4a')
const NoiseSecretStream = require('@hyperswarm/secret-stream')
const Protomux = require('protomux')
const id = require('hypercore-id-encoding')
const safetyCatch = require('safety-catch')
const unslab = require('unslab')
const flat = require('flat-tree')
const assert = require('nanoassert')

const { SMALL_WANTS } = require('./lib/feature-flags')
const { UPDATE_COMPAT } = require('./lib/wants')
const MarkBitfield = require('./lib/mark-bitfield')

const inspect = require('./lib/inspect')
const Core = require('./lib/core')
const Info = require('./lib/info')
const Download = require('./lib/download')
const DefaultEncryption = require('./lib/default-encryption')
const caps = require('./lib/caps')
const Replicator = require('./lib/replicator')
const { manifestHash, createManifest } = require('./lib/verifier')
const { ReadStream, WriteStream, ByteStream } = require('./lib/streams')
const { MerkleTree } = require('./lib/merkle-tree')
const { proof, verify } = require('./lib/fully-remote-proof')
const {
  ASSERTION,
  BAD_ARGUMENT,
  SESSION_CLOSED,
  SESSION_MOVED,
  SESSION_NOT_WRITABLE,
  SNAPSHOT_NOT_AVAILABLE,
  DECODING_ERROR
} = require('hypercore-errors')

// Hypercore actually does not have any notion of max/min block sizes
// but we enforce 15mb to ensure smooth replication (each block is transmitted atomically)
const MAX_SUGGESTED_BLOCK_SIZE = 15 * 1024 * 1024

class Hypercore extends EventEmitter {
  constructor(storage, key, opts) {
    super()

    if (isOptions(storage) && !storage.db) {
      opts = storage
      storage = null
      key = opts.key || null
    } else if (isOptions(key)) {
      opts = key
      key = opts.key || null
    }

    if (key && typeof key === 'string') key = id.decode(key)
    if (!opts) opts = {}

    if (!storage) storage = opts.storage

    this.core = null
    this.state = null
    this.encryption = null
    this.extensions = new Map()

    this.valueEncoding = null
    this.encodeBatch = null
    this.activeRequests = []
    this.sessions = null
    this.ongc = null

    this.keyPair = opts.keyPair || null
    this.readable = true
    this.writable = false
    this.exclusive = false
    this.opened = false
    this.closed = false
    this.weak = !!opts.weak
    this.snapshotted = !!opts.snapshot
    this.onseq = opts.onseq || null
    this.onwait = opts.onwait || null
    this.wait = opts.wait !== false
    this.timeout = opts.timeout || 0
    this.preload = null
    this.closing = null
    this.opening = null

    this._readonly = opts.writable === false
    this._preappend = preappend.bind(this)
    this._snapshot = null
    this._findingPeers = 0
    this._active = opts.weak ? !!opts.active : opts.active !== false

    this.waits = 0

    // Mark & Sweep GC
    this._marking = false
    this._marks = null

    this._sessionIndex = -1
    this._stateIndex = -1 // maintained by session state
    this._monitorIndex = -1 // maintained by replication state

    this.opening = this._open(storage, key, opts)
    this.opening.catch(safetyCatch)

    this.on('newListener', maybeAddMonitor)
  }

  [Symbol.for('nodejs.util.inspect.custom')](depth, opts) {
    return inspect(this, depth, opts)
  }

  static MAX_SUGGESTED_BLOCK_SIZE = MAX_SUGGESTED_BLOCK_SIZE

  static DefaultEncryption = DefaultEncryption

  static SMALL_WANTS = SMALL_WANTS

  static enable(flag) {
    const enableCompat = (flag & SMALL_WANTS) === 0
    UPDATE_COMPAT(enableCompat)
  }

  static setRecoveryPeers(peers) {
    Core.setRecoveryPeers(peers)
  }

  static key(manifest, { compat, version, namespace } = {}) {
    if (b4a.isBuffer(manifest)) {
      manifest = { version, signers: [{ publicKey: manifest, namespace }] }
    }
    return compat ? manifest.signers[0].publicKey : manifestHash(createManifest(manifest))
  }

  static discoveryKey(key) {
    return crypto.discoveryKey(key)
  }

  static blockEncryptionKey(key, encryptionKey) {
    return DefaultEncryption.blockEncryptionKey(key, encryptionKey)
  }

  static getProtocolMuxer(stream) {
    return stream.noiseStream.userData
  }

  static createCore(storage, opts) {
    return new Core(Hypercore.defaultStorage(storage), { autoClose: false, ...opts })
  }

  static createProtocolStream(isInitiator, opts = {}) {
    let outerStream = Protomux.isProtomux(isInitiator)
      ? isInitiator.stream
      : isStream(isInitiator)
        ? isInitiator
        : opts.stream

    let noiseStream = null

    if (outerStream) {
      noiseStream = outerStream.noiseStream
    } else {
      noiseStream = new NoiseSecretStream(isInitiator, null, opts)
      outerStream = noiseStream.rawStream
    }
    if (!noiseStream) throw BAD_ARGUMENT('Invalid stream', this.discoveryKey)

    if (!noiseStream.userData) {
      const protocol = Protomux.from(noiseStream)

      if (opts.keepAlive !== false && noiseStream.keepAlive === 0) {
        noiseStream.setKeepAlive(5000)
      }
      noiseStream.userData = protocol
    }

    if (opts.ondiscoverykey) {
      const ondiscoverykey = createDiscoveryKeyHandler(opts.ondiscoverykey)
      noiseStream.userData.pair({ protocol: 'hypercore/alpha' }, ondiscoverykey)
    }

    return outerStream
  }

  static defaultStorage(storage, opts = {}) {
    if (CoreStorage.isCoreStorage(storage)) return storage

    const directory = storage
    return new CoreStorage(directory, opts)
  }

  static clearRequests(session, err) {
    return Replicator.clearRequests(session, err)
  }

  static async treeHashFromStorage(session, length = session.length) {
    const roots = await MerkleTree.getRoots(session.state, length)
    return crypto.tree(roots)
  }

  snapshot(opts) {
    return this.session({ ...opts, snapshot: true })
  }

  compact() {
    return this.core.compact()
  }

  session(opts = {}) {
    if (this.closing) {
      // This makes the closing logic a lot easier. If this turns out to be a problem
      // in practice, open an issue and we'll try to make a solution for it.
      throw SESSION_CLOSED('Cannot make sessions on a closing core', this.discoveryKey)
    }
    if (opts.checkout !== undefined && !opts.name && !opts.atom) {
      throw ASSERTION('Checkouts are only supported on atoms or named sessions', this.discoveryKey)
    }

    const wait = opts.wait === false ? false : this.wait
    const writable = opts.writable === undefined ? !this._readonly : opts.writable === true
    const onwait = opts.onwait === undefined ? this.onwait : opts.onwait
    const onseq = opts.onseq === undefined ? this.onseq : opts.onseq
    const timeout = opts.timeout === undefined ? this.timeout : opts.timeout
    const weak = opts.weak === undefined ? this.weak : opts.weak
    const marking = this._marking
    const marks = this._marks
    const Clz = opts.class || Hypercore
    const s = new Clz(null, this.key, {
      ...opts,
      wait,
      onwait,
      onseq,
      timeout,
      writable,
      weak,
      parent: this
    })
    s._marking = marking
    s._marks = marks

    return s
  }

  async setEncryptionKey(key, opts) {
    if (!this.opened) await this.opening
    const encryption = this._getEncryptionProvider({ key, block: !!(opts && opts.block) })
    return this.setEncryption(encryption)
  }

  async setEncryption(encryption) {
    if (!this.opened) await this.opening

    if (encryption === null) {
      this.encryption = encryption
      return
    }

    if (!isEncryptionProvider(encryption)) {
      throw ASSERTION('Provider does not satisfy HypercoreEncryption interface', this.discoveryKey)
    }

    this.encryption = encryption
  }

  setKeyPair(keyPair) {
    this.keyPair = keyPair
  }

  setActive(bool) {
    const active = !!bool
    if (active === this._active || this.closing) return
    this._active = active
    if (!this.opened) return
    this.core.replicator.updateActivity(this._active ? 1 : -1)
  }

  async _open(storage, key, opts) {
    const preload = opts.preload || (opts.parent && opts.parent.preload)

    if (preload) {
      this.sessions = [] // in case someone looks at it like with peers
      this.preload = preload
      opts = { ...opts, ...(await this.preload) }
      this.preload = null
    }

    const parent = opts.parent || null
    const core = opts.core || (parent && parent.core)
    const sessions = opts.sessions || (parent && parent.sessions)
    const ongc = opts.ongc || (parent && parent.ongc)

    if (core) this.core = core
    if (ongc) this.ongc = ongc
    if (sessions) this.sessions = sessions

    if (this.sessions === null) this.sessions = []
    this._sessionIndex = this.sessions.push(this) - 1

    if (this.core === null) initOnce(this, storage, key, opts)
    if (this._monitorIndex === -2) this.core.addMonitor(this)

    try {
      await this._openSession(opts)
    } catch (err) {
      if (this.core.autoClose && this.core.hasSession() === false) await this.core.close()

      if (this.exclusive) this.core.unlockExclusive()

      this.core.removeMonitor(this)
      this._removeSession()

      if (this.state !== null) this.state.removeSession(this)

      this.closed = true
      this.emit('close')
      throw err
    }

    // Setup automatic recovery if in repair mode
    if (this.core._repairMode) {
      const recoverTreeNodeFromPeersBound = this.recoverTreeNodeFromPeers.bind(this)
      this.once('repaired', () => {
        this.off('peer-add', recoverTreeNodeFromPeersBound)
      })
      this.on('peer-add', recoverTreeNodeFromPeersBound)
    }

    this.emit('ready')

    // if we are a weak session the core might have closed...
    if (this.core.closing) this.close().catch(safetyCatch)
  }

  _removeSession() {
    if (this._sessionIndex === -1) return
    const head = this.sessions.pop()
    if (head !== this) this.sessions[(head._sessionIndex = this._sessionIndex)] = head
    this._sessionIndex = -1
    if (this.ongc !== null) this.ongc(this)
  }

  async _openSession(opts) {
    if (this.core.opened === false) await this.core.ready()

    if (this.keyPair === null) this.keyPair = opts.keyPair || this.core.header.keyPair

    const parent = opts.parent || null
    if (parent && parent.encryption) this.encryption = parent.encryption

    const e = getEncryptionOption(opts)
    if (!this.encryption) this.encryption = this._getEncryptionProvider(e)

    this.writable = this._isWritable()

    if (opts.valueEncoding) {
      this.valueEncoding = c.from(opts.valueEncoding)
    }
    if (opts.encodeBatch) {
      this.encodeBatch = opts.encodeBatch
    }

    // one session sets for pushOnly for all
    if (opts.pushOnly === true) {
      this.core.replicator.setPushOnly(true)
    }

    if (parent) {
      if (parent._stateIndex === -1) await parent.ready()
      if (!this.keyPair) this.keyPair = parent.keyPair

      const ps = parent.state

      if (ps) {
        const shouldSnapshot = this.snapshotted && !ps.isSnapshot()
        this.state = shouldSnapshot ? await ps.snapshot() : ps.ref()
      }

      if (this.snapshotted && this.core && !this._snapshot) {
        this._updateSnapshot()
      }
    }

    if (opts.exclusive && opts.writable !== false) {
      this.exclusive = true
      await this.core.lockExclusive()
    }

    const parentState = parent ? parent.state : this.core.state
    const checkout = opts.checkout === undefined ? -1 : opts.checkout
    const state = this.state

    if (opts.atom) {
      this.state = await parentState.createSession(null, false, opts.atom)
      if (state) state.unref()
    } else if (opts.name) {
      // todo: need to make named sessions safe before ready
      // atm we always copy the state in passCapabilities
      this.state = await parentState.createSession(opts.name, !!opts.overwrite, null)
      if (state) state.unref() // ref'ed above in setup session
    }

    if (this.state && checkout !== -1) {
      if (!opts.name && !opts.atom) {
        throw ASSERTION('Checkouts must be named or atomized', this.discoveryKey)
      }
      if (checkout > this.state.length) {
        throw ASSERTION(
          `Invalid checkout ${checkout} for ${opts.name}, length is ${this.state.length}`,
          this.discoveryKey
        )
      }
      if (this.state.prologue && checkout < this.state.prologue.length) {
        throw ASSERTION(
          `Invalid checkout ${checkout} for ${opts.name}, prologue length is ${this.state.prologue.length}`,
          this.discoveryKey
        )
      }
      if (checkout < this.state.length) await this.state.truncate(checkout, this.fork)
    }

    if (this.state === null) {
      this.state = this.core.state.ref()
    }

    this.writable = this._isWritable()

    if (this.snapshotted && this.core) this._updateSnapshot()

    this.state.addSession(this)
    // TODO: we need to rework the core reference flow, as the state and session do not always agree now due to moveTo
    this.core = this.state.core // in case it was wrong...

    if (opts.userData) {
      const tx = this.state.storage.write()
      for (const [key, value] of Object.entries(opts.userData)) {
        tx.putUserData(key, value)
      }
      await tx.flush()
    }

    if (opts.manifest && !this.core.header.manifest) {
      await this.core.setManifest(createManifest(opts.manifest))
    }

    this.core.replicator.updateActivity(this._active ? 1 : 0)

    this.opened = true
  }

  get replicator() {
    return this.core === null ? null : this.core.replicator
  }

  _getSnapshot() {
    return {
      length: this.state.length,
      byteLength: this.state.byteLength,
      fork: this.state.fork
    }
  }

  _updateSnapshot() {
    const prev = this._snapshot
    const next = (this._snapshot = this._getSnapshot())

    if (!prev) return true
    return prev.length !== next.length || prev.fork !== next.fork
  }

  _isWritable() {
    if (this._readonly) return false
    if (this.state && !this.state.isDefault()) return true
    return !!(this.keyPair && this.keyPair.secretKey)
  }

  close({ error } = {}) {
    if (this.closing) return this.closing

    this.closing = this._close(error || null)
    return this.closing
  }

  clearRequests(activeRequests, error) {
    if (!activeRequests.length) return
    if (this.core) this.core.replicator.clearRequests(activeRequests, error)
  }

  async _close(error) {
    if (this.opened === false) {
      try {
        await this.opening
      } catch (err) {
        if (!this.closed) throw err
      }
    }

    if (this.closed === true) return

    this.core.removeMonitor(this)
    this.state.removeSession(this)
    this._removeSession()

    this.readable = false
    this.writable = false
    this.opened = false

    const gc = []
    for (const ext of this.extensions.values()) {
      if (ext.session === this) gc.push(ext)
    }
    for (const ext of gc) ext.destroy()

    this.core.replicator.findingPeers -= this._findingPeers
    this.core.replicator.clearRequests(this.activeRequests, error)
    this.core.replicator.updateActivity(this._active ? -1 : 0)

    this._findingPeers = 0

    this.state.unref()

    if (this.exclusive) this.core.unlockExclusive()

    if (this.core.hasSession()) {
      // emit "fake" close as this is a session
      this.closed = true
      this.emit('close')
      return
    }

    if (this.core.autoClose) await this.core.close()

    this.closed = true
    this.emit('close')
  }

  async commit(session, opts) {
    await this.ready()
    await session.ready()

    return this.state.commit(session.state, { keyPair: this.keyPair, ...opts })
  }

  replicate(isInitiator, opts = {}) {
    // Only limitation here is that ondiscoverykey doesn't work atm when passing a muxer directly,
    // because it doesn't really make a lot of sense.
    if (Protomux.isProtomux(isInitiator)) return this._attachToMuxer(isInitiator)

    // if same stream is passed twice, ignore the 2nd one before we make sessions etc
    if (isStream(isInitiator) && this._isAttached(isInitiator)) return isInitiator

    const protocolStream = Hypercore.createProtocolStream(isInitiator, opts)
    const noiseStream = protocolStream.noiseStream
    const protocol = noiseStream.userData

    this._attachToMuxer(protocol)

    return protocolStream
  }

  _isAttached(stream) {
    return (
      stream.userData &&
      this.core &&
      this.core.replicator &&
      this.core.replicator.attached(stream.userData)
    )
  }

  _attachToMuxer(mux) {
    if (this.opened) {
      this.core.replicator.attachTo(mux)
    } else {
      this.opening.then(() => this.core.replicator.attachTo(mux), mux.destroy.bind(mux))
    }

    return mux
  }

  get id() {
    return this.core === null ? null : this.core.id
  }

  get key() {
    return this.core === null ? null : this.core.key
  }

  get discoveryKey() {
    return this.core === null ? null : this.core.discoveryKey
  }

  get manifest() {
    return this.core === null ? null : this.core.manifest
  }

  get length() {
    if (this._snapshot) return this._snapshot.length
    return this.opened === false ? 0 : this.state.length
  }

  get signedLength() {
    return this.opened === false ? 0 : this.state.signedLength()
  }

  /**
   * Deprecated. Use `const { byteLength } = await core.info()`.
   */
  get byteLength() {
    if (this.opened === false) return 0
    if (this._snapshot) return this._snapshot.byteLength
    return this.state.byteLength - this.state.length * this.padding
  }

  get remoteContiguousLength() {
    if (this.opened === false) return 0
    return Math.min(this.core.state.length, this.core.header.hints.remoteContiguousLength)
  }

  get contiguousLength() {
    if (this.opened === false) return 0
    return Math.min(this.core.state.length, this.core.header.hints.contiguousLength)
  }

  get contiguousByteLength() {
    return 0
  }

  get fork() {
    if (this.opened === false) return 0
    return this.state.fork
  }

  get padding() {
    if (this.encryption && this.key && this.manifest) {
      return this.encryption.padding(this.core, this.length)
    }

    return 0
  }

  get peers() {
    return this.opened === false ? [] : this.core.replicator.peers
  }

  get globalCache() {
    return this.opened === false ? null : this.core.globalCache
  }

  get recovering() {
    return this.opened === false ? 0 : this.core.header.hints.recovering
  }

  ready() {
    return this.opening
  }

  async recover() {
    if (this.opened === false) await this.opening
    return this.state.waitForRecovery()
  }

  async setUserData(key, value) {
    if (this.opened === false) await this.opening
    const existing = await this.getUserData(key)
    if (existing && b4a.isBuffer(value) && b4a.equals(existing, value)) return
    await this.state.setUserData(key, value)
  }

  async getUserData(key) {
    if (this.opened === false) await this.opening
    const batch = this.state.storage.read()
    const p = batch.getUserData(key)
    batch.tryFlush()
    return p
  }

  transferSession(core) {
    // todo: validate we can move

    if (this.weak === false) {
      this.core.activeSessions--
      core.activeSessions++
    }

    if (this._monitorIndex >= 0) {
      this.core.removeMonitor(this)
      core.addMonitor(this)
    }

    const old = this.core

    this.core = core

    old.replicator.clearRequests(this.activeRequests, SESSION_MOVED())

    this.emit('migrate', this.key)
  }

  findingPeers() {
    this._findingPeers++
    if (this.core !== null && !this.closing) this.core.replicator.findingPeers++

    let once = true

    return () => {
      if (this.closing || !once) return
      once = false
      this._findingPeers--
      if (this.core !== null && --this.core.replicator.findingPeers === 0) {
        this.core.replicator.updateAll()
      }
    }
  }

  async info(opts) {
    if (this.opened === false) await this.opening

    return Info.from(this, opts)
  }

  async update(opts) {
    if (this.opened === false) await this.opening
    if (this.closing !== null) return false
    if (this.snapshotted) return false

    if (this.writable && (!opts || opts.force !== true)) return false

    const remoteWait = this._shouldWait(opts, this.core.replicator.findingPeers > 0)

    let upgraded = false

    if (await this.core.replicator.applyPendingReorg()) {
      upgraded = true
    }

    if (!upgraded && remoteWait) {
      const activeRequests = (opts && opts.activeRequests) || this.activeRequests
      const req = this.core.replicator.addUpgrade(activeRequests)

      try {
        upgraded = await req.promise
      } catch (err) {
        if (isSessionMoved(err)) return this.update(opts)
        throw err
      }
    }

    if (!upgraded) return false
    return true
  }

  async seek(bytes, opts) {
    if (this.opened === false) await this.opening
    if (!isValidIndex(bytes)) throw ASSERTION('seek is invalid', this.discoveryKey)

    const activeRequests = (opts && opts.activeRequests) || this.activeRequests

    if (this.encryption && !this.core.manifest) {
      const req = this.replicator.addUpgrade(activeRequests)
      try {
        await req.promise
      } catch (err) {
        if (isSessionMoved(err)) return this.seek(bytes, opts)
        throw err
      }
    }

    const s = MerkleTree.seek(this.state, bytes, this.padding)

    const offset = await s.update()
    if (offset) return offset

    if (this.closing !== null) {
      throw SESSION_CLOSED('cannot seek on a closed session', this.discoveryKey)
    }

    if (!this._shouldWait(opts, this.wait)) return null

    const req = this.core.replicator.addSeek(activeRequests, s)

    const timeout = opts && opts.timeout !== undefined ? opts.timeout : this.timeout
    if (timeout) req.context.setTimeout(req, timeout)

    try {
      return await req.promise
    } catch (err) {
      if (isSessionMoved(err)) return this.seek(bytes, opts)
      throw err
    }
  }

  async has(start, end = start + 1) {
    if (this.opened === false) await this.opening
    if (!isValidIndex(start) || !isValidIndex(end)) {
      throw ASSERTION('has range is invalid', this.discoveryKey)
    }

    if (this.state.isDefault()) {
      if (end === start + 1) return this.core.bitfield.get(start)

      const i = this.core.bitfield.firstUnset(start)
      return i === -1 || i >= end
    }

    if (end === start + 1) {
      const rx = this.state.storage.read()
      const block = rx.getBlock(start)
      rx.tryFlush()

      return (await block) !== null
    }

    let count = 0

    const stream = this.state.storage.createBlockStream({ gte: start, lt: end })
    for await (const block of stream) {
      if (block === null) return false
      count++
    }

    return count === end - start
  }

  async get(index, opts) {
    if (this.opened === false) await this.opening
    if (!isValidIndex(index)) throw ASSERTION('block index is invalid', this.discoveryKey)

    if (this.closing !== null) {
      throw SESSION_CLOSED('cannot get on a closed session', this.discoveryKey)
    }

    const encoding =
      (opts && opts.valueEncoding && c.from(opts.valueEncoding)) || this.valueEncoding

    if (this.onseq !== null) this.onseq(index, this)
    if (this._marking) await this.markBlock(index)

    const req = this._get(index, opts)

    let block = await req
    if (!block) return null

    if (opts && opts.raw) return block

    if (this.encryption && (!opts || opts.decrypt !== false)) {
      // Copy the block as it might be shared with other sessions.
      block = b4a.from(block)

      await this.encryption.decrypt(index, block, this.core)
    }

    return this._decode(encoding, block, index)
  }

  async clear(start, end = start + 1, opts) {
    if (this.opened === false) await this.opening
    if (this.closing !== null) {
      throw SESSION_CLOSED('cannot clear on a closed session', this.discoveryKey)
    }

    if (typeof end === 'object') {
      opts = end
      end = start + 1
    }

    if (!isValidIndex(start) || !isValidIndex(end)) {
      throw ASSERTION('clear range is invalid', this.discoveryKey)
    }

    const cleared = opts && opts.diff ? { blocks: 0 } : null

    if (start >= end) return cleared
    if (start >= this.length) return cleared

    await this.state.clear(start, end, cleared)

    return cleared
  }

  async purge() {
    await this._closeAllSessions(null)
    await this.core.purge()
  }

  async _get(index, opts) {
    const block = await readBlock(this.state.storage.read(), index)

    if (block !== null) return block

    if (this.closing !== null) {
      throw SESSION_CLOSED('cannot get on a closed session', this.discoveryKey)
    }

    // snapshot should check if core has block
    if (this._snapshot !== null) {
      checkSnapshot(this, index)
      const coreBlock = await readBlock(this.core.state.storage.read(), index)

      checkSnapshot(this, index)
      if (coreBlock !== null) return coreBlock
    }

    // lets check the bitfield to see if we got it during the above async calls
    // this is the last resort before replication, so always safe.
    if (this.core.bitfield.get(index)) {
      const coreBlock = await readBlock(this.state.storage.read(), index)
      // TODO: this should not be needed, only needed atm in case we are doing a moveTo during this (we should fix)
      if (coreBlock !== null) return coreBlock
    }

    if (!this._shouldWait(opts, this.wait)) return null

    this.waits++
    if (opts && opts.onwait) opts.onwait(index, this)
    if (this.onwait) this.onwait(index, this)

    const activeRequests = (opts && opts.activeRequests) || this.activeRequests

    const force = opts ? opts.force === true : false
    const req = this.core.replicator.addBlock(activeRequests, index, force)
    req.snapshot = index < this.length

    const timeout = opts && opts.timeout !== undefined ? opts.timeout : this.timeout
    if (timeout) req.context.setTimeout(req, timeout)

    let replicatedBlock = null

    try {
      replicatedBlock = await req.promise
    } catch (err) {
      if (isSessionMoved(err)) return this._get(index, opts)
      throw err
    }

    if (this._snapshot !== null) checkSnapshot(this, index)
    return maybeUnslab(replicatedBlock)
  }

  _shouldWait(opts, defaultValue) {
    if (opts) {
      if (opts.wait === false) return false
      if (opts.wait === true) return true
    }
    return defaultValue
  }

  _setupMarks() {
    if (this._marks === null) {
      const storage = this.snapshotted ? this.core.state.storage : this.state.storage
      this._marks = new MarkBitfield(storage)
    }
  }

  async markBlock(start, end = start + 1) {
    if (this.opened === false) await this.opening

    this._setupMarks()

    // TODO support as single rocks batch
    const setPromises = []
    for (let i = start; i < end; i++) {
      setPromises.push(this._marks.set(i, true))
    }

    return Promise.all(setPromises)
  }

  async clearMarkings() {
    if (this.opened === false) await this.opening

    this._setupMarks()

    await this._marks.clear()
    this._marks = null
  }

  async startMarking() {
    if (this._marking) {
      throw ASSERTION("Hypercore cannot be gc'ed when already in gc mode", this.discoveryKey)
    }
    if (this.state && this.state.name) {
      throw ASSERTION("Hypercore cannot be gc'ed when a named session", this.discoveryKey)
    }
    if (this.state && this.state.storage.atom) {
      throw ASSERTION("Hypercore cannot be gc'ed when an atomic session", this.discoveryKey)
    }
    if (this.opened === false) await this.opening
    await this.clearMarkings()

    this._marking = true
  }

  async sweep({ batchSize = 1000 } = {}) {
    if (this.opened === false) await this.opening

    assert(!this.snapshotted, 'Cannot sweep a snapshot')

    // No marks - load from storage
    this._setupMarks()

    let clearing = []
    let prevIndex = this.length
    for await (const index of this._marks.createMarkStream({ reverse: true })) {
      if (index + 1 === prevIndex) {
        prevIndex = index
        continue
      }
      clearing.push(this.clear(index + 1, prevIndex))
      if (clearing.length >= batchSize) {
        await Promise.all(clearing)
        clearing = []
      }
      prevIndex = index
    }
    // Clear range from the very start if not marked
    if (prevIndex > 0) clearing.push(this.clear(0, prevIndex))
    await Promise.all(clearing)

    this._marking = false
    await this.clearMarkings()
  }

  createReadStream(opts) {
    return new ReadStream(this, opts)
  }

  createWriteStream() {
    return new WriteStream(this)
  }

  createByteStream(opts) {
    return new ByteStream(this, opts)
  }

  download(range) {
    return new Download(this, range)
  }

  // TODO: get rid of this / deprecate it?
  undownload(range) {
    range.destroy(null)
  }

  // TODO: get rid of this / deprecate it?
  cancel(request) {
    // Do nothing for now
  }

  async truncate(newLength = 0, opts = {}) {
    if (this.opened === false) await this.opening
    if (this.closing) throw SESSION_CLOSED('Cannot append to a closed session', this.discoveryKey)

    const {
      fork = this.state.fork + 1,
      keyPair = this.keyPair,
      signature = null
    } = typeof opts === 'number' ? { fork: opts } : opts

    const isDefault = this.state === this.core.state
    const writable = !this._readonly && !!(signature || (keyPair && keyPair.secretKey))
    if (isDefault && writable === false && (newLength > 0 || fork !== this.state.fork)) {
      throw SESSION_NOT_WRITABLE('cannot append to a non-writable core', this.discoveryKey)
    }

    await this.state.truncate(newLength, fork, { keyPair, signature })

    // TODO: Should propagate from an event triggered by the oplog
    if (this.state === this.core.state) this.core.replicator.updateAll()
  }

  async append(blocks, opts = {}) {
    if (this.opened === false) await this.opening
    if (this.closing) throw SESSION_CLOSED('Cannot append to a closed session', this.discoveryKey)

    const isDefault = this.state === this.core.state
    const defaultKeyPair = this.state.name === null ? this.keyPair : null

    const { keyPair = defaultKeyPair, signature = null, maxLength, postappend = null } = opts
    const writable =
      !isDefault || !!signature || !!(keyPair && keyPair.secretKey) || opts.writable === true

    if (this._readonly || writable === false) {
      throw SESSION_NOT_WRITABLE('cannot append to a readonly core', this.discoveryKey)
    }

    blocks = Array.isArray(blocks) ? blocks : [blocks]

    const preappend = this.encryption && this._preappend

    const buffers = this.encodeBatch !== null ? this.encodeBatch(blocks) : new Array(blocks.length)

    if (this.encodeBatch === null) {
      for (let i = 0; i < blocks.length; i++) {
        buffers[i] = this._encode(this.valueEncoding, blocks[i])
      }
    }
    for (const b of buffers) {
      if (b.byteLength > MAX_SUGGESTED_BLOCK_SIZE) {
        throw BAD_ARGUMENT(
          'Appended block exceeds the maximum suggested block size',
          this.discoveryKey
        )
      }
    }

    return this.state.append(buffers, { keyPair, signature, preappend, postappend, maxLength })
  }

  async signable(length = -1, fork = -1) {
    if (this.opened === false) await this.opening
    if (length === -1) length = this.length
    if (fork === -1) fork = this.fork

    return caps.treeSignable(this.key, await this.treeHash(length), length, fork)
  }

  async treeHash(length = -1) {
    if (this.opened === false) await this.opening
    if (length === -1) length = this.length
    if (length > 0 && !(await this.has(length - 1))) await this.get(length - 1)

    const roots = await MerkleTree.getRoots(this.state, length)
    return crypto.tree(roots)
  }

  async missingNodes(index) {
    if (this.opened === false) await this.opening
    return await MerkleTree.missingNodes(this.core.state, 2 * index, this.core.state.length)
  }

  async proof(opts) {
    if (this.opened === false) await this.opening
    const rx = this.state.storage.read()
    const proofPromise = MerkleTree.proof(this.state, rx, opts)
    const blockPromise = opts && opts.block ? rx.getBlock(opts.block.index) : null
    rx.tryFlush()
    const [proof, block] = await Promise.all([proofPromise, blockPromise])
    const settled = await proof.settle()
    if (block) settled.block.value = block
    return settled
  }

  async applyProof(proof, from) {
    if (this.opened === false) await this.opening
    return this.core.verify(proof, from)
  }

  async verifyFullyRemote(proof) {
    if (this.opened === false) await this.opening
    const batch = await MerkleTree.verifyFullyRemote(this.state, proof)
    await this.core._verifyBatchUpgrade(batch, proof.manifest)
    return batch
  }

  generateRemoteProofForTreeNode(treeNodeIndex) {
    const blockProofIndex = flat.rightSpan(treeNodeIndex) / 2
    return proof(this, {
      index: blockProofIndex,
      // + 1 to length so the block is included
      upgrade: { start: 0, length: blockProofIndex + 1 }
    })
  }

  async recoverFromRemoteProof(remoteProof) {
    this.core.replicator.setPushOnly(true)
    this.core._repairMode = true

    await this.core.state.mutex.lock()

    try {
      const p = await verify(this.core.db, remoteProof)
      if (!p) return false

      const tx = this.core.storage.write()
      for (const node of p.proof.upgrade.nodes) {
        tx.putTreeNode(node)
      }
      await tx.flush()

      const succeed = p.proof.upgrade.nodes.length !== 0
      if (succeed) {
        this.core.replicator.setPushOnly(false)
      }
      return succeed
    } finally {
      this.core.state.mutex.unlock()
    }
  }

  recoverTreeNodeFromPeers() {
    this.core.replicator.setPushOnly(true)

    for (const peer of this.core.replicator.peers) {
      const req = {
        id: 0,
        fork: this.fork,
        upgrade: {
          start: 0,
          length: this.length
        }
      }
      peer.wireRequest.send(req)
    }
  }

  registerExtension(name, handlers = {}) {
    if (this.extensions.has(name)) {
      const ext = this.extensions.get(name)
      ext.handlers = handlers
      ext.encoding = c.from(handlers.encoding || c.buffer)
      ext.session = this
      return ext
    }

    const ext = {
      name,
      handlers,
      encoding: c.from(handlers.encoding || c.buffer),
      session: this,
      send(message, peer) {
        const buffer = c.encode(this.encoding, message)
        peer.extension(name, buffer)
      },
      broadcast(message) {
        const buffer = c.encode(this.encoding, message)
        for (const peer of this.session.peers) {
          peer.extension(name, buffer)
        }
      },
      destroy() {
        for (const peer of this.session.peers) {
          if (peer.extensions.get(name) === ext) peer.extensions.delete(name)
        }
        this.session.extensions.delete(name)
      },
      _onmessage(state, peer) {
        const m = this.encoding.decode(state)
        if (this.handlers.onmessage) this.handlers.onmessage(m, peer)
      }
    }

    this.extensions.set(name, ext)

    if (this.core === null) this._monitorIndex = -2
    else this.core.addMonitor(this)

    for (const peer of this.peers) {
      peer.extensions.set(name, ext)
    }

    return ext
  }

  _encode(enc, val) {
    const state = { start: this.padding, end: this.padding, buffer: null }

    if (b4a.isBuffer(val)) {
      if (state.start === 0) return val
      state.end += val.byteLength
    } else if (enc) {
      enc.preencode(state, val)
    } else {
      val = b4a.from(val)
      if (state.start === 0) return val
      state.end += val.byteLength
    }

    state.buffer = b4a.allocUnsafe(state.end)

    if (enc) enc.encode(state, val)
    else state.buffer.set(val, state.start)

    return state.buffer
  }

  _decode(enc, block, index) {
    if (this.encryption) block = block.subarray(this.encryption.padding(this.core, index))
    try {
      if (enc) return c.decode(enc, block)
    } catch (err) {
      throw DECODING_ERROR(err.message, this.discoveryKey)
    }
    return block
  }

  _getEncryptionProvider(e) {
    if (isEncryptionProvider(e)) return e
    if (!e || !e.key) return null
    return new DefaultEncryption(e.key, this.key, { block: e.block, compat: this.core.compat })
  }
}

module.exports = Hypercore

function isStream(s) {
  return typeof s === 'object' && s && typeof s.pipe === 'function'
}

async function preappend(blocks) {
  const offset = this.state.length
  const fork = this.state.encryptionFork

  for (let i = 0; i < blocks.length; i++) {
    await this.encryption.encrypt(offset + i, blocks[i], fork, this.core)
  }
}

function isValidIndex(index) {
  return index === 0 || index > 0
}

function maybeUnslab(block) {
  // Unslab only when it takes up less then half the slab
  return block !== null && 2 * block.byteLength < block.buffer.byteLength ? unslab(block) : block
}

function checkSnapshot(snapshot, index) {
  if (index >= snapshot.state.snapshotCompatLength) {
    throw SNAPSHOT_NOT_AVAILABLE(
      `snapshot at index ${index} not available (max compat length ${snapshot.state.snapshotCompatLength})`,
      snapshot.discoveryKey
    )
  }
}

function readBlock(rx, index) {
  const promise = rx.getBlock(index)
  rx.tryFlush()
  return promise
}

function initOnce(session, storage, key, opts) {
  if (storage === null) storage = opts.storage || null
  if (key === null) key = opts.key || null

  session.core = new Core(Hypercore.defaultStorage(storage), {
    preopen: opts.preopen,
    eagerUpgrade: opts.eagerUpgrade !== false,
    notDownloadingLinger: opts.notDownloadingLinger,
    allowFork: opts.allowFork !== false,
    allowPush: !!opts.allowPush,
    pushOnly: !!opts.pushOnly,
    alwaysLatestBlock: !!opts.allowLatestBlock,
    inflightRange: opts.inflightRange,
    compat: opts.compat === true,
    force: opts.force,
    createIfMissing: opts.createIfMissing,
    discoveryKey: opts.discoveryKey,
    overwrite: opts.overwrite,
    key,
    keyPair: opts.keyPair,
    legacy: opts.legacy,
    manifest: opts.manifest,
    globalCache: opts.globalCache || null // session is a temp option, not to be relied on unless you know what you are doing (no semver guarantees)
  })
}

function maybeAddMonitor(name) {
  if (name === 'append' || name === 'truncate') return
  if (this._monitorIndex >= 0 || this.closing) return

  if (this.core === null) {
    this._monitorIndex = -2
  } else {
    this.core.addMonitor(this)
  }
}

function isSessionMoved(err) {
  return err.code === 'SESSION_MOVED'
}

function getEncryptionOption(opts) {
  // old style, supported for now but will go away
  if (opts.encryptionKey) return { key: opts.encryptionKey, block: !!opts.isBlockKey }
  if (!opts.encryption) return null
  return b4a.isBuffer(opts.encryption) ? { key: opts.encryption } : opts.encryption
}

function isEncryptionProvider(e) {
  return e && isFunction(e.padding) && isFunction(e.encrypt) && isFunction(e.decrypt)
}

function isFunction(fn) {
  return !!fn && typeof fn === 'function'
}

function createDiscoveryKeyHandler(fn) {
  return ondiscoverykey
  function ondiscoverykey(id) {
    if (!id || id.byteLength !== 32) throw BAD_ARGUMENT('Invalid discovery key')
    return fn(id)
  }
}
const crypto = require('hypercore-crypto')
const flat = require('flat-tree')
const b4a = require('b4a')
const { MerkleTree } = require('./merkle-tree')

module.exports = async function auditCore(
  core,
  { tree = true, blocks = true, bitfield = true, dryRun = false } = {}
) {
  const length = core.state.length
  const stats = {
    treeNodes: 0,
    blocks: 0,
    bits: 0,
    droppedTreeNodes: 0,
    droppedBlocks: 0,
    droppedBits: 0,
    corrupt: false
  }

  // audit the tree
  if (tree) {
    let tx = null

    const roots = await MerkleTree.getRootsFromStorage(core.state.storage, length)
    const stack = []

    for (const r of roots) {
      if (r === null) {
        if (!dryRun) {
          const storage = core.state.storage
          await storage.store.deleteCore(storage.core)
          return null
        }

        stats.corrupt = true
      }

      stack.push(r)
    }

    stats.treeNodes += roots.length

    while (stack.length > 0) {
      const node = stack.pop()

      if ((node.index & 1) === 0) continue

      const [left, right] = flat.children(node.index)

      const rx = core.state.storage.read()
      const leftNodePromise = rx.getTreeNode(left)
      const rightNodePromise = rx.getTreeNode(right)

      rx.tryFlush()

      const [leftNode, rightNode] = await Promise.all([leftNodePromise, rightNodePromise])

      if (isBadTree(node, leftNode, rightNode)) {
        if (!tx && !stats.corrupt) tx = core.state.storage.write()
        const [l, r] = flat.spans(node.index)
        tx.deleteTreeNodeRange(l, r + 1)
        stats.droppedTreeNodes++
        continue
      }

      if (!leftNode) continue

      stats.treeNodes += 2
      stack.push(leftNode, rightNode)
    }

    if (tx && !dryRun) await tx.flush()
  }

  // audit the blocks
  if (blocks) {
    let tx = null

    for await (const block of core.state.storage.createBlockStream()) {
      if (!core.bitfield.get(block.index)) {
        if (!tx && !stats.corrupt) tx = core.state.storage.write()
        tx.deleteBlock(block.index)
        stats.droppedBlocks++
      }

      const rx = core.state.storage.read()
      const treeNodePromise = rx.getTreeNode(2 * block.index)

      rx.tryFlush()

      const treeNode = await treeNodePromise

      if (isBadBlock(treeNode, block.value)) {
        if (!tx && !stats.corrupt) tx = core.state.storage.write()
        tx.deleteBlock(block.index)
        stats.droppedBlocks++
        continue
      }

      stats.blocks++
    }

    if (tx && !dryRun) await tx.flush()
  }

  if (bitfield) {
    let tx = null

    for (const index of allBits(core.bitfield)) {
      const rx = core.state.storage.read()
      const blockPromise = rx.getBlock(index)

      rx.tryFlush()

      const block = await blockPromise
      if (!block) {
        stats.droppedBits++
        if (dryRun) continue

        if (!tx && !stats.corrupt) tx = core.state.storage.write()

        core.bitfield.set(index, false)

        const page = core.bitfield.getBitfield(index)
        if (page.bitfield) tx.putBitfieldPage(page.index, page.bitfield)
        else tx.deleteBitfieldPage(page.index)
        continue
      }

      stats.bits++
    }

    if (tx && !dryRun) await tx.flush()
  }

  return stats
}

function isBadBlock(node, block) {
  if (!node) return true
  const hash = crypto.data(block)
  return !b4a.equals(hash, node.hash) || node.size !== block.byteLength
}

function isBadTree(parent, left, right) {
  if (!left && !right) return false
  if (!left || !right) return true
  const hash = crypto.parent(left, right)
  return !b4a.equals(hash, parent.hash) || parent.size !== left.size + right.size
}

function* allBits(bitfield) {
  let i = 0
  if (bitfield.get(0)) yield 0
  while (true) {
    i = bitfield.findFirst(true, i + 1)
    if (i === -1) break
    yield i
  }
}
const b4a = require('b4a')
const quickbit = require('./compat').quickbit

module.exports = class BitInterlude {
  constructor() {
    this.ranges = []
  }

  contiguousLength(from) {
    for (const r of this.ranges) {
      if (r.start > from) break
      if (!r.value && r.start <= from) return r.start
    }

    // TODO: be smarter
    while (this.get(from) === true) from++
    return from
  }

  get(index) {
    let start = 0
    let end = this.ranges.length

    while (start < end) {
      const mid = (start + end) >> 1
      const r = this.ranges[mid]

      if (index < r.start) {
        end = mid
        continue
      }

      if (index >= r.end) {
        if (mid === start) break
        start = mid
        continue
      }

      return r.value
    }

    return false
  }

  setRange(start, end, value) {
    if (start === end) return

    let r = null

    for (let i = 0; i < this.ranges.length; i++) {
      r = this.ranges[i]

      // if already inside, stop
      if (r.start <= start && end <= r.end) {
        if (value === r.value) return

        const ranges = mergeRanges(r, { start, end, value })
        this.ranges.splice(i, 1, ...ranges)

        return
      }

      // we wanna overun the interval
      if (start > r.end) {
        continue
      }

      // we overran but this interval is ending after us, move it back
      if (end >= r.start && end <= r.end) {
        r.start = r.value === value ? start : end
        if (r.value !== value) this.ranges.splice(i, 0, { start, end, value })
        return
      }

      // we overran but our start is contained in this interval, move start back
      if (start >= r.start && start <= r.end) {
        if (r.value !== value) {
          r.end = start // Crop current comparison

          // If there's a next range
          if (this.ranges.length - 1 > i) {
            const next = this.ranges[i + 1]
            // If the same, go next
            if (next.value === value) continue
            // Else we overlap so update next range
            if (next.start < end) next.start = end
          }

          this.ranges.splice(++i, 0, { start, end, value })
          return
        }

        start = r.start
      }

      let remove = 0

      for (let j = i; j < this.ranges.length; j++) {
        const n = this.ranges[j]
        if (n.start > end || n.value !== value) break
        if (n.start <= end && n.end > end) end = n.end
        remove++
      }

      this.ranges.splice(i, remove, { start, end, value })
      return
    }

    if (r !== null) {
      if (start <= r.end && end > r.end) {
        r.end = end
        return
      }

      // we never
      if (r.end > start) return
    }

    this.ranges.push({ start, end, value })
  }

  flush(tx, bitfield) {
    if (!this.ranges.length) return []

    let index = this.ranges[0].start
    const final = this.ranges[this.ranges.length - 1].end

    let i = 0

    while (index < final) {
      const page = bitfield.getBitfield(index) // read only
      const pageIndex = page ? page.index : bitfield.getPageIndex(index)

      const buf = b4a.allocUnsafe(bitfield.getPageByteLength())

      if (page) {
        const src = page.bitfield // Uint32Array
        buf.set(b4a.from(src.buffer, src.byteOffset, src.byteLength), 0)
      } else {
        b4a.fill(buf, 0)
      }

      const last = (pageIndex + 1) * (buf.byteLength << 3)
      const offset = pageIndex * (buf.byteLength << 3)

      let hasValue = false

      while (i < this.ranges.length) {
        const { start, end, value } = this.ranges[i]

        if (!hasValue && value) hasValue = true

        const from = start < index ? index : start
        const to = end < last ? end : last

        quickbit.fill(buf, value, from - offset, to - offset)

        index = to

        if (to === last) break

        i++
      }

      if (page || hasValue) tx.putBitfieldPage(pageIndex, buf)
    }

    return this.ranges
  }
}

function mergeRanges(a, b) {
  const ranges = []
  if (a.start < b.start) ranges.push({ start: a.start, end: b.start, value: a.value })
  ranges.push({ start: b.start, end: b.end, value: b.value })
  if (b.end < a.end) ranges.push({ start: b.end, end: a.end, value: a.value })

  return ranges
}
const BigSparseArray = require('big-sparse-array')
const b4a = require('b4a')
const quickbit = require('./compat').quickbit

const BITS_PER_PAGE = 32768
const BYTES_PER_PAGE = BITS_PER_PAGE / 8
const WORDS_PER_PAGE = BYTES_PER_PAGE / 4
const BITS_PER_SEGMENT = 2097152
const BYTES_PER_SEGMENT = BITS_PER_SEGMENT / 8
const WORDS_PER_SEGMENT = BYTES_PER_SEGMENT / 4
const INITIAL_WORDS_PER_SEGMENT = 1024
const PAGES_PER_SEGMENT = BITS_PER_SEGMENT / BITS_PER_PAGE
const SEGMENT_GROWTH_FACTOR = 4

class BitfieldPage {
  constructor(index, segment) {
    this.index = index
    this.offset = index * BYTES_PER_PAGE - segment.offset
    this.bitfield = null
    this.segment = segment

    segment.add(this)
  }

  get tree() {
    return this.segment.tree
  }

  get(index, dirty) {
    return quickbit.get(this.bitfield, index)
  }

  set(index, val) {
    if (quickbit.set(this.bitfield, index, val)) {
      this.tree.update(this.offset * 8 + index)
    }
  }

  setRange(start, end, val) {
    quickbit.fill(this.bitfield, val, start, end)

    let i = Math.floor(start / 128)
    const n = i + Math.ceil((end - start) / 128)

    while (i <= n) this.tree.update(this.offset * 8 + i++ * 128)
  }

  findFirst(val, position) {
    return quickbit.findFirst(this.bitfield, val, position)
  }

  findLast(val, position) {
    return quickbit.findLast(this.bitfield, val, position)
  }

  count(start, length, val) {
    const end = start + length

    let i = start
    let c = 0

    while (length > 0) {
      const l = this.findFirst(val, i)
      if (l === -1 || l >= end) return c

      const h = this.findFirst(!val, l + 1)
      if (h === -1 || h >= end) return c + end - l

      c += h - l
      length -= h - i
      i = h
    }

    return c
  }
}

class BitfieldSegment {
  constructor(index, bitfield) {
    this.index = index
    this.offset = index * BYTES_PER_SEGMENT
    this.tree = quickbit.Index.from(bitfield, BYTES_PER_SEGMENT)
    this.pages = new Array(PAGES_PER_SEGMENT)
  }

  get bitfield() {
    return this.tree.field
  }

  add(page) {
    const i = page.index - this.index * PAGES_PER_SEGMENT
    this.pages[i] = page

    const start = i * WORDS_PER_PAGE
    const end = start + WORDS_PER_PAGE

    if (end >= this.bitfield.length) this.reallocate(end)

    page.bitfield = this.bitfield.subarray(start, end)
  }

  reallocate(length) {
    let target = this.bitfield.length
    while (target < length) target *= SEGMENT_GROWTH_FACTOR

    const bitfield = new Uint32Array(target)
    bitfield.set(this.bitfield)

    this.tree = quickbit.Index.from(bitfield, BYTES_PER_SEGMENT)

    for (let i = 0; i < this.pages.length; i++) {
      const page = this.pages[i]
      if (!page) continue

      const start = i * WORDS_PER_PAGE
      const end = start + WORDS_PER_PAGE

      page.bitfield = bitfield.subarray(start, end)
    }
  }

  findFirst(val, position) {
    position = this.tree.skipFirst(!val, position)

    let j = position & (BITS_PER_PAGE - 1)
    let i = (position - j) / BITS_PER_PAGE

    if (i >= PAGES_PER_SEGMENT) return -1

    while (i < this.pages.length) {
      const p = this.pages[i]

      let index = -1

      if (p) index = p.findFirst(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_PAGE + index

      j = 0
      i++
    }

    return -1
  }

  findLast(val, position) {
    position = this.tree.skipLast(!val, position)

    let j = position & (BITS_PER_PAGE - 1)
    let i = (position - j) / BITS_PER_PAGE

    if (i >= PAGES_PER_SEGMENT) return -1

    while (i >= 0) {
      const p = this.pages[i]

      let index = -1

      if (p) index = p.findLast(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_PAGE + index

      j = BITS_PER_PAGE - 1
      i--
    }

    return -1
  }
}

module.exports = class Bitfield {
  static BITS_PER_PAGE = BITS_PER_PAGE
  static BYTES_PER_PAGE = BYTES_PER_PAGE

  constructor(buffer) {
    this.resumed = !!(buffer && buffer.byteLength >= 0)

    this._pages = new BigSparseArray()
    this._segments = new BigSparseArray()

    const view = this.resumed
      ? new Uint32Array(buffer.buffer, buffer.byteOffset, Math.floor(buffer.byteLength / 4))
      : new Uint32Array(INITIAL_WORDS_PER_SEGMENT)

    for (let i = 0; i < view.length; i += WORDS_PER_SEGMENT) {
      let bitfield = view.subarray(i, i + WORDS_PER_SEGMENT)
      let length = WORDS_PER_SEGMENT

      if (i === 0) {
        length = INITIAL_WORDS_PER_SEGMENT
        while (length < bitfield.length) length *= SEGMENT_GROWTH_FACTOR
      }

      if (bitfield.length !== length) {
        const copy = new Uint32Array(length)
        copy.set(bitfield, 0)
        bitfield = copy
      }

      const segment = new BitfieldSegment(i / WORDS_PER_SEGMENT, bitfield)
      this._segments.set(segment.index, segment)

      for (let j = 0; j < bitfield.length; j += WORDS_PER_PAGE) {
        const page = new BitfieldPage((i + j) / WORDS_PER_PAGE, segment)
        this._pages.set(page.index, page)
      }
    }
  }

  static from(bitfield) {
    return new Bitfield(bitfield.toBuffer(bitfield._pages.maxLength * BITS_PER_PAGE))
  }

  toBuffer(length) {
    const pages = Math.ceil(length / BITS_PER_PAGE)
    const buffer = b4a.allocUnsafe(pages * BYTES_PER_PAGE)

    for (let i = 0; i < pages; i++) {
      const page = this._pages.get(i)
      const offset = i * BYTES_PER_PAGE

      if (page) {
        const buf = b4a.from(
          page.bitfield.buffer,
          page.bitfield.byteOffset,
          page.bitfield.byteLength
        )

        buffer.set(buf, offset)
      } else {
        buffer.fill(0, offset, offset + BYTES_PER_PAGE)
      }
    }

    return buffer
  }

  getBitfield(index) {
    const i = this.getPageIndex(index)

    const p = this._pages.get(i)
    return p || null
  }

  merge(bitfield, length) {
    let i = 0

    while (i < length) {
      const start = bitfield.firstSet(i)
      if (start === -1) break

      i = bitfield.firstUnset(start)

      if (i === -1 || i > length) i = length

      this.setRange(start, i, true)

      if (i >= length) break
    }
  }

  get(index) {
    const j = index & (BITS_PER_PAGE - 1)
    const i = (index - j) / BITS_PER_PAGE

    const p = this._pages.get(i)

    return p ? p.get(j) : false
  }

  getPageByteLength() {
    return BYTES_PER_PAGE
  }

  getPageIndex(index) {
    const j = index & (BITS_PER_PAGE - 1)
    return (index - j) / BITS_PER_PAGE
  }

  getPage(index, create) {
    const i = this.getPageIndex(index)

    let p = this._pages.get(i)

    if (p) return p

    if (!create) return null

    const k = Math.floor(i / PAGES_PER_SEGMENT)
    const s =
      this._segments.get(k) ||
      this._segments.set(
        k,
        new BitfieldSegment(
          k,
          new Uint32Array(k === 0 ? INITIAL_WORDS_PER_SEGMENT : WORDS_PER_SEGMENT)
        )
      )

    p = this._pages.set(i, new BitfieldPage(i, s))

    return p
  }

  set(index, val) {
    const j = index & (BITS_PER_PAGE - 1)
    const i = (index - j) / BITS_PER_PAGE

    let p = this._pages.get(i)

    if (!p && val) {
      const k = Math.floor(i / PAGES_PER_SEGMENT)
      const s =
        this._segments.get(k) ||
        this._segments.set(
          k,
          new BitfieldSegment(
            k,
            new Uint32Array(k === 0 ? INITIAL_WORDS_PER_SEGMENT : WORDS_PER_SEGMENT)
          )
        )

      p = this._pages.set(i, new BitfieldPage(i, s))
    }

    if (p) p.set(j, val)
  }

  setRange(start, end, val) {
    let j = start & (BITS_PER_PAGE - 1)
    let i = (start - j) / BITS_PER_PAGE

    while (start < end) {
      let p = this._pages.get(i)

      if (!p && val) {
        const k = Math.floor(i / PAGES_PER_SEGMENT)
        const s =
          this._segments.get(k) ||
          this._segments.set(
            k,
            new BitfieldSegment(
              k,
              new Uint32Array(k === 0 ? INITIAL_WORDS_PER_SEGMENT : WORDS_PER_SEGMENT)
            )
          )

        p = this._pages.set(i, new BitfieldPage(i, s))
      }

      const offset = i * BITS_PER_PAGE
      const last = Math.min(end - offset, BITS_PER_PAGE)
      const range = last - j

      if (p) p.setRange(j, last, val)

      j = 0
      i++
      start += range
    }
  }

  findFirst(val, position) {
    let j = position & (BITS_PER_SEGMENT - 1)
    let i = (position - j) / BITS_PER_SEGMENT

    while (i < this._segments.maxLength) {
      const s = this._segments.get(i)

      let index = -1

      if (s) index = s.findFirst(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_SEGMENT + index

      j = 0
      i++
    }

    return val ? -1 : this._segments.maxLength * BITS_PER_SEGMENT
  }

  firstSet(position) {
    return this.findFirst(true, position)
  }

  firstUnset(position) {
    return this.findFirst(false, position)
  }

  findLast(val, position) {
    let j = position & (BITS_PER_SEGMENT - 1)
    let i = (position - j) / BITS_PER_SEGMENT

    while (i >= 0) {
      const s = this._segments.get(i)

      let index = -1

      if (s) index = s.findLast(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_SEGMENT + index

      j = BITS_PER_SEGMENT - 1
      i--
    }

    return -1
  }

  lastSet(position) {
    return this.findLast(true, position)
  }

  lastUnset(position) {
    return this.findLast(false, position)
  }

  hasUnset(start, length) {
    const end = start + length

    let j = start & (BITS_PER_SEGMENT - 1)
    let i = (start - j) / BITS_PER_SEGMENT

    while (i < this._segments.maxLength) {
      const s = this._segments.get(i)
      const index = s ? s.findFirst(false, j) : j
      if (index !== -1) return i * BITS_PER_SEGMENT + index < end

      j = 0
      i++

      if (i * BITS_PER_SEGMENT >= end) return false
    }

    return true
  }

  hasSet(start, length) {
    const end = start + length

    let j = start & (BITS_PER_SEGMENT - 1)
    let i = (start - j) / BITS_PER_SEGMENT

    while (i < this._segments.maxLength) {
      const s = this._segments.get(i)

      let index = -1

      if (s) index = s.findFirst(true, j)

      if (index !== -1) return i * BITS_PER_SEGMENT + index < end

      j = 0
      i++

      if (i * BITS_PER_SEGMENT >= end) return false
    }

    return false
  }

  count(start, length, val) {
    let j = start & (BITS_PER_PAGE - 1)
    let i = (start - j) / BITS_PER_PAGE
    let c = 0

    while (length > 0) {
      const p = this._pages.get(i)

      const end = Math.min(j + length, BITS_PER_PAGE)
      const range = end - j

      if (p) c += p.count(j, range, val)
      else if (!val) c += range

      j = 0
      i++
      length -= range
    }

    return c
  }

  countSet(start, length) {
    return this.count(start, length, true)
  }

  countUnset(start, length) {
    return this.count(start, length, false)
  }

  *want(start, length) {
    if (start & 31) {
      const d = start & 31
      start -= d
      length += d
    }

    let j = start & (BITS_PER_SEGMENT - 1)
    let i = (start - j) / BITS_PER_SEGMENT

    while (length > 0) {
      const s = this._segments.get(i)

      if (s) {
        let end = Math.min(j + length, BITS_PER_SEGMENT)
        if (end & 31) end += 32 - (end & 31)

        yield {
          start: i * BITS_PER_SEGMENT + j,
          bitfield: s.bitfield.subarray(j / 32, end / 32)
        }
      }

      j = 0
      i++
      length -= BITS_PER_SEGMENT
    }
  }

  clear(tx) {
    return tx.deleteBitfieldPageRange(0, -1)
  }

  onupdate(ranges) {
    for (const { start, end, value } of ranges) {
      this.setRange(start, end, value)
    }
  }

  static async open(storage, length) {
    if (length === 0) return new Bitfield(storage, null)

    const pages = Math.ceil(length / BITS_PER_PAGE)
    const buffer = b4a.alloc(pages * BYTES_PER_PAGE)
    const stream = storage.createBitfieldStream({ lt: pages })

    for await (const { index, page } of stream) {
      buffer.set(page, index * BYTES_PER_PAGE)
    }

    return new Bitfield(buffer)
  }
}
const crypto = require('hypercore-crypto')
const sodium = require('sodium-universal')
const b4a = require('b4a')
const c = require('compact-encoding')

// TODO: rename this to "crypto" and move everything hashing related etc in here
// Also lets move the tree stuff from hypercore-crypto here

const [
  TREE,
  REPLICATE_INITIATOR,
  REPLICATE_RESPONDER,
  MANIFEST,
  DEFAULT_NAMESPACE,
  DEFAULT_ENCRYPTION
] = crypto.namespace('hypercore', 6)

exports.MANIFEST = MANIFEST
exports.DEFAULT_NAMESPACE = DEFAULT_NAMESPACE
exports.DEFAULT_ENCRYPTION = DEFAULT_ENCRYPTION

exports.replicate = function (isInitiator, key, handshakeHash) {
  const out = b4a.allocUnsafe(32)
  sodium.crypto_generichash_batch(
    out,
    [isInitiator ? REPLICATE_INITIATOR : REPLICATE_RESPONDER, key],
    handshakeHash
  )
  return out
}

exports.treeSignable = function (manifestHash, treeHash, length, fork) {
  const state = { start: 0, end: 112, buffer: b4a.allocUnsafe(112) }
  c.fixed32.encode(state, TREE)
  c.fixed32.encode(state, manifestHash)
  c.fixed32.encode(state, treeHash)
  c.uint64.encode(state, length)
  c.uint64.encode(state, fork)
  return state.buffer
}

exports.treeSignableCompat = function (hash, length, fork, noHeader) {
  const end = noHeader ? 48 : 80
  const state = { start: 0, end, buffer: b4a.allocUnsafe(end) }
  if (!noHeader) c.fixed32.encode(state, TREE) // ultra legacy mode, kill in future major
  c.fixed32.encode(state, hash)
  c.uint64.encode(state, length)
  c.uint64.encode(state, fork)
  return state.buffer
}
// Export the appropriate version of `quickbit-universal` as the plain import
// may resolve to an older version in some environments
let quickbit = require('quickbit-universal')
if (
  typeof quickbit.findFirst !== 'function' ||
  typeof quickbit.findLast !== 'function' ||
  typeof quickbit.clear !== 'function'
) {
  // This should always load the fallback from the locally installed version
  quickbit = require('quickbit-universal/fallback')
}
exports.quickbit = quickbit
const crypto = require('hypercore-crypto')
const flat = require('flat-tree')
const b4a = require('b4a')
const quickbit = require('quickbit-universal')
const Bitfield = require('./bitfield')

const MAX_BATCH_USED = 4 * 1024 * 1024
const MIN_BATCH_USED = 512 * 1024

// just in its own file as its a bit involved

module.exports = copyPrologue

async function copyPrologue(src, dst) {
  const prologue = dst.header.manifest.prologue

  if (src.length < prologue.length || prologue.length === 0) return

  const stack = []
  const roots = flat.fullRoots(prologue.length * 2)
  const batch = { roots, first: true, last: false, contig: 0, used: 0, tree: [], blocks: [] }

  for (let i = 0; i < roots.length; i++) {
    const node = roots[i]
    batch.tree.push(node)
    stack.push(node)
  }

  let lastPage = -1
  let lastBlock = -1

  for await (const data of src.storage.createBlockStream({
    gte: 0,
    lt: prologue.length,
    reverse: true
  })) {
    if (walkTree(stack, data.index * 2, batch) === false) {
      throw new Error('Missing block or tree node for ' + data.index)
    }

    batch.contig = data.index + 1 === lastBlock ? batch.contig + 1 : 1
    lastBlock = data.index

    const page = getBitfieldPage(data.index)
    batch.blocks.push(data)

    if (lastPage !== page) batch.used += 4096
    batch.used += Math.max(data.value.byteLength, 128) // 128 is just a sanity number to avoid mega batches

    // always safe to partially flush so we do that ondemand to reduce memory usage...
    if ((batch.used >= MIN_BATCH_USED && page !== lastPage) || batch.used >= MAX_BATCH_USED) {
      await flushBatch(prologue, src, dst, batch)
    }

    lastPage = page
  }

  if (lastBlock !== 0) batch.contig = 0

  batch.last = true
  await flushBatch(prologue, src, dst, batch)
}

async function flushBatch(prologue, src, dst, batch) {
  const nodePromises = []

  const srcReader = src.storage.read()
  for (const index of batch.tree) {
    nodePromises.push(srcReader.getTreeNode(index))
  }
  srcReader.tryFlush()

  const nodes = await Promise.all(nodePromises)

  const pagePromises = []
  const dstReader = dst.storage.read()

  const headPromise = batch.first ? dstReader.getHead() : null
  if (headPromise) headPromise.catch(noop)

  let lastPage = -1
  for (const { index } of batch.blocks) {
    const page = getBitfieldPage(index)
    if (page === lastPage) continue
    lastPage = page
    pagePromises.push(dstReader.getBitfieldPage(page))
  }

  dstReader.tryFlush()

  const pages = await Promise.all(pagePromises)
  const head = headPromise === null ? null : await headPromise
  const userData = []

  // reads done!

  if (batch.first) {
    const roots = nodes.slice(0, batch.roots.length)

    for (const node of roots) {
      if (!node) throw new Error('Missing nodes for prologue hash')
    }

    const treeHash = crypto.tree(roots)
    if (!b4a.equals(treeHash, prologue.hash)) throw new Error('Prologue does not match source')
  }

  if (batch.first) {
    for await (const data of src.storage.createUserDataStream()) userData.push(data)
  }

  for (let i = 0; i < pages.length; i++) {
    if (!pages[i]) pages[i] = b4a.alloc(4096)
  }

  const tx = dst.storage.write()

  for (const node of nodes) tx.putTreeNode(node)

  lastPage = -1
  let pageIndex = -1

  for (const { index, value } of batch.blocks) {
    const page = getBitfieldPage(index)

    if (page !== lastPage) {
      lastPage = page
      pageIndex++
      // queue the page now, we mutate it below but its the same ref
      tx.putBitfieldPage(pageIndex, pages[pageIndex])
    }

    const pageBuffer = pages[pageIndex]
    quickbit.set(pageBuffer, getBitfieldOffset(index), true)
    tx.putBlock(index, value)
  }

  for (const { key, value } of userData) {
    tx.putUserData(key, value)
  }

  let upgraded = batch.first && !head
  if (upgraded) {
    tx.setHead(prologueToTree(prologue))
  }

  await tx.flush()

  if (upgraded) {
    const roots = nodes.slice(0, batch.roots.length)
    dst.state.setRoots(roots)
    dst.header.tree = prologueToTree(prologue)
  }

  if (userData.length > 0) {
    dst.header.userData = userData.concat(dst.header.userData)
  }

  if (batch.contig) {
    // TODO: we need to persist this somehow
    dst.header.hints.contiguousLength = batch.contig
  }

  let start = 0
  let length = 0

  // update in memory bitfield
  for (const { index } of batch.blocks) {
    if (start === 0 || start - 1 === index) {
      length++
    } else {
      if (length > 0) signalReplicator(dst, upgraded, start, length)
      upgraded = false
      length = 1
    }

    start = index
    dst.bitfield.set(index, true)
  }

  if (length > 0) signalReplicator(dst, upgraded, start, length)

  // unlink
  batch.tree = []
  batch.blocks = []
  batch.first = false
  batch.used = 0
}

function signalReplicator(core, upgraded, start, length) {
  if (upgraded) {
    core.replicator.cork()
    core.replicator.onhave(start, length, false)
    core.replicator.onupgrade()
    core.replicator.uncork()
  } else {
    core.replicator.onhave(start, length, false)
  }
}

function prologueToTree(prologue) {
  return {
    fork: 0,
    length: prologue.length,
    rootHash: prologue.hash,
    signature: null
  }
}

function getBitfieldPage(index) {
  return Math.floor(index / Bitfield.BITS_PER_PAGE)
}

function getBitfieldOffset(index) {
  return index & (Bitfield.BITS_PER_PAGE - 1)
}

function walkTree(stack, target, batch) {
  while (stack.length > 0) {
    const node = stack.pop()

    if ((node & 1) === 0) {
      if (node === target) return true
      continue
    }

    const ite = flat.iterator(node)
    if (!ite.contains(target)) continue

    while ((ite.index & 1) !== 0) {
      const left = ite.leftChild()
      const right = ite.sibling() // is right child

      batch.tree.push(left, right)

      if (ite.contains(target)) stack.push(left)
      else ite.sibling()
    }

    if (ite.index === target) return true
  }

  return false
}

function noop() {}
const crypto = require('hypercore-crypto')
const b4a = require('b4a')
const unslab = require('unslab')
const z32 = require('z32')
const Mutex = require('./mutex')
const { MerkleTree, ReorgBatch } = require('./merkle-tree')
const BitInterlude = require('./bit-interlude')
const Bitfield = require('./bitfield')
const RemoteBitfield = require('./remote-bitfield')
const {
  BAD_ARGUMENT,
  STORAGE_EMPTY,
  STORAGE_CONFLICT,
  INVALID_SIGNATURE,
  INVALID_CHECKSUM
} = require('hypercore-errors')
const Verifier = require('./verifier')
const audit = require('./audit')
const copyPrologue = require('./copy-prologue')
const SessionState = require('./session-state')
const Replicator = require('./replicator')

module.exports = class Core {
  constructor(db, opts = {}) {
    this.db = db
    this.storage = null
    this.replicator = new Replicator(this, opts)
    this.sessionStates = []
    this.monitors = []
    this.activeSessions = 0
    this.gc = 0 // corestore uses this to main a gc strike pool

    this.id = opts.key ? z32.encode(opts.key) : null
    this.key = opts.key || null
    this.discoveryKey = opts.discoveryKey || (opts.key && crypto.discoveryKey(opts.key)) || null
    this.manifest = null
    this.opening = null
    this.closing = null
    this.exclusive = null

    this.preupdate = null
    this.header = null
    this.compat = false
    this.bitfield = null
    this.verifier = null
    this.truncating = 0
    this.skipBitfield = null
    this.globalCache = opts.globalCache || null
    this.autoClose = opts.autoClose !== false
    this.onidle = noop

    this.state = null
    this.opened = false
    this.destroyed = false
    this.closed = false

    this.hintsChanged = false
    this.remoteContiguousLengthChanged = false

    this._bitfield = null
    this._verifies = null
    this._verifiesFlushed = null
    this._legacy = !!opts.legacy
    this._repairMode = false

    this.opening = this._open(opts)
    this.opening.catch(noop)
  }

  static setRecoveryPeers(peers) {
    SessionState.RECOVERY_PEERS = peers
  }

  ready() {
    return this.opening
  }

  addMonitor(s) {
    if (s._monitorIndex >= 0) return
    s._monitorIndex = this.monitors.push(s) - 1
  }

  removeMonitor(s) {
    if (s._monitorIndex < 0) return
    const head = this.monitors.pop()
    if (head !== s) this.monitors[(head._monitorIndex = s._monitorIndex)] = head
    s._monitorIndex = -1
  }

  emitRemoteContiguousLength() {
    if (!this.remoteContiguousLengthChanged) return
    this.remoteContiguousLengthChanged = false

    const length = this.header.hints.remoteContiguousLength

    for (let i = this.monitors.length - 1; i >= 0; i--) {
      this.monitors[i].emit('remote-contiguous-length', length)
    }
  }

  emitManifest() {
    for (let i = this.monitors.length - 1; i >= 0; i--) {
      this.monitors[i].emit('manifest')
    }
  }

  createUserDataStream(opts, session = this.state) {
    return session.storage.createUserDataStream(opts)
  }

  allSessions() {
    const sessions = []
    for (const state of this.sessionStates) {
      if (state.sessions.length) sessions.push(...state.sessions)
    }
    return sessions
  }

  hasSession() {
    return this.activeSessions !== 0
  }

  compact() {
    const compacting = []
    for (const s of this.sessionStates) {
      compacting.push(s.storage.compact())
    }
    return Promise.all(compacting)
  }

  checkIfIdle() {
    if (!this.opened || this.destroyed === true || this.hasSession() === true) return
    if (this.replicator.idle() === false) return
    if (this.state === null || this.state.mutex.idle() === false) return
    this.onidle()
  }

  async lockExclusive() {
    if (this.exclusive === null) this.exclusive = new Mutex()
    await this.exclusive.lock()
  }

  unlockExclusive() {
    if (this.exclusive !== null) this.exclusive.unlock()
  }

  async _open(opts) {
    try {
      await this._tryOpen(opts)
    } catch (err) {
      this.onidle()
      throw err
    }

    this.opened = true
  }

  async _tryOpen(opts) {
    if (opts.preopen) await opts.preopen // just a hook to allow exclusive access here...

    let storage = await this.db.resumeCore(this.discoveryKey)

    let overwrite = opts.overwrite === true

    const force = opts.force === true
    const createIfMissing = opts.createIfMissing !== false
    // kill this flag soon
    const legacy = !!opts.legacy

    // default to true for now if no manifest is provided
    let compat = opts.compat === true || (opts.compat !== false && !opts.manifest)

    let header = storage ? parseHeader(await getCoreInfo(storage)) : null

    const hadManifest = !!header && !!header.manifest && !!header.key
    const hadKeyPair = !!header && !!header.keyPair

    if (force && opts.key && header && !b4a.equals(header.key, opts.key)) {
      overwrite = true
    }

    if (!header && opts.discoveryKey && !(opts.key || opts.manifest)) {
      throw STORAGE_EMPTY('No Hypercore is stored here', this.discoveryKey)
    }

    if (!header || overwrite) {
      if (!createIfMissing) {
        throw STORAGE_EMPTY('No Hypercore is stored here', this.discoveryKey)
      }

      if (compat) {
        if (opts.key && opts.keyPair && !b4a.equals(opts.key, opts.keyPair.publicKey)) {
          throw BAD_ARGUMENT('Key must match publicKey when in compat mode', this.discoveryKey)
        }
      }

      const keyPair = opts.keyPair || (opts.key ? null : crypto.keyPair())

      const defaultManifest =
        !opts.manifest &&
        (!!opts.compat || !opts.key || !!(keyPair && b4a.equals(opts.key, keyPair.publicKey)))
      const manifest = defaultManifest
        ? Verifier.defaultSignerManifest(opts.key || keyPair.publicKey)
        : Verifier.createManifest(opts.manifest)

      header = {
        key: opts.key || (compat ? manifest.signers[0].publicKey : Verifier.manifestHash(manifest)),
        manifest,
        keyPair: keyPair
          ? { publicKey: keyPair.publicKey, secretKey: keyPair.secretKey || null }
          : null,
        frozen: false,
        tree: {
          fork: 0,
          length: 0,
          rootHash: null,
          signature: null
        },
        hints: {
          reorgs: [],
          contiguousLength: 0,
          remoteContiguousLength: 0,
          recovering: 0
        }
      }

      const discoveryKey = opts.discoveryKey || crypto.discoveryKey(header.key)

      storage = await this.db.createCore({
        key: header.key,
        manifest,
        keyPair,
        frozen: false,
        discoveryKey,
        userData: opts.userData || [],
        alias: opts.alias || null
      })
    }

    // unslab the long lived buffers to avoid keeping the slab alive
    header.key = unslab(header.key)

    if (header.tree) {
      header.tree.rootHash = unslab(header.tree.rootHash)
      header.tree.signature = unslab(header.tree.signature)
    }

    if (header.keyPair) {
      header.keyPair.publicKey = unslab(header.keyPair.publicKey)
      header.keyPair.secretKey = unslab(header.keyPair.secretKey)
    }

    if (header.keyPair) {
      header.keyPair.publicKey = unslab(header.keyPair.publicKey)
      header.keyPair.secretKey = unslab(header.keyPair.secretKey)
    }

    if (opts.manifest) {
      // if we provide a manifest and no key, verify that the stored key is the same
      if (
        !opts.key &&
        !Verifier.isValidManifest(header.key, Verifier.createManifest(opts.manifest))
      ) {
        throw STORAGE_CONFLICT('Manifest does not hash to provided key', this.discoveryKey)
      }

      if (!header.manifest) header.manifest = opts.manifest
    }

    if (opts.key && !b4a.equals(header.key, opts.key)) {
      throw STORAGE_CONFLICT('Another Hypercore is stored here', this.discoveryKey)
    }

    // if we signalled compat, but already now this core isn't disable it
    if (compat && header.manifest && !Verifier.isCompat(header.key, header.manifest)) {
      compat = false
    } else if (!compat && header.manifest && Verifier.isCompat(header.key, header.manifest)) {
      compat = true
    }

    const prologue = header.manifest ? header.manifest.prologue : null

    const bitfield = await Bitfield.open(storage, header.tree.length)

    const treeInfo = {
      fork: header.tree.fork,
      length: header.tree.length,
      signature: header.tree.signature,
      roots: await maybeGetRootsFromStorage(storage, header.tree.length),
      prologue
    }

    this._repairMode = !treeInfo.roots.length && treeInfo.length && !overwrite
    // Set push only mode if in repair mode
    if (this._repairMode) {
      this.replicator.setPushOnly(true)
    }

    if (overwrite) {
      const tx = storage.write()
      tx.deleteTreeNodeRange(0, -1)
      tx.deleteBlockRange(0, -1)
      bitfield.clear(tx)
      await tx.flush()
    }

    const len = bitfield.findFirst(false, header.hints.contiguousLength)
    if (header.hints.contiguousLength !== len && !storage.readOnly) {
      header.hints.contiguousLength = len
      const tx = storage.write()
      tx.setHints(header.hints)
      await tx.flush()
    }

    // to unslab
    if (header.manifest) {
      header.manifest = Verifier.createManifest(header.manifest)
      if (!hadManifest || (header.keyPair && !hadKeyPair)) {
        const tx = storage.write()
        tx.setAuth({
          key: header.key,
          discoveryKey: crypto.discoveryKey(header.key),
          manifest: header.manifest,
          keyPair: header.keyPair
        })
        await tx.flush()
      }
    }

    const verifier = header.manifest
      ? new Verifier(header.key, header.manifest, { crypto, legacy })
      : null

    this.storage = storage
    this.header = header
    this.compat = compat
    this.bitfield = bitfield
    this.verifier = verifier
    this.state = new SessionState(this, null, storage, treeInfo, null)

    if (this.key === null) this.key = this.header.key
    if (this.discoveryKey === null) this.discoveryKey = crypto.discoveryKey(this.key)
    if (this.id === null) this.id = z32.encode(this.key)
    if (this.manifest === null) this.manifest = this.header.manifest
  }

  async audit(opts) {
    await this.state.mutex.lock()

    try {
      return await audit(this, opts)
    } finally {
      this.state._unlock()
    }
  }

  async setManifest(manifest) {
    await this.state.mutex.lock()

    try {
      if (manifest && this.header.manifest === null) {
        if (!Verifier.isValidManifest(this.header.key, manifest)) {
          throw INVALID_CHECKSUM('Manifest hash does not match', this.discoveryKey)
        }

        const tx = this.state.createWriteBatch()
        this._setManifest(tx, Verifier.createManifest(manifest), null)
        await this.state.flush()
      }
    } finally {
      this.state._unlock()
    }
  }

  _setManifest(tx, manifest, keyPair) {
    if (!manifest && b4a.equals(keyPair.publicKey, this.header.key)) {
      manifest = Verifier.defaultSignerManifest(this.header.key)
    }
    if (!manifest) return

    const verifier = new Verifier(this.header.key, manifest, { legacy: this._legacy })

    if (verifier.prologue) this.state.prologue = Object.assign({}, verifier.prologue)

    this.manifest = this.header.manifest = manifest

    tx.setAuth({
      key: this.header.key,
      discoveryKey: this.discoveryKey,
      manifest,
      keyPair: this.header.keyPair
      // TODO: encryptionKey?
    })

    this.compat = verifier.compat
    this.verifier = verifier

    this.replicator.onupgrade()
    this.emitManifest()
  }

  async copyPrologue(src) {
    await this.state.mutex.lock()

    try {
      await src.mutex.lock()
    } catch (err) {
      this.state.mutex.unlock()
      throw err
    }

    try {
      await copyPrologue(src, this)
    } finally {
      src.mutex.unlock()
      this.state.mutex.unlock()
      this.checkIfIdle()
    }
  }

  flushed() {
    return this.state.flushed()
  }

  async _validateCommit(state, treeLength) {
    if (this.state.length > state.length) {
      return false // TODO: partial commit and truncation possible in the future
    }

    if (this.state.length > treeLength) {
      for (const root of this.state.roots) {
        const batchRoot = await MerkleTree.get(state, root.index)
        if (batchRoot.size !== root.size || !b4a.equals(batchRoot.hash, root.hash)) {
          return false
        }
      }
    }

    if (this.verifier === null) {
      return false // easier to assert than upsert
    }

    return true
  }

  _verifyBatchUpgrade(batch, manifest) {
    if (!this.header.manifest) {
      // compat, drop at some point
      if (!manifest) manifest = Verifier.defaultSignerManifest(this.header.key)

      if (
        !manifest ||
        !(
          Verifier.isValidManifest(this.header.key, manifest) ||
          Verifier.isCompat(this.header.key, manifest)
        )
      ) {
        throw INVALID_SIGNATURE('Proof contains an invalid manifest', this.discoveryKey) // TODO: proper error type
      }
    }

    const verifier =
      this.verifier ||
      new Verifier(this.header.key, Verifier.createManifest(manifest), { legacy: this._legacy })

    if (!verifier.verify(batch, batch.signature)) {
      throw INVALID_SIGNATURE('Proof contains an invalid signature', this.discoveryKey)
    }

    return manifest
  }

  async _verifyExclusive({ batch, bitfield, value, manifest }) {
    manifest = this._verifyBatchUpgrade(batch, manifest)

    if (
      !(await this.state._verifyBlock(
        batch,
        bitfield,
        value,
        this.header.manifest ? null : manifest
      ))
    ) {
      return false
    }

    if (!batch.upgraded && bitfield) {
      this.replicator.onhave(bitfield.start, bitfield.length, bitfield.drop)
    }

    return true
  }

  async _verifyShared() {
    if (!this._verifies.length) return false

    await this.state.mutex.lock()

    const tx = this.state.createWriteBatch()

    const verifies = this._verifies
    this._verifies = null
    this._verified = null

    try {
      for (const { batch, bitfield, value } of verifies) {
        if (!batch.commitable()) continue

        if (bitfield) {
          tx.putBlock(bitfield.start, value)
        }
      }

      const bits = new BitInterlude()

      for (let i = 0; i < verifies.length; i++) {
        const { batch, bitfield, manifest } = verifies[i]

        if (!batch.commitable()) {
          verifies[i] = null // signal that we cannot commit this one
          continue
        }

        if (bitfield) {
          bits.setRange(bitfield.start, bitfield.start + 1, true)
        }

        // if we got a manifest AND its strictly a non compat one, lets store it
        if (manifest && this.header.manifest === null) {
          if (!Verifier.isValidManifest(this.header.key, manifest)) {
            throw INVALID_CHECKSUM('Manifest hash does not match', this.discoveryKey)
          }
          this._setManifest(tx, manifest, null)
        }

        if (batch.commitable()) batch.commit(tx)
      }

      const ranges = bits.flush(tx, this.bitfield)

      await this.state.flush()

      for (const { start, end, value } of ranges) {
        this._setBitfieldRanges(start, end, value)
      }

      for (let i = 0; i < verifies.length; i++) {
        const bitfield = verifies[i] && verifies[i].bitfield
        if (bitfield) {
          this.updateContiguousLength(bitfield)
          this.replicator.onhave(bitfield.start, bitfield.length, bitfield.drop)
        }
      }

      if (this.hintsChanged) await this.flushHints()
    } finally {
      this.state._clearActiveBatch()
      this.state.mutex.unlock()
    }

    return verifies[0] !== null
  }

  async flushHints() {
    if (!this.hintsChanged) return
    this.hintsChanged = false // we unset this immediately as a "debounce"

    const tx = this.state.storage.write()

    tx.setHints({
      contiguousLength: this.header.hints.contiguousLength,
      remoteContiguousLength: this.header.hints.remoteContiguousLength,
      recovering: this.header.hints.recovering
    })

    await tx.flush()
  }

  async checkConflict(proof, from) {
    if (this.state.length < proof.upgrade.length || proof.fork !== this.state.fork) {
      // out of date this proof - ignore for now
      return false
    }

    // sanity check -> no manifest, no way to verify
    if (!this.header.manifest) {
      return false
    }

    const batch = MerkleTree.verifyFullyRemote(this.state, proof)

    try {
      this._verifyBatchUpgrade(batch, proof.manifest)
    } catch {
      return true
    }

    const roots = await maybeGetRootsFromStorage(this.storage, proof.upgrade.length)
    const remoteTreeHash = crypto.tree(proof.upgrade.nodes)
    const localTreeHash = crypto.tree(roots)

    try {
      const rx = this.state.storage.read()
      const treeProofPromise = MerkleTree.proof(this.state, rx, {
        block: null,
        hash: null,
        seek: null,
        upgrade: {
          start: 0,
          length: proof.upgrade.length
        }
      })

      rx.tryFlush()

      const treeProof = await treeProofPromise

      const verifyBatch = MerkleTree.verifyFullyRemote(this.state, await treeProof.settle())
      this._verifyBatchUpgrade(verifyBatch, this.header.manifest)
    } catch (err) {
      if (err.code !== 'INVALID_OPERATION') return true

      return !(await this._repairTreeNodes(proof))
    }

    // both proofs are valid, now check if they forked
    if (b4a.equals(localTreeHash, remoteTreeHash)) return false

    await this.state.mutex.lock()

    try {
      const tx = this.state.createWriteBatch()

      this.header.frozen = true

      tx.setAuth({
        key: this.header.key,
        discoveryKey: this.discoveryKey,
        manifest: this.header.manifest,
        keyPair: this.header.keyPair,
        frozen: true
      })

      await this.state.flush()
    } finally {
      this.state.mutex.unlock()
    }

    // tmp log so we can see these
    const id = b4a.toString(this.discoveryKey, 'hex')
    console.log(
      '[hypercore] conflict detected in ' +
        id +
        ' (writable=' +
        !!this.header.keyPair +
        ',quorum=' +
        this.header.manifest.quorum +
        ')'
    )
    await this._onconflict(proof)
    return true
  }

  async _repairTreeNodes(proof) {
    if (!this._repairMode) return false

    await this.state.mutex.lock()

    for (let i = this.monitors.length - 1; i >= 0; i--) {
      this.monitors[i].emit('repairing', proof)
    }

    try {
      const batch = MerkleTree.verifyFullyRemote(this.state, proof)
      this._verifyBatchUpgrade(batch, proof.manifest)
    } catch {
      this.state.mutex.unlock()
      for (let i = this.monitors.length - 1; i >= 0; i--) {
        this.monitors[i].emit('repair-failed')
      }
      return false
    }

    // Attempt to repair local merkle tree with remote roots
    const atom = this.storage.createAtom()
    const atomized = this.storage.atomize(atom)
    const tx = atomized.write()
    for (const node of proof.upgrade.nodes) {
      tx.putTreeNode(node)
    }
    await tx.flush()

    // Try local proof again
    try {
      const rx = atomized.read()
      const treeProofPromise = MerkleTree.proof(this.state, rx, {
        block: null,
        hash: null,
        seek: null,
        upgrade: {
          start: 0,
          length: proof.upgrade.length
        }
      })

      rx.tryFlush()

      const treeProof = await treeProofPromise

      const verifyBatch = MerkleTree.verifyFullyRemote(this.state, await treeProof.settle())
      this._verifyBatchUpgrade(verifyBatch, this.header.manifest)
    } catch (err) {
      this.state.mutex.unlock()
      for (let i = this.monitors.length - 1; i >= 0; i--) {
        this.monitors[i].emit('repair-failed')
      }
      return false
    }

    await atom.flush()

    for (let i = this.monitors.length - 1; i >= 0; i--) {
      this.monitors[i].emit('repaired', proof)
    }
    this.replicator.setPushOnly(false)
    this.state.mutex.unlock()
    return true
  }

  async verifyReorg(proof) {
    const batch = new ReorgBatch(this.state)
    await MerkleTree.reorg(this.state, proof, batch)
    const manifest = this._verifyBatchUpgrade(batch, proof.manifest)

    if (manifest && !this.header.manifest) {
      await this.state.mutex.lock()
      try {
        if (manifest && this.header.manifest === null) {
          const tx = this.state.createWriteBatch()
          this._setManifest(tx, Verifier.createManifest(manifest), null)
          await this.state.flush()
        }
      } finally {
        this.state._unlock()
      }
    }

    return batch
  }

  async verify(proof, from) {
    // We cannot apply "other forks" atm.
    // We should probably still try and they are likely super similar for non upgrades
    // but this is easy atm (and the above layer will just retry)
    if (proof.fork !== this.state.fork) return false

    const batch = await MerkleTree.verify(this.state, proof)

    if (batch.upgraded && batch.length <= this.state.length) {
      await batch.downgrade()
    }

    if (!batch.commitable()) {
      return false
    }

    const value = (proof.block && proof.block.value) || null
    const op = {
      batch,
      bitfield: value && { drop: false, start: proof.block.index, length: 1 },
      value,
      manifest: proof.manifest,
      from
    }

    if (batch.upgraded) {
      return this._verifyExclusive(op)
    }

    if (this._verifies !== null) {
      const verifies = this._verifies
      const i = verifies.push(op)
      await this._verified
      return verifies[i] !== null
    }

    this._verifies = [op]
    this._verified = this._verifyShared()

    return this._verified
  }

  async reorg(batch) {
    if (!batch.commitable()) return false

    this.truncating++

    try {
      await this.state.reorg(batch)
    } finally {
      this.truncating--
    }

    return true
  }

  openSkipBitfield() {
    if (this.skipBitfield !== null) return this.skipBitfield
    this.skipBitfield = new RemoteBitfield()
    const buf = this.bitfield.toBuffer(this.state.length)
    const bitfield = new Uint32Array(buf.buffer, buf.byteOffset, buf.byteLength / 4)
    this.skipBitfield.insert(0, bitfield)
    return this.skipBitfield
  }

  _setBitfieldRanges(start, end, value) {
    this.bitfield.setRange(start, end, value)
    if (this.skipBitfield !== null) this.skipBitfield.setRange(start, end, value)
  }

  close() {
    if (!this.closing) this.closing = this._close()
    return this.closing
  }

  updateContiguousLength(bitfield) {
    const contig = updateContigBatch(this.header.hints.contiguousLength, bitfield, this.bitfield)

    if (contig.length !== -1 && contig.length !== this.header.hints.contiguousLength) {
      this.header.hints.contiguousLength = contig.length
      this.hintsChanged = true
    }
  }

  updateRemoteContiguousLength(length) {
    this.header.hints.remoteContiguousLength = length
    this.hintsChanged = true
    this.remoteContiguousLengthChanged = true
  }

  onappend(tree, bitfield) {
    this.header.tree = tree

    if (!bitfield) {
      this.replicator.onupgrade()
      return
    }

    this.replicator.cork()

    const { start, length, drop } = bitfield

    this._setBitfieldRanges(start, start + length, true)
    this.updateContiguousLength({ start, length, drop: false })

    this.replicator.onupgrade()
    this.replicator.onhave(start, length, drop)
    this.replicator.uncork()
  }

  ontruncate(tree, { start, length }) {
    if (tree) this.header.tree = tree

    this.replicator.cork()

    this.replicator.ontruncate(start, length)
    this.replicator.onhave(start, length, true)
    this.replicator.onupgrade()
    this.replicator.uncork()

    for (const sessionState of this.sessionStates) {
      if (start < sessionState.snapshotCompatLength) sessionState.snapshotCompatLength = start
    }

    this._setBitfieldRanges(start, start + length, false)
    this.updateContiguousLength({ start, length, drop: true })
  }

  async _onconflict(proof) {
    await this.replicator.onconflict()

    for (let i = this.monitors.length - 1; i >= 0; i--) {
      const s = this.monitors[i]
      s.emit('conflict', proof.upgrade.length, proof.fork, proof)
    }

    const err = new Error('Two conflicting signatures exist for length ' + proof.upgrade.length)
    await this.closeAllSessions(err)
  }

  async closeAllSessions(err) {
    // this.sessions modifies itself when a session closes
    // This way we ensure we indeed iterate over all sessions
    const sessions = this.allSessions()

    const all = []
    for (const s of sessions) all.push(s.close({ error: err, force: false })) // force false or else infinite recursion
    await Promise.allSettled(all)
  }

  async destroy() {
    if (this.destroyed === true) return
    this.destroyed = true

    if (this.hasSession() === true) throw new Error('Cannot destroy while sessions are open')

    const weakSessions = this.allSessions()

    if (this.replicator) this.replicator.destroy()
    if (this.state) await this.state.close()

    // close all pending weak sessions...
    for (const s of weakSessions) s.close().catch(noop)
  }

  async _close() {
    if (this.opened === false) await this.opening
    if (this.hasSession() === true) throw new Error('Cannot close while sessions are open')

    if (this.replicator) await this.replicator.close()

    await this.destroy()
    if (this.autoClose) await this.storage.store.close()

    this.closed = true
  }
}

function updateContigBatch(start, upd, bitfield) {
  const end = upd.start + upd.length

  let c = start

  if (upd.drop) {
    // If we dropped a block in the current contig range, "downgrade" it
    if (c > upd.start) {
      c = upd.start
    }
  } else {
    if (c <= end && c >= upd.start) {
      c = end
      while (bitfield.get(c)) c++
    }
  }

  if (c === start) {
    return {
      length: -1
    }
  }

  if (c > start) {
    return {
      length: c
    }
  }

  return {
    length: c
  }
}

function getDefaultTree() {
  return {
    fork: 0,
    length: 0,
    rootHash: null,
    signature: null
  }
}

function parseHeader(info) {
  if (!info) return null

  return {
    key: info.key,
    manifest: info.manifest,
    external: null,
    keyPair: info.keyPair,
    tree: info.head || getDefaultTree(),
    hints: {
      reorgs: [],
      contiguousLength: info.hints ? info.hints.contiguousLength : 0,
      remoteContiguousLength: info.hints ? info.hints.remoteContiguousLength : 0,
      recovering: info.hints ? info.hints.recovering : 0
    }
  }
}

async function maybeGetRootsFromStorage(storage, length) {
  try {
    return length ? await MerkleTree.getRootsFromStorage(storage, length) : []
  } catch (err) {
    if (err.code !== 'INVALID_OPERATION') throw err
    // If INVALID_OPERATION, a root is likely missing so load empty roots to try to recover
    return []
  }
}

function noop() {}

async function getCoreInfo(storage) {
  const r = storage.read()

  const auth = r.getAuth()
  const head = r.getHead()
  const hints = r.getHints()

  r.tryFlush()

  const [authInfo, headInfo, hintsInfo] = await Promise.all([auth, head, hints])
  return {
    ...authInfo,
    head: headInfo,
    hints: hintsInfo
  }
}
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const b4a = require('b4a')
const { DEFAULT_ENCRYPTION } = require('./caps')

const nonce = b4a.alloc(sodium.crypto_stream_NONCEBYTES)

module.exports = class DefaultEncryption {
  static PADDING = 8

  constructor(encryptionKey, hypercoreKey, opts = {}) {
    this.key = encryptionKey
    this.compat = opts.compat === true

    const keys = DefaultEncryption.deriveKeys(encryptionKey, hypercoreKey, opts)

    this.blockKey = keys.block
    this.blindingKey = keys.blinding
  }

  static deriveKeys(encryptionKey, hypercoreKey, { block = false, compat = false } = {}) {
    const subKeys = b4a.alloc(2 * sodium.crypto_stream_KEYBYTES)

    const blockKey = block ? encryptionKey : subKeys.subarray(0, sodium.crypto_stream_KEYBYTES)
    const blindingKey = subKeys.subarray(sodium.crypto_stream_KEYBYTES)

    if (!block) {
      if (compat) {
        sodium.crypto_generichash_batch(blockKey, [encryptionKey], hypercoreKey)
      } else {
        sodium.crypto_generichash_batch(blockKey, [DEFAULT_ENCRYPTION, hypercoreKey, encryptionKey])
      }
    }

    sodium.crypto_generichash(blindingKey, blockKey)

    return {
      blinding: blindingKey,
      block: blockKey
    }
  }

  static blockEncryptionKey(hypercoreKey, encryptionKey) {
    const blockKey = b4a.alloc(sodium.crypto_stream_KEYBYTES)
    sodium.crypto_generichash_batch(blockKey, [DEFAULT_ENCRYPTION, hypercoreKey, encryptionKey])
    return blockKey
  }

  static encrypt(index, block, fork, blockKey, blindingKey) {
    const padding = block.subarray(0, DefaultEncryption.PADDING)
    block = block.subarray(DefaultEncryption.PADDING)

    c.uint64.encode({ start: 0, end: 8, buffer: padding }, fork)
    c.uint64.encode({ start: 0, end: 8, buffer: nonce }, index)

    // Zero out any previous padding.
    nonce.fill(0, 8, 8 + padding.byteLength)

    // Blind the fork ID, possibly risking reusing the nonce on a reorg of the
    // Hypercore. This is fine as the blinding is best-effort and the latest
    // fork ID shared on replication anyway.
    sodium.crypto_stream_xor(padding, padding, nonce, blindingKey)

    nonce.set(padding, 8)

    // The combination of a (blinded) fork ID and a block index is unique for a
    // given Hypercore and is therefore a valid nonce for encrypting the block.
    sodium.crypto_stream_xor(block, block, nonce, blockKey)
  }

  static decrypt(index, block, blockKey) {
    const padding = block.subarray(0, DefaultEncryption.PADDING)
    block = block.subarray(DefaultEncryption.PADDING)

    c.uint64.encode({ start: 0, end: 8, buffer: nonce }, index)

    nonce.set(padding, 8)

    // Decrypt the block using the blinded fork ID.
    sodium.crypto_stream_xor(block, block, nonce, blockKey)
  }

  encrypt(index, block, fork, core) {
    if (core.compat !== this.compat) this._reload(core)
    return DefaultEncryption.encrypt(index, block, fork, this.blockKey, this.blindingKey)
  }

  decrypt(index, block, core) {
    if (core.compat !== this.compat) this._reload(core)
    return DefaultEncryption.decrypt(index, block, this.blockKey)
  }

  padding() {
    return DefaultEncryption.PADDING
  }

  _reload(core) {
    const block = b4a.equals(this.key, this.blockKey)
    const keys = DefaultEncryption.deriveKeys(this.key, core.key, { block, compat: core.compat })

    this.blockKey = keys.blockKey
    this.blindingKey = keys.blindingKey
  }
}
module.exports = class Download {
  constructor(session, range) {
    this.session = session
    this.range = range
    this.request = null
    this.opened = false
    this.opening = this._open()
    this.opening.catch(noop)
  }

  ready() {
    return this.opening
  }

  async _open() {
    if (this.session.opened === false) await this.session.opening
    this._download()
    this.opened = true
  }

  async done() {
    await this.ready()

    try {
      return await this.request.promise
    } catch (err) {
      if (isSessionMoved(err)) return this._download()
      throw err
    }
  }

  _download() {
    const activeRequests = (this.range && this.range.activeRequests) || this.session.activeRequests
    this.request = this.session.core.replicator.addRange(activeRequests, this.range)
    this.request.promise.catch(noop)
    return this.request.promise
  }

  /**
   * Deprecated. Use `range.done()`.
   */
  downloaded() {
    return this.done()
  }

  destroy() {
    this._destroyBackground().catch(noop)
  }

  async _destroyBackground() {
    if (this.opened === false) await this.ready()
    if (this.request.context) this.request.context.detach(this.request)
  }
}

function noop() {}

function isSessionMoved(err) {
  return err.code === 'SESSION_MOVED'
}
module.exports = {
  SMALL_WANTS: 1
}
// this helper is for fully remote proofs, is like in a push notification where no other context exists

const { MerkleTree } = require('./merkle-tree.js')
const messages = require('./messages.js')
const b4a = require('b4a')
const c = require('compact-encoding')
const crypto = require('hypercore-crypto')
const flat = require('flat-tree')

class SlimSession {
  constructor(storage, auth, head, roots) {
    this.fork = head ? head.fork : 0
    this.roots = roots
    this.length = head ? head.length : 0
    this.signature = head ? head.signature : null
    this.ancestors = this.length
    this.byteLength = 0
    this.prologue = auth.manifest.prologue
    this.storage = storage

    for (let i = 0; i < roots.length; i++) this.byteLength += roots[i].size
  }
}

module.exports = { verify, proof }

async function verify(storage, buffer, { referrer = null } = {}) {
  const state = { buffer, start: 0, end: buffer.byteLength }

  const discoveryKey = c.fixed32.decode(state)
  const proof = messages.wire.data.decode(state)

  const result = {
    key: null,
    discoveryKey,
    newer: true,
    length: 0,
    proof,
    block: null
  }

  const core = await storage.resumeCore(discoveryKey)
  if (core === null) return null

  let rx = core.read()
  const authPromise = rx.getAuth()
  const headPromise = rx.getHead()
  const referrerPromise = rx.getUserData('referrer')

  rx.tryFlush()

  const [auth, head, ref] = await Promise.all([authPromise, headPromise, referrerPromise])

  if (auth === null) return null

  if (referrer && (!ref || !b4a.equals(ref, referrer))) return null

  rx = core.read()

  const rootPromises = []

  for (const index of flat.fullRoots(head ? 2 * head.length : 0)) {
    rootPromises.push(rx.getTreeNode(index))
  }

  rx.tryFlush()

  let roots = await Promise.all(rootPromises)
  if (roots.some(isNull)) roots = []

  const length = head ? head.length : 0

  if (!auth.manifest || !auth.manifest.signers.length) return null

  const batch = await MerkleTree.verifyFullyRemote(new SlimSession(core, auth, head, roots), proof)
  const publicKey = auth.manifest.signers[0].publicKey

  let signable = null
  let signature = null

  if (auth.manifest.version === 0) {
    signable = batch.signable(auth.manifest.signers[0].namespace)
    signature = batch.signature
  } else {
    if (batch.signature[0] !== 1) return null
    if (batch.signature[1] !== 0) return null

    signable = batch.signable(auth.key)
    signature = batch.signature.subarray(2, 66)
  }

  if (!crypto.verify(signable, signature, publicKey)) {
    return null
  }

  result.key = auth.key
  result.discoveryKey = discoveryKey
  result.newer = batch.length > length
  result.length = batch.length
  result.block = proof.block

  return result
}

async function proof(sender, { index, block = null, upgrade = null } = {}) {
  const proof = await sender.proof({
    block: block ? { index, nodes: 0 } : null,
    upgrade: upgrade ? upgrade : { start: 0, length: sender.length }
  })

  if (block) proof.block.value = block
  proof.manifest = sender.core.header.manifest

  const state = { buffer: null, start: 0, end: 0 }
  const data = { request: 0, ...proof }

  c.fixed32.preencode(state, sender.discoveryKey)
  messages.wire.data.preencode(state, data)

  state.buffer = b4a.allocUnsafe(state.end)

  c.fixed32.encode(state, sender.discoveryKey)
  messages.wire.data.encode(state, data)

  return state.buffer
}

function isNull(x) {
  return x === null
}
const TICKS = 16

module.exports = class HotswapQueue {
  constructor() {
    this.priorities = [[], [], []]
  }

  *pick(peer) {
    for (let i = 0; i < this.priorities.length; i++) {
      // try first one more than second one etc etc
      let ticks = (this.priorities.length - i) * TICKS
      const queue = this.priorities[i]

      for (let j = 0; j < queue.length; j++) {
        const r = j + Math.floor(Math.random() * queue.length - j)
        const a = queue[j]
        const b = queue[r]

        if (r !== j) {
          queue[(b.hotswap.index = j)] = b
          queue[(a.hotswap.index = r)] = a
        }

        if (hasInflight(b, peer)) continue

        yield b

        if (--ticks <= 0) break
      }
    }
  }

  add(block) {
    if (block.hotswap !== null) this.remove(block)
    if (block.inflight.length === 0 || block.inflight.length >= 3) return

    // TODO: also use other stuff to determine queue prio
    const queue = this.priorities[block.inflight.length - 1]

    const index = queue.push(block) - 1
    block.hotswap = { ref: this, queue, index }
  }

  remove(block) {
    const hotswap = block.hotswap
    if (hotswap === null) return

    block.hotswap = null
    const head = hotswap.queue.pop()
    if (head === block) return
    hotswap.queue[(head.hotswap.index = hotswap.index)] = head
  }
}

function hasInflight(block, peer) {
  for (let j = 0; j < block.inflight.length; j++) {
    if (block.inflight[j].peer === peer) return true
  }
  return false
}
module.exports = class Info {
  constructor(opts = {}) {
    this.key = opts.key
    this.discoveryKey = opts.discoveryKey
    this.length = opts.length || 0
    this.contiguousLength = opts.contiguousLength || 0
    this.byteLength = opts.byteLength || 0
    this.fork = opts.fork || 0
    this.padding = opts.padding || 0
    this.storage = opts.storage || null
  }

  static async from(session, opts = {}) {
    return new Info({
      key: session.key,
      discoveryKey: session.discoveryKey,
      length: session.length,
      contiguousLength: session.contiguousLength,
      byteLength: session.byteLength,
      fork: session.fork,
      padding: session.padding,
      storage: opts.storage ? await this.storage(session) : null
    })
  }

  static async storage(session) {
    const { oplog, tree, blocks, bitfield } = session.core
    try {
      return {
        oplog: await Info.bytesUsed(oplog.storage),
        tree: await Info.bytesUsed(tree.storage),
        blocks: await Info.bytesUsed(blocks.storage),
        bitfield: await Info.bytesUsed(bitfield.storage)
      }
    } catch {
      return null
    }
  }

  static bytesUsed(file) {
    return new Promise((resolve, reject) => {
      file.stat((err, st) => {
        if (err) {
          resolve(0) // prob just file not found (TODO, improve)
        } else if (typeof st.blocks !== 'number') {
          reject(new Error('cannot determine bytes used'))
        } else {
          resolve(st.blocks * 512)
        }
      })
    })
  }
}
const b4a = require('b4a')

module.exports = function (core, depth, opts) {
  let indent = ''
  if (typeof opts.indentationLvl === 'number') {
    while (indent.length < opts.indentationLvl) indent += ' '
  }

  let peers = ''
  const min = Math.min(core.peers.length, 5)

  for (let i = 0; i < min; i++) {
    const peer = core.peers[i]

    peers += `${indent}    Peer(\n`
    peers += `${indent}      remotePublicKey: ${opts.stylize(toHex(peer.remotePublicKey), 'string')}\n`
    peers += `${indent}      remoteLength: ${opts.stylize(peer.remoteLength, 'number')}\n`
    peers += `${indent}      remoteFork: ${opts.stylize(peer.remoteFork, 'number')}\n`
    peers += `${indent}      remoteCanUpgrade: ${opts.stylize(peer.remoteCanUpgrade, 'boolean')}\n`
    peers += `${indent}    )\n`
  }

  if (core.peers.length > 5) {
    peers += `${indent}  ... and ${core.peers.length - 5} more\n`
  }

  if (peers) peers = `[\n${peers}${indent}  ]`
  else peers = `[ ${opts.stylize(0, 'number')} ]`

  return (
    `${core.constructor.name}(\n` +
    `${indent}  id: ${opts.stylize(core.id, 'string')}\n` +
    `${indent}  key: ${opts.stylize(toHex(core.key), 'string')}\n` +
    `${indent}  discoveryKey: ${opts.stylize(toHex(core.discoveryKey), 'string')}\n` +
    `${indent}  opened: ${opts.stylize(core.opened, 'boolean')}\n` +
    `${indent}  closed: ${opts.stylize(core.closed, 'boolean')}\n` +
    `${indent}  snapshotted: ${opts.stylize(core.snapshotted, 'boolean')}\n` +
    `${indent}  writable: ${opts.stylize(core.writable, 'boolean')}\n` +
    `${indent}  length: ${opts.stylize(core.length, 'number')}\n` +
    `${indent}  fork: ${opts.stylize(core.fork, 'number')}\n` +
    `${indent}  sessions: [ ${opts.stylize(core.sessions.length, 'number')} ]\n` +
    `${indent}  activeRequests: [ ${opts.stylize(core.activeRequests.length, 'number')} ]\n` +
    `${indent}  peers: ${peers}\n` +
    `${indent})`
  )
}

function toHex(buf) {
  return buf && b4a.toString(buf, 'hex')
}
const BigSparseArray = require('big-sparse-array')
const { Transform } = require('streamx')
const quickbit = require('./compat').quickbit
const b4a = require('b4a')

const BITS_PER_PAGE = 32768
const BYTES_PER_PAGE = BITS_PER_PAGE / 8

class MarkPage {
  constructor() {
    this.bitfield = null
    this.loaded = new Promise((resolve) => {
      this.load = resolve
    })
  }

  setBitfield(bitfield) {
    this.bitfield = bitfield
    this.load()
  }

  get(index) {
    return quickbit.get(this.bitfield, index)
  }

  set(index, val) {
    quickbit.set(this.bitfield, index, val)
  }
}

module.exports = class MarkBitfield {
  static BITS_PER_PAGE = BITS_PER_PAGE
  static BYTES_PER_PAGE = BYTES_PER_PAGE

  constructor(storage) {
    this.storage = storage
    this._pages = new BigSparseArray()
  }

  async loadPage(pageIndex) {
    const p = this._pages.set(pageIndex, new MarkPage())
    const rx = this.storage.read()
    const pageBuf = rx.getMark(pageIndex)
    rx.tryFlush()
    const bitfield = (await pageBuf) ?? b4a.alloc(BYTES_PER_PAGE)
    await p.setBitfield(bitfield)
    return p
  }

  async get(index) {
    const j = index & (BITS_PER_PAGE - 1)
    const i = (index - j) / BITS_PER_PAGE

    let p = this._pages.get(i)
    if (!p) p = await this.loadPage(i)

    return p.get(j)
  }

  async set(index, val) {
    const j = index & (BITS_PER_PAGE - 1)
    const i = (index - j) / BITS_PER_PAGE

    let p = this._pages.get(i)

    if (!p && val) p = await this.loadPage(i)

    if (p) {
      await p.loaded
      p.set(j, val)
      const tx = this.storage.write()
      tx.putMark(i, p.bitfield)
      await tx.flush()
    }
  }

  async clear() {
    const tx = this.storage.write()
    tx.deleteMarkRange(0, -1)
    await tx.flush()
    this._pages = new BigSparseArray()
  }

  createMarkStream({ reverse = false } = {}) {
    return this.storage.createMarkStream({ reverse }).pipe(
      new Transform({
        transform({ index, page }, cb) {
          let bitIndex = reverse
            ? quickbit.findLast(page, true, BITS_PER_PAGE)
            : quickbit.findFirst(page, true, 0)
          while (bitIndex !== -1) {
            const blockIndex = index * BITS_PER_PAGE + bitIndex
            this.push(blockIndex)

            // Account for `bitIndex` being either causing infinite loop
            if (bitIndex === 0 && reverse) break

            bitIndex = reverse
              ? quickbit.findLast(page, true, bitIndex - 1)
              : quickbit.findFirst(page, true, bitIndex + 1)
          }

          cb(null)
        }
      })
    )
  }
}
const flat = require('flat-tree')
const crypto = require('hypercore-crypto')
const b4a = require('b4a')
const unslab = require('unslab')
const caps = require('./caps')
const {
  INVALID_PROOF,
  INVALID_CHECKSUM,
  INVALID_OPERATION,
  BAD_ARGUMENT,
  ASSERTION
} = require('hypercore-errors')

class NodeQueue {
  constructor(nodes, extra = null) {
    this.i = 0
    this.nodes = nodes
    this.extra = extra
    this.length = nodes.length + (this.extra === null ? 0 : 1)
  }

  shift(index) {
    if (this.extra !== null && this.extra.index === index) {
      const node = this.extra
      this.extra = null
      this.length--
      return node
    }

    if (this.i >= this.nodes.length) {
      throw INVALID_OPERATION('Expected node ' + index + ', got (nil)')
    }

    const node = this.nodes[this.i++]
    if (node.index !== index) {
      throw INVALID_OPERATION('Expected node ' + index + ', got node ' + node.index)
    }

    this.length--
    return node
  }
}

class MerkleTreeBatch {
  constructor(session) {
    this.fork = session.fork
    this.roots = [...session.roots]
    this.length = session.length
    this.signature = session.signature
    this.ancestors = session.length
    this.byteLength = session.byteLength
    this.prologue = session.prologue
    this.hashCached = null

    this.committed = false
    this.truncated = false
    this.treeLength = session.length
    this.treeFork = session.fork
    this.storage = session.storage
    this.session = session
    this.nodes = []
    this.upgraded = false
  }

  checkout(length, additionalRoots) {
    const roots = []
    let r = 0

    const head = 2 * length - 2
    const gaps = new Set()
    const all = new Map()

    // additional roots is so the original roots can be passed (we mutate the array in appendRoot)
    if (additionalRoots) {
      for (const node of additionalRoots) all.set(node.index, node)
    }

    for (const node of this.nodes) all.set(node.index, node)

    for (const index of flat.fullRoots(head + 2)) {
      const left = flat.leftSpan(index)
      if (left !== 0) gaps.add(left - 1)

      if (r < this.roots.length && this.roots[r].index === index) {
        roots.push(this.roots[r++])
        continue
      }
      const node = all.get(index)
      if (!node) throw new BAD_ARGUMENT('root missing for given length')
      roots.push(node)
    }

    this.roots = roots
    this.length = length
    this.byteLength = totalSize(roots)
    this.hashCached = null
    this.signature = null

    for (let i = 0; i < this.nodes.length; i++) {
      const index = this.nodes[i].index
      if (index <= head && !gaps.has(index)) continue
      const last = this.nodes.pop()
      if (i < this.nodes.length) this.nodes[i--] = last
    }
  }

  prune(length) {
    if (length === 0) return

    const head = 2 * length - 2
    const gaps = new Set()

    // TODO: make a function for this in flat-tree
    for (const index of flat.fullRoots(head + 2)) {
      const left = flat.leftSpan(index)
      if (left !== 0) gaps.add(left - 1)
    }

    for (let i = 0; i < this.nodes.length; i++) {
      const index = this.nodes[i].index
      if (index > head || gaps.has(index)) continue
      const last = this.nodes.pop()
      if (i < this.nodes.length) this.nodes[i--] = last
    }
  }

  clone() {
    const b = new MerkleTreeBatch(this.session)

    b.fork = this.fork
    b.roots = [...this.roots]
    b.length = this.length
    b.byteLength = this.byteLength
    b.signature = this.signature
    b.treeLength = this.treeLength
    b.treeFork = this.treeFork
    b.tree = this.tree
    b.nodes = [...this.nodes]
    b.upgraded = this.upgraded

    return b
  }

  hash() {
    if (this.hashCached === null) this.hashCached = unslab(crypto.tree(this.roots))
    return this.hashCached
  }

  signable(manifestHash) {
    return caps.treeSignable(manifestHash, this.hash(), this.length, this.fork)
  }

  signableCompat(noHeader) {
    return caps.treeSignableCompat(this.hash(), this.length, this.fork, noHeader)
  }

  get(index) {
    if (index >= this.length * 2) {
      return null
    }

    for (const n of this.nodes) {
      if (n.index === index) return n
    }

    return getTreeNodeFromStorage(this.session.storage, index)
  }

  // deprecated, use sssion proof instead
  proof(batch, { block, hash, seek, upgrade }) {
    return generateProof(this.session, batch, block, hash, seek, upgrade)
  }

  verifyUpgrade(proof) {
    const unverified = verifyTree(proof, this.nodes)

    if (!proof.upgrade) throw INVALID_OPERATION('Expected upgrade proof')

    return verifyUpgrade(proof, unverified, this)
  }

  addNodesUnsafe(nodes) {
    for (let i = 0; i < nodes.length; i++) {
      this.nodes.push(nodes[i])
    }
  }

  append(buf) {
    const head = this.length * 2
    const ite = flat.iterator(head)
    const node = blockNode(head, buf)

    this.appendRoot(node, ite)
  }

  appendRoot(node, ite) {
    node = unslabNode(node)
    this.hashCached = null
    this.upgraded = true
    this.length += ite.factor / 2
    this.byteLength += node.size
    this.roots.push(node)
    this.nodes.push(node)

    while (this.roots.length > 1) {
      const a = this.roots[this.roots.length - 1]
      const b = this.roots[this.roots.length - 2]

      // TODO: just have a peek sibling instead? (pretty sure it's always the left sib as well)
      if (ite.sibling() !== b.index) {
        ite.sibling() // unset so it always points to last root
        break
      }

      const node = unslabNode(parentNode(ite.parent(), a, b))
      this.nodes.push(node)
      this.roots.pop()
      this.roots.pop()
      this.roots.push(node)
    }
  }

  commitable() {
    return (
      this.treeFork === this.session.fork &&
      (this.upgraded
        ? this.treeLength === this.session.length
        : this.treeLength <= this.session.length)
    )
  }

  commit(tx) {
    if (tx === undefined) throw INVALID_OPERATION('No database batch was passed')

    if (this.session.core._repairMode) {
      throw ASSERTION('Cannot commit while repair mode is on')
    }

    if (!this.commitable()) {
      throw INVALID_OPERATION('Tree was modified during batch, refusing to commit')
    }

    if (this.upgraded) this._commitUpgrade(tx)

    for (let i = 0; i < this.nodes.length; i++) {
      const node = this.nodes[i]
      tx.putTreeNode(node)
    }

    this.committed = true

    return this
  }

  _commitUpgrade(tx) {
    // TODO: If easy to detect, we should refuse an trunc+append here without a fork id
    // change. Will only happen on user error so mostly to prevent that.

    if (this.ancestors < this.treeLength) {
      tx.deleteTreeNodeRange(this.ancestors * 2, this.treeLength * 2)

      if (this.ancestors > 0) {
        const head = this.ancestors * 2
        const ite = flat.iterator(head - 2)

        while (true) {
          if (ite.contains(head) && ite.index < head) {
            tx.deleteTreeNode(ite.index)
          }
          if (ite.offset === 0) break
          ite.parent()
        }

        this.truncated = true
      }
    }
  }

  seek(bytes, padding) {
    return new ByteSeeker(this, this, bytes, padding)
  }

  byteRange(index) {
    const rx = this.storage.read()
    const range = getByteRange(this, index, rx)
    rx.tryFlush()

    return range
  }

  byteOffset(index) {
    if (index === 2 * this.length) return this.byteLength

    const rx = this.storage.read()
    const offset = getByteOffset(this, index, rx)
    rx.tryFlush()

    return offset
  }

  async downgrade() {
    if (!this.upgraded) return true

    const rx = this.storage.read()
    const nodePromises = []

    for (const r of this.roots) {
      nodePromises.push(rx.getTreeNode(r.index))
    }

    rx.tryFlush()

    const nodes = await Promise.all(nodePromises)

    for (let i = 0; i < this.roots.length; i++) {
      const root = this.roots[i]
      const node = nodes[i]

      if (!node) return false
      if (!b4a.equals(node.hash, root.hash)) return false
    }

    this.upgraded = false
    return true
  }

  async restore(length) {
    if (length === this.length) return this

    const roots = unslabNodes(await MerkleTree.getRootsFromStorage(this.storage, length))

    this.roots = roots
    this.length = length
    this.byteLength = totalSize(roots)
    this.ancestors = length

    for (const node of roots) this.byteLength += node.size

    return this
  }
}

class ReorgBatch extends MerkleTreeBatch {
  constructor(session) {
    super(session)

    this.roots = []
    this.length = 0
    this.byteLength = 0
    this.diff = null
    this.ancestors = 0
    // We set upgraded because reorgs are signed so hit will
    // hit the same code paths (like the treeLength check in commit)
    this.upgraded = true
    this.want = {
      nodes: 0,
      start: 0,
      end: 0
    }
  }

  get finished() {
    return this.want === null
  }

  update(proof) {
    if (this.want === null) return true

    const nodes = []
    const root = verifyTree(proof, nodes)

    if (root === null || !b4a.equals(root.hash, this.diff.hash)) return false

    this.nodes.push(...nodes)
    return this._update(nodes)
  }

  async _update(nodes) {
    const n = new Map()
    for (const node of nodes) n.set(node.index, node)

    let diff = null
    const ite = flat.iterator(this.diff.index)
    const startingDiff = this.diff

    while ((ite.index & 1) !== 0) {
      const left = n.get(ite.leftChild())
      if (!left) break

      const existing = await getTreeNodeFromStorage(this.session.storage, left.index)
      if (!existing || !b4a.equals(existing.hash, left.hash)) {
        diff = left
      } else {
        diff = n.get(ite.sibling())
      }
    }

    if ((this.diff.index & 1) === 0) return true
    if (diff === null) return false
    if (startingDiff !== this.diff) return false

    return this._updateDiffRoot(diff)
  }

  _updateDiffRoot(diff) {
    if (this.want === null) return true

    const spans = flat.spans(diff.index)
    const start = spans[0] / 2
    const end = Math.min(this.treeLength, spans[1] / 2 + 1)
    const len = end - start

    this.ancestors = start
    this.diff = diff

    if ((diff.index & 1) === 0 || this.want.start >= this.treeLength || len <= 0) {
      this.want = null
      return true
    }

    this.want.start = start
    this.want.end = end
    this.want.nodes = log2(spans[1] - spans[0] + 2) - 1

    return false
  }
}

class ByteSeeker {
  constructor(session, bytes, padding = 0) {
    this.session = session
    this.bytes = bytes
    this.padding = padding

    const size = session.byteLength - session.length * padding

    this.start = bytes >= size ? session.length : 0
    this.end = bytes < size ? session.length : 0
  }

  async _seek(bytes) {
    if (!bytes) return [0, 0]

    for (const node of this.session.roots) {
      // all async ticks happen once we find the root so safe
      const size = getUnpaddedSize(node, this.padding, null)

      if (bytes === size) return [flat.rightSpan(node.index) + 2, 0]
      if (bytes > size) {
        bytes -= size
        continue
      }

      const ite = flat.iterator(node.index)

      while ((ite.index & 1) !== 0) {
        const l = await getTreeNodeFromStorage(this.session.storage, ite.leftChild())

        if (l) {
          const size = getUnpaddedSize(l, this.padding, ite)

          if (size === bytes) return [ite.rightSpan() + 2, 0]
          if (size > bytes) continue
          bytes -= size
          ite.sibling()
        } else {
          ite.parent()
          return [ite.index, bytes]
        }
      }

      return [ite.index, bytes]
    }

    return null
  }

  async update() {
    // TODO: combine _seek and this, much simpler
    const res = await this._seek(this.bytes)
    if (!res) return null
    if ((res[0] & 1) === 0) return [res[0] / 2, res[1]]

    const span = flat.spans(res[0])
    this.start = span[0] / 2
    this.end = span[1] / 2 + 1

    return null
  }
}

class TreeProof {
  constructor(session, block, hash, seek, upgrade) {
    this.fork = session.fork
    this.signature = session.signature

    this.block = block
    this.hash = hash
    this.seek = seek
    this.upgrade = upgrade

    this.pending = {
      node: null,
      seek: null,
      upgrade: null,
      additionalUpgrade: null
    }
  }

  async settle() {
    const result = {
      fork: this.fork,
      block: null,
      hash: null,
      seek: null,
      upgrade: null,
      manifest: null
    }

    const [pNode, pSeek, pUpgrade, pAdditional] = await settleProof(this.pending)

    if (this.block) {
      if (pNode === null) throw INVALID_OPERATION('Invalid block request')
      result.block = {
        index: this.block.index,
        value: null, // populated upstream, alloc it here for simplicity
        nodes: pNode
      }
    } else if (this.hash) {
      if (pNode === null) throw INVALID_OPERATION('Invalid block request')
      result.hash = {
        index: this.hash.index,
        nodes: pNode
      }
    }

    if (this.seek && pSeek !== null) {
      result.seek = {
        bytes: this.seek.bytes,
        nodes: pSeek
      }
    }

    if (this.upgrade) {
      result.upgrade = {
        start: this.upgrade.start,
        length: this.upgrade.length,
        nodes: pUpgrade,
        additionalNodes: pAdditional || [],
        signature: this.signature
      }
    }

    return result
  }
}

class MerkleTree {
  static hash(s) {
    return unslab(crypto.tree(s.roots))
  }

  static signable(s, namespace) {
    return caps.treeSignable(namespace, MerkleTree.hash(s), s.length, s.fork)
  }

  static size(roots) {
    return totalSize(roots)
  }

  static span(roots) {
    return totalSpan(roots)
  }

  static getRoots(session, length) {
    return MerkleTree.getRootsFromStorage(session.storage, length)
  }

  static getRootsFromStorage(storage, length) {
    const indexes = flat.fullRoots(2 * length)
    const roots = new Array(indexes.length)
    const rx = storage.read()

    for (let i = 0; i < indexes.length; i++) {
      roots[i] = getTreeNodeOrError(rx, indexes[i])
    }

    rx.tryFlush()

    return Promise.all(roots)
  }

  static async upgradeable(session, length) {
    const indexes = flat.fullRoots(2 * length)
    const roots = new Array(indexes.length)
    const rx = session.storage.read()

    for (let i = 0; i < indexes.length; i++) {
      roots[i] = rx.getTreeNode(indexes[i])
    }

    rx.tryFlush()

    for (const node of await Promise.all(roots)) {
      if (node === null) return false
    }

    return true
  }

  static seek(session, bytes, padding) {
    return new ByteSeeker(session, bytes, padding)
  }

  static get(session, index) {
    return getTreeNodeFromStorage(session.storage, index)
  }

  static async truncate(session, length, batch, fork = batch.fork) {
    const head = length * 2
    const fullRoots = flat.fullRoots(head)

    for (let i = 0; i < fullRoots.length; i++) {
      const root = fullRoots[i]
      if (i < batch.roots.length && batch.roots[i].index === root) continue

      while (batch.roots.length > i) batch.roots.pop()
      batch.roots.push(unslabNode(await getTreeNodeFromStorageOrError(session.storage, root)))
    }

    while (batch.roots.length > fullRoots.length) {
      batch.roots.pop()
    }

    batch.fork = fork
    batch.length = length
    batch.ancestors = length
    batch.byteLength = totalSize(batch.roots)
    batch.upgraded = true

    return batch
  }

  static async reorg(session, proof, batch) {
    let unverified = null

    if (proof.block || proof.hash || proof.seek) {
      unverified = verifyTree(proof, batch.nodes)
    }

    if (!verifyUpgrade(proof, unverified, batch)) {
      throw INVALID_PROOF('Fork proof not verifiable')
    }

    for (const root of batch.roots) {
      const existing = await getTreeNodeFromStorage(session.storage, root.index)
      if (existing && b4a.equals(existing.hash, root.hash)) continue
      batch._updateDiffRoot(root)
      break
    }

    if (batch.diff !== null) {
      await batch._update(batch.nodes)
    } else {
      batch.want = null
      batch.ancestors = batch.length
    }

    return batch
  }

  static verifyFullyRemote(session, proof) {
    // TODO: impl this less hackishly
    const batch = new MerkleTreeBatch(session)

    batch.fork = proof.fork
    batch.roots = []
    batch.length = 0
    batch.ancestors = 0
    batch.byteLength = 0

    let unverified = verifyTree(proof, batch.nodes)

    if (proof.upgrade) {
      if (verifyUpgrade(proof, unverified, batch)) {
        unverified = null
      }
    }

    return batch
  }

  static async verify(session, proof) {
    const batch = new MerkleTreeBatch(session)

    let unverified = verifyTree(proof, batch.nodes)

    if (proof.upgrade) {
      if (verifyUpgrade(proof, unverified, batch)) {
        unverified = null
      }
    }

    if (unverified) {
      const verified = await getTreeNodeFromStorageOrError(session.storage, unverified.index)
      if (!b4a.equals(verified.hash, unverified.hash)) {
        throw INVALID_CHECKSUM('Invalid checksum at node ' + unverified.index)
      }
    }

    return batch
  }

  static proof(session, rx, { block, hash, seek, upgrade }) {
    return generateProof(session, rx, block, hash, seek, upgrade)
  }

  static maxMissingNodes(index, length) {
    const head = 2 * length
    const ite = flat.iterator(index)

    // See iterator.rightSpan()
    const iteRightSpan = ite.index + ite.factor / 2 - 1
    // If the index is not in the current tree, we do not know how many missing nodes there are...
    if (iteRightSpan >= head) return 0

    for (const r of flat.fullRoots(head)) {
      if (r === index) return 0
    }

    // need missing nodes not inclusive of index
    ite.parent()

    let cnt = 0
    while (!ite.contains(head)) {
      cnt++
      ite.parent()
    }

    return cnt
  }

  static async missingNodes(session, index, length) {
    const head = 2 * length
    const ite = flat.iterator(index)

    // See iterator.rightSpan()
    const iteRightSpan = ite.index + ite.factor / 2 - 1
    // If the index is not in the current tree, we do not know how many missing nodes there are...
    if (iteRightSpan >= head) return 0

    let cnt = 0
    // TODO: we could prop use a read batch here and do this in blocks of X for perf
    while (!ite.contains(head) && !(await hasTreeNode(session.storage, ite.index))) {
      cnt++
      if (cnt >= 1024) {
        throw ASSERTION('Bad arguments to missingNodes index=' + index + ' at length=' + length)
      }
      ite.parent()
    }

    return cnt
  }

  static byteOffset(session, index) {
    return getByteOffsetSession(session, index, null)
  }

  static byteRange(session, index) {
    const rx = session.storage.read()
    const offset = getByteOffsetSession(session, index, rx)
    const size = getNodeSize(index, rx)
    rx.tryFlush()
    return Promise.all([offset, size])
  }

  static upgradeLength(proof) {
    const extra = proof.additionalNodes

    if (extra.length) {
      const last = extra[extra.length - 1]
      const index = flat.rightSpan(last.index)
      return index / 2 + 1
    }

    return proof.start + proof.length
  }
}

module.exports = {
  MerkleTreeBatch,
  ReorgBatch,
  MerkleTree
}

async function getNodeSize(index, rx) {
  return (await getTreeNodeOrError(rx, index)).size
}

async function getByteOffsetSession(session, index, rx) {
  if (index === 2 * session.length) return session.byteLength

  const treeNodes =
    rx === null
      ? await getByteOffsetBatchFlush(session.roots, index, session.storage.read())
      : await getByteOffsetBatch(session.roots, index, rx)

  let offset = 0
  for (const node of treeNodes) offset += node.size

  return offset
}

async function getByteOffset(tree, index, rx) {
  if (index === 2 * tree.length) return tree.byteLength

  const treeNodes = await getByteOffsetBatch(tree.roots, index, rx)

  let offset = 0
  for (const node of treeNodes) offset += node.size

  return offset
}

function getByteOffsetBatchFlush(roots, index, rx) {
  const treeNodes = getByteOffsetBatch(roots, index, rx)
  rx.tryFlush()
  return treeNodes
}

function getByteOffsetBatch(roots, index, rx) {
  if ((index & 1) === 1) index = flat.leftSpan(index)

  let head = 0
  let cnt = 0

  const promises = []

  for (const node of roots) {
    // all async ticks happen once we find the root so safe
    head += 2 * (node.index - head + 1)

    if (index >= head) {
      promises.push(node.size)
      continue
    }

    const ite = flat.iterator(node.index)

    while (ite.index !== index) {
      if (++cnt >= 1024) throw ASSERTION('Bad getByteOffsetSession index=' + index)

      if (index < ite.index) {
        ite.leftChild()
      } else {
        promises.push(getTreeNodeOrError(rx, ite.leftChild()))
        ite.sibling()
      }
    }

    return Promise.all(promises)
  }

  throw ASSERTION('Failed to find offset')
}

function getByteRange(tree, index, rx) {
  const head = 2 * tree.length
  if (((index & 1) === 0 ? index : flat.rightSpan(index)) >= head) {
    throw BAD_ARGUMENT('Index is out of bounds')
  }

  const offset = getByteOffset(tree, index, rx)
  const size = getNodeSize(index, rx)

  return Promise.all([offset, size])
}

// All the methods needed for proof verification

function verifyTree({ block, hash, seek }, nodes) {
  const untrustedNode = block
    ? { index: 2 * block.index, value: block.value, nodes: block.nodes }
    : hash
      ? { index: hash.index, value: null, nodes: hash.nodes }
      : null

  if (untrustedNode === null && (!seek || !seek.nodes.length)) return null

  let root = null

  if (seek && seek.nodes.length) {
    const ite = flat.iterator(seek.nodes[0].index)
    const q = new NodeQueue(seek.nodes)

    root = q.shift(ite.index)
    nodes.push(root)

    while (q.length > 0) {
      const node = q.shift(ite.sibling())

      root = parentNode(ite.parent(), root, node)
      nodes.push(node)
      nodes.push(root)
    }
  }

  if (untrustedNode === null) return root

  const ite = flat.iterator(untrustedNode.index)
  const blockHash = untrustedNode.value && blockNode(ite.index, untrustedNode.value)

  const q = new NodeQueue(untrustedNode.nodes, root)

  root = blockHash || q.shift(ite.index)
  nodes.push(root)

  while (q.length > 0) {
    const node = q.shift(ite.sibling())

    root = parentNode(ite.parent(), root, node)
    nodes.push(node)
    nodes.push(root)
  }

  return root
}

function verifyUpgrade({ fork, upgrade }, blockRoot, batch) {
  const prologue = batch.prologue

  if (prologue) {
    const { start, length } = upgrade
    if (start < prologue.length && (start !== 0 || length < prologue.length)) {
      throw INVALID_PROOF('Upgrade does not satisfy prologue')
    }
  }

  const q = new NodeQueue(upgrade.nodes, blockRoot)

  let grow = batch.roots.length > 0
  let i = 0

  const to = 2 * (upgrade.start + upgrade.length)
  const ite = flat.iterator(0)

  for (; ite.fullRoot(to); ite.nextTree()) {
    if (i < batch.roots.length && batch.roots[i].index === ite.index) {
      i++
      continue
    }

    if (grow) {
      grow = false
      const root = ite.index
      if (i < batch.roots.length) {
        ite.seek(batch.roots[batch.roots.length - 1].index)
        while (ite.index !== root) {
          batch.appendRoot(q.shift(ite.sibling()), ite)
        }
        continue
      }
    }

    batch.appendRoot(q.shift(ite.index), ite)
  }

  if (prologue && batch.length === prologue.length) {
    if (!b4a.equals(prologue.hash, batch.hash())) {
      throw INVALID_PROOF('Invalid hash')
    }
  }

  const extra = upgrade.additionalNodes

  ite.seek(batch.roots[batch.roots.length - 1].index)
  i = 0

  while (i < extra.length && extra[i].index === ite.sibling()) {
    batch.appendRoot(extra[i++], ite)
  }

  while (i < extra.length) {
    const node = extra[i++]

    while (node.index !== ite.index) {
      if (ite.factor === 2) throw INVALID_OPERATION('Unexpected node: ' + node.index)
      ite.leftChild()
    }

    batch.appendRoot(node, ite)
    ite.sibling()
  }

  batch.signature = unslab(upgrade.signature)
  batch.fork = fork

  return q.extra === null
}

async function seekFromHead(session, head, bytes, padding) {
  const roots = flat.fullRoots(head)

  for (let i = 0; i < roots.length; i++) {
    const root = roots[i]
    const node = await getTreeNodeFromStorage(session.storage, root)
    const size = getUnpaddedSize(node, padding, null)

    if (bytes === size) return root
    if (bytes > size) {
      bytes -= size
      continue
    }

    return seekTrustedTree(session, root, bytes, padding)
  }

  return head
}

// trust that bytes are within the root tree and find the block at bytes

async function seekTrustedTree(session, root, bytes, padding) {
  if (!bytes) return root

  const ite = flat.iterator(root)
  let cnt = 0

  while ((ite.index & 1) !== 0) {
    if (++cnt >= 1024) throw ASSERTION('Bad seekTrusted bytes=' + bytes + ', paddding=' + padding)
    const l = await getTreeNodeFromStorage(session.storage, ite.leftChild())

    if (l) {
      const size = getUnpaddedSize(l, padding, ite)
      if (size === bytes) return ite.index
      if (size > bytes) continue
      bytes -= size
      ite.sibling()
    } else {
      ite.parent()
      return ite.index
    }
  }

  return ite.index
}

// try to find the block at bytes without trusting that is *is* within the root passed

async function seekUntrustedTree(session, root, bytes, padding) {
  const offset =
    (await getByteOffsetSession(session, root, null)) -
    (padding ? (padding * flat.leftSpan(root)) / 2 : 0)

  if (offset > bytes) throw INVALID_OPERATION('Invalid seek')
  if (offset === bytes) return root

  bytes -= offset

  const node = await getTreeNodeFromStorageOrError(session.storage, root)

  if (getUnpaddedSize(node, padding, null) <= bytes) throw INVALID_OPERATION('Invalid seek')

  return seekTrustedTree(session, root, bytes, padding)
}

// Below is proof production, ie, construct proofs to verify a request
// Note, that all these methods are sync as we can statically infer which nodes
// are needed for the remote to verify given they arguments they passed us

function seekProof(session, rx, seekRoot, root, p) {
  const ite = flat.iterator(seekRoot)
  let cnt = 0

  p.seek = []
  p.seek.push(getTreeNodeOrError(rx, ite.index))

  while (ite.index !== root) {
    if (++cnt >= 1024) throw ASSERTION('Bad seekProof seekRoot=' + seekRoot + ', root=' + root)
    ite.sibling()
    p.seek.push(getTreeNodeOrError(rx, ite.index))
    ite.parent()
  }
}

function blockAndSeekProof(session, rx, node, seek, seekRoot, root, p) {
  if (!node) return seekProof(session, rx, seekRoot, root, p)

  const ite = flat.iterator(node.index)
  let cnt = 0

  p.node = []
  if (!node.value) p.node.push(getTreeNodeOrError(rx, ite.index))

  while (ite.index !== root) {
    if (++cnt >= 1024) {
      throw ASSERTION('Bad blockAndSeekProof seekRoot=' + seekRoot + ', root=' + root)
    }
    ite.sibling()

    if (seek && ite.contains(seekRoot) && ite.index !== seekRoot) {
      seekProof(session, rx, seekRoot, ite.index, p)
    } else {
      p.node.push(getTreeNodeOrError(rx, ite.index))
    }

    ite.parent()
  }
}

function upgradeProof(session, rx, node, seek, from, to, subTree, p) {
  if (from === 0) p.upgrade = []

  for (const ite = flat.iterator(0); ite.fullRoot(to); ite.nextTree()) {
    // check if they already have the node
    if (ite.index + ite.factor / 2 < from) continue

    // connect existing tree
    if (p.upgrade === null && ite.contains(from - 2)) {
      p.upgrade = []

      const root = ite.index
      const target = from - 2
      let cnt = 0

      ite.seek(target)

      while (ite.index !== root) {
        if (++cnt >= 1024) throw ASSERTION('Bad upgradeProof target=' + target + ', root=' + root)

        ite.sibling()
        if (ite.index > target) {
          if (p.node === null && p.seek === null && ite.contains(subTree)) {
            blockAndSeekProof(session, rx, node, seek, subTree, ite.index, p)
          } else {
            p.upgrade.push(getTreeNodeOrError(rx, ite.index))
          }
        }
        ite.parent()
      }

      continue
    }

    if (p.upgrade === null) {
      p.upgrade = []
    }

    // if the subtree included is a child of this tree, include that one
    // instead of a dup node
    if (p.node === null && p.seek === null && ite.contains(subTree)) {
      blockAndSeekProof(session, rx, node, seek, subTree, ite.index, p)
      continue
    }

    // add root (can be optimised since the root might be in tree.roots)
    p.upgrade.push(getTreeNodeOrError(rx, ite.index))
  }
}

function additionalUpgradeProof(session, rx, from, to, p) {
  if (from === 0) p.additionalUpgrade = []

  for (const ite = flat.iterator(0); ite.fullRoot(to); ite.nextTree()) {
    // check if they already have the node
    if (ite.index + ite.factor / 2 < from) continue

    // connect existing tree
    if (p.additionalUpgrade === null && ite.contains(from - 2)) {
      p.additionalUpgrade = []

      const root = ite.index
      const target = from - 2
      let cnt = 0

      ite.seek(target)

      while (ite.index !== root) {
        if (++cnt >= 1024) {
          throw ASSERTION(
            'Bad arguments to additionalUpgradeProof root=' + root + ' target=' + target
          )
        }
        ite.sibling()
        if (ite.index > target) {
          p.additionalUpgrade.push(getTreeNodeOrError(rx, ite.index))
        }
        ite.parent()
      }

      continue
    }

    if (p.additionalUpgrade === null) {
      p.additionalUpgrade = []
    }

    // add root (can be optimised since the root is in tree.roots)
    p.additionalUpgrade.push(getTreeNodeOrError(rx, ite.index))
  }
}

function nodesToRoot(index, nodes, head) {
  const ite = flat.iterator(index)

  for (let i = 0; i < nodes; i++) {
    ite.parent()
    if (ite.contains(head)) throw INVALID_OPERATION('Nodes is out of bounds')
  }

  return ite.index
}

function totalSize(nodes) {
  let s = 0
  for (const node of nodes) s += node.size
  return s
}

function totalSpan(nodes) {
  let s = 0
  for (const node of nodes) s += 2 * (node.index - s + 1)
  return s
}

function blockNode(index, value) {
  return { index, size: value.byteLength, hash: crypto.data(value) }
}

function parentNode(index, a, b) {
  return { index, size: a.size + b.size, hash: crypto.parent(a, b) }
}

function log2(n) {
  let res = 1

  while (n > 2) {
    n /= 2
    res++
  }

  return res
}

function normalizeIndexed(block, hash) {
  if (block) {
    return {
      value: true,
      index: block.index * 2,
      nodes: block.nodes,
      lastIndex: block.index
    }
  }
  if (hash) {
    return {
      value: false,
      index: hash.index,
      nodes: hash.nodes,
      lastIndex: flat.rightSpan(hash.index) / 2
    }
  }
  return null
}

async function getTreeNodeOrError(rx, index) {
  const node = await rx.getTreeNode(index)
  if (node === null) {
    throw INVALID_OPERATION('Expected tree node ' + index + ' from storage, got (nil)')
  }
  return node
}

function getTreeNodeFromStorageOrError(storage, index) {
  const rx = storage.read()
  const p = getTreeNodeOrError(rx, index)
  rx.tryFlush()
  return p
}

function getTreeNodeFromStorage(storage, index) {
  const rx = storage.read()
  const node = rx.getTreeNode(index)
  rx.tryFlush()
  return node
}

function hasTreeNode(storage, index) {
  const rx = storage.read()
  const has = rx.hasTreeNode(index)
  rx.tryFlush()
  return has
}

async function settleProof(p) {
  const result = [
    p.node && Promise.all(p.node),
    p.seek && Promise.all(p.seek),
    p.upgrade && Promise.all(p.upgrade),
    p.additionalUpgrade && Promise.all(p.additionalUpgrade)
  ]

  try {
    return await Promise.all(result)
  } catch (err) {
    if (p.node) await Promise.allSettled(p.node)
    if (p.seek) await Promise.allSettled(p.seek)
    if (p.upgrade) await Promise.allSettled(p.upgrade)
    if (p.additionalUpgrade) await Promise.allSettled(p.additionalUpgrade)
    throw err
  }
}

// tree can be either the merkle tree or a merkle tree batch
async function generateProof(session, rx, block, hash, seek, upgrade) {
  // Important that this does not throw inbetween making the promise arrays
  // and finalise being called, otherwise there will be lingering promises in the background

  if (session.prologue && upgrade) {
    upgrade.start = upgrade.start < session.prologue.length ? 0 : upgrade.start
    upgrade.length =
      upgrade.start < session.prologue.length ? session.prologue.length : upgrade.length
  }

  const head = 2 * session.length
  const from = upgrade ? upgrade.start * 2 : 0
  const to = upgrade ? from + upgrade.length * 2 : head
  const node = normalizeIndexed(block, hash)

  // can't do anything as we have no data...
  if (head === 0) return new TreeProof(session, null, null, null, null)

  if (from >= to || to > head) {
    throw INVALID_OPERATION('Invalid upgrade')
  }
  if (seek && upgrade && node !== null && node.index >= from) {
    throw INVALID_OPERATION('Cannot both do a seek and block/hash request when upgrading')
  }

  let subTree = head

  const p = new TreeProof(session, block, hash, seek, upgrade)

  if (node !== null && (!upgrade || node.lastIndex < upgrade.start)) {
    subTree = nodesToRoot(node.index, node.nodes, to)
    const seekRoot = seek
      ? await seekUntrustedTree(session, subTree, seek.bytes, seek.padding)
      : head
    blockAndSeekProof(session, rx, node, seek, seekRoot, subTree, p.pending)
  } else if ((node || seek) && upgrade) {
    subTree = seek ? await seekFromHead(session, to, seek.bytes, seek.padding) : node.index
  }

  if (upgrade) {
    upgradeProof(session, rx, node, seek, from, to, subTree, p.pending)
    if (head > to) additionalUpgradeProof(session, rx, to, head, p.pending)
  }

  return p
}

function getUnpaddedSize(node, padding, ite) {
  return padding === 0
    ? node.size
    : node.size - padding * (ite ? ite.countLeaves() : flat.countLeaves(node.index))
}

function unslabNodes(nodes) {
  for (const node of nodes) unslabNode(node)
  return nodes
}

function unslabNode(node) {
  if (node === null) return node
  node.hash = unslab(node.hash)
  return node
}
const c = require('compact-encoding')
const b4a = require('b4a')
const { DEFAULT_NAMESPACE } = require('./caps')
const { INVALID_OPLOG_VERSION } = require('hypercore-errors')
const unslab = require('unslab')

const EMPTY = b4a.alloc(0)

const MANIFEST_PATCH = 0b00000001
const MANIFEST_PROLOGUE = 0b00000010
const MANIFEST_LINKED = 0b00000100
const MANIFEST_USER_DATA = 0b00001000

const hashes = {
  preencode(state, m) {
    state.end++ // small uint
  },
  encode(state, m) {
    if (m === 'blake2b') {
      c.uint.encode(state, 0)
      return
    }

    throw new Error('Unknown hash: ' + m)
  },
  decode(state) {
    const n = c.uint.decode(state)
    if (n === 0) return 'blake2b'
    throw new Error('Unknown hash id: ' + n)
  }
}

const signatures = {
  preencode(state, m) {
    state.end++ // small uint
  },
  encode(state, m) {
    if (m === 'ed25519') {
      c.uint.encode(state, 0)
      return
    }

    throw new Error('Unknown signature: ' + m)
  },
  decode(state) {
    const n = c.uint.decode(state)
    if (n === 0) return 'ed25519'
    throw new Error('Unknown signature id: ' + n)
  }
}

const signer = {
  preencode(state, m) {
    signatures.preencode(state, m.signature)
    c.fixed32.preencode(state, m.namespace)
    c.fixed32.preencode(state, m.publicKey)
  },
  encode(state, m) {
    signatures.encode(state, m.signature)
    c.fixed32.encode(state, m.namespace)
    c.fixed32.encode(state, m.publicKey)
  },
  decode(state) {
    return {
      signature: signatures.decode(state),
      namespace: c.fixed32.decode(state),
      publicKey: c.fixed32.decode(state)
    }
  }
}

const signerArray = c.array(signer)

const prologue = {
  preencode(state, p) {
    c.fixed32.preencode(state, p.hash)
    c.uint.preencode(state, p.length)
  },
  encode(state, p) {
    c.fixed32.encode(state, p.hash)
    c.uint.encode(state, p.length)
  },
  decode(state) {
    return {
      hash: c.fixed32.decode(state),
      length: c.uint.decode(state)
    }
  }
}

const manifestv0 = {
  preencode(state, m) {
    hashes.preencode(state, m.hash)
    state.end++ // type

    if (m.prologue && m.signers.length === 0) {
      c.fixed32.preencode(state, m.prologue.hash)
      return
    }

    if (m.quorum === 1 && m.signers.length === 1 && !m.allowPatch) {
      signer.preencode(state, m.signers[0])
    } else {
      state.end++ // flags
      c.uint.preencode(state, m.quorum)
      signerArray.preencode(state, m.signers)
    }
  },
  encode(state, m) {
    hashes.encode(state, m.hash)

    if (m.prologue && m.signers.length === 0) {
      c.uint.encode(state, 0)
      c.fixed32.encode(state, m.prologue.hash)
      return
    }

    if (m.quorum === 1 && m.signers.length === 1 && !m.allowPatch) {
      c.uint.encode(state, 1)
      signer.encode(state, m.signers[0])
    } else {
      c.uint.encode(state, 2)
      c.uint.encode(state, m.allowPatch ? 1 : 0)
      c.uint.encode(state, m.quorum)
      signerArray.encode(state, m.signers)
    }
  },
  decode(state) {
    const hash = hashes.decode(state)
    const type = c.uint.decode(state)

    if (type > 2) throw new Error('Unknown type: ' + type)

    if (type === 0) {
      return {
        version: 0,
        hash,
        allowPatch: false,
        quorum: 0,
        signers: [],
        prologue: {
          hash: c.fixed32.decode(state),
          length: 0
        },
        linked: null,
        userData: null
      }
    }

    if (type === 1) {
      return {
        version: 0,
        hash,
        allowPatch: false,
        quorum: 1,
        signers: [signer.decode(state)],
        prologue: null,
        linked: null,
        userData: null
      }
    }

    const flags = c.uint.decode(state)

    return {
      version: 0,
      hash,
      allowPatch: (flags & 1) !== 0,
      quorum: c.uint.decode(state),
      signers: signerArray.decode(state),
      prologue: null,
      linked: null,
      userData: null
    }
  }
}

const fixed32Array = c.array(c.fixed32)

const manifest = (exports.manifest = {
  preencode(state, m) {
    state.end++ // version

    if (m.version === 0) return manifestv0.preencode(state, m)

    state.end++ // flags
    hashes.preencode(state, m.hash)

    c.uint.preencode(state, m.quorum)
    signerArray.preencode(state, m.signers)

    if (m.prologue) prologue.preencode(state, m.prologue)
    if (m.linked) fixed32Array.preencode(state, m.linked)
    if (m.userData) c.buffer.preencode(state, m.userData)
  },
  encode(state, m) {
    c.uint.encode(state, m.version)

    if (m.version === 0) return manifestv0.encode(state, m)

    let flags = 0
    if (m.allowPatch) flags |= MANIFEST_PATCH
    if (m.prologue) flags |= MANIFEST_PROLOGUE
    if (m.linked) flags |= MANIFEST_LINKED
    if (m.userData) flags |= MANIFEST_USER_DATA

    c.uint.encode(state, flags)
    hashes.encode(state, m.hash)

    c.uint.encode(state, m.quorum)
    signerArray.encode(state, m.signers)

    if (m.prologue) prologue.encode(state, m.prologue)
    if (m.linked) fixed32Array.encode(state, m.linked)
    if (m.userData) c.buffer.encode(state, m.userData)
  },
  decode(state) {
    const version = c.uint.decode(state)

    if (version === 0) return manifestv0.decode(state)
    if (version > 2) throw new Error('Unknown version: ' + version)

    const flags = c.uint.decode(state)
    const hash = hashes.decode(state)
    const quorum = c.uint.decode(state)
    const signers = signerArray.decode(state)

    const hasPatch = (flags & MANIFEST_PATCH) !== 0
    const hasPrologue = (flags & MANIFEST_PROLOGUE) !== 0
    const hasLinked = (flags & MANIFEST_LINKED) !== 0
    const hasUserData = (flags & MANIFEST_USER_DATA) !== 0

    return {
      version,
      hash,
      allowPatch: hasPatch,
      quorum,
      signers,
      prologue: hasPrologue ? prologue.decode(state) : null,
      linked: hasLinked ? fixed32Array.decode(state) : null,
      userData: hasUserData ? c.buffer.decode(state) : null
    }
  }
})

const node = {
  preencode(state, n) {
    c.uint.preencode(state, n.index)
    c.uint.preencode(state, n.size)
    c.fixed32.preencode(state, n.hash)
  },
  encode(state, n) {
    c.uint.encode(state, n.index)
    c.uint.encode(state, n.size)
    c.fixed32.encode(state, n.hash)
  },
  decode(state) {
    return {
      index: c.uint.decode(state),
      size: c.uint.decode(state),
      hash: c.fixed32.decode(state)
    }
  }
}

const nodeArray = c.array(node)

const wire = (exports.wire = {})

wire.handshake = {
  preencode(state, m) {
    c.uint.preencode(state, 1)
    c.fixed32.preencode(state, m.capability)
  },
  encode(state, m) {
    c.uint.encode(state, m.seeks ? 1 : 0)
    c.fixed32.encode(state, m.capability)
  },
  decode(state) {
    const flags = c.uint.decode(state)
    return {
      seeks: (flags & 1) !== 0,
      capability: unslab(c.fixed32.decode(state))
    }
  }
}

const requestBlock = {
  preencode(state, b) {
    c.uint.preencode(state, b.index)
    c.uint.preencode(state, b.nodes)
  },
  encode(state, b) {
    c.uint.encode(state, b.index)
    c.uint.encode(state, b.nodes)
  },
  decode(state) {
    return {
      index: c.uint.decode(state),
      nodes: c.uint.decode(state)
    }
  }
}

const requestSeek = {
  preencode(state, s) {
    c.uint.preencode(state, s.bytes)
    c.uint.preencode(state, s.padding)
  },
  encode(state, s) {
    c.uint.encode(state, s.bytes)
    c.uint.encode(state, s.padding)
  },
  decode(state) {
    return {
      bytes: c.uint.decode(state),
      padding: c.uint.decode(state)
    }
  }
}

const requestUpgrade = {
  preencode(state, u) {
    c.uint.preencode(state, u.start)
    c.uint.preencode(state, u.length)
  },
  encode(state, u) {
    c.uint.encode(state, u.start)
    c.uint.encode(state, u.length)
  },
  decode(state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

wire.request = {
  preencode(state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.id)
    c.uint.preencode(state, m.fork)

    if (m.block) requestBlock.preencode(state, m.block)
    if (m.hash) requestBlock.preencode(state, m.hash)
    if (m.seek) requestSeek.preencode(state, m.seek)
    if (m.upgrade) requestUpgrade.preencode(state, m.upgrade)
    if (m.priority) c.uint.preencode(state, m.priority)
  },
  encode(state, m) {
    const flags =
      (m.block ? 1 : 0) |
      (m.hash ? 2 : 0) |
      (m.seek ? 4 : 0) |
      (m.upgrade ? 8 : 0) |
      (m.manifest ? 16 : 0) |
      (m.priority ? 32 : 0)

    c.uint.encode(state, flags)
    c.uint.encode(state, m.id)
    c.uint.encode(state, m.fork)

    if (m.block) requestBlock.encode(state, m.block)
    if (m.hash) requestBlock.encode(state, m.hash)
    if (m.seek) requestSeek.encode(state, m.seek)
    if (m.upgrade) requestUpgrade.encode(state, m.upgrade)
    if (m.priority) c.uint.encode(state, m.priority)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      id: c.uint.decode(state),
      fork: c.uint.decode(state),
      block: flags & 1 ? requestBlock.decode(state) : null,
      hash: flags & 2 ? requestBlock.decode(state) : null,
      seek: flags & 4 ? requestSeek.decode(state) : null,
      upgrade: flags & 8 ? requestUpgrade.decode(state) : null,
      manifest: (flags & 16) !== 0,
      priority: flags & 32 ? c.uint.decode(state) : 0
    }
  }
}

wire.cancel = {
  preencode(state, m) {
    c.uint.preencode(state, m.request)
  },
  encode(state, m) {
    c.uint.encode(state, m.request)
  },
  decode(state, m) {
    return {
      request: c.uint.decode(state)
    }
  }
}

const dataUpgrade = {
  preencode(state, u) {
    c.uint.preencode(state, u.start)
    c.uint.preencode(state, u.length)
    nodeArray.preencode(state, u.nodes)
    nodeArray.preencode(state, u.additionalNodes)
    c.buffer.preencode(state, u.signature)
  },
  encode(state, u) {
    c.uint.encode(state, u.start)
    c.uint.encode(state, u.length)
    nodeArray.encode(state, u.nodes)
    nodeArray.encode(state, u.additionalNodes)
    c.buffer.encode(state, u.signature)
  },
  decode(state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state),
      nodes: nodeArray.decode(state),
      additionalNodes: nodeArray.decode(state),
      signature: c.buffer.decode(state)
    }
  }
}

const dataSeek = {
  preencode(state, s) {
    c.uint.preencode(state, s.bytes)
    nodeArray.preencode(state, s.nodes)
  },
  encode(state, s) {
    c.uint.encode(state, s.bytes)
    nodeArray.encode(state, s.nodes)
  },
  decode(state) {
    return {
      bytes: c.uint.decode(state),
      nodes: nodeArray.decode(state)
    }
  }
}

const dataBlock = {
  preencode(state, b) {
    c.uint.preencode(state, b.index)
    c.buffer.preencode(state, b.value)
    nodeArray.preencode(state, b.nodes)
  },
  encode(state, b) {
    c.uint.encode(state, b.index)
    c.buffer.encode(state, b.value)
    nodeArray.encode(state, b.nodes)
  },
  decode(state) {
    return {
      index: c.uint.decode(state),
      value: c.buffer.decode(state) || EMPTY,
      nodes: nodeArray.decode(state)
    }
  }
}

const dataHash = {
  preencode(state, b) {
    c.uint.preencode(state, b.index)
    nodeArray.preencode(state, b.nodes)
  },
  encode(state, b) {
    c.uint.encode(state, b.index)
    nodeArray.encode(state, b.nodes)
  },
  decode(state) {
    return {
      index: c.uint.decode(state),
      nodes: nodeArray.decode(state)
    }
  }
}

wire.data = {
  preencode(state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.request)
    c.uint.preencode(state, m.fork)

    if (m.block) dataBlock.preencode(state, m.block)
    if (m.hash) dataHash.preencode(state, m.hash)
    if (m.seek) dataSeek.preencode(state, m.seek)
    if (m.upgrade) dataUpgrade.preencode(state, m.upgrade)
    if (m.manifest) manifest.preencode(state, m.manifest)
  },
  encode(state, m) {
    const flags =
      (m.block ? 1 : 0) |
      (m.hash ? 2 : 0) |
      (m.seek ? 4 : 0) |
      (m.upgrade ? 8 : 0) |
      (m.manifest ? 16 : 0)

    c.uint.encode(state, flags)
    c.uint.encode(state, m.request)
    c.uint.encode(state, m.fork)

    if (m.block) dataBlock.encode(state, m.block)
    if (m.hash) dataHash.encode(state, m.hash)
    if (m.seek) dataSeek.encode(state, m.seek)
    if (m.upgrade) dataUpgrade.encode(state, m.upgrade)
    if (m.manifest) manifest.encode(state, m.manifest)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      request: c.uint.decode(state),
      fork: c.uint.decode(state),
      block: flags & 1 ? dataBlock.decode(state) : null,
      hash: flags & 2 ? dataHash.decode(state) : null,
      seek: flags & 4 ? dataSeek.decode(state) : null,
      upgrade: flags & 8 ? dataUpgrade.decode(state) : null,
      manifest: flags & 16 ? manifest.decode(state) : null
    }
  }
}

wire.noData = {
  preencode(state, m) {
    c.uint.preencode(state, m.request)
    c.uint.preencode(state, m.reason ? 1 : 0)
    if (m.reason) c.uint.preencode(state, m.reason)
  },
  encode(state, m) {
    c.uint.encode(state, m.request)
    c.uint.encode(state, m.reason ? 1 : 0)
    if (m.reason) c.uint.encode(state, m.reason)
  },
  decode(state, m) {
    const request = c.uint.decode(state)
    const flags = state.start < state.end ? c.uint.decode(state) : 0
    return {
      request,
      reason: flags & 1 ? c.uint.decode(state) : 0
    }
  }
}

// TODO: we should move to having these have a handle like in data, easier since they
// allocate state in practice
wire.want = {
  preencode(state, m) {
    c.uint.preencode(state, m.start)
    c.uint.preencode(state, m.length)

    const flags = m.any ? 1 : 0
    if (flags !== 0) c.uint.preencode(state, flags)
  },
  encode(state, m) {
    c.uint.encode(state, m.start)
    c.uint.encode(state, m.length)

    const flags = m.any ? 1 : 0
    if (flags !== 0) c.uint.encode(state, flags)
  },
  decode(state) {
    const start = c.uint.decode(state)
    const length = c.uint.decode(state)
    const flags = state.start < state.end ? c.uint.decode(state) : 0

    return {
      start,
      length,
      any: (flags & 1) !== 0
    }
  }
}

wire.unwant = {
  preencode(state, m) {
    c.uint.preencode(state, m.start)
    c.uint.preencode(state, m.length)

    const flags = m.any ? 1 : 0
    if (flags !== 0) c.uint.preencode(state, flags)
  },
  encode(state, m) {
    c.uint.encode(state, m.start)
    c.uint.encode(state, m.length)

    const flags = m.any ? 1 : 0
    if (flags !== 0) c.uint.encode(state, flags)
  },
  decode(state, m) {
    const start = c.uint.decode(state)
    const length = c.uint.decode(state)
    const flags = state.start < state.end ? c.uint.decode(state) : 0

    return {
      start,
      length,
      any: (flags & 1) !== 0
    }
  }
}

wire.range = {
  preencode(state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.start)
    if (m.length !== 1) c.uint.preencode(state, m.length)
  },
  encode(state, m) {
    c.uint.encode(state, (m.drop ? 1 : 0) | (m.length === 1 ? 2 : 0))
    c.uint.encode(state, m.start)
    if (m.length !== 1) c.uint.encode(state, m.length)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      drop: (flags & 1) !== 0,
      start: c.uint.decode(state),
      length: (flags & 2) !== 0 ? 1 : c.uint.decode(state)
    }
  }
}

wire.bitfield = {
  preencode(state, m) {
    c.uint.preencode(state, m.start)
    c.uint32array.preencode(state, m.bitfield)
  },
  encode(state, m) {
    c.uint.encode(state, m.start)
    c.uint32array.encode(state, m.bitfield)
  },
  decode(state, m) {
    return {
      start: c.uint.decode(state),
      bitfield: c.uint32array.decode(state)
    }
  }
}

wire.sync = {
  preencode(state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.fork)
    c.uint.preencode(state, m.length)
    c.uint.preencode(state, m.remoteLength)
  },
  encode(state, m) {
    c.uint.encode(
      state,
      (m.canUpgrade ? 1 : 0) |
        (m.uploading ? 2 : 0) |
        (m.downloading ? 4 : 0) |
        (m.hasManifest ? 8 : 0) |
        (m.allowPush ? 16 : 0)
    )
    c.uint.encode(state, m.fork)
    c.uint.encode(state, m.length)
    c.uint.encode(state, m.remoteLength)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      fork: c.uint.decode(state),
      length: c.uint.decode(state),
      remoteLength: c.uint.decode(state),
      canUpgrade: (flags & 1) !== 0,
      uploading: (flags & 2) !== 0,
      downloading: (flags & 4) !== 0,
      hasManifest: (flags & 8) !== 0,
      allowPush: (flags & 16) !== 0
    }
  }
}

wire.reorgHint = {
  preencode(state, m) {
    c.uint.preencode(state, m.from)
    c.uint.preencode(state, m.to)
    c.uint.preencode(state, m.ancestors)
  },
  encode(state, m) {
    c.uint.encode(state, m.from)
    c.uint.encode(state, m.to)
    c.uint.encode(state, m.ancestors)
  },
  decode(state) {
    return {
      from: c.uint.encode(state),
      to: c.uint.encode(state),
      ancestors: c.uint.encode(state)
    }
  }
}

wire.extension = {
  preencode(state, m) {
    c.string.preencode(state, m.name)
    c.raw.preencode(state, m.message)
  },
  encode(state, m) {
    c.string.encode(state, m.name)
    c.raw.encode(state, m.message)
  },
  decode(state) {
    return {
      name: c.string.decode(state),
      message: c.raw.decode(state)
    }
  }
}

const keyValue = {
  preencode(state, p) {
    c.string.preencode(state, p.key)
    c.buffer.preencode(state, p.value)
  },
  encode(state, p) {
    c.string.encode(state, p.key)
    c.buffer.encode(state, p.value)
  },
  decode(state) {
    return {
      key: c.string.decode(state),
      value: c.buffer.decode(state)
    }
  }
}

const treeUpgrade = {
  preencode(state, u) {
    c.uint.preencode(state, u.fork)
    c.uint.preencode(state, u.ancestors)
    c.uint.preencode(state, u.length)
    c.buffer.preencode(state, u.signature)
  },
  encode(state, u) {
    c.uint.encode(state, u.fork)
    c.uint.encode(state, u.ancestors)
    c.uint.encode(state, u.length)
    c.buffer.encode(state, u.signature)
  },
  decode(state) {
    return {
      fork: c.uint.decode(state),
      ancestors: c.uint.decode(state),
      length: c.uint.decode(state),
      signature: c.buffer.decode(state)
    }
  }
}

const bitfieldUpdate = {
  // TODO: can maybe be folded into a HAVE later on with the most recent spec
  preencode(state, b) {
    state.end++ // flags
    c.uint.preencode(state, b.start)
    c.uint.preencode(state, b.length)
  },
  encode(state, b) {
    state.buffer[state.start++] = b.drop ? 1 : 0
    c.uint.encode(state, b.start)
    c.uint.encode(state, b.length)
  },
  decode(state) {
    const flags = c.uint.decode(state)
    return {
      drop: (flags & 1) !== 0,
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

const oplog = (exports.oplog = {})

oplog.entry = {
  preencode(state, m) {
    state.end++ // flags
    if (m.userData) keyValue.preencode(state, m.userData)
    if (m.treeNodes) nodeArray.preencode(state, m.treeNodes)
    if (m.treeUpgrade) treeUpgrade.preencode(state, m.treeUpgrade)
    if (m.bitfield) bitfieldUpdate.preencode(state, m.bitfield)
  },
  encode(state, m) {
    const s = state.start++
    let flags = 0

    if (m.userData) {
      flags |= 1
      keyValue.encode(state, m.userData)
    }
    if (m.treeNodes) {
      flags |= 2
      nodeArray.encode(state, m.treeNodes)
    }
    if (m.treeUpgrade) {
      flags |= 4
      treeUpgrade.encode(state, m.treeUpgrade)
    }
    if (m.bitfield) {
      flags |= 8
      bitfieldUpdate.encode(state, m.bitfield)
    }

    state.buffer[s] = flags
  },
  decode(state) {
    const flags = c.uint.decode(state)
    return {
      userData: (flags & 1) !== 0 ? keyValue.decode(state) : null,
      treeNodes: (flags & 2) !== 0 ? nodeArray.decode(state) : null,
      treeUpgrade: (flags & 4) !== 0 ? treeUpgrade.decode(state) : null,
      bitfield: (flags & 8) !== 0 ? bitfieldUpdate.decode(state) : null
    }
  }
}

const keyPair = {
  preencode(state, kp) {
    c.buffer.preencode(state, kp.publicKey)
    c.buffer.preencode(state, kp.secretKey)
  },
  encode(state, kp) {
    c.buffer.encode(state, kp.publicKey)
    c.buffer.encode(state, kp.secretKey)
  },
  decode(state) {
    return {
      publicKey: c.buffer.decode(state),
      secretKey: c.buffer.decode(state)
    }
  }
}

const reorgHint = {
  preencode(state, r) {
    c.uint.preencode(state, r.from)
    c.uint.preencode(state, r.to)
    c.uint.preencode(state, r.ancestors)
  },
  encode(state, r) {
    c.uint.encode(state, r.from)
    c.uint.encode(state, r.to)
    c.uint.encode(state, r.ancestors)
  },
  decode(state) {
    return {
      from: c.uint.decode(state),
      to: c.uint.decode(state),
      ancestors: c.uint.decode(state)
    }
  }
}

const reorgHintArray = c.array(reorgHint)

const hints = {
  preencode(state, h) {
    reorgHintArray.preencode(state, h.reorgs)
    c.uint.preencode(state, h.contiguousLength)
  },
  encode(state, h) {
    reorgHintArray.encode(state, h.reorgs)
    c.uint.encode(state, h.contiguousLength)
  },
  decode(state) {
    return {
      reorgs: reorgHintArray.decode(state),
      contiguousLength: state.start < state.end ? c.uint.decode(state) : 0
    }
  }
}

const treeHeader = {
  preencode(state, t) {
    c.uint.preencode(state, t.fork)
    c.uint.preencode(state, t.length)
    c.buffer.preencode(state, t.rootHash)
    c.buffer.preencode(state, t.signature)
  },
  encode(state, t) {
    c.uint.encode(state, t.fork)
    c.uint.encode(state, t.length)
    c.buffer.encode(state, t.rootHash)
    c.buffer.encode(state, t.signature)
  },
  decode(state) {
    return {
      fork: c.uint.decode(state),
      length: c.uint.decode(state),
      rootHash: c.buffer.decode(state),
      signature: c.buffer.decode(state)
    }
  }
}

const types = {
  preencode(state, t) {
    c.string.preencode(state, t.tree)
    c.string.preencode(state, t.bitfield)
    c.string.preencode(state, t.signer)
  },
  encode(state, t) {
    c.string.encode(state, t.tree)
    c.string.encode(state, t.bitfield)
    c.string.encode(state, t.signer)
  },
  decode(state) {
    return {
      tree: c.string.decode(state),
      bitfield: c.string.decode(state),
      signer: c.string.decode(state)
    }
  }
}

const externalHeader = {
  preencode(state, m) {
    c.uint.preencode(state, m.start)
    c.uint.preencode(state, m.length)
  },
  encode(state, m) {
    c.uint.encode(state, m.start)
    c.uint.encode(state, m.length)
  },
  decode(state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

const keyValueArray = c.array(keyValue)

oplog.header = {
  preencode(state, h) {
    state.end += 2 // version + flags
    if (h.external) {
      externalHeader.preencode(state, h.external)
      return
    }
    c.fixed32.preencode(state, h.key)
    if (h.manifest) manifest.preencode(state, h.manifest)
    if (h.keyPair) keyPair.preencode(state, h.keyPair)
    keyValueArray.preencode(state, h.userData)
    treeHeader.preencode(state, h.tree)
    hints.preencode(state, h.hints)
  },
  encode(state, h) {
    c.uint.encode(state, 1)
    if (h.external) {
      c.uint.encode(state, 1) // ONLY set the first big for clarity
      externalHeader.encode(state, h.external)
      return
    }
    c.uint.encode(state, (h.manifest ? 2 : 0) | (h.keyPair ? 4 : 0))
    c.fixed32.encode(state, h.key)
    if (h.manifest) manifest.encode(state, h.manifest)
    if (h.keyPair) keyPair.encode(state, h.keyPair)
    keyValueArray.encode(state, h.userData)
    treeHeader.encode(state, h.tree)
    hints.encode(state, h.hints)
  },
  decode(state) {
    const version = c.uint.decode(state)

    if (version > 1) {
      throw INVALID_OPLOG_VERSION('Invalid header version. Expected <= 1, got ' + version)
    }

    if (version === 0) {
      const old = {
        types: types.decode(state),
        userData: keyValueArray.decode(state),
        tree: treeHeader.decode(state),
        signer: keyPair.decode(state),
        hints: hints.decode(state)
      }

      return {
        external: null,
        key: old.signer.publicKey,
        manifest: {
          version: 0,
          hash: old.types.tree,
          allowPatch: false,
          quorum: 1,
          signers: [
            {
              signature: old.types.signer,
              namespace: DEFAULT_NAMESPACE,
              publicKey: old.signer.publicKey
            }
          ],
          prologue: null,
          linked: null,
          userData: null
        },
        keyPair: old.signer.secretKey ? old.signer : null,
        userData: old.userData,
        tree: old.tree,
        hints: old.hints
      }
    }

    const flags = c.uint.decode(state)

    if (flags & 1) {
      return {
        external: externalHeader.decode(state),
        key: null,
        manifest: null,
        keyPair: null,
        userData: null,
        tree: null,
        hints: null
      }
    }

    return {
      external: null,
      key: c.fixed32.decode(state),
      manifest: (flags & 2) !== 0 ? manifest.decode(state) : null,
      keyPair: (flags & 4) !== 0 ? keyPair.decode(state) : null,
      userData: keyValueArray.decode(state),
      tree: treeHeader.decode(state),
      hints: hints.decode(state)
    }
  }
}

const uintArray = c.array(c.uint)

const multisigInput = {
  preencode(state, inp) {
    c.uint.preencode(state, inp.signer)
    c.fixed64.preencode(state, inp.signature)
    c.uint.preencode(state, inp.patch)
  },
  encode(state, inp) {
    c.uint.encode(state, inp.signer)
    c.fixed64.encode(state, inp.signature)
    c.uint.encode(state, inp.patch)
  },
  decode(state) {
    return {
      signer: c.uint.decode(state),
      signature: c.fixed64.decode(state),
      patch: c.uint.decode(state)
    }
  }
}

const patchEncodingv0 = {
  preencode(state, n) {
    c.uint.preencode(state, n.start)
    c.uint.preencode(state, n.length)
    uintArray.preencode(state, n.nodes)
  },
  encode(state, n) {
    c.uint.encode(state, n.start)
    c.uint.encode(state, n.length)
    uintArray.encode(state, n.nodes)
  },
  decode(state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state),
      nodes: uintArray.decode(state)
    }
  }
}

const multisigInputv0 = {
  preencode(state, n) {
    state.end++
    c.uint.preencode(state, n.signer)
    c.fixed64.preencode(state, n.signature)
    if (n.patch) patchEncodingv0.preencode(state, n.patch)
  },
  encode(state, n) {
    c.uint.encode(state, n.patch ? 1 : 0)
    c.uint.encode(state, n.signer)
    c.fixed64.encode(state, n.signature)
    if (n.patch) patchEncodingv0.encode(state, n.patch)
  },
  decode(state) {
    const flags = c.uint.decode(state)
    return {
      signer: c.uint.decode(state),
      signature: c.fixed64.decode(state),
      patch: flags & 1 ? patchEncodingv0.decode(state) : null
    }
  }
}

const multisigInputArrayv0 = c.array(multisigInputv0)
const multisigInputArray = c.array(multisigInput)

const compactNode = {
  preencode(state, n) {
    c.uint.preencode(state, n.index)
    c.uint.preencode(state, n.size)
    c.fixed32.preencode(state, n.hash)
  },
  encode(state, n) {
    c.uint.encode(state, n.index)
    c.uint.encode(state, n.size)
    c.fixed32.encode(state, n.hash)
  },
  decode(state) {
    return {
      index: c.uint.decode(state),
      size: c.uint.decode(state),
      hash: c.fixed32.decode(state)
    }
  }
}

const compactNodeArray = c.array(compactNode)

exports.multiSignaturev0 = {
  preencode(state, s) {
    multisigInputArrayv0.preencode(state, s.proofs)
    compactNodeArray.preencode(state, s.patch)
  },
  encode(state, s) {
    multisigInputArrayv0.encode(state, s.proofs)
    compactNodeArray.encode(state, s.patch)
  },
  decode(state) {
    return {
      proofs: multisigInputArrayv0.decode(state),
      patch: compactNodeArray.decode(state)
    }
  }
}

exports.multiSignature = {
  preencode(state, s) {
    multisigInputArray.preencode(state, s.proofs)
    compactNodeArray.preencode(state, s.patch)
  },
  encode(state, s) {
    multisigInputArray.encode(state, s.proofs)
    compactNodeArray.encode(state, s.patch)
  },
  decode(state) {
    return {
      proofs: multisigInputArray.decode(state),
      patch: compactNodeArray.decode(state)
    }
  }
}
const c = require('compact-encoding')
const b4a = require('b4a')
const flat = require('flat-tree')
const { MerkleTree } = require('./merkle-tree')
const { multiSignature, multiSignaturev0 } = require('./messages')

module.exports = {
  assemblev0,
  assemble,
  inflatev0,
  inflate,
  partialSignature,
  signableLength
}

function inflatev0(data) {
  return c.decode(multiSignaturev0, data)
}

function inflate(data) {
  return c.decode(multiSignature, data)
}

async function partialSignature(
  core,
  signer,
  from,
  to = core.state.length,
  signature = core.state.signature
) {
  if (from > core.state.length) return null
  const nodes = to <= from ? null : await upgradeNodes(core, from, to)

  if (signature.byteLength !== 64) {
    signature = c.decode(multiSignature, signature).proofs[0].signature
  }

  return {
    signer,
    signature,
    patch: nodes ? to - from : 0,
    nodes
  }
}

async function upgradeNodes(core, from, to) {
  const rx = core.state.storage.read()
  let p = null
  try {
    p = await MerkleTree.proof(core.state, rx, { upgrade: { start: from, length: to - from } })
  } catch (err) {
    rx.destroy()
    throw err
  }
  rx.tryFlush()
  return (await p.settle()).upgrade.nodes
}

function signableLength(lengths, quorum) {
  if (quorum <= 0) quorum = 1
  if (quorum > lengths.length) return 0

  return lengths.sort(cmp)[quorum - 1]
}

function cmp(a, b) {
  return b - a
}

function assemblev0(inputs) {
  const proofs = []
  const patch = []

  for (const u of inputs) {
    proofs.push(compressProof(u, patch))
  }

  return c.encode(multiSignaturev0, { proofs, patch })
}

function assemble(inputs) {
  const proofs = []
  const patch = []
  const seen = new Set()

  for (const u of inputs) {
    if (u.nodes) {
      for (const node of u.nodes) {
        if (seen.has(node.index)) continue
        seen.add(node.index)
        patch.push(node)
      }
    }

    proofs.push({
      signer: u.signer,
      signature: u.signature,
      patch: u.patch
    })
  }

  return c.encode(multiSignature, { proofs, patch })
}

function compareNode(a, b) {
  if (a.index !== b.index) return false
  if (a.size !== b.size) return false
  return b4a.equals(a.hash, b.hash)
}

function compressProof(proof, nodes) {
  return {
    signer: proof.signer,
    signature: proof.signature,
    patch: proof.patch ? compressUpgrade(proof, nodes) : null
  }
}

function compressUpgrade(p, nodes) {
  const u = {
    start: flat.rightSpan(p.nodes[p.nodes.length - 1].index) / 2 + 1,
    length: p.patch,
    nodes: []
  }

  for (const node of p.nodes) {
    let present = false
    for (let i = 0; i < nodes.length; i++) {
      if (!compareNode(nodes[i], node)) continue

      u.nodes.push(i)
      present = true
      break
    }

    if (present) continue
    u.nodes.push(nodes.push(node) - 1)
  }

  return u
}
module.exports = class Mutex {
  constructor() {
    this.locked = false
    this.destroyed = false

    this._destroying = null
    this._destroyError = null
    this._queue = []
    this._enqueue = (resolve, reject) => this._queue.push([resolve, reject])
  }

  idle() {
    return this._queue.length === 0 && this.locked === false
  }

  lock() {
    if (this.destroyed) {
      return Promise.reject(this._destroyError || new Error('Mutex has been destroyed'))
    }
    if (this.locked) return new Promise(this._enqueue)
    this.locked = true
    return Promise.resolve()
  }

  unlock() {
    if (!this._queue.length) {
      this.locked = false
      return
    }
    this._queue.shift()[0]()
  }

  destroy(err) {
    if (!this._destroying) {
      this._destroying = this.locked ? this.lock().catch(() => {}) : Promise.resolve()
    }

    this.destroyed = true
    if (err) this._destroyError = err

    if (err) {
      while (this._queue.length) this._queue.shift()[1](err)
    }

    return this._destroying
  }
}
const FIFO = require('fast-fifo')

module.exports = class ReceiverQueue {
  constructor() {
    this.queue = new FIFO()
    this.priority = []
    this.requests = new Map()
    this.length = 0
  }

  push(req) {
    // TODO: use a heap at some point if we wanna support multiple prios
    if (req.priority > 0) this.priority.push(req)
    else this.queue.push(req)

    this.requests.set(req.id, req)
    this.length++
  }

  shift() {
    while (this.priority.length > 0) {
      const msg = this.priority.pop()
      const req = this._processRequest(msg)
      if (req !== null) return req
    }

    while (this.queue.length > 0) {
      const msg = this.queue.shift()
      const req = this._processRequest(msg)
      if (req !== null) return req
    }

    return null
  }

  _processRequest(req) {
    if (req.block || req.hash || req.seek || req.upgrade || req.manifest) {
      this.requests.delete(req.id)
      this.length--
      return req
    }

    return null
  }

  clear() {
    this.queue.clear()
    this.priority = []
    this.length = 0
    this.requests.clear()
  }

  delete(id) {
    const req = this.requests.get(id)
    if (!req) return

    req.block = null
    req.hash = null
    req.seek = null
    req.upgrade = null
    req.manifest = false

    this.requests.delete(id)
    this.length--

    if (this.length === 0) {
      this.queue.clear()
      this.priority = []
    }
  }
}
const BigSparseArray = require('big-sparse-array')
const quickbit = require('./compat').quickbit

const BITS_PER_PAGE = 32768
const BYTES_PER_PAGE = BITS_PER_PAGE / 8
const WORDS_PER_PAGE = BYTES_PER_PAGE / 4
const BITS_PER_SEGMENT = 2097152
const BYTES_PER_SEGMENT = BITS_PER_SEGMENT / 8
const PAGES_PER_SEGMENT = BITS_PER_SEGMENT / BITS_PER_PAGE

class RemoteBitfieldPage {
  constructor(index, bitfield, segment) {
    this.index = index
    this.offset = index * BYTES_PER_PAGE - segment.offset
    this.bitfield = bitfield
    this.segment = segment

    segment.add(this)
  }

  get tree() {
    return this.segment.tree
  }

  get(index) {
    return quickbit.get(this.bitfield, index)
  }

  set(index, val) {
    if (quickbit.set(this.bitfield, index, val)) {
      this.tree.update(this.offset * 8 + index)
    }
  }

  setRange(start, end, val) {
    quickbit.fill(this.bitfield, val, start, end)

    let i = Math.floor(start / 128)
    const n = i + Math.ceil((end - start) / 128)

    while (i <= n) this.tree.update(this.offset * 8 + i++ * 128)
  }

  findFirst(val, position) {
    return quickbit.findFirst(this.bitfield, val, position)
  }

  findLast(val, position) {
    return quickbit.findLast(this.bitfield, val, position)
  }

  insert(start, bitfield) {
    this.bitfield.set(bitfield, start / 32)
    this.segment.refresh()
  }

  clear(start, bitfield) {
    quickbit.clear(this.bitfield, { field: bitfield, offset: start })
  }
}

class RemoteBitfieldSegment {
  constructor(index) {
    this.index = index
    this.offset = index * BYTES_PER_SEGMENT
    this.tree = quickbit.Index.from([], BYTES_PER_SEGMENT)
    this.pages = new Array(PAGES_PER_SEGMENT)
    this.pagesLength = 0
  }

  get chunks() {
    return this.tree.chunks
  }

  refresh() {
    this.tree = quickbit.Index.from(this.tree.chunks, BYTES_PER_SEGMENT)
  }

  add(page) {
    const pageIndex = page.index - this.index * PAGES_PER_SEGMENT
    if (pageIndex >= this.pagesLength) this.pagesLength = pageIndex + 1

    this.pages[pageIndex] = page

    const chunk = { field: page.bitfield, offset: page.offset }

    this.chunks.push(chunk)

    for (let i = this.chunks.length - 2; i >= 0; i--) {
      const prev = this.chunks[i]
      if (prev.offset <= chunk.offset) break
      this.chunks[i] = chunk
      this.chunks[i + 1] = prev
    }
  }

  findFirst(val, position) {
    position = this.tree.skipFirst(!val, position)

    let j = position & (BITS_PER_PAGE - 1)
    let i = (position - j) / BITS_PER_PAGE

    if (i >= PAGES_PER_SEGMENT) return -1

    while (i < this.pagesLength) {
      const p = this.pages[i]

      let index = -1

      if (p) index = p.findFirst(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_PAGE + index

      j = 0
      i++
    }

    return val || this.pagesLength === PAGES_PER_SEGMENT ? -1 : this.pagesLength * BITS_PER_PAGE
  }

  findLast(val, position) {
    position = this.tree.skipLast(!val, position)

    let j = position & (BITS_PER_PAGE - 1)
    let i = (position - j) / BITS_PER_PAGE

    if (i >= PAGES_PER_SEGMENT) return -1

    while (i >= 0) {
      const p = this.pages[i]

      let index = -1

      if (p) index = p.findLast(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_PAGE + index

      j = BITS_PER_PAGE - 1
      i--
    }

    return -1
  }
}

module.exports = class RemoteBitfield {
  static BITS_PER_PAGE = BITS_PER_PAGE
  static BITS_PER_SEGMENT = BITS_PER_SEGMENT

  constructor() {
    this._pages = new BigSparseArray()
    this._segments = new BigSparseArray()
    this._maxSegments = 0
  }

  getBitfield(index) {
    const j = index & (BITS_PER_PAGE - 1)
    const i = (index - j) / BITS_PER_PAGE

    const p = this._pages.get(i)
    return p || null
  }

  get(index) {
    const j = index & (BITS_PER_PAGE - 1)
    const i = (index - j) / BITS_PER_PAGE

    const p = this._pages.get(i)

    return p ? p.get(j) : false
  }

  set(index, val) {
    const j = index & (BITS_PER_PAGE - 1)
    const i = (index - j) / BITS_PER_PAGE

    let p = this._pages.get(i)

    if (!p && val) {
      const k = Math.floor(i / PAGES_PER_SEGMENT)
      const s = this._segments.get(k) || this._segments.set(k, new RemoteBitfieldSegment(k))
      if (this._maxSegments <= k) this._maxSegments = k + 1

      p = this._pages.set(i, new RemoteBitfieldPage(i, new Uint32Array(WORDS_PER_PAGE), s))
    }

    if (p) p.set(j, val)
  }

  setRange(start, end, val) {
    let j = start & (BITS_PER_PAGE - 1)
    let i = (start - j) / BITS_PER_PAGE

    while (start < end) {
      let p = this._pages.get(i)

      if (!p && val) {
        const k = Math.floor(i / PAGES_PER_SEGMENT)
        const s = this._segments.get(k) || this._segments.set(k, new RemoteBitfieldSegment(k))
        if (this._maxSegments <= k) this._maxSegments = k + 1

        p = this._pages.set(i, new RemoteBitfieldPage(i, new Uint32Array(WORDS_PER_PAGE), s))
      }

      const offset = i * BITS_PER_PAGE
      const last = Math.min(end - offset, BITS_PER_PAGE)
      const range = last - j

      if (p) p.setRange(j, last, val)

      j = 0
      i++
      start += range
    }
  }

  findFirst(val, position) {
    let j = position & (BITS_PER_SEGMENT - 1)
    let i = (position - j) / BITS_PER_SEGMENT

    while (i < this._maxSegments) {
      const s = this._segments.get(i)

      let index = -1

      if (s) index = s.findFirst(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_SEGMENT + index

      j = 0
      i++
    }

    // For the val === false case, we always return at least
    // the 'position', also if nothing was found
    return val ? -1 : Math.max(position, this._maxSegments * BITS_PER_SEGMENT)
  }

  firstSet(position) {
    return this.findFirst(true, position)
  }

  firstUnset(position) {
    return this.findFirst(false, position)
  }

  findLast(val, position) {
    let j = position & (BITS_PER_SEGMENT - 1)
    let i = (position - j) / BITS_PER_SEGMENT

    while (i >= 0) {
      const s = this._segments.get(i)

      let index = -1

      if (s) index = s.findLast(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_SEGMENT + index

      j = BITS_PER_SEGMENT - 1
      i--
    }

    return -1
  }

  lastSet(position) {
    return this.findLast(true, position)
  }

  lastUnset(position) {
    return this.findLast(false, position)
  }

  insert(start, bitfield) {
    if (start % 32 !== 0) return false

    let length = bitfield.byteLength * 8

    let j = start & (BITS_PER_PAGE - 1)
    let i = (start - j) / BITS_PER_PAGE

    while (length > 0) {
      let p = this._pages.get(i)

      if (!p) {
        const k = Math.floor(i / PAGES_PER_SEGMENT)
        const s = this._segments.get(k) || this._segments.set(k, new RemoteBitfieldSegment(k))
        if (this._maxSegments <= k) this._maxSegments = k + 1

        p = this._pages.set(i, new RemoteBitfieldPage(i, new Uint32Array(WORDS_PER_PAGE), s))
      }

      const end = Math.min(j + length, BITS_PER_PAGE)
      const range = end - j

      p.insert(j, bitfield.subarray(0, range / 32))

      bitfield = bitfield.subarray(range / 32)

      j = 0
      i++
      length -= range
    }

    return true
  }

  clear(start, bitfield) {
    if (start % 32 !== 0) return false

    let length = bitfield.byteLength * 8

    let j = start & (BITS_PER_PAGE - 1)
    let i = (start - j) / BITS_PER_PAGE

    while (length > 0) {
      let p = this._pages.get(i)

      if (!p) {
        const k = Math.floor(i / PAGES_PER_SEGMENT)
        const s = this._segments.get(k) || this._segments.set(k, new RemoteBitfieldSegment(k))
        if (this._maxSegments <= k) this._maxSegments = k + 1

        p = this._pages.set(i, new RemoteBitfieldPage(i, new Uint32Array(WORDS_PER_PAGE), s))
      }

      const end = Math.min(j + length, BITS_PER_PAGE)
      const range = end - j

      p.clear(j, bitfield.subarray(0, range / 32))

      bitfield = bitfield.subarray(range / 32)

      j = 0
      i++
      length -= range
    }

    return true
  }
}
/* DEV DOCS
  Every hypercore has one Replicator object managing its connections to other peers.
  There is one Peer object per peer connected to the Hypercore.
  Hypercores do not know about other hypercores, so when a peer is connected to multiple cores, there exists one Peer object per core.

  Hypercore indicates block should be downloaded through methods like Replicator.addRange or Replicator.addBlock
  Hypercore calls Replicator.updateActivity every time a hypercore session opens/closes
  Replicator.updateActivity ensures the Hypercore is downloading blocks as expected
  Replicator keeps track of:
    - Which blocks need to be downloaded (Replicator._blocks)
    - Which blocks currently have inflight requests (Replicator._inflight)

  Blocks are requested from remote peers by Peer objects. The flow is:
    - The replicator's updatePeer method gets called
    - The replicator detects whether the Peer can accept more requests (for example by checking if it's maxed out on inflight blocks)
    - The replicator then tells the Peer what to request (e.g. Peer_requestRange or Peer._requestBlock methods)

  The Peer object is responsible for tracking
    - Which blocks does the Peer have available (tracked in remoteBitfield)
    - Which blocks are you actively looking for from this peer (tracked in missingBlocks)
    - How many blocks are currently inflight (tracked in inflight)
  The Peer uses this information to decide which blocks to request from the peer in response to _requestRange requests and the like.
*/

const b4a = require('b4a')
const safetyCatch = require('safety-catch')
const RandomIterator = require('random-array-iterator')
const flatTree = require('flat-tree')
const Mutex = require('./mutex')
const ReceiverQueue = require('./receiver-queue')
const HotswapQueue = require('./hotswap-queue')
const RemoteBitfield = require('./remote-bitfield')
const { MerkleTree } = require('./merkle-tree')
const w = require('./wants')
const { LocalWants, RemoteWants } = w
const {
  REQUEST_CANCELLED,
  REQUEST_TIMEOUT,
  INVALID_CAPABILITY,
  SNAPSHOT_NOT_AVAILABLE,
  ASSERTION
} = require('hypercore-errors')
const m = require('./messages')
const caps = require('./caps')

const DEFAULT_MAX_INFLIGHT = [16, 512]
const SCALE_LATENCY = 50
const NOT_DOWNLOADING_SLACK = (20000 + Math.random() * 20000) | 0
const MAX_PEERS_UPGRADE = 3
const LAST_BLOCKS = 256

const MAX_RANGES = 64

const NOT_AVAILABLE = 1
const INVALID_REQUEST = 2
const MAX_INVALID_REQUESTS = 64
const MAX_BACKOFFS = MAX_INVALID_REQUESTS / 2

const PRIORITY = {
  NORMAL: 0,
  HIGH: 1,
  VERY_HIGH: 2,
  CANCELLED: 255 // reserved to mark cancellation
}

class Attachable {
  constructor(replicator) {
    this.replicator = replicator
    this.resolved = false
    this.processing = false
    this.refs = []
    this.wants = null
  }

  addWant(w) {
    if (this.wants === null) this.wants = new Set()
    this.wants.add(w)
  }

  removeWant(w) {
    if (this.wants === null) return
    this.wants.delete(w)
  }

  attach(session) {
    const r = {
      context: this,
      session,
      sindex: 0,
      rindex: 0,
      snapshot: true,
      resolve: null,
      reject: null,
      promise: null,
      timeout: null
    }

    r.sindex = session.push(r) - 1
    r.rindex = this.refs.push(r) - 1
    r.promise = new Promise((resolve, reject) => {
      r.resolve = resolve
      r.reject = reject
    })

    return r
  }

  detach(r, err = null) {
    if (r.context !== this) return false

    this._detach(r)
    this._cancel(r, err)
    this.gc()

    return true
  }

  _detach(r) {
    const rh = this.refs.pop()
    const sh = r.session.pop()

    if (r.rindex < this.refs.length) this.refs[(rh.rindex = r.rindex)] = rh
    if (r.sindex < r.session.length) r.session[(sh.sindex = r.sindex)] = sh

    destroyRequestTimeout(r)
    r.context = null

    return r
  }

  gc() {
    if (this.refs.length > 0 || this.processing) return
    this._unref()

    if (this.wants === null) return

    const wants = this.wants
    this.wants = null

    let update = null

    for (const w of wants) {
      if (w.any) {
        const removed = w.wants.removeAnyRange(w.start, w.length, this)
        if (!removed) continue
        if (update === null) update = new Set()
        update.add(w.wants.peer)
        // TODO: should also use a free list for simplicity
        w.wants.peer.wireUnwant.send(removed)
        continue
      }

      if (w.wants.removeBatch(w.start, this)) {
        if (update === null) update = new Set()
        update.add(w.wants.peer)
      }
    }

    if (update === null) return
    for (const peer of update) {
      this.replicator.updatePeer(peer)
    }
  }

  processed() {
    this.processing = false
    this.gc()
  }

  _cancel(r, err) {
    r.reject(err || REQUEST_CANCELLED())
  }

  _unref() {
    // overwrite me
  }

  resolve(val) {
    this.resolved = true
    while (this.refs.length > 0) {
      this._detach(this.refs[this.refs.length - 1]).resolve(val)
    }
    this.gc()
  }

  reject(err) {
    this.resolved = true
    while (this.refs.length > 0) {
      this._detach(this.refs[this.refs.length - 1]).reject(err)
    }
    this.gc()
  }

  setTimeout(r, ms) {
    destroyRequestTimeout(r)
    r.timeout = setTimeout(onrequesttimeout, ms, r)
  }
}

class BlockRequest extends Attachable {
  constructor(replicator, tracker, index, priority, force) {
    super(replicator)

    this.index = index
    this.priority = priority
    this.inflight = []
    this.queued = false
    this.hotswap = null
    this.tracker = tracker
    this.force = force
  }

  _unref() {
    if (this.resolved) return
    this.queued = false

    for (const req of this.inflight) {
      req.peer._cancelRequest(req)
    }

    this.tracker.remove(this.index)
    removeHotswap(this)
  }
}

class RangeBatchRequest extends Attachable {
  constructor(replicator, batch) {
    super(replicator)

    this.batch = batch
    this.index = 0
  }
}

class RangeRequest extends Attachable {
  constructor(replicator, ranges, start, end, linear, ifAvailable, blocks) {
    super(replicator)

    this.start = start
    this.end = end
    this.linear = linear
    this.ifAvailable = ifAvailable
    this.blocks = blocks
    this.ranges = ranges
    this.batches = []

    ranges.push(this)

    if (this.end === -1) {
      this.replicator._alwaysLatestBlock++
    }

    // As passed by the user, immut
    this.userStart = start
    this.userEnd = end
  }

  addBatch(batch) {
    for (let i = 0; i < this.batches.length; i++) {
      const b = this.batches[i]
      if (b.batch === batch) return false
    }
    const b = new RangeBatchRequest(this.replicator, batch)
    b.index = this.batches.length
    this.batches.push(b)
    return true
  }

  removeBatch(batch) {
    const head = this.batches.pop()

    if (head !== batch) {
      head.index = batch.index
      this.batches[head.index] = head
    }

    batch.gc()
  }

  _unref() {
    const rangeIndex = this.ranges.indexOf(this)
    if (rangeIndex === -1) return

    const h = this.ranges.pop()
    if (h !== this) {
      this.ranges[rangeIndex] = h
    }

    if (this.end === -1) {
      this.replicator._alwaysLatestBlock--
    }

    while (this.batches.length) {
      this.batches.pop().gc()
    }
  }

  _cancel(r) {
    r.resolve(false)
  }
}

class UpgradeRequest extends Attachable {
  constructor(replicator, fork, length) {
    super(replicator)

    this.fork = fork
    this.length = length
    this.inflight = []
  }

  _unref() {
    if (this.resolved) return
    if (this.replicator.eagerUpgrade === true || this.inflight.length > 0) return
    this.replicator._upgrade = null
  }

  _cancel(r) {
    r.resolve(false)
  }
}

class SeekRequest extends Attachable {
  constructor(replicator, seeks, seeker) {
    super(replicator)

    this.seeker = seeker
    this.inflight = []
    this.seeks = seeks
  }

  _unref() {
    if (this.resolved) return
    if (this.inflight.length > 0) return
    const i = this.seeks.indexOf(this)
    if (i === -1) return
    const h = this.seeks.pop()
    if (i < this.seeks.length) this.seeks[i] = h
  }
}

class ForkRequest extends Attachable {
  constructor(replicator, fork) {
    super(replicator)
    this.fork = fork
    this.inflight = []
    this.batch = null
  }
}

class InflightTracker {
  constructor() {
    this._requests = []
    this._free = []
    this._active = 0
  }

  get idle() {
    return this._active === 0
  }

  *[Symbol.iterator]() {
    for (const req of this._requests) {
      if (req !== null) yield req
    }
  }

  add(req) {
    const id = this._free.length ? this._free.pop() : this._requests.push(null)
    req.id = id
    this._requests[id - 1] = req
    this._active++
    return req
  }

  get(id) {
    return id <= this._requests.length ? this._requests[id - 1] : null
  }

  remove(id, roundtrip) {
    if (id > this._requests.length) return
    if (this._requests[id - 1]) this._active--
    this._requests[id - 1] = null
    if (roundtrip === true) this._free.push(id)
  }

  reusable(id) {
    this._free.push(id)
  }
}

class BlockTracker {
  constructor(replicator) {
    this._replicator = replicator
    this._map = new Map()
  }

  [Symbol.iterator]() {
    return this._map.values()
  }

  isEmpty() {
    return this._map.size === 0
  }

  has(index) {
    return this._map.has(index)
  }

  get(index) {
    return this._map.get(index) || null
  }

  add(index, priority, force) {
    let b = this._map.get(index)
    if (b) return b

    b = new BlockRequest(this._replicator, this, index, priority, force)
    this._map.set(index, b)

    return b
  }

  remove(index) {
    const b = this.get(index)
    this._map.delete(index)
    return b
  }
}

class RoundtripQueue {
  constructor() {
    this.queue = []
    this.tick = 0
  }

  clear() {
    const ids = new Array(this.queue.length)
    for (let i = 0; i < ids.length; i++) {
      ids[i] = this.queue[i][1]
    }

    this.queue = []

    return ids
  }

  add(id) {
    this.queue.push([++this.tick, id])
  }

  flush(tick) {
    let flushed = null

    for (let i = 0; i < this.queue.length; i++) {
      if (this.queue[i][0] > tick) break
      if (flushed === null) flushed = []
      flushed.push(this.queue[i][1])
    }

    if (flushed !== null) this.queue.splice(0, flushed.length)
    return flushed
  }
}

class ProofRequest {
  constructor(msg, proof, block, manifest) {
    this.msg = msg
    this.proof = proof
    this.block = block
    this.manifest = manifest
  }

  async fulfill() {
    if (this.proof === null) return null

    const [proof, block] = await Promise.all([this.proof.settle(), this.block])

    if (this.manifest) proof.manifest = this.manifest
    if (!block && proof.block) return null

    if (block) proof.block.value = block
    return proof
  }
}

class Peer {
  constructor(replicator, protomux, channel, inflightRange) {
    this.core = replicator.core
    this.replicator = replicator
    this.stream = protomux.stream
    this.protomux = protomux
    this.remotePublicKey = this.stream.remotePublicKey
    this.remoteSupportsSeeks = false
    this.inflightRange = inflightRange
    this.fullyDownloadedSignaled = 0

    this.paused = false
    this.removed = false

    this.channel = channel
    this.channel.userData = this

    this.wireSync = this.channel.messages[0]
    this.wireRequest = this.channel.messages[1]
    this.wireCancel = this.channel.messages[2]
    this.wireData = this.channel.messages[3]
    this.wireNoData = this.channel.messages[4]
    this.wireWant = this.channel.messages[5]
    this.wireUnwant = this.channel.messages[6]
    this.wireBitfield = this.channel.messages[7]
    this.wireRange = this.channel.messages[8]
    this.wireExtension = this.channel.messages[9]

    // Same stats as replicator, but for this specific peer
    this.stats = {
      wireSync: { tx: 0, rx: 0 },
      wireRequest: { tx: 0, rx: 0 },
      wireCancel: { tx: 0, rx: 0 },
      wireData: { tx: 0, rx: 0 },
      wireWant: { tx: 0, rx: 0 },
      wireUnwant: { tx: 0, rx: 0 },
      wireBitfield: { tx: 0, rx: 0 },
      wireRange: { tx: 0, rx: 0 },
      wireExtension: { tx: 0, rx: 0 },
      hotswaps: 0,
      invalidData: 0,
      invalidRequests: 0,
      backoffs: 0,
      notAvailableBackoffs: 0
    }

    this.receiverQueue = new ReceiverQueue()
    this.receiverBusy = false

    // most often not used, so made on demand
    this.roundtripQueue = null

    this.inflight = 0
    this.dataProcessing = 0

    this.canUpgrade = true

    this.needsSync = false
    this.syncsProcessing = 0
    this.lastUpgradableLength = 0
    this.lastUpgradableFork = 0

    this._remoteContiguousLength = 0

    // TODO: tweak pipelining so that data sent BEFORE remoteOpened is not cap verified!
    // we might wanna tweak that with some crypto, ie use the cap to encrypt it...
    // or just be aware of that, to only push non leaky data

    this.remoteOpened = false
    this.remoteBitfield = new RemoteBitfield()
    this.missingBlocks = new RemoteBitfield()

    this.pushedLength = 0

    this.remoteFork = 0
    this.remoteLength = 0
    this.remoteCanUpgrade = false
    this.remoteUploading = true
    this.remoteDownloading = true
    this.remoteSynced = false
    this.remoteHasManifest = false
    this.remoteAllowPush = false
    this.remoteRequests = new Map()

    this.segmentsWanted = new Set()
    this.broadcastedNonSparse = false

    this.wants = new LocalWants(this)
    this.remoteWants = new RemoteWants(this)

    this.lengthAcked = 0

    this.extensions = new Map()
    this.lastExtensionSent = ''
    this.lastExtensionRecv = ''

    replicator._ifAvailable++
    replicator._active++
  }

  get remoteContiguousLength() {
    return this.remoteBitfield.findFirst(false, this._remoteContiguousLength)
  }

  getMaxInflight() {
    const stream = this.stream.rawStream
    if (!stream.udx) return Math.min(this.inflightRange[1], this.inflightRange[0] * 3)

    const scale =
      stream.rtt <= SCALE_LATENCY
        ? 1
        : (stream.rtt / SCALE_LATENCY) * Math.min(1, 2 / this.replicator.peers.length)
    return Math.max(
      this.inflightRange[0],
      Math.round(Math.min(this.inflightRange[1], this.inflightRange[0] * scale))
    )
  }

  getMaxHotswapInflight() {
    const inf = this.getMaxInflight()
    return Math.max(16, inf / 2)
  }

  signalUpgrade() {
    if (this._shouldUpdateCanUpgrade() === true) this._updateCanUpgradeAndSync()
    else this.sendSync()
  }

  _markInflight(index) {
    this.missingBlocks.set(index, false)
  }

  broadcastRange(start, length, drop) {
    if (!this.isActive()) return

    if (drop) this._unclearLocalRange(start, length)
    else this._clearLocalRange(start, length)

    const fullyContig = this.core.header.hints.contiguousLength === this.core.state.length

    if (start + LAST_BLOCKS < this.core.state.length && !drop && !fullyContig) {
      if (!this.remoteWants.hasRange(start, length)) return
    }

    let force = false
    if (fullyContig && !drop) {
      start = 0
      length = this.core.state.length

      // Always send the broadcast when we switch from sparse to fully contiguous, so remote knows too
      if (this.fullyDownloadedSignaled < length) {
        this.fullyDownloadedSignaled = length
        force = true
      }
    }

    // TODO: consider also adding early-returns on the drop===true case
    if (!force && !drop) {
      // No need to broadcast if the remote already has this range

      if (this._remoteContiguousLength >= start + length) return

      if (length === 1) {
        if (this.remoteBitfield.get(start)) return
      } else {
        if (this.remoteBitfield.firstUnset(start) >= start + length) return
      }
    }

    this.wireRange.send({
      drop,
      start,
      length
    })
    incrementTx(this.stats.wireRange, this.replicator.stats.wireRange)
  }

  extension(name, message) {
    this.wireExtension.send({ name: name === this.lastExtensionSent ? '' : name, message })
    incrementTx(this.stats.wireExtension, this.replicator.stats.wireExtension)
    this.lastExtensionSent = name
  }

  onextension(message) {
    const name = message.name || this.lastExtensionRecv
    this.lastExtensionRecv = name
    const ext = this.extensions.get(name)
    if (ext) {
      ext._onmessage({ start: 0, end: message.message.byteLength, buffer: message.message }, this)
    }
  }

  sendSync() {
    // Skip syncs if in repair mode
    if (this.core._repairMode) return

    if (this.syncsProcessing !== 0) {
      this.needsSync = true
      return
    }

    if (this.core.state.fork !== this.remoteFork) {
      this.canUpgrade = false
    }

    this.needsSync = false

    this.wireSync.send({
      fork: this.core.state.fork,
      length: this.core.state.length,
      remoteLength: this.core.state.fork === this.remoteFork ? this.remoteLength : 0,
      canUpgrade: this.canUpgrade,
      uploading: true,
      downloading: this.replicator.isDownloading(),
      hasManifest: !!this.core.header.manifest && this.core.compat === false,
      allowPush: this.replicator.isAllowingPush()
    })
    incrementTx(this.stats.wireSync, this.replicator.stats.wireSync)
  }

  onopen({ seeks, capability }) {
    const expected = caps.replicate(
      this.stream.isInitiator === false,
      this.core.key,
      this.stream.handshakeHash
    )

    if (b4a.equals(capability, expected) !== true) {
      // TODO: change this to a rejection instead, less leakage
      throw INVALID_CAPABILITY('Remote sent an invalid replication capability')
    }

    if (this.remoteOpened === true) return
    this.remoteOpened = true
    this.remoteSupportsSeeks = seeks

    this.protomux.cork()

    this.sendSync()

    const contig = Math.min(this.core.state.length, this.core.header.hints.contiguousLength)
    if (contig > 0) {
      this.broadcastRange(0, contig, false)

      if (contig === this.core.state.length) {
        this.broadcastedNonSparse = true
      }
    }

    this.replicator._ifAvailable--
    this.replicator._addPeer(this)

    this.protomux.uncork()

    this.core.checkIfIdle()
  }

  onclose(isRemote) {
    // we might have signalled to the remote that we are done (ie not downloading) and the remote might agree on that
    // if that happens, the channel might be closed by the remote. if so just renegotiate it.
    // TODO: add a CLOSE_REASON to mux to we can make this cleaner...
    const reopen =
      isRemote === true &&
      this.remoteOpened === true &&
      this.remoteDownloading === false &&
      this.remoteUploading === true &&
      this.replicator.downloading === true

    if (this.remoteOpened === false) {
      this.replicator._ifAvailable--
      this.replicator.updateAll()
      return
    }

    this.remoteOpened = false
    this.removed = true
    this.remoteRequests.clear() // cancel all
    this.receiverQueue.clear()

    if (this.roundtripQueue !== null) {
      for (const id of this.roundtripQueue.clear()) this.replicator._inflight.reusable(id)
    }

    this.replicator._removePeer(this)

    if (reopen) {
      this.replicator._makePeer(this.protomux)
    }
  }

  closeIfIdle() {
    if (this.remoteDownloading === false && this.replicator.isDownloading() === false) {
      // idling, shut it down...
      this.channel.close()
      return true
    }

    return false
  }

  async onsync(msg) {
    const {
      fork,
      length,
      remoteLength,
      canUpgrade,
      uploading,
      downloading,
      hasManifest,
      allowPush
    } = msg

    const lengthChanged = length !== this.remoteLength
    const sameFork = fork === this.core.state.fork

    this.remoteSynced = true
    this.remoteFork = fork
    this.remoteLength = length
    this.remoteCanUpgrade = canUpgrade
    this.remoteUploading = uploading
    this.remoteDownloading = downloading
    this.remoteHasManifest = hasManifest
    this.remoteAllowPush = allowPush

    if (this.closeIfIdle()) return

    this.lengthAcked = sameFork ? remoteLength : 0
    this.syncsProcessing++

    this.replicator._updateFork(this)

    if (this.remoteLength > this.core.state.length && this.lengthAcked === this.core.state.length) {
      if (this.replicator._addUpgradeMaybe() !== null) this._update()
    }

    const upgrade =
      lengthChanged === false || sameFork === false
        ? this.canUpgrade && sameFork
        : await this._canUpgrade(length, fork)

    if (length === this.remoteLength && fork === this.core.state.fork) {
      this.canUpgrade = upgrade
      if (upgrade) {
        this.lastUpgradableFork = fork
        this.lastUpgradableLength = length
      }
    }

    if (--this.syncsProcessing !== 0) return // ie not latest

    if (
      this.needsSync === true ||
      (this.core.state.fork === this.remoteFork && this.core.state.length > this.remoteLength)
    ) {
      this.signalUpgrade()
    }

    this._update()
  }

  _shouldUpdateCanUpgrade() {
    return (
      this.core.state.fork === this.remoteFork &&
      this.core.state.length > this.remoteLength &&
      this.canUpgrade === false &&
      this.syncsProcessing === 0
    )
  }

  async _updateCanUpgradeAndSync() {
    const { length, fork } = this.core.state

    const remoteLength = this.remoteLength
    const remoteFork = this.remoteFork
    const canUpgrade = await this._canUpgrade(this.remoteLength, this.remoteFork)

    if (
      this.syncsProcessing > 0 ||
      length !== this.core.state.length ||
      fork !== this.core.state.fork
    ) {
      return
    }
    if (remoteLength !== this.remoteLength || remoteFork !== this.remoteFork) {
      return
    }
    if (canUpgrade === this.canUpgrade) {
      return
    }

    this.canUpgrade = canUpgrade
    if (canUpgrade) {
      this.lastUpgradableLength = this.remoteLength
      this.lastUpgradableFork = this.remoteFork
    }

    this.sendSync()
  }

  // Safe to call in the background - never fails
  async _canUpgrade(remoteLength, remoteFork) {
    if (remoteFork !== this.core.state.fork) return false

    if (remoteLength === 0) return true
    if (remoteLength >= this.core.state.length) return false

    try {
      // Rely on caching to make sure this is cheap...
      const canUpgrade = await MerkleTree.upgradeable(this.core.state, remoteLength)

      if (remoteFork !== this.core.state.fork) return false

      return canUpgrade
    } catch {
      return false
    }
  }

  async _getProof(batch, msg, pushing) {
    let block = null

    if (msg.block) {
      const index = msg.block.index

      if (!pushing && (msg.fork !== this.core.state.fork || !this.core.bitfield.get(index))) {
        return new ProofRequest(msg, null, null, null)
      }

      block = batch.getBlock(index)
      block.catch(noop)
    }

    const manifest = msg.manifest && !this.core.compat ? this.core.header.manifest : null

    try {
      const proof = await MerkleTree.proof(this.core.state, batch, msg)
      return new ProofRequest(msg, proof, block, manifest)
    } catch (err) {
      batch.destroy()

      this.replicator._oninvalidrequest(err, msg, this)

      if (this.stats.invalidRequests >= MAX_INVALID_REQUESTS) throw err

      await backoff(this.stats.invalidRequests)
      return null
    }
  }

  async onrequest(msg) {
    const size = this.remoteRequests.size
    this.remoteRequests.set(msg.id, msg)

    // if size didnt change -> id overwrite -> old one is deleted, cancel current and re-add
    if (size === this.remoteRequests.size) {
      this._cancel(msg.id)
      this.remoteRequests.set(msg.id, msg)
    }

    if (!this.protomux.drained || this.receiverQueue.length) {
      this.receiverQueue.push(msg)
      return
    }

    if (this.replicator.destroyed) return

    await this._handleRequest(msg)
  }

  oncancel(msg) {
    this._cancel(msg.request)
  }

  _cancel(id) {
    this.remoteRequests.delete(id)
    this.receiverQueue.delete(id)
  }

  ondrain() {
    return this._handleRequests()
  }

  async _handleRequests() {
    if (this.receiverBusy || this.replicator.destroyed) return
    this.receiverBusy = true
    this.protomux.cork()

    while (
      this.remoteOpened &&
      this.protomux.drained &&
      this.receiverQueue.length > 0 &&
      !this.removed
    ) {
      const msg = this.receiverQueue.shift()
      await this._handleRequest(msg)
    }

    this.protomux.uncork()
    this.receiverBusy = false
  }

  async push(index) {
    if (!this.remoteAllowPush) return
    if (!this.remoteDownloading) return
    if (this.core.state.length <= index) return
    if (this.core.state.fork !== this.remoteFork) return
    if (this.remoteBitfield.get(index)) return

    const msg = {
      id: 0,
      fork: this.core.state.fork,
      block: null,
      hash: null,
      seek: null,
      upgrade: null,
      manifest: this.remoteLength === 0,
      priority: 0
    }

    await this.replicator._txLock.lock()
    try {
      const remoteLength = Math.max(this.remoteLength, this.pushedLength)

      msg.block = {
        index,
        nodes: MerkleTree.maxMissingNodes(2 * index, remoteLength)
      }

      if (index >= remoteLength) {
        msg.upgrade = {
          start: remoteLength,
          length: this.core.state.length - remoteLength
        }
      }

      let req = null
      const batch = this.core.storage.read()
      try {
        req = await this._getProof(batch, msg, true)
      } catch (err) {
        this.replicator._oninvalidrequest(err, msg, this)
        return
      }

      if (req === null) return
      batch.tryFlush()

      await this._fulfillRequest(req, true)
    } finally {
      this.replicator._txLock.unlock()
    }
  }

  async _handleRequest(msg) {
    const locked = !!msg.upgrade && this.remoteAllowPush

    if (locked) {
      // ensure contig push proofs
      await this.replicator._txLock.lock()
      const end = msg.upgrade.start + msg.upgrade.length

      if (this.pushedLength < end) {
        msg.upgrade.start = this.pushedLength
        msg.upgrade.length = end - this.pushedLength
      }
    }

    try {
      const batch = this.core.storage.read()

      // TODO: could still be answerable if (index, fork) is an ancestor of the current fork
      const req =
        msg.fork === this.core.state.fork
          ? await this._getProof(batch, msg, false)
          : new ProofRequest(msg, null, null, null)

      if (req === null) {
        this.wireNoData.send({ request: msg.id, reason: INVALID_REQUEST })
        return
      }

      batch.tryFlush()

      await this._fulfillRequest(req, false)
    } finally {
      if (locked) this.replicator._txLock.unlock()
    }
  }

  async _fulfillRequest(req, pushing) {
    if (this.core._repairMode) {
      // if cancelled do not reply
      if (this.remoteRequests.get(req.msg.id) !== req.msg) {
        return
      }

      // sync from now on, so safe to delete from the map
      this.remoteRequests.delete(req.msg.id)

      // If cutting off the fulfillment, ensure promise is caught.
      // While repairing merkle tree nodes can be `nil` so can throw.
      req.fulfill().catch(safetyCatch)
      return
    }

    const proof = await req.fulfill()

    if (!pushing) {
      // if cancelled do not reply
      if (this.remoteRequests.get(req.msg.id) !== req.msg) {
        return
      }

      // sync from now on, so safe to delete from the map
      this.remoteRequests.delete(req.msg.id)
    } else if (!this.remoteAllowPush) {
      // if pushing but remote disabled it, just drop it
      return
    }

    if (!this.isActive() && proof.block !== null) {
      return
    }

    if (proof === null) {
      if (req.msg.manifest && this.core.header.manifest) {
        const manifest = this.core.header.manifest
        this.wireData.send({
          request: req.msg.id,
          fork: this.core.state.fork,
          block: null,
          hash: null,
          seek: null,
          upgrade: null,
          manifest
        })
        incrementTx(this.stats.wireData, this.replicator.stats.wireData)
        return
      }

      this.wireNoData.send({ request: req.msg.id, reason: NOT_AVAILABLE })
      return
    }

    if (proof.block !== null) {
      this.replicator._onupload(proof.block.index, proof.block.value.byteLength, this)
    }

    if (proof.upgrade) {
      const remoteLength = MerkleTree.upgradeLength(proof.upgrade)
      if (remoteLength > this.pushedLength) this.pushedLength = remoteLength
    }

    this.wireData.send({
      request: req.msg.id,
      fork: req.msg.fork,
      block: proof.block,
      hash: proof.hash,
      seek: proof.seek,
      upgrade: proof.upgrade,
      manifest: proof.manifest
    })
    incrementTx(this.stats.wireData, this.replicator.stats.wireData)
  }

  _cancelRequest(req) {
    if (req.priority === PRIORITY.CANCELLED) return
    // mark as cancelled also and avoid re-entry
    req.priority = PRIORITY.CANCELLED

    this.inflight--
    this.replicator._requestDone(req.id, false)

    // clear inflight state
    if (isBlockRequest(req)) this.replicator._unmarkInflight(req.block.index)
    if (isUpgradeRequest(req)) this.replicator._clearInflightUpgrade(req)

    if (this.roundtripQueue === null) this.roundtripQueue = new RoundtripQueue()
    this.roundtripQueue.add(req.id)
    this.wireCancel.send({ request: req.id })
    incrementTx(this.stats.wireCancel, this.replicator.stats.wireCancel)
  }

  _checkIfConflict() {
    this.paused = true

    const length = Math.min(this.core.state.length, this.remoteLength)
    if (length === 0) return // pause and ignore

    this.wireRequest.send({
      id: 0, // TODO: use an more explicit id for this eventually...
      fork: this.remoteFork,
      block: null,
      hash: null,
      seek: null,
      upgrade: {
        start: 0,
        length
      }
    })

    incrementTx(this.stats.wireRequest, this.replicator.stats.wireRequest)
  }

  _unmarkInflightBlockRequest(req, data) {
    if (isBlockRequest(req)) this.replicator._unmarkInflight(req.block.index)
    else if (data.block && !req) this.replicator._unmarkInflight(data.block.index)
  }

  async ondata(data) {
    if (data.request !== 0 && !data.upgrade) return this._handleData(data)

    await this.replicator._rxLock.lock()
    try {
      await this._handleData(data)
    } finally {
      this.replicator._rxLock.unlock()
    }
  }

  async _handleData(data) {
    // always allow a fork conflict proof to be sent
    if (data.request === 0 && data.upgrade && data.upgrade.start === 0) {
      if (await this.core.checkConflict(data, this)) return
      this.paused = false
    }

    const req = data.request > 0 ? this.replicator._inflight.get(data.request) : null
    const reorg = data.fork > this.core.state.fork

    // no push atm, TODO: check if this satisfies another pending request
    // allow reorg pushes tho as those are not written to storage so we'll take all the help we can get
    if (req === null && reorg === false && !this.replicator.allowPush) {
      return
    }

    // Skip accepting data if in repair mode to avoid corruption
    if (this.core._repairMode) {
      this.replicator._onnodata(this, req, NOT_AVAILABLE)
      return
    }

    if (req === null && reorg === false && data.block) {
      // mark this as inflight to avoid parallel requests
      this.replicator._markInflight(data.block.index)
    }

    if (req !== null) {
      if (req.peer !== this) return
      this._onrequestroundtrip(req)
    }

    try {
      if (reorg === true) return await this.replicator._onreorgdata(this, req, data)
    } catch (err) {
      safetyCatch(err)
      this._unmarkInflightBlockRequest(req, data)

      this.paused = true
      this.replicator._oninvaliddata(err, req, data, this)
      return
    }

    this.dataProcessing++
    if (isBlockRequest(req)) this.replicator._markProcessing(req.block.index)

    try {
      if (!this.replicator._matchingRequest(req, data) || !(await this.core.verify(data, this))) {
        this.replicator._onnodata(this, req, 0)
        return
      }
    } catch (err) {
      safetyCatch(err)
      this._unmarkInflightBlockRequest(req, data)

      if (err.code === 'WRITE_FAILED') {
        // For example, we don't want to keep pulling data when storage is full
        // TODO: notify the user somehow
        this.paused = true
        return
      }

      if (this.core.closed && !isCriticalError(err)) return

      if (err.code !== 'INVALID_OPERATION') {
        // might be a fork, verify
        this._checkIfConflict()
      }

      // if push mode, we MIGHT get an occasional bad message
      // no need to mega bail for that. TODO: rate limit instead as a general thing
      if (!this.replicator.allowPush) {
        this.paused = true
      }

      this.replicator._onnodata(this, req, 0)
      this.replicator._oninvaliddata(err, req, data, this)
      return
    } finally {
      if (isBlockRequest(req)) this.replicator._markProcessed(req.block.index)
      this.dataProcessing--
    }

    this.replicator._ondata(this, req, data)

    if (this._shouldUpdateCanUpgrade() === true) {
      this._updateCanUpgradeAndSync()
    }
  }

  onnodata({ request, reason }) {
    const req = request > 0 ? this.replicator._inflight.get(request) : null

    if (req === null || req.peer !== this) {
      this.replicator.updateAll()
      return
    }

    this._onrequestroundtrip(req)
    this.replicator._onnodata(this, req, reason)
  }

  _onrequestroundtrip(req) {
    if (req.priority === PRIORITY.CANCELLED) return
    // to avoid re-entry we also just mark it as cancelled
    req.priority = PRIORITY.CANCELLED

    this.inflight--
    this.replicator._requestDone(req.id, true)
    if (this.roundtripQueue === null) return
    const flushed = this.roundtripQueue.flush(req.rt)
    if (flushed === null) return
    for (const id of flushed) this.replicator._inflight.reusable(id)
  }

  onwant(range) {
    if (!this.remoteWants.add(range)) return
    this.replicator._onwant(this, range.start, range.length, range.any)
  }

  onunwant(range) {
    this.remoteWants.remove(range)
  }

  onbitfield({ start, bitfield }) {
    if (start < this._remoteContiguousLength) this._remoteContiguousLength = start // bitfield is always the truth
    this.remoteBitfield.insert(start, bitfield)
    this.missingBlocks.insert(start, bitfield)
    this._clearLocalRange(start, bitfield.byteLength * 8)
    this._update()
  }

  _clearLocalRange(start, length) {
    const bitfield = this.core.skipBitfield === null ? this.core.bitfield : this.core.skipBitfield

    if (length === 1) {
      this.missingBlocks.set(start, this._remoteHasBlock(start) && !bitfield.get(start))
      return
    }

    const contig = Math.min(this.core.state.length, this.core.header.hints.contiguousLength)

    if (start + length < contig) {
      this.missingBlocks.setRange(start, contig, false)
      return
    }

    const rem = start & 32767
    if (rem > 0) {
      start -= rem
      length += rem
    }

    const end = start + Math.min(length, this.core.state.length)
    while (start < end) {
      const local = bitfield.getBitfield(start)

      if (local && local.bitfield) {
        this.missingBlocks.clear(start, local.bitfield)
      }

      start += 32768
    }
  }

  _resetMissingBlock(index) {
    const bitfield = this.core.skipBitfield === null ? this.core.bitfield : this.core.skipBitfield
    this.missingBlocks.set(index, this._remoteHasBlock(index) && !bitfield.get(index))
  }

  _unclearLocalRange(start, length) {
    if (length === 1) {
      this._resetMissingBlock(start)
      return
    }

    const rem = start & (RemoteBitfield.BITS_PER_SEGMENT - 1)
    if (rem > 0) {
      start -= rem
      length += rem
    }

    const fixedStart = start

    const end = start + Math.min(length, this.remoteLength)
    while (start < end) {
      const remote = this.remoteBitfield.getBitfield(start)
      if (remote && remote.bitfield) {
        this.missingBlocks.insert(start, remote.bitfield)
      }

      start += RemoteBitfield.BITS_PER_SEGMENT
    }

    this._clearLocalRange(fixedStart, length)
  }

  async onrange({ drop, start, length }) {
    const has = drop === false

    if (drop === true && start < this._remoteContiguousLength) {
      this._remoteContiguousLength = start
    }

    if (start === 0 && drop === false) {
      if (length > this._remoteContiguousLength) {
        this._remoteContiguousLength = length
        if (
          this.remoteFork === this.core.state.fork &&
          length > this.core.header.hints.remoteContiguousLength
        ) {
          this.core.updateRemoteContiguousLength(length)
        }
      }
    } else if (length === 1) {
      const bitfield = this.core.skipBitfield === null ? this.core.bitfield : this.core.skipBitfield
      this.remoteBitfield.set(start, has)
      this.missingBlocks.set(start, has && !bitfield.get(start))
    } else {
      const rangeStart = this.remoteBitfield.findFirst(!has, start)
      const rangeEnd = length + start

      if (rangeStart !== -1 && rangeStart < rangeEnd) {
        this.remoteBitfield.setRange(rangeStart, rangeEnd, has)
        this.missingBlocks.setRange(rangeStart, rangeEnd, has)
        if (has) this._clearLocalRange(rangeStart, rangeEnd - rangeStart)
      }
    }

    if (this.core.hintsChanged) await this.core.flushHints()
    if (drop === false) this._update()

    this.core.emitRemoteContiguousLength()
  }

  onreorghint() {
    // TODO
  }

  _update() {
    // TODO: if this is in a batch or similar it would be better to defer it
    // we could do that with nextTick/microtick mb? (combined with a property on the session to signal read buffer mb)
    this.replicator.updatePeer(this)
  }

  async _onconflict() {
    this.protomux.cork()
    if (this.remoteLength > 0 && this.core.state.fork === this.remoteFork) {
      await this.onrequest({
        id: 0,
        fork: this.core.state.fork,
        block: null,
        hash: null,
        seek: null,
        upgrade: {
          start: 0,
          length: Math.min(this.core.state.length, this.remoteLength)
        }
      })
    }
    this.channel.close()
    this.protomux.uncork()
  }

  _makeRequest(needsUpgrade, priority, minLength) {
    if (needsUpgrade === true && this.replicator._shouldUpgrade(this) === false) {
      return null
    }

    // ensure that the remote has signalled they have the length we request
    if (this.remoteLength < minLength) {
      return null
    }

    if (needsUpgrade === false && this.replicator._autoUpgrade(this) === true) {
      needsUpgrade = true
    }

    return {
      peer: this,
      rt: this.roundtripQueue === null ? 0 : this.roundtripQueue.tick,
      id: 0,
      fork: this.remoteFork,
      block: null,
      hash: null,
      seek: null,
      upgrade:
        needsUpgrade === false
          ? null
          : { start: this.core.state.length, length: this.remoteLength - this.core.state.length },
      // remote manifest check can be removed eventually...
      manifest: this.core.header.manifest === null && this.remoteHasManifest === true,
      priority,
      timestamp: Date.now(),
      elapsed: 0
    }
  }

  _requestManifest() {
    const req = this._makeRequest(false, 0, 0)
    if (req === null) return

    this._send(req)
  }

  _includeLastBlock() {
    if (this.replicator._alwaysLatestBlock === 0) return null

    const index = this.remoteLength - 1

    // only valid if its an OOB get
    if (index < this.core.state.length) return null

    // do the normal checks
    if (!this._remoteHasBlock(index)) return null
    if (!this._canRequest(index, false)) return null

    // atm we only ever do one upgrade request in parallel, if that changes
    // then we should add some check here for inflights to avoid over requesting
    const b = this.replicator._blocks.add(index, PRIORITY.NORMAL, false)
    return b
  }

  _requestUpgrade(u) {
    if (this.replicator.pushOnly) return false

    const req = this._makeRequest(true, 0, 0)
    if (req === null) return false

    const b = this._includeLastBlock()

    if (b) this._sendBlockRequest(req, b)
    else this._send(req)

    return true
  }

  _requestSeek(s) {
    // if replicator is updating the seeks etc, bail and wait for it to drain
    if (this.replicator._updatesPending > 0) return false
    if (this.replicator.pushOnly) return false

    const { length, fork } = this.core.state

    if (fork !== this.remoteFork) return false

    if (s.seeker.start >= length) {
      const req = this._makeRequest(true, 0, 0)

      // We need an upgrade for the seek, if non can be provided, skip
      if (req === null) return false

      req.seek = this.remoteSupportsSeeks
        ? { bytes: s.seeker.bytes, padding: s.seeker.padding }
        : null

      s.inflight.push(req)
      this._send(req)

      return true
    }

    const len = s.seeker.end - s.seeker.start
    const off = s.seeker.start + Math.floor(Math.random() * len)

    for (let i = 0; i < len; i++) {
      let index = off + i
      if (index > s.seeker.end) index -= len

      if (this._remoteHasBlock(index) === false) continue
      if (this.core.bitfield.get(index) === true) continue
      if (!this._canRequest(index, false)) continue

      // Check if this block is currently inflight - if so pick another
      const b = this.replicator._blocks.get(index)
      if (b !== null && b.inflight.length > 0) continue

      // Block is not inflight, but we only want the hash, check if that is inflight
      const h = this.replicator._hashes.add(index, PRIORITY.NORMAL, false)
      if (h.inflight.length > 0) continue

      const req = this._makeRequest(false, h.priority, index + 1)
      if (req === null) continue

      const nodes = flatTree.depth(s.seeker.start + s.seeker.end - 1)

      req.hash = { index: 2 * index, nodes }
      req.seek = this.remoteSupportsSeeks
        ? { bytes: s.seeker.bytes, padding: s.seeker.padding }
        : null

      s.inflight.push(req)
      h.inflight.push(req)
      this._send(req)

      return true
    }

    this._maybeWantAnyRange(s.seeker.start, len, s)
    return false
  }

  _canRequest(index, force) {
    if (!(index >= 0)) throw ASSERTION('bad index to _canRequest: ' + index)

    if (!force && this.replicator.pushOnly) {
      return false
    }

    if (this.remoteLength >= this.core.state.length) {
      return true
    }

    if (index < this.lastUpgradableLength && this.lastUpgradableFork === this.core.state.fork) {
      return true
    }

    if (this.canUpgrade && this.syncsProcessing === 0) {
      return true
    }

    return false
  }

  _remoteHasBlock(index) {
    return index < this._remoteContiguousLength || this.remoteBitfield.get(index) === true
  }

  _sendBlockRequest(req, b) {
    if (this.core._repairMode) return

    req.block = { index: b.index, nodes: 0 }
    this.replicator._markInflight(b.index)

    b.inflight.push(req)
    this.replicator.hotswaps.add(b)
    this._send(req)
  }

  _requestBlock(b) {
    const { length, fork } = this.core.state

    if (this._remoteHasBlock(b.index) === false || fork !== this.remoteFork) {
      if (!this.core.bitfield.get(b.index)) this._maybeWant(b.index, b)
      return false
    }

    if (!this._canRequest(b.index, b.force)) return false

    const req = this._makeRequest(b.index >= length, b.priority, b.index + 1)
    if (req === null) return false

    this._sendBlockRequest(req, b)

    return true
  }

  _maybeWant(index, handle) {
    if (index < this.remoteContiguousLength) return

    const res = this.wants.add(index, handle)
    if (!res) return

    const batch = res.want && res.unwant
    if (batch) this.protomux.cork()

    if (res.unwant) {
      this.wireUnwant.send(res.unwant)
      incrementTx(this.stats.wireUnwant, this.replicator.stats.wireUnwant)
    }
    if (res.want) {
      this.wireWant.send(res.want)
      incrementTx(this.stats.wireWant, this.replicator.stats.wireWant)
    }

    if (batch) this.protomux.uncork()
  }

  _maybeWantAnyRange(start, length, handle) {
    if (handle.wants) {
      for (const w of handle.wants) {
        if ((w.start !== start || w.length !== length) && w.any) {
          const req = this.wants.removeAnyRange(w.start, w.length, handle)
          if (req) this.wireUnwant.send(req)
        }
      }
    }

    if (start + length <= this.remoteContiguousLength) return

    const req = this.wants.addAnyRange(start, length, handle)
    if (req) this.wireWant.send(req)
  }

  _requestRangeBlock(index, length) {
    if (this.core.bitfield.get(index) === true || !this._canRequest(index, false)) return false

    const b = this.replicator._blocks.add(index, PRIORITY.NORMAL, false)
    if (b.inflight.length > 0) {
      this.missingBlocks.set(index, false) // in case we missed some states just set them ondemand, nbd
      return false
    }

    const req = this._makeRequest(index >= length, b.priority, index + 1)

    // If the request cannot be satisfied, dealloc the block request if no one is subscribed to it
    if (req === null) {
      b.gc()
      return false
    }

    this._sendBlockRequest(req, b)

    // Don't think this will ever happen, as the pending queue is drained before the range queue
    // but doesn't hurt to check this explicitly here also.
    if (b.queued) b.queued = false
    return true
  }

  _findNext(i) {
    if (i < this._remoteContiguousLength) {
      if (this.core.skipBitfield === null) this.replicator._openSkipBitfield()
      i = this.core.skipBitfield.findFirst(false, i)
      if (i < this._remoteContiguousLength && i > -1) return i
      i = this._remoteContiguousLength
    }

    return this.missingBlocks.findFirst(true, i)
  }

  _addRangeBatch(r, offset, end) {
    const { WANT_BATCH } = w
    while (offset < end) {
      const next = this.core.bitfield.findFirst(false, offset)
      if (next === -1 || next >= end) return false

      const b = (next - (next & (WANT_BATCH - 1))) / WANT_BATCH

      if (r.addBatch(b)) return true

      offset = (b + 1) * WANT_BATCH
    }

    return false
  }

  _populateRangeBatches(r) {
    const { WANT_BATCH } = w
    for (let i = r.batches.length - 1; i >= 0; i--) {
      const b = r.batches[i]
      const minStart = b.batch * WANT_BATCH
      const maxEnd = minStart + WANT_BATCH

      const start = Math.max(r.start, minStart)
      const end = Math.min(r.end === -1 ? maxEnd : r.end, maxEnd)

      if (start < end && this.core.bitfield.hasUnset(start, end - start)) continue

      r.removeBatch(b)
    }

    while (r.batches.length < 3) {
      const end = r.end === -1 ? this.core.state.length : r.end
      if (end <= r.start) return

      const len = end - r.start
      const off = r.start + (r.linear ? 0 : Math.floor(Math.random() * len))

      if (!this._addRangeBatch(r, off, end) && !this._addRangeBatch(r, r.start, end)) break
    }
  }

  _requestRangeBatch(start, end, length) {
    let tries = this.inflight

    do {
      start = this._findNext(start)
      if (start === -1 || start >= end) break

      if (this._requestRangeBlock(start, length)) return true
      start++
    } while (tries-- > 0)

    return false
  }

  _getValidEnd(maxEnd) {
    // if we can upgrade the remote, or the remote is ahead, then all the remotes blocks are valid
    // otherwise truncate to the last length the remote has acked for us
    const maxLocalLength =
      this.canUpgrade || this.remoteLength >= this.core.state.length
        ? this.core.state.length
        : this.core.state.fork === this.lastUpgradableFork
          ? Math.min(this.lastUpgradableLength, this.core.state.length)
          : 0

    return Math.min(
      maxLocalLength,
      Math.min(maxEnd === -1 ? this.remoteLength : maxEnd, this.remoteLength)
    )
  }

  _requestRange(r) {
    const { WANT_BATCH } = w
    if (this.syncsProcessing > 0) return false

    const { length, fork } = this.core.state

    if (r.blocks) {
      for (let i = r.start; i < r.end; i++) {
        const index = r.blocks[i]
        const has = index < this._remoteContiguousLength || this.missingBlocks.get(index) === true
        if (has === true && this._requestRangeBlock(index, length)) return true
        this._maybeWant(index, r)
      }

      return false
    }

    this._populateRangeBatches(r)

    const end = this._getValidEnd(r.end)

    if (end <= r.start || fork !== this.remoteFork) return false

    for (let i = 0; i < r.batches.length; i++) {
      const b = r.batches[i]

      const batchStart = Math.max(b.batch * WANT_BATCH, r.start)
      const batchEnd = Math.min((b.batch + 1) * WANT_BATCH, end)
      const len = batchEnd - batchStart
      const off = batchStart + (r.linear ? 0 : Math.floor(Math.random() * len))

      if (
        this._requestRangeBatch(off, end, length) ||
        this._requestRangeBatch(batchStart, off, length)
      ) {
        return true
      }

      this._maybeWant(batchStart, b)
    }

    // Here we should consider making an OOB request (ie if the remote says they have a newer block)
    // but the upgrade code already does that, so no big deal for now

    return false
  }

  _requestForkProof(f) {
    if (!this.remoteLength) return
    if (this.replicator.pushOnly) return

    const req = this._makeRequest(false, 0, 0)
    if (req === null) return

    req.upgrade = { start: 0, length: this.remoteLength }
    req.manifest = !this.core.header.manifest

    f.inflight.push(req)
    this._send(req)
  }

  _requestForkRange(f) {
    if (f.fork !== this.remoteFork || f.batch.want === null) return false
    if (this.replicator.pushOnly) return false

    const end = Math.min(f.batch.want.end, this.remoteLength)
    if (end < f.batch.want.start) return false

    const len = end - f.batch.want.start
    const off = f.batch.want.start + Math.floor(Math.random() * len)

    for (let i = 0; i < len; i++) {
      let index = off + i
      if (index >= end) index -= len

      if (this._remoteHasBlock(index) === false) continue

      const req = this._makeRequest(false, 0, 0)
      if (req === null) return false

      req.hash = { index: 2 * index, nodes: f.batch.want.nodes }

      f.inflight.push(req)
      this._send(req)

      return true
    }

    this._maybeWantAnyRange(f.batch.want.start, len, f)
    return false
  }

  isActive() {
    if (this.paused || this.removed || this.core.header.frozen) return false
    return true
  }

  async _send(req) {
    const fork = this.core.state.fork

    this.inflight++
    this.replicator._inflight.add(req)

    if (req.upgrade !== null && req.fork === fork) {
      const u = this.replicator._addUpgrade()
      u.inflight.push(req)
    }

    try {
      if (req.block !== null && req.fork === fork) {
        req.block.nodes = await MerkleTree.missingNodes(
          this.core.state,
          2 * req.block.index,
          this.core.state.length
        )
        if (req.priority === PRIORITY.CANCELLED) return
      }
      if (req.hash !== null && req.fork === fork && req.hash.nodes === 0) {
        req.hash.nodes = await MerkleTree.missingNodes(
          this.core.state,
          req.hash.index,
          this.core.state.length
        )
        if (req.priority === PRIORITY.CANCELLED) return

        // nodes === 0, we already have it, bail
        if (req.hash.nodes === 0 && (req.hash.index & 1) === 0) {
          this.inflight--
          this.replicator._resolveHashLocally(this, req)
          return
        }
      }
    } catch (err) {
      this.stream.destroy(err)
      return
    }

    this.wireRequest.send(req)
    incrementTx(this.stats.wireRequest, this.replicator.stats.wireRequest)
  }
}

module.exports = class Replicator {
  static Peer = Peer // hack to be able to access Peer from outside this module

  constructor(
    core,
    {
      notDownloadingLinger = NOT_DOWNLOADING_SLACK,
      eagerUpgrade = true,
      allowFork = true,
      allowPush = false,
      alwaysLatestBlock = false,
      inflightRange = null
    } = {}
  ) {
    this.core = core
    this.eagerUpgrade = eagerUpgrade
    this.allowFork = allowFork
    this.allowPush = allowPush
    this.ondownloading = null // optional external hook for monitoring downloading status
    this.peers = []
    this.findingPeers = 0 // updatable from the outside
    this.destroyed = false
    this.downloading = false
    this.pushOnly = false
    this.activeSessions = 0

    this.hotswaps = new HotswapQueue()
    this.inflightRange = inflightRange || DEFAULT_MAX_INFLIGHT

    // Note: nodata and unwant not currently tracked
    // tx = transmitted, rx = received
    this.stats = {
      wireSync: { tx: 0, rx: 0 },
      wireRequest: { tx: 0, rx: 0 },
      wireCancel: { tx: 0, rx: 0 },
      wireData: { tx: 0, rx: 0 },
      wireWant: { tx: 0, rx: 0 },
      wireUnwant: { tx: 0, rx: 0 },
      wireBitfield: { tx: 0, rx: 0 },
      wireRange: { tx: 0, rx: 0 },
      wireExtension: { tx: 0, rx: 0 },
      hotswaps: 0,
      invalidData: 0,
      invalidRequests: 0,
      backoffs: 0,
      notAvailableBackoffs: 0
    }

    this._attached = new Set()
    this._inflight = new InflightTracker()
    this._blocks = new BlockTracker(this)
    this._hashes = new BlockTracker(this)

    this._alwaysLatestBlock = alwaysLatestBlock ? 1 : 0
    this._queued = []

    this._seeks = []
    this._upgrade = null
    this._reorgs = []
    this._ranges = []

    this._rxLock = new Mutex()
    this._txLock = new Mutex()

    this._hadPeers = false
    this._active = 0
    this._ifAvailable = 0
    this._updatesPending = 0
    this._applyingReorg = null
    this._manifestPeer = null
    this._notDownloadingLinger = notDownloadingLinger
    this._notDownloadingTimer = null

    const self = this
    this._onstreamclose = onstreamclose

    function onstreamclose() {
      self.detachFrom(this.userData)
    }
  }

  setInflightRange(min, max) {
    const def = this.inflightRange
    this.inflightRange = [min, max]
    for (const peer of this.peers) {
      if (peer.inflightRange !== def) continue
      peer.inflightRange = this.inflightRange
    }
  }

  updateActivity(inc, session) {
    this.activeSessions += inc
    this.setDownloading(this.activeSessions !== 0, session)
  }

  isDownloading() {
    return this.downloading || !this._inflight.idle
  }

  async push(index) {
    const all = []
    for (const peer of this.peers) {
      all.push(peer.push(index))
    }
    await Promise.all(all)
  }

  setAllowPush(allowPush) {
    if (allowPush === this.allowPush) return
    this.allowPush = allowPush
    for (const peer of this.peers) peer.sendSync()
  }

  isAllowingPush() {
    if (!this.allowPush) return false
    if (this._notDownloadingTimer) return false
    return this.downloading
  }

  setPushOnly(pushOnly) {
    if (pushOnly === this.pushOnly) return
    this.pushOnly = pushOnly
  }

  setDownloading(downloading) {
    const allowPush = this.isAllowingPush()
    const linger = this._notDownloadingLinger

    if (this._notDownloadingTimer) {
      clearTimeout(this._notDownloadingTimer)
      this._notDownloadingTimer = null
    }

    if (this.destroyed) return

    if (downloading || linger === 0) {
      if (!this._setDownloadingNow(downloading)) this.signalAllowPush(allowPush)
      return
    }

    this._notDownloadingTimer = setTimeout(setNotDownloadingLater, linger, this)
    if (this._notDownloadingTimer.unref) this._notDownloadingTimer.unref()
    this.signalAllowPush(allowPush)
  }

  signalAllowPush(allowPush) {
    if (allowPush === this.isAllowingPush()) return
    for (const peer of this.peers) peer.signalUpgrade()
  }

  _setDownloadingNow(downloading) {
    this._notDownloadingTimer = null

    if (this.downloading === downloading) return false
    this.downloading = downloading

    if (!downloading && this.isDownloading()) return false

    for (const peer of this.peers) peer.signalUpgrade()

    if (downloading) {
      // restart channel if needed...
      for (const protomux of this._attached) {
        if (!protomux.stream.handshakeHash) continue
        if (protomux.opened({ protocol: 'hypercore/alpha', id: this.core.discoveryKey })) continue
        this._makePeer(protomux, true)
      }
    } else {
      for (const peer of this.peers) peer.closeIfIdle()
    }

    if (this.ondownloading !== null && downloading) this.ondownloading()
    return true
  }

  cork() {
    for (const peer of this.peers) peer.protomux.cork()
  }

  uncork() {
    for (const peer of this.peers) peer.protomux.uncork()
  }

  // Called externally when a range of new blocks has been processed/removed
  onhave(start, length, drop = false) {
    for (const peer of this.peers) peer.broadcastRange(start, length, drop)
  }

  // Called externally when a truncation upgrade has been processed
  ontruncate(newLength, truncated) {
    const notify = []

    for (const blk of this._blocks) {
      if (blk.index < newLength) continue
      notify.push(blk)
    }

    for (const blk of notify) {
      for (const r of blk.refs) {
        if (r.snapshot === false) continue
        blk.detach(r, SNAPSHOT_NOT_AVAILABLE())
      }
    }

    for (const peer of this.peers) {
      peer.fullyDownloadedSignaled = Math.min(newLength, peer.fullyDownloadedSignaled)
      peer._unclearLocalRange(newLength, truncated)
    }
  }

  // Called externally when a upgrade has been processed
  onupgrade() {
    for (const peer of this.peers) peer.signalUpgrade()
    if (this._blocks.isEmpty() === false) this._resolveBlocksLocally()
    if (this._upgrade !== null) this._resolveUpgradeRequest(null)
    if (!this._blocks.isEmpty() || this._ranges.length !== 0 || this._seeks.length !== 0) {
      this._updateNonPrimary(true)
    }
  }

  // Called externally when a conflict has been detected and verified
  async onconflict() {
    const all = []
    for (const peer of this.peers) {
      all.push(peer._onconflict())
    }
    await Promise.allSettled(all)
  }

  async applyPendingReorg() {
    if (this._applyingReorg !== null) {
      await this._applyingReorg
      return true
    }

    for (let i = this._reorgs.length - 1; i >= 0; i--) {
      const f = this._reorgs[i]
      if (f.batch !== null && f.batch.finished) {
        await this._applyReorg(f)
        return true
      }
    }

    return false
  }

  addUpgrade(session) {
    if (this._upgrade !== null) {
      const ref = this._upgrade.attach(session)
      this._checkUpgradeIfAvailable()
      return ref
    }

    const ref = this._addUpgrade().attach(session)

    this.updateAll()

    return ref
  }

  addBlock(session, index, force) {
    const b = this._blocks.add(index, PRIORITY.HIGH, force)
    const ref = b.attach(session)

    this._queueBlock(b)
    this.updateAll()

    return ref
  }

  addSeek(session, seeker) {
    const s = new SeekRequest(this, this._seeks, seeker)
    const ref = s.attach(session)

    this._seeks.push(s)
    this.updateAll()

    return ref
  }

  addRange(
    session,
    {
      start = 0,
      end = -1,
      length = toLength(start, end),
      blocks = null,
      linear = false,
      ifAvailable = false
    } = {}
  ) {
    if (blocks !== null) {
      // if using blocks, start, end just acts as frames around the blocks array
      start = 0
      end = length = blocks.length
    }

    const r = new RangeRequest(
      this,
      this._ranges,
      start,
      length === -1 ? -1 : start + length,
      linear,
      ifAvailable,
      blocks
    )

    const ref = r.attach(session)

    // Trigger this to see if this is already resolved...
    // Also auto compresses the range based on local bitfield
    clampRange(this.core, r)

    if (r.end !== -1 && r.start >= r.end) {
      this._resolveRangeRequest(r)
      return ref
    }

    this.updateAll()

    return ref
  }

  cancel(ref) {
    ref.context.detach(ref, null)
  }

  static clearRequests(session, err) {
    if (session.length === 0) return

    const updated = new Set()

    while (session.length > 0) {
      const ref = session[session.length - 1]
      updated.add(ref.context.replicator)
      ref.context.detach(ref, err)
    }

    for (const replicator of updated) {
      replicator.updateAll()
    }
  }

  clearRequests(session, err = null) {
    let cleared = false
    while (session.length > 0) {
      const ref = session[session.length - 1]
      ref.context.detach(ref, err)
      cleared = true
    }

    if (cleared) this.updateAll()
  }

  _matchingRequest(req, data) {
    if (this.allowPush) {
      return true
    }
    if (data.block !== null && (req.block === null || req.block.index !== data.block.index)) {
      return false
    }
    if (data.hash !== null && (req.hash === null || req.hash.index !== data.hash.index)) {
      return false
    }
    if (data.seek !== null && (req.seek === null || req.seek.bytes !== data.seek.bytes)) {
      return false
    }
    if (data.upgrade !== null && req.upgrade === null) {
      return false
    }
    return req.fork === data.fork
  }

  _addUpgradeMaybe() {
    return this.eagerUpgrade === true ? this._addUpgrade() : this._upgrade
  }

  // TODO: this function is OVER called atm, at each updatePeer/updateAll
  // instead its more efficient to only call it when the conditions in here change - ie on sync/add/remove peer
  // Do this when we have more tests.
  _checkUpgradeIfAvailable() {
    if (this._ifAvailable > 0 && this.peers.length < MAX_PEERS_UPGRADE) return
    if (this._upgrade === null || this._upgrade.refs.length === 0) return
    if (this._hadPeers === false && this.findingPeers > 0) return

    const maxPeers = Math.min(this.peers.length, MAX_PEERS_UPGRADE)

    // check if a peer can upgrade us

    for (let i = 0; i < maxPeers; i++) {
      const peer = this.peers[i]

      if (peer.remoteSynced === false) return

      if (this.core.state.length === 0 && peer.remoteLength > 0) return

      if (peer.remoteLength <= this._upgrade.length || peer.remoteFork !== this._upgrade.fork) {
        continue
      }

      if (peer.syncsProcessing > 0) return

      if (peer.lengthAcked !== this.core.state.length && peer.remoteFork === this.core.state.fork) {
        return
      }

      if (peer.remoteCanUpgrade === true) return
    }

    // check if reorgs in progress...

    if (this._applyingReorg !== null) return

    // TODO: we prob should NOT wait for inflight reorgs here, seems better to just resolve the upgrade
    // and then apply the reorg on the next call in case it's slow - needs some testing in practice

    for (let i = 0; i < this._reorgs.length; i++) {
      const r = this._reorgs[i]
      if (r.inflight.length > 0) return
    }

    // if something is inflight, wait for that first
    if (this._upgrade.inflight.length > 0) return

    // nothing to do, indicate no update avail

    const u = this._upgrade
    this._upgrade = null
    u.resolve(false)
  }

  _addUpgrade() {
    if (this._upgrade !== null) return this._upgrade

    // TODO: needs a reorg: true/false flag to indicate if the user requested a reorg
    this._upgrade = new UpgradeRequest(this, this.core.state.fork, this.core.state.length)

    return this._upgrade
  }

  _addReorg(fork, peer) {
    if (this.allowFork === false) return null

    // TODO: eager gc old reorgs from the same peer
    // not super important because they'll get gc'ed when the request finishes
    // but just spam the remote can do ...

    for (const f of this._reorgs) {
      if (f.fork > fork && f.batch !== null) return null
      if (f.fork === fork) return f
    }

    const f = new ForkRequest(this, fork)

    this._reorgs.push(f)

    // maintain sorted by fork
    let i = this._reorgs.length - 1
    while (i > 0 && this._reorgs[i - 1].fork > fork) {
      this._reorgs[i] = this._reorgs[i - 1]
      this._reorgs[--i] = f
    }

    return f
  }

  _shouldUpgrade(peer) {
    if (this._upgrade !== null && this._upgrade.inflight.length > 0) return false
    return (
      peer.remoteCanUpgrade === true &&
      peer.remoteLength > this.core.state.length &&
      peer.lengthAcked === this.core.state.length
    )
  }

  _autoUpgrade(peer) {
    return (
      this._upgrade !== null &&
      peer.remoteFork === this.core.state.fork &&
      this._shouldUpgrade(peer)
    )
  }

  _addPeer(peer) {
    this._hadPeers = true
    this.peers.push(peer)
    this.updatePeer(peer)
    this._onpeerupdate(true, peer)
  }

  _requestDone(id, roundtrip) {
    this._inflight.remove(id, roundtrip)
    if (this.isDownloading() === true) return
    for (const peer of this.peers) peer.signalUpgrade()
  }

  _removePeer(peer) {
    this.peers.splice(this.peers.indexOf(peer), 1)
    peer.wants.destroy()

    if (this._manifestPeer === peer) this._manifestPeer = null

    for (const req of this._inflight) {
      if (req.peer !== peer) continue
      this._inflight.remove(req.id, true)
      this._clearRequest(peer, req)
    }

    this._onpeerupdate(false, peer)
    this.updateAll()
  }

  _queueBlock(b) {
    if (b.inflight.length > 0 || b.queued === true) return
    b.queued = true
    this._queued.push(b)
  }

  _resolveHashLocally(peer, req) {
    this._requestDone(req.id, false)
    this._resolveBlockRequest(this._hashes, req.hash.index / 2, null, req)
    this.updatePeer(peer)
  }

  // Runs in the background - not allowed to throw
  async _resolveBlocksLocally() {
    // TODO: check if fork compat etc. Requires that we pass down truncation info

    const clear = []
    const blocks = []

    const reader = this.core.storage.read()
    for (const b of this._blocks) {
      if (this.core.bitfield.get(b.index) === false) continue
      blocks.push(this._resolveLocalBlock(b, reader, clear))
    }
    reader.tryFlush()

    await Promise.all(blocks)

    if (!clear.length) return

    // Currently the block tracker does not support deletes during iteration, so we make
    // sure to clear them afterwards.
    for (const b of clear) {
      this._blocks.remove(b.index)
      removeHotswap(b)
    }
  }

  async _resolveLocalBlock(b, reader, resolved) {
    try {
      b.resolve(await reader.getBlock(b.index))
    } catch (err) {
      b.reject(err)
      return
    }

    resolved.push(b)
  }

  _resolveBlockRequest(tracker, index, value, req) {
    const b = tracker.remove(index)
    if (b === null) return false

    removeInflight(b.inflight, req)
    removeHotswap(b)
    b.queued = false

    b.resolve(value)

    if (b.inflight.length > 0) {
      // if anything is still inflight, cancel it
      for (let i = b.inflight.length - 1; i >= 0; i--) {
        const req = b.inflight[i]
        req.peer._cancelRequest(req)
      }
    }

    return true
  }

  _resolveUpgradeRequest(req) {
    if (req !== null) removeInflight(this._upgrade.inflight, req)

    if (
      this.core.state.length === this._upgrade.length &&
      this.core.state.fork === this._upgrade.fork
    ) {
      return false
    }

    const u = this._upgrade
    this._upgrade = null
    u.resolve(true)

    return true
  }

  _resolveRangeRequest(req) {
    req.resolve(true)
    req.gc()
  }

  _clearInflightBlock(tracker, req) {
    const isBlock = tracker === this._blocks
    const index = isBlock === true ? req.block.index : req.hash.index / 2
    const b = tracker.get(index)

    if (b === null || removeInflight(b.inflight, req) === false) return

    if (removeHotswap(b) === true && b.inflight.length > 0) {
      this.hotswaps.add(b)
    }

    if (b.refs.length > 0 && isBlock === true) {
      this._queueBlock(b)
      return
    }

    b.gc()
  }

  _clearInflightUpgrade(req) {
    if (this._upgrade === null || removeInflight(this._upgrade.inflight, req) === false) return
    this._upgrade.gc()
  }

  _clearInflightSeeks(req) {
    for (const s of this._seeks) {
      if (removeInflight(s.inflight, req) === false) continue
      s.gc()
    }
  }

  _clearInflightReorgs(req) {
    for (const r of this._reorgs) {
      removeInflight(r.inflight, req)
    }
  }

  _clearOldReorgs(fork) {
    for (let i = 0; i < this._reorgs.length; i++) {
      const f = this._reorgs[i]
      if (f.fork >= fork) continue
      if (i === this._reorgs.length - 1) this._reorgs.pop()
      else this._reorgs[i] = this._reorgs.pop()
      i--
    }
  }

  // "slow" updates here - async but not allowed to ever throw
  async _updateNonPrimary(updateAll) {
    // Check if running, if so skip it and the running one will issue another update for us (debounce)
    while (++this._updatesPending === 1) {
      let len = Math.min(MAX_RANGES, this._ranges.length)

      for (let i = 0; i < len; i++) {
        const r = this._ranges[i]

        clampRange(this.core, r)

        if (r.end !== -1 && r.start >= r.end) {
          this._resolveRangeRequest(r)
          i--
          if (len > this._ranges.length) len--
          if (this._ranges.length === MAX_RANGES) updateAll = true
        }
      }

      for (let i = 0; i < this._seeks.length; i++) {
        const s = this._seeks[i]

        let err = null
        let res = null

        try {
          res = await s.seeker.update()
        } catch (error) {
          err = error
        }

        if (!res && !err) continue

        if (i < this._seeks.length - 1) this._seeks[i] = this._seeks.pop()
        else this._seeks.pop()

        i--

        if (err) s.reject(err)
        else s.resolve(res)
      }

      // No additional updates scheduled - break
      if (--this._updatesPending === 0) break
      // Debounce the additional updates - continue
      this._updatesPending = 0
    }

    if (this._inflight.idle || updateAll) this.updateAll()
  }

  _maybeResolveIfAvailableRanges() {
    if (this._ifAvailable > 0 || !this._inflight.idle || !this._ranges.length) return

    for (let i = 0; i < this.peers.length; i++) {
      if (this.peers[i].dataProcessing > 0) return
    }

    for (let i = 0; i < this._ranges.length; i++) {
      const r = this._ranges[i]

      if (r.ifAvailable) {
        this._resolveRangeRequest(r)
        i--
      }
    }
  }

  _clearRequest(peer, req) {
    if (req.block !== null) {
      this._clearInflightBlock(this._blocks, req)
      this._unmarkInflight(req.block.index)
    }

    if (req.hash !== null) {
      this._clearInflightBlock(this._hashes, req)
    }

    if (req.upgrade !== null && this._upgrade !== null) {
      this._clearInflightUpgrade(req)
    }

    if (this._seeks.length > 0) {
      this._clearInflightSeeks(req)
    }

    if (this._reorgs.length > 0) {
      this._clearInflightReorgs(req)
    }
  }

  _onnodata(peer, req, reason) {
    if (reason === NOT_AVAILABLE) {
      peer.stats.notAvailableBackoffs++
      this.stats.notAvailableBackoffs++

      if (peer.stats.notAvailableBackoffs >= MAX_BACKOFFS) {
        peer.paused = true
      }
    }

    if (reason === INVALID_REQUEST) {
      peer.stats.backoffs++
      this.stats.backoffs++

      if (peer.stats.backoffs >= MAX_BACKOFFS) {
        peer.paused = true
      }
    }

    if (req) {
      this._clearRequest(peer, req)
    }

    this.updateAll()
  }

  _openSkipBitfield() {
    // technically the skip bitfield gets bits cleared if .clear() is called
    // also which might be in inflight also, but that just results in that section being overcalled shortly
    // worst case, so ok for now

    const bitfield = this.core.openSkipBitfield()

    for (const req of this._inflight) {
      if (req.block) bitfield.set(req.block.index, true) // skip
    }
  }

  _markProcessing(index) {
    const b = this._blocks.get(index)
    if (b) {
      b.processing = true
      return
    }

    const h = this._hashes.get(index)
    if (h) h.processing = true
  }

  _markProcessed(index) {
    const b = this._blocks.get(index)
    if (b) return b.processed()

    const h = this._hashes.get(index)
    if (h) h.processed()
  }

  _markInflight(index) {
    if (this.core.skipBitfield !== null) this.core.skipBitfield.set(index, true)
    for (const peer of this.peers) peer._markInflight(index)
  }

  _unmarkInflight(index) {
    if (this.core.skipBitfield !== null) {
      this.core.skipBitfield.set(index, this.core.bitfield.get(index))
    }
    for (const peer of this.peers) peer._resetMissingBlock(index)
  }

  _ondata(peer, req, data) {
    if (req) {
      req.elapsed = Date.now() - req.timestamp
    }

    if (data.block !== null) {
      this._resolveBlockRequest(this._blocks, data.block.index, data.block.value, req)
      this._ondownload(data.block.index, data.block.value.byteLength, peer, req)
    }

    if (data.hash !== null && (data.hash.index & 1) === 0) {
      this._resolveBlockRequest(this._hashes, data.hash.index / 2, null, req)
    }

    if (this._upgrade !== null) {
      this._resolveUpgradeRequest(req)
    }

    if (this._seeks.length > 0) {
      this._clearInflightSeeks(req)
    }

    if (this._reorgs.length > 0) {
      this._clearInflightReorgs(req)
    }

    if (this._manifestPeer === peer && this.core.header.manifest !== null) {
      this._manifestPeer = null
    }

    if (this._seeks.length > 0 || this._ranges.length > 0) {
      this._updateNonPrimary(this._seeks.length > 0)
    }

    this.updatePeer(peer)
  }

  _onwant(peer, start, length, any) {
    if (!peer.isActive()) return

    const contig = Math.min(this.core.state.length, this.core.header.hints.contiguousLength)

    if (start + length < contig || this.core.state.length === contig || (any && start < contig)) {
      peer.wireRange.send({
        drop: false,
        start: 0,
        length: contig
      })
      incrementTx(peer.stats.wireRange, this.stats.wireRange)
      return
    }

    length = Math.min(length, this.core.state.length - start)

    if (any) {
      const bit = this.core.bitfield.firstSet(start)
      if (bit > -1 && bit < start + length) {
        peer.wireRange.send({
          drop: false,
          start: bit,
          length: 1
        })
      }
      return
    }

    for (const msg of this.core.bitfield.want(start, length)) {
      peer.wireBitfield.send(msg)
      incrementTx(peer.stats.wireBitfield, this.stats.wireBitfield)
    }
  }

  async _onreorgdata(peer, req, data) {
    const newBatch = data.upgrade && (await this.core.verifyReorg(data))
    const f = this._addReorg(data.fork, peer)

    if (f === null) {
      this.updateAll()
      return
    }

    removeInflight(f.inflight, req)

    if (f.batch) {
      await f.batch.update(data)
    } else if (data.upgrade) {
      f.batch = newBatch

      // Remove "older" reorgs in progress as we just verified this one.
      this._clearOldReorgs(f.fork)
    }

    if (f.batch && f.batch.finished) {
      if (this._addUpgradeMaybe() !== null) {
        await this._applyReorg(f)
      }
    }

    this.updateAll()
  }

  // Never throws, allowed to run in the background
  async _applyReorg(f) {
    // TODO: more optimal here to check if potentially a better reorg
    // is available, ie higher fork, and request that one first.
    // This will request that one after this finishes, which is fine, but we
    // should investigate the complexity in going the other way

    const u = this._upgrade
    const old = this._reorgs

    this._reorgs = [] // clear all as the nodes are against the old tree - easier
    this._applyingReorg = this.core.reorg(f.batch, null) // TODO: null should be the first/last peer?

    try {
      await this._applyingReorg
    } catch (err) {
      this._upgrade = null
      u.reject(err)
    }

    this._applyingReorg = null

    if (this._upgrade !== null) {
      this._resolveUpgradeRequest(null)
    }

    for (const peer of this.peers) this._updateFork(peer)

    // TODO: all the remaining is a tmp workaround until we have a flag/way for ANY_FORK
    for (const r of this._ranges) {
      r.start = r.userStart
      r.end = r.userEnd
    }

    for (const f of old) f.resolve()
    f.resolve()

    this.updateAll()
  }

  _maybeUpdate() {
    return this._upgrade !== null && this._upgrade.inflight.length === 0
  }

  _maybeRequestManifest() {
    return this.core.header.manifest === null && this._manifestPeer === null
  }

  _updateFork(peer) {
    if (
      this._applyingReorg !== null ||
      this.allowFork === false ||
      peer.remoteFork <= this.core.state.fork
    ) {
      return false
    }

    const f = this._addReorg(peer.remoteFork, peer)

    // TODO: one per peer is better
    if (f !== null && f.batch === null && f.inflight.length === 0) {
      return peer._requestForkProof(f)
    }

    return false
  }

  _updateHotswap(peer) {
    const maxHotswaps = peer.getMaxHotswapInflight()
    if (!peer.isActive() || peer.inflight >= maxHotswaps) return

    for (const b of this.hotswaps.pick(peer)) {
      if (peer._requestBlock(b) === false) continue
      peer.stats.hotswaps++
      peer.replicator.stats.hotswaps++
      if (peer.inflight >= maxHotswaps) break
    }
  }

  _updatePeer(peer) {
    if (!peer.isActive() || peer.inflight >= peer.getMaxInflight() || !peer.remoteUploading) {
      return false
    }

    // Eagerly request the manifest even if the remote length is 0. If not 0 we'll get as part of the upgrade request...
    if (
      this._maybeRequestManifest() === true &&
      peer.remoteLength === 0 &&
      peer.remoteHasManifest === true
    ) {
      this._manifestPeer = peer
      peer._requestManifest()
    }

    for (const s of this._seeks) {
      if (s.inflight.length > 0) continue // TODO: one per peer is better
      if (peer._requestSeek(s) === true) {
        return true
      }
    }

    // Implied that any block in the queue should be requested, no matter how many inflights
    const blks = new RandomIterator(this._queued)

    for (const b of blks) {
      if (b.queued === false || peer._requestBlock(b) === true) {
        b.queued = false
        blks.dequeue()
        return true
      }
    }

    return false
  }

  _updatePeerNonPrimary(peer) {
    if (!peer.isActive() || peer.inflight >= peer.getMaxInflight() || !peer.remoteUploading) {
      return false
    }

    const ranges = new RandomIterator(this._ranges)
    let tried = 0

    for (const r of ranges) {
      if (peer._requestRange(r) === true) {
        return true
      }
      if (++tried >= MAX_RANGES) break
    }

    // Iterate from newest fork to oldest fork...
    for (let i = this._reorgs.length - 1; i >= 0; i--) {
      const f = this._reorgs[i]
      if (f.batch !== null && f.inflight.length === 0 && peer._requestForkRange(f) === true) {
        return true
      }
    }

    if (this._maybeUpdate() === true && peer._requestUpgrade(this._upgrade) === true) {
      return true
    }

    return false
  }

  updatePeer(peer) {
    // Quick shortcut to wait for flushing reorgs - not needed but less waisted requests
    if (this._applyingReorg !== null) return

    while (this._updatePeer(peer) === true);
    while (this._updatePeerNonPrimary(peer) === true);

    if (this.peers.length > 1 && this._blocks.isEmpty() === false) {
      this._updateHotswap(peer)
    }

    this._checkUpgradeIfAvailable()
    this._maybeResolveIfAvailableRanges()
  }

  updateAll() {
    // Quick shortcut to wait for flushing reorgs - not needed but less waisted requests
    if (this._applyingReorg !== null) return

    const peers = new RandomIterator(this.peers)

    for (const peer of peers) {
      if (this._updatePeer(peer) === true) {
        peers.requeue()
      }
    }

    // Check if we can skip the non primary check fully
    if (this._maybeUpdate() === false && this._ranges.length === 0 && this._reorgs.length === 0) {
      this._checkUpgradeIfAvailable()
      return
    }

    for (const peer of peers.restart()) {
      if (this._updatePeerNonPrimary(peer) === true) {
        peers.requeue()
      }
    }

    this._checkUpgradeIfAvailable()
    this._maybeResolveIfAvailableRanges()
  }

  onpeerdestroy() {
    if (--this._active === 0) this.core.checkIfIdle()
  }

  attached(protomux) {
    return this._attached.has(protomux)
  }

  attachTo(protomux) {
    if (this.core.closed) return

    const makePeer = this._makePeer.bind(this, protomux)

    this._attached.add(protomux)
    protomux.pair({ protocol: 'hypercore/alpha', id: this.core.discoveryKey }, makePeer)
    protomux.stream.setMaxListeners(0)
    protomux.stream.on('close', this._onstreamclose)

    this._ifAvailable++
    this._active++

    protomux.stream.opened.then((opened) => {
      this._ifAvailable--
      this._active--

      if (opened && !this.destroyed) makePeer()
      this._checkUpgradeIfAvailable()

      this.core.checkIfIdle()
    })
  }

  detachFrom(protomux) {
    if (this._attached.delete(protomux)) {
      protomux.stream.removeListener('close', this._onstreamclose)
      protomux.unpair({ protocol: 'hypercore/alpha', id: this.core.discoveryKey })
    }
  }

  idle() {
    return this.peers.length === 0 && this._active === 0
  }

  close() {
    const waiting = []

    for (const peer of this.peers) {
      waiting.push(peer.channel.fullyClosed())
    }

    this.destroy()
    return Promise.all(waiting)
  }

  destroy() {
    if (this.destroyed) return
    this.destroyed = true

    if (this._notDownloadingTimer) {
      clearTimeout(this._notDownloadingTimer)
      this._notDownloadingTimer = null
    }

    while (this.peers.length) {
      const peer = this.peers[this.peers.length - 1]
      this.detachFrom(peer.protomux)
      peer.channel.close() // peer is removed from array in onclose
    }

    for (const protomux of this._attached) {
      this.detachFrom(protomux)
    }
  }

  _makePeer(protomux) {
    const replicator = this
    if (protomux.opened({ protocol: 'hypercore/alpha', id: this.core.discoveryKey })) {
      return onnochannel()
    }

    const channel = protomux.createChannel({
      userData: null,
      protocol: 'hypercore/alpha',
      aliases: ['hypercore'],
      id: this.core.discoveryKey,
      handshake: m.wire.handshake,
      messages: [
        { encoding: m.wire.sync, onmessage: onwiresync },
        { encoding: m.wire.request, onmessage: onwirerequest },
        { encoding: m.wire.cancel, onmessage: onwirecancel },
        { encoding: m.wire.data, onmessage: onwiredata },
        { encoding: m.wire.noData, onmessage: onwirenodata },
        { encoding: m.wire.want, onmessage: onwirewant },
        { encoding: m.wire.unwant, onmessage: onwireunwant },
        { encoding: m.wire.bitfield, onmessage: onwirebitfield },
        { encoding: m.wire.range, onmessage: onwirerange },
        { encoding: m.wire.extension, onmessage: onwireextension }
      ],
      onopen: onwireopen,
      onclose: onwireclose,
      ondrain: onwiredrain,
      ondestroy: onwiredestroy
    })

    if (channel === null) return onnochannel()

    const peer = new Peer(replicator, protomux, channel, this.inflightRange)
    const stream = protomux.stream

    peer.channel.open({
      seeks: true,
      capability: caps.replicate(stream.isInitiator, this.core.key, stream.handshakeHash)
    })

    return true

    function onnochannel() {
      return false
    }
  }

  _onpeerupdate(added, peer) {
    const name = added ? 'peer-add' : 'peer-remove'
    const sessions = this.core.monitors

    for (let i = sessions.length - 1; i >= 0; i--) {
      sessions[i].emit(name, peer)

      if (added) {
        for (const ext of sessions[i].extensions.values()) {
          peer.extensions.set(ext.name, ext)
        }
      }
    }
  }

  _ondownload(index, byteLength, from, req) {
    const sessions = this.core.monitors

    for (let i = sessions.length - 1; i >= 0; i--) {
      const s = sessions[i]
      s.emit('download', index, byteLength - s.padding, from, req)
    }
  }

  _onupload(index, byteLength, from) {
    const sessions = this.core.monitors

    for (let i = sessions.length - 1; i >= 0; i--) {
      const s = sessions[i]
      s.emit('upload', index, byteLength - s.padding, from)
    }
  }

  _oninvaliddata(err, req, res, from) {
    const sessions = this.core.monitors

    this.stats.invalidData++
    from.stats.invalidData++
    for (let i = 0; i < sessions.length; i++) {
      sessions[i].emit('verification-error', err, req, res, from)
    }
  }

  _oninvalidrequest(err, req, from) {
    const sessions = this.core.monitors

    from.stats.invalidRequests++
    this.stats.invalidRequests++
    for (let i = 0; i < sessions.length; i++) {
      sessions[i].emit('invalid-request', err, req, from)
    }
  }
}

function removeHotswap(block) {
  if (block.hotswap === null) return false
  block.hotswap.ref.remove(block)
  return true
}

function removeInflight(inf, req) {
  const i = inf.indexOf(req)
  if (i === -1) return false
  if (i < inf.length - 1) inf[i] = inf.pop()
  else inf.pop()
  return true
}

function toLength(start, end) {
  return end === -1 ? -1 : end < start ? 0 : end - start
}

function clampRange(core, r) {
  if (r.blocks === null) {
    const start = core.bitfield.firstUnset(r.start)

    if (r.end === -1) r.start = start === -1 ? core.state.length : start
    else if (start === -1 || start >= r.end) r.start = r.end
    else {
      r.start = start

      const end = core.bitfield.lastUnset(r.end - 1)

      if (end === -1 || start >= end + 1) r.end = r.start
      else r.end = end + 1
    }
  } else {
    while (r.start < r.end && core.bitfield.get(r.blocks[r.start])) r.start++
    while (r.start < r.end && core.bitfield.get(r.blocks[r.end - 1])) r.end--
  }
}

function onrequesttimeout(req) {
  if (req.context) req.context.detach(req, REQUEST_TIMEOUT())
}

function destroyRequestTimeout(req) {
  if (req.timeout !== null) {
    clearTimeout(req.timeout)
    req.timeout = null
  }
}

function isCriticalError(err) {
  // TODO: expose .critical or similar on the hypercore errors that are critical (if all not are)
  return err.name === 'HypercoreError'
}

function onwireopen(m, c) {
  return c.userData.onopen(m)
}

function onwireclose(isRemote, c) {
  return c.userData.onclose(isRemote)
}

function onwiredestroy(c) {
  c.userData.replicator.onpeerdestroy()
}

function onwiredrain(c) {
  return c.userData.ondrain()
}

function onwiresync(m, c) {
  incrementRx(c.userData.stats.wireSync, c.userData.replicator.stats.wireSync)
  return c.userData.onsync(m)
}

function onwirerequest(m, c) {
  incrementRx(c.userData.stats.wireRequest, c.userData.replicator.stats.wireRequest)
  return c.userData.onrequest(m)
}

function onwirecancel(m, c) {
  incrementRx(c.userData.stats.wireCancel, c.userData.replicator.stats.wireCancel)
  return c.userData.oncancel(m)
}

function onwiredata(m, c) {
  incrementRx(c.userData.stats.wireData, c.userData.replicator.stats.wireData)
  return c.userData.ondata(m)
}

function onwirenodata(m, c) {
  return c.userData.onnodata(m)
}

function onwirewant(m, c) {
  incrementRx(c.userData.stats.wireWant, c.userData.replicator.stats.wireWant)
  return c.userData.onwant(m)
}

function onwireunwant(m, c) {
  return c.userData.onunwant(m)
}

function onwirebitfield(m, c) {
  incrementRx(c.userData.stats.wireBitfield, c.userData.replicator.stats.wireBitfield)
  return c.userData.onbitfield(m)
}

function onwirerange(m, c) {
  incrementRx(c.userData.stats.wireRange, c.userData.replicator.stats.wireRange)
  return c.userData.onrange(m)
}

function onwireextension(m, c) {
  incrementRx(c.userData.stats.wireExtension, c.userData.replicator.stats.wireExtension)
  return c.userData.onextension(m)
}

function setNotDownloadingLater(repl, session) {
  repl._setDownloadingNow(false, session)
}

function isBlockRequest(req) {
  return req !== null && req.block !== null
}

function isUpgradeRequest(req) {
  return req !== null && req.upgrade !== null
}

function incrementTx(stats1, stats2) {
  stats1.tx++
  stats2.tx++
}

function incrementRx(stats1, stats2) {
  stats1.rx++
  stats2.rx++
}

function noop() {}

function backoff(times) {
  const sleep = times < 2 ? 200 : times < 5 ? 500 : times < 40 ? 1000 : 5000
  return new Promise((resolve) => setTimeout(resolve, sleep))
}
const crypto = require('hypercore-crypto')
const b4a = require('b4a')
const assert = require('nanoassert')
const flat = require('flat-tree')
const quickbit = require('quickbit-universal')
const HypercoreStorage = require('hypercore-storage')

const {
  INVALID_OPERATION,
  INVALID_SIGNATURE,
  ASSERTION,
  SESSION_CLOSED,
  SESSION_NOT_WRITABLE
} = require('hypercore-errors')

const Mutex = require('./mutex')
const Bitfield = require('./bitfield')
const { MerkleTree, MerkleTreeBatch } = require('./merkle-tree')

class SessionState {
  constructor(core, parent, storage, treeInfo, name) {
    this.core = core
    this.index = this.core.sessionStates.push(this) - 1

    this.storage = storage
    this.name = name
    this.sessions = []

    // small hack to close old storages as late as possible.
    // TODO: add a read lock so we can avoid that
    this.lingers = null

    this.parent = parent
    this.atomized = null
    this.mutex = new Mutex()

    // merkle state
    this.roots = treeInfo.roots.length ? treeInfo.roots : []
    this.fork = treeInfo.fork || 0
    this.length = this.roots.length ? MerkleTree.span(this.roots) / 2 : treeInfo.length
    this.byteLength = MerkleTree.size(this.roots)
    this.prologue = treeInfo.prologue || null
    this.signature = treeInfo.signature || null

    this.snapshotCompatLength = this.isSnapshot()
      ? Math.min(this.length, this.core.state.length)
      : -1
    this.lastTruncation = null

    this.active = 0

    this._activeTx = null
    this._pendingBitfield = null

    this.ref()
  }

  static RECOVERY_PEERS = null

  isSnapshot() {
    return this.storage.snapshotted
  }

  isDefault() {
    return this.core.state === this || this.isAtomicDefault()
  }

  isAtomicDefault() {
    return !!this.storage.atom && !!this.parent && this.parent.isDefault()
  }

  createTreeBatch() {
    return new MerkleTreeBatch(this)
  }

  addSession(s) {
    if (s._stateIndex !== -1) return
    s._stateIndex = this.sessions.push(s) - 1
    if (s.weak === false) this.core.activeSessions++
  }

  removeSession(s) {
    if (s._stateIndex === -1) return
    const head = this.sessions.pop()
    if (head !== s) this.sessions[(head._stateIndex = s._stateIndex)] = head
    s._stateIndex = -1
    if (s.weak === false) this.core.activeSessions--
    this.core.checkIfIdle()
  }

  flushedLength() {
    if (this.isDefault() || this.isSnapshot()) return this.length
    const deps = this.storage.dependencies
    if (deps.length) return deps[deps.length - 1].length
    return 0
  }

  signedLength() {
    const l = Math.min(this.flushedLength(), this.core.state.length)
    return this.isSnapshot() && l > this.snapshotCompatLength ? this.snapshotCompatLength : l
  }

  unref() {
    if (--this.active > 0) return
    this.close().catch(noop) // technically async, but only for the last db session
  }

  ref() {
    this.active++
    return this
  }

  hash() {
    return MerkleTree.hash(this)
  }

  setRoots(roots) {
    this.roots = roots
    this.length = MerkleTree.span(roots) / 2
    this.byteLength = MerkleTree.size(roots)
  }

  get encryptionFork() {
    return this.core.header.tree.fork
  }

  async _updateSnapshotStorage(storage) {
    if (!this.atomized || !this.atomized.flushing) return this.treeInfo()
    while (this.atomized.flushing) await this.atomized.flushed()

    let rx = storage.read()
    const headPromise = rx.getHead()
    const authPromise = rx.getAuth()
    const depPromise = rx.getDependency()

    rx.tryFlush()
    const [head, auth, dep] = await Promise.all([headPromise, authPromise, depPromise])

    storage.setDependencyHead(dep)

    const fork = head ? head.fork : 0
    const length = head ? head.length : 0

    rx = storage.read()
    const rootPromises = []
    for (const r of flat.fullRoots(length * 2)) {
      rootPromises.push(rx.getTreeNode(r))
    }

    rx.tryFlush()

    const roots = await Promise.all(rootPromises)

    // dbl check if we are hitting an regression from earler
    for (const root of roots) {
      if (root === null) {
        throw new Error(
          'Bad snapshot from atomized session, id = ' +
            this.core.id +
            ' length = ' +
            length +
            ' fork = ' +
            fork
        )
      }
    }

    return {
      fork,
      roots,
      length,
      prologue: auth.manifest && auth.manifest.prologue,
      signature: head && head.signature
    }
  }

  treeInfo() {
    return {
      fork: this.fork,
      roots: this.roots.slice(),
      length: this.length,
      prologue: this.prologue,
      signature: this.signature
    }
  }

  async close() {
    if (this.index === -1) return

    this.active = 0
    this.mutex.destroy(new Error('Closed')).catch(noop)
    if (this.parent && this.parent.atomized) this.parent.atomized = null

    const closing = this.storage.close()

    const head = this.core.sessionStates.pop()
    if (head !== this) this.core.sessionStates[(head.index = this.index)] = head

    this.index = -1
    this.core.checkIfIdle()

    if (this.lingers !== null) {
      for (const storage of this.lingers) await storage.close()
    }

    return closing
  }

  async snapshot() {
    const storage = this.storage.snapshot()
    const treeInfo = await this._updateSnapshotStorage(storage)

    return new SessionState(this.core, null, storage, treeInfo, this.name)
  }

  updateDependency(tx, length) {
    const dependency = updateDependency(this, length, false)
    if (dependency) tx.setDependency(dependency)
    return dependency
  }

  _clearActiveBatch() {
    this._activeTx = null
  }

  createWriteBatch() {
    assert(!this._activeTx && !this.storage.snapshotted)

    this._activeTx = this.storage.write()
    return this._activeTx
  }

  _unlock() {
    this._clearActiveBatch()
    this.mutex.unlock()
    this.core.checkIfIdle()
  }

  async flush() {
    const tx = this._activeTx
    this._activeTx = null

    try {
      if (!(await tx.flush())) return false
    } finally {
      this._clearActiveBatch()
    }

    this.lastTruncation = null
    return true
  }

  _precommit(state) {
    assert(
      state.parent === this && state.storage.core.dataPointer === this.storage.core.dataPointer,
      'Atomic state must flush to parent'
    )
  }

  async _commit() {
    await this.mutex.lock()

    try {
      const bitfield = this._pendingBitfield
      this._pendingBitfield = null
      this.lastTruncation = null
      await this.parent._oncommit(this, bitfield)
    } finally {
      this.mutex.unlock()
    }
  }

  async _oncommit(src, bitfield) {
    await this.mutex.lock()

    try {
      const currLength = this.length

      // load dependency into memory
      const rx = this.storage.read()
      const dependencyPromise = rx.getDependency()

      rx.tryFlush()

      const dependency = await dependencyPromise

      this.fork = src.fork
      this.length = src.length
      this.byteLength = src.byteLength
      this.roots = src.roots.slice()
      this.signature = src.signature

      const tree = {
        fork: this.fork,
        length: this.length,
        rootHash: this.hash(),
        signature: this.signature
      }

      if (dependency) this.storage.setDependencyHead(dependency)

      const b = bitfield

      if (b && b.truncated && b.start < currLength) {
        this.ontruncate(tree, b.start, currLength, true)
        if (!b || b.appends === 0) return
      }

      const append = b ? { start: b.start, length: b.appends, drop: false } : null

      this.onappend(tree, append, true)

      if (this.core.hintsChanged && this.isDefault()) await this.core.flushHints()
    } finally {
      this._unlock()
    }
  }

  async setUserData(key, value) {
    await this.mutex.lock()

    try {
      const tx = this.createWriteBatch()
      tx.putUserData(key, value)

      return await this.flush()
    } finally {
      this._unlock()
    }
  }

  async _verifyBlock(batch, bitfield, value, manifest, from) {
    await this.mutex.lock()

    try {
      if (batch.upgraded && batch.length <= this.length) {
        await batch.downgrade()
      }

      if (!batch.commitable()) {
        return false
      }

      if (this.core.preupdate !== null) {
        await this.core.preupdate(batch, this.core.header.key)
      }

      const tx = this.createWriteBatch()

      if (bitfield) {
        tx.putBlock(bitfield.start, value)
      }

      if (bitfield && this.isDefault()) {
        await storeBitfieldRange(this.storage, tx, bitfield.start, bitfield.start + 1, true)
      }

      if (manifest) this.core._setManifest(tx, manifest, null)

      assert(batch.commitable(), 'Should still be commitable')
      batch.commit(tx)

      const head = {
        fork: batch.fork,
        length: batch.length,
        rootHash: batch.hash(),
        signature: batch.signature
      }

      if (batch.upgraded) tx.setHead(head)

      const flushed = await this.flush()

      if (batch.upgraded) {
        this.roots = batch.roots
        this.length = batch.length
        this.byteLength = batch.byteLength
        this.fork = batch.fork
        this.signature = batch.signature

        this.onappend(head, bitfield, flushed)
      }

      if (this.core.hintsChanged && this.isDefault()) await this.core.flushHints()
    } finally {
      this._unlock()
    }

    return true
  }

  async truncate(length, fork, { signature, keyPair } = {}) {
    if (!keyPair && this.isDefault()) keyPair = this.core.header.keyPair

    await this.mutex.lock()

    try {
      if (this.prologue && length < this.prologue.length) {
        throw INVALID_OPERATION('Truncation breaks prologue', this.core.discoveryKey)
      }
      if (length > this.length) {
        throw INVALID_OPERATION(
          'Not a truncation, ' + length + ' must be less or equal to ' + this.length,
          this.core.discoveryKey
        )
      }

      const batch = this.createTreeBatch()
      await MerkleTree.truncate(this, length, batch, fork)

      if (!signature && keyPair && length > 0) signature = this.core.verifier.sign(batch, keyPair)
      if (signature) batch.signature = signature

      const tx = this.createWriteBatch()

      // upsert compat manifest
      if (this.core.verifier === null && keyPair) this.core._setManifest(tx, null, keyPair)

      const { dependency, tree, roots } = await this._truncate(tx, batch)

      for (const sessionState of this.core.sessionStates) {
        if (
          sessionState.isSnapshot() &&
          sessionState.name === this.name &&
          length < sessionState.snapshotCompatLength
        ) {
          sessionState.snapshotCompatLength = length
        }
      }

      const flushed = await this.flush()

      this.fork = tree.fork
      this.length = tree.length
      this.byteLength = MerkleTree.size(roots)
      this.roots = roots
      this.signature = tree.signature

      if (dependency) this.storage.setDependencyHead(dependency)

      this.ontruncate(tree, tree.length, batch.treeLength, flushed)

      if (this.core.hintsChanged && this.isDefault()) await this.core.flushHints()
    } finally {
      this._unlock()
    }
  }

  async reorg(batch) {
    await this.mutex.lock()

    const storage = this.createWriteBatch()

    try {
      if (!batch.commitable()) return false

      const { dependency, tree } = await this._truncate(storage, batch)

      const flushed = await this.flush()

      this.fork = batch.fork
      this.length = batch.length
      this.byteLength = batch.byteLength
      this.roots = batch.roots
      this.signature = batch.signature

      if (dependency) this.storage.setDependencyHead(dependency)

      this.ontruncate(tree, batch.ancestors, batch.treeLength, flushed)

      if (this.core.hintsChanged && this.isDefault()) await this.core.flushHints()
    } finally {
      this._unlock()
    }
  }

  async _truncate(storage, batch) {
    storage.deleteBlockRange(batch.ancestors, batch.treeLength)

    assert(batch.commitable(), 'Batch must be commitable')

    const tree = {
      fork: batch.fork,
      length: batch.length,
      rootHash: batch.hash(),
      signature: batch.signature
    }

    storage.setHead(tree)
    batch.commit(storage)

    const truncated = batch.length < this.flushedLength()
    const dependency = truncated ? updateDependency(this, batch.length, true) : null

    if (dependency) storage.setDependency(dependency)

    if (this.isDefault()) {
      await storeBitfieldRange(this.storage, storage, batch.ancestors, batch.treeLength, false)
      if (batch.ancestors < this.core.header.hints.contiguousLength) {
        this.core.header.hints.remoteContiguousLength = Math.min(
          batch.length,
          this.core.header.hints.remoteContiguousLength
        )
        storage.setHints({
          contiguousLength: batch.ancestors,
          remoteContiguousLength: this.core.header.hints.remoteContiguousLength
        })
      }
    }

    return { dependency, tree, roots: batch.roots }
  }

  async clear(start, end, cleared) {
    await this.mutex.lock()

    try {
      const tx = this.createWriteBatch()

      const ite = flat.iterator(start * 2)
      while (!isRootIndex(ite.index, this.roots)) {
        const a = ite.index
        const b = ite.sibling()
        ite.parent()

        const [left, right] = flat.spans(b)
        const s = left / 2
        const e = right / 2 + 1
        const has = s <= start && e <= end ? false : this.core.bitfield.hasSet(s, e - s)
        if (has) break

        tx.deleteTreeNode(a)
        tx.deleteTreeNode(b)
      }

      if (this.isDefault()) {
        await storeBitfieldRange(this.storage, tx, start, end, false)
        if (start < this.core.header.hints.contiguousLength) {
          tx.setHints({
            contiguousLength: start,
            remoteContiguousLength: this.core.header.hints.remoteContiguousLength
          })
        }
      }

      if (end - start === 1) tx.deleteBlock(start)
      else tx.deleteBlockRange(start, end)

      const dependency = start < this.flushedLength() ? updateDependency(this, start, true) : null

      const flushed = await this.flush()

      if (dependency) this.storage.setDependencyHead(dependency)

      // todo: atomic event handle
      if (this.isDefault() && flushed) {
        const length = end - start

        this.core.updateContiguousLength({ start, length, drop: true })
        this.core._setBitfieldRanges(start, end, false)
        this.core.replicator.onhave(start, length, true)

        if (this.core.hintsChanged) await this.core.flushHints()
      }
    } finally {
      this._unlock()
    }
  }

  // simple tool to wait for other peers to catch us up
  async waitForRecovery() {
    const length = this.length
    const replicator = this.core.replicator

    while (!this.closing) {
      let peers = getRecoveryPeers(replicator.peers)

      if (peers.length < 1) {
        await new Promise((resolve) => setTimeout(resolve, 5000))
        continue
      }

      let restart = false

      for (let i = 0; i < 32; i++) {
        await new Promise((resolve) => setTimeout(resolve, 250))

        peers = getRecoveryPeers(replicator.peers)

        if (this.closing || !validateRecoveryPeers(peers, this.length)) {
          restart = true
          break
        }
      }

      if (restart) continue

      if (this.length !== length) {
        throw SESSION_NOT_WRITABLE('core recovered during append')
      }

      this.core.header.hints.recovering = 0
      this.core.hintsChanged = true

      await this.mutex.lock()
      try {
        await this.core.flushHints()
        return
      } finally {
        this.mutex.unlock()
      }
    }

    throw SESSION_CLOSED('Cannot recover a closed session', this.discoveryKey)
  }

  async append(values, { signature, keyPair, preappend, postappend, maxLength = -1 } = {}) {
    if (!keyPair && this.isDefault()) keyPair = this.core.header.keyPair

    if (this.isDefault() && this.core.header.hints.recovering) await this.waitForRecovery()

    await this.mutex.lock()

    try {
      if (maxLength >= 0 && this.length + values.length > maxLength) {
        return { length: this.length, byteLength: this.byteLength }
      }

      const tx = this.createWriteBatch()

      // upsert compat manifest
      if (this.core.verifier === null && keyPair) this.core._setManifest(tx, null, keyPair)

      if (preappend) await preappend(values)

      if (!values.length) {
        await this.flush()
        return { length: this.length, byteLength: this.byteLength }
      }

      const batch = this.createTreeBatch()
      for (const val of values) batch.append(val)

      // only multisig can have prologue so signature is always present
      if (this.prologue && batch.length < this.prologue.length) {
        throw INVALID_OPERATION('Append is not consistent with prologue', this.core.discoveryKey)
      }

      if (!signature && keyPair) signature = this.core.verifier.sign(batch, keyPair)
      if (signature) batch.signature = signature

      batch.commit(tx)

      const tree = {
        fork: batch.fork,
        length: batch.length,
        rootHash: batch.hash(),
        signature: batch.signature
      }

      tx.setHead(tree)

      if (this.isDefault()) {
        await storeBitfieldRange(this.storage, tx, batch.ancestors, batch.length, true)
        if (this.length === this.core.header.hints.contiguousLength) {
          tx.setHints({
            contiguousLength: this.length + values.length,
            remoteContiguousLength: this.core.header.hints.remoteContiguousLength
          })
        }
      }

      for (let i = 0; i < values.length; i++) {
        tx.putBlock(this.length + i, values[i])
      }

      const bitfield = {
        drop: false,
        start: batch.ancestors,
        length: values.length
      }

      const flushed = await this.flush()

      this.fork = batch.fork
      this.roots = batch.roots
      this.length = batch.length
      this.byteLength = batch.byteLength
      this.signature = batch.signature

      if (postappend) await postappend(values)

      this.onappend(tree, bitfield, flushed)

      if (this.core.hintsChanged && this.isDefault()) await this.core.flushHints()

      return { length: this.length, byteLength: this.byteLength }
    } finally {
      this._unlock()
    }
  }

  onappend(tree, bitfield, flushed) {
    if (!flushed) this._updateBitfield(bitfield)
    else if (this.isDefault()) this.core.onappend(tree, bitfield)

    for (let i = this.sessions.length - 1; i >= 0; i--) {
      this.sessions[i].emit('append')
    }
  }

  ontruncate(tree, to, from, flushed) {
    const bitfield = { start: to, length: from - to, drop: true }

    this.lastTruncation = { from, to }

    if (!flushed) this._updateBitfield(bitfield)
    else if (this.isDefault()) this.core.ontruncate(tree, bitfield)

    for (const sessionState of this.core.sessionStates) {
      if (
        sessionState.isSnapshot() &&
        sessionState.name === this.name &&
        to < sessionState.snapshotCompatLength
      ) {
        sessionState.snapshotCompatLength = to
      }
    }

    for (let i = this.sessions.length - 1; i >= 0; i--) {
      this.sessions[i].emit('truncate', to, tree.fork)
    }
  }

  _updateBitfield(bitfield, flushed) {
    if (!bitfield) return

    const p = this._pendingBitfield
    const b = bitfield

    if (b.drop) {
      // truncation must be from end
      if (p && b.start + b.length !== p.start + p.appends) {
        throw INVALID_OPERATION('Atomic truncations must be contiguous', this.core.discoveryKey)
      }

      // actual truncation
      if (p === null || b.start < p.start) {
        this._pendingBitfield = { truncated: true, start: b.start, appends: 0 }
        return
      }

      // just clearing batch data
      p.appends = b.start - p.start

      // we cleared the current batch
      if (p.appends === 0) this._pendingBitfield = null

      return
    }

    if (p === null) {
      this._pendingBitfield = { truncated: false, start: b.start, appends: b.length }
      return
    }

    if (b.start !== p.start + p.appends) {
      throw INVALID_OPERATION('Atomic operations must be contiguous', this.core.discoveryKey)
    }

    p.appends += b.length
  }

  async catchup(length) {
    assert(!this.isDefault(), 'Cannot catchup signed state') // TODO: make this check better

    await this.mutex.lock()

    try {
      const origLength = this.length

      let sharedLength = 0
      for (let i = this.storage.dependencies.length - 1; i >= 0; i--) {
        const dep = this.storage.dependencies[i]
        if (dep.dataPointer === this.core.state.storage.core.dataPointer) {
          sharedLength = dep.length
          break
        }
      }

      const tx = this.createWriteBatch()
      const rx = this.core.state.storage.read()
      const rootPromises = []

      for (const root of flat.fullRoots(length * 2)) {
        rootPromises.push(rx.getTreeNode(root))
      }

      rx.tryFlush()

      const roots = await Promise.all(rootPromises)
      const truncating = sharedLength < origLength

      for (const node of roots) {
        if (node === null) {
          throw INVALID_OPERATION(
            'Invalid catchup length, tree nodes not available',
            this.core.discoveryKey
          )
        }
      }

      const fork = truncating ? this.fork + 1 : this.fork

      // overwrite it atm, TODO: keep what we can connect to the tree
      tx.deleteBlockRange(0, -1)
      tx.deleteTreeNodeRange(0, -1)
      tx.deleteBitfieldPageRange(0, -1)

      const tree = {
        fork,
        length,
        rootHash: crypto.tree(roots),
        signature: null
      }

      tx.setHead(tree)

      // prop a better way to do this
      const dep = updateDependency(this, sharedLength, true)
      dep.length = length

      tx.setDependency(dep)

      const flushed = await this.flush()

      this.storage.setDependencyHead(dep)

      this.fork = tree.fork
      this.roots = roots
      this.length = tree.length
      this.byteLength = MerkleTree.size(roots)

      if (truncating) this.ontruncate(tree, sharedLength, origLength, flushed)
      if (sharedLength < length) this.onappend(tree, null, flushed)

      if (this.core.hintsChanged && this.isDefault()) await this.core.flushHints()
    } finally {
      this._unlock()
    }
  }

  async _overwrite(source, fork, length, treeLength, signature) {
    const blockPromises = []
    const treePromises = []
    const rootPromises = []

    const rx = source.storage.read()

    for (const root of flat.fullRoots(length * 2)) {
      rootPromises.push(rx.getTreeNode(root))
    }

    for (const index of flat.patch(treeLength * 2, length * 2)) {
      treePromises.push(rx.getTreeNode(index))
    }

    for (let i = treeLength; i < length; i++) {
      treePromises.push(rx.getTreeNode(i * 2))
      treePromises.push(rx.getTreeNode(i * 2 + 1))
      blockPromises.push(rx.getBlock(i))
    }

    rx.tryFlush()

    const blocks = await Promise.all(blockPromises)
    const nodes = await Promise.all(treePromises)
    const roots = await Promise.all(rootPromises)

    if (this.core.destroyed) throw new Error('Core destroyed')

    if (signature) {
      const batch = this.createTreeBatch()
      batch.roots = roots
      batch.length = length

      if (!this.core.verifier.verify(batch, signature)) {
        throw INVALID_SIGNATURE(
          'Signature is not valid over committed tree',
          this.core.discoveryKey
        )
      }
    }

    const tx = this.createWriteBatch()

    // truncate existing tree
    if (treeLength < this.length) {
      tx.deleteBlockRange(treeLength, this.length)
    }

    for (const root of roots) tx.putTreeNode(root)

    // no nodes will be copied in shallow mode
    for (const node of nodes) {
      if (node !== null) tx.putTreeNode(node)
    }

    for (let i = 0; i < blocks.length; i++) {
      assert(blocks[i] !== null, 'has block')
      tx.putBlock(i + treeLength, blocks[i])
    }

    const totalLength = Math.max(length, this.length)

    if (totalLength > treeLength) {
      const firstPage = getBitfieldPage(treeLength)
      const lastPage = getBitfieldPage(totalLength - 1)

      const srx = this.storage.read()
      const bitfieldPagePromise = srx.getBitfieldPage(firstPage)
      srx.tryFlush()

      const bitfieldPage = await bitfieldPagePromise

      let index = treeLength

      for (let i = firstPage; i <= lastPage; i++) {
        const page = b4a.alloc(Bitfield.BYTES_PER_PAGE)
        tx.putBitfieldPage(i, page)

        // copy existing bits in
        if (i === firstPage && bitfieldPage) page.set(bitfieldPage)

        if (index < length) {
          index = fillBitfieldPage(page, index, length, i, true)
          if (index < length) continue
        }

        if (index < this.length) {
          index = fillBitfieldPage(page, index, this.length, i, false)
        }
      }
    }

    const tree = {
      fork,
      length,
      rootHash: crypto.tree(roots),
      signature
    }

    const upgraded = treeLength < this.length || this.length < length || tree.fork !== this.fork

    if (upgraded) tx.setHead(tree)

    const flushed = await this.flush()

    this.fork = tree.fork
    this.roots = roots
    this.length = length
    this.byteLength = MerkleTree.size(roots)
    this.signature = signature

    return { tree, flushed }
  }

  static isParent(state, parent) {
    // atomic batches have parent set
    if (state.parent && state.parent === parent) return true

    return HypercoreStorage.isParentStorage(state.storage, parent.storage)
  }

  async commit(state, { signature, keyPair, length = state.length, treeLength = -1 } = {}) {
    assert(
      this.isDefault() || (this.parent && this.parent.isDefault()),
      'Can only commit into default state'
    )

    assert(SessionState.isParent(state, this), 'Cannot commit across cores')

    if (this.core._repairMode) {
      throw ASSERTION('Cannot commit while repair mode is on')
    }

    if (this.core.header.hints.recovering) await this.waitForRecovery()

    let srcLocked = false
    await this.mutex.lock()

    try {
      await state.mutex.lock()
      srcLocked = true

      if (treeLength === -1) treeLength = state.flushedLength()

      if (!(await this.core._validateCommit(state, treeLength))) return null
      if (this.length > length) return null

      if (this.length < length && !signature) {
        if (!keyPair) keyPair = this.core.header.keyPair
        const batch = state.createTreeBatch()
        if (length !== batch.length) await batch.restore(length)
        signature = this.core.verifier.sign(batch, keyPair)
      }

      const { tree, flushed } = await this._overwrite(
        state,
        this.fork,
        length,
        treeLength,
        signature
      )

      // gc blocks from source
      if (treeLength < length) {
        const tx = state.createWriteBatch()

        tx.deleteBlockRange(treeLength, length)
        const dependency = state.updateDependency(tx, length)

        await state.flush(tx)

        if (dependency) state.storage.setDependencyHead(dependency)
      }

      const bitfield = { start: treeLength, length: length - treeLength, drop: false }
      this.onappend(tree, bitfield, flushed)

      return {
        length: this.length,
        byteLength: this.byteLength
      }
    } finally {
      if (srcLocked) state._unlock()
      this._unlock()
    }
  }

  async _getTreeHeadAt(length) {
    if (length === null) return this.treeInfo()

    const head = getDefaultTree()

    head.length = length

    const roots = await MerkleTree.getRootsFromStorage(this.storage, length)
    const rootHash = crypto.tree(roots)

    head.fork = this.fork
    head.rootHash = rootHash

    if (length === this.length) head.signature = this.signature

    return head
  }

  _moveToCore(core, truncated, appended) {
    const head = this.core.sessionStates.pop()
    if (head !== this) this.core.sessionStates[(head.index = this.index)] = head

    this.core = core
    this.index = this.core.sessionStates.push(this) - 1

    for (let i = this.sessions.length - 1; i >= 0; i--) {
      const s = this.sessions[i]
      const manifest = s.manifest
      s.transferSession(this.core)
      if (!manifest && s.manifest) s.emit('manifest')
      if (truncated) s.emit('truncate', truncated.to, truncated.fork)
      if (appended) s.emit('append')
    }
  }

  async moveTo(core, length) {
    const state = core.state

    await this.mutex.lock()

    try {
      // if (state.storage && (await state.storage.resumeSession(this.name)) !== null) {
      //   throw STORAGE_CONFLICT('Batch has already been created')
      // }

      const treeLength = this.length

      let truncated = null
      let appended = false

      if (!this.isSnapshot()) {
        if (this.lingers === null) this.lingers = []
        this.lingers.push(this.storage)

        const resumed = await state.storage.resumeSession(this.name)

        const truncation = length < this.length ? await truncateAndFlush(this, length) : null
        const treeInfo = truncation
          ? truncation.tree
          : resumed
            ? null
            : await state._getTreeHeadAt(this.length)

        const fork = truncation ? this.fork + 1 : this.fork

        // todo: validate treeInfo

        let storage = null

        if (resumed) {
          storage = resumed
        } else {
          treeInfo.fork = fork
          storage = await state.storage.createSession(this.name, treeInfo)
        }

        const roots = await MerkleTree.getRootsFromStorage(storage, length)

        this.storage = storage
        this.prologue = state.prologue
        this.fork = fork
        this.length = length
        this.byteLength = MerkleTree.size(roots)
        this.roots = roots

        if (truncation) {
          const { dependency } = truncation

          if (dependency) this.storage.setDependencyHead(dependency)
          truncated = { to: treeLength, fork }
        }

        if (this.length > treeLength) {
          appended = true
        }
      }

      for (let i = this.core.sessionStates.length - 1; i >= 0; i--) {
        const state = this.core.sessionStates[i]
        if (state === this) continue
        if (state.name === this.name) state._moveToCore(core.core)
      }

      this._moveToCore(core.core, truncated, appended)
    } finally {
      this._unlock()
    }
  }

  async createSession(name, overwrite, atom) {
    await this.mutex.lock()

    try {
      let storage = null
      let treeInfo = null

      if (!atom && !overwrite && this.storage) {
        storage = await this.storage.resumeSession(name)

        if (storage !== null) treeInfo = (await getCoreHead(storage)) || getDefaultTree()
      }

      const length = treeInfo ? treeInfo.length : this.length

      if (storage === null) {
        treeInfo = await this._getTreeHeadAt(length)

        if (atom) {
          storage = await this.storage.createAtomicSession(atom, treeInfo)
        } else {
          storage = await this.storage.createSession(name, treeInfo)
        }
      }

      if (this.atomized && atom) {
        throw new Error('Session already atomized')
      }

      const head = {
        fork: this.fork,
        roots:
          length === this.length
            ? this.roots.slice()
            : await MerkleTree.getRootsFromStorage(storage, length),
        length,
        prologue: this.prologue,
        signature: length === this.length ? this.signature : null
      }

      const state = new SessionState(
        this.core,
        atom ? this : null,
        storage,
        head,
        atom ? this.name : name
      )

      if (atom) {
        this.atomized = atom
        atom.preflush(this._precommit.bind(this, state))
        atom.onflush(state._commit.bind(state))
      }

      return state
    } finally {
      this._unlock()
    }
  }
}

module.exports = SessionState

function noop() {}

function getBitfieldPage(index) {
  return Math.floor(index / Bitfield.BITS_PER_PAGE)
}

function fillBitfieldPage(page, start, end, pageIndex, value) {
  const offset = pageIndex * Bitfield.BITS_PER_PAGE
  const max = offset + Bitfield.BITS_PER_PAGE

  const index = max < end ? max : end

  const from = start - offset
  const to = index - offset

  quickbit.fill(page, value, from, to)

  return index
}

async function storeBitfieldRange(storage, tx, from, to, value) {
  if (from >= to) return

  const firstPage = getBitfieldPage(from)
  const lastPage = getBitfieldPage(to - 1)

  let index = from

  const rx = storage.read()

  const promises = []
  for (let i = firstPage; i <= lastPage; i++) {
    promises.push(rx.getBitfieldPage(i))
  }

  rx.tryFlush()

  const pages = await Promise.all(promises)
  const cnt = lastPage - firstPage + 1

  for (let i = 0; i < cnt; i++) {
    const pageIndex = i + firstPage
    if (!pages[i]) pages[i] = b4a.alloc(Bitfield.BYTES_PER_PAGE)

    index = fillBitfieldPage(pages[i], index, to, pageIndex, value)
    tx.putBitfieldPage(pageIndex, pages[i])
  }
}

async function truncateAndFlush(s, length) {
  const batch = s.createTreeBatch()
  await MerkleTree.truncate(s, length, batch, s.fork)
  const tx = s.createWriteBatch()

  const info = await s._truncate(tx, batch)
  const flushed = await s.flush()

  return {
    tree: info.tree,
    roots: info.roots,
    dependency: info.dependency,
    flushed
  }
}

function updateDependency(state, length, truncated) {
  const i = state.storage.findDependencyIndex(length, truncated)
  if (i === -1) return null // skip default state and overlays of default

  return {
    dataPointer: state.storage.dependencies[i].dataPointer,
    length
  }
}

function getDefaultTree() {
  return {
    fork: 0,
    length: 0,
    rootHash: null,
    signature: null
  }
}

function getCoreHead(storage) {
  const b = storage.read()
  const p = b.getHead()
  b.tryFlush()
  return p
}

function isRootIndex(index, roots) {
  for (const node of roots) {
    if (node.index === index) return true
  }

  return false
}

function getRecoveryPeers(peers) {
  if (!SessionState.RECOVERY_PEERS) return peers

  const actual = []

  for (const p of peers) {
    for (const r of SessionState.RECOVERY_PEERS) {
      if (b4a.equals(p.remotePublicKey, r)) {
        actual.push(p)
        break
      }
    }
  }

  return actual
}

function validateRecoveryPeers(peers, length) {
  if (peers.length < 1) return false

  for (const p of peers) {
    if (p.remoteLength > length) return false
    if (p.remoteLength === 0 && !p.remoteSynced) return false
  }

  return true
}
const { Writable, Readable } = require('streamx')

class ReadStream extends Readable {
  constructor(core, opts = {}) {
    super()

    this.core = core
    this.start = opts.start || 0
    this.end = typeof opts.end === 'number' ? opts.end : -1
    this.snapshot = !opts.live && opts.snapshot !== false
    this.live = this.end === -1 ? !!opts.live : false
    this.wait = typeof opts.wait === 'boolean' ? opts.wait : this.core.wait
    this.timeout = opts.timeout || core.timeout
  }

  _open(cb) {
    this._openP().then(cb, cb)
  }

  _read(cb) {
    this._readP().then(cb, cb)
  }

  async _openP() {
    if (this.end === -1) await this.core.update()
    else await this.core.ready()
    if (this.snapshot && this.end === -1) this.end = this.core.length
  }

  async _readP() {
    const end = this.live ? -1 : this.end === -1 ? this.core.length : this.end
    if (end >= 0 && this.start >= end) {
      this.push(null)
      return
    }

    this.push(await this.core.get(this.start++, { wait: this.wait, timeout: this.timeout }))
  }
}

exports.ReadStream = ReadStream

class WriteStream extends Writable {
  constructor(core) {
    super()
    this.core = core
  }

  _writev(batch, cb) {
    this._writevP(batch).then(cb, cb)
  }

  async _writevP(batch) {
    await this.core.append(batch)
  }
}

exports.WriteStream = WriteStream

class ByteStream extends Readable {
  constructor(core, opts = {}) {
    super()

    this._core = core
    this._index = 0
    this._range = null

    this._byteOffset = opts.byteOffset || 0
    this._byteLength = typeof opts.byteLength === 'number' ? opts.byteLength : -1
    this._prefetch = typeof opts.prefetch === 'number' ? opts.prefetch : 32

    this._applyOffset = this._byteOffset > 0
  }

  _open(cb) {
    this._openp().then(cb, cb)
  }

  _read(cb) {
    this._readp().then(cb, cb)
  }

  async _openp() {
    if (this._byteLength === -1) {
      await this._core.update()
      this._byteLength = Math.max(this._core.byteLength - this._byteOffset, 0)
    }
  }

  async _readp() {
    let data = null

    if (this._byteLength === 0) {
      this.push(null)
      return
    }

    let relativeOffset = 0

    if (this._applyOffset) {
      this._applyOffset = false

      const [block, byteOffset] = await this._core.seek(this._byteOffset)

      this._index = block
      relativeOffset = byteOffset
    }

    this._predownload(this._index + 1)
    data = await this._core.get(this._index++, { valueEncoding: 'binary' })

    if (relativeOffset > 0) data = data.subarray(relativeOffset)

    if (data.byteLength > this._byteLength) data = data.subarray(0, this._byteLength)
    this._byteLength -= data.byteLength

    this.push(data)
    if (this._byteLength === 0) this.push(null)
  }

  _predownload(index) {
    if (this._range) this._range.destroy()
    this._range = this._core.download({ start: index, end: index + this._prefetch, linear: true })
  }

  _destroy(cb) {
    if (this._range) this._range.destroy()
    cb(null)
  }
}

exports.ByteStream = ByteStream
const crypto = require('hypercore-crypto')
const b4a = require('b4a')
const c = require('compact-encoding')
const flat = require('flat-tree')
const { BAD_ARGUMENT } = require('hypercore-errors')
const unslab = require('unslab')

const m = require('./messages')
const multisig = require('./multisig')
const caps = require('./caps')

class Signer {
  constructor(
    manifestHash,
    version,
    index,
    { signature = 'ed25519', publicKey, namespace = caps.DEFAULT_NAMESPACE } = {}
  ) {
    if (!publicKey) throw BAD_ARGUMENT('public key is required for a signer')
    if (signature !== 'ed25519') throw BAD_ARGUMENT('Only Ed25519 signatures are supported')

    this.manifestHash = manifestHash
    this.version = version
    this.signer = index
    this.signature = signature
    this.publicKey = publicKey
    this.namespace = namespace
  }

  _ctx() {
    return this.version === 0 ? this.namespace : this.manifestHash
  }

  verify(batch, signature) {
    return crypto.verify(batch.signable(this._ctx()), signature, this.publicKey)
  }

  sign(batch, keyPair) {
    return crypto.sign(batch.signable(this._ctx()), keyPair.secretKey)
  }
}

class CompatSigner extends Signer {
  constructor(index, signer, legacy) {
    super(null, 0, index, signer)
    this.legacy = legacy
  }

  verify(batch, signature) {
    return crypto.verify(batch.signableCompat(this.legacy), signature, this.publicKey)
  }

  sign(batch, keyPair) {
    return crypto.sign(batch.signableCompat(this.legacy), keyPair.secretKey)
  }
}

module.exports = class Verifier {
  constructor(
    manifestHash,
    manifest,
    { compat = isCompat(manifestHash, manifest), legacy = false } = {}
  ) {
    const self = this

    this.manifestHash = manifestHash
    this.compat = compat || manifest === null
    this.version = this.compat ? 0 : typeof manifest.version === 'number' ? manifest.version : 1
    this.hash = manifest.hash || 'blake2b'
    this.allowPatch = !this.compat && !!manifest.allowPatch
    this.quorum = this.compat ? 1 : defaultQuorum(manifest)

    this.signers = manifest.signers ? manifest.signers.map(createSigner) : []
    this.prologue = this.compat ? null : manifest.prologue || null

    function createSigner(signer, index) {
      return self.compat
        ? new CompatSigner(index, signer, legacy)
        : new Signer(manifestHash, self.version, index, signer)
    }
  }

  _verifyCompat(batch, signature) {
    if (!signature) return false

    if (this.compat || (!this.allowPatch && this.signers.length === 1)) {
      return !!signature && this.signers[0].verify(batch, signature)
    }

    return this._verifyMulti(batch, signature)
  }

  _inflate(signature) {
    if (this.version >= 1) return multisig.inflate(signature)
    const { proofs, patch } = multisig.inflatev0(signature)

    return {
      proofs: proofs.map(proofToVersion1),
      patch
    }
  }

  _verifyMulti(batch, signature) {
    if (!signature || this.quorum === 0) return false

    const { proofs, patch } = this._inflate(signature)
    if (proofs.length < this.quorum) return false

    const tried = new Uint8Array(this.signers.length)
    const nodes = this.allowPatch && patch.length ? toMap(patch) : null

    for (let i = 0; i < this.quorum; i++) {
      const inp = proofs[i]

      let tree = batch

      if (inp.patch && this.allowPatch) {
        tree = batch.clone()

        const upgrade = generateUpgrade(nodes, batch.length, inp.patch)
        const proof = {
          fork: tree.fork,
          block: null,
          hash: null,
          seek: null,
          upgrade,
          manifest: null
        }

        try {
          if (!tree.verifyUpgrade(proof)) return false
        } catch {
          return false
        }
      }

      if (inp.signer >= this.signers.length || tried[inp.signer]) return false
      tried[inp.signer] = 1

      const s = this.signers[inp.signer]
      if (!s.verify(tree, inp.signature)) return false
    }

    return true
  }

  verify(batch, signature) {
    if (this.version === 0) {
      return this._verifyCompat(batch, signature)
    }

    if (this.prologue !== null && batch.length <= this.prologue.length) {
      return batch.length === this.prologue.length && b4a.equals(batch.hash(), this.prologue.hash)
    }

    return this._verifyMulti(batch, signature)
  }

  // TODO: better api for this that is more ... multisig-ey
  sign(batch, keyPair) {
    if (!keyPair || !keyPair.secretKey) throw BAD_ARGUMENT('No key pair was passed')

    for (const s of this.signers) {
      if (b4a.equals(s.publicKey, keyPair.publicKey)) {
        const signature = s.sign(batch, keyPair)
        if (this.signers.length !== 1 || this.version === 0) return signature
        return this.assemble([{ signer: 0, signature, patch: 0, nodes: null }])
      }
    }

    throw BAD_ARGUMENT('Public key is not a declared signer')
  }

  assemble(inputs) {
    return this.version === 0 ? multisig.assemblev0(inputs) : multisig.assemble(inputs)
  }

  static manifestHash(manifest) {
    return manifestHash(manifest)
  }

  static encodeManifest(manifest) {
    return c.encode(m.manifest, manifest)
  }

  static decodeManifest(manifest) {
    return c.decode(m.manifest, manifest)
  }

  static defaultSignerManifest(publicKey) {
    return {
      version: 1,
      hash: 'blake2b',
      allowPatch: false,
      quorum: 1,
      signers: [
        {
          signature: 'ed25519',
          namespace: caps.DEFAULT_NAMESPACE,
          publicKey
        }
      ],
      prologue: null,
      linked: null,
      userData: null
    }
  }

  static fromManifest(manifest, opts) {
    const m = this.createManifest(manifest)
    return new this(manifestHash(m), m, opts)
  }

  static createManifest(inp) {
    if (!inp) return null

    const manifest = {
      version: getManifestVersion(inp), // defaults to v1
      hash: 'blake2b',
      allowPatch: !!inp.allowPatch,
      quorum: defaultQuorum(inp),
      signers: inp.signers ? inp.signers.map(parseSigner) : [],
      prologue: null,
      linked: null,
      userData: inp.userData || null
    }

    if (inp.hash && inp.hash !== 'blake2b') throw BAD_ARGUMENT('Only Blake2b hashes are supported')

    if (inp.prologue) {
      if (
        !(b4a.isBuffer(inp.prologue.hash) && inp.prologue.hash.byteLength === 32) ||
        !(inp.prologue.length >= 0)
      ) {
        throw BAD_ARGUMENT('Invalid prologue')
      }

      manifest.prologue = inp.prologue
      manifest.prologue.hash = unslab(manifest.prologue.hash)
    }

    if (manifest.userData !== null && manifest.version < 2) {
      throw BAD_ARGUMENT('Invalid field: userData')
    }

    if (inp.linked && inp.linked.length) {
      if (manifest.version < 2) throw BAD_ARGUMENT('Invalid field: linked')

      for (const key of inp.linked) {
        if (!(b4a.isBuffer(key) && key.byteLength === 32)) {
          throw BAD_ARGUMENT('Invalid key')
        }
      }

      manifest.linked = inp.linked
    }

    return manifest
  }

  static isValidManifest(key, manifest) {
    return b4a.equals(key, manifestHash(manifest))
  }

  static isCompat(key, manifest) {
    return isCompat(key, manifest)
  }

  static sign(manifest, batch, keyPair, opts) {
    return Verifier.fromManifest(manifest, opts).sign(batch, keyPair)
  }
}

function toMap(nodes) {
  const m = new Map()
  for (const node of nodes) m.set(node.index, node)
  return m
}

function isCompat(key, manifest) {
  return !!(
    manifest &&
    manifest.signers.length === 1 &&
    b4a.equals(key, manifest.signers[0].publicKey)
  )
}

function defaultQuorum(man) {
  if (typeof man.quorum === 'number') return man.quorum
  if (!man.signers || !man.signers.length) return 0
  return (man.signers.length >> 1) + 1
}

function generateUpgrade(patch, start, length) {
  const upgrade = { start, length, nodes: null, additionalNodes: [], signature: null }

  const from = start * 2
  const to = from + length * 2

  for (const ite = flat.iterator(0); ite.fullRoot(to); ite.nextTree()) {
    if (ite.index + ite.factor / 2 < from) continue

    if (upgrade.nodes === null && ite.contains(from - 2)) {
      upgrade.nodes = []

      const root = ite.index
      const target = from - 2

      ite.seek(target)

      while (ite.index !== root) {
        ite.sibling()
        if (ite.index > target) upgrade.nodes.push(patch.get(ite.index))
        ite.parent()
      }

      continue
    }

    if (upgrade.nodes === null) upgrade.nodes = []
    upgrade.nodes.push(patch.get(ite.index))
  }

  if (upgrade.nodes === null) upgrade.nodes = []
  return upgrade
}

function parseSigner(signer) {
  validateSigner(signer)
  return {
    signature: 'ed25519',
    namespace: unslab(signer.namespace || caps.DEFAULT_NAMESPACE),
    publicKey: unslab(signer.publicKey)
  }
}

function validateSigner(signer) {
  if (!signer || !signer.publicKey) throw BAD_ARGUMENT('Signer missing public key')
  if (signer.signature && signer.signature !== 'ed25519') {
    throw BAD_ARGUMENT('Only Ed25519 signatures are supported')
  }
}

function manifestHash(manifest) {
  const state = { start: 0, end: 32, buffer: null }
  m.manifest.preencode(state, manifest)
  state.buffer = b4a.allocUnsafe(state.end)
  c.raw.encode(state, caps.MANIFEST)
  m.manifest.encode(state, manifest)
  return crypto.hash(state.buffer)
}

function proofToVersion1(proof) {
  return {
    signer: proof.signer,
    signature: proof.signature,
    patch: proof.patch ? proof.patch.length : 0
  }
}

function getManifestVersion(inp) {
  if (typeof inp.version === 'number') return inp.version
  if (inp.linked && inp.linked.length) return 2
  if (inp.userData) return 2
  return 1
}
let COMPAT = true
let BATCH_UINTS = COMPAT ? 65536 : 128
let BATCH_BYTES = BATCH_UINTS * 4
let BATCH = BATCH_BYTES * 8 // in bits
const MAX_REMOTE_BATCHES = 4
const MAX_RANGE = 8 * 256 * 1024
const MIN_RANGE = 32 // 4bit ints
const MAX = 512
const MAX_ANY = 16

class LocalWants {
  constructor(peer) {
    this.destroyed = false
    this.peer = peer
    this.wants = new Map()
    this.free = new Set()
    this.any = null
  }

  add(index, handle) {
    const b = (index - (index & (BATCH - 1))) / BATCH
    return this.addBatch(b, handle)
  }

  addAnyRange(start, length, handle) {
    if (this.destroyed) return null
    if (this.any === null) this.any = []

    if (COMPAT) {
      let r = start & (BATCH - 1)
      start -= r
      length += r
      r = length & (BATCH - 1)
      if (r) length = length - r + BATCH
    }

    for (let i = 0; i < this.any.length; i++) {
      const w = this.any[i]
      if (w.start === start && w.length === length) {
        w.handles.add(handle)
        handle.addWant(w)
        return null
      }
    }

    const w = { wants: this, start, length, any: true, handles: new Set([handle]) }
    this.any.push(w)
    handle.addWant(w)

    return { start, length, any: !COMPAT }
  }

  removeAnyRange(start, length, handle) {
    if (this.any === null) return null

    for (let i = 0; i < this.any.length; i++) {
      const w = this.any[i]
      if (w.start !== start || w.length !== length) continue

      w.handles.delete(handle)
      handle.removeWant(w)
      if (w.handles.size > 0) return null

      const head = this.any.pop()
      if (head !== w) this.any[i] = head
      return { start, length, any: !COMPAT }
    }

    return null
  }

  addBatch(index, handle) {
    if (this.destroyed) return null
    let w = this.wants.get(index)

    if (w) {
      const size = w.handles.size
      w.handles.add(handle)
      if (w.handles.size !== size) {
        handle.addWant(w)
      }
      return null
    }

    // start here is the batch number for simplicity....
    w = { wants: this, start: index, length: 0, any: false, handles: new Set([handle]) }

    if (this.free.has(index)) {
      this.free.delete(index)
      this.wants.set(index, w)
      handle.addWant(w)
      return null
    }

    let unwant = null
    if (this.wants.size + this.free.size === MAX) {
      if (this.free.size === 0) {
        return null
      }
      unwant = this._unwant()
    }

    this.wants.set(index, w)
    handle.addWant(w)

    return {
      want: { start: index * BATCH, length: BATCH, any: false },
      unwant
    }
  }

  remove(index, handle) {
    const b = (index - (index & (BATCH - 1))) / BATCH
    return this.removeBatch(b, handle)
  }

  removeBatch(index, handle) {
    if (this.destroyed) return false

    const w = this.wants.get(index)
    if (!w) {
      return false
    }

    w.handles.delete(handle)
    handle.removeWant(w)

    if (w.handles.size === 0) {
      this.free.add(index)
      this.wants.delete(index)
      return this.free.size === 1 && this.wants.size === MAX - 1
    }

    return false
  }

  destroy() {
    if (this.destroyed) return
    this.destroyed = true

    for (const w of this.wants.values()) {
      for (const handle of w.handles) {
        handle.removeWant(w)
      }
    }

    this.wants.clear()
  }

  _unwant() {
    for (const index of this.free) {
      this.free.delete(index)
      return { start: index * BATCH, length: BATCH, any: false }
    }
    return null
  }
}

class RemoteWants {
  constructor() {
    this.any = null
    this.all = false
    this.size = 0
    this.batches = []
  }

  hasAny(start, length) {
    for (let i = 0; i < this.any.length; i++) {
      const a = this.any[i]
      const e = start + length
      const end = a.start + a.length

      if (a.start <= start && start < end) return true
      if (a.start < e && e <= end) return true
    }

    return this.all
  }

  hasRange(start, length) {
    if (this.any !== null && this.hasAny(start, length)) return true
    if (length === 1) return this.has(start)

    let smallest = -1

    for (let i = 0; i < this.batches.length; i++) {
      const b = this.batches[i]
      if (b.length < smallest || smallest === -1) smallest = b.length
    }

    if (smallest === -1) return this.all

    const r = start & (smallest - 1)
    const end = start + length

    let max = 3

    for (let i = start - r; i < end; i += smallest) {
      if (max-- === 0) return true // just to save work
      if (this.has(i)) return true
    }

    return this.all
  }

  has(index) {
    for (let i = 0; i < this.batches.length; i++) {
      const b = this.batches[i]
      const block = (index - (index & (b.length - 1))) / b.length
      if (b.ranges.has(block)) return true
    }

    return this.all
  }

  add(range) {
    if (range.any) {
      if (this.any === null) this.any = []
      if (this.any.length < MAX_ANY) this.any.push(range)
      else this.all = true
      return true
    }

    if (range.length > MAX_RANGE) return false

    if (!validateBatchRange(range)) {
      this.all = true
      return true
    }

    if (this.size >= MAX) {
      this.all = true
      return true
    }

    for (let i = 0; i < this.batches.length; i++) {
      const b = this.batches[i]
      if (b.length === range.length) {
        b.ranges.add(range.start / range.length)
        this.size++
        return true
      }
    }

    if (this.batches.length >= MAX_REMOTE_BATCHES) {
      this.all = true
      return true
    }

    this.batches.push({
      length: range.length,
      ranges: new Set([range.start / range.length])
    })
    this.size++

    return true
  }

  remove(range) {
    if (range.any) {
      if (this.any === null) return false

      for (let i = 0; i < this.any.length; i++) {
        const a = this.any[i]

        if (a.start === range.start && a.length === range.length) {
          const head = this.any.pop()
          if (head !== a) this.any[i] = head
          return true
        }
      }

      return false
    }

    if (!validateBatchRange(range)) return false

    for (let i = 0; i < this.batches.length; i++) {
      const b = this.batches[i]
      if (b.length !== range.length) continue

      const size = b.ranges.size
      b.ranges.delete(range.start / range.length)
      if (b.ranges.size !== size) this.size--

      if (b.ranges.size === 0) {
        const head = this.batches.pop()
        if (head !== b) this.batches[i] = head
      }

      return true
    }

    return false
  }
}

function UPDATE_COMPAT(isCompat) {
  COMPAT = isCompat
  BATCH_UINTS = COMPAT ? 65536 : 128
  BATCH_BYTES = BATCH_UINTS * 4
  BATCH = BATCH_BYTES * 8 // in bits
  exports.WANT_BATCH = BATCH
}

exports.LocalWants = LocalWants
exports.RemoteWants = RemoteWants
exports.WANT_BATCH = BATCH
exports.UPDATE_COMPAT = UPDATE_COMPAT

function validateBatchRange(range) {
  if (range.length > MAX_RANGE || range.length < MIN_RANGE) {
    return false
  }
  // check if power of two
  if ((range.length & (range.length - 1)) !== 0) {
    return false
  }
  // start must be a multiple of the length
  if (range.start & (range.length - 1)) {
    return false
  }

  return true
}
{
  "name": "hypercore",
  "version": "11.28.1",
  "description": "Hypercore is a secure, distributed append-only log",
  "main": "index.js",
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "brittle test/all.js",
    "test:bare": "bare test/all.js",
    "test:generate": "brittle -r test/all.js test/*.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/hypercore.git"
  },
  "contributors": [
    {
      "name": "Mathias Buus",
      "email": "mathiasbuus@gmail.com",
      "url": "https://mafinto.sh"
    },
    {
      "name": "Andrew Osheroff",
      "email": "andrewosh@gmail.com",
      "url": "https://andrewosh.com"
    }
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/hypercore/issues"
  },
  "homepage": "https://github.com/holepunchto/hypercore#readme",
  "files": [
    "index.js",
    "errors.js",
    "messages.js",
    "lib/**.js"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "dependencies": {
    "@hyperswarm/secret-stream": "^6.0.0",
    "b4a": "^1.1.0",
    "bare-events": "^2.2.0",
    "big-sparse-array": "^1.0.3",
    "compact-encoding": "^2.11.0",
    "fast-fifo": "^1.3.0",
    "flat-tree": "^1.9.0",
    "hypercore-crypto": "^3.2.1",
    "hypercore-errors": "^1.5.0",
    "hypercore-id-encoding": "^1.2.0",
    "hypercore-storage": "^2.8.0",
    "is-options": "^1.0.1",
    "nanoassert": "^2.0.0",
    "protomux": "^3.5.0",
    "quickbit-universal": "^2.2.0",
    "random-array-iterator": "^1.0.0",
    "safety-catch": "^1.0.1",
    "sodium-universal": "^5.0.1",
    "streamx": "^2.12.4",
    "unslab": "^1.3.0",
    "z32": "^1.0.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "debugging-stream": "^3.1.0",
    "hyperswarm": "^4.3.6",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "rache": "^1.0.0",
    "range-parser": "^1.2.1",
    "resolve-reject-promise": "^1.1.0",
    "speedometer": "^1.1.0",
    "test-tmp": "^1.0.2",
    "tiny-byte-size": "^1.1.0",
    "udx-native": "^1.6.1",
    "uncaughts": "^1.1.0"
  }
}
{
  "name": "hyperschema",
  "version": "1.20.1",
  "description": "Create registries of declarative compact-encoding schemas",
  "files": [
    "lib/*.js",
    "builder.mjs",
    "builder.cjs",
    "runtime.mjs",
    "runtime.cjs",
    "primitives.mjs",
    "primitives.cjs"
  ],
  "exports": {
    "./package": "./package.json",
    ".": {
      "import": "./builder.mjs",
      "default": "./builder.cjs"
    },
    "./runtime": {
      "import": "./runtime.mjs",
      "default": "./runtime.cjs"
    },
    "./primitives": {
      "import": "./primitives.mjs",
      "default": "./primitives.cjs"
    }
  },
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    }
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test/index.js",
    "test:bare": "prettier . --check && bare test/index.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/hyperschema.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/hyperschema/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperschema#readme",
  "dependencies": {
    "bare-fs": "^4.0.1",
    "compact-encoding": "^2.19.0",
    "generate-object-property": "^2.0.0",
    "generate-string": "^1.0.1"
  },
  "devDependencies": {
    "brittle": "^3.7.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "test-tmp": "^1.3.0"
  }
}
module.exports = {
  c: require('compact-encoding')
}
const b4a = require('b4a')

const EMPTY = b4a.alloc(0)
const MAX = b4a.from([0xff])
const BUFFER = {}

BUFFER.preencode = function (state, buf) {
  if (buf === null) buf = EMPTY

  let i = 0
  let extra = 3

  while ((i = b4a.indexOf(buf, 0x00, i)) > -1) {
    i++
    extra++
  }

  state.end += buf.byteLength + extra
}

BUFFER.encode = function (state, buf) {
  if (buf === null) buf = EMPTY

  state.buffer[state.start++] = 0x00

  let prev = 0
  let i = 0

  while ((i = b4a.indexOf(buf, 0x00, i)) > -1) {
    const slice = buf.subarray(prev, ++i)

    state.buffer.set(slice, state.start)
    state.start += slice.byteLength
    state.buffer[state.start++] = 0x02
    prev = i
  }

  const slice = buf.subarray(prev)

  state.buffer.set(slice, state.start)
  state.start += slice.byteLength

  state.buffer[state.start++] = 0x00
  state.buffer[state.start++] = 0x01
}

BUFFER.decode = function (state) {
  if (state.start >= state.end) throw new Error('Out of bounds')
  if (state.buffer[state.start++] !== 0x00) {
    throw new Error('Invalid start of string')
  }

  let escaped = null

  let prev = state.start
  let i = state.start

  while ((i = b4a.indexOf(state.buffer, 0x00, i)) > -1) {
    const next = ++i < state.end ? state.buffer[i] : 0x00

    i++

    if (next === 0x01) {
      break
    }

    if (next === 0x02) {
      if (escaped === null) escaped = []
      escaped.push(state.buffer.subarray(prev, i - 1))
      prev = i
      continue
    }

    throw new Error('Unknown value in terminator')
  }

  if (i === -1) {
    throw new Error('No terminator found')
  }

  state.start = i
  const last = state.buffer.subarray(prev, i - 2)
  if (escaped === null) return last

  escaped.push(last)
  return b4a.concat(escaped)
}

// TODO: can be optimised a lot

const STRING = {}

STRING.preencode = function (state, str) {
  BUFFER.preencode(state, b4a.from(str || ''))
}

STRING.encode = function (state, str) {
  BUFFER.encode(state, b4a.from(str || ''))
}

STRING.decode = function (state, str) {
  return b4a.toString(BUFFER.decode(state))
}

const UINT = {}

UINT.preencode = function (state, n) {
  state.end += n <= 0xfb ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : n === Infinity ? 1 : 9
}

UINT.encode = function (state, n) {
  if (n === Infinity) {
    state.buffer[state.start++] = 0xff
    return
  }

  if (n <= 0xfb) {
    state.buffer[state.start++] = n
    return
  }

  if (n <= 0xffff) {
    state.buffer[state.start++] = 0xfc
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
    return
  }

  if (n <= 0xffffffff) {
    state.buffer[state.start++] = 0xfd
    encodeUint32(state, n)
    return
  }

  if (Number.isSafeInteger(n)) {
    state.buffer[state.start++] = 0xfe

    const r = Math.floor(n / 0x100000000)
    encodeUint32(state, r)
    encodeUint32(state, n)
    return
  }

  throw new Error('Invalid number ' + n)
}

UINT.decode = function (state) {
  if (state.start >= state.end) throw new Error('Out of bounds')

  const a = state.buffer[state.start++]

  if (a <= 0xfb) return a

  if (a === 0xfc) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] * 0x100 + state.buffer[state.start++]
  }

  if (a === 0xfd) {
    return decodeUint32(state)
  }

  if (a === 0xfe) {
    return decodeUint32(state) * 0x100000000 + decodeUint32(state)
  }

  return Infinity
}

const INT = {}

INT.preencode = function (state, n) {
  // One asymmetric condition
  if (n >= -0xff && n < 0) {
    state.end += 2
    return
  }
  n = Math.abs(n)
  state.end += n <= 0xf6 ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : n === Infinity ? 1 : 9
}

INT.encode = function (state, n) {
  if (n === Infinity) {
    state.buffer[state.start++] = 0xff
    return
  }

  if (n === -Infinity) {
    state.buffer[state.start++] = 0x00
    return
  }

  // Negative 64 bit
  if (n < -0xffffffff) {
    if (!Number.isSafeInteger(n)) throw new Error('Invalid number ' + n)
    state.buffer[state.start++] = 0x01

    const r = Math.floor(-n / 0x100000000)
    encodeUint32(state, -r + 0xffffffff)
    encodeUint32(state, -(-n % 0x100000000) + 0xffffffff)
    return
  }

  // Negative 32 bit
  if (n < -0xffff) {
    state.buffer[state.start++] = 0x02

    n += 0xffffffff
    encodeUint32(state, n)
    return
  }

  // Negative 16bit
  if (n < -0xff) {
    state.buffer[state.start++] = 0x03

    n += 0xffff
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
    return
  }

  // Negative 8bit
  if (n < 0) {
    state.buffer[state.start++] = 0x04

    n += 0xff
    state.buffer[state.start++] = n
    return
  }

  // Remainder of 8bit space for positive int
  if (n <= 0xf6) {
    state.buffer[state.start++] = n + 0x05
    return
  }

  // Positive 16bit
  if (n <= 0xffff) {
    state.buffer[state.start++] = 0xfc
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
    return
  }

  // Positive 32bit
  if (n <= 0xffffffff) {
    state.buffer[state.start++] = 0xfd
    encodeUint32(state, n)
    return
  }

  // Positive 64bit
  if (Number.isSafeInteger(n)) {
    state.buffer[state.start++] = 0xfe

    const r = Math.floor(n / 0x100000000)
    encodeUint32(state, r)
    encodeUint32(state, n)
    return
  }

  throw new Error('Invalid number ' + n)
}

INT.decode = function (state) {
  if (state.start >= state.end) throw new Error('Out of bounds')

  const a = state.buffer[state.start++]

  if (a === 0x00) return -Infinity

  if (a === 0x01) {
    // Split (2^64 - 1) into its 32 bit components
    // r * 0x100000000 + n - (2^64 - 1)
    // r * 0x100000000 + n - (0xffffffff * 0x100000000) - 0xffffffff
    // (r - 0xffffffff) * 0x100000000 + n - 0xffffffff
    return (decodeUint32(state) - 0xffffffff) * 0x100000000 + decodeUint32(state) - 0xffffffff
  }

  if (a === 0x02) {
    return decodeUint32(state) - 0xffffffff
  }

  if (a === 0x03) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] * 0x100 + state.buffer[state.start++] - 0xffff
  }

  if (a === 0x04) return state.buffer[state.start++] - 0xff

  if (a <= 0xfb) return a - 0x05

  if (a === 0xfc) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] * 0x100 + state.buffer[state.start++]
  }

  if (a === 0xfd) {
    return decodeUint32(state)
  }

  if (a === 0xfe) {
    return decodeUint32(state) * 0x100000000 + decodeUint32(state)
  }

  return Infinity
}

const DATE = {}

DATE.preencode = (state, d) => INT.preencode(state, d.getTime())
DATE.encode = (state, d) => INT.encode(state, d.getTime())
DATE.decode = (state) => new Date(INT.decode(state))

const BOOL = {}

BOOL.preencode = (state, b) => UINT.preencode(state, b ? 1 : 0)
BOOL.encode = (state, b) => UINT.encode(state, b ? 1 : 0)
BOOL.decode = (state) => !!UINT.decode(state)

module.exports = class IndexEncoder {
  constructor(encodings, { prefix = -1 } = {}) {
    this.encodings = encodings
    this.prefix = prefix
  }

  static BUFFER = BUFFER
  static STRING = STRING
  static UINT = UINT
  static INT = INT
  static DATE = DATE
  static BOOL = BOOL

  static lookup(c) {
    switch (c) {
      case 'uint':
        return UINT
      case 'uint8':
        return UINT
      case 'uint16':
        return UINT
      case 'uint24':
        return UINT
      case 'uint32':
        return UINT
      case 'uint40':
        return UINT
      case 'uint48':
        return UINT
      case 'uint56':
        return UINT
      case 'uint64':
        return UINT
      case 'int':
        return INT
      case 'int8':
        return INT
      case 'int16':
        return INT
      case 'int24':
        return INT
      case 'int32':
        return INT
      case 'int40':
        return INT
      case 'int48':
        return INT
      case 'int56':
        return INT
      case 'int64':
        return INT
      case 'string':
        return STRING
      case 'utf8':
        return STRING
      case 'ascii':
        return STRING
      case 'hex':
        return STRING
      case 'base64':
        return STRING
      case 'fixed32':
        return BUFFER
      case 'fixed64':
        return BUFFER
      case 'buffer':
        return BUFFER
      case 'date':
        return DATE
      case 'bool':
        return BOOL
    }

    throw new Error('Unknown type')
  }

  encode(keys) {
    return this._encode(keys, false)
  }

  _encode(keys, terminate) {
    if (b4a.isBuffer(keys)) return keys

    const state = { start: 0, end: 0, buffer: null }

    if (this.prefix !== -1) UINT.preencode(state, this.prefix)
    for (let i = 0; i < keys.length; i++) {
      this.encodings[i].preencode(state, keys[i])
    }

    if (terminate && keys.length < this.encodings.length) {
      state.end++
    }

    state.buffer = b4a.allocUnsafe(state.end)

    if (this.prefix !== -1) UINT.encode(state, this.prefix)
    for (let i = 0; i < keys.length; i++) {
      this.encodings[i].encode(state, keys[i])
    }

    if (terminate && keys.length < this.encodings.length) {
      state.buffer[state.start++] = MAX[0]
    }

    return state.buffer
  }

  decode(buffer) {
    const state = { start: 0, end: buffer.byteLength, buffer }
    const result = []

    if (this.prefix !== -1) UINT.decode(state)
    for (const enc of this.encodings) {
      const key = state.start < state.end ? enc.decode(state) : enc === UINT ? 0 : null
      result.push(key)
    }

    return result
  }

  encodeRange({ gt, gte, lt, lte }) {
    const range = {
      gt: gt && this._encode(gt, true),
      gte: gte && this._encode(gte, false),
      lt: lt && this._encode(lt, false),
      lte: lte && this._encode(lte, true)
    }

    if (this.prefix !== -1) {
      if (!gt && !gte) range.gte = encodeUint(this.prefix)
      if (!lt && !lte) range.lt = encodeUint(this.prefix + 1)
    }

    return range
  }
}

function encodeUint(n) {
  const state = { start: 0, end: 0, buffer: null }
  UINT.preencode(state, n)
  state.buffer = b4a.allocUnsafe(state.end)
  UINT.encode(state, n)
  return state.buffer
}

function encodeUint32(state, n) {
  state.buffer[state.start++] = n >>> 24
  state.buffer[state.start++] = n >>> 16
  state.buffer[state.start++] = n >>> 8
  state.buffer[state.start++] = n
}

function decodeUint32(state) {
  if (state.end - state.start < 4) throw new Error('Out of bounds')
  return (
    state.buffer[state.start++] * 0x1000000 +
    state.buffer[state.start++] * 0x10000 +
    state.buffer[state.start++] * 0x100 +
    state.buffer[state.start++]
  )
}
{
  "name": "index-encoder",
  "version": "3.5.0",
  "description": "Encode multiple values into sorted keys",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.6.4"
  },
  "devDependencies": {
    "brittle": "^3.2.1",
    "hyperbee": "^2.10.5",
    "hypercore": "^11.0.0",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/index-encoder.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/index-encoder/issues"
  },
  "homepage": "https://github.com/holepunchto/index-encoder"
}
const b4a = require('b4a')

module.exports = function isOptions (opts) {
  return typeof opts === 'object' && opts && !b4a.isBuffer(opts)
}
{
  "name": "is-options",
  "version": "1.0.2",
  "description": "Easily check if input is an options map",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.1.1"
  },
  "devDependencies": {
    "standard": "^11.0.1",
    "tape": "^4.9.0"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/is-options.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/is-options/issues"
  },
  "homepage": "https://github.com/mafintosh/is-options"
}
var queueTick = require('queue-tick')

var mutexify = function () {
  var queue = []
  var used = null

  var call = function () {
    used(release)
  }

  var acquire = function (fn) {
    if (used) return queue.push(fn)
    used = fn
    acquire.locked = true
    queueTick(call)
    return 0
  }

  acquire.locked = false

  var release = function (fn, err, value) {
    used = null
    acquire.locked = false
    if (queue.length) acquire(queue.shift())
    if (fn) fn(err, value)
  }

  return acquire
}

module.exports = mutexify
{
  "name": "mutexify",
  "version": "1.4.0",
  "description": "mutex lock for javascript",
  "main": "index.js",
  "dependencies": {
    "queue-tick": "^1.0.0"
  },
  "devDependencies": {
    "standard": "^14.3.3",
    "tape": "^3.0.2"
  },
  "scripts": {
    "test": "tape test.js",
    "posttest": "npm run lint",
    "lint": "standard"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/mutexify.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/mutexify/issues"
  },
  "keywords": [
    "mutex",
    "lock"
  ],
  "homepage": "https://github.com/mafintosh/mutexify"
}
var mutexify = require('.')

var mutexifyPromise = function () {
  var lock = mutexify()

  var acquire = function () {
    return new Promise(lock)
  }

  Object.defineProperty(acquire, 'locked', {
    get: function () { return lock.locked },
    enumerable: true
  })

  return acquire
}

module.exports = mutexifyPromise
module.exports = assert

class AssertionError extends Error {}
AssertionError.prototype.name = 'AssertionError'

/**
 * Minimal assert function
 * @param  {any} t Value to check if falsy
 * @param  {string=} m Optional assertion error message
 * @throws {AssertionError}
 */
function assert (t, m) {
  if (!t) {
    var err = new AssertionError(m)
    if (Error.captureStackTrace) Error.captureStackTrace(err, assert)
    throw err
  }
}
{
  "name": "nanoassert",
  "version": "2.0.0",
  "description": "Nanoscale assertion module",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "tape": "^4.9.1"
  },
  "scripts": {
    "test": "tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/emilbayes/nanoassert.git"
  },
  "keywords": [
    "assert",
    "unassert",
    "power-assert",
    "tiny",
    "nano",
    "pico"
  ],
  "author": "Emil Bay <github@tixz.dk>",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/emilbayes/nanoassert/issues"
  },
  "homepage": "https://github.com/emilbayes/nanoassert#readme"
}
/* eslint-disable camelcase */
const sodium = require('sodium-universal')
const assert = require('nanoassert')
const b4a = require('b4a')

const DHLEN = sodium.crypto_scalarmult_ed25519_BYTES
const PKLEN = sodium.crypto_scalarmult_ed25519_BYTES
const SCALARLEN = sodium.crypto_scalarmult_ed25519_BYTES
const SKLEN = sodium.crypto_sign_SECRETKEYBYTES
const ALG = 'Ed25519'

module.exports = {
  DHLEN,
  PKLEN,
  SCALARLEN,
  SKLEN,
  ALG,
  name: ALG,
  generateKeyPair,
  dh
}

function generateKeyPair (privKey) {
  if (privKey) return generateSeedKeyPair(privKey.subarray(0, 32))

  const keyPair = {}
  keyPair.secretKey = b4a.alloc(SKLEN)
  keyPair.publicKey = b4a.alloc(PKLEN)

  sodium.crypto_sign_keypair(keyPair.publicKey, keyPair.secretKey)
  return keyPair
}

function generateSeedKeyPair (seed) {
  const keyPair = {}
  keyPair.secretKey = b4a.alloc(SKLEN)
  keyPair.publicKey = b4a.alloc(PKLEN)

  sodium.crypto_sign_seed_keypair(keyPair.publicKey, keyPair.secretKey, seed)
  return keyPair
}

function dh (publicKey, { scalar, secretKey }) {
  // tweaked keys expose scalar directly
  if (!scalar) {
    assert(secretKey.byteLength === SKLEN)

    // libsodium stores seed not actual scalar
    const sk = b4a.alloc(64)
    sodium.crypto_hash_sha512(sk, secretKey.subarray(0, 32))
    sk[0] &= 248
    sk[31] &= 127
    sk[31] |= 64

    scalar = sk.subarray(0, 32)
  }

  assert(scalar.byteLength === SCALARLEN)
  assert(publicKey.byteLength === PKLEN)

  const output = b4a.alloc(DHLEN)

  // we clamp if necessary above
  sodium.crypto_scalarmult_ed25519_noclamp(
    output,
    scalar,
    publicKey
  )

  return output
}
{
  "name": "noise-curve-ed",
  "version": "2.1.0",
  "description": "Ed25519 elliptic curve operations for [`noise-handshake`](https://github.com/chm-diederichs/noise-handshake)",
  "main": "index.js",
  "scripts": {
    "test": "npx standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/chm-diederichs/noise-curve-ed.git"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/chm-diederichs/noise-curve-ed/issues"
  },
  "homepage": "https://github.com/chm-diederichs/noise-curve-ed#readme",
  "dependencies": {
    "b4a": "^1.1.0",
    "nanoassert": "^2.0.0",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "noise-handshake": "^3.0.0",
    "standard": "^16.0.3",
    "tape": "^5.2.2"
  }
}
const sodium = require('sodium-universal')
const b4a = require('b4a')

module.exports = class CipherState {
  constructor (key) {
    this.key = key || null
    this.nonce = 0
    this.CIPHER_ALG = 'ChaChaPoly'
  }

  initialiseKey (key) {
    this.key = key
    this.nonce = 0
  }

  setNonce (nonce) {
    this.nonce = nonce
  }

  encrypt (plaintext, ad) {
    if (!this.hasKey) return plaintext
    if (!ad) ad = b4a.alloc(0)

    const ciphertext = encryptWithAD(this.key, this.nonce, ad, plaintext)
    if (ciphertext.length > 65535) throw new Error(`ciphertext length of ${ciphertext.length} exceeds maximum Noise message length of 65535`)
    this.nonce++

    return ciphertext
  }

  decrypt (ciphertext, ad) {
    if (!this.hasKey) return ciphertext
    if (!ad) ad = b4a.alloc(0)
    if (ciphertext.length > 65535) throw new Error(`ciphertext length of ${ciphertext.length} exceeds maximum Noise message length of 65535`)

    const plaintext = decryptWithAD(this.key, this.nonce, ad, ciphertext)
    this.nonce++

    return plaintext
  }

  get hasKey () {
    return this.key !== null
  }

  _clear () {
    sodium.sodium_memzero(this.key)
    this.key = null
    this.nonce = null
  }

  static get MACBYTES () {
    return 16
  }

  static get NONCEBYTES () {
    return 8
  }

  static get KEYBYTES () {
    return 32
  }
}

function encryptWithAD (key, counter, additionalData, plaintext) {
  // for our purposes, additionalData will always be a pubkey so we encode from hex
  if (!b4a.isBuffer(additionalData)) additionalData = b4a.from(additionalData, 'hex')
  if (!b4a.isBuffer(plaintext)) plaintext = b4a.from(plaintext, 'hex')

  const nonce = b4a.alloc(sodium.crypto_aead_chacha20poly1305_ietf_NPUBBYTES)
  const view = new DataView(nonce.buffer, nonce.byteOffset, nonce.byteLength)
  view.setUint32(4, counter, true)

  const ciphertext = b4a.alloc(plaintext.byteLength + sodium.crypto_aead_chacha20poly1305_ietf_ABYTES)

  sodium.crypto_aead_chacha20poly1305_ietf_encrypt(ciphertext, plaintext, additionalData, null, nonce, key)
  return ciphertext
}

function decryptWithAD (key, counter, additionalData, ciphertext) {
  // for our purposes, additionalData will always be a pubkey so we encode from hex
  if (!b4a.isBuffer(additionalData)) additionalData = b4a.from(additionalData, 'hex')
  if (!b4a.isBuffer(ciphertext)) ciphertext = b4a.from(ciphertext, 'hex')

  const nonce = b4a.alloc(sodium.crypto_aead_chacha20poly1305_ietf_NPUBBYTES)
  const view = new DataView(nonce.buffer, nonce.byteOffset, nonce.byteLength)
  view.setUint32(4, counter, true)

  const plaintext = b4a.alloc(ciphertext.byteLength - sodium.crypto_aead_chacha20poly1305_ietf_ABYTES)

  sodium.crypto_aead_chacha20poly1305_ietf_decrypt(plaintext, null, ciphertext, additionalData, nonce, key)
  return plaintext
}
/* eslint-disable camelcase */
const {
  crypto_kx_SEEDBYTES,
  crypto_kx_keypair,
  crypto_kx_seed_keypair,
  crypto_scalarmult_BYTES,
  crypto_scalarmult_SCALARBYTES,
  crypto_scalarmult,
  crypto_scalarmult_base
} = require('sodium-universal')

const assert = require('nanoassert')
const b4a = require('b4a')

const DHLEN = crypto_scalarmult_BYTES
const PKLEN = crypto_scalarmult_BYTES
const SKLEN = crypto_scalarmult_SCALARBYTES
const SEEDLEN = crypto_kx_SEEDBYTES
const ALG = '25519'

module.exports = {
  DHLEN,
  PKLEN,
  SKLEN,
  SEEDLEN,
  ALG,
  generateKeyPair,
  generateSeedKeyPair,
  dh
}

function generateKeyPair (privKey) {
  const keyPair = {}

  keyPair.secretKey = privKey || b4a.alloc(SKLEN)
  keyPair.publicKey = b4a.alloc(PKLEN)

  if (privKey) {
    crypto_scalarmult_base(keyPair.publicKey, keyPair.secretKey)
  } else {
    crypto_kx_keypair(keyPair.publicKey, keyPair.secretKey)
  }

  return keyPair
}

function generateSeedKeyPair (seed) {
  assert(seed.byteLength === SKLEN)

  const keyPair = {}
  keyPair.secretKey = b4a.alloc(SKLEN)
  keyPair.publicKey = b4a.alloc(PKLEN)

  crypto_kx_seed_keypair(keyPair.publicKey, keyPair.secretKey, seed)
  return keyPair
}

function dh (publicKey, { secretKey }) {
  assert(secretKey.byteLength === SKLEN)
  assert(publicKey.byteLength === PKLEN)

  const output = b4a.alloc(DHLEN)

  crypto_scalarmult(
    output,
    secretKey,
    publicKey
  )

  return output
}
const hmacBlake2b = require('./hmac')
const b4a = require('b4a')

const HASHLEN = 64

module.exports = {
  hkdf,
  HASHLEN
}

// HMAC-based Extract-and-Expand KDF
// https://www.ietf.org/rfc/rfc5869.txt

function hkdf (salt, inputKeyMaterial, info = '', length = 2 * HASHLEN) {
  const pseudoRandomKey = hkdfExtract(salt, inputKeyMaterial)
  return hkdfExpand(pseudoRandomKey, info, length)
}

function hkdfExtract (salt, inputKeyMaterial) {
  const hmac = b4a.alloc(HASHLEN)
  return hmacDigest(hmac, salt, inputKeyMaterial)
}

function hkdfExpand (key, info, length) {
  // Put in dedicated slab to avoid keeping shared slab from being gc'ed
  const buffer = b4a.allocUnsafeSlow(length)

  const infoBuf = b4a.from(info)
  let prev = infoBuf

  const result = []
  for (let i = 0; i < length; i += HASHLEN) {
    const pos = b4a.from([(i / HASHLEN) + 1])

    const out = buffer.subarray(i, i + HASHLEN)
    result.push(out)

    prev = hmacDigest(out, key, [prev, infoBuf, pos])
  }

  return result
}

function hmacDigest (out, key, input) {
  hmacBlake2b(out, input, key)
  return out
}
/* eslint-disable camelcase */
const b4a = require('b4a')
const { sodium_memzero, crypto_generichash, crypto_generichash_batch } = require('sodium-universal')

const HASHLEN = 64
const BLOCKLEN = 128
const scratch = b4a.alloc(BLOCKLEN * 3)
const HMACKey = scratch.subarray(BLOCKLEN * 0, BLOCKLEN * 1)
const OuterKeyPad = scratch.subarray(BLOCKLEN * 1, BLOCKLEN * 2)
const InnerKeyPad = scratch.subarray(BLOCKLEN * 2, BLOCKLEN * 3)

// Post-fill is done in the cases where someone caught an exception that
// happened before we were able to clear data at the end

module.exports = function hmac (out, batch, key) {
  if (key.byteLength > BLOCKLEN) {
    crypto_generichash(HMACKey.subarray(0, HASHLEN), key)
    sodium_memzero(HMACKey.subarray(HASHLEN))
  } else {
    // Covers key <= BLOCKLEN
    HMACKey.set(key)
    sodium_memzero(HMACKey.subarray(key.byteLength))
  }

  for (let i = 0; i < HMACKey.byteLength; i++) {
    OuterKeyPad[i] = 0x5c ^ HMACKey[i]
    InnerKeyPad[i] = 0x36 ^ HMACKey[i]
  }
  sodium_memzero(HMACKey)

  crypto_generichash_batch(out, [InnerKeyPad].concat(batch))
  sodium_memzero(InnerKeyPad)
  crypto_generichash_batch(out, [OuterKeyPad, out])
  sodium_memzero(OuterKeyPad)
}

module.exports.BYTES = HASHLEN
module.exports.KEYBYTES = BLOCKLEN
const assert = require('nanoassert')
const b4a = require('b4a')

const SymmetricState = require('./symmetric-state')
const { HASHLEN } = require('./hkdf')

const PRESHARE_IS = Symbol('initiator static key preshared')
const PRESHARE_RS = Symbol('responder static key preshared')

const TOK_PSK = Symbol('psk')

const TOK_S = Symbol('s')
const TOK_E = Symbol('e')

const TOK_ES = Symbol('es')
const TOK_SE = Symbol('se')
const TOK_EE = Symbol('ee')
const TOK_SS = Symbol('ss')

const HANDSHAKES = Object.freeze({
  NN: [
    [TOK_E],
    [TOK_E, TOK_EE]
  ],
  NNpsk0: [
    [TOK_PSK, TOK_E],
    [TOK_E, TOK_EE]
  ],
  XX: [
    [TOK_E],
    [TOK_E, TOK_EE, TOK_S, TOK_ES],
    [TOK_S, TOK_SE]
  ],
  XXpsk0: [
    [TOK_PSK, TOK_E],
    [TOK_E, TOK_EE, TOK_S, TOK_ES],
    [TOK_S, TOK_SE]
  ],
  IK: [
    PRESHARE_RS,
    [TOK_E, TOK_ES, TOK_S, TOK_SS],
    [TOK_E, TOK_EE, TOK_SE]
  ],
  XK: [
    PRESHARE_RS,
    [TOK_E, TOK_ES],
    [TOK_E, TOK_EE],
    [TOK_S, TOK_SE]
  ]
})

class Writer {
  constructor () {
    this.size = 0
    this.buffers = []
  }

  push (b) {
    this.size += b.byteLength
    this.buffers.push(b)
  }

  end () {
    const all = b4a.alloc(this.size)
    let offset = 0
    for (const b of this.buffers) {
      all.set(b, offset)
      offset += b.byteLength
    }
    return all
  }
}

class Reader {
  constructor (buf) {
    this.offset = 0
    this.buffer = buf
  }

  shift (n) {
    const start = this.offset
    const end = this.offset += n
    if (end > this.buffer.byteLength) throw new Error('Insufficient bytes')
    return this.buffer.subarray(start, end)
  }

  end () {
    return this.shift(this.buffer.byteLength - this.offset)
  }
}

module.exports = class NoiseState extends SymmetricState {
  constructor (pattern, initiator, staticKeypair, opts = {}) {
    super(opts)

    this.s = staticKeypair || this.curve.generateKeyPair()
    this.e = null

    this.psk = null
    if (opts && opts.psk) this.psk = opts.psk

    this.re = null
    this.rs = null

    this.pattern = pattern
    this.handshake = HANDSHAKES[this.pattern].slice()

    this.isPskHandshake = !!this.psk && hasPskToken(this.handshake)

    this.protocol = b4a.from([
      'Noise',
      this.pattern,
      this.DH_ALG,
      this.CIPHER_ALG,
      'BLAKE2b'
    ].join('_'))

    this.initiator = initiator
    this.complete = false

    this.rx = null
    this.tx = null
    this.hash = null
  }

  initialise (prologue, remoteStatic) {
    if (this.protocol.byteLength <= HASHLEN) this.digest.set(this.protocol)
    else this.mixHash(this.protocol)

    this.chainingKey = b4a.from(this.digest)

    this.mixHash(prologue)

    while (!Array.isArray(this.handshake[0])) {
      const message = this.handshake.shift()

      // handshake steps should be as arrays, only
      // preshare tokens are provided otherwise
      assert(message === PRESHARE_RS || message === PRESHARE_IS,
        'Unexpected pattern')

      const takeRemoteKey = this.initiator
        ? message === PRESHARE_RS
        : message === PRESHARE_IS

      if (takeRemoteKey) this.rs = remoteStatic

      const key = takeRemoteKey ? this.rs : this.s.publicKey
      assert(key != null, 'Remote pubkey required')

      this.mixHash(key)
    }
  }

  final () {
    const [k1, k2] = this.split()

    this.tx = this.initiator ? k1 : k2
    this.rx = this.initiator ? k2 : k1

    this.complete = true
    this.hash = this.getHandshakeHash()

    this._clear()
  }

  recv (buf) {
    const r = new Reader(buf)

    for (const pattern of this.handshake.shift()) {
      switch (pattern) {
        case TOK_PSK :
          this.mixKeyAndHash(this.psk)
          break

        case TOK_E :
          this.re = r.shift(this.curve.PKLEN)
          this.mixHash(this.re)
          if (this.isPskHandshake) this.mixKeyNormal(this.re)
          break

        case TOK_S : {
          const klen = this.hasKey ? this.curve.PKLEN + 16 : this.curve.PKLEN
          this.rs = this.decryptAndHash(r.shift(klen))
          break
        }

        case TOK_EE :
        case TOK_ES :
        case TOK_SE :
        case TOK_SS : {
          const useStatic = keyPattern(pattern, this.initiator)

          const localKey = useStatic.local ? this.s : this.e
          const remoteKey = useStatic.remote ? this.rs : this.re

          this.mixKey(remoteKey, localKey)
          break
        }

        default :
          throw new Error('Unexpected message')
      }
    }

    const payload = this.decryptAndHash(r.end())

    if (!this.handshake.length) this.final()
    return payload
  }

  send (payload = b4a.alloc(0)) {
    const w = new Writer()

    for (const pattern of this.handshake.shift()) {
      switch (pattern) {
        case TOK_PSK :
          this.mixKeyAndHash(this.psk)
          break

        case TOK_E :
          if (this.e === null) this.e = this.curve.generateKeyPair()
          this.mixHash(this.e.publicKey)
          if (this.isPskHandshake) this.mixKeyNormal(this.e.publicKey)
          w.push(this.e.publicKey)
          break

        case TOK_S :
          w.push(this.encryptAndHash(this.s.publicKey))
          break

        case TOK_ES :
        case TOK_SE :
        case TOK_EE :
        case TOK_SS : {
          const useStatic = keyPattern(pattern, this.initiator)

          const localKey = useStatic.local ? this.s : this.e
          const remoteKey = useStatic.remote ? this.rs : this.re

          this.mixKey(remoteKey, localKey)
          break
        }

        default :
          throw new Error('Unexpected message')
      }
    }

    w.push(this.encryptAndHash(payload))
    const response = w.end()

    if (!this.handshake.length) this.final()
    return response
  }

  _clear () {
    super._clear()

    this.e.secretKey.fill(0)
    this.e.publicKey.fill(0)

    this.re.fill(0)

    this.e = null
    this.re = null
  }
}

function keyPattern (pattern, initiator) {
  const ret = {
    local: false,
    remote: false
  }

  switch (pattern) {
    case TOK_EE:
      return ret

    case TOK_ES:
      ret.local ^= !initiator
      ret.remote ^= initiator
      return ret

    case TOK_SE:
      ret.local ^= initiator
      ret.remote ^= !initiator
      return ret

    case TOK_SS:
      ret.local ^= 1
      ret.remote ^= 1
      return ret
  }
}

function hasPskToken (handshake) {
  return handshake.some(x => {
    return Array.isArray(x) && x.indexOf(TOK_PSK) !== -1
  })
}
{
  "name": "noise-handshake",
  "version": "4.2.0",
  "description": "Noise protocol handshake",
  "main": "noise.js",
  "files": [
    "*.js"
  ],
  "scripts": {
    "test": "standard && brittle test/*.js"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/noise-handshake.git"
  },
  "dependencies": {
    "b4a": "^1.1.0",
    "nanoassert": "^2.0.0",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "noise-protocol": "chm-diederichs/noise-protocol.git#xx-ephemeral-key",
    "standard": "^16.0.3"
  }
}
const sodium = require('sodium-universal')
const assert = require('nanoassert')
const b4a = require('b4a')
const CipherState = require('./cipher')
const curve = require('./dh')
const { HASHLEN, hkdf } = require('./hkdf')

module.exports = class SymmetricState extends CipherState {
  constructor (opts = {}) {
    super()

    this.curve = opts.curve || curve
    this.digest = b4a.alloc(HASHLEN)
    this.chainingKey = null
    this.offset = 0

    this.DH_ALG = this.curve.ALG
  }

  mixHash (data) {
    accumulateDigest(this.digest, data)
  }

  mixKeyAndHash (key) {
    const [ck, tempH, tempK] = hkdf(this.chainingKey, key, '', 3 * HASHLEN)
    this.chainingKey = ck
    this.mixHash(tempH)
    this.initialiseKey(tempK.subarray(0, 32))
  }

  mixKeyNormal (key) {
    const [ck, tempK] = hkdf(this.chainingKey, key)
    this.chainingKey = ck
    this.initialiseKey(tempK.subarray(0, 32))
  }

  mixKey (remoteKey, localKey) {
    const dh = this.curve.dh(remoteKey, localKey)
    const hkdfResult = hkdf(this.chainingKey, dh)
    this.chainingKey = hkdfResult[0]
    this.initialiseKey(hkdfResult[1].subarray(0, 32))
  }

  encryptAndHash (plaintext) {
    const ciphertext = this.encrypt(plaintext, this.digest)
    accumulateDigest(this.digest, ciphertext)
    return ciphertext
  }

  decryptAndHash (ciphertext) {
    const plaintext = this.decrypt(ciphertext, this.digest)
    accumulateDigest(this.digest, ciphertext)
    return plaintext
  }

  getHandshakeHash (out) {
    if (!out) return this.getHandshakeHash(b4a.alloc(HASHLEN))
    assert(out.byteLength === HASHLEN, `output must be ${HASHLEN} bytes`)

    out.set(this.digest)
    return out
  }

  split () {
    const res = hkdf(this.chainingKey, b4a.alloc(0))
    return res.map(k => k.subarray(0, 32))
  }

  _clear () {
    super._clear()

    sodium.sodium_memzero(this.digest)
    sodium.sodium_memzero(this.chainingKey)

    this.digest = null
    this.chainingKey = null
    this.offset = null

    this.curve = null
  }

  static get alg () {
    return CipherState.alg + '_BLAKE2b'
  }
}

function accumulateDigest (digest, input) {
  const toHash = b4a.concat([digest, input])
  sodium.crypto_generichash(digest, toHash)
}
var varint = require('varint')
var svarint = require('signed-varint')
var b4a = require('b4a')

exports.make = encoder

exports.name = function (enc) {
  var keys = Object.keys(exports)
  for (var i = 0; i < keys.length; i++) {
    if (exports[keys[i]] === enc) return keys[i]
  }
  return null
}

exports.skip = function (type, buffer, offset) {
  switch (type) {
    case 0:
      varint.decode(buffer, offset)
      return offset + varint.decode.bytes

    case 1:
      return offset + 8

    case 2:
      var len = varint.decode(buffer, offset)
      return offset + varint.decode.bytes + len

    case 3:
    case 4:
      throw new Error('Groups are not supported')

    case 5:
      return offset + 4
  }

  throw new Error('Unknown wire type: ' + type)
}

exports.bytes = encoder(2,
  function encode (val, buffer, offset) {
    var oldOffset = offset
    var len = bufferLength(val)

    varint.encode(len, buffer, offset)
    offset += varint.encode.bytes

    if (b4a.isBuffer(val)) b4a.copy(val, buffer, offset)
    else b4a.write(buffer, val, offset, len)
    offset += len

    encode.bytes = offset - oldOffset
    return buffer
  },
  function decode (buffer, offset) {
    var oldOffset = offset

    var len = varint.decode(buffer, offset)
    offset += varint.decode.bytes

    var val = buffer.subarray(offset, offset + len)
    offset += val.length

    decode.bytes = offset - oldOffset
    return val
  },
  function encodingLength (val) {
    var len = bufferLength(val)
    return varint.encodingLength(len) + len
  }
)

exports.string = encoder(2,
  function encode (val, buffer, offset) {
    var oldOffset = offset
    var len = b4a.byteLength(val)

    varint.encode(len, buffer, offset, 'utf-8')
    offset += varint.encode.bytes

    b4a.write(buffer, val, offset, len)
    offset += len

    encode.bytes = offset - oldOffset
    return buffer
  },
  function decode (buffer, offset) {
    var oldOffset = offset

    var len = varint.decode(buffer, offset)
    offset += varint.decode.bytes

    var val = b4a.toString(buffer, 'utf-8', offset, offset + len)
    offset += len

    decode.bytes = offset - oldOffset
    return val
  },
  function encodingLength (val) {
    var len = b4a.byteLength(val)
    return varint.encodingLength(len) + len
  }
)

exports.bool = encoder(0,
  function encode (val, buffer, offset) {
    buffer[offset] = val ? 1 : 0
    encode.bytes = 1
    return buffer
  },
  function decode (buffer, offset) {
    var bool = buffer[offset] > 0
    decode.bytes = 1
    return bool
  },
  function encodingLength () {
    return 1
  }
)

exports.int32 = encoder(0,
  function encode (val, buffer, offset) {
    varint.encode(val < 0 ? val + 4294967296 : val, buffer, offset)
    encode.bytes = varint.encode.bytes
    return buffer
  },
  function decode (buffer, offset) {
    var val = varint.decode(buffer, offset)
    decode.bytes = varint.decode.bytes
    return val > 2147483647 ? val - 4294967296 : val
  },
  function encodingLength (val) {
    return varint.encodingLength(val < 0 ? val + 4294967296 : val)
  }
)

exports.int64 = encoder(0,
  function encode (val, buffer, offset) {
    if (val < 0) {
      var last = offset + 9
      varint.encode(val * -1, buffer, offset)
      offset += varint.encode.bytes - 1
      buffer[offset] = buffer[offset] | 0x80
      while (offset < last - 1) {
        offset++
        buffer[offset] = 0xff
      }
      buffer[last] = 0x01
      encode.bytes = 10
    } else {
      varint.encode(val, buffer, offset)
      encode.bytes = varint.encode.bytes
    }
    return buffer
  },
  function decode (buffer, offset) {
    var val = varint.decode(buffer, offset)
    if (val >= Math.pow(2, 63)) {
      var limit = 9
      while (buffer[offset + limit - 1] === 0xff) limit--
      limit = limit || 9
      var subset = b4a.allocUnsafe(limit)
      b4a.copy(buffer, subset, 0, offset, offset + limit)
      subset[limit - 1] = subset[limit - 1] & 0x7f
      val = -1 * varint.decode(subset, 0)
      decode.bytes = 10
    } else {
      decode.bytes = varint.decode.bytes
    }
    return val
  },
  function encodingLength (val) {
    return val < 0 ? 10 : varint.encodingLength(val)
  }
)

exports.sint32 =
exports.sint64 = encoder(0,
  svarint.encode,
  svarint.decode,
  svarint.encodingLength
)

exports.uint32 =
exports.uint64 =
exports.enum =
exports.varint = encoder(0,
  varint.encode,
  varint.decode,
  varint.encodingLength
)

// we cannot represent these in javascript so we just use buffers
exports.fixed64 =
exports.sfixed64 = encoder(1,
  function encode (val, buffer, offset) {
    b4a.copy(val, buffer, offset)
    encode.bytes = 8
    return buffer
  },
  function decode (buffer, offset) {
    var val = buffer.subarray(offset, offset + 8)
    decode.bytes = 8
    return val
  },
  function encodingLength () {
    return 8
  }
)

exports.double = encoder(1,
  function encode (val, buffer, offset) {
    b4a.writeDoubleLE(buffer, val, offset)
    encode.bytes = 8
    return buffer
  },
  function decode (buffer, offset) {
    var val = b4a.readDoubleLE(buffer, offset)
    decode.bytes = 8
    return val
  },
  function encodingLength () {
    return 8
  }
)

exports.fixed32 = encoder(5,
  function encode (val, buffer, offset) {
    b4a.writeUInt32LE(buffer, val, offset)
    encode.bytes = 4
    return buffer
  },
  function decode (buffer, offset) {
    var val = b4a.readUInt32LE(buffer, offset)
    decode.bytes = 4
    return val
  },
  function encodingLength () {
    return 4
  }
)

exports.sfixed32 = encoder(5,
  function encode (val, buffer, offset) {
    b4a.writeInt32LE(buffer, val, offset)
    encode.bytes = 4
    return buffer
  },
  function decode (buffer, offset) {
    var val = b4a.readInt32LE(buffer, offset)
    decode.bytes = 4
    return val
  },
  function encodingLength () {
    return 4
  }
)

exports.float = encoder(5,
  function encode (val, buffer, offset) {
    b4a.writeFloatLE(buffer, val, offset)
    encode.bytes = 4
    return buffer
  },
  function decode (buffer, offset) {
    var val = b4a.readFloatLE(buffer, offset)
    decode.bytes = 4
    return val
  },
  function encodingLength () {
    return 4
  }
)

function encoder (type, encode, decode, encodingLength) {
  encode.bytes = decode.bytes = 0

  return {
    type: type,
    encode: encode,
    decode: decode,
    encodingLength: encodingLength
  }
}

function bufferLength (val) {
  return b4a.isBuffer(val) ? val.length : b4a.byteLength(val)
}
{
  "name": "protocol-buffers-encodings",
  "version": "1.2.0",
  "description": "Base encodings for protocol-buffers",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.6.0",
    "signed-varint": "^2.0.1",
    "varint": "5.0.0"
  },
  "devDependencies": {
    "standard": "^14.3.4",
    "tape": "^5.0.1"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/protocol-buffers-encodings.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/protocol-buffers-encodings/issues"
  },
  "homepage": "https://github.com/mafintosh/protocol-buffers-encodings"
}
const crypto = require('hypercore-crypto')
const Protomux = require('protomux')
const b4a = require('b4a')
const schema = require('./spec/hyperschema')

const [NS_INITATOR, NS_RESPONDER] = crypto.namespace('wakeup', 2)

const Handshake = schema.getEncoding('@wakeup/handshake')
const Announce = schema.getEncoding('@wakeup/announce')
const Lookup = schema.getEncoding('@wakeup/lookup')
const Info = schema.getEncoding('@wakeup/info')

module.exports = class WakeupSwarm {
  constructor(onwakeup = noop, { gcTickTime = 2000 } = {}) {
    this.gcTickTime = gcTickTime

    this.topics = new Map()
    this.topicsGC = new Set()
    this.muxers = new Set()
    this.stats = {
      sessionsOpened: 0,
      sessionsClosed: 0,
      topicsAdded: 0,
      topicsGcd: 0,
      peersAdded: 0,
      peersRemoved: 0,
      wireAnnounce: { rx: 0, tx: 0 },
      wireLookup: { rx: 0, tx: 0 },
      wireInfo: { rx: 0, tx: 0 }
    }

    this.onwakeup = onwakeup

    this._gcInterval = null
    this._gcBound = this._gc.bind(this)
  }

  session(capability, handlers = {}) {
    const id = handlers.discoveryKey || crypto.discoveryKey(capability)
    const active = handlers.active !== false
    const hex = b4a.toString(id, 'hex')

    let w = this.topics.get(hex)

    if (w) return w.addSession(handlers)

    w = new WakeupTopic(this, id, capability, active)

    this.topics.set(hex, w)

    for (const muxer of this.muxers) {
      w._onopen(muxer, true)
    }

    return w.addSession(handlers)
  }

  getSessions(capability, handlers = {}) {
    const id = handlers.discoveryKey || crypto.discoveryKey(capability)
    const hex = b4a.toString(id, 'hex')
    const w = this.topics.get(hex)
    return w ? w.sessions : []
  }

  hasStream(stream, capability, handlers = {}) {
    if (!capability) {
      const noiseStream = stream.noiseStream || stream
      return this.muxers.has(getMuxer(noiseStream))
    }

    const id = handlers.discoveryKey || crypto.discoveryKey(capability)
    const hex = b4a.toString(id, 'hex')
    const t = this.topics.get(hex)

    return t ? t.peersByStream.has(stream) : false
  }

  addStream(stream) {
    const noiseStream = stream.noiseStream || stream

    if (!noiseStream.connected) {
      noiseStream.once('open', this.addStream.bind(this, noiseStream))
      return
    }

    const muxer = getMuxer(noiseStream)
    muxer.pair({ protocol: 'wakeup' }, (id) => this._onpair(id, muxer))

    this.muxers.add(muxer)
    noiseStream.on('close', () => this.muxers.delete(muxer))

    for (const w of this.topics.values()) {
      if (!w.isActive) continue
      w._onopen(muxer, true)
    }
  }

  _onActive(w) {
    for (const m of this.muxers) {
      w._onopen(m, false)
    }
  }

  _addGC(topic) {
    if (topic.destroyed) return
    this.topicsGC.add(topic)
    if (this._gcInterval === null) {
      this._gcInterval = setInterval(this._gcBound, this.gcTickTime)
    }
  }

  _removeGC(topic) {
    this.topicsGC.delete(topic)
    if (this.topicsGC.size === 0 && this._gcInterval) {
      clearInterval(this._gcInterval)
      this._gcInterval = null
    }
  }

  _gc() {
    const destroy = []
    for (const w of this.topicsGC) {
      w.idleTicks++
      if (w.idleTicks >= 5) destroy.push(w)
    }
    for (const w of destroy) w.teardown()
  }

  destroy() {
    if (this._gcInterval) clearInterval(this._gcInterval)
    this._gcInterval = null

    for (const w of this.topics.values()) w.teardown()
  }

  async _onpair(id, stream) {
    const hex = b4a.toString(id, 'hex')
    const w = this.topics.get(hex)
    if (!w || !w.sessions.length) return this.onwakeup(id, stream)
    w._onopen(getMuxer(stream), false)
  }

  registerMetrics(promClient) {
    const self = this
    new promClient.Gauge({
      // eslint-disable-line no-new
      name: 'protomux_wakeup_sessions_opened',
      help: 'The amount of sessions opened by protomux wakeup',
      collect() {
        this.set(self.stats.sessionsOpened)
      }
    })

    new promClient.Gauge({
      // eslint-disable-line no-new
      name: 'protomux_wakeup_sessions_closed',
      help: 'The amount of sessions closed by protomux wakeup',
      collect() {
        this.set(self.stats.sessionsClosed)
      }
    })

    new promClient.Gauge({
      // eslint-disable-line no-new
      name: 'protomux_wakeup_topics_added',
      help: 'The amount of topics added to protomux wakeup',
      collect() {
        this.set(self.stats.topicsAdded)
      }
    })

    new promClient.Gauge({
      // eslint-disable-line no-new
      name: 'protomux_wakeup_topics_gcd',
      help: 'The amount of topics that got garbage collected by protomux wakeup',
      collect() {
        this.set(self.stats.topicsGcd)
      }
    })

    new promClient.Gauge({
      // eslint-disable-line no-new
      name: 'protomux_wakeup_peers_added',
      help: 'The amount of peers added by protomux wakeup, across all topics',
      collect() {
        this.set(self.stats.peersAdded)
      }
    })

    new promClient.Gauge({
      // eslint-disable-line no-new
      name: 'protomux_wakeup_peers_removed',
      help: 'The amount of peers removed by protomux wakeup, across all topics',
      collect() {
        this.set(self.stats.peersRemoved)
      }
    })

    new promClient.Gauge({
      // eslint-disable-line no-new
      name: 'protomux_wakeup_wire_announce_rx',
      help: 'The amount of wire announce messages received by protomux wakeup',
      collect() {
        this.set(self.stats.wireAnnounce.rx)
      }
    })
    new promClient.Gauge({
      // eslint-disable-line no-new
      name: 'protomux_wakeup_wire_announce_tx',
      help: 'The amount of wire announce messages transmitted by protomux wakeup',
      collect() {
        this.set(self.stats.wireAnnounce.tx)
      }
    })
    new promClient.Gauge({
      // eslint-disable-line no-new
      name: 'protomux_wakeup_wire_lookup_rx',
      help: 'The amount of wire lookup messages received by protomux wakeup',
      collect() {
        this.set(self.stats.wireLookup.rx)
      }
    })
    new promClient.Gauge({
      // eslint-disable-line no-new
      name: 'protomux_wakeup_wire_lookup_tx',
      help: 'The amount of wire lookup messages transmitted by protomux wakeup',
      collect() {
        this.set(self.stats.wireLookup.tx)
      }
    })
    new promClient.Gauge({
      // eslint-disable-line no-new
      name: 'protomux_wakeup_wire_info_rx',
      help: 'The amount of wire info messages received by protomux wakeup',
      collect() {
        this.set(self.stats.wireInfo.rx)
      }
    })
    new promClient.Gauge({
      // eslint-disable-line no-new
      name: 'protomux_wakeup_wire_info_tx',
      help: 'The amount of wire info messages transmitted by protomux wakeup',
      collect() {
        this.set(self.stats.wireInfo.rx)
      }
    })
  }
}

class WakeupPeer {
  constructor(topic) {
    this.index = 0
    this.userData = null // for the user
    this.clock = 0 // for the user, v useful to reduce traffic
    this.pending = true
    this.removed = false
    this.topic = topic
    this.channel = null
    this.stream = null
    this.wireLookup = null
    this.wireAnnounce = null
    this.wireInfo = null
    this.active = false
  }

  unlink(list) {
    // note that since we pop here we can iterate in reverse safely in case a peer is removed in the same tick
    const head = list.pop()
    if (head === this) return
    head.index = this.index
    list[head.index] = head
  }
}

class WakeupSession {
  constructor(topic, handlers) {
    this.index = 0
    this.topic = topic
    this.handlers = handlers
    this.isActive = handlers.active !== false
    this.destroyed = false
  }

  get peers() {
    return this.topic.peers
  }

  hasStream(stream) {
    return !!this.getPeer(stream)
  }

  addStream(stream) {
    this.topic.addStream(stream)
  }

  getPeer(stream) {
    return this.topic.peersByStream.get(stream) || null
  }

  broadcastLookup(req) {
    for (const peer of this.topic.pendingPeers) {
      this.lookup(peer, req)
    }
    for (const peer of this.topic.peers) {
      this.lookup(peer, req)
    }
  }

  lookupByStream(stream, req) {
    const peer = this.topic.peersByStream.get(stream)
    if (peer) this.lookup(peer, req)
  }

  lookup(peer, req) {
    peer.topic.state.stats.wireLookup.tx++
    peer.wireLookup.send(req || { hash: null })
  }

  announceByStream(stream, wakeup) {
    const peer = this.topic.peersByStream.get(stream)
    if (peer && !peer.pending) this.announce(peer, wakeup)
  }

  announce(peer, wakeup) {
    peer.topic.state.stats.wireAnnounce.tx++
    peer.wireAnnounce.send(wakeup)
  }

  active() {
    this.isActive = true
    this.topic._bumpActivity()
  }

  inactive() {
    this.isActive = false
    this.topic._bumpActivity()
  }

  destroy() {
    if (this.destroyed) return
    this.destroyed = true
    this.topic.removeSession(this)
  }
}

class WakeupTopic {
  constructor(state, id, capability, active) {
    this.state = state
    this.sessions = []
    this.id = id
    this.capability = capability
    this.peers = []
    this.pendingPeers = []
    this.peersByStream = new Map()
    this.activePeers = 0
    this.isActive = active
    this.idleTicks = 0
    this.gcing = false
    this.destroyed = false

    this.state.stats.topicsAdded++
  }

  addSession(handlers) {
    this.state.stats.sessionsOpened++
    const session = new WakeupSession(this, handlers)
    session.index = this.sessions.length
    this.sessions.push(session)
    this._bumpActivity()
    this._checkGC()
    return session
  }

  removeSession(session) {
    if (this.sessions.length <= session.index) return
    if (this.sessions[session.index] !== session) return

    this.state.stats.sessionsClosed++

    // same as with the peer, this allows us to iterate while removing if iterating backwards
    const head = this.sessions.pop()
    if (head !== session) {
      head.index = session.index
      this.sessions[head.index] = head
    }

    this._bumpActivity()
    this._checkGC()
  }

  _bumpActivity() {
    let isActive = false

    for (let i = this.sessions.length - 1; i >= 0; i--) {
      if (this.sessions[i].isActive) {
        isActive = true
        break
      }
    }

    if (isActive) this.active()
    else this.inactive()
  }

  active() {
    if (this.isActive) return
    this.idleTicks = 0
    this.isActive = true
    this._updateActive(true)
  }

  inactive() {
    if (!this.isActive) return
    this.isActive = false
    this._updateActive(false)
  }

  _updateActive(active) {
    const info = { active }

    for (const peer of this.pendingPeers) {
      peer.topic.state.stats.wireInfo.tx++
      peer.wireInfo.send(info)
    }
    for (const peer of this.peers) {
      peer.topic.state.stats.wireInfo.tx++
      peer.wireInfo.send(info)
    }

    this._checkGC()

    if (active) this.state._onActive(this)
  }

  teardown() {
    if (this.destroyed) return
    this.destroyed = true

    this.state.stats.topicsGcd++

    for (let i = this.peers.length - 1; i >= 0; i--) {
      this.peers[i].channel.close()
    }

    for (let i = this.pendingPeers.length - 1; i >= 0; i--) {
      this.pendingPeers[i].channel.close()
    }

    const hex = b4a.toString(this.id, 'hex')

    this.gcing = false
    this.state.topics.delete(hex)
    this.state._removeGC(this)

    for (let i = this.sessions.length - 1; i >= 0; i--) {
      this.state.stats.sessionsClosed++
      const session = this.sessions[i]
      if (session.handlers.ondestroy) session.handlers.ondestroy(session)
    }
  }

  addStream(stream) {
    this._onopen(getMuxer(stream), false)
  }

  _proveCapabilityTo(stream) {
    return this._makeCapability(stream.isInitiator, stream.handshakeHash)
  }

  _makeCapability(isInitiator, handshakeHash) {
    return crypto.hash([isInitiator ? NS_INITATOR : NS_RESPONDER, this.capability, handshakeHash])
  }

  _addPeer(peer, open) {
    if (
      !b4a.equals(
        open.capability,
        this._makeCapability(!peer.stream.isInitiator, peer.stream.handshakeHash)
      )
    ) {
      peer.channel.close()
      return
    }

    if (peer.pending) {
      peer.unlink(this.pendingPeers)
    }

    peer.active = open.active
    peer.pending = false
    peer.index = this.peers.push(peer) - 1

    if (peer.active) {
      this.activePeers++
      this._checkGC()
    }

    for (let i = this.sessions.length - 1; i >= 0; i--) {
      const session = this.sessions[i]
      const handlers = session.handlers

      if (handlers.onpeeradd) handlers.onpeeradd(peer, session)
      if (peer.active && handlers.onpeeractive) handlers.onpeeractive(peer, session)
    }
  }

  _checkGC() {
    const shouldGC = this.activePeers === 0 && this.sessions.length === 0

    if (shouldGC) {
      if (!this.gcing) {
        this.gcing = true
        this.state._addGC(this)
      }
    } else {
      if (this.gcing) {
        this.gcing = false
        this.state._removeGC(this)
      }
    }
  }

  _removePeer(peer) {
    this.state.stats.peersRemoved++
    peer.removed = true
    this.peersByStream.delete(peer.stream)

    if (peer.pending) {
      peer.unlink(this.pendingPeers)
      return
    }

    const active = peer.active

    if (active) {
      peer.active = false
      this.activePeers--
      this._checkGC()
    }

    peer.unlink(this.peers)

    for (let i = this.sessions.length - 1; i >= 0; i--) {
      const session = this.sessions[i]
      const handlers = session.handlers

      if (active && handlers.onpeerinactive) handlers.onpeerinactive(peer, session)
      if (handlers.onpeerremove) handlers.onpeerremove(peer, session)
    }
  }

  _onannounce(wakeup, peer) {
    for (let i = this.sessions.length - 1; i >= 0; i--) {
      const session = this.sessions[i]
      const handlers = session.handlers

      if (handlers.onannounce) handlers.onannounce(wakeup, peer, session)
    }
  }

  _onlookup(req, peer) {
    for (let i = this.sessions.length - 1; i >= 0; i--) {
      const session = this.sessions[i]
      const handlers = session.handlers

      if (handlers.onlookup) handlers.onlookup(req, peer, session)
    }
  }

  _oninfo(info, peer) {
    if (info.active) {
      if (!peer.active) {
        peer.active = true
        this.activePeers++
        this._checkGC()

        for (let i = this.sessions.length - 1; i >= 0; i--) {
          const session = this.sessions[i]
          const handlers = session.handlers

          if (handlers.onpeeractive) handlers.onpeeractive(peer, session)
        }
      }
    } else {
      if (peer.active) {
        peer.active = false
        this.activePeers--
        this._checkGC()

        for (let i = this.sessions.length - 1; i >= 0; i--) {
          const session = this.sessions[i]
          const handlers = session.handlers

          if (handlers.onpeerinactive) handlers.onpeerinactive(peer, session)
        }
      }
    }
  }

  _onopen(muxer, unique) {
    if (!unique && this.peersByStream.has(muxer.stream)) return

    const peer = new WakeupPeer(this)
    const ch = muxer.createChannel({
      userData: peer,
      protocol: 'wakeup',
      id: this.id,
      handshake: Handshake,
      messages: [
        { encoding: Lookup, onmessage: onlookup },
        { encoding: Announce, onmessage: onannounce },
        { encoding: Info, onmessage: onchannelinfo }
      ],
      onopen: onchannelopen,
      onclose: onchannelclose
    })

    if (!ch) return

    this.state.stats.peersAdded++

    peer.channel = ch
    peer.stream = muxer.stream

    peer.wireLookup = ch.messages[0]
    peer.wireAnnounce = ch.messages[1]
    peer.wireInfo = ch.messages[2]

    peer.index = this.pendingPeers.push(peer) - 1
    this.peersByStream.set(muxer.stream, peer)

    ch.open({
      version: 0,
      capability: this._proveCapabilityTo(muxer.stream),
      active: this.isActive
    })
  }
}

function onchannelopen(open, channel) {
  const peer = channel.userData
  peer.topic._addPeer(peer, open)
}

function onchannelclose(close, channel) {
  const peer = channel.userData
  peer.topic._removePeer(peer)
}

function onlookup(req, channel) {
  const peer = channel.userData
  peer.topic.state.stats.wireLookup.rx++
  peer.topic._onlookup(req, peer)
}

function onannounce(wakeup, channel) {
  const peer = channel.userData
  peer.topic.state.stats.wireAnnounce.rx++
  peer.topic._onannounce(wakeup, peer)
}

function onchannelinfo(info, channel) {
  const peer = channel.userData
  peer.topic.state.stats.wireInfo.rx++
  peer.topic._oninfo(info, peer)
}

function getMuxer(stream) {
  if (Protomux.isProtomux(stream)) return stream
  if (stream.noiseStream.userData) return stream.noiseStream.userData
  const mux = Protomux.from(stream.noiseStream)
  stream.noiseStream.userData = mux
  return mux
}

function noop() {}
{
  "name": "protomux-wakeup",
  "version": "2.9.0",
  "description": "Wakeup protocol over protomux",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.6.7",
    "hypercore-crypto": "^3.5.0",
    "hyperschema": "^1.10.4",
    "protomux": "^3.10.1"
  },
  "devDependencies": {
    "@hyperswarm/secret-stream": "^6.8.1",
    "brittle": "^3.17.1",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "prom-client": "^15.1.3"
  },
  "files": [
    "index.js",
    "spec/hyperschema/*.js"
  ],
  "scripts": {
    "format": "prettier --write .",
    "test": "prettier --check . && lunte && brittle test/*.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/protomux-wakeup.git"
  },
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/protomux-wakeup/issues"
  },
  "homepage": "https://github.com/holepunchto/protomux-wakeup"
}
// This file is autogenerated by the hyperschema compiler
// Schema Version: 1
/* eslint-disable camelcase */
/* eslint-disable quotes */

const VERSION = 1
const { c } = require('hyperschema/runtime')

// eslint-disable-next-line no-unused-vars
let version = VERSION

// @wakeup/info
const encoding0 = {
  preencode(state, m) {
    state.end++ // max flag is 1 so always one byte
  },
  encode(state, m) {
    const flags = m.active ? 1 : 0

    c.uint.encode(state, flags)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      active: (flags & 1) !== 0
    }
  }
}

// @wakeup/handshake
const encoding1 = {
  preencode(state, m) {
    c.uint.preencode(state, m.version)
    c.fixed32.preencode(state, m.capability)
    state.end++ // max flag is 1 so always one byte
  },
  encode(state, m) {
    const flags = m.active ? 1 : 0

    c.uint.encode(state, m.version)
    c.fixed32.encode(state, m.capability)
    c.uint.encode(state, flags)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const r1 = c.fixed32.decode(state)
    const flags = c.uint.decode(state)

    return {
      version: r0,
      capability: r1,
      active: (flags & 1) !== 0
    }
  }
}

// @wakeup/writer
const encoding2 = {
  preencode(state, m) {
    c.fixed32.preencode(state, m.key)
    c.uint.preencode(state, m.length)
  },
  encode(state, m) {
    c.fixed32.encode(state, m.key)
    c.uint.encode(state, m.length)
  },
  decode(state) {
    const r0 = c.fixed32.decode(state)
    const r1 = c.uint.decode(state)

    return {
      key: r0,
      length: r1
    }
  }
}

// @wakeup/announce
const encoding3 = c.array(encoding2)

// @wakeup/lookup
const encoding4 = {
  preencode(state, m) {
    state.end++ // max flag is 1 so always one byte

    if (m.hash) c.fixed32.preencode(state, m.hash)
  },
  encode(state, m) {
    const flags = m.hash ? 1 : 0

    c.uint.encode(state, flags)

    if (m.hash) c.fixed32.encode(state, m.hash)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      hash: (flags & 1) !== 0 ? c.fixed32.decode(state) : null
    }
  }
}

function setVersion(v) {
  version = v
}

function encode(name, value, v = VERSION) {
  version = v
  return c.encode(getEncoding(name), value)
}

function decode(name, buffer, v = VERSION) {
  version = v
  return c.decode(getEncoding(name), buffer)
}

function getEnum(name) {
  switch (name) {
    default:
      throw new Error('Enum not found ' + name)
  }
}

function getEncoding(name) {
  switch (name) {
    case '@wakeup/info':
      return encoding0
    case '@wakeup/handshake':
      return encoding1
    case '@wakeup/writer':
      return encoding2
    case '@wakeup/announce':
      return encoding3
    case '@wakeup/lookup':
      return encoding4
    default:
      throw new Error('Encoder not found ' + name)
  }
}

function getStruct(name, v = VERSION) {
  const enc = getEncoding(name)
  return {
    preencode(state, m) {
      version = v
      enc.preencode(state, m)
    },
    encode(state, m) {
      version = v
      enc.encode(state, m)
    },
    decode(state) {
      version = v
      return enc.decode(state)
    }
  }
}

const resolveStruct = getStruct // compat

module.exports = {
  resolveStruct,
  getStruct,
  getEnum,
  getEncoding,
  encode,
  decode,
  setVersion,
  version
}
const b4a = require('b4a')
const c = require('compact-encoding')
const queueTick = require('queue-tick')
const safetyCatch = require('safety-catch')
const unslab = require('unslab')

const MAX_BUFFERED = 32768
const MAX_BACKLOG = Infinity // TODO: impl "open" backpressure
const MAX_BATCH = 8 * 1024 * 1024

class Channel {
  constructor (mux, info, userData, protocol, aliases, id, handshake, messages, onopen, onclose, ondestroy, ondrain) {
    this.userData = userData
    this.protocol = protocol
    this.aliases = aliases
    this.id = id
    this.handshake = null
    this.messages = []

    this.opened = false
    this.closed = false
    this.destroyed = false

    this.onopen = onopen
    this.onclose = onclose
    this.ondestroy = ondestroy
    this.ondrain = ondrain

    this._handshake = handshake
    this._mux = mux
    this._info = info
    this._localId = 0
    this._remoteId = 0
    this._active = 0
    this._extensions = null

    this._decBound = this._dec.bind(this)
    this._decAndDestroyBound = this._decAndDestroy.bind(this)

    this._openedPromise = null
    this._openedResolve = null

    this._destroyedPromise = null
    this._destroyedResolve = null

    for (const m of messages) this.addMessage(m)
  }

  get drained () {
    return this._mux.drained
  }

  fullyOpened () {
    if (this.opened) return Promise.resolve(true)
    if (this.closed) return Promise.resolve(false)
    if (this._openedPromise) return this._openedPromise

    this._openedPromise = new Promise((resolve) => { this._openedResolve = resolve })
    return this._openedPromise
  }

  fullyClosed () {
    if (this.destroyed) return Promise.resolve()
    if (this._destroyedPromise) return this._destroyedPromise

    this._destroyedPromise = new Promise((resolve) => { this._destroyedResolve = resolve })
    return this._destroyedPromise
  }

  open (handshake) {
    const id = this._mux._free.length > 0
      ? this._mux._free.pop()
      : this._mux._local.push(null) - 1

    this._info.opened++
    this._info.lastChannel = this
    this._localId = id + 1
    this._mux._local[id] = this

    if (this._remoteId === 0) {
      this._info.outgoing.push(this._localId)
    }

    const state = { buffer: null, start: 2, end: 2 }

    c.uint.preencode(state, this._localId)
    c.string.preencode(state, this.protocol)
    c.buffer.preencode(state, this.id)
    if (this._handshake) this._handshake.preencode(state, handshake)

    state.buffer = this._mux._alloc(state.end)

    state.buffer[0] = 0
    state.buffer[1] = 1
    c.uint.encode(state, this._localId)
    c.string.encode(state, this.protocol)
    c.buffer.encode(state, this.id)
    if (this._handshake) this._handshake.encode(state, handshake)

    this._mux._write0(state.buffer)
  }

  _dec () {
    if (--this._active === 0 && this.closed === true) this._destroy()
  }

  _decAndDestroy (err) {
    this._dec()
    this._mux._safeDestroy(err)
  }

  _fullyOpenSoon () {
    this._mux._remote[this._remoteId - 1].session = this
    queueTick(this._fullyOpen.bind(this))
  }

  _fullyOpen () {
    if (this.opened === true || this.closed === true) return

    const remote = this._mux._remote[this._remoteId - 1]

    this.opened = true
    this.handshake = this._handshake ? this._handshake.decode(remote.state) : null
    this._track(this.onopen(this.handshake, this))

    remote.session = this
    remote.state = null
    if (remote.pending !== null) this._drain(remote)

    this._resolveOpen(true)
  }

  _resolveOpen (opened) {
    if (this._openedResolve !== null) {
      this._openedResolve(opened)
      this._openedResolve = this._openedPromise = null
    }
  }

  _resolveDestroyed () {
    if (this._destroyedResolve !== null) {
      this._destroyedResolve()
      this._destroyedResolve = this._destroyedPromise = null
    }
  }

  _drain (remote) {
    for (let i = 0; i < remote.pending.length; i++) {
      const p = remote.pending[i]
      this._mux._buffered -= byteSize(p.state)
      this._recv(p.type, p.state)
    }

    remote.pending = null
    this._mux._resumeMaybe()
  }

  _track (p) {
    if (isPromise(p) === true) {
      this._active++
      return p.then(this._decBound, this._decAndDestroyBound)
    }

    return null
  }

  _close (isRemote) {
    if (this.closed === true) return
    this.closed = true

    this._info.opened--
    if (this._info.lastChannel === this) this._info.lastChannel = null

    if (this._remoteId > 0) {
      this._mux._remote[this._remoteId - 1] = null
      this._remoteId = 0
      // If remote has acked, we can reuse the local id now
      // otherwise, we need to wait for the "ack" to arrive
      this._mux._free.push(this._localId - 1)
    }

    this._mux._local[this._localId - 1] = null
    this._localId = 0

    this._mux._gc(this._info)
    this._track(this.onclose(isRemote, this))

    if (this._active === 0) this._destroy()

    this._resolveOpen(false)
  }

  _destroy () {
    if (this.destroyed === true) return
    this.destroyed = true
    this._track(this.ondestroy(this))
    this._resolveDestroyed()
  }

  _recv (type, state) {
    if (type < this.messages.length) {
      const m = this.messages[type]
      const p = m.recv(state, this)
      if (m.autoBatch === true) return p
    }
    return null
  }

  cork () {
    this._mux.cork()
  }

  uncork () {
    this._mux.uncork()
  }

  close () {
    if (this.closed === true) return

    const state = { buffer: null, start: 2, end: 2 }

    c.uint.preencode(state, this._localId)

    state.buffer = this._mux._alloc(state.end)

    state.buffer[0] = 0
    state.buffer[1] = 3
    c.uint.encode(state, this._localId)

    this._close(false)
    this._mux._write0(state.buffer)
  }

  addMessage (opts) {
    if (!opts) return this._skipMessage()

    const type = this.messages.length
    const autoBatch = opts.autoBatch !== false
    const encoding = opts.encoding || c.raw
    const onmessage = opts.onmessage || noop

    const s = this
    const typeLen = encodingLength(c.uint, type)

    const m = {
      type,
      autoBatch,
      encoding,
      onmessage,
      recv (state, session) {
        return session._track(m.onmessage(encoding.decode(state), session))
      },
      send (m, session = s) {
        if (session.closed === true) return false

        const mux = session._mux
        const state = { buffer: null, start: 0, end: typeLen }

        if (mux._batch !== null) {
          encoding.preencode(state, m)
          state.buffer = mux._alloc(state.end)

          c.uint.encode(state, type)
          encoding.encode(state, m)

          mux._pushBatch(session._localId, state.buffer)
          return true
        }

        c.uint.preencode(state, session._localId)
        encoding.preencode(state, m)

        state.buffer = mux._alloc(state.end)

        c.uint.encode(state, session._localId)
        c.uint.encode(state, type)
        encoding.encode(state, m)

        mux.drained = mux.stream.write(state.buffer)

        return mux.drained
      }
    }

    this.messages.push(m)

    return m
  }

  _skipMessage () {
    const type = this.messages.length
    const m = {
      type,
      encoding: c.raw,
      onmessage: noop,
      recv (state, session) {},
      send (m, session) {}
    }

    this.messages.push(m)
    return m
  }
}

module.exports = class Protomux {
  constructor (stream, { alloc } = {}) {
    if (stream.userData === null) stream.userData = this

    this.isProtomux = true
    this.stream = stream
    this.corked = 0
    this.drained = true

    this._alloc = alloc || (typeof stream.alloc === 'function' ? stream.alloc.bind(stream) : b4a.allocUnsafe)
    this._safeDestroyBound = this._safeDestroy.bind(this)
    this._uncorkBound = this.uncork.bind(this)

    this._remoteBacklog = 0
    this._buffered = 0
    this._paused = false
    this._remote = []
    this._local = []
    this._free = []
    this._batch = null
    this._batchState = null

    this._infos = new Map()
    this._notify = new Map()

    this.stream.on('data', this._ondata.bind(this))
    this.stream.on('drain', this._ondrain.bind(this))
    this.stream.on('end', this._onend.bind(this))
    this.stream.on('error', noop) // we handle this in "close"
    this.stream.on('close', this._shutdown.bind(this))
  }

  static from (stream, opts) {
    if (stream.userData && stream.userData.isProtomux) return stream.userData
    if (stream.isProtomux) return stream
    return new this(stream, opts)
  }

  static isProtomux (mux) {
    return typeof mux === 'object' && mux.isProtomux === true
  }

  * [Symbol.iterator] () {
    for (const session of this._local) {
      if (session !== null) yield session
    }
  }

  isIdle () {
    return this._local.length === this._free.length
  }

  cork () {
    if (++this.corked === 1) {
      this._batch = []
      this._batchState = { buffer: null, start: 0, end: 1 }
    }
  }

  uncork () {
    if (--this.corked === 0) {
      this._sendBatch(this._batch, this._batchState)
      this._batch = null
      this._batchState = null
    }
  }

  getLastChannel ({ protocol, id = null }) {
    const key = toKey(protocol, id)
    const info = this._infos.get(key)
    if (info) return info.lastChannel
    return null
  }

  pair ({ protocol, id = null }, notify) {
    this._notify.set(toKey(protocol, id), notify)
  }

  unpair ({ protocol, id = null }) {
    this._notify.delete(toKey(protocol, id))
  }

  opened ({ protocol, id = null }) {
    const key = toKey(protocol, id)
    const info = this._infos.get(key)
    return info ? info.opened > 0 : false
  }

  createChannel ({ userData = null, protocol, aliases = [], id = null, unique = true, handshake = null, messages = [], onopen = noop, onclose = noop, ondestroy = noop, ondrain = noop }) {
    if (this.stream.destroyed) return null

    const info = this._get(protocol, id, aliases)
    if (unique && info.opened > 0) return null

    if (info.incoming.length === 0) {
      return new Channel(this, info, userData, protocol, aliases, id, handshake, messages, onopen, onclose, ondestroy, ondrain)
    }

    this._remoteBacklog--

    const remoteId = info.incoming.shift()
    const r = this._remote[remoteId - 1]
    if (r === null) return null

    const session = new Channel(this, info, userData, protocol, aliases, id, handshake, messages, onopen, onclose, ondestroy, ondrain)

    session._remoteId = remoteId
    session._fullyOpenSoon()

    return session
  }

  _pushBatch (localId, buffer) {
    if (this._batchState.end >= MAX_BATCH) {
      this._sendBatch(this._batch, this._batchState)
      this._batch = []
      this._batchState = { buffer: null, start: 0, end: 1 }
    }

    if (this._batch.length === 0 || this._batch[this._batch.length - 1].localId !== localId) {
      this._batchState.end++
      c.uint.preencode(this._batchState, localId)
    }
    c.buffer.preencode(this._batchState, buffer)
    this._batch.push({ localId, buffer })
  }

  _sendBatch (batch, state) {
    if (batch.length === 0) return

    let prev = batch[0].localId

    state.buffer = this._alloc(state.end)
    state.buffer[state.start++] = 0
    state.buffer[state.start++] = 0

    c.uint.encode(state, prev)

    for (let i = 0; i < batch.length; i++) {
      const b = batch[i]
      if (prev !== b.localId) {
        state.buffer[state.start++] = 0
        c.uint.encode(state, (prev = b.localId))
      }
      c.buffer.encode(state, b.buffer)
    }

    this.drained = this.stream.write(state.buffer)
  }

  _get (protocol, id, aliases = []) {
    const key = toKey(protocol, id)

    let info = this._infos.get(key)
    if (info) return info

    info = { key, protocol, aliases: [], id, pairing: 0, opened: 0, incoming: [], outgoing: [], lastChannel: null }
    this._infos.set(key, info)

    for (const alias of aliases) {
      const key = toKey(alias, id)
      info.aliases.push(key)

      this._infos.set(key, info)
    }

    return info
  }

  _gc (info) {
    if (info.opened === 0 && info.outgoing.length === 0 && info.incoming.length === 0) {
      this._infos.delete(info.key)

      for (const alias of info.aliases) this._infos.delete(alias)
    }
  }

  _ondata (buffer) {
    if (buffer.byteLength === 0) return // ignore empty frames...
    try {
      const state = { buffer, start: 0, end: buffer.byteLength }
      this._decode(c.uint.decode(state), state)
    } catch (err) {
      this._safeDestroy(err)
    }
  }

  _ondrain () {
    this.drained = true

    for (const s of this._local) {
      if (s !== null) s._track(s.ondrain(s))
    }
  }

  _onend () { // TODO: support half open mode for the users who wants that here
    this.stream.end()
  }

  _decode (remoteId, state) {
    const type = c.uint.decode(state)

    if (remoteId === 0) {
      return this._oncontrolsession(type, state)
    }

    const r = remoteId <= this._remote.length ? this._remote[remoteId - 1] : null

    // if the channel is closed ignore - could just be a pipeline message...
    if (r === null) return null

    if (r.pending !== null) {
      this._bufferMessage(r, type, state)
      return null
    }

    return r.session._recv(type, state)
  }

  _oncontrolsession (type, state) {
    switch (type) {
      case 0:
        this._onbatch(state)
        break

      case 1:
        // return the promise back up as this has sideeffects so we can batch reply
        return this._onopensession(state)

      case 2:
        this._onrejectsession(state)
        break

      case 3:
        this._onclosesession(state)
        break
    }

    return null
  }

  _bufferMessage (r, type, { buffer, start, end }) {
    const state = { buffer, start, end } // copy
    r.pending.push({ type, state })
    this._buffered += byteSize(state)
    this._pauseMaybe()
  }

  _pauseMaybe () {
    if (this._paused === true || this._buffered <= MAX_BUFFERED) return
    this._paused = true
    this.stream.pause()
  }

  _resumeMaybe () {
    if (this._paused === false || this._buffered > MAX_BUFFERED) return
    this._paused = false
    this.stream.resume()
  }

  _onbatch (state) {
    const end = state.end
    let remoteId = c.uint.decode(state)

    let waiting = null

    while (state.end > state.start) {
      const len = c.uint.decode(state)
      if (len === 0) {
        remoteId = c.uint.decode(state)
        continue
      }
      state.end = state.start + len
      // if batch contains more than one message, cork it so we reply back with a batch
      if (end !== state.end && waiting === null) {
        waiting = []
        this.cork()
      }
      const p = this._decode(remoteId, state)
      if (waiting !== null && p !== null) waiting.push(p)
      state.start = state.end
      state.end = end
    }

    if (waiting !== null) {
      // the waiting promises are not allowed to throw but we destroy the stream in case we are wrong
      Promise.all(waiting).then(this._uncorkBound, this._safeDestroyBound)
    }
  }

  _onopensession (state) {
    const remoteId = c.uint.decode(state)
    const protocol = c.string.decode(state)
    const id = unslab(c.buffer.decode(state))

    // remote tried to open the control session - auto reject for now
    // as we can use as an explicit control protocol declaration if we need to
    if (remoteId === 0) {
      this._rejectSession(0)
      return null
    }

    const rid = remoteId - 1
    const info = this._get(protocol, id)

    // allow the remote to grow the ids by one
    if (this._remote.length === rid) {
      this._remote.push(null)
    }

    if (rid >= this._remote.length || this._remote[rid] !== null) {
      throw new Error('Invalid open message')
    }

    if (info.outgoing.length > 0) {
      const localId = info.outgoing.shift()
      const session = this._local[localId - 1]

      if (session === null) { // we already closed the channel - ignore
        this._free.push(localId - 1)
        return null
      }

      this._remote[rid] = { state, pending: null, session: null }

      session._remoteId = remoteId
      session._fullyOpen()
      return null
    }

    const copyState = { buffer: state.buffer, start: state.start, end: state.end }
    this._remote[rid] = { state: copyState, pending: [], session: null }

    if (++this._remoteBacklog > MAX_BACKLOG) {
      throw new Error('Remote exceeded backlog')
    }

    info.pairing++
    info.incoming.push(remoteId)

    return this._requestSession(protocol, id, info).catch(this._safeDestroyBound)
  }

  _onrejectsession (state) {
    const localId = c.uint.decode(state)

    // TODO: can be done smarter...
    for (const info of this._infos.values()) {
      const i = info.outgoing.indexOf(localId)
      if (i === -1) continue

      info.outgoing.splice(i, 1)

      const session = this._local[localId - 1]

      this._free.push(localId - 1)
      if (session !== null) session._close(true)

      this._gc(info)
      return
    }

    throw new Error('Invalid reject message')
  }

  _onclosesession (state) {
    const remoteId = c.uint.decode(state)

    if (remoteId === 0) return // ignore

    const rid = remoteId - 1
    const r = rid < this._remote.length ? this._remote[rid] : null

    if (r === null) return

    if (r.session !== null) r.session._close(true)
  }

  async _requestSession (protocol, id, info) {
    const notify = this._notify.get(toKey(protocol, id)) || this._notify.get(toKey(protocol, null))

    if (notify) await notify(id)

    if (--info.pairing > 0) return

    while (info.incoming.length > 0) {
      this._rejectSession(info, info.incoming.shift())
    }

    this._gc(info)
  }

  _rejectSession (info, remoteId) {
    if (remoteId > 0) {
      const r = this._remote[remoteId - 1]

      if (r.pending !== null) {
        for (let i = 0; i < r.pending.length; i++) {
          this._buffered -= byteSize(r.pending[i].state)
        }
      }

      this._remote[remoteId - 1] = null
      this._resumeMaybe()
    }

    const state = { buffer: null, start: 2, end: 2 }

    c.uint.preencode(state, remoteId)

    state.buffer = this._alloc(state.end)

    state.buffer[0] = 0
    state.buffer[1] = 2
    c.uint.encode(state, remoteId)

    this._write0(state.buffer)
  }

  _write0 (buffer) {
    if (this._batch !== null) {
      this._pushBatch(0, buffer.subarray(1))
      return
    }

    this.drained = this.stream.write(buffer)
  }

  destroy (err) {
    this.stream.destroy(err)
  }

  _safeDestroy (err) {
    safetyCatch(err)
    this.stream.destroy(err)
  }

  _shutdown () {
    for (const s of this._local) {
      if (s !== null) s._close(true)
    }
  }
}

function noop () {}

function toKey (protocol, id) {
  return protocol + '##' + (id ? b4a.toString(id, 'hex') : '')
}

function byteSize (state) {
  return 512 + (state.end - state.start)
}

function isPromise (p) {
  return !!(p && typeof p.then === 'function')
}

function encodingLength (enc, val) {
  const state = { buffer: null, start: 0, end: 0 }
  enc.preencode(state, val)
  return state.end
}
{
  "name": "protomux",
  "version": "3.10.1",
  "description": "Multiplex multiple message oriented protocols over a stream",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.3.1",
    "compact-encoding": "^2.5.1",
    "queue-tick": "^1.0.0",
    "safety-catch": "^1.0.1",
    "unslab": "^1.3.0"
  },
  "devDependencies": {
    "@hyperswarm/secret-stream": "^6.0.0",
    "brittle": "^3.0.0",
    "standard": "^16.0.4"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/protomux.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/protomux/issues"
  },
  "homepage": "https://github.com/mafintosh/protomux"
}
{
  "name": "queue-tick",
  "version": "1.0.1",
  "description": "Next tick shim that prefers process.nextTick over queueMicrotask for compat",
  "main": "./process-next-tick.js",
  "browser": "./queue-microtask.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^16.0.3",
    "tape": "^5.3.1"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/queue-tick.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/queue-tick/issues"
  },
  "homepage": "https://github.com/mafintosh/queue-tick"
}
module.exports = (typeof process !== 'undefined' && typeof process.nextTick === 'function')
  ? process.nextTick.bind(process)
  : require('./queue-microtask')
module.exports = typeof queueMicrotask === 'function' ? queueMicrotask : (fn) => Promise.resolve().then(fn)
require.addon = require('require-addon')

module.exports = require.addon('.', __filename)
const binding = require('./binding')

exports.get = function get(field, bit) {
  const n = field.byteLength * 8

  if (bit < 0) bit += n
  if (bit < 0 || bit >= n) return false

  return binding.quickbit_napi_get(toBuffer(field), bit) !== 0
}

exports.set = function set(field, bit, value = true) {
  const n = field.byteLength * 8

  if (bit < 0) bit += n
  if (bit < 0 || bit >= n) return false

  return binding.quickbit_napi_set(toBuffer(field), bit, value ? 1 : 0) !== 0
}

exports.fill = function fill(
  field,
  value,
  start = 0,
  end = field.byteLength * 8
) {
  const n = field.byteLength * 8

  if (start < 0) start += n
  if (end < 0) end += n
  if (start < 0 || start >= field.byteLength * 8 || start >= end) return field

  binding.quickbit_napi_fill(toBuffer(field), value ? 1 : 0, start, end)
  return field
}

exports.clear = function clear(field, ...chunks) {
  binding.quickbit_napi_clear(toBuffer(field), chunks.map(toBufferChunk))
}

exports.findFirst = function findFirst(field, value, position = 0) {
  const n = field.byteLength * 8

  if (position < 0) position += n
  if (position < 0) position = 0
  if (position >= n) return -1

  return binding.quickbit_napi_find_first(
    toBuffer(field),
    value ? 1 : 0,
    position
  )
}

exports.findLast = function findLast(
  field,
  value,
  position = field.byteLength * 8 - 1
) {
  const n = field.byteLength * 8

  if (position < 0) position += n
  if (position < 0) return -1
  if (position >= n) position = n - 1

  return binding.quickbit_napi_find_last(
    toBuffer(field),
    value ? 1 : 0,
    position
  )
}

function toBuffer(field) {
  if (field.BYTES_PER_ELEMENT === 1) return field
  return new Uint8Array(field.buffer, field.byteOffset, field.byteLength)
}

function toBufferChunk(chunk) {
  return { field: toBuffer(chunk.field), offset: chunk.offset }
}

class Index {
  static from(fieldOrChunks, byteLength = -1) {
    if (Array.isArray(fieldOrChunks)) {
      return new SparseIndex(fieldOrChunks, byteLength)
    } else {
      return new DenseIndex(fieldOrChunks, byteLength)
    }
  }

  constructor(byteLength) {
    this._byteLength = byteLength
    this.handle = Buffer.allocUnsafe(binding.sizeof_quickbit_index_t)
  }

  get byteLength() {
    return this._byteLength
  }

  skipFirst(value, position = 0) {
    const n = this.byteLength * 8

    if (position < 0) position += n
    if (position < 0) position = 0
    if (position >= n) return n - 1

    return binding.quickbit_napi_skip_first(
      this.handle,
      this.byteLength,
      value ? 1 : 0,
      position
    )
  }

  skipLast(value, position = this.byteLength * 8 - 1) {
    const n = this.byteLength * 8

    if (position < 0) position += n
    if (position < 0) return 0
    if (position >= n) position = n - 1

    return binding.quickbit_napi_skip_last(
      this.handle,
      this.byteLength,
      value ? 1 : 0,
      position
    )
  }
}

exports.Index = Index

class DenseIndex extends Index {
  constructor(field, byteLength) {
    super(byteLength)
    this.field = field

    binding.quickbit_napi_index_init(this.handle, toBuffer(this.field))
  }

  get byteLength() {
    if (this._byteLength !== -1) return this._byteLength
    return this.field.byteLength
  }

  update(bit) {
    const n = this.byteLength * 8

    if (bit < 0) bit += n
    if (bit < 0 || bit >= n) return false

    return (
      binding.quickbit_napi_index_update(
        this.handle,
        toBuffer(this.field),
        bit
      ) !== 0
    )
  }
}

function selectChunk(chunks, offset) {
  for (let i = 0; i < chunks.length; i++) {
    const next = chunks[i]

    const start = next.offset
    const end = next.offset + next.field.byteLength

    if (offset >= start && offset + 16 <= end) {
      return next
    }
  }

  return null
}

class SparseIndex extends Index {
  constructor(chunks, byteLength) {
    super(byteLength)
    this.chunks = chunks

    binding.quickbit_napi_index_init_sparse(
      this.handle,
      this.chunks.map(toBufferChunk)
    )
  }

  get byteLength() {
    if (this._byteLength !== -1) return this._byteLength
    const last = this.chunks[this.chunks.length - 1]
    return last ? last.offset + last.field.byteLength : 0
  }

  update(bit) {
    const n = this.byteLength * 8

    if (bit < 0) bit += n
    if (bit < 0 || bit >= n) return false

    const j = Math.floor(bit / 128)

    const offset = j * 16

    const chunk = selectChunk(this.chunks, offset)

    if (chunk === null) return false

    return (
      binding.quickbit_napi_index_update_sparse(
        this.handle,
        toBuffer(chunk.field),
        chunk.offset,
        bit
      ) !== 0
    )
  }
}
{
  "name": "quickbit-native",
  "version": "2.4.8",
  "description": "libquickbit JavaScript bindings for Node.js",
  "main": "index.js",
  "files": [
    "index.js",
    "macros.h",
    "binding.cc",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "npm run lint && npm run test:bare && npm run test:node",
    "test:bare": "bare test.mjs",
    "test:node": "node test.mjs",
    "lint": "prettier . --check"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/quickbit-native.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/quickbit-native/issues"
  },
  "homepage": "https://github.com/holepunchto/quickbit-native#readme",
  "dependencies": {
    "require-addon": "^1.1.0"
  },
  "devDependencies": {
    "b4a": "^1.6.7",
    "bare-compat-napi": "^1.3.2",
    "brittle": "^3.1.0",
    "cmake-bare": "^1.1.7",
    "cmake-fetch": "^1.1.0",
    "cmake-napi": "^1.0.2",
    "prettier": "^3.5.3",
    "prettier-config-standard": "^7.0.0"
  }
}
const simdle = require('simdle-universal')

const INDEX_LEN = (16 /* root */ + 128 * 16 /* children */) * 2

const get = exports.get = function get (field, bit) {
  const n = field.byteLength * 8

  if (bit < 0) bit += n
  if (bit < 0 || bit >= n) return false

  const m = field.BYTES_PER_ELEMENT * 8

  const offset = bit & (m - 1)
  const i = (bit - offset) / m

  return (field[i] & (1 << offset)) !== 0
}

const set = exports.set = function set (field, bit, value = true) {
  const n = field.byteLength * 8

  if (bit < 0) bit += n
  if (bit < 0 || bit >= n) return false

  const m = field.BYTES_PER_ELEMENT * 8

  const offset = bit & (m - 1)
  const i = (bit - offset) / m
  const mask = 1 << offset

  if (value) {
    if ((field[i] & mask) !== 0) return false
  } else {
    if ((field[i] & mask) === 0) return false
  }

  field[i] ^= mask

  return true
}

exports.fill = function fill (field, value, start = 0, end = field.byteLength * 8) {
  const n = field.byteLength * 8

  if (start < 0) start += n
  if (end < 0) end += n
  if (start < 0 || start >= field.byteLength * 8 || start >= end) return field

  const m = field.BYTES_PER_ELEMENT * 8

  let i, j

  {
    const offset = start & (m - 1)
    i = (start - offset) / m

    if (offset !== 0) {
      let shift = m - offset
      if (end - start < shift) shift = end - start

      const mask = ((1 << shift) - 1) << offset

      if (value) field[i] |= mask
      else field[i] &= ~mask

      i++
    }
  }

  {
    const offset = end & (m - 1)
    j = (end - offset) / m

    if (offset !== 0 && j >= i) {
      const mask = (1 << offset) - 1

      if (value) field[j] |= mask
      else field[j] &= ~mask
    }
  }

  if (i < j) field.fill(value ? (2 ** m) - 1 : 0, i, j)

  return field
}

exports.clear = function clear (field, ...chunks) {
  const n = field.byteLength

  for (const chunk of chunks) {
    if (chunk.offset >= n) continue

    const m = chunk.field.byteLength

    let i = chunk.offset
    let j = 0

    while (((i & 15) !== 0 || (j & 15) !== 0) && i < n && j < m) {
      field[i] = field[i] & ~chunk.field[j]
      i++
      j++
    }

    if (i + 15 < n && j + 15 < m) {
      const len = Math.min(n - (n & 15) - i, m - (m & 15) - j)

      simdle.clear(field.subarray(i, i + len), chunk.field.subarray(j, j + len), field.subarray(i, i + len))
    }

    while (i < n && j < m) {
      field[i] = field[i] & ~chunk.field[j]
      i++
      j++
    }
  }
}

function bitOffset (bit, offset) {
  return !bit ? offset : (INDEX_LEN * 8 / 2) + offset
}

function byteOffset (bit, offset) {
  return !bit ? offset : (INDEX_LEN / 2) + offset
}

exports.findFirst = function findFirst (field, value, position = 0) {
  const n = field.byteLength * 8

  if (position < 0) position += n
  if (position < 0) position = 0
  if (position >= n) return -1

  value = !!value

  for (let i = position; i < n; i++) {
    if (get(field, i) === value) return i
  }

  return -1
}

exports.findLast = function findLast (field, value, position = field.byteLength * 8 - 1) {
  const n = field.byteLength * 8

  if (position < 0) position += n
  if (position < 0) return -1
  if (position >= n) position = n - 1

  value = !!value

  for (let i = position; i >= 0; i--) {
    if (get(field, i) === value) return i
  }

  return -1
}

const Index = exports.Index = class Index {
  static from (fieldOrChunks, byteLength = -1) {
    if (Array.isArray(fieldOrChunks)) {
      return new SparseIndex(fieldOrChunks, byteLength)
    } else {
      return new DenseIndex(fieldOrChunks, byteLength)
    }
  }

  constructor (byteLength) {
    this._byteLength = byteLength
    this.handle = new Uint32Array(INDEX_LEN / 4)
  }

  get byteLength () {
    return this._byteLength
  }

  skipFirst (value, position = 0) {
    const n = this.byteLength * 8

    if (position < 0) position += n
    if (position < 0) position = 0
    if (position >= n) return n - 1

    let i = Math.floor(position / 16384)

    if (i > 127) return position

    while (i <= 127 && get(this.handle, bitOffset(value, i))) {
      i++
    }

    if (i === 128) return n - 1

    let k = i * 16384
    let j = 0

    if (position > k) j = Math.floor((position - k) / 128)

    while (j <= 127 && get(this.handle, bitOffset(value, i * 128 + j + 128))) {
      j++
      k += 128
    }

    if (j === 128 && i !== 127) return this.skipFirst(value, (i + 1) * 16384)

    if (k > position) position = k

    return position < n ? position : n - 1
  }

  skipLast (value, position = this.byteLength * 8 - 1) {
    const n = this.byteLength * 8

    if (position < 0) position += n
    if (position < 0) return 0
    if (position >= n) position = n - 1

    let i = Math.floor(position / 16384)

    if (i > 127) return position

    while (i >= 0 && get(this.handle, bitOffset(value, i))) {
      i--
    }

    if (i === -1) return 0

    let k = ((i + 1) * 16384) - 1
    let j = 127

    if (position < k) j = 128 - Math.ceil((k - position) / 128)

    while (j >= 0 && get(this.handle, bitOffset(value, i * 128 + j + 128))) {
      j--
      k -= 128
    }

    if (j === -1 && i !== 0) return this.skipLast(value, i * 16384 - 1)

    if (k < position) position = k

    return position
  }
}

class DenseIndex extends Index {
  constructor (field, byteLength) {
    super(byteLength)
    this.field = field

    const m = field.BYTES_PER_ELEMENT

    for (let i = 0; i < 128; i++) {
      for (let j = 0; j < 128; j++) {
        const offset = (i * 128 + j) * 16
        let allz = true
        let allo = false

        if (offset + 16 <= this.field.byteLength) {
          const vec = this.field.subarray(offset / m, (offset + 16) / m)

          allz = simdle.allz(vec)
          allo = simdle.allo(vec)
        }

        const k = i * 128 + 128 + j

        set(this.handle, bitOffset(false, k), allz)
        set(this.handle, bitOffset(true, k), allo)
      }

      {
        const offset = byteOffset(false, i * 16 + 16) / 4
        const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

        set(this.handle, bitOffset(false, i), allo)
      }

      {
        const offset = byteOffset(true, i * 16 + 16) / 4
        const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

        set(this.handle, bitOffset(true, i), allo)
      }
    }
  }

  get byteLength () {
    if (this._byteLength !== -1) return this._byteLength
    return this.field.byteLength
  }

  update (bit) {
    const n = this.byteLength * 8

    if (bit < 0) bit += n
    if (bit < 0 || bit >= n) return false

    const m = this.field.BYTES_PER_ELEMENT

    const i = Math.floor(bit / 16384)
    const j = Math.floor(bit / 128)

    const offset = (j * 16) / m
    const vec = this.field.subarray(offset, offset + (16 / m))

    const allz = simdle.allz(vec)
    const allo = simdle.allo(vec)

    let changed = false

    if (set(this.handle, bitOffset(false, 128 + j), allz)) {
      changed = true

      const offset = byteOffset(false, i * 16 + 16) / 4
      const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

      set(this.handle, bitOffset(false, i), allo)
    }

    if (set(this.handle, bitOffset(true, 128 + j), allo)) {
      changed = true

      const offset = byteOffset(true, i * 16 + 16) / 4
      const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

      set(this.handle, bitOffset(true, i), allo)
    }

    return changed
  }
}

function selectChunk (chunks, offset) {
  for (let i = 0; i < chunks.length; i++) {
    const next = chunks[i]

    const start = next.offset
    const end = next.offset + next.field.byteLength

    if (offset >= start && offset + 16 <= end) {
      return next
    }
  }

  return null
}

class SparseIndex extends Index {
  constructor (chunks, byteLength) {
    super(byteLength)
    this.chunks = chunks

    for (let i = 0; i < 128; i++) {
      for (let j = 0; j < 128; j++) {
        const offset = (i * 128 + j) * 16
        let allz = true
        let allo = false

        const chunk = selectChunk(this.chunks, offset)

        if (chunk !== null) {
          const m = chunk.field.BYTES_PER_ELEMENT

          const vec = chunk.field.subarray((offset - chunk.offset) / m, (offset - chunk.offset + 16) / m)

          allz = simdle.allz(vec)
          allo = simdle.allo(vec)
        }

        const k = i * 128 + 128 + j

        set(this.handle, bitOffset(false, k), allz)
        set(this.handle, bitOffset(true, k), allo)
      }

      {
        const offset = byteOffset(false, i * 16 + 16) / 4
        const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

        set(this.handle, bitOffset(false, i), allo)
      }

      {
        const offset = byteOffset(true, i * 16 + 16) / 4
        const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

        set(this.handle, bitOffset(true, i), allo)
      }
    }
  }

  get byteLength () {
    if (this._byteLength !== -1) return this._byteLength
    const last = this.chunks[this.chunks.length - 1]
    return last ? last.offset + last.field.byteLength : 0
  }

  update (bit) {
    const n = this.byteLength * 8

    if (bit < 0) bit += n
    if (bit < 0 || bit >= n) return false

    const i = Math.floor(bit / 16384)
    const j = Math.floor(bit / 128)

    const offset = j * 16

    const chunk = selectChunk(this.chunks, offset)

    if (chunk === null) return false

    const m = chunk.field.BYTES_PER_ELEMENT

    const vec = chunk.field.subarray((offset - chunk.offset) / m, (offset - chunk.offset + 16) / m)

    const allz = simdle.allz(vec)
    const allo = simdle.allo(vec)

    let changed = false

    if (set(this.handle, bitOffset(false, 128 + j), allz)) {
      changed = true

      const offset = byteOffset(false, i * 16 + 16) / 4
      const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

      set(this.handle, bitOffset(false, i), allo)
    }

    if (set(this.handle, bitOffset(true, 128 + j), allo)) {
      changed = true

      const offset = byteOffset(true, i * 16 + 16) / 4
      const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

      set(this.handle, bitOffset(true, i), allo)
    }

    return changed
  }
}
const fallback = require('./fallback')

try {
  const native = require('quickbit-native')

  // These functions are faster in JavaScript
  exports.get = fallback.get
  exports.set = fallback.set
  exports.fill = fallback.fill

  // These functions are faster in C
  exports.clear = native.clear
  exports.findFirst = native.findFirst
  exports.findLast = native.findLast
  exports.Index = native.Index
} catch {
  module.exports = fallback
}
{
  "name": "quickbit-universal",
  "version": "2.2.0",
  "description": "Universal wrapper for libquickbit with a JavaScript fallback",
  "main": "index.js",
  "files": [
    "fallback.js",
    "index.js"
  ],
  "browser": {
    "./index.js": "./fallback.js"
  },
  "scripts": {
    "test": "standard && brittle test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/quickbit-universal.git"
  },
  "author": "Kasper Isager Dalsgarð <kasper@funktionel.co>",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/holepunchto/quickbit-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/quickbit-universal#readme",
  "dependencies": {
    "b4a": "^1.6.0",
    "simdle-universal": "^1.1.0"
  },
  "optionalDependencies": {
    "quickbit-native": "^2.2.0"
  },
  "devDependencies": {
    "brittle": "^3.1.0",
    "standard": "^17.0.0"
  }
}
class CacheEntry {
  constructor (key, index, map) {
    this.key = key
    this.index = index
    this.map = map
  }
}

class CacheValue {
  constructor (entry, value) {
    this.entry = entry
    this.value = value
  }
}

class Rache {
  constructor ({ maxSize = 65536, parent = null } = {}) {
    this.maxSize = parent?.maxSize || maxSize

    this._array = parent?._array || []
    this._map = new Map()
  }

  static from (cache) {
    return cache ? new this({ parent: cache }) : new this()
  }

  get globalSize () {
    return this._array.length
  }

  get size () {
    return this._map.size
  }

  sub () {
    return new Rache({ parent: this })
  }

  set (key, value) { // ~constant time
    const existing = this._map.get(key)
    if (existing !== undefined) {
      existing.value = value
      return
    }

    if (this._array.length >= this.maxSize) this._gc()

    const entry = new CacheEntry(key, this._array.length, this._map)
    this._array.push(entry)
    const cacheValue = new CacheValue(entry, value)
    this._map.set(key, cacheValue)
  }

  delete (key) {
    const existing = this._map.get(key)
    if (existing === undefined) return false

    this._delete(existing.entry.index)
    return true
  }

  get (key) {
    const existing = this._map.get(key)
    return existing === undefined ? undefined : existing.value
  }

  * [Symbol.iterator] () {
    for (const [key, { value }] of this._map) {
      yield [key, value]
    }
  }

  keys () {
    return this._map.keys()
  }

  * values () {
    for (const { value } of this._map.values()) {
      yield value
    }
  }

  clear () {
    // The entries in map linger on in _array,
    // so on top of clearing the map, we also kill the ref,
    // so that any gc running later on the old map won't interfere
    // (in case a new entry was added with the same key as a cleared entry)

    this._map.clear()
    this._map = new Map()
  }

  destroy () {
    this._map = null
    this._array = null
  }

  _gc () {
    this._delete(Math.floor(Math.random() * this._array.length))
  }

  _delete (index) { // ~constant time
    if (index >= this._array.length) throw new Error('Cannot delete unused index (logic bug?)')

    const head = this._array.pop()
    let removed = head

    if (index < this._array.length) {
      removed = this._array[index]
      head.index = index
      this._array[index] = head
    }

    removed.map.delete(removed.key)
  }
}

module.exports = Rache
{
  "name": "rache",
  "version": "1.0.0",
  "description": "Random-eviction cache",
  "main": "index.js",
  "scripts": {
    "test": "standard && brittle test.js --coverage"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/rache.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/rache/issues"
  },
  "homepage": "https://github.com/holepunchto/rache#readme",
  "files": [
    "index.js"
  ],
  "dependencies": {},
  "devDependencies": {
    "brittle": "^3.5.2",
    "standard": "^17.1.0"
  }
}
module.exports = class RandomArrayIterator {
  constructor (values) {
    this.values = values
    this.start = 0
    this.length = this.values.length
  }

  next () {
    if (this.length === 0) {
      if (this.start === 0) return { done: true, value: undefined }
      this.length = this.start
      this.start = 0
    }

    const i = this.start + ((Math.random() * this.length) | 0)
    const j = this.start + --this.length
    const value = this.values[i]

    this.values[i] = this.values[j]
    this.values[j] = value

    return { done: false, value }
  }

  dequeue () {
    this.values[this.start + this.length] = this.values[this.values.length - 1]
    this.values.pop()
  }

  requeue () {
    const i = this.start + this.length
    const value = this.values[i]
    this.values[i] = this.values[this.start]
    this.values[this.start++] = value
  }

  restart () {
    this.start = 0
    this.length = this.values.length
    return this
  }

  [Symbol.iterator] () {
    return this
  }
}
{
  "name": "random-array-iterator",
  "version": "1.0.0",
  "description": "An iterator to iterate an array in random order with controls to requeue or dequeue elements during the iteration",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^16.0.3",
    "tape": "^5.0.1"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/random-array-iterator.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/random-array-iterator/issues"
  },
  "homepage": "https://github.com/mafintosh/random-array-iterator"
}
const EventEmitter = require('events')

module.exports = class ReadyResource extends EventEmitter {
  constructor () {
    super()

    this.opening = null
    this.closing = null

    this.opened = false
    this.closed = false
  }

  ready () {
    if (this.opening !== null) return this.opening
    this.opening = open(this)
    return this.opening
  }

  close () {
    if (this.closing !== null) return this.closing
    this.closing = close(this)
    return this.closing
  }

  async _open () {
    // add impl here
  }

  async _close () {
    // add impl here
  }
}

async function open (self) {
  // open after close
  if (self.closing !== null) return

  try {
    await self._open()
  } catch (err) {
    self.close() // safe to run in bg
    throw err
  }

  self.opened = true
  self.emit('ready')
}

async function close (self) {
  try {
    if (self.opened === false && self.opening !== null) await self.opening
  } catch {
    // ignore errors on closing
  }
  if (self.opened === true || self.opening === null) await self._close()
  self.closed = true
  self.emit('close')
}
{
  "name": "ready-resource",
  "version": "1.2.0",
  "description": "Modern single resource management",
  "main": "index.js",
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "types": "index.d.ts",
  "files": [
    "index.js",
    "index.d.ts"
  ],
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "devDependencies": {
    "brittle": "^3.1.0",
    "standard": "^17.0.0"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/ready-resource.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/ready-resource/issues"
  },
  "homepage": "https://github.com/holepunchto/ready-resource",
  "dependencies": {
    "bare-events": "^2.2.0"
  }
}
module.exports = class RefCounter {
  constructor() {
    this.count = 0

    this._onidle = null
    this._idle = null
  }

  isIdle() {
    return this.count === 0
  }

  idle() {
    if (this.count === 0) return Promise.resolve()
    if (this._idle !== null) return this._idle

    this._idle = new Promise((resolve) => {
      this._onidle = resolve
    })

    return this._idle
  }

  inc() {
    this.count++
  }

  dec() {
    if (--this.count > 0) return

    if (this._onidle !== null) {
      const resolve = this._onidle
      this._idle = null
      this._onidle = null
      resolve()
    }
  }
}
{
  "name": "refcounter",
  "version": "1.0.0",
  "description": "Simple refcounter",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {},
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/refcounter.git"
  },
  "author": "Holepunch Inc",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/refcounter/issues"
  },
  "homepage": "https://github.com/holepunchto/refcounter"
}
module.exports = require.addon.bind(require)
{
  "name": "require-addon",
  "version": "1.2.0",
  "description": "Import native addons across JavaScript runtimes",
  "exports": {
    "./package": "./package.json",
    ".": {
      "bare": "./lib/bare.js",
      "node": "./lib/node.js",
      "default": "./lib/default.js"
    }
  },
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    },
    "url": {
      "bare": "bare-url",
      "default": "url"
    }
  },
  "files": [
    "lib"
  ],
  "scripts": {
    "test": "npm run lint && npm run test:bare && npm run test:node",
    "test:bare": "bare test.js",
    "test:node": "node test.js",
    "lint": "prettier --check .",
    "format": "prettier --write ."
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/require-addon.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/require-addon/issues"
  },
  "homepage": "https://github.com/holepunchto/require-addon#readme",
  "engines": {
    "bare": ">=1.10.0"
  },
  "dependencies": {
    "bare-addon-resolve": "^1.3.0"
  },
  "devDependencies": {
    "bare-bundle": "^1.8.1",
    "bare-bundle-evaluate": "^1.1.0",
    "bare-fs": "^4.0.0",
    "bare-path": "^3.0.0",
    "bare-url": "^2.1.0",
    "brittle": "^3.7.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
let tmpResolve = null
let tmpReject = null

if (Promise.withResolvers) {
  module.exports = Promise.withResolvers.bind(Promise)
} else {
  module.exports = function resolveRejectPromise () {
    const promise = new Promise(setTmp)
    const result = { promise, resolve: tmpResolve, reject: tmpReject }
    tmpResolve = tmpReject = null
    return result
  }
}

function setTmp (resolve, reject) {
  tmpResolve = resolve
  tmpReject = reject
}
{
  "name": "resolve-reject-promise",
  "version": "1.1.0",
  "description": "Create an inverted promise with no function allocs",
  "main": "index.js",
  "scripts": {
    "test": "standard"
  },
  "devDependencies": {
    "standard": "^17.1.2"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/resolve-reject-promise.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/resolve-reject-promise/issues"
  },
  "homepage": "https://github.com/mafintosh/resolve-reject-promise"
}
const resources = new Map()

exports.add = function(resource, teardown) {
  resources.set(resource, teardown)
}

exports.remove = function(resource) {
  resources.delete(resource)
}

if (global.Bare) global.Bare.on('exit', run)
else global.process.on('exit', run)

function run() {
  for (const [resource, teardown] of resources) {
    teardown(resource)
  }
}
{
  "name": "resource-on-exit",
  "version": "1.0.0",
  "description": "Register sync teardown handlers for a resource",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {},
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/bare-teardown.git"
  },
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-teardown/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-teardown"
}
require.addon = require('require-addon')

module.exports = require.addon('.', __filename)
const ColumnFamily = require('./lib/column-family')
const Iterator = require('./lib/iterator')
const Snapshot = require('./lib/snapshot')
const State = require('./lib/state')
const { BloomFilterPolicy, RibbonFilterPolicy } = require('./lib/filter-policy')
const constants = require('./lib/constants')

class RocksDB {
  constructor(path, opts = {}) {
    const {
      columnFamily,
      state = new State(this, path, opts),
      snapshot = null,
      keyEncoding = null,
      valueEncoding = null
    } = opts

    this._state = state
    this._snapshot = snapshot
    this._columnFamily = state.getColumnFamily(columnFamily)
    this._keyEncoding = keyEncoding
    this._valueEncoding = valueEncoding
    this._index = -1

    this._state.addSession(this)
  }

  get opened() {
    return this._state.opened
  }

  get closed() {
    return this.isRoot() ? this._state.closed : this._index === -1
  }

  get path() {
    return this._state.path
  }

  get stats() {
    return this._state.stats
  }

  get snapshotted() {
    return this._snapshot !== null
  }

  get defaultColumnFamily() {
    return this._columnFamily
  }

  session({
    columnFamily = this._columnFamily,
    snapshot = this._snapshot !== null,
    keyEncoding = this._keyEncoding,
    valueEncoding = this._valueEncoding
  } = {}) {
    maybeClosed(this)

    return new RocksDB(null, {
      state: this._state,
      columnFamily,
      snapshot: snapshot ? this._snapshot || new Snapshot(this._state) : null,
      keyEncoding,
      valueEncoding
    })
  }

  columnFamily(name, opts) {
    return this.session({ ...opts, columnFamily: name })
  }

  snapshot() {
    return this.session({ snapshot: true })
  }

  isRoot() {
    return this === this._state.db
  }

  ready() {
    return this._state.ready()
  }

  async close({ force } = {}) {
    if (!this._state.opened) await this._state.ready()

    if (this._index !== -1) this._state.removeSession(this)

    if (force) {
      while (this._state.sessions.length > 0) {
        await this._state.sessions[this._state.sessions.length - 1].close()
      }
    }

    return this.isRoot() ? this._state.close() : Promise.resolve()
  }

  suspend() {
    maybeClosed(this)

    return this._state.suspend()
  }

  resume() {
    maybeClosed(this)

    return this._state.resume()
  }

  isIdle() {
    return this._state.handles.isIdle()
  }

  idle() {
    return this._state.handles.idle()
  }

  iterator(range, opts) {
    maybeClosed(this)

    return new Iterator(this, { ...range, ...opts })
  }

  async *keys(range, opts) {
    for await (const { key } of this.iterator(range, {
      ...opts,
      values: false
    })) {
      yield key
    }
  }

  async peek(range, opts) {
    for await (const value of this.iterator({ ...range, ...opts, limit: 1 })) {
      return value
    }

    return null
  }

  read(opts) {
    maybeClosed(this)

    return this._state.createReadBatch(this, opts)
  }

  write(opts) {
    maybeClosed(this)

    return this._state.createWriteBatch(this, opts)
  }

  flush(opts) {
    maybeClosed(this)

    return this._state.flush(this, opts)
  }

  async get(key, opts) {
    const batch = this.read({ ...opts, capacity: 1, autoDestroy: true })
    const value = batch.get(key)
    batch.tryFlush()
    return value
  }

  async put(key, value, opts) {
    const batch = this.write({ ...opts, capacity: 1, autoDestroy: true })
    batch.tryPut(key, value)
    await batch.flush()
  }

  async delete(key, opts) {
    const batch = this.write({ ...opts, capacity: 1, autoDestroy: true })
    batch.tryDelete(key)
    await batch.flush()
  }

  async deleteRange(start, end, opts) {
    const batch = this.write({ ...opts, capacity: 1, autoDestroy: true })
    batch.tryDeleteRange(start, end)
    await batch.flush()
  }

  async compactRange(start = null, end = null, opts = {}) {
    if (typeof end === 'object' && end !== null) {
      opts = end
      end = null
    } else if (typeof start === 'object' && start !== null) {
      opts = start
      start = null
      end = null
    }

    await this._state.compactRange(this, start, end, opts)
  }

  async approximateSize(start, end, opts = {}) {
    return this._state.approximateSize(this, start, end, opts)
  }

  _ref() {
    if (this._snapshot) this._snapshot.ref()
    this._state.handles.inc()
  }

  _unref() {
    if (this._snapshot) this._snapshot.unref()
    this._state.handles.dec()
  }
}

module.exports = exports = RocksDB

exports.constants = constants

exports.ColumnFamily = ColumnFamily
exports.BloomFilterPolicy = BloomFilterPolicy
exports.RibbonFilterPolicy = RibbonFilterPolicy

function maybeClosed(db) {
  if (db._state.closing || db._index === -1) throw new Error('RocksDB session is closed')
}
const c = require('compact-encoding')
const binding = require('../binding')

const empty = Buffer.alloc(0)
const resolved = Promise.resolve()

class RocksDBBatch {
  constructor(db, opts = {}) {
    const { capacity = 8, autoDestroy = false } = opts

    db._ref()

    this._db = db
    this._destroyed = false
    this._capacity = capacity
    this._operations = []
    this._promises = []

    this._enqueuePromise = this._enqueuePromise.bind(this)

    this._request = null
    this._resolve = null
    this._reject = null

    this._handle = null
    this._buffer = null
    this._autoDestroy = autoDestroy
    this._stats = null

    this._resetStats()

    if (db._state.opened === true) this.ready()
  }

  _reuse(db, opts = {}) {
    const { autoDestroy = false } = opts

    db._ref()

    this._db = db
    this._destroyed = false
    this._autoDestroy = autoDestroy
  }

  _onfinished(err) {
    const resolve = this._resolve
    const reject = this._reject

    if (this._request) this._db._state.io.dec()

    this._operations = []
    this._promises = []
    this._request = null
    this._resolve = null
    this._reject = null

    this._resetStats()

    if (this._autoDestroy === true) this.destroy()

    if (reject !== null && err) reject(err)
    else if (resolve !== null) resolve()
  }

  _resize() {
    if (this._operations.length <= this._capacity) return false

    while (this._operations.length > this._capacity) {
      this._capacity *= 2
    }

    return true
  }

  async ready() {
    if (this._handle !== null) return

    if (this._db._state.opened === false) await this._db._state.ready()

    this._init()
  }

  destroy() {
    if (this._request) throw new Error('Request in progress')
    if (this._destroyed) return

    this._destroyed = true

    if (this._promises.length) this._abort()

    this._db._unref()
    this._onfree()
  }

  _onfree() {
    this._resetStats()
    this._db._state.freeBatch(this, false)
    this._db = null
  }

  _abort() {
    for (let i = 0; i < this._promises.length; i++) {
      const promise = this._promises[i]
      if (promise !== null) promise.reject(new Error('Batch is destroyed'))
    }

    this._onfinished(new Error('Batch is destroyed'))
  }

  _resetStats() {}

  async flush() {
    if (this._request) throw new Error('Request in progress')
    if (this._destroyed) throw new Error('Batch is destroyed')

    this._request = new Promise((resolve, reject) => {
      this._resolve = resolve
      this._reject = reject
    })

    this._flush()

    return this._request
  }

  tryFlush() {
    if (this._request) throw new Error('Request in progress')
    if (this._destroyed) throw new Error('Batch is destroyed')

    this._request = resolved

    this._flush()
  }

  async _flush() {
    if (this._handle === null) await this.ready()

    this._db._state.io.inc()

    if (this._db._state.resumed !== null) {
      const resumed = await this._db._state.resumed.promise

      if (!resumed) {
        if (this._destroyed) {
          this._db._state.io.dec()
        } else {
          this._destroyed = true
          this._abort()
          this._db._unref()
        }
      }
    }
  }

  _enqueuePromise(resolve, reject) {
    this._promises.push({ resolve, reject })
  }

  _encodeKey(k) {
    if (this._db._keyEncoding) return c.encode(this._db._keyEncoding, k)
    if (typeof k === 'string') return Buffer.from(k)
    return k
  }

  _encodeValue(v) {
    if (this._db._valueEncoding) return c.encode(this._db._valueEncoding, v)
    if (v === null) return empty
    if (typeof v === 'string') return Buffer.from(v)
    return v
  }

  _decodeValue(b) {
    if (this._db._valueEncoding) return c.decode(this._db._valueEncoding, b)
    return b
  }
}

exports.ReadBatch = class RocksDBReadBatch extends RocksDBBatch {
  constructor(db, opts = {}) {
    super(db, opts)

    const { asyncIO = false, fillCache = true } = opts

    this._asyncIO = asyncIO
    this._fillCache = fillCache
  }

  _init() {
    this._handle = binding.readInit()
    this._buffer = binding.readBuffer(this._handle, this._capacity)
  }

  _resize() {
    if (super._resize() && this._handle !== null) {
      this._buffer = binding.readBuffer(this._handle, this._capacity)
    }
  }

  async _flush() {
    await super._flush()

    if (this._destroyed) return

    try {
      binding.read(
        this._db._state._handle,
        this._handle,
        this._operations,
        this._db._snapshot ? this._db._snapshot._handle : undefined,
        this._asyncIO,
        this._fillCache,
        this,
        this._onread
      )
    } catch (err) {
      this._db._state.io.dec()
      throw err
    }

    this._db._state.stats.gets += this._stats.gets
    this._db._state.stats.readBatches++
  }

  _onread(errs, values) {
    let applied = true

    for (let i = 0, n = this._promises.length; i < n; i++) {
      const err = errs[i]
      if (err) applied = false

      const promise = this._promises[i]
      if (promise === null) continue

      if (err) promise.reject(err)
      else promise.resolve(values[i] ? this._decodeValue(Buffer.from(values[i])) : null)
    }

    this._onfinished(applied ? null : new AggregateError(errs, 'Batch was not applied'))
  }

  _resetStats() {
    this._stats = { gets: 0 }
  }

  get(key) {
    if (this._request) throw new Error('Request already in progress')
    this._stats.gets++

    const promise = new Promise(this._enqueuePromise)

    this._operations.push(new RocksDBGet(this._encodeKey(key), this._db._columnFamily))

    this._resize()

    return promise
  }
}

exports.WriteBatch = class RocksDBWriteBatch extends RocksDBBatch {
  _init() {
    this._handle = binding.writeInit()
    this._buffer = binding.writeBuffer(this._handle, this._capacity)
  }

  _resize() {
    if (super._resize() && this._handle !== null) {
      this._buffer = binding.writeBuffer(this._handle, this._capacity)
    }
  }

  _onfree() {
    this._resetStats()
    this._db._state.freeBatch(this, true)
    this._db = null
  }

  async _flush() {
    await super._flush()

    if (this._destroyed) return

    try {
      binding.write(this._db._state._handle, this._handle, this._operations, this, this._onwrite)
    } catch (err) {
      this._db._state.io.dec()
      throw err
    }

    this._db._state.stats.puts += this._stats.puts
    this._db._state.stats.deletes += this._stats.deletes
    this._db._state.stats.rangeDeletes += this._stats.rangeDeletes
    this._db._state.stats.writeBatches++
  }

  _onwrite(err) {
    const applied = !err

    for (let i = 0, n = this._promises.length; i < n; i++) {
      const promise = this._promises[i]
      if (promise === null) continue

      if (err) promise.reject(err)
      else promise.resolve()
    }

    this._onfinished(applied ? null : new Error('Batch was not applied', { cause: err }))
  }

  _resetStats() {
    this._stats = { puts: 0, deletes: 0, rangeDeletes: 0 }
  }

  put(key, value) {
    if (this._request) throw new Error('Request already in progress')
    this._stats.puts++

    const promise = new Promise(this._enqueuePromise)

    this._operations.push(
      new RocksDBPut(this._encodeKey(key), this._encodeValue(value), this._db._columnFamily)
    )

    this._resize()

    return promise
  }

  tryPut(key, value) {
    if (this._request) throw new Error('Request already in progress')
    this._stats.puts++

    this._operations.push(
      new RocksDBPut(this._encodeKey(key), this._encodeValue(value), this._db._columnFamily)
    )

    this._promises.push(null)

    this._resize()
  }

  delete(key) {
    if (this._request) throw new Error('Request already in progress')
    this._stats.deletes++

    const promise = new Promise(this._enqueuePromise)

    this._operations.push(new RocksDBDelete(this._encodeKey(key), this._db._columnFamily))

    this._resize()

    return promise
  }

  tryDelete(key) {
    if (this._request) throw new Error('Request already in progress')
    this._stats.deletes++

    this._operations.push(new RocksDBDelete(this._encodeKey(key), this._db._columnFamily))

    this._promises.push(null)

    this._resize()
  }

  deleteRange(start, end) {
    if (this._request) throw new Error('Request already in progress')
    this._stats.rangeDeletes++

    const promise = new Promise(this._enqueuePromise)

    this._operations.push(
      new RocksDBDeleteRange(this._encodeKey(start), this._encodeKey(end), this._db._columnFamily)
    )

    this._resize()

    return promise
  }

  tryDeleteRange(start, end) {
    if (this._request) throw new Error('Request already in progress')
    this._stats.rangeDeletes++

    this._operations.push(
      new RocksDBDeleteRange(this._encodeKey(start), this._encodeKey(end), this._db._columnFamily)
    )

    this._promises.push(null)

    this._resize()
  }
}

class RocksDBGet {
  constructor(key, columnFamily) {
    this.key = key
    this.columnFamily = columnFamily._handle
  }

  get type() {
    return binding.GET
  }
}

class RocksDBPut {
  constructor(key, value, columnFamily) {
    this.key = key
    this.value = value
    this.columnFamily = columnFamily._handle
  }

  get type() {
    return binding.PUT
  }
}

class RocksDBDelete {
  constructor(key, columnFamily) {
    this.key = key
    this.columnFamily = columnFamily._handle
  }

  get type() {
    return binding.DELETE
  }
}

class RocksDBDeleteRange {
  constructor(start, end, columnFamily) {
    this.start = start
    this.end = end
    this.columnFamily = columnFamily._handle
  }

  get type() {
    return binding.DELETE_RANGE
  }
}
const binding = require('../binding')
const constants = require('./constants')
const { BloomFilterPolicy } = require('./filter-policy')

class RocksDBColumnFamily {
  constructor(name, opts = {}) {
    const {
      // Blob options
      enableBlobFiles = false,
      minBlobSize = 0,
      blobFileSize = 0,
      enableBlobGarbageCollection = true,
      // Block table options
      tableBlockSize = 8192,
      tableCacheIndexAndFilterBlocks = true,
      tableFormatVersion = 6,
      optimizeFiltersForMemory = false,
      blockCache = true,
      filterPolicy = new BloomFilterPolicy(10),
      topLevelIndexPinningTier = constants.pinningTier.ALL,
      partitionPinningTier = constants.pinningTier.ALL,
      unpartitionedPinningTier = constants.pinningTier.ALL,
      optimizeFiltersForHits = false,
      numLevels = 7,
      maxWriteBufferNumber = 2,
      blobGarbageCollectionAgeCutOff = 0.25,
      blobGarbageCollectionForceThreshold = 1.0
    } = opts

    this._name = name
    this._flushing = null
    this._options = {
      enableBlobFiles,
      minBlobSize,
      blobFileSize,
      enableBlobGarbageCollection,
      tableBlockSize,
      tableCacheIndexAndFilterBlocks,
      tableFormatVersion,
      optimizeFiltersForMemory,
      blockCache,
      filterPolicy,
      topLevelIndexPinningTier,
      partitionPinningTier,
      unpartitionedPinningTier,
      optimizeFiltersForHits,
      numLevels,
      maxWriteBufferNumber
    }

    const filterPolicyArguments = [0, 0, 0]

    if (filterPolicy !== null) {
      filterPolicyArguments[0] = filterPolicy.type

      switch (filterPolicy.type) {
        case 1: // Bloom filter policy
          filterPolicyArguments[1] = filterPolicy.bitsPerKey
          break
        case 2: // Ribbon filter policy
          filterPolicyArguments[1] = filterPolicy.bloomEquivalentBitsPerKey
          filterPolicyArguments[2] = filterPolicy.bloomBeforeLevel

          break
      }
    }

    this._handle = binding.columnFamilyInit(
      name,
      enableBlobFiles,
      minBlobSize,
      blobFileSize,
      enableBlobGarbageCollection,
      tableBlockSize,
      tableCacheIndexAndFilterBlocks,
      tableFormatVersion,
      optimizeFiltersForMemory,
      blockCache === false,
      ...filterPolicyArguments,
      topLevelIndexPinningTier,
      partitionPinningTier,
      unpartitionedPinningTier,
      optimizeFiltersForHits,
      numLevels,
      maxWriteBufferNumber,
      blobGarbageCollectionAgeCutOff,
      blobGarbageCollectionForceThreshold
    )
  }

  cloneSettings(name) {
    return new RocksDBColumnFamily(name, this._options)
  }

  get name() {
    return this._name
  }

  destroy() {
    if (this._handle === null) return

    binding.columnFamilyDestroy(this._handle)

    this._handle = null
  }
}

module.exports = RocksDBColumnFamily
module.exports = {
  pinningTier: {
    NONE: 0,
    FLUSHED_AND_SIMILAR: 1,
    ALL: 2
  },
  garbageCollectionPolicy: {
    DEFAULT: 0,
    FORCE: 1,
    DISABLE: 2
  },
  bottommostLevelCompaction: {
    NONE: 0,
    SKIP: 1,
    FORCE: 2
  },
  walRecoveryMode: {
    TOLERATE_CORRUPTED_TAIL_RECORDS: 0,
    ABSOLUTE_CONSISTENCY: 1,
    POINT_IN_TIME: 2,
    SKIP_ANY_CORRUPTED_RECORDS: 3
  }
}
exports.BloomFilterPolicy = class RocksDBBloomFilterPolicy {
  get type() {
    return 1
  }

  constructor(bitsPerKey) {
    this.bitsPerKey = bitsPerKey
  }
}

exports.RibbonFilterPolicy = class RocksDBRibbonFilterPolicy {
  get type() {
    return 2
  }

  constructor(bloomEquivalentBitsPerKey, bloomBeforeLevel = 0) {
    this.bloomEquivalentBitsPerKey = bloomEquivalentBitsPerKey
    this.bloomBeforeLevel = bloomBeforeLevel
  }
}
const { Readable } = require('streamx')
const c = require('compact-encoding')
const binding = require('../binding')

const empty = Buffer.alloc(0)

module.exports = class RocksDBIterator extends Readable {
  constructor(db, opts = {}) {
    const {
      gt = null,
      gte = null,
      lt = null,
      lte = null,
      reverse = false,
      values = true,
      limit = Infinity,
      capacity = 8
    } = opts

    super()

    db._ref()

    this._db = db

    this._gt = gt ? this._encodeKey(gt) : empty
    this._gte = gte ? this._encodeKey(gte) : empty
    this._lt = lt ? this._encodeKey(lt) : empty
    this._lte = lte ? this._encodeKey(lte) : empty

    this._reverse = reverse
    this._values = values
    this._limit = limit < 0 ? Infinity : limit
    this._capacity = capacity
    this._opened = false

    this._pendingOpen = null
    this._pendingRead = null
    this._pendingDestroy = null

    this._buffer = null
    this._handle = null

    if (this._db._state.opened === true) this.ready()
  }

  _onopen(err) {
    const cb = this._pendingOpen
    this._pendingOpen = null
    this._opened = true
    this._db._state.io.dec()
    cb(err)
  }

  _onread(err, keys, values) {
    const cb = this._pendingRead
    this._pendingRead = null
    this._db._state.io.dec()
    if (err) return cb(err)

    const n = keys.length

    this._limit -= n

    for (let i = 0; i < n; i++) {
      this.push({
        key: this._decodeKey(Buffer.from(keys[i])),
        value: this._values ? this._decodeValue(Buffer.from(values[i])) : null
      })
    }

    if (n < this._capacity) this.push(null)

    cb(null)
  }

  _onclose(err) {
    const cb = this._pendingDestroy
    this._pendingDestroy = null
    this._db._state.io.dec()
    this._db._unref()
    cb(err)
  }

  _resize() {
    if (this._handle !== null) {
      this._buffer = binding.iteratorBuffer(this._handle, this._capacity)
    }
  }

  async ready() {
    if (this._handle !== null) return

    if (this._db._state.opened === false) await this._db._state.ready()

    this._init()
  }

  _init() {
    this._handle = binding.iteratorInit()
    this._buffer = binding.iteratorBuffer(this._handle, this._capacity)
  }

  async _open(cb) {
    await this.ready()

    this._db._state.io.inc()

    if (this._db._state.resumed !== null) {
      const resumed = await this._db._state.resumed.promise

      if (!resumed) {
        this._db._state.io.dec()

        return cb(new Error('RocksDB session is closed'))
      }
    }

    this._pendingOpen = cb

    try {
      binding.iteratorOpen(
        this._db._state._handle,
        this._handle,
        this._db._columnFamily._handle,
        this._gt,
        this._gte,
        this._lt,
        this._lte,
        this._reverse,
        !this._values, // Keys only
        this._db._snapshot ? this._db._snapshot._handle : undefined,
        this,
        this._onopen,
        this._onclose,
        this._onread
      )
    } catch (err) {
      this._db._state.io.dec()

      cb(err)
    }
  }

  async _read(cb) {
    this._db._state.io.inc()

    if (this._db._state.resumed !== null) {
      const resumed = await this._db._state.resumed.promise

      if (!resumed) {
        this._db._state.io.dec()

        return cb(new Error('RocksDB session is closed'))
      }
    }

    this._pendingRead = cb

    try {
      binding.iteratorRead(this._handle, Math.min(this._capacity, this._limit))
    } catch (err) {
      this._db._state.io.dec()

      cb(err)
    }
  }

  async _destroy(cb) {
    await this.ready()

    this._db._state.io.inc()

    if (this._opened === false) {
      this._db._state.io.dec()
      this._db._unref()

      return cb(null)
    }

    this._pendingDestroy = cb

    try {
      binding.iteratorClose(this._handle)
    } catch (err) {
      this._db._state.io.dec()
      this._db._unref()

      cb(err)
    }
  }

  _encodeKey(k) {
    if (this._db._keyEncoding !== null) return c.encode(this._db._keyEncoding, k)
    if (typeof k === 'string') return Buffer.from(k)
    return k
  }

  _decodeKey(b) {
    if (this._db._keyEncoding !== null) return c.decode(this._db._keyEncoding, b)
    return b
  }

  _decodeValue(b) {
    if (this._db._valueEncoding !== null) return c.decode(this._db._valueEncoding, b)
    return b
  }
}
const binding = require('../binding')

module.exports = class RocksDBSnapshot {
  constructor(state) {
    this._state = state

    this._handle = null
    this._refs = 0

    if (state.deferSnapshotInit === false) this._init()
  }

  _init() {
    this._handle = binding.snapshotCreate(this._state._handle)
  }

  ref() {
    this._refs++
  }

  unref() {
    if (--this._refs > 0) return

    if (this._handle === null) return

    binding.snapshotDestroy(this._handle)

    this._handle = null
  }
}
const ReadyResource = require('ready-resource')
const RefCounter = require('refcounter')
const rrp = require('resolve-reject-promise')
const SignalPromise = require('signal-promise')
const c = require('compact-encoding')
const { ReadBatch, WriteBatch } = require('./batch')
const ColumnFamily = require('./column-family')
const binding = require('../binding')
const constants = require('./constants')

const MAX_BATCH_REUSE = 64
const empty = Buffer.alloc(0)

module.exports = class RocksDBState extends ReadyResource {
  constructor(db, path, opts) {
    super()

    const {
      columnFamily = new ColumnFamily('default', opts),
      columnFamilies = [],
      readOnly = false,
      createIfMissing = true,
      createMissingColumnFamilies = true,
      maxBackgroundJobs = 6,
      bytesPerSync = 1048576,
      maxOpenFiles = -1,
      useDirectReads = false,
      avoidUnnecessaryBlockingIO = false,
      skipStatsUpdateOnOpen = false,
      useDirectIOForFlushAndCompaction = false,
      maxFileOpeningThreads = 16,
      lock = null,
      walRecoveryMode = constants.walRecoveryMode.POINT_IN_TIME,
      bestEffortsRecovery = false
    } = opts

    this.path = path
    this.db = db
    this.handles = new RefCounter()
    this.io = new RefCounter()
    this.sessions = []
    this.columnFamilies = [columnFamily]
    this.deferSnapshotInit = true
    this.resumed = null
    this.stats = {
      gets: 0,
      puts: 0,
      deletes: 0,
      rangeDeletes: 0,
      readBatches: 0,
      writeBatches: 0
    }

    this._suspended = false
    this._suspending = false
    this._updating = false
    this._updatingSignal = new SignalPromise()
    this._columnsFlushed = false
    this._lock = lock
    this._readBatches = []
    this._writeBatches = []

    for (const columnFamily of columnFamilies) {
      this.columnFamilies.push(
        typeof columnFamily === 'string' ? new ColumnFamily(columnFamily, opts) : columnFamily
      )
    }

    this._handle = binding.init(
      readOnly,
      createIfMissing,
      createMissingColumnFamilies,
      maxBackgroundJobs,
      bytesPerSync,
      maxOpenFiles,
      useDirectReads,
      avoidUnnecessaryBlockingIO,
      skipStatsUpdateOnOpen,
      useDirectIOForFlushAndCompaction,
      maxFileOpeningThreads,
      walRecoveryMode,
      bestEffortsRecovery
    )
  }

  createReadBatch(db, opts) {
    if (this._readBatches.length === 0) return new ReadBatch(db, opts)
    const batch = this._readBatches.pop()
    batch._reuse(db, opts)
    return batch
  }

  createWriteBatch(db, opts) {
    if (this._writeBatches.length === 0) return new WriteBatch(db, opts)
    const batch = this._writeBatches.pop()
    batch._reuse(db, opts)
    return batch
  }

  freeBatch(batch, writable) {
    if (batch._capacity > 16) return
    const queue = writable ? this._writeBatches : this._readBatches
    if (queue.length >= MAX_BATCH_REUSE) return
    queue.push(batch)
  }

  addSession(db) {
    db._index = this.sessions.push(db) - 1
    if (db._snapshot) db._snapshot.ref()
  }

  removeSession(db) {
    const head = this.sessions.pop()
    if (head !== db) this.sessions[(head._index = db._index)] = head
    db._index = -1
    if (db._snapshot) db._snapshot.unref()
  }

  upsertColumnFamily(c) {
    if (typeof c === 'string') {
      let col = this.getColumnFamilyByName(c)
      if (col) return col
      col = this.columnFamilies[0].cloneSettings(c)
      this.columnFamilies.push(col)
      return col
    }

    if (this.columnFamilies.includes(c)) return c
    this.columnFamilies.push(c)
    return c
  }

  getColumnFamily(c) {
    if (!c) return this.columnFamilies[0]
    if (!this._columnsFlushed) return this.upsertColumnFamily(c)

    if (typeof c !== 'string') return c

    const col = this.getColumnFamilyByName(c)
    if (col === null) throw new Error('Unknown column family')
    return col
  }

  getColumnFamilyByName(name) {
    for (const col of this.columnFamilies) {
      if (col.name === name) return col
    }
    return null
  }

  async _open() {
    await Promise.resolve() // Allow column families to populate if on-demand

    if (this._lock) await this._lock.ready()

    const req = { resolve: null, reject: null, handle: null }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    this._columnsFlushed = true

    const lock = this._lock === null ? -1 : this._lock.transfer()

    req.handle = binding.open(
      this._handle,
      this,
      this.path,
      this.columnFamilies.map((c) => c._handle),
      lock,
      req,
      onopen
    )

    await promise

    this.deferSnapshotInit = false

    for (const session of this.sessions) {
      if (session._snapshot) session._snapshot._init()
    }

    function onopen(err) {
      if (err) req.reject(err)
      else req.resolve()
    }
  }

  async _close() {
    while (this._updating) await this._updatingSignal.wait()
    if (this.resumed) this.resumed.resolve(false)

    while (!this.io.isIdle()) await this.io.idle()
    while (!this.handles.isIdle()) await this.handles.idle()

    while (this.sessions.length > 0) {
      await this.sessions[this.sessions.length - 1].close()
    }

    for (const columnFamily of this.columnFamilies) columnFamily.destroy()

    const req = { resolve: null, reject: null, handle: null }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    req.handle = binding.close(this._handle, req, onclose)

    try {
      await promise
    } finally {
      if (this._lock) await this._lock.close()
    }

    function onclose(err) {
      if (err) req.reject(err)
      else req.resolve()
    }
  }

  async flush(db, opts) {
    if (this.opened === false) await this.ready()

    this.io.inc()

    if (this.resumed !== null) {
      const resumed = await this.resumed.promise

      if (!resumed) {
        this.io.dec()

        throw new Error('RocksDB session is closed')
      }
    }

    const req = { resolve: null, reject: null, handle: null }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    try {
      req.handle = binding.flush(this._handle, db._columnFamily._handle, req, onflush)

      await promise
    } finally {
      this.io.dec()
    }

    function onflush(err) {
      if (err) req.reject(err)
      else req.resolve()
    }
  }

  suspend() {
    this._suspending = true
    return this.update()
  }

  resume() {
    this._suspending = false
    return this.update()
  }

  async update() {
    while (this._updating) await this._updatingSignal.wait()
    if (this._suspending === this._suspended || this.closing) return
    this._updating = true
    try {
      if (this._suspending) await this._suspend()
      else await this._resume()
    } finally {
      this._updating = false
      this._updatingSignal.notify()
    }
  }

  async _suspend() {
    if (this._suspended === true) return

    while (!this.io.isIdle()) await this.io.idle()

    this.io.inc()
    this.resumed = rrp()

    const req = { resolve: null, reject: null, handle: null }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    try {
      req.handle = binding.suspend(this._handle, req, onsuspend)

      await promise

      this._suspended = true
    } finally {
      this.io.dec()
    }

    function onsuspend(err) {
      if (err) req.reject(err)
      else req.resolve()
    }
  }

  async _resume() {
    if (this._suspended === false) return

    const req = { resolve: null, reject: null, handle: null }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    req.handle = binding.resume(this._handle, req, onresume)

    await promise

    this._suspended = false

    const resumed = this.resumed
    this.resumed = null
    resumed.resolve(true)

    function onresume(err) {
      if (err) req.reject(err)
      else req.resolve()
    }
  }

  async compactRange(db, start, end, opts) {
    if (this.opened === false) await this.ready()

    this.io.inc()

    const {
      exclusive = false,
      blobGarbageCollectionPolicy = constants.garbageCollectionPolicy.DEFAULT,
      blobGarbageCollectionAgeCutoff = 0.25,
      bottommostLevelCompaction = constants.bottommostLevelCompaction.NONE
    } = opts

    start = this._encodeKey(start)
    end = this._encodeKey(end)

    const req = { resolve: null, reject: null, handle: null, start, end }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    try {
      req.handle = binding.compactRange(
        this._handle,
        db._columnFamily._handle,
        start,
        end,
        exclusive,
        blobGarbageCollectionPolicy,
        blobGarbageCollectionAgeCutoff,
        bottommostLevelCompaction,
        req,
        oncompactrange
      )

      await promise
    } finally {
      this.io.dec()
    }

    function oncompactrange(err) {
      if (err) req.reject(err)
      else req.resolve()
    }
  }

  async approximateSize(db, start, end, opts) {
    if (this.opened === false) await this.ready()

    this.io.inc()

    const { includeMemtables = false, includeFiles = true, filesSizeErrorMargin = -1 } = opts

    start = this._encodeKey(start)
    end = this._encodeKey(end)

    const req = { resolve: null, reject: null, handle: null, start, end }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    try {
      req.handle = binding.approximateSize(
        this._handle,
        db._columnFamily._handle,
        start,
        end,
        includeMemtables,
        includeFiles,
        filesSizeErrorMargin,
        req,
        onapproximatesize
      )

      return await promise
    } finally {
      this.io.dec()
    }

    function onapproximatesize(err, result) {
      if (err) req.reject(err)
      else req.resolve(result)
    }
  }

  _encodeKey(k) {
    if (this.db._keyEncoding) return c.encode(this.db._keyEncoding, k)
    if (typeof k === 'string') return Buffer.from(k)
    if (k === null) return empty
    return k
  }
}
{
  "name": "rocksdb-native",
  "version": "3.15.0",
  "description": "librocksdb bindings for JavaScript",
  "exports": {
    ".": "./index.js",
    "./package": "./package.json"
  },
  "imports": {
    "crypto": {
      "bare": "bare-crypto",
      "default": "crypto"
    },
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    }
  },
  "files": [
    "index.js",
    "binding.cc",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds",
    "!prebuilds/android-*/**/*.node"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:bare": "brittle-bare test.js",
    "test:node": "brittle-node test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/rocksdb-native.git"
  },
  "author": "Holepunch Inc",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/rocksdb-native/issues"
  },
  "homepage": "https://github.com/holepunchto/rocksdb-native",
  "engines": {
    "bare": ">=1.16.0"
  },
  "dependencies": {
    "compact-encoding": "^2.15.0",
    "ready-resource": "^1.0.0",
    "refcounter": "^1.0.0",
    "require-addon": "^1.0.2",
    "resolve-reject-promise": "^1.1.0",
    "signal-promise": "^1.0.3",
    "streamx": "^2.16.1"
  },
  "devDependencies": {
    "bare-compat-napi": "^1.3.0",
    "bare-crypto": "^1.12.0",
    "bare-fs": "^4.5.0",
    "bare-path": "^3.0.0",
    "brittle": "^3.5.0",
    "cmake-bare": "^1.1.14",
    "cmake-fetch": "^1.0.1",
    "cmake-napi": "^1.0.6",
    "fd-lock": "^2.0.0",
    "lunte": "^1.3.0",
    "paparam": "^1.9.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = safetyCatch

function isActuallyUncaught (err) {
  if (!err) return false
  return err instanceof TypeError ||
    err instanceof SyntaxError ||
    err instanceof ReferenceError ||
    err instanceof EvalError ||
    err instanceof RangeError ||
    err instanceof URIError ||
    err.code === 'ERR_ASSERTION' ||
    err.name === 'AssertionError'
}

function throwErrorNT (err) {
  queueMicrotask(() => { throw err })
}

function safetyCatch (err) {
  if (isActuallyUncaught(err)) {
    throwErrorNT(err)
    throw err
  }
}
{
  "name": "safety-catch",
  "version": "1.0.3",
  "description": "Small module that makes sure your catch, caught an actual error and not a programming mistake or assertion",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {},
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/safety-catch.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/safety-catch/issues"
  },
  "homepage": "https://github.com/mafintosh/safety-catch"
}
let tmpResolve = null

module.exports = class ScopeLock {
  constructor ({ debounce = false } = {}) {
    this.debounce = debounce
    this.waiting = []
    this.locked = false
    this.skip = 0
    this.destroyed = false
  }

  flush () {
    if (this.locked === false && this.waiting.length === 0) return Promise.resolve(this.destroyed === false)

    const promise = new Promise(setTmpResolve)
    const resolve = tmpResolve

    tmpResolve = null
    this.waiting.push({ lock: false, resolve })

    return promise
  }

  destroy () {
    this.destroyed = true
  }

  lock () {
    const promise = new Promise(setTmpResolve)
    const resolve = tmpResolve

    tmpResolve = null

    if (this.locked === true) {
      this.waiting.push({ lock: true, resolve })
      return promise
    }

    if (this.destroyed === true) {
      resolve(false)
      return promise
    }

    this.locked = true
    resolve(true)

    return promise
  }

  unlock () {
    if (this.destroyed === true) {
      for (let i = 0; i < this.waiting.length; i++) {
        this.waiting[i].resolve(false)
      }
      this.waiting = []
      this.skip = 0
      this.locked = false
      return
    }

    if (this.skip !== 0) {
      for (let i = 0; i < this.skip; i++) {
        const { lock, resolve } = this.waiting[i]
        resolve(lock === false)
      }

      this.waiting = this.waiting.slice(this.skip)
      this.skip = 0
    }

    while (this.waiting.length > 0 && this.waiting[0].lock === false) {
      this.waiting.shift().resolve(true)
    }

    if (this.waiting.length === 0) {
      this.locked = false
      return
    }

    const { resolve } = this.waiting.shift()
    if (this.debounce === true) this.skip = this.waiting.length

    resolve(true)
  }
}

function setTmpResolve (resolve) {
  tmpResolve = resolve
}
{
  "name": "scope-lock",
  "version": "1.2.4",
  "description": "Some concurrency semantics around entering scopes",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "devDependencies": {
    "brittle": "^3.7.0",
    "standard": "^17.1.2"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/scope-lock.git"
  },
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/scope-lock/issues"
  },
  "homepage": "https://github.com/holepunchto/scope-lock"
}
module.exports = class Signal {
  constructor () {
    this._resolve = null
    this._reject = null
    this._promise = null
    this._bind = bind.bind(this)
    this._onerror = clear.bind(this)
    this._onsuccess = clear.bind(this, null)
    this._timers = new Set()
  }

  wait (max) {
    if (!this._promise) {
      this._promise = new Promise(this._bind)
      this._promise.then(this._onsuccess).catch(this._onerror)
    }
    if (max) return this._sleep(max)
    return this._promise
  }

  _sleep (max) {
    const s = new Promise((resolve, reject) => {
      const done = () => {
        this._timers.delete(state)
        resolve(true)
      }
      const id = setTimeout(done, max)
      const state = { id, resolve, reject }
      this._timers.add(state)
    })

    return s
  }

  notify (err) {
    if (!this._promise) return
    const resolve = this._resolve
    const reject = this._reject
    this._promise = null
    if (err) reject(err)
    else resolve(true)
  }
}

function clear (err) {
  for (const { id, resolve, reject } of this._timers) {
    clearTimeout(id)
    if (err) reject(err)
    else resolve(true)
  }
  this._timers.clear()
}

function bind (resolve, reject) {
  this._resolve = resolve
  this._reject = reject
}
{
  "name": "signal-promise",
  "version": "1.0.3",
  "description": "Simple wait/notify promise with optional max wait time",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {},
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/signal-promise.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/signal-promise/issues"
  },
  "homepage": "https://github.com/mafintosh/signal-promise"
}
var varint = require('varint')
exports.encode = function encode (v, b, o) {
  v = v >= 0 ? v*2 : v*-2 - 1
  var r = varint.encode(v, b, o)
  encode.bytes = varint.encode.bytes
  return r
}
exports.decode = function decode (b, o) {
  var v = varint.decode(b, o)
  decode.bytes = varint.decode.bytes
  return v & 1 ? (v+1) / -2 : v / 2
}

exports.encodingLength = function (v) {
  return varint.encodingLength(v >= 0 ? v*2 : v*-2 - 1)
}
{
  "name": "signed-varint",
  "description": "efficiently store signed integers in varint",
  "version": "2.0.1",
  "homepage": "https://github.com/dominictarr/signed-varint",
  "repository": {
    "type": "git",
    "url": "git://github.com/dominictarr/signed-varint.git"
  },
  "dependencies": {
    "varint": "~5.0.0"
  },
  "devDependencies": {
    "tape": "~2.12.3"
  },
  "scripts": {
    "test": "node test.js"
  },
  "author": "Dominic Tarr <dominic.tarr@gmail.com> (http://dominictarr.com)",
  "license": "MIT"
}
require.addon = require('require-addon')

module.exports = require.addon('.', __filename)
const binding = require('./binding')
const b4a = require('b4a')

function predicate(u8, u16, u32) {
  return function predicate(buf) {
    if (buf.byteLength % 16 !== 0) {
      throw new Error('Buffer length must be a multiple of 16')
    }

    const n = buf.BYTES_PER_ELEMENT

    if (n === 1) return u8(buf)
    if (n === 2) return u16(buf)
    return u32(buf)
  }
}

function unary(u8, u16, u32) {
  return function unary(buf, result = b4a.allocUnsafe(buf.byteLength)) {
    if (buf.byteLength % 16 !== 0) {
      throw new Error('Buffer length must be a multiple of 16')
    }

    if (buf.byteLength !== result.byteLength) {
      throw new Error('Length of result buffer is insufficient')
    }

    const n = buf.BYTES_PER_ELEMENT

    if (n === 1) u8(buf, result)
    else if (n === 2) u16(buf, result)
    else u32(buf, result)

    return result
  }
}

function binary(u8, u16, u32) {
  return function binary(a, b, result = b4a.allocUnsafe(a.byteLength)) {
    if (a.byteLength % 16 !== 0) {
      throw new Error('Buffer length must be a multiple of 16')
    }

    if (a.byteLength !== b.byteLength || a.byteLength !== result.byteLength) {
      throw new Error('Buffers must be the same length')
    }

    const n = a.BYTES_PER_ELEMENT

    if (n === 1) u8(a, b, result)
    else if (n === 2) u16(a, b, result)
    else u32(a, b, result)

    return result
  }
}

function reduce(u8, u16, u32) {
  return function reduce(buf) {
    if (buf.byteLength % 16 !== 0) {
      throw new Error('Buffer length must be a multiple of 16')
    }

    const n = buf.BYTES_PER_ELEMENT

    if (n === 1) return u8(buf)
    if (n === 2) return u16(buf)
    return u32(buf)
  }
}

exports.allo = predicate(
  binding.simdle_native_allo_v128_u8,
  binding.simdle_native_allo_v128_u16,
  binding.simdle_native_allo_v128_u32
)

exports.allz = predicate(
  binding.simdle_native_allz_v128_u8,
  binding.simdle_native_allz_v128_u16,
  binding.simdle_native_allz_v128_u32
)

exports.and = binary(
  binding.simdle_native_and_v128_u8,
  binding.simdle_native_and_v128_u16,
  binding.simdle_native_and_v128_u32
)

exports.clear = binary(
  binding.simdle_native_clear_v128_u8,
  binding.simdle_native_clear_v128_u16,
  binding.simdle_native_clear_v128_u32
)

exports.clo = unary(
  binding.simdle_native_clo_v128_u8,
  binding.simdle_native_clo_v128_u16,
  binding.simdle_native_clo_v128_u32
)

exports.clz = unary(
  binding.simdle_native_clz_v128_u8,
  binding.simdle_native_clz_v128_u16,
  binding.simdle_native_clz_v128_u32
)

exports.cnt = unary(
  binding.simdle_native_cnt_v128_u8,
  binding.simdle_native_cnt_v128_u16,
  binding.simdle_native_cnt_v128_u32
)

exports.cto = unary(
  binding.simdle_native_cto_v128_u8,
  binding.simdle_native_cto_v128_u16,
  binding.simdle_native_cto_v128_u32
)

exports.ctz = unary(
  binding.simdle_native_ctz_v128_u8,
  binding.simdle_native_ctz_v128_u16,
  binding.simdle_native_ctz_v128_u32
)

exports.not = unary(
  binding.simdle_native_not_v128_u8,
  binding.simdle_native_not_v128_u16,
  binding.simdle_native_not_v128_u32
)

exports.or = binary(
  binding.simdle_native_or_v128_u8,
  binding.simdle_native_or_v128_u16,
  binding.simdle_native_or_v128_u32
)

exports.sum = reduce(
  binding.simdle_native_sum_v128_u8,
  binding.simdle_native_sum_v128_u16,
  binding.simdle_native_sum_v128_u32
)

exports.xor = binary(
  binding.simdle_native_xor_v128_u8,
  binding.simdle_native_xor_v128_u16,
  binding.simdle_native_xor_v128_u32
)
{
  "name": "simdle-native",
  "version": "1.3.9",
  "description": "libsimdle JavaScript bindings for Node.js",
  "main": "index.js",
  "files": [
    "index.js",
    "binding.cc",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check .",
    "test": "npm run lint && npm run test:bare && npm run test:node",
    "test:bare": "bare test.mjs",
    "test:node": "node test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/simdle-native.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/simdle-native/issues"
  },
  "homepage": "https://github.com/holepunchto/simdle-native#readme",
  "dependencies": {
    "b4a": "^1.6.0",
    "require-addon": "^1.1.0"
  },
  "devDependencies": {
    "bare-compat-napi": "^1.3.2",
    "brittle": "^3.1.0",
    "cmake-bare": "^1.1.7",
    "cmake-fetch": "^1.1.0",
    "cmake-napi": "^1.0.2",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  }
}
const b4a = require('b4a')
const scalar = require('./scalar')

function view (buf, n) {
  if (n === buf.BYTES_PER_ELEMENT) return buf

  let TypedArray

  if (n === 1) TypedArray = Uint8Array
  else if (n === 2) TypedArray = Uint16Array
  else TypedArray = Uint32Array

  return new TypedArray(buf.buffer, buf.byteOffset, buf.byteLength / n)
}

function unary (u8, u16 = u8, u32 = u16) {
  return function unary (buf, result = b4a.allocUnsafe(buf.byteLength)) {
    if (buf.byteLength % 16 !== 0) {
      throw new Error('Buffer length must be a multiple of 16')
    }

    if (buf.byteLength !== result.byteLength) {
      throw new Error('Length of result buffer is insufficient')
    }

    const n = buf.BYTES_PER_ELEMENT

    if (n === 1) u8(buf, view(result, n))
    else if (n === 2) u16(buf, view(result, n))
    else u32(buf, view(result, n))

    return result
  }
}

function binary (u8, u16 = u8, u32 = u16) {
  return function binary (a, b, result = b4a.allocUnsafe(a.byteLength)) {
    if (a.byteLength % 16 !== 0) {
      throw new Error('Buffer length must be a multiple of 16')
    }

    if (a.byteLength !== b.byteLength || a.byteLength !== result.byteLength) {
      throw new Error('Buffers must be the same length')
    }

    const n = a.BYTES_PER_ELEMENT

    if (n === 1) u8(a, b, view(result, n))
    else if (n === 2) u16(a, b, view(result, n))
    else u32(a, b, view(result, n))

    return result
  }
}

function reduce (u8, u16 = u8, u32 = u16) {
  return function reduce (buf) {
    if (buf.byteLength % 16 !== 0) {
      throw new Error('Buffer length must be a multiple of 16')
    }

    const n = buf.BYTES_PER_ELEMENT

    if (n === 1) return u8(buf)
    if (n === 2) return u16(buf)
    return u32(buf)
  }
}

exports.allo = function allo (buf) {
  if (buf.byteLength % 16 !== 0) {
    throw new Error('Buffer length must be a multiple of 16')
  }

  const m = 2 ** (buf.BYTES_PER_ELEMENT * 8) - 1

  for (let i = 0, n = buf.length; i < n; i++) {
    if (buf[i] !== m) return false
  }

  return true
}

exports.allz = function allz (buf) {
  if (buf.byteLength % 16 !== 0) {
    throw new Error('Buffer length must be a multiple of 16')
  }

  for (let i = 0, n = buf.length; i < n; i++) {
    if (buf[i] !== 0) return false
  }

  return true
}

exports.and = binary(
  (a, b, result) => {
    for (let i = 0, n = result.length; i < n; i++) {
      result[i] = a[i] & b[i]
    }
  }
)

exports.clear = binary(
  (a, b, result) => {
    for (let i = 0, n = result.length; i < n; i++) {
      result[i] = a[i] & ~b[i]
    }
  }
)

exports.clo = unary(
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = 24 - scalar.clo(buf[i])
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = 16 - scalar.clo(buf[i])
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = scalar.clo(buf[i])
    }
  }
)

exports.clz = unary(
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = 24 - scalar.clz(buf[i])
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = 16 - scalar.clz(buf[i])
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = scalar.clz(buf[i])
    }
  }
)

exports.cnt = unary(
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = scalar.cnt(buf[i]) & 0xff
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = scalar.cnt(buf[i]) & 0xffff
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = scalar.cnt(buf[i])
    }
  }
)

exports.cto = unary(
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = Math.min(scalar.cto(buf[i]), 8)
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = Math.min(scalar.cto(buf[i]), 16)
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = scalar.cto(buf[i])
    }
  }
)

exports.ctz = unary(
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = Math.min(scalar.ctz(buf[i]), 8)
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = Math.min(scalar.ctz(buf[i]), 16)
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = scalar.ctz(buf[i])
    }
  }
)

exports.not = unary(
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = ~buf[i]
    }
  }
)

exports.or = binary(
  (a, b, result) => {
    for (let i = 0, n = result.length; i < n; i++) {
      result[i] = a[i] | b[i]
    }
  }
)

exports.sum = reduce(
  (buf) => {
    let result = 0n

    for (let i = 0, n = buf.length; i < n; i++) {
      result += BigInt(buf[i])
    }

    return result
  }
)

exports.xor = binary(
  (a, b, result) => {
    for (let i = 0, n = result.length; i < n; i++) {
      result[i] = a[i] ^ b[i]
    }
  }
)
try {
  module.exports = require('simdle-native')
} catch {
  module.exports = require('./fallback')
}
{
  "name": "simdle-universal",
  "version": "1.1.2",
  "description": "Universal wrapper for libsimdle with a JavaScript fallback",
  "main": "index.js",
  "files": [
    "fallback.js",
    "index.js",
    "scalar.js"
  ],
  "browser": {
    "./index.js": "./fallback.js"
  },
  "scripts": {
    "test": "standard && brittle test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/simdle-universal.git"
  },
  "author": "Kasper Isager Dalsgarð <kasper@funktionel.co>",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/holepunchto/simdle-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/simdle-universal#readme",
  "dependencies": {
    "b4a": "^1.6.0"
  },
  "optionalDependencies": {
    "simdle-native": "^1.1.1"
  },
  "devDependencies": {
    "brittle": "^3.1.0",
    "standard": "^17.0.0"
  }
}
const clz = exports.clz = function clz (n) {
  return Math.clz32(n)
}

exports.clo = function clo (n) {
  return clz(~n)
}

const ctz = exports.ctz = function ctz (n) {
  return 32 - (n === 0 ? 0 : (clz(n & -n) + 1))
}

exports.cto = function cto (n) {
  return ctz(~n)
}

exports.cnt = function cnt (n) {
  n = n - ((n >>> 1) & 0x55555555)
  n = (n & 0x33333333) + ((n >>> 2) & 0x33333333)
  n = (n + (n >>> 4)) & 0x0f0f0f0f
  n = (n * 0x01010101) >>> 24
  return n
}
require.addon = require('require-addon')
module.exports = require.addon('.', __filename)
const assert = require('assert')
const binding = require('./binding')
const { isNode } = require('which-runtime')

const OPTIONAL = Buffer.from(new ArrayBuffer(0))

module.exports = exports = { ...binding }

// memory

exports.sodium_memzero = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  binding.sodium_memzero(buf)
}

exports.sodium_mlock = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  const res = binding.sodium_mlock(buf)

  if (res !== 0) throw new Error('memory lock failed')
}

exports.sodium_munlock = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  const res = binding.sodium_munlock(buf)

  if (res !== 0) throw new Error('memory unlock failed')
}

exports.sodium_malloc = function (size) {
  assert(size >= 0, 'invalid size')

  const buf = Buffer.from(binding.sodium_malloc(size))
  buf.secure = true
  return buf
}

exports.sodium_free = function (buf) {
  if (!buf || !buf.secure) return

  binding.sodium_free(buf.buffer)
}

exports.sodium_mprotect_noaccess = function (buf) {
  const res = binding.sodium_mprotect_noaccess(buf.buffer)

  if (res !== 0) throw new Error('failed to lock buffer')
}

exports.sodium_mprotect_readonly = function (buf) {
  const res = binding.sodium_mprotect_readonly(buf.buffer)

  if (res !== 0) throw new Error('failed to unlock buffer')
}

exports.sodium_mprotect_readwrite = function (buf) {
  const res = binding.sodium_mprotect_readwrite(buf.buffer)

  if (res !== 0) throw new Error('failed to unlock buffer')
}

// crypto_randombytes

exports.randombytes_buf = function (buffer) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')

  binding.randombytes_buf(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

exports.randombytes_buf_deterministic = function (buffer, seed) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    seed.byteLength === binding.randombytes_SEEDBYTES,
    "seed must be 'randombytes_SEEDBYTES' bytes"
  )

  binding.randombytes_buf_deterministic(
    buffer.buffer,
    buffer.byteOffset,
    buffer.byteLength,

    seed.buffer,
    seed.byteOffset,
    seed.byteLength
  )
}

// sodium_helpers

exports.sodium_memcmp = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  return binding.sodium_memcmp(a, b)
}

exports.sodium_add = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  binding.sodium_add(a, b)
}

exports.sodium_sub = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  binding.sodium_sub(a, b)
}

exports.sodium_compare = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  return binding.sodium_compare(a, b)
}

exports.sodium_is_zero = function (buffer, length) {
  if (length === undefined) length = buffer.byteLength

  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(length >= 0 && length <= buffer.byteLength, 'invalid length')

  return binding.sodium_is_zero(buffer, length)
}

exports.sodium_pad = function (buffer, unpaddedBuflen, blockSize) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(unpaddedBuflen <= buffer.byteLength, 'unpadded length cannot exceed buffer length')
  assert(blockSize <= buffer.byteLength, 'block size cannot exceed buffer length')
  assert(blockSize >= 1, 'block size must be at least 1 byte')
  assert(
    buffer.byteLength >= unpaddedBuflen + (blockSize - (unpaddedBuflen % blockSize)),
    'buf not long enough'
  )

  return binding.sodium_pad(buffer, unpaddedBuflen, blockSize)
}

exports.sodium_unpad = function (buffer, paddedBuflen, blockSize) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(paddedBuflen <= buffer.byteLength, 'unpadded length cannot exceed buffer length')
  assert(blockSize <= buffer.byteLength, 'block size cannot exceed buffer length')
  assert(blockSize >= 1, 'block size must be at least 1 byte')

  return binding.sodium_unpad(buffer, paddedBuflen, blockSize)
}

// crypto_sign

exports.crypto_sign_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )
  assert(
    seed.byteLength === binding.crypto_sign_SEEDBYTES,
    "seed must be 'crypto_sign_SEEDBYTES' bytes"
  )

  const res = binding.crypto_sign_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign = function (sm, m, sk) {
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sm.byteLength === binding.crypto_sign_BYTES + m.byteLength,
    "sm must be 'm.byteLength + crypto_sign_BYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign(sm, m, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_open = function (m, sm, pk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sm.byteLength >= binding.crypto_sign_BYTES,
    "sm must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    m.byteLength === sm.byteLength - binding.crypto_sign_BYTES,
    "m must be 'sm.byteLength - crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_open(m, sm, pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_open = function (m, sm, pk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sm.byteLength >= binding.crypto_sign_BYTES,
    "sm must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    m.byteLength === sm.byteLength - binding.crypto_sign_BYTES,
    "m must be 'sm.byteLength - crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  return binding.crypto_sign_open(m, sm, pk)
}

exports.crypto_sign_detached = function (sig, m, sk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(sig.byteLength === binding.crypto_sign_BYTES, "sig must be 'crypto_sign_BYTES' bytes")
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_detached(sig, m, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_verify_detached = function (sig, m, pk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sig.byteLength >= binding.crypto_sign_BYTES,
    "sig must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  return binding.crypto_sign_verify_detached(
    sig.buffer,
    sig.byteOffset,
    sig.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    pk.buffer,
    pk.byteOffset,
    pk.byteLength
  )
}

exports.crypto_sign_ed25519_sk_to_pk = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_sk_to_pk(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_ed25519_pk_to_curve25519 = function (x25519pk, ed25519pk) {
  assert(ArrayBuffer.isView(x25519pk), 'x25519pk must be a typed array')
  assert(ArrayBuffer.isView(ed25519pk), 'ed25519pk must be a typed array')
  assert(
    x25519pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "x25519pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    ed25519pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "ed25519pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_pk_to_curve25519(x25519pk, ed25519pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_ed25519_sk_to_curve25519 = function (x25519sk, ed25519sk) {
  assert(ArrayBuffer.isView(x25519sk), 'x25519sk must be a typed array')
  assert(ArrayBuffer.isView(ed25519sk), 'ed25519sk must be a typed array')
  assert(
    x25519sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "x25519sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const edLen = ed25519sk.byteLength

  assert(
    edLen === binding.crypto_sign_SECRETKEYBYTES || edLen === binding.crypto_box_SECRETKEYBYTES,
    "ed25519sk must be 'crypto_sign_SECRETKEYBYTES' or 'crypto_sign_SECRETKEYBYTES - crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_sk_to_curve25519(x25519sk, ed25519sk)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_box

exports.crypto_box_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    seed.byteLength === binding.crypto_box_SEEDBYTES,
    "seed must be 'crypto_box_SEEDBYTES' bytes"
  )

  const res = binding.crypto_box_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_easy = function (c, m, n, pk, sk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength === m.byteLength + exports.crypto_box_MACBYTES,
    "c must be 'm.byteLength + crypto_box_MACBYTES' bytes"
  )
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_easy(c, m, n, pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_detached = function (c, mac, m, n, pk, sk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(mac.byteLength === exports.crypto_box_MACBYTES, "mac must be 'crypto_box_MACBYTES' bytes")
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_detached(c, mac, m, n, pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_open_easy = function (m, c, n, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength >= exports.crypto_box_MACBYTES,
    "c must be at least 'crypto_box_MACBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - exports.crypto_box_MACBYTES,
    "m must be 'c.byteLength - crypto_box_MACBYTES' bytes"
  )
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_open_easy(m, c, n, pk, sk)
}

exports.crypto_box_open_detached = function (m, c, mac, n, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(mac.byteLength === exports.crypto_box_MACBYTES, "mac must be 'crypto_box_MACBYTES' bytes")
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_open_detached(m, c, mac, n, pk, sk)
}

exports.crypto_box_seal = function (c, m, pk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    c.byteLength === m.byteLength + exports.crypto_box_SEALBYTES,
    "c must be 'm.byteLength + crypto_box_SEALBYTES' bytes"
  )
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_box_seal(c, m, pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_seal_open = function (m, c, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength >= exports.crypto_box_SEALBYTES,
    "c must be at least 'crypto_box_SEALBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - exports.crypto_box_SEALBYTES,
    "m must be 'c.byteLength - crypto_box_SEALBYTES' bytes"
  )
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_seal_open(
    m.buffer,
    m.byteOffset,
    m.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    pk.buffer,
    pk.byteOffset,
    pk.byteLength,

    sk.buffer,
    sk.byteOffset,
    sk.byteLength
  )
}

// crypto_secretbox

exports.crypto_secretbox_easy = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_secretbox_MACBYTES,
    "c must be 'm.byteLength + crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretbox_easy(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretbox_open_easy = function (m, c, n, k) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    c.byteLength >= binding.crypto_secretbox_MACBYTES,
    "c must be at least 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - binding.crypto_secretbox_MACBYTES,
    "m must be 'c.byteLength - crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  return binding.crypto_secretbox_open_easy(m, c, n, k)
}

exports.crypto_secretbox_detached = function (c, mac, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    mac.byteLength === binding.crypto_secretbox_MACBYTES,
    "mac must be 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretbox_detached(c, mac, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretbox_open_detached = function (m, c, mac, n, k) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(
    mac.byteLength === binding.crypto_secretbox_MACBYTES,
    "mac must be 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  return binding.crypto_secretbox_open_detached(m, c, mac, n, k)
}

// crypto_generichash

exports.crypto_generichash = function (output, input, key) {
  if (!key) key = OPTIONAL

  assert(ArrayBuffer.isView(output), 'output must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    output.byteLength >= binding.crypto_generichash_BYTES_MIN &&
      output.byteLength <= binding.crypto_generichash_BYTES_MAX,
    'output must be between crypto_generichash_BYTES_MIN and crypto_generichash_BYTES_MAX bytes'
  )

  if (key !== OPTIONAL) {
    assert(ArrayBuffer.isView(key), 'key must be a typed array')
    assert(
      key.byteLength >= binding.crypto_generichash_KEYBYTES_MIN &&
        key.byteLength <= binding.crypto_generichash_KEYBYTES_MAX,
      'key must be between crypto_generichash_KEYBYTES_MIN and crypto_generichash_KEYBYTES_MAX bytes'
    )
  }

  const res = binding.crypto_generichash(
    output.buffer,
    output.byteOffset,
    output.byteLength,

    input.buffer,
    input.byteOffset,
    input.byteLength,

    key.buffer,
    key.byteOffset,
    key.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_batch = function (output, batch, key) {
  assert(ArrayBuffer.isView(output), 'output must be a typed array')

  if (isNode || batch.length < 4) {
    const res = binding.crypto_generichash_batch(output, batch, !!key, key || OPTIONAL)
    if (res !== 0) throw new Error('status: ' + res)
  } else {
    const state = Buffer.alloc(binding.crypto_generichash_STATEBYTES)

    exports.crypto_generichash_init(state, key, output.byteLength)

    for (const buf of batch) {
      exports.crypto_generichash_update(state, buf)
    }

    exports.crypto_generichash_final(state, output)
  }
}

exports.crypto_generichash_keygen = function (key) {
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(
    key.byteLength === binding.crypto_generichash_KEYBYTES,
    "key must be 'crypto_generichash_KEYBYTES' bytes"
  )

  const res = binding.crypto_generichash_keygen(key.buffer, key.byteOffset, key.byteLength)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_init = function (state, key, outputLength) {
  if (!key) key = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_init(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    key.buffer,
    key.byteOffset,
    key.byteLength,

    outputLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_update(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    input.buffer,
    input.byteOffset,
    input.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_final = function (state, output) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(output), 'output must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_final(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    output.buffer,
    output.byteOffset,
    output.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

// secretstream

exports.crypto_secretstream_xchacha20poly1305_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  binding.crypto_secretstream_xchacha20poly1305_keygen(k.buffer, k.byteOffset, k.byteLength)
}

exports.crypto_secretstream_xchacha20poly1305_init_push = function (state, header, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(header), 'header must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    header.byteLength === binding.crypto_secretstream_xchacha20poly1305_HEADERBYTES,
    "header must be 'crypto_secretstream_xchacha20poly1305_HEADERBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_init_push(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    header.buffer,
    header.byteOffset,
    header.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretstream_xchacha20poly1305_init_pull = function (state, header, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(header), 'header must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    header.byteLength === binding.crypto_secretstream_xchacha20poly1305_HEADERBYTES,
    "header must be 'crypto_secretstream_xchacha20poly1305_HEADERBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_init_pull(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    header.buffer,
    header.byteOffset,
    header.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretstream_xchacha20poly1305_push = function (state, c, m, ad, tag) {
  if (!ad) ad = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    c.byteLength === m.byteLength + binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "c must be 'm.byteLength + crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_push(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    ad.buffer,
    ad.byteOffset,
    ad.byteLength,

    tag
  )

  if (res < 0) throw new Error('push failed')

  return res
}

exports.crypto_secretstream_xchacha20poly1305_pull = function (state, m, tag, c, ad) {
  if (!ad) ad = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(tag), 'tag must be a typed array')
  assert(tag.byteLength === 1, 'tag must be 1 byte')

  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    c.byteLength >= binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "c must be at least 'crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "m must be 'c.byteLength - crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_pull(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    tag.buffer,
    tag.byteOffset,
    tag.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    ad.buffer,
    ad.byteOffset,
    ad.byteLength
  )

  if (res < 0) throw new Error('pull failed')

  return res
}

exports.crypto_secretstream_xchacha20poly1305_rekey = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )

  binding.crypto_secretstream_xchacha20poly1305_rekey(
    state.buffer,
    state.byteOffset,
    state.byteLength
  )
}

// crypto_stream

exports.crypto_stream = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xor(
    c.buffer,
    c.byteOffset,
    c.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    n.buffer,
    n.byteOffset,
    n.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_auth

exports.crypto_auth = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(out.byteLength === binding.crypto_auth_BYTES, "out must be 'crypto_auth_BYTES' bytes")
  assert(k.byteLength === binding.crypto_auth_KEYBYTES, "k must be 'crypto_auth_KEYBYTES' bytes")

  const res = binding.crypto_auth(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_auth_verify = function (h, input, k) {
  assert(ArrayBuffer.isView(h), 'h must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(h.byteLength === binding.crypto_auth_BYTES, "h must be 'crypto_auth_BYTES' bytes")
  assert(k.byteLength === binding.crypto_auth_KEYBYTES, "k must be 'crypto_auth_KEYBYTES' bytes")

  return binding.crypto_auth_verify(h, input, k)
}

// crypto_onetimeauth

exports.crypto_onetimeauth = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    out.byteLength === binding.crypto_onetimeauth_BYTES,
    "out must be 'crypto_onetimeauth_BYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_init = function (state, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_init(state, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )
  assert(
    out.byteLength === binding.crypto_onetimeauth_BYTES,
    "out must be 'crypto_onetimeauth_BYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_verify = function (h, input, k) {
  assert(ArrayBuffer.isView(h), 'h must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    h.byteLength === binding.crypto_onetimeauth_BYTES,
    "h must be 'crypto_onetimeauth_BYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  return binding.crypto_onetimeauth_verify(h, input, k)
}

// crypto_pwhash

exports.crypto_pwhash = function (out, passwd, salt, opslimit, memlimit, alg) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_BYTES_MIN,
    "out must be at least 'crypto_pwhash_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_BYTES_MAX,
    "out must be at most 'crypto_pwhash_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_SALTBYTES,
    "salt must be 'crypto_pwhash_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )
  assert(alg >= 1 && alg <= 2, 'alg must be either Argon2i 1.3 or Argon2id 1.3')

  const res = binding.crypto_pwhash(out, passwd, salt, opslimit, memlimit, alg)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_async = function (
  out,
  passwd,
  salt,
  opslimit,
  memlimit,
  alg,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_BYTES_MIN,
    "out must be at least 'crypto_pwhash_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_BYTES_MAX,
    "out must be at most 'crypto_pwhash_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_SALTBYTES,
    "salt must be 'crypto_pwhash_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )
  assert(alg >= 1 && alg <= 2, 'alg must be either Argon2i 1.3 or Argon2id 1.3')

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    opslimit,
    memlimit,
    alg,

    done
  )

  return promise
}

exports.crypto_pwhash_str = function (out, passwd, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_STRBYTES,
    "out must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(typeof opslimit === 'number', 'opslimit must be a number')
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(typeof memlimit === 'number', 'memlimit must be a number')
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_str(out, passwd, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_str_async = function (out, passwd, opslimit, memlimit, callback = undefined) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_STRBYTES,
    "out must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(typeof opslimit === 'number', 'opslimit must be a number')
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(typeof memlimit === 'number', 'memlimit must be a number')
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_str_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_str_verify = function (str, passwd) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )

  return binding.crypto_pwhash_str_verify(str, passwd)
}

exports.crypto_pwhash_str_verify_async = function (str, passwd, callback = undefined) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  const [done, promise] = checkStatus(callback, true)

  binding.crypto_pwhash_str_verify_async(
    str.buffer,
    str.byteOffset,
    str.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    done
  )

  return promise
}

exports.crypto_pwhash_str_needs_rehash = function (str, opslimit, memlimit) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  return binding.crypto_pwhash_str_needs_rehash(str, opslimit, memlimit)
}

exports.crypto_pwhash_scryptsalsa208sha256 = function (out, passwd, salt, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MIN,
    "out must be at least 'crypto_pwhash_scryptsalsa208sha256_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MAX,
    "out must be at most 'crypto_pwhash_scryptsalsa208sha256_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_SALTBYTES,
    "salt must be 'crypto_pwhash_scryptsalsa208sha256_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_scryptsalsa208sha256(out, passwd, salt, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_scryptsalsa208sha256_async = function (
  out,
  passwd,
  salt,
  opslimit,
  memlimit,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MIN,
    "out must be at least 'crypto_pwhash_scryptsalsa208sha256_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MAX,
    "out must be at most 'crypto_pwhash_scryptsalsa208sha256_BYTES_MAX' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    salt.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_SALTBYTES,
    "salt must be 'crypto_pwhash_scryptsalsa208sha256_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_scryptsalsa208sha256_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str_async = function (
  out,
  passwd,
  opslimit,
  memlimit,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "out must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_scryptsalsa208sha256_str_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str = function (out, passwd, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "out must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_scryptsalsa208sha256_str(out, passwd, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_scryptsalsa208sha256_str_verify_async = function (
  str,
  passwd,
  callback = undefined
) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  const [done, promise] = checkStatus(callback, true)

  binding.crypto_pwhash_scryptsalsa208sha256_str_verify_async(
    str.buffer,
    str.byteOffset,
    str.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str_verify = function (str, passwd) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  return binding.crypto_pwhash_scryptsalsa208sha256_str_verify(str, passwd)
}

exports.crypto_pwhash_scryptsalsa208sha256_str_needs_rehash = function (str, opslimit, memlimit) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  return binding.crypto_pwhash_scryptsalsa208sha256_str_needs_rehash(str, opslimit, memlimit)
}

// crypto_kx

exports.crypto_kx_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "pk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "sk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    pk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "pk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "sk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    seed.byteLength === binding.crypto_kx_SEEDBYTES,
    "seed must be 'crypto_kx_SEEDBYTES' bytes"
  )

  const res = binding.crypto_kx_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_client_session_keys = function (rx, tx, clientPk, clientSk, serverPk) {
  if (!rx) rx = undefined
  if (!tx) tx = undefined

  assert(rx || tx, 'at least one session key must be specified')

  if (rx) {
    assert(ArrayBuffer.isView(rx), 'rx must be a typed array')
    assert(
      rx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "rx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  if (tx) {
    assert(ArrayBuffer.isView(tx), 'tx must be a typed array')
    assert(
      tx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "tx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  assert(ArrayBuffer.isView(clientPk), 'clientPk must be a typed array')
  assert(ArrayBuffer.isView(clientSk), 'clientSk must be a typed array')
  assert(ArrayBuffer.isView(serverPk), 'serverPk must be a typed array')
  assert(
    clientPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "clientPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    clientSk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "clientSk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    serverPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "serverPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_client_session_keys(rx, tx, clientPk, clientSk, serverPk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_server_session_keys = function (rx, tx, serverPk, serverSk, clientPk) {
  if (!rx) rx = undefined
  if (!tx) tx = undefined

  assert(rx || tx, 'at least one session key must be specified')

  if (rx) {
    assert(ArrayBuffer.isView(rx), 'rx must be a typed array')
    assert(
      rx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "rx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  if (tx) {
    assert(ArrayBuffer.isView(tx), 'tx must be a typed array')
    assert(
      tx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "tx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  assert(ArrayBuffer.isView(serverPk), 'serverPk must be a typed array')
  assert(ArrayBuffer.isView(serverSk), 'serverSk must be a typed array')
  assert(ArrayBuffer.isView(clientPk), 'clientPk must be a typed array')
  assert(
    serverPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "serverPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    serverSk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "serverSk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    clientPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "clientPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_server_session_keys(rx, tx, serverPk, serverSk, clientPk)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_scalarmult

exports.crypto_scalarmult_base = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_BYTES,
    "q must be 'crypto_scalarmult_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_SCALARBYTES,
    "n must be 'crypto_scalarmult_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_base(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_BYTES,
    "q must be 'crypto_scalarmult_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_SCALARBYTES,
    "n must be 'crypto_scalarmult_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_BYTES,
    "p must be 'crypto_scalarmult_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_base = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_base(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519 = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "p must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_is_valid_point = function (p) {
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )

  return binding.crypto_core_ed25519_is_valid_point(p)
}

exports.crypto_core_ed25519_from_uniform = function (p, r) {
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_UNIFORMBYTES,
    "r must be 'crypto_core_ed25519_UNIFORMBYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_from_uniform(p, r)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_base_noclamp = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_base_noclamp(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_noclamp = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "p must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_noclamp(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_core

exports.crypto_core_ed25519_add = function (r, p, q) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_BYTES,
    "r must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_core_ed25519_BYTES,
    "q must be 'crypto_core_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_add(r, p, q)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_sub = function (r, p, q) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_BYTES,
    "r must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_core_ed25519_BYTES,
    "q must be 'crypto_core_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_sub(r, p, q)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_scalar_random = function (r) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "r must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_random(r)
}

exports.crypto_core_ed25519_scalar_reduce = function (r, s) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "r must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_NONREDUCEDSCALARBYTES,
    "s must be 'crypto_core_ed25519_NONREDUCEDSCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_reduce(r, s)
}

exports.crypto_core_ed25519_scalar_invert = function (recip, s) {
  assert(ArrayBuffer.isView(recip), 'recip must be a typed array')
  assert(
    recip.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "recip must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_invert(recip, s)
}

exports.crypto_core_ed25519_scalar_negate = function (neg, s) {
  assert(ArrayBuffer.isView(neg), 'neg must be a typed array')
  assert(
    neg.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "neg must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_negate(neg, s)
}

exports.crypto_core_ed25519_scalar_complement = function (comp, s) {
  assert(ArrayBuffer.isView(comp), 'comp must be a typed array')
  assert(
    comp.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "comp must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_complement(comp, s)
}

exports.crypto_core_ed25519_scalar_add = function (z, x, y) {
  assert(ArrayBuffer.isView(z), 'z must be a typed array')
  assert(
    z.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "z must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(x), 'x must be a typed array')
  assert(
    x.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "x must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(y), 'y must be a typed array')
  assert(
    y.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "y must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_add(z, x, y)
}

exports.crypto_core_ed25519_scalar_sub = function (z, x, y) {
  assert(ArrayBuffer.isView(z), 'z must be a typed array')
  assert(
    z.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "z must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(x), 'x must be a typed array')
  assert(
    x.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "x must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(y), 'y must be a typed array')
  assert(
    y.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "y must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_sub(z, x, y)
}

// crypto_shorthash

exports.crypto_shorthash = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_shorthash_BYTES,
    "out must be 'crypto_shorthash_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_shorthash_KEYBYTES,
    "k must be 'crypto_shorthash_KEYBYTES' bytes"
  )

  const res = binding.crypto_shorthash(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_kdf

exports.crypto_kdf_keygen = function (key) {
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(key.byteLength === binding.crypto_kdf_KEYBYTES, "key must be 'crypto_kdf_KEYBYTES' bytes")

  binding.crypto_kdf_keygen(key)
}

exports.crypto_kdf_derive_from_key = function (subkey, subkeyId, ctx, key) {
  assert(ArrayBuffer.isView(subkey), 'subkey must be a typed array')
  assert(
    subkey.byteLength >= binding.crypto_kdf_BYTES_MIN,
    "subkey must be at least 'crypto_kdf_BYTES_MIN' bytes"
  )
  assert(
    subkey.byteLength <= binding.crypto_kdf_BYTES_MAX,
    "subkey must be at most 'crypto_kdf_BYTES_MAX' bytes"
  )
  assert(ArrayBuffer.isView(ctx), 'ctx must be a typed array')
  assert(
    ctx.byteLength === binding.crypto_kdf_CONTEXTBYTES,
    "ctx must be 'crypto_kdf_CONTEXTBYTES' bytes"
  )
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(key.byteLength === binding.crypto_kdf_KEYBYTES, "key must be 'crypto_kdf_KEYBYTES' bytes")

  const res = binding.crypto_kdf_derive_from_key(subkey, subkeyId, ctx, key)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_hash

exports.crypto_hash = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(out.byteLength === binding.crypto_hash_BYTES, "out must be 'crypto_hash_BYTES' bytes")

  const res = binding.crypto_hash(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256 = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha256_BYTES,
    "out must be 'crypto_hash_sha256_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha256(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_init = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_init(state)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha256_BYTES,
    "out must be 'crypto_hash_sha256_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512 = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha512_BYTES,
    "out must be 'crypto_hash_sha512_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha512(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_init = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_init(state)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha512_BYTES,
    "out must be 'crypto_hash_sha512_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_aead

exports.crypto_aead_xchacha20poly1305_ietf_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  binding.crypto_aead_xchacha20poly1305_ietf_keygen(k)
}

exports.crypto_aead_xchacha20poly1305_ietf_encrypt = function (c, m, ad, nsec, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "c must be 'm.byteLength + crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(c.byteLength <= 0xffffffff, 'c.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_encrypt(c, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_decrypt = function (m, nsec, c, ad, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "m must be 'c.byteLength - crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(m.byteLength <= 0xffffffff, 'm.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_decrypt(m, c, ad, npub, k)

  if (res < 0) throw new Error('could not verify data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_encrypt_detached = function (
  c,
  mac,
  m,
  ad,
  nsec,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_encrypt_detached(c, mac, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_decrypt_detached = function (
  m,
  nsec,
  c,
  mac,
  ad,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_decrypt_detached(m, c, mac, ad, npub, k)

  if (res !== 0) throw new Error('could not verify data')
}

exports.crypto_aead_chacha20poly1305_ietf_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  binding.crypto_aead_chacha20poly1305_ietf_keygen(k)
}

exports.crypto_aead_chacha20poly1305_ietf_encrypt = function (c, m, ad, nsec, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "c must be 'm.byteLength + crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(c.byteLength <= 0xffffffff, 'c.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_encrypt(c, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_decrypt = function (m, nsec, c, ad, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "m must be 'c.byteLength - crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(m.byteLength <= 0xffffffff, 'm.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_decrypt(m, c, ad, npub, k)

  if (res < 0) throw new Error('could not verify data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_encrypt_detached = function (
  c,
  mac,
  m,
  ad,
  nsec,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_encrypt_detached(c, mac, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_decrypt_detached = function (
  m,
  nsec,
  c,
  mac,
  ad,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_decrypt_detached(m, c, mac, ad, npub, k)

  if (res !== 0) throw new Error('could not verify data')
}

// crypto_stream

exports.crypto_stream_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  binding.crypto_stream_xor_wrap_init(state, n, k)
}

exports.crypto_stream_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_xor_wrap_update(state, c, m)
}

exports.crypto_stream_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_xor_wrap_final(state)
}

exports.crypto_stream_chacha20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  binding.crypto_stream_chacha20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_chacha20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_chacha20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_chacha20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_chacha20_xor_wrap_final(state)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  binding.crypto_stream_chacha20_ietf_xor_wrap_init(state, n, k)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_chacha20_ietf_xor_wrap_update(state, c, m)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_chacha20_ietf_xor_wrap_final(state)
}

exports.crypto_stream_xchacha20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  binding.crypto_stream_xchacha20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_xchacha20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_xchacha20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_xchacha20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_xchacha20_xor_wrap_final(state)
}

exports.crypto_stream_salsa20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  binding.crypto_stream_salsa20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_salsa20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_salsa20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_salsa20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_salsa20_xor_wrap_final(state)
}

// experimental

exports.extension_tweak_ed25519_base = function (n, p, ns) {
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.extension_tweak_ed25519_BYTES,
    "p must be 'extension_tweak_ed25519_BYTES' bytes"
  )

  binding.extension_tweak_ed25519_base(n, p, ns)
}

exports.extension_tweak_ed25519_sign_detached = function (sig, m, scalar, pk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(sig.byteLength === binding.crypto_sign_BYTES, "sig must be 'crypto_sign_BYTES' bytes")
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  if (pk) {
    assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
    assert(
      pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
      "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
    )
  }

  const res = binding.extension_tweak_ed25519_sign_detached(sig, m, scalar, pk)

  if (res !== 0) throw new Error('failed to compute signature')
}

exports.extension_tweak_ed25519_sk_to_scalar = function (n, sk) {
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  binding.extension_tweak_ed25519_sk_to_scalar(n, sk)
}

exports.extension_tweak_ed25519_scalar = function (scalarOut, scalar, ns) {
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_scalar(scalarOut, scalar, ns)
}

exports.extension_tweak_ed25519_pk = function (tpk, pk, ns) {
  assert(ArrayBuffer.isView(tpk), 'tpk must be a typed array')
  assert(
    tpk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "tpk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_pk(tpk, pk, ns)

  if (res !== 0) throw new Error('failed to tweak public key')
}

exports.extension_tweak_ed25519_keypair = function (pk, scalarOut, scalarIn, ns) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.extension_tweak_ed25519_BYTES,
    "pk must be 'extension_tweak_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarIn), 'scalarIn must be a typed array')
  assert(
    scalarIn.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarIn must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_keypair(pk, scalarOut, scalarIn, ns)
}

exports.extension_tweak_ed25519_scalar_add = function (scalarOut, scalar, n) {
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_scalar_add(scalarOut, scalar, n)
}

exports.extension_tweak_ed25519_pk_add = function (tpk, pk, p) {
  assert(ArrayBuffer.isView(tpk), 'tpk must be a typed array')
  assert(
    tpk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "tpk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "p must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_pk_add(tpk, pk, p)

  if (res !== 0) throw new Error('failed to add tweak to public key')
}

exports.extension_tweak_ed25519_keypair_add = function (pk, scalarOut, scalarIn, tweak) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.extension_tweak_ed25519_BYTES,
    "pk must be 'extension_tweak_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarIn), 'scalarIn must be a typed array')
  assert(
    scalarIn.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarIn must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(tweak), 'tweak must be a typed array')
  assert(
    tweak.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "tweak must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_keypair_add(pk, scalarOut, scalarIn, tweak)

  if (res !== 0) throw new Error('failed to add tweak to keypair')
}

exports.extension_pbkdf2_sha512_async = function (out, passwd, salt, iter, outlen, callback) {
  assert(
    iter >= binding.extension_pbkdf2_sha512_ITERATIONS_MIN,
    "iter must be at least 'extension_pbkdf2_sha512_ITERATIONS_MIN'"
  )
  assert(
    outlen <= binding.extension_pbkdf2_sha512_BYTES_MAX,
    "outlen must be at most 'extension_pbkdf2_sha512_BYTES_MAX'"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(out.byteLength >= outlen, "out must be at least 'outlen' bytes")
  assert(out.byteLength > 0, 'out must not be empty')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(salt.byteLength > 0, 'salt must not be empty')

  const [done, promise] = checkStatus(callback)

  binding.extension_pbkdf2_sha512_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    iter,
    outlen,

    done
  )

  return promise
}

exports.extension_pbkdf2_sha512 = function (out, passwd, salt, iter, outlen) {
  assert(
    iter >= binding.extension_pbkdf2_sha512_ITERATIONS_MIN,
    "iter must be at least 'extension_pbkdf2_sha512_ITERATIONS_MIN'"
  )
  assert(
    outlen <= binding.extension_pbkdf2_sha512_BYTES_MAX,
    "outlen must be at most 'extension_pbkdf2_sha512_BYTES_MAX'"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(out.byteLength >= outlen, "out must be at least 'outlen' bytes")
  assert(out.byteLength > 0, 'out must not be empty')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(salt.byteLength > 0, 'salt must not be empty')

  const res = binding.extension_pbkdf2_sha512(out, passwd, salt, iter, outlen)

  if (res !== 0) throw new Error('failed to add tweak to public key')
}

function checkStatus(callback, booleanResult = false) {
  let done, promise

  if (typeof callback === 'function') {
    done = function (status) {
      if (booleanResult) callback(null, status === 0)
      else if (status === 0) callback(null)
      else callback(new Error('status: ' + status))
    }
  } else {
    promise = new Promise(function (resolve, reject) {
      done = function (status) {
        if (booleanResult) resolve(status === 0)
        else if (status === 0) resolve()
        else reject(new Error('status: ' + status))
      }
    })
  }

  return [done, promise]
}
{
  "name": "sodium-native",
  "version": "5.1.0",
  "description": "Low level bindings for libsodium",
  "main": "index.js",
  "files": [
    "index.js",
    "binding.cc",
    "binding.js",
    "extensions",
    "prebuilds",
    "CMakeLists.txt"
  ],
  "imports": {
    "assert": {
      "bare": "bare-assert",
      "node": "assert"
    }
  },
  "addon": true,
  "dependencies": {
    "bare-assert": "^1.2.0",
    "require-addon": "^1.1.0",
    "which-runtime": "^1.2.1"
  },
  "devDependencies": {
    "bare-compat-napi": "^1.3.5",
    "brittle": "^3.16.2",
    "cmake-bare": "^1.6.1",
    "cmake-fetch": "^1.4.3",
    "cmake-napi": "^1.2.1",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "test": "prettier . --check && npm run test:node && npm run test:bare",
    "test:node": "node test/all.js",
    "test:bare": "bare test/all.js"
  },
  "standard": {
    "ignore": [
      "/test/fixtures/*.js"
    ]
  },
  "engines": {
    "bare": ">=1.16.0"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sodium-native.git"
  },
  "contributors": [
    "Emil Bay <github@tixz.dk> (http://bayes.dk)",
    "Mathias Buus <mathiasbuus@gmail.com> (https://mafinto.sh)",
    "Christophe Diederichs <chm-diederichs@hyperdivision.dk>"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/sodium-native/issues"
  },
  "homepage": "https://github.com/holepunchto/sodium-native"
}
const sodium = require('sodium-universal')
const b4a = require('b4a')

const ABYTES = sodium.crypto_secretstream_xchacha20poly1305_ABYTES
const TAG_MESSAGE = sodium.crypto_secretstream_xchacha20poly1305_TAG_MESSAGE
const TAG_FINAL = sodium.crypto_secretstream_xchacha20poly1305_TAG_FINAL
const STATEBYTES = sodium.crypto_secretstream_xchacha20poly1305_STATEBYTES
const HEADERBYTES = sodium.crypto_secretstream_xchacha20poly1305_HEADERBYTES
const KEYBYTES = sodium.crypto_secretstream_xchacha20poly1305_KEYBYTES
const TAG_FINAL_BYTE = b4a.isBuffer(TAG_FINAL) ? TAG_FINAL[0] : TAG_FINAL

const EMPTY = b4a.alloc(0)
const TAG = b4a.alloc(1)

class Push {
  constructor (key, state = b4a.allocUnsafeSlow(STATEBYTES), header = b4a.allocUnsafeSlow(HEADERBYTES)) {
    if (!TAG_FINAL) throw new Error('JavaScript sodium version needs to support crypto_secretstream_xchacha20poly')

    this.key = key
    this.state = state
    this.header = header

    sodium.crypto_secretstream_xchacha20poly1305_init_push(this.state, this.header, this.key)
  }

  next (message, cipher = b4a.allocUnsafe(message.byteLength + ABYTES)) {
    sodium.crypto_secretstream_xchacha20poly1305_push(this.state, cipher, message, null, TAG_MESSAGE)
    return cipher
  }

  final (message = EMPTY, cipher = b4a.allocUnsafe(ABYTES)) {
    sodium.crypto_secretstream_xchacha20poly1305_push(this.state, cipher, message, null, TAG_FINAL)
    return cipher
  }
}

class Pull {
  constructor (key, state = b4a.allocUnsafeSlow(STATEBYTES)) {
    if (!TAG_FINAL) throw new Error('JavaScript sodium version needs to support crypto_secretstream_xchacha20poly')

    this.key = key
    this.state = state
    this.final = false
  }

  init (header) {
    sodium.crypto_secretstream_xchacha20poly1305_init_pull(this.state, header, this.key)
  }

  next (cipher, message = b4a.allocUnsafe(cipher.byteLength - ABYTES)) {
    sodium.crypto_secretstream_xchacha20poly1305_pull(this.state, message, TAG, cipher, null)
    this.final = TAG[0] === TAG_FINAL_BYTE
    return message
  }
}

function keygen (buf = b4a.alloc(KEYBYTES)) {
  sodium.crypto_secretstream_xchacha20poly1305_keygen(buf)
  return buf
}

module.exports = {
  keygen,
  KEYBYTES,
  ABYTES,
  STATEBYTES,
  HEADERBYTES,
  Push,
  Pull
}
{
  "name": "sodium-secretstream",
  "version": "1.2.0",
  "description": "Wraps libsodiums secretstream in a higher level abstraction",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.1.1",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "standard": "^17.0.0"
  },
  "scripts": {
    "test": "standard"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/sodium-secretstream.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/sodium-secretstream/issues"
  },
  "homepage": "https://github.com/mafintosh/sodium-secretstream"
}
module.exports = require('sodium-native')
{
  "name": "sodium-universal",
  "version": "5.0.1",
  "description": "Universal wrapper for sodium-javascript and sodium-native working in Node.js and the Browser",
  "main": "index.js",
  "dependencies": {
    "sodium-native": "^5.0.1"
  },
  "peerDependencies": {
    "sodium-javascript": "~0.8.0"
  },
  "peerDependenciesMeta": {
    "sodium-javascript": {
      "optional": true
    }
  },
  "scripts": {
    "prepublish": "./build-scripts/generate.js"
  },
  "browser": {
    "sodium-native": "sodium-javascript"
  },
  "browserify": {
    "transform": [
      "./build-scripts/transform.js"
    ]
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sodium-universal.git"
  },
  "keywords": [
    "libsodium",
    "sodium",
    "sodium-native",
    "sodium-javascript",
    "browserify"
  ],
  "contributors": [
    "Emil Bay <github@tixz.dk> (http://bayes.dk)",
    "Mathias Buus <mathiasbuus@gmail.com> (https://mafinto.sh)",
    "Christophe Diederichs <chm-diederichs@hyperdivision.dk>"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/sodium-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/sodium-universal#readme"
}
const { EventEmitter } = require('events-universal')
const STREAM_DESTROYED = new Error('Stream was destroyed')
const PREMATURE_CLOSE = new Error('Premature close')

const FIFO = require('fast-fifo')
const TextDecoder = require('text-decoder')

// if we do a future major, expect queue microtask to be there always, for now a bit defensive
const qmt =
  typeof queueMicrotask === 'undefined' ? (fn) => global.process.nextTick(fn) : queueMicrotask

// 29 bits used total (4 from shared, 14 from read, and 11 from write)
const MAX = (1 << 29) - 1

// Shared state
const OPENING = 0b0001
const PREDESTROYING = 0b0010
const DESTROYING = 0b0100
const DESTROYED = 0b1000

const NOT_OPENING = MAX ^ OPENING
const NOT_PREDESTROYING = MAX ^ PREDESTROYING

// Read state (4 bit offset from shared state)
const READ_ACTIVE = 0b00000000000001 << 4
const READ_UPDATING = 0b00000000000010 << 4
const READ_PRIMARY = 0b00000000000100 << 4
const READ_QUEUED = 0b00000000001000 << 4
const READ_RESUMED = 0b00000000010000 << 4
const READ_PIPE_DRAINED = 0b00000000100000 << 4
const READ_ENDING = 0b00000001000000 << 4
const READ_EMIT_DATA = 0b00000010000000 << 4
const READ_EMIT_READABLE = 0b00000100000000 << 4
const READ_EMITTED_READABLE = 0b00001000000000 << 4
const READ_DONE = 0b00010000000000 << 4
const READ_NEXT_TICK = 0b00100000000000 << 4
const READ_NEEDS_PUSH = 0b01000000000000 << 4
const READ_READ_AHEAD = 0b10000000000000 << 4

// Combined read state
const READ_FLOWING = READ_RESUMED | READ_PIPE_DRAINED
const READ_ACTIVE_AND_NEEDS_PUSH = READ_ACTIVE | READ_NEEDS_PUSH
const READ_PRIMARY_AND_ACTIVE = READ_PRIMARY | READ_ACTIVE
const READ_EMIT_READABLE_AND_QUEUED = READ_EMIT_READABLE | READ_QUEUED
const READ_RESUMED_READ_AHEAD = READ_RESUMED | READ_READ_AHEAD

const READ_NOT_ACTIVE = MAX ^ READ_ACTIVE
const READ_NON_PRIMARY = MAX ^ READ_PRIMARY
const READ_NON_PRIMARY_AND_PUSHED = MAX ^ (READ_PRIMARY | READ_NEEDS_PUSH)
const READ_PUSHED = MAX ^ READ_NEEDS_PUSH
const READ_PAUSED = MAX ^ READ_RESUMED
const READ_NOT_QUEUED = MAX ^ (READ_QUEUED | READ_EMITTED_READABLE)
const READ_NOT_ENDING = MAX ^ READ_ENDING
const READ_PIPE_NOT_DRAINED = MAX ^ READ_FLOWING
const READ_NOT_NEXT_TICK = MAX ^ READ_NEXT_TICK
const READ_NOT_UPDATING = MAX ^ READ_UPDATING
const READ_NO_READ_AHEAD = MAX ^ READ_READ_AHEAD
const READ_PAUSED_NO_READ_AHEAD = MAX ^ READ_RESUMED_READ_AHEAD

// Write state (18 bit offset, 4 bit offset from shared state and 14 from read state)
const WRITE_ACTIVE = 0b00000000001 << 18
const WRITE_UPDATING = 0b00000000010 << 18
const WRITE_PRIMARY = 0b00000000100 << 18
const WRITE_QUEUED = 0b00000001000 << 18
const WRITE_UNDRAINED = 0b00000010000 << 18
const WRITE_DONE = 0b00000100000 << 18
const WRITE_EMIT_DRAIN = 0b00001000000 << 18
const WRITE_NEXT_TICK = 0b00010000000 << 18
const WRITE_WRITING = 0b00100000000 << 18
const WRITE_FINISHING = 0b01000000000 << 18
const WRITE_CORKED = 0b10000000000 << 18

const WRITE_NOT_ACTIVE = MAX ^ (WRITE_ACTIVE | WRITE_WRITING)
const WRITE_NON_PRIMARY = MAX ^ WRITE_PRIMARY
const WRITE_NOT_FINISHING = MAX ^ (WRITE_ACTIVE | WRITE_FINISHING)
const WRITE_DRAINED = MAX ^ WRITE_UNDRAINED
const WRITE_NOT_QUEUED = MAX ^ WRITE_QUEUED
const WRITE_NOT_NEXT_TICK = MAX ^ WRITE_NEXT_TICK
const WRITE_NOT_UPDATING = MAX ^ WRITE_UPDATING
const WRITE_NOT_CORKED = MAX ^ WRITE_CORKED

// Combined shared state
const ACTIVE = READ_ACTIVE | WRITE_ACTIVE
const NOT_ACTIVE = MAX ^ ACTIVE
const DONE = READ_DONE | WRITE_DONE
const DESTROY_STATUS = DESTROYING | DESTROYED | PREDESTROYING
const OPEN_STATUS = DESTROY_STATUS | OPENING
const AUTO_DESTROY = DESTROY_STATUS | DONE
const NON_PRIMARY = WRITE_NON_PRIMARY & READ_NON_PRIMARY
const ACTIVE_OR_TICKING = WRITE_NEXT_TICK | READ_NEXT_TICK
const TICKING = ACTIVE_OR_TICKING & NOT_ACTIVE
const IS_OPENING = OPEN_STATUS | TICKING

// Combined shared state and read state
const READ_PRIMARY_STATUS = OPEN_STATUS | READ_ENDING | READ_DONE
const READ_STATUS = OPEN_STATUS | READ_DONE | READ_QUEUED
const READ_ENDING_STATUS = OPEN_STATUS | READ_ENDING | READ_QUEUED
const READ_READABLE_STATUS = OPEN_STATUS | READ_EMIT_READABLE | READ_QUEUED | READ_EMITTED_READABLE
const SHOULD_NOT_READ =
  OPEN_STATUS | READ_ACTIVE | READ_ENDING | READ_DONE | READ_NEEDS_PUSH | READ_READ_AHEAD
const READ_BACKPRESSURE_STATUS = DESTROY_STATUS | READ_ENDING | READ_DONE
const READ_UPDATE_SYNC_STATUS = READ_UPDATING | OPEN_STATUS | READ_NEXT_TICK | READ_PRIMARY
const READ_NEXT_TICK_OR_OPENING = READ_NEXT_TICK | OPENING

// Combined write state
const WRITE_PRIMARY_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_DONE
const WRITE_QUEUED_AND_UNDRAINED = WRITE_QUEUED | WRITE_UNDRAINED
const WRITE_QUEUED_AND_ACTIVE = WRITE_QUEUED | WRITE_ACTIVE
const WRITE_DRAIN_STATUS = WRITE_QUEUED | WRITE_UNDRAINED | OPEN_STATUS | WRITE_ACTIVE
const WRITE_STATUS = OPEN_STATUS | WRITE_ACTIVE | WRITE_QUEUED | WRITE_CORKED
const WRITE_PRIMARY_AND_ACTIVE = WRITE_PRIMARY | WRITE_ACTIVE
const WRITE_ACTIVE_AND_WRITING = WRITE_ACTIVE | WRITE_WRITING
const WRITE_FINISHING_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_QUEUED_AND_ACTIVE | WRITE_DONE
const WRITE_BACKPRESSURE_STATUS = WRITE_UNDRAINED | DESTROY_STATUS | WRITE_FINISHING | WRITE_DONE
const WRITE_UPDATE_SYNC_STATUS = WRITE_UPDATING | OPEN_STATUS | WRITE_NEXT_TICK | WRITE_PRIMARY
const WRITE_DROP_DATA = WRITE_FINISHING | WRITE_DONE | DESTROY_STATUS

const asyncIterator = Symbol.asyncIterator || Symbol('asyncIterator')

class WritableState {
  constructor(
    stream,
    { highWaterMark = 16384, map = null, mapWritable, byteLength, byteLengthWritable } = {}
  ) {
    this.stream = stream
    this.queue = new FIFO()
    this.highWaterMark = highWaterMark
    this.buffered = 0
    this.error = null
    this.pipeline = null
    this.drains = null // if we add more seldomly used helpers we might them into a subobject so its a single ptr
    this.byteLength = byteLengthWritable || byteLength || defaultByteLength
    this.map = mapWritable || map
    this.afterWrite = afterWrite.bind(this)
    this.afterUpdateNextTick = updateWriteNT.bind(this)
  }

  get ending() {
    return (this.stream._duplexState & WRITE_FINISHING) !== 0
  }

  get ended() {
    return (this.stream._duplexState & WRITE_DONE) !== 0
  }

  push(data) {
    if ((this.stream._duplexState & WRITE_DROP_DATA) !== 0) return false
    if (this.map !== null) data = this.map(data)

    this.buffered += this.byteLength(data)
    this.queue.push(data)

    if (this.buffered < this.highWaterMark) {
      this.stream._duplexState |= WRITE_QUEUED
      return true
    }

    this.stream._duplexState |= WRITE_QUEUED_AND_UNDRAINED
    return false
  }

  shift() {
    const data = this.queue.shift()

    this.buffered -= this.byteLength(data)
    if (this.buffered === 0) this.stream._duplexState &= WRITE_NOT_QUEUED

    return data
  }

  end(data) {
    if (typeof data === 'function') this.stream.once('finish', data)
    else if (data !== undefined && data !== null) this.push(data)
    this.stream._duplexState = (this.stream._duplexState | WRITE_FINISHING) & WRITE_NON_PRIMARY
  }

  autoBatch(data, cb) {
    const buffer = []
    const stream = this.stream

    buffer.push(data)
    while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED_AND_ACTIVE) {
      buffer.push(stream._writableState.shift())
    }

    if ((stream._duplexState & OPEN_STATUS) !== 0) return cb(null)
    stream._writev(buffer, cb)
  }

  update() {
    const stream = this.stream

    stream._duplexState |= WRITE_UPDATING

    do {
      while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED) {
        const data = this.shift()
        stream._duplexState |= WRITE_ACTIVE_AND_WRITING
        stream._write(data, this.afterWrite)
      }

      if ((stream._duplexState & WRITE_PRIMARY_AND_ACTIVE) === 0) this.updateNonPrimary()
    } while (this.continueUpdate() === true)

    stream._duplexState &= WRITE_NOT_UPDATING
  }

  updateNonPrimary() {
    const stream = this.stream

    if ((stream._duplexState & WRITE_FINISHING_STATUS) === WRITE_FINISHING) {
      stream._duplexState = stream._duplexState | WRITE_ACTIVE
      stream._final(afterFinal.bind(this))
      return
    }

    if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
      if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
        stream._duplexState |= ACTIVE
        stream._destroy(afterDestroy.bind(this))
      }
      return
    }

    if ((stream._duplexState & IS_OPENING) === OPENING) {
      stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING
      stream._open(afterOpen.bind(this))
    }
  }

  continueUpdate() {
    if ((this.stream._duplexState & WRITE_NEXT_TICK) === 0) return false
    this.stream._duplexState &= WRITE_NOT_NEXT_TICK
    return true
  }

  updateCallback() {
    if ((this.stream._duplexState & WRITE_UPDATE_SYNC_STATUS) === WRITE_PRIMARY) this.update()
    else this.updateNextTick()
  }

  updateNextTick() {
    if ((this.stream._duplexState & WRITE_NEXT_TICK) !== 0) return
    this.stream._duplexState |= WRITE_NEXT_TICK
    if ((this.stream._duplexState & WRITE_UPDATING) === 0) qmt(this.afterUpdateNextTick)
  }
}

class ReadableState {
  constructor(
    stream,
    { highWaterMark = 16384, map = null, mapReadable, byteLength, byteLengthReadable } = {}
  ) {
    this.stream = stream
    this.queue = new FIFO()
    this.highWaterMark = highWaterMark === 0 ? 1 : highWaterMark
    this.buffered = 0
    this.readAhead = highWaterMark > 0
    this.error = null
    this.pipeline = null
    this.byteLength = byteLengthReadable || byteLength || defaultByteLength
    this.map = mapReadable || map
    this.pipeTo = null
    this.afterRead = afterRead.bind(this)
    this.afterUpdateNextTick = updateReadNT.bind(this)
  }

  get ending() {
    return (this.stream._duplexState & READ_ENDING) !== 0
  }

  get ended() {
    return (this.stream._duplexState & READ_DONE) !== 0
  }

  pipe(pipeTo, cb) {
    if (this.pipeTo !== null) throw new Error('Can only pipe to one destination')
    if (typeof cb !== 'function') cb = null

    this.stream._duplexState |= READ_PIPE_DRAINED
    this.pipeTo = pipeTo
    this.pipeline = new Pipeline(this.stream, pipeTo, cb)

    if (cb) this.stream.on('error', noop) // We already error handle this so supress crashes

    if (isStreamx(pipeTo)) {
      pipeTo._writableState.pipeline = this.pipeline
      if (cb) pipeTo.on('error', noop) // We already error handle this so supress crashes
      pipeTo.on('finish', this.pipeline.finished.bind(this.pipeline)) // TODO: just call finished from pipeTo itself
    } else {
      const onerror = this.pipeline.done.bind(this.pipeline, pipeTo)
      const onclose = this.pipeline.done.bind(this.pipeline, pipeTo, null) // onclose has a weird bool arg
      pipeTo.on('error', onerror)
      pipeTo.on('close', onclose)
      pipeTo.on('finish', this.pipeline.finished.bind(this.pipeline))
    }

    pipeTo.on('drain', afterDrain.bind(this))
    this.stream.emit('piping', pipeTo)
    pipeTo.emit('pipe', this.stream)
  }

  push(data) {
    const stream = this.stream

    if (data === null) {
      this.highWaterMark = 0
      stream._duplexState = (stream._duplexState | READ_ENDING) & READ_NON_PRIMARY_AND_PUSHED
      return false
    }

    if (this.map !== null) {
      data = this.map(data)
      if (data === null) {
        stream._duplexState &= READ_PUSHED
        return this.buffered < this.highWaterMark
      }
    }

    this.buffered += this.byteLength(data)
    this.queue.push(data)

    stream._duplexState = (stream._duplexState | READ_QUEUED) & READ_PUSHED

    return this.buffered < this.highWaterMark
  }

  shift() {
    const data = this.queue.shift()

    this.buffered -= this.byteLength(data)
    if (this.buffered === 0) this.stream._duplexState &= READ_NOT_QUEUED
    return data
  }

  unshift(data) {
    const pending = [this.map !== null ? this.map(data) : data]
    while (this.buffered > 0) pending.push(this.shift())

    for (let i = 0; i < pending.length - 1; i++) {
      const data = pending[i]
      this.buffered += this.byteLength(data)
      this.queue.push(data)
    }

    this.push(pending[pending.length - 1])
  }

  read() {
    const stream = this.stream

    if ((stream._duplexState & READ_STATUS) === READ_QUEUED) {
      const data = this.shift()
      if (this.pipeTo !== null && this.pipeTo.write(data) === false)
        stream._duplexState &= READ_PIPE_NOT_DRAINED
      if ((stream._duplexState & READ_EMIT_DATA) !== 0) stream.emit('data', data)
      return data
    }

    if (this.readAhead === false) {
      stream._duplexState |= READ_READ_AHEAD
      this.updateNextTick()
    }

    return null
  }

  drain() {
    const stream = this.stream

    while (
      (stream._duplexState & READ_STATUS) === READ_QUEUED &&
      (stream._duplexState & READ_FLOWING) !== 0
    ) {
      const data = this.shift()
      if (this.pipeTo !== null && this.pipeTo.write(data) === false)
        stream._duplexState &= READ_PIPE_NOT_DRAINED
      if ((stream._duplexState & READ_EMIT_DATA) !== 0) stream.emit('data', data)
    }
  }

  update() {
    const stream = this.stream

    stream._duplexState |= READ_UPDATING

    do {
      this.drain()

      while (
        this.buffered < this.highWaterMark &&
        (stream._duplexState & SHOULD_NOT_READ) === READ_READ_AHEAD
      ) {
        stream._duplexState |= READ_ACTIVE_AND_NEEDS_PUSH
        stream._read(this.afterRead)
        this.drain()
      }

      if ((stream._duplexState & READ_READABLE_STATUS) === READ_EMIT_READABLE_AND_QUEUED) {
        stream._duplexState |= READ_EMITTED_READABLE
        stream.emit('readable')
      }

      if ((stream._duplexState & READ_PRIMARY_AND_ACTIVE) === 0) this.updateNonPrimary()
    } while (this.continueUpdate() === true)

    stream._duplexState &= READ_NOT_UPDATING
  }

  updateNonPrimary() {
    const stream = this.stream

    if ((stream._duplexState & READ_ENDING_STATUS) === READ_ENDING) {
      stream._duplexState = (stream._duplexState | READ_DONE) & READ_NOT_ENDING
      stream.emit('end')
      if ((stream._duplexState & AUTO_DESTROY) === DONE) stream._duplexState |= DESTROYING
      if (this.pipeTo !== null) this.pipeTo.end()
    }

    if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
      if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
        stream._duplexState |= ACTIVE
        stream._destroy(afterDestroy.bind(this))
      }
      return
    }

    if ((stream._duplexState & IS_OPENING) === OPENING) {
      stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING
      stream._open(afterOpen.bind(this))
    }
  }

  continueUpdate() {
    if ((this.stream._duplexState & READ_NEXT_TICK) === 0) return false
    this.stream._duplexState &= READ_NOT_NEXT_TICK
    return true
  }

  updateCallback() {
    if ((this.stream._duplexState & READ_UPDATE_SYNC_STATUS) === READ_PRIMARY) this.update()
    else this.updateNextTick()
  }

  updateNextTickIfOpen() {
    if ((this.stream._duplexState & READ_NEXT_TICK_OR_OPENING) !== 0) return
    this.stream._duplexState |= READ_NEXT_TICK
    if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick)
  }

  updateNextTick() {
    if ((this.stream._duplexState & READ_NEXT_TICK) !== 0) return
    this.stream._duplexState |= READ_NEXT_TICK
    if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick)
  }
}

class TransformState {
  constructor(stream) {
    this.data = null
    this.afterTransform = afterTransform.bind(stream)
    this.afterFinal = null
  }
}

class Pipeline {
  constructor(src, dst, cb) {
    this.from = src
    this.to = dst
    this.afterPipe = cb
    this.error = null
    this.pipeToFinished = false
  }

  finished() {
    this.pipeToFinished = true
  }

  done(stream, err) {
    if (err) this.error = err

    if (stream === this.to) {
      this.to = null

      if (this.from !== null) {
        if ((this.from._duplexState & READ_DONE) === 0 || !this.pipeToFinished) {
          this.from.destroy(this.error || new Error('Writable stream closed prematurely'))
        }
        return
      }
    }

    if (stream === this.from) {
      this.from = null

      if (this.to !== null) {
        if ((stream._duplexState & READ_DONE) === 0) {
          this.to.destroy(this.error || new Error('Readable stream closed before ending'))
        }
        return
      }
    }

    if (this.afterPipe !== null) this.afterPipe(this.error)
    this.to = this.from = this.afterPipe = null
  }
}

function afterDrain() {
  this.stream._duplexState |= READ_PIPE_DRAINED
  this.updateCallback()
}

function afterFinal(err) {
  const stream = this.stream
  if (err) stream.destroy(err)
  if ((stream._duplexState & DESTROY_STATUS) === 0) {
    stream._duplexState |= WRITE_DONE
    stream.emit('finish')
  }
  if ((stream._duplexState & AUTO_DESTROY) === DONE) {
    stream._duplexState |= DESTROYING
  }

  stream._duplexState &= WRITE_NOT_FINISHING

  // no need to wait the extra tick here, so we short circuit that
  if ((stream._duplexState & WRITE_UPDATING) === 0) this.update()
  else this.updateNextTick()
}

function afterDestroy(err) {
  const stream = this.stream

  if (!err && this.error !== STREAM_DESTROYED) err = this.error
  if (err) stream.emit('error', err)
  stream._duplexState |= DESTROYED
  stream.emit('close')

  const rs = stream._readableState
  const ws = stream._writableState

  if (rs !== null && rs.pipeline !== null) rs.pipeline.done(stream, err)

  if (ws !== null) {
    while (ws.drains !== null && ws.drains.length > 0) ws.drains.shift().resolve(false)
    if (ws.pipeline !== null) ws.pipeline.done(stream, err)
  }
}

function afterWrite(err) {
  const stream = this.stream

  if (err) stream.destroy(err)
  stream._duplexState &= WRITE_NOT_ACTIVE

  if (this.drains !== null) tickDrains(this.drains)

  if ((stream._duplexState & WRITE_DRAIN_STATUS) === WRITE_UNDRAINED) {
    stream._duplexState &= WRITE_DRAINED
    if ((stream._duplexState & WRITE_EMIT_DRAIN) === WRITE_EMIT_DRAIN) {
      stream.emit('drain')
    }
  }

  this.updateCallback()
}

function afterRead(err) {
  if (err) this.stream.destroy(err)
  this.stream._duplexState &= READ_NOT_ACTIVE
  if (this.readAhead === false && (this.stream._duplexState & READ_RESUMED) === 0)
    this.stream._duplexState &= READ_NO_READ_AHEAD
  this.updateCallback()
}

function updateReadNT() {
  if ((this.stream._duplexState & READ_UPDATING) === 0) {
    this.stream._duplexState &= READ_NOT_NEXT_TICK
    this.update()
  }
}

function updateWriteNT() {
  if ((this.stream._duplexState & WRITE_UPDATING) === 0) {
    this.stream._duplexState &= WRITE_NOT_NEXT_TICK
    this.update()
  }
}

function tickDrains(drains) {
  for (let i = 0; i < drains.length; i++) {
    // drains.writes are monotonic, so if one is 0 its always the first one
    if (--drains[i].writes === 0) {
      drains.shift().resolve(true)
      i--
    }
  }
}

function afterOpen(err) {
  const stream = this.stream

  if (err) stream.destroy(err)

  if ((stream._duplexState & DESTROYING) === 0) {
    if ((stream._duplexState & READ_PRIMARY_STATUS) === 0) stream._duplexState |= READ_PRIMARY
    if ((stream._duplexState & WRITE_PRIMARY_STATUS) === 0) stream._duplexState |= WRITE_PRIMARY
    stream.emit('open')
  }

  stream._duplexState &= NOT_ACTIVE

  if (stream._writableState !== null) {
    stream._writableState.updateCallback()
  }

  if (stream._readableState !== null) {
    stream._readableState.updateCallback()
  }
}

function afterTransform(err, data) {
  if (data !== undefined && data !== null) this.push(data)
  this._writableState.afterWrite(err)
}

function newListener(name) {
  if (this._readableState !== null) {
    if (name === 'data') {
      this._duplexState |= READ_EMIT_DATA | READ_RESUMED_READ_AHEAD
      this._readableState.updateNextTick()
    }
    if (name === 'readable') {
      this._duplexState |= READ_EMIT_READABLE
      this._readableState.updateNextTick()
    }
  }

  if (this._writableState !== null) {
    if (name === 'drain') {
      this._duplexState |= WRITE_EMIT_DRAIN
      this._writableState.updateNextTick()
    }
  }
}

class Stream extends EventEmitter {
  constructor(opts) {
    super()

    this._duplexState = 0
    this._readableState = null
    this._writableState = null

    if (opts) {
      if (opts.open) this._open = opts.open
      if (opts.destroy) this._destroy = opts.destroy
      if (opts.predestroy) this._predestroy = opts.predestroy
      if (opts.signal) {
        opts.signal.addEventListener('abort', abort.bind(this))
      }
    }

    this.on('newListener', newListener)
  }

  _open(cb) {
    cb(null)
  }

  _destroy(cb) {
    cb(null)
  }

  _predestroy() {
    // does nothing
  }

  get readable() {
    return this._readableState !== null ? true : undefined
  }

  get writable() {
    return this._writableState !== null ? true : undefined
  }

  get destroyed() {
    return (this._duplexState & DESTROYED) !== 0
  }

  get destroying() {
    return (this._duplexState & DESTROY_STATUS) !== 0
  }

  destroy(err) {
    if ((this._duplexState & DESTROY_STATUS) === 0) {
      if (!err) err = STREAM_DESTROYED
      this._duplexState = (this._duplexState | DESTROYING) & NON_PRIMARY

      if (this._readableState !== null) {
        this._readableState.highWaterMark = 0
        this._readableState.error = err
      }
      if (this._writableState !== null) {
        this._writableState.highWaterMark = 0
        this._writableState.error = err
      }

      this._duplexState |= PREDESTROYING
      this._predestroy()
      this._duplexState &= NOT_PREDESTROYING

      if (this._readableState !== null) this._readableState.updateNextTick()
      if (this._writableState !== null) this._writableState.updateNextTick()
    }
  }
}

class Readable extends Stream {
  constructor(opts) {
    super(opts)

    this._duplexState |= OPENING | WRITE_DONE | READ_READ_AHEAD
    this._readableState = new ReadableState(this, opts)

    if (opts) {
      if (this._readableState.readAhead === false) this._duplexState &= READ_NO_READ_AHEAD
      if (opts.read) this._read = opts.read
      if (opts.eagerOpen) this._readableState.updateNextTick()
      if (opts.encoding) this.setEncoding(opts.encoding)
    }
  }

  setEncoding(encoding) {
    const dec = new TextDecoder(encoding)
    const map = this._readableState.map || echo
    this._readableState.map = mapOrSkip
    return this

    function mapOrSkip(data) {
      const next = dec.push(data)
      return next === '' && (data.byteLength !== 0 || dec.remaining > 0) ? null : map(next)
    }
  }

  _read(cb) {
    cb(null)
  }

  pipe(dest, cb) {
    this._readableState.updateNextTick()
    this._readableState.pipe(dest, cb)
    return dest
  }

  read() {
    this._readableState.updateNextTick()
    return this._readableState.read()
  }

  push(data) {
    this._readableState.updateNextTickIfOpen()
    return this._readableState.push(data)
  }

  unshift(data) {
    this._readableState.updateNextTickIfOpen()
    return this._readableState.unshift(data)
  }

  resume() {
    this._duplexState |= READ_RESUMED_READ_AHEAD
    this._readableState.updateNextTick()
    return this
  }

  pause() {
    this._duplexState &=
      this._readableState.readAhead === false ? READ_PAUSED_NO_READ_AHEAD : READ_PAUSED
    return this
  }

  static _fromAsyncIterator(ite, opts) {
    let destroy

    const rs = new Readable({
      ...opts,
      read(cb) {
        ite.next().then(push).then(cb.bind(null, null)).catch(cb)
      },
      predestroy() {
        destroy = ite.return()
      },
      destroy(cb) {
        if (!destroy) return cb(null)
        destroy.then(cb.bind(null, null)).catch(cb)
      }
    })

    return rs

    function push(data) {
      if (data.done) rs.push(null)
      else rs.push(data.value)
    }
  }

  static from(data, opts) {
    if (isReadStreamx(data)) return data
    if (data[asyncIterator]) return this._fromAsyncIterator(data[asyncIterator](), opts)
    if (!Array.isArray(data)) data = data === undefined ? [] : [data]

    let i = 0
    return new Readable({
      ...opts,
      read(cb) {
        this.push(i === data.length ? null : data[i++])
        cb(null)
      }
    })
  }

  static isBackpressured(rs) {
    return (
      (rs._duplexState & READ_BACKPRESSURE_STATUS) !== 0 ||
      rs._readableState.buffered >= rs._readableState.highWaterMark
    )
  }

  static isPaused(rs) {
    return (rs._duplexState & READ_RESUMED) === 0
  }

  [asyncIterator]() {
    const stream = this

    let error = null
    let promiseResolve = null
    let promiseReject = null

    this.on('error', (err) => {
      error = err
    })
    this.on('readable', onreadable)
    this.on('close', onclose)

    return {
      [asyncIterator]() {
        return this
      },
      next() {
        return new Promise(function (resolve, reject) {
          promiseResolve = resolve
          promiseReject = reject
          const data = stream.read()
          if (data !== null) ondata(data)
          else if ((stream._duplexState & DESTROYED) !== 0) ondata(null)
        })
      },
      return() {
        return destroy(null)
      },
      throw(err) {
        return destroy(err)
      }
    }

    function onreadable() {
      if (promiseResolve !== null) ondata(stream.read())
    }

    function onclose() {
      if (promiseResolve !== null) ondata(null)
    }

    function ondata(data) {
      if (promiseReject === null) return
      if (error) promiseReject(error)
      else if (data === null && (stream._duplexState & READ_DONE) === 0)
        promiseReject(STREAM_DESTROYED)
      else promiseResolve({ value: data, done: data === null })
      promiseReject = promiseResolve = null
    }

    function destroy(err) {
      stream.destroy(err)
      return new Promise((resolve, reject) => {
        if (stream._duplexState & DESTROYED) return resolve({ value: undefined, done: true })
        stream.once('close', function () {
          if (err) reject(err)
          else resolve({ value: undefined, done: true })
        })
      })
    }
  }
}

class Writable extends Stream {
  constructor(opts) {
    super(opts)

    this._duplexState |= OPENING | READ_DONE
    this._writableState = new WritableState(this, opts)

    if (opts) {
      if (opts.writev) this._writev = opts.writev
      if (opts.write) this._write = opts.write
      if (opts.final) this._final = opts.final
      if (opts.eagerOpen) this._writableState.updateNextTick()
    }
  }

  cork() {
    this._duplexState |= WRITE_CORKED
  }

  uncork() {
    this._duplexState &= WRITE_NOT_CORKED
    this._writableState.updateNextTick()
  }

  _writev(batch, cb) {
    cb(null)
  }

  _write(data, cb) {
    this._writableState.autoBatch(data, cb)
  }

  _final(cb) {
    cb(null)
  }

  static isBackpressured(ws) {
    return (ws._duplexState & WRITE_BACKPRESSURE_STATUS) !== 0
  }

  static drained(ws) {
    if (ws.destroyed) return Promise.resolve(false)
    const state = ws._writableState
    const pending = isWritev(ws) ? Math.min(1, state.queue.length) : state.queue.length
    const writes = pending + (ws._duplexState & WRITE_WRITING ? 1 : 0)
    if (writes === 0) return Promise.resolve(true)
    if (state.drains === null) state.drains = []
    return new Promise((resolve) => {
      state.drains.push({ writes, resolve })
    })
  }

  write(data) {
    this._writableState.updateNextTick()
    return this._writableState.push(data)
  }

  end(data) {
    this._writableState.updateNextTick()
    this._writableState.end(data)
    return this
  }
}

class Duplex extends Readable {
  // and Writable
  constructor(opts) {
    super(opts)

    this._duplexState = OPENING | (this._duplexState & READ_READ_AHEAD)
    this._writableState = new WritableState(this, opts)

    if (opts) {
      if (opts.writev) this._writev = opts.writev
      if (opts.write) this._write = opts.write
      if (opts.final) this._final = opts.final
    }
  }

  cork() {
    this._duplexState |= WRITE_CORKED
  }

  uncork() {
    this._duplexState &= WRITE_NOT_CORKED
    this._writableState.updateNextTick()
  }

  _writev(batch, cb) {
    cb(null)
  }

  _write(data, cb) {
    this._writableState.autoBatch(data, cb)
  }

  _final(cb) {
    cb(null)
  }

  write(data) {
    this._writableState.updateNextTick()
    return this._writableState.push(data)
  }

  end(data) {
    this._writableState.updateNextTick()
    this._writableState.end(data)
    return this
  }
}

class Transform extends Duplex {
  constructor(opts) {
    super(opts)
    this._transformState = new TransformState(this)

    if (opts) {
      if (opts.transform) this._transform = opts.transform
      if (opts.flush) this._flush = opts.flush
    }
  }

  _write(data, cb) {
    if (this._readableState.buffered >= this._readableState.highWaterMark) {
      this._transformState.data = data
    } else {
      this._transform(data, this._transformState.afterTransform)
    }
  }

  _read(cb) {
    if (this._transformState.data !== null) {
      const data = this._transformState.data
      this._transformState.data = null
      cb(null)
      this._transform(data, this._transformState.afterTransform)
    } else {
      cb(null)
    }
  }

  destroy(err) {
    super.destroy(err)
    if (this._transformState.data !== null) {
      this._transformState.data = null
      this._transformState.afterTransform()
    }
  }

  _transform(data, cb) {
    cb(null, data)
  }

  _flush(cb) {
    cb(null)
  }

  _final(cb) {
    this._transformState.afterFinal = cb
    this._flush(transformAfterFlush.bind(this))
  }
}

class PassThrough extends Transform {}

function transformAfterFlush(err, data) {
  const cb = this._transformState.afterFinal
  if (err) return cb(err)
  if (data !== null && data !== undefined) this.push(data)
  this.push(null)
  cb(null)
}

function pipelinePromise(...streams) {
  return new Promise((resolve, reject) => {
    return pipeline(...streams, (err) => {
      if (err) return reject(err)
      resolve()
    })
  })
}

function pipeline(stream, ...streams) {
  const all = Array.isArray(stream) ? [...stream, ...streams] : [stream, ...streams]
  const done = all.length && typeof all[all.length - 1] === 'function' ? all.pop() : null

  if (all.length < 2) throw new Error('Pipeline requires at least 2 streams')

  let src = all[0]
  let dest = null
  let error = null

  for (let i = 1; i < all.length; i++) {
    dest = all[i]

    if (isStreamx(src)) {
      src.pipe(dest, onerror)
    } else {
      errorHandle(src, true, i > 1, onerror)
      src.pipe(dest)
    }

    src = dest
  }

  if (done) {
    let fin = false

    const autoDestroy =
      isStreamx(dest) || !!(dest._writableState && dest._writableState.autoDestroy)

    dest.on('error', (err) => {
      if (error === null) error = err
    })

    dest.on('finish', () => {
      fin = true
      if (!autoDestroy) done(error)
    })

    if (autoDestroy) {
      dest.on('close', () => done(error || (fin ? null : PREMATURE_CLOSE)))
    }
  }

  return dest

  function errorHandle(s, rd, wr, onerror) {
    s.on('error', onerror)
    s.on('close', onclose)

    function onclose() {
      if (rd && s._readableState && !s._readableState.ended) return onerror(PREMATURE_CLOSE)
      if (wr && s._writableState && !s._writableState.ended) return onerror(PREMATURE_CLOSE)
    }
  }

  function onerror(err) {
    if (!err || error) return
    error = err

    for (const s of all) {
      s.destroy(err)
    }
  }
}

function echo(s) {
  return s
}

function isStream(stream) {
  return !!stream._readableState || !!stream._writableState
}

function isStreamx(stream) {
  return typeof stream._duplexState === 'number' && isStream(stream)
}

function isEnding(stream) {
  return !!stream._readableState && stream._readableState.ending
}

function isEnded(stream) {
  return !!stream._readableState && stream._readableState.ended
}

function isFinishing(stream) {
  return !!stream._writableState && stream._writableState.ending
}

function isFinished(stream) {
  return !!stream._writableState && stream._writableState.ended
}

function getStreamError(stream, opts = {}) {
  const err =
    (stream._readableState && stream._readableState.error) ||
    (stream._writableState && stream._writableState.error)

  // avoid implicit errors by default
  return !opts.all && err === STREAM_DESTROYED ? null : err
}

function isReadStreamx(stream) {
  return isStreamx(stream) && stream.readable
}

function isDisturbed(stream) {
  return (
    (stream._duplexState & OPENING) !== OPENING ||
    (stream._duplexState & DESTROYING) === DESTROYING ||
    (stream._duplexState & ACTIVE_OR_TICKING) !== 0
  )
}

function isTypedArray(data) {
  return typeof data === 'object' && data !== null && typeof data.byteLength === 'number'
}

function defaultByteLength(data) {
  return isTypedArray(data) ? data.byteLength : 1024
}

function noop() {}

function abort() {
  this.destroy(new Error('Stream aborted.'))
}

function isWritev(s) {
  return s._writev !== Writable.prototype._writev && s._writev !== Duplex.prototype._writev
}

module.exports = {
  pipeline,
  pipelinePromise,
  isStream,
  isStreamx,
  isEnding,
  isEnded,
  isFinishing,
  isFinished,
  isDisturbed,
  getStreamError,
  Stream,
  Writable,
  Readable,
  Duplex,
  Transform,
  // Export PassThrough for compatibility with Node.js core's stream module
  PassThrough
}
{
  "name": "streamx",
  "version": "2.25.0",
  "description": "An iteration of the Node.js core streams with a series of improvements",
  "main": "index.js",
  "dependencies": {
    "events-universal": "^1.0.0",
    "fast-fifo": "^1.3.2",
    "text-decoder": "^1.1.0"
  },
  "devDependencies": {
    "b4a": "^1.6.6",
    "brittle": "^3.1.1",
    "end-of-stream": "^1.4.4",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "files": [
    "index.js"
  ],
  "scripts": {
    "format": "prettier --write .",
    "test": "prettier --check . && node test/all.js",
    "test:bare": "bare test/all.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/streamx.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/streamx/issues"
  },
  "homepage": "https://github.com/mafintosh/streamx"
}
const codecs = require('codecs')
const b = require('b4a')

const SEP = b.alloc(1)
const SEP_BUMPED = b.from([0x1])
const EMPTY = b.alloc(0)

module.exports = class SubEncoder {
  constructor (prefix, encoding, parent = null) {
    this.userEncoding = codecs(encoding)
    this.prefix = prefix != null ? createPrefix(prefix, parent) : null
    this.lt = this.prefix && b.concat([this.prefix.subarray(0, this.prefix.byteLength - 1), SEP_BUMPED])
  }

  _encodeRangeUser (r) {
    if (this.userEncoding.encodeRange) return this.userEncoding.encodeRange(r)

    const res = {}
    if (r.gt != null) res.gt = this.userEncoding.encode(r.gt)
    if (r.gte != null) res.gte = this.userEncoding.encode(r.gte)
    if (r.lte != null) res.lte = this.userEncoding.encode(r.lte)
    if (r.lt != null) res.lt = this.userEncoding.encode(r.lt)

    return res
  }

  _addPrefix (key) {
    return this.prefix ? b.concat([this.prefix, key]) : key
  }

  encode (key) {
    return this._addPrefix(this.userEncoding.encode(key))
  }

  encodeRange (range) {
    const r = this._encodeRangeUser(range)

    if (r.gt) r.gt = this._addPrefix(r.gt)
    else if (r.gte) r.gte = this._addPrefix(r.gte)
    else if (this.prefix) r.gte = this.prefix

    if (r.lt) r.lt = this._addPrefix(r.lt)
    else if (r.lte) r.lte = this._addPrefix(r.lte)
    else if (this.prefix) r.lt = this.lt

    return r
  }

  decode (key) {
    return this.userEncoding.decode(this.prefix ? key.subarray(this.prefix.byteLength) : key)
  }

  sub (prefix, encoding) {
    return new SubEncoder(prefix || EMPTY, compat(encoding), this.prefix)
  }
}

function createPrefix (prefix, parent) {
  prefix = typeof prefix === 'string' ? b.from(prefix) : prefix

  if (prefix && parent) return b.concat([parent, prefix, SEP])
  if (prefix) return b.concat([prefix, SEP])
  if (parent) return b.concat([parent, SEP])
  return SEP
}

function compat (enc) {
  if (enc && enc.keyEncoding) return enc.keyEncoding
  return enc
}
{
  "name": "sub-encoder",
  "version": "2.1.3",
  "description": "Generate sub encodings for key/value stores",
  "main": "index.js",
  "scripts": {
    "test": "standard && brittle test/*.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sub-encoder.git"
  },
  "keywords": [
    "kv-store",
    "encoding",
    "hyperbee"
  ],
  "author": "Andrew Osheroff <andrewosh@gmail.com>",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/sub-encoder/issues"
  },
  "homepage": "https://github.com/holepunchto/sub-encoder#readme",
  "devDependencies": {
    "brittle": "^3.1.1",
    "compact-encoding": "^2.12.0",
    "hyperbee": "^2.11.0",
    "hypercore": "^10.3.2",
    "index-encoder": "^3.0.0",
    "random-access-memory": "^6.0.0",
    "standard": "^17.0.0"
  },
  "dependencies": {
    "b4a": "^1.6.0",
    "codecs": "^3.1.0"
  }
}
const { Readable } = require('streamx')

module.exports = function (s, forks = 2) {
  const streams = new Array(forks)
  const status = new Array(forks).fill(true)

  let ended = false

  for (let i = 0; i < forks; i++) {
    streams[i] = new Readable({
      read (cb) {
        const check = !status[i]
        status[i] = true
        if (check && allReadable()) s.resume()
        cb(null)
      }
    })
  }

  s.on('end', function () {
    ended = true
    for (const stream of streams) stream.push(null)
  })

  s.on('error', function (err) {
    for (const stream of streams) stream.destroy(err)
  })

  s.on('close', function () {
    if (ended) return
    for (const stream of streams) stream.destroy()
  })

  s.on('data', function (data) {
    let needsPause = false
    for (let i = 0; i < streams.length; i++) {
      if (!(status[i] = streams[i].push(data))) {
        needsPause = true
      }
    }
    if (needsPause) s.pause()
  })

  return streams

  function allReadable () {
    for (let j = 0; j < status.length; j++) {
      if (!status[j]) return false
    }
    return true
  }
}
{
  "name": "teex",
  "version": "1.0.1",
  "description": "Turn a readable stream into multiple readable streamx streams",
  "main": "index.js",
  "dependencies": {
    "streamx": "^2.12.5"
  },
  "devDependencies": {
    "standard": "^14.3.4",
    "tape": "^5.0.1"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/teex.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/teex/issues"
  },
  "homepage": "https://github.com/mafintosh/teex"
}
const PassThroughDecoder = require('./lib/pass-through-decoder')
const UTF8Decoder = require('./lib/utf8-decoder')

module.exports = class TextDecoder {
  constructor(encoding = 'utf8') {
    this.encoding = normalizeEncoding(encoding)

    switch (this.encoding) {
      case 'utf8':
        this.decoder = new UTF8Decoder()
        break
      case 'utf16le':
      case 'base64':
        throw new Error('Unsupported encoding: ' + this.encoding)
      default:
        this.decoder = new PassThroughDecoder(this.encoding)
    }
  }

  get remaining() {
    return this.decoder.remaining
  }

  push(data) {
    if (typeof data === 'string') return data
    return this.decoder.decode(data)
  }

  // For Node.js compatibility
  write(data) {
    return this.push(data)
  }

  end(data) {
    let result = ''
    if (data) result = this.push(data)
    result += this.decoder.flush()
    return result
  }
}

function normalizeEncoding(encoding) {
  encoding = encoding.toLowerCase()

  switch (encoding) {
    case 'utf8':
    case 'utf-8':
      return 'utf8'
    case 'ucs2':
    case 'ucs-2':
    case 'utf16le':
    case 'utf-16le':
      return 'utf16le'
    case 'latin1':
    case 'binary':
      return 'latin1'
    case 'base64':
    case 'ascii':
    case 'hex':
      return encoding
    default:
      throw new Error('Unknown encoding: ' + encoding)
  }
}
const b4a = require('b4a')

module.exports = class PassThroughDecoder {
  constructor(encoding) {
    this.encoding = encoding
  }

  get remaining() {
    return 0
  }

  decode(data) {
    return b4a.toString(data, this.encoding)
  }

  flush() {
    return ''
  }
}
const b4a = require('b4a')

/**
 * https://encoding.spec.whatwg.org/#utf-8-decoder
 */
module.exports = class UTF8Decoder {
  constructor() {
    this._reset()
  }

  get remaining() {
    return this.bytesSeen
  }

  decode(data) {
    if (data.byteLength === 0) return ''

    if (this.bytesNeeded === 0 && trailingIncomplete(data, 0) === 0) {
      this.bytesSeen = trailingBytesSeen(data)
      return b4a.toString(data, 'utf8')
    }

    let result = ''
    let start = 0

    if (this.bytesNeeded > 0) {
      while (start < data.byteLength) {
        const byte = data[start]

        if (byte < this.lowerBoundary || byte > this.upperBoundary) {
          result += '\ufffd'
          this._reset()
          break
        }

        this.lowerBoundary = 0x80
        this.upperBoundary = 0xbf
        this.codePoint = (this.codePoint << 6) | (byte & 0x3f)
        this.bytesSeen++
        start++

        if (this.bytesSeen === this.bytesNeeded) {
          result += String.fromCodePoint(this.codePoint)
          this._reset()
          break
        }
      }

      if (this.bytesNeeded > 0) return result
    }

    const trailing = trailingIncomplete(data, start)
    const end = data.byteLength - trailing

    if (end > start) result += b4a.toString(data, 'utf8', start, end)

    for (let i = end; i < data.byteLength; i++) {
      const byte = data[i]

      if (this.bytesNeeded === 0) {
        if (byte <= 0x7f) {
          this.bytesSeen = 0
          result += String.fromCharCode(byte)
        } else if (byte >= 0xc2 && byte <= 0xdf) {
          this.bytesNeeded = 2
          this.bytesSeen = 1
          this.codePoint = byte & 0x1f
        } else if (byte >= 0xe0 && byte <= 0xef) {
          if (byte === 0xe0) this.lowerBoundary = 0xa0
          else if (byte === 0xed) this.upperBoundary = 0x9f
          this.bytesNeeded = 3
          this.bytesSeen = 1
          this.codePoint = byte & 0xf
        } else if (byte >= 0xf0 && byte <= 0xf4) {
          if (byte === 0xf0) this.lowerBoundary = 0x90
          else if (byte === 0xf4) this.upperBoundary = 0x8f
          this.bytesNeeded = 4
          this.bytesSeen = 1
          this.codePoint = byte & 0x7
        } else {
          this.bytesSeen = 1
          result += '\ufffd'
        }

        continue
      }

      if (byte < this.lowerBoundary || byte > this.upperBoundary) {
        result += '\ufffd'
        i--
        this._reset()

        continue
      }

      this.lowerBoundary = 0x80
      this.upperBoundary = 0xbf

      this.codePoint = (this.codePoint << 6) | (byte & 0x3f)
      this.bytesSeen++

      if (this.bytesSeen === this.bytesNeeded) {
        result += String.fromCodePoint(this.codePoint)
        this._reset()
      }
    }

    return result
  }

  flush() {
    const result = this.bytesNeeded > 0 ? '\ufffd' : ''
    this._reset()
    return result
  }

  _reset() {
    this.codePoint = 0
    this.bytesNeeded = 0
    this.bytesSeen = 0
    this.lowerBoundary = 0x80
    this.upperBoundary = 0xbf
  }
}

function trailingIncomplete(data, start) {
  const len = data.byteLength
  if (len <= start) return 0

  const limit = Math.max(start, len - 4)

  let i = len - 1
  while (i > limit && (data[i] & 0xc0) === 0x80) i--

  if (i < start) return 0

  const byte = data[i]

  let needed
  if (byte <= 0x7f) return 0
  if (byte >= 0xc2 && byte <= 0xdf) needed = 2
  else if (byte >= 0xe0 && byte <= 0xef) needed = 3
  else if (byte >= 0xf0 && byte <= 0xf4) needed = 4
  else return 0

  const available = len - i
  return available < needed ? available : 0
}

function trailingBytesSeen(data) {
  const len = data.byteLength
  if (len === 0) return 0

  const last = data[len - 1]

  if (last <= 0x7f) return 0
  if ((last & 0xc0) !== 0x80) return 1

  const limit = Math.max(0, len - 4)

  let i = len - 2
  while (i >= limit && (data[i] & 0xc0) === 0x80) i--

  if (i < 0) return 1

  const first = data[i]

  let needed
  if (first >= 0xc2 && first <= 0xdf) needed = 2
  else if (first >= 0xe0 && first <= 0xef) needed = 3
  else if (first >= 0xf0 && first <= 0xf4) needed = 4
  else return 1

  if (len - i !== needed) return 1

  if (needed >= 3) {
    const second = data[i + 1]
    if (first === 0xe0 && second < 0xa0) return 1
    if (first === 0xed && second > 0x9f) return 1
    if (first === 0xf0 && second < 0x90) return 1
    if (first === 0xf4 && second > 0x8f) return 1
  }

  return 0
}
{
  "name": "text-decoder",
  "version": "1.2.7",
  "description": "Streaming text decoder that preserves multibyte Unicode characters",
  "exports": {
    "./package": "./package.json",
    ".": "./index.js"
  },
  "files": [
    "index.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/text-decoder.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/text-decoder/issues"
  },
  "homepage": "https://github.com/holepunchto/text-decoder#readme",
  "dependencies": {
    "b4a": "^1.6.4"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  }
}
module.exports = class TimerBrowser {
  constructor (ms, fn, ctx = null, interval = false) {
    this.ms = ms
    this.ontimeout = fn
    this.context = ctx || null
    this.interval = interval
    this.done = false

    this._timer = interval
      ? setInterval(callInterval, ms, this)
      : setTimeout(callTimeout, ms, this)
  }

  unref () {}

  ref () {}

  refresh () {
    if (this.done) return

    if (this.interval) {
      clearInterval(this._timer)
      this._timer = setInterval(callInterval, this.ms, this)
    } else {
      clearTimeout(this._timer)
      this._timer = setTimeout(callTimeout, this.ms, this)
    }
  }

  destroy () {
    this.done = true
    this.ontimeout = null

    if (this.interval) clearInterval(this._timer)
    else clearTimeout(this._timer)
  }

  static once (ms, fn, ctx) {
    return new this(ms, fn, ctx, false)
  }

  static on (ms, fn, ctx) {
    return new this(ms, fn, ctx, true)
  }
}

function callTimeout (self) {
  self.done = true
  self.ontimeout.call(self.context)
}

function callInterval (self) {
  self.ontimeout.call(self.context)
}
module.exports = isNode()
  ? require('./node')
  : require('./browser')

function isNode () {
  const to = setTimeout(function () {}, 1000)
  clearTimeout(to)
  return !!to.refresh
}
module.exports = class Timer {
  constructor (ms, fn, ctx = null, interval = false) {
    this.ms = ms
    this.ontimeout = fn
    this.context = ctx
    this.interval = interval
    this.done = false

    this._timer = interval
      ? setInterval(callInterval, ms, this)
      : setTimeout(callTimeout, ms, this)
  }

  unref () {
    this._timer.unref()
  }

  ref () {
    this._timer.ref()
  }

  refresh () {
    if (this.done !== true) this._timer.refresh()
  }

  destroy () {
    this.done = true
    this.ontimeout = null
    if (this.interval) clearInterval(this._timer)
    else clearTimeout(this._timer)
  }

  static once (ms, fn, ctx) {
    return new this(ms, fn, ctx, false)
  }

  static on (ms, fn, ctx) {
    return new this(ms, fn, ctx, true)
  }
}

function callTimeout (self) {
  self.done = true
  self.ontimeout.call(self.context)
}

function callInterval (self) {
  self.ontimeout.call(self.context)
}
{
  "name": "timeout-refresh",
  "version": "2.0.1",
  "description": "Efficiently refresh a timer",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^16.0.4",
    "tape": "^5.5.2"
  },
  "browser": "./browser.js",
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/timeout-refresh.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/timeout-refresh/issues"
  },
  "homepage": "https://github.com/mafintosh/timeout-refresh"
}
const b4a = require('b4a')

module.exports = class BufferMap {
  constructor (other) {
    this.m = other ? new Map([...other.m]) : new Map()
  }

  get size () {
    return this.m.size
  }

  get (key) {
    if (b4a.isBuffer(key)) key = b4a.toString(key, 'hex')
    return this.m.get(key)
  }

  set (key, value) {
    if (b4a.isBuffer(key)) key = b4a.toString(key, 'hex')
    return this.m.set(key, value)
  }

  delete (key) {
    if (b4a.isBuffer(key)) key = b4a.toString(key, 'hex')
    return this.m.delete(key)
  }

  has (key) {
    if (b4a.isBuffer(key)) key = b4a.toString(key, 'hex')
    return this.m.has(key)
  }

  * [Symbol.iterator] () {
    for (const [key, value] of this.m) {
      yield [b4a.from(key, 'hex'), value]
    }
  }

  * keys () {
    for (const key of this.m.keys()) {
      yield b4a.from(key, 'hex')
    }
  }

  values () {
    return this.m.values()
  }

  clear () {
    return this.m.clear()
  }
}
{
  "name": "tiny-buffer-map",
  "version": "1.1.1",
  "description": "A very simple map for Buffers",
  "main": "index.js",
  "scripts": {
    "test": "brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/andrewosh/tiny-buffer-map.git"
  },
  "keywords": [
    "buffer",
    "map"
  ],
  "author": "Andrew Osheroff <andrewosh@gmail.com>",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/andrewosh/tiny-buffer-map/issues"
  },
  "homepage": "https://github.com/andrewosh/tiny-buffer-map#readme",
  "dependencies": {
    "b4a": "^1.6.0"
  },
  "devDependencies": {
    "brittle": "^3.0.4"
  }
}
const b4a = require('b4a')

unslab.all = all
unslab.is = is

module.exports = unslab

function unslab (buf) {
  if (buf === null || buf.buffer.byteLength === buf.byteLength) return buf
  const copy = b4a.allocUnsafeSlow(buf.byteLength)
  copy.set(buf, 0)
  return copy
}

function is (buf) {
  return buf.buffer.byteLength !== buf.byteLength
}

function all (list) {
  let size = 0
  for (let i = 0; i < list.length; i++) {
    const buf = list[i]
    size += buf === null || buf.buffer.byteLength === buf.byteLength ? 0 : buf.byteLength
  }

  const copy = b4a.allocUnsafeSlow(size)
  const result = new Array(list.length)

  let offset = 0
  for (let i = 0; i < list.length; i++) {
    let buf = list[i]

    if (buf !== null && buf.buffer.byteLength !== buf.byteLength) {
      copy.set(buf, offset)
      buf = copy.subarray(offset, offset += buf.byteLength)
    }

    result[i] = buf
  }

  return result
}
{
  "name": "unslab",
  "version": "1.3.0",
  "description": "Unslab some slab'ed buffers",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.6.6"
  },
  "devDependencies": {
    "brittle": "^3.5.2",
    "standard": "^17.1.0"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/unslab.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/unslab/issues"
  },
  "homepage": "https://github.com/holepunchto/unslab"
}
module.exports = read

var MSB = 0x80
  , REST = 0x7F

function read(buf, offset) {
  var res    = 0
    , offset = offset || 0
    , shift  = 0
    , counter = offset
    , b
    , l = buf.length

  do {
    if (counter >= l) {
      read.bytes = 0
      throw new RangeError('Could not decode varint')
    }
    b = buf[counter++]
    res += shift < 28
      ? (b & REST) << shift
      : (b & REST) * Math.pow(2, shift)
    shift += 7
  } while (b >= MSB)

  read.bytes = counter - offset

  return res
}
module.exports = encode

var MSB = 0x80
  , REST = 0x7F
  , MSBALL = ~REST
  , INT = Math.pow(2, 31)

function encode(num, out, offset) {
  out = out || []
  offset = offset || 0
  var oldOffset = offset

  while(num >= INT) {
    out[offset++] = (num & 0xFF) | MSB
    num /= 128
  }
  while(num & MSBALL) {
    out[offset++] = (num & 0xFF) | MSB
    num >>>= 7
  }
  out[offset] = num | 0
  
  encode.bytes = offset - oldOffset + 1
  
  return out
}
module.exports = {
    encode: require('./encode.js')
  , decode: require('./decode.js')
  , encodingLength: require('./length.js')
}

var N1 = Math.pow(2,  7)
var N2 = Math.pow(2, 14)
var N3 = Math.pow(2, 21)
var N4 = Math.pow(2, 28)
var N5 = Math.pow(2, 35)
var N6 = Math.pow(2, 42)
var N7 = Math.pow(2, 49)
var N8 = Math.pow(2, 56)
var N9 = Math.pow(2, 63)

module.exports = function (value) {
  return (
    value < N1 ? 1
  : value < N2 ? 2
  : value < N3 ? 3
  : value < N4 ? 4
  : value < N5 ? 5
  : value < N6 ? 6
  : value < N7 ? 7
  : value < N8 ? 8
  : value < N9 ? 9
  :              10
  )
}
{
  "name": "varint",
  "version": "5.0.0",
  "description": "protobuf-style varint bytes - use msb to create integer values of varying sizes",
  "main": "index.js",
  "scripts": {
    "test": "node test.js"
  },
  "repository": {
    "type": "git",
    "url": "git://github.com/chrisdickinson/varint.git"
  },
  "keywords": [
    "varint",
    "protobuf",
    "encode",
    "decode"
  ],
  "author": "Chris Dickinson <chris@neversaw.us>",
  "license": "MIT",
  "devDependencies": {
    "tape": "~2.12.3"
  }
}
const { runtime, platform, arch } = typeof Bare !== 'undefined'
  ? { runtime: 'bare', platform: global.Bare.platform, arch: global.Bare.arch }
  : typeof process !== 'undefined'
    ? { runtime: 'node', platform: global.process.platform, arch: global.process.arch }
    : typeof Window !== 'undefined'
      ? { runtime: 'browser', platform: 'unknown', arch: 'unknown' }
      : { runtime: 'unknown', platform: 'unknown', arch: 'unknown' }

exports.runtime = runtime
exports.platform = platform
exports.arch = arch
exports.isBare = runtime === 'bare'
exports.isBareKit = exports.isBare && typeof BareKit !== 'undefined'
exports.isPear = typeof Pear !== 'undefined'
exports.isNode = runtime === 'node'
exports.isBrowser = runtime === 'browser'
exports.isWindows = platform === 'win32'
exports.isLinux = platform === 'linux'
exports.isMac = platform === 'darwin'
exports.isIOS = platform === 'ios' || platform === 'ios-simulator'
exports.isAndroid = platform === 'android'
exports.isElectron = typeof process !== 'undefined' && !!global.process.versions?.electron
exports.isElectronRenderer = exports.isElectron && global.process.type === 'renderer'
exports.isElectronWorker = exports.isElectron && global.process.type === 'worker'
{
  "name": "which-runtime",
  "version": "1.3.2",
  "description": "Detect if you are in Bare or Node and which os etc",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {},
  "devDependencies": {
    "standard": "^17.0.0"
  },
  "scripts": {
    "test": "standard"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/which-runtime.git"
  },
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/which-runtime/issues"
  },
  "homepage": "https://github.com/holepunchto/which-runtime"
}
const b4a = require('b4a')

const ALPHABET = 'ybndrfg8ejkmcpqxot1uwisza345h769'
const MIN = 0x31 // 1
const MAX = 0x7a // z
const REVERSE = new Int8Array(1 + MAX - MIN)

REVERSE.fill(-1)

for (let i = 0; i < ALPHABET.length; i++) {
  const v = ALPHABET.charCodeAt(i) - MIN
  REVERSE[v] = i
}

exports.encode = encode
exports.decode = decode
exports.ALPHABET = ALPHABET

function decode (s, out) {
  let pb = 0
  let ps = 0

  const r = s.length & 7
  const q = (s.length - r) / 8

  if (!out) out = b4a.allocUnsafe(Math.ceil(s.length * 5 / 8))

  // 0 5 2 7 4 1 6 3 (+5 mod 8)
  for (let i = 0; i < q; i++) {
    const a = quintet(s, ps++)
    const b = quintet(s, ps++)
    const c = quintet(s, ps++)
    const d = quintet(s, ps++)
    const e = quintet(s, ps++)
    const f = quintet(s, ps++)
    const g = quintet(s, ps++)
    const h = quintet(s, ps++)

    out[pb++] = (a << 3) | (b >>> 2)
    out[pb++] = ((b & 0b11) << 6) | (c << 1) | (d >>> 4)
    out[pb++] = ((d & 0b1111) << 4) | (e >>> 1)
    out[pb++] = ((e & 0b1) << 7) | (f << 2) | (g >>> 3)
    out[pb++] = ((g & 0b111) << 5) | h
  }

  if (r === 0) return out.subarray(0, pb)

  const a = quintet(s, ps++)
  const b = quintet(s, ps++)

  out[pb++] = (a << 3) | (b >>> 2)

  if (r <= 2) return out.subarray(0, pb)

  const c = quintet(s, ps++)
  const d = quintet(s, ps++)

  out[pb++] = ((b & 0b11) << 6) | (c << 1) | (d >>> 4)

  if (r <= 4) return out.subarray(0, pb)

  const e = quintet(s, ps++)

  out[pb++] = ((d & 0b1111) << 4) | (e >>> 1)

  if (r <= 5) return out.subarray(0, pb)

  const f = quintet(s, ps++)
  const g = quintet(s, ps++)

  out[pb++] = ((e & 0b1) << 7) | (f << 2) | (g >>> 3)

  if (r <= 7) return out.subarray(0, pb)

  const h = quintet(s, ps++)

  out[pb++] = ((g & 0b111) << 5) | h

  return out.subarray(0, pb)
}

function encode (buf) {
  if (typeof buf === 'string') buf = b4a.from(buf)

  const max = buf.byteLength * 8

  let s = ''

  for (let p = 0; p < max; p += 5) {
    const i = p >>> 3
    const j = p & 7

    if (j <= 3) {
      s += ALPHABET[(buf[i] >>> (3 - j)) & 0b11111]
      continue
    }

    const of = j - 3
    const h = (buf[i] << of) & 0b11111
    const l = (i >= buf.byteLength ? 0 : buf[i + 1]) >>> (8 - of)

    s += ALPHABET[h | l]
  }

  return s
}

function quintet (s, i) {
  if (i > s.length) {
    return 0
  }

  const v = s.charCodeAt(i)

  if (v < MIN || v > MAX) {
    throw Error('Invalid character in base32 input: "' + s[i] + '" at position ' + i)
  }

  const bits = REVERSE[v - MIN]

  if (bits === -1) {
    throw Error('Invalid character in base32 input: "' + s[i] + '" at position ' + i)
  }

  return bits
}
{
  "name": "z32",
  "version": "1.1.0",
  "description": "Encode & decode z-base32",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.5.3"
  },
  "devDependencies": {
    "base-x": "^4.0.0",
    "base32": "0.0.7",
    "brittle": "^3.1.3",
    "nanobench": "^3.0.0",
    "rfc4648": "^1.5.2",
    "standard": "^17.0.0"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/z32.git"
  },
  "scripts": {
    "test": "standard && brittle test.js",
    "bench": "node benchmark.js"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/z32/issues"
  },
  "homepage": "https://github.com/mafintosh/z32"
}
{
  "name": "hyper-rooms",
  "version": "0.1.5",
  "description": "Multiwriter rooms on Autobase with pluggable schemas — the substrate for hyper-issues, hyper-orgs, etc.",
  "type": "module",
  "main": "index.js",
  "scripts": {
    "test": "brittle test/*.test.js"
  },
  "dependencies": {
    "autobase": "^7.20.0",
    "b4a": "^1.6.0",
    "blind-pairing": "^2.3.1",
    "hyperbee": "^2.20.0",
    "hypercore-crypto": "^3.4.0",
    "ready-resource": "^1.1.0"
  },
  "devDependencies": {
    "@hyperswarm/testnet": "^3.1.4",
    "autobase-test-helpers": "^2.0.0",
    "brittle": "^3.0.0",
    "corestore": "^7.0.0",
    "hyperswarm": "^4.8.0"
  },
  "overrides": {
    "bare-fs": "^4.7.2"
  }
}
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const b4a = require('b4a')

// https://en.wikipedia.org/wiki/Merkle_tree#Second_preimage_attack
const LEAF_TYPE = b4a.from([0])
const PARENT_TYPE = b4a.from([1])
const ROOT_TYPE = b4a.from([2])

const HYPERCORE = b4a.from('hypercore')

exports.keyPair = function (seed) {
  // key pairs might stay around for a while, so better not to use a default slab to avoid retaining it completely
  const slab = b4a.allocUnsafeSlow(
    sodium.crypto_sign_PUBLICKEYBYTES + sodium.crypto_sign_SECRETKEYBYTES
  )
  const publicKey = slab.subarray(0, sodium.crypto_sign_PUBLICKEYBYTES)
  const secretKey = slab.subarray(sodium.crypto_sign_PUBLICKEYBYTES)

  if (seed) sodium.crypto_sign_seed_keypair(publicKey, secretKey, seed)
  else sodium.crypto_sign_keypair(publicKey, secretKey)

  return {
    publicKey,
    secretKey
  }
}

exports.validateKeyPair = function (keyPair) {
  const pk = b4a.allocUnsafe(sodium.crypto_sign_PUBLICKEYBYTES)
  sodium.crypto_sign_ed25519_sk_to_pk(pk, keyPair.secretKey)
  return b4a.equals(pk, keyPair.publicKey)
}

exports.sign = function (message, secretKey) {
  // Dedicated slab for the signature, to avoid retaining unneeded mem and for security
  const signature = b4a.allocUnsafeSlow(sodium.crypto_sign_BYTES)
  sodium.crypto_sign_detached(signature, message, secretKey)
  return signature
}

exports.verify = function (message, signature, publicKey) {
  if (signature.byteLength !== sodium.crypto_sign_BYTES) return false
  if (publicKey.byteLength !== sodium.crypto_sign_PUBLICKEYBYTES) return false
  return sodium.crypto_sign_verify_detached(signature, message, publicKey)
}

exports.encrypt = function (message, publicKey) {
  const ciphertext = b4a.alloc(message.byteLength + sodium.crypto_box_SEALBYTES)
  sodium.crypto_box_seal(ciphertext, message, publicKey)
  return ciphertext
}

exports.decrypt = function (ciphertext, keyPair) {
  if (ciphertext.byteLength < sodium.crypto_box_SEALBYTES) return null

  const plaintext = b4a.alloc(ciphertext.byteLength - sodium.crypto_box_SEALBYTES)

  if (!sodium.crypto_box_seal_open(plaintext, ciphertext, keyPair.publicKey, keyPair.secretKey)) {
    return null
  }

  return plaintext
}

exports.encryptionKeyPair = function (seed) {
  const publicKey = b4a.alloc(sodium.crypto_box_PUBLICKEYBYTES)
  const secretKey = b4a.alloc(sodium.crypto_box_SECRETKEYBYTES)

  if (seed) {
    sodium.crypto_box_seed_keypair(publicKey, secretKey, seed)
  } else {
    sodium.crypto_box_keypair(publicKey, secretKey)
  }

  return {
    publicKey,
    secretKey
  }
}

exports.data = function (data) {
  const out = b4a.allocUnsafe(32)

  sodium.crypto_generichash_batch(out, [LEAF_TYPE, c.encode(c.uint64, data.byteLength), data])

  return out
}

exports.parent = function (a, b) {
  if (a.index > b.index) {
    const tmp = a
    a = b
    b = tmp
  }

  const out = b4a.allocUnsafe(32)

  sodium.crypto_generichash_batch(out, [
    PARENT_TYPE,
    c.encode(c.uint64, a.size + b.size),
    a.hash,
    b.hash
  ])

  return out
}

exports.tree = function (roots, out) {
  const buffers = new Array(3 * roots.length + 1)
  let j = 0

  buffers[j++] = ROOT_TYPE

  for (let i = 0; i < roots.length; i++) {
    const r = roots[i]
    buffers[j++] = r.hash
    buffers[j++] = c.encode(c.uint64, r.index)
    buffers[j++] = c.encode(c.uint64, r.size)
  }

  if (!out) out = b4a.allocUnsafe(32)
  sodium.crypto_generichash_batch(out, buffers)
  return out
}

exports.hash = function (data, out) {
  if (!out) out = b4a.allocUnsafe(32)
  if (!Array.isArray(data)) data = [data]

  sodium.crypto_generichash_batch(out, data)

  return out
}

exports.randomBytes = function (n) {
  const buf = b4a.allocUnsafe(n)
  sodium.randombytes_buf(buf)
  return buf
}

exports.discoveryKey = function (key) {
  if (!key || key.byteLength !== 32) throw new Error('Must pass a 32 byte buffer')
  // Discovery keys might stay around for a while, so better not to use slab memory (for better gc)
  const digest = b4a.allocUnsafeSlow(32)
  sodium.crypto_generichash(digest, HYPERCORE, key)
  return digest
}

if (sodium.sodium_free) {
  exports.free = function (secureBuf) {
    if (secureBuf.secure) sodium.sodium_free(secureBuf)
  }
} else {
  exports.free = function () {}
}

exports.namespace = function (name, count) {
  const ids = typeof count === 'number' ? range(count) : count

  // Namespaces are long-lived, so better to use a dedicated slab
  const buf = b4a.allocUnsafeSlow(32 * ids.length)

  const list = new Array(ids.length)

  // ns is ephemeral, so default slab
  const ns = b4a.allocUnsafe(33)
  sodium.crypto_generichash(ns.subarray(0, 32), typeof name === 'string' ? b4a.from(name) : name)

  for (let i = 0; i < list.length; i++) {
    list[i] = buf.subarray(32 * i, 32 * i + 32)
    ns[32] = ids[i]
    sodium.crypto_generichash(list[i], ns)
  }

  return list
}

function range(count) {
  const arr = new Array(count)
  for (let i = 0; i < count; i++) arr[i] = i
  return arr
}
{
  "name": "hypercore-crypto",
  "version": "3.7.0",
  "description": "The crypto primitives used in hypercore, extracted into a separate module",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.6.6",
    "compact-encoding": "^3.0.0",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "brittle": "^3.5.0",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/hypercore-crypto.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/hypercore-crypto/issues"
  },
  "homepage": "https://github.com/mafintosh/hypercore-crypto"
}
module.exports = require.addon.bind(require)
{
  "name": "require-addon",
  "version": "1.2.0",
  "description": "Import native addons across JavaScript runtimes",
  "exports": {
    "./package": "./package.json",
    ".": {
      "bare": "./lib/bare.js",
      "node": "./lib/node.js",
      "default": "./lib/default.js"
    }
  },
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    },
    "url": {
      "bare": "bare-url",
      "default": "url"
    }
  },
  "files": [
    "lib"
  ],
  "scripts": {
    "test": "npm run lint && npm run test:bare && npm run test:node",
    "test:bare": "bare test.js",
    "test:node": "node test.js",
    "lint": "prettier --check .",
    "format": "prettier --write ."
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/require-addon.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/require-addon/issues"
  },
  "homepage": "https://github.com/holepunchto/require-addon#readme",
  "engines": {
    "bare": ">=1.10.0"
  },
  "dependencies": {
    "bare-addon-resolve": "^1.3.0"
  },
  "devDependencies": {
    "bare-bundle": "^1.8.1",
    "bare-bundle-evaluate": "^1.1.0",
    "bare-fs": "^4.0.0",
    "bare-path": "^3.0.0",
    "bare-url": "^2.1.0",
    "brittle": "^3.7.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
require.addon = require('require-addon')
module.exports = require.addon('.', __filename)
const assert = require('assert')
const binding = require('./binding')
const { isNode } = require('which-runtime')

const OPTIONAL = Buffer.from(new ArrayBuffer(0))

module.exports = exports = { ...binding }

// memory

exports.sodium_memzero = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  binding.sodium_memzero(buf)
}

exports.sodium_mlock = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  const res = binding.sodium_mlock(buf)

  if (res !== 0) throw new Error('memory lock failed')
}

exports.sodium_munlock = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  const res = binding.sodium_munlock(buf)

  if (res !== 0) throw new Error('memory unlock failed')
}

exports.sodium_malloc = function (size) {
  assert(size >= 0, 'invalid size')

  const buf = Buffer.from(binding.sodium_malloc(size))
  buf.secure = true
  return buf
}

exports.sodium_free = function (buf) {
  if (!buf || !buf.secure) return

  binding.sodium_free(buf.buffer)
}

exports.sodium_mprotect_noaccess = function (buf) {
  const res = binding.sodium_mprotect_noaccess(buf.buffer)

  if (res !== 0) throw new Error('failed to lock buffer')
}

exports.sodium_mprotect_readonly = function (buf) {
  const res = binding.sodium_mprotect_readonly(buf.buffer)

  if (res !== 0) throw new Error('failed to unlock buffer')
}

exports.sodium_mprotect_readwrite = function (buf) {
  const res = binding.sodium_mprotect_readwrite(buf.buffer)

  if (res !== 0) throw new Error('failed to unlock buffer')
}

// crypto_randombytes

exports.randombytes_buf = function (buffer) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')

  binding.randombytes_buf(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

exports.randombytes_buf_deterministic = function (buffer, seed) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    seed.byteLength === binding.randombytes_SEEDBYTES,
    "seed must be 'randombytes_SEEDBYTES' bytes"
  )

  binding.randombytes_buf_deterministic(
    buffer.buffer,
    buffer.byteOffset,
    buffer.byteLength,

    seed.buffer,
    seed.byteOffset,
    seed.byteLength
  )
}

// sodium_helpers

exports.sodium_memcmp = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  return binding.sodium_memcmp(a, b)
}

exports.sodium_add = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  binding.sodium_add(a, b)
}

exports.sodium_sub = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  binding.sodium_sub(a, b)
}

exports.sodium_compare = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  return binding.sodium_compare(a, b)
}

exports.sodium_is_zero = function (buffer, length) {
  if (length === undefined) length = buffer.byteLength

  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(length >= 0 && length <= buffer.byteLength, 'invalid length')

  return binding.sodium_is_zero(buffer, length)
}

exports.sodium_pad = function (buffer, unpaddedBuflen, blockSize) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(unpaddedBuflen <= buffer.byteLength, 'unpadded length cannot exceed buffer length')
  assert(blockSize <= buffer.byteLength, 'block size cannot exceed buffer length')
  assert(blockSize >= 1, 'block size must be at least 1 byte')
  assert(
    buffer.byteLength >= unpaddedBuflen + (blockSize - (unpaddedBuflen % blockSize)),
    'buf not long enough'
  )

  return binding.sodium_pad(buffer, unpaddedBuflen, blockSize)
}

exports.sodium_unpad = function (buffer, paddedBuflen, blockSize) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(paddedBuflen <= buffer.byteLength, 'unpadded length cannot exceed buffer length')
  assert(blockSize <= buffer.byteLength, 'block size cannot exceed buffer length')
  assert(blockSize >= 1, 'block size must be at least 1 byte')

  return binding.sodium_unpad(buffer, paddedBuflen, blockSize)
}

// crypto_sign

exports.crypto_sign_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )
  assert(
    seed.byteLength === binding.crypto_sign_SEEDBYTES,
    "seed must be 'crypto_sign_SEEDBYTES' bytes"
  )

  const res = binding.crypto_sign_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign = function (sm, m, sk) {
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sm.byteLength === binding.crypto_sign_BYTES + m.byteLength,
    "sm must be 'm.byteLength + crypto_sign_BYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign(sm, m, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_open = function (m, sm, pk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sm.byteLength >= binding.crypto_sign_BYTES,
    "sm must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    m.byteLength === sm.byteLength - binding.crypto_sign_BYTES,
    "m must be 'sm.byteLength - crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_open(m, sm, pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_open = function (m, sm, pk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sm.byteLength >= binding.crypto_sign_BYTES,
    "sm must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    m.byteLength === sm.byteLength - binding.crypto_sign_BYTES,
    "m must be 'sm.byteLength - crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  return binding.crypto_sign_open(m, sm, pk)
}

exports.crypto_sign_detached = function (sig, m, sk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(sig.byteLength === binding.crypto_sign_BYTES, "sig must be 'crypto_sign_BYTES' bytes")
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_detached(sig, m, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_verify_detached = function (sig, m, pk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sig.byteLength >= binding.crypto_sign_BYTES,
    "sig must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  return binding.crypto_sign_verify_detached(
    sig.buffer,
    sig.byteOffset,
    sig.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    pk.buffer,
    pk.byteOffset,
    pk.byteLength
  )
}

exports.crypto_sign_ed25519_sk_to_pk = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_sk_to_pk(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_ed25519_pk_to_curve25519 = function (x25519pk, ed25519pk) {
  assert(ArrayBuffer.isView(x25519pk), 'x25519pk must be a typed array')
  assert(ArrayBuffer.isView(ed25519pk), 'ed25519pk must be a typed array')
  assert(
    x25519pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "x25519pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    ed25519pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "ed25519pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_pk_to_curve25519(x25519pk, ed25519pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_ed25519_sk_to_curve25519 = function (x25519sk, ed25519sk) {
  assert(ArrayBuffer.isView(x25519sk), 'x25519sk must be a typed array')
  assert(ArrayBuffer.isView(ed25519sk), 'ed25519sk must be a typed array')
  assert(
    x25519sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "x25519sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const edLen = ed25519sk.byteLength

  assert(
    edLen === binding.crypto_sign_SECRETKEYBYTES || edLen === binding.crypto_box_SECRETKEYBYTES,
    "ed25519sk must be 'crypto_sign_SECRETKEYBYTES' or 'crypto_sign_SECRETKEYBYTES - crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_sk_to_curve25519(x25519sk, ed25519sk)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_box

exports.crypto_box_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    seed.byteLength === binding.crypto_box_SEEDBYTES,
    "seed must be 'crypto_box_SEEDBYTES' bytes"
  )

  const res = binding.crypto_box_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_easy = function (c, m, n, pk, sk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength === m.byteLength + exports.crypto_box_MACBYTES,
    "c must be 'm.byteLength + crypto_box_MACBYTES' bytes"
  )
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_easy(c, m, n, pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_detached = function (c, mac, m, n, pk, sk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(mac.byteLength === exports.crypto_box_MACBYTES, "mac must be 'crypto_box_MACBYTES' bytes")
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_detached(c, mac, m, n, pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_open_easy = function (m, c, n, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength >= exports.crypto_box_MACBYTES,
    "c must be at least 'crypto_box_MACBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - exports.crypto_box_MACBYTES,
    "m must be 'c.byteLength - crypto_box_MACBYTES' bytes"
  )
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_open_easy(m, c, n, pk, sk)
}

exports.crypto_box_open_detached = function (m, c, mac, n, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(mac.byteLength === exports.crypto_box_MACBYTES, "mac must be 'crypto_box_MACBYTES' bytes")
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_open_detached(m, c, mac, n, pk, sk)
}

exports.crypto_box_seal = function (c, m, pk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    c.byteLength === m.byteLength + exports.crypto_box_SEALBYTES,
    "c must be 'm.byteLength + crypto_box_SEALBYTES' bytes"
  )
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_box_seal(c, m, pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_seal_open = function (m, c, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength >= exports.crypto_box_SEALBYTES,
    "c must be at least 'crypto_box_SEALBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - exports.crypto_box_SEALBYTES,
    "m must be 'c.byteLength - crypto_box_SEALBYTES' bytes"
  )
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_seal_open(
    m.buffer,
    m.byteOffset,
    m.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    pk.buffer,
    pk.byteOffset,
    pk.byteLength,

    sk.buffer,
    sk.byteOffset,
    sk.byteLength
  )
}

// crypto_secretbox

exports.crypto_secretbox_easy = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_secretbox_MACBYTES,
    "c must be 'm.byteLength + crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretbox_easy(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretbox_open_easy = function (m, c, n, k) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    c.byteLength >= binding.crypto_secretbox_MACBYTES,
    "c must be at least 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - binding.crypto_secretbox_MACBYTES,
    "m must be 'c.byteLength - crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  return binding.crypto_secretbox_open_easy(m, c, n, k)
}

exports.crypto_secretbox_detached = function (c, mac, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    mac.byteLength === binding.crypto_secretbox_MACBYTES,
    "mac must be 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretbox_detached(c, mac, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretbox_open_detached = function (m, c, mac, n, k) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(
    mac.byteLength === binding.crypto_secretbox_MACBYTES,
    "mac must be 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  return binding.crypto_secretbox_open_detached(m, c, mac, n, k)
}

// crypto_generichash

exports.crypto_generichash = function (output, input, key) {
  if (!key) key = OPTIONAL

  assert(ArrayBuffer.isView(output), 'output must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    output.byteLength >= binding.crypto_generichash_BYTES_MIN &&
      output.byteLength <= binding.crypto_generichash_BYTES_MAX,
    'output must be between crypto_generichash_BYTES_MIN and crypto_generichash_BYTES_MAX bytes'
  )

  if (key !== OPTIONAL) {
    assert(ArrayBuffer.isView(key), 'key must be a typed array')
    assert(
      key.byteLength >= binding.crypto_generichash_KEYBYTES_MIN &&
        key.byteLength <= binding.crypto_generichash_KEYBYTES_MAX,
      'key must be between crypto_generichash_KEYBYTES_MIN and crypto_generichash_KEYBYTES_MAX bytes'
    )
  }

  const res = binding.crypto_generichash(
    output.buffer,
    output.byteOffset,
    output.byteLength,

    input.buffer,
    input.byteOffset,
    input.byteLength,

    key.buffer,
    key.byteOffset,
    key.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_batch = function (output, batch, key) {
  assert(ArrayBuffer.isView(output), 'output must be a typed array')

  if (isNode || batch.length < 4) {
    const res = binding.crypto_generichash_batch(output, batch, !!key, key || OPTIONAL)
    if (res !== 0) throw new Error('status: ' + res)
  } else {
    const state = Buffer.alloc(binding.crypto_generichash_STATEBYTES)

    exports.crypto_generichash_init(state, key, output.byteLength)

    for (const buf of batch) {
      exports.crypto_generichash_update(state, buf)
    }

    exports.crypto_generichash_final(state, output)
  }
}

exports.crypto_generichash_keygen = function (key) {
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(
    key.byteLength === binding.crypto_generichash_KEYBYTES,
    "key must be 'crypto_generichash_KEYBYTES' bytes"
  )

  const res = binding.crypto_generichash_keygen(key.buffer, key.byteOffset, key.byteLength)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_init = function (state, key, outputLength) {
  if (!key) key = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_init(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    key.buffer,
    key.byteOffset,
    key.byteLength,

    outputLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_update(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    input.buffer,
    input.byteOffset,
    input.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_final = function (state, output) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(output), 'output must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_final(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    output.buffer,
    output.byteOffset,
    output.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

// secretstream

exports.crypto_secretstream_xchacha20poly1305_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  binding.crypto_secretstream_xchacha20poly1305_keygen(k.buffer, k.byteOffset, k.byteLength)
}

exports.crypto_secretstream_xchacha20poly1305_init_push = function (state, header, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(header), 'header must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    header.byteLength === binding.crypto_secretstream_xchacha20poly1305_HEADERBYTES,
    "header must be 'crypto_secretstream_xchacha20poly1305_HEADERBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_init_push(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    header.buffer,
    header.byteOffset,
    header.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretstream_xchacha20poly1305_init_pull = function (state, header, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(header), 'header must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    header.byteLength === binding.crypto_secretstream_xchacha20poly1305_HEADERBYTES,
    "header must be 'crypto_secretstream_xchacha20poly1305_HEADERBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_init_pull(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    header.buffer,
    header.byteOffset,
    header.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretstream_xchacha20poly1305_push = function (state, c, m, ad, tag) {
  if (!ad) ad = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    c.byteLength === m.byteLength + binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "c must be 'm.byteLength + crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_push(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    ad.buffer,
    ad.byteOffset,
    ad.byteLength,

    tag
  )

  if (res < 0) throw new Error('push failed')

  return res
}

exports.crypto_secretstream_xchacha20poly1305_pull = function (state, m, tag, c, ad) {
  if (!ad) ad = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(tag), 'tag must be a typed array')
  assert(tag.byteLength === 1, 'tag must be 1 byte')

  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    c.byteLength >= binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "c must be at least 'crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "m must be 'c.byteLength - crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_pull(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    tag.buffer,
    tag.byteOffset,
    tag.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    ad.buffer,
    ad.byteOffset,
    ad.byteLength
  )

  if (res < 0) throw new Error('pull failed')

  return res
}

exports.crypto_secretstream_xchacha20poly1305_rekey = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )

  binding.crypto_secretstream_xchacha20poly1305_rekey(
    state.buffer,
    state.byteOffset,
    state.byteLength
  )
}

// crypto_stream

exports.crypto_stream = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xor(
    c.buffer,
    c.byteOffset,
    c.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    n.buffer,
    n.byteOffset,
    n.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_auth

exports.crypto_auth = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(out.byteLength === binding.crypto_auth_BYTES, "out must be 'crypto_auth_BYTES' bytes")
  assert(k.byteLength === binding.crypto_auth_KEYBYTES, "k must be 'crypto_auth_KEYBYTES' bytes")

  const res = binding.crypto_auth(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_auth_verify = function (h, input, k) {
  assert(ArrayBuffer.isView(h), 'h must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(h.byteLength === binding.crypto_auth_BYTES, "h must be 'crypto_auth_BYTES' bytes")
  assert(k.byteLength === binding.crypto_auth_KEYBYTES, "k must be 'crypto_auth_KEYBYTES' bytes")

  return binding.crypto_auth_verify(h, input, k)
}

// crypto_onetimeauth

exports.crypto_onetimeauth = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    out.byteLength === binding.crypto_onetimeauth_BYTES,
    "out must be 'crypto_onetimeauth_BYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_init = function (state, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_init(state, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )
  assert(
    out.byteLength === binding.crypto_onetimeauth_BYTES,
    "out must be 'crypto_onetimeauth_BYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_verify = function (h, input, k) {
  assert(ArrayBuffer.isView(h), 'h must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    h.byteLength === binding.crypto_onetimeauth_BYTES,
    "h must be 'crypto_onetimeauth_BYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  return binding.crypto_onetimeauth_verify(h, input, k)
}

// crypto_pwhash

exports.crypto_pwhash = function (out, passwd, salt, opslimit, memlimit, alg) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_BYTES_MIN,
    "out must be at least 'crypto_pwhash_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_BYTES_MAX,
    "out must be at most 'crypto_pwhash_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_SALTBYTES,
    "salt must be 'crypto_pwhash_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )
  assert(alg >= 1 && alg <= 2, 'alg must be either Argon2i 1.3 or Argon2id 1.3')

  const res = binding.crypto_pwhash(out, passwd, salt, opslimit, memlimit, alg)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_async = function (
  out,
  passwd,
  salt,
  opslimit,
  memlimit,
  alg,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_BYTES_MIN,
    "out must be at least 'crypto_pwhash_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_BYTES_MAX,
    "out must be at most 'crypto_pwhash_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_SALTBYTES,
    "salt must be 'crypto_pwhash_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )
  assert(alg >= 1 && alg <= 2, 'alg must be either Argon2i 1.3 or Argon2id 1.3')

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    opslimit,
    memlimit,
    alg,

    done
  )

  return promise
}

exports.crypto_pwhash_str = function (out, passwd, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_STRBYTES,
    "out must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(typeof opslimit === 'number', 'opslimit must be a number')
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(typeof memlimit === 'number', 'memlimit must be a number')
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_str(out, passwd, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_str_async = function (out, passwd, opslimit, memlimit, callback = undefined) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_STRBYTES,
    "out must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(typeof opslimit === 'number', 'opslimit must be a number')
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(typeof memlimit === 'number', 'memlimit must be a number')
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_str_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_str_verify = function (str, passwd) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )

  return binding.crypto_pwhash_str_verify(str, passwd)
}

exports.crypto_pwhash_str_verify_async = function (str, passwd, callback = undefined) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  const [done, promise] = checkStatus(callback, true)

  binding.crypto_pwhash_str_verify_async(
    str.buffer,
    str.byteOffset,
    str.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    done
  )

  return promise
}

exports.crypto_pwhash_str_needs_rehash = function (str, opslimit, memlimit) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  return binding.crypto_pwhash_str_needs_rehash(str, opslimit, memlimit)
}

exports.crypto_pwhash_scryptsalsa208sha256 = function (out, passwd, salt, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MIN,
    "out must be at least 'crypto_pwhash_scryptsalsa208sha256_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MAX,
    "out must be at most 'crypto_pwhash_scryptsalsa208sha256_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_SALTBYTES,
    "salt must be 'crypto_pwhash_scryptsalsa208sha256_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_scryptsalsa208sha256(out, passwd, salt, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_scryptsalsa208sha256_async = function (
  out,
  passwd,
  salt,
  opslimit,
  memlimit,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MIN,
    "out must be at least 'crypto_pwhash_scryptsalsa208sha256_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MAX,
    "out must be at most 'crypto_pwhash_scryptsalsa208sha256_BYTES_MAX' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    salt.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_SALTBYTES,
    "salt must be 'crypto_pwhash_scryptsalsa208sha256_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_scryptsalsa208sha256_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str_async = function (
  out,
  passwd,
  opslimit,
  memlimit,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "out must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_scryptsalsa208sha256_str_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str = function (out, passwd, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "out must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_scryptsalsa208sha256_str(out, passwd, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_scryptsalsa208sha256_str_verify_async = function (
  str,
  passwd,
  callback = undefined
) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  const [done, promise] = checkStatus(callback, true)

  binding.crypto_pwhash_scryptsalsa208sha256_str_verify_async(
    str.buffer,
    str.byteOffset,
    str.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str_verify = function (str, passwd) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  return binding.crypto_pwhash_scryptsalsa208sha256_str_verify(str, passwd)
}

exports.crypto_pwhash_scryptsalsa208sha256_str_needs_rehash = function (str, opslimit, memlimit) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  return binding.crypto_pwhash_scryptsalsa208sha256_str_needs_rehash(str, opslimit, memlimit)
}

// crypto_kx

exports.crypto_kx_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "pk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "sk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    pk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "pk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "sk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    seed.byteLength === binding.crypto_kx_SEEDBYTES,
    "seed must be 'crypto_kx_SEEDBYTES' bytes"
  )

  const res = binding.crypto_kx_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_client_session_keys = function (rx, tx, clientPk, clientSk, serverPk) {
  if (!rx) rx = undefined
  if (!tx) tx = undefined

  assert(rx || tx, 'at least one session key must be specified')

  if (rx) {
    assert(ArrayBuffer.isView(rx), 'rx must be a typed array')
    assert(
      rx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "rx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  if (tx) {
    assert(ArrayBuffer.isView(tx), 'tx must be a typed array')
    assert(
      tx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "tx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  assert(ArrayBuffer.isView(clientPk), 'clientPk must be a typed array')
  assert(ArrayBuffer.isView(clientSk), 'clientSk must be a typed array')
  assert(ArrayBuffer.isView(serverPk), 'serverPk must be a typed array')
  assert(
    clientPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "clientPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    clientSk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "clientSk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    serverPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "serverPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_client_session_keys(rx, tx, clientPk, clientSk, serverPk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_server_session_keys = function (rx, tx, serverPk, serverSk, clientPk) {
  if (!rx) rx = undefined
  if (!tx) tx = undefined

  assert(rx || tx, 'at least one session key must be specified')

  if (rx) {
    assert(ArrayBuffer.isView(rx), 'rx must be a typed array')
    assert(
      rx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "rx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  if (tx) {
    assert(ArrayBuffer.isView(tx), 'tx must be a typed array')
    assert(
      tx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "tx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  assert(ArrayBuffer.isView(serverPk), 'serverPk must be a typed array')
  assert(ArrayBuffer.isView(serverSk), 'serverSk must be a typed array')
  assert(ArrayBuffer.isView(clientPk), 'clientPk must be a typed array')
  assert(
    serverPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "serverPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    serverSk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "serverSk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    clientPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "clientPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_server_session_keys(rx, tx, serverPk, serverSk, clientPk)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_scalarmult

exports.crypto_scalarmult_base = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_BYTES,
    "q must be 'crypto_scalarmult_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_SCALARBYTES,
    "n must be 'crypto_scalarmult_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_base(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_BYTES,
    "q must be 'crypto_scalarmult_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_SCALARBYTES,
    "n must be 'crypto_scalarmult_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_BYTES,
    "p must be 'crypto_scalarmult_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_base = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_base(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519 = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "p must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_is_valid_point = function (p) {
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )

  return binding.crypto_core_ed25519_is_valid_point(p)
}

exports.crypto_core_ed25519_from_uniform = function (p, r) {
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_UNIFORMBYTES,
    "r must be 'crypto_core_ed25519_UNIFORMBYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_from_uniform(p, r)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_base_noclamp = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_base_noclamp(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_noclamp = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "p must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_noclamp(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_core

exports.crypto_core_ed25519_add = function (r, p, q) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_BYTES,
    "r must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_core_ed25519_BYTES,
    "q must be 'crypto_core_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_add(r, p, q)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_sub = function (r, p, q) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_BYTES,
    "r must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_core_ed25519_BYTES,
    "q must be 'crypto_core_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_sub(r, p, q)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_scalar_random = function (r) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "r must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_random(r)
}

exports.crypto_core_ed25519_scalar_reduce = function (r, s) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "r must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_NONREDUCEDSCALARBYTES,
    "s must be 'crypto_core_ed25519_NONREDUCEDSCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_reduce(r, s)
}

exports.crypto_core_ed25519_scalar_invert = function (recip, s) {
  assert(ArrayBuffer.isView(recip), 'recip must be a typed array')
  assert(
    recip.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "recip must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_invert(recip, s)
}

exports.crypto_core_ed25519_scalar_negate = function (neg, s) {
  assert(ArrayBuffer.isView(neg), 'neg must be a typed array')
  assert(
    neg.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "neg must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_negate(neg, s)
}

exports.crypto_core_ed25519_scalar_complement = function (comp, s) {
  assert(ArrayBuffer.isView(comp), 'comp must be a typed array')
  assert(
    comp.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "comp must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_complement(comp, s)
}

exports.crypto_core_ed25519_scalar_add = function (z, x, y) {
  assert(ArrayBuffer.isView(z), 'z must be a typed array')
  assert(
    z.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "z must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(x), 'x must be a typed array')
  assert(
    x.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "x must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(y), 'y must be a typed array')
  assert(
    y.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "y must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_add(z, x, y)
}

exports.crypto_core_ed25519_scalar_sub = function (z, x, y) {
  assert(ArrayBuffer.isView(z), 'z must be a typed array')
  assert(
    z.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "z must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(x), 'x must be a typed array')
  assert(
    x.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "x must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(y), 'y must be a typed array')
  assert(
    y.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "y must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_sub(z, x, y)
}

// crypto_shorthash

exports.crypto_shorthash = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_shorthash_BYTES,
    "out must be 'crypto_shorthash_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_shorthash_KEYBYTES,
    "k must be 'crypto_shorthash_KEYBYTES' bytes"
  )

  const res = binding.crypto_shorthash(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_kdf

exports.crypto_kdf_keygen = function (key) {
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(key.byteLength === binding.crypto_kdf_KEYBYTES, "key must be 'crypto_kdf_KEYBYTES' bytes")

  binding.crypto_kdf_keygen(key)
}

exports.crypto_kdf_derive_from_key = function (subkey, subkeyId, ctx, key) {
  assert(ArrayBuffer.isView(subkey), 'subkey must be a typed array')
  assert(
    subkey.byteLength >= binding.crypto_kdf_BYTES_MIN,
    "subkey must be at least 'crypto_kdf_BYTES_MIN' bytes"
  )
  assert(
    subkey.byteLength <= binding.crypto_kdf_BYTES_MAX,
    "subkey must be at most 'crypto_kdf_BYTES_MAX' bytes"
  )
  assert(ArrayBuffer.isView(ctx), 'ctx must be a typed array')
  assert(
    ctx.byteLength === binding.crypto_kdf_CONTEXTBYTES,
    "ctx must be 'crypto_kdf_CONTEXTBYTES' bytes"
  )
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(key.byteLength === binding.crypto_kdf_KEYBYTES, "key must be 'crypto_kdf_KEYBYTES' bytes")

  const res = binding.crypto_kdf_derive_from_key(subkey, subkeyId, ctx, key)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_hash

exports.crypto_hash = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(out.byteLength === binding.crypto_hash_BYTES, "out must be 'crypto_hash_BYTES' bytes")

  const res = binding.crypto_hash(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256 = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha256_BYTES,
    "out must be 'crypto_hash_sha256_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha256(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_init = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_init(state)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha256_BYTES,
    "out must be 'crypto_hash_sha256_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512 = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha512_BYTES,
    "out must be 'crypto_hash_sha512_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha512(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_init = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_init(state)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha512_BYTES,
    "out must be 'crypto_hash_sha512_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_aead

exports.crypto_aead_xchacha20poly1305_ietf_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  binding.crypto_aead_xchacha20poly1305_ietf_keygen(k)
}

exports.crypto_aead_xchacha20poly1305_ietf_encrypt = function (c, m, ad, nsec, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "c must be 'm.byteLength + crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(c.byteLength <= 0xffffffff, 'c.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_encrypt(c, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_decrypt = function (m, nsec, c, ad, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "m must be 'c.byteLength - crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(m.byteLength <= 0xffffffff, 'm.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_decrypt(m, c, ad, npub, k)

  if (res < 0) throw new Error('could not verify data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_encrypt_detached = function (
  c,
  mac,
  m,
  ad,
  nsec,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_encrypt_detached(c, mac, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_decrypt_detached = function (
  m,
  nsec,
  c,
  mac,
  ad,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_decrypt_detached(m, c, mac, ad, npub, k)

  if (res !== 0) throw new Error('could not verify data')
}

exports.crypto_aead_chacha20poly1305_ietf_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  binding.crypto_aead_chacha20poly1305_ietf_keygen(k)
}

exports.crypto_aead_chacha20poly1305_ietf_encrypt = function (c, m, ad, nsec, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "c must be 'm.byteLength + crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(c.byteLength <= 0xffffffff, 'c.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_encrypt(c, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_decrypt = function (m, nsec, c, ad, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "m must be 'c.byteLength - crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(m.byteLength <= 0xffffffff, 'm.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_decrypt(m, c, ad, npub, k)

  if (res < 0) throw new Error('could not verify data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_encrypt_detached = function (
  c,
  mac,
  m,
  ad,
  nsec,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_encrypt_detached(c, mac, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_decrypt_detached = function (
  m,
  nsec,
  c,
  mac,
  ad,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_decrypt_detached(m, c, mac, ad, npub, k)

  if (res !== 0) throw new Error('could not verify data')
}

// crypto_stream

exports.crypto_stream_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  binding.crypto_stream_xor_wrap_init(state, n, k)
}

exports.crypto_stream_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_xor_wrap_update(state, c, m)
}

exports.crypto_stream_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_xor_wrap_final(state)
}

exports.crypto_stream_chacha20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  binding.crypto_stream_chacha20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_chacha20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_chacha20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_chacha20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_chacha20_xor_wrap_final(state)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  binding.crypto_stream_chacha20_ietf_xor_wrap_init(state, n, k)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_chacha20_ietf_xor_wrap_update(state, c, m)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_chacha20_ietf_xor_wrap_final(state)
}

exports.crypto_stream_xchacha20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  binding.crypto_stream_xchacha20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_xchacha20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_xchacha20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_xchacha20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_xchacha20_xor_wrap_final(state)
}

exports.crypto_stream_salsa20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  binding.crypto_stream_salsa20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_salsa20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_salsa20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_salsa20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_salsa20_xor_wrap_final(state)
}

// experimental

exports.extension_tweak_ed25519_base = function (n, p, ns) {
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.extension_tweak_ed25519_BYTES,
    "p must be 'extension_tweak_ed25519_BYTES' bytes"
  )

  binding.extension_tweak_ed25519_base(n, p, ns)
}

exports.extension_tweak_ed25519_sign_detached = function (sig, m, scalar, pk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(sig.byteLength === binding.crypto_sign_BYTES, "sig must be 'crypto_sign_BYTES' bytes")
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  if (pk) {
    assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
    assert(
      pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
      "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
    )
  }

  const res = binding.extension_tweak_ed25519_sign_detached(sig, m, scalar, pk)

  if (res !== 0) throw new Error('failed to compute signature')
}

exports.extension_tweak_ed25519_sk_to_scalar = function (n, sk) {
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  binding.extension_tweak_ed25519_sk_to_scalar(n, sk)
}

exports.extension_tweak_ed25519_scalar = function (scalarOut, scalar, ns) {
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_scalar(scalarOut, scalar, ns)
}

exports.extension_tweak_ed25519_pk = function (tpk, pk, ns) {
  assert(ArrayBuffer.isView(tpk), 'tpk must be a typed array')
  assert(
    tpk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "tpk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_pk(tpk, pk, ns)

  if (res !== 0) throw new Error('failed to tweak public key')
}

exports.extension_tweak_ed25519_keypair = function (pk, scalarOut, scalarIn, ns) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.extension_tweak_ed25519_BYTES,
    "pk must be 'extension_tweak_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarIn), 'scalarIn must be a typed array')
  assert(
    scalarIn.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarIn must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_keypair(pk, scalarOut, scalarIn, ns)
}

exports.extension_tweak_ed25519_scalar_add = function (scalarOut, scalar, n) {
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_scalar_add(scalarOut, scalar, n)
}

exports.extension_tweak_ed25519_pk_add = function (tpk, pk, p) {
  assert(ArrayBuffer.isView(tpk), 'tpk must be a typed array')
  assert(
    tpk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "tpk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "p must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_pk_add(tpk, pk, p)

  if (res !== 0) throw new Error('failed to add tweak to public key')
}

exports.extension_tweak_ed25519_keypair_add = function (pk, scalarOut, scalarIn, tweak) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.extension_tweak_ed25519_BYTES,
    "pk must be 'extension_tweak_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarIn), 'scalarIn must be a typed array')
  assert(
    scalarIn.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarIn must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(tweak), 'tweak must be a typed array')
  assert(
    tweak.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "tweak must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_keypair_add(pk, scalarOut, scalarIn, tweak)

  if (res !== 0) throw new Error('failed to add tweak to keypair')
}

exports.extension_pbkdf2_sha512_async = function (out, passwd, salt, iter, outlen, callback) {
  assert(
    iter >= binding.extension_pbkdf2_sha512_ITERATIONS_MIN,
    "iter must be at least 'extension_pbkdf2_sha512_ITERATIONS_MIN'"
  )
  assert(
    outlen <= binding.extension_pbkdf2_sha512_BYTES_MAX,
    "outlen must be at most 'extension_pbkdf2_sha512_BYTES_MAX'"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(out.byteLength >= outlen, "out must be at least 'outlen' bytes")
  assert(out.byteLength > 0, 'out must not be empty')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(salt.byteLength > 0, 'salt must not be empty')

  const [done, promise] = checkStatus(callback)

  binding.extension_pbkdf2_sha512_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    iter,
    outlen,

    done
  )

  return promise
}

exports.extension_pbkdf2_sha512 = function (out, passwd, salt, iter, outlen) {
  assert(
    iter >= binding.extension_pbkdf2_sha512_ITERATIONS_MIN,
    "iter must be at least 'extension_pbkdf2_sha512_ITERATIONS_MIN'"
  )
  assert(
    outlen <= binding.extension_pbkdf2_sha512_BYTES_MAX,
    "outlen must be at most 'extension_pbkdf2_sha512_BYTES_MAX'"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(out.byteLength >= outlen, "out must be at least 'outlen' bytes")
  assert(out.byteLength > 0, 'out must not be empty')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(salt.byteLength > 0, 'salt must not be empty')

  const res = binding.extension_pbkdf2_sha512(out, passwd, salt, iter, outlen)

  if (res !== 0) throw new Error('failed to add tweak to public key')
}

function checkStatus(callback, booleanResult = false) {
  let done, promise

  if (typeof callback === 'function') {
    done = function (status) {
      if (booleanResult) callback(null, status === 0)
      else if (status === 0) callback(null)
      else callback(new Error('status: ' + status))
    }
  } else {
    promise = new Promise(function (resolve, reject) {
      done = function (status) {
        if (booleanResult) resolve(status === 0)
        else if (status === 0) resolve()
        else reject(new Error('status: ' + status))
      }
    })
  }

  return [done, promise]
}
{
  "name": "sodium-native",
  "version": "5.1.0",
  "description": "Low level bindings for libsodium",
  "main": "index.js",
  "files": [
    "index.js",
    "binding.cc",
    "binding.js",
    "extensions",
    "prebuilds",
    "CMakeLists.txt"
  ],
  "imports": {
    "assert": {
      "bare": "bare-assert",
      "node": "assert"
    }
  },
  "addon": true,
  "dependencies": {
    "bare-assert": "^1.2.0",
    "require-addon": "^1.1.0",
    "which-runtime": "^1.2.1"
  },
  "devDependencies": {
    "bare-compat-napi": "^1.3.5",
    "brittle": "^3.16.2",
    "cmake-bare": "^1.6.1",
    "cmake-fetch": "^1.4.3",
    "cmake-napi": "^1.2.1",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "test": "prettier . --check && npm run test:node && npm run test:bare",
    "test:node": "node test/all.js",
    "test:bare": "bare test/all.js"
  },
  "standard": {
    "ignore": [
      "/test/fixtures/*.js"
    ]
  },
  "engines": {
    "bare": ">=1.16.0"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sodium-native.git"
  },
  "contributors": [
    "Emil Bay <github@tixz.dk> (http://bayes.dk)",
    "Mathias Buus <mathiasbuus@gmail.com> (https://mafinto.sh)",
    "Christophe Diederichs <chm-diederichs@hyperdivision.dk>"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/sodium-native/issues"
  },
  "homepage": "https://github.com/holepunchto/sodium-native"
}
module.exports = require('sodium-native')
{
  "name": "sodium-universal",
  "version": "5.0.1",
  "description": "Universal wrapper for sodium-javascript and sodium-native working in Node.js and the Browser",
  "main": "index.js",
  "dependencies": {
    "sodium-native": "^5.0.1"
  },
  "peerDependencies": {
    "sodium-javascript": "~0.8.0"
  },
  "peerDependenciesMeta": {
    "sodium-javascript": {
      "optional": true
    }
  },
  "scripts": {
    "prepublish": "./build-scripts/generate.js"
  },
  "browser": {
    "sodium-native": "sodium-javascript"
  },
  "browserify": {
    "transform": [
      "./build-scripts/transform.js"
    ]
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sodium-universal.git"
  },
  "keywords": [
    "libsodium",
    "sodium",
    "sodium-native",
    "sodium-javascript",
    "browserify"
  ],
  "contributors": [
    "Emil Bay <github@tixz.dk> (http://bayes.dk)",
    "Mathias Buus <mathiasbuus@gmail.com> (https://mafinto.sh)",
    "Christophe Diederichs <chm-diederichs@hyperdivision.dk>"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/sodium-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/sodium-universal#readme"
}
const { runtime, platform, arch, version } =
  typeof Bare !== 'undefined'
    ? {
        runtime: 'bare',
        platform: global.Bare.platform,
        arch: global.Bare.arch,
        version: global.Bare.version
      }
    : typeof process !== 'undefined'
      ? {
          runtime: 'node',
          platform: global.process.platform,
          arch: global.process.arch,
          version: global.process.version
        }
      : typeof Window !== 'undefined'
        ? { runtime: 'browser', platform: 'unknown', arch: 'unknown', version: 'unknown' }
        : { runtime: 'unknown', platform: 'unknown', arch: 'unknown', version: 'unknown' }

exports.runtime = runtime
exports.version = version
exports.platform = platform
exports.arch = arch
exports.isBare = runtime === 'bare'
exports.isBareKit = exports.isBare && typeof BareKit !== 'undefined'
exports.isPear = typeof Pear !== 'undefined'
exports.isNode = runtime === 'node'
exports.isBrowser = runtime === 'browser'
exports.isWindows = platform === 'win32'
exports.isLinux = platform === 'linux'
exports.isMac = platform === 'darwin'
exports.isIOS = platform === 'ios' || platform === 'ios-simulator'
exports.isAndroid = platform === 'android'
exports.isElectron = typeof process !== 'undefined' && !!global.process.versions?.electron
exports.isElectronRenderer = exports.isElectron && global.process.type === 'renderer'
exports.isElectronWorker = exports.isElectron && global.process.type === 'worker'
{
  "name": "which-runtime",
  "version": "1.4.0",
  "description": "Detect if you are in Bare or Node and which os etc",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte .",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/which-runtime.git"
  },
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/which-runtime/issues"
  },
  "homepage": "https://github.com/holepunchto/which-runtime",
  "devDependencies": {
    "brittle": "^3.0.0",
    "lunte": "^1.4.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
{
  "name": "favela-community",
  "version": "0.1.5",
  "description": "Co-owned, plaintext community rooms for Favela — membership + moderation on a hyper-rooms Autobase. Read KEYLESSLY by the gateway (favela-web); WRITTEN by mods (hpp / full-node / CLI). One community protocol, shared across surfaces.",
  "type": "module",
  "main": "index.js",
  "bin": {
    "favela-community": "bin/favela-community.js"
  },
  "scripts": {
    "test": "bare test/community-room.test.mjs && bare test/feed-registry.test.mjs && bare test/cli.test.mjs && bare test/discovery.test.mjs",
    "e2e": "bare test/live-swarm-e2e.mjs"
  },
  "dependencies": {
    "hyper-rooms": "file:../hyper-rooms",
    "autobase": "^7.28.0",
    "corestore": "^7.4.0",
    "hyperswarm": "^4.11.0",
    "bare-process": "^4.0.0",
    "bare-path": "^3.0.0",
    "bare-fs": "^4.0.0",
    "b4a": "^1.8.1"
  }
}
const fs = require('fs')
const fsx = require('fs-native-extensions')
const onexit = require('resource-on-exit')
const ReadyResource = require('ready-resource')

module.exports = class FDLock extends ReadyResource {
  constructor(fd, opts = {}) {
    const { wait = false } = opts

    super()

    this._fd = fd
    this._wait = wait
    this._locked = false

    onexit.add(this, closeSync)
  }

  get locked() {
    return this._locked
  }

  async _open() {
    try {
      await this._resume()
    } catch (err) {
      onexit.remove(this)
      await close(this)
      throw err
    }
  }

  async _close() {
    onexit.remove(this)
    await close(this)
    this._locked = false
  }

  transfer() {
    const fd = this._fd
    if (fd === -1) throw new Error('Lock has already been transferred')
    this._fd = -1
    onexit.remove(this)
    return fd
  }

  async suspend() {
    if (!this.opened) await this.ready()
    return this._suspend()
  }

  async _suspend() {
    if (this._fd === -1 || this._locked === false) return
    fsx.unlock(this._fd)
    this._locked = false
  }

  async resume() {
    if (!this.opened) await this.ready()
    return this._resume()
  }

  async _resume() {
    if (this._fd === -1 || this._locked === true) return
    if (this._wait) await fsx.waitForLock(this._fd)
    else if (!fsx.tryLock(this._fd)) {
      throw new Error('File descriptor could not be locked')
    }
    this._locked = true
  }
}

function close(lock) {
  const fd = lock._fd
  if (fd === -1) return
  lock._fd = -1
  return new Promise((resolve) => fs.close(fd, () => resolve()))
}

function closeSync(lock) {
  const fd = lock._fd
  if (fd === -1) return
  lock._fd = -1
  lock._locked = false
  try {
    fs.closeSync(fd)
  } catch {}
}
{
  "name": "fd-lock",
  "version": "2.2.0",
  "description": "Stateful file descriptor locks for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": "./index.js"
  },
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    }
  },
  "files": [
    "index.js"
  ],
  "scripts": {
    "test": "npm run lint && npm run test:bare && npm run test:node",
    "test:bare": "bare test.js",
    "test:node": "node test.js",
    "lint": "prettier --check .",
    "format": "prettier --write ."
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/fd-lock.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/fd-lock/issues"
  },
  "homepage": "https://github.com/holepunchto/fd-lock#readme",
  "dependencies": {
    "bare-fs": "^4.5.0",
    "fs-native-extensions": "^1.4.4",
    "ready-resource": "^1.2.0",
    "resource-on-exit": "^1.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
exports.fullRoots = function (index, result) {
  if (index & 1) throw new Error('You can only look up roots for depth(0) blocks')
  if (!result) result = []

  index /= 2

  let offset = 0
  let factor = 1

  while (true) {
    if (!index) return result
    while (factor * 2 <= index) factor *= 2
    result.push(offset + factor - 1)
    offset = offset + 2 * factor
    index -= factor
    factor = 1
  }
}

exports.futureRoots = function (index, result) {
  if (index & 1) throw new Error('You can only look up future roots for depth(0) blocks')
  if (!result) result = []

  let factor = 1

  // make first root
  while (factor * 2 <= index) factor *= 2

  // full factor of 2 - done
  if (factor * 2 - 2 === index) return result

  let pos = factor / 2 - 1

  // while its not a full tree
  while ((pos + factor / 2 - 1) !== index) {
    pos += factor

    // read too far, to to left child
    while ((pos + factor / 2 - 1) > index) {
      factor /= 2
      pos -= factor / 2
    }

    // the "gap" is a future root
    result.push(pos - factor / 2)
  }

  return result
}

exports.patch = function (from, to) {
  if (from === 0 || from >= to) return []

  const roots = exports.fullRoots(from)
  const target = exports.fullRoots(to)

  // first find the first root that is different

  let i = 0
  for (; i < target.length; i++) {
    if (i >= roots.length || roots[i] !== target[i]) break
  }

  const patch = []

  if (i < roots.length) {
    // now we need to grow the newest root until it hits the diff one
    let prev = roots.length - 1

    const ite = exports.iterator(roots[prev--])

    while (ite.index !== target[i]) {
      ite.sibling()

      if (prev >= 0 && ite.index === roots[prev]) {
        prev--
      } else {
        patch.push(ite.index)
      }

      patch.push(ite.parent())
    }

    i++ // patched to next root, so inc
  }

  // include the rest

  for (; i < target.length; i++) patch.push(target[i])

  return patch
}

exports.depth = function (index) {
  let depth = 0

  index += 1
  while (!(index & 1)) {
    depth++
    index = rightShift(index)
  }

  return depth
}

exports.sibling = function (index, depth) {
  if (!depth) depth = exports.depth(index)
  const offset = exports.offset(index, depth)

  return exports.index(depth, offset & 1 ? offset - 1 : offset + 1)
}

exports.parent = function (index, depth) {
  if (!depth) depth = exports.depth(index)
  const offset = exports.offset(index, depth)

  return exports.index(depth + 1, rightShift(offset))
}

exports.leftChild = function (index, depth) {
  if (!(index & 1)) return -1
  if (!depth) depth = exports.depth(index)
  return exports.index(depth - 1, exports.offset(index, depth) * 2)
}

exports.rightChild = function (index, depth) {
  if (!(index & 1)) return -1
  if (!depth) depth = exports.depth(index)
  return exports.index(depth - 1, 1 + (exports.offset(index, depth) * 2))
}

exports.children = function (index, depth) {
  if (!(index & 1)) return null

  if (!depth) depth = exports.depth(index)
  const offset = exports.offset(index, depth) * 2

  return [
    exports.index(depth - 1, offset),
    exports.index(depth - 1, offset + 1)
  ]
}

exports.leftSpan = function (index, depth) {
  if (!(index & 1)) return index
  if (!depth) depth = exports.depth(index)
  return exports.offset(index, depth) * twoPow(depth + 1)
}

exports.rightSpan = function (index, depth) {
  if (!(index & 1)) return index
  if (!depth) depth = exports.depth(index)
  return (exports.offset(index, depth) + 1) * twoPow(depth + 1) - 2
}

exports.nextLeaf = function (index) {
  let factor = 1
  let r = index

  while ((r & 1) === 1) {
    r = (r - 1) / 2
    factor *= 2
  }

  return index + factor + 1
}

exports.count = function (index, depth) {
  if (!(index & 1)) return 1
  if (!depth) depth = exports.depth(index)
  return twoPow(depth + 1) - 1
}

exports.countLeaves = function (index) {
  return (exports.count(index) + 1) / 2
}

exports.spans = function (index, depth) {
  if (!(index & 1)) return [index, index]
  if (!depth) depth = exports.depth(index)

  const offset = exports.offset(index, depth)
  const width = twoPow(depth + 1)

  return [offset * width, (offset + 1) * width - 2]
}

exports.index = function (depth, offset) {
  return (1 + 2 * offset) * twoPow(depth) - 1
}

exports.offset = function (index, depth) {
  if (!(index & 1)) return index / 2
  if (!depth) depth = exports.depth(index)

  return ((index + 1) / twoPow(depth) - 1) / 2
}

exports.iterator = function (index) {
  const ite = new Iterator()
  ite.seek(index || 0)
  return ite
}

function twoPow (n) {
  return n < 31 ? 1 << n : ((1 << 30) * (1 << (n - 30)))
}

function rightShift (n) {
  return (n - (n & 1)) / 2
}

function Iterator () {
  this.index = 0
  this.offset = 0
  this.factor = 0
}

Iterator.prototype.seek = function (index) {
  this.index = index
  if (this.index & 1) {
    this.offset = exports.offset(index)
    this.factor = twoPow(exports.depth(index) + 1)
  } else {
    this.offset = index / 2
    this.factor = 2
  }
}

Iterator.prototype.isLeft = function () {
  return (this.offset & 1) === 0
}

Iterator.prototype.isRight = function () {
  return (this.offset & 1) === 1
}

Iterator.prototype.isRoot = function (length) {
  const currentLength = 1 + (this.index + this.factor / 2 - 1) / 2
  if (length < currentLength) return false

  const factor = this.factor * 2
  const index = (this.offset & 1)
    ? this.index - this.factor / 2
    : this.index + this.factor / 2

  const parentLength = 1 + (index + factor / 2 - 1) / 2
  return parentLength > length
}

Iterator.prototype.contains = function (index) {
  return index > this.index
    ? index < (this.index + this.factor / 2)
    : index < this.index
      ? index > (this.index - this.factor / 2)
      : true
}

Iterator.prototype.prev = function () {
  if (!this.offset) return this.index
  this.offset--
  this.index -= this.factor
  return this.index
}

Iterator.prototype.next = function () {
  this.offset++
  this.index += this.factor
  return this.index
}

Iterator.prototype.count = function () {
  if (!(this.index & 1)) return 1
  return this.factor - 1
}

Iterator.prototype.countLeaves = function () {
  return (this.count() + 1) / 2
}

Iterator.prototype.sibling = function () {
  return this.isLeft() ? this.next() : this.prev()
}

Iterator.prototype.parent = function () {
  if (this.offset & 1) {
    this.index -= this.factor / 2
    this.offset = (this.offset - 1) / 2
  } else {
    this.index += this.factor / 2
    this.offset /= 2
  }
  this.factor *= 2
  return this.index
}

Iterator.prototype.leftSpan = function () {
  this.index = this.index - this.factor / 2 + 1
  this.offset = this.index / 2
  this.factor = 2
  return this.index
}

Iterator.prototype.peekLeftSpan = function () {
  return this.index - this.factor / 2 + 1
}

Iterator.prototype.rightSpan = function () {
  this.index = this.index + this.factor / 2 - 1
  this.offset = this.index / 2
  this.factor = 2
  return this.index
}

Iterator.prototype.peekRightSpan = function () {
  return this.index + this.factor / 2 - 1
}

Iterator.prototype.leftChild = function () {
  if (this.factor === 2) return this.index
  this.factor /= 2
  this.index -= this.factor / 2
  this.offset *= 2
  return this.index
}

Iterator.prototype.rightChild = function () {
  if (this.factor === 2) return this.index
  this.factor /= 2
  this.index += this.factor / 2
  this.offset = 2 * this.offset + 1
  return this.index
}

Iterator.prototype.nextTree = function () {
  this.index = this.index + this.factor / 2 + 1
  this.offset = this.index / 2
  this.factor = 2
  return this.index
}

Iterator.prototype.prevTree = function () {
  if (!this.offset) {
    this.index = 0
    this.factor = 2
  } else {
    this.index = this.index - this.factor / 2 - 1
    this.offset = this.index / 2
    this.factor = 2
  }
  return this.index
}

Iterator.prototype.fullRoot = function (index) {
  if (index <= this.index || (this.index & 1) > 0) return false
  while (index > this.index + this.factor + this.factor / 2) {
    this.index += this.factor / 2
    this.factor *= 2
    this.offset /= 2
  }
  return true
}
{
  "name": "flat-tree",
  "version": "1.13.0",
  "description": "A series of functions to map a binary tree to a list",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {},
  "devDependencies": {
    "brittle": "^3.3.2",
    "standard": "^17.1.0"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/flat-tree.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/flat-tree/issues"
  },
  "homepage": "https://github.com/mafintosh/flat-tree"
}
require.addon = require('require-addon')

module.exports = require.addon('.', __filename)
const { isWindows } = require('which-runtime')
const binding = require('./binding')

function onwork(err, result) {
  if (err) this.reject(err)
  else this.resolve(result)
}

exports.tryLock = function tryLock(fd, offset = 0, length = 0, opts = {}) {
  if (typeof offset === 'object') {
    opts = offset
    offset = 0
  }

  if (typeof length === 'object') {
    opts = length
    length = 0
  }

  if (typeof opts !== 'object' || opts === null) {
    opts = {}
  }

  try {
    binding.tryLock(fd, offset, length, opts.shared !== true)
  } catch (err) {
    if (err.code === 'EAGAIN') return false
    throw err
  }

  return true
}

exports.waitForLock = function waitForLock(fd, offset = 0, length = 0, opts = {}) {
  if (typeof offset === 'object') {
    opts = offset
    offset = 0
  }

  if (typeof length === 'object') {
    opts = length
    length = 0
  }

  if (typeof opts !== 'object' || opts === null) {
    opts = {}
  }

  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.waitForLock(fd, offset, length, opts.shared !== true, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.waitForLockSync = function waitForLockSync(fd, offset = 0, length = 0, opts = {}) {
  if (typeof offset === 'object') {
    opts = offset
    offset = 0
  }

  if (typeof length === 'object') {
    opts = length
    length = 0
  }

  if (typeof opts !== 'object' || opts === null) {
    opts = {}
  }

  binding.waitForLockSync(fd, offset, length, opts.shared !== true)
}

exports.tryDowngradeLock = function tryDowngradeLock(fd, offset = 0, length = 0) {
  try {
    binding.tryDowngradeLock(fd, offset, length)
  } catch (err) {
    if (err.code === 'EAGAIN') return false
    throw err
  }

  return true
}

exports.waitForDowngradeLock = function downgradeLock(fd, offset = 0, length = 0) {
  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.waitForDowngradeLock(fd, offset, length, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.waitForDowngradeLockSync = function waitForDowngradeLockSync(fd, offset = 0, length = 0) {
  binding.waitForDowngradeLockSync(fd, offset, length)
}

exports.tryUpgradeLock = function tryUpgradeLock(fd, offset = 0, length = 0) {
  try {
    binding.tryUpgradeLock(fd, offset, length)
  } catch (err) {
    if (err.code === 'EAGAIN') return false
    throw err
  }

  return true
}

exports.waitForUpgradeLock = function upgradeLock(fd, offset = 0, length = 0) {
  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.waitForUpgradeLock(fd, offset, length, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.waitForUpgradeLockSync = function waitForUpgradeLockSync(fd, offset = 0, length = 0) {
  binding.waitForUpgradeLockSync(fd, offset, length)
}

exports.unlock = function unlock(fd, offset = 0, length = 0) {
  binding.unlock(fd, offset, length)
}

exports.trim = function trim(fd, offset, length) {
  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.trim(fd, offset, length, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.trimSync = function trimSync(fd, offset, length) {
  binding.trimSync(fd, offset, length)
}

exports.sparse = function sparse(fd) {
  // Short circuit on everything but Windows
  if (!isWindows) return Promise.resolve()

  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.sparse(fd, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.sparseSync = function sparseSync(fd) {
  // Short circuit on everything but Windows
  if (!isWindows) return

  binding.sparseSync(fd)
}

exports.swap = function swap(from, to) {
  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.swap(from, to, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.swapSync = function swapSync(from, to) {
  binding.swapSync(from, to)
}

exports.getAttr = function getAttr(fd, name) {
  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.getAttr(fd, name, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise.then((buffer) => (buffer === null ? null : Buffer.from(buffer)))
}

exports.getAttrSync = function getAttrSync(fd, name) {
  const buffer = binding.getAttrSync(fd, name)
  return buffer === null ? null : Buffer.from(buffer)
}

exports.setAttr = function setAttr(fd, name, value, encoding) {
  if (typeof value === 'string') value = Buffer.from(value, encoding)

  const req = {
    value,
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.setAttr(
      fd,
      name,
      value.buffer,
      value.byteOffset,
      value.byteLength,
      req,
      onwork
    )
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.setAttrSync = function setAttrSync(fd, name, value, encoding) {
  if (typeof value === 'string') value = Buffer.from(value, encoding)

  binding.setAttrSync(fd, name, value.buffer, value.byteOffset, value.byteLength)
}

exports.removeAttr = function removeAttr(fd, name) {
  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.removeAttr(fd, name, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.removeAttrSync = function removeAttrSync(fd, name) {
  binding.removeAttrSync(fd, name)
}

exports.listAttrs = function listAttrs(fd) {
  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.listAttrs(fd, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.listAttrsSync = function listAttrsSync(fd) {
  return binding.listAttrsSync(fd)
}
{
  "name": "fs-native-extensions",
  "version": "1.5.0",
  "description": "Native file system extensions for advanced file operations",
  "main": "index.js",
  "files": [
    "index.js",
    "macros.h",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "include",
    "src",
    "prebuilds"
  ],
  "imports": {
    "child_process": {
      "bare": "bare-subprocess",
      "default": "child_process"
    },
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "fs/*": {
      "bare": "bare-fs/*",
      "default": "fs/*"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    }
  },
  "addon": true,
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:bare": "brittle-bare --coverage test.js",
    "test:node": "brittle-node --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/fs-native-extensions.git"
  },
  "author": "Kasper Isager Dalsgarð <kasper@funktionel.co>",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/fs-native-extensions/issues"
  },
  "homepage": "https://github.com/holepunchto/fs-native-extensions#readme",
  "dependencies": {
    "require-addon": "^1.1.0",
    "which-runtime": "^1.2.0"
  },
  "devDependencies": {
    "bare-compat-napi": "^1.3.8",
    "bare-fs": "^4.4.4",
    "bare-path": "^3.0.0",
    "bare-subprocess": "^4.0.5",
    "brittle": "^3.1.1",
    "cmake-bare": "^1.1.10",
    "cmake-fetch": "^1.4.7",
    "cmake-napi": "^1.0.5",
    "cmake-npm": "^1.1.0",
    "lunte": "^1.6.0",
    "minimist": "^1.2.6",
    "prettier": "^3.5.3",
    "prettier-config-holepunch": "^2.0.0",
    "test-tmp": "^1.2.1"
  }
}
/**
 * BaseProvider — Abstract authentication provider
 *
 * All auth providers must implement:
 * - name: string identifier
 * - extractCredentials(req): Extract credentials from HTTP request
 * - authenticate(credentials): Verify credentials, return auth result
 */
export class BaseProvider {
  constructor (name) {
    this.name = name
  }

  /**
   * Extract credentials from HTTP request
   * @param {Object} req - HTTP request
   * @returns {Promise<Object|null>} Credentials or null if not applicable
   */
  async extractCredentials (req) {
    throw new Error('Not implemented')
  }

  /**
   * Authenticate with extracted credentials
   * @param {Object} credentials - Extracted credentials
   * @returns {Promise<Object>} Auth result { identityId, method, credentials, permissions? }
   */
  async authenticate (credentials) {
    throw new Error('Not implemented')
  }
}

export default BaseProvider
import { BaseProvider } from '../base-provider.js'

/**
 * AtprotoProvider — AT-Protocol (did:plc) authentication + binding.
 *
 * Binds a user's atproto identity (did:plc + secp256k1 signing key + handle) to
 * the registry. The binding is seed-anchored: one BIP39 mnemonic yields both the
 * keet Ed25519 identity (our P2P world) and the atproto secp256k1 key (bsky world)
 * — see atproto-bridge/identity.
 *
 * Verification of did:plc control is delegated to an injected `verify` fn (mirrors
 * how KeetIdentityProvider injects IdentityKey), so this package stays dep-light and
 * the atproto crypto lives in one place. `verify(proof)` must return a verified
 * binding `{ did, handle, didKey, ed25519PublicKey }` (or throw/return false).
 */
export class AtprotoProvider extends BaseProvider {
  constructor (identityRegistry, opts = {}) {
    super('atproto')
    this.registry = identityRegistry
    this._verify = opts.verify || null
  }

  async extractCredentials (req) {
    const raw = req.headers['x-atproto-proof']
    if (!raw) return null
    try {
      return { proof: JSON.parse(raw) }
    } catch {
      return null
    }
  }

  async authenticate (credentials) {
    if (!this._verify) throw new Error('atproto verifier not configured')

    const { proof } = credentials
    const binding = await this._verify(proof)
    if (!binding || !binding.did) throw new Error('Invalid atproto proof')

    const { did, handle, didKey, ed25519PublicKey } = binding

    let identity = await this.registry.getIdentityByDid(did)
    if (!identity) {
      // Auto-register. identityId = the did:plc (the atproto identity's own ID);
      // the ed25519 binding link + handle live in credentials.
      await this.registry.registerIdentity({
        identityId: did,
        method: 'atproto',
        credentials: { did, handle, didKey, ed25519PublicKey },
        createdAt: Date.now()
      })
      identity = { identityId: did, method: 'atproto' }
    }

    return {
      identityId: identity.identityId,
      method: 'atproto',
      credentials: { did, handle, didKey }
    }
  }
}

export default AtprotoProvider
{
  "name": "hyper-identity",
  "version": "1.1.3",
  "description": "Generic P2P identity management with Autobase, ANProto, and multi-method authentication",
  "type": "module",
  "main": "index.js",
  "exports": {
    ".": "./index.js",
    "./handle-registry": "./lib/handle-registry.js",
    "./anproto": "./lib/anproto.js",
    "./auth": "./lib/auth.js",
    "./identity-manager": "./lib/identity-manager.js",
    "./device-linker": "./lib/device-linker.js",
    "./secure-storage": "./lib/secure-storage.js",
    "./auth/identity-registry": "./lib/auth/identity-registry.js",
    "./auth/identity-apply": "./lib/auth/identity-apply.js",
    "./auth/identity-operations": "./lib/auth/identity-operations.js",
    "./auth/challenge-manager": "./lib/auth/challenge-manager.js",
    "./auth/rate-limiter": "./lib/auth/rate-limiter.js",
    "./auth/base-provider": "./lib/auth/base-provider.js",
    "./auth/ssh-parser": "./lib/auth/ssh-parser.js",
    "./auth/ssh-scan": "./lib/auth/ssh-scan.js",
    "./auth/ssh-agent": "./lib/auth/ssh-agent.js",
    "./auth/ssh-auto-import": "./lib/auth/ssh-auto-import.js",
    "./auth/providers/web-identity": "./lib/auth/providers/web-identity.js",
    "./auth/providers/keet-identity": "./lib/auth/providers/keet-identity.js",
    "./auth/providers/bearer-token": "./lib/auth/providers/bearer-token.js",
    "./auth/providers/ssh-key": "./lib/auth/providers/ssh-key.js",
    "./browser": "./lib/browser-identity.js",
    "./hyperident-vault": "./lib/hyperident-vault.js",
    "./auth/providers/atproto": "./lib/auth/providers/atproto.js"
  },
  "dependencies": {
    "autobase": "7.28.1",
    "b4a": "^1.6.4",
    "bare-fs": "^4.0.0",
    "bare-net": "^1.0.0",
    "bare-os": "^3.9.1",
    "bare-path": "^3.0.0",
    "bare-process": "^4.0.0",
    "bip39-mnemonic": "^2.5.0",
    "blind-pairing": "^2.3.1",
    "hyperbee": "^2.27.3",
    "hypercore": "^11.24.0",
    "hypercore-crypto": "^3.0.0",
    "hyperident": "file:../../repos/hyperident",
    "hyperswarm": "^4.16.0",
    "keet-identity-key": "github:holepunchto/keet-identity-key",
    "sodium-native": "^5.0.0",
    "hyper-identity-core": "file:../hyper-identity-core"
  },
  "scripts": {
    "test": "brittle test/*.test.js",
    "test:bare": "bare ./node_modules/.bin/brittle test/*.test.js"
  },
  "engines": {
    "node": ">=18",
    "bare": ">=1.0"
  },
  "imports": {
    "#node:fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "#node:fs/promises": {
      "bare": "bare-fs/promises",
      "default": "fs/promises"
    },
    "#node:path": {
      "bare": "bare-path",
      "default": "path"
    },
    "#node:os": {
      "bare": "bare-os",
      "default": "os"
    },
    "#node:net": {
      "bare": "bare-net",
      "default": "net"
    },
    "#node:process": {
      "bare": "bare-process",
      "default": "process"
    }
  },
  "license": "MIT",
  "devDependencies": {
    "brittle": "^3.19.1",
    "corestore": "^7.9.2",
    "random-access-memory": "^6.2.1"
  },
  "overrides": {
    "autobase": "7.28.1",
    "hyperschema": "1.21.0",
    "compact-encoding": "3.0.1",
    "hypercore": "11.30.1"
  }
}
// adopt — admit ANOTHER DEVICE into an existing DID over a blind-pairing tunnel instead of a file.
//
// Lives in hpp (not in a client) because ANY node holding the DID must be able to mint an invite for the
// next device — desktop or phone, symmetrically. That is keet's model: `addDevice`
// (contract/members/index.js) is available to any active member and the adder gains nothing by
// performing it. While this lived in the phone's tree, only the phone could mint.
//
// ⛔ THIS ADDS A TRANSPORT, NOT A CEREMONY. hyper-proto-peer's `coowner-invite` / `coowner-join` already
// do the whole cryptographic job, and do it correctly:
//   - chained attestation root -> existing -> joiner, with NO ROOT MNEMONIC anywhere (a node deliberately
//     never stores one; only the root's PUBLIC key, which every node already carries)
//   - the inviter pins `forceCreator` on itself, so growing the roster cannot silently demote it
//   - the joiner is written with `joiner: true` and WITHOUT `indexer` — a plain writer
// Those two lines are the loser-club fork and the N=2 quorum trap, already solved. Re-implementing any of
// it here would be writing a second, worse copy. This module only replaces the hand-off.
//
// WHAT WAS ACTUALLY MISSING. The existing ceremony moves the bundle as a FILE between two machines:
//     joiner$   hyper-proto-peer coowner-join <did>                  -> prints its device PUBLIC key
//     existing$ hyper-proto-peer coowner-invite <did> --device <hex> -> writes a bundle file
//     joiner$   hyper-proto-peer coowner-join <did> --bundle <file>
// That is fine between two servers you have shells on. It is useless for a phone: there is no shell, no
// scp, and the bundle CARRIES THE SHARED SIGNING KEY — so "move this secret by hand" is the worst
// possible instruction to give a user.
//
// The blind-pairing tunnel is strictly better than the file it replaces: one-time, owner-minted,
// end-to-end encrypted over the DHT, and the secret never touches a filesystem either side.
//
// ⚠ `coownerInvite` MUTATES THE LOCAL CONFIG (adds the member, pins forceCreator) as well as returning
// the bundle. So it must be called only AFTER the human approves — never speculatively on connection.
import { createPairInvite, joinPairInvite } from 'atproto-room/lib/pairing.js'
import { coownerInvite, coownerJoin } from './coowner.js'

// ── EXISTING DEVICE (desktop, or any already-attested device — NOT necessarily the root) ─────────────
//
// approve({ devicePublicKey, did }) -> boolean. Called when a phone reaches the tunnel and BEFORE any
// config is touched. Return false and the pairing is refused with the config untouched.
//
// Returns { inviteHex, waitForPeer, close } — same shape as createPairInvite, so a CLI or a UI can show
// the invite as text or a QR and then await the result.
export async function mintAdoptInvite ({ did, approve, configFile = null, swarm = null } = {}) {
  if (!did) throw new Error('mintAdoptInvite requires { did }')
  if (typeof approve !== 'function') throw new Error('mintAdoptInvite requires approve({ devicePublicKey, did }) -> boolean')

  let result = null

  const source = await createPairInvite({
    swarm,
    // The candidate's hello carries its device PUBLIC key. Same field the browser flow uses for a
    // sub-key — the tunnel does not care what the bytes mean, only this handler does.
    onSubkey: async (devicePublicKey) => {
      const ok = await approve({ devicePublicKey, did })
      if (!ok) {
        // Refusing must leave NOTHING behind: no roster entry, no forceCreator, no backup file.
        // Returning an error object rather than throwing keeps the tunnel's own teardown clean.
        return { error: 'refused by the device owner' }
      }
      // Only now does anything mutate. coownerInvite adds the member, pins our creator role, writes the
      // config (leaving a .bak), and hands back the bundle.
      const r = await coownerInvite({ did, devicePublicKey, configFile })
      result = { members: r.members, backup: r.backup, devicePublicKey }
      return r.bundle
    }
  })

  return {
    inviteHex: source.inviteHex,
    async waitForPeer () {
      await source.waitForPeer()
      return result // null iff refused
    },
    close: () => source.close()
  }
}

// ── PHONE ────────────────────────────────────────────────────────────────────────────────────────────
//
// Two calls, because the device key must exist before there is anything to attest:
//   1. coownerJoin({ did })          — mints a device mnemonic if absent, returns its PUBLIC key.
//                                      The mnemonic is written to config and never leaves the phone.
//   2. joinPairInvite(...)           — sends that public key up the tunnel, gets the bundle back.
//   3. coownerJoin({ did, bundle })  — writes the entry, sets joiner:true, leaves indexer unset.
//
// Step 3 is what makes the phone a NODE rather than a client: the bundle carries the shared #atproto
// signing key, so from here the phone materialises and signs its own commits.
// `did` is OPTIONAL and normally omitted — the invite alone is the whole handoff. The device mints its
// key knowing nothing (a keypair is derived from a mnemonic, not from an identity), sends the public
// half up the tunnel, and learns the DID from the bundle that comes back — which coownerJoin then
// cross-checks. Same shape as favela-web's browser join (bin/favela-web.js:962). Pass `did` only to
// ASSERT which identity you expect; a mismatch then throws instead of joining the wrong one.
export async function joinAdoptInvite ({ did = null, inviteHex, configFile = null, swarm = null, onStep = () => {} } = {}) {
  if (!inviteHex) throw new Error('joinAdoptInvite requires { inviteHex }')

  const pre = await coownerJoin({ did, configFile })
  onStep('device key ready', { devicePublicKey: pre.devicePublicKey })

  const bundle = await joinPairInvite(inviteHex, { subKey: pre.devicePublicKey, swarm })
  if (!bundle || bundle.error) throw new Error('adopt refused: ' + ((bundle && bundle.error) || 'no bundle'))
  onStep('bundle received', { did: bundle.did })

  const joined = await coownerJoin({ did: did || bundle.did, bundle, configFile })
  onStep('joined', { members: joined.entry.members })

  // The caller restarts the node; boot picks the entry up. Deliberately not restarting here — a pairing
  // function that also manages process lifecycle is two things.
  return { devicePublicKey: pre.devicePublicKey, entry: joined.entry, backup: joined.backup }
}
// Config — a file (${HOME}/.config/hyper-proto-peer/config.json) overlaid by PEER_* env, with
// defaults. One place decides storage/handle/pds/adopt so the daemon is config-driven (a normal
// pgh app), not purely env-driven. Env wins over file wins over default, so the pgh manifest's
// defaults.env and an operator's config.json both work.
//
// SECRETS STAY OUT OF GIT: the adopt device signing key (adoptDevicePrivHex) and the root
// mnemonic live in the operator's config.json on the box (or env at provision time) — NEVER in
// the committed manifest. The self-custody key is written to the vault (<storage>/peer-identity.json)
// on first boot and reloaded thereafter; config.json is only consulted to MINT the vault.

import fs from 'bare-fs'
import os from 'bare-os'
import path from 'bare-path'

const DEFAULT_DIR = path.join(os.homedir(), '.config', 'hyper-proto-peer')

function expand (v) {
  if (typeof v !== 'string') return v
  return v.replace(/\$\{HOME\}/g, os.homedir()).replace(/^~(?=\/|$)/, os.homedir())
}

// Normalize a WRITERS allowlist (Phase-2 write path): the hex Noise pubkeys of clients
// authorized to call the peer's `apply-write` RPC. Accepts an env comma-string
// (PEER_WRITERS) or a file array/comma-string (`writers`) → lowercased hex list, or null.
function normalizeWriters (raw) {
  if (!raw) return null
  const list = Array.isArray(raw) ? raw : String(raw).split(',')
  const set = list.map((s) => String(s).trim().toLowerCase()).filter(Boolean)
  return set.length ? set : null
}

// Normalize the device roster to [{ key: <hex>, role: 1 }] (all devices role-equal). Accepts a
// comma-string of hex pubkeys or an array of hex strings / {key,role} objects.
export function normalizeMembers (raw) {
  if (!raw) return null
  const list = Array.isArray(raw) ? raw : String(raw).split(',')
  const out = []
  for (const m of list) {
    const key = (typeof m === 'object' && m ? m.key : m)
    const hex = String(key || '').trim().toLowerCase()
    if (hex) out.push({ key: hex, role: 1 })
  }
  return out.length ? out : null
}

export function configPath () {
  return process.env.PEER_CONFIG || path.join(DEFAULT_DIR, 'config.json')
}

export function loadConfig () {
  let file = {}
  const p = configPath()
  try { file = JSON.parse(fs.readFileSync(p, 'utf8')) } catch { /* absent/invalid → defaults */ }

  const env = process.env
  const pick = (fileKey, envKey, def) => {
    if (env[envKey] != null && env[envKey] !== '') return env[envKey]
    if (file[fileKey] != null) return file[fileKey]
    return def
  }

  const storage = expand(pick('storage', 'PEER_STORAGE', path.join(DEFAULT_DIR, 'data')))
  const cfg = {
    storage,
    handle: pick('handle', 'PEER_HANDLE', 'peer.local'),
    pdsUrl: pick('pdsUrl', 'PEER_PDS_URL', 'https://pds.local'),
    appPassword: pick('appPassword', 'PEER_APP_PASSWORD', null),
    // WRITERS allowlist: hex Noise pubkeys allowed to call apply-write. Null (default) =
    // no remote writers → apply-write is NOT registered (secure default; the peer still
    // authors its own commits). See index.js (canWrite wiring) + lib/peer.js apply-write.
    writers: normalizeWriters(pick('writers', 'PEER_WRITERS', null)),
    // ADOPT an existing published DID (migration): presence of adoptDid + adoptDidKey +
    // adoptDevicePrivHex triggers Peer.adopt on first boot (only if no vault yet). adoptCar is
    // an optional path to a repo CAR whose records are imported (re-authored under the peer key).
    adoptDid: pick('adoptDid', 'ADOPT_DID', null),
    adoptDidKey: pick('adoptDidKey', 'ADOPT_DID_KEY', null),
    adoptDevicePrivHex: pick('adoptDevicePrivHex', 'ADOPT_DEVICE_PRIV_HEX', null),
    adoptCar: expand(pick('adoptCar', 'ADOPT_CAR', null)),
    // INIT a fresh self-custody identity (onboarding): the hyperident root recovery seed. Only
    // used when there is no vault AND no adopt block. Never stored in the vault.
    rootMnemonic: pick('rootMnemonic', 'PEER_ROOT_MNEMONIC', null),
    // MULTI-DEVICE swarm mode (atproto-base): boot a SwarmDevice (N attested devices of one DID
    // share the repo) instead of the single-tenant peer. Needs rootMnemonic (identity/shared-key
    // root) + deviceMnemonic (this device's keet identity, attested to the root).
    swarm: /^(1|true|yes)$/i.test(String(pick('swarm', 'PEER_SWARM', ''))),
    // ONE-TIME firehose repair: clear a malformed __commit__ log + re-emit a clean continuation from
    // the adoptCar baseline (guarded by a durable marker, so it's safe to leave set). See
    // bootSwarmDevice/SwarmDevice.resetFirehose. Set PEER_RESET_FIREHOSE=1 (or config resetFirehose).
    resetFirehose: /^(1|true|yes)$/i.test(String(pick('resetFirehose', 'PEER_RESET_FIREHOSE', ''))),
    deviceMnemonic: pick('deviceMnemonic', 'PEER_DEVICE_MNEMONIC', null),
    // The provisioned device BUNDLE (atproto-base-REVOCATION.md §4): a swarm device boots from these
    // — the received DID + shared signing key + root->device attestation + root identity pubkey —
    // NOT the root mnemonic (which it must never hold). Produced by provisionDevice() on the root.
    did: pick('did', 'PEER_DID', null),
    signingKey: pick('signingKey', 'PEER_SIGNING_KEY', null),
    deviceProof: pick('deviceProof', 'PEER_DEVICE_PROOF', null),
    rootIdentityKey: pick('rootIdentityKey', 'PEER_ROOT_IDENTITY_KEY', null),
    // bsky-login secrets (the peer is the sole auth authority): scrypt hash of the app-password +
    // the HMAC secret for session JWTs. Carried in the swarm config because the swarm boots from the
    // bundle, not the single-tenant vault. Enables com.atproto.server.createSession via the keyless
    // bridge. See lib/sessions.js + serve-membrane.js.
    appPasswordHash: pick('appPasswordHash', 'PEER_APP_PASSWORD_HASH', null),
    jwtSecret: pick('jwtSecret', 'PEER_JWT_SECRET', null),
    // The device ROSTER (co-equal multi-writer): the hex keet-identity pubkeys of ALL attested
    // devices of this DID. Each device is admitted iff it proves attestation AND is in this set.
    // Absent → self-only (this device signs; others can read/replicate but not co-sign). Accepts a
    // PEER_MEMBERS comma-string or a `members` file array of hex strings / {key,role} objects.
    members: normalizeMembers(pick('members', 'PEER_MEMBERS', null)),
    // MULTI-DID (multi-tenant) mode: a `dids` array in config.json — each entry a full per-DID bundle
    // { did, signingKey, deviceMnemonic, deviceProof, rootIdentityKey, handle, pdsUrl?, members?,
    // writers?, adopt? }. Present + swarm → index.js boots bootMultiDevice (ONE daemon, N DIDs, one
    // shared Corestore/swarm/wakeup). Absent → the single-DID path (this config's own did fields). A
    // user's own DID + the communities they co-own live here as separate entries.
    // Normalize each per-DID roster the same way the single-DID path does — bootMultiDevice passes
    // dids[] verbatim to bootSwarmDevice, whose projectMembers needs [{key,role}], NOT a raw
    // "hex,hex" comma-string. Without this a fresh multi-DID StateBase crashes on the roster encode.
    dids: Array.isArray(file.dids) ? file.dids.map((d) => ({ ...d, members: normalizeMembers(d && d.members) })) : null,
    configPath: p
  }
  return cfg
}
// coowner — admit another machine as a co-owner of a DID, as a COMMAND rather than a hand-edit.
//
// Co-owning a DID needs four things to line up on two machines: the joiner has its own device keypair,
// an existing co-owner has ATTESTED that keypair to the DID's root identity, both configs list both
// device keys in the roster, and the joiner holds the shared #atproto signing key. Done by hand that is
// four edits across two boxes with a secret in the middle — every one a chance to typo a hex string into
// a room that then silently refuses admission. It is also the exact operation anyone adding a second
// machine will need, so it belongs in the tool.
//
// The ceremony (mirrors pgv3's `pgh device invite` / `pgh device join` shape):
//
//   joiner$   hyper-proto-peer coowner-join <did>                  -> prints its device PUBLIC key
//   existing$ hyper-proto-peer coowner-invite <did> --device <hex> -> prints a bundle, adds the key locally
//   joiner$   hyper-proto-peer coowner-join <did> --bundle <file>  -> writes its dids entry
//   (restart both daemons)
//
// NO ROOT MNEMONIC IS INVOLVED. The invite is signed by the existing co-owner's own device key via
// keet's chained attestation (atproto-identity attestDeviceViaDevice): root -> existing -> joiner. The
// root mnemonic is deliberately never stored on a node, and this ceremony does not need it — only the
// root's PUBLIC key, which every node already carries as rootIdentityKey.
//
// THE BUNDLE CARRIES THE SHARED SIGNING KEY. That is inherent: a co-owner materializes the DID's signed
// commits, so it must hold the shared #atproto key (SwarmDevice's privateKey). Treat a bundle file as a
// secret — write it to a private path, move it over a trusted channel, delete it after joining.
//
// The joiner is admitted as a PLAIN WRITER, never an indexer (StateBaseV3's default). Two indexers is the
// N=2 quorum trap: the majority becomes 2, one loss freezes indexedLength, and the room forks. One
// indexer plus plain writers is the shape a 2-peer room wants.

import fs from 'bare-fs'
import b4a from 'b4a'
import IdentityKey from 'keet-identity-key'
import { deviceKeetKeyPair, attestDeviceViaDevice } from 'atproto-identity/lib/device-chain.js'
import { configPath } from './config.js'

const hex = (u8) => b4a.toString(b4a.from(u8), 'hex')

// ⛔ AN ABSENT CONFIG IS NOT AN ERROR — IT IS WHERE EVERY JOINER STARTS. A phone on first run has an
// hpp directory and no config file, so turning ENOENT into a hard failure meant the pairing ceremony
// died on its first line, before the tunnel even opened ("coowner: cannot read config at
// /data/user/0/to.favela.android/files/hpp/config.json (ENOENT…)").
//
// A MALFORMED config is still a hard failure, and deliberately so: silently replacing a corrupt file
// would discard a device's mnemonic and roster — the one thing that cannot be regenerated (a fresh key
// orphans an attestation and leaves the machine permanently unadmitted). Missing means "new"; unreadable
// means "stop".
// Exported for lib/mint.js, which writes the same `dids[]` file for a device that CREATES an identity
// rather than joining one. Shared rather than reimplemented on purpose: the ENOENT-is-not-an-error rule
// above and the backup-before-write rule below are both load-bearing, and a second copy would drift.
export function readConfigFile (p) {
  let raw
  try { raw = fs.readFileSync(p, 'utf8') } catch (e) {
    if (e && (e.code === 'ENOENT' || /ENOENT/.test(e.message || ''))) return {}
    throw new Error('coowner: cannot read config at ' + p + ' (' + e.message + ')')
  }
  try { return JSON.parse(raw) } catch (e) { throw new Error('coowner: cannot read config at ' + p + ' (' + e.message + ')') }
}

// Never write a config without leaving the previous one on disk. A mistyped roster locks a machine out
// of a room, and the old file is the fastest way back.
export function writeConfigFile (p, cfg) {
  const backup = p + '.bak.' + Math.floor(Date.now() / 1000)
  try { fs.copyFileSync(p, backup) } catch {}
  fs.writeFileSync(p, JSON.stringify(cfg, null, 2) + '\n')
  return backup
}

const findEntry = (cfg, did) => (cfg.dids || []).find((d) => d.did === did) || null

// Add a device key to a DID entry's roster, idempotently. The roster is the set of device ids that MAY be
// admitted; admission itself is still proof-gated, so listing a key grants nothing on its own.
function addMember (entry, deviceHex) {
  // ⛔ THE ROSTER IS NOT ALWAYS AN ARRAY. On disk it is an array of hex strings, an array of {key,role}
  // objects, OR a comma-separated string — wj62 in production is the string form. `config.js
  // normalizeMembers` accepts all three, but that is the BOOT path; this file reads the config with its
  // own raw JSON.parse, so it must accept them too. An `Array.isArray` gate treated a populated string
  // roster as EMPTY, which made `coownerInvite` rewrite it as [self, joiner] and silently DROP every
  // other device — a truncation performed by the command whose job is to grow the roster.
  // Control: test/coowner-members-string.test.mjs.
  const raw = entry.members
  const list = Array.isArray(raw) ? raw : (typeof raw === 'string' ? raw.split(',') : [])
  const cur = list.map((m) => String((typeof m === 'object' && m ? m.key : m) || '').trim()).filter(Boolean)
  const norm = cur.map((m) => m.toLowerCase())
  // A roster that was ABSENT means "self only" (bootSwarmDevice defaults to [{key:self}]), so the first
  // explicit roster must name the existing device too or it would silently drop it.
  if (!norm.length) return { members: null, added: false, needsSelf: true }
  if (norm.includes(String(deviceHex).toLowerCase())) return { members: cur, added: false }
  cur.push(String(deviceHex).toLowerCase())
  return { members: cur, added: true }
}

// ── coowner-invite (run on an EXISTING co-owner) ────────────────────────────────────────────────────
// Attest the joiner's device key against this DID's root (chained through OUR device), add it to our
// roster, and emit the bundle the joiner needs. Returns { bundle, backup, members }.
export async function coownerInvite ({ did, devicePublicKey, configFile = null } = {}) {
  if (!did) throw new Error('coowner-invite: <did> required')
  if (!/^[0-9a-fA-F]{64}$/.test(String(devicePublicKey || ''))) throw new Error('coowner-invite: --device <64-hex device public key> required')
  const p = configFile || configPath()
  const cfg = readConfigFile(p)
  const entry = findEntry(cfg, did)
  if (!entry) throw new Error('coowner-invite: this machine does not host ' + did + ' (no dids entry)')
  if (!entry.deviceMnemonic || !entry.deviceProof) throw new Error('coowner-invite: our entry lacks deviceMnemonic/deviceProof — cannot vouch for another device')
  if (!entry.signingKey || !entry.rootIdentityKey) throw new Error('coowner-invite: our entry lacks signingKey/rootIdentityKey — incomplete bundle')

  const parent = await deviceKeetKeyPair(entry.deviceMnemonic)
  const selfHex = hex(parent.publicKey)
  const childProof = attestDeviceViaDevice({
    parentKeyPair: parent,
    parentProof: b4a.from(entry.deviceProof, 'hex'),
    devicePublicKey: b4a.from(String(devicePublicKey), 'hex')
  })

  // Roster: both devices. An absent roster meant self-only, so seed it with US before adding THEM.
  const r = addMember(entry, devicePublicKey)
  const members = r.needsSelf ? [selfHex, String(devicePublicKey).toLowerCase()] : r.members
  entry.members = members

  // PIN OUR CREATOR ROLE. The creator election is `lowest-keyed member == self`, so growing the roster can
  // silently demote us: if the joiner's key sorts below ours we would stop opening the roomSeed-derived
  // genesis writer and ABANDON it, while the joiner claims it. That is the loser-club fork, reproduced in
  // test/coowner-join-role.test.js. A room's creator is a property of the room, not of key ordering.
  //
  // Only if we are not ourselves a joiner: chains nest, so a joiner can legitimately vouch for the next
  // machine, but it must never claim the genesis — that stays with whoever bootstrapped the room.
  //
  // ⛔ BUT INVITING IS NOT A CLAIM TO THE GENESIS. Keet is the reference here: `addDevice`
  // (contract/members/index.js) verifies the attestation, addWriters the device, and gives the ADDER
  // nothing — no role moves, because keet has no creator election at all (its room key IS the autobase
  // key, so there is no roomSeed-derived genesis writer to claim or abandon). Our election is a local
  // construct, so the pin must be too: it may only ever RE-STATE a role this node already holds.
  //
  // Two nodes are wrongly captured by a bare `!entry.joiner`:
  //   - one forced non-creator by `resyncStore` (device-node.js:178) — a RUNTIME flag, invisible here,
  //     which is tabertron's posture for wj62. state-base.js:406 checks _forceCreator BEFORE
  //     _forceNonCreator, so writing the pin would WIN and the DID would have two creators.
  //   - one carrying an explicit `forceCreator: false`, which is a decision on file.
  // Both must be able to invite the next device without changing who holds the genesis.
  if (!entry.joiner && entry.forceCreator !== false) entry.forceCreator = true
  const backup = writeConfigFile(p, cfg)

  return {
    backup,
    members,
    bundle: {
      did,
      handle: entry.handle || null,
      pdsUrl: entry.pdsUrl || null,
      signingKey: entry.signingKey,       // SECRET — the shared #atproto key a co-owner signs with
      rootIdentityKey: entry.rootIdentityKey,
      deviceProof: hex(childProof),        // root -> us -> joiner
      storeBackend: entry.storeBackend || null,
      members
    }
  }
}

// ── coowner-join (run on the JOINER) ───────────────────────────────────────────────────────────────
// Without --bundle: ensure this machine has a device mnemonic for the DID and print its PUBLIC key (the
// mnemonic stays here and is never printed). With --bundle: write the full dids entry.
// Idempotent: an existing mnemonic is REUSED, never regenerated — regenerating would orphan an already
// attested key and leave the machine permanently unadmitted.
//
// ⛔ THE DID IS OPTIONAL. A device keypair is derived from a mnemonic and nothing else
// (`deviceKeetKeyPair(mnemonic)` takes no DID), so a device can mint its key BEFORE it knows which
// identity it is joining — which is what lets a single opaque invite be the whole handoff. favela-web's
// browser join already works this way (bin/favela-web.js:962): generate locally, send only the invite,
// take the identity from what comes back. Without this, the phone had to be TOLD a DID that the bundle
// then hands back anyway (and that `:140` below already cross-checks).
//
// The mnemonic therefore lives at CONFIG ROOT — it identifies the DEVICE, not one of its rooms — with a
// per-DID mnemonic still winning when present. That ordering is load-bearing: an existing per-DID key
// may already be attested, and replacing it would orphan the attestation and leave the machine
// permanently unadmitted (the same hazard the "never regenerate" rule above guards).
export async function coownerJoin ({ did = null, bundle = null, configFile = null } = {}) {
  const p = configFile || configPath()
  const cfg = readConfigFile(p)
  if (!Array.isArray(cfg.dids)) cfg.dids = []
  // A bundle names its own DID; the caller need not.
  if (!did && bundle && bundle.did) did = bundle.did
  if (!did && bundle) throw new Error('coowner-join: bundle carries no did')
  let entry = did ? findEntry(cfg, did) : null

  // Key selection, most-specific first: an already-attested per-DID key, else this device's own.
  if (entry && entry.deviceMnemonic) {
    // keep it — never regenerate
  } else if (!cfg.deviceMnemonic) {
    cfg.deviceMnemonic = IdentityKey.generateMnemonic()
  }
  const mnemonic = (entry && entry.deviceMnemonic) || cfg.deviceMnemonic

  // With no DID at all we are in step 1 of the ceremony: mint/reuse the key, report it, write nothing
  // else. The entry cannot exist yet — the bundle that names the DID has not arrived.
  if (!did) {
    const kp0 = await deviceKeetKeyPair(mnemonic)
    const backup0 = writeConfigFile(p, cfg)
    return { devicePublicKey: hex(kp0.publicKey), joined: false, backup: backup0, entry: null }
  }

  if (!entry) {
    entry = { did }
    cfg.dids.push(entry)
  }
  const kp = await deviceKeetKeyPair(mnemonic)
  const devicePublicKey = hex(kp.publicKey)

  if (bundle) {
    if (bundle.did && bundle.did !== did) throw new Error('coowner-join: bundle is for ' + bundle.did + ', not ' + did)
    if (!bundle.deviceProof || !bundle.signingKey || !bundle.rootIdentityKey) throw new Error('coowner-join: bundle must carry deviceProof, signingKey and rootIdentityKey')
    entry.deviceProof = bundle.deviceProof
    entry.signingKey = bundle.signingKey
    entry.rootIdentityKey = bundle.rootIdentityKey
    if (bundle.handle) entry.handle = bundle.handle
    if (bundle.pdsUrl) entry.pdsUrl = bundle.pdsUrl
    if (bundle.storeBackend) entry.storeBackend = bundle.storeBackend
    if (Array.isArray(bundle.members) && bundle.members.length) {
      const set = bundle.members.map((m) => String(typeof m === 'object' && m ? m.key : m).toLowerCase())
      if (!set.includes(devicePublicKey)) set.push(devicePublicKey)
      entry.members = set
    }
    // JOINER POSTURE (load-bearing). Without this the joiner elects itself creator whenever its key sorts
    // below the incumbent's, opens the roomSeed-derived genesis writer empty-and-writable in its fresh
    // store, and the boot-write block authors a rival genesis — the loser-club fork. `joiner` makes it
    // forceNonCreator AND converge-only at boot (no migratePointers/restore/adopt/fresh-account), so it
    // takes the existing line by replication and the forward-only sign() picks up at the tip.
    // Proven two-node in test/coowner-join-role.test.js, control included.
    entry.joiner = true
    // A joiner must never also be pinned as creator — exactly one node holds the genesis.
    delete entry.forceCreator
    // Deliberately NOT set: `indexer`. The joiner is a plain writer — see the header (N=2 quorum trap).
  }

  const backup = writeConfigFile(p, cfg)
  return { devicePublicKey, joined: !!bundle, backup, entry: { did, handle: entry.handle || null, storeBackend: entry.storeBackend || null, members: entry.members || null } }
}

// CLI arg helpers shared by index.js's subcommand dispatch.
export function coownerCli (sub, args) {
  const did = args.find((a) => a.startsWith('did:'))
  const flag = (name) => { const i = args.indexOf(name); return i < 0 ? null : args[i + 1] }
  if (sub === 'coowner-invite') return coownerInvite({ did, devicePublicKey: flag('--device'), configFile: flag('--config') })
  const bundleFile = flag('--bundle')
  let bundle = null
  if (bundleFile) bundle = JSON.parse(fs.readFileSync(bundleFile, 'utf8'))
  return coownerJoin({ did, bundle, configFile: flag('--config') })
}
// keet-identity-key device chain — the P2P-verifiable half of device attestation.
//
// Runs in PARALLEL to the atproto PLC authority (device-attestation.js). atproto's
// rotationKeys/PLC-op-log carry the FEDERATION-visible authority (secp256k1); this keet
// chain carries the authority OUR P2P world verifies (Ed25519). Both anchor on the same
// root identity and vouch for the same device.
//
// Shape (from keet-identity-key): a proof is `{ identity, epoch, chain: [{publicKey,
// signature}], data? }`. `bootstrap` attests a device pubkey under the root identity;
// `attestData` lets the (leaf) device sign arbitrary data — here, the atproto DID — so a
// verifier learns "root → device → this device vouches for did:plc:…". `verify` walks the
// chain back to the identity and checks the data signature.

import IdentityKey from 'keet-identity-key'
import b4a from 'b4a'

// The device's keet-world Ed25519 keypair (derived from the device seed) — distinct from
// its secp256k1 atproto signing key. This is the device's identity in the keet chain.
export async function deviceKeetKeyPair (mnemonic, seed) {
  const idk = await IdentityKey.from({ mnemonic, seed })
  return idk.identityKeyPair // { publicKey, secretKey }
}

// The root identity's Ed25519 public key — the anchor every chain must resolve to.
export async function rootIdentityPublicKey (mnemonic, seed) {
  const idk = await IdentityKey.from({ mnemonic, seed })
  return b4a.from(idk.identityPublicKey)
}

// Root identity attests a device's Ed25519 public key → an encoded proof chain.
export async function attestDeviceChain ({ rootMnemonic, rootSeed, devicePublicKey }) {
  return IdentityKey.bootstrap({ mnemonic: rootMnemonic, seed: rootSeed }, devicePublicKey)
}

// An ALREADY-ATTESTED device attests ANOTHER device, extending the chain: root → parent → child.
// keet's attestDevice signs { epoch, identity, device } with the PARENT's keypair and pushes
// { publicKey, signature } onto the parent's chain, so the result still resolves to the same root
// identity and the same epoch — a chained device passes the identical admission gate and the identical
// minimum-epoch receipt check as a root-attested one.
//
// WHY THIS MATTERS OPERATIONALLY: admitting a new device to a room needs a proof anchored at the room's
// root identity, and attestDeviceChain above needs the ROOT MNEMONIC — which is deliberately not stored
// on any node (config.js: a device "must never hold" it). Read alone, that makes adding a co-owner
// impossible without recovering a secret nobody kept. It is not: an existing attested device already has
// everything required to vouch for the next one. Only the root's PUBLIC key is needed to verify.
//
// parentKeyPair: the attesting device's Ed25519 identity keypair (deviceKeetKeyPair of its mnemonic).
// parentProof: that device's own proof (root-attested, or itself chained — chains nest).
export function attestDeviceViaDevice ({ parentKeyPair, parentProof, devicePublicKey }) {
  if (!parentKeyPair || !parentProof || !devicePublicKey) throw new Error('attestDeviceViaDevice: parentKeyPair, parentProof, devicePublicKey required')
  // Pass the proof as BYTES: keet decodes a fresh copy, so the caller's proof is never mutated by the
  // chain.push inside attestDevice (it would otherwise grow the parent's own proof on every call).
  const proof = b4a.isBuffer(parentProof) ? parentProof : b4a.from(parentProof)
  return IdentityKey.attestDevice(b4a.from(devicePublicKey), parentKeyPair, proof)
}

// The attested (leaf) device vouches for the atproto DID by signing it as attested data,
// extending the proof with `proof.data`. Result: root → device → vouches-for(did).
export function attestAtprotoBinding ({ deviceKeyPair, did, proof }) {
  return IdentityKey.attestData(b4a.from(did), deviceKeyPair, proof)
}

// Verify the full binding: the chain resolves to the root identity AND the device vouched
// for exactly this DID. Returns { receipt, identityPublicKey, devicePublicKey } or null.
export function verifyAtprotoBinding ({ proof, did, expectedIdentity, expectedDevice }) {
  return IdentityKey.verify(proof, b4a.from(did), { expectedIdentity, expectedDevice })
}
function isBuffer(value) {
  return Buffer.isBuffer(value) || value instanceof Uint8Array
}

function isEncoding(encoding) {
  return Buffer.isEncoding(encoding)
}

function alloc(size, fill, encoding) {
  return Buffer.alloc(size, fill, encoding)
}

function allocUnsafe(size) {
  return Buffer.allocUnsafe(size)
}

function allocUnsafeSlow(size) {
  return Buffer.allocUnsafeSlow(size)
}

function byteLength(string, encoding) {
  return Buffer.byteLength(string, encoding)
}

function compare(a, b) {
  return Buffer.compare(a, b)
}

function concat(buffers, totalLength) {
  return Buffer.concat(buffers, totalLength)
}

function copy(source, target, targetStart, start, end) {
  return toBuffer(source).copy(target, targetStart, start, end)
}

function equals(a, b) {
  return toBuffer(a).equals(b)
}

function fill(buffer, value, offset, end, encoding) {
  return toBuffer(buffer).fill(value, offset, end, encoding)
}

function from(value, encodingOrOffset, length) {
  return Buffer.from(value, encodingOrOffset, length)
}

function includes(buffer, value, byteOffset, encoding) {
  return toBuffer(buffer).includes(value, byteOffset, encoding)
}

function indexOf(buffer, value, byfeOffset, encoding) {
  return toBuffer(buffer).indexOf(value, byfeOffset, encoding)
}

function lastIndexOf(buffer, value, byteOffset, encoding) {
  return toBuffer(buffer).lastIndexOf(value, byteOffset, encoding)
}

function swap16(buffer) {
  return toBuffer(buffer).swap16()
}

function swap32(buffer) {
  return toBuffer(buffer).swap32()
}

function swap64(buffer) {
  return toBuffer(buffer).swap64()
}

function toBuffer(buffer) {
  if (Buffer.isBuffer(buffer)) return buffer
  return Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

function toString(buffer, encoding, start, end) {
  return toBuffer(buffer).toString(encoding, start, end)
}

function write(buffer, string, offset, length, encoding) {
  return toBuffer(buffer).write(string, offset, length, encoding)
}

function readDoubleBE(buffer, offset) {
  return toBuffer(buffer).readDoubleBE(offset)
}

function readDoubleLE(buffer, offset) {
  return toBuffer(buffer).readDoubleLE(offset)
}

function readFloatBE(buffer, offset) {
  return toBuffer(buffer).readFloatBE(offset)
}

function readFloatLE(buffer, offset) {
  return toBuffer(buffer).readFloatLE(offset)
}

function readInt32BE(buffer, offset) {
  return toBuffer(buffer).readInt32BE(offset)
}

function readInt32LE(buffer, offset) {
  return toBuffer(buffer).readInt32LE(offset)
}

function readUInt32BE(buffer, offset) {
  return toBuffer(buffer).readUInt32BE(offset)
}

function readUInt32LE(buffer, offset) {
  return toBuffer(buffer).readUInt32LE(offset)
}

function writeDoubleBE(buffer, value, offset) {
  return toBuffer(buffer).writeDoubleBE(value, offset)
}

function writeDoubleLE(buffer, value, offset) {
  return toBuffer(buffer).writeDoubleLE(value, offset)
}

function writeFloatBE(buffer, value, offset) {
  return toBuffer(buffer).writeFloatBE(value, offset)
}

function writeFloatLE(buffer, value, offset) {
  return toBuffer(buffer).writeFloatLE(value, offset)
}

function writeInt32BE(buffer, value, offset) {
  return toBuffer(buffer).writeInt32BE(value, offset)
}

function writeInt32LE(buffer, value, offset) {
  return toBuffer(buffer).writeInt32LE(value, offset)
}

function writeUInt32BE(buffer, value, offset) {
  return toBuffer(buffer).writeUInt32BE(value, offset)
}

function writeUInt32LE(buffer, value, offset) {
  return toBuffer(buffer).writeUInt32LE(value, offset)
}

module.exports = {
  isBuffer,
  isEncoding,
  alloc,
  allocUnsafe,
  allocUnsafeSlow,
  byteLength,
  compare,
  concat,
  copy,
  equals,
  fill,
  from,
  includes,
  indexOf,
  lastIndexOf,
  swap16,
  swap32,
  swap64,
  toBuffer,
  toString,
  write,
  readDoubleBE,
  readDoubleLE,
  readFloatBE,
  readFloatLE,
  readInt32BE,
  readInt32LE,
  readUInt32BE,
  readUInt32LE,
  writeDoubleBE,
  writeDoubleLE,
  writeFloatBE,
  writeFloatLE,
  writeInt32BE,
  writeInt32LE,
  writeUInt32BE,
  writeUInt32LE
}
{
  "name": "b4a",
  "version": "1.8.1",
  "description": "Bridging the gap between buffers and typed arrays",
  "exports": {
    "./package": "./package.json",
    ".": {
      "react-native": "./react-native.js",
      "browser": "./browser.js",
      "default": "./index.js"
    }
  },
  "files": [
    "browser.js",
    "index.js",
    "react-native.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:bare && npm run test:node",
    "test:bare": "brittle-bare --coverage test.mjs",
    "test:node": "brittle-node --coverage test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/b4a.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/b4a/issues"
  },
  "homepage": "https://github.com/holepunchto/b4a#readme",
  "devDependencies": {
    "brittle": "^3.5.2",
    "lunte": "^1.7.0",
    "nanobench": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "react-native-b4a": "*"
  },
  "peerDependenciesMeta": {
    "react-native-b4a": {
      "optional": true
    }
  }
}
const ESC = '\x1b'
const CSI = ESC + '['
const SGR = (n) => CSI + n + 'm'

exports.constants = {
  ESC,
  CSI,
  SGR
}

// https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_(Control_Sequence_Introducer)_sequences

exports.cursorHide = CSI + '?25l'
exports.cursorShow = CSI + '?25h'

exports.cursorUp = function cursorUp(n = 1) {
  return CSI + n + 'A'
}

exports.cursorDown = function cursorDown(n = 1) {
  return CSI + n + 'B'
}

exports.cursorForward = function cursorForward(n = 1) {
  return CSI + n + 'C'
}

exports.cursorBack = function cursorBack(n = 1) {
  return CSI + n + 'D'
}

exports.cursorNextLine = function cursorNextLine(n = 1) {
  return CSI + n + 'E'
}

exports.cursorPreviousLine = function cursorPreviousLine(n = 1) {
  return CSI + n + 'F'
}

exports.cursorPosition = function cursorPosition(column, row = 0) {
  if (row === 0) return CSI + (column + 1) + 'G'

  return CSI + (row + 1) + ';' + (column + 1) + 'H'
}

exports.eraseDisplayEnd = CSI + 'J'
exports.eraseDisplayStart = CSI + '1J'
exports.eraseDisplay = CSI + '2J'
exports.eraseLineEnd = CSI + 'K'
exports.eraseLineStart = CSI + '1K'
exports.eraseLine = CSI + '2K'

exports.scrollUp = function scrollUp(n = 1) {
  return CSI + n + 'S'
}

exports.scrollDown = function scrollDown(n = 1) {
  return CSI + n + 'T'
}

// https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_(Select_Graphic_Rendition)_parameters

exports.modifierReset = SGR(0)
exports.modifierBold = SGR(1)
exports.modifierDim = SGR(2)
exports.modifierItalic = SGR(3)
exports.modifierUnderline = SGR(4)
exports.modifierNormal = SGR(22)
exports.modifierNotItalic = SGR(23)
exports.modifierNotUnderline = SGR(24)

// https://en.wikipedia.org/wiki/ANSI_escape_code#Colors

exports.colorBlack = SGR(30)
exports.colorRed = SGR(31)
exports.colorGreen = SGR(32)
exports.colorYellow = SGR(33)
exports.colorBlue = SGR(34)
exports.colorMagenta = SGR(35)
exports.colorCyan = SGR(36)
exports.colorWhite = SGR(37)
exports.colorDefault = SGR(39)
exports.colorBrightBlack = SGR(90)
exports.colorBrightRed = SGR(91)
exports.colorBrightGreen = SGR(92)
exports.colorBrightYellow = SGR(93)
exports.colorBrightBlue = SGR(94)
exports.colorBrightMagenta = SGR(95)
exports.colorBrightCyan = SGR(96)
exports.colorBrightWhite = SGR(97)
{
  "name": "bare-ansi-escapes",
  "version": "2.2.3",
  "description": "Parse and produce ANSI escape sequences",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./key-decoder": {
      "types": "./key-decoder.d.ts",
      "default": "./key-decoder.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "key-decoder.js",
    "key-decoder.d.ts"
  ],
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-ansi-escapes.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-ansi-escapes/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-ansi-escapes#readme",
  "dependencies": {
    "bare-stream": "^2.6.5"
  },
  "devDependencies": {
    "bare-buffer": "^3.0.2",
    "brittle": "^3.3.2",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  },
  "peerDependencies": {
    "bare-buffer": "*"
  },
  "peerDependenciesMeta": {
    "bare-buffer": {
      "optional": true
    }
  }
}
const inspect = require('bare-inspect')

class AssertionError extends Error {
  constructor(opts = {}) {
    let { message = null, actual, expected, operator } = opts

    if (message === null) {
      message = `${inspect(actual)} ${operator} ${inspect(expected)}`
    }

    super(message)

    this.actual = actual
    this.expected = expected
    this.operator = operator
  }

  get name() {
    return 'AssertionError'
  }

  get code() {
    'ASSERTION'
  }
}

function assertFail(opts, fn) {
  if (opts.message instanceof Error) throw opts.message

  const err = new AssertionError(opts)

  if (Error.captureStackTrace) Error.captureStackTrace(err, fn)

  throw err
}

module.exports = exports = function assert(actual, message) {
  if (actual) return

  assertFail({ message, actual, expected: true, operator: '==' }, assert)
}

exports.AssertionError = AssertionError

exports.fail = function fail(message) {
  if (message === undefined) message = 'Failed'

  assertFail({ message, operator: 'fail' }, fail)
}

exports.ok = function ok(actual, message) {
  if (actual) return

  assertFail({ message, actual, expected: true, operator: '==' }, ok)
}

exports.notOk = function ok(actual, message) {
  if (!actual) return

  assertFail({ message, actual, expected: false, operator: '==' }, ok)
}

exports.equal = function equal(actual, expected, message) {
  if (actual == expected || (actual !== actual && expected !== expected)) {
    return
  }

  assertFail({ message, actual, expected, operator: '==' }, equal)
}

exports.notEqual = function notEqual(actual, expected, message) {
  if (actual != expected && (actual === actual || expected === expected)) {
    return
  }

  assertFail({ message, actual, expected, operator: '!=' }, notEqual)
}

exports.strictEqual = function strictEqual(actual, expected, message) {
  if (Object.is(actual, expected)) return

  assertFail(
    { message, actual, expected, operator: 'strictEqual' },
    strictEqual
  )
}

exports.notStrictEqual = function notStrictEqual(actual, expected, message) {
  if (!Object.is(actual, expected)) return

  assertFail(
    { message, actual, expected, operator: 'notStrictEqual' },
    notStrictEqual
  )
}
{
  "name": "bare-assert",
  "version": "1.2.0",
  "description": "Assertion library for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts"
  ],
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-assert.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-assert/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-assert#readme",
  "dependencies": {
    "bare-inspect": "^3.1.2"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  }
}
module.exports = require.addon()
const ansiEscapes = require('bare-ansi-escapes')
const getType = require('bare-type')
const binding = require('./binding')

const PLAIN_KEY = /^[a-zA-Z_][a-zA-Z_0-9]*$/

const defaultDepth = 2
const defaultBreakLength = 80
const defaultMaxArrayLength = 40

module.exports = exports = function inspect(value, opts = {}) {
  const {
    colors = false,
    depth = defaultDepth,
    breakLength = defaultBreakLength,
    stylize = defaultStylize(colors)
  } = opts

  const references = new InspectRefMap()

  const tree = inspectValue(value, 0, {
    colors,
    depth,
    breakLength,
    stylize,
    references
  })

  return tree.toString()
}

exports.styles = {
  bigint: ansiEscapes.colorYellow,
  boolean: ansiEscapes.colorYellow,
  date: ansiEscapes.colorMagenta,
  module: ansiEscapes.modifierUnderline,
  name: ansiEscapes.modifierReset,
  null: ansiEscapes.modifierBold,
  number: ansiEscapes.colorYellow,
  regexp: ansiEscapes.colorRed,
  special: ansiEscapes.colorCyan,
  string: ansiEscapes.colorGreen,
  symbol: ansiEscapes.colorGreen,
  undefined: ansiEscapes.colorBrightBlack
}

const styles = exports.styles

function defaultStylize(colors) {
  return function stylize(value, style) {
    const color = colors && styles[style]

    if (color) return color + value + ansiEscapes.modifierReset

    return value
  }
}

class InspectRefMap {
  constructor() {
    this.refs = new WeakMap()
    this.ids = new WeakMap()
    this.nextId = 1
  }

  has(object) {
    return this.refs.has(object)
  }

  get(object) {
    return this.refs.get(object) || null
  }

  set(object, ref) {
    this.refs.set(object, ref)
  }

  id(object) {
    let id = this.ids.get(object)
    if (id) return id

    id = this.nextId++
    this.ids.set(object, id)

    return id
  }
}

class InspectNode {
  constructor(depth, length, opts) {
    const { breakLength = defaultBreakLength, breakAlways = false } = opts

    this.depth = depth
    this.length = length
    this.breakLength = breakLength
    this.breakAlways = breakAlways
  }

  pad(n, string) {
    return string.padStart(n, ' ')
  }

  indent(n, string) {
    return '  '.repeat(n) + string
  }
}

class InspectRef extends InspectNode {
  constructor(depth, opts) {
    super(depth, '[circular *]'.length, opts)

    this.refs = opts.references
    this.count = 0
    this.circular = false
    this.color = opts.colors && styles.special
  }

  get id() {
    return this.refs.id(this)
  }

  increment() {
    return ++this.count
  }

  decrement() {
    return --this.count
  }

  toString(opts = {}) {
    const { offset = 0, pad = 0, indent = 0 } = opts

    let value = this.pad(pad, '[circular *' + this.id + ']')

    if (this.color) value = this.color + value + ansiEscapes.modifierReset

    return offset ? value : this.indent(indent, value)
  }
}

class InspectLeaf extends InspectNode {
  constructor(value, color, depth, opts) {
    const length = value.length

    if (value.includes('\n')) {
      value = value.replaceAll('\n', '\n' + '  '.repeat(depth))

      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.value = value
    this.color = opts.colors && color
  }

  toString(opts = {}) {
    const { offset = 0, pad = 0, indent = 0 } = opts

    let value = this.pad(pad, this.value)

    if (this.color) value = this.color + value + ansiEscapes.modifierReset

    return offset ? value : this.indent(indent, value)
  }
}

class InspectPair extends InspectNode {
  constructor(delim, left, right, depth, opts) {
    const length = left.length + delim.length + right.length

    if (left.breakAlways || right.breakAlways) {
      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.delim = delim
    this.left = left
    this.right = right
  }

  toString(opts = {}) {
    const { indent = 0 } = opts

    return this.indent(
      indent,
      this.left +
        this.delim +
        this.right.toString({
          indent,
          offset: this.left.length + this.delim.length
        })
    )
  }
}

class InspectSuspension extends InspectNode {
  constructor(overflow, depth, opts) {
    const label = `... ${overflow} more`

    super(depth, label.length, opts)

    this.label = label
  }

  toString(opts = {}) {
    const { indent = 0 } = opts

    return this.indent(indent, this.label)
  }
}

class InspectSequence extends InspectNode {
  constructor(header, footer, delim, values, ref, depth, opts) {
    const { tabulate = false } = opts

    const length =
      (ref.circular ? '<ref *>'.length + 1 : 0) +
      header.length +
      values.reduce(
        (length, value, i) =>
          length + value.length + (i === 0 ? 0 : delim.length),
        0
      ) +
      footer.length

    if (values.some((value) => value.breakAlways)) {
      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.header = header
    this.footer = footer
    this.delim = delim
    this.values = values
    this.ref = ref
    this.tabulate = tabulate
  }

  toString(opts = {}) {
    const { offset = 0, indent = 0 } = opts

    const split =
      this.breakAlways ||
      (this.values.length &&
        (offset + this.length > this.breakLength ||
          indent * 2 + this.length > this.breakLength))

    let header = this.header

    if (this.ref.circular) {
      header = '<ref *' + this.ref.id + '> ' + header
    }

    if (this.values.length === 0) {
      header = header.trimEnd()
    }

    if (offset === 0) {
      header = this.indent(indent, header)
    }

    if (split) {
      header = header.trimEnd() + '\n'
    }

    let string = header

    let columns = 1
    let pad = 0

    if (this.tabulate) {
      const widest = this.values.reduce(
        (length, value) =>
          value.breakAlways ? length : Math.max(length, value.length),
        0
      )

      if (widest) {
        columns = Math.max(
          columns,
          Math.floor(
            (this.breakLength - indent * 2) / (widest + this.delim.length)
          )
        )

        if (columns > 1) pad = widest
      }
    }

    for (let i = 0, n = this.values.length, offset = 0; i < n; i++) {
      const value = this.values[i]

      if (split) {
        let part

        if (i % columns === 0 || value.breakAlways) {
          part = value.toString({ indent: indent + 1, pad })
        } else {
          part = value.toString({ pad })
        }

        string += part

        if (i < n - 1) {
          if (i % columns === columns - 1 || this.values[i + 1].breakAlways) {
            string += this.delim.trimEnd() + '\n'
          } else {
            string += this.delim
          }
        }
      } else {
        if (i > 0) string += this.delim

        string += value.toString({ offset })

        offset += value.length
      }
    }

    let footer = this.footer

    if (this.values.length === 0) {
      footer = footer.trimStart()
    }

    if (split) {
      string += '\n' + this.indent(indent, footer.trimStart())
    } else {
      string += footer
    }

    return string
  }
}

function inspectValue(value, depth, opts) {
  const type = getType(value)

  if (type.isUndefined()) return inspectUndefined(depth, opts)
  if (type.isNull()) return inspectNull(depth, opts)
  if (type.isBoolean()) return inspectBoolean(value, depth, opts)
  if (type.isNumber()) return inspectNumber(value, depth, opts)
  if (type.isBigInt()) return inspectBigInt(value, depth, opts)
  if (type.isString()) return inspectString(value, depth, opts)
  if (type.isSymbol()) return inspectSymbol(value, depth, opts)
  if (type.isObject()) return inspectObject(type, value, depth, opts)
  if (type.isFunction()) return inspectFunction(type, value, depth, opts)
  if (type.isExternal()) return inspectExternal(value, opts, opts)
}

function inspectUndefined(depth, opts) {
  return new InspectLeaf('undefined', styles.undefined, depth, opts)
}

function inspectNull(depth, opts) {
  return new InspectLeaf('null', styles.null, depth, opts)
}

function inspectBoolean(value, depth, opts) {
  return new InspectLeaf(value.toString(), styles.boolean, depth, opts)
}

function inspectNumber(value, depth, opts) {
  let string

  if (Object.is(value, -0)) {
    string = '-0'
  } else {
    string = value.toString(10)
  }

  return new InspectLeaf(string, styles.number, depth, opts)
}

function inspectBigInt(value, depth, opts) {
  return new InspectLeaf(value.toString(10) + 'n', styles.bigint, depth, opts)
}

const STRING_ESCAPES =
  /[\ud800-\udbff][\udc00-\udfff]|[\u0000-\u001f'\\\ud800-\udfff]/g

function inspectString(value, depth, opts) {
  // https://tc39.es/ecma262/multipage/structured-data.html#sec-quotejsonstring
  const string = value.replace(STRING_ESCAPES, (match) => {
    if (match.length === 2) return match

    switch (match) {
      case "'":
        return "\\'"
      case '\\':
        return '\\\\'
      case '\b':
        return '\\b'
      case '\t':
        return '\\t'
      case '\n':
        return '\\n'
      case '\f':
        return '\\f'
      case '\r':
        return '\\r'
      default:
        return '\\u' + match.charCodeAt(0).toString(16).padStart(4, '0')
    }
  })

  return new InspectLeaf("'" + string + "'", styles.string, depth, opts)
}

function inspectSymbol(value, depth, opts) {
  return new InspectLeaf(value.toString(), styles.symbol, depth, opts)
}

function inspectKey(value, depth, opts) {
  if (PLAIN_KEY.test(value)) {
    return new InspectLeaf(value, null, depth, opts)
  } else {
    return inspectValue(value, depth, opts)
  }
}

function inspectObject(type, object, depth, opts) {
  const refs = opts.references

  let ref = refs.get(object)
  if (ref === null) {
    ref = new InspectRef(depth, opts)
    refs.set(object, ref)
  } else if (ref.count) {
    ref.circular = true
    return ref
  }

  const maxDepth = typeof opts.depth === 'number' ? opts.depth : Infinity

  if (maxDepth < depth) {
    const constructor = object.constructor

    return new InspectLeaf(
      '[' +
        (constructor && constructor.name ? constructor.name : 'Object') +
        ']',
      styles.special,
      depth,
      opts
    )
  }

  const inspect =
    object[Symbol.for('bare.inspect')] ||
    object[Symbol.for('nodejs.util.inspect.custom')]

  if (typeof inspect === 'function') {
    const value = inspect.call(
      object,
      typeof opts.depth === 'number' ? opts.depth - depth : null,
      {
        colors: opts.colors,
        breakLength: opts.breakLength,
        stylize: opts.stylize
      },
      exports
    )

    if (typeof value === 'object' && value !== null) {
      refs.set(value, ref)
    }

    if (typeof value !== 'string') {
      return inspectValue(value, depth, opts)
    }

    return new InspectLeaf(value, null, depth, opts)
  }

  if (type.isArray()) return inspectArray(object, ref, depth, opts)
  if (type.isDate()) return inspectDate(object, ref, depth, opts)
  if (type.isRegExp()) return inspectRegExp(object, ref, depth, opts)
  if (type.isError()) return inspectError(object, ref, depth, opts)
  if (type.isPromise()) return inspectPromise(object, ref, depth, opts)
  if (type.isMap()) return inspectMap(object, ref, depth, opts)
  if (type.isSet()) return inspectSet(object, ref, depth, opts)
  if (type.isWeakMap()) return inspectWeakMap(object, ref, depth, opts)
  if (type.isWeakSet()) return inspectWeakSet(object, ref, depth, opts)
  if (type.isWeakRef()) return inspectWeakRef(object, ref, depth, opts)
  if (type.isArrayBuffer()) return inspectArrayBuffer(object, ref, depth, opts)
  if (type.isSharedArrayBuffer())
    return inspectSharedArrayBuffer(object, ref, depth, opts)
  if (type.isTypedArray()) return inspectTypedArray(object, ref, depth, opts)
  if (type.isDataView()) return inspectDataView(object, ref, depth, opts)

  ref.increment()

  const values = []

  for (const key in object) {
    if (key === 'constructor') continue

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(object[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  let header = '{ '

  const tag = object[Symbol.toStringTag]

  if (tag) header = '[' + tag + '] ' + header

  if (object.constructor) {
    const name = object.constructor.name

    if (name && name !== 'Object') {
      header = object.constructor.name + ' ' + header
    }
  }

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectArray(array, ref, depth, opts) {
  const { maxArrayLength = defaultMaxArrayLength } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxArrayLength, 0)

  for (let i = 0, n = array.length; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(array.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(inspectValue(array[i], depth + 1, opts))
  }

  for (const key of binding.getOwnNonIndexPropertyNames(array)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(array[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  let header = '[ '

  if (array.constructor.name !== 'Array') {
    header = array.constructor.name + '(' + array.length + ') ' + header
  }

  return new InspectSequence(header, ' ]', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectDate(date, ref, depth, opts) {
  return new InspectLeaf(date.toISOString(), styles.date, depth, opts)
}

function inspectRegExp(regExp, ref, depth, opts) {
  return new InspectLeaf(regExp.toString(), styles.regexp, depth, opts)
}

function inspectError(error, ref, depth, opts) {
  let header

  if ('stack' in error) {
    header = error.stack

    if (depth > 0) {
      header = header.replaceAll('\n', '\n' + '  '.repeat(depth))
    }
  } else {
    header = error.toString()
  }

  const builtins = ['cause']

  if (error.name === 'AggregateError') {
    builtins.push('errors')
  } else if (error.name === 'SuppressedError') {
    builtins.push('error', 'suppressed')
  }

  const values = []

  for (const key of builtins) {
    if (key in error === false) continue

    values.push(
      new InspectPair(
        ': ',
        new InspectLeaf('[' + key + ']', null, depth + 1, opts),
        inspectValue(error[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key in error) {
    if (key === 'constructor' || builtins.includes(key)) continue

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(error[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  if (values.length === 0) return new InspectLeaf(header, null, depth, opts)

  return new InspectSequence(
    header + ' {',
    ' }',
    ', ',
    values,
    ref,
    depth,
    opts
  )
}

function inspectPromise(promise, ref, depth, opts) {
  ref.increment()

  const state = binding.getPromiseState(promise)

  const values = []

  switch (state) {
    case 0: // Pending
      values.push(new InspectLeaf('<pending>', styles.special, depth, opts))
      break

    case 1: // Fulfilled
      values.push(inspectValue(binding.getPromiseResult(promise), depth, opts))
      break

    case 2: // Rejected
      values.push(
        new InspectLeaf('<rejected>', styles.special, depth, opts),
        inspectValue(binding.getPromiseResult(promise), depth, opts)
      )
  }

  ref.decrement()

  const header = promise.constructor.name + ' { '

  return new InspectSequence(header, ' }', ' ', values, ref, depth, opts)
}

function inspectMap(map, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxMapLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = maxMapLength

  for (const entry of map) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(map.size - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )
      break
    }

    values.push(
      new InspectPair(
        ' => ',
        inspectValue(entry[0], depth + 1, opts),
        inspectValue(entry[1], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key in map) {
    if (key === 'constructor') continue

    const value = inspectValue(map[key], depth + 1, opts)

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        value,
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = map.constructor.name + '(' + map.size + ') { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectSet(set, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxSetLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = maxSetLength

  for (const entry of set) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(set.size - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )
      break
    }

    values.push(inspectValue(entry, depth + 1, opts))
  }

  for (const key in set) {
    if (key === 'constructor') continue

    const value = inspectValue(set[key], depth + 1, opts)

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        value,
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = set.constructor.name + '(' + set.size + ') { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectWeakMap(weakMap, ref, depth, opts) {
  const header = weakMap.constructor.name + ' { '

  return new InspectSequence(
    header,
    ' }',
    ' ',
    [new InspectLeaf('<items unknown>', styles.special, depth + 1, opts)],
    ref,
    depth,
    opts
  )
}

function inspectWeakSet(weakSet, ref, depth, opts) {
  const header = weakSet.constructor.name + ' { '

  return new InspectSequence(
    header,
    ' }',
    ' ',
    [new InspectLeaf('<items unknown>', styles.special, depth + 1, opts)],
    ref,
    depth,
    opts
  )
}

function inspectWeakRef(weakRef, ref, depth, opts) {
  const target = weakRef.deref()

  let value

  if (target === undefined) {
    value = new InspectLeaf('<cleared>', styles.special, depth + 1, opts)
  } else {
    value = inspectValue(target, depth + 1, opts)
  }

  const header = weakRef.constructor.name + ' { '

  return new InspectSequence(header, ' }', ' ', [value], ref, depth, opts)
}

function inspectArrayBuffer(arrayBuffer, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(arrayBuffer[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = arrayBuffer.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectSharedArrayBuffer(sharedArrayBuffer, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(sharedArrayBuffer[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = sharedArrayBuffer.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectTypedArray(typedArray, ref, depth, opts) {
  if (Buffer.isBuffer(typedArray)) {
    return inspectBuffer(typedArray, ref, depth, opts)
  }

  const {
    maxArrayLength = defaultMaxArrayLength,
    maxTypedArrayLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxTypedArrayLength, 0)

  for (let i = 0, n = typedArray.length; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(typedArray.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(inspectValue(typedArray[i], depth + 1, opts))
  }

  for (const key of binding.getOwnNonIndexPropertyNames(typedArray)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(typedArray[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = typedArray.constructor.name + '(' + typedArray.length + ') [ '

  return new InspectSequence(header, ' ]', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectBuffer(buffer, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxBufferLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxBufferLength, 0)

  for (let i = 0, n = buffer.byteLength; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(buffer.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(
      new InspectLeaf(
        buffer[i].toString(16).padStart(2, '0'),
        null,
        depth + 1,
        opts
      )
    )
  }

  for (const key of binding.getOwnNonIndexPropertyNames(buffer)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(buffer[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  return new InspectSequence('<Buffer ', '>', ' ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectDataView(dataView, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength', 'byteOffset', 'buffer']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(dataView[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key of binding.getOwnNonIndexPropertyNames(dataView)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(dataView[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = dataView.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectFunction(type, fn, depth, opts) {
  if (fn.toString().startsWith('class')) return inspectClass(fn, depth, opts)

  let tag = 'function'

  if (type.isGeneratorFunction()) tag = 'generator ' + tag
  if (type.isAsyncFunction()) tag = 'async ' + tag

  return new InspectLeaf(
    '[' + tag + ' ' + (fn.name ? fn.name : '(anonymous)') + ']',
    styles.special,
    depth,
    opts
  )
}

function inspectClass(ctor, depth, opts) {
  return new InspectLeaf(
    '[class ' + (ctor.name ? ctor.name : '(anonymous)') + ']',
    styles.special,
    depth,
    opts
  )
}

function inspectExternal(external, depth, opts) {
  return new InspectLeaf(
    '[external 0x' + binding.getExternal(external).toString(16) + ']',
    styles.special,
    depth,
    opts
  )
}
{
  "name": "bare-inspect",
  "version": "3.1.4",
  "description": "Inspect objects as strings for debugging",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-inspect.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-inspect/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-inspect#readme",
  "engines": {
    "bare": ">=1.18.0"
  },
  "dependencies": {
    "bare-ansi-escapes": "^2.1.0",
    "bare-type": "^1.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
module.exports = require.addon()
const binding = require('./binding')

const t = binding.constants

class Type {
  constructor(type) {
    this._type = type
  }

  isUndefined() {
    return this._type === t.UNDEFINED
  }

  isNull() {
    return this._type === t.NULL
  }

  isBoolean() {
    return this._type === t.BOOLEAN
  }

  isNumber() {
    return (this._type & 0xff) === t.NUMBER
  }

  isInt32() {
    return (this._type & (0xff | t.INT32)) === (t.NUMBER | t.INT32)
  }

  isUint32() {
    return (this._type & (0xff | t.UINT32)) === (t.NUMBER | t.UINT32)
  }

  isString() {
    return this._type === t.STRING
  }

  isSymbol() {
    return this._type === t.SYMBOL
  }

  isObject() {
    return (this._type & 0xff) === t.OBJECT
  }

  isArray() {
    return this._type === (t.OBJECT | t.ARRAY)
  }

  isArguments() {
    return this._type === (t.OBJECT | t.ARGUMENTS)
  }

  isDate() {
    return this._type === (t.OBJECT | t.DATE)
  }

  isRegExp() {
    return this._type === (t.OBJECT | t.REGEXP)
  }

  isError() {
    return this._type === (t.OBJECT | t.ERROR)
  }

  isPromise() {
    return this._type === (t.OBJECT | t.PROMISE)
  }

  isProxy() {
    return this._type === (t.OBJECT | t.PROXY)
  }

  isGenerator() {
    return this._type === (t.OBJECT | t.GENERATOR)
  }

  isMap() {
    return this._type === (t.OBJECT | t.MAP)
  }

  isSet() {
    return this._type === (t.OBJECT | t.SET)
  }

  isWeakMap() {
    return this._type === (t.OBJECT | t.WEAK_MAP)
  }

  isWeakSet() {
    return this._type === (t.OBJECT | t.WEAK_SET)
  }

  isWeakRef() {
    return this._type === (t.OBJECT | t.WEAK_REF)
  }

  isArrayBuffer() {
    return this._type === (t.OBJECT | t.ARRAYBUFFER)
  }

  isSharedArrayBuffer() {
    return this._type === (t.OBJECT | t.SHAREDARRAYBUFFER)
  }

  isTypedArray() {
    return (this._type & 0xffff) === (t.OBJECT | t.TYPEDARRAY)
  }

  isInt8Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT8ARRAY)
  }

  isUint8Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT8ARRAY)
  }

  isUint8ClampedArray() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT8CLAMPEDARRAY)
  }

  isInt16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT16ARRAY)
  }

  isUint16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT16ARRAY)
  }

  isInt32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT32ARRAY)
  }

  isUint32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT32ARRAY)
  }

  isFloat16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT16ARRAY)
  }

  isFloat32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT32ARRAY)
  }

  isFloat64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT64ARRAY)
  }

  isBigInt64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.BIGINT64ARRAY)
  }

  isBigUint64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.BIGUINT64ARRAY)
  }

  isDataView() {
    return this._type === (t.OBJECT | t.DATAVIEW)
  }

  isModuleNamespace() {
    return this._type === (t.OBJECT | t.MODULE_NAMESPACE)
  }

  isFunction() {
    return (this._type & 0xff) === t.FUNCTION
  }

  isAsyncFunction() {
    return (
      (this._type & (0xff | t.ASYNC_FUNCTION)) ===
      (t.FUNCTION | t.ASYNC_FUNCTION)
    )
  }

  isGeneratorFunction() {
    return (
      (this._type & (0xff | t.GENERATOR_FUNCTION)) ===
      (t.FUNCTION | t.GENERATOR_FUNCTION)
    )
  }

  isExternal() {
    return this._type === t.EXTERNAL
  }

  isBigInt() {
    return this._type === t.BIGINT
  }
}

module.exports = exports = function type(value) {
  switch (typeof value) {
    case 'undefined':
      return new Type(t.UNDEFINED)
    case 'boolean':
      return new Type(t.BOOLEAN)
    case 'number':
      return new Type(
        Number.isSafeInteger(value) ? binding.type(value) : t.NUMBER
      )
    case 'string':
      return new Type(t.STRING)
    case 'symbol':
      return new Type(t.SYMBOL)
    case 'object':
      return new Type(value === null ? t.NULL : binding.type(value))
    case 'function':
      return new Type(binding.type(value))
    case 'bigint':
      return new Type(t.BIGINT)
  }
}

exports.createTag = function createTag(...components) {
  const tag = new Uint32Array(4)
  for (let i = 0; i < 4; i++) tag[i] = components[i] || 0
  return tag
}

exports.addTag = function addTag(object, tag) {
  binding.addTag(object, tag)
}

exports.checkTag = function checkTag(object, tag) {
  return binding.checkTag(object, tag)
}
{
  "name": "bare-type",
  "version": "1.1.0",
  "description": "Cross-realm type predicates for Bare",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-type.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-type/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-type#readme",
  "engines": {
    "bare": ">=1.2.0"
  },
  "devDependencies": {
    "brittle": "^3.4.0",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
const sodium = require('sodium-universal')
const b4a = require('b4a')
const assert = require('nanoassert')
const { detectLanguage, loadWordlist } = require('./wordlist')

module.exports = {
  generateEntropy,
  generateMnemonic,
  normalizeMnemonic,
  validateMnemonic,
  mnemonicToEntropy,
  mnemonicToSeed,
  entropyToMnemonic
}

function generateMnemonic ({ entropy = generateEntropy(), language = 'english' } = {}) {
  const wordlist = loadWordlist(language)
  const extended = computeCheckSum(entropy)

  const words = []

  for (const index of uint11Reader(extended)) {
    words.push(wordlist[index])
  }

  const delimiter = language === 'japanese' ? '\u3000' : ' '

  return words.join(delimiter).trim()
}

function entropyToMnemonic (entropy, { language = 'english' } = {}) {
  return generateMnemonic({ entropy, language })
}

function mnemonicToEntropy (mnemonic) {
  const words = mnemonic.replace(/\u3000/g, ' ').trim().split(' ')
  const language = detectLanguage(words)

  if (!language) {
    throw new Error('Language not recognised')
  }

  if (words.length % 3 !== 0) {
    throw new Error('Invalid length')
  }

  const wordlist = loadWordlist(language)

  const indexes = []
  for (const word of words) {
    const index = wordlist.indexOf(word)
    if (index === -1) {
      throw new Error('Bad word')
    }

    indexes.push(index)
  }

  const bits = words.length * 11
  const len = (bits * 32 / 33) >> 3

  const extended = b4a.alloc(Math.ceil(bits / 8))
  const entropy = extended.subarray(0, len)

  uint11Writer(extended, indexes)

  if (!b4a.equals(extended, computeCheckSum(entropy))) {
    throw new Error('Invalid checksum')
  }

  return entropy
}

function normalizeMnemonic (mnemonic) {
  return mnemonic.trim().replace(/\u3000/, ' ').split(/\s+/).map(c => c.toLowerCase()).join(' ')
}

async function mnemonicToSeed (mnemonic, passphrase = '') {
  mnemonic = normalizeMnemonic(mnemonic)

  if (!validateMnemonic(mnemonic)) {
    throw new Error('Invalid mnemonic')
  }

  const input = b4a.from(mnemonic)
  const salt = b4a.from('mnemonic' + passphrase)

  const output = b4a.alloc(64)

  await sodium.extension_pbkdf2_sha512_async(
    output,
    input,
    salt,
    2048,
    64
  )

  return output
}

function validateMnemonic (mnemonic) {
  try {
    mnemonicToEntropy(mnemonic)
  } catch (e) {
    return false
  }
  return true
}

function sha256 (data, output = b4a.alloc(32)) {
  sodium.crypto_hash_sha256(output, data)
  return output
}

function computeCheckSum (seed) {
  assert((seed.byteLength & 4) === 0, 'seed must be a multiple of 4 bytes')

  const len = seed.byteLength
  const cklen = len >> 2 // cksum bits
  const total = len + Math.ceil(cklen / 8)

  const output = b4a.alloc(len + 32)
  output.set(seed)

  const entropy = output.subarray(0, len)
  const cksum = output.subarray(len)

  sha256(entropy, cksum)

  // only append cklen bits
  output[total - 1] &= (0xff ^ (0xff >> cklen))

  return output.subarray(0, total)
}

function generateEntropy (length = 32) {
  const seed = b4a.alloc(length)
  sodium.randombytes_buf(seed)

  return seed
}

function * uint11Reader (state) {
  yield * uintReader(state, 11)
}

function uint11Writer (buf, uints) {
  return uintWriter(buf, uints, 11)
}

function * uintReader (buffer, width) {
  const MASK = (2 << (width - 1)) - 1

  let pos = 0
  let value = 0

  while (true) {
    const offset = pos >> 3 // byte offset

    if (offset >= buffer.byteLength) {
      return value & MASK
    }

    const height = width - (pos % width)
    const leftover = (offset + 1) * 8 - pos

    value += shift(buffer[offset], height - leftover)

    pos += Math.min(height, leftover)
    if (pos % width) continue

    yield value & MASK

    value = 0
  }
}

function uintWriter (buffer, uints, width) {
  let pos = 0

  while (true) {
    const offset = pos >> 3 // byte offset

    const i = Math.floor(pos / width)
    if (i >= uints.length) break

    if (offset >= buffer.length) {
      throw new Error('Failed to encode uints')
    }

    const rem = 8 - pos % 8
    const height = (i + 1) * width - pos

    const value = shift(uints[i], rem - height)

    buffer[offset] += mask(value, rem)

    pos += Math.min(rem, height)
  }

  return buffer
}

// when n is positive, shift left n bits
// when n is negative, shift right -n bits
function shift (val, n) {
  if (n === 0) return val
  if (n > 0) return val << n

  return val >> (-1 * n)
}

function mask (val, bits) {
  if (bits < 32) return val & ((1 << bits) - 1)
  return val % (2 ** bits)
}
{
  "name": "bip39-mnemonic",
  "version": "2.5.0",
  "description": "BIP39 mnemonic for key derivation schemes",
  "main": "index.js",
  "scripts": {
    "generate-wordlist": "node scripts/generate-wordlist.js",
    "test": "standard && brittle test/*.js"
  },
  "author": "Holepunch Inc",
  "license": "Apache-2.0",
  "devDependencies": {
    "brittle": "^3.4.0",
    "standard": "^17.1.0"
  },
  "dependencies": {
    "b4a": "^1.6.6",
    "nanoassert": "^2.0.0",
    "sodium-universal": "^5.0.1"
  },
  "files": [
    "index.js",
    "wordlist"
  ],
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bip39.git"
  },
  "bugs": {
    "url": "https://github.com/holepunchto/bip39/issues"
  },
  "homepage": "https://github.com/holepunchto/bip39#readme"
}
["的","一","是","在","不","了","有","和","人","这","中","大","为","上","个","国","我","以","要","他","时","来","用","们","生","到","作","地","于","出","就","分","对","成","会","可","主","发","年","动","同","工","也","能","下","过","子","说","产","种","面","而","方","后","多","定","行","学","法","所","民","得","经","十","三","之","进","着","等","部","度","家","电","力","里","如","水","化","高","自","二","理","起","小","物","现","实","加","量","都","两","体","制","机","当","使","点","从","业","本","去","把","性","好","应","开","它","合","还","因","由","其","些","然","前","外","天","政","四","日","那","社","义","事","平","形","相","全","表","间","样","与","关","各","重","新","线","内","数","正","心","反","你","明","看","原","又","么","利","比","或","但","质","气","第","向","道","命","此","变","条","只","没","结","解","问","意","建","月","公","无","系","军","很","情","者","最","立","代","想","已","通","并","提","直","题","党","程","展","五","果","料","象","员","革","位","入","常","文","总","次","品","式","活","设","及","管","特","件","长","求","老","头","基","资","边","流","路","级","少","图","山","统","接","知","较","将","组","见","计","别","她","手","角","期","根","论","运","农","指","几","九","区","强","放","决","西","被","干","做","必","战","先","回","则","任","取","据","处","队","南","给","色","光","门","即","保","治","北","造","百","规","热","领","七","海","口","东","导","器","压","志","世","金","增","争","济","阶","油","思","术","极","交","受","联","什","认","六","共","权","收","证","改","清","美","再","采","转","更","单","风","切","打","白","教","速","花","带","安","场","身","车","例","真","务","具","万","每","目","至","达","走","积","示","议","声","报","斗","完","类","八","离","华","名","确","才","科","张","信","马","节","话","米","整","空","元","况","今","集","温","传","土","许","步","群","广","石","记","需","段","研","界","拉","林","律","叫","且","究","观","越","织","装","影","算","低","持","音","众","书","布","复","容","儿","须","际","商","非","验","连","断","深","难","近","矿","千","周","委","素","技","备","半","办","青","省","列","习","响","约","支","般","史","感","劳","便","团","往","酸","历","市","克","何","除","消","构","府","称","太","准","精","值","号","率","族","维","划","选","标","写","存","候","毛","亲","快","效","斯","院","查","江","型","眼","王","按","格","养","易","置","派","层","片","始","却","专","状","育","厂","京","识","适","属","圆","包","火","住","调","满","县","局","照","参","红","细","引","听","该","铁","价","严","首","底","液","官","德","随","病","苏","失","尔","死","讲","配","女","黄","推","显","谈","罪","神","艺","呢","席","含","企","望","密","批","营","项","防","举","球","英","氧","势","告","李","台","落","木","帮","轮","破","亚","师","围","注","远","字","材","排","供","河","态","封","另","施","减","树","溶","怎","止","案","言","士","均","武","固","叶","鱼","波","视","仅","费","紧","爱","左","章","早","朝","害","续","轻","服","试","食","充","兵","源","判","护","司","足","某","练","差","致","板","田","降","黑","犯","负","击","范","继","兴","似","余","坚","曲","输","修","故","城","夫","够","送","笔","船","占","右","财","吃","富","春","职","觉","汉","画","功","巴","跟","虽","杂","飞","检","吸","助","升","阳","互","初","创","抗","考","投","坏","策","古","径","换","未","跑","留","钢","曾","端","责","站","简","述","钱","副","尽","帝","射","草","冲","承","独","令","限","阿","宣","环","双","请","超","微","让","控","州","良","轴","找","否","纪","益","依","优","顶","础","载","倒","房","突","坐","粉","敌","略","客","袁","冷","胜","绝","析","块","剂","测","丝","协","诉","念","陈","仍","罗","盐","友","洋","错","苦","夜","刑","移","频","逐","靠","混","母","短","皮","终","聚","汽","村","云","哪","既","距","卫","停","烈","央","察","烧","迅","境","若","印","洲","刻","括","激","孔","搞","甚","室","待","核","校","散","侵","吧","甲","游","久","菜","味","旧","模","湖","货","损","预","阻","毫","普","稳","乙","妈","植","息","扩","银","语","挥","酒","守","拿","序","纸","医","缺","雨","吗","针","刘","啊","急","唱","误","训","愿","审","附","获","茶","鲜","粮","斤","孩","脱","硫","肥","善","龙","演","父","渐","血","欢","械","掌","歌","沙","刚","攻","谓","盾","讨","晚","粒","乱","燃","矛","乎","杀","药","宁","鲁","贵","钟","煤","读","班","伯","香","介","迫","句","丰","培","握","兰","担","弦","蛋","沉","假","穿","执","答","乐","谁","顺","烟","缩","征","脸","喜","松","脚","困","异","免","背","星","福","买","染","井","概","慢","怕","磁","倍","祖","皇","促","静","补","评","翻","肉","践","尼","衣","宽","扬","棉","希","伤","操","垂","秋","宜","氢","套","督","振","架","亮","末","宪","庆","编","牛","触","映","雷","销","诗","座","居","抓","裂","胞","呼","娘","景","威","绿","晶","厚","盟","衡","鸡","孙","延","危","胶","屋","乡","临","陆","顾","掉","呀","灯","岁","措","束","耐","剧","玉","赵","跳","哥","季","课","凯","胡","额","款","绍","卷","齐","伟","蒸","殖","永","宗","苗","川","炉","岩","弱","零","杨","奏","沿","露","杆","探","滑","镇","饭","浓","航","怀","赶","库","夺","伊","灵","税","途","灭","赛","归","召","鼓","播","盘","裁","险","康","唯","录","菌","纯","借","糖","盖","横","符","私","努","堂","域","枪","润","幅","哈","竟","熟","虫","泽","脑","壤","碳","欧","遍","侧","寨","敢","彻","虑","斜","薄","庭","纳","弹","饲","伸","折","麦","湿","暗","荷","瓦","塞","床","筑","恶","户","访","塔","奇","透","梁","刀","旋","迹","卡","氯","遇","份","毒","泥","退","洗","摆","灰","彩","卖","耗","夏","择","忙","铜","献","硬","予","繁","圈","雪","函","亦","抽","篇","阵","阴","丁","尺","追","堆","雄","迎","泛","爸","楼","避","谋","吨","野","猪","旗","累","偏","典","馆","索","秦","脂","潮","爷","豆","忽","托","惊","塑","遗","愈","朱","替","纤","粗","倾","尚","痛","楚","谢","奋","购","磨","君","池","旁","碎","骨","监","捕","弟","暴","割","贯","殊","释","词","亡","壁","顿","宝","午","尘","闻","揭","炮","残","冬","桥","妇","警","综","招","吴","付","浮","遭","徐","您","摇","谷","赞","箱","隔","订","男","吹","园","纷","唐","败","宋","玻","巨","耕","坦","荣","闭","湾","键","凡","驻","锅","救","恩","剥","凝","碱","齿","截","炼","麻","纺","禁","废","盛","版","缓","净","睛","昌","婚","涉","筒","嘴","插","岸","朗","庄","街","藏","姑","贸","腐","奴","啦","惯","乘","伙","恢","匀","纱","扎","辩","耳","彪","臣","亿","璃","抵","脉","秀","萨","俄","网","舞","店","喷","纵","寸","汗","挂","洪","贺","闪","柬","爆","烯","津","稻","墙","软","勇","像","滚","厘","蒙","芳","肯","坡","柱","荡","腿","仪","旅","尾","轧","冰","贡","登","黎","削","钻","勒","逃","障","氨","郭","峰","币","港","伏","轨","亩","毕","擦","莫","刺","浪","秘","援","株","健","售","股","岛","甘","泡","睡","童","铸","汤","阀","休","汇","舍","牧","绕","炸","哲","磷","绩","朋","淡","尖","启","陷","柴","呈","徒","颜","泪","稍","忘","泵","蓝","拖","洞","授","镜","辛","壮","锋","贫","虚","弯","摩","泰","幼","廷","尊","窗","纲","弄","隶","疑","氏","宫","姐","震","瑞","怪","尤","琴","循","描","膜","违","夹","腰","缘","珠","穷","森","枝","竹","沟","催","绳","忆","邦","剩","幸","浆","栏","拥","牙","贮","礼","滤","钠","纹","罢","拍","咱","喊","袖","埃","勤","罚","焦","潜","伍","墨","欲","缝","姓","刊","饱","仿","奖","铝","鬼","丽","跨","默","挖","链","扫","喝","袋","炭","污","幕","诸","弧","励","梅","奶","洁","灾","舟","鉴","苯","讼","抱","毁","懂","寒","智","埔","寄","届","跃","渡","挑","丹","艰","贝","碰","拔","爹","戴","码","梦","芽","熔","赤","渔","哭","敬","颗","奔","铅","仲","虎","稀","妹","乏","珍","申","桌","遵","允","隆","螺","仓","魏","锐","晓","氮","兼","隐","碍","赫","拨","忠","肃","缸","牵","抢","博","巧","壳","兄","杜","讯","诚","碧","祥","柯","页","巡","矩","悲","灌","龄","伦","票","寻","桂","铺","圣","恐","恰","郑","趣","抬","荒","腾","贴","柔","滴","猛","阔","辆","妻","填","撤","储","签","闹","扰","紫","砂","递","戏","吊","陶","伐","喂","疗","瓶","婆","抚","臂","摸","忍","虾","蜡","邻","胸","巩","挤","偶","弃","槽","劲","乳","邓","吉","仁","烂","砖","租","乌","舰","伴","瓜","浅","丙","暂","燥","橡","柳","迷","暖","牌","秧","胆","详","簧","踏","瓷","谱","呆","宾","糊","洛","辉","愤","竞","隙","怒","粘","乃","绪","肩","籍","敏","涂","熙","皆","侦","悬","掘","享","纠","醒","狂","锁","淀","恨","牲","霸","爬","赏","逆","玩","陵","祝","秒","浙","貌","役","彼","悉","鸭","趋","凤","晨","畜","辈","秩","卵","署","梯","炎","滩","棋","驱","筛","峡","冒","啥","寿","译","浸","泉","帽","迟","硅","疆","贷","漏","稿","冠","嫩","胁","芯","牢","叛","蚀","奥","鸣","岭","羊","凭","串","塘","绘","酵","融","盆","锡","庙","筹","冻","辅","摄","袭","筋","拒","僚","旱","钾","鸟","漆","沈","眉","疏","添","棒","穗","硝","韩","逼","扭","侨","凉","挺","碗","栽","炒","杯","患","馏","劝","豪","辽","勃","鸿","旦","吏","拜","狗","埋","辊","掩","饮","搬","骂","辞","勾","扣","估","蒋","绒","雾","丈","朵","姆","拟","宇","辑","陕","雕","偿","蓄","崇","剪","倡","厅","咬","驶","薯","刷","斥","番","赋","奉","佛","浇","漫","曼","扇","钙","桃","扶","仔","返","俗","亏","腔","鞋","棱","覆","框","悄","叔","撞","骗","勘","旺","沸","孤","吐","孟","渠","屈","疾","妙","惜","仰","狠","胀","谐","抛","霉","桑","岗","嘛","衰","盗","渗","脏","赖","涌","甜","曹","阅","肌","哩","厉","烃","纬","毅","昨","伪","症","煮","叹","钉","搭","茎","笼","酷","偷","弓","锥","恒","杰","坑","鼻","翼","纶","叙","狱","逮","罐","络","棚","抑","膨","蔬","寺","骤","穆","冶","枯","册","尸","凸","绅","坯","牺","焰","轰","欣","晋","瘦","御","锭","锦","丧","旬","锻","垄","搜","扑","邀","亭","酯","迈","舒","脆","酶","闲","忧","酚","顽","羽","涨","卸","仗","陪","辟","惩","杭","姚","肚","捉","飘","漂","昆","欺","吾","郎","烷","汁","呵","饰","萧","雅","邮","迁","燕","撒","姻","赴","宴","烦","债","帐","斑","铃","旨","醇","董","饼","雏","姿","拌","傅","腹","妥","揉","贤","拆","歪","葡","胺","丢","浩","徽","昂","垫","挡","览","贪","慰","缴","汪","慌","冯","诺","姜","谊","凶","劣","诬","耀","昏","躺","盈","骑","乔","溪","丛","卢","抹","闷","咨","刮","驾","缆","悟","摘","铒","掷","颇","幻","柄","惠","惨","佳","仇","腊","窝","涤","剑","瞧","堡","泼","葱","罩","霍","捞","胎","苍","滨","俩","捅","湘","砍","霞","邵","萄","疯","淮","遂","熊","粪","烘","宿","档","戈","驳","嫂","裕","徙","箭","捐","肠","撑","晒","辨","殿","莲","摊","搅","酱","屏","疫","哀","蔡","堵","沫","皱","畅","叠","阁","莱","敲","辖","钩","痕","坝","巷","饿","祸","丘","玄","溜","曰","逻","彭","尝","卿","妨","艇","吞","韦","怨","矮","歇"]["的","一","是","在","不","了","有","和","人","這","中","大","為","上","個","國","我","以","要","他","時","來","用","們","生","到","作","地","於","出","就","分","對","成","會","可","主","發","年","動","同","工","也","能","下","過","子","說","產","種","面","而","方","後","多","定","行","學","法","所","民","得","經","十","三","之","進","著","等","部","度","家","電","力","裡","如","水","化","高","自","二","理","起","小","物","現","實","加","量","都","兩","體","制","機","當","使","點","從","業","本","去","把","性","好","應","開","它","合","還","因","由","其","些","然","前","外","天","政","四","日","那","社","義","事","平","形","相","全","表","間","樣","與","關","各","重","新","線","內","數","正","心","反","你","明","看","原","又","麼","利","比","或","但","質","氣","第","向","道","命","此","變","條","只","沒","結","解","問","意","建","月","公","無","系","軍","很","情","者","最","立","代","想","已","通","並","提","直","題","黨","程","展","五","果","料","象","員","革","位","入","常","文","總","次","品","式","活","設","及","管","特","件","長","求","老","頭","基","資","邊","流","路","級","少","圖","山","統","接","知","較","將","組","見","計","別","她","手","角","期","根","論","運","農","指","幾","九","區","強","放","決","西","被","幹","做","必","戰","先","回","則","任","取","據","處","隊","南","給","色","光","門","即","保","治","北","造","百","規","熱","領","七","海","口","東","導","器","壓","志","世","金","增","爭","濟","階","油","思","術","極","交","受","聯","什","認","六","共","權","收","證","改","清","美","再","採","轉","更","單","風","切","打","白","教","速","花","帶","安","場","身","車","例","真","務","具","萬","每","目","至","達","走","積","示","議","聲","報","鬥","完","類","八","離","華","名","確","才","科","張","信","馬","節","話","米","整","空","元","況","今","集","溫","傳","土","許","步","群","廣","石","記","需","段","研","界","拉","林","律","叫","且","究","觀","越","織","裝","影","算","低","持","音","眾","書","布","复","容","兒","須","際","商","非","驗","連","斷","深","難","近","礦","千","週","委","素","技","備","半","辦","青","省","列","習","響","約","支","般","史","感","勞","便","團","往","酸","歷","市","克","何","除","消","構","府","稱","太","準","精","值","號","率","族","維","劃","選","標","寫","存","候","毛","親","快","效","斯","院","查","江","型","眼","王","按","格","養","易","置","派","層","片","始","卻","專","狀","育","廠","京","識","適","屬","圓","包","火","住","調","滿","縣","局","照","參","紅","細","引","聽","該","鐵","價","嚴","首","底","液","官","德","隨","病","蘇","失","爾","死","講","配","女","黃","推","顯","談","罪","神","藝","呢","席","含","企","望","密","批","營","項","防","舉","球","英","氧","勢","告","李","台","落","木","幫","輪","破","亞","師","圍","注","遠","字","材","排","供","河","態","封","另","施","減","樹","溶","怎","止","案","言","士","均","武","固","葉","魚","波","視","僅","費","緊","愛","左","章","早","朝","害","續","輕","服","試","食","充","兵","源","判","護","司","足","某","練","差","致","板","田","降","黑","犯","負","擊","范","繼","興","似","餘","堅","曲","輸","修","故","城","夫","夠","送","筆","船","佔","右","財","吃","富","春","職","覺","漢","畫","功","巴","跟","雖","雜","飛","檢","吸","助","昇","陽","互","初","創","抗","考","投","壞","策","古","徑","換","未","跑","留","鋼","曾","端","責","站","簡","述","錢","副","盡","帝","射","草","衝","承","獨","令","限","阿","宣","環","雙","請","超","微","讓","控","州","良","軸","找","否","紀","益","依","優","頂","礎","載","倒","房","突","坐","粉","敵","略","客","袁","冷","勝","絕","析","塊","劑","測","絲","協","訴","念","陳","仍","羅","鹽","友","洋","錯","苦","夜","刑","移","頻","逐","靠","混","母","短","皮","終","聚","汽","村","雲","哪","既","距","衛","停","烈","央","察","燒","迅","境","若","印","洲","刻","括","激","孔","搞","甚","室","待","核","校","散","侵","吧","甲","遊","久","菜","味","舊","模","湖","貨","損","預","阻","毫","普","穩","乙","媽","植","息","擴","銀","語","揮","酒","守","拿","序","紙","醫","缺","雨","嗎","針","劉","啊","急","唱","誤","訓","願","審","附","獲","茶","鮮","糧","斤","孩","脫","硫","肥","善","龍","演","父","漸","血","歡","械","掌","歌","沙","剛","攻","謂","盾","討","晚","粒","亂","燃","矛","乎","殺","藥","寧","魯","貴","鐘","煤","讀","班","伯","香","介","迫","句","豐","培","握","蘭","擔","弦","蛋","沉","假","穿","執","答","樂","誰","順","煙","縮","徵","臉","喜","松","腳","困","異","免","背","星","福","買","染","井","概","慢","怕","磁","倍","祖","皇","促","靜","補","評","翻","肉","踐","尼","衣","寬","揚","棉","希","傷","操","垂","秋","宜","氫","套","督","振","架","亮","末","憲","慶","編","牛","觸","映","雷","銷","詩","座","居","抓","裂","胞","呼","娘","景","威","綠","晶","厚","盟","衡","雞","孫","延","危","膠","屋","鄉","臨","陸","顧","掉","呀","燈","歲","措","束","耐","劇","玉","趙","跳","哥","季","課","凱","胡","額","款","紹","卷","齊","偉","蒸","殖","永","宗","苗","川","爐","岩","弱","零","楊","奏","沿","露","桿","探","滑","鎮","飯","濃","航","懷","趕","庫","奪","伊","靈","稅","途","滅","賽","歸","召","鼓","播","盤","裁","險","康","唯","錄","菌","純","借","糖","蓋","橫","符","私","努","堂","域","槍","潤","幅","哈","竟","熟","蟲","澤","腦","壤","碳","歐","遍","側","寨","敢","徹","慮","斜","薄","庭","納","彈","飼","伸","折","麥","濕","暗","荷","瓦","塞","床","築","惡","戶","訪","塔","奇","透","梁","刀","旋","跡","卡","氯","遇","份","毒","泥","退","洗","擺","灰","彩","賣","耗","夏","擇","忙","銅","獻","硬","予","繁","圈","雪","函","亦","抽","篇","陣","陰","丁","尺","追","堆","雄","迎","泛","爸","樓","避","謀","噸","野","豬","旗","累","偏","典","館","索","秦","脂","潮","爺","豆","忽","托","驚","塑","遺","愈","朱","替","纖","粗","傾","尚","痛","楚","謝","奮","購","磨","君","池","旁","碎","骨","監","捕","弟","暴","割","貫","殊","釋","詞","亡","壁","頓","寶","午","塵","聞","揭","炮","殘","冬","橋","婦","警","綜","招","吳","付","浮","遭","徐","您","搖","谷","贊","箱","隔","訂","男","吹","園","紛","唐","敗","宋","玻","巨","耕","坦","榮","閉","灣","鍵","凡","駐","鍋","救","恩","剝","凝","鹼","齒","截","煉","麻","紡","禁","廢","盛","版","緩","淨","睛","昌","婚","涉","筒","嘴","插","岸","朗","莊","街","藏","姑","貿","腐","奴","啦","慣","乘","夥","恢","勻","紗","扎","辯","耳","彪","臣","億","璃","抵","脈","秀","薩","俄","網","舞","店","噴","縱","寸","汗","掛","洪","賀","閃","柬","爆","烯","津","稻","牆","軟","勇","像","滾","厘","蒙","芳","肯","坡","柱","盪","腿","儀","旅","尾","軋","冰","貢","登","黎","削","鑽","勒","逃","障","氨","郭","峰","幣","港","伏","軌","畝","畢","擦","莫","刺","浪","秘","援","株","健","售","股","島","甘","泡","睡","童","鑄","湯","閥","休","匯","舍","牧","繞","炸","哲","磷","績","朋","淡","尖","啟","陷","柴","呈","徒","顏","淚","稍","忘","泵","藍","拖","洞","授","鏡","辛","壯","鋒","貧","虛","彎","摩","泰","幼","廷","尊","窗","綱","弄","隸","疑","氏","宮","姐","震","瑞","怪","尤","琴","循","描","膜","違","夾","腰","緣","珠","窮","森","枝","竹","溝","催","繩","憶","邦","剩","幸","漿","欄","擁","牙","貯","禮","濾","鈉","紋","罷","拍","咱","喊","袖","埃","勤","罰","焦","潛","伍","墨","欲","縫","姓","刊","飽","仿","獎","鋁","鬼","麗","跨","默","挖","鏈","掃","喝","袋","炭","污","幕","諸","弧","勵","梅","奶","潔","災","舟","鑑","苯","訟","抱","毀","懂","寒","智","埔","寄","屆","躍","渡","挑","丹","艱","貝","碰","拔","爹","戴","碼","夢","芽","熔","赤","漁","哭","敬","顆","奔","鉛","仲","虎","稀","妹","乏","珍","申","桌","遵","允","隆","螺","倉","魏","銳","曉","氮","兼","隱","礙","赫","撥","忠","肅","缸","牽","搶","博","巧","殼","兄","杜","訊","誠","碧","祥","柯","頁","巡","矩","悲","灌","齡","倫","票","尋","桂","鋪","聖","恐","恰","鄭","趣","抬","荒","騰","貼","柔","滴","猛","闊","輛","妻","填","撤","儲","簽","鬧","擾","紫","砂","遞","戲","吊","陶","伐","餵","療","瓶","婆","撫","臂","摸","忍","蝦","蠟","鄰","胸","鞏","擠","偶","棄","槽","勁","乳","鄧","吉","仁","爛","磚","租","烏","艦","伴","瓜","淺","丙","暫","燥","橡","柳","迷","暖","牌","秧","膽","詳","簧","踏","瓷","譜","呆","賓","糊","洛","輝","憤","競","隙","怒","粘","乃","緒","肩","籍","敏","塗","熙","皆","偵","懸","掘","享","糾","醒","狂","鎖","淀","恨","牲","霸","爬","賞","逆","玩","陵","祝","秒","浙","貌","役","彼","悉","鴨","趨","鳳","晨","畜","輩","秩","卵","署","梯","炎","灘","棋","驅","篩","峽","冒","啥","壽","譯","浸","泉","帽","遲","矽","疆","貸","漏","稿","冠","嫩","脅","芯","牢","叛","蝕","奧","鳴","嶺","羊","憑","串","塘","繪","酵","融","盆","錫","廟","籌","凍","輔","攝","襲","筋","拒","僚","旱","鉀","鳥","漆","沈","眉","疏","添","棒","穗","硝","韓","逼","扭","僑","涼","挺","碗","栽","炒","杯","患","餾","勸","豪","遼","勃","鴻","旦","吏","拜","狗","埋","輥","掩","飲","搬","罵","辭","勾","扣","估","蔣","絨","霧","丈","朵","姆","擬","宇","輯","陝","雕","償","蓄","崇","剪","倡","廳","咬","駛","薯","刷","斥","番","賦","奉","佛","澆","漫","曼","扇","鈣","桃","扶","仔","返","俗","虧","腔","鞋","棱","覆","框","悄","叔","撞","騙","勘","旺","沸","孤","吐","孟","渠","屈","疾","妙","惜","仰","狠","脹","諧","拋","黴","桑","崗","嘛","衰","盜","滲","臟","賴","湧","甜","曹","閱","肌","哩","厲","烴","緯","毅","昨","偽","症","煮","嘆","釘","搭","莖","籠","酷","偷","弓","錐","恆","傑","坑","鼻","翼","綸","敘","獄","逮","罐","絡","棚","抑","膨","蔬","寺","驟","穆","冶","枯","冊","屍","凸","紳","坯","犧","焰","轟","欣","晉","瘦","禦","錠","錦","喪","旬","鍛","壟","搜","撲","邀","亭","酯","邁","舒","脆","酶","閒","憂","酚","頑","羽","漲","卸","仗","陪","闢","懲","杭","姚","肚","捉","飄","漂","昆","欺","吾","郎","烷","汁","呵","飾","蕭","雅","郵","遷","燕","撒","姻","赴","宴","煩","債","帳","斑","鈴","旨","醇","董","餅","雛","姿","拌","傅","腹","妥","揉","賢","拆","歪","葡","胺","丟","浩","徽","昂","墊","擋","覽","貪","慰","繳","汪","慌","馮","諾","姜","誼","兇","劣","誣","耀","昏","躺","盈","騎","喬","溪","叢","盧","抹","悶","諮","刮","駕","纜","悟","摘","鉺","擲","頗","幻","柄","惠","慘","佳","仇","臘","窩","滌","劍","瞧","堡","潑","蔥","罩","霍","撈","胎","蒼","濱","倆","捅","湘","砍","霞","邵","萄","瘋","淮","遂","熊","糞","烘","宿","檔","戈","駁","嫂","裕","徙","箭","捐","腸","撐","曬","辨","殿","蓮","攤","攪","醬","屏","疫","哀","蔡","堵","沫","皺","暢","疊","閣","萊","敲","轄","鉤","痕","壩","巷","餓","禍","丘","玄","溜","曰","邏","彭","嘗","卿","妨","艇","吞","韋","怨","矮","歇"]["abdikace","abeceda","adresa","agrese","akce","aktovka","alej","alkohol","amputace","ananas","andulka","anekdota","anketa","antika","anulovat","archa","arogance","asfalt","asistent","aspirace","astma","astronom","atlas","atletika","atol","autobus","azyl","babka","bachor","bacil","baculka","badatel","bageta","bagr","bahno","bakterie","balada","baletka","balkon","balonek","balvan","balza","bambus","bankomat","barbar","baret","barman","baroko","barva","baterka","batoh","bavlna","bazalka","bazilika","bazuka","bedna","beran","beseda","bestie","beton","bezinka","bezmoc","beztak","bicykl","bidlo","biftek","bikiny","bilance","biograf","biolog","bitva","bizon","blahobyt","blatouch","blecha","bledule","blesk","blikat","blizna","blokovat","bloudit","blud","bobek","bobr","bodlina","bodnout","bohatost","bojkot","bojovat","bokorys","bolest","borec","borovice","bota","boubel","bouchat","bouda","boule","bourat","boxer","bradavka","brambora","branka","bratr","brepta","briketa","brko","brloh","bronz","broskev","brunetka","brusinka","brzda","brzy","bublina","bubnovat","buchta","buditel","budka","budova","bufet","bujarost","bukvice","buldok","bulva","bunda","bunkr","burza","butik","buvol","buzola","bydlet","bylina","bytovka","bzukot","capart","carevna","cedr","cedule","cejch","cejn","cela","celer","celkem","celnice","cenina","cennost","cenovka","centrum","cenzor","cestopis","cetka","chalupa","chapadlo","charita","chata","chechtat","chemie","chichot","chirurg","chlad","chleba","chlubit","chmel","chmura","chobot","chochol","chodba","cholera","chomout","chopit","choroba","chov","chrapot","chrlit","chrt","chrup","chtivost","chudina","chutnat","chvat","chvilka","chvost","chyba","chystat","chytit","cibule","cigareta","cihelna","cihla","cinkot","cirkus","cisterna","citace","citrus","cizinec","cizost","clona","cokoliv","couvat","ctitel","ctnost","cudnost","cuketa","cukr","cupot","cvaknout","cval","cvik","cvrkot","cyklista","daleko","dareba","datel","datum","dcera","debata","dechovka","decibel","deficit","deflace","dekl","dekret","demokrat","deprese","derby","deska","detektiv","dikobraz","diktovat","dioda","diplom","disk","displej","divadlo","divoch","dlaha","dlouho","dluhopis","dnes","dobro","dobytek","docent","dochutit","dodnes","dohled","dohoda","dohra","dojem","dojnice","doklad","dokola","doktor","dokument","dolar","doleva","dolina","doma","dominant","domluvit","domov","donutit","dopad","dopis","doplnit","doposud","doprovod","dopustit","dorazit","dorost","dort","dosah","doslov","dostatek","dosud","dosyta","dotaz","dotek","dotknout","doufat","doutnat","dovozce","dozadu","doznat","dozorce","drahota","drak","dramatik","dravec","draze","drdol","drobnost","drogerie","drozd","drsnost","drtit","drzost","duben","duchovno","dudek","duha","duhovka","dusit","dusno","dutost","dvojice","dvorec","dynamit","ekolog","ekonomie","elektron","elipsa","email","emise","emoce","empatie","epizoda","epocha","epopej","epos","esej","esence","eskorta","eskymo","etiketa","euforie","evoluce","exekuce","exkurze","expedice","exploze","export","extrakt","facka","fajfka","fakulta","fanatik","fantazie","farmacie","favorit","fazole","federace","fejeton","fenka","fialka","figurant","filozof","filtr","finance","finta","fixace","fjord","flanel","flirt","flotila","fond","fosfor","fotbal","fotka","foton","frakce","freska","fronta","fukar","funkce","fyzika","galeje","garant","genetika","geolog","gilotina","glazura","glejt","golem","golfista","gotika","graf","gramofon","granule","grep","gril","grog","groteska","guma","hadice","hadr","hala","halenka","hanba","hanopis","harfa","harpuna","havran","hebkost","hejkal","hejno","hejtman","hektar","helma","hematom","herec","herna","heslo","hezky","historik","hladovka","hlasivky","hlava","hledat","hlen","hlodavec","hloh","hloupost","hltat","hlubina","hluchota","hmat","hmota","hmyz","hnis","hnojivo","hnout","hoblina","hoboj","hoch","hodiny","hodlat","hodnota","hodovat","hojnost","hokej","holinka","holka","holub","homole","honitba","honorace","horal","horda","horizont","horko","horlivec","hormon","hornina","horoskop","horstvo","hospoda","hostina","hotovost","houba","houf","houpat","houska","hovor","hradba","hranice","hravost","hrazda","hrbolek","hrdina","hrdlo","hrdost","hrnek","hrobka","hromada","hrot","hrouda","hrozen","hrstka","hrubost","hryzat","hubenost","hubnout","hudba","hukot","humr","husita","hustota","hvozd","hybnost","hydrant","hygiena","hymna","hysterik","idylka","ihned","ikona","iluze","imunita","infekce","inflace","inkaso","inovace","inspekce","internet","invalida","investor","inzerce","ironie","jablko","jachta","jahoda","jakmile","jakost","jalovec","jantar","jarmark","jaro","jasan","jasno","jatka","javor","jazyk","jedinec","jedle","jednatel","jehlan","jekot","jelen","jelito","jemnost","jenom","jepice","jeseter","jevit","jezdec","jezero","jinak","jindy","jinoch","jiskra","jistota","jitrnice","jizva","jmenovat","jogurt","jurta","kabaret","kabel","kabinet","kachna","kadet","kadidlo","kahan","kajak","kajuta","kakao","kaktus","kalamita","kalhoty","kalibr","kalnost","kamera","kamkoliv","kamna","kanibal","kanoe","kantor","kapalina","kapela","kapitola","kapka","kaple","kapota","kapr","kapusta","kapybara","karamel","karotka","karton","kasa","katalog","katedra","kauce","kauza","kavalec","kazajka","kazeta","kazivost","kdekoliv","kdesi","kedluben","kemp","keramika","kino","klacek","kladivo","klam","klapot","klasika","klaun","klec","klenba","klepat","klesnout","klid","klima","klisna","klobouk","klokan","klopa","kloub","klubovna","klusat","kluzkost","kmen","kmitat","kmotr","kniha","knot","koalice","koberec","kobka","kobliha","kobyla","kocour","kohout","kojenec","kokos","koktejl","kolaps","koleda","kolize","kolo","komando","kometa","komik","komnata","komora","kompas","komunita","konat","koncept","kondice","konec","konfese","kongres","konina","konkurs","kontakt","konzerva","kopanec","kopie","kopnout","koprovka","korbel","korektor","kormidlo","koroptev","korpus","koruna","koryto","korzet","kosatec","kostka","kotel","kotleta","kotoul","koukat","koupelna","kousek","kouzlo","kovboj","koza","kozoroh","krabice","krach","krajina","kralovat","krasopis","kravata","kredit","krejcar","kresba","kreveta","kriket","kritik","krize","krkavec","krmelec","krmivo","krocan","krok","kronika","kropit","kroupa","krovka","krtek","kruhadlo","krupice","krutost","krvinka","krychle","krypta","krystal","kryt","kudlanka","kufr","kujnost","kukla","kulajda","kulich","kulka","kulomet","kultura","kuna","kupodivu","kurt","kurzor","kutil","kvalita","kvasinka","kvestor","kynolog","kyselina","kytara","kytice","kytka","kytovec","kyvadlo","labrador","lachtan","ladnost","laik","lakomec","lamela","lampa","lanovka","lasice","laso","lastura","latinka","lavina","lebka","leckdy","leden","lednice","ledovka","ledvina","legenda","legie","legrace","lehce","lehkost","lehnout","lektvar","lenochod","lentilka","lepenka","lepidlo","letadlo","letec","letmo","letokruh","levhart","levitace","levobok","libra","lichotka","lidojed","lidskost","lihovina","lijavec","lilek","limetka","linie","linka","linoleum","listopad","litina","litovat","lobista","lodivod","logika","logoped","lokalita","loket","lomcovat","lopata","lopuch","lord","losos","lotr","loudal","louh","louka","louskat","lovec","lstivost","lucerna","lucifer","lump","lusk","lustrace","lvice","lyra","lyrika","lysina","madam","madlo","magistr","mahagon","majetek","majitel","majorita","makak","makovice","makrela","malba","malina","malovat","malvice","maminka","mandle","manko","marnost","masakr","maskot","masopust","matice","matrika","maturita","mazanec","mazivo","mazlit","mazurka","mdloba","mechanik","meditace","medovina","melasa","meloun","mentolka","metla","metoda","metr","mezera","migrace","mihnout","mihule","mikina","mikrofon","milenec","milimetr","milost","mimika","mincovna","minibar","minomet","minulost","miska","mistr","mixovat","mladost","mlha","mlhovina","mlok","mlsat","mluvit","mnich","mnohem","mobil","mocnost","modelka","modlitba","mohyla","mokro","molekula","momentka","monarcha","monokl","monstrum","montovat","monzun","mosaz","moskyt","most","motivace","motorka","motyka","moucha","moudrost","mozaika","mozek","mozol","mramor","mravenec","mrkev","mrtvola","mrzet","mrzutost","mstitel","mudrc","muflon","mulat","mumie","munice","muset","mutace","muzeum","muzikant","myslivec","mzda","nabourat","nachytat","nadace","nadbytek","nadhoz","nadobro","nadpis","nahlas","nahnat","nahodile","nahradit","naivita","najednou","najisto","najmout","naklonit","nakonec","nakrmit","nalevo","namazat","namluvit","nanometr","naoko","naopak","naostro","napadat","napevno","naplnit","napnout","naposled","naprosto","narodit","naruby","narychlo","nasadit","nasekat","naslepo","nastat","natolik","navenek","navrch","navzdory","nazvat","nebe","nechat","necky","nedaleko","nedbat","neduh","negace","nehet","nehoda","nejen","nejprve","neklid","nelibost","nemilost","nemoc","neochota","neonka","nepokoj","nerost","nerv","nesmysl","nesoulad","netvor","neuron","nevina","nezvykle","nicota","nijak","nikam","nikdy","nikl","nikterak","nitro","nocleh","nohavice","nominace","nora","norek","nositel","nosnost","nouze","noviny","novota","nozdra","nuda","nudle","nuget","nutit","nutnost","nutrie","nymfa","obal","obarvit","obava","obdiv","obec","obehnat","obejmout","obezita","obhajoba","obilnice","objasnit","objekt","obklopit","oblast","oblek","obliba","obloha","obluda","obnos","obohatit","obojek","obout","obrazec","obrna","obruba","obrys","obsah","obsluha","obstarat","obuv","obvaz","obvinit","obvod","obvykle","obyvatel","obzor","ocas","ocel","ocenit","ochladit","ochota","ochrana","ocitnout","odboj","odbyt","odchod","odcizit","odebrat","odeslat","odevzdat","odezva","odhadce","odhodit","odjet","odjinud","odkaz","odkoupit","odliv","odluka","odmlka","odolnost","odpad","odpis","odplout","odpor","odpustit","odpykat","odrazka","odsoudit","odstup","odsun","odtok","odtud","odvaha","odveta","odvolat","odvracet","odznak","ofina","ofsajd","ohlas","ohnisko","ohrada","ohrozit","ohryzek","okap","okenice","oklika","okno","okouzlit","okovy","okrasa","okres","okrsek","okruh","okupant","okurka","okusit","olejnina","olizovat","omak","omeleta","omezit","omladina","omlouvat","omluva","omyl","onehdy","opakovat","opasek","operace","opice","opilost","opisovat","opora","opozice","opravdu","oproti","orbital","orchestr","orgie","orlice","orloj","ortel","osada","oschnout","osika","osivo","oslava","oslepit","oslnit","oslovit","osnova","osoba","osolit","ospalec","osten","ostraha","ostuda","ostych","osvojit","oteplit","otisk","otop","otrhat","otrlost","otrok","otruby","otvor","ovanout","ovar","oves","ovlivnit","ovoce","oxid","ozdoba","pachatel","pacient","padouch","pahorek","pakt","palanda","palec","palivo","paluba","pamflet","pamlsek","panenka","panika","panna","panovat","panstvo","pantofle","paprika","parketa","parodie","parta","paruka","paryba","paseka","pasivita","pastelka","patent","patrona","pavouk","pazneht","pazourek","pecka","pedagog","pejsek","peklo","peloton","penalta","pendrek","penze","periskop","pero","pestrost","petarda","petice","petrolej","pevnina","pexeso","pianista","piha","pijavice","pikle","piknik","pilina","pilnost","pilulka","pinzeta","pipeta","pisatel","pistole","pitevna","pivnice","pivovar","placenta","plakat","plamen","planeta","plastika","platit","plavidlo","plaz","plech","plemeno","plenta","ples","pletivo","plevel","plivat","plnit","plno","plocha","plodina","plomba","plout","pluk","plyn","pobavit","pobyt","pochod","pocit","poctivec","podat","podcenit","podepsat","podhled","podivit","podklad","podmanit","podnik","podoba","podpora","podraz","podstata","podvod","podzim","poezie","pohanka","pohnutka","pohovor","pohroma","pohyb","pointa","pojistka","pojmout","pokazit","pokles","pokoj","pokrok","pokuta","pokyn","poledne","polibek","polknout","poloha","polynom","pomalu","pominout","pomlka","pomoc","pomsta","pomyslet","ponechat","ponorka","ponurost","popadat","popel","popisek","poplach","poprosit","popsat","popud","poradce","porce","porod","porucha","poryv","posadit","posed","posila","poskok","poslanec","posoudit","pospolu","postava","posudek","posyp","potah","potkan","potlesk","potomek","potrava","potupa","potvora","poukaz","pouto","pouzdro","povaha","povidla","povlak","povoz","povrch","povstat","povyk","povzdech","pozdrav","pozemek","poznatek","pozor","pozvat","pracovat","prahory","praktika","prales","praotec","praporek","prase","pravda","princip","prkno","probudit","procento","prodej","profese","prohra","projekt","prolomit","promile","pronikat","propad","prorok","prosba","proton","proutek","provaz","prskavka","prsten","prudkost","prut","prvek","prvohory","psanec","psovod","pstruh","ptactvo","puberta","puch","pudl","pukavec","puklina","pukrle","pult","pumpa","punc","pupen","pusa","pusinka","pustina","putovat","putyka","pyramida","pysk","pytel","racek","rachot","radiace","radnice","radon","raft","ragby","raketa","rakovina","rameno","rampouch","rande","rarach","rarita","rasovna","rastr","ratolest","razance","razidlo","reagovat","reakce","recept","redaktor","referent","reflex","rejnok","reklama","rekord","rekrut","rektor","reputace","revize","revma","revolver","rezerva","riskovat","riziko","robotika","rodokmen","rohovka","rokle","rokoko","romaneto","ropovod","ropucha","rorejs","rosol","rostlina","rotmistr","rotoped","rotunda","roubenka","roucho","roup","roura","rovina","rovnice","rozbor","rozchod","rozdat","rozeznat","rozhodce","rozinka","rozjezd","rozkaz","rozloha","rozmar","rozpad","rozruch","rozsah","roztok","rozum","rozvod","rubrika","ruchadlo","rukavice","rukopis","ryba","rybolov","rychlost","rydlo","rypadlo","rytina","ryzost","sadista","sahat","sako","samec","samizdat","samota","sanitka","sardinka","sasanka","satelit","sazba","sazenice","sbor","schovat","sebranka","secese","sedadlo","sediment","sedlo","sehnat","sejmout","sekera","sekta","sekunda","sekvoje","semeno","seno","servis","sesadit","seshora","seskok","seslat","sestra","sesuv","sesypat","setba","setina","setkat","setnout","setrvat","sever","seznam","shoda","shrnout","sifon","silnice","sirka","sirotek","sirup","situace","skafandr","skalisko","skanzen","skaut","skeptik","skica","skladba","sklenice","sklo","skluz","skoba","skokan","skoro","skripta","skrz","skupina","skvost","skvrna","slabika","sladidlo","slanina","slast","slavnost","sledovat","slepec","sleva","slezina","slib","slina","sliznice","slon","sloupek","slovo","sluch","sluha","slunce","slupka","slza","smaragd","smetana","smilstvo","smlouva","smog","smrad","smrk","smrtka","smutek","smysl","snad","snaha","snob","sobota","socha","sodovka","sokol","sopka","sotva","souboj","soucit","soudce","souhlas","soulad","soumrak","souprava","soused","soutok","souviset","spalovna","spasitel","spis","splav","spodek","spojenec","spolu","sponzor","spornost","spousta","sprcha","spustit","sranda","sraz","srdce","srna","srnec","srovnat","srpen","srst","srub","stanice","starosta","statika","stavba","stehno","stezka","stodola","stolek","stopa","storno","stoupat","strach","stres","strhnout","strom","struna","studna","stupnice","stvol","styk","subjekt","subtropy","suchar","sudost","sukno","sundat","sunout","surikata","surovina","svah","svalstvo","svetr","svatba","svazek","svisle","svitek","svoboda","svodidlo","svorka","svrab","sykavka","sykot","synek","synovec","sypat","sypkost","syrovost","sysel","sytost","tabletka","tabule","tahoun","tajemno","tajfun","tajga","tajit","tajnost","taktika","tamhle","tampon","tancovat","tanec","tanker","tapeta","tavenina","tazatel","technika","tehdy","tekutina","telefon","temnota","tendence","tenista","tenor","teplota","tepna","teprve","terapie","termoska","textil","ticho","tiskopis","titulek","tkadlec","tkanina","tlapka","tleskat","tlukot","tlupa","tmel","toaleta","topinka","topol","torzo","touha","toulec","tradice","traktor","tramp","trasa","traverza","trefit","trest","trezor","trhavina","trhlina","trochu","trojice","troska","trouba","trpce","trpitel","trpkost","trubec","truchlit","truhlice","trus","trvat","tudy","tuhnout","tuhost","tundra","turista","turnaj","tuzemsko","tvaroh","tvorba","tvrdost","tvrz","tygr","tykev","ubohost","uboze","ubrat","ubrousek","ubrus","ubytovna","ucho","uctivost","udivit","uhradit","ujednat","ujistit","ujmout","ukazatel","uklidnit","uklonit","ukotvit","ukrojit","ulice","ulita","ulovit","umyvadlo","unavit","uniforma","uniknout","upadnout","uplatnit","uplynout","upoutat","upravit","uran","urazit","usednout","usilovat","usmrtit","usnadnit","usnout","usoudit","ustlat","ustrnout","utahovat","utkat","utlumit","utonout","utopenec","utrousit","uvalit","uvolnit","uvozovka","uzdravit","uzel","uzenina","uzlina","uznat","vagon","valcha","valoun","vana","vandal","vanilka","varan","varhany","varovat","vcelku","vchod","vdova","vedro","vegetace","vejce","velbloud","veletrh","velitel","velmoc","velryba","venkov","veranda","verze","veselka","veskrze","vesnice","vespodu","vesta","veterina","veverka","vibrace","vichr","videohra","vidina","vidle","vila","vinice","viset","vitalita","vize","vizitka","vjezd","vklad","vkus","vlajka","vlak","vlasec","vlevo","vlhkost","vliv","vlnovka","vloupat","vnucovat","vnuk","voda","vodivost","vodoznak","vodstvo","vojensky","vojna","vojsko","volant","volba","volit","volno","voskovka","vozidlo","vozovna","vpravo","vrabec","vracet","vrah","vrata","vrba","vrcholek","vrhat","vrstva","vrtule","vsadit","vstoupit","vstup","vtip","vybavit","vybrat","vychovat","vydat","vydra","vyfotit","vyhledat","vyhnout","vyhodit","vyhradit","vyhubit","vyjasnit","vyjet","vyjmout","vyklopit","vykonat","vylekat","vymazat","vymezit","vymizet","vymyslet","vynechat","vynikat","vynutit","vypadat","vyplatit","vypravit","vypustit","vyrazit","vyrovnat","vyrvat","vyslovit","vysoko","vystavit","vysunout","vysypat","vytasit","vytesat","vytratit","vyvinout","vyvolat","vyvrhel","vyzdobit","vyznat","vzadu","vzbudit","vzchopit","vzdor","vzduch","vzdychat","vzestup","vzhledem","vzkaz","vzlykat","vznik","vzorek","vzpoura","vztah","vztek","xylofon","zabrat","zabydlet","zachovat","zadarmo","zadusit","zafoukat","zahltit","zahodit","zahrada","zahynout","zajatec","zajet","zajistit","zaklepat","zakoupit","zalepit","zamezit","zamotat","zamyslet","zanechat","zanikat","zaplatit","zapojit","zapsat","zarazit","zastavit","zasunout","zatajit","zatemnit","zatknout","zaujmout","zavalit","zavelet","zavinit","zavolat","zavrtat","zazvonit","zbavit","zbrusu","zbudovat","zbytek","zdaleka","zdarma","zdatnost","zdivo","zdobit","zdroj","zdvih","zdymadlo","zelenina","zeman","zemina","zeptat","zezadu","zezdola","zhatit","zhltnout","zhluboka","zhotovit","zhruba","zima","zimnice","zjemnit","zklamat","zkoumat","zkratka","zkumavka","zlato","zlehka","zloba","zlom","zlost","zlozvyk","zmapovat","zmar","zmatek","zmije","zmizet","zmocnit","zmodrat","zmrzlina","zmutovat","znak","znalost","znamenat","znovu","zobrazit","zotavit","zoubek","zoufale","zplodit","zpomalit","zprava","zprostit","zprudka","zprvu","zrada","zranit","zrcadlo","zrnitost","zrno","zrovna","zrychlit","zrzavost","zticha","ztratit","zubovina","zubr","zvednout","zvenku","zvesela","zvon","zvrat","zvukovod","zvyk"]["abandon","ability","able","about","above","absent","absorb","abstract","absurd","abuse","access","accident","account","accuse","achieve","acid","acoustic","acquire","across","act","action","actor","actress","actual","adapt","add","addict","address","adjust","admit","adult","advance","advice","aerobic","affair","afford","afraid","again","age","agent","agree","ahead","aim","air","airport","aisle","alarm","album","alcohol","alert","alien","all","alley","allow","almost","alone","alpha","already","also","alter","always","amateur","amazing","among","amount","amused","analyst","anchor","ancient","anger","angle","angry","animal","ankle","announce","annual","another","answer","antenna","antique","anxiety","any","apart","apology","appear","apple","approve","april","arch","arctic","area","arena","argue","arm","armed","armor","army","around","arrange","arrest","arrive","arrow","art","artefact","artist","artwork","ask","aspect","assault","asset","assist","assume","asthma","athlete","atom","attack","attend","attitude","attract","auction","audit","august","aunt","author","auto","autumn","average","avocado","avoid","awake","aware","away","awesome","awful","awkward","axis","baby","bachelor","bacon","badge","bag","balance","balcony","ball","bamboo","banana","banner","bar","barely","bargain","barrel","base","basic","basket","battle","beach","bean","beauty","because","become","beef","before","begin","behave","behind","believe","below","belt","bench","benefit","best","betray","better","between","beyond","bicycle","bid","bike","bind","biology","bird","birth","bitter","black","blade","blame","blanket","blast","bleak","bless","blind","blood","blossom","blouse","blue","blur","blush","board","boat","body","boil","bomb","bone","bonus","book","boost","border","boring","borrow","boss","bottom","bounce","box","boy","bracket","brain","brand","brass","brave","bread","breeze","brick","bridge","brief","bright","bring","brisk","broccoli","broken","bronze","broom","brother","brown","brush","bubble","buddy","budget","buffalo","build","bulb","bulk","bullet","bundle","bunker","burden","burger","burst","bus","business","busy","butter","buyer","buzz","cabbage","cabin","cable","cactus","cage","cake","call","calm","camera","camp","can","canal","cancel","candy","cannon","canoe","canvas","canyon","capable","capital","captain","car","carbon","card","cargo","carpet","carry","cart","case","cash","casino","castle","casual","cat","catalog","catch","category","cattle","caught","cause","caution","cave","ceiling","celery","cement","census","century","cereal","certain","chair","chalk","champion","change","chaos","chapter","charge","chase","chat","cheap","check","cheese","chef","cherry","chest","chicken","chief","child","chimney","choice","choose","chronic","chuckle","chunk","churn","cigar","cinnamon","circle","citizen","city","civil","claim","clap","clarify","claw","clay","clean","clerk","clever","click","client","cliff","climb","clinic","clip","clock","clog","close","cloth","cloud","clown","club","clump","cluster","clutch","coach","coast","coconut","code","coffee","coil","coin","collect","color","column","combine","come","comfort","comic","common","company","concert","conduct","confirm","congress","connect","consider","control","convince","cook","cool","copper","copy","coral","core","corn","correct","cost","cotton","couch","country","couple","course","cousin","cover","coyote","crack","cradle","craft","cram","crane","crash","crater","crawl","crazy","cream","credit","creek","crew","cricket","crime","crisp","critic","crop","cross","crouch","crowd","crucial","cruel","cruise","crumble","crunch","crush","cry","crystal","cube","culture","cup","cupboard","curious","current","curtain","curve","cushion","custom","cute","cycle","dad","damage","damp","dance","danger","daring","dash","daughter","dawn","day","deal","debate","debris","decade","december","decide","decline","decorate","decrease","deer","defense","define","defy","degree","delay","deliver","demand","demise","denial","dentist","deny","depart","depend","deposit","depth","deputy","derive","describe","desert","design","desk","despair","destroy","detail","detect","develop","device","devote","diagram","dial","diamond","diary","dice","diesel","diet","differ","digital","dignity","dilemma","dinner","dinosaur","direct","dirt","disagree","discover","disease","dish","dismiss","disorder","display","distance","divert","divide","divorce","dizzy","doctor","document","dog","doll","dolphin","domain","donate","donkey","donor","door","dose","double","dove","draft","dragon","drama","drastic","draw","dream","dress","drift","drill","drink","drip","drive","drop","drum","dry","duck","dumb","dune","during","dust","dutch","duty","dwarf","dynamic","eager","eagle","early","earn","earth","easily","east","easy","echo","ecology","economy","edge","edit","educate","effort","egg","eight","either","elbow","elder","electric","elegant","element","elephant","elevator","elite","else","embark","embody","embrace","emerge","emotion","employ","empower","empty","enable","enact","end","endless","endorse","enemy","energy","enforce","engage","engine","enhance","enjoy","enlist","enough","enrich","enroll","ensure","enter","entire","entry","envelope","episode","equal","equip","era","erase","erode","erosion","error","erupt","escape","essay","essence","estate","eternal","ethics","evidence","evil","evoke","evolve","exact","example","excess","exchange","excite","exclude","excuse","execute","exercise","exhaust","exhibit","exile","exist","exit","exotic","expand","expect","expire","explain","expose","express","extend","extra","eye","eyebrow","fabric","face","faculty","fade","faint","faith","fall","false","fame","family","famous","fan","fancy","fantasy","farm","fashion","fat","fatal","father","fatigue","fault","favorite","feature","february","federal","fee","feed","feel","female","fence","festival","fetch","fever","few","fiber","fiction","field","figure","file","film","filter","final","find","fine","finger","finish","fire","firm","first","fiscal","fish","fit","fitness","fix","flag","flame","flash","flat","flavor","flee","flight","flip","float","flock","floor","flower","fluid","flush","fly","foam","focus","fog","foil","fold","follow","food","foot","force","forest","forget","fork","fortune","forum","forward","fossil","foster","found","fox","fragile","frame","frequent","fresh","friend","fringe","frog","front","frost","frown","frozen","fruit","fuel","fun","funny","furnace","fury","future","gadget","gain","galaxy","gallery","game","gap","garage","garbage","garden","garlic","garment","gas","gasp","gate","gather","gauge","gaze","general","genius","genre","gentle","genuine","gesture","ghost","giant","gift","giggle","ginger","giraffe","girl","give","glad","glance","glare","glass","glide","glimpse","globe","gloom","glory","glove","glow","glue","goat","goddess","gold","good","goose","gorilla","gospel","gossip","govern","gown","grab","grace","grain","grant","grape","grass","gravity","great","green","grid","grief","grit","grocery","group","grow","grunt","guard","guess","guide","guilt","guitar","gun","gym","habit","hair","half","hammer","hamster","hand","happy","harbor","hard","harsh","harvest","hat","have","hawk","hazard","head","health","heart","heavy","hedgehog","height","hello","helmet","help","hen","hero","hidden","high","hill","hint","hip","hire","history","hobby","hockey","hold","hole","holiday","hollow","home","honey","hood","hope","horn","horror","horse","hospital","host","hotel","hour","hover","hub","huge","human","humble","humor","hundred","hungry","hunt","hurdle","hurry","hurt","husband","hybrid","ice","icon","idea","identify","idle","ignore","ill","illegal","illness","image","imitate","immense","immune","impact","impose","improve","impulse","inch","include","income","increase","index","indicate","indoor","industry","infant","inflict","inform","inhale","inherit","initial","inject","injury","inmate","inner","innocent","input","inquiry","insane","insect","inside","inspire","install","intact","interest","into","invest","invite","involve","iron","island","isolate","issue","item","ivory","jacket","jaguar","jar","jazz","jealous","jeans","jelly","jewel","job","join","joke","journey","joy","judge","juice","jump","jungle","junior","junk","just","kangaroo","keen","keep","ketchup","key","kick","kid","kidney","kind","kingdom","kiss","kit","kitchen","kite","kitten","kiwi","knee","knife","knock","know","lab","label","labor","ladder","lady","lake","lamp","language","laptop","large","later","latin","laugh","laundry","lava","law","lawn","lawsuit","layer","lazy","leader","leaf","learn","leave","lecture","left","leg","legal","legend","leisure","lemon","lend","length","lens","leopard","lesson","letter","level","liar","liberty","library","license","life","lift","light","like","limb","limit","link","lion","liquid","list","little","live","lizard","load","loan","lobster","local","lock","logic","lonely","long","loop","lottery","loud","lounge","love","loyal","lucky","luggage","lumber","lunar","lunch","luxury","lyrics","machine","mad","magic","magnet","maid","mail","main","major","make","mammal","man","manage","mandate","mango","mansion","manual","maple","marble","march","margin","marine","market","marriage","mask","mass","master","match","material","math","matrix","matter","maximum","maze","meadow","mean","measure","meat","mechanic","medal","media","melody","melt","member","memory","mention","menu","mercy","merge","merit","merry","mesh","message","metal","method","middle","midnight","milk","million","mimic","mind","minimum","minor","minute","miracle","mirror","misery","miss","mistake","mix","mixed","mixture","mobile","model","modify","mom","moment","monitor","monkey","monster","month","moon","moral","more","morning","mosquito","mother","motion","motor","mountain","mouse","move","movie","much","muffin","mule","multiply","muscle","museum","mushroom","music","must","mutual","myself","mystery","myth","naive","name","napkin","narrow","nasty","nation","nature","near","neck","need","negative","neglect","neither","nephew","nerve","nest","net","network","neutral","never","news","next","nice","night","noble","noise","nominee","noodle","normal","north","nose","notable","note","nothing","notice","novel","now","nuclear","number","nurse","nut","oak","obey","object","oblige","obscure","observe","obtain","obvious","occur","ocean","october","odor","off","offer","office","often","oil","okay","old","olive","olympic","omit","once","one","onion","online","only","open","opera","opinion","oppose","option","orange","orbit","orchard","order","ordinary","organ","orient","original","orphan","ostrich","other","outdoor","outer","output","outside","oval","oven","over","own","owner","oxygen","oyster","ozone","pact","paddle","page","pair","palace","palm","panda","panel","panic","panther","paper","parade","parent","park","parrot","party","pass","patch","path","patient","patrol","pattern","pause","pave","payment","peace","peanut","pear","peasant","pelican","pen","penalty","pencil","people","pepper","perfect","permit","person","pet","phone","photo","phrase","physical","piano","picnic","picture","piece","pig","pigeon","pill","pilot","pink","pioneer","pipe","pistol","pitch","pizza","place","planet","plastic","plate","play","please","pledge","pluck","plug","plunge","poem","poet","point","polar","pole","police","pond","pony","pool","popular","portion","position","possible","post","potato","pottery","poverty","powder","power","practice","praise","predict","prefer","prepare","present","pretty","prevent","price","pride","primary","print","priority","prison","private","prize","problem","process","produce","profit","program","project","promote","proof","property","prosper","protect","proud","provide","public","pudding","pull","pulp","pulse","pumpkin","punch","pupil","puppy","purchase","purity","purpose","purse","push","put","puzzle","pyramid","quality","quantum","quarter","question","quick","quit","quiz","quote","rabbit","raccoon","race","rack","radar","radio","rail","rain","raise","rally","ramp","ranch","random","range","rapid","rare","rate","rather","raven","raw","razor","ready","real","reason","rebel","rebuild","recall","receive","recipe","record","recycle","reduce","reflect","reform","refuse","region","regret","regular","reject","relax","release","relief","rely","remain","remember","remind","remove","render","renew","rent","reopen","repair","repeat","replace","report","require","rescue","resemble","resist","resource","response","result","retire","retreat","return","reunion","reveal","review","reward","rhythm","rib","ribbon","rice","rich","ride","ridge","rifle","right","rigid","ring","riot","ripple","risk","ritual","rival","river","road","roast","robot","robust","rocket","romance","roof","rookie","room","rose","rotate","rough","round","route","royal","rubber","rude","rug","rule","run","runway","rural","sad","saddle","sadness","safe","sail","salad","salmon","salon","salt","salute","same","sample","sand","satisfy","satoshi","sauce","sausage","save","say","scale","scan","scare","scatter","scene","scheme","school","science","scissors","scorpion","scout","scrap","screen","script","scrub","sea","search","season","seat","second","secret","section","security","seed","seek","segment","select","sell","seminar","senior","sense","sentence","series","service","session","settle","setup","seven","shadow","shaft","shallow","share","shed","shell","sheriff","shield","shift","shine","ship","shiver","shock","shoe","shoot","shop","short","shoulder","shove","shrimp","shrug","shuffle","shy","sibling","sick","side","siege","sight","sign","silent","silk","silly","silver","similar","simple","since","sing","siren","sister","situate","six","size","skate","sketch","ski","skill","skin","skirt","skull","slab","slam","sleep","slender","slice","slide","slight","slim","slogan","slot","slow","slush","small","smart","smile","smoke","smooth","snack","snake","snap","sniff","snow","soap","soccer","social","sock","soda","soft","solar","soldier","solid","solution","solve","someone","song","soon","sorry","sort","soul","sound","soup","source","south","space","spare","spatial","spawn","speak","special","speed","spell","spend","sphere","spice","spider","spike","spin","spirit","split","spoil","sponsor","spoon","sport","spot","spray","spread","spring","spy","square","squeeze","squirrel","stable","stadium","staff","stage","stairs","stamp","stand","start","state","stay","steak","steel","stem","step","stereo","stick","still","sting","stock","stomach","stone","stool","story","stove","strategy","street","strike","strong","struggle","student","stuff","stumble","style","subject","submit","subway","success","such","sudden","suffer","sugar","suggest","suit","summer","sun","sunny","sunset","super","supply","supreme","sure","surface","surge","surprise","surround","survey","suspect","sustain","swallow","swamp","swap","swarm","swear","sweet","swift","swim","swing","switch","sword","symbol","symptom","syrup","system","table","tackle","tag","tail","talent","talk","tank","tape","target","task","taste","tattoo","taxi","teach","team","tell","ten","tenant","tennis","tent","term","test","text","thank","that","theme","then","theory","there","they","thing","this","thought","three","thrive","throw","thumb","thunder","ticket","tide","tiger","tilt","timber","time","tiny","tip","tired","tissue","title","toast","tobacco","today","toddler","toe","together","toilet","token","tomato","tomorrow","tone","tongue","tonight","tool","tooth","top","topic","topple","torch","tornado","tortoise","toss","total","tourist","toward","tower","town","toy","track","trade","traffic","tragic","train","transfer","trap","trash","travel","tray","treat","tree","trend","trial","tribe","trick","trigger","trim","trip","trophy","trouble","truck","true","truly","trumpet","trust","truth","try","tube","tuition","tumble","tuna","tunnel","turkey","turn","turtle","twelve","twenty","twice","twin","twist","two","type","typical","ugly","umbrella","unable","unaware","uncle","uncover","under","undo","unfair","unfold","unhappy","uniform","unique","unit","universe","unknown","unlock","until","unusual","unveil","update","upgrade","uphold","upon","upper","upset","urban","urge","usage","use","used","useful","useless","usual","utility","vacant","vacuum","vague","valid","valley","valve","van","vanish","vapor","various","vast","vault","vehicle","velvet","vendor","venture","venue","verb","verify","version","very","vessel","veteran","viable","vibrant","vicious","victory","video","view","village","vintage","violin","virtual","virus","visa","visit","visual","vital","vivid","vocal","voice","void","volcano","volume","vote","voyage","wage","wagon","wait","walk","wall","walnut","want","warfare","warm","warrior","wash","wasp","waste","water","wave","way","wealth","weapon","wear","weasel","weather","web","wedding","weekend","weird","welcome","west","wet","whale","what","wheat","wheel","when","where","whip","whisper","wide","width","wife","wild","will","win","window","wine","wing","wink","winner","winter","wire","wisdom","wise","wish","witness","wolf","woman","wonder","wood","wool","word","work","world","worry","worth","wrap","wreck","wrestle","wrist","write","wrong","yard","year","yellow","you","young","youth","zebra","zero","zone","zoo"]["abaisser","abandon","abdiquer","abeille","abolir","aborder","aboutir","aboyer","abrasif","abreuver","abriter","abroger","abrupt","absence","absolu","absurde","abusif","abyssal","académie","acajou","acarien","accabler","accepter","acclamer","accolade","accroche","accuser","acerbe","achat","acheter","aciduler","acier","acompte","acquérir","acronyme","acteur","actif","actuel","adepte","adéquat","adhésif","adjectif","adjuger","admettre","admirer","adopter","adorer","adoucir","adresse","adroit","adulte","adverbe","aérer","aéronef","affaire","affecter","affiche","affreux","affubler","agacer","agencer","agile","agiter","agrafer","agréable","agrume","aider","aiguille","ailier","aimable","aisance","ajouter","ajuster","alarmer","alchimie","alerte","algèbre","algue","aliéner","aliment","alléger","alliage","allouer","allumer","alourdir","alpaga","altesse","alvéole","amateur","ambigu","ambre","aménager","amertume","amidon","amiral","amorcer","amour","amovible","amphibie","ampleur","amusant","analyse","anaphore","anarchie","anatomie","ancien","anéantir","angle","angoisse","anguleux","animal","annexer","annonce","annuel","anodin","anomalie","anonyme","anormal","antenne","antidote","anxieux","apaiser","apéritif","aplanir","apologie","appareil","appeler","apporter","appuyer","aquarium","aqueduc","arbitre","arbuste","ardeur","ardoise","argent","arlequin","armature","armement","armoire","armure","arpenter","arracher","arriver","arroser","arsenic","artériel","article","aspect","asphalte","aspirer","assaut","asservir","assiette","associer","assurer","asticot","astre","astuce","atelier","atome","atrium","atroce","attaque","attentif","attirer","attraper","aubaine","auberge","audace","audible","augurer","aurore","automne","autruche","avaler","avancer","avarice","avenir","averse","aveugle","aviateur","avide","avion","aviser","avoine","avouer","avril","axial","axiome","badge","bafouer","bagage","baguette","baignade","balancer","balcon","baleine","balisage","bambin","bancaire","bandage","banlieue","bannière","banquier","barbier","baril","baron","barque","barrage","bassin","bastion","bataille","bateau","batterie","baudrier","bavarder","belette","bélier","belote","bénéfice","berceau","berger","berline","bermuda","besace","besogne","bétail","beurre","biberon","bicycle","bidule","bijou","bilan","bilingue","billard","binaire","biologie","biopsie","biotype","biscuit","bison","bistouri","bitume","bizarre","blafard","blague","blanchir","blessant","blinder","blond","bloquer","blouson","bobard","bobine","boire","boiser","bolide","bonbon","bondir","bonheur","bonifier","bonus","bordure","borne","botte","boucle","boueux","bougie","boulon","bouquin","bourse","boussole","boutique","boxeur","branche","brasier","brave","brebis","brèche","breuvage","bricoler","brigade","brillant","brioche","brique","brochure","broder","bronzer","brousse","broyeur","brume","brusque","brutal","bruyant","buffle","buisson","bulletin","bureau","burin","bustier","butiner","butoir","buvable","buvette","cabanon","cabine","cachette","cadeau","cadre","caféine","caillou","caisson","calculer","calepin","calibre","calmer","calomnie","calvaire","camarade","caméra","camion","campagne","canal","caneton","canon","cantine","canular","capable","caporal","caprice","capsule","capter","capuche","carabine","carbone","caresser","caribou","carnage","carotte","carreau","carton","cascade","casier","casque","cassure","causer","caution","cavalier","caverne","caviar","cédille","ceinture","céleste","cellule","cendrier","censurer","central","cercle","cérébral","cerise","cerner","cerveau","cesser","chagrin","chaise","chaleur","chambre","chance","chapitre","charbon","chasseur","chaton","chausson","chavirer","chemise","chenille","chéquier","chercher","cheval","chien","chiffre","chignon","chimère","chiot","chlorure","chocolat","choisir","chose","chouette","chrome","chute","cigare","cigogne","cimenter","cinéma","cintrer","circuler","cirer","cirque","citerne","citoyen","citron","civil","clairon","clameur","claquer","classe","clavier","client","cligner","climat","clivage","cloche","clonage","cloporte","cobalt","cobra","cocasse","cocotier","coder","codifier","coffre","cogner","cohésion","coiffer","coincer","colère","colibri","colline","colmater","colonel","combat","comédie","commande","compact","concert","conduire","confier","congeler","connoter","consonne","contact","convexe","copain","copie","corail","corbeau","cordage","corniche","corpus","correct","cortège","cosmique","costume","coton","coude","coupure","courage","couteau","couvrir","coyote","crabe","crainte","cravate","crayon","créature","créditer","crémeux","creuser","crevette","cribler","crier","cristal","critère","croire","croquer","crotale","crucial","cruel","crypter","cubique","cueillir","cuillère","cuisine","cuivre","culminer","cultiver","cumuler","cupide","curatif","curseur","cyanure","cycle","cylindre","cynique","daigner","damier","danger","danseur","dauphin","débattre","débiter","déborder","débrider","débutant","décaler","décembre","déchirer","décider","déclarer","décorer","décrire","décupler","dédale","déductif","déesse","défensif","défiler","défrayer","dégager","dégivrer","déglutir","dégrafer","déjeuner","délice","déloger","demander","demeurer","démolir","dénicher","dénouer","dentelle","dénuder","départ","dépenser","déphaser","déplacer","déposer","déranger","dérober","désastre","descente","désert","désigner","désobéir","dessiner","destrier","détacher","détester","détourer","détresse","devancer","devenir","deviner","devoir","diable","dialogue","diamant","dicter","différer","digérer","digital","digne","diluer","dimanche","diminuer","dioxyde","directif","diriger","discuter","disposer","dissiper","distance","divertir","diviser","docile","docteur","dogme","doigt","domaine","domicile","dompter","donateur","donjon","donner","dopamine","dortoir","dorure","dosage","doseur","dossier","dotation","douanier","double","douceur","douter","doyen","dragon","draper","dresser","dribbler","droiture","duperie","duplexe","durable","durcir","dynastie","éblouir","écarter","écharpe","échelle","éclairer","éclipse","éclore","écluse","école","économie","écorce","écouter","écraser","écrémer","écrivain","écrou","écume","écureuil","édifier","éduquer","effacer","effectif","effigie","effort","effrayer","effusion","égaliser","égarer","éjecter","élaborer","élargir","électron","élégant","éléphant","élève","éligible","élitisme","éloge","élucider","éluder","emballer","embellir","embryon","émeraude","émission","emmener","émotion","émouvoir","empereur","employer","emporter","emprise","émulsion","encadrer","enchère","enclave","encoche","endiguer","endosser","endroit","enduire","énergie","enfance","enfermer","enfouir","engager","engin","englober","énigme","enjamber","enjeu","enlever","ennemi","ennuyeux","enrichir","enrobage","enseigne","entasser","entendre","entier","entourer","entraver","énumérer","envahir","enviable","envoyer","enzyme","éolien","épaissir","épargne","épatant","épaule","épicerie","épidémie","épier","épilogue","épine","épisode","épitaphe","époque","épreuve","éprouver","épuisant","équerre","équipe","ériger","érosion","erreur","éruption","escalier","espadon","espèce","espiègle","espoir","esprit","esquiver","essayer","essence","essieu","essorer","estime","estomac","estrade","étagère","étaler","étanche","étatique","éteindre","étendoir","éternel","éthanol","éthique","ethnie","étirer","étoffer","étoile","étonnant","étourdir","étrange","étroit","étude","euphorie","évaluer","évasion","éventail","évidence","éviter","évolutif","évoquer","exact","exagérer","exaucer","exceller","excitant","exclusif","excuse","exécuter","exemple","exercer","exhaler","exhorter","exigence","exiler","exister","exotique","expédier","explorer","exposer","exprimer","exquis","extensif","extraire","exulter","fable","fabuleux","facette","facile","facture","faiblir","falaise","fameux","famille","farceur","farfelu","farine","farouche","fasciner","fatal","fatigue","faucon","fautif","faveur","favori","fébrile","féconder","fédérer","félin","femme","fémur","fendoir","féodal","fermer","féroce","ferveur","festival","feuille","feutre","février","fiasco","ficeler","fictif","fidèle","figure","filature","filetage","filière","filleul","filmer","filou","filtrer","financer","finir","fiole","firme","fissure","fixer","flairer","flamme","flasque","flatteur","fléau","flèche","fleur","flexion","flocon","flore","fluctuer","fluide","fluvial","folie","fonderie","fongible","fontaine","forcer","forgeron","formuler","fortune","fossile","foudre","fougère","fouiller","foulure","fourmi","fragile","fraise","franchir","frapper","frayeur","frégate","freiner","frelon","frémir","frénésie","frère","friable","friction","frisson","frivole","froid","fromage","frontal","frotter","fruit","fugitif","fuite","fureur","furieux","furtif","fusion","futur","gagner","galaxie","galerie","gambader","garantir","gardien","garnir","garrigue","gazelle","gazon","géant","gélatine","gélule","gendarme","général","génie","genou","gentil","géologie","géomètre","géranium","germe","gestuel","geyser","gibier","gicler","girafe","givre","glace","glaive","glisser","globe","gloire","glorieux","golfeur","gomme","gonfler","gorge","gorille","goudron","gouffre","goulot","goupille","gourmand","goutte","graduel","graffiti","graine","grand","grappin","gratuit","gravir","grenat","griffure","griller","grimper","grogner","gronder","grotte","groupe","gruger","grutier","gruyère","guépard","guerrier","guide","guimauve","guitare","gustatif","gymnaste","gyrostat","habitude","hachoir","halte","hameau","hangar","hanneton","haricot","harmonie","harpon","hasard","hélium","hématome","herbe","hérisson","hermine","héron","hésiter","heureux","hiberner","hibou","hilarant","histoire","hiver","homard","hommage","homogène","honneur","honorer","honteux","horde","horizon","horloge","hormone","horrible","houleux","housse","hublot","huileux","humain","humble","humide","humour","hurler","hydromel","hygiène","hymne","hypnose","idylle","ignorer","iguane","illicite","illusion","image","imbiber","imiter","immense","immobile","immuable","impact","impérial","implorer","imposer","imprimer","imputer","incarner","incendie","incident","incliner","incolore","indexer","indice","inductif","inédit","ineptie","inexact","infini","infliger","informer","infusion","ingérer","inhaler","inhiber","injecter","injure","innocent","inoculer","inonder","inscrire","insecte","insigne","insolite","inspirer","instinct","insulter","intact","intense","intime","intrigue","intuitif","inutile","invasion","inventer","inviter","invoquer","ironique","irradier","irréel","irriter","isoler","ivoire","ivresse","jaguar","jaillir","jambe","janvier","jardin","jauger","jaune","javelot","jetable","jeton","jeudi","jeunesse","joindre","joncher","jongler","joueur","jouissif","journal","jovial","joyau","joyeux","jubiler","jugement","junior","jupon","juriste","justice","juteux","juvénile","kayak","kimono","kiosque","label","labial","labourer","lacérer","lactose","lagune","laine","laisser","laitier","lambeau","lamelle","lampe","lanceur","langage","lanterne","lapin","largeur","larme","laurier","lavabo","lavoir","lecture","légal","léger","légume","lessive","lettre","levier","lexique","lézard","liasse","libérer","libre","licence","licorne","liège","lièvre","ligature","ligoter","ligue","limer","limite","limonade","limpide","linéaire","lingot","lionceau","liquide","lisière","lister","lithium","litige","littoral","livreur","logique","lointain","loisir","lombric","loterie","louer","lourd","loutre","louve","loyal","lubie","lucide","lucratif","lueur","lugubre","luisant","lumière","lunaire","lundi","luron","lutter","luxueux","machine","magasin","magenta","magique","maigre","maillon","maintien","mairie","maison","majorer","malaxer","maléfice","malheur","malice","mallette","mammouth","mandater","maniable","manquant","manteau","manuel","marathon","marbre","marchand","mardi","maritime","marqueur","marron","marteler","mascotte","massif","matériel","matière","matraque","maudire","maussade","mauve","maximal","méchant","méconnu","médaille","médecin","méditer","méduse","meilleur","mélange","mélodie","membre","mémoire","menacer","mener","menhir","mensonge","mentor","mercredi","mérite","merle","messager","mesure","métal","météore","méthode","métier","meuble","miauler","microbe","miette","mignon","migrer","milieu","million","mimique","mince","minéral","minimal","minorer","minute","miracle","miroiter","missile","mixte","mobile","moderne","moelleux","mondial","moniteur","monnaie","monotone","monstre","montagne","monument","moqueur","morceau","morsure","mortier","moteur","motif","mouche","moufle","moulin","mousson","mouton","mouvant","multiple","munition","muraille","murène","murmure","muscle","muséum","musicien","mutation","muter","mutuel","myriade","myrtille","mystère","mythique","nageur","nappe","narquois","narrer","natation","nation","nature","naufrage","nautique","navire","nébuleux","nectar","néfaste","négation","négliger","négocier","neige","nerveux","nettoyer","neurone","neutron","neveu","niche","nickel","nitrate","niveau","noble","nocif","nocturne","noirceur","noisette","nomade","nombreux","nommer","normatif","notable","notifier","notoire","nourrir","nouveau","novateur","novembre","novice","nuage","nuancer","nuire","nuisible","numéro","nuptial","nuque","nutritif","obéir","objectif","obliger","obscur","observer","obstacle","obtenir","obturer","occasion","occuper","océan","octobre","octroyer","octupler","oculaire","odeur","odorant","offenser","officier","offrir","ogive","oiseau","oisillon","olfactif","olivier","ombrage","omettre","onctueux","onduler","onéreux","onirique","opale","opaque","opérer","opinion","opportun","opprimer","opter","optique","orageux","orange","orbite","ordonner","oreille","organe","orgueil","orifice","ornement","orque","ortie","osciller","osmose","ossature","otarie","ouragan","ourson","outil","outrager","ouvrage","ovation","oxyde","oxygène","ozone","paisible","palace","palmarès","palourde","palper","panache","panda","pangolin","paniquer","panneau","panorama","pantalon","papaye","papier","papoter","papyrus","paradoxe","parcelle","paresse","parfumer","parler","parole","parrain","parsemer","partager","parure","parvenir","passion","pastèque","paternel","patience","patron","pavillon","pavoiser","payer","paysage","peigne","peintre","pelage","pélican","pelle","pelouse","peluche","pendule","pénétrer","pénible","pensif","pénurie","pépite","péplum","perdrix","perforer","période","permuter","perplexe","persil","perte","peser","pétale","petit","pétrir","peuple","pharaon","phobie","phoque","photon","phrase","physique","piano","pictural","pièce","pierre","pieuvre","pilote","pinceau","pipette","piquer","pirogue","piscine","piston","pivoter","pixel","pizza","placard","plafond","plaisir","planer","plaque","plastron","plateau","pleurer","plexus","pliage","plomb","plonger","pluie","plumage","pochette","poésie","poète","pointe","poirier","poisson","poivre","polaire","policier","pollen","polygone","pommade","pompier","ponctuel","pondérer","poney","portique","position","posséder","posture","potager","poteau","potion","pouce","poulain","poumon","pourpre","poussin","pouvoir","prairie","pratique","précieux","prédire","préfixe","prélude","prénom","présence","prétexte","prévoir","primitif","prince","prison","priver","problème","procéder","prodige","profond","progrès","proie","projeter","prologue","promener","propre","prospère","protéger","prouesse","proverbe","prudence","pruneau","psychose","public","puceron","puiser","pulpe","pulsar","punaise","punitif","pupitre","purifier","puzzle","pyramide","quasar","querelle","question","quiétude","quitter","quotient","racine","raconter","radieux","ragondin","raideur","raisin","ralentir","rallonge","ramasser","rapide","rasage","ratisser","ravager","ravin","rayonner","réactif","réagir","réaliser","réanimer","recevoir","réciter","réclamer","récolter","recruter","reculer","recycler","rédiger","redouter","refaire","réflexe","réformer","refrain","refuge","régalien","région","réglage","régulier","réitérer","rejeter","rejouer","relatif","relever","relief","remarque","remède","remise","remonter","remplir","remuer","renard","renfort","renifler","renoncer","rentrer","renvoi","replier","reporter","reprise","reptile","requin","réserve","résineux","résoudre","respect","rester","résultat","rétablir","retenir","réticule","retomber","retracer","réunion","réussir","revanche","revivre","révolte","révulsif","richesse","rideau","rieur","rigide","rigoler","rincer","riposter","risible","risque","rituel","rival","rivière","rocheux","romance","rompre","ronce","rondin","roseau","rosier","rotatif","rotor","rotule","rouge","rouille","rouleau","routine","royaume","ruban","rubis","ruche","ruelle","rugueux","ruiner","ruisseau","ruser","rustique","rythme","sabler","saboter","sabre","sacoche","safari","sagesse","saisir","salade","salive","salon","saluer","samedi","sanction","sanglier","sarcasme","sardine","saturer","saugrenu","saumon","sauter","sauvage","savant","savonner","scalpel","scandale","scélérat","scénario","sceptre","schéma","science","scinder","score","scrutin","sculpter","séance","sécable","sécher","secouer","sécréter","sédatif","séduire","seigneur","séjour","sélectif","semaine","sembler","semence","séminal","sénateur","sensible","sentence","séparer","séquence","serein","sergent","sérieux","serrure","sérum","service","sésame","sévir","sevrage","sextuple","sidéral","siècle","siéger","siffler","sigle","signal","silence","silicium","simple","sincère","sinistre","siphon","sirop","sismique","situer","skier","social","socle","sodium","soigneux","soldat","soleil","solitude","soluble","sombre","sommeil","somnoler","sonde","songeur","sonnette","sonore","sorcier","sortir","sosie","sottise","soucieux","soudure","souffle","soulever","soupape","source","soutirer","souvenir","spacieux","spatial","spécial","sphère","spiral","stable","station","sternum","stimulus","stipuler","strict","studieux","stupeur","styliste","sublime","substrat","subtil","subvenir","succès","sucre","suffixe","suggérer","suiveur","sulfate","superbe","supplier","surface","suricate","surmener","surprise","sursaut","survie","suspect","syllabe","symbole","symétrie","synapse","syntaxe","système","tabac","tablier","tactile","tailler","talent","talisman","talonner","tambour","tamiser","tangible","tapis","taquiner","tarder","tarif","tartine","tasse","tatami","tatouage","taupe","taureau","taxer","témoin","temporel","tenaille","tendre","teneur","tenir","tension","terminer","terne","terrible","tétine","texte","thème","théorie","thérapie","thorax","tibia","tiède","timide","tirelire","tiroir","tissu","titane","titre","tituber","toboggan","tolérant","tomate","tonique","tonneau","toponyme","torche","tordre","tornade","torpille","torrent","torse","tortue","totem","toucher","tournage","tousser","toxine","traction","trafic","tragique","trahir","train","trancher","travail","trèfle","tremper","trésor","treuil","triage","tribunal","tricoter","trilogie","triomphe","tripler","triturer","trivial","trombone","tronc","tropical","troupeau","tuile","tulipe","tumulte","tunnel","turbine","tuteur","tutoyer","tuyau","tympan","typhon","typique","tyran","ubuesque","ultime","ultrason","unanime","unifier","union","unique","unitaire","univers","uranium","urbain","urticant","usage","usine","usuel","usure","utile","utopie","vacarme","vaccin","vagabond","vague","vaillant","vaincre","vaisseau","valable","valise","vallon","valve","vampire","vanille","vapeur","varier","vaseux","vassal","vaste","vecteur","vedette","végétal","véhicule","veinard","véloce","vendredi","vénérer","venger","venimeux","ventouse","verdure","vérin","vernir","verrou","verser","vertu","veston","vétéran","vétuste","vexant","vexer","viaduc","viande","victoire","vidange","vidéo","vignette","vigueur","vilain","village","vinaigre","violon","vipère","virement","virtuose","virus","visage","viseur","vision","visqueux","visuel","vital","vitesse","viticole","vitrine","vivace","vivipare","vocation","voguer","voile","voisin","voiture","volaille","volcan","voltiger","volume","vorace","vortex","voter","vouloir","voyage","voyelle","wagon","xénon","yacht","zèbre","zénith","zeste","zoologie"]// note all JSON files in this folder are generated with npm run generate-wordlist
const lookup = require('./lookup.json')

module.exports = {
  loadWordlist,
  detectLanguage
}

function loadWordlist (language) {
  switch (language) {
    case 'chinese_simplified': return require('./chinese_simplified.json')
    case 'chinese_traditional': return require('./chinese_traditional.json')
    case 'czech': return require('./czech.json')
    case 'english': return require('./english.json')
    case 'french': return require('./french.json')
    case 'italian': return require('./italian.json')
    case 'japanese': return require('./japanese.json')
    case 'korean': return require('./korean.json')
    case 'portuguese': return require('./portuguese.json')
    case 'russian': return require('./russian.json')
    case 'spanish': return require('./spanish.json')
    case 'turkish': return require('./turkish.json')
  }

  throw new Error('Unknown language: ' + language)
}

function detectLanguage (words) {
  let candidate = null

  for (const word of words) {
    const languages = lookup[word]
    if (!languages) return null

    if (languages.length === 1) return languages[0]

    if (!candidate) {
      candidate = languages
      continue
    }

    const intersect = candidate.filter(l => languages.includes(l))
    if (intersect.length === 1) return intersect[0]
  }

  return candidate[0]
}
["abaco","abbaglio","abbinato","abete","abisso","abolire","abrasivo","abrogato","accadere","accenno","accusato","acetone","achille","acido","acqua","acre","acrilico","acrobata","acuto","adagio","addebito","addome","adeguato","aderire","adipe","adottare","adulare","affabile","affetto","affisso","affranto","aforisma","afoso","africano","agave","agente","agevole","aggancio","agire","agitare","agonismo","agricolo","agrumeto","aguzzo","alabarda","alato","albatro","alberato","albo","albume","alce","alcolico","alettone","alfa","algebra","aliante","alibi","alimento","allagato","allegro","allievo","allodola","allusivo","almeno","alogeno","alpaca","alpestre","altalena","alterno","alticcio","altrove","alunno","alveolo","alzare","amalgama","amanita","amarena","ambito","ambrato","ameba","america","ametista","amico","ammasso","ammenda","ammirare","ammonito","amore","ampio","ampliare","amuleto","anacardo","anagrafe","analista","anarchia","anatra","anca","ancella","ancora","andare","andrea","anello","angelo","angolare","angusto","anima","annegare","annidato","anno","annuncio","anonimo","anticipo","anzi","apatico","apertura","apode","apparire","appetito","appoggio","approdo","appunto","aprile","arabica","arachide","aragosta","araldica","arancio","aratura","arazzo","arbitro","archivio","ardito","arenile","argento","argine","arguto","aria","armonia","arnese","arredato","arringa","arrosto","arsenico","arso","artefice","arzillo","asciutto","ascolto","asepsi","asettico","asfalto","asino","asola","aspirato","aspro","assaggio","asse","assoluto","assurdo","asta","astenuto","astice","astratto","atavico","ateismo","atomico","atono","attesa","attivare","attorno","attrito","attuale","ausilio","austria","autista","autonomo","autunno","avanzato","avere","avvenire","avviso","avvolgere","azione","azoto","azzimo","azzurro","babele","baccano","bacino","baco","badessa","badilata","bagnato","baita","balcone","baldo","balena","ballata","balzano","bambino","bandire","baraonda","barbaro","barca","baritono","barlume","barocco","basilico","basso","batosta","battuto","baule","bava","bavosa","becco","beffa","belgio","belva","benda","benevole","benigno","benzina","bere","berlina","beta","bibita","bici","bidone","bifido","biga","bilancia","bimbo","binocolo","biologo","bipede","bipolare","birbante","birra","biscotto","bisesto","bisnonno","bisonte","bisturi","bizzarro","blando","blatta","bollito","bonifico","bordo","bosco","botanico","bottino","bozzolo","braccio","bradipo","brama","branca","bravura","bretella","brevetto","brezza","briglia","brillante","brindare","broccolo","brodo","bronzina","brullo","bruno","bubbone","buca","budino","buffone","buio","bulbo","buono","burlone","burrasca","bussola","busta","cadetto","caduco","calamaro","calcolo","calesse","calibro","calmo","caloria","cambusa","camerata","camicia","cammino","camola","campale","canapa","candela","cane","canino","canotto","cantina","capace","capello","capitolo","capogiro","cappero","capra","capsula","carapace","carcassa","cardo","carisma","carovana","carretto","cartolina","casaccio","cascata","caserma","caso","cassone","castello","casuale","catasta","catena","catrame","cauto","cavillo","cedibile","cedrata","cefalo","celebre","cellulare","cena","cenone","centesimo","ceramica","cercare","certo","cerume","cervello","cesoia","cespo","ceto","chela","chiaro","chicca","chiedere","chimera","china","chirurgo","chitarra","ciao","ciclismo","cifrare","cigno","cilindro","ciottolo","circa","cirrosi","citrico","cittadino","ciuffo","civetta","civile","classico","clinica","cloro","cocco","codardo","codice","coerente","cognome","collare","colmato","colore","colposo","coltivato","colza","coma","cometa","commando","comodo","computer","comune","conciso","condurre","conferma","congelare","coniuge","connesso","conoscere","consumo","continuo","convegno","coperto","copione","coppia","copricapo","corazza","cordata","coricato","cornice","corolla","corpo","corredo","corsia","cortese","cosmico","costante","cottura","covato","cratere","cravatta","creato","credere","cremoso","crescita","creta","criceto","crinale","crisi","critico","croce","cronaca","crostata","cruciale","crusca","cucire","cuculo","cugino","cullato","cupola","curatore","cursore","curvo","cuscino","custode","dado","daino","dalmata","damerino","daniela","dannoso","danzare","datato","davanti","davvero","debutto","decennio","deciso","declino","decollo","decreto","dedicato","definito","deforme","degno","delegare","delfino","delirio","delta","demenza","denotato","dentro","deposito","derapata","derivare","deroga","descritto","deserto","desiderio","desumere","detersivo","devoto","diametro","dicembre","diedro","difeso","diffuso","digerire","digitale","diluvio","dinamico","dinnanzi","dipinto","diploma","dipolo","diradare","dire","dirotto","dirupo","disagio","discreto","disfare","disgelo","disposto","distanza","disumano","dito","divano","divelto","dividere","divorato","doblone","docente","doganale","dogma","dolce","domato","domenica","dominare","dondolo","dono","dormire","dote","dottore","dovuto","dozzina","drago","druido","dubbio","dubitare","ducale","duna","duomo","duplice","duraturo","ebano","eccesso","ecco","eclissi","economia","edera","edicola","edile","editoria","educare","egemonia","egli","egoismo","egregio","elaborato","elargire","elegante","elencato","eletto","elevare","elfico","elica","elmo","elsa","eluso","emanato","emblema","emesso","emiro","emotivo","emozione","empirico","emulo","endemico","enduro","energia","enfasi","enoteca","entrare","enzima","epatite","epilogo","episodio","epocale","eppure","equatore","erario","erba","erboso","erede","eremita","erigere","ermetico","eroe","erosivo","errante","esagono","esame","esanime","esaudire","esca","esempio","esercito","esibito","esigente","esistere","esito","esofago","esortato","esoso","espanso","espresso","essenza","esso","esteso","estimare","estonia","estroso","esultare","etilico","etnico","etrusco","etto","euclideo","europa","evaso","evidenza","evitato","evoluto","evviva","fabbrica","faccenda","fachiro","falco","famiglia","fanale","fanfara","fango","fantasma","fare","farfalla","farinoso","farmaco","fascia","fastoso","fasullo","faticare","fato","favoloso","febbre","fecola","fede","fegato","felpa","feltro","femmina","fendere","fenomeno","fermento","ferro","fertile","fessura","festivo","fetta","feudo","fiaba","fiducia","fifa","figurato","filo","finanza","finestra","finire","fiore","fiscale","fisico","fiume","flacone","flamenco","flebo","flemma","florido","fluente","fluoro","fobico","focaccia","focoso","foderato","foglio","folata","folclore","folgore","fondente","fonetico","fonia","fontana","forbito","forchetta","foresta","formica","fornaio","foro","fortezza","forzare","fosfato","fosso","fracasso","frana","frassino","fratello","freccetta","frenata","fresco","frigo","frollino","fronde","frugale","frutta","fucilata","fucsia","fuggente","fulmine","fulvo","fumante","fumetto","fumoso","fune","funzione","fuoco","furbo","furgone","furore","fuso","futile","gabbiano","gaffe","galateo","gallina","galoppo","gambero","gamma","garanzia","garbo","garofano","garzone","gasdotto","gasolio","gastrico","gatto","gaudio","gazebo","gazzella","geco","gelatina","gelso","gemello","gemmato","gene","genitore","gennaio","genotipo","gergo","ghepardo","ghiaccio","ghisa","giallo","gilda","ginepro","giocare","gioiello","giorno","giove","girato","girone","gittata","giudizio","giurato","giusto","globulo","glutine","gnomo","gobba","golf","gomito","gommone","gonfio","gonna","governo","gracile","grado","grafico","grammo","grande","grattare","gravoso","grazia","greca","gregge","grifone","grigio","grinza","grotta","gruppo","guadagno","guaio","guanto","guardare","gufo","guidare","ibernato","icona","identico","idillio","idolo","idra","idrico","idrogeno","igiene","ignaro","ignorato","ilare","illeso","illogico","illudere","imballo","imbevuto","imbocco","imbuto","immane","immerso","immolato","impacco","impeto","impiego","importo","impronta","inalare","inarcare","inattivo","incanto","incendio","inchino","incisivo","incluso","incontro","incrocio","incubo","indagine","india","indole","inedito","infatti","infilare","inflitto","ingaggio","ingegno","inglese","ingordo","ingrosso","innesco","inodore","inoltrare","inondato","insano","insetto","insieme","insonnia","insulina","intasato","intero","intonaco","intuito","inumidire","invalido","invece","invito","iperbole","ipnotico","ipotesi","ippica","iride","irlanda","ironico","irrigato","irrorare","isolato","isotopo","isterico","istituto","istrice","italia","iterare","labbro","labirinto","lacca","lacerato","lacrima","lacuna","laddove","lago","lampo","lancetta","lanterna","lardoso","larga","laringe","lastra","latenza","latino","lattuga","lavagna","lavoro","legale","leggero","lembo","lentezza","lenza","leone","lepre","lesivo","lessato","lesto","letterale","leva","levigato","libero","lido","lievito","lilla","limatura","limitare","limpido","lineare","lingua","liquido","lira","lirica","lisca","lite","litigio","livrea","locanda","lode","logica","lombare","londra","longevo","loquace","lorenzo","loto","lotteria","luce","lucidato","lumaca","luminoso","lungo","lupo","luppolo","lusinga","lusso","lutto","macabro","macchina","macero","macinato","madama","magico","maglia","magnete","magro","maiolica","malafede","malgrado","malinteso","malsano","malto","malumore","mana","mancia","mandorla","mangiare","manifesto","mannaro","manovra","mansarda","mantide","manubrio","mappa","maratona","marcire","maretta","marmo","marsupio","maschera","massaia","mastino","materasso","matricola","mattone","maturo","mazurca","meandro","meccanico","mecenate","medesimo","meditare","mega","melassa","melis","melodia","meninge","meno","mensola","mercurio","merenda","merlo","meschino","mese","messere","mestolo","metallo","metodo","mettere","miagolare","mica","micelio","michele","microbo","midollo","miele","migliore","milano","milite","mimosa","minerale","mini","minore","mirino","mirtillo","miscela","missiva","misto","misurare","mitezza","mitigare","mitra","mittente","mnemonico","modello","modifica","modulo","mogano","mogio","mole","molosso","monastero","monco","mondina","monetario","monile","monotono","monsone","montato","monviso","mora","mordere","morsicato","mostro","motivato","motosega","motto","movenza","movimento","mozzo","mucca","mucosa","muffa","mughetto","mugnaio","mulatto","mulinello","multiplo","mummia","munto","muovere","murale","musa","muscolo","musica","mutevole","muto","nababbo","nafta","nanometro","narciso","narice","narrato","nascere","nastrare","naturale","nautica","naviglio","nebulosa","necrosi","negativo","negozio","nemmeno","neofita","neretto","nervo","nessuno","nettuno","neutrale","neve","nevrotico","nicchia","ninfa","nitido","nobile","nocivo","nodo","nome","nomina","nordico","normale","norvegese","nostrano","notare","notizia","notturno","novella","nucleo","nulla","numero","nuovo","nutrire","nuvola","nuziale","oasi","obbedire","obbligo","obelisco","oblio","obolo","obsoleto","occasione","occhio","occidente","occorrere","occultare","ocra","oculato","odierno","odorare","offerta","offrire","offuscato","oggetto","oggi","ognuno","olandese","olfatto","oliato","oliva","ologramma","oltre","omaggio","ombelico","ombra","omega","omissione","ondoso","onere","onice","onnivoro","onorevole","onta","operato","opinione","opposto","oracolo","orafo","ordine","orecchino","orefice","orfano","organico","origine","orizzonte","orma","ormeggio","ornativo","orologio","orrendo","orribile","ortensia","ortica","orzata","orzo","osare","oscurare","osmosi","ospedale","ospite","ossa","ossidare","ostacolo","oste","otite","otre","ottagono","ottimo","ottobre","ovale","ovest","ovino","oviparo","ovocito","ovunque","ovviare","ozio","pacchetto","pace","pacifico","padella","padrone","paese","paga","pagina","palazzina","palesare","pallido","palo","palude","pandoro","pannello","paolo","paonazzo","paprica","parabola","parcella","parere","pargolo","pari","parlato","parola","partire","parvenza","parziale","passivo","pasticca","patacca","patologia","pattume","pavone","peccato","pedalare","pedonale","peggio","peloso","penare","pendice","penisola","pennuto","penombra","pensare","pentola","pepe","pepita","perbene","percorso","perdonato","perforare","pergamena","periodo","permesso","perno","perplesso","persuaso","pertugio","pervaso","pesatore","pesista","peso","pestifero","petalo","pettine","petulante","pezzo","piacere","pianta","piattino","piccino","picozza","piega","pietra","piffero","pigiama","pigolio","pigro","pila","pilifero","pillola","pilota","pimpante","pineta","pinna","pinolo","pioggia","piombo","piramide","piretico","pirite","pirolisi","pitone","pizzico","placebo","planare","plasma","platano","plenario","pochezza","poderoso","podismo","poesia","poggiare","polenta","poligono","pollice","polmonite","polpetta","polso","poltrona","polvere","pomice","pomodoro","ponte","popoloso","porfido","poroso","porpora","porre","portata","posa","positivo","possesso","postulato","potassio","potere","pranzo","prassi","pratica","precluso","predica","prefisso","pregiato","prelievo","premere","prenotare","preparato","presenza","pretesto","prevalso","prima","principe","privato","problema","procura","produrre","profumo","progetto","prolunga","promessa","pronome","proposta","proroga","proteso","prova","prudente","prugna","prurito","psiche","pubblico","pudica","pugilato","pugno","pulce","pulito","pulsante","puntare","pupazzo","pupilla","puro","quadro","qualcosa","quasi","querela","quota","raccolto","raddoppio","radicale","radunato","raffica","ragazzo","ragione","ragno","ramarro","ramingo","ramo","randagio","rantolare","rapato","rapina","rappreso","rasatura","raschiato","rasente","rassegna","rastrello","rata","ravveduto","reale","recepire","recinto","recluta","recondito","recupero","reddito","redimere","regalato","registro","regola","regresso","relazione","remare","remoto","renna","replica","reprimere","reputare","resa","residente","responso","restauro","rete","retina","retorica","rettifica","revocato","riassunto","ribadire","ribelle","ribrezzo","ricarica","ricco","ricevere","riciclato","ricordo","ricreduto","ridicolo","ridurre","rifasare","riflesso","riforma","rifugio","rigare","rigettato","righello","rilassato","rilevato","rimanere","rimbalzo","rimedio","rimorchio","rinascita","rincaro","rinforzo","rinnovo","rinomato","rinsavito","rintocco","rinuncia","rinvenire","riparato","ripetuto","ripieno","riportare","ripresa","ripulire","risata","rischio","riserva","risibile","riso","rispetto","ristoro","risultato","risvolto","ritardo","ritegno","ritmico","ritrovo","riunione","riva","riverso","rivincita","rivolto","rizoma","roba","robotico","robusto","roccia","roco","rodaggio","rodere","roditore","rogito","rollio","romantico","rompere","ronzio","rosolare","rospo","rotante","rotondo","rotula","rovescio","rubizzo","rubrica","ruga","rullino","rumine","rumoroso","ruolo","rupe","russare","rustico","sabato","sabbiare","sabotato","sagoma","salasso","saldatura","salgemma","salivare","salmone","salone","saltare","saluto","salvo","sapere","sapido","saporito","saraceno","sarcasmo","sarto","sassoso","satellite","satira","satollo","saturno","savana","savio","saziato","sbadiglio","sbalzo","sbancato","sbarra","sbattere","sbavare","sbendare","sbirciare","sbloccato","sbocciato","sbrinare","sbruffone","sbuffare","scabroso","scadenza","scala","scambiare","scandalo","scapola","scarso","scatenare","scavato","scelto","scenico","scettro","scheda","schiena","sciarpa","scienza","scindere","scippo","sciroppo","scivolo","sclerare","scodella","scolpito","scomparto","sconforto","scoprire","scorta","scossone","scozzese","scriba","scrollare","scrutinio","scuderia","scultore","scuola","scuro","scusare","sdebitare","sdoganare","seccatura","secondo","sedano","seggiola","segnalato","segregato","seguito","selciato","selettivo","sella","selvaggio","semaforo","sembrare","seme","seminato","sempre","senso","sentire","sepolto","sequenza","serata","serbato","sereno","serio","serpente","serraglio","servire","sestina","setola","settimana","sfacelo","sfaldare","sfamato","sfarzoso","sfaticato","sfera","sfida","sfilato","sfinge","sfocato","sfoderare","sfogo","sfoltire","sforzato","sfratto","sfruttato","sfuggito","sfumare","sfuso","sgabello","sgarbato","sgonfiare","sgorbio","sgrassato","sguardo","sibilo","siccome","sierra","sigla","signore","silenzio","sillaba","simbolo","simpatico","simulato","sinfonia","singolo","sinistro","sino","sintesi","sinusoide","sipario","sisma","sistole","situato","slitta","slogatura","sloveno","smarrito","smemorato","smentito","smeraldo","smilzo","smontare","smottato","smussato","snellire","snervato","snodo","sobbalzo","sobrio","soccorso","sociale","sodale","soffitto","sogno","soldato","solenne","solido","sollazzo","solo","solubile","solvente","somatico","somma","sonda","sonetto","sonnifero","sopire","soppeso","sopra","sorgere","sorpasso","sorriso","sorso","sorteggio","sorvolato","sospiro","sosta","sottile","spada","spalla","spargere","spatola","spavento","spazzola","specie","spedire","spegnere","spelatura","speranza","spessore","spettrale","spezzato","spia","spigoloso","spillato","spinoso","spirale","splendido","sportivo","sposo","spranga","sprecare","spronato","spruzzo","spuntino","squillo","sradicare","srotolato","stabile","stacco","staffa","stagnare","stampato","stantio","starnuto","stasera","statuto","stelo","steppa","sterzo","stiletto","stima","stirpe","stivale","stizzoso","stonato","storico","strappo","stregato","stridulo","strozzare","strutto","stuccare","stufo","stupendo","subentro","succoso","sudore","suggerito","sugo","sultano","suonare","superbo","supporto","surgelato","surrogato","sussurro","sutura","svagare","svedese","sveglio","svelare","svenuto","svezia","sviluppo","svista","svizzera","svolta","svuotare","tabacco","tabulato","tacciare","taciturno","tale","talismano","tampone","tannino","tara","tardivo","targato","tariffa","tarpare","tartaruga","tasto","tattico","taverna","tavolata","tazza","teca","tecnico","telefono","temerario","tempo","temuto","tendone","tenero","tensione","tentacolo","teorema","terme","terrazzo","terzetto","tesi","tesserato","testato","tetro","tettoia","tifare","tigella","timbro","tinto","tipico","tipografo","tiraggio","tiro","titanio","titolo","titubante","tizio","tizzone","toccare","tollerare","tolto","tombola","tomo","tonfo","tonsilla","topazio","topologia","toppa","torba","tornare","torrone","tortora","toscano","tossire","tostatura","totano","trabocco","trachea","trafila","tragedia","tralcio","tramonto","transito","trapano","trarre","trasloco","trattato","trave","treccia","tremolio","trespolo","tributo","tricheco","trifoglio","trillo","trincea","trio","tristezza","triturato","trivella","tromba","trono","troppo","trottola","trovare","truccato","tubatura","tuffato","tulipano","tumulto","tunisia","turbare","turchino","tuta","tutela","ubicato","uccello","uccisore","udire","uditivo","uffa","ufficio","uguale","ulisse","ultimato","umano","umile","umorismo","uncinetto","ungere","ungherese","unicorno","unificato","unisono","unitario","unte","uovo","upupa","uragano","urgenza","urlo","usanza","usato","uscito","usignolo","usuraio","utensile","utilizzo","utopia","vacante","vaccinato","vagabondo","vagliato","valanga","valgo","valico","valletta","valoroso","valutare","valvola","vampata","vangare","vanitoso","vano","vantaggio","vanvera","vapore","varano","varcato","variante","vasca","vedetta","vedova","veduto","vegetale","veicolo","velcro","velina","velluto","veloce","venato","vendemmia","vento","verace","verbale","vergogna","verifica","vero","verruca","verticale","vescica","vessillo","vestale","veterano","vetrina","vetusto","viandante","vibrante","vicenda","vichingo","vicinanza","vidimare","vigilia","vigneto","vigore","vile","villano","vimini","vincitore","viola","vipera","virgola","virologo","virulento","viscoso","visione","vispo","vissuto","visura","vita","vitello","vittima","vivanda","vivido","viziare","voce","voga","volatile","volere","volpe","voragine","vulcano","zampogna","zanna","zappato","zattera","zavorra","zefiro","zelante","zelo","zenzero","zerbino","zibetto","zinco","zircone","zitto","zolla","zotico","zucchero","zufolo","zulu","zuppa"]["あいこくしん","あいさつ","あいだ","あおぞら","あかちゃん","あきる","あけがた","あける","あこがれる","あさい","あさひ","あしあと","あじわう","あずかる","あずき","あそぶ","あたえる","あたためる","あたりまえ","あたる","あつい","あつかう","あっしゅく","あつまり","あつめる","あてな","あてはまる","あひる","あぶら","あぶる","あふれる","あまい","あまど","あまやかす","あまり","あみもの","あめりか","あやまる","あゆむ","あらいぐま","あらし","あらすじ","あらためる","あらゆる","あらわす","ありがとう","あわせる","あわてる","あんい","あんがい","あんこ","あんぜん","あんてい","あんない","あんまり","いいだす","いおん","いがい","いがく","いきおい","いきなり","いきもの","いきる","いくじ","いくぶん","いけばな","いけん","いこう","いこく","いこつ","いさましい","いさん","いしき","いじゅう","いじょう","いじわる","いずみ","いずれ","いせい","いせえび","いせかい","いせき","いぜん","いそうろう","いそがしい","いだい","いだく","いたずら","いたみ","いたりあ","いちおう","いちじ","いちど","いちば","いちぶ","いちりゅう","いつか","いっしゅん","いっせい","いっそう","いったん","いっち","いってい","いっぽう","いてざ","いてん","いどう","いとこ","いない","いなか","いねむり","いのち","いのる","いはつ","いばる","いはん","いびき","いひん","いふく","いへん","いほう","いみん","いもうと","いもたれ","いもり","いやがる","いやす","いよかん","いよく","いらい","いらすと","いりぐち","いりょう","いれい","いれもの","いれる","いろえんぴつ","いわい","いわう","いわかん","いわば","いわゆる","いんげんまめ","いんさつ","いんしょう","いんよう","うえき","うえる","うおざ","うがい","うかぶ","うかべる","うきわ","うくらいな","うくれれ","うけたまわる","うけつけ","うけとる","うけもつ","うける","うごかす","うごく","うこん","うさぎ","うしなう","うしろがみ","うすい","うすぎ","うすぐらい","うすめる","うせつ","うちあわせ","うちがわ","うちき","うちゅう","うっかり","うつくしい","うったえる","うつる","うどん","うなぎ","うなじ","うなずく","うなる","うねる","うのう","うぶげ","うぶごえ","うまれる","うめる","うもう","うやまう","うよく","うらがえす","うらぐち","うらない","うりあげ","うりきれ","うるさい","うれしい","うれゆき","うれる","うろこ","うわき","うわさ","うんこう","うんちん","うんてん","うんどう","えいえん","えいが","えいきょう","えいご","えいせい","えいぶん","えいよう","えいわ","えおり","えがお","えがく","えきたい","えくせる","えしゃく","えすて","えつらん","えのぐ","えほうまき","えほん","えまき","えもじ","えもの","えらい","えらぶ","えりあ","えんえん","えんかい","えんぎ","えんげき","えんしゅう","えんぜつ","えんそく","えんちょう","えんとつ","おいかける","おいこす","おいしい","おいつく","おうえん","おうさま","おうじ","おうせつ","おうたい","おうふく","おうべい","おうよう","おえる","おおい","おおう","おおどおり","おおや","おおよそ","おかえり","おかず","おがむ","おかわり","おぎなう","おきる","おくさま","おくじょう","おくりがな","おくる","おくれる","おこす","おこなう","おこる","おさえる","おさない","おさめる","おしいれ","おしえる","おじぎ","おじさん","おしゃれ","おそらく","おそわる","おたがい","おたく","おだやか","おちつく","おっと","おつり","おでかけ","おとしもの","おとなしい","おどり","おどろかす","おばさん","おまいり","おめでとう","おもいで","おもう","おもたい","おもちゃ","おやつ","おやゆび","およぼす","おらんだ","おろす","おんがく","おんけい","おんしゃ","おんせん","おんだん","おんちゅう","おんどけい","かあつ","かいが","がいき","がいけん","がいこう","かいさつ","かいしゃ","かいすいよく","かいぜん","かいぞうど","かいつう","かいてん","かいとう","かいふく","がいへき","かいほう","かいよう","がいらい","かいわ","かえる","かおり","かかえる","かがく","かがし","かがみ","かくご","かくとく","かざる","がぞう","かたい","かたち","がちょう","がっきゅう","がっこう","がっさん","がっしょう","かなざわし","かのう","がはく","かぶか","かほう","かほご","かまう","かまぼこ","かめれおん","かゆい","かようび","からい","かるい","かろう","かわく","かわら","がんか","かんけい","かんこう","かんしゃ","かんそう","かんたん","かんち","がんばる","きあい","きあつ","きいろ","ぎいん","きうい","きうん","きえる","きおう","きおく","きおち","きおん","きかい","きかく","きかんしゃ","ききて","きくばり","きくらげ","きけんせい","きこう","きこえる","きこく","きさい","きさく","きさま","きさらぎ","ぎじかがく","ぎしき","ぎじたいけん","ぎじにってい","ぎじゅつしゃ","きすう","きせい","きせき","きせつ","きそう","きぞく","きぞん","きたえる","きちょう","きつえん","ぎっちり","きつつき","きつね","きてい","きどう","きどく","きない","きなが","きなこ","きぬごし","きねん","きのう","きのした","きはく","きびしい","きひん","きふく","きぶん","きぼう","きほん","きまる","きみつ","きむずかしい","きめる","きもだめし","きもち","きもの","きゃく","きやく","ぎゅうにく","きよう","きょうりゅう","きらい","きらく","きりん","きれい","きれつ","きろく","ぎろん","きわめる","ぎんいろ","きんかくじ","きんじょ","きんようび","ぐあい","くいず","くうかん","くうき","くうぐん","くうこう","ぐうせい","くうそう","ぐうたら","くうふく","くうぼ","くかん","くきょう","くげん","ぐこう","くさい","くさき","くさばな","くさる","くしゃみ","くしょう","くすのき","くすりゆび","くせげ","くせん","ぐたいてき","くださる","くたびれる","くちこみ","くちさき","くつした","ぐっすり","くつろぐ","くとうてん","くどく","くなん","くねくね","くのう","くふう","くみあわせ","くみたてる","くめる","くやくしょ","くらす","くらべる","くるま","くれる","くろう","くわしい","ぐんかん","ぐんしょく","ぐんたい","ぐんて","けあな","けいかく","けいけん","けいこ","けいさつ","げいじゅつ","けいたい","げいのうじん","けいれき","けいろ","けおとす","けおりもの","げきか","げきげん","げきだん","げきちん","げきとつ","げきは","げきやく","げこう","げこくじょう","げざい","けさき","げざん","けしき","けしごむ","けしょう","げすと","けたば","けちゃっぷ","けちらす","けつあつ","けつい","けつえき","けっこん","けつじょ","けっせき","けってい","けつまつ","げつようび","げつれい","けつろん","げどく","けとばす","けとる","けなげ","けなす","けなみ","けぬき","げねつ","けねん","けはい","げひん","けぶかい","げぼく","けまり","けみかる","けむし","けむり","けもの","けらい","けろけろ","けわしい","けんい","けんえつ","けんお","けんか","げんき","けんげん","けんこう","けんさく","けんしゅう","けんすう","げんそう","けんちく","けんてい","けんとう","けんない","けんにん","げんぶつ","けんま","けんみん","けんめい","けんらん","けんり","こあくま","こいぬ","こいびと","ごうい","こうえん","こうおん","こうかん","ごうきゅう","ごうけい","こうこう","こうさい","こうじ","こうすい","ごうせい","こうそく","こうたい","こうちゃ","こうつう","こうてい","こうどう","こうない","こうはい","ごうほう","ごうまん","こうもく","こうりつ","こえる","こおり","ごかい","ごがつ","ごかん","こくご","こくさい","こくとう","こくない","こくはく","こぐま","こけい","こける","ここのか","こころ","こさめ","こしつ","こすう","こせい","こせき","こぜん","こそだて","こたい","こたえる","こたつ","こちょう","こっか","こつこつ","こつばん","こつぶ","こてい","こてん","ことがら","ことし","ことば","ことり","こなごな","こねこね","このまま","このみ","このよ","ごはん","こひつじ","こふう","こふん","こぼれる","ごまあぶら","こまかい","ごますり","こまつな","こまる","こむぎこ","こもじ","こもち","こもの","こもん","こやく","こやま","こゆう","こゆび","こよい","こよう","こりる","これくしょん","ころっけ","こわもて","こわれる","こんいん","こんかい","こんき","こんしゅう","こんすい","こんだて","こんとん","こんなん","こんびに","こんぽん","こんまけ","こんや","こんれい","こんわく","ざいえき","さいかい","さいきん","ざいげん","ざいこ","さいしょ","さいせい","ざいたく","ざいちゅう","さいてき","ざいりょう","さうな","さかいし","さがす","さかな","さかみち","さがる","さぎょう","さくし","さくひん","さくら","さこく","さこつ","さずかる","ざせき","さたん","さつえい","ざつおん","ざっか","ざつがく","さっきょく","ざっし","さつじん","ざっそう","さつたば","さつまいも","さてい","さといも","さとう","さとおや","さとし","さとる","さのう","さばく","さびしい","さべつ","さほう","さほど","さます","さみしい","さみだれ","さむけ","さめる","さやえんどう","さゆう","さよう","さよく","さらだ","ざるそば","さわやか","さわる","さんいん","さんか","さんきゃく","さんこう","さんさい","ざんしょ","さんすう","さんせい","さんそ","さんち","さんま","さんみ","さんらん","しあい","しあげ","しあさって","しあわせ","しいく","しいん","しうち","しえい","しおけ","しかい","しかく","じかん","しごと","しすう","じだい","したうけ","したぎ","したて","したみ","しちょう","しちりん","しっかり","しつじ","しつもん","してい","してき","してつ","じてん","じどう","しなぎれ","しなもの","しなん","しねま","しねん","しのぐ","しのぶ","しはい","しばかり","しはつ","しはらい","しはん","しひょう","しふく","じぶん","しへい","しほう","しほん","しまう","しまる","しみん","しむける","じむしょ","しめい","しめる","しもん","しゃいん","しゃうん","しゃおん","じゃがいも","しやくしょ","しゃくほう","しゃけん","しゃこ","しゃざい","しゃしん","しゃせん","しゃそう","しゃたい","しゃちょう","しゃっきん","じゃま","しゃりん","しゃれい","じゆう","じゅうしょ","しゅくはく","じゅしん","しゅっせき","しゅみ","しゅらば","じゅんばん","しょうかい","しょくたく","しょっけん","しょどう","しょもつ","しらせる","しらべる","しんか","しんこう","じんじゃ","しんせいじ","しんちく","しんりん","すあげ","すあし","すあな","ずあん","すいえい","すいか","すいとう","ずいぶん","すいようび","すうがく","すうじつ","すうせん","すおどり","すきま","すくう","すくない","すける","すごい","すこし","ずさん","すずしい","すすむ","すすめる","すっかり","ずっしり","ずっと","すてき","すてる","すねる","すのこ","すはだ","すばらしい","ずひょう","ずぶぬれ","すぶり","すふれ","すべて","すべる","ずほう","すぼん","すまい","すめし","すもう","すやき","すらすら","するめ","すれちがう","すろっと","すわる","すんぜん","すんぽう","せあぶら","せいかつ","せいげん","せいじ","せいよう","せおう","せかいかん","せきにん","せきむ","せきゆ","せきらんうん","せけん","せこう","せすじ","せたい","せたけ","せっかく","せっきゃく","ぜっく","せっけん","せっこつ","せっさたくま","せつぞく","せつだん","せつでん","せっぱん","せつび","せつぶん","せつめい","せつりつ","せなか","せのび","せはば","せびろ","せぼね","せまい","せまる","せめる","せもたれ","せりふ","ぜんあく","せんい","せんえい","せんか","せんきょ","せんく","せんげん","ぜんご","せんさい","せんしゅ","せんすい","せんせい","せんぞ","せんたく","せんちょう","せんてい","せんとう","せんぬき","せんねん","せんぱい","ぜんぶ","ぜんぽう","せんむ","せんめんじょ","せんもん","せんやく","せんゆう","せんよう","ぜんら","ぜんりゃく","せんれい","せんろ","そあく","そいとげる","そいね","そうがんきょう","そうき","そうご","そうしん","そうだん","そうなん","そうび","そうめん","そうり","そえもの","そえん","そがい","そげき","そこう","そこそこ","そざい","そしな","そせい","そせん","そそぐ","そだてる","そつう","そつえん","そっかん","そつぎょう","そっけつ","そっこう","そっせん","そっと","そとがわ","そとづら","そなえる","そなた","そふぼ","そぼく","そぼろ","そまつ","そまる","そむく","そむりえ","そめる","そもそも","そよかぜ","そらまめ","そろう","そんかい","そんけい","そんざい","そんしつ","そんぞく","そんちょう","ぞんび","ぞんぶん","そんみん","たあい","たいいん","たいうん","たいえき","たいおう","だいがく","たいき","たいぐう","たいけん","たいこ","たいざい","だいじょうぶ","だいすき","たいせつ","たいそう","だいたい","たいちょう","たいてい","だいどころ","たいない","たいねつ","たいのう","たいはん","だいひょう","たいふう","たいへん","たいほ","たいまつばな","たいみんぐ","たいむ","たいめん","たいやき","たいよう","たいら","たいりょく","たいる","たいわん","たうえ","たえる","たおす","たおる","たおれる","たかい","たかね","たきび","たくさん","たこく","たこやき","たさい","たしざん","だじゃれ","たすける","たずさわる","たそがれ","たたかう","たたく","ただしい","たたみ","たちばな","だっかい","だっきゃく","だっこ","だっしゅつ","だったい","たてる","たとえる","たなばた","たにん","たぬき","たのしみ","たはつ","たぶん","たべる","たぼう","たまご","たまる","だむる","ためいき","ためす","ためる","たもつ","たやすい","たよる","たらす","たりきほんがん","たりょう","たりる","たると","たれる","たれんと","たろっと","たわむれる","だんあつ","たんい","たんおん","たんか","たんき","たんけん","たんご","たんさん","たんじょうび","だんせい","たんそく","たんたい","だんち","たんてい","たんとう","だんな","たんにん","だんねつ","たんのう","たんぴん","だんぼう","たんまつ","たんめい","だんれつ","だんろ","だんわ","ちあい","ちあん","ちいき","ちいさい","ちえん","ちかい","ちから","ちきゅう","ちきん","ちけいず","ちけん","ちこく","ちさい","ちしき","ちしりょう","ちせい","ちそう","ちたい","ちたん","ちちおや","ちつじょ","ちてき","ちてん","ちぬき","ちぬり","ちのう","ちひょう","ちへいせん","ちほう","ちまた","ちみつ","ちみどろ","ちめいど","ちゃんこなべ","ちゅうい","ちゆりょく","ちょうし","ちょさくけん","ちらし","ちらみ","ちりがみ","ちりょう","ちるど","ちわわ","ちんたい","ちんもく","ついか","ついたち","つうか","つうじょう","つうはん","つうわ","つかう","つかれる","つくね","つくる","つけね","つける","つごう","つたえる","つづく","つつじ","つつむ","つとめる","つながる","つなみ","つねづね","つのる","つぶす","つまらない","つまる","つみき","つめたい","つもり","つもる","つよい","つるぼ","つるみく","つわもの","つわり","てあし","てあて","てあみ","ていおん","ていか","ていき","ていけい","ていこく","ていさつ","ていし","ていせい","ていたい","ていど","ていねい","ていひょう","ていへん","ていぼう","てうち","ておくれ","てきとう","てくび","でこぼこ","てさぎょう","てさげ","てすり","てそう","てちがい","てちょう","てつがく","てつづき","でっぱ","てつぼう","てつや","でぬかえ","てぬき","てぬぐい","てのひら","てはい","てぶくろ","てふだ","てほどき","てほん","てまえ","てまきずし","てみじか","てみやげ","てらす","てれび","てわけ","てわたし","でんあつ","てんいん","てんかい","てんき","てんぐ","てんけん","てんごく","てんさい","てんし","てんすう","でんち","てんてき","てんとう","てんない","てんぷら","てんぼうだい","てんめつ","てんらんかい","でんりょく","でんわ","どあい","といれ","どうかん","とうきゅう","どうぐ","とうし","とうむぎ","とおい","とおか","とおく","とおす","とおる","とかい","とかす","ときおり","ときどき","とくい","とくしゅう","とくてん","とくに","とくべつ","とけい","とける","とこや","とさか","としょかん","とそう","とたん","とちゅう","とっきゅう","とっくん","とつぜん","とつにゅう","とどける","ととのえる","とない","となえる","となり","とのさま","とばす","どぶがわ","とほう","とまる","とめる","ともだち","ともる","どようび","とらえる","とんかつ","どんぶり","ないかく","ないこう","ないしょ","ないす","ないせん","ないそう","なおす","ながい","なくす","なげる","なこうど","なさけ","なたでここ","なっとう","なつやすみ","ななおし","なにごと","なにもの","なにわ","なのか","なふだ","なまいき","なまえ","なまみ","なみだ","なめらか","なめる","なやむ","ならう","ならび","ならぶ","なれる","なわとび","なわばり","にあう","にいがた","にうけ","におい","にかい","にがて","にきび","にくしみ","にくまん","にげる","にさんかたんそ","にしき","にせもの","にちじょう","にちようび","にっか","にっき","にっけい","にっこう","にっさん","にっしょく","にっすう","にっせき","にってい","になう","にほん","にまめ","にもつ","にやり","にゅういん","にりんしゃ","にわとり","にんい","にんか","にんき","にんげん","にんしき","にんずう","にんそう","にんたい","にんち","にんてい","にんにく","にんぷ","にんまり","にんむ","にんめい","にんよう","ぬいくぎ","ぬかす","ぬぐいとる","ぬぐう","ぬくもり","ぬすむ","ぬまえび","ぬめり","ぬらす","ぬんちゃく","ねあげ","ねいき","ねいる","ねいろ","ねぐせ","ねくたい","ねくら","ねこぜ","ねこむ","ねさげ","ねすごす","ねそべる","ねだん","ねつい","ねっしん","ねつぞう","ねったいぎょ","ねぶそく","ねふだ","ねぼう","ねほりはほり","ねまき","ねまわし","ねみみ","ねむい","ねむたい","ねもと","ねらう","ねわざ","ねんいり","ねんおし","ねんかん","ねんきん","ねんぐ","ねんざ","ねんし","ねんちゃく","ねんど","ねんぴ","ねんぶつ","ねんまつ","ねんりょう","ねんれい","のいず","のおづま","のがす","のきなみ","のこぎり","のこす","のこる","のせる","のぞく","のぞむ","のたまう","のちほど","のっく","のばす","のはら","のべる","のぼる","のみもの","のやま","のらいぬ","のらねこ","のりもの","のりゆき","のれん","のんき","ばあい","はあく","ばあさん","ばいか","ばいく","はいけん","はいご","はいしん","はいすい","はいせん","はいそう","はいち","ばいばい","はいれつ","はえる","はおる","はかい","ばかり","はかる","はくしゅ","はけん","はこぶ","はさみ","はさん","はしご","ばしょ","はしる","はせる","ぱそこん","はそん","はたん","はちみつ","はつおん","はっかく","はづき","はっきり","はっくつ","はっけん","はっこう","はっさん","はっしん","はったつ","はっちゅう","はってん","はっぴょう","はっぽう","はなす","はなび","はにかむ","はぶらし","はみがき","はむかう","はめつ","はやい","はやし","はらう","はろうぃん","はわい","はんい","はんえい","はんおん","はんかく","はんきょう","ばんぐみ","はんこ","はんしゃ","はんすう","はんだん","ぱんち","ぱんつ","はんてい","はんとし","はんのう","はんぱ","はんぶん","はんぺん","はんぼうき","はんめい","はんらん","はんろん","ひいき","ひうん","ひえる","ひかく","ひかり","ひかる","ひかん","ひくい","ひけつ","ひこうき","ひこく","ひさい","ひさしぶり","ひさん","びじゅつかん","ひしょ","ひそか","ひそむ","ひたむき","ひだり","ひたる","ひつぎ","ひっこし","ひっし","ひつじゅひん","ひっす","ひつぜん","ぴったり","ぴっちり","ひつよう","ひてい","ひとごみ","ひなまつり","ひなん","ひねる","ひはん","ひびく","ひひょう","ひほう","ひまわり","ひまん","ひみつ","ひめい","ひめじし","ひやけ","ひやす","ひよう","びょうき","ひらがな","ひらく","ひりつ","ひりょう","ひるま","ひるやすみ","ひれい","ひろい","ひろう","ひろき","ひろゆき","ひんかく","ひんけつ","ひんこん","ひんしゅ","ひんそう","ぴんち","ひんぱん","びんぼう","ふあん","ふいうち","ふうけい","ふうせん","ぷうたろう","ふうとう","ふうふ","ふえる","ふおん","ふかい","ふきん","ふくざつ","ふくぶくろ","ふこう","ふさい","ふしぎ","ふじみ","ふすま","ふせい","ふせぐ","ふそく","ぶたにく","ふたん","ふちょう","ふつう","ふつか","ふっかつ","ふっき","ふっこく","ぶどう","ふとる","ふとん","ふのう","ふはい","ふひょう","ふへん","ふまん","ふみん","ふめつ","ふめん","ふよう","ふりこ","ふりる","ふるい","ふんいき","ぶんがく","ぶんぐ","ふんしつ","ぶんせき","ふんそう","ぶんぽう","へいあん","へいおん","へいがい","へいき","へいげん","へいこう","へいさ","へいしゃ","へいせつ","へいそ","へいたく","へいてん","へいねつ","へいわ","へきが","へこむ","べにいろ","べにしょうが","へらす","へんかん","べんきょう","べんごし","へんさい","へんたい","べんり","ほあん","ほいく","ぼうぎょ","ほうこく","ほうそう","ほうほう","ほうもん","ほうりつ","ほえる","ほおん","ほかん","ほきょう","ぼきん","ほくろ","ほけつ","ほけん","ほこう","ほこる","ほしい","ほしつ","ほしゅ","ほしょう","ほせい","ほそい","ほそく","ほたて","ほたる","ぽちぶくろ","ほっきょく","ほっさ","ほったん","ほとんど","ほめる","ほんい","ほんき","ほんけ","ほんしつ","ほんやく","まいにち","まかい","まかせる","まがる","まける","まこと","まさつ","まじめ","ますく","まぜる","まつり","まとめ","まなぶ","まぬけ","まねく","まほう","まもる","まゆげ","まよう","まろやか","まわす","まわり","まわる","まんが","まんきつ","まんぞく","まんなか","みいら","みうち","みえる","みがく","みかた","みかん","みけん","みこん","みじかい","みすい","みすえる","みせる","みっか","みつかる","みつける","みてい","みとめる","みなと","みなみかさい","みねらる","みのう","みのがす","みほん","みもと","みやげ","みらい","みりょく","みわく","みんか","みんぞく","むいか","むえき","むえん","むかい","むかう","むかえ","むかし","むぎちゃ","むける","むげん","むさぼる","むしあつい","むしば","むじゅん","むしろ","むすう","むすこ","むすぶ","むすめ","むせる","むせん","むちゅう","むなしい","むのう","むやみ","むよう","むらさき","むりょう","むろん","めいあん","めいうん","めいえん","めいかく","めいきょく","めいさい","めいし","めいそう","めいぶつ","めいれい","めいわく","めぐまれる","めざす","めした","めずらしい","めだつ","めまい","めやす","めんきょ","めんせき","めんどう","もうしあげる","もうどうけん","もえる","もくし","もくてき","もくようび","もちろん","もどる","もらう","もんく","もんだい","やおや","やける","やさい","やさしい","やすい","やすたろう","やすみ","やせる","やそう","やたい","やちん","やっと","やっぱり","やぶる","やめる","ややこしい","やよい","やわらかい","ゆうき","ゆうびんきょく","ゆうべ","ゆうめい","ゆけつ","ゆしゅつ","ゆせん","ゆそう","ゆたか","ゆちゃく","ゆでる","ゆにゅう","ゆびわ","ゆらい","ゆれる","ようい","ようか","ようきゅう","ようじ","ようす","ようちえん","よかぜ","よかん","よきん","よくせい","よくぼう","よけい","よごれる","よさん","よしゅう","よそう","よそく","よっか","よてい","よどがわく","よねつ","よやく","よゆう","よろこぶ","よろしい","らいう","らくがき","らくご","らくさつ","らくだ","らしんばん","らせん","らぞく","らたい","らっか","られつ","りえき","りかい","りきさく","りきせつ","りくぐん","りくつ","りけん","りこう","りせい","りそう","りそく","りてん","りねん","りゆう","りゅうがく","りよう","りょうり","りょかん","りょくちゃ","りょこう","りりく","りれき","りろん","りんご","るいけい","るいさい","るいじ","るいせき","るすばん","るりがわら","れいかん","れいぎ","れいせい","れいぞうこ","れいとう","れいぼう","れきし","れきだい","れんあい","れんけい","れんこん","れんさい","れんしゅう","れんぞく","れんらく","ろうか","ろうご","ろうじん","ろうそく","ろくが","ろこつ","ろじうら","ろしゅつ","ろせん","ろてん","ろめん","ろれつ","ろんぎ","ろんぱ","ろんぶん","ろんり","わかす","わかめ","わかやま","わかれる","わしつ","わじまし","わすれもの","わらう","われる"]["가격","가끔","가난","가능","가득","가르침","가뭄","가방","가상","가슴","가운데","가을","가이드","가입","가장","가정","가족","가죽","각오","각자","간격","간부","간섭","간장","간접","간판","갈등","갈비","갈색","갈증","감각","감기","감소","감수성","감자","감정","갑자기","강남","강당","강도","강력히","강변","강북","강사","강수량","강아지","강원도","강의","강제","강조","같이","개구리","개나리","개방","개별","개선","개성","개인","객관적","거실","거액","거울","거짓","거품","걱정","건강","건물","건설","건조","건축","걸음","검사","검토","게시판","게임","겨울","견해","결과","결국","결론","결석","결승","결심","결정","결혼","경계","경고","경기","경력","경복궁","경비","경상도","경영","경우","경쟁","경제","경주","경찰","경치","경향","경험","계곡","계단","계란","계산","계속","계약","계절","계층","계획","고객","고구려","고궁","고급","고등학생","고무신","고민","고양이","고장","고전","고집","고춧가루","고통","고향","곡식","골목","골짜기","골프","공간","공개","공격","공군","공급","공기","공동","공무원","공부","공사","공식","공업","공연","공원","공장","공짜","공책","공통","공포","공항","공휴일","과목","과일","과장","과정","과학","관객","관계","관광","관념","관람","관련","관리","관습","관심","관점","관찰","광경","광고","광장","광주","괴로움","굉장히","교과서","교문","교복","교실","교양","교육","교장","교직","교통","교환","교훈","구경","구름","구멍","구별","구분","구석","구성","구속","구역","구입","구청","구체적","국가","국기","국내","국립","국물","국민","국수","국어","국왕","국적","국제","국회","군대","군사","군인","궁극적","권리","권위","권투","귀국","귀신","규정","규칙","균형","그날","그냥","그늘","그러나","그룹","그릇","그림","그제서야","그토록","극복","극히","근거","근교","근래","근로","근무","근본","근원","근육","근처","글씨","글자","금강산","금고","금년","금메달","금액","금연","금요일","금지","긍정적","기간","기관","기념","기능","기독교","기둥","기록","기름","기법","기본","기분","기쁨","기숙사","기술","기억","기업","기온","기운","기원","기적","기준","기침","기혼","기획","긴급","긴장","길이","김밥","김치","김포공항","깍두기","깜빡","깨달음","깨소금","껍질","꼭대기","꽃잎","나들이","나란히","나머지","나물","나침반","나흘","낙엽","난방","날개","날씨","날짜","남녀","남대문","남매","남산","남자","남편","남학생","낭비","낱말","내년","내용","내일","냄비","냄새","냇물","냉동","냉면","냉방","냉장고","넥타이","넷째","노동","노란색","노력","노인","녹음","녹차","녹화","논리","논문","논쟁","놀이","농구","농담","농민","농부","농업","농장","농촌","높이","눈동자","눈물","눈썹","뉴욕","느낌","늑대","능동적","능력","다방","다양성","다음","다이어트","다행","단계","단골","단독","단맛","단순","단어","단위","단점","단체","단추","단편","단풍","달걀","달러","달력","달리","닭고기","담당","담배","담요","담임","답변","답장","당근","당분간","당연히","당장","대규모","대낮","대단히","대답","대도시","대략","대량","대륙","대문","대부분","대신","대응","대장","대전","대접","대중","대책","대출","대충","대통령","대학","대한민국","대합실","대형","덩어리","데이트","도대체","도덕","도둑","도망","도서관","도심","도움","도입","도자기","도저히","도전","도중","도착","독감","독립","독서","독일","독창적","동화책","뒷모습","뒷산","딸아이","마누라","마늘","마당","마라톤","마련","마무리","마사지","마약","마요네즈","마을","마음","마이크","마중","마지막","마찬가지","마찰","마흔","막걸리","막내","막상","만남","만두","만세","만약","만일","만점","만족","만화","많이","말기","말씀","말투","맘대로","망원경","매년","매달","매력","매번","매스컴","매일","매장","맥주","먹이","먼저","먼지","멀리","메일","며느리","며칠","면담","멸치","명단","명령","명예","명의","명절","명칭","명함","모금","모니터","모델","모든","모범","모습","모양","모임","모조리","모집","모퉁이","목걸이","목록","목사","목소리","목숨","목적","목표","몰래","몸매","몸무게","몸살","몸속","몸짓","몸통","몹시","무관심","무궁화","무더위","무덤","무릎","무슨","무엇","무역","무용","무조건","무지개","무척","문구","문득","문법","문서","문제","문학","문화","물가","물건","물결","물고기","물론","물리학","물음","물질","물체","미국","미디어","미사일","미술","미역","미용실","미움","미인","미팅","미혼","민간","민족","민주","믿음","밀가루","밀리미터","밑바닥","바가지","바구니","바나나","바늘","바닥","바닷가","바람","바이러스","바탕","박물관","박사","박수","반대","반드시","반말","반발","반성","반응","반장","반죽","반지","반찬","받침","발가락","발걸음","발견","발달","발레","발목","발바닥","발생","발음","발자국","발전","발톱","발표","밤하늘","밥그릇","밥맛","밥상","밥솥","방금","방면","방문","방바닥","방법","방송","방식","방안","방울","방지","방학","방해","방향","배경","배꼽","배달","배드민턴","백두산","백색","백성","백인","백제","백화점","버릇","버섯","버튼","번개","번역","번지","번호","벌금","벌레","벌써","범위","범인","범죄","법률","법원","법적","법칙","베이징","벨트","변경","변동","변명","변신","변호사","변화","별도","별명","별일","병실","병아리","병원","보관","보너스","보라색","보람","보름","보상","보안","보자기","보장","보전","보존","보통","보편적","보험","복도","복사","복숭아","복습","볶음","본격적","본래","본부","본사","본성","본인","본질","볼펜","봉사","봉지","봉투","부근","부끄러움","부담","부동산","부문","부분","부산","부상","부엌","부인","부작용","부장","부정","부족","부지런히","부친","부탁","부품","부회장","북부","북한","분노","분량","분리","분명","분석","분야","분위기","분필","분홍색","불고기","불과","불교","불꽃","불만","불법","불빛","불안","불이익","불행","브랜드","비극","비난","비닐","비둘기","비디오","비로소","비만","비명","비밀","비바람","비빔밥","비상","비용","비율","비중","비타민","비판","빌딩","빗물","빗방울","빗줄기","빛깔","빨간색","빨래","빨리","사건","사계절","사나이","사냥","사람","사랑","사립","사모님","사물","사방","사상","사생활","사설","사슴","사실","사업","사용","사월","사장","사전","사진","사촌","사춘기","사탕","사투리","사흘","산길","산부인과","산업","산책","살림","살인","살짝","삼계탕","삼국","삼십","삼월","삼촌","상관","상금","상대","상류","상반기","상상","상식","상업","상인","상자","상점","상처","상추","상태","상표","상품","상황","새벽","색깔","색연필","생각","생명","생물","생방송","생산","생선","생신","생일","생활","서랍","서른","서명","서민","서비스","서양","서울","서적","서점","서쪽","서클","석사","석유","선거","선물","선배","선생","선수","선원","선장","선전","선택","선풍기","설거지","설날","설렁탕","설명","설문","설사","설악산","설치","설탕","섭씨","성공","성당","성명","성별","성인","성장","성적","성질","성함","세금","세미나","세상","세월","세종대왕","세탁","센터","센티미터","셋째","소규모","소극적","소금","소나기","소년","소득","소망","소문","소설","소속","소아과","소용","소원","소음","소중히","소지품","소질","소풍","소형","속담","속도","속옷","손가락","손길","손녀","손님","손등","손목","손뼉","손실","손질","손톱","손해","솔직히","솜씨","송아지","송이","송편","쇠고기","쇼핑","수건","수년","수단","수돗물","수동적","수면","수명","수박","수상","수석","수술","수시로","수업","수염","수영","수입","수준","수집","수출","수컷","수필","수학","수험생","수화기","숙녀","숙소","숙제","순간","순서","순수","순식간","순위","숟가락","술병","술집","숫자","스님","스물","스스로","스승","스웨터","스위치","스케이트","스튜디오","스트레스","스포츠","슬쩍","슬픔","습관","습기","승객","승리","승부","승용차","승진","시각","시간","시골","시금치","시나리오","시댁","시리즈","시멘트","시민","시부모","시선","시설","시스템","시아버지","시어머니","시월","시인","시일","시작","시장","시절","시점","시중","시즌","시집","시청","시합","시험","식구","식기","식당","식량","식료품","식물","식빵","식사","식생활","식초","식탁","식품","신고","신규","신념","신문","신발","신비","신사","신세","신용","신제품","신청","신체","신화","실감","실내","실력","실례","실망","실수","실습","실시","실장","실정","실질적","실천","실체","실컷","실태","실패","실험","실현","심리","심부름","심사","심장","심정","심판","쌍둥이","씨름","씨앗","아가씨","아나운서","아드님","아들","아쉬움","아스팔트","아시아","아울러","아저씨","아줌마","아직","아침","아파트","아프리카","아픔","아홉","아흔","악기","악몽","악수","안개","안경","안과","안내","안녕","안동","안방","안부","안주","알루미늄","알코올","암시","암컷","압력","앞날","앞문","애인","애정","액수","앨범","야간","야단","야옹","약간","약국","약속","약수","약점","약품","약혼녀","양념","양력","양말","양배추","양주","양파","어둠","어려움","어른","어젯밤","어쨌든","어쩌다가","어쩐지","언니","언덕","언론","언어","얼굴","얼른","얼음","얼핏","엄마","업무","업종","업체","엉덩이","엉망","엉터리","엊그제","에너지","에어컨","엔진","여건","여고생","여관","여군","여권","여대생","여덟","여동생","여든","여론","여름","여섯","여성","여왕","여인","여전히","여직원","여학생","여행","역사","역시","역할","연결","연구","연극","연기","연락","연설","연세","연속","연습","연애","연예인","연인","연장","연주","연출","연필","연합","연휴","열기","열매","열쇠","열심히","열정","열차","열흘","염려","엽서","영국","영남","영상","영양","영역","영웅","영원히","영하","영향","영혼","영화","옆구리","옆방","옆집","예감","예금","예방","예산","예상","예선","예술","예습","예식장","예약","예전","예절","예정","예컨대","옛날","오늘","오락","오랫동안","오렌지","오로지","오른발","오븐","오십","오염","오월","오전","오직","오징어","오페라","오피스텔","오히려","옥상","옥수수","온갖","온라인","온몸","온종일","온통","올가을","올림픽","올해","옷차림","와이셔츠","와인","완성","완전","왕비","왕자","왜냐하면","왠지","외갓집","외국","외로움","외삼촌","외출","외침","외할머니","왼발","왼손","왼쪽","요금","요일","요즘","요청","용기","용서","용어","우산","우선","우승","우연히","우정","우체국","우편","운동","운명","운반","운전","운행","울산","울음","움직임","웃어른","웃음","워낙","원고","원래","원서","원숭이","원인","원장","원피스","월급","월드컵","월세","월요일","웨이터","위반","위법","위성","위원","위험","위협","윗사람","유난히","유럽","유명","유물","유산","유적","유치원","유학","유행","유형","육군","육상","육십","육체","은행","음력","음료","음반","음성","음식","음악","음주","의견","의논","의문","의복","의식","의심","의외로","의욕","의원","의학","이것","이곳","이념","이놈","이달","이대로","이동","이렇게","이력서","이론적","이름","이민","이발소","이별","이불","이빨","이상","이성","이슬","이야기","이용","이웃","이월","이윽고","이익","이전","이중","이튿날","이틀","이혼","인간","인격","인공","인구","인근","인기","인도","인류","인물","인생","인쇄","인연","인원","인재","인종","인천","인체","인터넷","인하","인형","일곱","일기","일단","일대","일등","일반","일본","일부","일상","일생","일손","일요일","일월","일정","일종","일주일","일찍","일체","일치","일행","일회용","임금","임무","입대","입력","입맛","입사","입술","입시","입원","입장","입학","자가용","자격","자극","자동","자랑","자부심","자식","자신","자연","자원","자율","자전거","자정","자존심","자판","작가","작년","작성","작업","작용","작은딸","작품","잔디","잔뜩","잔치","잘못","잠깐","잠수함","잠시","잠옷","잠자리","잡지","장관","장군","장기간","장래","장례","장르","장마","장면","장모","장미","장비","장사","장소","장식","장애인","장인","장점","장차","장학금","재능","재빨리","재산","재생","재작년","재정","재채기","재판","재학","재활용","저것","저고리","저곳","저녁","저런","저렇게","저번","저울","저절로","저축","적극","적당히","적성","적용","적응","전개","전공","전기","전달","전라도","전망","전문","전반","전부","전세","전시","전용","전자","전쟁","전주","전철","전체","전통","전혀","전후","절대","절망","절반","절약","절차","점검","점수","점심","점원","점점","점차","접근","접시","접촉","젓가락","정거장","정도","정류장","정리","정말","정면","정문","정반대","정보","정부","정비","정상","정성","정오","정원","정장","정지","정치","정확히","제공","제과점","제대로","제목","제발","제법","제삿날","제안","제일","제작","제주도","제출","제품","제한","조각","조건","조금","조깅","조명","조미료","조상","조선","조용히","조절","조정","조직","존댓말","존재","졸업","졸음","종교","종로","종류","종소리","종업원","종종","종합","좌석","죄인","주관적","주름","주말","주머니","주먹","주문","주민","주방","주변","주식","주인","주일","주장","주전자","주택","준비","줄거리","줄기","줄무늬","중간","중계방송","중국","중년","중단","중독","중반","중부","중세","중소기업","중순","중앙","중요","중학교","즉석","즉시","즐거움","증가","증거","증권","증상","증세","지각","지갑","지경","지극히","지금","지급","지능","지름길","지리산","지방","지붕","지식","지역","지우개","지원","지적","지점","지진","지출","직선","직업","직원","직장","진급","진동","진로","진료","진리","진짜","진찰","진출","진통","진행","질문","질병","질서","짐작","집단","집안","집중","짜증","찌꺼기","차남","차라리","차량","차림","차별","차선","차츰","착각","찬물","찬성","참가","참기름","참새","참석","참여","참외","참조","찻잔","창가","창고","창구","창문","창밖","창작","창조","채널","채점","책가방","책방","책상","책임","챔피언","처벌","처음","천국","천둥","천장","천재","천천히","철도","철저히","철학","첫날","첫째","청년","청바지","청소","청춘","체계","체력","체온","체육","체중","체험","초등학생","초반","초밥","초상화","초순","초여름","초원","초저녁","초점","초청","초콜릿","촛불","총각","총리","총장","촬영","최근","최상","최선","최신","최악","최종","추석","추억","추진","추천","추측","축구","축소","축제","축하","출근","출발","출산","출신","출연","출입","출장","출판","충격","충고","충돌","충분히","충청도","취업","취직","취향","치약","친구","친척","칠십","칠월","칠판","침대","침묵","침실","칫솔","칭찬","카메라","카운터","칼국수","캐릭터","캠퍼스","캠페인","커튼","컨디션","컬러","컴퓨터","코끼리","코미디","콘서트","콜라","콤플렉스","콩나물","쾌감","쿠데타","크림","큰길","큰딸","큰소리","큰아들","큰어머니","큰일","큰절","클래식","클럽","킬로","타입","타자기","탁구","탁자","탄생","태권도","태양","태풍","택시","탤런트","터널","터미널","테니스","테스트","테이블","텔레비전","토론","토마토","토요일","통계","통과","통로","통신","통역","통일","통장","통제","통증","통합","통화","퇴근","퇴원","퇴직금","튀김","트럭","특급","특별","특성","특수","특징","특히","튼튼히","티셔츠","파란색","파일","파출소","판결","판단","판매","판사","팔십","팔월","팝송","패션","팩스","팩시밀리","팬티","퍼센트","페인트","편견","편의","편지","편히","평가","평균","평생","평소","평양","평일","평화","포스터","포인트","포장","포함","표면","표정","표준","표현","품목","품질","풍경","풍속","풍습","프랑스","프린터","플라스틱","피곤","피망","피아노","필름","필수","필요","필자","필통","핑계","하느님","하늘","하드웨어","하룻밤","하반기","하숙집","하순","하여튼","하지만","하천","하품","하필","학과","학교","학급","학기","학년","학력","학번","학부모","학비","학생","학술","학습","학용품","학원","학위","학자","학점","한계","한글","한꺼번에","한낮","한눈","한동안","한때","한라산","한마디","한문","한번","한복","한식","한여름","한쪽","할머니","할아버지","할인","함께","함부로","합격","합리적","항공","항구","항상","항의","해결","해군","해답","해당","해물","해석","해설","해수욕장","해안","핵심","핸드백","햄버거","햇볕","햇살","행동","행복","행사","행운","행위","향기","향상","향수","허락","허용","헬기","현관","현금","현대","현상","현실","현장","현재","현지","혈액","협력","형부","형사","형수","형식","형제","형태","형편","혜택","호기심","호남","호랑이","호박","호텔","호흡","혹시","홀로","홈페이지","홍보","홍수","홍차","화면","화분","화살","화요일","화장","화학","확보","확인","확장","확정","환갑","환경","환영","환율","환자","활기","활동","활발히","활용","활짝","회견","회관","회복","회색","회원","회장","회전","횟수","횡단보도","효율적","후반","후춧가루","훈련","훨씬","휴식","휴일","흉내","흐름","흑백","흑인","흔적","흔히","흥미","흥분","희곡","희망","희생","흰색","힘껏"]{"的":["chinese_simplified","chinese_traditional"],"一":["chinese_simplified","chinese_traditional"],"是":["chinese_simplified","chinese_traditional"],"在":["chinese_simplified","chinese_traditional"],"不":["chinese_simplified","chinese_traditional"],"了":["chinese_simplified","chinese_traditional"],"有":["chinese_simplified","chinese_traditional"],"和":["chinese_simplified","chinese_traditional"],"人":["chinese_simplified","chinese_traditional"],"这":["chinese_simplified"],"中":["chinese_simplified","chinese_traditional"],"大":["chinese_simplified","chinese_traditional"],"为":["chinese_simplified"],"上":["chinese_simplified","chinese_traditional"],"个":["chinese_simplified"],"国":["chinese_simplified"],"我":["chinese_simplified","chinese_traditional"],"以":["chinese_simplified","chinese_traditional"],"要":["chinese_simplified","chinese_traditional"],"他":["chinese_simplified","chinese_traditional"],"时":["chinese_simplified"],"来":["chinese_simplified"],"用":["chinese_simplified","chinese_traditional"],"们":["chinese_simplified"],"生":["chinese_simplified","chinese_traditional"],"到":["chinese_simplified","chinese_traditional"],"作":["chinese_simplified","chinese_traditional"],"地":["chinese_simplified","chinese_traditional"],"于":["chinese_simplified"],"出":["chinese_simplified","chinese_traditional"],"就":["chinese_simplified","chinese_traditional"],"分":["chinese_simplified","chinese_traditional"],"对":["chinese_simplified"],"成":["chinese_simplified","chinese_traditional"],"会":["chinese_simplified"],"可":["chinese_simplified","chinese_traditional"],"主":["chinese_simplified","chinese_traditional"],"发":["chinese_simplified"],"年":["chinese_simplified","chinese_traditional"],"动":["chinese_simplified"],"同":["chinese_simplified","chinese_traditional"],"工":["chinese_simplified","chinese_traditional"],"也":["chinese_simplified","chinese_traditional"],"能":["chinese_simplified","chinese_traditional"],"下":["chinese_simplified","chinese_traditional"],"过":["chinese_simplified"],"子":["chinese_simplified","chinese_traditional"],"说":["chinese_simplified"],"产":["chinese_simplified"],"种":["chinese_simplified"],"面":["chinese_simplified","chinese_traditional"],"而":["chinese_simplified","chinese_traditional"],"方":["chinese_simplified","chinese_traditional"],"后":["chinese_simplified"],"多":["chinese_simplified","chinese_traditional"],"定":["chinese_simplified","chinese_traditional"],"行":["chinese_simplified","chinese_traditional"],"学":["chinese_simplified"],"法":["chinese_simplified","chinese_traditional"],"所":["chinese_simplified","chinese_traditional"],"民":["chinese_simplified","chinese_traditional"],"得":["chinese_simplified","chinese_traditional"],"经":["chinese_simplified"],"十":["chinese_simplified","chinese_traditional"],"三":["chinese_simplified","chinese_traditional"],"之":["chinese_simplified","chinese_traditional"],"进":["chinese_simplified"],"着":["chinese_simplified"],"等":["chinese_simplified","chinese_traditional"],"部":["chinese_simplified","chinese_traditional"],"度":["chinese_simplified","chinese_traditional"],"家":["chinese_simplified","chinese_traditional"],"电":["chinese_simplified"],"力":["chinese_simplified","chinese_traditional"],"里":["chinese_simplified"],"如":["chinese_simplified","chinese_traditional"],"水":["chinese_simplified","chinese_traditional"],"化":["chinese_simplified","chinese_traditional"],"高":["chinese_simplified","chinese_traditional"],"自":["chinese_simplified","chinese_traditional"],"二":["chinese_simplified","chinese_traditional"],"理":["chinese_simplified","chinese_traditional"],"起":["chinese_simplified","chinese_traditional"],"小":["chinese_simplified","chinese_traditional"],"物":["chinese_simplified","chinese_traditional"],"现":["chinese_simplified"],"实":["chinese_simplified"],"加":["chinese_simplified","chinese_traditional"],"量":["chinese_simplified","chinese_traditional"],"都":["chinese_simplified","chinese_traditional"],"两":["chinese_simplified"],"体":["chinese_simplified"],"制":["chinese_simplified","chinese_traditional"],"机":["chinese_simplified"],"当":["chinese_simplified"],"使":["chinese_simplified","chinese_traditional"],"点":["chinese_simplified"],"从":["chinese_simplified"],"业":["chinese_simplified"],"本":["chinese_simplified","chinese_traditional"],"去":["chinese_simplified","chinese_traditional"],"把":["chinese_simplified","chinese_traditional"],"性":["chinese_simplified","chinese_traditional"],"好":["chinese_simplified","chinese_traditional"],"应":["chinese_simplified"],"开":["chinese_simplified"],"它":["chinese_simplified","chinese_traditional"],"合":["chinese_simplified","chinese_traditional"],"还":["chinese_simplified"],"因":["chinese_simplified","chinese_traditional"],"由":["chinese_simplified","chinese_traditional"],"其":["chinese_simplified","chinese_traditional"],"些":["chinese_simplified","chinese_traditional"],"然":["chinese_simplified","chinese_traditional"],"前":["chinese_simplified","chinese_traditional"],"外":["chinese_simplified","chinese_traditional"],"天":["chinese_simplified","chinese_traditional"],"政":["chinese_simplified","chinese_traditional"],"四":["chinese_simplified","chinese_traditional"],"日":["chinese_simplified","chinese_traditional"],"那":["chinese_simplified","chinese_traditional"],"社":["chinese_simplified","chinese_traditional"],"义":["chinese_simplified"],"事":["chinese_simplified","chinese_traditional"],"平":["chinese_simplified","chinese_traditional"],"形":["chinese_simplified","chinese_traditional"],"相":["chinese_simplified","chinese_traditional"],"全":["chinese_simplified","chinese_traditional"],"表":["chinese_simplified","chinese_traditional"],"间":["chinese_simplified"],"样":["chinese_simplified"],"与":["chinese_simplified"],"关":["chinese_simplified"],"各":["chinese_simplified","chinese_traditional"],"重":["chinese_simplified","chinese_traditional"],"新":["chinese_simplified","chinese_traditional"],"线":["chinese_simplified"],"内":["chinese_simplified"],"数":["chinese_simplified"],"正":["chinese_simplified","chinese_traditional"],"心":["chinese_simplified","chinese_traditional"],"反":["chinese_simplified","chinese_traditional"],"你":["chinese_simplified","chinese_traditional"],"明":["chinese_simplified","chinese_traditional"],"看":["chinese_simplified","chinese_traditional"],"原":["chinese_simplified","chinese_traditional"],"又":["chinese_simplified","chinese_traditional"],"么":["chinese_simplified"],"利":["chinese_simplified","chinese_traditional"],"比":["chinese_simplified","chinese_traditional"],"或":["chinese_simplified","chinese_traditional"],"但":["chinese_simplified","chinese_traditional"],"质":["chinese_simplified"],"气":["chinese_simplified"],"第":["chinese_simplified","chinese_traditional"],"向":["chinese_simplified","chinese_traditional"],"道":["chinese_simplified","chinese_traditional"],"命":["chinese_simplified","chinese_traditional"],"此":["chinese_simplified","chinese_traditional"],"变":["chinese_simplified"],"条":["chinese_simplified"],"只":["chinese_simplified","chinese_traditional"],"没":["chinese_simplified"],"结":["chinese_simplified"],"解":["chinese_simplified","chinese_traditional"],"问":["chinese_simplified"],"意":["chinese_simplified","chinese_traditional"],"建":["chinese_simplified","chinese_traditional"],"月":["chinese_simplified","chinese_traditional"],"公":["chinese_simplified","chinese_traditional"],"无":["chinese_simplified"],"系":["chinese_simplified","chinese_traditional"],"军":["chinese_simplified"],"很":["chinese_simplified","chinese_traditional"],"情":["chinese_simplified","chinese_traditional"],"者":["chinese_simplified","chinese_traditional"],"最":["chinese_simplified","chinese_traditional"],"立":["chinese_simplified","chinese_traditional"],"代":["chinese_simplified","chinese_traditional"],"想":["chinese_simplified","chinese_traditional"],"已":["chinese_simplified","chinese_traditional"],"通":["chinese_simplified","chinese_traditional"],"并":["chinese_simplified"],"提":["chinese_simplified","chinese_traditional"],"直":["chinese_simplified","chinese_traditional"],"题":["chinese_simplified"],"党":["chinese_simplified"],"程":["chinese_simplified","chinese_traditional"],"展":["chinese_simplified","chinese_traditional"],"五":["chinese_simplified","chinese_traditional"],"果":["chinese_simplified","chinese_traditional"],"料":["chinese_simplified","chinese_traditional"],"象":["chinese_simplified","chinese_traditional"],"员":["chinese_simplified"],"革":["chinese_simplified","chinese_traditional"],"位":["chinese_simplified","chinese_traditional"],"入":["chinese_simplified","chinese_traditional"],"常":["chinese_simplified","chinese_traditional"],"文":["chinese_simplified","chinese_traditional"],"总":["chinese_simplified"],"次":["chinese_simplified","chinese_traditional"],"品":["chinese_simplified","chinese_traditional"],"式":["chinese_simplified","chinese_traditional"],"活":["chinese_simplified","chinese_traditional"],"设":["chinese_simplified"],"及":["chinese_simplified","chinese_traditional"],"管":["chinese_simplified","chinese_traditional"],"特":["chinese_simplified","chinese_traditional"],"件":["chinese_simplified","chinese_traditional"],"长":["chinese_simplified"],"求":["chinese_simplified","chinese_traditional"],"老":["chinese_simplified","chinese_traditional"],"头":["chinese_simplified"],"基":["chinese_simplified","chinese_traditional"],"资":["chinese_simplified"],"边":["chinese_simplified"],"流":["chinese_simplified","chinese_traditional"],"路":["chinese_simplified","chinese_traditional"],"级":["chinese_simplified"],"少":["chinese_simplified","chinese_traditional"],"图":["chinese_simplified"],"山":["chinese_simplified","chinese_traditional"],"统":["chinese_simplified"],"接":["chinese_simplified","chinese_traditional"],"知":["chinese_simplified","chinese_traditional"],"较":["chinese_simplified"],"将":["chinese_simplified"],"组":["chinese_simplified"],"见":["chinese_simplified"],"计":["chinese_simplified"],"别":["chinese_simplified"],"她":["chinese_simplified","chinese_traditional"],"手":["chinese_simplified","chinese_traditional"],"角":["chinese_simplified","chinese_traditional"],"期":["chinese_simplified","chinese_traditional"],"根":["chinese_simplified","chinese_traditional"],"论":["chinese_simplified"],"运":["chinese_simplified"],"农":["chinese_simplified"],"指":["chinese_simplified","chinese_traditional"],"几":["chinese_simplified"],"九":["chinese_simplified","chinese_traditional"],"区":["chinese_simplified"],"强":["chinese_simplified"],"放":["chinese_simplified","chinese_traditional"],"决":["chinese_simplified"],"西":["chinese_simplified","chinese_traditional"],"被":["chinese_simplified","chinese_traditional"],"干":["chinese_simplified"],"做":["chinese_simplified","chinese_traditional"],"必":["chinese_simplified","chinese_traditional"],"战":["chinese_simplified"],"先":["chinese_simplified","chinese_traditional"],"回":["chinese_simplified","chinese_traditional"],"则":["chinese_simplified"],"任":["chinese_simplified","chinese_traditional"],"取":["chinese_simplified","chinese_traditional"],"据":["chinese_simplified"],"处":["chinese_simplified"],"队":["chinese_simplified"],"南":["chinese_simplified","chinese_traditional"],"给":["chinese_simplified"],"色":["chinese_simplified","chinese_traditional"],"光":["chinese_simplified","chinese_traditional"],"门":["chinese_simplified"],"即":["chinese_simplified","chinese_traditional"],"保":["chinese_simplified","chinese_traditional"],"治":["chinese_simplified","chinese_traditional"],"北":["chinese_simplified","chinese_traditional"],"造":["chinese_simplified","chinese_traditional"],"百":["chinese_simplified","chinese_traditional"],"规":["chinese_simplified"],"热":["chinese_simplified"],"领":["chinese_simplified"],"七":["chinese_simplified","chinese_traditional"],"海":["chinese_simplified","chinese_traditional"],"口":["chinese_simplified","chinese_traditional"],"东":["chinese_simplified"],"导":["chinese_simplified"],"器":["chinese_simplified","chinese_traditional"],"压":["chinese_simplified"],"志":["chinese_simplified","chinese_traditional"],"世":["chinese_simplified","chinese_traditional"],"金":["chinese_simplified","chinese_traditional"],"增":["chinese_simplified","chinese_traditional"],"争":["chinese_simplified"],"济":["chinese_simplified"],"阶":["chinese_simplified"],"油":["chinese_simplified","chinese_traditional"],"思":["chinese_simplified","chinese_traditional"],"术":["chinese_simplified"],"极":["chinese_simplified"],"交":["chinese_simplified","chinese_traditional"],"受":["chinese_simplified","chinese_traditional"],"联":["chinese_simplified"],"什":["chinese_simplified","chinese_traditional"],"认":["chinese_simplified"],"六":["chinese_simplified","chinese_traditional"],"共":["chinese_simplified","chinese_traditional"],"权":["chinese_simplified"],"收":["chinese_simplified","chinese_traditional"],"证":["chinese_simplified"],"改":["chinese_simplified","chinese_traditional"],"清":["chinese_simplified","chinese_traditional"],"美":["chinese_simplified","chinese_traditional"],"再":["chinese_simplified","chinese_traditional"],"采":["chinese_simplified"],"转":["chinese_simplified"],"更":["chinese_simplified","chinese_traditional"],"单":["chinese_simplified"],"风":["chinese_simplified"],"切":["chinese_simplified","chinese_traditional"],"打":["chinese_simplified","chinese_traditional"],"白":["chinese_simplified","chinese_traditional"],"教":["chinese_simplified","chinese_traditional"],"速":["chinese_simplified","chinese_traditional"],"花":["chinese_simplified","chinese_traditional"],"带":["chinese_simplified"],"安":["chinese_simplified","chinese_traditional"],"场":["chinese_simplified"],"身":["chinese_simplified","chinese_traditional"],"车":["chinese_simplified"],"例":["chinese_simplified","chinese_traditional"],"真":["chinese_simplified","chinese_traditional"],"务":["chinese_simplified"],"具":["chinese_simplified","chinese_traditional"],"万":["chinese_simplified"],"每":["chinese_simplified","chinese_traditional"],"目":["chinese_simplified","chinese_traditional"],"至":["chinese_simplified","chinese_traditional"],"达":["chinese_simplified"],"走":["chinese_simplified","chinese_traditional"],"积":["chinese_simplified"],"示":["chinese_simplified","chinese_traditional"],"议":["chinese_simplified"],"声":["chinese_simplified"],"报":["chinese_simplified"],"斗":["chinese_simplified"],"完":["chinese_simplified","chinese_traditional"],"类":["chinese_simplified"],"八":["chinese_simplified","chinese_traditional"],"离":["chinese_simplified"],"华":["chinese_simplified"],"名":["chinese_simplified","chinese_traditional"],"确":["chinese_simplified"],"才":["chinese_simplified","chinese_traditional"],"科":["chinese_simplified","chinese_traditional"],"张":["chinese_simplified"],"信":["chinese_simplified","chinese_traditional"],"马":["chinese_simplified"],"节":["chinese_simplified"],"话":["chinese_simplified"],"米":["chinese_simplified","chinese_traditional"],"整":["chinese_simplified","chinese_traditional"],"空":["chinese_simplified","chinese_traditional"],"元":["chinese_simplified","chinese_traditional"],"况":["chinese_simplified"],"今":["chinese_simplified","chinese_traditional"],"集":["chinese_simplified","chinese_traditional"],"温":["chinese_simplified"],"传":["chinese_simplified"],"土":["chinese_simplified","chinese_traditional"],"许":["chinese_simplified"],"步":["chinese_simplified","chinese_traditional"],"群":["chinese_simplified","chinese_traditional"],"广":["chinese_simplified"],"石":["chinese_simplified","chinese_traditional"],"记":["chinese_simplified"],"需":["chinese_simplified","chinese_traditional"],"段":["chinese_simplified","chinese_traditional"],"研":["chinese_simplified","chinese_traditional"],"界":["chinese_simplified","chinese_traditional"],"拉":["chinese_simplified","chinese_traditional"],"林":["chinese_simplified","chinese_traditional"],"律":["chinese_simplified","chinese_traditional"],"叫":["chinese_simplified","chinese_traditional"],"且":["chinese_simplified","chinese_traditional"],"究":["chinese_simplified","chinese_traditional"],"观":["chinese_simplified"],"越":["chinese_simplified","chinese_traditional"],"织":["chinese_simplified"],"装":["chinese_simplified"],"影":["chinese_simplified","chinese_traditional"],"算":["chinese_simplified","chinese_traditional"],"低":["chinese_simplified","chinese_traditional"],"持":["chinese_simplified","chinese_traditional"],"音":["chinese_simplified","chinese_traditional"],"众":["chinese_simplified"],"书":["chinese_simplified"],"布":["chinese_simplified","chinese_traditional"],"复":["chinese_simplified","chinese_traditional"],"容":["chinese_simplified","chinese_traditional"],"儿":["chinese_simplified"],"须":["chinese_simplified"],"际":["chinese_simplified"],"商":["chinese_simplified","chinese_traditional"],"非":["chinese_simplified","chinese_traditional"],"验":["chinese_simplified"],"连":["chinese_simplified"],"断":["chinese_simplified"],"深":["chinese_simplified","chinese_traditional"],"难":["chinese_simplified"],"近":["chinese_simplified","chinese_traditional"],"矿":["chinese_simplified"],"千":["chinese_simplified","chinese_traditional"],"周":["chinese_simplified"],"委":["chinese_simplified","chinese_traditional"],"素":["chinese_simplified","chinese_traditional"],"技":["chinese_simplified","chinese_traditional"],"备":["chinese_simplified"],"半":["chinese_simplified","chinese_traditional"],"办":["chinese_simplified"],"青":["chinese_simplified","chinese_traditional"],"省":["chinese_simplified","chinese_traditional"],"列":["chinese_simplified","chinese_traditional"],"习":["chinese_simplified"],"响":["chinese_simplified"],"约":["chinese_simplified"],"支":["chinese_simplified","chinese_traditional"],"般":["chinese_simplified","chinese_traditional"],"史":["chinese_simplified","chinese_traditional"],"感":["chinese_simplified","chinese_traditional"],"劳":["chinese_simplified"],"便":["chinese_simplified","chinese_traditional"],"团":["chinese_simplified"],"往":["chinese_simplified","chinese_traditional"],"酸":["chinese_simplified","chinese_traditional"],"历":["chinese_simplified"],"市":["chinese_simplified","chinese_traditional"],"克":["chinese_simplified","chinese_traditional"],"何":["chinese_simplified","chinese_traditional"],"除":["chinese_simplified","chinese_traditional"],"消":["chinese_simplified","chinese_traditional"],"构":["chinese_simplified"],"府":["chinese_simplified","chinese_traditional"],"称":["chinese_simplified"],"太":["chinese_simplified","chinese_traditional"],"准":["chinese_simplified"],"精":["chinese_simplified","chinese_traditional"],"值":["chinese_simplified","chinese_traditional"],"号":["chinese_simplified"],"率":["chinese_simplified","chinese_traditional"],"族":["chinese_simplified","chinese_traditional"],"维":["chinese_simplified"],"划":["chinese_simplified"],"选":["chinese_simplified"],"标":["chinese_simplified"],"写":["chinese_simplified"],"存":["chinese_simplified","chinese_traditional"],"候":["chinese_simplified","chinese_traditional"],"毛":["chinese_simplified","chinese_traditional"],"亲":["chinese_simplified"],"快":["chinese_simplified","chinese_traditional"],"效":["chinese_simplified","chinese_traditional"],"斯":["chinese_simplified","chinese_traditional"],"院":["chinese_simplified","chinese_traditional"],"查":["chinese_simplified","chinese_traditional"],"江":["chinese_simplified","chinese_traditional"],"型":["chinese_simplified","chinese_traditional"],"眼":["chinese_simplified","chinese_traditional"],"王":["chinese_simplified","chinese_traditional"],"按":["chinese_simplified","chinese_traditional"],"格":["chinese_simplified","chinese_traditional"],"养":["chinese_simplified"],"易":["chinese_simplified","chinese_traditional"],"置":["chinese_simplified","chinese_traditional"],"派":["chinese_simplified","chinese_traditional"],"层":["chinese_simplified"],"片":["chinese_simplified","chinese_traditional"],"始":["chinese_simplified","chinese_traditional"],"却":["chinese_simplified"],"专":["chinese_simplified"],"状":["chinese_simplified"],"育":["chinese_simplified","chinese_traditional"],"厂":["chinese_simplified"],"京":["chinese_simplified","chinese_traditional"],"识":["chinese_simplified"],"适":["chinese_simplified"],"属":["chinese_simplified"],"圆":["chinese_simplified"],"包":["chinese_simplified","chinese_traditional"],"火":["chinese_simplified","chinese_traditional"],"住":["chinese_simplified","chinese_traditional"],"调":["chinese_simplified"],"满":["chinese_simplified"],"县":["chinese_simplified"],"局":["chinese_simplified","chinese_traditional"],"照":["chinese_simplified","chinese_traditional"],"参":["chinese_simplified"],"红":["chinese_simplified"],"细":["chinese_simplified"],"引":["chinese_simplified","chinese_traditional"],"听":["chinese_simplified"],"该":["chinese_simplified"],"铁":["chinese_simplified"],"价":["chinese_simplified"],"严":["chinese_simplified"],"首":["chinese_simplified","chinese_traditional"],"底":["chinese_simplified","chinese_traditional"],"液":["chinese_simplified","chinese_traditional"],"官":["chinese_simplified","chinese_traditional"],"德":["chinese_simplified","chinese_traditional"],"随":["chinese_simplified"],"病":["chinese_simplified","chinese_traditional"],"苏":["chinese_simplified"],"失":["chinese_simplified","chinese_traditional"],"尔":["chinese_simplified"],"死":["chinese_simplified","chinese_traditional"],"讲":["chinese_simplified"],"配":["chinese_simplified","chinese_traditional"],"女":["chinese_simplified","chinese_traditional"],"黄":["chinese_simplified"],"推":["chinese_simplified","chinese_traditional"],"显":["chinese_simplified"],"谈":["chinese_simplified"],"罪":["chinese_simplified","chinese_traditional"],"神":["chinese_simplified","chinese_traditional"],"艺":["chinese_simplified"],"呢":["chinese_simplified","chinese_traditional"],"席":["chinese_simplified","chinese_traditional"],"含":["chinese_simplified","chinese_traditional"],"企":["chinese_simplified","chinese_traditional"],"望":["chinese_simplified","chinese_traditional"],"密":["chinese_simplified","chinese_traditional"],"批":["chinese_simplified","chinese_traditional"],"营":["chinese_simplified"],"项":["chinese_simplified"],"防":["chinese_simplified","chinese_traditional"],"举":["chinese_simplified"],"球":["chinese_simplified","chinese_traditional"],"英":["chinese_simplified","chinese_traditional"],"氧":["chinese_simplified","chinese_traditional"],"势":["chinese_simplified"],"告":["chinese_simplified","chinese_traditional"],"李":["chinese_simplified","chinese_traditional"],"台":["chinese_simplified","chinese_traditional"],"落":["chinese_simplified","chinese_traditional"],"木":["chinese_simplified","chinese_traditional"],"帮":["chinese_simplified"],"轮":["chinese_simplified"],"破":["chinese_simplified","chinese_traditional"],"亚":["chinese_simplified"],"师":["chinese_simplified"],"围":["chinese_simplified"],"注":["chinese_simplified","chinese_traditional"],"远":["chinese_simplified"],"字":["chinese_simplified","chinese_traditional"],"材":["chinese_simplified","chinese_traditional"],"排":["chinese_simplified","chinese_traditional"],"供":["chinese_simplified","chinese_traditional"],"河":["chinese_simplified","chinese_traditional"],"态":["chinese_simplified"],"封":["chinese_simplified","chinese_traditional"],"另":["chinese_simplified","chinese_traditional"],"施":["chinese_simplified","chinese_traditional"],"减":["chinese_simplified"],"树":["chinese_simplified"],"溶":["chinese_simplified","chinese_traditional"],"怎":["chinese_simplified","chinese_traditional"],"止":["chinese_simplified","chinese_traditional"],"案":["chinese_simplified","chinese_traditional"],"言":["chinese_simplified","chinese_traditional"],"士":["chinese_simplified","chinese_traditional"],"均":["chinese_simplified","chinese_traditional"],"武":["chinese_simplified","chinese_traditional"],"固":["chinese_simplified","chinese_traditional"],"叶":["chinese_simplified"],"鱼":["chinese_simplified"],"波":["chinese_simplified","chinese_traditional"],"视":["chinese_simplified"],"仅":["chinese_simplified"],"费":["chinese_simplified"],"紧":["chinese_simplified"],"爱":["chinese_simplified"],"左":["chinese_simplified","chinese_traditional"],"章":["chinese_simplified","chinese_traditional"],"早":["chinese_simplified","chinese_traditional"],"朝":["chinese_simplified","chinese_traditional"],"害":["chinese_simplified","chinese_traditional"],"续":["chinese_simplified"],"轻":["chinese_simplified"],"服":["chinese_simplified","chinese_traditional"],"试":["chinese_simplified"],"食":["chinese_simplified","chinese_traditional"],"充":["chinese_simplified","chinese_traditional"],"兵":["chinese_simplified","chinese_traditional"],"源":["chinese_simplified","chinese_traditional"],"判":["chinese_simplified","chinese_traditional"],"护":["chinese_simplified"],"司":["chinese_simplified","chinese_traditional"],"足":["chinese_simplified","chinese_traditional"],"某":["chinese_simplified","chinese_traditional"],"练":["chinese_simplified"],"差":["chinese_simplified","chinese_traditional"],"致":["chinese_simplified","chinese_traditional"],"板":["chinese_simplified","chinese_traditional"],"田":["chinese_simplified","chinese_traditional"],"降":["chinese_simplified","chinese_traditional"],"黑":["chinese_simplified","chinese_traditional"],"犯":["chinese_simplified","chinese_traditional"],"负":["chinese_simplified"],"击":["chinese_simplified"],"范":["chinese_simplified","chinese_traditional"],"继":["chinese_simplified"],"兴":["chinese_simplified"],"似":["chinese_simplified","chinese_traditional"],"余":["chinese_simplified"],"坚":["chinese_simplified"],"曲":["chinese_simplified","chinese_traditional"],"输":["chinese_simplified"],"修":["chinese_simplified","chinese_traditional"],"故":["chinese_simplified","chinese_traditional"],"城":["chinese_simplified","chinese_traditional"],"夫":["chinese_simplified","chinese_traditional"],"够":["chinese_simplified"],"送":["chinese_simplified","chinese_traditional"],"笔":["chinese_simplified"],"船":["chinese_simplified","chinese_traditional"],"占":["chinese_simplified"],"右":["chinese_simplified","chinese_traditional"],"财":["chinese_simplified"],"吃":["chinese_simplified","chinese_traditional"],"富":["chinese_simplified","chinese_traditional"],"春":["chinese_simplified","chinese_traditional"],"职":["chinese_simplified"],"觉":["chinese_simplified"],"汉":["chinese_simplified"],"画":["chinese_simplified"],"功":["chinese_simplified","chinese_traditional"],"巴":["chinese_simplified","chinese_traditional"],"跟":["chinese_simplified","chinese_traditional"],"虽":["chinese_simplified"],"杂":["chinese_simplified"],"飞":["chinese_simplified"],"检":["chinese_simplified"],"吸":["chinese_simplified","chinese_traditional"],"助":["chinese_simplified","chinese_traditional"],"升":["chinese_simplified"],"阳":["chinese_simplified"],"互":["chinese_simplified","chinese_traditional"],"初":["chinese_simplified","chinese_traditional"],"创":["chinese_simplified"],"抗":["chinese_simplified","chinese_traditional"],"考":["chinese_simplified","chinese_traditional"],"投":["chinese_simplified","chinese_traditional"],"坏":["chinese_simplified"],"策":["chinese_simplified","chinese_traditional"],"古":["chinese_simplified","chinese_traditional"],"径":["chinese_simplified"],"换":["chinese_simplified"],"未":["chinese_simplified","chinese_traditional"],"跑":["chinese_simplified","chinese_traditional"],"留":["chinese_simplified","chinese_traditional"],"钢":["chinese_simplified"],"曾":["chinese_simplified","chinese_traditional"],"端":["chinese_simplified","chinese_traditional"],"责":["chinese_simplified"],"站":["chinese_simplified","chinese_traditional"],"简":["chinese_simplified"],"述":["chinese_simplified","chinese_traditional"],"钱":["chinese_simplified"],"副":["chinese_simplified","chinese_traditional"],"尽":["chinese_simplified"],"帝":["chinese_simplified","chinese_traditional"],"射":["chinese_simplified","chinese_traditional"],"草":["chinese_simplified","chinese_traditional"],"冲":["chinese_simplified"],"承":["chinese_simplified","chinese_traditional"],"独":["chinese_simplified"],"令":["chinese_simplified","chinese_traditional"],"限":["chinese_simplified","chinese_traditional"],"阿":["chinese_simplified","chinese_traditional"],"宣":["chinese_simplified","chinese_traditional"],"环":["chinese_simplified"],"双":["chinese_simplified"],"请":["chinese_simplified"],"超":["chinese_simplified","chinese_traditional"],"微":["chinese_simplified","chinese_traditional"],"让":["chinese_simplified"],"控":["chinese_simplified","chinese_traditional"],"州":["chinese_simplified","chinese_traditional"],"良":["chinese_simplified","chinese_traditional"],"轴":["chinese_simplified"],"找":["chinese_simplified","chinese_traditional"],"否":["chinese_simplified","chinese_traditional"],"纪":["chinese_simplified"],"益":["chinese_simplified","chinese_traditional"],"依":["chinese_simplified","chinese_traditional"],"优":["chinese_simplified"],"顶":["chinese_simplified"],"础":["chinese_simplified"],"载":["chinese_simplified"],"倒":["chinese_simplified","chinese_traditional"],"房":["chinese_simplified","chinese_traditional"],"突":["chinese_simplified","chinese_traditional"],"坐":["chinese_simplified","chinese_traditional"],"粉":["chinese_simplified","chinese_traditional"],"敌":["chinese_simplified"],"略":["chinese_simplified","chinese_traditional"],"客":["chinese_simplified","chinese_traditional"],"袁":["chinese_simplified","chinese_traditional"],"冷":["chinese_simplified","chinese_traditional"],"胜":["chinese_simplified"],"绝":["chinese_simplified"],"析":["chinese_simplified","chinese_traditional"],"块":["chinese_simplified"],"剂":["chinese_simplified"],"测":["chinese_simplified"],"丝":["chinese_simplified"],"协":["chinese_simplified"],"诉":["chinese_simplified"],"念":["chinese_simplified","chinese_traditional"],"陈":["chinese_simplified"],"仍":["chinese_simplified","chinese_traditional"],"罗":["chinese_simplified"],"盐":["chinese_simplified"],"友":["chinese_simplified","chinese_traditional"],"洋":["chinese_simplified","chinese_traditional"],"错":["chinese_simplified"],"苦":["chinese_simplified","chinese_traditional"],"夜":["chinese_simplified","chinese_traditional"],"刑":["chinese_simplified","chinese_traditional"],"移":["chinese_simplified","chinese_traditional"],"频":["chinese_simplified"],"逐":["chinese_simplified","chinese_traditional"],"靠":["chinese_simplified","chinese_traditional"],"混":["chinese_simplified","chinese_traditional"],"母":["chinese_simplified","chinese_traditional"],"短":["chinese_simplified","chinese_traditional"],"皮":["chinese_simplified","chinese_traditional"],"终":["chinese_simplified"],"聚":["chinese_simplified","chinese_traditional"],"汽":["chinese_simplified","chinese_traditional"],"村":["chinese_simplified","chinese_traditional"],"云":["chinese_simplified"],"哪":["chinese_simplified","chinese_traditional"],"既":["chinese_simplified","chinese_traditional"],"距":["chinese_simplified","chinese_traditional"],"卫":["chinese_simplified"],"停":["chinese_simplified","chinese_traditional"],"烈":["chinese_simplified","chinese_traditional"],"央":["chinese_simplified","chinese_traditional"],"察":["chinese_simplified","chinese_traditional"],"烧":["chinese_simplified"],"迅":["chinese_simplified","chinese_traditional"],"境":["chinese_simplified","chinese_traditional"],"若":["chinese_simplified","chinese_traditional"],"印":["chinese_simplified","chinese_traditional"],"洲":["chinese_simplified","chinese_traditional"],"刻":["chinese_simplified","chinese_traditional"],"括":["chinese_simplified","chinese_traditional"],"激":["chinese_simplified","chinese_traditional"],"孔":["chinese_simplified","chinese_traditional"],"搞":["chinese_simplified","chinese_traditional"],"甚":["chinese_simplified","chinese_traditional"],"室":["chinese_simplified","chinese_traditional"],"待":["chinese_simplified","chinese_traditional"],"核":["chinese_simplified","chinese_traditional"],"校":["chinese_simplified","chinese_traditional"],"散":["chinese_simplified","chinese_traditional"],"侵":["chinese_simplified","chinese_traditional"],"吧":["chinese_simplified","chinese_traditional"],"甲":["chinese_simplified","chinese_traditional"],"游":["chinese_simplified"],"久":["chinese_simplified","chinese_traditional"],"菜":["chinese_simplified","chinese_traditional"],"味":["chinese_simplified","chinese_traditional"],"旧":["chinese_simplified"],"模":["chinese_simplified","chinese_traditional"],"湖":["chinese_simplified","chinese_traditional"],"货":["chinese_simplified"],"损":["chinese_simplified"],"预":["chinese_simplified"],"阻":["chinese_simplified","chinese_traditional"],"毫":["chinese_simplified","chinese_traditional"],"普":["chinese_simplified","chinese_traditional"],"稳":["chinese_simplified"],"乙":["chinese_simplified","chinese_traditional"],"妈":["chinese_simplified"],"植":["chinese_simplified","chinese_traditional"],"息":["chinese_simplified","chinese_traditional"],"扩":["chinese_simplified"],"银":["chinese_simplified"],"语":["chinese_simplified"],"挥":["chinese_simplified"],"酒":["chinese_simplified","chinese_traditional"],"守":["chinese_simplified","chinese_traditional"],"拿":["chinese_simplified","chinese_traditional"],"序":["chinese_simplified","chinese_traditional"],"纸":["chinese_simplified"],"医":["chinese_simplified"],"缺":["chinese_simplified","chinese_traditional"],"雨":["chinese_simplified","chinese_traditional"],"吗":["chinese_simplified"],"针":["chinese_simplified"],"刘":["chinese_simplified"],"啊":["chinese_simplified","chinese_traditional"],"急":["chinese_simplified","chinese_traditional"],"唱":["chinese_simplified","chinese_traditional"],"误":["chinese_simplified"],"训":["chinese_simplified"],"愿":["chinese_simplified"],"审":["chinese_simplified"],"附":["chinese_simplified","chinese_traditional"],"获":["chinese_simplified"],"茶":["chinese_simplified","chinese_traditional"],"鲜":["chinese_simplified"],"粮":["chinese_simplified"],"斤":["chinese_simplified","chinese_traditional"],"孩":["chinese_simplified","chinese_traditional"],"脱":["chinese_simplified"],"硫":["chinese_simplified","chinese_traditional"],"肥":["chinese_simplified","chinese_traditional"],"善":["chinese_simplified","chinese_traditional"],"龙":["chinese_simplified"],"演":["chinese_simplified","chinese_traditional"],"父":["chinese_simplified","chinese_traditional"],"渐":["chinese_simplified"],"血":["chinese_simplified","chinese_traditional"],"欢":["chinese_simplified"],"械":["chinese_simplified","chinese_traditional"],"掌":["chinese_simplified","chinese_traditional"],"歌":["chinese_simplified","chinese_traditional"],"沙":["chinese_simplified","chinese_traditional"],"刚":["chinese_simplified"],"攻":["chinese_simplified","chinese_traditional"],"谓":["chinese_simplified"],"盾":["chinese_simplified","chinese_traditional"],"讨":["chinese_simplified"],"晚":["chinese_simplified","chinese_traditional"],"粒":["chinese_simplified","chinese_traditional"],"乱":["chinese_simplified"],"燃":["chinese_simplified","chinese_traditional"],"矛":["chinese_simplified","chinese_traditional"],"乎":["chinese_simplified","chinese_traditional"],"杀":["chinese_simplified"],"药":["chinese_simplified"],"宁":["chinese_simplified"],"鲁":["chinese_simplified"],"贵":["chinese_simplified"],"钟":["chinese_simplified"],"煤":["chinese_simplified","chinese_traditional"],"读":["chinese_simplified"],"班":["chinese_simplified","chinese_traditional"],"伯":["chinese_simplified","chinese_traditional"],"香":["chinese_simplified","chinese_traditional"],"介":["chinese_simplified","chinese_traditional"],"迫":["chinese_simplified","chinese_traditional"],"句":["chinese_simplified","chinese_traditional"],"丰":["chinese_simplified"],"培":["chinese_simplified","chinese_traditional"],"握":["chinese_simplified","chinese_traditional"],"兰":["chinese_simplified"],"担":["chinese_simplified"],"弦":["chinese_simplified","chinese_traditional"],"蛋":["chinese_simplified","chinese_traditional"],"沉":["chinese_simplified","chinese_traditional"],"假":["chinese_simplified","chinese_traditional"],"穿":["chinese_simplified","chinese_traditional"],"执":["chinese_simplified"],"答":["chinese_simplified","chinese_traditional"],"乐":["chinese_simplified"],"谁":["chinese_simplified"],"顺":["chinese_simplified"],"烟":["chinese_simplified"],"缩":["chinese_simplified"],"征":["chinese_simplified"],"脸":["chinese_simplified"],"喜":["chinese_simplified","chinese_traditional"],"松":["chinese_simplified","chinese_traditional"],"脚":["chinese_simplified"],"困":["chinese_simplified","chinese_traditional"],"异":["chinese_simplified"],"免":["chinese_simplified","chinese_traditional"],"背":["chinese_simplified","chinese_traditional"],"星":["chinese_simplified","chinese_traditional"],"福":["chinese_simplified","chinese_traditional"],"买":["chinese_simplified"],"染":["chinese_simplified","chinese_traditional"],"井":["chinese_simplified","chinese_traditional"],"概":["chinese_simplified","chinese_traditional"],"慢":["chinese_simplified","chinese_traditional"],"怕":["chinese_simplified","chinese_traditional"],"磁":["chinese_simplified","chinese_traditional"],"倍":["chinese_simplified","chinese_traditional"],"祖":["chinese_simplified","chinese_traditional"],"皇":["chinese_simplified","chinese_traditional"],"促":["chinese_simplified","chinese_traditional"],"静":["chinese_simplified"],"补":["chinese_simplified"],"评":["chinese_simplified"],"翻":["chinese_simplified","chinese_traditional"],"肉":["chinese_simplified","chinese_traditional"],"践":["chinese_simplified"],"尼":["chinese_simplified","chinese_traditional"],"衣":["chinese_simplified","chinese_traditional"],"宽":["chinese_simplified"],"扬":["chinese_simplified"],"棉":["chinese_simplified","chinese_traditional"],"希":["chinese_simplified","chinese_traditional"],"伤":["chinese_simplified"],"操":["chinese_simplified","chinese_traditional"],"垂":["chinese_simplified","chinese_traditional"],"秋":["chinese_simplified","chinese_traditional"],"宜":["chinese_simplified","chinese_traditional"],"氢":["chinese_simplified"],"套":["chinese_simplified","chinese_traditional"],"督":["chinese_simplified","chinese_traditional"],"振":["chinese_simplified","chinese_traditional"],"架":["chinese_simplified","chinese_traditional"],"亮":["chinese_simplified","chinese_traditional"],"末":["chinese_simplified","chinese_traditional"],"宪":["chinese_simplified"],"庆":["chinese_simplified"],"编":["chinese_simplified"],"牛":["chinese_simplified","chinese_traditional"],"触":["chinese_simplified"],"映":["chinese_simplified","chinese_traditional"],"雷":["chinese_simplified","chinese_traditional"],"销":["chinese_simplified"],"诗":["chinese_simplified"],"座":["chinese_simplified","chinese_traditional"],"居":["chinese_simplified","chinese_traditional"],"抓":["chinese_simplified","chinese_traditional"],"裂":["chinese_simplified","chinese_traditional"],"胞":["chinese_simplified","chinese_traditional"],"呼":["chinese_simplified","chinese_traditional"],"娘":["chinese_simplified","chinese_traditional"],"景":["chinese_simplified","chinese_traditional"],"威":["chinese_simplified","chinese_traditional"],"绿":["chinese_simplified"],"晶":["chinese_simplified","chinese_traditional"],"厚":["chinese_simplified","chinese_traditional"],"盟":["chinese_simplified","chinese_traditional"],"衡":["chinese_simplified","chinese_traditional"],"鸡":["chinese_simplified"],"孙":["chinese_simplified"],"延":["chinese_simplified","chinese_traditional"],"危":["chinese_simplified","chinese_traditional"],"胶":["chinese_simplified"],"屋":["chinese_simplified","chinese_traditional"],"乡":["chinese_simplified"],"临":["chinese_simplified"],"陆":["chinese_simplified"],"顾":["chinese_simplified"],"掉":["chinese_simplified","chinese_traditional"],"呀":["chinese_simplified","chinese_traditional"],"灯":["chinese_simplified"],"岁":["chinese_simplified"],"措":["chinese_simplified","chinese_traditional"],"束":["chinese_simplified","chinese_traditional"],"耐":["chinese_simplified","chinese_traditional"],"剧":["chinese_simplified"],"玉":["chinese_simplified","chinese_traditional"],"赵":["chinese_simplified"],"跳":["chinese_simplified","chinese_traditional"],"哥":["chinese_simplified","chinese_traditional"],"季":["chinese_simplified","chinese_traditional"],"课":["chinese_simplified"],"凯":["chinese_simplified"],"胡":["chinese_simplified","chinese_traditional"],"额":["chinese_simplified"],"款":["chinese_simplified","chinese_traditional"],"绍":["chinese_simplified"],"卷":["chinese_simplified","chinese_traditional"],"齐":["chinese_simplified"],"伟":["chinese_simplified"],"蒸":["chinese_simplified","chinese_traditional"],"殖":["chinese_simplified","chinese_traditional"],"永":["chinese_simplified","chinese_traditional"],"宗":["chinese_simplified","chinese_traditional"],"苗":["chinese_simplified","chinese_traditional"],"川":["chinese_simplified","chinese_traditional"],"炉":["chinese_simplified"],"岩":["chinese_simplified","chinese_traditional"],"弱":["chinese_simplified","chinese_traditional"],"零":["chinese_simplified","chinese_traditional"],"杨":["chinese_simplified"],"奏":["chinese_simplified","chinese_traditional"],"沿":["chinese_simplified","chinese_traditional"],"露":["chinese_simplified","chinese_traditional"],"杆":["chinese_simplified"],"探":["chinese_simplified","chinese_traditional"],"滑":["chinese_simplified","chinese_traditional"],"镇":["chinese_simplified"],"饭":["chinese_simplified"],"浓":["chinese_simplified"],"航":["chinese_simplified","chinese_traditional"],"怀":["chinese_simplified"],"赶":["chinese_simplified"],"库":["chinese_simplified"],"夺":["chinese_simplified"],"伊":["chinese_simplified","chinese_traditional"],"灵":["chinese_simplified"],"税":["chinese_simplified"],"途":["chinese_simplified","chinese_traditional"],"灭":["chinese_simplified"],"赛":["chinese_simplified"],"归":["chinese_simplified"],"召":["chinese_simplified","chinese_traditional"],"鼓":["chinese_simplified","chinese_traditional"],"播":["chinese_simplified","chinese_traditional"],"盘":["chinese_simplified"],"裁":["chinese_simplified","chinese_traditional"],"险":["chinese_simplified"],"康":["chinese_simplified","chinese_traditional"],"唯":["chinese_simplified","chinese_traditional"],"录":["chinese_simplified"],"菌":["chinese_simplified","chinese_traditional"],"纯":["chinese_simplified"],"借":["chinese_simplified","chinese_traditional"],"糖":["chinese_simplified","chinese_traditional"],"盖":["chinese_simplified"],"横":["chinese_simplified"],"符":["chinese_simplified","chinese_traditional"],"私":["chinese_simplified","chinese_traditional"],"努":["chinese_simplified","chinese_traditional"],"堂":["chinese_simplified","chinese_traditional"],"域":["chinese_simplified","chinese_traditional"],"枪":["chinese_simplified"],"润":["chinese_simplified"],"幅":["chinese_simplified","chinese_traditional"],"哈":["chinese_simplified","chinese_traditional"],"竟":["chinese_simplified","chinese_traditional"],"熟":["chinese_simplified","chinese_traditional"],"虫":["chinese_simplified"],"泽":["chinese_simplified"],"脑":["chinese_simplified"],"壤":["chinese_simplified","chinese_traditional"],"碳":["chinese_simplified","chinese_traditional"],"欧":["chinese_simplified"],"遍":["chinese_simplified","chinese_traditional"],"侧":["chinese_simplified"],"寨":["chinese_simplified","chinese_traditional"],"敢":["chinese_simplified","chinese_traditional"],"彻":["chinese_simplified"],"虑":["chinese_simplified"],"斜":["chinese_simplified","chinese_traditional"],"薄":["chinese_simplified","chinese_traditional"],"庭":["chinese_simplified","chinese_traditional"],"纳":["chinese_simplified"],"弹":["chinese_simplified"],"饲":["chinese_simplified"],"伸":["chinese_simplified","chinese_traditional"],"折":["chinese_simplified","chinese_traditional"],"麦":["chinese_simplified"],"湿":["chinese_simplified"],"暗":["chinese_simplified","chinese_traditional"],"荷":["chinese_simplified","chinese_traditional"],"瓦":["chinese_simplified","chinese_traditional"],"塞":["chinese_simplified","chinese_traditional"],"床":["chinese_simplified","chinese_traditional"],"筑":["chinese_simplified"],"恶":["chinese_simplified"],"户":["chinese_simplified"],"访":["chinese_simplified"],"塔":["chinese_simplified","chinese_traditional"],"奇":["chinese_simplified","chinese_traditional"],"透":["chinese_simplified","chinese_traditional"],"梁":["chinese_simplified","chinese_traditional"],"刀":["chinese_simplified","chinese_traditional"],"旋":["chinese_simplified","chinese_traditional"],"迹":["chinese_simplified"],"卡":["chinese_simplified","chinese_traditional"],"氯":["chinese_simplified","chinese_traditional"],"遇":["chinese_simplified","chinese_traditional"],"份":["chinese_simplified","chinese_traditional"],"毒":["chinese_simplified","chinese_traditional"],"泥":["chinese_simplified","chinese_traditional"],"退":["chinese_simplified","chinese_traditional"],"洗":["chinese_simplified","chinese_traditional"],"摆":["chinese_simplified"],"灰":["chinese_simplified","chinese_traditional"],"彩":["chinese_simplified","chinese_traditional"],"卖":["chinese_simplified"],"耗":["chinese_simplified","chinese_traditional"],"夏":["chinese_simplified","chinese_traditional"],"择":["chinese_simplified"],"忙":["chinese_simplified","chinese_traditional"],"铜":["chinese_simplified"],"献":["chinese_simplified"],"硬":["chinese_simplified","chinese_traditional"],"予":["chinese_simplified","chinese_traditional"],"繁":["chinese_simplified","chinese_traditional"],"圈":["chinese_simplified","chinese_traditional"],"雪":["chinese_simplified","chinese_traditional"],"函":["chinese_simplified","chinese_traditional"],"亦":["chinese_simplified","chinese_traditional"],"抽":["chinese_simplified","chinese_traditional"],"篇":["chinese_simplified","chinese_traditional"],"阵":["chinese_simplified"],"阴":["chinese_simplified"],"丁":["chinese_simplified","chinese_traditional"],"尺":["chinese_simplified","chinese_traditional"],"追":["chinese_simplified","chinese_traditional"],"堆":["chinese_simplified","chinese_traditional"],"雄":["chinese_simplified","chinese_traditional"],"迎":["chinese_simplified","chinese_traditional"],"泛":["chinese_simplified","chinese_traditional"],"爸":["chinese_simplified","chinese_traditional"],"楼":["chinese_simplified"],"避":["chinese_simplified","chinese_traditional"],"谋":["chinese_simplified"],"吨":["chinese_simplified"],"野":["chinese_simplified","chinese_traditional"],"猪":["chinese_simplified"],"旗":["chinese_simplified","chinese_traditional"],"累":["chinese_simplified","chinese_traditional"],"偏":["chinese_simplified","chinese_traditional"],"典":["chinese_simplified","chinese_traditional"],"馆":["chinese_simplified"],"索":["chinese_simplified","chinese_traditional"],"秦":["chinese_simplified","chinese_traditional"],"脂":["chinese_simplified","chinese_traditional"],"潮":["chinese_simplified","chinese_traditional"],"爷":["chinese_simplified"],"豆":["chinese_simplified","chinese_traditional"],"忽":["chinese_simplified","chinese_traditional"],"托":["chinese_simplified","chinese_traditional"],"惊":["chinese_simplified"],"塑":["chinese_simplified","chinese_traditional"],"遗":["chinese_simplified"],"愈":["chinese_simplified","chinese_traditional"],"朱":["chinese_simplified","chinese_traditional"],"替":["chinese_simplified","chinese_traditional"],"纤":["chinese_simplified"],"粗":["chinese_simplified","chinese_traditional"],"倾":["chinese_simplified"],"尚":["chinese_simplified","chinese_traditional"],"痛":["chinese_simplified","chinese_traditional"],"楚":["chinese_simplified","chinese_traditional"],"谢":["chinese_simplified"],"奋":["chinese_simplified"],"购":["chinese_simplified"],"磨":["chinese_simplified","chinese_traditional"],"君":["chinese_simplified","chinese_traditional"],"池":["chinese_simplified","chinese_traditional"],"旁":["chinese_simplified","chinese_traditional"],"碎":["chinese_simplified","chinese_traditional"],"骨":["chinese_simplified","chinese_traditional"],"监":["chinese_simplified"],"捕":["chinese_simplified","chinese_traditional"],"弟":["chinese_simplified","chinese_traditional"],"暴":["chinese_simplified","chinese_traditional"],"割":["chinese_simplified","chinese_traditional"],"贯":["chinese_simplified"],"殊":["chinese_simplified","chinese_traditional"],"释":["chinese_simplified"],"词":["chinese_simplified"],"亡":["chinese_simplified","chinese_traditional"],"壁":["chinese_simplified","chinese_traditional"],"顿":["chinese_simplified"],"宝":["chinese_simplified"],"午":["chinese_simplified","chinese_traditional"],"尘":["chinese_simplified"],"闻":["chinese_simplified"],"揭":["chinese_simplified","chinese_traditional"],"炮":["chinese_simplified","chinese_traditional"],"残":["chinese_simplified"],"冬":["chinese_simplified","chinese_traditional"],"桥":["chinese_simplified"],"妇":["chinese_simplified"],"警":["chinese_simplified","chinese_traditional"],"综":["chinese_simplified"],"招":["chinese_simplified","chinese_traditional"],"吴":["chinese_simplified"],"付":["chinese_simplified","chinese_traditional"],"浮":["chinese_simplified","chinese_traditional"],"遭":["chinese_simplified","chinese_traditional"],"徐":["chinese_simplified","chinese_traditional"],"您":["chinese_simplified","chinese_traditional"],"摇":["chinese_simplified"],"谷":["chinese_simplified","chinese_traditional"],"赞":["chinese_simplified"],"箱":["chinese_simplified","chinese_traditional"],"隔":["chinese_simplified","chinese_traditional"],"订":["chinese_simplified"],"男":["chinese_simplified","chinese_traditional"],"吹":["chinese_simplified","chinese_traditional"],"园":["chinese_simplified"],"纷":["chinese_simplified"],"唐":["chinese_simplified","chinese_traditional"],"败":["chinese_simplified"],"宋":["chinese_simplified","chinese_traditional"],"玻":["chinese_simplified","chinese_traditional"],"巨":["chinese_simplified","chinese_traditional"],"耕":["chinese_simplified","chinese_traditional"],"坦":["chinese_simplified","chinese_traditional"],"荣":["chinese_simplified"],"闭":["chinese_simplified"],"湾":["chinese_simplified"],"键":["chinese_simplified"],"凡":["chinese_simplified","chinese_traditional"],"驻":["chinese_simplified"],"锅":["chinese_simplified"],"救":["chinese_simplified","chinese_traditional"],"恩":["chinese_simplified","chinese_traditional"],"剥":["chinese_simplified"],"凝":["chinese_simplified","chinese_traditional"],"碱":["chinese_simplified"],"齿":["chinese_simplified"],"截":["chinese_simplified","chinese_traditional"],"炼":["chinese_simplified"],"麻":["chinese_simplified","chinese_traditional"],"纺":["chinese_simplified"],"禁":["chinese_simplified","chinese_traditional"],"废":["chinese_simplified"],"盛":["chinese_simplified","chinese_traditional"],"版":["chinese_simplified","chinese_traditional"],"缓":["chinese_simplified"],"净":["chinese_simplified"],"睛":["chinese_simplified","chinese_traditional"],"昌":["chinese_simplified","chinese_traditional"],"婚":["chinese_simplified","chinese_traditional"],"涉":["chinese_simplified","chinese_traditional"],"筒":["chinese_simplified","chinese_traditional"],"嘴":["chinese_simplified","chinese_traditional"],"插":["chinese_simplified","chinese_traditional"],"岸":["chinese_simplified","chinese_traditional"],"朗":["chinese_simplified","chinese_traditional"],"庄":["chinese_simplified"],"街":["chinese_simplified","chinese_traditional"],"藏":["chinese_simplified","chinese_traditional"],"姑":["chinese_simplified","chinese_traditional"],"贸":["chinese_simplified"],"腐":["chinese_simplified","chinese_traditional"],"奴":["chinese_simplified","chinese_traditional"],"啦":["chinese_simplified","chinese_traditional"],"惯":["chinese_simplified"],"乘":["chinese_simplified","chinese_traditional"],"伙":["chinese_simplified"],"恢":["chinese_simplified","chinese_traditional"],"匀":["chinese_simplified"],"纱":["chinese_simplified"],"扎":["chinese_simplified","chinese_traditional"],"辩":["chinese_simplified"],"耳":["chinese_simplified","chinese_traditional"],"彪":["chinese_simplified","chinese_traditional"],"臣":["chinese_simplified","chinese_traditional"],"亿":["chinese_simplified"],"璃":["chinese_simplified","chinese_traditional"],"抵":["chinese_simplified","chinese_traditional"],"脉":["chinese_simplified"],"秀":["chinese_simplified","chinese_traditional"],"萨":["chinese_simplified"],"俄":["chinese_simplified","chinese_traditional"],"网":["chinese_simplified"],"舞":["chinese_simplified","chinese_traditional"],"店":["chinese_simplified","chinese_traditional"],"喷":["chinese_simplified"],"纵":["chinese_simplified"],"寸":["chinese_simplified","chinese_traditional"],"汗":["chinese_simplified","chinese_traditional"],"挂":["chinese_simplified"],"洪":["chinese_simplified","chinese_traditional"],"贺":["chinese_simplified"],"闪":["chinese_simplified"],"柬":["chinese_simplified","chinese_traditional"],"爆":["chinese_simplified","chinese_traditional"],"烯":["chinese_simplified","chinese_traditional"],"津":["chinese_simplified","chinese_traditional"],"稻":["chinese_simplified","chinese_traditional"],"墙":["chinese_simplified"],"软":["chinese_simplified"],"勇":["chinese_simplified","chinese_traditional"],"像":["chinese_simplified","chinese_traditional"],"滚":["chinese_simplified"],"厘":["chinese_simplified","chinese_traditional"],"蒙":["chinese_simplified","chinese_traditional"],"芳":["chinese_simplified","chinese_traditional"],"肯":["chinese_simplified","chinese_traditional"],"坡":["chinese_simplified","chinese_traditional"],"柱":["chinese_simplified","chinese_traditional"],"荡":["chinese_simplified"],"腿":["chinese_simplified","chinese_traditional"],"仪":["chinese_simplified"],"旅":["chinese_simplified","chinese_traditional"],"尾":["chinese_simplified","chinese_traditional"],"轧":["chinese_simplified"],"冰":["chinese_simplified","chinese_traditional"],"贡":["chinese_simplified"],"登":["chinese_simplified","chinese_traditional"],"黎":["chinese_simplified","chinese_traditional"],"削":["chinese_simplified","chinese_traditional"],"钻":["chinese_simplified"],"勒":["chinese_simplified","chinese_traditional"],"逃":["chinese_simplified","chinese_traditional"],"障":["chinese_simplified","chinese_traditional"],"氨":["chinese_simplified","chinese_traditional"],"郭":["chinese_simplified","chinese_traditional"],"峰":["chinese_simplified","chinese_traditional"],"币":["chinese_simplified"],"港":["chinese_simplified","chinese_traditional"],"伏":["chinese_simplified","chinese_traditional"],"轨":["chinese_simplified"],"亩":["chinese_simplified"],"毕":["chinese_simplified"],"擦":["chinese_simplified","chinese_traditional"],"莫":["chinese_simplified","chinese_traditional"],"刺":["chinese_simplified","chinese_traditional"],"浪":["chinese_simplified","chinese_traditional"],"秘":["chinese_simplified","chinese_traditional"],"援":["chinese_simplified","chinese_traditional"],"株":["chinese_simplified","chinese_traditional"],"健":["chinese_simplified","chinese_traditional"],"售":["chinese_simplified","chinese_traditional"],"股":["chinese_simplified","chinese_traditional"],"岛":["chinese_simplified"],"甘":["chinese_simplified","chinese_traditional"],"泡":["chinese_simplified","chinese_traditional"],"睡":["chinese_simplified","chinese_traditional"],"童":["chinese_simplified","chinese_traditional"],"铸":["chinese_simplified"],"汤":["chinese_simplified"],"阀":["chinese_simplified"],"休":["chinese_simplified","chinese_traditional"],"汇":["chinese_simplified"],"舍":["chinese_simplified","chinese_traditional"],"牧":["chinese_simplified","chinese_traditional"],"绕":["chinese_simplified"],"炸":["chinese_simplified","chinese_traditional"],"哲":["chinese_simplified","chinese_traditional"],"磷":["chinese_simplified","chinese_traditional"],"绩":["chinese_simplified"],"朋":["chinese_simplified","chinese_traditional"],"淡":["chinese_simplified","chinese_traditional"],"尖":["chinese_simplified","chinese_traditional"],"启":["chinese_simplified"],"陷":["chinese_simplified","chinese_traditional"],"柴":["chinese_simplified","chinese_traditional"],"呈":["chinese_simplified","chinese_traditional"],"徒":["chinese_simplified","chinese_traditional"],"颜":["chinese_simplified"],"泪":["chinese_simplified"],"稍":["chinese_simplified","chinese_traditional"],"忘":["chinese_simplified","chinese_traditional"],"泵":["chinese_simplified","chinese_traditional"],"蓝":["chinese_simplified"],"拖":["chinese_simplified","chinese_traditional"],"洞":["chinese_simplified","chinese_traditional"],"授":["chinese_simplified","chinese_traditional"],"镜":["chinese_simplified"],"辛":["chinese_simplified","chinese_traditional"],"壮":["chinese_simplified"],"锋":["chinese_simplified"],"贫":["chinese_simplified"],"虚":["chinese_simplified"],"弯":["chinese_simplified"],"摩":["chinese_simplified","chinese_traditional"],"泰":["chinese_simplified","chinese_traditional"],"幼":["chinese_simplified","chinese_traditional"],"廷":["chinese_simplified","chinese_traditional"],"尊":["chinese_simplified","chinese_traditional"],"窗":["chinese_simplified","chinese_traditional"],"纲":["chinese_simplified"],"弄":["chinese_simplified","chinese_traditional"],"隶":["chinese_simplified"],"疑":["chinese_simplified","chinese_traditional"],"氏":["chinese_simplified","chinese_traditional"],"宫":["chinese_simplified"],"姐":["chinese_simplified","chinese_traditional"],"震":["chinese_simplified","chinese_traditional"],"瑞":["chinese_simplified","chinese_traditional"],"怪":["chinese_simplified","chinese_traditional"],"尤":["chinese_simplified","chinese_traditional"],"琴":["chinese_simplified","chinese_traditional"],"循":["chinese_simplified","chinese_traditional"],"描":["chinese_simplified","chinese_traditional"],"膜":["chinese_simplified","chinese_traditional"],"违":["chinese_simplified"],"夹":["chinese_simplified"],"腰":["chinese_simplified","chinese_traditional"],"缘":["chinese_simplified"],"珠":["chinese_simplified","chinese_traditional"],"穷":["chinese_simplified"],"森":["chinese_simplified","chinese_traditional"],"枝":["chinese_simplified","chinese_traditional"],"竹":["chinese_simplified","chinese_traditional"],"沟":["chinese_simplified"],"催":["chinese_simplified","chinese_traditional"],"绳":["chinese_simplified"],"忆":["chinese_simplified"],"邦":["chinese_simplified","chinese_traditional"],"剩":["chinese_simplified","chinese_traditional"],"幸":["chinese_simplified","chinese_traditional"],"浆":["chinese_simplified"],"栏":["chinese_simplified"],"拥":["chinese_simplified"],"牙":["chinese_simplified","chinese_traditional"],"贮":["chinese_simplified"],"礼":["chinese_simplified"],"滤":["chinese_simplified"],"钠":["chinese_simplified"],"纹":["chinese_simplified"],"罢":["chinese_simplified"],"拍":["chinese_simplified","chinese_traditional"],"咱":["chinese_simplified","chinese_traditional"],"喊":["chinese_simplified","chinese_traditional"],"袖":["chinese_simplified","chinese_traditional"],"埃":["chinese_simplified","chinese_traditional"],"勤":["chinese_simplified","chinese_traditional"],"罚":["chinese_simplified"],"焦":["chinese_simplified","chinese_traditional"],"潜":["chinese_simplified"],"伍":["chinese_simplified","chinese_traditional"],"墨":["chinese_simplified","chinese_traditional"],"欲":["chinese_simplified","chinese_traditional"],"缝":["chinese_simplified"],"姓":["chinese_simplified","chinese_traditional"],"刊":["chinese_simplified","chinese_traditional"],"饱":["chinese_simplified"],"仿":["chinese_simplified","chinese_traditional"],"奖":["chinese_simplified"],"铝":["chinese_simplified"],"鬼":["chinese_simplified","chinese_traditional"],"丽":["chinese_simplified"],"跨":["chinese_simplified","chinese_traditional"],"默":["chinese_simplified","chinese_traditional"],"挖":["chinese_simplified","chinese_traditional"],"链":["chinese_simplified"],"扫":["chinese_simplified"],"喝":["chinese_simplified","chinese_traditional"],"袋":["chinese_simplified","chinese_traditional"],"炭":["chinese_simplified","chinese_traditional"],"污":["chinese_simplified","chinese_traditional"],"幕":["chinese_simplified","chinese_traditional"],"诸":["chinese_simplified"],"弧":["chinese_simplified","chinese_traditional"],"励":["chinese_simplified"],"梅":["chinese_simplified","chinese_traditional"],"奶":["chinese_simplified","chinese_traditional"],"洁":["chinese_simplified"],"灾":["chinese_simplified"],"舟":["chinese_simplified","chinese_traditional"],"鉴":["chinese_simplified"],"苯":["chinese_simplified","chinese_traditional"],"讼":["chinese_simplified"],"抱":["chinese_simplified","chinese_traditional"],"毁":["chinese_simplified"],"懂":["chinese_simplified","chinese_traditional"],"寒":["chinese_simplified","chinese_traditional"],"智":["chinese_simplified","chinese_traditional"],"埔":["chinese_simplified","chinese_traditional"],"寄":["chinese_simplified","chinese_traditional"],"届":["chinese_simplified"],"跃":["chinese_simplified"],"渡":["chinese_simplified","chinese_traditional"],"挑":["chinese_simplified","chinese_traditional"],"丹":["chinese_simplified","chinese_traditional"],"艰":["chinese_simplified"],"贝":["chinese_simplified"],"碰":["chinese_simplified","chinese_traditional"],"拔":["chinese_simplified","chinese_traditional"],"爹":["chinese_simplified","chinese_traditional"],"戴":["chinese_simplified","chinese_traditional"],"码":["chinese_simplified"],"梦":["chinese_simplified"],"芽":["chinese_simplified","chinese_traditional"],"熔":["chinese_simplified","chinese_traditional"],"赤":["chinese_simplified","chinese_traditional"],"渔":["chinese_simplified"],"哭":["chinese_simplified","chinese_traditional"],"敬":["chinese_simplified","chinese_traditional"],"颗":["chinese_simplified"],"奔":["chinese_simplified","chinese_traditional"],"铅":["chinese_simplified"],"仲":["chinese_simplified","chinese_traditional"],"虎":["chinese_simplified","chinese_traditional"],"稀":["chinese_simplified","chinese_traditional"],"妹":["chinese_simplified","chinese_traditional"],"乏":["chinese_simplified","chinese_traditional"],"珍":["chinese_simplified","chinese_traditional"],"申":["chinese_simplified","chinese_traditional"],"桌":["chinese_simplified","chinese_traditional"],"遵":["chinese_simplified","chinese_traditional"],"允":["chinese_simplified","chinese_traditional"],"隆":["chinese_simplified","chinese_traditional"],"螺":["chinese_simplified","chinese_traditional"],"仓":["chinese_simplified"],"魏":["chinese_simplified","chinese_traditional"],"锐":["chinese_simplified"],"晓":["chinese_simplified"],"氮":["chinese_simplified","chinese_traditional"],"兼":["chinese_simplified","chinese_traditional"],"隐":["chinese_simplified"],"碍":["chinese_simplified"],"赫":["chinese_simplified","chinese_traditional"],"拨":["chinese_simplified"],"忠":["chinese_simplified","chinese_traditional"],"肃":["chinese_simplified"],"缸":["chinese_simplified","chinese_traditional"],"牵":["chinese_simplified"],"抢":["chinese_simplified"],"博":["chinese_simplified","chinese_traditional"],"巧":["chinese_simplified","chinese_traditional"],"壳":["chinese_simplified"],"兄":["chinese_simplified","chinese_traditional"],"杜":["chinese_simplified","chinese_traditional"],"讯":["chinese_simplified"],"诚":["chinese_simplified"],"碧":["chinese_simplified","chinese_traditional"],"祥":["chinese_simplified","chinese_traditional"],"柯":["chinese_simplified","chinese_traditional"],"页":["chinese_simplified"],"巡":["chinese_simplified","chinese_traditional"],"矩":["chinese_simplified","chinese_traditional"],"悲":["chinese_simplified","chinese_traditional"],"灌":["chinese_simplified","chinese_traditional"],"龄":["chinese_simplified"],"伦":["chinese_simplified"],"票":["chinese_simplified","chinese_traditional"],"寻":["chinese_simplified"],"桂":["chinese_simplified","chinese_traditional"],"铺":["chinese_simplified"],"圣":["chinese_simplified"],"恐":["chinese_simplified","chinese_traditional"],"恰":["chinese_simplified","chinese_traditional"],"郑":["chinese_simplified"],"趣":["chinese_simplified","chinese_traditional"],"抬":["chinese_simplified","chinese_traditional"],"荒":["chinese_simplified","chinese_traditional"],"腾":["chinese_simplified"],"贴":["chinese_simplified"],"柔":["chinese_simplified","chinese_traditional"],"滴":["chinese_simplified","chinese_traditional"],"猛":["chinese_simplified","chinese_traditional"],"阔":["chinese_simplified"],"辆":["chinese_simplified"],"妻":["chinese_simplified","chinese_traditional"],"填":["chinese_simplified","chinese_traditional"],"撤":["chinese_simplified","chinese_traditional"],"储":["chinese_simplified"],"签":["chinese_simplified"],"闹":["chinese_simplified"],"扰":["chinese_simplified"],"紫":["chinese_simplified","chinese_traditional"],"砂":["chinese_simplified","chinese_traditional"],"递":["chinese_simplified"],"戏":["chinese_simplified"],"吊":["chinese_simplified","chinese_traditional"],"陶":["chinese_simplified","chinese_traditional"],"伐":["chinese_simplified","chinese_traditional"],"喂":["chinese_simplified"],"疗":["chinese_simplified"],"瓶":["chinese_simplified","chinese_traditional"],"婆":["chinese_simplified","chinese_traditional"],"抚":["chinese_simplified"],"臂":["chinese_simplified","chinese_traditional"],"摸":["chinese_simplified","chinese_traditional"],"忍":["chinese_simplified","chinese_traditional"],"虾":["chinese_simplified"],"蜡":["chinese_simplified"],"邻":["chinese_simplified"],"胸":["chinese_simplified","chinese_traditional"],"巩":["chinese_simplified"],"挤":["chinese_simplified"],"偶":["chinese_simplified","chinese_traditional"],"弃":["chinese_simplified"],"槽":["chinese_simplified","chinese_traditional"],"劲":["chinese_simplified"],"乳":["chinese_simplified","chinese_traditional"],"邓":["chinese_simplified"],"吉":["chinese_simplified","chinese_traditional"],"仁":["chinese_simplified","chinese_traditional"],"烂":["chinese_simplified"],"砖":["chinese_simplified"],"租":["chinese_simplified","chinese_traditional"],"乌":["chinese_simplified"],"舰":["chinese_simplified"],"伴":["chinese_simplified","chinese_traditional"],"瓜":["chinese_simplified","chinese_traditional"],"浅":["chinese_simplified"],"丙":["chinese_simplified","chinese_traditional"],"暂":["chinese_simplified"],"燥":["chinese_simplified","chinese_traditional"],"橡":["chinese_simplified","chinese_traditional"],"柳":["chinese_simplified","chinese_traditional"],"迷":["chinese_simplified","chinese_traditional"],"暖":["chinese_simplified","chinese_traditional"],"牌":["chinese_simplified","chinese_traditional"],"秧":["chinese_simplified","chinese_traditional"],"胆":["chinese_simplified"],"详":["chinese_simplified"],"簧":["chinese_simplified","chinese_traditional"],"踏":["chinese_simplified","chinese_traditional"],"瓷":["chinese_simplified","chinese_traditional"],"谱":["chinese_simplified"],"呆":["chinese_simplified","chinese_traditional"],"宾":["chinese_simplified"],"糊":["chinese_simplified","chinese_traditional"],"洛":["chinese_simplified","chinese_traditional"],"辉":["chinese_simplified"],"愤":["chinese_simplified"],"竞":["chinese_simplified"],"隙":["chinese_simplified","chinese_traditional"],"怒":["chinese_simplified","chinese_traditional"],"粘":["chinese_simplified","chinese_traditional"],"乃":["chinese_simplified","chinese_traditional"],"绪":["chinese_simplified"],"肩":["chinese_simplified","chinese_traditional"],"籍":["chinese_simplified","chinese_traditional"],"敏":["chinese_simplified","chinese_traditional"],"涂":["chinese_simplified"],"熙":["chinese_simplified","chinese_traditional"],"皆":["chinese_simplified","chinese_traditional"],"侦":["chinese_simplified"],"悬":["chinese_simplified"],"掘":["chinese_simplified","chinese_traditional"],"享":["chinese_simplified","chinese_traditional"],"纠":["chinese_simplified"],"醒":["chinese_simplified","chinese_traditional"],"狂":["chinese_simplified","chinese_traditional"],"锁":["chinese_simplified"],"淀":["chinese_simplified","chinese_traditional"],"恨":["chinese_simplified","chinese_traditional"],"牲":["chinese_simplified","chinese_traditional"],"霸":["chinese_simplified","chinese_traditional"],"爬":["chinese_simplified","chinese_traditional"],"赏":["chinese_simplified"],"逆":["chinese_simplified","chinese_traditional"],"玩":["chinese_simplified","chinese_traditional"],"陵":["chinese_simplified","chinese_traditional"],"祝":["chinese_simplified","chinese_traditional"],"秒":["chinese_simplified","chinese_traditional"],"浙":["chinese_simplified","chinese_traditional"],"貌":["chinese_simplified","chinese_traditional"],"役":["chinese_simplified","chinese_traditional"],"彼":["chinese_simplified","chinese_traditional"],"悉":["chinese_simplified","chinese_traditional"],"鸭":["chinese_simplified"],"趋":["chinese_simplified"],"凤":["chinese_simplified"],"晨":["chinese_simplified","chinese_traditional"],"畜":["chinese_simplified","chinese_traditional"],"辈":["chinese_simplified"],"秩":["chinese_simplified","chinese_traditional"],"卵":["chinese_simplified","chinese_traditional"],"署":["chinese_simplified","chinese_traditional"],"梯":["chinese_simplified","chinese_traditional"],"炎":["chinese_simplified","chinese_traditional"],"滩":["chinese_simplified"],"棋":["chinese_simplified","chinese_traditional"],"驱":["chinese_simplified"],"筛":["chinese_simplified"],"峡":["chinese_simplified"],"冒":["chinese_simplified","chinese_traditional"],"啥":["chinese_simplified","chinese_traditional"],"寿":["chinese_simplified"],"译":["chinese_simplified"],"浸":["chinese_simplified","chinese_traditional"],"泉":["chinese_simplified","chinese_traditional"],"帽":["chinese_simplified","chinese_traditional"],"迟":["chinese_simplified"],"硅":["chinese_simplified"],"疆":["chinese_simplified","chinese_traditional"],"贷":["chinese_simplified"],"漏":["chinese_simplified","chinese_traditional"],"稿":["chinese_simplified","chinese_traditional"],"冠":["chinese_simplified","chinese_traditional"],"嫩":["chinese_simplified","chinese_traditional"],"胁":["chinese_simplified"],"芯":["chinese_simplified","chinese_traditional"],"牢":["chinese_simplified","chinese_traditional"],"叛":["chinese_simplified","chinese_traditional"],"蚀":["chinese_simplified"],"奥":["chinese_simplified"],"鸣":["chinese_simplified"],"岭":["chinese_simplified"],"羊":["chinese_simplified","chinese_traditional"],"凭":["chinese_simplified"],"串":["chinese_simplified","chinese_traditional"],"塘":["chinese_simplified","chinese_traditional"],"绘":["chinese_simplified"],"酵":["chinese_simplified","chinese_traditional"],"融":["chinese_simplified","chinese_traditional"],"盆":["chinese_simplified","chinese_traditional"],"锡":["chinese_simplified"],"庙":["chinese_simplified"],"筹":["chinese_simplified"],"冻":["chinese_simplified"],"辅":["chinese_simplified"],"摄":["chinese_simplified"],"袭":["chinese_simplified"],"筋":["chinese_simplified","chinese_traditional"],"拒":["chinese_simplified","chinese_traditional"],"僚":["chinese_simplified","chinese_traditional"],"旱":["chinese_simplified","chinese_traditional"],"钾":["chinese_simplified"],"鸟":["chinese_simplified"],"漆":["chinese_simplified","chinese_traditional"],"沈":["chinese_simplified","chinese_traditional"],"眉":["chinese_simplified","chinese_traditional"],"疏":["chinese_simplified","chinese_traditional"],"添":["chinese_simplified","chinese_traditional"],"棒":["chinese_simplified","chinese_traditional"],"穗":["chinese_simplified","chinese_traditional"],"硝":["chinese_simplified","chinese_traditional"],"韩":["chinese_simplified"],"逼":["chinese_simplified","chinese_traditional"],"扭":["chinese_simplified","chinese_traditional"],"侨":["chinese_simplified"],"凉":["chinese_simplified"],"挺":["chinese_simplified","chinese_traditional"],"碗":["chinese_simplified","chinese_traditional"],"栽":["chinese_simplified","chinese_traditional"],"炒":["chinese_simplified","chinese_traditional"],"杯":["chinese_simplified","chinese_traditional"],"患":["chinese_simplified","chinese_traditional"],"馏":["chinese_simplified"],"劝":["chinese_simplified"],"豪":["chinese_simplified","chinese_traditional"],"辽":["chinese_simplified"],"勃":["chinese_simplified","chinese_traditional"],"鸿":["chinese_simplified"],"旦":["chinese_simplified","chinese_traditional"],"吏":["chinese_simplified","chinese_traditional"],"拜":["chinese_simplified","chinese_traditional"],"狗":["chinese_simplified","chinese_traditional"],"埋":["chinese_simplified","chinese_traditional"],"辊":["chinese_simplified"],"掩":["chinese_simplified","chinese_traditional"],"饮":["chinese_simplified"],"搬":["chinese_simplified","chinese_traditional"],"骂":["chinese_simplified"],"辞":["chinese_simplified"],"勾":["chinese_simplified","chinese_traditional"],"扣":["chinese_simplified","chinese_traditional"],"估":["chinese_simplified","chinese_traditional"],"蒋":["chinese_simplified"],"绒":["chinese_simplified"],"雾":["chinese_simplified"],"丈":["chinese_simplified","chinese_traditional"],"朵":["chinese_simplified","chinese_traditional"],"姆":["chinese_simplified","chinese_traditional"],"拟":["chinese_simplified"],"宇":["chinese_simplified","chinese_traditional"],"辑":["chinese_simplified"],"陕":["chinese_simplified"],"雕":["chinese_simplified","chinese_traditional"],"偿":["chinese_simplified"],"蓄":["chinese_simplified","chinese_traditional"],"崇":["chinese_simplified","chinese_traditional"],"剪":["chinese_simplified","chinese_traditional"],"倡":["chinese_simplified","chinese_traditional"],"厅":["chinese_simplified"],"咬":["chinese_simplified","chinese_traditional"],"驶":["chinese_simplified"],"薯":["chinese_simplified","chinese_traditional"],"刷":["chinese_simplified","chinese_traditional"],"斥":["chinese_simplified","chinese_traditional"],"番":["chinese_simplified","chinese_traditional"],"赋":["chinese_simplified"],"奉":["chinese_simplified","chinese_traditional"],"佛":["chinese_simplified","chinese_traditional"],"浇":["chinese_simplified"],"漫":["chinese_simplified","chinese_traditional"],"曼":["chinese_simplified","chinese_traditional"],"扇":["chinese_simplified","chinese_traditional"],"钙":["chinese_simplified"],"桃":["chinese_simplified","chinese_traditional"],"扶":["chinese_simplified","chinese_traditional"],"仔":["chinese_simplified","chinese_traditional"],"返":["chinese_simplified","chinese_traditional"],"俗":["chinese_simplified","chinese_traditional"],"亏":["chinese_simplified"],"腔":["chinese_simplified","chinese_traditional"],"鞋":["chinese_simplified","chinese_traditional"],"棱":["chinese_simplified","chinese_traditional"],"覆":["chinese_simplified","chinese_traditional"],"框":["chinese_simplified","chinese_traditional"],"悄":["chinese_simplified","chinese_traditional"],"叔":["chinese_simplified","chinese_traditional"],"撞":["chinese_simplified","chinese_traditional"],"骗":["chinese_simplified"],"勘":["chinese_simplified","chinese_traditional"],"旺":["chinese_simplified","chinese_traditional"],"沸":["chinese_simplified","chinese_traditional"],"孤":["chinese_simplified","chinese_traditional"],"吐":["chinese_simplified","chinese_traditional"],"孟":["chinese_simplified","chinese_traditional"],"渠":["chinese_simplified","chinese_traditional"],"屈":["chinese_simplified","chinese_traditional"],"疾":["chinese_simplified","chinese_traditional"],"妙":["chinese_simplified","chinese_traditional"],"惜":["chinese_simplified","chinese_traditional"],"仰":["chinese_simplified","chinese_traditional"],"狠":["chinese_simplified","chinese_traditional"],"胀":["chinese_simplified"],"谐":["chinese_simplified"],"抛":["chinese_simplified"],"霉":["chinese_simplified"],"桑":["chinese_simplified","chinese_traditional"],"岗":["chinese_simplified"],"嘛":["chinese_simplified","chinese_traditional"],"衰":["chinese_simplified","chinese_traditional"],"盗":["chinese_simplified"],"渗":["chinese_simplified"],"脏":["chinese_simplified"],"赖":["chinese_simplified"],"涌":["chinese_simplified"],"甜":["chinese_simplified","chinese_traditional"],"曹":["chinese_simplified","chinese_traditional"],"阅":["chinese_simplified"],"肌":["chinese_simplified","chinese_traditional"],"哩":["chinese_simplified","chinese_traditional"],"厉":["chinese_simplified"],"烃":["chinese_simplified"],"纬":["chinese_simplified"],"毅":["chinese_simplified","chinese_traditional"],"昨":["chinese_simplified","chinese_traditional"],"伪":["chinese_simplified"],"症":["chinese_simplified","chinese_traditional"],"煮":["chinese_simplified","chinese_traditional"],"叹":["chinese_simplified"],"钉":["chinese_simplified"],"搭":["chinese_simplified","chinese_traditional"],"茎":["chinese_simplified"],"笼":["chinese_simplified"],"酷":["chinese_simplified","chinese_traditional"],"偷":["chinese_simplified","chinese_traditional"],"弓":["chinese_simplified","chinese_traditional"],"锥":["chinese_simplified"],"恒":["chinese_simplified"],"杰":["chinese_simplified"],"坑":["chinese_simplified","chinese_traditional"],"鼻":["chinese_simplified","chinese_traditional"],"翼":["chinese_simplified","chinese_traditional"],"纶":["chinese_simplified"],"叙":["chinese_simplified"],"狱":["chinese_simplified"],"逮":["chinese_simplified","chinese_traditional"],"罐":["chinese_simplified","chinese_traditional"],"络":["chinese_simplified"],"棚":["chinese_simplified","chinese_traditional"],"抑":["chinese_simplified","chinese_traditional"],"膨":["chinese_simplified","chinese_traditional"],"蔬":["chinese_simplified","chinese_traditional"],"寺":["chinese_simplified","chinese_traditional"],"骤":["chinese_simplified"],"穆":["chinese_simplified","chinese_traditional"],"冶":["chinese_simplified","chinese_traditional"],"枯":["chinese_simplified","chinese_traditional"],"册":["chinese_simplified"],"尸":["chinese_simplified"],"凸":["chinese_simplified","chinese_traditional"],"绅":["chinese_simplified"],"坯":["chinese_simplified","chinese_traditional"],"牺":["chinese_simplified"],"焰":["chinese_simplified","chinese_traditional"],"轰":["chinese_simplified"],"欣":["chinese_simplified","chinese_traditional"],"晋":["chinese_simplified"],"瘦":["chinese_simplified","chinese_traditional"],"御":["chinese_simplified"],"锭":["chinese_simplified"],"锦":["chinese_simplified"],"丧":["chinese_simplified"],"旬":["chinese_simplified","chinese_traditional"],"锻":["chinese_simplified"],"垄":["chinese_simplified"],"搜":["chinese_simplified","chinese_traditional"],"扑":["chinese_simplified"],"邀":["chinese_simplified","chinese_traditional"],"亭":["chinese_simplified","chinese_traditional"],"酯":["chinese_simplified","chinese_traditional"],"迈":["chinese_simplified"],"舒":["chinese_simplified","chinese_traditional"],"脆":["chinese_simplified","chinese_traditional"],"酶":["chinese_simplified","chinese_traditional"],"闲":["chinese_simplified"],"忧":["chinese_simplified"],"酚":["chinese_simplified","chinese_traditional"],"顽":["chinese_simplified"],"羽":["chinese_simplified","chinese_traditional"],"涨":["chinese_simplified"],"卸":["chinese_simplified","chinese_traditional"],"仗":["chinese_simplified","chinese_traditional"],"陪":["chinese_simplified","chinese_traditional"],"辟":["chinese_simplified"],"惩":["chinese_simplified"],"杭":["chinese_simplified","chinese_traditional"],"姚":["chinese_simplified","chinese_traditional"],"肚":["chinese_simplified","chinese_traditional"],"捉":["chinese_simplified","chinese_traditional"],"飘":["chinese_simplified"],"漂":["chinese_simplified","chinese_traditional"],"昆":["chinese_simplified","chinese_traditional"],"欺":["chinese_simplified","chinese_traditional"],"吾":["chinese_simplified","chinese_traditional"],"郎":["chinese_simplified","chinese_traditional"],"烷":["chinese_simplified","chinese_traditional"],"汁":["chinese_simplified","chinese_traditional"],"呵":["chinese_simplified","chinese_traditional"],"饰":["chinese_simplified"],"萧":["chinese_simplified"],"雅":["chinese_simplified","chinese_traditional"],"邮":["chinese_simplified"],"迁":["chinese_simplified"],"燕":["chinese_simplified","chinese_traditional"],"撒":["chinese_simplified","chinese_traditional"],"姻":["chinese_simplified","chinese_traditional"],"赴":["chinese_simplified","chinese_traditional"],"宴":["chinese_simplified","chinese_traditional"],"烦":["chinese_simplified"],"债":["chinese_simplified"],"帐":["chinese_simplified"],"斑":["chinese_simplified","chinese_traditional"],"铃":["chinese_simplified"],"旨":["chinese_simplified","chinese_traditional"],"醇":["chinese_simplified","chinese_traditional"],"董":["chinese_simplified","chinese_traditional"],"饼":["chinese_simplified"],"雏":["chinese_simplified"],"姿":["chinese_simplified","chinese_traditional"],"拌":["chinese_simplified","chinese_traditional"],"傅":["chinese_simplified","chinese_traditional"],"腹":["chinese_simplified","chinese_traditional"],"妥":["chinese_simplified","chinese_traditional"],"揉":["chinese_simplified","chinese_traditional"],"贤":["chinese_simplified"],"拆":["chinese_simplified","chinese_traditional"],"歪":["chinese_simplified","chinese_traditional"],"葡":["chinese_simplified","chinese_traditional"],"胺":["chinese_simplified","chinese_traditional"],"丢":["chinese_simplified"],"浩":["chinese_simplified","chinese_traditional"],"徽":["chinese_simplified","chinese_traditional"],"昂":["chinese_simplified","chinese_traditional"],"垫":["chinese_simplified"],"挡":["chinese_simplified"],"览":["chinese_simplified"],"贪":["chinese_simplified"],"慰":["chinese_simplified","chinese_traditional"],"缴":["chinese_simplified"],"汪":["chinese_simplified","chinese_traditional"],"慌":["chinese_simplified","chinese_traditional"],"冯":["chinese_simplified"],"诺":["chinese_simplified"],"姜":["chinese_simplified","chinese_traditional"],"谊":["chinese_simplified"],"凶":["chinese_simplified"],"劣":["chinese_simplified","chinese_traditional"],"诬":["chinese_simplified"],"耀":["chinese_simplified","chinese_traditional"],"昏":["chinese_simplified","chinese_traditional"],"躺":["chinese_simplified","chinese_traditional"],"盈":["chinese_simplified","chinese_traditional"],"骑":["chinese_simplified"],"乔":["chinese_simplified"],"溪":["chinese_simplified","chinese_traditional"],"丛":["chinese_simplified"],"卢":["chinese_simplified"],"抹":["chinese_simplified","chinese_traditional"],"闷":["chinese_simplified"],"咨":["chinese_simplified"],"刮":["chinese_simplified","chinese_traditional"],"驾":["chinese_simplified"],"缆":["chinese_simplified"],"悟":["chinese_simplified","chinese_traditional"],"摘":["chinese_simplified","chinese_traditional"],"铒":["chinese_simplified"],"掷":["chinese_simplified"],"颇":["chinese_simplified"],"幻":["chinese_simplified","chinese_traditional"],"柄":["chinese_simplified","chinese_traditional"],"惠":["chinese_simplified","chinese_traditional"],"惨":["chinese_simplified"],"佳":["chinese_simplified","chinese_traditional"],"仇":["chinese_simplified","chinese_traditional"],"腊":["chinese_simplified"],"窝":["chinese_simplified"],"涤":["chinese_simplified"],"剑":["chinese_simplified"],"瞧":["chinese_simplified","chinese_traditional"],"堡":["chinese_simplified","chinese_traditional"],"泼":["chinese_simplified"],"葱":["chinese_simplified"],"罩":["chinese_simplified","chinese_traditional"],"霍":["chinese_simplified","chinese_traditional"],"捞":["chinese_simplified"],"胎":["chinese_simplified","chinese_traditional"],"苍":["chinese_simplified"],"滨":["chinese_simplified"],"俩":["chinese_simplified"],"捅":["chinese_simplified","chinese_traditional"],"湘":["chinese_simplified","chinese_traditional"],"砍":["chinese_simplified","chinese_traditional"],"霞":["chinese_simplified","chinese_traditional"],"邵":["chinese_simplified","chinese_traditional"],"萄":["chinese_simplified","chinese_traditional"],"疯":["chinese_simplified"],"淮":["chinese_simplified","chinese_traditional"],"遂":["chinese_simplified","chinese_traditional"],"熊":["chinese_simplified","chinese_traditional"],"粪":["chinese_simplified"],"烘":["chinese_simplified","chinese_traditional"],"宿":["chinese_simplified","chinese_traditional"],"档":["chinese_simplified"],"戈":["chinese_simplified","chinese_traditional"],"驳":["chinese_simplified"],"嫂":["chinese_simplified","chinese_traditional"],"裕":["chinese_simplified","chinese_traditional"],"徙":["chinese_simplified","chinese_traditional"],"箭":["chinese_simplified","chinese_traditional"],"捐":["chinese_simplified","chinese_traditional"],"肠":["chinese_simplified"],"撑":["chinese_simplified"],"晒":["chinese_simplified"],"辨":["chinese_simplified","chinese_traditional"],"殿":["chinese_simplified","chinese_traditional"],"莲":["chinese_simplified"],"摊":["chinese_simplified"],"搅":["chinese_simplified"],"酱":["chinese_simplified"],"屏":["chinese_simplified","chinese_traditional"],"疫":["chinese_simplified","chinese_traditional"],"哀":["chinese_simplified","chinese_traditional"],"蔡":["chinese_simplified","chinese_traditional"],"堵":["chinese_simplified","chinese_traditional"],"沫":["chinese_simplified","chinese_traditional"],"皱":["chinese_simplified"],"畅":["chinese_simplified"],"叠":["chinese_simplified"],"阁":["chinese_simplified"],"莱":["chinese_simplified"],"敲":["chinese_simplified","chinese_traditional"],"辖":["chinese_simplified"],"钩":["chinese_simplified"],"痕":["chinese_simplified","chinese_traditional"],"坝":["chinese_simplified"],"巷":["chinese_simplified","chinese_traditional"],"饿":["chinese_simplified"],"祸":["chinese_simplified"],"丘":["chinese_simplified","chinese_traditional"],"玄":["chinese_simplified","chinese_traditional"],"溜":["chinese_simplified","chinese_traditional"],"曰":["chinese_simplified","chinese_traditional"],"逻":["chinese_simplified"],"彭":["chinese_simplified","chinese_traditional"],"尝":["chinese_simplified"],"卿":["chinese_simplified","chinese_traditional"],"妨":["chinese_simplified","chinese_traditional"],"艇":["chinese_simplified","chinese_traditional"],"吞":["chinese_simplified","chinese_traditional"],"韦":["chinese_simplified"],"怨":["chinese_simplified","chinese_traditional"],"矮":["chinese_simplified","chinese_traditional"],"歇":["chinese_simplified","chinese_traditional"],"這":["chinese_traditional"],"為":["chinese_traditional"],"個":["chinese_traditional"],"國":["chinese_traditional"],"時":["chinese_traditional"],"來":["chinese_traditional"],"們":["chinese_traditional"],"於":["chinese_traditional"],"對":["chinese_traditional"],"會":["chinese_traditional"],"發":["chinese_traditional"],"動":["chinese_traditional"],"過":["chinese_traditional"],"說":["chinese_traditional"],"產":["chinese_traditional"],"種":["chinese_traditional"],"後":["chinese_traditional"],"學":["chinese_traditional"],"經":["chinese_traditional"],"進":["chinese_traditional"],"著":["chinese_traditional"],"電":["chinese_traditional"],"裡":["chinese_traditional"],"現":["chinese_traditional"],"實":["chinese_traditional"],"兩":["chinese_traditional"],"體":["chinese_traditional"],"機":["chinese_traditional"],"當":["chinese_traditional"],"點":["chinese_traditional"],"從":["chinese_traditional"],"業":["chinese_traditional"],"應":["chinese_traditional"],"開":["chinese_traditional"],"還":["chinese_traditional"],"義":["chinese_traditional"],"間":["chinese_traditional"],"樣":["chinese_traditional"],"與":["chinese_traditional"],"關":["chinese_traditional"],"線":["chinese_traditional"],"內":["chinese_traditional"],"數":["chinese_traditional"],"麼":["chinese_traditional"],"質":["chinese_traditional"],"氣":["chinese_traditional"],"變":["chinese_traditional"],"條":["chinese_traditional"],"沒":["chinese_traditional"],"結":["chinese_traditional"],"問":["chinese_traditional"],"無":["chinese_traditional"],"軍":["chinese_traditional"],"並":["chinese_traditional"],"題":["chinese_traditional"],"黨":["chinese_traditional"],"員":["chinese_traditional"],"總":["chinese_traditional"],"設":["chinese_traditional"],"長":["chinese_traditional"],"頭":["chinese_traditional"],"資":["chinese_traditional"],"邊":["chinese_traditional"],"級":["chinese_traditional"],"圖":["chinese_traditional"],"統":["chinese_traditional"],"較":["chinese_traditional"],"將":["chinese_traditional"],"組":["chinese_traditional"],"見":["chinese_traditional"],"計":["chinese_traditional"],"別":["chinese_traditional"],"論":["chinese_traditional"],"運":["chinese_traditional"],"農":["chinese_traditional"],"幾":["chinese_traditional"],"區":["chinese_traditional"],"強":["chinese_traditional"],"決":["chinese_traditional"],"幹":["chinese_traditional"],"戰":["chinese_traditional"],"則":["chinese_traditional"],"據":["chinese_traditional"],"處":["chinese_traditional"],"隊":["chinese_traditional"],"給":["chinese_traditional"],"門":["chinese_traditional"],"規":["chinese_traditional"],"熱":["chinese_traditional"],"領":["chinese_traditional"],"東":["chinese_traditional"],"導":["chinese_traditional"],"壓":["chinese_traditional"],"爭":["chinese_traditional"],"濟":["chinese_traditional"],"階":["chinese_traditional"],"術":["chinese_traditional"],"極":["chinese_traditional"],"聯":["chinese_traditional"],"認":["chinese_traditional"],"權":["chinese_traditional"],"證":["chinese_traditional"],"採":["chinese_traditional"],"轉":["chinese_traditional"],"單":["chinese_traditional"],"風":["chinese_traditional"],"帶":["chinese_traditional"],"場":["chinese_traditional"],"車":["chinese_traditional"],"務":["chinese_traditional"],"萬":["chinese_traditional"],"達":["chinese_traditional"],"積":["chinese_traditional"],"議":["chinese_traditional"],"聲":["chinese_traditional"],"報":["chinese_traditional"],"鬥":["chinese_traditional"],"類":["chinese_traditional"],"離":["chinese_traditional"],"華":["chinese_traditional"],"確":["chinese_traditional"],"張":["chinese_traditional"],"馬":["chinese_traditional"],"節":["chinese_traditional"],"話":["chinese_traditional"],"況":["chinese_traditional"],"溫":["chinese_traditional"],"傳":["chinese_traditional"],"許":["chinese_traditional"],"廣":["chinese_traditional"],"記":["chinese_traditional"],"觀":["chinese_traditional"],"織":["chinese_traditional"],"裝":["chinese_traditional"],"眾":["chinese_traditional"],"書":["chinese_traditional"],"兒":["chinese_traditional"],"須":["chinese_traditional"],"際":["chinese_traditional"],"驗":["chinese_traditional"],"連":["chinese_traditional"],"斷":["chinese_traditional"],"難":["chinese_traditional"],"礦":["chinese_traditional"],"週":["chinese_traditional"],"備":["chinese_traditional"],"辦":["chinese_traditional"],"習":["chinese_traditional"],"響":["chinese_traditional"],"約":["chinese_traditional"],"勞":["chinese_traditional"],"團":["chinese_traditional"],"歷":["chinese_traditional"],"構":["chinese_traditional"],"稱":["chinese_traditional"],"準":["chinese_traditional"],"號":["chinese_traditional"],"維":["chinese_traditional"],"劃":["chinese_traditional"],"選":["chinese_traditional"],"標":["chinese_traditional"],"寫":["chinese_traditional"],"親":["chinese_traditional"],"養":["chinese_traditional"],"層":["chinese_traditional"],"卻":["chinese_traditional"],"專":["chinese_traditional"],"狀":["chinese_traditional"],"廠":["chinese_traditional"],"識":["chinese_traditional"],"適":["chinese_traditional"],"屬":["chinese_traditional"],"圓":["chinese_traditional"],"調":["chinese_traditional"],"滿":["chinese_traditional"],"縣":["chinese_traditional"],"參":["chinese_traditional"],"紅":["chinese_traditional"],"細":["chinese_traditional"],"聽":["chinese_traditional"],"該":["chinese_traditional"],"鐵":["chinese_traditional"],"價":["chinese_traditional"],"嚴":["chinese_traditional"],"隨":["chinese_traditional"],"蘇":["chinese_traditional"],"爾":["chinese_traditional"],"講":["chinese_traditional"],"黃":["chinese_traditional"],"顯":["chinese_traditional"],"談":["chinese_traditional"],"藝":["chinese_traditional"],"營":["chinese_traditional"],"項":["chinese_traditional"],"舉":["chinese_traditional"],"勢":["chinese_traditional"],"幫":["chinese_traditional"],"輪":["chinese_traditional"],"亞":["chinese_traditional"],"師":["chinese_traditional"],"圍":["chinese_traditional"],"遠":["chinese_traditional"],"態":["chinese_traditional"],"減":["chinese_traditional"],"樹":["chinese_traditional"],"葉":["chinese_traditional"],"魚":["chinese_traditional"],"視":["chinese_traditional"],"僅":["chinese_traditional"],"費":["chinese_traditional"],"緊":["chinese_traditional"],"愛":["chinese_traditional"],"續":["chinese_traditional"],"輕":["chinese_traditional"],"試":["chinese_traditional"],"護":["chinese_traditional"],"練":["chinese_traditional"],"負":["chinese_traditional"],"擊":["chinese_traditional"],"繼":["chinese_traditional"],"興":["chinese_traditional"],"餘":["chinese_traditional"],"堅":["chinese_traditional"],"輸":["chinese_traditional"],"夠":["chinese_traditional"],"筆":["chinese_traditional"],"佔":["chinese_traditional"],"財":["chinese_traditional"],"職":["chinese_traditional"],"覺":["chinese_traditional"],"漢":["chinese_traditional"],"畫":["chinese_traditional"],"雖":["chinese_traditional"],"雜":["chinese_traditional"],"飛":["chinese_traditional"],"檢":["chinese_traditional"],"昇":["chinese_traditional"],"陽":["chinese_traditional"],"創":["chinese_traditional"],"壞":["chinese_traditional"],"徑":["chinese_traditional"],"換":["chinese_traditional"],"鋼":["chinese_traditional"],"責":["chinese_traditional"],"簡":["chinese_traditional"],"錢":["chinese_traditional"],"盡":["chinese_traditional"],"衝":["chinese_traditional"],"獨":["chinese_traditional"],"環":["chinese_traditional"],"雙":["chinese_traditional"],"請":["chinese_traditional"],"讓":["chinese_traditional"],"軸":["chinese_traditional"],"紀":["chinese_traditional"],"優":["chinese_traditional"],"頂":["chinese_traditional"],"礎":["chinese_traditional"],"載":["chinese_traditional"],"敵":["chinese_traditional"],"勝":["chinese_traditional"],"絕":["chinese_traditional"],"塊":["chinese_traditional"],"劑":["chinese_traditional"],"測":["chinese_traditional"],"絲":["chinese_traditional"],"協":["chinese_traditional"],"訴":["chinese_traditional"],"陳":["chinese_traditional"],"羅":["chinese_traditional"],"鹽":["chinese_traditional"],"錯":["chinese_traditional"],"頻":["chinese_traditional"],"終":["chinese_traditional"],"雲":["chinese_traditional"],"衛":["chinese_traditional"],"燒":["chinese_traditional"],"遊":["chinese_traditional"],"舊":["chinese_traditional"],"貨":["chinese_traditional"],"損":["chinese_traditional"],"預":["chinese_traditional"],"穩":["chinese_traditional"],"媽":["chinese_traditional"],"擴":["chinese_traditional"],"銀":["chinese_traditional"],"語":["chinese_traditional"],"揮":["chinese_traditional"],"紙":["chinese_traditional"],"醫":["chinese_traditional"],"嗎":["chinese_traditional"],"針":["chinese_traditional"],"劉":["chinese_traditional"],"誤":["chinese_traditional"],"訓":["chinese_traditional"],"願":["chinese_traditional"],"審":["chinese_traditional"],"獲":["chinese_traditional"],"鮮":["chinese_traditional"],"糧":["chinese_traditional"],"脫":["chinese_traditional"],"龍":["chinese_traditional"],"漸":["chinese_traditional"],"歡":["chinese_traditional"],"剛":["chinese_traditional"],"謂":["chinese_traditional"],"討":["chinese_traditional"],"亂":["chinese_traditional"],"殺":["chinese_traditional"],"藥":["chinese_traditional"],"寧":["chinese_traditional"],"魯":["chinese_traditional"],"貴":["chinese_traditional"],"鐘":["chinese_traditional"],"讀":["chinese_traditional"],"豐":["chinese_traditional"],"蘭":["chinese_traditional"],"擔":["chinese_traditional"],"執":["chinese_traditional"],"樂":["chinese_traditional"],"誰":["chinese_traditional"],"順":["chinese_traditional"],"煙":["chinese_traditional"],"縮":["chinese_traditional"],"徵":["chinese_traditional"],"臉":["chinese_traditional"],"腳":["chinese_traditional"],"異":["chinese_traditional"],"買":["chinese_traditional"],"靜":["chinese_traditional"],"補":["chinese_traditional"],"評":["chinese_traditional"],"踐":["chinese_traditional"],"寬":["chinese_traditional"],"揚":["chinese_traditional"],"傷":["chinese_traditional"],"氫":["chinese_traditional"],"憲":["chinese_traditional"],"慶":["chinese_traditional"],"編":["chinese_traditional"],"觸":["chinese_traditional"],"銷":["chinese_traditional"],"詩":["chinese_traditional"],"綠":["chinese_traditional"],"雞":["chinese_traditional"],"孫":["chinese_traditional"],"膠":["chinese_traditional"],"鄉":["chinese_traditional"],"臨":["chinese_traditional"],"陸":["chinese_traditional"],"顧":["chinese_traditional"],"燈":["chinese_traditional"],"歲":["chinese_traditional"],"劇":["chinese_traditional"],"趙":["chinese_traditional"],"課":["chinese_traditional"],"凱":["chinese_traditional"],"額":["chinese_traditional"],"紹":["chinese_traditional"],"齊":["chinese_traditional"],"偉":["chinese_traditional"],"爐":["chinese_traditional"],"楊":["chinese_traditional"],"桿":["chinese_traditional"],"鎮":["chinese_traditional"],"飯":["chinese_traditional"],"濃":["chinese_traditional"],"懷":["chinese_traditional"],"趕":["chinese_traditional"],"庫":["chinese_traditional"],"奪":["chinese_traditional"],"靈":["chinese_traditional"],"稅":["chinese_traditional"],"滅":["chinese_traditional"],"賽":["chinese_traditional"],"歸":["chinese_traditional"],"盤":["chinese_traditional"],"險":["chinese_traditional"],"錄":["chinese_traditional"],"純":["chinese_traditional"],"蓋":["chinese_traditional"],"橫":["chinese_traditional"],"槍":["chinese_traditional"],"潤":["chinese_traditional"],"蟲":["chinese_traditional"],"澤":["chinese_traditional"],"腦":["chinese_traditional"],"歐":["chinese_traditional"],"側":["chinese_traditional"],"徹":["chinese_traditional"],"慮":["chinese_traditional"],"納":["chinese_traditional"],"彈":["chinese_traditional"],"飼":["chinese_traditional"],"麥":["chinese_traditional"],"濕":["chinese_traditional"],"築":["chinese_traditional"],"惡":["chinese_traditional"],"戶":["chinese_traditional"],"訪":["chinese_traditional"],"跡":["chinese_traditional"],"擺":["chinese_traditional"],"賣":["chinese_traditional"],"擇":["chinese_traditional"],"銅":["chinese_traditional"],"獻":["chinese_traditional"],"陣":["chinese_traditional"],"陰":["chinese_traditional"],"樓":["chinese_traditional"],"謀":["chinese_traditional"],"噸":["chinese_traditional"],"豬":["chinese_traditional"],"館":["chinese_traditional"],"爺":["chinese_traditional"],"驚":["chinese_traditional"],"遺":["chinese_traditional"],"纖":["chinese_traditional"],"傾":["chinese_traditional"],"謝":["chinese_traditional"],"奮":["chinese_traditional"],"購":["chinese_traditional"],"監":["chinese_traditional"],"貫":["chinese_traditional"],"釋":["chinese_traditional"],"詞":["chinese_traditional"],"頓":["chinese_traditional"],"寶":["chinese_traditional"],"塵":["chinese_traditional"],"聞":["chinese_traditional"],"殘":["chinese_traditional"],"橋":["chinese_traditional"],"婦":["chinese_traditional"],"綜":["chinese_traditional"],"吳":["chinese_traditional"],"搖":["chinese_traditional"],"贊":["chinese_traditional"],"訂":["chinese_traditional"],"園":["chinese_traditional"],"紛":["chinese_traditional"],"敗":["chinese_traditional"],"榮":["chinese_traditional"],"閉":["chinese_traditional"],"灣":["chinese_traditional"],"鍵":["chinese_traditional"],"駐":["chinese_traditional"],"鍋":["chinese_traditional"],"剝":["chinese_traditional"],"鹼":["chinese_traditional"],"齒":["chinese_traditional"],"煉":["chinese_traditional"],"紡":["chinese_traditional"],"廢":["chinese_traditional"],"緩":["chinese_traditional"],"淨":["chinese_traditional"],"莊":["chinese_traditional"],"貿":["chinese_traditional"],"慣":["chinese_traditional"],"夥":["chinese_traditional"],"勻":["chinese_traditional"],"紗":["chinese_traditional"],"辯":["chinese_traditional"],"億":["chinese_traditional"],"脈":["chinese_traditional"],"薩":["chinese_traditional"],"網":["chinese_traditional"],"噴":["chinese_traditional"],"縱":["chinese_traditional"],"掛":["chinese_traditional"],"賀":["chinese_traditional"],"閃":["chinese_traditional"],"牆":["chinese_traditional"],"軟":["chinese_traditional"],"滾":["chinese_traditional"],"盪":["chinese_traditional"],"儀":["chinese_traditional"],"軋":["chinese_traditional"],"貢":["chinese_traditional"],"鑽":["chinese_traditional"],"幣":["chinese_traditional"],"軌":["chinese_traditional"],"畝":["chinese_traditional"],"畢":["chinese_traditional"],"島":["chinese_traditional"],"鑄":["chinese_traditional"],"湯":["chinese_traditional"],"閥":["chinese_traditional"],"匯":["chinese_traditional"],"繞":["chinese_traditional"],"績":["chinese_traditional"],"啟":["chinese_traditional"],"顏":["chinese_traditional"],"淚":["chinese_traditional"],"藍":["chinese_traditional"],"鏡":["chinese_traditional"],"壯":["chinese_traditional"],"鋒":["chinese_traditional"],"貧":["chinese_traditional"],"虛":["chinese_traditional"],"彎":["chinese_traditional"],"綱":["chinese_traditional"],"隸":["chinese_traditional"],"宮":["chinese_traditional"],"違":["chinese_traditional"],"夾":["chinese_traditional"],"緣":["chinese_traditional"],"窮":["chinese_traditional"],"溝":["chinese_traditional"],"繩":["chinese_traditional"],"憶":["chinese_traditional"],"漿":["chinese_traditional"],"欄":["chinese_traditional"],"擁":["chinese_traditional"],"貯":["chinese_traditional"],"禮":["chinese_traditional"],"濾":["chinese_traditional"],"鈉":["chinese_traditional"],"紋":["chinese_traditional"],"罷":["chinese_traditional"],"罰":["chinese_traditional"],"潛":["chinese_traditional"],"縫":["chinese_traditional"],"飽":["chinese_traditional"],"獎":["chinese_traditional"],"鋁":["chinese_traditional"],"麗":["chinese_traditional"],"鏈":["chinese_traditional"],"掃":["chinese_traditional"],"諸":["chinese_traditional"],"勵":["chinese_traditional"],"潔":["chinese_traditional"],"災":["chinese_traditional"],"鑑":["chinese_traditional"],"訟":["chinese_traditional"],"毀":["chinese_traditional"],"屆":["chinese_traditional"],"躍":["chinese_traditional"],"艱":["chinese_traditional"],"貝":["chinese_traditional"],"碼":["chinese_traditional"],"夢":["chinese_traditional"],"漁":["chinese_traditional"],"顆":["chinese_traditional"],"鉛":["chinese_traditional"],"倉":["chinese_traditional"],"銳":["chinese_traditional"],"曉":["chinese_traditional"],"隱":["chinese_traditional"],"礙":["chinese_traditional"],"撥":["chinese_traditional"],"肅":["chinese_traditional"],"牽":["chinese_traditional"],"搶":["chinese_traditional"],"殼":["chinese_traditional"],"訊":["chinese_traditional"],"誠":["chinese_traditional"],"頁":["chinese_traditional"],"齡":["chinese_traditional"],"倫":["chinese_traditional"],"尋":["chinese_traditional"],"鋪":["chinese_traditional"],"聖":["chinese_traditional"],"鄭":["chinese_traditional"],"騰":["chinese_traditional"],"貼":["chinese_traditional"],"闊":["chinese_traditional"],"輛":["chinese_traditional"],"儲":["chinese_traditional"],"簽":["chinese_traditional"],"鬧":["chinese_traditional"],"擾":["chinese_traditional"],"遞":["chinese_traditional"],"戲":["chinese_traditional"],"餵":["chinese_traditional"],"療":["chinese_traditional"],"撫":["chinese_traditional"],"蝦":["chinese_traditional"],"蠟":["chinese_traditional"],"鄰":["chinese_traditional"],"鞏":["chinese_traditional"],"擠":["chinese_traditional"],"棄":["chinese_traditional"],"勁":["chinese_traditional"],"鄧":["chinese_traditional"],"爛":["chinese_traditional"],"磚":["chinese_traditional"],"烏":["chinese_traditional"],"艦":["chinese_traditional"],"淺":["chinese_traditional"],"暫":["chinese_traditional"],"膽":["chinese_traditional"],"詳":["chinese_traditional"],"譜":["chinese_traditional"],"賓":["chinese_traditional"],"輝":["chinese_traditional"],"憤":["chinese_traditional"],"競":["chinese_traditional"],"緒":["chinese_traditional"],"塗":["chinese_traditional"],"偵":["chinese_traditional"],"懸":["chinese_traditional"],"糾":["chinese_traditional"],"鎖":["chinese_traditional"],"賞":["chinese_traditional"],"鴨":["chinese_traditional"],"趨":["chinese_traditional"],"鳳":["chinese_traditional"],"輩":["chinese_traditional"],"灘":["chinese_traditional"],"驅":["chinese_traditional"],"篩":["chinese_traditional"],"峽":["chinese_traditional"],"壽":["chinese_traditional"],"譯":["chinese_traditional"],"遲":["chinese_traditional"],"矽":["chinese_traditional"],"貸":["chinese_traditional"],"脅":["chinese_traditional"],"蝕":["chinese_traditional"],"奧":["chinese_traditional"],"鳴":["chinese_traditional"],"嶺":["chinese_traditional"],"憑":["chinese_traditional"],"繪":["chinese_traditional"],"錫":["chinese_traditional"],"廟":["chinese_traditional"],"籌":["chinese_traditional"],"凍":["chinese_traditional"],"輔":["chinese_traditional"],"攝":["chinese_traditional"],"襲":["chinese_traditional"],"鉀":["chinese_traditional"],"鳥":["chinese_traditional"],"韓":["chinese_traditional"],"僑":["chinese_traditional"],"涼":["chinese_traditional"],"餾":["chinese_traditional"],"勸":["chinese_traditional"],"遼":["chinese_traditional"],"鴻":["chinese_traditional"],"輥":["chinese_traditional"],"飲":["chinese_traditional"],"罵":["chinese_traditional"],"辭":["chinese_traditional"],"蔣":["chinese_traditional"],"絨":["chinese_traditional"],"霧":["chinese_traditional"],"擬":["chinese_traditional"],"輯":["chinese_traditional"],"陝":["chinese_traditional"],"償":["chinese_traditional"],"廳":["chinese_traditional"],"駛":["chinese_traditional"],"賦":["chinese_traditional"],"澆":["chinese_traditional"],"鈣":["chinese_traditional"],"虧":["chinese_traditional"],"騙":["chinese_traditional"],"脹":["chinese_traditional"],"諧":["chinese_traditional"],"拋":["chinese_traditional"],"黴":["chinese_traditional"],"崗":["chinese_traditional"],"盜":["chinese_traditional"],"滲":["chinese_traditional"],"臟":["chinese_traditional"],"賴":["chinese_traditional"],"湧":["chinese_traditional"],"閱":["chinese_traditional"],"厲":["chinese_traditional"],"烴":["chinese_traditional"],"緯":["chinese_traditional"],"偽":["chinese_traditional"],"嘆":["chinese_traditional"],"釘":["chinese_traditional"],"莖":["chinese_traditional"],"籠":["chinese_traditional"],"錐":["chinese_traditional"],"恆":["chinese_traditional"],"傑":["chinese_traditional"],"綸":["chinese_traditional"],"敘":["chinese_traditional"],"獄":["chinese_traditional"],"絡":["chinese_traditional"],"驟":["chinese_traditional"],"冊":["chinese_traditional"],"屍":["chinese_traditional"],"紳":["chinese_traditional"],"犧":["chinese_traditional"],"轟":["chinese_traditional"],"晉":["chinese_traditional"],"禦":["chinese_traditional"],"錠":["chinese_traditional"],"錦":["chinese_traditional"],"喪":["chinese_traditional"],"鍛":["chinese_traditional"],"壟":["chinese_traditional"],"撲":["chinese_traditional"],"邁":["chinese_traditional"],"閒":["chinese_traditional"],"憂":["chinese_traditional"],"頑":["chinese_traditional"],"漲":["chinese_traditional"],"闢":["chinese_traditional"],"懲":["chinese_traditional"],"飄":["chinese_traditional"],"飾":["chinese_traditional"],"蕭":["chinese_traditional"],"郵":["chinese_traditional"],"遷":["chinese_traditional"],"煩":["chinese_traditional"],"債":["chinese_traditional"],"帳":["chinese_traditional"],"鈴":["chinese_traditional"],"餅":["chinese_traditional"],"雛":["chinese_traditional"],"賢":["chinese_traditional"],"丟":["chinese_traditional"],"墊":["chinese_traditional"],"擋":["chinese_traditional"],"覽":["chinese_traditional"],"貪":["chinese_traditional"],"繳":["chinese_traditional"],"馮":["chinese_traditional"],"諾":["chinese_traditional"],"誼":["chinese_traditional"],"兇":["chinese_traditional"],"誣":["chinese_traditional"],"騎":["chinese_traditional"],"喬":["chinese_traditional"],"叢":["chinese_traditional"],"盧":["chinese_traditional"],"悶":["chinese_traditional"],"諮":["chinese_traditional"],"駕":["chinese_traditional"],"纜":["chinese_traditional"],"鉺":["chinese_traditional"],"擲":["chinese_traditional"],"頗":["chinese_traditional"],"慘":["chinese_traditional"],"臘":["chinese_traditional"],"窩":["chinese_traditional"],"滌":["chinese_traditional"],"劍":["chinese_traditional"],"潑":["chinese_traditional"],"蔥":["chinese_traditional"],"撈":["chinese_traditional"],"蒼":["chinese_traditional"],"濱":["chinese_traditional"],"倆":["chinese_traditional"],"瘋":["chinese_traditional"],"糞":["chinese_traditional"],"檔":["chinese_traditional"],"駁":["chinese_traditional"],"腸":["chinese_traditional"],"撐":["chinese_traditional"],"曬":["chinese_traditional"],"蓮":["chinese_traditional"],"攤":["chinese_traditional"],"攪":["chinese_traditional"],"醬":["chinese_traditional"],"皺":["chinese_traditional"],"暢":["chinese_traditional"],"疊":["chinese_traditional"],"閣":["chinese_traditional"],"萊":["chinese_traditional"],"轄":["chinese_traditional"],"鉤":["chinese_traditional"],"壩":["chinese_traditional"],"餓":["chinese_traditional"],"禍":["chinese_traditional"],"邏":["chinese_traditional"],"嘗":["chinese_traditional"],"韋":["chinese_traditional"],"abdikace":["czech"],"abeceda":["czech"],"adresa":["czech"],"agrese":["czech"],"akce":["czech"],"aktovka":["czech"],"alej":["czech"],"alkohol":["czech"],"amputace":["czech"],"ananas":["czech"],"andulka":["czech"],"anekdota":["czech"],"anketa":["czech"],"antika":["czech"],"anulovat":["czech"],"archa":["czech"],"arogance":["czech"],"asfalt":["czech","turkish"],"asistent":["czech"],"aspirace":["czech"],"astma":["czech"],"astronom":["czech"],"atlas":["czech"],"atletika":["czech"],"atol":["czech"],"autobus":["czech"],"azyl":["czech"],"babka":["czech"],"bachor":["czech"],"bacil":["czech"],"baculka":["czech"],"badatel":["czech"],"bageta":["czech"],"bagr":["czech"],"bahno":["czech"],"bakterie":["czech"],"balada":["czech"],"baletka":["czech"],"balkon":["czech"],"balonek":["czech"],"balvan":["czech"],"balza":["czech"],"bambus":["czech"],"bankomat":["czech"],"barbar":["czech"],"baret":["czech"],"barman":["czech"],"baroko":["czech"],"barva":["czech"],"baterka":["czech"],"batoh":["czech"],"bavlna":["czech"],"bazalka":["czech"],"bazilika":["czech"],"bazuka":["czech"],"bedna":["czech"],"beran":["czech"],"beseda":["czech"],"bestie":["czech"],"beton":["czech","turkish"],"bezinka":["czech"],"bezmoc":["czech"],"beztak":["czech"],"bicykl":["czech"],"bidlo":["czech"],"biftek":["czech","turkish"],"bikiny":["czech"],"bilance":["czech"],"biograf":["czech"],"biolog":["czech"],"bitva":["czech"],"bizon":["czech"],"blahobyt":["czech"],"blatouch":["czech"],"blecha":["czech"],"bledule":["czech"],"blesk":["czech"],"blikat":["czech"],"blizna":["czech"],"blokovat":["czech"],"bloudit":["czech"],"blud":["czech"],"bobek":["czech"],"bobr":["czech"],"bodlina":["czech"],"bodnout":["czech"],"bohatost":["czech"],"bojkot":["czech"],"bojovat":["czech"],"bokorys":["czech"],"bolest":["czech"],"borec":["czech"],"borovice":["czech"],"bota":["czech"],"boubel":["czech"],"bouchat":["czech"],"bouda":["czech"],"boule":["czech"],"bourat":["czech"],"boxer":["czech"],"bradavka":["czech"],"brambora":["czech"],"branka":["czech"],"bratr":["czech"],"brepta":["czech"],"briketa":["czech"],"brko":["czech"],"brloh":["czech"],"bronz":["czech"],"broskev":["czech"],"brunetka":["czech"],"brusinka":["czech"],"brzda":["czech"],"brzy":["czech"],"bublina":["czech"],"bubnovat":["czech"],"buchta":["czech"],"buditel":["czech"],"budka":["czech"],"budova":["czech"],"bufet":["czech"],"bujarost":["czech"],"bukvice":["czech"],"buldok":["czech"],"bulva":["czech"],"bunda":["czech"],"bunkr":["czech"],"burza":["czech"],"butik":["czech","turkish"],"buvol":["czech"],"buzola":["czech"],"bydlet":["czech"],"bylina":["czech"],"bytovka":["czech"],"bzukot":["czech"],"capart":["czech"],"carevna":["czech"],"cedr":["czech"],"cedule":["czech"],"cejch":["czech"],"cejn":["czech"],"cela":["czech"],"celer":["czech"],"celkem":["czech"],"celnice":["czech"],"cenina":["czech"],"cennost":["czech"],"cenovka":["czech"],"centrum":["czech"],"cenzor":["czech"],"cestopis":["czech"],"cetka":["czech"],"chalupa":["czech"],"chapadlo":["czech"],"charita":["czech"],"chata":["czech"],"chechtat":["czech"],"chemie":["czech"],"chichot":["czech"],"chirurg":["czech"],"chlad":["czech"],"chleba":["czech"],"chlubit":["czech"],"chmel":["czech"],"chmura":["czech"],"chobot":["czech"],"chochol":["czech"],"chodba":["czech"],"cholera":["czech"],"chomout":["czech"],"chopit":["czech"],"choroba":["czech"],"chov":["czech"],"chrapot":["czech"],"chrlit":["czech"],"chrt":["czech"],"chrup":["czech"],"chtivost":["czech"],"chudina":["czech"],"chutnat":["czech"],"chvat":["czech"],"chvilka":["czech"],"chvost":["czech"],"chyba":["czech"],"chystat":["czech"],"chytit":["czech"],"cibule":["czech"],"cigareta":["czech"],"cihelna":["czech"],"cihla":["czech"],"cinkot":["czech"],"cirkus":["czech"],"cisterna":["czech"],"citace":["czech"],"citrus":["czech"],"cizinec":["czech"],"cizost":["czech"],"clona":["czech"],"cokoliv":["czech"],"couvat":["czech"],"ctitel":["czech"],"ctnost":["czech"],"cudnost":["czech"],"cuketa":["czech"],"cukr":["czech"],"cupot":["czech"],"cvaknout":["czech"],"cval":["czech"],"cvik":["czech"],"cvrkot":["czech"],"cyklista":["czech"],"daleko":["czech"],"dareba":["czech"],"datel":["czech"],"datum":["czech"],"dcera":["czech"],"debata":["czech"],"dechovka":["czech"],"decibel":["czech"],"deficit":["czech"],"deflace":["czech"],"dekl":["czech"],"dekret":["czech"],"demokrat":["czech"],"deprese":["czech"],"derby":["czech"],"deska":["czech"],"detektiv":["czech"],"dikobraz":["czech"],"diktovat":["czech"],"dioda":["czech"],"diplom":["czech"],"disk":["czech","turkish"],"displej":["czech"],"divadlo":["czech"],"divoch":["czech"],"dlaha":["czech"],"dlouho":["czech"],"dluhopis":["czech"],"dnes":["czech"],"dobro":["czech"],"dobytek":["czech"],"docent":["czech"],"dochutit":["czech"],"dodnes":["czech"],"dohled":["czech"],"dohoda":["czech"],"dohra":["czech"],"dojem":["czech"],"dojnice":["czech"],"doklad":["czech"],"dokola":["czech"],"doktor":["czech","turkish"],"dokument":["czech"],"dolar":["czech"],"doleva":["czech"],"dolina":["czech"],"doma":["czech"],"dominant":["czech"],"domluvit":["czech"],"domov":["czech"],"donutit":["czech"],"dopad":["czech"],"dopis":["czech"],"doplnit":["czech"],"doposud":["czech"],"doprovod":["czech"],"dopustit":["czech"],"dorazit":["czech"],"dorost":["czech"],"dort":["czech"],"dosah":["czech"],"doslov":["czech"],"dostatek":["czech"],"dosud":["czech"],"dosyta":["czech"],"dotaz":["czech"],"dotek":["czech"],"dotknout":["czech"],"doufat":["czech"],"doutnat":["czech"],"dovozce":["czech"],"dozadu":["czech"],"doznat":["czech"],"dozorce":["czech"],"drahota":["czech"],"drak":["czech"],"dramatik":["czech"],"dravec":["czech"],"draze":["czech"],"drdol":["czech"],"drobnost":["czech"],"drogerie":["czech"],"drozd":["czech"],"drsnost":["czech"],"drtit":["czech"],"drzost":["czech"],"duben":["czech"],"duchovno":["czech"],"dudek":["czech"],"duha":["czech"],"duhovka":["czech"],"dusit":["czech"],"dusno":["czech"],"dutost":["czech"],"dvojice":["czech"],"dvorec":["czech"],"dynamit":["czech"],"ekolog":["czech"],"ekonomie":["czech"],"elektron":["czech"],"elipsa":["czech"],"email":["czech"],"emise":["czech"],"emoce":["czech"],"empatie":["czech"],"epizoda":["czech"],"epocha":["czech"],"epopej":["czech"],"epos":["czech"],"esej":["czech"],"esence":["czech"],"eskorta":["czech"],"eskymo":["czech"],"etiketa":["czech"],"euforie":["czech"],"evoluce":["czech"],"exekuce":["czech"],"exkurze":["czech"],"expedice":["czech"],"exploze":["czech"],"export":["czech"],"extrakt":["czech"],"facka":["czech"],"fajfka":["czech"],"fakulta":["czech"],"fanatik":["czech","turkish"],"fantazie":["czech"],"farmacie":["czech"],"favorit":["czech"],"fazole":["czech"],"federace":["czech"],"fejeton":["czech"],"fenka":["czech"],"fialka":["czech"],"figurant":["czech"],"filozof":["czech"],"filtr":["czech"],"finance":["czech"],"finta":["czech"],"fixace":["czech"],"fjord":["czech"],"flanel":["czech"],"flirt":["czech"],"flotila":["czech"],"fond":["czech"],"fosfor":["czech"],"fotbal":["czech"],"fotka":["czech"],"foton":["czech"],"frakce":["czech"],"freska":["czech"],"fronta":["czech"],"fukar":["czech"],"funkce":["czech"],"fyzika":["czech"],"galeje":["czech"],"garant":["czech"],"genetika":["czech"],"geolog":["czech"],"gilotina":["czech"],"glazura":["czech"],"glejt":["czech"],"golem":["czech"],"golfista":["czech"],"gotika":["czech"],"graf":["czech"],"gramofon":["czech"],"granule":["czech"],"grep":["czech"],"gril":["czech"],"grog":["czech"],"groteska":["czech"],"guma":["czech"],"hadice":["czech"],"hadr":["czech"],"hala":["czech"],"halenka":["czech"],"hanba":["czech"],"hanopis":["czech"],"harfa":["czech"],"harpuna":["czech"],"havran":["czech"],"hebkost":["czech"],"hejkal":["czech"],"hejno":["czech"],"hejtman":["czech"],"hektar":["czech","turkish"],"helma":["czech"],"hematom":["czech"],"herec":["czech"],"herna":["czech"],"heslo":["czech"],"hezky":["czech"],"historik":["czech"],"hladovka":["czech"],"hlasivky":["czech"],"hlava":["czech"],"hledat":["czech"],"hlen":["czech"],"hlodavec":["czech"],"hloh":["czech"],"hloupost":["czech"],"hltat":["czech"],"hlubina":["czech"],"hluchota":["czech"],"hmat":["czech"],"hmota":["czech"],"hmyz":["czech"],"hnis":["czech"],"hnojivo":["czech"],"hnout":["czech"],"hoblina":["czech"],"hoboj":["czech"],"hoch":["czech"],"hodiny":["czech"],"hodlat":["czech"],"hodnota":["czech"],"hodovat":["czech"],"hojnost":["czech"],"hokej":["czech"],"holinka":["czech"],"holka":["czech"],"holub":["czech"],"homole":["czech"],"honitba":["czech"],"honorace":["czech"],"horal":["czech"],"horda":["czech"],"horizont":["czech"],"horko":["czech"],"horlivec":["czech"],"hormon":["czech","turkish"],"hornina":["czech"],"horoskop":["czech"],"horstvo":["czech"],"hospoda":["czech"],"hostina":["czech"],"hotovost":["czech"],"houba":["czech"],"houf":["czech"],"houpat":["czech"],"houska":["czech"],"hovor":["czech"],"hradba":["czech"],"hranice":["czech"],"hravost":["czech"],"hrazda":["czech"],"hrbolek":["czech"],"hrdina":["czech"],"hrdlo":["czech"],"hrdost":["czech"],"hrnek":["czech"],"hrobka":["czech"],"hromada":["czech"],"hrot":["czech"],"hrouda":["czech"],"hrozen":["czech"],"hrstka":["czech"],"hrubost":["czech"],"hryzat":["czech"],"hubenost":["czech"],"hubnout":["czech"],"hudba":["czech"],"hukot":["czech"],"humr":["czech"],"husita":["czech"],"hustota":["czech"],"hvozd":["czech"],"hybnost":["czech"],"hydrant":["czech"],"hygiena":["czech"],"hymna":["czech"],"hysterik":["czech"],"idylka":["czech"],"ihned":["czech"],"ikona":["czech"],"iluze":["czech"],"imunita":["czech"],"infekce":["czech"],"inflace":["czech"],"inkaso":["czech"],"inovace":["czech"],"inspekce":["czech"],"internet":["czech"],"invalida":["czech"],"investor":["czech"],"inzerce":["czech"],"ironie":["czech"],"jablko":["czech"],"jachta":["czech"],"jahoda":["czech"],"jakmile":["czech"],"jakost":["czech"],"jalovec":["czech"],"jantar":["czech"],"jarmark":["czech"],"jaro":["czech"],"jasan":["czech"],"jasno":["czech"],"jatka":["czech"],"javor":["czech"],"jazyk":["czech"],"jedinec":["czech"],"jedle":["czech"],"jednatel":["czech"],"jehlan":["czech"],"jekot":["czech"],"jelen":["czech"],"jelito":["czech"],"jemnost":["czech"],"jenom":["czech"],"jepice":["czech"],"jeseter":["czech"],"jevit":["czech"],"jezdec":["czech"],"jezero":["czech"],"jinak":["czech"],"jindy":["czech"],"jinoch":["czech"],"jiskra":["czech"],"jistota":["czech"],"jitrnice":["czech"],"jizva":["czech"],"jmenovat":["czech"],"jogurt":["czech"],"jurta":["czech"],"kabaret":["czech"],"kabel":["czech"],"kabinet":["czech"],"kachna":["czech"],"kadet":["czech"],"kadidlo":["czech"],"kahan":["czech"],"kajak":["czech"],"kajuta":["czech"],"kakao":["czech"],"kaktus":["czech"],"kalamita":["czech"],"kalhoty":["czech"],"kalibr":["czech"],"kalnost":["czech"],"kamera":["czech"],"kamkoliv":["czech"],"kamna":["czech"],"kanibal":["czech"],"kanoe":["czech"],"kantor":["czech"],"kapalina":["czech"],"kapela":["czech"],"kapitola":["czech"],"kapka":["czech"],"kaple":["czech"],"kapota":["czech"],"kapr":["czech"],"kapusta":["czech"],"kapybara":["czech"],"karamel":["czech"],"karotka":["czech"],"karton":["czech"],"kasa":["czech"],"katalog":["czech"],"katedra":["czech"],"kauce":["czech"],"kauza":["czech"],"kavalec":["czech"],"kazajka":["czech"],"kazeta":["czech"],"kazivost":["czech"],"kdekoliv":["czech"],"kdesi":["czech"],"kedluben":["czech"],"kemp":["czech"],"keramika":["czech"],"kino":["czech"],"klacek":["czech"],"kladivo":["czech"],"klam":["czech"],"klapot":["czech"],"klasika":["czech"],"klaun":["czech"],"klec":["czech"],"klenba":["czech"],"klepat":["czech"],"klesnout":["czech"],"klid":["czech"],"klima":["czech"],"klisna":["czech"],"klobouk":["czech"],"klokan":["czech"],"klopa":["czech"],"kloub":["czech"],"klubovna":["czech"],"klusat":["czech"],"kluzkost":["czech"],"kmen":["czech"],"kmitat":["czech"],"kmotr":["czech"],"kniha":["czech"],"knot":["czech"],"koalice":["czech"],"koberec":["czech"],"kobka":["czech"],"kobliha":["czech"],"kobyla":["czech"],"kocour":["czech"],"kohout":["czech"],"kojenec":["czech"],"kokos":["czech"],"koktejl":["czech"],"kolaps":["czech"],"koleda":["czech"],"kolize":["czech"],"kolo":["czech"],"komando":["czech"],"kometa":["czech"],"komik":["czech"],"komnata":["czech"],"komora":["czech"],"kompas":["czech"],"komunita":["czech"],"konat":["czech"],"koncept":["czech"],"kondice":["czech"],"konec":["czech"],"konfese":["czech"],"kongres":["czech"],"konina":["czech"],"konkurs":["czech"],"kontakt":["czech"],"konzerva":["czech"],"kopanec":["czech"],"kopie":["czech"],"kopnout":["czech"],"koprovka":["czech"],"korbel":["czech"],"korektor":["czech"],"kormidlo":["czech"],"koroptev":["czech"],"korpus":["czech"],"koruna":["czech"],"koryto":["czech"],"korzet":["czech"],"kosatec":["czech"],"kostka":["czech"],"kotel":["czech"],"kotleta":["czech"],"kotoul":["czech"],"koukat":["czech"],"koupelna":["czech"],"kousek":["czech"],"kouzlo":["czech"],"kovboj":["czech"],"koza":["czech"],"kozoroh":["czech"],"krabice":["czech"],"krach":["czech"],"krajina":["czech"],"kralovat":["czech"],"krasopis":["czech"],"kravata":["czech"],"kredit":["czech"],"krejcar":["czech"],"kresba":["czech"],"kreveta":["czech"],"kriket":["czech"],"kritik":["czech"],"krize":["czech"],"krkavec":["czech"],"krmelec":["czech"],"krmivo":["czech"],"krocan":["czech"],"krok":["czech"],"kronika":["czech"],"kropit":["czech"],"kroupa":["czech"],"krovka":["czech"],"krtek":["czech"],"kruhadlo":["czech"],"krupice":["czech"],"krutost":["czech"],"krvinka":["czech"],"krychle":["czech"],"krypta":["czech"],"krystal":["czech"],"kryt":["czech"],"kudlanka":["czech"],"kufr":["czech"],"kujnost":["czech"],"kukla":["czech"],"kulajda":["czech"],"kulich":["czech"],"kulka":["czech"],"kulomet":["czech"],"kultura":["czech"],"kuna":["czech"],"kupodivu":["czech"],"kurt":["czech"],"kurzor":["czech"],"kutil":["czech"],"kvalita":["czech"],"kvasinka":["czech"],"kvestor":["czech"],"kynolog":["czech"],"kyselina":["czech"],"kytara":["czech"],"kytice":["czech"],"kytka":["czech"],"kytovec":["czech"],"kyvadlo":["czech"],"labrador":["czech"],"lachtan":["czech"],"ladnost":["czech"],"laik":["czech"],"lakomec":["czech"],"lamela":["czech"],"lampa":["czech"],"lanovka":["czech"],"lasice":["czech"],"laso":["czech"],"lastura":["czech"],"latinka":["czech"],"lavina":["czech"],"lebka":["czech"],"leckdy":["czech"],"leden":["czech"],"lednice":["czech"],"ledovka":["czech"],"ledvina":["czech"],"legenda":["czech"],"legie":["czech"],"legrace":["czech"],"lehce":["czech"],"lehkost":["czech"],"lehnout":["czech"],"lektvar":["czech"],"lenochod":["czech"],"lentilka":["czech"],"lepenka":["czech"],"lepidlo":["czech"],"letadlo":["czech"],"letec":["czech"],"letmo":["czech"],"letokruh":["czech"],"levhart":["czech"],"levitace":["czech"],"levobok":["czech"],"libra":["czech"],"lichotka":["czech"],"lidojed":["czech"],"lidskost":["czech"],"lihovina":["czech"],"lijavec":["czech"],"lilek":["czech"],"limetka":["czech"],"linie":["czech"],"linka":["czech"],"linoleum":["czech"],"listopad":["czech"],"litina":["czech"],"litovat":["czech"],"lobista":["czech"],"lodivod":["czech"],"logika":["czech"],"logoped":["czech"],"lokalita":["czech"],"loket":["czech"],"lomcovat":["czech"],"lopata":["czech"],"lopuch":["czech"],"lord":["czech"],"losos":["czech"],"lotr":["czech"],"loudal":["czech"],"louh":["czech"],"louka":["czech"],"louskat":["czech"],"lovec":["czech"],"lstivost":["czech"],"lucerna":["czech"],"lucifer":["czech"],"lump":["czech"],"lusk":["czech"],"lustrace":["czech"],"lvice":["czech"],"lyra":["czech"],"lyrika":["czech"],"lysina":["czech"],"madam":["czech"],"madlo":["czech"],"magistr":["czech"],"mahagon":["czech"],"majetek":["czech"],"majitel":["czech"],"majorita":["czech"],"makak":["czech"],"makovice":["czech"],"makrela":["czech"],"malba":["czech"],"malina":["czech"],"malovat":["czech"],"malvice":["czech"],"maminka":["czech"],"mandle":["czech"],"manko":["czech"],"marnost":["czech"],"masakr":["czech"],"maskot":["czech"],"masopust":["czech"],"matice":["czech"],"matrika":["czech"],"maturita":["czech"],"mazanec":["czech"],"mazivo":["czech"],"mazlit":["czech"],"mazurka":["czech"],"mdloba":["czech"],"mechanik":["czech"],"meditace":["czech"],"medovina":["czech"],"melasa":["czech"],"meloun":["czech"],"mentolka":["czech"],"metla":["czech"],"metoda":["czech"],"metr":["czech"],"mezera":["czech"],"migrace":["czech"],"mihnout":["czech"],"mihule":["czech"],"mikina":["czech"],"mikrofon":["czech","turkish"],"milenec":["czech"],"milimetr":["czech"],"milost":["czech"],"mimika":["czech"],"mincovna":["czech"],"minibar":["czech"],"minomet":["czech"],"minulost":["czech"],"miska":["czech"],"mistr":["czech"],"mixovat":["czech"],"mladost":["czech"],"mlha":["czech"],"mlhovina":["czech"],"mlok":["czech"],"mlsat":["czech"],"mluvit":["czech"],"mnich":["czech"],"mnohem":["czech"],"mobil":["czech"],"mocnost":["czech"],"modelka":["czech"],"modlitba":["czech"],"mohyla":["czech"],"mokro":["czech"],"molekula":["czech"],"momentka":["czech"],"monarcha":["czech"],"monokl":["czech"],"monstrum":["czech"],"montovat":["czech"],"monzun":["czech"],"mosaz":["czech"],"moskyt":["czech"],"most":["czech"],"motivace":["czech"],"motorka":["czech"],"motyka":["czech"],"moucha":["czech"],"moudrost":["czech"],"mozaika":["czech"],"mozek":["czech"],"mozol":["czech"],"mramor":["czech"],"mravenec":["czech"],"mrkev":["czech"],"mrtvola":["czech"],"mrzet":["czech"],"mrzutost":["czech"],"mstitel":["czech"],"mudrc":["czech"],"muflon":["czech"],"mulat":["czech"],"mumie":["czech"],"munice":["czech"],"muset":["czech"],"mutace":["czech"],"muzeum":["czech"],"muzikant":["czech"],"myslivec":["czech"],"mzda":["czech"],"nabourat":["czech"],"nachytat":["czech"],"nadace":["czech"],"nadbytek":["czech"],"nadhoz":["czech"],"nadobro":["czech"],"nadpis":["czech"],"nahlas":["czech"],"nahnat":["czech"],"nahodile":["czech"],"nahradit":["czech"],"naivita":["czech"],"najednou":["czech"],"najisto":["czech"],"najmout":["czech"],"naklonit":["czech"],"nakonec":["czech"],"nakrmit":["czech"],"nalevo":["czech"],"namazat":["czech"],"namluvit":["czech"],"nanometr":["czech"],"naoko":["czech"],"naopak":["czech"],"naostro":["czech"],"napadat":["czech"],"napevno":["czech"],"naplnit":["czech"],"napnout":["czech"],"naposled":["czech"],"naprosto":["czech"],"narodit":["czech"],"naruby":["czech"],"narychlo":["czech"],"nasadit":["czech"],"nasekat":["czech"],"naslepo":["czech"],"nastat":["czech"],"natolik":["czech"],"navenek":["czech"],"navrch":["czech"],"navzdory":["czech"],"nazvat":["czech"],"nebe":["czech"],"nechat":["czech"],"necky":["czech"],"nedaleko":["czech"],"nedbat":["czech"],"neduh":["czech"],"negace":["czech"],"nehet":["czech"],"nehoda":["czech"],"nejen":["czech"],"nejprve":["czech"],"neklid":["czech"],"nelibost":["czech"],"nemilost":["czech"],"nemoc":["czech"],"neochota":["czech"],"neonka":["czech"],"nepokoj":["czech"],"nerost":["czech"],"nerv":["czech"],"nesmysl":["czech"],"nesoulad":["czech"],"netvor":["czech"],"neuron":["czech"],"nevina":["czech"],"nezvykle":["czech"],"nicota":["czech"],"nijak":["czech"],"nikam":["czech"],"nikdy":["czech"],"nikl":["czech"],"nikterak":["czech"],"nitro":["czech"],"nocleh":["czech"],"nohavice":["czech"],"nominace":["czech"],"nora":["czech"],"norek":["czech"],"nositel":["czech"],"nosnost":["czech"],"nouze":["czech"],"noviny":["czech"],"novota":["czech"],"nozdra":["czech"],"nuda":["czech"],"nudle":["czech"],"nuget":["czech"],"nutit":["czech"],"nutnost":["czech"],"nutrie":["czech"],"nymfa":["czech"],"obal":["czech"],"obarvit":["czech"],"obava":["czech"],"obdiv":["czech"],"obec":["czech"],"obehnat":["czech"],"obejmout":["czech"],"obezita":["czech"],"obhajoba":["czech"],"obilnice":["czech"],"objasnit":["czech"],"objekt":["czech"],"obklopit":["czech"],"oblast":["czech"],"oblek":["czech"],"obliba":["czech"],"obloha":["czech"],"obluda":["czech"],"obnos":["czech"],"obohatit":["czech"],"obojek":["czech"],"obout":["czech"],"obrazec":["czech"],"obrna":["czech"],"obruba":["czech"],"obrys":["czech"],"obsah":["czech"],"obsluha":["czech"],"obstarat":["czech"],"obuv":["czech"],"obvaz":["czech"],"obvinit":["czech"],"obvod":["czech"],"obvykle":["czech"],"obyvatel":["czech"],"obzor":["czech"],"ocas":["czech"],"ocel":["czech"],"ocenit":["czech"],"ochladit":["czech"],"ochota":["czech"],"ochrana":["czech"],"ocitnout":["czech"],"odboj":["czech"],"odbyt":["czech"],"odchod":["czech"],"odcizit":["czech"],"odebrat":["czech"],"odeslat":["czech"],"odevzdat":["czech"],"odezva":["czech"],"odhadce":["czech"],"odhodit":["czech"],"odjet":["czech"],"odjinud":["czech"],"odkaz":["czech"],"odkoupit":["czech"],"odliv":["czech"],"odluka":["czech"],"odmlka":["czech"],"odolnost":["czech"],"odpad":["czech"],"odpis":["czech"],"odplout":["czech"],"odpor":["czech"],"odpustit":["czech"],"odpykat":["czech"],"odrazka":["czech"],"odsoudit":["czech"],"odstup":["czech"],"odsun":["czech"],"odtok":["czech"],"odtud":["czech"],"odvaha":["czech"],"odveta":["czech"],"odvolat":["czech"],"odvracet":["czech"],"odznak":["czech"],"ofina":["czech"],"ofsajd":["czech"],"ohlas":["czech"],"ohnisko":["czech"],"ohrada":["czech"],"ohrozit":["czech"],"ohryzek":["czech"],"okap":["czech"],"okenice":["czech"],"oklika":["czech"],"okno":["czech"],"okouzlit":["czech"],"okovy":["czech"],"okrasa":["czech"],"okres":["czech"],"okrsek":["czech"],"okruh":["czech"],"okupant":["czech"],"okurka":["czech"],"okusit":["czech"],"olejnina":["czech"],"olizovat":["czech"],"omak":["czech"],"omeleta":["czech"],"omezit":["czech"],"omladina":["czech"],"omlouvat":["czech"],"omluva":["czech"],"omyl":["czech"],"onehdy":["czech"],"opakovat":["czech"],"opasek":["czech"],"operace":["czech"],"opice":["czech"],"opilost":["czech"],"opisovat":["czech"],"opora":["czech"],"opozice":["czech"],"opravdu":["czech"],"oproti":["czech"],"orbital":["czech"],"orchestr":["czech"],"orgie":["czech"],"orlice":["czech"],"orloj":["czech"],"ortel":["czech"],"osada":["czech"],"oschnout":["czech"],"osika":["czech"],"osivo":["czech"],"oslava":["czech"],"oslepit":["czech"],"oslnit":["czech"],"oslovit":["czech"],"osnova":["czech"],"osoba":["czech"],"osolit":["czech"],"ospalec":["czech"],"osten":["czech"],"ostraha":["czech"],"ostuda":["czech"],"ostych":["czech"],"osvojit":["czech"],"oteplit":["czech"],"otisk":["czech"],"otop":["czech"],"otrhat":["czech"],"otrlost":["czech"],"otrok":["czech"],"otruby":["czech"],"otvor":["czech"],"ovanout":["czech"],"ovar":["czech"],"oves":["czech"],"ovlivnit":["czech"],"ovoce":["czech"],"oxid":["czech"],"ozdoba":["czech"],"pachatel":["czech"],"pacient":["czech"],"padouch":["czech"],"pahorek":["czech"],"pakt":["czech"],"palanda":["czech"],"palec":["czech"],"palivo":["czech"],"paluba":["czech"],"pamflet":["czech"],"pamlsek":["czech"],"panenka":["czech"],"panika":["czech"],"panna":["czech"],"panovat":["czech"],"panstvo":["czech"],"pantofle":["czech"],"paprika":["czech"],"parketa":["czech"],"parodie":["czech"],"parta":["czech"],"paruka":["czech"],"paryba":["czech"],"paseka":["czech"],"pasivita":["czech"],"pastelka":["czech"],"patent":["czech"],"patrona":["czech"],"pavouk":["czech"],"pazneht":["czech"],"pazourek":["czech"],"pecka":["czech"],"pedagog":["czech"],"pejsek":["czech"],"peklo":["czech"],"peloton":["czech"],"penalta":["czech"],"pendrek":["czech"],"penze":["czech"],"periskop":["czech"],"pero":["czech"],"pestrost":["czech"],"petarda":["czech"],"petice":["czech"],"petrolej":["czech"],"pevnina":["czech"],"pexeso":["czech"],"pianista":["czech"],"piha":["czech"],"pijavice":["czech"],"pikle":["czech"],"piknik":["czech","turkish"],"pilina":["czech"],"pilnost":["czech"],"pilulka":["czech"],"pinzeta":["czech"],"pipeta":["czech"],"pisatel":["czech"],"pistole":["czech"],"pitevna":["czech"],"pivnice":["czech"],"pivovar":["czech"],"placenta":["czech"],"plakat":["czech"],"plamen":["czech"],"planeta":["czech"],"plastika":["czech"],"platit":["czech"],"plavidlo":["czech"],"plaz":["czech"],"plech":["czech"],"plemeno":["czech"],"plenta":["czech"],"ples":["czech"],"pletivo":["czech"],"plevel":["czech"],"plivat":["czech"],"plnit":["czech"],"plno":["czech"],"plocha":["czech"],"plodina":["czech"],"plomba":["czech"],"plout":["czech"],"pluk":["czech"],"plyn":["czech"],"pobavit":["czech"],"pobyt":["czech"],"pochod":["czech"],"pocit":["czech"],"poctivec":["czech"],"podat":["czech"],"podcenit":["czech"],"podepsat":["czech"],"podhled":["czech"],"podivit":["czech"],"podklad":["czech"],"podmanit":["czech"],"podnik":["czech"],"podoba":["czech"],"podpora":["czech"],"podraz":["czech"],"podstata":["czech"],"podvod":["czech"],"podzim":["czech"],"poezie":["czech"],"pohanka":["czech"],"pohnutka":["czech"],"pohovor":["czech"],"pohroma":["czech"],"pohyb":["czech"],"pointa":["czech"],"pojistka":["czech"],"pojmout":["czech"],"pokazit":["czech"],"pokles":["czech"],"pokoj":["czech"],"pokrok":["czech"],"pokuta":["czech"],"pokyn":["czech"],"poledne":["czech"],"polibek":["czech"],"polknout":["czech"],"poloha":["czech"],"polynom":["czech"],"pomalu":["czech"],"pominout":["czech"],"pomlka":["czech"],"pomoc":["czech"],"pomsta":["czech"],"pomyslet":["czech"],"ponechat":["czech"],"ponorka":["czech"],"ponurost":["czech"],"popadat":["czech"],"popel":["czech"],"popisek":["czech"],"poplach":["czech"],"poprosit":["czech"],"popsat":["czech"],"popud":["czech"],"poradce":["czech"],"porce":["czech"],"porod":["czech"],"porucha":["czech"],"poryv":["czech"],"posadit":["czech"],"posed":["czech"],"posila":["czech"],"poskok":["czech"],"poslanec":["czech"],"posoudit":["czech"],"pospolu":["czech"],"postava":["czech"],"posudek":["czech"],"posyp":["czech"],"potah":["czech"],"potkan":["czech"],"potlesk":["czech"],"potomek":["czech"],"potrava":["czech"],"potupa":["czech"],"potvora":["czech"],"poukaz":["czech"],"pouto":["czech"],"pouzdro":["czech"],"povaha":["czech"],"povidla":["czech"],"povlak":["czech"],"povoz":["czech"],"povrch":["czech"],"povstat":["czech"],"povyk":["czech"],"povzdech":["czech"],"pozdrav":["czech"],"pozemek":["czech"],"poznatek":["czech"],"pozor":["czech"],"pozvat":["czech"],"pracovat":["czech"],"prahory":["czech"],"praktika":["czech"],"prales":["czech"],"praotec":["czech"],"praporek":["czech"],"prase":["czech"],"pravda":["czech"],"princip":["czech"],"prkno":["czech"],"probudit":["czech"],"procento":["czech"],"prodej":["czech"],"profese":["czech"],"prohra":["czech"],"projekt":["czech"],"prolomit":["czech"],"promile":["czech"],"pronikat":["czech"],"propad":["czech"],"prorok":["czech"],"prosba":["czech"],"proton":["czech"],"proutek":["czech"],"provaz":["czech"],"prskavka":["czech"],"prsten":["czech"],"prudkost":["czech"],"prut":["czech"],"prvek":["czech"],"prvohory":["czech"],"psanec":["czech"],"psovod":["czech"],"pstruh":["czech"],"ptactvo":["czech"],"puberta":["czech"],"puch":["czech"],"pudl":["czech"],"pukavec":["czech"],"puklina":["czech"],"pukrle":["czech"],"pult":["czech"],"pumpa":["czech"],"punc":["czech"],"pupen":["czech"],"pusa":["czech"],"pusinka":["czech"],"pustina":["czech"],"putovat":["czech"],"putyka":["czech"],"pyramida":["czech"],"pysk":["czech"],"pytel":["czech"],"racek":["czech"],"rachot":["czech"],"radiace":["czech"],"radnice":["czech"],"radon":["czech"],"raft":["czech"],"ragby":["czech"],"raketa":["czech"],"rakovina":["czech"],"rameno":["czech"],"rampouch":["czech"],"rande":["czech"],"rarach":["czech"],"rarita":["czech"],"rasovna":["czech"],"rastr":["czech"],"ratolest":["czech"],"razance":["czech"],"razidlo":["czech"],"reagovat":["czech"],"reakce":["czech"],"recept":["czech"],"redaktor":["czech"],"referent":["czech"],"reflex":["czech"],"rejnok":["czech"],"reklama":["czech"],"rekord":["czech"],"rekrut":["czech"],"rektor":["czech"],"reputace":["czech"],"revize":["czech","turkish"],"revma":["czech"],"revolver":["czech"],"rezerva":["czech"],"riskovat":["czech"],"riziko":["czech"],"robotika":["czech"],"rodokmen":["czech"],"rohovka":["czech"],"rokle":["czech"],"rokoko":["czech"],"romaneto":["czech"],"ropovod":["czech"],"ropucha":["czech"],"rorejs":["czech"],"rosol":["czech"],"rostlina":["czech"],"rotmistr":["czech"],"rotoped":["czech"],"rotunda":["czech"],"roubenka":["czech"],"roucho":["czech"],"roup":["czech"],"roura":["czech"],"rovina":["czech"],"rovnice":["czech"],"rozbor":["czech"],"rozchod":["czech"],"rozdat":["czech"],"rozeznat":["czech"],"rozhodce":["czech"],"rozinka":["czech"],"rozjezd":["czech"],"rozkaz":["czech"],"rozloha":["czech"],"rozmar":["czech"],"rozpad":["czech"],"rozruch":["czech"],"rozsah":["czech"],"roztok":["czech"],"rozum":["czech"],"rozvod":["czech"],"rubrika":["czech"],"ruchadlo":["czech"],"rukavice":["czech"],"rukopis":["czech"],"ryba":["czech"],"rybolov":["czech"],"rychlost":["czech"],"rydlo":["czech"],"rypadlo":["czech"],"rytina":["czech"],"ryzost":["czech"],"sadista":["czech"],"sahat":["czech"],"sako":["czech"],"samec":["czech"],"samizdat":["czech"],"samota":["czech"],"sanitka":["czech"],"sardinka":["czech"],"sasanka":["czech"],"satelit":["czech"],"sazba":["czech"],"sazenice":["czech"],"sbor":["czech"],"schovat":["czech"],"sebranka":["czech"],"secese":["czech"],"sedadlo":["czech"],"sediment":["czech"],"sedlo":["czech"],"sehnat":["czech"],"sejmout":["czech"],"sekera":["czech"],"sekta":["czech"],"sekunda":["czech"],"sekvoje":["czech"],"semeno":["czech"],"seno":["czech"],"servis":["czech","turkish"],"sesadit":["czech"],"seshora":["czech"],"seskok":["czech"],"seslat":["czech"],"sestra":["czech"],"sesuv":["czech"],"sesypat":["czech"],"setba":["czech"],"setina":["czech"],"setkat":["czech"],"setnout":["czech"],"setrvat":["czech"],"sever":["czech"],"seznam":["czech"],"shoda":["czech"],"shrnout":["czech"],"sifon":["czech"],"silnice":["czech"],"sirka":["czech"],"sirotek":["czech"],"sirup":["czech"],"situace":["czech"],"skafandr":["czech"],"skalisko":["czech"],"skanzen":["czech"],"skaut":["czech"],"skeptik":["czech"],"skica":["czech"],"skladba":["czech"],"sklenice":["czech"],"sklo":["czech"],"skluz":["czech"],"skoba":["czech"],"skokan":["czech"],"skoro":["czech"],"skripta":["czech"],"skrz":["czech"],"skupina":["czech"],"skvost":["czech"],"skvrna":["czech"],"slabika":["czech"],"sladidlo":["czech"],"slanina":["czech"],"slast":["czech"],"slavnost":["czech"],"sledovat":["czech"],"slepec":["czech"],"sleva":["czech"],"slezina":["czech"],"slib":["czech"],"slina":["czech"],"sliznice":["czech"],"slon":["czech"],"sloupek":["czech"],"slovo":["czech"],"sluch":["czech"],"sluha":["czech"],"slunce":["czech"],"slupka":["czech"],"slza":["czech"],"smaragd":["czech"],"smetana":["czech"],"smilstvo":["czech"],"smlouva":["czech"],"smog":["czech"],"smrad":["czech"],"smrk":["czech"],"smrtka":["czech"],"smutek":["czech"],"smysl":["czech"],"snad":["czech"],"snaha":["czech"],"snob":["czech"],"sobota":["czech"],"socha":["czech"],"sodovka":["czech"],"sokol":["czech"],"sopka":["czech"],"sotva":["czech"],"souboj":["czech"],"soucit":["czech"],"soudce":["czech"],"souhlas":["czech"],"soulad":["czech"],"soumrak":["czech"],"souprava":["czech"],"soused":["czech"],"soutok":["czech"],"souviset":["czech"],"spalovna":["czech"],"spasitel":["czech"],"spis":["czech"],"splav":["czech"],"spodek":["czech"],"spojenec":["czech"],"spolu":["czech"],"sponzor":["czech"],"spornost":["czech"],"spousta":["czech"],"sprcha":["czech"],"spustit":["czech"],"sranda":["czech"],"sraz":["czech"],"srdce":["czech"],"srna":["czech"],"srnec":["czech"],"srovnat":["czech"],"srpen":["czech"],"srst":["czech"],"srub":["czech"],"stanice":["czech"],"starosta":["czech"],"statika":["czech"],"stavba":["czech"],"stehno":["czech"],"stezka":["czech"],"stodola":["czech"],"stolek":["czech"],"stopa":["czech"],"storno":["czech"],"stoupat":["czech"],"strach":["czech"],"stres":["czech"],"strhnout":["czech"],"strom":["czech"],"struna":["czech"],"studna":["czech"],"stupnice":["czech"],"stvol":["czech"],"styk":["czech"],"subjekt":["czech"],"subtropy":["czech"],"suchar":["czech"],"sudost":["czech"],"sukno":["czech"],"sundat":["czech"],"sunout":["czech"],"surikata":["czech"],"surovina":["czech"],"svah":["czech"],"svalstvo":["czech"],"svetr":["czech"],"svatba":["czech"],"svazek":["czech"],"svisle":["czech"],"svitek":["czech"],"svoboda":["czech"],"svodidlo":["czech"],"svorka":["czech"],"svrab":["czech"],"sykavka":["czech"],"sykot":["czech"],"synek":["czech"],"synovec":["czech"],"sypat":["czech"],"sypkost":["czech"],"syrovost":["czech"],"sysel":["czech"],"sytost":["czech"],"tabletka":["czech"],"tabule":["czech"],"tahoun":["czech"],"tajemno":["czech"],"tajfun":["czech"],"tajga":["czech"],"tajit":["czech"],"tajnost":["czech"],"taktika":["czech"],"tamhle":["czech"],"tampon":["czech","turkish"],"tancovat":["czech"],"tanec":["czech"],"tanker":["czech"],"tapeta":["czech"],"tavenina":["czech"],"tazatel":["czech"],"technika":["czech"],"tehdy":["czech"],"tekutina":["czech"],"telefon":["czech"],"temnota":["czech"],"tendence":["czech"],"tenista":["czech"],"tenor":["czech"],"teplota":["czech"],"tepna":["czech"],"teprve":["czech"],"terapie":["czech"],"termoska":["czech"],"textil":["czech"],"ticho":["czech"],"tiskopis":["czech"],"titulek":["czech"],"tkadlec":["czech"],"tkanina":["czech"],"tlapka":["czech"],"tleskat":["czech"],"tlukot":["czech"],"tlupa":["czech"],"tmel":["czech"],"toaleta":["czech"],"topinka":["czech"],"topol":["czech"],"torzo":["czech"],"touha":["czech"],"toulec":["czech"],"tradice":["czech"],"traktor":["czech"],"tramp":["czech"],"trasa":["czech"],"traverza":["czech"],"trefit":["czech"],"trest":["czech"],"trezor":["czech"],"trhavina":["czech"],"trhlina":["czech"],"trochu":["czech"],"trojice":["czech"],"troska":["czech"],"trouba":["czech"],"trpce":["czech"],"trpitel":["czech"],"trpkost":["czech"],"trubec":["czech"],"truchlit":["czech"],"truhlice":["czech"],"trus":["czech"],"trvat":["czech"],"tudy":["czech"],"tuhnout":["czech"],"tuhost":["czech"],"tundra":["czech"],"turista":["czech"],"turnaj":["czech"],"tuzemsko":["czech"],"tvaroh":["czech"],"tvorba":["czech"],"tvrdost":["czech"],"tvrz":["czech"],"tygr":["czech"],"tykev":["czech"],"ubohost":["czech"],"uboze":["czech"],"ubrat":["czech"],"ubrousek":["czech"],"ubrus":["czech"],"ubytovna":["czech"],"ucho":["czech"],"uctivost":["czech"],"udivit":["czech"],"uhradit":["czech"],"ujednat":["czech"],"ujistit":["czech"],"ujmout":["czech"],"ukazatel":["czech"],"uklidnit":["czech"],"uklonit":["czech"],"ukotvit":["czech"],"ukrojit":["czech"],"ulice":["czech"],"ulita":["czech"],"ulovit":["czech"],"umyvadlo":["czech"],"unavit":["czech"],"uniforma":["czech"],"uniknout":["czech"],"upadnout":["czech"],"uplatnit":["czech"],"uplynout":["czech"],"upoutat":["czech"],"upravit":["czech"],"uran":["czech"],"urazit":["czech"],"usednout":["czech"],"usilovat":["czech"],"usmrtit":["czech"],"usnadnit":["czech"],"usnout":["czech"],"usoudit":["czech"],"ustlat":["czech"],"ustrnout":["czech"],"utahovat":["czech"],"utkat":["czech"],"utlumit":["czech"],"utonout":["czech"],"utopenec":["czech"],"utrousit":["czech"],"uvalit":["czech"],"uvolnit":["czech"],"uvozovka":["czech"],"uzdravit":["czech"],"uzel":["czech"],"uzenina":["czech"],"uzlina":["czech"],"uznat":["czech"],"vagon":["czech","turkish"],"valcha":["czech"],"valoun":["czech"],"vana":["czech"],"vandal":["czech"],"vanilka":["czech"],"varan":["czech"],"varhany":["czech"],"varovat":["czech"],"vcelku":["czech"],"vchod":["czech"],"vdova":["czech"],"vedro":["czech"],"vegetace":["czech"],"vejce":["czech"],"velbloud":["czech"],"veletrh":["czech"],"velitel":["czech"],"velmoc":["czech"],"velryba":["czech"],"venkov":["czech"],"veranda":["czech"],"verze":["czech"],"veselka":["czech"],"veskrze":["czech"],"vesnice":["czech"],"vespodu":["czech"],"vesta":["czech"],"veterina":["czech"],"veverka":["czech"],"vibrace":["czech"],"vichr":["czech"],"videohra":["czech"],"vidina":["czech"],"vidle":["czech"],"vila":["czech"],"vinice":["czech"],"viset":["czech"],"vitalita":["czech"],"vize":["czech"],"vizitka":["czech"],"vjezd":["czech"],"vklad":["czech"],"vkus":["czech"],"vlajka":["czech"],"vlak":["czech"],"vlasec":["czech"],"vlevo":["czech"],"vlhkost":["czech"],"vliv":["czech"],"vlnovka":["czech"],"vloupat":["czech"],"vnucovat":["czech"],"vnuk":["czech"],"voda":["czech"],"vodivost":["czech"],"vodoznak":["czech"],"vodstvo":["czech"],"vojensky":["czech"],"vojna":["czech"],"vojsko":["czech"],"volant":["czech"],"volba":["czech"],"volit":["czech"],"volno":["czech"],"voskovka":["czech"],"vozidlo":["czech"],"vozovna":["czech"],"vpravo":["czech"],"vrabec":["czech"],"vracet":["czech"],"vrah":["czech"],"vrata":["czech"],"vrba":["czech"],"vrcholek":["czech"],"vrhat":["czech"],"vrstva":["czech"],"vrtule":["czech"],"vsadit":["czech"],"vstoupit":["czech"],"vstup":["czech"],"vtip":["czech"],"vybavit":["czech"],"vybrat":["czech"],"vychovat":["czech"],"vydat":["czech"],"vydra":["czech"],"vyfotit":["czech"],"vyhledat":["czech"],"vyhnout":["czech"],"vyhodit":["czech"],"vyhradit":["czech"],"vyhubit":["czech"],"vyjasnit":["czech"],"vyjet":["czech"],"vyjmout":["czech"],"vyklopit":["czech"],"vykonat":["czech"],"vylekat":["czech"],"vymazat":["czech"],"vymezit":["czech"],"vymizet":["czech"],"vymyslet":["czech"],"vynechat":["czech"],"vynikat":["czech"],"vynutit":["czech"],"vypadat":["czech"],"vyplatit":["czech"],"vypravit":["czech"],"vypustit":["czech"],"vyrazit":["czech"],"vyrovnat":["czech"],"vyrvat":["czech"],"vyslovit":["czech"],"vysoko":["czech"],"vystavit":["czech"],"vysunout":["czech"],"vysypat":["czech"],"vytasit":["czech"],"vytesat":["czech"],"vytratit":["czech"],"vyvinout":["czech"],"vyvolat":["czech"],"vyvrhel":["czech"],"vyzdobit":["czech"],"vyznat":["czech"],"vzadu":["czech"],"vzbudit":["czech"],"vzchopit":["czech"],"vzdor":["czech"],"vzduch":["czech"],"vzdychat":["czech"],"vzestup":["czech"],"vzhledem":["czech"],"vzkaz":["czech"],"vzlykat":["czech"],"vznik":["czech"],"vzorek":["czech"],"vzpoura":["czech"],"vztah":["czech"],"vztek":["czech"],"xylofon":["czech"],"zabrat":["czech"],"zabydlet":["czech"],"zachovat":["czech"],"zadarmo":["czech"],"zadusit":["czech"],"zafoukat":["czech"],"zahltit":["czech"],"zahodit":["czech"],"zahrada":["czech"],"zahynout":["czech"],"zajatec":["czech"],"zajet":["czech"],"zajistit":["czech"],"zaklepat":["czech"],"zakoupit":["czech"],"zalepit":["czech"],"zamezit":["czech"],"zamotat":["czech"],"zamyslet":["czech"],"zanechat":["czech"],"zanikat":["czech"],"zaplatit":["czech"],"zapojit":["czech"],"zapsat":["czech"],"zarazit":["czech"],"zastavit":["czech"],"zasunout":["czech"],"zatajit":["czech"],"zatemnit":["czech"],"zatknout":["czech"],"zaujmout":["czech"],"zavalit":["czech"],"zavelet":["czech"],"zavinit":["czech"],"zavolat":["czech"],"zavrtat":["czech"],"zazvonit":["czech"],"zbavit":["czech"],"zbrusu":["czech"],"zbudovat":["czech"],"zbytek":["czech"],"zdaleka":["czech"],"zdarma":["czech"],"zdatnost":["czech"],"zdivo":["czech"],"zdobit":["czech"],"zdroj":["czech"],"zdvih":["czech"],"zdymadlo":["czech"],"zelenina":["czech"],"zeman":["czech"],"zemina":["czech"],"zeptat":["czech"],"zezadu":["czech"],"zezdola":["czech"],"zhatit":["czech"],"zhltnout":["czech"],"zhluboka":["czech"],"zhotovit":["czech"],"zhruba":["czech"],"zima":["czech"],"zimnice":["czech"],"zjemnit":["czech"],"zklamat":["czech"],"zkoumat":["czech"],"zkratka":["czech"],"zkumavka":["czech"],"zlato":["czech"],"zlehka":["czech"],"zloba":["czech"],"zlom":["czech"],"zlost":["czech"],"zlozvyk":["czech"],"zmapovat":["czech"],"zmar":["czech"],"zmatek":["czech"],"zmije":["czech"],"zmizet":["czech"],"zmocnit":["czech"],"zmodrat":["czech"],"zmrzlina":["czech"],"zmutovat":["czech"],"znak":["czech"],"znalost":["czech"],"znamenat":["czech"],"znovu":["czech"],"zobrazit":["czech"],"zotavit":["czech"],"zoubek":["czech"],"zoufale":["czech"],"zplodit":["czech"],"zpomalit":["czech"],"zprava":["czech"],"zprostit":["czech"],"zprudka":["czech"],"zprvu":["czech"],"zrada":["czech"],"zranit":["czech"],"zrcadlo":["czech"],"zrnitost":["czech"],"zrno":["czech"],"zrovna":["czech"],"zrychlit":["czech"],"zrzavost":["czech"],"zticha":["czech"],"ztratit":["czech"],"zubovina":["czech"],"zubr":["czech"],"zvednout":["czech"],"zvenku":["czech"],"zvesela":["czech"],"zvon":["czech"],"zvrat":["czech"],"zvukovod":["czech"],"zvyk":["czech"],"abandon":["english","french"],"ability":["english"],"able":["english"],"about":["english"],"above":["english"],"absent":["english"],"absorb":["english"],"abstract":["english"],"absurd":["english"],"abuse":["english"],"access":["english"],"accident":["english"],"account":["english"],"accuse":["english"],"achieve":["english"],"acid":["english"],"acoustic":["english"],"acquire":["english"],"across":["english"],"act":["english"],"action":["english"],"actor":["english"],"actress":["english"],"actual":["english"],"adapt":["english"],"add":["english"],"addict":["english"],"address":["english"],"adjust":["english"],"admit":["english"],"adult":["english"],"advance":["english"],"advice":["english"],"aerobic":["english"],"affair":["english"],"afford":["english"],"afraid":["english"],"again":["english"],"age":["english"],"agent":["english"],"agree":["english"],"ahead":["english"],"aim":["english"],"air":["english"],"airport":["english"],"aisle":["english"],"alarm":["english"],"album":["english"],"alcohol":["english"],"alert":["english"],"alien":["english"],"all":["english"],"alley":["english"],"allow":["english"],"almost":["english"],"alone":["english"],"alpha":["english"],"already":["english"],"also":["english"],"alter":["english"],"always":["english"],"amateur":["english","french"],"amazing":["english"],"among":["english"],"amount":["english"],"amused":["english"],"analyst":["english"],"anchor":["english"],"ancient":["english"],"anger":["english"],"angle":["english","french"],"angry":["english"],"animal":["english","french"],"ankle":["english"],"announce":["english"],"annual":["english"],"another":["english"],"answer":["english"],"antenna":["english"],"antique":["english"],"anxiety":["english"],"any":["english"],"apart":["english"],"apology":["english"],"appear":["english"],"apple":["english"],"approve":["english"],"april":["english"],"arch":["english"],"arctic":["english"],"area":["english"],"arena":["english","turkish"],"argue":["english"],"arm":["english"],"armed":["english"],"armor":["english"],"army":["english"],"around":["english"],"arrange":["english"],"arrest":["english"],"arrive":["english"],"arrow":["english"],"art":["english"],"artefact":["english"],"artist":["english","turkish"],"artwork":["english"],"ask":["english"],"aspect":["english","french"],"assault":["english"],"asset":["english"],"assist":["english"],"assume":["english"],"asthma":["english"],"athlete":["english"],"atom":["english","turkish"],"attack":["english"],"attend":["english"],"attitude":["english"],"attract":["english"],"auction":["english"],"audit":["english"],"august":["english"],"aunt":["english"],"author":["english"],"auto":["english"],"autumn":["english"],"average":["english"],"avocado":["english"],"avoid":["english"],"awake":["english"],"aware":["english"],"away":["english"],"awesome":["english"],"awful":["english"],"awkward":["english"],"axis":["english"],"baby":["english"],"bachelor":["english"],"bacon":["english"],"badge":["english","french"],"bag":["english"],"balance":["english"],"balcony":["english"],"ball":["english"],"bamboo":["english"],"banana":["english"],"banner":["english"],"bar":["english"],"barely":["english"],"bargain":["english"],"barrel":["english"],"base":["english"],"basic":["english"],"basket":["english"],"battle":["english"],"beach":["english"],"bean":["english"],"beauty":["english"],"because":["english"],"become":["english"],"beef":["english"],"before":["english"],"begin":["english"],"behave":["english"],"behind":["english"],"believe":["english"],"below":["english"],"belt":["english"],"bench":["english"],"benefit":["english"],"best":["english"],"betray":["english"],"better":["english"],"between":["english"],"beyond":["english"],"bicycle":["english","french"],"bid":["english"],"bike":["english"],"bind":["english"],"biology":["english"],"bird":["english"],"birth":["english"],"bitter":["english"],"black":["english"],"blade":["english"],"blame":["english"],"blanket":["english"],"blast":["english"],"bleak":["english"],"bless":["english"],"blind":["english"],"blood":["english"],"blossom":["english"],"blouse":["english"],"blue":["english"],"blur":["english"],"blush":["english"],"board":["english"],"boat":["english"],"body":["english"],"boil":["english"],"bomb":["english"],"bone":["english"],"bonus":["english","french"],"book":["english"],"boost":["english"],"border":["english"],"boring":["english"],"borrow":["english"],"boss":["english"],"bottom":["english"],"bounce":["english"],"box":["english"],"boy":["english"],"bracket":["english"],"brain":["english"],"brand":["english"],"brass":["english"],"brave":["english","french"],"bread":["english"],"breeze":["english"],"brick":["english"],"bridge":["english"],"brief":["english"],"bright":["english"],"bring":["english"],"brisk":["english"],"broccoli":["english"],"broken":["english"],"bronze":["english"],"broom":["english"],"brother":["english"],"brown":["english"],"brush":["english"],"bubble":["english"],"buddy":["english"],"budget":["english"],"buffalo":["english"],"build":["english"],"bulb":["english"],"bulk":["english"],"bullet":["english"],"bundle":["english"],"bunker":["english"],"burden":["english"],"burger":["english"],"burst":["english"],"bus":["english"],"business":["english"],"busy":["english"],"butter":["english"],"buyer":["english"],"buzz":["english"],"cabbage":["english"],"cabin":["english"],"cable":["english"],"cactus":["english"],"cage":["english"],"cake":["english"],"call":["english"],"calm":["english"],"camera":["english"],"camp":["english"],"can":["english"],"canal":["english","french"],"cancel":["english"],"candy":["english"],"cannon":["english"],"canoe":["english"],"canvas":["english"],"canyon":["english"],"capable":["english","french"],"capital":["english"],"captain":["english"],"car":["english"],"carbon":["english"],"card":["english"],"cargo":["english"],"carpet":["english"],"carry":["english"],"cart":["english"],"case":["english"],"cash":["english"],"casino":["english"],"castle":["english"],"casual":["english"],"cat":["english"],"catalog":["english"],"catch":["english"],"category":["english"],"cattle":["english"],"caught":["english"],"cause":["english"],"caution":["english","french"],"cave":["english"],"ceiling":["english"],"celery":["english"],"cement":["english"],"census":["english"],"century":["english"],"cereal":["english"],"certain":["english"],"chair":["english"],"chalk":["english"],"champion":["english"],"change":["english"],"chaos":["english"],"chapter":["english"],"charge":["english"],"chase":["english"],"chat":["english"],"cheap":["english"],"check":["english"],"cheese":["english"],"chef":["english"],"cherry":["english"],"chest":["english"],"chicken":["english"],"chief":["english"],"child":["english"],"chimney":["english"],"choice":["english"],"choose":["english"],"chronic":["english"],"chuckle":["english"],"chunk":["english"],"churn":["english"],"cigar":["english"],"cinnamon":["english"],"circle":["english"],"citizen":["english"],"city":["english"],"civil":["english","french"],"claim":["english"],"clap":["english"],"clarify":["english"],"claw":["english"],"clay":["english"],"clean":["english"],"clerk":["english"],"clever":["english"],"click":["english"],"client":["english","french"],"cliff":["english"],"climb":["english"],"clinic":["english"],"clip":["english"],"clock":["english"],"clog":["english"],"close":["english"],"cloth":["english"],"cloud":["english"],"clown":["english"],"club":["english"],"clump":["english"],"cluster":["english"],"clutch":["english"],"coach":["english"],"coast":["english"],"coconut":["english"],"code":["english"],"coffee":["english"],"coil":["english"],"coin":["english"],"collect":["english"],"color":["english"],"column":["english"],"combine":["english"],"come":["english"],"comfort":["english"],"comic":["english"],"common":["english"],"company":["english"],"concert":["english","french"],"conduct":["english"],"confirm":["english"],"congress":["english"],"connect":["english"],"consider":["english"],"control":["english"],"convince":["english"],"cook":["english"],"cool":["english"],"copper":["english"],"copy":["english"],"coral":["english"],"core":["english"],"corn":["english"],"correct":["english","french"],"cost":["english"],"cotton":["english"],"couch":["english"],"country":["english"],"couple":["english"],"course":["english"],"cousin":["english"],"cover":["english"],"coyote":["english","french"],"crack":["english"],"cradle":["english"],"craft":["english"],"cram":["english"],"crane":["english"],"crash":["english"],"crater":["english"],"crawl":["english"],"crazy":["english"],"cream":["english"],"credit":["english"],"creek":["english"],"crew":["english"],"cricket":["english"],"crime":["english"],"crisp":["english"],"critic":["english"],"crop":["english"],"cross":["english"],"crouch":["english"],"crowd":["english"],"crucial":["english","french"],"cruel":["english","french"],"cruise":["english"],"crumble":["english"],"crunch":["english"],"crush":["english"],"cry":["english"],"crystal":["english"],"cube":["english"],"culture":["english"],"cup":["english"],"cupboard":["english"],"curious":["english"],"current":["english"],"curtain":["english"],"curve":["english"],"cushion":["english"],"custom":["english"],"cute":["english"],"cycle":["english","french"],"dad":["english"],"damage":["english"],"damp":["english"],"dance":["english"],"danger":["english","french"],"daring":["english"],"dash":["english"],"daughter":["english"],"dawn":["english"],"day":["english"],"deal":["english"],"debate":["english"],"debris":["english"],"decade":["english"],"december":["english"],"decide":["english"],"decline":["english"],"decorate":["english"],"decrease":["english"],"deer":["english"],"defense":["english"],"define":["english"],"defy":["english"],"degree":["english"],"delay":["english"],"deliver":["english"],"demand":["english"],"demise":["english"],"denial":["english"],"dentist":["english"],"deny":["english"],"depart":["english"],"depend":["english"],"deposit":["english"],"depth":["english"],"deputy":["english"],"derive":["english"],"describe":["english"],"desert":["english"],"design":["english"],"desk":["english"],"despair":["english"],"destroy":["english"],"detail":["english"],"detect":["english"],"develop":["english"],"device":["english"],"devote":["english"],"diagram":["english"],"dial":["english"],"diamond":["english"],"diary":["english"],"dice":["english"],"diesel":["english"],"diet":["english"],"differ":["english"],"digital":["english","french"],"dignity":["english"],"dilemma":["english"],"dinner":["english"],"dinosaur":["english"],"direct":["english"],"dirt":["english"],"disagree":["english"],"discover":["english"],"disease":["english"],"dish":["english"],"dismiss":["english"],"disorder":["english"],"display":["english"],"distance":["english","french"],"divert":["english"],"divide":["english"],"divorce":["english"],"dizzy":["english"],"doctor":["english"],"document":["english"],"dog":["english"],"doll":["english"],"dolphin":["english"],"domain":["english"],"donate":["english"],"donkey":["english"],"donor":["english"],"door":["english"],"dose":["english"],"double":["english","french"],"dove":["english"],"draft":["english"],"dragon":["english","french"],"drama":["english"],"drastic":["english"],"draw":["english"],"dream":["english"],"dress":["english"],"drift":["english"],"drill":["english"],"drink":["english"],"drip":["english"],"drive":["english"],"drop":["english"],"drum":["english"],"dry":["english"],"duck":["english"],"dumb":["english"],"dune":["english"],"during":["english"],"dust":["english"],"dutch":["english"],"duty":["english"],"dwarf":["english"],"dynamic":["english"],"eager":["english"],"eagle":["english"],"early":["english"],"earn":["english"],"earth":["english"],"easily":["english"],"east":["english"],"easy":["english"],"echo":["english"],"ecology":["english"],"economy":["english"],"edge":["english"],"edit":["english"],"educate":["english"],"effort":["english","french"],"egg":["english"],"eight":["english"],"either":["english"],"elbow":["english"],"elder":["english"],"electric":["english"],"elegant":["english"],"element":["english"],"elephant":["english"],"elevator":["english"],"elite":["english"],"else":["english"],"embark":["english"],"embody":["english"],"embrace":["english"],"emerge":["english"],"emotion":["english"],"employ":["english"],"empower":["english"],"empty":["english"],"enable":["english"],"enact":["english"],"end":["english"],"endless":["english"],"endorse":["english"],"enemy":["english"],"energy":["english"],"enforce":["english"],"engage":["english"],"engine":["english"],"enhance":["english"],"enjoy":["english"],"enlist":["english"],"enough":["english"],"enrich":["english"],"enroll":["english"],"ensure":["english"],"enter":["english"],"entire":["english"],"entry":["english"],"envelope":["english"],"episode":["english"],"equal":["english"],"equip":["english"],"era":["english"],"erase":["english"],"erode":["english"],"erosion":["english"],"error":["english"],"erupt":["english"],"escape":["english"],"essay":["english"],"essence":["english","french"],"estate":["english"],"eternal":["english"],"ethics":["english"],"evidence":["english"],"evil":["english"],"evoke":["english"],"evolve":["english"],"exact":["english","french"],"example":["english"],"excess":["english"],"exchange":["english"],"excite":["english"],"exclude":["english"],"excuse":["english","french"],"execute":["english"],"exercise":["english"],"exhaust":["english"],"exhibit":["english"],"exile":["english"],"exist":["english"],"exit":["english"],"exotic":["english"],"expand":["english"],"expect":["english"],"expire":["english"],"explain":["english"],"expose":["english"],"express":["english"],"extend":["english"],"extra":["english"],"eye":["english"],"eyebrow":["english"],"fabric":["english"],"face":["english"],"faculty":["english"],"fade":["english"],"faint":["english"],"faith":["english"],"fall":["english"],"false":["english"],"fame":["english"],"family":["english"],"famous":["english"],"fan":["english"],"fancy":["english"],"fantasy":["english"],"farm":["english"],"fashion":["english"],"fat":["english"],"fatal":["english","french"],"father":["english"],"fatigue":["english","french"],"fault":["english"],"favorite":["english"],"feature":["english"],"february":["english"],"federal":["english","turkish"],"fee":["english"],"feed":["english"],"feel":["english"],"female":["english"],"fence":["english"],"festival":["english","french","turkish"],"fetch":["english"],"fever":["english"],"few":["english"],"fiber":["english"],"fiction":["english"],"field":["english"],"figure":["english","french"],"file":["english"],"film":["english"],"filter":["english"],"final":["english"],"find":["english"],"fine":["english"],"finger":["english"],"finish":["english"],"fire":["english"],"firm":["english"],"first":["english"],"fiscal":["english"],"fish":["english"],"fit":["english"],"fitness":["english"],"fix":["english"],"flag":["english"],"flame":["english"],"flash":["english"],"flat":["english"],"flavor":["english"],"flee":["english"],"flight":["english"],"flip":["english"],"float":["english"],"flock":["english"],"floor":["english"],"flower":["english"],"fluid":["english"],"flush":["english"],"fly":["english"],"foam":["english"],"focus":["english"],"fog":["english"],"foil":["english"],"fold":["english"],"follow":["english"],"food":["english"],"foot":["english"],"force":["english"],"forest":["english"],"forget":["english"],"fork":["english"],"fortune":["english","french"],"forum":["english"],"forward":["english"],"fossil":["english"],"foster":["english"],"found":["english"],"fox":["english"],"fragile":["english","french"],"frame":["english"],"frequent":["english"],"fresh":["english"],"friend":["english"],"fringe":["english"],"frog":["english"],"front":["english"],"frost":["english"],"frown":["english"],"frozen":["english"],"fruit":["english","french"],"fuel":["english"],"fun":["english"],"funny":["english"],"furnace":["english"],"fury":["english"],"future":["english"],"gadget":["english"],"gain":["english"],"galaxy":["english"],"gallery":["english"],"game":["english"],"gap":["english"],"garage":["english"],"garbage":["english"],"garden":["english"],"garlic":["english"],"garment":["english"],"gas":["english"],"gasp":["english"],"gate":["english"],"gather":["english"],"gauge":["english"],"gaze":["english"],"general":["english"],"genius":["english"],"genre":["english"],"gentle":["english"],"genuine":["english"],"gesture":["english"],"ghost":["english"],"giant":["english"],"gift":["english"],"giggle":["english"],"ginger":["english"],"giraffe":["english"],"girl":["english"],"give":["english"],"glad":["english"],"glance":["english"],"glare":["english"],"glass":["english"],"glide":["english"],"glimpse":["english"],"globe":["english","french"],"gloom":["english"],"glory":["english"],"glove":["english"],"glow":["english"],"glue":["english"],"goat":["english"],"goddess":["english"],"gold":["english"],"good":["english"],"goose":["english"],"gorilla":["english"],"gospel":["english"],"gossip":["english"],"govern":["english"],"gown":["english"],"grab":["english"],"grace":["english"],"grain":["english"],"grant":["english"],"grape":["english"],"grass":["english"],"gravity":["english"],"great":["english"],"green":["english"],"grid":["english"],"grief":["english"],"grit":["english"],"grocery":["english"],"group":["english"],"grow":["english"],"grunt":["english"],"guard":["english"],"guess":["english"],"guide":["english","french"],"guilt":["english"],"guitar":["english"],"gun":["english"],"gym":["english"],"habit":["english"],"hair":["english"],"half":["english"],"hammer":["english"],"hamster":["english"],"hand":["english"],"happy":["english"],"harbor":["english"],"hard":["english"],"harsh":["english"],"harvest":["english"],"hat":["english"],"have":["english"],"hawk":["english"],"hazard":["english"],"head":["english"],"health":["english"],"heart":["english"],"heavy":["english"],"hedgehog":["english"],"height":["english"],"hello":["english"],"helmet":["english"],"help":["english"],"hen":["english"],"hero":["english"],"hidden":["english"],"high":["english"],"hill":["english"],"hint":["english"],"hip":["english"],"hire":["english"],"history":["english"],"hobby":["english"],"hockey":["english"],"hold":["english"],"hole":["english"],"holiday":["english"],"hollow":["english"],"home":["english"],"honey":["english"],"hood":["english"],"hope":["english"],"horn":["english"],"horror":["english"],"horse":["english"],"hospital":["english"],"host":["english"],"hotel":["english"],"hour":["english"],"hover":["english"],"hub":["english"],"huge":["english"],"human":["english"],"humble":["english","french"],"humor":["english"],"hundred":["english"],"hungry":["english"],"hunt":["english"],"hurdle":["english"],"hurry":["english"],"hurt":["english"],"husband":["english"],"hybrid":["english"],"ice":["english"],"icon":["english"],"idea":["english"],"identify":["english"],"idle":["english"],"ignore":["english"],"ill":["english"],"illegal":["english"],"illness":["english"],"image":["english","french"],"imitate":["english"],"immense":["english","french"],"immune":["english"],"impact":["english","french"],"impose":["english"],"improve":["english"],"impulse":["english"],"inch":["english"],"include":["english"],"income":["english"],"increase":["english"],"index":["english"],"indicate":["english"],"indoor":["english"],"industry":["english"],"infant":["english"],"inflict":["english"],"inform":["english"],"inhale":["english"],"inherit":["english"],"initial":["english"],"inject":["english"],"injury":["english"],"inmate":["english"],"inner":["english"],"innocent":["english","french"],"input":["english"],"inquiry":["english"],"insane":["english"],"insect":["english"],"inside":["english"],"inspire":["english"],"install":["english"],"intact":["english","french"],"interest":["english"],"into":["english"],"invest":["english"],"invite":["english"],"involve":["english"],"iron":["english"],"island":["english"],"isolate":["english"],"issue":["english"],"item":["english"],"ivory":["english"],"jacket":["english"],"jaguar":["english","french"],"jar":["english"],"jazz":["english"],"jealous":["english"],"jeans":["english"],"jelly":["english"],"jewel":["english"],"job":["english"],"join":["english"],"joke":["english"],"journey":["english"],"joy":["english"],"judge":["english"],"juice":["english"],"jump":["english"],"jungle":["english"],"junior":["english","french"],"junk":["english"],"just":["english"],"kangaroo":["english"],"keen":["english"],"keep":["english"],"ketchup":["english"],"key":["english"],"kick":["english"],"kid":["english"],"kidney":["english"],"kind":["english"],"kingdom":["english"],"kiss":["english"],"kit":["english"],"kitchen":["english"],"kite":["english"],"kitten":["english"],"kiwi":["english"],"knee":["english"],"knife":["english"],"knock":["english"],"know":["english"],"lab":["english"],"label":["english","french"],"labor":["english"],"ladder":["english"],"lady":["english"],"lake":["english"],"lamp":["english"],"language":["english"],"laptop":["english"],"large":["english"],"later":["english"],"latin":["english"],"laugh":["english"],"laundry":["english"],"lava":["english"],"law":["english"],"lawn":["english"],"lawsuit":["english"],"layer":["english"],"lazy":["english"],"leader":["english"],"leaf":["english"],"learn":["english"],"leave":["english"],"lecture":["english","french"],"left":["english"],"leg":["english"],"legal":["english"],"legend":["english"],"leisure":["english"],"lemon":["english"],"lend":["english"],"length":["english"],"lens":["english"],"leopard":["english"],"lesson":["english"],"letter":["english"],"level":["english"],"liar":["english"],"liberty":["english"],"library":["english"],"license":["english"],"life":["english"],"lift":["english"],"light":["english"],"like":["english"],"limb":["english"],"limit":["english"],"link":["english"],"lion":["english"],"liquid":["english"],"list":["english"],"little":["english"],"live":["english"],"lizard":["english"],"load":["english"],"loan":["english"],"lobster":["english"],"local":["english"],"lock":["english"],"logic":["english"],"lonely":["english"],"long":["english"],"loop":["english"],"lottery":["english"],"loud":["english"],"lounge":["english"],"love":["english"],"loyal":["english","french"],"lucky":["english"],"luggage":["english"],"lumber":["english"],"lunar":["english"],"lunch":["english"],"luxury":["english"],"lyrics":["english"],"machine":["english","french"],"mad":["english"],"magic":["english"],"magnet":["english"],"maid":["english"],"mail":["english"],"main":["english"],"major":["english"],"make":["english"],"mammal":["english"],"man":["english"],"manage":["english"],"mandate":["english"],"mango":["english"],"mansion":["english"],"manual":["english"],"maple":["english"],"marble":["english"],"march":["english"],"margin":["english"],"marine":["english"],"market":["english","turkish"],"marriage":["english"],"mask":["english"],"mass":["english"],"master":["english"],"match":["english"],"material":["english"],"math":["english"],"matrix":["english"],"matter":["english"],"maximum":["english"],"maze":["english"],"meadow":["english"],"mean":["english"],"measure":["english"],"meat":["english"],"mechanic":["english"],"medal":["english"],"media":["english"],"melody":["english"],"melt":["english"],"member":["english"],"memory":["english"],"mention":["english"],"menu":["english"],"mercy":["english"],"merge":["english"],"merit":["english"],"merry":["english"],"mesh":["english"],"message":["english"],"metal":["english"],"method":["english"],"middle":["english"],"midnight":["english"],"milk":["english"],"million":["english","french"],"mimic":["english"],"mind":["english"],"minimum":["english"],"minor":["english"],"minute":["english","french"],"miracle":["english","french"],"mirror":["english"],"misery":["english"],"miss":["english"],"mistake":["english"],"mix":["english"],"mixed":["english"],"mixture":["english"],"mobile":["english","french"],"model":["english","turkish"],"modify":["english"],"mom":["english"],"moment":["english"],"monitor":["english"],"monkey":["english"],"monster":["english"],"month":["english"],"moon":["english"],"moral":["english"],"more":["english"],"morning":["english"],"mosquito":["english"],"mother":["english"],"motion":["english"],"motor":["english","turkish"],"mountain":["english"],"mouse":["english"],"move":["english"],"movie":["english"],"much":["english"],"muffin":["english"],"mule":["english"],"multiply":["english"],"muscle":["english","french"],"museum":["english"],"mushroom":["english"],"music":["english"],"must":["english"],"mutual":["english"],"myself":["english"],"mystery":["english"],"myth":["english"],"naive":["english"],"name":["english"],"napkin":["english"],"narrow":["english"],"nasty":["english"],"nation":["english","french"],"nature":["english","french"],"near":["english"],"neck":["english"],"need":["english"],"negative":["english"],"neglect":["english"],"neither":["english"],"nephew":["english"],"nerve":["english"],"nest":["english"],"net":["english"],"network":["english"],"neutral":["english"],"never":["english"],"news":["english"],"next":["english"],"nice":["english"],"night":["english"],"noble":["english","french"],"noise":["english"],"nominee":["english"],"noodle":["english"],"normal":["english","turkish"],"north":["english"],"nose":["english"],"notable":["english","french"],"note":["english"],"nothing":["english"],"notice":["english"],"novel":["english"],"now":["english"],"nuclear":["english"],"number":["english"],"nurse":["english"],"nut":["english"],"oak":["english"],"obey":["english"],"object":["english"],"oblige":["english"],"obscure":["english"],"observe":["english"],"obtain":["english"],"obvious":["english"],"occur":["english"],"ocean":["english"],"october":["english"],"odor":["english"],"off":["english"],"offer":["english"],"office":["english"],"often":["english"],"oil":["english"],"okay":["english"],"old":["english"],"olive":["english"],"olympic":["english"],"omit":["english"],"once":["english"],"one":["english"],"onion":["english"],"online":["english"],"only":["english"],"open":["english"],"opera":["english","turkish"],"opinion":["english","french"],"oppose":["english"],"option":["english"],"orange":["english","french"],"orbit":["english"],"orchard":["english"],"order":["english"],"ordinary":["english"],"organ":["english"],"orient":["english"],"original":["english"],"orphan":["english"],"ostrich":["english"],"other":["english"],"outdoor":["english"],"outer":["english"],"output":["english"],"outside":["english"],"oval":["english"],"oven":["english"],"over":["english"],"own":["english"],"owner":["english"],"oxygen":["english"],"oyster":["english"],"ozone":["english","french"],"pact":["english"],"paddle":["english"],"page":["english"],"pair":["english"],"palace":["english","french"],"palm":["english"],"panda":["english","french","turkish"],"panel":["english","turkish"],"panic":["english"],"panther":["english"],"paper":["english"],"parade":["english"],"parent":["english"],"park":["english"],"parrot":["english"],"party":["english"],"pass":["english"],"patch":["english"],"path":["english"],"patient":["english"],"patrol":["english"],"pattern":["english"],"pause":["english"],"pave":["english"],"payment":["english"],"peace":["english"],"peanut":["english"],"pear":["english"],"peasant":["english"],"pelican":["english"],"pen":["english"],"penalty":["english"],"pencil":["english"],"people":["english"],"pepper":["english"],"perfect":["english"],"permit":["english"],"person":["english"],"pet":["english"],"phone":["english"],"photo":["english"],"phrase":["english","french"],"physical":["english"],"piano":["english","french"],"picnic":["english"],"picture":["english"],"piece":["english"],"pig":["english"],"pigeon":["english"],"pill":["english"],"pilot":["english","turkish"],"pink":["english"],"pioneer":["english"],"pipe":["english"],"pistol":["english"],"pitch":["english"],"pizza":["english","french"],"place":["english"],"planet":["english"],"plastic":["english"],"plate":["english"],"play":["english"],"please":["english"],"pledge":["english"],"pluck":["english"],"plug":["english"],"plunge":["english"],"poem":["english"],"poet":["english"],"point":["english"],"polar":["english"],"pole":["english"],"police":["english"],"pond":["english"],"pony":["english"],"pool":["english"],"popular":["english"],"portion":["english"],"position":["english","french"],"possible":["english"],"post":["english"],"potato":["english"],"pottery":["english"],"poverty":["english"],"powder":["english"],"power":["english"],"practice":["english"],"praise":["english"],"predict":["english"],"prefer":["english"],"prepare":["english"],"present":["english"],"pretty":["english"],"prevent":["english"],"price":["english"],"pride":["english"],"primary":["english"],"print":["english"],"priority":["english"],"prison":["english","french"],"private":["english"],"prize":["english"],"problem":["english","turkish"],"process":["english"],"produce":["english"],"profit":["english"],"program":["english","turkish"],"project":["english"],"promote":["english"],"proof":["english"],"property":["english"],"prosper":["english"],"protect":["english"],"proud":["english"],"provide":["english"],"public":["english","french"],"pudding":["english"],"pull":["english"],"pulp":["english"],"pulse":["english"],"pumpkin":["english"],"punch":["english"],"pupil":["english"],"puppy":["english"],"purchase":["english"],"purity":["english"],"purpose":["english"],"purse":["english"],"push":["english"],"put":["english"],"puzzle":["english","french"],"pyramid":["english"],"quality":["english"],"quantum":["english"],"quarter":["english"],"question":["english","french"],"quick":["english"],"quit":["english"],"quiz":["english"],"quote":["english"],"rabbit":["english"],"raccoon":["english"],"race":["english"],"rack":["english"],"radar":["english","turkish"],"radio":["english"],"rail":["english"],"rain":["english"],"raise":["english"],"rally":["english"],"ramp":["english"],"ranch":["english"],"random":["english"],"range":["english"],"rapid":["english"],"rare":["english"],"rate":["english"],"rather":["english"],"raven":["english"],"raw":["english"],"razor":["english"],"ready":["english"],"real":["english"],"reason":["english"],"rebel":["english"],"rebuild":["english"],"recall":["english"],"receive":["english"],"recipe":["english"],"record":["english"],"recycle":["english"],"reduce":["english"],"reflect":["english"],"reform":["english","turkish"],"refuse":["english"],"region":["english"],"regret":["english"],"regular":["english"],"reject":["english"],"relax":["english"],"release":["english"],"relief":["english","french"],"rely":["english"],"remain":["english"],"remember":["english"],"remind":["english"],"remove":["english"],"render":["english"],"renew":["english"],"rent":["english"],"reopen":["english"],"repair":["english"],"repeat":["english"],"replace":["english"],"report":["english"],"require":["english"],"rescue":["english"],"resemble":["english"],"resist":["english"],"resource":["english"],"response":["english"],"result":["english"],"retire":["english"],"retreat":["english"],"return":["english"],"reunion":["english"],"reveal":["english"],"review":["english"],"reward":["english"],"rhythm":["english"],"rib":["english"],"ribbon":["english"],"rice":["english"],"rich":["english"],"ride":["english"],"ridge":["english"],"rifle":["english"],"right":["english"],"rigid":["english"],"ring":["english"],"riot":["english"],"ripple":["english"],"risk":["english"],"ritual":["english"],"rival":["english","french"],"river":["english"],"road":["english"],"roast":["english"],"robot":["english","turkish"],"robust":["english"],"rocket":["english"],"romance":["english","french"],"roof":["english"],"rookie":["english"],"room":["english"],"rose":["english"],"rotate":["english"],"rough":["english"],"round":["english"],"route":["english"],"royal":["english"],"rubber":["english"],"rude":["english"],"rug":["english"],"rule":["english"],"run":["english"],"runway":["english"],"rural":["english"],"sad":["english"],"saddle":["english"],"sadness":["english"],"safe":["english"],"sail":["english"],"salad":["english"],"salmon":["english"],"salon":["english","french","turkish"],"salt":["english"],"salute":["english"],"same":["english"],"sample":["english"],"sand":["english"],"satisfy":["english"],"satoshi":["english"],"sauce":["english"],"sausage":["english"],"save":["english"],"say":["english"],"scale":["english"],"scan":["english"],"scare":["english"],"scatter":["english"],"scene":["english"],"scheme":["english"],"school":["english"],"science":["english","french"],"scissors":["english"],"scorpion":["english"],"scout":["english"],"scrap":["english"],"screen":["english"],"script":["english"],"scrub":["english"],"sea":["english"],"search":["english"],"season":["english"],"seat":["english"],"second":["english"],"secret":["english"],"section":["english"],"security":["english"],"seed":["english"],"seek":["english"],"segment":["english"],"select":["english"],"sell":["english"],"seminar":["english"],"senior":["english"],"sense":["english"],"sentence":["english","french"],"series":["english"],"service":["english","french"],"session":["english"],"settle":["english"],"setup":["english"],"seven":["english"],"shadow":["english"],"shaft":["english"],"shallow":["english"],"share":["english"],"shed":["english"],"shell":["english"],"sheriff":["english"],"shield":["english"],"shift":["english"],"shine":["english"],"ship":["english"],"shiver":["english"],"shock":["english"],"shoe":["english"],"shoot":["english"],"shop":["english"],"short":["english"],"shoulder":["english"],"shove":["english"],"shrimp":["english"],"shrug":["english"],"shuffle":["english"],"shy":["english"],"sibling":["english"],"sick":["english"],"side":["english"],"siege":["english"],"sight":["english"],"sign":["english"],"silent":["english"],"silk":["english"],"silly":["english"],"silver":["english"],"similar":["english"],"simple":["english","french"],"since":["english"],"sing":["english"],"siren":["english"],"sister":["english"],"situate":["english"],"six":["english"],"size":["english"],"skate":["english"],"sketch":["english"],"ski":["english"],"skill":["english"],"skin":["english"],"skirt":["english"],"skull":["english"],"slab":["english"],"slam":["english"],"sleep":["english"],"slender":["english"],"slice":["english"],"slide":["english"],"slight":["english"],"slim":["english"],"slogan":["english","turkish"],"slot":["english"],"slow":["english"],"slush":["english"],"small":["english"],"smart":["english"],"smile":["english"],"smoke":["english"],"smooth":["english"],"snack":["english"],"snake":["english"],"snap":["english"],"sniff":["english"],"snow":["english"],"soap":["english"],"soccer":["english"],"social":["english","french"],"sock":["english"],"soda":["english"],"soft":["english"],"solar":["english"],"soldier":["english"],"solid":["english"],"solution":["english"],"solve":["english"],"someone":["english"],"song":["english"],"soon":["english"],"sorry":["english"],"sort":["english"],"soul":["english"],"sound":["english"],"soup":["english"],"source":["english","french"],"south":["english"],"space":["english"],"spare":["english"],"spatial":["english","french"],"spawn":["english"],"speak":["english"],"special":["english"],"speed":["english"],"spell":["english"],"spend":["english"],"sphere":["english"],"spice":["english"],"spider":["english"],"spike":["english"],"spin":["english"],"spirit":["english"],"split":["english"],"spoil":["english"],"sponsor":["english","turkish"],"spoon":["english"],"sport":["english"],"spot":["english"],"spray":["english"],"spread":["english"],"spring":["english"],"spy":["english"],"square":["english"],"squeeze":["english"],"squirrel":["english"],"stable":["english","french"],"stadium":["english"],"staff":["english"],"stage":["english"],"stairs":["english"],"stamp":["english"],"stand":["english"],"start":["english"],"state":["english"],"stay":["english"],"steak":["english"],"steel":["english"],"stem":["english"],"step":["english"],"stereo":["english"],"stick":["english"],"still":["english"],"sting":["english"],"stock":["english"],"stomach":["english"],"stone":["english"],"stool":["english"],"story":["english"],"stove":["english"],"strategy":["english"],"street":["english"],"strike":["english"],"strong":["english"],"struggle":["english"],"student":["english"],"stuff":["english"],"stumble":["english"],"style":["english"],"subject":["english"],"submit":["english"],"subway":["english"],"success":["english"],"such":["english"],"sudden":["english"],"suffer":["english"],"sugar":["english"],"suggest":["english"],"suit":["english"],"summer":["english"],"sun":["english"],"sunny":["english"],"sunset":["english"],"super":["english"],"supply":["english"],"supreme":["english"],"sure":["english"],"surface":["english","french"],"surge":["english"],"surprise":["english","french"],"surround":["english"],"survey":["english"],"suspect":["english","french"],"sustain":["english"],"swallow":["english"],"swamp":["english"],"swap":["english"],"swarm":["english"],"swear":["english"],"sweet":["english"],"swift":["english"],"swim":["english"],"swing":["english"],"switch":["english"],"sword":["english"],"symbol":["english"],"symptom":["english"],"syrup":["english"],"system":["english"],"table":["english"],"tackle":["english"],"tag":["english"],"tail":["english"],"talent":["english","french"],"talk":["english"],"tank":["english"],"tape":["english"],"target":["english"],"task":["english"],"taste":["english"],"tattoo":["english"],"taxi":["english"],"teach":["english"],"team":["english"],"tell":["english"],"ten":["english"],"tenant":["english"],"tennis":["english"],"tent":["english"],"term":["english"],"test":["english"],"text":["english"],"thank":["english"],"that":["english"],"theme":["english"],"then":["english"],"theory":["english"],"there":["english"],"they":["english"],"thing":["english"],"this":["english"],"thought":["english"],"three":["english"],"thrive":["english"],"throw":["english"],"thumb":["english"],"thunder":["english"],"ticket":["english"],"tide":["english"],"tiger":["english"],"tilt":["english"],"timber":["english"],"time":["english"],"tiny":["english"],"tip":["english"],"tired":["english"],"tissue":["english"],"title":["english"],"toast":["english"],"tobacco":["english"],"today":["english"],"toddler":["english"],"toe":["english"],"together":["english"],"toilet":["english"],"token":["english"],"tomato":["english"],"tomorrow":["english"],"tone":["english"],"tongue":["english"],"tonight":["english"],"tool":["english"],"tooth":["english"],"top":["english"],"topic":["english"],"topple":["english"],"torch":["english"],"tornado":["english"],"tortoise":["english"],"toss":["english"],"total":["english"],"tourist":["english"],"toward":["english"],"tower":["english"],"town":["english"],"toy":["english"],"track":["english"],"trade":["english"],"traffic":["english"],"tragic":["english"],"train":["english","french"],"transfer":["english","turkish"],"trap":["english"],"trash":["english"],"travel":["english"],"tray":["english"],"treat":["english"],"tree":["english"],"trend":["english"],"trial":["english"],"tribe":["english"],"trick":["english"],"trigger":["english"],"trim":["english"],"trip":["english"],"trophy":["english"],"trouble":["english"],"truck":["english"],"true":["english"],"truly":["english"],"trumpet":["english"],"trust":["english"],"truth":["english"],"try":["english"],"tube":["english"],"tuition":["english"],"tumble":["english"],"tuna":["english"],"tunnel":["english","french"],"turkey":["english"],"turn":["english"],"turtle":["english"],"twelve":["english"],"twenty":["english"],"twice":["english"],"twin":["english"],"twist":["english"],"two":["english"],"type":["english"],"typical":["english"],"ugly":["english"],"umbrella":["english"],"unable":["english"],"unaware":["english"],"uncle":["english"],"uncover":["english"],"under":["english"],"undo":["english"],"unfair":["english"],"unfold":["english"],"unhappy":["english"],"uniform":["english"],"unique":["english","french"],"unit":["english"],"universe":["english"],"unknown":["english"],"unlock":["english"],"until":["english"],"unusual":["english"],"unveil":["english"],"update":["english"],"upgrade":["english"],"uphold":["english"],"upon":["english"],"upper":["english"],"upset":["english"],"urban":["english"],"urge":["english"],"usage":["english","french"],"use":["english"],"used":["english"],"useful":["english"],"useless":["english"],"usual":["english"],"utility":["english"],"vacant":["english"],"vacuum":["english"],"vague":["english","french"],"valid":["english"],"valley":["english"],"valve":["english","french"],"van":["english"],"vanish":["english"],"vapor":["english"],"various":["english"],"vast":["english"],"vault":["english"],"vehicle":["english"],"velvet":["english"],"vendor":["english"],"venture":["english"],"venue":["english"],"verb":["english"],"verify":["english"],"version":["english"],"very":["english"],"vessel":["english"],"veteran":["english"],"viable":["english"],"vibrant":["english"],"vicious":["english"],"victory":["english"],"video":["english"],"view":["english"],"village":["english","french"],"vintage":["english"],"violin":["english"],"virtual":["english"],"virus":["english","french"],"visa":["english"],"visit":["english"],"visual":["english"],"vital":["english","french"],"vivid":["english"],"vocal":["english"],"voice":["english"],"void":["english"],"volcano":["english"],"volume":["english","french"],"vote":["english"],"voyage":["english","french"],"wage":["english"],"wagon":["english","french"],"wait":["english"],"walk":["english"],"wall":["english"],"walnut":["english"],"want":["english"],"warfare":["english"],"warm":["english"],"warrior":["english"],"wash":["english"],"wasp":["english"],"waste":["english"],"water":["english"],"wave":["english"],"way":["english"],"wealth":["english"],"weapon":["english"],"wear":["english"],"weasel":["english"],"weather":["english"],"web":["english"],"wedding":["english"],"weekend":["english"],"weird":["english"],"welcome":["english"],"west":["english"],"wet":["english"],"whale":["english"],"what":["english"],"wheat":["english"],"wheel":["english"],"when":["english"],"where":["english"],"whip":["english"],"whisper":["english"],"wide":["english"],"width":["english"],"wife":["english"],"wild":["english"],"will":["english"],"win":["english"],"window":["english"],"wine":["english"],"wing":["english"],"wink":["english"],"winner":["english"],"winter":["english"],"wire":["english"],"wisdom":["english"],"wise":["english"],"wish":["english"],"witness":["english"],"wolf":["english"],"woman":["english"],"wonder":["english"],"wood":["english"],"wool":["english"],"word":["english"],"work":["english"],"world":["english"],"worry":["english"],"worth":["english"],"wrap":["english"],"wreck":["english"],"wrestle":["english"],"wrist":["english"],"write":["english"],"wrong":["english"],"yard":["english"],"year":["english"],"yellow":["english"],"you":["english"],"young":["english"],"youth":["english"],"zebra":["english"],"zero":["english"],"zone":["english"],"zoo":["english"],"abaisser":["french"],"abdiquer":["french"],"abeille":["french"],"abolir":["french"],"aborder":["french"],"aboutir":["french"],"aboyer":["french"],"abrasif":["french"],"abreuver":["french"],"abriter":["french"],"abroger":["french"],"abrupt":["french"],"absence":["french"],"absolu":["french"],"absurde":["french"],"abusif":["french"],"abyssal":["french"],"académie":["french"],"acajou":["french"],"acarien":["french"],"accabler":["french"],"accepter":["french"],"acclamer":["french"],"accolade":["french"],"accroche":["french"],"accuser":["french"],"acerbe":["french"],"achat":["french"],"acheter":["french"],"aciduler":["french"],"acier":["french"],"acompte":["french"],"acquérir":["french"],"acronyme":["french"],"acteur":["french"],"actif":["french"],"actuel":["french"],"adepte":["french"],"adéquat":["french"],"adhésif":["french"],"adjectif":["french"],"adjuger":["french"],"admettre":["french"],"admirer":["french"],"adopter":["french"],"adorer":["french"],"adoucir":["french"],"adresse":["french"],"adroit":["french"],"adulte":["french"],"adverbe":["french"],"aérer":["french"],"aéronef":["french"],"affaire":["french"],"affecter":["french"],"affiche":["french"],"affreux":["french"],"affubler":["french"],"agacer":["french"],"agencer":["french"],"agile":["french"],"agiter":["french"],"agrafer":["french"],"agréable":["french"],"agrume":["french"],"aider":["french"],"aiguille":["french"],"ailier":["french"],"aimable":["french"],"aisance":["french"],"ajouter":["french"],"ajuster":["french"],"alarmer":["french"],"alchimie":["french"],"alerte":["french"],"algèbre":["french"],"algue":["french"],"aliéner":["french"],"aliment":["french"],"alléger":["french"],"alliage":["french"],"allouer":["french"],"allumer":["french"],"alourdir":["french"],"alpaga":["french"],"altesse":["french"],"alvéole":["french"],"ambigu":["french"],"ambre":["french"],"aménager":["french"],"amertume":["french"],"amidon":["french"],"amiral":["french"],"amorcer":["french"],"amour":["french"],"amovible":["french"],"amphibie":["french"],"ampleur":["french"],"amusant":["french"],"analyse":["french"],"anaphore":["french"],"anarchie":["french"],"anatomie":["french"],"ancien":["french"],"anéantir":["french"],"angoisse":["french"],"anguleux":["french"],"annexer":["french"],"annonce":["french"],"annuel":["french"],"anodin":["french"],"anomalie":["french"],"anonyme":["french"],"anormal":["french"],"antenne":["french"],"antidote":["french"],"anxieux":["french"],"apaiser":["french"],"apéritif":["french"],"aplanir":["french"],"apologie":["french"],"appareil":["french"],"appeler":["french"],"apporter":["french"],"appuyer":["french"],"aquarium":["french"],"aqueduc":["french"],"arbitre":["french"],"arbuste":["french"],"ardeur":["french"],"ardoise":["french"],"argent":["french"],"arlequin":["french"],"armature":["french"],"armement":["french"],"armoire":["french"],"armure":["french"],"arpenter":["french"],"arracher":["french"],"arriver":["french"],"arroser":["french"],"arsenic":["french"],"artériel":["french"],"article":["french"],"asphalte":["french"],"aspirer":["french"],"assaut":["french"],"asservir":["french"],"assiette":["french"],"associer":["french"],"assurer":["french"],"asticot":["french"],"astre":["french"],"astuce":["french"],"atelier":["french"],"atome":["french"],"atrium":["french"],"atroce":["french"],"attaque":["french"],"attentif":["french"],"attirer":["french"],"attraper":["french"],"aubaine":["french"],"auberge":["french"],"audace":["french"],"audible":["french"],"augurer":["french"],"aurore":["french"],"automne":["french"],"autruche":["french"],"avaler":["french"],"avancer":["french"],"avarice":["french"],"avenir":["french"],"averse":["french"],"aveugle":["french"],"aviateur":["french"],"avide":["french"],"avion":["french"],"aviser":["french"],"avoine":["french"],"avouer":["french"],"avril":["french"],"axial":["french"],"axiome":["french"],"bafouer":["french"],"bagage":["french"],"baguette":["french"],"baignade":["french"],"balancer":["french"],"balcon":["french"],"baleine":["french"],"balisage":["french"],"bambin":["french"],"bancaire":["french"],"bandage":["french"],"banlieue":["french"],"bannière":["french"],"banquier":["french"],"barbier":["french"],"baril":["french"],"baron":["french"],"barque":["french"],"barrage":["french"],"bassin":["french"],"bastion":["french"],"bataille":["french"],"bateau":["french"],"batterie":["french"],"baudrier":["french"],"bavarder":["french"],"belette":["french"],"bélier":["french"],"belote":["french"],"bénéfice":["french"],"berceau":["french"],"berger":["french"],"berline":["french"],"bermuda":["french","turkish"],"besace":["french"],"besogne":["french"],"bétail":["french"],"beurre":["french"],"biberon":["french"],"bidule":["french"],"bijou":["french"],"bilan":["french"],"bilingue":["french"],"billard":["french"],"binaire":["french"],"biologie":["french"],"biopsie":["french"],"biotype":["french"],"biscuit":["french"],"bison":["french"],"bistouri":["french"],"bitume":["french"],"bizarre":["french"],"blafard":["french"],"blague":["french"],"blanchir":["french"],"blessant":["french"],"blinder":["french"],"blond":["french"],"bloquer":["french"],"blouson":["french"],"bobard":["french"],"bobine":["french"],"boire":["french"],"boiser":["french"],"bolide":["french"],"bonbon":["french"],"bondir":["french"],"bonheur":["french"],"bonifier":["french"],"bordure":["french"],"borne":["french"],"botte":["french"],"boucle":["french"],"boueux":["french"],"bougie":["french"],"boulon":["french"],"bouquin":["french"],"bourse":["french"],"boussole":["french"],"boutique":["french"],"boxeur":["french"],"branche":["french"],"brasier":["french"],"brebis":["french"],"brèche":["french"],"breuvage":["french"],"bricoler":["french"],"brigade":["french"],"brillant":["french"],"brioche":["french"],"brique":["french"],"brochure":["french"],"broder":["french"],"bronzer":["french"],"brousse":["french"],"broyeur":["french"],"brume":["french"],"brusque":["french"],"brutal":["french"],"bruyant":["french"],"buffle":["french"],"buisson":["french"],"bulletin":["french"],"bureau":["french"],"burin":["french"],"bustier":["french"],"butiner":["french"],"butoir":["french"],"buvable":["french"],"buvette":["french"],"cabanon":["french"],"cabine":["french"],"cachette":["french"],"cadeau":["french"],"cadre":["french"],"caféine":["french"],"caillou":["french"],"caisson":["french"],"calculer":["french"],"calepin":["french"],"calibre":["french"],"calmer":["french"],"calomnie":["french"],"calvaire":["french"],"camarade":["french"],"caméra":["french"],"camion":["french"],"campagne":["french"],"caneton":["french"],"canon":["french"],"cantine":["french"],"canular":["french"],"caporal":["french"],"caprice":["french"],"capsule":["french"],"capter":["french"],"capuche":["french"],"carabine":["french"],"carbone":["french"],"caresser":["french"],"caribou":["french"],"carnage":["french"],"carotte":["french"],"carreau":["french"],"carton":["french"],"cascade":["french"],"casier":["french"],"casque":["french"],"cassure":["french"],"causer":["french"],"cavalier":["french"],"caverne":["french"],"caviar":["french"],"cédille":["french"],"ceinture":["french"],"céleste":["french"],"cellule":["french"],"cendrier":["french"],"censurer":["french"],"central":["french"],"cercle":["french"],"cérébral":["french"],"cerise":["french"],"cerner":["french"],"cerveau":["french"],"cesser":["french"],"chagrin":["french"],"chaise":["french"],"chaleur":["french"],"chambre":["french"],"chance":["french"],"chapitre":["french"],"charbon":["french"],"chasseur":["french"],"chaton":["french"],"chausson":["french"],"chavirer":["french"],"chemise":["french"],"chenille":["french"],"chéquier":["french"],"chercher":["french"],"cheval":["french"],"chien":["french"],"chiffre":["french"],"chignon":["french"],"chimère":["french"],"chiot":["french"],"chlorure":["french"],"chocolat":["french"],"choisir":["french"],"chose":["french"],"chouette":["french"],"chrome":["french"],"chute":["french"],"cigare":["french"],"cigogne":["french"],"cimenter":["french"],"cinéma":["french"],"cintrer":["french"],"circuler":["french"],"cirer":["french"],"cirque":["french"],"citerne":["french"],"citoyen":["french"],"citron":["french"],"clairon":["french"],"clameur":["french"],"claquer":["french"],"classe":["french"],"clavier":["french"],"cligner":["french"],"climat":["french"],"clivage":["french"],"cloche":["french"],"clonage":["french"],"cloporte":["french"],"cobalt":["french"],"cobra":["french"],"cocasse":["french"],"cocotier":["french"],"coder":["french"],"codifier":["french"],"coffre":["french"],"cogner":["french"],"cohésion":["french"],"coiffer":["french"],"coincer":["french"],"colère":["french"],"colibri":["french"],"colline":["french"],"colmater":["french"],"colonel":["french"],"combat":["french"],"comédie":["french"],"commande":["french"],"compact":["french"],"conduire":["french"],"confier":["french"],"congeler":["french"],"connoter":["french"],"consonne":["french"],"contact":["french"],"convexe":["french"],"copain":["french"],"copie":["french"],"corail":["french"],"corbeau":["french"],"cordage":["french"],"corniche":["french"],"corpus":["french"],"cortège":["french"],"cosmique":["french"],"costume":["french"],"coton":["french"],"coude":["french"],"coupure":["french"],"courage":["french"],"couteau":["french"],"couvrir":["french"],"crabe":["french"],"crainte":["french"],"cravate":["french"],"crayon":["french"],"créature":["french"],"créditer":["french"],"crémeux":["french"],"creuser":["french"],"crevette":["french"],"cribler":["french"],"crier":["french"],"cristal":["french"],"critère":["french"],"croire":["french"],"croquer":["french"],"crotale":["french"],"crypter":["french"],"cubique":["french"],"cueillir":["french"],"cuillère":["french"],"cuisine":["french"],"cuivre":["french"],"culminer":["french"],"cultiver":["french"],"cumuler":["french"],"cupide":["french"],"curatif":["french"],"curseur":["french"],"cyanure":["french"],"cylindre":["french"],"cynique":["french"],"daigner":["french"],"damier":["french"],"danseur":["french"],"dauphin":["french"],"débattre":["french"],"débiter":["french"],"déborder":["french"],"débrider":["french"],"débutant":["french"],"décaler":["french"],"décembre":["french"],"déchirer":["french"],"décider":["french"],"déclarer":["french"],"décorer":["french"],"décrire":["french"],"décupler":["french"],"dédale":["french"],"déductif":["french"],"déesse":["french"],"défensif":["french"],"défiler":["french"],"défrayer":["french"],"dégager":["french"],"dégivrer":["french"],"déglutir":["french"],"dégrafer":["french"],"déjeuner":["french"],"délice":["french"],"déloger":["french"],"demander":["french"],"demeurer":["french"],"démolir":["french"],"dénicher":["french"],"dénouer":["french"],"dentelle":["french"],"dénuder":["french"],"départ":["french"],"dépenser":["french"],"déphaser":["french"],"déplacer":["french"],"déposer":["french"],"déranger":["french"],"dérober":["french"],"désastre":["french"],"descente":["french"],"désert":["french"],"désigner":["french"],"désobéir":["french"],"dessiner":["french"],"destrier":["french"],"détacher":["french"],"détester":["french"],"détourer":["french"],"détresse":["french"],"devancer":["french"],"devenir":["french"],"deviner":["french"],"devoir":["french"],"diable":["french"],"dialogue":["french"],"diamant":["french"],"dicter":["french"],"différer":["french"],"digérer":["french"],"digne":["french"],"diluer":["french"],"dimanche":["french"],"diminuer":["french"],"dioxyde":["french"],"directif":["french"],"diriger":["french"],"discuter":["french"],"disposer":["french"],"dissiper":["french"],"divertir":["french"],"diviser":["french"],"docile":["french"],"docteur":["french"],"dogme":["french"],"doigt":["french"],"domaine":["french"],"domicile":["french"],"dompter":["french"],"donateur":["french"],"donjon":["french"],"donner":["french"],"dopamine":["french"],"dortoir":["french"],"dorure":["french"],"dosage":["french"],"doseur":["french"],"dossier":["french"],"dotation":["french"],"douanier":["french"],"douceur":["french"],"douter":["french"],"doyen":["french"],"draper":["french"],"dresser":["french"],"dribbler":["french"],"droiture":["french"],"duperie":["french"],"duplexe":["french"],"durable":["french"],"durcir":["french"],"dynastie":["french"],"éblouir":["french"],"écarter":["french"],"écharpe":["french"],"échelle":["french"],"éclairer":["french"],"éclipse":["french"],"éclore":["french"],"écluse":["french"],"école":["french"],"économie":["french"],"écorce":["french"],"écouter":["french"],"écraser":["french"],"écrémer":["french"],"écrivain":["french"],"écrou":["french"],"écume":["french"],"écureuil":["french"],"édifier":["french"],"éduquer":["french"],"effacer":["french"],"effectif":["french"],"effigie":["french"],"effrayer":["french"],"effusion":["french"],"égaliser":["french"],"égarer":["french"],"éjecter":["french"],"élaborer":["french"],"élargir":["french"],"électron":["french"],"élégant":["french"],"éléphant":["french"],"élève":["french"],"éligible":["french"],"élitisme":["french"],"éloge":["french"],"élucider":["french"],"éluder":["french"],"emballer":["french"],"embellir":["french"],"embryon":["french"],"émeraude":["french"],"émission":["french"],"emmener":["french"],"émotion":["french"],"émouvoir":["french"],"empereur":["french"],"employer":["french"],"emporter":["french"],"emprise":["french"],"émulsion":["french"],"encadrer":["french"],"enchère":["french"],"enclave":["french"],"encoche":["french"],"endiguer":["french"],"endosser":["french"],"endroit":["french"],"enduire":["french"],"énergie":["french"],"enfance":["french"],"enfermer":["french"],"enfouir":["french"],"engager":["french"],"engin":["french","turkish"],"englober":["french"],"énigme":["french"],"enjamber":["french"],"enjeu":["french"],"enlever":["french"],"ennemi":["french"],"ennuyeux":["french"],"enrichir":["french"],"enrobage":["french"],"enseigne":["french"],"entasser":["french"],"entendre":["french"],"entier":["french"],"entourer":["french"],"entraver":["french"],"énumérer":["french"],"envahir":["french"],"enviable":["french"],"envoyer":["french"],"enzyme":["french"],"éolien":["french"],"épaissir":["french"],"épargne":["french"],"épatant":["french"],"épaule":["french"],"épicerie":["french"],"épidémie":["french"],"épier":["french"],"épilogue":["french"],"épine":["french"],"épisode":["french"],"épitaphe":["french"],"époque":["french"],"épreuve":["french"],"éprouver":["french"],"épuisant":["french"],"équerre":["french"],"équipe":["french"],"ériger":["french"],"érosion":["french"],"erreur":["french"],"éruption":["french"],"escalier":["french"],"espadon":["french"],"espèce":["french"],"espiègle":["french"],"espoir":["french"],"esprit":["french"],"esquiver":["french"],"essayer":["french"],"essieu":["french"],"essorer":["french"],"estime":["french"],"estomac":["french"],"estrade":["french"],"étagère":["french"],"étaler":["french"],"étanche":["french"],"étatique":["french"],"éteindre":["french"],"étendoir":["french"],"éternel":["french"],"éthanol":["french"],"éthique":["french"],"ethnie":["french"],"étirer":["french"],"étoffer":["french"],"étoile":["french"],"étonnant":["french"],"étourdir":["french"],"étrange":["french"],"étroit":["french"],"étude":["french"],"euphorie":["french"],"évaluer":["french"],"évasion":["french"],"éventail":["french"],"évidence":["french"],"éviter":["french"],"évolutif":["french"],"évoquer":["french"],"exagérer":["french"],"exaucer":["french"],"exceller":["french"],"excitant":["french"],"exclusif":["french"],"exécuter":["french"],"exemple":["french"],"exercer":["french"],"exhaler":["french"],"exhorter":["french"],"exigence":["french"],"exiler":["french"],"exister":["french"],"exotique":["french"],"expédier":["french"],"explorer":["french"],"exposer":["french"],"exprimer":["french"],"exquis":["french"],"extensif":["french"],"extraire":["french"],"exulter":["french"],"fable":["french"],"fabuleux":["french"],"facette":["french"],"facile":["french"],"facture":["french"],"faiblir":["french"],"falaise":["french"],"fameux":["french"],"famille":["french"],"farceur":["french"],"farfelu":["french"],"farine":["french"],"farouche":["french"],"fasciner":["french"],"faucon":["french"],"fautif":["french"],"faveur":["french"],"favori":["french","turkish"],"fébrile":["french"],"féconder":["french"],"fédérer":["french"],"félin":["french"],"femme":["french"],"fémur":["french"],"fendoir":["french"],"féodal":["french"],"fermer":["french"],"féroce":["french"],"ferveur":["french"],"feuille":["french"],"feutre":["french"],"février":["french"],"fiasco":["french"],"ficeler":["french"],"fictif":["french"],"fidèle":["french"],"filature":["french"],"filetage":["french"],"filière":["french"],"filleul":["french"],"filmer":["french"],"filou":["french"],"filtrer":["french"],"financer":["french"],"finir":["french"],"fiole":["french"],"firme":["french"],"fissure":["french"],"fixer":["french"],"flairer":["french"],"flamme":["french"],"flasque":["french"],"flatteur":["french"],"fléau":["french"],"flèche":["french"],"fleur":["french"],"flexion":["french"],"flocon":["french"],"flore":["french"],"fluctuer":["french"],"fluide":["french"],"fluvial":["french"],"folie":["french"],"fonderie":["french"],"fongible":["french"],"fontaine":["french"],"forcer":["french"],"forgeron":["french"],"formuler":["french"],"fossile":["french"],"foudre":["french"],"fougère":["french"],"fouiller":["french"],"foulure":["french"],"fourmi":["french"],"fraise":["french"],"franchir":["french"],"frapper":["french"],"frayeur":["french"],"frégate":["french"],"freiner":["french"],"frelon":["french"],"frémir":["french"],"frénésie":["french"],"frère":["french"],"friable":["french"],"friction":["french"],"frisson":["french"],"frivole":["french"],"froid":["french"],"fromage":["french"],"frontal":["french"],"frotter":["french"],"fugitif":["french"],"fuite":["french"],"fureur":["french"],"furieux":["french"],"furtif":["french"],"fusion":["french"],"futur":["french"],"gagner":["french"],"galaxie":["french"],"galerie":["french"],"gambader":["french"],"garantir":["french"],"gardien":["french"],"garnir":["french"],"garrigue":["french"],"gazelle":["french"],"gazon":["french"],"géant":["french"],"gélatine":["french"],"gélule":["french"],"gendarme":["french"],"général":["french"],"génie":["french"],"genou":["french"],"gentil":["french"],"géologie":["french"],"géomètre":["french"],"géranium":["french"],"germe":["french"],"gestuel":["french"],"geyser":["french"],"gibier":["french"],"gicler":["french"],"girafe":["french"],"givre":["french"],"glace":["french"],"glaive":["french"],"glisser":["french"],"gloire":["french"],"glorieux":["french"],"golfeur":["french"],"gomme":["french"],"gonfler":["french"],"gorge":["french"],"gorille":["french"],"goudron":["french"],"gouffre":["french"],"goulot":["french"],"goupille":["french"],"gourmand":["french"],"goutte":["french"],"graduel":["french"],"graffiti":["french"],"graine":["french"],"grand":["french"],"grappin":["french"],"gratuit":["french"],"gravir":["french"],"grenat":["french"],"griffure":["french"],"griller":["french"],"grimper":["french"],"grogner":["french"],"gronder":["french"],"grotte":["french"],"groupe":["french"],"gruger":["french"],"grutier":["french"],"gruyère":["french"],"guépard":["french"],"guerrier":["french"],"guimauve":["french"],"guitare":["french"],"gustatif":["french"],"gymnaste":["french"],"gyrostat":["french"],"habitude":["french"],"hachoir":["french"],"halte":["french"],"hameau":["french"],"hangar":["french","turkish"],"hanneton":["french"],"haricot":["french"],"harmonie":["french"],"harpon":["french"],"hasard":["french"],"hélium":["french"],"hématome":["french"],"herbe":["french"],"hérisson":["french"],"hermine":["french"],"héron":["french"],"hésiter":["french"],"heureux":["french"],"hiberner":["french"],"hibou":["french"],"hilarant":["french"],"histoire":["french"],"hiver":["french"],"homard":["french"],"hommage":["french"],"homogène":["french"],"honneur":["french"],"honorer":["french"],"honteux":["french"],"horde":["french"],"horizon":["french"],"horloge":["french"],"hormone":["french"],"horrible":["french"],"houleux":["french"],"housse":["french"],"hublot":["french"],"huileux":["french"],"humain":["french"],"humide":["french"],"humour":["french"],"hurler":["french"],"hydromel":["french"],"hygiène":["french"],"hymne":["french"],"hypnose":["french"],"idylle":["french"],"ignorer":["french"],"iguane":["french"],"illicite":["french"],"illusion":["french"],"imbiber":["french"],"imiter":["french"],"immobile":["french"],"immuable":["french"],"impérial":["french"],"implorer":["french"],"imposer":["french"],"imprimer":["french"],"imputer":["french"],"incarner":["french"],"incendie":["french"],"incident":["french"],"incliner":["french"],"incolore":["french"],"indexer":["french"],"indice":["french"],"inductif":["french"],"inédit":["french"],"ineptie":["french"],"inexact":["french"],"infini":["french"],"infliger":["french"],"informer":["french"],"infusion":["french"],"ingérer":["french"],"inhaler":["french"],"inhiber":["french"],"injecter":["french"],"injure":["french"],"inoculer":["french"],"inonder":["french"],"inscrire":["french"],"insecte":["french"],"insigne":["french"],"insolite":["french"],"inspirer":["french"],"instinct":["french"],"insulter":["french"],"intense":["french"],"intime":["french"],"intrigue":["french"],"intuitif":["french"],"inutile":["french"],"invasion":["french"],"inventer":["french"],"inviter":["french"],"invoquer":["french"],"ironique":["french"],"irradier":["french"],"irréel":["french"],"irriter":["french"],"isoler":["french"],"ivoire":["french"],"ivresse":["french"],"jaillir":["french"],"jambe":["french"],"janvier":["french"],"jardin":["french"],"jauger":["french"],"jaune":["french"],"javelot":["french"],"jetable":["french"],"jeton":["french"],"jeudi":["french"],"jeunesse":["french"],"joindre":["french"],"joncher":["french"],"jongler":["french"],"joueur":["french"],"jouissif":["french"],"journal":["french"],"jovial":["french"],"joyau":["french"],"joyeux":["french"],"jubiler":["french"],"jugement":["french"],"jupon":["french"],"juriste":["french"],"justice":["french"],"juteux":["french"],"juvénile":["french"],"kayak":["french"],"kimono":["french"],"kiosque":["french"],"labial":["french"],"labourer":["french"],"lacérer":["french"],"lactose":["french"],"lagune":["french"],"laine":["french"],"laisser":["french"],"laitier":["french"],"lambeau":["french"],"lamelle":["french"],"lampe":["french"],"lanceur":["french"],"langage":["french"],"lanterne":["french"],"lapin":["french"],"largeur":["french"],"larme":["french"],"laurier":["french"],"lavabo":["french"],"lavoir":["french"],"légal":["french"],"léger":["french"],"légume":["french"],"lessive":["french"],"lettre":["french"],"levier":["french"],"lexique":["french"],"lézard":["french"],"liasse":["french"],"libérer":["french"],"libre":["french"],"licence":["french"],"licorne":["french"],"liège":["french"],"lièvre":["french"],"ligature":["french"],"ligoter":["french"],"ligue":["french"],"limer":["french"],"limite":["french"],"limonade":["french"],"limpide":["french"],"linéaire":["french"],"lingot":["french"],"lionceau":["french"],"liquide":["french"],"lisière":["french"],"lister":["french"],"lithium":["french"],"litige":["french"],"littoral":["french"],"livreur":["french"],"logique":["french"],"lointain":["french"],"loisir":["french"],"lombric":["french"],"loterie":["french"],"louer":["french"],"lourd":["french"],"loutre":["french"],"louve":["french"],"lubie":["french"],"lucide":["french"],"lucratif":["french"],"lueur":["french"],"lugubre":["french"],"luisant":["french"],"lumière":["french"],"lunaire":["french"],"lundi":["french"],"luron":["french"],"lutter":["french"],"luxueux":["french"],"magasin":["french"],"magenta":["french"],"magique":["french"],"maigre":["french"],"maillon":["french"],"maintien":["french"],"mairie":["french"],"maison":["french"],"majorer":["french"],"malaxer":["french"],"maléfice":["french"],"malheur":["french"],"malice":["french"],"mallette":["french"],"mammouth":["french"],"mandater":["french"],"maniable":["french"],"manquant":["french"],"manteau":["french"],"manuel":["french"],"marathon":["french"],"marbre":["french"],"marchand":["french"],"mardi":["french"],"maritime":["french"],"marqueur":["french"],"marron":["french"],"marteler":["french"],"mascotte":["french"],"massif":["french"],"matériel":["french"],"matière":["french"],"matraque":["french"],"maudire":["french"],"maussade":["french"],"mauve":["french"],"maximal":["french"],"méchant":["french"],"méconnu":["french"],"médaille":["french"],"médecin":["french"],"méditer":["french"],"méduse":["french"],"meilleur":["french"],"mélange":["french"],"mélodie":["french"],"membre":["french"],"mémoire":["french"],"menacer":["french"],"mener":["french"],"menhir":["french"],"mensonge":["french"],"mentor":["french"],"mercredi":["french"],"mérite":["french"],"merle":["french"],"messager":["french"],"mesure":["french"],"métal":["french"],"météore":["french"],"méthode":["french"],"métier":["french"],"meuble":["french"],"miauler":["french"],"microbe":["french"],"miette":["french"],"mignon":["french"],"migrer":["french"],"milieu":["french"],"mimique":["french"],"mince":["french"],"minéral":["french"],"minimal":["french"],"minorer":["french"],"miroiter":["french"],"missile":["french"],"mixte":["french"],"moderne":["french"],"moelleux":["french"],"mondial":["french"],"moniteur":["french"],"monnaie":["french"],"monotone":["french"],"monstre":["french"],"montagne":["french"],"monument":["french"],"moqueur":["french"],"morceau":["french"],"morsure":["french"],"mortier":["french"],"moteur":["french"],"motif":["french"],"mouche":["french"],"moufle":["french"],"moulin":["french"],"mousson":["french"],"mouton":["french"],"mouvant":["french"],"multiple":["french"],"munition":["french"],"muraille":["french"],"murène":["french"],"murmure":["french"],"muséum":["french"],"musicien":["french"],"mutation":["french"],"muter":["french"],"mutuel":["french"],"myriade":["french"],"myrtille":["french"],"mystère":["french"],"mythique":["french"],"nageur":["french"],"nappe":["french"],"narquois":["french"],"narrer":["french"],"natation":["french"],"naufrage":["french"],"nautique":["french"],"navire":["french"],"nébuleux":["french"],"nectar":["french"],"néfaste":["french"],"négation":["french"],"négliger":["french"],"négocier":["french"],"neige":["french"],"nerveux":["french"],"nettoyer":["french"],"neurone":["french"],"neutron":["french"],"neveu":["french"],"niche":["french"],"nickel":["french"],"nitrate":["french"],"niveau":["french"],"nocif":["french"],"nocturne":["french"],"noirceur":["french"],"noisette":["french"],"nomade":["french"],"nombreux":["french"],"nommer":["french"],"normatif":["french"],"notifier":["french"],"notoire":["french"],"nourrir":["french"],"nouveau":["french"],"novateur":["french"],"novembre":["french"],"novice":["french"],"nuage":["french"],"nuancer":["french"],"nuire":["french"],"nuisible":["french"],"numéro":["french"],"nuptial":["french"],"nuque":["french"],"nutritif":["french"],"obéir":["french"],"objectif":["french"],"obliger":["french"],"obscur":["french"],"observer":["french"],"obstacle":["french"],"obtenir":["french"],"obturer":["french"],"occasion":["french"],"occuper":["french"],"océan":["french"],"octobre":["french"],"octroyer":["french"],"octupler":["french"],"oculaire":["french"],"odeur":["french"],"odorant":["french"],"offenser":["french"],"officier":["french"],"offrir":["french"],"ogive":["french"],"oiseau":["french"],"oisillon":["french"],"olfactif":["french"],"olivier":["french"],"ombrage":["french"],"omettre":["french"],"onctueux":["french"],"onduler":["french"],"onéreux":["french"],"onirique":["french"],"opale":["french"],"opaque":["french"],"opérer":["french"],"opportun":["french"],"opprimer":["french"],"opter":["french"],"optique":["french"],"orageux":["french"],"orbite":["french"],"ordonner":["french"],"oreille":["french"],"organe":["french"],"orgueil":["french"],"orifice":["french"],"ornement":["french"],"orque":["french"],"ortie":["french"],"osciller":["french"],"osmose":["french"],"ossature":["french"],"otarie":["french"],"ouragan":["french"],"ourson":["french"],"outil":["french"],"outrager":["french"],"ouvrage":["french"],"ovation":["french"],"oxyde":["french"],"oxygène":["french"],"paisible":["french"],"palmarès":["french"],"palourde":["french"],"palper":["french"],"panache":["french"],"pangolin":["french"],"paniquer":["french"],"panneau":["french"],"panorama":["french"],"pantalon":["french"],"papaye":["french"],"papier":["french"],"papoter":["french"],"papyrus":["french"],"paradoxe":["french"],"parcelle":["french"],"paresse":["french"],"parfumer":["french"],"parler":["french"],"parole":["french"],"parrain":["french"],"parsemer":["french"],"partager":["french"],"parure":["french"],"parvenir":["french"],"passion":["french"],"pastèque":["french"],"paternel":["french"],"patience":["french"],"patron":["french","turkish"],"pavillon":["french"],"pavoiser":["french"],"payer":["french"],"paysage":["french"],"peigne":["french"],"peintre":["french"],"pelage":["french"],"pélican":["french"],"pelle":["french"],"pelouse":["french"],"peluche":["french"],"pendule":["french"],"pénétrer":["french"],"pénible":["french"],"pensif":["french"],"pénurie":["french"],"pépite":["french"],"péplum":["french"],"perdrix":["french"],"perforer":["french"],"période":["french"],"permuter":["french"],"perplexe":["french"],"persil":["french"],"perte":["french"],"peser":["french"],"pétale":["french"],"petit":["french"],"pétrir":["french"],"peuple":["french"],"pharaon":["french"],"phobie":["french"],"phoque":["french"],"photon":["french"],"physique":["french"],"pictural":["french"],"pièce":["french"],"pierre":["french"],"pieuvre":["french"],"pilote":["french"],"pinceau":["french"],"pipette":["french"],"piquer":["french"],"pirogue":["french"],"piscine":["french"],"piston":["french"],"pivoter":["french"],"pixel":["french"],"placard":["french"],"plafond":["french"],"plaisir":["french"],"planer":["french"],"plaque":["french"],"plastron":["french"],"plateau":["french"],"pleurer":["french"],"plexus":["french"],"pliage":["french"],"plomb":["french"],"plonger":["french"],"pluie":["french"],"plumage":["french"],"pochette":["french"],"poésie":["french"],"poète":["french"],"pointe":["french"],"poirier":["french"],"poisson":["french"],"poivre":["french"],"polaire":["french"],"policier":["french"],"pollen":["french"],"polygone":["french"],"pommade":["french"],"pompier":["french"],"ponctuel":["french"],"pondérer":["french"],"poney":["french"],"portique":["french"],"posséder":["french"],"posture":["french"],"potager":["french"],"poteau":["french"],"potion":["french"],"pouce":["french"],"poulain":["french"],"poumon":["french"],"pourpre":["french"],"poussin":["french"],"pouvoir":["french"],"prairie":["french"],"pratique":["french"],"précieux":["french"],"prédire":["french"],"préfixe":["french"],"prélude":["french"],"prénom":["french"],"présence":["french"],"prétexte":["french"],"prévoir":["french"],"primitif":["french"],"prince":["french"],"priver":["french"],"problème":["french"],"procéder":["french"],"prodige":["french"],"profond":["french"],"progrès":["french"],"proie":["french"],"projeter":["french"],"prologue":["french"],"promener":["french"],"propre":["french"],"prospère":["french"],"protéger":["french"],"prouesse":["french"],"proverbe":["french"],"prudence":["french"],"pruneau":["french"],"psychose":["french"],"puceron":["french"],"puiser":["french"],"pulpe":["french"],"pulsar":["french"],"punaise":["french"],"punitif":["french"],"pupitre":["french"],"purifier":["french"],"pyramide":["french"],"quasar":["french"],"querelle":["french"],"quiétude":["french"],"quitter":["french"],"quotient":["french"],"racine":["french"],"raconter":["french"],"radieux":["french"],"ragondin":["french"],"raideur":["french"],"raisin":["french"],"ralentir":["french"],"rallonge":["french"],"ramasser":["french"],"rapide":["french"],"rasage":["french"],"ratisser":["french"],"ravager":["french"],"ravin":["french"],"rayonner":["french"],"réactif":["french"],"réagir":["french"],"réaliser":["french"],"réanimer":["french"],"recevoir":["french"],"réciter":["french"],"réclamer":["french"],"récolter":["french"],"recruter":["french"],"reculer":["french"],"recycler":["french"],"rédiger":["french"],"redouter":["french"],"refaire":["french"],"réflexe":["french"],"réformer":["french"],"refrain":["french"],"refuge":["french"],"régalien":["french"],"région":["french"],"réglage":["french"],"régulier":["french"],"réitérer":["french"],"rejeter":["french"],"rejouer":["french"],"relatif":["french"],"relever":["french"],"remarque":["french"],"remède":["french"],"remise":["french"],"remonter":["french"],"remplir":["french"],"remuer":["french"],"renard":["french"],"renfort":["french"],"renifler":["french"],"renoncer":["french"],"rentrer":["french"],"renvoi":["french"],"replier":["french"],"reporter":["french"],"reprise":["french"],"reptile":["french"],"requin":["french"],"réserve":["french"],"résineux":["french"],"résoudre":["french"],"respect":["french"],"rester":["french"],"résultat":["french"],"rétablir":["french"],"retenir":["french"],"réticule":["french"],"retomber":["french"],"retracer":["french"],"réunion":["french"],"réussir":["french"],"revanche":["french"],"revivre":["french"],"révolte":["french"],"révulsif":["french"],"richesse":["french"],"rideau":["french"],"rieur":["french"],"rigide":["french"],"rigoler":["french"],"rincer":["french"],"riposter":["french"],"risible":["french"],"risque":["french"],"rituel":["french"],"rivière":["french"],"rocheux":["french"],"rompre":["french"],"ronce":["french"],"rondin":["french"],"roseau":["french"],"rosier":["french"],"rotatif":["french"],"rotor":["french"],"rotule":["french"],"rouge":["french"],"rouille":["french"],"rouleau":["french"],"routine":["french"],"royaume":["french"],"ruban":["french"],"rubis":["french"],"ruche":["french"],"ruelle":["french"],"rugueux":["french"],"ruiner":["french"],"ruisseau":["french"],"ruser":["french"],"rustique":["french"],"rythme":["french"],"sabler":["french"],"saboter":["french"],"sabre":["french"],"sacoche":["french"],"safari":["french"],"sagesse":["french"],"saisir":["french"],"salade":["french"],"salive":["french"],"saluer":["french"],"samedi":["french"],"sanction":["french"],"sanglier":["french"],"sarcasme":["french"],"sardine":["french"],"saturer":["french"],"saugrenu":["french"],"saumon":["french"],"sauter":["french"],"sauvage":["french"],"savant":["french"],"savonner":["french"],"scalpel":["french"],"scandale":["french"],"scélérat":["french"],"scénario":["french"],"sceptre":["french"],"schéma":["french"],"scinder":["french"],"score":["french"],"scrutin":["french"],"sculpter":["french"],"séance":["french"],"sécable":["french"],"sécher":["french"],"secouer":["french"],"sécréter":["french"],"sédatif":["french"],"séduire":["french"],"seigneur":["french"],"séjour":["french"],"sélectif":["french"],"semaine":["french"],"sembler":["french"],"semence":["french"],"séminal":["french"],"sénateur":["french"],"sensible":["french"],"séparer":["french"],"séquence":["french"],"serein":["french"],"sergent":["french"],"sérieux":["french"],"serrure":["french"],"sérum":["french"],"sésame":["french"],"sévir":["french"],"sevrage":["french"],"sextuple":["french"],"sidéral":["french"],"siècle":["french"],"siéger":["french"],"siffler":["french"],"sigle":["french"],"signal":["french"],"silence":["french"],"silicium":["french"],"sincère":["french"],"sinistre":["french"],"siphon":["french"],"sirop":["french"],"sismique":["french"],"situer":["french"],"skier":["french"],"socle":["french"],"sodium":["french"],"soigneux":["french"],"soldat":["french"],"soleil":["french"],"solitude":["french"],"soluble":["french"],"sombre":["french"],"sommeil":["french"],"somnoler":["french"],"sonde":["french"],"songeur":["french"],"sonnette":["french"],"sonore":["french"],"sorcier":["french"],"sortir":["french"],"sosie":["french"],"sottise":["french"],"soucieux":["french"],"soudure":["french"],"souffle":["french"],"soulever":["french"],"soupape":["french"],"soutirer":["french"],"souvenir":["french"],"spacieux":["french"],"spécial":["french"],"sphère":["french"],"spiral":["french","turkish"],"station":["french"],"sternum":["french"],"stimulus":["french"],"stipuler":["french"],"strict":["french"],"studieux":["french"],"stupeur":["french"],"styliste":["french"],"sublime":["french"],"substrat":["french"],"subtil":["french"],"subvenir":["french"],"succès":["french"],"sucre":["french"],"suffixe":["french"],"suggérer":["french"],"suiveur":["french"],"sulfate":["french"],"superbe":["french"],"supplier":["french"],"suricate":["french"],"surmener":["french"],"sursaut":["french"],"survie":["french"],"syllabe":["french"],"symbole":["french"],"symétrie":["french"],"synapse":["french"],"syntaxe":["french"],"système":["french"],"tabac":["french"],"tablier":["french"],"tactile":["french"],"tailler":["french"],"talisman":["french"],"talonner":["french"],"tambour":["french"],"tamiser":["french"],"tangible":["french"],"tapis":["french"],"taquiner":["french"],"tarder":["french"],"tarif":["french"],"tartine":["french"],"tasse":["french"],"tatami":["french"],"tatouage":["french"],"taupe":["french"],"taureau":["french"],"taxer":["french"],"témoin":["french"],"temporel":["french"],"tenaille":["french"],"tendre":["french"],"teneur":["french"],"tenir":["french"],"tension":["french"],"terminer":["french"],"terne":["french"],"terrible":["french"],"tétine":["french"],"texte":["french"],"thème":["french"],"théorie":["french"],"thérapie":["french"],"thorax":["french"],"tibia":["french"],"tiède":["french"],"timide":["french"],"tirelire":["french"],"tiroir":["french"],"tissu":["french"],"titane":["french"],"titre":["french"],"tituber":["french"],"toboggan":["french"],"tolérant":["french"],"tomate":["french"],"tonique":["french"],"tonneau":["french"],"toponyme":["french"],"torche":["french"],"tordre":["french"],"tornade":["french"],"torpille":["french"],"torrent":["french"],"torse":["french"],"tortue":["french"],"totem":["french"],"toucher":["french"],"tournage":["french"],"tousser":["french"],"toxine":["french"],"traction":["french"],"trafic":["french"],"tragique":["french"],"trahir":["french"],"trancher":["french"],"travail":["french"],"trèfle":["french"],"tremper":["french"],"trésor":["french"],"treuil":["french"],"triage":["french"],"tribunal":["french"],"tricoter":["french"],"trilogie":["french"],"triomphe":["french"],"tripler":["french"],"triturer":["french"],"trivial":["french"],"trombone":["french"],"tronc":["french"],"tropical":["french"],"troupeau":["french"],"tuile":["french"],"tulipe":["french"],"tumulte":["french"],"turbine":["french"],"tuteur":["french"],"tutoyer":["french"],"tuyau":["french"],"tympan":["french"],"typhon":["french"],"typique":["french"],"tyran":["french"],"ubuesque":["french"],"ultime":["french"],"ultrason":["french"],"unanime":["french"],"unifier":["french"],"union":["french"],"unitaire":["french"],"univers":["french"],"uranium":["french"],"urbain":["french"],"urticant":["french"],"usine":["french"],"usuel":["french"],"usure":["french"],"utile":["french"],"utopie":["french"],"vacarme":["french"],"vaccin":["french"],"vagabond":["french"],"vaillant":["french"],"vaincre":["french"],"vaisseau":["french"],"valable":["french"],"valise":["french"],"vallon":["french"],"vampire":["french"],"vanille":["french"],"vapeur":["french"],"varier":["french"],"vaseux":["french"],"vassal":["french"],"vaste":["french"],"vecteur":["french"],"vedette":["french"],"végétal":["french"],"véhicule":["french"],"veinard":["french"],"véloce":["french"],"vendredi":["french"],"vénérer":["french"],"venger":["french"],"venimeux":["french"],"ventouse":["french"],"verdure":["french"],"vérin":["french"],"vernir":["french"],"verrou":["french"],"verser":["french"],"vertu":["french"],"veston":["french"],"vétéran":["french"],"vétuste":["french"],"vexant":["french"],"vexer":["french"],"viaduc":["french"],"viande":["french"],"victoire":["french"],"vidange":["french"],"vidéo":["french"],"vignette":["french"],"vigueur":["french"],"vilain":["french"],"vinaigre":["french"],"violon":["french"],"vipère":["french"],"virement":["french"],"virtuose":["french"],"visage":["french"],"viseur":["french"],"vision":["french"],"visqueux":["french"],"visuel":["french"],"vitesse":["french"],"viticole":["french"],"vitrine":["french"],"vivace":["french"],"vivipare":["french"],"vocation":["french"],"voguer":["french"],"voile":["french"],"voisin":["french"],"voiture":["french"],"volaille":["french"],"volcan":["french"],"voltiger":["french"],"vorace":["french"],"vortex":["french"],"voter":["french"],"vouloir":["french"],"voyelle":["french"],"xénon":["french"],"yacht":["french"],"zèbre":["french"],"zénith":["french"],"zeste":["french"],"zoologie":["french"],"abaco":["italian"],"abbaglio":["italian"],"abbinato":["italian"],"abete":["italian"],"abisso":["italian"],"abolire":["italian"],"abrasivo":["italian"],"abrogato":["italian"],"accadere":["italian"],"accenno":["italian"],"accusato":["italian"],"acetone":["italian"],"achille":["italian"],"acido":["italian"],"acqua":["italian"],"acre":["italian"],"acrilico":["italian"],"acrobata":["italian"],"acuto":["italian"],"adagio":["italian"],"addebito":["italian"],"addome":["italian"],"adeguato":["italian"],"aderire":["italian"],"adipe":["italian"],"adottare":["italian"],"adulare":["italian"],"affabile":["italian"],"affetto":["italian"],"affisso":["italian"],"affranto":["italian"],"aforisma":["italian"],"afoso":["italian"],"africano":["italian"],"agave":["italian"],"agente":["italian"],"agevole":["italian"],"aggancio":["italian"],"agire":["italian"],"agitare":["italian"],"agonismo":["italian"],"agricolo":["italian"],"agrumeto":["italian"],"aguzzo":["italian"],"alabarda":["italian"],"alato":["italian"],"albatro":["italian"],"alberato":["italian"],"albo":["italian"],"albume":["italian"],"alce":["italian"],"alcolico":["italian"],"alettone":["italian"],"alfa":["italian"],"algebra":["italian"],"aliante":["italian"],"alibi":["italian"],"alimento":["italian"],"allagato":["italian"],"allegro":["italian"],"allievo":["italian"],"allodola":["italian"],"allusivo":["italian"],"almeno":["italian"],"alogeno":["italian"],"alpaca":["italian"],"alpestre":["italian"],"altalena":["italian"],"alterno":["italian"],"alticcio":["italian"],"altrove":["italian"],"alunno":["italian"],"alveolo":["italian"],"alzare":["italian"],"amalgama":["italian"],"amanita":["italian"],"amarena":["italian"],"ambito":["italian"],"ambrato":["italian"],"ameba":["italian"],"america":["italian"],"ametista":["italian"],"amico":["italian"],"ammasso":["italian"],"ammenda":["italian"],"ammirare":["italian"],"ammonito":["italian"],"amore":["italian"],"ampio":["italian"],"ampliare":["italian"],"amuleto":["italian"],"anacardo":["italian"],"anagrafe":["italian"],"analista":["italian"],"anarchia":["italian"],"anatra":["italian"],"anca":["italian"],"ancella":["italian"],"ancora":["italian"],"andare":["italian"],"andrea":["italian"],"anello":["italian"],"angelo":["italian"],"angolare":["italian"],"angusto":["italian"],"anima":["italian"],"annegare":["italian"],"annidato":["italian"],"anno":["italian"],"annuncio":["italian"],"anonimo":["italian"],"anticipo":["italian"],"anzi":["italian"],"apatico":["italian"],"apertura":["italian"],"apode":["italian"],"apparire":["italian"],"appetito":["italian"],"appoggio":["italian"],"approdo":["italian"],"appunto":["italian"],"aprile":["italian"],"arabica":["italian"],"arachide":["italian"],"aragosta":["italian"],"araldica":["italian"],"arancio":["italian"],"aratura":["italian"],"arazzo":["italian"],"arbitro":["italian"],"archivio":["italian"],"ardito":["italian"],"arenile":["italian"],"argento":["italian"],"argine":["italian"],"arguto":["italian"],"aria":["italian"],"armonia":["italian"],"arnese":["italian"],"arredato":["italian"],"arringa":["italian"],"arrosto":["italian"],"arsenico":["italian"],"arso":["italian"],"artefice":["italian"],"arzillo":["italian"],"asciutto":["italian"],"ascolto":["italian"],"asepsi":["italian"],"asettico":["italian"],"asfalto":["italian"],"asino":["italian"],"asola":["italian"],"aspirato":["italian"],"aspro":["italian"],"assaggio":["italian"],"asse":["italian"],"assoluto":["italian"],"assurdo":["italian"],"asta":["italian"],"astenuto":["italian"],"astice":["italian"],"astratto":["italian"],"atavico":["italian"],"ateismo":["italian"],"atomico":["italian"],"atono":["italian"],"attesa":["italian"],"attivare":["italian"],"attorno":["italian"],"attrito":["italian"],"attuale":["italian"],"ausilio":["italian"],"austria":["italian"],"autista":["italian"],"autonomo":["italian"],"autunno":["italian"],"avanzato":["italian"],"avere":["italian"],"avvenire":["italian"],"avviso":["italian"],"avvolgere":["italian"],"azione":["italian"],"azoto":["italian"],"azzimo":["italian"],"azzurro":["italian"],"babele":["italian"],"baccano":["italian"],"bacino":["italian"],"baco":["italian"],"badessa":["italian"],"badilata":["italian"],"bagnato":["italian"],"baita":["italian"],"balcone":["italian"],"baldo":["italian"],"balena":["italian"],"ballata":["italian"],"balzano":["italian"],"bambino":["italian"],"bandire":["italian"],"baraonda":["italian"],"barbaro":["italian"],"barca":["italian"],"baritono":["italian"],"barlume":["italian"],"barocco":["italian"],"basilico":["italian"],"basso":["italian"],"batosta":["italian"],"battuto":["italian"],"baule":["italian"],"bava":["italian"],"bavosa":["italian"],"becco":["italian"],"beffa":["italian"],"belgio":["italian"],"belva":["italian"],"benda":["italian"],"benevole":["italian"],"benigno":["italian"],"benzina":["italian"],"bere":["italian"],"berlina":["italian"],"beta":["italian"],"bibita":["italian"],"bici":["italian"],"bidone":["italian"],"bifido":["italian"],"biga":["italian"],"bilancia":["italian"],"bimbo":["italian"],"binocolo":["italian"],"biologo":["italian"],"bipede":["italian"],"bipolare":["italian"],"birbante":["italian"],"birra":["italian"],"biscotto":["italian"],"bisesto":["italian"],"bisnonno":["italian"],"bisonte":["italian"],"bisturi":["italian"],"bizzarro":["italian"],"blando":["italian"],"blatta":["italian"],"bollito":["italian"],"bonifico":["italian"],"bordo":["italian"],"bosco":["italian"],"botanico":["italian"],"bottino":["italian"],"bozzolo":["italian"],"braccio":["italian"],"bradipo":["italian"],"brama":["italian"],"branca":["italian"],"bravura":["italian"],"bretella":["italian"],"brevetto":["italian"],"brezza":["italian"],"briglia":["italian"],"brillante":["italian"],"brindare":["italian"],"broccolo":["italian"],"brodo":["italian"],"bronzina":["italian"],"brullo":["italian"],"bruno":["italian"],"bubbone":["italian"],"buca":["italian"],"budino":["italian"],"buffone":["italian"],"buio":["italian"],"bulbo":["italian"],"buono":["italian"],"burlone":["italian"],"burrasca":["italian"],"bussola":["italian"],"busta":["italian"],"cadetto":["italian"],"caduco":["italian"],"calamaro":["italian"],"calcolo":["italian"],"calesse":["italian"],"calibro":["italian"],"calmo":["italian"],"caloria":["italian"],"cambusa":["italian"],"camerata":["italian"],"camicia":["italian"],"cammino":["italian"],"camola":["italian"],"campale":["italian"],"canapa":["italian"],"candela":["italian"],"cane":["italian"],"canino":["italian"],"canotto":["italian"],"cantina":["italian"],"capace":["italian"],"capello":["italian"],"capitolo":["italian"],"capogiro":["italian"],"cappero":["italian"],"capra":["italian"],"capsula":["italian"],"carapace":["italian"],"carcassa":["italian"],"cardo":["italian"],"carisma":["italian"],"carovana":["italian"],"carretto":["italian"],"cartolina":["italian"],"casaccio":["italian"],"cascata":["italian"],"caserma":["italian"],"caso":["italian"],"cassone":["italian"],"castello":["italian"],"casuale":["italian"],"catasta":["italian"],"catena":["italian"],"catrame":["italian"],"cauto":["italian"],"cavillo":["italian"],"cedibile":["italian"],"cedrata":["italian"],"cefalo":["italian"],"celebre":["italian"],"cellulare":["italian"],"cena":["italian"],"cenone":["italian"],"centesimo":["italian"],"ceramica":["italian"],"cercare":["italian"],"certo":["italian"],"cerume":["italian"],"cervello":["italian"],"cesoia":["italian"],"cespo":["italian"],"ceto":["italian"],"chela":["italian"],"chiaro":["italian"],"chicca":["italian"],"chiedere":["italian"],"chimera":["italian"],"china":["italian"],"chirurgo":["italian"],"chitarra":["italian"],"ciao":["italian"],"ciclismo":["italian"],"cifrare":["italian"],"cigno":["italian"],"cilindro":["italian"],"ciottolo":["italian"],"circa":["italian"],"cirrosi":["italian"],"citrico":["italian"],"cittadino":["italian"],"ciuffo":["italian"],"civetta":["italian"],"civile":["italian"],"classico":["italian"],"clinica":["italian"],"cloro":["italian"],"cocco":["italian"],"codardo":["italian"],"codice":["italian"],"coerente":["italian"],"cognome":["italian"],"collare":["italian"],"colmato":["italian"],"colore":["italian"],"colposo":["italian"],"coltivato":["italian"],"colza":["italian"],"coma":["italian"],"cometa":["italian"],"commando":["italian"],"comodo":["italian"],"computer":["italian"],"comune":["italian"],"conciso":["italian"],"condurre":["italian"],"conferma":["italian"],"congelare":["italian"],"coniuge":["italian"],"connesso":["italian"],"conoscere":["italian"],"consumo":["italian"],"continuo":["italian"],"convegno":["italian"],"coperto":["italian"],"copione":["italian"],"coppia":["italian"],"copricapo":["italian"],"corazza":["italian"],"cordata":["italian"],"coricato":["italian"],"cornice":["italian"],"corolla":["italian"],"corpo":["italian"],"corredo":["italian"],"corsia":["italian"],"cortese":["italian"],"cosmico":["italian"],"costante":["italian"],"cottura":["italian"],"covato":["italian"],"cratere":["italian"],"cravatta":["italian"],"creato":["italian"],"credere":["italian"],"cremoso":["italian"],"crescita":["italian"],"creta":["italian"],"criceto":["italian"],"crinale":["italian"],"crisi":["italian"],"critico":["italian"],"croce":["italian"],"cronaca":["italian"],"crostata":["italian"],"cruciale":["italian"],"crusca":["italian"],"cucire":["italian"],"cuculo":["italian"],"cugino":["italian"],"cullato":["italian"],"cupola":["italian"],"curatore":["italian"],"cursore":["italian"],"curvo":["italian"],"cuscino":["italian"],"custode":["italian"],"dado":["italian"],"daino":["italian"],"dalmata":["italian"],"damerino":["italian"],"daniela":["italian"],"dannoso":["italian"],"danzare":["italian"],"datato":["italian"],"davanti":["italian"],"davvero":["italian"],"debutto":["italian"],"decennio":["italian"],"deciso":["italian"],"declino":["italian"],"decollo":["italian"],"decreto":["italian"],"dedicato":["italian"],"definito":["italian"],"deforme":["italian"],"degno":["italian"],"delegare":["italian"],"delfino":["italian"],"delirio":["italian"],"delta":["italian"],"demenza":["italian"],"denotato":["italian"],"dentro":["italian"],"deposito":["italian"],"derapata":["italian"],"derivare":["italian"],"deroga":["italian"],"descritto":["italian"],"deserto":["italian"],"desiderio":["italian"],"desumere":["italian"],"detersivo":["italian"],"devoto":["italian"],"diametro":["italian"],"dicembre":["italian"],"diedro":["italian"],"difeso":["italian"],"diffuso":["italian"],"digerire":["italian"],"digitale":["italian"],"diluvio":["italian"],"dinamico":["italian"],"dinnanzi":["italian"],"dipinto":["italian"],"diploma":["italian"],"dipolo":["italian"],"diradare":["italian"],"dire":["italian"],"dirotto":["italian"],"dirupo":["italian"],"disagio":["italian"],"discreto":["italian"],"disfare":["italian"],"disgelo":["italian"],"disposto":["italian"],"distanza":["italian"],"disumano":["italian"],"dito":["italian"],"divano":["italian"],"divelto":["italian"],"dividere":["italian"],"divorato":["italian"],"doblone":["italian"],"docente":["italian"],"doganale":["italian"],"dogma":["italian"],"dolce":["italian"],"domato":["italian"],"domenica":["italian"],"dominare":["italian"],"dondolo":["italian"],"dono":["italian"],"dormire":["italian"],"dote":["italian"],"dottore":["italian"],"dovuto":["italian"],"dozzina":["italian"],"drago":["italian"],"druido":["italian"],"dubbio":["italian"],"dubitare":["italian"],"ducale":["italian"],"duna":["italian"],"duomo":["italian"],"duplice":["italian"],"duraturo":["italian"],"ebano":["italian"],"eccesso":["italian"],"ecco":["italian"],"eclissi":["italian"],"economia":["italian"],"edera":["italian"],"edicola":["italian"],"edile":["italian"],"editoria":["italian"],"educare":["italian"],"egemonia":["italian"],"egli":["italian"],"egoismo":["italian"],"egregio":["italian"],"elaborato":["italian"],"elargire":["italian"],"elegante":["italian"],"elencato":["italian"],"eletto":["italian"],"elevare":["italian"],"elfico":["italian"],"elica":["italian"],"elmo":["italian"],"elsa":["italian"],"eluso":["italian"],"emanato":["italian"],"emblema":["italian"],"emesso":["italian"],"emiro":["italian"],"emotivo":["italian"],"emozione":["italian"],"empirico":["italian"],"emulo":["italian"],"endemico":["italian"],"enduro":["italian"],"energia":["italian"],"enfasi":["italian"],"enoteca":["italian"],"entrare":["italian"],"enzima":["italian"],"epatite":["italian"],"epilogo":["italian"],"episodio":["italian"],"epocale":["italian"],"eppure":["italian"],"equatore":["italian"],"erario":["italian"],"erba":["italian"],"erboso":["italian"],"erede":["italian"],"eremita":["italian"],"erigere":["italian"],"ermetico":["italian"],"eroe":["italian"],"erosivo":["italian"],"errante":["italian"],"esagono":["italian"],"esame":["italian"],"esanime":["italian"],"esaudire":["italian"],"esca":["italian"],"esempio":["italian"],"esercito":["italian"],"esibito":["italian"],"esigente":["italian"],"esistere":["italian"],"esito":["italian"],"esofago":["italian"],"esortato":["italian"],"esoso":["italian"],"espanso":["italian"],"espresso":["italian"],"essenza":["italian"],"esso":["italian"],"esteso":["italian"],"estimare":["italian"],"estonia":["italian"],"estroso":["italian"],"esultare":["italian"],"etilico":["italian"],"etnico":["italian"],"etrusco":["italian"],"etto":["italian"],"euclideo":["italian"],"europa":["italian"],"evaso":["italian"],"evidenza":["italian"],"evitato":["italian"],"evoluto":["italian"],"evviva":["italian"],"fabbrica":["italian"],"faccenda":["italian"],"fachiro":["italian"],"falco":["italian"],"famiglia":["italian"],"fanale":["italian"],"fanfara":["italian"],"fango":["italian"],"fantasma":["italian"],"fare":["italian"],"farfalla":["italian"],"farinoso":["italian"],"farmaco":["italian"],"fascia":["italian"],"fastoso":["italian"],"fasullo":["italian"],"faticare":["italian"],"fato":["italian"],"favoloso":["italian"],"febbre":["italian"],"fecola":["italian"],"fede":["italian"],"fegato":["italian"],"felpa":["italian"],"feltro":["italian"],"femmina":["italian"],"fendere":["italian"],"fenomeno":["italian"],"fermento":["italian"],"ferro":["italian"],"fertile":["italian"],"fessura":["italian"],"festivo":["italian"],"fetta":["italian"],"feudo":["italian"],"fiaba":["italian"],"fiducia":["italian"],"fifa":["italian"],"figurato":["italian"],"filo":["italian","turkish"],"finanza":["italian"],"finestra":["italian"],"finire":["italian"],"fiore":["italian"],"fiscale":["italian"],"fisico":["italian"],"fiume":["italian"],"flacone":["italian"],"flamenco":["italian"],"flebo":["italian"],"flemma":["italian"],"florido":["italian"],"fluente":["italian"],"fluoro":["italian"],"fobico":["italian"],"focaccia":["italian"],"focoso":["italian"],"foderato":["italian"],"foglio":["italian"],"folata":["italian"],"folclore":["italian"],"folgore":["italian"],"fondente":["italian"],"fonetico":["italian"],"fonia":["italian"],"fontana":["italian"],"forbito":["italian"],"forchetta":["italian"],"foresta":["italian"],"formica":["italian"],"fornaio":["italian"],"foro":["italian"],"fortezza":["italian"],"forzare":["italian"],"fosfato":["italian"],"fosso":["italian"],"fracasso":["italian"],"frana":["italian"],"frassino":["italian"],"fratello":["italian"],"freccetta":["italian"],"frenata":["italian"],"fresco":["italian"],"frigo":["italian"],"frollino":["italian"],"fronde":["italian"],"frugale":["italian"],"frutta":["italian"],"fucilata":["italian"],"fucsia":["italian"],"fuggente":["italian"],"fulmine":["italian"],"fulvo":["italian"],"fumante":["italian"],"fumetto":["italian"],"fumoso":["italian"],"fune":["italian"],"funzione":["italian"],"fuoco":["italian"],"furbo":["italian"],"furgone":["italian"],"furore":["italian"],"fuso":["italian"],"futile":["italian"],"gabbiano":["italian"],"gaffe":["italian"],"galateo":["italian"],"gallina":["italian"],"galoppo":["italian"],"gambero":["italian"],"gamma":["italian"],"garanzia":["italian"],"garbo":["italian"],"garofano":["italian"],"garzone":["italian"],"gasdotto":["italian"],"gasolio":["italian"],"gastrico":["italian"],"gatto":["italian"],"gaudio":["italian"],"gazebo":["italian"],"gazzella":["italian"],"geco":["italian"],"gelatina":["italian"],"gelso":["italian"],"gemello":["italian"],"gemmato":["italian"],"gene":["italian"],"genitore":["italian"],"gennaio":["italian"],"genotipo":["italian"],"gergo":["italian"],"ghepardo":["italian"],"ghiaccio":["italian"],"ghisa":["italian"],"giallo":["italian"],"gilda":["italian"],"ginepro":["italian"],"giocare":["italian"],"gioiello":["italian"],"giorno":["italian"],"giove":["italian"],"girato":["italian"],"girone":["italian"],"gittata":["italian"],"giudizio":["italian"],"giurato":["italian"],"giusto":["italian"],"globulo":["italian"],"glutine":["italian"],"gnomo":["italian"],"gobba":["italian"],"golf":["italian"],"gomito":["italian"],"gommone":["italian"],"gonfio":["italian"],"gonna":["italian"],"governo":["italian"],"gracile":["italian"],"grado":["italian"],"grafico":["italian"],"grammo":["italian"],"grande":["italian"],"grattare":["italian"],"gravoso":["italian"],"grazia":["italian"],"greca":["italian"],"gregge":["italian"],"grifone":["italian"],"grigio":["italian"],"grinza":["italian"],"grotta":["italian"],"gruppo":["italian"],"guadagno":["italian"],"guaio":["italian"],"guanto":["italian"],"guardare":["italian"],"gufo":["italian"],"guidare":["italian"],"ibernato":["italian"],"icona":["italian"],"identico":["italian"],"idillio":["italian"],"idolo":["italian"],"idra":["italian"],"idrico":["italian"],"idrogeno":["italian"],"igiene":["italian"],"ignaro":["italian"],"ignorato":["italian"],"ilare":["italian"],"illeso":["italian"],"illogico":["italian"],"illudere":["italian"],"imballo":["italian"],"imbevuto":["italian"],"imbocco":["italian"],"imbuto":["italian"],"immane":["italian"],"immerso":["italian"],"immolato":["italian"],"impacco":["italian"],"impeto":["italian"],"impiego":["italian"],"importo":["italian"],"impronta":["italian"],"inalare":["italian"],"inarcare":["italian"],"inattivo":["italian"],"incanto":["italian"],"incendio":["italian"],"inchino":["italian"],"incisivo":["italian"],"incluso":["italian"],"incontro":["italian"],"incrocio":["italian"],"incubo":["italian"],"indagine":["italian"],"india":["italian"],"indole":["italian"],"inedito":["italian"],"infatti":["italian"],"infilare":["italian"],"inflitto":["italian"],"ingaggio":["italian"],"ingegno":["italian"],"inglese":["italian"],"ingordo":["italian"],"ingrosso":["italian"],"innesco":["italian"],"inodore":["italian"],"inoltrare":["italian"],"inondato":["italian"],"insano":["italian"],"insetto":["italian"],"insieme":["italian"],"insonnia":["italian"],"insulina":["italian"],"intasato":["italian"],"intero":["italian"],"intonaco":["italian"],"intuito":["italian"],"inumidire":["italian"],"invalido":["italian"],"invece":["italian"],"invito":["italian"],"iperbole":["italian"],"ipnotico":["italian"],"ipotesi":["italian"],"ippica":["italian"],"iride":["italian"],"irlanda":["italian"],"ironico":["italian"],"irrigato":["italian"],"irrorare":["italian"],"isolato":["italian"],"isotopo":["italian"],"isterico":["italian"],"istituto":["italian"],"istrice":["italian"],"italia":["italian"],"iterare":["italian"],"labbro":["italian"],"labirinto":["italian"],"lacca":["italian"],"lacerato":["italian"],"lacrima":["italian"],"lacuna":["italian"],"laddove":["italian"],"lago":["italian"],"lampo":["italian"],"lancetta":["italian"],"lanterna":["italian"],"lardoso":["italian"],"larga":["italian"],"laringe":["italian"],"lastra":["italian"],"latenza":["italian"],"latino":["italian"],"lattuga":["italian"],"lavagna":["italian"],"lavoro":["italian"],"legale":["italian"],"leggero":["italian"],"lembo":["italian"],"lentezza":["italian"],"lenza":["italian"],"leone":["italian"],"lepre":["italian"],"lesivo":["italian"],"lessato":["italian"],"lesto":["italian"],"letterale":["italian"],"leva":["italian"],"levigato":["italian"],"libero":["italian"],"lido":["italian"],"lievito":["italian"],"lilla":["italian"],"limatura":["italian"],"limitare":["italian"],"limpido":["italian"],"lineare":["italian"],"lingua":["italian"],"liquido":["italian"],"lira":["italian"],"lirica":["italian"],"lisca":["italian"],"lite":["italian"],"litigio":["italian"],"livrea":["italian"],"locanda":["italian"],"lode":["italian"],"logica":["italian"],"lombare":["italian"],"londra":["italian"],"longevo":["italian"],"loquace":["italian"],"lorenzo":["italian"],"loto":["italian"],"lotteria":["italian"],"luce":["italian"],"lucidato":["italian"],"lumaca":["italian"],"luminoso":["italian"],"lungo":["italian"],"lupo":["italian"],"luppolo":["italian"],"lusinga":["italian"],"lusso":["italian"],"lutto":["italian"],"macabro":["italian"],"macchina":["italian"],"macero":["italian"],"macinato":["italian"],"madama":["italian"],"magico":["italian"],"maglia":["italian"],"magnete":["italian"],"magro":["italian"],"maiolica":["italian"],"malafede":["italian"],"malgrado":["italian"],"malinteso":["italian"],"malsano":["italian"],"malto":["italian"],"malumore":["italian"],"mana":["italian"],"mancia":["italian"],"mandorla":["italian"],"mangiare":["italian"],"manifesto":["italian"],"mannaro":["italian"],"manovra":["italian"],"mansarda":["italian"],"mantide":["italian"],"manubrio":["italian"],"mappa":["italian"],"maratona":["italian"],"marcire":["italian"],"maretta":["italian"],"marmo":["italian"],"marsupio":["italian"],"maschera":["italian"],"massaia":["italian"],"mastino":["italian"],"materasso":["italian"],"matricola":["italian"],"mattone":["italian"],"maturo":["italian"],"mazurca":["italian"],"meandro":["italian"],"meccanico":["italian"],"mecenate":["italian"],"medesimo":["italian"],"meditare":["italian"],"mega":["italian"],"melassa":["italian"],"melis":["italian"],"melodia":["italian"],"meninge":["italian"],"meno":["italian"],"mensola":["italian"],"mercurio":["italian"],"merenda":["italian"],"merlo":["italian"],"meschino":["italian"],"mese":["italian"],"messere":["italian"],"mestolo":["italian"],"metallo":["italian"],"metodo":["italian"],"mettere":["italian"],"miagolare":["italian"],"mica":["italian"],"micelio":["italian"],"michele":["italian"],"microbo":["italian"],"midollo":["italian"],"miele":["italian"],"migliore":["italian"],"milano":["italian"],"milite":["italian"],"mimosa":["italian"],"minerale":["italian"],"mini":["italian"],"minore":["italian"],"mirino":["italian"],"mirtillo":["italian"],"miscela":["italian"],"missiva":["italian"],"misto":["italian"],"misurare":["italian"],"mitezza":["italian"],"mitigare":["italian"],"mitra":["italian"],"mittente":["italian"],"mnemonico":["italian"],"modello":["italian"],"modifica":["italian"],"modulo":["italian"],"mogano":["italian"],"mogio":["italian"],"mole":["italian"],"molosso":["italian"],"monastero":["italian"],"monco":["italian"],"mondina":["italian"],"monetario":["italian"],"monile":["italian"],"monotono":["italian"],"monsone":["italian"],"montato":["italian"],"monviso":["italian"],"mora":["italian"],"mordere":["italian"],"morsicato":["italian"],"mostro":["italian"],"motivato":["italian"],"motosega":["italian"],"motto":["italian"],"movenza":["italian"],"movimento":["italian"],"mozzo":["italian"],"mucca":["italian"],"mucosa":["italian"],"muffa":["italian"],"mughetto":["italian"],"mugnaio":["italian"],"mulatto":["italian"],"mulinello":["italian"],"multiplo":["italian"],"mummia":["italian"],"munto":["italian"],"muovere":["italian"],"murale":["italian"],"musa":["italian"],"muscolo":["italian"],"musica":["italian"],"mutevole":["italian"],"muto":["italian"],"nababbo":["italian"],"nafta":["italian"],"nanometro":["italian"],"narciso":["italian"],"narice":["italian"],"narrato":["italian"],"nascere":["italian"],"nastrare":["italian"],"naturale":["italian"],"nautica":["italian"],"naviglio":["italian"],"nebulosa":["italian"],"necrosi":["italian"],"negativo":["italian"],"negozio":["italian"],"nemmeno":["italian"],"neofita":["italian"],"neretto":["italian"],"nervo":["italian"],"nessuno":["italian"],"nettuno":["italian"],"neutrale":["italian"],"neve":["italian"],"nevrotico":["italian"],"nicchia":["italian"],"ninfa":["italian"],"nitido":["italian"],"nobile":["italian"],"nocivo":["italian"],"nodo":["italian"],"nome":["italian"],"nomina":["italian"],"nordico":["italian"],"normale":["italian"],"norvegese":["italian"],"nostrano":["italian"],"notare":["italian"],"notizia":["italian"],"notturno":["italian"],"novella":["italian"],"nucleo":["italian"],"nulla":["italian"],"numero":["italian"],"nuovo":["italian"],"nutrire":["italian"],"nuvola":["italian"],"nuziale":["italian"],"oasi":["italian"],"obbedire":["italian"],"obbligo":["italian"],"obelisco":["italian"],"oblio":["italian"],"obolo":["italian"],"obsoleto":["italian"],"occasione":["italian"],"occhio":["italian"],"occidente":["italian"],"occorrere":["italian"],"occultare":["italian"],"ocra":["italian"],"oculato":["italian"],"odierno":["italian"],"odorare":["italian"],"offerta":["italian"],"offrire":["italian"],"offuscato":["italian"],"oggetto":["italian"],"oggi":["italian"],"ognuno":["italian"],"olandese":["italian"],"olfatto":["italian"],"oliato":["italian"],"oliva":["italian"],"ologramma":["italian"],"oltre":["italian"],"omaggio":["italian"],"ombelico":["italian"],"ombra":["italian"],"omega":["italian"],"omissione":["italian"],"ondoso":["italian"],"onere":["italian"],"onice":["italian"],"onnivoro":["italian"],"onorevole":["italian"],"onta":["italian"],"operato":["italian"],"opinione":["italian"],"opposto":["italian"],"oracolo":["italian"],"orafo":["italian"],"ordine":["italian"],"orecchino":["italian"],"orefice":["italian"],"orfano":["italian"],"organico":["italian"],"origine":["italian"],"orizzonte":["italian"],"orma":["italian"],"ormeggio":["italian"],"ornativo":["italian"],"orologio":["italian"],"orrendo":["italian"],"orribile":["italian"],"ortensia":["italian"],"ortica":["italian"],"orzata":["italian"],"orzo":["italian"],"osare":["italian"],"oscurare":["italian"],"osmosi":["italian"],"ospedale":["italian"],"ospite":["italian"],"ossa":["italian"],"ossidare":["italian"],"ostacolo":["italian"],"oste":["italian"],"otite":["italian"],"otre":["italian"],"ottagono":["italian"],"ottimo":["italian"],"ottobre":["italian"],"ovale":["italian"],"ovest":["italian"],"ovino":["italian"],"oviparo":["italian"],"ovocito":["italian"],"ovunque":["italian"],"ovviare":["italian"],"ozio":["italian"],"pacchetto":["italian"],"pace":["italian"],"pacifico":["italian"],"padella":["italian"],"padrone":["italian"],"paese":["italian"],"paga":["italian"],"pagina":["italian"],"palazzina":["italian"],"palesare":["italian"],"pallido":["italian"],"palo":["italian"],"palude":["italian"],"pandoro":["italian"],"pannello":["italian"],"paolo":["italian"],"paonazzo":["italian"],"paprica":["italian"],"parabola":["italian"],"parcella":["italian"],"parere":["italian"],"pargolo":["italian"],"pari":["italian"],"parlato":["italian"],"parola":["italian"],"partire":["italian"],"parvenza":["italian"],"parziale":["italian"],"passivo":["italian"],"pasticca":["italian"],"patacca":["italian"],"patologia":["italian"],"pattume":["italian"],"pavone":["italian"],"peccato":["italian"],"pedalare":["italian"],"pedonale":["italian"],"peggio":["italian"],"peloso":["italian"],"penare":["italian"],"pendice":["italian"],"penisola":["italian"],"pennuto":["italian"],"penombra":["italian"],"pensare":["italian"],"pentola":["italian"],"pepe":["italian"],"pepita":["italian"],"perbene":["italian"],"percorso":["italian"],"perdonato":["italian"],"perforare":["italian"],"pergamena":["italian"],"periodo":["italian"],"permesso":["italian"],"perno":["italian"],"perplesso":["italian"],"persuaso":["italian"],"pertugio":["italian"],"pervaso":["italian"],"pesatore":["italian"],"pesista":["italian"],"peso":["italian"],"pestifero":["italian"],"petalo":["italian"],"pettine":["italian"],"petulante":["italian"],"pezzo":["italian"],"piacere":["italian"],"pianta":["italian"],"piattino":["italian"],"piccino":["italian"],"picozza":["italian"],"piega":["italian"],"pietra":["italian"],"piffero":["italian"],"pigiama":["italian"],"pigolio":["italian"],"pigro":["italian"],"pila":["italian"],"pilifero":["italian"],"pillola":["italian"],"pilota":["italian"],"pimpante":["italian"],"pineta":["italian"],"pinna":["italian"],"pinolo":["italian"],"pioggia":["italian"],"piombo":["italian"],"piramide":["italian"],"piretico":["italian"],"pirite":["italian"],"pirolisi":["italian"],"pitone":["italian"],"pizzico":["italian"],"placebo":["italian"],"planare":["italian"],"plasma":["italian"],"platano":["italian"],"plenario":["italian"],"pochezza":["italian"],"poderoso":["italian"],"podismo":["italian"],"poesia":["italian"],"poggiare":["italian"],"polenta":["italian"],"poligono":["italian"],"pollice":["italian"],"polmonite":["italian"],"polpetta":["italian"],"polso":["italian"],"poltrona":["italian"],"polvere":["italian"],"pomice":["italian"],"pomodoro":["italian"],"ponte":["italian"],"popoloso":["italian"],"porfido":["italian"],"poroso":["italian"],"porpora":["italian"],"porre":["italian"],"portata":["italian"],"posa":["italian","turkish"],"positivo":["italian"],"possesso":["italian"],"postulato":["italian"],"potassio":["italian"],"potere":["italian"],"pranzo":["italian"],"prassi":["italian"],"pratica":["italian"],"precluso":["italian"],"predica":["italian"],"prefisso":["italian"],"pregiato":["italian"],"prelievo":["italian"],"premere":["italian"],"prenotare":["italian"],"preparato":["italian"],"presenza":["italian"],"pretesto":["italian"],"prevalso":["italian"],"prima":["italian"],"principe":["italian"],"privato":["italian"],"problema":["italian"],"procura":["italian"],"produrre":["italian"],"profumo":["italian"],"progetto":["italian"],"prolunga":["italian"],"promessa":["italian"],"pronome":["italian"],"proposta":["italian"],"proroga":["italian"],"proteso":["italian"],"prova":["italian","turkish"],"prudente":["italian"],"prugna":["italian"],"prurito":["italian"],"psiche":["italian"],"pubblico":["italian"],"pudica":["italian"],"pugilato":["italian"],"pugno":["italian"],"pulce":["italian"],"pulito":["italian"],"pulsante":["italian"],"puntare":["italian"],"pupazzo":["italian"],"pupilla":["italian"],"puro":["italian"],"quadro":["italian"],"qualcosa":["italian"],"quasi":["italian"],"querela":["italian"],"quota":["italian"],"raccolto":["italian"],"raddoppio":["italian"],"radicale":["italian"],"radunato":["italian"],"raffica":["italian"],"ragazzo":["italian"],"ragione":["italian"],"ragno":["italian"],"ramarro":["italian"],"ramingo":["italian"],"ramo":["italian"],"randagio":["italian"],"rantolare":["italian"],"rapato":["italian"],"rapina":["italian"],"rappreso":["italian"],"rasatura":["italian"],"raschiato":["italian"],"rasente":["italian"],"rassegna":["italian"],"rastrello":["italian"],"rata":["italian"],"ravveduto":["italian"],"reale":["italian"],"recepire":["italian"],"recinto":["italian"],"recluta":["italian"],"recondito":["italian"],"recupero":["italian"],"reddito":["italian"],"redimere":["italian"],"regalato":["italian"],"registro":["italian"],"regola":["italian"],"regresso":["italian"],"relazione":["italian"],"remare":["italian"],"remoto":["italian"],"renna":["italian"],"replica":["italian"],"reprimere":["italian"],"reputare":["italian"],"resa":["italian"],"residente":["italian"],"responso":["italian"],"restauro":["italian"],"rete":["italian"],"retina":["italian"],"retorica":["italian"],"rettifica":["italian"],"revocato":["italian"],"riassunto":["italian"],"ribadire":["italian"],"ribelle":["italian"],"ribrezzo":["italian"],"ricarica":["italian"],"ricco":["italian"],"ricevere":["italian"],"riciclato":["italian"],"ricordo":["italian"],"ricreduto":["italian"],"ridicolo":["italian"],"ridurre":["italian"],"rifasare":["italian"],"riflesso":["italian"],"riforma":["italian"],"rifugio":["italian"],"rigare":["italian"],"rigettato":["italian"],"righello":["italian"],"rilassato":["italian"],"rilevato":["italian"],"rimanere":["italian"],"rimbalzo":["italian"],"rimedio":["italian"],"rimorchio":["italian"],"rinascita":["italian"],"rincaro":["italian"],"rinforzo":["italian"],"rinnovo":["italian"],"rinomato":["italian"],"rinsavito":["italian"],"rintocco":["italian"],"rinuncia":["italian"],"rinvenire":["italian"],"riparato":["italian"],"ripetuto":["italian"],"ripieno":["italian"],"riportare":["italian"],"ripresa":["italian"],"ripulire":["italian"],"risata":["italian"],"rischio":["italian"],"riserva":["italian"],"risibile":["italian"],"riso":["italian"],"rispetto":["italian"],"ristoro":["italian"],"risultato":["italian"],"risvolto":["italian"],"ritardo":["italian"],"ritegno":["italian"],"ritmico":["italian"],"ritrovo":["italian"],"riunione":["italian"],"riva":["italian"],"riverso":["italian"],"rivincita":["italian"],"rivolto":["italian"],"rizoma":["italian"],"roba":["italian"],"robotico":["italian"],"robusto":["italian"],"roccia":["italian"],"roco":["italian"],"rodaggio":["italian"],"rodere":["italian"],"roditore":["italian"],"rogito":["italian"],"rollio":["italian"],"romantico":["italian"],"rompere":["italian"],"ronzio":["italian"],"rosolare":["italian"],"rospo":["italian"],"rotante":["italian"],"rotondo":["italian"],"rotula":["italian"],"rovescio":["italian"],"rubizzo":["italian"],"rubrica":["italian"],"ruga":["italian"],"rullino":["italian"],"rumine":["italian"],"rumoroso":["italian"],"ruolo":["italian"],"rupe":["italian"],"russare":["italian"],"rustico":["italian"],"sabato":["italian"],"sabbiare":["italian"],"sabotato":["italian"],"sagoma":["italian"],"salasso":["italian"],"saldatura":["italian"],"salgemma":["italian"],"salivare":["italian"],"salmone":["italian"],"salone":["italian"],"saltare":["italian"],"saluto":["italian"],"salvo":["italian"],"sapere":["italian"],"sapido":["italian"],"saporito":["italian"],"saraceno":["italian"],"sarcasmo":["italian"],"sarto":["italian"],"sassoso":["italian"],"satellite":["italian"],"satira":["italian"],"satollo":["italian"],"saturno":["italian"],"savana":["italian"],"savio":["italian"],"saziato":["italian"],"sbadiglio":["italian"],"sbalzo":["italian"],"sbancato":["italian"],"sbarra":["italian"],"sbattere":["italian"],"sbavare":["italian"],"sbendare":["italian"],"sbirciare":["italian"],"sbloccato":["italian"],"sbocciato":["italian"],"sbrinare":["italian"],"sbruffone":["italian"],"sbuffare":["italian"],"scabroso":["italian"],"scadenza":["italian"],"scala":["italian"],"scambiare":["italian"],"scandalo":["italian"],"scapola":["italian"],"scarso":["italian"],"scatenare":["italian"],"scavato":["italian"],"scelto":["italian"],"scenico":["italian"],"scettro":["italian"],"scheda":["italian"],"schiena":["italian"],"sciarpa":["italian"],"scienza":["italian"],"scindere":["italian"],"scippo":["italian"],"sciroppo":["italian"],"scivolo":["italian"],"sclerare":["italian"],"scodella":["italian"],"scolpito":["italian"],"scomparto":["italian"],"sconforto":["italian"],"scoprire":["italian"],"scorta":["italian"],"scossone":["italian"],"scozzese":["italian"],"scriba":["italian"],"scrollare":["italian"],"scrutinio":["italian"],"scuderia":["italian"],"scultore":["italian"],"scuola":["italian"],"scuro":["italian"],"scusare":["italian"],"sdebitare":["italian"],"sdoganare":["italian"],"seccatura":["italian"],"secondo":["italian"],"sedano":["italian"],"seggiola":["italian"],"segnalato":["italian"],"segregato":["italian"],"seguito":["italian"],"selciato":["italian"],"selettivo":["italian"],"sella":["italian"],"selvaggio":["italian"],"semaforo":["italian"],"sembrare":["italian"],"seme":["italian"],"seminato":["italian"],"sempre":["italian"],"senso":["italian"],"sentire":["italian"],"sepolto":["italian"],"sequenza":["italian"],"serata":["italian"],"serbato":["italian"],"sereno":["italian"],"serio":["italian"],"serpente":["italian"],"serraglio":["italian"],"servire":["italian"],"sestina":["italian"],"setola":["italian"],"settimana":["italian"],"sfacelo":["italian"],"sfaldare":["italian"],"sfamato":["italian"],"sfarzoso":["italian"],"sfaticato":["italian"],"sfera":["italian"],"sfida":["italian"],"sfilato":["italian"],"sfinge":["italian"],"sfocato":["italian"],"sfoderare":["italian"],"sfogo":["italian"],"sfoltire":["italian"],"sforzato":["italian"],"sfratto":["italian"],"sfruttato":["italian"],"sfuggito":["italian"],"sfumare":["italian"],"sfuso":["italian"],"sgabello":["italian"],"sgarbato":["italian"],"sgonfiare":["italian"],"sgorbio":["italian"],"sgrassato":["italian"],"sguardo":["italian"],"sibilo":["italian"],"siccome":["italian"],"sierra":["italian"],"sigla":["italian"],"signore":["italian"],"silenzio":["italian"],"sillaba":["italian"],"simbolo":["italian"],"simpatico":["italian"],"simulato":["italian"],"sinfonia":["italian"],"singolo":["italian"],"sinistro":["italian"],"sino":["italian"],"sintesi":["italian"],"sinusoide":["italian"],"sipario":["italian"],"sisma":["italian"],"sistole":["italian"],"situato":["italian"],"slitta":["italian"],"slogatura":["italian"],"sloveno":["italian"],"smarrito":["italian"],"smemorato":["italian"],"smentito":["italian"],"smeraldo":["italian"],"smilzo":["italian"],"smontare":["italian"],"smottato":["italian"],"smussato":["italian"],"snellire":["italian"],"snervato":["italian"],"snodo":["italian"],"sobbalzo":["italian"],"sobrio":["italian"],"soccorso":["italian"],"sociale":["italian"],"sodale":["italian"],"soffitto":["italian"],"sogno":["italian"],"soldato":["italian"],"solenne":["italian"],"solido":["italian"],"sollazzo":["italian"],"solo":["italian"],"solubile":["italian"],"solvente":["italian"],"somatico":["italian"],"somma":["italian"],"sonda":["italian"],"sonetto":["italian"],"sonnifero":["italian"],"sopire":["italian"],"soppeso":["italian"],"sopra":["italian"],"sorgere":["italian"],"sorpasso":["italian"],"sorriso":["italian"],"sorso":["italian"],"sorteggio":["italian"],"sorvolato":["italian"],"sospiro":["italian"],"sosta":["italian"],"sottile":["italian"],"spada":["italian"],"spalla":["italian"],"spargere":["italian"],"spatola":["italian"],"spavento":["italian"],"spazzola":["italian"],"specie":["italian"],"spedire":["italian"],"spegnere":["italian"],"spelatura":["italian"],"speranza":["italian"],"spessore":["italian"],"spettrale":["italian"],"spezzato":["italian"],"spia":["italian"],"spigoloso":["italian"],"spillato":["italian"],"spinoso":["italian"],"spirale":["italian"],"splendido":["italian"],"sportivo":["italian"],"sposo":["italian"],"spranga":["italian"],"sprecare":["italian"],"spronato":["italian"],"spruzzo":["italian"],"spuntino":["italian"],"squillo":["italian"],"sradicare":["italian"],"srotolato":["italian"],"stabile":["italian"],"stacco":["italian"],"staffa":["italian"],"stagnare":["italian"],"stampato":["italian"],"stantio":["italian"],"starnuto":["italian"],"stasera":["italian"],"statuto":["italian"],"stelo":["italian"],"steppa":["italian"],"sterzo":["italian"],"stiletto":["italian"],"stima":["italian"],"stirpe":["italian"],"stivale":["italian"],"stizzoso":["italian"],"stonato":["italian"],"storico":["italian"],"strappo":["italian"],"stregato":["italian"],"stridulo":["italian"],"strozzare":["italian"],"strutto":["italian"],"stuccare":["italian"],"stufo":["italian"],"stupendo":["italian"],"subentro":["italian"],"succoso":["italian"],"sudore":["italian"],"suggerito":["italian"],"sugo":["italian"],"sultano":["italian"],"suonare":["italian"],"superbo":["italian"],"supporto":["italian"],"surgelato":["italian"],"surrogato":["italian"],"sussurro":["italian"],"sutura":["italian"],"svagare":["italian"],"svedese":["italian"],"sveglio":["italian"],"svelare":["italian"],"svenuto":["italian"],"svezia":["italian"],"sviluppo":["italian"],"svista":["italian"],"svizzera":["italian"],"svolta":["italian"],"svuotare":["italian"],"tabacco":["italian"],"tabulato":["italian"],"tacciare":["italian"],"taciturno":["italian"],"tale":["italian"],"talismano":["italian"],"tampone":["italian"],"tannino":["italian"],"tara":["italian"],"tardivo":["italian"],"targato":["italian"],"tariffa":["italian"],"tarpare":["italian"],"tartaruga":["italian"],"tasto":["italian"],"tattico":["italian"],"taverna":["italian"],"tavolata":["italian"],"tazza":["italian"],"teca":["italian"],"tecnico":["italian"],"telefono":["italian"],"temerario":["italian"],"tempo":["italian","turkish"],"temuto":["italian"],"tendone":["italian"],"tenero":["italian"],"tensione":["italian"],"tentacolo":["italian"],"teorema":["italian"],"terme":["italian"],"terrazzo":["italian"],"terzetto":["italian"],"tesi":["italian"],"tesserato":["italian"],"testato":["italian"],"tetro":["italian"],"tettoia":["italian"],"tifare":["italian"],"tigella":["italian"],"timbro":["italian"],"tinto":["italian"],"tipico":["italian"],"tipografo":["italian"],"tiraggio":["italian"],"tiro":["italian"],"titanio":["italian"],"titolo":["italian"],"titubante":["italian"],"tizio":["italian"],"tizzone":["italian"],"toccare":["italian"],"tollerare":["italian"],"tolto":["italian"],"tombola":["italian"],"tomo":["italian"],"tonfo":["italian"],"tonsilla":["italian"],"topazio":["italian"],"topologia":["italian"],"toppa":["italian"],"torba":["italian"],"tornare":["italian"],"torrone":["italian"],"tortora":["italian"],"toscano":["italian"],"tossire":["italian"],"tostatura":["italian"],"totano":["italian"],"trabocco":["italian"],"trachea":["italian"],"trafila":["italian"],"tragedia":["italian"],"tralcio":["italian"],"tramonto":["italian"],"transito":["italian"],"trapano":["italian"],"trarre":["italian"],"trasloco":["italian"],"trattato":["italian"],"trave":["italian"],"treccia":["italian"],"tremolio":["italian"],"trespolo":["italian"],"tributo":["italian"],"tricheco":["italian"],"trifoglio":["italian"],"trillo":["italian"],"trincea":["italian"],"trio":["italian"],"tristezza":["italian"],"triturato":["italian"],"trivella":["italian"],"tromba":["italian"],"trono":["italian"],"troppo":["italian"],"trottola":["italian"],"trovare":["italian"],"truccato":["italian"],"tubatura":["italian"],"tuffato":["italian"],"tulipano":["italian"],"tumulto":["italian"],"tunisia":["italian"],"turbare":["italian"],"turchino":["italian"],"tuta":["italian"],"tutela":["italian"],"ubicato":["italian"],"uccello":["italian"],"uccisore":["italian"],"udire":["italian"],"uditivo":["italian"],"uffa":["italian"],"ufficio":["italian"],"uguale":["italian"],"ulisse":["italian"],"ultimato":["italian"],"umano":["italian"],"umile":["italian"],"umorismo":["italian"],"uncinetto":["italian"],"ungere":["italian"],"ungherese":["italian"],"unicorno":["italian"],"unificato":["italian"],"unisono":["italian"],"unitario":["italian"],"unte":["italian"],"uovo":["italian"],"upupa":["italian"],"uragano":["italian"],"urgenza":["italian"],"urlo":["italian"],"usanza":["italian"],"usato":["italian"],"uscito":["italian"],"usignolo":["italian"],"usuraio":["italian"],"utensile":["italian"],"utilizzo":["italian"],"utopia":["italian"],"vacante":["italian"],"vaccinato":["italian"],"vagabondo":["italian"],"vagliato":["italian"],"valanga":["italian"],"valgo":["italian"],"valico":["italian"],"valletta":["italian"],"valoroso":["italian"],"valutare":["italian"],"valvola":["italian"],"vampata":["italian"],"vangare":["italian"],"vanitoso":["italian"],"vano":["italian"],"vantaggio":["italian"],"vanvera":["italian"],"vapore":["italian"],"varano":["italian"],"varcato":["italian"],"variante":["italian"],"vasca":["italian"],"vedetta":["italian"],"vedova":["italian"],"veduto":["italian"],"vegetale":["italian"],"veicolo":["italian"],"velcro":["italian"],"velina":["italian"],"velluto":["italian"],"veloce":["italian"],"venato":["italian"],"vendemmia":["italian"],"vento":["italian"],"verace":["italian"],"verbale":["italian"],"vergogna":["italian"],"verifica":["italian"],"vero":["italian"],"verruca":["italian"],"verticale":["italian"],"vescica":["italian"],"vessillo":["italian"],"vestale":["italian"],"veterano":["italian"],"vetrina":["italian"],"vetusto":["italian"],"viandante":["italian"],"vibrante":["italian"],"vicenda":["italian"],"vichingo":["italian"],"vicinanza":["italian"],"vidimare":["italian"],"vigilia":["italian"],"vigneto":["italian"],"vigore":["italian"],"vile":["italian"],"villano":["italian"],"vimini":["italian"],"vincitore":["italian"],"viola":["italian"],"vipera":["italian"],"virgola":["italian"],"virologo":["italian"],"virulento":["italian"],"viscoso":["italian"],"visione":["italian"],"vispo":["italian"],"vissuto":["italian"],"visura":["italian"],"vita":["italian"],"vitello":["italian"],"vittima":["italian"],"vivanda":["italian"],"vivido":["italian"],"viziare":["italian"],"voce":["italian"],"voga":["italian"],"volatile":["italian"],"volere":["italian"],"volpe":["italian"],"voragine":["italian"],"vulcano":["italian"],"zampogna":["italian"],"zanna":["italian"],"zappato":["italian"],"zattera":["italian"],"zavorra":["italian"],"zefiro":["italian"],"zelante":["italian"],"zelo":["italian"],"zenzero":["italian"],"zerbino":["italian"],"zibetto":["italian"],"zinco":["italian"],"zircone":["italian"],"zitto":["italian"],"zolla":["italian"],"zotico":["italian"],"zucchero":["italian"],"zufolo":["italian"],"zulu":["italian"],"zuppa":["italian"],"あいこくしん":["japanese"],"あいさつ":["japanese"],"あいだ":["japanese"],"あおぞら":["japanese"],"あかちゃん":["japanese"],"あきる":["japanese"],"あけがた":["japanese"],"あける":["japanese"],"あこがれる":["japanese"],"あさい":["japanese"],"あさひ":["japanese"],"あしあと":["japanese"],"あじわう":["japanese"],"あずかる":["japanese"],"あずき":["japanese"],"あそぶ":["japanese"],"あたえる":["japanese"],"あたためる":["japanese"],"あたりまえ":["japanese"],"あたる":["japanese"],"あつい":["japanese"],"あつかう":["japanese"],"あっしゅく":["japanese"],"あつまり":["japanese"],"あつめる":["japanese"],"あてな":["japanese"],"あてはまる":["japanese"],"あひる":["japanese"],"あぶら":["japanese"],"あぶる":["japanese"],"あふれる":["japanese"],"あまい":["japanese"],"あまど":["japanese"],"あまやかす":["japanese"],"あまり":["japanese"],"あみもの":["japanese"],"あめりか":["japanese"],"あやまる":["japanese"],"あゆむ":["japanese"],"あらいぐま":["japanese"],"あらし":["japanese"],"あらすじ":["japanese"],"あらためる":["japanese"],"あらゆる":["japanese"],"あらわす":["japanese"],"ありがとう":["japanese"],"あわせる":["japanese"],"あわてる":["japanese"],"あんい":["japanese"],"あんがい":["japanese"],"あんこ":["japanese"],"あんぜん":["japanese"],"あんてい":["japanese"],"あんない":["japanese"],"あんまり":["japanese"],"いいだす":["japanese"],"いおん":["japanese"],"いがい":["japanese"],"いがく":["japanese"],"いきおい":["japanese"],"いきなり":["japanese"],"いきもの":["japanese"],"いきる":["japanese"],"いくじ":["japanese"],"いくぶん":["japanese"],"いけばな":["japanese"],"いけん":["japanese"],"いこう":["japanese"],"いこく":["japanese"],"いこつ":["japanese"],"いさましい":["japanese"],"いさん":["japanese"],"いしき":["japanese"],"いじゅう":["japanese"],"いじょう":["japanese"],"いじわる":["japanese"],"いずみ":["japanese"],"いずれ":["japanese"],"いせい":["japanese"],"いせえび":["japanese"],"いせかい":["japanese"],"いせき":["japanese"],"いぜん":["japanese"],"いそうろう":["japanese"],"いそがしい":["japanese"],"いだい":["japanese"],"いだく":["japanese"],"いたずら":["japanese"],"いたみ":["japanese"],"いたりあ":["japanese"],"いちおう":["japanese"],"いちじ":["japanese"],"いちど":["japanese"],"いちば":["japanese"],"いちぶ":["japanese"],"いちりゅう":["japanese"],"いつか":["japanese"],"いっしゅん":["japanese"],"いっせい":["japanese"],"いっそう":["japanese"],"いったん":["japanese"],"いっち":["japanese"],"いってい":["japanese"],"いっぽう":["japanese"],"いてざ":["japanese"],"いてん":["japanese"],"いどう":["japanese"],"いとこ":["japanese"],"いない":["japanese"],"いなか":["japanese"],"いねむり":["japanese"],"いのち":["japanese"],"いのる":["japanese"],"いはつ":["japanese"],"いばる":["japanese"],"いはん":["japanese"],"いびき":["japanese"],"いひん":["japanese"],"いふく":["japanese"],"いへん":["japanese"],"いほう":["japanese"],"いみん":["japanese"],"いもうと":["japanese"],"いもたれ":["japanese"],"いもり":["japanese"],"いやがる":["japanese"],"いやす":["japanese"],"いよかん":["japanese"],"いよく":["japanese"],"いらい":["japanese"],"いらすと":["japanese"],"いりぐち":["japanese"],"いりょう":["japanese"],"いれい":["japanese"],"いれもの":["japanese"],"いれる":["japanese"],"いろえんぴつ":["japanese"],"いわい":["japanese"],"いわう":["japanese"],"いわかん":["japanese"],"いわば":["japanese"],"いわゆる":["japanese"],"いんげんまめ":["japanese"],"いんさつ":["japanese"],"いんしょう":["japanese"],"いんよう":["japanese"],"うえき":["japanese"],"うえる":["japanese"],"うおざ":["japanese"],"うがい":["japanese"],"うかぶ":["japanese"],"うかべる":["japanese"],"うきわ":["japanese"],"うくらいな":["japanese"],"うくれれ":["japanese"],"うけたまわる":["japanese"],"うけつけ":["japanese"],"うけとる":["japanese"],"うけもつ":["japanese"],"うける":["japanese"],"うごかす":["japanese"],"うごく":["japanese"],"うこん":["japanese"],"うさぎ":["japanese"],"うしなう":["japanese"],"うしろがみ":["japanese"],"うすい":["japanese"],"うすぎ":["japanese"],"うすぐらい":["japanese"],"うすめる":["japanese"],"うせつ":["japanese"],"うちあわせ":["japanese"],"うちがわ":["japanese"],"うちき":["japanese"],"うちゅう":["japanese"],"うっかり":["japanese"],"うつくしい":["japanese"],"うったえる":["japanese"],"うつる":["japanese"],"うどん":["japanese"],"うなぎ":["japanese"],"うなじ":["japanese"],"うなずく":["japanese"],"うなる":["japanese"],"うねる":["japanese"],"うのう":["japanese"],"うぶげ":["japanese"],"うぶごえ":["japanese"],"うまれる":["japanese"],"うめる":["japanese"],"うもう":["japanese"],"うやまう":["japanese"],"うよく":["japanese"],"うらがえす":["japanese"],"うらぐち":["japanese"],"うらない":["japanese"],"うりあげ":["japanese"],"うりきれ":["japanese"],"うるさい":["japanese"],"うれしい":["japanese"],"うれゆき":["japanese"],"うれる":["japanese"],"うろこ":["japanese"],"うわき":["japanese"],"うわさ":["japanese"],"うんこう":["japanese"],"うんちん":["japanese"],"うんてん":["japanese"],"うんどう":["japanese"],"えいえん":["japanese"],"えいが":["japanese"],"えいきょう":["japanese"],"えいご":["japanese"],"えいせい":["japanese"],"えいぶん":["japanese"],"えいよう":["japanese"],"えいわ":["japanese"],"えおり":["japanese"],"えがお":["japanese"],"えがく":["japanese"],"えきたい":["japanese"],"えくせる":["japanese"],"えしゃく":["japanese"],"えすて":["japanese"],"えつらん":["japanese"],"えのぐ":["japanese"],"えほうまき":["japanese"],"えほん":["japanese"],"えまき":["japanese"],"えもじ":["japanese"],"えもの":["japanese"],"えらい":["japanese"],"えらぶ":["japanese"],"えりあ":["japanese"],"えんえん":["japanese"],"えんかい":["japanese"],"えんぎ":["japanese"],"えんげき":["japanese"],"えんしゅう":["japanese"],"えんぜつ":["japanese"],"えんそく":["japanese"],"えんちょう":["japanese"],"えんとつ":["japanese"],"おいかける":["japanese"],"おいこす":["japanese"],"おいしい":["japanese"],"おいつく":["japanese"],"おうえん":["japanese"],"おうさま":["japanese"],"おうじ":["japanese"],"おうせつ":["japanese"],"おうたい":["japanese"],"おうふく":["japanese"],"おうべい":["japanese"],"おうよう":["japanese"],"おえる":["japanese"],"おおい":["japanese"],"おおう":["japanese"],"おおどおり":["japanese"],"おおや":["japanese"],"おおよそ":["japanese"],"おかえり":["japanese"],"おかず":["japanese"],"おがむ":["japanese"],"おかわり":["japanese"],"おぎなう":["japanese"],"おきる":["japanese"],"おくさま":["japanese"],"おくじょう":["japanese"],"おくりがな":["japanese"],"おくる":["japanese"],"おくれる":["japanese"],"おこす":["japanese"],"おこなう":["japanese"],"おこる":["japanese"],"おさえる":["japanese"],"おさない":["japanese"],"おさめる":["japanese"],"おしいれ":["japanese"],"おしえる":["japanese"],"おじぎ":["japanese"],"おじさん":["japanese"],"おしゃれ":["japanese"],"おそらく":["japanese"],"おそわる":["japanese"],"おたがい":["japanese"],"おたく":["japanese"],"おだやか":["japanese"],"おちつく":["japanese"],"おっと":["japanese"],"おつり":["japanese"],"おでかけ":["japanese"],"おとしもの":["japanese"],"おとなしい":["japanese"],"おどり":["japanese"],"おどろかす":["japanese"],"おばさん":["japanese"],"おまいり":["japanese"],"おめでとう":["japanese"],"おもいで":["japanese"],"おもう":["japanese"],"おもたい":["japanese"],"おもちゃ":["japanese"],"おやつ":["japanese"],"おやゆび":["japanese"],"およぼす":["japanese"],"おらんだ":["japanese"],"おろす":["japanese"],"おんがく":["japanese"],"おんけい":["japanese"],"おんしゃ":["japanese"],"おんせん":["japanese"],"おんだん":["japanese"],"おんちゅう":["japanese"],"おんどけい":["japanese"],"かあつ":["japanese"],"かいが":["japanese"],"がいき":["japanese"],"がいけん":["japanese"],"がいこう":["japanese"],"かいさつ":["japanese"],"かいしゃ":["japanese"],"かいすいよく":["japanese"],"かいぜん":["japanese"],"かいぞうど":["japanese"],"かいつう":["japanese"],"かいてん":["japanese"],"かいとう":["japanese"],"かいふく":["japanese"],"がいへき":["japanese"],"かいほう":["japanese"],"かいよう":["japanese"],"がいらい":["japanese"],"かいわ":["japanese"],"かえる":["japanese"],"かおり":["japanese"],"かかえる":["japanese"],"かがく":["japanese"],"かがし":["japanese"],"かがみ":["japanese"],"かくご":["japanese"],"かくとく":["japanese"],"かざる":["japanese"],"がぞう":["japanese"],"かたい":["japanese"],"かたち":["japanese"],"がちょう":["japanese"],"がっきゅう":["japanese"],"がっこう":["japanese"],"がっさん":["japanese"],"がっしょう":["japanese"],"かなざわし":["japanese"],"かのう":["japanese"],"がはく":["japanese"],"かぶか":["japanese"],"かほう":["japanese"],"かほご":["japanese"],"かまう":["japanese"],"かまぼこ":["japanese"],"かめれおん":["japanese"],"かゆい":["japanese"],"かようび":["japanese"],"からい":["japanese"],"かるい":["japanese"],"かろう":["japanese"],"かわく":["japanese"],"かわら":["japanese"],"がんか":["japanese"],"かんけい":["japanese"],"かんこう":["japanese"],"かんしゃ":["japanese"],"かんそう":["japanese"],"かんたん":["japanese"],"かんち":["japanese"],"がんばる":["japanese"],"きあい":["japanese"],"きあつ":["japanese"],"きいろ":["japanese"],"ぎいん":["japanese"],"きうい":["japanese"],"きうん":["japanese"],"きえる":["japanese"],"きおう":["japanese"],"きおく":["japanese"],"きおち":["japanese"],"きおん":["japanese"],"きかい":["japanese"],"きかく":["japanese"],"きかんしゃ":["japanese"],"ききて":["japanese"],"きくばり":["japanese"],"きくらげ":["japanese"],"きけんせい":["japanese"],"きこう":["japanese"],"きこえる":["japanese"],"きこく":["japanese"],"きさい":["japanese"],"きさく":["japanese"],"きさま":["japanese"],"きさらぎ":["japanese"],"ぎじかがく":["japanese"],"ぎしき":["japanese"],"ぎじたいけん":["japanese"],"ぎじにってい":["japanese"],"ぎじゅつしゃ":["japanese"],"きすう":["japanese"],"きせい":["japanese"],"きせき":["japanese"],"きせつ":["japanese"],"きそう":["japanese"],"きぞく":["japanese"],"きぞん":["japanese"],"きたえる":["japanese"],"きちょう":["japanese"],"きつえん":["japanese"],"ぎっちり":["japanese"],"きつつき":["japanese"],"きつね":["japanese"],"きてい":["japanese"],"きどう":["japanese"],"きどく":["japanese"],"きない":["japanese"],"きなが":["japanese"],"きなこ":["japanese"],"きぬごし":["japanese"],"きねん":["japanese"],"きのう":["japanese"],"きのした":["japanese"],"きはく":["japanese"],"きびしい":["japanese"],"きひん":["japanese"],"きふく":["japanese"],"きぶん":["japanese"],"きぼう":["japanese"],"きほん":["japanese"],"きまる":["japanese"],"きみつ":["japanese"],"きむずかしい":["japanese"],"きめる":["japanese"],"きもだめし":["japanese"],"きもち":["japanese"],"きもの":["japanese"],"きゃく":["japanese"],"きやく":["japanese"],"ぎゅうにく":["japanese"],"きよう":["japanese"],"きょうりゅう":["japanese"],"きらい":["japanese"],"きらく":["japanese"],"きりん":["japanese"],"きれい":["japanese"],"きれつ":["japanese"],"きろく":["japanese"],"ぎろん":["japanese"],"きわめる":["japanese"],"ぎんいろ":["japanese"],"きんかくじ":["japanese"],"きんじょ":["japanese"],"きんようび":["japanese"],"ぐあい":["japanese"],"くいず":["japanese"],"くうかん":["japanese"],"くうき":["japanese"],"くうぐん":["japanese"],"くうこう":["japanese"],"ぐうせい":["japanese"],"くうそう":["japanese"],"ぐうたら":["japanese"],"くうふく":["japanese"],"くうぼ":["japanese"],"くかん":["japanese"],"くきょう":["japanese"],"くげん":["japanese"],"ぐこう":["japanese"],"くさい":["japanese"],"くさき":["japanese"],"くさばな":["japanese"],"くさる":["japanese"],"くしゃみ":["japanese"],"くしょう":["japanese"],"くすのき":["japanese"],"くすりゆび":["japanese"],"くせげ":["japanese"],"くせん":["japanese"],"ぐたいてき":["japanese"],"くださる":["japanese"],"くたびれる":["japanese"],"くちこみ":["japanese"],"くちさき":["japanese"],"くつした":["japanese"],"ぐっすり":["japanese"],"くつろぐ":["japanese"],"くとうてん":["japanese"],"くどく":["japanese"],"くなん":["japanese"],"くねくね":["japanese"],"くのう":["japanese"],"くふう":["japanese"],"くみあわせ":["japanese"],"くみたてる":["japanese"],"くめる":["japanese"],"くやくしょ":["japanese"],"くらす":["japanese"],"くらべる":["japanese"],"くるま":["japanese"],"くれる":["japanese"],"くろう":["japanese"],"くわしい":["japanese"],"ぐんかん":["japanese"],"ぐんしょく":["japanese"],"ぐんたい":["japanese"],"ぐんて":["japanese"],"けあな":["japanese"],"けいかく":["japanese"],"けいけん":["japanese"],"けいこ":["japanese"],"けいさつ":["japanese"],"げいじゅつ":["japanese"],"けいたい":["japanese"],"げいのうじん":["japanese"],"けいれき":["japanese"],"けいろ":["japanese"],"けおとす":["japanese"],"けおりもの":["japanese"],"げきか":["japanese"],"げきげん":["japanese"],"げきだん":["japanese"],"げきちん":["japanese"],"げきとつ":["japanese"],"げきは":["japanese"],"げきやく":["japanese"],"げこう":["japanese"],"げこくじょう":["japanese"],"げざい":["japanese"],"けさき":["japanese"],"げざん":["japanese"],"けしき":["japanese"],"けしごむ":["japanese"],"けしょう":["japanese"],"げすと":["japanese"],"けたば":["japanese"],"けちゃっぷ":["japanese"],"けちらす":["japanese"],"けつあつ":["japanese"],"けつい":["japanese"],"けつえき":["japanese"],"けっこん":["japanese"],"けつじょ":["japanese"],"けっせき":["japanese"],"けってい":["japanese"],"けつまつ":["japanese"],"げつようび":["japanese"],"げつれい":["japanese"],"けつろん":["japanese"],"げどく":["japanese"],"けとばす":["japanese"],"けとる":["japanese"],"けなげ":["japanese"],"けなす":["japanese"],"けなみ":["japanese"],"けぬき":["japanese"],"げねつ":["japanese"],"けねん":["japanese"],"けはい":["japanese"],"げひん":["japanese"],"けぶかい":["japanese"],"げぼく":["japanese"],"けまり":["japanese"],"けみかる":["japanese"],"けむし":["japanese"],"けむり":["japanese"],"けもの":["japanese"],"けらい":["japanese"],"けろけろ":["japanese"],"けわしい":["japanese"],"けんい":["japanese"],"けんえつ":["japanese"],"けんお":["japanese"],"けんか":["japanese"],"げんき":["japanese"],"けんげん":["japanese"],"けんこう":["japanese"],"けんさく":["japanese"],"けんしゅう":["japanese"],"けんすう":["japanese"],"げんそう":["japanese"],"けんちく":["japanese"],"けんてい":["japanese"],"けんとう":["japanese"],"けんない":["japanese"],"けんにん":["japanese"],"げんぶつ":["japanese"],"けんま":["japanese"],"けんみん":["japanese"],"けんめい":["japanese"],"けんらん":["japanese"],"けんり":["japanese"],"こあくま":["japanese"],"こいぬ":["japanese"],"こいびと":["japanese"],"ごうい":["japanese"],"こうえん":["japanese"],"こうおん":["japanese"],"こうかん":["japanese"],"ごうきゅう":["japanese"],"ごうけい":["japanese"],"こうこう":["japanese"],"こうさい":["japanese"],"こうじ":["japanese"],"こうすい":["japanese"],"ごうせい":["japanese"],"こうそく":["japanese"],"こうたい":["japanese"],"こうちゃ":["japanese"],"こうつう":["japanese"],"こうてい":["japanese"],"こうどう":["japanese"],"こうない":["japanese"],"こうはい":["japanese"],"ごうほう":["japanese"],"ごうまん":["japanese"],"こうもく":["japanese"],"こうりつ":["japanese"],"こえる":["japanese"],"こおり":["japanese"],"ごかい":["japanese"],"ごがつ":["japanese"],"ごかん":["japanese"],"こくご":["japanese"],"こくさい":["japanese"],"こくとう":["japanese"],"こくない":["japanese"],"こくはく":["japanese"],"こぐま":["japanese"],"こけい":["japanese"],"こける":["japanese"],"ここのか":["japanese"],"こころ":["japanese"],"こさめ":["japanese"],"こしつ":["japanese"],"こすう":["japanese"],"こせい":["japanese"],"こせき":["japanese"],"こぜん":["japanese"],"こそだて":["japanese"],"こたい":["japanese"],"こたえる":["japanese"],"こたつ":["japanese"],"こちょう":["japanese"],"こっか":["japanese"],"こつこつ":["japanese"],"こつばん":["japanese"],"こつぶ":["japanese"],"こてい":["japanese"],"こてん":["japanese"],"ことがら":["japanese"],"ことし":["japanese"],"ことば":["japanese"],"ことり":["japanese"],"こなごな":["japanese"],"こねこね":["japanese"],"このまま":["japanese"],"このみ":["japanese"],"このよ":["japanese"],"ごはん":["japanese"],"こひつじ":["japanese"],"こふう":["japanese"],"こふん":["japanese"],"こぼれる":["japanese"],"ごまあぶら":["japanese"],"こまかい":["japanese"],"ごますり":["japanese"],"こまつな":["japanese"],"こまる":["japanese"],"こむぎこ":["japanese"],"こもじ":["japanese"],"こもち":["japanese"],"こもの":["japanese"],"こもん":["japanese"],"こやく":["japanese"],"こやま":["japanese"],"こゆう":["japanese"],"こゆび":["japanese"],"こよい":["japanese"],"こよう":["japanese"],"こりる":["japanese"],"これくしょん":["japanese"],"ころっけ":["japanese"],"こわもて":["japanese"],"こわれる":["japanese"],"こんいん":["japanese"],"こんかい":["japanese"],"こんき":["japanese"],"こんしゅう":["japanese"],"こんすい":["japanese"],"こんだて":["japanese"],"こんとん":["japanese"],"こんなん":["japanese"],"こんびに":["japanese"],"こんぽん":["japanese"],"こんまけ":["japanese"],"こんや":["japanese"],"こんれい":["japanese"],"こんわく":["japanese"],"ざいえき":["japanese"],"さいかい":["japanese"],"さいきん":["japanese"],"ざいげん":["japanese"],"ざいこ":["japanese"],"さいしょ":["japanese"],"さいせい":["japanese"],"ざいたく":["japanese"],"ざいちゅう":["japanese"],"さいてき":["japanese"],"ざいりょう":["japanese"],"さうな":["japanese"],"さかいし":["japanese"],"さがす":["japanese"],"さかな":["japanese"],"さかみち":["japanese"],"さがる":["japanese"],"さぎょう":["japanese"],"さくし":["japanese"],"さくひん":["japanese"],"さくら":["japanese"],"さこく":["japanese"],"さこつ":["japanese"],"さずかる":["japanese"],"ざせき":["japanese"],"さたん":["japanese"],"さつえい":["japanese"],"ざつおん":["japanese"],"ざっか":["japanese"],"ざつがく":["japanese"],"さっきょく":["japanese"],"ざっし":["japanese"],"さつじん":["japanese"],"ざっそう":["japanese"],"さつたば":["japanese"],"さつまいも":["japanese"],"さてい":["japanese"],"さといも":["japanese"],"さとう":["japanese"],"さとおや":["japanese"],"さとし":["japanese"],"さとる":["japanese"],"さのう":["japanese"],"さばく":["japanese"],"さびしい":["japanese"],"さべつ":["japanese"],"さほう":["japanese"],"さほど":["japanese"],"さます":["japanese"],"さみしい":["japanese"],"さみだれ":["japanese"],"さむけ":["japanese"],"さめる":["japanese"],"さやえんどう":["japanese"],"さゆう":["japanese"],"さよう":["japanese"],"さよく":["japanese"],"さらだ":["japanese"],"ざるそば":["japanese"],"さわやか":["japanese"],"さわる":["japanese"],"さんいん":["japanese"],"さんか":["japanese"],"さんきゃく":["japanese"],"さんこう":["japanese"],"さんさい":["japanese"],"ざんしょ":["japanese"],"さんすう":["japanese"],"さんせい":["japanese"],"さんそ":["japanese"],"さんち":["japanese"],"さんま":["japanese"],"さんみ":["japanese"],"さんらん":["japanese"],"しあい":["japanese"],"しあげ":["japanese"],"しあさって":["japanese"],"しあわせ":["japanese"],"しいく":["japanese"],"しいん":["japanese"],"しうち":["japanese"],"しえい":["japanese"],"しおけ":["japanese"],"しかい":["japanese"],"しかく":["japanese"],"じかん":["japanese"],"しごと":["japanese"],"しすう":["japanese"],"じだい":["japanese"],"したうけ":["japanese"],"したぎ":["japanese"],"したて":["japanese"],"したみ":["japanese"],"しちょう":["japanese"],"しちりん":["japanese"],"しっかり":["japanese"],"しつじ":["japanese"],"しつもん":["japanese"],"してい":["japanese"],"してき":["japanese"],"してつ":["japanese"],"じてん":["japanese"],"じどう":["japanese"],"しなぎれ":["japanese"],"しなもの":["japanese"],"しなん":["japanese"],"しねま":["japanese"],"しねん":["japanese"],"しのぐ":["japanese"],"しのぶ":["japanese"],"しはい":["japanese"],"しばかり":["japanese"],"しはつ":["japanese"],"しはらい":["japanese"],"しはん":["japanese"],"しひょう":["japanese"],"しふく":["japanese"],"じぶん":["japanese"],"しへい":["japanese"],"しほう":["japanese"],"しほん":["japanese"],"しまう":["japanese"],"しまる":["japanese"],"しみん":["japanese"],"しむける":["japanese"],"じむしょ":["japanese"],"しめい":["japanese"],"しめる":["japanese"],"しもん":["japanese"],"しゃいん":["japanese"],"しゃうん":["japanese"],"しゃおん":["japanese"],"じゃがいも":["japanese"],"しやくしょ":["japanese"],"しゃくほう":["japanese"],"しゃけん":["japanese"],"しゃこ":["japanese"],"しゃざい":["japanese"],"しゃしん":["japanese"],"しゃせん":["japanese"],"しゃそう":["japanese"],"しゃたい":["japanese"],"しゃちょう":["japanese"],"しゃっきん":["japanese"],"じゃま":["japanese"],"しゃりん":["japanese"],"しゃれい":["japanese"],"じゆう":["japanese"],"じゅうしょ":["japanese"],"しゅくはく":["japanese"],"じゅしん":["japanese"],"しゅっせき":["japanese"],"しゅみ":["japanese"],"しゅらば":["japanese"],"じゅんばん":["japanese"],"しょうかい":["japanese"],"しょくたく":["japanese"],"しょっけん":["japanese"],"しょどう":["japanese"],"しょもつ":["japanese"],"しらせる":["japanese"],"しらべる":["japanese"],"しんか":["japanese"],"しんこう":["japanese"],"じんじゃ":["japanese"],"しんせいじ":["japanese"],"しんちく":["japanese"],"しんりん":["japanese"],"すあげ":["japanese"],"すあし":["japanese"],"すあな":["japanese"],"ずあん":["japanese"],"すいえい":["japanese"],"すいか":["japanese"],"すいとう":["japanese"],"ずいぶん":["japanese"],"すいようび":["japanese"],"すうがく":["japanese"],"すうじつ":["japanese"],"すうせん":["japanese"],"すおどり":["japanese"],"すきま":["japanese"],"すくう":["japanese"],"すくない":["japanese"],"すける":["japanese"],"すごい":["japanese"],"すこし":["japanese"],"ずさん":["japanese"],"すずしい":["japanese"],"すすむ":["japanese"],"すすめる":["japanese"],"すっかり":["japanese"],"ずっしり":["japanese"],"ずっと":["japanese"],"すてき":["japanese"],"すてる":["japanese"],"すねる":["japanese"],"すのこ":["japanese"],"すはだ":["japanese"],"すばらしい":["japanese"],"ずひょう":["japanese"],"ずぶぬれ":["japanese"],"すぶり":["japanese"],"すふれ":["japanese"],"すべて":["japanese"],"すべる":["japanese"],"ずほう":["japanese"],"すぼん":["japanese"],"すまい":["japanese"],"すめし":["japanese"],"すもう":["japanese"],"すやき":["japanese"],"すらすら":["japanese"],"するめ":["japanese"],"すれちがう":["japanese"],"すろっと":["japanese"],"すわる":["japanese"],"すんぜん":["japanese"],"すんぽう":["japanese"],"せあぶら":["japanese"],"せいかつ":["japanese"],"せいげん":["japanese"],"せいじ":["japanese"],"せいよう":["japanese"],"せおう":["japanese"],"せかいかん":["japanese"],"せきにん":["japanese"],"せきむ":["japanese"],"せきゆ":["japanese"],"せきらんうん":["japanese"],"せけん":["japanese"],"せこう":["japanese"],"せすじ":["japanese"],"せたい":["japanese"],"せたけ":["japanese"],"せっかく":["japanese"],"せっきゃく":["japanese"],"ぜっく":["japanese"],"せっけん":["japanese"],"せっこつ":["japanese"],"せっさたくま":["japanese"],"せつぞく":["japanese"],"せつだん":["japanese"],"せつでん":["japanese"],"せっぱん":["japanese"],"せつび":["japanese"],"せつぶん":["japanese"],"せつめい":["japanese"],"せつりつ":["japanese"],"せなか":["japanese"],"せのび":["japanese"],"せはば":["japanese"],"せびろ":["japanese"],"せぼね":["japanese"],"せまい":["japanese"],"せまる":["japanese"],"せめる":["japanese"],"せもたれ":["japanese"],"せりふ":["japanese"],"ぜんあく":["japanese"],"せんい":["japanese"],"せんえい":["japanese"],"せんか":["japanese"],"せんきょ":["japanese"],"せんく":["japanese"],"せんげん":["japanese"],"ぜんご":["japanese"],"せんさい":["japanese"],"せんしゅ":["japanese"],"せんすい":["japanese"],"せんせい":["japanese"],"せんぞ":["japanese"],"せんたく":["japanese"],"せんちょう":["japanese"],"せんてい":["japanese"],"せんとう":["japanese"],"せんぬき":["japanese"],"せんねん":["japanese"],"せんぱい":["japanese"],"ぜんぶ":["japanese"],"ぜんぽう":["japanese"],"せんむ":["japanese"],"せんめんじょ":["japanese"],"せんもん":["japanese"],"せんやく":["japanese"],"せんゆう":["japanese"],"せんよう":["japanese"],"ぜんら":["japanese"],"ぜんりゃく":["japanese"],"せんれい":["japanese"],"せんろ":["japanese"],"そあく":["japanese"],"そいとげる":["japanese"],"そいね":["japanese"],"そうがんきょう":["japanese"],"そうき":["japanese"],"そうご":["japanese"],"そうしん":["japanese"],"そうだん":["japanese"],"そうなん":["japanese"],"そうび":["japanese"],"そうめん":["japanese"],"そうり":["japanese"],"そえもの":["japanese"],"そえん":["japanese"],"そがい":["japanese"],"そげき":["japanese"],"そこう":["japanese"],"そこそこ":["japanese"],"そざい":["japanese"],"そしな":["japanese"],"そせい":["japanese"],"そせん":["japanese"],"そそぐ":["japanese"],"そだてる":["japanese"],"そつう":["japanese"],"そつえん":["japanese"],"そっかん":["japanese"],"そつぎょう":["japanese"],"そっけつ":["japanese"],"そっこう":["japanese"],"そっせん":["japanese"],"そっと":["japanese"],"そとがわ":["japanese"],"そとづら":["japanese"],"そなえる":["japanese"],"そなた":["japanese"],"そふぼ":["japanese"],"そぼく":["japanese"],"そぼろ":["japanese"],"そまつ":["japanese"],"そまる":["japanese"],"そむく":["japanese"],"そむりえ":["japanese"],"そめる":["japanese"],"そもそも":["japanese"],"そよかぜ":["japanese"],"そらまめ":["japanese"],"そろう":["japanese"],"そんかい":["japanese"],"そんけい":["japanese"],"そんざい":["japanese"],"そんしつ":["japanese"],"そんぞく":["japanese"],"そんちょう":["japanese"],"ぞんび":["japanese"],"ぞんぶん":["japanese"],"そんみん":["japanese"],"たあい":["japanese"],"たいいん":["japanese"],"たいうん":["japanese"],"たいえき":["japanese"],"たいおう":["japanese"],"だいがく":["japanese"],"たいき":["japanese"],"たいぐう":["japanese"],"たいけん":["japanese"],"たいこ":["japanese"],"たいざい":["japanese"],"だいじょうぶ":["japanese"],"だいすき":["japanese"],"たいせつ":["japanese"],"たいそう":["japanese"],"だいたい":["japanese"],"たいちょう":["japanese"],"たいてい":["japanese"],"だいどころ":["japanese"],"たいない":["japanese"],"たいねつ":["japanese"],"たいのう":["japanese"],"たいはん":["japanese"],"だいひょう":["japanese"],"たいふう":["japanese"],"たいへん":["japanese"],"たいほ":["japanese"],"たいまつばな":["japanese"],"たいみんぐ":["japanese"],"たいむ":["japanese"],"たいめん":["japanese"],"たいやき":["japanese"],"たいよう":["japanese"],"たいら":["japanese"],"たいりょく":["japanese"],"たいる":["japanese"],"たいわん":["japanese"],"たうえ":["japanese"],"たえる":["japanese"],"たおす":["japanese"],"たおる":["japanese"],"たおれる":["japanese"],"たかい":["japanese"],"たかね":["japanese"],"たきび":["japanese"],"たくさん":["japanese"],"たこく":["japanese"],"たこやき":["japanese"],"たさい":["japanese"],"たしざん":["japanese"],"だじゃれ":["japanese"],"たすける":["japanese"],"たずさわる":["japanese"],"たそがれ":["japanese"],"たたかう":["japanese"],"たたく":["japanese"],"ただしい":["japanese"],"たたみ":["japanese"],"たちばな":["japanese"],"だっかい":["japanese"],"だっきゃく":["japanese"],"だっこ":["japanese"],"だっしゅつ":["japanese"],"だったい":["japanese"],"たてる":["japanese"],"たとえる":["japanese"],"たなばた":["japanese"],"たにん":["japanese"],"たぬき":["japanese"],"たのしみ":["japanese"],"たはつ":["japanese"],"たぶん":["japanese"],"たべる":["japanese"],"たぼう":["japanese"],"たまご":["japanese"],"たまる":["japanese"],"だむる":["japanese"],"ためいき":["japanese"],"ためす":["japanese"],"ためる":["japanese"],"たもつ":["japanese"],"たやすい":["japanese"],"たよる":["japanese"],"たらす":["japanese"],"たりきほんがん":["japanese"],"たりょう":["japanese"],"たりる":["japanese"],"たると":["japanese"],"たれる":["japanese"],"たれんと":["japanese"],"たろっと":["japanese"],"たわむれる":["japanese"],"だんあつ":["japanese"],"たんい":["japanese"],"たんおん":["japanese"],"たんか":["japanese"],"たんき":["japanese"],"たんけん":["japanese"],"たんご":["japanese"],"たんさん":["japanese"],"たんじょうび":["japanese"],"だんせい":["japanese"],"たんそく":["japanese"],"たんたい":["japanese"],"だんち":["japanese"],"たんてい":["japanese"],"たんとう":["japanese"],"だんな":["japanese"],"たんにん":["japanese"],"だんねつ":["japanese"],"たんのう":["japanese"],"たんぴん":["japanese"],"だんぼう":["japanese"],"たんまつ":["japanese"],"たんめい":["japanese"],"だんれつ":["japanese"],"だんろ":["japanese"],"だんわ":["japanese"],"ちあい":["japanese"],"ちあん":["japanese"],"ちいき":["japanese"],"ちいさい":["japanese"],"ちえん":["japanese"],"ちかい":["japanese"],"ちから":["japanese"],"ちきゅう":["japanese"],"ちきん":["japanese"],"ちけいず":["japanese"],"ちけん":["japanese"],"ちこく":["japanese"],"ちさい":["japanese"],"ちしき":["japanese"],"ちしりょう":["japanese"],"ちせい":["japanese"],"ちそう":["japanese"],"ちたい":["japanese"],"ちたん":["japanese"],"ちちおや":["japanese"],"ちつじょ":["japanese"],"ちてき":["japanese"],"ちてん":["japanese"],"ちぬき":["japanese"],"ちぬり":["japanese"],"ちのう":["japanese"],"ちひょう":["japanese"],"ちへいせん":["japanese"],"ちほう":["japanese"],"ちまた":["japanese"],"ちみつ":["japanese"],"ちみどろ":["japanese"],"ちめいど":["japanese"],"ちゃんこなべ":["japanese"],"ちゅうい":["japanese"],"ちゆりょく":["japanese"],"ちょうし":["japanese"],"ちょさくけん":["japanese"],"ちらし":["japanese"],"ちらみ":["japanese"],"ちりがみ":["japanese"],"ちりょう":["japanese"],"ちるど":["japanese"],"ちわわ":["japanese"],"ちんたい":["japanese"],"ちんもく":["japanese"],"ついか":["japanese"],"ついたち":["japanese"],"つうか":["japanese"],"つうじょう":["japanese"],"つうはん":["japanese"],"つうわ":["japanese"],"つかう":["japanese"],"つかれる":["japanese"],"つくね":["japanese"],"つくる":["japanese"],"つけね":["japanese"],"つける":["japanese"],"つごう":["japanese"],"つたえる":["japanese"],"つづく":["japanese"],"つつじ":["japanese"],"つつむ":["japanese"],"つとめる":["japanese"],"つながる":["japanese"],"つなみ":["japanese"],"つねづね":["japanese"],"つのる":["japanese"],"つぶす":["japanese"],"つまらない":["japanese"],"つまる":["japanese"],"つみき":["japanese"],"つめたい":["japanese"],"つもり":["japanese"],"つもる":["japanese"],"つよい":["japanese"],"つるぼ":["japanese"],"つるみく":["japanese"],"つわもの":["japanese"],"つわり":["japanese"],"てあし":["japanese"],"てあて":["japanese"],"てあみ":["japanese"],"ていおん":["japanese"],"ていか":["japanese"],"ていき":["japanese"],"ていけい":["japanese"],"ていこく":["japanese"],"ていさつ":["japanese"],"ていし":["japanese"],"ていせい":["japanese"],"ていたい":["japanese"],"ていど":["japanese"],"ていねい":["japanese"],"ていひょう":["japanese"],"ていへん":["japanese"],"ていぼう":["japanese"],"てうち":["japanese"],"ておくれ":["japanese"],"てきとう":["japanese"],"てくび":["japanese"],"でこぼこ":["japanese"],"てさぎょう":["japanese"],"てさげ":["japanese"],"てすり":["japanese"],"てそう":["japanese"],"てちがい":["japanese"],"てちょう":["japanese"],"てつがく":["japanese"],"てつづき":["japanese"],"でっぱ":["japanese"],"てつぼう":["japanese"],"てつや":["japanese"],"でぬかえ":["japanese"],"てぬき":["japanese"],"てぬぐい":["japanese"],"てのひら":["japanese"],"てはい":["japanese"],"てぶくろ":["japanese"],"てふだ":["japanese"],"てほどき":["japanese"],"てほん":["japanese"],"てまえ":["japanese"],"てまきずし":["japanese"],"てみじか":["japanese"],"てみやげ":["japanese"],"てらす":["japanese"],"てれび":["japanese"],"てわけ":["japanese"],"てわたし":["japanese"],"でんあつ":["japanese"],"てんいん":["japanese"],"てんかい":["japanese"],"てんき":["japanese"],"てんぐ":["japanese"],"てんけん":["japanese"],"てんごく":["japanese"],"てんさい":["japanese"],"てんし":["japanese"],"てんすう":["japanese"],"でんち":["japanese"],"てんてき":["japanese"],"てんとう":["japanese"],"てんない":["japanese"],"てんぷら":["japanese"],"てんぼうだい":["japanese"],"てんめつ":["japanese"],"てんらんかい":["japanese"],"でんりょく":["japanese"],"でんわ":["japanese"],"どあい":["japanese"],"といれ":["japanese"],"どうかん":["japanese"],"とうきゅう":["japanese"],"どうぐ":["japanese"],"とうし":["japanese"],"とうむぎ":["japanese"],"とおい":["japanese"],"とおか":["japanese"],"とおく":["japanese"],"とおす":["japanese"],"とおる":["japanese"],"とかい":["japanese"],"とかす":["japanese"],"ときおり":["japanese"],"ときどき":["japanese"],"とくい":["japanese"],"とくしゅう":["japanese"],"とくてん":["japanese"],"とくに":["japanese"],"とくべつ":["japanese"],"とけい":["japanese"],"とける":["japanese"],"とこや":["japanese"],"とさか":["japanese"],"としょかん":["japanese"],"とそう":["japanese"],"とたん":["japanese"],"とちゅう":["japanese"],"とっきゅう":["japanese"],"とっくん":["japanese"],"とつぜん":["japanese"],"とつにゅう":["japanese"],"とどける":["japanese"],"ととのえる":["japanese"],"とない":["japanese"],"となえる":["japanese"],"となり":["japanese"],"とのさま":["japanese"],"とばす":["japanese"],"どぶがわ":["japanese"],"とほう":["japanese"],"とまる":["japanese"],"とめる":["japanese"],"ともだち":["japanese"],"ともる":["japanese"],"どようび":["japanese"],"とらえる":["japanese"],"とんかつ":["japanese"],"どんぶり":["japanese"],"ないかく":["japanese"],"ないこう":["japanese"],"ないしょ":["japanese"],"ないす":["japanese"],"ないせん":["japanese"],"ないそう":["japanese"],"なおす":["japanese"],"ながい":["japanese"],"なくす":["japanese"],"なげる":["japanese"],"なこうど":["japanese"],"なさけ":["japanese"],"なたでここ":["japanese"],"なっとう":["japanese"],"なつやすみ":["japanese"],"ななおし":["japanese"],"なにごと":["japanese"],"なにもの":["japanese"],"なにわ":["japanese"],"なのか":["japanese"],"なふだ":["japanese"],"なまいき":["japanese"],"なまえ":["japanese"],"なまみ":["japanese"],"なみだ":["japanese"],"なめらか":["japanese"],"なめる":["japanese"],"なやむ":["japanese"],"ならう":["japanese"],"ならび":["japanese"],"ならぶ":["japanese"],"なれる":["japanese"],"なわとび":["japanese"],"なわばり":["japanese"],"にあう":["japanese"],"にいがた":["japanese"],"にうけ":["japanese"],"におい":["japanese"],"にかい":["japanese"],"にがて":["japanese"],"にきび":["japanese"],"にくしみ":["japanese"],"にくまん":["japanese"],"にげる":["japanese"],"にさんかたんそ":["japanese"],"にしき":["japanese"],"にせもの":["japanese"],"にちじょう":["japanese"],"にちようび":["japanese"],"にっか":["japanese"],"にっき":["japanese"],"にっけい":["japanese"],"にっこう":["japanese"],"にっさん":["japanese"],"にっしょく":["japanese"],"にっすう":["japanese"],"にっせき":["japanese"],"にってい":["japanese"],"になう":["japanese"],"にほん":["japanese"],"にまめ":["japanese"],"にもつ":["japanese"],"にやり":["japanese"],"にゅういん":["japanese"],"にりんしゃ":["japanese"],"にわとり":["japanese"],"にんい":["japanese"],"にんか":["japanese"],"にんき":["japanese"],"にんげん":["japanese"],"にんしき":["japanese"],"にんずう":["japanese"],"にんそう":["japanese"],"にんたい":["japanese"],"にんち":["japanese"],"にんてい":["japanese"],"にんにく":["japanese"],"にんぷ":["japanese"],"にんまり":["japanese"],"にんむ":["japanese"],"にんめい":["japanese"],"にんよう":["japanese"],"ぬいくぎ":["japanese"],"ぬかす":["japanese"],"ぬぐいとる":["japanese"],"ぬぐう":["japanese"],"ぬくもり":["japanese"],"ぬすむ":["japanese"],"ぬまえび":["japanese"],"ぬめり":["japanese"],"ぬらす":["japanese"],"ぬんちゃく":["japanese"],"ねあげ":["japanese"],"ねいき":["japanese"],"ねいる":["japanese"],"ねいろ":["japanese"],"ねぐせ":["japanese"],"ねくたい":["japanese"],"ねくら":["japanese"],"ねこぜ":["japanese"],"ねこむ":["japanese"],"ねさげ":["japanese"],"ねすごす":["japanese"],"ねそべる":["japanese"],"ねだん":["japanese"],"ねつい":["japanese"],"ねっしん":["japanese"],"ねつぞう":["japanese"],"ねったいぎょ":["japanese"],"ねぶそく":["japanese"],"ねふだ":["japanese"],"ねぼう":["japanese"],"ねほりはほり":["japanese"],"ねまき":["japanese"],"ねまわし":["japanese"],"ねみみ":["japanese"],"ねむい":["japanese"],"ねむたい":["japanese"],"ねもと":["japanese"],"ねらう":["japanese"],"ねわざ":["japanese"],"ねんいり":["japanese"],"ねんおし":["japanese"],"ねんかん":["japanese"],"ねんきん":["japanese"],"ねんぐ":["japanese"],"ねんざ":["japanese"],"ねんし":["japanese"],"ねんちゃく":["japanese"],"ねんど":["japanese"],"ねんぴ":["japanese"],"ねんぶつ":["japanese"],"ねんまつ":["japanese"],"ねんりょう":["japanese"],"ねんれい":["japanese"],"のいず":["japanese"],"のおづま":["japanese"],"のがす":["japanese"],"のきなみ":["japanese"],"のこぎり":["japanese"],"のこす":["japanese"],"のこる":["japanese"],"のせる":["japanese"],"のぞく":["japanese"],"のぞむ":["japanese"],"のたまう":["japanese"],"のちほど":["japanese"],"のっく":["japanese"],"のばす":["japanese"],"のはら":["japanese"],"のべる":["japanese"],"のぼる":["japanese"],"のみもの":["japanese"],"のやま":["japanese"],"のらいぬ":["japanese"],"のらねこ":["japanese"],"のりもの":["japanese"],"のりゆき":["japanese"],"のれん":["japanese"],"のんき":["japanese"],"ばあい":["japanese"],"はあく":["japanese"],"ばあさん":["japanese"],"ばいか":["japanese"],"ばいく":["japanese"],"はいけん":["japanese"],"はいご":["japanese"],"はいしん":["japanese"],"はいすい":["japanese"],"はいせん":["japanese"],"はいそう":["japanese"],"はいち":["japanese"],"ばいばい":["japanese"],"はいれつ":["japanese"],"はえる":["japanese"],"はおる":["japanese"],"はかい":["japanese"],"ばかり":["japanese"],"はかる":["japanese"],"はくしゅ":["japanese"],"はけん":["japanese"],"はこぶ":["japanese"],"はさみ":["japanese"],"はさん":["japanese"],"はしご":["japanese"],"ばしょ":["japanese"],"はしる":["japanese"],"はせる":["japanese"],"ぱそこん":["japanese"],"はそん":["japanese"],"はたん":["japanese"],"はちみつ":["japanese"],"はつおん":["japanese"],"はっかく":["japanese"],"はづき":["japanese"],"はっきり":["japanese"],"はっくつ":["japanese"],"はっけん":["japanese"],"はっこう":["japanese"],"はっさん":["japanese"],"はっしん":["japanese"],"はったつ":["japanese"],"はっちゅう":["japanese"],"はってん":["japanese"],"はっぴょう":["japanese"],"はっぽう":["japanese"],"はなす":["japanese"],"はなび":["japanese"],"はにかむ":["japanese"],"はぶらし":["japanese"],"はみがき":["japanese"],"はむかう":["japanese"],"はめつ":["japanese"],"はやい":["japanese"],"はやし":["japanese"],"はらう":["japanese"],"はろうぃん":["japanese"],"はわい":["japanese"],"はんい":["japanese"],"はんえい":["japanese"],"はんおん":["japanese"],"はんかく":["japanese"],"はんきょう":["japanese"],"ばんぐみ":["japanese"],"はんこ":["japanese"],"はんしゃ":["japanese"],"はんすう":["japanese"],"はんだん":["japanese"],"ぱんち":["japanese"],"ぱんつ":["japanese"],"はんてい":["japanese"],"はんとし":["japanese"],"はんのう":["japanese"],"はんぱ":["japanese"],"はんぶん":["japanese"],"はんぺん":["japanese"],"はんぼうき":["japanese"],"はんめい":["japanese"],"はんらん":["japanese"],"はんろん":["japanese"],"ひいき":["japanese"],"ひうん":["japanese"],"ひえる":["japanese"],"ひかく":["japanese"],"ひかり":["japanese"],"ひかる":["japanese"],"ひかん":["japanese"],"ひくい":["japanese"],"ひけつ":["japanese"],"ひこうき":["japanese"],"ひこく":["japanese"],"ひさい":["japanese"],"ひさしぶり":["japanese"],"ひさん":["japanese"],"びじゅつかん":["japanese"],"ひしょ":["japanese"],"ひそか":["japanese"],"ひそむ":["japanese"],"ひたむき":["japanese"],"ひだり":["japanese"],"ひたる":["japanese"],"ひつぎ":["japanese"],"ひっこし":["japanese"],"ひっし":["japanese"],"ひつじゅひん":["japanese"],"ひっす":["japanese"],"ひつぜん":["japanese"],"ぴったり":["japanese"],"ぴっちり":["japanese"],"ひつよう":["japanese"],"ひてい":["japanese"],"ひとごみ":["japanese"],"ひなまつり":["japanese"],"ひなん":["japanese"],"ひねる":["japanese"],"ひはん":["japanese"],"ひびく":["japanese"],"ひひょう":["japanese"],"ひほう":["japanese"],"ひまわり":["japanese"],"ひまん":["japanese"],"ひみつ":["japanese"],"ひめい":["japanese"],"ひめじし":["japanese"],"ひやけ":["japanese"],"ひやす":["japanese"],"ひよう":["japanese"],"びょうき":["japanese"],"ひらがな":["japanese"],"ひらく":["japanese"],"ひりつ":["japanese"],"ひりょう":["japanese"],"ひるま":["japanese"],"ひるやすみ":["japanese"],"ひれい":["japanese"],"ひろい":["japanese"],"ひろう":["japanese"],"ひろき":["japanese"],"ひろゆき":["japanese"],"ひんかく":["japanese"],"ひんけつ":["japanese"],"ひんこん":["japanese"],"ひんしゅ":["japanese"],"ひんそう":["japanese"],"ぴんち":["japanese"],"ひんぱん":["japanese"],"びんぼう":["japanese"],"ふあん":["japanese"],"ふいうち":["japanese"],"ふうけい":["japanese"],"ふうせん":["japanese"],"ぷうたろう":["japanese"],"ふうとう":["japanese"],"ふうふ":["japanese"],"ふえる":["japanese"],"ふおん":["japanese"],"ふかい":["japanese"],"ふきん":["japanese"],"ふくざつ":["japanese"],"ふくぶくろ":["japanese"],"ふこう":["japanese"],"ふさい":["japanese"],"ふしぎ":["japanese"],"ふじみ":["japanese"],"ふすま":["japanese"],"ふせい":["japanese"],"ふせぐ":["japanese"],"ふそく":["japanese"],"ぶたにく":["japanese"],"ふたん":["japanese"],"ふちょう":["japanese"],"ふつう":["japanese"],"ふつか":["japanese"],"ふっかつ":["japanese"],"ふっき":["japanese"],"ふっこく":["japanese"],"ぶどう":["japanese"],"ふとる":["japanese"],"ふとん":["japanese"],"ふのう":["japanese"],"ふはい":["japanese"],"ふひょう":["japanese"],"ふへん":["japanese"],"ふまん":["japanese"],"ふみん":["japanese"],"ふめつ":["japanese"],"ふめん":["japanese"],"ふよう":["japanese"],"ふりこ":["japanese"],"ふりる":["japanese"],"ふるい":["japanese"],"ふんいき":["japanese"],"ぶんがく":["japanese"],"ぶんぐ":["japanese"],"ふんしつ":["japanese"],"ぶんせき":["japanese"],"ふんそう":["japanese"],"ぶんぽう":["japanese"],"へいあん":["japanese"],"へいおん":["japanese"],"へいがい":["japanese"],"へいき":["japanese"],"へいげん":["japanese"],"へいこう":["japanese"],"へいさ":["japanese"],"へいしゃ":["japanese"],"へいせつ":["japanese"],"へいそ":["japanese"],"へいたく":["japanese"],"へいてん":["japanese"],"へいねつ":["japanese"],"へいわ":["japanese"],"へきが":["japanese"],"へこむ":["japanese"],"べにいろ":["japanese"],"べにしょうが":["japanese"],"へらす":["japanese"],"へんかん":["japanese"],"べんきょう":["japanese"],"べんごし":["japanese"],"へんさい":["japanese"],"へんたい":["japanese"],"べんり":["japanese"],"ほあん":["japanese"],"ほいく":["japanese"],"ぼうぎょ":["japanese"],"ほうこく":["japanese"],"ほうそう":["japanese"],"ほうほう":["japanese"],"ほうもん":["japanese"],"ほうりつ":["japanese"],"ほえる":["japanese"],"ほおん":["japanese"],"ほかん":["japanese"],"ほきょう":["japanese"],"ぼきん":["japanese"],"ほくろ":["japanese"],"ほけつ":["japanese"],"ほけん":["japanese"],"ほこう":["japanese"],"ほこる":["japanese"],"ほしい":["japanese"],"ほしつ":["japanese"],"ほしゅ":["japanese"],"ほしょう":["japanese"],"ほせい":["japanese"],"ほそい":["japanese"],"ほそく":["japanese"],"ほたて":["japanese"],"ほたる":["japanese"],"ぽちぶくろ":["japanese"],"ほっきょく":["japanese"],"ほっさ":["japanese"],"ほったん":["japanese"],"ほとんど":["japanese"],"ほめる":["japanese"],"ほんい":["japanese"],"ほんき":["japanese"],"ほんけ":["japanese"],"ほんしつ":["japanese"],"ほんやく":["japanese"],"まいにち":["japanese"],"まかい":["japanese"],"まかせる":["japanese"],"まがる":["japanese"],"まける":["japanese"],"まこと":["japanese"],"まさつ":["japanese"],"まじめ":["japanese"],"ますく":["japanese"],"まぜる":["japanese"],"まつり":["japanese"],"まとめ":["japanese"],"まなぶ":["japanese"],"まぬけ":["japanese"],"まねく":["japanese"],"まほう":["japanese"],"まもる":["japanese"],"まゆげ":["japanese"],"まよう":["japanese"],"まろやか":["japanese"],"まわす":["japanese"],"まわり":["japanese"],"まわる":["japanese"],"まんが":["japanese"],"まんきつ":["japanese"],"まんぞく":["japanese"],"まんなか":["japanese"],"みいら":["japanese"],"みうち":["japanese"],"みえる":["japanese"],"みがく":["japanese"],"みかた":["japanese"],"みかん":["japanese"],"みけん":["japanese"],"みこん":["japanese"],"みじかい":["japanese"],"みすい":["japanese"],"みすえる":["japanese"],"みせる":["japanese"],"みっか":["japanese"],"みつかる":["japanese"],"みつける":["japanese"],"みてい":["japanese"],"みとめる":["japanese"],"みなと":["japanese"],"みなみかさい":["japanese"],"みねらる":["japanese"],"みのう":["japanese"],"みのがす":["japanese"],"みほん":["japanese"],"みもと":["japanese"],"みやげ":["japanese"],"みらい":["japanese"],"みりょく":["japanese"],"みわく":["japanese"],"みんか":["japanese"],"みんぞく":["japanese"],"むいか":["japanese"],"むえき":["japanese"],"むえん":["japanese"],"むかい":["japanese"],"むかう":["japanese"],"むかえ":["japanese"],"むかし":["japanese"],"むぎちゃ":["japanese"],"むける":["japanese"],"むげん":["japanese"],"むさぼる":["japanese"],"むしあつい":["japanese"],"むしば":["japanese"],"むじゅん":["japanese"],"むしろ":["japanese"],"むすう":["japanese"],"むすこ":["japanese"],"むすぶ":["japanese"],"むすめ":["japanese"],"むせる":["japanese"],"むせん":["japanese"],"むちゅう":["japanese"],"むなしい":["japanese"],"むのう":["japanese"],"むやみ":["japanese"],"むよう":["japanese"],"むらさき":["japanese"],"むりょう":["japanese"],"むろん":["japanese"],"めいあん":["japanese"],"めいうん":["japanese"],"めいえん":["japanese"],"めいかく":["japanese"],"めいきょく":["japanese"],"めいさい":["japanese"],"めいし":["japanese"],"めいそう":["japanese"],"めいぶつ":["japanese"],"めいれい":["japanese"],"めいわく":["japanese"],"めぐまれる":["japanese"],"めざす":["japanese"],"めした":["japanese"],"めずらしい":["japanese"],"めだつ":["japanese"],"めまい":["japanese"],"めやす":["japanese"],"めんきょ":["japanese"],"めんせき":["japanese"],"めんどう":["japanese"],"もうしあげる":["japanese"],"もうどうけん":["japanese"],"もえる":["japanese"],"もくし":["japanese"],"もくてき":["japanese"],"もくようび":["japanese"],"もちろん":["japanese"],"もどる":["japanese"],"もらう":["japanese"],"もんく":["japanese"],"もんだい":["japanese"],"やおや":["japanese"],"やける":["japanese"],"やさい":["japanese"],"やさしい":["japanese"],"やすい":["japanese"],"やすたろう":["japanese"],"やすみ":["japanese"],"やせる":["japanese"],"やそう":["japanese"],"やたい":["japanese"],"やちん":["japanese"],"やっと":["japanese"],"やっぱり":["japanese"],"やぶる":["japanese"],"やめる":["japanese"],"ややこしい":["japanese"],"やよい":["japanese"],"やわらかい":["japanese"],"ゆうき":["japanese"],"ゆうびんきょく":["japanese"],"ゆうべ":["japanese"],"ゆうめい":["japanese"],"ゆけつ":["japanese"],"ゆしゅつ":["japanese"],"ゆせん":["japanese"],"ゆそう":["japanese"],"ゆたか":["japanese"],"ゆちゃく":["japanese"],"ゆでる":["japanese"],"ゆにゅう":["japanese"],"ゆびわ":["japanese"],"ゆらい":["japanese"],"ゆれる":["japanese"],"ようい":["japanese"],"ようか":["japanese"],"ようきゅう":["japanese"],"ようじ":["japanese"],"ようす":["japanese"],"ようちえん":["japanese"],"よかぜ":["japanese"],"よかん":["japanese"],"よきん":["japanese"],"よくせい":["japanese"],"よくぼう":["japanese"],"よけい":["japanese"],"よごれる":["japanese"],"よさん":["japanese"],"よしゅう":["japanese"],"よそう":["japanese"],"よそく":["japanese"],"よっか":["japanese"],"よてい":["japanese"],"よどがわく":["japanese"],"よねつ":["japanese"],"よやく":["japanese"],"よゆう":["japanese"],"よろこぶ":["japanese"],"よろしい":["japanese"],"らいう":["japanese"],"らくがき":["japanese"],"らくご":["japanese"],"らくさつ":["japanese"],"らくだ":["japanese"],"らしんばん":["japanese"],"らせん":["japanese"],"らぞく":["japanese"],"らたい":["japanese"],"らっか":["japanese"],"られつ":["japanese"],"りえき":["japanese"],"りかい":["japanese"],"りきさく":["japanese"],"りきせつ":["japanese"],"りくぐん":["japanese"],"りくつ":["japanese"],"りけん":["japanese"],"りこう":["japanese"],"りせい":["japanese"],"りそう":["japanese"],"りそく":["japanese"],"りてん":["japanese"],"りねん":["japanese"],"りゆう":["japanese"],"りゅうがく":["japanese"],"りよう":["japanese"],"りょうり":["japanese"],"りょかん":["japanese"],"りょくちゃ":["japanese"],"りょこう":["japanese"],"りりく":["japanese"],"りれき":["japanese"],"りろん":["japanese"],"りんご":["japanese"],"るいけい":["japanese"],"るいさい":["japanese"],"るいじ":["japanese"],"るいせき":["japanese"],"るすばん":["japanese"],"るりがわら":["japanese"],"れいかん":["japanese"],"れいぎ":["japanese"],"れいせい":["japanese"],"れいぞうこ":["japanese"],"れいとう":["japanese"],"れいぼう":["japanese"],"れきし":["japanese"],"れきだい":["japanese"],"れんあい":["japanese"],"れんけい":["japanese"],"れんこん":["japanese"],"れんさい":["japanese"],"れんしゅう":["japanese"],"れんぞく":["japanese"],"れんらく":["japanese"],"ろうか":["japanese"],"ろうご":["japanese"],"ろうじん":["japanese"],"ろうそく":["japanese"],"ろくが":["japanese"],"ろこつ":["japanese"],"ろじうら":["japanese"],"ろしゅつ":["japanese"],"ろせん":["japanese"],"ろてん":["japanese"],"ろめん":["japanese"],"ろれつ":["japanese"],"ろんぎ":["japanese"],"ろんぱ":["japanese"],"ろんぶん":["japanese"],"ろんり":["japanese"],"わかす":["japanese"],"わかめ":["japanese"],"わかやま":["japanese"],"わかれる":["japanese"],"わしつ":["japanese"],"わじまし":["japanese"],"わすれもの":["japanese"],"わらう":["japanese"],"われる":["japanese"],"가격":["korean"],"가끔":["korean"],"가난":["korean"],"가능":["korean"],"가득":["korean"],"가르침":["korean"],"가뭄":["korean"],"가방":["korean"],"가상":["korean"],"가슴":["korean"],"가운데":["korean"],"가을":["korean"],"가이드":["korean"],"가입":["korean"],"가장":["korean"],"가정":["korean"],"가족":["korean"],"가죽":["korean"],"각오":["korean"],"각자":["korean"],"간격":["korean"],"간부":["korean"],"간섭":["korean"],"간장":["korean"],"간접":["korean"],"간판":["korean"],"갈등":["korean"],"갈비":["korean"],"갈색":["korean"],"갈증":["korean"],"감각":["korean"],"감기":["korean"],"감소":["korean"],"감수성":["korean"],"감자":["korean"],"감정":["korean"],"갑자기":["korean"],"강남":["korean"],"강당":["korean"],"강도":["korean"],"강력히":["korean"],"강변":["korean"],"강북":["korean"],"강사":["korean"],"강수량":["korean"],"강아지":["korean"],"강원도":["korean"],"강의":["korean"],"강제":["korean"],"강조":["korean"],"같이":["korean"],"개구리":["korean"],"개나리":["korean"],"개방":["korean"],"개별":["korean"],"개선":["korean"],"개성":["korean"],"개인":["korean"],"객관적":["korean"],"거실":["korean"],"거액":["korean"],"거울":["korean"],"거짓":["korean"],"거품":["korean"],"걱정":["korean"],"건강":["korean"],"건물":["korean"],"건설":["korean"],"건조":["korean"],"건축":["korean"],"걸음":["korean"],"검사":["korean"],"검토":["korean"],"게시판":["korean"],"게임":["korean"],"겨울":["korean"],"견해":["korean"],"결과":["korean"],"결국":["korean"],"결론":["korean"],"결석":["korean"],"결승":["korean"],"결심":["korean"],"결정":["korean"],"결혼":["korean"],"경계":["korean"],"경고":["korean"],"경기":["korean"],"경력":["korean"],"경복궁":["korean"],"경비":["korean"],"경상도":["korean"],"경영":["korean"],"경우":["korean"],"경쟁":["korean"],"경제":["korean"],"경주":["korean"],"경찰":["korean"],"경치":["korean"],"경향":["korean"],"경험":["korean"],"계곡":["korean"],"계단":["korean"],"계란":["korean"],"계산":["korean"],"계속":["korean"],"계약":["korean"],"계절":["korean"],"계층":["korean"],"계획":["korean"],"고객":["korean"],"고구려":["korean"],"고궁":["korean"],"고급":["korean"],"고등학생":["korean"],"고무신":["korean"],"고민":["korean"],"고양이":["korean"],"고장":["korean"],"고전":["korean"],"고집":["korean"],"고춧가루":["korean"],"고통":["korean"],"고향":["korean"],"곡식":["korean"],"골목":["korean"],"골짜기":["korean"],"골프":["korean"],"공간":["korean"],"공개":["korean"],"공격":["korean"],"공군":["korean"],"공급":["korean"],"공기":["korean"],"공동":["korean"],"공무원":["korean"],"공부":["korean"],"공사":["korean"],"공식":["korean"],"공업":["korean"],"공연":["korean"],"공원":["korean"],"공장":["korean"],"공짜":["korean"],"공책":["korean"],"공통":["korean"],"공포":["korean"],"공항":["korean"],"공휴일":["korean"],"과목":["korean"],"과일":["korean"],"과장":["korean"],"과정":["korean"],"과학":["korean"],"관객":["korean"],"관계":["korean"],"관광":["korean"],"관념":["korean"],"관람":["korean"],"관련":["korean"],"관리":["korean"],"관습":["korean"],"관심":["korean"],"관점":["korean"],"관찰":["korean"],"광경":["korean"],"광고":["korean"],"광장":["korean"],"광주":["korean"],"괴로움":["korean"],"굉장히":["korean"],"교과서":["korean"],"교문":["korean"],"교복":["korean"],"교실":["korean"],"교양":["korean"],"교육":["korean"],"교장":["korean"],"교직":["korean"],"교통":["korean"],"교환":["korean"],"교훈":["korean"],"구경":["korean"],"구름":["korean"],"구멍":["korean"],"구별":["korean"],"구분":["korean"],"구석":["korean"],"구성":["korean"],"구속":["korean"],"구역":["korean"],"구입":["korean"],"구청":["korean"],"구체적":["korean"],"국가":["korean"],"국기":["korean"],"국내":["korean"],"국립":["korean"],"국물":["korean"],"국민":["korean"],"국수":["korean"],"국어":["korean"],"국왕":["korean"],"국적":["korean"],"국제":["korean"],"국회":["korean"],"군대":["korean"],"군사":["korean"],"군인":["korean"],"궁극적":["korean"],"권리":["korean"],"권위":["korean"],"권투":["korean"],"귀국":["korean"],"귀신":["korean"],"규정":["korean"],"규칙":["korean"],"균형":["korean"],"그날":["korean"],"그냥":["korean"],"그늘":["korean"],"그러나":["korean"],"그룹":["korean"],"그릇":["korean"],"그림":["korean"],"그제서야":["korean"],"그토록":["korean"],"극복":["korean"],"극히":["korean"],"근거":["korean"],"근교":["korean"],"근래":["korean"],"근로":["korean"],"근무":["korean"],"근본":["korean"],"근원":["korean"],"근육":["korean"],"근처":["korean"],"글씨":["korean"],"글자":["korean"],"금강산":["korean"],"금고":["korean"],"금년":["korean"],"금메달":["korean"],"금액":["korean"],"금연":["korean"],"금요일":["korean"],"금지":["korean"],"긍정적":["korean"],"기간":["korean"],"기관":["korean"],"기념":["korean"],"기능":["korean"],"기독교":["korean"],"기둥":["korean"],"기록":["korean"],"기름":["korean"],"기법":["korean"],"기본":["korean"],"기분":["korean"],"기쁨":["korean"],"기숙사":["korean"],"기술":["korean"],"기억":["korean"],"기업":["korean"],"기온":["korean"],"기운":["korean"],"기원":["korean"],"기적":["korean"],"기준":["korean"],"기침":["korean"],"기혼":["korean"],"기획":["korean"],"긴급":["korean"],"긴장":["korean"],"길이":["korean"],"김밥":["korean"],"김치":["korean"],"김포공항":["korean"],"깍두기":["korean"],"깜빡":["korean"],"깨달음":["korean"],"깨소금":["korean"],"껍질":["korean"],"꼭대기":["korean"],"꽃잎":["korean"],"나들이":["korean"],"나란히":["korean"],"나머지":["korean"],"나물":["korean"],"나침반":["korean"],"나흘":["korean"],"낙엽":["korean"],"난방":["korean"],"날개":["korean"],"날씨":["korean"],"날짜":["korean"],"남녀":["korean"],"남대문":["korean"],"남매":["korean"],"남산":["korean"],"남자":["korean"],"남편":["korean"],"남학생":["korean"],"낭비":["korean"],"낱말":["korean"],"내년":["korean"],"내용":["korean"],"내일":["korean"],"냄비":["korean"],"냄새":["korean"],"냇물":["korean"],"냉동":["korean"],"냉면":["korean"],"냉방":["korean"],"냉장고":["korean"],"넥타이":["korean"],"넷째":["korean"],"노동":["korean"],"노란색":["korean"],"노력":["korean"],"노인":["korean"],"녹음":["korean"],"녹차":["korean"],"녹화":["korean"],"논리":["korean"],"논문":["korean"],"논쟁":["korean"],"놀이":["korean"],"농구":["korean"],"농담":["korean"],"농민":["korean"],"농부":["korean"],"농업":["korean"],"농장":["korean"],"농촌":["korean"],"높이":["korean"],"눈동자":["korean"],"눈물":["korean"],"눈썹":["korean"],"뉴욕":["korean"],"느낌":["korean"],"늑대":["korean"],"능동적":["korean"],"능력":["korean"],"다방":["korean"],"다양성":["korean"],"다음":["korean"],"다이어트":["korean"],"다행":["korean"],"단계":["korean"],"단골":["korean"],"단독":["korean"],"단맛":["korean"],"단순":["korean"],"단어":["korean"],"단위":["korean"],"단점":["korean"],"단체":["korean"],"단추":["korean"],"단편":["korean"],"단풍":["korean"],"달걀":["korean"],"달러":["korean"],"달력":["korean"],"달리":["korean"],"닭고기":["korean"],"담당":["korean"],"담배":["korean"],"담요":["korean"],"담임":["korean"],"답변":["korean"],"답장":["korean"],"당근":["korean"],"당분간":["korean"],"당연히":["korean"],"당장":["korean"],"대규모":["korean"],"대낮":["korean"],"대단히":["korean"],"대답":["korean"],"대도시":["korean"],"대략":["korean"],"대량":["korean"],"대륙":["korean"],"대문":["korean"],"대부분":["korean"],"대신":["korean"],"대응":["korean"],"대장":["korean"],"대전":["korean"],"대접":["korean"],"대중":["korean"],"대책":["korean"],"대출":["korean"],"대충":["korean"],"대통령":["korean"],"대학":["korean"],"대한민국":["korean"],"대합실":["korean"],"대형":["korean"],"덩어리":["korean"],"데이트":["korean"],"도대체":["korean"],"도덕":["korean"],"도둑":["korean"],"도망":["korean"],"도서관":["korean"],"도심":["korean"],"도움":["korean"],"도입":["korean"],"도자기":["korean"],"도저히":["korean"],"도전":["korean"],"도중":["korean"],"도착":["korean"],"독감":["korean"],"독립":["korean"],"독서":["korean"],"독일":["korean"],"독창적":["korean"],"동화책":["korean"],"뒷모습":["korean"],"뒷산":["korean"],"딸아이":["korean"],"마누라":["korean"],"마늘":["korean"],"마당":["korean"],"마라톤":["korean"],"마련":["korean"],"마무리":["korean"],"마사지":["korean"],"마약":["korean"],"마요네즈":["korean"],"마을":["korean"],"마음":["korean"],"마이크":["korean"],"마중":["korean"],"마지막":["korean"],"마찬가지":["korean"],"마찰":["korean"],"마흔":["korean"],"막걸리":["korean"],"막내":["korean"],"막상":["korean"],"만남":["korean"],"만두":["korean"],"만세":["korean"],"만약":["korean"],"만일":["korean"],"만점":["korean"],"만족":["korean"],"만화":["korean"],"많이":["korean"],"말기":["korean"],"말씀":["korean"],"말투":["korean"],"맘대로":["korean"],"망원경":["korean"],"매년":["korean"],"매달":["korean"],"매력":["korean"],"매번":["korean"],"매스컴":["korean"],"매일":["korean"],"매장":["korean"],"맥주":["korean"],"먹이":["korean"],"먼저":["korean"],"먼지":["korean"],"멀리":["korean"],"메일":["korean"],"며느리":["korean"],"며칠":["korean"],"면담":["korean"],"멸치":["korean"],"명단":["korean"],"명령":["korean"],"명예":["korean"],"명의":["korean"],"명절":["korean"],"명칭":["korean"],"명함":["korean"],"모금":["korean"],"모니터":["korean"],"모델":["korean"],"모든":["korean"],"모범":["korean"],"모습":["korean"],"모양":["korean"],"모임":["korean"],"모조리":["korean"],"모집":["korean"],"모퉁이":["korean"],"목걸이":["korean"],"목록":["korean"],"목사":["korean"],"목소리":["korean"],"목숨":["korean"],"목적":["korean"],"목표":["korean"],"몰래":["korean"],"몸매":["korean"],"몸무게":["korean"],"몸살":["korean"],"몸속":["korean"],"몸짓":["korean"],"몸통":["korean"],"몹시":["korean"],"무관심":["korean"],"무궁화":["korean"],"무더위":["korean"],"무덤":["korean"],"무릎":["korean"],"무슨":["korean"],"무엇":["korean"],"무역":["korean"],"무용":["korean"],"무조건":["korean"],"무지개":["korean"],"무척":["korean"],"문구":["korean"],"문득":["korean"],"문법":["korean"],"문서":["korean"],"문제":["korean"],"문학":["korean"],"문화":["korean"],"물가":["korean"],"물건":["korean"],"물결":["korean"],"물고기":["korean"],"물론":["korean"],"물리학":["korean"],"물음":["korean"],"물질":["korean"],"물체":["korean"],"미국":["korean"],"미디어":["korean"],"미사일":["korean"],"미술":["korean"],"미역":["korean"],"미용실":["korean"],"미움":["korean"],"미인":["korean"],"미팅":["korean"],"미혼":["korean"],"민간":["korean"],"민족":["korean"],"민주":["korean"],"믿음":["korean"],"밀가루":["korean"],"밀리미터":["korean"],"밑바닥":["korean"],"바가지":["korean"],"바구니":["korean"],"바나나":["korean"],"바늘":["korean"],"바닥":["korean"],"바닷가":["korean"],"바람":["korean"],"바이러스":["korean"],"바탕":["korean"],"박물관":["korean"],"박사":["korean"],"박수":["korean"],"반대":["korean"],"반드시":["korean"],"반말":["korean"],"반발":["korean"],"반성":["korean"],"반응":["korean"],"반장":["korean"],"반죽":["korean"],"반지":["korean"],"반찬":["korean"],"받침":["korean"],"발가락":["korean"],"발걸음":["korean"],"발견":["korean"],"발달":["korean"],"발레":["korean"],"발목":["korean"],"발바닥":["korean"],"발생":["korean"],"발음":["korean"],"발자국":["korean"],"발전":["korean"],"발톱":["korean"],"발표":["korean"],"밤하늘":["korean"],"밥그릇":["korean"],"밥맛":["korean"],"밥상":["korean"],"밥솥":["korean"],"방금":["korean"],"방면":["korean"],"방문":["korean"],"방바닥":["korean"],"방법":["korean"],"방송":["korean"],"방식":["korean"],"방안":["korean"],"방울":["korean"],"방지":["korean"],"방학":["korean"],"방해":["korean"],"방향":["korean"],"배경":["korean"],"배꼽":["korean"],"배달":["korean"],"배드민턴":["korean"],"백두산":["korean"],"백색":["korean"],"백성":["korean"],"백인":["korean"],"백제":["korean"],"백화점":["korean"],"버릇":["korean"],"버섯":["korean"],"버튼":["korean"],"번개":["korean"],"번역":["korean"],"번지":["korean"],"번호":["korean"],"벌금":["korean"],"벌레":["korean"],"벌써":["korean"],"범위":["korean"],"범인":["korean"],"범죄":["korean"],"법률":["korean"],"법원":["korean"],"법적":["korean"],"법칙":["korean"],"베이징":["korean"],"벨트":["korean"],"변경":["korean"],"변동":["korean"],"변명":["korean"],"변신":["korean"],"변호사":["korean"],"변화":["korean"],"별도":["korean"],"별명":["korean"],"별일":["korean"],"병실":["korean"],"병아리":["korean"],"병원":["korean"],"보관":["korean"],"보너스":["korean"],"보라색":["korean"],"보람":["korean"],"보름":["korean"],"보상":["korean"],"보안":["korean"],"보자기":["korean"],"보장":["korean"],"보전":["korean"],"보존":["korean"],"보통":["korean"],"보편적":["korean"],"보험":["korean"],"복도":["korean"],"복사":["korean"],"복숭아":["korean"],"복습":["korean"],"볶음":["korean"],"본격적":["korean"],"본래":["korean"],"본부":["korean"],"본사":["korean"],"본성":["korean"],"본인":["korean"],"본질":["korean"],"볼펜":["korean"],"봉사":["korean"],"봉지":["korean"],"봉투":["korean"],"부근":["korean"],"부끄러움":["korean"],"부담":["korean"],"부동산":["korean"],"부문":["korean"],"부분":["korean"],"부산":["korean"],"부상":["korean"],"부엌":["korean"],"부인":["korean"],"부작용":["korean"],"부장":["korean"],"부정":["korean"],"부족":["korean"],"부지런히":["korean"],"부친":["korean"],"부탁":["korean"],"부품":["korean"],"부회장":["korean"],"북부":["korean"],"북한":["korean"],"분노":["korean"],"분량":["korean"],"분리":["korean"],"분명":["korean"],"분석":["korean"],"분야":["korean"],"분위기":["korean"],"분필":["korean"],"분홍색":["korean"],"불고기":["korean"],"불과":["korean"],"불교":["korean"],"불꽃":["korean"],"불만":["korean"],"불법":["korean"],"불빛":["korean"],"불안":["korean"],"불이익":["korean"],"불행":["korean"],"브랜드":["korean"],"비극":["korean"],"비난":["korean"],"비닐":["korean"],"비둘기":["korean"],"비디오":["korean"],"비로소":["korean"],"비만":["korean"],"비명":["korean"],"비밀":["korean"],"비바람":["korean"],"비빔밥":["korean"],"비상":["korean"],"비용":["korean"],"비율":["korean"],"비중":["korean"],"비타민":["korean"],"비판":["korean"],"빌딩":["korean"],"빗물":["korean"],"빗방울":["korean"],"빗줄기":["korean"],"빛깔":["korean"],"빨간색":["korean"],"빨래":["korean"],"빨리":["korean"],"사건":["korean"],"사계절":["korean"],"사나이":["korean"],"사냥":["korean"],"사람":["korean"],"사랑":["korean"],"사립":["korean"],"사모님":["korean"],"사물":["korean"],"사방":["korean"],"사상":["korean"],"사생활":["korean"],"사설":["korean"],"사슴":["korean"],"사실":["korean"],"사업":["korean"],"사용":["korean"],"사월":["korean"],"사장":["korean"],"사전":["korean"],"사진":["korean"],"사촌":["korean"],"사춘기":["korean"],"사탕":["korean"],"사투리":["korean"],"사흘":["korean"],"산길":["korean"],"산부인과":["korean"],"산업":["korean"],"산책":["korean"],"살림":["korean"],"살인":["korean"],"살짝":["korean"],"삼계탕":["korean"],"삼국":["korean"],"삼십":["korean"],"삼월":["korean"],"삼촌":["korean"],"상관":["korean"],"상금":["korean"],"상대":["korean"],"상류":["korean"],"상반기":["korean"],"상상":["korean"],"상식":["korean"],"상업":["korean"],"상인":["korean"],"상자":["korean"],"상점":["korean"],"상처":["korean"],"상추":["korean"],"상태":["korean"],"상표":["korean"],"상품":["korean"],"상황":["korean"],"새벽":["korean"],"색깔":["korean"],"색연필":["korean"],"생각":["korean"],"생명":["korean"],"생물":["korean"],"생방송":["korean"],"생산":["korean"],"생선":["korean"],"생신":["korean"],"생일":["korean"],"생활":["korean"],"서랍":["korean"],"서른":["korean"],"서명":["korean"],"서민":["korean"],"서비스":["korean"],"서양":["korean"],"서울":["korean"],"서적":["korean"],"서점":["korean"],"서쪽":["korean"],"서클":["korean"],"석사":["korean"],"석유":["korean"],"선거":["korean"],"선물":["korean"],"선배":["korean"],"선생":["korean"],"선수":["korean"],"선원":["korean"],"선장":["korean"],"선전":["korean"],"선택":["korean"],"선풍기":["korean"],"설거지":["korean"],"설날":["korean"],"설렁탕":["korean"],"설명":["korean"],"설문":["korean"],"설사":["korean"],"설악산":["korean"],"설치":["korean"],"설탕":["korean"],"섭씨":["korean"],"성공":["korean"],"성당":["korean"],"성명":["korean"],"성별":["korean"],"성인":["korean"],"성장":["korean"],"성적":["korean"],"성질":["korean"],"성함":["korean"],"세금":["korean"],"세미나":["korean"],"세상":["korean"],"세월":["korean"],"세종대왕":["korean"],"세탁":["korean"],"센터":["korean"],"센티미터":["korean"],"셋째":["korean"],"소규모":["korean"],"소극적":["korean"],"소금":["korean"],"소나기":["korean"],"소년":["korean"],"소득":["korean"],"소망":["korean"],"소문":["korean"],"소설":["korean"],"소속":["korean"],"소아과":["korean"],"소용":["korean"],"소원":["korean"],"소음":["korean"],"소중히":["korean"],"소지품":["korean"],"소질":["korean"],"소풍":["korean"],"소형":["korean"],"속담":["korean"],"속도":["korean"],"속옷":["korean"],"손가락":["korean"],"손길":["korean"],"손녀":["korean"],"손님":["korean"],"손등":["korean"],"손목":["korean"],"손뼉":["korean"],"손실":["korean"],"손질":["korean"],"손톱":["korean"],"손해":["korean"],"솔직히":["korean"],"솜씨":["korean"],"송아지":["korean"],"송이":["korean"],"송편":["korean"],"쇠고기":["korean"],"쇼핑":["korean"],"수건":["korean"],"수년":["korean"],"수단":["korean"],"수돗물":["korean"],"수동적":["korean"],"수면":["korean"],"수명":["korean"],"수박":["korean"],"수상":["korean"],"수석":["korean"],"수술":["korean"],"수시로":["korean"],"수업":["korean"],"수염":["korean"],"수영":["korean"],"수입":["korean"],"수준":["korean"],"수집":["korean"],"수출":["korean"],"수컷":["korean"],"수필":["korean"],"수학":["korean"],"수험생":["korean"],"수화기":["korean"],"숙녀":["korean"],"숙소":["korean"],"숙제":["korean"],"순간":["korean"],"순서":["korean"],"순수":["korean"],"순식간":["korean"],"순위":["korean"],"숟가락":["korean"],"술병":["korean"],"술집":["korean"],"숫자":["korean"],"스님":["korean"],"스물":["korean"],"스스로":["korean"],"스승":["korean"],"스웨터":["korean"],"스위치":["korean"],"스케이트":["korean"],"스튜디오":["korean"],"스트레스":["korean"],"스포츠":["korean"],"슬쩍":["korean"],"슬픔":["korean"],"습관":["korean"],"습기":["korean"],"승객":["korean"],"승리":["korean"],"승부":["korean"],"승용차":["korean"],"승진":["korean"],"시각":["korean"],"시간":["korean"],"시골":["korean"],"시금치":["korean"],"시나리오":["korean"],"시댁":["korean"],"시리즈":["korean"],"시멘트":["korean"],"시민":["korean"],"시부모":["korean"],"시선":["korean"],"시설":["korean"],"시스템":["korean"],"시아버지":["korean"],"시어머니":["korean"],"시월":["korean"],"시인":["korean"],"시일":["korean"],"시작":["korean"],"시장":["korean"],"시절":["korean"],"시점":["korean"],"시중":["korean"],"시즌":["korean"],"시집":["korean"],"시청":["korean"],"시합":["korean"],"시험":["korean"],"식구":["korean"],"식기":["korean"],"식당":["korean"],"식량":["korean"],"식료품":["korean"],"식물":["korean"],"식빵":["korean"],"식사":["korean"],"식생활":["korean"],"식초":["korean"],"식탁":["korean"],"식품":["korean"],"신고":["korean"],"신규":["korean"],"신념":["korean"],"신문":["korean"],"신발":["korean"],"신비":["korean"],"신사":["korean"],"신세":["korean"],"신용":["korean"],"신제품":["korean"],"신청":["korean"],"신체":["korean"],"신화":["korean"],"실감":["korean"],"실내":["korean"],"실력":["korean"],"실례":["korean"],"실망":["korean"],"실수":["korean"],"실습":["korean"],"실시":["korean"],"실장":["korean"],"실정":["korean"],"실질적":["korean"],"실천":["korean"],"실체":["korean"],"실컷":["korean"],"실태":["korean"],"실패":["korean"],"실험":["korean"],"실현":["korean"],"심리":["korean"],"심부름":["korean"],"심사":["korean"],"심장":["korean"],"심정":["korean"],"심판":["korean"],"쌍둥이":["korean"],"씨름":["korean"],"씨앗":["korean"],"아가씨":["korean"],"아나운서":["korean"],"아드님":["korean"],"아들":["korean"],"아쉬움":["korean"],"아스팔트":["korean"],"아시아":["korean"],"아울러":["korean"],"아저씨":["korean"],"아줌마":["korean"],"아직":["korean"],"아침":["korean"],"아파트":["korean"],"아프리카":["korean"],"아픔":["korean"],"아홉":["korean"],"아흔":["korean"],"악기":["korean"],"악몽":["korean"],"악수":["korean"],"안개":["korean"],"안경":["korean"],"안과":["korean"],"안내":["korean"],"안녕":["korean"],"안동":["korean"],"안방":["korean"],"안부":["korean"],"안주":["korean"],"알루미늄":["korean"],"알코올":["korean"],"암시":["korean"],"암컷":["korean"],"압력":["korean"],"앞날":["korean"],"앞문":["korean"],"애인":["korean"],"애정":["korean"],"액수":["korean"],"앨범":["korean"],"야간":["korean"],"야단":["korean"],"야옹":["korean"],"약간":["korean"],"약국":["korean"],"약속":["korean"],"약수":["korean"],"약점":["korean"],"약품":["korean"],"약혼녀":["korean"],"양념":["korean"],"양력":["korean"],"양말":["korean"],"양배추":["korean"],"양주":["korean"],"양파":["korean"],"어둠":["korean"],"어려움":["korean"],"어른":["korean"],"어젯밤":["korean"],"어쨌든":["korean"],"어쩌다가":["korean"],"어쩐지":["korean"],"언니":["korean"],"언덕":["korean"],"언론":["korean"],"언어":["korean"],"얼굴":["korean"],"얼른":["korean"],"얼음":["korean"],"얼핏":["korean"],"엄마":["korean"],"업무":["korean"],"업종":["korean"],"업체":["korean"],"엉덩이":["korean"],"엉망":["korean"],"엉터리":["korean"],"엊그제":["korean"],"에너지":["korean"],"에어컨":["korean"],"엔진":["korean"],"여건":["korean"],"여고생":["korean"],"여관":["korean"],"여군":["korean"],"여권":["korean"],"여대생":["korean"],"여덟":["korean"],"여동생":["korean"],"여든":["korean"],"여론":["korean"],"여름":["korean"],"여섯":["korean"],"여성":["korean"],"여왕":["korean"],"여인":["korean"],"여전히":["korean"],"여직원":["korean"],"여학생":["korean"],"여행":["korean"],"역사":["korean"],"역시":["korean"],"역할":["korean"],"연결":["korean"],"연구":["korean"],"연극":["korean"],"연기":["korean"],"연락":["korean"],"연설":["korean"],"연세":["korean"],"연속":["korean"],"연습":["korean"],"연애":["korean"],"연예인":["korean"],"연인":["korean"],"연장":["korean"],"연주":["korean"],"연출":["korean"],"연필":["korean"],"연합":["korean"],"연휴":["korean"],"열기":["korean"],"열매":["korean"],"열쇠":["korean"],"열심히":["korean"],"열정":["korean"],"열차":["korean"],"열흘":["korean"],"염려":["korean"],"엽서":["korean"],"영국":["korean"],"영남":["korean"],"영상":["korean"],"영양":["korean"],"영역":["korean"],"영웅":["korean"],"영원히":["korean"],"영하":["korean"],"영향":["korean"],"영혼":["korean"],"영화":["korean"],"옆구리":["korean"],"옆방":["korean"],"옆집":["korean"],"예감":["korean"],"예금":["korean"],"예방":["korean"],"예산":["korean"],"예상":["korean"],"예선":["korean"],"예술":["korean"],"예습":["korean"],"예식장":["korean"],"예약":["korean"],"예전":["korean"],"예절":["korean"],"예정":["korean"],"예컨대":["korean"],"옛날":["korean"],"오늘":["korean"],"오락":["korean"],"오랫동안":["korean"],"오렌지":["korean"],"오로지":["korean"],"오른발":["korean"],"오븐":["korean"],"오십":["korean"],"오염":["korean"],"오월":["korean"],"오전":["korean"],"오직":["korean"],"오징어":["korean"],"오페라":["korean"],"오피스텔":["korean"],"오히려":["korean"],"옥상":["korean"],"옥수수":["korean"],"온갖":["korean"],"온라인":["korean"],"온몸":["korean"],"온종일":["korean"],"온통":["korean"],"올가을":["korean"],"올림픽":["korean"],"올해":["korean"],"옷차림":["korean"],"와이셔츠":["korean"],"와인":["korean"],"완성":["korean"],"완전":["korean"],"왕비":["korean"],"왕자":["korean"],"왜냐하면":["korean"],"왠지":["korean"],"외갓집":["korean"],"외국":["korean"],"외로움":["korean"],"외삼촌":["korean"],"외출":["korean"],"외침":["korean"],"외할머니":["korean"],"왼발":["korean"],"왼손":["korean"],"왼쪽":["korean"],"요금":["korean"],"요일":["korean"],"요즘":["korean"],"요청":["korean"],"용기":["korean"],"용서":["korean"],"용어":["korean"],"우산":["korean"],"우선":["korean"],"우승":["korean"],"우연히":["korean"],"우정":["korean"],"우체국":["korean"],"우편":["korean"],"운동":["korean"],"운명":["korean"],"운반":["korean"],"운전":["korean"],"운행":["korean"],"울산":["korean"],"울음":["korean"],"움직임":["korean"],"웃어른":["korean"],"웃음":["korean"],"워낙":["korean"],"원고":["korean"],"원래":["korean"],"원서":["korean"],"원숭이":["korean"],"원인":["korean"],"원장":["korean"],"원피스":["korean"],"월급":["korean"],"월드컵":["korean"],"월세":["korean"],"월요일":["korean"],"웨이터":["korean"],"위반":["korean"],"위법":["korean"],"위성":["korean"],"위원":["korean"],"위험":["korean"],"위협":["korean"],"윗사람":["korean"],"유난히":["korean"],"유럽":["korean"],"유명":["korean"],"유물":["korean"],"유산":["korean"],"유적":["korean"],"유치원":["korean"],"유학":["korean"],"유행":["korean"],"유형":["korean"],"육군":["korean"],"육상":["korean"],"육십":["korean"],"육체":["korean"],"은행":["korean"],"음력":["korean"],"음료":["korean"],"음반":["korean"],"음성":["korean"],"음식":["korean"],"음악":["korean"],"음주":["korean"],"의견":["korean"],"의논":["korean"],"의문":["korean"],"의복":["korean"],"의식":["korean"],"의심":["korean"],"의외로":["korean"],"의욕":["korean"],"의원":["korean"],"의학":["korean"],"이것":["korean"],"이곳":["korean"],"이념":["korean"],"이놈":["korean"],"이달":["korean"],"이대로":["korean"],"이동":["korean"],"이렇게":["korean"],"이력서":["korean"],"이론적":["korean"],"이름":["korean"],"이민":["korean"],"이발소":["korean"],"이별":["korean"],"이불":["korean"],"이빨":["korean"],"이상":["korean"],"이성":["korean"],"이슬":["korean"],"이야기":["korean"],"이용":["korean"],"이웃":["korean"],"이월":["korean"],"이윽고":["korean"],"이익":["korean"],"이전":["korean"],"이중":["korean"],"이튿날":["korean"],"이틀":["korean"],"이혼":["korean"],"인간":["korean"],"인격":["korean"],"인공":["korean"],"인구":["korean"],"인근":["korean"],"인기":["korean"],"인도":["korean"],"인류":["korean"],"인물":["korean"],"인생":["korean"],"인쇄":["korean"],"인연":["korean"],"인원":["korean"],"인재":["korean"],"인종":["korean"],"인천":["korean"],"인체":["korean"],"인터넷":["korean"],"인하":["korean"],"인형":["korean"],"일곱":["korean"],"일기":["korean"],"일단":["korean"],"일대":["korean"],"일등":["korean"],"일반":["korean"],"일본":["korean"],"일부":["korean"],"일상":["korean"],"일생":["korean"],"일손":["korean"],"일요일":["korean"],"일월":["korean"],"일정":["korean"],"일종":["korean"],"일주일":["korean"],"일찍":["korean"],"일체":["korean"],"일치":["korean"],"일행":["korean"],"일회용":["korean"],"임금":["korean"],"임무":["korean"],"입대":["korean"],"입력":["korean"],"입맛":["korean"],"입사":["korean"],"입술":["korean"],"입시":["korean"],"입원":["korean"],"입장":["korean"],"입학":["korean"],"자가용":["korean"],"자격":["korean"],"자극":["korean"],"자동":["korean"],"자랑":["korean"],"자부심":["korean"],"자식":["korean"],"자신":["korean"],"자연":["korean"],"자원":["korean"],"자율":["korean"],"자전거":["korean"],"자정":["korean"],"자존심":["korean"],"자판":["korean"],"작가":["korean"],"작년":["korean"],"작성":["korean"],"작업":["korean"],"작용":["korean"],"작은딸":["korean"],"작품":["korean"],"잔디":["korean"],"잔뜩":["korean"],"잔치":["korean"],"잘못":["korean"],"잠깐":["korean"],"잠수함":["korean"],"잠시":["korean"],"잠옷":["korean"],"잠자리":["korean"],"잡지":["korean"],"장관":["korean"],"장군":["korean"],"장기간":["korean"],"장래":["korean"],"장례":["korean"],"장르":["korean"],"장마":["korean"],"장면":["korean"],"장모":["korean"],"장미":["korean"],"장비":["korean"],"장사":["korean"],"장소":["korean"],"장식":["korean"],"장애인":["korean"],"장인":["korean"],"장점":["korean"],"장차":["korean"],"장학금":["korean"],"재능":["korean"],"재빨리":["korean"],"재산":["korean"],"재생":["korean"],"재작년":["korean"],"재정":["korean"],"재채기":["korean"],"재판":["korean"],"재학":["korean"],"재활용":["korean"],"저것":["korean"],"저고리":["korean"],"저곳":["korean"],"저녁":["korean"],"저런":["korean"],"저렇게":["korean"],"저번":["korean"],"저울":["korean"],"저절로":["korean"],"저축":["korean"],"적극":["korean"],"적당히":["korean"],"적성":["korean"],"적용":["korean"],"적응":["korean"],"전개":["korean"],"전공":["korean"],"전기":["korean"],"전달":["korean"],"전라도":["korean"],"전망":["korean"],"전문":["korean"],"전반":["korean"],"전부":["korean"],"전세":["korean"],"전시":["korean"],"전용":["korean"],"전자":["korean"],"전쟁":["korean"],"전주":["korean"],"전철":["korean"],"전체":["korean"],"전통":["korean"],"전혀":["korean"],"전후":["korean"],"절대":["korean"],"절망":["korean"],"절반":["korean"],"절약":["korean"],"절차":["korean"],"점검":["korean"],"점수":["korean"],"점심":["korean"],"점원":["korean"],"점점":["korean"],"점차":["korean"],"접근":["korean"],"접시":["korean"],"접촉":["korean"],"젓가락":["korean"],"정거장":["korean"],"정도":["korean"],"정류장":["korean"],"정리":["korean"],"정말":["korean"],"정면":["korean"],"정문":["korean"],"정반대":["korean"],"정보":["korean"],"정부":["korean"],"정비":["korean"],"정상":["korean"],"정성":["korean"],"정오":["korean"],"정원":["korean"],"정장":["korean"],"정지":["korean"],"정치":["korean"],"정확히":["korean"],"제공":["korean"],"제과점":["korean"],"제대로":["korean"],"제목":["korean"],"제발":["korean"],"제법":["korean"],"제삿날":["korean"],"제안":["korean"],"제일":["korean"],"제작":["korean"],"제주도":["korean"],"제출":["korean"],"제품":["korean"],"제한":["korean"],"조각":["korean"],"조건":["korean"],"조금":["korean"],"조깅":["korean"],"조명":["korean"],"조미료":["korean"],"조상":["korean"],"조선":["korean"],"조용히":["korean"],"조절":["korean"],"조정":["korean"],"조직":["korean"],"존댓말":["korean"],"존재":["korean"],"졸업":["korean"],"졸음":["korean"],"종교":["korean"],"종로":["korean"],"종류":["korean"],"종소리":["korean"],"종업원":["korean"],"종종":["korean"],"종합":["korean"],"좌석":["korean"],"죄인":["korean"],"주관적":["korean"],"주름":["korean"],"주말":["korean"],"주머니":["korean"],"주먹":["korean"],"주문":["korean"],"주민":["korean"],"주방":["korean"],"주변":["korean"],"주식":["korean"],"주인":["korean"],"주일":["korean"],"주장":["korean"],"주전자":["korean"],"주택":["korean"],"준비":["korean"],"줄거리":["korean"],"줄기":["korean"],"줄무늬":["korean"],"중간":["korean"],"중계방송":["korean"],"중국":["korean"],"중년":["korean"],"중단":["korean"],"중독":["korean"],"중반":["korean"],"중부":["korean"],"중세":["korean"],"중소기업":["korean"],"중순":["korean"],"중앙":["korean"],"중요":["korean"],"중학교":["korean"],"즉석":["korean"],"즉시":["korean"],"즐거움":["korean"],"증가":["korean"],"증거":["korean"],"증권":["korean"],"증상":["korean"],"증세":["korean"],"지각":["korean"],"지갑":["korean"],"지경":["korean"],"지극히":["korean"],"지금":["korean"],"지급":["korean"],"지능":["korean"],"지름길":["korean"],"지리산":["korean"],"지방":["korean"],"지붕":["korean"],"지식":["korean"],"지역":["korean"],"지우개":["korean"],"지원":["korean"],"지적":["korean"],"지점":["korean"],"지진":["korean"],"지출":["korean"],"직선":["korean"],"직업":["korean"],"직원":["korean"],"직장":["korean"],"진급":["korean"],"진동":["korean"],"진로":["korean"],"진료":["korean"],"진리":["korean"],"진짜":["korean"],"진찰":["korean"],"진출":["korean"],"진통":["korean"],"진행":["korean"],"질문":["korean"],"질병":["korean"],"질서":["korean"],"짐작":["korean"],"집단":["korean"],"집안":["korean"],"집중":["korean"],"짜증":["korean"],"찌꺼기":["korean"],"차남":["korean"],"차라리":["korean"],"차량":["korean"],"차림":["korean"],"차별":["korean"],"차선":["korean"],"차츰":["korean"],"착각":["korean"],"찬물":["korean"],"찬성":["korean"],"참가":["korean"],"참기름":["korean"],"참새":["korean"],"참석":["korean"],"참여":["korean"],"참외":["korean"],"참조":["korean"],"찻잔":["korean"],"창가":["korean"],"창고":["korean"],"창구":["korean"],"창문":["korean"],"창밖":["korean"],"창작":["korean"],"창조":["korean"],"채널":["korean"],"채점":["korean"],"책가방":["korean"],"책방":["korean"],"책상":["korean"],"책임":["korean"],"챔피언":["korean"],"처벌":["korean"],"처음":["korean"],"천국":["korean"],"천둥":["korean"],"천장":["korean"],"천재":["korean"],"천천히":["korean"],"철도":["korean"],"철저히":["korean"],"철학":["korean"],"첫날":["korean"],"첫째":["korean"],"청년":["korean"],"청바지":["korean"],"청소":["korean"],"청춘":["korean"],"체계":["korean"],"체력":["korean"],"체온":["korean"],"체육":["korean"],"체중":["korean"],"체험":["korean"],"초등학생":["korean"],"초반":["korean"],"초밥":["korean"],"초상화":["korean"],"초순":["korean"],"초여름":["korean"],"초원":["korean"],"초저녁":["korean"],"초점":["korean"],"초청":["korean"],"초콜릿":["korean"],"촛불":["korean"],"총각":["korean"],"총리":["korean"],"총장":["korean"],"촬영":["korean"],"최근":["korean"],"최상":["korean"],"최선":["korean"],"최신":["korean"],"최악":["korean"],"최종":["korean"],"추석":["korean"],"추억":["korean"],"추진":["korean"],"추천":["korean"],"추측":["korean"],"축구":["korean"],"축소":["korean"],"축제":["korean"],"축하":["korean"],"출근":["korean"],"출발":["korean"],"출산":["korean"],"출신":["korean"],"출연":["korean"],"출입":["korean"],"출장":["korean"],"출판":["korean"],"충격":["korean"],"충고":["korean"],"충돌":["korean"],"충분히":["korean"],"충청도":["korean"],"취업":["korean"],"취직":["korean"],"취향":["korean"],"치약":["korean"],"친구":["korean"],"친척":["korean"],"칠십":["korean"],"칠월":["korean"],"칠판":["korean"],"침대":["korean"],"침묵":["korean"],"침실":["korean"],"칫솔":["korean"],"칭찬":["korean"],"카메라":["korean"],"카운터":["korean"],"칼국수":["korean"],"캐릭터":["korean"],"캠퍼스":["korean"],"캠페인":["korean"],"커튼":["korean"],"컨디션":["korean"],"컬러":["korean"],"컴퓨터":["korean"],"코끼리":["korean"],"코미디":["korean"],"콘서트":["korean"],"콜라":["korean"],"콤플렉스":["korean"],"콩나물":["korean"],"쾌감":["korean"],"쿠데타":["korean"],"크림":["korean"],"큰길":["korean"],"큰딸":["korean"],"큰소리":["korean"],"큰아들":["korean"],"큰어머니":["korean"],"큰일":["korean"],"큰절":["korean"],"클래식":["korean"],"클럽":["korean"],"킬로":["korean"],"타입":["korean"],"타자기":["korean"],"탁구":["korean"],"탁자":["korean"],"탄생":["korean"],"태권도":["korean"],"태양":["korean"],"태풍":["korean"],"택시":["korean"],"탤런트":["korean"],"터널":["korean"],"터미널":["korean"],"테니스":["korean"],"테스트":["korean"],"테이블":["korean"],"텔레비전":["korean"],"토론":["korean"],"토마토":["korean"],"토요일":["korean"],"통계":["korean"],"통과":["korean"],"통로":["korean"],"통신":["korean"],"통역":["korean"],"통일":["korean"],"통장":["korean"],"통제":["korean"],"통증":["korean"],"통합":["korean"],"통화":["korean"],"퇴근":["korean"],"퇴원":["korean"],"퇴직금":["korean"],"튀김":["korean"],"트럭":["korean"],"특급":["korean"],"특별":["korean"],"특성":["korean"],"특수":["korean"],"특징":["korean"],"특히":["korean"],"튼튼히":["korean"],"티셔츠":["korean"],"파란색":["korean"],"파일":["korean"],"파출소":["korean"],"판결":["korean"],"판단":["korean"],"판매":["korean"],"판사":["korean"],"팔십":["korean"],"팔월":["korean"],"팝송":["korean"],"패션":["korean"],"팩스":["korean"],"팩시밀리":["korean"],"팬티":["korean"],"퍼센트":["korean"],"페인트":["korean"],"편견":["korean"],"편의":["korean"],"편지":["korean"],"편히":["korean"],"평가":["korean"],"평균":["korean"],"평생":["korean"],"평소":["korean"],"평양":["korean"],"평일":["korean"],"평화":["korean"],"포스터":["korean"],"포인트":["korean"],"포장":["korean"],"포함":["korean"],"표면":["korean"],"표정":["korean"],"표준":["korean"],"표현":["korean"],"품목":["korean"],"품질":["korean"],"풍경":["korean"],"풍속":["korean"],"풍습":["korean"],"프랑스":["korean"],"프린터":["korean"],"플라스틱":["korean"],"피곤":["korean"],"피망":["korean"],"피아노":["korean"],"필름":["korean"],"필수":["korean"],"필요":["korean"],"필자":["korean"],"필통":["korean"],"핑계":["korean"],"하느님":["korean"],"하늘":["korean"],"하드웨어":["korean"],"하룻밤":["korean"],"하반기":["korean"],"하숙집":["korean"],"하순":["korean"],"하여튼":["korean"],"하지만":["korean"],"하천":["korean"],"하품":["korean"],"하필":["korean"],"학과":["korean"],"학교":["korean"],"학급":["korean"],"학기":["korean"],"학년":["korean"],"학력":["korean"],"학번":["korean"],"학부모":["korean"],"학비":["korean"],"학생":["korean"],"학술":["korean"],"학습":["korean"],"학용품":["korean"],"학원":["korean"],"학위":["korean"],"학자":["korean"],"학점":["korean"],"한계":["korean"],"한글":["korean"],"한꺼번에":["korean"],"한낮":["korean"],"한눈":["korean"],"한동안":["korean"],"한때":["korean"],"한라산":["korean"],"한마디":["korean"],"한문":["korean"],"한번":["korean"],"한복":["korean"],"한식":["korean"],"한여름":["korean"],"한쪽":["korean"],"할머니":["korean"],"할아버지":["korean"],"할인":["korean"],"함께":["korean"],"함부로":["korean"],"합격":["korean"],"합리적":["korean"],"항공":["korean"],"항구":["korean"],"항상":["korean"],"항의":["korean"],"해결":["korean"],"해군":["korean"],"해답":["korean"],"해당":["korean"],"해물":["korean"],"해석":["korean"],"해설":["korean"],"해수욕장":["korean"],"해안":["korean"],"핵심":["korean"],"핸드백":["korean"],"햄버거":["korean"],"햇볕":["korean"],"햇살":["korean"],"행동":["korean"],"행복":["korean"],"행사":["korean"],"행운":["korean"],"행위":["korean"],"향기":["korean"],"향상":["korean"],"향수":["korean"],"허락":["korean"],"허용":["korean"],"헬기":["korean"],"현관":["korean"],"현금":["korean"],"현대":["korean"],"현상":["korean"],"현실":["korean"],"현장":["korean"],"현재":["korean"],"현지":["korean"],"혈액":["korean"],"협력":["korean"],"형부":["korean"],"형사":["korean"],"형수":["korean"],"형식":["korean"],"형제":["korean"],"형태":["korean"],"형편":["korean"],"혜택":["korean"],"호기심":["korean"],"호남":["korean"],"호랑이":["korean"],"호박":["korean"],"호텔":["korean"],"호흡":["korean"],"혹시":["korean"],"홀로":["korean"],"홈페이지":["korean"],"홍보":["korean"],"홍수":["korean"],"홍차":["korean"],"화면":["korean"],"화분":["korean"],"화살":["korean"],"화요일":["korean"],"화장":["korean"],"화학":["korean"],"확보":["korean"],"확인":["korean"],"확장":["korean"],"확정":["korean"],"환갑":["korean"],"환경":["korean"],"환영":["korean"],"환율":["korean"],"환자":["korean"],"활기":["korean"],"활동":["korean"],"활발히":["korean"],"활용":["korean"],"활짝":["korean"],"회견":["korean"],"회관":["korean"],"회복":["korean"],"회색":["korean"],"회원":["korean"],"회장":["korean"],"회전":["korean"],"횟수":["korean"],"횡단보도":["korean"],"효율적":["korean"],"후반":["korean"],"후춧가루":["korean"],"훈련":["korean"],"훨씬":["korean"],"휴식":["korean"],"휴일":["korean"],"흉내":["korean"],"흐름":["korean"],"흑백":["korean"],"흑인":["korean"],"흔적":["korean"],"흔히":["korean"],"흥미":["korean"],"흥분":["korean"],"희곡":["korean"],"희망":["korean"],"희생":["korean"],"흰색":["korean"],"힘껏":["korean"],"abacate":["portuguese"],"abaixo":["portuguese"],"abalar":["portuguese"],"abater":["portuguese"],"abduzir":["portuguese"],"abelha":["portuguese"],"aberto":["portuguese"],"abismo":["portuguese"],"abotoar":["portuguese"],"abranger":["portuguese"],"abreviar":["portuguese"],"abrigar":["portuguese"],"abrupto":["portuguese"],"absinto":["portuguese"],"absoluto":["portuguese"],"absurdo":["portuguese"],"abutre":["portuguese"],"acabado":["portuguese"],"acalmar":["portuguese"],"acampar":["portuguese"],"acanhar":["portuguese"],"acaso":["portuguese"],"aceitar":["portuguese"],"acelerar":["portuguese"],"acenar":["portuguese"],"acervo":["portuguese"],"acessar":["portuguese"],"acetona":["portuguese"],"achatar":["portuguese"],"acidez":["portuguese"],"acima":["portuguese"],"acionado":["portuguese"],"acirrar":["portuguese"],"aclamar":["portuguese"],"aclive":["portuguese"],"acolhida":["portuguese"],"acomodar":["portuguese"],"acoplar":["portuguese"],"acordar":["portuguese"],"acumular":["portuguese"],"acusador":["portuguese"],"adaptar":["portuguese"],"adega":["portuguese"],"adentro":["portuguese"],"adepto":["portuguese"],"adequar":["portuguese"],"aderente":["portuguese"],"adesivo":["portuguese"],"adeus":["portuguese"],"adiante":["portuguese"],"aditivo":["portuguese"],"adjetivo":["portuguese"],"adjunto":["portuguese"],"admirar":["portuguese"],"adorar":["portuguese"],"adquirir":["portuguese"],"adubo":["portuguese"],"adverso":["portuguese"],"advogado":["portuguese"],"aeronave":["portuguese"],"afastar":["portuguese"],"aferir":["portuguese"],"afetivo":["portuguese"],"afinador":["portuguese"],"afivelar":["portuguese"],"aflito":["portuguese"],"afluente":["portuguese"],"afrontar":["portuguese"],"agachar":["portuguese"],"agarrar":["portuguese"],"agasalho":["portuguese"],"agenciar":["portuguese"],"agilizar":["portuguese"],"agiota":["portuguese"],"agitado":["portuguese"],"agora":["portuguese"],"agradar":["portuguese"],"agreste":["portuguese"],"agrupar":["portuguese"],"aguardar":["portuguese"],"agulha":["portuguese"],"ajoelhar":["portuguese"],"ajudar":["portuguese"],"ajustar":["portuguese"],"alameda":["portuguese"],"alarme":["portuguese"],"alastrar":["portuguese"],"alavanca":["portuguese"],"albergue":["portuguese"],"albino":["portuguese"],"alcatra":["portuguese"],"aldeia":["portuguese"],"alecrim":["portuguese"],"alegria":["portuguese"],"alertar":["portuguese"],"alface":["portuguese"],"alfinete":["portuguese"],"algum":["portuguese"],"alheio":["portuguese"],"aliar":["portuguese"],"alicate":["portuguese"],"alienar":["portuguese"],"alinhar":["portuguese"],"aliviar":["portuguese"],"almofada":["portuguese"],"alocar":["portuguese"],"alpiste":["portuguese"],"alterar":["portuguese"],"altitude":["portuguese"],"alucinar":["portuguese"],"alugar":["portuguese"],"aluno":["portuguese"],"alusivo":["portuguese"],"alvo":["portuguese"],"amaciar":["portuguese"],"amador":["portuguese"],"amarelo":["portuguese"],"amassar":["portuguese"],"ambas":["portuguese"],"ambiente":["portuguese"],"ameixa":["portuguese"],"amenizar":["portuguese"],"amido":["portuguese"],"amistoso":["portuguese"],"amizade":["portuguese"],"amolador":["portuguese"],"amontoar":["portuguese"],"amoroso":["portuguese"],"amostra":["portuguese"],"amparar":["portuguese"],"ampliar":["portuguese"],"ampola":["portuguese"],"anagrama":["portuguese"],"analisar":["portuguese"],"anarquia":["portuguese"],"anatomia":["portuguese"],"andaime":["portuguese"],"anel":["portuguese"],"anexo":["portuguese"],"angular":["portuguese"],"animar":["portuguese"],"anjo":["portuguese"],"anomalia":["portuguese"],"anotado":["portuguese"],"ansioso":["portuguese"],"anterior":["portuguese"],"anuidade":["portuguese"],"anunciar":["portuguese"],"anzol":["portuguese"],"apagador":["portuguese"],"apalpar":["portuguese"],"apanhado":["portuguese"],"apego":["portuguese"],"apelido":["portuguese"],"apertada":["portuguese"],"apesar":["portuguese"],"apetite":["portuguese"],"apito":["portuguese"],"aplauso":["portuguese"],"aplicada":["portuguese"],"apoio":["portuguese"],"apontar":["portuguese"],"aposta":["portuguese"],"aprendiz":["portuguese"],"aprovar":["portuguese"],"aquecer":["portuguese"],"arame":["portuguese"],"aranha":["portuguese"],"arara":["portuguese"],"arcada":["portuguese"],"ardente":["portuguese"],"areia":["portuguese"],"arejar":["portuguese"],"arenito":["portuguese"],"aresta":["portuguese"],"argiloso":["portuguese"],"argola":["portuguese"],"arma":["portuguese"],"arquivo":["portuguese"],"arraial":["portuguese"],"arrebate":["portuguese"],"arriscar":["portuguese"],"arroba":["portuguese"],"arrumar":["portuguese"],"arsenal":["portuguese"],"arterial":["portuguese"],"artigo":["portuguese"],"arvoredo":["portuguese"],"asfaltar":["portuguese"],"asilado":["portuguese"],"aspirar":["portuguese"],"assador":["portuguese"],"assinar":["portuguese"],"assoalho":["portuguese"],"assunto":["portuguese"],"astral":["portuguese"],"atacado":["portuguese"],"atadura":["portuguese"],"atalho":["portuguese"],"atarefar":["portuguese"],"atear":["portuguese"],"atender":["portuguese"],"aterro":["portuguese"],"ateu":["portuguese"],"atingir":["portuguese"],"atirador":["portuguese"],"ativo":["portuguese"],"atoleiro":["portuguese"],"atracar":["portuguese"],"atrevido":["portuguese"],"atriz":["portuguese"],"atual":["portuguese"],"atum":["portuguese"],"auditor":["portuguese"],"aumentar":["portuguese"],"aura":["portuguese"],"aurora":["portuguese"],"autismo":["portuguese"],"autoria":["portuguese"],"autuar":["portuguese"],"avaliar":["portuguese"],"avante":["portuguese"],"avaria":["portuguese"],"avental":["portuguese"],"avesso":["portuguese"],"aviador":["portuguese"],"avisar":["portuguese"],"avulso":["portuguese"],"axila":["portuguese"],"azarar":["portuguese"],"azedo":["portuguese"],"azeite":["portuguese"],"azulejo":["portuguese"],"babar":["portuguese"],"babosa":["portuguese"],"bacalhau":["portuguese"],"bacharel":["portuguese"],"bacia":["portuguese"],"bagagem":["portuguese"],"baiano":["portuguese"],"bailar":["portuguese"],"baioneta":["portuguese"],"bairro":["portuguese"],"baixista":["portuguese"],"bajular":["portuguese"],"baleia":["portuguese"],"baliza":["portuguese"],"balsa":["portuguese"],"banal":["portuguese"],"bandeira":["portuguese"],"banho":["portuguese"],"banir":["portuguese"],"banquete":["portuguese"],"barato":["portuguese"],"barbado":["portuguese"],"baronesa":["portuguese"],"barraca":["portuguese"],"barulho":["portuguese"],"baseado":["portuguese"],"bastante":["portuguese"],"batata":["portuguese"],"batedor":["portuguese"],"batida":["portuguese"],"batom":["portuguese"],"batucar":["portuguese"],"baunilha":["portuguese"],"beber":["portuguese"],"beijo":["portuguese"],"beirada":["portuguese"],"beisebol":["portuguese"],"beldade":["portuguese"],"beleza":["portuguese"],"belga":["portuguese"],"beliscar":["portuguese"],"bendito":["portuguese"],"bengala":["portuguese"],"benzer":["portuguese","turkish"],"berimbau":["portuguese"],"berlinda":["portuguese"],"berro":["portuguese"],"besouro":["portuguese"],"bexiga":["portuguese"],"bezerro":["portuguese"],"bico":["portuguese"],"bicudo":["portuguese"],"bienal":["portuguese"],"bifocal":["portuguese"],"bifurcar":["portuguese"],"bigorna":["portuguese"],"bilhete":["portuguese"],"bimestre":["portuguese"],"bimotor":["portuguese"],"biologia":["portuguese"],"biombo":["portuguese"],"biosfera":["portuguese"],"bipolar":["portuguese"],"birrento":["portuguese"],"biscoito":["portuguese"],"bisneto":["portuguese"],"bispo":["portuguese"],"bissexto":["portuguese"],"bitola":["portuguese"],"bizarro":["portuguese"],"blindado":["portuguese"],"bloco":["portuguese"],"bloquear":["portuguese"],"boato":["portuguese"],"bobagem":["portuguese"],"bocado":["portuguese"],"bocejo":["portuguese"],"bochecha":["portuguese"],"boicotar":["portuguese"],"bolada":["portuguese"],"boletim":["portuguese"],"bolha":["portuguese"],"bolo":["portuguese"],"bombeiro":["portuguese"],"bonde":["portuguese"],"boneco":["portuguese"],"bonita":["portuguese"],"borbulha":["portuguese"],"borda":["portuguese"],"boreal":["portuguese"],"borracha":["portuguese"],"bovino":["portuguese"],"boxeador":["portuguese"],"branco":["portuguese"],"brasa":["portuguese"],"braveza":["portuguese"],"breu":["portuguese"],"briga":["portuguese"],"brilho":["portuguese"],"brincar":["portuguese"],"broa":["portuguese"],"brochura":["portuguese"],"bronzear":["portuguese"],"broto":["portuguese"],"bruxo":["portuguese"],"bucha":["portuguese"],"budismo":["portuguese"],"bufar":["portuguese"],"bule":["portuguese"],"buraco":["portuguese"],"busca":["portuguese"],"busto":["portuguese"],"buzina":["portuguese"],"cabana":["portuguese"],"cabelo":["portuguese"],"cabide":["portuguese"],"cabo":["portuguese"],"cabrito":["portuguese"],"cacau":["portuguese"],"cacetada":["portuguese"],"cachorro":["portuguese"],"cacique":["portuguese"],"cadastro":["portuguese"],"cadeado":["portuguese"],"cafezal":["portuguese"],"caiaque":["portuguese"],"caipira":["portuguese"],"caixote":["portuguese"],"cajado":["portuguese"],"caju":["portuguese"],"calafrio":["portuguese"],"calcular":["portuguese"],"caldeira":["portuguese"],"calibrar":["portuguese"],"calmante":["portuguese"],"calota":["portuguese"],"camada":["portuguese"],"cambista":["portuguese"],"camisa":["portuguese"],"camomila":["portuguese"],"campanha":["portuguese"],"camuflar":["portuguese"],"canavial":["portuguese"],"cancelar":["portuguese"],"caneta":["portuguese"],"canguru":["portuguese"],"canhoto":["portuguese"],"canivete":["portuguese"],"canoa":["portuguese"],"cansado":["portuguese"],"cantar":["portuguese"],"canudo":["portuguese"],"capacho":["portuguese"],"capela":["portuguese"],"capinar":["portuguese"],"capotar":["portuguese"],"capricho":["portuguese"],"captador":["portuguese"],"capuz":["portuguese"],"caracol":["portuguese"],"carbono":["portuguese"],"cardeal":["portuguese"],"careca":["portuguese"],"carimbar":["portuguese"],"carneiro":["portuguese"],"carpete":["portuguese"],"carreira":["portuguese"],"cartaz":["portuguese"],"carvalho":["portuguese"],"casaco":["portuguese"],"casca":["portuguese"],"casebre":["portuguese"],"castelo":["portuguese"],"casulo":["portuguese"],"catarata":["portuguese"],"cativar":["portuguese"],"caule":["portuguese"],"causador":["portuguese"],"cautelar":["portuguese"],"cavalo":["portuguese"],"caverna":["portuguese"],"cebola":["portuguese"],"cedilha":["portuguese"],"cegonha":["portuguese"],"celebrar":["portuguese"],"celular":["portuguese"],"cenoura":["portuguese"],"censo":["portuguese"],"centeio":["portuguese"],"cercar":["portuguese"],"cerrado":["portuguese"],"certeiro":["portuguese"],"cerveja":["portuguese"],"cetim":["portuguese"],"cevada":["portuguese"],"chacota":["portuguese"],"chaleira":["portuguese"],"chamado":["portuguese"],"chapada":["portuguese"],"charme":["portuguese"],"chatice":["portuguese"],"chave":["portuguese"],"chefe":["portuguese"],"chegada":["portuguese"],"cheiro":["portuguese"],"cheque":["portuguese"],"chicote":["portuguese"],"chifre":["portuguese"],"chinelo":["portuguese"],"chocalho":["portuguese"],"chover":["portuguese"],"chumbo":["portuguese"],"chutar":["portuguese"],"chuva":["portuguese"],"cicatriz":["portuguese"],"ciclone":["portuguese"],"cidade":["portuguese"],"cidreira":["portuguese"],"ciente":["portuguese"],"cigana":["portuguese"],"cimento":["portuguese"],"cinto":["portuguese"],"cinza":["portuguese"],"ciranda":["portuguese"],"circuito":["portuguese"],"cirurgia":["portuguese"],"citar":["portuguese"],"clareza":["portuguese"],"clero":["portuguese"],"clicar":["portuguese"],"clone":["portuguese"],"clube":["portuguese"],"coado":["portuguese"],"coagir":["portuguese"],"cobaia":["portuguese"],"cobertor":["portuguese"],"cobrar":["portuguese"],"cocada":["portuguese"],"coelho":["portuguese"],"coentro":["portuguese"],"coeso":["portuguese"],"cogumelo":["portuguese"],"coibir":["portuguese"],"coifa":["portuguese"],"coiote":["portuguese"],"colar":["portuguese"],"coleira":["portuguese"],"colher":["portuguese"],"colidir":["portuguese"],"colmeia":["portuguese"],"colono":["portuguese"],"coluna":["portuguese"],"comando":["portuguese"],"combinar":["portuguese"],"comentar":["portuguese"],"comitiva":["portuguese"],"comover":["portuguese"],"complexo":["portuguese"],"comum":["portuguese"],"concha":["portuguese"],"condor":["portuguese"],"conectar":["portuguese"],"confuso":["portuguese"],"congelar":["portuguese"],"conhecer":["portuguese"],"conjugar":["portuguese"],"consumir":["portuguese"],"contrato":["portuguese"],"convite":["portuguese"],"cooperar":["portuguese"],"copeiro":["portuguese"],"copiador":["portuguese"],"copo":["portuguese"],"coquetel":["portuguese"],"coragem":["portuguese"],"cordial":["portuguese"],"corneta":["portuguese"],"coronha":["portuguese"],"corporal":["portuguese"],"correio":["portuguese"],"cortejo":["portuguese"],"coruja":["portuguese"],"corvo":["portuguese"],"cosseno":["portuguese"],"costela":["portuguese"],"cotonete":["portuguese"],"couro":["portuguese"],"couve":["portuguese"],"covil":["portuguese"],"cozinha":["portuguese"],"cratera":["portuguese"],"cravo":["portuguese"],"creche":["portuguese"],"credor":["portuguese"],"creme":["portuguese"],"crer":["portuguese"],"crespo":["portuguese"],"criada":["portuguese"],"criminal":["portuguese"],"crioulo":["portuguese"],"crise":["portuguese"],"criticar":["portuguese"],"crosta":["portuguese"],"crua":["portuguese"],"cruzeiro":["portuguese"],"cubano":["portuguese"],"cueca":["portuguese"],"cuidado":["portuguese"],"cujo":["portuguese"],"culatra":["portuguese"],"culminar":["portuguese"],"culpar":["portuguese"],"cultura":["portuguese"],"cumprir":["portuguese"],"cunhado":["portuguese"],"cupido":["portuguese"],"curativo":["portuguese"],"curral":["portuguese"],"cursar":["portuguese"],"curto":["portuguese"],"cuspir":["portuguese"],"custear":["portuguese"],"cutelo":["portuguese"],"damasco":["portuguese"],"datar":["portuguese"],"debater":["portuguese"],"debitar":["portuguese"],"deboche":["portuguese"],"debulhar":["portuguese"],"decalque":["portuguese"],"decimal":["portuguese"],"declive":["portuguese"],"decote":["portuguese"],"decretar":["portuguese"],"dedal":["portuguese"],"dedicado":["portuguese"],"deduzir":["portuguese"],"defesa":["portuguese"],"defumar":["portuguese"],"degelo":["portuguese"],"degrau":["portuguese"],"degustar":["portuguese"],"deitado":["portuguese"],"deixar":["portuguese"],"delator":["portuguese"],"delegado":["portuguese"],"delinear":["portuguese"],"delonga":["portuguese"],"demanda":["portuguese"],"demitir":["portuguese"],"demolido":["portuguese"],"dentista":["portuguese"],"depenado":["portuguese"],"depilar":["portuguese"],"depois":["portuguese"],"depressa":["portuguese"],"depurar":["portuguese"],"deriva":["portuguese"],"derramar":["portuguese"],"desafio":["portuguese"],"desbotar":["portuguese"],"descanso":["portuguese"],"desenho":["portuguese"],"desfiado":["portuguese"],"desgaste":["portuguese"],"desigual":["portuguese"],"deslize":["portuguese"],"desmamar":["portuguese"],"desova":["portuguese"],"despesa":["portuguese"],"destaque":["portuguese"],"desviar":["portuguese"],"detalhar":["portuguese"],"detentor":["portuguese"],"detonar":["portuguese"],"detrito":["portuguese"],"deusa":["portuguese"],"dever":["portuguese"],"devido":["portuguese"],"devotado":["portuguese"],"dezena":["portuguese"],"diagrama":["portuguese"],"dialeto":["portuguese"],"didata":["portuguese"],"difuso":["portuguese"],"digitar":["portuguese"],"dilatado":["portuguese"],"diluente":["portuguese"],"diminuir":["portuguese"],"dinastia":["portuguese"],"dinheiro":["portuguese"],"diocese":["portuguese"],"direto":["portuguese"],"discreta":["portuguese"],"disfarce":["portuguese"],"disparo":["portuguese"],"disquete":["portuguese"],"dissipar":["portuguese"],"distante":["portuguese"],"ditador":["portuguese"],"diurno":["portuguese"],"diverso":["portuguese"],"divisor":["portuguese"],"divulgar":["portuguese"],"dizer":["portuguese"],"dobrador":["portuguese"],"dolorido":["portuguese"],"domador":["portuguese"],"dominado":["portuguese"],"donativo":["portuguese"],"donzela":["portuguese"],"dormente":["portuguese"],"dorsal":["portuguese"],"dosagem":["portuguese"],"dourado":["portuguese"],"doutor":["portuguese"],"drenagem":["portuguese"],"drible":["portuguese"],"drogaria":["portuguese"],"duelar":["portuguese"],"duende":["portuguese"],"dueto":["portuguese"],"duplo":["portuguese"],"duquesa":["portuguese"],"durante":["portuguese"],"duvidoso":["portuguese"],"eclodir":["portuguese"],"ecoar":["portuguese"],"ecologia":["portuguese"],"edificar":["portuguese"],"edital":["portuguese"],"educado":["portuguese"],"efeito":["portuguese"],"efetivar":["portuguese"],"ejetar":["portuguese"],"elaborar":["portuguese"],"eleger":["portuguese"],"eleitor":["portuguese"],"elenco":["portuguese"],"elevador":["portuguese"],"eliminar":["portuguese"],"elogiar":["portuguese"],"embargo":["portuguese"],"embolado":["portuguese"],"embrulho":["portuguese"],"embutido":["portuguese"],"emenda":["portuguese"],"emergir":["portuguese"],"emissor":["portuguese"],"empatia":["portuguese"],"empenho":["portuguese"],"empinado":["portuguese"],"empolgar":["portuguese"],"emprego":["portuguese"],"empurrar":["portuguese"],"emulador":["portuguese"],"encaixe":["portuguese"],"encenado":["portuguese"],"enchente":["portuguese"],"encontro":["portuguese"],"endeusar":["portuguese"],"endossar":["portuguese"],"enfaixar":["portuguese"],"enfeite":["portuguese"],"enfim":["portuguese"],"engajado":["portuguese"],"engenho":["portuguese"],"englobar":["portuguese"],"engomado":["portuguese"],"engraxar":["portuguese"],"enguia":["portuguese"],"enjoar":["portuguese"],"enlatar":["portuguese"],"enquanto":["portuguese"],"enraizar":["portuguese"],"enrolado":["portuguese"],"enrugar":["portuguese"],"ensaio":["portuguese"],"enseada":["portuguese"],"ensino":["portuguese"],"ensopado":["portuguese"],"entanto":["portuguese"],"enteado":["portuguese"],"entidade":["portuguese"],"entortar":["portuguese"],"entrada":["portuguese"],"entulho":["portuguese"],"envergar":["portuguese"],"enviado":["portuguese"],"envolver":["portuguese"],"enxame":["portuguese"],"enxerto":["portuguese"],"enxofre":["portuguese"],"enxuto":["portuguese"],"epiderme":["portuguese"],"equipar":["portuguese"],"ereto":["portuguese"],"erguido":["portuguese"],"errata":["portuguese"],"erva":["portuguese"],"ervilha":["portuguese"],"esbanjar":["portuguese"],"esbelto":["portuguese"],"escama":["portuguese"],"escola":["portuguese"],"escrita":["portuguese"],"escuta":["portuguese"],"esfinge":["portuguese"],"esfolar":["portuguese"],"esfregar":["portuguese"],"esfumado":["portuguese"],"esgrima":["portuguese"],"esmalte":["portuguese"],"espanto":["portuguese"],"espelho":["portuguese"],"espiga":["portuguese"],"esponja":["portuguese"],"espreita":["portuguese"],"espumar":["portuguese"],"esquerda":["portuguese"],"estaca":["portuguese"],"esteira":["portuguese"],"esticar":["portuguese"],"estofado":["portuguese"],"estrela":["portuguese"],"estudo":["portuguese"],"esvaziar":["portuguese"],"etanol":["portuguese"],"etiqueta":["portuguese"],"euforia":["portuguese"],"europeu":["portuguese"],"evacuar":["portuguese"],"evaporar":["portuguese"],"evasivo":["portuguese"],"eventual":["portuguese"],"evidente":["portuguese"],"evoluir":["portuguese"],"exagero":["portuguese"],"exalar":["portuguese"],"examinar":["portuguese"],"exato":["portuguese"],"exausto":["portuguese"],"excesso":["portuguese"],"excitar":["portuguese"],"exclamar":["portuguese"],"executar":["portuguese"],"exemplo":["portuguese"],"exibir":["portuguese"],"exigente":["portuguese"],"exonerar":["portuguese"],"expandir":["portuguese"],"expelir":["portuguese"],"expirar":["portuguese"],"explanar":["portuguese"],"exposto":["portuguese"],"expresso":["portuguese"],"expulsar":["portuguese"],"externo":["portuguese"],"extinto":["portuguese"],"extrato":["portuguese"],"fabricar":["portuguese"],"fabuloso":["portuguese"],"faceta":["portuguese"],"facial":["portuguese"],"fada":["portuguese"],"fadiga":["portuguese"],"faixa":["portuguese"],"falar":["portuguese"],"falta":["portuguese"],"familiar":["portuguese"],"fandango":["portuguese"],"fanfarra":["portuguese"],"fantoche":["portuguese"],"fardado":["portuguese"],"farelo":["portuguese"],"farinha":["portuguese"],"farofa":["portuguese"],"farpa":["portuguese"],"fartura":["portuguese"],"fatia":["portuguese"],"fator":["portuguese"],"favorita":["portuguese"],"faxina":["portuguese"],"fazenda":["portuguese"],"fechado":["portuguese"],"feijoada":["portuguese"],"feirante":["portuguese"],"felino":["portuguese"],"feminino":["portuguese"],"fenda":["portuguese"],"feno":["portuguese"],"fera":["portuguese"],"feriado":["portuguese"],"ferrugem":["portuguese"],"ferver":["portuguese"],"festejar":["portuguese"],"fetal":["portuguese"],"feudal":["portuguese"],"fiapo":["portuguese"],"fibrose":["portuguese"],"ficar":["portuguese"],"ficheiro":["portuguese"],"figurado":["portuguese"],"fileira":["portuguese"],"filho":["portuguese"],"filme":["portuguese"],"filtrar":["portuguese"],"firmeza":["portuguese"],"fisgada":["portuguese"],"fissura":["portuguese"],"fita":["portuguese"],"fivela":["portuguese"],"fixador":["portuguese"],"fixo":["portuguese"],"flacidez":["portuguese"],"flamingo":["portuguese"],"flanela":["portuguese"],"flechada":["portuguese"],"flora":["portuguese"],"flutuar":["portuguese"],"fluxo":["portuguese"],"focal":["portuguese"],"focinho":["portuguese"],"fofocar":["portuguese"],"fogo":["portuguese"],"foguete":["portuguese"],"foice":["portuguese"],"folgado":["portuguese"],"folheto":["portuguese"],"forjar":["portuguese"],"formiga":["portuguese"],"forno":["portuguese"],"forte":["portuguese"],"fosco":["portuguese"],"fossa":["portuguese"],"fragata":["portuguese"],"fralda":["portuguese"],"frango":["portuguese"],"frasco":["portuguese"],"fraterno":["portuguese"],"freira":["portuguese"],"frente":["portuguese"],"fretar":["portuguese"],"frieza":["portuguese"],"friso":["portuguese"],"fritura":["portuguese"],"fronha":["portuguese"],"frustrar":["portuguese"],"fruteira":["portuguese"],"fugir":["portuguese"],"fulano":["portuguese"],"fuligem":["portuguese"],"fundar":["portuguese"],"fungo":["portuguese"],"funil":["portuguese"],"furador":["portuguese"],"furioso":["portuguese"],"futebol":["portuguese"],"gabarito":["portuguese"],"gabinete":["portuguese"],"gado":["portuguese"],"gaiato":["portuguese"],"gaiola":["portuguese"],"gaivota":["portuguese"],"galega":["portuguese"],"galho":["portuguese"],"galinha":["portuguese"],"galocha":["portuguese"],"ganhar":["portuguese"],"garagem":["portuguese"],"garfo":["portuguese"],"gargalo":["portuguese"],"garimpo":["portuguese"],"garoupa":["portuguese"],"garrafa":["portuguese"],"gasoduto":["portuguese"],"gasto":["portuguese"],"gata":["portuguese"],"gatilho":["portuguese"],"gaveta":["portuguese"],"gazela":["portuguese"],"gelado":["portuguese"],"geleia":["portuguese"],"gelo":["portuguese"],"gemada":["portuguese"],"gemer":["portuguese"],"gemido":["portuguese"],"generoso":["portuguese"],"gengiva":["portuguese"],"genial":["portuguese"],"genoma":["portuguese"],"genro":["portuguese"],"geologia":["portuguese"],"gerador":["portuguese"],"germinar":["portuguese"],"gesso":["portuguese"],"gestor":["portuguese"],"ginasta":["portuguese"],"gincana":["portuguese"],"gingado":["portuguese"],"girafa":["portuguese"],"girino":["portuguese"],"glacial":["portuguese"],"glicose":["portuguese"],"global":["portuguese"],"glorioso":["portuguese"],"goela":["portuguese"],"goiaba":["portuguese"],"golfe":["portuguese"],"golpear":["portuguese"],"gordura":["portuguese"],"gorjeta":["portuguese"],"gorro":["portuguese"],"gostoso":["portuguese"],"goteira":["portuguese"],"governar":["portuguese"],"gracejo":["portuguese"],"gradual":["portuguese"],"grafite":["portuguese"],"gralha":["portuguese"],"grampo":["portuguese"],"granada":["portuguese"],"gratuito":["portuguese"],"graveto":["portuguese"],"graxa":["portuguese"],"grego":["portuguese"],"grelhar":["portuguese"],"greve":["portuguese"],"grilo":["portuguese"],"grisalho":["portuguese"],"gritaria":["portuguese"],"grosso":["portuguese"],"grotesco":["portuguese"],"grudado":["portuguese"],"grunhido":["portuguese"],"gruta":["portuguese"],"guache":["portuguese"],"guarani":["portuguese"],"guaxinim":["portuguese"],"guerrear":["portuguese"],"guiar":["portuguese"],"guincho":["portuguese"],"guisado":["portuguese"],"gula":["portuguese"],"guloso":["portuguese"],"guru":["portuguese"],"habitar":["portuguese"],"harmonia":["portuguese"],"haste":["portuguese"],"haver":["portuguese"],"hectare":["portuguese"],"herdar":["portuguese"],"heresia":["portuguese"],"hesitar":["portuguese"],"hiato":["portuguese"],"hibernar":["portuguese"],"hidratar":["portuguese"],"hiena":["portuguese"],"hino":["portuguese"],"hipismo":["portuguese"],"hipnose":["portuguese"],"hipoteca":["portuguese"],"hoje":["portuguese"],"holofote":["portuguese"],"homem":["portuguese"],"honesto":["portuguese"],"honrado":["portuguese"],"hormonal":["portuguese"],"hospedar":["portuguese"],"humorado":["portuguese"],"iate":["portuguese"],"ideia":["portuguese"],"idoso":["portuguese"],"ignorado":["portuguese"],"igreja":["portuguese"],"iguana":["portuguese"],"ileso":["portuguese"],"ilha":["portuguese"],"iludido":["portuguese"],"iluminar":["portuguese"],"ilustrar":["portuguese"],"imagem":["portuguese"],"imediato":["portuguese"],"imenso":["portuguese"],"imersivo":["portuguese"],"iminente":["portuguese"],"imitador":["portuguese"],"imortal":["portuguese"],"impacto":["portuguese"],"impedir":["portuguese"],"implante":["portuguese"],"impor":["portuguese"],"imprensa":["portuguese"],"impune":["portuguese"],"imunizar":["portuguese"],"inalador":["portuguese"],"inapto":["portuguese"],"inativo":["portuguese"],"incenso":["portuguese"],"inchar":["portuguese"],"incidir":["portuguese"],"incluir":["portuguese"],"incolor":["portuguese"],"indeciso":["portuguese"],"indireto":["portuguese"],"indutor":["portuguese"],"ineficaz":["portuguese"],"inerente":["portuguese"],"infantil":["portuguese"],"infestar":["portuguese"],"infinito":["portuguese"],"inflamar":["portuguese"],"informal":["portuguese"],"infrator":["portuguese"],"ingerir":["portuguese"],"inibido":["portuguese"],"inicial":["portuguese"],"inimigo":["portuguese"],"injetar":["portuguese"],"inocente":["portuguese"],"inodoro":["portuguese"],"inovador":["portuguese"],"inox":["portuguese"],"inquieto":["portuguese"],"inscrito":["portuguese"],"inseto":["portuguese"],"insistir":["portuguese"],"inspetor":["portuguese"],"instalar":["portuguese"],"insulto":["portuguese"],"intacto":["portuguese"],"integral":["portuguese"],"intimar":["portuguese"],"intocado":["portuguese"],"intriga":["portuguese"],"invasor":["portuguese"],"inverno":["portuguese"],"invicto":["portuguese"],"invocar":["portuguese"],"iogurte":["portuguese"],"iraniano":["portuguese"],"ironizar":["portuguese"],"irreal":["portuguese"],"irritado":["portuguese"],"isca":["portuguese"],"isento":["portuguese"],"isolado":["portuguese"],"isqueiro":["portuguese"],"italiano":["portuguese"],"janeiro":["portuguese"],"jangada":["portuguese"],"janta":["portuguese"],"jararaca":["portuguese"],"jardim":["portuguese"],"jarro":["portuguese"],"jasmim":["portuguese"],"jato":["portuguese"],"javali":["portuguese"],"jazida":["portuguese"],"jejum":["portuguese"],"joaninha":["portuguese"],"joelhada":["portuguese"],"jogador":["portuguese"],"joia":["portuguese"],"jornal":["portuguese"],"jorrar":["portuguese"],"jovem":["portuguese"],"juba":["portuguese"],"judeu":["portuguese"],"judoca":["portuguese"],"juiz":["portuguese"],"julgador":["portuguese"],"julho":["portuguese"],"jurado":["portuguese"],"jurista":["portuguese"],"juro":["portuguese"],"justa":["portuguese"],"labareda":["portuguese"],"laboral":["portuguese"],"lacre":["portuguese"],"lactante":["portuguese"],"ladrilho":["portuguese"],"lagarta":["portuguese"],"lagoa":["portuguese"],"laje":["portuguese"],"lamber":["portuguese"],"lamentar":["portuguese"],"laminar":["portuguese"],"lampejo":["portuguese"],"lanche":["portuguese"],"lapidar":["portuguese"],"lapso":["portuguese"],"laranja":["portuguese"],"lareira":["portuguese"],"largura":["portuguese"],"lasanha":["portuguese"],"lastro":["portuguese"],"lateral":["portuguese"],"latido":["portuguese"],"lavanda":["portuguese"],"lavoura":["portuguese"],"lavrador":["portuguese"],"laxante":["portuguese"],"lazer":["portuguese"],"lealdade":["portuguese"],"lebre":["portuguese"],"legado":["portuguese"],"legendar":["portuguese"],"legista":["portuguese"],"leigo":["portuguese"],"leiloar":["portuguese"],"leitura":["portuguese"],"lembrete":["portuguese"],"leme":["portuguese"],"lenhador":["portuguese"],"lentilha":["portuguese"],"leoa":["portuguese"],"lesma":["portuguese"],"leste":["portuguese"],"letivo":["portuguese"],"letreiro":["portuguese"],"levar":["portuguese"],"leveza":["portuguese"],"levitar":["portuguese"],"liberal":["portuguese"],"libido":["portuguese"],"liderar":["portuguese"],"ligar":["portuguese"],"ligeiro":["portuguese"],"limitar":["portuguese"],"limoeiro":["portuguese"],"limpador":["portuguese"],"linda":["portuguese"],"linear":["portuguese"],"linhagem":["portuguese"],"liquidez":["portuguese"],"listagem":["portuguese"],"lisura":["portuguese"],"litoral":["portuguese"],"livro":["portuguese"],"lixa":["portuguese"],"lixeira":["portuguese"],"locador":["portuguese"],"locutor":["portuguese"],"lojista":["portuguese"],"lombo":["portuguese"],"lona":["portuguese"],"longe":["portuguese"],"lontra":["portuguese"],"lorde":["portuguese"],"lotado":["portuguese"],"loteria":["portuguese"],"loucura":["portuguese"],"lousa":["portuguese"],"louvar":["portuguese"],"luar":["portuguese"],"lucidez":["portuguese"],"lucro":["portuguese"],"luneta":["portuguese"],"lustre":["portuguese"],"lutador":["portuguese"],"luva":["portuguese"],"macaco":["portuguese"],"macete":["portuguese"],"machado":["portuguese"],"macio":["portuguese"],"madeira":["portuguese"],"madrinha":["portuguese"],"magnata":["portuguese"],"magreza":["portuguese"],"maior":["portuguese"],"mais":["portuguese"],"malandro":["portuguese"],"malha":["portuguese"],"malote":["portuguese"],"maluco":["portuguese"],"mamilo":["portuguese"],"mamoeiro":["portuguese"],"mamute":["portuguese"],"manada":["portuguese"],"mancha":["portuguese"],"mandato":["portuguese"],"manequim":["portuguese"],"manhoso":["portuguese"],"manivela":["portuguese"],"manobrar":["portuguese"],"mansa":["portuguese"],"manter":["portuguese"],"manusear":["portuguese"],"mapeado":["portuguese"],"maquinar":["portuguese"],"marcador":["portuguese"],"maresia":["portuguese"],"marfim":["portuguese"],"margem":["portuguese"],"marinho":["portuguese"],"marmita":["portuguese"],"maroto":["portuguese"],"marquise":["portuguese"],"marreco":["portuguese"],"martelo":["portuguese"],"marujo":["portuguese"],"mascote":["portuguese"],"masmorra":["portuguese"],"massagem":["portuguese"],"mastigar":["portuguese"],"matagal":["portuguese"],"materno":["portuguese"],"matinal":["portuguese"],"matutar":["portuguese"],"maxilar":["portuguese"],"medalha":["portuguese"],"medida":["portuguese"],"medusa":["portuguese"],"megafone":["portuguese"],"meiga":["portuguese"],"melancia":["portuguese"],"melhor":["portuguese"],"membro":["portuguese"],"memorial":["portuguese"],"menino":["portuguese"],"menos":["portuguese"],"mensagem":["portuguese"],"mental":["portuguese"],"merecer":["portuguese"],"mergulho":["portuguese"],"mesada":["portuguese"],"mesclar":["portuguese"],"mesmo":["portuguese"],"mesquita":["portuguese"],"mestre":["portuguese"],"metade":["portuguese"],"meteoro":["portuguese"],"metragem":["portuguese"],"mexer":["portuguese"],"mexicano":["portuguese"],"micro":["portuguese"],"migalha":["portuguese"],"migrar":["portuguese"],"milagre":["portuguese"],"milenar":["portuguese"],"milhar":["portuguese"],"mimado":["portuguese"],"minerar":["portuguese"],"minhoca":["portuguese"],"ministro":["portuguese"],"minoria":["portuguese"],"miolo":["portuguese"],"mirante":["portuguese"],"mirtilo":["portuguese"],"misturar":["portuguese"],"mocidade":["portuguese"],"moderno":["portuguese"],"modular":["portuguese"],"moeda":["portuguese"],"moer":["portuguese"],"moinho":["portuguese"],"moita":["portuguese"],"moldura":["portuguese"],"moleza":["portuguese"],"molho":["portuguese"],"molinete":["portuguese"],"molusco":["portuguese"],"montanha":["portuguese"],"moqueca":["portuguese"],"morango":["portuguese"],"morcego":["portuguese"],"mordomo":["portuguese"],"morena":["portuguese"],"mosaico":["portuguese"],"mosquete":["portuguese"],"mostarda":["portuguese"],"motel":["portuguese"],"motim":["portuguese"],"moto":["portuguese"],"motriz":["portuguese"],"muda":["portuguese"],"muito":["portuguese"],"mulata":["portuguese"],"mulher":["portuguese"],"multar":["portuguese"],"mundial":["portuguese"],"munido":["portuguese"],"muralha":["portuguese"],"murcho":["portuguese"],"muscular":["portuguese"],"museu":["portuguese"],"musical":["portuguese"],"nacional":["portuguese"],"nadador":["portuguese"],"naja":["portuguese"],"namoro":["portuguese"],"narina":["portuguese"],"narrado":["portuguese"],"nascer":["portuguese"],"nativa":["portuguese"],"natureza":["portuguese"],"navalha":["portuguese"],"navegar":["portuguese"],"navio":["portuguese"],"neblina":["portuguese"],"nebuloso":["portuguese"],"negativa":["portuguese"],"negociar":["portuguese"],"negrito":["portuguese"],"nervoso":["portuguese"],"neta":["portuguese"],"neural":["portuguese"],"nevasca":["portuguese"],"nevoeiro":["portuguese"],"ninar":["portuguese"],"ninho":["portuguese"],"nitidez":["portuguese"],"nivelar":["portuguese"],"nobreza":["portuguese"],"noite":["portuguese"],"noiva":["portuguese"],"nomear":["portuguese"],"nominal":["portuguese"],"nordeste":["portuguese"],"nortear":["portuguese"],"notar":["portuguese"],"noticiar":["portuguese"],"noturno":["portuguese"],"novelo":["portuguese"],"novilho":["portuguese"],"novo":["portuguese"],"nublado":["portuguese"],"nudez":["portuguese"],"numeral":["portuguese"],"nupcial":["portuguese"],"nutrir":["portuguese"],"nuvem":["portuguese"],"obcecado":["portuguese"],"obedecer":["portuguese"],"objetivo":["portuguese"],"obrigado":["portuguese"],"obscuro":["portuguese"],"obstetra":["portuguese"],"obter":["portuguese"],"obturar":["portuguese"],"ocidente":["portuguese"],"ocioso":["portuguese"],"ocorrer":["portuguese"],"oculista":["portuguese"],"ocupado":["portuguese"],"ofegante":["portuguese"],"ofensiva":["portuguese"],"oferenda":["portuguese"],"oficina":["portuguese"],"ofuscado":["portuguese"],"ogiva":["portuguese"],"olaria":["portuguese"],"oleoso":["portuguese"],"olhar":["portuguese"],"oliveira":["portuguese"],"ombro":["portuguese"],"omelete":["portuguese"],"omisso":["portuguese"],"omitir":["portuguese"],"ondulado":["portuguese"],"oneroso":["portuguese"],"ontem":["portuguese"],"opcional":["portuguese"],"operador":["portuguese"],"oponente":["portuguese"],"oportuno":["portuguese"],"oposto":["portuguese"],"orar":["portuguese"],"orbitar":["portuguese"],"ordem":["portuguese"],"ordinal":["portuguese"],"orfanato":["portuguese"],"orgasmo":["portuguese"],"orgulho":["portuguese"],"oriental":["portuguese"],"origem":["portuguese"],"oriundo":["portuguese"],"orla":["portuguese"],"ortodoxo":["portuguese"],"orvalho":["portuguese"],"oscilar":["portuguese"],"ossada":["portuguese"],"osso":["portuguese"],"ostentar":["portuguese"],"otimismo":["portuguese"],"ousadia":["portuguese"],"outono":["portuguese"],"outubro":["portuguese"],"ouvido":["portuguese"],"ovelha":["portuguese"],"ovular":["portuguese"],"oxidar":["portuguese"],"oxigenar":["portuguese"],"pacato":["portuguese"],"paciente":["portuguese"],"pacote":["portuguese"],"pactuar":["portuguese"],"padaria":["portuguese"],"padrinho":["portuguese"],"pagar":["portuguese"],"pagode":["portuguese"],"painel":["portuguese"],"pairar":["portuguese"],"paisagem":["portuguese"],"palavra":["portuguese"],"palestra":["portuguese"],"palheta":["portuguese"],"palito":["portuguese"],"palmada":["portuguese"],"palpitar":["portuguese"],"pancada":["portuguese"],"panela":["portuguese"],"panfleto":["portuguese"],"panqueca":["portuguese"],"pantanal":["portuguese"],"papagaio":["portuguese"],"papelada":["portuguese"],"papiro":["portuguese"],"parafina":["portuguese"],"parcial":["portuguese"],"pardal":["portuguese"],"parede":["portuguese"],"partida":["portuguese"],"pasmo":["portuguese"],"passado":["portuguese"],"pastel":["portuguese"],"patamar":["portuguese"],"patente":["portuguese"],"patinar":["portuguese"],"patrono":["portuguese"],"paulada":["portuguese"],"pausar":["portuguese"],"peculiar":["portuguese"],"pedalar":["portuguese"],"pedestre":["portuguese"],"pediatra":["portuguese"],"pedra":["portuguese"],"pegada":["portuguese"],"peitoral":["portuguese"],"peixe":["portuguese"],"pele":["portuguese"],"pelicano":["portuguese"],"penca":["portuguese"],"pendurar":["portuguese"],"peneira":["portuguese"],"penhasco":["portuguese"],"pensador":["portuguese"],"pente":["portuguese"],"perceber":["portuguese"],"perfeito":["portuguese"],"pergunta":["portuguese"],"perito":["portuguese"],"permitir":["portuguese"],"perna":["portuguese"],"perplexo":["portuguese"],"persiana":["portuguese"],"pertence":["portuguese"],"peruca":["portuguese"],"pescado":["portuguese"],"pesquisa":["portuguese"],"pessoa":["portuguese"],"petiscar":["portuguese"],"piada":["portuguese"],"picado":["portuguese"],"piedade":["portuguese"],"pigmento":["portuguese"],"pilastra":["portuguese"],"pilhado":["portuguese"],"pilotar":["portuguese"],"pimenta":["portuguese"],"pincel":["portuguese"],"pinguim":["portuguese"],"pinha":["portuguese"],"pinote":["portuguese"],"pintar":["portuguese"],"pioneiro":["portuguese"],"pipoca":["portuguese"],"piquete":["portuguese"],"piranha":["portuguese"],"pires":["portuguese"],"pirueta":["portuguese"],"piscar":["portuguese"],"pistola":["portuguese"],"pitanga":["portuguese"],"pivete":["portuguese"],"planta":["portuguese"],"plaqueta":["portuguese"],"platina":["portuguese"],"plebeu":["portuguese"],"plumagem":["portuguese"],"pluvial":["portuguese"],"pneu":["portuguese"],"poda":["portuguese"],"poeira":["portuguese"],"poetisa":["portuguese"],"polegada":["portuguese"],"policiar":["portuguese"],"poluente":["portuguese"],"polvilho":["portuguese"],"pomar":["portuguese"],"pomba":["portuguese"],"ponderar":["portuguese"],"pontaria":["portuguese"],"populoso":["portuguese"],"porta":["portuguese"],"possuir":["portuguese"],"postal":["portuguese"],"pote":["portuguese"],"poupar":["portuguese"],"pouso":["portuguese"],"povoar":["portuguese"],"praia":["portuguese"],"prancha":["portuguese"],"prato":["portuguese"],"praxe":["portuguese"],"prece":["portuguese"],"predador":["portuguese"],"prefeito":["portuguese"],"premiar":["portuguese"],"prensar":["portuguese"],"preparar":["portuguese"],"presilha":["portuguese"],"pretexto":["portuguese"],"prevenir":["portuguese"],"prezar":["portuguese"],"primata":["portuguese"],"princesa":["portuguese"],"prisma":["portuguese"],"privado":["portuguese"],"processo":["portuguese"],"produto":["portuguese"],"profeta":["portuguese"],"proibido":["portuguese"],"projeto":["portuguese"],"prometer":["portuguese"],"propagar":["portuguese"],"prosa":["portuguese"],"protetor":["portuguese"],"provador":["portuguese"],"publicar":["portuguese"],"pudim":["portuguese"],"pular":["portuguese"],"pulmonar":["portuguese"],"pulseira":["portuguese"],"punhal":["portuguese"],"punir":["portuguese"],"pupilo":["portuguese"],"pureza":["portuguese"],"puxador":["portuguese"],"quadra":["portuguese"],"quantia":["portuguese"],"quarto":["portuguese"],"quase":["portuguese"],"quebrar":["portuguese"],"queda":["portuguese"],"queijo":["portuguese"],"quente":["portuguese"],"querido":["portuguese"],"quimono":["portuguese"],"quina":["portuguese"],"quiosque":["portuguese"],"rabanada":["portuguese"],"rabisco":["portuguese"],"rachar":["portuguese"],"racionar":["portuguese"],"radial":["portuguese"],"raiar":["portuguese"],"rainha":["portuguese"],"raio":["portuguese"],"raiva":["portuguese"],"rajada":["portuguese"],"ralado":["portuguese"],"ramal":["portuguese"],"ranger":["portuguese"],"ranhura":["portuguese"],"rapadura":["portuguese"],"rapel":["portuguese"],"rapidez":["portuguese"],"raposa":["portuguese"],"raquete":["portuguese"],"raridade":["portuguese"],"rasante":["portuguese"],"rascunho":["portuguese"],"rasgar":["portuguese"],"raspador":["portuguese"],"rasteira":["portuguese"],"rasurar":["portuguese"],"ratazana":["portuguese"],"ratoeira":["portuguese"],"realeza":["portuguese"],"reanimar":["portuguese"],"reaver":["portuguese"],"rebaixar":["portuguese"],"rebelde":["portuguese"],"rebolar":["portuguese"],"recado":["portuguese"],"recente":["portuguese"],"recheio":["portuguese"],"recibo":["portuguese"],"recordar":["portuguese"],"recrutar":["portuguese"],"recuar":["portuguese"],"rede":["portuguese"],"redimir":["portuguese"],"redonda":["portuguese"],"reduzida":["portuguese"],"reenvio":["portuguese"],"refinar":["portuguese"],"refletir":["portuguese"],"refogar":["portuguese"],"refresco":["portuguese"],"refugiar":["portuguese"],"regalia":["portuguese"],"regime":["portuguese"],"regra":["portuguese"],"reinado":["portuguese"],"reitor":["portuguese"],"rejeitar":["portuguese"],"relativo":["portuguese"],"remador":["portuguese"],"remendo":["portuguese"],"remorso":["portuguese"],"renovado":["portuguese"],"reparo":["portuguese"],"repelir":["portuguese"],"repleto":["portuguese"],"repolho":["portuguese"],"represa":["portuguese"],"repudiar":["portuguese"],"requerer":["portuguese"],"resenha":["portuguese"],"resfriar":["portuguese"],"resgatar":["portuguese"],"residir":["portuguese"],"resolver":["portuguese"],"respeito":["portuguese"],"ressaca":["portuguese"],"restante":["portuguese"],"resumir":["portuguese"],"retalho":["portuguese"],"reter":["portuguese"],"retirar":["portuguese"],"retomada":["portuguese"],"retratar":["portuguese"],"revelar":["portuguese"],"revisor":["portuguese"],"revolta":["portuguese"],"riacho":["portuguese"],"rica":["portuguese"],"rigidez":["portuguese"],"rigoroso":["portuguese"],"rimar":["portuguese"],"ringue":["portuguese"],"risada":["portuguese"],"risco":["portuguese"],"risonho":["portuguese"],"robalo":["portuguese"],"rochedo":["portuguese"],"rodada":["portuguese"],"rodeio":["portuguese"],"rodovia":["portuguese"],"roedor":["portuguese"],"roleta":["portuguese"],"romano":["portuguese"],"roncar":["portuguese"],"rosado":["portuguese"],"roseira":["portuguese"],"rosto":["portuguese"],"rota":["portuguese","turkish"],"roteiro":["portuguese"],"rotina":["portuguese"],"rotular":["portuguese"],"rouco":["portuguese"],"roupa":["portuguese"],"roxo":["portuguese"],"rubro":["portuguese"],"rugido":["portuguese"],"rugoso":["portuguese"],"ruivo":["portuguese"],"rumo":["portuguese"],"rupestre":["portuguese"],"russo":["portuguese"],"sabor":["portuguese"],"saciar":["portuguese"],"sacola":["portuguese"],"sacudir":["portuguese"],"sadio":["portuguese"],"safira":["portuguese"],"saga":["portuguese"],"sagrada":["portuguese"],"saibro":["portuguese"],"salada":["portuguese"],"saleiro":["portuguese"],"salgado":["portuguese"],"saliva":["portuguese"],"salpicar":["portuguese"],"salsicha":["portuguese"],"saltar":["portuguese"],"salvador":["portuguese"],"sambar":["portuguese"],"samurai":["portuguese"],"sanar":["portuguese"],"sanfona":["portuguese"],"sangue":["portuguese"],"sanidade":["portuguese"],"sapato":["portuguese"],"sarda":["portuguese"],"sargento":["portuguese"],"sarjeta":["portuguese"],"saturar":["portuguese"],"saudade":["portuguese"],"saxofone":["portuguese"],"sazonal":["portuguese"],"secar":["portuguese"],"secular":["portuguese"],"seda":["portuguese","turkish"],"sedento":["portuguese"],"sediado":["portuguese"],"sedoso":["portuguese"],"sedutor":["portuguese"],"segmento":["portuguese"],"segredo":["portuguese"],"segundo":["portuguese"],"seiva":["portuguese"],"seleto":["portuguese"],"selvagem":["portuguese"],"semanal":["portuguese"],"semente":["portuguese"],"senador":["portuguese"],"senhor":["portuguese"],"sensual":["portuguese"],"sentado":["portuguese"],"separado":["portuguese"],"sereia":["portuguese"],"seringa":["portuguese"],"serra":["portuguese"],"servo":["portuguese"],"setembro":["portuguese"],"setor":["portuguese"],"sigilo":["portuguese"],"silhueta":["portuguese"],"silicone":["portuguese"],"simetria":["portuguese"],"simpatia":["portuguese"],"simular":["portuguese"],"sinal":["portuguese"],"sincero":["portuguese"],"singular":["portuguese"],"sinopse":["portuguese"],"sintonia":["portuguese"],"sirene":["portuguese"],"siri":["portuguese"],"situado":["portuguese"],"soberano":["portuguese"],"sobra":["portuguese"],"socorro":["portuguese"],"sogro":["portuguese"],"soja":["portuguese"],"solda":["portuguese"],"soletrar":["portuguese"],"solteiro":["portuguese"],"sombrio":["portuguese"],"sonata":["portuguese"],"sondar":["portuguese"],"sonegar":["portuguese"],"sonhador":["portuguese"],"sono":["portuguese"],"soprano":["portuguese"],"soquete":["portuguese"],"sorrir":["portuguese"],"sorteio":["portuguese"],"sossego":["portuguese"],"sotaque":["portuguese"],"soterrar":["portuguese"],"sovado":["portuguese"],"sozinho":["portuguese"],"suavizar":["portuguese"],"subida":["portuguese"],"submerso":["portuguese"],"subsolo":["portuguese"],"subtrair":["portuguese"],"sucata":["portuguese"],"sucesso":["portuguese"],"suco":["portuguese"],"sudeste":["portuguese"],"sufixo":["portuguese"],"sugador":["portuguese"],"sugerir":["portuguese"],"sujeito":["portuguese"],"sulfato":["portuguese"],"sumir":["portuguese"],"suor":["portuguese"],"superior":["portuguese"],"suplicar":["portuguese"],"suposto":["portuguese"],"suprimir":["portuguese"],"surdina":["portuguese"],"surfista":["portuguese"],"surpresa":["portuguese"],"surreal":["portuguese"],"surtir":["portuguese"],"suspiro":["portuguese"],"sustento":["portuguese"],"tabela":["portuguese","turkish"],"tablete":["portuguese"],"tabuada":["portuguese"],"tacho":["portuguese"],"tagarela":["portuguese"],"talher":["portuguese"],"talo":["portuguese"],"talvez":["portuguese"],"tamanho":["portuguese"],"tamborim":["portuguese"],"tampa":["portuguese"],"tangente":["portuguese"],"tanto":["portuguese"],"tapar":["portuguese"],"tapioca":["portuguese"],"tardio":["portuguese"],"tarefa":["portuguese"],"tarja":["portuguese"],"tarraxa":["portuguese"],"tatuagem":["portuguese"],"taurino":["portuguese"],"taxativo":["portuguese"],"taxista":["portuguese"],"teatral":["portuguese"],"tecer":["portuguese"],"tecido":["portuguese"],"teclado":["portuguese"],"tedioso":["portuguese"],"teia":["portuguese"],"teimar":["portuguese"],"telefone":["portuguese"],"telhado":["portuguese"],"tempero":["portuguese"],"tenente":["portuguese"],"tensor":["portuguese"],"tentar":["portuguese"],"termal":["portuguese"],"terno":["portuguese"],"terreno":["portuguese"],"tese":["portuguese"],"tesoura":["portuguese"],"testado":["portuguese"],"teto":["portuguese"],"textura":["portuguese"],"texugo":["portuguese"],"tiara":["portuguese"],"tigela":["portuguese"],"tijolo":["portuguese"],"timbrar":["portuguese"],"timidez":["portuguese"],"tingido":["portuguese"],"tinteiro":["portuguese"],"tiragem":["portuguese"],"titular":["portuguese"],"toalha":["portuguese"],"tocha":["portuguese"],"tolerar":["portuguese"],"tolice":["portuguese"],"tomada":["portuguese"],"tomilho":["portuguese"],"tonel":["portuguese"],"tontura":["portuguese"],"topete":["portuguese"],"tora":["portuguese"],"torcido":["portuguese"],"torneio":["portuguese"],"torque":["portuguese"],"torrada":["portuguese"],"torto":["portuguese"],"tostar":["portuguese"],"touca":["portuguese"],"toupeira":["portuguese"],"toxina":["portuguese"],"trabalho":["portuguese"],"tracejar":["portuguese"],"tradutor":["portuguese"],"trafegar":["portuguese"],"trajeto":["portuguese"],"trama":["portuguese"],"trancar":["portuguese"],"trapo":["portuguese"],"traseiro":["portuguese"],"tratador":["portuguese"],"travar":["portuguese"],"treino":["portuguese"],"tremer":["portuguese"],"trepidar":["portuguese"],"trevo":["portuguese"],"triagem":["portuguese"],"tribo":["portuguese"],"triciclo":["portuguese"],"tridente":["portuguese"],"trilogia":["portuguese"],"trindade":["portuguese"],"triplo":["portuguese"],"triturar":["portuguese"],"triunfal":["portuguese"],"trocar":["portuguese"],"trombeta":["portuguese"],"trova":["portuguese"],"trunfo":["portuguese"],"truque":["portuguese"],"tubular":["portuguese"],"tucano":["portuguese"],"tudo":["portuguese"],"tulipa":["portuguese"],"tupi":["portuguese"],"turbo":["portuguese"],"turma":["portuguese"],"turquesa":["portuguese"],"tutelar":["portuguese"],"tutorial":["portuguese"],"uivar":["portuguese"],"umbigo":["portuguese"],"unha":["portuguese"],"unidade":["portuguese"],"uniforme":["portuguese"],"urologia":["portuguese"],"urso":["portuguese"],"urtiga":["portuguese"],"urubu":["portuguese"],"usado":["portuguese"],"usina":["portuguese"],"usufruir":["portuguese"],"vacina":["portuguese"],"vadiar":["portuguese"],"vagaroso":["portuguese"],"vaidoso":["portuguese"],"vala":["portuguese"],"valente":["portuguese"],"validade":["portuguese"],"valores":["portuguese"],"vantagem":["portuguese"],"vaqueiro":["portuguese"],"varanda":["portuguese"],"vareta":["portuguese"],"varrer":["portuguese"],"vascular":["portuguese"],"vasilha":["portuguese"],"vassoura":["portuguese"],"vazar":["portuguese"],"vazio":["portuguese"],"veado":["portuguese"],"vedar":["portuguese"],"vegetar":["portuguese"],"veicular":["portuguese"],"veleiro":["portuguese"],"velhice":["portuguese"],"veludo":["portuguese"],"vencedor":["portuguese"],"vendaval":["portuguese"],"venerar":["portuguese"],"ventre":["portuguese"],"verbal":["portuguese"],"verdade":["portuguese"],"vereador":["portuguese"],"vergonha":["portuguese"],"vermelho":["portuguese"],"verniz":["portuguese"],"versar":["portuguese"],"vertente":["portuguese"],"vespa":["portuguese"],"vestido":["portuguese"],"vetorial":["portuguese"],"viaduto":["portuguese"],"viagem":["portuguese"],"viajar":["portuguese"],"viatura":["portuguese"],"vibrador":["portuguese"],"videira":["portuguese"],"vidraria":["portuguese"],"viela":["portuguese"],"viga":["portuguese"],"vigente":["portuguese"],"vigiar":["portuguese"],"vigorar":["portuguese"],"vilarejo":["portuguese"],"vinco":["portuguese"],"vinheta":["portuguese"],"vinil":["portuguese"],"violeta":["portuguese"],"virada":["portuguese"],"virtude":["portuguese"],"visitar":["portuguese"],"visto":["portuguese"],"vitral":["portuguese"],"viveiro":["portuguese"],"vizinho":["portuguese"],"voador":["portuguese"],"voar":["portuguese"],"vogal":["portuguese"],"volante":["portuguese"],"voleibol":["portuguese"],"voltagem":["portuguese"],"volumoso":["portuguese"],"vontade":["portuguese"],"vulto":["portuguese"],"vuvuzela":["portuguese"],"xadrez":["portuguese"],"xarope":["portuguese"],"xeque":["portuguese"],"xeretar":["portuguese"],"xerife":["portuguese"],"xingar":["portuguese"],"zangado":["portuguese"],"zarpar":["portuguese"],"zebu":["portuguese"],"zelador":["portuguese"],"zombar":["portuguese"],"zoologia":["portuguese"],"zumbido":["portuguese"],"абзац":["russian"],"абонент":["russian"],"абсурд":["russian"],"авангард":["russian"],"авария":["russian"],"август":["russian"],"авиация":["russian"],"автор":["russian"],"агент":["russian"],"агитация":["russian"],"агрегат":["russian"],"адвокат":["russian"],"адмирал":["russian"],"адрес":["russian"],"азарт":["russian"],"азот":["russian"],"академия":["russian"],"аквариум":["russian"],"аксиома":["russian"],"акула":["russian"],"акцент":["russian"],"акция":["russian"],"аллея":["russian"],"алмаз":["russian"],"алтарь":["russian"],"альбом":["russian"],"альянс":["russian"],"амбиция":["russian"],"анализ":["russian"],"анекдот":["russian"],"анкета":["russian"],"ансамбль":["russian"],"антенна":["russian"],"апельсин":["russian"],"аппарат":["russian"],"аппетит":["russian"],"апрель":["russian"],"аптека":["russian"],"арбуз":["russian"],"аргумент":["russian"],"аренда":["russian"],"арест":["russian"],"армия":["russian"],"аромат":["russian"],"арсенал":["russian"],"артерия":["russian"],"артист":["russian"],"архив":["russian"],"аспирант":["russian"],"асфальт":["russian"],"атака":["russian"],"атомный":["russian"],"атрибут":["russian"],"аукцион":["russian"],"афиша":["russian"],"аэропорт":["russian"],"бабочка":["russian"],"бабушка":["russian"],"багаж":["russian"],"база":["russian"],"бактерия":["russian"],"баланс":["russian"],"балерина":["russian"],"балкон":["russian"],"бандит":["russian"],"банк":["russian"],"барабан":["russian"],"барон":["russian"],"барышня":["russian"],"барьер":["russian"],"бассейн":["russian"],"батарея":["russian"],"башмак":["russian"],"башня":["russian"],"бедный":["russian"],"беженец":["russian"],"бездна":["russian"],"белка":["russian"],"белый":["russian"],"бензин":["russian"],"берег":["russian"],"беседа":["russian"],"бешеный":["russian"],"билет":["russian"],"бинокль":["russian"],"биржа":["russian"],"битва":["russian"],"благо":["russian"],"блеск":["russian"],"близкий":["russian"],"блин":["russian"],"блок":["russian"],"блюдо":["russian"],"богатый":["russian"],"бодрый":["russian"],"боец":["russian"],"бокал":["russian"],"боковой":["russian"],"бокс":["russian"],"более":["russian"],"болото":["russian"],"болтать":["russian"],"большой":["russian"],"бомба":["russian"],"борт":["russian"],"борьба":["russian"],"босой":["russian"],"ботинок":["russian"],"бояться":["russian"],"брак":["russian"],"брать":["russian"],"бревно":["russian"],"бред":["russian"],"бригада":["russian"],"бродяга":["russian"],"броня":["russian"],"бросить":["russian"],"брызги":["russian"],"брюки":["russian"],"брюхо":["russian"],"бугор":["russian"],"будка":["russian"],"будни":["russian"],"будущее":["russian"],"буква":["russian"],"букет":["russian"],"бульвар":["russian"],"бумага":["russian"],"бунт":["russian"],"бурный":["russian"],"буря":["russian"],"бутылка":["russian"],"бухта":["russian"],"бывший":["russian"],"быстро":["russian"],"бытовой":["russian"],"быть":["russian"],"бюджет":["russian"],"бюро":["russian"],"бюст":["russian"],"вагон":["russian"],"важный":["russian"],"вакцина":["russian"],"валенок":["russian"],"вальс":["russian"],"валюта":["russian"],"ванная":["russian"],"варенье":["russian"],"вариант":["russian"],"вблизи":["russian"],"вверх":["russian"],"вводить":["russian"],"вдали":["russian"],"вдвое":["russian"],"вдова":["russian"],"вдоль":["russian"],"вдруг":["russian"],"ведро":["russian"],"ведущий":["russian"],"ведьма":["russian"],"вежливо":["russian"],"везде":["russian"],"веко":["russian"],"вексель":["russian"],"велеть":["russian"],"великий":["russian"],"венец":["russian"],"веник":["russian"],"веранда":["russian"],"верблюд":["russian"],"верить":["russian"],"верный":["russian"],"версия":["russian"],"вертеть":["russian"],"верхний":["russian"],"вершина":["russian"],"весело":["russian"],"весна":["russian"],"весомый":["russian"],"вести":["russian"],"весь":["russian"],"ветеран":["russian"],"ветхий":["russian"],"вечер":["russian"],"вечно":["russian"],"вешалка":["russian"],"вещество":["russian"],"взамен":["russian"],"взгляд":["russian"],"вздох":["russian"],"взнос":["russian"],"взойти":["russian"],"взор":["russian"],"взрыв":["russian"],"взять":["russian"],"видеть":["russian"],"видимо":["russian"],"визг":["russian"],"визит":["russian"],"вилка":["russian"],"вина":["russian"],"вирус":["russian"],"висок":["russian"],"витамин":["russian"],"витрина":["russian"],"вихрь":["russian"],"вишня":["russian"],"вкус":["russian"],"влага":["russian"],"владелец":["russian"],"власть":["russian"],"влево":["russian"],"влияние":["russian"],"вложить":["russian"],"вместе":["russian"],"внешний":["russian"],"вникать":["russian"],"внимание":["russian"],"вновь":["russian"],"внук":["russian"],"внутри":["russian"],"внучка":["russian"],"внушать":["russian"],"вовлечь":["russian"],"вовремя":["russian"],"вовсю":["russian"],"вода":["russian"],"водород":["russian"],"водяной":["russian"],"воевать":["russian"],"возврат":["russian"],"возглас":["russian"],"воздух":["russian"],"возить":["russian"],"возле":["russian"],"возня":["russian"],"возраст":["russian"],"война":["russian"],"войско":["russian"],"вокзал":["russian"],"волос":["russian"],"волчий":["russian"],"вольный":["russian"],"воля":["russian"],"вообще":["russian"],"вопль":["russian"],"вопрос":["russian"],"ворота":["russian"],"восемь":["russian"],"восток":["russian"],"вплоть":["russian"],"вполне":["russian"],"вправе":["russian"],"впредь":["russian"],"впрочем":["russian"],"врач":["russian"],"вредный":["russian"],"время":["russian"],"вручить":["russian"],"всадник":["russian"],"всегда":["russian"],"вскоре":["russian"],"вскрыть":["russian"],"всплеск":["russian"],"вспышка":["russian"],"встреча":["russian"],"всюду":["russian"],"всякий":["russian"],"второй":["russian"],"вход":["russian"],"вчера":["russian"],"выбор":["russian"],"вывод":["russian"],"выгнать":["russian"],"выдать":["russian"],"выехать":["russian"],"вызов":["russian"],"выйти":["russian"],"выкуп":["russian"],"вылезти":["russian"],"вымыть":["russian"],"выпасть":["russian"],"выпить":["russian"],"выплата":["russian"],"выпуск":["russian"],"вырасти":["russian"],"выручка":["russian"],"выслать":["russian"],"высокий":["russian"],"выставка":["russian"],"вышка":["russian"],"вязать":["russian"],"вялый":["russian"],"газета":["russian"],"газовый":["russian"],"галерея":["russian"],"галстук":["russian"],"гамма":["russian"],"гарантия":["russian"],"гармония":["russian"],"гарнизон":["russian"],"гастроли":["russian"],"гвардия":["russian"],"гвоздь":["russian"],"гектар":["russian"],"генерал":["russian"],"гений":["russian"],"геном":["russian"],"геолог":["russian"],"герб":["russian"],"герой":["russian"],"гибкий":["russian"],"гигант":["russian"],"гимн":["russian"],"гипотеза":["russian"],"гитара":["russian"],"главный":["russian"],"глагол":["russian"],"гладить":["russian"],"глаз":["russian"],"глина":["russian"],"глоток":["russian"],"глубокий":["russian"],"глупый":["russian"],"глухой":["russian"],"глыба":["russian"],"глядеть":["russian"],"гнев":["russian"],"гнездо":["russian"],"гнилой":["russian"],"годовой":["russian"],"голова":["russian"],"голубой":["russian"],"голый":["russian"],"гонорар":["russian"],"гордость":["russian"],"горизонт":["russian"],"горло":["russian"],"горный":["russian"],"город":["russian"],"горшок":["russian"],"горький":["russian"],"горючее":["russian"],"горячий":["russian"],"готовый":["russian"],"градус":["russian"],"грамм":["russian"],"граница":["russian"],"граф":["russian"],"гребень":["russian"],"гриб":["russian"],"гримаса":["russian"],"грозить":["russian"],"грохот":["russian"],"грош":["russian"],"грубый":["russian"],"грудь":["russian"],"груз":["russian"],"грунт":["russian"],"группа":["russian"],"груша":["russian"],"грязный":["russian"],"губа":["russian"],"гудок":["russian"],"гулкий":["russian"],"гулять":["russian"],"гусеница":["russian"],"густо":["russian"],"гусь":["russian"],"давление":["russian"],"давно":["russian"],"даже":["russian"],"дальний":["russian"],"данный":["russian"],"дарить":["russian"],"датчик":["russian"],"дать":["russian"],"дача":["russian"],"двадцать":["russian"],"дважды":["russian"],"дверь":["russian"],"двигать":["russian"],"движение":["russian"],"двойной":["russian"],"двор":["russian"],"дебют":["russian"],"девятый":["russian"],"дежурный":["russian"],"действие":["russian"],"декабрь":["russian"],"деление":["russian"],"дело":["russian"],"дельфин":["russian"],"день":["russian"],"дерево":["russian"],"держать":["russian"],"дерзкий":["russian"],"десять":["russian"],"деталь":["russian"],"детский":["russian"],"дефект":["russian"],"дефицит":["russian"],"деятель":["russian"],"джаз":["russian"],"джинсы":["russian"],"джунгли":["russian"],"диагноз":["russian"],"диалог":["russian"],"диапазон":["russian"],"диван":["russian"],"дивизия":["russian"],"дивный":["russian"],"диета":["russian"],"дизайн":["russian"],"дикарь":["russian"],"дилер":["russian"],"динамика":["russian"],"диплом":["russian"],"директор":["russian"],"дитя":["russian"],"длинный":["russian"],"дневник":["russian"],"добрый":["russian"],"добыча":["russian"],"доверие":["russian"],"догадка":["russian"],"догнать":["russian"],"дождь":["russian"],"доклад":["russian"],"доктор":["russian"],"документ":["russian"],"долго":["russian"],"должен":["russian"],"долина":["russian"],"донос":["russian"],"дорога":["russian"],"досада":["russian"],"доска":["russian"],"достать":["russian"],"досуг":["russian"],"доход":["russian"],"доцент":["russian"],"дощатый":["russian"],"драка":["russian"],"древний":["russian"],"дремать":["russian"],"дробный":["russian"],"дрова":["russian"],"дрожать":["russian"],"другой":["russian"],"дружба":["russian"],"дубовый":["russian"],"дуга":["russian"],"думать":["russian"],"дурной":["russian"],"духи":["russian"],"душный":["russian"],"дуэль":["russian"],"дуэт":["russian"],"дыра":["russian"],"дыхание":["russian"],"дюжина":["russian"],"дядя":["russian"],"едва":["russian"],"единый":["russian"],"ерунда":["russian"],"если":["russian"],"ехать":["russian"],"жадный":["russian"],"жажда":["russian"],"жалеть":["russian"],"жалоба":["russian"],"жанр":["russian"],"жареный":["russian"],"жаркий":["russian"],"жгучий":["russian"],"жевать":["russian"],"желание":["russian"],"желудок":["russian"],"жена":["russian"],"женщина":["russian"],"жертва":["russian"],"жест":["russian"],"жидкость":["russian"],"житель":["russian"],"жить":["russian"],"жрец":["russian"],"жулик":["russian"],"журнал":["russian"],"жуткий":["russian"],"забрать":["russian"],"забыть":["russian"],"завести":["russian"],"завод":["russian"],"завтра":["russian"],"загадка":["russian"],"загнать":["russian"],"заговор":["russian"],"задача":["russian"],"задеть":["russian"],"задний":["russian"],"задолго":["russian"],"заехать":["russian"],"заказ":["russian"],"закон":["russian"],"закрыть":["russian"],"закуска":["russian"],"залезть":["russian"],"залить":["russian"],"залп":["russian"],"замок":["russian"],"замуж":["russian"],"замысел":["russian"],"занавес":["russian"],"заново":["russian"],"занять":["russian"],"заодно":["russian"],"запись":["russian"],"запрос":["russian"],"запуск":["russian"],"запястье":["russian"],"заранее":["russian"],"заросль":["russian"],"зарплата":["russian"],"заря":["russian"],"засада":["russian"],"заслуга":["russian"],"заснуть":["russian"],"застать":["russian"],"затвор":["russian"],"затеять":["russian"],"затрата":["russian"],"затылок":["russian"],"захват":["russian"],"зачем":["russian"],"защита":["russian"],"заявить":["russian"],"заяц":["russian"],"звезда":["russian"],"звено":["russian"],"звонить":["russian"],"здесь":["russian"],"зелень":["russian"],"земля":["russian"],"зеркало":["russian"],"зерно":["russian"],"зима":["russian"],"злой":["russian"],"змея":["russian"],"знамя":["russian"],"знание":["russian"],"значит":["russian"],"золотой":["russian"],"зона":["russian"],"зонтик":["russian"],"зоопарк":["russian"],"зрачок":["russian"],"зрение":["russian"],"зритель":["russian"],"зубной":["russian"],"зубр":["russian"],"игла":["russian"],"идеал":["russian"],"идеолог":["russian"],"идея":["russian"],"идол":["russian"],"идти":["russian"],"изба":["russian"],"избить":["russian"],"избрать":["russian"],"избыток":["russian"],"извлечь":["russian"],"извне":["russian"],"изгиб":["russian"],"изгнать":["russian"],"издание":["russian"],"изделие":["russian"],"изнутри":["russian"],"изобилие":["russian"],"изоляция":["russian"],"изредка":["russian"],"изрядно":["russian"],"изучение":["russian"],"изъять":["russian"],"изящный":["russian"],"икона":["russian"],"икра":["russian"],"иллюзия":["russian"],"именно":["russian"],"иметь":["russian"],"имидж":["russian"],"империя":["russian"],"импульс":["russian"],"иначе":["russian"],"инвалид":["russian"],"индекс":["russian"],"индивид":["russian"],"инерция":["russian"],"инженер":["russian"],"иногда":["russian"],"иной":["russian"],"институт":["russian"],"интерес":["russian"],"интрига":["russian"],"интуиция":["russian"],"инфаркт":["russian"],"инцидент":["russian"],"ирония":["russian"],"искать":["russian"],"испуг":["russian"],"история":["russian"],"итог":["russian"],"июнь":["russian"],"кабель":["russian"],"кабинет":["russian"],"каблук":["russian"],"кавалер":["russian"],"кадр":["russian"],"каждый":["russian"],"кажется":["russian"],"казино":["russian"],"калитка":["russian"],"камень":["russian"],"камин":["russian"],"канал":["russian"],"кандидат":["russian"],"каникулы":["russian"],"канон":["russian"],"капитан":["russian"],"капля":["russian"],"капот":["russian"],"капуста":["russian"],"карандаш":["russian"],"карета":["russian"],"каркас":["russian"],"карман":["russian"],"картина":["russian"],"карьера":["russian"],"каска":["russian"],"кассета":["russian"],"кастрюля":["russian"],"каталог":["russian"],"катер":["russian"],"каток":["russian"],"катушка":["russian"],"кафедра":["russian"],"качество":["russian"],"каша":["russian"],"кашлять":["russian"],"каюта":["russian"],"квадрат":["russian"],"квартира":["russian"],"квота":["russian"],"кепка":["russian"],"кивнуть":["russian"],"километр":["russian"],"кино":["russian"],"киоск":["russian"],"кипяток":["russian"],"кирпич":["russian"],"кислота":["russian"],"кисть":["russian"],"клавиша":["russian"],"клапан":["russian"],"класс":["russian"],"клей":["russian"],"клетка":["russian"],"клиент":["russian"],"климат":["russian"],"клиника":["russian"],"кличка":["russian"],"клоун":["russian"],"клочок":["russian"],"клуб":["russian"],"клумба":["russian"],"ключ":["russian"],"книга":["russian"],"кнопка":["russian"],"кнут":["russian"],"княгиня":["russian"],"князь":["russian"],"кобура":["russian"],"когда":["russian"],"кодекс":["russian"],"кожа":["russian"],"коктейль":["russian"],"колено":["russian"],"коллега":["russian"],"колонна":["russian"],"колпак":["russian"],"кольцо":["russian"],"колючий":["russian"],"коляска":["russian"],"команда":["russian"],"комедия":["russian"],"комиссия":["russian"],"коммуна":["russian"],"комната":["russian"],"комок":["russian"],"компания":["russian"],"комфорт":["russian"],"конвейер":["russian"],"конгресс":["russian"],"конечно":["russian"],"конкурс":["russian"],"контроль":["russian"],"концерт":["russian"],"конь":["russian"],"конюшня":["russian"],"копать":["russian"],"копейка":["russian"],"копыто":["russian"],"корабль":["russian"],"корень":["russian"],"корзина":["russian"],"коридор":["russian"],"кормить":["russian"],"корпус":["russian"],"космос":["russian"],"костюм":["russian"],"косяк":["russian"],"котел":["russian"],"котлета":["russian"],"который":["russian"],"коттедж":["russian"],"кофе":["russian"],"кофта":["russian"],"кошка":["russian"],"кража":["russian"],"край":["russian"],"красный":["russian"],"краткий":["russian"],"кредит":["russian"],"крем":["russian"],"крепкий":["russian"],"кресло":["russian"],"кривой":["russian"],"кризис":["russian"],"кристалл":["russian"],"критерий":["russian"],"кричать":["russian"],"кровь":["russian"],"крокодил":["russian"],"кролик":["russian"],"кроме":["russian"],"крона":["russian"],"круг":["russian"],"кружка":["russian"],"крупный":["russian"],"крутой":["russian"],"крушение":["russian"],"крыло":["russian"],"крыша":["russian"],"крючок":["russian"],"кстати":["russian"],"кубик":["russian"],"куда":["russian"],"кузов":["russian"],"кукла":["russian"],"кулак":["russian"],"кулиса":["russian"],"культура":["russian"],"кумир":["russian"],"купе":["russian"],"купить":["russian"],"купол":["russian"],"купюра":["russian"],"курица":["russian"],"курорт":["russian"],"курс":["russian"],"куртка":["russian"],"кусок":["russian"],"куст":["russian"],"кухня":["russian"],"кушать":["russian"],"лабиринт":["russian"],"лавка":["russian"],"лагерь":["russian"],"ладно":["russian"],"ладонь":["russian"],"лапа":["russian"],"лауреат":["russian"],"лгать":["russian"],"лебедь":["russian"],"левый":["russian"],"легенда":["russian"],"легкий":["russian"],"ледяной":["russian"],"лежать":["russian"],"лезвие":["russian"],"лезть":["russian"],"лекция":["russian"],"ленивый":["russian"],"лента":["russian"],"лепесток":["russian"],"лесной":["russian"],"лестница":["russian"],"лететь":["russian"],"лето":["russian"],"лечить":["russian"],"лига":["russian"],"лидер":["russian"],"лиловый":["russian"],"лимон":["russian"],"линия":["russian"],"липкий":["russian"],"лист":["russian"],"литр":["russian"],"лихой":["russian"],"лицо":["russian"],"лишить":["russian"],"лишний":["russian"],"ловить":["russian"],"логика":["russian"],"лодка":["russian"],"ложь":["russian"],"лозунг":["russian"],"локоть":["russian"],"лопата":["russian"],"лошадь":["russian"],"лукавый":["russian"],"луна":["russian"],"лучший":["russian"],"лысый":["russian"],"льгота":["russian"],"любить":["russian"],"любой":["russian"],"людской":["russian"],"люстра":["russian"],"лютый":["russian"],"лягушка":["russian"],"магазин":["russian"],"магия":["russian"],"майор":["russian"],"майский":["russian"],"максимум":["russian"],"макушка":["russian"],"мало":["russian"],"мальчик":["russian"],"мама":["russian"],"манера":["russian"],"марка":["russian"],"март":["russian"],"маршрут":["russian"],"масса":["russian"],"мастер":["russian"],"масштаб":["russian"],"материал":["russian"],"матч":["russian"],"махать":["russian"],"машина":["russian"],"маяк":["russian"],"мебель":["russian"],"медаль":["russian"],"медведь":["russian"],"медицина":["russian"],"медь":["russian"],"между":["russian"],"мелкий":["russian"],"мелочь":["russian"],"мемуары":["russian"],"меньше":["russian"],"меню":["russian"],"менять":["russian"],"мера":["russian"],"мерцать":["russian"],"место":["russian"],"месяц":["russian"],"металл":["russian"],"метод":["russian"],"метр":["russian"],"механизм":["russian"],"меховой":["russian"],"мечтать":["russian"],"мешать":["russian"],"мешок":["russian"],"миграция":["russian"],"микрофон":["russian"],"милиция":["russian"],"миллион":["russian"],"милость":["russian"],"миля":["russian"],"мимо":["russian"],"минерал":["russian"],"министр":["russian"],"минута":["russian"],"мирный":["russian"],"миска":["russian"],"миссия":["russian"],"митинг":["russian"],"мишень":["russian"],"младший":["russian"],"мнение":["russian"],"мнимый":["russian"],"много":["russian"],"могучий":["russian"],"модель":["russian"],"может":["russian"],"мозг":["russian"],"мокрый":["russian"],"молекула":["russian"],"молния":["russian"],"молодой":["russian"],"молчать":["russian"],"момент":["russian"],"монета":["russian"],"монитор":["russian"],"монолог":["russian"],"монстр":["russian"],"монтаж":["russian"],"мораль":["russian"],"море":["russian"],"морковь":["russian"],"мороз":["russian"],"морщина":["russian"],"мостовая":["russian"],"мотать":["russian"],"мотив":["russian"],"мотор":["russian"],"мохнатый":["russian"],"мрамор":["russian"],"мрачный":["russian"],"мстить":["russian"],"мудрый":["russian"],"мужество":["russian"],"мужчина":["russian"],"музей":["russian"],"музыка":["russian"],"мундир":["russian"],"муравей":["russian"],"мусор":["russian"],"муха":["russian"],"мчаться":["russian"],"мысль":["russian"],"мыться":["russian"],"мышца":["russian"],"мышь":["russian"],"мюзикл":["russian"],"мягкий":["russian"],"мясо":["russian"],"набор":["russian"],"навык":["russian"],"наглый":["russian"],"нагрузка":["russian"],"надежда":["russian"],"надзор":["russian"],"надо":["russian"],"наедине":["russian"],"назад":["russian"],"название":["russian"],"назло":["russian"],"наивный":["russian"],"найти":["russian"],"наконец":["russian"],"налево":["russian"],"наличие":["russian"],"налог":["russian"],"намерен":["russian"],"нанести":["russian"],"напасть":["russian"],"например":["russian"],"народ":["russian"],"наследие":["russian"],"натура":["russian"],"наука":["russian"],"наутро":["russian"],"начать":["russian"],"небо":["russian"],"неважно":["russian"],"невеста":["russian"],"негодяй":["russian"],"недавно":["russian"],"неделя":["russian"],"недолго":["russian"],"недра":["russian"],"недуг":["russian"],"нежный":["russian"],"незачем":["russian"],"некто":["russian"],"нелепый":["russian"],"неловко":["russian"],"нельзя":["russian"],"немало":["russian"],"немой":["russian"],"неплохо":["russian"],"нервный":["russian"],"нередко":["russian"],"нестись":["russian"],"неудача":["russian"],"неужели":["russian"],"нефть":["russian"],"неясный":["russian"],"нигде":["russian"],"низкий":["russian"],"никакой":["russian"],"никогда":["russian"],"никуда":["russian"],"ничто":["russian"],"ничуть":["russian"],"ниша":["russian"],"нищий":["russian"],"новость":["russian"],"новый":["russian"],"нога":["russian"],"ноготь":["russian"],"ножницы":["russian"],"ноздря":["russian"],"номер":["russian"],"носить":["russian"],"носок":["russian"],"ночь":["russian"],"ноябрь":["russian"],"нрав":["russian"],"нуль":["russian"],"нынче":["russian"],"нырять":["russian"],"нюанс":["russian"],"няня":["russian"],"обаяние":["russian"],"обед":["russian"],"обезьяна":["russian"],"обещать":["russian"],"обжечь":["russian"],"обзор":["russian"],"обилие":["russian"],"обитать":["russian"],"область":["russian"],"облик":["russian"],"обложка":["russian"],"обмен":["russian"],"обморок":["russian"],"обожать":["russian"],"обои":["russian"],"оболочка":["russian"],"оборона":["russian"],"обочина":["russian"],"образ":["russian"],"обрести":["russian"],"обрыв":["russian"],"обувь":["russian"],"обучение":["russian"],"обход":["russian"],"общество":["russian"],"общий":["russian"],"объект":["russian"],"обыск":["russian"],"обычно":["russian"],"обязать":["russian"],"овощи":["russian"],"овраг":["russian"],"овца":["russian"],"оговорка":["russian"],"ограда":["russian"],"огурец":["russian"],"одежда":["russian"],"одеяло":["russian"],"один":["russian"],"однако":["russian"],"одолеть":["russian"],"ожидать":["russian"],"озеро":["russian"],"океан":["russian"],"окно":["russian"],"около":["russian"],"окоп":["russian"],"окраина":["russian"],"октябрь":["russian"],"опасный":["russian"],"опека":["russian"],"операция":["russian"],"описание":["russian"],"оплата":["russian"],"опора":["russian"],"оппонент":["russian"],"оптимизм":["russian"],"оптовый":["russian"],"опухоль":["russian"],"опыт":["russian"],"оратор":["russian"],"орбита":["russian"],"орган":["russian"],"орден":["russian"],"орел":["russian"],"оригинал":["russian"],"ориентир":["russian"],"оркестр":["russian"],"оружие":["russian"],"осенний":["russian"],"осколок":["russian"],"осмотр":["russian"],"остров":["russian"],"отбор":["russian"],"отбыть":["russian"],"отвлечь":["russian"],"отдать":["russian"],"отдел":["russian"],"отдых":["russian"],"отель":["russian"],"отец":["russian"],"отзыв":["russian"],"отказ":["russian"],"отклик":["russian"],"открыть":["russian"],"откуда":["russian"],"отличие":["russian"],"отныне":["russian"],"отойти":["russian"],"отпуск":["russian"],"отрасль":["russian"],"отросток":["russian"],"отрывок":["russian"],"отряд":["russian"],"отсек":["russian"],"отставка":["russian"],"отсюда":["russian"],"оттенок":["russian"],"оттого":["russian"],"отчего":["russian"],"отъезд":["russian"],"офис":["russian"],"офицер":["russian"],"охота":["russian"],"охрана":["russian"],"оценка":["russian"],"очаг":["russian"],"очень":["russian"],"очередь":["russian"],"очищать":["russian"],"ошибка":["russian"],"ощущение":["russian"],"павильон":["russian"],"падать":["russian"],"пазуха":["russian"],"пакет":["russian"],"палата":["russian"],"палец":["russian"],"палуба":["russian"],"пальто":["russian"],"память":["russian"],"панель":["russian"],"паника":["russian"],"пара":["russian"],"парень":["russian"],"пароход":["russian"],"партия":["russian"],"парус":["russian"],"паспорт":["russian"],"пассажир":["russian"],"пастух":["russian"],"патент":["russian"],"патрон":["russian"],"пауза":["russian"],"паук":["russian"],"паутина":["russian"],"пафос":["russian"],"пахнуть":["russian"],"пациент":["russian"],"пачка":["russian"],"певец":["russian"],"педагог":["russian"],"пейзаж":["russian"],"пенсия":["russian"],"пепел":["russian"],"первый":["russian"],"перед":["russian"],"период":["russian"],"перо":["russian"],"перрон":["russian"],"персонаж":["russian"],"перчатка":["russian"],"песня":["russian"],"песок":["russian"],"петля":["russian"],"петрушка":["russian"],"петух":["russian"],"пехота":["russian"],"печать":["russian"],"печень":["russian"],"пешком":["russian"],"пещера":["russian"],"пианист":["russian"],"пиджак":["russian"],"пилот":["russian"],"пионер":["russian"],"пирамида":["russian"],"пирожок":["russian"],"письмо":["russian"],"пища":["russian"],"плавание":["russian"],"плакать":["russian"],"пламя":["russian"],"план":["russian"],"пласт":["russian"],"платить":["russian"],"пленный":["russian"],"плечо":["russian"],"плита":["russian"],"плод":["russian"],"плоский":["russian"],"плотный":["russian"],"плохой":["russian"],"площадь":["russian"],"плыть":["russian"],"плюс":["russian"],"пляж":["russian"],"плясать":["russian"],"победа":["russian"],"повар":["russian"],"повод":["russian"],"повсюду":["russian"],"повязка":["russian"],"погода":["russian"],"погреб":["russian"],"подбор":["russian"],"подвиг":["russian"],"подделка":["russian"],"поджать":["russian"],"поднос":["russian"],"подпись":["russian"],"подруга":["russian"],"подход":["russian"],"подчас":["russian"],"подъезд":["russian"],"поединок":["russian"],"поезд":["russian"],"поесть":["russian"],"поехать":["russian"],"пожалуй":["russian"],"пожилой":["russian"],"позади":["russian"],"позвать":["russian"],"поздний":["russian"],"позиция":["russian"],"позор":["russian"],"поиск":["russian"],"поймать":["russian"],"пойти":["russian"],"поклон":["russian"],"покой":["russian"],"покрыть":["russian"],"полдень":["russian"],"полезный":["russian"],"ползти":["russian"],"полк":["russian"],"полный":["russian"],"половина":["russian"],"полтора":["russian"],"польза":["russian"],"поляна":["russian"],"помидор":["russian"],"помнить":["russian"],"помощь":["russian"],"попасть":["russian"],"поперек":["russian"],"поплыть":["russian"],"пополам":["russian"],"поправка":["russian"],"попугай":["russian"],"попытка":["russian"],"порог":["russian"],"портрет":["russian"],"порция":["russian"],"порыв":["russian"],"порядок":["russian"],"после":["russian"],"посол":["russian"],"посреди":["russian"],"постель":["russian"],"посуда":["russian"],"потом":["russian"],"похвала":["russian"],"похожий":["russian"],"поцелуй":["russian"],"почва":["russian"],"почему":["russian"],"пошлина":["russian"],"поэма":["russian"],"поэтому":["russian"],"право":["russian"],"праздник":["russian"],"практика":["russian"],"прах":["russian"],"преграда":["russian"],"предмет":["russian"],"прежде":["russian"],"прелесть":["russian"],"премия":["russian"],"препарат":["russian"],"пресса":["russian"],"прибыть":["russian"],"прижать":["russian"],"прийти":["russian"],"приказ":["russian"],"прилавок":["russian"],"пример":["russian"],"принять":["russian"],"природа":["russian"],"притом":["russian"],"прихожая":["russian"],"прицел":["russian"],"причина":["russian"],"приют":["russian"],"прогноз":["russian"],"продукт":["russian"],"проект":["russian"],"прожить":["russian"],"прокат":["russian"],"промысел":["russian"],"пропуск":["russian"],"просто":["russian"],"против":["russian"],"профиль":["russian"],"процесс":["russian"],"прочий":["russian"],"прошлый":["russian"],"прощать":["russian"],"пружина":["russian"],"прут":["russian"],"прыжок":["russian"],"прямой":["russian"],"птица":["russian"],"публика":["russian"],"пугать":["russian"],"пуговица":["russian"],"пузырь":["russian"],"пульт":["russian"],"пуля":["russian"],"пункт":["russian"],"пускать":["russian"],"пустой":["russian"],"путь":["russian"],"пухлый":["russian"],"пучок":["russian"],"пушистый":["russian"],"пушка":["russian"],"пчела":["russian"],"пшеница":["russian"],"пылать":["russian"],"пыль":["russian"],"пышный":["russian"],"пьеса":["russian"],"пятка":["russian"],"пятно":["russian"],"пятый":["russian"],"пятьсот":["russian"],"работа":["russian"],"равнина":["russian"],"ради":["russian"],"радость":["russian"],"радуга":["russian"],"разбить":["russian"],"развитие":["russian"],"разговор":["russian"],"раздел":["russian"],"различие":["russian"],"размер":["russian"],"разный":["russian"],"разрыв":["russian"],"разум":["russian"],"район":["russian"],"ракета":["russian"],"раковина":["russian"],"рамка":["russian"],"рано":["russian"],"рапорт":["russian"],"распад":["russian"],"рассказ":["russian"],"расти":["russian"],"расход":["russian"],"расцвет":["russian"],"рация":["russian"],"рвануть":["russian"],"рваться":["russian"],"реакция":["russian"],"ребро":["russian"],"реветь":["russian"],"редактор":["russian"],"редкий":["russian"],"реестр":["russian"],"режим":["russian"],"резать":["russian"],"резерв":["russian"],"резина":["russian"],"резко":["russian"],"резной":["russian"],"рейс":["russian"],"реклама":["russian"],"рекорд":["russian"],"религия":["russian"],"рельс":["russian"],"ремень":["russian"],"ремонт":["russian"],"реплика":["russian"],"репортаж":["russian"],"ресница":["russian"],"ресторан":["russian"],"реформа":["russian"],"рецепт":["russian"],"речь":["russian"],"решение":["russian"],"ржавый":["russian"],"риск":["russian"],"рисунок":["russian"],"ритуал":["russian"],"рифма":["russian"],"робко":["russian"],"робот":["russian"],"ровесник":["russian"],"ровно":["russian"],"родной":["russian"],"рождение":["russian"],"роза":["russian"],"розовый":["russian"],"розыск":["russian"],"роль":["russian"],"роман":["russian"],"роскошь":["russian"],"роспись":["russian"],"рост":["russian"],"рубашка":["russian"],"рубеж":["russian"],"рубить":["russian"],"рубрика":["russian"],"рудник":["russian"],"рука":["russian"],"рукопись":["russian"],"румяный":["russian"],"русло":["russian"],"рухнуть":["russian"],"ручей":["russian"],"ручной":["russian"],"рыба":["russian"],"рыжий":["russian"],"рынок":["russian"],"рыхлый":["russian"],"рыцарь":["russian"],"рычаг":["russian"],"рюкзак":["russian"],"рядом":["russian"],"садовый":["russian"],"сажать":["russian"],"салон":["russian"],"салфетка":["russian"],"салют":["russian"],"самец":["russian"],"самовар":["russian"],"самый":["russian"],"сани":["russian"],"санкция":["russian"],"сапог":["russian"],"сарай":["russian"],"сатира":["russian"],"сахар":["russian"],"сбить":["russian"],"сбоку":["russian"],"сборная":["russian"],"сбыт":["russian"],"свадьба":["russian"],"свалка":["russian"],"сварить":["russian"],"свежий":["russian"],"сверху":["russian"],"свет":["russian"],"свеча":["russian"],"свинья":["russian"],"свист":["russian"],"свитер":["russian"],"свобода":["russian"],"сводка":["russian"],"свой":["russian"],"свыше":["russian"],"связь":["russian"],"сдаться":["russian"],"сделать":["russian"],"сегмент":["russian"],"сегодня":["russian"],"седло":["russian"],"седой":["russian"],"седьмой":["russian"],"сезон":["russian"],"сейф":["russian"],"сейчас":["russian"],"секрет":["russian"],"сектор":["russian"],"секунда":["russian"],"семинар":["russian"],"семья":["russian"],"сенатор":["russian"],"сено":["russian"],"сенсация":["russian"],"сентябрь":["russian"],"сервис":["russian"],"сердце":["russian"],"середина":["russian"],"сержант":["russian"],"серия":["russian"],"серый":["russian"],"сессия":["russian"],"сесть":["russian"],"сетевой":["russian"],"сжатый":["russian"],"сжечь":["russian"],"сзади":["russian"],"сигнал":["russian"],"сиденье":["russian"],"сила":["russian"],"силуэт":["russian"],"сильный":["russian"],"символ":["russian"],"симпатия":["russian"],"симфония":["russian"],"синий":["russian"],"синтез":["russian"],"синяк":["russian"],"сирень":["russian"],"система":["russian"],"ситуация":["russian"],"сияние":["russian"],"сказать":["russian"],"скала":["russian"],"скамейка":["russian"],"скандал":["russian"],"скатерть":["russian"],"скачок":["russian"],"скважина":["russian"],"сквер":["russian"],"сквозь":["russian"],"скелет":["russian"],"скидка":["russian"],"склад":["russian"],"сколько":["russian"],"скорый":["russian"],"скосить":["russian"],"скот":["russian"],"скрипка":["russian"],"скудный":["russian"],"скука":["russian"],"слабый":["russian"],"слава":["russian"],"сладкий":["russian"],"слегка":["russian"],"след":["russian"],"слеза":["russian"],"слепой":["russian"],"слесарь":["russian"],"слишком":["russian"],"слово":["russian"],"слог":["russian"],"сложный":["russian"],"сломать":["russian"],"служба":["russian"],"слух":["russian"],"случай":["russian"],"слышать":["russian"],"слюна":["russian"],"смежный":["russian"],"смелый":["russian"],"сменить":["russian"],"смесь":["russian"],"сметана":["russian"],"смех":["russian"],"смола":["russian"],"смуглый":["russian"],"смутный":["russian"],"смущать":["russian"],"смысл":["russian"],"снайпер":["russian"],"снаряд":["russian"],"сначала":["russian"],"снег":["russian"],"снизу":["russian"],"сниться":["russian"],"сно��а":["russian"],"снять":["russian"],"собака":["russian"],"соблазн":["russian"],"собрание":["russian"],"событие":["russian"],"совесть":["russian"],"совсем":["russian"],"согласие":["russian"],"создать":["russian"],"сознание":["russian"],"созреть":["russian"],"сойтись":["russian"],"сокол":["russian"],"солдат":["russian"],"соленый":["russian"],"солнце":["russian"],"солома":["russian"],"сомнение":["russian"],"сонный":["russian"],"соперник":["russian"],"соратник":["russian"],"сорвать":["russian"],"сосед":["russian"],"сосиска":["russian"],"состав":["russian"],"сотня":["russian"],"соус":["russian"],"союз":["russian"],"спад":["russian"],"спальня":["russian"],"спасти":["russian"],"спектр":["russian"],"сперва":["russian"],"спешить":["russian"],"спина":["russian"],"спирт":["russian"],"список":["russian"],"спичка":["russian"],"сплав":["russian"],"спонсор":["russian"],"спор":["russian"],"способ":["russian"],"справка":["russian"],"спустя":["russian"],"спутник":["russian"],"сразу":["russian"],"средство":["russian"],"срок":["russian"],"срыв":["russian"],"ссора":["russian"],"ссылка":["russian"],"ставить":["russian"],"стадия":["russian"],"стакан":["russian"],"станция":["russian"],"старый":["russian"],"стая":["russian"],"стебель":["russian"],"стекло":["russian"],"стена":["russian"],"степень":["russian"],"стереть":["russian"],"стиль":["russian"],"стимул":["russian"],"стирать":["russian"],"стихи":["russian"],"стоить":["russian"],"стойка":["russian"],"стол":["russian"],"стонать":["russian"],"стопа":["russian"],"сторона":["russian"],"стоянка":["russian"],"страна":["russian"],"стричь":["russian"],"строгий":["russian"],"струя":["russian"],"студент":["russian"],"стук":["russian"],"ступня":["russian"],"стыдно":["russian"],"суббота":["russian"],"субъект":["russian"],"сувенир":["russian"],"сугроб":["russian"],"сугубо":["russian"],"судить":["russian"],"судно":["russian"],"судьба":["russian"],"суета":["russian"],"суметь":["russian"],"сумма":["russian"],"сумрак":["russian"],"сундук":["russian"],"супруг":["russian"],"суровый":["russian"],"сутки":["russian"],"сухой":["russian"],"суша":["russian"],"существо":["russian"],"сфера":["russian"],"схема":["russian"],"схожий":["russian"],"сценарий":["russian"],"счастье":["russian"],"считать":["russian"],"съезд":["russian"],"сыграть":["russian"],"сырой":["russian"],"сытый":["russian"],"сыщик":["russian"],"сюда":["russian"],"сюжет":["russian"],"сюрприз":["russian"],"тайна":["russian"],"также":["russian"],"такой":["russian"],"такси":["russian"],"тактика":["russian"],"талия":["russian"],"таможня":["russian"],"танец":["russian"],"таракан":["russian"],"тарелка":["russian"],"тариф":["russian"],"тащить":["russian"],"таять":["russian"],"тварь":["russian"],"театр":["russian"],"тезис":["russian"],"текст":["russian"],"текущий":["russian"],"телефон":["russian"],"тема":["russian"],"темнота":["russian"],"теневой":["russian"],"теннис":["russian"],"теория":["russian"],"теперь":["russian"],"тепло":["russian"],"терапия":["russian"],"терзать":["russian"],"термин":["russian"],"терпеть":["russian"],"терраса":["russian"],"терять":["russian"],"тесный":["russian"],"тетрадь":["russian"],"техника":["russian"],"течение":["russian"],"тигр":["russian"],"типовой":["russian"],"тираж":["russian"],"титул":["russian"],"тихий":["russian"],"ткань":["russian"],"товарищ":["russian"],"тоже":["russian"],"толпа":["russian"],"толстый":["russian"],"толчок":["russian"],"толщина":["russian"],"только":["russian"],"тонкий":["russian"],"тонна":["russian"],"топить":["russian"],"топор":["russian"],"торговля":["russian"],"тормоз":["russian"],"торчать":["russian"],"тотчас":["russian"],"точка":["russian"],"точно":["russian"],"тощий":["russian"],"трава":["russian"],"традиция":["russian"],"трактор":["russian"],"трамвай":["russian"],"траншея":["russian"],"трасса":["russian"],"тревога":["russian"],"трезвый":["russian"],"тренер":["russian"],"трепет":["russian"],"треск":["russian"],"третий":["russian"],"трещина":["russian"],"трибуна":["russian"],"тридцать":["russian"],"триста":["russian"],"триумф":["russian"],"трогать":["russian"],"тройка":["russian"],"тронуть":["russian"],"тропа":["russian"],"тротуар":["russian"],"трубка":["russian"],"труд":["russian"],"трюк":["russian"],"тряпка":["russian"],"туго":["russian"],"туловище":["russian"],"туман":["russian"],"тумбочка":["russian"],"тундра":["russian"],"тупик":["russian"],"турист":["russian"],"турнир":["russian"],"тусклый":["russian"],"туфля":["russian"],"туча":["russian"],"тысяча":["russian"],"тяга":["russian"],"тяжело":["russian"],"убежать":["russian"],"убогий":["russian"],"уборка":["russian"],"уважение":["russian"],"увезти":["russian"],"уволить":["russian"],"угадать":["russian"],"угол":["russian"],"угощать":["russian"],"угроза":["russian"],"угрюмый":["russian"],"удар":["russian"],"удачный":["russian"],"уделять":["russian"],"удивить":["russian"],"удобный":["russian"],"удочка":["russian"],"уезжать":["russian"],"ужин":["russian"],"узел":["russian"],"узкий":["russian"],"уйти":["russian"],"указание":["russian"],"уклон":["russian"],"украсть":["russian"],"укусить":["russian"],"улетать":["russian"],"улица":["russian"],"улыбка":["russian"],"умело":["russian"],"умение":["russian"],"умный":["russian"],"умолять":["russian"],"унести":["russian"],"унижать":["russian"],"унылый":["russian"],"упаковка":["russian"],"упасть":["russian"],"упорно":["russian"],"упрек":["russian"],"урна":["russian"],"уровень":["russian"],"урожай":["russian"],"уронить":["russian"],"усадьба":["russian"],"усатый":["russian"],"усвоить":["russian"],"усилие":["russian"],"условие":["russian"],"услуга":["russian"],"усмешка":["russian"],"успеть":["russian"],"устав":["russian"],"устоять":["russian"],"утечка":["russian"],"утешать":["russian"],"утро":["russian"],"уцелеть":["russian"],"участие":["russian"],"ученик":["russian"],"учесть":["russian"],"ущелье":["russian"],"ущерб":["russian"],"уютный":["russian"],"фабрика":["russian"],"фаворит":["russian"],"факел":["russian"],"факт":["russian"],"фамилия":["russian"],"фантазия":["russian"],"фасад":["russian"],"февраль":["russian"],"феномен":["russian"],"фермер":["russian"],"фигура":["russian"],"физика":["russian"],"филиал":["russian"],"философ":["russian"],"фильм":["russian"],"финал":["russian"],"флаг":["russian"],"флот":["russian"],"фойе":["russian"],"фокус":["russian"],"фонарь":["russian"],"фонд":["russian"],"фонтан":["russian"],"форма":["russian"],"форум":["russian"],"фото":["russian"],"фрагмент":["russian"],"фраза":["russian"],"фракция":["russian"],"фронт":["russian"],"фрукт":["russian"],"функция":["russian"],"фуражка":["russian"],"футбол":["russian"],"футляр":["russian"],"халат":["russian"],"хаос":["russian"],"характер":["russian"],"хата":["russian"],"хвалить":["russian"],"хватать":["russian"],"хвойный":["russian"],"хвост":["russian"],"химия":["russian"],"хирург":["russian"],"хитрый":["russian"],"хищник":["russian"],"хлеб":["russian"],"хлынуть":["russian"],"хмурый":["russian"],"ходить":["russian"],"хозяин":["russian"],"хоккей":["russian"],"холм":["russian"],"холст":["russian"],"хорошо":["russian"],"хотеть":["russian"],"храбрый":["russian"],"храм":["russian"],"хранить":["russian"],"хребет":["russian"],"хрен":["russian"],"хрипло":["russian"],"хроника":["russian"],"хрупкий":["russian"],"художник":["russian"],"худший":["russian"],"хулиган":["russian"],"хутор":["russian"],"царь":["russian"],"цветок":["russian"],"целевой":["russian"],"целиком":["russian"],"целое":["russian"],"цель":["russian"],"цензура":["russian"],"ценить":["russian"],"центр":["russian"],"цепной":["russian"],"цикл":["russian"],"цилиндр":["russian"],"цирк":["russian"],"цитата":["russian"],"цифра":["russian"],"чайник":["russian"],"часы":["russian"],"чашка":["russian"],"человек":["russian"],"челюсть":["russian"],"чемодан":["russian"],"чемпион":["russian"],"чепуха":["russian"],"червь":["russian"],"чердак":["russian"],"через":["russian"],"чернила":["russian"],"черта":["russian"],"чеснок":["russian"],"честно":["russian"],"четверть":["russian"],"четыре":["russian"],"число":["russian"],"чистый":["russian"],"читатель":["russian"],"чтение":["russian"],"чтобы":["russian"],"чувство":["russian"],"чудак":["russian"],"чудный":["russian"],"чудо":["russian"],"чужой":["russian"],"чулок":["russian"],"чума":["russian"],"чушь":["russian"],"чуять":["russian"],"шагать":["russian"],"шанс":["russian"],"шапка":["russian"],"шарик":["russian"],"шарф":["russian"],"шахматы":["russian"],"шашлык":["russian"],"шедевр":["russian"],"шептать":["russian"],"шерсть":["russian"],"шестой":["russian"],"шинель":["russian"],"ширина":["russian"],"шишка":["russian"],"шкаф":["russian"],"школа":["russian"],"шкура":["russian"],"шланг":["russian"],"шлем":["russian"],"шнур":["russian"],"шоколад":["russian"],"шорох":["russian"],"шоссе":["russian"],"шпион":["russian"],"шприц":["russian"],"штаб":["russian"],"штамм":["russian"],"штаны":["russian"],"штатный":["russian"],"штора":["russian"],"штраф":["russian"],"штурм":["russian"],"штык":["russian"],"шумно":["russian"],"шуршать":["russian"],"шутить":["russian"],"шутка":["russian"],"щедрый":["russian"],"щека":["russian"],"щенок":["russian"],"экзамен":["russian"],"экипаж":["russian"],"экономия":["russian"],"экран":["russian"],"эксперт":["russian"],"элемент":["russian"],"элитный":["russian"],"эмоция":["russian"],"энергия":["russian"],"эпизод":["russian"],"эпоха":["russian"],"эскиз":["russian"],"эстрада":["russian"],"этап":["russian"],"этика":["russian"],"этот":["russian"],"эфир":["russian"],"эффект":["russian"],"эшелон":["russian"],"юбилей":["russian"],"юбка":["russian"],"южный":["russian"],"юмор":["russian"],"юность":["russian"],"юрист":["russian"],"юстиция":["russian"],"яблоко":["russian"],"явление":["russian"],"ягода":["russian"],"ядро":["russian"],"язык":["russian"],"яйцо":["russian"],"якобы":["russian"],"якорь":["russian"],"январь":["russian"],"яркий":["russian"],"ярмарка":["russian"],"ярость":["russian"],"ясный":["russian"],"яхта":["russian"],"ячейка":["russian"],"ящик":["russian"],"ábaco":["spanish"],"abdomen":["spanish"],"abeja":["spanish"],"abierto":["spanish"],"abogado":["spanish"],"abono":["spanish"],"aborto":["spanish"],"abrazo":["spanish"],"abrir":["spanish"],"abuelo":["spanish"],"abuso":["spanish"],"acabar":["spanish"],"academia":["spanish"],"acceso":["spanish"],"acción":["spanish"],"aceite":["spanish"],"acelga":["spanish"],"acento":["spanish"],"aceptar":["spanish"],"ácido":["spanish"],"aclarar":["spanish"],"acné":["spanish"],"acoger":["spanish"],"acoso":["spanish"],"activo":["spanish"],"acto":["spanish"],"actriz":["spanish"],"actuar":["spanish"],"acudir":["spanish"],"acuerdo":["spanish"],"acusar":["spanish"],"adicto":["spanish"],"admitir":["spanish"],"adoptar":["spanish"],"adorno":["spanish"],"aduana":["spanish"],"adulto":["spanish"],"aéreo":["spanish"],"afectar":["spanish"],"afición":["spanish"],"afinar":["spanish"],"afirmar":["spanish"],"ágil":["spanish"],"agitar":["spanish"],"agonía":["spanish"],"agosto":["spanish"],"agotar":["spanish"],"agregar":["spanish"],"agrio":["spanish"],"agua":["spanish"],"agudo":["spanish"],"águila":["spanish"],"aguja":["spanish"],"ahogo":["spanish"],"ahorro":["spanish"],"aire":["spanish"],"aislar":["spanish"],"ajedrez":["spanish"],"ajeno":["spanish"],"ajuste":["spanish"],"alacrán":["spanish"],"alambre":["spanish"],"alarma":["spanish"],"alba":["spanish"],"álbum":["spanish"],"alcalde":["spanish"],"aldea":["spanish"],"alegre":["spanish"],"alejar":["spanish"],"alerta":["spanish"],"aleta":["spanish"],"alfiler":["spanish"],"alga":["spanish"],"algodón":["spanish"],"aliado":["spanish"],"aliento":["spanish"],"alivio":["spanish"],"alma":["spanish"],"almeja":["spanish"],"almíbar":["spanish"],"altar":["spanish"],"alteza":["spanish"],"altivo":["spanish"],"alto":["spanish"],"altura":["spanish"],"alumno":["spanish"],"alzar":["spanish"],"amable":["spanish"],"amante":["spanish"],"amapola":["spanish"],"amargo":["spanish"],"amasar":["spanish"],"ámbar":["spanish"],"ámbito":["spanish"],"ameno":["spanish"],"amigo":["spanish","turkish"],"amistad":["spanish"],"amor":["spanish"],"amparo":["spanish"],"amplio":["spanish"],"ancho":["spanish"],"anciano":["spanish"],"ancla":["spanish"],"andar":["spanish"],"andén":["spanish"],"anemia":["spanish"],"ángulo":["spanish"],"anillo":["spanish"],"ánimo":["spanish"],"anís":["spanish"],"anotar":["spanish"],"antena":["spanish"],"antiguo":["spanish"],"antojo":["spanish"],"anual":["spanish"],"anular":["spanish"],"anuncio":["spanish"],"añadir":["spanish"],"añejo":["spanish"],"año":["spanish"],"apagar":["spanish"],"aparato":["spanish"],"apetito":["spanish"],"apio":["spanish"],"aplicar":["spanish"],"apodo":["spanish"],"aporte":["spanish"],"apoyo":["spanish"],"aprender":["spanish"],"aprobar":["spanish"],"apuesta":["spanish"],"apuro":["spanish"],"arado":["spanish"],"araña":["spanish"],"arar":["spanish"],"árbitro":["spanish"],"árbol":["spanish"],"arbusto":["spanish"],"archivo":["spanish"],"arco":["spanish"],"arder":["spanish"],"ardilla":["spanish"],"arduo":["spanish"],"área":["spanish"],"árido":["spanish"],"aries":["spanish"],"armonía":["spanish"],"arnés":["spanish"],"aroma":["spanish","turkish"],"arpa":["spanish"],"arpón":["spanish"],"arreglo":["spanish"],"arroz":["spanish"],"arruga":["spanish"],"arte":["spanish"],"artista":["spanish"],"asa":["spanish"],"asado":["spanish"],"asalto":["spanish"],"ascenso":["spanish"],"asegurar":["spanish"],"aseo":["spanish"],"asesor":["spanish"],"asiento":["spanish"],"asilo":["spanish"],"asistir":["spanish"],"asno":["spanish"],"asombro":["spanish"],"áspero":["spanish"],"astilla":["spanish"],"astro":["spanish"],"astuto":["spanish"],"asumir":["spanish"],"asunto":["spanish"],"atajo":["spanish"],"ataque":["spanish"],"atar":["spanish"],"atento":["spanish"],"ateo":["spanish"],"ático":["spanish"],"atleta":["spanish"],"átomo":["spanish"],"atraer":["spanish"],"atroz":["spanish"],"atún":["spanish"],"audaz":["spanish"],"audio":["spanish"],"auge":["spanish"],"aula":["spanish"],"aumento":["spanish"],"ausente":["spanish"],"autor":["spanish"],"aval":["spanish"],"avance":["spanish"],"avaro":["spanish"],"ave":["spanish"],"avellana":["spanish"],"avena":["spanish"],"avestruz":["spanish"],"avión":["spanish"],"aviso":["spanish"],"ayer":["spanish"],"ayuda":["spanish"],"ayuno":["spanish"],"azafrán":["spanish"],"azar":["spanish"],"azote":["spanish"],"azúcar":["spanish"],"azufre":["spanish"],"azul":["spanish"],"baba":["spanish"],"babor":["spanish"],"bache":["spanish"],"bahía":["spanish"],"baile":["spanish"],"bajar":["spanish"],"balanza":["spanish"],"balcón":["spanish"],"balde":["spanish"],"bambú":["spanish"],"banco":["spanish"],"banda":["spanish"],"baño":["spanish"],"barba":["spanish"],"barco":["spanish"],"barniz":["spanish"],"barro":["spanish"],"báscula":["spanish"],"bastón":["spanish"],"basura":["spanish"],"batalla":["spanish"],"batería":["spanish"],"batir":["spanish"],"batuta":["spanish"],"baúl":["spanish"],"bazar":["spanish"],"bebé":["spanish"],"bebida":["spanish"],"bello":["spanish"],"besar":["spanish"],"beso":["spanish"],"bestia":["spanish"],"bicho":["spanish"],"bien":["spanish"],"bingo":["spanish"],"blanco":["spanish"],"bloque":["spanish"],"blusa":["spanish"],"boa":["spanish"],"bobina":["spanish"],"bobo":["spanish"],"boca":["spanish"],"bocina":["spanish"],"boda":["spanish"],"bodega":["spanish"],"boina":["spanish"],"bola":["spanish"],"bolero":["spanish","turkish"],"bolsa":["spanish"],"bomba":["spanish"],"bondad":["spanish"],"bonito":["spanish"],"bono":["spanish"],"bonsái":["spanish"],"borde":["spanish"],"borrar":["spanish"],"bosque":["spanish"],"bote":["spanish"],"botín":["spanish"],"bóveda":["spanish"],"bozal":["spanish"],"bravo":["spanish"],"brazo":["spanish"],"brecha":["spanish"],"breve":["spanish"],"brillo":["spanish"],"brinco":["spanish"],"brisa":["spanish"],"broca":["spanish"],"broma":["spanish"],"bronce":["spanish"],"brote":["spanish"],"bruja":["spanish"],"brusco":["spanish"],"bruto":["spanish"],"buceo":["spanish"],"bucle":["spanish"],"bueno":["spanish"],"buey":["spanish"],"bufanda":["spanish"],"bufón":["spanish"],"búho":["spanish"],"buitre":["spanish"],"bulto":["spanish"],"burbuja":["spanish"],"burla":["spanish"],"burro":["spanish"],"buscar":["spanish"],"butaca":["spanish"],"buzón":["spanish"],"caballo":["spanish"],"cabeza":["spanish"],"cabina":["spanish"],"cabra":["spanish"],"cacao":["spanish"],"cadáver":["spanish"],"cadena":["spanish"],"caer":["spanish"],"café":["spanish"],"caída":["spanish"],"caimán":["spanish"],"caja":["spanish"],"cajón":["spanish"],"cal":["spanish"],"calamar":["spanish"],"calcio":["spanish"],"caldo":["spanish"],"calidad":["spanish"],"calle":["spanish"],"calma":["spanish"],"calor":["spanish"],"calvo":["spanish"],"cama":["spanish"],"cambio":["spanish"],"camello":["spanish"],"camino":["spanish"],"campo":["spanish"],"cáncer":["spanish"],"candil":["spanish"],"canela":["spanish"],"canguro":["spanish"],"canica":["spanish"],"canto":["spanish"],"caña":["spanish"],"cañón":["spanish"],"caoba":["spanish"],"caos":["spanish"],"capaz":["spanish"],"capitán":["spanish"],"capote":["spanish"],"captar":["spanish"],"capucha":["spanish"],"cara":["spanish"],"carbón":["spanish"],"cárcel":["spanish"],"careta":["spanish"],"carga":["spanish"],"cariño":["spanish"],"carne":["spanish"],"carpeta":["spanish"],"carro":["spanish"],"carta":["spanish"],"casa":["spanish"],"casco":["spanish"],"casero":["spanish"],"caspa":["spanish"],"castor":["spanish"],"catorce":["spanish"],"catre":["spanish"],"caudal":["spanish"],"causa":["spanish"],"cazo":["spanish"],"cebolla":["spanish"],"ceder":["spanish"],"cedro":["spanish"],"celda":["spanish"],"célebre":["spanish"],"celoso":["spanish"],"célula":["spanish"],"cemento":["spanish"],"ceniza":["spanish"],"centro":["spanish"],"cerca":["spanish"],"cerdo":["spanish"],"cereza":["spanish"],"cero":["spanish"],"cerrar":["spanish"],"certeza":["spanish"],"césped":["spanish"],"cetro":["spanish"],"chacal":["spanish"],"chaleco":["spanish"],"champú":["spanish"],"chancla":["spanish"],"chapa":["spanish"],"charla":["spanish"],"chico":["spanish"],"chiste":["spanish"],"chivo":["spanish"],"choque":["spanish"],"choza":["spanish"],"chuleta":["spanish"],"chupar":["spanish"],"ciclón":["spanish"],"ciego":["spanish"],"cielo":["spanish"],"cien":["spanish"],"cierto":["spanish"],"cifra":["spanish"],"cigarro":["spanish"],"cima":["spanish"],"cinco":["spanish"],"cine":["spanish"],"cinta":["spanish"],"ciprés":["spanish"],"circo":["spanish"],"ciruela":["spanish"],"cisne":["spanish"],"cita":["spanish"],"ciudad":["spanish"],"clamor":["spanish"],"clan":["spanish"],"claro":["spanish"],"clase":["spanish"],"clave":["spanish"],"cliente":["spanish"],"clima":["spanish"],"clínica":["spanish"],"cobre":["spanish"],"cocción":["spanish"],"cochino":["spanish"],"cocina":["spanish"],"coco":["spanish"],"código":["spanish"],"codo":["spanish"],"cofre":["spanish"],"coger":["spanish"],"cohete":["spanish"],"cojín":["spanish"],"cojo":["spanish"],"cola":["spanish"],"colcha":["spanish"],"colegio":["spanish"],"colgar":["spanish"],"colina":["spanish"],"collar":["spanish"],"colmo":["spanish"],"columna":["spanish"],"combate":["spanish"],"comer":["spanish"],"comida":["spanish"],"cómodo":["spanish"],"compra":["spanish"],"conde":["spanish"],"conejo":["spanish"],"conga":["spanish"],"conocer":["spanish"],"consejo":["spanish"],"contar":["spanish"],"copa":["spanish"],"copia":["spanish"],"corazón":["spanish"],"corbata":["spanish"],"corcho":["spanish"],"cordón":["spanish"],"corona":["spanish"],"correr":["spanish"],"coser":["spanish"],"cosmos":["spanish"],"costa":["spanish"],"cráneo":["spanish"],"cráter":["spanish"],"crear":["spanish"],"crecer":["spanish"],"creído":["spanish"],"crema":["spanish"],"cría":["spanish"],"crimen":["spanish"],"cripta":["spanish"],"crisis":["spanish"],"cromo":["spanish"],"crónica":["spanish"],"croqueta":["spanish"],"crudo":["spanish"],"cruz":["spanish"],"cuadro":["spanish"],"cuarto":["spanish"],"cuatro":["spanish"],"cubo":["spanish"],"cubrir":["spanish"],"cuchara":["spanish"],"cuello":["spanish"],"cuento":["spanish"],"cuerda":["spanish"],"cuesta":["spanish"],"cueva":["spanish"],"cuidar":["spanish"],"culebra":["spanish"],"culpa":["spanish"],"culto":["spanish"],"cumbre":["spanish"],"cumplir":["spanish"],"cuna":["spanish"],"cuneta":["spanish"],"cuota":["spanish"],"cupón":["spanish"],"cúpula":["spanish"],"curar":["spanish"],"curioso":["spanish"],"curso":["spanish"],"curva":["spanish"],"cutis":["spanish"],"dama":["spanish"],"danza":["spanish"],"dar":["spanish"],"dardo":["spanish"],"dátil":["spanish"],"deber":["spanish"],"débil":["spanish"],"década":["spanish"],"decir":["spanish"],"dedo":["spanish"],"defensa":["spanish"],"definir":["spanish"],"dejar":["spanish"],"delfín":["spanish"],"delgado":["spanish"],"delito":["spanish"],"demora":["spanish"],"denso":["spanish"],"dental":["spanish"],"deporte":["spanish"],"derecho":["spanish"],"derrota":["spanish"],"desayuno":["spanish"],"deseo":["spanish"],"desfile":["spanish"],"desnudo":["spanish"],"destino":["spanish"],"desvío":["spanish"],"detalle":["spanish"],"detener":["spanish"],"deuda":["spanish"],"día":["spanish"],"diablo":["spanish"],"diadema":["spanish"],"diamante":["spanish"],"diana":["spanish"],"diario":["spanish"],"dibujo":["spanish"],"dictar":["spanish"],"diente":["spanish"],"dieta":["spanish"],"diez":["spanish"],"difícil":["spanish"],"digno":["spanish"],"dilema":["spanish"],"diluir":["spanish"],"dinero":["spanish"],"directo":["spanish"],"dirigir":["spanish"],"disco":["spanish"],"diseño":["spanish"],"disfraz":["spanish"],"diva":["spanish"],"divino":["spanish"],"doble":["spanish"],"doce":["spanish"],"dolor":["spanish"],"domingo":["spanish"],"don":["spanish"],"donar":["spanish"],"dorado":["spanish"],"dormir":["spanish"],"dorso":["spanish"],"dos":["spanish"],"dosis":["spanish"],"dragón":["spanish"],"droga":["spanish"],"ducha":["spanish"],"duda":["spanish"],"duelo":["spanish"],"dueño":["spanish"],"dulce":["spanish"],"dúo":["spanish"],"duque":["spanish"],"durar":["spanish"],"dureza":["spanish"],"duro":["spanish"],"ébano":["spanish"],"ebrio":["spanish"],"echar":["spanish"],"eco":["spanish"],"ecuador":["spanish"],"edad":["spanish"],"edición":["spanish"],"edificio":["spanish"],"editor":["spanish"],"educar":["spanish"],"efecto":["spanish"],"eficaz":["spanish"],"eje":["spanish"],"ejemplo":["spanish"],"elefante":["spanish"],"elegir":["spanish"],"elemento":["spanish"],"elevar":["spanish"],"elipse":["spanish"],"élite":["spanish"],"elixir":["spanish"],"elogio":["spanish"],"eludir":["spanish"],"embudo":["spanish"],"emitir":["spanish"],"emoción":["spanish"],"empate":["spanish"],"empeño":["spanish"],"empleo":["spanish"],"empresa":["spanish"],"enano":["spanish"],"encargo":["spanish"],"enchufe":["spanish"],"encía":["spanish"],"enemigo":["spanish"],"enero":["spanish"],"enfado":["spanish"],"enfermo":["spanish"],"engaño":["spanish"],"enigma":["spanish"],"enlace":["spanish"],"enorme":["spanish"],"enredo":["spanish"],"ensayo":["spanish"],"enseñar":["spanish"],"entero":["spanish"],"entrar":["spanish"],"envase":["spanish"],"envío":["spanish"],"época":["spanish"],"equipo":["spanish"],"erizo":["spanish"],"escala":["spanish"],"escena":["spanish"],"escolar":["spanish"],"escribir":["spanish"],"escudo":["spanish"],"esencia":["spanish"],"esfera":["spanish"],"esfuerzo":["spanish"],"espada":["spanish"],"espejo":["spanish"],"espía":["spanish"],"esposa":["spanish"],"espuma":["spanish"],"esquí":["spanish"],"estar":["spanish"],"este":["spanish"],"estilo":["spanish"],"estufa":["spanish"],"etapa":["spanish"],"eterno":["spanish"],"ética":["spanish"],"etnia":["spanish"],"evadir":["spanish"],"evaluar":["spanish"],"evento":["spanish"],"evitar":["spanish"],"exacto":["spanish"],"examen":["spanish"],"exceso":["spanish"],"excusa":["spanish"],"exento":["spanish"],"exigir":["spanish"],"exilio":["spanish"],"existir":["spanish"],"éxito":["spanish"],"experto":["spanish"],"explicar":["spanish"],"exponer":["spanish"],"extremo":["spanish"],"fábrica":["spanish"],"fábula":["spanish"],"fachada":["spanish"],"fácil":["spanish"],"factor":["spanish"],"faena":["spanish"],"faja":["spanish"],"falda":["spanish"],"fallo":["spanish"],"falso":["spanish"],"faltar":["spanish"],"fama":["spanish"],"familia":["spanish"],"famoso":["spanish"],"faraón":["spanish"],"farmacia":["spanish"],"farol":["spanish"],"farsa":["spanish"],"fase":["spanish"],"fatiga":["spanish"],"fauna":["spanish","turkish"],"favor":["spanish"],"fax":["spanish"],"febrero":["spanish"],"fecha":["spanish"],"feliz":["spanish"],"feo":["spanish"],"feria":["spanish"],"feroz":["spanish"],"fértil":["spanish"],"fervor":["spanish"],"festín":["spanish"],"fiable":["spanish"],"fianza":["spanish"],"fiar":["spanish"],"fibra":["spanish"],"ficción":["spanish"],"ficha":["spanish"],"fideo":["spanish"],"fiebre":["spanish"],"fiel":["spanish"],"fiera":["spanish"],"fiesta":["spanish"],"figura":["spanish"],"fijar":["spanish"],"fijo":["spanish"],"fila":["spanish"],"filete":["spanish"],"filial":["spanish"],"filtro":["spanish"],"fin":["spanish"],"finca":["spanish"],"fingir":["spanish"],"finito":["spanish"],"firma":["spanish"],"flaco":["spanish"],"flauta":["spanish"],"flecha":["spanish"],"flor":["spanish"],"flota":["spanish"],"fluir":["spanish"],"flujo":["spanish"],"flúor":["spanish"],"fobia":["spanish"],"foca":["spanish"],"fogata":["spanish"],"fogón":["spanish"],"folio":["spanish"],"folleto":["spanish"],"fondo":["spanish"],"forma":["spanish"],"forro":["spanish"],"fortuna":["spanish"],"forzar":["spanish"],"fosa":["spanish"],"foto":["spanish"],"fracaso":["spanish"],"frágil":["spanish"],"franja":["spanish"],"frase":["spanish"],"fraude":["spanish"],"freír":["spanish"],"freno":["spanish"],"fresa":["spanish"],"frío":["spanish"],"frito":["spanish"],"fruta":["spanish"],"fuego":["spanish"],"fuente":["spanish"],"fuerza":["spanish"],"fuga":["spanish"],"fumar":["spanish"],"función":["spanish"],"funda":["spanish"],"furgón":["spanish"],"furia":["spanish"],"fusil":["spanish"],"fútbol":["spanish"],"futuro":["spanish"],"gacela":["spanish"],"gafas":["spanish"],"gaita":["spanish"],"gajo":["spanish"],"gala":["spanish"],"galería":["spanish"],"gallo":["spanish"],"gamba":["spanish"],"ganar":["spanish"],"gancho":["spanish"],"ganga":["spanish"],"ganso":["spanish"],"garaje":["spanish"],"garza":["spanish"],"gasolina":["spanish"],"gastar":["spanish"],"gato":["spanish"],"gavilán":["spanish"],"gemelo":["spanish"],"gemir":["spanish"],"gen":["spanish"],"género":["spanish"],"genio":["spanish"],"gente":["spanish"],"geranio":["spanish"],"gerente":["spanish"],"germen":["spanish"],"gesto":["spanish"],"gigante":["spanish"],"gimnasio":["spanish"],"girar":["spanish"],"giro":["spanish"],"glaciar":["spanish"],"globo":["spanish"],"gloria":["spanish"],"gol":["spanish"],"golfo":["spanish"],"goloso":["spanish"],"golpe":["spanish"],"goma":["spanish"],"gordo":["spanish"],"gorila":["spanish"],"gorra":["spanish"],"gota":["spanish"],"goteo":["spanish"],"gozar":["spanish"],"grada":["spanish"],"gráfico":["spanish"],"grano":["spanish"],"grasa":["spanish"],"gratis":["spanish"],"grave":["spanish"],"grieta":["spanish"],"grillo":["spanish"],"gripe":["spanish"],"gris":["spanish"],"grito":["spanish"],"grosor":["spanish"],"grúa":["spanish"],"grueso":["spanish"],"grumo":["spanish"],"grupo":["spanish"],"guante":["spanish"],"guapo":["spanish"],"guardia":["spanish"],"guerra":["spanish"],"guía":["spanish"],"guiño":["spanish"],"guion":["spanish"],"guiso":["spanish"],"guitarra":["spanish"],"gusano":["spanish"],"gustar":["spanish"],"haber":["spanish","turkish"],"hábil":["spanish"],"hablar":["spanish"],"hacer":["spanish"],"hacha":["spanish"],"hada":["spanish"],"hallar":["spanish"],"hamaca":["spanish"],"harina":["spanish"],"haz":["spanish"],"hazaña":["spanish"],"hebilla":["spanish"],"hebra":["spanish"],"hecho":["spanish"],"helado":["spanish"],"helio":["spanish"],"hembra":["spanish"],"herir":["spanish"],"hermano":["spanish"],"héroe":["spanish"],"hervir":["spanish"],"hielo":["spanish"],"hierro":["spanish"],"hígado":["spanish"],"higiene":["spanish"],"hijo":["spanish"],"himno":["spanish"],"historia":["spanish"],"hocico":["spanish"],"hogar":["spanish"],"hoguera":["spanish"],"hoja":["spanish"],"hombre":["spanish"],"hongo":["spanish"],"honor":["spanish"],"honra":["spanish"],"hora":["spanish"],"hormiga":["spanish"],"horno":["spanish"],"hostil":["spanish"],"hoyo":["spanish"],"hueco":["spanish"],"huelga":["spanish"],"huerta":["spanish"],"hueso":["spanish"],"huevo":["spanish"],"huida":["spanish"],"huir":["spanish"],"humano":["spanish"],"húmedo":["spanish"],"humilde":["spanish"],"humo":["spanish"],"hundir":["spanish"],"huracán":["spanish"],"hurto":["spanish"],"icono":["spanish"],"ideal":["spanish"],"idioma":["spanish"],"ídolo":["spanish"],"iglesia":["spanish"],"iglú":["spanish"],"igual":["spanish"],"ilegal":["spanish"],"ilusión":["spanish"],"imagen":["spanish"],"imán":["spanish"],"imitar":["spanish"],"impar":["spanish"],"imperio":["spanish"],"imponer":["spanish"],"impulso":["spanish"],"incapaz":["spanish"],"índice":["spanish"],"inerte":["spanish"],"infiel":["spanish"],"informe":["spanish"],"ingenio":["spanish"],"inicio":["spanish"],"inmenso":["spanish"],"inmune":["spanish"],"innato":["spanish"],"insecto":["spanish"],"instante":["spanish"],"interés":["spanish"],"íntimo":["spanish"],"intuir":["spanish"],"inútil":["spanish"],"invierno":["spanish"],"ira":["spanish"],"iris":["spanish"],"ironía":["spanish"],"isla":["spanish"],"islote":["spanish"],"jabalí":["spanish"],"jabón":["spanish"],"jamón":["spanish"],"jarabe":["spanish"],"jardín":["spanish"],"jarra":["spanish"],"jaula":["spanish"],"jazmín":["spanish"],"jefe":["spanish"],"jeringa":["spanish"],"jinete":["spanish"],"jornada":["spanish"],"joroba":["spanish"],"joven":["spanish"],"joya":["spanish"],"juerga":["spanish"],"jueves":["spanish"],"juez":["spanish"],"jugador":["spanish"],"jugo":["spanish"],"juguete":["spanish"],"juicio":["spanish"],"junco":["spanish"],"jungla":["spanish"],"junio":["spanish"],"juntar":["spanish"],"júpiter":["spanish"],"jurar":["spanish"],"justo":["spanish"],"juvenil":["spanish"],"juzgar":["spanish"],"kilo":["spanish"],"koala":["spanish"],"labio":["spanish"],"lacio":["spanish"],"lacra":["spanish"],"lado":["spanish"],"ladrón":["spanish"],"lagarto":["spanish"],"lágrima":["spanish"],"laguna":["spanish"],"laico":["spanish"],"lamer":["spanish"],"lámina":["spanish"],"lámpara":["spanish"],"lana":["spanish"],"lancha":["spanish"],"langosta":["spanish"],"lanza":["spanish"],"lápiz":["spanish"],"largo":["spanish"],"larva":["spanish"],"lástima":["spanish"],"lata":["spanish"],"látex":["spanish"],"latir":["spanish"],"laurel":["spanish"],"lavar":["spanish"],"lazo":["spanish"],"leal":["spanish"],"lección":["spanish"],"leche":["spanish"],"lector":["spanish"],"leer":["spanish"],"legión":["spanish"],"legumbre":["spanish"],"lejano":["spanish"],"lengua":["spanish"],"lento":["spanish"],"leña":["spanish"],"león":["spanish"],"leopardo":["spanish"],"lesión":["spanish"],"letal":["spanish"],"letra":["spanish"],"leve":["spanish"],"leyenda":["spanish"],"libertad":["spanish"],"libro":["spanish"],"licor":["spanish"],"líder":["spanish"],"lidiar":["spanish"],"lienzo":["spanish"],"liga":["spanish"],"ligero":["spanish"],"lima":["spanish"],"límite":["spanish"],"limón":["spanish"],"limpio":["spanish"],"lince":["spanish"],"lindo":["spanish"],"línea":["spanish"],"lingote":["spanish"],"lino":["spanish"],"linterna":["spanish"],"líquido":["spanish"],"liso":["spanish"],"lista":["spanish"],"litera":["spanish"],"litio":["spanish"],"litro":["spanish"],"llaga":["spanish"],"llama":["spanish"],"llanto":["spanish"],"llave":["spanish"],"llegar":["spanish"],"llenar":["spanish"],"llevar":["spanish"],"llorar":["spanish"],"llover":["spanish"],"lluvia":["spanish"],"lobo":["spanish"],"loción":["spanish"],"loco":["spanish"],"locura":["spanish"],"lógica":["spanish"],"logro":["spanish"],"lombriz":["spanish"],"lomo":["spanish"],"lonja":["spanish"],"lote":["spanish"],"lucha":["spanish"],"lucir":["spanish"],"lugar":["spanish"],"lujo":["spanish"],"luna":["spanish"],"lunes":["spanish"],"lupa":["spanish"],"lustro":["spanish"],"luto":["spanish"],"luz":["spanish"],"maceta":["spanish"],"macho":["spanish"],"madera":["spanish"],"madre":["spanish"],"maduro":["spanish"],"maestro":["spanish"],"mafia":["spanish"],"magia":["spanish"],"mago":["spanish"],"maíz":["spanish"],"maldad":["spanish"],"maleta":["spanish"],"malla":["spanish"],"malo":["spanish"],"mamá":["spanish"],"mambo":["spanish"],"mamut":["spanish"],"manco":["spanish"],"mando":["spanish"],"manejar":["spanish"],"manga":["spanish"],"maniquí":["spanish"],"manjar":["spanish"],"mano":["spanish"],"manso":["spanish"],"manta":["spanish"],"mañana":["spanish"],"mapa":["spanish"],"máquina":["spanish"],"mar":["spanish"],"marco":["spanish"],"marea":["spanish"],"marfil":["spanish"],"margen":["spanish"],"marido":["spanish"],"mármol":["spanish"],"marrón":["spanish"],"martes":["spanish"],"marzo":["spanish"],"masa":["spanish"],"máscara":["spanish"],"masivo":["spanish"],"matar":["spanish"],"materia":["spanish"],"matiz":["spanish"],"matriz":["spanish"],"máximo":["spanish"],"mayor":["spanish"],"mazorca":["spanish"],"mecha":["spanish"],"medalla":["spanish"],"medio":["spanish"],"médula":["spanish"],"mejilla":["spanish"],"mejor":["spanish"],"melena":["spanish"],"melón":["spanish"],"memoria":["spanish"],"menor":["spanish"],"mensaje":["spanish"],"mente":["spanish"],"menú":["spanish"],"mercado":["spanish"],"merengue":["spanish"],"mérito":["spanish"],"mes":["spanish"],"mesón":["spanish"],"meta":["spanish"],"meter":["spanish"],"método":["spanish"],"metro":["spanish"],"mezcla":["spanish"],"miedo":["spanish"],"miel":["spanish"],"miembro":["spanish"],"miga":["spanish"],"mil":["spanish"],"milagro":["spanish"],"militar":["spanish"],"millón":["spanish"],"mimo":["spanish"],"mina":["spanish"],"minero":["spanish"],"mínimo":["spanish"],"minuto":["spanish"],"miope":["spanish"],"mirar":["spanish"],"misa":["spanish"],"miseria":["spanish"],"misil":["spanish"],"mismo":["spanish"],"mitad":["spanish"],"mito":["spanish"],"mochila":["spanish"],"moción":["spanish"],"moda":["spanish"],"modelo":["spanish"],"moho":["spanish"],"mojar":["spanish"],"molde":["spanish"],"moler":["spanish"],"molino":["spanish"],"momento":["spanish"],"momia":["spanish"],"monarca":["spanish"],"moneda":["spanish"],"monja":["spanish"],"monto":["spanish"],"moño":["spanish"],"morada":["spanish"],"morder":["spanish"],"moreno":["spanish"],"morir":["spanish"],"morro":["spanish"],"morsa":["spanish"],"mortal":["spanish"],"mosca":["spanish"],"mostrar":["spanish"],"motivo":["spanish"],"mover":["spanish"],"móvil":["spanish"],"mozo":["spanish"],"mucho":["spanish"],"mudar":["spanish"],"mueble":["spanish"],"muela":["spanish"],"muerte":["spanish"],"muestra":["spanish"],"mugre":["spanish"],"mujer":["spanish"],"mula":["spanish"],"muleta":["spanish"],"multa":["spanish"],"mundo":["spanish"],"muñeca":["spanish"],"mural":["spanish"],"muro":["spanish"],"músculo":["spanish"],"museo":["spanish"],"musgo":["spanish"],"música":["spanish"],"muslo":["spanish"],"nácar":["spanish"],"nación":["spanish"],"nadar":["spanish"],"naipe":["spanish"],"naranja":["spanish"],"nariz":["spanish"],"narrar":["spanish"],"nasal":["spanish"],"natal":["spanish"],"nativo":["spanish"],"natural":["spanish"],"náusea":["spanish"],"naval":["spanish"],"nave":["spanish"],"navidad":["spanish"],"necio":["spanish"],"néctar":["spanish"],"negar":["spanish"],"negocio":["spanish"],"negro":["spanish"],"neón":["spanish"],"nervio":["spanish"],"neto":["spanish"],"neutro":["spanish"],"nevar":["spanish"],"nevera":["spanish"],"nicho":["spanish"],"nido":["spanish"],"niebla":["spanish"],"nieto":["spanish"],"niñez":["spanish"],"niño":["spanish"],"nítido":["spanish"],"nivel":["spanish"],"nobleza":["spanish"],"noche":["spanish"],"nómina":["spanish"],"noria":["spanish"],"norma":["spanish"],"norte":["spanish"],"nota":["spanish"],"noticia":["spanish"],"novato":["spanish"],"novela":["spanish"],"novio":["spanish"],"nube":["spanish"],"nuca":["spanish"],"núcleo":["spanish"],"nudillo":["spanish"],"nudo":["spanish"],"nuera":["spanish"],"nueve":["spanish"],"nuez":["spanish"],"nulo":["spanish"],"número":["spanish"],"nutria":["spanish"],"oasis":["spanish"],"obeso":["spanish"],"obispo":["spanish"],"objeto":["spanish"],"obra":["spanish"],"obrero":["spanish"],"observar":["spanish"],"obtener":["spanish"],"obvio":["spanish"],"oca":["spanish"],"ocaso":["spanish"],"océano":["spanish"],"ochenta":["spanish"],"ocho":["spanish"],"ocio":["spanish"],"ocre":["spanish"],"octavo":["spanish"],"octubre":["spanish"],"oculto":["spanish"],"ocupar":["spanish"],"ocurrir":["spanish"],"odiar":["spanish"],"odio":["spanish"],"odisea":["spanish"],"oeste":["spanish"],"ofensa":["spanish"],"oferta":["spanish"],"oficio":["spanish"],"ofrecer":["spanish"],"ogro":["spanish"],"oído":["spanish"],"oír":["spanish"],"ojo":["spanish"],"ola":["spanish"],"oleada":["spanish"],"olfato":["spanish"],"olivo":["spanish"],"olla":["spanish"],"olmo":["spanish"],"olor":["spanish"],"olvido":["spanish"],"ombligo":["spanish"],"onda":["spanish"],"onza":["spanish"],"opaco":["spanish"],"opción":["spanish"],"ópera":["spanish"],"opinar":["spanish"],"oponer":["spanish"],"optar":["spanish"],"óptica":["spanish"],"opuesto":["spanish"],"oración":["spanish"],"orador":["spanish"],"oral":["spanish","turkish"],"órbita":["spanish"],"orca":["spanish"],"orden":["spanish"],"oreja":["spanish"],"órgano":["spanish"],"orgía":["spanish"],"orgullo":["spanish"],"oriente":["spanish"],"origen":["spanish"],"orilla":["spanish"],"oro":["spanish"],"orquesta":["spanish"],"oruga":["spanish"],"osadía":["spanish"],"oscuro":["spanish"],"osezno":["spanish"],"oso":["spanish"],"ostra":["spanish"],"otoño":["spanish"],"otro":["spanish"],"oveja":["spanish"],"óvulo":["spanish"],"óxido":["spanish"],"oxígeno":["spanish"],"oyente":["spanish"],"ozono":["spanish"],"pacto":["spanish"],"padre":["spanish"],"paella":["spanish"],"página":["spanish"],"pago":["spanish"],"país":["spanish"],"pájaro":["spanish"],"palabra":["spanish"],"palco":["spanish"],"paleta":["spanish"],"pálido":["spanish"],"palma":["spanish"],"paloma":["spanish"],"palpar":["spanish"],"pan":["spanish"],"panal":["spanish"],"pánico":["spanish"],"pantera":["spanish"],"pañuelo":["spanish"],"papá":["spanish"],"papel":["spanish"],"papilla":["spanish"],"paquete":["spanish"],"parar":["spanish"],"parcela":["spanish"],"pared":["spanish"],"parir":["spanish"],"paro":["spanish"],"párpado":["spanish"],"parque":["spanish"],"párrafo":["spanish"],"parte":["spanish"],"pasar":["spanish"],"paseo":["spanish"],"pasión":["spanish"],"paso":["spanish"],"pasta":["spanish"],"pata":["spanish"],"patio":["spanish"],"patria":["spanish"],"pausa":["spanish"],"pauta":["spanish"],"pavo":["spanish"],"payaso":["spanish"],"peatón":["spanish"],"pecado":["spanish"],"pecera":["spanish"],"pecho":["spanish"],"pedal":["spanish","turkish"],"pedir":["spanish"],"pegar":["spanish"],"peine":["spanish"],"pelar":["spanish"],"peldaño":["spanish"],"pelea":["spanish"],"peligro":["spanish"],"pellejo":["spanish"],"pelo":["spanish"],"peluca":["spanish"],"pena":["spanish","turkish"],"pensar":["spanish"],"peñón":["spanish"],"peón":["spanish"],"peor":["spanish"],"pepino":["spanish"],"pequeño":["spanish"],"pera":["spanish"],"percha":["spanish"],"perder":["spanish"],"pereza":["spanish"],"perfil":["spanish"],"perico":["spanish"],"perla":["spanish"],"permiso":["spanish"],"perro":["spanish"],"persona":["spanish"],"pesa":["spanish"],"pesca":["spanish"],"pésimo":["spanish"],"pestaña":["spanish"],"pétalo":["spanish"],"petróleo":["spanish"],"pez":["spanish"],"pezuña":["spanish"],"picar":["spanish"],"pichón":["spanish"],"pie":["spanish"],"piedra":["spanish"],"pierna":["spanish"],"pieza":["spanish"],"pijama":["spanish"],"pilar":["spanish"],"piloto":["spanish"],"pimienta":["spanish"],"pino":["spanish"],"pintor":["spanish"],"pinza":["spanish"],"piña":["spanish"],"piojo":["spanish"],"pipa":["spanish"],"pirata":["spanish"],"pisar":["spanish"],"piscina":["spanish"],"piso":["spanish"],"pista":["spanish"],"pitón":["spanish"],"pizca":["spanish"],"placa":["spanish"],"plan":["spanish"],"plata":["spanish"],"playa":["spanish"],"plaza":["spanish"],"pleito":["spanish"],"pleno":["spanish"],"plomo":["spanish"],"pluma":["spanish"],"plural":["spanish"],"pobre":["spanish"],"poco":["spanish"],"poder":["spanish"],"podio":["spanish"],"poema":["spanish"],"poesía":["spanish"],"poeta":["spanish"],"polen":["spanish","turkish"],"policía":["spanish"],"pollo":["spanish"],"polvo":["spanish"],"pomada":["spanish"],"pomelo":["spanish"],"pomo":["spanish"],"pompa":["spanish","turkish"],"poner":["spanish"],"porción":["spanish"],"portal":["spanish"],"posada":["spanish"],"poseer":["spanish"],"posible":["spanish"],"poste":["spanish"],"potencia":["spanish"],"potro":["spanish"],"pozo":["spanish"],"prado":["spanish"],"precoz":["spanish"],"pregunta":["spanish"],"premio":["spanish"],"prensa":["spanish"],"preso":["spanish"],"previo":["spanish"],"primo":["spanish"],"príncipe":["spanish"],"prisión":["spanish"],"privar":["spanish"],"proa":["spanish"],"probar":["spanish"],"proceso":["spanish"],"producto":["spanish"],"proeza":["spanish"],"profesor":["spanish"],"programa":["spanish"],"prole":["spanish"],"promesa":["spanish"],"pronto":["spanish"],"propio":["spanish"],"próximo":["spanish"],"prueba":["spanish"],"público":["spanish"],"puchero":["spanish"],"pudor":["spanish"],"pueblo":["spanish"],"puerta":["spanish"],"puesto":["spanish"],"pulga":["spanish"],"pulir":["spanish"],"pulmón":["spanish"],"pulpo":["spanish"],"pulso":["spanish"],"puma":["spanish"],"punto":["spanish"],"puñal":["spanish"],"puño":["spanish"],"pupa":["spanish"],"pupila":["spanish"],"puré":["spanish"],"quedar":["spanish"],"queja":["spanish"],"quemar":["spanish"],"querer":["spanish"],"queso":["spanish"],"quieto":["spanish"],"química":["spanish"],"quince":["spanish"],"quitar":["spanish"],"rábano":["spanish"],"rabia":["spanish"],"rabo":["spanish"],"ración":["spanish"],"radical":["spanish"],"raíz":["spanish"],"rama":["spanish"],"rampa":["spanish","turkish"],"rancho":["spanish"],"rango":["spanish"],"rapaz":["spanish"],"rápido":["spanish"],"rapto":["spanish"],"rasgo":["spanish"],"raspa":["spanish"],"rato":["spanish"],"rayo":["spanish"],"raza":["spanish"],"razón":["spanish"],"reacción":["spanish"],"realidad":["spanish"],"rebaño":["spanish"],"rebote":["spanish"],"recaer":["spanish"],"receta":["spanish"],"rechazo":["spanish"],"recoger":["spanish"],"recreo":["spanish"],"recto":["spanish"],"recurso":["spanish"],"red":["spanish"],"redondo":["spanish"],"reducir":["spanish"],"reflejo":["spanish"],"reforma":["spanish"],"refrán":["spanish"],"refugio":["spanish"],"regalo":["spanish"],"regir":["spanish"],"regla":["spanish"],"regreso":["spanish"],"rehén":["spanish"],"reino":["spanish"],"reír":["spanish"],"reja":["spanish"],"relato":["spanish"],"relevo":["spanish"],"relieve":["spanish"],"relleno":["spanish"],"reloj":["spanish"],"remar":["spanish"],"remedio":["spanish"],"remo":["spanish"],"rencor":["spanish"],"rendir":["spanish"],"renta":["spanish"],"reparto":["spanish"],"repetir":["spanish"],"reposo":["spanish"],"reptil":["spanish"],"res":["spanish"],"rescate":["spanish"],"resina":["spanish"],"respeto":["spanish"],"resto":["spanish"],"resumen":["spanish"],"retiro":["spanish"],"retorno":["spanish"],"retrato":["spanish"],"reunir":["spanish"],"revés":["spanish"],"revista":["spanish"],"rey":["spanish"],"rezar":["spanish"],"rico":["spanish"],"riego":["spanish"],"rienda":["spanish"],"riesgo":["spanish"],"rifa":["spanish"],"rígido":["spanish"],"rigor":["spanish"],"rincón":["spanish"],"riñón":["spanish"],"río":["spanish"],"riqueza":["spanish"],"risa":["spanish"],"ritmo":["spanish"],"rito":["spanish"],"rizo":["spanish"],"roble":["spanish"],"roce":["spanish"],"rociar":["spanish"],"rodar":["spanish"],"rodeo":["spanish"],"rodilla":["spanish"],"roer":["spanish"],"rojizo":["spanish"],"rojo":["spanish"],"romero":["spanish"],"romper":["spanish"],"ron":["spanish"],"ronco":["spanish"],"ronda":["spanish"],"ropa":["spanish"],"ropero":["spanish"],"rosa":["spanish"],"rosca":["spanish"],"rostro":["spanish"],"rotar":["spanish"],"rubí":["spanish"],"rubor":["spanish"],"rudo":["spanish"],"rueda":["spanish"],"rugir":["spanish"],"ruido":["spanish"],"ruina":["spanish"],"ruleta":["spanish"],"rulo":["spanish","turkish"],"rumbo":["spanish"],"rumor":["spanish"],"ruptura":["spanish"],"ruta":["spanish"],"rutina":["spanish"],"sábado":["spanish"],"saber":["spanish"],"sabio":["spanish"],"sable":["spanish"],"sacar":["spanish"],"sagaz":["spanish"],"sagrado":["spanish"],"sala":["spanish"],"saldo":["spanish"],"salero":["spanish"],"salir":["spanish"],"salmón":["spanish"],"salón":["spanish"],"salsa":["spanish"],"salto":["spanish"],"salud":["spanish"],"salvar":["spanish"],"samba":["spanish"],"sanción":["spanish"],"sandía":["spanish"],"sanear":["spanish"],"sangre":["spanish"],"sanidad":["spanish"],"sano":["spanish"],"santo":["spanish"],"sapo":["spanish"],"saque":["spanish"],"sardina":["spanish"],"sartén":["spanish"],"sastre":["spanish"],"satán":["spanish"],"sauna":["spanish"],"saxofón":["spanish"],"sección":["spanish"],"seco":["spanish"],"secreto":["spanish"],"secta":["spanish"],"sed":["spanish"],"seguir":["spanish"],"seis":["spanish"],"sello":["spanish"],"selva":["spanish"],"semana":["spanish"],"semilla":["spanish"],"senda":["spanish"],"sensor":["spanish"],"señal":["spanish"],"señor":["spanish"],"separar":["spanish"],"sepia":["spanish"],"sequía":["spanish"],"ser":["spanish"],"serie":["spanish"],"sermón":["spanish"],"servir":["spanish"],"sesenta":["spanish"],"sesión":["spanish"],"seta":["spanish"],"setenta":["spanish"],"severo":["spanish"],"sexo":["spanish"],"sexto":["spanish"],"sidra":["spanish"],"siesta":["spanish"],"siete":["spanish"],"siglo":["spanish"],"signo":["spanish"],"sílaba":["spanish"],"silbar":["spanish"],"silencio":["spanish"],"silla":["spanish"],"símbolo":["spanish"],"simio":["spanish"],"sirena":["spanish"],"sistema":["spanish"],"sitio":["spanish"],"situar":["spanish"],"sobre":["spanish"],"socio":["spanish"],"sodio":["spanish"],"sol":["spanish"],"solapa":["spanish"],"soldado":["spanish"],"soledad":["spanish"],"sólido":["spanish"],"soltar":["spanish"],"solución":["spanish"],"sombra":["spanish"],"sondeo":["spanish"],"sonido":["spanish"],"sonoro":["spanish"],"sonrisa":["spanish"],"sopa":["spanish"],"soplar":["spanish"],"soporte":["spanish"],"sordo":["spanish"],"sorpresa":["spanish"],"sorteo":["spanish"],"sostén":["spanish"],"sótano":["spanish"],"suave":["spanish"],"subir":["spanish"],"suceso":["spanish"],"sudor":["spanish"],"suegra":["spanish"],"suelo":["spanish"],"sueño":["spanish"],"suerte":["spanish"],"sufrir":["spanish"],"sujeto":["spanish"],"sultán":["spanish"],"sumar":["spanish"],"superar":["spanish"],"suplir":["spanish"],"suponer":["spanish"],"supremo":["spanish"],"sur":["spanish"],"surco":["spanish"],"sureño":["spanish"],"surgir":["spanish"],"susto":["spanish"],"sutil":["spanish"],"tabaco":["spanish"],"tabique":["spanish"],"tabla":["spanish"],"tabú":["spanish"],"taco":["spanish"],"tacto":["spanish"],"tajo":["spanish"],"talar":["spanish"],"talco":["spanish"],"talento":["spanish"],"talla":["spanish"],"talón":["spanish"],"tamaño":["spanish"],"tambor":["spanish"],"tango":["spanish"],"tanque":["spanish"],"tapa":["spanish"],"tapete":["spanish"],"tapia":["spanish"],"tapón":["spanish"],"taquilla":["spanish"],"tarde":["spanish"],"tarea":["spanish"],"tarifa":["spanish"],"tarjeta":["spanish"],"tarot":["spanish"],"tarro":["spanish"],"tarta":["spanish"],"tatuaje":["spanish"],"tauro":["spanish"],"taza":["spanish"],"tazón":["spanish"],"teatro":["spanish"],"techo":["spanish"],"tecla":["spanish"],"técnica":["spanish"],"tejado":["spanish"],"tejer":["spanish"],"tejido":["spanish"],"tela":["spanish"],"teléfono":["spanish"],"tema":["spanish"],"temor":["spanish"],"templo":["spanish"],"tenaz":["spanish"],"tender":["spanish"],"tener":["spanish"],"tenis":["spanish"],"tenso":["spanish"],"teoría":["spanish"],"terapia":["spanish"],"terco":["spanish"],"término":["spanish"],"ternura":["spanish"],"terror":["spanish"],"tesis":["spanish"],"tesoro":["spanish"],"testigo":["spanish"],"tetera":["spanish"],"texto":["spanish"],"tez":["spanish"],"tibio":["spanish"],"tiburón":["spanish"],"tiempo":["spanish"],"tienda":["spanish"],"tierra":["spanish"],"tieso":["spanish"],"tigre":["spanish"],"tijera":["spanish"],"tilde":["spanish"],"timbre":["spanish"],"tímido":["spanish"],"timo":["spanish"],"tinta":["spanish"],"tío":["spanish"],"típico":["spanish"],"tipo":["spanish"],"tira":["spanish"],"tirón":["spanish"],"titán":["spanish"],"títere":["spanish"],"título":["spanish"],"tiza":["spanish"],"toalla":["spanish"],"tobillo":["spanish"],"tocar":["spanish"],"tocino":["spanish"],"todo":["spanish"],"toga":["spanish"],"toldo":["spanish"],"tomar":["spanish","turkish"],"tono":["spanish"],"tonto":["spanish"],"topar":["spanish"],"tope":["spanish"],"toque":["spanish"],"tórax":["spanish"],"torero":["spanish"],"tormenta":["spanish"],"torneo":["spanish"],"toro":["spanish"],"torpedo":["spanish"],"torre":["spanish"],"torso":["spanish"],"tortuga":["spanish"],"tos":["spanish"],"tosco":["spanish"],"toser":["spanish"],"tóxico":["spanish"],"trabajo":["spanish"],"tractor":["spanish"],"traer":["spanish"],"tráfico":["spanish"],"trago":["spanish"],"traje":["spanish"],"tramo":["spanish"],"trance":["spanish"],"trato":["spanish"],"trauma":["spanish"],"trazar":["spanish"],"trébol":["spanish"],"tregua":["spanish"],"treinta":["spanish"],"tren":["spanish"],"trepar":["spanish"],"tres":["spanish"],"tribu":["spanish"],"trigo":["spanish"],"tripa":["spanish"],"triste":["spanish"],"triunfo":["spanish"],"trofeo":["spanish"],"trompa":["spanish"],"tronco":["spanish"],"tropa":["spanish"],"trote":["spanish"],"trozo":["spanish"],"truco":["spanish"],"trueno":["spanish"],"trufa":["spanish"],"tubería":["spanish"],"tubo":["spanish"],"tuerto":["spanish"],"tumba":["spanish"],"tumor":["spanish"],"túnel":["spanish"],"túnica":["spanish"],"turbina":["spanish"],"turismo":["spanish"],"turno":["spanish"],"tutor":["spanish"],"ubicar":["spanish"],"úlcera":["spanish"],"umbral":["spanish"],"unidad":["spanish"],"unir":["spanish"],"universo":["spanish"],"uno":["spanish"],"untar":["spanish"],"uña":["spanish"],"urbano":["spanish"],"urbe":["spanish"],"urgente":["spanish"],"urna":["spanish"],"usar":["spanish"],"usuario":["spanish"],"útil":["spanish"],"utopía":["spanish"],"uva":["spanish"],"vaca":["spanish"],"vacío":["spanish"],"vacuna":["spanish"],"vagar":["spanish"],"vago":["spanish"],"vaina":["spanish"],"vajilla":["spanish"],"vale":["spanish"],"válido":["spanish"],"valle":["spanish"],"valor":["spanish"],"válvula":["spanish"],"vampiro":["spanish"],"vara":["spanish"],"variar":["spanish"],"varón":["spanish"],"vaso":["spanish"],"vecino":["spanish"],"vector":["spanish"],"vehículo":["spanish"],"veinte":["spanish"],"vejez":["spanish"],"vela":["spanish"],"velero":["spanish"],"veloz":["spanish"],"vena":["spanish"],"vencer":["spanish"],"venda":["spanish"],"veneno":["spanish"],"vengar":["spanish"],"venir":["spanish"],"venta":["spanish"],"venus":["spanish"],"ver":["spanish"],"verano":["spanish"],"verbo":["spanish"],"verde":["spanish"],"vereda":["spanish"],"verja":["spanish"],"verso":["spanish"],"verter":["spanish"],"vía":["spanish"],"viaje":["spanish"],"vibrar":["spanish"],"vicio":["spanish"],"víctima":["spanish"],"vida":["spanish"],"vídeo":["spanish"],"vidrio":["spanish"],"viejo":["spanish"],"viernes":["spanish"],"vigor":["spanish"],"vil":["spanish"],"villa":["spanish"],"vinagre":["spanish"],"vino":["spanish"],"viñedo":["spanish"],"violín":["spanish"],"viral":["spanish"],"virgo":["spanish"],"virtud":["spanish"],"visor":["spanish"],"víspera":["spanish"],"vista":["spanish"],"vitamina":["spanish"],"viudo":["spanish"],"vivaz":["spanish"],"vivero":["spanish"],"vivir":["spanish"],"vivo":["spanish"],"volcán":["spanish"],"volumen":["spanish"],"volver":["spanish"],"voraz":["spanish"],"votar":["spanish"],"voto":["spanish"],"voz":["spanish"],"vuelo":["spanish"],"vulgar":["spanish"],"yacer":["spanish"],"yate":["spanish"],"yegua":["spanish"],"yema":["spanish"],"yerno":["spanish"],"yeso":["spanish"],"yodo":["spanish"],"yoga":["spanish"],"yogur":["spanish"],"zafiro":["spanish"],"zanja":["spanish"],"zapato":["spanish"],"zarza":["spanish"],"zona":["spanish"],"zorro":["spanish"],"zumo":["spanish"],"zurdo":["spanish"],"abajur":["turkish"],"abaküs":["turkish"],"abartı":["turkish"],"abdal":["turkish"],"abdest":["turkish"],"abiye":["turkish"],"abluka":["turkish"],"abone":["turkish"],"absorbe":["turkish"],"absürt":["turkish"],"acayip":["turkish"],"acele":["turkish"],"acemi":["turkish"],"açıkgöz":["turkish"],"adalet":["turkish"],"adam":["turkish"],"adezyon":["turkish"],"adisyon":["turkish"],"adliye":["turkish"],"adres":["turkish"],"afacan":["turkish"],"afili":["turkish"],"afiş":["turkish"],"afiyet":["turkish"],"aforizm":["turkish"],"afra":["turkish"],"ağaç":["turkish"],"ağır":["turkish"],"ahbap":["turkish"],"ahkam":["turkish"],"ahlak":["turkish"],"ahtapot":["turkish"],"aidat":["turkish"],"aile":["turkish"],"ajan":["turkish"],"akademi":["turkish"],"akarsu":["turkish"],"akbaş":["turkish"],"akciğer":["turkish"],"akdeniz":["turkish"],"akıbet":["turkish"],"akıl":["turkish"],"akıntı":["turkish"],"akide":["turkish"],"akrep":["turkish"],"akrobasi":["turkish"],"aksiyon":["turkish"],"akşam":["turkish"],"aktif":["turkish"],"aktör":["turkish"],"aktris":["turkish"],"akustik":["turkish"],"alaca":["turkish"],"albüm":["turkish"],"alçak":["turkish"],"aldanma":["turkish"],"aleni":["turkish"],"alet":["turkish"],"alfabe":["turkish"],"algılama":["turkish"],"alıngan":["turkish"],"alkış":["turkish"],"alkol":["turkish"],"alpay":["turkish"],"alperen":["turkish"],"altın":["turkish"],"altüst":["turkish"],"altyapı":["turkish"],"alyuvar":["turkish"],"amade":["turkish"],"amatör":["turkish"],"amazon":["turkish"],"ambalaj":["turkish"],"amblem":["turkish"],"ambulans":["turkish"],"amca":["turkish"],"amel":["turkish"],"amir":["turkish"],"amiyane":["turkish"],"amorti":["turkish"],"ampul":["turkish"],"anadolu":["turkish"],"anahtar":["turkish"],"anakonda":["turkish"],"anaokul":["turkish"],"anapara":["turkish"],"anarşi":["turkish"],"anatomi":["turkish"],"anayasa":["turkish"],"anekdot":["turkish"],"anestezi":["turkish"],"angaje":["turkish"],"anka":["turkish"],"anket":["turkish"],"anlamlı":["turkish"],"anne":["turkish"],"anomali":["turkish"],"anonim":["turkish"],"anten":["turkish"],"antlaşma":["turkish"],"apse":["turkish"],"araba":["turkish"],"aracı":["turkish"],"araf":["turkish"],"arbede":["turkish"],"arda":["turkish"],"arefe":["turkish"],"argo":["turkish"],"argüman":["turkish"],"arkadaş":["turkish"],"armoni":["turkish"],"arsa":["turkish"],"arsız":["turkish"],"artı":["turkish"],"aruz":["turkish"],"asansör":["turkish"],"asayiş":["turkish"],"asgari":["turkish"],"asil":["turkish"],"asker":["turkish"],"askı":["turkish"],"aslan":["turkish"],"asosyal":["turkish"],"astsubay":["turkish"],"asya":["turkish"],"aşçı":["turkish"],"aşırı":["turkish"],"aşure":["turkish"],"atabey":["turkish"],"ataman":["turkish"],"ateş":["turkish"],"atmaca":["turkish"],"atmosfer":["turkish"],"atölye":["turkish"],"avcı":["turkish"],"avdet":["turkish"],"avize":["turkish"],"avlu":["turkish"],"avokado":["turkish"],"avrupa":["turkish"],"avukat":["turkish"],"ayaz":["turkish"],"ayçiçeği":["turkish"],"aydın":["turkish"],"aygıt":["turkish"],"ayna":["turkish"],"ayran":["turkish"],"ayrıntı":["turkish"],"azim":["turkish"],"baca":["turkish"],"bagaj":["turkish"],"bağlantı":["turkish"],"bahadır":["turkish"],"bahçe":["turkish"],"baki":["turkish"],"bakkal":["turkish"],"baklava":["turkish"],"bakteri":["turkish"],"balçık":["turkish"],"balina":["turkish"],"balo":["turkish"],"balta":["turkish"],"bant":["turkish"],"banyo":["turkish"],"bardak":["turkish"],"barış":["turkish"],"başbuğ":["turkish"],"başıboş":["turkish"],"başkan":["turkish"],"başlık":["turkish"],"bavul":["turkish"],"bayındır":["turkish"],"baykuş":["turkish"],"bazlama":["turkish"],"bedel":["turkish"],"begüm":["turkish"],"bekçi":["turkish"],"bekle":["turkish"],"belge":["turkish"],"belki":["turkish"],"bencil":["turkish"],"benek":["turkish"],"bengi":["turkish"],"berjer":["turkish"],"berk":["turkish"],"berrak":["turkish"],"beşik":["turkish"],"beyin":["turkish"],"beyoğlu":["turkish"],"bıçak":["turkish"],"biberiye":["turkish"],"bidon":["turkish"],"bihaber":["turkish"],"bikini":["turkish"],"bilezik":["turkish"],"bilinç":["turkish"],"bilye":["turkish"],"bina":["turkish"],"binbaşı":["turkish"],"binyıl":["turkish"],"bisiklet":["turkish"],"bisküvi":["turkish"],"bitki":["turkish"],"bizzat":["turkish"],"bodrum":["turkish"],"boğaz":["turkish"],"bohça":["turkish"],"boncuk":["turkish"],"bonfile":["turkish"],"borsa":["turkish"],"boru":["turkish"],"bostan":["turkish"],"boşboğaz":["turkish"],"botanik":["turkish"],"boya":["turkish"],"boykot":["turkish"],"boynuz":["turkish"],"bozgun":["turkish"],"bozkır":["turkish"],"bölüm":["turkish"],"börek":["turkish"],"buçuk":["turkish"],"bugün":["turkish"],"buğday":["turkish"],"buhar":["turkish"],"buhran":["turkish"],"bulvar":["turkish"],"buram":["turkish"],"burçak":["turkish"],"burs":["turkish"],"burun":["turkish"],"buzdağı":["turkish"],"buzkıran":["turkish"],"bücür":["turkish"],"büfe":["turkish"],"bülten":["turkish"],"bütçe":["turkish"],"bütün":["turkish"],"büyük":["turkish"],"cacık":["turkish"],"cadı":["turkish"],"cahil":["turkish"],"cambaz":["turkish"],"canhıraş":["turkish"],"casus":["turkish"],"cazibe":["turkish"],"cehalet":["turkish"],"cehennem":["turkish"],"ceket":["turkish"],"cemre":["turkish"],"cenin":["turkish"],"cennet":["turkish"],"cepken":["turkish"],"cerrah":["turkish"],"cesur":["turkish"],"cetvel":["turkish"],"cevher":["turkish"],"ceylan":["turkish"],"cılız":["turkish"],"cıva":["turkish"],"cilt":["turkish"],"cisim":["turkish"],"ciyak":["turkish"],"coğrafya":["turkish"],"cömert":["turkish"],"cumba":["turkish"],"cüzdan":["turkish"],"çabucak":["turkish"],"çadır":["turkish"],"çağdaş":["turkish"],"çağlayan":["turkish"],"çağrı":["turkish"],"çakmak":["turkish"],"çalışkan":["turkish"],"çamaşır":["turkish"],"çapa":["turkish"],"çaput":["turkish"],"çarık":["turkish"],"çarpan":["turkish"],"çarşaf":["turkish"],"çayhane":["turkish"],"çekirdek":["turkish"],"çelebi":["turkish"],"çember":["turkish"],"çenet":["turkish"],"çengel":["turkish"],"çerçeve":["turkish"],"çerez":["turkish"],"çeşit":["turkish"],"çeşme":["turkish"],"çete":["turkish"],"çevre":["turkish"],"çeyiz":["turkish"],"çeyrek":["turkish"],"çığır":["turkish"],"çılgın":["turkish"],"çıngırak":["turkish"],"çift":["turkish"],"çiğdem":["turkish"],"çikolata":["turkish"],"çilek":["turkish"],"çimen":["turkish"],"çivi":["turkish"],"çoban":["turkish"],"çocuk":["turkish"],"çokgen":["turkish"],"çomak":["turkish"],"çorba":["turkish"],"çözelti":["turkish"],"çubuk":["turkish"],"çukur":["turkish"],"çuval":["turkish"],"çürük":["turkish"],"dağbaşı":["turkish"],"dağılım":["turkish"],"daktilo":["turkish"],"daldırış":["turkish"],"dalga":["turkish"],"dalkavuk":["turkish"],"damak":["turkish"],"damıtma":["turkish"],"damla":["turkish"],"dana":["turkish"],"dandik":["turkish"],"danışman":["turkish"],"daniska":["turkish"],"dantel":["turkish"],"dargeçit":["turkish"],"darphane":["turkish"],"davet":["turkish"],"dayı":["turkish"],"defter":["turkish"],"değer":["turkish"],"değirmen":["turkish"],"dehşet":["turkish"],"delgeç":["turkish"],"demir":["turkish"],"deneyim":["turkish"],"denge":["turkish"],"depo":["turkish"],"deprem":["turkish"],"derdest":["turkish"],"dere":["turkish"],"derhal":["turkish"],"derman":["turkish"],"dernek":["turkish"],"derviş":["turkish"],"desen":["turkish"],"destan":["turkish"],"dışarı":["turkish"],"dışbükey":["turkish"],"dijital":["turkish"],"dikbaşlı":["turkish"],"dilekçe":["turkish"],"dimağ":["turkish"],"dinamik":["turkish"],"dindar":["turkish"],"dinleme":["turkish"],"dinozor":["turkish"],"dipçik":["turkish"],"dipnot":["turkish"],"direniş":["turkish"],"dirsek":["turkish"],"disiplin":["turkish"],"divriği":["turkish"],"dizüstü":["turkish"],"dobra":["turkish"],"dodurga":["turkish"],"doğalgaz":["turkish"],"doküman":["turkish"],"dolap":["turkish"],"donanım":["turkish"],"dondurma":["turkish"],"donör":["turkish"],"doruk":["turkish"],"dosdoğru":["turkish"],"dost":["turkish"],"dosya":["turkish"],"dozer":["turkish"],"döküm":["turkish"],"dönence":["turkish"],"dörtyol":["turkish"],"dövme":["turkish"],"dram":["turkish"],"dublaj":["turkish"],"durum":["turkish"],"duvak":["turkish"],"duyarga":["turkish"],"duyma":["turkish"],"duyuru":["turkish"],"düğme":["turkish"],"düğüm":["turkish"],"dükkan":["turkish"],"dünür":["turkish"],"düpedüz":["turkish"],"dürbün":["turkish"],"düşünür":["turkish"],"düzayak":["turkish"],"düzeltme":["turkish"],"ebeveyn":["turkish"],"ebru":["turkish"],"ecel":["turkish"],"ecnebi":["turkish"],"ecza":["turkish"],"edat":["turkish"],"edilgen":["turkish"],"efendi":["turkish"],"efor":["turkish"],"efsane":["turkish"],"egemen":["turkish"],"egzersiz":["turkish"],"eğrelti":["turkish"],"ekarte":["turkish"],"ekip":["turkish"],"eklem":["turkish"],"ekmek":["turkish"],"ekol":["turkish"],"ekonomi":["turkish"],"ekose":["turkish"],"ekran":["turkish"],"ekvator":["turkish"],"elaman":["turkish"],"elastik":["turkish"],"elbet":["turkish"],"elbise":["turkish"],"elçi":["turkish"],"eldiven":["turkish"],"elebaşı":["turkish"],"eleştiri":["turkish"],"elma":["turkish"],"eloğlu":["turkish"],"elveda":["turkish"],"emare":["turkish"],"emekçi":["turkish"],"emisyon":["turkish"],"emniyet":["turkish"],"empati":["turkish"],"emsal":["turkish"],"emzik":["turkish"],"endüstri":["turkish"],"enerji":["turkish"],"engebe":["turkish"],"enişte":["turkish"],"enkaz":["turkish"],"entari":["turkish"],"entegre":["turkish"],"entrika":["turkish"],"enzim":["turkish"],"erdem":["turkish"],"ergen":["turkish"],"erguvan":["turkish"],"erkek":["turkish"],"erozyon":["turkish"],"ertesi":["turkish"],"erzak":["turkish"],"esaret":["turkish"],"esenlik":["turkish"],"eser":["turkish"],"eski":["turkish"],"esnek":["turkish"],"eşarp":["turkish"],"eşofman":["turkish"],"eşraf":["turkish"],"eşya":["turkish"],"eşzaman":["turkish"],"etik":["turkish"],"etken":["turkish"],"etkinlik":["turkish"],"etüt":["turkish"],"evet":["turkish"],"evire":["turkish"],"evrak":["turkish"],"evrim":["turkish"],"eyalet":["turkish"],"eyvah":["turkish"],"ezber":["turkish"],"fabrika":["turkish"],"fanus":["turkish"],"fason":["turkish"],"fasulye":["turkish"],"fatih":["turkish"],"fatura":["turkish"],"fayans":["turkish"],"fayton":["turkish"],"fazıl":["turkish"],"fazilet":["turkish"],"felsefe":["turkish"],"fener":["turkish"],"feribot":["turkish"],"fersah":["turkish"],"fesih":["turkish"],"feveran":["turkish"],"feza":["turkish"],"fıçı":["turkish"],"fıldır":["turkish"],"fındık":["turkish"],"fırça":["turkish"],"fırsat":["turkish"],"fırtına":["turkish"],"fıtık":["turkish"],"fidan":["turkish"],"fidye":["turkish"],"figür":["turkish"],"fihrist":["turkish"],"fikir":["turkish"],"fildişi":["turkish"],"filtre":["turkish"],"fincan":["turkish"],"firuze":["turkish"],"fitil":["turkish"],"fiyaka":["turkish"],"fizik":["turkish"],"flaş":["turkish"],"flüt":["turkish"],"fosil":["turkish"],"fren":["turkish"],"fukara":["turkish"],"futbol":["turkish"],"garabet":["turkish"],"gariban":["turkish"],"garnitür":["turkish"],"gazi":["turkish"],"gece":["turkish"],"gedik":["turkish"],"gelenek":["turkish"],"gelin":["turkish"],"gemi":["turkish"],"genç":["turkish"],"geniş":["turkish"],"geometri":["turkish"],"gerçek":["turkish"],"gevrek":["turkish"],"gezegen":["turkish"],"gezgin":["turkish"],"geziyolu":["turkish"],"gıcık":["turkish"],"gıda":["turkish"],"gıybet":["turkish"],"girdap":["turkish"],"girişim":["turkish"],"gitar":["turkish"],"giyecek":["turkish"],"giysi":["turkish"],"gizem":["turkish"],"gofret":["turkish"],"goril":["turkish"],"göbek":["turkish"],"göçebe":["turkish"],"göğüs":["turkish"],"gökdelen":["turkish"],"gökmen":["turkish"],"gökyüzü":["turkish"],"gölge":["turkish"],"gömlek":["turkish"],"gönül":["turkish"],"görenek":["turkish"],"görkemli":["turkish"],"görsel":["turkish"],"gösteri":["turkish"],"gövde":["turkish"],"gözaltı":["turkish"],"gözcü":["turkish"],"gözdağı":["turkish"],"gözleme":["turkish"],"gözyaşı":["turkish"],"grup":["turkish"],"gurbet":["turkish"],"gusül":["turkish"],"gübre":["turkish"],"güfte":["turkish"],"gümüş":["turkish"],"günaydın":["turkish"],"güncel":["turkish"],"gündüz":["turkish"],"güneş":["turkish"],"günyüzü":["turkish"],"gürbüz":["turkish"],"güvercin":["turkish"],"güzel":["turkish"],"hacamat":["turkish"],"hacim":["turkish"],"hademe":["turkish"],"hafız":["turkish"],"hafriyat":["turkish"],"hafta":["turkish"],"hakan":["turkish"],"hakem":["turkish"],"hakikat":["turkish"],"haksever":["turkish"],"halı":["turkish"],"hançer":["turkish"],"hane":["turkish"],"hapis":["turkish"],"hapşırık":["turkish"],"harf":["turkish"],"haseki":["turkish"],"hasret":["turkish"],"hatun":["turkish"],"havuç":["turkish"],"haylaz":["turkish"],"haysiyet":["turkish"],"hayvan":["turkish"],"hedef":["turkish"],"hemen":["turkish"],"hemfikir":["turkish"],"hendek":["turkish"],"hepsi":["turkish"],"hergele":["turkish"],"herhangi":["turkish"],"hesap":["turkish"],"heyecan":["turkish"],"heykel":["turkish"],"hezimet":["turkish"],"hıçkırık":["turkish"],"hızölçer":["turkish"],"hicviye":["turkish"],"hikaye":["turkish"],"hikmet":["turkish"],"hile":["turkish"],"hisse":["turkish"],"hobi":["turkish"],"hoca":["turkish"],"horlama":["turkish"],"hoşbeş":["turkish"],"hoşgörü":["turkish"],"hoyrat":["turkish"],"hörgüç":["turkish"],"höyük":["turkish"],"hudut":["turkish"],"hukuk":["turkish"],"hunhar":["turkish"],"hurda":["turkish"],"huysuz":["turkish"],"huzur":["turkish"],"hücum":["turkish"],"hükümet":["turkish"],"hünkar":["turkish"],"hüviyet":["turkish"],"ırmak":["turkish"],"ısıölçer":["turkish"],"ısıtıcı":["turkish"],"ıspanak":["turkish"],"ısrar":["turkish"],"ışıldak":["turkish"],"ızdırap":["turkish"],"ızgara":["turkish"],"ibadet":["turkish"],"icat":["turkish"],"içbükey":["turkish"],"içecek":["turkish"],"içgüdü":["turkish"],"içsel":["turkish"],"idman":["turkish"],"iftihar":["turkish"],"iğne":["turkish"],"ihanet":["turkish"],"ihbar":["turkish"],"ihdas":["turkish"],"ihmal":["turkish"],"ihracat":["turkish"],"ihsan":["turkish"],"ikilem":["turkish"],"ikindi":["turkish"],"ikircik":["turkish"],"iklim":["turkish"],"iksir":["turkish"],"iktibas":["turkish"],"ilaç":["turkish"],"ilçe":["turkish"],"ileri":["turkish"],"iletişim":["turkish"],"ilgi":["turkish"],"ilhak":["turkish"],"ilkbahar":["turkish"],"ilkokul":["turkish"],"ilmek":["turkish"],"imkan":["turkish"],"imleç":["turkish"],"imsak":["turkish"],"imtihan":["turkish"],"imza":["turkish"],"ince":["turkish"],"inkar":["turkish"],"inşa":["turkish"],"ipek":["turkish"],"ipucu":["turkish"],"irade":["turkish"],"irfan":["turkish"],"irmik":["turkish"],"isabet":["turkish"],"iskele":["turkish"],"israf":["turkish"],"isyan":["turkish"],"işçi":["turkish"],"işgal":["turkish"],"işgüzar":["turkish"],"işlem":["turkish"],"itibar":["turkish"],"itiraf":["turkish"],"ivedi":["turkish"],"ivme":["turkish"],"iyileşme":["turkish"],"iyimser":["turkish"],"izbandut":["turkish"],"izci":["turkish"],"izdiham":["turkish"],"izin":["turkish"],"jakoben":["turkish"],"jandarma":["turkish"],"jargon":["turkish"],"kabadayı":["turkish"],"kablo":["turkish"],"kabus":["turkish"],"kaçamak":["turkish"],"kadeh":["turkish"],"kadın":["turkish"],"kadraj":["turkish"],"kafa":["turkish"],"kafkas":["turkish"],"kağıt":["turkish"],"kağnı":["turkish"],"kahkaha":["turkish"],"kahraman":["turkish"],"kahvaltı":["turkish"],"kakül":["turkish"],"kaldırım":["turkish"],"kale":["turkish"],"kalibre":["turkish"],"kalkan":["turkish"],"kalpak":["turkish"],"kamış":["turkish"],"kamyon":["turkish"],"kanat":["turkish"],"kandaş":["turkish"],"kanepe":["turkish"],"kanser":["turkish"],"kanun":["turkish"],"kaos":["turkish"],"kapı":["turkish"],"kaplıca":["turkish"],"kaptan":["turkish"],"karanlık":["turkish"],"kardeş":["turkish"],"karga":["turkish"],"karınca":["turkish"],"karmaşa":["turkish"],"karşıt":["turkish"],"kasırga":["turkish"],"kask":["turkish"],"kasvet":["turkish"],"katkı":["turkish"],"katman":["turkish"],"kavram":["turkish"],"kaygan":["turkish"],"kaynakça":["turkish"],"kayyum":["turkish"],"kedi":["turkish"],"kehanet":["turkish"],"kekik":["turkish"],"kelebek":["turkish"],"kenar":["turkish"],"kerkenez":["turkish"],"kerpiç":["turkish"],"kesirli":["turkish"],"kesmece":["turkish"],"kestane":["turkish"],"keşkek":["turkish"],"ketçap":["turkish"],"keyfiyet":["turkish"],"kıble":["turkish"],"kıdemli":["turkish"],"kılavuz":["turkish"],"kılçık":["turkish"],"kılıf":["turkish"],"kıraç":["turkish"],"kırmızı":["turkish"],"kırsal":["turkish"],"kısayol":["turkish"],"kısım":["turkish"],"kıskanç":["turkish"],"kısmet":["turkish"],"kışla":["turkish"],"kıvanç":["turkish"],"kıvılcım":["turkish"],"kıvrık":["turkish"],"kıyafet":["turkish"],"kıymetli":["turkish"],"kızak":["turkish"],"kızılcık":["turkish"],"kibar":["turkish"],"kinaye":["turkish"],"kira":["turkish"],"kiremit":["turkish"],"kirli":["turkish"],"kirpik":["turkish"],"kişisel":["turkish"],"kitap":["turkish"],"koçbaşı":["turkish"],"kodaman":["turkish"],"koğuş":["turkish"],"kokteyl":["turkish"],"kolaycı":["turkish"],"kolbastı":["turkish"],"kolonya":["turkish"],"koltuk":["turkish"],"kolye":["turkish"],"kombine":["turkish"],"komedyen":["turkish"],"komiser":["turkish"],"komposto":["turkish"],"komşu":["turkish"],"komuta":["turkish"],"konak":["turkish"],"konfor":["turkish"],"koni":["turkish"],"konsül":["turkish"],"kopya":["turkish"],"korkusuz":["turkish"],"korna":["turkish"],"korse":["turkish"],"korunak":["turkish"],"korvet":["turkish"],"kostüm":["turkish"],"koşul":["turkish"],"koyu":["turkish"],"kozmik":["turkish"],"köfte":["turkish"],"kökensel":["turkish"],"köprücük":["turkish"],"köpük":["turkish"],"kördüğüm":["turkish"],"körfez":["turkish"],"köstebek":["turkish"],"köşegen":["turkish"],"kötü":["turkish"],"kravat":["turkish"],"kriter":["turkish"],"kuantum":["turkish"],"kudurma":["turkish"],"kuluçka":["turkish"],"kulübe":["turkish"],"kumanya":["turkish"],"kumbara":["turkish"],"kumlu":["turkish"],"kumpir":["turkish"],"kumral":["turkish"],"kundura":["turkish"],"kupa":["turkish"],"kupkuru":["turkish"],"kuramsal":["turkish"],"kurbağa":["turkish"],"kurdele":["turkish"],"kurgu":["turkish"],"kurmay":["turkish"],"kurşun":["turkish"],"kurtuluş":["turkish"],"kurultay":["turkish"],"kurye":["turkish"],"kusursuz":["turkish"],"kuşak":["turkish"],"kuşbaşı":["turkish"],"kuşkulu":["turkish"],"kutlama":["turkish"],"kutsal":["turkish"],"kutup":["turkish"],"kuver":["turkish"],"kuyruk":["turkish"],"kuzey":["turkish"],"kuzgun":["turkish"],"küçük":["turkish"],"külçe":["turkish"],"külfet":["turkish"],"külliye":["turkish"],"kültürel":["turkish"],"kümes":["turkish"],"künefe":["turkish"],"küresel":["turkish"],"kütle":["turkish"],"lahana":["turkish"],"lahmacun":["turkish"],"lamba":["turkish"],"lansman":["turkish"],"lavaş":["turkish"],"layık":["turkish"],"leğen":["turkish"],"levent":["turkish"],"leziz":["turkish"],"lezzet":["turkish"],"lider":["turkish"],"likide":["turkish"],"liman":["turkish"],"liste":["turkish"],"litre":["turkish"],"liyakat":["turkish"],"lodos":["turkish"],"lokanta":["turkish"],"lokman":["turkish"],"lokum":["turkish"],"lunapark":["turkish"],"lütfen":["turkish"],"lüzum":["turkish"],"nokta":["turkish"],"mabet":["turkish"],"macera":["turkish"],"macun":["turkish"],"madalya":["turkish"],"madde":["turkish"],"madem":["turkish"],"mağara":["turkish"],"mağdur":["turkish"],"mağfiret":["turkish"],"mağlup":["turkish"],"mahalle":["turkish"],"mahcup":["turkish"],"mahir":["turkish"],"mahkeme":["turkish"],"mahlas":["turkish"],"mahrum":["turkish"],"mahsul":["turkish"],"makas":["turkish"],"makbuz":["turkish"],"makine":["turkish"],"makro":["turkish"],"maksat":["turkish"],"makul":["turkish"],"maliye":["turkish"],"manav":["turkish"],"mangal":["turkish"],"manidar":["turkish"],"manken":["turkish"],"mantık":["turkish"],"manzara":["turkish"],"mareşal":["turkish"],"margarin":["turkish"],"marifet":["turkish"],"marmelat":["turkish"],"masaüstü":["turkish"],"masmavi":["turkish"],"masraf":["turkish"],"masum":["turkish"],"matah":["turkish"],"materyal":["turkish"],"matrak":["turkish"],"maval":["turkish"],"mavra":["turkish"],"maydanoz":["turkish"],"mayhoş":["turkish"],"maytap":["turkish"],"mazbata":["turkish"],"mazeret":["turkish"],"mazlum":["turkish"],"mazot":["turkish"],"mazur":["turkish"],"meblağ":["turkish"],"mebus":["turkish"],"mecaz":["turkish"],"mecbur":["turkish"],"meclis":["turkish"],"mecmua":["turkish"],"mecnun":["turkish"],"meçhul":["turkish"],"medeni":["turkish"],"mehtap":["turkish"],"mekanik":["turkish"],"melodi":["turkish"],"meltem":["turkish"],"memur":["turkish"],"mendil":["turkish"],"menekşe":["turkish"],"menteşe":["turkish"],"meraklı":["turkish"],"mercek":["turkish"],"merdiven":["turkish"],"merhaba":["turkish"],"merinos":["turkish"],"merkez":["turkish"],"mermi":["turkish"],"mert":["turkish"],"mesafe":["turkish"],"mesele":["turkish"],"mesken":["turkish"],"meslek":["turkish"],"meşale":["turkish"],"meşgul":["turkish"],"meşhur":["turkish"],"metafor":["turkish"],"metin":["turkish"],"metre":["turkish"],"mevcut":["turkish"],"mevkidaş":["turkish"],"meydan":["turkish"],"meyil":["turkish"],"meyve":["turkish"],"meziyet":["turkish"],"mezun":["turkish"],"mıknatıs":["turkish"],"mısra":["turkish"],"mızıka":["turkish"],"miğfer":["turkish"],"mihrak":["turkish"],"miktar":["turkish"],"milat":["turkish"],"milli":["turkish"],"mimar":["turkish"],"minare":["turkish"],"mineral":["turkish"],"minik":["turkish"],"minyon":["turkish"],"mirliva":["turkish"],"misafir":["turkish"],"miskin":["turkish"],"miting":["turkish"],"miyop":["turkish"],"mizah":["turkish"],"mobilya":["turkish"],"monitör":["turkish"],"morötesi":["turkish"],"motive":["turkish"],"mozaik":["turkish"],"muavin":["turkish"],"mucize":["turkish"],"muhafız":["turkish"],"muhteşem":["turkish"],"mukayese":["turkish"],"mumya":["turkish"],"musluk":["turkish"],"muşamba":["turkish"],"mutabık":["turkish"],"mutfak":["turkish"],"mutlu":["turkish"],"muzaffer":["turkish"],"muzdarip":["turkish"],"mübarek":["turkish"],"mücadele":["turkish"],"müdür":["turkish"],"müfredat":["turkish"],"müftü":["turkish"],"mühendis":["turkish"],"mühim":["turkish"],"mühlet":["turkish"],"mükemmel":["turkish"],"mülk":["turkish"],"mümkün":["turkish"],"mümtaz":["turkish"],"müsrif":["turkish"],"müstesna":["turkish"],"müşahit":["turkish"],"müşteri":["turkish"],"mütercim":["turkish"],"müthiş":["turkish"],"müze":["turkish"],"müzik":["turkish"],"nabız":["turkish"],"nadas":["turkish"],"nadir":["turkish"],"nahoş":["turkish"],"nakarat":["turkish"],"nakış":["turkish"],"nalbur":["turkish"],"namlu":["turkish"],"namus":["turkish"],"nankör":["turkish"],"nargile":["turkish"],"narkoz":["turkish"],"nasıl":["turkish"],"nasip":["turkish"],"naylon":["turkish"],"nazar":["turkish"],"nazım":["turkish"],"nazik":["turkish"],"neden":["turkish"],"nefes":["turkish"],"negatif":["turkish"],"neon":["turkish"],"neptün":["turkish"],"nerede":["turkish"],"nesil":["turkish"],"nesnel":["turkish"],"neşeli":["turkish"],"netice":["turkish"],"nevresim":["turkish"],"neyse":["turkish"],"neyzen":["turkish"],"nezaket":["turkish"],"nezih":["turkish"],"nezle":["turkish"],"nicel":["turkish"],"nilüfer":["turkish"],"nimet":["turkish"],"nisan":["turkish"],"nispet":["turkish"],"nitekim":["turkish"],"nizam":["turkish"],"nohut":["turkish"],"noksan":["turkish"],"nostalji":["turkish"],"noter":["turkish"],"nöbet":["turkish"],"numara":["turkish"],"numune":["turkish"],"nutuk":["turkish"],"nüfus":["turkish"],"obabaşı":["turkish"],"obez":["turkish"],"obje":["turkish"],"ocak":["turkish"],"odun":["turkish"],"ofansif":["turkish"],"ofis":["turkish"],"oğlak":["turkish"],"oğuz":["turkish"],"okçu":["turkish"],"oklava":["turkish"],"oksijen":["turkish"],"okul":["turkish"],"okumuş":["turkish"],"okutman":["turkish"],"okuyucu":["turkish"],"okyanus":["turkish"],"olağan":["turkish"],"olanak":["turkish"],"olası":["turkish"],"olay":["turkish"],"olgun":["turkish"],"olimpik":["turkish"],"olumlu":["turkish"],"omlet":["turkish"],"omurga":["turkish"],"onarım":["turkish"],"onursal":["turkish"],"optik":["turkish"],"orantı":["turkish"],"ordu":["turkish"],"organik":["turkish"],"orijin":["turkish"],"orkide":["turkish"],"orman":["turkish"],"orta":["turkish"],"oruç":["turkish"],"otağ":["turkish"],"otantik":["turkish"],"otel":["turkish"],"otoban":["turkish"],"otogar":["turkish"],"otomobil":["turkish"],"otonom":["turkish"],"otopark":["turkish"],"otorite":["turkish"],"otoyol":["turkish"],"oturum":["turkish"],"oyuk":["turkish"],"oyuncak":["turkish"],"ozan":["turkish"],"ödeme":["turkish"],"ödenek":["turkish"],"ödev":["turkish"],"ödül":["turkish"],"ödünç":["turkish"],"öfke":["turkish"],"öğlen":["turkish"],"öğrenci":["turkish"],"öğün":["turkish"],"öğütücü":["turkish"],"öksürük":["turkish"],"ölçme":["turkish"],"ölçü":["turkish"],"ölümsüz":["turkish"],"ömür":["turkish"],"önayak":["turkish"],"öncü":["turkish"],"önder":["turkish"],"önem":["turkish"],"önerge":["turkish"],"öngörü":["turkish"],"önlük":["turkish"],"önsezi":["turkish"],"öpücük":["turkish"],"ördek":["turkish"],"örgü":["turkish"],"örtbas":["turkish"],"örtme":["turkish"],"örtü":["turkish"],"örümcek":["turkish"],"örüntü":["turkish"],"öteberi":["turkish"],"öteki":["turkish"],"övünç":["turkish"],"öykü":["turkish"],"öyleyse":["turkish"],"özçekim":["turkish"],"özdeyiş":["turkish"],"özel":["turkish"],"özenti":["turkish"],"özerk":["turkish"],"özgürlük":["turkish"],"özlem":["turkish"],"özlü":["turkish"],"özne":["turkish"],"özsever":["turkish"],"özümseme":["turkish"],"özür":["turkish"],"özveri":["turkish"],"pabuç":["turkish"],"padişah":["turkish"],"palamut":["turkish"],"palmiye":["turkish"],"palto":["turkish"],"palyaço":["turkish"],"pamuk":["turkish"],"panayır":["turkish"],"pancar":["turkish"],"panik":["turkish"],"panjur":["turkish"],"pankart":["turkish"],"pano":["turkish"],"pansuman":["turkish"],"pantolon":["turkish"],"panzehir":["turkish"],"papatya":["turkish"],"papyon":["turkish"],"paraşüt":["turkish"],"parça":["turkish"],"pardösü":["turkish"],"parfüm":["turkish"],"parıltı":["turkish"],"parkur":["turkish"],"parmak":["turkish"],"parodi":["turkish"],"parsel":["turkish"],"partner":["turkish"],"pasaport":["turkish"],"pasif":["turkish"],"paskalya":["turkish"],"pastırma":["turkish"],"paşa":["turkish"],"patates":["turkish"],"paten":["turkish"],"patika":["turkish"],"patlıcan":["turkish"],"patolog":["turkish"],"payanda":["turkish"],"paydaş":["turkish"],"payidar":["turkish"],"paylaşma":["turkish"],"paytak":["turkish"],"peçete":["turkish"],"peder":["turkish"],"pehlivan":["turkish"],"pekala":["turkish"],"pekmez":["turkish"],"pelerin":["turkish"],"pelikan":["turkish"],"pelüş":["turkish"],"pembe":["turkish"],"pencere":["turkish"],"pense":["turkish"],"perçin":["turkish"],"perde":["turkish"],"pergel":["turkish"],"perişan":["turkish"],"peron":["turkish"],"personel":["turkish"],"perşembe":["turkish"],"peruk":["turkish"],"pervane":["turkish"],"pespaye":["turkish"],"pestil":["turkish"],"peşin":["turkish"],"petek":["turkish"],"petrol":["turkish"],"petunya":["turkish"],"peynir":["turkish"],"peyzaj":["turkish"],"pınar":["turkish"],"pırasa":["turkish"],"pırlanta":["turkish"],"pide":["turkish"],"pikap":["turkish"],"pilav":["turkish"],"piliç":["turkish"],"pipet":["turkish"],"pipo":["turkish"],"piramit":["turkish"],"pirinç":["turkish"],"pirzola":["turkish"],"pist":["turkish"],"pişik":["turkish"],"pişman":["turkish"],"piyasa":["turkish"],"piyes":["turkish"],"plaj":["turkish"],"plaket":["turkish"],"planlama":["turkish"],"platform":["turkish"],"plazma":["turkish"],"podyum":["turkish"],"poğaça":["turkish"],"polat":["turkish"],"politika":["turkish"],"popüler":["turkish"],"porselen":["turkish"],"portakal":["turkish"],"poster":["turkish"],"poşet":["turkish"],"poyraz":["turkish"],"pozitif":["turkish"],"pranga":["turkish"],"pratik":["turkish"],"prenses":["turkish"],"prim":["turkish"],"profil":["turkish"],"proje":["turkish"],"protokol":["turkish"],"puan":["turkish"],"pudra":["turkish"],"pusula":["turkish"],"püre":["turkish"],"pürüz":["turkish"],"püstül":["turkish"],"püsür":["turkish"],"racon":["turkish"],"radikal":["turkish"],"radyo":["turkish"],"rafadan":["turkish"],"rafine":["turkish"],"rağbet":["turkish"],"rahat":["turkish"],"rahle":["turkish"],"rakam":["turkish"],"raket":["turkish"],"rakip":["turkish"],"rakun":["turkish"],"ralli":["turkish"],"randevu":["turkish"],"ranza":["turkish"],"rapor":["turkish"],"rastgele":["turkish"],"rasyonel":["turkish"],"razı":["turkish"],"realite":["turkish"],"reçine":["turkish"],"refah":["turkish"],"referans":["turkish"],"refik":["turkish"],"rehber":["turkish"],"rehin":["turkish"],"reis":["turkish"],"rekabet":["turkish"],"reklam":["turkish"],"rekor":["turkish"],"rektör":["turkish"],"renk":["turkish"],"resim":["turkish"],"resmen":["turkish"],"restoran":["turkish"],"retorik":["turkish"],"revaç":["turkish"],"reyon":["turkish"],"rezalet":["turkish"],"rezerv":["turkish"],"rezil":["turkish"],"rıhtım":["turkish"],"rıza":["turkish"],"ritim":["turkish"],"ritüel":["turkish"],"rivayet":["turkish"],"roman":["turkish"],"rozet":["turkish"],"röportaj":["turkish"],"rötar":["turkish"],"ruble":["turkish"],"ruhban":["turkish"],"ruhsat":["turkish"],"rulet":["turkish"],"runik":["turkish"],"rutin":["turkish"],"rutubet":["turkish"],"rüşvet":["turkish"],"rütbe":["turkish"],"rüya":["turkish"],"rüzgar":["turkish"],"sabah":["turkish"],"sabıka":["turkish"],"sabit":["turkish"],"sabun":["turkish"],"saçma":["turkish"],"sade":["turkish"],"sadık":["turkish"],"safahat":["turkish"],"safdil":["turkish"],"safkan":["turkish"],"sağanak":["turkish"],"sağduyu":["turkish"],"sağlam":["turkish"],"saha":["turkish"],"sahiden":["turkish"],"sahne":["turkish"],"sakal":["turkish"],"sakız":["turkish"],"sakin":["turkish"],"saklama":["turkish"],"saksağan":["turkish"],"salamura":["turkish"],"salça":["turkish"],"salgı":["turkish"],"salınım":["turkish"],"salkım":["turkish"],"saltanat":["turkish"],"sanatçı":["turkish"],"sancak":["turkish"],"sandalye":["turkish"],"saniye":["turkish"],"saplantı":["turkish"],"sapsız":["turkish"],"saray":["turkish"],"sarışın":["turkish"],"sarkık":["turkish"],"sarmaşık":["turkish"],"satır":["turkish"],"savaşım":["turkish"],"savunma":["turkish"],"saydam":["turkish"],"sayfa":["turkish"],"saygın":["turkish"],"sayısal":["turkish"],"sebep":["turkish"],"seçenek":["turkish"],"seçim":["turkish"],"seçkin":["turkish"],"seçmen":["turkish"],"sedir":["turkish"],"sedye":["turkish"],"sefer":["turkish"],"sehpa":["turkish"],"sekizgen":["turkish"],"selektör":["turkish"],"selvi":["turkish"],"semavi":["turkish"],"sembol":["turkish"],"seminer":["turkish"],"senaryo":["turkish"],"sendika":["turkish"],"senkron":["turkish"],"sensör":["turkish"],"sentez":["turkish"],"sepet":["turkish"],"seramik":["turkish"],"serbest":["turkish"],"serdar":["turkish"],"seremoni":["turkish"],"sergi":["turkish"],"serhat":["turkish"],"serin":["turkish"],"sermaye":["turkish"],"serpuş":["turkish"],"sersem":["turkish"],"serüven":["turkish"],"sesli":["turkish"],"sesteş":["turkish"],"sevap":["turkish"],"seviye":["turkish"],"seyahat":["turkish"],"seyirci":["turkish"],"sezon":["turkish"],"sıcak":["turkish"],"sıfat":["turkish"],"sıhhi":["turkish"],"sınanma":["turkish"],"sınır":["turkish"],"sıradan":["turkish"],"sırdaş":["turkish"],"sırma":["turkish"],"sırtüstü":["turkish"],"sızgıt":["turkish"],"siftah":["turkish"],"sigorta":["turkish"],"sihirbaz":["turkish"],"silah":["turkish"],"silecek":["turkish"],"silindir":["turkish"],"simetri":["turkish"],"simge":["turkish"],"simit":["turkish"],"sincap":["turkish"],"sindirim":["turkish"],"sinema":["turkish"],"sinirli":["turkish"],"sipariş":["turkish"],"sirke":["turkish"],"siroz":["turkish"],"sistem":["turkish"],"sivilce":["turkish"],"siyasi":["turkish"],"soba":["turkish"],"sofra":["turkish"],"soğuk":["turkish"],"sohbet":["turkish"],"sokak":["turkish"],"solfej":["turkish"],"solunum":["turkish"],"somut":["turkish"],"sonbahar":["turkish"],"sonraki":["turkish"],"sonsuz":["turkish"],"sorunsuz":["turkish"],"sosyete":["turkish"],"soyağacı":["turkish"],"soydaş":["turkish"],"soygun":["turkish"],"soytarı":["turkish"],"söğüş":["turkish"],"sömürge":["turkish"],"sönük":["turkish"],"söylem":["turkish"],"sözcük":["turkish"],"sözde":["turkish"],"spatula":["turkish"],"spektrum":["turkish"],"spiker":["turkish"],"sporcu":["turkish"],"sprey":["turkish"],"stabil":["turkish"],"statü":["turkish"],"stok":["turkish"],"stopaj":["turkish"],"strateji":["turkish"],"subay":["turkish"],"sucuk":["turkish"],"suçüstü":["turkish"],"suhulet":["turkish"],"sulama":["turkish"],"sungur":["turkish"],"sunucu":["turkish"],"surat":["turkish"],"susam":["turkish"],"suskun":["turkish"],"sükse":["turkish"],"sükut":["turkish"],"sülale":["turkish"],"sünger":["turkish"],"süpürge":["turkish"],"sürahi":["turkish"],"süreç":["turkish"],"sürgün":["turkish"],"sürüm":["turkish"],"süsleme":["turkish"],"sütanne":["turkish"],"sütlaç":["turkish"],"sütun":["turkish"],"süvari":["turkish"],"şahane":["turkish"],"şahbaz":["turkish"],"şahit":["turkish"],"şahsiyet":["turkish"],"şakıma":["turkish"],"şaklaban":["turkish"],"şakrak":["turkish"],"şamar":["turkish"],"şampiyon":["turkish"],"şanslı":["turkish"],"şantiye":["turkish"],"şapka":["turkish"],"şarkıcı":["turkish"],"şartname":["turkish"],"şaşırma":["turkish"],"şaşkın":["turkish"],"şatafat":["turkish"],"şayet":["turkish"],"şebeke":["turkish"],"şefkat":["turkish"],"şeftali":["turkish"],"şehir":["turkish"],"şehvet":["turkish"],"şeker":["turkish"],"şekil":["turkish"],"şelale":["turkish"],"şema":["turkish"],"şemsiye":["turkish"],"şerbet":["turkish"],"şeref":["turkish"],"şerit":["turkish"],"şımarık":["turkish"],"şıpıdık":["turkish"],"şifre":["turkish"],"şimdi":["turkish"],"şimşek":["turkish"],"şipşak":["turkish"],"şirin":["turkish"],"şişe":["turkish"],"şişirme":["turkish"],"şofben":["turkish"],"şöhret":["turkish"],"şölen":["turkish"],"şüphe":["turkish"],"tabaka":["turkish"],"tabure":["turkish"],"tadilat":["turkish"],"taharet":["turkish"],"tahıl":["turkish"],"tahkim":["turkish"],"tahlil":["turkish"],"tahmin":["turkish"],"tahrifat":["turkish"],"tahsilat":["turkish"],"tahta":["turkish"],"taklit":["turkish"],"takoz":["turkish"],"taksici":["turkish"],"taktik":["turkish"],"takvim":["turkish"],"talebe":["turkish"],"talip":["turkish"],"tamamen":["turkish"],"tamirci":["turkish"],"tamtakır":["turkish"],"tandır":["turkish"],"tanecik":["turkish"],"tanıtım":["turkish"],"tanrı":["turkish"],"tansiyon":["turkish"],"tapan":["turkish"],"tapınak":["turkish"],"taptaze":["turkish"],"tapu":["turkish"],"tarafgir":["turkish"],"tarhana":["turkish"],"tarım":["turkish"],"tarih":["turkish"],"tarla":["turkish"],"tartak":["turkish"],"tarumar":["turkish"],"tasarım":["turkish"],"tasdik":["turkish"],"taslak":["turkish"],"tastamam":["turkish"],"taşeron":["turkish"],"taşınmaz":["turkish"],"taşra":["turkish"],"tatava":["turkish"],"tatbikat":["turkish"],"tatil":["turkish"],"tatlı":["turkish"],"tavsiye":["turkish"],"tavşan":["turkish"],"tavuk":["turkish"],"taze":["turkish"],"taziye":["turkish"],"tazminat":["turkish"],"tebeşir":["turkish"],"tebrik":["turkish"],"tecrübe":["turkish"],"teçhizat":["turkish"],"tedarik":["turkish"],"tedbir":["turkish"],"teftiş":["turkish"],"teğet":["turkish"],"teğmen":["turkish"],"tehdit":["turkish"],"tehlike":["turkish"],"tekdüze":["turkish"],"tekerlek":["turkish"],"tekme":["turkish"],"teknik":["turkish"],"tekrar":["turkish"],"telef":["turkish"],"telsiz":["turkish"],"telve":["turkish"],"temas":["turkish"],"tembel":["turkish"],"temiz":["turkish"],"temkin":["turkish"],"temsilci":["turkish"],"tendon":["turkish"],"teneke":["turkish"],"tenha":["turkish"],"tenkit":["turkish"],"tepegöz":["turkish"],"tepki":["turkish"],"terazi":["turkish"],"terbiye":["turkish"],"tercih":["turkish"],"tereyağı":["turkish"],"terfi":["turkish"],"terim":["turkish"],"terminal":["turkish"],"tersane":["turkish"],"tertip":["turkish"],"tesadüf":["turkish"],"tescil":["turkish"],"tesir":["turkish"],"teslimat":["turkish"],"tespit":["turkish"],"testere":["turkish"],"teşekkür":["turkish"],"teşhir":["turkish"],"teşrif":["turkish"],"teşvik":["turkish"],"teyze":["turkish"],"tezahür":["turkish"],"tezgah":["turkish"],"tıbbi":["turkish"],"tıkaç":["turkish"],"tıkışık":["turkish"],"tıknaz":["turkish"],"tılsım":["turkish"],"tıpkı":["turkish"],"tıraş":["turkish"],"tırışka":["turkish"],"tırmanış":["turkish"],"tırnak":["turkish"],"tırpan":["turkish"],"tıslama":["turkish"],"ticaret":["turkish"],"tilki":["turkish"],"tiryaki":["turkish"],"titreşim":["turkish"],"tohum":["turkish"],"tokat":["turkish"],"tolere":["turkish"],"tombak":["turkish"],"tomurcuk":["turkish"],"topaç":["turkish"],"toplum":["turkish"],"toprak":["turkish"],"toptan":["turkish"],"toraman":["turkish"],"torpido":["turkish"],"tortu":["turkish"],"tosbağa":["turkish"],"toynak":["turkish"],"tören":["turkish"],"trafik":["turkish"],"trajedi":["turkish"],"tramvay":["turkish"],"tribün":["turkish"],"triko":["turkish"],"tugay":["turkish"],"tuğla":["turkish"],"tuğrul":["turkish"],"tuhaf":["turkish"],"tulumba":["turkish"],"tunç":["turkish"],"turan":["turkish"],"turkuaz":["turkish"],"turnusol":["turkish"],"turşu":["turkish"],"turuncu":["turkish"],"tutanak":["turkish"],"tutkal":["turkish"],"tutsak":["turkish"],"tutum":["turkish"],"tuyuğ":["turkish"],"tuzlu":["turkish"],"tüccar":["turkish"],"tüfek":["turkish"],"tükenmez":["turkish"],"tülbent":["turkish"],"tümleç":["turkish"],"tünel":["turkish"],"türbin":["turkish"],"türev":["turkish"],"türk":["turkish"],"tüzük":["turkish"],"ucube":["turkish"],"ucuz":["turkish"],"uçak":["turkish"],"uçurtma":["turkish"],"ufuk":["turkish"],"uğrak":["turkish"],"uğur":["turkish"],"ukala":["turkish"],"ulaşım":["turkish"],"ulema":["turkish"],"ulus":["turkish"],"ulvi":["turkish"],"umursama":["turkish"],"umut":["turkish"],"unutkan":["turkish"],"uslu":["turkish"],"ustabaşı":["turkish"],"ustura":["turkish"],"usul":["turkish"],"utangaç":["turkish"],"uyanık":["turkish"],"uyarı":["turkish"],"uydu":["turkish"],"uygar":["turkish"],"uygulama":["turkish"],"uykusuz":["turkish"],"uysal":["turkish"],"uyuşma":["turkish"],"uzantı":["turkish"],"uzay":["turkish"],"uzgören":["turkish"],"uzlaşma":["turkish"],"uzman":["turkish"],"uzun":["turkish"],"ücra":["turkish"],"ücret":["turkish"],"üçbudak":["turkish"],"üçgen":["turkish"],"üçkağıt":["turkish"],"üçleme":["turkish"],"üfürük":["turkish"],"ülke":["turkish"],"ümit":["turkish"],"üniforma":["turkish"],"ünite":["turkish"],"ünlem":["turkish"],"üretken":["turkish"],"ürün":["turkish"],"üslup":["turkish"],"üstel":["turkish"],"üstün":["turkish"],"üşengeç":["turkish"],"üşüme":["turkish"],"ütopya":["turkish"],"üvey":["turkish"],"üzengi":["turkish"],"üzgün":["turkish"],"üzüm":["turkish"],"vaka":["turkish"],"vakfiye":["turkish"],"vakıf":["turkish"],"vakit":["turkish"],"vakum":["turkish"],"vapur":["turkish"],"varil":["turkish"],"varlık":["turkish"],"varsayım":["turkish"],"varyemez":["turkish"],"vasıta":["turkish"],"vasiyet":["turkish"],"vatandaş":["turkish"],"vazife":["turkish"],"vazo":["turkish"],"veciz":["turkish"],"vefa":["turkish"],"vehim":["turkish"],"veliaht":["turkish"],"veresiye":["turkish"],"verimli":["turkish"],"verkaç":["turkish"],"vernik":["turkish"],"vertigo":["turkish"],"vesait":["turkish"],"vesika":["turkish"],"vestiyer":["turkish"],"veznedar":["turkish"],"vicdan":["turkish"],"vilayet":["turkish"],"virane":["turkish"],"virgül":["turkish"],"vişne":["turkish"],"vites":["turkish"],"vokal":["turkish"],"volkan":["turkish"],"vurma":["turkish"],"vurucu":["turkish"],"vücut":["turkish"],"yabancı":["turkish"],"yabgu":["turkish"],"yağış":["turkish"],"yağlı":["turkish"],"yağmur":["turkish"],"yakamoz":["turkish"],"yakın":["turkish"],"yaklaşık":["turkish"],"yalçın":["turkish"],"yalıtım":["turkish"],"yaman":["turkish"],"yanardağ":["turkish"],"yangın":["turkish"],"yanıt":["turkish"],"yankı":["turkish"],"yanlış":["turkish"],"yansıma":["turkish"],"yapay":["turkish"],"yapboz":["turkish"],"yapımcı":["turkish"],"yaprak":["turkish"],"yaratık":["turkish"],"yarbay":["turkish"],"yardım":["turkish"],"yargıç":["turkish"],"yarıçap":["turkish"],"yasemin":["turkish"],"yastık":["turkish"],"yaşam":["turkish"],"yatak":["turkish"],"yatırım":["turkish"],"yavru":["turkish"],"yaygara":["turkish"],"yayıncı":["turkish"],"yayla":["turkish"],"yazılım":["turkish"],"yekpare":["turkish"],"yekvücut":["turkish"],"yelkovan":["turkish"],"yelpaze":["turkish"],"yemek":["turkish"],"yemiş":["turkish"],"yengeç":["turkish"],"yeniçeri":["turkish"],"yeraltı":["turkish"],"yerküre":["turkish"],"yerleşke":["turkish"],"yeryüzü":["turkish"],"yeşil":["turkish"],"yetenek":["turkish"],"yetkili":["turkish"],"yığınak":["turkish"],"yıkama":["turkish"],"yılbaşı":["turkish"],"yıldırım":["turkish"],"yılkı":["turkish"],"yılmaz":["turkish"],"yırtıcı":["turkish"],"yiğit":["turkish"],"yoğurt":["turkish"],"yokuş":["turkish"],"yolcu":["turkish"],"yoldaş":["turkish"],"yolgeçen":["turkish"],"yolkesen":["turkish"],"yolüstü":["turkish"],"yordam":["turkish"],"yorgan":["turkish"],"yorumcu":["turkish"],"yosun":["turkish"],"yöndeş":["turkish"],"yönetim":["turkish"],"yönlü":["turkish"],"yöntem":["turkish"],"yöresel":["turkish"],"yörünge":["turkish"],"yufka":["turkish"],"yukarı":["turkish"],"yumruk":["turkish"],"yumurta":["turkish"],"yuvarlak":["turkish"],"yücelme":["turkish"],"yükçeker":["turkish"],"yüklem":["turkish"],"yüksek":["turkish"],"yürek":["turkish"],"yürütme":["turkish"],"yüzde":["turkish"],"yüzeysel":["turkish"],"yüzgeç":["turkish"],"yüzüstü":["turkish"],"yüzyıl":["turkish"],"zabıta":["turkish"],"zafer":["turkish"],"zahmet":["turkish"],"zambak":["turkish"],"zaptiye":["turkish"],"zarafet":["turkish"],"zaruret":["turkish"],"zeka":["turkish"],"zekice":["turkish"],"zemberek":["turkish"],"zemin":["turkish"],"zencefil":["turkish"],"zeplin":["turkish"],"zeytin":["turkish"],"zıbın":["turkish"],"zılgıt":["turkish"],"zımbırtı":["turkish"],"zımpara":["turkish"],"zıpkın":["turkish"],"zigon":["turkish"],"zihinsel":["turkish"],"zihniyet":["turkish"],"zincir":["turkish"],"zindan":["turkish"],"zirzop":["turkish"],"ziyaret":["turkish"],"ziynet":["turkish"],"zoraki":["turkish"],"zorlu":["turkish"],"zorunlu":["turkish"],"züğürt":["turkish"],"zümre":["turkish"]}["abacate","abaixo","abalar","abater","abduzir","abelha","aberto","abismo","abotoar","abranger","abreviar","abrigar","abrupto","absinto","absoluto","absurdo","abutre","acabado","acalmar","acampar","acanhar","acaso","aceitar","acelerar","acenar","acervo","acessar","acetona","achatar","acidez","acima","acionado","acirrar","aclamar","aclive","acolhida","acomodar","acoplar","acordar","acumular","acusador","adaptar","adega","adentro","adepto","adequar","aderente","adesivo","adeus","adiante","aditivo","adjetivo","adjunto","admirar","adorar","adquirir","adubo","adverso","advogado","aeronave","afastar","aferir","afetivo","afinador","afivelar","aflito","afluente","afrontar","agachar","agarrar","agasalho","agenciar","agilizar","agiota","agitado","agora","agradar","agreste","agrupar","aguardar","agulha","ajoelhar","ajudar","ajustar","alameda","alarme","alastrar","alavanca","albergue","albino","alcatra","aldeia","alecrim","alegria","alertar","alface","alfinete","algum","alheio","aliar","alicate","alienar","alinhar","aliviar","almofada","alocar","alpiste","alterar","altitude","alucinar","alugar","aluno","alusivo","alvo","amaciar","amador","amarelo","amassar","ambas","ambiente","ameixa","amenizar","amido","amistoso","amizade","amolador","amontoar","amoroso","amostra","amparar","ampliar","ampola","anagrama","analisar","anarquia","anatomia","andaime","anel","anexo","angular","animar","anjo","anomalia","anotado","ansioso","anterior","anuidade","anunciar","anzol","apagador","apalpar","apanhado","apego","apelido","apertada","apesar","apetite","apito","aplauso","aplicada","apoio","apontar","aposta","aprendiz","aprovar","aquecer","arame","aranha","arara","arcada","ardente","areia","arejar","arenito","aresta","argiloso","argola","arma","arquivo","arraial","arrebate","arriscar","arroba","arrumar","arsenal","arterial","artigo","arvoredo","asfaltar","asilado","aspirar","assador","assinar","assoalho","assunto","astral","atacado","atadura","atalho","atarefar","atear","atender","aterro","ateu","atingir","atirador","ativo","atoleiro","atracar","atrevido","atriz","atual","atum","auditor","aumentar","aura","aurora","autismo","autoria","autuar","avaliar","avante","avaria","avental","avesso","aviador","avisar","avulso","axila","azarar","azedo","azeite","azulejo","babar","babosa","bacalhau","bacharel","bacia","bagagem","baiano","bailar","baioneta","bairro","baixista","bajular","baleia","baliza","balsa","banal","bandeira","banho","banir","banquete","barato","barbado","baronesa","barraca","barulho","baseado","bastante","batata","batedor","batida","batom","batucar","baunilha","beber","beijo","beirada","beisebol","beldade","beleza","belga","beliscar","bendito","bengala","benzer","berimbau","berlinda","berro","besouro","bexiga","bezerro","bico","bicudo","bienal","bifocal","bifurcar","bigorna","bilhete","bimestre","bimotor","biologia","biombo","biosfera","bipolar","birrento","biscoito","bisneto","bispo","bissexto","bitola","bizarro","blindado","bloco","bloquear","boato","bobagem","bocado","bocejo","bochecha","boicotar","bolada","boletim","bolha","bolo","bombeiro","bonde","boneco","bonita","borbulha","borda","boreal","borracha","bovino","boxeador","branco","brasa","braveza","breu","briga","brilho","brincar","broa","brochura","bronzear","broto","bruxo","bucha","budismo","bufar","bule","buraco","busca","busto","buzina","cabana","cabelo","cabide","cabo","cabrito","cacau","cacetada","cachorro","cacique","cadastro","cadeado","cafezal","caiaque","caipira","caixote","cajado","caju","calafrio","calcular","caldeira","calibrar","calmante","calota","camada","cambista","camisa","camomila","campanha","camuflar","canavial","cancelar","caneta","canguru","canhoto","canivete","canoa","cansado","cantar","canudo","capacho","capela","capinar","capotar","capricho","captador","capuz","caracol","carbono","cardeal","careca","carimbar","carneiro","carpete","carreira","cartaz","carvalho","casaco","casca","casebre","castelo","casulo","catarata","cativar","caule","causador","cautelar","cavalo","caverna","cebola","cedilha","cegonha","celebrar","celular","cenoura","censo","centeio","cercar","cerrado","certeiro","cerveja","cetim","cevada","chacota","chaleira","chamado","chapada","charme","chatice","chave","chefe","chegada","cheiro","cheque","chicote","chifre","chinelo","chocalho","chover","chumbo","chutar","chuva","cicatriz","ciclone","cidade","cidreira","ciente","cigana","cimento","cinto","cinza","ciranda","circuito","cirurgia","citar","clareza","clero","clicar","clone","clube","coado","coagir","cobaia","cobertor","cobrar","cocada","coelho","coentro","coeso","cogumelo","coibir","coifa","coiote","colar","coleira","colher","colidir","colmeia","colono","coluna","comando","combinar","comentar","comitiva","comover","complexo","comum","concha","condor","conectar","confuso","congelar","conhecer","conjugar","consumir","contrato","convite","cooperar","copeiro","copiador","copo","coquetel","coragem","cordial","corneta","coronha","corporal","correio","cortejo","coruja","corvo","cosseno","costela","cotonete","couro","couve","covil","cozinha","cratera","cravo","creche","credor","creme","crer","crespo","criada","criminal","crioulo","crise","criticar","crosta","crua","cruzeiro","cubano","cueca","cuidado","cujo","culatra","culminar","culpar","cultura","cumprir","cunhado","cupido","curativo","curral","cursar","curto","cuspir","custear","cutelo","damasco","datar","debater","debitar","deboche","debulhar","decalque","decimal","declive","decote","decretar","dedal","dedicado","deduzir","defesa","defumar","degelo","degrau","degustar","deitado","deixar","delator","delegado","delinear","delonga","demanda","demitir","demolido","dentista","depenado","depilar","depois","depressa","depurar","deriva","derramar","desafio","desbotar","descanso","desenho","desfiado","desgaste","desigual","deslize","desmamar","desova","despesa","destaque","desviar","detalhar","detentor","detonar","detrito","deusa","dever","devido","devotado","dezena","diagrama","dialeto","didata","difuso","digitar","dilatado","diluente","diminuir","dinastia","dinheiro","diocese","direto","discreta","disfarce","disparo","disquete","dissipar","distante","ditador","diurno","diverso","divisor","divulgar","dizer","dobrador","dolorido","domador","dominado","donativo","donzela","dormente","dorsal","dosagem","dourado","doutor","drenagem","drible","drogaria","duelar","duende","dueto","duplo","duquesa","durante","duvidoso","eclodir","ecoar","ecologia","edificar","edital","educado","efeito","efetivar","ejetar","elaborar","eleger","eleitor","elenco","elevador","eliminar","elogiar","embargo","embolado","embrulho","embutido","emenda","emergir","emissor","empatia","empenho","empinado","empolgar","emprego","empurrar","emulador","encaixe","encenado","enchente","encontro","endeusar","endossar","enfaixar","enfeite","enfim","engajado","engenho","englobar","engomado","engraxar","enguia","enjoar","enlatar","enquanto","enraizar","enrolado","enrugar","ensaio","enseada","ensino","ensopado","entanto","enteado","entidade","entortar","entrada","entulho","envergar","enviado","envolver","enxame","enxerto","enxofre","enxuto","epiderme","equipar","ereto","erguido","errata","erva","ervilha","esbanjar","esbelto","escama","escola","escrita","escuta","esfinge","esfolar","esfregar","esfumado","esgrima","esmalte","espanto","espelho","espiga","esponja","espreita","espumar","esquerda","estaca","esteira","esticar","estofado","estrela","estudo","esvaziar","etanol","etiqueta","euforia","europeu","evacuar","evaporar","evasivo","eventual","evidente","evoluir","exagero","exalar","examinar","exato","exausto","excesso","excitar","exclamar","executar","exemplo","exibir","exigente","exonerar","expandir","expelir","expirar","explanar","exposto","expresso","expulsar","externo","extinto","extrato","fabricar","fabuloso","faceta","facial","fada","fadiga","faixa","falar","falta","familiar","fandango","fanfarra","fantoche","fardado","farelo","farinha","farofa","farpa","fartura","fatia","fator","favorita","faxina","fazenda","fechado","feijoada","feirante","felino","feminino","fenda","feno","fera","feriado","ferrugem","ferver","festejar","fetal","feudal","fiapo","fibrose","ficar","ficheiro","figurado","fileira","filho","filme","filtrar","firmeza","fisgada","fissura","fita","fivela","fixador","fixo","flacidez","flamingo","flanela","flechada","flora","flutuar","fluxo","focal","focinho","fofocar","fogo","foguete","foice","folgado","folheto","forjar","formiga","forno","forte","fosco","fossa","fragata","fralda","frango","frasco","fraterno","freira","frente","fretar","frieza","friso","fritura","fronha","frustrar","fruteira","fugir","fulano","fuligem","fundar","fungo","funil","furador","furioso","futebol","gabarito","gabinete","gado","gaiato","gaiola","gaivota","galega","galho","galinha","galocha","ganhar","garagem","garfo","gargalo","garimpo","garoupa","garrafa","gasoduto","gasto","gata","gatilho","gaveta","gazela","gelado","geleia","gelo","gemada","gemer","gemido","generoso","gengiva","genial","genoma","genro","geologia","gerador","germinar","gesso","gestor","ginasta","gincana","gingado","girafa","girino","glacial","glicose","global","glorioso","goela","goiaba","golfe","golpear","gordura","gorjeta","gorro","gostoso","goteira","governar","gracejo","gradual","grafite","gralha","grampo","granada","gratuito","graveto","graxa","grego","grelhar","greve","grilo","grisalho","gritaria","grosso","grotesco","grudado","grunhido","gruta","guache","guarani","guaxinim","guerrear","guiar","guincho","guisado","gula","guloso","guru","habitar","harmonia","haste","haver","hectare","herdar","heresia","hesitar","hiato","hibernar","hidratar","hiena","hino","hipismo","hipnose","hipoteca","hoje","holofote","homem","honesto","honrado","hormonal","hospedar","humorado","iate","ideia","idoso","ignorado","igreja","iguana","ileso","ilha","iludido","iluminar","ilustrar","imagem","imediato","imenso","imersivo","iminente","imitador","imortal","impacto","impedir","implante","impor","imprensa","impune","imunizar","inalador","inapto","inativo","incenso","inchar","incidir","incluir","incolor","indeciso","indireto","indutor","ineficaz","inerente","infantil","infestar","infinito","inflamar","informal","infrator","ingerir","inibido","inicial","inimigo","injetar","inocente","inodoro","inovador","inox","inquieto","inscrito","inseto","insistir","inspetor","instalar","insulto","intacto","integral","intimar","intocado","intriga","invasor","inverno","invicto","invocar","iogurte","iraniano","ironizar","irreal","irritado","isca","isento","isolado","isqueiro","italiano","janeiro","jangada","janta","jararaca","jardim","jarro","jasmim","jato","javali","jazida","jejum","joaninha","joelhada","jogador","joia","jornal","jorrar","jovem","juba","judeu","judoca","juiz","julgador","julho","jurado","jurista","juro","justa","labareda","laboral","lacre","lactante","ladrilho","lagarta","lagoa","laje","lamber","lamentar","laminar","lampejo","lanche","lapidar","lapso","laranja","lareira","largura","lasanha","lastro","lateral","latido","lavanda","lavoura","lavrador","laxante","lazer","lealdade","lebre","legado","legendar","legista","leigo","leiloar","leitura","lembrete","leme","lenhador","lentilha","leoa","lesma","leste","letivo","letreiro","levar","leveza","levitar","liberal","libido","liderar","ligar","ligeiro","limitar","limoeiro","limpador","linda","linear","linhagem","liquidez","listagem","lisura","litoral","livro","lixa","lixeira","locador","locutor","lojista","lombo","lona","longe","lontra","lorde","lotado","loteria","loucura","lousa","louvar","luar","lucidez","lucro","luneta","lustre","lutador","luva","macaco","macete","machado","macio","madeira","madrinha","magnata","magreza","maior","mais","malandro","malha","malote","maluco","mamilo","mamoeiro","mamute","manada","mancha","mandato","manequim","manhoso","manivela","manobrar","mansa","manter","manusear","mapeado","maquinar","marcador","maresia","marfim","margem","marinho","marmita","maroto","marquise","marreco","martelo","marujo","mascote","masmorra","massagem","mastigar","matagal","materno","matinal","matutar","maxilar","medalha","medida","medusa","megafone","meiga","melancia","melhor","membro","memorial","menino","menos","mensagem","mental","merecer","mergulho","mesada","mesclar","mesmo","mesquita","mestre","metade","meteoro","metragem","mexer","mexicano","micro","migalha","migrar","milagre","milenar","milhar","mimado","minerar","minhoca","ministro","minoria","miolo","mirante","mirtilo","misturar","mocidade","moderno","modular","moeda","moer","moinho","moita","moldura","moleza","molho","molinete","molusco","montanha","moqueca","morango","morcego","mordomo","morena","mosaico","mosquete","mostarda","motel","motim","moto","motriz","muda","muito","mulata","mulher","multar","mundial","munido","muralha","murcho","muscular","museu","musical","nacional","nadador","naja","namoro","narina","narrado","nascer","nativa","natureza","navalha","navegar","navio","neblina","nebuloso","negativa","negociar","negrito","nervoso","neta","neural","nevasca","nevoeiro","ninar","ninho","nitidez","nivelar","nobreza","noite","noiva","nomear","nominal","nordeste","nortear","notar","noticiar","noturno","novelo","novilho","novo","nublado","nudez","numeral","nupcial","nutrir","nuvem","obcecado","obedecer","objetivo","obrigado","obscuro","obstetra","obter","obturar","ocidente","ocioso","ocorrer","oculista","ocupado","ofegante","ofensiva","oferenda","oficina","ofuscado","ogiva","olaria","oleoso","olhar","oliveira","ombro","omelete","omisso","omitir","ondulado","oneroso","ontem","opcional","operador","oponente","oportuno","oposto","orar","orbitar","ordem","ordinal","orfanato","orgasmo","orgulho","oriental","origem","oriundo","orla","ortodoxo","orvalho","oscilar","ossada","osso","ostentar","otimismo","ousadia","outono","outubro","ouvido","ovelha","ovular","oxidar","oxigenar","pacato","paciente","pacote","pactuar","padaria","padrinho","pagar","pagode","painel","pairar","paisagem","palavra","palestra","palheta","palito","palmada","palpitar","pancada","panela","panfleto","panqueca","pantanal","papagaio","papelada","papiro","parafina","parcial","pardal","parede","partida","pasmo","passado","pastel","patamar","patente","patinar","patrono","paulada","pausar","peculiar","pedalar","pedestre","pediatra","pedra","pegada","peitoral","peixe","pele","pelicano","penca","pendurar","peneira","penhasco","pensador","pente","perceber","perfeito","pergunta","perito","permitir","perna","perplexo","persiana","pertence","peruca","pescado","pesquisa","pessoa","petiscar","piada","picado","piedade","pigmento","pilastra","pilhado","pilotar","pimenta","pincel","pinguim","pinha","pinote","pintar","pioneiro","pipoca","piquete","piranha","pires","pirueta","piscar","pistola","pitanga","pivete","planta","plaqueta","platina","plebeu","plumagem","pluvial","pneu","poda","poeira","poetisa","polegada","policiar","poluente","polvilho","pomar","pomba","ponderar","pontaria","populoso","porta","possuir","postal","pote","poupar","pouso","povoar","praia","prancha","prato","praxe","prece","predador","prefeito","premiar","prensar","preparar","presilha","pretexto","prevenir","prezar","primata","princesa","prisma","privado","processo","produto","profeta","proibido","projeto","prometer","propagar","prosa","protetor","provador","publicar","pudim","pular","pulmonar","pulseira","punhal","punir","pupilo","pureza","puxador","quadra","quantia","quarto","quase","quebrar","queda","queijo","quente","querido","quimono","quina","quiosque","rabanada","rabisco","rachar","racionar","radial","raiar","rainha","raio","raiva","rajada","ralado","ramal","ranger","ranhura","rapadura","rapel","rapidez","raposa","raquete","raridade","rasante","rascunho","rasgar","raspador","rasteira","rasurar","ratazana","ratoeira","realeza","reanimar","reaver","rebaixar","rebelde","rebolar","recado","recente","recheio","recibo","recordar","recrutar","recuar","rede","redimir","redonda","reduzida","reenvio","refinar","refletir","refogar","refresco","refugiar","regalia","regime","regra","reinado","reitor","rejeitar","relativo","remador","remendo","remorso","renovado","reparo","repelir","repleto","repolho","represa","repudiar","requerer","resenha","resfriar","resgatar","residir","resolver","respeito","ressaca","restante","resumir","retalho","reter","retirar","retomada","retratar","revelar","revisor","revolta","riacho","rica","rigidez","rigoroso","rimar","ringue","risada","risco","risonho","robalo","rochedo","rodada","rodeio","rodovia","roedor","roleta","romano","roncar","rosado","roseira","rosto","rota","roteiro","rotina","rotular","rouco","roupa","roxo","rubro","rugido","rugoso","ruivo","rumo","rupestre","russo","sabor","saciar","sacola","sacudir","sadio","safira","saga","sagrada","saibro","salada","saleiro","salgado","saliva","salpicar","salsicha","saltar","salvador","sambar","samurai","sanar","sanfona","sangue","sanidade","sapato","sarda","sargento","sarjeta","saturar","saudade","saxofone","sazonal","secar","secular","seda","sedento","sediado","sedoso","sedutor","segmento","segredo","segundo","seiva","seleto","selvagem","semanal","semente","senador","senhor","sensual","sentado","separado","sereia","seringa","serra","servo","setembro","setor","sigilo","silhueta","silicone","simetria","simpatia","simular","sinal","sincero","singular","sinopse","sintonia","sirene","siri","situado","soberano","sobra","socorro","sogro","soja","solda","soletrar","solteiro","sombrio","sonata","sondar","sonegar","sonhador","sono","soprano","soquete","sorrir","sorteio","sossego","sotaque","soterrar","sovado","sozinho","suavizar","subida","submerso","subsolo","subtrair","sucata","sucesso","suco","sudeste","sufixo","sugador","sugerir","sujeito","sulfato","sumir","suor","superior","suplicar","suposto","suprimir","surdina","surfista","surpresa","surreal","surtir","suspiro","sustento","tabela","tablete","tabuada","tacho","tagarela","talher","talo","talvez","tamanho","tamborim","tampa","tangente","tanto","tapar","tapioca","tardio","tarefa","tarja","tarraxa","tatuagem","taurino","taxativo","taxista","teatral","tecer","tecido","teclado","tedioso","teia","teimar","telefone","telhado","tempero","tenente","tensor","tentar","termal","terno","terreno","tese","tesoura","testado","teto","textura","texugo","tiara","tigela","tijolo","timbrar","timidez","tingido","tinteiro","tiragem","titular","toalha","tocha","tolerar","tolice","tomada","tomilho","tonel","tontura","topete","tora","torcido","torneio","torque","torrada","torto","tostar","touca","toupeira","toxina","trabalho","tracejar","tradutor","trafegar","trajeto","trama","trancar","trapo","traseiro","tratador","travar","treino","tremer","trepidar","trevo","triagem","tribo","triciclo","tridente","trilogia","trindade","triplo","triturar","triunfal","trocar","trombeta","trova","trunfo","truque","tubular","tucano","tudo","tulipa","tupi","turbo","turma","turquesa","tutelar","tutorial","uivar","umbigo","unha","unidade","uniforme","urologia","urso","urtiga","urubu","usado","usina","usufruir","vacina","vadiar","vagaroso","vaidoso","vala","valente","validade","valores","vantagem","vaqueiro","varanda","vareta","varrer","vascular","vasilha","vassoura","vazar","vazio","veado","vedar","vegetar","veicular","veleiro","velhice","veludo","vencedor","vendaval","venerar","ventre","verbal","verdade","vereador","vergonha","vermelho","verniz","versar","vertente","vespa","vestido","vetorial","viaduto","viagem","viajar","viatura","vibrador","videira","vidraria","viela","viga","vigente","vigiar","vigorar","vilarejo","vinco","vinheta","vinil","violeta","virada","virtude","visitar","visto","vitral","viveiro","vizinho","voador","voar","vogal","volante","voleibol","voltagem","volumoso","vontade","vulto","vuvuzela","xadrez","xarope","xeque","xeretar","xerife","xingar","zangado","zarpar","zebu","zelador","zombar","zoologia","zumbido"]["абзац","абонент","абсурд","авангард","авария","август","авиация","автор","агент","агитация","агрегат","адвокат","адмирал","адрес","азарт","азот","академия","аквариум","аксиома","акула","акцент","акция","аллея","алмаз","алтарь","альбом","альянс","амбиция","анализ","анекдот","анкета","ансамбль","антенна","апельсин","аппарат","аппетит","апрель","аптека","арбуз","аргумент","аренда","арест","армия","аромат","арсенал","артерия","артист","архив","аспирант","асфальт","атака","атомный","атрибут","аукцион","афиша","аэропорт","бабочка","бабушка","багаж","база","бактерия","баланс","балерина","балкон","бандит","банк","барабан","барон","барышня","барьер","бассейн","батарея","башмак","башня","бедный","беженец","бездна","белка","белый","бензин","берег","беседа","бешеный","билет","бинокль","биржа","битва","благо","блеск","близкий","блин","блок","блюдо","богатый","бодрый","боец","бокал","боковой","бокс","более","болото","болтать","большой","бомба","борт","борьба","босой","ботинок","бояться","брак","брать","бревно","бред","бригада","бродяга","броня","бросить","брызги","брюки","брюхо","бугор","будка","будни","будущее","буква","букет","бульвар","бумага","бунт","бурный","буря","бутылка","бухта","бывший","быстро","бытовой","быть","бюджет","бюро","бюст","вагон","важный","вакцина","валенок","вальс","валюта","ванная","варенье","вариант","вблизи","вверх","вводить","вдали","вдвое","вдова","вдоль","вдруг","ведро","ведущий","ведьма","вежливо","везде","веко","вексель","велеть","великий","венец","веник","веранда","верблюд","верить","верный","версия","вертеть","верхний","вершина","весело","весна","весомый","вести","весь","ветеран","ветхий","вечер","вечно","вешалка","вещество","взамен","взгляд","вздох","взнос","взойти","взор","взрыв","взять","видеть","видимо","визг","визит","вилка","вина","вирус","висок","витамин","витрина","вихрь","вишня","вкус","влага","владелец","власть","влево","влияние","вложить","вместе","внешний","вникать","внимание","вновь","внук","внутри","внучка","внушать","вовлечь","вовремя","вовсю","вода","водород","водяной","воевать","возврат","возглас","воздух","возить","возле","возня","возраст","война","войско","вокзал","волос","волчий","вольный","воля","вообще","вопль","вопрос","ворота","восемь","восток","вплоть","вполне","вправе","впредь","впрочем","врач","вредный","время","вручить","всадник","всегда","вскоре","вскрыть","всплеск","вспышка","встреча","всюду","всякий","второй","вход","вчера","выбор","вывод","выгнать","выдать","выехать","вызов","выйти","выкуп","вылезти","вымыть","выпасть","выпить","выплата","выпуск","вырасти","выручка","выслать","высокий","выставка","вышка","вязать","вялый","газета","газовый","галерея","галстук","гамма","гарантия","гармония","гарнизон","гастроли","гвардия","гвоздь","гектар","генерал","гений","геном","геолог","герб","герой","гибкий","гигант","гимн","гипотеза","гитара","главный","глагол","гладить","глаз","глина","глоток","глубокий","глупый","глухой","глыба","глядеть","гнев","гнездо","гнилой","годовой","голова","голубой","голый","гонорар","гордость","горизонт","горло","горный","город","горшок","горький","горючее","горячий","готовый","градус","грамм","граница","граф","гребень","гриб","гримаса","грозить","грохот","грош","грубый","грудь","груз","грунт","группа","груша","грязный","губа","гудок","гулкий","гулять","гусеница","густо","гусь","давление","давно","даже","дальний","данный","дарить","датчик","дать","дача","двадцать","дважды","дверь","двигать","движение","двойной","двор","дебют","девятый","дежурный","действие","декабрь","деление","дело","дельфин","день","дерево","держать","дерзкий","десять","деталь","детский","дефект","дефицит","деятель","джаз","джинсы","джунгли","диагноз","диалог","диапазон","диван","дивизия","дивный","диета","дизайн","дикарь","дилер","динамика","диплом","директор","дитя","длинный","дневник","добрый","добыча","доверие","догадка","догнать","дождь","доклад","доктор","документ","долго","должен","долина","донос","дорога","досада","доска","достать","досуг","доход","доцент","дощатый","драка","древний","дремать","дробный","дрова","дрожать","другой","дружба","дубовый","дуга","думать","дурной","духи","душный","дуэль","дуэт","дыра","дыхание","дюжина","дядя","едва","единый","ерунда","если","ехать","жадный","жажда","жалеть","жалоба","жанр","жареный","жаркий","жгучий","жевать","желание","желудок","жена","женщина","жертва","жест","жидкость","житель","жить","жрец","жулик","журнал","жуткий","забрать","забыть","завести","завод","завтра","загадка","загнать","заговор","задача","задеть","задний","задолго","заехать","заказ","закон","закрыть","закуска","залезть","залить","залп","замок","замуж","замысел","занавес","заново","занять","заодно","запись","запрос","запуск","запястье","заранее","заросль","зарплата","заря","засада","заслуга","заснуть","застать","затвор","затеять","затрата","затылок","захват","зачем","защита","заявить","заяц","звезда","звено","звонить","здесь","зелень","земля","зеркало","зерно","зима","злой","змея","знамя","знание","значит","золотой","зона","зонтик","зоопарк","зрачок","зрение","зритель","зубной","зубр","игла","идеал","идеолог","идея","идол","идти","изба","избить","избрать","избыток","извлечь","извне","изгиб","изгнать","издание","изделие","изнутри","изобилие","изоляция","изредка","изрядно","изучение","изъять","изящный","икона","икра","иллюзия","именно","иметь","имидж","империя","импульс","иначе","инвалид","индекс","индивид","инерция","инженер","иногда","иной","институт","интерес","интрига","интуиция","инфаркт","инцидент","ирония","искать","испуг","история","итог","июнь","кабель","кабинет","каблук","кавалер","кадр","каждый","кажется","казино","калитка","камень","камин","канал","кандидат","каникулы","канон","капитан","капля","капот","капуста","карандаш","карета","каркас","карман","картина","карьера","каска","кассета","кастрюля","каталог","катер","каток","катушка","кафедра","качество","каша","кашлять","каюта","квадрат","квартира","квота","кепка","кивнуть","километр","кино","киоск","кипяток","кирпич","кислота","кисть","клавиша","клапан","класс","клей","клетка","клиент","климат","клиника","кличка","клоун","клочок","клуб","клумба","ключ","книга","кнопка","кнут","княгиня","князь","кобура","когда","кодекс","кожа","коктейль","колено","коллега","колонна","колпак","кольцо","колючий","коляска","команда","комедия","комиссия","коммуна","комната","комок","компания","комфорт","конвейер","конгресс","конечно","конкурс","контроль","концерт","конь","конюшня","копать","копейка","копыто","корабль","корень","корзина","коридор","кормить","корпус","космос","костюм","косяк","котел","котлета","который","коттедж","кофе","кофта","кошка","кража","край","красный","краткий","кредит","крем","крепкий","кресло","кривой","кризис","кристалл","критерий","кричать","кровь","крокодил","кролик","кроме","крона","круг","кружка","крупный","крутой","крушение","крыло","крыша","крючок","кстати","кубик","куда","кузов","кукла","кулак","кулиса","культура","кумир","купе","купить","купол","купюра","курица","курорт","курс","куртка","кусок","куст","кухня","кушать","лабиринт","лавка","лагерь","ладно","ладонь","лапа","лауреат","лгать","лебедь","левый","легенда","легкий","ледяной","лежать","лезвие","лезть","лекция","ленивый","лента","лепесток","лесной","лестница","лететь","лето","лечить","лига","лидер","лиловый","лимон","линия","липкий","лист","литр","лихой","лицо","лишить","лишний","ловить","логика","лодка","ложь","лозунг","локоть","лопата","лошадь","лукавый","луна","лучший","лысый","льгота","любить","любой","людской","люстра","лютый","лягушка","магазин","магия","майор","майский","максимум","макушка","мало","мальчик","мама","манера","марка","март","маршрут","масса","мастер","масштаб","материал","матч","махать","машина","маяк","мебель","медаль","медведь","медицина","медь","между","мелкий","мелочь","мемуары","меньше","меню","менять","мера","мерцать","место","месяц","металл","метод","метр","механизм","меховой","мечтать","мешать","мешок","миграция","микрофон","милиция","миллион","милость","миля","мимо","минерал","министр","минута","мирный","миска","миссия","митинг","мишень","младший","мнение","мнимый","много","могучий","модель","может","мозг","мокрый","молекула","молния","молодой","молчать","момент","монета","монитор","монолог","монстр","монтаж","мораль","море","морковь","мороз","морщина","мостовая","мотать","мотив","мотор","мохнатый","мрамор","мрачный","мстить","мудрый","мужество","мужчина","музей","музыка","мундир","муравей","мусор","муха","мчаться","мысль","мыться","мышца","мышь","мюзикл","мягкий","мясо","набор","навык","наглый","нагрузка","надежда","надзор","надо","наедине","назад","название","назло","наивный","найти","наконец","налево","наличие","налог","намерен","нанести","напасть","например","народ","наследие","натура","наука","наутро","начать","небо","неважно","невеста","негодяй","недавно","неделя","недолго","недра","недуг","нежный","незачем","некто","нелепый","неловко","нельзя","немало","немой","неплохо","нервный","нередко","нестись","неудача","неужели","нефть","неясный","нигде","низкий","никакой","никогда","никуда","ничто","ничуть","ниша","нищий","новость","новый","нога","ноготь","ножницы","ноздря","номер","носить","носок","ночь","ноябрь","нрав","нуль","нынче","нырять","нюанс","няня","обаяние","обед","обезьяна","обещать","обжечь","обзор","обилие","обитать","область","облик","обложка","обмен","обморок","обожать","обои","оболочка","оборона","обочина","образ","обрести","обрыв","обувь","обучение","обход","общество","общий","объект","обыск","обычно","обязать","овощи","овраг","овца","оговорка","ограда","огурец","одежда","одеяло","один","однако","одолеть","ожидать","озеро","океан","окно","около","окоп","окраина","октябрь","опасный","опека","операция","описание","оплата","опора","оппонент","оптимизм","оптовый","опухоль","опыт","оратор","орбита","орган","орден","орел","оригинал","ориентир","оркестр","оружие","осенний","осколок","осмотр","остров","отбор","отбыть","отвлечь","отдать","отдел","отдых","отель","отец","отзыв","отказ","отклик","открыть","откуда","отличие","отныне","отойти","отпуск","отрасль","отросток","отрывок","отряд","отсек","отставка","отсюда","оттенок","оттого","отчего","отъезд","офис","офицер","охота","охрана","оценка","очаг","очень","очередь","очищать","ошибка","ощущение","павильон","падать","пазуха","пакет","палата","палец","палуба","пальто","память","панель","паника","пара","парень","пароход","партия","парус","паспорт","пассажир","пастух","патент","патрон","пауза","паук","паутина","пафос","пахнуть","пациент","пачка","певец","педагог","пейзаж","пенсия","пепел","первый","перед","период","перо","перрон","персонаж","перчатка","песня","песок","петля","петрушка","петух","пехота","печать","печень","пешком","пещера","пианист","пиджак","пилот","пионер","пирамида","пирожок","письмо","пища","плавание","плакать","пламя","план","пласт","платить","пленный","плечо","плита","плод","плоский","плотный","плохой","площадь","плыть","плюс","пляж","плясать","победа","повар","повод","повсюду","повязка","погода","погреб","подбор","подвиг","подделка","поджать","поднос","подпись","подруга","подход","подчас","подъезд","поединок","поезд","поесть","поехать","пожалуй","пожилой","позади","позвать","поздний","позиция","позор","поиск","поймать","пойти","поклон","покой","покрыть","полдень","полезный","ползти","полк","полный","половина","полтора","польза","поляна","помидор","помнить","помощь","попасть","поперек","поплыть","пополам","поправка","попугай","попытка","порог","портрет","порция","порыв","порядок","после","посол","посреди","постель","посуда","потом","похвала","похожий","поцелуй","почва","почему","пошлина","поэма","поэтому","право","праздник","практика","прах","преграда","предмет","прежде","прелесть","премия","препарат","пресса","прибыть","прижать","прийти","приказ","прилавок","пример","принять","природа","притом","прихожая","прицел","причина","приют","прогноз","продукт","проект","прожить","прокат","промысел","пропуск","просто","против","профиль","процесс","прочий","прошлый","прощать","пружина","прут","прыжок","прямой","птица","публика","пугать","пуговица","пузырь","пульт","пуля","пункт","пускать","пустой","путь","пухлый","пучок","пушистый","пушка","пчела","пшеница","пылать","пыль","пышный","пьеса","пятка","пятно","пятый","пятьсот","работа","равнина","ради","радость","радуга","разбить","развитие","разговор","раздел","различие","размер","разный","разрыв","разум","район","ракета","раковина","рамка","рано","рапорт","распад","рассказ","расти","расход","расцвет","рация","рвануть","рваться","реакция","ребро","реветь","редактор","редкий","реестр","режим","резать","резерв","резина","резко","резной","рейс","реклама","рекорд","религия","рельс","ремень","ремонт","реплика","репортаж","ресница","ресторан","реформа","рецепт","речь","решение","ржавый","риск","рисунок","ритуал","рифма","робко","робот","ровесник","ровно","родной","рождение","роза","розовый","розыск","роль","роман","роскошь","роспись","рост","рубашка","рубеж","рубить","рубрика","рудник","рука","рукопись","румяный","русло","рухнуть","ручей","ручной","рыба","рыжий","рынок","рыхлый","рыцарь","рычаг","рюкзак","рядом","садовый","сажать","салон","салфетка","салют","самец","самовар","самый","сани","санкция","сапог","сарай","сатира","сахар","сбить","сбоку","сборная","сбыт","свадьба","свалка","сварить","свежий","сверху","свет","свеча","свинья","свист","свитер","свобода","сводка","свой","свыше","связь","сдаться","сделать","сегмент","сегодня","седло","седой","седьмой","сезон","сейф","сейчас","секрет","сектор","секунда","семинар","семья","сенатор","сено","сенсация","сентябрь","сервис","сердце","середина","сержант","серия","серый","сессия","сесть","сетевой","сжатый","сжечь","сзади","сигнал","сиденье","сила","силуэт","сильный","символ","симпатия","симфония","синий","синтез","синяк","сирень","система","ситуация","сияние","сказать","скала","скамейка","скандал","скатерть","скачок","скважина","сквер","сквозь","скелет","скидка","склад","сколько","скорый","скосить","скот","скрипка","скудный","скука","слабый","слава","сладкий","слегка","след","слеза","слепой","слесарь","слишком","слово","слог","сложный","сломать","служба","слух","случай","слышать","слюна","смежный","смелый","сменить","смесь","сметана","смех","смола","смуглый","смутный","смущать","смысл","снайпер","снаряд","сначала","снег","снизу","сниться","сно��а","снять","собака","соблазн","собрание","событие","совесть","совсем","согласие","создать","сознание","созреть","сойтись","сокол","солдат","соленый","солнце","солома","сомнение","сонный","соперник","соратник","сорвать","сосед","сосиска","состав","сотня","соус","союз","спад","спальня","спасти","спектр","сперва","спешить","спина","спирт","список","спичка","сплав","спонсор","спор","способ","справка","спустя","спутник","сразу","средство","срок","срыв","ссора","ссылка","ставить","стадия","стакан","станция","старый","стая","стебель","стекло","стена","степень","стереть","стиль","стимул","стирать","стихи","стоить","стойка","стол","стонать","стопа","сторона","стоянка","страна","стричь","строгий","струя","студент","стук","ступня","стыдно","суббота","субъект","сувенир","сугроб","сугубо","судить","судно","судьба","суета","суметь","сумма","сумрак","сундук","супруг","суровый","сутки","сухой","суша","существо","сфера","схема","схожий","сценарий","счастье","считать","съезд","сыграть","сырой","сытый","сыщик","сюда","сюжет","сюрприз","тайна","также","такой","такси","тактика","талия","таможня","танец","таракан","тарелка","тариф","тащить","таять","тварь","театр","тезис","текст","текущий","телефон","тема","темнота","теневой","теннис","теория","теперь","тепло","терапия","терзать","термин","терпеть","терраса","терять","тесный","тетрадь","техника","течение","тигр","типовой","тираж","титул","тихий","ткань","товарищ","тоже","толпа","толстый","толчок","толщина","только","тонкий","тонна","топить","топор","торговля","тормоз","торчать","тотчас","точка","точно","тощий","трава","традиция","трактор","трамвай","траншея","трасса","тревога","трезвый","тренер","трепет","треск","третий","трещина","трибуна","тридцать","триста","триумф","трогать","тройка","тронуть","тропа","тротуар","трубка","труд","трюк","тряпка","туго","туловище","туман","тумбочка","тундра","тупик","турист","турнир","тусклый","туфля","туча","тысяча","тяга","тяжело","убежать","убогий","уборка","уважение","увезти","уволить","угадать","угол","угощать","угроза","угрюмый","удар","удачный","уделять","удивить","удобный","удочка","уезжать","ужин","узел","узкий","уйти","указание","уклон","украсть","укусить","улетать","улица","улыбка","умело","умение","умный","умолять","унести","унижать","унылый","упаковка","упасть","упорно","упрек","урна","уровень","урожай","уронить","усадьба","усатый","усвоить","усилие","условие","услуга","усмешка","успеть","устав","устоять","утечка","утешать","утро","уцелеть","участие","ученик","учесть","ущелье","ущерб","уютный","фабрика","фаворит","факел","факт","фамилия","фантазия","фасад","февраль","феномен","фермер","фигура","физика","филиал","философ","фильм","финал","флаг","флот","фойе","фокус","фонарь","фонд","фонтан","форма","форум","фото","фрагмент","фраза","фракция","фронт","фрукт","функция","фуражка","футбол","футляр","халат","хаос","характер","хата","хвалить","хватать","хвойный","хвост","химия","хирург","хитрый","хищник","хлеб","хлынуть","хмурый","ходить","хозяин","хоккей","холм","холст","хорошо","хотеть","храбрый","храм","хранить","хребет","хрен","хрипло","хроника","хрупкий","художник","худший","хулиган","хутор","царь","цветок","целевой","целиком","целое","цель","цензура","ценить","центр","цепной","цикл","цилиндр","цирк","цитата","цифра","чайник","часы","чашка","человек","челюсть","чемодан","чемпион","чепуха","червь","чердак","через","чернила","черта","чеснок","честно","четверть","четыре","число","чистый","читатель","чтение","чтобы","чувство","чудак","чудный","чудо","чужой","чулок","чума","чушь","чуять","шагать","шанс","шапка","шарик","шарф","шахматы","шашлык","шедевр","шептать","шерсть","шестой","шинель","ширина","шишка","шкаф","школа","шкура","шланг","шлем","шнур","шоколад","шорох","шоссе","шпион","шприц","штаб","штамм","штаны","штатный","штора","штраф","штурм","штык","шумно","шуршать","шутить","шутка","щедрый","щека","щенок","экзамен","экипаж","экономия","экран","эксперт","элемент","элитный","эмоция","энергия","эпизод","эпоха","эскиз","эстрада","этап","этика","этот","эфир","эффект","эшелон","юбилей","юбка","южный","юмор","юность","юрист","юстиция","яблоко","явление","ягода","ядро","язык","яйцо","якобы","якорь","январь","яркий","ярмарка","ярость","ясный","яхта","ячейка","ящик"]["ábaco","abdomen","abeja","abierto","abogado","abono","aborto","abrazo","abrir","abuelo","abuso","acabar","academia","acceso","acción","aceite","acelga","acento","aceptar","ácido","aclarar","acné","acoger","acoso","activo","acto","actriz","actuar","acudir","acuerdo","acusar","adicto","admitir","adoptar","adorno","aduana","adulto","aéreo","afectar","afición","afinar","afirmar","ágil","agitar","agonía","agosto","agotar","agregar","agrio","agua","agudo","águila","aguja","ahogo","ahorro","aire","aislar","ajedrez","ajeno","ajuste","alacrán","alambre","alarma","alba","álbum","alcalde","aldea","alegre","alejar","alerta","aleta","alfiler","alga","algodón","aliado","aliento","alivio","alma","almeja","almíbar","altar","alteza","altivo","alto","altura","alumno","alzar","amable","amante","amapola","amargo","amasar","ámbar","ámbito","ameno","amigo","amistad","amor","amparo","amplio","ancho","anciano","ancla","andar","andén","anemia","ángulo","anillo","ánimo","anís","anotar","antena","antiguo","antojo","anual","anular","anuncio","añadir","añejo","año","apagar","aparato","apetito","apio","aplicar","apodo","aporte","apoyo","aprender","aprobar","apuesta","apuro","arado","araña","arar","árbitro","árbol","arbusto","archivo","arco","arder","ardilla","arduo","área","árido","aries","armonía","arnés","aroma","arpa","arpón","arreglo","arroz","arruga","arte","artista","asa","asado","asalto","ascenso","asegurar","aseo","asesor","asiento","asilo","asistir","asno","asombro","áspero","astilla","astro","astuto","asumir","asunto","atajo","ataque","atar","atento","ateo","ático","atleta","átomo","atraer","atroz","atún","audaz","audio","auge","aula","aumento","ausente","autor","aval","avance","avaro","ave","avellana","avena","avestruz","avión","aviso","ayer","ayuda","ayuno","azafrán","azar","azote","azúcar","azufre","azul","baba","babor","bache","bahía","baile","bajar","balanza","balcón","balde","bambú","banco","banda","baño","barba","barco","barniz","barro","báscula","bastón","basura","batalla","batería","batir","batuta","baúl","bazar","bebé","bebida","bello","besar","beso","bestia","bicho","bien","bingo","blanco","bloque","blusa","boa","bobina","bobo","boca","bocina","boda","bodega","boina","bola","bolero","bolsa","bomba","bondad","bonito","bono","bonsái","borde","borrar","bosque","bote","botín","bóveda","bozal","bravo","brazo","brecha","breve","brillo","brinco","brisa","broca","broma","bronce","brote","bruja","brusco","bruto","buceo","bucle","bueno","buey","bufanda","bufón","búho","buitre","bulto","burbuja","burla","burro","buscar","butaca","buzón","caballo","cabeza","cabina","cabra","cacao","cadáver","cadena","caer","café","caída","caimán","caja","cajón","cal","calamar","calcio","caldo","calidad","calle","calma","calor","calvo","cama","cambio","camello","camino","campo","cáncer","candil","canela","canguro","canica","canto","caña","cañón","caoba","caos","capaz","capitán","capote","captar","capucha","cara","carbón","cárcel","careta","carga","cariño","carne","carpeta","carro","carta","casa","casco","casero","caspa","castor","catorce","catre","caudal","causa","cazo","cebolla","ceder","cedro","celda","célebre","celoso","célula","cemento","ceniza","centro","cerca","cerdo","cereza","cero","cerrar","certeza","césped","cetro","chacal","chaleco","champú","chancla","chapa","charla","chico","chiste","chivo","choque","choza","chuleta","chupar","ciclón","ciego","cielo","cien","cierto","cifra","cigarro","cima","cinco","cine","cinta","ciprés","circo","ciruela","cisne","cita","ciudad","clamor","clan","claro","clase","clave","cliente","clima","clínica","cobre","cocción","cochino","cocina","coco","código","codo","cofre","coger","cohete","cojín","cojo","cola","colcha","colegio","colgar","colina","collar","colmo","columna","combate","comer","comida","cómodo","compra","conde","conejo","conga","conocer","consejo","contar","copa","copia","corazón","corbata","corcho","cordón","corona","correr","coser","cosmos","costa","cráneo","cráter","crear","crecer","creído","crema","cría","crimen","cripta","crisis","cromo","crónica","croqueta","crudo","cruz","cuadro","cuarto","cuatro","cubo","cubrir","cuchara","cuello","cuento","cuerda","cuesta","cueva","cuidar","culebra","culpa","culto","cumbre","cumplir","cuna","cuneta","cuota","cupón","cúpula","curar","curioso","curso","curva","cutis","dama","danza","dar","dardo","dátil","deber","débil","década","decir","dedo","defensa","definir","dejar","delfín","delgado","delito","demora","denso","dental","deporte","derecho","derrota","desayuno","deseo","desfile","desnudo","destino","desvío","detalle","detener","deuda","día","diablo","diadema","diamante","diana","diario","dibujo","dictar","diente","dieta","diez","difícil","digno","dilema","diluir","dinero","directo","dirigir","disco","diseño","disfraz","diva","divino","doble","doce","dolor","domingo","don","donar","dorado","dormir","dorso","dos","dosis","dragón","droga","ducha","duda","duelo","dueño","dulce","dúo","duque","durar","dureza","duro","ébano","ebrio","echar","eco","ecuador","edad","edición","edificio","editor","educar","efecto","eficaz","eje","ejemplo","elefante","elegir","elemento","elevar","elipse","élite","elixir","elogio","eludir","embudo","emitir","emoción","empate","empeño","empleo","empresa","enano","encargo","enchufe","encía","enemigo","enero","enfado","enfermo","engaño","enigma","enlace","enorme","enredo","ensayo","enseñar","entero","entrar","envase","envío","época","equipo","erizo","escala","escena","escolar","escribir","escudo","esencia","esfera","esfuerzo","espada","espejo","espía","esposa","espuma","esquí","estar","este","estilo","estufa","etapa","eterno","ética","etnia","evadir","evaluar","evento","evitar","exacto","examen","exceso","excusa","exento","exigir","exilio","existir","éxito","experto","explicar","exponer","extremo","fábrica","fábula","fachada","fácil","factor","faena","faja","falda","fallo","falso","faltar","fama","familia","famoso","faraón","farmacia","farol","farsa","fase","fatiga","fauna","favor","fax","febrero","fecha","feliz","feo","feria","feroz","fértil","fervor","festín","fiable","fianza","fiar","fibra","ficción","ficha","fideo","fiebre","fiel","fiera","fiesta","figura","fijar","fijo","fila","filete","filial","filtro","fin","finca","fingir","finito","firma","flaco","flauta","flecha","flor","flota","fluir","flujo","flúor","fobia","foca","fogata","fogón","folio","folleto","fondo","forma","forro","fortuna","forzar","fosa","foto","fracaso","frágil","franja","frase","fraude","freír","freno","fresa","frío","frito","fruta","fuego","fuente","fuerza","fuga","fumar","función","funda","furgón","furia","fusil","fútbol","futuro","gacela","gafas","gaita","gajo","gala","galería","gallo","gamba","ganar","gancho","ganga","ganso","garaje","garza","gasolina","gastar","gato","gavilán","gemelo","gemir","gen","género","genio","gente","geranio","gerente","germen","gesto","gigante","gimnasio","girar","giro","glaciar","globo","gloria","gol","golfo","goloso","golpe","goma","gordo","gorila","gorra","gota","goteo","gozar","grada","gráfico","grano","grasa","gratis","grave","grieta","grillo","gripe","gris","grito","grosor","grúa","grueso","grumo","grupo","guante","guapo","guardia","guerra","guía","guiño","guion","guiso","guitarra","gusano","gustar","haber","hábil","hablar","hacer","hacha","hada","hallar","hamaca","harina","haz","hazaña","hebilla","hebra","hecho","helado","helio","hembra","herir","hermano","héroe","hervir","hielo","hierro","hígado","higiene","hijo","himno","historia","hocico","hogar","hoguera","hoja","hombre","hongo","honor","honra","hora","hormiga","horno","hostil","hoyo","hueco","huelga","huerta","hueso","huevo","huida","huir","humano","húmedo","humilde","humo","hundir","huracán","hurto","icono","ideal","idioma","ídolo","iglesia","iglú","igual","ilegal","ilusión","imagen","imán","imitar","impar","imperio","imponer","impulso","incapaz","índice","inerte","infiel","informe","ingenio","inicio","inmenso","inmune","innato","insecto","instante","interés","íntimo","intuir","inútil","invierno","ira","iris","ironía","isla","islote","jabalí","jabón","jamón","jarabe","jardín","jarra","jaula","jazmín","jefe","jeringa","jinete","jornada","joroba","joven","joya","juerga","jueves","juez","jugador","jugo","juguete","juicio","junco","jungla","junio","juntar","júpiter","jurar","justo","juvenil","juzgar","kilo","koala","labio","lacio","lacra","lado","ladrón","lagarto","lágrima","laguna","laico","lamer","lámina","lámpara","lana","lancha","langosta","lanza","lápiz","largo","larva","lástima","lata","látex","latir","laurel","lavar","lazo","leal","lección","leche","lector","leer","legión","legumbre","lejano","lengua","lento","leña","león","leopardo","lesión","letal","letra","leve","leyenda","libertad","libro","licor","líder","lidiar","lienzo","liga","ligero","lima","límite","limón","limpio","lince","lindo","línea","lingote","lino","linterna","líquido","liso","lista","litera","litio","litro","llaga","llama","llanto","llave","llegar","llenar","llevar","llorar","llover","lluvia","lobo","loción","loco","locura","lógica","logro","lombriz","lomo","lonja","lote","lucha","lucir","lugar","lujo","luna","lunes","lupa","lustro","luto","luz","maceta","macho","madera","madre","maduro","maestro","mafia","magia","mago","maíz","maldad","maleta","malla","malo","mamá","mambo","mamut","manco","mando","manejar","manga","maniquí","manjar","mano","manso","manta","mañana","mapa","máquina","mar","marco","marea","marfil","margen","marido","mármol","marrón","martes","marzo","masa","máscara","masivo","matar","materia","matiz","matriz","máximo","mayor","mazorca","mecha","medalla","medio","médula","mejilla","mejor","melena","melón","memoria","menor","mensaje","mente","menú","mercado","merengue","mérito","mes","mesón","meta","meter","método","metro","mezcla","miedo","miel","miembro","miga","mil","milagro","militar","millón","mimo","mina","minero","mínimo","minuto","miope","mirar","misa","miseria","misil","mismo","mitad","mito","mochila","moción","moda","modelo","moho","mojar","molde","moler","molino","momento","momia","monarca","moneda","monja","monto","moño","morada","morder","moreno","morir","morro","morsa","mortal","mosca","mostrar","motivo","mover","móvil","mozo","mucho","mudar","mueble","muela","muerte","muestra","mugre","mujer","mula","muleta","multa","mundo","muñeca","mural","muro","músculo","museo","musgo","música","muslo","nácar","nación","nadar","naipe","naranja","nariz","narrar","nasal","natal","nativo","natural","náusea","naval","nave","navidad","necio","néctar","negar","negocio","negro","neón","nervio","neto","neutro","nevar","nevera","nicho","nido","niebla","nieto","niñez","niño","nítido","nivel","nobleza","noche","nómina","noria","norma","norte","nota","noticia","novato","novela","novio","nube","nuca","núcleo","nudillo","nudo","nuera","nueve","nuez","nulo","número","nutria","oasis","obeso","obispo","objeto","obra","obrero","observar","obtener","obvio","oca","ocaso","océano","ochenta","ocho","ocio","ocre","octavo","octubre","oculto","ocupar","ocurrir","odiar","odio","odisea","oeste","ofensa","oferta","oficio","ofrecer","ogro","oído","oír","ojo","ola","oleada","olfato","olivo","olla","olmo","olor","olvido","ombligo","onda","onza","opaco","opción","ópera","opinar","oponer","optar","óptica","opuesto","oración","orador","oral","órbita","orca","orden","oreja","órgano","orgía","orgullo","oriente","origen","orilla","oro","orquesta","oruga","osadía","oscuro","osezno","oso","ostra","otoño","otro","oveja","óvulo","óxido","oxígeno","oyente","ozono","pacto","padre","paella","página","pago","país","pájaro","palabra","palco","paleta","pálido","palma","paloma","palpar","pan","panal","pánico","pantera","pañuelo","papá","papel","papilla","paquete","parar","parcela","pared","parir","paro","párpado","parque","párrafo","parte","pasar","paseo","pasión","paso","pasta","pata","patio","patria","pausa","pauta","pavo","payaso","peatón","pecado","pecera","pecho","pedal","pedir","pegar","peine","pelar","peldaño","pelea","peligro","pellejo","pelo","peluca","pena","pensar","peñón","peón","peor","pepino","pequeño","pera","percha","perder","pereza","perfil","perico","perla","permiso","perro","persona","pesa","pesca","pésimo","pestaña","pétalo","petróleo","pez","pezuña","picar","pichón","pie","piedra","pierna","pieza","pijama","pilar","piloto","pimienta","pino","pintor","pinza","piña","piojo","pipa","pirata","pisar","piscina","piso","pista","pitón","pizca","placa","plan","plata","playa","plaza","pleito","pleno","plomo","pluma","plural","pobre","poco","poder","podio","poema","poesía","poeta","polen","policía","pollo","polvo","pomada","pomelo","pomo","pompa","poner","porción","portal","posada","poseer","posible","poste","potencia","potro","pozo","prado","precoz","pregunta","premio","prensa","preso","previo","primo","príncipe","prisión","privar","proa","probar","proceso","producto","proeza","profesor","programa","prole","promesa","pronto","propio","próximo","prueba","público","puchero","pudor","pueblo","puerta","puesto","pulga","pulir","pulmón","pulpo","pulso","puma","punto","puñal","puño","pupa","pupila","puré","quedar","queja","quemar","querer","queso","quieto","química","quince","quitar","rábano","rabia","rabo","ración","radical","raíz","rama","rampa","rancho","rango","rapaz","rápido","rapto","rasgo","raspa","rato","rayo","raza","razón","reacción","realidad","rebaño","rebote","recaer","receta","rechazo","recoger","recreo","recto","recurso","red","redondo","reducir","reflejo","reforma","refrán","refugio","regalo","regir","regla","regreso","rehén","reino","reír","reja","relato","relevo","relieve","relleno","reloj","remar","remedio","remo","rencor","rendir","renta","reparto","repetir","reposo","reptil","res","rescate","resina","respeto","resto","resumen","retiro","retorno","retrato","reunir","revés","revista","rey","rezar","rico","riego","rienda","riesgo","rifa","rígido","rigor","rincón","riñón","río","riqueza","risa","ritmo","rito","rizo","roble","roce","rociar","rodar","rodeo","rodilla","roer","rojizo","rojo","romero","romper","ron","ronco","ronda","ropa","ropero","rosa","rosca","rostro","rotar","rubí","rubor","rudo","rueda","rugir","ruido","ruina","ruleta","rulo","rumbo","rumor","ruptura","ruta","rutina","sábado","saber","sabio","sable","sacar","sagaz","sagrado","sala","saldo","salero","salir","salmón","salón","salsa","salto","salud","salvar","samba","sanción","sandía","sanear","sangre","sanidad","sano","santo","sapo","saque","sardina","sartén","sastre","satán","sauna","saxofón","sección","seco","secreto","secta","sed","seguir","seis","sello","selva","semana","semilla","senda","sensor","señal","señor","separar","sepia","sequía","ser","serie","sermón","servir","sesenta","sesión","seta","setenta","severo","sexo","sexto","sidra","siesta","siete","siglo","signo","sílaba","silbar","silencio","silla","símbolo","simio","sirena","sistema","sitio","situar","sobre","socio","sodio","sol","solapa","soldado","soledad","sólido","soltar","solución","sombra","sondeo","sonido","sonoro","sonrisa","sopa","soplar","soporte","sordo","sorpresa","sorteo","sostén","sótano","suave","subir","suceso","sudor","suegra","suelo","sueño","suerte","sufrir","sujeto","sultán","sumar","superar","suplir","suponer","supremo","sur","surco","sureño","surgir","susto","sutil","tabaco","tabique","tabla","tabú","taco","tacto","tajo","talar","talco","talento","talla","talón","tamaño","tambor","tango","tanque","tapa","tapete","tapia","tapón","taquilla","tarde","tarea","tarifa","tarjeta","tarot","tarro","tarta","tatuaje","tauro","taza","tazón","teatro","techo","tecla","técnica","tejado","tejer","tejido","tela","teléfono","tema","temor","templo","tenaz","tender","tener","tenis","tenso","teoría","terapia","terco","término","ternura","terror","tesis","tesoro","testigo","tetera","texto","tez","tibio","tiburón","tiempo","tienda","tierra","tieso","tigre","tijera","tilde","timbre","tímido","timo","tinta","tío","típico","tipo","tira","tirón","titán","títere","título","tiza","toalla","tobillo","tocar","tocino","todo","toga","toldo","tomar","tono","tonto","topar","tope","toque","tórax","torero","tormenta","torneo","toro","torpedo","torre","torso","tortuga","tos","tosco","toser","tóxico","trabajo","tractor","traer","tráfico","trago","traje","tramo","trance","trato","trauma","trazar","trébol","tregua","treinta","tren","trepar","tres","tribu","trigo","tripa","triste","triunfo","trofeo","trompa","tronco","tropa","trote","trozo","truco","trueno","trufa","tubería","tubo","tuerto","tumba","tumor","túnel","túnica","turbina","turismo","turno","tutor","ubicar","úlcera","umbral","unidad","unir","universo","uno","untar","uña","urbano","urbe","urgente","urna","usar","usuario","útil","utopía","uva","vaca","vacío","vacuna","vagar","vago","vaina","vajilla","vale","válido","valle","valor","válvula","vampiro","vara","variar","varón","vaso","vecino","vector","vehículo","veinte","vejez","vela","velero","veloz","vena","vencer","venda","veneno","vengar","venir","venta","venus","ver","verano","verbo","verde","vereda","verja","verso","verter","vía","viaje","vibrar","vicio","víctima","vida","vídeo","vidrio","viejo","viernes","vigor","vil","villa","vinagre","vino","viñedo","violín","viral","virgo","virtud","visor","víspera","vista","vitamina","viudo","vivaz","vivero","vivir","vivo","volcán","volumen","volver","voraz","votar","voto","voz","vuelo","vulgar","yacer","yate","yegua","yema","yerno","yeso","yodo","yoga","yogur","zafiro","zanja","zapato","zarza","zona","zorro","zumo","zurdo"]["abajur","abaküs","abartı","abdal","abdest","abiye","abluka","abone","absorbe","absürt","acayip","acele","acemi","açıkgöz","adalet","adam","adezyon","adisyon","adliye","adres","afacan","afili","afiş","afiyet","aforizm","afra","ağaç","ağır","ahbap","ahkam","ahlak","ahtapot","aidat","aile","ajan","akademi","akarsu","akbaş","akciğer","akdeniz","akıbet","akıl","akıntı","akide","akrep","akrobasi","aksiyon","akşam","aktif","aktör","aktris","akustik","alaca","albüm","alçak","aldanma","aleni","alet","alfabe","algılama","alıngan","alkış","alkol","alpay","alperen","altın","altüst","altyapı","alyuvar","amade","amatör","amazon","ambalaj","amblem","ambulans","amca","amel","amigo","amir","amiyane","amorti","ampul","anadolu","anahtar","anakonda","anaokul","anapara","anarşi","anatomi","anayasa","anekdot","anestezi","angaje","anka","anket","anlamlı","anne","anomali","anonim","anten","antlaşma","apse","araba","aracı","araf","arbede","arda","arefe","arena","argo","argüman","arkadaş","armoni","aroma","arsa","arsız","artı","artist","aruz","asansör","asayiş","asfalt","asgari","asil","asker","askı","aslan","asosyal","astsubay","asya","aşçı","aşırı","aşure","atabey","ataman","ateş","atmaca","atmosfer","atom","atölye","avcı","avdet","avize","avlu","avokado","avrupa","avukat","ayaz","ayçiçeği","aydın","aygıt","ayna","ayran","ayrıntı","azim","baca","bagaj","bağlantı","bahadır","bahçe","baki","bakkal","baklava","bakteri","balçık","balina","balo","balta","bant","banyo","bardak","barış","başbuğ","başıboş","başkan","başlık","bavul","bayındır","baykuş","bazlama","bedel","begüm","bekçi","bekle","belge","belki","bencil","benek","bengi","benzer","berjer","berk","bermuda","berrak","beşik","beton","beyin","beyoğlu","bıçak","biberiye","bidon","biftek","bihaber","bikini","bilezik","bilinç","bilye","bina","binbaşı","binyıl","bisiklet","bisküvi","bitki","bizzat","bodrum","boğaz","bohça","bolero","boncuk","bonfile","borsa","boru","bostan","boşboğaz","botanik","boya","boykot","boynuz","bozgun","bozkır","bölüm","börek","buçuk","bugün","buğday","buhar","buhran","bulvar","buram","burçak","burs","burun","butik","buzdağı","buzkıran","bücür","büfe","bülten","bütçe","bütün","büyük","cacık","cadı","cahil","cambaz","canhıraş","casus","cazibe","cehalet","cehennem","ceket","cemre","cenin","cennet","cepken","cerrah","cesur","cetvel","cevher","ceylan","cılız","cıva","cilt","cisim","ciyak","coğrafya","cömert","cumba","cüzdan","çabucak","çadır","çağdaş","çağlayan","çağrı","çakmak","çalışkan","çamaşır","çapa","çaput","çarık","çarpan","çarşaf","çayhane","çekirdek","çelebi","çember","çenet","çengel","çerçeve","çerez","çeşit","çeşme","çete","çevre","çeyiz","çeyrek","çığır","çılgın","çıngırak","çift","çiğdem","çikolata","çilek","çimen","çivi","çoban","çocuk","çokgen","çomak","çorba","çözelti","çubuk","çukur","çuval","çürük","dağbaşı","dağılım","daktilo","daldırış","dalga","dalkavuk","damak","damıtma","damla","dana","dandik","danışman","daniska","dantel","dargeçit","darphane","davet","dayı","defter","değer","değirmen","dehşet","delgeç","demir","deneyim","denge","depo","deprem","derdest","dere","derhal","derman","dernek","derviş","desen","destan","dışarı","dışbükey","dijital","dikbaşlı","dilekçe","dimağ","dinamik","dindar","dinleme","dinozor","dipçik","dipnot","direniş","dirsek","disiplin","disk","divriği","dizüstü","dobra","dodurga","doğalgaz","doktor","doküman","dolap","donanım","dondurma","donör","doruk","dosdoğru","dost","dosya","dozer","döküm","dönence","dörtyol","dövme","dram","dublaj","durum","duvak","duyarga","duyma","duyuru","düğme","düğüm","dükkan","dünür","düpedüz","dürbün","düşünür","düzayak","düzeltme","ebeveyn","ebru","ecel","ecnebi","ecza","edat","edilgen","efendi","efor","efsane","egemen","egzersiz","eğrelti","ekarte","ekip","eklem","ekmek","ekol","ekonomi","ekose","ekran","ekvator","elaman","elastik","elbet","elbise","elçi","eldiven","elebaşı","eleştiri","elma","eloğlu","elveda","emare","emekçi","emisyon","emniyet","empati","emsal","emzik","endüstri","enerji","engebe","engin","enişte","enkaz","entari","entegre","entrika","enzim","erdem","ergen","erguvan","erkek","erozyon","ertesi","erzak","esaret","esenlik","eser","eski","esnek","eşarp","eşofman","eşraf","eşya","eşzaman","etik","etken","etkinlik","etüt","evet","evire","evrak","evrim","eyalet","eyvah","ezber","fabrika","fanatik","fanus","fason","fasulye","fatih","fatura","fauna","favori","fayans","fayton","fazıl","fazilet","federal","felsefe","fener","feribot","fersah","fesih","festival","feveran","feza","fıçı","fıldır","fındık","fırça","fırsat","fırtına","fıtık","fidan","fidye","figür","fihrist","fikir","fildişi","filo","filtre","fincan","firuze","fitil","fiyaka","fizik","flaş","flüt","fosil","fren","fukara","futbol","garabet","gariban","garnitür","gazi","gece","gedik","gelenek","gelin","gemi","genç","geniş","geometri","gerçek","gevrek","gezegen","gezgin","geziyolu","gıcık","gıda","gıybet","girdap","girişim","gitar","giyecek","giysi","gizem","gofret","goril","göbek","göçebe","göğüs","gökdelen","gökmen","gökyüzü","gölge","gömlek","gönül","görenek","görkemli","görsel","gösteri","gövde","gözaltı","gözcü","gözdağı","gözleme","gözyaşı","grup","gurbet","gusül","gübre","güfte","gümüş","günaydın","güncel","gündüz","güneş","günyüzü","gürbüz","güvercin","güzel","haber","hacamat","hacim","hademe","hafız","hafriyat","hafta","hakan","hakem","hakikat","haksever","halı","hançer","hane","hangar","hapis","hapşırık","harf","haseki","hasret","hatun","havuç","haylaz","haysiyet","hayvan","hedef","hektar","hemen","hemfikir","hendek","hepsi","hergele","herhangi","hesap","heyecan","heykel","hezimet","hıçkırık","hızölçer","hicviye","hikaye","hikmet","hile","hisse","hobi","hoca","horlama","hormon","hoşbeş","hoşgörü","hoyrat","hörgüç","höyük","hudut","hukuk","hunhar","hurda","huysuz","huzur","hücum","hükümet","hünkar","hüviyet","ırmak","ısıölçer","ısıtıcı","ıspanak","ısrar","ışıldak","ızdırap","ızgara","ibadet","icat","içbükey","içecek","içgüdü","içsel","idman","iftihar","iğne","ihanet","ihbar","ihdas","ihmal","ihracat","ihsan","ikilem","ikindi","ikircik","iklim","iksir","iktibas","ilaç","ilçe","ileri","iletişim","ilgi","ilhak","ilkbahar","ilkokul","ilmek","imkan","imleç","imsak","imtihan","imza","ince","inkar","inşa","ipek","ipucu","irade","irfan","irmik","isabet","iskele","israf","isyan","işçi","işgal","işgüzar","işlem","itibar","itiraf","ivedi","ivme","iyileşme","iyimser","izbandut","izci","izdiham","izin","jakoben","jandarma","jargon","kabadayı","kablo","kabus","kaçamak","kadeh","kadın","kadraj","kafa","kafkas","kağıt","kağnı","kahkaha","kahraman","kahvaltı","kakül","kaldırım","kale","kalibre","kalkan","kalpak","kamış","kamyon","kanat","kandaş","kanepe","kanser","kanun","kaos","kapı","kaplıca","kaptan","karanlık","kardeş","karga","karınca","karmaşa","karşıt","kasırga","kask","kasvet","katkı","katman","kavram","kaygan","kaynakça","kayyum","kedi","kehanet","kekik","kelebek","kenar","kerkenez","kerpiç","kesirli","kesmece","kestane","keşkek","ketçap","keyfiyet","kıble","kıdemli","kılavuz","kılçık","kılıf","kıraç","kırmızı","kırsal","kısayol","kısım","kıskanç","kısmet","kışla","kıvanç","kıvılcım","kıvrık","kıyafet","kıymetli","kızak","kızılcık","kibar","kinaye","kira","kiremit","kirli","kirpik","kişisel","kitap","koçbaşı","kodaman","koğuş","kokteyl","kolaycı","kolbastı","kolonya","koltuk","kolye","kombine","komedyen","komiser","komposto","komşu","komuta","konak","konfor","koni","konsül","kopya","korkusuz","korna","korse","korunak","korvet","kostüm","koşul","koyu","kozmik","köfte","kökensel","köprücük","köpük","kördüğüm","körfez","köstebek","köşegen","kötü","kravat","kriter","kuantum","kudurma","kuluçka","kulübe","kumanya","kumbara","kumlu","kumpir","kumral","kundura","kupa","kupkuru","kuramsal","kurbağa","kurdele","kurgu","kurmay","kurşun","kurtuluş","kurultay","kurye","kusursuz","kuşak","kuşbaşı","kuşkulu","kutlama","kutsal","kutup","kuver","kuyruk","kuzey","kuzgun","küçük","külçe","külfet","külliye","kültürel","kümes","künefe","küresel","kütle","lahana","lahmacun","lamba","lansman","lavaş","layık","leğen","levent","leziz","lezzet","lider","likide","liman","liste","litre","liyakat","lodos","lokanta","lokman","lokum","lunapark","lütfen","lüzum","nokta","mabet","macera","macun","madalya","madde","madem","mağara","mağdur","mağfiret","mağlup","mahalle","mahcup","mahir","mahkeme","mahlas","mahrum","mahsul","makas","makbuz","makine","makro","maksat","makul","maliye","manav","mangal","manidar","manken","mantık","manzara","mareşal","margarin","marifet","market","marmelat","masaüstü","masmavi","masraf","masum","matah","materyal","matrak","maval","mavra","maydanoz","mayhoş","maytap","mazbata","mazeret","mazlum","mazot","mazur","meblağ","mebus","mecaz","mecbur","meclis","mecmua","mecnun","meçhul","medeni","mehtap","mekanik","melodi","meltem","memur","mendil","menekşe","menteşe","meraklı","mercek","merdiven","merhaba","merinos","merkez","mermi","mert","mesafe","mesele","mesken","meslek","meşale","meşgul","meşhur","metafor","metin","metre","mevcut","mevkidaş","meydan","meyil","meyve","meziyet","mezun","mıknatıs","mısra","mızıka","miğfer","mihrak","mikrofon","miktar","milat","milli","mimar","minare","mineral","minik","minyon","mirliva","misafir","miskin","miting","miyop","mizah","mobilya","model","monitör","morötesi","motive","motor","mozaik","muavin","mucize","muhafız","muhteşem","mukayese","mumya","musluk","muşamba","mutabık","mutfak","mutlu","muzaffer","muzdarip","mübarek","mücadele","müdür","müfredat","müftü","mühendis","mühim","mühlet","mükemmel","mülk","mümkün","mümtaz","müsrif","müstesna","müşahit","müşteri","mütercim","müthiş","müze","müzik","nabız","nadas","nadir","nahoş","nakarat","nakış","nalbur","namlu","namus","nankör","nargile","narkoz","nasıl","nasip","naylon","nazar","nazım","nazik","neden","nefes","negatif","neon","neptün","nerede","nesil","nesnel","neşeli","netice","nevresim","neyse","neyzen","nezaket","nezih","nezle","nicel","nilüfer","nimet","nisan","nispet","nitekim","nizam","nohut","noksan","normal","nostalji","noter","nöbet","numara","numune","nutuk","nüfus","obabaşı","obez","obje","ocak","odun","ofansif","ofis","oğlak","oğuz","okçu","oklava","oksijen","okul","okumuş","okutman","okuyucu","okyanus","olağan","olanak","olası","olay","olgun","olimpik","olumlu","omlet","omurga","onarım","onursal","opera","optik","oral","orantı","ordu","organik","orijin","orkide","orman","orta","oruç","otağ","otantik","otel","otoban","otogar","otomobil","otonom","otopark","otorite","otoyol","oturum","oyuk","oyuncak","ozan","ödeme","ödenek","ödev","ödül","ödünç","öfke","öğlen","öğrenci","öğün","öğütücü","öksürük","ölçme","ölçü","ölümsüz","ömür","önayak","öncü","önder","önem","önerge","öngörü","önlük","önsezi","öpücük","ördek","örgü","örtbas","örtme","örtü","örümcek","örüntü","öteberi","öteki","övünç","öykü","öyleyse","özçekim","özdeyiş","özel","özenti","özerk","özgürlük","özlem","özlü","özne","özsever","özümseme","özür","özveri","pabuç","padişah","palamut","palmiye","palto","palyaço","pamuk","panayır","pancar","panda","panel","panik","panjur","pankart","pano","pansuman","pantolon","panzehir","papatya","papyon","paraşüt","parça","pardösü","parfüm","parıltı","parkur","parmak","parodi","parsel","partner","pasaport","pasif","paskalya","pastırma","paşa","patates","paten","patika","patlıcan","patolog","patron","payanda","paydaş","payidar","paylaşma","paytak","peçete","pedal","peder","pehlivan","pekala","pekmez","pelerin","pelikan","pelüş","pembe","pena","pencere","pense","perçin","perde","pergel","perişan","peron","personel","perşembe","peruk","pervane","pespaye","pestil","peşin","petek","petrol","petunya","peynir","peyzaj","pınar","pırasa","pırlanta","pide","pikap","piknik","pilav","piliç","pilot","pipet","pipo","piramit","pirinç","pirzola","pist","pişik","pişman","piyasa","piyes","plaj","plaket","planlama","platform","plazma","podyum","poğaça","polat","polen","politika","pompa","popüler","porselen","portakal","posa","poster","poşet","poyraz","pozitif","pranga","pratik","prenses","prim","problem","profil","program","proje","protokol","prova","puan","pudra","pusula","püre","pürüz","püstül","püsür","racon","radar","radikal","radyo","rafadan","rafine","rağbet","rahat","rahle","rakam","raket","rakip","rakun","ralli","rampa","randevu","ranza","rapor","rastgele","rasyonel","razı","realite","reçine","refah","referans","refik","reform","rehber","rehin","reis","rekabet","reklam","rekor","rektör","renk","resim","resmen","restoran","retorik","revaç","revize","reyon","rezalet","rezerv","rezil","rıhtım","rıza","ritim","ritüel","rivayet","robot","roman","rota","rozet","röportaj","rötar","ruble","ruhban","ruhsat","rulet","rulo","runik","rutin","rutubet","rüşvet","rütbe","rüya","rüzgar","sabah","sabıka","sabit","sabun","saçma","sade","sadık","safahat","safdil","safkan","sağanak","sağduyu","sağlam","saha","sahiden","sahne","sakal","sakız","sakin","saklama","saksağan","salamura","salça","salgı","salınım","salkım","salon","saltanat","sanatçı","sancak","sandalye","saniye","saplantı","sapsız","saray","sarışın","sarkık","sarmaşık","satır","savaşım","savunma","saydam","sayfa","saygın","sayısal","sebep","seçenek","seçim","seçkin","seçmen","seda","sedir","sedye","sefer","sehpa","sekizgen","selektör","selvi","semavi","sembol","seminer","senaryo","sendika","senkron","sensör","sentez","sepet","seramik","serbest","serdar","seremoni","sergi","serhat","serin","sermaye","serpuş","sersem","serüven","servis","sesli","sesteş","sevap","seviye","seyahat","seyirci","sezon","sıcak","sıfat","sıhhi","sınanma","sınır","sıradan","sırdaş","sırma","sırtüstü","sızgıt","siftah","sigorta","sihirbaz","silah","silecek","silindir","simetri","simge","simit","sincap","sindirim","sinema","sinirli","sipariş","sirke","siroz","sistem","sivilce","siyasi","slogan","soba","sofra","soğuk","sohbet","sokak","solfej","solunum","somut","sonbahar","sonraki","sonsuz","sorunsuz","sosyete","soyağacı","soydaş","soygun","soytarı","söğüş","sömürge","sönük","söylem","sözcük","sözde","spatula","spektrum","spiker","spiral","sponsor","sporcu","sprey","stabil","statü","stok","stopaj","strateji","subay","sucuk","suçüstü","suhulet","sulama","sungur","sunucu","surat","susam","suskun","sükse","sükut","sülale","sünger","süpürge","sürahi","süreç","sürgün","sürüm","süsleme","sütanne","sütlaç","sütun","süvari","şahane","şahbaz","şahit","şahsiyet","şakıma","şaklaban","şakrak","şamar","şampiyon","şanslı","şantiye","şapka","şarkıcı","şartname","şaşırma","şaşkın","şatafat","şayet","şebeke","şefkat","şeftali","şehir","şehvet","şeker","şekil","şelale","şema","şemsiye","şerbet","şeref","şerit","şımarık","şıpıdık","şifre","şimdi","şimşek","şipşak","şirin","şişe","şişirme","şofben","şöhret","şölen","şüphe","tabaka","tabela","tabure","tadilat","taharet","tahıl","tahkim","tahlil","tahmin","tahrifat","tahsilat","tahta","taklit","takoz","taksici","taktik","takvim","talebe","talip","tamamen","tamirci","tampon","tamtakır","tandır","tanecik","tanıtım","tanrı","tansiyon","tapan","tapınak","taptaze","tapu","tarafgir","tarhana","tarım","tarih","tarla","tartak","tarumar","tasarım","tasdik","taslak","tastamam","taşeron","taşınmaz","taşra","tatava","tatbikat","tatil","tatlı","tavsiye","tavşan","tavuk","taze","taziye","tazminat","tebeşir","tebrik","tecrübe","teçhizat","tedarik","tedbir","teftiş","teğet","teğmen","tehdit","tehlike","tekdüze","tekerlek","tekme","teknik","tekrar","telef","telsiz","telve","temas","tembel","temiz","temkin","tempo","temsilci","tendon","teneke","tenha","tenkit","tepegöz","tepki","terazi","terbiye","tercih","tereyağı","terfi","terim","terminal","tersane","tertip","tesadüf","tescil","tesir","teslimat","tespit","testere","teşekkür","teşhir","teşrif","teşvik","teyze","tezahür","tezgah","tıbbi","tıkaç","tıkışık","tıknaz","tılsım","tıpkı","tıraş","tırışka","tırmanış","tırnak","tırpan","tıslama","ticaret","tilki","tiryaki","titreşim","tohum","tokat","tolere","tomar","tombak","tomurcuk","topaç","toplum","toprak","toptan","toraman","torpido","tortu","tosbağa","toynak","tören","trafik","trajedi","tramvay","transfer","tribün","triko","tugay","tuğla","tuğrul","tuhaf","tulumba","tunç","turan","turkuaz","turnusol","turşu","turuncu","tutanak","tutkal","tutsak","tutum","tuyuğ","tuzlu","tüccar","tüfek","tükenmez","tülbent","tümleç","tünel","türbin","türev","türk","tüzük","ucube","ucuz","uçak","uçurtma","ufuk","uğrak","uğur","ukala","ulaşım","ulema","ulus","ulvi","umursama","umut","unutkan","uslu","ustabaşı","ustura","usul","utangaç","uyanık","uyarı","uydu","uygar","uygulama","uykusuz","uysal","uyuşma","uzantı","uzay","uzgören","uzlaşma","uzman","uzun","ücra","ücret","üçbudak","üçgen","üçkağıt","üçleme","üfürük","ülke","ümit","üniforma","ünite","ünlem","üretken","ürün","üslup","üstel","üstün","üşengeç","üşüme","ütopya","üvey","üzengi","üzgün","üzüm","vagon","vaka","vakfiye","vakıf","vakit","vakum","vapur","varil","varlık","varsayım","varyemez","vasıta","vasiyet","vatandaş","vazife","vazo","veciz","vefa","vehim","veliaht","veresiye","verimli","verkaç","vernik","vertigo","vesait","vesika","vestiyer","veznedar","vicdan","vilayet","virane","virgül","vişne","vites","vokal","volkan","vurma","vurucu","vücut","yabancı","yabgu","yağış","yağlı","yağmur","yakamoz","yakın","yaklaşık","yalçın","yalıtım","yaman","yanardağ","yangın","yanıt","yankı","yanlış","yansıma","yapay","yapboz","yapımcı","yaprak","yaratık","yarbay","yardım","yargıç","yarıçap","yasemin","yastık","yaşam","yatak","yatırım","yavru","yaygara","yayıncı","yayla","yazılım","yekpare","yekvücut","yelkovan","yelpaze","yemek","yemiş","yengeç","yeniçeri","yeraltı","yerküre","yerleşke","yeryüzü","yeşil","yetenek","yetkili","yığınak","yıkama","yılbaşı","yıldırım","yılkı","yılmaz","yırtıcı","yiğit","yoğurt","yokuş","yolcu","yoldaş","yolgeçen","yolkesen","yolüstü","yordam","yorgan","yorumcu","yosun","yöndeş","yönetim","yönlü","yöntem","yöresel","yörünge","yufka","yukarı","yumruk","yumurta","yuvarlak","yücelme","yükçeker","yüklem","yüksek","yürek","yürütme","yüzde","yüzeysel","yüzgeç","yüzüstü","yüzyıl","zabıta","zafer","zahmet","zambak","zaptiye","zarafet","zaruret","zeka","zekice","zemberek","zemin","zencefil","zeplin","zeytin","zıbın","zılgıt","zımbırtı","zımpara","zıpkın","zigon","zihinsel","zihniyet","zincir","zindan","zirzop","ziyaret","ziynet","zoraki","zorlu","zorunlu","züğürt","zümre"]const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
const c = require('compact-encoding')
const b4a = require('b4a')

const KeyChain = require('./lib/keychain')
const { sign, verify, hash } = require('./lib/crypto')

const {
  ProofEncoding,
  AttestedData,
  AttestedDevice,
  ReceiptEncoding
} = require('./lib/encoding')

const PROOF_VERSION = 1
const KEET_TYPE = 5338

const NS_PROFILE_DISC_ENC = hash(b4a.from('profile discovery'))

module.exports = class IdentityKey {
  constructor (keyChain) {
    this.keyChain = keyChain

    this.identityKeyPair = this.keyChain.get(identityKeyPath(0))
    this.profileDiscoveryKeyPair = this.keyChain.get(discoveryCorePath(0))
  }

  static generateMnemonic () {
    return KeyChain.generateMnemonic()
  }

  static deriveSeed (mnemonic) {
    return KeyChain.deriveSeed(mnemonic)
  }

  get identityPublicKey () {
    return this.identityKeyPair.publicKey
  }

  get profileDiscoveryPublicKey () {
    return this.profileDiscoveryKeyPair.publicKey
  }

  getProfileDiscoveryEncryptionKey () {
    return this.keyChain.getSymmetricKey(encryptionKeyPath(NS_PROFILE_DISC_ENC))
  }

  getEncryptionKey (profileKey) {
    return this.keyChain.getSymmetricKey(encryptionKeyPath(profileKey))
  }

  bootstrap (device) {
    return IdentityKey.bootstrap({ identity: this.identityKeyPair }, device)
  }

  clear () {
    this.keyChain.clear()
    this.identityKeyPair.secretKey.fill(0)
    this.profileDiscoveryKeyPair.secretKey.fill(0)
  }

  static async bootstrap ({ identity, seed, mnemonic }, device) {
    if (!identity) {
      const identityPath = identityKeyPath(0) // accountIndex unused for now
      identity = await KeyChain.from({ seed, mnemonic }, identityPath)
    }

    const proof = {
      version: PROOF_VERSION,
      epoch: Date.now(),
      identity: identity.publicKey,
      chain: []
    }

    return IdentityKey.attestDevice(device, identity, proof)
  }

  static attestDevice (publicKey, parent, proof) {
    if (!proof) return IdentityKey.bootstrap({ identity: parent }, publicKey)

    if (b4a.isBuffer(proof)) {
      proof = c.decode(ProofEncoding, proof)
    }

    if (proof.version === 0) {
      throw new Error('Version 0 proofs are not supported')
    }

    const signable = c.encode(AttestedDevice, {
      epoch: proof.epoch,
      identity: proof.identity,
      device: publicKey
    })

    const signature = sign(signable, parent)

    proof.chain.push({ publicKey, signature })

    return c.encode(ProofEncoding, proof)
  }

  static attestData (attestedData, keyPair, proof) {
    if (attestedData === null) throw new Error('Data is not attestable')

    if (b4a.isBuffer(proof)) {
      proof = c.decode(ProofEncoding, proof)
    }

    if (proof && proof.version === 0) {
      throw new Error('Version 0 proofs are not supported')
    }

    if (!proof) {
      proof = {
        version: PROOF_VERSION,
        epoch: Date.now(),
        identity: keyPair.publicKey,
        chain: []
      }
    }

    const signable = c.encode(AttestedData, {
      epoch: proof.epoch,
      identity: proof.identity,
      data: hash(attestedData)
    })

    proof.data = { signature: sign(signable, keyPair) }

    return c.encode(ProofEncoding, proof)
  }

  static async from ({ seed, mnemonic }) {
    const keyChain = await KeyChain.from({ seed, mnemonic })

    return new IdentityKey(keyChain)
  }

  static verify (proof, attestedData, opts = {}) {
    if (b4a.isBuffer(proof)) {
      proof = c.decode(ProofEncoding, proof)
    }

    if (!validateProof(proof, attestedData, opts)) {
      return null
    }

    const { epoch, identity, chain } = proof

    const candidate = getLastKey(chain) || identity

    if (opts.expectedDevice) {
      if (!b4a.equals(candidate, opts.expectedDevice)) return null
    }

    let parent = identity

    // verify chain
    for (let i = 0; i < chain.length; i++) {
      const { publicKey, signature } = chain[i]

      const signable = c.encode(AttestedDevice, {
        epoch,
        identity,
        device: publicKey
      })

      if (!verify(signable, signature, parent)) {
        return null
      }

      parent = publicKey
    }

    if (proof.data) {
      const signable = c.encode(AttestedData, {
        epoch,
        identity,
        data: hash(attestedData)
      })

      if (!verify(signable, proof.data.signature, parent)) {
        return null
      }
    }

    const receipt = c.encode(ReceiptEncoding, { epoch })

    return {
      receipt,
      identityPublicKey: identity,
      devicePublicKey: candidate
    }
  }
}

function validateProof (proof, attestedData, opts = {}) {
  // version 0 is ignored
  if (proof.version === 0) return false

  // validate version
  if (proof.version > PROOF_VERSION) return false

  // verify epoch
  if (opts.receipt) {
    const { epoch } = c.decode(ReceiptEncoding, opts.receipt)
    if (proof.epoch < epoch) return false
  }

  // verify identity
  if (opts.expectedIdentity) {
    if (!b4a.equals(proof.identity, opts.expectedIdentity)) return false
  }

  return validateAttestedData(proof.data, attestedData)
}

function validateAttestedData (data, attestedData) {
  if (!data && attestedData) return false
  return true
}

function getLastKey (chain) {
  if (!chain.length) return null

  const last = chain[chain.length - 1]
  return last.publicKey
}

// slip48 derivations:
// https://github.com/satoshilabs/slips/blob/master/slip-0048.md

function keyPath (accountIndex, index) {
  // https://github.com/bitcoin/bips/blob/master/bip-0043.mediawiki
  const purpose = 48 // SLIP-48 wallet
  const role = 0 // owner

  return [purpose, KEET_TYPE, role, accountIndex, index]
}

// identityKey -> m/48'/keet'/0'/0'

function identityKeyPath (accountIndex) {
  return keyPath(accountIndex, 0)
}

// identityKey -> m/48'/keet'/0'/1'

function discoveryCorePath (accountIndex) {
  return keyPath(accountIndex, 1)
}

// slip21 derivations
// https://github.com/satoshilabs/slips/blob/master/slip-0021.md

function symmetricPath (...path) {
  const purpose = 'SLIP-0021' // SLIP-21 wallet
  const namespace = 'keet-identity-key' // keet

  return [purpose, namespace, ...path]
}

// encryptionKey  -> m/SLIP-10/keet-identity-key/account/"encryption key"

function encryptionKeyPath (profileKey) {
  return symmetricPath(b4a.toString(profileKey, 'hex'), 'encryption key')
}
const sodium = require('sodium-universal')
const b4a = require('b4a')

module.exports = {
  sign,
  verify,
  hash: blake2b
}

function sign (signable, keyPair) {
  const signature = b4a.alloc(sodium.crypto_sign_BYTES)
  sodium.crypto_sign_detached(signature, signable, keyPair.secretKey)

  return signature
}

function verify (signable, signature, publicKey) {
  return sodium.crypto_sign_verify_detached(signature, signable, publicKey)
}

function blake2b (data, output = b4a.alloc(32)) {
  sodium.crypto_generichash(output, data)
  return output
}
const c = require('compact-encoding')

const ATTESTED_DEVICE = 0
const ATTESTED_DATA = 1

const Epoch = {
  preencode (state, e) {
    c.uint64.preencode(state, Math.floor(e / 1000))
  },
  encode (state, e) {
    c.uint64.encode(state, Math.floor(e / 1000))
  },
  decode (state) {
    return c.uint64.decode(state) * 1000
  }
}

const AttestedDevice = {
  preencode (state, a) {
    c.uint8.preencode(state, ATTESTED_DEVICE)
    Epoch.preencode(state, a.epoch)
    c.fixed32.preencode(state, a.identity)
    c.fixed32.preencode(state, a.device)
  },
  encode (state, a) {
    c.uint8.encode(state, ATTESTED_DEVICE)
    Epoch.encode(state, a.epoch)
    c.fixed32.encode(state, a.identity)
    c.fixed32.encode(state, a.device)
  },
  decode (state) {
    throw new Error('Signed data should only be encoded')
  }
}

const AttestedData = {
  preencode (state, a) {
    c.uint8.preencode(state, ATTESTED_DATA)
    Epoch.preencode(state, a.epoch)
    c.fixed32.preencode(state, a.identity)
    c.fixed32.preencode(state, a.data)
  },
  encode (state, a) {
    c.uint8.encode(state, ATTESTED_DATA)
    Epoch.encode(state, a.epoch)
    c.fixed32.encode(state, a.identity)
    c.fixed32.encode(state, a.data)
  },
  decode (state) {
    throw new Error('Signed data should only be encoded')
  }
}

const DeviceAttestation = {
  preencode (state, a) {
    c.fixed32.preencode(state, a.publicKey)
    c.fixed64.preencode(state, a.signature)
  },
  encode (state, a) {
    c.fixed32.encode(state, a.publicKey)
    c.fixed64.encode(state, a.signature)
  },
  decode (state) {
    return {
      publicKey: c.fixed32.decode(state),
      signature: c.fixed64.decode(state)
    }
  }
}

const DeviceAttestationArray = c.array(DeviceAttestation)

const DataAttestation = {
  preencode (state, a) {
    c.fixed64.preencode(state, a.signature)
  },
  encode (state, a) {
    c.fixed64.encode(state, a.signature)
  },
  decode (state) {
    return {
      signature: c.fixed64.decode(state)
    }
  }
}

const ProofEncoding = {
  preencode (state, proof) {
    c.uint.preencode(state, proof.version)
    Epoch.preencode(state, proof.epoch)
    c.fixed32.preencode(state, proof.identity)
    DeviceAttestationArray.preencode(state, proof.chain)

    let flags = 0
    if (proof.data) flags |= 1
    c.uint.preencode(state, flags)

    if (proof.data) DataAttestation.preencode(state, proof.data)
  },
  encode (state, proof) {
    c.uint.encode(state, proof.version)
    Epoch.encode(state, proof.epoch)
    c.fixed32.encode(state, proof.identity)
    DeviceAttestationArray.encode(state, proof.chain)

    let flags = 0
    if (proof.data) flags |= 1
    c.uint.encode(state, flags)

    if (proof.data) DataAttestation.encode(state, proof.data)
  },
  decode (state) {
    const version = c.uint.decode(state)

    // ignore v0 proofs
    if (version === 0) {
      return {
        version: 0,
        epoch: 0,
        identity: null,
        chain: [],
        data: null
      }
    }

    const epoch = Epoch.decode(state)
    const identity = c.fixed32.decode(state)
    const chain = DeviceAttestationArray.decode(state)

    const flags = c.uint.decode(state)
    const data = flags & 1 ? DataAttestation.decode(state) : null

    return {
      version,
      epoch,
      identity,
      chain,
      data
    }
  }
}

const ReceiptEncoding = {
  preencode (state, receipt) {
    Epoch.preencode(state, receipt.epoch)
  },
  encode (state, receipt) {
    Epoch.encode(state, receipt.epoch)
  },
  decode (state) {
    return {
      epoch: Epoch.decode(state)
    }
  }
}

module.exports = {
  ATTESTED_DEVICE,
  ATTESTED_DATA,
  AttestedDevice,
  AttestedData,
  ProofEncoding,
  ReceiptEncoding
}
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const assert = require('nanoassert')
const b4a = require('b4a')
const { HMAC } = require('sodium-hmac')
const bip39 = require('bip39-mnemonic')

const { sign } = require('./crypto')

const MASTER_CHAIN_CODE = b4a.from('ed25519 seed')
const MASTER_SYMMETRIC_CODE = b4a.from('Symmetric key seed')

const HARDENED_OFFSET = 0x80000000

class KeyChain {
  constructor (seed) {
    this.seed = seed

    this._buffer = b4a.alloc(64)

    this.chainKey = this._buffer.subarray(0, 32)
    this.chainCode = this._buffer.subarray(32)

    this.publicKey = b4a.alloc(sodium.crypto_sign_PUBLICKEYBYTES)
    this.secretKey = b4a.alloc(sodium.crypto_sign_SECRETKEYBYTES)

    this._initialise()
  }

  static generateMnemonic () {
    return bip39.generateMnemonic()
  }

  static deriveSeed (mnemonic) {
    return bip39.mnemonicToSeed(mnemonic)
  }

  static async from ({ mnemonic, seed }, path) {
    assert(mnemonic || seed, 'No mnemonic or seed was passed.')

    if (!seed) seed = await KeyChain.deriveSeed(mnemonic)

    const key = new KeyChain(seed)

    if (!path) return key

    return key.get(path)
  }

  getSymmetricKey (path) {
    const buffer = b4a.alloc(64)

    const chainKey = buffer.subarray(0, 32)
    const key = buffer.subarray(32)

    HMAC.sha512(this.seed, MASTER_SYMMETRIC_CODE, buffer)

    for (const step of path) {
      const label = b4a.alloc(step.length + 1)
      b4a.write(label, step, 1, 'utf8')

      HMAC.sha512(label, chainKey, buffer)
    }

    return key
  }

  get isKeychain () {
    return true
  }

  _initialise () {
    HMAC.sha512(this.seed, MASTER_CHAIN_CODE, this._buffer)
    sodium.crypto_sign_seed_keypair(this.publicKey, this.secretKey, this.chainKey)
  }

  clear () {
    this.secretKey.fill(0)
    this.chainKey.fill(0)
    this.chainCode.fill(0)
  }

  get (path) {
    return this.derive(path)
  }

  sign (signable) {
    return sign(signable, this)
  }

  derive (path) {
    const buffer = b4a.from(this._buffer)

    const chainKey = buffer.subarray(0, 32)
    const chainCode = buffer.subarray(32)

    for (const step of path) {
      const index = ensureHardened(step) // hardened indices are >= 2^31
      HMAC.sha512(encodeDerivationData(chainKey, index), chainCode, buffer)
    }

    return createKeyPair(chainKey)
  }
}

module.exports = KeyChain

function createKeyPair (seed) {
  if (!seed) throw new Error('No seed provided')

  const publicKey = b4a.alloc(sodium.crypto_sign_PUBLICKEYBYTES)
  const secretKey = b4a.alloc(sodium.crypto_sign_SECRETKEYBYTES)

  sodium.crypto_sign_seed_keypair(publicKey, secretKey, seed)

  return {
    publicKey,
    secretKey
  }
}

function encodeDerivationData (key, step) {
  const state = { buffer: b4a.alloc(37), start: 0, end: 37 }

  c.uint8.encode(state, 0)
  c.fixed32.encode(state, key)
  state.buffer.writeUInt32BE(step, state.start)

  state.buffer[33] |= 0x80

  return state.buffer
}

function ensureHardened (n) {
  if (n >= HARDENED_OFFSET) return n
  return n + HARDENED_OFFSET
}
{
  "name": "keet-identity-key",
  "version": "3.2.0",
  "description": "Hierarchical Deterministic Keys for Keet Identities",
  "main": "index.js",
  "scripts": {
    "test": "standard && brittle test/*.js"
  },
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "devDependencies": {
    "brittle": "^3.3.2",
    "hypercore-crypto": "^3.4.0",
    "standard": "^17.1.0"
  },
  "dependencies": {
    "b4a": "^1.6.4",
    "bip39-mnemonic": "^2.2.0",
    "compact-encoding": "^3.0.0",
    "nanoassert": "^2.0.0",
    "sodium-hmac": "^2.0.1",
    "sodium-universal": "^5.0.1"
  },
  "files": [
    "lib/*"
  ],
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/keet-identity-key.git"
  },
  "bugs": {
    "url": "https://github.com/holepunchto/keet-identity-key/issues"
  },
  "homepage": "https://github.com/holepunchto/keet-identity-key#readme"
}
module.exports = assert

class AssertionError extends Error {}
AssertionError.prototype.name = 'AssertionError'

/**
 * Minimal assert function
 * @param  {any} t Value to check if falsy
 * @param  {string=} m Optional assertion error message
 * @throws {AssertionError}
 */
function assert (t, m) {
  if (!t) {
    var err = new AssertionError(m)
    if (Error.captureStackTrace) Error.captureStackTrace(err, assert)
    throw err
  }
}
{
  "name": "nanoassert",
  "version": "2.0.0",
  "description": "Nanoscale assertion module",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "tape": "^4.9.1"
  },
  "scripts": {
    "test": "tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/emilbayes/nanoassert.git"
  },
  "keywords": [
    "assert",
    "unassert",
    "power-assert",
    "tiny",
    "nano",
    "pico"
  ],
  "author": "Emil Bay <github@tixz.dk>",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/emilbayes/nanoassert/issues"
  },
  "homepage": "https://github.com/emilbayes/nanoassert#readme"
}
module.exports = require.addon.bind(require)
{
  "name": "require-addon",
  "version": "1.2.0",
  "description": "Import native addons across JavaScript runtimes",
  "exports": {
    "./package": "./package.json",
    ".": {
      "bare": "./lib/bare.js",
      "node": "./lib/node.js",
      "default": "./lib/default.js"
    }
  },
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    },
    "url": {
      "bare": "bare-url",
      "default": "url"
    }
  },
  "files": [
    "lib"
  ],
  "scripts": {
    "test": "npm run lint && npm run test:bare && npm run test:node",
    "test:bare": "bare test.js",
    "test:node": "node test.js",
    "lint": "prettier --check .",
    "format": "prettier --write ."
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/require-addon.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/require-addon/issues"
  },
  "homepage": "https://github.com/holepunchto/require-addon#readme",
  "engines": {
    "bare": ">=1.10.0"
  },
  "dependencies": {
    "bare-addon-resolve": "^1.3.0"
  },
  "devDependencies": {
    "bare-bundle": "^1.8.1",
    "bare-bundle-evaluate": "^1.1.0",
    "bare-fs": "^4.0.0",
    "bare-path": "^3.0.0",
    "bare-url": "^2.1.0",
    "brittle": "^3.7.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
const sodium = require('sodium-universal')

module.exports = {
  init: sodium.crypto_hash_sha256_init,
  update: sodium.crypto_hash_sha256_update,
  final: sodium.crypto_hash_sha256_final,
  BYTES: sodium.crypto_hash_sha256_BYTES,
  STATEBYTES: sodium.crypto_hash_sha256_STATEBYTES
}
const sodium = require('sodium-universal')

module.exports = {
  init: sodium.crypto_hash_sha512_init,
  update: sodium.crypto_hash_sha512_update,
  final: sodium.crypto_hash_sha512_final,
  BYTES: sodium.crypto_hash_sha512_BYTES,
  STATEBYTES: sodium.crypto_hash_sha512_STATEBYTES
}
const b4a = require('b4a')

const sha256 = require('./hash/sha256')
const sha512 = require('./hash/sha512')

class HMAC {
  constructor (hash, key) {
    this.hash = hash
    this.length = hash.BYTES

    this._blocksize = 2 * hash.BYTES

    this._initialised = false

    this.state = b4a.alloc(hash.STATEBYTES)
    this.pad = b4a.alloc(this._blocksize)

    if (key) this.init(key)
  }

  init (key) {
    if (this._initialised) {
      throw new Error('Already initialised, call final first')
    }

    if (key.length > this._blocksize) {
      this.hash.init(this.state)
      this.hash.update(this.state, key)
      this.hash.final(this.state, this.pad.subarray(0, this.length))
    } else {
      this.pad.set(key)
    }

    bufferByteXor(this.pad, 0x36)

    this.hash.init(this.state)
    this.hash.update(this.state, this.pad)

    bufferByteXor(this.pad, 0x5c ^ 0x36)

    this._initialised = true

    return this
  }

  update (data) {
    if (!this._initialised) {
      throw new Error('First initialise with a key')
    }

    this.hash.update(this.state, data)
    return this
  }

  final (output = b4a.alloc(this.length)) {
    if (!this._initialised) {
      throw new Error('First initialise with a key')
    }

    const out = output.byteLength === this.length
      ? output
      : output.subarray(0, this.hash.BYTES)

    this.hash.final(this.state, out)

    this.hash.init(this.state)
    this.hash.update(this.state, this.pad)
    this.hash.update(this.state, out)
    this.hash.final(this.state, out)

    this.pad.fill(0)
    this.state.fill(0)

    this._initialised = false

    return out
  }

  static sha256 (data, key, output) {
    const hmac = new HMAC(sha256, key)
    return hmac.update(data).final(output)
  }

  static sha512 (data, key, output) {
    const hmac = new HMAC(sha512, key)
    return hmac.update(data).final(output)
  }
}

module.exports = {
  HMAC,
  sha256,
  sha512
}

function bufferByteXor (output, byte) {
  for (let i = 0; i < output.byteLength; i++) {
    output[i] ^= byte
  }

  return output
}
{
  "name": "sodium-hmac",
  "version": "2.1.0",
  "description": "HMAC utility",
  "main": "index.js",
  "scripts": {
    "test": "standard && brittle test/*.js"
  },
  "author": "",
  "license": "Apache-2.0",
  "dependencies": {
    "b4a": "^1.6.6",
    "sodium-universal": "^5.0.1"
  },
  "devDependencies": {
    "brittle": "^3.4.0",
    "standard": "^17.1.0"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sodium-hmac.git"
  },
  "files": [
    "index.js",
    "hash/*"
  ],
  "bugs": {
    "url": "https://github.com/holepunchto/sodium-hmac/issues"
  },
  "homepage": "https://github.com/holepunchto/sodium-hmac#readme"
}
require.addon = require('require-addon')
module.exports = require.addon('.', __filename)
const assert = require('assert')
const binding = require('./binding')
const { isNode } = require('which-runtime')

const OPTIONAL = Buffer.from(new ArrayBuffer(0))

module.exports = exports = { ...binding }

// memory

exports.sodium_memzero = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  binding.sodium_memzero(buf)
}

exports.sodium_mlock = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  const res = binding.sodium_mlock(buf)

  if (res !== 0) throw new Error('memory lock failed')
}

exports.sodium_munlock = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  const res = binding.sodium_munlock(buf)

  if (res !== 0) throw new Error('memory unlock failed')
}

exports.sodium_malloc = function (size) {
  assert(size >= 0, 'invalid size')

  const buf = Buffer.from(binding.sodium_malloc(size))
  buf.secure = true
  return buf
}

exports.sodium_free = function (buf) {
  if (!buf || !buf.secure) return

  binding.sodium_free(buf.buffer)
}

exports.sodium_mprotect_noaccess = function (buf) {
  const res = binding.sodium_mprotect_noaccess(buf.buffer)

  if (res !== 0) throw new Error('failed to lock buffer')
}

exports.sodium_mprotect_readonly = function (buf) {
  const res = binding.sodium_mprotect_readonly(buf.buffer)

  if (res !== 0) throw new Error('failed to unlock buffer')
}

exports.sodium_mprotect_readwrite = function (buf) {
  const res = binding.sodium_mprotect_readwrite(buf.buffer)

  if (res !== 0) throw new Error('failed to unlock buffer')
}

// crypto_randombytes

exports.randombytes_buf = function (buffer) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')

  binding.randombytes_buf(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

exports.randombytes_buf_deterministic = function (buffer, seed) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    seed.byteLength === binding.randombytes_SEEDBYTES,
    "seed must be 'randombytes_SEEDBYTES' bytes"
  )

  binding.randombytes_buf_deterministic(
    buffer.buffer,
    buffer.byteOffset,
    buffer.byteLength,

    seed.buffer,
    seed.byteOffset,
    seed.byteLength
  )
}

// sodium_helpers

exports.sodium_memcmp = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  return binding.sodium_memcmp(a, b)
}

exports.sodium_add = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  binding.sodium_add(a, b)
}

exports.sodium_sub = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  binding.sodium_sub(a, b)
}

exports.sodium_compare = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  return binding.sodium_compare(a, b)
}

exports.sodium_is_zero = function (buffer, length) {
  if (length === undefined) length = buffer.byteLength

  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(length >= 0 && length <= buffer.byteLength, 'invalid length')

  return binding.sodium_is_zero(buffer, length)
}

exports.sodium_pad = function (buffer, unpaddedBuflen, blockSize) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(unpaddedBuflen <= buffer.byteLength, 'unpadded length cannot exceed buffer length')
  assert(blockSize <= buffer.byteLength, 'block size cannot exceed buffer length')
  assert(blockSize >= 1, 'block size must be at least 1 byte')
  assert(
    buffer.byteLength >= unpaddedBuflen + (blockSize - (unpaddedBuflen % blockSize)),
    'buf not long enough'
  )

  return binding.sodium_pad(buffer, unpaddedBuflen, blockSize)
}

exports.sodium_unpad = function (buffer, paddedBuflen, blockSize) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(paddedBuflen <= buffer.byteLength, 'unpadded length cannot exceed buffer length')
  assert(blockSize <= buffer.byteLength, 'block size cannot exceed buffer length')
  assert(blockSize >= 1, 'block size must be at least 1 byte')

  return binding.sodium_unpad(buffer, paddedBuflen, blockSize)
}

// crypto_sign

exports.crypto_sign_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )
  assert(
    seed.byteLength === binding.crypto_sign_SEEDBYTES,
    "seed must be 'crypto_sign_SEEDBYTES' bytes"
  )

  const res = binding.crypto_sign_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign = function (sm, m, sk) {
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sm.byteLength === binding.crypto_sign_BYTES + m.byteLength,
    "sm must be 'm.byteLength + crypto_sign_BYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign(sm, m, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_open = function (m, sm, pk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sm.byteLength >= binding.crypto_sign_BYTES,
    "sm must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    m.byteLength === sm.byteLength - binding.crypto_sign_BYTES,
    "m must be 'sm.byteLength - crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_open(m, sm, pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_open = function (m, sm, pk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sm.byteLength >= binding.crypto_sign_BYTES,
    "sm must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    m.byteLength === sm.byteLength - binding.crypto_sign_BYTES,
    "m must be 'sm.byteLength - crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  return binding.crypto_sign_open(m, sm, pk)
}

exports.crypto_sign_detached = function (sig, m, sk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(sig.byteLength === binding.crypto_sign_BYTES, "sig must be 'crypto_sign_BYTES' bytes")
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_detached(sig, m, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_verify_detached = function (sig, m, pk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sig.byteLength >= binding.crypto_sign_BYTES,
    "sig must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  return binding.crypto_sign_verify_detached(
    sig.buffer,
    sig.byteOffset,
    sig.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    pk.buffer,
    pk.byteOffset,
    pk.byteLength
  )
}

exports.crypto_sign_ed25519_sk_to_pk = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_sk_to_pk(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_ed25519_pk_to_curve25519 = function (x25519pk, ed25519pk) {
  assert(ArrayBuffer.isView(x25519pk), 'x25519pk must be a typed array')
  assert(ArrayBuffer.isView(ed25519pk), 'ed25519pk must be a typed array')
  assert(
    x25519pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "x25519pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    ed25519pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "ed25519pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_pk_to_curve25519(x25519pk, ed25519pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_ed25519_sk_to_curve25519 = function (x25519sk, ed25519sk) {
  assert(ArrayBuffer.isView(x25519sk), 'x25519sk must be a typed array')
  assert(ArrayBuffer.isView(ed25519sk), 'ed25519sk must be a typed array')
  assert(
    x25519sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "x25519sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const edLen = ed25519sk.byteLength

  assert(
    edLen === binding.crypto_sign_SECRETKEYBYTES || edLen === binding.crypto_box_SECRETKEYBYTES,
    "ed25519sk must be 'crypto_sign_SECRETKEYBYTES' or 'crypto_sign_SECRETKEYBYTES - crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_sk_to_curve25519(x25519sk, ed25519sk)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_box

exports.crypto_box_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    seed.byteLength === binding.crypto_box_SEEDBYTES,
    "seed must be 'crypto_box_SEEDBYTES' bytes"
  )

  const res = binding.crypto_box_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_easy = function (c, m, n, pk, sk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength === m.byteLength + exports.crypto_box_MACBYTES,
    "c must be 'm.byteLength + crypto_box_MACBYTES' bytes"
  )
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_easy(c, m, n, pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_detached = function (c, mac, m, n, pk, sk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(mac.byteLength === exports.crypto_box_MACBYTES, "mac must be 'crypto_box_MACBYTES' bytes")
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_detached(c, mac, m, n, pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_open_easy = function (m, c, n, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength >= exports.crypto_box_MACBYTES,
    "c must be at least 'crypto_box_MACBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - exports.crypto_box_MACBYTES,
    "m must be 'c.byteLength - crypto_box_MACBYTES' bytes"
  )
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_open_easy(m, c, n, pk, sk)
}

exports.crypto_box_open_detached = function (m, c, mac, n, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(mac.byteLength === exports.crypto_box_MACBYTES, "mac must be 'crypto_box_MACBYTES' bytes")
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_open_detached(m, c, mac, n, pk, sk)
}

exports.crypto_box_seal = function (c, m, pk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    c.byteLength === m.byteLength + exports.crypto_box_SEALBYTES,
    "c must be 'm.byteLength + crypto_box_SEALBYTES' bytes"
  )
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_box_seal(c, m, pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_seal_open = function (m, c, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength >= exports.crypto_box_SEALBYTES,
    "c must be at least 'crypto_box_SEALBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - exports.crypto_box_SEALBYTES,
    "m must be 'c.byteLength - crypto_box_SEALBYTES' bytes"
  )
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_seal_open(
    m.buffer,
    m.byteOffset,
    m.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    pk.buffer,
    pk.byteOffset,
    pk.byteLength,

    sk.buffer,
    sk.byteOffset,
    sk.byteLength
  )
}

// crypto_secretbox

exports.crypto_secretbox_easy = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_secretbox_MACBYTES,
    "c must be 'm.byteLength + crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretbox_easy(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretbox_open_easy = function (m, c, n, k) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    c.byteLength >= binding.crypto_secretbox_MACBYTES,
    "c must be at least 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - binding.crypto_secretbox_MACBYTES,
    "m must be 'c.byteLength - crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  return binding.crypto_secretbox_open_easy(m, c, n, k)
}

exports.crypto_secretbox_detached = function (c, mac, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    mac.byteLength === binding.crypto_secretbox_MACBYTES,
    "mac must be 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretbox_detached(c, mac, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretbox_open_detached = function (m, c, mac, n, k) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(
    mac.byteLength === binding.crypto_secretbox_MACBYTES,
    "mac must be 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  return binding.crypto_secretbox_open_detached(m, c, mac, n, k)
}

// crypto_generichash

exports.crypto_generichash = function (output, input, key) {
  if (!key) key = OPTIONAL

  assert(ArrayBuffer.isView(output), 'output must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    output.byteLength >= binding.crypto_generichash_BYTES_MIN &&
      output.byteLength <= binding.crypto_generichash_BYTES_MAX,
    'output must be between crypto_generichash_BYTES_MIN and crypto_generichash_BYTES_MAX bytes'
  )

  if (key !== OPTIONAL) {
    assert(ArrayBuffer.isView(key), 'key must be a typed array')
    assert(
      key.byteLength >= binding.crypto_generichash_KEYBYTES_MIN &&
        key.byteLength <= binding.crypto_generichash_KEYBYTES_MAX,
      'key must be between crypto_generichash_KEYBYTES_MIN and crypto_generichash_KEYBYTES_MAX bytes'
    )
  }

  const res = binding.crypto_generichash(
    output.buffer,
    output.byteOffset,
    output.byteLength,

    input.buffer,
    input.byteOffset,
    input.byteLength,

    key.buffer,
    key.byteOffset,
    key.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_batch = function (output, batch, key) {
  assert(ArrayBuffer.isView(output), 'output must be a typed array')

  if (isNode || batch.length < 4) {
    const res = binding.crypto_generichash_batch(output, batch, !!key, key || OPTIONAL)
    if (res !== 0) throw new Error('status: ' + res)
  } else {
    const state = Buffer.alloc(binding.crypto_generichash_STATEBYTES)

    exports.crypto_generichash_init(state, key, output.byteLength)

    for (const buf of batch) {
      exports.crypto_generichash_update(state, buf)
    }

    exports.crypto_generichash_final(state, output)
  }
}

exports.crypto_generichash_keygen = function (key) {
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(
    key.byteLength === binding.crypto_generichash_KEYBYTES,
    "key must be 'crypto_generichash_KEYBYTES' bytes"
  )

  const res = binding.crypto_generichash_keygen(key.buffer, key.byteOffset, key.byteLength)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_init = function (state, key, outputLength) {
  if (!key) key = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_init(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    key.buffer,
    key.byteOffset,
    key.byteLength,

    outputLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_update(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    input.buffer,
    input.byteOffset,
    input.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_final = function (state, output) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(output), 'output must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_final(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    output.buffer,
    output.byteOffset,
    output.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

// secretstream

exports.crypto_secretstream_xchacha20poly1305_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  binding.crypto_secretstream_xchacha20poly1305_keygen(k.buffer, k.byteOffset, k.byteLength)
}

exports.crypto_secretstream_xchacha20poly1305_init_push = function (state, header, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(header), 'header must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    header.byteLength === binding.crypto_secretstream_xchacha20poly1305_HEADERBYTES,
    "header must be 'crypto_secretstream_xchacha20poly1305_HEADERBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_init_push(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    header.buffer,
    header.byteOffset,
    header.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretstream_xchacha20poly1305_init_pull = function (state, header, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(header), 'header must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    header.byteLength === binding.crypto_secretstream_xchacha20poly1305_HEADERBYTES,
    "header must be 'crypto_secretstream_xchacha20poly1305_HEADERBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_init_pull(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    header.buffer,
    header.byteOffset,
    header.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretstream_xchacha20poly1305_push = function (state, c, m, ad, tag) {
  if (!ad) ad = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    c.byteLength === m.byteLength + binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "c must be 'm.byteLength + crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_push(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    ad.buffer,
    ad.byteOffset,
    ad.byteLength,

    tag
  )

  if (res < 0) throw new Error('push failed')

  return res
}

exports.crypto_secretstream_xchacha20poly1305_pull = function (state, m, tag, c, ad) {
  if (!ad) ad = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(tag), 'tag must be a typed array')
  assert(tag.byteLength === 1, 'tag must be 1 byte')

  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    c.byteLength >= binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "c must be at least 'crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "m must be 'c.byteLength - crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_pull(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    tag.buffer,
    tag.byteOffset,
    tag.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    ad.buffer,
    ad.byteOffset,
    ad.byteLength
  )

  if (res < 0) throw new Error('pull failed')

  return res
}

exports.crypto_secretstream_xchacha20poly1305_rekey = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )

  binding.crypto_secretstream_xchacha20poly1305_rekey(
    state.buffer,
    state.byteOffset,
    state.byteLength
  )
}

// crypto_stream

exports.crypto_stream = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xor(
    c.buffer,
    c.byteOffset,
    c.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    n.buffer,
    n.byteOffset,
    n.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_auth

exports.crypto_auth = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(out.byteLength === binding.crypto_auth_BYTES, "out must be 'crypto_auth_BYTES' bytes")
  assert(k.byteLength === binding.crypto_auth_KEYBYTES, "k must be 'crypto_auth_KEYBYTES' bytes")

  const res = binding.crypto_auth(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_auth_verify = function (h, input, k) {
  assert(ArrayBuffer.isView(h), 'h must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(h.byteLength === binding.crypto_auth_BYTES, "h must be 'crypto_auth_BYTES' bytes")
  assert(k.byteLength === binding.crypto_auth_KEYBYTES, "k must be 'crypto_auth_KEYBYTES' bytes")

  return binding.crypto_auth_verify(h, input, k)
}

// crypto_onetimeauth

exports.crypto_onetimeauth = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    out.byteLength === binding.crypto_onetimeauth_BYTES,
    "out must be 'crypto_onetimeauth_BYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_init = function (state, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_init(state, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )
  assert(
    out.byteLength === binding.crypto_onetimeauth_BYTES,
    "out must be 'crypto_onetimeauth_BYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_verify = function (h, input, k) {
  assert(ArrayBuffer.isView(h), 'h must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    h.byteLength === binding.crypto_onetimeauth_BYTES,
    "h must be 'crypto_onetimeauth_BYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  return binding.crypto_onetimeauth_verify(h, input, k)
}

// crypto_pwhash

exports.crypto_pwhash = function (out, passwd, salt, opslimit, memlimit, alg) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_BYTES_MIN,
    "out must be at least 'crypto_pwhash_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_BYTES_MAX,
    "out must be at most 'crypto_pwhash_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_SALTBYTES,
    "salt must be 'crypto_pwhash_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )
  assert(alg >= 1 && alg <= 2, 'alg must be either Argon2i 1.3 or Argon2id 1.3')

  const res = binding.crypto_pwhash(out, passwd, salt, opslimit, memlimit, alg)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_async = function (
  out,
  passwd,
  salt,
  opslimit,
  memlimit,
  alg,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_BYTES_MIN,
    "out must be at least 'crypto_pwhash_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_BYTES_MAX,
    "out must be at most 'crypto_pwhash_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_SALTBYTES,
    "salt must be 'crypto_pwhash_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )
  assert(alg >= 1 && alg <= 2, 'alg must be either Argon2i 1.3 or Argon2id 1.3')

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    opslimit,
    memlimit,
    alg,

    done
  )

  return promise
}

exports.crypto_pwhash_str = function (out, passwd, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_STRBYTES,
    "out must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(typeof opslimit === 'number', 'opslimit must be a number')
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(typeof memlimit === 'number', 'memlimit must be a number')
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_str(out, passwd, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_str_async = function (out, passwd, opslimit, memlimit, callback = undefined) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_STRBYTES,
    "out must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(typeof opslimit === 'number', 'opslimit must be a number')
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(typeof memlimit === 'number', 'memlimit must be a number')
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_str_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_str_verify = function (str, passwd) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )

  return binding.crypto_pwhash_str_verify(str, passwd)
}

exports.crypto_pwhash_str_verify_async = function (str, passwd, callback = undefined) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  const [done, promise] = checkStatus(callback, true)

  binding.crypto_pwhash_str_verify_async(
    str.buffer,
    str.byteOffset,
    str.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    done
  )

  return promise
}

exports.crypto_pwhash_str_needs_rehash = function (str, opslimit, memlimit) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  return binding.crypto_pwhash_str_needs_rehash(str, opslimit, memlimit)
}

exports.crypto_pwhash_scryptsalsa208sha256 = function (out, passwd, salt, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MIN,
    "out must be at least 'crypto_pwhash_scryptsalsa208sha256_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MAX,
    "out must be at most 'crypto_pwhash_scryptsalsa208sha256_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_SALTBYTES,
    "salt must be 'crypto_pwhash_scryptsalsa208sha256_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_scryptsalsa208sha256(out, passwd, salt, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_scryptsalsa208sha256_async = function (
  out,
  passwd,
  salt,
  opslimit,
  memlimit,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MIN,
    "out must be at least 'crypto_pwhash_scryptsalsa208sha256_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MAX,
    "out must be at most 'crypto_pwhash_scryptsalsa208sha256_BYTES_MAX' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    salt.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_SALTBYTES,
    "salt must be 'crypto_pwhash_scryptsalsa208sha256_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_scryptsalsa208sha256_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str_async = function (
  out,
  passwd,
  opslimit,
  memlimit,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "out must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_scryptsalsa208sha256_str_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str = function (out, passwd, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "out must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_scryptsalsa208sha256_str(out, passwd, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_scryptsalsa208sha256_str_verify_async = function (
  str,
  passwd,
  callback = undefined
) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  const [done, promise] = checkStatus(callback, true)

  binding.crypto_pwhash_scryptsalsa208sha256_str_verify_async(
    str.buffer,
    str.byteOffset,
    str.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str_verify = function (str, passwd) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  return binding.crypto_pwhash_scryptsalsa208sha256_str_verify(str, passwd)
}

exports.crypto_pwhash_scryptsalsa208sha256_str_needs_rehash = function (str, opslimit, memlimit) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  return binding.crypto_pwhash_scryptsalsa208sha256_str_needs_rehash(str, opslimit, memlimit)
}

// crypto_kx

exports.crypto_kx_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "pk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "sk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    pk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "pk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "sk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    seed.byteLength === binding.crypto_kx_SEEDBYTES,
    "seed must be 'crypto_kx_SEEDBYTES' bytes"
  )

  const res = binding.crypto_kx_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_client_session_keys = function (rx, tx, clientPk, clientSk, serverPk) {
  if (!rx) rx = undefined
  if (!tx) tx = undefined

  assert(rx || tx, 'at least one session key must be specified')

  if (rx) {
    assert(ArrayBuffer.isView(rx), 'rx must be a typed array')
    assert(
      rx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "rx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  if (tx) {
    assert(ArrayBuffer.isView(tx), 'tx must be a typed array')
    assert(
      tx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "tx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  assert(ArrayBuffer.isView(clientPk), 'clientPk must be a typed array')
  assert(ArrayBuffer.isView(clientSk), 'clientSk must be a typed array')
  assert(ArrayBuffer.isView(serverPk), 'serverPk must be a typed array')
  assert(
    clientPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "clientPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    clientSk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "clientSk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    serverPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "serverPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_client_session_keys(rx, tx, clientPk, clientSk, serverPk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_server_session_keys = function (rx, tx, serverPk, serverSk, clientPk) {
  if (!rx) rx = undefined
  if (!tx) tx = undefined

  assert(rx || tx, 'at least one session key must be specified')

  if (rx) {
    assert(ArrayBuffer.isView(rx), 'rx must be a typed array')
    assert(
      rx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "rx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  if (tx) {
    assert(ArrayBuffer.isView(tx), 'tx must be a typed array')
    assert(
      tx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "tx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  assert(ArrayBuffer.isView(serverPk), 'serverPk must be a typed array')
  assert(ArrayBuffer.isView(serverSk), 'serverSk must be a typed array')
  assert(ArrayBuffer.isView(clientPk), 'clientPk must be a typed array')
  assert(
    serverPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "serverPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    serverSk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "serverSk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    clientPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "clientPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_server_session_keys(rx, tx, serverPk, serverSk, clientPk)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_scalarmult

exports.crypto_scalarmult_base = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_BYTES,
    "q must be 'crypto_scalarmult_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_SCALARBYTES,
    "n must be 'crypto_scalarmult_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_base(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_BYTES,
    "q must be 'crypto_scalarmult_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_SCALARBYTES,
    "n must be 'crypto_scalarmult_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_BYTES,
    "p must be 'crypto_scalarmult_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_base = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_base(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519 = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "p must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_is_valid_point = function (p) {
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )

  return binding.crypto_core_ed25519_is_valid_point(p)
}

exports.crypto_core_ed25519_from_uniform = function (p, r) {
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_UNIFORMBYTES,
    "r must be 'crypto_core_ed25519_UNIFORMBYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_from_uniform(p, r)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_base_noclamp = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_base_noclamp(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_noclamp = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "p must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_noclamp(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_core

exports.crypto_core_ed25519_add = function (r, p, q) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_BYTES,
    "r must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_core_ed25519_BYTES,
    "q must be 'crypto_core_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_add(r, p, q)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_sub = function (r, p, q) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_BYTES,
    "r must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_core_ed25519_BYTES,
    "q must be 'crypto_core_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_sub(r, p, q)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_scalar_random = function (r) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "r must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_random(r)
}

exports.crypto_core_ed25519_scalar_reduce = function (r, s) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "r must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_NONREDUCEDSCALARBYTES,
    "s must be 'crypto_core_ed25519_NONREDUCEDSCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_reduce(r, s)
}

exports.crypto_core_ed25519_scalar_invert = function (recip, s) {
  assert(ArrayBuffer.isView(recip), 'recip must be a typed array')
  assert(
    recip.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "recip must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_invert(recip, s)
}

exports.crypto_core_ed25519_scalar_negate = function (neg, s) {
  assert(ArrayBuffer.isView(neg), 'neg must be a typed array')
  assert(
    neg.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "neg must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_negate(neg, s)
}

exports.crypto_core_ed25519_scalar_complement = function (comp, s) {
  assert(ArrayBuffer.isView(comp), 'comp must be a typed array')
  assert(
    comp.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "comp must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_complement(comp, s)
}

exports.crypto_core_ed25519_scalar_add = function (z, x, y) {
  assert(ArrayBuffer.isView(z), 'z must be a typed array')
  assert(
    z.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "z must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(x), 'x must be a typed array')
  assert(
    x.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "x must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(y), 'y must be a typed array')
  assert(
    y.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "y must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_add(z, x, y)
}

exports.crypto_core_ed25519_scalar_sub = function (z, x, y) {
  assert(ArrayBuffer.isView(z), 'z must be a typed array')
  assert(
    z.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "z must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(x), 'x must be a typed array')
  assert(
    x.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "x must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(y), 'y must be a typed array')
  assert(
    y.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "y must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_sub(z, x, y)
}

// crypto_shorthash

exports.crypto_shorthash = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_shorthash_BYTES,
    "out must be 'crypto_shorthash_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_shorthash_KEYBYTES,
    "k must be 'crypto_shorthash_KEYBYTES' bytes"
  )

  const res = binding.crypto_shorthash(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_kdf

exports.crypto_kdf_keygen = function (key) {
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(key.byteLength === binding.crypto_kdf_KEYBYTES, "key must be 'crypto_kdf_KEYBYTES' bytes")

  binding.crypto_kdf_keygen(key)
}

exports.crypto_kdf_derive_from_key = function (subkey, subkeyId, ctx, key) {
  assert(ArrayBuffer.isView(subkey), 'subkey must be a typed array')
  assert(
    subkey.byteLength >= binding.crypto_kdf_BYTES_MIN,
    "subkey must be at least 'crypto_kdf_BYTES_MIN' bytes"
  )
  assert(
    subkey.byteLength <= binding.crypto_kdf_BYTES_MAX,
    "subkey must be at most 'crypto_kdf_BYTES_MAX' bytes"
  )
  assert(ArrayBuffer.isView(ctx), 'ctx must be a typed array')
  assert(
    ctx.byteLength === binding.crypto_kdf_CONTEXTBYTES,
    "ctx must be 'crypto_kdf_CONTEXTBYTES' bytes"
  )
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(key.byteLength === binding.crypto_kdf_KEYBYTES, "key must be 'crypto_kdf_KEYBYTES' bytes")

  const res = binding.crypto_kdf_derive_from_key(subkey, subkeyId, ctx, key)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_hash

exports.crypto_hash = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(out.byteLength === binding.crypto_hash_BYTES, "out must be 'crypto_hash_BYTES' bytes")

  const res = binding.crypto_hash(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256 = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha256_BYTES,
    "out must be 'crypto_hash_sha256_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha256(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_init = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_init(state)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha256_BYTES,
    "out must be 'crypto_hash_sha256_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512 = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha512_BYTES,
    "out must be 'crypto_hash_sha512_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha512(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_init = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_init(state)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha512_BYTES,
    "out must be 'crypto_hash_sha512_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_aead

exports.crypto_aead_xchacha20poly1305_ietf_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  binding.crypto_aead_xchacha20poly1305_ietf_keygen(k)
}

exports.crypto_aead_xchacha20poly1305_ietf_encrypt = function (c, m, ad, nsec, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "c must be 'm.byteLength + crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(c.byteLength <= 0xffffffff, 'c.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_encrypt(c, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_decrypt = function (m, nsec, c, ad, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "m must be 'c.byteLength - crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(m.byteLength <= 0xffffffff, 'm.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_decrypt(m, c, ad, npub, k)

  if (res < 0) throw new Error('could not verify data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_encrypt_detached = function (
  c,
  mac,
  m,
  ad,
  nsec,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_encrypt_detached(c, mac, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_decrypt_detached = function (
  m,
  nsec,
  c,
  mac,
  ad,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_decrypt_detached(m, c, mac, ad, npub, k)

  if (res !== 0) throw new Error('could not verify data')
}

exports.crypto_aead_chacha20poly1305_ietf_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  binding.crypto_aead_chacha20poly1305_ietf_keygen(k)
}

exports.crypto_aead_chacha20poly1305_ietf_encrypt = function (c, m, ad, nsec, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "c must be 'm.byteLength + crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(c.byteLength <= 0xffffffff, 'c.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_encrypt(c, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_decrypt = function (m, nsec, c, ad, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "m must be 'c.byteLength - crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(m.byteLength <= 0xffffffff, 'm.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_decrypt(m, c, ad, npub, k)

  if (res < 0) throw new Error('could not verify data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_encrypt_detached = function (
  c,
  mac,
  m,
  ad,
  nsec,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_encrypt_detached(c, mac, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_decrypt_detached = function (
  m,
  nsec,
  c,
  mac,
  ad,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_decrypt_detached(m, c, mac, ad, npub, k)

  if (res !== 0) throw new Error('could not verify data')
}

// crypto_stream

exports.crypto_stream_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  binding.crypto_stream_xor_wrap_init(state, n, k)
}

exports.crypto_stream_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_xor_wrap_update(state, c, m)
}

exports.crypto_stream_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_xor_wrap_final(state)
}

exports.crypto_stream_chacha20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  binding.crypto_stream_chacha20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_chacha20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_chacha20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_chacha20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_chacha20_xor_wrap_final(state)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  binding.crypto_stream_chacha20_ietf_xor_wrap_init(state, n, k)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_chacha20_ietf_xor_wrap_update(state, c, m)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_chacha20_ietf_xor_wrap_final(state)
}

exports.crypto_stream_xchacha20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  binding.crypto_stream_xchacha20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_xchacha20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_xchacha20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_xchacha20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_xchacha20_xor_wrap_final(state)
}

exports.crypto_stream_salsa20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  binding.crypto_stream_salsa20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_salsa20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_salsa20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_salsa20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_salsa20_xor_wrap_final(state)
}

// experimental

exports.extension_tweak_ed25519_base = function (n, p, ns) {
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.extension_tweak_ed25519_BYTES,
    "p must be 'extension_tweak_ed25519_BYTES' bytes"
  )

  binding.extension_tweak_ed25519_base(n, p, ns)
}

exports.extension_tweak_ed25519_sign_detached = function (sig, m, scalar, pk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(sig.byteLength === binding.crypto_sign_BYTES, "sig must be 'crypto_sign_BYTES' bytes")
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  if (pk) {
    assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
    assert(
      pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
      "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
    )
  }

  const res = binding.extension_tweak_ed25519_sign_detached(sig, m, scalar, pk)

  if (res !== 0) throw new Error('failed to compute signature')
}

exports.extension_tweak_ed25519_sk_to_scalar = function (n, sk) {
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  binding.extension_tweak_ed25519_sk_to_scalar(n, sk)
}

exports.extension_tweak_ed25519_scalar = function (scalarOut, scalar, ns) {
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_scalar(scalarOut, scalar, ns)
}

exports.extension_tweak_ed25519_pk = function (tpk, pk, ns) {
  assert(ArrayBuffer.isView(tpk), 'tpk must be a typed array')
  assert(
    tpk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "tpk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_pk(tpk, pk, ns)

  if (res !== 0) throw new Error('failed to tweak public key')
}

exports.extension_tweak_ed25519_keypair = function (pk, scalarOut, scalarIn, ns) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.extension_tweak_ed25519_BYTES,
    "pk must be 'extension_tweak_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarIn), 'scalarIn must be a typed array')
  assert(
    scalarIn.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarIn must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_keypair(pk, scalarOut, scalarIn, ns)
}

exports.extension_tweak_ed25519_scalar_add = function (scalarOut, scalar, n) {
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_scalar_add(scalarOut, scalar, n)
}

exports.extension_tweak_ed25519_pk_add = function (tpk, pk, p) {
  assert(ArrayBuffer.isView(tpk), 'tpk must be a typed array')
  assert(
    tpk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "tpk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "p must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_pk_add(tpk, pk, p)

  if (res !== 0) throw new Error('failed to add tweak to public key')
}

exports.extension_tweak_ed25519_keypair_add = function (pk, scalarOut, scalarIn, tweak) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.extension_tweak_ed25519_BYTES,
    "pk must be 'extension_tweak_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarIn), 'scalarIn must be a typed array')
  assert(
    scalarIn.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarIn must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(tweak), 'tweak must be a typed array')
  assert(
    tweak.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "tweak must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_keypair_add(pk, scalarOut, scalarIn, tweak)

  if (res !== 0) throw new Error('failed to add tweak to keypair')
}

exports.extension_pbkdf2_sha512_async = function (out, passwd, salt, iter, outlen, callback) {
  assert(
    iter >= binding.extension_pbkdf2_sha512_ITERATIONS_MIN,
    "iter must be at least 'extension_pbkdf2_sha512_ITERATIONS_MIN'"
  )
  assert(
    outlen <= binding.extension_pbkdf2_sha512_BYTES_MAX,
    "outlen must be at most 'extension_pbkdf2_sha512_BYTES_MAX'"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(out.byteLength >= outlen, "out must be at least 'outlen' bytes")
  assert(out.byteLength > 0, 'out must not be empty')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(salt.byteLength > 0, 'salt must not be empty')

  const [done, promise] = checkStatus(callback)

  binding.extension_pbkdf2_sha512_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    iter,
    outlen,

    done
  )

  return promise
}

exports.extension_pbkdf2_sha512 = function (out, passwd, salt, iter, outlen) {
  assert(
    iter >= binding.extension_pbkdf2_sha512_ITERATIONS_MIN,
    "iter must be at least 'extension_pbkdf2_sha512_ITERATIONS_MIN'"
  )
  assert(
    outlen <= binding.extension_pbkdf2_sha512_BYTES_MAX,
    "outlen must be at most 'extension_pbkdf2_sha512_BYTES_MAX'"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(out.byteLength >= outlen, "out must be at least 'outlen' bytes")
  assert(out.byteLength > 0, 'out must not be empty')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(salt.byteLength > 0, 'salt must not be empty')

  const res = binding.extension_pbkdf2_sha512(out, passwd, salt, iter, outlen)

  if (res !== 0) throw new Error('failed to add tweak to public key')
}

function checkStatus(callback, booleanResult = false) {
  let done, promise

  if (typeof callback === 'function') {
    done = function (status) {
      if (booleanResult) callback(null, status === 0)
      else if (status === 0) callback(null)
      else callback(new Error('status: ' + status))
    }
  } else {
    promise = new Promise(function (resolve, reject) {
      done = function (status) {
        if (booleanResult) resolve(status === 0)
        else if (status === 0) resolve()
        else reject(new Error('status: ' + status))
      }
    })
  }

  return [done, promise]
}
{
  "name": "sodium-native",
  "version": "5.1.0",
  "description": "Low level bindings for libsodium",
  "main": "index.js",
  "files": [
    "index.js",
    "binding.cc",
    "binding.js",
    "extensions",
    "prebuilds",
    "CMakeLists.txt"
  ],
  "imports": {
    "assert": {
      "bare": "bare-assert",
      "node": "assert"
    }
  },
  "addon": true,
  "dependencies": {
    "bare-assert": "^1.2.0",
    "require-addon": "^1.1.0",
    "which-runtime": "^1.2.1"
  },
  "devDependencies": {
    "bare-compat-napi": "^1.3.5",
    "brittle": "^3.16.2",
    "cmake-bare": "^1.6.1",
    "cmake-fetch": "^1.4.3",
    "cmake-napi": "^1.2.1",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "test": "prettier . --check && npm run test:node && npm run test:bare",
    "test:node": "node test/all.js",
    "test:bare": "bare test/all.js"
  },
  "standard": {
    "ignore": [
      "/test/fixtures/*.js"
    ]
  },
  "engines": {
    "bare": ">=1.16.0"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sodium-native.git"
  },
  "contributors": [
    "Emil Bay <github@tixz.dk> (http://bayes.dk)",
    "Mathias Buus <mathiasbuus@gmail.com> (https://mafinto.sh)",
    "Christophe Diederichs <chm-diederichs@hyperdivision.dk>"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/sodium-native/issues"
  },
  "homepage": "https://github.com/holepunchto/sodium-native"
}
module.exports = require('sodium-native')
{
  "name": "sodium-universal",
  "version": "5.0.1",
  "description": "Universal wrapper for sodium-javascript and sodium-native working in Node.js and the Browser",
  "main": "index.js",
  "dependencies": {
    "sodium-native": "^5.0.1"
  },
  "peerDependencies": {
    "sodium-javascript": "~0.8.0"
  },
  "peerDependenciesMeta": {
    "sodium-javascript": {
      "optional": true
    }
  },
  "scripts": {
    "prepublish": "./build-scripts/generate.js"
  },
  "browser": {
    "sodium-native": "sodium-javascript"
  },
  "browserify": {
    "transform": [
      "./build-scripts/transform.js"
    ]
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sodium-universal.git"
  },
  "keywords": [
    "libsodium",
    "sodium",
    "sodium-native",
    "sodium-javascript",
    "browserify"
  ],
  "contributors": [
    "Emil Bay <github@tixz.dk> (http://bayes.dk)",
    "Mathias Buus <mathiasbuus@gmail.com> (https://mafinto.sh)",
    "Christophe Diederichs <chm-diederichs@hyperdivision.dk>"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/sodium-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/sodium-universal#readme"
}
const { runtime, platform, arch, version } =
  typeof Bare !== 'undefined'
    ? {
        runtime: 'bare',
        platform: global.Bare.platform,
        arch: global.Bare.arch,
        version: global.Bare.version
      }
    : typeof process !== 'undefined'
      ? {
          runtime: 'node',
          platform: global.process.platform,
          arch: global.process.arch,
          version: global.process.version
        }
      : typeof Window !== 'undefined'
        ? { runtime: 'browser', platform: 'unknown', arch: 'unknown', version: 'unknown' }
        : { runtime: 'unknown', platform: 'unknown', arch: 'unknown', version: 'unknown' }

exports.runtime = runtime
exports.version = version
exports.platform = platform
exports.arch = arch
exports.isBare = runtime === 'bare'
exports.isBareKit = exports.isBare && typeof BareKit !== 'undefined'
exports.isPear = typeof Pear !== 'undefined'
exports.isNode = runtime === 'node'
exports.isBrowser = runtime === 'browser'
exports.isWindows = platform === 'win32'
exports.isLinux = platform === 'linux'
exports.isMac = platform === 'darwin'
exports.isIOS = platform === 'ios' || platform === 'ios-simulator'
exports.isAndroid = platform === 'android'
exports.isElectron = typeof process !== 'undefined' && !!global.process.versions?.electron
exports.isElectronRenderer = exports.isElectron && global.process.type === 'renderer'
exports.isElectronWorker = exports.isElectron && global.process.type === 'worker'
{
  "name": "which-runtime",
  "version": "1.4.0",
  "description": "Detect if you are in Bare or Node and which os etc",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte .",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/which-runtime.git"
  },
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/which-runtime/issues"
  },
  "homepage": "https://github.com/holepunchto/which-runtime",
  "devDependencies": {
    "brittle": "^3.0.0",
    "lunte": "^1.4.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
{
  "name": "atproto-identity",
  "version": "0.0.4",
  "description": "Seed-anchored atproto identity: one BIP39 mnemonic -> Ed25519 (Hypercore) + secp256k1 (did:plc). Offline did:plc genesis + verification.",
  "type": "module",
  "main": "lib/atproto-identity.js",
  "scripts": {
    "test": "brittle-node test/*.test.js && node test/labels.test.mjs",
    "postinstall": "node scripts/bare-deps.mjs"
  },
  "dependencies": {
    "@ipld/dag-cbor": "^9.2.1",
    "@noble/curves": "^1.6.0",
    "@noble/hashes": "^1.5.0",
    "@scure/bip32": "^1.5.0",
    "@scure/bip39": "^1.4.0",
    "b4a": "^1.6.7",
    "hypercore-crypto": "^3.0.0",
    "keet-identity-key": "^3.2.0",
    "multiformats": "^13.3.0",
    "sodium-native": "^5.1.0"
  },
  "devDependencies": {
    "brittle": "^4.0.2"
  }
}
// pairing.js — hpp-initiated browser pairing over blind-pairing (the "hash URL" that opens a peer tunnel).
//
// Aligns with pgv3's DeviceLinker (blind-pairing). pgv3's browser auth is TOFU (the daemon IS the identity
// authority, so it self-registers a browser key). favela is KEYLESS — the authority is the remote hpp/DID —
// so a browser sub-key must be DELEGATED by the DID. The DID key-holder (hpp) mints a one-time invite; the
// candidate (favela-web, on the browser's behalf) joins → an E2E tunnel opens over the DHT → the browser's
// sub-key PUBKEY goes up → the hpp delegates it → the delegation comes back. Works REMOTELY (any hpp on the
// DHT) and is owner-gated by construction (only the key-holder can mint an invite; favela-web holds no key).
//
// Direction note: DeviceLinker's source PUSHES a bundle to the joiner; here the candidate must send its
// sub-key UP first, so the sub-key rides the candidate's blind-pairing `userData` (the member's hello) and
// the delegation comes back as the confirm's `additional.data`.
import Hyperswarm from 'hyperswarm'
import BlindPairing from 'blind-pairing'
import crypto from 'hypercore-crypto'
import b4a from 'b4a'

const TIMEOUT_MS = 5 * 60 * 1000

// SOURCE (hpp): mint a one-time pairing invite. onSubkey(subKeyHex) => delegation object (device.delegate).
// Returns { inviteHex, waitForPeer, close }. Stays open for ONE pairing session (owner mints per browser).
export async function createPairInvite ({ onSubkey, swarm = null, timeout = TIMEOUT_MS } = {}) {
  if (typeof onSubkey !== 'function') throw new Error('createPairInvite requires onSubkey(subKey) => delegation')
  const pairingKey = crypto.keyPair()
  const { invite, publicKey: invitePublicKey, discoveryKey, seed } = BlindPairing.createInvite(pairingKey.publicKey)
  const inviteKeyPair = crypto.keyPair(seed)
  const sw = swarm || new Hyperswarm()
  const pairing = new BlindPairing(sw)
  const done = new Promise((resolve, reject) => {
    const timer = setTimeout(() => reject(new Error('createPairInvite: timeout waiting for the browser')), timeout)
    pairing.addMember({
      discoveryKey,
      onadd: async (request) => {
        clearTimeout(timer)
        try {
          request.open(invitePublicKey)
          const hello = JSON.parse(b4a.toString(request.userData)) // the candidate's sub-key
          const delegation = await onSubkey(hello.subKey)
          const data = b4a.from(JSON.stringify(delegation))
          request.confirm({ key: pairingKey.publicKey, encryptionKey: null, additional: { data, signature: crypto.sign(data, inviteKeyPair.secretKey) } })
          resolve({ subKey: hello.subKey, delegation })
        } catch (e) {
          // ⛔ TELL THE CANDIDATE. Rejecting only settles OUR promise; the joiner is left holding an open
          // tunnel with nothing coming back, so it waits out its full timeout (5 min) and reports
          // nothing about why. That is exactly how a BROWSER invite pasted into a NODE presents: the
          // node sends a 64-hex keet device key, delegate() demands 66-hex secp256k1 and throws here,
          // and the node just… hangs. A refusal is information the other side needs.
          //
          // Confirm with an { error } payload — the same shape mintAdoptInvite already returns when a
          // human declines — then reject locally. Best-effort: if the channel is already gone there is
          // nothing to say and the timeout remains the backstop.
          try {
            const data = b4a.from(JSON.stringify({ error: (e && e.message) || String(e) }))
            request.confirm({ key: pairingKey.publicKey, encryptionKey: null, additional: { data, signature: crypto.sign(data, inviteKeyPair.secretKey) } })
          } catch { /* channel gone — the candidate falls back to its timeout */ }
          reject(e)
        }
      }
    })
  })
  return {
    inviteHex: b4a.toString(invite, 'hex'),
    waitForPeer: () => done,
    // DRAIN before teardown (mirrors pgv3 DeviceLinker.close). The confirm frame carrying the delegation
    // is enqueued via protomux AFTER onadd returns, but waitForPeer resolves SYNCHRONOUSLY inside onadd —
    // so the CLI's `await waitForPeer(); await close()` would destroy the swarm before the frame hits the
    // wire. The candidate (favela-web) then never receives the delegation and hangs to timeout, while the
    // source falsely reports success. Awaiting conn.flush() drains protomux→noise→UDX before destroy.
    close: async () => {
      try {
        const flushes = []
        for (const conn of sw.connections) { if (typeof conn.flush === 'function') flushes.push(conn.flush()) }
        await Promise.all(flushes).catch(() => {})
      } catch {}
      try { await pairing.close() } catch {}
      if (!swarm) { try { await sw.destroy() } catch {} }
    }
  }
}

// CANDIDATE (favela-web): join with the invite + the browser's sub-key pubkey → receive the delegation.
// swarm optional (an ephemeral one is created + destroyed). Throws on timeout.
export async function joinPairInvite (inviteHex, { subKey, swarm = null, timeout = TIMEOUT_MS } = {}) {
  if (!subKey) throw new Error('joinPairInvite requires subKey')
  const sw = swarm || new Hyperswarm()
  const pairing = new BlindPairing(sw)
  const userData = b4a.from(JSON.stringify({ subKey }))
  try {
    return await new Promise((resolve, reject) => {
      const timer = setTimeout(() => reject(new Error('joinPairInvite: timeout')), timeout)
      pairing.addCandidate({
        invite: b4a.from(inviteHex, 'hex'),
        userData,
        onadd: (result) => {
          clearTimeout(timer)
          try { resolve(JSON.parse(b4a.toString(result.data))) } catch (e) { reject(e) }
        }
      })
    })
  } finally {
    try { await pairing.close() } catch {}
    if (!swarm) { try { await sw.destroy() } catch {} }
  }
}
const { Pull, Push, HEADERBYTES, KEYBYTES, ABYTES } = require('sodium-secretstream')
const sodium = require('sodium-universal')
const crypto = require('hypercore-crypto')
const { Duplex, Writable, getStreamError } = require('streamx')
const b4a = require('b4a')
const Timeout = require('timeout-refresh')
const unslab = require('unslab')
const Bridge = require('./lib/bridge')
const Handshake = require('./lib/handshake')

const IDHEADERBYTES = HEADERBYTES + 32
const [NS_INITIATOR, NS_RESPONDER, NS_SEND] = crypto.namespace('hyperswarm/secret-stream', 3)
const MAX_ATOMIC_WRITE = 256 * 256 * 256 - 1

module.exports = class NoiseSecretStream extends Duplex {
  constructor(isInitiator, rawStream, opts = {}) {
    super({ mapWritable: toBuffer })

    if (typeof isInitiator !== 'boolean') {
      throw new Error('isInitiator should be a boolean')
    }

    this.noiseStream = this
    this.isInitiator = isInitiator
    this.rawStream = null

    this.publicKey = opts.publicKey || null
    this.remotePublicKey = opts.remotePublicKey || null
    this.handshakeHash = null
    this.connected = false
    this.keepAlive = opts.keepAlive || 0
    this.timeout = 0
    this.enableSend = opts.enableSend !== false

    // pointer for upstream to set data here if they want
    this.userData = null

    let openedDone = null
    this.opened = new Promise((resolve) => {
      openedDone = resolve
    })

    this.rawBytesWritten = 0
    this.rawBytesRead = 0

    // metadata used by 'hyperdht'
    this.relay = null
    this.puncher = null

    // unwrapped raw stream
    this._rawStream = null

    // handshake state
    this._handshake = null
    this._handshakePattern = opts.pattern || null
    this._handshakeDone = null

    // message parsing state
    this._state = 0
    this._len = 0
    this._tmp = 1
    this._message = null

    this._openedDone = openedDone
    this._startDone = null
    this._drainDone = null
    this._outgoingPlain = null
    this._outgoingWrapped = null
    this._utp = null
    this._setup = true
    this._ended = 2
    this._encrypt = null
    this._decrypt = null
    this._timeoutTimer = null
    this._keepAliveTimer = null
    this._sendState = null

    if (opts.autoStart !== false) this.start(rawStream, opts)

    // wiggle it to trigger open immediately (TODO add streamx option for this)
    this.resume()
    this.pause()
  }

  static keyPair(seed) {
    return Handshake.keyPair(seed)
  }

  static id(handshakeHash, isInitiator, id) {
    return streamId(handshakeHash, isInitiator, id)
  }

  setTimeout(ms) {
    if (!ms) ms = 0

    this._clearTimeout()
    this.timeout = ms

    if (!ms || this.rawStream === null) return

    this._timeoutTimer = Timeout.once(ms, destroyTimeout, this)
    this._timeoutTimer.unref()
  }

  setKeepAlive(ms) {
    if (!ms) ms = 0

    this._clearKeepAlive()

    this.keepAlive = ms

    if (!ms || this.rawStream === null) return

    this._keepAliveTimer = Timeout.on(ms, sendKeepAlive, this)
    this._keepAliveTimer.unref()
  }

  sendKeepAlive() {
    const empty = this.alloc(0)
    this.write(empty)
  }

  start(rawStream, opts = {}) {
    if (rawStream) {
      this.rawStream = rawStream
      this._rawStream = rawStream
      if (typeof this.rawStream.setContentSize === 'function') {
        this._utp = rawStream
      }
    } else {
      this.rawStream = new Bridge(this)
      this._rawStream = this.rawStream.reverse
    }

    this.rawStream.on('error', this._onrawerror.bind(this))
    this.rawStream.on('close', this._onrawclose.bind(this))

    this._startHandshake(opts.handshake, opts.keyPair || null)
    this._continueOpen(null)

    if (this.destroying) return

    if (opts.data) this._onrawdata(opts.data)
    if (opts.ended) this._onrawend()

    if (this.keepAlive > 0 && this._keepAliveTimer === null) {
      this.setKeepAlive(this.keepAlive)
    }

    if (this.timeout > 0 && this._timeoutTimer === null) {
      this.setTimeout(this.timeout)
    }
  }

  async flush() {
    if ((await this.opened) === false) return false
    if ((await Writable.drained(this)) === false) return false
    if (this.destroying) return false

    if (this.rawStream !== null && this.rawStream.flush) {
      return await this.rawStream.flush()
    }

    return true
  }

  _continueOpen(err) {
    if (err) this.destroy(err)
    if (this._startDone === null) return
    const done = this._startDone
    this._startDone = null
    this._open(done)
  }

  _onkeypairpromise(p) {
    const self = this
    const cont = this._continueOpen.bind(this)

    p.then(onkeypair, cont)

    function onkeypair(kp) {
      self._onkeypair(kp)
      cont(null)
    }
  }

  _onkeypair(keyPair) {
    const pattern = this._handshakePattern || 'XX'
    const remotePublicKey = this.remotePublicKey

    this._handshake = new Handshake(this.isInitiator, keyPair, remotePublicKey, pattern)
    this.publicKey = this._handshake.keyPair.publicKey
  }

  _startHandshake(handshake, keyPair) {
    if (handshake) {
      const { tx, rx, hash, publicKey, remotePublicKey } = handshake
      this._setupSecretStream(tx, rx, hash, publicKey, remotePublicKey)
      return
    }

    if (!keyPair) keyPair = Handshake.keyPair()

    if (typeof keyPair.then === 'function') {
      this._onkeypairpromise(keyPair)
    } else {
      this._onkeypair(keyPair)
    }
  }

  _onrawerror(err) {
    this.destroy(err)
  }

  _onrawclose() {
    if (this._ended !== 0) this.destroy()
  }

  _onrawdata(data) {
    let offset = 0

    if (this._timeoutTimer !== null) {
      this._timeoutTimer.refresh()
    }

    do {
      switch (this._state) {
        case 0: {
          while (this._tmp !== 0x1000000 && offset < data.byteLength) {
            const v = data[offset++]
            this._len += this._tmp * v
            this._tmp *= 256
          }

          if (this._tmp === 0x1000000) {
            this._tmp = 0
            this._state = 1
            const unprocessed = data.byteLength - offset
            if (unprocessed < this._len && this._utp !== null)
              this._utp.setContentSize(this._len - unprocessed)
          }

          break
        }

        case 1: {
          const missing = this._len - this._tmp
          const end = missing + offset

          if (this._message === null && end <= data.byteLength) {
            this._message = data.subarray(offset, end)
            offset += missing
            this._incoming()
            break
          }

          const unprocessed = data.byteLength - offset

          if (this._message === null) {
            this._message = b4a.allocUnsafe(this._len)
          }

          b4a.copy(data, this._message, this._tmp, offset)
          this._tmp += unprocessed

          if (end <= data.byteLength) {
            offset += missing
            this._incoming()
          } else {
            offset += unprocessed
          }

          break
        }
      }
    } while (offset < data.byteLength && !this.destroying)
  }

  _onrawend() {
    this._ended--
    this.push(null)
  }

  _onrawdrain() {
    const drain = this._drainDone
    if (drain === null) return
    this._drainDone = null
    drain()
  }

  _read(cb) {
    this.rawStream.resume()
    cb(null)
  }

  _incoming() {
    const message = this._message

    this._state = 0
    this._len = 0
    this._tmp = 1
    this._message = null

    if (this._setup === true) {
      if (this._handshake) {
        this._onhandshakert(this._handshake.recv(message))
      } else {
        if (message.byteLength !== IDHEADERBYTES) {
          this.destroy(new Error('Invalid header message received'))
          return
        }

        const remoteId = message.subarray(0, 32)
        const expectedId = streamId(this.handshakeHash, !this.isInitiator)
        const header = message.subarray(32)

        if (!b4a.equals(expectedId, remoteId)) {
          this.destroy(new Error('Invalid header received'))
          return
        }

        this._decrypt.init(header)
        this._setup = false // setup is now done
      }
      return
    }

    if (message.byteLength < ABYTES) {
      this.destroy(new Error('Invalid message received'))
      return
    }

    this.rawBytesRead += message.byteLength

    const plain = message.subarray(1, message.byteLength - ABYTES + 1)

    try {
      this._decrypt.next(message, plain)
    } catch (err) {
      this.destroy(err)
      return
    }

    // If keep alive is selective, eat the empty buffers (ie assume the other side has it enabled also)
    if (plain.byteLength === 0 && this.keepAlive !== 0) return

    if (this.push(plain) === false) {
      this.rawStream.pause()
    }
  }

  _onhandshakert(h) {
    if (this._handshakeDone === null) return

    if (h !== null) {
      if (h.data) this._rawStream.write(h.data)
      if (!h.tx) return
    }

    const done = this._handshakeDone
    const publicKey = this._handshake.keyPair.publicKey

    this._handshakeDone = null
    this._handshake = null

    if (h === null) return done(new Error('Noise handshake failed'))

    this._setupSecretStream(h.tx, h.rx, h.hash, publicKey, h.remotePublicKey)
    this._resolveOpened(true)
    done(null)
  }

  _setupSecretStream(tx, rx, handshakeHash, publicKey, remotePublicKey) {
    const buf = b4a.allocUnsafeSlow(3 + IDHEADERBYTES)
    writeUint24le(IDHEADERBYTES, buf)

    this._encrypt = new Push(unslab(tx.subarray(0, KEYBYTES)), undefined, buf.subarray(3 + 32))
    this._decrypt = new Pull(unslab(rx.subarray(0, KEYBYTES)))

    this.publicKey = publicKey
    this.remotePublicKey = remotePublicKey
    this.handshakeHash = handshakeHash

    const id = buf.subarray(3, 3 + 32)
    streamId(handshakeHash, this.isInitiator, id)

    // initialize secretbox state for unordered messages
    this._setupSecretSend(handshakeHash)

    this.emit('handshake')
    // if rawStream is a bridge, also emit it there
    if (this.rawStream !== this._rawStream) this.rawStream.emit('handshake')

    if (this.destroying) return

    this._rawStream.write(buf)
  }

  _setupSecretSend(handshakeHash) {
    this._sendState = b4a.allocUnsafeSlow(32 + 32 + 8 + 8)
    const encrypt = this._sendState.subarray(0, 32) // secrets
    const decrypt = this._sendState.subarray(32, 64)
    const counter = this._sendState.subarray(64, 72) // nonce
    const initial = this._sendState.subarray(72)

    const inputs = this.isInitiator
      ? [
          [NS_INITIATOR, NS_SEND],
          [NS_RESPONDER, NS_SEND]
        ]
      : [
          [NS_RESPONDER, NS_SEND],
          [NS_INITIATOR, NS_SEND]
        ]

    sodium.crypto_generichash_batch(encrypt, inputs[0], handshakeHash)
    sodium.crypto_generichash_batch(decrypt, inputs[1], handshakeHash)

    sodium.randombytes_buf(initial)
    counter.set(initial)
  }

  _open(cb) {
    // no autostart or no handshake yet
    if (this._rawStream === null || (this._handshake === null && this._encrypt === null)) {
      this._startDone = cb
      return
    }

    this._rawStream.on('data', this._onrawdata.bind(this))
    this._rawStream.on('end', this._onrawend.bind(this))
    this._rawStream.on('drain', this._onrawdrain.bind(this))

    if (this.enableSend) this._rawStream.on('message', this._onmessage.bind(this))

    if (this._encrypt !== null) {
      this._resolveOpened(true)
      return cb(null)
    }

    this._handshakeDone = cb

    if (this.isInitiator) this._onhandshakert(this._handshake.send())
  }

  _predestroy() {
    if (this.rawStream) {
      const error = getStreamError(this)
      this.rawStream.destroy(error)
    }

    if (this._startDone !== null) {
      const done = this._startDone
      this._startDone = null
      done(new Error('Stream destroyed'))
    }

    if (this._handshakeDone !== null) {
      const done = this._handshakeDone
      this._handshakeDone = null
      done(new Error('Stream destroyed'))
    }

    if (this._drainDone !== null) {
      const done = this._drainDone
      this._drainDone = null
      done(new Error('Stream destroyed'))
    }
  }

  _write(data, cb) {
    let wrapped = this._outgoingWrapped

    if (data !== this._outgoingPlain) {
      wrapped = b4a.allocUnsafe(data.byteLength + 3 + ABYTES)
      wrapped.set(data, 4)
    } else {
      this._outgoingWrapped = this._outgoingPlain = null
    }

    if (wrapped.byteLength - 3 > MAX_ATOMIC_WRITE) {
      return cb(
        new Error(
          'Message is too large for an atomic write. Max size is ' + MAX_ATOMIC_WRITE + ' bytes.'
        )
      )
    }
    this.rawBytesWritten += wrapped.byteLength

    writeUint24le(wrapped.byteLength - 3, wrapped)
    // offset 4 so we can do it in-place
    this._encrypt.next(wrapped.subarray(4, 4 + data.byteLength), wrapped.subarray(3))

    if (this._keepAliveTimer !== null) this._keepAliveTimer.refresh()

    if (this._rawStream.write(wrapped) === false) {
      this._drainDone = cb
    } else {
      cb(null)
    }
  }

  _final(cb) {
    this._clearKeepAlive()
    this._ended--
    this._rawStream.end()
    cb(null)
  }

  _resolveOpened(val) {
    if (this._openedDone === null) return
    const opened = this._openedDone
    this._openedDone = null
    opened(val)
    if (!val) return
    this.connected = true
    this.emit('connect')
  }

  _clearTimeout() {
    if (this._timeoutTimer === null) return
    this._timeoutTimer.destroy()
    this._timeoutTimer = null
    this.timeout = 0
  }

  _clearKeepAlive() {
    if (this._keepAliveTimer === null) return
    this._keepAliveTimer.destroy()
    this._keepAliveTimer = null
    this.keepAlive = 0
  }

  _destroy(cb) {
    this._clearKeepAlive()
    this._clearTimeout()
    this._resolveOpened(false)
    cb(null)
  }

  _boxMessage(buffer) {
    const MB = sodium.crypto_secretbox_MACBYTES // 16
    const NB = sodium.crypto_secretbox_NONCEBYTES // 24

    const counter = this._sendState.subarray(64, 72)
    sodium.sodium_increment(counter)
    if (b4a.equals(counter, this._sendState.subarray(72))) {
      this.destroy(new Error('udp send nonce exchausted'))
      return
    }

    const secret = this._sendState.subarray(0, 32)
    const envelope = b4a.allocUnsafe(8 + MB + buffer.byteLength)
    const nonce = envelope.subarray(0, NB)
    const ciphertext = envelope.subarray(8)

    b4a.fill(nonce, 0) // pad suffix
    nonce.set(counter)

    sodium.crypto_secretbox_easy(ciphertext, buffer, nonce, secret)
    return envelope
  }

  send(buffer) {
    if (!this._sendState) return
    if (!this.rawStream?.send) return // udx-stream expected

    const message = this._boxMessage(buffer)
    return this.rawStream.send(message)
  }

  trySend(buffer) {
    if (!this._sendState) return
    if (!this.rawStream?.trySend) return // udx-stream expected

    const message = this._boxMessage(buffer)
    this.rawStream.trySend(message)
  }

  _onmessage(buffer) {
    if (!this._sendState) return // messages before handshake are dropped

    const MB = sodium.crypto_secretbox_MACBYTES // 16
    const NB = sodium.crypto_secretbox_NONCEBYTES // 24

    if (buffer.byteLength < NB) return // Invalid message

    const nonce = b4a.allocUnsafe(NB)
    b4a.fill(nonce, 0)
    nonce.set(buffer.subarray(0, 8))

    const secret = this._sendState.subarray(32, 64)
    const ciphertext = buffer.subarray(8)
    const plain = buffer.subarray(8, buffer.byteLength - MB)

    if (ciphertext.byteLength < MB) return // invalid message

    const success = sodium.crypto_secretbox_open_easy(plain, ciphertext, nonce, secret)

    if (success) this.emit('message', plain)
  }

  alloc(len) {
    const buf = b4a.allocUnsafe(len + 3 + ABYTES)
    this._outgoingWrapped = buf
    this._outgoingPlain = buf.subarray(4, buf.byteLength - ABYTES + 1)
    return this._outgoingPlain
  }

  toJSON() {
    return {
      isInitiator: this.isInitiator,
      publicKey: this.publicKey && b4a.toString(this.publicKey, 'hex'),
      remotePublicKey: this.remotePublicKey && b4a.toString(this.remotePublicKey, 'hex'),
      connected: this.connected,
      destroying: this.destroying,
      destroyed: this.destroyed,
      rawStream: this.rawStream && this.rawStream.toJSON ? this.rawStream.toJSON() : null
    }
  }
}

function writeUint24le(n, buf) {
  buf[0] = n & 255
  buf[1] = (n >>> 8) & 255
  buf[2] = (n >>> 16) & 255
}

function streamId(handshakeHash, isInitiator, out = b4a.allocUnsafe(32)) {
  sodium.crypto_generichash(out, isInitiator ? NS_INITIATOR : NS_RESPONDER, handshakeHash)
  return out
}

function toBuffer(data) {
  return typeof data === 'string' ? b4a.from(data) : data
}

function destroyTimeout() {
  this.destroy(new Error('Stream timed out'))
}

function sendKeepAlive() {
  const empty = this.alloc(0)
  this.write(empty)
}
const { Duplex, Writable } = require('streamx')

class ReversePassThrough extends Duplex {
  constructor(s) {
    super()
    this._stream = s
    this._ondrain = null
  }

  _write(data, cb) {
    if (this._stream.push(data) === false) {
      this._stream._ondrain = cb
    } else {
      cb(null)
    }
  }

  _final(cb) {
    this._stream.push(null)
    cb(null)
  }

  _read(cb) {
    const ondrain = this._ondrain
    this._ondrain = null
    if (ondrain) ondrain()
    cb(null)
  }
}

module.exports = class Bridge extends Duplex {
  constructor(noiseStream) {
    super()

    this.noiseStream = noiseStream

    this._ondrain = null
    this.reverse = new ReversePassThrough(this)
  }

  get publicKey() {
    return this.noiseStream.publicKey
  }

  get remotePublicKey() {
    return this.noiseStream.remotePublicKey
  }

  get handshakeHash() {
    return this.noiseStream.handshakeHash
  }

  flush() {
    return Writable.drained(this)
  }

  _read(cb) {
    const ondrain = this._ondrain
    this._ondrain = null
    if (ondrain) ondrain()
    cb(null)
  }

  _write(data, cb) {
    if (this.reverse.push(data) === false) {
      this.reverse._ondrain = cb
    } else {
      cb(null)
    }
  }

  _final(cb) {
    this.reverse.push(null)
    cb(null)
  }
}
const sodium = require('sodium-universal')
const curve = require('noise-curve-ed')
const Noise = require('noise-handshake')
const b4a = require('b4a')

const EMPTY = b4a.alloc(0)

module.exports = class Handshake {
  constructor(isInitiator, keyPair, remotePublicKey, pattern) {
    this.isInitiator = isInitiator
    this.keyPair = keyPair
    this.noise = new Noise(pattern, isInitiator, keyPair, { curve })
    this.noise.initialise(EMPTY, remotePublicKey)
    this.destroyed = false
  }

  static keyPair(seed) {
    const publicKey = b4a.alloc(32)
    const secretKey = b4a.alloc(64)
    if (seed) sodium.crypto_sign_seed_keypair(publicKey, secretKey, seed)
    else sodium.crypto_sign_keypair(publicKey, secretKey)
    return { publicKey, secretKey }
  }

  recv(data) {
    try {
      this.noise.recv(data)
      if (this.noise.complete) return this._return(null)
      return this.send()
    } catch {
      this.destroy()
      return null
    }
  }

  // note that the data returned here is framed so we don't have to do an extra copy
  // when sending it...
  send() {
    try {
      const data = this.noise.send()
      const wrap = b4a.allocUnsafe(data.byteLength + 3)

      writeUint24le(data.byteLength, wrap)
      wrap.set(data, 3)

      return this._return(wrap)
    } catch {
      this.destroy()
      return null
    }
  }

  destroy() {
    if (this.destroyed) return
    this.destroyed = true
  }

  _return(data) {
    const tx = this.noise.complete ? b4a.toBuffer(this.noise.tx) : null
    const rx = this.noise.complete ? b4a.toBuffer(this.noise.rx) : null
    const hash = this.noise.complete ? b4a.toBuffer(this.noise.hash) : null
    const remotePublicKey = this.noise.complete ? b4a.toBuffer(this.noise.rs) : null

    return {
      data,
      remotePublicKey,
      hash,
      tx,
      rx
    }
  }
}

function writeUint24le(n, buf) {
  buf[0] = n & 255
  buf[1] = (n >>> 8) & 255
  buf[2] = (n >>> 16) & 255
}
{
  "name": "@hyperswarm/secret-stream",
  "version": "6.9.1",
  "description": "Secret stream backed by Noise and libsodium's secretstream",
  "main": "index.js",
  "files": [
    "index.js",
    "lib/**.js"
  ],
  "dependencies": {
    "b4a": "^1.1.0",
    "hypercore-crypto": "^3.3.1",
    "noise-curve-ed": "^2.0.1",
    "noise-handshake": "^4.0.0",
    "sodium-secretstream": "^1.1.0",
    "sodium-universal": "^5.0.0",
    "streamx": "^2.14.0",
    "timeout-refresh": "^2.0.0",
    "unslab": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "udx-native": "^1.13.2"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check .",
    "test": "brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/hyperswarm-secret-stream.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/hyperswarm-secret-stream/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperswarm-secret-stream"
}
const Cache = require('xache')

module.exports = class AdaptiveTimeout {
  constructor(opts = {}) {
    this._cache = new Cache({
      maxSize: opts.maxSize || 65536,
      maxAge: opts.maxAge || 10 * 60 * 1000 // 10 minutes
    })
    this._fallback = opts.fallback || AdaptiveTimeout.TimeoutExponential
    this._min = opts.min ?? 300
    this._max = opts.max || 4000
    this._jitter = opts.jitter ?? 256
  }

  // Default - aggressive ramp
  static TimeoutAggressive = [500, 750, 1000, 1500, 2000]

  // Linear - steady increase
  static TimeoutLinear = [500, 1000, 1500, 2000, 2500]

  // Exponential - slow start, rapid backoff
  static TimeoutExponential = [250, 500, 1000, 2000, 4000]

  // Gentle - conservative, patient
  static TimeoutGentle = [1000, 1250, 1500, 1750, 2000]

  // Fast - rapid fire retries
  static TimeoutFast = [200, 400, 600, 800, 1000]

  // U-shape - long, short, long
  static TimeoutUShape = [1500, 750, 500, 750, 1500]

  // Inverse U - short, long, short
  static TimeoutInverseU = [500, 1000, 1500, 1000, 500]

  // Sawtooth - alternating fast/slow
  static TimeoutSawtooth = [500, 1500, 500, 1500, 500]

  // Plateau - quick ramp then steady
  static TimeoutPlateau = [500, 1000, 2000, 2000, 2000]

  // Logarithmic - diminishing increases
  static TimeoutLogarithmic = [500, 1000, 1300, 1500, 1600]

  getValue(key) {
    return this._cache.get(key)
  }

  put(key, value) {
    let p = this._cache.get(key)

    if (!p) {
      p = { avg: value, variance: value >> 1 }
    } else {
      // blend 75% old + 25% new deviation
      p.variance += (Math.abs(p.avg - value) - p.variance) >> 2
      // blend 87.5% old + 12.5% new sample
      p.avg += (value - p.avg) >> 3
    }

    this._cache.set(key, p)

    return p
  }

  get(key, attempt = 1) {
    const p = this._cache.get(key)
    const jitter = (Math.random() * this._jitter) | 0

    if (p) {
      // known - use adaptive with linear backoff
      const base = p.avg + (p.variance << 1)
      const backoff = base * attempt
      return Math.min(Math.max(backoff + jitter, this._min), this._max)
    } else {
      // unknown - use aggressive fallback
      const base = this._fallback[Math.min(attempt - 1, this._fallback.length - 1)]
      return base + jitter
    }
  }

  has(key) {
    return this._cache.has(key)
  }

  delete(key) {
    return this._cache.delete(key)
  }

  clear() {
    this._cache.clear()
  }
}
{
  "name": "adaptive-timeout",
  "version": "1.0.1",
  "description": "adaptive-timeout",
  "main": "index.js",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    }
  },
  "files": [
    "package.json",
    "index.js",
    "index.d.ts"
  ],
  "devDependencies": {
    "brittle": "^3.19.0",
    "lunte": "^1.2.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && lunte && brittle-bare test/index.js",
    "lint": "lunte"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/adaptive-timeout.git"
  },
  "author": "Holepunch Inc",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/adaptive-timeout/issues"
  },
  "homepage": "https://github.com/holepunchto/adaptive-timeout",
  "dependencies": {
    "xache": "^1.2.1"
  }
}
function isBuffer(value) {
  return Buffer.isBuffer(value) || value instanceof Uint8Array
}

function isEncoding(encoding) {
  return Buffer.isEncoding(encoding)
}

function alloc(size, fill, encoding) {
  return Buffer.alloc(size, fill, encoding)
}

function allocUnsafe(size) {
  return Buffer.allocUnsafe(size)
}

function allocUnsafeSlow(size) {
  return Buffer.allocUnsafeSlow(size)
}

function byteLength(string, encoding) {
  return Buffer.byteLength(string, encoding)
}

function compare(a, b) {
  return Buffer.compare(a, b)
}

function concat(buffers, totalLength) {
  return Buffer.concat(buffers, totalLength)
}

function copy(source, target, targetStart, start, end) {
  return toBuffer(source).copy(target, targetStart, start, end)
}

function equals(a, b) {
  return toBuffer(a).equals(b)
}

function fill(buffer, value, offset, end, encoding) {
  return toBuffer(buffer).fill(value, offset, end, encoding)
}

function from(value, encodingOrOffset, length) {
  return Buffer.from(value, encodingOrOffset, length)
}

function includes(buffer, value, byteOffset, encoding) {
  return toBuffer(buffer).includes(value, byteOffset, encoding)
}

function indexOf(buffer, value, byfeOffset, encoding) {
  return toBuffer(buffer).indexOf(value, byfeOffset, encoding)
}

function lastIndexOf(buffer, value, byteOffset, encoding) {
  return toBuffer(buffer).lastIndexOf(value, byteOffset, encoding)
}

function swap16(buffer) {
  return toBuffer(buffer).swap16()
}

function swap32(buffer) {
  return toBuffer(buffer).swap32()
}

function swap64(buffer) {
  return toBuffer(buffer).swap64()
}

function toBuffer(buffer) {
  if (Buffer.isBuffer(buffer)) return buffer
  return Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

function toString(buffer, encoding, start, end) {
  return toBuffer(buffer).toString(encoding, start, end)
}

function write(buffer, string, offset, length, encoding) {
  return toBuffer(buffer).write(string, offset, length, encoding)
}

function readDoubleBE(buffer, offset) {
  return toBuffer(buffer).readDoubleBE(offset)
}

function readDoubleLE(buffer, offset) {
  return toBuffer(buffer).readDoubleLE(offset)
}

function readFloatBE(buffer, offset) {
  return toBuffer(buffer).readFloatBE(offset)
}

function readFloatLE(buffer, offset) {
  return toBuffer(buffer).readFloatLE(offset)
}

function readInt32BE(buffer, offset) {
  return toBuffer(buffer).readInt32BE(offset)
}

function readInt32LE(buffer, offset) {
  return toBuffer(buffer).readInt32LE(offset)
}

function readUInt32BE(buffer, offset) {
  return toBuffer(buffer).readUInt32BE(offset)
}

function readUInt32LE(buffer, offset) {
  return toBuffer(buffer).readUInt32LE(offset)
}

function writeDoubleBE(buffer, value, offset) {
  return toBuffer(buffer).writeDoubleBE(value, offset)
}

function writeDoubleLE(buffer, value, offset) {
  return toBuffer(buffer).writeDoubleLE(value, offset)
}

function writeFloatBE(buffer, value, offset) {
  return toBuffer(buffer).writeFloatBE(value, offset)
}

function writeFloatLE(buffer, value, offset) {
  return toBuffer(buffer).writeFloatLE(value, offset)
}

function writeInt32BE(buffer, value, offset) {
  return toBuffer(buffer).writeInt32BE(value, offset)
}

function writeInt32LE(buffer, value, offset) {
  return toBuffer(buffer).writeInt32LE(value, offset)
}

function writeUInt32BE(buffer, value, offset) {
  return toBuffer(buffer).writeUInt32BE(value, offset)
}

function writeUInt32LE(buffer, value, offset) {
  return toBuffer(buffer).writeUInt32LE(value, offset)
}

module.exports = {
  isBuffer,
  isEncoding,
  alloc,
  allocUnsafe,
  allocUnsafeSlow,
  byteLength,
  compare,
  concat,
  copy,
  equals,
  fill,
  from,
  includes,
  indexOf,
  lastIndexOf,
  swap16,
  swap32,
  swap64,
  toBuffer,
  toString,
  write,
  readDoubleBE,
  readDoubleLE,
  readFloatBE,
  readFloatLE,
  readInt32BE,
  readInt32LE,
  readUInt32BE,
  readUInt32LE,
  writeDoubleBE,
  writeDoubleLE,
  writeFloatBE,
  writeFloatLE,
  writeInt32BE,
  writeInt32LE,
  writeUInt32BE,
  writeUInt32LE
}
{
  "name": "b4a",
  "version": "1.8.1",
  "description": "Bridging the gap between buffers and typed arrays",
  "exports": {
    "./package": "./package.json",
    ".": {
      "react-native": "./react-native.js",
      "browser": "./browser.js",
      "default": "./index.js"
    }
  },
  "files": [
    "browser.js",
    "index.js",
    "react-native.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:bare && npm run test:node",
    "test:bare": "brittle-bare --coverage test.mjs",
    "test:node": "brittle-node --coverage test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/b4a.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/b4a/issues"
  },
  "homepage": "https://github.com/holepunchto/b4a#readme",
  "devDependencies": {
    "brittle": "^3.5.2",
    "lunte": "^1.7.0",
    "nanobench": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "react-native-b4a": "*"
  },
  "peerDependenciesMeta": {
    "react-native-b4a": {
      "optional": true
    }
  }
}
const ESC = '\x1b'
const CSI = ESC + '['
const SGR = (n) => CSI + n + 'm'

exports.constants = {
  ESC,
  CSI,
  SGR
}

// https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_(Control_Sequence_Introducer)_sequences

exports.cursorHide = CSI + '?25l'
exports.cursorShow = CSI + '?25h'

exports.cursorUp = function cursorUp(n = 1) {
  return CSI + n + 'A'
}

exports.cursorDown = function cursorDown(n = 1) {
  return CSI + n + 'B'
}

exports.cursorForward = function cursorForward(n = 1) {
  return CSI + n + 'C'
}

exports.cursorBack = function cursorBack(n = 1) {
  return CSI + n + 'D'
}

exports.cursorNextLine = function cursorNextLine(n = 1) {
  return CSI + n + 'E'
}

exports.cursorPreviousLine = function cursorPreviousLine(n = 1) {
  return CSI + n + 'F'
}

exports.cursorPosition = function cursorPosition(column, row = 0) {
  if (row === 0) return CSI + (column + 1) + 'G'

  return CSI + (row + 1) + ';' + (column + 1) + 'H'
}

exports.eraseDisplayEnd = CSI + 'J'
exports.eraseDisplayStart = CSI + '1J'
exports.eraseDisplay = CSI + '2J'
exports.eraseLineEnd = CSI + 'K'
exports.eraseLineStart = CSI + '1K'
exports.eraseLine = CSI + '2K'

exports.scrollUp = function scrollUp(n = 1) {
  return CSI + n + 'S'
}

exports.scrollDown = function scrollDown(n = 1) {
  return CSI + n + 'T'
}

// https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_(Select_Graphic_Rendition)_parameters

exports.modifierReset = SGR(0)
exports.modifierBold = SGR(1)
exports.modifierDim = SGR(2)
exports.modifierItalic = SGR(3)
exports.modifierUnderline = SGR(4)
exports.modifierNormal = SGR(22)
exports.modifierNotItalic = SGR(23)
exports.modifierNotUnderline = SGR(24)

// https://en.wikipedia.org/wiki/ANSI_escape_code#Colors

exports.colorBlack = SGR(30)
exports.colorRed = SGR(31)
exports.colorGreen = SGR(32)
exports.colorYellow = SGR(33)
exports.colorBlue = SGR(34)
exports.colorMagenta = SGR(35)
exports.colorCyan = SGR(36)
exports.colorWhite = SGR(37)
exports.colorDefault = SGR(39)
exports.colorBrightBlack = SGR(90)
exports.colorBrightRed = SGR(91)
exports.colorBrightGreen = SGR(92)
exports.colorBrightYellow = SGR(93)
exports.colorBrightBlue = SGR(94)
exports.colorBrightMagenta = SGR(95)
exports.colorBrightCyan = SGR(96)
exports.colorBrightWhite = SGR(97)
{
  "name": "bare-ansi-escapes",
  "version": "2.2.3",
  "description": "Parse and produce ANSI escape sequences",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./key-decoder": {
      "types": "./key-decoder.d.ts",
      "default": "./key-decoder.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "key-decoder.js",
    "key-decoder.d.ts"
  ],
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-ansi-escapes.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-ansi-escapes/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-ansi-escapes#readme",
  "dependencies": {
    "bare-stream": "^2.6.5"
  },
  "devDependencies": {
    "bare-buffer": "^3.0.2",
    "brittle": "^3.3.2",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  },
  "peerDependencies": {
    "bare-buffer": "*"
  },
  "peerDependenciesMeta": {
    "bare-buffer": {
      "optional": true
    }
  }
}
const inspect = require('bare-inspect')

class AssertionError extends Error {
  constructor(opts = {}) {
    let { message = null, actual, expected, operator } = opts

    if (message === null) {
      message = `${inspect(actual)} ${operator} ${inspect(expected)}`
    }

    super(message)

    this.actual = actual
    this.expected = expected
    this.operator = operator
  }

  get name() {
    return 'AssertionError'
  }

  get code() {
    'ASSERTION'
  }
}

function assertFail(opts, fn) {
  if (opts.message instanceof Error) throw opts.message

  const err = new AssertionError(opts)

  if (Error.captureStackTrace) Error.captureStackTrace(err, fn)

  throw err
}

module.exports = exports = function assert(actual, message) {
  if (actual) return

  assertFail({ message, actual, expected: true, operator: '==' }, assert)
}

exports.AssertionError = AssertionError

exports.fail = function fail(message) {
  if (message === undefined) message = 'Failed'

  assertFail({ message, operator: 'fail' }, fail)
}

exports.ok = function ok(actual, message) {
  if (actual) return

  assertFail({ message, actual, expected: true, operator: '==' }, ok)
}

exports.notOk = function ok(actual, message) {
  if (!actual) return

  assertFail({ message, actual, expected: false, operator: '==' }, ok)
}

exports.equal = function equal(actual, expected, message) {
  if (actual == expected || (actual !== actual && expected !== expected)) {
    return
  }

  assertFail({ message, actual, expected, operator: '==' }, equal)
}

exports.notEqual = function notEqual(actual, expected, message) {
  if (actual != expected && (actual === actual || expected === expected)) {
    return
  }

  assertFail({ message, actual, expected, operator: '!=' }, notEqual)
}

exports.strictEqual = function strictEqual(actual, expected, message) {
  if (Object.is(actual, expected)) return

  assertFail(
    { message, actual, expected, operator: 'strictEqual' },
    strictEqual
  )
}

exports.notStrictEqual = function notStrictEqual(actual, expected, message) {
  if (!Object.is(actual, expected)) return

  assertFail(
    { message, actual, expected, operator: 'notStrictEqual' },
    notStrictEqual
  )
}
{
  "name": "bare-assert",
  "version": "1.2.0",
  "description": "Assertion library for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts"
  ],
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-assert.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-assert/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-assert#readme",
  "dependencies": {
    "bare-inspect": "^3.1.2"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  }
}
const errors = require('./lib/errors')

class EventListener {
  constructor() {
    this.list = []
    this.count = 0
  }

  append(ctx, name, fn, once) {
    this.count++
    ctx.emit('newListener', name, fn) // Emit BEFORE adding
    this.list.push([fn, once])
  }

  prepend(ctx, name, fn, once) {
    this.count++
    ctx.emit('newListener', name, fn) // Emit BEFORE adding
    this.list.unshift([fn, once])
  }

  remove(ctx, name, fn) {
    for (let i = 0, n = this.list.length; i < n; i++) {
      const l = this.list[i]

      if (l[0] === fn) {
        this.list.splice(i, 1)

        if (this.count === 1) delete ctx._events[name]

        ctx.emit('removeListener', name, fn) // Emit AFTER removing

        this.count--
        return
      }
    }
  }

  removeAll(ctx, name) {
    const list = [...this.list]
    this.list = []

    if (this.count === list.length) delete ctx._events[name]

    for (let i = list.length - 1; i >= 0; i--) {
      ctx.emit('removeListener', name, list[i][0]) // Emit AFTER removing
    }

    this.count -= list.length
  }

  emit(ctx, name, ...args) {
    const list = [...this.list]

    for (let i = 0, n = list.length; i < n; i++) {
      const l = list[i]

      if (l[1] === true) this.remove(ctx, name, l[0])

      Reflect.apply(l[0], ctx, args)
    }

    return list.length > 0
  }
}

function appendListener(ctx, name, fn, once) {
  if (ctx._events === undefined) ctx._events = Object.create(null)
  const e = ctx._events[name] || (ctx._events[name] = new EventListener())
  e.append(ctx, name, fn, once)
  return ctx
}

function prependListener(ctx, name, fn, once) {
  if (ctx._events === undefined) ctx._events = Object.create(null)
  const e = ctx._events[name] || (ctx._events[name] = new EventListener())
  e.prepend(ctx, name, fn, once)
  return ctx
}

function removeListener(ctx, name, fn) {
  if (ctx._events === undefined) return ctx
  const e = ctx._events[name]
  if (e !== undefined) e.remove(ctx, name, fn)
  return ctx
}

function throwUnhandledError(...args) {
  let err

  if (args.length > 0) err = args[0]

  if (err instanceof Error === false) err = errors.UNHANDLED_ERROR(err)

  if (Error.captureStackTrace) {
    Error.captureStackTrace(err, exports.prototype.emit)
  }

  queueMicrotask(() => {
    throw err
  })
}

module.exports = exports = class EventEmitter {
  constructor() {
    this._events = Object.create(null)
  }

  addListener(name, fn) {
    return appendListener(this, name, fn, false)
  }

  addOnceListener(name, fn) {
    return appendListener(this, name, fn, true)
  }

  prependListener(name, fn) {
    return prependListener(this, name, fn, false)
  }

  prependOnceListener(name, fn) {
    return prependListener(this, name, fn, true)
  }

  removeListener(name, fn) {
    return removeListener(this, name, fn)
  }

  on(name, fn) {
    return appendListener(this, name, fn, false)
  }

  once(name, fn) {
    return appendListener(this, name, fn, true)
  }

  off(name, fn) {
    return removeListener(this, name, fn)
  }

  emit(name, ...args) {
    if (name === 'error' && this._events !== undefined && this._events.error === undefined) {
      throwUnhandledError(...args)
    }

    if (this._events === undefined) return false
    const e = this._events[name]
    return e === undefined ? false : e.emit(this, name, ...args)
  }

  listeners(name) {
    if (this._events === undefined) return []
    const e = this._events[name]
    return e === undefined ? [] : [...e.list]
  }

  rawListeners(name) {
    if (this._events === undefined) return []
    const e = this._events[name]
    return e === undefined ? [] : e.list.map((l) => l[0])
  }

  eventNames() {
    if (this._events === undefined) return []
    return Reflect.ownKeys(this._events)
  }

  listenerCount(name) {
    if (this._events === undefined) return 0
    const e = this._events[name]
    return e === undefined ? 0 : e.list.length
  }

  getMaxListeners() {
    return EventEmitter.defaultMaxListeners
  }

  setMaxListeners(n) {}

  removeAllListeners(name) {
    if (arguments.length === 0) {
      for (const key of Reflect.ownKeys(this._events)) {
        if (key === 'removeListener') continue
        this.removeAllListeners(key)
      }
      this.removeAllListeners('removeListener')
    } else {
      const e = this._events[name]
      if (e !== undefined) e.removeAll(this, name)
    }
    return this
  }
}

exports.EventEmitter = exports

exports.errors = errors

exports.defaultMaxListeners = 10

exports.on = function on(emitter, name, opts = {}) {
  const { signal } = opts

  if (signal && signal.aborted) {
    throw errors.OPERATION_ABORTED(signal.reason)
  }

  let error = null
  let done = false

  const events = []
  const promises = []

  if (name !== 'error') emitter.on('error', onerror)

  if (signal) signal.addEventListener('abort', onabort)

  emitter.on(name, onevent)

  return {
    next() {
      if (events.length) {
        return Promise.resolve({ value: events.shift(), done: false })
      }

      if (error) {
        const err = error

        error = null

        return Promise.reject(err)
      }

      if (done) return onclose()

      return new Promise((resolve, reject) => promises.push({ resolve, reject }))
    },

    return() {
      return onclose()
    },

    throw(err) {
      return onerror(err)
    },

    [Symbol.asyncIterator]() {
      return this
    }
  }

  function onevent(...args) {
    if (promises.length) {
      promises.shift().resolve({ value: args, done: false })
    } else {
      events.push(args)
    }
  }

  function onerror(err) {
    emitter.off(name, onevent).off('error', onerror)

    if (promises.length) {
      promises.shift().reject(err)
    } else {
      error = err
    }

    return Promise.resolve({ done: true })
  }

  function onabort() {
    signal.removeEventListener('abort', onabort)

    onerror(errors.OPERATION_ABORTED(signal.reason))
  }

  function onclose() {
    emitter.off(name, onevent)

    if (name !== 'error') emitter.off('error', onerror)

    if (signal) signal.removeEventListener('abort', onabort)

    done = true

    if (promises.length) promises.shift().resolve({ done: true })

    return Promise.resolve({ done: true })
  }
}

exports.once = function once(emitter, name, opts = {}) {
  const { signal } = opts

  if (signal && signal.aborted) {
    return Promise.reject(errors.OPERATION_ABORTED(signal.reason))
  }

  return new Promise((resolve, reject) => {
    if (name !== 'error') emitter.on('error', onerror)

    if (signal) signal.addEventListener('abort', onabort)

    emitter.once(name, onevent)

    function onevent(...args) {
      if (name !== 'error') emitter.off('error', onerror)

      if (signal) signal.removeEventListener('abort', onabort)

      resolve(args)
    }

    function onerror(err) {
      emitter.off(name, onevent)

      if (name !== 'error') emitter.off('error', onerror)

      reject(err)
    }

    function onabort() {
      signal.removeEventListener('abort', onabort)

      onerror(errors.OPERATION_ABORTED(signal.reason))
    }
  })
}

exports.forward = function forward(from, to, names, opts = {}) {
  if (typeof names === 'string') names = [names]

  const { emit = to.emit.bind(to) } = opts

  const listeners = names.map(
    (name) =>
      function onevent(...args) {
        emit(name, ...args)
      }
  )

  to.on('newListener', (name) => {
    const i = names.indexOf(name)

    if (i !== -1 && to.listenerCount(name) === 0) {
      from.on(name, listeners[i])
    }
  }).on('removeListener', (name) => {
    const i = names.indexOf(name)

    if (i !== -1 && to.listenerCount(name) === 0) {
      from.off(name, listeners[i])
    }
  })
}

exports.listenerCount = function listenerCount(emitter, name) {
  return emitter.listenerCount(name)
}

exports.getMaxListeners = function getMaxListeners(emitter) {
  if (typeof emitter.getMaxListeners === 'function') {
    return emitter.getMaxListeners()
  }

  return exports.defaultMaxListeners
}

exports.setMaxListeners = function setMaxListeners(n, ...emitters) {
  if (emitters.length === 0) exports.defaultMaxListeners = n
  else {
    for (const emitter of emitters) {
      if (typeof emitter.setMaxListeners === 'function') {
        emitter.setMaxListeners(n)
      }
    }
  }
}
module.exports = class EventEmitterError extends Error {
  constructor(msg, code, fn = EventEmitterError, opts) {
    super(`${code}: ${msg}`, opts)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'EventEmitterError'
  }

  static OPERATION_ABORTED(cause, msg = 'Operation aborted') {
    return new EventEmitterError(msg, 'OPERATION_ABORTED', EventEmitterError.OPERATION_ABORTED, {
      cause
    })
  }

  static UNHANDLED_ERROR(cause, msg = 'Unhandled error') {
    return new EventEmitterError(msg, 'UNHANDLED_ERROR', EventEmitterError.UNHANDLED_ERROR, {
      cause
    })
  }
}
{
  "name": "bare-events",
  "version": "2.9.1",
  "description": "Event emitters for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    },
    "./web": {
      "types": "./web.d.ts",
      "default": "./web.js"
    },
    "./errors": "./lib/errors.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "global.js",
    "global.d.ts",
    "web.js",
    "web.d.ts",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:bare && npm run test:node",
    "test:bare": "brittle-bare --coverage test.js",
    "test:node": "brittle-node --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-events.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-events/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-events#readme",
  "devDependencies": {
    "bare-abort-controller": "^1.0.0",
    "brittle": "^3.3.2",
    "lunte": "^1.8.0",
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^2.0.0",
    "uncaughts": "^1.1.1"
  },
  "peerDependencies": {
    "bare-abort-controller": "*"
  },
  "peerDependenciesMeta": {
    "bare-abort-controller": {
      "optional": true
    }
  }
}
module.exports = require.addon()
const ansiEscapes = require('bare-ansi-escapes')
const getType = require('bare-type')
const binding = require('./binding')

const PLAIN_KEY = /^[a-zA-Z_][a-zA-Z_0-9]*$/

const defaultDepth = 2
const defaultBreakLength = 80
const defaultMaxArrayLength = 40

module.exports = exports = function inspect(value, opts = {}) {
  const {
    colors = false,
    depth = defaultDepth,
    breakLength = defaultBreakLength,
    stylize = defaultStylize(colors)
  } = opts

  const references = new InspectRefMap()

  const tree = inspectValue(value, 0, {
    colors,
    depth,
    breakLength,
    stylize,
    references
  })

  return tree.toString()
}

exports.styles = {
  bigint: ansiEscapes.colorYellow,
  boolean: ansiEscapes.colorYellow,
  date: ansiEscapes.colorMagenta,
  module: ansiEscapes.modifierUnderline,
  name: ansiEscapes.modifierReset,
  null: ansiEscapes.modifierBold,
  number: ansiEscapes.colorYellow,
  regexp: ansiEscapes.colorRed,
  special: ansiEscapes.colorCyan,
  string: ansiEscapes.colorGreen,
  symbol: ansiEscapes.colorGreen,
  undefined: ansiEscapes.colorBrightBlack
}

const styles = exports.styles

function defaultStylize(colors) {
  return function stylize(value, style) {
    const color = colors && styles[style]

    if (color) return color + value + ansiEscapes.modifierReset

    return value
  }
}

class InspectRefMap {
  constructor() {
    this.refs = new WeakMap()
    this.ids = new WeakMap()
    this.nextId = 1
  }

  has(object) {
    return this.refs.has(object)
  }

  get(object) {
    return this.refs.get(object) || null
  }

  set(object, ref) {
    this.refs.set(object, ref)
  }

  id(object) {
    let id = this.ids.get(object)
    if (id) return id

    id = this.nextId++
    this.ids.set(object, id)

    return id
  }
}

class InspectNode {
  constructor(depth, length, opts) {
    const { breakLength = defaultBreakLength, breakAlways = false } = opts

    this.depth = depth
    this.length = length
    this.breakLength = breakLength
    this.breakAlways = breakAlways
  }

  pad(n, string) {
    return string.padStart(n, ' ')
  }

  indent(n, string) {
    return '  '.repeat(n) + string
  }
}

class InspectRef extends InspectNode {
  constructor(depth, opts) {
    super(depth, '[circular *]'.length, opts)

    this.refs = opts.references
    this.count = 0
    this.circular = false
    this.color = opts.colors && styles.special
  }

  get id() {
    return this.refs.id(this)
  }

  increment() {
    return ++this.count
  }

  decrement() {
    return --this.count
  }

  toString(opts = {}) {
    const { offset = 0, pad = 0, indent = 0 } = opts

    let value = this.pad(pad, '[circular *' + this.id + ']')

    if (this.color) value = this.color + value + ansiEscapes.modifierReset

    return offset ? value : this.indent(indent, value)
  }
}

class InspectLeaf extends InspectNode {
  constructor(value, color, depth, opts) {
    const length = value.length

    if (value.includes('\n')) {
      value = value.replaceAll('\n', '\n' + '  '.repeat(depth))

      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.value = value
    this.color = opts.colors && color
  }

  toString(opts = {}) {
    const { offset = 0, pad = 0, indent = 0 } = opts

    let value = this.pad(pad, this.value)

    if (this.color) value = this.color + value + ansiEscapes.modifierReset

    return offset ? value : this.indent(indent, value)
  }
}

class InspectPair extends InspectNode {
  constructor(delim, left, right, depth, opts) {
    const length = left.length + delim.length + right.length

    if (left.breakAlways || right.breakAlways) {
      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.delim = delim
    this.left = left
    this.right = right
  }

  toString(opts = {}) {
    const { indent = 0 } = opts

    return this.indent(
      indent,
      this.left +
        this.delim +
        this.right.toString({
          indent,
          offset: this.left.length + this.delim.length
        })
    )
  }
}

class InspectSuspension extends InspectNode {
  constructor(overflow, depth, opts) {
    const label = `... ${overflow} more`

    super(depth, label.length, opts)

    this.label = label
  }

  toString(opts = {}) {
    const { indent = 0 } = opts

    return this.indent(indent, this.label)
  }
}

class InspectSequence extends InspectNode {
  constructor(header, footer, delim, values, ref, depth, opts) {
    const { tabulate = false } = opts

    const length =
      (ref.circular ? '<ref *>'.length + 1 : 0) +
      header.length +
      values.reduce(
        (length, value, i) =>
          length + value.length + (i === 0 ? 0 : delim.length),
        0
      ) +
      footer.length

    if (values.some((value) => value.breakAlways)) {
      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.header = header
    this.footer = footer
    this.delim = delim
    this.values = values
    this.ref = ref
    this.tabulate = tabulate
  }

  toString(opts = {}) {
    const { offset = 0, indent = 0 } = opts

    const split =
      this.breakAlways ||
      (this.values.length &&
        (offset + this.length > this.breakLength ||
          indent * 2 + this.length > this.breakLength))

    let header = this.header

    if (this.ref.circular) {
      header = '<ref *' + this.ref.id + '> ' + header
    }

    if (this.values.length === 0) {
      header = header.trimEnd()
    }

    if (offset === 0) {
      header = this.indent(indent, header)
    }

    if (split) {
      header = header.trimEnd() + '\n'
    }

    let string = header

    let columns = 1
    let pad = 0

    if (this.tabulate) {
      const widest = this.values.reduce(
        (length, value) =>
          value.breakAlways ? length : Math.max(length, value.length),
        0
      )

      if (widest) {
        columns = Math.max(
          columns,
          Math.floor(
            (this.breakLength - indent * 2) / (widest + this.delim.length)
          )
        )

        if (columns > 1) pad = widest
      }
    }

    for (let i = 0, n = this.values.length, offset = 0; i < n; i++) {
      const value = this.values[i]

      if (split) {
        let part

        if (i % columns === 0 || value.breakAlways) {
          part = value.toString({ indent: indent + 1, pad })
        } else {
          part = value.toString({ pad })
        }

        string += part

        if (i < n - 1) {
          if (i % columns === columns - 1 || this.values[i + 1].breakAlways) {
            string += this.delim.trimEnd() + '\n'
          } else {
            string += this.delim
          }
        }
      } else {
        if (i > 0) string += this.delim

        string += value.toString({ offset })

        offset += value.length
      }
    }

    let footer = this.footer

    if (this.values.length === 0) {
      footer = footer.trimStart()
    }

    if (split) {
      string += '\n' + this.indent(indent, footer.trimStart())
    } else {
      string += footer
    }

    return string
  }
}

function inspectValue(value, depth, opts) {
  const type = getType(value)

  if (type.isUndefined()) return inspectUndefined(depth, opts)
  if (type.isNull()) return inspectNull(depth, opts)
  if (type.isBoolean()) return inspectBoolean(value, depth, opts)
  if (type.isNumber()) return inspectNumber(value, depth, opts)
  if (type.isBigInt()) return inspectBigInt(value, depth, opts)
  if (type.isString()) return inspectString(value, depth, opts)
  if (type.isSymbol()) return inspectSymbol(value, depth, opts)
  if (type.isObject()) return inspectObject(type, value, depth, opts)
  if (type.isFunction()) return inspectFunction(type, value, depth, opts)
  if (type.isExternal()) return inspectExternal(value, opts, opts)
}

function inspectUndefined(depth, opts) {
  return new InspectLeaf('undefined', styles.undefined, depth, opts)
}

function inspectNull(depth, opts) {
  return new InspectLeaf('null', styles.null, depth, opts)
}

function inspectBoolean(value, depth, opts) {
  return new InspectLeaf(value.toString(), styles.boolean, depth, opts)
}

function inspectNumber(value, depth, opts) {
  let string

  if (Object.is(value, -0)) {
    string = '-0'
  } else {
    string = value.toString(10)
  }

  return new InspectLeaf(string, styles.number, depth, opts)
}

function inspectBigInt(value, depth, opts) {
  return new InspectLeaf(value.toString(10) + 'n', styles.bigint, depth, opts)
}

const STRING_ESCAPES =
  /[\ud800-\udbff][\udc00-\udfff]|[\u0000-\u001f'\\\ud800-\udfff]/g

function inspectString(value, depth, opts) {
  // https://tc39.es/ecma262/multipage/structured-data.html#sec-quotejsonstring
  const string = value.replace(STRING_ESCAPES, (match) => {
    if (match.length === 2) return match

    switch (match) {
      case "'":
        return "\\'"
      case '\\':
        return '\\\\'
      case '\b':
        return '\\b'
      case '\t':
        return '\\t'
      case '\n':
        return '\\n'
      case '\f':
        return '\\f'
      case '\r':
        return '\\r'
      default:
        return '\\u' + match.charCodeAt(0).toString(16).padStart(4, '0')
    }
  })

  return new InspectLeaf("'" + string + "'", styles.string, depth, opts)
}

function inspectSymbol(value, depth, opts) {
  return new InspectLeaf(value.toString(), styles.symbol, depth, opts)
}

function inspectKey(value, depth, opts) {
  if (PLAIN_KEY.test(value)) {
    return new InspectLeaf(value, null, depth, opts)
  } else {
    return inspectValue(value, depth, opts)
  }
}

function inspectObject(type, object, depth, opts) {
  const refs = opts.references

  let ref = refs.get(object)
  if (ref === null) {
    ref = new InspectRef(depth, opts)
    refs.set(object, ref)
  } else if (ref.count) {
    ref.circular = true
    return ref
  }

  const maxDepth = typeof opts.depth === 'number' ? opts.depth : Infinity

  if (maxDepth < depth) {
    const constructor = object.constructor

    return new InspectLeaf(
      '[' +
        (constructor && constructor.name ? constructor.name : 'Object') +
        ']',
      styles.special,
      depth,
      opts
    )
  }

  const inspect =
    object[Symbol.for('bare.inspect')] ||
    object[Symbol.for('nodejs.util.inspect.custom')]

  if (typeof inspect === 'function') {
    const value = inspect.call(
      object,
      typeof opts.depth === 'number' ? opts.depth - depth : null,
      {
        colors: opts.colors,
        breakLength: opts.breakLength,
        stylize: opts.stylize
      },
      exports
    )

    if (typeof value === 'object' && value !== null) {
      refs.set(value, ref)
    }

    if (typeof value !== 'string') {
      return inspectValue(value, depth, opts)
    }

    return new InspectLeaf(value, null, depth, opts)
  }

  if (type.isArray()) return inspectArray(object, ref, depth, opts)
  if (type.isDate()) return inspectDate(object, ref, depth, opts)
  if (type.isRegExp()) return inspectRegExp(object, ref, depth, opts)
  if (type.isError()) return inspectError(object, ref, depth, opts)
  if (type.isPromise()) return inspectPromise(object, ref, depth, opts)
  if (type.isMap()) return inspectMap(object, ref, depth, opts)
  if (type.isSet()) return inspectSet(object, ref, depth, opts)
  if (type.isWeakMap()) return inspectWeakMap(object, ref, depth, opts)
  if (type.isWeakSet()) return inspectWeakSet(object, ref, depth, opts)
  if (type.isWeakRef()) return inspectWeakRef(object, ref, depth, opts)
  if (type.isArrayBuffer()) return inspectArrayBuffer(object, ref, depth, opts)
  if (type.isSharedArrayBuffer())
    return inspectSharedArrayBuffer(object, ref, depth, opts)
  if (type.isTypedArray()) return inspectTypedArray(object, ref, depth, opts)
  if (type.isDataView()) return inspectDataView(object, ref, depth, opts)

  ref.increment()

  const values = []

  for (const key in object) {
    if (key === 'constructor') continue

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(object[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  let header = '{ '

  const tag = object[Symbol.toStringTag]

  if (tag) header = '[' + tag + '] ' + header

  if (object.constructor) {
    const name = object.constructor.name

    if (name && name !== 'Object') {
      header = object.constructor.name + ' ' + header
    }
  }

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectArray(array, ref, depth, opts) {
  const { maxArrayLength = defaultMaxArrayLength } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxArrayLength, 0)

  for (let i = 0, n = array.length; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(array.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(inspectValue(array[i], depth + 1, opts))
  }

  for (const key of binding.getOwnNonIndexPropertyNames(array)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(array[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  let header = '[ '

  if (array.constructor.name !== 'Array') {
    header = array.constructor.name + '(' + array.length + ') ' + header
  }

  return new InspectSequence(header, ' ]', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectDate(date, ref, depth, opts) {
  return new InspectLeaf(date.toISOString(), styles.date, depth, opts)
}

function inspectRegExp(regExp, ref, depth, opts) {
  return new InspectLeaf(regExp.toString(), styles.regexp, depth, opts)
}

function inspectError(error, ref, depth, opts) {
  let header

  if ('stack' in error) {
    header = error.stack

    if (depth > 0) {
      header = header.replaceAll('\n', '\n' + '  '.repeat(depth))
    }
  } else {
    header = error.toString()
  }

  const builtins = ['cause']

  if (error.name === 'AggregateError') {
    builtins.push('errors')
  } else if (error.name === 'SuppressedError') {
    builtins.push('error', 'suppressed')
  }

  const values = []

  for (const key of builtins) {
    if (key in error === false) continue

    values.push(
      new InspectPair(
        ': ',
        new InspectLeaf('[' + key + ']', null, depth + 1, opts),
        inspectValue(error[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key in error) {
    if (key === 'constructor' || builtins.includes(key)) continue

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(error[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  if (values.length === 0) return new InspectLeaf(header, null, depth, opts)

  return new InspectSequence(
    header + ' {',
    ' }',
    ', ',
    values,
    ref,
    depth,
    opts
  )
}

function inspectPromise(promise, ref, depth, opts) {
  ref.increment()

  const state = binding.getPromiseState(promise)

  const values = []

  switch (state) {
    case 0: // Pending
      values.push(new InspectLeaf('<pending>', styles.special, depth, opts))
      break

    case 1: // Fulfilled
      values.push(inspectValue(binding.getPromiseResult(promise), depth, opts))
      break

    case 2: // Rejected
      values.push(
        new InspectLeaf('<rejected>', styles.special, depth, opts),
        inspectValue(binding.getPromiseResult(promise), depth, opts)
      )
  }

  ref.decrement()

  const header = promise.constructor.name + ' { '

  return new InspectSequence(header, ' }', ' ', values, ref, depth, opts)
}

function inspectMap(map, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxMapLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = maxMapLength

  for (const entry of map) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(map.size - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )
      break
    }

    values.push(
      new InspectPair(
        ' => ',
        inspectValue(entry[0], depth + 1, opts),
        inspectValue(entry[1], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key in map) {
    if (key === 'constructor') continue

    const value = inspectValue(map[key], depth + 1, opts)

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        value,
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = map.constructor.name + '(' + map.size + ') { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectSet(set, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxSetLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = maxSetLength

  for (const entry of set) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(set.size - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )
      break
    }

    values.push(inspectValue(entry, depth + 1, opts))
  }

  for (const key in set) {
    if (key === 'constructor') continue

    const value = inspectValue(set[key], depth + 1, opts)

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        value,
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = set.constructor.name + '(' + set.size + ') { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectWeakMap(weakMap, ref, depth, opts) {
  const header = weakMap.constructor.name + ' { '

  return new InspectSequence(
    header,
    ' }',
    ' ',
    [new InspectLeaf('<items unknown>', styles.special, depth + 1, opts)],
    ref,
    depth,
    opts
  )
}

function inspectWeakSet(weakSet, ref, depth, opts) {
  const header = weakSet.constructor.name + ' { '

  return new InspectSequence(
    header,
    ' }',
    ' ',
    [new InspectLeaf('<items unknown>', styles.special, depth + 1, opts)],
    ref,
    depth,
    opts
  )
}

function inspectWeakRef(weakRef, ref, depth, opts) {
  const target = weakRef.deref()

  let value

  if (target === undefined) {
    value = new InspectLeaf('<cleared>', styles.special, depth + 1, opts)
  } else {
    value = inspectValue(target, depth + 1, opts)
  }

  const header = weakRef.constructor.name + ' { '

  return new InspectSequence(header, ' }', ' ', [value], ref, depth, opts)
}

function inspectArrayBuffer(arrayBuffer, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(arrayBuffer[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = arrayBuffer.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectSharedArrayBuffer(sharedArrayBuffer, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(sharedArrayBuffer[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = sharedArrayBuffer.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectTypedArray(typedArray, ref, depth, opts) {
  if (Buffer.isBuffer(typedArray)) {
    return inspectBuffer(typedArray, ref, depth, opts)
  }

  const {
    maxArrayLength = defaultMaxArrayLength,
    maxTypedArrayLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxTypedArrayLength, 0)

  for (let i = 0, n = typedArray.length; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(typedArray.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(inspectValue(typedArray[i], depth + 1, opts))
  }

  for (const key of binding.getOwnNonIndexPropertyNames(typedArray)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(typedArray[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = typedArray.constructor.name + '(' + typedArray.length + ') [ '

  return new InspectSequence(header, ' ]', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectBuffer(buffer, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxBufferLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxBufferLength, 0)

  for (let i = 0, n = buffer.byteLength; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(buffer.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(
      new InspectLeaf(
        buffer[i].toString(16).padStart(2, '0'),
        null,
        depth + 1,
        opts
      )
    )
  }

  for (const key of binding.getOwnNonIndexPropertyNames(buffer)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(buffer[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  return new InspectSequence('<Buffer ', '>', ' ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectDataView(dataView, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength', 'byteOffset', 'buffer']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(dataView[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key of binding.getOwnNonIndexPropertyNames(dataView)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(dataView[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = dataView.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectFunction(type, fn, depth, opts) {
  if (fn.toString().startsWith('class')) return inspectClass(fn, depth, opts)

  let tag = 'function'

  if (type.isGeneratorFunction()) tag = 'generator ' + tag
  if (type.isAsyncFunction()) tag = 'async ' + tag

  return new InspectLeaf(
    '[' + tag + ' ' + (fn.name ? fn.name : '(anonymous)') + ']',
    styles.special,
    depth,
    opts
  )
}

function inspectClass(ctor, depth, opts) {
  return new InspectLeaf(
    '[class ' + (ctor.name ? ctor.name : '(anonymous)') + ']',
    styles.special,
    depth,
    opts
  )
}

function inspectExternal(external, depth, opts) {
  return new InspectLeaf(
    '[external 0x' + binding.getExternal(external).toString(16) + ']',
    styles.special,
    depth,
    opts
  )
}
{
  "name": "bare-inspect",
  "version": "3.1.4",
  "description": "Inspect objects as strings for debugging",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-inspect.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-inspect/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-inspect#readme",
  "engines": {
    "bare": ">=1.18.0"
  },
  "dependencies": {
    "bare-ansi-escapes": "^2.1.0",
    "bare-type": "^1.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
module.exports = require.addon()
const binding = require('./binding')

const t = binding.constants

class Type {
  constructor(type) {
    this._type = type
  }

  isUndefined() {
    return this._type === t.UNDEFINED
  }

  isNull() {
    return this._type === t.NULL
  }

  isBoolean() {
    return this._type === t.BOOLEAN
  }

  isNumber() {
    return (this._type & 0xff) === t.NUMBER
  }

  isInt32() {
    return (this._type & (0xff | t.INT32)) === (t.NUMBER | t.INT32)
  }

  isUint32() {
    return (this._type & (0xff | t.UINT32)) === (t.NUMBER | t.UINT32)
  }

  isString() {
    return this._type === t.STRING
  }

  isSymbol() {
    return this._type === t.SYMBOL
  }

  isObject() {
    return (this._type & 0xff) === t.OBJECT
  }

  isArray() {
    return this._type === (t.OBJECT | t.ARRAY)
  }

  isArguments() {
    return this._type === (t.OBJECT | t.ARGUMENTS)
  }

  isDate() {
    return this._type === (t.OBJECT | t.DATE)
  }

  isRegExp() {
    return this._type === (t.OBJECT | t.REGEXP)
  }

  isError() {
    return this._type === (t.OBJECT | t.ERROR)
  }

  isPromise() {
    return this._type === (t.OBJECT | t.PROMISE)
  }

  isProxy() {
    return this._type === (t.OBJECT | t.PROXY)
  }

  isGenerator() {
    return this._type === (t.OBJECT | t.GENERATOR)
  }

  isMap() {
    return this._type === (t.OBJECT | t.MAP)
  }

  isSet() {
    return this._type === (t.OBJECT | t.SET)
  }

  isWeakMap() {
    return this._type === (t.OBJECT | t.WEAK_MAP)
  }

  isWeakSet() {
    return this._type === (t.OBJECT | t.WEAK_SET)
  }

  isWeakRef() {
    return this._type === (t.OBJECT | t.WEAK_REF)
  }

  isArrayBuffer() {
    return this._type === (t.OBJECT | t.ARRAYBUFFER)
  }

  isSharedArrayBuffer() {
    return this._type === (t.OBJECT | t.SHAREDARRAYBUFFER)
  }

  isTypedArray() {
    return (this._type & 0xffff) === (t.OBJECT | t.TYPEDARRAY)
  }

  isInt8Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT8ARRAY)
  }

  isUint8Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT8ARRAY)
  }

  isUint8ClampedArray() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT8CLAMPEDARRAY)
  }

  isInt16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT16ARRAY)
  }

  isUint16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT16ARRAY)
  }

  isInt32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT32ARRAY)
  }

  isUint32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT32ARRAY)
  }

  isFloat16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT16ARRAY)
  }

  isFloat32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT32ARRAY)
  }

  isFloat64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT64ARRAY)
  }

  isBigInt64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.BIGINT64ARRAY)
  }

  isBigUint64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.BIGUINT64ARRAY)
  }

  isDataView() {
    return this._type === (t.OBJECT | t.DATAVIEW)
  }

  isModuleNamespace() {
    return this._type === (t.OBJECT | t.MODULE_NAMESPACE)
  }

  isFunction() {
    return (this._type & 0xff) === t.FUNCTION
  }

  isAsyncFunction() {
    return (
      (this._type & (0xff | t.ASYNC_FUNCTION)) ===
      (t.FUNCTION | t.ASYNC_FUNCTION)
    )
  }

  isGeneratorFunction() {
    return (
      (this._type & (0xff | t.GENERATOR_FUNCTION)) ===
      (t.FUNCTION | t.GENERATOR_FUNCTION)
    )
  }

  isExternal() {
    return this._type === t.EXTERNAL
  }

  isBigInt() {
    return this._type === t.BIGINT
  }
}

module.exports = exports = function type(value) {
  switch (typeof value) {
    case 'undefined':
      return new Type(t.UNDEFINED)
    case 'boolean':
      return new Type(t.BOOLEAN)
    case 'number':
      return new Type(
        Number.isSafeInteger(value) ? binding.type(value) : t.NUMBER
      )
    case 'string':
      return new Type(t.STRING)
    case 'symbol':
      return new Type(t.SYMBOL)
    case 'object':
      return new Type(value === null ? t.NULL : binding.type(value))
    case 'function':
      return new Type(binding.type(value))
    case 'bigint':
      return new Type(t.BIGINT)
  }
}

exports.createTag = function createTag(...components) {
  const tag = new Uint32Array(4)
  for (let i = 0; i < 4; i++) tag[i] = components[i] || 0
  return tag
}

exports.addTag = function addTag(object, tag) {
  binding.addTag(object, tag)
}

exports.checkTag = function checkTag(object, tag) {
  return binding.checkTag(object, tag)
}
{
  "name": "bare-type",
  "version": "1.1.0",
  "description": "Cross-realm type predicates for Bare",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-type.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-type/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-type#readme",
  "engines": {
    "bare": ">=1.2.0"
  },
  "devDependencies": {
    "brittle": "^3.4.0",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
const b4a = require('b4a')

function byteLength (size) {
  return Math.ceil(size / 8)
}

function get (buffer, bit) {
  const n = buffer.BYTES_PER_ELEMENT * 8

  const offset = bit & (n - 1)
  const i = (bit - offset) / n

  return (buffer[i] & (1 << offset)) !== 0
}

function set (buffer, bit, value = true) {
  const n = buffer.BYTES_PER_ELEMENT * 8

  const offset = bit & (n - 1)
  const i = (bit - offset) / n
  const mask = 1 << offset

  if (value) {
    if ((buffer[i] & mask) !== 0) return false
  } else {
    if ((buffer[i] & mask) === 0) return false
  }

  buffer[i] ^= mask
  return true
}

function setRange (buffer, start, end, value = true) {
  const n = buffer.BYTES_PER_ELEMENT * 8

  let remaining = end - start
  let offset = start & (n - 1)
  let i = (start - offset) / n

  let changed = false

  while (remaining > 0) {
    const mask = (2 ** Math.min(remaining, n - offset) - 1) << offset

    if (value) {
      if ((buffer[i] & mask) !== mask) {
        buffer[i] |= mask
        changed = true
      }
    } else {
      if ((buffer[i] & mask) !== 0) {
        buffer[i] &= ~mask
        changed = true
      }
    }

    remaining -= n - offset
    offset = 0
    i++
  }

  return changed
}

function fill (buffer, value, start = 0, end = buffer.byteLength * 8) {
  const n = buffer.BYTES_PER_ELEMENT * 8
  let i, j

  {
    const offset = start & (n - 1)
    i = (start - offset) / n

    if (offset !== 0) {
      const mask = (2 ** Math.min(n - offset, end - start) - 1) << offset

      if (value) buffer[i] |= mask
      else buffer[i] &= ~mask

      i++
    }
  }

  {
    const offset = end & (n - 1)
    j = (end - offset) / n

    if (offset !== 0 && j >= i) {
      const mask = (2 ** offset) - 1

      if (value) buffer[j] |= mask
      else buffer[j] &= ~mask
    }
  }

  return buffer.fill(value ? (2 ** n) - 1 : 0, i, j)
}

function toggle (buffer, bit) {
  const n = buffer.BYTES_PER_ELEMENT * 8

  const offset = bit & (n - 1)
  const i = (bit - offset) / n
  const mask = 1 << offset

  buffer[i] ^= mask
  return (buffer[i] & mask) !== 0
}

function remove (buffer, bit) {
  return set(buffer, bit, false)
}

function removeRange (buffer, start, end) {
  return setRange(buffer, start, end, false)
}

function indexOf (buffer, value, position = 0) {
  for (let i = position, n = buffer.byteLength * 8; i < n; i++) {
    if (get(buffer, i) === value) return i
  }

  return -1
}

function lastIndexOf (buffer, value, position = buffer.byteLength * 8 - 1) {
  for (let i = position; i >= 0; i--) {
    if (get(buffer, i) === value) return i
  }

  return -1
}

function of (...bits) {
  return from(bits)
}

function from (bits) {
  const buffer = b4a.alloc(byteLength(bits.length))
  for (let i = 0; i < bits.length; i++) set(buffer, i, bits[i])
  return buffer
}

function * iterator (buffer) {
  for (let i = 0, n = buffer.byteLength * 8; i < n; i++) yield get(buffer, i)
}

module.exports = {
  byteLength,
  get,
  set,
  setRange,
  fill,
  toggle,
  remove,
  removeRange,
  indexOf,
  lastIndexOf,
  of,
  from,
  iterator
}
{
  "name": "bits-to-bytes",
  "version": "1.3.0",
  "description": "Functions for doing bit manipulation of typed arrays",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "scripts": {
    "test": "standard && brittle test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bits-to-bytes.git"
  },
  "author": "Kasper Isager Dalsgarð <kasper@funktionel.co>",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/holepunchto/bits-to-bytes/issues"
  },
  "homepage": "https://github.com/holepunchto/bits-to-bytes#readme",
  "dependencies": {
    "b4a": "^1.5.0"
  },
  "devDependencies": {
    "brittle": "^2.3.1",
    "standard": "^17.0.0"
  }
}
const crypto = require('hypercore-crypto')
const b4a = require('b4a')
const safetyCatch = require('safety-catch')
const ReadyResource = require('ready-resource')
const Xache = require('xache')
const { MemberRequest, CandidateRequest, createInvite, decodeInvite, verifyReceipt, Invite } = require('blind-pairing-core')
const Protomux = require('protomux')
const c = require('compact-encoding')
const debounce = require('debounceify')
const isOptions = require('is-options')

const [NS_EPHEMERAL, NS_REPLY, NS_DISCOVERY] = crypto.namespace('blind-pairing/dht', 3)

const DEFAULT_POLL = 7 * 60 * 1000
const PEER_INTERVAL = 1000

class TimeoutPromise {
  constructor (ms) {
    this.ms = ms
    this.resolve = null
    this.timeout = null
    this.destroyed = false
    this.suspended = false

    this._resolveBound = this._resolve.bind(this)
    this._ontimerBound = this._ontimer.bind(this)
  }

  wait () {
    if (this.destroyed) return Promise.resolve()
    if (this.resolve) this._resolve()
    return new Promise(this._ontimerBound)
  }

  suspend () {
    this.suspended = true
    if (this.timeout !== null) clearTimeout(this.timeout)
    this.timeout = null
  }

  resume () {
    this.suspended = false
    if (this.resolve) this._resolve()
  }

  destroy () {
    this.destroyed = true
    if (this.resolve) this._resolve()
  }

  _ontimer (resolve) {
    this.resolve = resolve
    if (!this.suspended) this.timeout = setTimeout(this._resolveBound, this.ms)
  }

  _resolve () {
    if (this.timeout !== null) clearTimeout(this.timeout)

    const resolve = this.resolve
    this.timeout = null
    this.resolve = null

    resolve()
  }
}

class BlindPairing extends ReadyResource {
  constructor (swarm, { poll = DEFAULT_POLL, onincoming = noop } = {}) {
    super()

    this.swarm = swarm
    this.poll = poll
    this.active = new Map()
    this.suspended = false

    this._onincoming = onincoming
    this._onconnectionBound = this._onconnection.bind(this)
    this._refreshBound = this.refresh.bind(this)
    this._refreshing = null

    this.swarm.on('connection', this._onconnectionBound)
    this.swarm.dht.on('network-change', this._refreshBound)
  }

  static Invite = Invite

  static createInvite (key, opts) {
    return createInvite(key, opts)
  }

  static decodeInvite (invite) {
    return decodeInvite(invite)
  }

  static verifyReceipt (receipt, publicKey) {
    return verifyReceipt(receipt, publicKey)
  }

  static createRequest (invite, userData) {
    return new CandidateRequest(invite, userData)
  }

  async suspend () {
    if (this.suspended) return
    this.suspended = true

    const all = []

    for (const ref of this.active.values()) {
      if (ref.candidate) all.push(ref.candidate._suspend())
      if (ref.member) all.push(ref.member._suspend())
    }

    await Promise.allSettled(all)
  }

  resume () {
    if (!this.suspended) return
    this.suspended = false
    this.refresh().catch(safetyCatch) // no need to wait for the refreshes
  }

  async refresh () {
    if (this._refreshing) {
      await this._refreshing
      return
    }

    if (this.closing || this.suspended) return

    const r = this._refreshing = this._refresh()

    try {
      await r
    } finally {
      if (r === this._refreshing) this._refreshing = null
    }
  }

  async _refresh () {
    if (this.closing || this.suspended) return

    const all = []

    for (const ref of this.active.values()) {
      if (ref.candidate) all.push(ref.candidate.refresh())
      if (ref.member) all.push(ref.member.refresh())
    }

    await Promise.allSettled(all)
  }

  addMember (opts) {
    return new Member(this, opts)
  }

  addCandidate (request, opts) {
    if (isOptions(request)) return this.addCandidate(null, request)
    if (!request) request = new CandidateRequest(opts.invite, opts.userData)
    return new Candidate(this, request, opts)
  }

  async _close () {
    this.swarm.removeListener('connection', this._onconnectionBound)
    this.swarm.dht.removeListener('network-change', this._refreshBound)

    const all = []

    for (const conn of this.swarm.connections) {
      const mux = getMuxer(conn)
      mux.unpair({ protocol: 'blind-pairing' })
      for (const ref of this.active.values()) mux.unpair({ protocol: 'blind-pairing', id: ref.discoveryKey })
    }

    for (const ref of this.active.values()) {
      if (ref.member) all.push(ref.member.close())
      if (ref.candidate) all.push(ref.candidate.close())
      if (ref.discovery) all.push(ref.discovery.destroy())
    }

    await Promise.allSettled(all)
  }

  _randomPoll () {
    return randomInterval(this.poll)
  }

  _add (discoveryKey) {
    const id = b4a.toString(discoveryKey, 'hex')
    const t = this.active.get(id)
    if (t) return t

    const fresh = {
      id,
      discoveryKey,
      member: null,
      candidate: null,
      channels: new Set(),
      alwaysServer: false,
      alwaysClient: false,
      discovery: null
    }

    this.active.set(id, fresh)
    return fresh
  }

  _swarm (ref) {
    const server = ref.alwaysServer || !!ref.member
    const client = ref.alwaysClient || !!ref.candidate

    if (ref.discovery && ref.discovery.isServer === server && ref.discovery.isClient === client) {
      return
    }

    if (ref.discovery) ref.discovery.destroy().catch(safetyCatch)

    // just a sanity check, not needed but doesnt hurt
    if (!server && !client) return

    ref.discovery = this.swarm.join(ref.discoveryKey, { server, client })
    this._attachToSwarm(ref)
  }

  _attachToSwarm (ref) {
    for (const conn of this.swarm.connections) {
      const mux = getMuxer(conn)
      this._attachToMuxer(mux, ref.discoveryKey, ref)
    }
  }

  _gc (ref) {
    if (ref.member || ref.candidate) {
      if (ref.discovery) this._swarm(ref) // in case it needs updating...
      return false
    }
    this.active.delete(ref.id)
    for (const ch of ref.channels) ch.close()
    for (const conn of this.swarm.connections) {
      const mux = getMuxer(conn)
      mux.unpair({ protocol: 'blind-pairing', id: ref.discoveryKey })
    }
    if (ref.discovery) ref.discovery.destroy().catch(safetyCatch)
    return true
  }

  _onconnection (conn) {
    const mux = getMuxer(conn)

    mux.pair({ protocol: 'blind-pairing' }, this._onincoming)

    for (const ref of this.active.values()) {
      this._attachToMuxer(mux, ref.discoveryKey, ref)
    }
  }

  _attachToMuxer (mux, discoveryKey, ref) {
    if (!ref) ref = this._add(discoveryKey)

    const ch = mux.createChannel({
      protocol: 'blind-pairing',
      id: discoveryKey,
      messages: [
        { encoding: c.buffer, onmessage: (req) => this._onpairingrequest(ch, ref, req) },
        { encoding: c.buffer, onmessage: (res) => this._onpairingresponse(ch, ref, res) }
      ],
      onclose: () => {
        ref.channels.delete(ch)
        if (ref.candidate) ref.candidate.visited.delete(ch)
      }
    })

    if (ch === null) return

    ch.open()
    mux.pair({ protocol: 'blind-pairing', id: discoveryKey }, () => this._attachToMuxer(mux, discoveryKey, null))
    ref.channels.add(ch)

    if (ref.candidate) ref.candidate.broadcast()
  }

  async _onpairingrequest (ch, ref, req) {
    if (!ref.member) return

    const request = await ref.member._addRequest(req)
    if (!request) return

    ch.messages[1].send(request.response)
  }

  async _onpairingresponse (ch, ref, res) {
    if (!ref.candidate) return

    await ref.candidate._addResponse(res, false)
  }
}

class Member extends ReadyResource {
  constructor (blind, { announce = true, discoveryKey, onadd = noop } = {}) {
    super()

    if (!discoveryKey) {
      throw new Error('Must provide discoveryKey')
    }

    const ref = blind._add(discoveryKey)

    if (ref.member) {
      throw new Error('Active member already exist')
    }

    ref.member = this

    this._pendingRequests = new Map()

    this.blind = blind
    this.dht = blind.swarm.dht
    this.discoveryKey = discoveryKey
    this.pairingDiscoveryKey = deriveDiscoveryKey(discoveryKey)
    this.timeout = new TimeoutPromise(blind._randomPoll())
    this.pairing = null
    this.skip = new Xache({ maxSize: 512 })
    this.ref = ref
    this.onadd = onadd

    this._activeQuery = null
    this._activePoll = null
    this._closestNodes = null
    this._autoAnnounce = announce

    this.ready()
  }

  announce () {
    if (this.pairing) return this.pairing

    this.blind._swarm(this.ref)
    this.pairing = this._run()
    this.pairing.catch(safetyCatch)

    return this.pairing
  }

  async flushed () {
    if (!this.ref.discovery) return
    return this.ref.discovery.flushed()
  }

  _open () {
    if (this._autoAnnounce) this.announce()
    else this.blind._attachToSwarm(this.ref)
  }

  _suspend () {
    this.timeout.suspend()
    return this._abort()
  }

  async _abort () {
    if (this._activeQuery) this._activeQuery.destroy()
    while (this._activePoll !== null) await this._activePoll
  }

  async refresh () {
    await this._abort()
    this.timeout.resume()
  }

  async _close () {
    this.ref.member = null
    this.blind._gc(this.ref)
    this.timeout.destroy()
    await this._abort()

    try {
      await this.pairing
    } catch {
      // ignore errors since we teardown
    }
  }

  async _run () {
    while (!this.closing) {
      this._activePoll = this._poll()
      await this._activePoll
      this._activePoll = null
      await this.timeout.wait()
    }
  }

  async _poll () {
    const visited = new Set()
    let alwaysClient = false

    if (this._activeQuery) this._activeQuery.destroy()

    const query = this._activeQuery = this.dht.lookup(this.pairingDiscoveryKey, { closestNodes: this._closestNodes })

    try {
      for await (const data of this._activeQuery) {
        if (this.closing || this.blind.suspended) return

        for (const peer of data.peers) {
          const id = b4a.toString(peer.publicKey, 'hex')

          if (visited.has(id) || this.skip.get(id)) continue
          visited.add(id)

          try {
            if (await this._add(peer.publicKey, id)) alwaysClient = true
          } catch (err) {
            safetyCatch(err)
          }

          if (this.closing || this.blind.suspended) return

          if (alwaysClient && !this.ref.alwaysClient) {
            this.ref.alwaysClient = true
            this.blind._swarm(this.ref)
          }
        }
      }
    } catch {
      // do nothing
    } finally {
      const nodes = this._activeQuery.closestNodes
      if (this._activeQuery === query) this._activeQuery = null
      if (nodes && nodes.length > 0) this._closestNodes = nodes
    }

    if (alwaysClient) this._revertClientAfterFlush() // safe to do in bg
  }

  async _revertClientAfterFlush () {
    try {
      await this.blind.swarm.flush()
    } catch {
      return
    }
    if (this.closing || this.blind.suspended) return

    this.ref.alwaysClient = false
    this.blind._swarm(this.ref)
  }

  async _addRequest (value) {
    let request = null
    try {
      request = MemberRequest.from(value)
    } catch {
      return null
    }

    request.discoveryKey = this.discoveryKey

    const session = b4a.toString(request.requestData.session, 'hex')

    if (!this._pendingRequests.has(session)) {
      this._pendingRequests.set(session, {
        request,
        promise: this.onadd(request)
      })
    }

    // laod existing request if it exists
    const pending = this._pendingRequests.get(session)

    try {
      await pending.promise
    } catch (e) {
      safetyCatch(e)
      return null
    }

    this._pendingRequests.delete(session)

    if (!pending.request.response) return null

    return pending.request
  }

  async _add (publicKey, id) {
    const node = await this.dht.mutableGet(publicKey, { latest: false })
    if (!node) return false

    this.skip.set(id, true)

    const request = await this._addRequest(node.value)
    if (!request) return false

    const replyKeyPair = deriveReplyKeyPair(request.token)
    await this.dht.mutablePut(replyKeyPair, request.response)

    return true
  }
}

class Candidate extends ReadyResource {
  constructor (blind, request, { discoveryKey = request.discoveryKey, onadd = noop } = {}) {
    super()

    const ref = blind._add(discoveryKey)
    if (ref.candidate) {
      throw new Error('Active candidate already exist')
    }

    ref.candidate = this

    this.blind = blind
    this.discoveryKey = discoveryKey
    this.pairingDiscoveryKey = deriveDiscoveryKey(discoveryKey)
    this.dht = blind.swarm.dht
    this.request = request
    this.token = request.token
    this.timeout = new TimeoutPromise(blind._randomPoll())
    this.announced = false
    this.gcing = null
    this.ref = ref
    this.paired = null
    this.pairing = null
    this.onadd = onadd

    this.signal = null
    this.visited = new Set()
    this.broadcast = debounce(this._broadcast.bind(this))

    this._activePoll = null

    this.ready()
  }

  _open () {
    this.blind._swarm(this.ref)
    this.pairing = this._run()
    this.broadcast()
  }

  _suspend () {
    this.timeout.suspend()
    // no good way to suspend the mut gets atm unfortunately so we just rely on the polls timing out
  }

  async refresh () {
    while (this._activePoll !== null) await this._activePoll
    this.announced = false
    this.timeout.resume()
  }

  async _close () {
    this.ref.candidate = null
    this.blind._gc(this.ref)
    this.timeout.destroy()
    this.visited.clear()
    await this.pairing
    // gc never throws
    if (this.gcing) await this.gcing
  }

  async _addResponse (value, gc) {
    if (this.paired) return

    const paired = this.request.handleResponse(value)
    if (!paired) return

    this.paired = paired
    if (this.signal) this.signal.destroy()

    if ((gc || this.announced) && !this.gcing) this.gcing = this._gc() // gc in the background
    await this.onadd(paired)
    this.timeout.destroy()
  }

  async _run () {
    while (!this._done()) {
      this._activePoll = this._poll()
      await this._activePoll
      this._activePoll = null
      if (this._done()) break
      await this.timeout.wait()
    }

    this.close().catch(safetyCatch)
    return this.paired
  }

  _done () {
    return !!(this.closing || this.paired)
  }

  async _announce () {
    const eph = deriveEphemeralKeyPair(this.token)

    await this.dht.mutablePut(eph, this.request.encode())
    if (this._done()) return

    await this.dht.announce(this.pairingDiscoveryKey, eph).finished()
    if (this._done()) return

    if (!this.paired) {
      this.ref.alwaysServer = true
      this.blind._swarm(this.ref)
    }

    this.emit('announce')
  }

  async _gc () {
    const eph = deriveEphemeralKeyPair(this.token)

    try {
      await this.dht.unannounce(this.pairingDiscoveryKey, eph)
    } catch (err) {
      safetyCatch(err) // just gc, whatevs
    }
  }

  _sendRequest (ch) {
    ch.messages[0].send(this.request.encode())
    this.visited.add(ch)
  }

  async _broadcast () {
    for (const channel of this.closestPeers()) {
      this.signal = new TimeoutPromise(randomInterval(PEER_INTERVAL))
      if (channel) this._sendRequest(channel)

      await this.signal.wait() // resolves on destroy

      if (this.paired || this.suspended) break
    }
  }

  * closestPeers () {
    while (!this.paired) {
      const closest = Infinity
      let channel = null

      for (const ch of this.ref.channels) {
        if (this.visited.has(ch)) continue

        const { rtt } = ch._mux.stream.rawStream
        if (rtt < closest) channel = ch
      }

      if (!channel) return

      yield channel
    }
  }

  async _poll () {
    try {
      const value = await this._getReply()
      if (this._done() || this.blind.suspended) return

      if (value) {
        await this._addResponse(value, true)
        if (this._done() || this.blind.suspended) return
      }

      if (!this.announced) {
        this.announced = true
        await this._announce()
      }
    } catch {
      // can run in bg, should never crash it
    }
  }

  async _getReply () {
    const { publicKey } = deriveReplyKeyPair(this.token)
    const node = await this.dht.mutableGet(publicKey, { latest: false })
    if (!node) return null
    return node.value
  }
}

module.exports = BlindPairing

function noop () {}

function deriveReplyKeyPair (token) {
  return crypto.keyPair(crypto.hash([NS_REPLY, token]))
}

function deriveEphemeralKeyPair (token) {
  return crypto.keyPair(crypto.hash([NS_EPHEMERAL, token]))
}

function deriveDiscoveryKey (discoveryKey) {
  return crypto.hash([NS_DISCOVERY, discoveryKey])
}

function getMuxer (stream) {
  if (stream.userData) return stream.userData
  const protocol = Protomux.from(stream)
  stream.setKeepAlive(5000)
  stream.userData = protocol
  return protocol
}

function randomInterval (n) {
  return n + (n * 0.5 * Math.random()) | 0
}
{
  "name": "blind-pairing",
  "version": "2.3.1",
  "description": "Blind pairing using Hyperswarm",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "blind-pairing-core": "^2.0.0",
    "b4a": "^1.6.4",
    "debounceify": "^1.1.0",
    "hypercore-crypto": "^3.4.0",
    "is-options": "^1.0.2",
    "ready-resource": "^1.0.0",
    "safety-catch": "^1.0.2",
    "xache": "^1.2.0"
  },
  "devDependencies": {
    "@hyperswarm/testnet": "^3.1.4",
    "brittle": "^3.3.2",
    "hyperdht": "^6.8.9",
    "hyperswarm": "^4.7.3",
    "minimist": "^1.2.8",
    "standard": "^17.1.0",
    "z32": "^1.0.1"
  },
  "scripts": {
    "test": "standard && brittle test/*.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/blind-pairing.git"
  },
  "author": "Holepunch Inc",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/blind-pairing/issues"
  },
  "homepage": "https://github.com/holepunchto/blind-pairing"
}
const EventEmitter = require('events')
const Protomux = require('protomux')
const { Readable } = require('streamx')
const sodium = require('sodium-universal')
const b4a = require('b4a')
const c = require('compact-encoding')
const bitfield = require('compact-encoding-bitfield')
const bits = require('bits-to-bytes')
const errors = require('./lib/errors')

exports.Server = class BlindRelayServer extends EventEmitter {
  constructor(opts = {}) {
    super()

    const { createStream } = opts

    this._createStream = createStream
    this._pairing = new Map()
    this._activePairingRefs = new Map()
    this._sessions = new Set()
    this.stats = createStats()
  }

  get sessions() {
    return this._sessions[Symbol.iterator]()
  }

  accept(stream, opts) {
    const session = new BlindRelaySession(this, stream, opts)

    this._sessions.add(session)
    this.stats.sessions.accepted++

    return session
  }

  async close() {
    const ending = []

    for (const session of this._sessions) {
      ending.push(session.end())
    }

    await Promise.all(ending)

    this._pairing.clear()
  }

  _trackActiveLink(keyString) {
    const refs = this._activePairingRefs.get(keyString) || 0

    if (refs === 0) this.stats.pairings.active++

    this._activePairingRefs.set(keyString, refs + 1)
  }

  _untrackActiveLink(keyString) {
    const refs = this._activePairingRefs.get(keyString)

    if (refs === undefined) return

    if (refs === 1) {
      this._activePairingRefs.delete(keyString)
      this.stats.pairings.active--
    } else {
      this._activePairingRefs.set(keyString, refs - 1)
    }
  }
}

class BlindRelaySession extends EventEmitter {
  constructor(server, stream, opts = {}) {
    super()

    const { id, handshake, handshakeEncoding } = opts

    this._server = server
    this._mux = Protomux.from(stream)

    this._channel = this._mux.createChannel({
      protocol: 'blind-relay',
      id,
      handshake: handshake ? handshakeEncoding || c.raw : null,
      onopen: this._onopen.bind(this),
      onclose: this._onclose.bind(this),
      ondestroy: this._ondestroy.bind(this)
    })

    this._pair = this._channel.addMessage({
      encoding: m.pair,
      onmessage: this._onpair.bind(this)
    })

    this._unpair = this._channel.addMessage({
      encoding: m.unpair,
      onmessage: this._onunpair.bind(this)
    })

    this._ending = null
    this._destroyed = false
    this._error = null
    this._pairing = new Set()
    this._links = new Map()

    this._onerror = (err) => {
      this._server.stats.streams.errors++
      this.emit('error', err)
    }

    this._channel.open(handshake)
  }

  get closed() {
    return this._channel.closed
  }

  get mux() {
    return this._mux
  }

  get stream() {
    return this._mux.stream
  }

  _onopen() {
    this._server.stats.sessions.opened++
    this.emit('open')
  }

  _onclose() {
    this._ending = Promise.resolve()

    const err = this._error || errors.CHANNEL_CLOSED()
    this._server.stats.pairings.cancelled += this._pairing.size

    for (const token of this._pairing) {
      if (this._server._pairing.delete(token.toString('hex'))) {
        this._server.stats.pairings.pending--
      }
    }

    for (const link of this._links.values()) {
      link.destroy(err)
    }

    this._pairing.clear()
    this._links.clear()

    this._server._sessions.delete(this)
    this._server.stats.sessions.closed++

    this.emit('close')
  }

  _ondestroy() {
    this._destroyed = true
    this.emit('destroy')
  }

  _onpair({ isInitiator, token, id: remoteId }) {
    const keyString = token.toString('hex')

    let pair = this._server._pairing.get(keyString)

    if (pair === undefined) {
      pair = new BlindRelayPair(token)
      this._server._pairing.set(keyString, pair)
      this._server.stats.pairings.pending++
    } else if (pair.links[+isInitiator]) return

    this._pairing.add(keyString)
    this._server.stats.pairings.requested++

    pair.links[+isInitiator] = new BlindRelayLink(this, isInitiator, remoteId)

    if (!pair.paired) return

    this._server._pairing.delete(keyString)
    this._server.stats.pairings.pending--
    this._server.stats.pairings.matched++

    // 1st pass: Create the raw streams needed for each end of the link.
    for (const link of pair.links) {
      link.createStream()
    }

    // 2nd pass: Connect the raw streams and set up handlers.
    for (const link of pair.links) {
      link.remote = pair.remote(link.isInitiator)
      link.activate(keyString)
    }

    // 3rd pass: Let either end of the link know the streams were set up.
    for (const { isInitiator, session, remoteId, stream } of pair.links) {
      session._pair.send({
        isInitiator,
        token,
        id: stream.id,
        seq: 0
      })

      session._endMaybe()

      session.emit('pair', isInitiator, token, stream, remoteId)
    }
  }

  _onunpair({ token }) {
    const keyString = token.toString('hex')

    const pair = this._server._pairing.get(keyString)

    if (pair) {
      for (const link of pair.links) {
        if (link) link.session._pairing.delete(keyString)
      }

      this._server._pairing.delete(keyString)
      this._server.stats.pairings.pending--
      this._server.stats.pairings.cancelled++
      return
    }

    const link = this._links.get(keyString)

    if (link) {
      link.destroyPair(errors.PAIRING_CANCELLED())
      this._server.stats.pairings.cancelled++
    }
  }

  cork() {
    this._channel.cork()
  }

  uncork() {
    this._channel.uncork()
  }

  async end() {
    if (this._ending) return this._ending

    this._ending = EventEmitter.once(this, 'close')
    this._endMaybe()

    return this._ending
  }

  _endMaybe() {
    if (this._ending && this._pairing.size === 0) {
      this._channel.close()
    }
  }

  destroy(err) {
    if (this._destroyed) return
    this._destroyed = true

    this._error = err || errors.CHANNEL_DESTROYED()
    this._channel.close()
  }
}

class BlindRelayPair {
  constructor(token) {
    this.token = token
    this.links = [null, null]
  }

  get paired() {
    return this.links[0] !== null && this.links[1] !== null
  }

  remote(isInitiator) {
    return this.links[isInitiator ? 0 : 1]
  }
}

class BlindRelayLink {
  constructor(session, isInitiator, remoteId) {
    this.session = session
    this.isInitiator = isInitiator
    this.remoteId = remoteId
    this.stream = null
    this.remote = null
    this.keyString = null
    this._onclose = null
  }

  createStream() {
    if (this.stream) return

    this.stream = this.session._server._createStream({
      firewall: this._onfirewall.bind(this)
    })
  }

  activate(keyString) {
    const stream = this.stream

    this.keyString = keyString
    this._onclose = () => {
      if (this.stream !== stream) return

      this.stream = null
      unlink(this)
      this.session._links.delete(keyString)
      this.session._server._untrackActiveLink(keyString)
      this.session._server.stats.streams.closed++
    }

    stream.on('error', this.session._onerror).on('close', this._onclose).relayTo(this.remote.stream)

    this.session._pairing.delete(keyString)
    this.session._links.set(keyString, this)
    this.session._server._trackActiveLink(keyString)
    this.session._server.stats.streams.opened++
  }

  destroy(err) {
    const stream = this.stream

    if (!stream) return

    this.stream = null

    stream.off('close', this._onclose)
    this._onclose = null

    stream.off('error', this.session._onerror)
    unlink(this)
    this.session._links.delete(this.keyString)
    this.session._server._untrackActiveLink(this.keyString)
    this.session._server.stats.streams.closed++
    stream.on('error', noop).destroy(err)
  }

  destroyPair(err) {
    const remote = this.remote

    this.destroy(err)
    if (remote) remote.destroy(err)
  }

  _onfirewall(socket, port, host) {
    this.stream.connect(socket, this.remoteId, port, host)

    return false
  }
}

exports.Client = class BlindRelayClient extends EventEmitter {
  static _clients = new WeakMap()

  static from(stream, opts) {
    let client = this._clients.get(stream)
    if (client) return client
    client = new this(stream, opts)
    this._clients.set(stream, client)
    return client
  }

  constructor(stream, opts = {}) {
    super()

    const { id, handshake, handshakeEncoding } = opts

    this._mux = Protomux.from(stream)

    this._channel = this._mux.createChannel({
      protocol: 'blind-relay',
      id,
      handshake: handshake ? handshakeEncoding || c.raw : null,
      onopen: this._onopen.bind(this),
      onclose: this._onclose.bind(this),
      ondestroy: this._ondestroy.bind(this)
    })

    this._pair = this._channel.addMessage({
      encoding: m.pair,
      onmessage: this._onpair.bind(this)
    })

    this._unpair = this._channel.addMessage({
      encoding: m.unpair
    })

    this._ending = false
    this._destroyed = false
    this._error = null
    this._requests = new Map()

    this._channel.open(handshake)
  }

  get closed() {
    return this._channel.closed
  }

  get mux() {
    return this._mux
  }

  get stream() {
    return this._mux.stream
  }

  get requests() {
    return this._requests.values()
  }

  _onopen() {
    this.emit('open')
  }

  _onclose() {
    this._ending = Promise.resolve()

    const err = this._error || errors.CHANNEL_CLOSED()

    for (const request of this._requests.values()) {
      request.destroy(err)
    }

    this._requests.clear()

    this.constructor._clients.delete(this.stream)

    this.emit('close')
  }

  _ondestroy() {
    this._destroyed = true
    this.emit('destroy')
  }

  _onpair({ isInitiator, token, id: remoteId }) {
    const request = this._requests.get(token.toString('hex'))

    if (request === undefined || request.isInitiator !== isInitiator) return

    request.push(remoteId)
    request.push(null)

    this.emit('pair', request.isInitiator, request.token, request.stream, remoteId)
  }

  pair(isInitiator, token, stream) {
    if (this._destroyed) throw errors.CHANNEL_DESTROYED()

    const keyString = token.toString('hex')

    if (this._requests.has(keyString)) throw errors.ALREADY_PAIRING()

    const request = new BlindRelayRequest(this, isInitiator, token, stream)

    this._requests.set(keyString, request)

    return request
  }

  unpair(token) {
    if (this._destroyed) throw errors.CHANNEL_DESTROYED()

    const request = this._requests.get(token.toString('hex'))

    if (request) request.destroy(errors.PAIRING_CANCELLED())

    this._unpair.send({ token })
  }

  cork() {
    this._channel.cork()
  }

  uncork() {
    this._channel.uncork()
  }

  async end() {
    if (this._ending) return this._ending

    this._ending = EventEmitter.once(this, 'close')
    this._endMaybe()

    return this._ending
  }

  _endMaybe() {
    if (this._ending && this._requests.size === 0) {
      this._channel.close()
    }
  }

  destroy(err) {
    if (this._destroyed) return
    this._destroyed = true

    this._error = err || errors.CHANNEL_DESTROYED()
    this._channel.close()
  }
}

class BlindRelayRequest extends Readable {
  constructor(client, isInitiator, token, stream) {
    super()

    this.client = client
    this.isInitiator = isInitiator
    this.token = token
    this.stream = stream
  }

  _open(cb) {
    if (this.client._destroyed) return cb(errors.CHANNEL_DESTROYED())

    this.client._pair.send({
      isInitiator: this.isInitiator,
      token: this.token,
      id: this.stream.id,
      seq: 0
    })

    cb(null)
  }

  _destroy(cb) {
    this.client._requests.delete(this.token.toString('hex'))

    cb(null)

    this.client._endMaybe()
  }
}

exports.token = function token(buf = b4a.allocUnsafe(32)) {
  sodium.randombytes_buf(buf)
  return buf
}

function noop() {}

function unlink(link) {
  const remote = link.remote

  link.remote = null

  if (remote && remote.remote === link) {
    remote.remote = null
  }
}

function createStats() {
  const stats = {
    sessions: {
      accepted: 0,
      opened: 0,
      closed: 0,
      get active() {
        return this.accepted - this.closed
      }
    },
    pairings: {
      requested: 0,
      matched: 0,
      cancelled: 0,
      pending: 0,
      active: 0
    },
    streams: {
      opened: 0,
      closed: 0,
      errors: 0,
      get active() {
        return this.opened - this.closed
      }
    }
  }

  return stats
}

const m = (exports.messages = {})

const flags = bitfield(7)

m.pair = {
  preencode(state, m) {
    flags.preencode(state)
    c.fixed32.preencode(state, m.token)
    c.uint.preencode(state, m.id)
    c.uint.preencode(state, m.seq)
  },
  encode(state, m) {
    flags.encode(state, bits.of(m.isInitiator))
    c.fixed32.encode(state, m.token)
    c.uint.encode(state, m.id)
    c.uint.encode(state, m.seq)
  },
  decode(state) {
    const [isInitiator] = bits.iterator(flags.decode(state))

    return {
      isInitiator,
      token: c.fixed32.decode(state),
      id: c.uint.decode(state),
      seq: c.uint.decode(state)
    }
  }
}

m.unpair = {
  preencode(state, m) {
    flags.preencode(state)
    c.fixed32.preencode(state, m.token)
  },
  encode(state, m) {
    flags.encode(state, bits.of())
    c.fixed32.encode(state, m.token)
  },
  decode(state) {
    flags.decode(state)

    return {
      token: c.fixed32.decode(state)
    }
  }
}
module.exports = class BlindRelayError extends Error {
  constructor(msg, code, fn = BlindRelayError) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'BlindRelayError'
  }

  static DUPLICATE_CHANNEL(msg = 'Duplicate channel') {
    return new BlindRelayError(msg, 'DUPLICATE_CHANNEL', BlindRelayError.DUPLICATE_CHANNEL)
  }

  static CHANNEL_CLOSED(msg = 'Channel closed') {
    return new BlindRelayError(msg, 'CHANNEL_CLOSED', BlindRelayError.CHANNEL_CLOSED)
  }

  static CHANNEL_DESTROYED(msg = 'Channel destroyed') {
    return new BlindRelayError(msg, 'CHANNEL_DESTROYED', BlindRelayError.CHANNEL_DESTROYED)
  }

  static ALREADY_PAIRING(msg = 'Already pairing') {
    return new BlindRelayError(msg, 'ALREADY_PAIRING', BlindRelayError.ALREADY_PAIRING)
  }

  static PAIRING_CANCELLED(msg = 'Pairing cancelled') {
    return new BlindRelayError(msg, 'PAIRING_CANCELLED', BlindRelayError.PAIRING_CANCELLED)
  }
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "blind-relay",
  "version": "1.6.1",
  "description": "Blind relay for UDX over Protomux channels",
  "main": "index.js",
  "files": [
    "index.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:bare",
    "test:bare": "brittle-bare --coverage test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/blind-relay.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/blind-relay/issues"
  },
  "homepage": "https://github.com/holepunchto/blind-relay#readme",
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "dependencies": {
    "b4a": "^1.6.4",
    "bare-events": "^2.2.0",
    "bits-to-bytes": "^1.3.0",
    "compact-encoding": "^3.0.0",
    "compact-encoding-bitfield": "^1.0.0",
    "protomux": "^3.5.1",
    "sodium-universal": "^5.0.0",
    "streamx": "^2.15.1"
  },
  "devDependencies": {
    "brittle": "^3.2.1",
    "hyperdht": "^6.6.1",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "udx-native": "^1.6.1"
  }
}
// https://ipinfo.io/bogon

const b4a = require('b4a')
const c = require('compact-encoding')

module.exports = exports = function isBogon (ip) {
  return isBogonIP(ensureBuffer(ip))
}

exports.isBogon = exports

exports.isPrivate = function isPrivate (ip) {
  return isPrivateIP(ensureBuffer(ip))
}

exports.isReserved = function isReserved (ip) {
  return isReservedIP(ensureBuffer(ip))
}

function isBogonIP (ip) {
  return isPrivateIP(ip) || isReservedIP(ip)
}

function isPrivateIP (ip) {
  return ip.byteLength === 4 ? isPrivateIPv4(ip) : false // IPv6 has no private IPs
}

function isPrivateIPv4 (ip) {
  return (
    // 10.0.0.0/8  Private-use networks
    (ip[0] === 10) ||
    // 100.64.0.0/10 Carrier-grade NAT
    (ip[0] === 100 && ip[1] >= 64 && ip[1] <= 127) ||
    // 127.0.0.0/8 Loopback + Name collision occurrence (127.0.53.53)
    (ip[0] === 127) ||
    // 169.254.0.0/16  Link local
    (ip[0] === 169 && ip[1] === 254) ||
    // 172.16.0.0/12 Private-use networks
    (ip[0] === 172 && ip[1] >= 16 && ip[1] <= 31) ||
    // 192.168.0.0/16  Private-use networks
    (ip[0] === 192 && ip[1] === 168)
  )
}

function isReservedIP (ip) {
  return ip.byteLength === 4 ? isReservedIPv4(ip) : isReservedIPv6(ip)
}

function isReservedIPv4 (ip) {
  return (
    // 0.0.0.0/8 "This" network
    (ip[0] === 0) ||
    // 192.0.0.0/24  IETF protocol assignments
    (ip[0] === 192 && ip[1] === 0 && ip[2] === 0) ||
    // 192.0.2.0/24  TEST-NET-1
    (ip[0] === 192 && ip[1] === 0 && ip[2] === 2) ||
    // 198.18.0.0/15 Network interconnect device benchmark testing
    (ip[0] === 198 && ip[1] >= 18 && ip[1] <= 19) ||
    // 198.51.100.0/24 TEST-NET-2
    (ip[0] === 198 && ip[1] === 51 && ip[2] === 100) ||
    // 203.0.113.0/24  TEST-NET-3
    (ip[0] === 203 && ip[1] === 0 && ip[2] === 113) ||
    // 224.0.0.0/4 Multicast
    (ip[0] >= 224 && ip[0] <= 239) ||
    // 240.0.0.0/4 Reserved for future use
    (ip[0] >= 240) ||
    // 255.255.255.255/32
    (ip[0] === 255 && ip[1] === 255 && ip[2] === 255 && ip[3] === 255)
  )
}

function isReservedIPv6 (ip) {
  return (
    // ::/128 Node-scope unicast unspecified address
    // ::1/128 Node-scope unicast loopback address
    (
      ip[0] === 0 && ip[1] === 0 && ip[2] === 0 && ip[3] === 0 && ip[4] === 0 &&
      ip[5] === 0 && ip[6] === 0 && ip[7] === 0 && ip[8] === 0 && ip[9] === 0 &&
      ip[10] === 0 && ip[11] === 0 && ip[12] === 0 && ip[13] === 0 && ip[14] === 0 &&
      ip[15] <= 1
    ) ||
    // ::ffff:0:0/96 IPv4-mapped addresses
    // ::/96 IPv4-compatible addresses
    (
      ip[0] === 0 && ip[1] === 0 && ip[2] === 0 && ip[3] === 0 && ip[4] === 0 &&
      ip[5] === 0 && ip[6] === 0 && ip[7] === 0 && ip[8] === 0 && ip[9] === 0 &&
      (ip[10] === 0 || ip[10] === 0xff) &&
      (ip[11] === 0 || ip[11] === 0xff)
    ) ||
    // 100::/64 Remotely triggered black hole addresses
    (ip[0] === 0x01 && ip[1] === 0 && ip[2] === 0 && ip[3] === 0 && ip[4] === 0 && ip[5] === 0 && ip[6] === 0 && ip[7] === 0) ||
    // 2001:10::/28 Overlay routable cryptographic hash identifiers (ORCHID)
    (ip[0] === 0x20 && ip[1] === 0x01 && ip[2] === 0 && ip[3] >= 0x10 && ip[3] <= 0x1f) ||
    // 2001:20::/28 Overlay routable cryptographic hash identifiers version 2 (ORCHIDv2)
    (ip[0] === 0x20 && ip[1] === 0x01 && ip[2] === 0 && ip[3] >= 0x20 && ip[3] <= 0x2f) ||
    // 2001:db8::/32 Documentation prefix
    (ip[0] === 0x20 && ip[1] === 0x01 && ip[2] === 0x0d && ip[3] === 0xb8) ||
    // fc00::/7 Unique local addresses (ULA)
    (ip[0] >= 0xfc && ip[0] <= 0xfd) ||
    // fe80::/10 Link-local unicast
    (ip[0] === 0xfe && ip[1] >= 0x80 && ip[1] <= 0xbf) ||
    // ff00::/8 Multicast
    (ip[0] === 0xff)
  )
}

const state = c.state(0, 0, b4a.allocUnsafe(1 /* family */ + 16))

function ensureBuffer (ip) {
  if (b4a.isBuffer(ip)) return ip

  c.ip.preencode(state, ip)
  c.ip.encode(state, ip)

  const buffer = state.buffer.subarray(1 /* family */, state.end)

  state.start = 0
  state.end = 0

  return buffer
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "bogon",
  "version": "1.3.0",
  "description": "Check if an IP is a bogon",
  "main": "index.js",
  "scripts": {
    "test": "standard && brittle test.mjs"
  },
  "dependencies": {
    "compact-encoding": "^3.0.0",
    "compact-encoding-net": "^1.2.0"
  },
  "devDependencies": {
    "brittle": "^3.0.4",
    "nanobench": "^2.1.1",
    "standard": "^17.0.0"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/bogon.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/bogon/issues"
  },
  "homepage": "https://github.com/mafintosh/bogon"
}
const c = require('compact-encoding')

module.exports = function bitfield(length) {
  if (length > 64) {
    throw new RangeError('Bitfield cannot be larger than 64 bits')
  }

  let byteLength
  if (length < 8) byteLength = 1
  else if (length <= 16) byteLength = 2
  else if (length <= 32) byteLength = 4
  else byteLength = 8

  return {
    preencode(state) {
      state.end++ // Length byte, used for data when byteLength === 1

      if (byteLength === 1);
      else if (byteLength === 2) c.uint16.preencode(state)
      else if (byteLength === 4) c.uint32.preencode(state)
      else c.uint64.preencode(state)
    },

    encode(state, b) {
      if (byteLength === 1);
      else if (byteLength === 2) c.uint8.encode(state, 0xfd)
      else if (byteLength === 4) c.uint8.encode(state, 0xfe)
      else c.uint8.encode(state, 0xff)

      if (typeof b === 'number') {
        if (byteLength === 1) c.uint8.encode(state, b)
        else if (byteLength === 2) c.uint16.encode(state, b)
        else if (byteLength === 4) c.uint32.encode(state, b)
        else c.uint64.encode(state, b)
      } else {
        state.buffer.set(b, state.start)

        if (b.byteLength < byteLength) {
          // Zero-fill the rest of the byte length.
          state.buffer.fill(
            0,
            state.start + b.byteLength,
            state.start + byteLength
          )
        }

        state.start += byteLength
      }
    },

    decode(state) {
      const byte = state.buffer[state.start]

      let byteLength
      if (byte <= 0xfc) byteLength = 1
      else if (byte === 0xfd) byteLength = 2
      else if (byte === 0xfe) byteLength = 4
      else byteLength = 8

      if (byteLength > 1) state.start++ // Skip the length byte

      if (state.end - state.start < byteLength) throw new Error('Out of bounds')

      const b = state.buffer.subarray(state.start, (state.start += byteLength))

      return length <= 8 ? b.subarray(0, 1) : b
    }
  }
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "compact-encoding-bitfield",
  "version": "1.1.0",
  "description": "Compact codec for bitfields",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node --coverage test.mjs",
    "test:bare": "brittle-bare --coverage test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/compact-encoding/compact-encoding-bitfield.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/compact-encoding/compact-encoding-bitfield/issues"
  },
  "homepage": "https://github.com/compact-encoding/compact-encoding-bitfield#readme",
  "imports": {
    "util": {
      "bare": "bare-utils",
      "default": "util"
    }
  },
  "dependencies": {
    "compact-encoding": "^3.0.0"
  },
  "devDependencies": {
    "bare-utils": "^1.5.1",
    "brittle": "^3.1.0",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  }
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return uint24.decode(state) + 0x1000000 * uint32.decode(state)
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return uint32.decode(state) + 0x100000000 * uint32.decode(state)
  }
})

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "2.19.2",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    if (b.byteLength === 0) return null
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
module.exports = function debounce (worker, context = null) {
  debounced.running = null
  return debounced

  async function debounced () {
    if (debounced.running !== null) {
      try {
        await debounced.running
      } catch (_) {
        // ignore - do not fail on old errors
      }
    }

    // another "thread" beat us to it, just piggy pack on that one
    if (debounced.running !== null) return debounced.running

    debounced.running = worker.call(context)

    try {
      return await debounced.running
    } finally {
      debounced.running = null
    }
  }
}
{
  "name": "debounceify",
  "version": "1.1.0",
  "description": "Tiny async debouncer",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^16.0.3",
    "tape": "^5.1.1"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/debounceify.git"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/debounceify/issues"
  },
  "homepage": "https://github.com/mafintosh/debounceify"
}
const { EventEmitter } = require('events')
const Table = require('kademlia-routing-table')
const TOS = require('time-ordered-set')
const UDX = require('udx-native')
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const NatSampler = require('nat-sampler')
const b4a = require('b4a')
const NetworkHealth = require('./lib/health')
const IO = require('./lib/io')
const Query = require('./lib/query')
const Session = require('./lib/session')
const peer = require('./lib/peer')
const { UNKNOWN_COMMAND, INVALID_TOKEN } = require('./lib/errors')
const { PING, PING_NAT, FIND_NODE, DOWN_HINT, DELAYED_PING } = require('./lib/commands')

const TMP = b4a.allocUnsafe(32)
const TICK_INTERVAL = 5000
const SLEEPING_INTERVAL = 3 * TICK_INTERVAL
const STABLE_TICKS = 240 // if nothing major bad happens in ~20mins we can consider this node stable (if nat is friendly)
const MORE_STABLE_TICKS = 3 * STABLE_TICKS
const REFRESH_TICKS = 60 // refresh every ~5min when idle
const RECENT_NODE = 12 // we've heard from a node less than 1min ago
const OLD_NODE = 360 // if an node has been around more than 30 min we consider it old

const DEFAULTS = {
  concurrency: 10,
  maxWindow: IO.DEFAULT_MAX_WINDOW,
  maxPingDelay: 10_000
}

class DHT extends EventEmitter {
  constructor(opts = {}) {
    super()

    this.bootstrapNodes = opts.bootstrap === false ? [] : (opts.bootstrap || []).map(parseNode)
    this.table = new Table(randomBytes(32))
    this.nodes = new TOS()
    this.udx = opts.udx || new UDX()
    this.io = new IO(this.table, this.udx, {
      ...opts,
      onrequest: this._onrequest.bind(this),
      onresponse: this._onresponse.bind(this),
      ontimeout: this._ontimeout.bind(this)
    })
    this.health = new NetworkHealth(this)

    this.concurrency = opts.concurrency || DEFAULTS.concurrency
    this.maxPingDelay = opts.maxPingDelay || DEFAULTS.maxPingDelay
    this.bootstrapped = false
    this.ephemeral = true
    this.firewalled = this.io.firewalled
    this.adaptive = typeof opts.ephemeral !== 'boolean' && opts.adaptive !== false
    this.destroyed = false
    this.suspended = false
    this.online = true
    this.degraded = false
    this.stats = {
      queries: { active: 0, total: 0 },
      requests: this.io.stats.requests,
      commands: {
        ping: this.io.stats.commands[PING],
        pingNat: this.io.stats.commands[PING_NAT],
        findNode: this.io.stats.commands[FIND_NODE],
        downHint: this.io.stats.commands[DOWN_HINT]
      }
    }

    this._nat = new NatSampler()
    this._quickFirewall = opts.quickFirewall !== false
    this._forcePersistent = opts.ephemeral === false
    this._repinging = 0
    this._checks = 0
    this._tick = randomOffset(100) // make sure to random offset all the network ticks
    this._refreshTicks = randomOffset(REFRESH_TICKS)
    this._stableTicks = this.adaptive ? STABLE_TICKS : 0
    this._tickInterval = setInterval(this._ontick.bind(this), TICK_INTERVAL)
    this._lastTick = Date.now()
    this._lastHost = null
    this._filterNode = opts.filterNode || opts.addNode || null // opts.addNode is deprecating, use opts.filterNode instead
    this._onrow = (row) => row.on('full', (node) => this._onfullrow(node, row))
    this._nonePersistentSamples = []
    this._bootstrapping = this._bootstrap()
    this._bootstrapping.catch(noop)
    this._sendDownHints = opts.sendDownHints !== false
    this._downHintsRateLimit =
      opts.downHintsRateLimit !== undefined ? opts.downHintsRateLimit : 10 * 5
    this._downHintsSentPerTick = 0
    this._pendingTimers = new Set()

    this.table.on('row', this._onrow)

    this.io.networkInterfaces.on('change', (interfaces) => this._onnetworkchange(interfaces))

    if (opts.nodes) {
      for (let i = opts.nodes.length - 1; i >= 0; i--) {
        this.addNode(opts.nodes[i])
      }
    }
  }

  static DEFAULTS = DEFAULTS

  static bootstrapper(port, host, opts) {
    if (!port) throw new Error('Port is required')
    if (!host) throw new Error('Host is required')
    if (host === '0.0.0.0' || host === '::') throw new Error('Invalid host')
    if (!UDX.isIPv4(host)) throw new Error('Host must be a IPv4 address')

    const dht = new this({
      port,
      ephemeral: false,
      firewalled: false,
      anyPort: false,
      bootstrap: [],
      ...opts
    })
    dht._nat.add(host, port)
    return dht
  }

  get id() {
    return this.ephemeral ? null : this.table.id
  }

  get host() {
    return this._nat.host
  }

  get port() {
    return this._nat.port
  }

  get randomized() {
    return this._nat.host !== null && this._nat.port === 0
  }

  get socket() {
    return this.firewalled ? this.io.clientSocket : this.io.serverSocket
  }

  get config() {
    return {
      concurrency: this.concurrency,
      maxWindow: this.io.congestion._maxWindow,
      randomPunchInterval: this._randomPunchInterval,
      connectionKeepAlive: this.connectionKeepAlive,
      sendDownHints: this._sendDownHints,
      downHintsRateLimit: this._downHintsRateLimit
    }
  }

  onmessage(socket, buf, rinfo) {
    if (buf.byteLength > 1) this.io.onmessage(socket, buf, rinfo)
  }

  bind() {
    return this.io.bind()
  }

  async suspend({ log = noop } = {}) {
    log('Suspending waiting for io bind...')
    await this.io.bind()
    log('Done, continuing')
    if (this.suspended || this.destroyed) return
    this.suspended = true
    clearInterval(this._tickInterval)
    log('Done, suspending io')
    await this.io.suspend({ log })
    log('Done, dht suspended')
    this.emit('suspend')
  }

  async resume({ log = noop } = {}) {
    if (!this.suspended || this.destroyed) return
    this.suspended = false
    this._tickInterval = setInterval(this._ontick.bind(this), TICK_INTERVAL)
    this._onwakeup()
    log('Resuming io')
    await this.io.resume()
    log('Done, dht resumed')
    this.io.networkInterfaces.on('change', (interfaces) => this._onnetworkchange(interfaces))
    this.refresh()
    this.emit('resume')
  }

  address() {
    const socket = this.socket
    return socket ? socket.address() : null
  }

  localAddress() {
    if (!this.io.serverSocket) return null

    return {
      host: localIP(this.udx),
      port: this.io.serverSocket.address().port
    }
  }

  remoteAddress() {
    if (!this.host) return null
    if (!this.port) return null
    if (this.firewalled) return null
    if (!this.io.serverSocket) return null

    const port = this.io.serverSocket.address().port
    if (port !== this.port) return null

    return {
      host: this.host,
      port
    }
  }

  addNode({ host, port }) {
    this._addNode({
      id: peer.id(host, port),
      port,
      host,
      token: null,
      to: null,
      sampled: 0,
      added: this._tick,
      pinged: 0,
      seen: 0,
      downHints: 0,
      prev: null,
      next: null
    })
  }

  toArray(opts) {
    const limit = opts && opts.limit
    if (limit === 0) return []
    return this.nodes.toArray({ limit, reverse: true }).map(({ host, port }) => ({ host, port }))
  }

  async fullyBootstrapped() {
    return this._bootstrapping
  }

  ready() {
    // Deprecating, use fullyBootstrapped instead (removed on next major)
    return this.fullyBootstrapped()
  }

  findNode(target, opts) {
    if (this.destroyed) throw new Error('Node destroyed')
    this._refreshTicks = REFRESH_TICKS
    return new Query(this, target, true, FIND_NODE, null, opts)
  }

  query({ target, command, value }, opts) {
    if (this.destroyed) throw new Error('Node destroyed')
    this._refreshTicks = REFRESH_TICKS
    return new Query(this, target, false, command, value || null, opts)
  }

  ping({ host, port }, opts) {
    let value = null

    if (opts && opts.size && opts.size > 0) value = b4a.alloc(opts.size)

    const req = this.io.createRequest(
      { id: null, host, port },
      null,
      true,
      PING,
      null,
      value,
      (opts && opts.session) || null,
      opts && opts.ttl
    )
    return this._requestToPromise(req, opts)
  }

  delayedPing({ host, port }, delayMs, opts) {
    if (delayMs > this.maxPingDelay) {
      throw new Error(`Delay exceeds max delay: ${this.maxPingDelay}ms`)
    }

    const value = b4a.allocUnsafe(4)
    c.uint32.encode({ start: 0, end: 4, buffer: value }, delayMs)

    const req = this.io.createRequest(
      { id: null, host, port },
      null,
      true,
      DELAYED_PING,
      null,
      value,
      (opts && opts.session) || null,
      opts && opts.ttl
    )
    // add 1 second to the timeout to account for network overhead
    req.timeout = delayMs + 1_000
    return this._requestToPromise(req, opts)
  }

  async rttStats() {
    const stats = {
      successes: 0,
      errors: 0,
      responses: {
        avgRtt: 0,
        errors: 0,
        avgCloserNodes: 0
      },
      closestReplies: {
        avgRtt: 0,
        errors: 0,
        avgCloserNodes: 0
      }
    }

    if (this.nodes.latest) {
      const q = this.findNode(this.nodes.latest.id)

      let responseCount = 0
      let closestCount = 0

      for await (const msg of q) {
        stats.responses.avgRtt += msg.rtt
        stats.responses.errors += msg.error
        stats.responses.avgCloserNodes += msg.closerNodes?.length || 0
        responseCount++
      }
      stats.responses.avgRtt /= responseCount
      stats.responses.avgCloserNodes /= responseCount

      for await (const msg of q.closestReplies) {
        stats.closestReplies.avgRtt += msg.rtt
        stats.closestReplies.errors += msg.error
        stats.closestReplies.avgCloserNodes += msg.closerNodes?.length || 0
        closestCount++
      }
      stats.closestReplies.avgRtt /= closestCount
      stats.closestReplies.avgCloserNodes /= closestCount

      stats.successes = q.successes
      stats.errors = q.errors
    }

    return stats
  }

  request({ token = null, command, target = null, value = null }, { host, port }, opts) {
    const req = this.io.createRequest(
      { id: null, host, port },
      token,
      false,
      command,
      target,
      value,
      (opts && opts.session) || null,
      opts && opts.ttl
    )
    return this._requestToPromise(req, opts)
  }

  session() {
    return new Session(this)
  }

  _requestToPromise(req, opts) {
    if (req === null) return Promise.reject(new Error('Node destroyed'))

    if (opts && opts.socket) req.socket = opts.socket
    if (opts && opts.retry === false) req.retries = 0

    return new Promise((resolve, reject) => {
      req.onresponse = resolve
      req.onerror = reject
      req.send()
    })
  }

  async _bootstrap() {
    const self = this

    await Promise.resolve() // wait a tick, so apis can be used from the outside
    await this.io.bind()

    this.emit('listening')

    // TODO: some papers describe more advanced ways of bootstrapping - we should prob look into that

    let first = this.firewalled && this._quickFirewall && !this._forcePersistent
    let testNat = false

    const onlyFirewall = !this._forcePersistent

    for (let i = 0; i < 2; i++) {
      await this._backgroundQuery(this.table.id).on('data', ondata).finished()

      if (this.bootstrapped || (!testNat && !this._forcePersistent)) break
      if (!(await this._updateNetworkState(onlyFirewall))) break
    }

    if (this.bootstrapped) return
    this.bootstrapped = true

    this.emit('ready')

    function ondata(data) {
      // Simple QUICK nat heuristic.
      // If we get ONE positive nat ping before the bootstrap query finishes
      // then we always to a nat test, no matter if we are adaptive...
      // This should be expanded in the future to try more than one node etc, not always hit the first etc
      // If this fails, then nbd, as the onstable hook will pick it up later.

      if (!first) return
      first = false

      const value = b4a.allocUnsafe(2)
      c.uint16.encode({ start: 0, end: 2, buffer: value }, self.io.serverSocket.address().port)

      self._request(
        data.from,
        false,
        true,
        PING_NAT,
        null,
        value,
        null,
        () => {
          testNat = true
        },
        noop
      )
    }
  }

  refresh() {
    const node = this.table.random()
    this._backgroundQuery(node ? node.id : this.table.id).on('error', noop)
  }

  async destroy() {
    const emitClose = !this.destroyed
    this.destroyed = true
    clearInterval(this._tickInterval)
    for (const timer of this._pendingTimers) {
      clearTimeout(timer)
    }
    await this.io.destroy()
    if (emitClose) this.emit('close')
  }

  _request(to, force, internal, command, target, value, session, onresponse, onerror) {
    if (internal && !this._sendDownHints && command === DOWN_HINT) return null
    const req = this.io.createRequest(to, null, internal, command, target, value, session)
    if (req === null) return null

    req.onresponse = onresponse
    req.onerror = onerror
    req.send(force)

    return req
  }

  _natAdd(host, port) {
    const prevHost = this._nat.host
    const prevPort = this._nat.port

    this._nat.add(host, port)

    if (prevHost === this._nat.host && prevPort === this._nat.port) return

    this.emit('nat-update', this._nat.host, this._nat.port)
  }

  // we don't check that this is a bootstrap node but we limit the sample size to very few nodes, so fine
  _sampleBootstrapMaybe(from, to) {
    if (this._nonePersistentSamples.length >= Math.max(1, this.bootstrapNodes.length)) return
    const id = from.host + ':' + from.port
    if (this._nonePersistentSamples.indexOf(id) > -1) return
    this._nonePersistentSamples.push(id)
    this._natAdd(to.host, to.port)
  }

  _addNodeFromNetwork(sample, from, to) {
    if (this._filterNode !== null && !this._filterNode(from)) {
      return
    }

    if (from.id === null) {
      this._sampleBootstrapMaybe(from, to)
      return
    }

    const oldNode = this.table.get(from.id)

    // refresh it, if we've seen this before
    if (oldNode) {
      if (sample && (oldNode.sampled === 0 || this._tick - oldNode.sampled >= OLD_NODE)) {
        oldNode.to = to
        oldNode.sampled = this._tick
        this._natAdd(to.host, to.port)
      }

      oldNode.pinged = oldNode.seen = this._tick
      this.nodes.add(oldNode)
      return
    }

    this._addNode({
      id: from.id,
      port: from.port,
      host: from.host,
      to,
      sampled: 0,
      added: this._tick,
      pinged: this._tick, // last time we interacted with them
      seen: this._tick, // last time we heard from them
      downHints: 0,
      prev: null,
      next: null
    })
  }

  _addNode(node) {
    if (this.nodes.has(node) || b4a.equals(node.id, this.table.id)) return

    node.added = node.pinged = node.seen = this._tick

    if (!this.table.add(node)) return
    this.nodes.add(node)

    if (node.to && node.sampled === 0) {
      node.sampled = this._tick
      this._natAdd(node.to.host, node.to.port)
    }

    this.emit('add-node', node)
  }

  _removeStaleNode(node, lastSeen) {
    if (node.seen <= lastSeen) this._removeNode(node)
  }

  _removeNode(node) {
    if (!this.nodes.has(node)) return

    this.table.remove(node.id)
    this.nodes.remove(node)

    this.emit('remove-node', node)
  }

  _onwakeup() {
    this._tick += 2 * OLD_NODE // bump the tick enough that everything appears old.
    this._tick += 8 - (this._tick & 7) - 2 // triggers a series of pings in two ticks
    this._stableTicks = MORE_STABLE_TICKS
    this._refreshTicks = 1 // triggers a refresh next tick (allow network time to wake up also)
    this._lastHost = null // clear network cache check
    this.health.reset()

    if (this.adaptive) {
      // TODO: re-enable this as soon as we find out why this is over triggering in some edge cases
      // this.firewalled = true
      // this.io.firewalled = true

      if (!this.ephemeral) {
        this.ephemeral = true
        this.io.ephemeral = true
        this.emit('ephemeral')
      }
    }

    this.emit('wakeup')
  }

  _onfullrow(newNode, row) {
    if (!this.bootstrapped || this._repinging >= 3) return

    let oldest = null
    for (const node of row.nodes) {
      if (node.pinged === this._tick) continue
      if (
        oldest === null ||
        oldest.pinged > node.pinged ||
        (oldest.pinged === node.pinged && oldest.added > node.added)
      ) {
        oldest = node
      }
    }

    if (oldest === null) return
    if (this._tick - oldest.pinged < RECENT_NODE && this._tick - oldest.added > OLD_NODE) return

    this._repingAndSwap(newNode, oldest)
  }

  _onnetworkchange(interfaces) {
    this.emit('network-change', interfaces)
    this.emit('network-update')
  }

  _repingAndSwap(newNode, oldNode) {
    const self = this
    const lastSeen = oldNode.seen

    oldNode.pinged = this._tick

    this._repinging++
    this._request(
      { id: null, host: oldNode.host, port: oldNode.port },
      false,
      true,
      PING,
      null,
      null,
      null,
      onsuccess,
      onswap
    )

    function onsuccess(m) {
      if (oldNode.seen <= lastSeen) return onswap()
      self._repinging--
    }

    function onswap(e) {
      self._repinging--
      self._removeNode(oldNode)
      self._addNode(newNode)
    }
  }

  _onrequest(req, external) {
    if (req.from.id !== null) {
      this._addNodeFromNetwork(!external, req.from, req.to)
    }

    if (req.internal) {
      switch (req.command) {
        // standard keep alive call
        case PING: {
          req.sendReply(0, null, false, false)
          return
        }
        case DELAYED_PING: {
          this._ondelayedping(req)
          return
        }
        // check if the other side can receive a message to their other socket
        case PING_NAT: {
          if (req.value === null || req.value.byteLength < 2) return
          const port = c.uint16.decode({ start: 0, end: 2, buffer: req.value })
          if (port === 0) return
          req.from.port = port
          req.sendReply(0, null, false, false)
          return
        }
        // empty dht reply back
        case FIND_NODE: {
          if (!req.target) return
          req.sendReply(0, null, false, true)
          return
        }
        // "this is node you sent me is down" - let's try to ping it
        case DOWN_HINT: {
          if (req.value === null || req.value.byteLength < 6) return
          if (this._checks < 10) {
            sodium.crypto_generichash(TMP, req.value.subarray(0, 6))
            const node = this.table.get(TMP)
            if (node && (node.pinged < this._tick || node.downHints === 0)) {
              node.downHints++
              this._check(node)
            }
          }
          req.sendReply(0, null, false, false)
          return
        }
      }

      req.sendReply(UNKNOWN_COMMAND, null, false, req.target !== null)
      return
    }

    // ask the user to handle it or reply back with a bad command
    if (this.onrequest(req) === false) {
      req.sendReply(UNKNOWN_COMMAND, null, false, req.target !== null)
    }
  }

  onrequest(req) {
    return this.emit('request', req)
  }

  _ondelayedping(req) {
    if (req.value === null || req.value.byteLength < 4) return
    const delayMs = c.uint32.decode({ start: 0, end: 4, buffer: req.value })
    if (delayMs > this.maxPingDelay) return
    const timer = setTimeout(() => {
      if (this.destroyed) return
      this._pendingTimers.delete(timer)
      req.sendReply(0, null, false, false)
    }, delayMs)
    this._pendingTimers.add(timer)
  }

  _onresponse(res, external) {
    this._addNodeFromNetwork(!external, res.from, res.to)
  }

  _ontimeout(req) {
    if (!req.to.id) return
    const node = this.table.get(req.to.id)
    if (node) this._removeNode(node)
  }

  _pingSome() {
    let cnt = this.io.inflight.length > 2 ? 3 : 5
    let oldest = this.nodes.oldest

    // tiny dht, pinged the bootstrap again
    if (!oldest) {
      this.refresh()
      return
    }

    // we've recently pinged the oldest one, so only trigger a couple of repings
    if (this._tick - oldest.pinged < RECENT_NODE) {
      cnt = 2
    }

    while (cnt--) {
      if (!oldest || this._tick === oldest.pinged) continue
      this._check(oldest)
      oldest = oldest.next
    }
  }

  _check(node) {
    node.pinged = this._tick

    const lastSeen = node.seen
    const onresponse = () => {
      this._checks--
      this._removeStaleNode(node, lastSeen)
    }
    const onerror = () => {
      this._checks--
      this._removeNode(node)
    }

    this._checks++
    this._request(
      { id: null, host: node.host, port: node.port },
      false,
      true,
      PING,
      null,
      null,
      null,
      onresponse,
      onerror
    )
  }

  _ontick() {
    const time = Date.now()

    if (time - this._lastTick > SLEEPING_INTERVAL && this.suspended === false) {
      this._onwakeup()
    } else {
      this._tick++
    }

    this._lastTick = time

    if (!this.bootstrapped || this.suspended) return

    if (this.adaptive && this.ephemeral && --this._stableTicks <= 0) {
      if (this._lastHost === this._nat.host) {
        // do not recheck the same network...
        this._stableTicks = MORE_STABLE_TICKS
      } else {
        this._updateNetworkState() // the promise returned here never fails so just ignore it
      }
    }

    if ((this._tick & 7) === 0) {
      this._pingSome()
    }

    if (
      ((this._tick & 63) === 0 && this.nodes.length < this.table.k) ||
      --this._refreshTicks <= 0
    ) {
      this.refresh()
    }

    this._downHintsSentPerTick = 0
    this.health.update()
  }

  async _updateNetworkState(onlyFirewall = false) {
    if (!this.ephemeral) return false
    if (onlyFirewall && !this.firewalled) return false

    const { host, port } = this._nat

    if (!onlyFirewall) {
      // remember what host we checked and reset the counter
      this._stableTicks = MORE_STABLE_TICKS
      this._lastHost = host
    }

    // check if we have a consistent host and port
    if (host === null || port === 0) {
      return false
    }

    const natSampler = this.firewalled ? new NatSampler() : this._nat

    // ask remote nodes to ping us on our server socket to see if we have the port open
    const firewalled = this.firewalled && (await this._checkIfFirewalled(natSampler))
    if (firewalled) return false

    this.firewalled = this.io.firewalled = false

    // incase it's called in parallel for some reason, or if our nat status somehow changed
    if (!this.ephemeral || host !== this._nat.host || port !== this._nat.port) return false
    // if the firewall probe returned a different host / non consistent port, bail as well
    if (natSampler.host !== host || natSampler.port === 0) return false

    const id = peer.id(natSampler.host, natSampler.port)

    if (!onlyFirewall) {
      this.ephemeral = this.io.ephemeral = false
    }

    if (natSampler !== this._nat) {
      const prevHost = this._nat.host
      const prevPort = this._nat.port

      this._nonePersistentSamples = []
      this._nat = natSampler

      if (prevHost !== this._nat.host || prevPort !== this._nat.port) {
        this.emit('nat-update', this._nat.host, this._nat.port)
      }
    }

    // TODO: we should make this a bit more defensive in terms of using more
    // resources to make sure that the new routing table contains as many alive nodes
    // as possible, vs blindly copying them over...

    // all good! copy over the old routing table to the new one
    if (!b4a.equals(this.table.id, id)) {
      const nodes = this.table.toArray()

      this.table = this.io.table = new Table(id)

      for (const node of nodes) {
        if (b4a.equals(node.id, id)) continue
        if (!this.table.add(node)) this.nodes.remove(node)
      }

      this.table.on('row', this._onrow)

      // we need to rebootstrap/refresh since we updated our id
      if (this.bootstrapped) this.refresh()
    }

    if (!this.ephemeral) {
      this.emit('persistent')
    }

    return true
  }

  async *_resolveBootstrapNodes() {
    for (let { host, port } of this.bootstrapNodes) {
      let doLookup = false

      if (host.indexOf('@') === -1) {
        doLookup = true
      } else {
        const [suggestedIP, fallbackHost] = host.split('@')
        try {
          await this.ping({ host: suggestedIP, port })
          host = suggestedIP
        } catch {
          host = fallbackHost
          doLookup = true
        }
      }

      if (doLookup) {
        try {
          host = UDX.isIPv4(host) ? host : (await this.udx.lookup(host, { family: 4 })).host
        } catch {
          continue
        }
      }

      yield {
        id: peer.id(host, port),
        host,
        port
      }
    }
  }

  async _addBootstrapNodes(nodes) {
    for await (const node of this._resolveBootstrapNodes()) {
      nodes.push(node)
    }
  }

  async _checkIfFirewalled(natSampler = new NatSampler()) {
    const nodes = []
    for (let node = this.nodes.latest; node && nodes.length < 5; node = node.prev) {
      nodes.push(node)
    }

    if (nodes.length < 5) await this._addBootstrapNodes(nodes)
    // if no nodes are available, including bootstrappers - bail
    if (nodes.length === 0) return true

    const hosts = new Set()
    const value = b4a.allocUnsafe(2)

    c.uint16.encode({ start: 0, end: 2, buffer: value }, this.io.serverSocket.address().port)

    // double check they actually came on the server socket...
    this.io.serverSocket.on('message', onmessage)

    const pongs = await requestAll(this, true, PING_NAT, value, nodes)

    let count = 0
    for (const res of pongs) {
      if (hosts.has(res.from.host)) {
        count++
        natSampler.add(res.to.host, res.to.port)
      }
    }

    this.io.serverSocket.removeListener('message', onmessage)

    // if we got no or very few replies, consider it a fluke
    if (count < (nodes.length >= 5 ? 3 : 1)) return true

    // check that the server socket has the same ip as the client socket
    if (natSampler.host === null || this._nat.host !== natSampler.host) return true

    // check that the local port of the server socket is the same as the remote port
    // TODO: we might want a flag to opt out of this heuristic for specific remapped port servers
    if (natSampler.port === 0 || natSampler.port !== this.io.serverSocket.address().port) {
      return true
    }

    return false

    function onmessage(_, { host }) {
      hosts.add(host)
    }
  }

  _backgroundQuery(target) {
    this._refreshTicks = REFRESH_TICKS

    const backgroundCon = Math.min(this.concurrency, Math.max(2, (this.concurrency / 8) | 0))
    const q = new Query(this, target, true, FIND_NODE, null, {
      concurrency: backgroundCon
    })

    q.on('data', () => {
      // yield to other traffic
      q.concurrency = this.io.inflight.length < 3 ? this.concurrency : backgroundCon
    })

    return q
  }

  // called by health
  _online() {
    if (this.online && !this.degraded) return
    this.online = true
    this.degraded = false
    this.emit('network-update')
  }

  // called by health
  _degraded() {
    if (this.degraded) return
    this.online = true
    this.degraded = true
    this.emit('network-update')
  }

  // called by health
  _offline() {
    if (!this.online) return
    this.online = false
    this.degraded = false
    this.emit('network-update')
  }
}

DHT.OK = 0
DHT.ERROR_UNKNOWN_COMMAND = UNKNOWN_COMMAND
DHT.ERROR_INVALID_TOKEN = INVALID_TOKEN

module.exports = DHT

function localIP(udx, family = 4) {
  let host = null

  for (const n of udx.networkInterfaces()) {
    if (n.family !== family || n.internal) continue

    // mac really likes en0, mb a better way but this shouldnt be bad anywhere so return now
    if (n.name === 'en0') return n.host

    // otherwise pick the first non internal host (let the loop continue in case we see en0)
    if (host === null) host = n.host
  }

  return host || (family === 4 ? '127.0.0.1' : '::1')
}

function parseNode(s) {
  if (typeof s === 'object') return s
  if (typeof s === 'number') return { host: '127.0.0.1', port: s }
  const [host, port] = s.split(':')
  if (!port) throw new Error('Bootstrap node format is host:port')

  return {
    host,
    port: Number(port)
  }
}

function randomBytes(n) {
  const b = b4a.alloc(n)
  sodium.randombytes_buf(b)
  return b
}

function randomOffset(n) {
  return n - ((Math.random() * 0.5 * n) | 0)
}

function requestAll(dht, internal, command, value, nodes) {
  let missing = nodes.length
  const replies = []

  return new Promise((resolve) => {
    for (const node of nodes) {
      const req = dht._request(
        node,
        false,
        internal,
        command,
        null,
        value,
        null,
        onsuccess,
        onerror
      )
      if (!req) return resolve(replies)
    }

    function onsuccess(res) {
      replies.push(res)
      if (--missing === 0) resolve(replies)
    }

    function onerror() {
      if (--missing === 0) resolve(replies)
    }
  })
}

function noop() {}
exports.PING = 0
exports.PING_NAT = 1
exports.FIND_NODE = 2
exports.DOWN_HINT = 3
exports.DELAYED_PING = 4
module.exports = class DHTError extends Error {
  constructor(msg, code, fn = DHTError) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'DHTError'
  }

  static UNKNOWN_COMMAND = 1
  static INVALID_TOKEN = 2

  static REQUEST_TIMEOUT(msg = 'Request timed out') {
    return new DHTError(msg, 'REQUEST_TIMEOUT', DHTError.REQUEST_TIMEOUT)
  }

  static REQUEST_DESTROYED(msg = 'Request destroyed') {
    return new DHTError(msg, 'REQUEST_DESTROYED', DHTError.REQUEST_DESTROYED)
  }

  static IO_SUSPENDED(msg = 'I/O suspended') {
    return new DHTError(msg, 'IO_SUSPENDED', DHTError.IO_SUSPENDED)
  }
}
const MAX_HEALTH_WINDOW = 4
const OFFLINE_THRESHOLD = 2
const IDLE_THRESHOLD = 4
const DEGRADED_TIMEOUT_RATE_THRESHOLD = 0.5

module.exports = class NetworkHealth {
  constructor(dht) {
    this._dht = dht
    this._window = []
    this._head = -1
    this._offlineTicks = 0
    this._degradedTicks = 0
    this._healthyTicks = 0
    this.online = true
    this.degraded = false
  }

  get oldest() {
    return this._window[this._tail]
  }

  get previous() {
    return this._window[(this._head - 1 + MAX_HEALTH_WINDOW) % MAX_HEALTH_WINDOW]
  }

  get newest() {
    return this._window[this._head]
  }

  get responses() {
    if (!this.newest || !this.previous) return 0
    return this.newest.responses - this.previous.responses
  }

  get timeouts() {
    if (!this.newest || !this.previous) return 0
    return this.newest.timeouts - this.previous.timeouts
  }

  get timeoutsRate() {
    if (this.timeouts === 0) return 0
    return this.timeouts / (this.responses + this.timeouts)
  }

  get cold() {
    return this._window.length < MAX_HEALTH_WINDOW
  }

  get idle() {
    return this.responses + this.timeouts < IDLE_THRESHOLD
  }

  get stats() {
    return {
      online: this.online,
      degraded: this.degraded,
      cold: this.cold,
      idle: this.idle,
      responses: this.responses,
      timeouts: this.timeouts,
      timeoutsRate: this.timeoutsRate
    }
  }

  get _tail() {
    return (this._head + 1) % MAX_HEALTH_WINDOW
  }

  reset() {
    this._window = []
    this._head = -1
    this._offlineTicks = 0
    this._degradedTicks = 0
    this._healthyTicks = 0
    this.online = true
    this.degraded = false
    this._dht._online()
  }

  update() {
    // update counters before dropping oldest
    if (this.oldest?.degraded) this._degradedTicks--
    else if (this.oldest?.degraded === false) this._healthyTicks--

    // move window
    this._head = this._tail
    this._window[this._head] = {
      responses: this._dht.stats.requests.responses,
      timeouts: this._dht.stats.requests.timeouts
    }

    // skip state changes
    if (this.cold || this.idle) return

    // update newest
    this.newest.offline = this.responses === 0
    this.newest.degraded =
      !this.newest.offline && this.timeoutsRate > DEGRADED_TIMEOUT_RATE_THRESHOLD

    // update counters
    if (this.newest.offline) this._offlineTicks++
    else {
      this._offlineTicks = 0
      if (this.newest.degraded) this._degradedTicks++
      else this._healthyTicks++
    }

    // check online/offline
    if (!this.newest.offline) this.online = true
    else if (this._offlineTicks >= OFFLINE_THRESHOLD) this.online = false

    // check degraded
    if (!this.online || this._healthyTicks === MAX_HEALTH_WINDOW) this.degraded = false
    else if (this._degradedTicks === MAX_HEALTH_WINDOW) this.degraded = true

    // fire events
    if (this.online && !this.degraded) this._dht._online()
    else if (this.degraded) this._dht._degraded()
    else this._dht._offline()
  }
}
const FIFO = require('fast-fifo')
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const b4a = require('b4a')
const AdaptiveTimeout = require('adaptive-timeout')
const peer = require('./peer')
const { INVALID_TOKEN, REQUEST_TIMEOUT, REQUEST_DESTROYED, IO_SUSPENDED } = require('./errors')

const VERSION = 0b11
const RESPONSE_ID = (0b0001 << 4) | VERSION
const REQUEST_ID = (0b0000 << 4) | VERSION
const EMPTY_ARRAY = []
const MAX_WINDOW = 80

module.exports = class IO {
  constructor(
    table,
    udx,
    {
      maxWindow = MAX_WINDOW,
      port = 0,
      host = '0.0.0.0',
      anyPort = true,
      firewalled = true,
      onrequest,
      onresponse = noop,
      ontimeout = noop,
      adaptiveTimeout
    } = {}
  ) {
    this.table = table
    this.udx = udx
    this.inflight = []
    this.clientSocket = null
    this.serverSocket = null
    this.firewalled = firewalled !== false
    this.ephemeral = true
    this.congestion = new CongestionWindow(maxWindow)
    this.networkInterfaces = udx.watchNetworkInterfaces()
    this.suspended = false

    this.stats = {
      requests: {
        active: 0,
        total: 0,
        responses: 0,
        timeouts: 0,
        retries: 0
      },
      commands: [
        { tx: 0, rx: 0 }, // tx = transmitted, rx = received
        { tx: 0, rx: 0 },
        { tx: 0, rx: 0 },
        { tx: 0, rx: 0 }
      ]
    }

    this.onrequest = onrequest
    this.onresponse = onresponse
    this.ontimeout = ontimeout

    this._pending = new FIFO()
    this._rotateSecrets = 10
    this._tid = (Math.random() * 65536) | 0
    this._secrets = null
    this._drainInterval = null
    this._destroying = null
    this._binding = null

    // port can be a number or a range [start, to]
    this.portRange = port.length ? port : port === 0 ? [0, 0] : [port, port + 5]

    this._host = host
    this._anyPort = anyPort !== false
    this._boundServerPort = 0
    this._boundClientPort = 0

    this._adt = adaptiveTimeout ? new AdaptiveTimeout(adaptiveTimeout) : null
  }

  static DEFAULT_MAX_WINDOW = MAX_WINDOW

  onmessage(socket, buffer, { host, port }) {
    if (buffer.byteLength < 2 || !(port > 0 && port < 65536) || this.suspended === true) return

    const from = { id: null, host, port }
    const state = { start: 1, end: buffer.byteLength, buffer }
    const expectedSocket = this.firewalled ? this.clientSocket : this.serverSocket
    const external = socket !== expectedSocket

    if (buffer[0] === REQUEST_ID) {
      const req = Request.decode(this, socket, from, state)
      if (req === null) return
      if (
        req.token !== null &&
        !b4a.equals(req.token, this.token(req.from, 1)) &&
        !b4a.equals(req.token, this.token(req.from, 0))
      ) {
        req.error(INVALID_TOKEN, { token: true })
        return
      }
      this.onrequest(req, external)
      return
    }

    if (buffer[0] === RESPONSE_ID) {
      const res = decodeReply(from, state)
      if (res === null) return

      for (let i = 0; i < this.inflight.length; i++) {
        const req = this.inflight[i]
        if (req.tid !== res.tid) continue

        res.rtt = Date.now() - req._timestamp

        if (this._adt && req.sent <= 2) {
          this._adt.put(`${req.to.host}:${req.to.port}`, res.rtt)
        }

        if (i === this.inflight.length - 1) this.inflight.pop()
        else this.inflight[i] = this.inflight.pop()

        if (req.session) req.session._detach(req)

        // TODO: Auto retry here if errors.INVALID_TOKEN is returned?

        if (req._timeout) {
          clearTimeout(req._timeout)
          req._timeout = null
        }

        this.congestion.recv()

        if (req.internal && req.command < this.stats.commands.length) {
          this.stats.commands[req.command].rx++
        }

        this.stats.requests.active--
        this.stats.requests.responses++

        this.onresponse(res, external)
        req.onresponse(res, req)
        break
      }
    }
  }

  token(addr, i) {
    if (this._secrets === null) {
      const buf = b4a.alloc(64)
      this._secrets = [buf.subarray(0, 32), buf.subarray(32, 64)]
      sodium.randombytes_buf(this._secrets[0])
      sodium.randombytes_buf(this._secrets[1])
    }

    const token = b4a.allocUnsafe(32)
    sodium.crypto_generichash(token, b4a.from(addr.host), this._secrets[i])
    return token
  }

  async destroy() {
    if (this._destroying) return this._destroying
    this._destroying = this._destroy()
    return this._destroying
  }

  async _destroy() {
    // simplifies timing to await the bind here also, although it might be unneeded
    await this.bind()
    await this._clear(false)
  }

  async _clear(suspended) {
    if (this._drainInterval) {
      clearInterval(this._drainInterval)
      this._drainInterval = null
    }

    while (this.inflight.length) {
      const req = this.inflight.pop()
      if (req._timeout) clearTimeout(req._timeout)
      req._timeout = null
      req.destroyed = true

      if (req.session) req.session._detach(req)

      this.congestion.recv()
      this.stats.requests.active--

      req.onerror(suspended ? IO_SUSPENDED() : REQUEST_DESTROYED(), req)
    }

    await Promise.allSettled([this.serverSocket.close(), this.clientSocket.close()])

    this.networkInterfaces.destroy()
  }

  async suspend() {
    this.suspended = true
    await this._clear(true)

    this.congestion.clear()

    if (this._drainInterval) {
      clearInterval(this._drainInterval)
      this._drainInterval = null
    }
  }

  async _rebind(binding) {
    if (binding) await binding
    if (this._destroying) return this._destroying
    await this._bindSockets()
    this.networkInterfaces = this.udx.watchNetworkInterfaces()
  }

  resume() {
    this.suspended = false
    const binding = this._binding
    this._binding = this._rebind(binding)
    return this._binding
  }

  bind() {
    if (this._binding) return this._binding
    this._binding = this._bindSockets()
    return this._binding
  }

  async _bindSockets() {
    const serverSocket = this.udx.createSocket()

    const candidatePorts = []

    // Retrying previous port always has precedence
    if (this._boundServerPort) candidatePorts.push(this._boundServerPort)

    for (let i = this.portRange[0]; i < this.portRange[1]; i++) candidatePorts.push(i)

    for (const port of candidatePorts) {
      if (serverSocket.bound) break

      try {
        serverSocket.bind(port, this._host)
      } catch (err) {
        if (!this._anyPort) {
          await serverSocket.close()
          throw err
        }
      }
    }

    if (!serverSocket.bound) {
      try {
        serverSocket.bind(0, this._host)
      } catch (err) {
        await serverSocket.close()
        throw err
      }
    }

    const clientSocket = this.udx.createSocket()

    try {
      clientSocket.bind(this._boundClientPort || 0, this._host)
    } catch {
      try {
        clientSocket.bind(0, this._host)
      } catch (err) {
        await serverSocket.close()
        await clientSocket.close()
        throw err
      }
    }

    this._boundServerPort = serverSocket.address().port
    this._boundClientPort = clientSocket.address().port

    this.clientSocket = clientSocket
    this.serverSocket = serverSocket

    this.serverSocket.on('message', this.onmessage.bind(this, this.serverSocket))
    this.clientSocket.on('message', this.onmessage.bind(this, this.clientSocket))

    if (this._drainInterval === null) {
      this._drainInterval = setInterval(this._drain.bind(this), 750)
      if (this._drainInterval.unref) this._drainInterval.unref()
    }

    for (const req of this.inflight) {
      if (!req.socket) req.socket = this.firewalled ? this.clientSocket : this.serverSocket
      req.sent = 0
      req.send(false)
    }
  }

  _drain() {
    if (this._secrets !== null && --this._rotateSecrets === 0) {
      this._rotateSecrets = 10
      const tmp = this._secrets[0]
      this._secrets[0] = this._secrets[1]
      this._secrets[1] = tmp
      sodium.crypto_generichash(tmp, tmp)
    }

    this.congestion.drain()

    while (!this.congestion.isFull()) {
      const p = this._pending.shift()
      if (p === undefined) return
      p._sendNow()
    }
  }

  createRequest(to, token, internal, command, target, value, session, ttl) {
    if (this._destroying !== null) return null

    if (this._tid === 65536) this._tid = 0

    const tid = this._tid++
    const socket = this.firewalled ? this.clientSocket : this.serverSocket

    const req = new Request(
      this,
      socket,
      tid,
      null,
      to,
      token,
      internal,
      command,
      target,
      value,
      session,
      ttl || 0
    )
    this.inflight.push(req)
    if (session) session._attach(req)

    if (internal && command < this.stats.commands.length) {
      this.stats.commands[command].tx++
    }

    this.stats.requests.active++
    this.stats.requests.total++

    return req
  }
}

class Request {
  constructor(io, socket, tid, from, to, token, internal, command, target, value, session, ttl) {
    this.socket = socket
    this.tid = tid
    this.from = from
    this.to = to
    this.token = token
    this.command = command
    this.target = target
    this.value = value
    this.internal = internal
    this.session = session
    this.ttl = ttl
    this.index = -1
    this.sent = 0
    this.retries = 3
    this.destroyed = false
    this.timeout = 0

    this.oncycle = noop
    this.onerror = noop
    this.onresponse = noop

    this._buffer = null
    this._io = io
    this._timeout = null
    this._timestamp = Date.now()
  }

  static decode(io, socket, from, state) {
    try {
      const flags = c.uint.decode(state)
      const tid = c.uint16.decode(state)
      const to = peer.ipv4.decode(state)
      const id = flags & 1 ? c.fixed32.decode(state) : null
      const token = flags & 2 ? c.fixed32.decode(state) : null
      const internal = (flags & 4) !== 0
      const command = c.uint.decode(state)
      const target = flags & 8 ? c.fixed32.decode(state) : null
      const value = flags & 16 ? c.buffer.decode(state) : null

      if (id !== null) from.id = validateId(id, from)

      return new Request(
        io,
        socket,
        tid,
        from,
        to,
        token,
        internal,
        command,
        target,
        value,
        null,
        0
      )
    } catch {
      return null
    }
  }

  reply(value, opts = {}) {
    const socket = opts.socket || this.socket
    const to = opts.to || this.from
    this._sendReply(0, value || null, opts.token !== false, opts.closerNodes !== false, to, socket)
  }

  error(code, opts = {}) {
    const socket = opts.socket || this.socket
    const to = opts.to || this.from
    this._sendReply(code, null, opts.token === true, opts.closerNodes !== false, to, socket)
  }

  relay(value, to, opts) {
    const socket = (opts && opts.socket) || this.socket
    const buffer = this._encodeRequest(null, value, to, socket)
    socket.trySend(buffer, to.port, to.host, this.ttl)
  }

  send(force = false) {
    if (this.destroyed) return

    if (this.socket === null) return
    if (this._buffer === null) {
      this._buffer = this._encodeRequest(this.token, this.value, this.to, this.socket)
    }

    if (!force && this._io.congestion.isFull()) {
      this._io._pending.push(this)
      return
    }

    this._sendNow()
  }

  sendReply(error, value, token, hasCloserNodes) {
    this._sendReply(error, value, token, hasCloserNodes, this.from, this.socket, null)
  }

  _sendNow() {
    if (this.destroyed) return
    this.sent++
    this._io.congestion.send()
    this.socket.trySend(this._buffer, this.to.port, this.to.host, this.ttl)
    if (this._timeout) clearTimeout(this._timeout)
    const value =
      this.timeout || this._io._adt?.get(`${this.to.host}:${this.to.port}`, this.sent) || 1000
    this._timeout = setTimeout(oncycle, value, this)
  }

  destroy(err) {
    if (this.destroyed) return
    this.destroyed = true

    if (this._timeout) {
      clearTimeout(this._timeout)
      this._timeout = null
    }

    const i = this._io.inflight.indexOf(this)
    if (i === -1) return

    if (i === this._io.inflight.length - 1) this._io.inflight.pop()
    else this._io.inflight[i] = this._io.inflight.pop()

    if (this.session) this.session._detach(this)

    this._io.stats.requests.active--
    this._io.congestion.recv()

    this.onerror(err || REQUEST_DESTROYED(), this)
  }

  _sendReply(error, value, token, hasCloserNodes, from, socket) {
    if (socket === null || this.destroyed) return

    const id = this._io.ephemeral === false && socket === this._io.serverSocket
    const closerNodes =
      this.target !== null && hasCloserNodes ? this._io.table.closest(this.target) : EMPTY_ARRAY
    const state = { start: 0, end: 1 + 1 + 6 + 2, buffer: null } // (type | version) + flags + to + tid

    if (id) state.end += 32
    if (token) state.end += 32
    if (closerNodes.length > 0) peer.ipv4Array.preencode(state, closerNodes)
    if (error > 0) c.uint.preencode(state, error)
    if (value) c.buffer.preencode(state, value)

    state.buffer = b4a.allocUnsafe(state.end)
    state.buffer[state.start++] = RESPONSE_ID
    state.buffer[state.start++] =
      (id ? 1 : 0) |
      (token ? 2 : 0) |
      (closerNodes.length > 0 ? 4 : 0) |
      (error > 0 ? 8 : 0) |
      (value ? 16 : 0)

    c.uint16.encode(state, this.tid)
    peer.ipv4.encode(state, from)

    if (id) c.fixed32.encode(state, this._io.table.id)
    if (token) c.fixed32.encode(state, this._io.token(from, 1))
    if (closerNodes.length > 0) peer.ipv4Array.encode(state, closerNodes)
    if (error > 0) c.uint.encode(state, error)
    if (value) c.buffer.encode(state, value)

    socket.trySend(state.buffer, from.port, from.host, this.ttl)
  }

  _encodeRequest(token, value, to, socket) {
    const id = this._io.ephemeral === false && socket === this._io.serverSocket
    const state = { start: 0, end: 1 + 1 + 6 + 2, buffer: null } // (type | version) + flags + to + tid

    if (id) state.end += 32
    if (token) state.end += 32

    c.uint.preencode(state, this.command)

    if (this.target) state.end += 32
    if (value) c.buffer.preencode(state, value)

    state.buffer = b4a.allocUnsafe(state.end)
    state.buffer[state.start++] = REQUEST_ID
    state.buffer[state.start++] =
      (id ? 1 : 0) |
      (token ? 2 : 0) |
      (this.internal ? 4 : 0) |
      (this.target ? 8 : 0) |
      (value ? 16 : 0)

    c.uint16.encode(state, this.tid)
    peer.ipv4.encode(state, to)

    if (id) c.fixed32.encode(state, this._io.table.id)
    if (token) c.fixed32.encode(state, token)

    c.uint.encode(state, this.command)

    if (this.target) c.fixed32.encode(state, this.target)
    if (value) c.buffer.encode(state, value)

    return state.buffer
  }
}

class CongestionWindow {
  constructor(maxWindow) {
    this._i = 0
    this._total = 0
    this._window = [0, 0, 0, 0]
    this._maxWindow = maxWindow
  }

  clear() {
    this._i = 0
    this._total = 0
    this._window = [0, 0, 0, 0]
  }

  isFull() {
    return this._total >= 2 * this._maxWindow || this._window[this._i] >= this._maxWindow
  }

  recv() {
    if (this._window[this._i] > 0) {
      this._window[this._i]--
      this._total--
    }
  }

  send() {
    this._total++
    this._window[this._i]++
  }

  drain() {
    this._i = (this._i + 1) & 3
    this._total -= this._window[this._i]
    this._window[this._i] = 0 // clear oldest
  }
}

function noop() {}

function oncycle(req) {
  req._timeout = null
  req.oncycle(req)
  if (req.sent > req.retries) {
    req._io.stats.requests.timeouts++
    req.destroy(REQUEST_TIMEOUT())
    req._io.ontimeout(req)
  } else {
    req._io.stats.requests.retries++
    req.send()
  }
}

function decodeReply(from, state) {
  try {
    const flags = c.uint.decode(state)
    const tid = c.uint16.decode(state)
    const to = peer.ipv4.decode(state)
    const id = flags & 1 ? c.fixed32.decode(state) : null
    const token = flags & 2 ? c.fixed32.decode(state) : null
    const closerNodes = flags & 4 ? peer.ipv4Array.decode(state) : null
    const error = flags & 8 ? c.uint.decode(state) : 0
    const value = flags & 16 ? c.buffer.decode(state) : null

    if (id !== null) from.id = validateId(id, from)

    return { tid, rtt: 0, from, to, token, closerNodes, error, value }
  } catch {
    return null
  }
}

function validateId(id, from) {
  const expected = peer.id(from.host, from.port)
  return b4a.equals(expected, id) ? expected : null
}
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const b4a = require('b4a')

const ipv4 = {
  ...c.ipv4Address,
  decode(state) {
    const ip = c.ipv4Address.decode(state)
    return {
      id: null, // populated by the callee
      host: ip.host,
      port: ip.port
    }
  }
}

module.exports = { id, ipv4, ipv4Array: c.array(ipv4) }

function id(host, port, out = b4a.allocUnsafeSlow(32)) {
  const addr = out.subarray(0, 6)
  ipv4.encode({ start: 0, end: 6, buffer: addr }, { host, port })
  sodium.crypto_generichash(out, addr)
  return out
}
const { Readable, getStreamError } = require('streamx')
const b4a = require('b4a')
const peer = require('./peer')
const { DOWN_HINT } = require('./commands')

const DONE = []
const DOWN = []

module.exports = class Query extends Readable {
  constructor(dht, target, internal, command, value, opts = {}) {
    super()

    dht.stats.queries.total++
    dht.stats.queries.active++

    this.force = !!opts.force
    this.dht = dht
    this.k = this.dht.table.k
    this.target = target
    this.internal = internal
    this.command = command
    this.value = value
    this.errors = 0
    this.successes = 0
    this.concurrency = opts.concurrency || this.dht.concurrency
    this.inflight = 0
    this.map = opts.map || defaultMap
    this.retries =
      opts.retries === 0 ? 0 : opts.retries || (this.internal && command === DOWN_HINT ? 3 : 5)
    this.closestReplies = []

    this._slow = 0
    this._slowdown = false
    this._seen = new Map()
    this._pending = []
    this._fromTable = false
    this._commit = opts.commit === true ? autoCommit : opts.commit || null
    this._commiting = false
    this._session = opts.session || dht.session()
    this._autoDestroySession = !opts.session
    this._onlyClosestNodes = false

    this._onvisitbound = this._onvisit.bind(this)
    this._onerrorbound = this._onerror.bind(this)
    this._oncyclebound = this._oncycle.bind(this)

    const nodes = opts.nodes || opts.closestNodes
    const replies = opts.replies || opts.closestReplies

    // add them reverse as we pop below
    if (nodes) {
      for (let i = nodes.length - 1; i >= 0; i--) {
        const node = nodes[i]
        this._addPending(
          {
            id: node.id || peer.id(node.host, node.port),
            host: node.host,
            port: node.port
          },
          null
        )
      }
    } else if (replies) {
      for (let i = replies.length - 1; i >= 0; i--) {
        this._addPending(replies[i].from, null)
      }
    }

    if (opts.onlyClosestNodes) this._onlyClosestNodes = true
  }

  get closestNodes() {
    const nodes = new Array(this.closestReplies.length)

    for (let i = 0; i < nodes.length; i++) {
      nodes[i] = this.closestReplies[i].from
    }

    return nodes
  }

  finished() {
    return new Promise((resolve, reject) => {
      if (this.destroyed) {
        const error = getStreamError(this)
        if (error) reject(error)
        else resolve()
        return
      }

      const self = this
      let error = null

      this.resume()
      this.on('error', onerror)
      this.on('close', onclose)

      function onclose() {
        self.removeListener('error', onerror)
        self.removeListener('close', onclose)
        if (error) reject(error)
        else resolve()
      }

      function onerror(err) {
        error = err
      }
    })
  }

  _addFromTable() {
    if (this._pending.length >= this.k) return
    this._fromTable = true

    const closest = this.dht.table.closest(this.target, this.k - this._pending.length)

    for (const node of closest) {
      this._addPending({ id: node.id, host: node.host, port: node.port }, null)
    }
  }

  async _open(cb) {
    this._addFromTable()
    if (this._pending.length >= this.k) return cb(null)

    for await (const node of this.dht._resolveBootstrapNodes()) {
      this._addPending(node, null)
    }

    cb(null)
  }

  _isCloser(id) {
    return (
      this.closestReplies.length < this.k ||
      this._compare(id, this.closestReplies[this.closestReplies.length - 1].from.id) < 0
    )
  }

  _addPending(node, ref) {
    if (this._onlyClosestNodes) return false

    const addr = node.host + ':' + node.port
    const refs = this._seen.get(addr)
    const isCloser = this._isCloser(node.id)

    if (refs === DONE) {
      return isCloser
    }

    if (refs === DOWN) {
      if (ref) this._downHint(ref, node)
      return isCloser
    }

    if (refs) {
      if (ref !== null) refs.push(ref)
      return isCloser
    }

    if (!isCloser) {
      return false
    }

    this._seen.set(addr, ref === null ? [] : [ref])
    this._pending.push(node)

    return true
  }

  _read(cb) {
    this._readMore()
    cb(null)
  }

  _readMore() {
    if (this.destroying || this._commiting) return

    const concurrency = (this._slowdown ? 3 : this.concurrency) + this._slow

    while (this.inflight < concurrency && this._pending.length > 0) {
      const next = this._pending.pop()
      if (next && next.id && !this._isCloser(next.id)) continue
      this._visit(next)
    }

    // if reusing closest nodes, slow down after the first readMore tick to allow
    // the closest node a chance to reply before going broad to question more
    if (!this._fromTable && this.successes === 0 && this.errors === 0) {
      this._slowdown = true
    }

    if (this._pending.length > 0) return

    // if no inflight OR all the queries we are waiting on are marked as slow and we have a full result.
    if (
      this.inflight === 0 ||
      (this._slow === this.inflight && this.closestReplies.length >= this.k)
    ) {
      // if more than 3/4 failed and we only used cached nodes, try again from the routing table
      if (!this._fromTable && this.successes < this.k / 4) {
        this._addFromTable()
        this._readMore()
        return
      }

      this._flush()
    }
  }

  _flush() {
    if (this._commiting) return
    this._commiting = true

    if (this._commit === null) {
      this.push(null)
      return
    }

    const p = []
    for (const m of this.closestReplies) p.push(this._commit(m, this.dht, this))
    this._endAfterCommit(p)
  }

  _endAfterCommit(ps) {
    if (!ps.length) {
      this.destroy(new Error('Too few nodes responded'))
      return
    }

    const self = this

    let pending = ps.length
    let success = 0

    for (const p of ps) p.then(ondone, onerror)

    function ondone() {
      success++
      if (--pending === 0) self.push(null)
    }

    function onerror(err) {
      if (--pending > 0) return
      if (success) self.push(null)
      else self.destroy(err)
    }
  }

  _dec(req) {
    if (req.oncycle === noop) {
      this._slow--
    } else {
      req.oncycle = noop
    }
    this.inflight--
  }

  _onvisit(m, req) {
    this._dec(req)

    const addr = req.to.host + ':' + req.to.port
    this._seen.set(addr, DONE)

    if (this._commiting) return

    if (m.error === 0) this.successes++
    else this.errors++

    if (m.error === 0 && m.from.id !== null && this._isCloser(m.from.id)) this._pushClosest(m)

    if (m.closerNodes !== null) {
      for (const node of m.closerNodes) {
        node.id = peer.id(node.host, node.port)
        if (this.dht._filterNode !== null && !this.dht._filterNode(node)) continue
        if (b4a.equals(node.id, this.dht.table.id)) continue
        // TODO: we could continue here instead of breaking to ensure that one of the nodes in the closer list
        // is later marked as DOWN that we gossip that back
        if (!this._addPending(node, m.from)) break
      }
    }

    if (!this._fromTable && this.successes + this.errors >= this.concurrency) {
      this._slowdown = false
    }

    if (m.error !== 0) {
      this._readMore()
      return
    }

    const data = this.map(m)
    if (!data || this.push(data) !== false) {
      this._readMore()
    }
  }

  _onerror(err, req) {
    const addr = req.to.host + ':' + req.to.port
    const refs = this._seen.get(addr)

    if (err.code === 'REQUEST_TIMEOUT') {
      this._seen.set(addr, DOWN)
      for (const node of refs) this._downHint(node, req.to)
    }

    this._dec(req)
    this.errors++
    this._readMore()
  }

  _oncycle(req) {
    req.oncycle = noop
    this._slow++
    this._readMore()
  }

  _downHint(node, down) {
    // Check rate limit
    if (
      this.dht._downHintsRateLimit !== -1 &&
      this.dht._downHintsSentPerTick >= this.dht._downHintsRateLimit
    ) {
      return null
    }

    this.dht._downHintsSentPerTick++

    const state = { start: 0, end: 6, buffer: b4a.allocUnsafe(6) }
    peer.ipv4.encode(state, down)
    this.dht._request(node, false, true, DOWN_HINT, null, state.buffer, this._session, noop, noop)
  }

  _pushClosest(m) {
    this.closestReplies.push(m)
    for (let i = this.closestReplies.length - 2; i >= 0; i--) {
      const prev = this.closestReplies[i]
      const cmp = this._compare(prev.from.id, m.from.id)
      // if sorted, done!
      if (cmp < 0) break
      // if dup, splice it out (rare)
      if (cmp === 0) {
        this.closestReplies.splice(i + 1, 1)
        break
      }
      // swap and continue down
      this.closestReplies[i + 1] = prev
      this.closestReplies[i] = m
    }
    if (this.closestReplies.length > this.k) this.closestReplies.pop()
  }

  _compare(a, b) {
    for (let i = 0; i < a.length; i++) {
      if (a[i] === b[i]) continue
      const t = this.target[i]
      return (t ^ a[i]) - (t ^ b[i])
    }
    return 0
  }

  _visit(to) {
    this.inflight++

    const req = this.dht._request(
      to,
      this.force,
      this.internal,
      this.command,
      this.target,
      this.value,
      this._session,
      this._onvisitbound,
      this._onerrorbound
    )
    if (req === null) {
      this.destroy(new Error('Node was destroyed'))
      return
    }
    req.retries = this.retries
    req.oncycle = this._oncyclebound
    if (this.force) req.retries = 0
  }

  _destroy(cb) {
    this.dht.stats.queries.active--
    if (this._autoDestroySession) this._session.destroy()
    cb(null)
  }
}

function autoCommit(reply, dht, query) {
  if (!reply.token) return Promise.reject(new Error('No token received for closest node'))
  return dht.request(
    {
      token: reply.token,
      target: query.target,
      command: query.command,
      value: query.value
    },
    reply.from
  )
}

function defaultMap(m) {
  return m
}

function noop() {}
module.exports = class Session {
  constructor(dht) {
    this.dht = dht
    this.inflight = []
  }

  _attach(req) {
    req.index = this.inflight.push(req) - 1
  }

  _detach(req) {
    const i = req.index
    if (i === -1) return
    req.index = -1

    if (i === this.inflight.length - 1) this.inflight.pop()
    else {
      const req = (this.inflight[i] = this.inflight.pop())
      req.index = i
    }
  }

  query({ target, command, value }, opts = {}) {
    return this.dht.query({ target, command, value }, { ...opts, session: this })
  }

  request({ token, command, target, value }, { host, port }, opts = {}) {
    return this.dht.request(
      { token, command, target, value },
      { host, port },
      { ...opts, session: this }
    )
  }

  ping({ host, port }, opts = {}) {
    return this.dht.ping({ host, port }, { ...opts, session: this })
  }

  destroy(err) {
    while (this.inflight.length) {
      const req = this.inflight[0]
      // prevent destroyed requests from contributing to congestion counts
      this.dht.io.congestion.recv()
      req.destroy(err)
    }
  }
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "dht-rpc",
  "version": "6.27.0",
  "description": "Make RPC calls over a Kademlia based DHT",
  "main": "index.js",
  "files": [
    "index.js",
    "lib/*.js"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "dependencies": {
    "adaptive-timeout": "^1.0.1",
    "b4a": "^1.6.1",
    "bare-events": "^2.2.0",
    "compact-encoding": "^3.0.0",
    "compact-encoding-net": "^1.2.0",
    "fast-fifo": "^1.1.0",
    "kademlia-routing-table": "^1.0.1",
    "nat-sampler": "^1.0.1",
    "sodium-universal": "^5.0.0",
    "streamx": "^2.13.2",
    "time-ordered-set": "^2.0.0",
    "udx-native": "^1.5.3"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "test-suspend": "^1.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "test": "npm run test:node && npm run test:bare",
    "test:bare": "brittle-bare --coverage test.js",
    "lint": "prettier --check . && lunte",
    "test:node": "brittle-node --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/dht-rpc.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/dht-rpc/issues"
  },
  "homepage": "https://github.com/holepunchto/dht-rpc#"
}
module.exports = require('bare-events')
{
  "name": "events-universal",
  "version": "1.0.1",
  "description": "Universal wrapper for the Node.js events module",
  "exports": {
    "./package": "./package.json",
    ".": {
      "bare": "./bare.js",
      "react-native": "./react-native.js",
      "default": "./default.js"
    }
  },
  "files": [
    "index.js",
    "default.js",
    "bare.js",
    "react-native.js"
  ],
  "scripts": {
    "test": "prettier . --check"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/events-universal.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/events-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/events-universal#readme",
  "dependencies": {
    "bare-events": "^2.7.0"
  },
  "devDependencies": {
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^1.0.0"
  }
}
module.exports = class FixedFIFO {
  constructor (hwm) {
    if (!(hwm > 0) || ((hwm - 1) & hwm) !== 0) throw new Error('Max size for a FixedFIFO should be a power of two')
    this.buffer = new Array(hwm)
    this.mask = hwm - 1
    this.top = 0
    this.btm = 0
    this.next = null
  }

  clear () {
    this.top = this.btm = 0
    this.next = null
    this.buffer.fill(undefined)
  }

  push (data) {
    if (this.buffer[this.top] !== undefined) return false
    this.buffer[this.top] = data
    this.top = (this.top + 1) & this.mask
    return true
  }

  shift () {
    const last = this.buffer[this.btm]
    if (last === undefined) return undefined
    this.buffer[this.btm] = undefined
    this.btm = (this.btm + 1) & this.mask
    return last
  }

  peek () {
    return this.buffer[this.btm]
  }

  isEmpty () {
    return this.buffer[this.btm] === undefined
  }
}
const FixedFIFO = require('./fixed-size')

module.exports = class FastFIFO {
  constructor (hwm) {
    this.hwm = hwm || 16
    this.head = new FixedFIFO(this.hwm)
    this.tail = this.head
    this.length = 0
  }

  clear () {
    this.head = this.tail
    this.head.clear()
    this.length = 0
  }

  push (val) {
    this.length++
    if (!this.head.push(val)) {
      const prev = this.head
      this.head = prev.next = new FixedFIFO(2 * this.head.buffer.length)
      this.head.push(val)
    }
  }

  shift () {
    if (this.length !== 0) this.length--
    const val = this.tail.shift()
    if (val === undefined && this.tail.next) {
      const next = this.tail.next
      this.tail.next = null
      this.tail = next
      return this.tail.shift()
    }

    return val
  }

  peek () {
    const val = this.tail.peek()
    if (val === undefined && this.tail.next) return this.tail.next.peek()
    return val
  }

  isEmpty () {
    return this.length === 0
  }
}
{
  "name": "fast-fifo",
  "version": "1.3.2",
  "description": "A fast fifo implementation similar to the one powering nextTick in Node.js core",
  "main": "index.js",
  "files": [
    "./index.js",
    "./fixed-size.js"
  ],
  "dependencies": {},
  "devDependencies": {
    "standard": "^17.1.0",
    "brittle": "^3.3.2"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/fast-fifo.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/fast-fifo/issues"
  },
  "homepage": "https://github.com/mafintosh/fast-fifo"
}
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const b4a = require('b4a')

// https://en.wikipedia.org/wiki/Merkle_tree#Second_preimage_attack
const LEAF_TYPE = b4a.from([0])
const PARENT_TYPE = b4a.from([1])
const ROOT_TYPE = b4a.from([2])

const HYPERCORE = b4a.from('hypercore')

exports.keyPair = function (seed) {
  // key pairs might stay around for a while, so better not to use a default slab to avoid retaining it completely
  const slab = b4a.allocUnsafeSlow(
    sodium.crypto_sign_PUBLICKEYBYTES + sodium.crypto_sign_SECRETKEYBYTES
  )
  const publicKey = slab.subarray(0, sodium.crypto_sign_PUBLICKEYBYTES)
  const secretKey = slab.subarray(sodium.crypto_sign_PUBLICKEYBYTES)

  if (seed) sodium.crypto_sign_seed_keypair(publicKey, secretKey, seed)
  else sodium.crypto_sign_keypair(publicKey, secretKey)

  return {
    publicKey,
    secretKey
  }
}

exports.validateKeyPair = function (keyPair) {
  const pk = b4a.allocUnsafe(sodium.crypto_sign_PUBLICKEYBYTES)
  sodium.crypto_sign_ed25519_sk_to_pk(pk, keyPair.secretKey)
  return b4a.equals(pk, keyPair.publicKey)
}

exports.sign = function (message, secretKey) {
  // Dedicated slab for the signature, to avoid retaining unneeded mem and for security
  const signature = b4a.allocUnsafeSlow(sodium.crypto_sign_BYTES)
  sodium.crypto_sign_detached(signature, message, secretKey)
  return signature
}

exports.verify = function (message, signature, publicKey) {
  if (signature.byteLength !== sodium.crypto_sign_BYTES) return false
  if (publicKey.byteLength !== sodium.crypto_sign_PUBLICKEYBYTES) return false
  return sodium.crypto_sign_verify_detached(signature, message, publicKey)
}

exports.encrypt = function (message, publicKey) {
  const ciphertext = b4a.alloc(message.byteLength + sodium.crypto_box_SEALBYTES)
  sodium.crypto_box_seal(ciphertext, message, publicKey)
  return ciphertext
}

exports.decrypt = function (ciphertext, keyPair) {
  if (ciphertext.byteLength < sodium.crypto_box_SEALBYTES) return null

  const plaintext = b4a.alloc(ciphertext.byteLength - sodium.crypto_box_SEALBYTES)

  if (!sodium.crypto_box_seal_open(plaintext, ciphertext, keyPair.publicKey, keyPair.secretKey)) {
    return null
  }

  return plaintext
}

exports.encryptionKeyPair = function (seed) {
  const publicKey = b4a.alloc(sodium.crypto_box_PUBLICKEYBYTES)
  const secretKey = b4a.alloc(sodium.crypto_box_SECRETKEYBYTES)

  if (seed) {
    sodium.crypto_box_seed_keypair(publicKey, secretKey, seed)
  } else {
    sodium.crypto_box_keypair(publicKey, secretKey)
  }

  return {
    publicKey,
    secretKey
  }
}

exports.data = function (data) {
  const out = b4a.allocUnsafe(32)

  sodium.crypto_generichash_batch(out, [LEAF_TYPE, c.encode(c.uint64, data.byteLength), data])

  return out
}

exports.parent = function (a, b) {
  if (a.index > b.index) {
    const tmp = a
    a = b
    b = tmp
  }

  const out = b4a.allocUnsafe(32)

  sodium.crypto_generichash_batch(out, [
    PARENT_TYPE,
    c.encode(c.uint64, a.size + b.size),
    a.hash,
    b.hash
  ])

  return out
}

exports.tree = function (roots, out) {
  const buffers = new Array(3 * roots.length + 1)
  let j = 0

  buffers[j++] = ROOT_TYPE

  for (let i = 0; i < roots.length; i++) {
    const r = roots[i]
    buffers[j++] = r.hash
    buffers[j++] = c.encode(c.uint64, r.index)
    buffers[j++] = c.encode(c.uint64, r.size)
  }

  if (!out) out = b4a.allocUnsafe(32)
  sodium.crypto_generichash_batch(out, buffers)
  return out
}

exports.hash = function (data, out) {
  if (!out) out = b4a.allocUnsafe(32)
  if (!Array.isArray(data)) data = [data]

  sodium.crypto_generichash_batch(out, data)

  return out
}

exports.randomBytes = function (n) {
  const buf = b4a.allocUnsafe(n)
  sodium.randombytes_buf(buf)
  return buf
}

exports.discoveryKey = function (key) {
  if (!key || key.byteLength !== 32) throw new Error('Must pass a 32 byte buffer')
  // Discovery keys might stay around for a while, so better not to use slab memory (for better gc)
  const digest = b4a.allocUnsafeSlow(32)
  sodium.crypto_generichash(digest, HYPERCORE, key)
  return digest
}

if (sodium.sodium_free) {
  exports.free = function (secureBuf) {
    if (secureBuf.secure) sodium.sodium_free(secureBuf)
  }
} else {
  exports.free = function () {}
}

exports.namespace = function (name, count) {
  const ids = typeof count === 'number' ? range(count) : count

  // Namespaces are long-lived, so better to use a dedicated slab
  const buf = b4a.allocUnsafeSlow(32 * ids.length)

  const list = new Array(ids.length)

  // ns is ephemeral, so default slab
  const ns = b4a.allocUnsafe(33)
  sodium.crypto_generichash(ns.subarray(0, 32), typeof name === 'string' ? b4a.from(name) : name)

  for (let i = 0; i < list.length; i++) {
    list[i] = buf.subarray(32 * i, 32 * i + 32)
    ns[32] = ids[i]
    sodium.crypto_generichash(list[i], ns)
  }

  return list
}

function range(count) {
  const arr = new Array(count)
  for (let i = 0; i < count; i++) arr[i] = i
  return arr
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "hypercore-crypto",
  "version": "3.7.0",
  "description": "The crypto primitives used in hypercore, extracted into a separate module",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.6.6",
    "compact-encoding": "^3.0.0",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "brittle": "^3.5.0",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/hypercore-crypto.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/hypercore-crypto/issues"
  },
  "homepage": "https://github.com/mafintosh/hypercore-crypto"
}
const z32 = require('z32')
const b4a = require('b4a')

module.exports = {
  encode,
  decode,
  normalize,
  isValid
}

function encode (key) {
  if (!b4a.isBuffer(key)) throw new Error('Key must be a Buffer')
  if (key.byteLength !== 32) throw new Error('Key must be 32-bytes long')
  return z32.encode(key)
}

function decode (id) {
  if (b4a.isBuffer(id)) {
    if (id.byteLength !== 32) throw new Error('ID must be 32-bytes long')
    return id
  }
  if (typeof id === 'string') {
    if (id.startsWith('pear://')) id = id.slice(7).split('/')[0]
    if (id.length === 52) return z32.decode(id)
    if (id.length === 64) {
      const buf = b4a.from(id, 'hex')
      if (buf.byteLength === 32) return buf
    }
  }
  throw new Error('Invalid Hypercore key')
}

function normalize (any) {
  return encode(decode(any))
}

function isValid (any) {
  try {
    decode(any)
    return true
  } catch {
    return false
  }
}
{
  "name": "hypercore-id-encoding",
  "version": "1.3.0",
  "description": "Convert Hypercore keys to/from z-base32 or hex",
  "main": "index.js",
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.5.3",
    "z32": "^1.0.0"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "hypercore": "^10.0.0",
    "random-access-memory": "^6.0.0",
    "standard": "^17.1.0"
  },
  "license": "Apache-2.0",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/hypercore-id-encoding.git"
  },
  "keywords": [],
  "author": "",
  "bugs": {
    "url": "https://github.com/holepunchto/hypercore-id-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/hypercore-id-encoding#readme"
}
const c = require('compact-encoding')
const { getEncoding } = require('./spec/hyperschema')

const HyperdhtAddress = getEncoding('@hyperdht/address')

function decode(buf) {
  const addr = c.decode(HyperdhtAddress, buf)
  return addr
}

function encode(key, nodes) {
  return c.encode(HyperdhtAddress, { key, nodes })
}

module.exports = { decode, encode }
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "hyperdht-address",
  "version": "1.1.1",
  "description": "hyperdht-address",
  "main": "index.js",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    }
  },
  "files": [
    "package.json",
    "index.js",
    "index.d.ts",
    "spec"
  ],
  "devDependencies": {
    "b4a": "^1.8.0",
    "brittle": "^3.19.0",
    "lunte": "^1.2.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && lunte && brittle-bare test/index.js",
    "lint": "lunte"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/hyperdht-address.git"
  },
  "author": "Holepunch Inc",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/hyperdht-address/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperdht-address",
  "dependencies": {
    "compact-encoding": "^3.0.0",
    "hyperschema": "^1.20.1"
  }
}
// This file is autogenerated by the hyperschema compiler
// Schema Version: 2
/* eslint-disable camelcase */
/* eslint-disable quotes */
/* eslint-disable space-before-function-paren */

const { c } = require('hyperschema/runtime')

const VERSION = 2

// eslint-disable-next-line no-unused-vars
let version = VERSION

// @hyperdht/address.nodes
const encoding0_1 = c.array(c.ipv4Address)

// @hyperdht/address
const encoding0 = {
  preencode(state, m) {
    c.fixed32.preencode(state, m.key)
    state.end++ // max flag is 1 so always one byte

    if (version >= 2 && m.nodes) encoding0_1.preencode(state, m.nodes)
  },
  encode(state, m) {
    const flags = version >= 2 && m.nodes ? 1 : 0

    c.fixed32.encode(state, m.key)
    c.uint.encode(state, flags)

    if (version >= 2 && m.nodes) encoding0_1.encode(state, m.nodes)
  },
  decode(state) {
    const r0 = c.fixed32.decode(state)
    const flags = state.start < state.end ? c.uint.decode(state) : 0

    return {
      key: r0,
      nodes: version >= 2 && (flags & 1) !== 0 ? encoding0_1.decode(state) : null
    }
  }
}

function setVersion(v) {
  version = v
}

function encode(name, value, v = VERSION) {
  version = v
  return c.encode(getEncoding(name), value)
}

function decode(name, buffer, v = VERSION) {
  version = v
  return c.decode(getEncoding(name), buffer)
}

function getEnum(name) {
  switch (name) {
    default:
      throw new Error('Enum not found ' + name)
  }
}

function getEncoding(name) {
  switch (name) {
    case '@hyperdht/address':
      return encoding0
    default:
      throw new Error('Encoder not found ' + name)
  }
}

function getStruct(name, v = VERSION) {
  const enc = getEncoding(name)
  return {
    preencode(state, m) {
      version = v
      enc.preencode(state, m)
    },
    encode(state, m) {
      version = v
      enc.encode(state, m)
    },
    decode(state) {
      version = v
      return enc.decode(state)
    }
  }
}

const resolveStruct = getStruct // compat

module.exports = {
  resolveStruct,
  getStruct,
  getEnum,
  getEncoding,
  encode,
  decode,
  setVersion,
  version
}
const DHT = require('dht-rpc')
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const b4a = require('b4a')
const safetyCatch = require('safety-catch')
const m = require('./lib/messages')
const SocketPool = require('./lib/socket-pool')
const Persistent = require('./lib/persistent')
const Router = require('./lib/router')
const Cache = require('xache')
const Server = require('./lib/server')
const connect = require('./lib/connect')
const { FIREWALL, BOOTSTRAP_NODES, COMMANDS } = require('./lib/constants')
const { hash, createKeyPair } = require('./lib/crypto')
const RawStreamSet = require('./lib/raw-stream-set')
const ConnectionPool = require('./lib/connection-pool')
const { STREAM_NOT_CONNECTED } = require('./lib/errors')

const DEFAULTS = {
  ...DHT.DEFAULTS,
  connectionKeepAlive: 5000,
  randomPunchInterval: 20000
}

class HyperDHT extends DHT {
  constructor(opts = {}) {
    const port = opts.port || 49737
    const bootstrap = opts.bootstrap || BOOTSTRAP_NODES
    const nodes = opts.nodes || []

    super({ ...opts, port, bootstrap, nodes, filterNode })

    const { router, relayAddresses, persistent } = defaultCacheOpts(opts)

    this.defaultKeyPair = opts.keyPair || createKeyPair(opts.seed)
    this.listening = new Set()
    this.connectionKeepAlive =
      opts.connectionKeepAlive === false
        ? 0
        : opts.connectionKeepAlive || DEFAULTS.connectionKeepAlive

    // stats is inherited from dht-rpc so fwd the ones from there
    this.stats = {
      punches: { consistent: 0, random: 0, open: 0 },
      relaying: { attempts: 0, successes: 0, aborts: 0 },
      ...this.stats
    }
    this.rawStreams = new RawStreamSet(this)
    this.plugins = new Map()

    this._router = new Router(this, router)
    this._socketPool = new SocketPool(this, opts.host || '0.0.0.0')
    this._persistent = null
    this._validatedLocalAddresses = new Map()
    this._relayAddressesCache = new Cache(relayAddresses)

    this._deferRandomPunch = !!opts.deferRandomPunch
    this._lastRandomPunch = this._deferRandomPunch ? Date.now() : 0
    this._connectable = true
    this._randomPunchInterval = opts.randomPunchInterval || DEFAULTS.randomPunchInterval // min 20s between random punches...
    this._randomPunches = 0
    this._randomPunchLimit = 1 // set to one for extra safety for now

    this.once('persistent', () => {
      this._persistent = new Persistent(this, persistent)
      for (const plugin of this.plugins.values()) plugin.onpersistent()
    })

    this.on('network-change', () => {
      for (const server of this.listening) server.refresh()
    })

    this.on('network-update', () => {
      if (!this.online) return
      for (const server of this.listening) server.notifyOnline()
    })
  }

  static DEFAULTS = DEFAULTS

  connect(remotePublicKey, opts) {
    return connect(this, remotePublicKey, opts)
  }

  createServer(opts, onconnection) {
    if (typeof opts === 'function') return this.createServer({}, opts)
    if (opts && opts.onconnection) onconnection = opts.onconnection
    const s = new Server(this, opts)
    if (onconnection) s.on('connection', onconnection)
    return s
  }

  pool() {
    return new ConnectionPool(this)
  }

  async resume({ log = noop } = {}) {
    if (this._deferRandomPunch) this._lastRandomPunch = Date.now()
    await super.resume({ log })
    const resuming = []
    for (const server of this.listening) resuming.push(server.resume())
    log('Resuming hyperdht servers')
    await Promise.allSettled(resuming)
    log('Done, hyperdht fully resumed')
  }

  async suspend({ log = noop } = {}) {
    this._connectable = false // just so nothing gets connected during suspension
    const suspending = []
    for (const server of this.listening) suspending.push(server.suspend())
    log('Suspending all hyperdht servers')
    await Promise.allSettled(suspending)
    log('Done, clearing all raw streams')
    await this.rawStreams.clear()
    log('Done, suspending dht-rpc')
    await super.suspend({ log })
    log('Done, clearing raw streams again')
    await this.rawStreams.clear()
    log('Done, hyperdht fully suspended')
    this._connectable = true
  }

  async destroy({ force = false } = {}) {
    if (!force) {
      const closing = []
      for (const server of this.listening) closing.push(server.close())
      await Promise.allSettled(closing)
    }
    this._router.destroy()
    if (this._persistent) this._persistent.destroy()
    for (const plugin of this.plugins.values()) plugin.destroy()
    await this.rawStreams.clear()
    await this._socketPool.destroy()
    await super.destroy()
  }

  async validateLocalAddresses(addresses) {
    const list = []
    const socks = []
    const waiting = []

    for (const addr of addresses) {
      const { host } = addr

      if (this._validatedLocalAddresses.has(host)) {
        if (await this._validatedLocalAddresses.get(host)) {
          list.push(addr)
        }
        continue
      }

      const sock = this.udx.createSocket()
      try {
        sock.bind(0, host)
      } catch {
        this._validatedLocalAddresses.set(host, Promise.resolve(false))
        continue
      }

      socks.push(sock)

      // semi terrible heuristic until we proper fix local connections by racing them to the remote...
      const promise = new Promise((resolve) => {
        sock.on('message', () => resolve(true))
        setTimeout(() => resolve(false), 500)
        sock.trySend(b4a.alloc(1), sock.address().port, addr.host)
      })

      this._validatedLocalAddresses.set(host, promise)
      waiting.push(addr)
    }

    for (const addr of waiting) {
      const { host } = addr
      if (this._validatedLocalAddresses.has(host)) {
        if (await this._validatedLocalAddresses.get(host)) {
          list.push(addr)
        }
        continue
      }
    }

    for (const sock of socks) await sock.close()

    return list
  }

  findPeer(publicKey, opts = {}) {
    const target = opts.hash === false ? publicKey : hash(publicKey)
    opts = { ...opts, map: mapFindPeer }
    return this.query({ target, command: COMMANDS.FIND_PEER, value: null }, opts)
  }

  lookup(target, opts = {}) {
    opts = { ...opts, map: mapLookup }
    return this.query({ target, command: COMMANDS.LOOKUP, value: null }, opts)
  }

  lookupAndUnannounce(target, keyPair, opts = {}) {
    const unannounces = []
    const dht = this
    const userCommit = opts.commit || noop
    const signUnannounce = opts.signUnannounce || Persistent.signUnannounce

    if (this._persistent !== null) {
      // unlink self
      this._persistent.unannounce(target, keyPair.publicKey)
    }

    opts = { ...opts, map, commit }
    return this.query({ target, command: COMMANDS.LOOKUP, value: null }, opts)

    async function commit(reply, dht, query) {
      await Promise.all(unannounces) // can never fail, caught below
      return userCommit(reply, dht, query)
    }

    function map(reply) {
      const data = mapLookup(reply)

      if (!data || !data.token) return data

      let found = data.peers.length >= 20
      for (let i = 0; !found && i < data.peers.length; i++) {
        found = b4a.equals(data.peers[i].publicKey, keyPair.publicKey)
      }

      if (!found) return data

      if (!data.from.id) return data

      unannounces.push(
        dht
          ._requestUnannounce(keyPair, dht, target, data.token, data.from, signUnannounce)
          .catch(safetyCatch)
      )

      return data
    }
  }

  unannounce(target, keyPair, opts = {}) {
    return this.lookupAndUnannounce(target, keyPair, opts).finished()
  }

  announce(target, keyPair, relayAddresses, opts = {}) {
    const signAnnounce = opts.signAnnounce || Persistent.signAnnounce
    const bump = opts.bump || 0

    opts = { ...opts, commit }

    return opts.clear ? this.lookupAndUnannounce(target, keyPair, opts) : this.lookup(target, opts)

    function commit(reply, dht) {
      return dht._requestAnnounce(
        keyPair,
        dht,
        target,
        reply.token,
        reply.from,
        relayAddresses,
        signAnnounce,
        bump
      )
    }
  }

  async immutableGet(target, opts = {}) {
    opts = { ...opts, map: mapImmutable }

    const query = this.query({ target, command: COMMANDS.IMMUTABLE_GET, value: null }, opts)
    const check = b4a.allocUnsafe(32)

    for await (const node of query) {
      const { value } = node
      sodium.crypto_generichash(check, value)
      if (b4a.equals(check, target)) return node
    }

    return null
  }

  async immutablePut(value, opts = {}) {
    const target = b4a.allocUnsafe(32)
    sodium.crypto_generichash(target, value)

    opts = {
      ...opts,
      map: mapImmutable,
      commit(reply, dht) {
        return dht.request(
          { token: reply.token, target, command: COMMANDS.IMMUTABLE_PUT, value },
          reply.from
        )
      }
    }

    const query = this.query({ target, command: COMMANDS.IMMUTABLE_GET, value: null }, opts)
    await query.finished()

    return { hash: target, closestNodes: query.closestNodes }
  }

  async mutableGet(publicKey, opts = {}) {
    let refresh = opts.refresh || null
    let signed = null
    let result = null

    opts = { ...opts, map: mapMutable, commit: refresh ? commit : null }

    const target = b4a.allocUnsafe(32)
    sodium.crypto_generichash(target, publicKey)

    const userSeq = opts.seq || 0
    const query = this.query(
      { target, command: COMMANDS.MUTABLE_GET, value: c.encode(c.uint, userSeq) },
      opts
    )
    const latest = opts.latest !== false

    for await (const node of query) {
      if (result && node.seq <= result.seq) continue
      if (
        node.seq < userSeq ||
        !Persistent.verifyMutable(node.signature, node.seq, node.value, publicKey)
      )
        continue
      if (!latest) return node
      if (!result || node.seq > result.seq) result = node
    }

    return result

    function commit(reply, dht) {
      if (!signed && result && refresh) {
        if (refresh(result)) {
          signed = c.encode(m.mutablePutRequest, {
            publicKey,
            seq: result.seq,
            value: result.value,
            signature: result.signature
          })
        } else {
          refresh = null
        }
      }

      return signed
        ? dht.request(
            { token: reply.token, target, command: COMMANDS.MUTABLE_PUT, value: signed },
            reply.from
          )
        : Promise.resolve(null)
    }
  }

  async mutablePut(keyPair, value, opts = {}) {
    const signMutable = opts.signMutable || Persistent.signMutable

    const target = b4a.allocUnsafe(32)
    sodium.crypto_generichash(target, keyPair.publicKey)

    const seq = opts.seq || 0
    const signature = await signMutable(seq, value, keyPair)

    const signed = c.encode(m.mutablePutRequest, {
      publicKey: keyPair.publicKey,
      seq,
      value,
      signature
    })

    opts = {
      ...opts,
      map: mapMutable,
      commit(reply, dht) {
        return dht.request(
          { token: reply.token, target, command: COMMANDS.MUTABLE_PUT, value: signed },
          reply.from
        )
      }
    }

    // use seq = 0, for the query part here, as we don't care about the actual values
    const query = this.query(
      { target, command: COMMANDS.MUTABLE_GET, value: c.encode(c.uint, 0) },
      opts
    )
    await query.finished()

    return { publicKey: keyPair.publicKey, closestNodes: query.closestNodes, seq, signature }
  }

  onrequest(req) {
    switch (req.command) {
      case COMMANDS.PEER_HANDSHAKE: {
        this._router.onpeerhandshake(req)
        return true
      }
      case COMMANDS.PEER_HOLEPUNCH: {
        this._router.onpeerholepunch(req)
        return true
      }
    }

    if (this._persistent === null || this.id === null) return false

    switch (req.command) {
      case COMMANDS.FIND_PEER: {
        this._persistent.onfindpeer(req)
        return true
      }
      case COMMANDS.LOOKUP: {
        this._persistent.onlookup(req)
        return true
      }
      case COMMANDS.ANNOUNCE: {
        this._persistent.onannounce(req)
        return true
      }
      case COMMANDS.UNANNOUNCE: {
        this._persistent.onunannounce(req)
        return true
      }
      case COMMANDS.MUTABLE_PUT: {
        this._persistent.onmutableput(req)
        return true
      }
      case COMMANDS.MUTABLE_GET: {
        this._persistent.onmutableget(req)
        return true
      }
      case COMMANDS.IMMUTABLE_PUT: {
        this._persistent.onimmutableput(req)
        return true
      }
      case COMMANDS.IMMUTABLE_GET: {
        this._persistent.onimmutableget(req)
        return true
      }
      case COMMANDS.PLUGIN: {
        this._persistent.onplugin(req)
        return true
      }
    }

    return false
  }

  static keyPair(seed) {
    return createKeyPair(seed)
  }

  static hash(data) {
    return hash(data)
  }

  static connectRawStream(encryptedStream, rawStream, remoteId) {
    const stream = encryptedStream.rawStream

    if (!stream.connected) throw STREAM_NOT_CONNECTED()

    rawStream.connect(stream.socket, remoteId, stream.remotePort, stream.remoteHost)
  }

  createRawStream(opts) {
    return this.rawStreams.add(opts)
  }

  async _requestAnnounce(keyPair, dht, target, token, from, relayAddresses, sign, bump) {
    const ann = {
      peer: {
        publicKey: keyPair.publicKey,
        relayAddresses: relayAddresses || []
      },
      refresh: null,
      signature: null,
      bump
    }

    ann.signature = await sign(target, token, from.id, ann, keyPair)

    const value = c.encode(m.announce, ann)

    return dht.request(
      {
        token,
        target,
        command: COMMANDS.ANNOUNCE,
        value
      },
      from
    )
  }

  async _requestUnannounce(keyPair, dht, target, token, from, sign) {
    const unann = {
      peer: {
        publicKey: keyPair.publicKey,
        relayAddresses: []
      },
      signature: null
    }

    unann.signature = await sign(target, token, from.id, unann, keyPair)

    const value = c.encode(m.announce, unann)

    return dht.request(
      {
        token,
        target,
        command: COMMANDS.UNANNOUNCE,
        value
      },
      from
    )
  }

  register(name, plugin) {
    this.plugins.set(name, plugin)
    plugin.onregister(this)
  }
}

HyperDHT.BOOTSTRAP = BOOTSTRAP_NODES
HyperDHT.FIREWALL = FIREWALL

module.exports = HyperDHT

function mapLookup(node) {
  if (!node.value) return null

  try {
    const l = c.decode(m.lookupRawReply, node.value)

    return {
      token: node.token,
      from: node.from,
      to: node.to,
      peers: l.peers,
      bump: l.bump
    }
  } catch {
    return null
  }
}

function mapFindPeer(node) {
  if (!node.value) return null

  try {
    return {
      token: node.token,
      from: node.from,
      to: node.to,
      peer: c.decode(m.peer, node.value)
    }
  } catch {
    return null
  }
}

function mapImmutable(node) {
  if (!node.value) return null

  return {
    token: node.token,
    from: node.from,
    to: node.to,
    value: node.value
  }
}

function mapMutable(node) {
  if (!node.value) return null

  try {
    const { seq, value, signature } = c.decode(m.mutableGetResponse, node.value)

    return {
      token: node.token,
      from: node.from,
      to: node.to,
      seq,
      value,
      signature
    }
  } catch {
    return null
  }
}

function noop() {}

function filterNode(node) {
  // always skip these testnet nodes that got mixed in by accident, until they get updated
  return (
    !(node.port === 49738 && (node.host === '134.209.28.98' || node.host === '167.99.142.185')) &&
    !(node.port === 9400 && node.host === '35.233.47.252') &&
    !(node.host === '150.136.142.116')
  )
}

const defaultMaxSize = 65536
const defaultMaxAge = 20 * 60 * 1000 // 20 minutes

function defaultCacheOpts(opts) {
  const maxSize = opts.maxSize || defaultMaxSize
  const maxAge = opts.maxAge || defaultMaxAge

  return {
    router: {
      forwards: { maxSize, maxAge }
    },
    relayAddresses: { maxSize: Math.min(maxSize, 512), maxAge: 0 },
    persistent: {
      records: { maxSize, maxAge },
      refreshes: { maxSize, maxAge },
      mutables: {
        maxSize: (maxSize / 2) | 0,
        maxAge: opts.maxAge || 48 * 60 * 60 * 1000 // 48 hours
      },
      immutables: {
        maxSize: (maxSize / 2) | 0,
        maxAge: opts.maxAge || 48 * 60 * 60 * 1000 // 48 hours
      },
      bumps: { maxSize, maxAge }
    }
  }
}
const safetyCatch = require('safety-catch')
const c = require('compact-encoding')
const Signal = require('signal-promise')
const { encodeUnslab } = require('./encode')
const Sleeper = require('./sleeper')
const m = require('./messages')
const Persistent = require('./persistent')
const { COMMANDS } = require('./constants')

const MIN_ACTIVE = 3

module.exports = class Announcer {
  constructor(dht, keyPair, target, opts = {}) {
    this.dht = dht
    this.keyPair = keyPair
    this.target = target
    this.relays = []
    this.relayAddresses = []
    this.stopped = false
    this.suspended = false
    this.record = encodeUnslab(m.peer, { publicKey: keyPair.publicKey, relayAddresses: [] })
    this.online = new Signal()

    this._refreshing = false
    this._closestNodes = null
    this._active = null
    this._sleeper = new Sleeper()
    this._resumed = new Signal()
    this._signAnnounce = opts.signAnnounce || Persistent.signAnnounce
    this._signUnannounce = opts.signUnannounce || Persistent.signUnannounce
    this._updating = null
    this._activeQuery = null
    this._unannouncing = null

    this._serverRelays = [new Map(), new Map(), new Map()]
  }

  isRelay(addr) {
    const id = addr.host + ':' + addr.port
    const [a, b, c] = this._serverRelays
    return a.has(id) || b.has(id) || c.has(id)
  }

  async suspend({ log = noop } = {}) {
    if (this.suspended) return
    this.suspended = true

    log('Suspending announcer')

    // Suspend has its own sleep logic
    // so we don't want to hang on this one
    this.online.notify()

    if (this._activeQuery) this._activeQuery.destroy()

    this._sleeper.resume()
    if (this._updating) await this._updating
    log('Suspending announcer (post update)')

    if (this.suspended === false || this.stopped) return

    log('Suspending announcer (pre unannounce)')
    await this._unannounceCurrent()
    log('Suspending announcer (post unannounce)')
  }

  resume() {
    if (!this.suspended) return
    this.suspended = false

    this.refresh()
    this._sleeper.resume()
    this._resumed.notify()
  }

  refresh() {
    if (this.stopped) return
    this._refreshing = true
  }

  async start() {
    if (this.stopped) return
    this._active = this._runUpdate()
    await this._active
    if (this.stopped) return
    this._active = this._background()
  }

  async stop() {
    this.stopped = true
    this.online.notify() // Break out of the _background loop if we're offline
    this._sleeper.resume()
    this._resumed.notify()
    await this._active
    await this._unannounceCurrent()
  }

  async _unannounceCurrent() {
    while (this._unannouncing !== null) await this._unannouncing
    const un = (this._unannouncing = this._unannounceAll(this._serverRelays[2].values()))
    await this._unannouncing
    if (un === this._unannouncing) this._unannouncing = null
  }

  async _background() {
    while (!this.dht.destroyed && !this.stopped) {
      try {
        this._refreshing = false

        // ~5min +-
        for (let i = 0; i < 100 && !this.stopped && !this._refreshing && !this.suspended; i++) {
          const pings = []

          for (const node of this._serverRelays[2].values()) {
            pings.push(this.dht.ping(node))
          }

          const active = await resolved(pings)
          if (active < Math.min(pings.length, MIN_ACTIVE)) {
            this.refresh() // we lost too many relay nodes, retry all
          }

          if (this.stopped) return

          if (!this.suspended && !this._refreshing) await this._sleeper.pause(3000)
        }

        while (!this.stopped && this.suspended) await this._resumed.wait()

        if (!this.stopped) await this._runUpdate()

        while (!this.dht.online && !this.stopped && !this.suspended) {
          // Being offline can make _background repeat very quickly
          // So wait until we're back online
          await this.online.wait()
        }
      } catch (err) {
        safetyCatch(err)
      }
    }
  }

  async _runUpdate() {
    this._updating = this._update()
    await this._updating
    this._updating = null
  }

  async _update() {
    while (this._unannouncing) await this._unannouncing

    this._cycle()

    const q = (this._activeQuery = this.dht.findPeer(this.target, {
      hash: false,
      nodes: this._closestNodes
    }))

    try {
      await q.finished()
    } catch {
      // ignore failures...
    }

    this._activeQuery = null

    if (this.stopped || this.suspended) return

    const ann = []
    const replies = pickBest(q.closestReplies)

    const relays = []
    const relayAddresses = []

    if (!this.dht.firewalled) {
      const addr = this.dht.remoteAddress()
      if (addr) relayAddresses.push(addr)
    }

    for (const msg of replies) {
      ann.push(this._commit(msg, relays, relayAddresses))
    }

    await Promise.allSettled(ann)
    if (this.stopped || this.suspended) return

    this._closestNodes = q.closestNodes
    this.relays = relays
    this.relayAddresses = relayAddresses

    const removed = []
    for (const [key, value] of this._serverRelays[1]) {
      if (!this._serverRelays[2].has(key)) removed.push(value)
    }

    await this._unannounceAll(removed)
  }

  _unannounceAll(relays) {
    const unann = []
    for (const r of relays) unann.push(this._unannounce(r))
    return Promise.allSettled(unann)
  }

  async _unannounce(to) {
    const unann = {
      peer: {
        publicKey: this.keyPair.publicKey,
        relayAddresses: []
      },
      refresh: null,
      signature: null
    }

    const { from, token, value } = await this.dht.request(
      {
        token: null,
        command: COMMANDS.FIND_PEER,
        target: this.target,
        value: null
      },
      to
    )

    if (!token || !from.id || !value) return

    unann.signature = await this._signUnannounce(this.target, token, from.id, unann, this.keyPair)

    await this.dht.request(
      {
        token,
        command: COMMANDS.UNANNOUNCE,
        target: this.target,
        value: c.encode(m.announce, unann)
      },
      to
    )
  }

  async _commit(msg, relays, relayAddresses) {
    const ann = {
      peer: {
        publicKey: this.keyPair.publicKey,
        relayAddresses: []
      },
      refresh: null,
      signature: null
    }

    ann.signature = await this._signAnnounce(this.target, msg.token, msg.from.id, ann, this.keyPair)

    const res = await this.dht.request(
      {
        token: msg.token,
        command: COMMANDS.ANNOUNCE,
        target: this.target,
        value: c.encode(m.announce, ann)
      },
      msg.from
    )

    if (res.error !== 0) return

    if (relayAddresses.length < 3) relayAddresses.push({ host: msg.from.host, port: msg.from.port })
    relays.push({ relayAddress: msg.from, peerAddress: msg.to })

    this._serverRelays[2].set(msg.from.host + ':' + msg.from.port, msg.from)
  }

  _cycle() {
    const tmp = this._serverRelays[0]
    this._serverRelays[0] = this._serverRelays[1]
    this._serverRelays[1] = this._serverRelays[2]
    this._serverRelays[2] = tmp
    tmp.clear()
  }
}

function resolved(ps) {
  let replied = 0
  let ticks = ps.length + 1

  return new Promise((resolve) => {
    for (const p of ps) p.then(push, tick)
    tick()

    function push(v) {
      replied++
      tick()
    }

    function tick() {
      if (--ticks === 0) resolve(replied)
    }
  })
}

function pickBest(replies) {
  // TODO: pick the ones closest to us RTT wise
  return replies.slice(0, 3)
}

function noop() {}
const NoiseSecretStream = require('@hyperswarm/secret-stream')
const b4a = require('b4a')
const relay = require('blind-relay')
const { isReserved, isBogon } = require('bogon')
const safetyCatch = require('safety-catch')
const unslab = require('unslab')
const Semaphore = require('./semaphore')
const NoiseWrap = require('./noise-wrap')
const SecurePayload = require('./secure-payload')
const Holepuncher = require('./holepuncher')
const Sleeper = require('./sleeper')
const {
  clearRelayTimeout,
  confirmDirectUpgrade,
  destroyRelayConnection
} = require('./relay-connection')
const { FIREWALL, ERROR } = require('./constants')
const { unslabbedHash } = require('./crypto')
const {
  CANNOT_HOLEPUNCH,
  HANDSHAKE_INVALID,
  HOLEPUNCH_ABORTED,
  HOLEPUNCH_INVALID,
  HOLEPUNCH_PROBE_TIMEOUT,
  HOLEPUNCH_DOUBLE_RANDOMIZED_NATS,
  PEER_CONNECTION_FAILED,
  PEER_NOT_FOUND,
  REMOTE_ABORTED,
  REMOTE_NOT_HOLEPUNCHABLE,
  REMOTE_NOT_HOLEPUNCHING,
  SERVER_ERROR,
  SERVER_INCOMPATIBLE,
  RELAY_ABORTED,
  SUSPENDED
} = require('./errors')
const { decode } = require('hypercore-id-encoding')
const HyperDHTAddress = require('hyperdht-address')

module.exports = function connect(dht, publicKey, opts = {}) {
  const pool = opts.pool || null

  const { key, nodes: providedNodes } = HyperDHTAddress.decode(
    b4a.isBuffer(publicKey) ? publicKey : decode(publicKey)
  )
  publicKey = key

  if (pool && pool.has(publicKey)) return pool.get(publicKey)

  publicKey = unslab(publicKey)

  opts.relayAddresses = opts.relayAddresses || providedNodes || []
  const keyPair = opts.keyPair || dht.defaultKeyPair
  const relayThrough = selectRelay(opts.relayThrough || null)
  const encryptedSocket = (opts.createSecretStream || defaultCreateSecretStream)(true, null, {
    publicKey: keyPair.publicKey,
    remotePublicKey: publicKey,
    autoStart: false,
    keepAlive: dht.connectionKeepAlive
  })

  // in case a socket is made during suspended state, destroy it immediately
  if (dht.suspended || !dht._connectable) {
    encryptedSocket.destroy(SUSPENDED())
    return encryptedSocket
  }

  if (pool) pool._attachStream(encryptedSocket, false)

  const id = b4a.toString(publicKey, 'hex')
  const c = {
    id,
    dht,
    session: dht.session(),
    relayAddresses: opts.relayAddresses,
    remoteRelayAddresses: [],
    pool,
    round: 0,
    target: unslabbedHash(publicKey),
    remotePublicKey: publicKey,
    reusableSocket: !!opts.reusableSocket,
    handshake: (opts.createHandshake || defaultCreateHandshake)(keyPair, publicKey),
    request: null,
    requesting: false,
    lan: opts.localConnection !== false,
    firewall: FIREWALL.UNKNOWN,
    rawStream: dht.createRawStream({ framed: true, firewall }),
    connect: null,
    query: null,
    puncher: null,
    payload: null,
    passiveConnectTimeout: null,
    serverSocket: null,
    serverAddress: null,
    onsocket: null,
    sleeper: new Sleeper(),
    encryptedSocket,

    // Relay state
    relayTimeout: null,
    relayThrough,
    relayToken: relayThrough ? relay.token() : null,
    relaySocket: null,
    relayClient: null,
    relayPaired: false,
    validUpgrade: true,
    relayKeepAlive: opts.relayKeepAlive || 5000
  }

  // If the raw stream receives an error signal pre connect (ie from the firewall hook), make sure
  // to forward that to the encrypted socket for proper teardown
  c.rawStream.on('error', autoDestroy)
  c.rawStream.once('connect', () => {
    c.rawStream.removeListener('error', autoDestroy)
  })

  encryptedSocket.on('close', function () {
    if (c.passiveConnectTimeout) clearPassiveConnectTimeout(c)
    if (c.query) c.query.destroy()
    if (c.puncher) c.puncher.destroy()
    if (c.rawStream) c.rawStream.destroy()
    c.session.destroy()
    c.sleeper.resume()
  })

  // Safe to run in the background - never throws
  if (dht.suspended) encryptedSocket.destroy(SUSPENDED())
  else connectAndHolepunch(c, opts)

  return encryptedSocket

  function autoDestroy(err) {
    maybeDestroyEncryptedSocket(c, err)
  }

  function firewall(socket, port, host) {
    // Check if the traffic originated from the socket on which we're expecting relay traffic. If so,
    // we haven't hole punched yet and the other side is just sending us traffic through the relay.
    if (c.relaySocket && isRelay(c.relaySocket, socket, port, host)) {
      c.validUpgrade = false
      return false
    }

    c.validUpgrade = true
    if (c.onsocket) {
      c.onsocket(socket, port, host)
    } else {
      c.serverSocket = socket
      c.serverAddress = { port, host }
    }
    return false
  }
}

function isDone(c) {
  // we are destroying or the puncher is connected - done
  if (c.encryptedSocket.destroying || !!(c.puncher && c.puncher.connected)) {
    return true
  }
  // not destroying, but no raw stream - def not done
  if (c.encryptedSocket.rawStream === null) {
    return false
  }
  // we are relayed, but the puncher is not done yet
  if (c.relaySocket && !!(c.puncher && !c.puncher.connected && !c.puncher.destroyed)) {
    return false
  }
  // we are done
  return true
}

async function retryRoute(c, route) {
  const ref = c.dht._socketPool.lookup(route.socket)

  if (!ref) {
    if (route.socket === c.dht.socket) {
      await connectThroughNode(c, route.address, c.dht.socket)
    }
    return
  }

  ref.active()

  try {
    await connectThroughNode(c, route.address, route.socket)
  } catch {
    // if error, just ignore, and continue through the existing strat
  }

  ref.inactive()
}

async function connectAndHolepunch(c, opts) {
  const route = c.reusableSocket ? c.dht._socketPool.routes.get(c.remotePublicKey) : null

  if (route) {
    await retryRoute(c, route)
    if (isDone(c)) return
  }

  await findAndConnect(c, opts)
  if (isDone(c)) return

  if (!c.connect) {
    // TODO: just a quick fix for now, should retry prob
    maybeDestroyEncryptedSocket(c, HANDSHAKE_INVALID())
    return
  }

  await holepunch(c, opts)
}

function getFirstRemoteAddress(addrs, serverAddress) {
  for (const addr of addrs) {
    if (isBogon(addr.host)) continue
    return addr
  }

  return serverAddress
}

async function holepunch(c, opts) {
  let { relayAddress, serverAddress, clientAddress, payload } = c.connect

  const remoteHolepunchable = !!(payload.holepunch && payload.holepunch.relays.length)
  const relayed = diffAddress(serverAddress, relayAddress)

  if (payload.firewall === FIREWALL.OPEN || (relayed && !remoteHolepunchable)) {
    const addr = getFirstRemoteAddress(payload.addresses4, serverAddress)
    if (addr) {
      const socket = c.dht.socket
      c.dht.stats.punches.open++
      c.onsocket(socket, addr.port, addr.host)
      return
    }
    // TODO: check all addresses also obvs
  }

  const onabort = () => {
    c.session.destroy()
    maybeDestroyEncryptedSocket(c, HOLEPUNCH_ABORTED())
  }

  if (c.firewall === FIREWALL.OPEN) {
    c.passiveConnectTimeout = setTimeout(onabort, 10000)
    return
  }

  // Race the LAN shortcut with normal holepunch when possible. A blocked LAN ping
  // should not abort a connection that can still holepunch. If the remote is not
  // holepunchable, the LAN ping is the only remaining path.
  if (c.lan && relayed && clientAddress.host === serverAddress.host) {
    const serverAddresses = payload.addresses4.filter(onlyNonReserved)

    if (serverAddresses.length > 0) {
      const myAddresses = Holepuncher.localAddresses(c.dht.io.serverSocket)
      const addr = Holepuncher.matchAddress(myAddresses, serverAddresses) || serverAddresses[0]

      const socket = c.dht.io.serverSocket
      c.dht.ping(addr).then(onlanconnect, onlanerror)
      if (!remoteHolepunchable) return

      function onlanconnect() {
        // LAN and holepunch completions both converge through onsocket,
        // which claims c.rawStream once and ignores later winners.
        if (isDone(c)) return
        c.onsocket(socket, addr.port, addr.host)
      }

      function onlanerror() {
        if (!remoteHolepunchable) {
          maybeDestroyEncryptedSocket(c, HOLEPUNCH_ABORTED())
        }
      }
    }
  }

  if (!remoteHolepunchable) {
    maybeDestroyEncryptedSocket(c, CANNOT_HOLEPUNCH())
    return
  }

  c.puncher = new Holepuncher(c.dht, c.session, true, payload.firewall)

  c.puncher.onconnect = c.onsocket
  c.puncher.onabort = onabort

  const serverRelay = pickServerRelay(payload.holepunch.relays, relayAddress)

  // Begin holepunching!

  let probe
  try {
    probe = await probeRound(c, opts.fastOpen === false ? null : serverAddress, serverRelay, true)
  } catch (err) {
    destroyPuncher(c)
    // TODO: we should retry here with some of the other relays, bail for now
    maybeDestroyEncryptedSocket(c, err)
    return
  }

  if (isDone(c) || !probe) return
  const { token, peerAddress } = probe

  // If the relay the server picked is the same as the relay the client picked,
  // then we can use the peerAddress that round one indicates the server wants to use.
  // This shaves off a roundtrip if the server chose to reroll its socket due to some NAT
  // issue with the first one it picked (ie mobile nat inconsistencies...).
  // If the relays were different, then the server would not have a UDP session open on this address
  // to the client relay, which round2 uses.
  if (
    !diffAddress(serverRelay.relayAddress, relayAddress) &&
    diffAddress(serverAddress, peerAddress)
  ) {
    serverAddress = peerAddress
    await c.puncher.openSession(serverAddress)
    if (isDone(c)) return
  }

  // TODO: still continue here if a local connection might work, but then do not holepunch...
  if (
    opts.holepunch &&
    !opts.holepunch(
      c.puncher.remoteFirewall,
      c.puncher.nat.firewall,
      c.puncher.remoteAddresses,
      c.puncher.nat.addresses
    )
  ) {
    await abort(c, serverRelay, HOLEPUNCH_ABORTED('Client aborted holepunch'))
    return
  }

  try {
    await roundPunch(c, serverAddress, token, relayAddress, serverRelay, false)
  } catch (err) {
    destroyPuncher(c)
    // TODO: retry with another relay?
    maybeDestroyEncryptedSocket(c, err)
  }
}

async function connectThroughNodes(c, addresses, socket) {
  for (const address of addresses) {
    if (isDone(c) || c.connect) return

    c.remoteRelayAddresses.push(address)
    await connectThroughNode(c, address, socket)
  }
}

async function findAndConnect(c, opts) {
  let attempts = 0
  let relayAddresses =
    opts.relayAddresses && opts.relayAddresses.length ? opts.relayAddresses : null

  if (!relayAddresses) {
    const cachedRelayAddresses = c.dht._relayAddressesCache.get(c.id)
    if (cachedRelayAddresses) relayAddresses = cachedRelayAddresses
  }

  if (c.dht._persistent) {
    // check if we know the route ourself...
    const route = c.dht._router.get(c.target)
    if (route && route.relay !== null) {
      relayAddresses = [{ host: route.relay.host, port: route.relay.port }]
    }
  }

  // 2 is how many parallel connect attempts we want to do, we can make this configurable
  const preConnect = relayAddresses !== null && relayAddresses.length > 0
  const sem = new Semaphore(preConnect ? 3 : 2)
  const signal = sem.signal.bind(sem)
  const tries = relayAddresses !== null ? 2 : 1

  if (preConnect) {
    await sem.wait()
    connectThroughNodes(c, relayAddresses, null).then(signal, signal)
  }

  try {
    for (let i = 0; i < tries && !isDone(c) && !c.connect; i++) {
      c.query = c.dht.findPeer(c.target, {
        hash: false,
        session: c.session,
        nodes: relayAddresses,
        retries: 3
      })

      for await (const data of c.query) {
        await sem.wait()
        if (isDone(c)) return

        if (c.connect) {
          sem.signal()
          break
        }

        // Skip node already run via preConnect
        if (preConnect && relayAddresses && isRelayAddress(relayAddresses, data)) {
          sem.signal()
          continue
        }

        c.remoteRelayAddresses.push(data.from)
        attempts++
        connectThroughNode(c, data.from, null).then(signal, signal)
      }

      relayAddresses = null

      if (attempts > 0) await sem.flush()
    }

    c.query = null
    if (isDone(c)) return

    // flush the semaphore
    await sem.flush()
    if (isDone(c)) return
  } catch (err) {
    c.query = null
    maybeDestroyEncryptedSocket(c, err)
    return
  }

  if (!c.connect) {
    maybeDestroyEncryptedSocket(c, attempts ? PEER_CONNECTION_FAILED() : PEER_NOT_FOUND())
  }
}

async function connectThroughNode(c, address, socket) {
  if (!c.requesting) {
    // If we have a stable server address, send it over now
    const addr = c.dht.remoteAddress()
    const localAddrs = c.lan ? Holepuncher.localAddresses(c.dht.io.serverSocket) : null
    const addresses4 = []

    if (addr) addresses4.push(addr)
    if (localAddrs) addresses4.push(...localAddrs)

    c.firewall = addr ? FIREWALL.OPEN : FIREWALL.UNKNOWN
    c.requesting = true
    c.request = await c.handshake.send({
      error: ERROR.NONE,
      firewall: c.firewall,
      holepunch: null,
      addresses4,
      addresses6: [],
      udx: {
        reusableSocket: c.reusableSocket,
        id: c.rawStream.id,
        seq: 0
      },
      secretStream: {},
      relayThrough: c.relayThrough ? { publicKey: c.relayThrough, token: c.relayToken } : null
    })
    if (isDone(c)) return
  }

  const { serverAddress, clientAddress, relayed, noise } = await c.dht._router.peerHandshake(
    c.target,
    { noise: c.request, socket, session: c.session },
    address
  )
  if (isDone(c) || c.connect) return

  const payload = await c.handshake.recv(noise)
  if (isDone(c) || !payload) return

  if (payload.version !== 1) {
    maybeDestroyEncryptedSocket(c, SERVER_INCOMPATIBLE())
    return
  }
  if (payload.error !== ERROR.NONE) {
    maybeDestroyEncryptedSocket(c, SERVER_ERROR())
    return
  }
  if (!payload.udx) {
    maybeDestroyEncryptedSocket(c, SERVER_ERROR('Server did not send UDX data'))
    return
  }

  const hs = c.handshake.final()

  c.handshake = null
  c.request = null
  c.requesting = false
  c.connect = {
    relayed,
    relayAddress: address,
    clientAddress,
    serverAddress,
    payload
  }

  c.payload = new SecurePayload(hs.holepunchSecret)

  c.onsocket = function (socket, port, host) {
    if (c.rawStream === null) return // Already hole punched

    if (c.rawStream.connected) {
      const rawStream = c.rawStream
      const remoteChanging = rawStream.changeRemote(socket, c.connect.payload.udx.id, port, host)
      confirmDirectUpgrade(c, rawStream, remoteChanging)
    } else {
      // cache the relay addrs for a future reconnect, we prefer the remote one so they
      // can give us the correct ones from their pov
      if (payload.relayAddresses && payload.relayAddresses.length) {
        c.dht._relayAddressesCache.set(c.id, payload.relayAddresses)
      } else if (c.remoteRelayAddresses.length) {
        c.dht._relayAddressesCache.set(c.id, c.remoteRelayAddresses)
      }

      c.rawStream.connect(socket, c.connect.payload.udx.id, port, host)
      c.encryptedSocket.start(c.rawStream, { handshake: hs })
    }

    if (c.reusableSocket && payload.udx.reusableSocket) {
      c.dht._socketPool.routes.add(c.remotePublicKey, c.rawStream)
    }

    if (c.puncher) {
      c.puncher.onabort = noop
      c.puncher.destroy()
    }

    if (c.passiveConnectTimeout) {
      clearPassiveConnectTimeout(c)
    }

    c.rawStream = null
  }

  if (payload.relayThrough || c.relayThrough) {
    relayConnection(c, c.relayThrough, payload, hs)
  }

  if (c.serverSocket) {
    c.onsocket(c.serverSocket, c.serverAddress.port, c.serverAddress.host)
    return
  }

  if (!relayed) {
    c.onsocket(socket || c.dht.socket, address.port, address.host)
  }

  c.session.destroy()
}

async function updateHolepunch(c, peerAddress, relayAddr, payload) {
  const holepunch = await c.dht._router.peerHolepunch(
    c.target,
    {
      id: c.connect.payload.holepunch.id,
      payload: c.payload.encrypt(payload),
      peerAddress,
      socket: c.puncher.socket,
      session: c.session
    },
    relayAddr
  )

  if (isDone(c)) return null

  const remotePayload = c.payload.decrypt(holepunch.payload)
  if (!remotePayload) {
    throw HOLEPUNCH_INVALID()
  }

  const { error, firewall, punching, addresses, remoteToken } = remotePayload

  if (error === ERROR.TRY_LATER && c.relayToken && payload.punching) {
    return {
      tryLater: true,
      ...holepunch,
      payload: remotePayload
    }
  }

  if (error !== ERROR.NONE) {
    throw REMOTE_ABORTED('Remote aborted with error code ' + error)
  }

  const echoed = !!(remoteToken && payload.token && b4a.equals(remoteToken, payload.token))

  c.puncher.updateRemote({
    punching,
    firewall,
    addresses,
    verified: echoed ? peerAddress.host : null
  })

  return {
    tryLater: false,
    ...holepunch,
    payload: remotePayload
  }
}

async function probeRound(c, serverAddress, serverRelay, retry) {
  // Open a quick low ttl session against what we think is the server
  if (serverAddress) await c.puncher.openSession(serverAddress)

  if (isDone(c)) return null

  const reply = await updateHolepunch(c, serverRelay.peerAddress, serverRelay.relayAddress, {
    error: ERROR.NONE,
    firewall: c.puncher.nat.firewall,
    round: c.round++,
    connected: false,
    punching: false,
    addresses: c.puncher.nat.addresses,
    remoteAddress: serverAddress,
    token: null,
    remoteToken: null
  })

  if (isDone(c) || !reply) return null

  const { peerAddress } = reply
  const { address, token } = reply.payload

  c.puncher.nat.add(reply.to, reply.from)

  // Open another quick low ttl session against what the server says their address is,
  // if they haven't said they are random yet
  if (
    c.puncher.remoteFirewall < FIREWALL.RANDOM &&
    address &&
    address.host &&
    address.port &&
    diffAddress(address, serverAddress)
  ) {
    await c.puncher.openSession(address)
    if (isDone(c)) return null
  }

  // If the remote told us they didn't know their nat firewall yet, give them a chance to figure it out
  // They might say this to see if the "fast mode" punch comes through first.
  if (c.puncher.remoteFirewall === FIREWALL.UNKNOWN) {
    await c.sleeper.pause(1000)
    if (isDone(c)) return null
  }

  let stable = await c.puncher.analyze(false)
  if (isDone(c)) return null

  // If the socket seems unstable, try to make it stable by setting the "allowReopen" flag
  // Mostly relevant for mobile networks
  if (!stable) {
    stable = await c.puncher.analyze(true)
    if (isDone(c)) return null
    if (stable) return probeRound(c, serverAddress, serverRelay, false)
  }

  if ((c.puncher.remoteFirewall === FIREWALL.UNKNOWN || !token) && retry) {
    return probeRound(c, serverAddress, serverRelay, false)
  }

  if (
    c.puncher.remoteFirewall === FIREWALL.UNKNOWN ||
    c.puncher.nat.firewall === FIREWALL.UNKNOWN
  ) {
    await abort(c, serverRelay, HOLEPUNCH_PROBE_TIMEOUT())
    return null
  }

  if (c.puncher.remoteFirewall >= FIREWALL.RANDOM && c.puncher.nat.firewall >= FIREWALL.RANDOM) {
    await abort(c, serverRelay, HOLEPUNCH_DOUBLE_RANDOMIZED_NATS())
    return null
  }

  return { token, peerAddress }
}

async function roundPunch(c, serverAddress, remoteToken, clientRelay, serverRelay, delayed) {
  // We are gossiping our final NAT status to the other peer now
  // so make sure we don't update our local view for now as that can make things weird
  c.puncher.nat.freeze()

  const isRandom =
    c.puncher.remoteFirewall >= FIREWALL.RANDOM || c.puncher.nat.firewall >= FIREWALL.RANDOM
  if (isRandom) {
    while (
      c.dht._randomPunches >= c.dht._randomPunchLimit ||
      Date.now() - c.dht._lastRandomPunch < c.dht._randomPunchInterval
    ) {
      // if no relay can help, bail
      if (!c.relayToken) throw HOLEPUNCH_ABORTED()

      if (!delayed) {
        delayed = true
        await updateHolepunch(c, serverAddress, clientRelay, {
          error: ERROR.NONE,
          firewall: c.puncher.nat.firewall,
          round: c.round++,
          connected: false,
          punching: false,
          addresses: c.puncher.nat.addresses,
          remoteAddress: null,
          token: c.payload.token(serverAddress),
          remoteToken
        })
        if (isDone(c)) return
      }

      await tryLater(c)
      if (isDone(c)) return
    }
  }

  // increment now, so we can commit to punching
  if (isRandom) c.dht._randomPunches++

  let reply

  try {
    // if delayed switch to the servers chosen relay - we validated anyway
    reply = await updateHolepunch(
      c,
      delayed ? serverRelay.peerAddress : serverAddress,
      delayed ? serverRelay.relayAddress : clientRelay,
      {
        error: ERROR.NONE,
        firewall: c.puncher.nat.firewall,
        round: c.round++,
        connected: false,
        punching: true,
        addresses: c.puncher.nat.addresses,
        remoteAddress: null,
        token: delayed ? null : c.payload.token(serverAddress),
        remoteToken
      }
    )
  } finally {
    // decrement as punch increments for us
    if (isRandom) c.dht._randomPunches--
  }

  if (isDone(c)) return
  if (!reply) return

  if (reply.tryLater) {
    await tryLater(c)
    if (isDone(c)) return
    return roundPunch(c, serverAddress, remoteToken, clientRelay, serverRelay, true)
  }

  if (!c.puncher.remoteHolepunching) {
    throw REMOTE_NOT_HOLEPUNCHING()
  }

  if (!(await c.puncher.punch())) {
    throw REMOTE_NOT_HOLEPUNCHABLE()
  }
}

async function tryLater(c) {
  if (!c.relayToken) throw HOLEPUNCH_ABORTED()
  await c.sleeper.pause(10000 + Math.round(Math.random() * 10000))
}

function maybeDestroyEncryptedSocket(c, err) {
  if (isDone(c)) return
  if (c.encryptedSocket.rawStream) return
  if (c.relaySocket) return // waiting for the relay
  if (c.puncher && !c.puncher.destroyed) return // waiting for the puncher
  c.session.destroy()
  c.encryptedSocket.destroy(err)
}

async function abort(c, { peerAddress, relayAddress }, err) {
  try {
    await updateHolepunch(c, peerAddress, relayAddress, {
      error: ERROR.ABORTED,
      firewall: FIREWALL.UNKNOWN,
      round: c.round++,
      connected: false,
      punching: false,
      addresses: null,
      remoteAddress: null,
      token: null,
      remoteToken: null
    })
  } catch (err) {
    safetyCatch(err)
  }

  destroyPuncher(c)
  maybeDestroyEncryptedSocket(c, err)
}

function relayConnection(c, relayThrough, payload, hs) {
  let isInitiator
  let publicKey
  let token

  if (payload.relayThrough) {
    isInitiator = false
    publicKey = payload.relayThrough.publicKey
    token = payload.relayThrough.token
  } else {
    isInitiator = true
    publicKey = relayThrough
    token = c.relayToken
  }

  c.relayToken = token
  c.relaySocket = c.dht.connect(publicKey)
  c.relaySocket.setKeepAlive(c.relayKeepAlive)
  c.relayClient = relay.Client.from(c.relaySocket, { id: c.relaySocket.publicKey })
  c.relayTimeout = setTimeout(onabort, 15000, null)

  c.relayClient.pair(isInitiator, token, c.rawStream).on('error', onabort).on('data', ondata)

  function ondata(remoteId) {
    if (c.relayTimeout) clearRelayTimeout(c)
    if (c.rawStream === null) {
      onabort(null)
      return
    }

    c.relayPaired = true

    const { remotePort, remoteHost, socket } = c.relaySocket.rawStream

    c.rawStream
      .on('close', () => destroyRelayConnection(c))
      .connect(socket, remoteId, remotePort, remoteHost)

    c.encryptedSocket.start(c.rawStream, { handshake: hs })
  }

  function onabort(err) {
    destroyRelayConnection(c)
    maybeDestroyEncryptedSocket(c, err || RELAY_ABORTED())
  }
}

function clearPassiveConnectTimeout(c) {
  clearTimeout(c.passiveConnectTimeout)
  c.passiveConnectTimeout = null
}

function destroyPuncher(c) {
  if (c.puncher) c.puncher.destroy()
  c.session.destroy()
}

function pickServerRelay(relays, clientRelay) {
  for (const r of relays) {
    if (!diffAddress(r.relayAddress, clientRelay)) return r
  }
  return relays[0]
}

function diffAddress(a, b) {
  return a.host !== b.host || a.port !== b.port
}

function defaultCreateHandshake(keyPair, remotePublicKey) {
  return new NoiseWrap(keyPair, remotePublicKey)
}

function defaultCreateSecretStream(isInitiator, rawStream, opts) {
  return new NoiseSecretStream(isInitiator, rawStream, opts)
}

function onlyNonReserved(addr) {
  return !isReserved(addr.host)
}

function isRelay(relaySocket, socket, port, host) {
  const stream = relaySocket.rawStream
  if (!stream) return false
  if (stream.socket !== socket) return false
  return port === stream.remotePort && host === stream.remoteHost
}

function selectRelay(relayThrough) {
  if (typeof relayThrough === 'function') relayThrough = relayThrough()
  if (relayThrough === null) return null
  if (Array.isArray(relayThrough))
    return relayThrough[Math.floor(Math.random() * relayThrough.length)]
  return relayThrough
}

function isRelayAddress(relayAddresses, data) {
  for (const node of relayAddresses) {
    if (node.host === data.from.host && node.port === data.from.port) return true
  }

  return false
}

function noop() {}
const EventEmitter = require('events')
const b4a = require('b4a')
const errors = require('./errors')

module.exports = class ConnectionPool extends EventEmitter {
  constructor(dht) {
    super()

    this._dht = dht
    this._servers = new Map()
    this._connecting = new Map()
    this._connections = new Map()
  }

  _attachServer(server) {
    const keyString = b4a.toString(server.publicKey, 'hex')

    this._servers.set(keyString, server)

    server
      .on('close', () => {
        this._servers.delete(keyString)
      })
      .on('connection', (socket) => {
        this._attachStream(socket, true)
      })
  }

  _attachStream(stream, opened) {
    const existing = this.get(stream.remotePublicKey)

    if (existing) {
      const keepNew =
        stream.isInitiator === existing.isInitiator ||
        b4a.compare(stream.publicKey, stream.remotePublicKey) > 0

      if (keepNew) {
        let closed = false

        const onclose = () => {
          closed = true
        }

        existing
          .on('error', noop)
          .on('close', () => {
            if (closed) return

            stream.off('error', noop).off('close', onclose)

            this._attachStream(stream, opened)
          })
          .destroy(errors.DUPLICATE_CONNECTION())

        stream.on('error', noop).on('close', onclose)
      } else {
        stream.on('error', noop).destroy(errors.DUPLICATE_CONNECTION())
      }

      return
    }

    const session = new ConnectionRef(this, stream)

    const keyString = b4a.toString(stream.remotePublicKey, 'hex')

    if (opened) {
      this._connections.set(keyString, session)

      stream.on('close', () => {
        this._connections.delete(keyString)
      })

      this.emit('connection', stream, session)
    } else {
      this._connecting.set(keyString, session)

      stream
        .on('error', noop)
        .on('close', () => {
          if (opened) this._connections.delete(keyString)
          else this._connecting.delete(keyString)
        })
        .on('open', () => {
          opened = true

          this._connecting.delete(keyString)
          this._connections.set(keyString, session)

          stream.off('error', noop)

          this.emit('connection', stream, session)
        })
    }

    return session
  }

  get connecting() {
    return this._connecting.size
  }

  get connections() {
    return this._connections.values()
  }

  has(publicKey) {
    const keyString = b4a.toString(publicKey, 'hex')

    return this._connections.has(keyString) || this._connecting.has(keyString)
  }

  get(publicKey) {
    const keyString = b4a.toString(publicKey, 'hex')

    const existing = this._connections.get(keyString) || this._connecting.get(keyString)

    return existing?._stream || null
  }
}

class ConnectionRef {
  constructor(pool, stream) {
    this._pool = pool
    this._stream = stream
    this._refs = 0
  }

  active() {
    this._refs++
  }

  inactive() {
    this._refs--
  }

  release() {
    this._stream.destroy()
  }
}

function noop() {}
const crypto = require('hypercore-crypto')

const COMMANDS = (exports.COMMANDS = {
  PEER_HANDSHAKE: 0,
  PEER_HOLEPUNCH: 1,
  FIND_PEER: 2,
  LOOKUP: 3,
  ANNOUNCE: 4,
  UNANNOUNCE: 5,
  MUTABLE_PUT: 6,
  MUTABLE_GET: 7,
  IMMUTABLE_PUT: 8,
  IMMUTABLE_GET: 9,
  PLUGIN: 10
})

exports.BOOTSTRAP_NODES = [
  '88.99.3.86@node1.hyperdht.org:49737',
  '142.93.90.113@node2.hyperdht.org:49737',
  '138.68.147.8@node3.hyperdht.org:49737'
]

exports.FIREWALL = {
  UNKNOWN: 0,
  OPEN: 1,
  CONSISTENT: 2,
  RANDOM: 3
}

exports.ERROR = {
  // noise / connection related
  NONE: 0,
  ABORTED: 1,
  VERSION_MISMATCH: 2,
  TRY_LATER: 3,
  // dht related
  SEQ_REUSED: 16,
  SEQ_TOO_LOW: 17
}

const [
  NS_ANNOUNCE,
  NS_UNANNOUNCE,
  NS_MUTABLE_PUT,
  NS_PEER_HANDSHAKE,
  NS_PEER_HOLEPUNCH,
  NS_PLUGIN
] = crypto.namespace('hyperswarm/dht', [
  COMMANDS.ANNOUNCE,
  COMMANDS.UNANNOUNCE,
  COMMANDS.MUTABLE_PUT,
  COMMANDS.PEER_HANDSHAKE,
  COMMANDS.PEER_HOLEPUNCH,
  COMMANDS.PLUGIN
])

exports.NS = {
  ANNOUNCE: NS_ANNOUNCE,
  UNANNOUNCE: NS_UNANNOUNCE,
  MUTABLE_PUT: NS_MUTABLE_PUT,
  PEER_HANDSHAKE: NS_PEER_HANDSHAKE,
  PEER_HOLEPUNCH: NS_PEER_HOLEPUNCH,
  PLUGIN: NS_PLUGIN
}
const sodium = require('sodium-universal')
const b4a = require('b4a')

function hash(data) {
  const out = b4a.allocUnsafe(32)
  sodium.crypto_generichash(out, data)
  return out
}

function unslabbedHash(data) {
  const out = b4a.allocUnsafeSlow(32)
  sodium.crypto_generichash(out, data)
  return out
}

function createKeyPair(seed) {
  const publicKey = b4a.alloc(32)
  const secretKey = b4a.alloc(64)
  if (seed) sodium.crypto_sign_seed_keypair(publicKey, secretKey, seed)
  else sodium.crypto_sign_keypair(publicKey, secretKey)
  return { publicKey, secretKey }
}

module.exports = {
  hash,
  unslabbedHash,
  createKeyPair
}
const b4a = require('b4a')
const cenc = require('compact-encoding')

function encodeUnslab(enc, m) {
  // Faster than unslab(c.encode(enc, data)) because it avoids the mem copy.
  // Makes sense to put in compact-encoding when we need it in other modules too
  const state = cenc.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafeSlow(state.end)
  enc.encode(state, m)
  return state.buffer
}

module.exports = {
  encodeUnslab
}
module.exports = class DHTError extends Error {
  constructor(msg, code, fn = DHTError) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'DHTError'
  }

  static BAD_HANDSHAKE_REPLY(msg = 'Bad handshake reply') {
    return new DHTError(msg, 'BAD_HANDSHAKE_REPLY', DHTError.BAD_HANDSHAKE_REPLY)
  }

  static BAD_HOLEPUNCH_REPLY(msg = 'Bad holepunch reply') {
    return new DHTError(msg, 'BAD_HOLEPUNCH_REPLY', DHTError.BAD_HOLEPUNCH_REPLY)
  }

  static HOLEPUNCH_ABORTED(msg = 'Holepunch aborted') {
    return new DHTError(msg, 'HOLEPUNCH_ABORTED', DHTError.HOLEPUNCH_ABORTED)
  }

  static HOLEPUNCH_INVALID(msg = 'Invalid holepunch payload') {
    return new DHTError(msg, 'HOLEPUNCH_INVALID', DHTError.HOLEPUNCH_INVALID)
  }

  static HOLEPUNCH_PROBE_TIMEOUT(msg = 'Holepunching probe did not finish in time') {
    return new DHTError(msg, 'HOLEPUNCH_PROBE_TIMEOUT', DHTError.HOLEPUNCH_PROBE_TIMEOUT)
  }

  static HOLEPUNCH_DOUBLE_RANDOMIZED_NATS(msg = 'Both remote and local NATs are randomized') {
    return new DHTError(
      msg,
      'HOLEPUNCH_DOUBLE_RANDOMIZED_NATS',
      DHTError.HOLEPUNCH_DOUBLE_RANDOMIZED_NATS
    )
  }

  static CANNOT_HOLEPUNCH(msg = 'Cannot holepunch to remote') {
    return new DHTError(msg, 'CANNOT_HOLEPUNCH', DHTError.CANNOT_HOLEPUNCH)
  }

  static REMOTE_NOT_HOLEPUNCHING(msg = 'Remote is not holepunching') {
    return new DHTError(msg, 'REMOTE_NOT_HOLEPUNCHING', DHTError.REMOTE_NOT_HOLEPUNCHING)
  }

  static REMOTE_NOT_HOLEPUNCHABLE(msg = 'Remote is not holepunchable') {
    return new DHTError(msg, 'REMOTE_NOT_HOLEPUNCHABLE', DHTError.REMOTE_NOT_HOLEPUNCHABLE)
  }

  static REMOTE_ABORTED(msg = 'Remote aborted') {
    return new DHTError(msg, 'REMOTE_ABORTED', DHTError.REMOTE_ABORTED)
  }

  static HANDSHAKE_UNFINISHED(msg = 'Handshake did not finish') {
    return new DHTError(msg, 'HANDSHAKE_UNFINISHED', DHTError.HANDSHAKE_UNFINISHED)
  }

  static HANDSHAKE_INVALID(msg = 'Received invalid handshake') {
    return new DHTError(msg, 'HANDSHAKE_INVALID', DHTError.HANDSHAKE_INVALID)
  }

  static ALREADY_LISTENING(msg = 'Already listening') {
    return new DHTError(msg, 'ALREADY_LISTENING', DHTError.ALREADY_LISTENING)
  }

  static KEYPAIR_ALREADY_USED(msg = 'Keypair already used') {
    return new DHTError(msg, 'KEYPAIR_ALREADY_USED', DHTError.KEYPAIR_ALREADY_USED)
  }

  static NODE_DESTROYED(msg = 'Node destroyed') {
    return new DHTError(msg, 'NODE_DESTROYED', DHTError.NODE_DESTROYED)
  }

  static PEER_CONNECTION_FAILED(msg = 'Could not connect to peer') {
    return new DHTError(msg, 'PEER_CONNECTION_FAILED', DHTError.PEER_CONNECTION_FAILED)
  }

  static PEER_NOT_FOUND(msg = 'Peer not found') {
    return new DHTError(msg, 'PEER_NOT_FOUND', DHTError.PEER_NOT_FOUND)
  }

  static STREAM_NOT_CONNECTED(msg = 'Stream is not connected') {
    return new DHTError(msg, 'STREAM_NOT_CONNECTED', DHTError.STREAM_NOT_CONNECTED)
  }

  static SERVER_INCOMPATIBLE(msg = 'Server is using an incompatible version') {
    return new DHTError(msg, 'SERVER_INCOMPATIBLE', DHTError.SERVER_INCOMPATIBLE)
  }

  static SERVER_ERROR(msg = 'Server returned an error') {
    return new DHTError(msg, 'SERVER_ERROR', DHTError.SERVER_ERROR)
  }

  static DUPLICATE_CONNECTION(msg = 'Duplicate connection') {
    return new DHTError(msg, 'DUPLICATE_CONNECTION', DHTError.DUPLICATE_CONNECTION)
  }

  static RELAY_ABORTED(msg = 'Relay aborted') {
    return new DHTError(msg, 'RELAY_ABORTED', DHTError.RELAY_ABORTED)
  }

  static SUSPENDED(msg = 'Suspended') {
    return new DHTError(msg, 'SUSPENDED', DHTError.SUSPENDED)
  }
}
const b4a = require('b4a')
const Nat = require('./nat')
const Sleeper = require('./sleeper')
const { FIREWALL } = require('./constants')

const BIRTHDAY_SOCKETS = 256
const HOLEPUNCH = b4a.from([0])
const HOLEPUNCH_TTL = 5
const DEFAULT_TTL = 64
const MAX_REOPENS = 3

module.exports = class Holepuncher {
  constructor(dht, session, isInitiator, remoteFirewall = FIREWALL.UNKNOWN) {
    const holder = dht._socketPool.acquire()

    this.dht = dht
    this.session = session

    this.nat = new Nat(dht, session, holder.socket)
    this.nat.autoSample()

    this.isInitiator = isInitiator

    // events
    this.onconnect = noop
    this.onabort = noop

    this.punching = false
    this.connected = false
    this.destroyed = false
    this.randomized = false

    // track remote state
    this.remoteFirewall = remoteFirewall
    this.remoteAddresses = []
    this.remoteHolepunching = false

    this._sleeper = new Sleeper()
    this._reopening = null
    this._timeout = null
    this._punching = null
    this._allHolders = []
    this._holder = this._addRef(holder)
  }

  get socket() {
    return this._holder.socket
  }

  updateRemote({ punching, firewall, addresses, verified }) {
    const remoteAddresses = []

    if (addresses) {
      for (const addr of addresses) {
        remoteAddresses.push({
          host: addr.host,
          port: addr.port,
          verified: verified === addr.host || this._isVerified(addr.host)
        })
      }
    }

    this.remoteFirewall = firewall
    this.remoteAddresses = remoteAddresses
    this.remoteHolepunching = punching
  }

  _isVerified(host) {
    for (const addr of this.remoteAddresses) {
      if (addr.verified && addr.host === host) {
        return true
      }
    }
    return false
  }

  ping(addr, socket = this._holder.socket) {
    return holepunch(socket, addr, false)
  }

  openSession(addr, socket = this._holder.socket) {
    return holepunch(socket, addr, true)
  }

  async analyze(allowReopen) {
    await this.nat.analyzing
    if (this._unstable()) {
      if (!allowReopen) return false
      if (!this._reopening) this._reopening = this._reopen()
      return this._reopening
    }
    return true
  }

  _unstable() {
    // TODO!!: We need an additional heuristic here... If we were NOT random in the past we should also do this.
    const firewall = this.nat.firewall
    return (
      (this.remoteFirewall >= FIREWALL.RANDOM && firewall >= FIREWALL.RANDOM) ||
      firewall === FIREWALL.UNKNOWN
    )
  }

  _reset() {
    const prev = this._holder

    this._allHolders.pop()
    this._holder = this._addRef(this.dht._socketPool.acquire())

    prev.release()
    this.nat.destroy()

    this.nat = new Nat(this.dht, this.session, this._holder.socket)
    // TODO: maybe make auto sampling configurable somehow?
    this.nat.autoSample()
  }

  _addRef(ref) {
    this._allHolders.push(ref)
    ref.onholepunchmessage = (msg, rinfo) => this._onholepunchmessage(msg, rinfo, ref)
    return ref
  }

  _onholepunchmessage(_, addr, ref) {
    if (!this.isInitiator) {
      // TODO: we don't need this if we had a way to connect a socket to many hosts
      holepunch(ref.socket, addr, false) // never fails
      return
    }

    if (this.connected) return

    this.connected = true
    this.punching = false

    for (const r of this._allHolders) {
      if (r === ref) continue
      r.release()
    }

    this._allHolders[0] = ref
    while (this._allHolders.length > 1) this._allHolders.pop()

    this._decrementRandomized()
    this.onconnect(ref.socket, addr.port, addr.host)
  }

  _done() {
    return this.destroyed || this.connected
  }

  async _reopen() {
    for (let i = 0; this._unstable() && i < MAX_REOPENS && !this._done() && !this.punching; i++) {
      this._reset()
      await this.nat.analyzing
    }

    return coerceFirewall(this.nat.firewall) === FIREWALL.CONSISTENT
  }

  punch() {
    if (!this._punching) this._punching = this._punch()
    return this._punching
  }

  async _punch() {
    if (this._done() || !this.remoteAddresses.length) return false

    this.punching = true

    // Coerce into consistency for now. Obvs we could make this this more efficient if we use that info
    // but that's seldomly used since those will just use tcp most of the time.

    const local = coerceFirewall(this.nat.firewall)
    const remote = coerceFirewall(this.remoteFirewall)

    // Note that most of these async functions are meant to run in the background
    // which is why we don't await them here and why they are not allowed to throw

    let remoteVerifiedAddress = null
    for (const addr of this.remoteAddresses) {
      if (addr.verified) {
        remoteVerifiedAddress = addr
        break
      }
    }

    if (local === FIREWALL.CONSISTENT && remote === FIREWALL.CONSISTENT) {
      this.dht.stats.punches.consistent++
      this._consistentProbe()
      return true
    }

    if (!remoteVerifiedAddress) return false

    if (local === FIREWALL.CONSISTENT && remote >= FIREWALL.RANDOM) {
      this.dht.stats.punches.random++
      this._incrementRandomized()
      this._randomProbes(remoteVerifiedAddress)
      return true
    }

    if (local >= FIREWALL.RANDOM && remote === FIREWALL.CONSISTENT) {
      this.dht.stats.punches.random++
      this._incrementRandomized()
      await this._openBirthdaySockets(remoteVerifiedAddress)
      if (this.punching) this._keepAliveRandomNat(remoteVerifiedAddress)
      return true
    }

    return false
  }

  // Note that this never throws so it is safe to run in the background
  async _consistentProbe() {
    // Here we do the sleep first because the "fast open" mode in the server just fired a ping
    if (!this.isInitiator) await this._sleeper.pause(1000)

    let tries = 0

    while (this.punching && tries++ < 10) {
      for (const addr of this.remoteAddresses) {
        // only try unverified addresses every 4 ticks
        if (!addr.verified && (tries & 3) !== 0) continue
        await holepunch(this._holder.socket, addr, false)
      }
      if (this.punching) await this._sleeper.pause(1000)
    }

    this._autoDestroy()
  }

  // Note that this never throws so it is safe to run in the background
  async _randomProbes(remoteAddr) {
    let tries = 1750 // ~35s

    while (this.punching && tries-- > 0) {
      const addr = { host: remoteAddr.host, port: randomPort() }
      await holepunch(this._holder.socket, addr, false)
      if (this.punching) await this._sleeper.pause(20)
    }

    this._autoDestroy()
  }

  // Note that this never throws so it is safe to run in the background
  async _keepAliveRandomNat(remoteAddr) {
    let i = 0
    let lowTTLRounds = 1

    // TODO: experiment with this here. We just bursted all the messages in
    // openOtherSockets to ensure the sockets are open, so it's potentially
    // a good idea to slow down for a bit.
    await this._sleeper.pause(100)

    let tries = 1750 // ~35s

    while (this.punching && tries-- > 0) {
      if (i === this._allHolders.length) {
        i = 0
        if (lowTTLRounds > 0) lowTTLRounds--
      }

      await holepunch(this._allHolders[i++].socket, remoteAddr, lowTTLRounds > 0)
      if (this.punching) await this._sleeper.pause(20)
    }

    this._autoDestroy()
  }

  async _openBirthdaySockets(remoteAddr) {
    while (this.punching && this._allHolders.length < BIRTHDAY_SOCKETS) {
      const ref = this._addRef(this.dht._socketPool.acquire())
      await holepunch(ref.socket, remoteAddr, HOLEPUNCH_TTL)
    }
  }

  _autoDestroy() {
    if (!this.connected) this.destroy()
  }

  _incrementRandomized() {
    if (!this.randomized) {
      this.randomized = true
      this.dht._randomPunches++
    }
  }

  _decrementRandomized() {
    if (this.randomized) {
      this.dht._lastRandomPunch = Date.now()
      this.randomized = false
      this.dht._randomPunches--
    }
  }

  destroy() {
    if (this.destroyed) return
    this.destroyed = true
    this.punching = false

    for (const ref of this._allHolders) ref.release()
    this._allHolders = []
    this.nat.destroy()

    if (!this.connected) {
      this._decrementRandomized()
      this.onabort()
    }
  }

  static ping(socket, addr) {
    return holepunch(socket, addr, false)
  }

  static localAddresses(socket) {
    return localAddresses(socket)
  }

  static matchAddress(myAddresses, externalAddresses) {
    return matchAddress(myAddresses, externalAddresses)
  }
}

function holepunch(socket, addr, lowTTL) {
  return socket.send(HOLEPUNCH, addr.port, addr.host, lowTTL ? HOLEPUNCH_TTL : DEFAULT_TTL)
}

function randomPort() {
  return (1000 + Math.random() * 64536) | 0
}

function coerceFirewall(fw) {
  return fw === FIREWALL.OPEN ? FIREWALL.CONSISTENT : fw
}

function localAddresses(socket) {
  const addrs = []
  const { host, port } = socket.address()

  if (host === '127.0.0.1') return [{ host, port }]

  for (const n of socket.udx.networkInterfaces()) {
    if (n.family !== 4 || n.internal) continue

    addrs.push({ host: n.host, port })
  }

  if (addrs.length === 0) {
    addrs.push({ host: '127.0.0.1', port })
  }

  return addrs
}

function matchAddress(localAddresses, remoteLocalAddresses) {
  if (remoteLocalAddresses.length === 0) return null

  let best = { segment: 1, addr: null }

  for (const localAddress of localAddresses) {
    // => 192.168.122.238
    const a = localAddress.host.split('.')

    for (const remoteAddress of remoteLocalAddresses) {
      // => 192.168.0.23
      // => 192.168.122.1
      const b = remoteAddress.host.split('.')

      // Matches 192.*.*.*
      if (a[0] === b[0]) {
        if (best.segment === 1) best = { segment: 2, addr: remoteAddress }

        // Matches 192.168.*.*
        if (a[1] === b[1]) {
          if (best.segment === 2) best = { segment: 3, addr: remoteAddress }

          // Matches 192.168.122.*
          if (a[2] === b[2]) return remoteAddress
        }
      }
    }
  }

  return best.addr
}

function noop() {}
const c = require('compact-encoding')

const ipv4 = {
  ...c.ipv4Address,
  decode(state) {
    const ip = c.ipv4Address.decode(state)
    return {
      host: ip.host,
      port: ip.port
    }
  }
}

const ipv4Array = c.array(ipv4)

const ipv6 = {
  ...c.ipv6Address,
  decode(state) {
    const ip = c.ipv6Address.decode(state)
    return {
      host: ip.host,
      port: ip.port
    }
  }
}

const ipv6Array = c.array(ipv6)

exports.handshake = {
  preencode(state, m) {
    state.end += 1 + 1 + (m.peerAddress ? 6 : 0) + (m.relayAddress ? 6 : 0)
    c.buffer.preencode(state, m.noise)
  },
  encode(state, m) {
    const flags = (m.peerAddress ? 1 : 0) | (m.relayAddress ? 2 : 0)

    c.uint.encode(state, flags)
    c.uint.encode(state, m.mode)
    c.buffer.encode(state, m.noise)

    if (m.peerAddress) ipv4.encode(state, m.peerAddress)
    if (m.relayAddress) ipv4.encode(state, m.relayAddress)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      mode: c.uint.decode(state),
      noise: c.buffer.decode(state),
      peerAddress: flags & 1 ? ipv4.decode(state) : null,
      relayAddress: flags & 2 ? ipv4.decode(state) : null
    }
  }
}

const relayInfo = {
  preencode(state, m) {
    state.end += 12
  },
  encode(state, m) {
    ipv4.encode(state, m.relayAddress)
    ipv4.encode(state, m.peerAddress)
  },
  decode(state) {
    return {
      relayAddress: ipv4.decode(state),
      peerAddress: ipv4.decode(state)
    }
  }
}

const relayInfoArray = c.array(relayInfo)

const holepunchInfo = {
  preencode(state, m) {
    c.uint.preencode(state, m.id)
    relayInfoArray.preencode(state, m.relays)
  },
  encode(state, m) {
    c.uint.encode(state, m.id)
    relayInfoArray.encode(state, m.relays)
  },
  decode(state) {
    return {
      id: c.uint.decode(state),
      relays: relayInfoArray.decode(state)
    }
  }
}

const udxInfo = {
  preencode(state, m) {
    state.end += 2 // version + features
    c.uint.preencode(state, m.id)
    c.uint.preencode(state, m.seq)
  },
  encode(state, m) {
    c.uint.encode(state, 1)
    c.uint.encode(state, m.reusableSocket ? 1 : 0)
    c.uint.encode(state, m.id)
    c.uint.encode(state, m.seq)
  },
  decode(state) {
    const version = c.uint.decode(state)
    const features = c.uint.decode(state)

    return {
      version,
      reusableSocket: (features & 1) !== 0,
      id: c.uint.decode(state),
      seq: c.uint.decode(state)
    }
  }
}

const secretStreamInfo = {
  preencode(state, m) {
    c.uint.preencode(state, 1)
  },
  encode(state, m) {
    c.uint.encode(state, 1)
  },
  decode(state) {
    return {
      version: c.uint.decode(state)
    }
  }
}

const relayThroughInfo = {
  preencode(state, m) {
    c.uint.preencode(state, 1) // version
    c.uint.preencode(state, 0) // flags
    c.fixed32.preencode(state, m.publicKey)
    c.fixed32.preencode(state, m.token)
  },
  encode(state, m) {
    c.uint.encode(state, 1)
    c.uint.encode(state, 0)
    c.fixed32.encode(state, m.publicKey)
    c.fixed32.encode(state, m.token)
  },
  decode(state) {
    const version = c.uint.decode(state)
    c.uint.decode(state)

    return {
      version,
      publicKey: c.fixed32.decode(state),
      token: c.fixed32.decode(state)
    }
  }
}

exports.noisePayload = {
  preencode(state, m) {
    state.end += 4 // version + flags + error + firewall
    if (m.holepunch) holepunchInfo.preencode(state, m.holepunch)
    if (m.addresses4 && m.addresses4.length) ipv4Array.preencode(state, m.addresses4)
    if (m.addresses6 && m.addresses6.length) ipv6Array.preencode(state, m.addresses6)
    if (m.udx) udxInfo.preencode(state, m.udx)
    if (m.secretStream) secretStreamInfo.preencode(state, m.secretStream)
    if (m.relayThrough) relayThroughInfo.preencode(state, m.relayThrough)
    if (m.relayAddresses) ipv4Array.preencode(state, m.relayAddresses)
  },
  encode(state, m) {
    let flags = 0

    if (m.holepunch) flags |= 1
    if (m.addresses4 && m.addresses4.length) flags |= 2
    if (m.addresses6 && m.addresses6.length) flags |= 4
    if (m.udx) flags |= 8
    if (m.secretStream) flags |= 16
    if (m.relayThrough) flags |= 32
    if (m.relayAddresses) flags |= 64

    c.uint.encode(state, 1) // version
    c.uint.encode(state, flags)
    c.uint.encode(state, m.error)
    c.uint.encode(state, m.firewall)

    if (m.holepunch) holepunchInfo.encode(state, m.holepunch)
    if (m.addresses4 && m.addresses4.length) ipv4Array.encode(state, m.addresses4)
    if (m.addresses6 && m.addresses6.length) ipv6Array.encode(state, m.addresses6)
    if (m.udx) udxInfo.encode(state, m.udx)
    if (m.secretStream) secretStreamInfo.encode(state, m.secretStream)
    if (m.relayThrough) relayThroughInfo.encode(state, m.relayThrough)
    if (m.relayAddresses) ipv4Array.encode(state, m.relayAddresses)
  },
  decode(state) {
    const version = c.uint.decode(state)

    if (version !== 1) {
      // Do not attempt to decode but return this back to the user so they can
      // actually handle it
      return {
        version,
        error: 0,
        firewall: 0,
        holepunch: null,
        addresses4: [],
        addresses6: [],
        udx: null,
        secretStream: null,
        relayThrough: null,
        relayAddresses: null
      }
    }

    const flags = c.uint.decode(state)

    return {
      version,
      error: c.uint.decode(state),
      firewall: c.uint.decode(state),
      holepunch: (flags & 1) !== 0 ? holepunchInfo.decode(state) : null,
      addresses4: (flags & 2) !== 0 ? ipv4Array.decode(state) : [],
      addresses6: (flags & 4) !== 0 ? ipv6Array.decode(state) : [],
      udx: (flags & 8) !== 0 ? udxInfo.decode(state) : null,
      secretStream: (flags & 16) !== 0 ? secretStreamInfo.decode(state) : null,
      relayThrough: (flags & 32) !== 0 ? relayThroughInfo.decode(state) : null,
      relayAddresses: (flags & 64) !== 0 ? ipv4Array.decode(state) : null
    }
  }
}

exports.holepunch = {
  preencode(state, m) {
    state.end += 2
    c.uint.preencode(state, m.id)
    c.buffer.preencode(state, m.payload)
    if (m.peerAddress) ipv4.preencode(state, m.peerAddress)
  },
  encode(state, m) {
    const flags = m.peerAddress ? 1 : 0
    c.uint.encode(state, flags)
    c.uint.encode(state, m.mode)
    c.uint.encode(state, m.id)
    c.buffer.encode(state, m.payload)
    if (m.peerAddress) ipv4.encode(state, m.peerAddress)
  },
  decode(state) {
    const flags = c.uint.decode(state)
    return {
      mode: c.uint.decode(state),
      id: c.uint.decode(state),
      payload: c.buffer.decode(state),
      peerAddress: flags & 1 ? ipv4.decode(state) : null
    }
  }
}

exports.holepunchPayload = {
  preencode(state, m) {
    state.end += 4 // flags + error + firewall + round
    if (m.addresses) ipv4Array.preencode(state, m.addresses)
    if (m.remoteAddress) state.end += 6
    if (m.token) state.end += 32
    if (m.remoteToken) state.end += 32
  },
  encode(state, m) {
    const flags =
      (m.connected ? 1 : 0) |
      (m.punching ? 2 : 0) |
      (m.addresses ? 4 : 0) |
      (m.remoteAddress ? 8 : 0) |
      (m.token ? 16 : 0) |
      (m.remoteToken ? 32 : 0)

    c.uint.encode(state, flags)
    c.uint.encode(state, m.error)
    c.uint.encode(state, m.firewall)
    c.uint.encode(state, m.round)

    if (m.addresses) ipv4Array.encode(state, m.addresses)
    if (m.remoteAddress) ipv4.encode(state, m.remoteAddress)
    if (m.token) c.fixed32.encode(state, m.token)
    if (m.remoteToken) c.fixed32.encode(state, m.remoteToken)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      error: c.uint.decode(state),
      firewall: c.uint.decode(state),
      round: c.uint.decode(state),
      connected: (flags & 1) !== 0,
      punching: (flags & 2) !== 0,
      addresses: (flags & 4) !== 0 ? ipv4Array.decode(state) : null,
      remoteAddress: (flags & 8) !== 0 ? ipv4.decode(state) : null,
      token: (flags & 16) !== 0 ? c.fixed32.decode(state) : null,
      remoteToken: (flags & 32) !== 0 ? c.fixed32.decode(state) : null
    }
  }
}

const peer = (exports.peer = {
  preencode(state, m) {
    state.end += 32
    ipv4Array.preencode(state, m.relayAddresses)
  },
  encode(state, m) {
    c.fixed32.encode(state, m.publicKey)
    ipv4Array.encode(state, m.relayAddresses)
  },
  decode(state) {
    return {
      publicKey: c.fixed32.decode(state),
      relayAddresses: ipv4Array.decode(state)
    }
  }
})

const peers = (exports.peers = c.array(peer))

const rawPeers = c.array(c.raw)

exports.lookupRawReply = {
  preencode(state, m) {
    rawPeers.preencode(state, m.peers)
    c.uint.preencode(state, m.bump)
  },
  encode(state, m) {
    rawPeers.encode(state, m.peers)
    c.uint.encode(state, m.bump)
  },
  decode(state) {
    return {
      peers: peers.decode(state),
      bump: state.start < state.end ? c.uint.decode(state) : 0
    }
  }
}

exports.announce = {
  preencode(state, m) {
    state.end++ // flags
    if (m.peer) peer.preencode(state, m.peer)
    if (m.refresh) state.end += 32
    if (m.signature) state.end += 64
    if (m.bump) c.uint.preencode(state, m.bump)
  },
  encode(state, m) {
    const flags = (m.peer ? 1 : 0) | (m.refresh ? 2 : 0) | (m.signature ? 4 : 0) | (m.bump ? 8 : 0)
    c.uint.encode(state, flags)
    if (m.peer) peer.encode(state, m.peer)
    if (m.refresh) c.fixed32.encode(state, m.refresh)
    if (m.signature) c.fixed64.encode(state, m.signature)
    if (m.bump) c.uint.encode(state, m.bump)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      peer: (flags & 1) !== 0 ? peer.decode(state) : null,
      refresh: (flags & 2) !== 0 ? c.fixed32.decode(state) : null,
      signature: (flags & 4) !== 0 ? c.fixed64.decode(state) : null,
      bump: (flags & 8) !== 0 ? c.uint.decode(state) : 0
    }
  }
}

exports.mutableSignable = {
  preencode(state, m) {
    c.uint.preencode(state, m.seq)
    c.buffer.preencode(state, m.value)
  },
  encode(state, m) {
    c.uint.encode(state, m.seq)
    c.buffer.encode(state, m.value)
  },
  decode(state) {
    return {
      seq: c.uint.decode(state),
      value: c.buffer.decode(state)
    }
  }
}

exports.mutablePutRequest = {
  preencode(state, m) {
    c.fixed32.preencode(state, m.publicKey)
    c.uint.preencode(state, m.seq)
    c.buffer.preencode(state, m.value)
    c.fixed64.preencode(state, m.signature)
  },
  encode(state, m) {
    c.fixed32.encode(state, m.publicKey)
    c.uint.encode(state, m.seq)
    c.buffer.encode(state, m.value)
    c.fixed64.encode(state, m.signature)
  },
  decode(state) {
    return {
      publicKey: c.fixed32.decode(state),
      seq: c.uint.decode(state),
      value: c.buffer.decode(state),
      signature: c.fixed64.decode(state)
    }
  }
}

exports.mutableGetResponse = {
  preencode(state, m) {
    c.uint.preencode(state, m.seq)
    c.buffer.preencode(state, m.value)
    c.fixed64.preencode(state, m.signature)
  },
  encode(state, m) {
    c.uint.encode(state, m.seq)
    c.buffer.encode(state, m.value)
    c.fixed64.encode(state, m.signature)
  },
  decode(state) {
    return {
      seq: c.uint.decode(state),
      value: c.buffer.decode(state),
      signature: c.fixed64.decode(state)
    }
  }
}

exports.pluginRequest = {
  preencode(state, m) {
    c.string.preencode(state, m.plugin)
    c.uint.preencode(state, m.version)
    c.uint.preencode(state, m.command)
    state.end++ // max flag is 1 so always one byte

    if (m.value) c.buffer.preencode(state, m.value)
  },
  encode(state, m) {
    const flags = m.value ? 1 : 0

    c.string.encode(state, m.plugin)
    c.uint.encode(state, m.version)
    c.uint.encode(state, m.command)
    c.uint.encode(state, flags)

    if (m.value) c.buffer.encode(state, m.value)
  },
  decode(state) {
    const r0 = c.string.decode(state)
    const r1 = c.uint.decode(state)
    const r2 = c.uint.decode(state)
    const flags = c.uint.decode(state)

    return {
      plugin: r0,
      version: r1,
      command: r2,
      value: (flags & 1) !== 0 ? c.buffer.decode(state) : null
    }
  }
}
const { FIREWALL } = require('../lib/constants')

module.exports = class Nat {
  constructor(dht, session, socket) {
    this._samplesHost = []
    this._samplesFull = []
    this._visited = new Map()
    this._resolve = null
    this._minSamples = 4
    this._autoSampling = false

    this.dht = dht
    this.session = session
    this.socket = socket

    this.sampled = 0
    this.firewall = dht.firewalled ? FIREWALL.UNKNOWN : FIREWALL.OPEN
    this.addresses = null

    this.analyzing = new Promise((resolve) => {
      this._resolve = resolve
    })
  }

  autoSample(retry = true) {
    if (this._autoSampling) return
    this._autoSampling = true

    const self = this
    const socket = this.socket
    const maxPings = this._minSamples

    let skip = this.dht.nodes.length >= 8 ? 5 : 0
    let pending = 0

    // TODO: it would be best to pick the nodes to help us based on latency to us
    // That should reduce connect latency in general. We should investigate tracking that later on.

    // TODO 2: try to pick nodes with different IPs as well, as that'll help multi IP cell connections...
    // If we expose this from the nat sampler then the DHT should be able to help us filter out scams as well...

    for (
      let node = this.dht.nodes.latest;
      node && this.sampled + pending < maxPings;
      node = node.prev
    ) {
      if (skip > 0) {
        skip--
        continue
      }

      const ref = node.host + ':' + node.port

      if (this._visited.has(ref)) continue
      this._visited.set(ref, 1)

      pending++
      this.session.ping(node, { socket, retry: false }).then(onpong, onskip)
    }

    pending++
    onskip()

    function onpong(res) {
      self.add(res.to, res.from)
      onskip()
    }

    function onskip() {
      if (--pending === 0 && self.sampled < self._minSamples) {
        if (retry) {
          self._autoSampling = false
          self.autoSample(false)
          return
        }
        self._resolve()
      }
    }
  }

  destroy() {
    this._autoSampling = true
    this._minSamples = 0
    this._resolve()
  }

  unfreeze() {
    this.frozen = false
    this._updateFirewall()
    this._updateAddresses()
  }

  freeze() {
    this.frozen = true
  }

  _updateFirewall() {
    if (!this.dht.firewalled) {
      this.firewall = FIREWALL.OPEN
      return
    }

    if (this.sampled < 3) return

    const max = this._samplesFull[0].hits

    if (max >= 3) {
      this.firewall = FIREWALL.CONSISTENT
      return
    }

    if (max === 1) {
      this.firewall = FIREWALL.RANDOM
      return
    }

    // else max === 2

    // 1 host, >= 4 total samples ie, 2 bad ones -> random
    if (this._samplesHost.length === 1 && this.sampled > 3) {
      this.firewall = FIREWALL.RANDOM
      return
    }

    // double hit on two different ips -> assume consistent
    if (this._samplesHost.length > 1 && this._samplesFull[1].hits > 1) {
      this.firewall = FIREWALL.CONSISTENT
      return
    }

    // (4 is just means - all the samples we expect) - no decision - assume random
    if (this.sampled > 4) {
      this.firewall = FIREWALL.RANDOM
    }
  }

  _updateAddresses() {
    if (this.firewall === FIREWALL.UNKNOWN) {
      this.addresses = null
      return
    }

    if (this.firewall === FIREWALL.RANDOM) {
      this.addresses = [this._samplesHost[0]]
      return
    }

    if (this.firewall === FIREWALL.CONSISTENT) {
      this.addresses = []
      for (const addr of this._samplesFull) {
        if (addr.hits >= 2 || this.addresses.length < 2) this.addresses.push(addr)
      }
    }
  }

  update() {
    if (this.dht.firewalled && this.firewall === FIREWALL.OPEN) {
      this.firewall = FIREWALL.UNKNOWN
    }
    this._updateFirewall()
    this._updateAddresses()
  }

  add(addr, from) {
    const ref = from.host + ':' + from.port

    if (this._visited.get(ref) === 2) return
    this._visited.set(ref, 2)

    addSample(this._samplesHost, addr.host, 0)
    addSample(this._samplesFull, addr.host, addr.port)

    if ((++this.sampled >= 3 || !this.dht.firewalled) && !this.frozen) {
      this.update()
    }

    if (this.firewall === FIREWALL.CONSISTENT || this.firewall === FIREWALL.OPEN) {
      this._resolve()
    } else if (this.sampled >= this._minSamples) {
      this._resolve()
    }
  }
}

function addSample(samples, host, port) {
  for (let i = 0; i < samples.length; i++) {
    const s = samples[i]

    if (s.port !== port || s.host !== host) continue
    s.hits++

    for (; i > 0; i--) {
      const prev = samples[i - 1]
      if (prev.hits >= s.hits) return
      samples[i - 1] = s
      samples[i] = prev
    }

    return
  }

  samples.push({
    host,
    port,
    hits: 1
  })
}
const NoiseSecretStream = require('@hyperswarm/secret-stream')
const NoiseHandshake = require('noise-handshake')
const curve = require('noise-curve-ed')
const c = require('compact-encoding')
const b4a = require('b4a')
const sodium = require('sodium-universal')
const m = require('./messages')
const { NS } = require('./constants')
const { HANDSHAKE_UNFINISHED } = require('./errors')

const NOISE_PROLOUGE = NS.PEER_HANDSHAKE

module.exports = class NoiseWrap {
  constructor(keyPair, remotePublicKey) {
    this.isInitiator = !!remotePublicKey
    this.remotePublicKey = remotePublicKey
    this.keyPair = keyPair
    this.handshake = new NoiseHandshake('IK', this.isInitiator, keyPair, { curve })
    this.handshake.initialise(NOISE_PROLOUGE, remotePublicKey)
  }

  send(payload) {
    const buf = c.encode(m.noisePayload, payload)
    return this.handshake.send(buf)
  }

  recv(buf) {
    const payload = c.decode(m.noisePayload, this.handshake.recv(buf))
    this.remotePublicKey = b4a.toBuffer(this.handshake.rs)
    return payload
  }

  final() {
    if (!this.handshake.complete) throw HANDSHAKE_UNFINISHED()

    const holepunchSecret = b4a.allocUnsafe(32)

    sodium.crypto_generichash(holepunchSecret, NS.PEER_HOLEPUNCH, this.handshake.hash)

    return {
      isInitiator: this.isInitiator,
      publicKey: this.keyPair.publicKey,
      streamId: this.streamId,
      remotePublicKey: this.remotePublicKey,
      remoteId: NoiseSecretStream.id(this.handshake.hash, !this.isInitiator),
      holepunchSecret,
      hash: b4a.toBuffer(this.handshake.hash),
      rx: b4a.toBuffer(this.handshake.rx),
      tx: b4a.toBuffer(this.handshake.tx)
    }
  }
}
const c = require('compact-encoding')
const sodium = require('sodium-universal')
const RecordCache = require('record-cache')
const Cache = require('xache')
const b4a = require('b4a')
const unslab = require('unslab')

const { encodeUnslab } = require('./encode')
const m = require('./messages')
const { NS, ERROR } = require('./constants')

const EMPTY = b4a.alloc(0)
const TMP = b4a.allocUnsafe(32)
const MAX_BUMP_DRIFT = 60_000

module.exports = class Persistent {
  constructor(dht, opts) {
    this.dht = dht
    this.records = new RecordCache(opts.records)
    this.bumps = new Cache(opts.bumps)
    this.refreshes = new Cache(opts.refreshes)
    this.mutables = new Cache(opts.mutables)
    this.immutables = new Cache(opts.immutables)
  }

  onlookup(req) {
    if (!req.target) return

    const k = b4a.toString(req.target, 'hex')
    const records = this.records.get(k, 20)
    const bump = this.bumps.get(k) || 0
    const fwd = this.dht._router.get(k)

    if (fwd && records.length < 20) records.push(fwd.record)

    req.reply(records.length ? c.encode(m.lookupRawReply, { peers: records, bump }) : null)
  }

  onfindpeer(req) {
    if (!req.target) return
    const fwd = this.dht._router.get(req.target)
    req.reply(fwd ? fwd.record : null)
  }

  unannounce(target, publicKey) {
    const k = b4a.toString(target, 'hex')
    sodium.crypto_generichash(TMP, publicKey)

    if (b4a.equals(TMP, target)) this.dht._router.delete(k)
    this.records.remove(k, publicKey)
  }

  onunannounce(req) {
    if (!req.target || !req.token) return

    const unann = decode(m.announce, req.value)
    if (unann === null) return

    const { peer, signature } = unann
    if (!peer || !signature) return

    const signable = annSignable(req.target, req.token, this.dht.id, unann, NS.UNANNOUNCE)

    if (!sodium.crypto_sign_verify_detached(signature, signable, peer.publicKey)) {
      return
    }

    this.unannounce(req.target, peer.publicKey)
    req.reply(null, { token: false, closerNodes: false })
  }

  _onrefresh(token, req) {
    sodium.crypto_generichash(TMP, token)
    const activeRefresh = b4a.toString(TMP, 'hex')

    const r = this.refreshes.get(activeRefresh)
    if (!r) return

    const { announceSelf, k, record } = r
    const publicKey = record.subarray(0, 32)

    if (announceSelf) {
      this.dht._router.set(k, {
        relay: req.from,
        record,
        onconnect: null,
        onholepunch: null
      })
      this.records.remove(k, publicKey)
    } else {
      this.records.add(k, publicKey, record)
    }

    this.refreshes.delete(activeRefresh)
    this.refreshes.set(b4a.toString(token, 'hex'), r)

    req.reply(null, { token: false, closerNodes: false })
  }

  onannounce(req) {
    if (!req.target || !req.token || !this.dht.id) return

    const ann = decode(m.announce, req.value)
    if (ann === null) return

    const { peer, refresh, signature, bump } = ann

    if (!peer) {
      if (!refresh) return
      this._onrefresh(refresh, req)
      return
    }

    const signable = annSignable(req.target, req.token, this.dht.id, ann, NS.ANNOUNCE)

    if (!signature || !sodium.crypto_sign_verify_detached(signature, signable, peer.publicKey)) {
      return
    }

    // TODO: it would be potentially be more optimal to allow more than 3 addresses here for a findPeer response
    // and only use max 3 for a lookup reply
    if (peer.relayAddresses.length > 3) {
      peer.relayAddresses = peer.relayAddresses.slice(0, 3)
    }

    sodium.crypto_generichash(TMP, peer.publicKey)

    const k = b4a.toString(req.target, 'hex')
    const announceSelf = b4a.equals(TMP, req.target)
    const record = encodeUnslab(m.peer, peer)

    if (announceSelf) {
      this.dht._router.set(k, {
        relay: req.from,
        record,
        onconnect: null,
        onholepunch: null
      })
      this.records.remove(k, peer.publicKey)
    } else {
      const currentBump = this.bumps.get(k) || 0
      if (bump > currentBump && bump <= Date.now() + MAX_BUMP_DRIFT) this.bumps.set(k, bump)
      this.records.add(k, peer.publicKey, record)
    }

    if (refresh) {
      this.refreshes.set(b4a.toString(refresh, 'hex'), { k, record, announceSelf })
    }

    req.reply(null, { token: false, closerNodes: false })
  }

  onmutableget(req) {
    if (!req.target || !req.value) return

    let seq = 0
    try {
      seq = c.decode(c.uint, req.value)
    } catch {
      return
    }

    const k = b4a.toString(req.target, 'hex')
    const value = this.mutables.get(k)

    if (!value) {
      req.reply(null)
      return
    }

    const localSeq = c.decode(c.uint, value)
    req.reply(localSeq < seq ? null : value)
  }

  onmutableput(req) {
    if (!req.target || !req.token || !req.value) return

    const p = decode(m.mutablePutRequest, req.value)
    if (!p) return

    const { publicKey, seq, value, signature } = p

    const hash = b4a.allocUnsafe(32)
    sodium.crypto_generichash(hash, publicKey)
    if (!b4a.equals(hash, req.target)) return

    if (!value || !verifyMutable(signature, seq, value, publicKey)) return

    const k = b4a.toString(hash, 'hex')
    const local = this.mutables.get(k)

    if (local) {
      const existing = c.decode(m.mutableGetResponse, local)
      if (existing.value && existing.seq === seq && b4a.compare(value, existing.value) !== 0) {
        req.error(ERROR.SEQ_REUSED)
        return
      }
      if (seq < existing.seq) {
        req.error(ERROR.SEQ_TOO_LOW)
        return
      }
    }

    this.mutables.set(k, encodeUnslab(m.mutableGetResponse, { seq, value, signature }))
    req.reply(null)
  }

  onimmutableget(req) {
    if (!req.target) return

    const k = b4a.toString(req.target, 'hex')
    const value = this.immutables.get(k)

    req.reply(value || null)
  }

  onimmutableput(req) {
    if (!req.target || !req.token || !req.value) return

    const hash = b4a.alloc(32)
    sodium.crypto_generichash(hash, req.value)
    if (!b4a.equals(hash, req.target)) return

    const k = b4a.toString(hash, 'hex')
    this.immutables.set(k, unslab(req.value))

    req.reply(null)
  }

  onplugin(req) {
    if (!req.value) return

    const plugreq = decode(m.pluginRequest, req.value)
    if (plugreq === null) return

    const p = this.dht.plugins.get(plugreq.plugin)
    if (!p || p.version !== plugreq.version) return

    p.onrequest(plugreq, req)
  }

  destroy() {
    this.records.destroy()
    this.refreshes.destroy()
    this.mutables.destroy()
    this.immutables.destroy()
  }

  static signMutable(seq, value, keyPair) {
    const signable = b4a.allocUnsafe(32 + 32)
    const hash = signable.subarray(32)

    signable.set(NS.MUTABLE_PUT, 0)

    sodium.crypto_generichash(hash, c.encode(m.mutableSignable, { seq, value }))
    return sign(signable, keyPair)
  }

  static verifyMutable(signature, seq, value, publicKey) {
    return verifyMutable(signature, seq, value, publicKey)
  }

  static signAnnounce(target, token, id, ann, keyPair) {
    return sign(annSignable(target, token, id, ann, NS.ANNOUNCE), keyPair)
  }

  static signUnannounce(target, token, id, ann, keyPair) {
    return sign(annSignable(target, token, id, ann, NS.UNANNOUNCE), keyPair)
  }
}

function verifyMutable(signature, seq, value, publicKey) {
  const signable = b4a.allocUnsafe(32 + 32)
  const hash = signable.subarray(32)

  signable.set(NS.MUTABLE_PUT, 0)

  sodium.crypto_generichash(hash, c.encode(m.mutableSignable, { seq, value }))
  return sodium.crypto_sign_verify_detached(signature, signable, publicKey)
}

function annSignable(target, token, id, ann, ns) {
  const signable = b4a.allocUnsafe(32 + 32)
  const hash = signable.subarray(32)

  signable.set(ns, 0)

  sodium.crypto_generichash_batch(hash, [
    target,
    id,
    token,
    c.encode(m.peer, ann.peer), // note that this is the partial encoding of the announce message so we could just use that for perf
    ann.refresh || EMPTY
  ])

  return signable
}

function sign(signable, keyPair) {
  if (keyPair.sign) {
    return keyPair.sign(signable)
  }
  const secretKey = keyPair.secretKey ? keyPair.secretKey : keyPair
  const signature = b4a.allocUnsafe(64)
  sodium.crypto_sign_detached(signature, signable, secretKey)
  return signature
}

function decode(enc, val) {
  try {
    return val && c.decode(enc, val)
  } catch (err) {
    return null
  }
}
module.exports = class RawStreamSet {
  constructor(dht) {
    this._dht = dht

    this._prefix = 16 - 1 // 16 is the default stream-set side in udx
    this._streams = new Map()
  }

  get size() {
    return this._streams.size
  }

  [Symbol.iterator]() {
    return this._streams.values()
  }

  add(opts) {
    const self = this

    // TODO: we should prob have a udx helper for id generation, given the slight complexity
    // of the below. requires a PRNG in udx tho.

    let id = 0

    while (true) {
      id = (Math.random() * 0x100000000) >>> 0

      if (this._streams.has(id & this._prefix)) continue
      break
    }

    // always have ~50% change of rolling a free one
    if (2 * this._streams.size >= this._prefix) {
      // ie 0b11111 = 0b1111 + 1 + 0b1111
      this._prefix = 2 * this._prefix + 1

      // move the prefixes over
      const next = new Map()
      for (const stream of this._streams.values()) {
        next.set(stream.id & this._prefix, stream)
      }
      this._streams = next
    }

    const stream = this._dht.udx.createStream(id, opts)
    this._streams.set(id & this._prefix, stream)

    stream.on('close', onclose)

    return stream

    function onclose() {
      self._streams.delete(id & self._prefix)
    }
  }

  async clear() {
    const destroying = []

    for (const stream of this._streams.values()) {
      destroying.push(new Promise((resolve) => stream.once('close', resolve).destroy()))
    }

    await Promise.allSettled(destroying)
  }
}
const b4a = require('b4a')
const safetyCatch = require('safety-catch')

exports.clearRelayTimeout = clearRelayTimeout
exports.closeRelayConnection = closeRelayConnection
exports.confirmDirectUpgrade = confirmDirectUpgrade
exports.destroyRelayConnection = destroyRelayConnection

function clearRelayTimeout(connectionOrHandshake) {
  clearTimeout(connectionOrHandshake.relayTimeout)
  connectionOrHandshake.relayTimeout = null
}

function closeRelayConnection(connectionOrHandshake) {
  const socket = resetRelayConnection(connectionOrHandshake)

  if (socket) socket.end()
}

function confirmDirectUpgrade(connectionOrHandshake, rawStream, remoteChanging) {
  const cleanup = () => {
    rawStream.off('data', ondirect)
    rawStream.off('message', ondirect)
    rawStream.off('close', cleanup)
  }

  function ondirect() {
    if (!connectionOrHandshake.validUpgrade) {
      // reset, aka assume from direct
      connectionOrHandshake.validUpgrade = true
      return
    }

    cleanup()
    closeRelayConnection(connectionOrHandshake)
  }

  const confirm = () => {
    rawStream.on('data', ondirect)
    rawStream.on('message', ondirect)
    rawStream.once('close', cleanup)

    // Use a raw UDX message to make the peer observe the direct path without
    // writing application data into the secret stream.
    if (rawStream.trySend) rawStream.trySend(b4a.alloc(0))
  }

  if (!remoteChanging) {
    confirm()
    return
  }

  remoteChanging.then(confirm).catch(safetyCatch)
}

function destroyRelayConnection(connectionOrHandshake) {
  const socket = resetRelayConnection(connectionOrHandshake)

  if (socket) socket.destroy()
}

function resetRelayConnection(connectionOrHandshake) {
  if (connectionOrHandshake.relayTimeout) clearRelayTimeout(connectionOrHandshake)

  const socket = connectionOrHandshake.relaySocket
  // Drop relay references so the app connection no longer keeps relay state alive.
  connectionOrHandshake.relayToken = null
  connectionOrHandshake.relaySocket = null
  connectionOrHandshake.relayClient = null

  return socket
}
const c = require('compact-encoding')
const Cache = require('xache')
const safetyCatch = require('safety-catch')
const b4a = require('b4a')
const { handshake, holepunch } = require('./messages')
const { COMMANDS } = require('./constants')
const { BAD_HANDSHAKE_REPLY, BAD_HOLEPUNCH_REPLY } = require('./errors')

const FROM_CLIENT = 0
const FROM_SERVER = 1
const FROM_RELAY = 2
const FROM_SECOND_RELAY = 3
const REPLY = 4

// TODO: While the current design is very trustless in regards to clients/servers trusting the DHT,
// we should add a bunch of rate limits everywhere, especially including here to avoid bad users
// using a DHT node to relay traffic indiscriminately using the connect/holepunch messages.
// That's mostly from an abuse POV as none of the messsages do amplication.

module.exports = class Router {
  constructor(dht, opts) {
    this.dht = dht
    this.forwards = new Cache(opts.forwards)
  }

  set(target, state) {
    if (state.onpeerhandshake) {
      this.forwards.retain(toString(target), state)
    } else {
      this.forwards.set(toString(target), state)
    }
  }

  get(target) {
    return this.forwards.get(toString(target))
  }

  delete(target) {
    this.forwards.delete(toString(target))
  }

  destroy() {
    this.forwards.destroy()
  }

  async peerHandshake(target, { noise, peerAddress, relayAddress, socket, session }, to) {
    const dht = this.dht

    const requestValue = c.encode(handshake, {
      mode: FROM_CLIENT,
      noise,
      peerAddress,
      relayAddress
    })

    const res = await dht.request(
      { command: COMMANDS.PEER_HANDSHAKE, target, value: requestValue },
      to,
      { socket, session }
    )

    const hs = decode(handshake, res.value)
    if (
      !hs ||
      hs.mode !== REPLY ||
      to.host !== res.from.host ||
      to.port !== res.from.port ||
      !hs.noise
    ) {
      throw BAD_HANDSHAKE_REPLY()
    }

    return {
      noise: hs.noise,
      relayed: !!hs.peerAddress,
      serverAddress: hs.peerAddress || to,
      clientAddress: res.to
    }
  }

  async onpeerhandshake(req) {
    const hs = req.value && decode(handshake, req.value)
    if (!hs) return

    const { mode, noise, peerAddress, relayAddress } = hs

    const state = req.target && this.get(req.target)
    const isServer = !!(state && state.onpeerhandshake)
    const relay = state && state.relay

    if (isServer) {
      let reply = null
      try {
        reply = noise && (await state.onpeerhandshake({ noise, peerAddress }, req))
      } catch (e) {
        safetyCatch(e)
        return
      }
      if (!reply || !reply.noise) return
      const opts = { socket: reply.socket, closerNodes: false, token: false }

      switch (mode) {
        case FROM_CLIENT: {
          req.reply(
            c.encode(handshake, { mode: REPLY, noise: reply.noise, peerAddress: null }),
            opts
          )
          return
        }
        case FROM_RELAY: {
          req.relay(
            c.encode(handshake, { mode: FROM_SERVER, noise: reply.noise, peerAddress }),
            req.from,
            opts
          )
          return
        }
        case FROM_SECOND_RELAY: {
          if (!relayAddress) return
          req.relay(
            c.encode(handshake, { mode: FROM_SERVER, noise: reply.noise, peerAddress }),
            relayAddress,
            opts
          )
          return // eslint-disable-line
        }
      }
    } else {
      switch (mode) {
        case FROM_CLIENT: {
          // TODO: if no relay is known route closer to the target instead of timing out
          if (!noise) return
          if (!relay && !relayAddress) {
            // help the user route
            req.reply(null, { token: false, closerNodes: true })
            return
          }
          req.relay(
            c.encode(handshake, {
              mode: FROM_RELAY,
              noise,
              peerAddress: req.from,
              relayAddress: null
            }),
            relayAddress || relay
          )
          return
        }
        case FROM_RELAY: {
          if (!relay || !noise) return
          req.relay(
            c.encode(handshake, {
              mode: FROM_SECOND_RELAY,
              noise,
              peerAddress,
              relayAddress: req.from
            }),
            relay
          )
          return
        }
        case FROM_SERVER: {
          if (!peerAddress || !noise) return
          req.reply(
            c.encode(handshake, { mode: REPLY, noise, peerAddress: req.from, relayAddress: null }),
            { to: peerAddress, closerNodes: false, token: false }
          )
          return // eslint-disable-line
        }
      }
    }
  }

  async peerHolepunch(target, { id, payload, peerAddress, socket, session }, to) {
    const dht = this.dht
    const requestValue = c.encode(holepunch, {
      mode: FROM_CLIENT,
      id,
      payload,
      peerAddress
    })

    const res = await dht.request(
      { command: COMMANDS.PEER_HOLEPUNCH, target, value: requestValue },
      to,
      { socket, session }
    )

    const hp = decode(holepunch, res.value)
    if (!hp || hp.mode !== REPLY || to.host !== res.from.host || to.port !== res.from.port) {
      throw BAD_HOLEPUNCH_REPLY()
    }

    return {
      from: res.from,
      to: res.to,
      payload: hp.payload,
      peerAddress: hp.peerAddress || to
    }
  }

  async onpeerholepunch(req) {
    const hp = req.value && decode(holepunch, req.value)
    if (!hp) return

    const { mode, id, payload, peerAddress } = hp

    const state = req.target && this.get(req.target)
    const isServer = !!(state && state.onpeerholepunch)
    const relay = state && state.relay

    switch (mode) {
      case FROM_CLIENT: {
        if (!peerAddress && !relay) return
        req.relay(
          c.encode(holepunch, { mode: FROM_RELAY, id, payload, peerAddress: req.from }),
          peerAddress || relay
        )
        return
      }
      case FROM_RELAY: {
        if (!isServer || !peerAddress) return
        let reply = null
        try {
          reply = await state.onpeerholepunch({ id, payload, peerAddress }, req)
        } catch (e) {
          safetyCatch(e)
          return
        }
        if (!reply) return
        const opts = { socket: reply.socket, closerNodes: false, token: false }
        req.relay(
          c.encode(holepunch, { mode: FROM_SERVER, id: 0, payload: reply.payload, peerAddress }),
          req.from,
          opts
        )
        return
      }
      case FROM_SERVER: {
        req.reply(c.encode(holepunch, { mode: REPLY, id, payload, peerAddress: req.from }), {
          to: peerAddress,
          closerNodes: false,
          token: false
        })
        return // eslint-disable-line
      }
    }
  }
}

function decode(enc, val) {
  try {
    return c.decode(enc, val)
  } catch {
    return null
  }
}

function toString(t) {
  return typeof t === 'string' ? t : b4a.toString(t, 'hex')
}
const sodium = require('sodium-universal')
const b4a = require('b4a')
const { holepunchPayload } = require('./messages')

module.exports = class HolepunchPayload {
  constructor(holepunchSecret) {
    this._sharedSecret = holepunchSecret
    this._localSecret = b4a.allocUnsafe(32)

    sodium.randombytes_buf(this._localSecret)
  }

  decrypt(buffer) {
    const state = { start: 24, end: buffer.byteLength - 16, buffer }

    if (state.end <= state.start) return null

    const nonce = buffer.subarray(0, 24)
    const msg = state.buffer.subarray(state.start, state.end)
    const cipher = state.buffer.subarray(state.start)

    if (!sodium.crypto_secretbox_open_easy(msg, cipher, nonce, this._sharedSecret)) return null

    try {
      return holepunchPayload.decode(state)
    } catch {
      return null
    }
  }

  encrypt(payload) {
    const state = { start: 24, end: 24, buffer: null }
    holepunchPayload.preencode(state, payload)
    state.buffer = b4a.allocUnsafe(state.end + 16)

    const nonce = state.buffer.subarray(0, 24)
    const msg = state.buffer.subarray(state.start, state.end)
    const cipher = state.buffer.subarray(state.start)

    holepunchPayload.encode(state, payload)
    sodium.randombytes_buf(nonce)
    sodium.crypto_secretbox_easy(cipher, msg, nonce, this._sharedSecret)

    return state.buffer
  }

  token(addr) {
    const out = b4a.allocUnsafe(32)
    sodium.crypto_generichash(out, b4a.from(addr.host), this._localSecret)
    return out
  }
}
const DONE = Promise.resolve(true)
const DESTROYED = Promise.resolve(false)

module.exports = class Semaphore {
  constructor(limit = 1) {
    this.limit = limit
    this.active = 0
    this.waiting = []

    this.flushedPromise = null
    this.flushedResolve = null

    this.destroyed = false

    this._onwait = this._queueWaiting.bind(this)
    this._onflush = this._queueFlushed.bind(this)
  }

  _queueWaiting(resolve) {
    this.waiting.push(resolve)
  }

  _queueFlushed(resolve) {
    this.flushedResolve = resolve
  }

  wait() {
    if (this.destroyed === true) return DESTROYED

    if (this.active < this.limit && this.waiting.length === 0) {
      this.active++
      return DONE
    }

    return new Promise(this._onwait)
  }

  signal() {
    if (this.destroyed === true) return

    this.active--
    while (this.active < this.limit && this.waiting.length > 0 && this.destroyed === false) {
      this.active++
      this.waiting.shift()(true)
    }

    if (this.active === 0 && this.flushedResolve) {
      const resolve = this.flushedResolve
      this.flushedResolve = null
      this.flushedPromise = null
      resolve(true)
    }
  }

  async flush() {
    if (this.destroyed === true) return
    if (this.active === 0) return
    if (this.flushedPromise) return this.flushedPromise
    this.flushedPromise = new Promise(this._onflush)
    return this.flushedPromise
  }

  destroy() {
    this.destroyed = true
    this.active = 0
    while (this.waiting.length) this.waiting.pop()(false)
    if (this.flushedResolve) this.flushedResolve(false)
  }
}
const { EventEmitter } = require('events')
const safetyCatch = require('safety-catch')
const NoiseSecretStream = require('@hyperswarm/secret-stream')
const b4a = require('b4a')
const relay = require('blind-relay')
const NoiseWrap = require('./noise-wrap')
const Announcer = require('./announcer')
const { FIREWALL, ERROR } = require('./constants')
const { unslabbedHash } = require('./crypto')
const SecurePayload = require('./secure-payload')
const Holepuncher = require('./holepuncher')
const {
  clearRelayTimeout,
  confirmDirectUpgrade,
  destroyRelayConnection
} = require('./relay-connection')
const { isPrivate } = require('bogon')
const { ALREADY_LISTENING, NODE_DESTROYED, KEYPAIR_ALREADY_USED } = require('./errors')

const HANDSHAKE_CLEAR_WAIT = 10000
const HANDSHAKE_INITIAL_TIMEOUT = 10000

module.exports = class Server extends EventEmitter {
  constructor(dht, opts = {}) {
    super()

    this.dht = dht
    this.target = null

    this.closed = false
    this.firewall = opts.firewall || (() => false)
    this.holepunch = opts.holepunch || (() => true)
    this.relayThrough = opts.relayThrough || null
    this.relayKeepAlive = opts.relayKeepAlive || 5000
    this.pool = opts.pool || null
    this.createHandshake = opts.createHandshake || defaultCreateHandshake
    this.createSecretStream = opts.createSecretStream || defaultCreateSecretStream
    this.suspended = false
    this.handshakeClearWait = opts.handshakeClearWait || HANDSHAKE_CLEAR_WAIT

    this._shareLocalAddress = opts.shareLocalAddress !== false
    this._reusableSocket = !!opts.reusableSocket
    this._neverPunch = opts.holepunch === false // useful for fully disabling punching
    this._keyPair = null
    this._announcer = null
    this._connects = new Map()
    this._holepunches = []
    this._listening = null
    this._closing = null
  }

  get listening() {
    return this._listening !== null
  }

  get publicKey() {
    return this._keyPair && this._keyPair.publicKey
  }

  get relayAddresses() {
    return this._announcer ? this._announcer.relayAddresses : []
  }

  onconnection(encryptedSocket) {
    this.emit('connection', encryptedSocket)
  }

  async suspend({ log = noop } = {}) {
    log('Suspending hyperdht server')
    if (this._listening !== null) await this._listening
    log('Suspending hyperdht server (post listening)')
    this.suspended = true
    this._clearAll()
    return this._announcer ? this._announcer.suspend({ log }) : Promise.resolve()
  }

  async resume() {
    if (this._listening !== null) await this._listening
    this.suspended = false
    return this._announcer ? this._announcer.resume() : Promise.resolve()
  }

  address() {
    if (!this._keyPair) return null

    return {
      publicKey: this._keyPair.publicKey,
      host: this.dht.host,
      port: this.dht.port
    }
  }

  close() {
    if (this._closing) return this._closing
    this._closing = this._close()
    return this._closing
  }

  _gc() {
    this.dht.listening.delete(this)
    if (this.target) this.dht._router.delete(this.target)
  }

  async _stopListening() {
    try {
      if (this._announcer) await this._announcer.stop()
    } catch {
      // ignore
    }

    this._announcer = null
    this._listening = null
    this._keyPair = null
  }

  async _close() {
    if (this._listening === null) {
      this.closed = true
      this.emit('close')
      return
    }

    try {
      await this._listening
    } catch (err) {
      safetyCatch(err)
    }

    this._gc()
    this._clearAll()

    await this._stopListening()

    this.closed = true
    this.emit('close')
  }

  _clearAll() {
    while (this._holepunches.length > 0) {
      const h = this._holepunches.pop()
      if (h && h.puncher) h.puncher.destroy()
      if (h && h.clearing) clearTimeout(h.clearing)
      if (h && h.prepunching) clearTimeout(h.prepunching)
      if (h && h.rawStream) h.rawStream.destroy()
    }

    this._connects.clear()
  }

  async listen(keyPair = this.dht.defaultKeyPair, opts = {}) {
    if (this._listening !== null) throw ALREADY_LISTENING()
    if (this.dht.destroyed) throw NODE_DESTROYED()

    this._listening = this._listen(keyPair, opts)
    await this._listening
    return this
  }

  async _listen(keyPair, opts) {
    // From now on, the DHT object which created me is responsible for closing me
    this.dht.listening.add(this)

    try {
      await this.dht.bind()
      if (this._closing) return

      for (const s of this.dht.listening) {
        if (s._keyPair && b4a.equals(s._keyPair.publicKey, keyPair.publicKey)) {
          throw KEYPAIR_ALREADY_USED()
        }
      }

      this.target = unslabbedHash(keyPair.publicKey)
      this._keyPair = keyPair
      this._announcer = new Announcer(this.dht, keyPair, this.target, opts)

      this.dht._router.set(this.target, {
        relay: null,
        record: this._announcer.record,
        onpeerhandshake: this._onpeerhandshake.bind(this),
        onpeerholepunch: this._onpeerholepunch.bind(this)
      })

      // warm it up for now
      this._localAddresses().catch(safetyCatch)

      await this._announcer.start()
    } catch (err) {
      await this._stopListening()
      this._gc()
      throw err
    }

    if (this._closing) return
    if (this.suspended) await this._announcer.suspend()

    if (this._closing) return
    if (this.dht.destroyed) throw NODE_DESTROYED()

    if (this.pool) this.pool._attachServer(this)

    this.emit('listening')
  }

  refresh() {
    if (this._announcer && !this.suspended) this._announcer.refresh()
  }

  notifyOnline() {
    if (this._announcer) this._announcer.online.notify()
  }

  _localAddresses() {
    return this.dht.validateLocalAddresses(Holepuncher.localAddresses(this.dht.io.serverSocket))
  }

  async _addHandshake(k, noise, clientAddress, { to: serverAddress, socket }, direct) {
    let id = this._holepunches.indexOf(null)
    if (id === -1) id = this._holepunches.push(null) - 1

    const hs = {
      round: 0,
      reply: null,
      puncher: null,
      payload: null,
      rawStream: null,
      encryptedSocket: null,
      prepunching: null,
      firewalled: true,
      clearing: null,
      replyFromPuncher: false,
      onsocket: null,
      aborted: false,

      // Relay state
      relayTimeout: null,
      relayToken: null,
      relaySocket: null,
      relayClient: null,
      relayPaired: false,
      validUpgrade: true
    }

    this._holepunches[id] = hs

    const handshake = this.createHandshake(this._keyPair, null)

    let remotePayload
    try {
      remotePayload = await handshake.recv(noise)
    } catch (err) {
      safetyCatch(err)
      this._clearLater(hs, id, k)
      return null
    }

    if (this._closing || this.suspended) return null

    try {
      hs.firewalled = await this.firewall(handshake.remotePublicKey, remotePayload, clientAddress)
    } catch (err) {
      safetyCatch(err)
    }

    if (this._closing || this.suspended) return null

    if (hs.firewalled) {
      this._clearLater(hs, id, k)
      return null
    }

    const error =
      remotePayload.version === 1
        ? remotePayload.udx
          ? ERROR.NONE
          : ERROR.ABORTED
        : ERROR.VERSION_MISMATCH

    const addresses = []
    const ourRemoteAddr = this.dht.remoteAddress()
    const ourLocalAddrs = this._shareLocalAddress ? await this._localAddresses() : null

    if (this._closing || this.suspended) return null

    if (ourRemoteAddr) addresses.push(ourRemoteAddr)
    if (ourLocalAddrs) addresses.push(...ourLocalAddrs)

    if (error === ERROR.NONE) {
      hs.rawStream = this.dht.createRawStream({
        framed: true,
        firewall(socket, port, host) {
          if (!(port > 0 && port < 65536)) return true

          // Check if the traffic originated from the socket on which we're expecting relay traffic. If so,
          // we haven't hole punched yet and the other side is just sending us traffic through the relay.
          if (hs.relaySocket && isRelay(hs.relaySocket, socket, port, host)) {
            hs.validUpgrade = false
            return false
          }

          hs.onsocket(socket, port, host)
          hs.validUpgrade = true
          return false
        }
      })

      hs.rawStream.on('error', autoDestroy)

      // Handles the case where onsocket is never called, but the stream got setup
      // This can happen on a relayed connection which never connects directly
      // (onsocket is called there only when the direct connection is established)
      const onrawstreamclose = () => {
        if (this._closing) return
        this._clearLater(hs, id, k)
      }
      hs.rawStream.on('close', onrawstreamclose)

      hs.onsocket = (socket, port, host) => {
        if (hs.rawStream === null) return // Already hole punched

        this._clearLater(hs, id, k)

        if (hs.prepunching) {
          clearTimeout(hs.prepunching)
          hs.prepunching = null
        }

        if (this._reusableSocket && remotePayload.udx.reusableSocket) {
          this.dht._socketPool.routes.add(handshake.remotePublicKey, hs.rawStream)
        }

        hs.rawStream.removeListener('error', autoDestroy)
        hs.rawStream.removeListener('close', onrawstreamclose)

        if (hs.rawStream.connected) {
          const rawStream = hs.rawStream
          const remoteChanging = rawStream.changeRemote(socket, remotePayload.udx.id, port, host)
          confirmDirectUpgrade(hs, rawStream, remoteChanging)
        } else {
          hs.rawStream.connect(socket, remotePayload.udx.id, port, host)
          hs.encryptedSocket = this.createSecretStream(false, hs.rawStream, {
            handshake: h,
            keepAlive: this.dht.connectionKeepAlive
          })

          this.onconnection(hs.encryptedSocket)
        }

        if (hs.puncher) {
          hs.puncher.onabort = noop
          hs.puncher.destroy()
        }

        hs.rawStream = null
      }

      function autoDestroy() {
        if (hs.puncher) hs.puncher.destroy()
      }
    }

    const relayAddresses = this.relayAddresses
    const relayThrough = selectRelay(this.relayThrough)

    if (relayThrough) hs.relayToken = relay.token()

    try {
      hs.reply = await handshake.send({
        error,
        firewall: ourRemoteAddr ? FIREWALL.OPEN : FIREWALL.UNKNOWN,
        holepunch: ourRemoteAddr ? null : { id, relays: this._announcer.relays },
        addresses4: addresses,
        addresses6: null,
        udx: {
          reusableSocket: this._reusableSocket,
          id: hs.rawStream ? hs.rawStream.id : 0,
          seq: 0
        },
        secretStream: {},
        relayThrough: relayThrough ? { publicKey: relayThrough, token: hs.relayToken } : null,
        relayAddresses: relayAddresses.length ? relayAddresses : null
      })
    } catch (err) {
      safetyCatch(err)
      if (hs.rawStream) hs.rawStream.destroy()
      this._clearLater(hs, id, k)
      return null
    }

    if (this._closing || this.suspended) {
      if (hs.rawStream) hs.rawStream.destroy()
      return null
    }

    const h = handshake.final()

    if (error !== ERROR.NONE) {
      if (hs.rawStream) hs.rawStream.destroy()
      this._clearLater(hs, id, k)
      return hs
    }

    if (remotePayload.firewall === FIREWALL.OPEN || direct) {
      const sock = direct ? socket : this.dht.socket
      this.dht.stats.punches.open++
      hs.onsocket(sock, clientAddress.port, clientAddress.host)
      return hs
    }

    if (relayThrough || remotePayload.relayThrough) {
      this._relayConnection(hs, relayThrough, remotePayload, h)
    }

    const onabort = () => {
      hs.aborted = true
      if (hs.prepunching) clearTimeout(hs.prepunching)
      hs.prepunching = null
      if (hs.puncher) {
        hs.puncher.onabort = noop
        hs.puncher.destroy()
      }
      if (hs.rawStream.destroyed) {
        this._clearLater(hs, id, k)
        return
      }

      hs.rawStream.on('close', () => this._clearLater(hs, id, k))
      if (hs.relayToken === null) hs.rawStream.destroy()
    }

    if (!direct && clientAddress.host === serverAddress.host) {
      const clientAddresses = remotePayload.addresses4.filter((addr) => isPrivate(addr.host))

      if (clientAddresses.length > 0 && this._shareLocalAddress) {
        const myAddresses = await this._localAddresses()
        const addr = Holepuncher.matchAddress(myAddresses, clientAddresses)

        if (addr) {
          hs.payload = new SecurePayload(h.holepunchSecret)
          setupHolepuncher(this.dht, hs, remotePayload.firewall, onabort)
          hs.prepunching = setTimeout(onabort, HANDSHAKE_INITIAL_TIMEOUT)
          return hs
        }
      }
    }

    if (this._closing || this.suspended) return null

    if (ourRemoteAddr || this._neverPunch) {
      hs.prepunching = setTimeout(onabort, HANDSHAKE_INITIAL_TIMEOUT)
      return hs
    }

    hs.payload = new SecurePayload(h.holepunchSecret)
    setupHolepuncher(this.dht, hs, remotePayload.firewall, onabort)
    hs.replyFromPuncher = true
    hs.prepunching = setTimeout(hs.puncher.destroy.bind(hs.puncher), HANDSHAKE_INITIAL_TIMEOUT)

    return hs
  }

  _clearLater(hs, id, k) {
    if (hs.clearing) return
    hs.clearing = setTimeout(() => this._clear(hs, id, k), this.handshakeClearWait)
  }

  _clear(hs, id, k) {
    if (id >= this._holepunches.length || this._holepunches[id] !== hs) return
    if (hs.clearing) clearTimeout(hs.clearing)

    this._holepunches[id] = null
    while (
      this._holepunches.length > 0 &&
      this._holepunches[this._holepunches.length - 1] === null
    ) {
      this._holepunches.pop()
    }
    this._connects.delete(k)
  }

  async _onpeerhandshake({ noise, peerAddress }, req) {
    const k = b4a.toString(noise, 'hex')

    // The next couple of statements MUST run within the same tick to prevent
    // a malicious peer from flooding us with handshakes.
    let p = this._connects.get(k)
    if (!p) {
      p = this._addHandshake(k, noise, peerAddress || req.from, req, !peerAddress)
      this._connects.set(k, p)
    }

    const h = await p
    if (!h) return null

    if (this._closing !== null || this.suspended) return null

    // Routed handshake replies advertise the socket they are sent from as the
    // server address. Same-LAN prepunch also creates a puncher, but it must
    // keep advertising the normal server socket so the LAN shortcut can open.
    return { socket: h.replyFromPuncher ? h.puncher.socket : null, noise: h.reply }
  }

  async _onpeerholepunch({ id, peerAddress, payload }, req) {
    const h = id < this._holepunches.length ? this._holepunches[id] : null
    if (!h) return null

    if (!peerAddress || this._closing !== null || this.suspended) return null
    if (!h.payload) return this._abort(h) // not opened

    const remotePayload = h.payload.decrypt(payload)
    if (!remotePayload) return null

    const p = h.puncher
    if (!p || !p.socket) return this._abort(h) // not opened

    const isServerRelay = this._announcer.isRelay(req.from)
    const { error, firewall, round, punching, addresses, remoteAddress, remoteToken } =
      remotePayload

    if (error !== ERROR.NONE) {
      // We actually do not need to set the round here, but just do it for consistency.
      if (round >= h.round) h.round = round
      return this._abort(h)
    }

    const token = h.payload.token(peerAddress)
    const echoed = isServerRelay && !!remoteToken && b4a.equals(token, remoteToken)

    // Update our heuristics here
    if (req.socket === p.socket) {
      p.nat.add(req.to, req.from)
    }

    if (round >= h.round) {
      h.round = round
      p.updateRemote({ punching, firewall, addresses, verified: echoed ? peerAddress.host : null })
    }

    // Wait for the analyzer to reach a conclusion...
    let stable = await p.analyze(false)
    if (p.destroyed) return null

    if (!p.remoteHolepunching && !stable) {
      stable = await p.analyze(true)
      if (p.destroyed) return null
      if (!stable) return this._abort(h)
    }

    // Fast mode! If we are consistent and the remote has opened a session to us (remoteAddress)
    // then fire a quick punch back. Note the await here just waits for the udp socket to flush.
    if (
      isConsistent(p.nat.firewall) &&
      remoteAddress &&
      hasSameAddr(p.nat.addresses, remoteAddress)
    ) {
      await p.ping(peerAddress)
      if (p.destroyed) return null
    }

    // Remote said they are punching (or willing to), so we will punch as well.
    // Note that this returns when the punching has STARTED, so no guarantee
    // we will have a connection after this promise etc.
    if (p.remoteHolepunching) {
      // TODO: still continue here if a local connection might work, but then do not holepunch...
      if (!this.holepunch(p.remoteFirewall, p.nat.firewall, p.remoteAddresses, p.nat.addresses)) {
        return p.destroyed ? null : this._abort(h)
      }

      if (h.prepunching) {
        clearTimeout(h.prepunching)
        h.prepunching = null
      }

      if (p.remoteFirewall >= FIREWALL.RANDOM || p.nat.firewall >= FIREWALL.RANDOM) {
        if (
          this.dht._randomPunches >= this.dht._randomPunchLimit ||
          Date.now() - this.dht._lastRandomPunch < this.dht._randomPunchInterval
        ) {
          if (!h.relayToken) return this._abort(h, ERROR.TRY_LATER)
          return {
            socket: p.socket,
            payload: h.payload.encrypt({
              error: ERROR.TRY_LATER,
              firewall: p.nat.firewall,
              round: h.round,
              connected: p.connected,
              punching: p.punching,
              addresses: p.nat.addresses,
              remoteAddress: null,
              token: isServerRelay ? token : null,
              remoteToken: remotePayload.token
            })
          }
        }
      }

      const punching = await p.punch()
      if (p.destroyed) return null
      if (!punching) return this._abort(h)
    }

    // Freeze that analysis as soon as we have a result we are giving to the other peer
    if (p.nat.firewall !== FIREWALL.UNKNOWN) {
      p.nat.freeze()
    }

    return {
      socket: p.socket,
      payload: h.payload.encrypt({
        error: ERROR.NONE,
        firewall: p.nat.firewall,
        round: h.round,
        connected: p.connected,
        punching: p.punching,
        addresses: p.nat.addresses,
        remoteAddress: null,
        token: isServerRelay ? token : null,
        remoteToken: remotePayload.token
      })
    }
  }

  _abort(h, error = ERROR.ABORTED) {
    if (!h.payload) {
      if (h.puncher) h.puncher.destroy()
      return null
    }

    const payload = h.payload.encrypt({
      error,
      firewall: FIREWALL.UNKNOWN,
      round: h.round,
      connected: false,
      punching: false,
      addresses: null,
      remoteAddress: null,
      token: null,
      remoteToken: null
    })

    if (h.puncher) h.puncher.destroy()

    return { socket: this.dht.socket, payload }
  }

  _relayConnection(hs, relayThrough, remotePayload, h) {
    this.dht.stats.relaying.attempts++

    let isInitiator
    let publicKey
    let token

    if (relayThrough) {
      isInitiator = true
      publicKey = relayThrough
      token = hs.relayToken
    } else {
      isInitiator = false
      publicKey = remotePayload.relayThrough.publicKey
      token = remotePayload.relayThrough.token
    }

    hs.relayToken = token
    hs.relaySocket = this.dht.connect(publicKey)
    hs.relaySocket.setKeepAlive(this.relayKeepAlive)
    hs.relayClient = relay.Client.from(hs.relaySocket, { id: hs.relaySocket.publicKey })
    hs.relayTimeout = setTimeout(onabort, 15000)

    hs.relayClient
      .pair(isInitiator, token, hs.rawStream)
      .on('error', onabort)
      .on('data', (remoteId) => {
        if (hs.relayTimeout) clearRelayTimeout(hs)
        if (hs.rawStream === null) {
          onabort(null)
          return
        }

        hs.relayPaired = true
        this.dht.stats.relaying.successes++

        if (hs.prepunching) clearTimeout(hs.prepunching)
        hs.prepunching = null

        const { remotePort, remoteHost, socket } = hs.relaySocket.rawStream

        hs.rawStream
          .on('close', () => destroyRelayConnection(hs))
          .connect(socket, remoteId, remotePort, remoteHost)

        hs.encryptedSocket = this.createSecretStream(false, hs.rawStream, {
          handshake: h,
          keepAlive: this.dht.connectionKeepAlive
        })

        this.onconnection(hs.encryptedSocket)
      })

    const dht = this.dht
    function onabort() {
      if (!hs.relayPaired) dht.stats.relaying.aborts++
      destroyRelayConnection(hs)
      if (hs.aborted && hs.rawStream) hs.rawStream.destroy()
    }
  }
}

function isConsistent(fw) {
  return fw === FIREWALL.OPEN || fw === FIREWALL.CONSISTENT
}

function hasSameAddr(addrs, other) {
  if (addrs === null) return false

  for (const addr of addrs) {
    if (addr.port === other.port && addr.host === other.host) return true
  }
  return false
}

function defaultCreateHandshake(keyPair, remotePublicKey) {
  return new NoiseWrap(keyPair, remotePublicKey)
}

function defaultCreateSecretStream(isInitiator, rawStream, opts) {
  return new NoiseSecretStream(isInitiator, rawStream, opts)
}

function setupHolepuncher(dht, hs, remoteFirewall, onabort) {
  if (hs.puncher) return

  hs.puncher = new Holepuncher(dht, dht.session(), false, remoteFirewall)
  hs.puncher.onconnect = hs.onsocket
  hs.puncher.onabort = onabort
}

function isRelay(relaySocket, socket, port, host) {
  const stream = relaySocket.rawStream
  if (!stream) return false
  if (stream.socket !== socket) return false
  return port === stream.remotePort && host === stream.remoteHost
}

function selectRelay(relayThrough) {
  if (typeof relayThrough === 'function') relayThrough = relayThrough()
  if (relayThrough === null) return null
  if (Array.isArray(relayThrough)) {
    return relayThrough[Math.floor(Math.random() * relayThrough.length)]
  }
  return relayThrough
}

function noop() {}
module.exports = class Sleeper {
  constructor() {
    this._timeout = null
    this._resolve = null

    this._start = (resolve) => {
      this._resolve = resolve
    }

    this._trigger = () => {
      if (this._resolve === null) return
      const resolve = this._resolve
      this._timeout = null
      this._resolve = null
      resolve()
    }
  }

  pause(ms) {
    const p = new Promise(this._start)
    if (this._timeout !== null) {
      clearTimeout(this._timeout)
      this._trigger()
    }
    this._timeout = setTimeout(this._trigger, ms)
    return p
  }

  resume() {
    if (this._timeout !== null) {
      clearTimeout(this._timeout)
      this._trigger()
    }
  }
}
const b4a = require('b4a')

const LINGER_TIME = 3000

module.exports = class SocketPool {
  constructor(dht, host) {
    this._dht = dht
    this._sockets = new Map()
    this._lingering = new Set() // updated by the ref
    this._host = host

    this.routes = new SocketRoutes(this)
  }

  _onmessage(ref, data, address) {
    this._dht.onmessage(ref.socket, data, address)
  }

  _add(ref) {
    this._sockets.set(ref.socket, ref)
  }

  _remove(ref) {
    this._sockets.delete(ref.socket)
    this._lingering.delete(ref)
  }

  lookup(socket) {
    return this._sockets.get(socket) || null
  }

  setReusable(socket, bool) {
    const ref = this.lookup(socket)
    if (ref) ref.reusable = bool
  }

  acquire() {
    // TODO: Enable socket reuse
    return new SocketRef(this)
  }

  async destroy() {
    const closing = []

    for (const ref of this._sockets.values()) {
      ref._unlinger()
      closing.push(ref.socket.close())
    }

    await Promise.allSettled(closing)
  }
}

class SocketRoutes {
  constructor(pool) {
    this._pool = pool
    this._routes = new Map()
  }

  add(publicKey, rawStream) {
    if (rawStream.socket) this._onconnect(publicKey, rawStream)
    else rawStream.on('connect', this._onconnect.bind(this, publicKey, rawStream))
  }

  get(publicKey) {
    const id = b4a.toString(publicKey, 'hex')
    const route = this._routes.get(id)
    if (!route) return null
    return route
  }

  _onconnect(publicKey, rawStream) {
    const id = b4a.toString(publicKey, 'hex')
    const socket = rawStream.socket

    let route = this._routes.get(id)

    if (!route) {
      const gc = () => {
        if (this._routes.get(id) === route) this._routes.delete(id)
        socket.removeListener('close', gc)
      }

      route = {
        socket,
        address: { host: rawStream.remoteHost, port: rawStream.remotePort },
        gc
      }

      this._routes.set(id, route)
      socket.on('close', gc)
    }

    this._pool.setReusable(socket, true)

    rawStream.on('error', () => {
      this._pool.setReusable(socket, false)
      if (!route) route = this._routes.get(id)
      if (route && route.socket === socket) route.gc()
    })
  }
}

// TODO: we should just make some "user data" object on udx to allow to attach this info
class SocketRef {
  constructor(pool) {
    this._pool = pool

    // Events
    this.onholepunchmessage = noop

    // Whether it should teardown immediately or wait a bit
    this.reusable = false

    this.socket = pool._dht.udx.createSocket()
    this.socket
      .on('close', this._onclose.bind(this))
      .on('message', this._onmessage.bind(this))
      .on('idle', this._onidle.bind(this))
      .on('busy', this._onbusy.bind(this))
      .bind(0, this._pool._host)

    this._refs = 1
    this._released = false
    this._closed = false

    this._timeout = null
    this._wasBusy = false

    this._pool._add(this)
  }

  _onclose() {
    this._pool._remove(this)
  }

  _onmessage(data, address) {
    if (data.byteLength > 1) {
      this._pool._onmessage(this, data, address)
    } else {
      this.onholepunchmessage(data, address, this)
    }
  }

  _onidle() {
    this._closeMaybe()
  }

  _onbusy() {
    this._wasBusy = true
    this._unlinger()
  }

  _reset() {
    this.onholepunchmessage = noop
  }

  _closeMaybe() {
    if (this._refs === 0 && this.socket.idle && !this._timeout) this._close()
  }

  _lingeringClose() {
    this._pool._lingering.delete(this)
    this._timeout = null
    this._closeMaybe()
  }

  _close() {
    this._unlinger()

    if (this.reusable && this._wasBusy) {
      this._wasBusy = false
      this._pool._lingering.add(this)
      this._timeout = setTimeout(this._lingeringClose.bind(this), LINGER_TIME)
      return
    }

    this._closed = true
    this.socket.close()
  }

  _unlinger() {
    if (this._timeout !== null) {
      clearTimeout(this._timeout)
      this._pool._lingering.delete(this)
      this._timeout = null
    }
  }

  get free() {
    return this._refs === 0
  }

  active() {
    this._refs++
    this._unlinger()
  }

  inactive() {
    this._refs--
    this._closeMaybe()
  }

  address() {
    return this.socket.address()
  }

  release() {
    if (this._released) return

    this._released = true
    this._reset()

    this._refs--
    this._closeMaybe()
  }
}

function noop() {}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "hyperdht",
  "version": "6.33.0",
  "description": "The DHT powering Hyperswarm",
  "main": "index.js",
  "browser": "browser.js",
  "bin": {
    "hyperdht": "./bin.js"
  },
  "files": [
    "index.js",
    "browser.js",
    "testnet.js",
    "bin.js",
    "lib/**.js"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    },
    "child_process": {
      "bare": "bare-node-child-process",
      "default": "child_process"
    }
  },
  "dependencies": {
    "@hyperswarm/secret-stream": "^6.6.2",
    "b4a": "^1.3.1",
    "bare-events": "^2.2.0",
    "blind-relay": "^1.3.0",
    "bogon": "^1.0.0",
    "compact-encoding": "^3.0.0",
    "dht-rpc": "^6.15.1",
    "hypercore-crypto": "^3.3.0",
    "hypercore-id-encoding": "^1.2.0",
    "hyperdht-address": "^1.0.1",
    "noise-curve-ed": "^2.0.0",
    "noise-handshake": "^4.0.0",
    "record-cache": "^1.1.1",
    "safety-catch": "^1.0.1",
    "signal-promise": "^1.0.3",
    "sodium-universal": "^5.0.1",
    "streamx": "^2.16.1",
    "unslab": "^1.3.0",
    "xache": "^1.1.0"
  },
  "devDependencies": {
    "bare-node-child-process": "^1.0.1",
    "brittle": "^3.0.0",
    "graceful-goodbye": "^1.3.0",
    "newline-decoder": "^1.0.2",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "test": "prettier --check . && node test/all.js",
    "test:bare": "bare test/all.js",
    "test:generate": "brittle -r test/all.js test/*.js",
    "integration": "brittle test/integration/*.js",
    "end-to-end": "brittle test/end-to-end/*.js"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "directories": {
    "lib": "lib",
    "test": "test"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/hyperdht.git"
  },
  "keywords": [],
  "bugs": {
    "url": "https://github.com/holepunchto/hyperdht/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperdht#readme"
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "hyperschema",
  "version": "1.21.0",
  "description": "Create registries of declarative compact-encoding schemas",
  "files": [
    "lib/*.js",
    "builder.mjs",
    "builder.cjs",
    "runtime.mjs",
    "runtime.cjs",
    "primitives.mjs",
    "primitives.cjs"
  ],
  "exports": {
    "./package": "./package.json",
    ".": {
      "import": "./builder.mjs",
      "default": "./builder.cjs"
    },
    "./runtime": {
      "import": "./runtime.mjs",
      "default": "./runtime.cjs"
    },
    "./primitives": {
      "import": "./primitives.mjs",
      "default": "./primitives.cjs"
    }
  },
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    }
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test/index.js",
    "test:bare": "prettier . --check && bare test/index.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/hyperschema.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/hyperschema/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperschema#readme",
  "dependencies": {
    "bare-fs": "^4.0.1",
    "compact-encoding": "^3.0.0",
    "generate-object-property": "^2.0.0",
    "generate-string": "^1.0.1"
  },
  "devDependencies": {
    "brittle": "^3.7.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "test-tmp": "^1.3.0"
  }
}
module.exports = {
  c: require('compact-encoding')
}
const { EventEmitter } = require('events')
const { getStreamError } = require('streamx')
const DHT = require('hyperdht')
const spq = require('shuffled-priority-queue')
const b4a = require('b4a')
const unslab = require('unslab')

const PeerInfo = require('./lib/peer-info')
const RetryTimer = require('./lib/retry-timer')
const ConnectionSet = require('./lib/connection-set')
const PeerDiscovery = require('./lib/peer-discovery')

const MAX_PEERS = 64
const MAX_PARALLEL = 3
const MAX_CLIENT_CONNECTIONS = Infinity // TODO: Change
const MAX_SERVER_CONNECTIONS = Infinity

const ERR_MISSING_TOPIC = 'Topic is required and must be a 32-byte buffer'
const ERR_DESTROYED = 'Swarm has been destroyed'
const ERR_DUPLICATE = 'Duplicate connection'
const ERR_FIREWALL = 'Peer is firewalled'

module.exports = class Hyperswarm extends EventEmitter {
  constructor(opts = {}) {
    super()
    const {
      seed,
      relayThrough,
      keyPair = DHT.keyPair(seed),
      maxPeers = MAX_PEERS,
      maxClientConnections = MAX_CLIENT_CONNECTIONS,
      maxServerConnections = MAX_SERVER_CONNECTIONS,
      maxParallel = MAX_PARALLEL,
      firewall = allowAll
    } = opts
    this.keyPair = keyPair

    this.dht =
      opts.dht ||
      new DHT({
        bootstrap: opts.bootstrap,
        nodes: opts.nodes,
        port: opts.port,
        deferRandomPunch: opts.deferRandomPunch,
        randomPunchInterval: opts.randomPunchInterval
      })
    this.server = this.dht.createServer(
      {
        firewall: this._handleFirewall.bind(this),
        relayThrough: this._maybeRelayConnection.bind(this),
        handshakeClearWait: opts.handshakeClearWait
      },
      this._handleServerConnection.bind(this)
    )

    this.destroyed = false
    this.suspended = false
    this.maxPeers = maxPeers
    this.maxClientConnections = maxClientConnections
    this.maxServerConnections = maxServerConnections
    this.maxParallel = maxParallel
    this.relayThrough = relayThrough ? toRelayFunction(relayThrough) : null

    this.connecting = 0
    this.connections = new Set()
    this.peers = new Map()
    this.explicitPeers = new Set()
    this.listening = null
    this.stats = {
      updates: 0,
      connects: {
        client: {
          opened: 0,
          closed: 0,
          attempted: 0
        },
        server: {
          // Note: there is no notion of 'attempts' for server connections
          opened: 0,
          closed: 0
        }
      },
      bannedPeers: 0
    }

    this._discovery = new Map()
    this._timer = new RetryTimer(this._requeue.bind(this), {
      backoffs: opts.backoffs,
      jitter: opts.jitter
    })
    this._queue = spq()

    this._allConnections = new ConnectionSet()
    this._pendingFlushes = []
    this._flushTick = 0

    this._drainingQueue = false
    this._clientConnections = 0
    this._serverConnections = 0
    this._firewall = firewall

    this.dht.on('network-change', this._handleNetworkChange.bind(this))
    this.dht.on('network-update', this._handleNetworkUpdate.bind(this))
    this.on('update', this._handleUpdate)
  }

  _maybeRelayConnection(force) {
    if (!this.relayThrough) return null
    return this.relayThrough(force, this)
  }

  _enqueue(peerInfo) {
    if (peerInfo.queued) return
    peerInfo.queued = true
    peerInfo._flushTick = this._flushTick
    this._queue.add(peerInfo)

    this._attemptClientConnections()
  }

  _requeue(batch) {
    if (this.suspended) return
    for (const peerInfo of batch) {
      peerInfo.waiting = false

      if (
        peerInfo._updatePriority() === false ||
        this._allConnections.has(peerInfo.publicKey) ||
        peerInfo.queued
      ) {
        continue
      }
      peerInfo.queued = true
      peerInfo._flushTick = this._flushTick
      this._queue.add(peerInfo)
    }

    this._attemptClientConnections()
  }

  _flushMaybe(peerInfo) {
    for (let i = 0; i < this._pendingFlushes.length; i++) {
      const flush = this._pendingFlushes[i]
      if (peerInfo._flushTick > flush.tick) continue
      if (--flush.missing > 0) continue
      flush.onflush(true)
      this._pendingFlushes.splice(i--, 1)
    }
  }

  _withinMaxPeers() {
    const e = this.explicitPeers.size
    const factor = e === 0 ? 1 : e < 2 ? 2 : e < 4 ? 3 : 4
    return factor * this._allConnections.size < this.maxPeers
  }

  _flushAllMaybe() {
    if (
      this.connecting > 0 ||
      (this._withinMaxPeers() && this._clientConnections < this.maxClientConnections)
    ) {
      return false
    }

    while (this._pendingFlushes.length) {
      const flush = this._pendingFlushes.pop()
      flush.onflush(true)
    }

    return true
  }

  _shouldConnectExplicit() {
    return !this.destroyed && !this.suspended && this.connecting < this.maxParallel
  }

  _shouldConnect() {
    return (
      !this.destroyed &&
      !this.suspended &&
      this.connecting < this.maxParallel &&
      this._withinMaxPeers() &&
      this._clientConnections < this.maxClientConnections
    )
  }

  _shouldRequeue(peerInfo) {
    if (this.suspended) return false
    if (peerInfo.explicit) return true
    for (const topic of peerInfo.topics) {
      if (this._discovery.has(b4a.toString(topic, 'hex')) && !this.destroyed) {
        return true
      }
    }
    return false
  }

  _connect(peerInfo, queued) {
    if (peerInfo.banned || this._allConnections.has(peerInfo.publicKey)) {
      if (queued) this._flushMaybe(peerInfo)
      return
    }

    // TODO: Support async firewalling at some point.
    if (this._handleFirewall(peerInfo.publicKey, null)) {
      if (queued) this._flushMaybe(peerInfo)
      return
    }

    const relayThrough = this._maybeRelayConnection(peerInfo.forceRelaying)
    const conn = this.dht.connect(peerInfo.publicKey, {
      relayAddresses: peerInfo.relayAddresses,
      keyPair: this.keyPair,
      relayThrough
    })
    this._allConnections.add(conn)

    this.stats.connects.client.attempted++

    this.connecting++
    this._clientConnections++
    let opened = false

    const onerror = (err) => {
      if (this.relayThrough && shouldForceRelaying(err.code)) {
        peerInfo.forceRelaying = true
        // Reset the attempts in order to fast connect to relay
        peerInfo.attempts = 0
      }
    }

    // Removed once a connection is opened
    conn.on('error', onerror)

    conn.on('open', () => {
      opened = true
      this.stats.connects.client.opened++

      this._connectDone()
      this.connections.add(conn)
      conn.removeListener('error', onerror)
      peerInfo._connected()
      peerInfo.client = true
      this.emit('connection', conn, peerInfo)
      if (queued) this._flushMaybe(peerInfo)

      this.emit('update')
    })
    conn.on('close', () => {
      if (!opened) this._connectDone()
      this.stats.connects.client.closed++

      const err = getStreamError(conn)
      if (shouldBan(err)) {
        this._banPeer(peerInfo, true, err)
      }

      this.connections.delete(conn)
      this._allConnections.delete(conn)
      this._clientConnections--
      peerInfo._disconnected()

      peerInfo.waiting = this._shouldRequeue(peerInfo) && this._timer.add(peerInfo)
      this._maybeDeletePeer(peerInfo)

      if (!opened && queued) this._flushMaybe(peerInfo)

      this._attemptClientConnections()

      this.emit('update')
    })

    this.emit('update')
  }

  _connectDone() {
    this.connecting--

    if (this.connecting < this.maxParallel) this._attemptClientConnections()
    if (this.connecting === 0) this._flushAllMaybe()
  }

  // Called when the PeerQueue indicates a connection should be attempted.
  _attemptClientConnections() {
    // Guard against re-entries - unsure if it still needed but doesn't hurt
    if (this._drainingQueue || this.suspended) return
    this._drainingQueue = true

    for (const peerInfo of this.explicitPeers) {
      if (!this._shouldConnectExplicit()) break
      if (
        peerInfo.attempts >= 5 ||
        Date.now() - peerInfo.disconnectedTime < peerInfo.attempts * 1000
      ) {
        continue
      }
      this._connect(peerInfo, false)
    }

    while (this._queue.length && this._shouldConnect()) {
      const peerInfo = this._queue.shift()
      peerInfo.queued = false
      this._connect(peerInfo, true)
    }
    this._drainingQueue = false
    if (this.connecting === 0) this._flushAllMaybe()
  }

  _handleFirewall(remotePublicKey, payload) {
    if (b4a.equals(remotePublicKey, this.keyPair.publicKey)) return true

    let peerInfo = this.peers.get(b4a.toString(remotePublicKey, 'hex'))
    if (peerInfo && peerInfo.banned) return true

    const firewalled = this._firewall(remotePublicKey, payload)
    if (firewalled) {
      if (!peerInfo) peerInfo = this._upsertPeer(remotePublicKey)
      this._banPeer(peerInfo, true, new Error(ERR_FIREWALL))
    }

    return firewalled
  }

  _handleServerConnectionSwap(existing, conn) {
    let closed = false

    existing.on('close', () => {
      if (closed) return

      conn.removeListener('error', noop)
      conn.removeListener('close', onclose)

      this._handleServerConnection(conn)
    })

    conn.on('error', noop)
    conn.on('close', onclose)

    function onclose() {
      closed = true
    }
  }

  // Called when the DHT receives a new server connection.
  _handleServerConnection(conn) {
    if (this.destroyed || this.suspended) {
      // TODO: Investigate why a final server connection can be received after close
      conn.on('error', noop)
      return conn.destroy(ERR_DESTROYED)
    }

    const existing = this._allConnections.get(conn.remotePublicKey)

    if (existing) {
      // If both connections are from the same peer,
      // - pick the new one if the existing stream is already established (has sent and received bytes),
      //   because the other client must have lost that connection and be reconnecting
      // - otherwise, pick the one thats expected to initiate in a tie break
      const existingIsOutdated = existing.rawBytesRead > 0 && existing.rawBytesWritten > 0
      const expectedInitiator = b4a.compare(conn.publicKey, conn.remotePublicKey) > 0
      const keepNew = existingIsOutdated || expectedInitiator === conn.isInitiator

      if (keepNew === false) {
        existing.sendKeepAlive()
        conn.on('error', noop)
        conn.destroy(new Error(ERR_DUPLICATE))
        return
      }

      existing.on('error', noop)
      existing.destroy(new Error(ERR_DUPLICATE))
      this._handleServerConnectionSwap(existing, conn)
      return
    }

    // When reaching here, the connection will always be 'opened' next tick
    this.stats.connects.server.opened++

    const peerInfo = this._upsertPeer(conn.remotePublicKey, null)

    this.connections.add(conn)
    this._allConnections.add(conn)
    this._serverConnections++

    conn.on('close', () => {
      const err = getStreamError(conn)
      if (shouldBan(err)) {
        this._banPeer(peerInfo, true, err)
      }

      this.connections.delete(conn)
      this._allConnections.delete(conn)
      this._serverConnections--
      this.stats.connects.server.closed++

      this._maybeDeletePeer(peerInfo)

      this._attemptClientConnections()

      this.emit('update')
    })
    peerInfo.client = false
    this.emit('connection', conn, peerInfo)

    this.emit('update')
  }

  _upsertPeer(publicKey, relayAddresses) {
    if (b4a.equals(publicKey, this.keyPair.publicKey)) return null
    const keyString = b4a.toString(publicKey, 'hex')
    let peerInfo = this.peers.get(keyString)

    if (peerInfo) {
      peerInfo.relayAddresses = relayAddresses // new is always better
      return peerInfo
    }

    peerInfo = new PeerInfo({
      publicKey,
      relayAddresses
    })

    this.peers.set(keyString, peerInfo)
    return peerInfo
  }

  _handleUpdate() {
    this.stats.updates++
  }

  _maybeDeletePeer(peerInfo) {
    if (!peerInfo.shouldGC()) return

    const hasActiveConn = this._allConnections.has(peerInfo.publicKey)
    if (hasActiveConn) return

    const keyString = b4a.toString(peerInfo.publicKey, 'hex')
    this.peers.delete(keyString)
  }

  /*
   * Called when a peer is actively discovered during a lookup.
   *
   * Three conditions:
   *  1. Not a known peer -- insert into queue
   *  2. A known peer with normal priority -- do nothing
   *  3. A known peer with low priority -- bump priority, because it's been rediscovered
   */
  _handlePeer(peer, topic) {
    const peerInfo = this._upsertPeer(peer.publicKey, peer.relayAddresses)
    if (peerInfo) peerInfo._topic(topic)
    if (!peerInfo || this._allConnections.has(peer.publicKey)) return
    if (!peerInfo.prioritized || peerInfo.server) peerInfo._reset()
    if (peerInfo._updatePriority()) {
      this._enqueue(peerInfo)
    }
  }

  async _handleNetworkUpdate() {
    if (!this.online) return
    this._handleNetworkChange()
  }

  async _handleNetworkChange() {
    if (this.suspended) return

    // prioritize figuring out if existing connections are dead
    for (const conn of this._allConnections) {
      conn.sendKeepAlive()
    }

    const refreshes = []

    for (const discovery of this._discovery.values()) {
      refreshes.push(discovery.refresh())
    }

    await Promise.allSettled(refreshes)
  }

  _banPeer(peerInfo, banned, err) {
    peerInfo.ban(banned)
    this.stats.bannedPeers++
    this.emit('ban', peerInfo, err)
  }

  status(key) {
    return this._discovery.get(b4a.toString(key, 'hex')) || null
  }

  listen() {
    if (!this.listening) {
      if (this.destroyed) throw new Error('Swarm destroyed')
      this.listening = this.server.listen(this.keyPair)
    }
    return this.listening
  }

  // Object that exposes a cancellation method (destroy)
  // TODO: When you rejoin, it should reannounce + bump lookup priority
  join(topic, opts = {}) {
    if (this.destroyed) throw new Error('Swarm destroyed')
    if (!topic) throw new Error(ERR_MISSING_TOPIC)
    topic = unslab(topic)

    const topicString = b4a.toString(topic, 'hex')

    let discovery = this._discovery.get(topicString)

    if (discovery && !discovery.destroyed) {
      return discovery.session(opts)
    }

    discovery = new PeerDiscovery(this, topic, {
      limit: opts.limit,
      wait: discovery ? discovery.destroy() : null,
      suspended: this.suspended,
      onpeer: (peer) => this._handlePeer(peer, topic)
    })
    this._discovery.set(topicString, discovery)
    return discovery.session(opts)
  }

  // Returns a promise
  async leave(topic) {
    if (!topic) throw new Error(ERR_MISSING_TOPIC)
    const topicString = b4a.toString(topic, 'hex')
    if (!this._discovery.has(topicString)) return Promise.resolve()

    const discovery = this._discovery.get(topicString)

    try {
      await discovery.destroy()
    } catch {
      // ignore, prop network
    }

    if (this._discovery.get(topicString) === discovery) {
      this._discovery.delete(topicString)
    }
  }

  joinPeer(publicKey) {
    const peerInfo = this._upsertPeer(publicKey, null)
    if (!peerInfo) return
    if (!this.explicitPeers.has(peerInfo)) {
      peerInfo.explicit = true
      this.explicitPeers.add(peerInfo)
    }
    if (this._allConnections.has(publicKey)) return
    if (peerInfo._updatePriority()) {
      this._enqueue(peerInfo)
    }
  }

  leavePeer(publicKey) {
    const keyString = b4a.toString(publicKey, 'hex')
    if (!this.peers.has(keyString)) return

    const peerInfo = this.peers.get(keyString)
    peerInfo.explicit = false
    this.explicitPeers.delete(peerInfo)
    this._maybeDeletePeer(peerInfo)
  }

  // Returns a promise
  async flush() {
    const allFlushed = [...this._discovery.values()].map((v) => v.flushed())
    await Promise.all(allFlushed)
    if (this._flushAllMaybe()) return true
    const pendingSize = this._allConnections.size - this.connections.size
    if (!this._queue.length && !pendingSize) return true
    return new Promise((resolve) => {
      this._pendingFlushes.push({
        onflush: resolve,
        missing: this._queue.length + pendingSize,
        tick: this._flushTick++
      })
    })
  }

  async clear() {
    const cleared = Promise.allSettled([...this._discovery.values()].map((d) => d.destroy()))
    this._discovery.clear()
    return cleared
  }

  async destroy({ force } = {}) {
    if (this.destroyed && !force) return
    this.destroyed = true

    this._timer.destroy()

    if (!force) await this.clear()

    await this.server.close()

    while (this._pendingFlushes.length) {
      const flush = this._pendingFlushes.pop()
      flush.onflush(false)
    }

    await this.dht.destroy({ force })
  }

  async suspend({ log = noop } = {}) {
    if (this.suspended) return

    const promises = []

    promises.push(this.server.suspend({ log }))

    for (const discovery of this._discovery.values()) {
      promises.push(discovery.suspend({ log }))
    }

    const pending = []
    for (const connection of this._allConnections) {
      connection.destroy()
      pending.push(new Promise((resolve) => connection.on('close', resolve)))
    }

    this.suspended = true

    log('Suspending server and discovery... (' + promises.length + ')')
    await Promise.allSettled(promises)
    log('Done, suspending the dht...')
    await this.dht.suspend({ log })
    log('Done, swarm fully suspended')

    await Promise.all(pending)

    // reset queue
    this._timer.destroy()
    this._timer = new RetryTimer(this._requeue.bind(this), {
      backoffs: this._timer.backoffs,
      jitter: this._timer.jitter
    })
    this._queue = spq()
  }

  async resume({ log = noop } = {}) {
    if (!this.suspended) return

    log('Resuming the dht')
    await this.dht.resume()
    log('Done, resuming the server')
    await this.server.resume()
    log('Done, all discovery')

    for (const discovery of this._discovery.values()) {
      discovery.resume()
    }

    this.suspended = false
    this._attemptClientConnections()
  }

  topics() {
    return this._discovery.values()
  }
}

function noop() {}

function allowAll() {
  return false
}

function shouldForceRelaying(code) {
  return (
    code === 'HOLEPUNCH_ABORTED' ||
    code === 'HOLEPUNCH_DOUBLE_RANDOMIZED_NATS' ||
    code === 'REMOTE_NOT_HOLEPUNCHABLE'
  )
}

function shouldBan() {
  // return !!err && err.name === 'HypercoreError' && err.code === 'INVALID_OPERATION'
  return false
}

function toRelayFunction(relayThrough) {
  return typeof relayThrough === 'function'
    ? relayThrough
    : (force, swarm) => (force || swarm.dht.randomized ? relayThrough : null)
}
module.exports = class BulkTimer {
  constructor(time, fn) {
    this._time = time
    this._fn = fn
    this._interval = null
    this._next = []
    this._pending = []
    this._destroyed = false
  }

  destroy() {
    if (this._destroyed) return
    this._destroyed = true
    clearInterval(this._interval)
    this._interval = null
  }

  _ontick() {
    if (!this._next.length && !this._pending.length) return
    if (this._next.length) this._fn(this._next)
    this._next = this._pending
    this._pending = []
  }

  add(info) {
    if (this._destroyed) return
    if (!this._interval) {
      this._interval = setInterval(this._ontick.bind(this), Math.floor(this._time * 0.66))
    }

    this._pending.push(info)
  }
}
const b4a = require('b4a')

module.exports = class ConnectionSet {
  constructor() {
    this._byPublicKey = new Map()
  }

  [Symbol.iterator]() {
    return this._byPublicKey.values()
  }

  get size() {
    return this._byPublicKey.size
  }

  has(publicKey) {
    return this._byPublicKey.has(toHex(publicKey))
  }

  get(publicKey) {
    return this._byPublicKey.get(toHex(publicKey))
  }

  add(connection) {
    this._byPublicKey.set(b4a.toString(connection.remotePublicKey, 'hex'), connection)
  }

  delete(connection) {
    const keyString = b4a.toString(connection.remotePublicKey, 'hex')
    const existing = this._byPublicKey.get(keyString)
    if (existing !== connection) return
    this._byPublicKey.delete(keyString)
  }
}

function toHex(b) {
  return typeof b === 'string' ? b : b4a.toString(b, 'hex')
}
const safetyCatch = require('safety-catch')
const b4a = require('b4a')

const REFRESH_INTERVAL = 1000 * 60 * 10 // 10 min
const RANDOM_JITTER = 1000 * 60 * 2 // 2 min
const DELAY_GRACE_PERIOD = 1000 * 30 // 30s

const MAX_DISCOVERY_CACHE = 64

module.exports = class PeerDiscovery {
  constructor(
    swarm,
    topic,
    { limit = Infinity, wait = null, suspended = false, onpeer = noop, onerror = safetyCatch }
  ) {
    this.limit = limit
    this.swarm = swarm
    this.topic = topic
    this.isClient = false
    this.isServer = false
    this.destroyed = false
    this.destroying = null
    this.suspended = suspended

    this._sessions = []
    this._clientSessions = 0
    this._serverSessions = 0

    this._onpeer = onpeer
    this._onerror = onerror

    this._discovered = new Set()
    this._activeQuery = null
    this._timer = null
    this._currentRefresh = null
    this._closestNodes = null
    this._firstAnnounce = true
    this._needsUnannounce = false
    this._refreshes = 0
    this._wait = wait
  }

  session({ server = true, client = true, limit = Infinity, onerror = safetyCatch }) {
    if (this.destroyed) throw new Error('PeerDiscovery is destroyed')
    const session = new PeerDiscoverySession(this)
    session.refresh({ server, client, limit }).catch(onerror)
    this._sessions.push(session)
    return session
  }

  _refreshLater(eager) {
    const jitter = Math.round(Math.random() * RANDOM_JITTER)
    const delay = !eager ? REFRESH_INTERVAL + jitter : jitter

    if (this._timer) clearTimeout(this._timer)

    const startTime = Date.now()
    this._timer = setTimeout(() => {
      // If your laptop went to sleep, and is coming back online...
      const overdue = Date.now() - startTime > delay + DELAY_GRACE_PERIOD
      if (overdue) this._refreshLater(true)
      else this.refresh().catch(this._onerror)
    }, delay)
  }

  _isActive() {
    return !this.destroyed && !this.suspended
  }

  // TODO: Allow announce to be an argument to this
  // TODO: Maybe announce should be a setter?
  async _refresh() {
    if (this.suspended) return
    const clock = ++this._refreshes

    if (this._wait) {
      await this._wait
      this._wait = null
      if (clock !== this._refreshes || !this._isActive()) return
    }

    const clear = this.isServer && this._firstAnnounce
    if (clear) this._firstAnnounce = false

    const opts = {
      clear,
      closestNodes: this._closestNodes
    }

    if (this.isServer) {
      await this.swarm.listen()
      // if a parallel refresh is happening, yield to the new one
      if (clock !== this._refreshes || !this._isActive()) return
      this._needsUnannounce = true
    }

    let limit = this.limit

    if (limit < Infinity && limit > 0) {
      for (const id of this._discovered) {
        if (!this.swarm.connections.has(id)) continue
        if (--limit === 0) break
      }
    }

    this._discovered.clear()

    const announcing = this.isServer
    const query = (this._activeQuery = announcing
      ? this.swarm.dht.announce(
          this.topic,
          this.swarm.keyPair,
          this.swarm.server.relayAddresses,
          opts
        )
      : this._needsUnannounce
        ? this.swarm.dht.lookupAndUnannounce(this.topic, this.swarm.keyPair, opts)
        : this.swarm.dht.lookup(this.topic, opts))

    try {
      for await (const data of this._activeQuery) {
        if (!this.isClient || !this._isActive()) continue
        for (const peer of data.peers) {
          if (limit < Infinity) {
            const id = b4a.toString(peer.publicKey, 'hex')

            if (this._discovered.size < MAX_DISCOVERY_CACHE) {
              this._discovered.add(id)
            }

            if (limit === 0) continue

            // there is a chance it has updated a connection during discovery and we go over
            // the limit - thats acceptable to avoid a complexity spiral here.
            if (!this.swarm.connections.has(id)) limit--
          }

          this._onpeer(peer, data)
        }
      }
    } catch (err) {
      if (this._isActive()) throw err
    } finally {
      if (this._activeQuery === query) {
        this._activeQuery = null
        if (!this.destroyed && !this.suspended) this._refreshLater(false)
      }
    }

    // This is set at the very end, when the query completes successfully.
    this._closestNodes = query.closestNodes

    if (clock !== this._refreshes) return

    // In this is the latest query, unannounce has been fulfilled as well
    if (!announcing) this._needsUnannounce = false
  }

  async refresh() {
    if (this.destroyed) throw new Error('PeerDiscovery is destroyed')

    const server = this._serverSessions > 0
    const client = this._clientSessions > 0

    if (this.suspended) return

    if (server === this.isServer && client === this.isClient) {
      if (this._currentRefresh) return this._currentRefresh
      this._currentRefresh = this._refresh()
    } else {
      if (this._activeQuery) this._activeQuery.destroy()
      this.isServer = server
      this.isClient = client
      this._currentRefresh = this._refresh()
    }

    const refresh = this._currentRefresh
    try {
      await refresh
    } catch {
      return false
    } finally {
      if (refresh === this._currentRefresh) {
        this._currentRefresh = null
      }
    }

    return true
  }

  async flushed() {
    if (this.swarm.listening) await this.swarm.listening

    try {
      await this._currentRefresh
      return true
    } catch {
      return false
    }
  }

  async _destroyMaybe() {
    if (this.destroyed) return

    try {
      if (this._sessions.length === 0) await this.swarm.leave(this.topic)
      else if (this._serverSessions === 0 && this._needsUnannounce) await this.refresh()
    } catch (err) {
      // ignore network failures here, as we are tearing down
      safetyCatch(err)
    }
  }

  destroy() {
    if (this.destroying) return this.destroying
    this.destroying = this._destroy()
    return this.destroying
  }

  async _abort(log) {
    const id = log === noop ? '' : b4a.toString(this.topic, 'hex')

    log('Aborting discovery', id)
    if (this._wait) await this._wait
    log('Aborting discovery (post wait)', id)

    if (this._activeQuery) {
      this._activeQuery.destroy()
      this._activeQuery = null
    }
    if (this._timer) {
      clearTimeout(this._timer)
      this._timer = null
    }

    let nodes = this._closestNodes

    if (this._currentRefresh) {
      try {
        await this._currentRefresh
      } catch {
        // If the destroy causes the refresh to fail, suppress it.
      }
    }

    log('Aborting discovery (post refresh)', id)
    if (this._isActive()) return

    if (!nodes) nodes = this._closestNodes
    else if (this._closestNodes !== nodes) {
      const len = nodes.length
      for (const newer of this._closestNodes) {
        if (newer.id && !hasNode(nodes, len, newer)) nodes.push(newer)
      }
    }

    if (this._needsUnannounce) {
      log('Unannouncing discovery', id)
      if (nodes && nodes.length) {
        await this.swarm.dht.unannounce(this.topic, this.swarm.keyPair, {
          closestNodes: nodes,
          onlyClosestNodes: true,
          force: true
        })
      }
      this._needsUnannounce = false
      log('Unannouncing discovery (done)', id)
    }
  }

  _destroy() {
    if (this.destroyed) return
    this.destroyed = true
    return this._abort(noop)
  }

  async suspend({ log = noop } = {}) {
    if (this.suspended) return
    this.suspended = true
    try {
      await this._abort(log)
    } catch {
      // ignore
    }
  }

  resume() {
    if (!this.suspended) return
    this.suspended = false
    this.refresh().catch(noop)
  }
}

class PeerDiscoverySession {
  constructor(discovery) {
    this.discovery = discovery
    this.isClient = false
    this.isServer = false
    this.destroyed = false
  }

  get swarm() {
    return this.discovery.swarm
  }

  get topic() {
    return this.discovery.topic
  }

  async refresh({ client = this.isClient, server = this.isServer, limit = Infinity } = {}) {
    if (this.destroyed) throw new Error('PeerDiscovery is destroyed')
    if (!client && !server) throw new Error('Cannot refresh with neither client nor server option')

    if (client !== this.isClient) {
      this.isClient = client
      this.discovery._clientSessions += client ? 1 : -1
    }

    if (server !== this.isServer) {
      this.isServer = server
      this.discovery._serverSessions += server ? 1 : -1
    }

    this.discovery.limit = limit

    return this.discovery.refresh()
  }

  async flushed() {
    return this.discovery.flushed()
  }

  async destroy() {
    if (this.destroyed) return
    this.destroyed = true

    if (this.isClient) this.discovery._clientSessions--
    if (this.isServer) this.discovery._serverSessions--

    const index = this.discovery._sessions.indexOf(this)
    const head = this.discovery._sessions.pop()

    if (head !== this) this.discovery._sessions[index] = head

    return this.discovery._destroyMaybe()
  }
}

function hasNode(nodes, len, node) {
  for (let i = 0; i < len; i++) {
    const existing = nodes[i]
    if (existing.id && b4a.equals(existing.id, node.id)) return true
  }

  return false
}

function noop() {}
const { EventEmitter } = require('events')
const b4a = require('b4a')
const unslab = require('unslab')

const MIN_CONNECTION_TIME = 15000

const VERY_LOW_PRIORITY = 0
const LOW_PRIORITY = 1
const NORMAL_PRIORITY = 2
const HIGH_PRIORITY = 3
const VERY_HIGH_PRIORITY = 4

module.exports = class PeerInfo extends EventEmitter {
  constructor({ publicKey, relayAddresses }) {
    super()

    this.publicKey = unslab(publicKey)
    this.relayAddresses = relayAddresses

    this.reconnecting = true
    this.proven = false
    this.connectedTime = -1
    this.disconnectedTime = 0
    this.banned = false
    this.tried = false
    this.explicit = false
    this.waiting = false
    this.forceRelaying = false

    // Set by the Swarm
    this.queued = false
    this.client = false
    this.topics = [] // TODO: remove on next major (check with mafintosh for context)

    this.attempts = 0
    this.priority = NORMAL_PRIORITY

    // Used by shuffled-priority-queue
    this._index = 0

    // Used for flush management
    this._flushTick = 0

    // Used for topic multiplexing
    this._seenTopics = new Set()
  }

  get server() {
    return !this.client
  }

  get prioritized() {
    return this.priority >= NORMAL_PRIORITY
  }

  _getPriority() {
    const peerIsStale = this.tried && !this.proven
    if (peerIsStale || this.attempts > 3) return VERY_LOW_PRIORITY
    if (this.attempts === 3) return LOW_PRIORITY
    if (this.attempts === 2) return HIGH_PRIORITY
    if (this.attempts === 1) return VERY_HIGH_PRIORITY
    return NORMAL_PRIORITY
  }

  _connected() {
    this.proven = true
    this.connectedTime = Date.now()
  }

  _disconnected() {
    this.disconnectedTime = Date.now()
    if (this.connectedTime > -1) {
      if (this.disconnectedTime - this.connectedTime >= MIN_CONNECTION_TIME) this.attempts = 0 // fast retry
      this.connectedTime = -1
    }
    this.attempts++
  }

  _deprioritize() {
    this.attempts = 3
  }

  _reset() {
    this.client = false
    this.proven = false
    this.tried = false
    this.attempts = 0
  }

  _updatePriority() {
    if (this.explicit && this.attempts > 3) this._deprioritize()
    if (this.banned || this.queued || this.attempts > 3) return false
    this.priority = this._getPriority()
    return true
  }

  _topic(topic) {
    const topicString = b4a.toString(topic, 'hex')
    if (this._seenTopics.has(topicString)) return
    this._seenTopics.add(topicString)
    this.topics.push(topic)
    this.emit('topic', topic)
  }

  reconnect(val) {
    this.reconnecting = !!val
  }

  ban(val) {
    this.banned = !!val
  }

  shouldGC() {
    return !(this.banned || this.queued || this.explicit || this.waiting)
  }
}
const BulkTimer = require('./bulk-timer')

const BACKOFF_JITTER = 500
const BACKOFF_S = 1000 + Math.round(BACKOFF_JITTER * Math.random())
const BACKOFF_M = 5000 + Math.round(2 * BACKOFF_JITTER * Math.random())
const BACKOFF_L = 15000 + Math.round(4 * BACKOFF_JITTER * Math.random())
const BACKOFF_X = 1000 * 60 * 10 + Math.round(240 * BACKOFF_JITTER * Math.random())

module.exports = class RetryTimer {
  constructor(
    push,
    { backoffs = [BACKOFF_S, BACKOFF_M, BACKOFF_L, BACKOFF_X], jitter = BACKOFF_JITTER } = {}
  ) {
    this.jitter = jitter
    this.backoffs = backoffs

    this._sTimer = new BulkTimer(backoffs[0] + Math.round(jitter * Math.random()), push)
    this._mTimer = new BulkTimer(backoffs[1] + Math.round(jitter * Math.random()), push)
    this._lTimer = new BulkTimer(backoffs[2] + Math.round(jitter * Math.random()), push)
    this._xTimer = new BulkTimer(backoffs[3] + Math.round(jitter * Math.random()), push)
  }

  _selectRetryTimer(peerInfo) {
    if (peerInfo.banned || !peerInfo.reconnecting) return null

    if (peerInfo.attempts > 3) {
      return peerInfo.explicit ? this._xTimer : null
    }

    if (peerInfo.attempts === 0) return this._sTimer
    if (peerInfo.proven) {
      switch (peerInfo.attempts) {
        case 1:
          return this._sTimer
        case 2:
          return this._mTimer
        case 3:
          return this._lTimer
      }
    } else {
      switch (peerInfo.attempts) {
        case 1:
          return this._mTimer
        case 2:
          return this._lTimer
        case 3:
          return this._lTimer
      }
    }

    return null
  }

  add(peerInfo) {
    const timer = this._selectRetryTimer(peerInfo)
    if (!timer) return false

    timer.add(peerInfo)
    return true
  }

  destroy() {
    this._sTimer.destroy()
    this._mTimer.destroy()
    this._lTimer.destroy()
    this._xTimer.destroy()
  }
}
{
  "name": "hyperswarm",
  "version": "4.17.0",
  "description": "A distributed networking stack for connecting peers",
  "files": [
    "index.js",
    "lib/**.js"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    },
    "process": {
      "bare": "bare-process",
      "default": "process"
    }
  },
  "dependencies": {
    "b4a": "^1.3.1",
    "bare-events": "^2.2.0",
    "hyperdht": "^6.21.0",
    "safety-catch": "^1.0.2",
    "shuffled-priority-queue": "^2.1.0",
    "streamx": "^2.22.1",
    "unslab": "^1.3.0"
  },
  "devDependencies": {
    "bare-process": "^4.2.2",
    "brittle": "^3.0.2",
    "hypercore-crypto": "^3.4.0",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "which-runtime": "^1.3.2"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:generate": "brittle -r test/all.js test/*.js",
    "test:node": "brittle-node --coverage test/*.js",
    "test:bare": "bare test/all.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/hyperswarm.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "contributors": [
    "David Mark Clements (@davidmarkclem)",
    "Andrew Osheroff (@andrewosh)"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/hyperswarm/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperswarm"
}
const b4a = require('b4a')

module.exports = function isOptions (opts) {
  return typeof opts === 'object' && opts && !b4a.isBuffer(opts)
}
{
  "name": "is-options",
  "version": "1.0.2",
  "description": "Easily check if input is an options map",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.1.1"
  },
  "devDependencies": {
    "standard": "^11.0.1",
    "tape": "^4.9.0"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/is-options.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/is-options/issues"
  },
  "homepage": "https://github.com/mafintosh/is-options"
}
const { EventEmitter } = require('events')

module.exports = class RoutingTable extends EventEmitter {
  constructor (id, opts) {
    if (!opts) opts = {}

    super()

    this.id = id
    this.k = opts.k || 20
    this.size = 0
    this.rows = new Array(id.length * 8)
  }

  add (node) {
    const i = this._diff(node.id)

    let row = this.rows[i]

    if (!row) {
      row = this.rows[i] = new Row(this, i)
      this.emit('row', row)
    }

    const len = row.nodes.length
    if (!row.add(node, this.k)) return false

    this.size += row.nodes.length - len
    return true
  }

  remove (id) {
    const i = this._diff(id)
    const row = this.rows[i]
    if (!row) return false
    if (!row.remove(id)) return false
    this.size--
    return true
  }

  get (id) {
    const i = this._diff(id)
    const row = this.rows[i]
    if (!row) return null
    return row.get(id)
  }

  has (id) {
    return this.get(id) !== null
  }

  random () {
    let n = (Math.random() * this.size) | 0

    for (let i = 0; i < this.rows.length; i++) {
      const r = this.rows[i]
      if (!r) continue
      if (n < r.nodes.length) return r.nodes[n]
      n -= r.nodes.length
    }

    return null
  }

  closest (id, k) {
    if (!k) k = this.k

    const result = []
    const d = this._diff(id)

    // push close nodes
    for (let i = d; i >= 0 && result.length < k; i--) this._pushNodes(i, k, result)

    // if we don't have enough close nodes, populate from other rows, re the paper
    for (let i = d + 1; i < this.rows.length && result.length < k; i++) this._pushNodes(i, k, result)

    return result
  }

  _pushNodes (i, k, result) {
    const row = this.rows[i]
    if (!row) return

    const missing = Math.min(k - result.length, row.nodes.length)
    for (let j = 0; j < missing; j++) result.push(row.nodes[j])
  }

  toArray () {
    return this.closest(this.id, Infinity)
  }

  _diff (id) {
    for (let i = 0; i < id.length; i++) {
      const a = id[i]
      const b = this.id[i]

      if (a !== b) return i * 8 + Math.clz32(a ^ b) - 24
    }

    return this.rows.length - 1
  }
}

class Row extends EventEmitter {
  constructor (table, index) {
    super()

    this.data = null // can be used be upstream for whatevs
    this.byteOffset = index >> 3
    this.index = index
    this.table = table
    this.nodes = []
  }

  add (node) {
    const id = node.id

    let l = 0
    let r = this.nodes.length - 1

    while (l <= r) {
      const m = (l + r) >> 1
      const c = this.compare(id, this.nodes[m].id)

      if (c === 0) {
        this.nodes[m] = node
        return true
      }

      if (c < 0) r = m - 1
      else l = m + 1
    }

    if (this.nodes.length >= this.table.k) {
      this.emit('full', node)
      return false
    }

    this.insert(l, node)
    return true
  }

  remove (id) {
    let l = 0
    let r = this.nodes.length - 1

    while (l <= r) {
      const m = (l + r) >> 1
      const c = this.compare(id, this.nodes[m].id)

      if (c === 0) {
        this.splice(m)
        return true
      }

      if (c < 0) r = m - 1
      else l = m + 1
    }

    return false
  }

  get (id) {
    let l = 0
    let r = this.nodes.length - 1

    while (l <= r) {
      const m = (l + r) >> 1
      const node = this.nodes[m]
      const c = this.compare(id, node.id)

      if (c === 0) return node
      if (c < 0) r = m - 1
      else l = m + 1
    }

    return null
  }

  insert (i, node) {
    this.nodes.push(node) // push node or null or whatevs, just trying to not be polymorphic
    for (let j = this.nodes.length - 1; j > i; j--) this.nodes[j] = this.nodes[j - 1]
    this.nodes[i] = node
    this.emit('add', node)
  }

  splice (i) {
    for (; i < this.nodes.length - 1; i++) this.nodes[i] = this.nodes[i + 1]
    this.emit('remove', this.nodes.pop())
  }

  // very likely they diverge after a couple of bytes so a simple impl, like this is prop fastest vs Buffer.compare
  compare (a, b) {
    for (let i = this.byteOffset; i < a.length; i++) {
      const ai = a[i]
      const bi = b[i]
      if (ai === bi) continue
      return ai < bi ? -1 : 1
    }
    return 0
  }
}
{
  "name": "kademlia-routing-table",
  "version": "1.0.6",
  "description": "XOR based routing table used for P2P networks such as a Kademlia DHT.",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "dependencies": {
    "bare-events": "^2.2.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "standard": "^17.1.0"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "keywords": [
    "kademlia",
    "p2p",
    "k-bucket",
    "k-buckets",
    "xor",
    "routing",
    "distributed",
    "systems"
  ],
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/kademlia-routing-table.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/kademlia-routing-table/issues"
  },
  "homepage": "https://github.com/mafintosh/kademlia-routing-table"
}
module.exports = assert

class AssertionError extends Error {}
AssertionError.prototype.name = 'AssertionError'

/**
 * Minimal assert function
 * @param  {any} t Value to check if falsy
 * @param  {string=} m Optional assertion error message
 * @throws {AssertionError}
 */
function assert (t, m) {
  if (!t) {
    var err = new AssertionError(m)
    if (Error.captureStackTrace) Error.captureStackTrace(err, assert)
    throw err
  }
}
{
  "name": "nanoassert",
  "version": "2.0.0",
  "description": "Nanoscale assertion module",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "tape": "^4.9.1"
  },
  "scripts": {
    "test": "tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/emilbayes/nanoassert.git"
  },
  "keywords": [
    "assert",
    "unassert",
    "power-assert",
    "tiny",
    "nano",
    "pico"
  ],
  "author": "Emil Bay <github@tixz.dk>",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/emilbayes/nanoassert/issues"
  },
  "homepage": "https://github.com/emilbayes/nanoassert#readme"
}
module.exports = class NatSampler {
  constructor () {
    this.host = null
    this.port = 0
    this.size = 0

    this._a = null
    this._b = null
    this._threshold = 0
    this._top = 0
    this._samples = []
  }

  add (host, port) {
    const a = this._bump(host, port, 2)
    const b = this._bump(host, 0, 1)

    if (this._samples.length < 32) {
      this.size++
      this._threshold = this.size - (this.size < 4 ? 0 : this.size < 8 ? 1 : this.size < 12 ? 2 : 3)
      this._samples.push(a, b)
      this._top += 2
    } else {
      if (this._top === 32) this._top = 0

      const oa = this._samples[this._top]
      this._samples[this._top++] = a
      oa.hits--

      const ob = this._samples[this._top]
      this._samples[this._top++] = b
      ob.hits--
    }

    if (this._a === null || this._a.hits < a.hits) this._a = a
    if (this._b === null || this._b.hits < b.hits) this._b = b

    if (this._a.hits >= this._threshold) {
      this.host = this._a.host
      this.port = this._a.port
    } else if (this._b.hits >= this._threshold) {
      this.host = this._b.host
      this.port = 0
    } else {
      this.host = null
      this.port = 0
    }

    return a.hits
  }

  _bump (host, port, inc) {
    for (let i = 0; i < 4; i++) {
      const j = (this._top - inc - (2 * i)) & 31
      if (j >= this._samples.length) return { host, port, hits: 1 }
      const s = this._samples[j]
      if (s.port === port && s.host === host) {
        s.hits++
        return s
      }
    }
    return { host, port, hits: 1 }
  }
}
{
  "name": "nat-sampler",
  "version": "1.0.1",
  "description": "Sample addresses to figure out if a host + port is consistent",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^16.0.3",
    "tape": "^5.2.2"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/nat-sampler.git"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/nat-sampler/issues"
  },
  "homepage": "https://github.com/mafintosh/nat-sampler"
}
/* eslint-disable camelcase */
const sodium = require('sodium-universal')
const assert = require('nanoassert')
const b4a = require('b4a')

const DHLEN = sodium.crypto_scalarmult_ed25519_BYTES
const PKLEN = sodium.crypto_scalarmult_ed25519_BYTES
const SCALARLEN = sodium.crypto_scalarmult_ed25519_BYTES
const SKLEN = sodium.crypto_sign_SECRETKEYBYTES
const ALG = 'Ed25519'

module.exports = {
  DHLEN,
  PKLEN,
  SCALARLEN,
  SKLEN,
  ALG,
  name: ALG,
  generateKeyPair,
  dh
}

function generateKeyPair (privKey) {
  if (privKey) return generateSeedKeyPair(privKey.subarray(0, 32))

  const keyPair = {}
  keyPair.secretKey = b4a.alloc(SKLEN)
  keyPair.publicKey = b4a.alloc(PKLEN)

  sodium.crypto_sign_keypair(keyPair.publicKey, keyPair.secretKey)
  return keyPair
}

function generateSeedKeyPair (seed) {
  const keyPair = {}
  keyPair.secretKey = b4a.alloc(SKLEN)
  keyPair.publicKey = b4a.alloc(PKLEN)

  sodium.crypto_sign_seed_keypair(keyPair.publicKey, keyPair.secretKey, seed)
  return keyPair
}

function dh (publicKey, { scalar, secretKey }) {
  // tweaked keys expose scalar directly
  if (!scalar) {
    assert(secretKey.byteLength === SKLEN)

    // libsodium stores seed not actual scalar
    const sk = b4a.alloc(64)
    sodium.crypto_hash_sha512(sk, secretKey.subarray(0, 32))
    sk[0] &= 248
    sk[31] &= 127
    sk[31] |= 64

    scalar = sk.subarray(0, 32)
  }

  assert(scalar.byteLength === SCALARLEN)
  assert(publicKey.byteLength === PKLEN)

  const output = b4a.alloc(DHLEN)

  // we clamp if necessary above
  sodium.crypto_scalarmult_ed25519_noclamp(
    output,
    scalar,
    publicKey
  )

  return output
}
{
  "name": "noise-curve-ed",
  "version": "2.1.0",
  "description": "Ed25519 elliptic curve operations for [`noise-handshake`](https://github.com/chm-diederichs/noise-handshake)",
  "main": "index.js",
  "scripts": {
    "test": "npx standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/chm-diederichs/noise-curve-ed.git"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/chm-diederichs/noise-curve-ed/issues"
  },
  "homepage": "https://github.com/chm-diederichs/noise-curve-ed#readme",
  "dependencies": {
    "b4a": "^1.1.0",
    "nanoassert": "^2.0.0",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "noise-handshake": "^3.0.0",
    "standard": "^16.0.3",
    "tape": "^5.2.2"
  }
}
const sodium = require('sodium-universal')
const b4a = require('b4a')

module.exports = class CipherState {
  constructor (key) {
    this.key = key || null
    this.nonce = 0
    this.CIPHER_ALG = 'ChaChaPoly'
  }

  initialiseKey (key) {
    this.key = key
    this.nonce = 0
  }

  setNonce (nonce) {
    this.nonce = nonce
  }

  encrypt (plaintext, ad) {
    if (!this.hasKey) return plaintext
    if (!ad) ad = b4a.alloc(0)

    const ciphertext = encryptWithAD(this.key, this.nonce, ad, plaintext)
    if (ciphertext.length > 65535) throw new Error(`ciphertext length of ${ciphertext.length} exceeds maximum Noise message length of 65535`)
    this.nonce++

    return ciphertext
  }

  decrypt (ciphertext, ad) {
    if (!this.hasKey) return ciphertext
    if (!ad) ad = b4a.alloc(0)
    if (ciphertext.length > 65535) throw new Error(`ciphertext length of ${ciphertext.length} exceeds maximum Noise message length of 65535`)

    const plaintext = decryptWithAD(this.key, this.nonce, ad, ciphertext)
    this.nonce++

    return plaintext
  }

  get hasKey () {
    return this.key !== null
  }

  _clear () {
    sodium.sodium_memzero(this.key)
    this.key = null
    this.nonce = null
  }

  static get MACBYTES () {
    return 16
  }

  static get NONCEBYTES () {
    return 8
  }

  static get KEYBYTES () {
    return 32
  }
}

function encryptWithAD (key, counter, additionalData, plaintext) {
  // for our purposes, additionalData will always be a pubkey so we encode from hex
  if (!b4a.isBuffer(additionalData)) additionalData = b4a.from(additionalData, 'hex')
  if (!b4a.isBuffer(plaintext)) plaintext = b4a.from(plaintext, 'hex')

  const nonce = b4a.alloc(sodium.crypto_aead_chacha20poly1305_ietf_NPUBBYTES)
  const view = new DataView(nonce.buffer, nonce.byteOffset, nonce.byteLength)
  view.setUint32(4, counter, true)

  const ciphertext = b4a.alloc(plaintext.byteLength + sodium.crypto_aead_chacha20poly1305_ietf_ABYTES)

  sodium.crypto_aead_chacha20poly1305_ietf_encrypt(ciphertext, plaintext, additionalData, null, nonce, key)
  return ciphertext
}

function decryptWithAD (key, counter, additionalData, ciphertext) {
  // for our purposes, additionalData will always be a pubkey so we encode from hex
  if (!b4a.isBuffer(additionalData)) additionalData = b4a.from(additionalData, 'hex')
  if (!b4a.isBuffer(ciphertext)) ciphertext = b4a.from(ciphertext, 'hex')

  const nonce = b4a.alloc(sodium.crypto_aead_chacha20poly1305_ietf_NPUBBYTES)
  const view = new DataView(nonce.buffer, nonce.byteOffset, nonce.byteLength)
  view.setUint32(4, counter, true)

  const plaintext = b4a.alloc(ciphertext.byteLength - sodium.crypto_aead_chacha20poly1305_ietf_ABYTES)

  sodium.crypto_aead_chacha20poly1305_ietf_decrypt(plaintext, null, ciphertext, additionalData, nonce, key)
  return plaintext
}
/* eslint-disable camelcase */
const {
  crypto_kx_SEEDBYTES,
  crypto_kx_keypair,
  crypto_kx_seed_keypair,
  crypto_scalarmult_BYTES,
  crypto_scalarmult_SCALARBYTES,
  crypto_scalarmult,
  crypto_scalarmult_base
} = require('sodium-universal')

const assert = require('nanoassert')
const b4a = require('b4a')

const DHLEN = crypto_scalarmult_BYTES
const PKLEN = crypto_scalarmult_BYTES
const SKLEN = crypto_scalarmult_SCALARBYTES
const SEEDLEN = crypto_kx_SEEDBYTES
const ALG = '25519'

module.exports = {
  DHLEN,
  PKLEN,
  SKLEN,
  SEEDLEN,
  ALG,
  generateKeyPair,
  generateSeedKeyPair,
  dh
}

function generateKeyPair (privKey) {
  const keyPair = {}

  keyPair.secretKey = privKey || b4a.alloc(SKLEN)
  keyPair.publicKey = b4a.alloc(PKLEN)

  if (privKey) {
    crypto_scalarmult_base(keyPair.publicKey, keyPair.secretKey)
  } else {
    crypto_kx_keypair(keyPair.publicKey, keyPair.secretKey)
  }

  return keyPair
}

function generateSeedKeyPair (seed) {
  assert(seed.byteLength === SKLEN)

  const keyPair = {}
  keyPair.secretKey = b4a.alloc(SKLEN)
  keyPair.publicKey = b4a.alloc(PKLEN)

  crypto_kx_seed_keypair(keyPair.publicKey, keyPair.secretKey, seed)
  return keyPair
}

function dh (publicKey, { secretKey }) {
  assert(secretKey.byteLength === SKLEN)
  assert(publicKey.byteLength === PKLEN)

  const output = b4a.alloc(DHLEN)

  crypto_scalarmult(
    output,
    secretKey,
    publicKey
  )

  return output
}
const hmacBlake2b = require('./hmac')
const b4a = require('b4a')

const HASHLEN = 64

module.exports = {
  hkdf,
  HASHLEN
}

// HMAC-based Extract-and-Expand KDF
// https://www.ietf.org/rfc/rfc5869.txt

function hkdf (salt, inputKeyMaterial, info = '', length = 2 * HASHLEN) {
  const pseudoRandomKey = hkdfExtract(salt, inputKeyMaterial)
  return hkdfExpand(pseudoRandomKey, info, length)
}

function hkdfExtract (salt, inputKeyMaterial) {
  const hmac = b4a.alloc(HASHLEN)
  return hmacDigest(hmac, salt, inputKeyMaterial)
}

function hkdfExpand (key, info, length) {
  // Put in dedicated slab to avoid keeping shared slab from being gc'ed
  const buffer = b4a.allocUnsafeSlow(length)

  const infoBuf = b4a.from(info)
  let prev = infoBuf

  const result = []
  for (let i = 0; i < length; i += HASHLEN) {
    const pos = b4a.from([(i / HASHLEN) + 1])

    const out = buffer.subarray(i, i + HASHLEN)
    result.push(out)

    prev = hmacDigest(out, key, [prev, infoBuf, pos])
  }

  return result
}

function hmacDigest (out, key, input) {
  hmacBlake2b(out, input, key)
  return out
}
/* eslint-disable camelcase */
const b4a = require('b4a')
const { sodium_memzero, crypto_generichash, crypto_generichash_batch } = require('sodium-universal')

const HASHLEN = 64
const BLOCKLEN = 128
const scratch = b4a.alloc(BLOCKLEN * 3)
const HMACKey = scratch.subarray(BLOCKLEN * 0, BLOCKLEN * 1)
const OuterKeyPad = scratch.subarray(BLOCKLEN * 1, BLOCKLEN * 2)
const InnerKeyPad = scratch.subarray(BLOCKLEN * 2, BLOCKLEN * 3)

// Post-fill is done in the cases where someone caught an exception that
// happened before we were able to clear data at the end

module.exports = function hmac (out, batch, key) {
  if (key.byteLength > BLOCKLEN) {
    crypto_generichash(HMACKey.subarray(0, HASHLEN), key)
    sodium_memzero(HMACKey.subarray(HASHLEN))
  } else {
    // Covers key <= BLOCKLEN
    HMACKey.set(key)
    sodium_memzero(HMACKey.subarray(key.byteLength))
  }

  for (let i = 0; i < HMACKey.byteLength; i++) {
    OuterKeyPad[i] = 0x5c ^ HMACKey[i]
    InnerKeyPad[i] = 0x36 ^ HMACKey[i]
  }
  sodium_memzero(HMACKey)

  crypto_generichash_batch(out, [InnerKeyPad].concat(batch))
  sodium_memzero(InnerKeyPad)
  crypto_generichash_batch(out, [OuterKeyPad, out])
  sodium_memzero(OuterKeyPad)
}

module.exports.BYTES = HASHLEN
module.exports.KEYBYTES = BLOCKLEN
const assert = require('nanoassert')
const b4a = require('b4a')

const SymmetricState = require('./symmetric-state')
const { HASHLEN } = require('./hkdf')

const PRESHARE_IS = Symbol('initiator static key preshared')
const PRESHARE_RS = Symbol('responder static key preshared')

const TOK_PSK = Symbol('psk')

const TOK_S = Symbol('s')
const TOK_E = Symbol('e')

const TOK_ES = Symbol('es')
const TOK_SE = Symbol('se')
const TOK_EE = Symbol('ee')
const TOK_SS = Symbol('ss')

const HANDSHAKES = Object.freeze({
  NN: [
    [TOK_E],
    [TOK_E, TOK_EE]
  ],
  NNpsk0: [
    [TOK_PSK, TOK_E],
    [TOK_E, TOK_EE]
  ],
  XX: [
    [TOK_E],
    [TOK_E, TOK_EE, TOK_S, TOK_ES],
    [TOK_S, TOK_SE]
  ],
  XXpsk0: [
    [TOK_PSK, TOK_E],
    [TOK_E, TOK_EE, TOK_S, TOK_ES],
    [TOK_S, TOK_SE]
  ],
  IK: [
    PRESHARE_RS,
    [TOK_E, TOK_ES, TOK_S, TOK_SS],
    [TOK_E, TOK_EE, TOK_SE]
  ],
  XK: [
    PRESHARE_RS,
    [TOK_E, TOK_ES],
    [TOK_E, TOK_EE],
    [TOK_S, TOK_SE]
  ]
})

class Writer {
  constructor () {
    this.size = 0
    this.buffers = []
  }

  push (b) {
    this.size += b.byteLength
    this.buffers.push(b)
  }

  end () {
    const all = b4a.alloc(this.size)
    let offset = 0
    for (const b of this.buffers) {
      all.set(b, offset)
      offset += b.byteLength
    }
    return all
  }
}

class Reader {
  constructor (buf) {
    this.offset = 0
    this.buffer = buf
  }

  shift (n) {
    const start = this.offset
    const end = this.offset += n
    if (end > this.buffer.byteLength) throw new Error('Insufficient bytes')
    return this.buffer.subarray(start, end)
  }

  end () {
    return this.shift(this.buffer.byteLength - this.offset)
  }
}

module.exports = class NoiseState extends SymmetricState {
  constructor (pattern, initiator, staticKeypair, opts = {}) {
    super(opts)

    this.s = staticKeypair || this.curve.generateKeyPair()
    this.e = null

    this.psk = null
    if (opts && opts.psk) this.psk = opts.psk

    this.re = null
    this.rs = null

    this.pattern = pattern
    this.handshake = HANDSHAKES[this.pattern].slice()

    this.isPskHandshake = !!this.psk && hasPskToken(this.handshake)

    this.protocol = b4a.from([
      'Noise',
      this.pattern,
      this.DH_ALG,
      this.CIPHER_ALG,
      'BLAKE2b'
    ].join('_'))

    this.initiator = initiator
    this.complete = false

    this.rx = null
    this.tx = null
    this.hash = null
  }

  initialise (prologue, remoteStatic) {
    if (this.protocol.byteLength <= HASHLEN) this.digest.set(this.protocol)
    else this.mixHash(this.protocol)

    this.chainingKey = b4a.from(this.digest)

    this.mixHash(prologue)

    while (!Array.isArray(this.handshake[0])) {
      const message = this.handshake.shift()

      // handshake steps should be as arrays, only
      // preshare tokens are provided otherwise
      assert(message === PRESHARE_RS || message === PRESHARE_IS,
        'Unexpected pattern')

      const takeRemoteKey = this.initiator
        ? message === PRESHARE_RS
        : message === PRESHARE_IS

      if (takeRemoteKey) this.rs = remoteStatic

      const key = takeRemoteKey ? this.rs : this.s.publicKey
      assert(key != null, 'Remote pubkey required')

      this.mixHash(key)
    }
  }

  final () {
    const [k1, k2] = this.split()

    this.tx = this.initiator ? k1 : k2
    this.rx = this.initiator ? k2 : k1

    this.complete = true
    this.hash = this.getHandshakeHash()

    this._clear()
  }

  recv (buf) {
    const r = new Reader(buf)

    for (const pattern of this.handshake.shift()) {
      switch (pattern) {
        case TOK_PSK :
          this.mixKeyAndHash(this.psk)
          break

        case TOK_E :
          this.re = r.shift(this.curve.PKLEN)
          this.mixHash(this.re)
          if (this.isPskHandshake) this.mixKeyNormal(this.re)
          break

        case TOK_S : {
          const klen = this.hasKey ? this.curve.PKLEN + 16 : this.curve.PKLEN
          this.rs = this.decryptAndHash(r.shift(klen))
          break
        }

        case TOK_EE :
        case TOK_ES :
        case TOK_SE :
        case TOK_SS : {
          const useStatic = keyPattern(pattern, this.initiator)

          const localKey = useStatic.local ? this.s : this.e
          const remoteKey = useStatic.remote ? this.rs : this.re

          this.mixKey(remoteKey, localKey)
          break
        }

        default :
          throw new Error('Unexpected message')
      }
    }

    const payload = this.decryptAndHash(r.end())

    if (!this.handshake.length) this.final()
    return payload
  }

  send (payload = b4a.alloc(0)) {
    const w = new Writer()

    for (const pattern of this.handshake.shift()) {
      switch (pattern) {
        case TOK_PSK :
          this.mixKeyAndHash(this.psk)
          break

        case TOK_E :
          if (this.e === null) this.e = this.curve.generateKeyPair()
          this.mixHash(this.e.publicKey)
          if (this.isPskHandshake) this.mixKeyNormal(this.e.publicKey)
          w.push(this.e.publicKey)
          break

        case TOK_S :
          w.push(this.encryptAndHash(this.s.publicKey))
          break

        case TOK_ES :
        case TOK_SE :
        case TOK_EE :
        case TOK_SS : {
          const useStatic = keyPattern(pattern, this.initiator)

          const localKey = useStatic.local ? this.s : this.e
          const remoteKey = useStatic.remote ? this.rs : this.re

          this.mixKey(remoteKey, localKey)
          break
        }

        default :
          throw new Error('Unexpected message')
      }
    }

    w.push(this.encryptAndHash(payload))
    const response = w.end()

    if (!this.handshake.length) this.final()
    return response
  }

  _clear () {
    super._clear()

    this.e.secretKey.fill(0)
    this.e.publicKey.fill(0)

    this.re.fill(0)

    this.e = null
    this.re = null
  }
}

function keyPattern (pattern, initiator) {
  const ret = {
    local: false,
    remote: false
  }

  switch (pattern) {
    case TOK_EE:
      return ret

    case TOK_ES:
      ret.local ^= !initiator
      ret.remote ^= initiator
      return ret

    case TOK_SE:
      ret.local ^= initiator
      ret.remote ^= !initiator
      return ret

    case TOK_SS:
      ret.local ^= 1
      ret.remote ^= 1
      return ret
  }
}

function hasPskToken (handshake) {
  return handshake.some(x => {
    return Array.isArray(x) && x.indexOf(TOK_PSK) !== -1
  })
}
{
  "name": "noise-handshake",
  "version": "4.2.0",
  "description": "Noise protocol handshake",
  "main": "noise.js",
  "files": [
    "*.js"
  ],
  "scripts": {
    "test": "standard && brittle test/*.js"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/noise-handshake.git"
  },
  "dependencies": {
    "b4a": "^1.1.0",
    "nanoassert": "^2.0.0",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "noise-protocol": "chm-diederichs/noise-protocol.git#xx-ephemeral-key",
    "standard": "^16.0.3"
  }
}
const sodium = require('sodium-universal')
const assert = require('nanoassert')
const b4a = require('b4a')
const CipherState = require('./cipher')
const curve = require('./dh')
const { HASHLEN, hkdf } = require('./hkdf')

module.exports = class SymmetricState extends CipherState {
  constructor (opts = {}) {
    super()

    this.curve = opts.curve || curve
    this.digest = b4a.alloc(HASHLEN)
    this.chainingKey = null
    this.offset = 0

    this.DH_ALG = this.curve.ALG
  }

  mixHash (data) {
    accumulateDigest(this.digest, data)
  }

  mixKeyAndHash (key) {
    const [ck, tempH, tempK] = hkdf(this.chainingKey, key, '', 3 * HASHLEN)
    this.chainingKey = ck
    this.mixHash(tempH)
    this.initialiseKey(tempK.subarray(0, 32))
  }

  mixKeyNormal (key) {
    const [ck, tempK] = hkdf(this.chainingKey, key)
    this.chainingKey = ck
    this.initialiseKey(tempK.subarray(0, 32))
  }

  mixKey (remoteKey, localKey) {
    const dh = this.curve.dh(remoteKey, localKey)
    const hkdfResult = hkdf(this.chainingKey, dh)
    this.chainingKey = hkdfResult[0]
    this.initialiseKey(hkdfResult[1].subarray(0, 32))
  }

  encryptAndHash (plaintext) {
    const ciphertext = this.encrypt(plaintext, this.digest)
    accumulateDigest(this.digest, ciphertext)
    return ciphertext
  }

  decryptAndHash (ciphertext) {
    const plaintext = this.decrypt(ciphertext, this.digest)
    accumulateDigest(this.digest, ciphertext)
    return plaintext
  }

  getHandshakeHash (out) {
    if (!out) return this.getHandshakeHash(b4a.alloc(HASHLEN))
    assert(out.byteLength === HASHLEN, `output must be ${HASHLEN} bytes`)

    out.set(this.digest)
    return out
  }

  split () {
    const res = hkdf(this.chainingKey, b4a.alloc(0))
    return res.map(k => k.subarray(0, 32))
  }

  _clear () {
    super._clear()

    sodium.sodium_memzero(this.digest)
    sodium.sodium_memzero(this.chainingKey)

    this.digest = null
    this.chainingKey = null
    this.offset = null

    this.curve = null
  }

  static get alg () {
    return CipherState.alg + '_BLAKE2b'
  }
}

function accumulateDigest (digest, input) {
  const toHash = b4a.concat([digest, input])
  sodium.crypto_generichash(digest, toHash)
}
const b4a = require('b4a')
const c = require('compact-encoding')
const queueTick = require('queue-tick')
const safetyCatch = require('safety-catch')
const unslab = require('unslab')

const MAX_BUFFERED = 32768
const MAX_BACKLOG = Infinity // TODO: impl "open" backpressure
const MAX_BATCH = 8 * 1024 * 1024

class Channel {
  constructor(
    mux,
    info,
    userData,
    protocol,
    aliases,
    id,
    handshake,
    messages,
    onopen,
    onclose,
    ondestroy,
    ondrain
  ) {
    this.userData = userData
    this.protocol = protocol
    this.aliases = aliases
    this.id = id
    this.handshake = null
    this.messages = []

    this.opened = false
    this.closed = false
    this.destroyed = false

    this.onopen = onopen
    this.onclose = onclose
    this.ondestroy = ondestroy
    this.ondrain = ondrain

    this._handshake = handshake
    this._mux = mux
    this._info = info
    this._localId = 0
    this._remoteId = 0
    this._active = 0
    this._extensions = null

    this._decBound = this._dec.bind(this)
    this._decAndDestroyBound = this._decAndDestroy.bind(this)

    this._openedPromise = null
    this._openedResolve = null

    this._destroyedPromise = null
    this._destroyedResolve = null

    for (const m of messages) this.addMessage(m)
  }

  get drained() {
    return this._mux.drained
  }

  fullyOpened() {
    if (this.opened) return Promise.resolve(true)
    if (this.closed) return Promise.resolve(false)
    if (this._openedPromise) return this._openedPromise

    this._openedPromise = new Promise((resolve) => {
      this._openedResolve = resolve
    })
    return this._openedPromise
  }

  fullyClosed() {
    if (this.destroyed) return Promise.resolve()
    if (this._destroyedPromise) return this._destroyedPromise

    this._destroyedPromise = new Promise((resolve) => {
      this._destroyedResolve = resolve
    })
    return this._destroyedPromise
  }

  open(handshake) {
    const id = this._mux._free.length > 0 ? this._mux._free.pop() : this._mux._local.push(null) - 1

    this._info.opened++
    this._info.lastChannel = this
    this._localId = id + 1
    this._mux._local[id] = this

    if (this._remoteId === 0) {
      this._info.outgoing.push(this._localId)
    }

    const state = { buffer: null, start: 2, end: 2 }

    c.uint.preencode(state, this._localId)
    c.string.preencode(state, this.protocol)
    c.optionalBuffer.preencode(state, this.id)
    if (this._handshake) this._handshake.preencode(state, handshake)

    state.buffer = this._mux._alloc(state.end)

    state.buffer[0] = 0
    state.buffer[1] = 1
    c.uint.encode(state, this._localId)
    c.string.encode(state, this.protocol)
    c.optionalBuffer.encode(state, this.id)
    if (this._handshake) this._handshake.encode(state, handshake)

    this._mux._write0(state.buffer)
  }

  _dec() {
    if (--this._active === 0 && this.closed === true) this._destroy()
  }

  _decAndDestroy(err) {
    this._dec()
    this._mux._safeDestroy(err)
  }

  _fullyOpenSoon() {
    this._mux._remote[this._remoteId - 1].session = this
    queueTick(this._fullyOpenOrDestroy.bind(this))
  }

  _fullyOpenOrDestroy() {
    try {
      this._fullyOpen()
    } catch (err) {
      this._mux._safeDestroyBound(err)
    }
  }

  _fullyOpen() {
    if (this.opened === true || this.closed === true) return

    const remote = this._mux._remote[this._remoteId - 1]

    this.handshake = this._handshake ? this._handshake.decode(remote.state) : null
    this._track(this.onopen(this.handshake, this))

    remote.session = this
    remote.state = null
    if (remote.pending !== null) this._drain(remote)
    if (this._mux._destroying === true) return

    this.opened = true
    this._resolveOpen(true)
  }

  _resolveOpen(opened) {
    if (this._openedResolve !== null) {
      this._openedResolve(opened)
      this._openedResolve = this._openedPromise = null
    }
  }

  _resolveDestroyed() {
    if (this._destroyedResolve !== null) {
      this._destroyedResolve()
      this._destroyedResolve = this._destroyedPromise = null
    }
  }

  _drain(remote) {
    for (let i = 0; i < remote.pending.length; i++) {
      const p = remote.pending[i]
      this._mux._buffered -= byteSize(p.state)
      this._recv(p.type, p.state)
      if (this._mux._destroying === true) return
    }

    remote.pending = null
    this._mux._resumeMaybe()
  }

  _track(p) {
    if (isPromise(p) === true) {
      this._active++
      return p.then(this._decBound, this._decAndDestroyBound)
    }

    return null
  }

  _close(isRemote) {
    if (this.closed === true) return
    this.closed = true

    this._info.opened--
    if (this._info.lastChannel === this) this._info.lastChannel = null

    if (this._remoteId > 0) {
      this._mux._remote[this._remoteId - 1] = null
      this._remoteId = 0
      // If remote has acked, we can reuse the local id now
      // otherwise, we need to wait for the "ack" to arrive
      this._mux._free.push(this._localId - 1)
    }

    this._mux._local[this._localId - 1] = null
    this._localId = 0

    this._mux._gc(this._info)
    this._track(this.onclose(isRemote, this))

    if (this._active === 0) this._destroy()

    this._resolveOpen(false)
  }

  _destroy() {
    if (this.destroyed === true) return
    this.destroyed = true
    this._track(this.ondestroy(this))
    this._resolveDestroyed()
  }

  _recv(type, state) {
    if (type < this.messages.length) {
      const m = this.messages[type]
      const p = m.recv(state, this)
      if (m.autoBatch === true) return p
    }
    return null
  }

  cork() {
    this._mux.cork()
  }

  uncork() {
    this._mux.uncork()
  }

  close() {
    if (this.closed === true) return

    const state = { buffer: null, start: 2, end: 2 }

    c.uint.preencode(state, this._localId)

    state.buffer = this._mux._alloc(state.end)

    state.buffer[0] = 0
    state.buffer[1] = 3
    c.uint.encode(state, this._localId)

    this._close(false)
    this._mux._write0(state.buffer)
  }

  addMessage(opts) {
    if (!opts) return this._skipMessage()

    const type = this.messages.length
    const autoBatch = opts.autoBatch !== false
    const encoding = opts.encoding || c.raw
    const onmessage = opts.onmessage || noop

    const s = this
    const typeLen = encodingLength(c.uint, type)

    const m = {
      type,
      autoBatch,
      encoding,
      onmessage,
      recv(state, session) {
        return session._track(m.onmessage(encoding.decode(state), session))
      },
      send(m, session = s) {
        if (session.closed === true) return false

        const mux = session._mux
        const state = { buffer: null, start: 0, end: typeLen }

        if (mux._batch !== null) {
          encoding.preencode(state, m)
          state.buffer = mux._alloc(state.end)

          c.uint.encode(state, type)
          encoding.encode(state, m)

          mux._pushBatch(session._localId, state.buffer)
          return true
        }

        c.uint.preencode(state, session._localId)
        encoding.preencode(state, m)

        state.buffer = mux._alloc(state.end)

        c.uint.encode(state, session._localId)
        c.uint.encode(state, type)
        encoding.encode(state, m)

        mux.drained = mux.stream.write(state.buffer)

        return mux.drained
      }
    }

    this.messages.push(m)

    return m
  }

  _skipMessage() {
    const type = this.messages.length
    const m = {
      type,
      encoding: c.raw,
      onmessage: noop,
      recv(state, session) {},
      send(m, session) {}
    }

    this.messages.push(m)
    return m
  }
}

module.exports = class Protomux {
  constructor(stream, { alloc } = {}) {
    if (stream.userData === null) stream.userData = this

    this.isProtomux = true
    this.stream = stream
    this.corked = 0
    this.drained = true

    this._alloc =
      alloc || (typeof stream.alloc === 'function' ? stream.alloc.bind(stream) : b4a.allocUnsafe)
    this._safeDestroyBound = this._safeDestroy.bind(this)
    this._uncorkBound = this.uncork.bind(this)

    this._remoteBacklog = 0
    this._buffered = 0
    this._paused = false
    this._remote = []
    this._local = []
    this._free = []
    this._batch = null
    this._batchState = null

    this._infos = new Map()
    this._notify = new Map()
    // stream.destroyed flips asynchronously on streamx-based transports.
    this._destroying = false

    this.stream.on('data', this._ondata.bind(this))
    this.stream.on('drain', this._ondrain.bind(this))
    this.stream.on('end', this._onend.bind(this))
    this.stream.on('error', noop) // we handle this in "close"
    this.stream.on('close', this._shutdown.bind(this))
  }

  static from(stream, opts) {
    if (stream.userData && stream.userData.isProtomux) return stream.userData
    if (stream.isProtomux) return stream
    return new this(stream, opts)
  }

  static isProtomux(mux) {
    return typeof mux === 'object' && mux.isProtomux === true
  }

  *[Symbol.iterator]() {
    for (const session of this._local) {
      if (session !== null) yield session
    }
  }

  isIdle() {
    return this._local.length === this._free.length
  }

  cork() {
    if (++this.corked === 1) {
      this._batch = []
      this._batchState = { buffer: null, start: 0, end: 1 }
    }
  }

  uncork() {
    if (--this.corked === 0) {
      this._sendBatch(this._batch, this._batchState)
      this._batch = null
      this._batchState = null
    }
  }

  getLastChannel({ protocol, id = null }) {
    const key = toKey(protocol, id)
    const info = this._infos.get(key)
    if (info) return info.lastChannel
    return null
  }

  pair({ protocol, id = null }, notify) {
    this._notify.set(toKey(protocol, id), notify)
  }

  unpair({ protocol, id = null }) {
    this._notify.delete(toKey(protocol, id))
  }

  opened({ protocol, id = null }) {
    const key = toKey(protocol, id)
    const info = this._infos.get(key)
    return info ? info.opened > 0 : false
  }

  createChannel({
    userData = null,
    protocol,
    aliases = [],
    id = null,
    unique = true,
    handshake = null,
    messages = [],
    onopen = noop,
    onclose = noop,
    ondestroy = noop,
    ondrain = noop
  }) {
    if (this.stream.destroyed) return null

    const info = this._get(protocol, id, aliases)
    if (unique && info.opened > 0) return null

    if (info.incoming.length === 0) {
      return new Channel(
        this,
        info,
        userData,
        protocol,
        aliases,
        id,
        handshake,
        messages,
        onopen,
        onclose,
        ondestroy,
        ondrain
      )
    }

    this._remoteBacklog--

    const remoteId = info.incoming.shift()
    const r = this._remote[remoteId - 1]
    if (r === null) return null

    const session = new Channel(
      this,
      info,
      userData,
      protocol,
      aliases,
      id,
      handshake,
      messages,
      onopen,
      onclose,
      ondestroy,
      ondrain
    )

    session._remoteId = remoteId
    session._fullyOpenSoon()

    return session
  }

  _pushBatch(localId, buffer) {
    if (this._batchState.end >= MAX_BATCH) {
      this._sendBatch(this._batch, this._batchState)
      this._batch = []
      this._batchState = { buffer: null, start: 0, end: 1 }
    }

    if (this._batch.length === 0 || this._batch[this._batch.length - 1].localId !== localId) {
      this._batchState.end++
      c.uint.preencode(this._batchState, localId)
    }
    c.buffer.preencode(this._batchState, buffer)
    this._batch.push({ localId, buffer })
  }

  _sendBatch(batch, state) {
    if (batch.length === 0) return

    let prev = batch[0].localId

    state.buffer = this._alloc(state.end)
    state.buffer[state.start++] = 0
    state.buffer[state.start++] = 0

    c.uint.encode(state, prev)

    for (let i = 0; i < batch.length; i++) {
      const b = batch[i]
      if (prev !== b.localId) {
        state.buffer[state.start++] = 0
        c.uint.encode(state, (prev = b.localId))
      }
      c.buffer.encode(state, b.buffer)
    }

    this.drained = this.stream.write(state.buffer)
  }

  _get(protocol, id, aliases = []) {
    const key = toKey(protocol, id)

    let info = this._infos.get(key)
    if (info) return info

    info = {
      key,
      protocol,
      aliases: [],
      id,
      pairing: 0,
      opened: 0,
      incoming: [],
      outgoing: [],
      lastChannel: null
    }
    this._infos.set(key, info)

    for (const alias of aliases) {
      const key = toKey(alias, id)
      info.aliases.push(key)

      this._infos.set(key, info)
    }

    return info
  }

  _gc(info) {
    if (info.opened === 0 && info.outgoing.length === 0 && info.incoming.length === 0) {
      this._infos.delete(info.key)

      for (const alias of info.aliases) this._infos.delete(alias)
    }
  }

  _ondata(buffer) {
    if (buffer.byteLength === 0) return // ignore empty frames...
    try {
      const state = { buffer, start: 0, end: buffer.byteLength }
      this._decode(c.uint.decode(state), state)
    } catch (err) {
      this._safeDestroy(err)
    }
  }

  _ondrain() {
    this.drained = true

    for (const s of this._local) {
      if (s !== null) s._track(s.ondrain(s))
    }
  }

  _onend() {
    // TODO: support half open mode for the users who wants that here
    this.stream.end()
  }

  _decode(remoteId, state) {
    const type = c.uint.decode(state)

    if (remoteId === 0) {
      return this._oncontrolsession(type, state)
    }

    const r = remoteId <= this._remote.length ? this._remote[remoteId - 1] : null

    // if the channel is closed ignore - could just be a pipeline message...
    if (r === null) return null

    if (r.pending !== null) {
      this._bufferMessage(r, type, state)
      return null
    }

    return r.session._recv(type, state)
  }

  _oncontrolsession(type, state) {
    switch (type) {
      case 0:
        this._onbatch(state)
        break

      case 1:
        // return the promise back up as this has sideeffects so we can batch reply
        return this._onopensession(state)

      case 2:
        this._onrejectsession(state)
        break

      case 3:
        this._onclosesession(state)
        break
    }

    return null
  }

  _bufferMessage(r, type, { buffer, start, end }) {
    const state = { buffer, start, end } // copy
    r.pending.push({ type, state })
    this._buffered += byteSize(state)
    this._pauseMaybe()
  }

  _pauseMaybe() {
    if (this._paused === true || this._buffered <= MAX_BUFFERED) return
    this._paused = true
    this.stream.pause()
  }

  _resumeMaybe() {
    if (this._paused === false || this._buffered > MAX_BUFFERED) return
    this._paused = false
    this.stream.resume()
  }

  _onbatch(state) {
    const end = state.end
    let remoteId = c.uint.decode(state)

    let waiting = null

    while (state.end > state.start) {
      const len = c.uint.decode(state)
      if (len === 0) {
        remoteId = c.uint.decode(state)
        continue
      }
      state.end = state.start + len
      // if batch contains more than one message, cork it so we reply back with a batch
      if (end !== state.end && waiting === null) {
        waiting = []
        this.cork()
      }
      const p = this._decode(remoteId, state)
      if (waiting !== null && p !== null) waiting.push(p)
      state.start = state.end
      state.end = end
    }

    if (waiting !== null) {
      // the waiting promises are not allowed to throw but we destroy the stream in case we are wrong
      Promise.all(waiting).then(this._uncorkBound, this._safeDestroyBound)
    }
  }

  _onopensession(state) {
    const remoteId = c.uint.decode(state)
    const protocol = c.string.decode(state)
    const id = unslab(c.optionalBuffer.decode(state))

    // remote tried to open the control session - auto reject for now
    // as we can use as an explicit control protocol declaration if we need to
    if (remoteId === 0) {
      this._rejectSession(0)
      return null
    }

    const rid = remoteId - 1
    const info = this._get(protocol, id)

    // allow the remote to grow the ids by one
    if (this._remote.length === rid) {
      this._remote.push(null)
    }

    if (rid >= this._remote.length || this._remote[rid] !== null) {
      throw new Error('Invalid open message')
    }

    if (info.outgoing.length > 0) {
      const localId = info.outgoing.shift()
      const session = this._local[localId - 1]

      if (session === null) {
        // we already closed the channel - ignore
        this._free.push(localId - 1)
        return null
      }

      this._remote[rid] = { state, pending: null, session: null }

      session._remoteId = remoteId
      session._fullyOpen()
      return null
    }

    const copyState = { buffer: state.buffer, start: state.start, end: state.end }
    this._remote[rid] = { state: copyState, pending: [], session: null }

    if (++this._remoteBacklog > MAX_BACKLOG) {
      throw new Error('Remote exceeded backlog')
    }

    info.pairing++
    info.incoming.push(remoteId)

    return this._requestSession(protocol, id, info).catch(this._safeDestroyBound)
  }

  _onrejectsession(state) {
    const localId = c.uint.decode(state)

    // TODO: can be done smarter...
    for (const info of this._infos.values()) {
      const i = info.outgoing.indexOf(localId)
      if (i === -1) continue

      info.outgoing.splice(i, 1)

      const session = this._local[localId - 1]

      this._free.push(localId - 1)
      if (session !== null) session._close(true)

      this._gc(info)
      return
    }

    throw new Error('Invalid reject message')
  }

  _onclosesession(state) {
    const remoteId = c.uint.decode(state)

    if (remoteId === 0) return // ignore

    const rid = remoteId - 1
    const r = rid < this._remote.length ? this._remote[rid] : null

    if (r === null) return

    if (r.session !== null) r.session._close(true)
  }

  async _requestSession(protocol, id, info) {
    const notify = this._notify.get(toKey(protocol, id)) || this._notify.get(toKey(protocol, null))

    if (notify) await notify(id)

    if (--info.pairing > 0) return

    while (info.incoming.length > 0) {
      this._rejectSession(info, info.incoming.shift())
    }

    this._gc(info)
  }

  _rejectSession(info, remoteId) {
    if (remoteId > 0) {
      const r = this._remote[remoteId - 1]

      if (r.pending !== null) {
        for (let i = 0; i < r.pending.length; i++) {
          this._buffered -= byteSize(r.pending[i].state)
        }
      }

      this._remote[remoteId - 1] = null
      this._resumeMaybe()
    }

    const state = { buffer: null, start: 2, end: 2 }

    c.uint.preencode(state, remoteId)

    state.buffer = this._alloc(state.end)

    state.buffer[0] = 0
    state.buffer[1] = 2
    c.uint.encode(state, remoteId)

    this._write0(state.buffer)
  }

  _write0(buffer) {
    if (this._batch !== null) {
      this._pushBatch(0, buffer.subarray(1))
      return
    }

    this.drained = this.stream.write(buffer)
  }

  destroy(err) {
    this._destroying = true
    this.stream.destroy(err)
  }

  _safeDestroy(err) {
    safetyCatch(err)
    this._destroying = true
    this.stream.destroy(err)
  }

  _shutdown() {
    this._destroying = true
    for (const s of this._local) {
      if (s !== null) s._close(true)
    }
  }
}

function noop() {}

function toKey(protocol, id) {
  return protocol + '##' + (id ? b4a.toString(id, 'hex') : '')
}

function byteSize(state) {
  return 512 + (state.end - state.start)
}

function isPromise(p) {
  return !!(p && typeof p.then === 'function')
}

function encodingLength(enc, val) {
  const state = { buffer: null, start: 0, end: 0 }
  enc.preencode(state, val)
  return state.end
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "protomux",
  "version": "3.11.0",
  "description": "Multiplex multiple message oriented protocols over a stream",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.3.1",
    "compact-encoding": "^3.0.0",
    "queue-tick": "^1.0.0",
    "safety-catch": "^1.0.1",
    "unslab": "^1.3.0"
  },
  "devDependencies": {
    "@hyperswarm/secret-stream": "^6.0.0",
    "brittle": "^3.0.0",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/protomux.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/protomux/issues"
  },
  "homepage": "https://github.com/holepunchto/protomux"
}
{
  "name": "queue-tick",
  "version": "1.0.1",
  "description": "Next tick shim that prefers process.nextTick over queueMicrotask for compat",
  "main": "./process-next-tick.js",
  "browser": "./queue-microtask.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^16.0.3",
    "tape": "^5.3.1"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/queue-tick.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/queue-tick/issues"
  },
  "homepage": "https://github.com/mafintosh/queue-tick"
}
module.exports = (typeof process !== 'undefined' && typeof process.nextTick === 'function')
  ? process.nextTick.bind(process)
  : require('./queue-microtask')
module.exports = typeof queueMicrotask === 'function' ? queueMicrotask : (fn) => Promise.resolve().then(fn)
const EventEmitter = require('events')

module.exports = class ReadyResource extends EventEmitter {
  constructor () {
    super()

    this.opening = null
    this.closing = null

    this.opened = false
    this.closed = false
  }

  ready () {
    if (this.opening !== null) return this.opening
    this.opening = open(this)
    return this.opening
  }

  close () {
    if (this.closing !== null) return this.closing
    this.closing = close(this)
    return this.closing
  }

  async _open () {
    // add impl here
  }

  async _close () {
    // add impl here
  }
}

async function open (self) {
  // open after close
  if (self.closing !== null) return

  try {
    await self._open()
  } catch (err) {
    self.close() // safe to run in bg
    throw err
  }

  self.opened = true
  self.emit('ready')
}

async function close (self) {
  try {
    if (self.opened === false && self.opening !== null) await self.opening
  } catch {
    // ignore errors on closing
  }
  if (self.opened === true || self.opening === null) await self._close()
  self.closed = true
  self.emit('close')
}
{
  "name": "ready-resource",
  "version": "1.2.0",
  "description": "Modern single resource management",
  "main": "index.js",
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "types": "index.d.ts",
  "files": [
    "index.js",
    "index.d.ts"
  ],
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "devDependencies": {
    "brittle": "^3.1.0",
    "standard": "^17.0.0"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/ready-resource.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/ready-resource/issues"
  },
  "homepage": "https://github.com/holepunchto/ready-resource",
  "dependencies": {
    "bare-events": "^2.2.0"
  }
}
const b4a = require('b4a')

var EMPTY = []

module.exports = RecordCache

function RecordSet () {
  this.list = []
  this.map = new Map()
}

RecordSet.prototype.add = function (record, value) {
  var k = toString(record)
  var r = this.map.get(k)
  if (r) return false

  r = {index: this.list.length, record: value || record}
  this.list.push(r)
  this.map.set(k, r)
  return true
}

RecordSet.prototype.remove = function (record) {
  var k = toString(record)
  var r = this.map.get(k)
  if (!r) return false

  swap(this.list, r.index, this.list.length - 1)
  this.list.pop()
  this.map.delete(k)
  return true
}

function RecordStore () {
  this.records = new Map()
  this.size = 0
}

RecordStore.prototype.add = function (name, record, value) {
  var r = this.records.get(name)

  if (!r) {
    r = new RecordSet()
    this.records.set(name, r)
  }

  if (r.add(record, value)) {
    this.size++
    return true
  }

  return false
}

RecordStore.prototype.remove = function (name, record, value) {
  var r = this.records.get(name)
  if (!r) return false

  if (r.remove(record, value)) {
    this.size--
    if (!r.map.size) this.records.delete(name)
    return true
  }

  return false
}

RecordStore.prototype.get = function (name) {
  var r = this.records.get(name)
  return r ? r.list : EMPTY
}

function RecordCache (opts) {
  if (!(this instanceof RecordCache)) return new RecordCache(opts)
  if (!opts) opts = {}

  this.maxSize = opts.maxSize || Infinity
  this.maxAge = opts.maxAge || 0

  this._onstale = opts.onStale || opts.onstale || null
  this._fresh = new RecordStore()
  this._stale = new RecordStore()
  this._interval = null
  this._gced = false

  if (this.maxAge && this.maxAge < Infinity) {
    // 2/3 gives us a span of 0.66-1.33 maxAge or avg maxAge
    var tick = Math.ceil(2 / 3 * this.maxAge)
    this._interval = setInterval(this._gcAuto.bind(this), tick)
    if (this._interval.unref) this._interval.unref()
  }
}

Object.defineProperty(RecordCache.prototype, 'size', {
  get: function () {
    return this._fresh.size + this._stale.size
  }
})

RecordCache.prototype.add = function (name, record, value) {
  this._stale.remove(name, record, value)
  if (this._fresh.add(name, record, value) && this._fresh.size > this.maxSize) {
    this._gc()
  }
}

RecordCache.prototype.remove = function (name, record, value) {
  this._fresh.remove(name, record, value)
  this._stale.remove(name, record, value)
}

RecordCache.prototype.get = function (name, n) {
  var a = this._fresh.get(name)
  var b = this._stale.get(name)
  var aLen = a.length
  var bLen = b.length
  var len = aLen + bLen

  if (n > len || !n) n = len
  var result = new Array(n)

  for (var i = 0; i < n; i++) {
    var j = Math.floor(Math.random() * (aLen + bLen))
    if (j < aLen) {
      result[i] = a[j].record
      swap(a, j, --aLen)
    } else {
      j -= aLen
      result[i] = b[j].record
      swap(b, j, --bLen)
    }
  }

  return result
}

RecordCache.prototype._gcAuto = function () {
  if (!this._gced) this._gc()
  this._gced = false
}

RecordCache.prototype._gc = function () {
  if (this._onstale && this._stale.size > 0) this._onstale(this._stale)
  this._stale = this._fresh
  this._fresh = new RecordStore()
  this._gced = true
}

RecordCache.prototype.clear = function () {
  this._gc()
  this._gc()
}

RecordCache.prototype.destroy = function () {
  this.clear()
  clearInterval(this._interval)
  this._interval = null
}

function toString (record) {
  return b4a.isBuffer(record) ? b4a.toString(record, 'hex') : record
}

function swap (list, a, b) {
  var tmp = list[a]
  tmp.index = b
  list[b].index = a
  list[a] = list[b]
  list[b] = tmp
}
{
  "name": "record-cache",
  "version": "1.2.0",
  "description": "Cache optimised for record like things",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.3.1"
  },
  "devDependencies": {
    "standard": "^10.0.3",
    "tape": "^4.8.0"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/record-cache.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/record-cache/issues"
  },
  "homepage": "https://github.com/mafintosh/record-cache"
}
module.exports = require.addon.bind(require)
{
  "name": "require-addon",
  "version": "1.2.0",
  "description": "Import native addons across JavaScript runtimes",
  "exports": {
    "./package": "./package.json",
    ".": {
      "bare": "./lib/bare.js",
      "node": "./lib/node.js",
      "default": "./lib/default.js"
    }
  },
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    },
    "url": {
      "bare": "bare-url",
      "default": "url"
    }
  },
  "files": [
    "lib"
  ],
  "scripts": {
    "test": "npm run lint && npm run test:bare && npm run test:node",
    "test:bare": "bare test.js",
    "test:node": "node test.js",
    "lint": "prettier --check .",
    "format": "prettier --write ."
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/require-addon.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/require-addon/issues"
  },
  "homepage": "https://github.com/holepunchto/require-addon#readme",
  "engines": {
    "bare": ">=1.10.0"
  },
  "dependencies": {
    "bare-addon-resolve": "^1.3.0"
  },
  "devDependencies": {
    "bare-bundle": "^1.8.1",
    "bare-bundle-evaluate": "^1.1.0",
    "bare-fs": "^4.0.0",
    "bare-path": "^3.0.0",
    "bare-url": "^2.1.0",
    "brittle": "^3.7.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = safetyCatch

function isActuallyUncaught (err) {
  if (!err) return false
  return err instanceof TypeError ||
    err instanceof SyntaxError ||
    err instanceof ReferenceError ||
    err instanceof EvalError ||
    err instanceof RangeError ||
    err instanceof URIError ||
    err.code === 'ERR_ASSERTION' ||
    err.name === 'AssertionError'
}

function throwErrorNT (err) {
  queueMicrotask(() => { throw err })
}

function safetyCatch (err) {
  if (isActuallyUncaught(err)) {
    throwErrorNT(err)
    throw err
  }
}
{
  "name": "safety-catch",
  "version": "1.0.3",
  "description": "Small module that makes sure your catch, caught an actual error and not a programming mistake or assertion",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {},
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/safety-catch.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/safety-catch/issues"
  },
  "homepage": "https://github.com/mafintosh/safety-catch"
}
const set = require('unordered-set')

module.exports = opts => new ShuffledPriorityQueue(opts)

class ShuffledPriorityQueue {
  constructor (opts) {
    this.priorities = []
    this.equals = (opts && opts.equals) || null
  }

  get length () {
    return this.priorities.reduce(add, 0)
  }

  [Symbol.iterator] () {
    return new Iterator(this)
  }

  head () {
    for (let i = this.priorities.length - 1; i >= 0; i--) {
      const q = this.priorities[i]
      if (q.length) return shuffle(q, 0)
    }
    return null
  }

  tail () {
    for (let i = 0; i < this.priorities.length; i++) {
      const q = this.priorities[i]
      if (q.length) return shuffle(q, 0)
    }
    return null
  }

  prev (prev) {
    if (!prev) return this.tail()
    return next(this.priorities, prev, 1)
  }

  next (prev) {
    if (!prev) return this.head()
    return next(this.priorities, prev, -1)
  }

  shift () {
    return this.remove(this.head())
  }

  pop () {
    return this.remove(this.tail())
  }

  add (val) {
    const prio = val.priority || 0
    while (prio >= this.priorities.length) this.priorities.push([])
    set.add(this.priorities[prio], val)
    return val
  }

  remove (val) {
    if (!val) return null

    if (val._index === undefined) {
      val = this.find(val)
      if (!val) return null
    }

    return set.remove(this.priorities[val.priority || 0], val)
  }

  has (val) {
    if (val._index === undefined) return this.find(val)
    const priority = val.priority || 0
    if (priority >= this.priorities.length) return false
    return set.has(this.priorities[priority], val)
  }

  find (val) {
    if (val._index !== undefined) return val

    const prio = val.priority || 0
    const qs = this.priorities
    if (prio >= qs.length) return null

    const q = qs[prio]

    for (let i = 0; i < q.length; i++) {
      if (this.equals(q[i], val)) return q[i]
    }

    return null
  }
}

class Iterator {
  constructor (queue) {
    this.prev = null
    this.queue = queue
  }

  next () {
    const next = this.queue.next(this.prev)
    this.prev = next
    return { done: !next, value: next }
  }
}

function shuffle (q, i) {
  const ran = i + Math.floor(Math.random() * (q.length - i))
  set.swap(q, q[ran], q[i])
  return q[i]
}

function next (queues, prev, inc) {
  let i = prev.priority || 0
  let j = (prev._index || 0) + 1

  while (true) {
    if (i < 0 || i >= queues.length) return null
    const q = queues[i]

    if (j >= q.length) {
      i += inc
      j = 0
      continue
    }

    return shuffle(q, j)
  }
}

function add (len, b) {
  return len + b.length
}
{
  "name": "shuffled-priority-queue",
  "version": "2.1.0",
  "description": "A priority queue that shuffles elements with the same priority.",
  "main": "index.js",
  "scripts": {
    "test": "standard && tape test.js"
  },
  "dependencies": {
    "unordered-set": "^2.0.1"
  },
  "devDependencies": {
    "standard": "^12.0.1",
    "tape": "^4.9.1"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/shuffled-priority-queue.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/shuffled-priority-queue/issues"
  },
  "homepage": "https://github.com/mafintosh/shuffled-priority-queue"
}
module.exports = class Signal {
  constructor () {
    this._resolve = null
    this._reject = null
    this._promise = null
    this._bind = bind.bind(this)
    this._onerror = clear.bind(this)
    this._onsuccess = clear.bind(this, null)
    this._timers = new Set()
  }

  wait (max) {
    if (!this._promise) {
      this._promise = new Promise(this._bind)
      this._promise.then(this._onsuccess).catch(this._onerror)
    }
    if (max) return this._sleep(max)
    return this._promise
  }

  _sleep (max) {
    const s = new Promise((resolve, reject) => {
      const done = () => {
        this._timers.delete(state)
        resolve(true)
      }
      const id = setTimeout(done, max)
      const state = { id, resolve, reject }
      this._timers.add(state)
    })

    return s
  }

  notify (err) {
    if (!this._promise) return
    const resolve = this._resolve
    const reject = this._reject
    this._promise = null
    if (err) reject(err)
    else resolve(true)
  }
}

function clear (err) {
  for (const { id, resolve, reject } of this._timers) {
    clearTimeout(id)
    if (err) reject(err)
    else resolve(true)
  }
  this._timers.clear()
}

function bind (resolve, reject) {
  this._resolve = resolve
  this._reject = reject
}
{
  "name": "signal-promise",
  "version": "1.0.3",
  "description": "Simple wait/notify promise with optional max wait time",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {},
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/signal-promise.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/signal-promise/issues"
  },
  "homepage": "https://github.com/mafintosh/signal-promise"
}
require.addon = require('require-addon')
module.exports = require.addon('.', __filename)
const assert = require('assert')
const binding = require('./binding')
const { isNode } = require('which-runtime')

const OPTIONAL = Buffer.from(new ArrayBuffer(0))

module.exports = exports = { ...binding }

// memory

exports.sodium_memzero = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  binding.sodium_memzero(buf)
}

exports.sodium_mlock = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  const res = binding.sodium_mlock(buf)

  if (res !== 0) throw new Error('memory lock failed')
}

exports.sodium_munlock = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  const res = binding.sodium_munlock(buf)

  if (res !== 0) throw new Error('memory unlock failed')
}

exports.sodium_malloc = function (size) {
  assert(size >= 0, 'invalid size')

  const buf = Buffer.from(binding.sodium_malloc(size))
  buf.secure = true
  return buf
}

exports.sodium_free = function (buf) {
  if (!buf || !buf.secure) return

  binding.sodium_free(buf.buffer)
}

exports.sodium_mprotect_noaccess = function (buf) {
  const res = binding.sodium_mprotect_noaccess(buf.buffer)

  if (res !== 0) throw new Error('failed to lock buffer')
}

exports.sodium_mprotect_readonly = function (buf) {
  const res = binding.sodium_mprotect_readonly(buf.buffer)

  if (res !== 0) throw new Error('failed to unlock buffer')
}

exports.sodium_mprotect_readwrite = function (buf) {
  const res = binding.sodium_mprotect_readwrite(buf.buffer)

  if (res !== 0) throw new Error('failed to unlock buffer')
}

// crypto_randombytes

exports.randombytes_buf = function (buffer) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')

  binding.randombytes_buf(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

exports.randombytes_buf_deterministic = function (buffer, seed) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    seed.byteLength === binding.randombytes_SEEDBYTES,
    "seed must be 'randombytes_SEEDBYTES' bytes"
  )

  binding.randombytes_buf_deterministic(
    buffer.buffer,
    buffer.byteOffset,
    buffer.byteLength,

    seed.buffer,
    seed.byteOffset,
    seed.byteLength
  )
}

// sodium_helpers

exports.sodium_memcmp = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  return binding.sodium_memcmp(a, b)
}

exports.sodium_add = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  binding.sodium_add(a, b)
}

exports.sodium_sub = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  binding.sodium_sub(a, b)
}

exports.sodium_compare = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  return binding.sodium_compare(a, b)
}

exports.sodium_is_zero = function (buffer, length) {
  if (length === undefined) length = buffer.byteLength

  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(length >= 0 && length <= buffer.byteLength, 'invalid length')

  return binding.sodium_is_zero(buffer, length)
}

exports.sodium_pad = function (buffer, unpaddedBuflen, blockSize) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(unpaddedBuflen <= buffer.byteLength, 'unpadded length cannot exceed buffer length')
  assert(blockSize <= buffer.byteLength, 'block size cannot exceed buffer length')
  assert(blockSize >= 1, 'block size must be at least 1 byte')
  assert(
    buffer.byteLength >= unpaddedBuflen + (blockSize - (unpaddedBuflen % blockSize)),
    'buf not long enough'
  )

  return binding.sodium_pad(buffer, unpaddedBuflen, blockSize)
}

exports.sodium_unpad = function (buffer, paddedBuflen, blockSize) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(paddedBuflen <= buffer.byteLength, 'unpadded length cannot exceed buffer length')
  assert(blockSize <= buffer.byteLength, 'block size cannot exceed buffer length')
  assert(blockSize >= 1, 'block size must be at least 1 byte')

  return binding.sodium_unpad(buffer, paddedBuflen, blockSize)
}

// crypto_sign

exports.crypto_sign_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )
  assert(
    seed.byteLength === binding.crypto_sign_SEEDBYTES,
    "seed must be 'crypto_sign_SEEDBYTES' bytes"
  )

  const res = binding.crypto_sign_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign = function (sm, m, sk) {
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sm.byteLength === binding.crypto_sign_BYTES + m.byteLength,
    "sm must be 'm.byteLength + crypto_sign_BYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign(sm, m, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_open = function (m, sm, pk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sm.byteLength >= binding.crypto_sign_BYTES,
    "sm must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    m.byteLength === sm.byteLength - binding.crypto_sign_BYTES,
    "m must be 'sm.byteLength - crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_open(m, sm, pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_open = function (m, sm, pk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sm.byteLength >= binding.crypto_sign_BYTES,
    "sm must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    m.byteLength === sm.byteLength - binding.crypto_sign_BYTES,
    "m must be 'sm.byteLength - crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  return binding.crypto_sign_open(m, sm, pk)
}

exports.crypto_sign_detached = function (sig, m, sk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(sig.byteLength === binding.crypto_sign_BYTES, "sig must be 'crypto_sign_BYTES' bytes")
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_detached(sig, m, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_verify_detached = function (sig, m, pk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sig.byteLength >= binding.crypto_sign_BYTES,
    "sig must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  return binding.crypto_sign_verify_detached(
    sig.buffer,
    sig.byteOffset,
    sig.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    pk.buffer,
    pk.byteOffset,
    pk.byteLength
  )
}

exports.crypto_sign_ed25519_sk_to_pk = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_sk_to_pk(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_ed25519_pk_to_curve25519 = function (x25519pk, ed25519pk) {
  assert(ArrayBuffer.isView(x25519pk), 'x25519pk must be a typed array')
  assert(ArrayBuffer.isView(ed25519pk), 'ed25519pk must be a typed array')
  assert(
    x25519pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "x25519pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    ed25519pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "ed25519pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_pk_to_curve25519(x25519pk, ed25519pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_ed25519_sk_to_curve25519 = function (x25519sk, ed25519sk) {
  assert(ArrayBuffer.isView(x25519sk), 'x25519sk must be a typed array')
  assert(ArrayBuffer.isView(ed25519sk), 'ed25519sk must be a typed array')
  assert(
    x25519sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "x25519sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const edLen = ed25519sk.byteLength

  assert(
    edLen === binding.crypto_sign_SECRETKEYBYTES || edLen === binding.crypto_box_SECRETKEYBYTES,
    "ed25519sk must be 'crypto_sign_SECRETKEYBYTES' or 'crypto_sign_SECRETKEYBYTES - crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_sk_to_curve25519(x25519sk, ed25519sk)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_box

exports.crypto_box_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    seed.byteLength === binding.crypto_box_SEEDBYTES,
    "seed must be 'crypto_box_SEEDBYTES' bytes"
  )

  const res = binding.crypto_box_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_easy = function (c, m, n, pk, sk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength === m.byteLength + exports.crypto_box_MACBYTES,
    "c must be 'm.byteLength + crypto_box_MACBYTES' bytes"
  )
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_easy(c, m, n, pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_detached = function (c, mac, m, n, pk, sk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(mac.byteLength === exports.crypto_box_MACBYTES, "mac must be 'crypto_box_MACBYTES' bytes")
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_detached(c, mac, m, n, pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_open_easy = function (m, c, n, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength >= exports.crypto_box_MACBYTES,
    "c must be at least 'crypto_box_MACBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - exports.crypto_box_MACBYTES,
    "m must be 'c.byteLength - crypto_box_MACBYTES' bytes"
  )
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_open_easy(m, c, n, pk, sk)
}

exports.crypto_box_open_detached = function (m, c, mac, n, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(mac.byteLength === exports.crypto_box_MACBYTES, "mac must be 'crypto_box_MACBYTES' bytes")
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_open_detached(m, c, mac, n, pk, sk)
}

exports.crypto_box_seal = function (c, m, pk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    c.byteLength === m.byteLength + exports.crypto_box_SEALBYTES,
    "c must be 'm.byteLength + crypto_box_SEALBYTES' bytes"
  )
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_box_seal(c, m, pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_seal_open = function (m, c, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength >= exports.crypto_box_SEALBYTES,
    "c must be at least 'crypto_box_SEALBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - exports.crypto_box_SEALBYTES,
    "m must be 'c.byteLength - crypto_box_SEALBYTES' bytes"
  )
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_seal_open(
    m.buffer,
    m.byteOffset,
    m.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    pk.buffer,
    pk.byteOffset,
    pk.byteLength,

    sk.buffer,
    sk.byteOffset,
    sk.byteLength
  )
}

// crypto_secretbox

exports.crypto_secretbox_easy = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_secretbox_MACBYTES,
    "c must be 'm.byteLength + crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretbox_easy(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretbox_open_easy = function (m, c, n, k) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    c.byteLength >= binding.crypto_secretbox_MACBYTES,
    "c must be at least 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - binding.crypto_secretbox_MACBYTES,
    "m must be 'c.byteLength - crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  return binding.crypto_secretbox_open_easy(m, c, n, k)
}

exports.crypto_secretbox_detached = function (c, mac, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    mac.byteLength === binding.crypto_secretbox_MACBYTES,
    "mac must be 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretbox_detached(c, mac, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretbox_open_detached = function (m, c, mac, n, k) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(
    mac.byteLength === binding.crypto_secretbox_MACBYTES,
    "mac must be 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  return binding.crypto_secretbox_open_detached(m, c, mac, n, k)
}

// crypto_generichash

exports.crypto_generichash = function (output, input, key) {
  if (!key) key = OPTIONAL

  assert(ArrayBuffer.isView(output), 'output must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    output.byteLength >= binding.crypto_generichash_BYTES_MIN &&
      output.byteLength <= binding.crypto_generichash_BYTES_MAX,
    'output must be between crypto_generichash_BYTES_MIN and crypto_generichash_BYTES_MAX bytes'
  )

  if (key !== OPTIONAL) {
    assert(ArrayBuffer.isView(key), 'key must be a typed array')
    assert(
      key.byteLength >= binding.crypto_generichash_KEYBYTES_MIN &&
        key.byteLength <= binding.crypto_generichash_KEYBYTES_MAX,
      'key must be between crypto_generichash_KEYBYTES_MIN and crypto_generichash_KEYBYTES_MAX bytes'
    )
  }

  const res = binding.crypto_generichash(
    output.buffer,
    output.byteOffset,
    output.byteLength,

    input.buffer,
    input.byteOffset,
    input.byteLength,

    key.buffer,
    key.byteOffset,
    key.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_batch = function (output, batch, key) {
  assert(ArrayBuffer.isView(output), 'output must be a typed array')

  if (isNode || batch.length < 4) {
    const res = binding.crypto_generichash_batch(output, batch, !!key, key || OPTIONAL)
    if (res !== 0) throw new Error('status: ' + res)
  } else {
    const state = Buffer.alloc(binding.crypto_generichash_STATEBYTES)

    exports.crypto_generichash_init(state, key, output.byteLength)

    for (const buf of batch) {
      exports.crypto_generichash_update(state, buf)
    }

    exports.crypto_generichash_final(state, output)
  }
}

exports.crypto_generichash_keygen = function (key) {
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(
    key.byteLength === binding.crypto_generichash_KEYBYTES,
    "key must be 'crypto_generichash_KEYBYTES' bytes"
  )

  const res = binding.crypto_generichash_keygen(key.buffer, key.byteOffset, key.byteLength)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_init = function (state, key, outputLength) {
  if (!key) key = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_init(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    key.buffer,
    key.byteOffset,
    key.byteLength,

    outputLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_update(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    input.buffer,
    input.byteOffset,
    input.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_final = function (state, output) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(output), 'output must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_final(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    output.buffer,
    output.byteOffset,
    output.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

// secretstream

exports.crypto_secretstream_xchacha20poly1305_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  binding.crypto_secretstream_xchacha20poly1305_keygen(k.buffer, k.byteOffset, k.byteLength)
}

exports.crypto_secretstream_xchacha20poly1305_init_push = function (state, header, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(header), 'header must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    header.byteLength === binding.crypto_secretstream_xchacha20poly1305_HEADERBYTES,
    "header must be 'crypto_secretstream_xchacha20poly1305_HEADERBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_init_push(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    header.buffer,
    header.byteOffset,
    header.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretstream_xchacha20poly1305_init_pull = function (state, header, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(header), 'header must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    header.byteLength === binding.crypto_secretstream_xchacha20poly1305_HEADERBYTES,
    "header must be 'crypto_secretstream_xchacha20poly1305_HEADERBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_init_pull(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    header.buffer,
    header.byteOffset,
    header.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretstream_xchacha20poly1305_push = function (state, c, m, ad, tag) {
  if (!ad) ad = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    c.byteLength === m.byteLength + binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "c must be 'm.byteLength + crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_push(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    ad.buffer,
    ad.byteOffset,
    ad.byteLength,

    tag
  )

  if (res < 0) throw new Error('push failed')

  return res
}

exports.crypto_secretstream_xchacha20poly1305_pull = function (state, m, tag, c, ad) {
  if (!ad) ad = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(tag), 'tag must be a typed array')
  assert(tag.byteLength === 1, 'tag must be 1 byte')

  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    c.byteLength >= binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "c must be at least 'crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "m must be 'c.byteLength - crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_pull(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    tag.buffer,
    tag.byteOffset,
    tag.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    ad.buffer,
    ad.byteOffset,
    ad.byteLength
  )

  if (res < 0) throw new Error('pull failed')

  return res
}

exports.crypto_secretstream_xchacha20poly1305_rekey = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )

  binding.crypto_secretstream_xchacha20poly1305_rekey(
    state.buffer,
    state.byteOffset,
    state.byteLength
  )
}

// crypto_stream

exports.crypto_stream = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xor(
    c.buffer,
    c.byteOffset,
    c.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    n.buffer,
    n.byteOffset,
    n.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_auth

exports.crypto_auth = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(out.byteLength === binding.crypto_auth_BYTES, "out must be 'crypto_auth_BYTES' bytes")
  assert(k.byteLength === binding.crypto_auth_KEYBYTES, "k must be 'crypto_auth_KEYBYTES' bytes")

  const res = binding.crypto_auth(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_auth_verify = function (h, input, k) {
  assert(ArrayBuffer.isView(h), 'h must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(h.byteLength === binding.crypto_auth_BYTES, "h must be 'crypto_auth_BYTES' bytes")
  assert(k.byteLength === binding.crypto_auth_KEYBYTES, "k must be 'crypto_auth_KEYBYTES' bytes")

  return binding.crypto_auth_verify(h, input, k)
}

// crypto_onetimeauth

exports.crypto_onetimeauth = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    out.byteLength === binding.crypto_onetimeauth_BYTES,
    "out must be 'crypto_onetimeauth_BYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_init = function (state, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_init(state, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )
  assert(
    out.byteLength === binding.crypto_onetimeauth_BYTES,
    "out must be 'crypto_onetimeauth_BYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_verify = function (h, input, k) {
  assert(ArrayBuffer.isView(h), 'h must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    h.byteLength === binding.crypto_onetimeauth_BYTES,
    "h must be 'crypto_onetimeauth_BYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  return binding.crypto_onetimeauth_verify(h, input, k)
}

// crypto_pwhash

exports.crypto_pwhash = function (out, passwd, salt, opslimit, memlimit, alg) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_BYTES_MIN,
    "out must be at least 'crypto_pwhash_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_BYTES_MAX,
    "out must be at most 'crypto_pwhash_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_SALTBYTES,
    "salt must be 'crypto_pwhash_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )
  assert(alg >= 1 && alg <= 2, 'alg must be either Argon2i 1.3 or Argon2id 1.3')

  const res = binding.crypto_pwhash(out, passwd, salt, opslimit, memlimit, alg)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_async = function (
  out,
  passwd,
  salt,
  opslimit,
  memlimit,
  alg,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_BYTES_MIN,
    "out must be at least 'crypto_pwhash_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_BYTES_MAX,
    "out must be at most 'crypto_pwhash_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_SALTBYTES,
    "salt must be 'crypto_pwhash_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )
  assert(alg >= 1 && alg <= 2, 'alg must be either Argon2i 1.3 or Argon2id 1.3')

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    opslimit,
    memlimit,
    alg,

    done
  )

  return promise
}

exports.crypto_pwhash_str = function (out, passwd, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_STRBYTES,
    "out must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(typeof opslimit === 'number', 'opslimit must be a number')
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(typeof memlimit === 'number', 'memlimit must be a number')
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_str(out, passwd, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_str_async = function (out, passwd, opslimit, memlimit, callback = undefined) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_STRBYTES,
    "out must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(typeof opslimit === 'number', 'opslimit must be a number')
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(typeof memlimit === 'number', 'memlimit must be a number')
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_str_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_str_verify = function (str, passwd) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )

  return binding.crypto_pwhash_str_verify(str, passwd)
}

exports.crypto_pwhash_str_verify_async = function (str, passwd, callback = undefined) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  const [done, promise] = checkStatus(callback, true)

  binding.crypto_pwhash_str_verify_async(
    str.buffer,
    str.byteOffset,
    str.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    done
  )

  return promise
}

exports.crypto_pwhash_str_needs_rehash = function (str, opslimit, memlimit) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  return binding.crypto_pwhash_str_needs_rehash(str, opslimit, memlimit)
}

exports.crypto_pwhash_scryptsalsa208sha256 = function (out, passwd, salt, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MIN,
    "out must be at least 'crypto_pwhash_scryptsalsa208sha256_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MAX,
    "out must be at most 'crypto_pwhash_scryptsalsa208sha256_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_SALTBYTES,
    "salt must be 'crypto_pwhash_scryptsalsa208sha256_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_scryptsalsa208sha256(out, passwd, salt, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_scryptsalsa208sha256_async = function (
  out,
  passwd,
  salt,
  opslimit,
  memlimit,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MIN,
    "out must be at least 'crypto_pwhash_scryptsalsa208sha256_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MAX,
    "out must be at most 'crypto_pwhash_scryptsalsa208sha256_BYTES_MAX' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    salt.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_SALTBYTES,
    "salt must be 'crypto_pwhash_scryptsalsa208sha256_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_scryptsalsa208sha256_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str_async = function (
  out,
  passwd,
  opslimit,
  memlimit,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "out must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_scryptsalsa208sha256_str_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str = function (out, passwd, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "out must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_scryptsalsa208sha256_str(out, passwd, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_scryptsalsa208sha256_str_verify_async = function (
  str,
  passwd,
  callback = undefined
) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  const [done, promise] = checkStatus(callback, true)

  binding.crypto_pwhash_scryptsalsa208sha256_str_verify_async(
    str.buffer,
    str.byteOffset,
    str.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str_verify = function (str, passwd) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  return binding.crypto_pwhash_scryptsalsa208sha256_str_verify(str, passwd)
}

exports.crypto_pwhash_scryptsalsa208sha256_str_needs_rehash = function (str, opslimit, memlimit) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  return binding.crypto_pwhash_scryptsalsa208sha256_str_needs_rehash(str, opslimit, memlimit)
}

// crypto_kx

exports.crypto_kx_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "pk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "sk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    pk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "pk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "sk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    seed.byteLength === binding.crypto_kx_SEEDBYTES,
    "seed must be 'crypto_kx_SEEDBYTES' bytes"
  )

  const res = binding.crypto_kx_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_client_session_keys = function (rx, tx, clientPk, clientSk, serverPk) {
  if (!rx) rx = undefined
  if (!tx) tx = undefined

  assert(rx || tx, 'at least one session key must be specified')

  if (rx) {
    assert(ArrayBuffer.isView(rx), 'rx must be a typed array')
    assert(
      rx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "rx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  if (tx) {
    assert(ArrayBuffer.isView(tx), 'tx must be a typed array')
    assert(
      tx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "tx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  assert(ArrayBuffer.isView(clientPk), 'clientPk must be a typed array')
  assert(ArrayBuffer.isView(clientSk), 'clientSk must be a typed array')
  assert(ArrayBuffer.isView(serverPk), 'serverPk must be a typed array')
  assert(
    clientPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "clientPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    clientSk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "clientSk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    serverPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "serverPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_client_session_keys(rx, tx, clientPk, clientSk, serverPk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_server_session_keys = function (rx, tx, serverPk, serverSk, clientPk) {
  if (!rx) rx = undefined
  if (!tx) tx = undefined

  assert(rx || tx, 'at least one session key must be specified')

  if (rx) {
    assert(ArrayBuffer.isView(rx), 'rx must be a typed array')
    assert(
      rx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "rx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  if (tx) {
    assert(ArrayBuffer.isView(tx), 'tx must be a typed array')
    assert(
      tx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "tx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  assert(ArrayBuffer.isView(serverPk), 'serverPk must be a typed array')
  assert(ArrayBuffer.isView(serverSk), 'serverSk must be a typed array')
  assert(ArrayBuffer.isView(clientPk), 'clientPk must be a typed array')
  assert(
    serverPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "serverPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    serverSk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "serverSk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    clientPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "clientPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_server_session_keys(rx, tx, serverPk, serverSk, clientPk)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_scalarmult

exports.crypto_scalarmult_base = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_BYTES,
    "q must be 'crypto_scalarmult_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_SCALARBYTES,
    "n must be 'crypto_scalarmult_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_base(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_BYTES,
    "q must be 'crypto_scalarmult_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_SCALARBYTES,
    "n must be 'crypto_scalarmult_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_BYTES,
    "p must be 'crypto_scalarmult_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_base = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_base(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519 = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "p must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_is_valid_point = function (p) {
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )

  return binding.crypto_core_ed25519_is_valid_point(p)
}

exports.crypto_core_ed25519_from_uniform = function (p, r) {
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_UNIFORMBYTES,
    "r must be 'crypto_core_ed25519_UNIFORMBYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_from_uniform(p, r)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_base_noclamp = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_base_noclamp(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_noclamp = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "p must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_noclamp(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_core

exports.crypto_core_ed25519_add = function (r, p, q) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_BYTES,
    "r must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_core_ed25519_BYTES,
    "q must be 'crypto_core_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_add(r, p, q)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_sub = function (r, p, q) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_BYTES,
    "r must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_core_ed25519_BYTES,
    "q must be 'crypto_core_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_sub(r, p, q)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_scalar_random = function (r) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "r must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_random(r)
}

exports.crypto_core_ed25519_scalar_reduce = function (r, s) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "r must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_NONREDUCEDSCALARBYTES,
    "s must be 'crypto_core_ed25519_NONREDUCEDSCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_reduce(r, s)
}

exports.crypto_core_ed25519_scalar_invert = function (recip, s) {
  assert(ArrayBuffer.isView(recip), 'recip must be a typed array')
  assert(
    recip.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "recip must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_invert(recip, s)
}

exports.crypto_core_ed25519_scalar_negate = function (neg, s) {
  assert(ArrayBuffer.isView(neg), 'neg must be a typed array')
  assert(
    neg.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "neg must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_negate(neg, s)
}

exports.crypto_core_ed25519_scalar_complement = function (comp, s) {
  assert(ArrayBuffer.isView(comp), 'comp must be a typed array')
  assert(
    comp.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "comp must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_complement(comp, s)
}

exports.crypto_core_ed25519_scalar_add = function (z, x, y) {
  assert(ArrayBuffer.isView(z), 'z must be a typed array')
  assert(
    z.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "z must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(x), 'x must be a typed array')
  assert(
    x.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "x must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(y), 'y must be a typed array')
  assert(
    y.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "y must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_add(z, x, y)
}

exports.crypto_core_ed25519_scalar_sub = function (z, x, y) {
  assert(ArrayBuffer.isView(z), 'z must be a typed array')
  assert(
    z.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "z must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(x), 'x must be a typed array')
  assert(
    x.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "x must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(y), 'y must be a typed array')
  assert(
    y.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "y must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_sub(z, x, y)
}

// crypto_shorthash

exports.crypto_shorthash = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_shorthash_BYTES,
    "out must be 'crypto_shorthash_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_shorthash_KEYBYTES,
    "k must be 'crypto_shorthash_KEYBYTES' bytes"
  )

  const res = binding.crypto_shorthash(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_kdf

exports.crypto_kdf_keygen = function (key) {
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(key.byteLength === binding.crypto_kdf_KEYBYTES, "key must be 'crypto_kdf_KEYBYTES' bytes")

  binding.crypto_kdf_keygen(key)
}

exports.crypto_kdf_derive_from_key = function (subkey, subkeyId, ctx, key) {
  assert(ArrayBuffer.isView(subkey), 'subkey must be a typed array')
  assert(
    subkey.byteLength >= binding.crypto_kdf_BYTES_MIN,
    "subkey must be at least 'crypto_kdf_BYTES_MIN' bytes"
  )
  assert(
    subkey.byteLength <= binding.crypto_kdf_BYTES_MAX,
    "subkey must be at most 'crypto_kdf_BYTES_MAX' bytes"
  )
  assert(ArrayBuffer.isView(ctx), 'ctx must be a typed array')
  assert(
    ctx.byteLength === binding.crypto_kdf_CONTEXTBYTES,
    "ctx must be 'crypto_kdf_CONTEXTBYTES' bytes"
  )
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(key.byteLength === binding.crypto_kdf_KEYBYTES, "key must be 'crypto_kdf_KEYBYTES' bytes")

  const res = binding.crypto_kdf_derive_from_key(subkey, subkeyId, ctx, key)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_hash

exports.crypto_hash = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(out.byteLength === binding.crypto_hash_BYTES, "out must be 'crypto_hash_BYTES' bytes")

  const res = binding.crypto_hash(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256 = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha256_BYTES,
    "out must be 'crypto_hash_sha256_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha256(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_init = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_init(state)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha256_BYTES,
    "out must be 'crypto_hash_sha256_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512 = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha512_BYTES,
    "out must be 'crypto_hash_sha512_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha512(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_init = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_init(state)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha512_BYTES,
    "out must be 'crypto_hash_sha512_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_aead

exports.crypto_aead_xchacha20poly1305_ietf_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  binding.crypto_aead_xchacha20poly1305_ietf_keygen(k)
}

exports.crypto_aead_xchacha20poly1305_ietf_encrypt = function (c, m, ad, nsec, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "c must be 'm.byteLength + crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(c.byteLength <= 0xffffffff, 'c.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_encrypt(c, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_decrypt = function (m, nsec, c, ad, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "m must be 'c.byteLength - crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(m.byteLength <= 0xffffffff, 'm.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_decrypt(m, c, ad, npub, k)

  if (res < 0) throw new Error('could not verify data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_encrypt_detached = function (
  c,
  mac,
  m,
  ad,
  nsec,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_encrypt_detached(c, mac, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_decrypt_detached = function (
  m,
  nsec,
  c,
  mac,
  ad,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_decrypt_detached(m, c, mac, ad, npub, k)

  if (res !== 0) throw new Error('could not verify data')
}

exports.crypto_aead_chacha20poly1305_ietf_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  binding.crypto_aead_chacha20poly1305_ietf_keygen(k)
}

exports.crypto_aead_chacha20poly1305_ietf_encrypt = function (c, m, ad, nsec, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "c must be 'm.byteLength + crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(c.byteLength <= 0xffffffff, 'c.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_encrypt(c, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_decrypt = function (m, nsec, c, ad, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "m must be 'c.byteLength - crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(m.byteLength <= 0xffffffff, 'm.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_decrypt(m, c, ad, npub, k)

  if (res < 0) throw new Error('could not verify data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_encrypt_detached = function (
  c,
  mac,
  m,
  ad,
  nsec,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_encrypt_detached(c, mac, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_decrypt_detached = function (
  m,
  nsec,
  c,
  mac,
  ad,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_decrypt_detached(m, c, mac, ad, npub, k)

  if (res !== 0) throw new Error('could not verify data')
}

// crypto_stream

exports.crypto_stream_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  binding.crypto_stream_xor_wrap_init(state, n, k)
}

exports.crypto_stream_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_xor_wrap_update(state, c, m)
}

exports.crypto_stream_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_xor_wrap_final(state)
}

exports.crypto_stream_chacha20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  binding.crypto_stream_chacha20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_chacha20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_chacha20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_chacha20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_chacha20_xor_wrap_final(state)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  binding.crypto_stream_chacha20_ietf_xor_wrap_init(state, n, k)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_chacha20_ietf_xor_wrap_update(state, c, m)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_chacha20_ietf_xor_wrap_final(state)
}

exports.crypto_stream_xchacha20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  binding.crypto_stream_xchacha20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_xchacha20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_xchacha20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_xchacha20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_xchacha20_xor_wrap_final(state)
}

exports.crypto_stream_salsa20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  binding.crypto_stream_salsa20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_salsa20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_salsa20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_salsa20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_salsa20_xor_wrap_final(state)
}

// experimental

exports.extension_tweak_ed25519_base = function (n, p, ns) {
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.extension_tweak_ed25519_BYTES,
    "p must be 'extension_tweak_ed25519_BYTES' bytes"
  )

  binding.extension_tweak_ed25519_base(n, p, ns)
}

exports.extension_tweak_ed25519_sign_detached = function (sig, m, scalar, pk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(sig.byteLength === binding.crypto_sign_BYTES, "sig must be 'crypto_sign_BYTES' bytes")
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  if (pk) {
    assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
    assert(
      pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
      "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
    )
  }

  const res = binding.extension_tweak_ed25519_sign_detached(sig, m, scalar, pk)

  if (res !== 0) throw new Error('failed to compute signature')
}

exports.extension_tweak_ed25519_sk_to_scalar = function (n, sk) {
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  binding.extension_tweak_ed25519_sk_to_scalar(n, sk)
}

exports.extension_tweak_ed25519_scalar = function (scalarOut, scalar, ns) {
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_scalar(scalarOut, scalar, ns)
}

exports.extension_tweak_ed25519_pk = function (tpk, pk, ns) {
  assert(ArrayBuffer.isView(tpk), 'tpk must be a typed array')
  assert(
    tpk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "tpk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_pk(tpk, pk, ns)

  if (res !== 0) throw new Error('failed to tweak public key')
}

exports.extension_tweak_ed25519_keypair = function (pk, scalarOut, scalarIn, ns) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.extension_tweak_ed25519_BYTES,
    "pk must be 'extension_tweak_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarIn), 'scalarIn must be a typed array')
  assert(
    scalarIn.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarIn must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_keypair(pk, scalarOut, scalarIn, ns)
}

exports.extension_tweak_ed25519_scalar_add = function (scalarOut, scalar, n) {
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_scalar_add(scalarOut, scalar, n)
}

exports.extension_tweak_ed25519_pk_add = function (tpk, pk, p) {
  assert(ArrayBuffer.isView(tpk), 'tpk must be a typed array')
  assert(
    tpk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "tpk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "p must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_pk_add(tpk, pk, p)

  if (res !== 0) throw new Error('failed to add tweak to public key')
}

exports.extension_tweak_ed25519_keypair_add = function (pk, scalarOut, scalarIn, tweak) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.extension_tweak_ed25519_BYTES,
    "pk must be 'extension_tweak_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarIn), 'scalarIn must be a typed array')
  assert(
    scalarIn.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarIn must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(tweak), 'tweak must be a typed array')
  assert(
    tweak.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "tweak must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_keypair_add(pk, scalarOut, scalarIn, tweak)

  if (res !== 0) throw new Error('failed to add tweak to keypair')
}

exports.extension_pbkdf2_sha512_async = function (out, passwd, salt, iter, outlen, callback) {
  assert(
    iter >= binding.extension_pbkdf2_sha512_ITERATIONS_MIN,
    "iter must be at least 'extension_pbkdf2_sha512_ITERATIONS_MIN'"
  )
  assert(
    outlen <= binding.extension_pbkdf2_sha512_BYTES_MAX,
    "outlen must be at most 'extension_pbkdf2_sha512_BYTES_MAX'"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(out.byteLength >= outlen, "out must be at least 'outlen' bytes")
  assert(out.byteLength > 0, 'out must not be empty')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(salt.byteLength > 0, 'salt must not be empty')

  const [done, promise] = checkStatus(callback)

  binding.extension_pbkdf2_sha512_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    iter,
    outlen,

    done
  )

  return promise
}

exports.extension_pbkdf2_sha512 = function (out, passwd, salt, iter, outlen) {
  assert(
    iter >= binding.extension_pbkdf2_sha512_ITERATIONS_MIN,
    "iter must be at least 'extension_pbkdf2_sha512_ITERATIONS_MIN'"
  )
  assert(
    outlen <= binding.extension_pbkdf2_sha512_BYTES_MAX,
    "outlen must be at most 'extension_pbkdf2_sha512_BYTES_MAX'"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(out.byteLength >= outlen, "out must be at least 'outlen' bytes")
  assert(out.byteLength > 0, 'out must not be empty')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(salt.byteLength > 0, 'salt must not be empty')

  const res = binding.extension_pbkdf2_sha512(out, passwd, salt, iter, outlen)

  if (res !== 0) throw new Error('failed to add tweak to public key')
}

function checkStatus(callback, booleanResult = false) {
  let done, promise

  if (typeof callback === 'function') {
    done = function (status) {
      if (booleanResult) callback(null, status === 0)
      else if (status === 0) callback(null)
      else callback(new Error('status: ' + status))
    }
  } else {
    promise = new Promise(function (resolve, reject) {
      done = function (status) {
        if (booleanResult) resolve(status === 0)
        else if (status === 0) resolve()
        else reject(new Error('status: ' + status))
      }
    })
  }

  return [done, promise]
}
{
  "name": "sodium-native",
  "version": "5.1.0",
  "description": "Low level bindings for libsodium",
  "main": "index.js",
  "files": [
    "index.js",
    "binding.cc",
    "binding.js",
    "extensions",
    "prebuilds",
    "CMakeLists.txt"
  ],
  "imports": {
    "assert": {
      "bare": "bare-assert",
      "node": "assert"
    }
  },
  "addon": true,
  "dependencies": {
    "bare-assert": "^1.2.0",
    "require-addon": "^1.1.0",
    "which-runtime": "^1.2.1"
  },
  "devDependencies": {
    "bare-compat-napi": "^1.3.5",
    "brittle": "^3.16.2",
    "cmake-bare": "^1.6.1",
    "cmake-fetch": "^1.4.3",
    "cmake-napi": "^1.2.1",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "test": "prettier . --check && npm run test:node && npm run test:bare",
    "test:node": "node test/all.js",
    "test:bare": "bare test/all.js"
  },
  "standard": {
    "ignore": [
      "/test/fixtures/*.js"
    ]
  },
  "engines": {
    "bare": ">=1.16.0"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sodium-native.git"
  },
  "contributors": [
    "Emil Bay <github@tixz.dk> (http://bayes.dk)",
    "Mathias Buus <mathiasbuus@gmail.com> (https://mafinto.sh)",
    "Christophe Diederichs <chm-diederichs@hyperdivision.dk>"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/sodium-native/issues"
  },
  "homepage": "https://github.com/holepunchto/sodium-native"
}
const sodium = require('sodium-universal')
const b4a = require('b4a')

const ABYTES = sodium.crypto_secretstream_xchacha20poly1305_ABYTES
const TAG_MESSAGE = sodium.crypto_secretstream_xchacha20poly1305_TAG_MESSAGE
const TAG_FINAL = sodium.crypto_secretstream_xchacha20poly1305_TAG_FINAL
const STATEBYTES = sodium.crypto_secretstream_xchacha20poly1305_STATEBYTES
const HEADERBYTES = sodium.crypto_secretstream_xchacha20poly1305_HEADERBYTES
const KEYBYTES = sodium.crypto_secretstream_xchacha20poly1305_KEYBYTES
const TAG_FINAL_BYTE = b4a.isBuffer(TAG_FINAL) ? TAG_FINAL[0] : TAG_FINAL

const EMPTY = b4a.alloc(0)
const TAG = b4a.alloc(1)

class Push {
  constructor (key, state = b4a.allocUnsafeSlow(STATEBYTES), header = b4a.allocUnsafeSlow(HEADERBYTES)) {
    if (!TAG_FINAL) throw new Error('JavaScript sodium version needs to support crypto_secretstream_xchacha20poly')

    this.key = key
    this.state = state
    this.header = header

    sodium.crypto_secretstream_xchacha20poly1305_init_push(this.state, this.header, this.key)
  }

  next (message, cipher = b4a.allocUnsafe(message.byteLength + ABYTES)) {
    sodium.crypto_secretstream_xchacha20poly1305_push(this.state, cipher, message, null, TAG_MESSAGE)
    return cipher
  }

  final (message = EMPTY, cipher = b4a.allocUnsafe(ABYTES)) {
    sodium.crypto_secretstream_xchacha20poly1305_push(this.state, cipher, message, null, TAG_FINAL)
    return cipher
  }
}

class Pull {
  constructor (key, state = b4a.allocUnsafeSlow(STATEBYTES)) {
    if (!TAG_FINAL) throw new Error('JavaScript sodium version needs to support crypto_secretstream_xchacha20poly')

    this.key = key
    this.state = state
    this.final = false
  }

  init (header) {
    sodium.crypto_secretstream_xchacha20poly1305_init_pull(this.state, header, this.key)
  }

  next (cipher, message = b4a.allocUnsafe(cipher.byteLength - ABYTES)) {
    sodium.crypto_secretstream_xchacha20poly1305_pull(this.state, message, TAG, cipher, null)
    this.final = TAG[0] === TAG_FINAL_BYTE
    return message
  }
}

function keygen (buf = b4a.alloc(KEYBYTES)) {
  sodium.crypto_secretstream_xchacha20poly1305_keygen(buf)
  return buf
}

module.exports = {
  keygen,
  KEYBYTES,
  ABYTES,
  STATEBYTES,
  HEADERBYTES,
  Push,
  Pull
}
{
  "name": "sodium-secretstream",
  "version": "1.2.0",
  "description": "Wraps libsodiums secretstream in a higher level abstraction",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.1.1",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "standard": "^17.0.0"
  },
  "scripts": {
    "test": "standard"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/sodium-secretstream.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/sodium-secretstream/issues"
  },
  "homepage": "https://github.com/mafintosh/sodium-secretstream"
}
module.exports = require('sodium-native')
{
  "name": "sodium-universal",
  "version": "5.0.1",
  "description": "Universal wrapper for sodium-javascript and sodium-native working in Node.js and the Browser",
  "main": "index.js",
  "dependencies": {
    "sodium-native": "^5.0.1"
  },
  "peerDependencies": {
    "sodium-javascript": "~0.8.0"
  },
  "peerDependenciesMeta": {
    "sodium-javascript": {
      "optional": true
    }
  },
  "scripts": {
    "prepublish": "./build-scripts/generate.js"
  },
  "browser": {
    "sodium-native": "sodium-javascript"
  },
  "browserify": {
    "transform": [
      "./build-scripts/transform.js"
    ]
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sodium-universal.git"
  },
  "keywords": [
    "libsodium",
    "sodium",
    "sodium-native",
    "sodium-javascript",
    "browserify"
  ],
  "contributors": [
    "Emil Bay <github@tixz.dk> (http://bayes.dk)",
    "Mathias Buus <mathiasbuus@gmail.com> (https://mafinto.sh)",
    "Christophe Diederichs <chm-diederichs@hyperdivision.dk>"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/sodium-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/sodium-universal#readme"
}
const { EventEmitter } = require('events-universal')
const FIFO = require('fast-fifo')
const TextDecoder = require('text-decoder')

const StreamError = require('./lib/errors.js')

// if we do a future major, expect queue microtask to be there always, for now a bit defensive
const qmt =
  typeof queueMicrotask === 'undefined' ? (fn) => global.process.nextTick(fn) : queueMicrotask

// 29 bits used total (4 from shared, 14 from read, and 11 from write)
const MAX = (1 << 29) - 1

// Shared state
const OPENING = 0b0001
const PREDESTROYING = 0b0010
const DESTROYING = 0b0100
const DESTROYED = 0b1000

const NOT_OPENING = MAX ^ OPENING
const NOT_PREDESTROYING = MAX ^ PREDESTROYING

// Read state (4 bit offset from shared state)
const READ_ACTIVE = 0b00000000000001 << 4
const READ_UPDATING = 0b00000000000010 << 4
const READ_PRIMARY = 0b00000000000100 << 4
const READ_QUEUED = 0b00000000001000 << 4
const READ_RESUMED = 0b00000000010000 << 4
const READ_PIPE_DRAINED = 0b00000000100000 << 4
const READ_ENDING = 0b00000001000000 << 4
const READ_EMIT_DATA = 0b00000010000000 << 4
const READ_EMIT_READABLE = 0b00000100000000 << 4
const READ_EMITTED_READABLE = 0b00001000000000 << 4
const READ_DONE = 0b00010000000000 << 4
const READ_NEXT_TICK = 0b00100000000000 << 4
const READ_NEEDS_PUSH = 0b01000000000000 << 4
const READ_READ_AHEAD = 0b10000000000000 << 4

// Combined read state
const READ_FLOWING = READ_RESUMED | READ_PIPE_DRAINED
const READ_ACTIVE_AND_NEEDS_PUSH = READ_ACTIVE | READ_NEEDS_PUSH
const READ_PRIMARY_AND_ACTIVE = READ_PRIMARY | READ_ACTIVE
const READ_EMIT_READABLE_AND_QUEUED = READ_EMIT_READABLE | READ_QUEUED
const READ_RESUMED_READ_AHEAD = READ_RESUMED | READ_READ_AHEAD

const READ_NOT_ACTIVE = MAX ^ READ_ACTIVE
const READ_NON_PRIMARY = MAX ^ READ_PRIMARY
const READ_NON_PRIMARY_AND_PUSHED = MAX ^ (READ_PRIMARY | READ_NEEDS_PUSH)
const READ_PUSHED = MAX ^ READ_NEEDS_PUSH
const READ_PAUSED = MAX ^ READ_RESUMED
const READ_NOT_QUEUED = MAX ^ (READ_QUEUED | READ_EMITTED_READABLE)
const READ_NOT_ENDING = MAX ^ READ_ENDING
const READ_PIPE_NOT_DRAINED = MAX ^ READ_FLOWING
const READ_NOT_NEXT_TICK = MAX ^ READ_NEXT_TICK
const READ_NOT_UPDATING = MAX ^ READ_UPDATING
const READ_NO_READ_AHEAD = MAX ^ READ_READ_AHEAD
const READ_PAUSED_NO_READ_AHEAD = MAX ^ READ_RESUMED_READ_AHEAD

// Write state (18 bit offset, 4 bit offset from shared state and 14 from read state)
const WRITE_ACTIVE = 0b00000000001 << 18
const WRITE_UPDATING = 0b00000000010 << 18
const WRITE_PRIMARY = 0b00000000100 << 18
const WRITE_QUEUED = 0b00000001000 << 18
const WRITE_UNDRAINED = 0b00000010000 << 18
const WRITE_DONE = 0b00000100000 << 18
const WRITE_EMIT_DRAIN = 0b00001000000 << 18
const WRITE_NEXT_TICK = 0b00010000000 << 18
const WRITE_WRITING = 0b00100000000 << 18
const WRITE_FINISHING = 0b01000000000 << 18
const WRITE_CORKED = 0b10000000000 << 18

const WRITE_NOT_ACTIVE = MAX ^ (WRITE_ACTIVE | WRITE_WRITING)
const WRITE_NON_PRIMARY = MAX ^ WRITE_PRIMARY
const WRITE_NOT_FINISHING = MAX ^ (WRITE_ACTIVE | WRITE_FINISHING)
const WRITE_DRAINED = MAX ^ WRITE_UNDRAINED
const WRITE_NOT_QUEUED = MAX ^ WRITE_QUEUED
const WRITE_NOT_NEXT_TICK = MAX ^ WRITE_NEXT_TICK
const WRITE_NOT_UPDATING = MAX ^ WRITE_UPDATING
const WRITE_NOT_CORKED = MAX ^ WRITE_CORKED

// Combined shared state
const ACTIVE = READ_ACTIVE | WRITE_ACTIVE
const NOT_ACTIVE = MAX ^ ACTIVE
const DONE = READ_DONE | WRITE_DONE
const DESTROY_STATUS = DESTROYING | DESTROYED | PREDESTROYING
const OPEN_STATUS = DESTROY_STATUS | OPENING
const AUTO_DESTROY = DESTROY_STATUS | DONE
const NON_PRIMARY = WRITE_NON_PRIMARY & READ_NON_PRIMARY
const ACTIVE_OR_TICKING = WRITE_NEXT_TICK | READ_NEXT_TICK
const TICKING = ACTIVE_OR_TICKING & NOT_ACTIVE
const IS_OPENING = OPEN_STATUS | TICKING

// Combined shared state and read state
const READ_PRIMARY_STATUS = OPEN_STATUS | READ_ENDING | READ_DONE
const READ_STATUS = OPEN_STATUS | READ_DONE | READ_QUEUED
const READ_ENDING_STATUS = OPEN_STATUS | READ_ENDING | READ_QUEUED
const READ_READABLE_STATUS = OPEN_STATUS | READ_EMIT_READABLE | READ_QUEUED | READ_EMITTED_READABLE
const SHOULD_NOT_READ =
  OPEN_STATUS | READ_ACTIVE | READ_ENDING | READ_DONE | READ_NEEDS_PUSH | READ_READ_AHEAD
const READ_BACKPRESSURE_STATUS = DESTROY_STATUS | READ_ENDING | READ_DONE
const READ_UPDATE_SYNC_STATUS = READ_UPDATING | OPEN_STATUS | READ_NEXT_TICK | READ_PRIMARY
const READ_NEXT_TICK_OR_OPENING = READ_NEXT_TICK | OPENING

// Combined write state
const WRITE_PRIMARY_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_DONE
const WRITE_QUEUED_AND_UNDRAINED = WRITE_QUEUED | WRITE_UNDRAINED
const WRITE_QUEUED_AND_ACTIVE = WRITE_QUEUED | WRITE_ACTIVE
const WRITE_DRAIN_STATUS = WRITE_QUEUED | WRITE_UNDRAINED | OPEN_STATUS | WRITE_ACTIVE
const WRITE_STATUS = OPEN_STATUS | WRITE_ACTIVE | WRITE_QUEUED | WRITE_CORKED
const WRITE_PRIMARY_AND_ACTIVE = WRITE_PRIMARY | WRITE_ACTIVE
const WRITE_ACTIVE_AND_WRITING = WRITE_ACTIVE | WRITE_WRITING
const WRITE_FINISHING_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_QUEUED_AND_ACTIVE | WRITE_DONE
const WRITE_BACKPRESSURE_STATUS = WRITE_UNDRAINED | DESTROY_STATUS | WRITE_FINISHING | WRITE_DONE
const WRITE_UPDATE_SYNC_STATUS = WRITE_UPDATING | OPEN_STATUS | WRITE_NEXT_TICK | WRITE_PRIMARY
const WRITE_DROP_DATA = WRITE_FINISHING | WRITE_DONE | DESTROY_STATUS

const asyncIterator = Symbol.asyncIterator || Symbol('asyncIterator')

class WritableState {
  constructor(
    stream,
    { highWaterMark = 16384, map = null, mapWritable, byteLength, byteLengthWritable } = {}
  ) {
    this.stream = stream
    this.queue = new FIFO()
    this.highWaterMark = highWaterMark
    this.buffered = 0
    this.error = null
    this.pipeline = null
    this.drains = null // if we add more seldomly used helpers we might them into a subobject so its a single ptr
    this.byteLength = byteLengthWritable || byteLength || defaultByteLength
    this.map = mapWritable || map
    this.afterWrite = afterWrite.bind(this)
    this.afterUpdateNextTick = updateWriteNT.bind(this)
  }

  get ending() {
    return (this.stream._duplexState & WRITE_FINISHING) !== 0
  }

  get ended() {
    return (this.stream._duplexState & WRITE_DONE) !== 0
  }

  push(data) {
    if ((this.stream._duplexState & WRITE_DROP_DATA) !== 0) return false
    if (this.map !== null) data = this.map(data)

    this.buffered += this.byteLength(data)
    this.queue.push(data)

    if (this.buffered < this.highWaterMark) {
      this.stream._duplexState |= WRITE_QUEUED
      return true
    }

    this.stream._duplexState |= WRITE_QUEUED_AND_UNDRAINED
    return false
  }

  shift() {
    const data = this.queue.shift()

    this.buffered -= this.byteLength(data)
    if (this.buffered === 0) this.stream._duplexState &= WRITE_NOT_QUEUED

    return data
  }

  end(data) {
    if (typeof data === 'function') {
      this.stream.once('finish', data)
    } else if (data !== undefined && data !== null) {
      this.push(data)
    }

    this.stream._duplexState = (this.stream._duplexState | WRITE_FINISHING) & WRITE_NON_PRIMARY
  }

  autoBatch(data, cb) {
    const buffer = []
    const stream = this.stream

    buffer.push(data)
    while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED_AND_ACTIVE) {
      buffer.push(stream._writableState.shift())
    }

    if ((stream._duplexState & OPEN_STATUS) !== 0) return cb(null)
    stream._writev(buffer, cb)
  }

  update() {
    const stream = this.stream

    stream._duplexState |= WRITE_UPDATING

    do {
      while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED) {
        const data = this.shift()
        stream._duplexState |= WRITE_ACTIVE_AND_WRITING
        stream._write(data, this.afterWrite)
      }

      if ((stream._duplexState & WRITE_PRIMARY_AND_ACTIVE) === 0) this.updateNonPrimary()
    } while (this.continueUpdate() === true)

    stream._duplexState &= WRITE_NOT_UPDATING
  }

  updateNonPrimary() {
    const stream = this.stream

    if ((stream._duplexState & WRITE_FINISHING_STATUS) === WRITE_FINISHING) {
      stream._duplexState = stream._duplexState | WRITE_ACTIVE
      stream._final(afterFinal.bind(this))
      return
    }

    if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
      if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
        stream._duplexState |= ACTIVE
        stream._destroy(afterDestroy.bind(this))
      }
      return
    }

    if ((stream._duplexState & IS_OPENING) === OPENING) {
      stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING
      stream._open(afterOpen.bind(this))
    }
  }

  continueUpdate() {
    if ((this.stream._duplexState & WRITE_NEXT_TICK) === 0) return false
    this.stream._duplexState &= WRITE_NOT_NEXT_TICK
    return true
  }

  updateCallback() {
    if ((this.stream._duplexState & WRITE_UPDATE_SYNC_STATUS) === WRITE_PRIMARY) {
      this.update()
    } else {
      this.updateNextTick()
    }
  }

  updateNextTick() {
    if ((this.stream._duplexState & WRITE_NEXT_TICK) !== 0) return
    this.stream._duplexState |= WRITE_NEXT_TICK
    if ((this.stream._duplexState & WRITE_UPDATING) === 0) qmt(this.afterUpdateNextTick)
  }
}

class ReadableState {
  constructor(
    stream,
    { highWaterMark = 16384, map = null, mapReadable, byteLength, byteLengthReadable } = {}
  ) {
    this.stream = stream
    this.queue = new FIFO()
    this.highWaterMark = highWaterMark === 0 ? 1 : highWaterMark
    this.buffered = 0
    this.readAhead = highWaterMark > 0
    this.error = null
    this.pipeline = null
    this.byteLength = byteLengthReadable || byteLength || defaultByteLength
    this.map = mapReadable || map
    this.pipeTo = null
    this.afterRead = afterRead.bind(this)
    this.afterUpdateNextTick = updateReadNT.bind(this)
  }

  get ending() {
    return (this.stream._duplexState & READ_ENDING) !== 0
  }

  get ended() {
    return (this.stream._duplexState & READ_DONE) !== 0
  }

  pipe(pipeTo, cb) {
    if (this.pipeTo !== null) throw StreamError.BAD_ARGUMENT('Can only pipe to one destination')
    if (typeof cb !== 'function') cb = null

    this.stream._duplexState |= READ_PIPE_DRAINED
    this.pipeTo = pipeTo
    this.pipeline = new Pipeline(this.stream, pipeTo, cb)

    if (cb) this.stream.on('error', noop) // We already error handle this so supress crashes

    if (isStreamx(pipeTo)) {
      pipeTo._writableState.pipeline = this.pipeline
      if (cb) pipeTo.on('error', noop) // We already error handle this so supress crashes
      pipeTo.on('finish', this.pipeline.finished.bind(this.pipeline)) // TODO: just call finished from pipeTo itself
    } else {
      const onerror = this.pipeline.done.bind(this.pipeline, pipeTo)
      const onclose = this.pipeline.done.bind(this.pipeline, pipeTo, null) // onclose has a weird bool arg
      pipeTo.on('error', onerror)
      pipeTo.on('close', onclose)
      pipeTo.on('finish', this.pipeline.finished.bind(this.pipeline))
    }

    pipeTo.on('drain', afterDrain.bind(this))
    this.stream.emit('piping', pipeTo)
    pipeTo.emit('pipe', this.stream)
  }

  push(data) {
    const stream = this.stream

    if (data === null) {
      this.highWaterMark = 0
      stream._duplexState = (stream._duplexState | READ_ENDING) & READ_NON_PRIMARY_AND_PUSHED
      return false
    }

    if (this.map !== null) {
      data = this.map(data)
      if (data === null) {
        stream._duplexState &= READ_PUSHED
        return this.buffered < this.highWaterMark
      }
    }

    this.buffered += this.byteLength(data)
    this.queue.push(data)

    stream._duplexState = (stream._duplexState | READ_QUEUED) & READ_PUSHED

    return this.buffered < this.highWaterMark
  }

  shift() {
    const data = this.queue.shift()

    this.buffered -= this.byteLength(data)
    if (this.buffered === 0) {
      this.stream._duplexState &= READ_NOT_QUEUED
    }

    return data
  }

  unshift(data) {
    const pending = [this.map !== null ? this.map(data) : data]
    while (this.buffered > 0) pending.push(this.shift())

    for (let i = 0; i < pending.length - 1; i++) {
      const data = pending[i]
      this.buffered += this.byteLength(data)
      this.queue.push(data)
    }

    this.push(pending[pending.length - 1])
  }

  read() {
    const stream = this.stream

    if ((stream._duplexState & READ_STATUS) === READ_QUEUED) {
      const data = this.shift()

      if (this.pipeTo !== null && this.pipeTo.write(data) === false) {
        stream._duplexState &= READ_PIPE_NOT_DRAINED
      }

      if ((stream._duplexState & READ_EMIT_DATA) !== 0) {
        stream.emit('data', data)
      }

      return data
    }

    if (this.readAhead === false) {
      stream._duplexState |= READ_READ_AHEAD
      this.updateNextTick()
    }

    return null
  }

  drain() {
    const stream = this.stream

    while (
      (stream._duplexState & READ_STATUS) === READ_QUEUED &&
      (stream._duplexState & READ_FLOWING) !== 0
    ) {
      const data = this.shift()

      if (this.pipeTo !== null && this.pipeTo.write(data) === false) {
        stream._duplexState &= READ_PIPE_NOT_DRAINED
      }

      if ((stream._duplexState & READ_EMIT_DATA) !== 0) {
        stream.emit('data', data)
      }
    }
  }

  update() {
    const stream = this.stream

    stream._duplexState |= READ_UPDATING

    do {
      this.drain()

      while (
        this.buffered < this.highWaterMark &&
        (stream._duplexState & SHOULD_NOT_READ) === READ_READ_AHEAD
      ) {
        stream._duplexState |= READ_ACTIVE_AND_NEEDS_PUSH
        stream._read(this.afterRead)
        this.drain()
      }

      if ((stream._duplexState & READ_READABLE_STATUS) === READ_EMIT_READABLE_AND_QUEUED) {
        stream._duplexState |= READ_EMITTED_READABLE
        stream.emit('readable')
      }

      if ((stream._duplexState & READ_PRIMARY_AND_ACTIVE) === 0) {
        this.updateNonPrimary()
      }
    } while (this.continueUpdate() === true)

    stream._duplexState &= READ_NOT_UPDATING
  }

  updateNonPrimary() {
    const stream = this.stream

    if ((stream._duplexState & READ_ENDING_STATUS) === READ_ENDING) {
      stream._duplexState = (stream._duplexState | READ_DONE) & READ_NOT_ENDING
      stream.emit('end')

      if ((stream._duplexState & AUTO_DESTROY) === DONE) {
        stream._duplexState |= DESTROYING
      }

      if (this.pipeTo !== null) {
        this.pipeTo.end()
      }
    }

    if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
      if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
        stream._duplexState |= ACTIVE
        stream._destroy(afterDestroy.bind(this))
      }
      return
    }

    if ((stream._duplexState & IS_OPENING) === OPENING) {
      stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING
      stream._open(afterOpen.bind(this))
    }
  }

  continueUpdate() {
    if ((this.stream._duplexState & READ_NEXT_TICK) === 0) return false
    this.stream._duplexState &= READ_NOT_NEXT_TICK
    return true
  }

  updateCallback() {
    if ((this.stream._duplexState & READ_UPDATE_SYNC_STATUS) === READ_PRIMARY) {
      this.update()
    } else {
      this.updateNextTick()
    }
  }

  updateNextTickIfOpen() {
    if ((this.stream._duplexState & READ_NEXT_TICK_OR_OPENING) !== 0) return
    this.stream._duplexState |= READ_NEXT_TICK
    if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick)
  }

  updateNextTick() {
    if ((this.stream._duplexState & READ_NEXT_TICK) !== 0) return
    this.stream._duplexState |= READ_NEXT_TICK
    if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick)
  }
}

class TransformState {
  constructor(stream) {
    this.data = null
    this.afterTransform = afterTransform.bind(stream)
    this.afterFinal = null
  }
}

class Pipeline {
  constructor(src, dst, cb) {
    this.from = src
    this.to = dst
    this.afterPipe = cb
    this.error = null
    this.pipeToFinished = false
  }

  finished() {
    this.pipeToFinished = true
  }

  done(stream, err) {
    if (err) this.error = err

    if (stream === this.to) {
      this.to = null

      if (this.from !== null) {
        if ((this.from._duplexState & READ_DONE) === 0 || !this.pipeToFinished) {
          this.from.destroy(this.error || StreamError.PREMATURE_CLOSE('Writable stream closed'))
        }
        return
      }
    }

    if (stream === this.from) {
      this.from = null

      if (this.to !== null) {
        if ((stream._duplexState & READ_DONE) === 0) {
          this.to.destroy(this.error || StreamError.PREMATURE_CLOSE('Readable stream closed'))
        }
        return
      }
    }

    if (this.afterPipe !== null) this.afterPipe(this.error)
    this.to = this.from = this.afterPipe = null
  }
}

function afterDrain() {
  this.stream._duplexState |= READ_PIPE_DRAINED
  this.updateCallback()
}

function afterFinal(err) {
  const stream = this.stream
  if (err) stream.destroy(err)

  if ((stream._duplexState & DESTROY_STATUS) === 0) {
    stream._duplexState |= WRITE_DONE
    stream.emit('finish')
  }

  if ((stream._duplexState & AUTO_DESTROY) === DONE) {
    stream._duplexState |= DESTROYING
  }

  stream._duplexState &= WRITE_NOT_FINISHING

  // no need to wait the extra tick here, so we short circuit that
  if ((stream._duplexState & WRITE_UPDATING) === 0) {
    this.update()
  } else {
    this.updateNextTick()
  }
}

function afterDestroy(err) {
  const stream = this.stream

  if (!err && !StreamError.isStreamDestroyed(this.error)) err = this.error
  if (err) stream.emit('error', err)

  stream._duplexState |= DESTROYED
  stream.emit('close')

  const rs = stream._readableState
  const ws = stream._writableState

  if (rs !== null && rs.pipeline !== null) {
    rs.pipeline.done(stream, err)
  }

  if (ws !== null) {
    while (ws.drains !== null && ws.drains.length > 0) {
      ws.drains.shift().resolve(false)
    }

    if (ws.pipeline !== null) {
      ws.pipeline.done(stream, err)
    }
  }
}

function afterWrite(err) {
  const stream = this.stream

  if (err) stream.destroy(err)
  stream._duplexState &= WRITE_NOT_ACTIVE

  if (this.drains !== null) tickDrains(this.drains)

  if ((stream._duplexState & WRITE_DRAIN_STATUS) === WRITE_UNDRAINED) {
    stream._duplexState &= WRITE_DRAINED

    if ((stream._duplexState & WRITE_EMIT_DRAIN) === WRITE_EMIT_DRAIN) {
      stream.emit('drain')
    }
  }

  this.updateCallback()
}

function afterRead(err) {
  if (err) this.stream.destroy(err)
  this.stream._duplexState &= READ_NOT_ACTIVE

  if (this.readAhead === false && (this.stream._duplexState & READ_RESUMED) === 0) {
    this.stream._duplexState &= READ_NO_READ_AHEAD
  }

  this.updateCallback()
}

function updateReadNT() {
  if ((this.stream._duplexState & READ_UPDATING) === 0) {
    this.stream._duplexState &= READ_NOT_NEXT_TICK
    this.update()
  }
}

function updateWriteNT() {
  if ((this.stream._duplexState & WRITE_UPDATING) === 0) {
    this.stream._duplexState &= WRITE_NOT_NEXT_TICK
    this.update()
  }
}

function tickDrains(drains) {
  for (let i = 0; i < drains.length; i++) {
    // drains.writes are monotonic, so if one is 0 its always the first one
    if (--drains[i].writes === 0) {
      drains.shift().resolve(true)
      i--
    }
  }
}

function afterOpen(err) {
  const stream = this.stream

  if (err) stream.destroy(err)

  if ((stream._duplexState & DESTROYING) === 0) {
    if ((stream._duplexState & READ_PRIMARY_STATUS) === 0) {
      stream._duplexState |= READ_PRIMARY
    }

    if ((stream._duplexState & WRITE_PRIMARY_STATUS) === 0) {
      stream._duplexState |= WRITE_PRIMARY
    }

    stream.emit('open')
  }

  stream._duplexState &= NOT_ACTIVE

  if (stream._writableState !== null) {
    stream._writableState.updateCallback()
  }

  if (stream._readableState !== null) {
    stream._readableState.updateCallback()
  }
}

function afterTransform(err, data) {
  if (data !== undefined && data !== null) this.push(data)
  this._writableState.afterWrite(err)
}

function newListener(name) {
  if (this._readableState !== null) {
    if (name === 'data') {
      this._duplexState |= READ_EMIT_DATA | READ_RESUMED_READ_AHEAD
      this._readableState.updateNextTick()
    }
    if (name === 'readable') {
      this._duplexState |= READ_EMIT_READABLE
      this._readableState.updateNextTick()
    }
  }

  if (this._writableState !== null) {
    if (name === 'drain') {
      this._duplexState |= WRITE_EMIT_DRAIN
      this._writableState.updateNextTick()
    }
  }
}

class Stream extends EventEmitter {
  constructor(opts) {
    super()

    this._duplexState = 0
    this._readableState = null
    this._writableState = null

    if (opts) {
      if (opts.open) this._open = opts.open
      if (opts.destroy) this._destroy = opts.destroy
      if (opts.predestroy) this._predestroy = opts.predestroy
      if (opts.signal) opts.signal.addEventListener('abort', abort.bind(this))
    }

    this.on('newListener', newListener)
  }

  _open(cb) {
    cb(null)
  }

  _destroy(cb) {
    cb(null)
  }

  _predestroy() {
    // does nothing
  }

  get readable() {
    return this._readableState !== null ? true : undefined
  }

  get writable() {
    return this._writableState !== null ? true : undefined
  }

  get destroyed() {
    return (this._duplexState & DESTROYED) !== 0
  }

  get destroying() {
    return (this._duplexState & DESTROY_STATUS) !== 0
  }

  destroy(err) {
    if ((this._duplexState & DESTROY_STATUS) === 0) {
      if (!err) err = StreamError.STREAM_DESTROYED()
      this._duplexState = (this._duplexState | DESTROYING) & NON_PRIMARY

      if (this._readableState !== null) {
        this._readableState.highWaterMark = 0
        this._readableState.error = err
      }

      if (this._writableState !== null) {
        this._writableState.highWaterMark = 0
        this._writableState.error = err
      }

      this._duplexState |= PREDESTROYING
      this._predestroy()
      this._duplexState &= NOT_PREDESTROYING

      if (this._readableState !== null) {
        this._readableState.updateNextTick()
      }

      if (this._writableState !== null) {
        this._writableState.updateNextTick()
      }
    }
  }
}

class Readable extends Stream {
  constructor(opts) {
    super(opts)

    this._duplexState |= OPENING | WRITE_DONE | READ_READ_AHEAD
    this._readableState = new ReadableState(this, opts)

    if (opts) {
      if (this._readableState.readAhead === false) this._duplexState &= READ_NO_READ_AHEAD
      if (opts.read) this._read = opts.read
      if (opts.eagerOpen) this._readableState.updateNextTick()
      if (opts.encoding) this.setEncoding(opts.encoding)
    }
  }

  static deferred(fn, opts) {
    const out = new PassThrough(opts)

    fn()
      .then((src) => {
        if (src === null) return out.end()
        if (out.destroying) return
        pipeline(src, out, noop)
      })
      .catch((err) => out.destroy(err))

    return out
  }

  setEncoding(encoding) {
    const dec = new TextDecoder(encoding)
    const map = this._readableState.map || echo
    this._readableState.map = mapOrSkip
    return this

    function mapOrSkip(data) {
      const next = dec.push(data)
      return next === '' && (data.byteLength !== 0 || dec.remaining > 0) ? null : map(next)
    }
  }

  _read(cb) {
    cb(null)
  }

  pipe(dest, cb) {
    this._readableState.updateNextTick()
    this._readableState.pipe(dest, cb)
    return dest
  }

  read() {
    this._readableState.updateNextTick()
    return this._readableState.read()
  }

  push(data) {
    this._readableState.updateNextTickIfOpen()
    return this._readableState.push(data)
  }

  unshift(data) {
    this._readableState.updateNextTickIfOpen()
    return this._readableState.unshift(data)
  }

  resume() {
    this._duplexState |= READ_RESUMED_READ_AHEAD
    this._readableState.updateNextTick()
    return this
  }

  pause() {
    this._duplexState &=
      this._readableState.readAhead === false ? READ_PAUSED_NO_READ_AHEAD : READ_PAUSED
    return this
  }

  static _fromAsyncIterator(ite, opts) {
    let destroy

    const rs = new Readable({
      ...opts,
      read(cb) {
        ite.next().then(push).then(cb.bind(null, null)).catch(cb)
      },
      predestroy() {
        destroy = ite.return()
      },
      destroy(cb) {
        if (!destroy) return cb(null)
        destroy.then(cb.bind(null, null)).catch(cb)
      }
    })

    return rs

    function push(data) {
      if (data.done) rs.push(null)
      else rs.push(data.value)
    }
  }

  static from(data, opts) {
    if (isReadStreamx(data)) return data
    if (data[asyncIterator]) return this._fromAsyncIterator(data[asyncIterator](), opts)
    if (!Array.isArray(data)) data = data === undefined ? [] : [data]

    let i = 0
    return new Readable({
      ...opts,
      read(cb) {
        this.push(i === data.length ? null : data[i++])
        cb(null)
      }
    })
  }

  static isBackpressured(rs) {
    return (
      (rs._duplexState & READ_BACKPRESSURE_STATUS) !== 0 ||
      rs._readableState.buffered >= rs._readableState.highWaterMark
    )
  }

  static isPaused(rs) {
    return (rs._duplexState & READ_RESUMED) === 0
  }

  [asyncIterator]() {
    const stream = this

    let error = null
    let promiseResolve = null
    let promiseReject = null

    this.on('error', (err) => {
      error = err
    })
    this.on('readable', onreadable)
    this.on('close', onclose)

    return {
      [asyncIterator]() {
        return this
      },
      next() {
        return new Promise(function (resolve, reject) {
          promiseResolve = resolve
          promiseReject = reject
          const data = stream.read()
          if (data !== null) ondata(data)
          else if ((stream._duplexState & DESTROYED) !== 0) ondata(null)
        })
      },
      return() {
        return destroy(null)
      },
      throw(err) {
        return destroy(err)
      }
    }

    function onreadable() {
      if (promiseResolve !== null) ondata(stream.read())
    }

    function onclose() {
      if (promiseResolve !== null) ondata(null)
    }

    function ondata(data) {
      if (promiseReject === null) return
      if (error) {
        promiseReject(error)
      } else if (data === null && (stream._duplexState & READ_DONE) === 0) {
        promiseReject(StreamError.STREAM_DESTROYED())
      } else {
        promiseResolve({ value: data, done: data === null })
      }
      promiseReject = promiseResolve = null
    }

    function destroy(err) {
      stream.destroy(err)
      return new Promise((resolve, reject) => {
        if (stream._duplexState & DESTROYED) return resolve({ value: undefined, done: true })
        stream.once('close', function () {
          if (err) reject(err)
          else resolve({ value: undefined, done: true })
        })
      })
    }
  }
}

class Writable extends Stream {
  constructor(opts) {
    super(opts)

    this._duplexState |= OPENING | READ_DONE
    this._writableState = new WritableState(this, opts)

    if (opts) {
      if (opts.writev) this._writev = opts.writev
      if (opts.write) this._write = opts.write
      if (opts.final) this._final = opts.final
      if (opts.eagerOpen) this._writableState.updateNextTick()
    }
  }

  cork() {
    this._duplexState |= WRITE_CORKED
  }

  uncork() {
    this._duplexState &= WRITE_NOT_CORKED
    this._writableState.updateNextTick()
  }

  _writev(batch, cb) {
    cb(null)
  }

  _write(data, cb) {
    this._writableState.autoBatch(data, cb)
  }

  _final(cb) {
    cb(null)
  }

  static isBackpressured(ws) {
    return (ws._duplexState & WRITE_BACKPRESSURE_STATUS) !== 0
  }

  static drained(ws) {
    if (ws.destroyed) return Promise.resolve(false)

    const state = ws._writableState
    const pending = isWritev(ws) ? Math.min(1, state.queue.length) : state.queue.length
    const writes = pending + (ws._duplexState & WRITE_WRITING ? 1 : 0)
    if (writes === 0) return Promise.resolve(true)

    if (state.drains === null) state.drains = []
    return new Promise((resolve) => {
      state.drains.push({ writes, resolve })
    })
  }

  write(data) {
    this._writableState.updateNextTick()
    return this._writableState.push(data)
  }

  end(data) {
    this._writableState.updateNextTick()
    this._writableState.end(data)
    return this
  }
}

class Duplex extends Readable {
  // and Writable
  constructor(opts) {
    super(opts)

    this._duplexState = OPENING | (this._duplexState & READ_READ_AHEAD)
    this._writableState = new WritableState(this, opts)

    if (opts) {
      if (opts.writev) this._writev = opts.writev
      if (opts.write) this._write = opts.write
      if (opts.final) this._final = opts.final
    }
  }

  cork() {
    this._duplexState |= WRITE_CORKED
  }

  uncork() {
    this._duplexState &= WRITE_NOT_CORKED
    this._writableState.updateNextTick()
  }

  _writev(batch, cb) {
    cb(null)
  }

  _write(data, cb) {
    this._writableState.autoBatch(data, cb)
  }

  _final(cb) {
    cb(null)
  }

  write(data) {
    this._writableState.updateNextTick()
    return this._writableState.push(data)
  }

  end(data) {
    this._writableState.updateNextTick()
    this._writableState.end(data)
    return this
  }
}

class Transform extends Duplex {
  constructor(opts) {
    super(opts)
    this._transformState = new TransformState(this)

    if (opts) {
      if (opts.transform) this._transform = opts.transform
      if (opts.flush) this._flush = opts.flush
    }
  }

  _write(data, cb) {
    if (this._readableState.buffered >= this._readableState.highWaterMark) {
      this._transformState.data = data
    } else {
      this._transform(data, this._transformState.afterTransform)
    }
  }

  _read(cb) {
    if (this._transformState.data !== null) {
      const data = this._transformState.data
      this._transformState.data = null
      cb(null)
      this._transform(data, this._transformState.afterTransform)
    } else {
      cb(null)
    }
  }

  destroy(err) {
    super.destroy(err)
    if (this._transformState.data !== null) {
      this._transformState.data = null
      this._transformState.afterTransform()
    }
  }

  _transform(data, cb) {
    cb(null, data)
  }

  _flush(cb) {
    cb(null)
  }

  _final(cb) {
    this._transformState.afterFinal = cb
    this._flush(transformAfterFlush.bind(this))
  }
}

class PassThrough extends Transform {}

function transformAfterFlush(err, data) {
  const cb = this._transformState.afterFinal
  if (err) return cb(err)

  if (data !== null && data !== undefined) this.push(data)
  this.push(null)
  cb(null)
}

function pipelinePromise(...streams) {
  return new Promise((resolve, reject) => {
    return pipeline(...streams, (err) => {
      if (err) return reject(err)
      resolve()
    })
  })
}

function pipeline(stream, ...streams) {
  const all = Array.isArray(stream) ? [...stream, ...streams] : [stream, ...streams]
  const done = all.length && typeof all[all.length - 1] === 'function' ? all.pop() : null

  if (all.length < 2) throw StreamError.BAD_ARGUMENT('Pipeline requires at least 2 streams')

  let src = all[0]
  let dest = null
  let error = null

  for (let i = 1; i < all.length; i++) {
    dest = all[i]

    if (isStreamx(src)) {
      src.pipe(dest, onerror)
    } else {
      errorHandle(src, true, i > 1, onerror)
      src.pipe(dest)
    }

    src = dest
  }

  if (done) {
    let fin = false

    const autoDestroy =
      isStreamx(dest) || !!(dest._writableState && dest._writableState.autoDestroy)

    dest.on('error', (err) => {
      if (error === null) error = err
    })

    dest.on('finish', () => {
      fin = true
      if (!autoDestroy) done(error)
    })

    if (autoDestroy) {
      dest.on('close', () => done(error || (fin ? null : StreamError.PREMATURE_CLOSE())))
    }
  }

  return dest

  function errorHandle(s, rd, wr, onerror) {
    s.on('error', onerror)
    s.on('close', onclose)

    function onclose() {
      if (rd && s._readableState && !s._readableState.ended) {
        return onerror(StreamError.PREMATURE_CLOSE())
      }
      if (wr && s._writableState && !s._writableState.ended) {
        return onerror(StreamError.PREMATURE_CLOSE())
      }
    }
  }

  function onerror(err) {
    if (!err || error) return
    error = err

    for (const s of all) {
      s.destroy(err)
    }
  }
}

function echo(s) {
  return s
}

function isStream(stream) {
  return !!stream._readableState || !!stream._writableState
}

function isStreamx(stream) {
  return typeof stream._duplexState === 'number' && isStream(stream)
}

function isEnding(stream) {
  return !!stream._readableState && stream._readableState.ending
}

function isEnded(stream) {
  return !!stream._readableState && stream._readableState.ended
}

function isFinishing(stream) {
  return !!stream._writableState && stream._writableState.ending
}

function isFinished(stream) {
  return !!stream._writableState && stream._writableState.ended
}

function getStreamError(stream, opts = {}) {
  const err =
    (stream._readableState && stream._readableState.error) ||
    (stream._writableState && stream._writableState.error)

  // avoid implicit errors by default
  return !opts.all && StreamError.isStreamDestroyed(err) ? null : err
}

function isReadStreamx(stream) {
  return isStreamx(stream) && stream.readable
}

function isDisturbed(stream) {
  return (
    (stream._duplexState & OPENING) !== OPENING ||
    (stream._duplexState & DESTROYING) === DESTROYING ||
    (stream._duplexState & ACTIVE_OR_TICKING) !== 0
  )
}

function isTypedArray(data) {
  return typeof data === 'object' && data !== null && typeof data.byteLength === 'number'
}

function defaultByteLength(data) {
  return isTypedArray(data) ? data.byteLength : 1024
}

function noop() {}

function abort() {
  this.destroy(StreamError.ABORTED())
}

function isWritev(s) {
  return s._writev !== Writable.prototype._writev && s._writev !== Duplex.prototype._writev
}

module.exports = {
  pipeline,
  pipelinePromise,
  isStream,
  isStreamx,
  isEnding,
  isEnded,
  isFinishing,
  isFinished,
  isDisturbed,
  getStreamError,
  Stream,
  Writable,
  Readable,
  Duplex,
  Transform,
  // Export PassThrough for compatibility with Node.js core's stream module
  PassThrough
}
module.exports = class StreamError extends Error {
  constructor(msg, code, fn = StreamError) {
    super(msg)

    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  static isStreamDestroyed(err) {
    return err && err.code === 'STREAM_DESTROYED'
  }

  static isPrematureClose(err) {
    return err && err.code === 'PREMATURE_CLOSE'
  }

  static isAborted(err) {
    return err && err.code === 'ABORTED'
  }

  static isBadArgument(err) {
    return err && err.code === 'BAD_ARGUMENT'
  }

  get name() {
    return 'StreamError'
  }

  static STREAM_DESTROYED() {
    return new StreamError('Stream was destroyed', 'STREAM_DESTROYED', StreamError.STREAM_DESTROYED)
  }

  static PREMATURE_CLOSE(msg = 'Premature close') {
    return new StreamError(msg, 'PREMATURE_CLOSE', StreamError.PREMATURE_CLOSE)
  }

  static ABORTED() {
    return new StreamError('Stream aborted', 'ABORTED', StreamError.ABORTED)
  }

  static BAD_ARGUMENT(msg = 'Bad argument') {
    return new StreamError(msg, 'BAD_ARGUMENT', StreamError.BAD_ARGUMENT)
  }
}
{
  "name": "streamx",
  "version": "2.28.0",
  "description": "An iteration of the Node.js core streams with a series of improvements",
  "main": "index.js",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./errors": {
      "types": "./lib/errors.d.ts",
      "default": "./lib/errors"
    }
  },
  "dependencies": {
    "events-universal": "^1.0.0",
    "fast-fifo": "^1.3.2",
    "text-decoder": "^1.1.0"
  },
  "devDependencies": {
    "b4a": "^1.6.6",
    "brittle": "^3.1.1",
    "end-of-stream": "^1.4.4",
    "lunte": "^1.8.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "runtime.d.ts",
    "lib"
  ],
  "scripts": {
    "format": "prettier . --write",
    "test": "brittle test/all.js && brittle-bare test/all.js",
    "lint": "prettier . --check && lunte"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/streamx.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/streamx/issues"
  },
  "homepage": "https://github.com/mafintosh/streamx"
}
const PassThroughDecoder = require('./lib/pass-through-decoder')
const UTF8Decoder = require('./lib/utf8-decoder')

module.exports = class TextDecoder {
  constructor(encoding = 'utf8') {
    this.encoding = normalizeEncoding(encoding)

    switch (this.encoding) {
      case 'utf8':
        this.decoder = new UTF8Decoder()
        break
      case 'utf16le':
      case 'base64':
        throw new Error('Unsupported encoding: ' + this.encoding)
      default:
        this.decoder = new PassThroughDecoder(this.encoding)
    }
  }

  get remaining() {
    return this.decoder.remaining
  }

  push(data) {
    if (typeof data === 'string') return data
    return this.decoder.decode(data)
  }

  // For Node.js compatibility
  write(data) {
    return this.push(data)
  }

  end(data) {
    let result = ''
    if (data) result = this.push(data)
    result += this.decoder.flush()
    return result
  }
}

function normalizeEncoding(encoding) {
  encoding = encoding.toLowerCase()

  switch (encoding) {
    case 'utf8':
    case 'utf-8':
      return 'utf8'
    case 'ucs2':
    case 'ucs-2':
    case 'utf16le':
    case 'utf-16le':
      return 'utf16le'
    case 'latin1':
    case 'binary':
      return 'latin1'
    case 'base64':
    case 'ascii':
    case 'hex':
      return encoding
    default:
      throw new Error('Unknown encoding: ' + encoding)
  }
}
const b4a = require('b4a')

module.exports = class PassThroughDecoder {
  constructor(encoding) {
    this.encoding = encoding
  }

  get remaining() {
    return 0
  }

  decode(data) {
    return b4a.toString(data, this.encoding)
  }

  flush() {
    return ''
  }
}
const b4a = require('b4a')

/**
 * https://encoding.spec.whatwg.org/#utf-8-decoder
 */
module.exports = class UTF8Decoder {
  constructor() {
    this._reset()
  }

  get remaining() {
    return this.bytesSeen
  }

  decode(data) {
    if (data.byteLength === 0) return ''

    if (this.bytesNeeded === 0 && trailingIncomplete(data, 0) === 0) {
      this.bytesSeen = trailingBytesSeen(data)
      return b4a.toString(data, 'utf8')
    }

    let result = ''
    let start = 0

    if (this.bytesNeeded > 0) {
      while (start < data.byteLength) {
        const byte = data[start]

        if (byte < this.lowerBoundary || byte > this.upperBoundary) {
          result += '\ufffd'
          this._reset()
          break
        }

        this.lowerBoundary = 0x80
        this.upperBoundary = 0xbf
        this.codePoint = (this.codePoint << 6) | (byte & 0x3f)
        this.bytesSeen++
        start++

        if (this.bytesSeen === this.bytesNeeded) {
          result += String.fromCodePoint(this.codePoint)
          this._reset()
          break
        }
      }

      if (this.bytesNeeded > 0) return result
    }

    const trailing = trailingIncomplete(data, start)
    const end = data.byteLength - trailing

    if (end > start) result += b4a.toString(data, 'utf8', start, end)

    for (let i = end; i < data.byteLength; i++) {
      const byte = data[i]

      if (this.bytesNeeded === 0) {
        if (byte <= 0x7f) {
          this.bytesSeen = 0
          result += String.fromCharCode(byte)
        } else if (byte >= 0xc2 && byte <= 0xdf) {
          this.bytesNeeded = 2
          this.bytesSeen = 1
          this.codePoint = byte & 0x1f
        } else if (byte >= 0xe0 && byte <= 0xef) {
          if (byte === 0xe0) this.lowerBoundary = 0xa0
          else if (byte === 0xed) this.upperBoundary = 0x9f
          this.bytesNeeded = 3
          this.bytesSeen = 1
          this.codePoint = byte & 0xf
        } else if (byte >= 0xf0 && byte <= 0xf4) {
          if (byte === 0xf0) this.lowerBoundary = 0x90
          else if (byte === 0xf4) this.upperBoundary = 0x8f
          this.bytesNeeded = 4
          this.bytesSeen = 1
          this.codePoint = byte & 0x7
        } else {
          this.bytesSeen = 1
          result += '\ufffd'
        }

        continue
      }

      if (byte < this.lowerBoundary || byte > this.upperBoundary) {
        result += '\ufffd'
        i--
        this._reset()

        continue
      }

      this.lowerBoundary = 0x80
      this.upperBoundary = 0xbf

      this.codePoint = (this.codePoint << 6) | (byte & 0x3f)
      this.bytesSeen++

      if (this.bytesSeen === this.bytesNeeded) {
        result += String.fromCodePoint(this.codePoint)
        this._reset()
      }
    }

    return result
  }

  flush() {
    const result = this.bytesNeeded > 0 ? '\ufffd' : ''
    this._reset()
    return result
  }

  _reset() {
    this.codePoint = 0
    this.bytesNeeded = 0
    this.bytesSeen = 0
    this.lowerBoundary = 0x80
    this.upperBoundary = 0xbf
  }
}

function trailingIncomplete(data, start) {
  const len = data.byteLength
  if (len <= start) return 0

  const limit = Math.max(start, len - 4)

  let i = len - 1
  while (i > limit && (data[i] & 0xc0) === 0x80) i--

  if (i < start) return 0

  const byte = data[i]

  let needed
  if (byte <= 0x7f) return 0
  if (byte >= 0xc2 && byte <= 0xdf) needed = 2
  else if (byte >= 0xe0 && byte <= 0xef) needed = 3
  else if (byte >= 0xf0 && byte <= 0xf4) needed = 4
  else return 0

  const available = len - i
  return available < needed ? available : 0
}

function trailingBytesSeen(data) {
  const len = data.byteLength
  if (len === 0) return 0

  const last = data[len - 1]

  if (last <= 0x7f) return 0
  if ((last & 0xc0) !== 0x80) return 1

  const limit = Math.max(0, len - 4)

  let i = len - 2
  while (i >= limit && (data[i] & 0xc0) === 0x80) i--

  if (i < 0) return 1

  const first = data[i]

  let needed
  if (first >= 0xc2 && first <= 0xdf) needed = 2
  else if (first >= 0xe0 && first <= 0xef) needed = 3
  else if (first >= 0xf0 && first <= 0xf4) needed = 4
  else return 1

  if (len - i !== needed) return 1

  if (needed >= 3) {
    const second = data[i + 1]
    if (first === 0xe0 && second < 0xa0) return 1
    if (first === 0xed && second > 0x9f) return 1
    if (first === 0xf0 && second < 0x90) return 1
    if (first === 0xf4 && second > 0x8f) return 1
  }

  return 0
}
{
  "name": "text-decoder",
  "version": "1.2.7",
  "description": "Streaming text decoder that preserves multibyte Unicode characters",
  "exports": {
    "./package": "./package.json",
    ".": "./index.js"
  },
  "files": [
    "index.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/text-decoder.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/text-decoder/issues"
  },
  "homepage": "https://github.com/holepunchto/text-decoder#readme",
  "dependencies": {
    "b4a": "^1.6.4"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  }
}
module.exports = class TimeOrderedSet {
  constructor () {
    this.oldest = null
    this.latest = null
    this.length = 0
  }

  has (node) {
    return !!(node.next || node.prev) || node === this.oldest
  }

  add (node) {
    if (this.has(node)) this.remove(node)

    if (!this.latest && !this.oldest) {
      this.latest = this.oldest = node
      node.prev = node.next = null
    } else {
      this.latest.next = node
      node.prev = this.latest
      node.next = null
      this.latest = node
    }

    this.length++

    return node
  }

  remove (node) {
    if (!this.has(node)) return node

    if (this.oldest !== node && this.latest !== node) {
      node.prev.next = node.next
      node.next.prev = node.prev
    } else {
      if (this.oldest === node) {
        this.oldest = node.next
        if (this.oldest) this.oldest.prev = null
      }
      if (this.latest === node) {
        this.latest = node.prev
        if (this.latest) this.latest.next = null
      }
    }

    node.next = node.prev = null
    this.length--

    return node
  }

  toArray ({ limit = Infinity, reverse = false } = {}) {
    const list = []

    if (reverse) {
      let node = this.latest
      while (node && limit--) {
        list.push(node)
        node = node.prev
      }
    } else {
      let node = this.oldest
      while (node && limit--) {
        list.push(node)
        node = node.next
      }
    }

    return list
  }
}
{
  "name": "time-ordered-set",
  "version": "2.0.1",
  "description": "Efficiently maintain a set of nodes ordered by the time they were added to the set",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "devDependencies": {
    "brittle": "^3.0.0",
    "standard": "^17.1.2"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/time-ordered-set.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/time-ordered-set/issues"
  },
  "homepage": "https://github.com/mafintosh/time-ordered-set"
}
module.exports = class TimerBrowser {
  constructor (ms, fn, ctx = null, interval = false) {
    this.ms = ms
    this.ontimeout = fn
    this.context = ctx || null
    this.interval = interval
    this.done = false

    this._timer = interval
      ? setInterval(callInterval, ms, this)
      : setTimeout(callTimeout, ms, this)
  }

  unref () {}

  ref () {}

  refresh () {
    if (this.done) return

    if (this.interval) {
      clearInterval(this._timer)
      this._timer = setInterval(callInterval, this.ms, this)
    } else {
      clearTimeout(this._timer)
      this._timer = setTimeout(callTimeout, this.ms, this)
    }
  }

  destroy () {
    this.done = true
    this.ontimeout = null

    if (this.interval) clearInterval(this._timer)
    else clearTimeout(this._timer)
  }

  static once (ms, fn, ctx) {
    return new this(ms, fn, ctx, false)
  }

  static on (ms, fn, ctx) {
    return new this(ms, fn, ctx, true)
  }
}

function callTimeout (self) {
  self.done = true
  self.ontimeout.call(self.context)
}

function callInterval (self) {
  self.ontimeout.call(self.context)
}
module.exports = isNode()
  ? require('./node')
  : require('./browser')

function isNode () {
  const to = setTimeout(function () {}, 1000)
  clearTimeout(to)
  return !!to.refresh
}
module.exports = class Timer {
  constructor (ms, fn, ctx = null, interval = false) {
    this.ms = ms
    this.ontimeout = fn
    this.context = ctx
    this.interval = interval
    this.done = false

    this._timer = interval
      ? setInterval(callInterval, ms, this)
      : setTimeout(callTimeout, ms, this)
  }

  unref () {
    this._timer.unref()
  }

  ref () {
    this._timer.ref()
  }

  refresh () {
    if (this.done !== true) this._timer.refresh()
  }

  destroy () {
    this.done = true
    this.ontimeout = null
    if (this.interval) clearInterval(this._timer)
    else clearTimeout(this._timer)
  }

  static once (ms, fn, ctx) {
    return new this(ms, fn, ctx, false)
  }

  static on (ms, fn, ctx) {
    return new this(ms, fn, ctx, true)
  }
}

function callTimeout (self) {
  self.done = true
  self.ontimeout.call(self.context)
}

function callInterval (self) {
  self.ontimeout.call(self.context)
}
{
  "name": "timeout-refresh",
  "version": "2.0.1",
  "description": "Efficiently refresh a timer",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^16.0.4",
    "tape": "^5.5.2"
  },
  "browser": "./browser.js",
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/timeout-refresh.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/timeout-refresh/issues"
  },
  "homepage": "https://github.com/mafintosh/timeout-refresh"
}
require.addon = require('require-addon')

module.exports = require.addon('.', __filename)
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

const v4Seg = '(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])'
const v4Str = `(${v4Seg}[.]){3}${v4Seg}`
const IPv4Pattern = new RegExp(`^${v4Str}$`)

const v6Seg = '(?:[0-9a-fA-F]{1,4})'
const IPv6Pattern = new RegExp(
  '^(' +
    `(?:${v6Seg}:){7}(?:${v6Seg}|:)|` +
    `(?:${v6Seg}:){6}(?:${v4Str}|:${v6Seg}|:)|` +
    `(?:${v6Seg}:){5}(?::${v4Str}|(:${v6Seg}){1,2}|:)|` +
    `(?:${v6Seg}:){4}(?:(:${v6Seg}){0,1}:${v4Str}|(:${v6Seg}){1,3}|:)|` +
    `(?:${v6Seg}:){3}(?:(:${v6Seg}){0,2}:${v4Str}|(:${v6Seg}){1,4}|:)|` +
    `(?:${v6Seg}:){2}(?:(:${v6Seg}){0,3}:${v4Str}|(:${v6Seg}){1,5}|:)|` +
    `(?:${v6Seg}:){1}(?:(:${v6Seg}){0,4}:${v4Str}|(:${v6Seg}){1,6}|:)|` +
    `(?::((?::${v6Seg}){0,5}:${v4Str}|(?::${v6Seg}){1,7}|:))` +
    ')(%[0-9a-zA-Z-.:]{1,})?$'
)

const isIPv4 = (exports.isIPv4 = function isIPv4(host) {
  return IPv4Pattern.test(host)
})

const isIPv6 = (exports.isIPv6 = function isIPv6(host) {
  return IPv6Pattern.test(host)
})

exports.isIP = function isIP(host) {
  if (isIPv4(host)) return 4
  if (isIPv6(host)) return 6
  return 0
}
const events = require('events')
const b4a = require('b4a')
const binding = require('../binding')

module.exports = class NetworkInterfaces extends events.EventEmitter {
  constructor(udx) {
    super()

    this._handle = b4a.alloc(binding.sizeof_udx_napi_interface_event_t)
    this._watching = false
    this._destroying = null

    binding.udx_napi_interface_event_init(
      udx._handle,
      this._handle,
      this,
      this._onevent,
      this._onclose
    )

    this.interfaces = binding.udx_napi_interface_event_get_addrs(this._handle)
  }

  _onclose() {
    this.emit('close')
  }

  _onevent() {
    this.interfaces = binding.udx_napi_interface_event_get_addrs(this._handle)

    this.emit('change', this.interfaces)
  }

  watch() {
    if (this._watching) return this
    this._watching = true

    binding.udx_napi_interface_event_start(this._handle)

    return this
  }

  unwatch() {
    if (!this._watching) return this
    this._watching = false

    binding.udx_napi_interface_event_stop(this._handle)

    return this
  }

  async destroy() {
    if (this._destroying) return this._destroying
    this._destroying = events.once(this, 'close')

    binding.udx_napi_interface_event_close(this._handle)

    return this._destroying
  }

  [Symbol.iterator]() {
    return this.interfaces[Symbol.iterator]()
  }
}
const events = require('events')
const b4a = require('b4a')
const binding = require('../binding')
const ip = require('./ip')

module.exports = class UDXSocket extends events.EventEmitter {
  constructor(udx, opts = {}) {
    super()

    this.udx = udx

    this._handle = b4a.alloc(binding.sizeof_udx_napi_socket_t)
    this._inited = false
    this._host = null
    this._family = 0
    this._ipv6Only = opts.ipv6Only === true
    this._reuseAddress = opts.reuseAddress === true
    this._port = 0
    this._reqs = []
    this._free = []
    this._closing = null
    this._closed = false

    this._view64 = new BigUint64Array(
      this._handle.buffer,
      this._handle.byteOffset,
      this._handle.byteLength >> 3
    )

    this.streams = new Set()

    this.userData = null
  }

  get bound() {
    return this._port !== 0
  }

  get closing() {
    return this._closing !== null
  }

  get idle() {
    return this.streams.size === 0
  }

  get busy() {
    return this.streams.size > 0
  }

  get bytesTransmitted() {
    if (this._inited !== true) return 0
    return Number(this._view64[binding.offsetof_udx_socket_t_bytes_tx >> 3])
  }

  get packetsTransmitted() {
    if (this._inited !== true) return 0
    return Number(this._view64[binding.offsetof_udx_socket_t_packets_tx >> 3])
  }

  get bytesReceived() {
    if (this._inited !== true) return 0
    return Number(this._view64[binding.offsetof_udx_socket_t_bytes_rx >> 3])
  }

  get packetsReceived() {
    if (this._inited !== true) return 0
    return Number(this._view64[binding.offsetof_udx_socket_t_packets_rx >> 3])
  }

  get packetsDroppedByKernel() {
    if (this._inited !== true) return 0
    return Number(this._view64[binding.offsetof_udx_socket_t_packets_dropped_by_kernel >> 3])
  }

  toJSON() {
    return {
      bound: this.bound,
      closing: this.closing,
      streams: this.streams.size,
      address: this.address(),
      ipv6Only: this._ipv6Only,
      reuseAddress: this._reuseAddress,
      idle: this.idle,
      busy: this.busy
    }
  }

  _init() {
    if (this._inited) return

    binding.udx_napi_socket_init(
      this.udx._handle,
      this._handle,
      this,
      this._onsend,
      this._onmessage,
      this._onclose,
      this._reallocMessage
    )

    this._inited = true
  }

  _onsend(id, err) {
    const req = this._reqs[id]

    const onflush = req.onflush

    req.buffer = null
    req.onflush = null

    this._free.push(id)

    onflush(err >= 0)

    // gc the free list
    if (this._free.length >= 16 && this._free.length === this._reqs.length) {
      this._free = []
      this._reqs = []
    }
  }

  _onmessage(len, port, host, family) {
    this.emit('message', this.udx._consumeMessage(len), { host, family, port })
    return this.udx._buffer
  }

  _onclose() {
    this.emit('close')
  }

  _reallocMessage() {
    return this.udx._reallocMessage()
  }

  _onidle() {
    this.emit('idle')
  }

  _onbusy() {
    this.emit('busy')
  }

  _addStream(stream) {
    if (this.streams.has(stream)) return false
    this.streams.add(stream)
    if (this.streams.size === 1) this._onbusy()
    return true
  }

  _removeStream(stream) {
    if (!this.streams.has(stream)) return false
    this.streams.delete(stream)
    const closed = this._closeMaybe()
    if (this.idle && !closed) this._onidle()
    return true
  }

  address() {
    if (!this.bound) return null
    return { host: this._host, family: this._family, port: this._port }
  }

  bind(port, host) {
    if (this.bound) throw new Error('Already bound')
    if (this.closing) throw new Error('Socket is closed')

    if (!port) port = 0

    let flags = 0
    if (this._ipv6Only) flags |= binding.UV_UDP_IPV6ONLY
    if (this._reuseAddress) flags |= binding.UV_UDP_REUSEADDR

    let family

    if (host) {
      family = ip.isIP(host)
      if (!family) throw new Error(`${host} is not a valid IP address`)

      if (!this._inited) this._init()

      this._port = binding.udx_napi_socket_bind(this._handle, port, host, family, flags)
    } else {
      if (!this._inited) this._init()

      try {
        host = '::'
        family = 6
        this._port = binding.udx_napi_socket_bind(this._handle, port, host, family, flags)
      } catch {
        host = '0.0.0.0'
        family = 4
        this._port = binding.udx_napi_socket_bind(this._handle, port, host, family, flags)
      }
    }

    this._host = host
    this._family = family

    this.emit('listening')
  }

  async close() {
    if (this._closing) return this._closing
    this._closing = new Promise((resolve) => this.once('close', resolve))
    this._closeMaybe()
    return this._closing
  }

  _closeMaybe() {
    if (this._closed || this._closing === null) return this._closed

    if (!this._inited) {
      this._closed = true
      this.emit('close')
      return true
    }

    if (this.idle) {
      binding.udx_napi_socket_close(this._handle)
      this._closed = true
    }

    return this._closed
  }

  setTTL(ttl) {
    if (!this._inited) throw new Error('Socket not active')
    binding.udx_napi_socket_set_ttl(this._handle, ttl)
  }

  getRecvBufferSize() {
    if (!this._inited) throw new Error('Socket not active')
    return binding.udx_napi_socket_get_recv_buffer_size(this._handle)
  }

  setRecvBufferSize(size) {
    if (!this._inited) throw new Error('Socket not active')
    return binding.udx_napi_socket_set_recv_buffer_size(this._handle, size)
  }

  getSendBufferSize() {
    if (!this._inited) throw new Error('Socket not active')
    return binding.udx_napi_socket_get_send_buffer_size(this._handle)
  }

  setSendBufferSize(size) {
    if (!this._inited) throw new Error('Socket not active')
    return binding.udx_napi_socket_set_send_buffer_size(this._handle, size)
  }

  addMembership(group, ifaceAddress) {
    if (!this._inited) throw new Error('Socket not active')
    return binding.udx_napi_socket_set_membership(this._handle, group, ifaceAddress || '', true)
  }

  dropMembership(group, ifaceAddress) {
    if (!this._inited) throw new Error('Socket not active')
    return binding.udx_napi_socket_set_membership(this._handle, group, ifaceAddress || '', false)
  }

  async send(buffer, port, host, ttl) {
    if (this.closing) return false

    if (!host) host = '127.0.0.1'

    const family = ip.isIP(host)
    if (!family) throw new Error(`${host} is not a valid IP address`)

    if (!this.bound) this.bind(0)

    const id = this._allocSend()
    const req = this._reqs[id]

    req.buffer = buffer

    const promise = new Promise((resolve) => {
      req.onflush = resolve
    })

    binding.udx_napi_socket_send_ttl(
      this._handle,
      req.handle,
      id,
      buffer,
      port,
      host,
      family,
      ttl || 0
    )

    return promise
  }

  trySend(buffer, port, host, ttl) {
    if (this.closing) return

    if (!host) host = '127.0.0.1'

    const family = ip.isIP(host)
    if (!family) throw new Error(`${host} is not a valid IP address`)

    if (!this.bound) this.bind(0)

    const id = this._allocSend()
    const req = this._reqs[id]

    req.buffer = buffer
    req.onflush = noop

    binding.udx_napi_socket_send_ttl(
      this._handle,
      req.handle,
      id,
      buffer,
      port,
      host,
      family,
      ttl || 0
    )
  }

  _allocSend() {
    if (this._free.length > 0) return this._free.pop()
    const handle = b4a.allocUnsafe(binding.sizeof_udx_socket_send_t)
    return this._reqs.push({ handle, buffer: null, onflush: null }) - 1
  }
}

function noop() {}
const streamx = require('streamx')
const b4a = require('b4a')
const binding = require('../binding')
const ip = require('./ip')

const MAX_PACKET = 2048
const BUFFER_SIZE = 65536 + MAX_PACKET

module.exports = class UDXStream extends streamx.Duplex {
  constructor(udx, id, opts = {}) {
    super({ mapWritable: toBuffer, eagerOpen: true })

    this.udx = udx
    this.socket = null

    this._handle = b4a.alloc(binding.sizeof_udx_napi_stream_t)
    this._view = new Uint32Array(
      this._handle.buffer,
      this._handle.byteOffset,
      this._handle.byteLength >> 2
    )
    this._view16 = new Uint16Array(
      this._handle.buffer,
      this._handle.byteOffset,
      this._handle.byteLength >> 1
    )
    this._view64 = new BigUint64Array(
      this._handle.buffer,
      this._handle.byteOffset,
      this._handle.byteLength >> 3
    )

    this._wreqs = []
    this._wfree = []

    this._sreqs = []
    this._sfree = []
    this._closed = false

    this._flushing = 0
    this._flushes = []

    this._buffer = null
    this._reallocData()

    this._onwrite = null
    this._ondestroy = null
    this._firewall = opts.firewall || firewallAll

    this._remoteChanging = null
    this._previousSocket = null

    this.id = id
    this.remoteId = 0
    this.remoteHost = null
    this.remoteFamily = 0
    this.remotePort = 0

    this.userData = null

    binding.udx_napi_stream_init(
      this.udx._handle,
      this._handle,
      id,
      opts.framed ? 1 : 0,
      this,
      this._ondata,
      this._onend,
      this._ondrain,
      this._onack,
      this._onsend,
      this._onmessage,
      this._onclose,
      this._onfirewall,
      this._onremotechanged,
      this._reallocData,
      this._reallocMessage
    )

    if (opts.seq) binding.udx_napi_stream_set_seq(this._handle, opts.seq)

    binding.udx_napi_stream_recv_start(this._handle, this._buffer)
  }

  get connected() {
    return this.socket !== null
  }

  get mtu() {
    return this._view16[binding.offsetof_udx_stream_t_mtu >> 1]
  }

  get rtt() {
    return this._view[binding.offsetof_udx_stream_t_srtt >> 2]
  }

  get cwnd() {
    return this._view[binding.offsetof_udx_stream_t_cwnd >> 2]
  }

  get rtoCount() {
    return this._view16[binding.offsetof_udx_stream_t_rto_count >> 1]
  }

  get retransmits() {
    return this._view16[binding.offsetof_udx_stream_t_retransmit_count >> 1]
  }

  get bbrState() {
    const view = new Uint8Array(
      this._handle.buffer,
      this._handle.byteOffset,
      this._handle.byteLength
    )
    return view[binding.offsetof_udx_stream_t_bbr_state]
  }

  get bbrBandwidth() {
    return binding.udx_napi_stream_get_bw(this._handle)
  }

  get fastRecoveries() {
    return this._view16[binding.offsetof_udx_stream_t_fast_recovery_count >> 1]
  }

  get inflight() {
    return this._view[binding.offsetof_udx_stream_t_inflight >> 2]
  }

  get bytesTransmitted() {
    return Number(this._view64[binding.offsetof_udx_stream_t_bytes_tx >> 3])
  }

  get packetsTransmitted() {
    return Number(this._view64[binding.offsetof_udx_stream_t_packets_tx >> 3])
  }

  get bytesReceived() {
    return Number(this._view64[binding.offsetof_udx_stream_t_bytes_rx >> 3])
  }

  get packetsReceived() {
    return Number(this._view64[binding.offsetof_udx_stream_t_packets_rx >> 3])
  }

  get localHost() {
    return this.socket ? this.socket.address().host : null
  }

  get localFamily() {
    return this.socket ? this.socket.address().family : 0
  }

  get localPort() {
    return this.socket ? this.socket.address().port : 0
  }

  setInteractive(bool) {
    if (!this._closed) return
    binding.udx_napi_stream_set_mode(this._handle, bool ? 0 : 1)
  }

  connect(socket, remoteId, port, host, opts = {}) {
    if (this._closed) return

    if (this.connected) throw new Error('Already connected')
    if (socket.closing) throw new Error('Socket is closed')

    if (typeof host === 'object') {
      opts = host
      host = null
    }

    if (!host) host = '127.0.0.1'

    const family = ip.isIP(host)
    if (!family) throw new Error(`${host} is not a valid IP address`)
    if (!(port > 0 && port < 65536)) throw new Error(`${port} is not a valid port`)

    if (!socket.bound) socket.bind(0)

    this.remoteId = remoteId
    this.remotePort = port
    this.remoteHost = host
    this.remoteFamily = family
    this.socket = socket

    if (opts.ack) binding.udx_napi_stream_set_ack(this._handle, opts.ack)

    binding.udx_napi_stream_connect(this._handle, socket._handle, remoteId, port, host, family)

    this.socket._addStream(this)

    this.emit('connect')
  }

  changeRemote(socket, remoteId, port, host) {
    if (this._remoteChanging) throw new Error('Remote already changing')

    if (!this.connected) throw new Error('Not yet connected')
    if (socket.closing) throw new Error('Socket is closed')

    if (this.socket.udx !== socket.udx) {
      throw new Error('Cannot change to a socket on another UDX instance')
    }

    if (!host) host = '127.0.0.1'

    const family = ip.isIP(host)
    if (!family) throw new Error(`${host} is not a valid IP address`)
    if (!(port > 0 && port < 65536)) throw new Error(`${port} is not a valid port`)

    if (this.socket !== socket) this._previousSocket = this.socket

    this.remoteId = remoteId
    this.remotePort = port
    this.remoteHost = host
    this.remoteFamily = family
    this.socket = socket

    this._remoteChanging = new Promise((resolve, reject) => {
      const onchanged = () => {
        this.off('close', onclose)
        resolve()
      }

      const onclose = () => {
        this.off('remote-changed', onchanged)
        reject(new Error('Stream is closed'))
      }

      this.once('remote-changed', onchanged).once('close', onclose)
    })

    binding.udx_napi_stream_change_remote(
      this._handle,
      socket._handle,
      remoteId,
      port,
      host,
      family
    )

    this.socket._addStream(this)

    return this._remoteChanging
  }

  relayTo(destination) {
    if (this._closed) return

    binding.udx_napi_stream_relay_to(this._handle, destination._handle)
  }

  async send(buffer) {
    if (!this.connected || this._closed) return false

    const id = this._allocSend()
    const req = this._sreqs[id]

    req.buffer = buffer

    const promise = new Promise((resolve) => {
      req.onflush = resolve
    })

    binding.udx_napi_stream_send(this._handle, req.handle, id, buffer)

    return promise
  }

  trySend(buffer) {
    if (!this.connected || this._closed) return

    const id = this._allocSend()
    const req = this._sreqs[id]

    req.buffer = buffer
    req.onflush = noop

    binding.udx_napi_stream_send(this._handle, req.handle, id, buffer)
  }

  async flush() {
    if ((await streamx.Writable.drained(this)) === false) return false
    if (this.destroying) return false

    const missing = this._wreqs.length - this._wfree.length
    if (missing === 0) return true

    return new Promise((resolve) => {
      this._flushes.push({ flush: this._flushing++, missing, resolve })
    })
  }

  toJSON() {
    return {
      id: this.id,
      connected: this.connected,
      destroying: this.destroying,
      destroyed: this.destroyed,
      remoteId: this.remoteId,
      remoteHost: this.remoteHost,
      remoteFamily: this.remoteFamily,
      remotePort: this.remotePort,
      mtu: this.mtu,
      rtt: this.rtt,
      cwnd: this.cwnd,
      inflight: this.inflight,
      socket: this.socket ? this.socket.toJSON() : null
    }
  }

  _read(cb) {
    cb(null)
  }

  _writeContinue(err) {
    if (this._onwrite === null) return
    const cb = this._onwrite
    this._onwrite = null
    cb(err)
  }

  _destroyContinue(err) {
    if (this._ondestroy === null) return
    const cb = this._ondestroy
    this._ondestroy = null
    cb(err)
  }

  _writev(buffers, cb) {
    if (!this.connected) {
      throw customError('Writing while not connected not currently supported', 'ERR_ASSERTION')
    }

    let drained = true

    if (buffers.length === 1) {
      const id = this._allocWrite(1)
      const req = this._wreqs[id]

      req.flush = this._flushing
      req.buffer = buffers[0]

      drained = binding.udx_napi_stream_write(this._handle, req.handle, id, req.buffer) !== 0
    } else {
      const id = this._allocWrite(nextBatchSize(buffers.length))
      const req = this._wreqs[id]

      req.flush = this._flushing
      req.buffers = buffers

      drained = binding.udx_napi_stream_writev(this._handle, req.handle, id, req.buffers) !== 0
    }

    if (drained) cb(null)
    else this._onwrite = cb
  }

  _final(cb) {
    const id = this._allocWrite(1)
    const req = this._wreqs[id]

    req.flush = this._flushes
    req.buffer = b4a.allocUnsafe(0)

    const drained =
      binding.udx_napi_stream_write_end(this._handle, req.handle, id, req.buffer) !== 0

    if (drained) cb(null)
    else this._onwrite = cb
  }

  _predestroy() {
    if (!this._closed) binding.udx_napi_stream_destroy(this._handle)
    this._closed = true
    this._writeContinue(null)
  }

  _destroy(cb) {
    if (this.connected) this._ondestroy = cb
    else cb(null)
  }

  _ondata(read) {
    this.push(this._consumeData(read))
    return this._buffer
  }

  _onend(read) {
    if (read > 0) this.push(this._consumeData(read))
    this.push(null)
  }

  _ondrain() {
    this._writeContinue(null)
  }

  _flushAck(flush) {
    for (let i = this._flushes.length - 1; i >= 0; i--) {
      const f = this._flushes[i]
      if (f.flush < flush) break
      f.missing--
    }

    while (this._flushes.length > 0 && this._flushes[0].missing === 0) {
      this._flushes.shift().resolve(true)
    }
  }

  _onack(id) {
    const req = this._wreqs[id]

    req.buffers = req.buffer = null
    this._wfree.push(id)

    if (this._flushes.length > 0) this._flushAck(req.flush)

    // gc the free list
    if (this._wfree.length >= 64 && this._wfree.length === this._wreqs.length) {
      this._wfree = []
      this._wreqs = []
    }
  }

  _onsend(id, err) {
    const req = this._sreqs[id]

    const onflush = req.onflush

    req.buffer = null
    req.onflush = null

    this._sfree.push(id)

    onflush(err >= 0)

    // gc the free list
    if (this._sfree.length >= 16 && this._sfree.length === this._sreqs.length) {
      this._sfree = []
      this._sreqs = []
    }
  }

  _onmessage(len) {
    this.emit('message', this.udx._consumeMessage(len))
    return this.udx._buffer
  }

  _onclose(err) {
    this._closed = true

    if (this.socket) {
      this.socket._removeStream(this)
      this.socket = null
    }

    if (this._previousSocket) {
      this._previousSocket._removeStream(this)
      this._previousSocket = null
    }

    // no error, we don't need to do anything
    if (!err) return this._destroyContinue(null)

    if (this._ondestroy === null) this.destroy(err)
    else this._destroyContinue(err)
  }

  _onfirewall(socket, port, host, family) {
    if (port <= 0 || port > 65535) return 1
    return this._firewall(socket, port, host, family) ? 1 : 0
  }

  _onremotechanged() {
    if (this._previousSocket) {
      this._previousSocket._removeStream(this)
      this._previousSocket = null
    }

    this._remoteChanging = null
    this.emit('remote-changed')
  }

  _consumeData(len) {
    const next = this._buffer.subarray(0, len)
    this._buffer = this._buffer.subarray(len)
    if (this._buffer.byteLength < MAX_PACKET) this._reallocData()
    return next
  }

  _reallocData() {
    this._buffer = b4a.allocUnsafe(BUFFER_SIZE)
    return this._buffer
  }

  _reallocMessage() {
    return this.udx._reallocMessage()
  }

  _allocWrite(size) {
    if (this._wfree.length === 0) {
      const handle = b4a.allocUnsafe(binding.udx_napi_stream_write_sizeof(size))
      return (
        this._wreqs.push({
          handle,
          size,
          buffers: null,
          buffer: null,
          flush: 0
        }) - 1
      )
    }

    const free = this._wfree.pop()
    if (size === 1) return free

    const next = this._wreqs[free]
    if (next.size < size) {
      next.handle = b4a.allocUnsafe(binding.udx_napi_stream_write_sizeof(size))
      next.size = size
    }

    return free
  }

  _allocSend() {
    if (this._sfree.length > 0) return this._sfree.pop()
    const handle = b4a.allocUnsafe(binding.sizeof_udx_stream_send_t)
    return this._sreqs.push({ handle, buffer: null, resolve: null, reject: null }) - 1
  }
}

function noop() {}

function toBuffer(data) {
  return typeof data === 'string' ? b4a.from(data) : data
}

function firewallAll(socket, port, host) {
  return true
}

function customError(message, code) {
  const error = new Error(message)
  error.code = code
  return error
}

function nextBatchSize(n) {
  // try to coerce the the writevs into sameish size
  if (n === 1) return 1
  // group all < 8 to the same size, low mem overhead but save some small allocs
  if (n < 8) return 8
  if (n < 16) return 16
  if (n < 32) return 32
  if (n < 64) return 64
  return n
}
const b4a = require('b4a')
const binding = require('../binding')
const ip = require('./ip')
const Socket = require('./socket')
const Stream = require('./stream')
const NetworkInterfaces = require('./network-interfaces')

const MAX_MESSAGE = 4096
const BUFFER_SIZE = 65536 + MAX_MESSAGE

module.exports = class UDX {
  constructor() {
    this._handle = b4a.alloc(binding.sizeof_udx_napi_t)
    this._watchers = new Set()
    this._view64 = new BigUint64Array(
      this._handle.buffer,
      this._handle.byteOffset,
      this._handle.byteLength >> 3
    )

    this._buffer = null
    this._reallocMessage()

    binding.udx_napi_init(this._handle, this._buffer)
  }

  static isIPv4(host) {
    return ip.isIPv4(host)
  }

  static isIPv6(host) {
    return ip.isIPv6(host)
  }

  static isIP(host) {
    return ip.isIP(host)
  }

  get bytesTransmitted() {
    return Number(this._view64[binding.offsetof_udx_t_bytes_tx >> 3])
  }

  get packetsTransmitted() {
    return Number(this._view64[binding.offsetof_udx_t_packets_tx >> 3])
  }

  get bytesReceived() {
    return Number(this._view64[binding.offsetof_udx_t_bytes_rx >> 3])
  }

  get packetsReceived() {
    return Number(this._view64[binding.offsetof_udx_t_packets_rx >> 3])
  }

  get packetsDroppedByKernel() {
    return Number(this._view64[binding.offsetof_udx_t_packets_dropped_by_kernel >> 3])
  }

  _consumeMessage(len) {
    const next = this._buffer.subarray(0, len)
    this._buffer = this._buffer.subarray(len)
    if (this._buffer.byteLength < MAX_MESSAGE) this._reallocMessage()
    return next
  }

  _reallocMessage() {
    // TODO: move reallocation to native
    this._buffer = b4a.allocUnsafe(BUFFER_SIZE)
    return this._buffer
  }

  createSocket(opts) {
    return new Socket(this, opts)
  }

  createStream(id, opts) {
    return new Stream(this, id, opts)
  }

  networkInterfaces() {
    let [watcher = null] = this._watchers
    if (watcher) return watcher.interfaces

    watcher = new NetworkInterfaces(this)
    watcher.destroy()

    return watcher.interfaces
  }

  watchNetworkInterfaces(onchange) {
    const watcher = new NetworkInterfaces(this)

    this._watchers.add(watcher)
    watcher.on('close', () => {
      this._watchers.delete(watcher)
    })

    if (onchange) watcher.on('change', onchange)

    return watcher.watch()
  }

  async lookup(host, opts = {}) {
    const { family = 0 } = opts

    const req = b4a.alloc(binding.sizeof_udx_napi_lookup_t)
    const ctx = {
      req,
      resolve: null,
      reject: null
    }

    const promise = new Promise((resolve, reject) => {
      ctx.resolve = resolve
      ctx.reject = reject
    })

    binding.udx_napi_lookup(this._handle, req, host, family, ctx, onlookup)

    return promise
  }
}

function onlookup(err, host, family) {
  if (err) this.reject(err)
  else this.resolve({ host, family })
}
{
  "name": "udx-native",
  "version": "1.20.7",
  "description": "udx is reliable, multiplexed, and congestion-controlled streams over udp",
  "main": "lib/udx.js",
  "files": [
    "lib",
    "prebuilds",
    "binding.cc",
    "binding.js",
    "CMakeLists.txt"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "addon": true,
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node --coverage test/*.js",
    "test:bare": "brittle-bare --coverage test/*.js",
    "test:all": "brittle test/*.js test/slow/*.js",
    "test:generate": "brittle -r test/all.js test/*.js",
    "bench": "brittle test/bench/*.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/udx-native.git"
  },
  "keywords": [
    "tcp",
    "udp",
    "stream",
    "reliable"
  ],
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/udx-native/issues"
  },
  "homepage": "https://github.com/holepunchto/udx-native#readme",
  "engines": {
    "bare": ">=1.17.4"
  },
  "dependencies": {
    "b4a": "^1.5.0",
    "bare-events": "^2.2.0",
    "require-addon": "^1.1.0",
    "streamx": "^2.22.0"
  },
  "devDependencies": {
    "bare-compat-napi": "^1.3.0",
    "brittle": "^3.1.0",
    "cmake-bare": "^1.1.10",
    "cmake-fetch": "^1.0.1",
    "cmake-napi": "^1.0.5",
    "is-ci": "^3.0.1",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "tiny-byte-size": "^1.1.0"
  }
}
exports.add = add
exports.has = has
exports.remove = remove
exports.swap = swap

function add (list, item) {
  if (has(list, item)) return item
  item._index = list.length
  list.push(item)
  return item
}

function has (list, item) {
  return item._index < list.length && list[item._index] === item
}

function remove (list, item) {
  if (!has(list, item)) return null

  var last = list.pop()
  if (last !== item) {
    list[item._index] = last
    last._index = item._index
  }

  return item
}

function swap (list, a, b) {
  if (!has(list, a) || !has(list, b)) return
  var tmp = a._index
  a._index = b._index
  list[a._index] = a
  b._index = tmp
  list[b._index] = b
}
{
  "name": "unordered-set",
  "version": "2.0.1",
  "description": "A couple of functions that make it easy to maintain an unordered set as an array in an efficient way",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^6.0.4",
    "tape": "^4.4.0"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/unordered-set.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/unordered-set/issues"
  },
  "homepage": "https://github.com/mafintosh/unordered-set"
}
const b4a = require('b4a')

unslab.all = all
unslab.is = is

module.exports = unslab

function unslab (buf) {
  if (buf === null || buf.buffer.byteLength === buf.byteLength) return buf
  const copy = b4a.allocUnsafeSlow(buf.byteLength)
  copy.set(buf, 0)
  return copy
}

function is (buf) {
  return buf.buffer.byteLength !== buf.byteLength
}

function all (list) {
  let size = 0
  for (let i = 0; i < list.length; i++) {
    const buf = list[i]
    size += buf === null || buf.buffer.byteLength === buf.byteLength ? 0 : buf.byteLength
  }

  const copy = b4a.allocUnsafeSlow(size)
  const result = new Array(list.length)

  let offset = 0
  for (let i = 0; i < list.length; i++) {
    let buf = list[i]

    if (buf !== null && buf.buffer.byteLength !== buf.byteLength) {
      copy.set(buf, offset)
      buf = copy.subarray(offset, offset += buf.byteLength)
    }

    result[i] = buf
  }

  return result
}
{
  "name": "unslab",
  "version": "1.3.0",
  "description": "Unslab some slab'ed buffers",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.6.6"
  },
  "devDependencies": {
    "brittle": "^3.5.2",
    "standard": "^17.1.0"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/unslab.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/unslab/issues"
  },
  "homepage": "https://github.com/holepunchto/unslab"
}
const { runtime, platform, arch, version } =
  typeof Bare !== 'undefined'
    ? {
        runtime: 'bare',
        platform: global.Bare.platform,
        arch: global.Bare.arch,
        version: global.Bare.version
      }
    : typeof process !== 'undefined'
      ? {
          runtime: 'node',
          platform: global.process.platform,
          arch: global.process.arch,
          version: global.process.version
        }
      : typeof Window !== 'undefined'
        ? { runtime: 'browser', platform: 'unknown', arch: 'unknown', version: 'unknown' }
        : { runtime: 'unknown', platform: 'unknown', arch: 'unknown', version: 'unknown' }

exports.runtime = runtime
exports.version = version
exports.platform = platform
exports.arch = arch
exports.isBare = runtime === 'bare'
exports.isBareKit = exports.isBare && typeof BareKit !== 'undefined'
exports.isPear = typeof Pear !== 'undefined'
exports.isNode = runtime === 'node'
exports.isBrowser = runtime === 'browser'
exports.isWindows = platform === 'win32'
exports.isLinux = platform === 'linux'
exports.isMac = platform === 'darwin'
exports.isIOS = platform === 'ios' || platform === 'ios-simulator'
exports.isAndroid = platform === 'android'
exports.isElectron = typeof process !== 'undefined' && !!global.process.versions?.electron
exports.isElectronRenderer = exports.isElectron && global.process.type === 'renderer'
exports.isElectronWorker = exports.isElectron && global.process.type === 'worker'
{
  "name": "which-runtime",
  "version": "1.4.0",
  "description": "Detect if you are in Bare or Node and which os etc",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte .",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/which-runtime.git"
  },
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/which-runtime/issues"
  },
  "homepage": "https://github.com/holepunchto/which-runtime",
  "devDependencies": {
    "brittle": "^3.0.0",
    "lunte": "^1.4.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = class MaxCache {
  constructor ({ maxSize, maxAge, createMap, ongc }) {
    this.maxSize = maxSize
    this.maxAge = maxAge
    this.ongc = ongc || null

    this._createMap = createMap || defaultCreateMap
    this._latest = this._createMap()
    this._oldest = this._createMap()
    this._retained = this._createMap()
    this._gced = false
    this._interval = null

    if (this.maxAge > 0 && this.maxAge < Infinity) {
      const tick = Math.ceil(2 / 3 * this.maxAge)
      this._interval = setInterval(this._gcAuto.bind(this), tick)
      if (this._interval.unref) this._interval.unref()
    }
  }

  * [Symbol.iterator] () {
    for (const it of [this._latest, this._oldest, this._retained]) {
      yield * it
    }
  }

  * keys () {
    for (const it of [this._latest, this._oldest, this._retained]) {
      yield * it.keys()
    }
  }

  * values () {
    for (const it of [this._latest, this._oldest, this._retained]) {
      yield * it.values()
    }
  }

  destroy () {
    this.clear()
    clearInterval(this._interval)
    this._interval = null
  }

  clear () {
    this._gced = true
    this._latest.clear()
    this._oldest.clear()
    this._retained.clear()
  }

  set (k, v) {
    if (this._retained.has(k)) return this
    this._latest.set(k, v)
    this._oldest.delete(k) || this._retained.delete(k)
    if (this._latest.size >= this.maxSize) this._gc()
    return this
  }

  retain (k, v) {
    this._retained.set(k, v)
    this._latest.delete(k) || this._oldest.delete(k)
    return this
  }

  delete (k) {
    return this._latest.delete(k) || this._oldest.delete(k) || this._retained.delete(k)
  }

  has (k) {
    return this._latest.has(k) || this._oldest.has(k) || this._retained.has(k)
  }

  get (k) {
    if (this._latest.has(k)) {
      return this._latest.get(k)
    }

    if (this._oldest.has(k)) {
      const v = this._oldest.get(k)
      this._latest.set(k, v)
      this._oldest.delete(k)
      return v
    }

    if (this._retained.has(k)) {
      return this._retained.get(k)
    }

    return null
  }

  _gcAuto () {
    if (!this._gced) this._gc()
    this._gced = false
  }

  _gc () {
    this._gced = true
    if (this.ongc !== null && this._oldest.size > 0) this.ongc(this._oldest)
    this._oldest = this._latest
    this._latest = this._createMap()
  }
}

function defaultCreateMap () {
  return new Map()
}
{
  "name": "xache",
  "version": "1.2.1",
  "description": "Yet another auto expiring, max sizable cache",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "devDependencies": {
    "brittle": "^3.3.2",
    "standard": "^17.1.0"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/xache.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/xache/issues"
  },
  "homepage": "https://github.com/mafintosh/xache"
}
const b4a = require('b4a')

const ALPHABET = 'ybndrfg8ejkmcpqxot1uwisza345h769'
const MIN = 0x31 // 1
const MAX = 0x7a // z
const REVERSE = new Int8Array(1 + MAX - MIN)

REVERSE.fill(-1)

for (let i = 0; i < ALPHABET.length; i++) {
  const v = ALPHABET.charCodeAt(i) - MIN
  REVERSE[v] = i
}

exports.encode = encode
exports.decode = decode
exports.ALPHABET = ALPHABET

function decode (s, out) {
  let pb = 0
  let ps = 0

  const r = s.length & 7
  const q = (s.length - r) / 8

  if (!out) out = b4a.allocUnsafe(Math.ceil(s.length * 5 / 8))

  // 0 5 2 7 4 1 6 3 (+5 mod 8)
  for (let i = 0; i < q; i++) {
    const a = quintet(s, ps++)
    const b = quintet(s, ps++)
    const c = quintet(s, ps++)
    const d = quintet(s, ps++)
    const e = quintet(s, ps++)
    const f = quintet(s, ps++)
    const g = quintet(s, ps++)
    const h = quintet(s, ps++)

    out[pb++] = (a << 3) | (b >>> 2)
    out[pb++] = ((b & 0b11) << 6) | (c << 1) | (d >>> 4)
    out[pb++] = ((d & 0b1111) << 4) | (e >>> 1)
    out[pb++] = ((e & 0b1) << 7) | (f << 2) | (g >>> 3)
    out[pb++] = ((g & 0b111) << 5) | h
  }

  if (r === 0) return out.subarray(0, pb)

  const a = quintet(s, ps++)
  const b = quintet(s, ps++)

  out[pb++] = (a << 3) | (b >>> 2)

  if (r <= 2) return out.subarray(0, pb)

  const c = quintet(s, ps++)
  const d = quintet(s, ps++)

  out[pb++] = ((b & 0b11) << 6) | (c << 1) | (d >>> 4)

  if (r <= 4) return out.subarray(0, pb)

  const e = quintet(s, ps++)

  out[pb++] = ((d & 0b1111) << 4) | (e >>> 1)

  if (r <= 5) return out.subarray(0, pb)

  const f = quintet(s, ps++)
  const g = quintet(s, ps++)

  out[pb++] = ((e & 0b1) << 7) | (f << 2) | (g >>> 3)

  if (r <= 7) return out.subarray(0, pb)

  const h = quintet(s, ps++)

  out[pb++] = ((g & 0b111) << 5) | h

  return out.subarray(0, pb)
}

function encode (buf) {
  if (typeof buf === 'string') buf = b4a.from(buf)

  const max = buf.byteLength * 8

  let s = ''

  for (let p = 0; p < max; p += 5) {
    const i = p >>> 3
    const j = p & 7

    if (j <= 3) {
      s += ALPHABET[(buf[i] >>> (3 - j)) & 0b11111]
      continue
    }

    const of = j - 3
    const h = (buf[i] << of) & 0b11111
    const l = (i >= buf.byteLength ? 0 : buf[i + 1]) >>> (8 - of)

    s += ALPHABET[h | l]
  }

  return s
}

function quintet (s, i) {
  if (i > s.length) {
    return 0
  }

  const v = s.charCodeAt(i)

  if (v < MIN || v > MAX) {
    throw Error('Invalid character in base32 input: "' + s[i] + '" at position ' + i)
  }

  const bits = REVERSE[v - MIN]

  if (bits === -1) {
    throw Error('Invalid character in base32 input: "' + s[i] + '" at position ' + i)
  }

  return bits
}
{
  "name": "z32",
  "version": "1.1.0",
  "description": "Encode & decode z-base32",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.5.3"
  },
  "devDependencies": {
    "base-x": "^4.0.0",
    "base32": "0.0.7",
    "brittle": "^3.1.3",
    "nanobench": "^3.0.0",
    "rfc4648": "^1.5.2",
    "standard": "^17.0.0"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/z32.git"
  },
  "scripts": {
    "test": "standard && brittle test.js",
    "bench": "node benchmark.js"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/z32/issues"
  },
  "homepage": "https://github.com/mafintosh/z32"
}
{
  "name": "atproto-room",
  "version": "0.2.22",
  "description": "Attestation-gated, encrypted multi-writer room engine — StateBase (keet-model admission) + Lease + signer + RepoBase + LabelBase/LabelRoom + serve-membrane. Extracted from hyper-proto-peer; consumed by the atproto peer (repo devices) and the co-authored labeler.",
  "type": "module",
  "main": "index.js",
  "scripts": {
    "test": "bare test/all.js",
    "test:units": "node test/label-base.test.mjs && node test/label-signer.test.mjs && node test/label-room.test.mjs",
    "postinstall": "node scripts/bare-deps.mjs"
  },
  "dependencies": {
    "@ipld/dag-cbor": "^9.2.1",
    "atproto-identity": "file:../atproto-identity",
    "atproto-repo": "file:../atproto-repo",
    "atproto-store": "file:../atproto-store",
    "autobase": "7.28.1",
    "b4a": "^1.6.0",
    "bare-fs": "^4.7.1",
    "bare-path": "^3.0.1",
    "bare-process": "^4.2.1",
    "blind-pairing": "^2.3.1",
    "compact-encoding": "^2.16.0",
    "corestore": "^7.10.0",
    "hypercore": "^11.33.1",
    "hypercore-crypto": "^3.0.0",
    "hyperdb": "^6.7.0",
    "hyperdispatch": "^1.6.0",
    "hyperschema": "^1.21.0",
    "hyperswarm": "^4.17.0",
    "keet-identity-key": "^3.2.0",
    "multiformats": "^13.4.2",
    "protomux": "^3.11.0",
    "protomux-rpc": "^1.10.0"
  },
  "devDependencies": {
    "@hyperswarm/testnet": "^3.1.4",
    "@noble/curves": "^1.6.0",
    "brittle": "^4.0.2"
  }
}
function isBuffer(value) {
  return Buffer.isBuffer(value) || value instanceof Uint8Array
}

function isEncoding(encoding) {
  return Buffer.isEncoding(encoding)
}

function alloc(size, fill, encoding) {
  return Buffer.alloc(size, fill, encoding)
}

function allocUnsafe(size) {
  return Buffer.allocUnsafe(size)
}

function allocUnsafeSlow(size) {
  return Buffer.allocUnsafeSlow(size)
}

function byteLength(string, encoding) {
  return Buffer.byteLength(string, encoding)
}

function compare(a, b) {
  return Buffer.compare(a, b)
}

function concat(buffers, totalLength) {
  return Buffer.concat(buffers, totalLength)
}

function copy(source, target, targetStart, start, end) {
  return toBuffer(source).copy(target, targetStart, start, end)
}

function equals(a, b) {
  return toBuffer(a).equals(b)
}

function fill(buffer, value, offset, end, encoding) {
  return toBuffer(buffer).fill(value, offset, end, encoding)
}

function from(value, encodingOrOffset, length) {
  return Buffer.from(value, encodingOrOffset, length)
}

function includes(buffer, value, byteOffset, encoding) {
  return toBuffer(buffer).includes(value, byteOffset, encoding)
}

function indexOf(buffer, value, byfeOffset, encoding) {
  return toBuffer(buffer).indexOf(value, byfeOffset, encoding)
}

function lastIndexOf(buffer, value, byteOffset, encoding) {
  return toBuffer(buffer).lastIndexOf(value, byteOffset, encoding)
}

function swap16(buffer) {
  return toBuffer(buffer).swap16()
}

function swap32(buffer) {
  return toBuffer(buffer).swap32()
}

function swap64(buffer) {
  return toBuffer(buffer).swap64()
}

function toBuffer(buffer) {
  if (Buffer.isBuffer(buffer)) return buffer
  return Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

function toString(buffer, encoding, start, end) {
  return toBuffer(buffer).toString(encoding, start, end)
}

function write(buffer, string, offset, length, encoding) {
  return toBuffer(buffer).write(string, offset, length, encoding)
}

function readDoubleBE(buffer, offset) {
  return toBuffer(buffer).readDoubleBE(offset)
}

function readDoubleLE(buffer, offset) {
  return toBuffer(buffer).readDoubleLE(offset)
}

function readFloatBE(buffer, offset) {
  return toBuffer(buffer).readFloatBE(offset)
}

function readFloatLE(buffer, offset) {
  return toBuffer(buffer).readFloatLE(offset)
}

function readInt32BE(buffer, offset) {
  return toBuffer(buffer).readInt32BE(offset)
}

function readInt32LE(buffer, offset) {
  return toBuffer(buffer).readInt32LE(offset)
}

function readUInt32BE(buffer, offset) {
  return toBuffer(buffer).readUInt32BE(offset)
}

function readUInt32LE(buffer, offset) {
  return toBuffer(buffer).readUInt32LE(offset)
}

function writeDoubleBE(buffer, value, offset) {
  return toBuffer(buffer).writeDoubleBE(value, offset)
}

function writeDoubleLE(buffer, value, offset) {
  return toBuffer(buffer).writeDoubleLE(value, offset)
}

function writeFloatBE(buffer, value, offset) {
  return toBuffer(buffer).writeFloatBE(value, offset)
}

function writeFloatLE(buffer, value, offset) {
  return toBuffer(buffer).writeFloatLE(value, offset)
}

function writeInt32BE(buffer, value, offset) {
  return toBuffer(buffer).writeInt32BE(value, offset)
}

function writeInt32LE(buffer, value, offset) {
  return toBuffer(buffer).writeInt32LE(value, offset)
}

function writeUInt32BE(buffer, value, offset) {
  return toBuffer(buffer).writeUInt32BE(value, offset)
}

function writeUInt32LE(buffer, value, offset) {
  return toBuffer(buffer).writeUInt32LE(value, offset)
}

module.exports = {
  isBuffer,
  isEncoding,
  alloc,
  allocUnsafe,
  allocUnsafeSlow,
  byteLength,
  compare,
  concat,
  copy,
  equals,
  fill,
  from,
  includes,
  indexOf,
  lastIndexOf,
  swap16,
  swap32,
  swap64,
  toBuffer,
  toString,
  write,
  readDoubleBE,
  readDoubleLE,
  readFloatBE,
  readFloatLE,
  readInt32BE,
  readInt32LE,
  readUInt32BE,
  readUInt32LE,
  writeDoubleBE,
  writeDoubleLE,
  writeFloatBE,
  writeFloatLE,
  writeInt32BE,
  writeInt32LE,
  writeUInt32BE,
  writeUInt32LE
}
{
  "name": "b4a",
  "version": "1.8.1",
  "description": "Bridging the gap between buffers and typed arrays",
  "exports": {
    "./package": "./package.json",
    ".": {
      "react-native": "./react-native.js",
      "browser": "./browser.js",
      "default": "./index.js"
    }
  },
  "files": [
    "browser.js",
    "index.js",
    "react-native.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:bare && npm run test:node",
    "test:bare": "brittle-bare --coverage test.mjs",
    "test:node": "brittle-node --coverage test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/b4a.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/b4a/issues"
  },
  "homepage": "https://github.com/holepunchto/b4a#readme",
  "devDependencies": {
    "brittle": "^3.5.2",
    "lunte": "^1.7.0",
    "nanobench": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "react-native-b4a": "*"
  },
  "peerDependenciesMeta": {
    "react-native-b4a": {
      "optional": true
    }
  }
}
const ESC = '\x1b'
const CSI = ESC + '['
const SGR = (n) => CSI + n + 'm'

exports.constants = {
  ESC,
  CSI,
  SGR
}

// https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_(Control_Sequence_Introducer)_sequences

exports.cursorHide = CSI + '?25l'
exports.cursorShow = CSI + '?25h'

exports.cursorUp = function cursorUp(n = 1) {
  return CSI + n + 'A'
}

exports.cursorDown = function cursorDown(n = 1) {
  return CSI + n + 'B'
}

exports.cursorForward = function cursorForward(n = 1) {
  return CSI + n + 'C'
}

exports.cursorBack = function cursorBack(n = 1) {
  return CSI + n + 'D'
}

exports.cursorNextLine = function cursorNextLine(n = 1) {
  return CSI + n + 'E'
}

exports.cursorPreviousLine = function cursorPreviousLine(n = 1) {
  return CSI + n + 'F'
}

exports.cursorPosition = function cursorPosition(column, row = 0) {
  if (row === 0) return CSI + (column + 1) + 'G'

  return CSI + (row + 1) + ';' + (column + 1) + 'H'
}

exports.eraseDisplayEnd = CSI + 'J'
exports.eraseDisplayStart = CSI + '1J'
exports.eraseDisplay = CSI + '2J'
exports.eraseLineEnd = CSI + 'K'
exports.eraseLineStart = CSI + '1K'
exports.eraseLine = CSI + '2K'

exports.scrollUp = function scrollUp(n = 1) {
  return CSI + n + 'S'
}

exports.scrollDown = function scrollDown(n = 1) {
  return CSI + n + 'T'
}

// https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_(Select_Graphic_Rendition)_parameters

exports.modifierReset = SGR(0)
exports.modifierBold = SGR(1)
exports.modifierDim = SGR(2)
exports.modifierItalic = SGR(3)
exports.modifierUnderline = SGR(4)
exports.modifierNormal = SGR(22)
exports.modifierNotItalic = SGR(23)
exports.modifierNotUnderline = SGR(24)

// https://en.wikipedia.org/wiki/ANSI_escape_code#Colors

exports.colorBlack = SGR(30)
exports.colorRed = SGR(31)
exports.colorGreen = SGR(32)
exports.colorYellow = SGR(33)
exports.colorBlue = SGR(34)
exports.colorMagenta = SGR(35)
exports.colorCyan = SGR(36)
exports.colorWhite = SGR(37)
exports.colorDefault = SGR(39)
exports.colorBrightBlack = SGR(90)
exports.colorBrightRed = SGR(91)
exports.colorBrightGreen = SGR(92)
exports.colorBrightYellow = SGR(93)
exports.colorBrightBlue = SGR(94)
exports.colorBrightMagenta = SGR(95)
exports.colorBrightCyan = SGR(96)
exports.colorBrightWhite = SGR(97)
{
  "name": "bare-ansi-escapes",
  "version": "2.2.3",
  "description": "Parse and produce ANSI escape sequences",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./key-decoder": {
      "types": "./key-decoder.d.ts",
      "default": "./key-decoder.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "key-decoder.js",
    "key-decoder.d.ts"
  ],
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-ansi-escapes.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-ansi-escapes/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-ansi-escapes#readme",
  "dependencies": {
    "bare-stream": "^2.6.5"
  },
  "devDependencies": {
    "bare-buffer": "^3.0.2",
    "brittle": "^3.3.2",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  },
  "peerDependencies": {
    "bare-buffer": "*"
  },
  "peerDependenciesMeta": {
    "bare-buffer": {
      "optional": true
    }
  }
}
const inspect = require('bare-inspect')

class AssertionError extends Error {
  constructor(opts = {}) {
    let { message = null, actual, expected, operator } = opts

    if (message === null) {
      message = `${inspect(actual)} ${operator} ${inspect(expected)}`
    }

    super(message)

    this.actual = actual
    this.expected = expected
    this.operator = operator
  }

  get name() {
    return 'AssertionError'
  }

  get code() {
    'ASSERTION'
  }
}

function assertFail(opts, fn) {
  if (opts.message instanceof Error) throw opts.message

  const err = new AssertionError(opts)

  if (Error.captureStackTrace) Error.captureStackTrace(err, fn)

  throw err
}

module.exports = exports = function assert(actual, message) {
  if (actual) return

  assertFail({ message, actual, expected: true, operator: '==' }, assert)
}

exports.AssertionError = AssertionError

exports.fail = function fail(message) {
  if (message === undefined) message = 'Failed'

  assertFail({ message, operator: 'fail' }, fail)
}

exports.ok = function ok(actual, message) {
  if (actual) return

  assertFail({ message, actual, expected: true, operator: '==' }, ok)
}

exports.notOk = function ok(actual, message) {
  if (!actual) return

  assertFail({ message, actual, expected: false, operator: '==' }, ok)
}

exports.equal = function equal(actual, expected, message) {
  if (actual == expected || (actual !== actual && expected !== expected)) {
    return
  }

  assertFail({ message, actual, expected, operator: '==' }, equal)
}

exports.notEqual = function notEqual(actual, expected, message) {
  if (actual != expected && (actual === actual || expected === expected)) {
    return
  }

  assertFail({ message, actual, expected, operator: '!=' }, notEqual)
}

exports.strictEqual = function strictEqual(actual, expected, message) {
  if (Object.is(actual, expected)) return

  assertFail(
    { message, actual, expected, operator: 'strictEqual' },
    strictEqual
  )
}

exports.notStrictEqual = function notStrictEqual(actual, expected, message) {
  if (!Object.is(actual, expected)) return

  assertFail(
    { message, actual, expected, operator: 'notStrictEqual' },
    notStrictEqual
  )
}
{
  "name": "bare-assert",
  "version": "1.2.0",
  "description": "Assertion library for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts"
  ],
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-assert.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-assert/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-assert#readme",
  "dependencies": {
    "bare-inspect": "^3.1.2"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  }
}
const errors = require('./lib/errors')

class EventListener {
  constructor() {
    this.list = []
    this.count = 0
  }

  append(ctx, name, fn, once) {
    this.count++
    ctx.emit('newListener', name, fn) // Emit BEFORE adding
    this.list.push([fn, once])
  }

  prepend(ctx, name, fn, once) {
    this.count++
    ctx.emit('newListener', name, fn) // Emit BEFORE adding
    this.list.unshift([fn, once])
  }

  remove(ctx, name, fn) {
    for (let i = 0, n = this.list.length; i < n; i++) {
      const l = this.list[i]

      if (l[0] === fn) {
        this.list.splice(i, 1)

        if (this.count === 1) delete ctx._events[name]

        ctx.emit('removeListener', name, fn) // Emit AFTER removing

        this.count--
        return
      }
    }
  }

  removeAll(ctx, name) {
    const list = [...this.list]
    this.list = []

    if (this.count === list.length) delete ctx._events[name]

    for (let i = list.length - 1; i >= 0; i--) {
      ctx.emit('removeListener', name, list[i][0]) // Emit AFTER removing
    }

    this.count -= list.length
  }

  emit(ctx, name, ...args) {
    const list = [...this.list]

    for (let i = 0, n = list.length; i < n; i++) {
      const l = list[i]

      if (l[1] === true) this.remove(ctx, name, l[0])

      Reflect.apply(l[0], ctx, args)
    }

    return list.length > 0
  }
}

function appendListener(ctx, name, fn, once) {
  if (ctx._events === undefined) ctx._events = Object.create(null)
  const e = ctx._events[name] || (ctx._events[name] = new EventListener())
  e.append(ctx, name, fn, once)
  return ctx
}

function prependListener(ctx, name, fn, once) {
  if (ctx._events === undefined) ctx._events = Object.create(null)
  const e = ctx._events[name] || (ctx._events[name] = new EventListener())
  e.prepend(ctx, name, fn, once)
  return ctx
}

function removeListener(ctx, name, fn) {
  if (ctx._events === undefined) return ctx
  const e = ctx._events[name]
  if (e !== undefined) e.remove(ctx, name, fn)
  return ctx
}

function throwUnhandledError(...args) {
  let err

  if (args.length > 0) err = args[0]

  if (err instanceof Error === false) err = errors.UNHANDLED_ERROR(err)

  if (Error.captureStackTrace) {
    Error.captureStackTrace(err, exports.prototype.emit)
  }

  queueMicrotask(() => {
    throw err
  })
}

module.exports = exports = class EventEmitter {
  constructor() {
    this._events = Object.create(null)
  }

  addListener(name, fn) {
    return appendListener(this, name, fn, false)
  }

  addOnceListener(name, fn) {
    return appendListener(this, name, fn, true)
  }

  prependListener(name, fn) {
    return prependListener(this, name, fn, false)
  }

  prependOnceListener(name, fn) {
    return prependListener(this, name, fn, true)
  }

  removeListener(name, fn) {
    return removeListener(this, name, fn)
  }

  on(name, fn) {
    return appendListener(this, name, fn, false)
  }

  once(name, fn) {
    return appendListener(this, name, fn, true)
  }

  off(name, fn) {
    return removeListener(this, name, fn)
  }

  emit(name, ...args) {
    if (name === 'error' && this._events !== undefined && this._events.error === undefined) {
      throwUnhandledError(...args)
    }

    if (this._events === undefined) return false
    const e = this._events[name]
    return e === undefined ? false : e.emit(this, name, ...args)
  }

  listeners(name) {
    if (this._events === undefined) return []
    const e = this._events[name]
    return e === undefined ? [] : [...e.list]
  }

  rawListeners(name) {
    if (this._events === undefined) return []
    const e = this._events[name]
    return e === undefined ? [] : e.list.map((l) => l[0])
  }

  eventNames() {
    if (this._events === undefined) return []
    return Reflect.ownKeys(this._events)
  }

  listenerCount(name) {
    if (this._events === undefined) return 0
    const e = this._events[name]
    return e === undefined ? 0 : e.list.length
  }

  getMaxListeners() {
    return EventEmitter.defaultMaxListeners
  }

  setMaxListeners(n) {}

  removeAllListeners(name) {
    if (arguments.length === 0) {
      for (const key of Reflect.ownKeys(this._events)) {
        if (key === 'removeListener') continue
        this.removeAllListeners(key)
      }
      this.removeAllListeners('removeListener')
    } else {
      const e = this._events[name]
      if (e !== undefined) e.removeAll(this, name)
    }
    return this
  }
}

exports.EventEmitter = exports

exports.errors = errors

exports.defaultMaxListeners = 10

exports.on = function on(emitter, name, opts = {}) {
  const { signal } = opts

  if (signal && signal.aborted) {
    throw errors.OPERATION_ABORTED(signal.reason)
  }

  let error = null
  let done = false

  const events = []
  const promises = []

  if (name !== 'error') emitter.on('error', onerror)

  if (signal) signal.addEventListener('abort', onabort)

  emitter.on(name, onevent)

  return {
    next() {
      if (events.length) {
        return Promise.resolve({ value: events.shift(), done: false })
      }

      if (error) {
        const err = error

        error = null

        return Promise.reject(err)
      }

      if (done) return onclose()

      return new Promise((resolve, reject) => promises.push({ resolve, reject }))
    },

    return() {
      return onclose()
    },

    throw(err) {
      return onerror(err)
    },

    [Symbol.asyncIterator]() {
      return this
    }
  }

  function onevent(...args) {
    if (promises.length) {
      promises.shift().resolve({ value: args, done: false })
    } else {
      events.push(args)
    }
  }

  function onerror(err) {
    emitter.off(name, onevent).off('error', onerror)

    if (promises.length) {
      promises.shift().reject(err)
    } else {
      error = err
    }

    return Promise.resolve({ done: true })
  }

  function onabort() {
    signal.removeEventListener('abort', onabort)

    onerror(errors.OPERATION_ABORTED(signal.reason))
  }

  function onclose() {
    emitter.off(name, onevent)

    if (name !== 'error') emitter.off('error', onerror)

    if (signal) signal.removeEventListener('abort', onabort)

    done = true

    if (promises.length) promises.shift().resolve({ done: true })

    return Promise.resolve({ done: true })
  }
}

exports.once = function once(emitter, name, opts = {}) {
  const { signal } = opts

  if (signal && signal.aborted) {
    return Promise.reject(errors.OPERATION_ABORTED(signal.reason))
  }

  return new Promise((resolve, reject) => {
    if (name !== 'error') emitter.on('error', onerror)

    if (signal) signal.addEventListener('abort', onabort)

    emitter.once(name, onevent)

    function onevent(...args) {
      if (name !== 'error') emitter.off('error', onerror)

      if (signal) signal.removeEventListener('abort', onabort)

      resolve(args)
    }

    function onerror(err) {
      emitter.off(name, onevent)

      if (name !== 'error') emitter.off('error', onerror)

      reject(err)
    }

    function onabort() {
      signal.removeEventListener('abort', onabort)

      onerror(errors.OPERATION_ABORTED(signal.reason))
    }
  })
}

exports.forward = function forward(from, to, names, opts = {}) {
  if (typeof names === 'string') names = [names]

  const { emit = to.emit.bind(to) } = opts

  const listeners = names.map(
    (name) =>
      function onevent(...args) {
        emit(name, ...args)
      }
  )

  to.on('newListener', (name) => {
    const i = names.indexOf(name)

    if (i !== -1 && to.listenerCount(name) === 0) {
      from.on(name, listeners[i])
    }
  }).on('removeListener', (name) => {
    const i = names.indexOf(name)

    if (i !== -1 && to.listenerCount(name) === 0) {
      from.off(name, listeners[i])
    }
  })
}

exports.listenerCount = function listenerCount(emitter, name) {
  return emitter.listenerCount(name)
}

exports.getMaxListeners = function getMaxListeners(emitter) {
  if (typeof emitter.getMaxListeners === 'function') {
    return emitter.getMaxListeners()
  }

  return exports.defaultMaxListeners
}

exports.setMaxListeners = function setMaxListeners(n, ...emitters) {
  if (emitters.length === 0) exports.defaultMaxListeners = n
  else {
    for (const emitter of emitters) {
      if (typeof emitter.setMaxListeners === 'function') {
        emitter.setMaxListeners(n)
      }
    }
  }
}
module.exports = class EventEmitterError extends Error {
  constructor(msg, code, fn = EventEmitterError, opts) {
    super(`${code}: ${msg}`, opts)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'EventEmitterError'
  }

  static OPERATION_ABORTED(cause, msg = 'Operation aborted') {
    return new EventEmitterError(msg, 'OPERATION_ABORTED', EventEmitterError.OPERATION_ABORTED, {
      cause
    })
  }

  static UNHANDLED_ERROR(cause, msg = 'Unhandled error') {
    return new EventEmitterError(msg, 'UNHANDLED_ERROR', EventEmitterError.UNHANDLED_ERROR, {
      cause
    })
  }
}
{
  "name": "bare-events",
  "version": "2.9.1",
  "description": "Event emitters for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    },
    "./web": {
      "types": "./web.d.ts",
      "default": "./web.js"
    },
    "./errors": "./lib/errors.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "global.js",
    "global.d.ts",
    "web.js",
    "web.d.ts",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:bare && npm run test:node",
    "test:bare": "brittle-bare --coverage test.js",
    "test:node": "brittle-node --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-events.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-events/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-events#readme",
  "devDependencies": {
    "bare-abort-controller": "^1.0.0",
    "brittle": "^3.3.2",
    "lunte": "^1.8.0",
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^2.0.0",
    "uncaughts": "^1.1.1"
  },
  "peerDependencies": {
    "bare-abort-controller": "*"
  },
  "peerDependenciesMeta": {
    "bare-abort-controller": {
      "optional": true
    }
  }
}
module.exports = require.addon()
const FIFO = require('fast-fifo')
const EventEmitter = require('bare-events')
const path = require('bare-path')
const { isURL, fileURLToPath } = require('bare-url')
const { Readable, Writable } = require('bare-stream')
const binding = require('./binding')
const constants = require('./lib/constants')
const FileError = require('./lib/errors')

const isWindows = Bare.platform === 'win32'

exports.constants = constants

class FileRequest {
  static borrow() {
    if (this._free.length > 0) return this._free.pop()
    return new FileRequest()
  }

  static return(req) {
    if (this._free.length < 32) this._free.push(req.reset())
    else req.destroy()
  }

  constructor() {
    this._reset()
    this._handle = binding.requestInit(this, this._onresult)
  }

  get handle() {
    return this._handle
  }

  retain(value) {
    this._retain = value // Tie the lifetime of `value` to the lifetime of `this`
  }

  reset() {
    if (this._handle === null) return this

    binding.requestReset(this._handle)

    this._reset()

    return this
  }

  destroy() {
    if (this._handle === null) return this

    binding.requestDestroy(this._handle)

    this._reset()
    this._handle = null

    return this
  }

  then(resolve, reject) {
    return this._promise.then(resolve, reject)
  }

  return() {
    if (this._handle === null) return this

    FileRequest.return(this)

    return this
  }

  _reset() {
    this._promise = new Promise((resolve, reject) => {
      this._resolve = resolve
      this._reject = reject
    })
    this._retain = null
  }

  _onresult(err, status) {
    if (err) this._reject(err)
    else this._resolve(status)
  }
}

FileRequest._free = []

function ok(result, cb) {
  if (typeof result === 'function') {
    cb = result
    result = undefined
  }

  if (cb) cb(null, result)
  else return result
}

function fail(err, cb) {
  if (cb) cb(err)
  else throw err
}

function done(err, result, cb) {
  if (typeof result === 'function') {
    cb = result
    result = undefined
  }

  if (err) fail(err, cb)
  else return ok(result, cb)
}

async function open(filepath, flags = 'r', mode = 0o666, cb) {
  if (typeof flags === 'function') {
    cb = flags
    flags = 'r'
    mode = 0o666
  } else if (typeof mode === 'function') {
    cb = mode
    mode = 0o666
  }

  if (typeof flags === 'string') flags = toFlags(flags)
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let fd
  let err = null
  try {
    binding.open(req.handle, filepath, flags, mode)

    fd = await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'open',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, fd, cb)
}

function openSync(filepath, flags = 'r', mode = 0o666) {
  if (typeof flags === 'string') flags = toFlags(flags)
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    return binding.openSync(req.handle, filepath, flags, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'open',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function close(fd, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.close(req.handle, fd)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'close', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function closeSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.closeSync(req.handle, fd)
  } catch (e) {
    throw new FileError(e.message, { operation: 'close', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function access(filepath, mode = constants.F_OK, cb) {
  if (typeof mode === 'function') {
    cb = mode
    mode = constants.F_OK
  }

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.access(req.handle, filepath, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'access',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function accessSync(filepath, mode = constants.F_OK) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.accessSync(req.handle, filepath, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'access',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function exists(filepath, cb) {
  let ok = true
  try {
    await access(filepath)
  } catch {
    ok = false
  }

  return done(null, ok, cb)
}

function existsSync(filepath) {
  try {
    accessSync(filepath)
  } catch {
    return false
  }

  return true
}

async function read(fd, buffer, offset = 0, len = buffer.byteLength - offset, pos = -1, cb) {
  if (typeof offset === 'function') {
    cb = offset
    offset = 0
    len = buffer.byteLength
    pos = -1
  } else if (typeof len === 'function') {
    cb = len
    len = buffer.byteLength - offset
    pos = -1
  } else if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.read(req.handle, fd, buffer, offset, len, pos)

    req.retain(buffer)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'read', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function readSync(fd, buffer, offset = 0, len = buffer.byteLength - offset, pos = -1) {
  const req = FileRequest.borrow()

  try {
    return binding.readSync(req.handle, fd, buffer, offset, len, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'read', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function readv(fd, buffers, pos = -1, cb) {
  if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.readv(req.handle, fd, buffers, pos)

    req.retain(buffers)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'readv', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function readvSync(fd, buffers, pos = -1) {
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  try {
    return binding.readvSync(req.handle, fd, buffers, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'readv', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function write(fd, data, offset, len, pos = -1, cb) {
  if (typeof data === 'string') {
    let encoding = len
    cb = pos
    pos = offset

    if (typeof pos === 'function') {
      cb = pos
      pos = -1
      encoding = 'utf8'
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = 'utf8'
    }

    if (typeof pos === 'string') {
      encoding = pos
      pos = -1
    }

    data = Buffer.from(data, encoding)
    offset = 0
    len = data.byteLength
  } else if (typeof offset === 'function') {
    cb = offset
    offset = 0
    len = data.byteLength
    pos = -1
  } else if (typeof len === 'function') {
    cb = len
    len = data.byteLength - offset
    pos = -1
  } else if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof offset !== 'number') offset = 0
  if (typeof len !== 'number') len = data.byteLength - offset
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.write(req.handle, fd, data, offset, len, pos)

    req.retain(data)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'write', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function writeSync(fd, data, offset, len, pos = -1) {
  if (typeof data === 'string') {
    let encoding = len
    pos = offset

    if (typeof pos === 'string') {
      encoding = pos
      pos = -1
    }

    data = Buffer.from(data, encoding)
    offset = 0
    len = data.byteLength
  }

  if (typeof offset !== 'number') offset = 0
  if (typeof len !== 'number') len = data.byteLength - offset
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  try {
    return binding.writeSync(req.handle, fd, data, offset, len, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'write', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function writev(fd, buffers, pos = -1, cb) {
  if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.writev(req.handle, fd, buffers, pos)

    req.retain(buffers)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'writev', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function writevSync(fd, buffers, pos = -1) {
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  try {
    return binding.writevSync(req.handle, fd, buffers, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'writev', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function stat(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.stat(req.handle, filepath)

    await req

    st = new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'stat', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function statSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.statSync(req.handle, filepath)

    return new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'stat', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function lstat(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.lstat(req.handle, filepath)

    await req

    st = new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'lstat', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function lstatSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.lstatSync(req.handle, filepath)

    return new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'lstat', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function fstat(fd, cb) {
  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.fstat(req.handle, fd)

    await req

    st = new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'fstat', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function fstatSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.fstatSync(req.handle, fd)

    return new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'fstat', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function statfs(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.statfs(req.handle, filepath)

    await req

    st = new StatFs(...binding.requestResultStatfs(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'statfs', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function statfsSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.statfsSync(req.handle, filepath)

    return new StatFs(...binding.requestResultStatfs(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'statfs', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function ftruncate(fd, len = 0, cb) {
  if (typeof len === 'function') {
    cb = len
    len = 0
  }

  if (typeof len !== 'number') len = 0

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.ftruncate(req.handle, fd, len)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'ftruncate', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function ftruncateSync(fd, len = 0) {
  if (typeof len !== 'number') len = 0

  const req = FileRequest.borrow()

  try {
    binding.ftruncateSync(req.handle, fd, len)
  } catch (e) {
    throw new FileError(e.message, { operation: 'ftruncate', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function truncate(filepath, len, cb) {
  let fd = -1
  let err

  try {
    fd = await open(filepath, 'r+')

    await ftruncate(fd, len)
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) await close(fd)
  }

  return done(err, cb)
}

function truncateSync(filepath, len) {
  let fd = -1
  let err

  try {
    fd = openSync(filepath, 'r+')

    ftruncateSync(fd, len)
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) closeSync(fd)
  }
}

async function chmod(filepath, mode, cb) {
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.chmod(req.handle, filepath, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'chmod',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function chmodSync(filepath, mode) {
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.chmodSync(req.handle, filepath, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'chmod',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function fchmod(fd, mode, cb) {
  if (typeof mode === 'string') mode = toMode(mode)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fchmod(req.handle, fd, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fchmod', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fchmodSync(fd, mode) {
  if (typeof mode === 'string') mode = toMode(mode)

  const req = FileRequest.borrow()

  try {
    binding.fchmodSync(req.handle, fd, mode)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fchmod', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function chown(filepath, uid, gid, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.chown(req.handle, filepath, uid, gid)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'chown', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function chownSync(filepath, uid, gid) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.chownSync(req.handle, filepath, uid, gid)
  } catch (e) {
    throw new FileError(e.message, { operation: 'chownSync', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function lchown(filepath, uid, gid, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.lchown(req.handle, filepath, uid, gid)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'lchown', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function lchownSync(filepath, uid, gid) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.lchownSync(req.handle, filepath, uid, gid)
  } catch (e) {
    throw new FileError(e.message, { operation: 'lchownSync', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function fchown(fd, uid, gid, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fchown(req.handle, fd, uid, gid)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fchown', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fchownSync(fd, uid, gid) {
  const req = FileRequest.borrow()

  try {
    binding.fchownSync(req.handle, fd, uid, gid)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fchownSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function utimes(filepath, atime, mtime, cb) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.utimes(req.handle, filepath, atime, mtime)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'utimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function utimesSync(filepath, atime, mtime) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.utimesSync(req.handle, filepath, atime, mtime)
  } catch (e) {
    throw new FileError(e.message, { operation: 'utimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function lutimes(filepath, atime, mtime, cb) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.lutimes(req.handle, filepath, atime, mtime)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'lutimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function lutimesSync(filepath, atime, mtime) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.lutimesSync(req.handle, filepath, atime, mtime)
  } catch (e) {
    throw new FileError(e.message, { operation: 'lutimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function futimes(fd, atime, mtime, cb) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.futimes(req.handle, fd, atime, mtime)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'futimes', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function futimesSync(fd, atime, mtime) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  const req = FileRequest.borrow()

  try {
    binding.futimesSync(req.handle, fd, atime, mtime)
  } catch (e) {
    throw new FileError(e.message, { operation: 'futimesSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function link(src, dst, cb) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.link(req.handle, src, dst)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'link', code: e.code, path: src, destination: dst })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function linkSync(src, dst) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  try {
    binding.linkSync(req.handle, src, dst)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'linkSync',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }
}

async function mkdir(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = { mode: 0o777 }
  }

  if (typeof opts === 'number') opts = { mode: opts }
  else if (!opts) opts = {}

  const mode = typeof opts.mode === 'number' ? opts.mode : 0o777

  filepath = toNamespacedPath(filepath)

  if (opts.recursive) {
    let err = null
    try {
      try {
        await mkdir(filepath, { mode })
      } catch (err) {
        if (err.code !== 'ENOENT') {
          if (!(await stat(filepath)).isDirectory()) throw err
        } else {
          while (filepath.endsWith(path.sep)) filepath = filepath.slice(0, -1)
          const i = filepath.lastIndexOf(path.sep)
          if (i <= 0) throw err

          await mkdir(filepath.slice(0, i), { mode, recursive: true })

          try {
            await mkdir(filepath, { mode })
          } catch (err) {
            if (!(await stat(filepath)).isDirectory()) throw err
          }
        }
      }
    } catch (e) {
      err = e
    }

    return done(err, cb)
  }

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.mkdir(req.handle, filepath, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'mkdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function mkdirSync(filepath, opts) {
  if (typeof opts === 'number') opts = { mode: opts }
  else if (!opts) opts = {}

  const mode = typeof opts.mode === 'number' ? opts.mode : 0o777

  filepath = toNamespacedPath(filepath)

  if (opts.recursive) {
    try {
      mkdirSync(filepath, { mode })
    } catch (err) {
      if (err.code !== 'ENOENT') {
        if (!statSync(filepath).isDirectory()) throw err
      } else {
        while (filepath.endsWith(path.sep)) filepath = filepath.slice(0, -1)
        const i = filepath.lastIndexOf(path.sep)
        if (i <= 0) throw err

        mkdirSync(filepath.slice(0, i), { mode, recursive: true })

        try {
          mkdirSync(filepath, { mode })
        } catch (err) {
          if (!statSync(filepath).isDirectory()) throw err
        }
      }
    }

    return
  }

  const req = FileRequest.borrow()

  try {
    binding.mkdirSync(req.handle, filepath, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'mkdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function mkdtemp(prefix, cb) {
  prefix = toNamespacedPath(prefix)

  const req = FileRequest.borrow()

  let res
  let err = null
  try {
    binding.mkdtemp(req.handle, prefix + 'XXXXXX')

    await req

    res = binding.requestResultPath(req.handle)
  } catch (e) {
    err = new FileError(e.message, { operation: 'mkdtemp', code: e.code, path: prefix })
  } finally {
    req.return()
  }

  return done(err, res, cb)
}

function mkdtempSync(prefix) {
  prefix = toNamespacedPath(prefix)

  const req = FileRequest.borrow()

  try {
    binding.mkdtempSync(req.handle, prefix + 'XXXXXX')

    return binding.requestResultPath(req.handle)
  } catch (e) {
    throw new FileError(e.message, { operation: 'mkdtempSync', code: e.code, path: prefix })
  } finally {
    req.return()
  }
}

async function rmdir(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.rmdir(req.handle, filepath)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'rmdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function rmdirSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.rmdirSync(req.handle, filepath)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'rmdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function rm(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  let err = null
  try {
    const st = await lstat(filepath)

    if (st.isDirectory()) {
      if (opts.recursive) {
        try {
          await rmdir(filepath)
        } catch (err) {
          if (err.code !== 'ENOTEMPTY') throw err

          const files = await readdir(filepath)

          for (const file of files) {
            await rm(filepath + path.sep + file, opts)
          }

          await rmdir(filepath)
        }
      } else {
        throw new FileError('is a directory', {
          operation: 'rm',
          code: 'EISDIR',
          path: filepath
        })
      }
    } else {
      await unlink(filepath)
    }
  } catch (e) {
    if (e.code !== 'ENOENT' || !opts.force) err = e
  }

  return done(err, cb)
}

function rmSync(filepath, opts) {
  if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  try {
    const st = lstatSync(filepath)

    if (st.isDirectory()) {
      if (opts.recursive) {
        try {
          rmdirSync(filepath)
        } catch (err) {
          if (err.code !== 'ENOTEMPTY') throw err

          const files = readdirSync(filepath)

          for (const file of files) {
            rmSync(filepath + path.sep + file, opts)
          }

          rmdirSync(filepath)
        }
      } else {
        throw new FileError('is a directory', {
          operation: 'rm',
          code: 'EISDIR',
          path: filepath
        })
      }
    } else {
      unlinkSync(filepath)
    }
  } catch (err) {
    if (err.code !== 'ENOENT' || !opts.force) throw err
  }
}

async function unlink(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.unlink(req.handle, filepath)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'unlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function unlinkSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.unlinkSync(req.handle, filepath)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'unlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function rename(src, dst, cb) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.rename(req.handle, src, dst)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'rename',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function renameSync(src, dst) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  try {
    binding.renameSync(req.handle, src, dst)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'rename',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }
}

async function copyFile(src, dst, mode = 0, cb) {
  if (typeof mode === 'function') {
    cb = mode
    mode = 0
  }

  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.copyfile(req.handle, src, dst, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'copyfile',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function copyFileSync(src, dst, mode = 0) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  try {
    binding.copyfileSync(req.handle, src, dst, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'copyfile',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }
}

async function cp(src, dst, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (!opts) opts = {}

  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  let err = null
  try {
    const st = await lstat(src)

    if (st.isDirectory()) {
      if (opts.recursive !== true) {
        throw new FileError('is a directory', { operation: 'cp', code: 'EISDIR', path: src })
      }

      try {
        await lstat(dst)
      } catch (e) {
        if (e.code !== 'ENOENT') throw e

        await mkdir(dst, { mode: st.mode, recursive: true })
      }

      const dir = await opendir(src)
      for await (const { name } of dir) {
        await cp(path.join(src, name), path.join(dst, name), opts)
      }
    } else if (st.isFile()) {
      await copyFile(src, dst)
      await chmod(dst, st.mode)
    }
  } catch (e) {
    err = e
  }

  return done(err, cb)
}

function cpSync(src, dst, opts = {}) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const st = lstatSync(src)

  if (st.isDirectory()) {
    if (opts.recursive !== true) {
      throw new FileError('is a directory', { operation: 'cp', code: 'EISDIR', path: src })
    }

    try {
      lstatSync(dst)
    } catch (e) {
      if (e.code !== 'ENOENT') throw e

      mkdirSync(dst, { mode: st.mode, recursive: true })
    }

    const dir = opendirSync(src)
    for (const { name } of dir) {
      cpSync(path.join(src, name), path.join(dst, name), opts)
    }
  } else if (st.isFile()) {
    copyFileSync(src, dst)
    chmodSync(dst, st.mode)
  }
}

async function realpath(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let res
  let err = null
  try {
    binding.realpath(req.handle, filepath)

    await req

    res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'realpath',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, res, cb)
}

function realpathSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.realpathSync(req.handle, filepath)

    let res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)

    return res
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'realpath',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function readlink(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let res
  let err = null
  try {
    binding.readlink(req.handle, filepath)

    await req

    res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'readlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, res, cb)
}

function readlinkSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.readlinkSync(req.handle, filepath)

    let res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)

    return res
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'readlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function fsync(fd, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fsync(req.handle, fd)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fsync', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fsyncSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.fsyncSync(req.handle, fd)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fsyncSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function fdatasync(fd, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fdatasync(req.handle, fd)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fdatasync', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fdatasyncSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.fdatasyncSync(req.handle, fd)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fdatasyncSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

function normalizeSymlinkTarget(target, type, filepath) {
  if (isWindows) {
    if (type === constants.UV_FS_SYMLINK_JUNCTION) target = path.resolve(filepath, '..', target)

    if (path.isAbsolute(target)) return path.toNamespacedPath(target)

    return target.replace(/\//g, path.sep)
  }

  return target
}

async function symlink(target, filepath, type, cb) {
  if (typeof type === 'function') {
    cb = type
    type = null
  }

  filepath = toNamespacedPath(filepath)

  if (typeof type === 'string') {
    switch (type) {
      case 'dir':
        type = constants.UV_FS_SYMLINK_DIR
        break
      case 'junction':
        type = constants.UV_FS_SYMLINK_JUNCTION
        break
      case 'file':
      default:
        type = 0
        break
    }
  } else if (typeof type !== 'number') {
    if (isWindows) {
      target = path.resolve(filepath, '..', target)

      try {
        type = (await stat(target)).isDirectory()
          ? constants.UV_FS_SYMLINK_DIR
          : constants.UV_FS_SYMLINK_JUNCTION
      } catch {
        type = 0
      }
    } else {
      type = 0
    }
  }

  target = normalizeSymlinkTarget(target, type, filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.symlink(req.handle, target, filepath, type)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'symlink',
      code: e.code,
      path: target,
      destination: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function symlinkSync(target, filepath, type) {
  filepath = toNamespacedPath(filepath)

  if (typeof type === 'string') {
    switch (type) {
      case 'dir':
        type = constants.UV_FS_SYMLINK_DIR
        break
      case 'junction':
        type = constants.UV_FS_SYMLINK_JUNCTION
        break
      case 'file':
      default:
        type = 0
        break
    }
  } else if (typeof type !== 'number') {
    if (isWindows) {
      target = path.resolve(filepath, '..', target)

      try {
        type = statSync(target).isDirectory()
          ? constants.UV_FS_SYMLINK_DIR
          : constants.UV_FS_SYMLINK_JUNCTION
      } catch {
        type = 0
      }
    } else {
      type = 0
    }
  }

  target = normalizeSymlinkTarget(target, type, filepath)

  const req = FileRequest.borrow()

  try {
    binding.symlinkSync(req.handle, target, filepath, type)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'symlink',
      code: e.code,
      path: target,
      destination: filepath
    })
  } finally {
    req.return()
  }
}

async function opendir(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let dir
  let err = null
  try {
    binding.opendir(req.handle, filepath)

    await req

    dir = new Dir(filepath, binding.requestResultDir(req.handle), opts)
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'opendir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, dir, cb)
}

function opendirSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.opendirSync(req.handle, filepath)

    return new Dir(filepath, binding.requestResultDir(req.handle), opts)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'opendir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function readdir(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { withFileTypes = false, recursive = false } = opts

  filepath = toNamespacedPath(filepath)

  const queue = [filepath]
  let result = []
  let err = null
  try {
    while (queue.length !== 0) {
      const dir = await opendir(queue.pop())

      for await (const entry of dir) {
        const entryPath = path.join(entry.parentPath, entry.name)

        if (withFileTypes) {
          result.push(entry)
        } else {
          result.push(path.relative(filepath, entryPath))
        }

        if (recursive && entry.isDirectory()) queue.push(entryPath)
      }
    }
  } catch (e) {
    result = []
    err = e
  }

  return done(err, result, cb)
}

function readdirSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { withFileTypes = false, recursive = false } = opts

  filepath = toNamespacedPath(filepath)

  const queue = [filepath]
  const result = []

  while (queue.length !== 0) {
    const dir = opendirSync(queue.pop(), opts)

    for (const entry of dir) {
      const entryPath = path.join(entry.parentPath, entry.name)

      if (withFileTypes) {
        result.push(entry)
      } else {
        result.push(path.relative(filepath, entryPath))
      }

      if (recursive && entry.isDirectory()) queue.push(entryPath)
    }
  }

  return result
}

async function readFile(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'buffer' } = opts

  let fd = -1
  let buffer = null
  let err = null
  try {
    fd = await open(filepath, opts.flag || 'r')

    const st = await fstat(fd)

    let len = 0

    if (st.size === 0) {
      const buffers = []

      while (true) {
        buffer = Buffer.allocUnsafe(8192)
        const r = await read(fd, buffer)
        len += r
        if (r === 0) break
        buffers.push(buffer.subarray(0, r))
      }

      buffer = Buffer.concat(buffers)
    } else {
      buffer = Buffer.allocUnsafe(st.size)

      while (true) {
        const r = await read(fd, len ? buffer.subarray(len) : buffer)
        len += r
        if (r === 0 || len === buffer.byteLength) break
      }

      if (len !== buffer.byteLength) buffer = buffer.subarray(0, len)
    }

    if (encoding !== 'buffer') buffer = buffer.toString(encoding)
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) await close(fd)
  }

  return done(err, buffer, cb)
}

function readFileSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'buffer' } = opts

  let fd = -1
  try {
    fd = openSync(filepath, opts.flag || 'r')

    const st = fstatSync(fd)

    let buffer
    let len = 0

    if (st.size === 0) {
      const buffers = []

      while (true) {
        buffer = Buffer.allocUnsafe(8192)
        const r = readSync(fd, buffer)
        len += r
        if (r === 0) break
        buffers.push(buffer.subarray(0, r))
      }

      buffer = Buffer.concat(buffers)
    } else {
      buffer = Buffer.allocUnsafe(st.size)

      while (true) {
        const r = readSync(fd, len ? buffer.subarray(len) : buffer)
        len += r
        if (r === 0 || len === buffer.byteLength) break
      }

      if (len !== buffer.byteLength) buffer = buffer.subarray(0, len)
    }

    if (encoding !== 'buffer') buffer = buffer.toString(encoding)

    return buffer
  } finally {
    if (fd !== -1) closeSync(fd)
  }
}

async function writeFile(filepath, data, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (typeof data === 'string') data = Buffer.from(data, opts.encoding)

  let fd = -1
  let len = 0
  let err = null
  try {
    fd = await open(filepath, opts.flag || 'w', opts.mode || 0o666)

    while (true) {
      len += await write(fd, len ? data.subarray(len) : data)
      if (len === data.byteLength) break
    }
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) await close(fd)
  }

  return done(err, len, cb)
}

function writeFileSync(filepath, data, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (typeof data === 'string') data = Buffer.from(data, opts.encoding)

  let fd = -1
  try {
    fd = openSync(filepath, opts.flag || 'w', opts.mode || 0o666)

    let len = 0

    while (true) {
      len += writeSync(fd, len ? data.subarray(len) : data)
      if (len === data.byteLength) break
    }
  } finally {
    if (fd !== -1) closeSync(fd)
  }
}

function appendFile(filepath, data, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (!opts.flag) opts = { ...opts, flag: 'a' }

  return writeFile(filepath, data, opts, cb)
}

function appendFileSync(filepath, data, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (!opts.flag) opts = { ...opts, flag: 'a' }

  return writeFileSync(filepath, data, opts)
}

function watch(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  return new Watcher(filepath, opts, cb)
}

class Stats {
  constructor(
    dev,
    mode,
    nlink,
    uid,
    gid,
    rdev,
    blksize,
    ino,
    size,
    blocks,
    atimeMs,
    mtimeMs,
    ctimeMs,
    birthtimeMs
  ) {
    this.dev = dev
    this.mode = mode
    this.nlink = nlink
    this.uid = uid
    this.gid = gid
    this.rdev = rdev
    this.blksize = blksize
    this.ino = ino
    this.size = size
    this.blocks = blocks
    this.atimeMs = atimeMs
    this.mtimeMs = mtimeMs
    this.ctimeMs = ctimeMs
    this.birthtimeMs = birthtimeMs
    this.atime = new Date(atimeMs)
    this.mtime = new Date(mtimeMs)
    this.ctime = new Date(ctimeMs)
    this.birthtime = new Date(birthtimeMs)
  }

  isDirectory() {
    return (this.mode & constants.S_IFMT) === constants.S_IFDIR
  }

  isFile() {
    return (this.mode & constants.S_IFMT) === constants.S_IFREG
  }

  isBlockDevice() {
    return (this.mode & constants.S_IFMT) === constants.S_IFBLK
  }

  isCharacterDevice() {
    return (this.mode & constants.S_IFMT) === constants.S_IFCHR
  }

  isFIFO() {
    return (this.mode & constants.S_IFMT) === constants.S_IFIFO
  }

  isSymbolicLink() {
    return (this.mode & constants.S_IFMT) === constants.S_IFLNK
  }

  isSocket() {
    return (this.mode & constants.S_IFMT) === constants.S_IFSOCK
  }
}

class StatFs {
  constructor(type, bsize, blocks, bfree, bavail, files, ffree) {
    this.type = type
    this.bsize = bsize
    this.blocks = blocks
    this.bfree = bfree
    this.bavail = bavail
    this.files = files
    this.ffree = ffree
  }
}

class Dir {
  constructor(path, handle, opts = {}) {
    const { encoding = 'utf8', bufferSize = 32 } = opts

    this.path = path

    this._encoding = encoding
    this._capacity = bufferSize
    this._buffer = new FIFO()
    this._ended = false
    this._handle = handle
  }

  async read(cb) {
    if (this._buffer.length) return ok(this._buffer.shift(), cb)
    if (this._ended) return ok(null, cb)

    const req = FileRequest.borrow()

    let entries
    let err = null
    try {
      req.retain(binding.readdir(req.handle, this._handle, this._capacity))

      await req

      entries = binding.requestResultDirents(req.handle)
    } catch (e) {
      err = new FileError(e.message, {
        operation: 'readdir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    if (err) return fail(err, cb)

    if (entries.length === 0) {
      this._ended = true

      return ok(null, cb)
    }

    for (const entry of entries) {
      let name = Buffer.from(entry.name)

      if (this._encoding !== 'buffer') name = name.toString(this._encoding)

      this._buffer.push(new Dirent(this.path, name, entry.type))
    }

    return ok(this._buffer.shift(), cb)
  }

  readSync() {
    if (this._buffer.length) return this._buffer.shift()
    if (this._ended) return null

    const req = FileRequest.borrow()

    let entries
    try {
      req.retain(binding.readdirSync(req.handle, this._handle, this._capacity))

      entries = binding.requestResultDirents(req.handle)
    } catch (e) {
      throw new FileError(e.message, {
        operation: 'readdir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    if (entries.length === 0) {
      this._ended = true

      return null
    }

    for (const entry of entries) {
      let name = Buffer.from(entry.name)

      if (this._encoding !== 'buffer') name = name.toString(this._encoding)

      this._buffer.push(new Dirent(this.path, name, entry.type))
    }

    return this._buffer.shift()
  }

  async close(cb) {
    const req = FileRequest.borrow()

    let err = null
    try {
      binding.closedir(req.handle, this._handle)

      await req
    } catch (e) {
      err = new FileError(e.message, {
        operation: 'closedir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    this._handle = null

    return done(err, cb)
  }

  closeSync() {
    const req = FileRequest.borrow()

    try {
      binding.closedirSync(req.handle, this._handle)
    } catch (e) {
      throw new FileError(e.message, {
        operation: 'closedir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    this._handle = null
  }

  [Symbol.dispose]() {
    this.closeSync()
  }

  async [Symbol.asyncDispose]() {
    await this.close()
  }

  *[Symbol.iterator]() {
    while (true) {
      const entry = this.readSync()
      if (entry === null) break
      yield entry
    }

    this.closeSync()
  }

  async *[Symbol.asyncIterator]() {
    while (true) {
      const entry = await this.read()
      if (entry === null) break
      yield entry
    }

    await this.close()
  }
}

class Dirent {
  constructor(parentPath, name, type) {
    this.parentPath = parentPath
    this.name = name
    this.type = type
  }

  isFile() {
    return this.type === constants.UV_DIRENT_FILE
  }

  isDirectory() {
    return this.type === constants.UV_DIRENT_DIR
  }

  isSymbolicLink() {
    return this.type === constants.UV_DIRENT_LINK
  }

  isFIFO() {
    return this.type === constants.UV_DIRENT_FIFO
  }

  isSocket() {
    return this.type === constants.UV_DIRENT_SOCKET
  }

  isCharacterDevice() {
    return this.type === constants.UV_DIRENT_CHAR
  }

  isBlockDevice() {
    return this.type === constants.UV_DIRENT_BLOCK
  }
}

class FileReadStream extends Readable {
  constructor(path, opts = {}) {
    const { eagerOpen = true } = opts

    super({ eagerOpen, ...opts })

    this.path = path
    this.fd = typeof opts.fd === 'number' ? opts.fd : -1
    this.flags = opts.flags || 'r'
    this.mode = opts.mode || 0o666

    this._offset = opts.start || 0
    this._missing = 0

    if (opts.length) {
      this._missing = opts.length
    } else if (typeof opts.end === 'number') {
      this._missing = opts.end - this._offset + 1
    } else {
      this._missing = -1
    }
  }

  async _open(cb) {
    let err

    if (this.fd === -1) {
      err = null
      try {
        this.fd = await open(this.path, this.flags, this.mode)
      } catch (e) {
        err = e
      }

      if (err) return cb(err)
    }

    let st
    err = null
    try {
      st = await fstat(this.fd)
    } catch (e) {
      err = e
    }

    if (err) return cb(err)

    if (this._missing === -1) this._missing = st.size

    if (st.size < this._offset) {
      this._offset = st.size
      this._missing = 0
    } else if (st.size < this._offset + this._missing) {
      this._missing = st.size - this._offset
    }

    cb(null)
  }

  async _read(size) {
    if (this._missing <= 0) return this.push(null)

    const data = Buffer.allocUnsafe(Math.min(this._missing, size))

    let len
    let err = null
    try {
      len = await read(this.fd, data, 0, data.byteLength, this._offset)
    } catch (e) {
      err = e
    }

    if (err) return this.destroy(err)

    if (len === 0) return this.push(null)

    if (this._missing < len) len = this._missing

    this._missing -= len
    this._offset += len

    this.push(data.subarray(0, len))
  }

  async _destroy(err, cb) {
    if (this.fd === -1) return cb(err)

    try {
      await close(this.fd)
    } catch (e) {
      err = err || e
    }

    cb(err)
  }
}

class FileWriteStream extends Writable {
  constructor(path, opts = {}) {
    const { eagerOpen = true } = opts

    super({ eagerOpen, ...opts })

    this.path = path
    this.fd = typeof opts.fd === 'number' ? opts.fd : -1
    this.flags = opts.flags || 'w'
    this.mode = opts.mode || 0o666
  }

  async _open(cb) {
    if (this.fd !== -1) return cb(null)

    let err = null
    try {
      this.fd = await open(this.path, this.flags, this.mode)
    } catch (e) {
      err = e
    }

    cb(err)
  }

  async _writev(batch, cb) {
    let err = null
    try {
      await writev(
        this.fd,
        batch.map(({ chunk }) => chunk)
      )
    } catch (e) {
      err = e
    }

    cb(err)
  }

  async _destroy(err, cb) {
    if (this.fd === -1) return cb(err)

    try {
      await close(this.fd)
    } catch (e) {
      err = err || e
    }

    cb(err)
  }
}

class Watcher extends EventEmitter {
  constructor(path, opts, onchange) {
    if (typeof opts === 'function') {
      onchange = opts
      opts = {}
    }

    if (!opts) opts = {}

    const { persistent = true, recursive = false, encoding = 'utf8' } = opts

    super()

    this._closed = false
    this._encoding = encoding
    this._handle = binding.watcherInit(path, recursive, this, this._onevent, this._onclose)

    if (!persistent) this.unref()

    if (onchange) this.on('change', onchange)
  }

  close() {
    if (this._closed) return
    this._closed = true

    binding.watcherClose(this._handle)
  }

  ref() {
    if (this._handle) binding.watcherRef(this._handle)
    return this
  }

  unref() {
    if (this._handle) binding.watcherUnref(this._handle)
    return this
  }

  [Symbol.asyncIterator]() {
    const buffer = []
    let done = false
    let error = null
    let next = null

    this.on('change', (eventType, filename) => {
      if (next) {
        next.resolve({ done: false, value: { eventType, filename } })
        next = null
      } else {
        buffer.push({ eventType, filename })
      }
    })
      .on('error', (err) => {
        done = true
        error = err

        if (next) {
          next.reject(error)
          next = null
        }
      })
      .on('close', () => {
        done = true

        if (next) {
          next.resolve({ done })
          next = null
        }
      })

    return {
      next: () =>
        new Promise((resolve, reject) => {
          if (error) return reject(error)

          if (buffer.length) return resolve({ done: false, value: buffer.shift() })

          if (done) return resolve({ done })

          next = { resolve, reject }
        })
    }
  }

  _onevent(err, events, filename) {
    if (err) {
      this.close()
      this.emit('error', err)
    } else {
      const path =
        this._encoding === 'buffer'
          ? Buffer.from(filename)
          : Buffer.from(filename).toString(this._encoding)

      if (events & binding.UV_RENAME) {
        this.emit('change', 'rename', path)
      }

      if (events & binding.UV_CHANGE) {
        this.emit('change', 'change', path)
      }
    }
  }

  _onclose() {
    this._handle = null

    this.emit('close')
  }
}

exports.access = access
exports.appendFile = appendFile
exports.chmod = chmod
exports.chown = chown
exports.close = close
exports.copyFile = copyFile
exports.cp = cp
exports.exists = exists
exports.fchmod = fchmod
exports.fchown = fchown
exports.fdatasync = fdatasync
exports.fstat = fstat
exports.fsync = fsync
exports.ftruncate = ftruncate
exports.futimes = futimes
exports.lchown = lchown
exports.lutimes = lutimes
exports.link = link
exports.lstat = lstat
exports.mkdir = mkdir
exports.mkdtemp = mkdtemp
exports.open = open
exports.opendir = opendir
exports.read = read
exports.readFile = readFile
exports.readdir = readdir
exports.readlink = readlink
exports.readv = readv
exports.realpath = realpath
exports.rename = rename
exports.rm = rm
exports.rmdir = rmdir
exports.stat = stat
exports.statfs = statfs
exports.symlink = symlink
exports.truncate = truncate
exports.unlink = unlink
exports.utimes = utimes
exports.watch = watch
exports.write = write
exports.writeFile = writeFile
exports.writev = writev

exports.accessSync = accessSync
exports.appendFileSync = appendFileSync
exports.chmodSync = chmodSync
exports.chownSync = chownSync
exports.closeSync = closeSync
exports.copyFileSync = copyFileSync
exports.cpSync = cpSync
exports.existsSync = existsSync
exports.fchmodSync = fchmodSync
exports.fchownSync = fchownSync
exports.fdatasyncSync = fdatasyncSync
exports.fstatSync = fstatSync
exports.fsyncSync = fsyncSync
exports.ftruncateSync = ftruncateSync
exports.futimesSync = futimesSync
exports.lchownSync = lchownSync
exports.lutimesSync = lutimesSync
exports.linkSync = linkSync
exports.lstatSync = lstatSync
exports.mkdirSync = mkdirSync
exports.mkdtempSync = mkdtempSync
exports.openSync = openSync
exports.opendirSync = opendirSync
exports.readFileSync = readFileSync
exports.readSync = readSync
exports.readdirSync = readdirSync
exports.readlinkSync = readlinkSync
exports.readvSync = readvSync
exports.realpathSync = realpathSync
exports.renameSync = renameSync
exports.rmSync = rmSync
exports.rmdirSync = rmdirSync
exports.statSync = statSync
exports.statfsSync = statfsSync
exports.symlinkSync = symlinkSync
exports.truncateSync = truncateSync
exports.unlinkSync = unlinkSync
exports.utimesSync = utimesSync
exports.writeFileSync = writeFileSync
exports.writeSync = writeSync
exports.writevSync = writevSync

exports.promises = require('./promises')

exports.Stats = Stats
exports.StatFs = StatFs
exports.Dir = Dir
exports.Dirent = Dirent
exports.Watcher = Watcher

exports.ReadStream = FileReadStream

exports.createReadStream = function createReadStream(path, opts) {
  return new FileReadStream(path, opts)
}

exports.WriteStream = FileWriteStream

exports.createWriteStream = function createWriteStream(path, opts) {
  return new FileWriteStream(path, opts)
}

function toNamespacedPath(filepath) {
  if (typeof filepath !== 'string') {
    if (isURL(filepath)) filepath = fileURLToPath(filepath)
    else filepath = filepath.toString()
  }

  return path.toNamespacedPath(filepath)
}

function toFlags(flags) {
  switch (flags) {
    case 'r':
      return constants.O_RDONLY
    case 'rs': // Fall through.
    case 'sr':
      return constants.O_RDONLY | constants.O_SYNC
    case 'r+':
      return constants.O_RDWR
    case 'rs+': // Fall through.
    case 'sr+':
      return constants.O_RDWR | constants.O_SYNC

    case 'w':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_WRONLY
    case 'wx': // Fall through.
    case 'xw':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_WRONLY | constants.O_EXCL

    case 'w+':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_RDWR
    case 'wx+': // Fall through.
    case 'xw+':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_RDWR | constants.O_EXCL

    case 'a':
      return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY
    case 'ax': // Fall through.
    case 'xa':
      return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY | constants.O_EXCL
    case 'as': // Fall through.
    case 'sa':
      return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY | constants.O_SYNC

    case 'a+':
      return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR
    case 'ax+': // Fall through.
    case 'xa+':
      return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR | constants.O_EXCL
    case 'as+': // Fall through.
    case 'sa+':
      return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR | constants.O_SYNC
    default:
      return 0
  }
}

function toMode(mode) {
  return parseInt(mode, 8)
}
const binding = require('../binding')

module.exports = {
  O_RDWR: binding.O_RDWR,
  O_RDONLY: binding.O_RDONLY,
  O_WRONLY: binding.O_WRONLY,
  O_CREAT: binding.O_CREAT,
  O_TRUNC: binding.O_TRUNC,
  O_APPEND: binding.O_APPEND,

  F_OK: binding.F_OK || 0,
  R_OK: binding.R_OK || 0,
  W_OK: binding.W_OK || 0,
  X_OK: binding.X_OK || 0,

  S_IFMT: binding.S_IFMT,
  S_IFREG: binding.S_IFREG,
  S_IFDIR: binding.S_IFDIR,
  S_IFCHR: binding.S_IFCHR,
  S_IFLNK: binding.S_IFLNK,
  S_IFBLK: binding.S_IFBLK || 0,
  S_IFIFO: binding.S_IFIFO || 0,
  S_IFSOCK: binding.S_IFSOCK || 0,

  S_IRUSR: binding.S_IRUSR || 0,
  S_IWUSR: binding.S_IWUSR || 0,
  S_IXUSR: binding.S_IXUSR || 0,
  S_IRGRP: binding.S_IRGRP || 0,
  S_IWGRP: binding.S_IWGRP || 0,
  S_IXGRP: binding.S_IXGRP || 0,
  S_IROTH: binding.S_IROTH || 0,
  S_IWOTH: binding.S_IWOTH || 0,
  S_IXOTH: binding.S_IXOTH || 0,

  UV_DIRENT_UNKNOWN: binding.UV_DIRENT_UNKNOWN,
  UV_DIRENT_FILE: binding.UV_DIRENT_FILE,
  UV_DIRENT_DIR: binding.UV_DIRENT_DIR,
  UV_DIRENT_LINK: binding.UV_DIRENT_LINK,
  UV_DIRENT_FIFO: binding.UV_DIRENT_FIFO,
  UV_DIRENT_SOCKET: binding.UV_DIRENT_SOCKET,
  UV_DIRENT_CHAR: binding.UV_DIRENT_CHAR,
  UV_DIRENT_BLOCK: binding.UV_DIRENT_BLOCK,

  COPYFILE_EXCL: binding.UV_FS_COPYFILE_EXCL,
  COPYFILE_FICLONE: binding.UV_FS_COPYFILE_FICLONE,
  COPYFILE_FICLONE_FORCE: binding.UV_FS_COPYFILE_FICLONE_FORCE,
  UV_FS_SYMLINK_DIR: binding.UV_FS_SYMLINK_DIR,
  UV_FS_SYMLINK_JUNCTION: binding.UV_FS_SYMLINK_JUNCTION
}
const os = require('bare-os')

module.exports = class FileError extends Error {
  constructor(msg, opts = {}) {
    const { code, operation = null, path = null, destination = null, fd = -1 } = opts

    if (operation !== null) msg += describe(operation, opts)

    super(`${code}: ${msg}`)

    this.code = code

    if (operation !== null) this.operation = operation
    if (path !== null) this.path = path
    if (destination !== null) this.destination = destination
    if (fd !== -1) this.fd = fd
  }

  get name() {
    return 'FileError'
  }

  // For Node.js compatibility
  get errno() {
    return os.constants.errnos[this.code]
  }

  // For Node.js compatibility
  get syscall() {
    return this.operation
  }

  // For Node.js compatibility
  get dest() {
    return this.destination
  }
}

function describe(operation, opts) {
  const { path = null, destination = null, fd = -1 } = opts

  let result = `, ${operation}`

  if (path !== null) {
    result += ` ${JSON.stringify(path)}`

    if (destination !== null) {
      result += ` -> ${JSON.stringify(destination)}`
    }
  } else if (fd !== -1) {
    result += ` ${fd}`
  }

  return result
}
{
  "name": "bare-fs",
  "version": "4.7.3",
  "description": "Native file system operations for Bare",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./promises": {
      "types": "./promises.d.ts",
      "default": "./promises.js"
    },
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "promises.js",
    "promises.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-fs.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-fs/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-fs#readme",
  "engines": {
    "bare": ">=1.16.0"
  },
  "dependencies": {
    "bare-events": "^2.5.4",
    "bare-path": "^3.0.0",
    "bare-stream": "^2.6.4",
    "bare-url": "^2.2.2",
    "fast-fifo": "^1.3.2"
  },
  "devDependencies": {
    "bare-buffer": "^3.0.2",
    "bare-crypto": "^1.11.2",
    "brittle": "^3.1.1",
    "cmake-bare": "^1.1.7",
    "lunte": "^1.6.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "bare-buffer": "*"
  },
  "peerDependenciesMeta": {
    "bare-buffer": {
      "optional": true
    }
  }
}
const EventEmitter = require('bare-events')
const fs = require('.')

class FileHandle extends EventEmitter {
  constructor(fd) {
    super()

    this.fd = fd
  }

  async close() {
    await fs.close(this.fd)

    this.fd = -1
    this.emit('close')
  }

  async read(buffer, ...args) {
    return {
      bytesRead: await fs.read(this.fd, buffer, ...args),
      buffer
    }
  }

  async readv(buffers, ...args) {
    return {
      bytesRead: await fs.readv(this.fd, buffers, ...args),
      buffers
    }
  }

  async write(buffer, ...args) {
    return {
      bytesWritten: await fs.write(this.fd, buffer, ...args),
      buffer
    }
  }

  async writev(buffers, ...args) {
    return {
      bytesWritten: await fs.writev(this.fd, buffers, ...args),
      buffers
    }
  }

  async stat() {
    return fs.fstat(this.fd)
  }

  async chmod(mode) {
    await fs.fchmod(this.fd, mode)
  }

  async chown(uid, gid) {
    await fs.fchown(this.fd, uid, gid)
  }

  async datasync() {
    return fs.fdatasync(this.fd)
  }

  async sync() {
    return fs.fsync(this.fd)
  }

  async truncate(len) {
    await fs.ftruncate(this.fd, len)
  }

  async utimes(atime, mtime) {
    await fs.futimes(this.fd, atime, mtime)
  }

  createReadStream(opts) {
    return fs.createReadStream(null, { ...opts, fd: this.fd })
  }

  createWriteStream(opts) {
    return fs.createWriteStream(null, { ...opts, fd: this.fd })
  }

  async [Symbol.asyncDispose]() {
    await this.close()
  }
}

exports.open = async function open(filepath, flags, mode) {
  return new FileHandle(await fs.open(filepath, flags, mode))
}

exports.access = fs.access
exports.appendFile = fs.appendFile
exports.chmod = fs.chmod
exports.chown = fs.chown
exports.constants = fs.constants
exports.copyFile = fs.copyFile
exports.cp = fs.cp
exports.lchown = fs.lchown
exports.lutimes = fs.lutimes
exports.link = fs.link
exports.lstat = fs.lstat
exports.mkdir = fs.mkdir
exports.mkdtemp = fs.mkdtemp
exports.opendir = fs.opendir
exports.readFile = fs.readFile
exports.readdir = fs.readdir
exports.readlink = fs.readlink
exports.realpath = fs.realpath
exports.rename = fs.rename
exports.rm = fs.rm
exports.rmdir = fs.rmdir
exports.stat = fs.stat
exports.statfs = fs.statfs
exports.truncate = fs.truncate
exports.symlink = fs.symlink
exports.unlink = fs.unlink
exports.utimes = fs.utimes
exports.watch = fs.watch
exports.writeFile = fs.writeFile
module.exports = require.addon()
const ansiEscapes = require('bare-ansi-escapes')
const getType = require('bare-type')
const binding = require('./binding')

const PLAIN_KEY = /^[a-zA-Z_][a-zA-Z_0-9]*$/

const defaultDepth = 2
const defaultBreakLength = 80
const defaultMaxArrayLength = 40

module.exports = exports = function inspect(value, opts = {}) {
  const {
    colors = false,
    depth = defaultDepth,
    breakLength = defaultBreakLength,
    stylize = defaultStylize(colors)
  } = opts

  const references = new InspectRefMap()

  const tree = inspectValue(value, 0, {
    colors,
    depth,
    breakLength,
    stylize,
    references
  })

  return tree.toString()
}

exports.styles = {
  bigint: ansiEscapes.colorYellow,
  boolean: ansiEscapes.colorYellow,
  date: ansiEscapes.colorMagenta,
  module: ansiEscapes.modifierUnderline,
  name: ansiEscapes.modifierReset,
  null: ansiEscapes.modifierBold,
  number: ansiEscapes.colorYellow,
  regexp: ansiEscapes.colorRed,
  special: ansiEscapes.colorCyan,
  string: ansiEscapes.colorGreen,
  symbol: ansiEscapes.colorGreen,
  undefined: ansiEscapes.colorBrightBlack
}

const styles = exports.styles

function defaultStylize(colors) {
  return function stylize(value, style) {
    const color = colors && styles[style]

    if (color) return color + value + ansiEscapes.modifierReset

    return value
  }
}

class InspectRefMap {
  constructor() {
    this.refs = new WeakMap()
    this.ids = new WeakMap()
    this.nextId = 1
  }

  has(object) {
    return this.refs.has(object)
  }

  get(object) {
    return this.refs.get(object) || null
  }

  set(object, ref) {
    this.refs.set(object, ref)
  }

  id(object) {
    let id = this.ids.get(object)
    if (id) return id

    id = this.nextId++
    this.ids.set(object, id)

    return id
  }
}

class InspectNode {
  constructor(depth, length, opts) {
    const { breakLength = defaultBreakLength, breakAlways = false } = opts

    this.depth = depth
    this.length = length
    this.breakLength = breakLength
    this.breakAlways = breakAlways
  }

  pad(n, string) {
    return string.padStart(n, ' ')
  }

  indent(n, string) {
    return '  '.repeat(n) + string
  }
}

class InspectRef extends InspectNode {
  constructor(depth, opts) {
    super(depth, '[circular *]'.length, opts)

    this.refs = opts.references
    this.count = 0
    this.circular = false
    this.color = opts.colors && styles.special
  }

  get id() {
    return this.refs.id(this)
  }

  increment() {
    return ++this.count
  }

  decrement() {
    return --this.count
  }

  toString(opts = {}) {
    const { offset = 0, pad = 0, indent = 0 } = opts

    let value = this.pad(pad, '[circular *' + this.id + ']')

    if (this.color) value = this.color + value + ansiEscapes.modifierReset

    return offset ? value : this.indent(indent, value)
  }
}

class InspectLeaf extends InspectNode {
  constructor(value, color, depth, opts) {
    const length = value.length

    if (value.includes('\n')) {
      value = value.replaceAll('\n', '\n' + '  '.repeat(depth))

      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.value = value
    this.color = opts.colors && color
  }

  toString(opts = {}) {
    const { offset = 0, pad = 0, indent = 0 } = opts

    let value = this.pad(pad, this.value)

    if (this.color) value = this.color + value + ansiEscapes.modifierReset

    return offset ? value : this.indent(indent, value)
  }
}

class InspectPair extends InspectNode {
  constructor(delim, left, right, depth, opts) {
    const length = left.length + delim.length + right.length

    if (left.breakAlways || right.breakAlways) {
      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.delim = delim
    this.left = left
    this.right = right
  }

  toString(opts = {}) {
    const { indent = 0 } = opts

    return this.indent(
      indent,
      this.left +
        this.delim +
        this.right.toString({
          indent,
          offset: this.left.length + this.delim.length
        })
    )
  }
}

class InspectSuspension extends InspectNode {
  constructor(overflow, depth, opts) {
    const label = `... ${overflow} more`

    super(depth, label.length, opts)

    this.label = label
  }

  toString(opts = {}) {
    const { indent = 0 } = opts

    return this.indent(indent, this.label)
  }
}

class InspectSequence extends InspectNode {
  constructor(header, footer, delim, values, ref, depth, opts) {
    const { tabulate = false } = opts

    const length =
      (ref.circular ? '<ref *>'.length + 1 : 0) +
      header.length +
      values.reduce(
        (length, value, i) =>
          length + value.length + (i === 0 ? 0 : delim.length),
        0
      ) +
      footer.length

    if (values.some((value) => value.breakAlways)) {
      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.header = header
    this.footer = footer
    this.delim = delim
    this.values = values
    this.ref = ref
    this.tabulate = tabulate
  }

  toString(opts = {}) {
    const { offset = 0, indent = 0 } = opts

    const split =
      this.breakAlways ||
      (this.values.length &&
        (offset + this.length > this.breakLength ||
          indent * 2 + this.length > this.breakLength))

    let header = this.header

    if (this.ref.circular) {
      header = '<ref *' + this.ref.id + '> ' + header
    }

    if (this.values.length === 0) {
      header = header.trimEnd()
    }

    if (offset === 0) {
      header = this.indent(indent, header)
    }

    if (split) {
      header = header.trimEnd() + '\n'
    }

    let string = header

    let columns = 1
    let pad = 0

    if (this.tabulate) {
      const widest = this.values.reduce(
        (length, value) =>
          value.breakAlways ? length : Math.max(length, value.length),
        0
      )

      if (widest) {
        columns = Math.max(
          columns,
          Math.floor(
            (this.breakLength - indent * 2) / (widest + this.delim.length)
          )
        )

        if (columns > 1) pad = widest
      }
    }

    for (let i = 0, n = this.values.length, offset = 0; i < n; i++) {
      const value = this.values[i]

      if (split) {
        let part

        if (i % columns === 0 || value.breakAlways) {
          part = value.toString({ indent: indent + 1, pad })
        } else {
          part = value.toString({ pad })
        }

        string += part

        if (i < n - 1) {
          if (i % columns === columns - 1 || this.values[i + 1].breakAlways) {
            string += this.delim.trimEnd() + '\n'
          } else {
            string += this.delim
          }
        }
      } else {
        if (i > 0) string += this.delim

        string += value.toString({ offset })

        offset += value.length
      }
    }

    let footer = this.footer

    if (this.values.length === 0) {
      footer = footer.trimStart()
    }

    if (split) {
      string += '\n' + this.indent(indent, footer.trimStart())
    } else {
      string += footer
    }

    return string
  }
}

function inspectValue(value, depth, opts) {
  const type = getType(value)

  if (type.isUndefined()) return inspectUndefined(depth, opts)
  if (type.isNull()) return inspectNull(depth, opts)
  if (type.isBoolean()) return inspectBoolean(value, depth, opts)
  if (type.isNumber()) return inspectNumber(value, depth, opts)
  if (type.isBigInt()) return inspectBigInt(value, depth, opts)
  if (type.isString()) return inspectString(value, depth, opts)
  if (type.isSymbol()) return inspectSymbol(value, depth, opts)
  if (type.isObject()) return inspectObject(type, value, depth, opts)
  if (type.isFunction()) return inspectFunction(type, value, depth, opts)
  if (type.isExternal()) return inspectExternal(value, opts, opts)
}

function inspectUndefined(depth, opts) {
  return new InspectLeaf('undefined', styles.undefined, depth, opts)
}

function inspectNull(depth, opts) {
  return new InspectLeaf('null', styles.null, depth, opts)
}

function inspectBoolean(value, depth, opts) {
  return new InspectLeaf(value.toString(), styles.boolean, depth, opts)
}

function inspectNumber(value, depth, opts) {
  let string

  if (Object.is(value, -0)) {
    string = '-0'
  } else {
    string = value.toString(10)
  }

  return new InspectLeaf(string, styles.number, depth, opts)
}

function inspectBigInt(value, depth, opts) {
  return new InspectLeaf(value.toString(10) + 'n', styles.bigint, depth, opts)
}

const STRING_ESCAPES =
  /[\ud800-\udbff][\udc00-\udfff]|[\u0000-\u001f'\\\ud800-\udfff]/g

function inspectString(value, depth, opts) {
  // https://tc39.es/ecma262/multipage/structured-data.html#sec-quotejsonstring
  const string = value.replace(STRING_ESCAPES, (match) => {
    if (match.length === 2) return match

    switch (match) {
      case "'":
        return "\\'"
      case '\\':
        return '\\\\'
      case '\b':
        return '\\b'
      case '\t':
        return '\\t'
      case '\n':
        return '\\n'
      case '\f':
        return '\\f'
      case '\r':
        return '\\r'
      default:
        return '\\u' + match.charCodeAt(0).toString(16).padStart(4, '0')
    }
  })

  return new InspectLeaf("'" + string + "'", styles.string, depth, opts)
}

function inspectSymbol(value, depth, opts) {
  return new InspectLeaf(value.toString(), styles.symbol, depth, opts)
}

function inspectKey(value, depth, opts) {
  if (PLAIN_KEY.test(value)) {
    return new InspectLeaf(value, null, depth, opts)
  } else {
    return inspectValue(value, depth, opts)
  }
}

function inspectObject(type, object, depth, opts) {
  const refs = opts.references

  let ref = refs.get(object)
  if (ref === null) {
    ref = new InspectRef(depth, opts)
    refs.set(object, ref)
  } else if (ref.count) {
    ref.circular = true
    return ref
  }

  const maxDepth = typeof opts.depth === 'number' ? opts.depth : Infinity

  if (maxDepth < depth) {
    const constructor = object.constructor

    return new InspectLeaf(
      '[' +
        (constructor && constructor.name ? constructor.name : 'Object') +
        ']',
      styles.special,
      depth,
      opts
    )
  }

  const inspect =
    object[Symbol.for('bare.inspect')] ||
    object[Symbol.for('nodejs.util.inspect.custom')]

  if (typeof inspect === 'function') {
    const value = inspect.call(
      object,
      typeof opts.depth === 'number' ? opts.depth - depth : null,
      {
        colors: opts.colors,
        breakLength: opts.breakLength,
        stylize: opts.stylize
      },
      exports
    )

    if (typeof value === 'object' && value !== null) {
      refs.set(value, ref)
    }

    if (typeof value !== 'string') {
      return inspectValue(value, depth, opts)
    }

    return new InspectLeaf(value, null, depth, opts)
  }

  if (type.isArray()) return inspectArray(object, ref, depth, opts)
  if (type.isDate()) return inspectDate(object, ref, depth, opts)
  if (type.isRegExp()) return inspectRegExp(object, ref, depth, opts)
  if (type.isError()) return inspectError(object, ref, depth, opts)
  if (type.isPromise()) return inspectPromise(object, ref, depth, opts)
  if (type.isMap()) return inspectMap(object, ref, depth, opts)
  if (type.isSet()) return inspectSet(object, ref, depth, opts)
  if (type.isWeakMap()) return inspectWeakMap(object, ref, depth, opts)
  if (type.isWeakSet()) return inspectWeakSet(object, ref, depth, opts)
  if (type.isWeakRef()) return inspectWeakRef(object, ref, depth, opts)
  if (type.isArrayBuffer()) return inspectArrayBuffer(object, ref, depth, opts)
  if (type.isSharedArrayBuffer())
    return inspectSharedArrayBuffer(object, ref, depth, opts)
  if (type.isTypedArray()) return inspectTypedArray(object, ref, depth, opts)
  if (type.isDataView()) return inspectDataView(object, ref, depth, opts)

  ref.increment()

  const values = []

  for (const key in object) {
    if (key === 'constructor') continue

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(object[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  let header = '{ '

  const tag = object[Symbol.toStringTag]

  if (tag) header = '[' + tag + '] ' + header

  if (object.constructor) {
    const name = object.constructor.name

    if (name && name !== 'Object') {
      header = object.constructor.name + ' ' + header
    }
  }

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectArray(array, ref, depth, opts) {
  const { maxArrayLength = defaultMaxArrayLength } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxArrayLength, 0)

  for (let i = 0, n = array.length; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(array.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(inspectValue(array[i], depth + 1, opts))
  }

  for (const key of binding.getOwnNonIndexPropertyNames(array)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(array[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  let header = '[ '

  if (array.constructor.name !== 'Array') {
    header = array.constructor.name + '(' + array.length + ') ' + header
  }

  return new InspectSequence(header, ' ]', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectDate(date, ref, depth, opts) {
  return new InspectLeaf(date.toISOString(), styles.date, depth, opts)
}

function inspectRegExp(regExp, ref, depth, opts) {
  return new InspectLeaf(regExp.toString(), styles.regexp, depth, opts)
}

function inspectError(error, ref, depth, opts) {
  let header

  if ('stack' in error) {
    header = error.stack

    if (depth > 0) {
      header = header.replaceAll('\n', '\n' + '  '.repeat(depth))
    }
  } else {
    header = error.toString()
  }

  const builtins = ['cause']

  if (error.name === 'AggregateError') {
    builtins.push('errors')
  } else if (error.name === 'SuppressedError') {
    builtins.push('error', 'suppressed')
  }

  const values = []

  for (const key of builtins) {
    if (key in error === false) continue

    values.push(
      new InspectPair(
        ': ',
        new InspectLeaf('[' + key + ']', null, depth + 1, opts),
        inspectValue(error[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key in error) {
    if (key === 'constructor' || builtins.includes(key)) continue

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(error[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  if (values.length === 0) return new InspectLeaf(header, null, depth, opts)

  return new InspectSequence(
    header + ' {',
    ' }',
    ', ',
    values,
    ref,
    depth,
    opts
  )
}

function inspectPromise(promise, ref, depth, opts) {
  ref.increment()

  const state = binding.getPromiseState(promise)

  const values = []

  switch (state) {
    case 0: // Pending
      values.push(new InspectLeaf('<pending>', styles.special, depth, opts))
      break

    case 1: // Fulfilled
      values.push(inspectValue(binding.getPromiseResult(promise), depth, opts))
      break

    case 2: // Rejected
      values.push(
        new InspectLeaf('<rejected>', styles.special, depth, opts),
        inspectValue(binding.getPromiseResult(promise), depth, opts)
      )
  }

  ref.decrement()

  const header = promise.constructor.name + ' { '

  return new InspectSequence(header, ' }', ' ', values, ref, depth, opts)
}

function inspectMap(map, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxMapLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = maxMapLength

  for (const entry of map) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(map.size - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )
      break
    }

    values.push(
      new InspectPair(
        ' => ',
        inspectValue(entry[0], depth + 1, opts),
        inspectValue(entry[1], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key in map) {
    if (key === 'constructor') continue

    const value = inspectValue(map[key], depth + 1, opts)

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        value,
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = map.constructor.name + '(' + map.size + ') { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectSet(set, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxSetLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = maxSetLength

  for (const entry of set) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(set.size - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )
      break
    }

    values.push(inspectValue(entry, depth + 1, opts))
  }

  for (const key in set) {
    if (key === 'constructor') continue

    const value = inspectValue(set[key], depth + 1, opts)

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        value,
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = set.constructor.name + '(' + set.size + ') { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectWeakMap(weakMap, ref, depth, opts) {
  const header = weakMap.constructor.name + ' { '

  return new InspectSequence(
    header,
    ' }',
    ' ',
    [new InspectLeaf('<items unknown>', styles.special, depth + 1, opts)],
    ref,
    depth,
    opts
  )
}

function inspectWeakSet(weakSet, ref, depth, opts) {
  const header = weakSet.constructor.name + ' { '

  return new InspectSequence(
    header,
    ' }',
    ' ',
    [new InspectLeaf('<items unknown>', styles.special, depth + 1, opts)],
    ref,
    depth,
    opts
  )
}

function inspectWeakRef(weakRef, ref, depth, opts) {
  const target = weakRef.deref()

  let value

  if (target === undefined) {
    value = new InspectLeaf('<cleared>', styles.special, depth + 1, opts)
  } else {
    value = inspectValue(target, depth + 1, opts)
  }

  const header = weakRef.constructor.name + ' { '

  return new InspectSequence(header, ' }', ' ', [value], ref, depth, opts)
}

function inspectArrayBuffer(arrayBuffer, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(arrayBuffer[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = arrayBuffer.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectSharedArrayBuffer(sharedArrayBuffer, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(sharedArrayBuffer[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = sharedArrayBuffer.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectTypedArray(typedArray, ref, depth, opts) {
  if (Buffer.isBuffer(typedArray)) {
    return inspectBuffer(typedArray, ref, depth, opts)
  }

  const {
    maxArrayLength = defaultMaxArrayLength,
    maxTypedArrayLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxTypedArrayLength, 0)

  for (let i = 0, n = typedArray.length; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(typedArray.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(inspectValue(typedArray[i], depth + 1, opts))
  }

  for (const key of binding.getOwnNonIndexPropertyNames(typedArray)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(typedArray[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = typedArray.constructor.name + '(' + typedArray.length + ') [ '

  return new InspectSequence(header, ' ]', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectBuffer(buffer, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxBufferLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxBufferLength, 0)

  for (let i = 0, n = buffer.byteLength; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(buffer.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(
      new InspectLeaf(
        buffer[i].toString(16).padStart(2, '0'),
        null,
        depth + 1,
        opts
      )
    )
  }

  for (const key of binding.getOwnNonIndexPropertyNames(buffer)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(buffer[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  return new InspectSequence('<Buffer ', '>', ' ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectDataView(dataView, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength', 'byteOffset', 'buffer']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(dataView[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key of binding.getOwnNonIndexPropertyNames(dataView)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(dataView[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = dataView.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectFunction(type, fn, depth, opts) {
  if (fn.toString().startsWith('class')) return inspectClass(fn, depth, opts)

  let tag = 'function'

  if (type.isGeneratorFunction()) tag = 'generator ' + tag
  if (type.isAsyncFunction()) tag = 'async ' + tag

  return new InspectLeaf(
    '[' + tag + ' ' + (fn.name ? fn.name : '(anonymous)') + ']',
    styles.special,
    depth,
    opts
  )
}

function inspectClass(ctor, depth, opts) {
  return new InspectLeaf(
    '[class ' + (ctor.name ? ctor.name : '(anonymous)') + ']',
    styles.special,
    depth,
    opts
  )
}

function inspectExternal(external, depth, opts) {
  return new InspectLeaf(
    '[external 0x' + binding.getExternal(external).toString(16) + ']',
    styles.special,
    depth,
    opts
  )
}
{
  "name": "bare-inspect",
  "version": "3.1.4",
  "description": "Inspect objects as strings for debugging",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-inspect.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-inspect/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-inspect#readme",
  "engines": {
    "bare": ">=1.18.0"
  },
  "dependencies": {
    "bare-ansi-escapes": "^2.1.0",
    "bare-type": "^1.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
module.exports = require.addon()
const binding = require('./binding')
const errors = require('./lib/errors')
const constants = require('./lib/constants')

exports.constants = constants
exports.errors = errors

exports.EOL = binding.platform === 'win32' ? '\r\n' : '\n'

exports.devNull = binding.platform === 'win32' ? '\\\\.\\nul' : '/dev/null'

exports.platform = function platform() {
  return binding.platform
}

exports.arch = function arch() {
  return binding.arch
}

exports.type = function type() {
  return binding.type()
}

exports.version = function version() {
  return binding.version()
}

exports.release = function release() {
  return binding.release()
}

exports.machine = function machine() {
  return binding.machine()
}

exports.execPath = function execPath() {
  return binding.execPath()
}

exports.pid = function pid() {
  return binding.pid()
}

exports.ppid = function ppid() {
  return binding.ppid()
}

exports.cwd = function cwd() {
  return binding.cwd()
}

exports.chdir = function chdir(dir) {
  validateString(dir, 'Directory')

  binding.chdir(dir)
}

exports.tmpdir = function tmpdir() {
  return binding.tmpdir()
}

exports.homedir = function homedir() {
  return binding.homedir()
}

exports.hostname = function hostname() {
  return binding.hostname()
}

exports.userInfo = function userInfo(uid) {
  if (uid !== undefined) validateInteger(uid, 'User ID')

  return binding.userInfo(uid)
}

exports.groupInfo = function groupInfo(gid) {
  if (gid !== undefined) validateInteger(gid, 'Group ID')

  return binding.groupInfo(gid)
}

exports.networkInterfaces = function networkInterfaces() {
  const result = {}

  for (const entry of binding.networkInterfaces()) {
    const { name, ...properties } = entry

    if (result[name]) result[name].push(properties)
    else result[name] = [properties]
  }

  return result
}

exports.kill = function kill(pid, signal = constants.signals.SIGTERM) {
  validateInteger(pid, 'Process ID')

  if (typeof signal === 'string') {
    if (signal in constants.signals === false) {
      throw errors.UNKNOWN_SIGNAL('Unknown signal: ' + signal)
    }

    signal = constants.signals[signal]
  } else {
    validateInteger(signal, 'Signal')
  }

  binding.kill(pid, signal)
}

exports.endianness = function endianness() {
  return binding.isLittleEndian ? 'LE' : 'BE'
}

exports.availableParallelism = function availableParallelism() {
  return binding.availableParallelism()
}

exports.cpuUsage = function cpuUsage(previous) {
  const current = binding.cpuUsage()

  if (previous) {
    return {
      user: current.user - previous.user,
      system: current.system - previous.system
    }
  }

  return current
}

exports.threadCpuUsage = function threadCpuUsage(previous) {
  const current = binding.threadCpuUsage()

  if (previous) {
    return {
      user: current.user - previous.user,
      system: current.system - previous.system
    }
  }

  return current
}

exports.resourceUsage = function resourceUsage() {
  return binding.resourceUsage()
}

exports.memoryUsage = function memoryUsage() {
  return binding.memoryUsage()
}

exports.freemem = function freemem() {
  return binding.freemem()
}

exports.totalmem = function totalmem() {
  return binding.totalmem()
}

exports.availableMemory = function availableMemory() {
  return binding.availableMemory()
}

exports.constrainedMemory = function constrainedMemory() {
  return binding.constrainedMemory()
}

exports.uptime = function uptime() {
  return binding.uptime()
}

exports.loadavg = function loadavg() {
  return binding.loadavg()
}

exports.cpus = function cpus() {
  return binding.cpus()
}

exports.getProcessTitle = function getProcessTitle() {
  return binding.getProcessTitle()
}

exports.setProcessTitle = function setProcessTitle(title) {
  if (typeof title !== 'string') title = title.toString()

  if (title.length >= 256) {
    throw errors.TITLE_OVERFLOW('Process title is too long')
  }

  binding.setProcessTitle(title)
}

exports.getPriority = function getPriority(pid = 0) {
  validateInteger(pid, 'Process ID')

  return binding.getPriority(pid)
}

exports.setPriority = function setPriority(pid, priority) {
  if (priority === undefined) {
    priority = pid
    pid = 0
  }

  validateInteger(pid, 'Process ID')
  validateInteger(priority, 'Priority')

  binding.setPriority(pid, priority)
}

exports.getEnvKeys = function getEnvKeys() {
  return binding.getEnvKeys()
}

exports.getEnv = function getEnv(name) {
  validateString(name, 'Name')

  return binding.getEnv(name)
}

exports.hasEnv = function hasEnv(name) {
  validateString(name, 'Name')

  return binding.hasEnv(name)
}

exports.setEnv = function setEnv(name, value) {
  validateString(name, 'Name')
  validateString(value, 'Value')

  binding.setEnv(name, value)
}

exports.unsetEnv = function unsetEnv(name) {
  validateString(name, 'Name')

  binding.unsetEnv(name)
}

function validateString(value, name) {
  if (typeof value !== 'string') {
    throw new TypeError(`${name} must be a string. Received type ${typeof value} (${value})`)
  }
}

function validateInteger(value, name) {
  if (!Number.isInteger(value)) {
    throw new TypeError(`${name} must be an integer. Received type ${typeof value} (${value})`)
  }
}
const binding = require('../binding')

module.exports = {
  signals: binding.signals,
  errnos: binding.errnos,
  priority: binding.priority
}
module.exports = class OSError extends Error {
  constructor(msg, fn = OSError, code = fn.name) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'OSError'
  }

  static UNKNOWN_SIGNAL(msg) {
    return new OSError(msg, OSError.UNKNOWN_SIGNAL)
  }

  static TITLE_OVERFLOW(msg) {
    return new OSError(msg, OSError.TITLE_OVERFLOW)
  }
}
{
  "name": "bare-os",
  "version": "3.9.3",
  "description": "Operating system utilities for Bare",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    },
    "./errors": {
      "types": "./lib/errors.d.ts",
      "default": "./lib/errors.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-os.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-os/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-os#readme",
  "engines": {
    "bare": ">=1.14.0"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "cmake-bare": "^1.1.6",
    "lunte": "^1.6.0",
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
// This export SHOULD NOT be shortened in any way as having the full
// `module.exports = require(...)` statement is crucial for synthesizing
// ESM exports.

if (Bare.platform === 'win32') {
  module.exports = require('./lib/win32')
} else {
  module.exports = require('./lib/posix')
}
module.exports = {
  CHAR_UPPERCASE_A: 0x41,
  CHAR_LOWERCASE_A: 0x61,
  CHAR_UPPERCASE_Z: 0x5a,
  CHAR_LOWERCASE_Z: 0x7a,
  CHAR_DOT: 0x2e,
  CHAR_FORWARD_SLASH: 0x2f,
  CHAR_BACKWARD_SLASH: 0x5c,
  CHAR_COLON: 0x3a,
  CHAR_QUESTION_MARK: 0x3f
}
const os = require('bare-os')

const { normalizeString } = require('./shared')
const { CHAR_DOT, CHAR_FORWARD_SLASH } = require('./constants')

function isPosixPathSeparator(code) {
  return code === CHAR_FORWARD_SLASH
}

exports.win32 = require('./win32')
exports.posix = exports

exports.sep = '/'
exports.delimiter = ':'

exports.resolve = function resolve(...args) {
  let resolvedPath = ''
  let resolvedAbsolute = false

  for (let i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) {
    const path = i >= 0 ? args[i] : os.cwd()

    if (path.length === 0) {
      continue
    }

    resolvedPath = `${path}/${resolvedPath}`
    resolvedAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH
  }

  resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute, '/', isPosixPathSeparator)

  if (resolvedAbsolute) {
    return `/${resolvedPath}`
  }

  return resolvedPath.length > 0 ? resolvedPath : '.'
}

exports.normalize = function normalize(path) {
  if (path.length === 0) return '.'

  const isAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH
  const trailingSeparator = path.charCodeAt(path.length - 1) === CHAR_FORWARD_SLASH

  path = normalizeString(path, !isAbsolute, '/', isPosixPathSeparator)

  if (path.length === 0) {
    if (isAbsolute) return '/'
    return trailingSeparator ? './' : '.'
  }

  if (trailingSeparator) path += '/'

  return isAbsolute ? `/${path}` : path
}

exports.isAbsolute = function isAbsolute(path) {
  return path.length > 0 && path.charCodeAt(0) === CHAR_FORWARD_SLASH
}

exports.join = function join(...args) {
  if (args.length === 0) return '.'
  let joined
  for (let i = 0; i < args.length; ++i) {
    const arg = args[i]
    if (arg.length > 0) {
      if (joined === undefined) joined = arg
      else joined += `/${arg}`
    }
  }
  if (joined === undefined) return '.'
  return exports.normalize(joined)
}

exports.relative = function relative(from, to) {
  if (from === to) return ''

  from = exports.resolve(from)
  to = exports.resolve(to)

  if (from === to) return ''

  const fromStart = 1
  const fromEnd = from.length
  const fromLen = fromEnd - fromStart
  const toStart = 1
  const toLen = to.length - toStart

  const length = fromLen < toLen ? fromLen : toLen
  let lastCommonSep = -1
  let i = 0
  for (; i < length; i++) {
    const fromCode = from.charCodeAt(fromStart + i)
    if (fromCode !== to.charCodeAt(toStart + i)) {
      break
    } else if (fromCode === CHAR_FORWARD_SLASH) {
      lastCommonSep = i
    }
  }
  if (i === length) {
    if (toLen > length) {
      if (to.charCodeAt(toStart + i) === CHAR_FORWARD_SLASH) {
        return to.substring(toStart + i + 1)
      }
      if (i === 0) {
        return to.substring(toStart + i)
      }
    } else if (fromLen > length) {
      if (from.charCodeAt(fromStart + i) === CHAR_FORWARD_SLASH) {
        lastCommonSep = i
      } else if (i === 0) {
        lastCommonSep = 0
      }
    }
  }

  let out = ''
  for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
    if (i === fromEnd || from.charCodeAt(i) === CHAR_FORWARD_SLASH) {
      out += out.length === 0 ? '..' : '/..'
    }
  }

  return `${out}${to.substring(toStart + lastCommonSep)}`
}

exports.toNamespacedPath = function toNamespacedPath(path) {
  return path
}

exports.dirname = function dirname(path) {
  if (path.length === 0) return '.'
  const hasRoot = path.charCodeAt(0) === CHAR_FORWARD_SLASH
  let end = -1
  let matchedSlash = true
  for (let i = path.length - 1; i >= 1; --i) {
    if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) {
      if (!matchedSlash) {
        end = i
        break
      }
    } else {
      matchedSlash = false
    }
  }

  if (end === -1) return hasRoot ? '/' : '.'
  if (hasRoot && end === 1) return '//'
  return path.substring(0, end)
}

exports.basename = function basename(path, suffix) {
  let start = 0
  let end = -1
  let matchedSlash = true

  if (suffix !== undefined && suffix.length > 0 && suffix.length <= path.length) {
    if (suffix === path) {
      return ''
    }
    let extIdx = suffix.length - 1
    let firstNonSlashEnd = -1
    for (let i = path.length - 1; i >= 0; --i) {
      const code = path.charCodeAt(i)
      if (code === CHAR_FORWARD_SLASH) {
        if (!matchedSlash) {
          start = i + 1
          break
        }
      } else {
        if (firstNonSlashEnd === -1) {
          matchedSlash = false
          firstNonSlashEnd = i + 1
        }
        if (extIdx >= 0) {
          if (code === suffix.charCodeAt(extIdx)) {
            if (--extIdx === -1) {
              end = i
            }
          } else {
            extIdx = -1
            end = firstNonSlashEnd
          }
        }
      }
    }

    if (start === end) end = firstNonSlashEnd
    else if (end === -1) end = path.length
    return path.substring(start, end)
  }

  for (let i = path.length - 1; i >= 0; --i) {
    if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) {
      if (!matchedSlash) {
        start = i + 1
        break
      }
    } else if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
  }

  if (end === -1) return ''
  return path.substring(start, end)
}

exports.extname = function extname(path) {
  let startDot = -1
  let startPart = 0
  let end = -1
  let matchedSlash = true
  let preDotState = 0
  for (let i = path.length - 1; i >= 0; --i) {
    const code = path.charCodeAt(i)
    if (code === CHAR_FORWARD_SLASH) {
      if (!matchedSlash) {
        startPart = i + 1
        break
      }
      continue
    }
    if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
    if (code === CHAR_DOT) {
      if (startDot === -1) startDot = i
      else if (preDotState !== 1) preDotState = 1
    } else if (startDot !== -1) {
      preDotState = -1
    }
  }

  if (
    startDot === -1 ||
    end === -1 ||
    preDotState === 0 ||
    (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1)
  ) {
    return ''
  }
  return path.substring(startDot, end)
}
const { CHAR_DOT, CHAR_FORWARD_SLASH } = require('./constants')

exports.normalizeString = function normalizeString(
  path,
  allowAboveRoot,
  separator,
  isPathSeparator
) {
  let res = ''
  let lastSegmentLength = 0
  let lastSlash = -1
  let dots = 0
  let code = 0
  for (let i = 0; i <= path.length; ++i) {
    if (i < path.length) {
      code = path.charCodeAt(i)
    } else if (isPathSeparator(code)) {
      break
    } else {
      code = CHAR_FORWARD_SLASH
    }

    if (isPathSeparator(code)) {
      if (lastSlash === i - 1 || dots === 1);
      else if (dots === 2) {
        if (
          res.length < 2 ||
          lastSegmentLength !== 2 ||
          res.charCodeAt(res.length - 1) !== CHAR_DOT ||
          res.charCodeAt(res.length - 2) !== CHAR_DOT
        ) {
          if (res.length > 2) {
            const lastSlashIndex = res.lastIndexOf(separator)
            if (lastSlashIndex === -1) {
              res = ''
              lastSegmentLength = 0
            } else {
              res = res.substring(0, lastSlashIndex)
              lastSegmentLength = res.length - 1 - res.lastIndexOf(separator)
            }
            lastSlash = i
            dots = 0
            continue
          } else if (res.length !== 0) {
            res = ''
            lastSegmentLength = 0
            lastSlash = i
            dots = 0
            continue
          }
        }
        if (allowAboveRoot) {
          res += res.length > 0 ? `${separator}..` : '..'
          lastSegmentLength = 2
        }
      } else {
        if (res.length > 0) {
          res += `${separator}${path.substring(lastSlash + 1, i)}`
        } else {
          res = path.substring(lastSlash + 1, i)
        }
        lastSegmentLength = i - lastSlash - 1
      }
      lastSlash = i
      dots = 0
    } else if (code === CHAR_DOT && dots !== -1) {
      ++dots
    } else {
      dots = -1
    }
  }
  return res
}
const os = require('bare-os')

const { normalizeString } = require('./shared')
const {
  CHAR_UPPERCASE_A,
  CHAR_LOWERCASE_A,
  CHAR_UPPERCASE_Z,
  CHAR_LOWERCASE_Z,
  CHAR_DOT,
  CHAR_FORWARD_SLASH,
  CHAR_BACKWARD_SLASH,
  CHAR_COLON,
  CHAR_QUESTION_MARK
} = require('./constants')

function isWindowsPathSeparator(code) {
  return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH
}

function isWindowsDeviceRoot(code) {
  return (
    (code >= CHAR_UPPERCASE_A && code <= CHAR_UPPERCASE_Z) ||
    (code >= CHAR_LOWERCASE_A && code <= CHAR_LOWERCASE_Z)
  )
}

exports.posix = require('./posix')
exports.win32 = exports

exports.sep = '\\'
exports.delimiter = ';'

exports.resolve = function resolve(...args) {
  let resolvedDevice = ''
  let resolvedTail = ''
  let resolvedAbsolute = false

  for (let i = args.length - 1; i >= -1; i--) {
    let path
    if (i >= 0) {
      path = args[i]

      if (path.length === 0) continue
    } else if (resolvedDevice.length === 0) {
      path = os.cwd()
    } else {
      path = os.getEnv(`=${resolvedDevice}`) || os.cwd()

      if (
        path === undefined ||
        (path.substring(0, 2).toLowerCase() !== resolvedDevice.toLowerCase() &&
          path.charCodeAt(2) === CHAR_BACKWARD_SLASH)
      ) {
        path = `${resolvedDevice}\\`
      }
    }

    const len = path.length
    let rootEnd = 0
    let device = ''
    let isAbsolute = false
    const code = path.charCodeAt(0)

    if (len === 1) {
      if (isWindowsPathSeparator(code)) {
        rootEnd = 1
        isAbsolute = true
      }
    } else if (isWindowsPathSeparator(code)) {
      isAbsolute = true

      if (isWindowsPathSeparator(path.charCodeAt(1))) {
        let j = 2
        let last = j
        while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
          j++
        }
        if (j < len && j !== last) {
          const firstPart = path.substring(last, j)
          last = j
          while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
            j++
          }
          if (j < len && j !== last) {
            last = j
            while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
              j++
            }
            if (j === len || j !== last) {
              device = `\\\\${firstPart}\\${path.substring(last, j)}`
              rootEnd = j
            }
          }
        }
      } else {
        rootEnd = 1
      }
    } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
      device = path.substring(0, 2)
      rootEnd = 2
      if (len > 2 && isWindowsPathSeparator(path.charCodeAt(2))) {
        isAbsolute = true
        rootEnd = 3
      }
    }

    if (device.length > 0) {
      if (resolvedDevice.length > 0) {
        if (device.toLowerCase() !== resolvedDevice.toLowerCase()) {
          continue
        }
      } else {
        resolvedDevice = device
      }
    }

    if (resolvedAbsolute) {
      if (resolvedDevice.length > 0) {
        break
      }
    } else {
      resolvedTail = `${path.substring(rootEnd)}\\${resolvedTail}`
      resolvedAbsolute = isAbsolute
      if (isAbsolute && resolvedDevice.length > 0) {
        break
      }
    }
  }

  resolvedTail = normalizeString(resolvedTail, !resolvedAbsolute, '\\', isWindowsPathSeparator)

  return resolvedAbsolute
    ? `${resolvedDevice}\\${resolvedTail}`
    : `${resolvedDevice}${resolvedTail}` || '.'
}

exports.normalize = function normalize(path) {
  const len = path.length
  if (len === 0) return '.'
  let rootEnd = 0
  let device
  let isAbsolute = false
  const code = path.charCodeAt(0)

  if (len === 1) {
    return code === CHAR_FORWARD_SLASH ? '\\' : path
  }

  if (isWindowsPathSeparator(code)) {
    isAbsolute = true

    if (isWindowsPathSeparator(path.charCodeAt(1))) {
      let j = 2
      let last = j
      while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
        j++
      }
      if (j < len && j !== last) {
        const firstPart = path.substring(last, j)
        last = j
        while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
          j++
        }
        if (j < len && j !== last) {
          last = j
          while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
            j++
          }
          if (j === len) {
            return `\\\\${firstPart}\\${path.substring(last)}\\`
          }
          if (j !== last) {
            device = `\\\\${firstPart}\\${path.substring(last, j)}`
            rootEnd = j
          }
        }
      }
    } else {
      rootEnd = 1
    }
  } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
    device = path.substring(0, 2)
    rootEnd = 2
    if (len > 2 && isWindowsPathSeparator(path.charCodeAt(2))) {
      isAbsolute = true
      rootEnd = 3
    }
  }

  let tail =
    rootEnd < len
      ? normalizeString(path.substring(rootEnd), !isAbsolute, '\\', isWindowsPathSeparator)
      : ''
  if (tail.length === 0 && !isAbsolute) {
    tail = '.'
  }
  if (tail.length > 0 && isWindowsPathSeparator(path.charCodeAt(len - 1))) {
    tail += '\\'
  }
  if (device === undefined) {
    return isAbsolute ? `\\${tail}` : tail
  }
  return isAbsolute ? `${device}\\${tail}` : `${device}${tail}`
}

exports.isAbsolute = function isAbsolute(path) {
  const len = path.length
  if (len === 0) return false

  const code = path.charCodeAt(0)

  return (
    isWindowsPathSeparator(code) ||
    (len > 2 &&
      isWindowsDeviceRoot(code) &&
      path.charCodeAt(1) === CHAR_COLON &&
      isWindowsPathSeparator(path.charCodeAt(2)))
  )
}

exports.join = function join(...args) {
  if (args.length === 0) return '.'

  let joined
  let firstPart
  for (let i = 0; i < args.length; ++i) {
    const arg = args[i]
    if (arg.length > 0) {
      if (joined === undefined) joined = firstPart = arg
      else joined += `\\${arg}`
    }
  }

  if (joined === undefined) return '.'

  let needsReplace = true
  let slashCount = 0
  if (isWindowsPathSeparator(firstPart.charCodeAt(0))) {
    ++slashCount
    const firstLen = firstPart.length
    if (firstLen > 1 && isWindowsPathSeparator(firstPart.charCodeAt(1))) {
      ++slashCount
      if (firstLen > 2) {
        if (isWindowsPathSeparator(firstPart.charCodeAt(2))) {
          ++slashCount
        } else {
          needsReplace = false
        }
      }
    }
  }
  if (needsReplace) {
    while (slashCount < joined.length && isWindowsPathSeparator(joined.charCodeAt(slashCount))) {
      slashCount++
    }

    if (slashCount >= 2) {
      joined = `\\${joined.substring(slashCount)}`
    }
  }

  return exports.normalize(joined)
}

exports.relative = function relative(from, to) {
  if (from === to) return ''

  const fromOrig = exports.resolve(from)
  const toOrig = exports.resolve(to)

  if (fromOrig === toOrig) return ''

  from = fromOrig.toLowerCase()
  to = toOrig.toLowerCase()

  if (from === to) return ''

  let fromStart = 0
  while (fromStart < from.length && from.charCodeAt(fromStart) === CHAR_BACKWARD_SLASH) {
    fromStart++
  }
  let fromEnd = from.length
  while (fromEnd - 1 > fromStart && from.charCodeAt(fromEnd - 1) === CHAR_BACKWARD_SLASH) {
    fromEnd--
  }
  const fromLen = fromEnd - fromStart

  let toStart = 0
  while (toStart < to.length && to.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) {
    toStart++
  }
  let toEnd = to.length
  while (toEnd - 1 > toStart && to.charCodeAt(toEnd - 1) === CHAR_BACKWARD_SLASH) {
    toEnd--
  }
  const toLen = toEnd - toStart

  const length = fromLen < toLen ? fromLen : toLen
  let lastCommonSep = -1
  let i = 0
  for (; i < length; i++) {
    const fromCode = from.charCodeAt(fromStart + i)
    if (fromCode !== to.charCodeAt(toStart + i)) {
      break
    } else if (fromCode === CHAR_BACKWARD_SLASH) {
      lastCommonSep = i
    }
  }

  if (i !== length) {
    if (lastCommonSep === -1) return toOrig
  } else {
    if (toLen > length) {
      if (to.charCodeAt(toStart + i) === CHAR_BACKWARD_SLASH) {
        return toOrig.substring(toStart + i + 1)
      }
      if (i === 2) {
        return toOrig.substring(toStart + i)
      }
    }
    if (fromLen > length) {
      if (from.charCodeAt(fromStart + i) === CHAR_BACKWARD_SLASH) {
        lastCommonSep = i
      } else if (i === 2) {
        lastCommonSep = 3
      }
    }
    if (lastCommonSep === -1) lastCommonSep = 0
  }

  let out = ''
  for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
    if (i === fromEnd || from.charCodeAt(i) === CHAR_BACKWARD_SLASH) {
      out += out.length === 0 ? '..' : '\\..'
    }
  }

  toStart += lastCommonSep

  if (out.length > 0) {
    return `${out}${toOrig.substring(toStart, toEnd)}`
  }
  if (toOrig.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) {
    ++toStart
  }
  return toOrig.substring(toStart, toEnd)
}

exports.toNamespacedPath = function toNamespacedPath(path) {
  if (path.length === 0) return path

  const resolvedPath = exports.resolve(path)

  if (resolvedPath.length <= 2) return path

  if (resolvedPath.charCodeAt(0) === CHAR_BACKWARD_SLASH) {
    if (resolvedPath.charCodeAt(1) === CHAR_BACKWARD_SLASH) {
      const code = resolvedPath.charCodeAt(2)
      if (code !== CHAR_QUESTION_MARK && code !== CHAR_DOT) {
        return `\\\\?\\UNC\\${resolvedPath.substring(2)}`
      }
    }
  } else if (
    isWindowsDeviceRoot(resolvedPath.charCodeAt(0)) &&
    resolvedPath.charCodeAt(1) === CHAR_COLON &&
    resolvedPath.charCodeAt(2) === CHAR_BACKWARD_SLASH
  ) {
    return `\\\\?\\${resolvedPath}`
  }

  return path
}

exports.dirname = function dirname(path) {
  const len = path.length
  if (len === 0) return '.'
  let rootEnd = -1
  let offset = 0
  const code = path.charCodeAt(0)

  if (len === 1) {
    return isWindowsPathSeparator(code) ? path : '.'
  }

  if (isWindowsPathSeparator(code)) {
    rootEnd = offset = 1

    if (isWindowsPathSeparator(path.charCodeAt(1))) {
      let j = 2
      let last = j
      while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
        j++
      }
      if (j < len && j !== last) {
        last = j
        while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
          j++
        }
        if (j < len && j !== last) {
          last = j
          while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
            j++
          }
          if (j === len) {
            return path
          }
          if (j !== last) {
            rootEnd = offset = j + 1
          }
        }
      }
    }
  } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
    rootEnd = len > 2 && isWindowsPathSeparator(path.charCodeAt(2)) ? 3 : 2
    offset = rootEnd
  }

  let end = -1
  let matchedSlash = true
  for (let i = len - 1; i >= offset; --i) {
    if (isWindowsPathSeparator(path.charCodeAt(i))) {
      if (!matchedSlash) {
        end = i
        break
      }
    } else {
      matchedSlash = false
    }
  }

  if (end === -1) {
    if (rootEnd === -1) return '.'

    end = rootEnd
  }
  return path.substring(0, end)
}

exports.basename = function basename(path, suffix) {
  let start = 0
  let end = -1
  let matchedSlash = true

  if (
    path.length >= 2 &&
    isWindowsDeviceRoot(path.charCodeAt(0)) &&
    path.charCodeAt(1) === CHAR_COLON
  ) {
    start = 2
  }

  if (suffix !== undefined && suffix.length > 0 && suffix.length <= path.length) {
    if (suffix === path) return ''
    let extIdx = suffix.length - 1
    let firstNonSlashEnd = -1
    for (let i = path.length - 1; i >= start; --i) {
      const code = path.charCodeAt(i)
      if (isWindowsPathSeparator(code)) {
        if (!matchedSlash) {
          start = i + 1
          break
        }
      } else {
        if (firstNonSlashEnd === -1) {
          matchedSlash = false
          firstNonSlashEnd = i + 1
        }
        if (extIdx >= 0) {
          if (code === suffix.charCodeAt(extIdx)) {
            if (--extIdx === -1) {
              end = i
            }
          } else {
            extIdx = -1
            end = firstNonSlashEnd
          }
        }
      }
    }

    if (start === end) end = firstNonSlashEnd
    else if (end === -1) end = path.length
    return path.substring(start, end)
  }
  for (let i = path.length - 1; i >= start; --i) {
    if (isWindowsPathSeparator(path.charCodeAt(i))) {
      if (!matchedSlash) {
        start = i + 1
        break
      }
    } else if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
  }

  if (end === -1) return ''
  return path.substring(start, end)
}

exports.extname = function extname(path) {
  let start = 0
  let startDot = -1
  let startPart = 0
  let end = -1
  let matchedSlash = true
  let preDotState = 0

  if (
    path.length >= 2 &&
    path.charCodeAt(1) === CHAR_COLON &&
    isWindowsDeviceRoot(path.charCodeAt(0))
  ) {
    start = startPart = 2
  }

  for (let i = path.length - 1; i >= start; --i) {
    const code = path.charCodeAt(i)
    if (isWindowsPathSeparator(code)) {
      if (!matchedSlash) {
        startPart = i + 1
        break
      }
      continue
    }
    if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
    if (code === CHAR_DOT) {
      if (startDot === -1) startDot = i
      else if (preDotState !== 1) preDotState = 1
    } else if (startDot !== -1) {
      preDotState = -1
    }
  }

  if (
    startDot === -1 ||
    end === -1 ||
    preDotState === 0 ||
    (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1)
  ) {
    return ''
  }
  return path.substring(startDot, end)
}
{
  "name": "bare-path",
  "version": "3.0.1",
  "description": "Path manipulation library for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./posix": "./lib/posix.js",
    "./win32": "./lib/win32.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "lib",
    "NOTICE"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-path.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-path/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-path#readme",
  "dependencies": {
    "bare-os": "^3.0.1"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "lunte": "^1.8.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
const b4a = require('b4a')
const stream = require('streamx')
const { ReadableStream, WritableStream } = require('./web')

const defaultEncoding = 'utf8'

module.exports = exports = stream.Stream

exports.pipeline = stream.pipeline

exports.isStream = stream.isStream
exports.isEnding = stream.isEnding
exports.isEnded = stream.isEnded
exports.isFinishing = stream.isFinishing
exports.isFinished = stream.isFinished
exports.isDisturbed = stream.isDisturbed

exports.isErrored = function isErrored(stream) {
  return exports.getStreamError(stream) !== null
}

exports.isReadable = function isReadable(stream) {
  return stream.readable && !stream.destroying && !exports.isEnded(stream)
}

exports.isWritable = function isWritable(stream) {
  return stream.writable && !stream.destroying && !exports.isFinishing(stream)
}

exports.getStreamError = stream.getStreamError

exports.addAbortSignal = function addAbortSignal(signal, stream) {
  function onAbort() {
    stream.destroy(signal.reason)
  }

  if (signal.aborted) onAbort()
  else signal.addEventListener('abort', onAbort)

  return stream
}

exports.Stream = exports

exports.Readable = class Readable extends stream.Readable {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthReadable: null,
      map: null,
      mapReadable: null
    })

    if (this._construct) this._open = this._construct

    if (this._read !== stream.Readable.prototype._read) {
      this._read = read.bind(this, this._read)
    }

    if (this._destroy !== stream.Stream.prototype._destroy) {
      this._destroy = destroy.bind(this, this._destroy)
    }
  }

  get closed() {
    return !exports.isReadable(this)
  }

  get errored() {
    return stream.getStreamError(this)
  }

  push(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    return super.push(chunk)
  }

  unshift(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    super.unshift(chunk)
  }

  static fromWeb(readableStream, opts = {}) {
    const stream = readableStream._stream

    if (opts.encoding) stream.setEncoding(opts.encoding)
    if (opts.signal) exports.addAbortSignal(opts.signal, stream)

    return stream
  }

  static toWeb(readable, opts = {}) {
    return new ReadableStream(readable, opts.strategy)
  }

  async [Symbol.asyncDispose]() {
    if (!this.destroyed) this.destroy()

    await new Promise((resolve) => exports.finished(this, resolve))
  }
}

exports.Writable = class Writable extends stream.Writable {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthWritable,
      map: null,
      mapWritable: null
    })

    if (this._construct) this._open = this._construct

    if (this._write !== stream.Writable.prototype._write) {
      this._write = write.bind(this, this._write)
    }

    if (this._destroy !== stream.Stream.prototype._destroy) {
      this._destroy = destroy.bind(this, this._destroy)
    }
  }

  get closed() {
    return !exports.isWritable(this)
  }

  get errored() {
    return stream.getStreamError(this)
  }

  write(chunk, encoding, cb) {
    if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result = super.write({ chunk, encoding })

    if (cb) stream.Writable.drained(this).then(() => cb(null), cb)

    return result
  }

  end(chunk, encoding, cb) {
    if (typeof chunk === 'function') {
      cb = chunk
      chunk = null
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    } else {
      encoding = 'buffer'
    }

    const result =
      chunk !== undefined && chunk !== null ? super.end({ chunk, encoding }) : super.end()

    if (cb) this.once('finish', () => cb(null))

    return result
  }

  static fromWeb(writableStream, opts = {}) {
    const stream = writableStream._stream

    if (opts.signal) exports.addAbortSignal(opts.signal, stream)

    return stream
  }

  static toWeb(writable) {
    return new WritableStream(writable)
  }

  async [Symbol.asyncDispose]() {
    if (!this.destroyed) this.destroy()

    await new Promise((resolve) => exports.finished(this, resolve))
  }
}

exports.Duplex = class Duplex extends stream.Duplex {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthReadable: null,
      byteLengthWritable,
      map: null,
      mapReadable: null,
      mapWritable: null
    })

    if (this._construct) this._open = this._construct

    if (this._read !== stream.Readable.prototype._read) {
      this._read = read.bind(this, this._read)
    }

    if (this._write !== stream.Duplex.prototype._write) {
      this._write = write.bind(this, this._write)
    }

    if (this._destroy !== stream.Stream.prototype._destroy) {
      this._destroy = destroy.bind(this, this._destroy)
    }
  }

  push(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    return super.push(chunk)
  }

  unshift(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    super.unshift(chunk)
  }

  write(chunk, encoding, cb) {
    if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result = super.write({ chunk, encoding })

    if (cb) stream.Writable.drained(this).then(() => cb(null), cb)

    return result
  }

  end(chunk, encoding, cb) {
    if (typeof chunk === 'function') {
      cb = chunk
      chunk = null
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result =
      chunk !== undefined && chunk !== null ? super.end({ chunk, encoding }) : super.end()

    if (cb) this.once('finish', () => cb(null))

    return result
  }

  static fromWeb({ readable: readableStream, writable: writableStream }, opts) {
    const readable = exports.Readable.fromWeb(readableStream, opts)
    const writable = exports.Writable.fromWeb(writableStream, opts)

    const duplex = new exports.Duplex({
      write(data, encoding, cb) {
        writable.write(data, encoding, cb)
      }
    })

    readable
      .on('data', (data) => duplex.push(data))
      .on('end', () => duplex.push(null))
      .on('error', (err) => duplex.destroy(err))

    writable.on('finish', () => duplex.end()).on('error', (err) => duplex.destroy(err))

    return duplex
  }

  static toWeb(duplex) {
    const readableStream = exports.Readable.toWeb(duplex)
    const writableStream = exports.Writable.toWeb(duplex)

    return { readable: readableStream, writable: writableStream }
  }
}

class DuplexSide extends exports.Duplex {
  constructor(opts) {
    super(opts)

    this._otherSide = null
    this._cb = null
  }

  _read() {
    const cb = this._cb
    if (!cb) return

    this._cb = null
    cb()
  }

  _write(chunk, encoding, cb) {
    this._otherSide.push(chunk, encoding)
    this._otherSide._cb = cb
  }

  _final(cb) {
    this._otherSide.on('end', cb)
    this._otherSide.push(null)
  }
}

exports.duplexPair = function duplexPair(opts) {
  const sideA = new DuplexSide(opts)
  const sideB = new DuplexSide(opts)

  sideA._otherSide = sideB
  sideB._otherSide = sideA

  return [sideA, sideB]
}

exports.Transform = class Transform extends stream.Transform {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthReadable: null,
      byteLengthWritable,
      map: null,
      mapReadable: null,
      mapWritable: null
    })

    if (this._transform !== stream.Transform.prototype._transform) {
      this._transform = transform.bind(this, this._transform)
    } else {
      this._transform = passthrough
    }
  }

  push(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    return super.push(chunk)
  }

  unshift(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    super.unshift(chunk)
  }

  write(chunk, encoding, cb) {
    if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result = super.write({ chunk, encoding })

    if (cb) stream.Writable.drained(this).then(() => cb(null), cb)

    return result
  }

  end(chunk, encoding, cb) {
    if (typeof chunk === 'function') {
      cb = chunk
      chunk = null
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result =
      chunk !== undefined && chunk !== null ? super.end({ chunk, encoding }) : super.end()

    if (cb) this.once('finish', () => cb(null))

    return result
  }
}

exports.PassThrough = class PassThrough extends exports.Transform {}

exports.finished = function finished(stream, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (!opts) opts = {}

  const { cleanup = false } = opts

  const done = () => {
    cb(exports.getStreamError(stream, { all: true }))

    if (cleanup) detach()
  }

  const detach = () => {
    stream.off('close', done)
    stream.off('error', noop)
  }

  if (stream.destroyed) {
    done()
  } else {
    stream.on('close', done)
    stream.on('error', noop)
  }

  return detach
}

function read(read, cb) {
  read.call(this, 65536)

  cb(null)
}

function write(write, data, cb) {
  write.call(this, data.chunk, data.encoding, cb)
}

function transform(transform, data, cb) {
  transform.call(this, data.chunk, data.encoding, cb)
}

function destroy(destroy, cb) {
  destroy.call(this, exports.getStreamError(this), cb)
}

function passthrough(data, cb) {
  cb(null, data.chunk)
}

function byteLengthWritable(data) {
  return data.chunk.byteLength
}

function noop() {}
{
  "name": "bare-stream",
  "version": "2.13.3",
  "description": "Streaming data for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./promises": "./promises.js",
    "./web": {
      "types": "./web.d.ts",
      "default": "./web.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "promises.js",
    "web.js",
    "web.d.ts",
    "global.js",
    "global.d.ts"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-stream.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-stream/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-stream#readme",
  "dependencies": {
    "b4a": "^1.8.1",
    "streamx": "^2.25.0",
    "teex": "^1.0.1"
  },
  "devDependencies": {
    "bare-abort-controller": "^1.1.0",
    "bare-buffer": "^3.0.0",
    "bare-events": "^2.5.4",
    "brittle": "^3.5.2",
    "lunte": "^1.6.0",
    "prettier": "^3.3.3",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "bare-abort-controller": "*",
    "bare-buffer": "*",
    "bare-events": "*"
  },
  "peerDependenciesMeta": {
    "bare-abort-controller": {
      "optional": true
    },
    "bare-buffer": {
      "optional": true
    },
    "bare-events": {
      "optional": true
    }
  }
}
const { Readable, Writable, Transform, getStreamError, isStreamx, isDisturbed } = require('streamx')
const tee = require('teex')

const readableKind = Symbol.for('bare.stream.readable.kind')
const writableKind = Symbol.for('bare.stream.writable.kind')
const transformKind = Symbol.for('bare.stream.transform.kind')

// https://streams.spec.whatwg.org/#readablestreamdefaultreader
exports.ReadableStreamDefaultReader = class ReadableStreamDefaultReader {
  constructor(stream) {
    this._stream = stream
    this._stream._stream.once('close', onclose).once('error', onerror)

    const closed = Promise.withResolvers()

    // Avoid unhandled exceptions
    closed.promise.catch(noop)

    this._closed = closed

    function onclose() {
      closed.resolve()
    }

    function onerror(err) {
      closed.reject(err)
    }
  }

  get closed() {
    return this._closed.promise
  }

  read() {
    const stream = this._stream._stream

    return new Promise((resolve, reject) => {
      const err = getStreamError(stream)

      if (err) return reject(err)

      if (stream.destroyed) {
        return resolve({ value: undefined, done: true })
      }

      const value = stream.read()

      if (value !== null) {
        return resolve({ value, done: false })
      }

      stream.once('readable', onreadable).once('close', onclose).once('error', onerror)

      function onreadable() {
        const value = stream.read()

        ondone(null, value === null ? { value: undefined, done: true } : { value, done: false })
      }

      function onclose() {
        ondone(null, { value: undefined, done: true })
      }

      function onerror(err) {
        ondone(err, null)
      }

      function ondone(err, value) {
        stream.off('readable', onreadable).off('close', onclose).off('error', onerror)

        if (err) reject(err)
        else resolve(value)
      }
    })
  }

  releaseLock() {
    this._closed.reject(new TypeError('Reader was released'))
    this._stream._releaseLock()
    this._stream = null
  }

  cancel(reason = new TypeError('Stream was cancelled')) {
    const stream = this._stream._stream

    if (stream.destroyed) return Promise.resolve()

    return new Promise((resolve) =>
      stream.once('close', resolve).once('error', noop).destroy(reason)
    )
  }
}

// https://streams.spec.whatwg.org/#readablestreamdefaultcontroller
exports.ReadableStreamDefaultController = class ReadableStreamDefaultController {
  constructor(stream) {
    this._stream = stream
  }

  get desiredSize() {
    const stream = this._stream._stream

    return stream._readableState.highWaterMark - stream._readableState.buffered
  }

  enqueue(data) {
    this._stream._stream.push(data)
  }

  close() {
    this._stream._stream.push(null)
  }

  error(err) {
    this._stream._stream.destroy(err)
  }
}

// https://streams.spec.whatwg.org/#readablestream
class ReadableStream {
  static get [readableKind]() {
    return 0 // Compatibility version
  }

  static from(iterable) {
    return new ReadableStream(Readable.from(iterable))
  }

  constructor(underlyingSource = {}, queuingStrategy) {
    if (isStreamx(underlyingSource)) {
      this._stream = underlyingSource
    } else {
      if (queuingStrategy === undefined) {
        queuingStrategy = new exports.CountQueuingStrategy()
      }

      const { start, pull, cancel } = underlyingSource
      const { highWaterMark = 1, size = defaultSize } = queuingStrategy

      this._stream = new Readable({ highWaterMark, byteLength: size })

      const controller = new exports.ReadableStreamDefaultController(this)

      try {
        let starting = Promise.resolve()

        if (start) starting = forwardError(start.call(this, controller), controller)

        if (pull) {
          this._stream._read = this._read.bind(this, starting, pull.bind(this, controller))
        }

        if (cancel) {
          this._stream.once('error', cancel.bind(this))
        }
      } catch (err) {
        controller.error(err)
      }
    }

    this._reader = null
  }

  get [readableKind]() {
    return ReadableStream[readableKind]
  }

  get locked() {
    return this._reader !== null
  }

  getReader() {
    if (this.locked) throw new TypeError('Stream is locked')

    this._reader = new exports.ReadableStreamDefaultReader(this)

    return this._reader
  }

  cancel(reason = new TypeError('Stream was cancelled')) {
    const stream = this._stream

    if (stream.destroyed) return Promise.resolve()

    if (this.locked) return Promise.reject(new TypeError('Stream is locked'))

    return new Promise((resolve) =>
      stream.once('close', resolve).once('error', noop).destroy(reason)
    )
  }

  tee() {
    const [a, b] = tee(this._stream)

    return [new ReadableStream(a), new ReadableStream(b)]
  }

  pipeTo(destination) {
    return new Promise((resolve, reject) =>
      this._stream.pipe(destination._stream, (err) => {
        err ? reject(err) : resolve()
      })
    )
  }

  [Symbol.asyncIterator]() {
    return this._stream[Symbol.asyncIterator]()
  }

  _releaseLock() {
    this._reader = null
  }

  async _read(starting, pull, cb) {
    await starting

    let err = null
    try {
      await pull()
    } catch (e) {
      err = e
    }
    cb(err)
  }
}

function defaultSize() {
  return 1
}

exports.ReadableStream = ReadableStream

// https://streams.spec.whatwg.org/#countqueuingstrategy
exports.CountQueuingStrategy = class CountQueuingStrategy {
  constructor(opts = {}) {
    const { highWaterMark = 1 } = opts

    this.highWaterMark = highWaterMark
  }

  size(chunk) {
    return 1
  }
}

// https://streams.spec.whatwg.org/#bytelengthqueuingstrategy
exports.ByteLengthQueuingStrategy = class ByteLengthQueuingStrategy {
  constructor(opts = {}) {
    const { highWaterMark = 16384 } = opts

    this.highWaterMark = highWaterMark
  }

  size(chunk) {
    return chunk.byteLength
  }
}

exports.isReadableStream = function isReadableStream(value) {
  if (value instanceof ReadableStream) return true

  return (
    typeof value === 'object' &&
    value !== null &&
    value[readableKind] === ReadableStream[readableKind]
  )
}

// https://streams.spec.whatwg.org/#readablestream-errored
exports.isReadableStreamErrored = function isReadableStreamErrored(stream) {
  return getStreamError(stream._stream) !== null
}

// https://streams.spec.whatwg.org/#is-readable-stream-disturbed
exports.isReadableStreamDisturbed = function isReadableStreamDisturbed(stream) {
  return isDisturbed(stream._stream)
}

// https://streams.spec.whatwg.org/#writablestreamdefaultwriter
exports.WritableStreamDefaultWriter = class WritableStreamDefaultWriter {
  constructor(stream) {
    this._stream = stream
    this._stream._stream.once('close', onclose).once('error', onerror)

    const closed = Promise.withResolvers()

    // Avoid unhandled exceptions
    closed.promise.catch(noop)

    this._closed = closed

    function onclose() {
      closed.resolve()
    }

    function onerror(err) {
      closed.reject(err)
    }
  }

  get desiredSize() {
    const stream = this._stream._stream

    return stream._writableState.highWaterMark - stream._writableState.buffered
  }

  get closed() {
    return this._closed.promise
  }

  get ready() {
    const stream = this._stream._stream

    if (getStreamError(stream)) return Promise.reject()

    return Writable.drained(stream).then()
  }

  async write(chunk) {
    const stream = this._stream._stream

    let err = getStreamError(stream)
    if (err) return Promise.reject(err)

    stream.write(chunk)

    await Writable.drained(stream)

    err = getStreamError(stream)
    if (err) return Promise.reject(err)
  }

  releaseLock() {
    this._closed.reject(new TypeError('Writer was released'))
    this._stream._releaseLock()
    this._stream = null
  }

  close() {
    const stream = this._stream._stream

    if (stream.destroyed) return Promise.resolve()

    return new Promise((resolve) => stream.once('close', resolve).end())
  }

  abort(reason = new TypeError('Stream was aborted')) {
    const stream = this._stream._stream

    if (stream.destroyed) return Promise.resolve()

    return new Promise((resolve) => stream.once('close', resolve).destroy(reason))
  }
}

// https://streams.spec.whatwg.org/#writablestreamdefaultcontroller
exports.WritableStreamDefaultController = class WritableStreamDefaultController {
  constructor(stream) {
    this._stream = stream
  }

  error(err) {
    this._stream._stream.destroy(err)
  }
}

// https://streams.spec.whatwg.org/#writablestream
class WritableStream {
  static get [writableKind]() {
    return 0 // Compatibility version
  }

  constructor(underlyingSink = {}, queuingStrategy = {}) {
    if (isStreamx(underlyingSink)) {
      this._stream = underlyingSink
    } else {
      if (queuingStrategy === undefined) {
        queuingStrategy = new exports.CountQueuingStrategy()
      }

      const { start, write, close, abort } = underlyingSink
      const { highWaterMark = 1, size = defaultSize } = queuingStrategy

      this._stream = new Writable({ highWaterMark, byteLength: size })

      const controller = new exports.WritableStreamDefaultController(this)

      this._controller = controller

      try {
        let starting = Promise.resolve()

        if (start) starting = forwardError(start.call(this, controller), controller)

        if (write) {
          this._stream._write = this._write.bind(this, starting, write.bind(this))
        }

        if (close) {
          this._stream._destroy = this._destroy.bind(this, close.call(this))
        }

        if (abort) {
          this._stream.once('error', abort.bind(this))
        }
      } catch (err) {
        controller.error(err)
      }
    }

    this._writer = null
  }

  get [writableKind]() {
    return WritableStream[writableKind]
  }

  get locked() {
    return this._writer !== null
  }

  getWriter() {
    if (this.locked) throw new TypeError('Stream is locked')

    this._writer = new exports.WritableStreamDefaultWriter(this)

    return this._writer
  }

  abort(reason = new TypeError('Stream was aborted')) {
    if (this._stream.destroyed) return Promise.resolve()

    if (this.locked) return Promise.reject(new TypeError('Stream is locked'))

    return new Promise((resolve) => this._stream.once('close', resolve).destroy(reason))
  }

  close() {
    if (this._stream.destroyed) return Promise.resolve()

    if (this.locked) return Promise.reject(new TypeError('Stream is locked'))

    return new Promise((resolve) => this._stream.once('close', resolve).end())
  }

  _releaseLock() {
    this._writer = null
  }

  async _write(starting, write, data, cb) {
    await starting

    let err = null
    try {
      await write(data, this._controller)
    } catch (e) {
      err = e
    }
    cb(err)
  }

  async _destroy(closing, cb) {
    let err = null
    try {
      await closing
    } catch (e) {
      err = e
    }
    cb(err)
  }
}

exports.WritableStream = WritableStream

exports.isWritableStream = function isWritableStream(value) {
  if (value instanceof WritableStream) return true

  return (
    typeof value === 'object' &&
    value !== null &&
    value[writableKind] === WritableStream[writableKind]
  )
}

// https://streams.spec.whatwg.org/#transformstreamdefaultcontroller
exports.TransformStreamDefaultController = class TransformStreamDefaultController {
  constructor(stream) {
    this._stream = stream
  }

  get desiredSize() {
    const stream = this._stream._stream

    return stream._readableState.highWaterMark - stream._readableState.buffered
  }

  enqueue(data) {
    this._stream._stream.push(data)
  }

  error(err) {
    this._stream._stream.destroy(err)
  }

  terminate() {
    const stream = this._stream._stream

    stream.push(null)
    stream.destroy(new TypeError('Stream has been terminated'))
  }
}

// https://streams.spec.whatwg.org/#transformstream
class TransformStream {
  static get [transformKind]() {
    return 0 // Compatibility version
  }

  constructor(transformer = {}, writableStrategy = {}, readableStrategy = {}) {
    if (isStreamx(transformer)) {
      this._stream = transformer
    } else {
      const { start, transform, flush } = transformer

      this._stream = new Transform({ ...writableStrategy, ...readableStrategy })

      const controller = new exports.TransformStreamDefaultController(this)

      this._controller = controller

      try {
        let starting = Promise.resolve()

        if (start) starting = forwardError(start.call(this, controller), controller)

        if (transform) {
          this._stream._transform = this._transform.bind(this, starting, transform.bind(this))
        }

        if (flush) {
          this._stream._flush = this._flush.bind(this, flush.call(this, this._controller))
        }
      } catch (err) {
        controller.error(err)
      }
    }

    this._writable = new WritableStream(this._stream)
    this._readable = new ReadableStream(this._stream)
  }

  get [transformKind]() {
    return TransformStream[transformKind]
  }

  get writable() {
    return this._writable
  }

  get readable() {
    return this._readable
  }

  async _transform(starting, transform, data, cb) {
    await starting

    let err = null
    try {
      await transform(data, this._controller)
    } catch (e) {
      err = e
    }
    cb(err)
  }

  async _flush(flush, cb) {
    let err = null
    try {
      await flush
    } catch (e) {
      err = e
    }
    cb(err)
  }
}

exports.TransformStream = TransformStream

exports.isTransformStream = function isTransformStream(value) {
  if (value instanceof TransformStream) return true

  return (
    typeof value === 'object' &&
    value !== null &&
    value[transformKind] === TransformStream[transformKind]
  )
}

async function forwardError(promise, controller) {
  try {
    await promise
  } catch (err) {
    controller.error(err)
  }
}

function noop() {}
module.exports = require.addon()
const binding = require('./binding')

const t = binding.constants

class Type {
  constructor(type) {
    this._type = type
  }

  isUndefined() {
    return this._type === t.UNDEFINED
  }

  isNull() {
    return this._type === t.NULL
  }

  isBoolean() {
    return this._type === t.BOOLEAN
  }

  isNumber() {
    return (this._type & 0xff) === t.NUMBER
  }

  isInt32() {
    return (this._type & (0xff | t.INT32)) === (t.NUMBER | t.INT32)
  }

  isUint32() {
    return (this._type & (0xff | t.UINT32)) === (t.NUMBER | t.UINT32)
  }

  isString() {
    return this._type === t.STRING
  }

  isSymbol() {
    return this._type === t.SYMBOL
  }

  isObject() {
    return (this._type & 0xff) === t.OBJECT
  }

  isArray() {
    return this._type === (t.OBJECT | t.ARRAY)
  }

  isArguments() {
    return this._type === (t.OBJECT | t.ARGUMENTS)
  }

  isDate() {
    return this._type === (t.OBJECT | t.DATE)
  }

  isRegExp() {
    return this._type === (t.OBJECT | t.REGEXP)
  }

  isError() {
    return this._type === (t.OBJECT | t.ERROR)
  }

  isPromise() {
    return this._type === (t.OBJECT | t.PROMISE)
  }

  isProxy() {
    return this._type === (t.OBJECT | t.PROXY)
  }

  isGenerator() {
    return this._type === (t.OBJECT | t.GENERATOR)
  }

  isMap() {
    return this._type === (t.OBJECT | t.MAP)
  }

  isSet() {
    return this._type === (t.OBJECT | t.SET)
  }

  isWeakMap() {
    return this._type === (t.OBJECT | t.WEAK_MAP)
  }

  isWeakSet() {
    return this._type === (t.OBJECT | t.WEAK_SET)
  }

  isWeakRef() {
    return this._type === (t.OBJECT | t.WEAK_REF)
  }

  isArrayBuffer() {
    return this._type === (t.OBJECT | t.ARRAYBUFFER)
  }

  isSharedArrayBuffer() {
    return this._type === (t.OBJECT | t.SHAREDARRAYBUFFER)
  }

  isTypedArray() {
    return (this._type & 0xffff) === (t.OBJECT | t.TYPEDARRAY)
  }

  isInt8Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT8ARRAY)
  }

  isUint8Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT8ARRAY)
  }

  isUint8ClampedArray() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT8CLAMPEDARRAY)
  }

  isInt16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT16ARRAY)
  }

  isUint16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT16ARRAY)
  }

  isInt32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT32ARRAY)
  }

  isUint32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT32ARRAY)
  }

  isFloat16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT16ARRAY)
  }

  isFloat32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT32ARRAY)
  }

  isFloat64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT64ARRAY)
  }

  isBigInt64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.BIGINT64ARRAY)
  }

  isBigUint64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.BIGUINT64ARRAY)
  }

  isDataView() {
    return this._type === (t.OBJECT | t.DATAVIEW)
  }

  isModuleNamespace() {
    return this._type === (t.OBJECT | t.MODULE_NAMESPACE)
  }

  isFunction() {
    return (this._type & 0xff) === t.FUNCTION
  }

  isAsyncFunction() {
    return (
      (this._type & (0xff | t.ASYNC_FUNCTION)) ===
      (t.FUNCTION | t.ASYNC_FUNCTION)
    )
  }

  isGeneratorFunction() {
    return (
      (this._type & (0xff | t.GENERATOR_FUNCTION)) ===
      (t.FUNCTION | t.GENERATOR_FUNCTION)
    )
  }

  isExternal() {
    return this._type === t.EXTERNAL
  }

  isBigInt() {
    return this._type === t.BIGINT
  }
}

module.exports = exports = function type(value) {
  switch (typeof value) {
    case 'undefined':
      return new Type(t.UNDEFINED)
    case 'boolean':
      return new Type(t.BOOLEAN)
    case 'number':
      return new Type(
        Number.isSafeInteger(value) ? binding.type(value) : t.NUMBER
      )
    case 'string':
      return new Type(t.STRING)
    case 'symbol':
      return new Type(t.SYMBOL)
    case 'object':
      return new Type(value === null ? t.NULL : binding.type(value))
    case 'function':
      return new Type(binding.type(value))
    case 'bigint':
      return new Type(t.BIGINT)
  }
}

exports.createTag = function createTag(...components) {
  const tag = new Uint32Array(4)
  for (let i = 0; i < 4; i++) tag[i] = components[i] || 0
  return tag
}

exports.addTag = function addTag(object, tag) {
  binding.addTag(object, tag)
}

exports.checkTag = function checkTag(object, tag) {
  return binding.checkTag(object, tag)
}
{
  "name": "bare-type",
  "version": "1.1.0",
  "description": "Cross-realm type predicates for Bare",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-type.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-type/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-type#readme",
  "engines": {
    "bare": ">=1.2.0"
  },
  "devDependencies": {
    "brittle": "^3.4.0",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
module.exports = require.addon()
const path = require('bare-path')
const binding = require('./binding')
const errors = require('./lib/errors')
const URLSearchParams = require('./lib/url-search-params')

const kind = Symbol.for('bare.url.kind')

const isWindows = Bare.platform === 'win32'

class URL {
  static get [kind]() {
    return 0 // Compatibility version
  }

  constructor(input, base, opts = {}) {
    if (arguments.length === 0) throw errors.INVALID_URL()

    input = String(input)

    if (base !== undefined) base = String(base)

    this._components = new Uint32Array(8)

    this._parse(input, base, opts.throw !== false)

    if (this._href) this._params = new URLSearchParams(this.search, this)
  }

  get [kind]() {
    return URL[kind]
  }

  // https://url.spec.whatwg.org/#dom-url-href

  get href() {
    return this._href
  }

  set href(value) {
    this._update(value)

    this._params._parse(this.search)
  }

  // https://url.spec.whatwg.org/#dom-url-protocol

  get protocol() {
    return this._slice(0, this._components[0]) + ':'
  }

  set protocol(value) {
    this._update(this._replace(value.replace(/:+$/, ''), 0, this._components[0]))
  }

  // https://url.spec.whatwg.org/#dom-url-username

  get username() {
    return this._slice(this._components[0] + 3 /* :// */, this._components[1])
  }

  set username(value) {
    if (cannotHaveCredentialsOrPort(this)) {
      return
    }

    if (this.username === '') value += '@'

    this._update(this._replace(value, this._components[0] + 3 /* :// */, this._components[1]))
  }

  // https://url.spec.whatwg.org/#dom-url-password

  get password() {
    return this._href.slice(this._components[1] + 1 /* : */, this._components[2] - 1 /* @ */)
  }

  set password(value) {
    if (cannotHaveCredentialsOrPort(this)) {
      return
    }

    let start = this._components[1] + 1 /* : */
    let end = this._components[2] - 1 /* @ */

    if (this.password === '') {
      value = ':' + value
      start--
    }

    if (this.username === '') {
      value += '@'
      end++
    }

    this._update(this._replace(value, start, end))
  }

  // https://url.spec.whatwg.org/#dom-url-host

  get host() {
    return this._slice(this._components[2], this._components[5])
  }

  set host(value) {
    if (hasOpaquePath(this)) {
      return
    }

    this._update(
      this._replace(value, this._components[2], this._components[value.includes(':') ? 5 : 3])
    )
  }

  // https://url.spec.whatwg.org/#dom-url-hostname

  get hostname() {
    return this._slice(this._components[2], this._components[3])
  }

  set hostname(value) {
    if (hasOpaquePath(this)) {
      return
    }

    this._update(this._replace(value, this._components[2], this._components[3]))
  }

  // https://url.spec.whatwg.org/#dom-url-port

  get port() {
    return this._slice(this._components[3] + 1 /* : */, this._components[5])
  }

  set port(value) {
    if (cannotHaveCredentialsOrPort(this)) {
      return
    }

    let start = this._components[3] + 1 /* : */

    if (this.port === '') {
      value = ':' + value
      start--
    }

    this._update(this._replace(value, start, this._components[5]))
  }

  // https://url.spec.whatwg.org/#dom-url-pathname

  get pathname() {
    return this._slice(this._components[5], this._components[6] - 1 /* ? */)
  }

  set pathname(value) {
    if (hasOpaquePath(this)) {
      return
    }

    if (value[0] !== '/' && value[0] !== '\\') {
      value = '/' + value
    }

    this._update(this._replace(value, this._components[5], this._components[6] - 1 /* ? */))
  }

  // https://url.spec.whatwg.org/#dom-url-search

  get search() {
    return this._slice(this._components[6] - 1 /* ? */, this._components[7] - 1 /* # */)
  }

  set search(value) {
    if (value && value[0] !== '?') value = '?' + value

    this._update(
      this._replace(value, this._components[6] - 1 /* ? */, this._components[7] - 1 /* # */)
    )

    this._params._parse(this.search)
  }

  // https://url.spec.whatwg.org/#dom-url-searchparams

  get searchParams() {
    return this._params
  }

  // https://url.spec.whatwg.org/#dom-url-hash

  get hash() {
    return this._slice(this._components[7] - 1 /* # */)
  }

  set hash(value) {
    if (value && value[0] !== '#') value = '#' + value

    this._update(this._replace(value, this._components[7] - 1 /* # */))
  }

  toString() {
    return this._href
  }

  toJSON() {
    return this._href
  }

  [Symbol.for('bare.inspect')]() {
    return {
      __proto__: { constructor: URL },

      href: this.href,
      protocol: this.protocol,
      username: this.username,
      password: this.password,
      host: this.host,
      hostname: this.hostname,
      port: this.port,
      pathname: this.pathname,
      search: this.search,
      searchParams: this.searchParams,
      hash: this.hash
    }
  }

  _slice(start, end = this._href.length) {
    return this._href.slice(start, end)
  }

  _replace(replacement, start, end = this._href.length) {
    return this._slice(0, start) + replacement + this._slice(end)
  }

  _parse(input, base, shouldThrow) {
    try {
      this._href = binding.parse(
        String(input),
        base ? String(base) : null,
        this._components,
        shouldThrow
      )
    } catch (err) {
      if (err instanceof TypeError) throw err

      throw errors.INVALID_URL(`Invalid URL '${input}'`, input)
    }
  }

  _update(input) {
    try {
      this._parse(input, null, true)
    } catch (err) {
      if (err instanceof TypeError) throw err
    }
  }
}

module.exports = exports = URL

// https://url.spec.whatwg.org/#url-opaque-path
function hasOpaquePath(url) {
  return url.pathname[0] !== '/'
}

// https://url.spec.whatwg.org/#cannot-have-a-username-password-port
function cannotHaveCredentialsOrPort(url) {
  return url.hostname === '' || url.protocol === 'file:'
}

exports.URL = URL
exports.URLSearchParams = URLSearchParams

exports.errors = errors

exports.isURL = function isURL(value) {
  if (value instanceof URL) return true

  return typeof value === 'object' && value !== null && value[kind] === URL[kind]
}

exports.isURLSearchParams = URLSearchParams.isURLSearchParams

// https://url.spec.whatwg.org/#dom-url-parse
exports.parse = function parse(input, base) {
  const url = new URL(input, base, { throw: false })
  return url._href ? url : null
}

// https://url.spec.whatwg.org/#dom-url-canparse
exports.canParse = function canParse(input, base) {
  return binding.canParse(String(input), base ? String(base) : null)
}

exports.fileURLToPath = function fileURLToPath(url) {
  if (typeof url === 'string') {
    url = new URL(url)
  }

  if (url.protocol !== 'file:') {
    throw errors.INVALID_URL_SCHEME('The URL must use the file: protocol')
  }

  if (isWindows) {
    if (/%2f|%5c/i.test(url.pathname)) {
      throw errors.INVALID_FILE_URL_PATH(
        'The file: URL path must not include encoded \\ or / characters'
      )
    }
  } else {
    if (url.hostname) {
      throw errors.INVALID_FILE_URL_HOST("The file: URL host must be 'localhost' or empty")
    }

    if (/%2f/i.test(url.pathname)) {
      throw errors.INVALID_FILE_URL_PATH('The file: URL path must not include encoded / characters')
    }
  }

  if (/%00/i.test(url.pathname)) {
    throw errors.INVALID_FILE_URL_PATH('The file: URL path must not include encoded NUL characters')
  }

  const pathname = path.normalize(decodeURIComponent(url.pathname))

  if (isWindows) {
    if (url.hostname) return '\\\\' + url.hostname + pathname

    const letter = pathname.charCodeAt(1) | 0x20

    if (letter < 0x61 /* a */ || letter > 0x7a /* z */ || pathname.charCodeAt(2) !== 0x3a /* : */) {
      throw errors.INVALID_FILE_URL_PATH('The file: URL path must be absolute')
    }

    return pathname.slice(1)
  }

  return pathname
}

exports.pathToFileURL = function pathToFileURL(pathname) {
  let resolved = path.resolve(pathname)

  if (pathname[pathname.length - 1] === '/') {
    resolved += '/'
  } else if (isWindows && pathname[pathname.length - 1] === '\\') {
    resolved += '\\'
  }

  resolved = resolved
    .replaceAll('%', '%25') // Must be first
    .replaceAll('#', '%23')
    .replaceAll('?', '%3f')
    .replaceAll('\n', '%0a')
    .replaceAll('\r', '%0d')
    .replaceAll('\t', '%09')

  if (!isWindows) {
    resolved = resolved.replaceAll('\\', '%5c')
  }

  return new URL('file:' + resolved)
}

exports.format = function format(parts) {
  const { protocol, auth, host, hostname, port, pathname, search, query, hash, slashes } = parts

  let result = ''

  if (typeof protocol === 'string') {
    result += protocol

    if (protocol[protocol.length - 1] !== ':') {
      result += ':'
    }

    if (slashes === true || /https?|ftp|gopher|file/.test(protocol)) {
      result += '//'
    }
  }

  if (typeof auth === 'string') {
    if (host || hostname) result += auth + '@'
  }

  if (typeof host === 'string') result += host
  else {
    result += hostname

    if (port) result += ':' + port
  }

  if (typeof pathname === 'string' && pathname !== '') {
    if (pathname[0] !== '/') result += '/'
    result += pathname
  }

  if (typeof search === 'string') {
    if (search[0] !== '?') result += '?'
    result += search
  } else if (typeof query === 'object' && query !== null) {
    result += '?' + new URLSearchParams(query)
  }

  if (typeof hash === 'string') {
    if (hash[0] !== '#') result += '#'
    result += hash
  }

  return result
}
module.exports = class URLError extends Error {
  constructor(msg, fn = URLError, code = fn.name) {
    super(`${code}: ${msg}`)

    this.code = code

    if (Error.captureStackTrace) Error.captureStackTrace(this, fn)
  }

  get name() {
    return 'URLError'
  }

  static INVALID_URL(msg, input) {
    const err = new URLError(msg, URLError.INVALID_URL)

    err.input = input

    return err
  }

  static INVALID_URL_SCHEME(msg = 'Invalid URL') {
    return new URLError(msg, URLError.INVALID_URL_SCHEME)
  }

  static INVALID_FILE_URL_HOST(msg = 'Invalid file: URL host') {
    return new URLError(msg, URLError.INVALID_FILE_URL_HOST)
  }

  static INVALID_FILE_URL_PATH(msg = 'Invalid file: URL path') {
    return new URLError(msg, URLError.INVALID_FILE_URL_PATH)
  }
}
const kind = Symbol.for('bare.url.search-params.kind')

class URLSearchParams {
  static _urls = new WeakMap()

  static get [kind]() {
    return 0 // Compatibility version
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-urlsearchparams
  constructor(init, url = null) {
    this._params = new Map()

    if (url) URLSearchParams._urls.set(this, url)

    if (typeof init === 'string') {
      this._parse(init)
    } else if (init) {
      for (const [name, value] of typeof init[Symbol.iterator] === 'function'
        ? init
        : Object.entries(init)) {
        this.append(name, value)
      }
    }
  }

  get [kind]() {
    return URLSearchParams[kind]
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-size
  get size() {
    return this._params.length
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-append
  append(name, value = null) {
    if (value === null) return

    let list = this._params.get(name)

    if (list === undefined) {
      list = []
      this._params.set(name, list)
    }

    list.push(value)

    this._update()
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-delete
  delete(name, value = null) {
    if (value === null) this._params.delete(name)
    else {
      let list = this._params.get(name)

      if (list === undefined) return

      list = list.filter((found) => found !== value)

      if (list.length === 0) this._params.delete(name)
      else this._params.set(name, list)
    }

    this._update()
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-get
  get(name) {
    const list = this._params.get(name)

    if (list === undefined) return null

    return list[0]
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-getall
  getAll(name) {
    const list = this._params.get(name)

    if (list === undefined) return []

    return Array.from(list)
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-has
  has(name, value = null) {
    const list = this._params.get(name)

    if (list === undefined) return false

    if (value === null) return true

    return list.includes(value)
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-set
  set(name, value = null) {
    if (value === null) this._params.delete(name)
    else this._params.set(name, [value])

    this._update()
  }

  toString() {
    return this._serialize()
  }

  toJSON() {
    return [...this]
  }

  *[Symbol.iterator]() {
    for (const [name, values] of this._params) {
      for (const value of values) yield [name, value]
    }
  }

  [Symbol.for('bare.inspect')]() {
    const object = {
      __proto__: { constructor: URLSearchParams }
    }

    for (const [name, values] of this._params) {
      if (values.length === 1) object[name] = values[0]
      else object[name] = values
    }

    return object
  }

  // https://url.spec.whatwg.org/#concept-urlsearchparams-update
  _update() {
    const url = URLSearchParams._urls.get(this)

    if (url === undefined) return

    url.search = this._serialize()
  }

  // https://url.spec.whatwg.org/#concept-urlencoded-parser
  _parse(input) {
    if (input[0] === '?') input = input.substring(1)

    this._params = new Map()

    for (let sequence of input.split('&')) {
      if (sequence.length === 0) continue

      sequence = sequence.replace(/\+/g, ' ')

      let i = sequence.indexOf('=')
      if (i === -1) i = sequence.length

      const name = decodeURIComponent(sequence.substring(0, i))
      const value = decodeURIComponent(sequence.substring(i + 1, sequence.length))

      let list = this._params.get(name)

      if (list === undefined) {
        list = []
        this._params.set(name, list)
      }

      list.push(value)
    }
  }

  // https://url.spec.whatwg.org/#concept-urlencoded-serializer
  _serialize() {
    let output = ''

    for (let [name, values] of this._params) {
      name = encodeURIComponent(name)

      for (const value of values) {
        if (output) output += '&'

        output += name + '=' + encodeURIComponent(value)
      }
    }

    return output
  }
}

module.exports = exports = URLSearchParams

exports.isURLSearchParams = function isURLSearchParams(value) {
  if (value instanceof URLSearchParams) return true

  return typeof value === 'object' && value !== null && value[kind] === URLSearchParams[kind]
}
{
  "name": "bare-url",
  "version": "2.4.5",
  "description": "WHATWG URL implementation for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "global.js",
    "global.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-url.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-url/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-url",
  "dependencies": {
    "bare-path": "^3.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "cmake-bare": "^1.1.6",
    "cmake-fetch": "^1.0.0",
    "lunte": "^1.6.0",
    "prettier": "^3.3.3",
    "prettier-config-holepunch": "^2.0.0"
  }
}
const sodium = require('sodium-universal')
const b4a = require('b4a')
const assert = require('nanoassert')
const { detectLanguage, loadWordlist } = require('./wordlist')

module.exports = {
  generateEntropy,
  generateMnemonic,
  normalizeMnemonic,
  validateMnemonic,
  mnemonicToEntropy,
  mnemonicToSeed,
  entropyToMnemonic
}

function generateMnemonic ({ entropy = generateEntropy(), language = 'english' } = {}) {
  const wordlist = loadWordlist(language)
  const extended = computeCheckSum(entropy)

  const words = []

  for (const index of uint11Reader(extended)) {
    words.push(wordlist[index])
  }

  const delimiter = language === 'japanese' ? '\u3000' : ' '

  return words.join(delimiter).trim()
}

function entropyToMnemonic (entropy, { language = 'english' } = {}) {
  return generateMnemonic({ entropy, language })
}

function mnemonicToEntropy (mnemonic) {
  const words = mnemonic.replace(/\u3000/g, ' ').trim().split(' ')
  const language = detectLanguage(words)

  if (!language) {
    throw new Error('Language not recognised')
  }

  if (words.length % 3 !== 0) {
    throw new Error('Invalid length')
  }

  const wordlist = loadWordlist(language)

  const indexes = []
  for (const word of words) {
    const index = wordlist.indexOf(word)
    if (index === -1) {
      throw new Error('Bad word')
    }

    indexes.push(index)
  }

  const bits = words.length * 11
  const len = (bits * 32 / 33) >> 3

  const extended = b4a.alloc(Math.ceil(bits / 8))
  const entropy = extended.subarray(0, len)

  uint11Writer(extended, indexes)

  if (!b4a.equals(extended, computeCheckSum(entropy))) {
    throw new Error('Invalid checksum')
  }

  return entropy
}

function normalizeMnemonic (mnemonic) {
  return mnemonic.trim().replace(/\u3000/, ' ').split(/\s+/).map(c => c.toLowerCase()).join(' ')
}

async function mnemonicToSeed (mnemonic, passphrase = '') {
  mnemonic = normalizeMnemonic(mnemonic)

  if (!validateMnemonic(mnemonic)) {
    throw new Error('Invalid mnemonic')
  }

  const input = b4a.from(mnemonic)
  const salt = b4a.from('mnemonic' + passphrase)

  const output = b4a.alloc(64)

  await sodium.extension_pbkdf2_sha512_async(
    output,
    input,
    salt,
    2048,
    64
  )

  return output
}

function validateMnemonic (mnemonic) {
  try {
    mnemonicToEntropy(mnemonic)
  } catch (e) {
    return false
  }
  return true
}

function sha256 (data, output = b4a.alloc(32)) {
  sodium.crypto_hash_sha256(output, data)
  return output
}

function computeCheckSum (seed) {
  assert((seed.byteLength & 4) === 0, 'seed must be a multiple of 4 bytes')

  const len = seed.byteLength
  const cklen = len >> 2 // cksum bits
  const total = len + Math.ceil(cklen / 8)

  const output = b4a.alloc(len + 32)
  output.set(seed)

  const entropy = output.subarray(0, len)
  const cksum = output.subarray(len)

  sha256(entropy, cksum)

  // only append cklen bits
  output[total - 1] &= (0xff ^ (0xff >> cklen))

  return output.subarray(0, total)
}

function generateEntropy (length = 32) {
  const seed = b4a.alloc(length)
  sodium.randombytes_buf(seed)

  return seed
}

function * uint11Reader (state) {
  yield * uintReader(state, 11)
}

function uint11Writer (buf, uints) {
  return uintWriter(buf, uints, 11)
}

function * uintReader (buffer, width) {
  const MASK = (2 << (width - 1)) - 1

  let pos = 0
  let value = 0

  while (true) {
    const offset = pos >> 3 // byte offset

    if (offset >= buffer.byteLength) {
      return value & MASK
    }

    const height = width - (pos % width)
    const leftover = (offset + 1) * 8 - pos

    value += shift(buffer[offset], height - leftover)

    pos += Math.min(height, leftover)
    if (pos % width) continue

    yield value & MASK

    value = 0
  }
}

function uintWriter (buffer, uints, width) {
  let pos = 0

  while (true) {
    const offset = pos >> 3 // byte offset

    const i = Math.floor(pos / width)
    if (i >= uints.length) break

    if (offset >= buffer.length) {
      throw new Error('Failed to encode uints')
    }

    const rem = 8 - pos % 8
    const height = (i + 1) * width - pos

    const value = shift(uints[i], rem - height)

    buffer[offset] += mask(value, rem)

    pos += Math.min(rem, height)
  }

  return buffer
}

// when n is positive, shift left n bits
// when n is negative, shift right -n bits
function shift (val, n) {
  if (n === 0) return val
  if (n > 0) return val << n

  return val >> (-1 * n)
}

function mask (val, bits) {
  if (bits < 32) return val & ((1 << bits) - 1)
  return val % (2 ** bits)
}
{
  "name": "bip39-mnemonic",
  "version": "2.5.0",
  "description": "BIP39 mnemonic for key derivation schemes",
  "main": "index.js",
  "scripts": {
    "generate-wordlist": "node scripts/generate-wordlist.js",
    "test": "standard && brittle test/*.js"
  },
  "author": "Holepunch Inc",
  "license": "Apache-2.0",
  "devDependencies": {
    "brittle": "^3.4.0",
    "standard": "^17.1.0"
  },
  "dependencies": {
    "b4a": "^1.6.6",
    "nanoassert": "^2.0.0",
    "sodium-universal": "^5.0.1"
  },
  "files": [
    "index.js",
    "wordlist"
  ],
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bip39.git"
  },
  "bugs": {
    "url": "https://github.com/holepunchto/bip39/issues"
  },
  "homepage": "https://github.com/holepunchto/bip39#readme"
}
["的","一","是","在","不","了","有","和","人","这","中","大","为","上","个","国","我","以","要","他","时","来","用","们","生","到","作","地","于","出","就","分","对","成","会","可","主","发","年","动","同","工","也","能","下","过","子","说","产","种","面","而","方","后","多","定","行","学","法","所","民","得","经","十","三","之","进","着","等","部","度","家","电","力","里","如","水","化","高","自","二","理","起","小","物","现","实","加","量","都","两","体","制","机","当","使","点","从","业","本","去","把","性","好","应","开","它","合","还","因","由","其","些","然","前","外","天","政","四","日","那","社","义","事","平","形","相","全","表","间","样","与","关","各","重","新","线","内","数","正","心","反","你","明","看","原","又","么","利","比","或","但","质","气","第","向","道","命","此","变","条","只","没","结","解","问","意","建","月","公","无","系","军","很","情","者","最","立","代","想","已","通","并","提","直","题","党","程","展","五","果","料","象","员","革","位","入","常","文","总","次","品","式","活","设","及","管","特","件","长","求","老","头","基","资","边","流","路","级","少","图","山","统","接","知","较","将","组","见","计","别","她","手","角","期","根","论","运","农","指","几","九","区","强","放","决","西","被","干","做","必","战","先","回","则","任","取","据","处","队","南","给","色","光","门","即","保","治","北","造","百","规","热","领","七","海","口","东","导","器","压","志","世","金","增","争","济","阶","油","思","术","极","交","受","联","什","认","六","共","权","收","证","改","清","美","再","采","转","更","单","风","切","打","白","教","速","花","带","安","场","身","车","例","真","务","具","万","每","目","至","达","走","积","示","议","声","报","斗","完","类","八","离","华","名","确","才","科","张","信","马","节","话","米","整","空","元","况","今","集","温","传","土","许","步","群","广","石","记","需","段","研","界","拉","林","律","叫","且","究","观","越","织","装","影","算","低","持","音","众","书","布","复","容","儿","须","际","商","非","验","连","断","深","难","近","矿","千","周","委","素","技","备","半","办","青","省","列","习","响","约","支","般","史","感","劳","便","团","往","酸","历","市","克","何","除","消","构","府","称","太","准","精","值","号","率","族","维","划","选","标","写","存","候","毛","亲","快","效","斯","院","查","江","型","眼","王","按","格","养","易","置","派","层","片","始","却","专","状","育","厂","京","识","适","属","圆","包","火","住","调","满","县","局","照","参","红","细","引","听","该","铁","价","严","首","底","液","官","德","随","病","苏","失","尔","死","讲","配","女","黄","推","显","谈","罪","神","艺","呢","席","含","企","望","密","批","营","项","防","举","球","英","氧","势","告","李","台","落","木","帮","轮","破","亚","师","围","注","远","字","材","排","供","河","态","封","另","施","减","树","溶","怎","止","案","言","士","均","武","固","叶","鱼","波","视","仅","费","紧","爱","左","章","早","朝","害","续","轻","服","试","食","充","兵","源","判","护","司","足","某","练","差","致","板","田","降","黑","犯","负","击","范","继","兴","似","余","坚","曲","输","修","故","城","夫","够","送","笔","船","占","右","财","吃","富","春","职","觉","汉","画","功","巴","跟","虽","杂","飞","检","吸","助","升","阳","互","初","创","抗","考","投","坏","策","古","径","换","未","跑","留","钢","曾","端","责","站","简","述","钱","副","尽","帝","射","草","冲","承","独","令","限","阿","宣","环","双","请","超","微","让","控","州","良","轴","找","否","纪","益","依","优","顶","础","载","倒","房","突","坐","粉","敌","略","客","袁","冷","胜","绝","析","块","剂","测","丝","协","诉","念","陈","仍","罗","盐","友","洋","错","苦","夜","刑","移","频","逐","靠","混","母","短","皮","终","聚","汽","村","云","哪","既","距","卫","停","烈","央","察","烧","迅","境","若","印","洲","刻","括","激","孔","搞","甚","室","待","核","校","散","侵","吧","甲","游","久","菜","味","旧","模","湖","货","损","预","阻","毫","普","稳","乙","妈","植","息","扩","银","语","挥","酒","守","拿","序","纸","医","缺","雨","吗","针","刘","啊","急","唱","误","训","愿","审","附","获","茶","鲜","粮","斤","孩","脱","硫","肥","善","龙","演","父","渐","血","欢","械","掌","歌","沙","刚","攻","谓","盾","讨","晚","粒","乱","燃","矛","乎","杀","药","宁","鲁","贵","钟","煤","读","班","伯","香","介","迫","句","丰","培","握","兰","担","弦","蛋","沉","假","穿","执","答","乐","谁","顺","烟","缩","征","脸","喜","松","脚","困","异","免","背","星","福","买","染","井","概","慢","怕","磁","倍","祖","皇","促","静","补","评","翻","肉","践","尼","衣","宽","扬","棉","希","伤","操","垂","秋","宜","氢","套","督","振","架","亮","末","宪","庆","编","牛","触","映","雷","销","诗","座","居","抓","裂","胞","呼","娘","景","威","绿","晶","厚","盟","衡","鸡","孙","延","危","胶","屋","乡","临","陆","顾","掉","呀","灯","岁","措","束","耐","剧","玉","赵","跳","哥","季","课","凯","胡","额","款","绍","卷","齐","伟","蒸","殖","永","宗","苗","川","炉","岩","弱","零","杨","奏","沿","露","杆","探","滑","镇","饭","浓","航","怀","赶","库","夺","伊","灵","税","途","灭","赛","归","召","鼓","播","盘","裁","险","康","唯","录","菌","纯","借","糖","盖","横","符","私","努","堂","域","枪","润","幅","哈","竟","熟","虫","泽","脑","壤","碳","欧","遍","侧","寨","敢","彻","虑","斜","薄","庭","纳","弹","饲","伸","折","麦","湿","暗","荷","瓦","塞","床","筑","恶","户","访","塔","奇","透","梁","刀","旋","迹","卡","氯","遇","份","毒","泥","退","洗","摆","灰","彩","卖","耗","夏","择","忙","铜","献","硬","予","繁","圈","雪","函","亦","抽","篇","阵","阴","丁","尺","追","堆","雄","迎","泛","爸","楼","避","谋","吨","野","猪","旗","累","偏","典","馆","索","秦","脂","潮","爷","豆","忽","托","惊","塑","遗","愈","朱","替","纤","粗","倾","尚","痛","楚","谢","奋","购","磨","君","池","旁","碎","骨","监","捕","弟","暴","割","贯","殊","释","词","亡","壁","顿","宝","午","尘","闻","揭","炮","残","冬","桥","妇","警","综","招","吴","付","浮","遭","徐","您","摇","谷","赞","箱","隔","订","男","吹","园","纷","唐","败","宋","玻","巨","耕","坦","荣","闭","湾","键","凡","驻","锅","救","恩","剥","凝","碱","齿","截","炼","麻","纺","禁","废","盛","版","缓","净","睛","昌","婚","涉","筒","嘴","插","岸","朗","庄","街","藏","姑","贸","腐","奴","啦","惯","乘","伙","恢","匀","纱","扎","辩","耳","彪","臣","亿","璃","抵","脉","秀","萨","俄","网","舞","店","喷","纵","寸","汗","挂","洪","贺","闪","柬","爆","烯","津","稻","墙","软","勇","像","滚","厘","蒙","芳","肯","坡","柱","荡","腿","仪","旅","尾","轧","冰","贡","登","黎","削","钻","勒","逃","障","氨","郭","峰","币","港","伏","轨","亩","毕","擦","莫","刺","浪","秘","援","株","健","售","股","岛","甘","泡","睡","童","铸","汤","阀","休","汇","舍","牧","绕","炸","哲","磷","绩","朋","淡","尖","启","陷","柴","呈","徒","颜","泪","稍","忘","泵","蓝","拖","洞","授","镜","辛","壮","锋","贫","虚","弯","摩","泰","幼","廷","尊","窗","纲","弄","隶","疑","氏","宫","姐","震","瑞","怪","尤","琴","循","描","膜","违","夹","腰","缘","珠","穷","森","枝","竹","沟","催","绳","忆","邦","剩","幸","浆","栏","拥","牙","贮","礼","滤","钠","纹","罢","拍","咱","喊","袖","埃","勤","罚","焦","潜","伍","墨","欲","缝","姓","刊","饱","仿","奖","铝","鬼","丽","跨","默","挖","链","扫","喝","袋","炭","污","幕","诸","弧","励","梅","奶","洁","灾","舟","鉴","苯","讼","抱","毁","懂","寒","智","埔","寄","届","跃","渡","挑","丹","艰","贝","碰","拔","爹","戴","码","梦","芽","熔","赤","渔","哭","敬","颗","奔","铅","仲","虎","稀","妹","乏","珍","申","桌","遵","允","隆","螺","仓","魏","锐","晓","氮","兼","隐","碍","赫","拨","忠","肃","缸","牵","抢","博","巧","壳","兄","杜","讯","诚","碧","祥","柯","页","巡","矩","悲","灌","龄","伦","票","寻","桂","铺","圣","恐","恰","郑","趣","抬","荒","腾","贴","柔","滴","猛","阔","辆","妻","填","撤","储","签","闹","扰","紫","砂","递","戏","吊","陶","伐","喂","疗","瓶","婆","抚","臂","摸","忍","虾","蜡","邻","胸","巩","挤","偶","弃","槽","劲","乳","邓","吉","仁","烂","砖","租","乌","舰","伴","瓜","浅","丙","暂","燥","橡","柳","迷","暖","牌","秧","胆","详","簧","踏","瓷","谱","呆","宾","糊","洛","辉","愤","竞","隙","怒","粘","乃","绪","肩","籍","敏","涂","熙","皆","侦","悬","掘","享","纠","醒","狂","锁","淀","恨","牲","霸","爬","赏","逆","玩","陵","祝","秒","浙","貌","役","彼","悉","鸭","趋","凤","晨","畜","辈","秩","卵","署","梯","炎","滩","棋","驱","筛","峡","冒","啥","寿","译","浸","泉","帽","迟","硅","疆","贷","漏","稿","冠","嫩","胁","芯","牢","叛","蚀","奥","鸣","岭","羊","凭","串","塘","绘","酵","融","盆","锡","庙","筹","冻","辅","摄","袭","筋","拒","僚","旱","钾","鸟","漆","沈","眉","疏","添","棒","穗","硝","韩","逼","扭","侨","凉","挺","碗","栽","炒","杯","患","馏","劝","豪","辽","勃","鸿","旦","吏","拜","狗","埋","辊","掩","饮","搬","骂","辞","勾","扣","估","蒋","绒","雾","丈","朵","姆","拟","宇","辑","陕","雕","偿","蓄","崇","剪","倡","厅","咬","驶","薯","刷","斥","番","赋","奉","佛","浇","漫","曼","扇","钙","桃","扶","仔","返","俗","亏","腔","鞋","棱","覆","框","悄","叔","撞","骗","勘","旺","沸","孤","吐","孟","渠","屈","疾","妙","惜","仰","狠","胀","谐","抛","霉","桑","岗","嘛","衰","盗","渗","脏","赖","涌","甜","曹","阅","肌","哩","厉","烃","纬","毅","昨","伪","症","煮","叹","钉","搭","茎","笼","酷","偷","弓","锥","恒","杰","坑","鼻","翼","纶","叙","狱","逮","罐","络","棚","抑","膨","蔬","寺","骤","穆","冶","枯","册","尸","凸","绅","坯","牺","焰","轰","欣","晋","瘦","御","锭","锦","丧","旬","锻","垄","搜","扑","邀","亭","酯","迈","舒","脆","酶","闲","忧","酚","顽","羽","涨","卸","仗","陪","辟","惩","杭","姚","肚","捉","飘","漂","昆","欺","吾","郎","烷","汁","呵","饰","萧","雅","邮","迁","燕","撒","姻","赴","宴","烦","债","帐","斑","铃","旨","醇","董","饼","雏","姿","拌","傅","腹","妥","揉","贤","拆","歪","葡","胺","丢","浩","徽","昂","垫","挡","览","贪","慰","缴","汪","慌","冯","诺","姜","谊","凶","劣","诬","耀","昏","躺","盈","骑","乔","溪","丛","卢","抹","闷","咨","刮","驾","缆","悟","摘","铒","掷","颇","幻","柄","惠","惨","佳","仇","腊","窝","涤","剑","瞧","堡","泼","葱","罩","霍","捞","胎","苍","滨","俩","捅","湘","砍","霞","邵","萄","疯","淮","遂","熊","粪","烘","宿","档","戈","驳","嫂","裕","徙","箭","捐","肠","撑","晒","辨","殿","莲","摊","搅","酱","屏","疫","哀","蔡","堵","沫","皱","畅","叠","阁","莱","敲","辖","钩","痕","坝","巷","饿","祸","丘","玄","溜","曰","逻","彭","尝","卿","妨","艇","吞","韦","怨","矮","歇"]["的","一","是","在","不","了","有","和","人","這","中","大","為","上","個","國","我","以","要","他","時","來","用","們","生","到","作","地","於","出","就","分","對","成","會","可","主","發","年","動","同","工","也","能","下","過","子","說","產","種","面","而","方","後","多","定","行","學","法","所","民","得","經","十","三","之","進","著","等","部","度","家","電","力","裡","如","水","化","高","自","二","理","起","小","物","現","實","加","量","都","兩","體","制","機","當","使","點","從","業","本","去","把","性","好","應","開","它","合","還","因","由","其","些","然","前","外","天","政","四","日","那","社","義","事","平","形","相","全","表","間","樣","與","關","各","重","新","線","內","數","正","心","反","你","明","看","原","又","麼","利","比","或","但","質","氣","第","向","道","命","此","變","條","只","沒","結","解","問","意","建","月","公","無","系","軍","很","情","者","最","立","代","想","已","通","並","提","直","題","黨","程","展","五","果","料","象","員","革","位","入","常","文","總","次","品","式","活","設","及","管","特","件","長","求","老","頭","基","資","邊","流","路","級","少","圖","山","統","接","知","較","將","組","見","計","別","她","手","角","期","根","論","運","農","指","幾","九","區","強","放","決","西","被","幹","做","必","戰","先","回","則","任","取","據","處","隊","南","給","色","光","門","即","保","治","北","造","百","規","熱","領","七","海","口","東","導","器","壓","志","世","金","增","爭","濟","階","油","思","術","極","交","受","聯","什","認","六","共","權","收","證","改","清","美","再","採","轉","更","單","風","切","打","白","教","速","花","帶","安","場","身","車","例","真","務","具","萬","每","目","至","達","走","積","示","議","聲","報","鬥","完","類","八","離","華","名","確","才","科","張","信","馬","節","話","米","整","空","元","況","今","集","溫","傳","土","許","步","群","廣","石","記","需","段","研","界","拉","林","律","叫","且","究","觀","越","織","裝","影","算","低","持","音","眾","書","布","复","容","兒","須","際","商","非","驗","連","斷","深","難","近","礦","千","週","委","素","技","備","半","辦","青","省","列","習","響","約","支","般","史","感","勞","便","團","往","酸","歷","市","克","何","除","消","構","府","稱","太","準","精","值","號","率","族","維","劃","選","標","寫","存","候","毛","親","快","效","斯","院","查","江","型","眼","王","按","格","養","易","置","派","層","片","始","卻","專","狀","育","廠","京","識","適","屬","圓","包","火","住","調","滿","縣","局","照","參","紅","細","引","聽","該","鐵","價","嚴","首","底","液","官","德","隨","病","蘇","失","爾","死","講","配","女","黃","推","顯","談","罪","神","藝","呢","席","含","企","望","密","批","營","項","防","舉","球","英","氧","勢","告","李","台","落","木","幫","輪","破","亞","師","圍","注","遠","字","材","排","供","河","態","封","另","施","減","樹","溶","怎","止","案","言","士","均","武","固","葉","魚","波","視","僅","費","緊","愛","左","章","早","朝","害","續","輕","服","試","食","充","兵","源","判","護","司","足","某","練","差","致","板","田","降","黑","犯","負","擊","范","繼","興","似","餘","堅","曲","輸","修","故","城","夫","夠","送","筆","船","佔","右","財","吃","富","春","職","覺","漢","畫","功","巴","跟","雖","雜","飛","檢","吸","助","昇","陽","互","初","創","抗","考","投","壞","策","古","徑","換","未","跑","留","鋼","曾","端","責","站","簡","述","錢","副","盡","帝","射","草","衝","承","獨","令","限","阿","宣","環","雙","請","超","微","讓","控","州","良","軸","找","否","紀","益","依","優","頂","礎","載","倒","房","突","坐","粉","敵","略","客","袁","冷","勝","絕","析","塊","劑","測","絲","協","訴","念","陳","仍","羅","鹽","友","洋","錯","苦","夜","刑","移","頻","逐","靠","混","母","短","皮","終","聚","汽","村","雲","哪","既","距","衛","停","烈","央","察","燒","迅","境","若","印","洲","刻","括","激","孔","搞","甚","室","待","核","校","散","侵","吧","甲","遊","久","菜","味","舊","模","湖","貨","損","預","阻","毫","普","穩","乙","媽","植","息","擴","銀","語","揮","酒","守","拿","序","紙","醫","缺","雨","嗎","針","劉","啊","急","唱","誤","訓","願","審","附","獲","茶","鮮","糧","斤","孩","脫","硫","肥","善","龍","演","父","漸","血","歡","械","掌","歌","沙","剛","攻","謂","盾","討","晚","粒","亂","燃","矛","乎","殺","藥","寧","魯","貴","鐘","煤","讀","班","伯","香","介","迫","句","豐","培","握","蘭","擔","弦","蛋","沉","假","穿","執","答","樂","誰","順","煙","縮","徵","臉","喜","松","腳","困","異","免","背","星","福","買","染","井","概","慢","怕","磁","倍","祖","皇","促","靜","補","評","翻","肉","踐","尼","衣","寬","揚","棉","希","傷","操","垂","秋","宜","氫","套","督","振","架","亮","末","憲","慶","編","牛","觸","映","雷","銷","詩","座","居","抓","裂","胞","呼","娘","景","威","綠","晶","厚","盟","衡","雞","孫","延","危","膠","屋","鄉","臨","陸","顧","掉","呀","燈","歲","措","束","耐","劇","玉","趙","跳","哥","季","課","凱","胡","額","款","紹","卷","齊","偉","蒸","殖","永","宗","苗","川","爐","岩","弱","零","楊","奏","沿","露","桿","探","滑","鎮","飯","濃","航","懷","趕","庫","奪","伊","靈","稅","途","滅","賽","歸","召","鼓","播","盤","裁","險","康","唯","錄","菌","純","借","糖","蓋","橫","符","私","努","堂","域","槍","潤","幅","哈","竟","熟","蟲","澤","腦","壤","碳","歐","遍","側","寨","敢","徹","慮","斜","薄","庭","納","彈","飼","伸","折","麥","濕","暗","荷","瓦","塞","床","築","惡","戶","訪","塔","奇","透","梁","刀","旋","跡","卡","氯","遇","份","毒","泥","退","洗","擺","灰","彩","賣","耗","夏","擇","忙","銅","獻","硬","予","繁","圈","雪","函","亦","抽","篇","陣","陰","丁","尺","追","堆","雄","迎","泛","爸","樓","避","謀","噸","野","豬","旗","累","偏","典","館","索","秦","脂","潮","爺","豆","忽","托","驚","塑","遺","愈","朱","替","纖","粗","傾","尚","痛","楚","謝","奮","購","磨","君","池","旁","碎","骨","監","捕","弟","暴","割","貫","殊","釋","詞","亡","壁","頓","寶","午","塵","聞","揭","炮","殘","冬","橋","婦","警","綜","招","吳","付","浮","遭","徐","您","搖","谷","贊","箱","隔","訂","男","吹","園","紛","唐","敗","宋","玻","巨","耕","坦","榮","閉","灣","鍵","凡","駐","鍋","救","恩","剝","凝","鹼","齒","截","煉","麻","紡","禁","廢","盛","版","緩","淨","睛","昌","婚","涉","筒","嘴","插","岸","朗","莊","街","藏","姑","貿","腐","奴","啦","慣","乘","夥","恢","勻","紗","扎","辯","耳","彪","臣","億","璃","抵","脈","秀","薩","俄","網","舞","店","噴","縱","寸","汗","掛","洪","賀","閃","柬","爆","烯","津","稻","牆","軟","勇","像","滾","厘","蒙","芳","肯","坡","柱","盪","腿","儀","旅","尾","軋","冰","貢","登","黎","削","鑽","勒","逃","障","氨","郭","峰","幣","港","伏","軌","畝","畢","擦","莫","刺","浪","秘","援","株","健","售","股","島","甘","泡","睡","童","鑄","湯","閥","休","匯","舍","牧","繞","炸","哲","磷","績","朋","淡","尖","啟","陷","柴","呈","徒","顏","淚","稍","忘","泵","藍","拖","洞","授","鏡","辛","壯","鋒","貧","虛","彎","摩","泰","幼","廷","尊","窗","綱","弄","隸","疑","氏","宮","姐","震","瑞","怪","尤","琴","循","描","膜","違","夾","腰","緣","珠","窮","森","枝","竹","溝","催","繩","憶","邦","剩","幸","漿","欄","擁","牙","貯","禮","濾","鈉","紋","罷","拍","咱","喊","袖","埃","勤","罰","焦","潛","伍","墨","欲","縫","姓","刊","飽","仿","獎","鋁","鬼","麗","跨","默","挖","鏈","掃","喝","袋","炭","污","幕","諸","弧","勵","梅","奶","潔","災","舟","鑑","苯","訟","抱","毀","懂","寒","智","埔","寄","屆","躍","渡","挑","丹","艱","貝","碰","拔","爹","戴","碼","夢","芽","熔","赤","漁","哭","敬","顆","奔","鉛","仲","虎","稀","妹","乏","珍","申","桌","遵","允","隆","螺","倉","魏","銳","曉","氮","兼","隱","礙","赫","撥","忠","肅","缸","牽","搶","博","巧","殼","兄","杜","訊","誠","碧","祥","柯","頁","巡","矩","悲","灌","齡","倫","票","尋","桂","鋪","聖","恐","恰","鄭","趣","抬","荒","騰","貼","柔","滴","猛","闊","輛","妻","填","撤","儲","簽","鬧","擾","紫","砂","遞","戲","吊","陶","伐","餵","療","瓶","婆","撫","臂","摸","忍","蝦","蠟","鄰","胸","鞏","擠","偶","棄","槽","勁","乳","鄧","吉","仁","爛","磚","租","烏","艦","伴","瓜","淺","丙","暫","燥","橡","柳","迷","暖","牌","秧","膽","詳","簧","踏","瓷","譜","呆","賓","糊","洛","輝","憤","競","隙","怒","粘","乃","緒","肩","籍","敏","塗","熙","皆","偵","懸","掘","享","糾","醒","狂","鎖","淀","恨","牲","霸","爬","賞","逆","玩","陵","祝","秒","浙","貌","役","彼","悉","鴨","趨","鳳","晨","畜","輩","秩","卵","署","梯","炎","灘","棋","驅","篩","峽","冒","啥","壽","譯","浸","泉","帽","遲","矽","疆","貸","漏","稿","冠","嫩","脅","芯","牢","叛","蝕","奧","鳴","嶺","羊","憑","串","塘","繪","酵","融","盆","錫","廟","籌","凍","輔","攝","襲","筋","拒","僚","旱","鉀","鳥","漆","沈","眉","疏","添","棒","穗","硝","韓","逼","扭","僑","涼","挺","碗","栽","炒","杯","患","餾","勸","豪","遼","勃","鴻","旦","吏","拜","狗","埋","輥","掩","飲","搬","罵","辭","勾","扣","估","蔣","絨","霧","丈","朵","姆","擬","宇","輯","陝","雕","償","蓄","崇","剪","倡","廳","咬","駛","薯","刷","斥","番","賦","奉","佛","澆","漫","曼","扇","鈣","桃","扶","仔","返","俗","虧","腔","鞋","棱","覆","框","悄","叔","撞","騙","勘","旺","沸","孤","吐","孟","渠","屈","疾","妙","惜","仰","狠","脹","諧","拋","黴","桑","崗","嘛","衰","盜","滲","臟","賴","湧","甜","曹","閱","肌","哩","厲","烴","緯","毅","昨","偽","症","煮","嘆","釘","搭","莖","籠","酷","偷","弓","錐","恆","傑","坑","鼻","翼","綸","敘","獄","逮","罐","絡","棚","抑","膨","蔬","寺","驟","穆","冶","枯","冊","屍","凸","紳","坯","犧","焰","轟","欣","晉","瘦","禦","錠","錦","喪","旬","鍛","壟","搜","撲","邀","亭","酯","邁","舒","脆","酶","閒","憂","酚","頑","羽","漲","卸","仗","陪","闢","懲","杭","姚","肚","捉","飄","漂","昆","欺","吾","郎","烷","汁","呵","飾","蕭","雅","郵","遷","燕","撒","姻","赴","宴","煩","債","帳","斑","鈴","旨","醇","董","餅","雛","姿","拌","傅","腹","妥","揉","賢","拆","歪","葡","胺","丟","浩","徽","昂","墊","擋","覽","貪","慰","繳","汪","慌","馮","諾","姜","誼","兇","劣","誣","耀","昏","躺","盈","騎","喬","溪","叢","盧","抹","悶","諮","刮","駕","纜","悟","摘","鉺","擲","頗","幻","柄","惠","慘","佳","仇","臘","窩","滌","劍","瞧","堡","潑","蔥","罩","霍","撈","胎","蒼","濱","倆","捅","湘","砍","霞","邵","萄","瘋","淮","遂","熊","糞","烘","宿","檔","戈","駁","嫂","裕","徙","箭","捐","腸","撐","曬","辨","殿","蓮","攤","攪","醬","屏","疫","哀","蔡","堵","沫","皺","暢","疊","閣","萊","敲","轄","鉤","痕","壩","巷","餓","禍","丘","玄","溜","曰","邏","彭","嘗","卿","妨","艇","吞","韋","怨","矮","歇"]["abdikace","abeceda","adresa","agrese","akce","aktovka","alej","alkohol","amputace","ananas","andulka","anekdota","anketa","antika","anulovat","archa","arogance","asfalt","asistent","aspirace","astma","astronom","atlas","atletika","atol","autobus","azyl","babka","bachor","bacil","baculka","badatel","bageta","bagr","bahno","bakterie","balada","baletka","balkon","balonek","balvan","balza","bambus","bankomat","barbar","baret","barman","baroko","barva","baterka","batoh","bavlna","bazalka","bazilika","bazuka","bedna","beran","beseda","bestie","beton","bezinka","bezmoc","beztak","bicykl","bidlo","biftek","bikiny","bilance","biograf","biolog","bitva","bizon","blahobyt","blatouch","blecha","bledule","blesk","blikat","blizna","blokovat","bloudit","blud","bobek","bobr","bodlina","bodnout","bohatost","bojkot","bojovat","bokorys","bolest","borec","borovice","bota","boubel","bouchat","bouda","boule","bourat","boxer","bradavka","brambora","branka","bratr","brepta","briketa","brko","brloh","bronz","broskev","brunetka","brusinka","brzda","brzy","bublina","bubnovat","buchta","buditel","budka","budova","bufet","bujarost","bukvice","buldok","bulva","bunda","bunkr","burza","butik","buvol","buzola","bydlet","bylina","bytovka","bzukot","capart","carevna","cedr","cedule","cejch","cejn","cela","celer","celkem","celnice","cenina","cennost","cenovka","centrum","cenzor","cestopis","cetka","chalupa","chapadlo","charita","chata","chechtat","chemie","chichot","chirurg","chlad","chleba","chlubit","chmel","chmura","chobot","chochol","chodba","cholera","chomout","chopit","choroba","chov","chrapot","chrlit","chrt","chrup","chtivost","chudina","chutnat","chvat","chvilka","chvost","chyba","chystat","chytit","cibule","cigareta","cihelna","cihla","cinkot","cirkus","cisterna","citace","citrus","cizinec","cizost","clona","cokoliv","couvat","ctitel","ctnost","cudnost","cuketa","cukr","cupot","cvaknout","cval","cvik","cvrkot","cyklista","daleko","dareba","datel","datum","dcera","debata","dechovka","decibel","deficit","deflace","dekl","dekret","demokrat","deprese","derby","deska","detektiv","dikobraz","diktovat","dioda","diplom","disk","displej","divadlo","divoch","dlaha","dlouho","dluhopis","dnes","dobro","dobytek","docent","dochutit","dodnes","dohled","dohoda","dohra","dojem","dojnice","doklad","dokola","doktor","dokument","dolar","doleva","dolina","doma","dominant","domluvit","domov","donutit","dopad","dopis","doplnit","doposud","doprovod","dopustit","dorazit","dorost","dort","dosah","doslov","dostatek","dosud","dosyta","dotaz","dotek","dotknout","doufat","doutnat","dovozce","dozadu","doznat","dozorce","drahota","drak","dramatik","dravec","draze","drdol","drobnost","drogerie","drozd","drsnost","drtit","drzost","duben","duchovno","dudek","duha","duhovka","dusit","dusno","dutost","dvojice","dvorec","dynamit","ekolog","ekonomie","elektron","elipsa","email","emise","emoce","empatie","epizoda","epocha","epopej","epos","esej","esence","eskorta","eskymo","etiketa","euforie","evoluce","exekuce","exkurze","expedice","exploze","export","extrakt","facka","fajfka","fakulta","fanatik","fantazie","farmacie","favorit","fazole","federace","fejeton","fenka","fialka","figurant","filozof","filtr","finance","finta","fixace","fjord","flanel","flirt","flotila","fond","fosfor","fotbal","fotka","foton","frakce","freska","fronta","fukar","funkce","fyzika","galeje","garant","genetika","geolog","gilotina","glazura","glejt","golem","golfista","gotika","graf","gramofon","granule","grep","gril","grog","groteska","guma","hadice","hadr","hala","halenka","hanba","hanopis","harfa","harpuna","havran","hebkost","hejkal","hejno","hejtman","hektar","helma","hematom","herec","herna","heslo","hezky","historik","hladovka","hlasivky","hlava","hledat","hlen","hlodavec","hloh","hloupost","hltat","hlubina","hluchota","hmat","hmota","hmyz","hnis","hnojivo","hnout","hoblina","hoboj","hoch","hodiny","hodlat","hodnota","hodovat","hojnost","hokej","holinka","holka","holub","homole","honitba","honorace","horal","horda","horizont","horko","horlivec","hormon","hornina","horoskop","horstvo","hospoda","hostina","hotovost","houba","houf","houpat","houska","hovor","hradba","hranice","hravost","hrazda","hrbolek","hrdina","hrdlo","hrdost","hrnek","hrobka","hromada","hrot","hrouda","hrozen","hrstka","hrubost","hryzat","hubenost","hubnout","hudba","hukot","humr","husita","hustota","hvozd","hybnost","hydrant","hygiena","hymna","hysterik","idylka","ihned","ikona","iluze","imunita","infekce","inflace","inkaso","inovace","inspekce","internet","invalida","investor","inzerce","ironie","jablko","jachta","jahoda","jakmile","jakost","jalovec","jantar","jarmark","jaro","jasan","jasno","jatka","javor","jazyk","jedinec","jedle","jednatel","jehlan","jekot","jelen","jelito","jemnost","jenom","jepice","jeseter","jevit","jezdec","jezero","jinak","jindy","jinoch","jiskra","jistota","jitrnice","jizva","jmenovat","jogurt","jurta","kabaret","kabel","kabinet","kachna","kadet","kadidlo","kahan","kajak","kajuta","kakao","kaktus","kalamita","kalhoty","kalibr","kalnost","kamera","kamkoliv","kamna","kanibal","kanoe","kantor","kapalina","kapela","kapitola","kapka","kaple","kapota","kapr","kapusta","kapybara","karamel","karotka","karton","kasa","katalog","katedra","kauce","kauza","kavalec","kazajka","kazeta","kazivost","kdekoliv","kdesi","kedluben","kemp","keramika","kino","klacek","kladivo","klam","klapot","klasika","klaun","klec","klenba","klepat","klesnout","klid","klima","klisna","klobouk","klokan","klopa","kloub","klubovna","klusat","kluzkost","kmen","kmitat","kmotr","kniha","knot","koalice","koberec","kobka","kobliha","kobyla","kocour","kohout","kojenec","kokos","koktejl","kolaps","koleda","kolize","kolo","komando","kometa","komik","komnata","komora","kompas","komunita","konat","koncept","kondice","konec","konfese","kongres","konina","konkurs","kontakt","konzerva","kopanec","kopie","kopnout","koprovka","korbel","korektor","kormidlo","koroptev","korpus","koruna","koryto","korzet","kosatec","kostka","kotel","kotleta","kotoul","koukat","koupelna","kousek","kouzlo","kovboj","koza","kozoroh","krabice","krach","krajina","kralovat","krasopis","kravata","kredit","krejcar","kresba","kreveta","kriket","kritik","krize","krkavec","krmelec","krmivo","krocan","krok","kronika","kropit","kroupa","krovka","krtek","kruhadlo","krupice","krutost","krvinka","krychle","krypta","krystal","kryt","kudlanka","kufr","kujnost","kukla","kulajda","kulich","kulka","kulomet","kultura","kuna","kupodivu","kurt","kurzor","kutil","kvalita","kvasinka","kvestor","kynolog","kyselina","kytara","kytice","kytka","kytovec","kyvadlo","labrador","lachtan","ladnost","laik","lakomec","lamela","lampa","lanovka","lasice","laso","lastura","latinka","lavina","lebka","leckdy","leden","lednice","ledovka","ledvina","legenda","legie","legrace","lehce","lehkost","lehnout","lektvar","lenochod","lentilka","lepenka","lepidlo","letadlo","letec","letmo","letokruh","levhart","levitace","levobok","libra","lichotka","lidojed","lidskost","lihovina","lijavec","lilek","limetka","linie","linka","linoleum","listopad","litina","litovat","lobista","lodivod","logika","logoped","lokalita","loket","lomcovat","lopata","lopuch","lord","losos","lotr","loudal","louh","louka","louskat","lovec","lstivost","lucerna","lucifer","lump","lusk","lustrace","lvice","lyra","lyrika","lysina","madam","madlo","magistr","mahagon","majetek","majitel","majorita","makak","makovice","makrela","malba","malina","malovat","malvice","maminka","mandle","manko","marnost","masakr","maskot","masopust","matice","matrika","maturita","mazanec","mazivo","mazlit","mazurka","mdloba","mechanik","meditace","medovina","melasa","meloun","mentolka","metla","metoda","metr","mezera","migrace","mihnout","mihule","mikina","mikrofon","milenec","milimetr","milost","mimika","mincovna","minibar","minomet","minulost","miska","mistr","mixovat","mladost","mlha","mlhovina","mlok","mlsat","mluvit","mnich","mnohem","mobil","mocnost","modelka","modlitba","mohyla","mokro","molekula","momentka","monarcha","monokl","monstrum","montovat","monzun","mosaz","moskyt","most","motivace","motorka","motyka","moucha","moudrost","mozaika","mozek","mozol","mramor","mravenec","mrkev","mrtvola","mrzet","mrzutost","mstitel","mudrc","muflon","mulat","mumie","munice","muset","mutace","muzeum","muzikant","myslivec","mzda","nabourat","nachytat","nadace","nadbytek","nadhoz","nadobro","nadpis","nahlas","nahnat","nahodile","nahradit","naivita","najednou","najisto","najmout","naklonit","nakonec","nakrmit","nalevo","namazat","namluvit","nanometr","naoko","naopak","naostro","napadat","napevno","naplnit","napnout","naposled","naprosto","narodit","naruby","narychlo","nasadit","nasekat","naslepo","nastat","natolik","navenek","navrch","navzdory","nazvat","nebe","nechat","necky","nedaleko","nedbat","neduh","negace","nehet","nehoda","nejen","nejprve","neklid","nelibost","nemilost","nemoc","neochota","neonka","nepokoj","nerost","nerv","nesmysl","nesoulad","netvor","neuron","nevina","nezvykle","nicota","nijak","nikam","nikdy","nikl","nikterak","nitro","nocleh","nohavice","nominace","nora","norek","nositel","nosnost","nouze","noviny","novota","nozdra","nuda","nudle","nuget","nutit","nutnost","nutrie","nymfa","obal","obarvit","obava","obdiv","obec","obehnat","obejmout","obezita","obhajoba","obilnice","objasnit","objekt","obklopit","oblast","oblek","obliba","obloha","obluda","obnos","obohatit","obojek","obout","obrazec","obrna","obruba","obrys","obsah","obsluha","obstarat","obuv","obvaz","obvinit","obvod","obvykle","obyvatel","obzor","ocas","ocel","ocenit","ochladit","ochota","ochrana","ocitnout","odboj","odbyt","odchod","odcizit","odebrat","odeslat","odevzdat","odezva","odhadce","odhodit","odjet","odjinud","odkaz","odkoupit","odliv","odluka","odmlka","odolnost","odpad","odpis","odplout","odpor","odpustit","odpykat","odrazka","odsoudit","odstup","odsun","odtok","odtud","odvaha","odveta","odvolat","odvracet","odznak","ofina","ofsajd","ohlas","ohnisko","ohrada","ohrozit","ohryzek","okap","okenice","oklika","okno","okouzlit","okovy","okrasa","okres","okrsek","okruh","okupant","okurka","okusit","olejnina","olizovat","omak","omeleta","omezit","omladina","omlouvat","omluva","omyl","onehdy","opakovat","opasek","operace","opice","opilost","opisovat","opora","opozice","opravdu","oproti","orbital","orchestr","orgie","orlice","orloj","ortel","osada","oschnout","osika","osivo","oslava","oslepit","oslnit","oslovit","osnova","osoba","osolit","ospalec","osten","ostraha","ostuda","ostych","osvojit","oteplit","otisk","otop","otrhat","otrlost","otrok","otruby","otvor","ovanout","ovar","oves","ovlivnit","ovoce","oxid","ozdoba","pachatel","pacient","padouch","pahorek","pakt","palanda","palec","palivo","paluba","pamflet","pamlsek","panenka","panika","panna","panovat","panstvo","pantofle","paprika","parketa","parodie","parta","paruka","paryba","paseka","pasivita","pastelka","patent","patrona","pavouk","pazneht","pazourek","pecka","pedagog","pejsek","peklo","peloton","penalta","pendrek","penze","periskop","pero","pestrost","petarda","petice","petrolej","pevnina","pexeso","pianista","piha","pijavice","pikle","piknik","pilina","pilnost","pilulka","pinzeta","pipeta","pisatel","pistole","pitevna","pivnice","pivovar","placenta","plakat","plamen","planeta","plastika","platit","plavidlo","plaz","plech","plemeno","plenta","ples","pletivo","plevel","plivat","plnit","plno","plocha","plodina","plomba","plout","pluk","plyn","pobavit","pobyt","pochod","pocit","poctivec","podat","podcenit","podepsat","podhled","podivit","podklad","podmanit","podnik","podoba","podpora","podraz","podstata","podvod","podzim","poezie","pohanka","pohnutka","pohovor","pohroma","pohyb","pointa","pojistka","pojmout","pokazit","pokles","pokoj","pokrok","pokuta","pokyn","poledne","polibek","polknout","poloha","polynom","pomalu","pominout","pomlka","pomoc","pomsta","pomyslet","ponechat","ponorka","ponurost","popadat","popel","popisek","poplach","poprosit","popsat","popud","poradce","porce","porod","porucha","poryv","posadit","posed","posila","poskok","poslanec","posoudit","pospolu","postava","posudek","posyp","potah","potkan","potlesk","potomek","potrava","potupa","potvora","poukaz","pouto","pouzdro","povaha","povidla","povlak","povoz","povrch","povstat","povyk","povzdech","pozdrav","pozemek","poznatek","pozor","pozvat","pracovat","prahory","praktika","prales","praotec","praporek","prase","pravda","princip","prkno","probudit","procento","prodej","profese","prohra","projekt","prolomit","promile","pronikat","propad","prorok","prosba","proton","proutek","provaz","prskavka","prsten","prudkost","prut","prvek","prvohory","psanec","psovod","pstruh","ptactvo","puberta","puch","pudl","pukavec","puklina","pukrle","pult","pumpa","punc","pupen","pusa","pusinka","pustina","putovat","putyka","pyramida","pysk","pytel","racek","rachot","radiace","radnice","radon","raft","ragby","raketa","rakovina","rameno","rampouch","rande","rarach","rarita","rasovna","rastr","ratolest","razance","razidlo","reagovat","reakce","recept","redaktor","referent","reflex","rejnok","reklama","rekord","rekrut","rektor","reputace","revize","revma","revolver","rezerva","riskovat","riziko","robotika","rodokmen","rohovka","rokle","rokoko","romaneto","ropovod","ropucha","rorejs","rosol","rostlina","rotmistr","rotoped","rotunda","roubenka","roucho","roup","roura","rovina","rovnice","rozbor","rozchod","rozdat","rozeznat","rozhodce","rozinka","rozjezd","rozkaz","rozloha","rozmar","rozpad","rozruch","rozsah","roztok","rozum","rozvod","rubrika","ruchadlo","rukavice","rukopis","ryba","rybolov","rychlost","rydlo","rypadlo","rytina","ryzost","sadista","sahat","sako","samec","samizdat","samota","sanitka","sardinka","sasanka","satelit","sazba","sazenice","sbor","schovat","sebranka","secese","sedadlo","sediment","sedlo","sehnat","sejmout","sekera","sekta","sekunda","sekvoje","semeno","seno","servis","sesadit","seshora","seskok","seslat","sestra","sesuv","sesypat","setba","setina","setkat","setnout","setrvat","sever","seznam","shoda","shrnout","sifon","silnice","sirka","sirotek","sirup","situace","skafandr","skalisko","skanzen","skaut","skeptik","skica","skladba","sklenice","sklo","skluz","skoba","skokan","skoro","skripta","skrz","skupina","skvost","skvrna","slabika","sladidlo","slanina","slast","slavnost","sledovat","slepec","sleva","slezina","slib","slina","sliznice","slon","sloupek","slovo","sluch","sluha","slunce","slupka","slza","smaragd","smetana","smilstvo","smlouva","smog","smrad","smrk","smrtka","smutek","smysl","snad","snaha","snob","sobota","socha","sodovka","sokol","sopka","sotva","souboj","soucit","soudce","souhlas","soulad","soumrak","souprava","soused","soutok","souviset","spalovna","spasitel","spis","splav","spodek","spojenec","spolu","sponzor","spornost","spousta","sprcha","spustit","sranda","sraz","srdce","srna","srnec","srovnat","srpen","srst","srub","stanice","starosta","statika","stavba","stehno","stezka","stodola","stolek","stopa","storno","stoupat","strach","stres","strhnout","strom","struna","studna","stupnice","stvol","styk","subjekt","subtropy","suchar","sudost","sukno","sundat","sunout","surikata","surovina","svah","svalstvo","svetr","svatba","svazek","svisle","svitek","svoboda","svodidlo","svorka","svrab","sykavka","sykot","synek","synovec","sypat","sypkost","syrovost","sysel","sytost","tabletka","tabule","tahoun","tajemno","tajfun","tajga","tajit","tajnost","taktika","tamhle","tampon","tancovat","tanec","tanker","tapeta","tavenina","tazatel","technika","tehdy","tekutina","telefon","temnota","tendence","tenista","tenor","teplota","tepna","teprve","terapie","termoska","textil","ticho","tiskopis","titulek","tkadlec","tkanina","tlapka","tleskat","tlukot","tlupa","tmel","toaleta","topinka","topol","torzo","touha","toulec","tradice","traktor","tramp","trasa","traverza","trefit","trest","trezor","trhavina","trhlina","trochu","trojice","troska","trouba","trpce","trpitel","trpkost","trubec","truchlit","truhlice","trus","trvat","tudy","tuhnout","tuhost","tundra","turista","turnaj","tuzemsko","tvaroh","tvorba","tvrdost","tvrz","tygr","tykev","ubohost","uboze","ubrat","ubrousek","ubrus","ubytovna","ucho","uctivost","udivit","uhradit","ujednat","ujistit","ujmout","ukazatel","uklidnit","uklonit","ukotvit","ukrojit","ulice","ulita","ulovit","umyvadlo","unavit","uniforma","uniknout","upadnout","uplatnit","uplynout","upoutat","upravit","uran","urazit","usednout","usilovat","usmrtit","usnadnit","usnout","usoudit","ustlat","ustrnout","utahovat","utkat","utlumit","utonout","utopenec","utrousit","uvalit","uvolnit","uvozovka","uzdravit","uzel","uzenina","uzlina","uznat","vagon","valcha","valoun","vana","vandal","vanilka","varan","varhany","varovat","vcelku","vchod","vdova","vedro","vegetace","vejce","velbloud","veletrh","velitel","velmoc","velryba","venkov","veranda","verze","veselka","veskrze","vesnice","vespodu","vesta","veterina","veverka","vibrace","vichr","videohra","vidina","vidle","vila","vinice","viset","vitalita","vize","vizitka","vjezd","vklad","vkus","vlajka","vlak","vlasec","vlevo","vlhkost","vliv","vlnovka","vloupat","vnucovat","vnuk","voda","vodivost","vodoznak","vodstvo","vojensky","vojna","vojsko","volant","volba","volit","volno","voskovka","vozidlo","vozovna","vpravo","vrabec","vracet","vrah","vrata","vrba","vrcholek","vrhat","vrstva","vrtule","vsadit","vstoupit","vstup","vtip","vybavit","vybrat","vychovat","vydat","vydra","vyfotit","vyhledat","vyhnout","vyhodit","vyhradit","vyhubit","vyjasnit","vyjet","vyjmout","vyklopit","vykonat","vylekat","vymazat","vymezit","vymizet","vymyslet","vynechat","vynikat","vynutit","vypadat","vyplatit","vypravit","vypustit","vyrazit","vyrovnat","vyrvat","vyslovit","vysoko","vystavit","vysunout","vysypat","vytasit","vytesat","vytratit","vyvinout","vyvolat","vyvrhel","vyzdobit","vyznat","vzadu","vzbudit","vzchopit","vzdor","vzduch","vzdychat","vzestup","vzhledem","vzkaz","vzlykat","vznik","vzorek","vzpoura","vztah","vztek","xylofon","zabrat","zabydlet","zachovat","zadarmo","zadusit","zafoukat","zahltit","zahodit","zahrada","zahynout","zajatec","zajet","zajistit","zaklepat","zakoupit","zalepit","zamezit","zamotat","zamyslet","zanechat","zanikat","zaplatit","zapojit","zapsat","zarazit","zastavit","zasunout","zatajit","zatemnit","zatknout","zaujmout","zavalit","zavelet","zavinit","zavolat","zavrtat","zazvonit","zbavit","zbrusu","zbudovat","zbytek","zdaleka","zdarma","zdatnost","zdivo","zdobit","zdroj","zdvih","zdymadlo","zelenina","zeman","zemina","zeptat","zezadu","zezdola","zhatit","zhltnout","zhluboka","zhotovit","zhruba","zima","zimnice","zjemnit","zklamat","zkoumat","zkratka","zkumavka","zlato","zlehka","zloba","zlom","zlost","zlozvyk","zmapovat","zmar","zmatek","zmije","zmizet","zmocnit","zmodrat","zmrzlina","zmutovat","znak","znalost","znamenat","znovu","zobrazit","zotavit","zoubek","zoufale","zplodit","zpomalit","zprava","zprostit","zprudka","zprvu","zrada","zranit","zrcadlo","zrnitost","zrno","zrovna","zrychlit","zrzavost","zticha","ztratit","zubovina","zubr","zvednout","zvenku","zvesela","zvon","zvrat","zvukovod","zvyk"]["abandon","ability","able","about","above","absent","absorb","abstract","absurd","abuse","access","accident","account","accuse","achieve","acid","acoustic","acquire","across","act","action","actor","actress","actual","adapt","add","addict","address","adjust","admit","adult","advance","advice","aerobic","affair","afford","afraid","again","age","agent","agree","ahead","aim","air","airport","aisle","alarm","album","alcohol","alert","alien","all","alley","allow","almost","alone","alpha","already","also","alter","always","amateur","amazing","among","amount","amused","analyst","anchor","ancient","anger","angle","angry","animal","ankle","announce","annual","another","answer","antenna","antique","anxiety","any","apart","apology","appear","apple","approve","april","arch","arctic","area","arena","argue","arm","armed","armor","army","around","arrange","arrest","arrive","arrow","art","artefact","artist","artwork","ask","aspect","assault","asset","assist","assume","asthma","athlete","atom","attack","attend","attitude","attract","auction","audit","august","aunt","author","auto","autumn","average","avocado","avoid","awake","aware","away","awesome","awful","awkward","axis","baby","bachelor","bacon","badge","bag","balance","balcony","ball","bamboo","banana","banner","bar","barely","bargain","barrel","base","basic","basket","battle","beach","bean","beauty","because","become","beef","before","begin","behave","behind","believe","below","belt","bench","benefit","best","betray","better","between","beyond","bicycle","bid","bike","bind","biology","bird","birth","bitter","black","blade","blame","blanket","blast","bleak","bless","blind","blood","blossom","blouse","blue","blur","blush","board","boat","body","boil","bomb","bone","bonus","book","boost","border","boring","borrow","boss","bottom","bounce","box","boy","bracket","brain","brand","brass","brave","bread","breeze","brick","bridge","brief","bright","bring","brisk","broccoli","broken","bronze","broom","brother","brown","brush","bubble","buddy","budget","buffalo","build","bulb","bulk","bullet","bundle","bunker","burden","burger","burst","bus","business","busy","butter","buyer","buzz","cabbage","cabin","cable","cactus","cage","cake","call","calm","camera","camp","can","canal","cancel","candy","cannon","canoe","canvas","canyon","capable","capital","captain","car","carbon","card","cargo","carpet","carry","cart","case","cash","casino","castle","casual","cat","catalog","catch","category","cattle","caught","cause","caution","cave","ceiling","celery","cement","census","century","cereal","certain","chair","chalk","champion","change","chaos","chapter","charge","chase","chat","cheap","check","cheese","chef","cherry","chest","chicken","chief","child","chimney","choice","choose","chronic","chuckle","chunk","churn","cigar","cinnamon","circle","citizen","city","civil","claim","clap","clarify","claw","clay","clean","clerk","clever","click","client","cliff","climb","clinic","clip","clock","clog","close","cloth","cloud","clown","club","clump","cluster","clutch","coach","coast","coconut","code","coffee","coil","coin","collect","color","column","combine","come","comfort","comic","common","company","concert","conduct","confirm","congress","connect","consider","control","convince","cook","cool","copper","copy","coral","core","corn","correct","cost","cotton","couch","country","couple","course","cousin","cover","coyote","crack","cradle","craft","cram","crane","crash","crater","crawl","crazy","cream","credit","creek","crew","cricket","crime","crisp","critic","crop","cross","crouch","crowd","crucial","cruel","cruise","crumble","crunch","crush","cry","crystal","cube","culture","cup","cupboard","curious","current","curtain","curve","cushion","custom","cute","cycle","dad","damage","damp","dance","danger","daring","dash","daughter","dawn","day","deal","debate","debris","decade","december","decide","decline","decorate","decrease","deer","defense","define","defy","degree","delay","deliver","demand","demise","denial","dentist","deny","depart","depend","deposit","depth","deputy","derive","describe","desert","design","desk","despair","destroy","detail","detect","develop","device","devote","diagram","dial","diamond","diary","dice","diesel","diet","differ","digital","dignity","dilemma","dinner","dinosaur","direct","dirt","disagree","discover","disease","dish","dismiss","disorder","display","distance","divert","divide","divorce","dizzy","doctor","document","dog","doll","dolphin","domain","donate","donkey","donor","door","dose","double","dove","draft","dragon","drama","drastic","draw","dream","dress","drift","drill","drink","drip","drive","drop","drum","dry","duck","dumb","dune","during","dust","dutch","duty","dwarf","dynamic","eager","eagle","early","earn","earth","easily","east","easy","echo","ecology","economy","edge","edit","educate","effort","egg","eight","either","elbow","elder","electric","elegant","element","elephant","elevator","elite","else","embark","embody","embrace","emerge","emotion","employ","empower","empty","enable","enact","end","endless","endorse","enemy","energy","enforce","engage","engine","enhance","enjoy","enlist","enough","enrich","enroll","ensure","enter","entire","entry","envelope","episode","equal","equip","era","erase","erode","erosion","error","erupt","escape","essay","essence","estate","eternal","ethics","evidence","evil","evoke","evolve","exact","example","excess","exchange","excite","exclude","excuse","execute","exercise","exhaust","exhibit","exile","exist","exit","exotic","expand","expect","expire","explain","expose","express","extend","extra","eye","eyebrow","fabric","face","faculty","fade","faint","faith","fall","false","fame","family","famous","fan","fancy","fantasy","farm","fashion","fat","fatal","father","fatigue","fault","favorite","feature","february","federal","fee","feed","feel","female","fence","festival","fetch","fever","few","fiber","fiction","field","figure","file","film","filter","final","find","fine","finger","finish","fire","firm","first","fiscal","fish","fit","fitness","fix","flag","flame","flash","flat","flavor","flee","flight","flip","float","flock","floor","flower","fluid","flush","fly","foam","focus","fog","foil","fold","follow","food","foot","force","forest","forget","fork","fortune","forum","forward","fossil","foster","found","fox","fragile","frame","frequent","fresh","friend","fringe","frog","front","frost","frown","frozen","fruit","fuel","fun","funny","furnace","fury","future","gadget","gain","galaxy","gallery","game","gap","garage","garbage","garden","garlic","garment","gas","gasp","gate","gather","gauge","gaze","general","genius","genre","gentle","genuine","gesture","ghost","giant","gift","giggle","ginger","giraffe","girl","give","glad","glance","glare","glass","glide","glimpse","globe","gloom","glory","glove","glow","glue","goat","goddess","gold","good","goose","gorilla","gospel","gossip","govern","gown","grab","grace","grain","grant","grape","grass","gravity","great","green","grid","grief","grit","grocery","group","grow","grunt","guard","guess","guide","guilt","guitar","gun","gym","habit","hair","half","hammer","hamster","hand","happy","harbor","hard","harsh","harvest","hat","have","hawk","hazard","head","health","heart","heavy","hedgehog","height","hello","helmet","help","hen","hero","hidden","high","hill","hint","hip","hire","history","hobby","hockey","hold","hole","holiday","hollow","home","honey","hood","hope","horn","horror","horse","hospital","host","hotel","hour","hover","hub","huge","human","humble","humor","hundred","hungry","hunt","hurdle","hurry","hurt","husband","hybrid","ice","icon","idea","identify","idle","ignore","ill","illegal","illness","image","imitate","immense","immune","impact","impose","improve","impulse","inch","include","income","increase","index","indicate","indoor","industry","infant","inflict","inform","inhale","inherit","initial","inject","injury","inmate","inner","innocent","input","inquiry","insane","insect","inside","inspire","install","intact","interest","into","invest","invite","involve","iron","island","isolate","issue","item","ivory","jacket","jaguar","jar","jazz","jealous","jeans","jelly","jewel","job","join","joke","journey","joy","judge","juice","jump","jungle","junior","junk","just","kangaroo","keen","keep","ketchup","key","kick","kid","kidney","kind","kingdom","kiss","kit","kitchen","kite","kitten","kiwi","knee","knife","knock","know","lab","label","labor","ladder","lady","lake","lamp","language","laptop","large","later","latin","laugh","laundry","lava","law","lawn","lawsuit","layer","lazy","leader","leaf","learn","leave","lecture","left","leg","legal","legend","leisure","lemon","lend","length","lens","leopard","lesson","letter","level","liar","liberty","library","license","life","lift","light","like","limb","limit","link","lion","liquid","list","little","live","lizard","load","loan","lobster","local","lock","logic","lonely","long","loop","lottery","loud","lounge","love","loyal","lucky","luggage","lumber","lunar","lunch","luxury","lyrics","machine","mad","magic","magnet","maid","mail","main","major","make","mammal","man","manage","mandate","mango","mansion","manual","maple","marble","march","margin","marine","market","marriage","mask","mass","master","match","material","math","matrix","matter","maximum","maze","meadow","mean","measure","meat","mechanic","medal","media","melody","melt","member","memory","mention","menu","mercy","merge","merit","merry","mesh","message","metal","method","middle","midnight","milk","million","mimic","mind","minimum","minor","minute","miracle","mirror","misery","miss","mistake","mix","mixed","mixture","mobile","model","modify","mom","moment","monitor","monkey","monster","month","moon","moral","more","morning","mosquito","mother","motion","motor","mountain","mouse","move","movie","much","muffin","mule","multiply","muscle","museum","mushroom","music","must","mutual","myself","mystery","myth","naive","name","napkin","narrow","nasty","nation","nature","near","neck","need","negative","neglect","neither","nephew","nerve","nest","net","network","neutral","never","news","next","nice","night","noble","noise","nominee","noodle","normal","north","nose","notable","note","nothing","notice","novel","now","nuclear","number","nurse","nut","oak","obey","object","oblige","obscure","observe","obtain","obvious","occur","ocean","october","odor","off","offer","office","often","oil","okay","old","olive","olympic","omit","once","one","onion","online","only","open","opera","opinion","oppose","option","orange","orbit","orchard","order","ordinary","organ","orient","original","orphan","ostrich","other","outdoor","outer","output","outside","oval","oven","over","own","owner","oxygen","oyster","ozone","pact","paddle","page","pair","palace","palm","panda","panel","panic","panther","paper","parade","parent","park","parrot","party","pass","patch","path","patient","patrol","pattern","pause","pave","payment","peace","peanut","pear","peasant","pelican","pen","penalty","pencil","people","pepper","perfect","permit","person","pet","phone","photo","phrase","physical","piano","picnic","picture","piece","pig","pigeon","pill","pilot","pink","pioneer","pipe","pistol","pitch","pizza","place","planet","plastic","plate","play","please","pledge","pluck","plug","plunge","poem","poet","point","polar","pole","police","pond","pony","pool","popular","portion","position","possible","post","potato","pottery","poverty","powder","power","practice","praise","predict","prefer","prepare","present","pretty","prevent","price","pride","primary","print","priority","prison","private","prize","problem","process","produce","profit","program","project","promote","proof","property","prosper","protect","proud","provide","public","pudding","pull","pulp","pulse","pumpkin","punch","pupil","puppy","purchase","purity","purpose","purse","push","put","puzzle","pyramid","quality","quantum","quarter","question","quick","quit","quiz","quote","rabbit","raccoon","race","rack","radar","radio","rail","rain","raise","rally","ramp","ranch","random","range","rapid","rare","rate","rather","raven","raw","razor","ready","real","reason","rebel","rebuild","recall","receive","recipe","record","recycle","reduce","reflect","reform","refuse","region","regret","regular","reject","relax","release","relief","rely","remain","remember","remind","remove","render","renew","rent","reopen","repair","repeat","replace","report","require","rescue","resemble","resist","resource","response","result","retire","retreat","return","reunion","reveal","review","reward","rhythm","rib","ribbon","rice","rich","ride","ridge","rifle","right","rigid","ring","riot","ripple","risk","ritual","rival","river","road","roast","robot","robust","rocket","romance","roof","rookie","room","rose","rotate","rough","round","route","royal","rubber","rude","rug","rule","run","runway","rural","sad","saddle","sadness","safe","sail","salad","salmon","salon","salt","salute","same","sample","sand","satisfy","satoshi","sauce","sausage","save","say","scale","scan","scare","scatter","scene","scheme","school","science","scissors","scorpion","scout","scrap","screen","script","scrub","sea","search","season","seat","second","secret","section","security","seed","seek","segment","select","sell","seminar","senior","sense","sentence","series","service","session","settle","setup","seven","shadow","shaft","shallow","share","shed","shell","sheriff","shield","shift","shine","ship","shiver","shock","shoe","shoot","shop","short","shoulder","shove","shrimp","shrug","shuffle","shy","sibling","sick","side","siege","sight","sign","silent","silk","silly","silver","similar","simple","since","sing","siren","sister","situate","six","size","skate","sketch","ski","skill","skin","skirt","skull","slab","slam","sleep","slender","slice","slide","slight","slim","slogan","slot","slow","slush","small","smart","smile","smoke","smooth","snack","snake","snap","sniff","snow","soap","soccer","social","sock","soda","soft","solar","soldier","solid","solution","solve","someone","song","soon","sorry","sort","soul","sound","soup","source","south","space","spare","spatial","spawn","speak","special","speed","spell","spend","sphere","spice","spider","spike","spin","spirit","split","spoil","sponsor","spoon","sport","spot","spray","spread","spring","spy","square","squeeze","squirrel","stable","stadium","staff","stage","stairs","stamp","stand","start","state","stay","steak","steel","stem","step","stereo","stick","still","sting","stock","stomach","stone","stool","story","stove","strategy","street","strike","strong","struggle","student","stuff","stumble","style","subject","submit","subway","success","such","sudden","suffer","sugar","suggest","suit","summer","sun","sunny","sunset","super","supply","supreme","sure","surface","surge","surprise","surround","survey","suspect","sustain","swallow","swamp","swap","swarm","swear","sweet","swift","swim","swing","switch","sword","symbol","symptom","syrup","system","table","tackle","tag","tail","talent","talk","tank","tape","target","task","taste","tattoo","taxi","teach","team","tell","ten","tenant","tennis","tent","term","test","text","thank","that","theme","then","theory","there","they","thing","this","thought","three","thrive","throw","thumb","thunder","ticket","tide","tiger","tilt","timber","time","tiny","tip","tired","tissue","title","toast","tobacco","today","toddler","toe","together","toilet","token","tomato","tomorrow","tone","tongue","tonight","tool","tooth","top","topic","topple","torch","tornado","tortoise","toss","total","tourist","toward","tower","town","toy","track","trade","traffic","tragic","train","transfer","trap","trash","travel","tray","treat","tree","trend","trial","tribe","trick","trigger","trim","trip","trophy","trouble","truck","true","truly","trumpet","trust","truth","try","tube","tuition","tumble","tuna","tunnel","turkey","turn","turtle","twelve","twenty","twice","twin","twist","two","type","typical","ugly","umbrella","unable","unaware","uncle","uncover","under","undo","unfair","unfold","unhappy","uniform","unique","unit","universe","unknown","unlock","until","unusual","unveil","update","upgrade","uphold","upon","upper","upset","urban","urge","usage","use","used","useful","useless","usual","utility","vacant","vacuum","vague","valid","valley","valve","van","vanish","vapor","various","vast","vault","vehicle","velvet","vendor","venture","venue","verb","verify","version","very","vessel","veteran","viable","vibrant","vicious","victory","video","view","village","vintage","violin","virtual","virus","visa","visit","visual","vital","vivid","vocal","voice","void","volcano","volume","vote","voyage","wage","wagon","wait","walk","wall","walnut","want","warfare","warm","warrior","wash","wasp","waste","water","wave","way","wealth","weapon","wear","weasel","weather","web","wedding","weekend","weird","welcome","west","wet","whale","what","wheat","wheel","when","where","whip","whisper","wide","width","wife","wild","will","win","window","wine","wing","wink","winner","winter","wire","wisdom","wise","wish","witness","wolf","woman","wonder","wood","wool","word","work","world","worry","worth","wrap","wreck","wrestle","wrist","write","wrong","yard","year","yellow","you","young","youth","zebra","zero","zone","zoo"]["abaisser","abandon","abdiquer","abeille","abolir","aborder","aboutir","aboyer","abrasif","abreuver","abriter","abroger","abrupt","absence","absolu","absurde","abusif","abyssal","académie","acajou","acarien","accabler","accepter","acclamer","accolade","accroche","accuser","acerbe","achat","acheter","aciduler","acier","acompte","acquérir","acronyme","acteur","actif","actuel","adepte","adéquat","adhésif","adjectif","adjuger","admettre","admirer","adopter","adorer","adoucir","adresse","adroit","adulte","adverbe","aérer","aéronef","affaire","affecter","affiche","affreux","affubler","agacer","agencer","agile","agiter","agrafer","agréable","agrume","aider","aiguille","ailier","aimable","aisance","ajouter","ajuster","alarmer","alchimie","alerte","algèbre","algue","aliéner","aliment","alléger","alliage","allouer","allumer","alourdir","alpaga","altesse","alvéole","amateur","ambigu","ambre","aménager","amertume","amidon","amiral","amorcer","amour","amovible","amphibie","ampleur","amusant","analyse","anaphore","anarchie","anatomie","ancien","anéantir","angle","angoisse","anguleux","animal","annexer","annonce","annuel","anodin","anomalie","anonyme","anormal","antenne","antidote","anxieux","apaiser","apéritif","aplanir","apologie","appareil","appeler","apporter","appuyer","aquarium","aqueduc","arbitre","arbuste","ardeur","ardoise","argent","arlequin","armature","armement","armoire","armure","arpenter","arracher","arriver","arroser","arsenic","artériel","article","aspect","asphalte","aspirer","assaut","asservir","assiette","associer","assurer","asticot","astre","astuce","atelier","atome","atrium","atroce","attaque","attentif","attirer","attraper","aubaine","auberge","audace","audible","augurer","aurore","automne","autruche","avaler","avancer","avarice","avenir","averse","aveugle","aviateur","avide","avion","aviser","avoine","avouer","avril","axial","axiome","badge","bafouer","bagage","baguette","baignade","balancer","balcon","baleine","balisage","bambin","bancaire","bandage","banlieue","bannière","banquier","barbier","baril","baron","barque","barrage","bassin","bastion","bataille","bateau","batterie","baudrier","bavarder","belette","bélier","belote","bénéfice","berceau","berger","berline","bermuda","besace","besogne","bétail","beurre","biberon","bicycle","bidule","bijou","bilan","bilingue","billard","binaire","biologie","biopsie","biotype","biscuit","bison","bistouri","bitume","bizarre","blafard","blague","blanchir","blessant","blinder","blond","bloquer","blouson","bobard","bobine","boire","boiser","bolide","bonbon","bondir","bonheur","bonifier","bonus","bordure","borne","botte","boucle","boueux","bougie","boulon","bouquin","bourse","boussole","boutique","boxeur","branche","brasier","brave","brebis","brèche","breuvage","bricoler","brigade","brillant","brioche","brique","brochure","broder","bronzer","brousse","broyeur","brume","brusque","brutal","bruyant","buffle","buisson","bulletin","bureau","burin","bustier","butiner","butoir","buvable","buvette","cabanon","cabine","cachette","cadeau","cadre","caféine","caillou","caisson","calculer","calepin","calibre","calmer","calomnie","calvaire","camarade","caméra","camion","campagne","canal","caneton","canon","cantine","canular","capable","caporal","caprice","capsule","capter","capuche","carabine","carbone","caresser","caribou","carnage","carotte","carreau","carton","cascade","casier","casque","cassure","causer","caution","cavalier","caverne","caviar","cédille","ceinture","céleste","cellule","cendrier","censurer","central","cercle","cérébral","cerise","cerner","cerveau","cesser","chagrin","chaise","chaleur","chambre","chance","chapitre","charbon","chasseur","chaton","chausson","chavirer","chemise","chenille","chéquier","chercher","cheval","chien","chiffre","chignon","chimère","chiot","chlorure","chocolat","choisir","chose","chouette","chrome","chute","cigare","cigogne","cimenter","cinéma","cintrer","circuler","cirer","cirque","citerne","citoyen","citron","civil","clairon","clameur","claquer","classe","clavier","client","cligner","climat","clivage","cloche","clonage","cloporte","cobalt","cobra","cocasse","cocotier","coder","codifier","coffre","cogner","cohésion","coiffer","coincer","colère","colibri","colline","colmater","colonel","combat","comédie","commande","compact","concert","conduire","confier","congeler","connoter","consonne","contact","convexe","copain","copie","corail","corbeau","cordage","corniche","corpus","correct","cortège","cosmique","costume","coton","coude","coupure","courage","couteau","couvrir","coyote","crabe","crainte","cravate","crayon","créature","créditer","crémeux","creuser","crevette","cribler","crier","cristal","critère","croire","croquer","crotale","crucial","cruel","crypter","cubique","cueillir","cuillère","cuisine","cuivre","culminer","cultiver","cumuler","cupide","curatif","curseur","cyanure","cycle","cylindre","cynique","daigner","damier","danger","danseur","dauphin","débattre","débiter","déborder","débrider","débutant","décaler","décembre","déchirer","décider","déclarer","décorer","décrire","décupler","dédale","déductif","déesse","défensif","défiler","défrayer","dégager","dégivrer","déglutir","dégrafer","déjeuner","délice","déloger","demander","demeurer","démolir","dénicher","dénouer","dentelle","dénuder","départ","dépenser","déphaser","déplacer","déposer","déranger","dérober","désastre","descente","désert","désigner","désobéir","dessiner","destrier","détacher","détester","détourer","détresse","devancer","devenir","deviner","devoir","diable","dialogue","diamant","dicter","différer","digérer","digital","digne","diluer","dimanche","diminuer","dioxyde","directif","diriger","discuter","disposer","dissiper","distance","divertir","diviser","docile","docteur","dogme","doigt","domaine","domicile","dompter","donateur","donjon","donner","dopamine","dortoir","dorure","dosage","doseur","dossier","dotation","douanier","double","douceur","douter","doyen","dragon","draper","dresser","dribbler","droiture","duperie","duplexe","durable","durcir","dynastie","éblouir","écarter","écharpe","échelle","éclairer","éclipse","éclore","écluse","école","économie","écorce","écouter","écraser","écrémer","écrivain","écrou","écume","écureuil","édifier","éduquer","effacer","effectif","effigie","effort","effrayer","effusion","égaliser","égarer","éjecter","élaborer","élargir","électron","élégant","éléphant","élève","éligible","élitisme","éloge","élucider","éluder","emballer","embellir","embryon","émeraude","émission","emmener","émotion","émouvoir","empereur","employer","emporter","emprise","émulsion","encadrer","enchère","enclave","encoche","endiguer","endosser","endroit","enduire","énergie","enfance","enfermer","enfouir","engager","engin","englober","énigme","enjamber","enjeu","enlever","ennemi","ennuyeux","enrichir","enrobage","enseigne","entasser","entendre","entier","entourer","entraver","énumérer","envahir","enviable","envoyer","enzyme","éolien","épaissir","épargne","épatant","épaule","épicerie","épidémie","épier","épilogue","épine","épisode","épitaphe","époque","épreuve","éprouver","épuisant","équerre","équipe","ériger","érosion","erreur","éruption","escalier","espadon","espèce","espiègle","espoir","esprit","esquiver","essayer","essence","essieu","essorer","estime","estomac","estrade","étagère","étaler","étanche","étatique","éteindre","étendoir","éternel","éthanol","éthique","ethnie","étirer","étoffer","étoile","étonnant","étourdir","étrange","étroit","étude","euphorie","évaluer","évasion","éventail","évidence","éviter","évolutif","évoquer","exact","exagérer","exaucer","exceller","excitant","exclusif","excuse","exécuter","exemple","exercer","exhaler","exhorter","exigence","exiler","exister","exotique","expédier","explorer","exposer","exprimer","exquis","extensif","extraire","exulter","fable","fabuleux","facette","facile","facture","faiblir","falaise","fameux","famille","farceur","farfelu","farine","farouche","fasciner","fatal","fatigue","faucon","fautif","faveur","favori","fébrile","féconder","fédérer","félin","femme","fémur","fendoir","féodal","fermer","féroce","ferveur","festival","feuille","feutre","février","fiasco","ficeler","fictif","fidèle","figure","filature","filetage","filière","filleul","filmer","filou","filtrer","financer","finir","fiole","firme","fissure","fixer","flairer","flamme","flasque","flatteur","fléau","flèche","fleur","flexion","flocon","flore","fluctuer","fluide","fluvial","folie","fonderie","fongible","fontaine","forcer","forgeron","formuler","fortune","fossile","foudre","fougère","fouiller","foulure","fourmi","fragile","fraise","franchir","frapper","frayeur","frégate","freiner","frelon","frémir","frénésie","frère","friable","friction","frisson","frivole","froid","fromage","frontal","frotter","fruit","fugitif","fuite","fureur","furieux","furtif","fusion","futur","gagner","galaxie","galerie","gambader","garantir","gardien","garnir","garrigue","gazelle","gazon","géant","gélatine","gélule","gendarme","général","génie","genou","gentil","géologie","géomètre","géranium","germe","gestuel","geyser","gibier","gicler","girafe","givre","glace","glaive","glisser","globe","gloire","glorieux","golfeur","gomme","gonfler","gorge","gorille","goudron","gouffre","goulot","goupille","gourmand","goutte","graduel","graffiti","graine","grand","grappin","gratuit","gravir","grenat","griffure","griller","grimper","grogner","gronder","grotte","groupe","gruger","grutier","gruyère","guépard","guerrier","guide","guimauve","guitare","gustatif","gymnaste","gyrostat","habitude","hachoir","halte","hameau","hangar","hanneton","haricot","harmonie","harpon","hasard","hélium","hématome","herbe","hérisson","hermine","héron","hésiter","heureux","hiberner","hibou","hilarant","histoire","hiver","homard","hommage","homogène","honneur","honorer","honteux","horde","horizon","horloge","hormone","horrible","houleux","housse","hublot","huileux","humain","humble","humide","humour","hurler","hydromel","hygiène","hymne","hypnose","idylle","ignorer","iguane","illicite","illusion","image","imbiber","imiter","immense","immobile","immuable","impact","impérial","implorer","imposer","imprimer","imputer","incarner","incendie","incident","incliner","incolore","indexer","indice","inductif","inédit","ineptie","inexact","infini","infliger","informer","infusion","ingérer","inhaler","inhiber","injecter","injure","innocent","inoculer","inonder","inscrire","insecte","insigne","insolite","inspirer","instinct","insulter","intact","intense","intime","intrigue","intuitif","inutile","invasion","inventer","inviter","invoquer","ironique","irradier","irréel","irriter","isoler","ivoire","ivresse","jaguar","jaillir","jambe","janvier","jardin","jauger","jaune","javelot","jetable","jeton","jeudi","jeunesse","joindre","joncher","jongler","joueur","jouissif","journal","jovial","joyau","joyeux","jubiler","jugement","junior","jupon","juriste","justice","juteux","juvénile","kayak","kimono","kiosque","label","labial","labourer","lacérer","lactose","lagune","laine","laisser","laitier","lambeau","lamelle","lampe","lanceur","langage","lanterne","lapin","largeur","larme","laurier","lavabo","lavoir","lecture","légal","léger","légume","lessive","lettre","levier","lexique","lézard","liasse","libérer","libre","licence","licorne","liège","lièvre","ligature","ligoter","ligue","limer","limite","limonade","limpide","linéaire","lingot","lionceau","liquide","lisière","lister","lithium","litige","littoral","livreur","logique","lointain","loisir","lombric","loterie","louer","lourd","loutre","louve","loyal","lubie","lucide","lucratif","lueur","lugubre","luisant","lumière","lunaire","lundi","luron","lutter","luxueux","machine","magasin","magenta","magique","maigre","maillon","maintien","mairie","maison","majorer","malaxer","maléfice","malheur","malice","mallette","mammouth","mandater","maniable","manquant","manteau","manuel","marathon","marbre","marchand","mardi","maritime","marqueur","marron","marteler","mascotte","massif","matériel","matière","matraque","maudire","maussade","mauve","maximal","méchant","méconnu","médaille","médecin","méditer","méduse","meilleur","mélange","mélodie","membre","mémoire","menacer","mener","menhir","mensonge","mentor","mercredi","mérite","merle","messager","mesure","métal","météore","méthode","métier","meuble","miauler","microbe","miette","mignon","migrer","milieu","million","mimique","mince","minéral","minimal","minorer","minute","miracle","miroiter","missile","mixte","mobile","moderne","moelleux","mondial","moniteur","monnaie","monotone","monstre","montagne","monument","moqueur","morceau","morsure","mortier","moteur","motif","mouche","moufle","moulin","mousson","mouton","mouvant","multiple","munition","muraille","murène","murmure","muscle","muséum","musicien","mutation","muter","mutuel","myriade","myrtille","mystère","mythique","nageur","nappe","narquois","narrer","natation","nation","nature","naufrage","nautique","navire","nébuleux","nectar","néfaste","négation","négliger","négocier","neige","nerveux","nettoyer","neurone","neutron","neveu","niche","nickel","nitrate","niveau","noble","nocif","nocturne","noirceur","noisette","nomade","nombreux","nommer","normatif","notable","notifier","notoire","nourrir","nouveau","novateur","novembre","novice","nuage","nuancer","nuire","nuisible","numéro","nuptial","nuque","nutritif","obéir","objectif","obliger","obscur","observer","obstacle","obtenir","obturer","occasion","occuper","océan","octobre","octroyer","octupler","oculaire","odeur","odorant","offenser","officier","offrir","ogive","oiseau","oisillon","olfactif","olivier","ombrage","omettre","onctueux","onduler","onéreux","onirique","opale","opaque","opérer","opinion","opportun","opprimer","opter","optique","orageux","orange","orbite","ordonner","oreille","organe","orgueil","orifice","ornement","orque","ortie","osciller","osmose","ossature","otarie","ouragan","ourson","outil","outrager","ouvrage","ovation","oxyde","oxygène","ozone","paisible","palace","palmarès","palourde","palper","panache","panda","pangolin","paniquer","panneau","panorama","pantalon","papaye","papier","papoter","papyrus","paradoxe","parcelle","paresse","parfumer","parler","parole","parrain","parsemer","partager","parure","parvenir","passion","pastèque","paternel","patience","patron","pavillon","pavoiser","payer","paysage","peigne","peintre","pelage","pélican","pelle","pelouse","peluche","pendule","pénétrer","pénible","pensif","pénurie","pépite","péplum","perdrix","perforer","période","permuter","perplexe","persil","perte","peser","pétale","petit","pétrir","peuple","pharaon","phobie","phoque","photon","phrase","physique","piano","pictural","pièce","pierre","pieuvre","pilote","pinceau","pipette","piquer","pirogue","piscine","piston","pivoter","pixel","pizza","placard","plafond","plaisir","planer","plaque","plastron","plateau","pleurer","plexus","pliage","plomb","plonger","pluie","plumage","pochette","poésie","poète","pointe","poirier","poisson","poivre","polaire","policier","pollen","polygone","pommade","pompier","ponctuel","pondérer","poney","portique","position","posséder","posture","potager","poteau","potion","pouce","poulain","poumon","pourpre","poussin","pouvoir","prairie","pratique","précieux","prédire","préfixe","prélude","prénom","présence","prétexte","prévoir","primitif","prince","prison","priver","problème","procéder","prodige","profond","progrès","proie","projeter","prologue","promener","propre","prospère","protéger","prouesse","proverbe","prudence","pruneau","psychose","public","puceron","puiser","pulpe","pulsar","punaise","punitif","pupitre","purifier","puzzle","pyramide","quasar","querelle","question","quiétude","quitter","quotient","racine","raconter","radieux","ragondin","raideur","raisin","ralentir","rallonge","ramasser","rapide","rasage","ratisser","ravager","ravin","rayonner","réactif","réagir","réaliser","réanimer","recevoir","réciter","réclamer","récolter","recruter","reculer","recycler","rédiger","redouter","refaire","réflexe","réformer","refrain","refuge","régalien","région","réglage","régulier","réitérer","rejeter","rejouer","relatif","relever","relief","remarque","remède","remise","remonter","remplir","remuer","renard","renfort","renifler","renoncer","rentrer","renvoi","replier","reporter","reprise","reptile","requin","réserve","résineux","résoudre","respect","rester","résultat","rétablir","retenir","réticule","retomber","retracer","réunion","réussir","revanche","revivre","révolte","révulsif","richesse","rideau","rieur","rigide","rigoler","rincer","riposter","risible","risque","rituel","rival","rivière","rocheux","romance","rompre","ronce","rondin","roseau","rosier","rotatif","rotor","rotule","rouge","rouille","rouleau","routine","royaume","ruban","rubis","ruche","ruelle","rugueux","ruiner","ruisseau","ruser","rustique","rythme","sabler","saboter","sabre","sacoche","safari","sagesse","saisir","salade","salive","salon","saluer","samedi","sanction","sanglier","sarcasme","sardine","saturer","saugrenu","saumon","sauter","sauvage","savant","savonner","scalpel","scandale","scélérat","scénario","sceptre","schéma","science","scinder","score","scrutin","sculpter","séance","sécable","sécher","secouer","sécréter","sédatif","séduire","seigneur","séjour","sélectif","semaine","sembler","semence","séminal","sénateur","sensible","sentence","séparer","séquence","serein","sergent","sérieux","serrure","sérum","service","sésame","sévir","sevrage","sextuple","sidéral","siècle","siéger","siffler","sigle","signal","silence","silicium","simple","sincère","sinistre","siphon","sirop","sismique","situer","skier","social","socle","sodium","soigneux","soldat","soleil","solitude","soluble","sombre","sommeil","somnoler","sonde","songeur","sonnette","sonore","sorcier","sortir","sosie","sottise","soucieux","soudure","souffle","soulever","soupape","source","soutirer","souvenir","spacieux","spatial","spécial","sphère","spiral","stable","station","sternum","stimulus","stipuler","strict","studieux","stupeur","styliste","sublime","substrat","subtil","subvenir","succès","sucre","suffixe","suggérer","suiveur","sulfate","superbe","supplier","surface","suricate","surmener","surprise","sursaut","survie","suspect","syllabe","symbole","symétrie","synapse","syntaxe","système","tabac","tablier","tactile","tailler","talent","talisman","talonner","tambour","tamiser","tangible","tapis","taquiner","tarder","tarif","tartine","tasse","tatami","tatouage","taupe","taureau","taxer","témoin","temporel","tenaille","tendre","teneur","tenir","tension","terminer","terne","terrible","tétine","texte","thème","théorie","thérapie","thorax","tibia","tiède","timide","tirelire","tiroir","tissu","titane","titre","tituber","toboggan","tolérant","tomate","tonique","tonneau","toponyme","torche","tordre","tornade","torpille","torrent","torse","tortue","totem","toucher","tournage","tousser","toxine","traction","trafic","tragique","trahir","train","trancher","travail","trèfle","tremper","trésor","treuil","triage","tribunal","tricoter","trilogie","triomphe","tripler","triturer","trivial","trombone","tronc","tropical","troupeau","tuile","tulipe","tumulte","tunnel","turbine","tuteur","tutoyer","tuyau","tympan","typhon","typique","tyran","ubuesque","ultime","ultrason","unanime","unifier","union","unique","unitaire","univers","uranium","urbain","urticant","usage","usine","usuel","usure","utile","utopie","vacarme","vaccin","vagabond","vague","vaillant","vaincre","vaisseau","valable","valise","vallon","valve","vampire","vanille","vapeur","varier","vaseux","vassal","vaste","vecteur","vedette","végétal","véhicule","veinard","véloce","vendredi","vénérer","venger","venimeux","ventouse","verdure","vérin","vernir","verrou","verser","vertu","veston","vétéran","vétuste","vexant","vexer","viaduc","viande","victoire","vidange","vidéo","vignette","vigueur","vilain","village","vinaigre","violon","vipère","virement","virtuose","virus","visage","viseur","vision","visqueux","visuel","vital","vitesse","viticole","vitrine","vivace","vivipare","vocation","voguer","voile","voisin","voiture","volaille","volcan","voltiger","volume","vorace","vortex","voter","vouloir","voyage","voyelle","wagon","xénon","yacht","zèbre","zénith","zeste","zoologie"]// note all JSON files in this folder are generated with npm run generate-wordlist
const lookup = require('./lookup.json')

module.exports = {
  loadWordlist,
  detectLanguage
}

function loadWordlist (language) {
  switch (language) {
    case 'chinese_simplified': return require('./chinese_simplified.json')
    case 'chinese_traditional': return require('./chinese_traditional.json')
    case 'czech': return require('./czech.json')
    case 'english': return require('./english.json')
    case 'french': return require('./french.json')
    case 'italian': return require('./italian.json')
    case 'japanese': return require('./japanese.json')
    case 'korean': return require('./korean.json')
    case 'portuguese': return require('./portuguese.json')
    case 'russian': return require('./russian.json')
    case 'spanish': return require('./spanish.json')
    case 'turkish': return require('./turkish.json')
  }

  throw new Error('Unknown language: ' + language)
}

function detectLanguage (words) {
  let candidate = null

  for (const word of words) {
    const languages = lookup[word]
    if (!languages) return null

    if (languages.length === 1) return languages[0]

    if (!candidate) {
      candidate = languages
      continue
    }

    const intersect = candidate.filter(l => languages.includes(l))
    if (intersect.length === 1) return intersect[0]
  }

  return candidate[0]
}
["abaco","abbaglio","abbinato","abete","abisso","abolire","abrasivo","abrogato","accadere","accenno","accusato","acetone","achille","acido","acqua","acre","acrilico","acrobata","acuto","adagio","addebito","addome","adeguato","aderire","adipe","adottare","adulare","affabile","affetto","affisso","affranto","aforisma","afoso","africano","agave","agente","agevole","aggancio","agire","agitare","agonismo","agricolo","agrumeto","aguzzo","alabarda","alato","albatro","alberato","albo","albume","alce","alcolico","alettone","alfa","algebra","aliante","alibi","alimento","allagato","allegro","allievo","allodola","allusivo","almeno","alogeno","alpaca","alpestre","altalena","alterno","alticcio","altrove","alunno","alveolo","alzare","amalgama","amanita","amarena","ambito","ambrato","ameba","america","ametista","amico","ammasso","ammenda","ammirare","ammonito","amore","ampio","ampliare","amuleto","anacardo","anagrafe","analista","anarchia","anatra","anca","ancella","ancora","andare","andrea","anello","angelo","angolare","angusto","anima","annegare","annidato","anno","annuncio","anonimo","anticipo","anzi","apatico","apertura","apode","apparire","appetito","appoggio","approdo","appunto","aprile","arabica","arachide","aragosta","araldica","arancio","aratura","arazzo","arbitro","archivio","ardito","arenile","argento","argine","arguto","aria","armonia","arnese","arredato","arringa","arrosto","arsenico","arso","artefice","arzillo","asciutto","ascolto","asepsi","asettico","asfalto","asino","asola","aspirato","aspro","assaggio","asse","assoluto","assurdo","asta","astenuto","astice","astratto","atavico","ateismo","atomico","atono","attesa","attivare","attorno","attrito","attuale","ausilio","austria","autista","autonomo","autunno","avanzato","avere","avvenire","avviso","avvolgere","azione","azoto","azzimo","azzurro","babele","baccano","bacino","baco","badessa","badilata","bagnato","baita","balcone","baldo","balena","ballata","balzano","bambino","bandire","baraonda","barbaro","barca","baritono","barlume","barocco","basilico","basso","batosta","battuto","baule","bava","bavosa","becco","beffa","belgio","belva","benda","benevole","benigno","benzina","bere","berlina","beta","bibita","bici","bidone","bifido","biga","bilancia","bimbo","binocolo","biologo","bipede","bipolare","birbante","birra","biscotto","bisesto","bisnonno","bisonte","bisturi","bizzarro","blando","blatta","bollito","bonifico","bordo","bosco","botanico","bottino","bozzolo","braccio","bradipo","brama","branca","bravura","bretella","brevetto","brezza","briglia","brillante","brindare","broccolo","brodo","bronzina","brullo","bruno","bubbone","buca","budino","buffone","buio","bulbo","buono","burlone","burrasca","bussola","busta","cadetto","caduco","calamaro","calcolo","calesse","calibro","calmo","caloria","cambusa","camerata","camicia","cammino","camola","campale","canapa","candela","cane","canino","canotto","cantina","capace","capello","capitolo","capogiro","cappero","capra","capsula","carapace","carcassa","cardo","carisma","carovana","carretto","cartolina","casaccio","cascata","caserma","caso","cassone","castello","casuale","catasta","catena","catrame","cauto","cavillo","cedibile","cedrata","cefalo","celebre","cellulare","cena","cenone","centesimo","ceramica","cercare","certo","cerume","cervello","cesoia","cespo","ceto","chela","chiaro","chicca","chiedere","chimera","china","chirurgo","chitarra","ciao","ciclismo","cifrare","cigno","cilindro","ciottolo","circa","cirrosi","citrico","cittadino","ciuffo","civetta","civile","classico","clinica","cloro","cocco","codardo","codice","coerente","cognome","collare","colmato","colore","colposo","coltivato","colza","coma","cometa","commando","comodo","computer","comune","conciso","condurre","conferma","congelare","coniuge","connesso","conoscere","consumo","continuo","convegno","coperto","copione","coppia","copricapo","corazza","cordata","coricato","cornice","corolla","corpo","corredo","corsia","cortese","cosmico","costante","cottura","covato","cratere","cravatta","creato","credere","cremoso","crescita","creta","criceto","crinale","crisi","critico","croce","cronaca","crostata","cruciale","crusca","cucire","cuculo","cugino","cullato","cupola","curatore","cursore","curvo","cuscino","custode","dado","daino","dalmata","damerino","daniela","dannoso","danzare","datato","davanti","davvero","debutto","decennio","deciso","declino","decollo","decreto","dedicato","definito","deforme","degno","delegare","delfino","delirio","delta","demenza","denotato","dentro","deposito","derapata","derivare","deroga","descritto","deserto","desiderio","desumere","detersivo","devoto","diametro","dicembre","diedro","difeso","diffuso","digerire","digitale","diluvio","dinamico","dinnanzi","dipinto","diploma","dipolo","diradare","dire","dirotto","dirupo","disagio","discreto","disfare","disgelo","disposto","distanza","disumano","dito","divano","divelto","dividere","divorato","doblone","docente","doganale","dogma","dolce","domato","domenica","dominare","dondolo","dono","dormire","dote","dottore","dovuto","dozzina","drago","druido","dubbio","dubitare","ducale","duna","duomo","duplice","duraturo","ebano","eccesso","ecco","eclissi","economia","edera","edicola","edile","editoria","educare","egemonia","egli","egoismo","egregio","elaborato","elargire","elegante","elencato","eletto","elevare","elfico","elica","elmo","elsa","eluso","emanato","emblema","emesso","emiro","emotivo","emozione","empirico","emulo","endemico","enduro","energia","enfasi","enoteca","entrare","enzima","epatite","epilogo","episodio","epocale","eppure","equatore","erario","erba","erboso","erede","eremita","erigere","ermetico","eroe","erosivo","errante","esagono","esame","esanime","esaudire","esca","esempio","esercito","esibito","esigente","esistere","esito","esofago","esortato","esoso","espanso","espresso","essenza","esso","esteso","estimare","estonia","estroso","esultare","etilico","etnico","etrusco","etto","euclideo","europa","evaso","evidenza","evitato","evoluto","evviva","fabbrica","faccenda","fachiro","falco","famiglia","fanale","fanfara","fango","fantasma","fare","farfalla","farinoso","farmaco","fascia","fastoso","fasullo","faticare","fato","favoloso","febbre","fecola","fede","fegato","felpa","feltro","femmina","fendere","fenomeno","fermento","ferro","fertile","fessura","festivo","fetta","feudo","fiaba","fiducia","fifa","figurato","filo","finanza","finestra","finire","fiore","fiscale","fisico","fiume","flacone","flamenco","flebo","flemma","florido","fluente","fluoro","fobico","focaccia","focoso","foderato","foglio","folata","folclore","folgore","fondente","fonetico","fonia","fontana","forbito","forchetta","foresta","formica","fornaio","foro","fortezza","forzare","fosfato","fosso","fracasso","frana","frassino","fratello","freccetta","frenata","fresco","frigo","frollino","fronde","frugale","frutta","fucilata","fucsia","fuggente","fulmine","fulvo","fumante","fumetto","fumoso","fune","funzione","fuoco","furbo","furgone","furore","fuso","futile","gabbiano","gaffe","galateo","gallina","galoppo","gambero","gamma","garanzia","garbo","garofano","garzone","gasdotto","gasolio","gastrico","gatto","gaudio","gazebo","gazzella","geco","gelatina","gelso","gemello","gemmato","gene","genitore","gennaio","genotipo","gergo","ghepardo","ghiaccio","ghisa","giallo","gilda","ginepro","giocare","gioiello","giorno","giove","girato","girone","gittata","giudizio","giurato","giusto","globulo","glutine","gnomo","gobba","golf","gomito","gommone","gonfio","gonna","governo","gracile","grado","grafico","grammo","grande","grattare","gravoso","grazia","greca","gregge","grifone","grigio","grinza","grotta","gruppo","guadagno","guaio","guanto","guardare","gufo","guidare","ibernato","icona","identico","idillio","idolo","idra","idrico","idrogeno","igiene","ignaro","ignorato","ilare","illeso","illogico","illudere","imballo","imbevuto","imbocco","imbuto","immane","immerso","immolato","impacco","impeto","impiego","importo","impronta","inalare","inarcare","inattivo","incanto","incendio","inchino","incisivo","incluso","incontro","incrocio","incubo","indagine","india","indole","inedito","infatti","infilare","inflitto","ingaggio","ingegno","inglese","ingordo","ingrosso","innesco","inodore","inoltrare","inondato","insano","insetto","insieme","insonnia","insulina","intasato","intero","intonaco","intuito","inumidire","invalido","invece","invito","iperbole","ipnotico","ipotesi","ippica","iride","irlanda","ironico","irrigato","irrorare","isolato","isotopo","isterico","istituto","istrice","italia","iterare","labbro","labirinto","lacca","lacerato","lacrima","lacuna","laddove","lago","lampo","lancetta","lanterna","lardoso","larga","laringe","lastra","latenza","latino","lattuga","lavagna","lavoro","legale","leggero","lembo","lentezza","lenza","leone","lepre","lesivo","lessato","lesto","letterale","leva","levigato","libero","lido","lievito","lilla","limatura","limitare","limpido","lineare","lingua","liquido","lira","lirica","lisca","lite","litigio","livrea","locanda","lode","logica","lombare","londra","longevo","loquace","lorenzo","loto","lotteria","luce","lucidato","lumaca","luminoso","lungo","lupo","luppolo","lusinga","lusso","lutto","macabro","macchina","macero","macinato","madama","magico","maglia","magnete","magro","maiolica","malafede","malgrado","malinteso","malsano","malto","malumore","mana","mancia","mandorla","mangiare","manifesto","mannaro","manovra","mansarda","mantide","manubrio","mappa","maratona","marcire","maretta","marmo","marsupio","maschera","massaia","mastino","materasso","matricola","mattone","maturo","mazurca","meandro","meccanico","mecenate","medesimo","meditare","mega","melassa","melis","melodia","meninge","meno","mensola","mercurio","merenda","merlo","meschino","mese","messere","mestolo","metallo","metodo","mettere","miagolare","mica","micelio","michele","microbo","midollo","miele","migliore","milano","milite","mimosa","minerale","mini","minore","mirino","mirtillo","miscela","missiva","misto","misurare","mitezza","mitigare","mitra","mittente","mnemonico","modello","modifica","modulo","mogano","mogio","mole","molosso","monastero","monco","mondina","monetario","monile","monotono","monsone","montato","monviso","mora","mordere","morsicato","mostro","motivato","motosega","motto","movenza","movimento","mozzo","mucca","mucosa","muffa","mughetto","mugnaio","mulatto","mulinello","multiplo","mummia","munto","muovere","murale","musa","muscolo","musica","mutevole","muto","nababbo","nafta","nanometro","narciso","narice","narrato","nascere","nastrare","naturale","nautica","naviglio","nebulosa","necrosi","negativo","negozio","nemmeno","neofita","neretto","nervo","nessuno","nettuno","neutrale","neve","nevrotico","nicchia","ninfa","nitido","nobile","nocivo","nodo","nome","nomina","nordico","normale","norvegese","nostrano","notare","notizia","notturno","novella","nucleo","nulla","numero","nuovo","nutrire","nuvola","nuziale","oasi","obbedire","obbligo","obelisco","oblio","obolo","obsoleto","occasione","occhio","occidente","occorrere","occultare","ocra","oculato","odierno","odorare","offerta","offrire","offuscato","oggetto","oggi","ognuno","olandese","olfatto","oliato","oliva","ologramma","oltre","omaggio","ombelico","ombra","omega","omissione","ondoso","onere","onice","onnivoro","onorevole","onta","operato","opinione","opposto","oracolo","orafo","ordine","orecchino","orefice","orfano","organico","origine","orizzonte","orma","ormeggio","ornativo","orologio","orrendo","orribile","ortensia","ortica","orzata","orzo","osare","oscurare","osmosi","ospedale","ospite","ossa","ossidare","ostacolo","oste","otite","otre","ottagono","ottimo","ottobre","ovale","ovest","ovino","oviparo","ovocito","ovunque","ovviare","ozio","pacchetto","pace","pacifico","padella","padrone","paese","paga","pagina","palazzina","palesare","pallido","palo","palude","pandoro","pannello","paolo","paonazzo","paprica","parabola","parcella","parere","pargolo","pari","parlato","parola","partire","parvenza","parziale","passivo","pasticca","patacca","patologia","pattume","pavone","peccato","pedalare","pedonale","peggio","peloso","penare","pendice","penisola","pennuto","penombra","pensare","pentola","pepe","pepita","perbene","percorso","perdonato","perforare","pergamena","periodo","permesso","perno","perplesso","persuaso","pertugio","pervaso","pesatore","pesista","peso","pestifero","petalo","pettine","petulante","pezzo","piacere","pianta","piattino","piccino","picozza","piega","pietra","piffero","pigiama","pigolio","pigro","pila","pilifero","pillola","pilota","pimpante","pineta","pinna","pinolo","pioggia","piombo","piramide","piretico","pirite","pirolisi","pitone","pizzico","placebo","planare","plasma","platano","plenario","pochezza","poderoso","podismo","poesia","poggiare","polenta","poligono","pollice","polmonite","polpetta","polso","poltrona","polvere","pomice","pomodoro","ponte","popoloso","porfido","poroso","porpora","porre","portata","posa","positivo","possesso","postulato","potassio","potere","pranzo","prassi","pratica","precluso","predica","prefisso","pregiato","prelievo","premere","prenotare","preparato","presenza","pretesto","prevalso","prima","principe","privato","problema","procura","produrre","profumo","progetto","prolunga","promessa","pronome","proposta","proroga","proteso","prova","prudente","prugna","prurito","psiche","pubblico","pudica","pugilato","pugno","pulce","pulito","pulsante","puntare","pupazzo","pupilla","puro","quadro","qualcosa","quasi","querela","quota","raccolto","raddoppio","radicale","radunato","raffica","ragazzo","ragione","ragno","ramarro","ramingo","ramo","randagio","rantolare","rapato","rapina","rappreso","rasatura","raschiato","rasente","rassegna","rastrello","rata","ravveduto","reale","recepire","recinto","recluta","recondito","recupero","reddito","redimere","regalato","registro","regola","regresso","relazione","remare","remoto","renna","replica","reprimere","reputare","resa","residente","responso","restauro","rete","retina","retorica","rettifica","revocato","riassunto","ribadire","ribelle","ribrezzo","ricarica","ricco","ricevere","riciclato","ricordo","ricreduto","ridicolo","ridurre","rifasare","riflesso","riforma","rifugio","rigare","rigettato","righello","rilassato","rilevato","rimanere","rimbalzo","rimedio","rimorchio","rinascita","rincaro","rinforzo","rinnovo","rinomato","rinsavito","rintocco","rinuncia","rinvenire","riparato","ripetuto","ripieno","riportare","ripresa","ripulire","risata","rischio","riserva","risibile","riso","rispetto","ristoro","risultato","risvolto","ritardo","ritegno","ritmico","ritrovo","riunione","riva","riverso","rivincita","rivolto","rizoma","roba","robotico","robusto","roccia","roco","rodaggio","rodere","roditore","rogito","rollio","romantico","rompere","ronzio","rosolare","rospo","rotante","rotondo","rotula","rovescio","rubizzo","rubrica","ruga","rullino","rumine","rumoroso","ruolo","rupe","russare","rustico","sabato","sabbiare","sabotato","sagoma","salasso","saldatura","salgemma","salivare","salmone","salone","saltare","saluto","salvo","sapere","sapido","saporito","saraceno","sarcasmo","sarto","sassoso","satellite","satira","satollo","saturno","savana","savio","saziato","sbadiglio","sbalzo","sbancato","sbarra","sbattere","sbavare","sbendare","sbirciare","sbloccato","sbocciato","sbrinare","sbruffone","sbuffare","scabroso","scadenza","scala","scambiare","scandalo","scapola","scarso","scatenare","scavato","scelto","scenico","scettro","scheda","schiena","sciarpa","scienza","scindere","scippo","sciroppo","scivolo","sclerare","scodella","scolpito","scomparto","sconforto","scoprire","scorta","scossone","scozzese","scriba","scrollare","scrutinio","scuderia","scultore","scuola","scuro","scusare","sdebitare","sdoganare","seccatura","secondo","sedano","seggiola","segnalato","segregato","seguito","selciato","selettivo","sella","selvaggio","semaforo","sembrare","seme","seminato","sempre","senso","sentire","sepolto","sequenza","serata","serbato","sereno","serio","serpente","serraglio","servire","sestina","setola","settimana","sfacelo","sfaldare","sfamato","sfarzoso","sfaticato","sfera","sfida","sfilato","sfinge","sfocato","sfoderare","sfogo","sfoltire","sforzato","sfratto","sfruttato","sfuggito","sfumare","sfuso","sgabello","sgarbato","sgonfiare","sgorbio","sgrassato","sguardo","sibilo","siccome","sierra","sigla","signore","silenzio","sillaba","simbolo","simpatico","simulato","sinfonia","singolo","sinistro","sino","sintesi","sinusoide","sipario","sisma","sistole","situato","slitta","slogatura","sloveno","smarrito","smemorato","smentito","smeraldo","smilzo","smontare","smottato","smussato","snellire","snervato","snodo","sobbalzo","sobrio","soccorso","sociale","sodale","soffitto","sogno","soldato","solenne","solido","sollazzo","solo","solubile","solvente","somatico","somma","sonda","sonetto","sonnifero","sopire","soppeso","sopra","sorgere","sorpasso","sorriso","sorso","sorteggio","sorvolato","sospiro","sosta","sottile","spada","spalla","spargere","spatola","spavento","spazzola","specie","spedire","spegnere","spelatura","speranza","spessore","spettrale","spezzato","spia","spigoloso","spillato","spinoso","spirale","splendido","sportivo","sposo","spranga","sprecare","spronato","spruzzo","spuntino","squillo","sradicare","srotolato","stabile","stacco","staffa","stagnare","stampato","stantio","starnuto","stasera","statuto","stelo","steppa","sterzo","stiletto","stima","stirpe","stivale","stizzoso","stonato","storico","strappo","stregato","stridulo","strozzare","strutto","stuccare","stufo","stupendo","subentro","succoso","sudore","suggerito","sugo","sultano","suonare","superbo","supporto","surgelato","surrogato","sussurro","sutura","svagare","svedese","sveglio","svelare","svenuto","svezia","sviluppo","svista","svizzera","svolta","svuotare","tabacco","tabulato","tacciare","taciturno","tale","talismano","tampone","tannino","tara","tardivo","targato","tariffa","tarpare","tartaruga","tasto","tattico","taverna","tavolata","tazza","teca","tecnico","telefono","temerario","tempo","temuto","tendone","tenero","tensione","tentacolo","teorema","terme","terrazzo","terzetto","tesi","tesserato","testato","tetro","tettoia","tifare","tigella","timbro","tinto","tipico","tipografo","tiraggio","tiro","titanio","titolo","titubante","tizio","tizzone","toccare","tollerare","tolto","tombola","tomo","tonfo","tonsilla","topazio","topologia","toppa","torba","tornare","torrone","tortora","toscano","tossire","tostatura","totano","trabocco","trachea","trafila","tragedia","tralcio","tramonto","transito","trapano","trarre","trasloco","trattato","trave","treccia","tremolio","trespolo","tributo","tricheco","trifoglio","trillo","trincea","trio","tristezza","triturato","trivella","tromba","trono","troppo","trottola","trovare","truccato","tubatura","tuffato","tulipano","tumulto","tunisia","turbare","turchino","tuta","tutela","ubicato","uccello","uccisore","udire","uditivo","uffa","ufficio","uguale","ulisse","ultimato","umano","umile","umorismo","uncinetto","ungere","ungherese","unicorno","unificato","unisono","unitario","unte","uovo","upupa","uragano","urgenza","urlo","usanza","usato","uscito","usignolo","usuraio","utensile","utilizzo","utopia","vacante","vaccinato","vagabondo","vagliato","valanga","valgo","valico","valletta","valoroso","valutare","valvola","vampata","vangare","vanitoso","vano","vantaggio","vanvera","vapore","varano","varcato","variante","vasca","vedetta","vedova","veduto","vegetale","veicolo","velcro","velina","velluto","veloce","venato","vendemmia","vento","verace","verbale","vergogna","verifica","vero","verruca","verticale","vescica","vessillo","vestale","veterano","vetrina","vetusto","viandante","vibrante","vicenda","vichingo","vicinanza","vidimare","vigilia","vigneto","vigore","vile","villano","vimini","vincitore","viola","vipera","virgola","virologo","virulento","viscoso","visione","vispo","vissuto","visura","vita","vitello","vittima","vivanda","vivido","viziare","voce","voga","volatile","volere","volpe","voragine","vulcano","zampogna","zanna","zappato","zattera","zavorra","zefiro","zelante","zelo","zenzero","zerbino","zibetto","zinco","zircone","zitto","zolla","zotico","zucchero","zufolo","zulu","zuppa"]["あいこくしん","あいさつ","あいだ","あおぞら","あかちゃん","あきる","あけがた","あける","あこがれる","あさい","あさひ","あしあと","あじわう","あずかる","あずき","あそぶ","あたえる","あたためる","あたりまえ","あたる","あつい","あつかう","あっしゅく","あつまり","あつめる","あてな","あてはまる","あひる","あぶら","あぶる","あふれる","あまい","あまど","あまやかす","あまり","あみもの","あめりか","あやまる","あゆむ","あらいぐま","あらし","あらすじ","あらためる","あらゆる","あらわす","ありがとう","あわせる","あわてる","あんい","あんがい","あんこ","あんぜん","あんてい","あんない","あんまり","いいだす","いおん","いがい","いがく","いきおい","いきなり","いきもの","いきる","いくじ","いくぶん","いけばな","いけん","いこう","いこく","いこつ","いさましい","いさん","いしき","いじゅう","いじょう","いじわる","いずみ","いずれ","いせい","いせえび","いせかい","いせき","いぜん","いそうろう","いそがしい","いだい","いだく","いたずら","いたみ","いたりあ","いちおう","いちじ","いちど","いちば","いちぶ","いちりゅう","いつか","いっしゅん","いっせい","いっそう","いったん","いっち","いってい","いっぽう","いてざ","いてん","いどう","いとこ","いない","いなか","いねむり","いのち","いのる","いはつ","いばる","いはん","いびき","いひん","いふく","いへん","いほう","いみん","いもうと","いもたれ","いもり","いやがる","いやす","いよかん","いよく","いらい","いらすと","いりぐち","いりょう","いれい","いれもの","いれる","いろえんぴつ","いわい","いわう","いわかん","いわば","いわゆる","いんげんまめ","いんさつ","いんしょう","いんよう","うえき","うえる","うおざ","うがい","うかぶ","うかべる","うきわ","うくらいな","うくれれ","うけたまわる","うけつけ","うけとる","うけもつ","うける","うごかす","うごく","うこん","うさぎ","うしなう","うしろがみ","うすい","うすぎ","うすぐらい","うすめる","うせつ","うちあわせ","うちがわ","うちき","うちゅう","うっかり","うつくしい","うったえる","うつる","うどん","うなぎ","うなじ","うなずく","うなる","うねる","うのう","うぶげ","うぶごえ","うまれる","うめる","うもう","うやまう","うよく","うらがえす","うらぐち","うらない","うりあげ","うりきれ","うるさい","うれしい","うれゆき","うれる","うろこ","うわき","うわさ","うんこう","うんちん","うんてん","うんどう","えいえん","えいが","えいきょう","えいご","えいせい","えいぶん","えいよう","えいわ","えおり","えがお","えがく","えきたい","えくせる","えしゃく","えすて","えつらん","えのぐ","えほうまき","えほん","えまき","えもじ","えもの","えらい","えらぶ","えりあ","えんえん","えんかい","えんぎ","えんげき","えんしゅう","えんぜつ","えんそく","えんちょう","えんとつ","おいかける","おいこす","おいしい","おいつく","おうえん","おうさま","おうじ","おうせつ","おうたい","おうふく","おうべい","おうよう","おえる","おおい","おおう","おおどおり","おおや","おおよそ","おかえり","おかず","おがむ","おかわり","おぎなう","おきる","おくさま","おくじょう","おくりがな","おくる","おくれる","おこす","おこなう","おこる","おさえる","おさない","おさめる","おしいれ","おしえる","おじぎ","おじさん","おしゃれ","おそらく","おそわる","おたがい","おたく","おだやか","おちつく","おっと","おつり","おでかけ","おとしもの","おとなしい","おどり","おどろかす","おばさん","おまいり","おめでとう","おもいで","おもう","おもたい","おもちゃ","おやつ","おやゆび","およぼす","おらんだ","おろす","おんがく","おんけい","おんしゃ","おんせん","おんだん","おんちゅう","おんどけい","かあつ","かいが","がいき","がいけん","がいこう","かいさつ","かいしゃ","かいすいよく","かいぜん","かいぞうど","かいつう","かいてん","かいとう","かいふく","がいへき","かいほう","かいよう","がいらい","かいわ","かえる","かおり","かかえる","かがく","かがし","かがみ","かくご","かくとく","かざる","がぞう","かたい","かたち","がちょう","がっきゅう","がっこう","がっさん","がっしょう","かなざわし","かのう","がはく","かぶか","かほう","かほご","かまう","かまぼこ","かめれおん","かゆい","かようび","からい","かるい","かろう","かわく","かわら","がんか","かんけい","かんこう","かんしゃ","かんそう","かんたん","かんち","がんばる","きあい","きあつ","きいろ","ぎいん","きうい","きうん","きえる","きおう","きおく","きおち","きおん","きかい","きかく","きかんしゃ","ききて","きくばり","きくらげ","きけんせい","きこう","きこえる","きこく","きさい","きさく","きさま","きさらぎ","ぎじかがく","ぎしき","ぎじたいけん","ぎじにってい","ぎじゅつしゃ","きすう","きせい","きせき","きせつ","きそう","きぞく","きぞん","きたえる","きちょう","きつえん","ぎっちり","きつつき","きつね","きてい","きどう","きどく","きない","きなが","きなこ","きぬごし","きねん","きのう","きのした","きはく","きびしい","きひん","きふく","きぶん","きぼう","きほん","きまる","きみつ","きむずかしい","きめる","きもだめし","きもち","きもの","きゃく","きやく","ぎゅうにく","きよう","きょうりゅう","きらい","きらく","きりん","きれい","きれつ","きろく","ぎろん","きわめる","ぎんいろ","きんかくじ","きんじょ","きんようび","ぐあい","くいず","くうかん","くうき","くうぐん","くうこう","ぐうせい","くうそう","ぐうたら","くうふく","くうぼ","くかん","くきょう","くげん","ぐこう","くさい","くさき","くさばな","くさる","くしゃみ","くしょう","くすのき","くすりゆび","くせげ","くせん","ぐたいてき","くださる","くたびれる","くちこみ","くちさき","くつした","ぐっすり","くつろぐ","くとうてん","くどく","くなん","くねくね","くのう","くふう","くみあわせ","くみたてる","くめる","くやくしょ","くらす","くらべる","くるま","くれる","くろう","くわしい","ぐんかん","ぐんしょく","ぐんたい","ぐんて","けあな","けいかく","けいけん","けいこ","けいさつ","げいじゅつ","けいたい","げいのうじん","けいれき","けいろ","けおとす","けおりもの","げきか","げきげん","げきだん","げきちん","げきとつ","げきは","げきやく","げこう","げこくじょう","げざい","けさき","げざん","けしき","けしごむ","けしょう","げすと","けたば","けちゃっぷ","けちらす","けつあつ","けつい","けつえき","けっこん","けつじょ","けっせき","けってい","けつまつ","げつようび","げつれい","けつろん","げどく","けとばす","けとる","けなげ","けなす","けなみ","けぬき","げねつ","けねん","けはい","げひん","けぶかい","げぼく","けまり","けみかる","けむし","けむり","けもの","けらい","けろけろ","けわしい","けんい","けんえつ","けんお","けんか","げんき","けんげん","けんこう","けんさく","けんしゅう","けんすう","げんそう","けんちく","けんてい","けんとう","けんない","けんにん","げんぶつ","けんま","けんみん","けんめい","けんらん","けんり","こあくま","こいぬ","こいびと","ごうい","こうえん","こうおん","こうかん","ごうきゅう","ごうけい","こうこう","こうさい","こうじ","こうすい","ごうせい","こうそく","こうたい","こうちゃ","こうつう","こうてい","こうどう","こうない","こうはい","ごうほう","ごうまん","こうもく","こうりつ","こえる","こおり","ごかい","ごがつ","ごかん","こくご","こくさい","こくとう","こくない","こくはく","こぐま","こけい","こける","ここのか","こころ","こさめ","こしつ","こすう","こせい","こせき","こぜん","こそだて","こたい","こたえる","こたつ","こちょう","こっか","こつこつ","こつばん","こつぶ","こてい","こてん","ことがら","ことし","ことば","ことり","こなごな","こねこね","このまま","このみ","このよ","ごはん","こひつじ","こふう","こふん","こぼれる","ごまあぶら","こまかい","ごますり","こまつな","こまる","こむぎこ","こもじ","こもち","こもの","こもん","こやく","こやま","こゆう","こゆび","こよい","こよう","こりる","これくしょん","ころっけ","こわもて","こわれる","こんいん","こんかい","こんき","こんしゅう","こんすい","こんだて","こんとん","こんなん","こんびに","こんぽん","こんまけ","こんや","こんれい","こんわく","ざいえき","さいかい","さいきん","ざいげん","ざいこ","さいしょ","さいせい","ざいたく","ざいちゅう","さいてき","ざいりょう","さうな","さかいし","さがす","さかな","さかみち","さがる","さぎょう","さくし","さくひん","さくら","さこく","さこつ","さずかる","ざせき","さたん","さつえい","ざつおん","ざっか","ざつがく","さっきょく","ざっし","さつじん","ざっそう","さつたば","さつまいも","さてい","さといも","さとう","さとおや","さとし","さとる","さのう","さばく","さびしい","さべつ","さほう","さほど","さます","さみしい","さみだれ","さむけ","さめる","さやえんどう","さゆう","さよう","さよく","さらだ","ざるそば","さわやか","さわる","さんいん","さんか","さんきゃく","さんこう","さんさい","ざんしょ","さんすう","さんせい","さんそ","さんち","さんま","さんみ","さんらん","しあい","しあげ","しあさって","しあわせ","しいく","しいん","しうち","しえい","しおけ","しかい","しかく","じかん","しごと","しすう","じだい","したうけ","したぎ","したて","したみ","しちょう","しちりん","しっかり","しつじ","しつもん","してい","してき","してつ","じてん","じどう","しなぎれ","しなもの","しなん","しねま","しねん","しのぐ","しのぶ","しはい","しばかり","しはつ","しはらい","しはん","しひょう","しふく","じぶん","しへい","しほう","しほん","しまう","しまる","しみん","しむける","じむしょ","しめい","しめる","しもん","しゃいん","しゃうん","しゃおん","じゃがいも","しやくしょ","しゃくほう","しゃけん","しゃこ","しゃざい","しゃしん","しゃせん","しゃそう","しゃたい","しゃちょう","しゃっきん","じゃま","しゃりん","しゃれい","じゆう","じゅうしょ","しゅくはく","じゅしん","しゅっせき","しゅみ","しゅらば","じゅんばん","しょうかい","しょくたく","しょっけん","しょどう","しょもつ","しらせる","しらべる","しんか","しんこう","じんじゃ","しんせいじ","しんちく","しんりん","すあげ","すあし","すあな","ずあん","すいえい","すいか","すいとう","ずいぶん","すいようび","すうがく","すうじつ","すうせん","すおどり","すきま","すくう","すくない","すける","すごい","すこし","ずさん","すずしい","すすむ","すすめる","すっかり","ずっしり","ずっと","すてき","すてる","すねる","すのこ","すはだ","すばらしい","ずひょう","ずぶぬれ","すぶり","すふれ","すべて","すべる","ずほう","すぼん","すまい","すめし","すもう","すやき","すらすら","するめ","すれちがう","すろっと","すわる","すんぜん","すんぽう","せあぶら","せいかつ","せいげん","せいじ","せいよう","せおう","せかいかん","せきにん","せきむ","せきゆ","せきらんうん","せけん","せこう","せすじ","せたい","せたけ","せっかく","せっきゃく","ぜっく","せっけん","せっこつ","せっさたくま","せつぞく","せつだん","せつでん","せっぱん","せつび","せつぶん","せつめい","せつりつ","せなか","せのび","せはば","せびろ","せぼね","せまい","せまる","せめる","せもたれ","せりふ","ぜんあく","せんい","せんえい","せんか","せんきょ","せんく","せんげん","ぜんご","せんさい","せんしゅ","せんすい","せんせい","せんぞ","せんたく","せんちょう","せんてい","せんとう","せんぬき","せんねん","せんぱい","ぜんぶ","ぜんぽう","せんむ","せんめんじょ","せんもん","せんやく","せんゆう","せんよう","ぜんら","ぜんりゃく","せんれい","せんろ","そあく","そいとげる","そいね","そうがんきょう","そうき","そうご","そうしん","そうだん","そうなん","そうび","そうめん","そうり","そえもの","そえん","そがい","そげき","そこう","そこそこ","そざい","そしな","そせい","そせん","そそぐ","そだてる","そつう","そつえん","そっかん","そつぎょう","そっけつ","そっこう","そっせん","そっと","そとがわ","そとづら","そなえる","そなた","そふぼ","そぼく","そぼろ","そまつ","そまる","そむく","そむりえ","そめる","そもそも","そよかぜ","そらまめ","そろう","そんかい","そんけい","そんざい","そんしつ","そんぞく","そんちょう","ぞんび","ぞんぶん","そんみん","たあい","たいいん","たいうん","たいえき","たいおう","だいがく","たいき","たいぐう","たいけん","たいこ","たいざい","だいじょうぶ","だいすき","たいせつ","たいそう","だいたい","たいちょう","たいてい","だいどころ","たいない","たいねつ","たいのう","たいはん","だいひょう","たいふう","たいへん","たいほ","たいまつばな","たいみんぐ","たいむ","たいめん","たいやき","たいよう","たいら","たいりょく","たいる","たいわん","たうえ","たえる","たおす","たおる","たおれる","たかい","たかね","たきび","たくさん","たこく","たこやき","たさい","たしざん","だじゃれ","たすける","たずさわる","たそがれ","たたかう","たたく","ただしい","たたみ","たちばな","だっかい","だっきゃく","だっこ","だっしゅつ","だったい","たてる","たとえる","たなばた","たにん","たぬき","たのしみ","たはつ","たぶん","たべる","たぼう","たまご","たまる","だむる","ためいき","ためす","ためる","たもつ","たやすい","たよる","たらす","たりきほんがん","たりょう","たりる","たると","たれる","たれんと","たろっと","たわむれる","だんあつ","たんい","たんおん","たんか","たんき","たんけん","たんご","たんさん","たんじょうび","だんせい","たんそく","たんたい","だんち","たんてい","たんとう","だんな","たんにん","だんねつ","たんのう","たんぴん","だんぼう","たんまつ","たんめい","だんれつ","だんろ","だんわ","ちあい","ちあん","ちいき","ちいさい","ちえん","ちかい","ちから","ちきゅう","ちきん","ちけいず","ちけん","ちこく","ちさい","ちしき","ちしりょう","ちせい","ちそう","ちたい","ちたん","ちちおや","ちつじょ","ちてき","ちてん","ちぬき","ちぬり","ちのう","ちひょう","ちへいせん","ちほう","ちまた","ちみつ","ちみどろ","ちめいど","ちゃんこなべ","ちゅうい","ちゆりょく","ちょうし","ちょさくけん","ちらし","ちらみ","ちりがみ","ちりょう","ちるど","ちわわ","ちんたい","ちんもく","ついか","ついたち","つうか","つうじょう","つうはん","つうわ","つかう","つかれる","つくね","つくる","つけね","つける","つごう","つたえる","つづく","つつじ","つつむ","つとめる","つながる","つなみ","つねづね","つのる","つぶす","つまらない","つまる","つみき","つめたい","つもり","つもる","つよい","つるぼ","つるみく","つわもの","つわり","てあし","てあて","てあみ","ていおん","ていか","ていき","ていけい","ていこく","ていさつ","ていし","ていせい","ていたい","ていど","ていねい","ていひょう","ていへん","ていぼう","てうち","ておくれ","てきとう","てくび","でこぼこ","てさぎょう","てさげ","てすり","てそう","てちがい","てちょう","てつがく","てつづき","でっぱ","てつぼう","てつや","でぬかえ","てぬき","てぬぐい","てのひら","てはい","てぶくろ","てふだ","てほどき","てほん","てまえ","てまきずし","てみじか","てみやげ","てらす","てれび","てわけ","てわたし","でんあつ","てんいん","てんかい","てんき","てんぐ","てんけん","てんごく","てんさい","てんし","てんすう","でんち","てんてき","てんとう","てんない","てんぷら","てんぼうだい","てんめつ","てんらんかい","でんりょく","でんわ","どあい","といれ","どうかん","とうきゅう","どうぐ","とうし","とうむぎ","とおい","とおか","とおく","とおす","とおる","とかい","とかす","ときおり","ときどき","とくい","とくしゅう","とくてん","とくに","とくべつ","とけい","とける","とこや","とさか","としょかん","とそう","とたん","とちゅう","とっきゅう","とっくん","とつぜん","とつにゅう","とどける","ととのえる","とない","となえる","となり","とのさま","とばす","どぶがわ","とほう","とまる","とめる","ともだち","ともる","どようび","とらえる","とんかつ","どんぶり","ないかく","ないこう","ないしょ","ないす","ないせん","ないそう","なおす","ながい","なくす","なげる","なこうど","なさけ","なたでここ","なっとう","なつやすみ","ななおし","なにごと","なにもの","なにわ","なのか","なふだ","なまいき","なまえ","なまみ","なみだ","なめらか","なめる","なやむ","ならう","ならび","ならぶ","なれる","なわとび","なわばり","にあう","にいがた","にうけ","におい","にかい","にがて","にきび","にくしみ","にくまん","にげる","にさんかたんそ","にしき","にせもの","にちじょう","にちようび","にっか","にっき","にっけい","にっこう","にっさん","にっしょく","にっすう","にっせき","にってい","になう","にほん","にまめ","にもつ","にやり","にゅういん","にりんしゃ","にわとり","にんい","にんか","にんき","にんげん","にんしき","にんずう","にんそう","にんたい","にんち","にんてい","にんにく","にんぷ","にんまり","にんむ","にんめい","にんよう","ぬいくぎ","ぬかす","ぬぐいとる","ぬぐう","ぬくもり","ぬすむ","ぬまえび","ぬめり","ぬらす","ぬんちゃく","ねあげ","ねいき","ねいる","ねいろ","ねぐせ","ねくたい","ねくら","ねこぜ","ねこむ","ねさげ","ねすごす","ねそべる","ねだん","ねつい","ねっしん","ねつぞう","ねったいぎょ","ねぶそく","ねふだ","ねぼう","ねほりはほり","ねまき","ねまわし","ねみみ","ねむい","ねむたい","ねもと","ねらう","ねわざ","ねんいり","ねんおし","ねんかん","ねんきん","ねんぐ","ねんざ","ねんし","ねんちゃく","ねんど","ねんぴ","ねんぶつ","ねんまつ","ねんりょう","ねんれい","のいず","のおづま","のがす","のきなみ","のこぎり","のこす","のこる","のせる","のぞく","のぞむ","のたまう","のちほど","のっく","のばす","のはら","のべる","のぼる","のみもの","のやま","のらいぬ","のらねこ","のりもの","のりゆき","のれん","のんき","ばあい","はあく","ばあさん","ばいか","ばいく","はいけん","はいご","はいしん","はいすい","はいせん","はいそう","はいち","ばいばい","はいれつ","はえる","はおる","はかい","ばかり","はかる","はくしゅ","はけん","はこぶ","はさみ","はさん","はしご","ばしょ","はしる","はせる","ぱそこん","はそん","はたん","はちみつ","はつおん","はっかく","はづき","はっきり","はっくつ","はっけん","はっこう","はっさん","はっしん","はったつ","はっちゅう","はってん","はっぴょう","はっぽう","はなす","はなび","はにかむ","はぶらし","はみがき","はむかう","はめつ","はやい","はやし","はらう","はろうぃん","はわい","はんい","はんえい","はんおん","はんかく","はんきょう","ばんぐみ","はんこ","はんしゃ","はんすう","はんだん","ぱんち","ぱんつ","はんてい","はんとし","はんのう","はんぱ","はんぶん","はんぺん","はんぼうき","はんめい","はんらん","はんろん","ひいき","ひうん","ひえる","ひかく","ひかり","ひかる","ひかん","ひくい","ひけつ","ひこうき","ひこく","ひさい","ひさしぶり","ひさん","びじゅつかん","ひしょ","ひそか","ひそむ","ひたむき","ひだり","ひたる","ひつぎ","ひっこし","ひっし","ひつじゅひん","ひっす","ひつぜん","ぴったり","ぴっちり","ひつよう","ひてい","ひとごみ","ひなまつり","ひなん","ひねる","ひはん","ひびく","ひひょう","ひほう","ひまわり","ひまん","ひみつ","ひめい","ひめじし","ひやけ","ひやす","ひよう","びょうき","ひらがな","ひらく","ひりつ","ひりょう","ひるま","ひるやすみ","ひれい","ひろい","ひろう","ひろき","ひろゆき","ひんかく","ひんけつ","ひんこん","ひんしゅ","ひんそう","ぴんち","ひんぱん","びんぼう","ふあん","ふいうち","ふうけい","ふうせん","ぷうたろう","ふうとう","ふうふ","ふえる","ふおん","ふかい","ふきん","ふくざつ","ふくぶくろ","ふこう","ふさい","ふしぎ","ふじみ","ふすま","ふせい","ふせぐ","ふそく","ぶたにく","ふたん","ふちょう","ふつう","ふつか","ふっかつ","ふっき","ふっこく","ぶどう","ふとる","ふとん","ふのう","ふはい","ふひょう","ふへん","ふまん","ふみん","ふめつ","ふめん","ふよう","ふりこ","ふりる","ふるい","ふんいき","ぶんがく","ぶんぐ","ふんしつ","ぶんせき","ふんそう","ぶんぽう","へいあん","へいおん","へいがい","へいき","へいげん","へいこう","へいさ","へいしゃ","へいせつ","へいそ","へいたく","へいてん","へいねつ","へいわ","へきが","へこむ","べにいろ","べにしょうが","へらす","へんかん","べんきょう","べんごし","へんさい","へんたい","べんり","ほあん","ほいく","ぼうぎょ","ほうこく","ほうそう","ほうほう","ほうもん","ほうりつ","ほえる","ほおん","ほかん","ほきょう","ぼきん","ほくろ","ほけつ","ほけん","ほこう","ほこる","ほしい","ほしつ","ほしゅ","ほしょう","ほせい","ほそい","ほそく","ほたて","ほたる","ぽちぶくろ","ほっきょく","ほっさ","ほったん","ほとんど","ほめる","ほんい","ほんき","ほんけ","ほんしつ","ほんやく","まいにち","まかい","まかせる","まがる","まける","まこと","まさつ","まじめ","ますく","まぜる","まつり","まとめ","まなぶ","まぬけ","まねく","まほう","まもる","まゆげ","まよう","まろやか","まわす","まわり","まわる","まんが","まんきつ","まんぞく","まんなか","みいら","みうち","みえる","みがく","みかた","みかん","みけん","みこん","みじかい","みすい","みすえる","みせる","みっか","みつかる","みつける","みてい","みとめる","みなと","みなみかさい","みねらる","みのう","みのがす","みほん","みもと","みやげ","みらい","みりょく","みわく","みんか","みんぞく","むいか","むえき","むえん","むかい","むかう","むかえ","むかし","むぎちゃ","むける","むげん","むさぼる","むしあつい","むしば","むじゅん","むしろ","むすう","むすこ","むすぶ","むすめ","むせる","むせん","むちゅう","むなしい","むのう","むやみ","むよう","むらさき","むりょう","むろん","めいあん","めいうん","めいえん","めいかく","めいきょく","めいさい","めいし","めいそう","めいぶつ","めいれい","めいわく","めぐまれる","めざす","めした","めずらしい","めだつ","めまい","めやす","めんきょ","めんせき","めんどう","もうしあげる","もうどうけん","もえる","もくし","もくてき","もくようび","もちろん","もどる","もらう","もんく","もんだい","やおや","やける","やさい","やさしい","やすい","やすたろう","やすみ","やせる","やそう","やたい","やちん","やっと","やっぱり","やぶる","やめる","ややこしい","やよい","やわらかい","ゆうき","ゆうびんきょく","ゆうべ","ゆうめい","ゆけつ","ゆしゅつ","ゆせん","ゆそう","ゆたか","ゆちゃく","ゆでる","ゆにゅう","ゆびわ","ゆらい","ゆれる","ようい","ようか","ようきゅう","ようじ","ようす","ようちえん","よかぜ","よかん","よきん","よくせい","よくぼう","よけい","よごれる","よさん","よしゅう","よそう","よそく","よっか","よてい","よどがわく","よねつ","よやく","よゆう","よろこぶ","よろしい","らいう","らくがき","らくご","らくさつ","らくだ","らしんばん","らせん","らぞく","らたい","らっか","られつ","りえき","りかい","りきさく","りきせつ","りくぐん","りくつ","りけん","りこう","りせい","りそう","りそく","りてん","りねん","りゆう","りゅうがく","りよう","りょうり","りょかん","りょくちゃ","りょこう","りりく","りれき","りろん","りんご","るいけい","るいさい","るいじ","るいせき","るすばん","るりがわら","れいかん","れいぎ","れいせい","れいぞうこ","れいとう","れいぼう","れきし","れきだい","れんあい","れんけい","れんこん","れんさい","れんしゅう","れんぞく","れんらく","ろうか","ろうご","ろうじん","ろうそく","ろくが","ろこつ","ろじうら","ろしゅつ","ろせん","ろてん","ろめん","ろれつ","ろんぎ","ろんぱ","ろんぶん","ろんり","わかす","わかめ","わかやま","わかれる","わしつ","わじまし","わすれもの","わらう","われる"]["가격","가끔","가난","가능","가득","가르침","가뭄","가방","가상","가슴","가운데","가을","가이드","가입","가장","가정","가족","가죽","각오","각자","간격","간부","간섭","간장","간접","간판","갈등","갈비","갈색","갈증","감각","감기","감소","감수성","감자","감정","갑자기","강남","강당","강도","강력히","강변","강북","강사","강수량","강아지","강원도","강의","강제","강조","같이","개구리","개나리","개방","개별","개선","개성","개인","객관적","거실","거액","거울","거짓","거품","걱정","건강","건물","건설","건조","건축","걸음","검사","검토","게시판","게임","겨울","견해","결과","결국","결론","결석","결승","결심","결정","결혼","경계","경고","경기","경력","경복궁","경비","경상도","경영","경우","경쟁","경제","경주","경찰","경치","경향","경험","계곡","계단","계란","계산","계속","계약","계절","계층","계획","고객","고구려","고궁","고급","고등학생","고무신","고민","고양이","고장","고전","고집","고춧가루","고통","고향","곡식","골목","골짜기","골프","공간","공개","공격","공군","공급","공기","공동","공무원","공부","공사","공식","공업","공연","공원","공장","공짜","공책","공통","공포","공항","공휴일","과목","과일","과장","과정","과학","관객","관계","관광","관념","관람","관련","관리","관습","관심","관점","관찰","광경","광고","광장","광주","괴로움","굉장히","교과서","교문","교복","교실","교양","교육","교장","교직","교통","교환","교훈","구경","구름","구멍","구별","구분","구석","구성","구속","구역","구입","구청","구체적","국가","국기","국내","국립","국물","국민","국수","국어","국왕","국적","국제","국회","군대","군사","군인","궁극적","권리","권위","권투","귀국","귀신","규정","규칙","균형","그날","그냥","그늘","그러나","그룹","그릇","그림","그제서야","그토록","극복","극히","근거","근교","근래","근로","근무","근본","근원","근육","근처","글씨","글자","금강산","금고","금년","금메달","금액","금연","금요일","금지","긍정적","기간","기관","기념","기능","기독교","기둥","기록","기름","기법","기본","기분","기쁨","기숙사","기술","기억","기업","기온","기운","기원","기적","기준","기침","기혼","기획","긴급","긴장","길이","김밥","김치","김포공항","깍두기","깜빡","깨달음","깨소금","껍질","꼭대기","꽃잎","나들이","나란히","나머지","나물","나침반","나흘","낙엽","난방","날개","날씨","날짜","남녀","남대문","남매","남산","남자","남편","남학생","낭비","낱말","내년","내용","내일","냄비","냄새","냇물","냉동","냉면","냉방","냉장고","넥타이","넷째","노동","노란색","노력","노인","녹음","녹차","녹화","논리","논문","논쟁","놀이","농구","농담","농민","농부","농업","농장","농촌","높이","눈동자","눈물","눈썹","뉴욕","느낌","늑대","능동적","능력","다방","다양성","다음","다이어트","다행","단계","단골","단독","단맛","단순","단어","단위","단점","단체","단추","단편","단풍","달걀","달러","달력","달리","닭고기","담당","담배","담요","담임","답변","답장","당근","당분간","당연히","당장","대규모","대낮","대단히","대답","대도시","대략","대량","대륙","대문","대부분","대신","대응","대장","대전","대접","대중","대책","대출","대충","대통령","대학","대한민국","대합실","대형","덩어리","데이트","도대체","도덕","도둑","도망","도서관","도심","도움","도입","도자기","도저히","도전","도중","도착","독감","독립","독서","독일","독창적","동화책","뒷모습","뒷산","딸아이","마누라","마늘","마당","마라톤","마련","마무리","마사지","마약","마요네즈","마을","마음","마이크","마중","마지막","마찬가지","마찰","마흔","막걸리","막내","막상","만남","만두","만세","만약","만일","만점","만족","만화","많이","말기","말씀","말투","맘대로","망원경","매년","매달","매력","매번","매스컴","매일","매장","맥주","먹이","먼저","먼지","멀리","메일","며느리","며칠","면담","멸치","명단","명령","명예","명의","명절","명칭","명함","모금","모니터","모델","모든","모범","모습","모양","모임","모조리","모집","모퉁이","목걸이","목록","목사","목소리","목숨","목적","목표","몰래","몸매","몸무게","몸살","몸속","몸짓","몸통","몹시","무관심","무궁화","무더위","무덤","무릎","무슨","무엇","무역","무용","무조건","무지개","무척","문구","문득","문법","문서","문제","문학","문화","물가","물건","물결","물고기","물론","물리학","물음","물질","물체","미국","미디어","미사일","미술","미역","미용실","미움","미인","미팅","미혼","민간","민족","민주","믿음","밀가루","밀리미터","밑바닥","바가지","바구니","바나나","바늘","바닥","바닷가","바람","바이러스","바탕","박물관","박사","박수","반대","반드시","반말","반발","반성","반응","반장","반죽","반지","반찬","받침","발가락","발걸음","발견","발달","발레","발목","발바닥","발생","발음","발자국","발전","발톱","발표","밤하늘","밥그릇","밥맛","밥상","밥솥","방금","방면","방문","방바닥","방법","방송","방식","방안","방울","방지","방학","방해","방향","배경","배꼽","배달","배드민턴","백두산","백색","백성","백인","백제","백화점","버릇","버섯","버튼","번개","번역","번지","번호","벌금","벌레","벌써","범위","범인","범죄","법률","법원","법적","법칙","베이징","벨트","변경","변동","변명","변신","변호사","변화","별도","별명","별일","병실","병아리","병원","보관","보너스","보라색","보람","보름","보상","보안","보자기","보장","보전","보존","보통","보편적","보험","복도","복사","복숭아","복습","볶음","본격적","본래","본부","본사","본성","본인","본질","볼펜","봉사","봉지","봉투","부근","부끄러움","부담","부동산","부문","부분","부산","부상","부엌","부인","부작용","부장","부정","부족","부지런히","부친","부탁","부품","부회장","북부","북한","분노","분량","분리","분명","분석","분야","분위기","분필","분홍색","불고기","불과","불교","불꽃","불만","불법","불빛","불안","불이익","불행","브랜드","비극","비난","비닐","비둘기","비디오","비로소","비만","비명","비밀","비바람","비빔밥","비상","비용","비율","비중","비타민","비판","빌딩","빗물","빗방울","빗줄기","빛깔","빨간색","빨래","빨리","사건","사계절","사나이","사냥","사람","사랑","사립","사모님","사물","사방","사상","사생활","사설","사슴","사실","사업","사용","사월","사장","사전","사진","사촌","사춘기","사탕","사투리","사흘","산길","산부인과","산업","산책","살림","살인","살짝","삼계탕","삼국","삼십","삼월","삼촌","상관","상금","상대","상류","상반기","상상","상식","상업","상인","상자","상점","상처","상추","상태","상표","상품","상황","새벽","색깔","색연필","생각","생명","생물","생방송","생산","생선","생신","생일","생활","서랍","서른","서명","서민","서비스","서양","서울","서적","서점","서쪽","서클","석사","석유","선거","선물","선배","선생","선수","선원","선장","선전","선택","선풍기","설거지","설날","설렁탕","설명","설문","설사","설악산","설치","설탕","섭씨","성공","성당","성명","성별","성인","성장","성적","성질","성함","세금","세미나","세상","세월","세종대왕","세탁","센터","센티미터","셋째","소규모","소극적","소금","소나기","소년","소득","소망","소문","소설","소속","소아과","소용","소원","소음","소중히","소지품","소질","소풍","소형","속담","속도","속옷","손가락","손길","손녀","손님","손등","손목","손뼉","손실","손질","손톱","손해","솔직히","솜씨","송아지","송이","송편","쇠고기","쇼핑","수건","수년","수단","수돗물","수동적","수면","수명","수박","수상","수석","수술","수시로","수업","수염","수영","수입","수준","수집","수출","수컷","수필","수학","수험생","수화기","숙녀","숙소","숙제","순간","순서","순수","순식간","순위","숟가락","술병","술집","숫자","스님","스물","스스로","스승","스웨터","스위치","스케이트","스튜디오","스트레스","스포츠","슬쩍","슬픔","습관","습기","승객","승리","승부","승용차","승진","시각","시간","시골","시금치","시나리오","시댁","시리즈","시멘트","시민","시부모","시선","시설","시스템","시아버지","시어머니","시월","시인","시일","시작","시장","시절","시점","시중","시즌","시집","시청","시합","시험","식구","식기","식당","식량","식료품","식물","식빵","식사","식생활","식초","식탁","식품","신고","신규","신념","신문","신발","신비","신사","신세","신용","신제품","신청","신체","신화","실감","실내","실력","실례","실망","실수","실습","실시","실장","실정","실질적","실천","실체","실컷","실태","실패","실험","실현","심리","심부름","심사","심장","심정","심판","쌍둥이","씨름","씨앗","아가씨","아나운서","아드님","아들","아쉬움","아스팔트","아시아","아울러","아저씨","아줌마","아직","아침","아파트","아프리카","아픔","아홉","아흔","악기","악몽","악수","안개","안경","안과","안내","안녕","안동","안방","안부","안주","알루미늄","알코올","암시","암컷","압력","앞날","앞문","애인","애정","액수","앨범","야간","야단","야옹","약간","약국","약속","약수","약점","약품","약혼녀","양념","양력","양말","양배추","양주","양파","어둠","어려움","어른","어젯밤","어쨌든","어쩌다가","어쩐지","언니","언덕","언론","언어","얼굴","얼른","얼음","얼핏","엄마","업무","업종","업체","엉덩이","엉망","엉터리","엊그제","에너지","에어컨","엔진","여건","여고생","여관","여군","여권","여대생","여덟","여동생","여든","여론","여름","여섯","여성","여왕","여인","여전히","여직원","여학생","여행","역사","역시","역할","연결","연구","연극","연기","연락","연설","연세","연속","연습","연애","연예인","연인","연장","연주","연출","연필","연합","연휴","열기","열매","열쇠","열심히","열정","열차","열흘","염려","엽서","영국","영남","영상","영양","영역","영웅","영원히","영하","영향","영혼","영화","옆구리","옆방","옆집","예감","예금","예방","예산","예상","예선","예술","예습","예식장","예약","예전","예절","예정","예컨대","옛날","오늘","오락","오랫동안","오렌지","오로지","오른발","오븐","오십","오염","오월","오전","오직","오징어","오페라","오피스텔","오히려","옥상","옥수수","온갖","온라인","온몸","온종일","온통","올가을","올림픽","올해","옷차림","와이셔츠","와인","완성","완전","왕비","왕자","왜냐하면","왠지","외갓집","외국","외로움","외삼촌","외출","외침","외할머니","왼발","왼손","왼쪽","요금","요일","요즘","요청","용기","용서","용어","우산","우선","우승","우연히","우정","우체국","우편","운동","운명","운반","운전","운행","울산","울음","움직임","웃어른","웃음","워낙","원고","원래","원서","원숭이","원인","원장","원피스","월급","월드컵","월세","월요일","웨이터","위반","위법","위성","위원","위험","위협","윗사람","유난히","유럽","유명","유물","유산","유적","유치원","유학","유행","유형","육군","육상","육십","육체","은행","음력","음료","음반","음성","음식","음악","음주","의견","의논","의문","의복","의식","의심","의외로","의욕","의원","의학","이것","이곳","이념","이놈","이달","이대로","이동","이렇게","이력서","이론적","이름","이민","이발소","이별","이불","이빨","이상","이성","이슬","이야기","이용","이웃","이월","이윽고","이익","이전","이중","이튿날","이틀","이혼","인간","인격","인공","인구","인근","인기","인도","인류","인물","인생","인쇄","인연","인원","인재","인종","인천","인체","인터넷","인하","인형","일곱","일기","일단","일대","일등","일반","일본","일부","일상","일생","일손","일요일","일월","일정","일종","일주일","일찍","일체","일치","일행","일회용","임금","임무","입대","입력","입맛","입사","입술","입시","입원","입장","입학","자가용","자격","자극","자동","자랑","자부심","자식","자신","자연","자원","자율","자전거","자정","자존심","자판","작가","작년","작성","작업","작용","작은딸","작품","잔디","잔뜩","잔치","잘못","잠깐","잠수함","잠시","잠옷","잠자리","잡지","장관","장군","장기간","장래","장례","장르","장마","장면","장모","장미","장비","장사","장소","장식","장애인","장인","장점","장차","장학금","재능","재빨리","재산","재생","재작년","재정","재채기","재판","재학","재활용","저것","저고리","저곳","저녁","저런","저렇게","저번","저울","저절로","저축","적극","적당히","적성","적용","적응","전개","전공","전기","전달","전라도","전망","전문","전반","전부","전세","전시","전용","전자","전쟁","전주","전철","전체","전통","전혀","전후","절대","절망","절반","절약","절차","점검","점수","점심","점원","점점","점차","접근","접시","접촉","젓가락","정거장","정도","정류장","정리","정말","정면","정문","정반대","정보","정부","정비","정상","정성","정오","정원","정장","정지","정치","정확히","제공","제과점","제대로","제목","제발","제법","제삿날","제안","제일","제작","제주도","제출","제품","제한","조각","조건","조금","조깅","조명","조미료","조상","조선","조용히","조절","조정","조직","존댓말","존재","졸업","졸음","종교","종로","종류","종소리","종업원","종종","종합","좌석","죄인","주관적","주름","주말","주머니","주먹","주문","주민","주방","주변","주식","주인","주일","주장","주전자","주택","준비","줄거리","줄기","줄무늬","중간","중계방송","중국","중년","중단","중독","중반","중부","중세","중소기업","중순","중앙","중요","중학교","즉석","즉시","즐거움","증가","증거","증권","증상","증세","지각","지갑","지경","지극히","지금","지급","지능","지름길","지리산","지방","지붕","지식","지역","지우개","지원","지적","지점","지진","지출","직선","직업","직원","직장","진급","진동","진로","진료","진리","진짜","진찰","진출","진통","진행","질문","질병","질서","짐작","집단","집안","집중","짜증","찌꺼기","차남","차라리","차량","차림","차별","차선","차츰","착각","찬물","찬성","참가","참기름","참새","참석","참여","참외","참조","찻잔","창가","창고","창구","창문","창밖","창작","창조","채널","채점","책가방","책방","책상","책임","챔피언","처벌","처음","천국","천둥","천장","천재","천천히","철도","철저히","철학","첫날","첫째","청년","청바지","청소","청춘","체계","체력","체온","체육","체중","체험","초등학생","초반","초밥","초상화","초순","초여름","초원","초저녁","초점","초청","초콜릿","촛불","총각","총리","총장","촬영","최근","최상","최선","최신","최악","최종","추석","추억","추진","추천","추측","축구","축소","축제","축하","출근","출발","출산","출신","출연","출입","출장","출판","충격","충고","충돌","충분히","충청도","취업","취직","취향","치약","친구","친척","칠십","칠월","칠판","침대","침묵","침실","칫솔","칭찬","카메라","카운터","칼국수","캐릭터","캠퍼스","캠페인","커튼","컨디션","컬러","컴퓨터","코끼리","코미디","콘서트","콜라","콤플렉스","콩나물","쾌감","쿠데타","크림","큰길","큰딸","큰소리","큰아들","큰어머니","큰일","큰절","클래식","클럽","킬로","타입","타자기","탁구","탁자","탄생","태권도","태양","태풍","택시","탤런트","터널","터미널","테니스","테스트","테이블","텔레비전","토론","토마토","토요일","통계","통과","통로","통신","통역","통일","통장","통제","통증","통합","통화","퇴근","퇴원","퇴직금","튀김","트럭","특급","특별","특성","특수","특징","특히","튼튼히","티셔츠","파란색","파일","파출소","판결","판단","판매","판사","팔십","팔월","팝송","패션","팩스","팩시밀리","팬티","퍼센트","페인트","편견","편의","편지","편히","평가","평균","평생","평소","평양","평일","평화","포스터","포인트","포장","포함","표면","표정","표준","표현","품목","품질","풍경","풍속","풍습","프랑스","프린터","플라스틱","피곤","피망","피아노","필름","필수","필요","필자","필통","핑계","하느님","하늘","하드웨어","하룻밤","하반기","하숙집","하순","하여튼","하지만","하천","하품","하필","학과","학교","학급","학기","학년","학력","학번","학부모","학비","학생","학술","학습","학용품","학원","학위","학자","학점","한계","한글","한꺼번에","한낮","한눈","한동안","한때","한라산","한마디","한문","한번","한복","한식","한여름","한쪽","할머니","할아버지","할인","함께","함부로","합격","합리적","항공","항구","항상","항의","해결","해군","해답","해당","해물","해석","해설","해수욕장","해안","핵심","핸드백","햄버거","햇볕","햇살","행동","행복","행사","행운","행위","향기","향상","향수","허락","허용","헬기","현관","현금","현대","현상","현실","현장","현재","현지","혈액","협력","형부","형사","형수","형식","형제","형태","형편","혜택","호기심","호남","호랑이","호박","호텔","호흡","혹시","홀로","홈페이지","홍보","홍수","홍차","화면","화분","화살","화요일","화장","화학","확보","확인","확장","확정","환갑","환경","환영","환율","환자","활기","활동","활발히","활용","활짝","회견","회관","회복","회색","회원","회장","회전","횟수","횡단보도","효율적","후반","후춧가루","훈련","훨씬","휴식","휴일","흉내","흐름","흑백","흑인","흔적","흔히","흥미","흥분","희곡","희망","희생","흰색","힘껏"]{"的":["chinese_simplified","chinese_traditional"],"一":["chinese_simplified","chinese_traditional"],"是":["chinese_simplified","chinese_traditional"],"在":["chinese_simplified","chinese_traditional"],"不":["chinese_simplified","chinese_traditional"],"了":["chinese_simplified","chinese_traditional"],"有":["chinese_simplified","chinese_traditional"],"和":["chinese_simplified","chinese_traditional"],"人":["chinese_simplified","chinese_traditional"],"这":["chinese_simplified"],"中":["chinese_simplified","chinese_traditional"],"大":["chinese_simplified","chinese_traditional"],"为":["chinese_simplified"],"上":["chinese_simplified","chinese_traditional"],"个":["chinese_simplified"],"国":["chinese_simplified"],"我":["chinese_simplified","chinese_traditional"],"以":["chinese_simplified","chinese_traditional"],"要":["chinese_simplified","chinese_traditional"],"他":["chinese_simplified","chinese_traditional"],"时":["chinese_simplified"],"来":["chinese_simplified"],"用":["chinese_simplified","chinese_traditional"],"们":["chinese_simplified"],"生":["chinese_simplified","chinese_traditional"],"到":["chinese_simplified","chinese_traditional"],"作":["chinese_simplified","chinese_traditional"],"地":["chinese_simplified","chinese_traditional"],"于":["chinese_simplified"],"出":["chinese_simplified","chinese_traditional"],"就":["chinese_simplified","chinese_traditional"],"分":["chinese_simplified","chinese_traditional"],"对":["chinese_simplified"],"成":["chinese_simplified","chinese_traditional"],"会":["chinese_simplified"],"可":["chinese_simplified","chinese_traditional"],"主":["chinese_simplified","chinese_traditional"],"发":["chinese_simplified"],"年":["chinese_simplified","chinese_traditional"],"动":["chinese_simplified"],"同":["chinese_simplified","chinese_traditional"],"工":["chinese_simplified","chinese_traditional"],"也":["chinese_simplified","chinese_traditional"],"能":["chinese_simplified","chinese_traditional"],"下":["chinese_simplified","chinese_traditional"],"过":["chinese_simplified"],"子":["chinese_simplified","chinese_traditional"],"说":["chinese_simplified"],"产":["chinese_simplified"],"种":["chinese_simplified"],"面":["chinese_simplified","chinese_traditional"],"而":["chinese_simplified","chinese_traditional"],"方":["chinese_simplified","chinese_traditional"],"后":["chinese_simplified"],"多":["chinese_simplified","chinese_traditional"],"定":["chinese_simplified","chinese_traditional"],"行":["chinese_simplified","chinese_traditional"],"学":["chinese_simplified"],"法":["chinese_simplified","chinese_traditional"],"所":["chinese_simplified","chinese_traditional"],"民":["chinese_simplified","chinese_traditional"],"得":["chinese_simplified","chinese_traditional"],"经":["chinese_simplified"],"十":["chinese_simplified","chinese_traditional"],"三":["chinese_simplified","chinese_traditional"],"之":["chinese_simplified","chinese_traditional"],"进":["chinese_simplified"],"着":["chinese_simplified"],"等":["chinese_simplified","chinese_traditional"],"部":["chinese_simplified","chinese_traditional"],"度":["chinese_simplified","chinese_traditional"],"家":["chinese_simplified","chinese_traditional"],"电":["chinese_simplified"],"力":["chinese_simplified","chinese_traditional"],"里":["chinese_simplified"],"如":["chinese_simplified","chinese_traditional"],"水":["chinese_simplified","chinese_traditional"],"化":["chinese_simplified","chinese_traditional"],"高":["chinese_simplified","chinese_traditional"],"自":["chinese_simplified","chinese_traditional"],"二":["chinese_simplified","chinese_traditional"],"理":["chinese_simplified","chinese_traditional"],"起":["chinese_simplified","chinese_traditional"],"小":["chinese_simplified","chinese_traditional"],"物":["chinese_simplified","chinese_traditional"],"现":["chinese_simplified"],"实":["chinese_simplified"],"加":["chinese_simplified","chinese_traditional"],"量":["chinese_simplified","chinese_traditional"],"都":["chinese_simplified","chinese_traditional"],"两":["chinese_simplified"],"体":["chinese_simplified"],"制":["chinese_simplified","chinese_traditional"],"机":["chinese_simplified"],"当":["chinese_simplified"],"使":["chinese_simplified","chinese_traditional"],"点":["chinese_simplified"],"从":["chinese_simplified"],"业":["chinese_simplified"],"本":["chinese_simplified","chinese_traditional"],"去":["chinese_simplified","chinese_traditional"],"把":["chinese_simplified","chinese_traditional"],"性":["chinese_simplified","chinese_traditional"],"好":["chinese_simplified","chinese_traditional"],"应":["chinese_simplified"],"开":["chinese_simplified"],"它":["chinese_simplified","chinese_traditional"],"合":["chinese_simplified","chinese_traditional"],"还":["chinese_simplified"],"因":["chinese_simplified","chinese_traditional"],"由":["chinese_simplified","chinese_traditional"],"其":["chinese_simplified","chinese_traditional"],"些":["chinese_simplified","chinese_traditional"],"然":["chinese_simplified","chinese_traditional"],"前":["chinese_simplified","chinese_traditional"],"外":["chinese_simplified","chinese_traditional"],"天":["chinese_simplified","chinese_traditional"],"政":["chinese_simplified","chinese_traditional"],"四":["chinese_simplified","chinese_traditional"],"日":["chinese_simplified","chinese_traditional"],"那":["chinese_simplified","chinese_traditional"],"社":["chinese_simplified","chinese_traditional"],"义":["chinese_simplified"],"事":["chinese_simplified","chinese_traditional"],"平":["chinese_simplified","chinese_traditional"],"形":["chinese_simplified","chinese_traditional"],"相":["chinese_simplified","chinese_traditional"],"全":["chinese_simplified","chinese_traditional"],"表":["chinese_simplified","chinese_traditional"],"间":["chinese_simplified"],"样":["chinese_simplified"],"与":["chinese_simplified"],"关":["chinese_simplified"],"各":["chinese_simplified","chinese_traditional"],"重":["chinese_simplified","chinese_traditional"],"新":["chinese_simplified","chinese_traditional"],"线":["chinese_simplified"],"内":["chinese_simplified"],"数":["chinese_simplified"],"正":["chinese_simplified","chinese_traditional"],"心":["chinese_simplified","chinese_traditional"],"反":["chinese_simplified","chinese_traditional"],"你":["chinese_simplified","chinese_traditional"],"明":["chinese_simplified","chinese_traditional"],"看":["chinese_simplified","chinese_traditional"],"原":["chinese_simplified","chinese_traditional"],"又":["chinese_simplified","chinese_traditional"],"么":["chinese_simplified"],"利":["chinese_simplified","chinese_traditional"],"比":["chinese_simplified","chinese_traditional"],"或":["chinese_simplified","chinese_traditional"],"但":["chinese_simplified","chinese_traditional"],"质":["chinese_simplified"],"气":["chinese_simplified"],"第":["chinese_simplified","chinese_traditional"],"向":["chinese_simplified","chinese_traditional"],"道":["chinese_simplified","chinese_traditional"],"命":["chinese_simplified","chinese_traditional"],"此":["chinese_simplified","chinese_traditional"],"变":["chinese_simplified"],"条":["chinese_simplified"],"只":["chinese_simplified","chinese_traditional"],"没":["chinese_simplified"],"结":["chinese_simplified"],"解":["chinese_simplified","chinese_traditional"],"问":["chinese_simplified"],"意":["chinese_simplified","chinese_traditional"],"建":["chinese_simplified","chinese_traditional"],"月":["chinese_simplified","chinese_traditional"],"公":["chinese_simplified","chinese_traditional"],"无":["chinese_simplified"],"系":["chinese_simplified","chinese_traditional"],"军":["chinese_simplified"],"很":["chinese_simplified","chinese_traditional"],"情":["chinese_simplified","chinese_traditional"],"者":["chinese_simplified","chinese_traditional"],"最":["chinese_simplified","chinese_traditional"],"立":["chinese_simplified","chinese_traditional"],"代":["chinese_simplified","chinese_traditional"],"想":["chinese_simplified","chinese_traditional"],"已":["chinese_simplified","chinese_traditional"],"通":["chinese_simplified","chinese_traditional"],"并":["chinese_simplified"],"提":["chinese_simplified","chinese_traditional"],"直":["chinese_simplified","chinese_traditional"],"题":["chinese_simplified"],"党":["chinese_simplified"],"程":["chinese_simplified","chinese_traditional"],"展":["chinese_simplified","chinese_traditional"],"五":["chinese_simplified","chinese_traditional"],"果":["chinese_simplified","chinese_traditional"],"料":["chinese_simplified","chinese_traditional"],"象":["chinese_simplified","chinese_traditional"],"员":["chinese_simplified"],"革":["chinese_simplified","chinese_traditional"],"位":["chinese_simplified","chinese_traditional"],"入":["chinese_simplified","chinese_traditional"],"常":["chinese_simplified","chinese_traditional"],"文":["chinese_simplified","chinese_traditional"],"总":["chinese_simplified"],"次":["chinese_simplified","chinese_traditional"],"品":["chinese_simplified","chinese_traditional"],"式":["chinese_simplified","chinese_traditional"],"活":["chinese_simplified","chinese_traditional"],"设":["chinese_simplified"],"及":["chinese_simplified","chinese_traditional"],"管":["chinese_simplified","chinese_traditional"],"特":["chinese_simplified","chinese_traditional"],"件":["chinese_simplified","chinese_traditional"],"长":["chinese_simplified"],"求":["chinese_simplified","chinese_traditional"],"老":["chinese_simplified","chinese_traditional"],"头":["chinese_simplified"],"基":["chinese_simplified","chinese_traditional"],"资":["chinese_simplified"],"边":["chinese_simplified"],"流":["chinese_simplified","chinese_traditional"],"路":["chinese_simplified","chinese_traditional"],"级":["chinese_simplified"],"少":["chinese_simplified","chinese_traditional"],"图":["chinese_simplified"],"山":["chinese_simplified","chinese_traditional"],"统":["chinese_simplified"],"接":["chinese_simplified","chinese_traditional"],"知":["chinese_simplified","chinese_traditional"],"较":["chinese_simplified"],"将":["chinese_simplified"],"组":["chinese_simplified"],"见":["chinese_simplified"],"计":["chinese_simplified"],"别":["chinese_simplified"],"她":["chinese_simplified","chinese_traditional"],"手":["chinese_simplified","chinese_traditional"],"角":["chinese_simplified","chinese_traditional"],"期":["chinese_simplified","chinese_traditional"],"根":["chinese_simplified","chinese_traditional"],"论":["chinese_simplified"],"运":["chinese_simplified"],"农":["chinese_simplified"],"指":["chinese_simplified","chinese_traditional"],"几":["chinese_simplified"],"九":["chinese_simplified","chinese_traditional"],"区":["chinese_simplified"],"强":["chinese_simplified"],"放":["chinese_simplified","chinese_traditional"],"决":["chinese_simplified"],"西":["chinese_simplified","chinese_traditional"],"被":["chinese_simplified","chinese_traditional"],"干":["chinese_simplified"],"做":["chinese_simplified","chinese_traditional"],"必":["chinese_simplified","chinese_traditional"],"战":["chinese_simplified"],"先":["chinese_simplified","chinese_traditional"],"回":["chinese_simplified","chinese_traditional"],"则":["chinese_simplified"],"任":["chinese_simplified","chinese_traditional"],"取":["chinese_simplified","chinese_traditional"],"据":["chinese_simplified"],"处":["chinese_simplified"],"队":["chinese_simplified"],"南":["chinese_simplified","chinese_traditional"],"给":["chinese_simplified"],"色":["chinese_simplified","chinese_traditional"],"光":["chinese_simplified","chinese_traditional"],"门":["chinese_simplified"],"即":["chinese_simplified","chinese_traditional"],"保":["chinese_simplified","chinese_traditional"],"治":["chinese_simplified","chinese_traditional"],"北":["chinese_simplified","chinese_traditional"],"造":["chinese_simplified","chinese_traditional"],"百":["chinese_simplified","chinese_traditional"],"规":["chinese_simplified"],"热":["chinese_simplified"],"领":["chinese_simplified"],"七":["chinese_simplified","chinese_traditional"],"海":["chinese_simplified","chinese_traditional"],"口":["chinese_simplified","chinese_traditional"],"东":["chinese_simplified"],"导":["chinese_simplified"],"器":["chinese_simplified","chinese_traditional"],"压":["chinese_simplified"],"志":["chinese_simplified","chinese_traditional"],"世":["chinese_simplified","chinese_traditional"],"金":["chinese_simplified","chinese_traditional"],"增":["chinese_simplified","chinese_traditional"],"争":["chinese_simplified"],"济":["chinese_simplified"],"阶":["chinese_simplified"],"油":["chinese_simplified","chinese_traditional"],"思":["chinese_simplified","chinese_traditional"],"术":["chinese_simplified"],"极":["chinese_simplified"],"交":["chinese_simplified","chinese_traditional"],"受":["chinese_simplified","chinese_traditional"],"联":["chinese_simplified"],"什":["chinese_simplified","chinese_traditional"],"认":["chinese_simplified"],"六":["chinese_simplified","chinese_traditional"],"共":["chinese_simplified","chinese_traditional"],"权":["chinese_simplified"],"收":["chinese_simplified","chinese_traditional"],"证":["chinese_simplified"],"改":["chinese_simplified","chinese_traditional"],"清":["chinese_simplified","chinese_traditional"],"美":["chinese_simplified","chinese_traditional"],"再":["chinese_simplified","chinese_traditional"],"采":["chinese_simplified"],"转":["chinese_simplified"],"更":["chinese_simplified","chinese_traditional"],"单":["chinese_simplified"],"风":["chinese_simplified"],"切":["chinese_simplified","chinese_traditional"],"打":["chinese_simplified","chinese_traditional"],"白":["chinese_simplified","chinese_traditional"],"教":["chinese_simplified","chinese_traditional"],"速":["chinese_simplified","chinese_traditional"],"花":["chinese_simplified","chinese_traditional"],"带":["chinese_simplified"],"安":["chinese_simplified","chinese_traditional"],"场":["chinese_simplified"],"身":["chinese_simplified","chinese_traditional"],"车":["chinese_simplified"],"例":["chinese_simplified","chinese_traditional"],"真":["chinese_simplified","chinese_traditional"],"务":["chinese_simplified"],"具":["chinese_simplified","chinese_traditional"],"万":["chinese_simplified"],"每":["chinese_simplified","chinese_traditional"],"目":["chinese_simplified","chinese_traditional"],"至":["chinese_simplified","chinese_traditional"],"达":["chinese_simplified"],"走":["chinese_simplified","chinese_traditional"],"积":["chinese_simplified"],"示":["chinese_simplified","chinese_traditional"],"议":["chinese_simplified"],"声":["chinese_simplified"],"报":["chinese_simplified"],"斗":["chinese_simplified"],"完":["chinese_simplified","chinese_traditional"],"类":["chinese_simplified"],"八":["chinese_simplified","chinese_traditional"],"离":["chinese_simplified"],"华":["chinese_simplified"],"名":["chinese_simplified","chinese_traditional"],"确":["chinese_simplified"],"才":["chinese_simplified","chinese_traditional"],"科":["chinese_simplified","chinese_traditional"],"张":["chinese_simplified"],"信":["chinese_simplified","chinese_traditional"],"马":["chinese_simplified"],"节":["chinese_simplified"],"话":["chinese_simplified"],"米":["chinese_simplified","chinese_traditional"],"整":["chinese_simplified","chinese_traditional"],"空":["chinese_simplified","chinese_traditional"],"元":["chinese_simplified","chinese_traditional"],"况":["chinese_simplified"],"今":["chinese_simplified","chinese_traditional"],"集":["chinese_simplified","chinese_traditional"],"温":["chinese_simplified"],"传":["chinese_simplified"],"土":["chinese_simplified","chinese_traditional"],"许":["chinese_simplified"],"步":["chinese_simplified","chinese_traditional"],"群":["chinese_simplified","chinese_traditional"],"广":["chinese_simplified"],"石":["chinese_simplified","chinese_traditional"],"记":["chinese_simplified"],"需":["chinese_simplified","chinese_traditional"],"段":["chinese_simplified","chinese_traditional"],"研":["chinese_simplified","chinese_traditional"],"界":["chinese_simplified","chinese_traditional"],"拉":["chinese_simplified","chinese_traditional"],"林":["chinese_simplified","chinese_traditional"],"律":["chinese_simplified","chinese_traditional"],"叫":["chinese_simplified","chinese_traditional"],"且":["chinese_simplified","chinese_traditional"],"究":["chinese_simplified","chinese_traditional"],"观":["chinese_simplified"],"越":["chinese_simplified","chinese_traditional"],"织":["chinese_simplified"],"装":["chinese_simplified"],"影":["chinese_simplified","chinese_traditional"],"算":["chinese_simplified","chinese_traditional"],"低":["chinese_simplified","chinese_traditional"],"持":["chinese_simplified","chinese_traditional"],"音":["chinese_simplified","chinese_traditional"],"众":["chinese_simplified"],"书":["chinese_simplified"],"布":["chinese_simplified","chinese_traditional"],"复":["chinese_simplified","chinese_traditional"],"容":["chinese_simplified","chinese_traditional"],"儿":["chinese_simplified"],"须":["chinese_simplified"],"际":["chinese_simplified"],"商":["chinese_simplified","chinese_traditional"],"非":["chinese_simplified","chinese_traditional"],"验":["chinese_simplified"],"连":["chinese_simplified"],"断":["chinese_simplified"],"深":["chinese_simplified","chinese_traditional"],"难":["chinese_simplified"],"近":["chinese_simplified","chinese_traditional"],"矿":["chinese_simplified"],"千":["chinese_simplified","chinese_traditional"],"周":["chinese_simplified"],"委":["chinese_simplified","chinese_traditional"],"素":["chinese_simplified","chinese_traditional"],"技":["chinese_simplified","chinese_traditional"],"备":["chinese_simplified"],"半":["chinese_simplified","chinese_traditional"],"办":["chinese_simplified"],"青":["chinese_simplified","chinese_traditional"],"省":["chinese_simplified","chinese_traditional"],"列":["chinese_simplified","chinese_traditional"],"习":["chinese_simplified"],"响":["chinese_simplified"],"约":["chinese_simplified"],"支":["chinese_simplified","chinese_traditional"],"般":["chinese_simplified","chinese_traditional"],"史":["chinese_simplified","chinese_traditional"],"感":["chinese_simplified","chinese_traditional"],"劳":["chinese_simplified"],"便":["chinese_simplified","chinese_traditional"],"团":["chinese_simplified"],"往":["chinese_simplified","chinese_traditional"],"酸":["chinese_simplified","chinese_traditional"],"历":["chinese_simplified"],"市":["chinese_simplified","chinese_traditional"],"克":["chinese_simplified","chinese_traditional"],"何":["chinese_simplified","chinese_traditional"],"除":["chinese_simplified","chinese_traditional"],"消":["chinese_simplified","chinese_traditional"],"构":["chinese_simplified"],"府":["chinese_simplified","chinese_traditional"],"称":["chinese_simplified"],"太":["chinese_simplified","chinese_traditional"],"准":["chinese_simplified"],"精":["chinese_simplified","chinese_traditional"],"值":["chinese_simplified","chinese_traditional"],"号":["chinese_simplified"],"率":["chinese_simplified","chinese_traditional"],"族":["chinese_simplified","chinese_traditional"],"维":["chinese_simplified"],"划":["chinese_simplified"],"选":["chinese_simplified"],"标":["chinese_simplified"],"写":["chinese_simplified"],"存":["chinese_simplified","chinese_traditional"],"候":["chinese_simplified","chinese_traditional"],"毛":["chinese_simplified","chinese_traditional"],"亲":["chinese_simplified"],"快":["chinese_simplified","chinese_traditional"],"效":["chinese_simplified","chinese_traditional"],"斯":["chinese_simplified","chinese_traditional"],"院":["chinese_simplified","chinese_traditional"],"查":["chinese_simplified","chinese_traditional"],"江":["chinese_simplified","chinese_traditional"],"型":["chinese_simplified","chinese_traditional"],"眼":["chinese_simplified","chinese_traditional"],"王":["chinese_simplified","chinese_traditional"],"按":["chinese_simplified","chinese_traditional"],"格":["chinese_simplified","chinese_traditional"],"养":["chinese_simplified"],"易":["chinese_simplified","chinese_traditional"],"置":["chinese_simplified","chinese_traditional"],"派":["chinese_simplified","chinese_traditional"],"层":["chinese_simplified"],"片":["chinese_simplified","chinese_traditional"],"始":["chinese_simplified","chinese_traditional"],"却":["chinese_simplified"],"专":["chinese_simplified"],"状":["chinese_simplified"],"育":["chinese_simplified","chinese_traditional"],"厂":["chinese_simplified"],"京":["chinese_simplified","chinese_traditional"],"识":["chinese_simplified"],"适":["chinese_simplified"],"属":["chinese_simplified"],"圆":["chinese_simplified"],"包":["chinese_simplified","chinese_traditional"],"火":["chinese_simplified","chinese_traditional"],"住":["chinese_simplified","chinese_traditional"],"调":["chinese_simplified"],"满":["chinese_simplified"],"县":["chinese_simplified"],"局":["chinese_simplified","chinese_traditional"],"照":["chinese_simplified","chinese_traditional"],"参":["chinese_simplified"],"红":["chinese_simplified"],"细":["chinese_simplified"],"引":["chinese_simplified","chinese_traditional"],"听":["chinese_simplified"],"该":["chinese_simplified"],"铁":["chinese_simplified"],"价":["chinese_simplified"],"严":["chinese_simplified"],"首":["chinese_simplified","chinese_traditional"],"底":["chinese_simplified","chinese_traditional"],"液":["chinese_simplified","chinese_traditional"],"官":["chinese_simplified","chinese_traditional"],"德":["chinese_simplified","chinese_traditional"],"随":["chinese_simplified"],"病":["chinese_simplified","chinese_traditional"],"苏":["chinese_simplified"],"失":["chinese_simplified","chinese_traditional"],"尔":["chinese_simplified"],"死":["chinese_simplified","chinese_traditional"],"讲":["chinese_simplified"],"配":["chinese_simplified","chinese_traditional"],"女":["chinese_simplified","chinese_traditional"],"黄":["chinese_simplified"],"推":["chinese_simplified","chinese_traditional"],"显":["chinese_simplified"],"谈":["chinese_simplified"],"罪":["chinese_simplified","chinese_traditional"],"神":["chinese_simplified","chinese_traditional"],"艺":["chinese_simplified"],"呢":["chinese_simplified","chinese_traditional"],"席":["chinese_simplified","chinese_traditional"],"含":["chinese_simplified","chinese_traditional"],"企":["chinese_simplified","chinese_traditional"],"望":["chinese_simplified","chinese_traditional"],"密":["chinese_simplified","chinese_traditional"],"批":["chinese_simplified","chinese_traditional"],"营":["chinese_simplified"],"项":["chinese_simplified"],"防":["chinese_simplified","chinese_traditional"],"举":["chinese_simplified"],"球":["chinese_simplified","chinese_traditional"],"英":["chinese_simplified","chinese_traditional"],"氧":["chinese_simplified","chinese_traditional"],"势":["chinese_simplified"],"告":["chinese_simplified","chinese_traditional"],"李":["chinese_simplified","chinese_traditional"],"台":["chinese_simplified","chinese_traditional"],"落":["chinese_simplified","chinese_traditional"],"木":["chinese_simplified","chinese_traditional"],"帮":["chinese_simplified"],"轮":["chinese_simplified"],"破":["chinese_simplified","chinese_traditional"],"亚":["chinese_simplified"],"师":["chinese_simplified"],"围":["chinese_simplified"],"注":["chinese_simplified","chinese_traditional"],"远":["chinese_simplified"],"字":["chinese_simplified","chinese_traditional"],"材":["chinese_simplified","chinese_traditional"],"排":["chinese_simplified","chinese_traditional"],"供":["chinese_simplified","chinese_traditional"],"河":["chinese_simplified","chinese_traditional"],"态":["chinese_simplified"],"封":["chinese_simplified","chinese_traditional"],"另":["chinese_simplified","chinese_traditional"],"施":["chinese_simplified","chinese_traditional"],"减":["chinese_simplified"],"树":["chinese_simplified"],"溶":["chinese_simplified","chinese_traditional"],"怎":["chinese_simplified","chinese_traditional"],"止":["chinese_simplified","chinese_traditional"],"案":["chinese_simplified","chinese_traditional"],"言":["chinese_simplified","chinese_traditional"],"士":["chinese_simplified","chinese_traditional"],"均":["chinese_simplified","chinese_traditional"],"武":["chinese_simplified","chinese_traditional"],"固":["chinese_simplified","chinese_traditional"],"叶":["chinese_simplified"],"鱼":["chinese_simplified"],"波":["chinese_simplified","chinese_traditional"],"视":["chinese_simplified"],"仅":["chinese_simplified"],"费":["chinese_simplified"],"紧":["chinese_simplified"],"爱":["chinese_simplified"],"左":["chinese_simplified","chinese_traditional"],"章":["chinese_simplified","chinese_traditional"],"早":["chinese_simplified","chinese_traditional"],"朝":["chinese_simplified","chinese_traditional"],"害":["chinese_simplified","chinese_traditional"],"续":["chinese_simplified"],"轻":["chinese_simplified"],"服":["chinese_simplified","chinese_traditional"],"试":["chinese_simplified"],"食":["chinese_simplified","chinese_traditional"],"充":["chinese_simplified","chinese_traditional"],"兵":["chinese_simplified","chinese_traditional"],"源":["chinese_simplified","chinese_traditional"],"判":["chinese_simplified","chinese_traditional"],"护":["chinese_simplified"],"司":["chinese_simplified","chinese_traditional"],"足":["chinese_simplified","chinese_traditional"],"某":["chinese_simplified","chinese_traditional"],"练":["chinese_simplified"],"差":["chinese_simplified","chinese_traditional"],"致":["chinese_simplified","chinese_traditional"],"板":["chinese_simplified","chinese_traditional"],"田":["chinese_simplified","chinese_traditional"],"降":["chinese_simplified","chinese_traditional"],"黑":["chinese_simplified","chinese_traditional"],"犯":["chinese_simplified","chinese_traditional"],"负":["chinese_simplified"],"击":["chinese_simplified"],"范":["chinese_simplified","chinese_traditional"],"继":["chinese_simplified"],"兴":["chinese_simplified"],"似":["chinese_simplified","chinese_traditional"],"余":["chinese_simplified"],"坚":["chinese_simplified"],"曲":["chinese_simplified","chinese_traditional"],"输":["chinese_simplified"],"修":["chinese_simplified","chinese_traditional"],"故":["chinese_simplified","chinese_traditional"],"城":["chinese_simplified","chinese_traditional"],"夫":["chinese_simplified","chinese_traditional"],"够":["chinese_simplified"],"送":["chinese_simplified","chinese_traditional"],"笔":["chinese_simplified"],"船":["chinese_simplified","chinese_traditional"],"占":["chinese_simplified"],"右":["chinese_simplified","chinese_traditional"],"财":["chinese_simplified"],"吃":["chinese_simplified","chinese_traditional"],"富":["chinese_simplified","chinese_traditional"],"春":["chinese_simplified","chinese_traditional"],"职":["chinese_simplified"],"觉":["chinese_simplified"],"汉":["chinese_simplified"],"画":["chinese_simplified"],"功":["chinese_simplified","chinese_traditional"],"巴":["chinese_simplified","chinese_traditional"],"跟":["chinese_simplified","chinese_traditional"],"虽":["chinese_simplified"],"杂":["chinese_simplified"],"飞":["chinese_simplified"],"检":["chinese_simplified"],"吸":["chinese_simplified","chinese_traditional"],"助":["chinese_simplified","chinese_traditional"],"升":["chinese_simplified"],"阳":["chinese_simplified"],"互":["chinese_simplified","chinese_traditional"],"初":["chinese_simplified","chinese_traditional"],"创":["chinese_simplified"],"抗":["chinese_simplified","chinese_traditional"],"考":["chinese_simplified","chinese_traditional"],"投":["chinese_simplified","chinese_traditional"],"坏":["chinese_simplified"],"策":["chinese_simplified","chinese_traditional"],"古":["chinese_simplified","chinese_traditional"],"径":["chinese_simplified"],"换":["chinese_simplified"],"未":["chinese_simplified","chinese_traditional"],"跑":["chinese_simplified","chinese_traditional"],"留":["chinese_simplified","chinese_traditional"],"钢":["chinese_simplified"],"曾":["chinese_simplified","chinese_traditional"],"端":["chinese_simplified","chinese_traditional"],"责":["chinese_simplified"],"站":["chinese_simplified","chinese_traditional"],"简":["chinese_simplified"],"述":["chinese_simplified","chinese_traditional"],"钱":["chinese_simplified"],"副":["chinese_simplified","chinese_traditional"],"尽":["chinese_simplified"],"帝":["chinese_simplified","chinese_traditional"],"射":["chinese_simplified","chinese_traditional"],"草":["chinese_simplified","chinese_traditional"],"冲":["chinese_simplified"],"承":["chinese_simplified","chinese_traditional"],"独":["chinese_simplified"],"令":["chinese_simplified","chinese_traditional"],"限":["chinese_simplified","chinese_traditional"],"阿":["chinese_simplified","chinese_traditional"],"宣":["chinese_simplified","chinese_traditional"],"环":["chinese_simplified"],"双":["chinese_simplified"],"请":["chinese_simplified"],"超":["chinese_simplified","chinese_traditional"],"微":["chinese_simplified","chinese_traditional"],"让":["chinese_simplified"],"控":["chinese_simplified","chinese_traditional"],"州":["chinese_simplified","chinese_traditional"],"良":["chinese_simplified","chinese_traditional"],"轴":["chinese_simplified"],"找":["chinese_simplified","chinese_traditional"],"否":["chinese_simplified","chinese_traditional"],"纪":["chinese_simplified"],"益":["chinese_simplified","chinese_traditional"],"依":["chinese_simplified","chinese_traditional"],"优":["chinese_simplified"],"顶":["chinese_simplified"],"础":["chinese_simplified"],"载":["chinese_simplified"],"倒":["chinese_simplified","chinese_traditional"],"房":["chinese_simplified","chinese_traditional"],"突":["chinese_simplified","chinese_traditional"],"坐":["chinese_simplified","chinese_traditional"],"粉":["chinese_simplified","chinese_traditional"],"敌":["chinese_simplified"],"略":["chinese_simplified","chinese_traditional"],"客":["chinese_simplified","chinese_traditional"],"袁":["chinese_simplified","chinese_traditional"],"冷":["chinese_simplified","chinese_traditional"],"胜":["chinese_simplified"],"绝":["chinese_simplified"],"析":["chinese_simplified","chinese_traditional"],"块":["chinese_simplified"],"剂":["chinese_simplified"],"测":["chinese_simplified"],"丝":["chinese_simplified"],"协":["chinese_simplified"],"诉":["chinese_simplified"],"念":["chinese_simplified","chinese_traditional"],"陈":["chinese_simplified"],"仍":["chinese_simplified","chinese_traditional"],"罗":["chinese_simplified"],"盐":["chinese_simplified"],"友":["chinese_simplified","chinese_traditional"],"洋":["chinese_simplified","chinese_traditional"],"错":["chinese_simplified"],"苦":["chinese_simplified","chinese_traditional"],"夜":["chinese_simplified","chinese_traditional"],"刑":["chinese_simplified","chinese_traditional"],"移":["chinese_simplified","chinese_traditional"],"频":["chinese_simplified"],"逐":["chinese_simplified","chinese_traditional"],"靠":["chinese_simplified","chinese_traditional"],"混":["chinese_simplified","chinese_traditional"],"母":["chinese_simplified","chinese_traditional"],"短":["chinese_simplified","chinese_traditional"],"皮":["chinese_simplified","chinese_traditional"],"终":["chinese_simplified"],"聚":["chinese_simplified","chinese_traditional"],"汽":["chinese_simplified","chinese_traditional"],"村":["chinese_simplified","chinese_traditional"],"云":["chinese_simplified"],"哪":["chinese_simplified","chinese_traditional"],"既":["chinese_simplified","chinese_traditional"],"距":["chinese_simplified","chinese_traditional"],"卫":["chinese_simplified"],"停":["chinese_simplified","chinese_traditional"],"烈":["chinese_simplified","chinese_traditional"],"央":["chinese_simplified","chinese_traditional"],"察":["chinese_simplified","chinese_traditional"],"烧":["chinese_simplified"],"迅":["chinese_simplified","chinese_traditional"],"境":["chinese_simplified","chinese_traditional"],"若":["chinese_simplified","chinese_traditional"],"印":["chinese_simplified","chinese_traditional"],"洲":["chinese_simplified","chinese_traditional"],"刻":["chinese_simplified","chinese_traditional"],"括":["chinese_simplified","chinese_traditional"],"激":["chinese_simplified","chinese_traditional"],"孔":["chinese_simplified","chinese_traditional"],"搞":["chinese_simplified","chinese_traditional"],"甚":["chinese_simplified","chinese_traditional"],"室":["chinese_simplified","chinese_traditional"],"待":["chinese_simplified","chinese_traditional"],"核":["chinese_simplified","chinese_traditional"],"校":["chinese_simplified","chinese_traditional"],"散":["chinese_simplified","chinese_traditional"],"侵":["chinese_simplified","chinese_traditional"],"吧":["chinese_simplified","chinese_traditional"],"甲":["chinese_simplified","chinese_traditional"],"游":["chinese_simplified"],"久":["chinese_simplified","chinese_traditional"],"菜":["chinese_simplified","chinese_traditional"],"味":["chinese_simplified","chinese_traditional"],"旧":["chinese_simplified"],"模":["chinese_simplified","chinese_traditional"],"湖":["chinese_simplified","chinese_traditional"],"货":["chinese_simplified"],"损":["chinese_simplified"],"预":["chinese_simplified"],"阻":["chinese_simplified","chinese_traditional"],"毫":["chinese_simplified","chinese_traditional"],"普":["chinese_simplified","chinese_traditional"],"稳":["chinese_simplified"],"乙":["chinese_simplified","chinese_traditional"],"妈":["chinese_simplified"],"植":["chinese_simplified","chinese_traditional"],"息":["chinese_simplified","chinese_traditional"],"扩":["chinese_simplified"],"银":["chinese_simplified"],"语":["chinese_simplified"],"挥":["chinese_simplified"],"酒":["chinese_simplified","chinese_traditional"],"守":["chinese_simplified","chinese_traditional"],"拿":["chinese_simplified","chinese_traditional"],"序":["chinese_simplified","chinese_traditional"],"纸":["chinese_simplified"],"医":["chinese_simplified"],"缺":["chinese_simplified","chinese_traditional"],"雨":["chinese_simplified","chinese_traditional"],"吗":["chinese_simplified"],"针":["chinese_simplified"],"刘":["chinese_simplified"],"啊":["chinese_simplified","chinese_traditional"],"急":["chinese_simplified","chinese_traditional"],"唱":["chinese_simplified","chinese_traditional"],"误":["chinese_simplified"],"训":["chinese_simplified"],"愿":["chinese_simplified"],"审":["chinese_simplified"],"附":["chinese_simplified","chinese_traditional"],"获":["chinese_simplified"],"茶":["chinese_simplified","chinese_traditional"],"鲜":["chinese_simplified"],"粮":["chinese_simplified"],"斤":["chinese_simplified","chinese_traditional"],"孩":["chinese_simplified","chinese_traditional"],"脱":["chinese_simplified"],"硫":["chinese_simplified","chinese_traditional"],"肥":["chinese_simplified","chinese_traditional"],"善":["chinese_simplified","chinese_traditional"],"龙":["chinese_simplified"],"演":["chinese_simplified","chinese_traditional"],"父":["chinese_simplified","chinese_traditional"],"渐":["chinese_simplified"],"血":["chinese_simplified","chinese_traditional"],"欢":["chinese_simplified"],"械":["chinese_simplified","chinese_traditional"],"掌":["chinese_simplified","chinese_traditional"],"歌":["chinese_simplified","chinese_traditional"],"沙":["chinese_simplified","chinese_traditional"],"刚":["chinese_simplified"],"攻":["chinese_simplified","chinese_traditional"],"谓":["chinese_simplified"],"盾":["chinese_simplified","chinese_traditional"],"讨":["chinese_simplified"],"晚":["chinese_simplified","chinese_traditional"],"粒":["chinese_simplified","chinese_traditional"],"乱":["chinese_simplified"],"燃":["chinese_simplified","chinese_traditional"],"矛":["chinese_simplified","chinese_traditional"],"乎":["chinese_simplified","chinese_traditional"],"杀":["chinese_simplified"],"药":["chinese_simplified"],"宁":["chinese_simplified"],"鲁":["chinese_simplified"],"贵":["chinese_simplified"],"钟":["chinese_simplified"],"煤":["chinese_simplified","chinese_traditional"],"读":["chinese_simplified"],"班":["chinese_simplified","chinese_traditional"],"伯":["chinese_simplified","chinese_traditional"],"香":["chinese_simplified","chinese_traditional"],"介":["chinese_simplified","chinese_traditional"],"迫":["chinese_simplified","chinese_traditional"],"句":["chinese_simplified","chinese_traditional"],"丰":["chinese_simplified"],"培":["chinese_simplified","chinese_traditional"],"握":["chinese_simplified","chinese_traditional"],"兰":["chinese_simplified"],"担":["chinese_simplified"],"弦":["chinese_simplified","chinese_traditional"],"蛋":["chinese_simplified","chinese_traditional"],"沉":["chinese_simplified","chinese_traditional"],"假":["chinese_simplified","chinese_traditional"],"穿":["chinese_simplified","chinese_traditional"],"执":["chinese_simplified"],"答":["chinese_simplified","chinese_traditional"],"乐":["chinese_simplified"],"谁":["chinese_simplified"],"顺":["chinese_simplified"],"烟":["chinese_simplified"],"缩":["chinese_simplified"],"征":["chinese_simplified"],"脸":["chinese_simplified"],"喜":["chinese_simplified","chinese_traditional"],"松":["chinese_simplified","chinese_traditional"],"脚":["chinese_simplified"],"困":["chinese_simplified","chinese_traditional"],"异":["chinese_simplified"],"免":["chinese_simplified","chinese_traditional"],"背":["chinese_simplified","chinese_traditional"],"星":["chinese_simplified","chinese_traditional"],"福":["chinese_simplified","chinese_traditional"],"买":["chinese_simplified"],"染":["chinese_simplified","chinese_traditional"],"井":["chinese_simplified","chinese_traditional"],"概":["chinese_simplified","chinese_traditional"],"慢":["chinese_simplified","chinese_traditional"],"怕":["chinese_simplified","chinese_traditional"],"磁":["chinese_simplified","chinese_traditional"],"倍":["chinese_simplified","chinese_traditional"],"祖":["chinese_simplified","chinese_traditional"],"皇":["chinese_simplified","chinese_traditional"],"促":["chinese_simplified","chinese_traditional"],"静":["chinese_simplified"],"补":["chinese_simplified"],"评":["chinese_simplified"],"翻":["chinese_simplified","chinese_traditional"],"肉":["chinese_simplified","chinese_traditional"],"践":["chinese_simplified"],"尼":["chinese_simplified","chinese_traditional"],"衣":["chinese_simplified","chinese_traditional"],"宽":["chinese_simplified"],"扬":["chinese_simplified"],"棉":["chinese_simplified","chinese_traditional"],"希":["chinese_simplified","chinese_traditional"],"伤":["chinese_simplified"],"操":["chinese_simplified","chinese_traditional"],"垂":["chinese_simplified","chinese_traditional"],"秋":["chinese_simplified","chinese_traditional"],"宜":["chinese_simplified","chinese_traditional"],"氢":["chinese_simplified"],"套":["chinese_simplified","chinese_traditional"],"督":["chinese_simplified","chinese_traditional"],"振":["chinese_simplified","chinese_traditional"],"架":["chinese_simplified","chinese_traditional"],"亮":["chinese_simplified","chinese_traditional"],"末":["chinese_simplified","chinese_traditional"],"宪":["chinese_simplified"],"庆":["chinese_simplified"],"编":["chinese_simplified"],"牛":["chinese_simplified","chinese_traditional"],"触":["chinese_simplified"],"映":["chinese_simplified","chinese_traditional"],"雷":["chinese_simplified","chinese_traditional"],"销":["chinese_simplified"],"诗":["chinese_simplified"],"座":["chinese_simplified","chinese_traditional"],"居":["chinese_simplified","chinese_traditional"],"抓":["chinese_simplified","chinese_traditional"],"裂":["chinese_simplified","chinese_traditional"],"胞":["chinese_simplified","chinese_traditional"],"呼":["chinese_simplified","chinese_traditional"],"娘":["chinese_simplified","chinese_traditional"],"景":["chinese_simplified","chinese_traditional"],"威":["chinese_simplified","chinese_traditional"],"绿":["chinese_simplified"],"晶":["chinese_simplified","chinese_traditional"],"厚":["chinese_simplified","chinese_traditional"],"盟":["chinese_simplified","chinese_traditional"],"衡":["chinese_simplified","chinese_traditional"],"鸡":["chinese_simplified"],"孙":["chinese_simplified"],"延":["chinese_simplified","chinese_traditional"],"危":["chinese_simplified","chinese_traditional"],"胶":["chinese_simplified"],"屋":["chinese_simplified","chinese_traditional"],"乡":["chinese_simplified"],"临":["chinese_simplified"],"陆":["chinese_simplified"],"顾":["chinese_simplified"],"掉":["chinese_simplified","chinese_traditional"],"呀":["chinese_simplified","chinese_traditional"],"灯":["chinese_simplified"],"岁":["chinese_simplified"],"措":["chinese_simplified","chinese_traditional"],"束":["chinese_simplified","chinese_traditional"],"耐":["chinese_simplified","chinese_traditional"],"剧":["chinese_simplified"],"玉":["chinese_simplified","chinese_traditional"],"赵":["chinese_simplified"],"跳":["chinese_simplified","chinese_traditional"],"哥":["chinese_simplified","chinese_traditional"],"季":["chinese_simplified","chinese_traditional"],"课":["chinese_simplified"],"凯":["chinese_simplified"],"胡":["chinese_simplified","chinese_traditional"],"额":["chinese_simplified"],"款":["chinese_simplified","chinese_traditional"],"绍":["chinese_simplified"],"卷":["chinese_simplified","chinese_traditional"],"齐":["chinese_simplified"],"伟":["chinese_simplified"],"蒸":["chinese_simplified","chinese_traditional"],"殖":["chinese_simplified","chinese_traditional"],"永":["chinese_simplified","chinese_traditional"],"宗":["chinese_simplified","chinese_traditional"],"苗":["chinese_simplified","chinese_traditional"],"川":["chinese_simplified","chinese_traditional"],"炉":["chinese_simplified"],"岩":["chinese_simplified","chinese_traditional"],"弱":["chinese_simplified","chinese_traditional"],"零":["chinese_simplified","chinese_traditional"],"杨":["chinese_simplified"],"奏":["chinese_simplified","chinese_traditional"],"沿":["chinese_simplified","chinese_traditional"],"露":["chinese_simplified","chinese_traditional"],"杆":["chinese_simplified"],"探":["chinese_simplified","chinese_traditional"],"滑":["chinese_simplified","chinese_traditional"],"镇":["chinese_simplified"],"饭":["chinese_simplified"],"浓":["chinese_simplified"],"航":["chinese_simplified","chinese_traditional"],"怀":["chinese_simplified"],"赶":["chinese_simplified"],"库":["chinese_simplified"],"夺":["chinese_simplified"],"伊":["chinese_simplified","chinese_traditional"],"灵":["chinese_simplified"],"税":["chinese_simplified"],"途":["chinese_simplified","chinese_traditional"],"灭":["chinese_simplified"],"赛":["chinese_simplified"],"归":["chinese_simplified"],"召":["chinese_simplified","chinese_traditional"],"鼓":["chinese_simplified","chinese_traditional"],"播":["chinese_simplified","chinese_traditional"],"盘":["chinese_simplified"],"裁":["chinese_simplified","chinese_traditional"],"险":["chinese_simplified"],"康":["chinese_simplified","chinese_traditional"],"唯":["chinese_simplified","chinese_traditional"],"录":["chinese_simplified"],"菌":["chinese_simplified","chinese_traditional"],"纯":["chinese_simplified"],"借":["chinese_simplified","chinese_traditional"],"糖":["chinese_simplified","chinese_traditional"],"盖":["chinese_simplified"],"横":["chinese_simplified"],"符":["chinese_simplified","chinese_traditional"],"私":["chinese_simplified","chinese_traditional"],"努":["chinese_simplified","chinese_traditional"],"堂":["chinese_simplified","chinese_traditional"],"域":["chinese_simplified","chinese_traditional"],"枪":["chinese_simplified"],"润":["chinese_simplified"],"幅":["chinese_simplified","chinese_traditional"],"哈":["chinese_simplified","chinese_traditional"],"竟":["chinese_simplified","chinese_traditional"],"熟":["chinese_simplified","chinese_traditional"],"虫":["chinese_simplified"],"泽":["chinese_simplified"],"脑":["chinese_simplified"],"壤":["chinese_simplified","chinese_traditional"],"碳":["chinese_simplified","chinese_traditional"],"欧":["chinese_simplified"],"遍":["chinese_simplified","chinese_traditional"],"侧":["chinese_simplified"],"寨":["chinese_simplified","chinese_traditional"],"敢":["chinese_simplified","chinese_traditional"],"彻":["chinese_simplified"],"虑":["chinese_simplified"],"斜":["chinese_simplified","chinese_traditional"],"薄":["chinese_simplified","chinese_traditional"],"庭":["chinese_simplified","chinese_traditional"],"纳":["chinese_simplified"],"弹":["chinese_simplified"],"饲":["chinese_simplified"],"伸":["chinese_simplified","chinese_traditional"],"折":["chinese_simplified","chinese_traditional"],"麦":["chinese_simplified"],"湿":["chinese_simplified"],"暗":["chinese_simplified","chinese_traditional"],"荷":["chinese_simplified","chinese_traditional"],"瓦":["chinese_simplified","chinese_traditional"],"塞":["chinese_simplified","chinese_traditional"],"床":["chinese_simplified","chinese_traditional"],"筑":["chinese_simplified"],"恶":["chinese_simplified"],"户":["chinese_simplified"],"访":["chinese_simplified"],"塔":["chinese_simplified","chinese_traditional"],"奇":["chinese_simplified","chinese_traditional"],"透":["chinese_simplified","chinese_traditional"],"梁":["chinese_simplified","chinese_traditional"],"刀":["chinese_simplified","chinese_traditional"],"旋":["chinese_simplified","chinese_traditional"],"迹":["chinese_simplified"],"卡":["chinese_simplified","chinese_traditional"],"氯":["chinese_simplified","chinese_traditional"],"遇":["chinese_simplified","chinese_traditional"],"份":["chinese_simplified","chinese_traditional"],"毒":["chinese_simplified","chinese_traditional"],"泥":["chinese_simplified","chinese_traditional"],"退":["chinese_simplified","chinese_traditional"],"洗":["chinese_simplified","chinese_traditional"],"摆":["chinese_simplified"],"灰":["chinese_simplified","chinese_traditional"],"彩":["chinese_simplified","chinese_traditional"],"卖":["chinese_simplified"],"耗":["chinese_simplified","chinese_traditional"],"夏":["chinese_simplified","chinese_traditional"],"择":["chinese_simplified"],"忙":["chinese_simplified","chinese_traditional"],"铜":["chinese_simplified"],"献":["chinese_simplified"],"硬":["chinese_simplified","chinese_traditional"],"予":["chinese_simplified","chinese_traditional"],"繁":["chinese_simplified","chinese_traditional"],"圈":["chinese_simplified","chinese_traditional"],"雪":["chinese_simplified","chinese_traditional"],"函":["chinese_simplified","chinese_traditional"],"亦":["chinese_simplified","chinese_traditional"],"抽":["chinese_simplified","chinese_traditional"],"篇":["chinese_simplified","chinese_traditional"],"阵":["chinese_simplified"],"阴":["chinese_simplified"],"丁":["chinese_simplified","chinese_traditional"],"尺":["chinese_simplified","chinese_traditional"],"追":["chinese_simplified","chinese_traditional"],"堆":["chinese_simplified","chinese_traditional"],"雄":["chinese_simplified","chinese_traditional"],"迎":["chinese_simplified","chinese_traditional"],"泛":["chinese_simplified","chinese_traditional"],"爸":["chinese_simplified","chinese_traditional"],"楼":["chinese_simplified"],"避":["chinese_simplified","chinese_traditional"],"谋":["chinese_simplified"],"吨":["chinese_simplified"],"野":["chinese_simplified","chinese_traditional"],"猪":["chinese_simplified"],"旗":["chinese_simplified","chinese_traditional"],"累":["chinese_simplified","chinese_traditional"],"偏":["chinese_simplified","chinese_traditional"],"典":["chinese_simplified","chinese_traditional"],"馆":["chinese_simplified"],"索":["chinese_simplified","chinese_traditional"],"秦":["chinese_simplified","chinese_traditional"],"脂":["chinese_simplified","chinese_traditional"],"潮":["chinese_simplified","chinese_traditional"],"爷":["chinese_simplified"],"豆":["chinese_simplified","chinese_traditional"],"忽":["chinese_simplified","chinese_traditional"],"托":["chinese_simplified","chinese_traditional"],"惊":["chinese_simplified"],"塑":["chinese_simplified","chinese_traditional"],"遗":["chinese_simplified"],"愈":["chinese_simplified","chinese_traditional"],"朱":["chinese_simplified","chinese_traditional"],"替":["chinese_simplified","chinese_traditional"],"纤":["chinese_simplified"],"粗":["chinese_simplified","chinese_traditional"],"倾":["chinese_simplified"],"尚":["chinese_simplified","chinese_traditional"],"痛":["chinese_simplified","chinese_traditional"],"楚":["chinese_simplified","chinese_traditional"],"谢":["chinese_simplified"],"奋":["chinese_simplified"],"购":["chinese_simplified"],"磨":["chinese_simplified","chinese_traditional"],"君":["chinese_simplified","chinese_traditional"],"池":["chinese_simplified","chinese_traditional"],"旁":["chinese_simplified","chinese_traditional"],"碎":["chinese_simplified","chinese_traditional"],"骨":["chinese_simplified","chinese_traditional"],"监":["chinese_simplified"],"捕":["chinese_simplified","chinese_traditional"],"弟":["chinese_simplified","chinese_traditional"],"暴":["chinese_simplified","chinese_traditional"],"割":["chinese_simplified","chinese_traditional"],"贯":["chinese_simplified"],"殊":["chinese_simplified","chinese_traditional"],"释":["chinese_simplified"],"词":["chinese_simplified"],"亡":["chinese_simplified","chinese_traditional"],"壁":["chinese_simplified","chinese_traditional"],"顿":["chinese_simplified"],"宝":["chinese_simplified"],"午":["chinese_simplified","chinese_traditional"],"尘":["chinese_simplified"],"闻":["chinese_simplified"],"揭":["chinese_simplified","chinese_traditional"],"炮":["chinese_simplified","chinese_traditional"],"残":["chinese_simplified"],"冬":["chinese_simplified","chinese_traditional"],"桥":["chinese_simplified"],"妇":["chinese_simplified"],"警":["chinese_simplified","chinese_traditional"],"综":["chinese_simplified"],"招":["chinese_simplified","chinese_traditional"],"吴":["chinese_simplified"],"付":["chinese_simplified","chinese_traditional"],"浮":["chinese_simplified","chinese_traditional"],"遭":["chinese_simplified","chinese_traditional"],"徐":["chinese_simplified","chinese_traditional"],"您":["chinese_simplified","chinese_traditional"],"摇":["chinese_simplified"],"谷":["chinese_simplified","chinese_traditional"],"赞":["chinese_simplified"],"箱":["chinese_simplified","chinese_traditional"],"隔":["chinese_simplified","chinese_traditional"],"订":["chinese_simplified"],"男":["chinese_simplified","chinese_traditional"],"吹":["chinese_simplified","chinese_traditional"],"园":["chinese_simplified"],"纷":["chinese_simplified"],"唐":["chinese_simplified","chinese_traditional"],"败":["chinese_simplified"],"宋":["chinese_simplified","chinese_traditional"],"玻":["chinese_simplified","chinese_traditional"],"巨":["chinese_simplified","chinese_traditional"],"耕":["chinese_simplified","chinese_traditional"],"坦":["chinese_simplified","chinese_traditional"],"荣":["chinese_simplified"],"闭":["chinese_simplified"],"湾":["chinese_simplified"],"键":["chinese_simplified"],"凡":["chinese_simplified","chinese_traditional"],"驻":["chinese_simplified"],"锅":["chinese_simplified"],"救":["chinese_simplified","chinese_traditional"],"恩":["chinese_simplified","chinese_traditional"],"剥":["chinese_simplified"],"凝":["chinese_simplified","chinese_traditional"],"碱":["chinese_simplified"],"齿":["chinese_simplified"],"截":["chinese_simplified","chinese_traditional"],"炼":["chinese_simplified"],"麻":["chinese_simplified","chinese_traditional"],"纺":["chinese_simplified"],"禁":["chinese_simplified","chinese_traditional"],"废":["chinese_simplified"],"盛":["chinese_simplified","chinese_traditional"],"版":["chinese_simplified","chinese_traditional"],"缓":["chinese_simplified"],"净":["chinese_simplified"],"睛":["chinese_simplified","chinese_traditional"],"昌":["chinese_simplified","chinese_traditional"],"婚":["chinese_simplified","chinese_traditional"],"涉":["chinese_simplified","chinese_traditional"],"筒":["chinese_simplified","chinese_traditional"],"嘴":["chinese_simplified","chinese_traditional"],"插":["chinese_simplified","chinese_traditional"],"岸":["chinese_simplified","chinese_traditional"],"朗":["chinese_simplified","chinese_traditional"],"庄":["chinese_simplified"],"街":["chinese_simplified","chinese_traditional"],"藏":["chinese_simplified","chinese_traditional"],"姑":["chinese_simplified","chinese_traditional"],"贸":["chinese_simplified"],"腐":["chinese_simplified","chinese_traditional"],"奴":["chinese_simplified","chinese_traditional"],"啦":["chinese_simplified","chinese_traditional"],"惯":["chinese_simplified"],"乘":["chinese_simplified","chinese_traditional"],"伙":["chinese_simplified"],"恢":["chinese_simplified","chinese_traditional"],"匀":["chinese_simplified"],"纱":["chinese_simplified"],"扎":["chinese_simplified","chinese_traditional"],"辩":["chinese_simplified"],"耳":["chinese_simplified","chinese_traditional"],"彪":["chinese_simplified","chinese_traditional"],"臣":["chinese_simplified","chinese_traditional"],"亿":["chinese_simplified"],"璃":["chinese_simplified","chinese_traditional"],"抵":["chinese_simplified","chinese_traditional"],"脉":["chinese_simplified"],"秀":["chinese_simplified","chinese_traditional"],"萨":["chinese_simplified"],"俄":["chinese_simplified","chinese_traditional"],"网":["chinese_simplified"],"舞":["chinese_simplified","chinese_traditional"],"店":["chinese_simplified","chinese_traditional"],"喷":["chinese_simplified"],"纵":["chinese_simplified"],"寸":["chinese_simplified","chinese_traditional"],"汗":["chinese_simplified","chinese_traditional"],"挂":["chinese_simplified"],"洪":["chinese_simplified","chinese_traditional"],"贺":["chinese_simplified"],"闪":["chinese_simplified"],"柬":["chinese_simplified","chinese_traditional"],"爆":["chinese_simplified","chinese_traditional"],"烯":["chinese_simplified","chinese_traditional"],"津":["chinese_simplified","chinese_traditional"],"稻":["chinese_simplified","chinese_traditional"],"墙":["chinese_simplified"],"软":["chinese_simplified"],"勇":["chinese_simplified","chinese_traditional"],"像":["chinese_simplified","chinese_traditional"],"滚":["chinese_simplified"],"厘":["chinese_simplified","chinese_traditional"],"蒙":["chinese_simplified","chinese_traditional"],"芳":["chinese_simplified","chinese_traditional"],"肯":["chinese_simplified","chinese_traditional"],"坡":["chinese_simplified","chinese_traditional"],"柱":["chinese_simplified","chinese_traditional"],"荡":["chinese_simplified"],"腿":["chinese_simplified","chinese_traditional"],"仪":["chinese_simplified"],"旅":["chinese_simplified","chinese_traditional"],"尾":["chinese_simplified","chinese_traditional"],"轧":["chinese_simplified"],"冰":["chinese_simplified","chinese_traditional"],"贡":["chinese_simplified"],"登":["chinese_simplified","chinese_traditional"],"黎":["chinese_simplified","chinese_traditional"],"削":["chinese_simplified","chinese_traditional"],"钻":["chinese_simplified"],"勒":["chinese_simplified","chinese_traditional"],"逃":["chinese_simplified","chinese_traditional"],"障":["chinese_simplified","chinese_traditional"],"氨":["chinese_simplified","chinese_traditional"],"郭":["chinese_simplified","chinese_traditional"],"峰":["chinese_simplified","chinese_traditional"],"币":["chinese_simplified"],"港":["chinese_simplified","chinese_traditional"],"伏":["chinese_simplified","chinese_traditional"],"轨":["chinese_simplified"],"亩":["chinese_simplified"],"毕":["chinese_simplified"],"擦":["chinese_simplified","chinese_traditional"],"莫":["chinese_simplified","chinese_traditional"],"刺":["chinese_simplified","chinese_traditional"],"浪":["chinese_simplified","chinese_traditional"],"秘":["chinese_simplified","chinese_traditional"],"援":["chinese_simplified","chinese_traditional"],"株":["chinese_simplified","chinese_traditional"],"健":["chinese_simplified","chinese_traditional"],"售":["chinese_simplified","chinese_traditional"],"股":["chinese_simplified","chinese_traditional"],"岛":["chinese_simplified"],"甘":["chinese_simplified","chinese_traditional"],"泡":["chinese_simplified","chinese_traditional"],"睡":["chinese_simplified","chinese_traditional"],"童":["chinese_simplified","chinese_traditional"],"铸":["chinese_simplified"],"汤":["chinese_simplified"],"阀":["chinese_simplified"],"休":["chinese_simplified","chinese_traditional"],"汇":["chinese_simplified"],"舍":["chinese_simplified","chinese_traditional"],"牧":["chinese_simplified","chinese_traditional"],"绕":["chinese_simplified"],"炸":["chinese_simplified","chinese_traditional"],"哲":["chinese_simplified","chinese_traditional"],"磷":["chinese_simplified","chinese_traditional"],"绩":["chinese_simplified"],"朋":["chinese_simplified","chinese_traditional"],"淡":["chinese_simplified","chinese_traditional"],"尖":["chinese_simplified","chinese_traditional"],"启":["chinese_simplified"],"陷":["chinese_simplified","chinese_traditional"],"柴":["chinese_simplified","chinese_traditional"],"呈":["chinese_simplified","chinese_traditional"],"徒":["chinese_simplified","chinese_traditional"],"颜":["chinese_simplified"],"泪":["chinese_simplified"],"稍":["chinese_simplified","chinese_traditional"],"忘":["chinese_simplified","chinese_traditional"],"泵":["chinese_simplified","chinese_traditional"],"蓝":["chinese_simplified"],"拖":["chinese_simplified","chinese_traditional"],"洞":["chinese_simplified","chinese_traditional"],"授":["chinese_simplified","chinese_traditional"],"镜":["chinese_simplified"],"辛":["chinese_simplified","chinese_traditional"],"壮":["chinese_simplified"],"锋":["chinese_simplified"],"贫":["chinese_simplified"],"虚":["chinese_simplified"],"弯":["chinese_simplified"],"摩":["chinese_simplified","chinese_traditional"],"泰":["chinese_simplified","chinese_traditional"],"幼":["chinese_simplified","chinese_traditional"],"廷":["chinese_simplified","chinese_traditional"],"尊":["chinese_simplified","chinese_traditional"],"窗":["chinese_simplified","chinese_traditional"],"纲":["chinese_simplified"],"弄":["chinese_simplified","chinese_traditional"],"隶":["chinese_simplified"],"疑":["chinese_simplified","chinese_traditional"],"氏":["chinese_simplified","chinese_traditional"],"宫":["chinese_simplified"],"姐":["chinese_simplified","chinese_traditional"],"震":["chinese_simplified","chinese_traditional"],"瑞":["chinese_simplified","chinese_traditional"],"怪":["chinese_simplified","chinese_traditional"],"尤":["chinese_simplified","chinese_traditional"],"琴":["chinese_simplified","chinese_traditional"],"循":["chinese_simplified","chinese_traditional"],"描":["chinese_simplified","chinese_traditional"],"膜":["chinese_simplified","chinese_traditional"],"违":["chinese_simplified"],"夹":["chinese_simplified"],"腰":["chinese_simplified","chinese_traditional"],"缘":["chinese_simplified"],"珠":["chinese_simplified","chinese_traditional"],"穷":["chinese_simplified"],"森":["chinese_simplified","chinese_traditional"],"枝":["chinese_simplified","chinese_traditional"],"竹":["chinese_simplified","chinese_traditional"],"沟":["chinese_simplified"],"催":["chinese_simplified","chinese_traditional"],"绳":["chinese_simplified"],"忆":["chinese_simplified"],"邦":["chinese_simplified","chinese_traditional"],"剩":["chinese_simplified","chinese_traditional"],"幸":["chinese_simplified","chinese_traditional"],"浆":["chinese_simplified"],"栏":["chinese_simplified"],"拥":["chinese_simplified"],"牙":["chinese_simplified","chinese_traditional"],"贮":["chinese_simplified"],"礼":["chinese_simplified"],"滤":["chinese_simplified"],"钠":["chinese_simplified"],"纹":["chinese_simplified"],"罢":["chinese_simplified"],"拍":["chinese_simplified","chinese_traditional"],"咱":["chinese_simplified","chinese_traditional"],"喊":["chinese_simplified","chinese_traditional"],"袖":["chinese_simplified","chinese_traditional"],"埃":["chinese_simplified","chinese_traditional"],"勤":["chinese_simplified","chinese_traditional"],"罚":["chinese_simplified"],"焦":["chinese_simplified","chinese_traditional"],"潜":["chinese_simplified"],"伍":["chinese_simplified","chinese_traditional"],"墨":["chinese_simplified","chinese_traditional"],"欲":["chinese_simplified","chinese_traditional"],"缝":["chinese_simplified"],"姓":["chinese_simplified","chinese_traditional"],"刊":["chinese_simplified","chinese_traditional"],"饱":["chinese_simplified"],"仿":["chinese_simplified","chinese_traditional"],"奖":["chinese_simplified"],"铝":["chinese_simplified"],"鬼":["chinese_simplified","chinese_traditional"],"丽":["chinese_simplified"],"跨":["chinese_simplified","chinese_traditional"],"默":["chinese_simplified","chinese_traditional"],"挖":["chinese_simplified","chinese_traditional"],"链":["chinese_simplified"],"扫":["chinese_simplified"],"喝":["chinese_simplified","chinese_traditional"],"袋":["chinese_simplified","chinese_traditional"],"炭":["chinese_simplified","chinese_traditional"],"污":["chinese_simplified","chinese_traditional"],"幕":["chinese_simplified","chinese_traditional"],"诸":["chinese_simplified"],"弧":["chinese_simplified","chinese_traditional"],"励":["chinese_simplified"],"梅":["chinese_simplified","chinese_traditional"],"奶":["chinese_simplified","chinese_traditional"],"洁":["chinese_simplified"],"灾":["chinese_simplified"],"舟":["chinese_simplified","chinese_traditional"],"鉴":["chinese_simplified"],"苯":["chinese_simplified","chinese_traditional"],"讼":["chinese_simplified"],"抱":["chinese_simplified","chinese_traditional"],"毁":["chinese_simplified"],"懂":["chinese_simplified","chinese_traditional"],"寒":["chinese_simplified","chinese_traditional"],"智":["chinese_simplified","chinese_traditional"],"埔":["chinese_simplified","chinese_traditional"],"寄":["chinese_simplified","chinese_traditional"],"届":["chinese_simplified"],"跃":["chinese_simplified"],"渡":["chinese_simplified","chinese_traditional"],"挑":["chinese_simplified","chinese_traditional"],"丹":["chinese_simplified","chinese_traditional"],"艰":["chinese_simplified"],"贝":["chinese_simplified"],"碰":["chinese_simplified","chinese_traditional"],"拔":["chinese_simplified","chinese_traditional"],"爹":["chinese_simplified","chinese_traditional"],"戴":["chinese_simplified","chinese_traditional"],"码":["chinese_simplified"],"梦":["chinese_simplified"],"芽":["chinese_simplified","chinese_traditional"],"熔":["chinese_simplified","chinese_traditional"],"赤":["chinese_simplified","chinese_traditional"],"渔":["chinese_simplified"],"哭":["chinese_simplified","chinese_traditional"],"敬":["chinese_simplified","chinese_traditional"],"颗":["chinese_simplified"],"奔":["chinese_simplified","chinese_traditional"],"铅":["chinese_simplified"],"仲":["chinese_simplified","chinese_traditional"],"虎":["chinese_simplified","chinese_traditional"],"稀":["chinese_simplified","chinese_traditional"],"妹":["chinese_simplified","chinese_traditional"],"乏":["chinese_simplified","chinese_traditional"],"珍":["chinese_simplified","chinese_traditional"],"申":["chinese_simplified","chinese_traditional"],"桌":["chinese_simplified","chinese_traditional"],"遵":["chinese_simplified","chinese_traditional"],"允":["chinese_simplified","chinese_traditional"],"隆":["chinese_simplified","chinese_traditional"],"螺":["chinese_simplified","chinese_traditional"],"仓":["chinese_simplified"],"魏":["chinese_simplified","chinese_traditional"],"锐":["chinese_simplified"],"晓":["chinese_simplified"],"氮":["chinese_simplified","chinese_traditional"],"兼":["chinese_simplified","chinese_traditional"],"隐":["chinese_simplified"],"碍":["chinese_simplified"],"赫":["chinese_simplified","chinese_traditional"],"拨":["chinese_simplified"],"忠":["chinese_simplified","chinese_traditional"],"肃":["chinese_simplified"],"缸":["chinese_simplified","chinese_traditional"],"牵":["chinese_simplified"],"抢":["chinese_simplified"],"博":["chinese_simplified","chinese_traditional"],"巧":["chinese_simplified","chinese_traditional"],"壳":["chinese_simplified"],"兄":["chinese_simplified","chinese_traditional"],"杜":["chinese_simplified","chinese_traditional"],"讯":["chinese_simplified"],"诚":["chinese_simplified"],"碧":["chinese_simplified","chinese_traditional"],"祥":["chinese_simplified","chinese_traditional"],"柯":["chinese_simplified","chinese_traditional"],"页":["chinese_simplified"],"巡":["chinese_simplified","chinese_traditional"],"矩":["chinese_simplified","chinese_traditional"],"悲":["chinese_simplified","chinese_traditional"],"灌":["chinese_simplified","chinese_traditional"],"龄":["chinese_simplified"],"伦":["chinese_simplified"],"票":["chinese_simplified","chinese_traditional"],"寻":["chinese_simplified"],"桂":["chinese_simplified","chinese_traditional"],"铺":["chinese_simplified"],"圣":["chinese_simplified"],"恐":["chinese_simplified","chinese_traditional"],"恰":["chinese_simplified","chinese_traditional"],"郑":["chinese_simplified"],"趣":["chinese_simplified","chinese_traditional"],"抬":["chinese_simplified","chinese_traditional"],"荒":["chinese_simplified","chinese_traditional"],"腾":["chinese_simplified"],"贴":["chinese_simplified"],"柔":["chinese_simplified","chinese_traditional"],"滴":["chinese_simplified","chinese_traditional"],"猛":["chinese_simplified","chinese_traditional"],"阔":["chinese_simplified"],"辆":["chinese_simplified"],"妻":["chinese_simplified","chinese_traditional"],"填":["chinese_simplified","chinese_traditional"],"撤":["chinese_simplified","chinese_traditional"],"储":["chinese_simplified"],"签":["chinese_simplified"],"闹":["chinese_simplified"],"扰":["chinese_simplified"],"紫":["chinese_simplified","chinese_traditional"],"砂":["chinese_simplified","chinese_traditional"],"递":["chinese_simplified"],"戏":["chinese_simplified"],"吊":["chinese_simplified","chinese_traditional"],"陶":["chinese_simplified","chinese_traditional"],"伐":["chinese_simplified","chinese_traditional"],"喂":["chinese_simplified"],"疗":["chinese_simplified"],"瓶":["chinese_simplified","chinese_traditional"],"婆":["chinese_simplified","chinese_traditional"],"抚":["chinese_simplified"],"臂":["chinese_simplified","chinese_traditional"],"摸":["chinese_simplified","chinese_traditional"],"忍":["chinese_simplified","chinese_traditional"],"虾":["chinese_simplified"],"蜡":["chinese_simplified"],"邻":["chinese_simplified"],"胸":["chinese_simplified","chinese_traditional"],"巩":["chinese_simplified"],"挤":["chinese_simplified"],"偶":["chinese_simplified","chinese_traditional"],"弃":["chinese_simplified"],"槽":["chinese_simplified","chinese_traditional"],"劲":["chinese_simplified"],"乳":["chinese_simplified","chinese_traditional"],"邓":["chinese_simplified"],"吉":["chinese_simplified","chinese_traditional"],"仁":["chinese_simplified","chinese_traditional"],"烂":["chinese_simplified"],"砖":["chinese_simplified"],"租":["chinese_simplified","chinese_traditional"],"乌":["chinese_simplified"],"舰":["chinese_simplified"],"伴":["chinese_simplified","chinese_traditional"],"瓜":["chinese_simplified","chinese_traditional"],"浅":["chinese_simplified"],"丙":["chinese_simplified","chinese_traditional"],"暂":["chinese_simplified"],"燥":["chinese_simplified","chinese_traditional"],"橡":["chinese_simplified","chinese_traditional"],"柳":["chinese_simplified","chinese_traditional"],"迷":["chinese_simplified","chinese_traditional"],"暖":["chinese_simplified","chinese_traditional"],"牌":["chinese_simplified","chinese_traditional"],"秧":["chinese_simplified","chinese_traditional"],"胆":["chinese_simplified"],"详":["chinese_simplified"],"簧":["chinese_simplified","chinese_traditional"],"踏":["chinese_simplified","chinese_traditional"],"瓷":["chinese_simplified","chinese_traditional"],"谱":["chinese_simplified"],"呆":["chinese_simplified","chinese_traditional"],"宾":["chinese_simplified"],"糊":["chinese_simplified","chinese_traditional"],"洛":["chinese_simplified","chinese_traditional"],"辉":["chinese_simplified"],"愤":["chinese_simplified"],"竞":["chinese_simplified"],"隙":["chinese_simplified","chinese_traditional"],"怒":["chinese_simplified","chinese_traditional"],"粘":["chinese_simplified","chinese_traditional"],"乃":["chinese_simplified","chinese_traditional"],"绪":["chinese_simplified"],"肩":["chinese_simplified","chinese_traditional"],"籍":["chinese_simplified","chinese_traditional"],"敏":["chinese_simplified","chinese_traditional"],"涂":["chinese_simplified"],"熙":["chinese_simplified","chinese_traditional"],"皆":["chinese_simplified","chinese_traditional"],"侦":["chinese_simplified"],"悬":["chinese_simplified"],"掘":["chinese_simplified","chinese_traditional"],"享":["chinese_simplified","chinese_traditional"],"纠":["chinese_simplified"],"醒":["chinese_simplified","chinese_traditional"],"狂":["chinese_simplified","chinese_traditional"],"锁":["chinese_simplified"],"淀":["chinese_simplified","chinese_traditional"],"恨":["chinese_simplified","chinese_traditional"],"牲":["chinese_simplified","chinese_traditional"],"霸":["chinese_simplified","chinese_traditional"],"爬":["chinese_simplified","chinese_traditional"],"赏":["chinese_simplified"],"逆":["chinese_simplified","chinese_traditional"],"玩":["chinese_simplified","chinese_traditional"],"陵":["chinese_simplified","chinese_traditional"],"祝":["chinese_simplified","chinese_traditional"],"秒":["chinese_simplified","chinese_traditional"],"浙":["chinese_simplified","chinese_traditional"],"貌":["chinese_simplified","chinese_traditional"],"役":["chinese_simplified","chinese_traditional"],"彼":["chinese_simplified","chinese_traditional"],"悉":["chinese_simplified","chinese_traditional"],"鸭":["chinese_simplified"],"趋":["chinese_simplified"],"凤":["chinese_simplified"],"晨":["chinese_simplified","chinese_traditional"],"畜":["chinese_simplified","chinese_traditional"],"辈":["chinese_simplified"],"秩":["chinese_simplified","chinese_traditional"],"卵":["chinese_simplified","chinese_traditional"],"署":["chinese_simplified","chinese_traditional"],"梯":["chinese_simplified","chinese_traditional"],"炎":["chinese_simplified","chinese_traditional"],"滩":["chinese_simplified"],"棋":["chinese_simplified","chinese_traditional"],"驱":["chinese_simplified"],"筛":["chinese_simplified"],"峡":["chinese_simplified"],"冒":["chinese_simplified","chinese_traditional"],"啥":["chinese_simplified","chinese_traditional"],"寿":["chinese_simplified"],"译":["chinese_simplified"],"浸":["chinese_simplified","chinese_traditional"],"泉":["chinese_simplified","chinese_traditional"],"帽":["chinese_simplified","chinese_traditional"],"迟":["chinese_simplified"],"硅":["chinese_simplified"],"疆":["chinese_simplified","chinese_traditional"],"贷":["chinese_simplified"],"漏":["chinese_simplified","chinese_traditional"],"稿":["chinese_simplified","chinese_traditional"],"冠":["chinese_simplified","chinese_traditional"],"嫩":["chinese_simplified","chinese_traditional"],"胁":["chinese_simplified"],"芯":["chinese_simplified","chinese_traditional"],"牢":["chinese_simplified","chinese_traditional"],"叛":["chinese_simplified","chinese_traditional"],"蚀":["chinese_simplified"],"奥":["chinese_simplified"],"鸣":["chinese_simplified"],"岭":["chinese_simplified"],"羊":["chinese_simplified","chinese_traditional"],"凭":["chinese_simplified"],"串":["chinese_simplified","chinese_traditional"],"塘":["chinese_simplified","chinese_traditional"],"绘":["chinese_simplified"],"酵":["chinese_simplified","chinese_traditional"],"融":["chinese_simplified","chinese_traditional"],"盆":["chinese_simplified","chinese_traditional"],"锡":["chinese_simplified"],"庙":["chinese_simplified"],"筹":["chinese_simplified"],"冻":["chinese_simplified"],"辅":["chinese_simplified"],"摄":["chinese_simplified"],"袭":["chinese_simplified"],"筋":["chinese_simplified","chinese_traditional"],"拒":["chinese_simplified","chinese_traditional"],"僚":["chinese_simplified","chinese_traditional"],"旱":["chinese_simplified","chinese_traditional"],"钾":["chinese_simplified"],"鸟":["chinese_simplified"],"漆":["chinese_simplified","chinese_traditional"],"沈":["chinese_simplified","chinese_traditional"],"眉":["chinese_simplified","chinese_traditional"],"疏":["chinese_simplified","chinese_traditional"],"添":["chinese_simplified","chinese_traditional"],"棒":["chinese_simplified","chinese_traditional"],"穗":["chinese_simplified","chinese_traditional"],"硝":["chinese_simplified","chinese_traditional"],"韩":["chinese_simplified"],"逼":["chinese_simplified","chinese_traditional"],"扭":["chinese_simplified","chinese_traditional"],"侨":["chinese_simplified"],"凉":["chinese_simplified"],"挺":["chinese_simplified","chinese_traditional"],"碗":["chinese_simplified","chinese_traditional"],"栽":["chinese_simplified","chinese_traditional"],"炒":["chinese_simplified","chinese_traditional"],"杯":["chinese_simplified","chinese_traditional"],"患":["chinese_simplified","chinese_traditional"],"馏":["chinese_simplified"],"劝":["chinese_simplified"],"豪":["chinese_simplified","chinese_traditional"],"辽":["chinese_simplified"],"勃":["chinese_simplified","chinese_traditional"],"鸿":["chinese_simplified"],"旦":["chinese_simplified","chinese_traditional"],"吏":["chinese_simplified","chinese_traditional"],"拜":["chinese_simplified","chinese_traditional"],"狗":["chinese_simplified","chinese_traditional"],"埋":["chinese_simplified","chinese_traditional"],"辊":["chinese_simplified"],"掩":["chinese_simplified","chinese_traditional"],"饮":["chinese_simplified"],"搬":["chinese_simplified","chinese_traditional"],"骂":["chinese_simplified"],"辞":["chinese_simplified"],"勾":["chinese_simplified","chinese_traditional"],"扣":["chinese_simplified","chinese_traditional"],"估":["chinese_simplified","chinese_traditional"],"蒋":["chinese_simplified"],"绒":["chinese_simplified"],"雾":["chinese_simplified"],"丈":["chinese_simplified","chinese_traditional"],"朵":["chinese_simplified","chinese_traditional"],"姆":["chinese_simplified","chinese_traditional"],"拟":["chinese_simplified"],"宇":["chinese_simplified","chinese_traditional"],"辑":["chinese_simplified"],"陕":["chinese_simplified"],"雕":["chinese_simplified","chinese_traditional"],"偿":["chinese_simplified"],"蓄":["chinese_simplified","chinese_traditional"],"崇":["chinese_simplified","chinese_traditional"],"剪":["chinese_simplified","chinese_traditional"],"倡":["chinese_simplified","chinese_traditional"],"厅":["chinese_simplified"],"咬":["chinese_simplified","chinese_traditional"],"驶":["chinese_simplified"],"薯":["chinese_simplified","chinese_traditional"],"刷":["chinese_simplified","chinese_traditional"],"斥":["chinese_simplified","chinese_traditional"],"番":["chinese_simplified","chinese_traditional"],"赋":["chinese_simplified"],"奉":["chinese_simplified","chinese_traditional"],"佛":["chinese_simplified","chinese_traditional"],"浇":["chinese_simplified"],"漫":["chinese_simplified","chinese_traditional"],"曼":["chinese_simplified","chinese_traditional"],"扇":["chinese_simplified","chinese_traditional"],"钙":["chinese_simplified"],"桃":["chinese_simplified","chinese_traditional"],"扶":["chinese_simplified","chinese_traditional"],"仔":["chinese_simplified","chinese_traditional"],"返":["chinese_simplified","chinese_traditional"],"俗":["chinese_simplified","chinese_traditional"],"亏":["chinese_simplified"],"腔":["chinese_simplified","chinese_traditional"],"鞋":["chinese_simplified","chinese_traditional"],"棱":["chinese_simplified","chinese_traditional"],"覆":["chinese_simplified","chinese_traditional"],"框":["chinese_simplified","chinese_traditional"],"悄":["chinese_simplified","chinese_traditional"],"叔":["chinese_simplified","chinese_traditional"],"撞":["chinese_simplified","chinese_traditional"],"骗":["chinese_simplified"],"勘":["chinese_simplified","chinese_traditional"],"旺":["chinese_simplified","chinese_traditional"],"沸":["chinese_simplified","chinese_traditional"],"孤":["chinese_simplified","chinese_traditional"],"吐":["chinese_simplified","chinese_traditional"],"孟":["chinese_simplified","chinese_traditional"],"渠":["chinese_simplified","chinese_traditional"],"屈":["chinese_simplified","chinese_traditional"],"疾":["chinese_simplified","chinese_traditional"],"妙":["chinese_simplified","chinese_traditional"],"惜":["chinese_simplified","chinese_traditional"],"仰":["chinese_simplified","chinese_traditional"],"狠":["chinese_simplified","chinese_traditional"],"胀":["chinese_simplified"],"谐":["chinese_simplified"],"抛":["chinese_simplified"],"霉":["chinese_simplified"],"桑":["chinese_simplified","chinese_traditional"],"岗":["chinese_simplified"],"嘛":["chinese_simplified","chinese_traditional"],"衰":["chinese_simplified","chinese_traditional"],"盗":["chinese_simplified"],"渗":["chinese_simplified"],"脏":["chinese_simplified"],"赖":["chinese_simplified"],"涌":["chinese_simplified"],"甜":["chinese_simplified","chinese_traditional"],"曹":["chinese_simplified","chinese_traditional"],"阅":["chinese_simplified"],"肌":["chinese_simplified","chinese_traditional"],"哩":["chinese_simplified","chinese_traditional"],"厉":["chinese_simplified"],"烃":["chinese_simplified"],"纬":["chinese_simplified"],"毅":["chinese_simplified","chinese_traditional"],"昨":["chinese_simplified","chinese_traditional"],"伪":["chinese_simplified"],"症":["chinese_simplified","chinese_traditional"],"煮":["chinese_simplified","chinese_traditional"],"叹":["chinese_simplified"],"钉":["chinese_simplified"],"搭":["chinese_simplified","chinese_traditional"],"茎":["chinese_simplified"],"笼":["chinese_simplified"],"酷":["chinese_simplified","chinese_traditional"],"偷":["chinese_simplified","chinese_traditional"],"弓":["chinese_simplified","chinese_traditional"],"锥":["chinese_simplified"],"恒":["chinese_simplified"],"杰":["chinese_simplified"],"坑":["chinese_simplified","chinese_traditional"],"鼻":["chinese_simplified","chinese_traditional"],"翼":["chinese_simplified","chinese_traditional"],"纶":["chinese_simplified"],"叙":["chinese_simplified"],"狱":["chinese_simplified"],"逮":["chinese_simplified","chinese_traditional"],"罐":["chinese_simplified","chinese_traditional"],"络":["chinese_simplified"],"棚":["chinese_simplified","chinese_traditional"],"抑":["chinese_simplified","chinese_traditional"],"膨":["chinese_simplified","chinese_traditional"],"蔬":["chinese_simplified","chinese_traditional"],"寺":["chinese_simplified","chinese_traditional"],"骤":["chinese_simplified"],"穆":["chinese_simplified","chinese_traditional"],"冶":["chinese_simplified","chinese_traditional"],"枯":["chinese_simplified","chinese_traditional"],"册":["chinese_simplified"],"尸":["chinese_simplified"],"凸":["chinese_simplified","chinese_traditional"],"绅":["chinese_simplified"],"坯":["chinese_simplified","chinese_traditional"],"牺":["chinese_simplified"],"焰":["chinese_simplified","chinese_traditional"],"轰":["chinese_simplified"],"欣":["chinese_simplified","chinese_traditional"],"晋":["chinese_simplified"],"瘦":["chinese_simplified","chinese_traditional"],"御":["chinese_simplified"],"锭":["chinese_simplified"],"锦":["chinese_simplified"],"丧":["chinese_simplified"],"旬":["chinese_simplified","chinese_traditional"],"锻":["chinese_simplified"],"垄":["chinese_simplified"],"搜":["chinese_simplified","chinese_traditional"],"扑":["chinese_simplified"],"邀":["chinese_simplified","chinese_traditional"],"亭":["chinese_simplified","chinese_traditional"],"酯":["chinese_simplified","chinese_traditional"],"迈":["chinese_simplified"],"舒":["chinese_simplified","chinese_traditional"],"脆":["chinese_simplified","chinese_traditional"],"酶":["chinese_simplified","chinese_traditional"],"闲":["chinese_simplified"],"忧":["chinese_simplified"],"酚":["chinese_simplified","chinese_traditional"],"顽":["chinese_simplified"],"羽":["chinese_simplified","chinese_traditional"],"涨":["chinese_simplified"],"卸":["chinese_simplified","chinese_traditional"],"仗":["chinese_simplified","chinese_traditional"],"陪":["chinese_simplified","chinese_traditional"],"辟":["chinese_simplified"],"惩":["chinese_simplified"],"杭":["chinese_simplified","chinese_traditional"],"姚":["chinese_simplified","chinese_traditional"],"肚":["chinese_simplified","chinese_traditional"],"捉":["chinese_simplified","chinese_traditional"],"飘":["chinese_simplified"],"漂":["chinese_simplified","chinese_traditional"],"昆":["chinese_simplified","chinese_traditional"],"欺":["chinese_simplified","chinese_traditional"],"吾":["chinese_simplified","chinese_traditional"],"郎":["chinese_simplified","chinese_traditional"],"烷":["chinese_simplified","chinese_traditional"],"汁":["chinese_simplified","chinese_traditional"],"呵":["chinese_simplified","chinese_traditional"],"饰":["chinese_simplified"],"萧":["chinese_simplified"],"雅":["chinese_simplified","chinese_traditional"],"邮":["chinese_simplified"],"迁":["chinese_simplified"],"燕":["chinese_simplified","chinese_traditional"],"撒":["chinese_simplified","chinese_traditional"],"姻":["chinese_simplified","chinese_traditional"],"赴":["chinese_simplified","chinese_traditional"],"宴":["chinese_simplified","chinese_traditional"],"烦":["chinese_simplified"],"债":["chinese_simplified"],"帐":["chinese_simplified"],"斑":["chinese_simplified","chinese_traditional"],"铃":["chinese_simplified"],"旨":["chinese_simplified","chinese_traditional"],"醇":["chinese_simplified","chinese_traditional"],"董":["chinese_simplified","chinese_traditional"],"饼":["chinese_simplified"],"雏":["chinese_simplified"],"姿":["chinese_simplified","chinese_traditional"],"拌":["chinese_simplified","chinese_traditional"],"傅":["chinese_simplified","chinese_traditional"],"腹":["chinese_simplified","chinese_traditional"],"妥":["chinese_simplified","chinese_traditional"],"揉":["chinese_simplified","chinese_traditional"],"贤":["chinese_simplified"],"拆":["chinese_simplified","chinese_traditional"],"歪":["chinese_simplified","chinese_traditional"],"葡":["chinese_simplified","chinese_traditional"],"胺":["chinese_simplified","chinese_traditional"],"丢":["chinese_simplified"],"浩":["chinese_simplified","chinese_traditional"],"徽":["chinese_simplified","chinese_traditional"],"昂":["chinese_simplified","chinese_traditional"],"垫":["chinese_simplified"],"挡":["chinese_simplified"],"览":["chinese_simplified"],"贪":["chinese_simplified"],"慰":["chinese_simplified","chinese_traditional"],"缴":["chinese_simplified"],"汪":["chinese_simplified","chinese_traditional"],"慌":["chinese_simplified","chinese_traditional"],"冯":["chinese_simplified"],"诺":["chinese_simplified"],"姜":["chinese_simplified","chinese_traditional"],"谊":["chinese_simplified"],"凶":["chinese_simplified"],"劣":["chinese_simplified","chinese_traditional"],"诬":["chinese_simplified"],"耀":["chinese_simplified","chinese_traditional"],"昏":["chinese_simplified","chinese_traditional"],"躺":["chinese_simplified","chinese_traditional"],"盈":["chinese_simplified","chinese_traditional"],"骑":["chinese_simplified"],"乔":["chinese_simplified"],"溪":["chinese_simplified","chinese_traditional"],"丛":["chinese_simplified"],"卢":["chinese_simplified"],"抹":["chinese_simplified","chinese_traditional"],"闷":["chinese_simplified"],"咨":["chinese_simplified"],"刮":["chinese_simplified","chinese_traditional"],"驾":["chinese_simplified"],"缆":["chinese_simplified"],"悟":["chinese_simplified","chinese_traditional"],"摘":["chinese_simplified","chinese_traditional"],"铒":["chinese_simplified"],"掷":["chinese_simplified"],"颇":["chinese_simplified"],"幻":["chinese_simplified","chinese_traditional"],"柄":["chinese_simplified","chinese_traditional"],"惠":["chinese_simplified","chinese_traditional"],"惨":["chinese_simplified"],"佳":["chinese_simplified","chinese_traditional"],"仇":["chinese_simplified","chinese_traditional"],"腊":["chinese_simplified"],"窝":["chinese_simplified"],"涤":["chinese_simplified"],"剑":["chinese_simplified"],"瞧":["chinese_simplified","chinese_traditional"],"堡":["chinese_simplified","chinese_traditional"],"泼":["chinese_simplified"],"葱":["chinese_simplified"],"罩":["chinese_simplified","chinese_traditional"],"霍":["chinese_simplified","chinese_traditional"],"捞":["chinese_simplified"],"胎":["chinese_simplified","chinese_traditional"],"苍":["chinese_simplified"],"滨":["chinese_simplified"],"俩":["chinese_simplified"],"捅":["chinese_simplified","chinese_traditional"],"湘":["chinese_simplified","chinese_traditional"],"砍":["chinese_simplified","chinese_traditional"],"霞":["chinese_simplified","chinese_traditional"],"邵":["chinese_simplified","chinese_traditional"],"萄":["chinese_simplified","chinese_traditional"],"疯":["chinese_simplified"],"淮":["chinese_simplified","chinese_traditional"],"遂":["chinese_simplified","chinese_traditional"],"熊":["chinese_simplified","chinese_traditional"],"粪":["chinese_simplified"],"烘":["chinese_simplified","chinese_traditional"],"宿":["chinese_simplified","chinese_traditional"],"档":["chinese_simplified"],"戈":["chinese_simplified","chinese_traditional"],"驳":["chinese_simplified"],"嫂":["chinese_simplified","chinese_traditional"],"裕":["chinese_simplified","chinese_traditional"],"徙":["chinese_simplified","chinese_traditional"],"箭":["chinese_simplified","chinese_traditional"],"捐":["chinese_simplified","chinese_traditional"],"肠":["chinese_simplified"],"撑":["chinese_simplified"],"晒":["chinese_simplified"],"辨":["chinese_simplified","chinese_traditional"],"殿":["chinese_simplified","chinese_traditional"],"莲":["chinese_simplified"],"摊":["chinese_simplified"],"搅":["chinese_simplified"],"酱":["chinese_simplified"],"屏":["chinese_simplified","chinese_traditional"],"疫":["chinese_simplified","chinese_traditional"],"哀":["chinese_simplified","chinese_traditional"],"蔡":["chinese_simplified","chinese_traditional"],"堵":["chinese_simplified","chinese_traditional"],"沫":["chinese_simplified","chinese_traditional"],"皱":["chinese_simplified"],"畅":["chinese_simplified"],"叠":["chinese_simplified"],"阁":["chinese_simplified"],"莱":["chinese_simplified"],"敲":["chinese_simplified","chinese_traditional"],"辖":["chinese_simplified"],"钩":["chinese_simplified"],"痕":["chinese_simplified","chinese_traditional"],"坝":["chinese_simplified"],"巷":["chinese_simplified","chinese_traditional"],"饿":["chinese_simplified"],"祸":["chinese_simplified"],"丘":["chinese_simplified","chinese_traditional"],"玄":["chinese_simplified","chinese_traditional"],"溜":["chinese_simplified","chinese_traditional"],"曰":["chinese_simplified","chinese_traditional"],"逻":["chinese_simplified"],"彭":["chinese_simplified","chinese_traditional"],"尝":["chinese_simplified"],"卿":["chinese_simplified","chinese_traditional"],"妨":["chinese_simplified","chinese_traditional"],"艇":["chinese_simplified","chinese_traditional"],"吞":["chinese_simplified","chinese_traditional"],"韦":["chinese_simplified"],"怨":["chinese_simplified","chinese_traditional"],"矮":["chinese_simplified","chinese_traditional"],"歇":["chinese_simplified","chinese_traditional"],"這":["chinese_traditional"],"為":["chinese_traditional"],"個":["chinese_traditional"],"國":["chinese_traditional"],"時":["chinese_traditional"],"來":["chinese_traditional"],"們":["chinese_traditional"],"於":["chinese_traditional"],"對":["chinese_traditional"],"會":["chinese_traditional"],"發":["chinese_traditional"],"動":["chinese_traditional"],"過":["chinese_traditional"],"說":["chinese_traditional"],"產":["chinese_traditional"],"種":["chinese_traditional"],"後":["chinese_traditional"],"學":["chinese_traditional"],"經":["chinese_traditional"],"進":["chinese_traditional"],"著":["chinese_traditional"],"電":["chinese_traditional"],"裡":["chinese_traditional"],"現":["chinese_traditional"],"實":["chinese_traditional"],"兩":["chinese_traditional"],"體":["chinese_traditional"],"機":["chinese_traditional"],"當":["chinese_traditional"],"點":["chinese_traditional"],"從":["chinese_traditional"],"業":["chinese_traditional"],"應":["chinese_traditional"],"開":["chinese_traditional"],"還":["chinese_traditional"],"義":["chinese_traditional"],"間":["chinese_traditional"],"樣":["chinese_traditional"],"與":["chinese_traditional"],"關":["chinese_traditional"],"線":["chinese_traditional"],"內":["chinese_traditional"],"數":["chinese_traditional"],"麼":["chinese_traditional"],"質":["chinese_traditional"],"氣":["chinese_traditional"],"變":["chinese_traditional"],"條":["chinese_traditional"],"沒":["chinese_traditional"],"結":["chinese_traditional"],"問":["chinese_traditional"],"無":["chinese_traditional"],"軍":["chinese_traditional"],"並":["chinese_traditional"],"題":["chinese_traditional"],"黨":["chinese_traditional"],"員":["chinese_traditional"],"總":["chinese_traditional"],"設":["chinese_traditional"],"長":["chinese_traditional"],"頭":["chinese_traditional"],"資":["chinese_traditional"],"邊":["chinese_traditional"],"級":["chinese_traditional"],"圖":["chinese_traditional"],"統":["chinese_traditional"],"較":["chinese_traditional"],"將":["chinese_traditional"],"組":["chinese_traditional"],"見":["chinese_traditional"],"計":["chinese_traditional"],"別":["chinese_traditional"],"論":["chinese_traditional"],"運":["chinese_traditional"],"農":["chinese_traditional"],"幾":["chinese_traditional"],"區":["chinese_traditional"],"強":["chinese_traditional"],"決":["chinese_traditional"],"幹":["chinese_traditional"],"戰":["chinese_traditional"],"則":["chinese_traditional"],"據":["chinese_traditional"],"處":["chinese_traditional"],"隊":["chinese_traditional"],"給":["chinese_traditional"],"門":["chinese_traditional"],"規":["chinese_traditional"],"熱":["chinese_traditional"],"領":["chinese_traditional"],"東":["chinese_traditional"],"導":["chinese_traditional"],"壓":["chinese_traditional"],"爭":["chinese_traditional"],"濟":["chinese_traditional"],"階":["chinese_traditional"],"術":["chinese_traditional"],"極":["chinese_traditional"],"聯":["chinese_traditional"],"認":["chinese_traditional"],"權":["chinese_traditional"],"證":["chinese_traditional"],"採":["chinese_traditional"],"轉":["chinese_traditional"],"單":["chinese_traditional"],"風":["chinese_traditional"],"帶":["chinese_traditional"],"場":["chinese_traditional"],"車":["chinese_traditional"],"務":["chinese_traditional"],"萬":["chinese_traditional"],"達":["chinese_traditional"],"積":["chinese_traditional"],"議":["chinese_traditional"],"聲":["chinese_traditional"],"報":["chinese_traditional"],"鬥":["chinese_traditional"],"類":["chinese_traditional"],"離":["chinese_traditional"],"華":["chinese_traditional"],"確":["chinese_traditional"],"張":["chinese_traditional"],"馬":["chinese_traditional"],"節":["chinese_traditional"],"話":["chinese_traditional"],"況":["chinese_traditional"],"溫":["chinese_traditional"],"傳":["chinese_traditional"],"許":["chinese_traditional"],"廣":["chinese_traditional"],"記":["chinese_traditional"],"觀":["chinese_traditional"],"織":["chinese_traditional"],"裝":["chinese_traditional"],"眾":["chinese_traditional"],"書":["chinese_traditional"],"兒":["chinese_traditional"],"須":["chinese_traditional"],"際":["chinese_traditional"],"驗":["chinese_traditional"],"連":["chinese_traditional"],"斷":["chinese_traditional"],"難":["chinese_traditional"],"礦":["chinese_traditional"],"週":["chinese_traditional"],"備":["chinese_traditional"],"辦":["chinese_traditional"],"習":["chinese_traditional"],"響":["chinese_traditional"],"約":["chinese_traditional"],"勞":["chinese_traditional"],"團":["chinese_traditional"],"歷":["chinese_traditional"],"構":["chinese_traditional"],"稱":["chinese_traditional"],"準":["chinese_traditional"],"號":["chinese_traditional"],"維":["chinese_traditional"],"劃":["chinese_traditional"],"選":["chinese_traditional"],"標":["chinese_traditional"],"寫":["chinese_traditional"],"親":["chinese_traditional"],"養":["chinese_traditional"],"層":["chinese_traditional"],"卻":["chinese_traditional"],"專":["chinese_traditional"],"狀":["chinese_traditional"],"廠":["chinese_traditional"],"識":["chinese_traditional"],"適":["chinese_traditional"],"屬":["chinese_traditional"],"圓":["chinese_traditional"],"調":["chinese_traditional"],"滿":["chinese_traditional"],"縣":["chinese_traditional"],"參":["chinese_traditional"],"紅":["chinese_traditional"],"細":["chinese_traditional"],"聽":["chinese_traditional"],"該":["chinese_traditional"],"鐵":["chinese_traditional"],"價":["chinese_traditional"],"嚴":["chinese_traditional"],"隨":["chinese_traditional"],"蘇":["chinese_traditional"],"爾":["chinese_traditional"],"講":["chinese_traditional"],"黃":["chinese_traditional"],"顯":["chinese_traditional"],"談":["chinese_traditional"],"藝":["chinese_traditional"],"營":["chinese_traditional"],"項":["chinese_traditional"],"舉":["chinese_traditional"],"勢":["chinese_traditional"],"幫":["chinese_traditional"],"輪":["chinese_traditional"],"亞":["chinese_traditional"],"師":["chinese_traditional"],"圍":["chinese_traditional"],"遠":["chinese_traditional"],"態":["chinese_traditional"],"減":["chinese_traditional"],"樹":["chinese_traditional"],"葉":["chinese_traditional"],"魚":["chinese_traditional"],"視":["chinese_traditional"],"僅":["chinese_traditional"],"費":["chinese_traditional"],"緊":["chinese_traditional"],"愛":["chinese_traditional"],"續":["chinese_traditional"],"輕":["chinese_traditional"],"試":["chinese_traditional"],"護":["chinese_traditional"],"練":["chinese_traditional"],"負":["chinese_traditional"],"擊":["chinese_traditional"],"繼":["chinese_traditional"],"興":["chinese_traditional"],"餘":["chinese_traditional"],"堅":["chinese_traditional"],"輸":["chinese_traditional"],"夠":["chinese_traditional"],"筆":["chinese_traditional"],"佔":["chinese_traditional"],"財":["chinese_traditional"],"職":["chinese_traditional"],"覺":["chinese_traditional"],"漢":["chinese_traditional"],"畫":["chinese_traditional"],"雖":["chinese_traditional"],"雜":["chinese_traditional"],"飛":["chinese_traditional"],"檢":["chinese_traditional"],"昇":["chinese_traditional"],"陽":["chinese_traditional"],"創":["chinese_traditional"],"壞":["chinese_traditional"],"徑":["chinese_traditional"],"換":["chinese_traditional"],"鋼":["chinese_traditional"],"責":["chinese_traditional"],"簡":["chinese_traditional"],"錢":["chinese_traditional"],"盡":["chinese_traditional"],"衝":["chinese_traditional"],"獨":["chinese_traditional"],"環":["chinese_traditional"],"雙":["chinese_traditional"],"請":["chinese_traditional"],"讓":["chinese_traditional"],"軸":["chinese_traditional"],"紀":["chinese_traditional"],"優":["chinese_traditional"],"頂":["chinese_traditional"],"礎":["chinese_traditional"],"載":["chinese_traditional"],"敵":["chinese_traditional"],"勝":["chinese_traditional"],"絕":["chinese_traditional"],"塊":["chinese_traditional"],"劑":["chinese_traditional"],"測":["chinese_traditional"],"絲":["chinese_traditional"],"協":["chinese_traditional"],"訴":["chinese_traditional"],"陳":["chinese_traditional"],"羅":["chinese_traditional"],"鹽":["chinese_traditional"],"錯":["chinese_traditional"],"頻":["chinese_traditional"],"終":["chinese_traditional"],"雲":["chinese_traditional"],"衛":["chinese_traditional"],"燒":["chinese_traditional"],"遊":["chinese_traditional"],"舊":["chinese_traditional"],"貨":["chinese_traditional"],"損":["chinese_traditional"],"預":["chinese_traditional"],"穩":["chinese_traditional"],"媽":["chinese_traditional"],"擴":["chinese_traditional"],"銀":["chinese_traditional"],"語":["chinese_traditional"],"揮":["chinese_traditional"],"紙":["chinese_traditional"],"醫":["chinese_traditional"],"嗎":["chinese_traditional"],"針":["chinese_traditional"],"劉":["chinese_traditional"],"誤":["chinese_traditional"],"訓":["chinese_traditional"],"願":["chinese_traditional"],"審":["chinese_traditional"],"獲":["chinese_traditional"],"鮮":["chinese_traditional"],"糧":["chinese_traditional"],"脫":["chinese_traditional"],"龍":["chinese_traditional"],"漸":["chinese_traditional"],"歡":["chinese_traditional"],"剛":["chinese_traditional"],"謂":["chinese_traditional"],"討":["chinese_traditional"],"亂":["chinese_traditional"],"殺":["chinese_traditional"],"藥":["chinese_traditional"],"寧":["chinese_traditional"],"魯":["chinese_traditional"],"貴":["chinese_traditional"],"鐘":["chinese_traditional"],"讀":["chinese_traditional"],"豐":["chinese_traditional"],"蘭":["chinese_traditional"],"擔":["chinese_traditional"],"執":["chinese_traditional"],"樂":["chinese_traditional"],"誰":["chinese_traditional"],"順":["chinese_traditional"],"煙":["chinese_traditional"],"縮":["chinese_traditional"],"徵":["chinese_traditional"],"臉":["chinese_traditional"],"腳":["chinese_traditional"],"異":["chinese_traditional"],"買":["chinese_traditional"],"靜":["chinese_traditional"],"補":["chinese_traditional"],"評":["chinese_traditional"],"踐":["chinese_traditional"],"寬":["chinese_traditional"],"揚":["chinese_traditional"],"傷":["chinese_traditional"],"氫":["chinese_traditional"],"憲":["chinese_traditional"],"慶":["chinese_traditional"],"編":["chinese_traditional"],"觸":["chinese_traditional"],"銷":["chinese_traditional"],"詩":["chinese_traditional"],"綠":["chinese_traditional"],"雞":["chinese_traditional"],"孫":["chinese_traditional"],"膠":["chinese_traditional"],"鄉":["chinese_traditional"],"臨":["chinese_traditional"],"陸":["chinese_traditional"],"顧":["chinese_traditional"],"燈":["chinese_traditional"],"歲":["chinese_traditional"],"劇":["chinese_traditional"],"趙":["chinese_traditional"],"課":["chinese_traditional"],"凱":["chinese_traditional"],"額":["chinese_traditional"],"紹":["chinese_traditional"],"齊":["chinese_traditional"],"偉":["chinese_traditional"],"爐":["chinese_traditional"],"楊":["chinese_traditional"],"桿":["chinese_traditional"],"鎮":["chinese_traditional"],"飯":["chinese_traditional"],"濃":["chinese_traditional"],"懷":["chinese_traditional"],"趕":["chinese_traditional"],"庫":["chinese_traditional"],"奪":["chinese_traditional"],"靈":["chinese_traditional"],"稅":["chinese_traditional"],"滅":["chinese_traditional"],"賽":["chinese_traditional"],"歸":["chinese_traditional"],"盤":["chinese_traditional"],"險":["chinese_traditional"],"錄":["chinese_traditional"],"純":["chinese_traditional"],"蓋":["chinese_traditional"],"橫":["chinese_traditional"],"槍":["chinese_traditional"],"潤":["chinese_traditional"],"蟲":["chinese_traditional"],"澤":["chinese_traditional"],"腦":["chinese_traditional"],"歐":["chinese_traditional"],"側":["chinese_traditional"],"徹":["chinese_traditional"],"慮":["chinese_traditional"],"納":["chinese_traditional"],"彈":["chinese_traditional"],"飼":["chinese_traditional"],"麥":["chinese_traditional"],"濕":["chinese_traditional"],"築":["chinese_traditional"],"惡":["chinese_traditional"],"戶":["chinese_traditional"],"訪":["chinese_traditional"],"跡":["chinese_traditional"],"擺":["chinese_traditional"],"賣":["chinese_traditional"],"擇":["chinese_traditional"],"銅":["chinese_traditional"],"獻":["chinese_traditional"],"陣":["chinese_traditional"],"陰":["chinese_traditional"],"樓":["chinese_traditional"],"謀":["chinese_traditional"],"噸":["chinese_traditional"],"豬":["chinese_traditional"],"館":["chinese_traditional"],"爺":["chinese_traditional"],"驚":["chinese_traditional"],"遺":["chinese_traditional"],"纖":["chinese_traditional"],"傾":["chinese_traditional"],"謝":["chinese_traditional"],"奮":["chinese_traditional"],"購":["chinese_traditional"],"監":["chinese_traditional"],"貫":["chinese_traditional"],"釋":["chinese_traditional"],"詞":["chinese_traditional"],"頓":["chinese_traditional"],"寶":["chinese_traditional"],"塵":["chinese_traditional"],"聞":["chinese_traditional"],"殘":["chinese_traditional"],"橋":["chinese_traditional"],"婦":["chinese_traditional"],"綜":["chinese_traditional"],"吳":["chinese_traditional"],"搖":["chinese_traditional"],"贊":["chinese_traditional"],"訂":["chinese_traditional"],"園":["chinese_traditional"],"紛":["chinese_traditional"],"敗":["chinese_traditional"],"榮":["chinese_traditional"],"閉":["chinese_traditional"],"灣":["chinese_traditional"],"鍵":["chinese_traditional"],"駐":["chinese_traditional"],"鍋":["chinese_traditional"],"剝":["chinese_traditional"],"鹼":["chinese_traditional"],"齒":["chinese_traditional"],"煉":["chinese_traditional"],"紡":["chinese_traditional"],"廢":["chinese_traditional"],"緩":["chinese_traditional"],"淨":["chinese_traditional"],"莊":["chinese_traditional"],"貿":["chinese_traditional"],"慣":["chinese_traditional"],"夥":["chinese_traditional"],"勻":["chinese_traditional"],"紗":["chinese_traditional"],"辯":["chinese_traditional"],"億":["chinese_traditional"],"脈":["chinese_traditional"],"薩":["chinese_traditional"],"網":["chinese_traditional"],"噴":["chinese_traditional"],"縱":["chinese_traditional"],"掛":["chinese_traditional"],"賀":["chinese_traditional"],"閃":["chinese_traditional"],"牆":["chinese_traditional"],"軟":["chinese_traditional"],"滾":["chinese_traditional"],"盪":["chinese_traditional"],"儀":["chinese_traditional"],"軋":["chinese_traditional"],"貢":["chinese_traditional"],"鑽":["chinese_traditional"],"幣":["chinese_traditional"],"軌":["chinese_traditional"],"畝":["chinese_traditional"],"畢":["chinese_traditional"],"島":["chinese_traditional"],"鑄":["chinese_traditional"],"湯":["chinese_traditional"],"閥":["chinese_traditional"],"匯":["chinese_traditional"],"繞":["chinese_traditional"],"績":["chinese_traditional"],"啟":["chinese_traditional"],"顏":["chinese_traditional"],"淚":["chinese_traditional"],"藍":["chinese_traditional"],"鏡":["chinese_traditional"],"壯":["chinese_traditional"],"鋒":["chinese_traditional"],"貧":["chinese_traditional"],"虛":["chinese_traditional"],"彎":["chinese_traditional"],"綱":["chinese_traditional"],"隸":["chinese_traditional"],"宮":["chinese_traditional"],"違":["chinese_traditional"],"夾":["chinese_traditional"],"緣":["chinese_traditional"],"窮":["chinese_traditional"],"溝":["chinese_traditional"],"繩":["chinese_traditional"],"憶":["chinese_traditional"],"漿":["chinese_traditional"],"欄":["chinese_traditional"],"擁":["chinese_traditional"],"貯":["chinese_traditional"],"禮":["chinese_traditional"],"濾":["chinese_traditional"],"鈉":["chinese_traditional"],"紋":["chinese_traditional"],"罷":["chinese_traditional"],"罰":["chinese_traditional"],"潛":["chinese_traditional"],"縫":["chinese_traditional"],"飽":["chinese_traditional"],"獎":["chinese_traditional"],"鋁":["chinese_traditional"],"麗":["chinese_traditional"],"鏈":["chinese_traditional"],"掃":["chinese_traditional"],"諸":["chinese_traditional"],"勵":["chinese_traditional"],"潔":["chinese_traditional"],"災":["chinese_traditional"],"鑑":["chinese_traditional"],"訟":["chinese_traditional"],"毀":["chinese_traditional"],"屆":["chinese_traditional"],"躍":["chinese_traditional"],"艱":["chinese_traditional"],"貝":["chinese_traditional"],"碼":["chinese_traditional"],"夢":["chinese_traditional"],"漁":["chinese_traditional"],"顆":["chinese_traditional"],"鉛":["chinese_traditional"],"倉":["chinese_traditional"],"銳":["chinese_traditional"],"曉":["chinese_traditional"],"隱":["chinese_traditional"],"礙":["chinese_traditional"],"撥":["chinese_traditional"],"肅":["chinese_traditional"],"牽":["chinese_traditional"],"搶":["chinese_traditional"],"殼":["chinese_traditional"],"訊":["chinese_traditional"],"誠":["chinese_traditional"],"頁":["chinese_traditional"],"齡":["chinese_traditional"],"倫":["chinese_traditional"],"尋":["chinese_traditional"],"鋪":["chinese_traditional"],"聖":["chinese_traditional"],"鄭":["chinese_traditional"],"騰":["chinese_traditional"],"貼":["chinese_traditional"],"闊":["chinese_traditional"],"輛":["chinese_traditional"],"儲":["chinese_traditional"],"簽":["chinese_traditional"],"鬧":["chinese_traditional"],"擾":["chinese_traditional"],"遞":["chinese_traditional"],"戲":["chinese_traditional"],"餵":["chinese_traditional"],"療":["chinese_traditional"],"撫":["chinese_traditional"],"蝦":["chinese_traditional"],"蠟":["chinese_traditional"],"鄰":["chinese_traditional"],"鞏":["chinese_traditional"],"擠":["chinese_traditional"],"棄":["chinese_traditional"],"勁":["chinese_traditional"],"鄧":["chinese_traditional"],"爛":["chinese_traditional"],"磚":["chinese_traditional"],"烏":["chinese_traditional"],"艦":["chinese_traditional"],"淺":["chinese_traditional"],"暫":["chinese_traditional"],"膽":["chinese_traditional"],"詳":["chinese_traditional"],"譜":["chinese_traditional"],"賓":["chinese_traditional"],"輝":["chinese_traditional"],"憤":["chinese_traditional"],"競":["chinese_traditional"],"緒":["chinese_traditional"],"塗":["chinese_traditional"],"偵":["chinese_traditional"],"懸":["chinese_traditional"],"糾":["chinese_traditional"],"鎖":["chinese_traditional"],"賞":["chinese_traditional"],"鴨":["chinese_traditional"],"趨":["chinese_traditional"],"鳳":["chinese_traditional"],"輩":["chinese_traditional"],"灘":["chinese_traditional"],"驅":["chinese_traditional"],"篩":["chinese_traditional"],"峽":["chinese_traditional"],"壽":["chinese_traditional"],"譯":["chinese_traditional"],"遲":["chinese_traditional"],"矽":["chinese_traditional"],"貸":["chinese_traditional"],"脅":["chinese_traditional"],"蝕":["chinese_traditional"],"奧":["chinese_traditional"],"鳴":["chinese_traditional"],"嶺":["chinese_traditional"],"憑":["chinese_traditional"],"繪":["chinese_traditional"],"錫":["chinese_traditional"],"廟":["chinese_traditional"],"籌":["chinese_traditional"],"凍":["chinese_traditional"],"輔":["chinese_traditional"],"攝":["chinese_traditional"],"襲":["chinese_traditional"],"鉀":["chinese_traditional"],"鳥":["chinese_traditional"],"韓":["chinese_traditional"],"僑":["chinese_traditional"],"涼":["chinese_traditional"],"餾":["chinese_traditional"],"勸":["chinese_traditional"],"遼":["chinese_traditional"],"鴻":["chinese_traditional"],"輥":["chinese_traditional"],"飲":["chinese_traditional"],"罵":["chinese_traditional"],"辭":["chinese_traditional"],"蔣":["chinese_traditional"],"絨":["chinese_traditional"],"霧":["chinese_traditional"],"擬":["chinese_traditional"],"輯":["chinese_traditional"],"陝":["chinese_traditional"],"償":["chinese_traditional"],"廳":["chinese_traditional"],"駛":["chinese_traditional"],"賦":["chinese_traditional"],"澆":["chinese_traditional"],"鈣":["chinese_traditional"],"虧":["chinese_traditional"],"騙":["chinese_traditional"],"脹":["chinese_traditional"],"諧":["chinese_traditional"],"拋":["chinese_traditional"],"黴":["chinese_traditional"],"崗":["chinese_traditional"],"盜":["chinese_traditional"],"滲":["chinese_traditional"],"臟":["chinese_traditional"],"賴":["chinese_traditional"],"湧":["chinese_traditional"],"閱":["chinese_traditional"],"厲":["chinese_traditional"],"烴":["chinese_traditional"],"緯":["chinese_traditional"],"偽":["chinese_traditional"],"嘆":["chinese_traditional"],"釘":["chinese_traditional"],"莖":["chinese_traditional"],"籠":["chinese_traditional"],"錐":["chinese_traditional"],"恆":["chinese_traditional"],"傑":["chinese_traditional"],"綸":["chinese_traditional"],"敘":["chinese_traditional"],"獄":["chinese_traditional"],"絡":["chinese_traditional"],"驟":["chinese_traditional"],"冊":["chinese_traditional"],"屍":["chinese_traditional"],"紳":["chinese_traditional"],"犧":["chinese_traditional"],"轟":["chinese_traditional"],"晉":["chinese_traditional"],"禦":["chinese_traditional"],"錠":["chinese_traditional"],"錦":["chinese_traditional"],"喪":["chinese_traditional"],"鍛":["chinese_traditional"],"壟":["chinese_traditional"],"撲":["chinese_traditional"],"邁":["chinese_traditional"],"閒":["chinese_traditional"],"憂":["chinese_traditional"],"頑":["chinese_traditional"],"漲":["chinese_traditional"],"闢":["chinese_traditional"],"懲":["chinese_traditional"],"飄":["chinese_traditional"],"飾":["chinese_traditional"],"蕭":["chinese_traditional"],"郵":["chinese_traditional"],"遷":["chinese_traditional"],"煩":["chinese_traditional"],"債":["chinese_traditional"],"帳":["chinese_traditional"],"鈴":["chinese_traditional"],"餅":["chinese_traditional"],"雛":["chinese_traditional"],"賢":["chinese_traditional"],"丟":["chinese_traditional"],"墊":["chinese_traditional"],"擋":["chinese_traditional"],"覽":["chinese_traditional"],"貪":["chinese_traditional"],"繳":["chinese_traditional"],"馮":["chinese_traditional"],"諾":["chinese_traditional"],"誼":["chinese_traditional"],"兇":["chinese_traditional"],"誣":["chinese_traditional"],"騎":["chinese_traditional"],"喬":["chinese_traditional"],"叢":["chinese_traditional"],"盧":["chinese_traditional"],"悶":["chinese_traditional"],"諮":["chinese_traditional"],"駕":["chinese_traditional"],"纜":["chinese_traditional"],"鉺":["chinese_traditional"],"擲":["chinese_traditional"],"頗":["chinese_traditional"],"慘":["chinese_traditional"],"臘":["chinese_traditional"],"窩":["chinese_traditional"],"滌":["chinese_traditional"],"劍":["chinese_traditional"],"潑":["chinese_traditional"],"蔥":["chinese_traditional"],"撈":["chinese_traditional"],"蒼":["chinese_traditional"],"濱":["chinese_traditional"],"倆":["chinese_traditional"],"瘋":["chinese_traditional"],"糞":["chinese_traditional"],"檔":["chinese_traditional"],"駁":["chinese_traditional"],"腸":["chinese_traditional"],"撐":["chinese_traditional"],"曬":["chinese_traditional"],"蓮":["chinese_traditional"],"攤":["chinese_traditional"],"攪":["chinese_traditional"],"醬":["chinese_traditional"],"皺":["chinese_traditional"],"暢":["chinese_traditional"],"疊":["chinese_traditional"],"閣":["chinese_traditional"],"萊":["chinese_traditional"],"轄":["chinese_traditional"],"鉤":["chinese_traditional"],"壩":["chinese_traditional"],"餓":["chinese_traditional"],"禍":["chinese_traditional"],"邏":["chinese_traditional"],"嘗":["chinese_traditional"],"韋":["chinese_traditional"],"abdikace":["czech"],"abeceda":["czech"],"adresa":["czech"],"agrese":["czech"],"akce":["czech"],"aktovka":["czech"],"alej":["czech"],"alkohol":["czech"],"amputace":["czech"],"ananas":["czech"],"andulka":["czech"],"anekdota":["czech"],"anketa":["czech"],"antika":["czech"],"anulovat":["czech"],"archa":["czech"],"arogance":["czech"],"asfalt":["czech","turkish"],"asistent":["czech"],"aspirace":["czech"],"astma":["czech"],"astronom":["czech"],"atlas":["czech"],"atletika":["czech"],"atol":["czech"],"autobus":["czech"],"azyl":["czech"],"babka":["czech"],"bachor":["czech"],"bacil":["czech"],"baculka":["czech"],"badatel":["czech"],"bageta":["czech"],"bagr":["czech"],"bahno":["czech"],"bakterie":["czech"],"balada":["czech"],"baletka":["czech"],"balkon":["czech"],"balonek":["czech"],"balvan":["czech"],"balza":["czech"],"bambus":["czech"],"bankomat":["czech"],"barbar":["czech"],"baret":["czech"],"barman":["czech"],"baroko":["czech"],"barva":["czech"],"baterka":["czech"],"batoh":["czech"],"bavlna":["czech"],"bazalka":["czech"],"bazilika":["czech"],"bazuka":["czech"],"bedna":["czech"],"beran":["czech"],"beseda":["czech"],"bestie":["czech"],"beton":["czech","turkish"],"bezinka":["czech"],"bezmoc":["czech"],"beztak":["czech"],"bicykl":["czech"],"bidlo":["czech"],"biftek":["czech","turkish"],"bikiny":["czech"],"bilance":["czech"],"biograf":["czech"],"biolog":["czech"],"bitva":["czech"],"bizon":["czech"],"blahobyt":["czech"],"blatouch":["czech"],"blecha":["czech"],"bledule":["czech"],"blesk":["czech"],"blikat":["czech"],"blizna":["czech"],"blokovat":["czech"],"bloudit":["czech"],"blud":["czech"],"bobek":["czech"],"bobr":["czech"],"bodlina":["czech"],"bodnout":["czech"],"bohatost":["czech"],"bojkot":["czech"],"bojovat":["czech"],"bokorys":["czech"],"bolest":["czech"],"borec":["czech"],"borovice":["czech"],"bota":["czech"],"boubel":["czech"],"bouchat":["czech"],"bouda":["czech"],"boule":["czech"],"bourat":["czech"],"boxer":["czech"],"bradavka":["czech"],"brambora":["czech"],"branka":["czech"],"bratr":["czech"],"brepta":["czech"],"briketa":["czech"],"brko":["czech"],"brloh":["czech"],"bronz":["czech"],"broskev":["czech"],"brunetka":["czech"],"brusinka":["czech"],"brzda":["czech"],"brzy":["czech"],"bublina":["czech"],"bubnovat":["czech"],"buchta":["czech"],"buditel":["czech"],"budka":["czech"],"budova":["czech"],"bufet":["czech"],"bujarost":["czech"],"bukvice":["czech"],"buldok":["czech"],"bulva":["czech"],"bunda":["czech"],"bunkr":["czech"],"burza":["czech"],"butik":["czech","turkish"],"buvol":["czech"],"buzola":["czech"],"bydlet":["czech"],"bylina":["czech"],"bytovka":["czech"],"bzukot":["czech"],"capart":["czech"],"carevna":["czech"],"cedr":["czech"],"cedule":["czech"],"cejch":["czech"],"cejn":["czech"],"cela":["czech"],"celer":["czech"],"celkem":["czech"],"celnice":["czech"],"cenina":["czech"],"cennost":["czech"],"cenovka":["czech"],"centrum":["czech"],"cenzor":["czech"],"cestopis":["czech"],"cetka":["czech"],"chalupa":["czech"],"chapadlo":["czech"],"charita":["czech"],"chata":["czech"],"chechtat":["czech"],"chemie":["czech"],"chichot":["czech"],"chirurg":["czech"],"chlad":["czech"],"chleba":["czech"],"chlubit":["czech"],"chmel":["czech"],"chmura":["czech"],"chobot":["czech"],"chochol":["czech"],"chodba":["czech"],"cholera":["czech"],"chomout":["czech"],"chopit":["czech"],"choroba":["czech"],"chov":["czech"],"chrapot":["czech"],"chrlit":["czech"],"chrt":["czech"],"chrup":["czech"],"chtivost":["czech"],"chudina":["czech"],"chutnat":["czech"],"chvat":["czech"],"chvilka":["czech"],"chvost":["czech"],"chyba":["czech"],"chystat":["czech"],"chytit":["czech"],"cibule":["czech"],"cigareta":["czech"],"cihelna":["czech"],"cihla":["czech"],"cinkot":["czech"],"cirkus":["czech"],"cisterna":["czech"],"citace":["czech"],"citrus":["czech"],"cizinec":["czech"],"cizost":["czech"],"clona":["czech"],"cokoliv":["czech"],"couvat":["czech"],"ctitel":["czech"],"ctnost":["czech"],"cudnost":["czech"],"cuketa":["czech"],"cukr":["czech"],"cupot":["czech"],"cvaknout":["czech"],"cval":["czech"],"cvik":["czech"],"cvrkot":["czech"],"cyklista":["czech"],"daleko":["czech"],"dareba":["czech"],"datel":["czech"],"datum":["czech"],"dcera":["czech"],"debata":["czech"],"dechovka":["czech"],"decibel":["czech"],"deficit":["czech"],"deflace":["czech"],"dekl":["czech"],"dekret":["czech"],"demokrat":["czech"],"deprese":["czech"],"derby":["czech"],"deska":["czech"],"detektiv":["czech"],"dikobraz":["czech"],"diktovat":["czech"],"dioda":["czech"],"diplom":["czech"],"disk":["czech","turkish"],"displej":["czech"],"divadlo":["czech"],"divoch":["czech"],"dlaha":["czech"],"dlouho":["czech"],"dluhopis":["czech"],"dnes":["czech"],"dobro":["czech"],"dobytek":["czech"],"docent":["czech"],"dochutit":["czech"],"dodnes":["czech"],"dohled":["czech"],"dohoda":["czech"],"dohra":["czech"],"dojem":["czech"],"dojnice":["czech"],"doklad":["czech"],"dokola":["czech"],"doktor":["czech","turkish"],"dokument":["czech"],"dolar":["czech"],"doleva":["czech"],"dolina":["czech"],"doma":["czech"],"dominant":["czech"],"domluvit":["czech"],"domov":["czech"],"donutit":["czech"],"dopad":["czech"],"dopis":["czech"],"doplnit":["czech"],"doposud":["czech"],"doprovod":["czech"],"dopustit":["czech"],"dorazit":["czech"],"dorost":["czech"],"dort":["czech"],"dosah":["czech"],"doslov":["czech"],"dostatek":["czech"],"dosud":["czech"],"dosyta":["czech"],"dotaz":["czech"],"dotek":["czech"],"dotknout":["czech"],"doufat":["czech"],"doutnat":["czech"],"dovozce":["czech"],"dozadu":["czech"],"doznat":["czech"],"dozorce":["czech"],"drahota":["czech"],"drak":["czech"],"dramatik":["czech"],"dravec":["czech"],"draze":["czech"],"drdol":["czech"],"drobnost":["czech"],"drogerie":["czech"],"drozd":["czech"],"drsnost":["czech"],"drtit":["czech"],"drzost":["czech"],"duben":["czech"],"duchovno":["czech"],"dudek":["czech"],"duha":["czech"],"duhovka":["czech"],"dusit":["czech"],"dusno":["czech"],"dutost":["czech"],"dvojice":["czech"],"dvorec":["czech"],"dynamit":["czech"],"ekolog":["czech"],"ekonomie":["czech"],"elektron":["czech"],"elipsa":["czech"],"email":["czech"],"emise":["czech"],"emoce":["czech"],"empatie":["czech"],"epizoda":["czech"],"epocha":["czech"],"epopej":["czech"],"epos":["czech"],"esej":["czech"],"esence":["czech"],"eskorta":["czech"],"eskymo":["czech"],"etiketa":["czech"],"euforie":["czech"],"evoluce":["czech"],"exekuce":["czech"],"exkurze":["czech"],"expedice":["czech"],"exploze":["czech"],"export":["czech"],"extrakt":["czech"],"facka":["czech"],"fajfka":["czech"],"fakulta":["czech"],"fanatik":["czech","turkish"],"fantazie":["czech"],"farmacie":["czech"],"favorit":["czech"],"fazole":["czech"],"federace":["czech"],"fejeton":["czech"],"fenka":["czech"],"fialka":["czech"],"figurant":["czech"],"filozof":["czech"],"filtr":["czech"],"finance":["czech"],"finta":["czech"],"fixace":["czech"],"fjord":["czech"],"flanel":["czech"],"flirt":["czech"],"flotila":["czech"],"fond":["czech"],"fosfor":["czech"],"fotbal":["czech"],"fotka":["czech"],"foton":["czech"],"frakce":["czech"],"freska":["czech"],"fronta":["czech"],"fukar":["czech"],"funkce":["czech"],"fyzika":["czech"],"galeje":["czech"],"garant":["czech"],"genetika":["czech"],"geolog":["czech"],"gilotina":["czech"],"glazura":["czech"],"glejt":["czech"],"golem":["czech"],"golfista":["czech"],"gotika":["czech"],"graf":["czech"],"gramofon":["czech"],"granule":["czech"],"grep":["czech"],"gril":["czech"],"grog":["czech"],"groteska":["czech"],"guma":["czech"],"hadice":["czech"],"hadr":["czech"],"hala":["czech"],"halenka":["czech"],"hanba":["czech"],"hanopis":["czech"],"harfa":["czech"],"harpuna":["czech"],"havran":["czech"],"hebkost":["czech"],"hejkal":["czech"],"hejno":["czech"],"hejtman":["czech"],"hektar":["czech","turkish"],"helma":["czech"],"hematom":["czech"],"herec":["czech"],"herna":["czech"],"heslo":["czech"],"hezky":["czech"],"historik":["czech"],"hladovka":["czech"],"hlasivky":["czech"],"hlava":["czech"],"hledat":["czech"],"hlen":["czech"],"hlodavec":["czech"],"hloh":["czech"],"hloupost":["czech"],"hltat":["czech"],"hlubina":["czech"],"hluchota":["czech"],"hmat":["czech"],"hmota":["czech"],"hmyz":["czech"],"hnis":["czech"],"hnojivo":["czech"],"hnout":["czech"],"hoblina":["czech"],"hoboj":["czech"],"hoch":["czech"],"hodiny":["czech"],"hodlat":["czech"],"hodnota":["czech"],"hodovat":["czech"],"hojnost":["czech"],"hokej":["czech"],"holinka":["czech"],"holka":["czech"],"holub":["czech"],"homole":["czech"],"honitba":["czech"],"honorace":["czech"],"horal":["czech"],"horda":["czech"],"horizont":["czech"],"horko":["czech"],"horlivec":["czech"],"hormon":["czech","turkish"],"hornina":["czech"],"horoskop":["czech"],"horstvo":["czech"],"hospoda":["czech"],"hostina":["czech"],"hotovost":["czech"],"houba":["czech"],"houf":["czech"],"houpat":["czech"],"houska":["czech"],"hovor":["czech"],"hradba":["czech"],"hranice":["czech"],"hravost":["czech"],"hrazda":["czech"],"hrbolek":["czech"],"hrdina":["czech"],"hrdlo":["czech"],"hrdost":["czech"],"hrnek":["czech"],"hrobka":["czech"],"hromada":["czech"],"hrot":["czech"],"hrouda":["czech"],"hrozen":["czech"],"hrstka":["czech"],"hrubost":["czech"],"hryzat":["czech"],"hubenost":["czech"],"hubnout":["czech"],"hudba":["czech"],"hukot":["czech"],"humr":["czech"],"husita":["czech"],"hustota":["czech"],"hvozd":["czech"],"hybnost":["czech"],"hydrant":["czech"],"hygiena":["czech"],"hymna":["czech"],"hysterik":["czech"],"idylka":["czech"],"ihned":["czech"],"ikona":["czech"],"iluze":["czech"],"imunita":["czech"],"infekce":["czech"],"inflace":["czech"],"inkaso":["czech"],"inovace":["czech"],"inspekce":["czech"],"internet":["czech"],"invalida":["czech"],"investor":["czech"],"inzerce":["czech"],"ironie":["czech"],"jablko":["czech"],"jachta":["czech"],"jahoda":["czech"],"jakmile":["czech"],"jakost":["czech"],"jalovec":["czech"],"jantar":["czech"],"jarmark":["czech"],"jaro":["czech"],"jasan":["czech"],"jasno":["czech"],"jatka":["czech"],"javor":["czech"],"jazyk":["czech"],"jedinec":["czech"],"jedle":["czech"],"jednatel":["czech"],"jehlan":["czech"],"jekot":["czech"],"jelen":["czech"],"jelito":["czech"],"jemnost":["czech"],"jenom":["czech"],"jepice":["czech"],"jeseter":["czech"],"jevit":["czech"],"jezdec":["czech"],"jezero":["czech"],"jinak":["czech"],"jindy":["czech"],"jinoch":["czech"],"jiskra":["czech"],"jistota":["czech"],"jitrnice":["czech"],"jizva":["czech"],"jmenovat":["czech"],"jogurt":["czech"],"jurta":["czech"],"kabaret":["czech"],"kabel":["czech"],"kabinet":["czech"],"kachna":["czech"],"kadet":["czech"],"kadidlo":["czech"],"kahan":["czech"],"kajak":["czech"],"kajuta":["czech"],"kakao":["czech"],"kaktus":["czech"],"kalamita":["czech"],"kalhoty":["czech"],"kalibr":["czech"],"kalnost":["czech"],"kamera":["czech"],"kamkoliv":["czech"],"kamna":["czech"],"kanibal":["czech"],"kanoe":["czech"],"kantor":["czech"],"kapalina":["czech"],"kapela":["czech"],"kapitola":["czech"],"kapka":["czech"],"kaple":["czech"],"kapota":["czech"],"kapr":["czech"],"kapusta":["czech"],"kapybara":["czech"],"karamel":["czech"],"karotka":["czech"],"karton":["czech"],"kasa":["czech"],"katalog":["czech"],"katedra":["czech"],"kauce":["czech"],"kauza":["czech"],"kavalec":["czech"],"kazajka":["czech"],"kazeta":["czech"],"kazivost":["czech"],"kdekoliv":["czech"],"kdesi":["czech"],"kedluben":["czech"],"kemp":["czech"],"keramika":["czech"],"kino":["czech"],"klacek":["czech"],"kladivo":["czech"],"klam":["czech"],"klapot":["czech"],"klasika":["czech"],"klaun":["czech"],"klec":["czech"],"klenba":["czech"],"klepat":["czech"],"klesnout":["czech"],"klid":["czech"],"klima":["czech"],"klisna":["czech"],"klobouk":["czech"],"klokan":["czech"],"klopa":["czech"],"kloub":["czech"],"klubovna":["czech"],"klusat":["czech"],"kluzkost":["czech"],"kmen":["czech"],"kmitat":["czech"],"kmotr":["czech"],"kniha":["czech"],"knot":["czech"],"koalice":["czech"],"koberec":["czech"],"kobka":["czech"],"kobliha":["czech"],"kobyla":["czech"],"kocour":["czech"],"kohout":["czech"],"kojenec":["czech"],"kokos":["czech"],"koktejl":["czech"],"kolaps":["czech"],"koleda":["czech"],"kolize":["czech"],"kolo":["czech"],"komando":["czech"],"kometa":["czech"],"komik":["czech"],"komnata":["czech"],"komora":["czech"],"kompas":["czech"],"komunita":["czech"],"konat":["czech"],"koncept":["czech"],"kondice":["czech"],"konec":["czech"],"konfese":["czech"],"kongres":["czech"],"konina":["czech"],"konkurs":["czech"],"kontakt":["czech"],"konzerva":["czech"],"kopanec":["czech"],"kopie":["czech"],"kopnout":["czech"],"koprovka":["czech"],"korbel":["czech"],"korektor":["czech"],"kormidlo":["czech"],"koroptev":["czech"],"korpus":["czech"],"koruna":["czech"],"koryto":["czech"],"korzet":["czech"],"kosatec":["czech"],"kostka":["czech"],"kotel":["czech"],"kotleta":["czech"],"kotoul":["czech"],"koukat":["czech"],"koupelna":["czech"],"kousek":["czech"],"kouzlo":["czech"],"kovboj":["czech"],"koza":["czech"],"kozoroh":["czech"],"krabice":["czech"],"krach":["czech"],"krajina":["czech"],"kralovat":["czech"],"krasopis":["czech"],"kravata":["czech"],"kredit":["czech"],"krejcar":["czech"],"kresba":["czech"],"kreveta":["czech"],"kriket":["czech"],"kritik":["czech"],"krize":["czech"],"krkavec":["czech"],"krmelec":["czech"],"krmivo":["czech"],"krocan":["czech"],"krok":["czech"],"kronika":["czech"],"kropit":["czech"],"kroupa":["czech"],"krovka":["czech"],"krtek":["czech"],"kruhadlo":["czech"],"krupice":["czech"],"krutost":["czech"],"krvinka":["czech"],"krychle":["czech"],"krypta":["czech"],"krystal":["czech"],"kryt":["czech"],"kudlanka":["czech"],"kufr":["czech"],"kujnost":["czech"],"kukla":["czech"],"kulajda":["czech"],"kulich":["czech"],"kulka":["czech"],"kulomet":["czech"],"kultura":["czech"],"kuna":["czech"],"kupodivu":["czech"],"kurt":["czech"],"kurzor":["czech"],"kutil":["czech"],"kvalita":["czech"],"kvasinka":["czech"],"kvestor":["czech"],"kynolog":["czech"],"kyselina":["czech"],"kytara":["czech"],"kytice":["czech"],"kytka":["czech"],"kytovec":["czech"],"kyvadlo":["czech"],"labrador":["czech"],"lachtan":["czech"],"ladnost":["czech"],"laik":["czech"],"lakomec":["czech"],"lamela":["czech"],"lampa":["czech"],"lanovka":["czech"],"lasice":["czech"],"laso":["czech"],"lastura":["czech"],"latinka":["czech"],"lavina":["czech"],"lebka":["czech"],"leckdy":["czech"],"leden":["czech"],"lednice":["czech"],"ledovka":["czech"],"ledvina":["czech"],"legenda":["czech"],"legie":["czech"],"legrace":["czech"],"lehce":["czech"],"lehkost":["czech"],"lehnout":["czech"],"lektvar":["czech"],"lenochod":["czech"],"lentilka":["czech"],"lepenka":["czech"],"lepidlo":["czech"],"letadlo":["czech"],"letec":["czech"],"letmo":["czech"],"letokruh":["czech"],"levhart":["czech"],"levitace":["czech"],"levobok":["czech"],"libra":["czech"],"lichotka":["czech"],"lidojed":["czech"],"lidskost":["czech"],"lihovina":["czech"],"lijavec":["czech"],"lilek":["czech"],"limetka":["czech"],"linie":["czech"],"linka":["czech"],"linoleum":["czech"],"listopad":["czech"],"litina":["czech"],"litovat":["czech"],"lobista":["czech"],"lodivod":["czech"],"logika":["czech"],"logoped":["czech"],"lokalita":["czech"],"loket":["czech"],"lomcovat":["czech"],"lopata":["czech"],"lopuch":["czech"],"lord":["czech"],"losos":["czech"],"lotr":["czech"],"loudal":["czech"],"louh":["czech"],"louka":["czech"],"louskat":["czech"],"lovec":["czech"],"lstivost":["czech"],"lucerna":["czech"],"lucifer":["czech"],"lump":["czech"],"lusk":["czech"],"lustrace":["czech"],"lvice":["czech"],"lyra":["czech"],"lyrika":["czech"],"lysina":["czech"],"madam":["czech"],"madlo":["czech"],"magistr":["czech"],"mahagon":["czech"],"majetek":["czech"],"majitel":["czech"],"majorita":["czech"],"makak":["czech"],"makovice":["czech"],"makrela":["czech"],"malba":["czech"],"malina":["czech"],"malovat":["czech"],"malvice":["czech"],"maminka":["czech"],"mandle":["czech"],"manko":["czech"],"marnost":["czech"],"masakr":["czech"],"maskot":["czech"],"masopust":["czech"],"matice":["czech"],"matrika":["czech"],"maturita":["czech"],"mazanec":["czech"],"mazivo":["czech"],"mazlit":["czech"],"mazurka":["czech"],"mdloba":["czech"],"mechanik":["czech"],"meditace":["czech"],"medovina":["czech"],"melasa":["czech"],"meloun":["czech"],"mentolka":["czech"],"metla":["czech"],"metoda":["czech"],"metr":["czech"],"mezera":["czech"],"migrace":["czech"],"mihnout":["czech"],"mihule":["czech"],"mikina":["czech"],"mikrofon":["czech","turkish"],"milenec":["czech"],"milimetr":["czech"],"milost":["czech"],"mimika":["czech"],"mincovna":["czech"],"minibar":["czech"],"minomet":["czech"],"minulost":["czech"],"miska":["czech"],"mistr":["czech"],"mixovat":["czech"],"mladost":["czech"],"mlha":["czech"],"mlhovina":["czech"],"mlok":["czech"],"mlsat":["czech"],"mluvit":["czech"],"mnich":["czech"],"mnohem":["czech"],"mobil":["czech"],"mocnost":["czech"],"modelka":["czech"],"modlitba":["czech"],"mohyla":["czech"],"mokro":["czech"],"molekula":["czech"],"momentka":["czech"],"monarcha":["czech"],"monokl":["czech"],"monstrum":["czech"],"montovat":["czech"],"monzun":["czech"],"mosaz":["czech"],"moskyt":["czech"],"most":["czech"],"motivace":["czech"],"motorka":["czech"],"motyka":["czech"],"moucha":["czech"],"moudrost":["czech"],"mozaika":["czech"],"mozek":["czech"],"mozol":["czech"],"mramor":["czech"],"mravenec":["czech"],"mrkev":["czech"],"mrtvola":["czech"],"mrzet":["czech"],"mrzutost":["czech"],"mstitel":["czech"],"mudrc":["czech"],"muflon":["czech"],"mulat":["czech"],"mumie":["czech"],"munice":["czech"],"muset":["czech"],"mutace":["czech"],"muzeum":["czech"],"muzikant":["czech"],"myslivec":["czech"],"mzda":["czech"],"nabourat":["czech"],"nachytat":["czech"],"nadace":["czech"],"nadbytek":["czech"],"nadhoz":["czech"],"nadobro":["czech"],"nadpis":["czech"],"nahlas":["czech"],"nahnat":["czech"],"nahodile":["czech"],"nahradit":["czech"],"naivita":["czech"],"najednou":["czech"],"najisto":["czech"],"najmout":["czech"],"naklonit":["czech"],"nakonec":["czech"],"nakrmit":["czech"],"nalevo":["czech"],"namazat":["czech"],"namluvit":["czech"],"nanometr":["czech"],"naoko":["czech"],"naopak":["czech"],"naostro":["czech"],"napadat":["czech"],"napevno":["czech"],"naplnit":["czech"],"napnout":["czech"],"naposled":["czech"],"naprosto":["czech"],"narodit":["czech"],"naruby":["czech"],"narychlo":["czech"],"nasadit":["czech"],"nasekat":["czech"],"naslepo":["czech"],"nastat":["czech"],"natolik":["czech"],"navenek":["czech"],"navrch":["czech"],"navzdory":["czech"],"nazvat":["czech"],"nebe":["czech"],"nechat":["czech"],"necky":["czech"],"nedaleko":["czech"],"nedbat":["czech"],"neduh":["czech"],"negace":["czech"],"nehet":["czech"],"nehoda":["czech"],"nejen":["czech"],"nejprve":["czech"],"neklid":["czech"],"nelibost":["czech"],"nemilost":["czech"],"nemoc":["czech"],"neochota":["czech"],"neonka":["czech"],"nepokoj":["czech"],"nerost":["czech"],"nerv":["czech"],"nesmysl":["czech"],"nesoulad":["czech"],"netvor":["czech"],"neuron":["czech"],"nevina":["czech"],"nezvykle":["czech"],"nicota":["czech"],"nijak":["czech"],"nikam":["czech"],"nikdy":["czech"],"nikl":["czech"],"nikterak":["czech"],"nitro":["czech"],"nocleh":["czech"],"nohavice":["czech"],"nominace":["czech"],"nora":["czech"],"norek":["czech"],"nositel":["czech"],"nosnost":["czech"],"nouze":["czech"],"noviny":["czech"],"novota":["czech"],"nozdra":["czech"],"nuda":["czech"],"nudle":["czech"],"nuget":["czech"],"nutit":["czech"],"nutnost":["czech"],"nutrie":["czech"],"nymfa":["czech"],"obal":["czech"],"obarvit":["czech"],"obava":["czech"],"obdiv":["czech"],"obec":["czech"],"obehnat":["czech"],"obejmout":["czech"],"obezita":["czech"],"obhajoba":["czech"],"obilnice":["czech"],"objasnit":["czech"],"objekt":["czech"],"obklopit":["czech"],"oblast":["czech"],"oblek":["czech"],"obliba":["czech"],"obloha":["czech"],"obluda":["czech"],"obnos":["czech"],"obohatit":["czech"],"obojek":["czech"],"obout":["czech"],"obrazec":["czech"],"obrna":["czech"],"obruba":["czech"],"obrys":["czech"],"obsah":["czech"],"obsluha":["czech"],"obstarat":["czech"],"obuv":["czech"],"obvaz":["czech"],"obvinit":["czech"],"obvod":["czech"],"obvykle":["czech"],"obyvatel":["czech"],"obzor":["czech"],"ocas":["czech"],"ocel":["czech"],"ocenit":["czech"],"ochladit":["czech"],"ochota":["czech"],"ochrana":["czech"],"ocitnout":["czech"],"odboj":["czech"],"odbyt":["czech"],"odchod":["czech"],"odcizit":["czech"],"odebrat":["czech"],"odeslat":["czech"],"odevzdat":["czech"],"odezva":["czech"],"odhadce":["czech"],"odhodit":["czech"],"odjet":["czech"],"odjinud":["czech"],"odkaz":["czech"],"odkoupit":["czech"],"odliv":["czech"],"odluka":["czech"],"odmlka":["czech"],"odolnost":["czech"],"odpad":["czech"],"odpis":["czech"],"odplout":["czech"],"odpor":["czech"],"odpustit":["czech"],"odpykat":["czech"],"odrazka":["czech"],"odsoudit":["czech"],"odstup":["czech"],"odsun":["czech"],"odtok":["czech"],"odtud":["czech"],"odvaha":["czech"],"odveta":["czech"],"odvolat":["czech"],"odvracet":["czech"],"odznak":["czech"],"ofina":["czech"],"ofsajd":["czech"],"ohlas":["czech"],"ohnisko":["czech"],"ohrada":["czech"],"ohrozit":["czech"],"ohryzek":["czech"],"okap":["czech"],"okenice":["czech"],"oklika":["czech"],"okno":["czech"],"okouzlit":["czech"],"okovy":["czech"],"okrasa":["czech"],"okres":["czech"],"okrsek":["czech"],"okruh":["czech"],"okupant":["czech"],"okurka":["czech"],"okusit":["czech"],"olejnina":["czech"],"olizovat":["czech"],"omak":["czech"],"omeleta":["czech"],"omezit":["czech"],"omladina":["czech"],"omlouvat":["czech"],"omluva":["czech"],"omyl":["czech"],"onehdy":["czech"],"opakovat":["czech"],"opasek":["czech"],"operace":["czech"],"opice":["czech"],"opilost":["czech"],"opisovat":["czech"],"opora":["czech"],"opozice":["czech"],"opravdu":["czech"],"oproti":["czech"],"orbital":["czech"],"orchestr":["czech"],"orgie":["czech"],"orlice":["czech"],"orloj":["czech"],"ortel":["czech"],"osada":["czech"],"oschnout":["czech"],"osika":["czech"],"osivo":["czech"],"oslava":["czech"],"oslepit":["czech"],"oslnit":["czech"],"oslovit":["czech"],"osnova":["czech"],"osoba":["czech"],"osolit":["czech"],"ospalec":["czech"],"osten":["czech"],"ostraha":["czech"],"ostuda":["czech"],"ostych":["czech"],"osvojit":["czech"],"oteplit":["czech"],"otisk":["czech"],"otop":["czech"],"otrhat":["czech"],"otrlost":["czech"],"otrok":["czech"],"otruby":["czech"],"otvor":["czech"],"ovanout":["czech"],"ovar":["czech"],"oves":["czech"],"ovlivnit":["czech"],"ovoce":["czech"],"oxid":["czech"],"ozdoba":["czech"],"pachatel":["czech"],"pacient":["czech"],"padouch":["czech"],"pahorek":["czech"],"pakt":["czech"],"palanda":["czech"],"palec":["czech"],"palivo":["czech"],"paluba":["czech"],"pamflet":["czech"],"pamlsek":["czech"],"panenka":["czech"],"panika":["czech"],"panna":["czech"],"panovat":["czech"],"panstvo":["czech"],"pantofle":["czech"],"paprika":["czech"],"parketa":["czech"],"parodie":["czech"],"parta":["czech"],"paruka":["czech"],"paryba":["czech"],"paseka":["czech"],"pasivita":["czech"],"pastelka":["czech"],"patent":["czech"],"patrona":["czech"],"pavouk":["czech"],"pazneht":["czech"],"pazourek":["czech"],"pecka":["czech"],"pedagog":["czech"],"pejsek":["czech"],"peklo":["czech"],"peloton":["czech"],"penalta":["czech"],"pendrek":["czech"],"penze":["czech"],"periskop":["czech"],"pero":["czech"],"pestrost":["czech"],"petarda":["czech"],"petice":["czech"],"petrolej":["czech"],"pevnina":["czech"],"pexeso":["czech"],"pianista":["czech"],"piha":["czech"],"pijavice":["czech"],"pikle":["czech"],"piknik":["czech","turkish"],"pilina":["czech"],"pilnost":["czech"],"pilulka":["czech"],"pinzeta":["czech"],"pipeta":["czech"],"pisatel":["czech"],"pistole":["czech"],"pitevna":["czech"],"pivnice":["czech"],"pivovar":["czech"],"placenta":["czech"],"plakat":["czech"],"plamen":["czech"],"planeta":["czech"],"plastika":["czech"],"platit":["czech"],"plavidlo":["czech"],"plaz":["czech"],"plech":["czech"],"plemeno":["czech"],"plenta":["czech"],"ples":["czech"],"pletivo":["czech"],"plevel":["czech"],"plivat":["czech"],"plnit":["czech"],"plno":["czech"],"plocha":["czech"],"plodina":["czech"],"plomba":["czech"],"plout":["czech"],"pluk":["czech"],"plyn":["czech"],"pobavit":["czech"],"pobyt":["czech"],"pochod":["czech"],"pocit":["czech"],"poctivec":["czech"],"podat":["czech"],"podcenit":["czech"],"podepsat":["czech"],"podhled":["czech"],"podivit":["czech"],"podklad":["czech"],"podmanit":["czech"],"podnik":["czech"],"podoba":["czech"],"podpora":["czech"],"podraz":["czech"],"podstata":["czech"],"podvod":["czech"],"podzim":["czech"],"poezie":["czech"],"pohanka":["czech"],"pohnutka":["czech"],"pohovor":["czech"],"pohroma":["czech"],"pohyb":["czech"],"pointa":["czech"],"pojistka":["czech"],"pojmout":["czech"],"pokazit":["czech"],"pokles":["czech"],"pokoj":["czech"],"pokrok":["czech"],"pokuta":["czech"],"pokyn":["czech"],"poledne":["czech"],"polibek":["czech"],"polknout":["czech"],"poloha":["czech"],"polynom":["czech"],"pomalu":["czech"],"pominout":["czech"],"pomlka":["czech"],"pomoc":["czech"],"pomsta":["czech"],"pomyslet":["czech"],"ponechat":["czech"],"ponorka":["czech"],"ponurost":["czech"],"popadat":["czech"],"popel":["czech"],"popisek":["czech"],"poplach":["czech"],"poprosit":["czech"],"popsat":["czech"],"popud":["czech"],"poradce":["czech"],"porce":["czech"],"porod":["czech"],"porucha":["czech"],"poryv":["czech"],"posadit":["czech"],"posed":["czech"],"posila":["czech"],"poskok":["czech"],"poslanec":["czech"],"posoudit":["czech"],"pospolu":["czech"],"postava":["czech"],"posudek":["czech"],"posyp":["czech"],"potah":["czech"],"potkan":["czech"],"potlesk":["czech"],"potomek":["czech"],"potrava":["czech"],"potupa":["czech"],"potvora":["czech"],"poukaz":["czech"],"pouto":["czech"],"pouzdro":["czech"],"povaha":["czech"],"povidla":["czech"],"povlak":["czech"],"povoz":["czech"],"povrch":["czech"],"povstat":["czech"],"povyk":["czech"],"povzdech":["czech"],"pozdrav":["czech"],"pozemek":["czech"],"poznatek":["czech"],"pozor":["czech"],"pozvat":["czech"],"pracovat":["czech"],"prahory":["czech"],"praktika":["czech"],"prales":["czech"],"praotec":["czech"],"praporek":["czech"],"prase":["czech"],"pravda":["czech"],"princip":["czech"],"prkno":["czech"],"probudit":["czech"],"procento":["czech"],"prodej":["czech"],"profese":["czech"],"prohra":["czech"],"projekt":["czech"],"prolomit":["czech"],"promile":["czech"],"pronikat":["czech"],"propad":["czech"],"prorok":["czech"],"prosba":["czech"],"proton":["czech"],"proutek":["czech"],"provaz":["czech"],"prskavka":["czech"],"prsten":["czech"],"prudkost":["czech"],"prut":["czech"],"prvek":["czech"],"prvohory":["czech"],"psanec":["czech"],"psovod":["czech"],"pstruh":["czech"],"ptactvo":["czech"],"puberta":["czech"],"puch":["czech"],"pudl":["czech"],"pukavec":["czech"],"puklina":["czech"],"pukrle":["czech"],"pult":["czech"],"pumpa":["czech"],"punc":["czech"],"pupen":["czech"],"pusa":["czech"],"pusinka":["czech"],"pustina":["czech"],"putovat":["czech"],"putyka":["czech"],"pyramida":["czech"],"pysk":["czech"],"pytel":["czech"],"racek":["czech"],"rachot":["czech"],"radiace":["czech"],"radnice":["czech"],"radon":["czech"],"raft":["czech"],"ragby":["czech"],"raketa":["czech"],"rakovina":["czech"],"rameno":["czech"],"rampouch":["czech"],"rande":["czech"],"rarach":["czech"],"rarita":["czech"],"rasovna":["czech"],"rastr":["czech"],"ratolest":["czech"],"razance":["czech"],"razidlo":["czech"],"reagovat":["czech"],"reakce":["czech"],"recept":["czech"],"redaktor":["czech"],"referent":["czech"],"reflex":["czech"],"rejnok":["czech"],"reklama":["czech"],"rekord":["czech"],"rekrut":["czech"],"rektor":["czech"],"reputace":["czech"],"revize":["czech","turkish"],"revma":["czech"],"revolver":["czech"],"rezerva":["czech"],"riskovat":["czech"],"riziko":["czech"],"robotika":["czech"],"rodokmen":["czech"],"rohovka":["czech"],"rokle":["czech"],"rokoko":["czech"],"romaneto":["czech"],"ropovod":["czech"],"ropucha":["czech"],"rorejs":["czech"],"rosol":["czech"],"rostlina":["czech"],"rotmistr":["czech"],"rotoped":["czech"],"rotunda":["czech"],"roubenka":["czech"],"roucho":["czech"],"roup":["czech"],"roura":["czech"],"rovina":["czech"],"rovnice":["czech"],"rozbor":["czech"],"rozchod":["czech"],"rozdat":["czech"],"rozeznat":["czech"],"rozhodce":["czech"],"rozinka":["czech"],"rozjezd":["czech"],"rozkaz":["czech"],"rozloha":["czech"],"rozmar":["czech"],"rozpad":["czech"],"rozruch":["czech"],"rozsah":["czech"],"roztok":["czech"],"rozum":["czech"],"rozvod":["czech"],"rubrika":["czech"],"ruchadlo":["czech"],"rukavice":["czech"],"rukopis":["czech"],"ryba":["czech"],"rybolov":["czech"],"rychlost":["czech"],"rydlo":["czech"],"rypadlo":["czech"],"rytina":["czech"],"ryzost":["czech"],"sadista":["czech"],"sahat":["czech"],"sako":["czech"],"samec":["czech"],"samizdat":["czech"],"samota":["czech"],"sanitka":["czech"],"sardinka":["czech"],"sasanka":["czech"],"satelit":["czech"],"sazba":["czech"],"sazenice":["czech"],"sbor":["czech"],"schovat":["czech"],"sebranka":["czech"],"secese":["czech"],"sedadlo":["czech"],"sediment":["czech"],"sedlo":["czech"],"sehnat":["czech"],"sejmout":["czech"],"sekera":["czech"],"sekta":["czech"],"sekunda":["czech"],"sekvoje":["czech"],"semeno":["czech"],"seno":["czech"],"servis":["czech","turkish"],"sesadit":["czech"],"seshora":["czech"],"seskok":["czech"],"seslat":["czech"],"sestra":["czech"],"sesuv":["czech"],"sesypat":["czech"],"setba":["czech"],"setina":["czech"],"setkat":["czech"],"setnout":["czech"],"setrvat":["czech"],"sever":["czech"],"seznam":["czech"],"shoda":["czech"],"shrnout":["czech"],"sifon":["czech"],"silnice":["czech"],"sirka":["czech"],"sirotek":["czech"],"sirup":["czech"],"situace":["czech"],"skafandr":["czech"],"skalisko":["czech"],"skanzen":["czech"],"skaut":["czech"],"skeptik":["czech"],"skica":["czech"],"skladba":["czech"],"sklenice":["czech"],"sklo":["czech"],"skluz":["czech"],"skoba":["czech"],"skokan":["czech"],"skoro":["czech"],"skripta":["czech"],"skrz":["czech"],"skupina":["czech"],"skvost":["czech"],"skvrna":["czech"],"slabika":["czech"],"sladidlo":["czech"],"slanina":["czech"],"slast":["czech"],"slavnost":["czech"],"sledovat":["czech"],"slepec":["czech"],"sleva":["czech"],"slezina":["czech"],"slib":["czech"],"slina":["czech"],"sliznice":["czech"],"slon":["czech"],"sloupek":["czech"],"slovo":["czech"],"sluch":["czech"],"sluha":["czech"],"slunce":["czech"],"slupka":["czech"],"slza":["czech"],"smaragd":["czech"],"smetana":["czech"],"smilstvo":["czech"],"smlouva":["czech"],"smog":["czech"],"smrad":["czech"],"smrk":["czech"],"smrtka":["czech"],"smutek":["czech"],"smysl":["czech"],"snad":["czech"],"snaha":["czech"],"snob":["czech"],"sobota":["czech"],"socha":["czech"],"sodovka":["czech"],"sokol":["czech"],"sopka":["czech"],"sotva":["czech"],"souboj":["czech"],"soucit":["czech"],"soudce":["czech"],"souhlas":["czech"],"soulad":["czech"],"soumrak":["czech"],"souprava":["czech"],"soused":["czech"],"soutok":["czech"],"souviset":["czech"],"spalovna":["czech"],"spasitel":["czech"],"spis":["czech"],"splav":["czech"],"spodek":["czech"],"spojenec":["czech"],"spolu":["czech"],"sponzor":["czech"],"spornost":["czech"],"spousta":["czech"],"sprcha":["czech"],"spustit":["czech"],"sranda":["czech"],"sraz":["czech"],"srdce":["czech"],"srna":["czech"],"srnec":["czech"],"srovnat":["czech"],"srpen":["czech"],"srst":["czech"],"srub":["czech"],"stanice":["czech"],"starosta":["czech"],"statika":["czech"],"stavba":["czech"],"stehno":["czech"],"stezka":["czech"],"stodola":["czech"],"stolek":["czech"],"stopa":["czech"],"storno":["czech"],"stoupat":["czech"],"strach":["czech"],"stres":["czech"],"strhnout":["czech"],"strom":["czech"],"struna":["czech"],"studna":["czech"],"stupnice":["czech"],"stvol":["czech"],"styk":["czech"],"subjekt":["czech"],"subtropy":["czech"],"suchar":["czech"],"sudost":["czech"],"sukno":["czech"],"sundat":["czech"],"sunout":["czech"],"surikata":["czech"],"surovina":["czech"],"svah":["czech"],"svalstvo":["czech"],"svetr":["czech"],"svatba":["czech"],"svazek":["czech"],"svisle":["czech"],"svitek":["czech"],"svoboda":["czech"],"svodidlo":["czech"],"svorka":["czech"],"svrab":["czech"],"sykavka":["czech"],"sykot":["czech"],"synek":["czech"],"synovec":["czech"],"sypat":["czech"],"sypkost":["czech"],"syrovost":["czech"],"sysel":["czech"],"sytost":["czech"],"tabletka":["czech"],"tabule":["czech"],"tahoun":["czech"],"tajemno":["czech"],"tajfun":["czech"],"tajga":["czech"],"tajit":["czech"],"tajnost":["czech"],"taktika":["czech"],"tamhle":["czech"],"tampon":["czech","turkish"],"tancovat":["czech"],"tanec":["czech"],"tanker":["czech"],"tapeta":["czech"],"tavenina":["czech"],"tazatel":["czech"],"technika":["czech"],"tehdy":["czech"],"tekutina":["czech"],"telefon":["czech"],"temnota":["czech"],"tendence":["czech"],"tenista":["czech"],"tenor":["czech"],"teplota":["czech"],"tepna":["czech"],"teprve":["czech"],"terapie":["czech"],"termoska":["czech"],"textil":["czech"],"ticho":["czech"],"tiskopis":["czech"],"titulek":["czech"],"tkadlec":["czech"],"tkanina":["czech"],"tlapka":["czech"],"tleskat":["czech"],"tlukot":["czech"],"tlupa":["czech"],"tmel":["czech"],"toaleta":["czech"],"topinka":["czech"],"topol":["czech"],"torzo":["czech"],"touha":["czech"],"toulec":["czech"],"tradice":["czech"],"traktor":["czech"],"tramp":["czech"],"trasa":["czech"],"traverza":["czech"],"trefit":["czech"],"trest":["czech"],"trezor":["czech"],"trhavina":["czech"],"trhlina":["czech"],"trochu":["czech"],"trojice":["czech"],"troska":["czech"],"trouba":["czech"],"trpce":["czech"],"trpitel":["czech"],"trpkost":["czech"],"trubec":["czech"],"truchlit":["czech"],"truhlice":["czech"],"trus":["czech"],"trvat":["czech"],"tudy":["czech"],"tuhnout":["czech"],"tuhost":["czech"],"tundra":["czech"],"turista":["czech"],"turnaj":["czech"],"tuzemsko":["czech"],"tvaroh":["czech"],"tvorba":["czech"],"tvrdost":["czech"],"tvrz":["czech"],"tygr":["czech"],"tykev":["czech"],"ubohost":["czech"],"uboze":["czech"],"ubrat":["czech"],"ubrousek":["czech"],"ubrus":["czech"],"ubytovna":["czech"],"ucho":["czech"],"uctivost":["czech"],"udivit":["czech"],"uhradit":["czech"],"ujednat":["czech"],"ujistit":["czech"],"ujmout":["czech"],"ukazatel":["czech"],"uklidnit":["czech"],"uklonit":["czech"],"ukotvit":["czech"],"ukrojit":["czech"],"ulice":["czech"],"ulita":["czech"],"ulovit":["czech"],"umyvadlo":["czech"],"unavit":["czech"],"uniforma":["czech"],"uniknout":["czech"],"upadnout":["czech"],"uplatnit":["czech"],"uplynout":["czech"],"upoutat":["czech"],"upravit":["czech"],"uran":["czech"],"urazit":["czech"],"usednout":["czech"],"usilovat":["czech"],"usmrtit":["czech"],"usnadnit":["czech"],"usnout":["czech"],"usoudit":["czech"],"ustlat":["czech"],"ustrnout":["czech"],"utahovat":["czech"],"utkat":["czech"],"utlumit":["czech"],"utonout":["czech"],"utopenec":["czech"],"utrousit":["czech"],"uvalit":["czech"],"uvolnit":["czech"],"uvozovka":["czech"],"uzdravit":["czech"],"uzel":["czech"],"uzenina":["czech"],"uzlina":["czech"],"uznat":["czech"],"vagon":["czech","turkish"],"valcha":["czech"],"valoun":["czech"],"vana":["czech"],"vandal":["czech"],"vanilka":["czech"],"varan":["czech"],"varhany":["czech"],"varovat":["czech"],"vcelku":["czech"],"vchod":["czech"],"vdova":["czech"],"vedro":["czech"],"vegetace":["czech"],"vejce":["czech"],"velbloud":["czech"],"veletrh":["czech"],"velitel":["czech"],"velmoc":["czech"],"velryba":["czech"],"venkov":["czech"],"veranda":["czech"],"verze":["czech"],"veselka":["czech"],"veskrze":["czech"],"vesnice":["czech"],"vespodu":["czech"],"vesta":["czech"],"veterina":["czech"],"veverka":["czech"],"vibrace":["czech"],"vichr":["czech"],"videohra":["czech"],"vidina":["czech"],"vidle":["czech"],"vila":["czech"],"vinice":["czech"],"viset":["czech"],"vitalita":["czech"],"vize":["czech"],"vizitka":["czech"],"vjezd":["czech"],"vklad":["czech"],"vkus":["czech"],"vlajka":["czech"],"vlak":["czech"],"vlasec":["czech"],"vlevo":["czech"],"vlhkost":["czech"],"vliv":["czech"],"vlnovka":["czech"],"vloupat":["czech"],"vnucovat":["czech"],"vnuk":["czech"],"voda":["czech"],"vodivost":["czech"],"vodoznak":["czech"],"vodstvo":["czech"],"vojensky":["czech"],"vojna":["czech"],"vojsko":["czech"],"volant":["czech"],"volba":["czech"],"volit":["czech"],"volno":["czech"],"voskovka":["czech"],"vozidlo":["czech"],"vozovna":["czech"],"vpravo":["czech"],"vrabec":["czech"],"vracet":["czech"],"vrah":["czech"],"vrata":["czech"],"vrba":["czech"],"vrcholek":["czech"],"vrhat":["czech"],"vrstva":["czech"],"vrtule":["czech"],"vsadit":["czech"],"vstoupit":["czech"],"vstup":["czech"],"vtip":["czech"],"vybavit":["czech"],"vybrat":["czech"],"vychovat":["czech"],"vydat":["czech"],"vydra":["czech"],"vyfotit":["czech"],"vyhledat":["czech"],"vyhnout":["czech"],"vyhodit":["czech"],"vyhradit":["czech"],"vyhubit":["czech"],"vyjasnit":["czech"],"vyjet":["czech"],"vyjmout":["czech"],"vyklopit":["czech"],"vykonat":["czech"],"vylekat":["czech"],"vymazat":["czech"],"vymezit":["czech"],"vymizet":["czech"],"vymyslet":["czech"],"vynechat":["czech"],"vynikat":["czech"],"vynutit":["czech"],"vypadat":["czech"],"vyplatit":["czech"],"vypravit":["czech"],"vypustit":["czech"],"vyrazit":["czech"],"vyrovnat":["czech"],"vyrvat":["czech"],"vyslovit":["czech"],"vysoko":["czech"],"vystavit":["czech"],"vysunout":["czech"],"vysypat":["czech"],"vytasit":["czech"],"vytesat":["czech"],"vytratit":["czech"],"vyvinout":["czech"],"vyvolat":["czech"],"vyvrhel":["czech"],"vyzdobit":["czech"],"vyznat":["czech"],"vzadu":["czech"],"vzbudit":["czech"],"vzchopit":["czech"],"vzdor":["czech"],"vzduch":["czech"],"vzdychat":["czech"],"vzestup":["czech"],"vzhledem":["czech"],"vzkaz":["czech"],"vzlykat":["czech"],"vznik":["czech"],"vzorek":["czech"],"vzpoura":["czech"],"vztah":["czech"],"vztek":["czech"],"xylofon":["czech"],"zabrat":["czech"],"zabydlet":["czech"],"zachovat":["czech"],"zadarmo":["czech"],"zadusit":["czech"],"zafoukat":["czech"],"zahltit":["czech"],"zahodit":["czech"],"zahrada":["czech"],"zahynout":["czech"],"zajatec":["czech"],"zajet":["czech"],"zajistit":["czech"],"zaklepat":["czech"],"zakoupit":["czech"],"zalepit":["czech"],"zamezit":["czech"],"zamotat":["czech"],"zamyslet":["czech"],"zanechat":["czech"],"zanikat":["czech"],"zaplatit":["czech"],"zapojit":["czech"],"zapsat":["czech"],"zarazit":["czech"],"zastavit":["czech"],"zasunout":["czech"],"zatajit":["czech"],"zatemnit":["czech"],"zatknout":["czech"],"zaujmout":["czech"],"zavalit":["czech"],"zavelet":["czech"],"zavinit":["czech"],"zavolat":["czech"],"zavrtat":["czech"],"zazvonit":["czech"],"zbavit":["czech"],"zbrusu":["czech"],"zbudovat":["czech"],"zbytek":["czech"],"zdaleka":["czech"],"zdarma":["czech"],"zdatnost":["czech"],"zdivo":["czech"],"zdobit":["czech"],"zdroj":["czech"],"zdvih":["czech"],"zdymadlo":["czech"],"zelenina":["czech"],"zeman":["czech"],"zemina":["czech"],"zeptat":["czech"],"zezadu":["czech"],"zezdola":["czech"],"zhatit":["czech"],"zhltnout":["czech"],"zhluboka":["czech"],"zhotovit":["czech"],"zhruba":["czech"],"zima":["czech"],"zimnice":["czech"],"zjemnit":["czech"],"zklamat":["czech"],"zkoumat":["czech"],"zkratka":["czech"],"zkumavka":["czech"],"zlato":["czech"],"zlehka":["czech"],"zloba":["czech"],"zlom":["czech"],"zlost":["czech"],"zlozvyk":["czech"],"zmapovat":["czech"],"zmar":["czech"],"zmatek":["czech"],"zmije":["czech"],"zmizet":["czech"],"zmocnit":["czech"],"zmodrat":["czech"],"zmrzlina":["czech"],"zmutovat":["czech"],"znak":["czech"],"znalost":["czech"],"znamenat":["czech"],"znovu":["czech"],"zobrazit":["czech"],"zotavit":["czech"],"zoubek":["czech"],"zoufale":["czech"],"zplodit":["czech"],"zpomalit":["czech"],"zprava":["czech"],"zprostit":["czech"],"zprudka":["czech"],"zprvu":["czech"],"zrada":["czech"],"zranit":["czech"],"zrcadlo":["czech"],"zrnitost":["czech"],"zrno":["czech"],"zrovna":["czech"],"zrychlit":["czech"],"zrzavost":["czech"],"zticha":["czech"],"ztratit":["czech"],"zubovina":["czech"],"zubr":["czech"],"zvednout":["czech"],"zvenku":["czech"],"zvesela":["czech"],"zvon":["czech"],"zvrat":["czech"],"zvukovod":["czech"],"zvyk":["czech"],"abandon":["english","french"],"ability":["english"],"able":["english"],"about":["english"],"above":["english"],"absent":["english"],"absorb":["english"],"abstract":["english"],"absurd":["english"],"abuse":["english"],"access":["english"],"accident":["english"],"account":["english"],"accuse":["english"],"achieve":["english"],"acid":["english"],"acoustic":["english"],"acquire":["english"],"across":["english"],"act":["english"],"action":["english"],"actor":["english"],"actress":["english"],"actual":["english"],"adapt":["english"],"add":["english"],"addict":["english"],"address":["english"],"adjust":["english"],"admit":["english"],"adult":["english"],"advance":["english"],"advice":["english"],"aerobic":["english"],"affair":["english"],"afford":["english"],"afraid":["english"],"again":["english"],"age":["english"],"agent":["english"],"agree":["english"],"ahead":["english"],"aim":["english"],"air":["english"],"airport":["english"],"aisle":["english"],"alarm":["english"],"album":["english"],"alcohol":["english"],"alert":["english"],"alien":["english"],"all":["english"],"alley":["english"],"allow":["english"],"almost":["english"],"alone":["english"],"alpha":["english"],"already":["english"],"also":["english"],"alter":["english"],"always":["english"],"amateur":["english","french"],"amazing":["english"],"among":["english"],"amount":["english"],"amused":["english"],"analyst":["english"],"anchor":["english"],"ancient":["english"],"anger":["english"],"angle":["english","french"],"angry":["english"],"animal":["english","french"],"ankle":["english"],"announce":["english"],"annual":["english"],"another":["english"],"answer":["english"],"antenna":["english"],"antique":["english"],"anxiety":["english"],"any":["english"],"apart":["english"],"apology":["english"],"appear":["english"],"apple":["english"],"approve":["english"],"april":["english"],"arch":["english"],"arctic":["english"],"area":["english"],"arena":["english","turkish"],"argue":["english"],"arm":["english"],"armed":["english"],"armor":["english"],"army":["english"],"around":["english"],"arrange":["english"],"arrest":["english"],"arrive":["english"],"arrow":["english"],"art":["english"],"artefact":["english"],"artist":["english","turkish"],"artwork":["english"],"ask":["english"],"aspect":["english","french"],"assault":["english"],"asset":["english"],"assist":["english"],"assume":["english"],"asthma":["english"],"athlete":["english"],"atom":["english","turkish"],"attack":["english"],"attend":["english"],"attitude":["english"],"attract":["english"],"auction":["english"],"audit":["english"],"august":["english"],"aunt":["english"],"author":["english"],"auto":["english"],"autumn":["english"],"average":["english"],"avocado":["english"],"avoid":["english"],"awake":["english"],"aware":["english"],"away":["english"],"awesome":["english"],"awful":["english"],"awkward":["english"],"axis":["english"],"baby":["english"],"bachelor":["english"],"bacon":["english"],"badge":["english","french"],"bag":["english"],"balance":["english"],"balcony":["english"],"ball":["english"],"bamboo":["english"],"banana":["english"],"banner":["english"],"bar":["english"],"barely":["english"],"bargain":["english"],"barrel":["english"],"base":["english"],"basic":["english"],"basket":["english"],"battle":["english"],"beach":["english"],"bean":["english"],"beauty":["english"],"because":["english"],"become":["english"],"beef":["english"],"before":["english"],"begin":["english"],"behave":["english"],"behind":["english"],"believe":["english"],"below":["english"],"belt":["english"],"bench":["english"],"benefit":["english"],"best":["english"],"betray":["english"],"better":["english"],"between":["english"],"beyond":["english"],"bicycle":["english","french"],"bid":["english"],"bike":["english"],"bind":["english"],"biology":["english"],"bird":["english"],"birth":["english"],"bitter":["english"],"black":["english"],"blade":["english"],"blame":["english"],"blanket":["english"],"blast":["english"],"bleak":["english"],"bless":["english"],"blind":["english"],"blood":["english"],"blossom":["english"],"blouse":["english"],"blue":["english"],"blur":["english"],"blush":["english"],"board":["english"],"boat":["english"],"body":["english"],"boil":["english"],"bomb":["english"],"bone":["english"],"bonus":["english","french"],"book":["english"],"boost":["english"],"border":["english"],"boring":["english"],"borrow":["english"],"boss":["english"],"bottom":["english"],"bounce":["english"],"box":["english"],"boy":["english"],"bracket":["english"],"brain":["english"],"brand":["english"],"brass":["english"],"brave":["english","french"],"bread":["english"],"breeze":["english"],"brick":["english"],"bridge":["english"],"brief":["english"],"bright":["english"],"bring":["english"],"brisk":["english"],"broccoli":["english"],"broken":["english"],"bronze":["english"],"broom":["english"],"brother":["english"],"brown":["english"],"brush":["english"],"bubble":["english"],"buddy":["english"],"budget":["english"],"buffalo":["english"],"build":["english"],"bulb":["english"],"bulk":["english"],"bullet":["english"],"bundle":["english"],"bunker":["english"],"burden":["english"],"burger":["english"],"burst":["english"],"bus":["english"],"business":["english"],"busy":["english"],"butter":["english"],"buyer":["english"],"buzz":["english"],"cabbage":["english"],"cabin":["english"],"cable":["english"],"cactus":["english"],"cage":["english"],"cake":["english"],"call":["english"],"calm":["english"],"camera":["english"],"camp":["english"],"can":["english"],"canal":["english","french"],"cancel":["english"],"candy":["english"],"cannon":["english"],"canoe":["english"],"canvas":["english"],"canyon":["english"],"capable":["english","french"],"capital":["english"],"captain":["english"],"car":["english"],"carbon":["english"],"card":["english"],"cargo":["english"],"carpet":["english"],"carry":["english"],"cart":["english"],"case":["english"],"cash":["english"],"casino":["english"],"castle":["english"],"casual":["english"],"cat":["english"],"catalog":["english"],"catch":["english"],"category":["english"],"cattle":["english"],"caught":["english"],"cause":["english"],"caution":["english","french"],"cave":["english"],"ceiling":["english"],"celery":["english"],"cement":["english"],"census":["english"],"century":["english"],"cereal":["english"],"certain":["english"],"chair":["english"],"chalk":["english"],"champion":["english"],"change":["english"],"chaos":["english"],"chapter":["english"],"charge":["english"],"chase":["english"],"chat":["english"],"cheap":["english"],"check":["english"],"cheese":["english"],"chef":["english"],"cherry":["english"],"chest":["english"],"chicken":["english"],"chief":["english"],"child":["english"],"chimney":["english"],"choice":["english"],"choose":["english"],"chronic":["english"],"chuckle":["english"],"chunk":["english"],"churn":["english"],"cigar":["english"],"cinnamon":["english"],"circle":["english"],"citizen":["english"],"city":["english"],"civil":["english","french"],"claim":["english"],"clap":["english"],"clarify":["english"],"claw":["english"],"clay":["english"],"clean":["english"],"clerk":["english"],"clever":["english"],"click":["english"],"client":["english","french"],"cliff":["english"],"climb":["english"],"clinic":["english"],"clip":["english"],"clock":["english"],"clog":["english"],"close":["english"],"cloth":["english"],"cloud":["english"],"clown":["english"],"club":["english"],"clump":["english"],"cluster":["english"],"clutch":["english"],"coach":["english"],"coast":["english"],"coconut":["english"],"code":["english"],"coffee":["english"],"coil":["english"],"coin":["english"],"collect":["english"],"color":["english"],"column":["english"],"combine":["english"],"come":["english"],"comfort":["english"],"comic":["english"],"common":["english"],"company":["english"],"concert":["english","french"],"conduct":["english"],"confirm":["english"],"congress":["english"],"connect":["english"],"consider":["english"],"control":["english"],"convince":["english"],"cook":["english"],"cool":["english"],"copper":["english"],"copy":["english"],"coral":["english"],"core":["english"],"corn":["english"],"correct":["english","french"],"cost":["english"],"cotton":["english"],"couch":["english"],"country":["english"],"couple":["english"],"course":["english"],"cousin":["english"],"cover":["english"],"coyote":["english","french"],"crack":["english"],"cradle":["english"],"craft":["english"],"cram":["english"],"crane":["english"],"crash":["english"],"crater":["english"],"crawl":["english"],"crazy":["english"],"cream":["english"],"credit":["english"],"creek":["english"],"crew":["english"],"cricket":["english"],"crime":["english"],"crisp":["english"],"critic":["english"],"crop":["english"],"cross":["english"],"crouch":["english"],"crowd":["english"],"crucial":["english","french"],"cruel":["english","french"],"cruise":["english"],"crumble":["english"],"crunch":["english"],"crush":["english"],"cry":["english"],"crystal":["english"],"cube":["english"],"culture":["english"],"cup":["english"],"cupboard":["english"],"curious":["english"],"current":["english"],"curtain":["english"],"curve":["english"],"cushion":["english"],"custom":["english"],"cute":["english"],"cycle":["english","french"],"dad":["english"],"damage":["english"],"damp":["english"],"dance":["english"],"danger":["english","french"],"daring":["english"],"dash":["english"],"daughter":["english"],"dawn":["english"],"day":["english"],"deal":["english"],"debate":["english"],"debris":["english"],"decade":["english"],"december":["english"],"decide":["english"],"decline":["english"],"decorate":["english"],"decrease":["english"],"deer":["english"],"defense":["english"],"define":["english"],"defy":["english"],"degree":["english"],"delay":["english"],"deliver":["english"],"demand":["english"],"demise":["english"],"denial":["english"],"dentist":["english"],"deny":["english"],"depart":["english"],"depend":["english"],"deposit":["english"],"depth":["english"],"deputy":["english"],"derive":["english"],"describe":["english"],"desert":["english"],"design":["english"],"desk":["english"],"despair":["english"],"destroy":["english"],"detail":["english"],"detect":["english"],"develop":["english"],"device":["english"],"devote":["english"],"diagram":["english"],"dial":["english"],"diamond":["english"],"diary":["english"],"dice":["english"],"diesel":["english"],"diet":["english"],"differ":["english"],"digital":["english","french"],"dignity":["english"],"dilemma":["english"],"dinner":["english"],"dinosaur":["english"],"direct":["english"],"dirt":["english"],"disagree":["english"],"discover":["english"],"disease":["english"],"dish":["english"],"dismiss":["english"],"disorder":["english"],"display":["english"],"distance":["english","french"],"divert":["english"],"divide":["english"],"divorce":["english"],"dizzy":["english"],"doctor":["english"],"document":["english"],"dog":["english"],"doll":["english"],"dolphin":["english"],"domain":["english"],"donate":["english"],"donkey":["english"],"donor":["english"],"door":["english"],"dose":["english"],"double":["english","french"],"dove":["english"],"draft":["english"],"dragon":["english","french"],"drama":["english"],"drastic":["english"],"draw":["english"],"dream":["english"],"dress":["english"],"drift":["english"],"drill":["english"],"drink":["english"],"drip":["english"],"drive":["english"],"drop":["english"],"drum":["english"],"dry":["english"],"duck":["english"],"dumb":["english"],"dune":["english"],"during":["english"],"dust":["english"],"dutch":["english"],"duty":["english"],"dwarf":["english"],"dynamic":["english"],"eager":["english"],"eagle":["english"],"early":["english"],"earn":["english"],"earth":["english"],"easily":["english"],"east":["english"],"easy":["english"],"echo":["english"],"ecology":["english"],"economy":["english"],"edge":["english"],"edit":["english"],"educate":["english"],"effort":["english","french"],"egg":["english"],"eight":["english"],"either":["english"],"elbow":["english"],"elder":["english"],"electric":["english"],"elegant":["english"],"element":["english"],"elephant":["english"],"elevator":["english"],"elite":["english"],"else":["english"],"embark":["english"],"embody":["english"],"embrace":["english"],"emerge":["english"],"emotion":["english"],"employ":["english"],"empower":["english"],"empty":["english"],"enable":["english"],"enact":["english"],"end":["english"],"endless":["english"],"endorse":["english"],"enemy":["english"],"energy":["english"],"enforce":["english"],"engage":["english"],"engine":["english"],"enhance":["english"],"enjoy":["english"],"enlist":["english"],"enough":["english"],"enrich":["english"],"enroll":["english"],"ensure":["english"],"enter":["english"],"entire":["english"],"entry":["english"],"envelope":["english"],"episode":["english"],"equal":["english"],"equip":["english"],"era":["english"],"erase":["english"],"erode":["english"],"erosion":["english"],"error":["english"],"erupt":["english"],"escape":["english"],"essay":["english"],"essence":["english","french"],"estate":["english"],"eternal":["english"],"ethics":["english"],"evidence":["english"],"evil":["english"],"evoke":["english"],"evolve":["english"],"exact":["english","french"],"example":["english"],"excess":["english"],"exchange":["english"],"excite":["english"],"exclude":["english"],"excuse":["english","french"],"execute":["english"],"exercise":["english"],"exhaust":["english"],"exhibit":["english"],"exile":["english"],"exist":["english"],"exit":["english"],"exotic":["english"],"expand":["english"],"expect":["english"],"expire":["english"],"explain":["english"],"expose":["english"],"express":["english"],"extend":["english"],"extra":["english"],"eye":["english"],"eyebrow":["english"],"fabric":["english"],"face":["english"],"faculty":["english"],"fade":["english"],"faint":["english"],"faith":["english"],"fall":["english"],"false":["english"],"fame":["english"],"family":["english"],"famous":["english"],"fan":["english"],"fancy":["english"],"fantasy":["english"],"farm":["english"],"fashion":["english"],"fat":["english"],"fatal":["english","french"],"father":["english"],"fatigue":["english","french"],"fault":["english"],"favorite":["english"],"feature":["english"],"february":["english"],"federal":["english","turkish"],"fee":["english"],"feed":["english"],"feel":["english"],"female":["english"],"fence":["english"],"festival":["english","french","turkish"],"fetch":["english"],"fever":["english"],"few":["english"],"fiber":["english"],"fiction":["english"],"field":["english"],"figure":["english","french"],"file":["english"],"film":["english"],"filter":["english"],"final":["english"],"find":["english"],"fine":["english"],"finger":["english"],"finish":["english"],"fire":["english"],"firm":["english"],"first":["english"],"fiscal":["english"],"fish":["english"],"fit":["english"],"fitness":["english"],"fix":["english"],"flag":["english"],"flame":["english"],"flash":["english"],"flat":["english"],"flavor":["english"],"flee":["english"],"flight":["english"],"flip":["english"],"float":["english"],"flock":["english"],"floor":["english"],"flower":["english"],"fluid":["english"],"flush":["english"],"fly":["english"],"foam":["english"],"focus":["english"],"fog":["english"],"foil":["english"],"fold":["english"],"follow":["english"],"food":["english"],"foot":["english"],"force":["english"],"forest":["english"],"forget":["english"],"fork":["english"],"fortune":["english","french"],"forum":["english"],"forward":["english"],"fossil":["english"],"foster":["english"],"found":["english"],"fox":["english"],"fragile":["english","french"],"frame":["english"],"frequent":["english"],"fresh":["english"],"friend":["english"],"fringe":["english"],"frog":["english"],"front":["english"],"frost":["english"],"frown":["english"],"frozen":["english"],"fruit":["english","french"],"fuel":["english"],"fun":["english"],"funny":["english"],"furnace":["english"],"fury":["english"],"future":["english"],"gadget":["english"],"gain":["english"],"galaxy":["english"],"gallery":["english"],"game":["english"],"gap":["english"],"garage":["english"],"garbage":["english"],"garden":["english"],"garlic":["english"],"garment":["english"],"gas":["english"],"gasp":["english"],"gate":["english"],"gather":["english"],"gauge":["english"],"gaze":["english"],"general":["english"],"genius":["english"],"genre":["english"],"gentle":["english"],"genuine":["english"],"gesture":["english"],"ghost":["english"],"giant":["english"],"gift":["english"],"giggle":["english"],"ginger":["english"],"giraffe":["english"],"girl":["english"],"give":["english"],"glad":["english"],"glance":["english"],"glare":["english"],"glass":["english"],"glide":["english"],"glimpse":["english"],"globe":["english","french"],"gloom":["english"],"glory":["english"],"glove":["english"],"glow":["english"],"glue":["english"],"goat":["english"],"goddess":["english"],"gold":["english"],"good":["english"],"goose":["english"],"gorilla":["english"],"gospel":["english"],"gossip":["english"],"govern":["english"],"gown":["english"],"grab":["english"],"grace":["english"],"grain":["english"],"grant":["english"],"grape":["english"],"grass":["english"],"gravity":["english"],"great":["english"],"green":["english"],"grid":["english"],"grief":["english"],"grit":["english"],"grocery":["english"],"group":["english"],"grow":["english"],"grunt":["english"],"guard":["english"],"guess":["english"],"guide":["english","french"],"guilt":["english"],"guitar":["english"],"gun":["english"],"gym":["english"],"habit":["english"],"hair":["english"],"half":["english"],"hammer":["english"],"hamster":["english"],"hand":["english"],"happy":["english"],"harbor":["english"],"hard":["english"],"harsh":["english"],"harvest":["english"],"hat":["english"],"have":["english"],"hawk":["english"],"hazard":["english"],"head":["english"],"health":["english"],"heart":["english"],"heavy":["english"],"hedgehog":["english"],"height":["english"],"hello":["english"],"helmet":["english"],"help":["english"],"hen":["english"],"hero":["english"],"hidden":["english"],"high":["english"],"hill":["english"],"hint":["english"],"hip":["english"],"hire":["english"],"history":["english"],"hobby":["english"],"hockey":["english"],"hold":["english"],"hole":["english"],"holiday":["english"],"hollow":["english"],"home":["english"],"honey":["english"],"hood":["english"],"hope":["english"],"horn":["english"],"horror":["english"],"horse":["english"],"hospital":["english"],"host":["english"],"hotel":["english"],"hour":["english"],"hover":["english"],"hub":["english"],"huge":["english"],"human":["english"],"humble":["english","french"],"humor":["english"],"hundred":["english"],"hungry":["english"],"hunt":["english"],"hurdle":["english"],"hurry":["english"],"hurt":["english"],"husband":["english"],"hybrid":["english"],"ice":["english"],"icon":["english"],"idea":["english"],"identify":["english"],"idle":["english"],"ignore":["english"],"ill":["english"],"illegal":["english"],"illness":["english"],"image":["english","french"],"imitate":["english"],"immense":["english","french"],"immune":["english"],"impact":["english","french"],"impose":["english"],"improve":["english"],"impulse":["english"],"inch":["english"],"include":["english"],"income":["english"],"increase":["english"],"index":["english"],"indicate":["english"],"indoor":["english"],"industry":["english"],"infant":["english"],"inflict":["english"],"inform":["english"],"inhale":["english"],"inherit":["english"],"initial":["english"],"inject":["english"],"injury":["english"],"inmate":["english"],"inner":["english"],"innocent":["english","french"],"input":["english"],"inquiry":["english"],"insane":["english"],"insect":["english"],"inside":["english"],"inspire":["english"],"install":["english"],"intact":["english","french"],"interest":["english"],"into":["english"],"invest":["english"],"invite":["english"],"involve":["english"],"iron":["english"],"island":["english"],"isolate":["english"],"issue":["english"],"item":["english"],"ivory":["english"],"jacket":["english"],"jaguar":["english","french"],"jar":["english"],"jazz":["english"],"jealous":["english"],"jeans":["english"],"jelly":["english"],"jewel":["english"],"job":["english"],"join":["english"],"joke":["english"],"journey":["english"],"joy":["english"],"judge":["english"],"juice":["english"],"jump":["english"],"jungle":["english"],"junior":["english","french"],"junk":["english"],"just":["english"],"kangaroo":["english"],"keen":["english"],"keep":["english"],"ketchup":["english"],"key":["english"],"kick":["english"],"kid":["english"],"kidney":["english"],"kind":["english"],"kingdom":["english"],"kiss":["english"],"kit":["english"],"kitchen":["english"],"kite":["english"],"kitten":["english"],"kiwi":["english"],"knee":["english"],"knife":["english"],"knock":["english"],"know":["english"],"lab":["english"],"label":["english","french"],"labor":["english"],"ladder":["english"],"lady":["english"],"lake":["english"],"lamp":["english"],"language":["english"],"laptop":["english"],"large":["english"],"later":["english"],"latin":["english"],"laugh":["english"],"laundry":["english"],"lava":["english"],"law":["english"],"lawn":["english"],"lawsuit":["english"],"layer":["english"],"lazy":["english"],"leader":["english"],"leaf":["english"],"learn":["english"],"leave":["english"],"lecture":["english","french"],"left":["english"],"leg":["english"],"legal":["english"],"legend":["english"],"leisure":["english"],"lemon":["english"],"lend":["english"],"length":["english"],"lens":["english"],"leopard":["english"],"lesson":["english"],"letter":["english"],"level":["english"],"liar":["english"],"liberty":["english"],"library":["english"],"license":["english"],"life":["english"],"lift":["english"],"light":["english"],"like":["english"],"limb":["english"],"limit":["english"],"link":["english"],"lion":["english"],"liquid":["english"],"list":["english"],"little":["english"],"live":["english"],"lizard":["english"],"load":["english"],"loan":["english"],"lobster":["english"],"local":["english"],"lock":["english"],"logic":["english"],"lonely":["english"],"long":["english"],"loop":["english"],"lottery":["english"],"loud":["english"],"lounge":["english"],"love":["english"],"loyal":["english","french"],"lucky":["english"],"luggage":["english"],"lumber":["english"],"lunar":["english"],"lunch":["english"],"luxury":["english"],"lyrics":["english"],"machine":["english","french"],"mad":["english"],"magic":["english"],"magnet":["english"],"maid":["english"],"mail":["english"],"main":["english"],"major":["english"],"make":["english"],"mammal":["english"],"man":["english"],"manage":["english"],"mandate":["english"],"mango":["english"],"mansion":["english"],"manual":["english"],"maple":["english"],"marble":["english"],"march":["english"],"margin":["english"],"marine":["english"],"market":["english","turkish"],"marriage":["english"],"mask":["english"],"mass":["english"],"master":["english"],"match":["english"],"material":["english"],"math":["english"],"matrix":["english"],"matter":["english"],"maximum":["english"],"maze":["english"],"meadow":["english"],"mean":["english"],"measure":["english"],"meat":["english"],"mechanic":["english"],"medal":["english"],"media":["english"],"melody":["english"],"melt":["english"],"member":["english"],"memory":["english"],"mention":["english"],"menu":["english"],"mercy":["english"],"merge":["english"],"merit":["english"],"merry":["english"],"mesh":["english"],"message":["english"],"metal":["english"],"method":["english"],"middle":["english"],"midnight":["english"],"milk":["english"],"million":["english","french"],"mimic":["english"],"mind":["english"],"minimum":["english"],"minor":["english"],"minute":["english","french"],"miracle":["english","french"],"mirror":["english"],"misery":["english"],"miss":["english"],"mistake":["english"],"mix":["english"],"mixed":["english"],"mixture":["english"],"mobile":["english","french"],"model":["english","turkish"],"modify":["english"],"mom":["english"],"moment":["english"],"monitor":["english"],"monkey":["english"],"monster":["english"],"month":["english"],"moon":["english"],"moral":["english"],"more":["english"],"morning":["english"],"mosquito":["english"],"mother":["english"],"motion":["english"],"motor":["english","turkish"],"mountain":["english"],"mouse":["english"],"move":["english"],"movie":["english"],"much":["english"],"muffin":["english"],"mule":["english"],"multiply":["english"],"muscle":["english","french"],"museum":["english"],"mushroom":["english"],"music":["english"],"must":["english"],"mutual":["english"],"myself":["english"],"mystery":["english"],"myth":["english"],"naive":["english"],"name":["english"],"napkin":["english"],"narrow":["english"],"nasty":["english"],"nation":["english","french"],"nature":["english","french"],"near":["english"],"neck":["english"],"need":["english"],"negative":["english"],"neglect":["english"],"neither":["english"],"nephew":["english"],"nerve":["english"],"nest":["english"],"net":["english"],"network":["english"],"neutral":["english"],"never":["english"],"news":["english"],"next":["english"],"nice":["english"],"night":["english"],"noble":["english","french"],"noise":["english"],"nominee":["english"],"noodle":["english"],"normal":["english","turkish"],"north":["english"],"nose":["english"],"notable":["english","french"],"note":["english"],"nothing":["english"],"notice":["english"],"novel":["english"],"now":["english"],"nuclear":["english"],"number":["english"],"nurse":["english"],"nut":["english"],"oak":["english"],"obey":["english"],"object":["english"],"oblige":["english"],"obscure":["english"],"observe":["english"],"obtain":["english"],"obvious":["english"],"occur":["english"],"ocean":["english"],"october":["english"],"odor":["english"],"off":["english"],"offer":["english"],"office":["english"],"often":["english"],"oil":["english"],"okay":["english"],"old":["english"],"olive":["english"],"olympic":["english"],"omit":["english"],"once":["english"],"one":["english"],"onion":["english"],"online":["english"],"only":["english"],"open":["english"],"opera":["english","turkish"],"opinion":["english","french"],"oppose":["english"],"option":["english"],"orange":["english","french"],"orbit":["english"],"orchard":["english"],"order":["english"],"ordinary":["english"],"organ":["english"],"orient":["english"],"original":["english"],"orphan":["english"],"ostrich":["english"],"other":["english"],"outdoor":["english"],"outer":["english"],"output":["english"],"outside":["english"],"oval":["english"],"oven":["english"],"over":["english"],"own":["english"],"owner":["english"],"oxygen":["english"],"oyster":["english"],"ozone":["english","french"],"pact":["english"],"paddle":["english"],"page":["english"],"pair":["english"],"palace":["english","french"],"palm":["english"],"panda":["english","french","turkish"],"panel":["english","turkish"],"panic":["english"],"panther":["english"],"paper":["english"],"parade":["english"],"parent":["english"],"park":["english"],"parrot":["english"],"party":["english"],"pass":["english"],"patch":["english"],"path":["english"],"patient":["english"],"patrol":["english"],"pattern":["english"],"pause":["english"],"pave":["english"],"payment":["english"],"peace":["english"],"peanut":["english"],"pear":["english"],"peasant":["english"],"pelican":["english"],"pen":["english"],"penalty":["english"],"pencil":["english"],"people":["english"],"pepper":["english"],"perfect":["english"],"permit":["english"],"person":["english"],"pet":["english"],"phone":["english"],"photo":["english"],"phrase":["english","french"],"physical":["english"],"piano":["english","french"],"picnic":["english"],"picture":["english"],"piece":["english"],"pig":["english"],"pigeon":["english"],"pill":["english"],"pilot":["english","turkish"],"pink":["english"],"pioneer":["english"],"pipe":["english"],"pistol":["english"],"pitch":["english"],"pizza":["english","french"],"place":["english"],"planet":["english"],"plastic":["english"],"plate":["english"],"play":["english"],"please":["english"],"pledge":["english"],"pluck":["english"],"plug":["english"],"plunge":["english"],"poem":["english"],"poet":["english"],"point":["english"],"polar":["english"],"pole":["english"],"police":["english"],"pond":["english"],"pony":["english"],"pool":["english"],"popular":["english"],"portion":["english"],"position":["english","french"],"possible":["english"],"post":["english"],"potato":["english"],"pottery":["english"],"poverty":["english"],"powder":["english"],"power":["english"],"practice":["english"],"praise":["english"],"predict":["english"],"prefer":["english"],"prepare":["english"],"present":["english"],"pretty":["english"],"prevent":["english"],"price":["english"],"pride":["english"],"primary":["english"],"print":["english"],"priority":["english"],"prison":["english","french"],"private":["english"],"prize":["english"],"problem":["english","turkish"],"process":["english"],"produce":["english"],"profit":["english"],"program":["english","turkish"],"project":["english"],"promote":["english"],"proof":["english"],"property":["english"],"prosper":["english"],"protect":["english"],"proud":["english"],"provide":["english"],"public":["english","french"],"pudding":["english"],"pull":["english"],"pulp":["english"],"pulse":["english"],"pumpkin":["english"],"punch":["english"],"pupil":["english"],"puppy":["english"],"purchase":["english"],"purity":["english"],"purpose":["english"],"purse":["english"],"push":["english"],"put":["english"],"puzzle":["english","french"],"pyramid":["english"],"quality":["english"],"quantum":["english"],"quarter":["english"],"question":["english","french"],"quick":["english"],"quit":["english"],"quiz":["english"],"quote":["english"],"rabbit":["english"],"raccoon":["english"],"race":["english"],"rack":["english"],"radar":["english","turkish"],"radio":["english"],"rail":["english"],"rain":["english"],"raise":["english"],"rally":["english"],"ramp":["english"],"ranch":["english"],"random":["english"],"range":["english"],"rapid":["english"],"rare":["english"],"rate":["english"],"rather":["english"],"raven":["english"],"raw":["english"],"razor":["english"],"ready":["english"],"real":["english"],"reason":["english"],"rebel":["english"],"rebuild":["english"],"recall":["english"],"receive":["english"],"recipe":["english"],"record":["english"],"recycle":["english"],"reduce":["english"],"reflect":["english"],"reform":["english","turkish"],"refuse":["english"],"region":["english"],"regret":["english"],"regular":["english"],"reject":["english"],"relax":["english"],"release":["english"],"relief":["english","french"],"rely":["english"],"remain":["english"],"remember":["english"],"remind":["english"],"remove":["english"],"render":["english"],"renew":["english"],"rent":["english"],"reopen":["english"],"repair":["english"],"repeat":["english"],"replace":["english"],"report":["english"],"require":["english"],"rescue":["english"],"resemble":["english"],"resist":["english"],"resource":["english"],"response":["english"],"result":["english"],"retire":["english"],"retreat":["english"],"return":["english"],"reunion":["english"],"reveal":["english"],"review":["english"],"reward":["english"],"rhythm":["english"],"rib":["english"],"ribbon":["english"],"rice":["english"],"rich":["english"],"ride":["english"],"ridge":["english"],"rifle":["english"],"right":["english"],"rigid":["english"],"ring":["english"],"riot":["english"],"ripple":["english"],"risk":["english"],"ritual":["english"],"rival":["english","french"],"river":["english"],"road":["english"],"roast":["english"],"robot":["english","turkish"],"robust":["english"],"rocket":["english"],"romance":["english","french"],"roof":["english"],"rookie":["english"],"room":["english"],"rose":["english"],"rotate":["english"],"rough":["english"],"round":["english"],"route":["english"],"royal":["english"],"rubber":["english"],"rude":["english"],"rug":["english"],"rule":["english"],"run":["english"],"runway":["english"],"rural":["english"],"sad":["english"],"saddle":["english"],"sadness":["english"],"safe":["english"],"sail":["english"],"salad":["english"],"salmon":["english"],"salon":["english","french","turkish"],"salt":["english"],"salute":["english"],"same":["english"],"sample":["english"],"sand":["english"],"satisfy":["english"],"satoshi":["english"],"sauce":["english"],"sausage":["english"],"save":["english"],"say":["english"],"scale":["english"],"scan":["english"],"scare":["english"],"scatter":["english"],"scene":["english"],"scheme":["english"],"school":["english"],"science":["english","french"],"scissors":["english"],"scorpion":["english"],"scout":["english"],"scrap":["english"],"screen":["english"],"script":["english"],"scrub":["english"],"sea":["english"],"search":["english"],"season":["english"],"seat":["english"],"second":["english"],"secret":["english"],"section":["english"],"security":["english"],"seed":["english"],"seek":["english"],"segment":["english"],"select":["english"],"sell":["english"],"seminar":["english"],"senior":["english"],"sense":["english"],"sentence":["english","french"],"series":["english"],"service":["english","french"],"session":["english"],"settle":["english"],"setup":["english"],"seven":["english"],"shadow":["english"],"shaft":["english"],"shallow":["english"],"share":["english"],"shed":["english"],"shell":["english"],"sheriff":["english"],"shield":["english"],"shift":["english"],"shine":["english"],"ship":["english"],"shiver":["english"],"shock":["english"],"shoe":["english"],"shoot":["english"],"shop":["english"],"short":["english"],"shoulder":["english"],"shove":["english"],"shrimp":["english"],"shrug":["english"],"shuffle":["english"],"shy":["english"],"sibling":["english"],"sick":["english"],"side":["english"],"siege":["english"],"sight":["english"],"sign":["english"],"silent":["english"],"silk":["english"],"silly":["english"],"silver":["english"],"similar":["english"],"simple":["english","french"],"since":["english"],"sing":["english"],"siren":["english"],"sister":["english"],"situate":["english"],"six":["english"],"size":["english"],"skate":["english"],"sketch":["english"],"ski":["english"],"skill":["english"],"skin":["english"],"skirt":["english"],"skull":["english"],"slab":["english"],"slam":["english"],"sleep":["english"],"slender":["english"],"slice":["english"],"slide":["english"],"slight":["english"],"slim":["english"],"slogan":["english","turkish"],"slot":["english"],"slow":["english"],"slush":["english"],"small":["english"],"smart":["english"],"smile":["english"],"smoke":["english"],"smooth":["english"],"snack":["english"],"snake":["english"],"snap":["english"],"sniff":["english"],"snow":["english"],"soap":["english"],"soccer":["english"],"social":["english","french"],"sock":["english"],"soda":["english"],"soft":["english"],"solar":["english"],"soldier":["english"],"solid":["english"],"solution":["english"],"solve":["english"],"someone":["english"],"song":["english"],"soon":["english"],"sorry":["english"],"sort":["english"],"soul":["english"],"sound":["english"],"soup":["english"],"source":["english","french"],"south":["english"],"space":["english"],"spare":["english"],"spatial":["english","french"],"spawn":["english"],"speak":["english"],"special":["english"],"speed":["english"],"spell":["english"],"spend":["english"],"sphere":["english"],"spice":["english"],"spider":["english"],"spike":["english"],"spin":["english"],"spirit":["english"],"split":["english"],"spoil":["english"],"sponsor":["english","turkish"],"spoon":["english"],"sport":["english"],"spot":["english"],"spray":["english"],"spread":["english"],"spring":["english"],"spy":["english"],"square":["english"],"squeeze":["english"],"squirrel":["english"],"stable":["english","french"],"stadium":["english"],"staff":["english"],"stage":["english"],"stairs":["english"],"stamp":["english"],"stand":["english"],"start":["english"],"state":["english"],"stay":["english"],"steak":["english"],"steel":["english"],"stem":["english"],"step":["english"],"stereo":["english"],"stick":["english"],"still":["english"],"sting":["english"],"stock":["english"],"stomach":["english"],"stone":["english"],"stool":["english"],"story":["english"],"stove":["english"],"strategy":["english"],"street":["english"],"strike":["english"],"strong":["english"],"struggle":["english"],"student":["english"],"stuff":["english"],"stumble":["english"],"style":["english"],"subject":["english"],"submit":["english"],"subway":["english"],"success":["english"],"such":["english"],"sudden":["english"],"suffer":["english"],"sugar":["english"],"suggest":["english"],"suit":["english"],"summer":["english"],"sun":["english"],"sunny":["english"],"sunset":["english"],"super":["english"],"supply":["english"],"supreme":["english"],"sure":["english"],"surface":["english","french"],"surge":["english"],"surprise":["english","french"],"surround":["english"],"survey":["english"],"suspect":["english","french"],"sustain":["english"],"swallow":["english"],"swamp":["english"],"swap":["english"],"swarm":["english"],"swear":["english"],"sweet":["english"],"swift":["english"],"swim":["english"],"swing":["english"],"switch":["english"],"sword":["english"],"symbol":["english"],"symptom":["english"],"syrup":["english"],"system":["english"],"table":["english"],"tackle":["english"],"tag":["english"],"tail":["english"],"talent":["english","french"],"talk":["english"],"tank":["english"],"tape":["english"],"target":["english"],"task":["english"],"taste":["english"],"tattoo":["english"],"taxi":["english"],"teach":["english"],"team":["english"],"tell":["english"],"ten":["english"],"tenant":["english"],"tennis":["english"],"tent":["english"],"term":["english"],"test":["english"],"text":["english"],"thank":["english"],"that":["english"],"theme":["english"],"then":["english"],"theory":["english"],"there":["english"],"they":["english"],"thing":["english"],"this":["english"],"thought":["english"],"three":["english"],"thrive":["english"],"throw":["english"],"thumb":["english"],"thunder":["english"],"ticket":["english"],"tide":["english"],"tiger":["english"],"tilt":["english"],"timber":["english"],"time":["english"],"tiny":["english"],"tip":["english"],"tired":["english"],"tissue":["english"],"title":["english"],"toast":["english"],"tobacco":["english"],"today":["english"],"toddler":["english"],"toe":["english"],"together":["english"],"toilet":["english"],"token":["english"],"tomato":["english"],"tomorrow":["english"],"tone":["english"],"tongue":["english"],"tonight":["english"],"tool":["english"],"tooth":["english"],"top":["english"],"topic":["english"],"topple":["english"],"torch":["english"],"tornado":["english"],"tortoise":["english"],"toss":["english"],"total":["english"],"tourist":["english"],"toward":["english"],"tower":["english"],"town":["english"],"toy":["english"],"track":["english"],"trade":["english"],"traffic":["english"],"tragic":["english"],"train":["english","french"],"transfer":["english","turkish"],"trap":["english"],"trash":["english"],"travel":["english"],"tray":["english"],"treat":["english"],"tree":["english"],"trend":["english"],"trial":["english"],"tribe":["english"],"trick":["english"],"trigger":["english"],"trim":["english"],"trip":["english"],"trophy":["english"],"trouble":["english"],"truck":["english"],"true":["english"],"truly":["english"],"trumpet":["english"],"trust":["english"],"truth":["english"],"try":["english"],"tube":["english"],"tuition":["english"],"tumble":["english"],"tuna":["english"],"tunnel":["english","french"],"turkey":["english"],"turn":["english"],"turtle":["english"],"twelve":["english"],"twenty":["english"],"twice":["english"],"twin":["english"],"twist":["english"],"two":["english"],"type":["english"],"typical":["english"],"ugly":["english"],"umbrella":["english"],"unable":["english"],"unaware":["english"],"uncle":["english"],"uncover":["english"],"under":["english"],"undo":["english"],"unfair":["english"],"unfold":["english"],"unhappy":["english"],"uniform":["english"],"unique":["english","french"],"unit":["english"],"universe":["english"],"unknown":["english"],"unlock":["english"],"until":["english"],"unusual":["english"],"unveil":["english"],"update":["english"],"upgrade":["english"],"uphold":["english"],"upon":["english"],"upper":["english"],"upset":["english"],"urban":["english"],"urge":["english"],"usage":["english","french"],"use":["english"],"used":["english"],"useful":["english"],"useless":["english"],"usual":["english"],"utility":["english"],"vacant":["english"],"vacuum":["english"],"vague":["english","french"],"valid":["english"],"valley":["english"],"valve":["english","french"],"van":["english"],"vanish":["english"],"vapor":["english"],"various":["english"],"vast":["english"],"vault":["english"],"vehicle":["english"],"velvet":["english"],"vendor":["english"],"venture":["english"],"venue":["english"],"verb":["english"],"verify":["english"],"version":["english"],"very":["english"],"vessel":["english"],"veteran":["english"],"viable":["english"],"vibrant":["english"],"vicious":["english"],"victory":["english"],"video":["english"],"view":["english"],"village":["english","french"],"vintage":["english"],"violin":["english"],"virtual":["english"],"virus":["english","french"],"visa":["english"],"visit":["english"],"visual":["english"],"vital":["english","french"],"vivid":["english"],"vocal":["english"],"voice":["english"],"void":["english"],"volcano":["english"],"volume":["english","french"],"vote":["english"],"voyage":["english","french"],"wage":["english"],"wagon":["english","french"],"wait":["english"],"walk":["english"],"wall":["english"],"walnut":["english"],"want":["english"],"warfare":["english"],"warm":["english"],"warrior":["english"],"wash":["english"],"wasp":["english"],"waste":["english"],"water":["english"],"wave":["english"],"way":["english"],"wealth":["english"],"weapon":["english"],"wear":["english"],"weasel":["english"],"weather":["english"],"web":["english"],"wedding":["english"],"weekend":["english"],"weird":["english"],"welcome":["english"],"west":["english"],"wet":["english"],"whale":["english"],"what":["english"],"wheat":["english"],"wheel":["english"],"when":["english"],"where":["english"],"whip":["english"],"whisper":["english"],"wide":["english"],"width":["english"],"wife":["english"],"wild":["english"],"will":["english"],"win":["english"],"window":["english"],"wine":["english"],"wing":["english"],"wink":["english"],"winner":["english"],"winter":["english"],"wire":["english"],"wisdom":["english"],"wise":["english"],"wish":["english"],"witness":["english"],"wolf":["english"],"woman":["english"],"wonder":["english"],"wood":["english"],"wool":["english"],"word":["english"],"work":["english"],"world":["english"],"worry":["english"],"worth":["english"],"wrap":["english"],"wreck":["english"],"wrestle":["english"],"wrist":["english"],"write":["english"],"wrong":["english"],"yard":["english"],"year":["english"],"yellow":["english"],"you":["english"],"young":["english"],"youth":["english"],"zebra":["english"],"zero":["english"],"zone":["english"],"zoo":["english"],"abaisser":["french"],"abdiquer":["french"],"abeille":["french"],"abolir":["french"],"aborder":["french"],"aboutir":["french"],"aboyer":["french"],"abrasif":["french"],"abreuver":["french"],"abriter":["french"],"abroger":["french"],"abrupt":["french"],"absence":["french"],"absolu":["french"],"absurde":["french"],"abusif":["french"],"abyssal":["french"],"académie":["french"],"acajou":["french"],"acarien":["french"],"accabler":["french"],"accepter":["french"],"acclamer":["french"],"accolade":["french"],"accroche":["french"],"accuser":["french"],"acerbe":["french"],"achat":["french"],"acheter":["french"],"aciduler":["french"],"acier":["french"],"acompte":["french"],"acquérir":["french"],"acronyme":["french"],"acteur":["french"],"actif":["french"],"actuel":["french"],"adepte":["french"],"adéquat":["french"],"adhésif":["french"],"adjectif":["french"],"adjuger":["french"],"admettre":["french"],"admirer":["french"],"adopter":["french"],"adorer":["french"],"adoucir":["french"],"adresse":["french"],"adroit":["french"],"adulte":["french"],"adverbe":["french"],"aérer":["french"],"aéronef":["french"],"affaire":["french"],"affecter":["french"],"affiche":["french"],"affreux":["french"],"affubler":["french"],"agacer":["french"],"agencer":["french"],"agile":["french"],"agiter":["french"],"agrafer":["french"],"agréable":["french"],"agrume":["french"],"aider":["french"],"aiguille":["french"],"ailier":["french"],"aimable":["french"],"aisance":["french"],"ajouter":["french"],"ajuster":["french"],"alarmer":["french"],"alchimie":["french"],"alerte":["french"],"algèbre":["french"],"algue":["french"],"aliéner":["french"],"aliment":["french"],"alléger":["french"],"alliage":["french"],"allouer":["french"],"allumer":["french"],"alourdir":["french"],"alpaga":["french"],"altesse":["french"],"alvéole":["french"],"ambigu":["french"],"ambre":["french"],"aménager":["french"],"amertume":["french"],"amidon":["french"],"amiral":["french"],"amorcer":["french"],"amour":["french"],"amovible":["french"],"amphibie":["french"],"ampleur":["french"],"amusant":["french"],"analyse":["french"],"anaphore":["french"],"anarchie":["french"],"anatomie":["french"],"ancien":["french"],"anéantir":["french"],"angoisse":["french"],"anguleux":["french"],"annexer":["french"],"annonce":["french"],"annuel":["french"],"anodin":["french"],"anomalie":["french"],"anonyme":["french"],"anormal":["french"],"antenne":["french"],"antidote":["french"],"anxieux":["french"],"apaiser":["french"],"apéritif":["french"],"aplanir":["french"],"apologie":["french"],"appareil":["french"],"appeler":["french"],"apporter":["french"],"appuyer":["french"],"aquarium":["french"],"aqueduc":["french"],"arbitre":["french"],"arbuste":["french"],"ardeur":["french"],"ardoise":["french"],"argent":["french"],"arlequin":["french"],"armature":["french"],"armement":["french"],"armoire":["french"],"armure":["french"],"arpenter":["french"],"arracher":["french"],"arriver":["french"],"arroser":["french"],"arsenic":["french"],"artériel":["french"],"article":["french"],"asphalte":["french"],"aspirer":["french"],"assaut":["french"],"asservir":["french"],"assiette":["french"],"associer":["french"],"assurer":["french"],"asticot":["french"],"astre":["french"],"astuce":["french"],"atelier":["french"],"atome":["french"],"atrium":["french"],"atroce":["french"],"attaque":["french"],"attentif":["french"],"attirer":["french"],"attraper":["french"],"aubaine":["french"],"auberge":["french"],"audace":["french"],"audible":["french"],"augurer":["french"],"aurore":["french"],"automne":["french"],"autruche":["french"],"avaler":["french"],"avancer":["french"],"avarice":["french"],"avenir":["french"],"averse":["french"],"aveugle":["french"],"aviateur":["french"],"avide":["french"],"avion":["french"],"aviser":["french"],"avoine":["french"],"avouer":["french"],"avril":["french"],"axial":["french"],"axiome":["french"],"bafouer":["french"],"bagage":["french"],"baguette":["french"],"baignade":["french"],"balancer":["french"],"balcon":["french"],"baleine":["french"],"balisage":["french"],"bambin":["french"],"bancaire":["french"],"bandage":["french"],"banlieue":["french"],"bannière":["french"],"banquier":["french"],"barbier":["french"],"baril":["french"],"baron":["french"],"barque":["french"],"barrage":["french"],"bassin":["french"],"bastion":["french"],"bataille":["french"],"bateau":["french"],"batterie":["french"],"baudrier":["french"],"bavarder":["french"],"belette":["french"],"bélier":["french"],"belote":["french"],"bénéfice":["french"],"berceau":["french"],"berger":["french"],"berline":["french"],"bermuda":["french","turkish"],"besace":["french"],"besogne":["french"],"bétail":["french"],"beurre":["french"],"biberon":["french"],"bidule":["french"],"bijou":["french"],"bilan":["french"],"bilingue":["french"],"billard":["french"],"binaire":["french"],"biologie":["french"],"biopsie":["french"],"biotype":["french"],"biscuit":["french"],"bison":["french"],"bistouri":["french"],"bitume":["french"],"bizarre":["french"],"blafard":["french"],"blague":["french"],"blanchir":["french"],"blessant":["french"],"blinder":["french"],"blond":["french"],"bloquer":["french"],"blouson":["french"],"bobard":["french"],"bobine":["french"],"boire":["french"],"boiser":["french"],"bolide":["french"],"bonbon":["french"],"bondir":["french"],"bonheur":["french"],"bonifier":["french"],"bordure":["french"],"borne":["french"],"botte":["french"],"boucle":["french"],"boueux":["french"],"bougie":["french"],"boulon":["french"],"bouquin":["french"],"bourse":["french"],"boussole":["french"],"boutique":["french"],"boxeur":["french"],"branche":["french"],"brasier":["french"],"brebis":["french"],"brèche":["french"],"breuvage":["french"],"bricoler":["french"],"brigade":["french"],"brillant":["french"],"brioche":["french"],"brique":["french"],"brochure":["french"],"broder":["french"],"bronzer":["french"],"brousse":["french"],"broyeur":["french"],"brume":["french"],"brusque":["french"],"brutal":["french"],"bruyant":["french"],"buffle":["french"],"buisson":["french"],"bulletin":["french"],"bureau":["french"],"burin":["french"],"bustier":["french"],"butiner":["french"],"butoir":["french"],"buvable":["french"],"buvette":["french"],"cabanon":["french"],"cabine":["french"],"cachette":["french"],"cadeau":["french"],"cadre":["french"],"caféine":["french"],"caillou":["french"],"caisson":["french"],"calculer":["french"],"calepin":["french"],"calibre":["french"],"calmer":["french"],"calomnie":["french"],"calvaire":["french"],"camarade":["french"],"caméra":["french"],"camion":["french"],"campagne":["french"],"caneton":["french"],"canon":["french"],"cantine":["french"],"canular":["french"],"caporal":["french"],"caprice":["french"],"capsule":["french"],"capter":["french"],"capuche":["french"],"carabine":["french"],"carbone":["french"],"caresser":["french"],"caribou":["french"],"carnage":["french"],"carotte":["french"],"carreau":["french"],"carton":["french"],"cascade":["french"],"casier":["french"],"casque":["french"],"cassure":["french"],"causer":["french"],"cavalier":["french"],"caverne":["french"],"caviar":["french"],"cédille":["french"],"ceinture":["french"],"céleste":["french"],"cellule":["french"],"cendrier":["french"],"censurer":["french"],"central":["french"],"cercle":["french"],"cérébral":["french"],"cerise":["french"],"cerner":["french"],"cerveau":["french"],"cesser":["french"],"chagrin":["french"],"chaise":["french"],"chaleur":["french"],"chambre":["french"],"chance":["french"],"chapitre":["french"],"charbon":["french"],"chasseur":["french"],"chaton":["french"],"chausson":["french"],"chavirer":["french"],"chemise":["french"],"chenille":["french"],"chéquier":["french"],"chercher":["french"],"cheval":["french"],"chien":["french"],"chiffre":["french"],"chignon":["french"],"chimère":["french"],"chiot":["french"],"chlorure":["french"],"chocolat":["french"],"choisir":["french"],"chose":["french"],"chouette":["french"],"chrome":["french"],"chute":["french"],"cigare":["french"],"cigogne":["french"],"cimenter":["french"],"cinéma":["french"],"cintrer":["french"],"circuler":["french"],"cirer":["french"],"cirque":["french"],"citerne":["french"],"citoyen":["french"],"citron":["french"],"clairon":["french"],"clameur":["french"],"claquer":["french"],"classe":["french"],"clavier":["french"],"cligner":["french"],"climat":["french"],"clivage":["french"],"cloche":["french"],"clonage":["french"],"cloporte":["french"],"cobalt":["french"],"cobra":["french"],"cocasse":["french"],"cocotier":["french"],"coder":["french"],"codifier":["french"],"coffre":["french"],"cogner":["french"],"cohésion":["french"],"coiffer":["french"],"coincer":["french"],"colère":["french"],"colibri":["french"],"colline":["french"],"colmater":["french"],"colonel":["french"],"combat":["french"],"comédie":["french"],"commande":["french"],"compact":["french"],"conduire":["french"],"confier":["french"],"congeler":["french"],"connoter":["french"],"consonne":["french"],"contact":["french"],"convexe":["french"],"copain":["french"],"copie":["french"],"corail":["french"],"corbeau":["french"],"cordage":["french"],"corniche":["french"],"corpus":["french"],"cortège":["french"],"cosmique":["french"],"costume":["french"],"coton":["french"],"coude":["french"],"coupure":["french"],"courage":["french"],"couteau":["french"],"couvrir":["french"],"crabe":["french"],"crainte":["french"],"cravate":["french"],"crayon":["french"],"créature":["french"],"créditer":["french"],"crémeux":["french"],"creuser":["french"],"crevette":["french"],"cribler":["french"],"crier":["french"],"cristal":["french"],"critère":["french"],"croire":["french"],"croquer":["french"],"crotale":["french"],"crypter":["french"],"cubique":["french"],"cueillir":["french"],"cuillère":["french"],"cuisine":["french"],"cuivre":["french"],"culminer":["french"],"cultiver":["french"],"cumuler":["french"],"cupide":["french"],"curatif":["french"],"curseur":["french"],"cyanure":["french"],"cylindre":["french"],"cynique":["french"],"daigner":["french"],"damier":["french"],"danseur":["french"],"dauphin":["french"],"débattre":["french"],"débiter":["french"],"déborder":["french"],"débrider":["french"],"débutant":["french"],"décaler":["french"],"décembre":["french"],"déchirer":["french"],"décider":["french"],"déclarer":["french"],"décorer":["french"],"décrire":["french"],"décupler":["french"],"dédale":["french"],"déductif":["french"],"déesse":["french"],"défensif":["french"],"défiler":["french"],"défrayer":["french"],"dégager":["french"],"dégivrer":["french"],"déglutir":["french"],"dégrafer":["french"],"déjeuner":["french"],"délice":["french"],"déloger":["french"],"demander":["french"],"demeurer":["french"],"démolir":["french"],"dénicher":["french"],"dénouer":["french"],"dentelle":["french"],"dénuder":["french"],"départ":["french"],"dépenser":["french"],"déphaser":["french"],"déplacer":["french"],"déposer":["french"],"déranger":["french"],"dérober":["french"],"désastre":["french"],"descente":["french"],"désert":["french"],"désigner":["french"],"désobéir":["french"],"dessiner":["french"],"destrier":["french"],"détacher":["french"],"détester":["french"],"détourer":["french"],"détresse":["french"],"devancer":["french"],"devenir":["french"],"deviner":["french"],"devoir":["french"],"diable":["french"],"dialogue":["french"],"diamant":["french"],"dicter":["french"],"différer":["french"],"digérer":["french"],"digne":["french"],"diluer":["french"],"dimanche":["french"],"diminuer":["french"],"dioxyde":["french"],"directif":["french"],"diriger":["french"],"discuter":["french"],"disposer":["french"],"dissiper":["french"],"divertir":["french"],"diviser":["french"],"docile":["french"],"docteur":["french"],"dogme":["french"],"doigt":["french"],"domaine":["french"],"domicile":["french"],"dompter":["french"],"donateur":["french"],"donjon":["french"],"donner":["french"],"dopamine":["french"],"dortoir":["french"],"dorure":["french"],"dosage":["french"],"doseur":["french"],"dossier":["french"],"dotation":["french"],"douanier":["french"],"douceur":["french"],"douter":["french"],"doyen":["french"],"draper":["french"],"dresser":["french"],"dribbler":["french"],"droiture":["french"],"duperie":["french"],"duplexe":["french"],"durable":["french"],"durcir":["french"],"dynastie":["french"],"éblouir":["french"],"écarter":["french"],"écharpe":["french"],"échelle":["french"],"éclairer":["french"],"éclipse":["french"],"éclore":["french"],"écluse":["french"],"école":["french"],"économie":["french"],"écorce":["french"],"écouter":["french"],"écraser":["french"],"écrémer":["french"],"écrivain":["french"],"écrou":["french"],"écume":["french"],"écureuil":["french"],"édifier":["french"],"éduquer":["french"],"effacer":["french"],"effectif":["french"],"effigie":["french"],"effrayer":["french"],"effusion":["french"],"égaliser":["french"],"égarer":["french"],"éjecter":["french"],"élaborer":["french"],"élargir":["french"],"électron":["french"],"élégant":["french"],"éléphant":["french"],"élève":["french"],"éligible":["french"],"élitisme":["french"],"éloge":["french"],"élucider":["french"],"éluder":["french"],"emballer":["french"],"embellir":["french"],"embryon":["french"],"émeraude":["french"],"émission":["french"],"emmener":["french"],"émotion":["french"],"émouvoir":["french"],"empereur":["french"],"employer":["french"],"emporter":["french"],"emprise":["french"],"émulsion":["french"],"encadrer":["french"],"enchère":["french"],"enclave":["french"],"encoche":["french"],"endiguer":["french"],"endosser":["french"],"endroit":["french"],"enduire":["french"],"énergie":["french"],"enfance":["french"],"enfermer":["french"],"enfouir":["french"],"engager":["french"],"engin":["french","turkish"],"englober":["french"],"énigme":["french"],"enjamber":["french"],"enjeu":["french"],"enlever":["french"],"ennemi":["french"],"ennuyeux":["french"],"enrichir":["french"],"enrobage":["french"],"enseigne":["french"],"entasser":["french"],"entendre":["french"],"entier":["french"],"entourer":["french"],"entraver":["french"],"énumérer":["french"],"envahir":["french"],"enviable":["french"],"envoyer":["french"],"enzyme":["french"],"éolien":["french"],"épaissir":["french"],"épargne":["french"],"épatant":["french"],"épaule":["french"],"épicerie":["french"],"épidémie":["french"],"épier":["french"],"épilogue":["french"],"épine":["french"],"épisode":["french"],"épitaphe":["french"],"époque":["french"],"épreuve":["french"],"éprouver":["french"],"épuisant":["french"],"équerre":["french"],"équipe":["french"],"ériger":["french"],"érosion":["french"],"erreur":["french"],"éruption":["french"],"escalier":["french"],"espadon":["french"],"espèce":["french"],"espiègle":["french"],"espoir":["french"],"esprit":["french"],"esquiver":["french"],"essayer":["french"],"essieu":["french"],"essorer":["french"],"estime":["french"],"estomac":["french"],"estrade":["french"],"étagère":["french"],"étaler":["french"],"étanche":["french"],"étatique":["french"],"éteindre":["french"],"étendoir":["french"],"éternel":["french"],"éthanol":["french"],"éthique":["french"],"ethnie":["french"],"étirer":["french"],"étoffer":["french"],"étoile":["french"],"étonnant":["french"],"étourdir":["french"],"étrange":["french"],"étroit":["french"],"étude":["french"],"euphorie":["french"],"évaluer":["french"],"évasion":["french"],"éventail":["french"],"évidence":["french"],"éviter":["french"],"évolutif":["french"],"évoquer":["french"],"exagérer":["french"],"exaucer":["french"],"exceller":["french"],"excitant":["french"],"exclusif":["french"],"exécuter":["french"],"exemple":["french"],"exercer":["french"],"exhaler":["french"],"exhorter":["french"],"exigence":["french"],"exiler":["french"],"exister":["french"],"exotique":["french"],"expédier":["french"],"explorer":["french"],"exposer":["french"],"exprimer":["french"],"exquis":["french"],"extensif":["french"],"extraire":["french"],"exulter":["french"],"fable":["french"],"fabuleux":["french"],"facette":["french"],"facile":["french"],"facture":["french"],"faiblir":["french"],"falaise":["french"],"fameux":["french"],"famille":["french"],"farceur":["french"],"farfelu":["french"],"farine":["french"],"farouche":["french"],"fasciner":["french"],"faucon":["french"],"fautif":["french"],"faveur":["french"],"favori":["french","turkish"],"fébrile":["french"],"féconder":["french"],"fédérer":["french"],"félin":["french"],"femme":["french"],"fémur":["french"],"fendoir":["french"],"féodal":["french"],"fermer":["french"],"féroce":["french"],"ferveur":["french"],"feuille":["french"],"feutre":["french"],"février":["french"],"fiasco":["french"],"ficeler":["french"],"fictif":["french"],"fidèle":["french"],"filature":["french"],"filetage":["french"],"filière":["french"],"filleul":["french"],"filmer":["french"],"filou":["french"],"filtrer":["french"],"financer":["french"],"finir":["french"],"fiole":["french"],"firme":["french"],"fissure":["french"],"fixer":["french"],"flairer":["french"],"flamme":["french"],"flasque":["french"],"flatteur":["french"],"fléau":["french"],"flèche":["french"],"fleur":["french"],"flexion":["french"],"flocon":["french"],"flore":["french"],"fluctuer":["french"],"fluide":["french"],"fluvial":["french"],"folie":["french"],"fonderie":["french"],"fongible":["french"],"fontaine":["french"],"forcer":["french"],"forgeron":["french"],"formuler":["french"],"fossile":["french"],"foudre":["french"],"fougère":["french"],"fouiller":["french"],"foulure":["french"],"fourmi":["french"],"fraise":["french"],"franchir":["french"],"frapper":["french"],"frayeur":["french"],"frégate":["french"],"freiner":["french"],"frelon":["french"],"frémir":["french"],"frénésie":["french"],"frère":["french"],"friable":["french"],"friction":["french"],"frisson":["french"],"frivole":["french"],"froid":["french"],"fromage":["french"],"frontal":["french"],"frotter":["french"],"fugitif":["french"],"fuite":["french"],"fureur":["french"],"furieux":["french"],"furtif":["french"],"fusion":["french"],"futur":["french"],"gagner":["french"],"galaxie":["french"],"galerie":["french"],"gambader":["french"],"garantir":["french"],"gardien":["french"],"garnir":["french"],"garrigue":["french"],"gazelle":["french"],"gazon":["french"],"géant":["french"],"gélatine":["french"],"gélule":["french"],"gendarme":["french"],"général":["french"],"génie":["french"],"genou":["french"],"gentil":["french"],"géologie":["french"],"géomètre":["french"],"géranium":["french"],"germe":["french"],"gestuel":["french"],"geyser":["french"],"gibier":["french"],"gicler":["french"],"girafe":["french"],"givre":["french"],"glace":["french"],"glaive":["french"],"glisser":["french"],"gloire":["french"],"glorieux":["french"],"golfeur":["french"],"gomme":["french"],"gonfler":["french"],"gorge":["french"],"gorille":["french"],"goudron":["french"],"gouffre":["french"],"goulot":["french"],"goupille":["french"],"gourmand":["french"],"goutte":["french"],"graduel":["french"],"graffiti":["french"],"graine":["french"],"grand":["french"],"grappin":["french"],"gratuit":["french"],"gravir":["french"],"grenat":["french"],"griffure":["french"],"griller":["french"],"grimper":["french"],"grogner":["french"],"gronder":["french"],"grotte":["french"],"groupe":["french"],"gruger":["french"],"grutier":["french"],"gruyère":["french"],"guépard":["french"],"guerrier":["french"],"guimauve":["french"],"guitare":["french"],"gustatif":["french"],"gymnaste":["french"],"gyrostat":["french"],"habitude":["french"],"hachoir":["french"],"halte":["french"],"hameau":["french"],"hangar":["french","turkish"],"hanneton":["french"],"haricot":["french"],"harmonie":["french"],"harpon":["french"],"hasard":["french"],"hélium":["french"],"hématome":["french"],"herbe":["french"],"hérisson":["french"],"hermine":["french"],"héron":["french"],"hésiter":["french"],"heureux":["french"],"hiberner":["french"],"hibou":["french"],"hilarant":["french"],"histoire":["french"],"hiver":["french"],"homard":["french"],"hommage":["french"],"homogène":["french"],"honneur":["french"],"honorer":["french"],"honteux":["french"],"horde":["french"],"horizon":["french"],"horloge":["french"],"hormone":["french"],"horrible":["french"],"houleux":["french"],"housse":["french"],"hublot":["french"],"huileux":["french"],"humain":["french"],"humide":["french"],"humour":["french"],"hurler":["french"],"hydromel":["french"],"hygiène":["french"],"hymne":["french"],"hypnose":["french"],"idylle":["french"],"ignorer":["french"],"iguane":["french"],"illicite":["french"],"illusion":["french"],"imbiber":["french"],"imiter":["french"],"immobile":["french"],"immuable":["french"],"impérial":["french"],"implorer":["french"],"imposer":["french"],"imprimer":["french"],"imputer":["french"],"incarner":["french"],"incendie":["french"],"incident":["french"],"incliner":["french"],"incolore":["french"],"indexer":["french"],"indice":["french"],"inductif":["french"],"inédit":["french"],"ineptie":["french"],"inexact":["french"],"infini":["french"],"infliger":["french"],"informer":["french"],"infusion":["french"],"ingérer":["french"],"inhaler":["french"],"inhiber":["french"],"injecter":["french"],"injure":["french"],"inoculer":["french"],"inonder":["french"],"inscrire":["french"],"insecte":["french"],"insigne":["french"],"insolite":["french"],"inspirer":["french"],"instinct":["french"],"insulter":["french"],"intense":["french"],"intime":["french"],"intrigue":["french"],"intuitif":["french"],"inutile":["french"],"invasion":["french"],"inventer":["french"],"inviter":["french"],"invoquer":["french"],"ironique":["french"],"irradier":["french"],"irréel":["french"],"irriter":["french"],"isoler":["french"],"ivoire":["french"],"ivresse":["french"],"jaillir":["french"],"jambe":["french"],"janvier":["french"],"jardin":["french"],"jauger":["french"],"jaune":["french"],"javelot":["french"],"jetable":["french"],"jeton":["french"],"jeudi":["french"],"jeunesse":["french"],"joindre":["french"],"joncher":["french"],"jongler":["french"],"joueur":["french"],"jouissif":["french"],"journal":["french"],"jovial":["french"],"joyau":["french"],"joyeux":["french"],"jubiler":["french"],"jugement":["french"],"jupon":["french"],"juriste":["french"],"justice":["french"],"juteux":["french"],"juvénile":["french"],"kayak":["french"],"kimono":["french"],"kiosque":["french"],"labial":["french"],"labourer":["french"],"lacérer":["french"],"lactose":["french"],"lagune":["french"],"laine":["french"],"laisser":["french"],"laitier":["french"],"lambeau":["french"],"lamelle":["french"],"lampe":["french"],"lanceur":["french"],"langage":["french"],"lanterne":["french"],"lapin":["french"],"largeur":["french"],"larme":["french"],"laurier":["french"],"lavabo":["french"],"lavoir":["french"],"légal":["french"],"léger":["french"],"légume":["french"],"lessive":["french"],"lettre":["french"],"levier":["french"],"lexique":["french"],"lézard":["french"],"liasse":["french"],"libérer":["french"],"libre":["french"],"licence":["french"],"licorne":["french"],"liège":["french"],"lièvre":["french"],"ligature":["french"],"ligoter":["french"],"ligue":["french"],"limer":["french"],"limite":["french"],"limonade":["french"],"limpide":["french"],"linéaire":["french"],"lingot":["french"],"lionceau":["french"],"liquide":["french"],"lisière":["french"],"lister":["french"],"lithium":["french"],"litige":["french"],"littoral":["french"],"livreur":["french"],"logique":["french"],"lointain":["french"],"loisir":["french"],"lombric":["french"],"loterie":["french"],"louer":["french"],"lourd":["french"],"loutre":["french"],"louve":["french"],"lubie":["french"],"lucide":["french"],"lucratif":["french"],"lueur":["french"],"lugubre":["french"],"luisant":["french"],"lumière":["french"],"lunaire":["french"],"lundi":["french"],"luron":["french"],"lutter":["french"],"luxueux":["french"],"magasin":["french"],"magenta":["french"],"magique":["french"],"maigre":["french"],"maillon":["french"],"maintien":["french"],"mairie":["french"],"maison":["french"],"majorer":["french"],"malaxer":["french"],"maléfice":["french"],"malheur":["french"],"malice":["french"],"mallette":["french"],"mammouth":["french"],"mandater":["french"],"maniable":["french"],"manquant":["french"],"manteau":["french"],"manuel":["french"],"marathon":["french"],"marbre":["french"],"marchand":["french"],"mardi":["french"],"maritime":["french"],"marqueur":["french"],"marron":["french"],"marteler":["french"],"mascotte":["french"],"massif":["french"],"matériel":["french"],"matière":["french"],"matraque":["french"],"maudire":["french"],"maussade":["french"],"mauve":["french"],"maximal":["french"],"méchant":["french"],"méconnu":["french"],"médaille":["french"],"médecin":["french"],"méditer":["french"],"méduse":["french"],"meilleur":["french"],"mélange":["french"],"mélodie":["french"],"membre":["french"],"mémoire":["french"],"menacer":["french"],"mener":["french"],"menhir":["french"],"mensonge":["french"],"mentor":["french"],"mercredi":["french"],"mérite":["french"],"merle":["french"],"messager":["french"],"mesure":["french"],"métal":["french"],"météore":["french"],"méthode":["french"],"métier":["french"],"meuble":["french"],"miauler":["french"],"microbe":["french"],"miette":["french"],"mignon":["french"],"migrer":["french"],"milieu":["french"],"mimique":["french"],"mince":["french"],"minéral":["french"],"minimal":["french"],"minorer":["french"],"miroiter":["french"],"missile":["french"],"mixte":["french"],"moderne":["french"],"moelleux":["french"],"mondial":["french"],"moniteur":["french"],"monnaie":["french"],"monotone":["french"],"monstre":["french"],"montagne":["french"],"monument":["french"],"moqueur":["french"],"morceau":["french"],"morsure":["french"],"mortier":["french"],"moteur":["french"],"motif":["french"],"mouche":["french"],"moufle":["french"],"moulin":["french"],"mousson":["french"],"mouton":["french"],"mouvant":["french"],"multiple":["french"],"munition":["french"],"muraille":["french"],"murène":["french"],"murmure":["french"],"muséum":["french"],"musicien":["french"],"mutation":["french"],"muter":["french"],"mutuel":["french"],"myriade":["french"],"myrtille":["french"],"mystère":["french"],"mythique":["french"],"nageur":["french"],"nappe":["french"],"narquois":["french"],"narrer":["french"],"natation":["french"],"naufrage":["french"],"nautique":["french"],"navire":["french"],"nébuleux":["french"],"nectar":["french"],"néfaste":["french"],"négation":["french"],"négliger":["french"],"négocier":["french"],"neige":["french"],"nerveux":["french"],"nettoyer":["french"],"neurone":["french"],"neutron":["french"],"neveu":["french"],"niche":["french"],"nickel":["french"],"nitrate":["french"],"niveau":["french"],"nocif":["french"],"nocturne":["french"],"noirceur":["french"],"noisette":["french"],"nomade":["french"],"nombreux":["french"],"nommer":["french"],"normatif":["french"],"notifier":["french"],"notoire":["french"],"nourrir":["french"],"nouveau":["french"],"novateur":["french"],"novembre":["french"],"novice":["french"],"nuage":["french"],"nuancer":["french"],"nuire":["french"],"nuisible":["french"],"numéro":["french"],"nuptial":["french"],"nuque":["french"],"nutritif":["french"],"obéir":["french"],"objectif":["french"],"obliger":["french"],"obscur":["french"],"observer":["french"],"obstacle":["french"],"obtenir":["french"],"obturer":["french"],"occasion":["french"],"occuper":["french"],"océan":["french"],"octobre":["french"],"octroyer":["french"],"octupler":["french"],"oculaire":["french"],"odeur":["french"],"odorant":["french"],"offenser":["french"],"officier":["french"],"offrir":["french"],"ogive":["french"],"oiseau":["french"],"oisillon":["french"],"olfactif":["french"],"olivier":["french"],"ombrage":["french"],"omettre":["french"],"onctueux":["french"],"onduler":["french"],"onéreux":["french"],"onirique":["french"],"opale":["french"],"opaque":["french"],"opérer":["french"],"opportun":["french"],"opprimer":["french"],"opter":["french"],"optique":["french"],"orageux":["french"],"orbite":["french"],"ordonner":["french"],"oreille":["french"],"organe":["french"],"orgueil":["french"],"orifice":["french"],"ornement":["french"],"orque":["french"],"ortie":["french"],"osciller":["french"],"osmose":["french"],"ossature":["french"],"otarie":["french"],"ouragan":["french"],"ourson":["french"],"outil":["french"],"outrager":["french"],"ouvrage":["french"],"ovation":["french"],"oxyde":["french"],"oxygène":["french"],"paisible":["french"],"palmarès":["french"],"palourde":["french"],"palper":["french"],"panache":["french"],"pangolin":["french"],"paniquer":["french"],"panneau":["french"],"panorama":["french"],"pantalon":["french"],"papaye":["french"],"papier":["french"],"papoter":["french"],"papyrus":["french"],"paradoxe":["french"],"parcelle":["french"],"paresse":["french"],"parfumer":["french"],"parler":["french"],"parole":["french"],"parrain":["french"],"parsemer":["french"],"partager":["french"],"parure":["french"],"parvenir":["french"],"passion":["french"],"pastèque":["french"],"paternel":["french"],"patience":["french"],"patron":["french","turkish"],"pavillon":["french"],"pavoiser":["french"],"payer":["french"],"paysage":["french"],"peigne":["french"],"peintre":["french"],"pelage":["french"],"pélican":["french"],"pelle":["french"],"pelouse":["french"],"peluche":["french"],"pendule":["french"],"pénétrer":["french"],"pénible":["french"],"pensif":["french"],"pénurie":["french"],"pépite":["french"],"péplum":["french"],"perdrix":["french"],"perforer":["french"],"période":["french"],"permuter":["french"],"perplexe":["french"],"persil":["french"],"perte":["french"],"peser":["french"],"pétale":["french"],"petit":["french"],"pétrir":["french"],"peuple":["french"],"pharaon":["french"],"phobie":["french"],"phoque":["french"],"photon":["french"],"physique":["french"],"pictural":["french"],"pièce":["french"],"pierre":["french"],"pieuvre":["french"],"pilote":["french"],"pinceau":["french"],"pipette":["french"],"piquer":["french"],"pirogue":["french"],"piscine":["french"],"piston":["french"],"pivoter":["french"],"pixel":["french"],"placard":["french"],"plafond":["french"],"plaisir":["french"],"planer":["french"],"plaque":["french"],"plastron":["french"],"plateau":["french"],"pleurer":["french"],"plexus":["french"],"pliage":["french"],"plomb":["french"],"plonger":["french"],"pluie":["french"],"plumage":["french"],"pochette":["french"],"poésie":["french"],"poète":["french"],"pointe":["french"],"poirier":["french"],"poisson":["french"],"poivre":["french"],"polaire":["french"],"policier":["french"],"pollen":["french"],"polygone":["french"],"pommade":["french"],"pompier":["french"],"ponctuel":["french"],"pondérer":["french"],"poney":["french"],"portique":["french"],"posséder":["french"],"posture":["french"],"potager":["french"],"poteau":["french"],"potion":["french"],"pouce":["french"],"poulain":["french"],"poumon":["french"],"pourpre":["french"],"poussin":["french"],"pouvoir":["french"],"prairie":["french"],"pratique":["french"],"précieux":["french"],"prédire":["french"],"préfixe":["french"],"prélude":["french"],"prénom":["french"],"présence":["french"],"prétexte":["french"],"prévoir":["french"],"primitif":["french"],"prince":["french"],"priver":["french"],"problème":["french"],"procéder":["french"],"prodige":["french"],"profond":["french"],"progrès":["french"],"proie":["french"],"projeter":["french"],"prologue":["french"],"promener":["french"],"propre":["french"],"prospère":["french"],"protéger":["french"],"prouesse":["french"],"proverbe":["french"],"prudence":["french"],"pruneau":["french"],"psychose":["french"],"puceron":["french"],"puiser":["french"],"pulpe":["french"],"pulsar":["french"],"punaise":["french"],"punitif":["french"],"pupitre":["french"],"purifier":["french"],"pyramide":["french"],"quasar":["french"],"querelle":["french"],"quiétude":["french"],"quitter":["french"],"quotient":["french"],"racine":["french"],"raconter":["french"],"radieux":["french"],"ragondin":["french"],"raideur":["french"],"raisin":["french"],"ralentir":["french"],"rallonge":["french"],"ramasser":["french"],"rapide":["french"],"rasage":["french"],"ratisser":["french"],"ravager":["french"],"ravin":["french"],"rayonner":["french"],"réactif":["french"],"réagir":["french"],"réaliser":["french"],"réanimer":["french"],"recevoir":["french"],"réciter":["french"],"réclamer":["french"],"récolter":["french"],"recruter":["french"],"reculer":["french"],"recycler":["french"],"rédiger":["french"],"redouter":["french"],"refaire":["french"],"réflexe":["french"],"réformer":["french"],"refrain":["french"],"refuge":["french"],"régalien":["french"],"région":["french"],"réglage":["french"],"régulier":["french"],"réitérer":["french"],"rejeter":["french"],"rejouer":["french"],"relatif":["french"],"relever":["french"],"remarque":["french"],"remède":["french"],"remise":["french"],"remonter":["french"],"remplir":["french"],"remuer":["french"],"renard":["french"],"renfort":["french"],"renifler":["french"],"renoncer":["french"],"rentrer":["french"],"renvoi":["french"],"replier":["french"],"reporter":["french"],"reprise":["french"],"reptile":["french"],"requin":["french"],"réserve":["french"],"résineux":["french"],"résoudre":["french"],"respect":["french"],"rester":["french"],"résultat":["french"],"rétablir":["french"],"retenir":["french"],"réticule":["french"],"retomber":["french"],"retracer":["french"],"réunion":["french"],"réussir":["french"],"revanche":["french"],"revivre":["french"],"révolte":["french"],"révulsif":["french"],"richesse":["french"],"rideau":["french"],"rieur":["french"],"rigide":["french"],"rigoler":["french"],"rincer":["french"],"riposter":["french"],"risible":["french"],"risque":["french"],"rituel":["french"],"rivière":["french"],"rocheux":["french"],"rompre":["french"],"ronce":["french"],"rondin":["french"],"roseau":["french"],"rosier":["french"],"rotatif":["french"],"rotor":["french"],"rotule":["french"],"rouge":["french"],"rouille":["french"],"rouleau":["french"],"routine":["french"],"royaume":["french"],"ruban":["french"],"rubis":["french"],"ruche":["french"],"ruelle":["french"],"rugueux":["french"],"ruiner":["french"],"ruisseau":["french"],"ruser":["french"],"rustique":["french"],"rythme":["french"],"sabler":["french"],"saboter":["french"],"sabre":["french"],"sacoche":["french"],"safari":["french"],"sagesse":["french"],"saisir":["french"],"salade":["french"],"salive":["french"],"saluer":["french"],"samedi":["french"],"sanction":["french"],"sanglier":["french"],"sarcasme":["french"],"sardine":["french"],"saturer":["french"],"saugrenu":["french"],"saumon":["french"],"sauter":["french"],"sauvage":["french"],"savant":["french"],"savonner":["french"],"scalpel":["french"],"scandale":["french"],"scélérat":["french"],"scénario":["french"],"sceptre":["french"],"schéma":["french"],"scinder":["french"],"score":["french"],"scrutin":["french"],"sculpter":["french"],"séance":["french"],"sécable":["french"],"sécher":["french"],"secouer":["french"],"sécréter":["french"],"sédatif":["french"],"séduire":["french"],"seigneur":["french"],"séjour":["french"],"sélectif":["french"],"semaine":["french"],"sembler":["french"],"semence":["french"],"séminal":["french"],"sénateur":["french"],"sensible":["french"],"séparer":["french"],"séquence":["french"],"serein":["french"],"sergent":["french"],"sérieux":["french"],"serrure":["french"],"sérum":["french"],"sésame":["french"],"sévir":["french"],"sevrage":["french"],"sextuple":["french"],"sidéral":["french"],"siècle":["french"],"siéger":["french"],"siffler":["french"],"sigle":["french"],"signal":["french"],"silence":["french"],"silicium":["french"],"sincère":["french"],"sinistre":["french"],"siphon":["french"],"sirop":["french"],"sismique":["french"],"situer":["french"],"skier":["french"],"socle":["french"],"sodium":["french"],"soigneux":["french"],"soldat":["french"],"soleil":["french"],"solitude":["french"],"soluble":["french"],"sombre":["french"],"sommeil":["french"],"somnoler":["french"],"sonde":["french"],"songeur":["french"],"sonnette":["french"],"sonore":["french"],"sorcier":["french"],"sortir":["french"],"sosie":["french"],"sottise":["french"],"soucieux":["french"],"soudure":["french"],"souffle":["french"],"soulever":["french"],"soupape":["french"],"soutirer":["french"],"souvenir":["french"],"spacieux":["french"],"spécial":["french"],"sphère":["french"],"spiral":["french","turkish"],"station":["french"],"sternum":["french"],"stimulus":["french"],"stipuler":["french"],"strict":["french"],"studieux":["french"],"stupeur":["french"],"styliste":["french"],"sublime":["french"],"substrat":["french"],"subtil":["french"],"subvenir":["french"],"succès":["french"],"sucre":["french"],"suffixe":["french"],"suggérer":["french"],"suiveur":["french"],"sulfate":["french"],"superbe":["french"],"supplier":["french"],"suricate":["french"],"surmener":["french"],"sursaut":["french"],"survie":["french"],"syllabe":["french"],"symbole":["french"],"symétrie":["french"],"synapse":["french"],"syntaxe":["french"],"système":["french"],"tabac":["french"],"tablier":["french"],"tactile":["french"],"tailler":["french"],"talisman":["french"],"talonner":["french"],"tambour":["french"],"tamiser":["french"],"tangible":["french"],"tapis":["french"],"taquiner":["french"],"tarder":["french"],"tarif":["french"],"tartine":["french"],"tasse":["french"],"tatami":["french"],"tatouage":["french"],"taupe":["french"],"taureau":["french"],"taxer":["french"],"témoin":["french"],"temporel":["french"],"tenaille":["french"],"tendre":["french"],"teneur":["french"],"tenir":["french"],"tension":["french"],"terminer":["french"],"terne":["french"],"terrible":["french"],"tétine":["french"],"texte":["french"],"thème":["french"],"théorie":["french"],"thérapie":["french"],"thorax":["french"],"tibia":["french"],"tiède":["french"],"timide":["french"],"tirelire":["french"],"tiroir":["french"],"tissu":["french"],"titane":["french"],"titre":["french"],"tituber":["french"],"toboggan":["french"],"tolérant":["french"],"tomate":["french"],"tonique":["french"],"tonneau":["french"],"toponyme":["french"],"torche":["french"],"tordre":["french"],"tornade":["french"],"torpille":["french"],"torrent":["french"],"torse":["french"],"tortue":["french"],"totem":["french"],"toucher":["french"],"tournage":["french"],"tousser":["french"],"toxine":["french"],"traction":["french"],"trafic":["french"],"tragique":["french"],"trahir":["french"],"trancher":["french"],"travail":["french"],"trèfle":["french"],"tremper":["french"],"trésor":["french"],"treuil":["french"],"triage":["french"],"tribunal":["french"],"tricoter":["french"],"trilogie":["french"],"triomphe":["french"],"tripler":["french"],"triturer":["french"],"trivial":["french"],"trombone":["french"],"tronc":["french"],"tropical":["french"],"troupeau":["french"],"tuile":["french"],"tulipe":["french"],"tumulte":["french"],"turbine":["french"],"tuteur":["french"],"tutoyer":["french"],"tuyau":["french"],"tympan":["french"],"typhon":["french"],"typique":["french"],"tyran":["french"],"ubuesque":["french"],"ultime":["french"],"ultrason":["french"],"unanime":["french"],"unifier":["french"],"union":["french"],"unitaire":["french"],"univers":["french"],"uranium":["french"],"urbain":["french"],"urticant":["french"],"usine":["french"],"usuel":["french"],"usure":["french"],"utile":["french"],"utopie":["french"],"vacarme":["french"],"vaccin":["french"],"vagabond":["french"],"vaillant":["french"],"vaincre":["french"],"vaisseau":["french"],"valable":["french"],"valise":["french"],"vallon":["french"],"vampire":["french"],"vanille":["french"],"vapeur":["french"],"varier":["french"],"vaseux":["french"],"vassal":["french"],"vaste":["french"],"vecteur":["french"],"vedette":["french"],"végétal":["french"],"véhicule":["french"],"veinard":["french"],"véloce":["french"],"vendredi":["french"],"vénérer":["french"],"venger":["french"],"venimeux":["french"],"ventouse":["french"],"verdure":["french"],"vérin":["french"],"vernir":["french"],"verrou":["french"],"verser":["french"],"vertu":["french"],"veston":["french"],"vétéran":["french"],"vétuste":["french"],"vexant":["french"],"vexer":["french"],"viaduc":["french"],"viande":["french"],"victoire":["french"],"vidange":["french"],"vidéo":["french"],"vignette":["french"],"vigueur":["french"],"vilain":["french"],"vinaigre":["french"],"violon":["french"],"vipère":["french"],"virement":["french"],"virtuose":["french"],"visage":["french"],"viseur":["french"],"vision":["french"],"visqueux":["french"],"visuel":["french"],"vitesse":["french"],"viticole":["french"],"vitrine":["french"],"vivace":["french"],"vivipare":["french"],"vocation":["french"],"voguer":["french"],"voile":["french"],"voisin":["french"],"voiture":["french"],"volaille":["french"],"volcan":["french"],"voltiger":["french"],"vorace":["french"],"vortex":["french"],"voter":["french"],"vouloir":["french"],"voyelle":["french"],"xénon":["french"],"yacht":["french"],"zèbre":["french"],"zénith":["french"],"zeste":["french"],"zoologie":["french"],"abaco":["italian"],"abbaglio":["italian"],"abbinato":["italian"],"abete":["italian"],"abisso":["italian"],"abolire":["italian"],"abrasivo":["italian"],"abrogato":["italian"],"accadere":["italian"],"accenno":["italian"],"accusato":["italian"],"acetone":["italian"],"achille":["italian"],"acido":["italian"],"acqua":["italian"],"acre":["italian"],"acrilico":["italian"],"acrobata":["italian"],"acuto":["italian"],"adagio":["italian"],"addebito":["italian"],"addome":["italian"],"adeguato":["italian"],"aderire":["italian"],"adipe":["italian"],"adottare":["italian"],"adulare":["italian"],"affabile":["italian"],"affetto":["italian"],"affisso":["italian"],"affranto":["italian"],"aforisma":["italian"],"afoso":["italian"],"africano":["italian"],"agave":["italian"],"agente":["italian"],"agevole":["italian"],"aggancio":["italian"],"agire":["italian"],"agitare":["italian"],"agonismo":["italian"],"agricolo":["italian"],"agrumeto":["italian"],"aguzzo":["italian"],"alabarda":["italian"],"alato":["italian"],"albatro":["italian"],"alberato":["italian"],"albo":["italian"],"albume":["italian"],"alce":["italian"],"alcolico":["italian"],"alettone":["italian"],"alfa":["italian"],"algebra":["italian"],"aliante":["italian"],"alibi":["italian"],"alimento":["italian"],"allagato":["italian"],"allegro":["italian"],"allievo":["italian"],"allodola":["italian"],"allusivo":["italian"],"almeno":["italian"],"alogeno":["italian"],"alpaca":["italian"],"alpestre":["italian"],"altalena":["italian"],"alterno":["italian"],"alticcio":["italian"],"altrove":["italian"],"alunno":["italian"],"alveolo":["italian"],"alzare":["italian"],"amalgama":["italian"],"amanita":["italian"],"amarena":["italian"],"ambito":["italian"],"ambrato":["italian"],"ameba":["italian"],"america":["italian"],"ametista":["italian"],"amico":["italian"],"ammasso":["italian"],"ammenda":["italian"],"ammirare":["italian"],"ammonito":["italian"],"amore":["italian"],"ampio":["italian"],"ampliare":["italian"],"amuleto":["italian"],"anacardo":["italian"],"anagrafe":["italian"],"analista":["italian"],"anarchia":["italian"],"anatra":["italian"],"anca":["italian"],"ancella":["italian"],"ancora":["italian"],"andare":["italian"],"andrea":["italian"],"anello":["italian"],"angelo":["italian"],"angolare":["italian"],"angusto":["italian"],"anima":["italian"],"annegare":["italian"],"annidato":["italian"],"anno":["italian"],"annuncio":["italian"],"anonimo":["italian"],"anticipo":["italian"],"anzi":["italian"],"apatico":["italian"],"apertura":["italian"],"apode":["italian"],"apparire":["italian"],"appetito":["italian"],"appoggio":["italian"],"approdo":["italian"],"appunto":["italian"],"aprile":["italian"],"arabica":["italian"],"arachide":["italian"],"aragosta":["italian"],"araldica":["italian"],"arancio":["italian"],"aratura":["italian"],"arazzo":["italian"],"arbitro":["italian"],"archivio":["italian"],"ardito":["italian"],"arenile":["italian"],"argento":["italian"],"argine":["italian"],"arguto":["italian"],"aria":["italian"],"armonia":["italian"],"arnese":["italian"],"arredato":["italian"],"arringa":["italian"],"arrosto":["italian"],"arsenico":["italian"],"arso":["italian"],"artefice":["italian"],"arzillo":["italian"],"asciutto":["italian"],"ascolto":["italian"],"asepsi":["italian"],"asettico":["italian"],"asfalto":["italian"],"asino":["italian"],"asola":["italian"],"aspirato":["italian"],"aspro":["italian"],"assaggio":["italian"],"asse":["italian"],"assoluto":["italian"],"assurdo":["italian"],"asta":["italian"],"astenuto":["italian"],"astice":["italian"],"astratto":["italian"],"atavico":["italian"],"ateismo":["italian"],"atomico":["italian"],"atono":["italian"],"attesa":["italian"],"attivare":["italian"],"attorno":["italian"],"attrito":["italian"],"attuale":["italian"],"ausilio":["italian"],"austria":["italian"],"autista":["italian"],"autonomo":["italian"],"autunno":["italian"],"avanzato":["italian"],"avere":["italian"],"avvenire":["italian"],"avviso":["italian"],"avvolgere":["italian"],"azione":["italian"],"azoto":["italian"],"azzimo":["italian"],"azzurro":["italian"],"babele":["italian"],"baccano":["italian"],"bacino":["italian"],"baco":["italian"],"badessa":["italian"],"badilata":["italian"],"bagnato":["italian"],"baita":["italian"],"balcone":["italian"],"baldo":["italian"],"balena":["italian"],"ballata":["italian"],"balzano":["italian"],"bambino":["italian"],"bandire":["italian"],"baraonda":["italian"],"barbaro":["italian"],"barca":["italian"],"baritono":["italian"],"barlume":["italian"],"barocco":["italian"],"basilico":["italian"],"basso":["italian"],"batosta":["italian"],"battuto":["italian"],"baule":["italian"],"bava":["italian"],"bavosa":["italian"],"becco":["italian"],"beffa":["italian"],"belgio":["italian"],"belva":["italian"],"benda":["italian"],"benevole":["italian"],"benigno":["italian"],"benzina":["italian"],"bere":["italian"],"berlina":["italian"],"beta":["italian"],"bibita":["italian"],"bici":["italian"],"bidone":["italian"],"bifido":["italian"],"biga":["italian"],"bilancia":["italian"],"bimbo":["italian"],"binocolo":["italian"],"biologo":["italian"],"bipede":["italian"],"bipolare":["italian"],"birbante":["italian"],"birra":["italian"],"biscotto":["italian"],"bisesto":["italian"],"bisnonno":["italian"],"bisonte":["italian"],"bisturi":["italian"],"bizzarro":["italian"],"blando":["italian"],"blatta":["italian"],"bollito":["italian"],"bonifico":["italian"],"bordo":["italian"],"bosco":["italian"],"botanico":["italian"],"bottino":["italian"],"bozzolo":["italian"],"braccio":["italian"],"bradipo":["italian"],"brama":["italian"],"branca":["italian"],"bravura":["italian"],"bretella":["italian"],"brevetto":["italian"],"brezza":["italian"],"briglia":["italian"],"brillante":["italian"],"brindare":["italian"],"broccolo":["italian"],"brodo":["italian"],"bronzina":["italian"],"brullo":["italian"],"bruno":["italian"],"bubbone":["italian"],"buca":["italian"],"budino":["italian"],"buffone":["italian"],"buio":["italian"],"bulbo":["italian"],"buono":["italian"],"burlone":["italian"],"burrasca":["italian"],"bussola":["italian"],"busta":["italian"],"cadetto":["italian"],"caduco":["italian"],"calamaro":["italian"],"calcolo":["italian"],"calesse":["italian"],"calibro":["italian"],"calmo":["italian"],"caloria":["italian"],"cambusa":["italian"],"camerata":["italian"],"camicia":["italian"],"cammino":["italian"],"camola":["italian"],"campale":["italian"],"canapa":["italian"],"candela":["italian"],"cane":["italian"],"canino":["italian"],"canotto":["italian"],"cantina":["italian"],"capace":["italian"],"capello":["italian"],"capitolo":["italian"],"capogiro":["italian"],"cappero":["italian"],"capra":["italian"],"capsula":["italian"],"carapace":["italian"],"carcassa":["italian"],"cardo":["italian"],"carisma":["italian"],"carovana":["italian"],"carretto":["italian"],"cartolina":["italian"],"casaccio":["italian"],"cascata":["italian"],"caserma":["italian"],"caso":["italian"],"cassone":["italian"],"castello":["italian"],"casuale":["italian"],"catasta":["italian"],"catena":["italian"],"catrame":["italian"],"cauto":["italian"],"cavillo":["italian"],"cedibile":["italian"],"cedrata":["italian"],"cefalo":["italian"],"celebre":["italian"],"cellulare":["italian"],"cena":["italian"],"cenone":["italian"],"centesimo":["italian"],"ceramica":["italian"],"cercare":["italian"],"certo":["italian"],"cerume":["italian"],"cervello":["italian"],"cesoia":["italian"],"cespo":["italian"],"ceto":["italian"],"chela":["italian"],"chiaro":["italian"],"chicca":["italian"],"chiedere":["italian"],"chimera":["italian"],"china":["italian"],"chirurgo":["italian"],"chitarra":["italian"],"ciao":["italian"],"ciclismo":["italian"],"cifrare":["italian"],"cigno":["italian"],"cilindro":["italian"],"ciottolo":["italian"],"circa":["italian"],"cirrosi":["italian"],"citrico":["italian"],"cittadino":["italian"],"ciuffo":["italian"],"civetta":["italian"],"civile":["italian"],"classico":["italian"],"clinica":["italian"],"cloro":["italian"],"cocco":["italian"],"codardo":["italian"],"codice":["italian"],"coerente":["italian"],"cognome":["italian"],"collare":["italian"],"colmato":["italian"],"colore":["italian"],"colposo":["italian"],"coltivato":["italian"],"colza":["italian"],"coma":["italian"],"cometa":["italian"],"commando":["italian"],"comodo":["italian"],"computer":["italian"],"comune":["italian"],"conciso":["italian"],"condurre":["italian"],"conferma":["italian"],"congelare":["italian"],"coniuge":["italian"],"connesso":["italian"],"conoscere":["italian"],"consumo":["italian"],"continuo":["italian"],"convegno":["italian"],"coperto":["italian"],"copione":["italian"],"coppia":["italian"],"copricapo":["italian"],"corazza":["italian"],"cordata":["italian"],"coricato":["italian"],"cornice":["italian"],"corolla":["italian"],"corpo":["italian"],"corredo":["italian"],"corsia":["italian"],"cortese":["italian"],"cosmico":["italian"],"costante":["italian"],"cottura":["italian"],"covato":["italian"],"cratere":["italian"],"cravatta":["italian"],"creato":["italian"],"credere":["italian"],"cremoso":["italian"],"crescita":["italian"],"creta":["italian"],"criceto":["italian"],"crinale":["italian"],"crisi":["italian"],"critico":["italian"],"croce":["italian"],"cronaca":["italian"],"crostata":["italian"],"cruciale":["italian"],"crusca":["italian"],"cucire":["italian"],"cuculo":["italian"],"cugino":["italian"],"cullato":["italian"],"cupola":["italian"],"curatore":["italian"],"cursore":["italian"],"curvo":["italian"],"cuscino":["italian"],"custode":["italian"],"dado":["italian"],"daino":["italian"],"dalmata":["italian"],"damerino":["italian"],"daniela":["italian"],"dannoso":["italian"],"danzare":["italian"],"datato":["italian"],"davanti":["italian"],"davvero":["italian"],"debutto":["italian"],"decennio":["italian"],"deciso":["italian"],"declino":["italian"],"decollo":["italian"],"decreto":["italian"],"dedicato":["italian"],"definito":["italian"],"deforme":["italian"],"degno":["italian"],"delegare":["italian"],"delfino":["italian"],"delirio":["italian"],"delta":["italian"],"demenza":["italian"],"denotato":["italian"],"dentro":["italian"],"deposito":["italian"],"derapata":["italian"],"derivare":["italian"],"deroga":["italian"],"descritto":["italian"],"deserto":["italian"],"desiderio":["italian"],"desumere":["italian"],"detersivo":["italian"],"devoto":["italian"],"diametro":["italian"],"dicembre":["italian"],"diedro":["italian"],"difeso":["italian"],"diffuso":["italian"],"digerire":["italian"],"digitale":["italian"],"diluvio":["italian"],"dinamico":["italian"],"dinnanzi":["italian"],"dipinto":["italian"],"diploma":["italian"],"dipolo":["italian"],"diradare":["italian"],"dire":["italian"],"dirotto":["italian"],"dirupo":["italian"],"disagio":["italian"],"discreto":["italian"],"disfare":["italian"],"disgelo":["italian"],"disposto":["italian"],"distanza":["italian"],"disumano":["italian"],"dito":["italian"],"divano":["italian"],"divelto":["italian"],"dividere":["italian"],"divorato":["italian"],"doblone":["italian"],"docente":["italian"],"doganale":["italian"],"dogma":["italian"],"dolce":["italian"],"domato":["italian"],"domenica":["italian"],"dominare":["italian"],"dondolo":["italian"],"dono":["italian"],"dormire":["italian"],"dote":["italian"],"dottore":["italian"],"dovuto":["italian"],"dozzina":["italian"],"drago":["italian"],"druido":["italian"],"dubbio":["italian"],"dubitare":["italian"],"ducale":["italian"],"duna":["italian"],"duomo":["italian"],"duplice":["italian"],"duraturo":["italian"],"ebano":["italian"],"eccesso":["italian"],"ecco":["italian"],"eclissi":["italian"],"economia":["italian"],"edera":["italian"],"edicola":["italian"],"edile":["italian"],"editoria":["italian"],"educare":["italian"],"egemonia":["italian"],"egli":["italian"],"egoismo":["italian"],"egregio":["italian"],"elaborato":["italian"],"elargire":["italian"],"elegante":["italian"],"elencato":["italian"],"eletto":["italian"],"elevare":["italian"],"elfico":["italian"],"elica":["italian"],"elmo":["italian"],"elsa":["italian"],"eluso":["italian"],"emanato":["italian"],"emblema":["italian"],"emesso":["italian"],"emiro":["italian"],"emotivo":["italian"],"emozione":["italian"],"empirico":["italian"],"emulo":["italian"],"endemico":["italian"],"enduro":["italian"],"energia":["italian"],"enfasi":["italian"],"enoteca":["italian"],"entrare":["italian"],"enzima":["italian"],"epatite":["italian"],"epilogo":["italian"],"episodio":["italian"],"epocale":["italian"],"eppure":["italian"],"equatore":["italian"],"erario":["italian"],"erba":["italian"],"erboso":["italian"],"erede":["italian"],"eremita":["italian"],"erigere":["italian"],"ermetico":["italian"],"eroe":["italian"],"erosivo":["italian"],"errante":["italian"],"esagono":["italian"],"esame":["italian"],"esanime":["italian"],"esaudire":["italian"],"esca":["italian"],"esempio":["italian"],"esercito":["italian"],"esibito":["italian"],"esigente":["italian"],"esistere":["italian"],"esito":["italian"],"esofago":["italian"],"esortato":["italian"],"esoso":["italian"],"espanso":["italian"],"espresso":["italian"],"essenza":["italian"],"esso":["italian"],"esteso":["italian"],"estimare":["italian"],"estonia":["italian"],"estroso":["italian"],"esultare":["italian"],"etilico":["italian"],"etnico":["italian"],"etrusco":["italian"],"etto":["italian"],"euclideo":["italian"],"europa":["italian"],"evaso":["italian"],"evidenza":["italian"],"evitato":["italian"],"evoluto":["italian"],"evviva":["italian"],"fabbrica":["italian"],"faccenda":["italian"],"fachiro":["italian"],"falco":["italian"],"famiglia":["italian"],"fanale":["italian"],"fanfara":["italian"],"fango":["italian"],"fantasma":["italian"],"fare":["italian"],"farfalla":["italian"],"farinoso":["italian"],"farmaco":["italian"],"fascia":["italian"],"fastoso":["italian"],"fasullo":["italian"],"faticare":["italian"],"fato":["italian"],"favoloso":["italian"],"febbre":["italian"],"fecola":["italian"],"fede":["italian"],"fegato":["italian"],"felpa":["italian"],"feltro":["italian"],"femmina":["italian"],"fendere":["italian"],"fenomeno":["italian"],"fermento":["italian"],"ferro":["italian"],"fertile":["italian"],"fessura":["italian"],"festivo":["italian"],"fetta":["italian"],"feudo":["italian"],"fiaba":["italian"],"fiducia":["italian"],"fifa":["italian"],"figurato":["italian"],"filo":["italian","turkish"],"finanza":["italian"],"finestra":["italian"],"finire":["italian"],"fiore":["italian"],"fiscale":["italian"],"fisico":["italian"],"fiume":["italian"],"flacone":["italian"],"flamenco":["italian"],"flebo":["italian"],"flemma":["italian"],"florido":["italian"],"fluente":["italian"],"fluoro":["italian"],"fobico":["italian"],"focaccia":["italian"],"focoso":["italian"],"foderato":["italian"],"foglio":["italian"],"folata":["italian"],"folclore":["italian"],"folgore":["italian"],"fondente":["italian"],"fonetico":["italian"],"fonia":["italian"],"fontana":["italian"],"forbito":["italian"],"forchetta":["italian"],"foresta":["italian"],"formica":["italian"],"fornaio":["italian"],"foro":["italian"],"fortezza":["italian"],"forzare":["italian"],"fosfato":["italian"],"fosso":["italian"],"fracasso":["italian"],"frana":["italian"],"frassino":["italian"],"fratello":["italian"],"freccetta":["italian"],"frenata":["italian"],"fresco":["italian"],"frigo":["italian"],"frollino":["italian"],"fronde":["italian"],"frugale":["italian"],"frutta":["italian"],"fucilata":["italian"],"fucsia":["italian"],"fuggente":["italian"],"fulmine":["italian"],"fulvo":["italian"],"fumante":["italian"],"fumetto":["italian"],"fumoso":["italian"],"fune":["italian"],"funzione":["italian"],"fuoco":["italian"],"furbo":["italian"],"furgone":["italian"],"furore":["italian"],"fuso":["italian"],"futile":["italian"],"gabbiano":["italian"],"gaffe":["italian"],"galateo":["italian"],"gallina":["italian"],"galoppo":["italian"],"gambero":["italian"],"gamma":["italian"],"garanzia":["italian"],"garbo":["italian"],"garofano":["italian"],"garzone":["italian"],"gasdotto":["italian"],"gasolio":["italian"],"gastrico":["italian"],"gatto":["italian"],"gaudio":["italian"],"gazebo":["italian"],"gazzella":["italian"],"geco":["italian"],"gelatina":["italian"],"gelso":["italian"],"gemello":["italian"],"gemmato":["italian"],"gene":["italian"],"genitore":["italian"],"gennaio":["italian"],"genotipo":["italian"],"gergo":["italian"],"ghepardo":["italian"],"ghiaccio":["italian"],"ghisa":["italian"],"giallo":["italian"],"gilda":["italian"],"ginepro":["italian"],"giocare":["italian"],"gioiello":["italian"],"giorno":["italian"],"giove":["italian"],"girato":["italian"],"girone":["italian"],"gittata":["italian"],"giudizio":["italian"],"giurato":["italian"],"giusto":["italian"],"globulo":["italian"],"glutine":["italian"],"gnomo":["italian"],"gobba":["italian"],"golf":["italian"],"gomito":["italian"],"gommone":["italian"],"gonfio":["italian"],"gonna":["italian"],"governo":["italian"],"gracile":["italian"],"grado":["italian"],"grafico":["italian"],"grammo":["italian"],"grande":["italian"],"grattare":["italian"],"gravoso":["italian"],"grazia":["italian"],"greca":["italian"],"gregge":["italian"],"grifone":["italian"],"grigio":["italian"],"grinza":["italian"],"grotta":["italian"],"gruppo":["italian"],"guadagno":["italian"],"guaio":["italian"],"guanto":["italian"],"guardare":["italian"],"gufo":["italian"],"guidare":["italian"],"ibernato":["italian"],"icona":["italian"],"identico":["italian"],"idillio":["italian"],"idolo":["italian"],"idra":["italian"],"idrico":["italian"],"idrogeno":["italian"],"igiene":["italian"],"ignaro":["italian"],"ignorato":["italian"],"ilare":["italian"],"illeso":["italian"],"illogico":["italian"],"illudere":["italian"],"imballo":["italian"],"imbevuto":["italian"],"imbocco":["italian"],"imbuto":["italian"],"immane":["italian"],"immerso":["italian"],"immolato":["italian"],"impacco":["italian"],"impeto":["italian"],"impiego":["italian"],"importo":["italian"],"impronta":["italian"],"inalare":["italian"],"inarcare":["italian"],"inattivo":["italian"],"incanto":["italian"],"incendio":["italian"],"inchino":["italian"],"incisivo":["italian"],"incluso":["italian"],"incontro":["italian"],"incrocio":["italian"],"incubo":["italian"],"indagine":["italian"],"india":["italian"],"indole":["italian"],"inedito":["italian"],"infatti":["italian"],"infilare":["italian"],"inflitto":["italian"],"ingaggio":["italian"],"ingegno":["italian"],"inglese":["italian"],"ingordo":["italian"],"ingrosso":["italian"],"innesco":["italian"],"inodore":["italian"],"inoltrare":["italian"],"inondato":["italian"],"insano":["italian"],"insetto":["italian"],"insieme":["italian"],"insonnia":["italian"],"insulina":["italian"],"intasato":["italian"],"intero":["italian"],"intonaco":["italian"],"intuito":["italian"],"inumidire":["italian"],"invalido":["italian"],"invece":["italian"],"invito":["italian"],"iperbole":["italian"],"ipnotico":["italian"],"ipotesi":["italian"],"ippica":["italian"],"iride":["italian"],"irlanda":["italian"],"ironico":["italian"],"irrigato":["italian"],"irrorare":["italian"],"isolato":["italian"],"isotopo":["italian"],"isterico":["italian"],"istituto":["italian"],"istrice":["italian"],"italia":["italian"],"iterare":["italian"],"labbro":["italian"],"labirinto":["italian"],"lacca":["italian"],"lacerato":["italian"],"lacrima":["italian"],"lacuna":["italian"],"laddove":["italian"],"lago":["italian"],"lampo":["italian"],"lancetta":["italian"],"lanterna":["italian"],"lardoso":["italian"],"larga":["italian"],"laringe":["italian"],"lastra":["italian"],"latenza":["italian"],"latino":["italian"],"lattuga":["italian"],"lavagna":["italian"],"lavoro":["italian"],"legale":["italian"],"leggero":["italian"],"lembo":["italian"],"lentezza":["italian"],"lenza":["italian"],"leone":["italian"],"lepre":["italian"],"lesivo":["italian"],"lessato":["italian"],"lesto":["italian"],"letterale":["italian"],"leva":["italian"],"levigato":["italian"],"libero":["italian"],"lido":["italian"],"lievito":["italian"],"lilla":["italian"],"limatura":["italian"],"limitare":["italian"],"limpido":["italian"],"lineare":["italian"],"lingua":["italian"],"liquido":["italian"],"lira":["italian"],"lirica":["italian"],"lisca":["italian"],"lite":["italian"],"litigio":["italian"],"livrea":["italian"],"locanda":["italian"],"lode":["italian"],"logica":["italian"],"lombare":["italian"],"londra":["italian"],"longevo":["italian"],"loquace":["italian"],"lorenzo":["italian"],"loto":["italian"],"lotteria":["italian"],"luce":["italian"],"lucidato":["italian"],"lumaca":["italian"],"luminoso":["italian"],"lungo":["italian"],"lupo":["italian"],"luppolo":["italian"],"lusinga":["italian"],"lusso":["italian"],"lutto":["italian"],"macabro":["italian"],"macchina":["italian"],"macero":["italian"],"macinato":["italian"],"madama":["italian"],"magico":["italian"],"maglia":["italian"],"magnete":["italian"],"magro":["italian"],"maiolica":["italian"],"malafede":["italian"],"malgrado":["italian"],"malinteso":["italian"],"malsano":["italian"],"malto":["italian"],"malumore":["italian"],"mana":["italian"],"mancia":["italian"],"mandorla":["italian"],"mangiare":["italian"],"manifesto":["italian"],"mannaro":["italian"],"manovra":["italian"],"mansarda":["italian"],"mantide":["italian"],"manubrio":["italian"],"mappa":["italian"],"maratona":["italian"],"marcire":["italian"],"maretta":["italian"],"marmo":["italian"],"marsupio":["italian"],"maschera":["italian"],"massaia":["italian"],"mastino":["italian"],"materasso":["italian"],"matricola":["italian"],"mattone":["italian"],"maturo":["italian"],"mazurca":["italian"],"meandro":["italian"],"meccanico":["italian"],"mecenate":["italian"],"medesimo":["italian"],"meditare":["italian"],"mega":["italian"],"melassa":["italian"],"melis":["italian"],"melodia":["italian"],"meninge":["italian"],"meno":["italian"],"mensola":["italian"],"mercurio":["italian"],"merenda":["italian"],"merlo":["italian"],"meschino":["italian"],"mese":["italian"],"messere":["italian"],"mestolo":["italian"],"metallo":["italian"],"metodo":["italian"],"mettere":["italian"],"miagolare":["italian"],"mica":["italian"],"micelio":["italian"],"michele":["italian"],"microbo":["italian"],"midollo":["italian"],"miele":["italian"],"migliore":["italian"],"milano":["italian"],"milite":["italian"],"mimosa":["italian"],"minerale":["italian"],"mini":["italian"],"minore":["italian"],"mirino":["italian"],"mirtillo":["italian"],"miscela":["italian"],"missiva":["italian"],"misto":["italian"],"misurare":["italian"],"mitezza":["italian"],"mitigare":["italian"],"mitra":["italian"],"mittente":["italian"],"mnemonico":["italian"],"modello":["italian"],"modifica":["italian"],"modulo":["italian"],"mogano":["italian"],"mogio":["italian"],"mole":["italian"],"molosso":["italian"],"monastero":["italian"],"monco":["italian"],"mondina":["italian"],"monetario":["italian"],"monile":["italian"],"monotono":["italian"],"monsone":["italian"],"montato":["italian"],"monviso":["italian"],"mora":["italian"],"mordere":["italian"],"morsicato":["italian"],"mostro":["italian"],"motivato":["italian"],"motosega":["italian"],"motto":["italian"],"movenza":["italian"],"movimento":["italian"],"mozzo":["italian"],"mucca":["italian"],"mucosa":["italian"],"muffa":["italian"],"mughetto":["italian"],"mugnaio":["italian"],"mulatto":["italian"],"mulinello":["italian"],"multiplo":["italian"],"mummia":["italian"],"munto":["italian"],"muovere":["italian"],"murale":["italian"],"musa":["italian"],"muscolo":["italian"],"musica":["italian"],"mutevole":["italian"],"muto":["italian"],"nababbo":["italian"],"nafta":["italian"],"nanometro":["italian"],"narciso":["italian"],"narice":["italian"],"narrato":["italian"],"nascere":["italian"],"nastrare":["italian"],"naturale":["italian"],"nautica":["italian"],"naviglio":["italian"],"nebulosa":["italian"],"necrosi":["italian"],"negativo":["italian"],"negozio":["italian"],"nemmeno":["italian"],"neofita":["italian"],"neretto":["italian"],"nervo":["italian"],"nessuno":["italian"],"nettuno":["italian"],"neutrale":["italian"],"neve":["italian"],"nevrotico":["italian"],"nicchia":["italian"],"ninfa":["italian"],"nitido":["italian"],"nobile":["italian"],"nocivo":["italian"],"nodo":["italian"],"nome":["italian"],"nomina":["italian"],"nordico":["italian"],"normale":["italian"],"norvegese":["italian"],"nostrano":["italian"],"notare":["italian"],"notizia":["italian"],"notturno":["italian"],"novella":["italian"],"nucleo":["italian"],"nulla":["italian"],"numero":["italian"],"nuovo":["italian"],"nutrire":["italian"],"nuvola":["italian"],"nuziale":["italian"],"oasi":["italian"],"obbedire":["italian"],"obbligo":["italian"],"obelisco":["italian"],"oblio":["italian"],"obolo":["italian"],"obsoleto":["italian"],"occasione":["italian"],"occhio":["italian"],"occidente":["italian"],"occorrere":["italian"],"occultare":["italian"],"ocra":["italian"],"oculato":["italian"],"odierno":["italian"],"odorare":["italian"],"offerta":["italian"],"offrire":["italian"],"offuscato":["italian"],"oggetto":["italian"],"oggi":["italian"],"ognuno":["italian"],"olandese":["italian"],"olfatto":["italian"],"oliato":["italian"],"oliva":["italian"],"ologramma":["italian"],"oltre":["italian"],"omaggio":["italian"],"ombelico":["italian"],"ombra":["italian"],"omega":["italian"],"omissione":["italian"],"ondoso":["italian"],"onere":["italian"],"onice":["italian"],"onnivoro":["italian"],"onorevole":["italian"],"onta":["italian"],"operato":["italian"],"opinione":["italian"],"opposto":["italian"],"oracolo":["italian"],"orafo":["italian"],"ordine":["italian"],"orecchino":["italian"],"orefice":["italian"],"orfano":["italian"],"organico":["italian"],"origine":["italian"],"orizzonte":["italian"],"orma":["italian"],"ormeggio":["italian"],"ornativo":["italian"],"orologio":["italian"],"orrendo":["italian"],"orribile":["italian"],"ortensia":["italian"],"ortica":["italian"],"orzata":["italian"],"orzo":["italian"],"osare":["italian"],"oscurare":["italian"],"osmosi":["italian"],"ospedale":["italian"],"ospite":["italian"],"ossa":["italian"],"ossidare":["italian"],"ostacolo":["italian"],"oste":["italian"],"otite":["italian"],"otre":["italian"],"ottagono":["italian"],"ottimo":["italian"],"ottobre":["italian"],"ovale":["italian"],"ovest":["italian"],"ovino":["italian"],"oviparo":["italian"],"ovocito":["italian"],"ovunque":["italian"],"ovviare":["italian"],"ozio":["italian"],"pacchetto":["italian"],"pace":["italian"],"pacifico":["italian"],"padella":["italian"],"padrone":["italian"],"paese":["italian"],"paga":["italian"],"pagina":["italian"],"palazzina":["italian"],"palesare":["italian"],"pallido":["italian"],"palo":["italian"],"palude":["italian"],"pandoro":["italian"],"pannello":["italian"],"paolo":["italian"],"paonazzo":["italian"],"paprica":["italian"],"parabola":["italian"],"parcella":["italian"],"parere":["italian"],"pargolo":["italian"],"pari":["italian"],"parlato":["italian"],"parola":["italian"],"partire":["italian"],"parvenza":["italian"],"parziale":["italian"],"passivo":["italian"],"pasticca":["italian"],"patacca":["italian"],"patologia":["italian"],"pattume":["italian"],"pavone":["italian"],"peccato":["italian"],"pedalare":["italian"],"pedonale":["italian"],"peggio":["italian"],"peloso":["italian"],"penare":["italian"],"pendice":["italian"],"penisola":["italian"],"pennuto":["italian"],"penombra":["italian"],"pensare":["italian"],"pentola":["italian"],"pepe":["italian"],"pepita":["italian"],"perbene":["italian"],"percorso":["italian"],"perdonato":["italian"],"perforare":["italian"],"pergamena":["italian"],"periodo":["italian"],"permesso":["italian"],"perno":["italian"],"perplesso":["italian"],"persuaso":["italian"],"pertugio":["italian"],"pervaso":["italian"],"pesatore":["italian"],"pesista":["italian"],"peso":["italian"],"pestifero":["italian"],"petalo":["italian"],"pettine":["italian"],"petulante":["italian"],"pezzo":["italian"],"piacere":["italian"],"pianta":["italian"],"piattino":["italian"],"piccino":["italian"],"picozza":["italian"],"piega":["italian"],"pietra":["italian"],"piffero":["italian"],"pigiama":["italian"],"pigolio":["italian"],"pigro":["italian"],"pila":["italian"],"pilifero":["italian"],"pillola":["italian"],"pilota":["italian"],"pimpante":["italian"],"pineta":["italian"],"pinna":["italian"],"pinolo":["italian"],"pioggia":["italian"],"piombo":["italian"],"piramide":["italian"],"piretico":["italian"],"pirite":["italian"],"pirolisi":["italian"],"pitone":["italian"],"pizzico":["italian"],"placebo":["italian"],"planare":["italian"],"plasma":["italian"],"platano":["italian"],"plenario":["italian"],"pochezza":["italian"],"poderoso":["italian"],"podismo":["italian"],"poesia":["italian"],"poggiare":["italian"],"polenta":["italian"],"poligono":["italian"],"pollice":["italian"],"polmonite":["italian"],"polpetta":["italian"],"polso":["italian"],"poltrona":["italian"],"polvere":["italian"],"pomice":["italian"],"pomodoro":["italian"],"ponte":["italian"],"popoloso":["italian"],"porfido":["italian"],"poroso":["italian"],"porpora":["italian"],"porre":["italian"],"portata":["italian"],"posa":["italian","turkish"],"positivo":["italian"],"possesso":["italian"],"postulato":["italian"],"potassio":["italian"],"potere":["italian"],"pranzo":["italian"],"prassi":["italian"],"pratica":["italian"],"precluso":["italian"],"predica":["italian"],"prefisso":["italian"],"pregiato":["italian"],"prelievo":["italian"],"premere":["italian"],"prenotare":["italian"],"preparato":["italian"],"presenza":["italian"],"pretesto":["italian"],"prevalso":["italian"],"prima":["italian"],"principe":["italian"],"privato":["italian"],"problema":["italian"],"procura":["italian"],"produrre":["italian"],"profumo":["italian"],"progetto":["italian"],"prolunga":["italian"],"promessa":["italian"],"pronome":["italian"],"proposta":["italian"],"proroga":["italian"],"proteso":["italian"],"prova":["italian","turkish"],"prudente":["italian"],"prugna":["italian"],"prurito":["italian"],"psiche":["italian"],"pubblico":["italian"],"pudica":["italian"],"pugilato":["italian"],"pugno":["italian"],"pulce":["italian"],"pulito":["italian"],"pulsante":["italian"],"puntare":["italian"],"pupazzo":["italian"],"pupilla":["italian"],"puro":["italian"],"quadro":["italian"],"qualcosa":["italian"],"quasi":["italian"],"querela":["italian"],"quota":["italian"],"raccolto":["italian"],"raddoppio":["italian"],"radicale":["italian"],"radunato":["italian"],"raffica":["italian"],"ragazzo":["italian"],"ragione":["italian"],"ragno":["italian"],"ramarro":["italian"],"ramingo":["italian"],"ramo":["italian"],"randagio":["italian"],"rantolare":["italian"],"rapato":["italian"],"rapina":["italian"],"rappreso":["italian"],"rasatura":["italian"],"raschiato":["italian"],"rasente":["italian"],"rassegna":["italian"],"rastrello":["italian"],"rata":["italian"],"ravveduto":["italian"],"reale":["italian"],"recepire":["italian"],"recinto":["italian"],"recluta":["italian"],"recondito":["italian"],"recupero":["italian"],"reddito":["italian"],"redimere":["italian"],"regalato":["italian"],"registro":["italian"],"regola":["italian"],"regresso":["italian"],"relazione":["italian"],"remare":["italian"],"remoto":["italian"],"renna":["italian"],"replica":["italian"],"reprimere":["italian"],"reputare":["italian"],"resa":["italian"],"residente":["italian"],"responso":["italian"],"restauro":["italian"],"rete":["italian"],"retina":["italian"],"retorica":["italian"],"rettifica":["italian"],"revocato":["italian"],"riassunto":["italian"],"ribadire":["italian"],"ribelle":["italian"],"ribrezzo":["italian"],"ricarica":["italian"],"ricco":["italian"],"ricevere":["italian"],"riciclato":["italian"],"ricordo":["italian"],"ricreduto":["italian"],"ridicolo":["italian"],"ridurre":["italian"],"rifasare":["italian"],"riflesso":["italian"],"riforma":["italian"],"rifugio":["italian"],"rigare":["italian"],"rigettato":["italian"],"righello":["italian"],"rilassato":["italian"],"rilevato":["italian"],"rimanere":["italian"],"rimbalzo":["italian"],"rimedio":["italian"],"rimorchio":["italian"],"rinascita":["italian"],"rincaro":["italian"],"rinforzo":["italian"],"rinnovo":["italian"],"rinomato":["italian"],"rinsavito":["italian"],"rintocco":["italian"],"rinuncia":["italian"],"rinvenire":["italian"],"riparato":["italian"],"ripetuto":["italian"],"ripieno":["italian"],"riportare":["italian"],"ripresa":["italian"],"ripulire":["italian"],"risata":["italian"],"rischio":["italian"],"riserva":["italian"],"risibile":["italian"],"riso":["italian"],"rispetto":["italian"],"ristoro":["italian"],"risultato":["italian"],"risvolto":["italian"],"ritardo":["italian"],"ritegno":["italian"],"ritmico":["italian"],"ritrovo":["italian"],"riunione":["italian"],"riva":["italian"],"riverso":["italian"],"rivincita":["italian"],"rivolto":["italian"],"rizoma":["italian"],"roba":["italian"],"robotico":["italian"],"robusto":["italian"],"roccia":["italian"],"roco":["italian"],"rodaggio":["italian"],"rodere":["italian"],"roditore":["italian"],"rogito":["italian"],"rollio":["italian"],"romantico":["italian"],"rompere":["italian"],"ronzio":["italian"],"rosolare":["italian"],"rospo":["italian"],"rotante":["italian"],"rotondo":["italian"],"rotula":["italian"],"rovescio":["italian"],"rubizzo":["italian"],"rubrica":["italian"],"ruga":["italian"],"rullino":["italian"],"rumine":["italian"],"rumoroso":["italian"],"ruolo":["italian"],"rupe":["italian"],"russare":["italian"],"rustico":["italian"],"sabato":["italian"],"sabbiare":["italian"],"sabotato":["italian"],"sagoma":["italian"],"salasso":["italian"],"saldatura":["italian"],"salgemma":["italian"],"salivare":["italian"],"salmone":["italian"],"salone":["italian"],"saltare":["italian"],"saluto":["italian"],"salvo":["italian"],"sapere":["italian"],"sapido":["italian"],"saporito":["italian"],"saraceno":["italian"],"sarcasmo":["italian"],"sarto":["italian"],"sassoso":["italian"],"satellite":["italian"],"satira":["italian"],"satollo":["italian"],"saturno":["italian"],"savana":["italian"],"savio":["italian"],"saziato":["italian"],"sbadiglio":["italian"],"sbalzo":["italian"],"sbancato":["italian"],"sbarra":["italian"],"sbattere":["italian"],"sbavare":["italian"],"sbendare":["italian"],"sbirciare":["italian"],"sbloccato":["italian"],"sbocciato":["italian"],"sbrinare":["italian"],"sbruffone":["italian"],"sbuffare":["italian"],"scabroso":["italian"],"scadenza":["italian"],"scala":["italian"],"scambiare":["italian"],"scandalo":["italian"],"scapola":["italian"],"scarso":["italian"],"scatenare":["italian"],"scavato":["italian"],"scelto":["italian"],"scenico":["italian"],"scettro":["italian"],"scheda":["italian"],"schiena":["italian"],"sciarpa":["italian"],"scienza":["italian"],"scindere":["italian"],"scippo":["italian"],"sciroppo":["italian"],"scivolo":["italian"],"sclerare":["italian"],"scodella":["italian"],"scolpito":["italian"],"scomparto":["italian"],"sconforto":["italian"],"scoprire":["italian"],"scorta":["italian"],"scossone":["italian"],"scozzese":["italian"],"scriba":["italian"],"scrollare":["italian"],"scrutinio":["italian"],"scuderia":["italian"],"scultore":["italian"],"scuola":["italian"],"scuro":["italian"],"scusare":["italian"],"sdebitare":["italian"],"sdoganare":["italian"],"seccatura":["italian"],"secondo":["italian"],"sedano":["italian"],"seggiola":["italian"],"segnalato":["italian"],"segregato":["italian"],"seguito":["italian"],"selciato":["italian"],"selettivo":["italian"],"sella":["italian"],"selvaggio":["italian"],"semaforo":["italian"],"sembrare":["italian"],"seme":["italian"],"seminato":["italian"],"sempre":["italian"],"senso":["italian"],"sentire":["italian"],"sepolto":["italian"],"sequenza":["italian"],"serata":["italian"],"serbato":["italian"],"sereno":["italian"],"serio":["italian"],"serpente":["italian"],"serraglio":["italian"],"servire":["italian"],"sestina":["italian"],"setola":["italian"],"settimana":["italian"],"sfacelo":["italian"],"sfaldare":["italian"],"sfamato":["italian"],"sfarzoso":["italian"],"sfaticato":["italian"],"sfera":["italian"],"sfida":["italian"],"sfilato":["italian"],"sfinge":["italian"],"sfocato":["italian"],"sfoderare":["italian"],"sfogo":["italian"],"sfoltire":["italian"],"sforzato":["italian"],"sfratto":["italian"],"sfruttato":["italian"],"sfuggito":["italian"],"sfumare":["italian"],"sfuso":["italian"],"sgabello":["italian"],"sgarbato":["italian"],"sgonfiare":["italian"],"sgorbio":["italian"],"sgrassato":["italian"],"sguardo":["italian"],"sibilo":["italian"],"siccome":["italian"],"sierra":["italian"],"sigla":["italian"],"signore":["italian"],"silenzio":["italian"],"sillaba":["italian"],"simbolo":["italian"],"simpatico":["italian"],"simulato":["italian"],"sinfonia":["italian"],"singolo":["italian"],"sinistro":["italian"],"sino":["italian"],"sintesi":["italian"],"sinusoide":["italian"],"sipario":["italian"],"sisma":["italian"],"sistole":["italian"],"situato":["italian"],"slitta":["italian"],"slogatura":["italian"],"sloveno":["italian"],"smarrito":["italian"],"smemorato":["italian"],"smentito":["italian"],"smeraldo":["italian"],"smilzo":["italian"],"smontare":["italian"],"smottato":["italian"],"smussato":["italian"],"snellire":["italian"],"snervato":["italian"],"snodo":["italian"],"sobbalzo":["italian"],"sobrio":["italian"],"soccorso":["italian"],"sociale":["italian"],"sodale":["italian"],"soffitto":["italian"],"sogno":["italian"],"soldato":["italian"],"solenne":["italian"],"solido":["italian"],"sollazzo":["italian"],"solo":["italian"],"solubile":["italian"],"solvente":["italian"],"somatico":["italian"],"somma":["italian"],"sonda":["italian"],"sonetto":["italian"],"sonnifero":["italian"],"sopire":["italian"],"soppeso":["italian"],"sopra":["italian"],"sorgere":["italian"],"sorpasso":["italian"],"sorriso":["italian"],"sorso":["italian"],"sorteggio":["italian"],"sorvolato":["italian"],"sospiro":["italian"],"sosta":["italian"],"sottile":["italian"],"spada":["italian"],"spalla":["italian"],"spargere":["italian"],"spatola":["italian"],"spavento":["italian"],"spazzola":["italian"],"specie":["italian"],"spedire":["italian"],"spegnere":["italian"],"spelatura":["italian"],"speranza":["italian"],"spessore":["italian"],"spettrale":["italian"],"spezzato":["italian"],"spia":["italian"],"spigoloso":["italian"],"spillato":["italian"],"spinoso":["italian"],"spirale":["italian"],"splendido":["italian"],"sportivo":["italian"],"sposo":["italian"],"spranga":["italian"],"sprecare":["italian"],"spronato":["italian"],"spruzzo":["italian"],"spuntino":["italian"],"squillo":["italian"],"sradicare":["italian"],"srotolato":["italian"],"stabile":["italian"],"stacco":["italian"],"staffa":["italian"],"stagnare":["italian"],"stampato":["italian"],"stantio":["italian"],"starnuto":["italian"],"stasera":["italian"],"statuto":["italian"],"stelo":["italian"],"steppa":["italian"],"sterzo":["italian"],"stiletto":["italian"],"stima":["italian"],"stirpe":["italian"],"stivale":["italian"],"stizzoso":["italian"],"stonato":["italian"],"storico":["italian"],"strappo":["italian"],"stregato":["italian"],"stridulo":["italian"],"strozzare":["italian"],"strutto":["italian"],"stuccare":["italian"],"stufo":["italian"],"stupendo":["italian"],"subentro":["italian"],"succoso":["italian"],"sudore":["italian"],"suggerito":["italian"],"sugo":["italian"],"sultano":["italian"],"suonare":["italian"],"superbo":["italian"],"supporto":["italian"],"surgelato":["italian"],"surrogato":["italian"],"sussurro":["italian"],"sutura":["italian"],"svagare":["italian"],"svedese":["italian"],"sveglio":["italian"],"svelare":["italian"],"svenuto":["italian"],"svezia":["italian"],"sviluppo":["italian"],"svista":["italian"],"svizzera":["italian"],"svolta":["italian"],"svuotare":["italian"],"tabacco":["italian"],"tabulato":["italian"],"tacciare":["italian"],"taciturno":["italian"],"tale":["italian"],"talismano":["italian"],"tampone":["italian"],"tannino":["italian"],"tara":["italian"],"tardivo":["italian"],"targato":["italian"],"tariffa":["italian"],"tarpare":["italian"],"tartaruga":["italian"],"tasto":["italian"],"tattico":["italian"],"taverna":["italian"],"tavolata":["italian"],"tazza":["italian"],"teca":["italian"],"tecnico":["italian"],"telefono":["italian"],"temerario":["italian"],"tempo":["italian","turkish"],"temuto":["italian"],"tendone":["italian"],"tenero":["italian"],"tensione":["italian"],"tentacolo":["italian"],"teorema":["italian"],"terme":["italian"],"terrazzo":["italian"],"terzetto":["italian"],"tesi":["italian"],"tesserato":["italian"],"testato":["italian"],"tetro":["italian"],"tettoia":["italian"],"tifare":["italian"],"tigella":["italian"],"timbro":["italian"],"tinto":["italian"],"tipico":["italian"],"tipografo":["italian"],"tiraggio":["italian"],"tiro":["italian"],"titanio":["italian"],"titolo":["italian"],"titubante":["italian"],"tizio":["italian"],"tizzone":["italian"],"toccare":["italian"],"tollerare":["italian"],"tolto":["italian"],"tombola":["italian"],"tomo":["italian"],"tonfo":["italian"],"tonsilla":["italian"],"topazio":["italian"],"topologia":["italian"],"toppa":["italian"],"torba":["italian"],"tornare":["italian"],"torrone":["italian"],"tortora":["italian"],"toscano":["italian"],"tossire":["italian"],"tostatura":["italian"],"totano":["italian"],"trabocco":["italian"],"trachea":["italian"],"trafila":["italian"],"tragedia":["italian"],"tralcio":["italian"],"tramonto":["italian"],"transito":["italian"],"trapano":["italian"],"trarre":["italian"],"trasloco":["italian"],"trattato":["italian"],"trave":["italian"],"treccia":["italian"],"tremolio":["italian"],"trespolo":["italian"],"tributo":["italian"],"tricheco":["italian"],"trifoglio":["italian"],"trillo":["italian"],"trincea":["italian"],"trio":["italian"],"tristezza":["italian"],"triturato":["italian"],"trivella":["italian"],"tromba":["italian"],"trono":["italian"],"troppo":["italian"],"trottola":["italian"],"trovare":["italian"],"truccato":["italian"],"tubatura":["italian"],"tuffato":["italian"],"tulipano":["italian"],"tumulto":["italian"],"tunisia":["italian"],"turbare":["italian"],"turchino":["italian"],"tuta":["italian"],"tutela":["italian"],"ubicato":["italian"],"uccello":["italian"],"uccisore":["italian"],"udire":["italian"],"uditivo":["italian"],"uffa":["italian"],"ufficio":["italian"],"uguale":["italian"],"ulisse":["italian"],"ultimato":["italian"],"umano":["italian"],"umile":["italian"],"umorismo":["italian"],"uncinetto":["italian"],"ungere":["italian"],"ungherese":["italian"],"unicorno":["italian"],"unificato":["italian"],"unisono":["italian"],"unitario":["italian"],"unte":["italian"],"uovo":["italian"],"upupa":["italian"],"uragano":["italian"],"urgenza":["italian"],"urlo":["italian"],"usanza":["italian"],"usato":["italian"],"uscito":["italian"],"usignolo":["italian"],"usuraio":["italian"],"utensile":["italian"],"utilizzo":["italian"],"utopia":["italian"],"vacante":["italian"],"vaccinato":["italian"],"vagabondo":["italian"],"vagliato":["italian"],"valanga":["italian"],"valgo":["italian"],"valico":["italian"],"valletta":["italian"],"valoroso":["italian"],"valutare":["italian"],"valvola":["italian"],"vampata":["italian"],"vangare":["italian"],"vanitoso":["italian"],"vano":["italian"],"vantaggio":["italian"],"vanvera":["italian"],"vapore":["italian"],"varano":["italian"],"varcato":["italian"],"variante":["italian"],"vasca":["italian"],"vedetta":["italian"],"vedova":["italian"],"veduto":["italian"],"vegetale":["italian"],"veicolo":["italian"],"velcro":["italian"],"velina":["italian"],"velluto":["italian"],"veloce":["italian"],"venato":["italian"],"vendemmia":["italian"],"vento":["italian"],"verace":["italian"],"verbale":["italian"],"vergogna":["italian"],"verifica":["italian"],"vero":["italian"],"verruca":["italian"],"verticale":["italian"],"vescica":["italian"],"vessillo":["italian"],"vestale":["italian"],"veterano":["italian"],"vetrina":["italian"],"vetusto":["italian"],"viandante":["italian"],"vibrante":["italian"],"vicenda":["italian"],"vichingo":["italian"],"vicinanza":["italian"],"vidimare":["italian"],"vigilia":["italian"],"vigneto":["italian"],"vigore":["italian"],"vile":["italian"],"villano":["italian"],"vimini":["italian"],"vincitore":["italian"],"viola":["italian"],"vipera":["italian"],"virgola":["italian"],"virologo":["italian"],"virulento":["italian"],"viscoso":["italian"],"visione":["italian"],"vispo":["italian"],"vissuto":["italian"],"visura":["italian"],"vita":["italian"],"vitello":["italian"],"vittima":["italian"],"vivanda":["italian"],"vivido":["italian"],"viziare":["italian"],"voce":["italian"],"voga":["italian"],"volatile":["italian"],"volere":["italian"],"volpe":["italian"],"voragine":["italian"],"vulcano":["italian"],"zampogna":["italian"],"zanna":["italian"],"zappato":["italian"],"zattera":["italian"],"zavorra":["italian"],"zefiro":["italian"],"zelante":["italian"],"zelo":["italian"],"zenzero":["italian"],"zerbino":["italian"],"zibetto":["italian"],"zinco":["italian"],"zircone":["italian"],"zitto":["italian"],"zolla":["italian"],"zotico":["italian"],"zucchero":["italian"],"zufolo":["italian"],"zulu":["italian"],"zuppa":["italian"],"あいこくしん":["japanese"],"あいさつ":["japanese"],"あいだ":["japanese"],"あおぞら":["japanese"],"あかちゃん":["japanese"],"あきる":["japanese"],"あけがた":["japanese"],"あける":["japanese"],"あこがれる":["japanese"],"あさい":["japanese"],"あさひ":["japanese"],"あしあと":["japanese"],"あじわう":["japanese"],"あずかる":["japanese"],"あずき":["japanese"],"あそぶ":["japanese"],"あたえる":["japanese"],"あたためる":["japanese"],"あたりまえ":["japanese"],"あたる":["japanese"],"あつい":["japanese"],"あつかう":["japanese"],"あっしゅく":["japanese"],"あつまり":["japanese"],"あつめる":["japanese"],"あてな":["japanese"],"あてはまる":["japanese"],"あひる":["japanese"],"あぶら":["japanese"],"あぶる":["japanese"],"あふれる":["japanese"],"あまい":["japanese"],"あまど":["japanese"],"あまやかす":["japanese"],"あまり":["japanese"],"あみもの":["japanese"],"あめりか":["japanese"],"あやまる":["japanese"],"あゆむ":["japanese"],"あらいぐま":["japanese"],"あらし":["japanese"],"あらすじ":["japanese"],"あらためる":["japanese"],"あらゆる":["japanese"],"あらわす":["japanese"],"ありがとう":["japanese"],"あわせる":["japanese"],"あわてる":["japanese"],"あんい":["japanese"],"あんがい":["japanese"],"あんこ":["japanese"],"あんぜん":["japanese"],"あんてい":["japanese"],"あんない":["japanese"],"あんまり":["japanese"],"いいだす":["japanese"],"いおん":["japanese"],"いがい":["japanese"],"いがく":["japanese"],"いきおい":["japanese"],"いきなり":["japanese"],"いきもの":["japanese"],"いきる":["japanese"],"いくじ":["japanese"],"いくぶん":["japanese"],"いけばな":["japanese"],"いけん":["japanese"],"いこう":["japanese"],"いこく":["japanese"],"いこつ":["japanese"],"いさましい":["japanese"],"いさん":["japanese"],"いしき":["japanese"],"いじゅう":["japanese"],"いじょう":["japanese"],"いじわる":["japanese"],"いずみ":["japanese"],"いずれ":["japanese"],"いせい":["japanese"],"いせえび":["japanese"],"いせかい":["japanese"],"いせき":["japanese"],"いぜん":["japanese"],"いそうろう":["japanese"],"いそがしい":["japanese"],"いだい":["japanese"],"いだく":["japanese"],"いたずら":["japanese"],"いたみ":["japanese"],"いたりあ":["japanese"],"いちおう":["japanese"],"いちじ":["japanese"],"いちど":["japanese"],"いちば":["japanese"],"いちぶ":["japanese"],"いちりゅう":["japanese"],"いつか":["japanese"],"いっしゅん":["japanese"],"いっせい":["japanese"],"いっそう":["japanese"],"いったん":["japanese"],"いっち":["japanese"],"いってい":["japanese"],"いっぽう":["japanese"],"いてざ":["japanese"],"いてん":["japanese"],"いどう":["japanese"],"いとこ":["japanese"],"いない":["japanese"],"いなか":["japanese"],"いねむり":["japanese"],"いのち":["japanese"],"いのる":["japanese"],"いはつ":["japanese"],"いばる":["japanese"],"いはん":["japanese"],"いびき":["japanese"],"いひん":["japanese"],"いふく":["japanese"],"いへん":["japanese"],"いほう":["japanese"],"いみん":["japanese"],"いもうと":["japanese"],"いもたれ":["japanese"],"いもり":["japanese"],"いやがる":["japanese"],"いやす":["japanese"],"いよかん":["japanese"],"いよく":["japanese"],"いらい":["japanese"],"いらすと":["japanese"],"いりぐち":["japanese"],"いりょう":["japanese"],"いれい":["japanese"],"いれもの":["japanese"],"いれる":["japanese"],"いろえんぴつ":["japanese"],"いわい":["japanese"],"いわう":["japanese"],"いわかん":["japanese"],"いわば":["japanese"],"いわゆる":["japanese"],"いんげんまめ":["japanese"],"いんさつ":["japanese"],"いんしょう":["japanese"],"いんよう":["japanese"],"うえき":["japanese"],"うえる":["japanese"],"うおざ":["japanese"],"うがい":["japanese"],"うかぶ":["japanese"],"うかべる":["japanese"],"うきわ":["japanese"],"うくらいな":["japanese"],"うくれれ":["japanese"],"うけたまわる":["japanese"],"うけつけ":["japanese"],"うけとる":["japanese"],"うけもつ":["japanese"],"うける":["japanese"],"うごかす":["japanese"],"うごく":["japanese"],"うこん":["japanese"],"うさぎ":["japanese"],"うしなう":["japanese"],"うしろがみ":["japanese"],"うすい":["japanese"],"うすぎ":["japanese"],"うすぐらい":["japanese"],"うすめる":["japanese"],"うせつ":["japanese"],"うちあわせ":["japanese"],"うちがわ":["japanese"],"うちき":["japanese"],"うちゅう":["japanese"],"うっかり":["japanese"],"うつくしい":["japanese"],"うったえる":["japanese"],"うつる":["japanese"],"うどん":["japanese"],"うなぎ":["japanese"],"うなじ":["japanese"],"うなずく":["japanese"],"うなる":["japanese"],"うねる":["japanese"],"うのう":["japanese"],"うぶげ":["japanese"],"うぶごえ":["japanese"],"うまれる":["japanese"],"うめる":["japanese"],"うもう":["japanese"],"うやまう":["japanese"],"うよく":["japanese"],"うらがえす":["japanese"],"うらぐち":["japanese"],"うらない":["japanese"],"うりあげ":["japanese"],"うりきれ":["japanese"],"うるさい":["japanese"],"うれしい":["japanese"],"うれゆき":["japanese"],"うれる":["japanese"],"うろこ":["japanese"],"うわき":["japanese"],"うわさ":["japanese"],"うんこう":["japanese"],"うんちん":["japanese"],"うんてん":["japanese"],"うんどう":["japanese"],"えいえん":["japanese"],"えいが":["japanese"],"えいきょう":["japanese"],"えいご":["japanese"],"えいせい":["japanese"],"えいぶん":["japanese"],"えいよう":["japanese"],"えいわ":["japanese"],"えおり":["japanese"],"えがお":["japanese"],"えがく":["japanese"],"えきたい":["japanese"],"えくせる":["japanese"],"えしゃく":["japanese"],"えすて":["japanese"],"えつらん":["japanese"],"えのぐ":["japanese"],"えほうまき":["japanese"],"えほん":["japanese"],"えまき":["japanese"],"えもじ":["japanese"],"えもの":["japanese"],"えらい":["japanese"],"えらぶ":["japanese"],"えりあ":["japanese"],"えんえん":["japanese"],"えんかい":["japanese"],"えんぎ":["japanese"],"えんげき":["japanese"],"えんしゅう":["japanese"],"えんぜつ":["japanese"],"えんそく":["japanese"],"えんちょう":["japanese"],"えんとつ":["japanese"],"おいかける":["japanese"],"おいこす":["japanese"],"おいしい":["japanese"],"おいつく":["japanese"],"おうえん":["japanese"],"おうさま":["japanese"],"おうじ":["japanese"],"おうせつ":["japanese"],"おうたい":["japanese"],"おうふく":["japanese"],"おうべい":["japanese"],"おうよう":["japanese"],"おえる":["japanese"],"おおい":["japanese"],"おおう":["japanese"],"おおどおり":["japanese"],"おおや":["japanese"],"おおよそ":["japanese"],"おかえり":["japanese"],"おかず":["japanese"],"おがむ":["japanese"],"おかわり":["japanese"],"おぎなう":["japanese"],"おきる":["japanese"],"おくさま":["japanese"],"おくじょう":["japanese"],"おくりがな":["japanese"],"おくる":["japanese"],"おくれる":["japanese"],"おこす":["japanese"],"おこなう":["japanese"],"おこる":["japanese"],"おさえる":["japanese"],"おさない":["japanese"],"おさめる":["japanese"],"おしいれ":["japanese"],"おしえる":["japanese"],"おじぎ":["japanese"],"おじさん":["japanese"],"おしゃれ":["japanese"],"おそらく":["japanese"],"おそわる":["japanese"],"おたがい":["japanese"],"おたく":["japanese"],"おだやか":["japanese"],"おちつく":["japanese"],"おっと":["japanese"],"おつり":["japanese"],"おでかけ":["japanese"],"おとしもの":["japanese"],"おとなしい":["japanese"],"おどり":["japanese"],"おどろかす":["japanese"],"おばさん":["japanese"],"おまいり":["japanese"],"おめでとう":["japanese"],"おもいで":["japanese"],"おもう":["japanese"],"おもたい":["japanese"],"おもちゃ":["japanese"],"おやつ":["japanese"],"おやゆび":["japanese"],"およぼす":["japanese"],"おらんだ":["japanese"],"おろす":["japanese"],"おんがく":["japanese"],"おんけい":["japanese"],"おんしゃ":["japanese"],"おんせん":["japanese"],"おんだん":["japanese"],"おんちゅう":["japanese"],"おんどけい":["japanese"],"かあつ":["japanese"],"かいが":["japanese"],"がいき":["japanese"],"がいけん":["japanese"],"がいこう":["japanese"],"かいさつ":["japanese"],"かいしゃ":["japanese"],"かいすいよく":["japanese"],"かいぜん":["japanese"],"かいぞうど":["japanese"],"かいつう":["japanese"],"かいてん":["japanese"],"かいとう":["japanese"],"かいふく":["japanese"],"がいへき":["japanese"],"かいほう":["japanese"],"かいよう":["japanese"],"がいらい":["japanese"],"かいわ":["japanese"],"かえる":["japanese"],"かおり":["japanese"],"かかえる":["japanese"],"かがく":["japanese"],"かがし":["japanese"],"かがみ":["japanese"],"かくご":["japanese"],"かくとく":["japanese"],"かざる":["japanese"],"がぞう":["japanese"],"かたい":["japanese"],"かたち":["japanese"],"がちょう":["japanese"],"がっきゅう":["japanese"],"がっこう":["japanese"],"がっさん":["japanese"],"がっしょう":["japanese"],"かなざわし":["japanese"],"かのう":["japanese"],"がはく":["japanese"],"かぶか":["japanese"],"かほう":["japanese"],"かほご":["japanese"],"かまう":["japanese"],"かまぼこ":["japanese"],"かめれおん":["japanese"],"かゆい":["japanese"],"かようび":["japanese"],"からい":["japanese"],"かるい":["japanese"],"かろう":["japanese"],"かわく":["japanese"],"かわら":["japanese"],"がんか":["japanese"],"かんけい":["japanese"],"かんこう":["japanese"],"かんしゃ":["japanese"],"かんそう":["japanese"],"かんたん":["japanese"],"かんち":["japanese"],"がんばる":["japanese"],"きあい":["japanese"],"きあつ":["japanese"],"きいろ":["japanese"],"ぎいん":["japanese"],"きうい":["japanese"],"きうん":["japanese"],"きえる":["japanese"],"きおう":["japanese"],"きおく":["japanese"],"きおち":["japanese"],"きおん":["japanese"],"きかい":["japanese"],"きかく":["japanese"],"きかんしゃ":["japanese"],"ききて":["japanese"],"きくばり":["japanese"],"きくらげ":["japanese"],"きけんせい":["japanese"],"きこう":["japanese"],"きこえる":["japanese"],"きこく":["japanese"],"きさい":["japanese"],"きさく":["japanese"],"きさま":["japanese"],"きさらぎ":["japanese"],"ぎじかがく":["japanese"],"ぎしき":["japanese"],"ぎじたいけん":["japanese"],"ぎじにってい":["japanese"],"ぎじゅつしゃ":["japanese"],"きすう":["japanese"],"きせい":["japanese"],"きせき":["japanese"],"きせつ":["japanese"],"きそう":["japanese"],"きぞく":["japanese"],"きぞん":["japanese"],"きたえる":["japanese"],"きちょう":["japanese"],"きつえん":["japanese"],"ぎっちり":["japanese"],"きつつき":["japanese"],"きつね":["japanese"],"きてい":["japanese"],"きどう":["japanese"],"きどく":["japanese"],"きない":["japanese"],"きなが":["japanese"],"きなこ":["japanese"],"きぬごし":["japanese"],"きねん":["japanese"],"きのう":["japanese"],"きのした":["japanese"],"きはく":["japanese"],"きびしい":["japanese"],"きひん":["japanese"],"きふく":["japanese"],"きぶん":["japanese"],"きぼう":["japanese"],"きほん":["japanese"],"きまる":["japanese"],"きみつ":["japanese"],"きむずかしい":["japanese"],"きめる":["japanese"],"きもだめし":["japanese"],"きもち":["japanese"],"きもの":["japanese"],"きゃく":["japanese"],"きやく":["japanese"],"ぎゅうにく":["japanese"],"きよう":["japanese"],"きょうりゅう":["japanese"],"きらい":["japanese"],"きらく":["japanese"],"きりん":["japanese"],"きれい":["japanese"],"きれつ":["japanese"],"きろく":["japanese"],"ぎろん":["japanese"],"きわめる":["japanese"],"ぎんいろ":["japanese"],"きんかくじ":["japanese"],"きんじょ":["japanese"],"きんようび":["japanese"],"ぐあい":["japanese"],"くいず":["japanese"],"くうかん":["japanese"],"くうき":["japanese"],"くうぐん":["japanese"],"くうこう":["japanese"],"ぐうせい":["japanese"],"くうそう":["japanese"],"ぐうたら":["japanese"],"くうふく":["japanese"],"くうぼ":["japanese"],"くかん":["japanese"],"くきょう":["japanese"],"くげん":["japanese"],"ぐこう":["japanese"],"くさい":["japanese"],"くさき":["japanese"],"くさばな":["japanese"],"くさる":["japanese"],"くしゃみ":["japanese"],"くしょう":["japanese"],"くすのき":["japanese"],"くすりゆび":["japanese"],"くせげ":["japanese"],"くせん":["japanese"],"ぐたいてき":["japanese"],"くださる":["japanese"],"くたびれる":["japanese"],"くちこみ":["japanese"],"くちさき":["japanese"],"くつした":["japanese"],"ぐっすり":["japanese"],"くつろぐ":["japanese"],"くとうてん":["japanese"],"くどく":["japanese"],"くなん":["japanese"],"くねくね":["japanese"],"くのう":["japanese"],"くふう":["japanese"],"くみあわせ":["japanese"],"くみたてる":["japanese"],"くめる":["japanese"],"くやくしょ":["japanese"],"くらす":["japanese"],"くらべる":["japanese"],"くるま":["japanese"],"くれる":["japanese"],"くろう":["japanese"],"くわしい":["japanese"],"ぐんかん":["japanese"],"ぐんしょく":["japanese"],"ぐんたい":["japanese"],"ぐんて":["japanese"],"けあな":["japanese"],"けいかく":["japanese"],"けいけん":["japanese"],"けいこ":["japanese"],"けいさつ":["japanese"],"げいじゅつ":["japanese"],"けいたい":["japanese"],"げいのうじん":["japanese"],"けいれき":["japanese"],"けいろ":["japanese"],"けおとす":["japanese"],"けおりもの":["japanese"],"げきか":["japanese"],"げきげん":["japanese"],"げきだん":["japanese"],"げきちん":["japanese"],"げきとつ":["japanese"],"げきは":["japanese"],"げきやく":["japanese"],"げこう":["japanese"],"げこくじょう":["japanese"],"げざい":["japanese"],"けさき":["japanese"],"げざん":["japanese"],"けしき":["japanese"],"けしごむ":["japanese"],"けしょう":["japanese"],"げすと":["japanese"],"けたば":["japanese"],"けちゃっぷ":["japanese"],"けちらす":["japanese"],"けつあつ":["japanese"],"けつい":["japanese"],"けつえき":["japanese"],"けっこん":["japanese"],"けつじょ":["japanese"],"けっせき":["japanese"],"けってい":["japanese"],"けつまつ":["japanese"],"げつようび":["japanese"],"げつれい":["japanese"],"けつろん":["japanese"],"げどく":["japanese"],"けとばす":["japanese"],"けとる":["japanese"],"けなげ":["japanese"],"けなす":["japanese"],"けなみ":["japanese"],"けぬき":["japanese"],"げねつ":["japanese"],"けねん":["japanese"],"けはい":["japanese"],"げひん":["japanese"],"けぶかい":["japanese"],"げぼく":["japanese"],"けまり":["japanese"],"けみかる":["japanese"],"けむし":["japanese"],"けむり":["japanese"],"けもの":["japanese"],"けらい":["japanese"],"けろけろ":["japanese"],"けわしい":["japanese"],"けんい":["japanese"],"けんえつ":["japanese"],"けんお":["japanese"],"けんか":["japanese"],"げんき":["japanese"],"けんげん":["japanese"],"けんこう":["japanese"],"けんさく":["japanese"],"けんしゅう":["japanese"],"けんすう":["japanese"],"げんそう":["japanese"],"けんちく":["japanese"],"けんてい":["japanese"],"けんとう":["japanese"],"けんない":["japanese"],"けんにん":["japanese"],"げんぶつ":["japanese"],"けんま":["japanese"],"けんみん":["japanese"],"けんめい":["japanese"],"けんらん":["japanese"],"けんり":["japanese"],"こあくま":["japanese"],"こいぬ":["japanese"],"こいびと":["japanese"],"ごうい":["japanese"],"こうえん":["japanese"],"こうおん":["japanese"],"こうかん":["japanese"],"ごうきゅう":["japanese"],"ごうけい":["japanese"],"こうこう":["japanese"],"こうさい":["japanese"],"こうじ":["japanese"],"こうすい":["japanese"],"ごうせい":["japanese"],"こうそく":["japanese"],"こうたい":["japanese"],"こうちゃ":["japanese"],"こうつう":["japanese"],"こうてい":["japanese"],"こうどう":["japanese"],"こうない":["japanese"],"こうはい":["japanese"],"ごうほう":["japanese"],"ごうまん":["japanese"],"こうもく":["japanese"],"こうりつ":["japanese"],"こえる":["japanese"],"こおり":["japanese"],"ごかい":["japanese"],"ごがつ":["japanese"],"ごかん":["japanese"],"こくご":["japanese"],"こくさい":["japanese"],"こくとう":["japanese"],"こくない":["japanese"],"こくはく":["japanese"],"こぐま":["japanese"],"こけい":["japanese"],"こける":["japanese"],"ここのか":["japanese"],"こころ":["japanese"],"こさめ":["japanese"],"こしつ":["japanese"],"こすう":["japanese"],"こせい":["japanese"],"こせき":["japanese"],"こぜん":["japanese"],"こそだて":["japanese"],"こたい":["japanese"],"こたえる":["japanese"],"こたつ":["japanese"],"こちょう":["japanese"],"こっか":["japanese"],"こつこつ":["japanese"],"こつばん":["japanese"],"こつぶ":["japanese"],"こてい":["japanese"],"こてん":["japanese"],"ことがら":["japanese"],"ことし":["japanese"],"ことば":["japanese"],"ことり":["japanese"],"こなごな":["japanese"],"こねこね":["japanese"],"このまま":["japanese"],"このみ":["japanese"],"このよ":["japanese"],"ごはん":["japanese"],"こひつじ":["japanese"],"こふう":["japanese"],"こふん":["japanese"],"こぼれる":["japanese"],"ごまあぶら":["japanese"],"こまかい":["japanese"],"ごますり":["japanese"],"こまつな":["japanese"],"こまる":["japanese"],"こむぎこ":["japanese"],"こもじ":["japanese"],"こもち":["japanese"],"こもの":["japanese"],"こもん":["japanese"],"こやく":["japanese"],"こやま":["japanese"],"こゆう":["japanese"],"こゆび":["japanese"],"こよい":["japanese"],"こよう":["japanese"],"こりる":["japanese"],"これくしょん":["japanese"],"ころっけ":["japanese"],"こわもて":["japanese"],"こわれる":["japanese"],"こんいん":["japanese"],"こんかい":["japanese"],"こんき":["japanese"],"こんしゅう":["japanese"],"こんすい":["japanese"],"こんだて":["japanese"],"こんとん":["japanese"],"こんなん":["japanese"],"こんびに":["japanese"],"こんぽん":["japanese"],"こんまけ":["japanese"],"こんや":["japanese"],"こんれい":["japanese"],"こんわく":["japanese"],"ざいえき":["japanese"],"さいかい":["japanese"],"さいきん":["japanese"],"ざいげん":["japanese"],"ざいこ":["japanese"],"さいしょ":["japanese"],"さいせい":["japanese"],"ざいたく":["japanese"],"ざいちゅう":["japanese"],"さいてき":["japanese"],"ざいりょう":["japanese"],"さうな":["japanese"],"さかいし":["japanese"],"さがす":["japanese"],"さかな":["japanese"],"さかみち":["japanese"],"さがる":["japanese"],"さぎょう":["japanese"],"さくし":["japanese"],"さくひん":["japanese"],"さくら":["japanese"],"さこく":["japanese"],"さこつ":["japanese"],"さずかる":["japanese"],"ざせき":["japanese"],"さたん":["japanese"],"さつえい":["japanese"],"ざつおん":["japanese"],"ざっか":["japanese"],"ざつがく":["japanese"],"さっきょく":["japanese"],"ざっし":["japanese"],"さつじん":["japanese"],"ざっそう":["japanese"],"さつたば":["japanese"],"さつまいも":["japanese"],"さてい":["japanese"],"さといも":["japanese"],"さとう":["japanese"],"さとおや":["japanese"],"さとし":["japanese"],"さとる":["japanese"],"さのう":["japanese"],"さばく":["japanese"],"さびしい":["japanese"],"さべつ":["japanese"],"さほう":["japanese"],"さほど":["japanese"],"さます":["japanese"],"さみしい":["japanese"],"さみだれ":["japanese"],"さむけ":["japanese"],"さめる":["japanese"],"さやえんどう":["japanese"],"さゆう":["japanese"],"さよう":["japanese"],"さよく":["japanese"],"さらだ":["japanese"],"ざるそば":["japanese"],"さわやか":["japanese"],"さわる":["japanese"],"さんいん":["japanese"],"さんか":["japanese"],"さんきゃく":["japanese"],"さんこう":["japanese"],"さんさい":["japanese"],"ざんしょ":["japanese"],"さんすう":["japanese"],"さんせい":["japanese"],"さんそ":["japanese"],"さんち":["japanese"],"さんま":["japanese"],"さんみ":["japanese"],"さんらん":["japanese"],"しあい":["japanese"],"しあげ":["japanese"],"しあさって":["japanese"],"しあわせ":["japanese"],"しいく":["japanese"],"しいん":["japanese"],"しうち":["japanese"],"しえい":["japanese"],"しおけ":["japanese"],"しかい":["japanese"],"しかく":["japanese"],"じかん":["japanese"],"しごと":["japanese"],"しすう":["japanese"],"じだい":["japanese"],"したうけ":["japanese"],"したぎ":["japanese"],"したて":["japanese"],"したみ":["japanese"],"しちょう":["japanese"],"しちりん":["japanese"],"しっかり":["japanese"],"しつじ":["japanese"],"しつもん":["japanese"],"してい":["japanese"],"してき":["japanese"],"してつ":["japanese"],"じてん":["japanese"],"じどう":["japanese"],"しなぎれ":["japanese"],"しなもの":["japanese"],"しなん":["japanese"],"しねま":["japanese"],"しねん":["japanese"],"しのぐ":["japanese"],"しのぶ":["japanese"],"しはい":["japanese"],"しばかり":["japanese"],"しはつ":["japanese"],"しはらい":["japanese"],"しはん":["japanese"],"しひょう":["japanese"],"しふく":["japanese"],"じぶん":["japanese"],"しへい":["japanese"],"しほう":["japanese"],"しほん":["japanese"],"しまう":["japanese"],"しまる":["japanese"],"しみん":["japanese"],"しむける":["japanese"],"じむしょ":["japanese"],"しめい":["japanese"],"しめる":["japanese"],"しもん":["japanese"],"しゃいん":["japanese"],"しゃうん":["japanese"],"しゃおん":["japanese"],"じゃがいも":["japanese"],"しやくしょ":["japanese"],"しゃくほう":["japanese"],"しゃけん":["japanese"],"しゃこ":["japanese"],"しゃざい":["japanese"],"しゃしん":["japanese"],"しゃせん":["japanese"],"しゃそう":["japanese"],"しゃたい":["japanese"],"しゃちょう":["japanese"],"しゃっきん":["japanese"],"じゃま":["japanese"],"しゃりん":["japanese"],"しゃれい":["japanese"],"じゆう":["japanese"],"じゅうしょ":["japanese"],"しゅくはく":["japanese"],"じゅしん":["japanese"],"しゅっせき":["japanese"],"しゅみ":["japanese"],"しゅらば":["japanese"],"じゅんばん":["japanese"],"しょうかい":["japanese"],"しょくたく":["japanese"],"しょっけん":["japanese"],"しょどう":["japanese"],"しょもつ":["japanese"],"しらせる":["japanese"],"しらべる":["japanese"],"しんか":["japanese"],"しんこう":["japanese"],"じんじゃ":["japanese"],"しんせいじ":["japanese"],"しんちく":["japanese"],"しんりん":["japanese"],"すあげ":["japanese"],"すあし":["japanese"],"すあな":["japanese"],"ずあん":["japanese"],"すいえい":["japanese"],"すいか":["japanese"],"すいとう":["japanese"],"ずいぶん":["japanese"],"すいようび":["japanese"],"すうがく":["japanese"],"すうじつ":["japanese"],"すうせん":["japanese"],"すおどり":["japanese"],"すきま":["japanese"],"すくう":["japanese"],"すくない":["japanese"],"すける":["japanese"],"すごい":["japanese"],"すこし":["japanese"],"ずさん":["japanese"],"すずしい":["japanese"],"すすむ":["japanese"],"すすめる":["japanese"],"すっかり":["japanese"],"ずっしり":["japanese"],"ずっと":["japanese"],"すてき":["japanese"],"すてる":["japanese"],"すねる":["japanese"],"すのこ":["japanese"],"すはだ":["japanese"],"すばらしい":["japanese"],"ずひょう":["japanese"],"ずぶぬれ":["japanese"],"すぶり":["japanese"],"すふれ":["japanese"],"すべて":["japanese"],"すべる":["japanese"],"ずほう":["japanese"],"すぼん":["japanese"],"すまい":["japanese"],"すめし":["japanese"],"すもう":["japanese"],"すやき":["japanese"],"すらすら":["japanese"],"するめ":["japanese"],"すれちがう":["japanese"],"すろっと":["japanese"],"すわる":["japanese"],"すんぜん":["japanese"],"すんぽう":["japanese"],"せあぶら":["japanese"],"せいかつ":["japanese"],"せいげん":["japanese"],"せいじ":["japanese"],"せいよう":["japanese"],"せおう":["japanese"],"せかいかん":["japanese"],"せきにん":["japanese"],"せきむ":["japanese"],"せきゆ":["japanese"],"せきらんうん":["japanese"],"せけん":["japanese"],"せこう":["japanese"],"せすじ":["japanese"],"せたい":["japanese"],"せたけ":["japanese"],"せっかく":["japanese"],"せっきゃく":["japanese"],"ぜっく":["japanese"],"せっけん":["japanese"],"せっこつ":["japanese"],"せっさたくま":["japanese"],"せつぞく":["japanese"],"せつだん":["japanese"],"せつでん":["japanese"],"せっぱん":["japanese"],"せつび":["japanese"],"せつぶん":["japanese"],"せつめい":["japanese"],"せつりつ":["japanese"],"せなか":["japanese"],"せのび":["japanese"],"せはば":["japanese"],"せびろ":["japanese"],"せぼね":["japanese"],"せまい":["japanese"],"せまる":["japanese"],"せめる":["japanese"],"せもたれ":["japanese"],"せりふ":["japanese"],"ぜんあく":["japanese"],"せんい":["japanese"],"せんえい":["japanese"],"せんか":["japanese"],"せんきょ":["japanese"],"せんく":["japanese"],"せんげん":["japanese"],"ぜんご":["japanese"],"せんさい":["japanese"],"せんしゅ":["japanese"],"せんすい":["japanese"],"せんせい":["japanese"],"せんぞ":["japanese"],"せんたく":["japanese"],"せんちょう":["japanese"],"せんてい":["japanese"],"せんとう":["japanese"],"せんぬき":["japanese"],"せんねん":["japanese"],"せんぱい":["japanese"],"ぜんぶ":["japanese"],"ぜんぽう":["japanese"],"せんむ":["japanese"],"せんめんじょ":["japanese"],"せんもん":["japanese"],"せんやく":["japanese"],"せんゆう":["japanese"],"せんよう":["japanese"],"ぜんら":["japanese"],"ぜんりゃく":["japanese"],"せんれい":["japanese"],"せんろ":["japanese"],"そあく":["japanese"],"そいとげる":["japanese"],"そいね":["japanese"],"そうがんきょう":["japanese"],"そうき":["japanese"],"そうご":["japanese"],"そうしん":["japanese"],"そうだん":["japanese"],"そうなん":["japanese"],"そうび":["japanese"],"そうめん":["japanese"],"そうり":["japanese"],"そえもの":["japanese"],"そえん":["japanese"],"そがい":["japanese"],"そげき":["japanese"],"そこう":["japanese"],"そこそこ":["japanese"],"そざい":["japanese"],"そしな":["japanese"],"そせい":["japanese"],"そせん":["japanese"],"そそぐ":["japanese"],"そだてる":["japanese"],"そつう":["japanese"],"そつえん":["japanese"],"そっかん":["japanese"],"そつぎょう":["japanese"],"そっけつ":["japanese"],"そっこう":["japanese"],"そっせん":["japanese"],"そっと":["japanese"],"そとがわ":["japanese"],"そとづら":["japanese"],"そなえる":["japanese"],"そなた":["japanese"],"そふぼ":["japanese"],"そぼく":["japanese"],"そぼろ":["japanese"],"そまつ":["japanese"],"そまる":["japanese"],"そむく":["japanese"],"そむりえ":["japanese"],"そめる":["japanese"],"そもそも":["japanese"],"そよかぜ":["japanese"],"そらまめ":["japanese"],"そろう":["japanese"],"そんかい":["japanese"],"そんけい":["japanese"],"そんざい":["japanese"],"そんしつ":["japanese"],"そんぞく":["japanese"],"そんちょう":["japanese"],"ぞんび":["japanese"],"ぞんぶん":["japanese"],"そんみん":["japanese"],"たあい":["japanese"],"たいいん":["japanese"],"たいうん":["japanese"],"たいえき":["japanese"],"たいおう":["japanese"],"だいがく":["japanese"],"たいき":["japanese"],"たいぐう":["japanese"],"たいけん":["japanese"],"たいこ":["japanese"],"たいざい":["japanese"],"だいじょうぶ":["japanese"],"だいすき":["japanese"],"たいせつ":["japanese"],"たいそう":["japanese"],"だいたい":["japanese"],"たいちょう":["japanese"],"たいてい":["japanese"],"だいどころ":["japanese"],"たいない":["japanese"],"たいねつ":["japanese"],"たいのう":["japanese"],"たいはん":["japanese"],"だいひょう":["japanese"],"たいふう":["japanese"],"たいへん":["japanese"],"たいほ":["japanese"],"たいまつばな":["japanese"],"たいみんぐ":["japanese"],"たいむ":["japanese"],"たいめん":["japanese"],"たいやき":["japanese"],"たいよう":["japanese"],"たいら":["japanese"],"たいりょく":["japanese"],"たいる":["japanese"],"たいわん":["japanese"],"たうえ":["japanese"],"たえる":["japanese"],"たおす":["japanese"],"たおる":["japanese"],"たおれる":["japanese"],"たかい":["japanese"],"たかね":["japanese"],"たきび":["japanese"],"たくさん":["japanese"],"たこく":["japanese"],"たこやき":["japanese"],"たさい":["japanese"],"たしざん":["japanese"],"だじゃれ":["japanese"],"たすける":["japanese"],"たずさわる":["japanese"],"たそがれ":["japanese"],"たたかう":["japanese"],"たたく":["japanese"],"ただしい":["japanese"],"たたみ":["japanese"],"たちばな":["japanese"],"だっかい":["japanese"],"だっきゃく":["japanese"],"だっこ":["japanese"],"だっしゅつ":["japanese"],"だったい":["japanese"],"たてる":["japanese"],"たとえる":["japanese"],"たなばた":["japanese"],"たにん":["japanese"],"たぬき":["japanese"],"たのしみ":["japanese"],"たはつ":["japanese"],"たぶん":["japanese"],"たべる":["japanese"],"たぼう":["japanese"],"たまご":["japanese"],"たまる":["japanese"],"だむる":["japanese"],"ためいき":["japanese"],"ためす":["japanese"],"ためる":["japanese"],"たもつ":["japanese"],"たやすい":["japanese"],"たよる":["japanese"],"たらす":["japanese"],"たりきほんがん":["japanese"],"たりょう":["japanese"],"たりる":["japanese"],"たると":["japanese"],"たれる":["japanese"],"たれんと":["japanese"],"たろっと":["japanese"],"たわむれる":["japanese"],"だんあつ":["japanese"],"たんい":["japanese"],"たんおん":["japanese"],"たんか":["japanese"],"たんき":["japanese"],"たんけん":["japanese"],"たんご":["japanese"],"たんさん":["japanese"],"たんじょうび":["japanese"],"だんせい":["japanese"],"たんそく":["japanese"],"たんたい":["japanese"],"だんち":["japanese"],"たんてい":["japanese"],"たんとう":["japanese"],"だんな":["japanese"],"たんにん":["japanese"],"だんねつ":["japanese"],"たんのう":["japanese"],"たんぴん":["japanese"],"だんぼう":["japanese"],"たんまつ":["japanese"],"たんめい":["japanese"],"だんれつ":["japanese"],"だんろ":["japanese"],"だんわ":["japanese"],"ちあい":["japanese"],"ちあん":["japanese"],"ちいき":["japanese"],"ちいさい":["japanese"],"ちえん":["japanese"],"ちかい":["japanese"],"ちから":["japanese"],"ちきゅう":["japanese"],"ちきん":["japanese"],"ちけいず":["japanese"],"ちけん":["japanese"],"ちこく":["japanese"],"ちさい":["japanese"],"ちしき":["japanese"],"ちしりょう":["japanese"],"ちせい":["japanese"],"ちそう":["japanese"],"ちたい":["japanese"],"ちたん":["japanese"],"ちちおや":["japanese"],"ちつじょ":["japanese"],"ちてき":["japanese"],"ちてん":["japanese"],"ちぬき":["japanese"],"ちぬり":["japanese"],"ちのう":["japanese"],"ちひょう":["japanese"],"ちへいせん":["japanese"],"ちほう":["japanese"],"ちまた":["japanese"],"ちみつ":["japanese"],"ちみどろ":["japanese"],"ちめいど":["japanese"],"ちゃんこなべ":["japanese"],"ちゅうい":["japanese"],"ちゆりょく":["japanese"],"ちょうし":["japanese"],"ちょさくけん":["japanese"],"ちらし":["japanese"],"ちらみ":["japanese"],"ちりがみ":["japanese"],"ちりょう":["japanese"],"ちるど":["japanese"],"ちわわ":["japanese"],"ちんたい":["japanese"],"ちんもく":["japanese"],"ついか":["japanese"],"ついたち":["japanese"],"つうか":["japanese"],"つうじょう":["japanese"],"つうはん":["japanese"],"つうわ":["japanese"],"つかう":["japanese"],"つかれる":["japanese"],"つくね":["japanese"],"つくる":["japanese"],"つけね":["japanese"],"つける":["japanese"],"つごう":["japanese"],"つたえる":["japanese"],"つづく":["japanese"],"つつじ":["japanese"],"つつむ":["japanese"],"つとめる":["japanese"],"つながる":["japanese"],"つなみ":["japanese"],"つねづね":["japanese"],"つのる":["japanese"],"つぶす":["japanese"],"つまらない":["japanese"],"つまる":["japanese"],"つみき":["japanese"],"つめたい":["japanese"],"つもり":["japanese"],"つもる":["japanese"],"つよい":["japanese"],"つるぼ":["japanese"],"つるみく":["japanese"],"つわもの":["japanese"],"つわり":["japanese"],"てあし":["japanese"],"てあて":["japanese"],"てあみ":["japanese"],"ていおん":["japanese"],"ていか":["japanese"],"ていき":["japanese"],"ていけい":["japanese"],"ていこく":["japanese"],"ていさつ":["japanese"],"ていし":["japanese"],"ていせい":["japanese"],"ていたい":["japanese"],"ていど":["japanese"],"ていねい":["japanese"],"ていひょう":["japanese"],"ていへん":["japanese"],"ていぼう":["japanese"],"てうち":["japanese"],"ておくれ":["japanese"],"てきとう":["japanese"],"てくび":["japanese"],"でこぼこ":["japanese"],"てさぎょう":["japanese"],"てさげ":["japanese"],"てすり":["japanese"],"てそう":["japanese"],"てちがい":["japanese"],"てちょう":["japanese"],"てつがく":["japanese"],"てつづき":["japanese"],"でっぱ":["japanese"],"てつぼう":["japanese"],"てつや":["japanese"],"でぬかえ":["japanese"],"てぬき":["japanese"],"てぬぐい":["japanese"],"てのひら":["japanese"],"てはい":["japanese"],"てぶくろ":["japanese"],"てふだ":["japanese"],"てほどき":["japanese"],"てほん":["japanese"],"てまえ":["japanese"],"てまきずし":["japanese"],"てみじか":["japanese"],"てみやげ":["japanese"],"てらす":["japanese"],"てれび":["japanese"],"てわけ":["japanese"],"てわたし":["japanese"],"でんあつ":["japanese"],"てんいん":["japanese"],"てんかい":["japanese"],"てんき":["japanese"],"てんぐ":["japanese"],"てんけん":["japanese"],"てんごく":["japanese"],"てんさい":["japanese"],"てんし":["japanese"],"てんすう":["japanese"],"でんち":["japanese"],"てんてき":["japanese"],"てんとう":["japanese"],"てんない":["japanese"],"てんぷら":["japanese"],"てんぼうだい":["japanese"],"てんめつ":["japanese"],"てんらんかい":["japanese"],"でんりょく":["japanese"],"でんわ":["japanese"],"どあい":["japanese"],"といれ":["japanese"],"どうかん":["japanese"],"とうきゅう":["japanese"],"どうぐ":["japanese"],"とうし":["japanese"],"とうむぎ":["japanese"],"とおい":["japanese"],"とおか":["japanese"],"とおく":["japanese"],"とおす":["japanese"],"とおる":["japanese"],"とかい":["japanese"],"とかす":["japanese"],"ときおり":["japanese"],"ときどき":["japanese"],"とくい":["japanese"],"とくしゅう":["japanese"],"とくてん":["japanese"],"とくに":["japanese"],"とくべつ":["japanese"],"とけい":["japanese"],"とける":["japanese"],"とこや":["japanese"],"とさか":["japanese"],"としょかん":["japanese"],"とそう":["japanese"],"とたん":["japanese"],"とちゅう":["japanese"],"とっきゅう":["japanese"],"とっくん":["japanese"],"とつぜん":["japanese"],"とつにゅう":["japanese"],"とどける":["japanese"],"ととのえる":["japanese"],"とない":["japanese"],"となえる":["japanese"],"となり":["japanese"],"とのさま":["japanese"],"とばす":["japanese"],"どぶがわ":["japanese"],"とほう":["japanese"],"とまる":["japanese"],"とめる":["japanese"],"ともだち":["japanese"],"ともる":["japanese"],"どようび":["japanese"],"とらえる":["japanese"],"とんかつ":["japanese"],"どんぶり":["japanese"],"ないかく":["japanese"],"ないこう":["japanese"],"ないしょ":["japanese"],"ないす":["japanese"],"ないせん":["japanese"],"ないそう":["japanese"],"なおす":["japanese"],"ながい":["japanese"],"なくす":["japanese"],"なげる":["japanese"],"なこうど":["japanese"],"なさけ":["japanese"],"なたでここ":["japanese"],"なっとう":["japanese"],"なつやすみ":["japanese"],"ななおし":["japanese"],"なにごと":["japanese"],"なにもの":["japanese"],"なにわ":["japanese"],"なのか":["japanese"],"なふだ":["japanese"],"なまいき":["japanese"],"なまえ":["japanese"],"なまみ":["japanese"],"なみだ":["japanese"],"なめらか":["japanese"],"なめる":["japanese"],"なやむ":["japanese"],"ならう":["japanese"],"ならび":["japanese"],"ならぶ":["japanese"],"なれる":["japanese"],"なわとび":["japanese"],"なわばり":["japanese"],"にあう":["japanese"],"にいがた":["japanese"],"にうけ":["japanese"],"におい":["japanese"],"にかい":["japanese"],"にがて":["japanese"],"にきび":["japanese"],"にくしみ":["japanese"],"にくまん":["japanese"],"にげる":["japanese"],"にさんかたんそ":["japanese"],"にしき":["japanese"],"にせもの":["japanese"],"にちじょう":["japanese"],"にちようび":["japanese"],"にっか":["japanese"],"にっき":["japanese"],"にっけい":["japanese"],"にっこう":["japanese"],"にっさん":["japanese"],"にっしょく":["japanese"],"にっすう":["japanese"],"にっせき":["japanese"],"にってい":["japanese"],"になう":["japanese"],"にほん":["japanese"],"にまめ":["japanese"],"にもつ":["japanese"],"にやり":["japanese"],"にゅういん":["japanese"],"にりんしゃ":["japanese"],"にわとり":["japanese"],"にんい":["japanese"],"にんか":["japanese"],"にんき":["japanese"],"にんげん":["japanese"],"にんしき":["japanese"],"にんずう":["japanese"],"にんそう":["japanese"],"にんたい":["japanese"],"にんち":["japanese"],"にんてい":["japanese"],"にんにく":["japanese"],"にんぷ":["japanese"],"にんまり":["japanese"],"にんむ":["japanese"],"にんめい":["japanese"],"にんよう":["japanese"],"ぬいくぎ":["japanese"],"ぬかす":["japanese"],"ぬぐいとる":["japanese"],"ぬぐう":["japanese"],"ぬくもり":["japanese"],"ぬすむ":["japanese"],"ぬまえび":["japanese"],"ぬめり":["japanese"],"ぬらす":["japanese"],"ぬんちゃく":["japanese"],"ねあげ":["japanese"],"ねいき":["japanese"],"ねいる":["japanese"],"ねいろ":["japanese"],"ねぐせ":["japanese"],"ねくたい":["japanese"],"ねくら":["japanese"],"ねこぜ":["japanese"],"ねこむ":["japanese"],"ねさげ":["japanese"],"ねすごす":["japanese"],"ねそべる":["japanese"],"ねだん":["japanese"],"ねつい":["japanese"],"ねっしん":["japanese"],"ねつぞう":["japanese"],"ねったいぎょ":["japanese"],"ねぶそく":["japanese"],"ねふだ":["japanese"],"ねぼう":["japanese"],"ねほりはほり":["japanese"],"ねまき":["japanese"],"ねまわし":["japanese"],"ねみみ":["japanese"],"ねむい":["japanese"],"ねむたい":["japanese"],"ねもと":["japanese"],"ねらう":["japanese"],"ねわざ":["japanese"],"ねんいり":["japanese"],"ねんおし":["japanese"],"ねんかん":["japanese"],"ねんきん":["japanese"],"ねんぐ":["japanese"],"ねんざ":["japanese"],"ねんし":["japanese"],"ねんちゃく":["japanese"],"ねんど":["japanese"],"ねんぴ":["japanese"],"ねんぶつ":["japanese"],"ねんまつ":["japanese"],"ねんりょう":["japanese"],"ねんれい":["japanese"],"のいず":["japanese"],"のおづま":["japanese"],"のがす":["japanese"],"のきなみ":["japanese"],"のこぎり":["japanese"],"のこす":["japanese"],"のこる":["japanese"],"のせる":["japanese"],"のぞく":["japanese"],"のぞむ":["japanese"],"のたまう":["japanese"],"のちほど":["japanese"],"のっく":["japanese"],"のばす":["japanese"],"のはら":["japanese"],"のべる":["japanese"],"のぼる":["japanese"],"のみもの":["japanese"],"のやま":["japanese"],"のらいぬ":["japanese"],"のらねこ":["japanese"],"のりもの":["japanese"],"のりゆき":["japanese"],"のれん":["japanese"],"のんき":["japanese"],"ばあい":["japanese"],"はあく":["japanese"],"ばあさん":["japanese"],"ばいか":["japanese"],"ばいく":["japanese"],"はいけん":["japanese"],"はいご":["japanese"],"はいしん":["japanese"],"はいすい":["japanese"],"はいせん":["japanese"],"はいそう":["japanese"],"はいち":["japanese"],"ばいばい":["japanese"],"はいれつ":["japanese"],"はえる":["japanese"],"はおる":["japanese"],"はかい":["japanese"],"ばかり":["japanese"],"はかる":["japanese"],"はくしゅ":["japanese"],"はけん":["japanese"],"はこぶ":["japanese"],"はさみ":["japanese"],"はさん":["japanese"],"はしご":["japanese"],"ばしょ":["japanese"],"はしる":["japanese"],"はせる":["japanese"],"ぱそこん":["japanese"],"はそん":["japanese"],"はたん":["japanese"],"はちみつ":["japanese"],"はつおん":["japanese"],"はっかく":["japanese"],"はづき":["japanese"],"はっきり":["japanese"],"はっくつ":["japanese"],"はっけん":["japanese"],"はっこう":["japanese"],"はっさん":["japanese"],"はっしん":["japanese"],"はったつ":["japanese"],"はっちゅう":["japanese"],"はってん":["japanese"],"はっぴょう":["japanese"],"はっぽう":["japanese"],"はなす":["japanese"],"はなび":["japanese"],"はにかむ":["japanese"],"はぶらし":["japanese"],"はみがき":["japanese"],"はむかう":["japanese"],"はめつ":["japanese"],"はやい":["japanese"],"はやし":["japanese"],"はらう":["japanese"],"はろうぃん":["japanese"],"はわい":["japanese"],"はんい":["japanese"],"はんえい":["japanese"],"はんおん":["japanese"],"はんかく":["japanese"],"はんきょう":["japanese"],"ばんぐみ":["japanese"],"はんこ":["japanese"],"はんしゃ":["japanese"],"はんすう":["japanese"],"はんだん":["japanese"],"ぱんち":["japanese"],"ぱんつ":["japanese"],"はんてい":["japanese"],"はんとし":["japanese"],"はんのう":["japanese"],"はんぱ":["japanese"],"はんぶん":["japanese"],"はんぺん":["japanese"],"はんぼうき":["japanese"],"はんめい":["japanese"],"はんらん":["japanese"],"はんろん":["japanese"],"ひいき":["japanese"],"ひうん":["japanese"],"ひえる":["japanese"],"ひかく":["japanese"],"ひかり":["japanese"],"ひかる":["japanese"],"ひかん":["japanese"],"ひくい":["japanese"],"ひけつ":["japanese"],"ひこうき":["japanese"],"ひこく":["japanese"],"ひさい":["japanese"],"ひさしぶり":["japanese"],"ひさん":["japanese"],"びじゅつかん":["japanese"],"ひしょ":["japanese"],"ひそか":["japanese"],"ひそむ":["japanese"],"ひたむき":["japanese"],"ひだり":["japanese"],"ひたる":["japanese"],"ひつぎ":["japanese"],"ひっこし":["japanese"],"ひっし":["japanese"],"ひつじゅひん":["japanese"],"ひっす":["japanese"],"ひつぜん":["japanese"],"ぴったり":["japanese"],"ぴっちり":["japanese"],"ひつよう":["japanese"],"ひてい":["japanese"],"ひとごみ":["japanese"],"ひなまつり":["japanese"],"ひなん":["japanese"],"ひねる":["japanese"],"ひはん":["japanese"],"ひびく":["japanese"],"ひひょう":["japanese"],"ひほう":["japanese"],"ひまわり":["japanese"],"ひまん":["japanese"],"ひみつ":["japanese"],"ひめい":["japanese"],"ひめじし":["japanese"],"ひやけ":["japanese"],"ひやす":["japanese"],"ひよう":["japanese"],"びょうき":["japanese"],"ひらがな":["japanese"],"ひらく":["japanese"],"ひりつ":["japanese"],"ひりょう":["japanese"],"ひるま":["japanese"],"ひるやすみ":["japanese"],"ひれい":["japanese"],"ひろい":["japanese"],"ひろう":["japanese"],"ひろき":["japanese"],"ひろゆき":["japanese"],"ひんかく":["japanese"],"ひんけつ":["japanese"],"ひんこん":["japanese"],"ひんしゅ":["japanese"],"ひんそう":["japanese"],"ぴんち":["japanese"],"ひんぱん":["japanese"],"びんぼう":["japanese"],"ふあん":["japanese"],"ふいうち":["japanese"],"ふうけい":["japanese"],"ふうせん":["japanese"],"ぷうたろう":["japanese"],"ふうとう":["japanese"],"ふうふ":["japanese"],"ふえる":["japanese"],"ふおん":["japanese"],"ふかい":["japanese"],"ふきん":["japanese"],"ふくざつ":["japanese"],"ふくぶくろ":["japanese"],"ふこう":["japanese"],"ふさい":["japanese"],"ふしぎ":["japanese"],"ふじみ":["japanese"],"ふすま":["japanese"],"ふせい":["japanese"],"ふせぐ":["japanese"],"ふそく":["japanese"],"ぶたにく":["japanese"],"ふたん":["japanese"],"ふちょう":["japanese"],"ふつう":["japanese"],"ふつか":["japanese"],"ふっかつ":["japanese"],"ふっき":["japanese"],"ふっこく":["japanese"],"ぶどう":["japanese"],"ふとる":["japanese"],"ふとん":["japanese"],"ふのう":["japanese"],"ふはい":["japanese"],"ふひょう":["japanese"],"ふへん":["japanese"],"ふまん":["japanese"],"ふみん":["japanese"],"ふめつ":["japanese"],"ふめん":["japanese"],"ふよう":["japanese"],"ふりこ":["japanese"],"ふりる":["japanese"],"ふるい":["japanese"],"ふんいき":["japanese"],"ぶんがく":["japanese"],"ぶんぐ":["japanese"],"ふんしつ":["japanese"],"ぶんせき":["japanese"],"ふんそう":["japanese"],"ぶんぽう":["japanese"],"へいあん":["japanese"],"へいおん":["japanese"],"へいがい":["japanese"],"へいき":["japanese"],"へいげん":["japanese"],"へいこう":["japanese"],"へいさ":["japanese"],"へいしゃ":["japanese"],"へいせつ":["japanese"],"へいそ":["japanese"],"へいたく":["japanese"],"へいてん":["japanese"],"へいねつ":["japanese"],"へいわ":["japanese"],"へきが":["japanese"],"へこむ":["japanese"],"べにいろ":["japanese"],"べにしょうが":["japanese"],"へらす":["japanese"],"へんかん":["japanese"],"べんきょう":["japanese"],"べんごし":["japanese"],"へんさい":["japanese"],"へんたい":["japanese"],"べんり":["japanese"],"ほあん":["japanese"],"ほいく":["japanese"],"ぼうぎょ":["japanese"],"ほうこく":["japanese"],"ほうそう":["japanese"],"ほうほう":["japanese"],"ほうもん":["japanese"],"ほうりつ":["japanese"],"ほえる":["japanese"],"ほおん":["japanese"],"ほかん":["japanese"],"ほきょう":["japanese"],"ぼきん":["japanese"],"ほくろ":["japanese"],"ほけつ":["japanese"],"ほけん":["japanese"],"ほこう":["japanese"],"ほこる":["japanese"],"ほしい":["japanese"],"ほしつ":["japanese"],"ほしゅ":["japanese"],"ほしょう":["japanese"],"ほせい":["japanese"],"ほそい":["japanese"],"ほそく":["japanese"],"ほたて":["japanese"],"ほたる":["japanese"],"ぽちぶくろ":["japanese"],"ほっきょく":["japanese"],"ほっさ":["japanese"],"ほったん":["japanese"],"ほとんど":["japanese"],"ほめる":["japanese"],"ほんい":["japanese"],"ほんき":["japanese"],"ほんけ":["japanese"],"ほんしつ":["japanese"],"ほんやく":["japanese"],"まいにち":["japanese"],"まかい":["japanese"],"まかせる":["japanese"],"まがる":["japanese"],"まける":["japanese"],"まこと":["japanese"],"まさつ":["japanese"],"まじめ":["japanese"],"ますく":["japanese"],"まぜる":["japanese"],"まつり":["japanese"],"まとめ":["japanese"],"まなぶ":["japanese"],"まぬけ":["japanese"],"まねく":["japanese"],"まほう":["japanese"],"まもる":["japanese"],"まゆげ":["japanese"],"まよう":["japanese"],"まろやか":["japanese"],"まわす":["japanese"],"まわり":["japanese"],"まわる":["japanese"],"まんが":["japanese"],"まんきつ":["japanese"],"まんぞく":["japanese"],"まんなか":["japanese"],"みいら":["japanese"],"みうち":["japanese"],"みえる":["japanese"],"みがく":["japanese"],"みかた":["japanese"],"みかん":["japanese"],"みけん":["japanese"],"みこん":["japanese"],"みじかい":["japanese"],"みすい":["japanese"],"みすえる":["japanese"],"みせる":["japanese"],"みっか":["japanese"],"みつかる":["japanese"],"みつける":["japanese"],"みてい":["japanese"],"みとめる":["japanese"],"みなと":["japanese"],"みなみかさい":["japanese"],"みねらる":["japanese"],"みのう":["japanese"],"みのがす":["japanese"],"みほん":["japanese"],"みもと":["japanese"],"みやげ":["japanese"],"みらい":["japanese"],"みりょく":["japanese"],"みわく":["japanese"],"みんか":["japanese"],"みんぞく":["japanese"],"むいか":["japanese"],"むえき":["japanese"],"むえん":["japanese"],"むかい":["japanese"],"むかう":["japanese"],"むかえ":["japanese"],"むかし":["japanese"],"むぎちゃ":["japanese"],"むける":["japanese"],"むげん":["japanese"],"むさぼる":["japanese"],"むしあつい":["japanese"],"むしば":["japanese"],"むじゅん":["japanese"],"むしろ":["japanese"],"むすう":["japanese"],"むすこ":["japanese"],"むすぶ":["japanese"],"むすめ":["japanese"],"むせる":["japanese"],"むせん":["japanese"],"むちゅう":["japanese"],"むなしい":["japanese"],"むのう":["japanese"],"むやみ":["japanese"],"むよう":["japanese"],"むらさき":["japanese"],"むりょう":["japanese"],"むろん":["japanese"],"めいあん":["japanese"],"めいうん":["japanese"],"めいえん":["japanese"],"めいかく":["japanese"],"めいきょく":["japanese"],"めいさい":["japanese"],"めいし":["japanese"],"めいそう":["japanese"],"めいぶつ":["japanese"],"めいれい":["japanese"],"めいわく":["japanese"],"めぐまれる":["japanese"],"めざす":["japanese"],"めした":["japanese"],"めずらしい":["japanese"],"めだつ":["japanese"],"めまい":["japanese"],"めやす":["japanese"],"めんきょ":["japanese"],"めんせき":["japanese"],"めんどう":["japanese"],"もうしあげる":["japanese"],"もうどうけん":["japanese"],"もえる":["japanese"],"もくし":["japanese"],"もくてき":["japanese"],"もくようび":["japanese"],"もちろん":["japanese"],"もどる":["japanese"],"もらう":["japanese"],"もんく":["japanese"],"もんだい":["japanese"],"やおや":["japanese"],"やける":["japanese"],"やさい":["japanese"],"やさしい":["japanese"],"やすい":["japanese"],"やすたろう":["japanese"],"やすみ":["japanese"],"やせる":["japanese"],"やそう":["japanese"],"やたい":["japanese"],"やちん":["japanese"],"やっと":["japanese"],"やっぱり":["japanese"],"やぶる":["japanese"],"やめる":["japanese"],"ややこしい":["japanese"],"やよい":["japanese"],"やわらかい":["japanese"],"ゆうき":["japanese"],"ゆうびんきょく":["japanese"],"ゆうべ":["japanese"],"ゆうめい":["japanese"],"ゆけつ":["japanese"],"ゆしゅつ":["japanese"],"ゆせん":["japanese"],"ゆそう":["japanese"],"ゆたか":["japanese"],"ゆちゃく":["japanese"],"ゆでる":["japanese"],"ゆにゅう":["japanese"],"ゆびわ":["japanese"],"ゆらい":["japanese"],"ゆれる":["japanese"],"ようい":["japanese"],"ようか":["japanese"],"ようきゅう":["japanese"],"ようじ":["japanese"],"ようす":["japanese"],"ようちえん":["japanese"],"よかぜ":["japanese"],"よかん":["japanese"],"よきん":["japanese"],"よくせい":["japanese"],"よくぼう":["japanese"],"よけい":["japanese"],"よごれる":["japanese"],"よさん":["japanese"],"よしゅう":["japanese"],"よそう":["japanese"],"よそく":["japanese"],"よっか":["japanese"],"よてい":["japanese"],"よどがわく":["japanese"],"よねつ":["japanese"],"よやく":["japanese"],"よゆう":["japanese"],"よろこぶ":["japanese"],"よろしい":["japanese"],"らいう":["japanese"],"らくがき":["japanese"],"らくご":["japanese"],"らくさつ":["japanese"],"らくだ":["japanese"],"らしんばん":["japanese"],"らせん":["japanese"],"らぞく":["japanese"],"らたい":["japanese"],"らっか":["japanese"],"られつ":["japanese"],"りえき":["japanese"],"りかい":["japanese"],"りきさく":["japanese"],"りきせつ":["japanese"],"りくぐん":["japanese"],"りくつ":["japanese"],"りけん":["japanese"],"りこう":["japanese"],"りせい":["japanese"],"りそう":["japanese"],"りそく":["japanese"],"りてん":["japanese"],"りねん":["japanese"],"りゆう":["japanese"],"りゅうがく":["japanese"],"りよう":["japanese"],"りょうり":["japanese"],"りょかん":["japanese"],"りょくちゃ":["japanese"],"りょこう":["japanese"],"りりく":["japanese"],"りれき":["japanese"],"りろん":["japanese"],"りんご":["japanese"],"るいけい":["japanese"],"るいさい":["japanese"],"るいじ":["japanese"],"るいせき":["japanese"],"るすばん":["japanese"],"るりがわら":["japanese"],"れいかん":["japanese"],"れいぎ":["japanese"],"れいせい":["japanese"],"れいぞうこ":["japanese"],"れいとう":["japanese"],"れいぼう":["japanese"],"れきし":["japanese"],"れきだい":["japanese"],"れんあい":["japanese"],"れんけい":["japanese"],"れんこん":["japanese"],"れんさい":["japanese"],"れんしゅう":["japanese"],"れんぞく":["japanese"],"れんらく":["japanese"],"ろうか":["japanese"],"ろうご":["japanese"],"ろうじん":["japanese"],"ろうそく":["japanese"],"ろくが":["japanese"],"ろこつ":["japanese"],"ろじうら":["japanese"],"ろしゅつ":["japanese"],"ろせん":["japanese"],"ろてん":["japanese"],"ろめん":["japanese"],"ろれつ":["japanese"],"ろんぎ":["japanese"],"ろんぱ":["japanese"],"ろんぶん":["japanese"],"ろんり":["japanese"],"わかす":["japanese"],"わかめ":["japanese"],"わかやま":["japanese"],"わかれる":["japanese"],"わしつ":["japanese"],"わじまし":["japanese"],"わすれもの":["japanese"],"わらう":["japanese"],"われる":["japanese"],"가격":["korean"],"가끔":["korean"],"가난":["korean"],"가능":["korean"],"가득":["korean"],"가르침":["korean"],"가뭄":["korean"],"가방":["korean"],"가상":["korean"],"가슴":["korean"],"가운데":["korean"],"가을":["korean"],"가이드":["korean"],"가입":["korean"],"가장":["korean"],"가정":["korean"],"가족":["korean"],"가죽":["korean"],"각오":["korean"],"각자":["korean"],"간격":["korean"],"간부":["korean"],"간섭":["korean"],"간장":["korean"],"간접":["korean"],"간판":["korean"],"갈등":["korean"],"갈비":["korean"],"갈색":["korean"],"갈증":["korean"],"감각":["korean"],"감기":["korean"],"감소":["korean"],"감수성":["korean"],"감자":["korean"],"감정":["korean"],"갑자기":["korean"],"강남":["korean"],"강당":["korean"],"강도":["korean"],"강력히":["korean"],"강변":["korean"],"강북":["korean"],"강사":["korean"],"강수량":["korean"],"강아지":["korean"],"강원도":["korean"],"강의":["korean"],"강제":["korean"],"강조":["korean"],"같이":["korean"],"개구리":["korean"],"개나리":["korean"],"개방":["korean"],"개별":["korean"],"개선":["korean"],"개성":["korean"],"개인":["korean"],"객관적":["korean"],"거실":["korean"],"거액":["korean"],"거울":["korean"],"거짓":["korean"],"거품":["korean"],"걱정":["korean"],"건강":["korean"],"건물":["korean"],"건설":["korean"],"건조":["korean"],"건축":["korean"],"걸음":["korean"],"검사":["korean"],"검토":["korean"],"게시판":["korean"],"게임":["korean"],"겨울":["korean"],"견해":["korean"],"결과":["korean"],"결국":["korean"],"결론":["korean"],"결석":["korean"],"결승":["korean"],"결심":["korean"],"결정":["korean"],"결혼":["korean"],"경계":["korean"],"경고":["korean"],"경기":["korean"],"경력":["korean"],"경복궁":["korean"],"경비":["korean"],"경상도":["korean"],"경영":["korean"],"경우":["korean"],"경쟁":["korean"],"경제":["korean"],"경주":["korean"],"경찰":["korean"],"경치":["korean"],"경향":["korean"],"경험":["korean"],"계곡":["korean"],"계단":["korean"],"계란":["korean"],"계산":["korean"],"계속":["korean"],"계약":["korean"],"계절":["korean"],"계층":["korean"],"계획":["korean"],"고객":["korean"],"고구려":["korean"],"고궁":["korean"],"고급":["korean"],"고등학생":["korean"],"고무신":["korean"],"고민":["korean"],"고양이":["korean"],"고장":["korean"],"고전":["korean"],"고집":["korean"],"고춧가루":["korean"],"고통":["korean"],"고향":["korean"],"곡식":["korean"],"골목":["korean"],"골짜기":["korean"],"골프":["korean"],"공간":["korean"],"공개":["korean"],"공격":["korean"],"공군":["korean"],"공급":["korean"],"공기":["korean"],"공동":["korean"],"공무원":["korean"],"공부":["korean"],"공사":["korean"],"공식":["korean"],"공업":["korean"],"공연":["korean"],"공원":["korean"],"공장":["korean"],"공짜":["korean"],"공책":["korean"],"공통":["korean"],"공포":["korean"],"공항":["korean"],"공휴일":["korean"],"과목":["korean"],"과일":["korean"],"과장":["korean"],"과정":["korean"],"과학":["korean"],"관객":["korean"],"관계":["korean"],"관광":["korean"],"관념":["korean"],"관람":["korean"],"관련":["korean"],"관리":["korean"],"관습":["korean"],"관심":["korean"],"관점":["korean"],"관찰":["korean"],"광경":["korean"],"광고":["korean"],"광장":["korean"],"광주":["korean"],"괴로움":["korean"],"굉장히":["korean"],"교과서":["korean"],"교문":["korean"],"교복":["korean"],"교실":["korean"],"교양":["korean"],"교육":["korean"],"교장":["korean"],"교직":["korean"],"교통":["korean"],"교환":["korean"],"교훈":["korean"],"구경":["korean"],"구름":["korean"],"구멍":["korean"],"구별":["korean"],"구분":["korean"],"구석":["korean"],"구성":["korean"],"구속":["korean"],"구역":["korean"],"구입":["korean"],"구청":["korean"],"구체적":["korean"],"국가":["korean"],"국기":["korean"],"국내":["korean"],"국립":["korean"],"국물":["korean"],"국민":["korean"],"국수":["korean"],"국어":["korean"],"국왕":["korean"],"국적":["korean"],"국제":["korean"],"국회":["korean"],"군대":["korean"],"군사":["korean"],"군인":["korean"],"궁극적":["korean"],"권리":["korean"],"권위":["korean"],"권투":["korean"],"귀국":["korean"],"귀신":["korean"],"규정":["korean"],"규칙":["korean"],"균형":["korean"],"그날":["korean"],"그냥":["korean"],"그늘":["korean"],"그러나":["korean"],"그룹":["korean"],"그릇":["korean"],"그림":["korean"],"그제서야":["korean"],"그토록":["korean"],"극복":["korean"],"극히":["korean"],"근거":["korean"],"근교":["korean"],"근래":["korean"],"근로":["korean"],"근무":["korean"],"근본":["korean"],"근원":["korean"],"근육":["korean"],"근처":["korean"],"글씨":["korean"],"글자":["korean"],"금강산":["korean"],"금고":["korean"],"금년":["korean"],"금메달":["korean"],"금액":["korean"],"금연":["korean"],"금요일":["korean"],"금지":["korean"],"긍정적":["korean"],"기간":["korean"],"기관":["korean"],"기념":["korean"],"기능":["korean"],"기독교":["korean"],"기둥":["korean"],"기록":["korean"],"기름":["korean"],"기법":["korean"],"기본":["korean"],"기분":["korean"],"기쁨":["korean"],"기숙사":["korean"],"기술":["korean"],"기억":["korean"],"기업":["korean"],"기온":["korean"],"기운":["korean"],"기원":["korean"],"기적":["korean"],"기준":["korean"],"기침":["korean"],"기혼":["korean"],"기획":["korean"],"긴급":["korean"],"긴장":["korean"],"길이":["korean"],"김밥":["korean"],"김치":["korean"],"김포공항":["korean"],"깍두기":["korean"],"깜빡":["korean"],"깨달음":["korean"],"깨소금":["korean"],"껍질":["korean"],"꼭대기":["korean"],"꽃잎":["korean"],"나들이":["korean"],"나란히":["korean"],"나머지":["korean"],"나물":["korean"],"나침반":["korean"],"나흘":["korean"],"낙엽":["korean"],"난방":["korean"],"날개":["korean"],"날씨":["korean"],"날짜":["korean"],"남녀":["korean"],"남대문":["korean"],"남매":["korean"],"남산":["korean"],"남자":["korean"],"남편":["korean"],"남학생":["korean"],"낭비":["korean"],"낱말":["korean"],"내년":["korean"],"내용":["korean"],"내일":["korean"],"냄비":["korean"],"냄새":["korean"],"냇물":["korean"],"냉동":["korean"],"냉면":["korean"],"냉방":["korean"],"냉장고":["korean"],"넥타이":["korean"],"넷째":["korean"],"노동":["korean"],"노란색":["korean"],"노력":["korean"],"노인":["korean"],"녹음":["korean"],"녹차":["korean"],"녹화":["korean"],"논리":["korean"],"논문":["korean"],"논쟁":["korean"],"놀이":["korean"],"농구":["korean"],"농담":["korean"],"농민":["korean"],"농부":["korean"],"농업":["korean"],"농장":["korean"],"농촌":["korean"],"높이":["korean"],"눈동자":["korean"],"눈물":["korean"],"눈썹":["korean"],"뉴욕":["korean"],"느낌":["korean"],"늑대":["korean"],"능동적":["korean"],"능력":["korean"],"다방":["korean"],"다양성":["korean"],"다음":["korean"],"다이어트":["korean"],"다행":["korean"],"단계":["korean"],"단골":["korean"],"단독":["korean"],"단맛":["korean"],"단순":["korean"],"단어":["korean"],"단위":["korean"],"단점":["korean"],"단체":["korean"],"단추":["korean"],"단편":["korean"],"단풍":["korean"],"달걀":["korean"],"달러":["korean"],"달력":["korean"],"달리":["korean"],"닭고기":["korean"],"담당":["korean"],"담배":["korean"],"담요":["korean"],"담임":["korean"],"답변":["korean"],"답장":["korean"],"당근":["korean"],"당분간":["korean"],"당연히":["korean"],"당장":["korean"],"대규모":["korean"],"대낮":["korean"],"대단히":["korean"],"대답":["korean"],"대도시":["korean"],"대략":["korean"],"대량":["korean"],"대륙":["korean"],"대문":["korean"],"대부분":["korean"],"대신":["korean"],"대응":["korean"],"대장":["korean"],"대전":["korean"],"대접":["korean"],"대중":["korean"],"대책":["korean"],"대출":["korean"],"대충":["korean"],"대통령":["korean"],"대학":["korean"],"대한민국":["korean"],"대합실":["korean"],"대형":["korean"],"덩어리":["korean"],"데이트":["korean"],"도대체":["korean"],"도덕":["korean"],"도둑":["korean"],"도망":["korean"],"도서관":["korean"],"도심":["korean"],"도움":["korean"],"도입":["korean"],"도자기":["korean"],"도저히":["korean"],"도전":["korean"],"도중":["korean"],"도착":["korean"],"독감":["korean"],"독립":["korean"],"독서":["korean"],"독일":["korean"],"독창적":["korean"],"동화책":["korean"],"뒷모습":["korean"],"뒷산":["korean"],"딸아이":["korean"],"마누라":["korean"],"마늘":["korean"],"마당":["korean"],"마라톤":["korean"],"마련":["korean"],"마무리":["korean"],"마사지":["korean"],"마약":["korean"],"마요네즈":["korean"],"마을":["korean"],"마음":["korean"],"마이크":["korean"],"마중":["korean"],"마지막":["korean"],"마찬가지":["korean"],"마찰":["korean"],"마흔":["korean"],"막걸리":["korean"],"막내":["korean"],"막상":["korean"],"만남":["korean"],"만두":["korean"],"만세":["korean"],"만약":["korean"],"만일":["korean"],"만점":["korean"],"만족":["korean"],"만화":["korean"],"많이":["korean"],"말기":["korean"],"말씀":["korean"],"말투":["korean"],"맘대로":["korean"],"망원경":["korean"],"매년":["korean"],"매달":["korean"],"매력":["korean"],"매번":["korean"],"매스컴":["korean"],"매일":["korean"],"매장":["korean"],"맥주":["korean"],"먹이":["korean"],"먼저":["korean"],"먼지":["korean"],"멀리":["korean"],"메일":["korean"],"며느리":["korean"],"며칠":["korean"],"면담":["korean"],"멸치":["korean"],"명단":["korean"],"명령":["korean"],"명예":["korean"],"명의":["korean"],"명절":["korean"],"명칭":["korean"],"명함":["korean"],"모금":["korean"],"모니터":["korean"],"모델":["korean"],"모든":["korean"],"모범":["korean"],"모습":["korean"],"모양":["korean"],"모임":["korean"],"모조리":["korean"],"모집":["korean"],"모퉁이":["korean"],"목걸이":["korean"],"목록":["korean"],"목사":["korean"],"목소리":["korean"],"목숨":["korean"],"목적":["korean"],"목표":["korean"],"몰래":["korean"],"몸매":["korean"],"몸무게":["korean"],"몸살":["korean"],"몸속":["korean"],"몸짓":["korean"],"몸통":["korean"],"몹시":["korean"],"무관심":["korean"],"무궁화":["korean"],"무더위":["korean"],"무덤":["korean"],"무릎":["korean"],"무슨":["korean"],"무엇":["korean"],"무역":["korean"],"무용":["korean"],"무조건":["korean"],"무지개":["korean"],"무척":["korean"],"문구":["korean"],"문득":["korean"],"문법":["korean"],"문서":["korean"],"문제":["korean"],"문학":["korean"],"문화":["korean"],"물가":["korean"],"물건":["korean"],"물결":["korean"],"물고기":["korean"],"물론":["korean"],"물리학":["korean"],"물음":["korean"],"물질":["korean"],"물체":["korean"],"미국":["korean"],"미디어":["korean"],"미사일":["korean"],"미술":["korean"],"미역":["korean"],"미용실":["korean"],"미움":["korean"],"미인":["korean"],"미팅":["korean"],"미혼":["korean"],"민간":["korean"],"민족":["korean"],"민주":["korean"],"믿음":["korean"],"밀가루":["korean"],"밀리미터":["korean"],"밑바닥":["korean"],"바가지":["korean"],"바구니":["korean"],"바나나":["korean"],"바늘":["korean"],"바닥":["korean"],"바닷가":["korean"],"바람":["korean"],"바이러스":["korean"],"바탕":["korean"],"박물관":["korean"],"박사":["korean"],"박수":["korean"],"반대":["korean"],"반드시":["korean"],"반말":["korean"],"반발":["korean"],"반성":["korean"],"반응":["korean"],"반장":["korean"],"반죽":["korean"],"반지":["korean"],"반찬":["korean"],"받침":["korean"],"발가락":["korean"],"발걸음":["korean"],"발견":["korean"],"발달":["korean"],"발레":["korean"],"발목":["korean"],"발바닥":["korean"],"발생":["korean"],"발음":["korean"],"발자국":["korean"],"발전":["korean"],"발톱":["korean"],"발표":["korean"],"밤하늘":["korean"],"밥그릇":["korean"],"밥맛":["korean"],"밥상":["korean"],"밥솥":["korean"],"방금":["korean"],"방면":["korean"],"방문":["korean"],"방바닥":["korean"],"방법":["korean"],"방송":["korean"],"방식":["korean"],"방안":["korean"],"방울":["korean"],"방지":["korean"],"방학":["korean"],"방해":["korean"],"방향":["korean"],"배경":["korean"],"배꼽":["korean"],"배달":["korean"],"배드민턴":["korean"],"백두산":["korean"],"백색":["korean"],"백성":["korean"],"백인":["korean"],"백제":["korean"],"백화점":["korean"],"버릇":["korean"],"버섯":["korean"],"버튼":["korean"],"번개":["korean"],"번역":["korean"],"번지":["korean"],"번호":["korean"],"벌금":["korean"],"벌레":["korean"],"벌써":["korean"],"범위":["korean"],"범인":["korean"],"범죄":["korean"],"법률":["korean"],"법원":["korean"],"법적":["korean"],"법칙":["korean"],"베이징":["korean"],"벨트":["korean"],"변경":["korean"],"변동":["korean"],"변명":["korean"],"변신":["korean"],"변호사":["korean"],"변화":["korean"],"별도":["korean"],"별명":["korean"],"별일":["korean"],"병실":["korean"],"병아리":["korean"],"병원":["korean"],"보관":["korean"],"보너스":["korean"],"보라색":["korean"],"보람":["korean"],"보름":["korean"],"보상":["korean"],"보안":["korean"],"보자기":["korean"],"보장":["korean"],"보전":["korean"],"보존":["korean"],"보통":["korean"],"보편적":["korean"],"보험":["korean"],"복도":["korean"],"복사":["korean"],"복숭아":["korean"],"복습":["korean"],"볶음":["korean"],"본격적":["korean"],"본래":["korean"],"본부":["korean"],"본사":["korean"],"본성":["korean"],"본인":["korean"],"본질":["korean"],"볼펜":["korean"],"봉사":["korean"],"봉지":["korean"],"봉투":["korean"],"부근":["korean"],"부끄러움":["korean"],"부담":["korean"],"부동산":["korean"],"부문":["korean"],"부분":["korean"],"부산":["korean"],"부상":["korean"],"부엌":["korean"],"부인":["korean"],"부작용":["korean"],"부장":["korean"],"부정":["korean"],"부족":["korean"],"부지런히":["korean"],"부친":["korean"],"부탁":["korean"],"부품":["korean"],"부회장":["korean"],"북부":["korean"],"북한":["korean"],"분노":["korean"],"분량":["korean"],"분리":["korean"],"분명":["korean"],"분석":["korean"],"분야":["korean"],"분위기":["korean"],"분필":["korean"],"분홍색":["korean"],"불고기":["korean"],"불과":["korean"],"불교":["korean"],"불꽃":["korean"],"불만":["korean"],"불법":["korean"],"불빛":["korean"],"불안":["korean"],"불이익":["korean"],"불행":["korean"],"브랜드":["korean"],"비극":["korean"],"비난":["korean"],"비닐":["korean"],"비둘기":["korean"],"비디오":["korean"],"비로소":["korean"],"비만":["korean"],"비명":["korean"],"비밀":["korean"],"비바람":["korean"],"비빔밥":["korean"],"비상":["korean"],"비용":["korean"],"비율":["korean"],"비중":["korean"],"비타민":["korean"],"비판":["korean"],"빌딩":["korean"],"빗물":["korean"],"빗방울":["korean"],"빗줄기":["korean"],"빛깔":["korean"],"빨간색":["korean"],"빨래":["korean"],"빨리":["korean"],"사건":["korean"],"사계절":["korean"],"사나이":["korean"],"사냥":["korean"],"사람":["korean"],"사랑":["korean"],"사립":["korean"],"사모님":["korean"],"사물":["korean"],"사방":["korean"],"사상":["korean"],"사생활":["korean"],"사설":["korean"],"사슴":["korean"],"사실":["korean"],"사업":["korean"],"사용":["korean"],"사월":["korean"],"사장":["korean"],"사전":["korean"],"사진":["korean"],"사촌":["korean"],"사춘기":["korean"],"사탕":["korean"],"사투리":["korean"],"사흘":["korean"],"산길":["korean"],"산부인과":["korean"],"산업":["korean"],"산책":["korean"],"살림":["korean"],"살인":["korean"],"살짝":["korean"],"삼계탕":["korean"],"삼국":["korean"],"삼십":["korean"],"삼월":["korean"],"삼촌":["korean"],"상관":["korean"],"상금":["korean"],"상대":["korean"],"상류":["korean"],"상반기":["korean"],"상상":["korean"],"상식":["korean"],"상업":["korean"],"상인":["korean"],"상자":["korean"],"상점":["korean"],"상처":["korean"],"상추":["korean"],"상태":["korean"],"상표":["korean"],"상품":["korean"],"상황":["korean"],"새벽":["korean"],"색깔":["korean"],"색연필":["korean"],"생각":["korean"],"생명":["korean"],"생물":["korean"],"생방송":["korean"],"생산":["korean"],"생선":["korean"],"생신":["korean"],"생일":["korean"],"생활":["korean"],"서랍":["korean"],"서른":["korean"],"서명":["korean"],"서민":["korean"],"서비스":["korean"],"서양":["korean"],"서울":["korean"],"서적":["korean"],"서점":["korean"],"서쪽":["korean"],"서클":["korean"],"석사":["korean"],"석유":["korean"],"선거":["korean"],"선물":["korean"],"선배":["korean"],"선생":["korean"],"선수":["korean"],"선원":["korean"],"선장":["korean"],"선전":["korean"],"선택":["korean"],"선풍기":["korean"],"설거지":["korean"],"설날":["korean"],"설렁탕":["korean"],"설명":["korean"],"설문":["korean"],"설사":["korean"],"설악산":["korean"],"설치":["korean"],"설탕":["korean"],"섭씨":["korean"],"성공":["korean"],"성당":["korean"],"성명":["korean"],"성별":["korean"],"성인":["korean"],"성장":["korean"],"성적":["korean"],"성질":["korean"],"성함":["korean"],"세금":["korean"],"세미나":["korean"],"세상":["korean"],"세월":["korean"],"세종대왕":["korean"],"세탁":["korean"],"센터":["korean"],"센티미터":["korean"],"셋째":["korean"],"소규모":["korean"],"소극적":["korean"],"소금":["korean"],"소나기":["korean"],"소년":["korean"],"소득":["korean"],"소망":["korean"],"소문":["korean"],"소설":["korean"],"소속":["korean"],"소아과":["korean"],"소용":["korean"],"소원":["korean"],"소음":["korean"],"소중히":["korean"],"소지품":["korean"],"소질":["korean"],"소풍":["korean"],"소형":["korean"],"속담":["korean"],"속도":["korean"],"속옷":["korean"],"손가락":["korean"],"손길":["korean"],"손녀":["korean"],"손님":["korean"],"손등":["korean"],"손목":["korean"],"손뼉":["korean"],"손실":["korean"],"손질":["korean"],"손톱":["korean"],"손해":["korean"],"솔직히":["korean"],"솜씨":["korean"],"송아지":["korean"],"송이":["korean"],"송편":["korean"],"쇠고기":["korean"],"쇼핑":["korean"],"수건":["korean"],"수년":["korean"],"수단":["korean"],"수돗물":["korean"],"수동적":["korean"],"수면":["korean"],"수명":["korean"],"수박":["korean"],"수상":["korean"],"수석":["korean"],"수술":["korean"],"수시로":["korean"],"수업":["korean"],"수염":["korean"],"수영":["korean"],"수입":["korean"],"수준":["korean"],"수집":["korean"],"수출":["korean"],"수컷":["korean"],"수필":["korean"],"수학":["korean"],"수험생":["korean"],"수화기":["korean"],"숙녀":["korean"],"숙소":["korean"],"숙제":["korean"],"순간":["korean"],"순서":["korean"],"순수":["korean"],"순식간":["korean"],"순위":["korean"],"숟가락":["korean"],"술병":["korean"],"술집":["korean"],"숫자":["korean"],"스님":["korean"],"스물":["korean"],"스스로":["korean"],"스승":["korean"],"스웨터":["korean"],"스위치":["korean"],"스케이트":["korean"],"스튜디오":["korean"],"스트레스":["korean"],"스포츠":["korean"],"슬쩍":["korean"],"슬픔":["korean"],"습관":["korean"],"습기":["korean"],"승객":["korean"],"승리":["korean"],"승부":["korean"],"승용차":["korean"],"승진":["korean"],"시각":["korean"],"시간":["korean"],"시골":["korean"],"시금치":["korean"],"시나리오":["korean"],"시댁":["korean"],"시리즈":["korean"],"시멘트":["korean"],"시민":["korean"],"시부모":["korean"],"시선":["korean"],"시설":["korean"],"시스템":["korean"],"시아버지":["korean"],"시어머니":["korean"],"시월":["korean"],"시인":["korean"],"시일":["korean"],"시작":["korean"],"시장":["korean"],"시절":["korean"],"시점":["korean"],"시중":["korean"],"시즌":["korean"],"시집":["korean"],"시청":["korean"],"시합":["korean"],"시험":["korean"],"식구":["korean"],"식기":["korean"],"식당":["korean"],"식량":["korean"],"식료품":["korean"],"식물":["korean"],"식빵":["korean"],"식사":["korean"],"식생활":["korean"],"식초":["korean"],"식탁":["korean"],"식품":["korean"],"신고":["korean"],"신규":["korean"],"신념":["korean"],"신문":["korean"],"신발":["korean"],"신비":["korean"],"신사":["korean"],"신세":["korean"],"신용":["korean"],"신제품":["korean"],"신청":["korean"],"신체":["korean"],"신화":["korean"],"실감":["korean"],"실내":["korean"],"실력":["korean"],"실례":["korean"],"실망":["korean"],"실수":["korean"],"실습":["korean"],"실시":["korean"],"실장":["korean"],"실정":["korean"],"실질적":["korean"],"실천":["korean"],"실체":["korean"],"실컷":["korean"],"실태":["korean"],"실패":["korean"],"실험":["korean"],"실현":["korean"],"심리":["korean"],"심부름":["korean"],"심사":["korean"],"심장":["korean"],"심정":["korean"],"심판":["korean"],"쌍둥이":["korean"],"씨름":["korean"],"씨앗":["korean"],"아가씨":["korean"],"아나운서":["korean"],"아드님":["korean"],"아들":["korean"],"아쉬움":["korean"],"아스팔트":["korean"],"아시아":["korean"],"아울러":["korean"],"아저씨":["korean"],"아줌마":["korean"],"아직":["korean"],"아침":["korean"],"아파트":["korean"],"아프리카":["korean"],"아픔":["korean"],"아홉":["korean"],"아흔":["korean"],"악기":["korean"],"악몽":["korean"],"악수":["korean"],"안개":["korean"],"안경":["korean"],"안과":["korean"],"안내":["korean"],"안녕":["korean"],"안동":["korean"],"안방":["korean"],"안부":["korean"],"안주":["korean"],"알루미늄":["korean"],"알코올":["korean"],"암시":["korean"],"암컷":["korean"],"압력":["korean"],"앞날":["korean"],"앞문":["korean"],"애인":["korean"],"애정":["korean"],"액수":["korean"],"앨범":["korean"],"야간":["korean"],"야단":["korean"],"야옹":["korean"],"약간":["korean"],"약국":["korean"],"약속":["korean"],"약수":["korean"],"약점":["korean"],"약품":["korean"],"약혼녀":["korean"],"양념":["korean"],"양력":["korean"],"양말":["korean"],"양배추":["korean"],"양주":["korean"],"양파":["korean"],"어둠":["korean"],"어려움":["korean"],"어른":["korean"],"어젯밤":["korean"],"어쨌든":["korean"],"어쩌다가":["korean"],"어쩐지":["korean"],"언니":["korean"],"언덕":["korean"],"언론":["korean"],"언어":["korean"],"얼굴":["korean"],"얼른":["korean"],"얼음":["korean"],"얼핏":["korean"],"엄마":["korean"],"업무":["korean"],"업종":["korean"],"업체":["korean"],"엉덩이":["korean"],"엉망":["korean"],"엉터리":["korean"],"엊그제":["korean"],"에너지":["korean"],"에어컨":["korean"],"엔진":["korean"],"여건":["korean"],"여고생":["korean"],"여관":["korean"],"여군":["korean"],"여권":["korean"],"여대생":["korean"],"여덟":["korean"],"여동생":["korean"],"여든":["korean"],"여론":["korean"],"여름":["korean"],"여섯":["korean"],"여성":["korean"],"여왕":["korean"],"여인":["korean"],"여전히":["korean"],"여직원":["korean"],"여학생":["korean"],"여행":["korean"],"역사":["korean"],"역시":["korean"],"역할":["korean"],"연결":["korean"],"연구":["korean"],"연극":["korean"],"연기":["korean"],"연락":["korean"],"연설":["korean"],"연세":["korean"],"연속":["korean"],"연습":["korean"],"연애":["korean"],"연예인":["korean"],"연인":["korean"],"연장":["korean"],"연주":["korean"],"연출":["korean"],"연필":["korean"],"연합":["korean"],"연휴":["korean"],"열기":["korean"],"열매":["korean"],"열쇠":["korean"],"열심히":["korean"],"열정":["korean"],"열차":["korean"],"열흘":["korean"],"염려":["korean"],"엽서":["korean"],"영국":["korean"],"영남":["korean"],"영상":["korean"],"영양":["korean"],"영역":["korean"],"영웅":["korean"],"영원히":["korean"],"영하":["korean"],"영향":["korean"],"영혼":["korean"],"영화":["korean"],"옆구리":["korean"],"옆방":["korean"],"옆집":["korean"],"예감":["korean"],"예금":["korean"],"예방":["korean"],"예산":["korean"],"예상":["korean"],"예선":["korean"],"예술":["korean"],"예습":["korean"],"예식장":["korean"],"예약":["korean"],"예전":["korean"],"예절":["korean"],"예정":["korean"],"예컨대":["korean"],"옛날":["korean"],"오늘":["korean"],"오락":["korean"],"오랫동안":["korean"],"오렌지":["korean"],"오로지":["korean"],"오른발":["korean"],"오븐":["korean"],"오십":["korean"],"오염":["korean"],"오월":["korean"],"오전":["korean"],"오직":["korean"],"오징어":["korean"],"오페라":["korean"],"오피스텔":["korean"],"오히려":["korean"],"옥상":["korean"],"옥수수":["korean"],"온갖":["korean"],"온라인":["korean"],"온몸":["korean"],"온종일":["korean"],"온통":["korean"],"올가을":["korean"],"올림픽":["korean"],"올해":["korean"],"옷차림":["korean"],"와이셔츠":["korean"],"와인":["korean"],"완성":["korean"],"완전":["korean"],"왕비":["korean"],"왕자":["korean"],"왜냐하면":["korean"],"왠지":["korean"],"외갓집":["korean"],"외국":["korean"],"외로움":["korean"],"외삼촌":["korean"],"외출":["korean"],"외침":["korean"],"외할머니":["korean"],"왼발":["korean"],"왼손":["korean"],"왼쪽":["korean"],"요금":["korean"],"요일":["korean"],"요즘":["korean"],"요청":["korean"],"용기":["korean"],"용서":["korean"],"용어":["korean"],"우산":["korean"],"우선":["korean"],"우승":["korean"],"우연히":["korean"],"우정":["korean"],"우체국":["korean"],"우편":["korean"],"운동":["korean"],"운명":["korean"],"운반":["korean"],"운전":["korean"],"운행":["korean"],"울산":["korean"],"울음":["korean"],"움직임":["korean"],"웃어른":["korean"],"웃음":["korean"],"워낙":["korean"],"원고":["korean"],"원래":["korean"],"원서":["korean"],"원숭이":["korean"],"원인":["korean"],"원장":["korean"],"원피스":["korean"],"월급":["korean"],"월드컵":["korean"],"월세":["korean"],"월요일":["korean"],"웨이터":["korean"],"위반":["korean"],"위법":["korean"],"위성":["korean"],"위원":["korean"],"위험":["korean"],"위협":["korean"],"윗사람":["korean"],"유난히":["korean"],"유럽":["korean"],"유명":["korean"],"유물":["korean"],"유산":["korean"],"유적":["korean"],"유치원":["korean"],"유학":["korean"],"유행":["korean"],"유형":["korean"],"육군":["korean"],"육상":["korean"],"육십":["korean"],"육체":["korean"],"은행":["korean"],"음력":["korean"],"음료":["korean"],"음반":["korean"],"음성":["korean"],"음식":["korean"],"음악":["korean"],"음주":["korean"],"의견":["korean"],"의논":["korean"],"의문":["korean"],"의복":["korean"],"의식":["korean"],"의심":["korean"],"의외로":["korean"],"의욕":["korean"],"의원":["korean"],"의학":["korean"],"이것":["korean"],"이곳":["korean"],"이념":["korean"],"이놈":["korean"],"이달":["korean"],"이대로":["korean"],"이동":["korean"],"이렇게":["korean"],"이력서":["korean"],"이론적":["korean"],"이름":["korean"],"이민":["korean"],"이발소":["korean"],"이별":["korean"],"이불":["korean"],"이빨":["korean"],"이상":["korean"],"이성":["korean"],"이슬":["korean"],"이야기":["korean"],"이용":["korean"],"이웃":["korean"],"이월":["korean"],"이윽고":["korean"],"이익":["korean"],"이전":["korean"],"이중":["korean"],"이튿날":["korean"],"이틀":["korean"],"이혼":["korean"],"인간":["korean"],"인격":["korean"],"인공":["korean"],"인구":["korean"],"인근":["korean"],"인기":["korean"],"인도":["korean"],"인류":["korean"],"인물":["korean"],"인생":["korean"],"인쇄":["korean"],"인연":["korean"],"인원":["korean"],"인재":["korean"],"인종":["korean"],"인천":["korean"],"인체":["korean"],"인터넷":["korean"],"인하":["korean"],"인형":["korean"],"일곱":["korean"],"일기":["korean"],"일단":["korean"],"일대":["korean"],"일등":["korean"],"일반":["korean"],"일본":["korean"],"일부":["korean"],"일상":["korean"],"일생":["korean"],"일손":["korean"],"일요일":["korean"],"일월":["korean"],"일정":["korean"],"일종":["korean"],"일주일":["korean"],"일찍":["korean"],"일체":["korean"],"일치":["korean"],"일행":["korean"],"일회용":["korean"],"임금":["korean"],"임무":["korean"],"입대":["korean"],"입력":["korean"],"입맛":["korean"],"입사":["korean"],"입술":["korean"],"입시":["korean"],"입원":["korean"],"입장":["korean"],"입학":["korean"],"자가용":["korean"],"자격":["korean"],"자극":["korean"],"자동":["korean"],"자랑":["korean"],"자부심":["korean"],"자식":["korean"],"자신":["korean"],"자연":["korean"],"자원":["korean"],"자율":["korean"],"자전거":["korean"],"자정":["korean"],"자존심":["korean"],"자판":["korean"],"작가":["korean"],"작년":["korean"],"작성":["korean"],"작업":["korean"],"작용":["korean"],"작은딸":["korean"],"작품":["korean"],"잔디":["korean"],"잔뜩":["korean"],"잔치":["korean"],"잘못":["korean"],"잠깐":["korean"],"잠수함":["korean"],"잠시":["korean"],"잠옷":["korean"],"잠자리":["korean"],"잡지":["korean"],"장관":["korean"],"장군":["korean"],"장기간":["korean"],"장래":["korean"],"장례":["korean"],"장르":["korean"],"장마":["korean"],"장면":["korean"],"장모":["korean"],"장미":["korean"],"장비":["korean"],"장사":["korean"],"장소":["korean"],"장식":["korean"],"장애인":["korean"],"장인":["korean"],"장점":["korean"],"장차":["korean"],"장학금":["korean"],"재능":["korean"],"재빨리":["korean"],"재산":["korean"],"재생":["korean"],"재작년":["korean"],"재정":["korean"],"재채기":["korean"],"재판":["korean"],"재학":["korean"],"재활용":["korean"],"저것":["korean"],"저고리":["korean"],"저곳":["korean"],"저녁":["korean"],"저런":["korean"],"저렇게":["korean"],"저번":["korean"],"저울":["korean"],"저절로":["korean"],"저축":["korean"],"적극":["korean"],"적당히":["korean"],"적성":["korean"],"적용":["korean"],"적응":["korean"],"전개":["korean"],"전공":["korean"],"전기":["korean"],"전달":["korean"],"전라도":["korean"],"전망":["korean"],"전문":["korean"],"전반":["korean"],"전부":["korean"],"전세":["korean"],"전시":["korean"],"전용":["korean"],"전자":["korean"],"전쟁":["korean"],"전주":["korean"],"전철":["korean"],"전체":["korean"],"전통":["korean"],"전혀":["korean"],"전후":["korean"],"절대":["korean"],"절망":["korean"],"절반":["korean"],"절약":["korean"],"절차":["korean"],"점검":["korean"],"점수":["korean"],"점심":["korean"],"점원":["korean"],"점점":["korean"],"점차":["korean"],"접근":["korean"],"접시":["korean"],"접촉":["korean"],"젓가락":["korean"],"정거장":["korean"],"정도":["korean"],"정류장":["korean"],"정리":["korean"],"정말":["korean"],"정면":["korean"],"정문":["korean"],"정반대":["korean"],"정보":["korean"],"정부":["korean"],"정비":["korean"],"정상":["korean"],"정성":["korean"],"정오":["korean"],"정원":["korean"],"정장":["korean"],"정지":["korean"],"정치":["korean"],"정확히":["korean"],"제공":["korean"],"제과점":["korean"],"제대로":["korean"],"제목":["korean"],"제발":["korean"],"제법":["korean"],"제삿날":["korean"],"제안":["korean"],"제일":["korean"],"제작":["korean"],"제주도":["korean"],"제출":["korean"],"제품":["korean"],"제한":["korean"],"조각":["korean"],"조건":["korean"],"조금":["korean"],"조깅":["korean"],"조명":["korean"],"조미료":["korean"],"조상":["korean"],"조선":["korean"],"조용히":["korean"],"조절":["korean"],"조정":["korean"],"조직":["korean"],"존댓말":["korean"],"존재":["korean"],"졸업":["korean"],"졸음":["korean"],"종교":["korean"],"종로":["korean"],"종류":["korean"],"종소리":["korean"],"종업원":["korean"],"종종":["korean"],"종합":["korean"],"좌석":["korean"],"죄인":["korean"],"주관적":["korean"],"주름":["korean"],"주말":["korean"],"주머니":["korean"],"주먹":["korean"],"주문":["korean"],"주민":["korean"],"주방":["korean"],"주변":["korean"],"주식":["korean"],"주인":["korean"],"주일":["korean"],"주장":["korean"],"주전자":["korean"],"주택":["korean"],"준비":["korean"],"줄거리":["korean"],"줄기":["korean"],"줄무늬":["korean"],"중간":["korean"],"중계방송":["korean"],"중국":["korean"],"중년":["korean"],"중단":["korean"],"중독":["korean"],"중반":["korean"],"중부":["korean"],"중세":["korean"],"중소기업":["korean"],"중순":["korean"],"중앙":["korean"],"중요":["korean"],"중학교":["korean"],"즉석":["korean"],"즉시":["korean"],"즐거움":["korean"],"증가":["korean"],"증거":["korean"],"증권":["korean"],"증상":["korean"],"증세":["korean"],"지각":["korean"],"지갑":["korean"],"지경":["korean"],"지극히":["korean"],"지금":["korean"],"지급":["korean"],"지능":["korean"],"지름길":["korean"],"지리산":["korean"],"지방":["korean"],"지붕":["korean"],"지식":["korean"],"지역":["korean"],"지우개":["korean"],"지원":["korean"],"지적":["korean"],"지점":["korean"],"지진":["korean"],"지출":["korean"],"직선":["korean"],"직업":["korean"],"직원":["korean"],"직장":["korean"],"진급":["korean"],"진동":["korean"],"진로":["korean"],"진료":["korean"],"진리":["korean"],"진짜":["korean"],"진찰":["korean"],"진출":["korean"],"진통":["korean"],"진행":["korean"],"질문":["korean"],"질병":["korean"],"질서":["korean"],"짐작":["korean"],"집단":["korean"],"집안":["korean"],"집중":["korean"],"짜증":["korean"],"찌꺼기":["korean"],"차남":["korean"],"차라리":["korean"],"차량":["korean"],"차림":["korean"],"차별":["korean"],"차선":["korean"],"차츰":["korean"],"착각":["korean"],"찬물":["korean"],"찬성":["korean"],"참가":["korean"],"참기름":["korean"],"참새":["korean"],"참석":["korean"],"참여":["korean"],"참외":["korean"],"참조":["korean"],"찻잔":["korean"],"창가":["korean"],"창고":["korean"],"창구":["korean"],"창문":["korean"],"창밖":["korean"],"창작":["korean"],"창조":["korean"],"채널":["korean"],"채점":["korean"],"책가방":["korean"],"책방":["korean"],"책상":["korean"],"책임":["korean"],"챔피언":["korean"],"처벌":["korean"],"처음":["korean"],"천국":["korean"],"천둥":["korean"],"천장":["korean"],"천재":["korean"],"천천히":["korean"],"철도":["korean"],"철저히":["korean"],"철학":["korean"],"첫날":["korean"],"첫째":["korean"],"청년":["korean"],"청바지":["korean"],"청소":["korean"],"청춘":["korean"],"체계":["korean"],"체력":["korean"],"체온":["korean"],"체육":["korean"],"체중":["korean"],"체험":["korean"],"초등학생":["korean"],"초반":["korean"],"초밥":["korean"],"초상화":["korean"],"초순":["korean"],"초여름":["korean"],"초원":["korean"],"초저녁":["korean"],"초점":["korean"],"초청":["korean"],"초콜릿":["korean"],"촛불":["korean"],"총각":["korean"],"총리":["korean"],"총장":["korean"],"촬영":["korean"],"최근":["korean"],"최상":["korean"],"최선":["korean"],"최신":["korean"],"최악":["korean"],"최종":["korean"],"추석":["korean"],"추억":["korean"],"추진":["korean"],"추천":["korean"],"추측":["korean"],"축구":["korean"],"축소":["korean"],"축제":["korean"],"축하":["korean"],"출근":["korean"],"출발":["korean"],"출산":["korean"],"출신":["korean"],"출연":["korean"],"출입":["korean"],"출장":["korean"],"출판":["korean"],"충격":["korean"],"충고":["korean"],"충돌":["korean"],"충분히":["korean"],"충청도":["korean"],"취업":["korean"],"취직":["korean"],"취향":["korean"],"치약":["korean"],"친구":["korean"],"친척":["korean"],"칠십":["korean"],"칠월":["korean"],"칠판":["korean"],"침대":["korean"],"침묵":["korean"],"침실":["korean"],"칫솔":["korean"],"칭찬":["korean"],"카메라":["korean"],"카운터":["korean"],"칼국수":["korean"],"캐릭터":["korean"],"캠퍼스":["korean"],"캠페인":["korean"],"커튼":["korean"],"컨디션":["korean"],"컬러":["korean"],"컴퓨터":["korean"],"코끼리":["korean"],"코미디":["korean"],"콘서트":["korean"],"콜라":["korean"],"콤플렉스":["korean"],"콩나물":["korean"],"쾌감":["korean"],"쿠데타":["korean"],"크림":["korean"],"큰길":["korean"],"큰딸":["korean"],"큰소리":["korean"],"큰아들":["korean"],"큰어머니":["korean"],"큰일":["korean"],"큰절":["korean"],"클래식":["korean"],"클럽":["korean"],"킬로":["korean"],"타입":["korean"],"타자기":["korean"],"탁구":["korean"],"탁자":["korean"],"탄생":["korean"],"태권도":["korean"],"태양":["korean"],"태풍":["korean"],"택시":["korean"],"탤런트":["korean"],"터널":["korean"],"터미널":["korean"],"테니스":["korean"],"테스트":["korean"],"테이블":["korean"],"텔레비전":["korean"],"토론":["korean"],"토마토":["korean"],"토요일":["korean"],"통계":["korean"],"통과":["korean"],"통로":["korean"],"통신":["korean"],"통역":["korean"],"통일":["korean"],"통장":["korean"],"통제":["korean"],"통증":["korean"],"통합":["korean"],"통화":["korean"],"퇴근":["korean"],"퇴원":["korean"],"퇴직금":["korean"],"튀김":["korean"],"트럭":["korean"],"특급":["korean"],"특별":["korean"],"특성":["korean"],"특수":["korean"],"특징":["korean"],"특히":["korean"],"튼튼히":["korean"],"티셔츠":["korean"],"파란색":["korean"],"파일":["korean"],"파출소":["korean"],"판결":["korean"],"판단":["korean"],"판매":["korean"],"판사":["korean"],"팔십":["korean"],"팔월":["korean"],"팝송":["korean"],"패션":["korean"],"팩스":["korean"],"팩시밀리":["korean"],"팬티":["korean"],"퍼센트":["korean"],"페인트":["korean"],"편견":["korean"],"편의":["korean"],"편지":["korean"],"편히":["korean"],"평가":["korean"],"평균":["korean"],"평생":["korean"],"평소":["korean"],"평양":["korean"],"평일":["korean"],"평화":["korean"],"포스터":["korean"],"포인트":["korean"],"포장":["korean"],"포함":["korean"],"표면":["korean"],"표정":["korean"],"표준":["korean"],"표현":["korean"],"품목":["korean"],"품질":["korean"],"풍경":["korean"],"풍속":["korean"],"풍습":["korean"],"프랑스":["korean"],"프린터":["korean"],"플라스틱":["korean"],"피곤":["korean"],"피망":["korean"],"피아노":["korean"],"필름":["korean"],"필수":["korean"],"필요":["korean"],"필자":["korean"],"필통":["korean"],"핑계":["korean"],"하느님":["korean"],"하늘":["korean"],"하드웨어":["korean"],"하룻밤":["korean"],"하반기":["korean"],"하숙집":["korean"],"하순":["korean"],"하여튼":["korean"],"하지만":["korean"],"하천":["korean"],"하품":["korean"],"하필":["korean"],"학과":["korean"],"학교":["korean"],"학급":["korean"],"학기":["korean"],"학년":["korean"],"학력":["korean"],"학번":["korean"],"학부모":["korean"],"학비":["korean"],"학생":["korean"],"학술":["korean"],"학습":["korean"],"학용품":["korean"],"학원":["korean"],"학위":["korean"],"학자":["korean"],"학점":["korean"],"한계":["korean"],"한글":["korean"],"한꺼번에":["korean"],"한낮":["korean"],"한눈":["korean"],"한동안":["korean"],"한때":["korean"],"한라산":["korean"],"한마디":["korean"],"한문":["korean"],"한번":["korean"],"한복":["korean"],"한식":["korean"],"한여름":["korean"],"한쪽":["korean"],"할머니":["korean"],"할아버지":["korean"],"할인":["korean"],"함께":["korean"],"함부로":["korean"],"합격":["korean"],"합리적":["korean"],"항공":["korean"],"항구":["korean"],"항상":["korean"],"항의":["korean"],"해결":["korean"],"해군":["korean"],"해답":["korean"],"해당":["korean"],"해물":["korean"],"해석":["korean"],"해설":["korean"],"해수욕장":["korean"],"해안":["korean"],"핵심":["korean"],"핸드백":["korean"],"햄버거":["korean"],"햇볕":["korean"],"햇살":["korean"],"행동":["korean"],"행복":["korean"],"행사":["korean"],"행운":["korean"],"행위":["korean"],"향기":["korean"],"향상":["korean"],"향수":["korean"],"허락":["korean"],"허용":["korean"],"헬기":["korean"],"현관":["korean"],"현금":["korean"],"현대":["korean"],"현상":["korean"],"현실":["korean"],"현장":["korean"],"현재":["korean"],"현지":["korean"],"혈액":["korean"],"협력":["korean"],"형부":["korean"],"형사":["korean"],"형수":["korean"],"형식":["korean"],"형제":["korean"],"형태":["korean"],"형편":["korean"],"혜택":["korean"],"호기심":["korean"],"호남":["korean"],"호랑이":["korean"],"호박":["korean"],"호텔":["korean"],"호흡":["korean"],"혹시":["korean"],"홀로":["korean"],"홈페이지":["korean"],"홍보":["korean"],"홍수":["korean"],"홍차":["korean"],"화면":["korean"],"화분":["korean"],"화살":["korean"],"화요일":["korean"],"화장":["korean"],"화학":["korean"],"확보":["korean"],"확인":["korean"],"확장":["korean"],"확정":["korean"],"환갑":["korean"],"환경":["korean"],"환영":["korean"],"환율":["korean"],"환자":["korean"],"활기":["korean"],"활동":["korean"],"활발히":["korean"],"활용":["korean"],"활짝":["korean"],"회견":["korean"],"회관":["korean"],"회복":["korean"],"회색":["korean"],"회원":["korean"],"회장":["korean"],"회전":["korean"],"횟수":["korean"],"횡단보도":["korean"],"효율적":["korean"],"후반":["korean"],"후춧가루":["korean"],"훈련":["korean"],"훨씬":["korean"],"휴식":["korean"],"휴일":["korean"],"흉내":["korean"],"흐름":["korean"],"흑백":["korean"],"흑인":["korean"],"흔적":["korean"],"흔히":["korean"],"흥미":["korean"],"흥분":["korean"],"희곡":["korean"],"희망":["korean"],"희생":["korean"],"흰색":["korean"],"힘껏":["korean"],"abacate":["portuguese"],"abaixo":["portuguese"],"abalar":["portuguese"],"abater":["portuguese"],"abduzir":["portuguese"],"abelha":["portuguese"],"aberto":["portuguese"],"abismo":["portuguese"],"abotoar":["portuguese"],"abranger":["portuguese"],"abreviar":["portuguese"],"abrigar":["portuguese"],"abrupto":["portuguese"],"absinto":["portuguese"],"absoluto":["portuguese"],"absurdo":["portuguese"],"abutre":["portuguese"],"acabado":["portuguese"],"acalmar":["portuguese"],"acampar":["portuguese"],"acanhar":["portuguese"],"acaso":["portuguese"],"aceitar":["portuguese"],"acelerar":["portuguese"],"acenar":["portuguese"],"acervo":["portuguese"],"acessar":["portuguese"],"acetona":["portuguese"],"achatar":["portuguese"],"acidez":["portuguese"],"acima":["portuguese"],"acionado":["portuguese"],"acirrar":["portuguese"],"aclamar":["portuguese"],"aclive":["portuguese"],"acolhida":["portuguese"],"acomodar":["portuguese"],"acoplar":["portuguese"],"acordar":["portuguese"],"acumular":["portuguese"],"acusador":["portuguese"],"adaptar":["portuguese"],"adega":["portuguese"],"adentro":["portuguese"],"adepto":["portuguese"],"adequar":["portuguese"],"aderente":["portuguese"],"adesivo":["portuguese"],"adeus":["portuguese"],"adiante":["portuguese"],"aditivo":["portuguese"],"adjetivo":["portuguese"],"adjunto":["portuguese"],"admirar":["portuguese"],"adorar":["portuguese"],"adquirir":["portuguese"],"adubo":["portuguese"],"adverso":["portuguese"],"advogado":["portuguese"],"aeronave":["portuguese"],"afastar":["portuguese"],"aferir":["portuguese"],"afetivo":["portuguese"],"afinador":["portuguese"],"afivelar":["portuguese"],"aflito":["portuguese"],"afluente":["portuguese"],"afrontar":["portuguese"],"agachar":["portuguese"],"agarrar":["portuguese"],"agasalho":["portuguese"],"agenciar":["portuguese"],"agilizar":["portuguese"],"agiota":["portuguese"],"agitado":["portuguese"],"agora":["portuguese"],"agradar":["portuguese"],"agreste":["portuguese"],"agrupar":["portuguese"],"aguardar":["portuguese"],"agulha":["portuguese"],"ajoelhar":["portuguese"],"ajudar":["portuguese"],"ajustar":["portuguese"],"alameda":["portuguese"],"alarme":["portuguese"],"alastrar":["portuguese"],"alavanca":["portuguese"],"albergue":["portuguese"],"albino":["portuguese"],"alcatra":["portuguese"],"aldeia":["portuguese"],"alecrim":["portuguese"],"alegria":["portuguese"],"alertar":["portuguese"],"alface":["portuguese"],"alfinete":["portuguese"],"algum":["portuguese"],"alheio":["portuguese"],"aliar":["portuguese"],"alicate":["portuguese"],"alienar":["portuguese"],"alinhar":["portuguese"],"aliviar":["portuguese"],"almofada":["portuguese"],"alocar":["portuguese"],"alpiste":["portuguese"],"alterar":["portuguese"],"altitude":["portuguese"],"alucinar":["portuguese"],"alugar":["portuguese"],"aluno":["portuguese"],"alusivo":["portuguese"],"alvo":["portuguese"],"amaciar":["portuguese"],"amador":["portuguese"],"amarelo":["portuguese"],"amassar":["portuguese"],"ambas":["portuguese"],"ambiente":["portuguese"],"ameixa":["portuguese"],"amenizar":["portuguese"],"amido":["portuguese"],"amistoso":["portuguese"],"amizade":["portuguese"],"amolador":["portuguese"],"amontoar":["portuguese"],"amoroso":["portuguese"],"amostra":["portuguese"],"amparar":["portuguese"],"ampliar":["portuguese"],"ampola":["portuguese"],"anagrama":["portuguese"],"analisar":["portuguese"],"anarquia":["portuguese"],"anatomia":["portuguese"],"andaime":["portuguese"],"anel":["portuguese"],"anexo":["portuguese"],"angular":["portuguese"],"animar":["portuguese"],"anjo":["portuguese"],"anomalia":["portuguese"],"anotado":["portuguese"],"ansioso":["portuguese"],"anterior":["portuguese"],"anuidade":["portuguese"],"anunciar":["portuguese"],"anzol":["portuguese"],"apagador":["portuguese"],"apalpar":["portuguese"],"apanhado":["portuguese"],"apego":["portuguese"],"apelido":["portuguese"],"apertada":["portuguese"],"apesar":["portuguese"],"apetite":["portuguese"],"apito":["portuguese"],"aplauso":["portuguese"],"aplicada":["portuguese"],"apoio":["portuguese"],"apontar":["portuguese"],"aposta":["portuguese"],"aprendiz":["portuguese"],"aprovar":["portuguese"],"aquecer":["portuguese"],"arame":["portuguese"],"aranha":["portuguese"],"arara":["portuguese"],"arcada":["portuguese"],"ardente":["portuguese"],"areia":["portuguese"],"arejar":["portuguese"],"arenito":["portuguese"],"aresta":["portuguese"],"argiloso":["portuguese"],"argola":["portuguese"],"arma":["portuguese"],"arquivo":["portuguese"],"arraial":["portuguese"],"arrebate":["portuguese"],"arriscar":["portuguese"],"arroba":["portuguese"],"arrumar":["portuguese"],"arsenal":["portuguese"],"arterial":["portuguese"],"artigo":["portuguese"],"arvoredo":["portuguese"],"asfaltar":["portuguese"],"asilado":["portuguese"],"aspirar":["portuguese"],"assador":["portuguese"],"assinar":["portuguese"],"assoalho":["portuguese"],"assunto":["portuguese"],"astral":["portuguese"],"atacado":["portuguese"],"atadura":["portuguese"],"atalho":["portuguese"],"atarefar":["portuguese"],"atear":["portuguese"],"atender":["portuguese"],"aterro":["portuguese"],"ateu":["portuguese"],"atingir":["portuguese"],"atirador":["portuguese"],"ativo":["portuguese"],"atoleiro":["portuguese"],"atracar":["portuguese"],"atrevido":["portuguese"],"atriz":["portuguese"],"atual":["portuguese"],"atum":["portuguese"],"auditor":["portuguese"],"aumentar":["portuguese"],"aura":["portuguese"],"aurora":["portuguese"],"autismo":["portuguese"],"autoria":["portuguese"],"autuar":["portuguese"],"avaliar":["portuguese"],"avante":["portuguese"],"avaria":["portuguese"],"avental":["portuguese"],"avesso":["portuguese"],"aviador":["portuguese"],"avisar":["portuguese"],"avulso":["portuguese"],"axila":["portuguese"],"azarar":["portuguese"],"azedo":["portuguese"],"azeite":["portuguese"],"azulejo":["portuguese"],"babar":["portuguese"],"babosa":["portuguese"],"bacalhau":["portuguese"],"bacharel":["portuguese"],"bacia":["portuguese"],"bagagem":["portuguese"],"baiano":["portuguese"],"bailar":["portuguese"],"baioneta":["portuguese"],"bairro":["portuguese"],"baixista":["portuguese"],"bajular":["portuguese"],"baleia":["portuguese"],"baliza":["portuguese"],"balsa":["portuguese"],"banal":["portuguese"],"bandeira":["portuguese"],"banho":["portuguese"],"banir":["portuguese"],"banquete":["portuguese"],"barato":["portuguese"],"barbado":["portuguese"],"baronesa":["portuguese"],"barraca":["portuguese"],"barulho":["portuguese"],"baseado":["portuguese"],"bastante":["portuguese"],"batata":["portuguese"],"batedor":["portuguese"],"batida":["portuguese"],"batom":["portuguese"],"batucar":["portuguese"],"baunilha":["portuguese"],"beber":["portuguese"],"beijo":["portuguese"],"beirada":["portuguese"],"beisebol":["portuguese"],"beldade":["portuguese"],"beleza":["portuguese"],"belga":["portuguese"],"beliscar":["portuguese"],"bendito":["portuguese"],"bengala":["portuguese"],"benzer":["portuguese","turkish"],"berimbau":["portuguese"],"berlinda":["portuguese"],"berro":["portuguese"],"besouro":["portuguese"],"bexiga":["portuguese"],"bezerro":["portuguese"],"bico":["portuguese"],"bicudo":["portuguese"],"bienal":["portuguese"],"bifocal":["portuguese"],"bifurcar":["portuguese"],"bigorna":["portuguese"],"bilhete":["portuguese"],"bimestre":["portuguese"],"bimotor":["portuguese"],"biologia":["portuguese"],"biombo":["portuguese"],"biosfera":["portuguese"],"bipolar":["portuguese"],"birrento":["portuguese"],"biscoito":["portuguese"],"bisneto":["portuguese"],"bispo":["portuguese"],"bissexto":["portuguese"],"bitola":["portuguese"],"bizarro":["portuguese"],"blindado":["portuguese"],"bloco":["portuguese"],"bloquear":["portuguese"],"boato":["portuguese"],"bobagem":["portuguese"],"bocado":["portuguese"],"bocejo":["portuguese"],"bochecha":["portuguese"],"boicotar":["portuguese"],"bolada":["portuguese"],"boletim":["portuguese"],"bolha":["portuguese"],"bolo":["portuguese"],"bombeiro":["portuguese"],"bonde":["portuguese"],"boneco":["portuguese"],"bonita":["portuguese"],"borbulha":["portuguese"],"borda":["portuguese"],"boreal":["portuguese"],"borracha":["portuguese"],"bovino":["portuguese"],"boxeador":["portuguese"],"branco":["portuguese"],"brasa":["portuguese"],"braveza":["portuguese"],"breu":["portuguese"],"briga":["portuguese"],"brilho":["portuguese"],"brincar":["portuguese"],"broa":["portuguese"],"brochura":["portuguese"],"bronzear":["portuguese"],"broto":["portuguese"],"bruxo":["portuguese"],"bucha":["portuguese"],"budismo":["portuguese"],"bufar":["portuguese"],"bule":["portuguese"],"buraco":["portuguese"],"busca":["portuguese"],"busto":["portuguese"],"buzina":["portuguese"],"cabana":["portuguese"],"cabelo":["portuguese"],"cabide":["portuguese"],"cabo":["portuguese"],"cabrito":["portuguese"],"cacau":["portuguese"],"cacetada":["portuguese"],"cachorro":["portuguese"],"cacique":["portuguese"],"cadastro":["portuguese"],"cadeado":["portuguese"],"cafezal":["portuguese"],"caiaque":["portuguese"],"caipira":["portuguese"],"caixote":["portuguese"],"cajado":["portuguese"],"caju":["portuguese"],"calafrio":["portuguese"],"calcular":["portuguese"],"caldeira":["portuguese"],"calibrar":["portuguese"],"calmante":["portuguese"],"calota":["portuguese"],"camada":["portuguese"],"cambista":["portuguese"],"camisa":["portuguese"],"camomila":["portuguese"],"campanha":["portuguese"],"camuflar":["portuguese"],"canavial":["portuguese"],"cancelar":["portuguese"],"caneta":["portuguese"],"canguru":["portuguese"],"canhoto":["portuguese"],"canivete":["portuguese"],"canoa":["portuguese"],"cansado":["portuguese"],"cantar":["portuguese"],"canudo":["portuguese"],"capacho":["portuguese"],"capela":["portuguese"],"capinar":["portuguese"],"capotar":["portuguese"],"capricho":["portuguese"],"captador":["portuguese"],"capuz":["portuguese"],"caracol":["portuguese"],"carbono":["portuguese"],"cardeal":["portuguese"],"careca":["portuguese"],"carimbar":["portuguese"],"carneiro":["portuguese"],"carpete":["portuguese"],"carreira":["portuguese"],"cartaz":["portuguese"],"carvalho":["portuguese"],"casaco":["portuguese"],"casca":["portuguese"],"casebre":["portuguese"],"castelo":["portuguese"],"casulo":["portuguese"],"catarata":["portuguese"],"cativar":["portuguese"],"caule":["portuguese"],"causador":["portuguese"],"cautelar":["portuguese"],"cavalo":["portuguese"],"caverna":["portuguese"],"cebola":["portuguese"],"cedilha":["portuguese"],"cegonha":["portuguese"],"celebrar":["portuguese"],"celular":["portuguese"],"cenoura":["portuguese"],"censo":["portuguese"],"centeio":["portuguese"],"cercar":["portuguese"],"cerrado":["portuguese"],"certeiro":["portuguese"],"cerveja":["portuguese"],"cetim":["portuguese"],"cevada":["portuguese"],"chacota":["portuguese"],"chaleira":["portuguese"],"chamado":["portuguese"],"chapada":["portuguese"],"charme":["portuguese"],"chatice":["portuguese"],"chave":["portuguese"],"chefe":["portuguese"],"chegada":["portuguese"],"cheiro":["portuguese"],"cheque":["portuguese"],"chicote":["portuguese"],"chifre":["portuguese"],"chinelo":["portuguese"],"chocalho":["portuguese"],"chover":["portuguese"],"chumbo":["portuguese"],"chutar":["portuguese"],"chuva":["portuguese"],"cicatriz":["portuguese"],"ciclone":["portuguese"],"cidade":["portuguese"],"cidreira":["portuguese"],"ciente":["portuguese"],"cigana":["portuguese"],"cimento":["portuguese"],"cinto":["portuguese"],"cinza":["portuguese"],"ciranda":["portuguese"],"circuito":["portuguese"],"cirurgia":["portuguese"],"citar":["portuguese"],"clareza":["portuguese"],"clero":["portuguese"],"clicar":["portuguese"],"clone":["portuguese"],"clube":["portuguese"],"coado":["portuguese"],"coagir":["portuguese"],"cobaia":["portuguese"],"cobertor":["portuguese"],"cobrar":["portuguese"],"cocada":["portuguese"],"coelho":["portuguese"],"coentro":["portuguese"],"coeso":["portuguese"],"cogumelo":["portuguese"],"coibir":["portuguese"],"coifa":["portuguese"],"coiote":["portuguese"],"colar":["portuguese"],"coleira":["portuguese"],"colher":["portuguese"],"colidir":["portuguese"],"colmeia":["portuguese"],"colono":["portuguese"],"coluna":["portuguese"],"comando":["portuguese"],"combinar":["portuguese"],"comentar":["portuguese"],"comitiva":["portuguese"],"comover":["portuguese"],"complexo":["portuguese"],"comum":["portuguese"],"concha":["portuguese"],"condor":["portuguese"],"conectar":["portuguese"],"confuso":["portuguese"],"congelar":["portuguese"],"conhecer":["portuguese"],"conjugar":["portuguese"],"consumir":["portuguese"],"contrato":["portuguese"],"convite":["portuguese"],"cooperar":["portuguese"],"copeiro":["portuguese"],"copiador":["portuguese"],"copo":["portuguese"],"coquetel":["portuguese"],"coragem":["portuguese"],"cordial":["portuguese"],"corneta":["portuguese"],"coronha":["portuguese"],"corporal":["portuguese"],"correio":["portuguese"],"cortejo":["portuguese"],"coruja":["portuguese"],"corvo":["portuguese"],"cosseno":["portuguese"],"costela":["portuguese"],"cotonete":["portuguese"],"couro":["portuguese"],"couve":["portuguese"],"covil":["portuguese"],"cozinha":["portuguese"],"cratera":["portuguese"],"cravo":["portuguese"],"creche":["portuguese"],"credor":["portuguese"],"creme":["portuguese"],"crer":["portuguese"],"crespo":["portuguese"],"criada":["portuguese"],"criminal":["portuguese"],"crioulo":["portuguese"],"crise":["portuguese"],"criticar":["portuguese"],"crosta":["portuguese"],"crua":["portuguese"],"cruzeiro":["portuguese"],"cubano":["portuguese"],"cueca":["portuguese"],"cuidado":["portuguese"],"cujo":["portuguese"],"culatra":["portuguese"],"culminar":["portuguese"],"culpar":["portuguese"],"cultura":["portuguese"],"cumprir":["portuguese"],"cunhado":["portuguese"],"cupido":["portuguese"],"curativo":["portuguese"],"curral":["portuguese"],"cursar":["portuguese"],"curto":["portuguese"],"cuspir":["portuguese"],"custear":["portuguese"],"cutelo":["portuguese"],"damasco":["portuguese"],"datar":["portuguese"],"debater":["portuguese"],"debitar":["portuguese"],"deboche":["portuguese"],"debulhar":["portuguese"],"decalque":["portuguese"],"decimal":["portuguese"],"declive":["portuguese"],"decote":["portuguese"],"decretar":["portuguese"],"dedal":["portuguese"],"dedicado":["portuguese"],"deduzir":["portuguese"],"defesa":["portuguese"],"defumar":["portuguese"],"degelo":["portuguese"],"degrau":["portuguese"],"degustar":["portuguese"],"deitado":["portuguese"],"deixar":["portuguese"],"delator":["portuguese"],"delegado":["portuguese"],"delinear":["portuguese"],"delonga":["portuguese"],"demanda":["portuguese"],"demitir":["portuguese"],"demolido":["portuguese"],"dentista":["portuguese"],"depenado":["portuguese"],"depilar":["portuguese"],"depois":["portuguese"],"depressa":["portuguese"],"depurar":["portuguese"],"deriva":["portuguese"],"derramar":["portuguese"],"desafio":["portuguese"],"desbotar":["portuguese"],"descanso":["portuguese"],"desenho":["portuguese"],"desfiado":["portuguese"],"desgaste":["portuguese"],"desigual":["portuguese"],"deslize":["portuguese"],"desmamar":["portuguese"],"desova":["portuguese"],"despesa":["portuguese"],"destaque":["portuguese"],"desviar":["portuguese"],"detalhar":["portuguese"],"detentor":["portuguese"],"detonar":["portuguese"],"detrito":["portuguese"],"deusa":["portuguese"],"dever":["portuguese"],"devido":["portuguese"],"devotado":["portuguese"],"dezena":["portuguese"],"diagrama":["portuguese"],"dialeto":["portuguese"],"didata":["portuguese"],"difuso":["portuguese"],"digitar":["portuguese"],"dilatado":["portuguese"],"diluente":["portuguese"],"diminuir":["portuguese"],"dinastia":["portuguese"],"dinheiro":["portuguese"],"diocese":["portuguese"],"direto":["portuguese"],"discreta":["portuguese"],"disfarce":["portuguese"],"disparo":["portuguese"],"disquete":["portuguese"],"dissipar":["portuguese"],"distante":["portuguese"],"ditador":["portuguese"],"diurno":["portuguese"],"diverso":["portuguese"],"divisor":["portuguese"],"divulgar":["portuguese"],"dizer":["portuguese"],"dobrador":["portuguese"],"dolorido":["portuguese"],"domador":["portuguese"],"dominado":["portuguese"],"donativo":["portuguese"],"donzela":["portuguese"],"dormente":["portuguese"],"dorsal":["portuguese"],"dosagem":["portuguese"],"dourado":["portuguese"],"doutor":["portuguese"],"drenagem":["portuguese"],"drible":["portuguese"],"drogaria":["portuguese"],"duelar":["portuguese"],"duende":["portuguese"],"dueto":["portuguese"],"duplo":["portuguese"],"duquesa":["portuguese"],"durante":["portuguese"],"duvidoso":["portuguese"],"eclodir":["portuguese"],"ecoar":["portuguese"],"ecologia":["portuguese"],"edificar":["portuguese"],"edital":["portuguese"],"educado":["portuguese"],"efeito":["portuguese"],"efetivar":["portuguese"],"ejetar":["portuguese"],"elaborar":["portuguese"],"eleger":["portuguese"],"eleitor":["portuguese"],"elenco":["portuguese"],"elevador":["portuguese"],"eliminar":["portuguese"],"elogiar":["portuguese"],"embargo":["portuguese"],"embolado":["portuguese"],"embrulho":["portuguese"],"embutido":["portuguese"],"emenda":["portuguese"],"emergir":["portuguese"],"emissor":["portuguese"],"empatia":["portuguese"],"empenho":["portuguese"],"empinado":["portuguese"],"empolgar":["portuguese"],"emprego":["portuguese"],"empurrar":["portuguese"],"emulador":["portuguese"],"encaixe":["portuguese"],"encenado":["portuguese"],"enchente":["portuguese"],"encontro":["portuguese"],"endeusar":["portuguese"],"endossar":["portuguese"],"enfaixar":["portuguese"],"enfeite":["portuguese"],"enfim":["portuguese"],"engajado":["portuguese"],"engenho":["portuguese"],"englobar":["portuguese"],"engomado":["portuguese"],"engraxar":["portuguese"],"enguia":["portuguese"],"enjoar":["portuguese"],"enlatar":["portuguese"],"enquanto":["portuguese"],"enraizar":["portuguese"],"enrolado":["portuguese"],"enrugar":["portuguese"],"ensaio":["portuguese"],"enseada":["portuguese"],"ensino":["portuguese"],"ensopado":["portuguese"],"entanto":["portuguese"],"enteado":["portuguese"],"entidade":["portuguese"],"entortar":["portuguese"],"entrada":["portuguese"],"entulho":["portuguese"],"envergar":["portuguese"],"enviado":["portuguese"],"envolver":["portuguese"],"enxame":["portuguese"],"enxerto":["portuguese"],"enxofre":["portuguese"],"enxuto":["portuguese"],"epiderme":["portuguese"],"equipar":["portuguese"],"ereto":["portuguese"],"erguido":["portuguese"],"errata":["portuguese"],"erva":["portuguese"],"ervilha":["portuguese"],"esbanjar":["portuguese"],"esbelto":["portuguese"],"escama":["portuguese"],"escola":["portuguese"],"escrita":["portuguese"],"escuta":["portuguese"],"esfinge":["portuguese"],"esfolar":["portuguese"],"esfregar":["portuguese"],"esfumado":["portuguese"],"esgrima":["portuguese"],"esmalte":["portuguese"],"espanto":["portuguese"],"espelho":["portuguese"],"espiga":["portuguese"],"esponja":["portuguese"],"espreita":["portuguese"],"espumar":["portuguese"],"esquerda":["portuguese"],"estaca":["portuguese"],"esteira":["portuguese"],"esticar":["portuguese"],"estofado":["portuguese"],"estrela":["portuguese"],"estudo":["portuguese"],"esvaziar":["portuguese"],"etanol":["portuguese"],"etiqueta":["portuguese"],"euforia":["portuguese"],"europeu":["portuguese"],"evacuar":["portuguese"],"evaporar":["portuguese"],"evasivo":["portuguese"],"eventual":["portuguese"],"evidente":["portuguese"],"evoluir":["portuguese"],"exagero":["portuguese"],"exalar":["portuguese"],"examinar":["portuguese"],"exato":["portuguese"],"exausto":["portuguese"],"excesso":["portuguese"],"excitar":["portuguese"],"exclamar":["portuguese"],"executar":["portuguese"],"exemplo":["portuguese"],"exibir":["portuguese"],"exigente":["portuguese"],"exonerar":["portuguese"],"expandir":["portuguese"],"expelir":["portuguese"],"expirar":["portuguese"],"explanar":["portuguese"],"exposto":["portuguese"],"expresso":["portuguese"],"expulsar":["portuguese"],"externo":["portuguese"],"extinto":["portuguese"],"extrato":["portuguese"],"fabricar":["portuguese"],"fabuloso":["portuguese"],"faceta":["portuguese"],"facial":["portuguese"],"fada":["portuguese"],"fadiga":["portuguese"],"faixa":["portuguese"],"falar":["portuguese"],"falta":["portuguese"],"familiar":["portuguese"],"fandango":["portuguese"],"fanfarra":["portuguese"],"fantoche":["portuguese"],"fardado":["portuguese"],"farelo":["portuguese"],"farinha":["portuguese"],"farofa":["portuguese"],"farpa":["portuguese"],"fartura":["portuguese"],"fatia":["portuguese"],"fator":["portuguese"],"favorita":["portuguese"],"faxina":["portuguese"],"fazenda":["portuguese"],"fechado":["portuguese"],"feijoada":["portuguese"],"feirante":["portuguese"],"felino":["portuguese"],"feminino":["portuguese"],"fenda":["portuguese"],"feno":["portuguese"],"fera":["portuguese"],"feriado":["portuguese"],"ferrugem":["portuguese"],"ferver":["portuguese"],"festejar":["portuguese"],"fetal":["portuguese"],"feudal":["portuguese"],"fiapo":["portuguese"],"fibrose":["portuguese"],"ficar":["portuguese"],"ficheiro":["portuguese"],"figurado":["portuguese"],"fileira":["portuguese"],"filho":["portuguese"],"filme":["portuguese"],"filtrar":["portuguese"],"firmeza":["portuguese"],"fisgada":["portuguese"],"fissura":["portuguese"],"fita":["portuguese"],"fivela":["portuguese"],"fixador":["portuguese"],"fixo":["portuguese"],"flacidez":["portuguese"],"flamingo":["portuguese"],"flanela":["portuguese"],"flechada":["portuguese"],"flora":["portuguese"],"flutuar":["portuguese"],"fluxo":["portuguese"],"focal":["portuguese"],"focinho":["portuguese"],"fofocar":["portuguese"],"fogo":["portuguese"],"foguete":["portuguese"],"foice":["portuguese"],"folgado":["portuguese"],"folheto":["portuguese"],"forjar":["portuguese"],"formiga":["portuguese"],"forno":["portuguese"],"forte":["portuguese"],"fosco":["portuguese"],"fossa":["portuguese"],"fragata":["portuguese"],"fralda":["portuguese"],"frango":["portuguese"],"frasco":["portuguese"],"fraterno":["portuguese"],"freira":["portuguese"],"frente":["portuguese"],"fretar":["portuguese"],"frieza":["portuguese"],"friso":["portuguese"],"fritura":["portuguese"],"fronha":["portuguese"],"frustrar":["portuguese"],"fruteira":["portuguese"],"fugir":["portuguese"],"fulano":["portuguese"],"fuligem":["portuguese"],"fundar":["portuguese"],"fungo":["portuguese"],"funil":["portuguese"],"furador":["portuguese"],"furioso":["portuguese"],"futebol":["portuguese"],"gabarito":["portuguese"],"gabinete":["portuguese"],"gado":["portuguese"],"gaiato":["portuguese"],"gaiola":["portuguese"],"gaivota":["portuguese"],"galega":["portuguese"],"galho":["portuguese"],"galinha":["portuguese"],"galocha":["portuguese"],"ganhar":["portuguese"],"garagem":["portuguese"],"garfo":["portuguese"],"gargalo":["portuguese"],"garimpo":["portuguese"],"garoupa":["portuguese"],"garrafa":["portuguese"],"gasoduto":["portuguese"],"gasto":["portuguese"],"gata":["portuguese"],"gatilho":["portuguese"],"gaveta":["portuguese"],"gazela":["portuguese"],"gelado":["portuguese"],"geleia":["portuguese"],"gelo":["portuguese"],"gemada":["portuguese"],"gemer":["portuguese"],"gemido":["portuguese"],"generoso":["portuguese"],"gengiva":["portuguese"],"genial":["portuguese"],"genoma":["portuguese"],"genro":["portuguese"],"geologia":["portuguese"],"gerador":["portuguese"],"germinar":["portuguese"],"gesso":["portuguese"],"gestor":["portuguese"],"ginasta":["portuguese"],"gincana":["portuguese"],"gingado":["portuguese"],"girafa":["portuguese"],"girino":["portuguese"],"glacial":["portuguese"],"glicose":["portuguese"],"global":["portuguese"],"glorioso":["portuguese"],"goela":["portuguese"],"goiaba":["portuguese"],"golfe":["portuguese"],"golpear":["portuguese"],"gordura":["portuguese"],"gorjeta":["portuguese"],"gorro":["portuguese"],"gostoso":["portuguese"],"goteira":["portuguese"],"governar":["portuguese"],"gracejo":["portuguese"],"gradual":["portuguese"],"grafite":["portuguese"],"gralha":["portuguese"],"grampo":["portuguese"],"granada":["portuguese"],"gratuito":["portuguese"],"graveto":["portuguese"],"graxa":["portuguese"],"grego":["portuguese"],"grelhar":["portuguese"],"greve":["portuguese"],"grilo":["portuguese"],"grisalho":["portuguese"],"gritaria":["portuguese"],"grosso":["portuguese"],"grotesco":["portuguese"],"grudado":["portuguese"],"grunhido":["portuguese"],"gruta":["portuguese"],"guache":["portuguese"],"guarani":["portuguese"],"guaxinim":["portuguese"],"guerrear":["portuguese"],"guiar":["portuguese"],"guincho":["portuguese"],"guisado":["portuguese"],"gula":["portuguese"],"guloso":["portuguese"],"guru":["portuguese"],"habitar":["portuguese"],"harmonia":["portuguese"],"haste":["portuguese"],"haver":["portuguese"],"hectare":["portuguese"],"herdar":["portuguese"],"heresia":["portuguese"],"hesitar":["portuguese"],"hiato":["portuguese"],"hibernar":["portuguese"],"hidratar":["portuguese"],"hiena":["portuguese"],"hino":["portuguese"],"hipismo":["portuguese"],"hipnose":["portuguese"],"hipoteca":["portuguese"],"hoje":["portuguese"],"holofote":["portuguese"],"homem":["portuguese"],"honesto":["portuguese"],"honrado":["portuguese"],"hormonal":["portuguese"],"hospedar":["portuguese"],"humorado":["portuguese"],"iate":["portuguese"],"ideia":["portuguese"],"idoso":["portuguese"],"ignorado":["portuguese"],"igreja":["portuguese"],"iguana":["portuguese"],"ileso":["portuguese"],"ilha":["portuguese"],"iludido":["portuguese"],"iluminar":["portuguese"],"ilustrar":["portuguese"],"imagem":["portuguese"],"imediato":["portuguese"],"imenso":["portuguese"],"imersivo":["portuguese"],"iminente":["portuguese"],"imitador":["portuguese"],"imortal":["portuguese"],"impacto":["portuguese"],"impedir":["portuguese"],"implante":["portuguese"],"impor":["portuguese"],"imprensa":["portuguese"],"impune":["portuguese"],"imunizar":["portuguese"],"inalador":["portuguese"],"inapto":["portuguese"],"inativo":["portuguese"],"incenso":["portuguese"],"inchar":["portuguese"],"incidir":["portuguese"],"incluir":["portuguese"],"incolor":["portuguese"],"indeciso":["portuguese"],"indireto":["portuguese"],"indutor":["portuguese"],"ineficaz":["portuguese"],"inerente":["portuguese"],"infantil":["portuguese"],"infestar":["portuguese"],"infinito":["portuguese"],"inflamar":["portuguese"],"informal":["portuguese"],"infrator":["portuguese"],"ingerir":["portuguese"],"inibido":["portuguese"],"inicial":["portuguese"],"inimigo":["portuguese"],"injetar":["portuguese"],"inocente":["portuguese"],"inodoro":["portuguese"],"inovador":["portuguese"],"inox":["portuguese"],"inquieto":["portuguese"],"inscrito":["portuguese"],"inseto":["portuguese"],"insistir":["portuguese"],"inspetor":["portuguese"],"instalar":["portuguese"],"insulto":["portuguese"],"intacto":["portuguese"],"integral":["portuguese"],"intimar":["portuguese"],"intocado":["portuguese"],"intriga":["portuguese"],"invasor":["portuguese"],"inverno":["portuguese"],"invicto":["portuguese"],"invocar":["portuguese"],"iogurte":["portuguese"],"iraniano":["portuguese"],"ironizar":["portuguese"],"irreal":["portuguese"],"irritado":["portuguese"],"isca":["portuguese"],"isento":["portuguese"],"isolado":["portuguese"],"isqueiro":["portuguese"],"italiano":["portuguese"],"janeiro":["portuguese"],"jangada":["portuguese"],"janta":["portuguese"],"jararaca":["portuguese"],"jardim":["portuguese"],"jarro":["portuguese"],"jasmim":["portuguese"],"jato":["portuguese"],"javali":["portuguese"],"jazida":["portuguese"],"jejum":["portuguese"],"joaninha":["portuguese"],"joelhada":["portuguese"],"jogador":["portuguese"],"joia":["portuguese"],"jornal":["portuguese"],"jorrar":["portuguese"],"jovem":["portuguese"],"juba":["portuguese"],"judeu":["portuguese"],"judoca":["portuguese"],"juiz":["portuguese"],"julgador":["portuguese"],"julho":["portuguese"],"jurado":["portuguese"],"jurista":["portuguese"],"juro":["portuguese"],"justa":["portuguese"],"labareda":["portuguese"],"laboral":["portuguese"],"lacre":["portuguese"],"lactante":["portuguese"],"ladrilho":["portuguese"],"lagarta":["portuguese"],"lagoa":["portuguese"],"laje":["portuguese"],"lamber":["portuguese"],"lamentar":["portuguese"],"laminar":["portuguese"],"lampejo":["portuguese"],"lanche":["portuguese"],"lapidar":["portuguese"],"lapso":["portuguese"],"laranja":["portuguese"],"lareira":["portuguese"],"largura":["portuguese"],"lasanha":["portuguese"],"lastro":["portuguese"],"lateral":["portuguese"],"latido":["portuguese"],"lavanda":["portuguese"],"lavoura":["portuguese"],"lavrador":["portuguese"],"laxante":["portuguese"],"lazer":["portuguese"],"lealdade":["portuguese"],"lebre":["portuguese"],"legado":["portuguese"],"legendar":["portuguese"],"legista":["portuguese"],"leigo":["portuguese"],"leiloar":["portuguese"],"leitura":["portuguese"],"lembrete":["portuguese"],"leme":["portuguese"],"lenhador":["portuguese"],"lentilha":["portuguese"],"leoa":["portuguese"],"lesma":["portuguese"],"leste":["portuguese"],"letivo":["portuguese"],"letreiro":["portuguese"],"levar":["portuguese"],"leveza":["portuguese"],"levitar":["portuguese"],"liberal":["portuguese"],"libido":["portuguese"],"liderar":["portuguese"],"ligar":["portuguese"],"ligeiro":["portuguese"],"limitar":["portuguese"],"limoeiro":["portuguese"],"limpador":["portuguese"],"linda":["portuguese"],"linear":["portuguese"],"linhagem":["portuguese"],"liquidez":["portuguese"],"listagem":["portuguese"],"lisura":["portuguese"],"litoral":["portuguese"],"livro":["portuguese"],"lixa":["portuguese"],"lixeira":["portuguese"],"locador":["portuguese"],"locutor":["portuguese"],"lojista":["portuguese"],"lombo":["portuguese"],"lona":["portuguese"],"longe":["portuguese"],"lontra":["portuguese"],"lorde":["portuguese"],"lotado":["portuguese"],"loteria":["portuguese"],"loucura":["portuguese"],"lousa":["portuguese"],"louvar":["portuguese"],"luar":["portuguese"],"lucidez":["portuguese"],"lucro":["portuguese"],"luneta":["portuguese"],"lustre":["portuguese"],"lutador":["portuguese"],"luva":["portuguese"],"macaco":["portuguese"],"macete":["portuguese"],"machado":["portuguese"],"macio":["portuguese"],"madeira":["portuguese"],"madrinha":["portuguese"],"magnata":["portuguese"],"magreza":["portuguese"],"maior":["portuguese"],"mais":["portuguese"],"malandro":["portuguese"],"malha":["portuguese"],"malote":["portuguese"],"maluco":["portuguese"],"mamilo":["portuguese"],"mamoeiro":["portuguese"],"mamute":["portuguese"],"manada":["portuguese"],"mancha":["portuguese"],"mandato":["portuguese"],"manequim":["portuguese"],"manhoso":["portuguese"],"manivela":["portuguese"],"manobrar":["portuguese"],"mansa":["portuguese"],"manter":["portuguese"],"manusear":["portuguese"],"mapeado":["portuguese"],"maquinar":["portuguese"],"marcador":["portuguese"],"maresia":["portuguese"],"marfim":["portuguese"],"margem":["portuguese"],"marinho":["portuguese"],"marmita":["portuguese"],"maroto":["portuguese"],"marquise":["portuguese"],"marreco":["portuguese"],"martelo":["portuguese"],"marujo":["portuguese"],"mascote":["portuguese"],"masmorra":["portuguese"],"massagem":["portuguese"],"mastigar":["portuguese"],"matagal":["portuguese"],"materno":["portuguese"],"matinal":["portuguese"],"matutar":["portuguese"],"maxilar":["portuguese"],"medalha":["portuguese"],"medida":["portuguese"],"medusa":["portuguese"],"megafone":["portuguese"],"meiga":["portuguese"],"melancia":["portuguese"],"melhor":["portuguese"],"membro":["portuguese"],"memorial":["portuguese"],"menino":["portuguese"],"menos":["portuguese"],"mensagem":["portuguese"],"mental":["portuguese"],"merecer":["portuguese"],"mergulho":["portuguese"],"mesada":["portuguese"],"mesclar":["portuguese"],"mesmo":["portuguese"],"mesquita":["portuguese"],"mestre":["portuguese"],"metade":["portuguese"],"meteoro":["portuguese"],"metragem":["portuguese"],"mexer":["portuguese"],"mexicano":["portuguese"],"micro":["portuguese"],"migalha":["portuguese"],"migrar":["portuguese"],"milagre":["portuguese"],"milenar":["portuguese"],"milhar":["portuguese"],"mimado":["portuguese"],"minerar":["portuguese"],"minhoca":["portuguese"],"ministro":["portuguese"],"minoria":["portuguese"],"miolo":["portuguese"],"mirante":["portuguese"],"mirtilo":["portuguese"],"misturar":["portuguese"],"mocidade":["portuguese"],"moderno":["portuguese"],"modular":["portuguese"],"moeda":["portuguese"],"moer":["portuguese"],"moinho":["portuguese"],"moita":["portuguese"],"moldura":["portuguese"],"moleza":["portuguese"],"molho":["portuguese"],"molinete":["portuguese"],"molusco":["portuguese"],"montanha":["portuguese"],"moqueca":["portuguese"],"morango":["portuguese"],"morcego":["portuguese"],"mordomo":["portuguese"],"morena":["portuguese"],"mosaico":["portuguese"],"mosquete":["portuguese"],"mostarda":["portuguese"],"motel":["portuguese"],"motim":["portuguese"],"moto":["portuguese"],"motriz":["portuguese"],"muda":["portuguese"],"muito":["portuguese"],"mulata":["portuguese"],"mulher":["portuguese"],"multar":["portuguese"],"mundial":["portuguese"],"munido":["portuguese"],"muralha":["portuguese"],"murcho":["portuguese"],"muscular":["portuguese"],"museu":["portuguese"],"musical":["portuguese"],"nacional":["portuguese"],"nadador":["portuguese"],"naja":["portuguese"],"namoro":["portuguese"],"narina":["portuguese"],"narrado":["portuguese"],"nascer":["portuguese"],"nativa":["portuguese"],"natureza":["portuguese"],"navalha":["portuguese"],"navegar":["portuguese"],"navio":["portuguese"],"neblina":["portuguese"],"nebuloso":["portuguese"],"negativa":["portuguese"],"negociar":["portuguese"],"negrito":["portuguese"],"nervoso":["portuguese"],"neta":["portuguese"],"neural":["portuguese"],"nevasca":["portuguese"],"nevoeiro":["portuguese"],"ninar":["portuguese"],"ninho":["portuguese"],"nitidez":["portuguese"],"nivelar":["portuguese"],"nobreza":["portuguese"],"noite":["portuguese"],"noiva":["portuguese"],"nomear":["portuguese"],"nominal":["portuguese"],"nordeste":["portuguese"],"nortear":["portuguese"],"notar":["portuguese"],"noticiar":["portuguese"],"noturno":["portuguese"],"novelo":["portuguese"],"novilho":["portuguese"],"novo":["portuguese"],"nublado":["portuguese"],"nudez":["portuguese"],"numeral":["portuguese"],"nupcial":["portuguese"],"nutrir":["portuguese"],"nuvem":["portuguese"],"obcecado":["portuguese"],"obedecer":["portuguese"],"objetivo":["portuguese"],"obrigado":["portuguese"],"obscuro":["portuguese"],"obstetra":["portuguese"],"obter":["portuguese"],"obturar":["portuguese"],"ocidente":["portuguese"],"ocioso":["portuguese"],"ocorrer":["portuguese"],"oculista":["portuguese"],"ocupado":["portuguese"],"ofegante":["portuguese"],"ofensiva":["portuguese"],"oferenda":["portuguese"],"oficina":["portuguese"],"ofuscado":["portuguese"],"ogiva":["portuguese"],"olaria":["portuguese"],"oleoso":["portuguese"],"olhar":["portuguese"],"oliveira":["portuguese"],"ombro":["portuguese"],"omelete":["portuguese"],"omisso":["portuguese"],"omitir":["portuguese"],"ondulado":["portuguese"],"oneroso":["portuguese"],"ontem":["portuguese"],"opcional":["portuguese"],"operador":["portuguese"],"oponente":["portuguese"],"oportuno":["portuguese"],"oposto":["portuguese"],"orar":["portuguese"],"orbitar":["portuguese"],"ordem":["portuguese"],"ordinal":["portuguese"],"orfanato":["portuguese"],"orgasmo":["portuguese"],"orgulho":["portuguese"],"oriental":["portuguese"],"origem":["portuguese"],"oriundo":["portuguese"],"orla":["portuguese"],"ortodoxo":["portuguese"],"orvalho":["portuguese"],"oscilar":["portuguese"],"ossada":["portuguese"],"osso":["portuguese"],"ostentar":["portuguese"],"otimismo":["portuguese"],"ousadia":["portuguese"],"outono":["portuguese"],"outubro":["portuguese"],"ouvido":["portuguese"],"ovelha":["portuguese"],"ovular":["portuguese"],"oxidar":["portuguese"],"oxigenar":["portuguese"],"pacato":["portuguese"],"paciente":["portuguese"],"pacote":["portuguese"],"pactuar":["portuguese"],"padaria":["portuguese"],"padrinho":["portuguese"],"pagar":["portuguese"],"pagode":["portuguese"],"painel":["portuguese"],"pairar":["portuguese"],"paisagem":["portuguese"],"palavra":["portuguese"],"palestra":["portuguese"],"palheta":["portuguese"],"palito":["portuguese"],"palmada":["portuguese"],"palpitar":["portuguese"],"pancada":["portuguese"],"panela":["portuguese"],"panfleto":["portuguese"],"panqueca":["portuguese"],"pantanal":["portuguese"],"papagaio":["portuguese"],"papelada":["portuguese"],"papiro":["portuguese"],"parafina":["portuguese"],"parcial":["portuguese"],"pardal":["portuguese"],"parede":["portuguese"],"partida":["portuguese"],"pasmo":["portuguese"],"passado":["portuguese"],"pastel":["portuguese"],"patamar":["portuguese"],"patente":["portuguese"],"patinar":["portuguese"],"patrono":["portuguese"],"paulada":["portuguese"],"pausar":["portuguese"],"peculiar":["portuguese"],"pedalar":["portuguese"],"pedestre":["portuguese"],"pediatra":["portuguese"],"pedra":["portuguese"],"pegada":["portuguese"],"peitoral":["portuguese"],"peixe":["portuguese"],"pele":["portuguese"],"pelicano":["portuguese"],"penca":["portuguese"],"pendurar":["portuguese"],"peneira":["portuguese"],"penhasco":["portuguese"],"pensador":["portuguese"],"pente":["portuguese"],"perceber":["portuguese"],"perfeito":["portuguese"],"pergunta":["portuguese"],"perito":["portuguese"],"permitir":["portuguese"],"perna":["portuguese"],"perplexo":["portuguese"],"persiana":["portuguese"],"pertence":["portuguese"],"peruca":["portuguese"],"pescado":["portuguese"],"pesquisa":["portuguese"],"pessoa":["portuguese"],"petiscar":["portuguese"],"piada":["portuguese"],"picado":["portuguese"],"piedade":["portuguese"],"pigmento":["portuguese"],"pilastra":["portuguese"],"pilhado":["portuguese"],"pilotar":["portuguese"],"pimenta":["portuguese"],"pincel":["portuguese"],"pinguim":["portuguese"],"pinha":["portuguese"],"pinote":["portuguese"],"pintar":["portuguese"],"pioneiro":["portuguese"],"pipoca":["portuguese"],"piquete":["portuguese"],"piranha":["portuguese"],"pires":["portuguese"],"pirueta":["portuguese"],"piscar":["portuguese"],"pistola":["portuguese"],"pitanga":["portuguese"],"pivete":["portuguese"],"planta":["portuguese"],"plaqueta":["portuguese"],"platina":["portuguese"],"plebeu":["portuguese"],"plumagem":["portuguese"],"pluvial":["portuguese"],"pneu":["portuguese"],"poda":["portuguese"],"poeira":["portuguese"],"poetisa":["portuguese"],"polegada":["portuguese"],"policiar":["portuguese"],"poluente":["portuguese"],"polvilho":["portuguese"],"pomar":["portuguese"],"pomba":["portuguese"],"ponderar":["portuguese"],"pontaria":["portuguese"],"populoso":["portuguese"],"porta":["portuguese"],"possuir":["portuguese"],"postal":["portuguese"],"pote":["portuguese"],"poupar":["portuguese"],"pouso":["portuguese"],"povoar":["portuguese"],"praia":["portuguese"],"prancha":["portuguese"],"prato":["portuguese"],"praxe":["portuguese"],"prece":["portuguese"],"predador":["portuguese"],"prefeito":["portuguese"],"premiar":["portuguese"],"prensar":["portuguese"],"preparar":["portuguese"],"presilha":["portuguese"],"pretexto":["portuguese"],"prevenir":["portuguese"],"prezar":["portuguese"],"primata":["portuguese"],"princesa":["portuguese"],"prisma":["portuguese"],"privado":["portuguese"],"processo":["portuguese"],"produto":["portuguese"],"profeta":["portuguese"],"proibido":["portuguese"],"projeto":["portuguese"],"prometer":["portuguese"],"propagar":["portuguese"],"prosa":["portuguese"],"protetor":["portuguese"],"provador":["portuguese"],"publicar":["portuguese"],"pudim":["portuguese"],"pular":["portuguese"],"pulmonar":["portuguese"],"pulseira":["portuguese"],"punhal":["portuguese"],"punir":["portuguese"],"pupilo":["portuguese"],"pureza":["portuguese"],"puxador":["portuguese"],"quadra":["portuguese"],"quantia":["portuguese"],"quarto":["portuguese"],"quase":["portuguese"],"quebrar":["portuguese"],"queda":["portuguese"],"queijo":["portuguese"],"quente":["portuguese"],"querido":["portuguese"],"quimono":["portuguese"],"quina":["portuguese"],"quiosque":["portuguese"],"rabanada":["portuguese"],"rabisco":["portuguese"],"rachar":["portuguese"],"racionar":["portuguese"],"radial":["portuguese"],"raiar":["portuguese"],"rainha":["portuguese"],"raio":["portuguese"],"raiva":["portuguese"],"rajada":["portuguese"],"ralado":["portuguese"],"ramal":["portuguese"],"ranger":["portuguese"],"ranhura":["portuguese"],"rapadura":["portuguese"],"rapel":["portuguese"],"rapidez":["portuguese"],"raposa":["portuguese"],"raquete":["portuguese"],"raridade":["portuguese"],"rasante":["portuguese"],"rascunho":["portuguese"],"rasgar":["portuguese"],"raspador":["portuguese"],"rasteira":["portuguese"],"rasurar":["portuguese"],"ratazana":["portuguese"],"ratoeira":["portuguese"],"realeza":["portuguese"],"reanimar":["portuguese"],"reaver":["portuguese"],"rebaixar":["portuguese"],"rebelde":["portuguese"],"rebolar":["portuguese"],"recado":["portuguese"],"recente":["portuguese"],"recheio":["portuguese"],"recibo":["portuguese"],"recordar":["portuguese"],"recrutar":["portuguese"],"recuar":["portuguese"],"rede":["portuguese"],"redimir":["portuguese"],"redonda":["portuguese"],"reduzida":["portuguese"],"reenvio":["portuguese"],"refinar":["portuguese"],"refletir":["portuguese"],"refogar":["portuguese"],"refresco":["portuguese"],"refugiar":["portuguese"],"regalia":["portuguese"],"regime":["portuguese"],"regra":["portuguese"],"reinado":["portuguese"],"reitor":["portuguese"],"rejeitar":["portuguese"],"relativo":["portuguese"],"remador":["portuguese"],"remendo":["portuguese"],"remorso":["portuguese"],"renovado":["portuguese"],"reparo":["portuguese"],"repelir":["portuguese"],"repleto":["portuguese"],"repolho":["portuguese"],"represa":["portuguese"],"repudiar":["portuguese"],"requerer":["portuguese"],"resenha":["portuguese"],"resfriar":["portuguese"],"resgatar":["portuguese"],"residir":["portuguese"],"resolver":["portuguese"],"respeito":["portuguese"],"ressaca":["portuguese"],"restante":["portuguese"],"resumir":["portuguese"],"retalho":["portuguese"],"reter":["portuguese"],"retirar":["portuguese"],"retomada":["portuguese"],"retratar":["portuguese"],"revelar":["portuguese"],"revisor":["portuguese"],"revolta":["portuguese"],"riacho":["portuguese"],"rica":["portuguese"],"rigidez":["portuguese"],"rigoroso":["portuguese"],"rimar":["portuguese"],"ringue":["portuguese"],"risada":["portuguese"],"risco":["portuguese"],"risonho":["portuguese"],"robalo":["portuguese"],"rochedo":["portuguese"],"rodada":["portuguese"],"rodeio":["portuguese"],"rodovia":["portuguese"],"roedor":["portuguese"],"roleta":["portuguese"],"romano":["portuguese"],"roncar":["portuguese"],"rosado":["portuguese"],"roseira":["portuguese"],"rosto":["portuguese"],"rota":["portuguese","turkish"],"roteiro":["portuguese"],"rotina":["portuguese"],"rotular":["portuguese"],"rouco":["portuguese"],"roupa":["portuguese"],"roxo":["portuguese"],"rubro":["portuguese"],"rugido":["portuguese"],"rugoso":["portuguese"],"ruivo":["portuguese"],"rumo":["portuguese"],"rupestre":["portuguese"],"russo":["portuguese"],"sabor":["portuguese"],"saciar":["portuguese"],"sacola":["portuguese"],"sacudir":["portuguese"],"sadio":["portuguese"],"safira":["portuguese"],"saga":["portuguese"],"sagrada":["portuguese"],"saibro":["portuguese"],"salada":["portuguese"],"saleiro":["portuguese"],"salgado":["portuguese"],"saliva":["portuguese"],"salpicar":["portuguese"],"salsicha":["portuguese"],"saltar":["portuguese"],"salvador":["portuguese"],"sambar":["portuguese"],"samurai":["portuguese"],"sanar":["portuguese"],"sanfona":["portuguese"],"sangue":["portuguese"],"sanidade":["portuguese"],"sapato":["portuguese"],"sarda":["portuguese"],"sargento":["portuguese"],"sarjeta":["portuguese"],"saturar":["portuguese"],"saudade":["portuguese"],"saxofone":["portuguese"],"sazonal":["portuguese"],"secar":["portuguese"],"secular":["portuguese"],"seda":["portuguese","turkish"],"sedento":["portuguese"],"sediado":["portuguese"],"sedoso":["portuguese"],"sedutor":["portuguese"],"segmento":["portuguese"],"segredo":["portuguese"],"segundo":["portuguese"],"seiva":["portuguese"],"seleto":["portuguese"],"selvagem":["portuguese"],"semanal":["portuguese"],"semente":["portuguese"],"senador":["portuguese"],"senhor":["portuguese"],"sensual":["portuguese"],"sentado":["portuguese"],"separado":["portuguese"],"sereia":["portuguese"],"seringa":["portuguese"],"serra":["portuguese"],"servo":["portuguese"],"setembro":["portuguese"],"setor":["portuguese"],"sigilo":["portuguese"],"silhueta":["portuguese"],"silicone":["portuguese"],"simetria":["portuguese"],"simpatia":["portuguese"],"simular":["portuguese"],"sinal":["portuguese"],"sincero":["portuguese"],"singular":["portuguese"],"sinopse":["portuguese"],"sintonia":["portuguese"],"sirene":["portuguese"],"siri":["portuguese"],"situado":["portuguese"],"soberano":["portuguese"],"sobra":["portuguese"],"socorro":["portuguese"],"sogro":["portuguese"],"soja":["portuguese"],"solda":["portuguese"],"soletrar":["portuguese"],"solteiro":["portuguese"],"sombrio":["portuguese"],"sonata":["portuguese"],"sondar":["portuguese"],"sonegar":["portuguese"],"sonhador":["portuguese"],"sono":["portuguese"],"soprano":["portuguese"],"soquete":["portuguese"],"sorrir":["portuguese"],"sorteio":["portuguese"],"sossego":["portuguese"],"sotaque":["portuguese"],"soterrar":["portuguese"],"sovado":["portuguese"],"sozinho":["portuguese"],"suavizar":["portuguese"],"subida":["portuguese"],"submerso":["portuguese"],"subsolo":["portuguese"],"subtrair":["portuguese"],"sucata":["portuguese"],"sucesso":["portuguese"],"suco":["portuguese"],"sudeste":["portuguese"],"sufixo":["portuguese"],"sugador":["portuguese"],"sugerir":["portuguese"],"sujeito":["portuguese"],"sulfato":["portuguese"],"sumir":["portuguese"],"suor":["portuguese"],"superior":["portuguese"],"suplicar":["portuguese"],"suposto":["portuguese"],"suprimir":["portuguese"],"surdina":["portuguese"],"surfista":["portuguese"],"surpresa":["portuguese"],"surreal":["portuguese"],"surtir":["portuguese"],"suspiro":["portuguese"],"sustento":["portuguese"],"tabela":["portuguese","turkish"],"tablete":["portuguese"],"tabuada":["portuguese"],"tacho":["portuguese"],"tagarela":["portuguese"],"talher":["portuguese"],"talo":["portuguese"],"talvez":["portuguese"],"tamanho":["portuguese"],"tamborim":["portuguese"],"tampa":["portuguese"],"tangente":["portuguese"],"tanto":["portuguese"],"tapar":["portuguese"],"tapioca":["portuguese"],"tardio":["portuguese"],"tarefa":["portuguese"],"tarja":["portuguese"],"tarraxa":["portuguese"],"tatuagem":["portuguese"],"taurino":["portuguese"],"taxativo":["portuguese"],"taxista":["portuguese"],"teatral":["portuguese"],"tecer":["portuguese"],"tecido":["portuguese"],"teclado":["portuguese"],"tedioso":["portuguese"],"teia":["portuguese"],"teimar":["portuguese"],"telefone":["portuguese"],"telhado":["portuguese"],"tempero":["portuguese"],"tenente":["portuguese"],"tensor":["portuguese"],"tentar":["portuguese"],"termal":["portuguese"],"terno":["portuguese"],"terreno":["portuguese"],"tese":["portuguese"],"tesoura":["portuguese"],"testado":["portuguese"],"teto":["portuguese"],"textura":["portuguese"],"texugo":["portuguese"],"tiara":["portuguese"],"tigela":["portuguese"],"tijolo":["portuguese"],"timbrar":["portuguese"],"timidez":["portuguese"],"tingido":["portuguese"],"tinteiro":["portuguese"],"tiragem":["portuguese"],"titular":["portuguese"],"toalha":["portuguese"],"tocha":["portuguese"],"tolerar":["portuguese"],"tolice":["portuguese"],"tomada":["portuguese"],"tomilho":["portuguese"],"tonel":["portuguese"],"tontura":["portuguese"],"topete":["portuguese"],"tora":["portuguese"],"torcido":["portuguese"],"torneio":["portuguese"],"torque":["portuguese"],"torrada":["portuguese"],"torto":["portuguese"],"tostar":["portuguese"],"touca":["portuguese"],"toupeira":["portuguese"],"toxina":["portuguese"],"trabalho":["portuguese"],"tracejar":["portuguese"],"tradutor":["portuguese"],"trafegar":["portuguese"],"trajeto":["portuguese"],"trama":["portuguese"],"trancar":["portuguese"],"trapo":["portuguese"],"traseiro":["portuguese"],"tratador":["portuguese"],"travar":["portuguese"],"treino":["portuguese"],"tremer":["portuguese"],"trepidar":["portuguese"],"trevo":["portuguese"],"triagem":["portuguese"],"tribo":["portuguese"],"triciclo":["portuguese"],"tridente":["portuguese"],"trilogia":["portuguese"],"trindade":["portuguese"],"triplo":["portuguese"],"triturar":["portuguese"],"triunfal":["portuguese"],"trocar":["portuguese"],"trombeta":["portuguese"],"trova":["portuguese"],"trunfo":["portuguese"],"truque":["portuguese"],"tubular":["portuguese"],"tucano":["portuguese"],"tudo":["portuguese"],"tulipa":["portuguese"],"tupi":["portuguese"],"turbo":["portuguese"],"turma":["portuguese"],"turquesa":["portuguese"],"tutelar":["portuguese"],"tutorial":["portuguese"],"uivar":["portuguese"],"umbigo":["portuguese"],"unha":["portuguese"],"unidade":["portuguese"],"uniforme":["portuguese"],"urologia":["portuguese"],"urso":["portuguese"],"urtiga":["portuguese"],"urubu":["portuguese"],"usado":["portuguese"],"usina":["portuguese"],"usufruir":["portuguese"],"vacina":["portuguese"],"vadiar":["portuguese"],"vagaroso":["portuguese"],"vaidoso":["portuguese"],"vala":["portuguese"],"valente":["portuguese"],"validade":["portuguese"],"valores":["portuguese"],"vantagem":["portuguese"],"vaqueiro":["portuguese"],"varanda":["portuguese"],"vareta":["portuguese"],"varrer":["portuguese"],"vascular":["portuguese"],"vasilha":["portuguese"],"vassoura":["portuguese"],"vazar":["portuguese"],"vazio":["portuguese"],"veado":["portuguese"],"vedar":["portuguese"],"vegetar":["portuguese"],"veicular":["portuguese"],"veleiro":["portuguese"],"velhice":["portuguese"],"veludo":["portuguese"],"vencedor":["portuguese"],"vendaval":["portuguese"],"venerar":["portuguese"],"ventre":["portuguese"],"verbal":["portuguese"],"verdade":["portuguese"],"vereador":["portuguese"],"vergonha":["portuguese"],"vermelho":["portuguese"],"verniz":["portuguese"],"versar":["portuguese"],"vertente":["portuguese"],"vespa":["portuguese"],"vestido":["portuguese"],"vetorial":["portuguese"],"viaduto":["portuguese"],"viagem":["portuguese"],"viajar":["portuguese"],"viatura":["portuguese"],"vibrador":["portuguese"],"videira":["portuguese"],"vidraria":["portuguese"],"viela":["portuguese"],"viga":["portuguese"],"vigente":["portuguese"],"vigiar":["portuguese"],"vigorar":["portuguese"],"vilarejo":["portuguese"],"vinco":["portuguese"],"vinheta":["portuguese"],"vinil":["portuguese"],"violeta":["portuguese"],"virada":["portuguese"],"virtude":["portuguese"],"visitar":["portuguese"],"visto":["portuguese"],"vitral":["portuguese"],"viveiro":["portuguese"],"vizinho":["portuguese"],"voador":["portuguese"],"voar":["portuguese"],"vogal":["portuguese"],"volante":["portuguese"],"voleibol":["portuguese"],"voltagem":["portuguese"],"volumoso":["portuguese"],"vontade":["portuguese"],"vulto":["portuguese"],"vuvuzela":["portuguese"],"xadrez":["portuguese"],"xarope":["portuguese"],"xeque":["portuguese"],"xeretar":["portuguese"],"xerife":["portuguese"],"xingar":["portuguese"],"zangado":["portuguese"],"zarpar":["portuguese"],"zebu":["portuguese"],"zelador":["portuguese"],"zombar":["portuguese"],"zoologia":["portuguese"],"zumbido":["portuguese"],"абзац":["russian"],"абонент":["russian"],"абсурд":["russian"],"авангард":["russian"],"авария":["russian"],"август":["russian"],"авиация":["russian"],"автор":["russian"],"агент":["russian"],"агитация":["russian"],"агрегат":["russian"],"адвокат":["russian"],"адмирал":["russian"],"адрес":["russian"],"азарт":["russian"],"азот":["russian"],"академия":["russian"],"аквариум":["russian"],"аксиома":["russian"],"акула":["russian"],"акцент":["russian"],"акция":["russian"],"аллея":["russian"],"алмаз":["russian"],"алтарь":["russian"],"альбом":["russian"],"альянс":["russian"],"амбиция":["russian"],"анализ":["russian"],"анекдот":["russian"],"анкета":["russian"],"ансамбль":["russian"],"антенна":["russian"],"апельсин":["russian"],"аппарат":["russian"],"аппетит":["russian"],"апрель":["russian"],"аптека":["russian"],"арбуз":["russian"],"аргумент":["russian"],"аренда":["russian"],"арест":["russian"],"армия":["russian"],"аромат":["russian"],"арсенал":["russian"],"артерия":["russian"],"артист":["russian"],"архив":["russian"],"аспирант":["russian"],"асфальт":["russian"],"атака":["russian"],"атомный":["russian"],"атрибут":["russian"],"аукцион":["russian"],"афиша":["russian"],"аэропорт":["russian"],"бабочка":["russian"],"бабушка":["russian"],"багаж":["russian"],"база":["russian"],"бактерия":["russian"],"баланс":["russian"],"балерина":["russian"],"балкон":["russian"],"бандит":["russian"],"банк":["russian"],"барабан":["russian"],"барон":["russian"],"барышня":["russian"],"барьер":["russian"],"бассейн":["russian"],"батарея":["russian"],"башмак":["russian"],"башня":["russian"],"бедный":["russian"],"беженец":["russian"],"бездна":["russian"],"белка":["russian"],"белый":["russian"],"бензин":["russian"],"берег":["russian"],"беседа":["russian"],"бешеный":["russian"],"билет":["russian"],"бинокль":["russian"],"биржа":["russian"],"битва":["russian"],"благо":["russian"],"блеск":["russian"],"близкий":["russian"],"блин":["russian"],"блок":["russian"],"блюдо":["russian"],"богатый":["russian"],"бодрый":["russian"],"боец":["russian"],"бокал":["russian"],"боковой":["russian"],"бокс":["russian"],"более":["russian"],"болото":["russian"],"болтать":["russian"],"большой":["russian"],"бомба":["russian"],"борт":["russian"],"борьба":["russian"],"босой":["russian"],"ботинок":["russian"],"бояться":["russian"],"брак":["russian"],"брать":["russian"],"бревно":["russian"],"бред":["russian"],"бригада":["russian"],"бродяга":["russian"],"броня":["russian"],"бросить":["russian"],"брызги":["russian"],"брюки":["russian"],"брюхо":["russian"],"бугор":["russian"],"будка":["russian"],"будни":["russian"],"будущее":["russian"],"буква":["russian"],"букет":["russian"],"бульвар":["russian"],"бумага":["russian"],"бунт":["russian"],"бурный":["russian"],"буря":["russian"],"бутылка":["russian"],"бухта":["russian"],"бывший":["russian"],"быстро":["russian"],"бытовой":["russian"],"быть":["russian"],"бюджет":["russian"],"бюро":["russian"],"бюст":["russian"],"вагон":["russian"],"важный":["russian"],"вакцина":["russian"],"валенок":["russian"],"вальс":["russian"],"валюта":["russian"],"ванная":["russian"],"варенье":["russian"],"вариант":["russian"],"вблизи":["russian"],"вверх":["russian"],"вводить":["russian"],"вдали":["russian"],"вдвое":["russian"],"вдова":["russian"],"вдоль":["russian"],"вдруг":["russian"],"ведро":["russian"],"ведущий":["russian"],"ведьма":["russian"],"вежливо":["russian"],"везде":["russian"],"веко":["russian"],"вексель":["russian"],"велеть":["russian"],"великий":["russian"],"венец":["russian"],"веник":["russian"],"веранда":["russian"],"верблюд":["russian"],"верить":["russian"],"верный":["russian"],"версия":["russian"],"вертеть":["russian"],"верхний":["russian"],"вершина":["russian"],"весело":["russian"],"весна":["russian"],"весомый":["russian"],"вести":["russian"],"весь":["russian"],"ветеран":["russian"],"ветхий":["russian"],"вечер":["russian"],"вечно":["russian"],"вешалка":["russian"],"вещество":["russian"],"взамен":["russian"],"взгляд":["russian"],"вздох":["russian"],"взнос":["russian"],"взойти":["russian"],"взор":["russian"],"взрыв":["russian"],"взять":["russian"],"видеть":["russian"],"видимо":["russian"],"визг":["russian"],"визит":["russian"],"вилка":["russian"],"вина":["russian"],"вирус":["russian"],"висок":["russian"],"витамин":["russian"],"витрина":["russian"],"вихрь":["russian"],"вишня":["russian"],"вкус":["russian"],"влага":["russian"],"владелец":["russian"],"власть":["russian"],"влево":["russian"],"влияние":["russian"],"вложить":["russian"],"вместе":["russian"],"внешний":["russian"],"вникать":["russian"],"внимание":["russian"],"вновь":["russian"],"внук":["russian"],"внутри":["russian"],"внучка":["russian"],"внушать":["russian"],"вовлечь":["russian"],"вовремя":["russian"],"вовсю":["russian"],"вода":["russian"],"водород":["russian"],"водяной":["russian"],"воевать":["russian"],"возврат":["russian"],"возглас":["russian"],"воздух":["russian"],"возить":["russian"],"возле":["russian"],"возня":["russian"],"возраст":["russian"],"война":["russian"],"войско":["russian"],"вокзал":["russian"],"волос":["russian"],"волчий":["russian"],"вольный":["russian"],"воля":["russian"],"вообще":["russian"],"вопль":["russian"],"вопрос":["russian"],"ворота":["russian"],"восемь":["russian"],"восток":["russian"],"вплоть":["russian"],"вполне":["russian"],"вправе":["russian"],"впредь":["russian"],"впрочем":["russian"],"врач":["russian"],"вредный":["russian"],"время":["russian"],"вручить":["russian"],"всадник":["russian"],"всегда":["russian"],"вскоре":["russian"],"вскрыть":["russian"],"всплеск":["russian"],"вспышка":["russian"],"встреча":["russian"],"всюду":["russian"],"всякий":["russian"],"второй":["russian"],"вход":["russian"],"вчера":["russian"],"выбор":["russian"],"вывод":["russian"],"выгнать":["russian"],"выдать":["russian"],"выехать":["russian"],"вызов":["russian"],"выйти":["russian"],"выкуп":["russian"],"вылезти":["russian"],"вымыть":["russian"],"выпасть":["russian"],"выпить":["russian"],"выплата":["russian"],"выпуск":["russian"],"вырасти":["russian"],"выручка":["russian"],"выслать":["russian"],"высокий":["russian"],"выставка":["russian"],"вышка":["russian"],"вязать":["russian"],"вялый":["russian"],"газета":["russian"],"газовый":["russian"],"галерея":["russian"],"галстук":["russian"],"гамма":["russian"],"гарантия":["russian"],"гармония":["russian"],"гарнизон":["russian"],"гастроли":["russian"],"гвардия":["russian"],"гвоздь":["russian"],"гектар":["russian"],"генерал":["russian"],"гений":["russian"],"геном":["russian"],"геолог":["russian"],"герб":["russian"],"герой":["russian"],"гибкий":["russian"],"гигант":["russian"],"гимн":["russian"],"гипотеза":["russian"],"гитара":["russian"],"главный":["russian"],"глагол":["russian"],"гладить":["russian"],"глаз":["russian"],"глина":["russian"],"глоток":["russian"],"глубокий":["russian"],"глупый":["russian"],"глухой":["russian"],"глыба":["russian"],"глядеть":["russian"],"гнев":["russian"],"гнездо":["russian"],"гнилой":["russian"],"годовой":["russian"],"голова":["russian"],"голубой":["russian"],"голый":["russian"],"гонорар":["russian"],"гордость":["russian"],"горизонт":["russian"],"горло":["russian"],"горный":["russian"],"город":["russian"],"горшок":["russian"],"горький":["russian"],"горючее":["russian"],"горячий":["russian"],"готовый":["russian"],"градус":["russian"],"грамм":["russian"],"граница":["russian"],"граф":["russian"],"гребень":["russian"],"гриб":["russian"],"гримаса":["russian"],"грозить":["russian"],"грохот":["russian"],"грош":["russian"],"грубый":["russian"],"грудь":["russian"],"груз":["russian"],"грунт":["russian"],"группа":["russian"],"груша":["russian"],"грязный":["russian"],"губа":["russian"],"гудок":["russian"],"гулкий":["russian"],"гулять":["russian"],"гусеница":["russian"],"густо":["russian"],"гусь":["russian"],"давление":["russian"],"давно":["russian"],"даже":["russian"],"дальний":["russian"],"данный":["russian"],"дарить":["russian"],"датчик":["russian"],"дать":["russian"],"дача":["russian"],"двадцать":["russian"],"дважды":["russian"],"дверь":["russian"],"двигать":["russian"],"движение":["russian"],"двойной":["russian"],"двор":["russian"],"дебют":["russian"],"девятый":["russian"],"дежурный":["russian"],"действие":["russian"],"декабрь":["russian"],"деление":["russian"],"дело":["russian"],"дельфин":["russian"],"день":["russian"],"дерево":["russian"],"держать":["russian"],"дерзкий":["russian"],"десять":["russian"],"деталь":["russian"],"детский":["russian"],"дефект":["russian"],"дефицит":["russian"],"деятель":["russian"],"джаз":["russian"],"джинсы":["russian"],"джунгли":["russian"],"диагноз":["russian"],"диалог":["russian"],"диапазон":["russian"],"диван":["russian"],"дивизия":["russian"],"дивный":["russian"],"диета":["russian"],"дизайн":["russian"],"дикарь":["russian"],"дилер":["russian"],"динамика":["russian"],"диплом":["russian"],"директор":["russian"],"дитя":["russian"],"длинный":["russian"],"дневник":["russian"],"добрый":["russian"],"добыча":["russian"],"доверие":["russian"],"догадка":["russian"],"догнать":["russian"],"дождь":["russian"],"доклад":["russian"],"доктор":["russian"],"документ":["russian"],"долго":["russian"],"должен":["russian"],"долина":["russian"],"донос":["russian"],"дорога":["russian"],"досада":["russian"],"доска":["russian"],"достать":["russian"],"досуг":["russian"],"доход":["russian"],"доцент":["russian"],"дощатый":["russian"],"драка":["russian"],"древний":["russian"],"дремать":["russian"],"дробный":["russian"],"дрова":["russian"],"дрожать":["russian"],"другой":["russian"],"дружба":["russian"],"дубовый":["russian"],"дуга":["russian"],"думать":["russian"],"дурной":["russian"],"духи":["russian"],"душный":["russian"],"дуэль":["russian"],"дуэт":["russian"],"дыра":["russian"],"дыхание":["russian"],"дюжина":["russian"],"дядя":["russian"],"едва":["russian"],"единый":["russian"],"ерунда":["russian"],"если":["russian"],"ехать":["russian"],"жадный":["russian"],"жажда":["russian"],"жалеть":["russian"],"жалоба":["russian"],"жанр":["russian"],"жареный":["russian"],"жаркий":["russian"],"жгучий":["russian"],"жевать":["russian"],"желание":["russian"],"желудок":["russian"],"жена":["russian"],"женщина":["russian"],"жертва":["russian"],"жест":["russian"],"жидкость":["russian"],"житель":["russian"],"жить":["russian"],"жрец":["russian"],"жулик":["russian"],"журнал":["russian"],"жуткий":["russian"],"забрать":["russian"],"забыть":["russian"],"завести":["russian"],"завод":["russian"],"завтра":["russian"],"загадка":["russian"],"загнать":["russian"],"заговор":["russian"],"задача":["russian"],"задеть":["russian"],"задний":["russian"],"задолго":["russian"],"заехать":["russian"],"заказ":["russian"],"закон":["russian"],"закрыть":["russian"],"закуска":["russian"],"залезть":["russian"],"залить":["russian"],"залп":["russian"],"замок":["russian"],"замуж":["russian"],"замысел":["russian"],"занавес":["russian"],"заново":["russian"],"занять":["russian"],"заодно":["russian"],"запись":["russian"],"запрос":["russian"],"запуск":["russian"],"запястье":["russian"],"заранее":["russian"],"заросль":["russian"],"зарплата":["russian"],"заря":["russian"],"засада":["russian"],"заслуга":["russian"],"заснуть":["russian"],"застать":["russian"],"затвор":["russian"],"затеять":["russian"],"затрата":["russian"],"затылок":["russian"],"захват":["russian"],"зачем":["russian"],"защита":["russian"],"заявить":["russian"],"заяц":["russian"],"звезда":["russian"],"звено":["russian"],"звонить":["russian"],"здесь":["russian"],"зелень":["russian"],"земля":["russian"],"зеркало":["russian"],"зерно":["russian"],"зима":["russian"],"злой":["russian"],"змея":["russian"],"знамя":["russian"],"знание":["russian"],"значит":["russian"],"золотой":["russian"],"зона":["russian"],"зонтик":["russian"],"зоопарк":["russian"],"зрачок":["russian"],"зрение":["russian"],"зритель":["russian"],"зубной":["russian"],"зубр":["russian"],"игла":["russian"],"идеал":["russian"],"идеолог":["russian"],"идея":["russian"],"идол":["russian"],"идти":["russian"],"изба":["russian"],"избить":["russian"],"избрать":["russian"],"избыток":["russian"],"извлечь":["russian"],"извне":["russian"],"изгиб":["russian"],"изгнать":["russian"],"издание":["russian"],"изделие":["russian"],"изнутри":["russian"],"изобилие":["russian"],"изоляция":["russian"],"изредка":["russian"],"изрядно":["russian"],"изучение":["russian"],"изъять":["russian"],"изящный":["russian"],"икона":["russian"],"икра":["russian"],"иллюзия":["russian"],"именно":["russian"],"иметь":["russian"],"имидж":["russian"],"империя":["russian"],"импульс":["russian"],"иначе":["russian"],"инвалид":["russian"],"индекс":["russian"],"индивид":["russian"],"инерция":["russian"],"инженер":["russian"],"иногда":["russian"],"иной":["russian"],"институт":["russian"],"интерес":["russian"],"интрига":["russian"],"интуиция":["russian"],"инфаркт":["russian"],"инцидент":["russian"],"ирония":["russian"],"искать":["russian"],"испуг":["russian"],"история":["russian"],"итог":["russian"],"июнь":["russian"],"кабель":["russian"],"кабинет":["russian"],"каблук":["russian"],"кавалер":["russian"],"кадр":["russian"],"каждый":["russian"],"кажется":["russian"],"казино":["russian"],"калитка":["russian"],"камень":["russian"],"камин":["russian"],"канал":["russian"],"кандидат":["russian"],"каникулы":["russian"],"канон":["russian"],"капитан":["russian"],"капля":["russian"],"капот":["russian"],"капуста":["russian"],"карандаш":["russian"],"карета":["russian"],"каркас":["russian"],"карман":["russian"],"картина":["russian"],"карьера":["russian"],"каска":["russian"],"кассета":["russian"],"кастрюля":["russian"],"каталог":["russian"],"катер":["russian"],"каток":["russian"],"катушка":["russian"],"кафедра":["russian"],"качество":["russian"],"каша":["russian"],"кашлять":["russian"],"каюта":["russian"],"квадрат":["russian"],"квартира":["russian"],"квота":["russian"],"кепка":["russian"],"кивнуть":["russian"],"километр":["russian"],"кино":["russian"],"киоск":["russian"],"кипяток":["russian"],"кирпич":["russian"],"кислота":["russian"],"кисть":["russian"],"клавиша":["russian"],"клапан":["russian"],"класс":["russian"],"клей":["russian"],"клетка":["russian"],"клиент":["russian"],"климат":["russian"],"клиника":["russian"],"кличка":["russian"],"клоун":["russian"],"клочок":["russian"],"клуб":["russian"],"клумба":["russian"],"ключ":["russian"],"книга":["russian"],"кнопка":["russian"],"кнут":["russian"],"княгиня":["russian"],"князь":["russian"],"кобура":["russian"],"когда":["russian"],"кодекс":["russian"],"кожа":["russian"],"коктейль":["russian"],"колено":["russian"],"коллега":["russian"],"колонна":["russian"],"колпак":["russian"],"кольцо":["russian"],"колючий":["russian"],"коляска":["russian"],"команда":["russian"],"комедия":["russian"],"комиссия":["russian"],"коммуна":["russian"],"комната":["russian"],"комок":["russian"],"компания":["russian"],"комфорт":["russian"],"конвейер":["russian"],"конгресс":["russian"],"конечно":["russian"],"конкурс":["russian"],"контроль":["russian"],"концерт":["russian"],"конь":["russian"],"конюшня":["russian"],"копать":["russian"],"копейка":["russian"],"копыто":["russian"],"корабль":["russian"],"корень":["russian"],"корзина":["russian"],"коридор":["russian"],"кормить":["russian"],"корпус":["russian"],"космос":["russian"],"костюм":["russian"],"косяк":["russian"],"котел":["russian"],"котлета":["russian"],"который":["russian"],"коттедж":["russian"],"кофе":["russian"],"кофта":["russian"],"кошка":["russian"],"кража":["russian"],"край":["russian"],"красный":["russian"],"краткий":["russian"],"кредит":["russian"],"крем":["russian"],"крепкий":["russian"],"кресло":["russian"],"кривой":["russian"],"кризис":["russian"],"кристалл":["russian"],"критерий":["russian"],"кричать":["russian"],"кровь":["russian"],"крокодил":["russian"],"кролик":["russian"],"кроме":["russian"],"крона":["russian"],"круг":["russian"],"кружка":["russian"],"крупный":["russian"],"крутой":["russian"],"крушение":["russian"],"крыло":["russian"],"крыша":["russian"],"крючок":["russian"],"кстати":["russian"],"кубик":["russian"],"куда":["russian"],"кузов":["russian"],"кукла":["russian"],"кулак":["russian"],"кулиса":["russian"],"культура":["russian"],"кумир":["russian"],"купе":["russian"],"купить":["russian"],"купол":["russian"],"купюра":["russian"],"курица":["russian"],"курорт":["russian"],"курс":["russian"],"куртка":["russian"],"кусок":["russian"],"куст":["russian"],"кухня":["russian"],"кушать":["russian"],"лабиринт":["russian"],"лавка":["russian"],"лагерь":["russian"],"ладно":["russian"],"ладонь":["russian"],"лапа":["russian"],"лауреат":["russian"],"лгать":["russian"],"лебедь":["russian"],"левый":["russian"],"легенда":["russian"],"легкий":["russian"],"ледяной":["russian"],"лежать":["russian"],"лезвие":["russian"],"лезть":["russian"],"лекция":["russian"],"ленивый":["russian"],"лента":["russian"],"лепесток":["russian"],"лесной":["russian"],"лестница":["russian"],"лететь":["russian"],"лето":["russian"],"лечить":["russian"],"лига":["russian"],"лидер":["russian"],"лиловый":["russian"],"лимон":["russian"],"линия":["russian"],"липкий":["russian"],"лист":["russian"],"литр":["russian"],"лихой":["russian"],"лицо":["russian"],"лишить":["russian"],"лишний":["russian"],"ловить":["russian"],"логика":["russian"],"лодка":["russian"],"ложь":["russian"],"лозунг":["russian"],"локоть":["russian"],"лопата":["russian"],"лошадь":["russian"],"лукавый":["russian"],"луна":["russian"],"лучший":["russian"],"лысый":["russian"],"льгота":["russian"],"любить":["russian"],"любой":["russian"],"людской":["russian"],"люстра":["russian"],"лютый":["russian"],"лягушка":["russian"],"магазин":["russian"],"магия":["russian"],"майор":["russian"],"майский":["russian"],"максимум":["russian"],"макушка":["russian"],"мало":["russian"],"мальчик":["russian"],"мама":["russian"],"манера":["russian"],"марка":["russian"],"март":["russian"],"маршрут":["russian"],"масса":["russian"],"мастер":["russian"],"масштаб":["russian"],"материал":["russian"],"матч":["russian"],"махать":["russian"],"машина":["russian"],"маяк":["russian"],"мебель":["russian"],"медаль":["russian"],"медведь":["russian"],"медицина":["russian"],"медь":["russian"],"между":["russian"],"мелкий":["russian"],"мелочь":["russian"],"мемуары":["russian"],"меньше":["russian"],"меню":["russian"],"менять":["russian"],"мера":["russian"],"мерцать":["russian"],"место":["russian"],"месяц":["russian"],"металл":["russian"],"метод":["russian"],"метр":["russian"],"механизм":["russian"],"меховой":["russian"],"мечтать":["russian"],"мешать":["russian"],"мешок":["russian"],"миграция":["russian"],"микрофон":["russian"],"милиция":["russian"],"миллион":["russian"],"милость":["russian"],"миля":["russian"],"мимо":["russian"],"минерал":["russian"],"министр":["russian"],"минута":["russian"],"мирный":["russian"],"миска":["russian"],"миссия":["russian"],"митинг":["russian"],"мишень":["russian"],"младший":["russian"],"мнение":["russian"],"мнимый":["russian"],"много":["russian"],"могучий":["russian"],"модель":["russian"],"может":["russian"],"мозг":["russian"],"мокрый":["russian"],"молекула":["russian"],"молния":["russian"],"молодой":["russian"],"молчать":["russian"],"момент":["russian"],"монета":["russian"],"монитор":["russian"],"монолог":["russian"],"монстр":["russian"],"монтаж":["russian"],"мораль":["russian"],"море":["russian"],"морковь":["russian"],"мороз":["russian"],"морщина":["russian"],"мостовая":["russian"],"мотать":["russian"],"мотив":["russian"],"мотор":["russian"],"мохнатый":["russian"],"мрамор":["russian"],"мрачный":["russian"],"мстить":["russian"],"мудрый":["russian"],"мужество":["russian"],"мужчина":["russian"],"музей":["russian"],"музыка":["russian"],"мундир":["russian"],"муравей":["russian"],"мусор":["russian"],"муха":["russian"],"мчаться":["russian"],"мысль":["russian"],"мыться":["russian"],"мышца":["russian"],"мышь":["russian"],"мюзикл":["russian"],"мягкий":["russian"],"мясо":["russian"],"набор":["russian"],"навык":["russian"],"наглый":["russian"],"нагрузка":["russian"],"надежда":["russian"],"надзор":["russian"],"надо":["russian"],"наедине":["russian"],"назад":["russian"],"название":["russian"],"назло":["russian"],"наивный":["russian"],"найти":["russian"],"наконец":["russian"],"налево":["russian"],"наличие":["russian"],"налог":["russian"],"намерен":["russian"],"нанести":["russian"],"напасть":["russian"],"например":["russian"],"народ":["russian"],"наследие":["russian"],"натура":["russian"],"наука":["russian"],"наутро":["russian"],"начать":["russian"],"небо":["russian"],"неважно":["russian"],"невеста":["russian"],"негодяй":["russian"],"недавно":["russian"],"неделя":["russian"],"недолго":["russian"],"недра":["russian"],"недуг":["russian"],"нежный":["russian"],"незачем":["russian"],"некто":["russian"],"нелепый":["russian"],"неловко":["russian"],"нельзя":["russian"],"немало":["russian"],"немой":["russian"],"неплохо":["russian"],"нервный":["russian"],"нередко":["russian"],"нестись":["russian"],"неудача":["russian"],"неужели":["russian"],"нефть":["russian"],"неясный":["russian"],"нигде":["russian"],"низкий":["russian"],"никакой":["russian"],"никогда":["russian"],"никуда":["russian"],"ничто":["russian"],"ничуть":["russian"],"ниша":["russian"],"нищий":["russian"],"новость":["russian"],"новый":["russian"],"нога":["russian"],"ноготь":["russian"],"ножницы":["russian"],"ноздря":["russian"],"номер":["russian"],"носить":["russian"],"носок":["russian"],"ночь":["russian"],"ноябрь":["russian"],"нрав":["russian"],"нуль":["russian"],"нынче":["russian"],"нырять":["russian"],"нюанс":["russian"],"няня":["russian"],"обаяние":["russian"],"обед":["russian"],"обезьяна":["russian"],"обещать":["russian"],"обжечь":["russian"],"обзор":["russian"],"обилие":["russian"],"обитать":["russian"],"область":["russian"],"облик":["russian"],"обложка":["russian"],"обмен":["russian"],"обморок":["russian"],"обожать":["russian"],"обои":["russian"],"оболочка":["russian"],"оборона":["russian"],"обочина":["russian"],"образ":["russian"],"обрести":["russian"],"обрыв":["russian"],"обувь":["russian"],"обучение":["russian"],"обход":["russian"],"общество":["russian"],"общий":["russian"],"объект":["russian"],"обыск":["russian"],"обычно":["russian"],"обязать":["russian"],"овощи":["russian"],"овраг":["russian"],"овца":["russian"],"оговорка":["russian"],"ограда":["russian"],"огурец":["russian"],"одежда":["russian"],"одеяло":["russian"],"один":["russian"],"однако":["russian"],"одолеть":["russian"],"ожидать":["russian"],"озеро":["russian"],"океан":["russian"],"окно":["russian"],"около":["russian"],"окоп":["russian"],"окраина":["russian"],"октябрь":["russian"],"опасный":["russian"],"опека":["russian"],"операция":["russian"],"описание":["russian"],"оплата":["russian"],"опора":["russian"],"оппонент":["russian"],"оптимизм":["russian"],"оптовый":["russian"],"опухоль":["russian"],"опыт":["russian"],"оратор":["russian"],"орбита":["russian"],"орган":["russian"],"орден":["russian"],"орел":["russian"],"оригинал":["russian"],"ориентир":["russian"],"оркестр":["russian"],"оружие":["russian"],"осенний":["russian"],"осколок":["russian"],"осмотр":["russian"],"остров":["russian"],"отбор":["russian"],"отбыть":["russian"],"отвлечь":["russian"],"отдать":["russian"],"отдел":["russian"],"отдых":["russian"],"отель":["russian"],"отец":["russian"],"отзыв":["russian"],"отказ":["russian"],"отклик":["russian"],"открыть":["russian"],"откуда":["russian"],"отличие":["russian"],"отныне":["russian"],"отойти":["russian"],"отпуск":["russian"],"отрасль":["russian"],"отросток":["russian"],"отрывок":["russian"],"отряд":["russian"],"отсек":["russian"],"отставка":["russian"],"отсюда":["russian"],"оттенок":["russian"],"оттого":["russian"],"отчего":["russian"],"отъезд":["russian"],"офис":["russian"],"офицер":["russian"],"охота":["russian"],"охрана":["russian"],"оценка":["russian"],"очаг":["russian"],"очень":["russian"],"очередь":["russian"],"очищать":["russian"],"ошибка":["russian"],"ощущение":["russian"],"павильон":["russian"],"падать":["russian"],"пазуха":["russian"],"пакет":["russian"],"палата":["russian"],"палец":["russian"],"палуба":["russian"],"пальто":["russian"],"память":["russian"],"панель":["russian"],"паника":["russian"],"пара":["russian"],"парень":["russian"],"пароход":["russian"],"партия":["russian"],"парус":["russian"],"паспорт":["russian"],"пассажир":["russian"],"пастух":["russian"],"патент":["russian"],"патрон":["russian"],"пауза":["russian"],"паук":["russian"],"паутина":["russian"],"пафос":["russian"],"пахнуть":["russian"],"пациент":["russian"],"пачка":["russian"],"певец":["russian"],"педагог":["russian"],"пейзаж":["russian"],"пенсия":["russian"],"пепел":["russian"],"первый":["russian"],"перед":["russian"],"период":["russian"],"перо":["russian"],"перрон":["russian"],"персонаж":["russian"],"перчатка":["russian"],"песня":["russian"],"песок":["russian"],"петля":["russian"],"петрушка":["russian"],"петух":["russian"],"пехота":["russian"],"печать":["russian"],"печень":["russian"],"пешком":["russian"],"пещера":["russian"],"пианист":["russian"],"пиджак":["russian"],"пилот":["russian"],"пионер":["russian"],"пирамида":["russian"],"пирожок":["russian"],"письмо":["russian"],"пища":["russian"],"плавание":["russian"],"плакать":["russian"],"пламя":["russian"],"план":["russian"],"пласт":["russian"],"платить":["russian"],"пленный":["russian"],"плечо":["russian"],"плита":["russian"],"плод":["russian"],"плоский":["russian"],"плотный":["russian"],"плохой":["russian"],"площадь":["russian"],"плыть":["russian"],"плюс":["russian"],"пляж":["russian"],"плясать":["russian"],"победа":["russian"],"повар":["russian"],"повод":["russian"],"повсюду":["russian"],"повязка":["russian"],"погода":["russian"],"погреб":["russian"],"подбор":["russian"],"подвиг":["russian"],"подделка":["russian"],"поджать":["russian"],"поднос":["russian"],"подпись":["russian"],"подруга":["russian"],"подход":["russian"],"подчас":["russian"],"подъезд":["russian"],"поединок":["russian"],"поезд":["russian"],"поесть":["russian"],"поехать":["russian"],"пожалуй":["russian"],"пожилой":["russian"],"позади":["russian"],"позвать":["russian"],"поздний":["russian"],"позиция":["russian"],"позор":["russian"],"поиск":["russian"],"поймать":["russian"],"пойти":["russian"],"поклон":["russian"],"покой":["russian"],"покрыть":["russian"],"полдень":["russian"],"полезный":["russian"],"ползти":["russian"],"полк":["russian"],"полный":["russian"],"половина":["russian"],"полтора":["russian"],"польза":["russian"],"поляна":["russian"],"помидор":["russian"],"помнить":["russian"],"помощь":["russian"],"попасть":["russian"],"поперек":["russian"],"поплыть":["russian"],"пополам":["russian"],"поправка":["russian"],"попугай":["russian"],"попытка":["russian"],"порог":["russian"],"портрет":["russian"],"порция":["russian"],"порыв":["russian"],"порядок":["russian"],"после":["russian"],"посол":["russian"],"посреди":["russian"],"постель":["russian"],"посуда":["russian"],"потом":["russian"],"похвала":["russian"],"похожий":["russian"],"поцелуй":["russian"],"почва":["russian"],"почему":["russian"],"пошлина":["russian"],"поэма":["russian"],"поэтому":["russian"],"право":["russian"],"праздник":["russian"],"практика":["russian"],"прах":["russian"],"преграда":["russian"],"предмет":["russian"],"прежде":["russian"],"прелесть":["russian"],"премия":["russian"],"препарат":["russian"],"пресса":["russian"],"прибыть":["russian"],"прижать":["russian"],"прийти":["russian"],"приказ":["russian"],"прилавок":["russian"],"пример":["russian"],"принять":["russian"],"природа":["russian"],"притом":["russian"],"прихожая":["russian"],"прицел":["russian"],"причина":["russian"],"приют":["russian"],"прогноз":["russian"],"продукт":["russian"],"проект":["russian"],"прожить":["russian"],"прокат":["russian"],"промысел":["russian"],"пропуск":["russian"],"просто":["russian"],"против":["russian"],"профиль":["russian"],"процесс":["russian"],"прочий":["russian"],"прошлый":["russian"],"прощать":["russian"],"пружина":["russian"],"прут":["russian"],"прыжок":["russian"],"прямой":["russian"],"птица":["russian"],"публика":["russian"],"пугать":["russian"],"пуговица":["russian"],"пузырь":["russian"],"пульт":["russian"],"пуля":["russian"],"пункт":["russian"],"пускать":["russian"],"пустой":["russian"],"путь":["russian"],"пухлый":["russian"],"пучок":["russian"],"пушистый":["russian"],"пушка":["russian"],"пчела":["russian"],"пшеница":["russian"],"пылать":["russian"],"пыль":["russian"],"пышный":["russian"],"пьеса":["russian"],"пятка":["russian"],"пятно":["russian"],"пятый":["russian"],"пятьсот":["russian"],"работа":["russian"],"равнина":["russian"],"ради":["russian"],"радость":["russian"],"радуга":["russian"],"разбить":["russian"],"развитие":["russian"],"разговор":["russian"],"раздел":["russian"],"различие":["russian"],"размер":["russian"],"разный":["russian"],"разрыв":["russian"],"разум":["russian"],"район":["russian"],"ракета":["russian"],"раковина":["russian"],"рамка":["russian"],"рано":["russian"],"рапорт":["russian"],"распад":["russian"],"рассказ":["russian"],"расти":["russian"],"расход":["russian"],"расцвет":["russian"],"рация":["russian"],"рвануть":["russian"],"рваться":["russian"],"реакция":["russian"],"ребро":["russian"],"реветь":["russian"],"редактор":["russian"],"редкий":["russian"],"реестр":["russian"],"режим":["russian"],"резать":["russian"],"резерв":["russian"],"резина":["russian"],"резко":["russian"],"резной":["russian"],"рейс":["russian"],"реклама":["russian"],"рекорд":["russian"],"религия":["russian"],"рельс":["russian"],"ремень":["russian"],"ремонт":["russian"],"реплика":["russian"],"репортаж":["russian"],"ресница":["russian"],"ресторан":["russian"],"реформа":["russian"],"рецепт":["russian"],"речь":["russian"],"решение":["russian"],"ржавый":["russian"],"риск":["russian"],"рисунок":["russian"],"ритуал":["russian"],"рифма":["russian"],"робко":["russian"],"робот":["russian"],"ровесник":["russian"],"ровно":["russian"],"родной":["russian"],"рождение":["russian"],"роза":["russian"],"розовый":["russian"],"розыск":["russian"],"роль":["russian"],"роман":["russian"],"роскошь":["russian"],"роспись":["russian"],"рост":["russian"],"рубашка":["russian"],"рубеж":["russian"],"рубить":["russian"],"рубрика":["russian"],"рудник":["russian"],"рука":["russian"],"рукопись":["russian"],"румяный":["russian"],"русло":["russian"],"рухнуть":["russian"],"ручей":["russian"],"ручной":["russian"],"рыба":["russian"],"рыжий":["russian"],"рынок":["russian"],"рыхлый":["russian"],"рыцарь":["russian"],"рычаг":["russian"],"рюкзак":["russian"],"рядом":["russian"],"садовый":["russian"],"сажать":["russian"],"салон":["russian"],"салфетка":["russian"],"салют":["russian"],"самец":["russian"],"самовар":["russian"],"самый":["russian"],"сани":["russian"],"санкция":["russian"],"сапог":["russian"],"сарай":["russian"],"сатира":["russian"],"сахар":["russian"],"сбить":["russian"],"сбоку":["russian"],"сборная":["russian"],"сбыт":["russian"],"свадьба":["russian"],"свалка":["russian"],"сварить":["russian"],"свежий":["russian"],"сверху":["russian"],"свет":["russian"],"свеча":["russian"],"свинья":["russian"],"свист":["russian"],"свитер":["russian"],"свобода":["russian"],"сводка":["russian"],"свой":["russian"],"свыше":["russian"],"связь":["russian"],"сдаться":["russian"],"сделать":["russian"],"сегмент":["russian"],"сегодня":["russian"],"седло":["russian"],"седой":["russian"],"седьмой":["russian"],"сезон":["russian"],"сейф":["russian"],"сейчас":["russian"],"секрет":["russian"],"сектор":["russian"],"секунда":["russian"],"семинар":["russian"],"семья":["russian"],"сенатор":["russian"],"сено":["russian"],"сенсация":["russian"],"сентябрь":["russian"],"сервис":["russian"],"сердце":["russian"],"середина":["russian"],"сержант":["russian"],"серия":["russian"],"серый":["russian"],"сессия":["russian"],"сесть":["russian"],"сетевой":["russian"],"сжатый":["russian"],"сжечь":["russian"],"сзади":["russian"],"сигнал":["russian"],"сиденье":["russian"],"сила":["russian"],"силуэт":["russian"],"сильный":["russian"],"символ":["russian"],"симпатия":["russian"],"симфония":["russian"],"синий":["russian"],"синтез":["russian"],"синяк":["russian"],"сирень":["russian"],"система":["russian"],"ситуация":["russian"],"сияние":["russian"],"сказать":["russian"],"скала":["russian"],"скамейка":["russian"],"скандал":["russian"],"скатерть":["russian"],"скачок":["russian"],"скважина":["russian"],"сквер":["russian"],"сквозь":["russian"],"скелет":["russian"],"скидка":["russian"],"склад":["russian"],"сколько":["russian"],"скорый":["russian"],"скосить":["russian"],"скот":["russian"],"скрипка":["russian"],"скудный":["russian"],"скука":["russian"],"слабый":["russian"],"слава":["russian"],"сладкий":["russian"],"слегка":["russian"],"след":["russian"],"слеза":["russian"],"слепой":["russian"],"слесарь":["russian"],"слишком":["russian"],"слово":["russian"],"слог":["russian"],"сложный":["russian"],"сломать":["russian"],"служба":["russian"],"слух":["russian"],"случай":["russian"],"слышать":["russian"],"слюна":["russian"],"смежный":["russian"],"смелый":["russian"],"сменить":["russian"],"смесь":["russian"],"сметана":["russian"],"смех":["russian"],"смола":["russian"],"смуглый":["russian"],"смутный":["russian"],"смущать":["russian"],"смысл":["russian"],"снайпер":["russian"],"снаряд":["russian"],"сначала":["russian"],"снег":["russian"],"снизу":["russian"],"сниться":["russian"],"сно��а":["russian"],"снять":["russian"],"собака":["russian"],"соблазн":["russian"],"собрание":["russian"],"событие":["russian"],"совесть":["russian"],"совсем":["russian"],"согласие":["russian"],"создать":["russian"],"сознание":["russian"],"созреть":["russian"],"сойтись":["russian"],"сокол":["russian"],"солдат":["russian"],"соленый":["russian"],"солнце":["russian"],"солома":["russian"],"сомнение":["russian"],"сонный":["russian"],"соперник":["russian"],"соратник":["russian"],"сорвать":["russian"],"сосед":["russian"],"сосиска":["russian"],"состав":["russian"],"сотня":["russian"],"соус":["russian"],"союз":["russian"],"спад":["russian"],"спальня":["russian"],"спасти":["russian"],"спектр":["russian"],"сперва":["russian"],"спешить":["russian"],"спина":["russian"],"спирт":["russian"],"список":["russian"],"спичка":["russian"],"сплав":["russian"],"спонсор":["russian"],"спор":["russian"],"способ":["russian"],"справка":["russian"],"спустя":["russian"],"спутник":["russian"],"сразу":["russian"],"средство":["russian"],"срок":["russian"],"срыв":["russian"],"ссора":["russian"],"ссылка":["russian"],"ставить":["russian"],"стадия":["russian"],"стакан":["russian"],"станция":["russian"],"старый":["russian"],"стая":["russian"],"стебель":["russian"],"стекло":["russian"],"стена":["russian"],"степень":["russian"],"стереть":["russian"],"стиль":["russian"],"стимул":["russian"],"стирать":["russian"],"стихи":["russian"],"стоить":["russian"],"стойка":["russian"],"стол":["russian"],"стонать":["russian"],"стопа":["russian"],"сторона":["russian"],"стоянка":["russian"],"страна":["russian"],"стричь":["russian"],"строгий":["russian"],"струя":["russian"],"студент":["russian"],"стук":["russian"],"ступня":["russian"],"стыдно":["russian"],"суббота":["russian"],"субъект":["russian"],"сувенир":["russian"],"сугроб":["russian"],"сугубо":["russian"],"судить":["russian"],"судно":["russian"],"судьба":["russian"],"суета":["russian"],"суметь":["russian"],"сумма":["russian"],"сумрак":["russian"],"сундук":["russian"],"супруг":["russian"],"суровый":["russian"],"сутки":["russian"],"сухой":["russian"],"суша":["russian"],"существо":["russian"],"сфера":["russian"],"схема":["russian"],"схожий":["russian"],"сценарий":["russian"],"счастье":["russian"],"считать":["russian"],"съезд":["russian"],"сыграть":["russian"],"сырой":["russian"],"сытый":["russian"],"сыщик":["russian"],"сюда":["russian"],"сюжет":["russian"],"сюрприз":["russian"],"тайна":["russian"],"также":["russian"],"такой":["russian"],"такси":["russian"],"тактика":["russian"],"талия":["russian"],"таможня":["russian"],"танец":["russian"],"таракан":["russian"],"тарелка":["russian"],"тариф":["russian"],"тащить":["russian"],"таять":["russian"],"тварь":["russian"],"театр":["russian"],"тезис":["russian"],"текст":["russian"],"текущий":["russian"],"телефон":["russian"],"тема":["russian"],"темнота":["russian"],"теневой":["russian"],"теннис":["russian"],"теория":["russian"],"теперь":["russian"],"тепло":["russian"],"терапия":["russian"],"терзать":["russian"],"термин":["russian"],"терпеть":["russian"],"терраса":["russian"],"терять":["russian"],"тесный":["russian"],"тетрадь":["russian"],"техника":["russian"],"течение":["russian"],"тигр":["russian"],"типовой":["russian"],"тираж":["russian"],"титул":["russian"],"тихий":["russian"],"ткань":["russian"],"товарищ":["russian"],"тоже":["russian"],"толпа":["russian"],"толстый":["russian"],"толчок":["russian"],"толщина":["russian"],"только":["russian"],"тонкий":["russian"],"тонна":["russian"],"топить":["russian"],"топор":["russian"],"торговля":["russian"],"тормоз":["russian"],"торчать":["russian"],"тотчас":["russian"],"точка":["russian"],"точно":["russian"],"тощий":["russian"],"трава":["russian"],"традиция":["russian"],"трактор":["russian"],"трамвай":["russian"],"траншея":["russian"],"трасса":["russian"],"тревога":["russian"],"трезвый":["russian"],"тренер":["russian"],"трепет":["russian"],"треск":["russian"],"третий":["russian"],"трещина":["russian"],"трибуна":["russian"],"тридцать":["russian"],"триста":["russian"],"триумф":["russian"],"трогать":["russian"],"тройка":["russian"],"тронуть":["russian"],"тропа":["russian"],"тротуар":["russian"],"трубка":["russian"],"труд":["russian"],"трюк":["russian"],"тряпка":["russian"],"туго":["russian"],"туловище":["russian"],"туман":["russian"],"тумбочка":["russian"],"тундра":["russian"],"тупик":["russian"],"турист":["russian"],"турнир":["russian"],"тусклый":["russian"],"туфля":["russian"],"туча":["russian"],"тысяча":["russian"],"тяга":["russian"],"тяжело":["russian"],"убежать":["russian"],"убогий":["russian"],"уборка":["russian"],"уважение":["russian"],"увезти":["russian"],"уволить":["russian"],"угадать":["russian"],"угол":["russian"],"угощать":["russian"],"угроза":["russian"],"угрюмый":["russian"],"удар":["russian"],"удачный":["russian"],"уделять":["russian"],"удивить":["russian"],"удобный":["russian"],"удочка":["russian"],"уезжать":["russian"],"ужин":["russian"],"узел":["russian"],"узкий":["russian"],"уйти":["russian"],"указание":["russian"],"уклон":["russian"],"украсть":["russian"],"укусить":["russian"],"улетать":["russian"],"улица":["russian"],"улыбка":["russian"],"умело":["russian"],"умение":["russian"],"умный":["russian"],"умолять":["russian"],"унести":["russian"],"унижать":["russian"],"унылый":["russian"],"упаковка":["russian"],"упасть":["russian"],"упорно":["russian"],"упрек":["russian"],"урна":["russian"],"уровень":["russian"],"урожай":["russian"],"уронить":["russian"],"усадьба":["russian"],"усатый":["russian"],"усвоить":["russian"],"усилие":["russian"],"условие":["russian"],"услуга":["russian"],"усмешка":["russian"],"успеть":["russian"],"устав":["russian"],"устоять":["russian"],"утечка":["russian"],"утешать":["russian"],"утро":["russian"],"уцелеть":["russian"],"участие":["russian"],"ученик":["russian"],"учесть":["russian"],"ущелье":["russian"],"ущерб":["russian"],"уютный":["russian"],"фабрика":["russian"],"фаворит":["russian"],"факел":["russian"],"факт":["russian"],"фамилия":["russian"],"фантазия":["russian"],"фасад":["russian"],"февраль":["russian"],"феномен":["russian"],"фермер":["russian"],"фигура":["russian"],"физика":["russian"],"филиал":["russian"],"философ":["russian"],"фильм":["russian"],"финал":["russian"],"флаг":["russian"],"флот":["russian"],"фойе":["russian"],"фокус":["russian"],"фонарь":["russian"],"фонд":["russian"],"фонтан":["russian"],"форма":["russian"],"форум":["russian"],"фото":["russian"],"фрагмент":["russian"],"фраза":["russian"],"фракция":["russian"],"фронт":["russian"],"фрукт":["russian"],"функция":["russian"],"фуражка":["russian"],"футбол":["russian"],"футляр":["russian"],"халат":["russian"],"хаос":["russian"],"характер":["russian"],"хата":["russian"],"хвалить":["russian"],"хватать":["russian"],"хвойный":["russian"],"хвост":["russian"],"химия":["russian"],"хирург":["russian"],"хитрый":["russian"],"хищник":["russian"],"хлеб":["russian"],"хлынуть":["russian"],"хмурый":["russian"],"ходить":["russian"],"хозяин":["russian"],"хоккей":["russian"],"холм":["russian"],"холст":["russian"],"хорошо":["russian"],"хотеть":["russian"],"храбрый":["russian"],"храм":["russian"],"хранить":["russian"],"хребет":["russian"],"хрен":["russian"],"хрипло":["russian"],"хроника":["russian"],"хрупкий":["russian"],"художник":["russian"],"худший":["russian"],"хулиган":["russian"],"хутор":["russian"],"царь":["russian"],"цветок":["russian"],"целевой":["russian"],"целиком":["russian"],"целое":["russian"],"цель":["russian"],"цензура":["russian"],"ценить":["russian"],"центр":["russian"],"цепной":["russian"],"цикл":["russian"],"цилиндр":["russian"],"цирк":["russian"],"цитата":["russian"],"цифра":["russian"],"чайник":["russian"],"часы":["russian"],"чашка":["russian"],"человек":["russian"],"челюсть":["russian"],"чемодан":["russian"],"чемпион":["russian"],"чепуха":["russian"],"червь":["russian"],"чердак":["russian"],"через":["russian"],"чернила":["russian"],"черта":["russian"],"чеснок":["russian"],"честно":["russian"],"четверть":["russian"],"четыре":["russian"],"число":["russian"],"чистый":["russian"],"читатель":["russian"],"чтение":["russian"],"чтобы":["russian"],"чувство":["russian"],"чудак":["russian"],"чудный":["russian"],"чудо":["russian"],"чужой":["russian"],"чулок":["russian"],"чума":["russian"],"чушь":["russian"],"чуять":["russian"],"шагать":["russian"],"шанс":["russian"],"шапка":["russian"],"шарик":["russian"],"шарф":["russian"],"шахматы":["russian"],"шашлык":["russian"],"шедевр":["russian"],"шептать":["russian"],"шерсть":["russian"],"шестой":["russian"],"шинель":["russian"],"ширина":["russian"],"шишка":["russian"],"шкаф":["russian"],"школа":["russian"],"шкура":["russian"],"шланг":["russian"],"шлем":["russian"],"шнур":["russian"],"шоколад":["russian"],"шорох":["russian"],"шоссе":["russian"],"шпион":["russian"],"шприц":["russian"],"штаб":["russian"],"штамм":["russian"],"штаны":["russian"],"штатный":["russian"],"штора":["russian"],"штраф":["russian"],"штурм":["russian"],"штык":["russian"],"шумно":["russian"],"шуршать":["russian"],"шутить":["russian"],"шутка":["russian"],"щедрый":["russian"],"щека":["russian"],"щенок":["russian"],"экзамен":["russian"],"экипаж":["russian"],"экономия":["russian"],"экран":["russian"],"эксперт":["russian"],"элемент":["russian"],"элитный":["russian"],"эмоция":["russian"],"энергия":["russian"],"эпизод":["russian"],"эпоха":["russian"],"эскиз":["russian"],"эстрада":["russian"],"этап":["russian"],"этика":["russian"],"этот":["russian"],"эфир":["russian"],"эффект":["russian"],"эшелон":["russian"],"юбилей":["russian"],"юбка":["russian"],"южный":["russian"],"юмор":["russian"],"юность":["russian"],"юрист":["russian"],"юстиция":["russian"],"яблоко":["russian"],"явление":["russian"],"ягода":["russian"],"ядро":["russian"],"язык":["russian"],"яйцо":["russian"],"якобы":["russian"],"якорь":["russian"],"январь":["russian"],"яркий":["russian"],"ярмарка":["russian"],"ярость":["russian"],"ясный":["russian"],"яхта":["russian"],"ячейка":["russian"],"ящик":["russian"],"ábaco":["spanish"],"abdomen":["spanish"],"abeja":["spanish"],"abierto":["spanish"],"abogado":["spanish"],"abono":["spanish"],"aborto":["spanish"],"abrazo":["spanish"],"abrir":["spanish"],"abuelo":["spanish"],"abuso":["spanish"],"acabar":["spanish"],"academia":["spanish"],"acceso":["spanish"],"acción":["spanish"],"aceite":["spanish"],"acelga":["spanish"],"acento":["spanish"],"aceptar":["spanish"],"ácido":["spanish"],"aclarar":["spanish"],"acné":["spanish"],"acoger":["spanish"],"acoso":["spanish"],"activo":["spanish"],"acto":["spanish"],"actriz":["spanish"],"actuar":["spanish"],"acudir":["spanish"],"acuerdo":["spanish"],"acusar":["spanish"],"adicto":["spanish"],"admitir":["spanish"],"adoptar":["spanish"],"adorno":["spanish"],"aduana":["spanish"],"adulto":["spanish"],"aéreo":["spanish"],"afectar":["spanish"],"afición":["spanish"],"afinar":["spanish"],"afirmar":["spanish"],"ágil":["spanish"],"agitar":["spanish"],"agonía":["spanish"],"agosto":["spanish"],"agotar":["spanish"],"agregar":["spanish"],"agrio":["spanish"],"agua":["spanish"],"agudo":["spanish"],"águila":["spanish"],"aguja":["spanish"],"ahogo":["spanish"],"ahorro":["spanish"],"aire":["spanish"],"aislar":["spanish"],"ajedrez":["spanish"],"ajeno":["spanish"],"ajuste":["spanish"],"alacrán":["spanish"],"alambre":["spanish"],"alarma":["spanish"],"alba":["spanish"],"álbum":["spanish"],"alcalde":["spanish"],"aldea":["spanish"],"alegre":["spanish"],"alejar":["spanish"],"alerta":["spanish"],"aleta":["spanish"],"alfiler":["spanish"],"alga":["spanish"],"algodón":["spanish"],"aliado":["spanish"],"aliento":["spanish"],"alivio":["spanish"],"alma":["spanish"],"almeja":["spanish"],"almíbar":["spanish"],"altar":["spanish"],"alteza":["spanish"],"altivo":["spanish"],"alto":["spanish"],"altura":["spanish"],"alumno":["spanish"],"alzar":["spanish"],"amable":["spanish"],"amante":["spanish"],"amapola":["spanish"],"amargo":["spanish"],"amasar":["spanish"],"ámbar":["spanish"],"ámbito":["spanish"],"ameno":["spanish"],"amigo":["spanish","turkish"],"amistad":["spanish"],"amor":["spanish"],"amparo":["spanish"],"amplio":["spanish"],"ancho":["spanish"],"anciano":["spanish"],"ancla":["spanish"],"andar":["spanish"],"andén":["spanish"],"anemia":["spanish"],"ángulo":["spanish"],"anillo":["spanish"],"ánimo":["spanish"],"anís":["spanish"],"anotar":["spanish"],"antena":["spanish"],"antiguo":["spanish"],"antojo":["spanish"],"anual":["spanish"],"anular":["spanish"],"anuncio":["spanish"],"añadir":["spanish"],"añejo":["spanish"],"año":["spanish"],"apagar":["spanish"],"aparato":["spanish"],"apetito":["spanish"],"apio":["spanish"],"aplicar":["spanish"],"apodo":["spanish"],"aporte":["spanish"],"apoyo":["spanish"],"aprender":["spanish"],"aprobar":["spanish"],"apuesta":["spanish"],"apuro":["spanish"],"arado":["spanish"],"araña":["spanish"],"arar":["spanish"],"árbitro":["spanish"],"árbol":["spanish"],"arbusto":["spanish"],"archivo":["spanish"],"arco":["spanish"],"arder":["spanish"],"ardilla":["spanish"],"arduo":["spanish"],"área":["spanish"],"árido":["spanish"],"aries":["spanish"],"armonía":["spanish"],"arnés":["spanish"],"aroma":["spanish","turkish"],"arpa":["spanish"],"arpón":["spanish"],"arreglo":["spanish"],"arroz":["spanish"],"arruga":["spanish"],"arte":["spanish"],"artista":["spanish"],"asa":["spanish"],"asado":["spanish"],"asalto":["spanish"],"ascenso":["spanish"],"asegurar":["spanish"],"aseo":["spanish"],"asesor":["spanish"],"asiento":["spanish"],"asilo":["spanish"],"asistir":["spanish"],"asno":["spanish"],"asombro":["spanish"],"áspero":["spanish"],"astilla":["spanish"],"astro":["spanish"],"astuto":["spanish"],"asumir":["spanish"],"asunto":["spanish"],"atajo":["spanish"],"ataque":["spanish"],"atar":["spanish"],"atento":["spanish"],"ateo":["spanish"],"ático":["spanish"],"atleta":["spanish"],"átomo":["spanish"],"atraer":["spanish"],"atroz":["spanish"],"atún":["spanish"],"audaz":["spanish"],"audio":["spanish"],"auge":["spanish"],"aula":["spanish"],"aumento":["spanish"],"ausente":["spanish"],"autor":["spanish"],"aval":["spanish"],"avance":["spanish"],"avaro":["spanish"],"ave":["spanish"],"avellana":["spanish"],"avena":["spanish"],"avestruz":["spanish"],"avión":["spanish"],"aviso":["spanish"],"ayer":["spanish"],"ayuda":["spanish"],"ayuno":["spanish"],"azafrán":["spanish"],"azar":["spanish"],"azote":["spanish"],"azúcar":["spanish"],"azufre":["spanish"],"azul":["spanish"],"baba":["spanish"],"babor":["spanish"],"bache":["spanish"],"bahía":["spanish"],"baile":["spanish"],"bajar":["spanish"],"balanza":["spanish"],"balcón":["spanish"],"balde":["spanish"],"bambú":["spanish"],"banco":["spanish"],"banda":["spanish"],"baño":["spanish"],"barba":["spanish"],"barco":["spanish"],"barniz":["spanish"],"barro":["spanish"],"báscula":["spanish"],"bastón":["spanish"],"basura":["spanish"],"batalla":["spanish"],"batería":["spanish"],"batir":["spanish"],"batuta":["spanish"],"baúl":["spanish"],"bazar":["spanish"],"bebé":["spanish"],"bebida":["spanish"],"bello":["spanish"],"besar":["spanish"],"beso":["spanish"],"bestia":["spanish"],"bicho":["spanish"],"bien":["spanish"],"bingo":["spanish"],"blanco":["spanish"],"bloque":["spanish"],"blusa":["spanish"],"boa":["spanish"],"bobina":["spanish"],"bobo":["spanish"],"boca":["spanish"],"bocina":["spanish"],"boda":["spanish"],"bodega":["spanish"],"boina":["spanish"],"bola":["spanish"],"bolero":["spanish","turkish"],"bolsa":["spanish"],"bomba":["spanish"],"bondad":["spanish"],"bonito":["spanish"],"bono":["spanish"],"bonsái":["spanish"],"borde":["spanish"],"borrar":["spanish"],"bosque":["spanish"],"bote":["spanish"],"botín":["spanish"],"bóveda":["spanish"],"bozal":["spanish"],"bravo":["spanish"],"brazo":["spanish"],"brecha":["spanish"],"breve":["spanish"],"brillo":["spanish"],"brinco":["spanish"],"brisa":["spanish"],"broca":["spanish"],"broma":["spanish"],"bronce":["spanish"],"brote":["spanish"],"bruja":["spanish"],"brusco":["spanish"],"bruto":["spanish"],"buceo":["spanish"],"bucle":["spanish"],"bueno":["spanish"],"buey":["spanish"],"bufanda":["spanish"],"bufón":["spanish"],"búho":["spanish"],"buitre":["spanish"],"bulto":["spanish"],"burbuja":["spanish"],"burla":["spanish"],"burro":["spanish"],"buscar":["spanish"],"butaca":["spanish"],"buzón":["spanish"],"caballo":["spanish"],"cabeza":["spanish"],"cabina":["spanish"],"cabra":["spanish"],"cacao":["spanish"],"cadáver":["spanish"],"cadena":["spanish"],"caer":["spanish"],"café":["spanish"],"caída":["spanish"],"caimán":["spanish"],"caja":["spanish"],"cajón":["spanish"],"cal":["spanish"],"calamar":["spanish"],"calcio":["spanish"],"caldo":["spanish"],"calidad":["spanish"],"calle":["spanish"],"calma":["spanish"],"calor":["spanish"],"calvo":["spanish"],"cama":["spanish"],"cambio":["spanish"],"camello":["spanish"],"camino":["spanish"],"campo":["spanish"],"cáncer":["spanish"],"candil":["spanish"],"canela":["spanish"],"canguro":["spanish"],"canica":["spanish"],"canto":["spanish"],"caña":["spanish"],"cañón":["spanish"],"caoba":["spanish"],"caos":["spanish"],"capaz":["spanish"],"capitán":["spanish"],"capote":["spanish"],"captar":["spanish"],"capucha":["spanish"],"cara":["spanish"],"carbón":["spanish"],"cárcel":["spanish"],"careta":["spanish"],"carga":["spanish"],"cariño":["spanish"],"carne":["spanish"],"carpeta":["spanish"],"carro":["spanish"],"carta":["spanish"],"casa":["spanish"],"casco":["spanish"],"casero":["spanish"],"caspa":["spanish"],"castor":["spanish"],"catorce":["spanish"],"catre":["spanish"],"caudal":["spanish"],"causa":["spanish"],"cazo":["spanish"],"cebolla":["spanish"],"ceder":["spanish"],"cedro":["spanish"],"celda":["spanish"],"célebre":["spanish"],"celoso":["spanish"],"célula":["spanish"],"cemento":["spanish"],"ceniza":["spanish"],"centro":["spanish"],"cerca":["spanish"],"cerdo":["spanish"],"cereza":["spanish"],"cero":["spanish"],"cerrar":["spanish"],"certeza":["spanish"],"césped":["spanish"],"cetro":["spanish"],"chacal":["spanish"],"chaleco":["spanish"],"champú":["spanish"],"chancla":["spanish"],"chapa":["spanish"],"charla":["spanish"],"chico":["spanish"],"chiste":["spanish"],"chivo":["spanish"],"choque":["spanish"],"choza":["spanish"],"chuleta":["spanish"],"chupar":["spanish"],"ciclón":["spanish"],"ciego":["spanish"],"cielo":["spanish"],"cien":["spanish"],"cierto":["spanish"],"cifra":["spanish"],"cigarro":["spanish"],"cima":["spanish"],"cinco":["spanish"],"cine":["spanish"],"cinta":["spanish"],"ciprés":["spanish"],"circo":["spanish"],"ciruela":["spanish"],"cisne":["spanish"],"cita":["spanish"],"ciudad":["spanish"],"clamor":["spanish"],"clan":["spanish"],"claro":["spanish"],"clase":["spanish"],"clave":["spanish"],"cliente":["spanish"],"clima":["spanish"],"clínica":["spanish"],"cobre":["spanish"],"cocción":["spanish"],"cochino":["spanish"],"cocina":["spanish"],"coco":["spanish"],"código":["spanish"],"codo":["spanish"],"cofre":["spanish"],"coger":["spanish"],"cohete":["spanish"],"cojín":["spanish"],"cojo":["spanish"],"cola":["spanish"],"colcha":["spanish"],"colegio":["spanish"],"colgar":["spanish"],"colina":["spanish"],"collar":["spanish"],"colmo":["spanish"],"columna":["spanish"],"combate":["spanish"],"comer":["spanish"],"comida":["spanish"],"cómodo":["spanish"],"compra":["spanish"],"conde":["spanish"],"conejo":["spanish"],"conga":["spanish"],"conocer":["spanish"],"consejo":["spanish"],"contar":["spanish"],"copa":["spanish"],"copia":["spanish"],"corazón":["spanish"],"corbata":["spanish"],"corcho":["spanish"],"cordón":["spanish"],"corona":["spanish"],"correr":["spanish"],"coser":["spanish"],"cosmos":["spanish"],"costa":["spanish"],"cráneo":["spanish"],"cráter":["spanish"],"crear":["spanish"],"crecer":["spanish"],"creído":["spanish"],"crema":["spanish"],"cría":["spanish"],"crimen":["spanish"],"cripta":["spanish"],"crisis":["spanish"],"cromo":["spanish"],"crónica":["spanish"],"croqueta":["spanish"],"crudo":["spanish"],"cruz":["spanish"],"cuadro":["spanish"],"cuarto":["spanish"],"cuatro":["spanish"],"cubo":["spanish"],"cubrir":["spanish"],"cuchara":["spanish"],"cuello":["spanish"],"cuento":["spanish"],"cuerda":["spanish"],"cuesta":["spanish"],"cueva":["spanish"],"cuidar":["spanish"],"culebra":["spanish"],"culpa":["spanish"],"culto":["spanish"],"cumbre":["spanish"],"cumplir":["spanish"],"cuna":["spanish"],"cuneta":["spanish"],"cuota":["spanish"],"cupón":["spanish"],"cúpula":["spanish"],"curar":["spanish"],"curioso":["spanish"],"curso":["spanish"],"curva":["spanish"],"cutis":["spanish"],"dama":["spanish"],"danza":["spanish"],"dar":["spanish"],"dardo":["spanish"],"dátil":["spanish"],"deber":["spanish"],"débil":["spanish"],"década":["spanish"],"decir":["spanish"],"dedo":["spanish"],"defensa":["spanish"],"definir":["spanish"],"dejar":["spanish"],"delfín":["spanish"],"delgado":["spanish"],"delito":["spanish"],"demora":["spanish"],"denso":["spanish"],"dental":["spanish"],"deporte":["spanish"],"derecho":["spanish"],"derrota":["spanish"],"desayuno":["spanish"],"deseo":["spanish"],"desfile":["spanish"],"desnudo":["spanish"],"destino":["spanish"],"desvío":["spanish"],"detalle":["spanish"],"detener":["spanish"],"deuda":["spanish"],"día":["spanish"],"diablo":["spanish"],"diadema":["spanish"],"diamante":["spanish"],"diana":["spanish"],"diario":["spanish"],"dibujo":["spanish"],"dictar":["spanish"],"diente":["spanish"],"dieta":["spanish"],"diez":["spanish"],"difícil":["spanish"],"digno":["spanish"],"dilema":["spanish"],"diluir":["spanish"],"dinero":["spanish"],"directo":["spanish"],"dirigir":["spanish"],"disco":["spanish"],"diseño":["spanish"],"disfraz":["spanish"],"diva":["spanish"],"divino":["spanish"],"doble":["spanish"],"doce":["spanish"],"dolor":["spanish"],"domingo":["spanish"],"don":["spanish"],"donar":["spanish"],"dorado":["spanish"],"dormir":["spanish"],"dorso":["spanish"],"dos":["spanish"],"dosis":["spanish"],"dragón":["spanish"],"droga":["spanish"],"ducha":["spanish"],"duda":["spanish"],"duelo":["spanish"],"dueño":["spanish"],"dulce":["spanish"],"dúo":["spanish"],"duque":["spanish"],"durar":["spanish"],"dureza":["spanish"],"duro":["spanish"],"ébano":["spanish"],"ebrio":["spanish"],"echar":["spanish"],"eco":["spanish"],"ecuador":["spanish"],"edad":["spanish"],"edición":["spanish"],"edificio":["spanish"],"editor":["spanish"],"educar":["spanish"],"efecto":["spanish"],"eficaz":["spanish"],"eje":["spanish"],"ejemplo":["spanish"],"elefante":["spanish"],"elegir":["spanish"],"elemento":["spanish"],"elevar":["spanish"],"elipse":["spanish"],"élite":["spanish"],"elixir":["spanish"],"elogio":["spanish"],"eludir":["spanish"],"embudo":["spanish"],"emitir":["spanish"],"emoción":["spanish"],"empate":["spanish"],"empeño":["spanish"],"empleo":["spanish"],"empresa":["spanish"],"enano":["spanish"],"encargo":["spanish"],"enchufe":["spanish"],"encía":["spanish"],"enemigo":["spanish"],"enero":["spanish"],"enfado":["spanish"],"enfermo":["spanish"],"engaño":["spanish"],"enigma":["spanish"],"enlace":["spanish"],"enorme":["spanish"],"enredo":["spanish"],"ensayo":["spanish"],"enseñar":["spanish"],"entero":["spanish"],"entrar":["spanish"],"envase":["spanish"],"envío":["spanish"],"época":["spanish"],"equipo":["spanish"],"erizo":["spanish"],"escala":["spanish"],"escena":["spanish"],"escolar":["spanish"],"escribir":["spanish"],"escudo":["spanish"],"esencia":["spanish"],"esfera":["spanish"],"esfuerzo":["spanish"],"espada":["spanish"],"espejo":["spanish"],"espía":["spanish"],"esposa":["spanish"],"espuma":["spanish"],"esquí":["spanish"],"estar":["spanish"],"este":["spanish"],"estilo":["spanish"],"estufa":["spanish"],"etapa":["spanish"],"eterno":["spanish"],"ética":["spanish"],"etnia":["spanish"],"evadir":["spanish"],"evaluar":["spanish"],"evento":["spanish"],"evitar":["spanish"],"exacto":["spanish"],"examen":["spanish"],"exceso":["spanish"],"excusa":["spanish"],"exento":["spanish"],"exigir":["spanish"],"exilio":["spanish"],"existir":["spanish"],"éxito":["spanish"],"experto":["spanish"],"explicar":["spanish"],"exponer":["spanish"],"extremo":["spanish"],"fábrica":["spanish"],"fábula":["spanish"],"fachada":["spanish"],"fácil":["spanish"],"factor":["spanish"],"faena":["spanish"],"faja":["spanish"],"falda":["spanish"],"fallo":["spanish"],"falso":["spanish"],"faltar":["spanish"],"fama":["spanish"],"familia":["spanish"],"famoso":["spanish"],"faraón":["spanish"],"farmacia":["spanish"],"farol":["spanish"],"farsa":["spanish"],"fase":["spanish"],"fatiga":["spanish"],"fauna":["spanish","turkish"],"favor":["spanish"],"fax":["spanish"],"febrero":["spanish"],"fecha":["spanish"],"feliz":["spanish"],"feo":["spanish"],"feria":["spanish"],"feroz":["spanish"],"fértil":["spanish"],"fervor":["spanish"],"festín":["spanish"],"fiable":["spanish"],"fianza":["spanish"],"fiar":["spanish"],"fibra":["spanish"],"ficción":["spanish"],"ficha":["spanish"],"fideo":["spanish"],"fiebre":["spanish"],"fiel":["spanish"],"fiera":["spanish"],"fiesta":["spanish"],"figura":["spanish"],"fijar":["spanish"],"fijo":["spanish"],"fila":["spanish"],"filete":["spanish"],"filial":["spanish"],"filtro":["spanish"],"fin":["spanish"],"finca":["spanish"],"fingir":["spanish"],"finito":["spanish"],"firma":["spanish"],"flaco":["spanish"],"flauta":["spanish"],"flecha":["spanish"],"flor":["spanish"],"flota":["spanish"],"fluir":["spanish"],"flujo":["spanish"],"flúor":["spanish"],"fobia":["spanish"],"foca":["spanish"],"fogata":["spanish"],"fogón":["spanish"],"folio":["spanish"],"folleto":["spanish"],"fondo":["spanish"],"forma":["spanish"],"forro":["spanish"],"fortuna":["spanish"],"forzar":["spanish"],"fosa":["spanish"],"foto":["spanish"],"fracaso":["spanish"],"frágil":["spanish"],"franja":["spanish"],"frase":["spanish"],"fraude":["spanish"],"freír":["spanish"],"freno":["spanish"],"fresa":["spanish"],"frío":["spanish"],"frito":["spanish"],"fruta":["spanish"],"fuego":["spanish"],"fuente":["spanish"],"fuerza":["spanish"],"fuga":["spanish"],"fumar":["spanish"],"función":["spanish"],"funda":["spanish"],"furgón":["spanish"],"furia":["spanish"],"fusil":["spanish"],"fútbol":["spanish"],"futuro":["spanish"],"gacela":["spanish"],"gafas":["spanish"],"gaita":["spanish"],"gajo":["spanish"],"gala":["spanish"],"galería":["spanish"],"gallo":["spanish"],"gamba":["spanish"],"ganar":["spanish"],"gancho":["spanish"],"ganga":["spanish"],"ganso":["spanish"],"garaje":["spanish"],"garza":["spanish"],"gasolina":["spanish"],"gastar":["spanish"],"gato":["spanish"],"gavilán":["spanish"],"gemelo":["spanish"],"gemir":["spanish"],"gen":["spanish"],"género":["spanish"],"genio":["spanish"],"gente":["spanish"],"geranio":["spanish"],"gerente":["spanish"],"germen":["spanish"],"gesto":["spanish"],"gigante":["spanish"],"gimnasio":["spanish"],"girar":["spanish"],"giro":["spanish"],"glaciar":["spanish"],"globo":["spanish"],"gloria":["spanish"],"gol":["spanish"],"golfo":["spanish"],"goloso":["spanish"],"golpe":["spanish"],"goma":["spanish"],"gordo":["spanish"],"gorila":["spanish"],"gorra":["spanish"],"gota":["spanish"],"goteo":["spanish"],"gozar":["spanish"],"grada":["spanish"],"gráfico":["spanish"],"grano":["spanish"],"grasa":["spanish"],"gratis":["spanish"],"grave":["spanish"],"grieta":["spanish"],"grillo":["spanish"],"gripe":["spanish"],"gris":["spanish"],"grito":["spanish"],"grosor":["spanish"],"grúa":["spanish"],"grueso":["spanish"],"grumo":["spanish"],"grupo":["spanish"],"guante":["spanish"],"guapo":["spanish"],"guardia":["spanish"],"guerra":["spanish"],"guía":["spanish"],"guiño":["spanish"],"guion":["spanish"],"guiso":["spanish"],"guitarra":["spanish"],"gusano":["spanish"],"gustar":["spanish"],"haber":["spanish","turkish"],"hábil":["spanish"],"hablar":["spanish"],"hacer":["spanish"],"hacha":["spanish"],"hada":["spanish"],"hallar":["spanish"],"hamaca":["spanish"],"harina":["spanish"],"haz":["spanish"],"hazaña":["spanish"],"hebilla":["spanish"],"hebra":["spanish"],"hecho":["spanish"],"helado":["spanish"],"helio":["spanish"],"hembra":["spanish"],"herir":["spanish"],"hermano":["spanish"],"héroe":["spanish"],"hervir":["spanish"],"hielo":["spanish"],"hierro":["spanish"],"hígado":["spanish"],"higiene":["spanish"],"hijo":["spanish"],"himno":["spanish"],"historia":["spanish"],"hocico":["spanish"],"hogar":["spanish"],"hoguera":["spanish"],"hoja":["spanish"],"hombre":["spanish"],"hongo":["spanish"],"honor":["spanish"],"honra":["spanish"],"hora":["spanish"],"hormiga":["spanish"],"horno":["spanish"],"hostil":["spanish"],"hoyo":["spanish"],"hueco":["spanish"],"huelga":["spanish"],"huerta":["spanish"],"hueso":["spanish"],"huevo":["spanish"],"huida":["spanish"],"huir":["spanish"],"humano":["spanish"],"húmedo":["spanish"],"humilde":["spanish"],"humo":["spanish"],"hundir":["spanish"],"huracán":["spanish"],"hurto":["spanish"],"icono":["spanish"],"ideal":["spanish"],"idioma":["spanish"],"ídolo":["spanish"],"iglesia":["spanish"],"iglú":["spanish"],"igual":["spanish"],"ilegal":["spanish"],"ilusión":["spanish"],"imagen":["spanish"],"imán":["spanish"],"imitar":["spanish"],"impar":["spanish"],"imperio":["spanish"],"imponer":["spanish"],"impulso":["spanish"],"incapaz":["spanish"],"índice":["spanish"],"inerte":["spanish"],"infiel":["spanish"],"informe":["spanish"],"ingenio":["spanish"],"inicio":["spanish"],"inmenso":["spanish"],"inmune":["spanish"],"innato":["spanish"],"insecto":["spanish"],"instante":["spanish"],"interés":["spanish"],"íntimo":["spanish"],"intuir":["spanish"],"inútil":["spanish"],"invierno":["spanish"],"ira":["spanish"],"iris":["spanish"],"ironía":["spanish"],"isla":["spanish"],"islote":["spanish"],"jabalí":["spanish"],"jabón":["spanish"],"jamón":["spanish"],"jarabe":["spanish"],"jardín":["spanish"],"jarra":["spanish"],"jaula":["spanish"],"jazmín":["spanish"],"jefe":["spanish"],"jeringa":["spanish"],"jinete":["spanish"],"jornada":["spanish"],"joroba":["spanish"],"joven":["spanish"],"joya":["spanish"],"juerga":["spanish"],"jueves":["spanish"],"juez":["spanish"],"jugador":["spanish"],"jugo":["spanish"],"juguete":["spanish"],"juicio":["spanish"],"junco":["spanish"],"jungla":["spanish"],"junio":["spanish"],"juntar":["spanish"],"júpiter":["spanish"],"jurar":["spanish"],"justo":["spanish"],"juvenil":["spanish"],"juzgar":["spanish"],"kilo":["spanish"],"koala":["spanish"],"labio":["spanish"],"lacio":["spanish"],"lacra":["spanish"],"lado":["spanish"],"ladrón":["spanish"],"lagarto":["spanish"],"lágrima":["spanish"],"laguna":["spanish"],"laico":["spanish"],"lamer":["spanish"],"lámina":["spanish"],"lámpara":["spanish"],"lana":["spanish"],"lancha":["spanish"],"langosta":["spanish"],"lanza":["spanish"],"lápiz":["spanish"],"largo":["spanish"],"larva":["spanish"],"lástima":["spanish"],"lata":["spanish"],"látex":["spanish"],"latir":["spanish"],"laurel":["spanish"],"lavar":["spanish"],"lazo":["spanish"],"leal":["spanish"],"lección":["spanish"],"leche":["spanish"],"lector":["spanish"],"leer":["spanish"],"legión":["spanish"],"legumbre":["spanish"],"lejano":["spanish"],"lengua":["spanish"],"lento":["spanish"],"leña":["spanish"],"león":["spanish"],"leopardo":["spanish"],"lesión":["spanish"],"letal":["spanish"],"letra":["spanish"],"leve":["spanish"],"leyenda":["spanish"],"libertad":["spanish"],"libro":["spanish"],"licor":["spanish"],"líder":["spanish"],"lidiar":["spanish"],"lienzo":["spanish"],"liga":["spanish"],"ligero":["spanish"],"lima":["spanish"],"límite":["spanish"],"limón":["spanish"],"limpio":["spanish"],"lince":["spanish"],"lindo":["spanish"],"línea":["spanish"],"lingote":["spanish"],"lino":["spanish"],"linterna":["spanish"],"líquido":["spanish"],"liso":["spanish"],"lista":["spanish"],"litera":["spanish"],"litio":["spanish"],"litro":["spanish"],"llaga":["spanish"],"llama":["spanish"],"llanto":["spanish"],"llave":["spanish"],"llegar":["spanish"],"llenar":["spanish"],"llevar":["spanish"],"llorar":["spanish"],"llover":["spanish"],"lluvia":["spanish"],"lobo":["spanish"],"loción":["spanish"],"loco":["spanish"],"locura":["spanish"],"lógica":["spanish"],"logro":["spanish"],"lombriz":["spanish"],"lomo":["spanish"],"lonja":["spanish"],"lote":["spanish"],"lucha":["spanish"],"lucir":["spanish"],"lugar":["spanish"],"lujo":["spanish"],"luna":["spanish"],"lunes":["spanish"],"lupa":["spanish"],"lustro":["spanish"],"luto":["spanish"],"luz":["spanish"],"maceta":["spanish"],"macho":["spanish"],"madera":["spanish"],"madre":["spanish"],"maduro":["spanish"],"maestro":["spanish"],"mafia":["spanish"],"magia":["spanish"],"mago":["spanish"],"maíz":["spanish"],"maldad":["spanish"],"maleta":["spanish"],"malla":["spanish"],"malo":["spanish"],"mamá":["spanish"],"mambo":["spanish"],"mamut":["spanish"],"manco":["spanish"],"mando":["spanish"],"manejar":["spanish"],"manga":["spanish"],"maniquí":["spanish"],"manjar":["spanish"],"mano":["spanish"],"manso":["spanish"],"manta":["spanish"],"mañana":["spanish"],"mapa":["spanish"],"máquina":["spanish"],"mar":["spanish"],"marco":["spanish"],"marea":["spanish"],"marfil":["spanish"],"margen":["spanish"],"marido":["spanish"],"mármol":["spanish"],"marrón":["spanish"],"martes":["spanish"],"marzo":["spanish"],"masa":["spanish"],"máscara":["spanish"],"masivo":["spanish"],"matar":["spanish"],"materia":["spanish"],"matiz":["spanish"],"matriz":["spanish"],"máximo":["spanish"],"mayor":["spanish"],"mazorca":["spanish"],"mecha":["spanish"],"medalla":["spanish"],"medio":["spanish"],"médula":["spanish"],"mejilla":["spanish"],"mejor":["spanish"],"melena":["spanish"],"melón":["spanish"],"memoria":["spanish"],"menor":["spanish"],"mensaje":["spanish"],"mente":["spanish"],"menú":["spanish"],"mercado":["spanish"],"merengue":["spanish"],"mérito":["spanish"],"mes":["spanish"],"mesón":["spanish"],"meta":["spanish"],"meter":["spanish"],"método":["spanish"],"metro":["spanish"],"mezcla":["spanish"],"miedo":["spanish"],"miel":["spanish"],"miembro":["spanish"],"miga":["spanish"],"mil":["spanish"],"milagro":["spanish"],"militar":["spanish"],"millón":["spanish"],"mimo":["spanish"],"mina":["spanish"],"minero":["spanish"],"mínimo":["spanish"],"minuto":["spanish"],"miope":["spanish"],"mirar":["spanish"],"misa":["spanish"],"miseria":["spanish"],"misil":["spanish"],"mismo":["spanish"],"mitad":["spanish"],"mito":["spanish"],"mochila":["spanish"],"moción":["spanish"],"moda":["spanish"],"modelo":["spanish"],"moho":["spanish"],"mojar":["spanish"],"molde":["spanish"],"moler":["spanish"],"molino":["spanish"],"momento":["spanish"],"momia":["spanish"],"monarca":["spanish"],"moneda":["spanish"],"monja":["spanish"],"monto":["spanish"],"moño":["spanish"],"morada":["spanish"],"morder":["spanish"],"moreno":["spanish"],"morir":["spanish"],"morro":["spanish"],"morsa":["spanish"],"mortal":["spanish"],"mosca":["spanish"],"mostrar":["spanish"],"motivo":["spanish"],"mover":["spanish"],"móvil":["spanish"],"mozo":["spanish"],"mucho":["spanish"],"mudar":["spanish"],"mueble":["spanish"],"muela":["spanish"],"muerte":["spanish"],"muestra":["spanish"],"mugre":["spanish"],"mujer":["spanish"],"mula":["spanish"],"muleta":["spanish"],"multa":["spanish"],"mundo":["spanish"],"muñeca":["spanish"],"mural":["spanish"],"muro":["spanish"],"músculo":["spanish"],"museo":["spanish"],"musgo":["spanish"],"música":["spanish"],"muslo":["spanish"],"nácar":["spanish"],"nación":["spanish"],"nadar":["spanish"],"naipe":["spanish"],"naranja":["spanish"],"nariz":["spanish"],"narrar":["spanish"],"nasal":["spanish"],"natal":["spanish"],"nativo":["spanish"],"natural":["spanish"],"náusea":["spanish"],"naval":["spanish"],"nave":["spanish"],"navidad":["spanish"],"necio":["spanish"],"néctar":["spanish"],"negar":["spanish"],"negocio":["spanish"],"negro":["spanish"],"neón":["spanish"],"nervio":["spanish"],"neto":["spanish"],"neutro":["spanish"],"nevar":["spanish"],"nevera":["spanish"],"nicho":["spanish"],"nido":["spanish"],"niebla":["spanish"],"nieto":["spanish"],"niñez":["spanish"],"niño":["spanish"],"nítido":["spanish"],"nivel":["spanish"],"nobleza":["spanish"],"noche":["spanish"],"nómina":["spanish"],"noria":["spanish"],"norma":["spanish"],"norte":["spanish"],"nota":["spanish"],"noticia":["spanish"],"novato":["spanish"],"novela":["spanish"],"novio":["spanish"],"nube":["spanish"],"nuca":["spanish"],"núcleo":["spanish"],"nudillo":["spanish"],"nudo":["spanish"],"nuera":["spanish"],"nueve":["spanish"],"nuez":["spanish"],"nulo":["spanish"],"número":["spanish"],"nutria":["spanish"],"oasis":["spanish"],"obeso":["spanish"],"obispo":["spanish"],"objeto":["spanish"],"obra":["spanish"],"obrero":["spanish"],"observar":["spanish"],"obtener":["spanish"],"obvio":["spanish"],"oca":["spanish"],"ocaso":["spanish"],"océano":["spanish"],"ochenta":["spanish"],"ocho":["spanish"],"ocio":["spanish"],"ocre":["spanish"],"octavo":["spanish"],"octubre":["spanish"],"oculto":["spanish"],"ocupar":["spanish"],"ocurrir":["spanish"],"odiar":["spanish"],"odio":["spanish"],"odisea":["spanish"],"oeste":["spanish"],"ofensa":["spanish"],"oferta":["spanish"],"oficio":["spanish"],"ofrecer":["spanish"],"ogro":["spanish"],"oído":["spanish"],"oír":["spanish"],"ojo":["spanish"],"ola":["spanish"],"oleada":["spanish"],"olfato":["spanish"],"olivo":["spanish"],"olla":["spanish"],"olmo":["spanish"],"olor":["spanish"],"olvido":["spanish"],"ombligo":["spanish"],"onda":["spanish"],"onza":["spanish"],"opaco":["spanish"],"opción":["spanish"],"ópera":["spanish"],"opinar":["spanish"],"oponer":["spanish"],"optar":["spanish"],"óptica":["spanish"],"opuesto":["spanish"],"oración":["spanish"],"orador":["spanish"],"oral":["spanish","turkish"],"órbita":["spanish"],"orca":["spanish"],"orden":["spanish"],"oreja":["spanish"],"órgano":["spanish"],"orgía":["spanish"],"orgullo":["spanish"],"oriente":["spanish"],"origen":["spanish"],"orilla":["spanish"],"oro":["spanish"],"orquesta":["spanish"],"oruga":["spanish"],"osadía":["spanish"],"oscuro":["spanish"],"osezno":["spanish"],"oso":["spanish"],"ostra":["spanish"],"otoño":["spanish"],"otro":["spanish"],"oveja":["spanish"],"óvulo":["spanish"],"óxido":["spanish"],"oxígeno":["spanish"],"oyente":["spanish"],"ozono":["spanish"],"pacto":["spanish"],"padre":["spanish"],"paella":["spanish"],"página":["spanish"],"pago":["spanish"],"país":["spanish"],"pájaro":["spanish"],"palabra":["spanish"],"palco":["spanish"],"paleta":["spanish"],"pálido":["spanish"],"palma":["spanish"],"paloma":["spanish"],"palpar":["spanish"],"pan":["spanish"],"panal":["spanish"],"pánico":["spanish"],"pantera":["spanish"],"pañuelo":["spanish"],"papá":["spanish"],"papel":["spanish"],"papilla":["spanish"],"paquete":["spanish"],"parar":["spanish"],"parcela":["spanish"],"pared":["spanish"],"parir":["spanish"],"paro":["spanish"],"párpado":["spanish"],"parque":["spanish"],"párrafo":["spanish"],"parte":["spanish"],"pasar":["spanish"],"paseo":["spanish"],"pasión":["spanish"],"paso":["spanish"],"pasta":["spanish"],"pata":["spanish"],"patio":["spanish"],"patria":["spanish"],"pausa":["spanish"],"pauta":["spanish"],"pavo":["spanish"],"payaso":["spanish"],"peatón":["spanish"],"pecado":["spanish"],"pecera":["spanish"],"pecho":["spanish"],"pedal":["spanish","turkish"],"pedir":["spanish"],"pegar":["spanish"],"peine":["spanish"],"pelar":["spanish"],"peldaño":["spanish"],"pelea":["spanish"],"peligro":["spanish"],"pellejo":["spanish"],"pelo":["spanish"],"peluca":["spanish"],"pena":["spanish","turkish"],"pensar":["spanish"],"peñón":["spanish"],"peón":["spanish"],"peor":["spanish"],"pepino":["spanish"],"pequeño":["spanish"],"pera":["spanish"],"percha":["spanish"],"perder":["spanish"],"pereza":["spanish"],"perfil":["spanish"],"perico":["spanish"],"perla":["spanish"],"permiso":["spanish"],"perro":["spanish"],"persona":["spanish"],"pesa":["spanish"],"pesca":["spanish"],"pésimo":["spanish"],"pestaña":["spanish"],"pétalo":["spanish"],"petróleo":["spanish"],"pez":["spanish"],"pezuña":["spanish"],"picar":["spanish"],"pichón":["spanish"],"pie":["spanish"],"piedra":["spanish"],"pierna":["spanish"],"pieza":["spanish"],"pijama":["spanish"],"pilar":["spanish"],"piloto":["spanish"],"pimienta":["spanish"],"pino":["spanish"],"pintor":["spanish"],"pinza":["spanish"],"piña":["spanish"],"piojo":["spanish"],"pipa":["spanish"],"pirata":["spanish"],"pisar":["spanish"],"piscina":["spanish"],"piso":["spanish"],"pista":["spanish"],"pitón":["spanish"],"pizca":["spanish"],"placa":["spanish"],"plan":["spanish"],"plata":["spanish"],"playa":["spanish"],"plaza":["spanish"],"pleito":["spanish"],"pleno":["spanish"],"plomo":["spanish"],"pluma":["spanish"],"plural":["spanish"],"pobre":["spanish"],"poco":["spanish"],"poder":["spanish"],"podio":["spanish"],"poema":["spanish"],"poesía":["spanish"],"poeta":["spanish"],"polen":["spanish","turkish"],"policía":["spanish"],"pollo":["spanish"],"polvo":["spanish"],"pomada":["spanish"],"pomelo":["spanish"],"pomo":["spanish"],"pompa":["spanish","turkish"],"poner":["spanish"],"porción":["spanish"],"portal":["spanish"],"posada":["spanish"],"poseer":["spanish"],"posible":["spanish"],"poste":["spanish"],"potencia":["spanish"],"potro":["spanish"],"pozo":["spanish"],"prado":["spanish"],"precoz":["spanish"],"pregunta":["spanish"],"premio":["spanish"],"prensa":["spanish"],"preso":["spanish"],"previo":["spanish"],"primo":["spanish"],"príncipe":["spanish"],"prisión":["spanish"],"privar":["spanish"],"proa":["spanish"],"probar":["spanish"],"proceso":["spanish"],"producto":["spanish"],"proeza":["spanish"],"profesor":["spanish"],"programa":["spanish"],"prole":["spanish"],"promesa":["spanish"],"pronto":["spanish"],"propio":["spanish"],"próximo":["spanish"],"prueba":["spanish"],"público":["spanish"],"puchero":["spanish"],"pudor":["spanish"],"pueblo":["spanish"],"puerta":["spanish"],"puesto":["spanish"],"pulga":["spanish"],"pulir":["spanish"],"pulmón":["spanish"],"pulpo":["spanish"],"pulso":["spanish"],"puma":["spanish"],"punto":["spanish"],"puñal":["spanish"],"puño":["spanish"],"pupa":["spanish"],"pupila":["spanish"],"puré":["spanish"],"quedar":["spanish"],"queja":["spanish"],"quemar":["spanish"],"querer":["spanish"],"queso":["spanish"],"quieto":["spanish"],"química":["spanish"],"quince":["spanish"],"quitar":["spanish"],"rábano":["spanish"],"rabia":["spanish"],"rabo":["spanish"],"ración":["spanish"],"radical":["spanish"],"raíz":["spanish"],"rama":["spanish"],"rampa":["spanish","turkish"],"rancho":["spanish"],"rango":["spanish"],"rapaz":["spanish"],"rápido":["spanish"],"rapto":["spanish"],"rasgo":["spanish"],"raspa":["spanish"],"rato":["spanish"],"rayo":["spanish"],"raza":["spanish"],"razón":["spanish"],"reacción":["spanish"],"realidad":["spanish"],"rebaño":["spanish"],"rebote":["spanish"],"recaer":["spanish"],"receta":["spanish"],"rechazo":["spanish"],"recoger":["spanish"],"recreo":["spanish"],"recto":["spanish"],"recurso":["spanish"],"red":["spanish"],"redondo":["spanish"],"reducir":["spanish"],"reflejo":["spanish"],"reforma":["spanish"],"refrán":["spanish"],"refugio":["spanish"],"regalo":["spanish"],"regir":["spanish"],"regla":["spanish"],"regreso":["spanish"],"rehén":["spanish"],"reino":["spanish"],"reír":["spanish"],"reja":["spanish"],"relato":["spanish"],"relevo":["spanish"],"relieve":["spanish"],"relleno":["spanish"],"reloj":["spanish"],"remar":["spanish"],"remedio":["spanish"],"remo":["spanish"],"rencor":["spanish"],"rendir":["spanish"],"renta":["spanish"],"reparto":["spanish"],"repetir":["spanish"],"reposo":["spanish"],"reptil":["spanish"],"res":["spanish"],"rescate":["spanish"],"resina":["spanish"],"respeto":["spanish"],"resto":["spanish"],"resumen":["spanish"],"retiro":["spanish"],"retorno":["spanish"],"retrato":["spanish"],"reunir":["spanish"],"revés":["spanish"],"revista":["spanish"],"rey":["spanish"],"rezar":["spanish"],"rico":["spanish"],"riego":["spanish"],"rienda":["spanish"],"riesgo":["spanish"],"rifa":["spanish"],"rígido":["spanish"],"rigor":["spanish"],"rincón":["spanish"],"riñón":["spanish"],"río":["spanish"],"riqueza":["spanish"],"risa":["spanish"],"ritmo":["spanish"],"rito":["spanish"],"rizo":["spanish"],"roble":["spanish"],"roce":["spanish"],"rociar":["spanish"],"rodar":["spanish"],"rodeo":["spanish"],"rodilla":["spanish"],"roer":["spanish"],"rojizo":["spanish"],"rojo":["spanish"],"romero":["spanish"],"romper":["spanish"],"ron":["spanish"],"ronco":["spanish"],"ronda":["spanish"],"ropa":["spanish"],"ropero":["spanish"],"rosa":["spanish"],"rosca":["spanish"],"rostro":["spanish"],"rotar":["spanish"],"rubí":["spanish"],"rubor":["spanish"],"rudo":["spanish"],"rueda":["spanish"],"rugir":["spanish"],"ruido":["spanish"],"ruina":["spanish"],"ruleta":["spanish"],"rulo":["spanish","turkish"],"rumbo":["spanish"],"rumor":["spanish"],"ruptura":["spanish"],"ruta":["spanish"],"rutina":["spanish"],"sábado":["spanish"],"saber":["spanish"],"sabio":["spanish"],"sable":["spanish"],"sacar":["spanish"],"sagaz":["spanish"],"sagrado":["spanish"],"sala":["spanish"],"saldo":["spanish"],"salero":["spanish"],"salir":["spanish"],"salmón":["spanish"],"salón":["spanish"],"salsa":["spanish"],"salto":["spanish"],"salud":["spanish"],"salvar":["spanish"],"samba":["spanish"],"sanción":["spanish"],"sandía":["spanish"],"sanear":["spanish"],"sangre":["spanish"],"sanidad":["spanish"],"sano":["spanish"],"santo":["spanish"],"sapo":["spanish"],"saque":["spanish"],"sardina":["spanish"],"sartén":["spanish"],"sastre":["spanish"],"satán":["spanish"],"sauna":["spanish"],"saxofón":["spanish"],"sección":["spanish"],"seco":["spanish"],"secreto":["spanish"],"secta":["spanish"],"sed":["spanish"],"seguir":["spanish"],"seis":["spanish"],"sello":["spanish"],"selva":["spanish"],"semana":["spanish"],"semilla":["spanish"],"senda":["spanish"],"sensor":["spanish"],"señal":["spanish"],"señor":["spanish"],"separar":["spanish"],"sepia":["spanish"],"sequía":["spanish"],"ser":["spanish"],"serie":["spanish"],"sermón":["spanish"],"servir":["spanish"],"sesenta":["spanish"],"sesión":["spanish"],"seta":["spanish"],"setenta":["spanish"],"severo":["spanish"],"sexo":["spanish"],"sexto":["spanish"],"sidra":["spanish"],"siesta":["spanish"],"siete":["spanish"],"siglo":["spanish"],"signo":["spanish"],"sílaba":["spanish"],"silbar":["spanish"],"silencio":["spanish"],"silla":["spanish"],"símbolo":["spanish"],"simio":["spanish"],"sirena":["spanish"],"sistema":["spanish"],"sitio":["spanish"],"situar":["spanish"],"sobre":["spanish"],"socio":["spanish"],"sodio":["spanish"],"sol":["spanish"],"solapa":["spanish"],"soldado":["spanish"],"soledad":["spanish"],"sólido":["spanish"],"soltar":["spanish"],"solución":["spanish"],"sombra":["spanish"],"sondeo":["spanish"],"sonido":["spanish"],"sonoro":["spanish"],"sonrisa":["spanish"],"sopa":["spanish"],"soplar":["spanish"],"soporte":["spanish"],"sordo":["spanish"],"sorpresa":["spanish"],"sorteo":["spanish"],"sostén":["spanish"],"sótano":["spanish"],"suave":["spanish"],"subir":["spanish"],"suceso":["spanish"],"sudor":["spanish"],"suegra":["spanish"],"suelo":["spanish"],"sueño":["spanish"],"suerte":["spanish"],"sufrir":["spanish"],"sujeto":["spanish"],"sultán":["spanish"],"sumar":["spanish"],"superar":["spanish"],"suplir":["spanish"],"suponer":["spanish"],"supremo":["spanish"],"sur":["spanish"],"surco":["spanish"],"sureño":["spanish"],"surgir":["spanish"],"susto":["spanish"],"sutil":["spanish"],"tabaco":["spanish"],"tabique":["spanish"],"tabla":["spanish"],"tabú":["spanish"],"taco":["spanish"],"tacto":["spanish"],"tajo":["spanish"],"talar":["spanish"],"talco":["spanish"],"talento":["spanish"],"talla":["spanish"],"talón":["spanish"],"tamaño":["spanish"],"tambor":["spanish"],"tango":["spanish"],"tanque":["spanish"],"tapa":["spanish"],"tapete":["spanish"],"tapia":["spanish"],"tapón":["spanish"],"taquilla":["spanish"],"tarde":["spanish"],"tarea":["spanish"],"tarifa":["spanish"],"tarjeta":["spanish"],"tarot":["spanish"],"tarro":["spanish"],"tarta":["spanish"],"tatuaje":["spanish"],"tauro":["spanish"],"taza":["spanish"],"tazón":["spanish"],"teatro":["spanish"],"techo":["spanish"],"tecla":["spanish"],"técnica":["spanish"],"tejado":["spanish"],"tejer":["spanish"],"tejido":["spanish"],"tela":["spanish"],"teléfono":["spanish"],"tema":["spanish"],"temor":["spanish"],"templo":["spanish"],"tenaz":["spanish"],"tender":["spanish"],"tener":["spanish"],"tenis":["spanish"],"tenso":["spanish"],"teoría":["spanish"],"terapia":["spanish"],"terco":["spanish"],"término":["spanish"],"ternura":["spanish"],"terror":["spanish"],"tesis":["spanish"],"tesoro":["spanish"],"testigo":["spanish"],"tetera":["spanish"],"texto":["spanish"],"tez":["spanish"],"tibio":["spanish"],"tiburón":["spanish"],"tiempo":["spanish"],"tienda":["spanish"],"tierra":["spanish"],"tieso":["spanish"],"tigre":["spanish"],"tijera":["spanish"],"tilde":["spanish"],"timbre":["spanish"],"tímido":["spanish"],"timo":["spanish"],"tinta":["spanish"],"tío":["spanish"],"típico":["spanish"],"tipo":["spanish"],"tira":["spanish"],"tirón":["spanish"],"titán":["spanish"],"títere":["spanish"],"título":["spanish"],"tiza":["spanish"],"toalla":["spanish"],"tobillo":["spanish"],"tocar":["spanish"],"tocino":["spanish"],"todo":["spanish"],"toga":["spanish"],"toldo":["spanish"],"tomar":["spanish","turkish"],"tono":["spanish"],"tonto":["spanish"],"topar":["spanish"],"tope":["spanish"],"toque":["spanish"],"tórax":["spanish"],"torero":["spanish"],"tormenta":["spanish"],"torneo":["spanish"],"toro":["spanish"],"torpedo":["spanish"],"torre":["spanish"],"torso":["spanish"],"tortuga":["spanish"],"tos":["spanish"],"tosco":["spanish"],"toser":["spanish"],"tóxico":["spanish"],"trabajo":["spanish"],"tractor":["spanish"],"traer":["spanish"],"tráfico":["spanish"],"trago":["spanish"],"traje":["spanish"],"tramo":["spanish"],"trance":["spanish"],"trato":["spanish"],"trauma":["spanish"],"trazar":["spanish"],"trébol":["spanish"],"tregua":["spanish"],"treinta":["spanish"],"tren":["spanish"],"trepar":["spanish"],"tres":["spanish"],"tribu":["spanish"],"trigo":["spanish"],"tripa":["spanish"],"triste":["spanish"],"triunfo":["spanish"],"trofeo":["spanish"],"trompa":["spanish"],"tronco":["spanish"],"tropa":["spanish"],"trote":["spanish"],"trozo":["spanish"],"truco":["spanish"],"trueno":["spanish"],"trufa":["spanish"],"tubería":["spanish"],"tubo":["spanish"],"tuerto":["spanish"],"tumba":["spanish"],"tumor":["spanish"],"túnel":["spanish"],"túnica":["spanish"],"turbina":["spanish"],"turismo":["spanish"],"turno":["spanish"],"tutor":["spanish"],"ubicar":["spanish"],"úlcera":["spanish"],"umbral":["spanish"],"unidad":["spanish"],"unir":["spanish"],"universo":["spanish"],"uno":["spanish"],"untar":["spanish"],"uña":["spanish"],"urbano":["spanish"],"urbe":["spanish"],"urgente":["spanish"],"urna":["spanish"],"usar":["spanish"],"usuario":["spanish"],"útil":["spanish"],"utopía":["spanish"],"uva":["spanish"],"vaca":["spanish"],"vacío":["spanish"],"vacuna":["spanish"],"vagar":["spanish"],"vago":["spanish"],"vaina":["spanish"],"vajilla":["spanish"],"vale":["spanish"],"válido":["spanish"],"valle":["spanish"],"valor":["spanish"],"válvula":["spanish"],"vampiro":["spanish"],"vara":["spanish"],"variar":["spanish"],"varón":["spanish"],"vaso":["spanish"],"vecino":["spanish"],"vector":["spanish"],"vehículo":["spanish"],"veinte":["spanish"],"vejez":["spanish"],"vela":["spanish"],"velero":["spanish"],"veloz":["spanish"],"vena":["spanish"],"vencer":["spanish"],"venda":["spanish"],"veneno":["spanish"],"vengar":["spanish"],"venir":["spanish"],"venta":["spanish"],"venus":["spanish"],"ver":["spanish"],"verano":["spanish"],"verbo":["spanish"],"verde":["spanish"],"vereda":["spanish"],"verja":["spanish"],"verso":["spanish"],"verter":["spanish"],"vía":["spanish"],"viaje":["spanish"],"vibrar":["spanish"],"vicio":["spanish"],"víctima":["spanish"],"vida":["spanish"],"vídeo":["spanish"],"vidrio":["spanish"],"viejo":["spanish"],"viernes":["spanish"],"vigor":["spanish"],"vil":["spanish"],"villa":["spanish"],"vinagre":["spanish"],"vino":["spanish"],"viñedo":["spanish"],"violín":["spanish"],"viral":["spanish"],"virgo":["spanish"],"virtud":["spanish"],"visor":["spanish"],"víspera":["spanish"],"vista":["spanish"],"vitamina":["spanish"],"viudo":["spanish"],"vivaz":["spanish"],"vivero":["spanish"],"vivir":["spanish"],"vivo":["spanish"],"volcán":["spanish"],"volumen":["spanish"],"volver":["spanish"],"voraz":["spanish"],"votar":["spanish"],"voto":["spanish"],"voz":["spanish"],"vuelo":["spanish"],"vulgar":["spanish"],"yacer":["spanish"],"yate":["spanish"],"yegua":["spanish"],"yema":["spanish"],"yerno":["spanish"],"yeso":["spanish"],"yodo":["spanish"],"yoga":["spanish"],"yogur":["spanish"],"zafiro":["spanish"],"zanja":["spanish"],"zapato":["spanish"],"zarza":["spanish"],"zona":["spanish"],"zorro":["spanish"],"zumo":["spanish"],"zurdo":["spanish"],"abajur":["turkish"],"abaküs":["turkish"],"abartı":["turkish"],"abdal":["turkish"],"abdest":["turkish"],"abiye":["turkish"],"abluka":["turkish"],"abone":["turkish"],"absorbe":["turkish"],"absürt":["turkish"],"acayip":["turkish"],"acele":["turkish"],"acemi":["turkish"],"açıkgöz":["turkish"],"adalet":["turkish"],"adam":["turkish"],"adezyon":["turkish"],"adisyon":["turkish"],"adliye":["turkish"],"adres":["turkish"],"afacan":["turkish"],"afili":["turkish"],"afiş":["turkish"],"afiyet":["turkish"],"aforizm":["turkish"],"afra":["turkish"],"ağaç":["turkish"],"ağır":["turkish"],"ahbap":["turkish"],"ahkam":["turkish"],"ahlak":["turkish"],"ahtapot":["turkish"],"aidat":["turkish"],"aile":["turkish"],"ajan":["turkish"],"akademi":["turkish"],"akarsu":["turkish"],"akbaş":["turkish"],"akciğer":["turkish"],"akdeniz":["turkish"],"akıbet":["turkish"],"akıl":["turkish"],"akıntı":["turkish"],"akide":["turkish"],"akrep":["turkish"],"akrobasi":["turkish"],"aksiyon":["turkish"],"akşam":["turkish"],"aktif":["turkish"],"aktör":["turkish"],"aktris":["turkish"],"akustik":["turkish"],"alaca":["turkish"],"albüm":["turkish"],"alçak":["turkish"],"aldanma":["turkish"],"aleni":["turkish"],"alet":["turkish"],"alfabe":["turkish"],"algılama":["turkish"],"alıngan":["turkish"],"alkış":["turkish"],"alkol":["turkish"],"alpay":["turkish"],"alperen":["turkish"],"altın":["turkish"],"altüst":["turkish"],"altyapı":["turkish"],"alyuvar":["turkish"],"amade":["turkish"],"amatör":["turkish"],"amazon":["turkish"],"ambalaj":["turkish"],"amblem":["turkish"],"ambulans":["turkish"],"amca":["turkish"],"amel":["turkish"],"amir":["turkish"],"amiyane":["turkish"],"amorti":["turkish"],"ampul":["turkish"],"anadolu":["turkish"],"anahtar":["turkish"],"anakonda":["turkish"],"anaokul":["turkish"],"anapara":["turkish"],"anarşi":["turkish"],"anatomi":["turkish"],"anayasa":["turkish"],"anekdot":["turkish"],"anestezi":["turkish"],"angaje":["turkish"],"anka":["turkish"],"anket":["turkish"],"anlamlı":["turkish"],"anne":["turkish"],"anomali":["turkish"],"anonim":["turkish"],"anten":["turkish"],"antlaşma":["turkish"],"apse":["turkish"],"araba":["turkish"],"aracı":["turkish"],"araf":["turkish"],"arbede":["turkish"],"arda":["turkish"],"arefe":["turkish"],"argo":["turkish"],"argüman":["turkish"],"arkadaş":["turkish"],"armoni":["turkish"],"arsa":["turkish"],"arsız":["turkish"],"artı":["turkish"],"aruz":["turkish"],"asansör":["turkish"],"asayiş":["turkish"],"asgari":["turkish"],"asil":["turkish"],"asker":["turkish"],"askı":["turkish"],"aslan":["turkish"],"asosyal":["turkish"],"astsubay":["turkish"],"asya":["turkish"],"aşçı":["turkish"],"aşırı":["turkish"],"aşure":["turkish"],"atabey":["turkish"],"ataman":["turkish"],"ateş":["turkish"],"atmaca":["turkish"],"atmosfer":["turkish"],"atölye":["turkish"],"avcı":["turkish"],"avdet":["turkish"],"avize":["turkish"],"avlu":["turkish"],"avokado":["turkish"],"avrupa":["turkish"],"avukat":["turkish"],"ayaz":["turkish"],"ayçiçeği":["turkish"],"aydın":["turkish"],"aygıt":["turkish"],"ayna":["turkish"],"ayran":["turkish"],"ayrıntı":["turkish"],"azim":["turkish"],"baca":["turkish"],"bagaj":["turkish"],"bağlantı":["turkish"],"bahadır":["turkish"],"bahçe":["turkish"],"baki":["turkish"],"bakkal":["turkish"],"baklava":["turkish"],"bakteri":["turkish"],"balçık":["turkish"],"balina":["turkish"],"balo":["turkish"],"balta":["turkish"],"bant":["turkish"],"banyo":["turkish"],"bardak":["turkish"],"barış":["turkish"],"başbuğ":["turkish"],"başıboş":["turkish"],"başkan":["turkish"],"başlık":["turkish"],"bavul":["turkish"],"bayındır":["turkish"],"baykuş":["turkish"],"bazlama":["turkish"],"bedel":["turkish"],"begüm":["turkish"],"bekçi":["turkish"],"bekle":["turkish"],"belge":["turkish"],"belki":["turkish"],"bencil":["turkish"],"benek":["turkish"],"bengi":["turkish"],"berjer":["turkish"],"berk":["turkish"],"berrak":["turkish"],"beşik":["turkish"],"beyin":["turkish"],"beyoğlu":["turkish"],"bıçak":["turkish"],"biberiye":["turkish"],"bidon":["turkish"],"bihaber":["turkish"],"bikini":["turkish"],"bilezik":["turkish"],"bilinç":["turkish"],"bilye":["turkish"],"bina":["turkish"],"binbaşı":["turkish"],"binyıl":["turkish"],"bisiklet":["turkish"],"bisküvi":["turkish"],"bitki":["turkish"],"bizzat":["turkish"],"bodrum":["turkish"],"boğaz":["turkish"],"bohça":["turkish"],"boncuk":["turkish"],"bonfile":["turkish"],"borsa":["turkish"],"boru":["turkish"],"bostan":["turkish"],"boşboğaz":["turkish"],"botanik":["turkish"],"boya":["turkish"],"boykot":["turkish"],"boynuz":["turkish"],"bozgun":["turkish"],"bozkır":["turkish"],"bölüm":["turkish"],"börek":["turkish"],"buçuk":["turkish"],"bugün":["turkish"],"buğday":["turkish"],"buhar":["turkish"],"buhran":["turkish"],"bulvar":["turkish"],"buram":["turkish"],"burçak":["turkish"],"burs":["turkish"],"burun":["turkish"],"buzdağı":["turkish"],"buzkıran":["turkish"],"bücür":["turkish"],"büfe":["turkish"],"bülten":["turkish"],"bütçe":["turkish"],"bütün":["turkish"],"büyük":["turkish"],"cacık":["turkish"],"cadı":["turkish"],"cahil":["turkish"],"cambaz":["turkish"],"canhıraş":["turkish"],"casus":["turkish"],"cazibe":["turkish"],"cehalet":["turkish"],"cehennem":["turkish"],"ceket":["turkish"],"cemre":["turkish"],"cenin":["turkish"],"cennet":["turkish"],"cepken":["turkish"],"cerrah":["turkish"],"cesur":["turkish"],"cetvel":["turkish"],"cevher":["turkish"],"ceylan":["turkish"],"cılız":["turkish"],"cıva":["turkish"],"cilt":["turkish"],"cisim":["turkish"],"ciyak":["turkish"],"coğrafya":["turkish"],"cömert":["turkish"],"cumba":["turkish"],"cüzdan":["turkish"],"çabucak":["turkish"],"çadır":["turkish"],"çağdaş":["turkish"],"çağlayan":["turkish"],"çağrı":["turkish"],"çakmak":["turkish"],"çalışkan":["turkish"],"çamaşır":["turkish"],"çapa":["turkish"],"çaput":["turkish"],"çarık":["turkish"],"çarpan":["turkish"],"çarşaf":["turkish"],"çayhane":["turkish"],"çekirdek":["turkish"],"çelebi":["turkish"],"çember":["turkish"],"çenet":["turkish"],"çengel":["turkish"],"çerçeve":["turkish"],"çerez":["turkish"],"çeşit":["turkish"],"çeşme":["turkish"],"çete":["turkish"],"çevre":["turkish"],"çeyiz":["turkish"],"çeyrek":["turkish"],"çığır":["turkish"],"çılgın":["turkish"],"çıngırak":["turkish"],"çift":["turkish"],"çiğdem":["turkish"],"çikolata":["turkish"],"çilek":["turkish"],"çimen":["turkish"],"çivi":["turkish"],"çoban":["turkish"],"çocuk":["turkish"],"çokgen":["turkish"],"çomak":["turkish"],"çorba":["turkish"],"çözelti":["turkish"],"çubuk":["turkish"],"çukur":["turkish"],"çuval":["turkish"],"çürük":["turkish"],"dağbaşı":["turkish"],"dağılım":["turkish"],"daktilo":["turkish"],"daldırış":["turkish"],"dalga":["turkish"],"dalkavuk":["turkish"],"damak":["turkish"],"damıtma":["turkish"],"damla":["turkish"],"dana":["turkish"],"dandik":["turkish"],"danışman":["turkish"],"daniska":["turkish"],"dantel":["turkish"],"dargeçit":["turkish"],"darphane":["turkish"],"davet":["turkish"],"dayı":["turkish"],"defter":["turkish"],"değer":["turkish"],"değirmen":["turkish"],"dehşet":["turkish"],"delgeç":["turkish"],"demir":["turkish"],"deneyim":["turkish"],"denge":["turkish"],"depo":["turkish"],"deprem":["turkish"],"derdest":["turkish"],"dere":["turkish"],"derhal":["turkish"],"derman":["turkish"],"dernek":["turkish"],"derviş":["turkish"],"desen":["turkish"],"destan":["turkish"],"dışarı":["turkish"],"dışbükey":["turkish"],"dijital":["turkish"],"dikbaşlı":["turkish"],"dilekçe":["turkish"],"dimağ":["turkish"],"dinamik":["turkish"],"dindar":["turkish"],"dinleme":["turkish"],"dinozor":["turkish"],"dipçik":["turkish"],"dipnot":["turkish"],"direniş":["turkish"],"dirsek":["turkish"],"disiplin":["turkish"],"divriği":["turkish"],"dizüstü":["turkish"],"dobra":["turkish"],"dodurga":["turkish"],"doğalgaz":["turkish"],"doküman":["turkish"],"dolap":["turkish"],"donanım":["turkish"],"dondurma":["turkish"],"donör":["turkish"],"doruk":["turkish"],"dosdoğru":["turkish"],"dost":["turkish"],"dosya":["turkish"],"dozer":["turkish"],"döküm":["turkish"],"dönence":["turkish"],"dörtyol":["turkish"],"dövme":["turkish"],"dram":["turkish"],"dublaj":["turkish"],"durum":["turkish"],"duvak":["turkish"],"duyarga":["turkish"],"duyma":["turkish"],"duyuru":["turkish"],"düğme":["turkish"],"düğüm":["turkish"],"dükkan":["turkish"],"dünür":["turkish"],"düpedüz":["turkish"],"dürbün":["turkish"],"düşünür":["turkish"],"düzayak":["turkish"],"düzeltme":["turkish"],"ebeveyn":["turkish"],"ebru":["turkish"],"ecel":["turkish"],"ecnebi":["turkish"],"ecza":["turkish"],"edat":["turkish"],"edilgen":["turkish"],"efendi":["turkish"],"efor":["turkish"],"efsane":["turkish"],"egemen":["turkish"],"egzersiz":["turkish"],"eğrelti":["turkish"],"ekarte":["turkish"],"ekip":["turkish"],"eklem":["turkish"],"ekmek":["turkish"],"ekol":["turkish"],"ekonomi":["turkish"],"ekose":["turkish"],"ekran":["turkish"],"ekvator":["turkish"],"elaman":["turkish"],"elastik":["turkish"],"elbet":["turkish"],"elbise":["turkish"],"elçi":["turkish"],"eldiven":["turkish"],"elebaşı":["turkish"],"eleştiri":["turkish"],"elma":["turkish"],"eloğlu":["turkish"],"elveda":["turkish"],"emare":["turkish"],"emekçi":["turkish"],"emisyon":["turkish"],"emniyet":["turkish"],"empati":["turkish"],"emsal":["turkish"],"emzik":["turkish"],"endüstri":["turkish"],"enerji":["turkish"],"engebe":["turkish"],"enişte":["turkish"],"enkaz":["turkish"],"entari":["turkish"],"entegre":["turkish"],"entrika":["turkish"],"enzim":["turkish"],"erdem":["turkish"],"ergen":["turkish"],"erguvan":["turkish"],"erkek":["turkish"],"erozyon":["turkish"],"ertesi":["turkish"],"erzak":["turkish"],"esaret":["turkish"],"esenlik":["turkish"],"eser":["turkish"],"eski":["turkish"],"esnek":["turkish"],"eşarp":["turkish"],"eşofman":["turkish"],"eşraf":["turkish"],"eşya":["turkish"],"eşzaman":["turkish"],"etik":["turkish"],"etken":["turkish"],"etkinlik":["turkish"],"etüt":["turkish"],"evet":["turkish"],"evire":["turkish"],"evrak":["turkish"],"evrim":["turkish"],"eyalet":["turkish"],"eyvah":["turkish"],"ezber":["turkish"],"fabrika":["turkish"],"fanus":["turkish"],"fason":["turkish"],"fasulye":["turkish"],"fatih":["turkish"],"fatura":["turkish"],"fayans":["turkish"],"fayton":["turkish"],"fazıl":["turkish"],"fazilet":["turkish"],"felsefe":["turkish"],"fener":["turkish"],"feribot":["turkish"],"fersah":["turkish"],"fesih":["turkish"],"feveran":["turkish"],"feza":["turkish"],"fıçı":["turkish"],"fıldır":["turkish"],"fındık":["turkish"],"fırça":["turkish"],"fırsat":["turkish"],"fırtına":["turkish"],"fıtık":["turkish"],"fidan":["turkish"],"fidye":["turkish"],"figür":["turkish"],"fihrist":["turkish"],"fikir":["turkish"],"fildişi":["turkish"],"filtre":["turkish"],"fincan":["turkish"],"firuze":["turkish"],"fitil":["turkish"],"fiyaka":["turkish"],"fizik":["turkish"],"flaş":["turkish"],"flüt":["turkish"],"fosil":["turkish"],"fren":["turkish"],"fukara":["turkish"],"futbol":["turkish"],"garabet":["turkish"],"gariban":["turkish"],"garnitür":["turkish"],"gazi":["turkish"],"gece":["turkish"],"gedik":["turkish"],"gelenek":["turkish"],"gelin":["turkish"],"gemi":["turkish"],"genç":["turkish"],"geniş":["turkish"],"geometri":["turkish"],"gerçek":["turkish"],"gevrek":["turkish"],"gezegen":["turkish"],"gezgin":["turkish"],"geziyolu":["turkish"],"gıcık":["turkish"],"gıda":["turkish"],"gıybet":["turkish"],"girdap":["turkish"],"girişim":["turkish"],"gitar":["turkish"],"giyecek":["turkish"],"giysi":["turkish"],"gizem":["turkish"],"gofret":["turkish"],"goril":["turkish"],"göbek":["turkish"],"göçebe":["turkish"],"göğüs":["turkish"],"gökdelen":["turkish"],"gökmen":["turkish"],"gökyüzü":["turkish"],"gölge":["turkish"],"gömlek":["turkish"],"gönül":["turkish"],"görenek":["turkish"],"görkemli":["turkish"],"görsel":["turkish"],"gösteri":["turkish"],"gövde":["turkish"],"gözaltı":["turkish"],"gözcü":["turkish"],"gözdağı":["turkish"],"gözleme":["turkish"],"gözyaşı":["turkish"],"grup":["turkish"],"gurbet":["turkish"],"gusül":["turkish"],"gübre":["turkish"],"güfte":["turkish"],"gümüş":["turkish"],"günaydın":["turkish"],"güncel":["turkish"],"gündüz":["turkish"],"güneş":["turkish"],"günyüzü":["turkish"],"gürbüz":["turkish"],"güvercin":["turkish"],"güzel":["turkish"],"hacamat":["turkish"],"hacim":["turkish"],"hademe":["turkish"],"hafız":["turkish"],"hafriyat":["turkish"],"hafta":["turkish"],"hakan":["turkish"],"hakem":["turkish"],"hakikat":["turkish"],"haksever":["turkish"],"halı":["turkish"],"hançer":["turkish"],"hane":["turkish"],"hapis":["turkish"],"hapşırık":["turkish"],"harf":["turkish"],"haseki":["turkish"],"hasret":["turkish"],"hatun":["turkish"],"havuç":["turkish"],"haylaz":["turkish"],"haysiyet":["turkish"],"hayvan":["turkish"],"hedef":["turkish"],"hemen":["turkish"],"hemfikir":["turkish"],"hendek":["turkish"],"hepsi":["turkish"],"hergele":["turkish"],"herhangi":["turkish"],"hesap":["turkish"],"heyecan":["turkish"],"heykel":["turkish"],"hezimet":["turkish"],"hıçkırık":["turkish"],"hızölçer":["turkish"],"hicviye":["turkish"],"hikaye":["turkish"],"hikmet":["turkish"],"hile":["turkish"],"hisse":["turkish"],"hobi":["turkish"],"hoca":["turkish"],"horlama":["turkish"],"hoşbeş":["turkish"],"hoşgörü":["turkish"],"hoyrat":["turkish"],"hörgüç":["turkish"],"höyük":["turkish"],"hudut":["turkish"],"hukuk":["turkish"],"hunhar":["turkish"],"hurda":["turkish"],"huysuz":["turkish"],"huzur":["turkish"],"hücum":["turkish"],"hükümet":["turkish"],"hünkar":["turkish"],"hüviyet":["turkish"],"ırmak":["turkish"],"ısıölçer":["turkish"],"ısıtıcı":["turkish"],"ıspanak":["turkish"],"ısrar":["turkish"],"ışıldak":["turkish"],"ızdırap":["turkish"],"ızgara":["turkish"],"ibadet":["turkish"],"icat":["turkish"],"içbükey":["turkish"],"içecek":["turkish"],"içgüdü":["turkish"],"içsel":["turkish"],"idman":["turkish"],"iftihar":["turkish"],"iğne":["turkish"],"ihanet":["turkish"],"ihbar":["turkish"],"ihdas":["turkish"],"ihmal":["turkish"],"ihracat":["turkish"],"ihsan":["turkish"],"ikilem":["turkish"],"ikindi":["turkish"],"ikircik":["turkish"],"iklim":["turkish"],"iksir":["turkish"],"iktibas":["turkish"],"ilaç":["turkish"],"ilçe":["turkish"],"ileri":["turkish"],"iletişim":["turkish"],"ilgi":["turkish"],"ilhak":["turkish"],"ilkbahar":["turkish"],"ilkokul":["turkish"],"ilmek":["turkish"],"imkan":["turkish"],"imleç":["turkish"],"imsak":["turkish"],"imtihan":["turkish"],"imza":["turkish"],"ince":["turkish"],"inkar":["turkish"],"inşa":["turkish"],"ipek":["turkish"],"ipucu":["turkish"],"irade":["turkish"],"irfan":["turkish"],"irmik":["turkish"],"isabet":["turkish"],"iskele":["turkish"],"israf":["turkish"],"isyan":["turkish"],"işçi":["turkish"],"işgal":["turkish"],"işgüzar":["turkish"],"işlem":["turkish"],"itibar":["turkish"],"itiraf":["turkish"],"ivedi":["turkish"],"ivme":["turkish"],"iyileşme":["turkish"],"iyimser":["turkish"],"izbandut":["turkish"],"izci":["turkish"],"izdiham":["turkish"],"izin":["turkish"],"jakoben":["turkish"],"jandarma":["turkish"],"jargon":["turkish"],"kabadayı":["turkish"],"kablo":["turkish"],"kabus":["turkish"],"kaçamak":["turkish"],"kadeh":["turkish"],"kadın":["turkish"],"kadraj":["turkish"],"kafa":["turkish"],"kafkas":["turkish"],"kağıt":["turkish"],"kağnı":["turkish"],"kahkaha":["turkish"],"kahraman":["turkish"],"kahvaltı":["turkish"],"kakül":["turkish"],"kaldırım":["turkish"],"kale":["turkish"],"kalibre":["turkish"],"kalkan":["turkish"],"kalpak":["turkish"],"kamış":["turkish"],"kamyon":["turkish"],"kanat":["turkish"],"kandaş":["turkish"],"kanepe":["turkish"],"kanser":["turkish"],"kanun":["turkish"],"kaos":["turkish"],"kapı":["turkish"],"kaplıca":["turkish"],"kaptan":["turkish"],"karanlık":["turkish"],"kardeş":["turkish"],"karga":["turkish"],"karınca":["turkish"],"karmaşa":["turkish"],"karşıt":["turkish"],"kasırga":["turkish"],"kask":["turkish"],"kasvet":["turkish"],"katkı":["turkish"],"katman":["turkish"],"kavram":["turkish"],"kaygan":["turkish"],"kaynakça":["turkish"],"kayyum":["turkish"],"kedi":["turkish"],"kehanet":["turkish"],"kekik":["turkish"],"kelebek":["turkish"],"kenar":["turkish"],"kerkenez":["turkish"],"kerpiç":["turkish"],"kesirli":["turkish"],"kesmece":["turkish"],"kestane":["turkish"],"keşkek":["turkish"],"ketçap":["turkish"],"keyfiyet":["turkish"],"kıble":["turkish"],"kıdemli":["turkish"],"kılavuz":["turkish"],"kılçık":["turkish"],"kılıf":["turkish"],"kıraç":["turkish"],"kırmızı":["turkish"],"kırsal":["turkish"],"kısayol":["turkish"],"kısım":["turkish"],"kıskanç":["turkish"],"kısmet":["turkish"],"kışla":["turkish"],"kıvanç":["turkish"],"kıvılcım":["turkish"],"kıvrık":["turkish"],"kıyafet":["turkish"],"kıymetli":["turkish"],"kızak":["turkish"],"kızılcık":["turkish"],"kibar":["turkish"],"kinaye":["turkish"],"kira":["turkish"],"kiremit":["turkish"],"kirli":["turkish"],"kirpik":["turkish"],"kişisel":["turkish"],"kitap":["turkish"],"koçbaşı":["turkish"],"kodaman":["turkish"],"koğuş":["turkish"],"kokteyl":["turkish"],"kolaycı":["turkish"],"kolbastı":["turkish"],"kolonya":["turkish"],"koltuk":["turkish"],"kolye":["turkish"],"kombine":["turkish"],"komedyen":["turkish"],"komiser":["turkish"],"komposto":["turkish"],"komşu":["turkish"],"komuta":["turkish"],"konak":["turkish"],"konfor":["turkish"],"koni":["turkish"],"konsül":["turkish"],"kopya":["turkish"],"korkusuz":["turkish"],"korna":["turkish"],"korse":["turkish"],"korunak":["turkish"],"korvet":["turkish"],"kostüm":["turkish"],"koşul":["turkish"],"koyu":["turkish"],"kozmik":["turkish"],"köfte":["turkish"],"kökensel":["turkish"],"köprücük":["turkish"],"köpük":["turkish"],"kördüğüm":["turkish"],"körfez":["turkish"],"köstebek":["turkish"],"köşegen":["turkish"],"kötü":["turkish"],"kravat":["turkish"],"kriter":["turkish"],"kuantum":["turkish"],"kudurma":["turkish"],"kuluçka":["turkish"],"kulübe":["turkish"],"kumanya":["turkish"],"kumbara":["turkish"],"kumlu":["turkish"],"kumpir":["turkish"],"kumral":["turkish"],"kundura":["turkish"],"kupa":["turkish"],"kupkuru":["turkish"],"kuramsal":["turkish"],"kurbağa":["turkish"],"kurdele":["turkish"],"kurgu":["turkish"],"kurmay":["turkish"],"kurşun":["turkish"],"kurtuluş":["turkish"],"kurultay":["turkish"],"kurye":["turkish"],"kusursuz":["turkish"],"kuşak":["turkish"],"kuşbaşı":["turkish"],"kuşkulu":["turkish"],"kutlama":["turkish"],"kutsal":["turkish"],"kutup":["turkish"],"kuver":["turkish"],"kuyruk":["turkish"],"kuzey":["turkish"],"kuzgun":["turkish"],"küçük":["turkish"],"külçe":["turkish"],"külfet":["turkish"],"külliye":["turkish"],"kültürel":["turkish"],"kümes":["turkish"],"künefe":["turkish"],"küresel":["turkish"],"kütle":["turkish"],"lahana":["turkish"],"lahmacun":["turkish"],"lamba":["turkish"],"lansman":["turkish"],"lavaş":["turkish"],"layık":["turkish"],"leğen":["turkish"],"levent":["turkish"],"leziz":["turkish"],"lezzet":["turkish"],"lider":["turkish"],"likide":["turkish"],"liman":["turkish"],"liste":["turkish"],"litre":["turkish"],"liyakat":["turkish"],"lodos":["turkish"],"lokanta":["turkish"],"lokman":["turkish"],"lokum":["turkish"],"lunapark":["turkish"],"lütfen":["turkish"],"lüzum":["turkish"],"nokta":["turkish"],"mabet":["turkish"],"macera":["turkish"],"macun":["turkish"],"madalya":["turkish"],"madde":["turkish"],"madem":["turkish"],"mağara":["turkish"],"mağdur":["turkish"],"mağfiret":["turkish"],"mağlup":["turkish"],"mahalle":["turkish"],"mahcup":["turkish"],"mahir":["turkish"],"mahkeme":["turkish"],"mahlas":["turkish"],"mahrum":["turkish"],"mahsul":["turkish"],"makas":["turkish"],"makbuz":["turkish"],"makine":["turkish"],"makro":["turkish"],"maksat":["turkish"],"makul":["turkish"],"maliye":["turkish"],"manav":["turkish"],"mangal":["turkish"],"manidar":["turkish"],"manken":["turkish"],"mantık":["turkish"],"manzara":["turkish"],"mareşal":["turkish"],"margarin":["turkish"],"marifet":["turkish"],"marmelat":["turkish"],"masaüstü":["turkish"],"masmavi":["turkish"],"masraf":["turkish"],"masum":["turkish"],"matah":["turkish"],"materyal":["turkish"],"matrak":["turkish"],"maval":["turkish"],"mavra":["turkish"],"maydanoz":["turkish"],"mayhoş":["turkish"],"maytap":["turkish"],"mazbata":["turkish"],"mazeret":["turkish"],"mazlum":["turkish"],"mazot":["turkish"],"mazur":["turkish"],"meblağ":["turkish"],"mebus":["turkish"],"mecaz":["turkish"],"mecbur":["turkish"],"meclis":["turkish"],"mecmua":["turkish"],"mecnun":["turkish"],"meçhul":["turkish"],"medeni":["turkish"],"mehtap":["turkish"],"mekanik":["turkish"],"melodi":["turkish"],"meltem":["turkish"],"memur":["turkish"],"mendil":["turkish"],"menekşe":["turkish"],"menteşe":["turkish"],"meraklı":["turkish"],"mercek":["turkish"],"merdiven":["turkish"],"merhaba":["turkish"],"merinos":["turkish"],"merkez":["turkish"],"mermi":["turkish"],"mert":["turkish"],"mesafe":["turkish"],"mesele":["turkish"],"mesken":["turkish"],"meslek":["turkish"],"meşale":["turkish"],"meşgul":["turkish"],"meşhur":["turkish"],"metafor":["turkish"],"metin":["turkish"],"metre":["turkish"],"mevcut":["turkish"],"mevkidaş":["turkish"],"meydan":["turkish"],"meyil":["turkish"],"meyve":["turkish"],"meziyet":["turkish"],"mezun":["turkish"],"mıknatıs":["turkish"],"mısra":["turkish"],"mızıka":["turkish"],"miğfer":["turkish"],"mihrak":["turkish"],"miktar":["turkish"],"milat":["turkish"],"milli":["turkish"],"mimar":["turkish"],"minare":["turkish"],"mineral":["turkish"],"minik":["turkish"],"minyon":["turkish"],"mirliva":["turkish"],"misafir":["turkish"],"miskin":["turkish"],"miting":["turkish"],"miyop":["turkish"],"mizah":["turkish"],"mobilya":["turkish"],"monitör":["turkish"],"morötesi":["turkish"],"motive":["turkish"],"mozaik":["turkish"],"muavin":["turkish"],"mucize":["turkish"],"muhafız":["turkish"],"muhteşem":["turkish"],"mukayese":["turkish"],"mumya":["turkish"],"musluk":["turkish"],"muşamba":["turkish"],"mutabık":["turkish"],"mutfak":["turkish"],"mutlu":["turkish"],"muzaffer":["turkish"],"muzdarip":["turkish"],"mübarek":["turkish"],"mücadele":["turkish"],"müdür":["turkish"],"müfredat":["turkish"],"müftü":["turkish"],"mühendis":["turkish"],"mühim":["turkish"],"mühlet":["turkish"],"mükemmel":["turkish"],"mülk":["turkish"],"mümkün":["turkish"],"mümtaz":["turkish"],"müsrif":["turkish"],"müstesna":["turkish"],"müşahit":["turkish"],"müşteri":["turkish"],"mütercim":["turkish"],"müthiş":["turkish"],"müze":["turkish"],"müzik":["turkish"],"nabız":["turkish"],"nadas":["turkish"],"nadir":["turkish"],"nahoş":["turkish"],"nakarat":["turkish"],"nakış":["turkish"],"nalbur":["turkish"],"namlu":["turkish"],"namus":["turkish"],"nankör":["turkish"],"nargile":["turkish"],"narkoz":["turkish"],"nasıl":["turkish"],"nasip":["turkish"],"naylon":["turkish"],"nazar":["turkish"],"nazım":["turkish"],"nazik":["turkish"],"neden":["turkish"],"nefes":["turkish"],"negatif":["turkish"],"neon":["turkish"],"neptün":["turkish"],"nerede":["turkish"],"nesil":["turkish"],"nesnel":["turkish"],"neşeli":["turkish"],"netice":["turkish"],"nevresim":["turkish"],"neyse":["turkish"],"neyzen":["turkish"],"nezaket":["turkish"],"nezih":["turkish"],"nezle":["turkish"],"nicel":["turkish"],"nilüfer":["turkish"],"nimet":["turkish"],"nisan":["turkish"],"nispet":["turkish"],"nitekim":["turkish"],"nizam":["turkish"],"nohut":["turkish"],"noksan":["turkish"],"nostalji":["turkish"],"noter":["turkish"],"nöbet":["turkish"],"numara":["turkish"],"numune":["turkish"],"nutuk":["turkish"],"nüfus":["turkish"],"obabaşı":["turkish"],"obez":["turkish"],"obje":["turkish"],"ocak":["turkish"],"odun":["turkish"],"ofansif":["turkish"],"ofis":["turkish"],"oğlak":["turkish"],"oğuz":["turkish"],"okçu":["turkish"],"oklava":["turkish"],"oksijen":["turkish"],"okul":["turkish"],"okumuş":["turkish"],"okutman":["turkish"],"okuyucu":["turkish"],"okyanus":["turkish"],"olağan":["turkish"],"olanak":["turkish"],"olası":["turkish"],"olay":["turkish"],"olgun":["turkish"],"olimpik":["turkish"],"olumlu":["turkish"],"omlet":["turkish"],"omurga":["turkish"],"onarım":["turkish"],"onursal":["turkish"],"optik":["turkish"],"orantı":["turkish"],"ordu":["turkish"],"organik":["turkish"],"orijin":["turkish"],"orkide":["turkish"],"orman":["turkish"],"orta":["turkish"],"oruç":["turkish"],"otağ":["turkish"],"otantik":["turkish"],"otel":["turkish"],"otoban":["turkish"],"otogar":["turkish"],"otomobil":["turkish"],"otonom":["turkish"],"otopark":["turkish"],"otorite":["turkish"],"otoyol":["turkish"],"oturum":["turkish"],"oyuk":["turkish"],"oyuncak":["turkish"],"ozan":["turkish"],"ödeme":["turkish"],"ödenek":["turkish"],"ödev":["turkish"],"ödül":["turkish"],"ödünç":["turkish"],"öfke":["turkish"],"öğlen":["turkish"],"öğrenci":["turkish"],"öğün":["turkish"],"öğütücü":["turkish"],"öksürük":["turkish"],"ölçme":["turkish"],"ölçü":["turkish"],"ölümsüz":["turkish"],"ömür":["turkish"],"önayak":["turkish"],"öncü":["turkish"],"önder":["turkish"],"önem":["turkish"],"önerge":["turkish"],"öngörü":["turkish"],"önlük":["turkish"],"önsezi":["turkish"],"öpücük":["turkish"],"ördek":["turkish"],"örgü":["turkish"],"örtbas":["turkish"],"örtme":["turkish"],"örtü":["turkish"],"örümcek":["turkish"],"örüntü":["turkish"],"öteberi":["turkish"],"öteki":["turkish"],"övünç":["turkish"],"öykü":["turkish"],"öyleyse":["turkish"],"özçekim":["turkish"],"özdeyiş":["turkish"],"özel":["turkish"],"özenti":["turkish"],"özerk":["turkish"],"özgürlük":["turkish"],"özlem":["turkish"],"özlü":["turkish"],"özne":["turkish"],"özsever":["turkish"],"özümseme":["turkish"],"özür":["turkish"],"özveri":["turkish"],"pabuç":["turkish"],"padişah":["turkish"],"palamut":["turkish"],"palmiye":["turkish"],"palto":["turkish"],"palyaço":["turkish"],"pamuk":["turkish"],"panayır":["turkish"],"pancar":["turkish"],"panik":["turkish"],"panjur":["turkish"],"pankart":["turkish"],"pano":["turkish"],"pansuman":["turkish"],"pantolon":["turkish"],"panzehir":["turkish"],"papatya":["turkish"],"papyon":["turkish"],"paraşüt":["turkish"],"parça":["turkish"],"pardösü":["turkish"],"parfüm":["turkish"],"parıltı":["turkish"],"parkur":["turkish"],"parmak":["turkish"],"parodi":["turkish"],"parsel":["turkish"],"partner":["turkish"],"pasaport":["turkish"],"pasif":["turkish"],"paskalya":["turkish"],"pastırma":["turkish"],"paşa":["turkish"],"patates":["turkish"],"paten":["turkish"],"patika":["turkish"],"patlıcan":["turkish"],"patolog":["turkish"],"payanda":["turkish"],"paydaş":["turkish"],"payidar":["turkish"],"paylaşma":["turkish"],"paytak":["turkish"],"peçete":["turkish"],"peder":["turkish"],"pehlivan":["turkish"],"pekala":["turkish"],"pekmez":["turkish"],"pelerin":["turkish"],"pelikan":["turkish"],"pelüş":["turkish"],"pembe":["turkish"],"pencere":["turkish"],"pense":["turkish"],"perçin":["turkish"],"perde":["turkish"],"pergel":["turkish"],"perişan":["turkish"],"peron":["turkish"],"personel":["turkish"],"perşembe":["turkish"],"peruk":["turkish"],"pervane":["turkish"],"pespaye":["turkish"],"pestil":["turkish"],"peşin":["turkish"],"petek":["turkish"],"petrol":["turkish"],"petunya":["turkish"],"peynir":["turkish"],"peyzaj":["turkish"],"pınar":["turkish"],"pırasa":["turkish"],"pırlanta":["turkish"],"pide":["turkish"],"pikap":["turkish"],"pilav":["turkish"],"piliç":["turkish"],"pipet":["turkish"],"pipo":["turkish"],"piramit":["turkish"],"pirinç":["turkish"],"pirzola":["turkish"],"pist":["turkish"],"pişik":["turkish"],"pişman":["turkish"],"piyasa":["turkish"],"piyes":["turkish"],"plaj":["turkish"],"plaket":["turkish"],"planlama":["turkish"],"platform":["turkish"],"plazma":["turkish"],"podyum":["turkish"],"poğaça":["turkish"],"polat":["turkish"],"politika":["turkish"],"popüler":["turkish"],"porselen":["turkish"],"portakal":["turkish"],"poster":["turkish"],"poşet":["turkish"],"poyraz":["turkish"],"pozitif":["turkish"],"pranga":["turkish"],"pratik":["turkish"],"prenses":["turkish"],"prim":["turkish"],"profil":["turkish"],"proje":["turkish"],"protokol":["turkish"],"puan":["turkish"],"pudra":["turkish"],"pusula":["turkish"],"püre":["turkish"],"pürüz":["turkish"],"püstül":["turkish"],"püsür":["turkish"],"racon":["turkish"],"radikal":["turkish"],"radyo":["turkish"],"rafadan":["turkish"],"rafine":["turkish"],"rağbet":["turkish"],"rahat":["turkish"],"rahle":["turkish"],"rakam":["turkish"],"raket":["turkish"],"rakip":["turkish"],"rakun":["turkish"],"ralli":["turkish"],"randevu":["turkish"],"ranza":["turkish"],"rapor":["turkish"],"rastgele":["turkish"],"rasyonel":["turkish"],"razı":["turkish"],"realite":["turkish"],"reçine":["turkish"],"refah":["turkish"],"referans":["turkish"],"refik":["turkish"],"rehber":["turkish"],"rehin":["turkish"],"reis":["turkish"],"rekabet":["turkish"],"reklam":["turkish"],"rekor":["turkish"],"rektör":["turkish"],"renk":["turkish"],"resim":["turkish"],"resmen":["turkish"],"restoran":["turkish"],"retorik":["turkish"],"revaç":["turkish"],"reyon":["turkish"],"rezalet":["turkish"],"rezerv":["turkish"],"rezil":["turkish"],"rıhtım":["turkish"],"rıza":["turkish"],"ritim":["turkish"],"ritüel":["turkish"],"rivayet":["turkish"],"roman":["turkish"],"rozet":["turkish"],"röportaj":["turkish"],"rötar":["turkish"],"ruble":["turkish"],"ruhban":["turkish"],"ruhsat":["turkish"],"rulet":["turkish"],"runik":["turkish"],"rutin":["turkish"],"rutubet":["turkish"],"rüşvet":["turkish"],"rütbe":["turkish"],"rüya":["turkish"],"rüzgar":["turkish"],"sabah":["turkish"],"sabıka":["turkish"],"sabit":["turkish"],"sabun":["turkish"],"saçma":["turkish"],"sade":["turkish"],"sadık":["turkish"],"safahat":["turkish"],"safdil":["turkish"],"safkan":["turkish"],"sağanak":["turkish"],"sağduyu":["turkish"],"sağlam":["turkish"],"saha":["turkish"],"sahiden":["turkish"],"sahne":["turkish"],"sakal":["turkish"],"sakız":["turkish"],"sakin":["turkish"],"saklama":["turkish"],"saksağan":["turkish"],"salamura":["turkish"],"salça":["turkish"],"salgı":["turkish"],"salınım":["turkish"],"salkım":["turkish"],"saltanat":["turkish"],"sanatçı":["turkish"],"sancak":["turkish"],"sandalye":["turkish"],"saniye":["turkish"],"saplantı":["turkish"],"sapsız":["turkish"],"saray":["turkish"],"sarışın":["turkish"],"sarkık":["turkish"],"sarmaşık":["turkish"],"satır":["turkish"],"savaşım":["turkish"],"savunma":["turkish"],"saydam":["turkish"],"sayfa":["turkish"],"saygın":["turkish"],"sayısal":["turkish"],"sebep":["turkish"],"seçenek":["turkish"],"seçim":["turkish"],"seçkin":["turkish"],"seçmen":["turkish"],"sedir":["turkish"],"sedye":["turkish"],"sefer":["turkish"],"sehpa":["turkish"],"sekizgen":["turkish"],"selektör":["turkish"],"selvi":["turkish"],"semavi":["turkish"],"sembol":["turkish"],"seminer":["turkish"],"senaryo":["turkish"],"sendika":["turkish"],"senkron":["turkish"],"sensör":["turkish"],"sentez":["turkish"],"sepet":["turkish"],"seramik":["turkish"],"serbest":["turkish"],"serdar":["turkish"],"seremoni":["turkish"],"sergi":["turkish"],"serhat":["turkish"],"serin":["turkish"],"sermaye":["turkish"],"serpuş":["turkish"],"sersem":["turkish"],"serüven":["turkish"],"sesli":["turkish"],"sesteş":["turkish"],"sevap":["turkish"],"seviye":["turkish"],"seyahat":["turkish"],"seyirci":["turkish"],"sezon":["turkish"],"sıcak":["turkish"],"sıfat":["turkish"],"sıhhi":["turkish"],"sınanma":["turkish"],"sınır":["turkish"],"sıradan":["turkish"],"sırdaş":["turkish"],"sırma":["turkish"],"sırtüstü":["turkish"],"sızgıt":["turkish"],"siftah":["turkish"],"sigorta":["turkish"],"sihirbaz":["turkish"],"silah":["turkish"],"silecek":["turkish"],"silindir":["turkish"],"simetri":["turkish"],"simge":["turkish"],"simit":["turkish"],"sincap":["turkish"],"sindirim":["turkish"],"sinema":["turkish"],"sinirli":["turkish"],"sipariş":["turkish"],"sirke":["turkish"],"siroz":["turkish"],"sistem":["turkish"],"sivilce":["turkish"],"siyasi":["turkish"],"soba":["turkish"],"sofra":["turkish"],"soğuk":["turkish"],"sohbet":["turkish"],"sokak":["turkish"],"solfej":["turkish"],"solunum":["turkish"],"somut":["turkish"],"sonbahar":["turkish"],"sonraki":["turkish"],"sonsuz":["turkish"],"sorunsuz":["turkish"],"sosyete":["turkish"],"soyağacı":["turkish"],"soydaş":["turkish"],"soygun":["turkish"],"soytarı":["turkish"],"söğüş":["turkish"],"sömürge":["turkish"],"sönük":["turkish"],"söylem":["turkish"],"sözcük":["turkish"],"sözde":["turkish"],"spatula":["turkish"],"spektrum":["turkish"],"spiker":["turkish"],"sporcu":["turkish"],"sprey":["turkish"],"stabil":["turkish"],"statü":["turkish"],"stok":["turkish"],"stopaj":["turkish"],"strateji":["turkish"],"subay":["turkish"],"sucuk":["turkish"],"suçüstü":["turkish"],"suhulet":["turkish"],"sulama":["turkish"],"sungur":["turkish"],"sunucu":["turkish"],"surat":["turkish"],"susam":["turkish"],"suskun":["turkish"],"sükse":["turkish"],"sükut":["turkish"],"sülale":["turkish"],"sünger":["turkish"],"süpürge":["turkish"],"sürahi":["turkish"],"süreç":["turkish"],"sürgün":["turkish"],"sürüm":["turkish"],"süsleme":["turkish"],"sütanne":["turkish"],"sütlaç":["turkish"],"sütun":["turkish"],"süvari":["turkish"],"şahane":["turkish"],"şahbaz":["turkish"],"şahit":["turkish"],"şahsiyet":["turkish"],"şakıma":["turkish"],"şaklaban":["turkish"],"şakrak":["turkish"],"şamar":["turkish"],"şampiyon":["turkish"],"şanslı":["turkish"],"şantiye":["turkish"],"şapka":["turkish"],"şarkıcı":["turkish"],"şartname":["turkish"],"şaşırma":["turkish"],"şaşkın":["turkish"],"şatafat":["turkish"],"şayet":["turkish"],"şebeke":["turkish"],"şefkat":["turkish"],"şeftali":["turkish"],"şehir":["turkish"],"şehvet":["turkish"],"şeker":["turkish"],"şekil":["turkish"],"şelale":["turkish"],"şema":["turkish"],"şemsiye":["turkish"],"şerbet":["turkish"],"şeref":["turkish"],"şerit":["turkish"],"şımarık":["turkish"],"şıpıdık":["turkish"],"şifre":["turkish"],"şimdi":["turkish"],"şimşek":["turkish"],"şipşak":["turkish"],"şirin":["turkish"],"şişe":["turkish"],"şişirme":["turkish"],"şofben":["turkish"],"şöhret":["turkish"],"şölen":["turkish"],"şüphe":["turkish"],"tabaka":["turkish"],"tabure":["turkish"],"tadilat":["turkish"],"taharet":["turkish"],"tahıl":["turkish"],"tahkim":["turkish"],"tahlil":["turkish"],"tahmin":["turkish"],"tahrifat":["turkish"],"tahsilat":["turkish"],"tahta":["turkish"],"taklit":["turkish"],"takoz":["turkish"],"taksici":["turkish"],"taktik":["turkish"],"takvim":["turkish"],"talebe":["turkish"],"talip":["turkish"],"tamamen":["turkish"],"tamirci":["turkish"],"tamtakır":["turkish"],"tandır":["turkish"],"tanecik":["turkish"],"tanıtım":["turkish"],"tanrı":["turkish"],"tansiyon":["turkish"],"tapan":["turkish"],"tapınak":["turkish"],"taptaze":["turkish"],"tapu":["turkish"],"tarafgir":["turkish"],"tarhana":["turkish"],"tarım":["turkish"],"tarih":["turkish"],"tarla":["turkish"],"tartak":["turkish"],"tarumar":["turkish"],"tasarım":["turkish"],"tasdik":["turkish"],"taslak":["turkish"],"tastamam":["turkish"],"taşeron":["turkish"],"taşınmaz":["turkish"],"taşra":["turkish"],"tatava":["turkish"],"tatbikat":["turkish"],"tatil":["turkish"],"tatlı":["turkish"],"tavsiye":["turkish"],"tavşan":["turkish"],"tavuk":["turkish"],"taze":["turkish"],"taziye":["turkish"],"tazminat":["turkish"],"tebeşir":["turkish"],"tebrik":["turkish"],"tecrübe":["turkish"],"teçhizat":["turkish"],"tedarik":["turkish"],"tedbir":["turkish"],"teftiş":["turkish"],"teğet":["turkish"],"teğmen":["turkish"],"tehdit":["turkish"],"tehlike":["turkish"],"tekdüze":["turkish"],"tekerlek":["turkish"],"tekme":["turkish"],"teknik":["turkish"],"tekrar":["turkish"],"telef":["turkish"],"telsiz":["turkish"],"telve":["turkish"],"temas":["turkish"],"tembel":["turkish"],"temiz":["turkish"],"temkin":["turkish"],"temsilci":["turkish"],"tendon":["turkish"],"teneke":["turkish"],"tenha":["turkish"],"tenkit":["turkish"],"tepegöz":["turkish"],"tepki":["turkish"],"terazi":["turkish"],"terbiye":["turkish"],"tercih":["turkish"],"tereyağı":["turkish"],"terfi":["turkish"],"terim":["turkish"],"terminal":["turkish"],"tersane":["turkish"],"tertip":["turkish"],"tesadüf":["turkish"],"tescil":["turkish"],"tesir":["turkish"],"teslimat":["turkish"],"tespit":["turkish"],"testere":["turkish"],"teşekkür":["turkish"],"teşhir":["turkish"],"teşrif":["turkish"],"teşvik":["turkish"],"teyze":["turkish"],"tezahür":["turkish"],"tezgah":["turkish"],"tıbbi":["turkish"],"tıkaç":["turkish"],"tıkışık":["turkish"],"tıknaz":["turkish"],"tılsım":["turkish"],"tıpkı":["turkish"],"tıraş":["turkish"],"tırışka":["turkish"],"tırmanış":["turkish"],"tırnak":["turkish"],"tırpan":["turkish"],"tıslama":["turkish"],"ticaret":["turkish"],"tilki":["turkish"],"tiryaki":["turkish"],"titreşim":["turkish"],"tohum":["turkish"],"tokat":["turkish"],"tolere":["turkish"],"tombak":["turkish"],"tomurcuk":["turkish"],"topaç":["turkish"],"toplum":["turkish"],"toprak":["turkish"],"toptan":["turkish"],"toraman":["turkish"],"torpido":["turkish"],"tortu":["turkish"],"tosbağa":["turkish"],"toynak":["turkish"],"tören":["turkish"],"trafik":["turkish"],"trajedi":["turkish"],"tramvay":["turkish"],"tribün":["turkish"],"triko":["turkish"],"tugay":["turkish"],"tuğla":["turkish"],"tuğrul":["turkish"],"tuhaf":["turkish"],"tulumba":["turkish"],"tunç":["turkish"],"turan":["turkish"],"turkuaz":["turkish"],"turnusol":["turkish"],"turşu":["turkish"],"turuncu":["turkish"],"tutanak":["turkish"],"tutkal":["turkish"],"tutsak":["turkish"],"tutum":["turkish"],"tuyuğ":["turkish"],"tuzlu":["turkish"],"tüccar":["turkish"],"tüfek":["turkish"],"tükenmez":["turkish"],"tülbent":["turkish"],"tümleç":["turkish"],"tünel":["turkish"],"türbin":["turkish"],"türev":["turkish"],"türk":["turkish"],"tüzük":["turkish"],"ucube":["turkish"],"ucuz":["turkish"],"uçak":["turkish"],"uçurtma":["turkish"],"ufuk":["turkish"],"uğrak":["turkish"],"uğur":["turkish"],"ukala":["turkish"],"ulaşım":["turkish"],"ulema":["turkish"],"ulus":["turkish"],"ulvi":["turkish"],"umursama":["turkish"],"umut":["turkish"],"unutkan":["turkish"],"uslu":["turkish"],"ustabaşı":["turkish"],"ustura":["turkish"],"usul":["turkish"],"utangaç":["turkish"],"uyanık":["turkish"],"uyarı":["turkish"],"uydu":["turkish"],"uygar":["turkish"],"uygulama":["turkish"],"uykusuz":["turkish"],"uysal":["turkish"],"uyuşma":["turkish"],"uzantı":["turkish"],"uzay":["turkish"],"uzgören":["turkish"],"uzlaşma":["turkish"],"uzman":["turkish"],"uzun":["turkish"],"ücra":["turkish"],"ücret":["turkish"],"üçbudak":["turkish"],"üçgen":["turkish"],"üçkağıt":["turkish"],"üçleme":["turkish"],"üfürük":["turkish"],"ülke":["turkish"],"ümit":["turkish"],"üniforma":["turkish"],"ünite":["turkish"],"ünlem":["turkish"],"üretken":["turkish"],"ürün":["turkish"],"üslup":["turkish"],"üstel":["turkish"],"üstün":["turkish"],"üşengeç":["turkish"],"üşüme":["turkish"],"ütopya":["turkish"],"üvey":["turkish"],"üzengi":["turkish"],"üzgün":["turkish"],"üzüm":["turkish"],"vaka":["turkish"],"vakfiye":["turkish"],"vakıf":["turkish"],"vakit":["turkish"],"vakum":["turkish"],"vapur":["turkish"],"varil":["turkish"],"varlık":["turkish"],"varsayım":["turkish"],"varyemez":["turkish"],"vasıta":["turkish"],"vasiyet":["turkish"],"vatandaş":["turkish"],"vazife":["turkish"],"vazo":["turkish"],"veciz":["turkish"],"vefa":["turkish"],"vehim":["turkish"],"veliaht":["turkish"],"veresiye":["turkish"],"verimli":["turkish"],"verkaç":["turkish"],"vernik":["turkish"],"vertigo":["turkish"],"vesait":["turkish"],"vesika":["turkish"],"vestiyer":["turkish"],"veznedar":["turkish"],"vicdan":["turkish"],"vilayet":["turkish"],"virane":["turkish"],"virgül":["turkish"],"vişne":["turkish"],"vites":["turkish"],"vokal":["turkish"],"volkan":["turkish"],"vurma":["turkish"],"vurucu":["turkish"],"vücut":["turkish"],"yabancı":["turkish"],"yabgu":["turkish"],"yağış":["turkish"],"yağlı":["turkish"],"yağmur":["turkish"],"yakamoz":["turkish"],"yakın":["turkish"],"yaklaşık":["turkish"],"yalçın":["turkish"],"yalıtım":["turkish"],"yaman":["turkish"],"yanardağ":["turkish"],"yangın":["turkish"],"yanıt":["turkish"],"yankı":["turkish"],"yanlış":["turkish"],"yansıma":["turkish"],"yapay":["turkish"],"yapboz":["turkish"],"yapımcı":["turkish"],"yaprak":["turkish"],"yaratık":["turkish"],"yarbay":["turkish"],"yardım":["turkish"],"yargıç":["turkish"],"yarıçap":["turkish"],"yasemin":["turkish"],"yastık":["turkish"],"yaşam":["turkish"],"yatak":["turkish"],"yatırım":["turkish"],"yavru":["turkish"],"yaygara":["turkish"],"yayıncı":["turkish"],"yayla":["turkish"],"yazılım":["turkish"],"yekpare":["turkish"],"yekvücut":["turkish"],"yelkovan":["turkish"],"yelpaze":["turkish"],"yemek":["turkish"],"yemiş":["turkish"],"yengeç":["turkish"],"yeniçeri":["turkish"],"yeraltı":["turkish"],"yerküre":["turkish"],"yerleşke":["turkish"],"yeryüzü":["turkish"],"yeşil":["turkish"],"yetenek":["turkish"],"yetkili":["turkish"],"yığınak":["turkish"],"yıkama":["turkish"],"yılbaşı":["turkish"],"yıldırım":["turkish"],"yılkı":["turkish"],"yılmaz":["turkish"],"yırtıcı":["turkish"],"yiğit":["turkish"],"yoğurt":["turkish"],"yokuş":["turkish"],"yolcu":["turkish"],"yoldaş":["turkish"],"yolgeçen":["turkish"],"yolkesen":["turkish"],"yolüstü":["turkish"],"yordam":["turkish"],"yorgan":["turkish"],"yorumcu":["turkish"],"yosun":["turkish"],"yöndeş":["turkish"],"yönetim":["turkish"],"yönlü":["turkish"],"yöntem":["turkish"],"yöresel":["turkish"],"yörünge":["turkish"],"yufka":["turkish"],"yukarı":["turkish"],"yumruk":["turkish"],"yumurta":["turkish"],"yuvarlak":["turkish"],"yücelme":["turkish"],"yükçeker":["turkish"],"yüklem":["turkish"],"yüksek":["turkish"],"yürek":["turkish"],"yürütme":["turkish"],"yüzde":["turkish"],"yüzeysel":["turkish"],"yüzgeç":["turkish"],"yüzüstü":["turkish"],"yüzyıl":["turkish"],"zabıta":["turkish"],"zafer":["turkish"],"zahmet":["turkish"],"zambak":["turkish"],"zaptiye":["turkish"],"zarafet":["turkish"],"zaruret":["turkish"],"zeka":["turkish"],"zekice":["turkish"],"zemberek":["turkish"],"zemin":["turkish"],"zencefil":["turkish"],"zeplin":["turkish"],"zeytin":["turkish"],"zıbın":["turkish"],"zılgıt":["turkish"],"zımbırtı":["turkish"],"zımpara":["turkish"],"zıpkın":["turkish"],"zigon":["turkish"],"zihinsel":["turkish"],"zihniyet":["turkish"],"zincir":["turkish"],"zindan":["turkish"],"zirzop":["turkish"],"ziyaret":["turkish"],"ziynet":["turkish"],"zoraki":["turkish"],"zorlu":["turkish"],"zorunlu":["turkish"],"züğürt":["turkish"],"zümre":["turkish"]}["abacate","abaixo","abalar","abater","abduzir","abelha","aberto","abismo","abotoar","abranger","abreviar","abrigar","abrupto","absinto","absoluto","absurdo","abutre","acabado","acalmar","acampar","acanhar","acaso","aceitar","acelerar","acenar","acervo","acessar","acetona","achatar","acidez","acima","acionado","acirrar","aclamar","aclive","acolhida","acomodar","acoplar","acordar","acumular","acusador","adaptar","adega","adentro","adepto","adequar","aderente","adesivo","adeus","adiante","aditivo","adjetivo","adjunto","admirar","adorar","adquirir","adubo","adverso","advogado","aeronave","afastar","aferir","afetivo","afinador","afivelar","aflito","afluente","afrontar","agachar","agarrar","agasalho","agenciar","agilizar","agiota","agitado","agora","agradar","agreste","agrupar","aguardar","agulha","ajoelhar","ajudar","ajustar","alameda","alarme","alastrar","alavanca","albergue","albino","alcatra","aldeia","alecrim","alegria","alertar","alface","alfinete","algum","alheio","aliar","alicate","alienar","alinhar","aliviar","almofada","alocar","alpiste","alterar","altitude","alucinar","alugar","aluno","alusivo","alvo","amaciar","amador","amarelo","amassar","ambas","ambiente","ameixa","amenizar","amido","amistoso","amizade","amolador","amontoar","amoroso","amostra","amparar","ampliar","ampola","anagrama","analisar","anarquia","anatomia","andaime","anel","anexo","angular","animar","anjo","anomalia","anotado","ansioso","anterior","anuidade","anunciar","anzol","apagador","apalpar","apanhado","apego","apelido","apertada","apesar","apetite","apito","aplauso","aplicada","apoio","apontar","aposta","aprendiz","aprovar","aquecer","arame","aranha","arara","arcada","ardente","areia","arejar","arenito","aresta","argiloso","argola","arma","arquivo","arraial","arrebate","arriscar","arroba","arrumar","arsenal","arterial","artigo","arvoredo","asfaltar","asilado","aspirar","assador","assinar","assoalho","assunto","astral","atacado","atadura","atalho","atarefar","atear","atender","aterro","ateu","atingir","atirador","ativo","atoleiro","atracar","atrevido","atriz","atual","atum","auditor","aumentar","aura","aurora","autismo","autoria","autuar","avaliar","avante","avaria","avental","avesso","aviador","avisar","avulso","axila","azarar","azedo","azeite","azulejo","babar","babosa","bacalhau","bacharel","bacia","bagagem","baiano","bailar","baioneta","bairro","baixista","bajular","baleia","baliza","balsa","banal","bandeira","banho","banir","banquete","barato","barbado","baronesa","barraca","barulho","baseado","bastante","batata","batedor","batida","batom","batucar","baunilha","beber","beijo","beirada","beisebol","beldade","beleza","belga","beliscar","bendito","bengala","benzer","berimbau","berlinda","berro","besouro","bexiga","bezerro","bico","bicudo","bienal","bifocal","bifurcar","bigorna","bilhete","bimestre","bimotor","biologia","biombo","biosfera","bipolar","birrento","biscoito","bisneto","bispo","bissexto","bitola","bizarro","blindado","bloco","bloquear","boato","bobagem","bocado","bocejo","bochecha","boicotar","bolada","boletim","bolha","bolo","bombeiro","bonde","boneco","bonita","borbulha","borda","boreal","borracha","bovino","boxeador","branco","brasa","braveza","breu","briga","brilho","brincar","broa","brochura","bronzear","broto","bruxo","bucha","budismo","bufar","bule","buraco","busca","busto","buzina","cabana","cabelo","cabide","cabo","cabrito","cacau","cacetada","cachorro","cacique","cadastro","cadeado","cafezal","caiaque","caipira","caixote","cajado","caju","calafrio","calcular","caldeira","calibrar","calmante","calota","camada","cambista","camisa","camomila","campanha","camuflar","canavial","cancelar","caneta","canguru","canhoto","canivete","canoa","cansado","cantar","canudo","capacho","capela","capinar","capotar","capricho","captador","capuz","caracol","carbono","cardeal","careca","carimbar","carneiro","carpete","carreira","cartaz","carvalho","casaco","casca","casebre","castelo","casulo","catarata","cativar","caule","causador","cautelar","cavalo","caverna","cebola","cedilha","cegonha","celebrar","celular","cenoura","censo","centeio","cercar","cerrado","certeiro","cerveja","cetim","cevada","chacota","chaleira","chamado","chapada","charme","chatice","chave","chefe","chegada","cheiro","cheque","chicote","chifre","chinelo","chocalho","chover","chumbo","chutar","chuva","cicatriz","ciclone","cidade","cidreira","ciente","cigana","cimento","cinto","cinza","ciranda","circuito","cirurgia","citar","clareza","clero","clicar","clone","clube","coado","coagir","cobaia","cobertor","cobrar","cocada","coelho","coentro","coeso","cogumelo","coibir","coifa","coiote","colar","coleira","colher","colidir","colmeia","colono","coluna","comando","combinar","comentar","comitiva","comover","complexo","comum","concha","condor","conectar","confuso","congelar","conhecer","conjugar","consumir","contrato","convite","cooperar","copeiro","copiador","copo","coquetel","coragem","cordial","corneta","coronha","corporal","correio","cortejo","coruja","corvo","cosseno","costela","cotonete","couro","couve","covil","cozinha","cratera","cravo","creche","credor","creme","crer","crespo","criada","criminal","crioulo","crise","criticar","crosta","crua","cruzeiro","cubano","cueca","cuidado","cujo","culatra","culminar","culpar","cultura","cumprir","cunhado","cupido","curativo","curral","cursar","curto","cuspir","custear","cutelo","damasco","datar","debater","debitar","deboche","debulhar","decalque","decimal","declive","decote","decretar","dedal","dedicado","deduzir","defesa","defumar","degelo","degrau","degustar","deitado","deixar","delator","delegado","delinear","delonga","demanda","demitir","demolido","dentista","depenado","depilar","depois","depressa","depurar","deriva","derramar","desafio","desbotar","descanso","desenho","desfiado","desgaste","desigual","deslize","desmamar","desova","despesa","destaque","desviar","detalhar","detentor","detonar","detrito","deusa","dever","devido","devotado","dezena","diagrama","dialeto","didata","difuso","digitar","dilatado","diluente","diminuir","dinastia","dinheiro","diocese","direto","discreta","disfarce","disparo","disquete","dissipar","distante","ditador","diurno","diverso","divisor","divulgar","dizer","dobrador","dolorido","domador","dominado","donativo","donzela","dormente","dorsal","dosagem","dourado","doutor","drenagem","drible","drogaria","duelar","duende","dueto","duplo","duquesa","durante","duvidoso","eclodir","ecoar","ecologia","edificar","edital","educado","efeito","efetivar","ejetar","elaborar","eleger","eleitor","elenco","elevador","eliminar","elogiar","embargo","embolado","embrulho","embutido","emenda","emergir","emissor","empatia","empenho","empinado","empolgar","emprego","empurrar","emulador","encaixe","encenado","enchente","encontro","endeusar","endossar","enfaixar","enfeite","enfim","engajado","engenho","englobar","engomado","engraxar","enguia","enjoar","enlatar","enquanto","enraizar","enrolado","enrugar","ensaio","enseada","ensino","ensopado","entanto","enteado","entidade","entortar","entrada","entulho","envergar","enviado","envolver","enxame","enxerto","enxofre","enxuto","epiderme","equipar","ereto","erguido","errata","erva","ervilha","esbanjar","esbelto","escama","escola","escrita","escuta","esfinge","esfolar","esfregar","esfumado","esgrima","esmalte","espanto","espelho","espiga","esponja","espreita","espumar","esquerda","estaca","esteira","esticar","estofado","estrela","estudo","esvaziar","etanol","etiqueta","euforia","europeu","evacuar","evaporar","evasivo","eventual","evidente","evoluir","exagero","exalar","examinar","exato","exausto","excesso","excitar","exclamar","executar","exemplo","exibir","exigente","exonerar","expandir","expelir","expirar","explanar","exposto","expresso","expulsar","externo","extinto","extrato","fabricar","fabuloso","faceta","facial","fada","fadiga","faixa","falar","falta","familiar","fandango","fanfarra","fantoche","fardado","farelo","farinha","farofa","farpa","fartura","fatia","fator","favorita","faxina","fazenda","fechado","feijoada","feirante","felino","feminino","fenda","feno","fera","feriado","ferrugem","ferver","festejar","fetal","feudal","fiapo","fibrose","ficar","ficheiro","figurado","fileira","filho","filme","filtrar","firmeza","fisgada","fissura","fita","fivela","fixador","fixo","flacidez","flamingo","flanela","flechada","flora","flutuar","fluxo","focal","focinho","fofocar","fogo","foguete","foice","folgado","folheto","forjar","formiga","forno","forte","fosco","fossa","fragata","fralda","frango","frasco","fraterno","freira","frente","fretar","frieza","friso","fritura","fronha","frustrar","fruteira","fugir","fulano","fuligem","fundar","fungo","funil","furador","furioso","futebol","gabarito","gabinete","gado","gaiato","gaiola","gaivota","galega","galho","galinha","galocha","ganhar","garagem","garfo","gargalo","garimpo","garoupa","garrafa","gasoduto","gasto","gata","gatilho","gaveta","gazela","gelado","geleia","gelo","gemada","gemer","gemido","generoso","gengiva","genial","genoma","genro","geologia","gerador","germinar","gesso","gestor","ginasta","gincana","gingado","girafa","girino","glacial","glicose","global","glorioso","goela","goiaba","golfe","golpear","gordura","gorjeta","gorro","gostoso","goteira","governar","gracejo","gradual","grafite","gralha","grampo","granada","gratuito","graveto","graxa","grego","grelhar","greve","grilo","grisalho","gritaria","grosso","grotesco","grudado","grunhido","gruta","guache","guarani","guaxinim","guerrear","guiar","guincho","guisado","gula","guloso","guru","habitar","harmonia","haste","haver","hectare","herdar","heresia","hesitar","hiato","hibernar","hidratar","hiena","hino","hipismo","hipnose","hipoteca","hoje","holofote","homem","honesto","honrado","hormonal","hospedar","humorado","iate","ideia","idoso","ignorado","igreja","iguana","ileso","ilha","iludido","iluminar","ilustrar","imagem","imediato","imenso","imersivo","iminente","imitador","imortal","impacto","impedir","implante","impor","imprensa","impune","imunizar","inalador","inapto","inativo","incenso","inchar","incidir","incluir","incolor","indeciso","indireto","indutor","ineficaz","inerente","infantil","infestar","infinito","inflamar","informal","infrator","ingerir","inibido","inicial","inimigo","injetar","inocente","inodoro","inovador","inox","inquieto","inscrito","inseto","insistir","inspetor","instalar","insulto","intacto","integral","intimar","intocado","intriga","invasor","inverno","invicto","invocar","iogurte","iraniano","ironizar","irreal","irritado","isca","isento","isolado","isqueiro","italiano","janeiro","jangada","janta","jararaca","jardim","jarro","jasmim","jato","javali","jazida","jejum","joaninha","joelhada","jogador","joia","jornal","jorrar","jovem","juba","judeu","judoca","juiz","julgador","julho","jurado","jurista","juro","justa","labareda","laboral","lacre","lactante","ladrilho","lagarta","lagoa","laje","lamber","lamentar","laminar","lampejo","lanche","lapidar","lapso","laranja","lareira","largura","lasanha","lastro","lateral","latido","lavanda","lavoura","lavrador","laxante","lazer","lealdade","lebre","legado","legendar","legista","leigo","leiloar","leitura","lembrete","leme","lenhador","lentilha","leoa","lesma","leste","letivo","letreiro","levar","leveza","levitar","liberal","libido","liderar","ligar","ligeiro","limitar","limoeiro","limpador","linda","linear","linhagem","liquidez","listagem","lisura","litoral","livro","lixa","lixeira","locador","locutor","lojista","lombo","lona","longe","lontra","lorde","lotado","loteria","loucura","lousa","louvar","luar","lucidez","lucro","luneta","lustre","lutador","luva","macaco","macete","machado","macio","madeira","madrinha","magnata","magreza","maior","mais","malandro","malha","malote","maluco","mamilo","mamoeiro","mamute","manada","mancha","mandato","manequim","manhoso","manivela","manobrar","mansa","manter","manusear","mapeado","maquinar","marcador","maresia","marfim","margem","marinho","marmita","maroto","marquise","marreco","martelo","marujo","mascote","masmorra","massagem","mastigar","matagal","materno","matinal","matutar","maxilar","medalha","medida","medusa","megafone","meiga","melancia","melhor","membro","memorial","menino","menos","mensagem","mental","merecer","mergulho","mesada","mesclar","mesmo","mesquita","mestre","metade","meteoro","metragem","mexer","mexicano","micro","migalha","migrar","milagre","milenar","milhar","mimado","minerar","minhoca","ministro","minoria","miolo","mirante","mirtilo","misturar","mocidade","moderno","modular","moeda","moer","moinho","moita","moldura","moleza","molho","molinete","molusco","montanha","moqueca","morango","morcego","mordomo","morena","mosaico","mosquete","mostarda","motel","motim","moto","motriz","muda","muito","mulata","mulher","multar","mundial","munido","muralha","murcho","muscular","museu","musical","nacional","nadador","naja","namoro","narina","narrado","nascer","nativa","natureza","navalha","navegar","navio","neblina","nebuloso","negativa","negociar","negrito","nervoso","neta","neural","nevasca","nevoeiro","ninar","ninho","nitidez","nivelar","nobreza","noite","noiva","nomear","nominal","nordeste","nortear","notar","noticiar","noturno","novelo","novilho","novo","nublado","nudez","numeral","nupcial","nutrir","nuvem","obcecado","obedecer","objetivo","obrigado","obscuro","obstetra","obter","obturar","ocidente","ocioso","ocorrer","oculista","ocupado","ofegante","ofensiva","oferenda","oficina","ofuscado","ogiva","olaria","oleoso","olhar","oliveira","ombro","omelete","omisso","omitir","ondulado","oneroso","ontem","opcional","operador","oponente","oportuno","oposto","orar","orbitar","ordem","ordinal","orfanato","orgasmo","orgulho","oriental","origem","oriundo","orla","ortodoxo","orvalho","oscilar","ossada","osso","ostentar","otimismo","ousadia","outono","outubro","ouvido","ovelha","ovular","oxidar","oxigenar","pacato","paciente","pacote","pactuar","padaria","padrinho","pagar","pagode","painel","pairar","paisagem","palavra","palestra","palheta","palito","palmada","palpitar","pancada","panela","panfleto","panqueca","pantanal","papagaio","papelada","papiro","parafina","parcial","pardal","parede","partida","pasmo","passado","pastel","patamar","patente","patinar","patrono","paulada","pausar","peculiar","pedalar","pedestre","pediatra","pedra","pegada","peitoral","peixe","pele","pelicano","penca","pendurar","peneira","penhasco","pensador","pente","perceber","perfeito","pergunta","perito","permitir","perna","perplexo","persiana","pertence","peruca","pescado","pesquisa","pessoa","petiscar","piada","picado","piedade","pigmento","pilastra","pilhado","pilotar","pimenta","pincel","pinguim","pinha","pinote","pintar","pioneiro","pipoca","piquete","piranha","pires","pirueta","piscar","pistola","pitanga","pivete","planta","plaqueta","platina","plebeu","plumagem","pluvial","pneu","poda","poeira","poetisa","polegada","policiar","poluente","polvilho","pomar","pomba","ponderar","pontaria","populoso","porta","possuir","postal","pote","poupar","pouso","povoar","praia","prancha","prato","praxe","prece","predador","prefeito","premiar","prensar","preparar","presilha","pretexto","prevenir","prezar","primata","princesa","prisma","privado","processo","produto","profeta","proibido","projeto","prometer","propagar","prosa","protetor","provador","publicar","pudim","pular","pulmonar","pulseira","punhal","punir","pupilo","pureza","puxador","quadra","quantia","quarto","quase","quebrar","queda","queijo","quente","querido","quimono","quina","quiosque","rabanada","rabisco","rachar","racionar","radial","raiar","rainha","raio","raiva","rajada","ralado","ramal","ranger","ranhura","rapadura","rapel","rapidez","raposa","raquete","raridade","rasante","rascunho","rasgar","raspador","rasteira","rasurar","ratazana","ratoeira","realeza","reanimar","reaver","rebaixar","rebelde","rebolar","recado","recente","recheio","recibo","recordar","recrutar","recuar","rede","redimir","redonda","reduzida","reenvio","refinar","refletir","refogar","refresco","refugiar","regalia","regime","regra","reinado","reitor","rejeitar","relativo","remador","remendo","remorso","renovado","reparo","repelir","repleto","repolho","represa","repudiar","requerer","resenha","resfriar","resgatar","residir","resolver","respeito","ressaca","restante","resumir","retalho","reter","retirar","retomada","retratar","revelar","revisor","revolta","riacho","rica","rigidez","rigoroso","rimar","ringue","risada","risco","risonho","robalo","rochedo","rodada","rodeio","rodovia","roedor","roleta","romano","roncar","rosado","roseira","rosto","rota","roteiro","rotina","rotular","rouco","roupa","roxo","rubro","rugido","rugoso","ruivo","rumo","rupestre","russo","sabor","saciar","sacola","sacudir","sadio","safira","saga","sagrada","saibro","salada","saleiro","salgado","saliva","salpicar","salsicha","saltar","salvador","sambar","samurai","sanar","sanfona","sangue","sanidade","sapato","sarda","sargento","sarjeta","saturar","saudade","saxofone","sazonal","secar","secular","seda","sedento","sediado","sedoso","sedutor","segmento","segredo","segundo","seiva","seleto","selvagem","semanal","semente","senador","senhor","sensual","sentado","separado","sereia","seringa","serra","servo","setembro","setor","sigilo","silhueta","silicone","simetria","simpatia","simular","sinal","sincero","singular","sinopse","sintonia","sirene","siri","situado","soberano","sobra","socorro","sogro","soja","solda","soletrar","solteiro","sombrio","sonata","sondar","sonegar","sonhador","sono","soprano","soquete","sorrir","sorteio","sossego","sotaque","soterrar","sovado","sozinho","suavizar","subida","submerso","subsolo","subtrair","sucata","sucesso","suco","sudeste","sufixo","sugador","sugerir","sujeito","sulfato","sumir","suor","superior","suplicar","suposto","suprimir","surdina","surfista","surpresa","surreal","surtir","suspiro","sustento","tabela","tablete","tabuada","tacho","tagarela","talher","talo","talvez","tamanho","tamborim","tampa","tangente","tanto","tapar","tapioca","tardio","tarefa","tarja","tarraxa","tatuagem","taurino","taxativo","taxista","teatral","tecer","tecido","teclado","tedioso","teia","teimar","telefone","telhado","tempero","tenente","tensor","tentar","termal","terno","terreno","tese","tesoura","testado","teto","textura","texugo","tiara","tigela","tijolo","timbrar","timidez","tingido","tinteiro","tiragem","titular","toalha","tocha","tolerar","tolice","tomada","tomilho","tonel","tontura","topete","tora","torcido","torneio","torque","torrada","torto","tostar","touca","toupeira","toxina","trabalho","tracejar","tradutor","trafegar","trajeto","trama","trancar","trapo","traseiro","tratador","travar","treino","tremer","trepidar","trevo","triagem","tribo","triciclo","tridente","trilogia","trindade","triplo","triturar","triunfal","trocar","trombeta","trova","trunfo","truque","tubular","tucano","tudo","tulipa","tupi","turbo","turma","turquesa","tutelar","tutorial","uivar","umbigo","unha","unidade","uniforme","urologia","urso","urtiga","urubu","usado","usina","usufruir","vacina","vadiar","vagaroso","vaidoso","vala","valente","validade","valores","vantagem","vaqueiro","varanda","vareta","varrer","vascular","vasilha","vassoura","vazar","vazio","veado","vedar","vegetar","veicular","veleiro","velhice","veludo","vencedor","vendaval","venerar","ventre","verbal","verdade","vereador","vergonha","vermelho","verniz","versar","vertente","vespa","vestido","vetorial","viaduto","viagem","viajar","viatura","vibrador","videira","vidraria","viela","viga","vigente","vigiar","vigorar","vilarejo","vinco","vinheta","vinil","violeta","virada","virtude","visitar","visto","vitral","viveiro","vizinho","voador","voar","vogal","volante","voleibol","voltagem","volumoso","vontade","vulto","vuvuzela","xadrez","xarope","xeque","xeretar","xerife","xingar","zangado","zarpar","zebu","zelador","zombar","zoologia","zumbido"]["абзац","абонент","абсурд","авангард","авария","август","авиация","автор","агент","агитация","агрегат","адвокат","адмирал","адрес","азарт","азот","академия","аквариум","аксиома","акула","акцент","акция","аллея","алмаз","алтарь","альбом","альянс","амбиция","анализ","анекдот","анкета","ансамбль","антенна","апельсин","аппарат","аппетит","апрель","аптека","арбуз","аргумент","аренда","арест","армия","аромат","арсенал","артерия","артист","архив","аспирант","асфальт","атака","атомный","атрибут","аукцион","афиша","аэропорт","бабочка","бабушка","багаж","база","бактерия","баланс","балерина","балкон","бандит","банк","барабан","барон","барышня","барьер","бассейн","батарея","башмак","башня","бедный","беженец","бездна","белка","белый","бензин","берег","беседа","бешеный","билет","бинокль","биржа","битва","благо","блеск","близкий","блин","блок","блюдо","богатый","бодрый","боец","бокал","боковой","бокс","более","болото","болтать","большой","бомба","борт","борьба","босой","ботинок","бояться","брак","брать","бревно","бред","бригада","бродяга","броня","бросить","брызги","брюки","брюхо","бугор","будка","будни","будущее","буква","букет","бульвар","бумага","бунт","бурный","буря","бутылка","бухта","бывший","быстро","бытовой","быть","бюджет","бюро","бюст","вагон","важный","вакцина","валенок","вальс","валюта","ванная","варенье","вариант","вблизи","вверх","вводить","вдали","вдвое","вдова","вдоль","вдруг","ведро","ведущий","ведьма","вежливо","везде","веко","вексель","велеть","великий","венец","веник","веранда","верблюд","верить","верный","версия","вертеть","верхний","вершина","весело","весна","весомый","вести","весь","ветеран","ветхий","вечер","вечно","вешалка","вещество","взамен","взгляд","вздох","взнос","взойти","взор","взрыв","взять","видеть","видимо","визг","визит","вилка","вина","вирус","висок","витамин","витрина","вихрь","вишня","вкус","влага","владелец","власть","влево","влияние","вложить","вместе","внешний","вникать","внимание","вновь","внук","внутри","внучка","внушать","вовлечь","вовремя","вовсю","вода","водород","водяной","воевать","возврат","возглас","воздух","возить","возле","возня","возраст","война","войско","вокзал","волос","волчий","вольный","воля","вообще","вопль","вопрос","ворота","восемь","восток","вплоть","вполне","вправе","впредь","впрочем","врач","вредный","время","вручить","всадник","всегда","вскоре","вскрыть","всплеск","вспышка","встреча","всюду","всякий","второй","вход","вчера","выбор","вывод","выгнать","выдать","выехать","вызов","выйти","выкуп","вылезти","вымыть","выпасть","выпить","выплата","выпуск","вырасти","выручка","выслать","высокий","выставка","вышка","вязать","вялый","газета","газовый","галерея","галстук","гамма","гарантия","гармония","гарнизон","гастроли","гвардия","гвоздь","гектар","генерал","гений","геном","геолог","герб","герой","гибкий","гигант","гимн","гипотеза","гитара","главный","глагол","гладить","глаз","глина","глоток","глубокий","глупый","глухой","глыба","глядеть","гнев","гнездо","гнилой","годовой","голова","голубой","голый","гонорар","гордость","горизонт","горло","горный","город","горшок","горький","горючее","горячий","готовый","градус","грамм","граница","граф","гребень","гриб","гримаса","грозить","грохот","грош","грубый","грудь","груз","грунт","группа","груша","грязный","губа","гудок","гулкий","гулять","гусеница","густо","гусь","давление","давно","даже","дальний","данный","дарить","датчик","дать","дача","двадцать","дважды","дверь","двигать","движение","двойной","двор","дебют","девятый","дежурный","действие","декабрь","деление","дело","дельфин","день","дерево","держать","дерзкий","десять","деталь","детский","дефект","дефицит","деятель","джаз","джинсы","джунгли","диагноз","диалог","диапазон","диван","дивизия","дивный","диета","дизайн","дикарь","дилер","динамика","диплом","директор","дитя","длинный","дневник","добрый","добыча","доверие","догадка","догнать","дождь","доклад","доктор","документ","долго","должен","долина","донос","дорога","досада","доска","достать","досуг","доход","доцент","дощатый","драка","древний","дремать","дробный","дрова","дрожать","другой","дружба","дубовый","дуга","думать","дурной","духи","душный","дуэль","дуэт","дыра","дыхание","дюжина","дядя","едва","единый","ерунда","если","ехать","жадный","жажда","жалеть","жалоба","жанр","жареный","жаркий","жгучий","жевать","желание","желудок","жена","женщина","жертва","жест","жидкость","житель","жить","жрец","жулик","журнал","жуткий","забрать","забыть","завести","завод","завтра","загадка","загнать","заговор","задача","задеть","задний","задолго","заехать","заказ","закон","закрыть","закуска","залезть","залить","залп","замок","замуж","замысел","занавес","заново","занять","заодно","запись","запрос","запуск","запястье","заранее","заросль","зарплата","заря","засада","заслуга","заснуть","застать","затвор","затеять","затрата","затылок","захват","зачем","защита","заявить","заяц","звезда","звено","звонить","здесь","зелень","земля","зеркало","зерно","зима","злой","змея","знамя","знание","значит","золотой","зона","зонтик","зоопарк","зрачок","зрение","зритель","зубной","зубр","игла","идеал","идеолог","идея","идол","идти","изба","избить","избрать","избыток","извлечь","извне","изгиб","изгнать","издание","изделие","изнутри","изобилие","изоляция","изредка","изрядно","изучение","изъять","изящный","икона","икра","иллюзия","именно","иметь","имидж","империя","импульс","иначе","инвалид","индекс","индивид","инерция","инженер","иногда","иной","институт","интерес","интрига","интуиция","инфаркт","инцидент","ирония","искать","испуг","история","итог","июнь","кабель","кабинет","каблук","кавалер","кадр","каждый","кажется","казино","калитка","камень","камин","канал","кандидат","каникулы","канон","капитан","капля","капот","капуста","карандаш","карета","каркас","карман","картина","карьера","каска","кассета","кастрюля","каталог","катер","каток","катушка","кафедра","качество","каша","кашлять","каюта","квадрат","квартира","квота","кепка","кивнуть","километр","кино","киоск","кипяток","кирпич","кислота","кисть","клавиша","клапан","класс","клей","клетка","клиент","климат","клиника","кличка","клоун","клочок","клуб","клумба","ключ","книга","кнопка","кнут","княгиня","князь","кобура","когда","кодекс","кожа","коктейль","колено","коллега","колонна","колпак","кольцо","колючий","коляска","команда","комедия","комиссия","коммуна","комната","комок","компания","комфорт","конвейер","конгресс","конечно","конкурс","контроль","концерт","конь","конюшня","копать","копейка","копыто","корабль","корень","корзина","коридор","кормить","корпус","космос","костюм","косяк","котел","котлета","который","коттедж","кофе","кофта","кошка","кража","край","красный","краткий","кредит","крем","крепкий","кресло","кривой","кризис","кристалл","критерий","кричать","кровь","крокодил","кролик","кроме","крона","круг","кружка","крупный","крутой","крушение","крыло","крыша","крючок","кстати","кубик","куда","кузов","кукла","кулак","кулиса","культура","кумир","купе","купить","купол","купюра","курица","курорт","курс","куртка","кусок","куст","кухня","кушать","лабиринт","лавка","лагерь","ладно","ладонь","лапа","лауреат","лгать","лебедь","левый","легенда","легкий","ледяной","лежать","лезвие","лезть","лекция","ленивый","лента","лепесток","лесной","лестница","лететь","лето","лечить","лига","лидер","лиловый","лимон","линия","липкий","лист","литр","лихой","лицо","лишить","лишний","ловить","логика","лодка","ложь","лозунг","локоть","лопата","лошадь","лукавый","луна","лучший","лысый","льгота","любить","любой","людской","люстра","лютый","лягушка","магазин","магия","майор","майский","максимум","макушка","мало","мальчик","мама","манера","марка","март","маршрут","масса","мастер","масштаб","материал","матч","махать","машина","маяк","мебель","медаль","медведь","медицина","медь","между","мелкий","мелочь","мемуары","меньше","меню","менять","мера","мерцать","место","месяц","металл","метод","метр","механизм","меховой","мечтать","мешать","мешок","миграция","микрофон","милиция","миллион","милость","миля","мимо","минерал","министр","минута","мирный","миска","миссия","митинг","мишень","младший","мнение","мнимый","много","могучий","модель","может","мозг","мокрый","молекула","молния","молодой","молчать","момент","монета","монитор","монолог","монстр","монтаж","мораль","море","морковь","мороз","морщина","мостовая","мотать","мотив","мотор","мохнатый","мрамор","мрачный","мстить","мудрый","мужество","мужчина","музей","музыка","мундир","муравей","мусор","муха","мчаться","мысль","мыться","мышца","мышь","мюзикл","мягкий","мясо","набор","навык","наглый","нагрузка","надежда","надзор","надо","наедине","назад","название","назло","наивный","найти","наконец","налево","наличие","налог","намерен","нанести","напасть","например","народ","наследие","натура","наука","наутро","начать","небо","неважно","невеста","негодяй","недавно","неделя","недолго","недра","недуг","нежный","незачем","некто","нелепый","неловко","нельзя","немало","немой","неплохо","нервный","нередко","нестись","неудача","неужели","нефть","неясный","нигде","низкий","никакой","никогда","никуда","ничто","ничуть","ниша","нищий","новость","новый","нога","ноготь","ножницы","ноздря","номер","носить","носок","ночь","ноябрь","нрав","нуль","нынче","нырять","нюанс","няня","обаяние","обед","обезьяна","обещать","обжечь","обзор","обилие","обитать","область","облик","обложка","обмен","обморок","обожать","обои","оболочка","оборона","обочина","образ","обрести","обрыв","обувь","обучение","обход","общество","общий","объект","обыск","обычно","обязать","овощи","овраг","овца","оговорка","ограда","огурец","одежда","одеяло","один","однако","одолеть","ожидать","озеро","океан","окно","около","окоп","окраина","октябрь","опасный","опека","операция","описание","оплата","опора","оппонент","оптимизм","оптовый","опухоль","опыт","оратор","орбита","орган","орден","орел","оригинал","ориентир","оркестр","оружие","осенний","осколок","осмотр","остров","отбор","отбыть","отвлечь","отдать","отдел","отдых","отель","отец","отзыв","отказ","отклик","открыть","откуда","отличие","отныне","отойти","отпуск","отрасль","отросток","отрывок","отряд","отсек","отставка","отсюда","оттенок","оттого","отчего","отъезд","офис","офицер","охота","охрана","оценка","очаг","очень","очередь","очищать","ошибка","ощущение","павильон","падать","пазуха","пакет","палата","палец","палуба","пальто","память","панель","паника","пара","парень","пароход","партия","парус","паспорт","пассажир","пастух","патент","патрон","пауза","паук","паутина","пафос","пахнуть","пациент","пачка","певец","педагог","пейзаж","пенсия","пепел","первый","перед","период","перо","перрон","персонаж","перчатка","песня","песок","петля","петрушка","петух","пехота","печать","печень","пешком","пещера","пианист","пиджак","пилот","пионер","пирамида","пирожок","письмо","пища","плавание","плакать","пламя","план","пласт","платить","пленный","плечо","плита","плод","плоский","плотный","плохой","площадь","плыть","плюс","пляж","плясать","победа","повар","повод","повсюду","повязка","погода","погреб","подбор","подвиг","подделка","поджать","поднос","подпись","подруга","подход","подчас","подъезд","поединок","поезд","поесть","поехать","пожалуй","пожилой","позади","позвать","поздний","позиция","позор","поиск","поймать","пойти","поклон","покой","покрыть","полдень","полезный","ползти","полк","полный","половина","полтора","польза","поляна","помидор","помнить","помощь","попасть","поперек","поплыть","пополам","поправка","попугай","попытка","порог","портрет","порция","порыв","порядок","после","посол","посреди","постель","посуда","потом","похвала","похожий","поцелуй","почва","почему","пошлина","поэма","поэтому","право","праздник","практика","прах","преграда","предмет","прежде","прелесть","премия","препарат","пресса","прибыть","прижать","прийти","приказ","прилавок","пример","принять","природа","притом","прихожая","прицел","причина","приют","прогноз","продукт","проект","прожить","прокат","промысел","пропуск","просто","против","профиль","процесс","прочий","прошлый","прощать","пружина","прут","прыжок","прямой","птица","публика","пугать","пуговица","пузырь","пульт","пуля","пункт","пускать","пустой","путь","пухлый","пучок","пушистый","пушка","пчела","пшеница","пылать","пыль","пышный","пьеса","пятка","пятно","пятый","пятьсот","работа","равнина","ради","радость","радуга","разбить","развитие","разговор","раздел","различие","размер","разный","разрыв","разум","район","ракета","раковина","рамка","рано","рапорт","распад","рассказ","расти","расход","расцвет","рация","рвануть","рваться","реакция","ребро","реветь","редактор","редкий","реестр","режим","резать","резерв","резина","резко","резной","рейс","реклама","рекорд","религия","рельс","ремень","ремонт","реплика","репортаж","ресница","ресторан","реформа","рецепт","речь","решение","ржавый","риск","рисунок","ритуал","рифма","робко","робот","ровесник","ровно","родной","рождение","роза","розовый","розыск","роль","роман","роскошь","роспись","рост","рубашка","рубеж","рубить","рубрика","рудник","рука","рукопись","румяный","русло","рухнуть","ручей","ручной","рыба","рыжий","рынок","рыхлый","рыцарь","рычаг","рюкзак","рядом","садовый","сажать","салон","салфетка","салют","самец","самовар","самый","сани","санкция","сапог","сарай","сатира","сахар","сбить","сбоку","сборная","сбыт","свадьба","свалка","сварить","свежий","сверху","свет","свеча","свинья","свист","свитер","свобода","сводка","свой","свыше","связь","сдаться","сделать","сегмент","сегодня","седло","седой","седьмой","сезон","сейф","сейчас","секрет","сектор","секунда","семинар","семья","сенатор","сено","сенсация","сентябрь","сервис","сердце","середина","сержант","серия","серый","сессия","сесть","сетевой","сжатый","сжечь","сзади","сигнал","сиденье","сила","силуэт","сильный","символ","симпатия","симфония","синий","синтез","синяк","сирень","система","ситуация","сияние","сказать","скала","скамейка","скандал","скатерть","скачок","скважина","сквер","сквозь","скелет","скидка","склад","сколько","скорый","скосить","скот","скрипка","скудный","скука","слабый","слава","сладкий","слегка","след","слеза","слепой","слесарь","слишком","слово","слог","сложный","сломать","служба","слух","случай","слышать","слюна","смежный","смелый","сменить","смесь","сметана","смех","смола","смуглый","смутный","смущать","смысл","снайпер","снаряд","сначала","снег","снизу","сниться","сно��а","снять","собака","соблазн","собрание","событие","совесть","совсем","согласие","создать","сознание","созреть","сойтись","сокол","солдат","соленый","солнце","солома","сомнение","сонный","соперник","соратник","сорвать","сосед","сосиска","состав","сотня","соус","союз","спад","спальня","спасти","спектр","сперва","спешить","спина","спирт","список","спичка","сплав","спонсор","спор","способ","справка","спустя","спутник","сразу","средство","срок","срыв","ссора","ссылка","ставить","стадия","стакан","станция","старый","стая","стебель","стекло","стена","степень","стереть","стиль","стимул","стирать","стихи","стоить","стойка","стол","стонать","стопа","сторона","стоянка","страна","стричь","строгий","струя","студент","стук","ступня","стыдно","суббота","субъект","сувенир","сугроб","сугубо","судить","судно","судьба","суета","суметь","сумма","сумрак","сундук","супруг","суровый","сутки","сухой","суша","существо","сфера","схема","схожий","сценарий","счастье","считать","съезд","сыграть","сырой","сытый","сыщик","сюда","сюжет","сюрприз","тайна","также","такой","такси","тактика","талия","таможня","танец","таракан","тарелка","тариф","тащить","таять","тварь","театр","тезис","текст","текущий","телефон","тема","темнота","теневой","теннис","теория","теперь","тепло","терапия","терзать","термин","терпеть","терраса","терять","тесный","тетрадь","техника","течение","тигр","типовой","тираж","титул","тихий","ткань","товарищ","тоже","толпа","толстый","толчок","толщина","только","тонкий","тонна","топить","топор","торговля","тормоз","торчать","тотчас","точка","точно","тощий","трава","традиция","трактор","трамвай","траншея","трасса","тревога","трезвый","тренер","трепет","треск","третий","трещина","трибуна","тридцать","триста","триумф","трогать","тройка","тронуть","тропа","тротуар","трубка","труд","трюк","тряпка","туго","туловище","туман","тумбочка","тундра","тупик","турист","турнир","тусклый","туфля","туча","тысяча","тяга","тяжело","убежать","убогий","уборка","уважение","увезти","уволить","угадать","угол","угощать","угроза","угрюмый","удар","удачный","уделять","удивить","удобный","удочка","уезжать","ужин","узел","узкий","уйти","указание","уклон","украсть","укусить","улетать","улица","улыбка","умело","умение","умный","умолять","унести","унижать","унылый","упаковка","упасть","упорно","упрек","урна","уровень","урожай","уронить","усадьба","усатый","усвоить","усилие","условие","услуга","усмешка","успеть","устав","устоять","утечка","утешать","утро","уцелеть","участие","ученик","учесть","ущелье","ущерб","уютный","фабрика","фаворит","факел","факт","фамилия","фантазия","фасад","февраль","феномен","фермер","фигура","физика","филиал","философ","фильм","финал","флаг","флот","фойе","фокус","фонарь","фонд","фонтан","форма","форум","фото","фрагмент","фраза","фракция","фронт","фрукт","функция","фуражка","футбол","футляр","халат","хаос","характер","хата","хвалить","хватать","хвойный","хвост","химия","хирург","хитрый","хищник","хлеб","хлынуть","хмурый","ходить","хозяин","хоккей","холм","холст","хорошо","хотеть","храбрый","храм","хранить","хребет","хрен","хрипло","хроника","хрупкий","художник","худший","хулиган","хутор","царь","цветок","целевой","целиком","целое","цель","цензура","ценить","центр","цепной","цикл","цилиндр","цирк","цитата","цифра","чайник","часы","чашка","человек","челюсть","чемодан","чемпион","чепуха","червь","чердак","через","чернила","черта","чеснок","честно","четверть","четыре","число","чистый","читатель","чтение","чтобы","чувство","чудак","чудный","чудо","чужой","чулок","чума","чушь","чуять","шагать","шанс","шапка","шарик","шарф","шахматы","шашлык","шедевр","шептать","шерсть","шестой","шинель","ширина","шишка","шкаф","школа","шкура","шланг","шлем","шнур","шоколад","шорох","шоссе","шпион","шприц","штаб","штамм","штаны","штатный","штора","штраф","штурм","штык","шумно","шуршать","шутить","шутка","щедрый","щека","щенок","экзамен","экипаж","экономия","экран","эксперт","элемент","элитный","эмоция","энергия","эпизод","эпоха","эскиз","эстрада","этап","этика","этот","эфир","эффект","эшелон","юбилей","юбка","южный","юмор","юность","юрист","юстиция","яблоко","явление","ягода","ядро","язык","яйцо","якобы","якорь","январь","яркий","ярмарка","ярость","ясный","яхта","ячейка","ящик"]["ábaco","abdomen","abeja","abierto","abogado","abono","aborto","abrazo","abrir","abuelo","abuso","acabar","academia","acceso","acción","aceite","acelga","acento","aceptar","ácido","aclarar","acné","acoger","acoso","activo","acto","actriz","actuar","acudir","acuerdo","acusar","adicto","admitir","adoptar","adorno","aduana","adulto","aéreo","afectar","afición","afinar","afirmar","ágil","agitar","agonía","agosto","agotar","agregar","agrio","agua","agudo","águila","aguja","ahogo","ahorro","aire","aislar","ajedrez","ajeno","ajuste","alacrán","alambre","alarma","alba","álbum","alcalde","aldea","alegre","alejar","alerta","aleta","alfiler","alga","algodón","aliado","aliento","alivio","alma","almeja","almíbar","altar","alteza","altivo","alto","altura","alumno","alzar","amable","amante","amapola","amargo","amasar","ámbar","ámbito","ameno","amigo","amistad","amor","amparo","amplio","ancho","anciano","ancla","andar","andén","anemia","ángulo","anillo","ánimo","anís","anotar","antena","antiguo","antojo","anual","anular","anuncio","añadir","añejo","año","apagar","aparato","apetito","apio","aplicar","apodo","aporte","apoyo","aprender","aprobar","apuesta","apuro","arado","araña","arar","árbitro","árbol","arbusto","archivo","arco","arder","ardilla","arduo","área","árido","aries","armonía","arnés","aroma","arpa","arpón","arreglo","arroz","arruga","arte","artista","asa","asado","asalto","ascenso","asegurar","aseo","asesor","asiento","asilo","asistir","asno","asombro","áspero","astilla","astro","astuto","asumir","asunto","atajo","ataque","atar","atento","ateo","ático","atleta","átomo","atraer","atroz","atún","audaz","audio","auge","aula","aumento","ausente","autor","aval","avance","avaro","ave","avellana","avena","avestruz","avión","aviso","ayer","ayuda","ayuno","azafrán","azar","azote","azúcar","azufre","azul","baba","babor","bache","bahía","baile","bajar","balanza","balcón","balde","bambú","banco","banda","baño","barba","barco","barniz","barro","báscula","bastón","basura","batalla","batería","batir","batuta","baúl","bazar","bebé","bebida","bello","besar","beso","bestia","bicho","bien","bingo","blanco","bloque","blusa","boa","bobina","bobo","boca","bocina","boda","bodega","boina","bola","bolero","bolsa","bomba","bondad","bonito","bono","bonsái","borde","borrar","bosque","bote","botín","bóveda","bozal","bravo","brazo","brecha","breve","brillo","brinco","brisa","broca","broma","bronce","brote","bruja","brusco","bruto","buceo","bucle","bueno","buey","bufanda","bufón","búho","buitre","bulto","burbuja","burla","burro","buscar","butaca","buzón","caballo","cabeza","cabina","cabra","cacao","cadáver","cadena","caer","café","caída","caimán","caja","cajón","cal","calamar","calcio","caldo","calidad","calle","calma","calor","calvo","cama","cambio","camello","camino","campo","cáncer","candil","canela","canguro","canica","canto","caña","cañón","caoba","caos","capaz","capitán","capote","captar","capucha","cara","carbón","cárcel","careta","carga","cariño","carne","carpeta","carro","carta","casa","casco","casero","caspa","castor","catorce","catre","caudal","causa","cazo","cebolla","ceder","cedro","celda","célebre","celoso","célula","cemento","ceniza","centro","cerca","cerdo","cereza","cero","cerrar","certeza","césped","cetro","chacal","chaleco","champú","chancla","chapa","charla","chico","chiste","chivo","choque","choza","chuleta","chupar","ciclón","ciego","cielo","cien","cierto","cifra","cigarro","cima","cinco","cine","cinta","ciprés","circo","ciruela","cisne","cita","ciudad","clamor","clan","claro","clase","clave","cliente","clima","clínica","cobre","cocción","cochino","cocina","coco","código","codo","cofre","coger","cohete","cojín","cojo","cola","colcha","colegio","colgar","colina","collar","colmo","columna","combate","comer","comida","cómodo","compra","conde","conejo","conga","conocer","consejo","contar","copa","copia","corazón","corbata","corcho","cordón","corona","correr","coser","cosmos","costa","cráneo","cráter","crear","crecer","creído","crema","cría","crimen","cripta","crisis","cromo","crónica","croqueta","crudo","cruz","cuadro","cuarto","cuatro","cubo","cubrir","cuchara","cuello","cuento","cuerda","cuesta","cueva","cuidar","culebra","culpa","culto","cumbre","cumplir","cuna","cuneta","cuota","cupón","cúpula","curar","curioso","curso","curva","cutis","dama","danza","dar","dardo","dátil","deber","débil","década","decir","dedo","defensa","definir","dejar","delfín","delgado","delito","demora","denso","dental","deporte","derecho","derrota","desayuno","deseo","desfile","desnudo","destino","desvío","detalle","detener","deuda","día","diablo","diadema","diamante","diana","diario","dibujo","dictar","diente","dieta","diez","difícil","digno","dilema","diluir","dinero","directo","dirigir","disco","diseño","disfraz","diva","divino","doble","doce","dolor","domingo","don","donar","dorado","dormir","dorso","dos","dosis","dragón","droga","ducha","duda","duelo","dueño","dulce","dúo","duque","durar","dureza","duro","ébano","ebrio","echar","eco","ecuador","edad","edición","edificio","editor","educar","efecto","eficaz","eje","ejemplo","elefante","elegir","elemento","elevar","elipse","élite","elixir","elogio","eludir","embudo","emitir","emoción","empate","empeño","empleo","empresa","enano","encargo","enchufe","encía","enemigo","enero","enfado","enfermo","engaño","enigma","enlace","enorme","enredo","ensayo","enseñar","entero","entrar","envase","envío","época","equipo","erizo","escala","escena","escolar","escribir","escudo","esencia","esfera","esfuerzo","espada","espejo","espía","esposa","espuma","esquí","estar","este","estilo","estufa","etapa","eterno","ética","etnia","evadir","evaluar","evento","evitar","exacto","examen","exceso","excusa","exento","exigir","exilio","existir","éxito","experto","explicar","exponer","extremo","fábrica","fábula","fachada","fácil","factor","faena","faja","falda","fallo","falso","faltar","fama","familia","famoso","faraón","farmacia","farol","farsa","fase","fatiga","fauna","favor","fax","febrero","fecha","feliz","feo","feria","feroz","fértil","fervor","festín","fiable","fianza","fiar","fibra","ficción","ficha","fideo","fiebre","fiel","fiera","fiesta","figura","fijar","fijo","fila","filete","filial","filtro","fin","finca","fingir","finito","firma","flaco","flauta","flecha","flor","flota","fluir","flujo","flúor","fobia","foca","fogata","fogón","folio","folleto","fondo","forma","forro","fortuna","forzar","fosa","foto","fracaso","frágil","franja","frase","fraude","freír","freno","fresa","frío","frito","fruta","fuego","fuente","fuerza","fuga","fumar","función","funda","furgón","furia","fusil","fútbol","futuro","gacela","gafas","gaita","gajo","gala","galería","gallo","gamba","ganar","gancho","ganga","ganso","garaje","garza","gasolina","gastar","gato","gavilán","gemelo","gemir","gen","género","genio","gente","geranio","gerente","germen","gesto","gigante","gimnasio","girar","giro","glaciar","globo","gloria","gol","golfo","goloso","golpe","goma","gordo","gorila","gorra","gota","goteo","gozar","grada","gráfico","grano","grasa","gratis","grave","grieta","grillo","gripe","gris","grito","grosor","grúa","grueso","grumo","grupo","guante","guapo","guardia","guerra","guía","guiño","guion","guiso","guitarra","gusano","gustar","haber","hábil","hablar","hacer","hacha","hada","hallar","hamaca","harina","haz","hazaña","hebilla","hebra","hecho","helado","helio","hembra","herir","hermano","héroe","hervir","hielo","hierro","hígado","higiene","hijo","himno","historia","hocico","hogar","hoguera","hoja","hombre","hongo","honor","honra","hora","hormiga","horno","hostil","hoyo","hueco","huelga","huerta","hueso","huevo","huida","huir","humano","húmedo","humilde","humo","hundir","huracán","hurto","icono","ideal","idioma","ídolo","iglesia","iglú","igual","ilegal","ilusión","imagen","imán","imitar","impar","imperio","imponer","impulso","incapaz","índice","inerte","infiel","informe","ingenio","inicio","inmenso","inmune","innato","insecto","instante","interés","íntimo","intuir","inútil","invierno","ira","iris","ironía","isla","islote","jabalí","jabón","jamón","jarabe","jardín","jarra","jaula","jazmín","jefe","jeringa","jinete","jornada","joroba","joven","joya","juerga","jueves","juez","jugador","jugo","juguete","juicio","junco","jungla","junio","juntar","júpiter","jurar","justo","juvenil","juzgar","kilo","koala","labio","lacio","lacra","lado","ladrón","lagarto","lágrima","laguna","laico","lamer","lámina","lámpara","lana","lancha","langosta","lanza","lápiz","largo","larva","lástima","lata","látex","latir","laurel","lavar","lazo","leal","lección","leche","lector","leer","legión","legumbre","lejano","lengua","lento","leña","león","leopardo","lesión","letal","letra","leve","leyenda","libertad","libro","licor","líder","lidiar","lienzo","liga","ligero","lima","límite","limón","limpio","lince","lindo","línea","lingote","lino","linterna","líquido","liso","lista","litera","litio","litro","llaga","llama","llanto","llave","llegar","llenar","llevar","llorar","llover","lluvia","lobo","loción","loco","locura","lógica","logro","lombriz","lomo","lonja","lote","lucha","lucir","lugar","lujo","luna","lunes","lupa","lustro","luto","luz","maceta","macho","madera","madre","maduro","maestro","mafia","magia","mago","maíz","maldad","maleta","malla","malo","mamá","mambo","mamut","manco","mando","manejar","manga","maniquí","manjar","mano","manso","manta","mañana","mapa","máquina","mar","marco","marea","marfil","margen","marido","mármol","marrón","martes","marzo","masa","máscara","masivo","matar","materia","matiz","matriz","máximo","mayor","mazorca","mecha","medalla","medio","médula","mejilla","mejor","melena","melón","memoria","menor","mensaje","mente","menú","mercado","merengue","mérito","mes","mesón","meta","meter","método","metro","mezcla","miedo","miel","miembro","miga","mil","milagro","militar","millón","mimo","mina","minero","mínimo","minuto","miope","mirar","misa","miseria","misil","mismo","mitad","mito","mochila","moción","moda","modelo","moho","mojar","molde","moler","molino","momento","momia","monarca","moneda","monja","monto","moño","morada","morder","moreno","morir","morro","morsa","mortal","mosca","mostrar","motivo","mover","móvil","mozo","mucho","mudar","mueble","muela","muerte","muestra","mugre","mujer","mula","muleta","multa","mundo","muñeca","mural","muro","músculo","museo","musgo","música","muslo","nácar","nación","nadar","naipe","naranja","nariz","narrar","nasal","natal","nativo","natural","náusea","naval","nave","navidad","necio","néctar","negar","negocio","negro","neón","nervio","neto","neutro","nevar","nevera","nicho","nido","niebla","nieto","niñez","niño","nítido","nivel","nobleza","noche","nómina","noria","norma","norte","nota","noticia","novato","novela","novio","nube","nuca","núcleo","nudillo","nudo","nuera","nueve","nuez","nulo","número","nutria","oasis","obeso","obispo","objeto","obra","obrero","observar","obtener","obvio","oca","ocaso","océano","ochenta","ocho","ocio","ocre","octavo","octubre","oculto","ocupar","ocurrir","odiar","odio","odisea","oeste","ofensa","oferta","oficio","ofrecer","ogro","oído","oír","ojo","ola","oleada","olfato","olivo","olla","olmo","olor","olvido","ombligo","onda","onza","opaco","opción","ópera","opinar","oponer","optar","óptica","opuesto","oración","orador","oral","órbita","orca","orden","oreja","órgano","orgía","orgullo","oriente","origen","orilla","oro","orquesta","oruga","osadía","oscuro","osezno","oso","ostra","otoño","otro","oveja","óvulo","óxido","oxígeno","oyente","ozono","pacto","padre","paella","página","pago","país","pájaro","palabra","palco","paleta","pálido","palma","paloma","palpar","pan","panal","pánico","pantera","pañuelo","papá","papel","papilla","paquete","parar","parcela","pared","parir","paro","párpado","parque","párrafo","parte","pasar","paseo","pasión","paso","pasta","pata","patio","patria","pausa","pauta","pavo","payaso","peatón","pecado","pecera","pecho","pedal","pedir","pegar","peine","pelar","peldaño","pelea","peligro","pellejo","pelo","peluca","pena","pensar","peñón","peón","peor","pepino","pequeño","pera","percha","perder","pereza","perfil","perico","perla","permiso","perro","persona","pesa","pesca","pésimo","pestaña","pétalo","petróleo","pez","pezuña","picar","pichón","pie","piedra","pierna","pieza","pijama","pilar","piloto","pimienta","pino","pintor","pinza","piña","piojo","pipa","pirata","pisar","piscina","piso","pista","pitón","pizca","placa","plan","plata","playa","plaza","pleito","pleno","plomo","pluma","plural","pobre","poco","poder","podio","poema","poesía","poeta","polen","policía","pollo","polvo","pomada","pomelo","pomo","pompa","poner","porción","portal","posada","poseer","posible","poste","potencia","potro","pozo","prado","precoz","pregunta","premio","prensa","preso","previo","primo","príncipe","prisión","privar","proa","probar","proceso","producto","proeza","profesor","programa","prole","promesa","pronto","propio","próximo","prueba","público","puchero","pudor","pueblo","puerta","puesto","pulga","pulir","pulmón","pulpo","pulso","puma","punto","puñal","puño","pupa","pupila","puré","quedar","queja","quemar","querer","queso","quieto","química","quince","quitar","rábano","rabia","rabo","ración","radical","raíz","rama","rampa","rancho","rango","rapaz","rápido","rapto","rasgo","raspa","rato","rayo","raza","razón","reacción","realidad","rebaño","rebote","recaer","receta","rechazo","recoger","recreo","recto","recurso","red","redondo","reducir","reflejo","reforma","refrán","refugio","regalo","regir","regla","regreso","rehén","reino","reír","reja","relato","relevo","relieve","relleno","reloj","remar","remedio","remo","rencor","rendir","renta","reparto","repetir","reposo","reptil","res","rescate","resina","respeto","resto","resumen","retiro","retorno","retrato","reunir","revés","revista","rey","rezar","rico","riego","rienda","riesgo","rifa","rígido","rigor","rincón","riñón","río","riqueza","risa","ritmo","rito","rizo","roble","roce","rociar","rodar","rodeo","rodilla","roer","rojizo","rojo","romero","romper","ron","ronco","ronda","ropa","ropero","rosa","rosca","rostro","rotar","rubí","rubor","rudo","rueda","rugir","ruido","ruina","ruleta","rulo","rumbo","rumor","ruptura","ruta","rutina","sábado","saber","sabio","sable","sacar","sagaz","sagrado","sala","saldo","salero","salir","salmón","salón","salsa","salto","salud","salvar","samba","sanción","sandía","sanear","sangre","sanidad","sano","santo","sapo","saque","sardina","sartén","sastre","satán","sauna","saxofón","sección","seco","secreto","secta","sed","seguir","seis","sello","selva","semana","semilla","senda","sensor","señal","señor","separar","sepia","sequía","ser","serie","sermón","servir","sesenta","sesión","seta","setenta","severo","sexo","sexto","sidra","siesta","siete","siglo","signo","sílaba","silbar","silencio","silla","símbolo","simio","sirena","sistema","sitio","situar","sobre","socio","sodio","sol","solapa","soldado","soledad","sólido","soltar","solución","sombra","sondeo","sonido","sonoro","sonrisa","sopa","soplar","soporte","sordo","sorpresa","sorteo","sostén","sótano","suave","subir","suceso","sudor","suegra","suelo","sueño","suerte","sufrir","sujeto","sultán","sumar","superar","suplir","suponer","supremo","sur","surco","sureño","surgir","susto","sutil","tabaco","tabique","tabla","tabú","taco","tacto","tajo","talar","talco","talento","talla","talón","tamaño","tambor","tango","tanque","tapa","tapete","tapia","tapón","taquilla","tarde","tarea","tarifa","tarjeta","tarot","tarro","tarta","tatuaje","tauro","taza","tazón","teatro","techo","tecla","técnica","tejado","tejer","tejido","tela","teléfono","tema","temor","templo","tenaz","tender","tener","tenis","tenso","teoría","terapia","terco","término","ternura","terror","tesis","tesoro","testigo","tetera","texto","tez","tibio","tiburón","tiempo","tienda","tierra","tieso","tigre","tijera","tilde","timbre","tímido","timo","tinta","tío","típico","tipo","tira","tirón","titán","títere","título","tiza","toalla","tobillo","tocar","tocino","todo","toga","toldo","tomar","tono","tonto","topar","tope","toque","tórax","torero","tormenta","torneo","toro","torpedo","torre","torso","tortuga","tos","tosco","toser","tóxico","trabajo","tractor","traer","tráfico","trago","traje","tramo","trance","trato","trauma","trazar","trébol","tregua","treinta","tren","trepar","tres","tribu","trigo","tripa","triste","triunfo","trofeo","trompa","tronco","tropa","trote","trozo","truco","trueno","trufa","tubería","tubo","tuerto","tumba","tumor","túnel","túnica","turbina","turismo","turno","tutor","ubicar","úlcera","umbral","unidad","unir","universo","uno","untar","uña","urbano","urbe","urgente","urna","usar","usuario","útil","utopía","uva","vaca","vacío","vacuna","vagar","vago","vaina","vajilla","vale","válido","valle","valor","válvula","vampiro","vara","variar","varón","vaso","vecino","vector","vehículo","veinte","vejez","vela","velero","veloz","vena","vencer","venda","veneno","vengar","venir","venta","venus","ver","verano","verbo","verde","vereda","verja","verso","verter","vía","viaje","vibrar","vicio","víctima","vida","vídeo","vidrio","viejo","viernes","vigor","vil","villa","vinagre","vino","viñedo","violín","viral","virgo","virtud","visor","víspera","vista","vitamina","viudo","vivaz","vivero","vivir","vivo","volcán","volumen","volver","voraz","votar","voto","voz","vuelo","vulgar","yacer","yate","yegua","yema","yerno","yeso","yodo","yoga","yogur","zafiro","zanja","zapato","zarza","zona","zorro","zumo","zurdo"]["abajur","abaküs","abartı","abdal","abdest","abiye","abluka","abone","absorbe","absürt","acayip","acele","acemi","açıkgöz","adalet","adam","adezyon","adisyon","adliye","adres","afacan","afili","afiş","afiyet","aforizm","afra","ağaç","ağır","ahbap","ahkam","ahlak","ahtapot","aidat","aile","ajan","akademi","akarsu","akbaş","akciğer","akdeniz","akıbet","akıl","akıntı","akide","akrep","akrobasi","aksiyon","akşam","aktif","aktör","aktris","akustik","alaca","albüm","alçak","aldanma","aleni","alet","alfabe","algılama","alıngan","alkış","alkol","alpay","alperen","altın","altüst","altyapı","alyuvar","amade","amatör","amazon","ambalaj","amblem","ambulans","amca","amel","amigo","amir","amiyane","amorti","ampul","anadolu","anahtar","anakonda","anaokul","anapara","anarşi","anatomi","anayasa","anekdot","anestezi","angaje","anka","anket","anlamlı","anne","anomali","anonim","anten","antlaşma","apse","araba","aracı","araf","arbede","arda","arefe","arena","argo","argüman","arkadaş","armoni","aroma","arsa","arsız","artı","artist","aruz","asansör","asayiş","asfalt","asgari","asil","asker","askı","aslan","asosyal","astsubay","asya","aşçı","aşırı","aşure","atabey","ataman","ateş","atmaca","atmosfer","atom","atölye","avcı","avdet","avize","avlu","avokado","avrupa","avukat","ayaz","ayçiçeği","aydın","aygıt","ayna","ayran","ayrıntı","azim","baca","bagaj","bağlantı","bahadır","bahçe","baki","bakkal","baklava","bakteri","balçık","balina","balo","balta","bant","banyo","bardak","barış","başbuğ","başıboş","başkan","başlık","bavul","bayındır","baykuş","bazlama","bedel","begüm","bekçi","bekle","belge","belki","bencil","benek","bengi","benzer","berjer","berk","bermuda","berrak","beşik","beton","beyin","beyoğlu","bıçak","biberiye","bidon","biftek","bihaber","bikini","bilezik","bilinç","bilye","bina","binbaşı","binyıl","bisiklet","bisküvi","bitki","bizzat","bodrum","boğaz","bohça","bolero","boncuk","bonfile","borsa","boru","bostan","boşboğaz","botanik","boya","boykot","boynuz","bozgun","bozkır","bölüm","börek","buçuk","bugün","buğday","buhar","buhran","bulvar","buram","burçak","burs","burun","butik","buzdağı","buzkıran","bücür","büfe","bülten","bütçe","bütün","büyük","cacık","cadı","cahil","cambaz","canhıraş","casus","cazibe","cehalet","cehennem","ceket","cemre","cenin","cennet","cepken","cerrah","cesur","cetvel","cevher","ceylan","cılız","cıva","cilt","cisim","ciyak","coğrafya","cömert","cumba","cüzdan","çabucak","çadır","çağdaş","çağlayan","çağrı","çakmak","çalışkan","çamaşır","çapa","çaput","çarık","çarpan","çarşaf","çayhane","çekirdek","çelebi","çember","çenet","çengel","çerçeve","çerez","çeşit","çeşme","çete","çevre","çeyiz","çeyrek","çığır","çılgın","çıngırak","çift","çiğdem","çikolata","çilek","çimen","çivi","çoban","çocuk","çokgen","çomak","çorba","çözelti","çubuk","çukur","çuval","çürük","dağbaşı","dağılım","daktilo","daldırış","dalga","dalkavuk","damak","damıtma","damla","dana","dandik","danışman","daniska","dantel","dargeçit","darphane","davet","dayı","defter","değer","değirmen","dehşet","delgeç","demir","deneyim","denge","depo","deprem","derdest","dere","derhal","derman","dernek","derviş","desen","destan","dışarı","dışbükey","dijital","dikbaşlı","dilekçe","dimağ","dinamik","dindar","dinleme","dinozor","dipçik","dipnot","direniş","dirsek","disiplin","disk","divriği","dizüstü","dobra","dodurga","doğalgaz","doktor","doküman","dolap","donanım","dondurma","donör","doruk","dosdoğru","dost","dosya","dozer","döküm","dönence","dörtyol","dövme","dram","dublaj","durum","duvak","duyarga","duyma","duyuru","düğme","düğüm","dükkan","dünür","düpedüz","dürbün","düşünür","düzayak","düzeltme","ebeveyn","ebru","ecel","ecnebi","ecza","edat","edilgen","efendi","efor","efsane","egemen","egzersiz","eğrelti","ekarte","ekip","eklem","ekmek","ekol","ekonomi","ekose","ekran","ekvator","elaman","elastik","elbet","elbise","elçi","eldiven","elebaşı","eleştiri","elma","eloğlu","elveda","emare","emekçi","emisyon","emniyet","empati","emsal","emzik","endüstri","enerji","engebe","engin","enişte","enkaz","entari","entegre","entrika","enzim","erdem","ergen","erguvan","erkek","erozyon","ertesi","erzak","esaret","esenlik","eser","eski","esnek","eşarp","eşofman","eşraf","eşya","eşzaman","etik","etken","etkinlik","etüt","evet","evire","evrak","evrim","eyalet","eyvah","ezber","fabrika","fanatik","fanus","fason","fasulye","fatih","fatura","fauna","favori","fayans","fayton","fazıl","fazilet","federal","felsefe","fener","feribot","fersah","fesih","festival","feveran","feza","fıçı","fıldır","fındık","fırça","fırsat","fırtına","fıtık","fidan","fidye","figür","fihrist","fikir","fildişi","filo","filtre","fincan","firuze","fitil","fiyaka","fizik","flaş","flüt","fosil","fren","fukara","futbol","garabet","gariban","garnitür","gazi","gece","gedik","gelenek","gelin","gemi","genç","geniş","geometri","gerçek","gevrek","gezegen","gezgin","geziyolu","gıcık","gıda","gıybet","girdap","girişim","gitar","giyecek","giysi","gizem","gofret","goril","göbek","göçebe","göğüs","gökdelen","gökmen","gökyüzü","gölge","gömlek","gönül","görenek","görkemli","görsel","gösteri","gövde","gözaltı","gözcü","gözdağı","gözleme","gözyaşı","grup","gurbet","gusül","gübre","güfte","gümüş","günaydın","güncel","gündüz","güneş","günyüzü","gürbüz","güvercin","güzel","haber","hacamat","hacim","hademe","hafız","hafriyat","hafta","hakan","hakem","hakikat","haksever","halı","hançer","hane","hangar","hapis","hapşırık","harf","haseki","hasret","hatun","havuç","haylaz","haysiyet","hayvan","hedef","hektar","hemen","hemfikir","hendek","hepsi","hergele","herhangi","hesap","heyecan","heykel","hezimet","hıçkırık","hızölçer","hicviye","hikaye","hikmet","hile","hisse","hobi","hoca","horlama","hormon","hoşbeş","hoşgörü","hoyrat","hörgüç","höyük","hudut","hukuk","hunhar","hurda","huysuz","huzur","hücum","hükümet","hünkar","hüviyet","ırmak","ısıölçer","ısıtıcı","ıspanak","ısrar","ışıldak","ızdırap","ızgara","ibadet","icat","içbükey","içecek","içgüdü","içsel","idman","iftihar","iğne","ihanet","ihbar","ihdas","ihmal","ihracat","ihsan","ikilem","ikindi","ikircik","iklim","iksir","iktibas","ilaç","ilçe","ileri","iletişim","ilgi","ilhak","ilkbahar","ilkokul","ilmek","imkan","imleç","imsak","imtihan","imza","ince","inkar","inşa","ipek","ipucu","irade","irfan","irmik","isabet","iskele","israf","isyan","işçi","işgal","işgüzar","işlem","itibar","itiraf","ivedi","ivme","iyileşme","iyimser","izbandut","izci","izdiham","izin","jakoben","jandarma","jargon","kabadayı","kablo","kabus","kaçamak","kadeh","kadın","kadraj","kafa","kafkas","kağıt","kağnı","kahkaha","kahraman","kahvaltı","kakül","kaldırım","kale","kalibre","kalkan","kalpak","kamış","kamyon","kanat","kandaş","kanepe","kanser","kanun","kaos","kapı","kaplıca","kaptan","karanlık","kardeş","karga","karınca","karmaşa","karşıt","kasırga","kask","kasvet","katkı","katman","kavram","kaygan","kaynakça","kayyum","kedi","kehanet","kekik","kelebek","kenar","kerkenez","kerpiç","kesirli","kesmece","kestane","keşkek","ketçap","keyfiyet","kıble","kıdemli","kılavuz","kılçık","kılıf","kıraç","kırmızı","kırsal","kısayol","kısım","kıskanç","kısmet","kışla","kıvanç","kıvılcım","kıvrık","kıyafet","kıymetli","kızak","kızılcık","kibar","kinaye","kira","kiremit","kirli","kirpik","kişisel","kitap","koçbaşı","kodaman","koğuş","kokteyl","kolaycı","kolbastı","kolonya","koltuk","kolye","kombine","komedyen","komiser","komposto","komşu","komuta","konak","konfor","koni","konsül","kopya","korkusuz","korna","korse","korunak","korvet","kostüm","koşul","koyu","kozmik","köfte","kökensel","köprücük","köpük","kördüğüm","körfez","köstebek","köşegen","kötü","kravat","kriter","kuantum","kudurma","kuluçka","kulübe","kumanya","kumbara","kumlu","kumpir","kumral","kundura","kupa","kupkuru","kuramsal","kurbağa","kurdele","kurgu","kurmay","kurşun","kurtuluş","kurultay","kurye","kusursuz","kuşak","kuşbaşı","kuşkulu","kutlama","kutsal","kutup","kuver","kuyruk","kuzey","kuzgun","küçük","külçe","külfet","külliye","kültürel","kümes","künefe","küresel","kütle","lahana","lahmacun","lamba","lansman","lavaş","layık","leğen","levent","leziz","lezzet","lider","likide","liman","liste","litre","liyakat","lodos","lokanta","lokman","lokum","lunapark","lütfen","lüzum","nokta","mabet","macera","macun","madalya","madde","madem","mağara","mağdur","mağfiret","mağlup","mahalle","mahcup","mahir","mahkeme","mahlas","mahrum","mahsul","makas","makbuz","makine","makro","maksat","makul","maliye","manav","mangal","manidar","manken","mantık","manzara","mareşal","margarin","marifet","market","marmelat","masaüstü","masmavi","masraf","masum","matah","materyal","matrak","maval","mavra","maydanoz","mayhoş","maytap","mazbata","mazeret","mazlum","mazot","mazur","meblağ","mebus","mecaz","mecbur","meclis","mecmua","mecnun","meçhul","medeni","mehtap","mekanik","melodi","meltem","memur","mendil","menekşe","menteşe","meraklı","mercek","merdiven","merhaba","merinos","merkez","mermi","mert","mesafe","mesele","mesken","meslek","meşale","meşgul","meşhur","metafor","metin","metre","mevcut","mevkidaş","meydan","meyil","meyve","meziyet","mezun","mıknatıs","mısra","mızıka","miğfer","mihrak","mikrofon","miktar","milat","milli","mimar","minare","mineral","minik","minyon","mirliva","misafir","miskin","miting","miyop","mizah","mobilya","model","monitör","morötesi","motive","motor","mozaik","muavin","mucize","muhafız","muhteşem","mukayese","mumya","musluk","muşamba","mutabık","mutfak","mutlu","muzaffer","muzdarip","mübarek","mücadele","müdür","müfredat","müftü","mühendis","mühim","mühlet","mükemmel","mülk","mümkün","mümtaz","müsrif","müstesna","müşahit","müşteri","mütercim","müthiş","müze","müzik","nabız","nadas","nadir","nahoş","nakarat","nakış","nalbur","namlu","namus","nankör","nargile","narkoz","nasıl","nasip","naylon","nazar","nazım","nazik","neden","nefes","negatif","neon","neptün","nerede","nesil","nesnel","neşeli","netice","nevresim","neyse","neyzen","nezaket","nezih","nezle","nicel","nilüfer","nimet","nisan","nispet","nitekim","nizam","nohut","noksan","normal","nostalji","noter","nöbet","numara","numune","nutuk","nüfus","obabaşı","obez","obje","ocak","odun","ofansif","ofis","oğlak","oğuz","okçu","oklava","oksijen","okul","okumuş","okutman","okuyucu","okyanus","olağan","olanak","olası","olay","olgun","olimpik","olumlu","omlet","omurga","onarım","onursal","opera","optik","oral","orantı","ordu","organik","orijin","orkide","orman","orta","oruç","otağ","otantik","otel","otoban","otogar","otomobil","otonom","otopark","otorite","otoyol","oturum","oyuk","oyuncak","ozan","ödeme","ödenek","ödev","ödül","ödünç","öfke","öğlen","öğrenci","öğün","öğütücü","öksürük","ölçme","ölçü","ölümsüz","ömür","önayak","öncü","önder","önem","önerge","öngörü","önlük","önsezi","öpücük","ördek","örgü","örtbas","örtme","örtü","örümcek","örüntü","öteberi","öteki","övünç","öykü","öyleyse","özçekim","özdeyiş","özel","özenti","özerk","özgürlük","özlem","özlü","özne","özsever","özümseme","özür","özveri","pabuç","padişah","palamut","palmiye","palto","palyaço","pamuk","panayır","pancar","panda","panel","panik","panjur","pankart","pano","pansuman","pantolon","panzehir","papatya","papyon","paraşüt","parça","pardösü","parfüm","parıltı","parkur","parmak","parodi","parsel","partner","pasaport","pasif","paskalya","pastırma","paşa","patates","paten","patika","patlıcan","patolog","patron","payanda","paydaş","payidar","paylaşma","paytak","peçete","pedal","peder","pehlivan","pekala","pekmez","pelerin","pelikan","pelüş","pembe","pena","pencere","pense","perçin","perde","pergel","perişan","peron","personel","perşembe","peruk","pervane","pespaye","pestil","peşin","petek","petrol","petunya","peynir","peyzaj","pınar","pırasa","pırlanta","pide","pikap","piknik","pilav","piliç","pilot","pipet","pipo","piramit","pirinç","pirzola","pist","pişik","pişman","piyasa","piyes","plaj","plaket","planlama","platform","plazma","podyum","poğaça","polat","polen","politika","pompa","popüler","porselen","portakal","posa","poster","poşet","poyraz","pozitif","pranga","pratik","prenses","prim","problem","profil","program","proje","protokol","prova","puan","pudra","pusula","püre","pürüz","püstül","püsür","racon","radar","radikal","radyo","rafadan","rafine","rağbet","rahat","rahle","rakam","raket","rakip","rakun","ralli","rampa","randevu","ranza","rapor","rastgele","rasyonel","razı","realite","reçine","refah","referans","refik","reform","rehber","rehin","reis","rekabet","reklam","rekor","rektör","renk","resim","resmen","restoran","retorik","revaç","revize","reyon","rezalet","rezerv","rezil","rıhtım","rıza","ritim","ritüel","rivayet","robot","roman","rota","rozet","röportaj","rötar","ruble","ruhban","ruhsat","rulet","rulo","runik","rutin","rutubet","rüşvet","rütbe","rüya","rüzgar","sabah","sabıka","sabit","sabun","saçma","sade","sadık","safahat","safdil","safkan","sağanak","sağduyu","sağlam","saha","sahiden","sahne","sakal","sakız","sakin","saklama","saksağan","salamura","salça","salgı","salınım","salkım","salon","saltanat","sanatçı","sancak","sandalye","saniye","saplantı","sapsız","saray","sarışın","sarkık","sarmaşık","satır","savaşım","savunma","saydam","sayfa","saygın","sayısal","sebep","seçenek","seçim","seçkin","seçmen","seda","sedir","sedye","sefer","sehpa","sekizgen","selektör","selvi","semavi","sembol","seminer","senaryo","sendika","senkron","sensör","sentez","sepet","seramik","serbest","serdar","seremoni","sergi","serhat","serin","sermaye","serpuş","sersem","serüven","servis","sesli","sesteş","sevap","seviye","seyahat","seyirci","sezon","sıcak","sıfat","sıhhi","sınanma","sınır","sıradan","sırdaş","sırma","sırtüstü","sızgıt","siftah","sigorta","sihirbaz","silah","silecek","silindir","simetri","simge","simit","sincap","sindirim","sinema","sinirli","sipariş","sirke","siroz","sistem","sivilce","siyasi","slogan","soba","sofra","soğuk","sohbet","sokak","solfej","solunum","somut","sonbahar","sonraki","sonsuz","sorunsuz","sosyete","soyağacı","soydaş","soygun","soytarı","söğüş","sömürge","sönük","söylem","sözcük","sözde","spatula","spektrum","spiker","spiral","sponsor","sporcu","sprey","stabil","statü","stok","stopaj","strateji","subay","sucuk","suçüstü","suhulet","sulama","sungur","sunucu","surat","susam","suskun","sükse","sükut","sülale","sünger","süpürge","sürahi","süreç","sürgün","sürüm","süsleme","sütanne","sütlaç","sütun","süvari","şahane","şahbaz","şahit","şahsiyet","şakıma","şaklaban","şakrak","şamar","şampiyon","şanslı","şantiye","şapka","şarkıcı","şartname","şaşırma","şaşkın","şatafat","şayet","şebeke","şefkat","şeftali","şehir","şehvet","şeker","şekil","şelale","şema","şemsiye","şerbet","şeref","şerit","şımarık","şıpıdık","şifre","şimdi","şimşek","şipşak","şirin","şişe","şişirme","şofben","şöhret","şölen","şüphe","tabaka","tabela","tabure","tadilat","taharet","tahıl","tahkim","tahlil","tahmin","tahrifat","tahsilat","tahta","taklit","takoz","taksici","taktik","takvim","talebe","talip","tamamen","tamirci","tampon","tamtakır","tandır","tanecik","tanıtım","tanrı","tansiyon","tapan","tapınak","taptaze","tapu","tarafgir","tarhana","tarım","tarih","tarla","tartak","tarumar","tasarım","tasdik","taslak","tastamam","taşeron","taşınmaz","taşra","tatava","tatbikat","tatil","tatlı","tavsiye","tavşan","tavuk","taze","taziye","tazminat","tebeşir","tebrik","tecrübe","teçhizat","tedarik","tedbir","teftiş","teğet","teğmen","tehdit","tehlike","tekdüze","tekerlek","tekme","teknik","tekrar","telef","telsiz","telve","temas","tembel","temiz","temkin","tempo","temsilci","tendon","teneke","tenha","tenkit","tepegöz","tepki","terazi","terbiye","tercih","tereyağı","terfi","terim","terminal","tersane","tertip","tesadüf","tescil","tesir","teslimat","tespit","testere","teşekkür","teşhir","teşrif","teşvik","teyze","tezahür","tezgah","tıbbi","tıkaç","tıkışık","tıknaz","tılsım","tıpkı","tıraş","tırışka","tırmanış","tırnak","tırpan","tıslama","ticaret","tilki","tiryaki","titreşim","tohum","tokat","tolere","tomar","tombak","tomurcuk","topaç","toplum","toprak","toptan","toraman","torpido","tortu","tosbağa","toynak","tören","trafik","trajedi","tramvay","transfer","tribün","triko","tugay","tuğla","tuğrul","tuhaf","tulumba","tunç","turan","turkuaz","turnusol","turşu","turuncu","tutanak","tutkal","tutsak","tutum","tuyuğ","tuzlu","tüccar","tüfek","tükenmez","tülbent","tümleç","tünel","türbin","türev","türk","tüzük","ucube","ucuz","uçak","uçurtma","ufuk","uğrak","uğur","ukala","ulaşım","ulema","ulus","ulvi","umursama","umut","unutkan","uslu","ustabaşı","ustura","usul","utangaç","uyanık","uyarı","uydu","uygar","uygulama","uykusuz","uysal","uyuşma","uzantı","uzay","uzgören","uzlaşma","uzman","uzun","ücra","ücret","üçbudak","üçgen","üçkağıt","üçleme","üfürük","ülke","ümit","üniforma","ünite","ünlem","üretken","ürün","üslup","üstel","üstün","üşengeç","üşüme","ütopya","üvey","üzengi","üzgün","üzüm","vagon","vaka","vakfiye","vakıf","vakit","vakum","vapur","varil","varlık","varsayım","varyemez","vasıta","vasiyet","vatandaş","vazife","vazo","veciz","vefa","vehim","veliaht","veresiye","verimli","verkaç","vernik","vertigo","vesait","vesika","vestiyer","veznedar","vicdan","vilayet","virane","virgül","vişne","vites","vokal","volkan","vurma","vurucu","vücut","yabancı","yabgu","yağış","yağlı","yağmur","yakamoz","yakın","yaklaşık","yalçın","yalıtım","yaman","yanardağ","yangın","yanıt","yankı","yanlış","yansıma","yapay","yapboz","yapımcı","yaprak","yaratık","yarbay","yardım","yargıç","yarıçap","yasemin","yastık","yaşam","yatak","yatırım","yavru","yaygara","yayıncı","yayla","yazılım","yekpare","yekvücut","yelkovan","yelpaze","yemek","yemiş","yengeç","yeniçeri","yeraltı","yerküre","yerleşke","yeryüzü","yeşil","yetenek","yetkili","yığınak","yıkama","yılbaşı","yıldırım","yılkı","yılmaz","yırtıcı","yiğit","yoğurt","yokuş","yolcu","yoldaş","yolgeçen","yolkesen","yolüstü","yordam","yorgan","yorumcu","yosun","yöndeş","yönetim","yönlü","yöntem","yöresel","yörünge","yufka","yukarı","yumruk","yumurta","yuvarlak","yücelme","yükçeker","yüklem","yüksek","yürek","yürütme","yüzde","yüzeysel","yüzgeç","yüzüstü","yüzyıl","zabıta","zafer","zahmet","zambak","zaptiye","zarafet","zaruret","zeka","zekice","zemberek","zemin","zencefil","zeplin","zeytin","zıbın","zılgıt","zımbırtı","zımpara","zıpkın","zigon","zihinsel","zihniyet","zincir","zindan","zirzop","ziyaret","ziynet","zoraki","zorlu","zorunlu","züğürt","zümre"]module.exports = require('bare-events')
{
  "name": "events-universal",
  "version": "1.0.1",
  "description": "Universal wrapper for the Node.js events module",
  "exports": {
    "./package": "./package.json",
    ".": {
      "bare": "./bare.js",
      "react-native": "./react-native.js",
      "default": "./default.js"
    }
  },
  "files": [
    "index.js",
    "default.js",
    "bare.js",
    "react-native.js"
  ],
  "scripts": {
    "test": "prettier . --check"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/events-universal.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/events-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/events-universal#readme",
  "dependencies": {
    "bare-events": "^2.7.0"
  },
  "devDependencies": {
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^1.0.0"
  }
}
module.exports = class FixedFIFO {
  constructor (hwm) {
    if (!(hwm > 0) || ((hwm - 1) & hwm) !== 0) throw new Error('Max size for a FixedFIFO should be a power of two')
    this.buffer = new Array(hwm)
    this.mask = hwm - 1
    this.top = 0
    this.btm = 0
    this.next = null
  }

  clear () {
    this.top = this.btm = 0
    this.next = null
    this.buffer.fill(undefined)
  }

  push (data) {
    if (this.buffer[this.top] !== undefined) return false
    this.buffer[this.top] = data
    this.top = (this.top + 1) & this.mask
    return true
  }

  shift () {
    const last = this.buffer[this.btm]
    if (last === undefined) return undefined
    this.buffer[this.btm] = undefined
    this.btm = (this.btm + 1) & this.mask
    return last
  }

  peek () {
    return this.buffer[this.btm]
  }

  isEmpty () {
    return this.buffer[this.btm] === undefined
  }
}
const FixedFIFO = require('./fixed-size')

module.exports = class FastFIFO {
  constructor (hwm) {
    this.hwm = hwm || 16
    this.head = new FixedFIFO(this.hwm)
    this.tail = this.head
    this.length = 0
  }

  clear () {
    this.head = this.tail
    this.head.clear()
    this.length = 0
  }

  push (val) {
    this.length++
    if (!this.head.push(val)) {
      const prev = this.head
      this.head = prev.next = new FixedFIFO(2 * this.head.buffer.length)
      this.head.push(val)
    }
  }

  shift () {
    if (this.length !== 0) this.length--
    const val = this.tail.shift()
    if (val === undefined && this.tail.next) {
      const next = this.tail.next
      this.tail.next = null
      this.tail = next
      return this.tail.shift()
    }

    return val
  }

  peek () {
    const val = this.tail.peek()
    if (val === undefined && this.tail.next) return this.tail.next.peek()
    return val
  }

  isEmpty () {
    return this.length === 0
  }
}
{
  "name": "fast-fifo",
  "version": "1.3.2",
  "description": "A fast fifo implementation similar to the one powering nextTick in Node.js core",
  "main": "index.js",
  "files": [
    "./index.js",
    "./fixed-size.js"
  ],
  "dependencies": {},
  "devDependencies": {
    "standard": "^17.1.0",
    "brittle": "^3.3.2"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/fast-fifo.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/fast-fifo/issues"
  },
  "homepage": "https://github.com/mafintosh/fast-fifo"
}
const c = require('compact-encoding')
const b4a = require('b4a')

const KeyChain = require('./lib/keychain')
const { sign, verify, hash } = require('./lib/crypto')

const {
  ProofEncoding,
  AttestedData,
  AttestedDevice,
  ReceiptEncoding
} = require('./lib/encoding')

const PROOF_VERSION = 1
const KEET_TYPE = 5338

const NS_PROFILE_DISC_ENC = hash(b4a.from('profile discovery'))

module.exports = class IdentityKey {
  constructor (keyChain) {
    this.keyChain = keyChain

    this.identityKeyPair = this.keyChain.get(identityKeyPath(0))
    this.profileDiscoveryKeyPair = this.keyChain.get(discoveryCorePath(0))
  }

  static generateMnemonic () {
    return KeyChain.generateMnemonic()
  }

  static deriveSeed (mnemonic) {
    return KeyChain.deriveSeed(mnemonic)
  }

  get identityPublicKey () {
    return this.identityKeyPair.publicKey
  }

  get profileDiscoveryPublicKey () {
    return this.profileDiscoveryKeyPair.publicKey
  }

  getProfileDiscoveryEncryptionKey () {
    return this.keyChain.getSymmetricKey(encryptionKeyPath(NS_PROFILE_DISC_ENC))
  }

  getEncryptionKey (profileKey) {
    return this.keyChain.getSymmetricKey(encryptionKeyPath(profileKey))
  }

  bootstrap (device) {
    return IdentityKey.bootstrap({ identity: this.identityKeyPair }, device)
  }

  clear () {
    this.keyChain.clear()
    this.identityKeyPair.secretKey.fill(0)
    this.profileDiscoveryKeyPair.secretKey.fill(0)
  }

  static async bootstrap ({ identity, seed, mnemonic }, device) {
    if (!identity) {
      const identityPath = identityKeyPath(0) // accountIndex unused for now
      identity = await KeyChain.from({ seed, mnemonic }, identityPath)
    }

    const proof = {
      version: PROOF_VERSION,
      epoch: Date.now(),
      identity: identity.publicKey,
      chain: []
    }

    return IdentityKey.attestDevice(device, identity, proof)
  }

  static attestDevice (publicKey, parent, proof) {
    if (!proof) return IdentityKey.bootstrap({ identity: parent }, publicKey)

    if (b4a.isBuffer(proof)) {
      proof = c.decode(ProofEncoding, proof)
    }

    if (proof.version === 0) {
      throw new Error('Version 0 proofs are not supported')
    }

    const signable = c.encode(AttestedDevice, {
      epoch: proof.epoch,
      identity: proof.identity,
      device: publicKey
    })

    const signature = sign(signable, parent)

    proof.chain.push({ publicKey, signature })

    return c.encode(ProofEncoding, proof)
  }

  static attestData (attestedData, keyPair, proof) {
    if (attestedData === null) throw new Error('Data is not attestable')

    if (b4a.isBuffer(proof)) {
      proof = c.decode(ProofEncoding, proof)
    }

    if (proof && proof.version === 0) {
      throw new Error('Version 0 proofs are not supported')
    }

    if (!proof) {
      proof = {
        version: PROOF_VERSION,
        epoch: Date.now(),
        identity: keyPair.publicKey,
        chain: []
      }
    }

    const signable = c.encode(AttestedData, {
      epoch: proof.epoch,
      identity: proof.identity,
      data: hash(attestedData)
    })

    proof.data = { signature: sign(signable, keyPair) }

    return c.encode(ProofEncoding, proof)
  }

  static async from ({ seed, mnemonic }) {
    const keyChain = await KeyChain.from({ seed, mnemonic })

    return new IdentityKey(keyChain)
  }

  static verify (proof, attestedData, opts = {}) {
    if (b4a.isBuffer(proof)) {
      proof = c.decode(ProofEncoding, proof)
    }

    if (!validateProof(proof, attestedData, opts)) {
      return null
    }

    const { epoch, identity, chain } = proof

    const candidate = getLastKey(chain) || identity

    if (opts.expectedDevice) {
      if (!b4a.equals(candidate, opts.expectedDevice)) return null
    }

    let parent = identity

    // verify chain
    for (let i = 0; i < chain.length; i++) {
      const { publicKey, signature } = chain[i]

      const signable = c.encode(AttestedDevice, {
        epoch,
        identity,
        device: publicKey
      })

      if (!verify(signable, signature, parent)) {
        return null
      }

      parent = publicKey
    }

    if (proof.data) {
      const signable = c.encode(AttestedData, {
        epoch,
        identity,
        data: hash(attestedData)
      })

      if (!verify(signable, proof.data.signature, parent)) {
        return null
      }
    }

    const receipt = c.encode(ReceiptEncoding, { epoch })

    return {
      receipt,
      identityPublicKey: identity,
      devicePublicKey: candidate
    }
  }
}

function validateProof (proof, attestedData, opts = {}) {
  // version 0 is ignored
  if (proof.version === 0) return false

  // validate version
  if (proof.version > PROOF_VERSION) return false

  // verify epoch
  if (opts.receipt) {
    const { epoch } = c.decode(ReceiptEncoding, opts.receipt)
    if (proof.epoch < epoch) return false
  }

  // verify identity
  if (opts.expectedIdentity) {
    if (!b4a.equals(proof.identity, opts.expectedIdentity)) return false
  }

  return validateAttestedData(proof.data, attestedData)
}

function validateAttestedData (data, attestedData) {
  if (!data && attestedData) return false
  return true
}

function getLastKey (chain) {
  if (!chain.length) return null

  const last = chain[chain.length - 1]
  return last.publicKey
}

// slip48 derivations:
// https://github.com/satoshilabs/slips/blob/master/slip-0048.md

function keyPath (accountIndex, index) {
  // https://github.com/bitcoin/bips/blob/master/bip-0043.mediawiki
  const purpose = 48 // SLIP-48 wallet
  const role = 0 // owner

  return [purpose, KEET_TYPE, role, accountIndex, index]
}

// identityKey -> m/48'/keet'/0'/0'

function identityKeyPath (accountIndex) {
  return keyPath(accountIndex, 0)
}

// identityKey -> m/48'/keet'/0'/1'

function discoveryCorePath (accountIndex) {
  return keyPath(accountIndex, 1)
}

// slip21 derivations
// https://github.com/satoshilabs/slips/blob/master/slip-0021.md

function symmetricPath (...path) {
  const purpose = 'SLIP-0021' // SLIP-21 wallet
  const namespace = 'keet-identity-key' // keet

  return [purpose, namespace, ...path]
}

// encryptionKey  -> m/SLIP-10/keet-identity-key/account/"encryption key"

function encryptionKeyPath (profileKey) {
  return symmetricPath(b4a.toString(profileKey, 'hex'), 'encryption key')
}
const sodium = require('sodium-universal')
const b4a = require('b4a')

module.exports = {
  sign,
  verify,
  hash: blake2b
}

function sign (signable, keyPair) {
  const signature = b4a.alloc(sodium.crypto_sign_BYTES)
  sodium.crypto_sign_detached(signature, signable, keyPair.secretKey)

  return signature
}

function verify (signable, signature, publicKey) {
  return sodium.crypto_sign_verify_detached(signature, signable, publicKey)
}

function blake2b (data, output = b4a.alloc(32)) {
  sodium.crypto_generichash(output, data)
  return output
}
const c = require('compact-encoding')

const ATTESTED_DEVICE = 0
const ATTESTED_DATA = 1

const Epoch = {
  preencode (state, e) {
    c.uint64.preencode(state, Math.floor(e / 1000))
  },
  encode (state, e) {
    c.uint64.encode(state, Math.floor(e / 1000))
  },
  decode (state) {
    return c.uint64.decode(state) * 1000
  }
}

const AttestedDevice = {
  preencode (state, a) {
    c.uint8.preencode(state, ATTESTED_DEVICE)
    Epoch.preencode(state, a.epoch)
    c.fixed32.preencode(state, a.identity)
    c.fixed32.preencode(state, a.device)
  },
  encode (state, a) {
    c.uint8.encode(state, ATTESTED_DEVICE)
    Epoch.encode(state, a.epoch)
    c.fixed32.encode(state, a.identity)
    c.fixed32.encode(state, a.device)
  },
  decode (state) {
    throw new Error('Signed data should only be encoded')
  }
}

const AttestedData = {
  preencode (state, a) {
    c.uint8.preencode(state, ATTESTED_DATA)
    Epoch.preencode(state, a.epoch)
    c.fixed32.preencode(state, a.identity)
    c.fixed32.preencode(state, a.data)
  },
  encode (state, a) {
    c.uint8.encode(state, ATTESTED_DATA)
    Epoch.encode(state, a.epoch)
    c.fixed32.encode(state, a.identity)
    c.fixed32.encode(state, a.data)
  },
  decode (state) {
    throw new Error('Signed data should only be encoded')
  }
}

const DeviceAttestation = {
  preencode (state, a) {
    c.fixed32.preencode(state, a.publicKey)
    c.fixed64.preencode(state, a.signature)
  },
  encode (state, a) {
    c.fixed32.encode(state, a.publicKey)
    c.fixed64.encode(state, a.signature)
  },
  decode (state) {
    return {
      publicKey: c.fixed32.decode(state),
      signature: c.fixed64.decode(state)
    }
  }
}

const DeviceAttestationArray = c.array(DeviceAttestation)

const DataAttestation = {
  preencode (state, a) {
    c.fixed64.preencode(state, a.signature)
  },
  encode (state, a) {
    c.fixed64.encode(state, a.signature)
  },
  decode (state) {
    return {
      signature: c.fixed64.decode(state)
    }
  }
}

const ProofEncoding = {
  preencode (state, proof) {
    c.uint.preencode(state, proof.version)
    Epoch.preencode(state, proof.epoch)
    c.fixed32.preencode(state, proof.identity)
    DeviceAttestationArray.preencode(state, proof.chain)

    let flags = 0
    if (proof.data) flags |= 1
    c.uint.preencode(state, flags)

    if (proof.data) DataAttestation.preencode(state, proof.data)
  },
  encode (state, proof) {
    c.uint.encode(state, proof.version)
    Epoch.encode(state, proof.epoch)
    c.fixed32.encode(state, proof.identity)
    DeviceAttestationArray.encode(state, proof.chain)

    let flags = 0
    if (proof.data) flags |= 1
    c.uint.encode(state, flags)

    if (proof.data) DataAttestation.encode(state, proof.data)
  },
  decode (state) {
    const version = c.uint.decode(state)

    // ignore v0 proofs
    if (version === 0) {
      return {
        version: 0,
        epoch: 0,
        identity: null,
        chain: [],
        data: null
      }
    }

    const epoch = Epoch.decode(state)
    const identity = c.fixed32.decode(state)
    const chain = DeviceAttestationArray.decode(state)

    const flags = c.uint.decode(state)
    const data = flags & 1 ? DataAttestation.decode(state) : null

    return {
      version,
      epoch,
      identity,
      chain,
      data
    }
  }
}

const ReceiptEncoding = {
  preencode (state, receipt) {
    Epoch.preencode(state, receipt.epoch)
  },
  encode (state, receipt) {
    Epoch.encode(state, receipt.epoch)
  },
  decode (state) {
    return {
      epoch: Epoch.decode(state)
    }
  }
}

module.exports = {
  ATTESTED_DEVICE,
  ATTESTED_DATA,
  AttestedDevice,
  AttestedData,
  ProofEncoding,
  ReceiptEncoding
}
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const assert = require('nanoassert')
const b4a = require('b4a')
const { HMAC } = require('sodium-hmac')
const bip39 = require('bip39-mnemonic')

const { sign } = require('./crypto')

const MASTER_CHAIN_CODE = b4a.from('ed25519 seed')
const MASTER_SYMMETRIC_CODE = b4a.from('Symmetric key seed')

const HARDENED_OFFSET = 0x80000000

class KeyChain {
  constructor (seed) {
    this.seed = seed

    this._buffer = b4a.alloc(64)

    this.chainKey = this._buffer.subarray(0, 32)
    this.chainCode = this._buffer.subarray(32)

    this.publicKey = b4a.alloc(sodium.crypto_sign_PUBLICKEYBYTES)
    this.secretKey = b4a.alloc(sodium.crypto_sign_SECRETKEYBYTES)

    this._initialise()
  }

  static generateMnemonic () {
    return bip39.generateMnemonic()
  }

  static deriveSeed (mnemonic) {
    return bip39.mnemonicToSeed(mnemonic)
  }

  static async from ({ mnemonic, seed }, path) {
    assert(mnemonic || seed, 'No mnemonic or seed was passed.')

    if (!seed) seed = await KeyChain.deriveSeed(mnemonic)

    const key = new KeyChain(seed)

    if (!path) return key

    return key.get(path)
  }

  getSymmetricKey (path) {
    const buffer = b4a.alloc(64)

    const chainKey = buffer.subarray(0, 32)
    const key = buffer.subarray(32)

    HMAC.sha512(this.seed, MASTER_SYMMETRIC_CODE, buffer)

    for (const step of path) {
      const label = b4a.alloc(step.length + 1)
      b4a.write(label, step, 1, 'utf8')

      HMAC.sha512(label, chainKey, buffer)
    }

    return key
  }

  get isKeychain () {
    return true
  }

  _initialise () {
    HMAC.sha512(this.seed, MASTER_CHAIN_CODE, this._buffer)
    sodium.crypto_sign_seed_keypair(this.publicKey, this.secretKey, this.chainKey)
  }

  clear () {
    this.secretKey.fill(0)
    this.chainKey.fill(0)
    this.chainCode.fill(0)
  }

  get (path) {
    return this.derive(path)
  }

  sign (signable) {
    return sign(signable, this)
  }

  derive (path) {
    const buffer = b4a.from(this._buffer)

    const chainKey = buffer.subarray(0, 32)
    const chainCode = buffer.subarray(32)

    for (const step of path) {
      const index = ensureHardened(step) // hardened indices are >= 2^31
      HMAC.sha512(encodeDerivationData(chainKey, index), chainCode, buffer)
    }

    return createKeyPair(chainKey)
  }
}

module.exports = KeyChain

function createKeyPair (seed) {
  if (!seed) throw new Error('No seed provided')

  const publicKey = b4a.alloc(sodium.crypto_sign_PUBLICKEYBYTES)
  const secretKey = b4a.alloc(sodium.crypto_sign_SECRETKEYBYTES)

  sodium.crypto_sign_seed_keypair(publicKey, secretKey, seed)

  return {
    publicKey,
    secretKey
  }
}

function encodeDerivationData (key, step) {
  const state = { buffer: b4a.alloc(37), start: 0, end: 37 }

  c.uint8.encode(state, 0)
  c.fixed32.encode(state, key)
  state.buffer.writeUInt32BE(step, state.start)

  state.buffer[33] |= 0x80

  return state.buffer
}

function ensureHardened (n) {
  if (n >= HARDENED_OFFSET) return n
  return n + HARDENED_OFFSET
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "keet-identity-key",
  "version": "3.2.0",
  "description": "Hierarchical Deterministic Keys for Keet Identities",
  "main": "index.js",
  "scripts": {
    "test": "standard && brittle test/*.js"
  },
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "devDependencies": {
    "brittle": "^3.3.2",
    "hypercore-crypto": "^3.4.0",
    "standard": "^17.1.0"
  },
  "dependencies": {
    "b4a": "^1.6.4",
    "bip39-mnemonic": "^2.2.0",
    "compact-encoding": "^3.0.0",
    "nanoassert": "^2.0.0",
    "sodium-hmac": "^2.0.1",
    "sodium-universal": "^5.0.1"
  },
  "files": [
    "lib/*"
  ],
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/keet-identity-key.git"
  },
  "bugs": {
    "url": "https://github.com/holepunchto/keet-identity-key/issues"
  },
  "homepage": "https://github.com/holepunchto/keet-identity-key#readme"
}
module.exports = assert

class AssertionError extends Error {}
AssertionError.prototype.name = 'AssertionError'

/**
 * Minimal assert function
 * @param  {any} t Value to check if falsy
 * @param  {string=} m Optional assertion error message
 * @throws {AssertionError}
 */
function assert (t, m) {
  if (!t) {
    var err = new AssertionError(m)
    if (Error.captureStackTrace) Error.captureStackTrace(err, assert)
    throw err
  }
}
{
  "name": "nanoassert",
  "version": "2.0.0",
  "description": "Nanoscale assertion module",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "tape": "^4.9.1"
  },
  "scripts": {
    "test": "tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/emilbayes/nanoassert.git"
  },
  "keywords": [
    "assert",
    "unassert",
    "power-assert",
    "tiny",
    "nano",
    "pico"
  ],
  "author": "Emil Bay <github@tixz.dk>",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/emilbayes/nanoassert/issues"
  },
  "homepage": "https://github.com/emilbayes/nanoassert#readme"
}
module.exports = require.addon.bind(require)
{
  "name": "require-addon",
  "version": "1.2.0",
  "description": "Import native addons across JavaScript runtimes",
  "exports": {
    "./package": "./package.json",
    ".": {
      "bare": "./lib/bare.js",
      "node": "./lib/node.js",
      "default": "./lib/default.js"
    }
  },
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    },
    "url": {
      "bare": "bare-url",
      "default": "url"
    }
  },
  "files": [
    "lib"
  ],
  "scripts": {
    "test": "npm run lint && npm run test:bare && npm run test:node",
    "test:bare": "bare test.js",
    "test:node": "node test.js",
    "lint": "prettier --check .",
    "format": "prettier --write ."
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/require-addon.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/require-addon/issues"
  },
  "homepage": "https://github.com/holepunchto/require-addon#readme",
  "engines": {
    "bare": ">=1.10.0"
  },
  "dependencies": {
    "bare-addon-resolve": "^1.3.0"
  },
  "devDependencies": {
    "bare-bundle": "^1.8.1",
    "bare-bundle-evaluate": "^1.1.0",
    "bare-fs": "^4.0.0",
    "bare-path": "^3.0.0",
    "bare-url": "^2.1.0",
    "brittle": "^3.7.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
const sodium = require('sodium-universal')

module.exports = {
  init: sodium.crypto_hash_sha256_init,
  update: sodium.crypto_hash_sha256_update,
  final: sodium.crypto_hash_sha256_final,
  BYTES: sodium.crypto_hash_sha256_BYTES,
  STATEBYTES: sodium.crypto_hash_sha256_STATEBYTES
}
const sodium = require('sodium-universal')

module.exports = {
  init: sodium.crypto_hash_sha512_init,
  update: sodium.crypto_hash_sha512_update,
  final: sodium.crypto_hash_sha512_final,
  BYTES: sodium.crypto_hash_sha512_BYTES,
  STATEBYTES: sodium.crypto_hash_sha512_STATEBYTES
}
const b4a = require('b4a')

const sha256 = require('./hash/sha256')
const sha512 = require('./hash/sha512')

class HMAC {
  constructor (hash, key) {
    this.hash = hash
    this.length = hash.BYTES

    this._blocksize = 2 * hash.BYTES

    this._initialised = false

    this.state = b4a.alloc(hash.STATEBYTES)
    this.pad = b4a.alloc(this._blocksize)

    if (key) this.init(key)
  }

  init (key) {
    if (this._initialised) {
      throw new Error('Already initialised, call final first')
    }

    if (key.length > this._blocksize) {
      this.hash.init(this.state)
      this.hash.update(this.state, key)
      this.hash.final(this.state, this.pad.subarray(0, this.length))
    } else {
      this.pad.set(key)
    }

    bufferByteXor(this.pad, 0x36)

    this.hash.init(this.state)
    this.hash.update(this.state, this.pad)

    bufferByteXor(this.pad, 0x5c ^ 0x36)

    this._initialised = true

    return this
  }

  update (data) {
    if (!this._initialised) {
      throw new Error('First initialise with a key')
    }

    this.hash.update(this.state, data)
    return this
  }

  final (output = b4a.alloc(this.length)) {
    if (!this._initialised) {
      throw new Error('First initialise with a key')
    }

    const out = output.byteLength === this.length
      ? output
      : output.subarray(0, this.hash.BYTES)

    this.hash.final(this.state, out)

    this.hash.init(this.state)
    this.hash.update(this.state, this.pad)
    this.hash.update(this.state, out)
    this.hash.final(this.state, out)

    this.pad.fill(0)
    this.state.fill(0)

    this._initialised = false

    return out
  }

  static sha256 (data, key, output) {
    const hmac = new HMAC(sha256, key)
    return hmac.update(data).final(output)
  }

  static sha512 (data, key, output) {
    const hmac = new HMAC(sha512, key)
    return hmac.update(data).final(output)
  }
}

module.exports = {
  HMAC,
  sha256,
  sha512
}

function bufferByteXor (output, byte) {
  for (let i = 0; i < output.byteLength; i++) {
    output[i] ^= byte
  }

  return output
}
{
  "name": "sodium-hmac",
  "version": "2.1.0",
  "description": "HMAC utility",
  "main": "index.js",
  "scripts": {
    "test": "standard && brittle test/*.js"
  },
  "author": "",
  "license": "Apache-2.0",
  "dependencies": {
    "b4a": "^1.6.6",
    "sodium-universal": "^5.0.1"
  },
  "devDependencies": {
    "brittle": "^3.4.0",
    "standard": "^17.1.0"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sodium-hmac.git"
  },
  "files": [
    "index.js",
    "hash/*"
  ],
  "bugs": {
    "url": "https://github.com/holepunchto/sodium-hmac/issues"
  },
  "homepage": "https://github.com/holepunchto/sodium-hmac#readme"
}
require.addon = require('require-addon')
module.exports = require.addon('.', __filename)
const assert = require('assert')
const binding = require('./binding')
const { isNode } = require('which-runtime')

const OPTIONAL = Buffer.from(new ArrayBuffer(0))

module.exports = exports = { ...binding }

// memory

exports.sodium_memzero = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  binding.sodium_memzero(buf)
}

exports.sodium_mlock = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  const res = binding.sodium_mlock(buf)

  if (res !== 0) throw new Error('memory lock failed')
}

exports.sodium_munlock = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  const res = binding.sodium_munlock(buf)

  if (res !== 0) throw new Error('memory unlock failed')
}

exports.sodium_malloc = function (size) {
  assert(size >= 0, 'invalid size')

  const buf = Buffer.from(binding.sodium_malloc(size))
  buf.secure = true
  return buf
}

exports.sodium_free = function (buf) {
  if (!buf || !buf.secure) return

  binding.sodium_free(buf.buffer)
}

exports.sodium_mprotect_noaccess = function (buf) {
  const res = binding.sodium_mprotect_noaccess(buf.buffer)

  if (res !== 0) throw new Error('failed to lock buffer')
}

exports.sodium_mprotect_readonly = function (buf) {
  const res = binding.sodium_mprotect_readonly(buf.buffer)

  if (res !== 0) throw new Error('failed to unlock buffer')
}

exports.sodium_mprotect_readwrite = function (buf) {
  const res = binding.sodium_mprotect_readwrite(buf.buffer)

  if (res !== 0) throw new Error('failed to unlock buffer')
}

// crypto_randombytes

exports.randombytes_buf = function (buffer) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')

  binding.randombytes_buf(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

exports.randombytes_buf_deterministic = function (buffer, seed) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    seed.byteLength === binding.randombytes_SEEDBYTES,
    "seed must be 'randombytes_SEEDBYTES' bytes"
  )

  binding.randombytes_buf_deterministic(
    buffer.buffer,
    buffer.byteOffset,
    buffer.byteLength,

    seed.buffer,
    seed.byteOffset,
    seed.byteLength
  )
}

// sodium_helpers

exports.sodium_memcmp = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  return binding.sodium_memcmp(a, b)
}

exports.sodium_add = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  binding.sodium_add(a, b)
}

exports.sodium_sub = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  binding.sodium_sub(a, b)
}

exports.sodium_compare = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  return binding.sodium_compare(a, b)
}

exports.sodium_is_zero = function (buffer, length) {
  if (length === undefined) length = buffer.byteLength

  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(length >= 0 && length <= buffer.byteLength, 'invalid length')

  return binding.sodium_is_zero(buffer, length)
}

exports.sodium_pad = function (buffer, unpaddedBuflen, blockSize) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(unpaddedBuflen <= buffer.byteLength, 'unpadded length cannot exceed buffer length')
  assert(blockSize <= buffer.byteLength, 'block size cannot exceed buffer length')
  assert(blockSize >= 1, 'block size must be at least 1 byte')
  assert(
    buffer.byteLength >= unpaddedBuflen + (blockSize - (unpaddedBuflen % blockSize)),
    'buf not long enough'
  )

  return binding.sodium_pad(buffer, unpaddedBuflen, blockSize)
}

exports.sodium_unpad = function (buffer, paddedBuflen, blockSize) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(paddedBuflen <= buffer.byteLength, 'unpadded length cannot exceed buffer length')
  assert(blockSize <= buffer.byteLength, 'block size cannot exceed buffer length')
  assert(blockSize >= 1, 'block size must be at least 1 byte')

  return binding.sodium_unpad(buffer, paddedBuflen, blockSize)
}

// crypto_sign

exports.crypto_sign_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )
  assert(
    seed.byteLength === binding.crypto_sign_SEEDBYTES,
    "seed must be 'crypto_sign_SEEDBYTES' bytes"
  )

  const res = binding.crypto_sign_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign = function (sm, m, sk) {
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sm.byteLength === binding.crypto_sign_BYTES + m.byteLength,
    "sm must be 'm.byteLength + crypto_sign_BYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign(sm, m, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_open = function (m, sm, pk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sm.byteLength >= binding.crypto_sign_BYTES,
    "sm must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    m.byteLength === sm.byteLength - binding.crypto_sign_BYTES,
    "m must be 'sm.byteLength - crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_open(m, sm, pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_open = function (m, sm, pk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sm.byteLength >= binding.crypto_sign_BYTES,
    "sm must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    m.byteLength === sm.byteLength - binding.crypto_sign_BYTES,
    "m must be 'sm.byteLength - crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  return binding.crypto_sign_open(m, sm, pk)
}

exports.crypto_sign_detached = function (sig, m, sk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(sig.byteLength === binding.crypto_sign_BYTES, "sig must be 'crypto_sign_BYTES' bytes")
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_detached(sig, m, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_verify_detached = function (sig, m, pk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sig.byteLength >= binding.crypto_sign_BYTES,
    "sig must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  return binding.crypto_sign_verify_detached(
    sig.buffer,
    sig.byteOffset,
    sig.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    pk.buffer,
    pk.byteOffset,
    pk.byteLength
  )
}

exports.crypto_sign_ed25519_sk_to_pk = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_sk_to_pk(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_ed25519_pk_to_curve25519 = function (x25519pk, ed25519pk) {
  assert(ArrayBuffer.isView(x25519pk), 'x25519pk must be a typed array')
  assert(ArrayBuffer.isView(ed25519pk), 'ed25519pk must be a typed array')
  assert(
    x25519pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "x25519pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    ed25519pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "ed25519pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_pk_to_curve25519(x25519pk, ed25519pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_ed25519_sk_to_curve25519 = function (x25519sk, ed25519sk) {
  assert(ArrayBuffer.isView(x25519sk), 'x25519sk must be a typed array')
  assert(ArrayBuffer.isView(ed25519sk), 'ed25519sk must be a typed array')
  assert(
    x25519sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "x25519sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const edLen = ed25519sk.byteLength

  assert(
    edLen === binding.crypto_sign_SECRETKEYBYTES || edLen === binding.crypto_box_SECRETKEYBYTES,
    "ed25519sk must be 'crypto_sign_SECRETKEYBYTES' or 'crypto_sign_SECRETKEYBYTES - crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_sk_to_curve25519(x25519sk, ed25519sk)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_box

exports.crypto_box_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    seed.byteLength === binding.crypto_box_SEEDBYTES,
    "seed must be 'crypto_box_SEEDBYTES' bytes"
  )

  const res = binding.crypto_box_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_easy = function (c, m, n, pk, sk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength === m.byteLength + exports.crypto_box_MACBYTES,
    "c must be 'm.byteLength + crypto_box_MACBYTES' bytes"
  )
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_easy(c, m, n, pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_detached = function (c, mac, m, n, pk, sk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(mac.byteLength === exports.crypto_box_MACBYTES, "mac must be 'crypto_box_MACBYTES' bytes")
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_detached(c, mac, m, n, pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_open_easy = function (m, c, n, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength >= exports.crypto_box_MACBYTES,
    "c must be at least 'crypto_box_MACBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - exports.crypto_box_MACBYTES,
    "m must be 'c.byteLength - crypto_box_MACBYTES' bytes"
  )
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_open_easy(m, c, n, pk, sk)
}

exports.crypto_box_open_detached = function (m, c, mac, n, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(mac.byteLength === exports.crypto_box_MACBYTES, "mac must be 'crypto_box_MACBYTES' bytes")
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_open_detached(m, c, mac, n, pk, sk)
}

exports.crypto_box_seal = function (c, m, pk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    c.byteLength === m.byteLength + exports.crypto_box_SEALBYTES,
    "c must be 'm.byteLength + crypto_box_SEALBYTES' bytes"
  )
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_box_seal(c, m, pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_seal_open = function (m, c, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength >= exports.crypto_box_SEALBYTES,
    "c must be at least 'crypto_box_SEALBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - exports.crypto_box_SEALBYTES,
    "m must be 'c.byteLength - crypto_box_SEALBYTES' bytes"
  )
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_seal_open(
    m.buffer,
    m.byteOffset,
    m.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    pk.buffer,
    pk.byteOffset,
    pk.byteLength,

    sk.buffer,
    sk.byteOffset,
    sk.byteLength
  )
}

// crypto_secretbox

exports.crypto_secretbox_easy = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_secretbox_MACBYTES,
    "c must be 'm.byteLength + crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretbox_easy(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretbox_open_easy = function (m, c, n, k) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    c.byteLength >= binding.crypto_secretbox_MACBYTES,
    "c must be at least 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - binding.crypto_secretbox_MACBYTES,
    "m must be 'c.byteLength - crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  return binding.crypto_secretbox_open_easy(m, c, n, k)
}

exports.crypto_secretbox_detached = function (c, mac, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    mac.byteLength === binding.crypto_secretbox_MACBYTES,
    "mac must be 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretbox_detached(c, mac, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretbox_open_detached = function (m, c, mac, n, k) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(
    mac.byteLength === binding.crypto_secretbox_MACBYTES,
    "mac must be 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  return binding.crypto_secretbox_open_detached(m, c, mac, n, k)
}

// crypto_generichash

exports.crypto_generichash = function (output, input, key) {
  if (!key) key = OPTIONAL

  assert(ArrayBuffer.isView(output), 'output must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    output.byteLength >= binding.crypto_generichash_BYTES_MIN &&
      output.byteLength <= binding.crypto_generichash_BYTES_MAX,
    'output must be between crypto_generichash_BYTES_MIN and crypto_generichash_BYTES_MAX bytes'
  )

  if (key !== OPTIONAL) {
    assert(ArrayBuffer.isView(key), 'key must be a typed array')
    assert(
      key.byteLength >= binding.crypto_generichash_KEYBYTES_MIN &&
        key.byteLength <= binding.crypto_generichash_KEYBYTES_MAX,
      'key must be between crypto_generichash_KEYBYTES_MIN and crypto_generichash_KEYBYTES_MAX bytes'
    )
  }

  const res = binding.crypto_generichash(
    output.buffer,
    output.byteOffset,
    output.byteLength,

    input.buffer,
    input.byteOffset,
    input.byteLength,

    key.buffer,
    key.byteOffset,
    key.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_batch = function (output, batch, key) {
  assert(ArrayBuffer.isView(output), 'output must be a typed array')

  if (isNode || batch.length < 4) {
    const res = binding.crypto_generichash_batch(output, batch, !!key, key || OPTIONAL)
    if (res !== 0) throw new Error('status: ' + res)
  } else {
    const state = Buffer.alloc(binding.crypto_generichash_STATEBYTES)

    exports.crypto_generichash_init(state, key, output.byteLength)

    for (const buf of batch) {
      exports.crypto_generichash_update(state, buf)
    }

    exports.crypto_generichash_final(state, output)
  }
}

exports.crypto_generichash_keygen = function (key) {
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(
    key.byteLength === binding.crypto_generichash_KEYBYTES,
    "key must be 'crypto_generichash_KEYBYTES' bytes"
  )

  const res = binding.crypto_generichash_keygen(key.buffer, key.byteOffset, key.byteLength)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_init = function (state, key, outputLength) {
  if (!key) key = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_init(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    key.buffer,
    key.byteOffset,
    key.byteLength,

    outputLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_update(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    input.buffer,
    input.byteOffset,
    input.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_final = function (state, output) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(output), 'output must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_final(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    output.buffer,
    output.byteOffset,
    output.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

// secretstream

exports.crypto_secretstream_xchacha20poly1305_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  binding.crypto_secretstream_xchacha20poly1305_keygen(k.buffer, k.byteOffset, k.byteLength)
}

exports.crypto_secretstream_xchacha20poly1305_init_push = function (state, header, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(header), 'header must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    header.byteLength === binding.crypto_secretstream_xchacha20poly1305_HEADERBYTES,
    "header must be 'crypto_secretstream_xchacha20poly1305_HEADERBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_init_push(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    header.buffer,
    header.byteOffset,
    header.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretstream_xchacha20poly1305_init_pull = function (state, header, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(header), 'header must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    header.byteLength === binding.crypto_secretstream_xchacha20poly1305_HEADERBYTES,
    "header must be 'crypto_secretstream_xchacha20poly1305_HEADERBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_init_pull(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    header.buffer,
    header.byteOffset,
    header.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretstream_xchacha20poly1305_push = function (state, c, m, ad, tag) {
  if (!ad) ad = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    c.byteLength === m.byteLength + binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "c must be 'm.byteLength + crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_push(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    ad.buffer,
    ad.byteOffset,
    ad.byteLength,

    tag
  )

  if (res < 0) throw new Error('push failed')

  return res
}

exports.crypto_secretstream_xchacha20poly1305_pull = function (state, m, tag, c, ad) {
  if (!ad) ad = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(tag), 'tag must be a typed array')
  assert(tag.byteLength === 1, 'tag must be 1 byte')

  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    c.byteLength >= binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "c must be at least 'crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "m must be 'c.byteLength - crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_pull(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    tag.buffer,
    tag.byteOffset,
    tag.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    ad.buffer,
    ad.byteOffset,
    ad.byteLength
  )

  if (res < 0) throw new Error('pull failed')

  return res
}

exports.crypto_secretstream_xchacha20poly1305_rekey = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )

  binding.crypto_secretstream_xchacha20poly1305_rekey(
    state.buffer,
    state.byteOffset,
    state.byteLength
  )
}

// crypto_stream

exports.crypto_stream = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xor(
    c.buffer,
    c.byteOffset,
    c.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    n.buffer,
    n.byteOffset,
    n.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_auth

exports.crypto_auth = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(out.byteLength === binding.crypto_auth_BYTES, "out must be 'crypto_auth_BYTES' bytes")
  assert(k.byteLength === binding.crypto_auth_KEYBYTES, "k must be 'crypto_auth_KEYBYTES' bytes")

  const res = binding.crypto_auth(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_auth_verify = function (h, input, k) {
  assert(ArrayBuffer.isView(h), 'h must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(h.byteLength === binding.crypto_auth_BYTES, "h must be 'crypto_auth_BYTES' bytes")
  assert(k.byteLength === binding.crypto_auth_KEYBYTES, "k must be 'crypto_auth_KEYBYTES' bytes")

  return binding.crypto_auth_verify(h, input, k)
}

// crypto_onetimeauth

exports.crypto_onetimeauth = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    out.byteLength === binding.crypto_onetimeauth_BYTES,
    "out must be 'crypto_onetimeauth_BYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_init = function (state, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_init(state, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )
  assert(
    out.byteLength === binding.crypto_onetimeauth_BYTES,
    "out must be 'crypto_onetimeauth_BYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_verify = function (h, input, k) {
  assert(ArrayBuffer.isView(h), 'h must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    h.byteLength === binding.crypto_onetimeauth_BYTES,
    "h must be 'crypto_onetimeauth_BYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  return binding.crypto_onetimeauth_verify(h, input, k)
}

// crypto_pwhash

exports.crypto_pwhash = function (out, passwd, salt, opslimit, memlimit, alg) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_BYTES_MIN,
    "out must be at least 'crypto_pwhash_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_BYTES_MAX,
    "out must be at most 'crypto_pwhash_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_SALTBYTES,
    "salt must be 'crypto_pwhash_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )
  assert(alg >= 1 && alg <= 2, 'alg must be either Argon2i 1.3 or Argon2id 1.3')

  const res = binding.crypto_pwhash(out, passwd, salt, opslimit, memlimit, alg)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_async = function (
  out,
  passwd,
  salt,
  opslimit,
  memlimit,
  alg,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_BYTES_MIN,
    "out must be at least 'crypto_pwhash_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_BYTES_MAX,
    "out must be at most 'crypto_pwhash_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_SALTBYTES,
    "salt must be 'crypto_pwhash_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )
  assert(alg >= 1 && alg <= 2, 'alg must be either Argon2i 1.3 or Argon2id 1.3')

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    opslimit,
    memlimit,
    alg,

    done
  )

  return promise
}

exports.crypto_pwhash_str = function (out, passwd, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_STRBYTES,
    "out must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(typeof opslimit === 'number', 'opslimit must be a number')
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(typeof memlimit === 'number', 'memlimit must be a number')
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_str(out, passwd, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_str_async = function (out, passwd, opslimit, memlimit, callback = undefined) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_STRBYTES,
    "out must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(typeof opslimit === 'number', 'opslimit must be a number')
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(typeof memlimit === 'number', 'memlimit must be a number')
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_str_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_str_verify = function (str, passwd) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )

  return binding.crypto_pwhash_str_verify(str, passwd)
}

exports.crypto_pwhash_str_verify_async = function (str, passwd, callback = undefined) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  const [done, promise] = checkStatus(callback, true)

  binding.crypto_pwhash_str_verify_async(
    str.buffer,
    str.byteOffset,
    str.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    done
  )

  return promise
}

exports.crypto_pwhash_str_needs_rehash = function (str, opslimit, memlimit) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  return binding.crypto_pwhash_str_needs_rehash(str, opslimit, memlimit)
}

exports.crypto_pwhash_scryptsalsa208sha256 = function (out, passwd, salt, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MIN,
    "out must be at least 'crypto_pwhash_scryptsalsa208sha256_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MAX,
    "out must be at most 'crypto_pwhash_scryptsalsa208sha256_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_SALTBYTES,
    "salt must be 'crypto_pwhash_scryptsalsa208sha256_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_scryptsalsa208sha256(out, passwd, salt, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_scryptsalsa208sha256_async = function (
  out,
  passwd,
  salt,
  opslimit,
  memlimit,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MIN,
    "out must be at least 'crypto_pwhash_scryptsalsa208sha256_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MAX,
    "out must be at most 'crypto_pwhash_scryptsalsa208sha256_BYTES_MAX' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    salt.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_SALTBYTES,
    "salt must be 'crypto_pwhash_scryptsalsa208sha256_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_scryptsalsa208sha256_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str_async = function (
  out,
  passwd,
  opslimit,
  memlimit,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "out must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_scryptsalsa208sha256_str_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str = function (out, passwd, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "out must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_scryptsalsa208sha256_str(out, passwd, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_scryptsalsa208sha256_str_verify_async = function (
  str,
  passwd,
  callback = undefined
) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  const [done, promise] = checkStatus(callback, true)

  binding.crypto_pwhash_scryptsalsa208sha256_str_verify_async(
    str.buffer,
    str.byteOffset,
    str.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str_verify = function (str, passwd) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  return binding.crypto_pwhash_scryptsalsa208sha256_str_verify(str, passwd)
}

exports.crypto_pwhash_scryptsalsa208sha256_str_needs_rehash = function (str, opslimit, memlimit) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  return binding.crypto_pwhash_scryptsalsa208sha256_str_needs_rehash(str, opslimit, memlimit)
}

// crypto_kx

exports.crypto_kx_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "pk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "sk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    pk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "pk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "sk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    seed.byteLength === binding.crypto_kx_SEEDBYTES,
    "seed must be 'crypto_kx_SEEDBYTES' bytes"
  )

  const res = binding.crypto_kx_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_client_session_keys = function (rx, tx, clientPk, clientSk, serverPk) {
  if (!rx) rx = undefined
  if (!tx) tx = undefined

  assert(rx || tx, 'at least one session key must be specified')

  if (rx) {
    assert(ArrayBuffer.isView(rx), 'rx must be a typed array')
    assert(
      rx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "rx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  if (tx) {
    assert(ArrayBuffer.isView(tx), 'tx must be a typed array')
    assert(
      tx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "tx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  assert(ArrayBuffer.isView(clientPk), 'clientPk must be a typed array')
  assert(ArrayBuffer.isView(clientSk), 'clientSk must be a typed array')
  assert(ArrayBuffer.isView(serverPk), 'serverPk must be a typed array')
  assert(
    clientPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "clientPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    clientSk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "clientSk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    serverPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "serverPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_client_session_keys(rx, tx, clientPk, clientSk, serverPk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_server_session_keys = function (rx, tx, serverPk, serverSk, clientPk) {
  if (!rx) rx = undefined
  if (!tx) tx = undefined

  assert(rx || tx, 'at least one session key must be specified')

  if (rx) {
    assert(ArrayBuffer.isView(rx), 'rx must be a typed array')
    assert(
      rx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "rx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  if (tx) {
    assert(ArrayBuffer.isView(tx), 'tx must be a typed array')
    assert(
      tx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "tx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  assert(ArrayBuffer.isView(serverPk), 'serverPk must be a typed array')
  assert(ArrayBuffer.isView(serverSk), 'serverSk must be a typed array')
  assert(ArrayBuffer.isView(clientPk), 'clientPk must be a typed array')
  assert(
    serverPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "serverPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    serverSk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "serverSk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    clientPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "clientPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_server_session_keys(rx, tx, serverPk, serverSk, clientPk)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_scalarmult

exports.crypto_scalarmult_base = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_BYTES,
    "q must be 'crypto_scalarmult_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_SCALARBYTES,
    "n must be 'crypto_scalarmult_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_base(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_BYTES,
    "q must be 'crypto_scalarmult_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_SCALARBYTES,
    "n must be 'crypto_scalarmult_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_BYTES,
    "p must be 'crypto_scalarmult_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_base = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_base(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519 = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "p must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_is_valid_point = function (p) {
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )

  return binding.crypto_core_ed25519_is_valid_point(p)
}

exports.crypto_core_ed25519_from_uniform = function (p, r) {
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_UNIFORMBYTES,
    "r must be 'crypto_core_ed25519_UNIFORMBYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_from_uniform(p, r)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_base_noclamp = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_base_noclamp(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_noclamp = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "p must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_noclamp(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_core

exports.crypto_core_ed25519_add = function (r, p, q) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_BYTES,
    "r must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_core_ed25519_BYTES,
    "q must be 'crypto_core_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_add(r, p, q)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_sub = function (r, p, q) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_BYTES,
    "r must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_core_ed25519_BYTES,
    "q must be 'crypto_core_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_sub(r, p, q)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_scalar_random = function (r) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "r must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_random(r)
}

exports.crypto_core_ed25519_scalar_reduce = function (r, s) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "r must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_NONREDUCEDSCALARBYTES,
    "s must be 'crypto_core_ed25519_NONREDUCEDSCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_reduce(r, s)
}

exports.crypto_core_ed25519_scalar_invert = function (recip, s) {
  assert(ArrayBuffer.isView(recip), 'recip must be a typed array')
  assert(
    recip.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "recip must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_invert(recip, s)
}

exports.crypto_core_ed25519_scalar_negate = function (neg, s) {
  assert(ArrayBuffer.isView(neg), 'neg must be a typed array')
  assert(
    neg.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "neg must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_negate(neg, s)
}

exports.crypto_core_ed25519_scalar_complement = function (comp, s) {
  assert(ArrayBuffer.isView(comp), 'comp must be a typed array')
  assert(
    comp.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "comp must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_complement(comp, s)
}

exports.crypto_core_ed25519_scalar_add = function (z, x, y) {
  assert(ArrayBuffer.isView(z), 'z must be a typed array')
  assert(
    z.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "z must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(x), 'x must be a typed array')
  assert(
    x.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "x must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(y), 'y must be a typed array')
  assert(
    y.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "y must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_add(z, x, y)
}

exports.crypto_core_ed25519_scalar_sub = function (z, x, y) {
  assert(ArrayBuffer.isView(z), 'z must be a typed array')
  assert(
    z.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "z must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(x), 'x must be a typed array')
  assert(
    x.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "x must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(y), 'y must be a typed array')
  assert(
    y.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "y must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_sub(z, x, y)
}

// crypto_shorthash

exports.crypto_shorthash = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_shorthash_BYTES,
    "out must be 'crypto_shorthash_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_shorthash_KEYBYTES,
    "k must be 'crypto_shorthash_KEYBYTES' bytes"
  )

  const res = binding.crypto_shorthash(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_kdf

exports.crypto_kdf_keygen = function (key) {
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(key.byteLength === binding.crypto_kdf_KEYBYTES, "key must be 'crypto_kdf_KEYBYTES' bytes")

  binding.crypto_kdf_keygen(key)
}

exports.crypto_kdf_derive_from_key = function (subkey, subkeyId, ctx, key) {
  assert(ArrayBuffer.isView(subkey), 'subkey must be a typed array')
  assert(
    subkey.byteLength >= binding.crypto_kdf_BYTES_MIN,
    "subkey must be at least 'crypto_kdf_BYTES_MIN' bytes"
  )
  assert(
    subkey.byteLength <= binding.crypto_kdf_BYTES_MAX,
    "subkey must be at most 'crypto_kdf_BYTES_MAX' bytes"
  )
  assert(ArrayBuffer.isView(ctx), 'ctx must be a typed array')
  assert(
    ctx.byteLength === binding.crypto_kdf_CONTEXTBYTES,
    "ctx must be 'crypto_kdf_CONTEXTBYTES' bytes"
  )
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(key.byteLength === binding.crypto_kdf_KEYBYTES, "key must be 'crypto_kdf_KEYBYTES' bytes")

  const res = binding.crypto_kdf_derive_from_key(subkey, subkeyId, ctx, key)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_hash

exports.crypto_hash = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(out.byteLength === binding.crypto_hash_BYTES, "out must be 'crypto_hash_BYTES' bytes")

  const res = binding.crypto_hash(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256 = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha256_BYTES,
    "out must be 'crypto_hash_sha256_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha256(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_init = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_init(state)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha256_BYTES,
    "out must be 'crypto_hash_sha256_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512 = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha512_BYTES,
    "out must be 'crypto_hash_sha512_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha512(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_init = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_init(state)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha512_BYTES,
    "out must be 'crypto_hash_sha512_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_aead

exports.crypto_aead_xchacha20poly1305_ietf_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  binding.crypto_aead_xchacha20poly1305_ietf_keygen(k)
}

exports.crypto_aead_xchacha20poly1305_ietf_encrypt = function (c, m, ad, nsec, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "c must be 'm.byteLength + crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(c.byteLength <= 0xffffffff, 'c.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_encrypt(c, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_decrypt = function (m, nsec, c, ad, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "m must be 'c.byteLength - crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(m.byteLength <= 0xffffffff, 'm.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_decrypt(m, c, ad, npub, k)

  if (res < 0) throw new Error('could not verify data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_encrypt_detached = function (
  c,
  mac,
  m,
  ad,
  nsec,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_encrypt_detached(c, mac, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_decrypt_detached = function (
  m,
  nsec,
  c,
  mac,
  ad,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_decrypt_detached(m, c, mac, ad, npub, k)

  if (res !== 0) throw new Error('could not verify data')
}

exports.crypto_aead_chacha20poly1305_ietf_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  binding.crypto_aead_chacha20poly1305_ietf_keygen(k)
}

exports.crypto_aead_chacha20poly1305_ietf_encrypt = function (c, m, ad, nsec, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "c must be 'm.byteLength + crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(c.byteLength <= 0xffffffff, 'c.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_encrypt(c, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_decrypt = function (m, nsec, c, ad, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "m must be 'c.byteLength - crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(m.byteLength <= 0xffffffff, 'm.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_decrypt(m, c, ad, npub, k)

  if (res < 0) throw new Error('could not verify data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_encrypt_detached = function (
  c,
  mac,
  m,
  ad,
  nsec,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_encrypt_detached(c, mac, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_decrypt_detached = function (
  m,
  nsec,
  c,
  mac,
  ad,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_decrypt_detached(m, c, mac, ad, npub, k)

  if (res !== 0) throw new Error('could not verify data')
}

// crypto_stream

exports.crypto_stream_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  binding.crypto_stream_xor_wrap_init(state, n, k)
}

exports.crypto_stream_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_xor_wrap_update(state, c, m)
}

exports.crypto_stream_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_xor_wrap_final(state)
}

exports.crypto_stream_chacha20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  binding.crypto_stream_chacha20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_chacha20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_chacha20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_chacha20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_chacha20_xor_wrap_final(state)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  binding.crypto_stream_chacha20_ietf_xor_wrap_init(state, n, k)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_chacha20_ietf_xor_wrap_update(state, c, m)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_chacha20_ietf_xor_wrap_final(state)
}

exports.crypto_stream_xchacha20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  binding.crypto_stream_xchacha20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_xchacha20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_xchacha20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_xchacha20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_xchacha20_xor_wrap_final(state)
}

exports.crypto_stream_salsa20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  binding.crypto_stream_salsa20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_salsa20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_salsa20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_salsa20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_salsa20_xor_wrap_final(state)
}

// experimental

exports.extension_tweak_ed25519_base = function (n, p, ns) {
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.extension_tweak_ed25519_BYTES,
    "p must be 'extension_tweak_ed25519_BYTES' bytes"
  )

  binding.extension_tweak_ed25519_base(n, p, ns)
}

exports.extension_tweak_ed25519_sign_detached = function (sig, m, scalar, pk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(sig.byteLength === binding.crypto_sign_BYTES, "sig must be 'crypto_sign_BYTES' bytes")
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  if (pk) {
    assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
    assert(
      pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
      "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
    )
  }

  const res = binding.extension_tweak_ed25519_sign_detached(sig, m, scalar, pk)

  if (res !== 0) throw new Error('failed to compute signature')
}

exports.extension_tweak_ed25519_sk_to_scalar = function (n, sk) {
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  binding.extension_tweak_ed25519_sk_to_scalar(n, sk)
}

exports.extension_tweak_ed25519_scalar = function (scalarOut, scalar, ns) {
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_scalar(scalarOut, scalar, ns)
}

exports.extension_tweak_ed25519_pk = function (tpk, pk, ns) {
  assert(ArrayBuffer.isView(tpk), 'tpk must be a typed array')
  assert(
    tpk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "tpk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_pk(tpk, pk, ns)

  if (res !== 0) throw new Error('failed to tweak public key')
}

exports.extension_tweak_ed25519_keypair = function (pk, scalarOut, scalarIn, ns) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.extension_tweak_ed25519_BYTES,
    "pk must be 'extension_tweak_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarIn), 'scalarIn must be a typed array')
  assert(
    scalarIn.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarIn must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_keypair(pk, scalarOut, scalarIn, ns)
}

exports.extension_tweak_ed25519_scalar_add = function (scalarOut, scalar, n) {
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_scalar_add(scalarOut, scalar, n)
}

exports.extension_tweak_ed25519_pk_add = function (tpk, pk, p) {
  assert(ArrayBuffer.isView(tpk), 'tpk must be a typed array')
  assert(
    tpk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "tpk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "p must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_pk_add(tpk, pk, p)

  if (res !== 0) throw new Error('failed to add tweak to public key')
}

exports.extension_tweak_ed25519_keypair_add = function (pk, scalarOut, scalarIn, tweak) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.extension_tweak_ed25519_BYTES,
    "pk must be 'extension_tweak_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarIn), 'scalarIn must be a typed array')
  assert(
    scalarIn.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarIn must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(tweak), 'tweak must be a typed array')
  assert(
    tweak.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "tweak must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_keypair_add(pk, scalarOut, scalarIn, tweak)

  if (res !== 0) throw new Error('failed to add tweak to keypair')
}

exports.extension_pbkdf2_sha512_async = function (out, passwd, salt, iter, outlen, callback) {
  assert(
    iter >= binding.extension_pbkdf2_sha512_ITERATIONS_MIN,
    "iter must be at least 'extension_pbkdf2_sha512_ITERATIONS_MIN'"
  )
  assert(
    outlen <= binding.extension_pbkdf2_sha512_BYTES_MAX,
    "outlen must be at most 'extension_pbkdf2_sha512_BYTES_MAX'"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(out.byteLength >= outlen, "out must be at least 'outlen' bytes")
  assert(out.byteLength > 0, 'out must not be empty')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(salt.byteLength > 0, 'salt must not be empty')

  const [done, promise] = checkStatus(callback)

  binding.extension_pbkdf2_sha512_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    iter,
    outlen,

    done
  )

  return promise
}

exports.extension_pbkdf2_sha512 = function (out, passwd, salt, iter, outlen) {
  assert(
    iter >= binding.extension_pbkdf2_sha512_ITERATIONS_MIN,
    "iter must be at least 'extension_pbkdf2_sha512_ITERATIONS_MIN'"
  )
  assert(
    outlen <= binding.extension_pbkdf2_sha512_BYTES_MAX,
    "outlen must be at most 'extension_pbkdf2_sha512_BYTES_MAX'"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(out.byteLength >= outlen, "out must be at least 'outlen' bytes")
  assert(out.byteLength > 0, 'out must not be empty')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(salt.byteLength > 0, 'salt must not be empty')

  const res = binding.extension_pbkdf2_sha512(out, passwd, salt, iter, outlen)

  if (res !== 0) throw new Error('failed to add tweak to public key')
}

function checkStatus(callback, booleanResult = false) {
  let done, promise

  if (typeof callback === 'function') {
    done = function (status) {
      if (booleanResult) callback(null, status === 0)
      else if (status === 0) callback(null)
      else callback(new Error('status: ' + status))
    }
  } else {
    promise = new Promise(function (resolve, reject) {
      done = function (status) {
        if (booleanResult) resolve(status === 0)
        else if (status === 0) resolve()
        else reject(new Error('status: ' + status))
      }
    })
  }

  return [done, promise]
}
{
  "name": "sodium-native",
  "version": "5.1.0",
  "description": "Low level bindings for libsodium",
  "main": "index.js",
  "files": [
    "index.js",
    "binding.cc",
    "binding.js",
    "extensions",
    "prebuilds",
    "CMakeLists.txt"
  ],
  "imports": {
    "assert": {
      "bare": "bare-assert",
      "node": "assert"
    }
  },
  "addon": true,
  "dependencies": {
    "bare-assert": "^1.2.0",
    "require-addon": "^1.1.0",
    "which-runtime": "^1.2.1"
  },
  "devDependencies": {
    "bare-compat-napi": "^1.3.5",
    "brittle": "^3.16.2",
    "cmake-bare": "^1.6.1",
    "cmake-fetch": "^1.4.3",
    "cmake-napi": "^1.2.1",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "test": "prettier . --check && npm run test:node && npm run test:bare",
    "test:node": "node test/all.js",
    "test:bare": "bare test/all.js"
  },
  "standard": {
    "ignore": [
      "/test/fixtures/*.js"
    ]
  },
  "engines": {
    "bare": ">=1.16.0"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sodium-native.git"
  },
  "contributors": [
    "Emil Bay <github@tixz.dk> (http://bayes.dk)",
    "Mathias Buus <mathiasbuus@gmail.com> (https://mafinto.sh)",
    "Christophe Diederichs <chm-diederichs@hyperdivision.dk>"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/sodium-native/issues"
  },
  "homepage": "https://github.com/holepunchto/sodium-native"
}
module.exports = require('sodium-native')
{
  "name": "sodium-universal",
  "version": "5.0.1",
  "description": "Universal wrapper for sodium-javascript and sodium-native working in Node.js and the Browser",
  "main": "index.js",
  "dependencies": {
    "sodium-native": "^5.0.1"
  },
  "peerDependencies": {
    "sodium-javascript": "~0.8.0"
  },
  "peerDependenciesMeta": {
    "sodium-javascript": {
      "optional": true
    }
  },
  "scripts": {
    "prepublish": "./build-scripts/generate.js"
  },
  "browser": {
    "sodium-native": "sodium-javascript"
  },
  "browserify": {
    "transform": [
      "./build-scripts/transform.js"
    ]
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sodium-universal.git"
  },
  "keywords": [
    "libsodium",
    "sodium",
    "sodium-native",
    "sodium-javascript",
    "browserify"
  ],
  "contributors": [
    "Emil Bay <github@tixz.dk> (http://bayes.dk)",
    "Mathias Buus <mathiasbuus@gmail.com> (https://mafinto.sh)",
    "Christophe Diederichs <chm-diederichs@hyperdivision.dk>"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/sodium-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/sodium-universal#readme"
}
const { EventEmitter } = require('events-universal')
const FIFO = require('fast-fifo')
const TextDecoder = require('text-decoder')

const StreamError = require('./lib/errors.js')

// if we do a future major, expect queue microtask to be there always, for now a bit defensive
const qmt =
  typeof queueMicrotask === 'undefined' ? (fn) => global.process.nextTick(fn) : queueMicrotask

// 29 bits used total (4 from shared, 14 from read, and 11 from write)
const MAX = (1 << 29) - 1

// Shared state
const OPENING = 0b0001
const PREDESTROYING = 0b0010
const DESTROYING = 0b0100
const DESTROYED = 0b1000

const NOT_OPENING = MAX ^ OPENING
const NOT_PREDESTROYING = MAX ^ PREDESTROYING

// Read state (4 bit offset from shared state)
const READ_ACTIVE = 0b00000000000001 << 4
const READ_UPDATING = 0b00000000000010 << 4
const READ_PRIMARY = 0b00000000000100 << 4
const READ_QUEUED = 0b00000000001000 << 4
const READ_RESUMED = 0b00000000010000 << 4
const READ_PIPE_DRAINED = 0b00000000100000 << 4
const READ_ENDING = 0b00000001000000 << 4
const READ_EMIT_DATA = 0b00000010000000 << 4
const READ_EMIT_READABLE = 0b00000100000000 << 4
const READ_EMITTED_READABLE = 0b00001000000000 << 4
const READ_DONE = 0b00010000000000 << 4
const READ_NEXT_TICK = 0b00100000000000 << 4
const READ_NEEDS_PUSH = 0b01000000000000 << 4
const READ_READ_AHEAD = 0b10000000000000 << 4

// Combined read state
const READ_FLOWING = READ_RESUMED | READ_PIPE_DRAINED
const READ_ACTIVE_AND_NEEDS_PUSH = READ_ACTIVE | READ_NEEDS_PUSH
const READ_PRIMARY_AND_ACTIVE = READ_PRIMARY | READ_ACTIVE
const READ_EMIT_READABLE_AND_QUEUED = READ_EMIT_READABLE | READ_QUEUED
const READ_RESUMED_READ_AHEAD = READ_RESUMED | READ_READ_AHEAD

const READ_NOT_ACTIVE = MAX ^ READ_ACTIVE
const READ_NON_PRIMARY = MAX ^ READ_PRIMARY
const READ_NON_PRIMARY_AND_PUSHED = MAX ^ (READ_PRIMARY | READ_NEEDS_PUSH)
const READ_PUSHED = MAX ^ READ_NEEDS_PUSH
const READ_PAUSED = MAX ^ READ_RESUMED
const READ_NOT_QUEUED = MAX ^ (READ_QUEUED | READ_EMITTED_READABLE)
const READ_NOT_ENDING = MAX ^ READ_ENDING
const READ_PIPE_NOT_DRAINED = MAX ^ READ_FLOWING
const READ_NOT_NEXT_TICK = MAX ^ READ_NEXT_TICK
const READ_NOT_UPDATING = MAX ^ READ_UPDATING
const READ_NO_READ_AHEAD = MAX ^ READ_READ_AHEAD
const READ_PAUSED_NO_READ_AHEAD = MAX ^ READ_RESUMED_READ_AHEAD

// Write state (18 bit offset, 4 bit offset from shared state and 14 from read state)
const WRITE_ACTIVE = 0b00000000001 << 18
const WRITE_UPDATING = 0b00000000010 << 18
const WRITE_PRIMARY = 0b00000000100 << 18
const WRITE_QUEUED = 0b00000001000 << 18
const WRITE_UNDRAINED = 0b00000010000 << 18
const WRITE_DONE = 0b00000100000 << 18
const WRITE_EMIT_DRAIN = 0b00001000000 << 18
const WRITE_NEXT_TICK = 0b00010000000 << 18
const WRITE_WRITING = 0b00100000000 << 18
const WRITE_FINISHING = 0b01000000000 << 18
const WRITE_CORKED = 0b10000000000 << 18

const WRITE_NOT_ACTIVE = MAX ^ (WRITE_ACTIVE | WRITE_WRITING)
const WRITE_NON_PRIMARY = MAX ^ WRITE_PRIMARY
const WRITE_NOT_FINISHING = MAX ^ (WRITE_ACTIVE | WRITE_FINISHING)
const WRITE_DRAINED = MAX ^ WRITE_UNDRAINED
const WRITE_NOT_QUEUED = MAX ^ WRITE_QUEUED
const WRITE_NOT_NEXT_TICK = MAX ^ WRITE_NEXT_TICK
const WRITE_NOT_UPDATING = MAX ^ WRITE_UPDATING
const WRITE_NOT_CORKED = MAX ^ WRITE_CORKED

// Combined shared state
const ACTIVE = READ_ACTIVE | WRITE_ACTIVE
const NOT_ACTIVE = MAX ^ ACTIVE
const DONE = READ_DONE | WRITE_DONE
const DESTROY_STATUS = DESTROYING | DESTROYED | PREDESTROYING
const OPEN_STATUS = DESTROY_STATUS | OPENING
const AUTO_DESTROY = DESTROY_STATUS | DONE
const NON_PRIMARY = WRITE_NON_PRIMARY & READ_NON_PRIMARY
const ACTIVE_OR_TICKING = WRITE_NEXT_TICK | READ_NEXT_TICK
const TICKING = ACTIVE_OR_TICKING & NOT_ACTIVE
const IS_OPENING = OPEN_STATUS | TICKING

// Combined shared state and read state
const READ_PRIMARY_STATUS = OPEN_STATUS | READ_ENDING | READ_DONE
const READ_STATUS = OPEN_STATUS | READ_DONE | READ_QUEUED
const READ_ENDING_STATUS = OPEN_STATUS | READ_ENDING | READ_QUEUED
const READ_READABLE_STATUS = OPEN_STATUS | READ_EMIT_READABLE | READ_QUEUED | READ_EMITTED_READABLE
const SHOULD_NOT_READ =
  OPEN_STATUS | READ_ACTIVE | READ_ENDING | READ_DONE | READ_NEEDS_PUSH | READ_READ_AHEAD
const READ_BACKPRESSURE_STATUS = DESTROY_STATUS | READ_ENDING | READ_DONE
const READ_UPDATE_SYNC_STATUS = READ_UPDATING | OPEN_STATUS | READ_NEXT_TICK | READ_PRIMARY
const READ_NEXT_TICK_OR_OPENING = READ_NEXT_TICK | OPENING

// Combined write state
const WRITE_PRIMARY_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_DONE
const WRITE_QUEUED_AND_UNDRAINED = WRITE_QUEUED | WRITE_UNDRAINED
const WRITE_QUEUED_AND_ACTIVE = WRITE_QUEUED | WRITE_ACTIVE
const WRITE_DRAIN_STATUS = WRITE_QUEUED | WRITE_UNDRAINED | OPEN_STATUS | WRITE_ACTIVE
const WRITE_STATUS = OPEN_STATUS | WRITE_ACTIVE | WRITE_QUEUED | WRITE_CORKED
const WRITE_PRIMARY_AND_ACTIVE = WRITE_PRIMARY | WRITE_ACTIVE
const WRITE_ACTIVE_AND_WRITING = WRITE_ACTIVE | WRITE_WRITING
const WRITE_FINISHING_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_QUEUED_AND_ACTIVE | WRITE_DONE
const WRITE_BACKPRESSURE_STATUS = WRITE_UNDRAINED | DESTROY_STATUS | WRITE_FINISHING | WRITE_DONE
const WRITE_UPDATE_SYNC_STATUS = WRITE_UPDATING | OPEN_STATUS | WRITE_NEXT_TICK | WRITE_PRIMARY
const WRITE_DROP_DATA = WRITE_FINISHING | WRITE_DONE | DESTROY_STATUS

const asyncIterator = Symbol.asyncIterator || Symbol('asyncIterator')

class WritableState {
  constructor(
    stream,
    { highWaterMark = 16384, map = null, mapWritable, byteLength, byteLengthWritable } = {}
  ) {
    this.stream = stream
    this.queue = new FIFO()
    this.highWaterMark = highWaterMark
    this.buffered = 0
    this.error = null
    this.pipeline = null
    this.drains = null // if we add more seldomly used helpers we might them into a subobject so its a single ptr
    this.byteLength = byteLengthWritable || byteLength || defaultByteLength
    this.map = mapWritable || map
    this.afterWrite = afterWrite.bind(this)
    this.afterUpdateNextTick = updateWriteNT.bind(this)
  }

  get ending() {
    return (this.stream._duplexState & WRITE_FINISHING) !== 0
  }

  get ended() {
    return (this.stream._duplexState & WRITE_DONE) !== 0
  }

  push(data) {
    if ((this.stream._duplexState & WRITE_DROP_DATA) !== 0) return false
    if (this.map !== null) data = this.map(data)

    this.buffered += this.byteLength(data)
    this.queue.push(data)

    if (this.buffered < this.highWaterMark) {
      this.stream._duplexState |= WRITE_QUEUED
      return true
    }

    this.stream._duplexState |= WRITE_QUEUED_AND_UNDRAINED
    return false
  }

  shift() {
    const data = this.queue.shift()

    this.buffered -= this.byteLength(data)
    if (this.buffered === 0) this.stream._duplexState &= WRITE_NOT_QUEUED

    return data
  }

  end(data) {
    if (typeof data === 'function') {
      this.stream.once('finish', data)
    } else if (data !== undefined && data !== null) {
      this.push(data)
    }

    this.stream._duplexState = (this.stream._duplexState | WRITE_FINISHING) & WRITE_NON_PRIMARY
  }

  autoBatch(data, cb) {
    const buffer = []
    const stream = this.stream

    buffer.push(data)
    while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED_AND_ACTIVE) {
      buffer.push(stream._writableState.shift())
    }

    if ((stream._duplexState & OPEN_STATUS) !== 0) return cb(null)
    stream._writev(buffer, cb)
  }

  update() {
    const stream = this.stream

    stream._duplexState |= WRITE_UPDATING

    do {
      while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED) {
        const data = this.shift()
        stream._duplexState |= WRITE_ACTIVE_AND_WRITING
        stream._write(data, this.afterWrite)
      }

      if ((stream._duplexState & WRITE_PRIMARY_AND_ACTIVE) === 0) this.updateNonPrimary()
    } while (this.continueUpdate() === true)

    stream._duplexState &= WRITE_NOT_UPDATING
  }

  updateNonPrimary() {
    const stream = this.stream

    if ((stream._duplexState & WRITE_FINISHING_STATUS) === WRITE_FINISHING) {
      stream._duplexState = stream._duplexState | WRITE_ACTIVE
      stream._final(afterFinal.bind(this))
      return
    }

    if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
      if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
        stream._duplexState |= ACTIVE
        stream._destroy(afterDestroy.bind(this))
      }
      return
    }

    if ((stream._duplexState & IS_OPENING) === OPENING) {
      stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING
      stream._open(afterOpen.bind(this))
    }
  }

  continueUpdate() {
    if ((this.stream._duplexState & WRITE_NEXT_TICK) === 0) return false
    this.stream._duplexState &= WRITE_NOT_NEXT_TICK
    return true
  }

  updateCallback() {
    if ((this.stream._duplexState & WRITE_UPDATE_SYNC_STATUS) === WRITE_PRIMARY) {
      this.update()
    } else {
      this.updateNextTick()
    }
  }

  updateNextTick() {
    if ((this.stream._duplexState & WRITE_NEXT_TICK) !== 0) return
    this.stream._duplexState |= WRITE_NEXT_TICK
    if ((this.stream._duplexState & WRITE_UPDATING) === 0) qmt(this.afterUpdateNextTick)
  }
}

class ReadableState {
  constructor(
    stream,
    { highWaterMark = 16384, map = null, mapReadable, byteLength, byteLengthReadable } = {}
  ) {
    this.stream = stream
    this.queue = new FIFO()
    this.highWaterMark = highWaterMark === 0 ? 1 : highWaterMark
    this.buffered = 0
    this.readAhead = highWaterMark > 0
    this.error = null
    this.pipeline = null
    this.byteLength = byteLengthReadable || byteLength || defaultByteLength
    this.map = mapReadable || map
    this.pipeTo = null
    this.afterRead = afterRead.bind(this)
    this.afterUpdateNextTick = updateReadNT.bind(this)
  }

  get ending() {
    return (this.stream._duplexState & READ_ENDING) !== 0
  }

  get ended() {
    return (this.stream._duplexState & READ_DONE) !== 0
  }

  pipe(pipeTo, cb) {
    if (this.pipeTo !== null) throw StreamError.BAD_ARGUMENT('Can only pipe to one destination')
    if (typeof cb !== 'function') cb = null

    this.stream._duplexState |= READ_PIPE_DRAINED
    this.pipeTo = pipeTo
    this.pipeline = new Pipeline(this.stream, pipeTo, cb)

    if (cb) this.stream.on('error', noop) // We already error handle this so supress crashes

    if (isStreamx(pipeTo)) {
      pipeTo._writableState.pipeline = this.pipeline
      if (cb) pipeTo.on('error', noop) // We already error handle this so supress crashes
      pipeTo.on('finish', this.pipeline.finished.bind(this.pipeline)) // TODO: just call finished from pipeTo itself
    } else {
      const onerror = this.pipeline.done.bind(this.pipeline, pipeTo)
      const onclose = this.pipeline.done.bind(this.pipeline, pipeTo, null) // onclose has a weird bool arg
      pipeTo.on('error', onerror)
      pipeTo.on('close', onclose)
      pipeTo.on('finish', this.pipeline.finished.bind(this.pipeline))
    }

    pipeTo.on('drain', afterDrain.bind(this))
    this.stream.emit('piping', pipeTo)
    pipeTo.emit('pipe', this.stream)
  }

  push(data) {
    const stream = this.stream

    if (data === null) {
      this.highWaterMark = 0
      stream._duplexState = (stream._duplexState | READ_ENDING) & READ_NON_PRIMARY_AND_PUSHED
      return false
    }

    if (this.map !== null) {
      data = this.map(data)
      if (data === null) {
        stream._duplexState &= READ_PUSHED
        return this.buffered < this.highWaterMark
      }
    }

    this.buffered += this.byteLength(data)
    this.queue.push(data)

    stream._duplexState = (stream._duplexState | READ_QUEUED) & READ_PUSHED

    return this.buffered < this.highWaterMark
  }

  shift() {
    const data = this.queue.shift()

    this.buffered -= this.byteLength(data)
    if (this.buffered === 0) {
      this.stream._duplexState &= READ_NOT_QUEUED
    }

    return data
  }

  unshift(data) {
    const pending = [this.map !== null ? this.map(data) : data]
    while (this.buffered > 0) pending.push(this.shift())

    for (let i = 0; i < pending.length - 1; i++) {
      const data = pending[i]
      this.buffered += this.byteLength(data)
      this.queue.push(data)
    }

    this.push(pending[pending.length - 1])
  }

  read() {
    const stream = this.stream

    if ((stream._duplexState & READ_STATUS) === READ_QUEUED) {
      const data = this.shift()

      if (this.pipeTo !== null && this.pipeTo.write(data) === false) {
        stream._duplexState &= READ_PIPE_NOT_DRAINED
      }

      if ((stream._duplexState & READ_EMIT_DATA) !== 0) {
        stream.emit('data', data)
      }

      return data
    }

    if (this.readAhead === false) {
      stream._duplexState |= READ_READ_AHEAD
      this.updateNextTick()
    }

    return null
  }

  drain() {
    const stream = this.stream

    while (
      (stream._duplexState & READ_STATUS) === READ_QUEUED &&
      (stream._duplexState & READ_FLOWING) !== 0
    ) {
      const data = this.shift()

      if (this.pipeTo !== null && this.pipeTo.write(data) === false) {
        stream._duplexState &= READ_PIPE_NOT_DRAINED
      }

      if ((stream._duplexState & READ_EMIT_DATA) !== 0) {
        stream.emit('data', data)
      }
    }
  }

  update() {
    const stream = this.stream

    stream._duplexState |= READ_UPDATING

    do {
      this.drain()

      while (
        this.buffered < this.highWaterMark &&
        (stream._duplexState & SHOULD_NOT_READ) === READ_READ_AHEAD
      ) {
        stream._duplexState |= READ_ACTIVE_AND_NEEDS_PUSH
        stream._read(this.afterRead)
        this.drain()
      }

      if ((stream._duplexState & READ_READABLE_STATUS) === READ_EMIT_READABLE_AND_QUEUED) {
        stream._duplexState |= READ_EMITTED_READABLE
        stream.emit('readable')
      }

      if ((stream._duplexState & READ_PRIMARY_AND_ACTIVE) === 0) {
        this.updateNonPrimary()
      }
    } while (this.continueUpdate() === true)

    stream._duplexState &= READ_NOT_UPDATING
  }

  updateNonPrimary() {
    const stream = this.stream

    if ((stream._duplexState & READ_ENDING_STATUS) === READ_ENDING) {
      stream._duplexState = (stream._duplexState | READ_DONE) & READ_NOT_ENDING
      stream.emit('end')

      if ((stream._duplexState & AUTO_DESTROY) === DONE) {
        stream._duplexState |= DESTROYING
      }

      if (this.pipeTo !== null) {
        this.pipeTo.end()
      }
    }

    if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
      if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
        stream._duplexState |= ACTIVE
        stream._destroy(afterDestroy.bind(this))
      }
      return
    }

    if ((stream._duplexState & IS_OPENING) === OPENING) {
      stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING
      stream._open(afterOpen.bind(this))
    }
  }

  continueUpdate() {
    if ((this.stream._duplexState & READ_NEXT_TICK) === 0) return false
    this.stream._duplexState &= READ_NOT_NEXT_TICK
    return true
  }

  updateCallback() {
    if ((this.stream._duplexState & READ_UPDATE_SYNC_STATUS) === READ_PRIMARY) {
      this.update()
    } else {
      this.updateNextTick()
    }
  }

  updateNextTickIfOpen() {
    if ((this.stream._duplexState & READ_NEXT_TICK_OR_OPENING) !== 0) return
    this.stream._duplexState |= READ_NEXT_TICK
    if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick)
  }

  updateNextTick() {
    if ((this.stream._duplexState & READ_NEXT_TICK) !== 0) return
    this.stream._duplexState |= READ_NEXT_TICK
    if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick)
  }
}

class TransformState {
  constructor(stream) {
    this.data = null
    this.afterTransform = afterTransform.bind(stream)
    this.afterFinal = null
  }
}

class Pipeline {
  constructor(src, dst, cb) {
    this.from = src
    this.to = dst
    this.afterPipe = cb
    this.error = null
    this.pipeToFinished = false
  }

  finished() {
    this.pipeToFinished = true
  }

  done(stream, err) {
    if (err) this.error = err

    if (stream === this.to) {
      this.to = null

      if (this.from !== null) {
        if ((this.from._duplexState & READ_DONE) === 0 || !this.pipeToFinished) {
          this.from.destroy(this.error || StreamError.PREMATURE_CLOSE('Writable stream closed'))
        }
        return
      }
    }

    if (stream === this.from) {
      this.from = null

      if (this.to !== null) {
        if ((stream._duplexState & READ_DONE) === 0) {
          this.to.destroy(this.error || StreamError.PREMATURE_CLOSE('Readable stream closed'))
        }
        return
      }
    }

    if (this.afterPipe !== null) this.afterPipe(this.error)
    this.to = this.from = this.afterPipe = null
  }
}

function afterDrain() {
  this.stream._duplexState |= READ_PIPE_DRAINED
  this.updateCallback()
}

function afterFinal(err) {
  const stream = this.stream
  if (err) stream.destroy(err)

  if ((stream._duplexState & DESTROY_STATUS) === 0) {
    stream._duplexState |= WRITE_DONE
    stream.emit('finish')
  }

  if ((stream._duplexState & AUTO_DESTROY) === DONE) {
    stream._duplexState |= DESTROYING
  }

  stream._duplexState &= WRITE_NOT_FINISHING

  // no need to wait the extra tick here, so we short circuit that
  if ((stream._duplexState & WRITE_UPDATING) === 0) {
    this.update()
  } else {
    this.updateNextTick()
  }
}

function afterDestroy(err) {
  const stream = this.stream

  if (!err && !StreamError.isStreamDestroyed(this.error)) err = this.error
  if (err) stream.emit('error', err)

  stream._duplexState |= DESTROYED
  stream.emit('close')

  const rs = stream._readableState
  const ws = stream._writableState

  if (rs !== null && rs.pipeline !== null) {
    rs.pipeline.done(stream, err)
  }

  if (ws !== null) {
    while (ws.drains !== null && ws.drains.length > 0) {
      ws.drains.shift().resolve(false)
    }

    if (ws.pipeline !== null) {
      ws.pipeline.done(stream, err)
    }
  }
}

function afterWrite(err) {
  const stream = this.stream

  if (err) stream.destroy(err)
  stream._duplexState &= WRITE_NOT_ACTIVE

  if (this.drains !== null) tickDrains(this.drains)

  if ((stream._duplexState & WRITE_DRAIN_STATUS) === WRITE_UNDRAINED) {
    stream._duplexState &= WRITE_DRAINED

    if ((stream._duplexState & WRITE_EMIT_DRAIN) === WRITE_EMIT_DRAIN) {
      stream.emit('drain')
    }
  }

  this.updateCallback()
}

function afterRead(err) {
  if (err) this.stream.destroy(err)
  this.stream._duplexState &= READ_NOT_ACTIVE

  if (this.readAhead === false && (this.stream._duplexState & READ_RESUMED) === 0) {
    this.stream._duplexState &= READ_NO_READ_AHEAD
  }

  this.updateCallback()
}

function updateReadNT() {
  if ((this.stream._duplexState & READ_UPDATING) === 0) {
    this.stream._duplexState &= READ_NOT_NEXT_TICK
    this.update()
  }
}

function updateWriteNT() {
  if ((this.stream._duplexState & WRITE_UPDATING) === 0) {
    this.stream._duplexState &= WRITE_NOT_NEXT_TICK
    this.update()
  }
}

function tickDrains(drains) {
  for (let i = 0; i < drains.length; i++) {
    // drains.writes are monotonic, so if one is 0 its always the first one
    if (--drains[i].writes === 0) {
      drains.shift().resolve(true)
      i--
    }
  }
}

function afterOpen(err) {
  const stream = this.stream

  if (err) stream.destroy(err)

  if ((stream._duplexState & DESTROYING) === 0) {
    if ((stream._duplexState & READ_PRIMARY_STATUS) === 0) {
      stream._duplexState |= READ_PRIMARY
    }

    if ((stream._duplexState & WRITE_PRIMARY_STATUS) === 0) {
      stream._duplexState |= WRITE_PRIMARY
    }

    stream.emit('open')
  }

  stream._duplexState &= NOT_ACTIVE

  if (stream._writableState !== null) {
    stream._writableState.updateCallback()
  }

  if (stream._readableState !== null) {
    stream._readableState.updateCallback()
  }
}

function afterTransform(err, data) {
  if (data !== undefined && data !== null) this.push(data)
  this._writableState.afterWrite(err)
}

function newListener(name) {
  if (this._readableState !== null) {
    if (name === 'data') {
      this._duplexState |= READ_EMIT_DATA | READ_RESUMED_READ_AHEAD
      this._readableState.updateNextTick()
    }
    if (name === 'readable') {
      this._duplexState |= READ_EMIT_READABLE
      this._readableState.updateNextTick()
    }
  }

  if (this._writableState !== null) {
    if (name === 'drain') {
      this._duplexState |= WRITE_EMIT_DRAIN
      this._writableState.updateNextTick()
    }
  }
}

class Stream extends EventEmitter {
  constructor(opts) {
    super()

    this._duplexState = 0
    this._readableState = null
    this._writableState = null

    if (opts) {
      if (opts.open) this._open = opts.open
      if (opts.destroy) this._destroy = opts.destroy
      if (opts.predestroy) this._predestroy = opts.predestroy
      if (opts.signal) opts.signal.addEventListener('abort', abort.bind(this))
    }

    this.on('newListener', newListener)
  }

  _open(cb) {
    cb(null)
  }

  _destroy(cb) {
    cb(null)
  }

  _predestroy() {
    // does nothing
  }

  get readable() {
    return this._readableState !== null ? true : undefined
  }

  get writable() {
    return this._writableState !== null ? true : undefined
  }

  get destroyed() {
    return (this._duplexState & DESTROYED) !== 0
  }

  get destroying() {
    return (this._duplexState & DESTROY_STATUS) !== 0
  }

  destroy(err) {
    if ((this._duplexState & DESTROY_STATUS) === 0) {
      if (!err) err = StreamError.STREAM_DESTROYED()
      this._duplexState = (this._duplexState | DESTROYING) & NON_PRIMARY

      if (this._readableState !== null) {
        this._readableState.highWaterMark = 0
        this._readableState.error = err
      }

      if (this._writableState !== null) {
        this._writableState.highWaterMark = 0
        this._writableState.error = err
      }

      this._duplexState |= PREDESTROYING
      this._predestroy()
      this._duplexState &= NOT_PREDESTROYING

      if (this._readableState !== null) {
        this._readableState.updateNextTick()
      }

      if (this._writableState !== null) {
        this._writableState.updateNextTick()
      }
    }
  }
}

class Readable extends Stream {
  constructor(opts) {
    super(opts)

    this._duplexState |= OPENING | WRITE_DONE | READ_READ_AHEAD
    this._readableState = new ReadableState(this, opts)

    if (opts) {
      if (this._readableState.readAhead === false) this._duplexState &= READ_NO_READ_AHEAD
      if (opts.read) this._read = opts.read
      if (opts.eagerOpen) this._readableState.updateNextTick()
      if (opts.encoding) this.setEncoding(opts.encoding)
    }
  }

  static deferred(fn, opts) {
    const out = new PassThrough(opts)

    fn()
      .then((src) => {
        if (src === null) return out.end()
        if (out.destroying) return
        pipeline(src, out, noop)
      })
      .catch((err) => out.destroy(err))

    return out
  }

  setEncoding(encoding) {
    const dec = new TextDecoder(encoding)
    const map = this._readableState.map || echo
    this._readableState.map = mapOrSkip
    return this

    function mapOrSkip(data) {
      const next = dec.push(data)
      return next === '' && (data.byteLength !== 0 || dec.remaining > 0) ? null : map(next)
    }
  }

  _read(cb) {
    cb(null)
  }

  pipe(dest, cb) {
    this._readableState.updateNextTick()
    this._readableState.pipe(dest, cb)
    return dest
  }

  read() {
    this._readableState.updateNextTick()
    return this._readableState.read()
  }

  push(data) {
    this._readableState.updateNextTickIfOpen()
    return this._readableState.push(data)
  }

  unshift(data) {
    this._readableState.updateNextTickIfOpen()
    return this._readableState.unshift(data)
  }

  resume() {
    this._duplexState |= READ_RESUMED_READ_AHEAD
    this._readableState.updateNextTick()
    return this
  }

  pause() {
    this._duplexState &=
      this._readableState.readAhead === false ? READ_PAUSED_NO_READ_AHEAD : READ_PAUSED
    return this
  }

  static _fromAsyncIterator(ite, opts) {
    let destroy

    const rs = new Readable({
      ...opts,
      read(cb) {
        ite.next().then(push).then(cb.bind(null, null)).catch(cb)
      },
      predestroy() {
        destroy = ite.return()
      },
      destroy(cb) {
        if (!destroy) return cb(null)
        destroy.then(cb.bind(null, null)).catch(cb)
      }
    })

    return rs

    function push(data) {
      if (data.done) rs.push(null)
      else rs.push(data.value)
    }
  }

  static from(data, opts) {
    if (isReadStreamx(data)) return data
    if (data[asyncIterator]) return this._fromAsyncIterator(data[asyncIterator](), opts)
    if (!Array.isArray(data)) data = data === undefined ? [] : [data]

    let i = 0
    return new Readable({
      ...opts,
      read(cb) {
        this.push(i === data.length ? null : data[i++])
        cb(null)
      }
    })
  }

  static isBackpressured(rs) {
    return (
      (rs._duplexState & READ_BACKPRESSURE_STATUS) !== 0 ||
      rs._readableState.buffered >= rs._readableState.highWaterMark
    )
  }

  static isPaused(rs) {
    return (rs._duplexState & READ_RESUMED) === 0
  }

  [asyncIterator]() {
    const stream = this

    let error = null
    let promiseResolve = null
    let promiseReject = null

    this.on('error', (err) => {
      error = err
    })
    this.on('readable', onreadable)
    this.on('close', onclose)

    return {
      [asyncIterator]() {
        return this
      },
      next() {
        return new Promise(function (resolve, reject) {
          promiseResolve = resolve
          promiseReject = reject
          const data = stream.read()
          if (data !== null) ondata(data)
          else if ((stream._duplexState & DESTROYED) !== 0) ondata(null)
        })
      },
      return() {
        return destroy(null)
      },
      throw(err) {
        return destroy(err)
      }
    }

    function onreadable() {
      if (promiseResolve !== null) ondata(stream.read())
    }

    function onclose() {
      if (promiseResolve !== null) ondata(null)
    }

    function ondata(data) {
      if (promiseReject === null) return
      if (error) {
        promiseReject(error)
      } else if (data === null && (stream._duplexState & READ_DONE) === 0) {
        promiseReject(StreamError.STREAM_DESTROYED())
      } else {
        promiseResolve({ value: data, done: data === null })
      }
      promiseReject = promiseResolve = null
    }

    function destroy(err) {
      stream.destroy(err)
      return new Promise((resolve, reject) => {
        if (stream._duplexState & DESTROYED) return resolve({ value: undefined, done: true })
        stream.once('close', function () {
          if (err) reject(err)
          else resolve({ value: undefined, done: true })
        })
      })
    }
  }
}

class Writable extends Stream {
  constructor(opts) {
    super(opts)

    this._duplexState |= OPENING | READ_DONE
    this._writableState = new WritableState(this, opts)

    if (opts) {
      if (opts.writev) this._writev = opts.writev
      if (opts.write) this._write = opts.write
      if (opts.final) this._final = opts.final
      if (opts.eagerOpen) this._writableState.updateNextTick()
    }
  }

  cork() {
    this._duplexState |= WRITE_CORKED
  }

  uncork() {
    this._duplexState &= WRITE_NOT_CORKED
    this._writableState.updateNextTick()
  }

  _writev(batch, cb) {
    cb(null)
  }

  _write(data, cb) {
    this._writableState.autoBatch(data, cb)
  }

  _final(cb) {
    cb(null)
  }

  static isBackpressured(ws) {
    return (ws._duplexState & WRITE_BACKPRESSURE_STATUS) !== 0
  }

  static drained(ws) {
    if (ws.destroyed) return Promise.resolve(false)

    const state = ws._writableState
    const pending = isWritev(ws) ? Math.min(1, state.queue.length) : state.queue.length
    const writes = pending + (ws._duplexState & WRITE_WRITING ? 1 : 0)
    if (writes === 0) return Promise.resolve(true)

    if (state.drains === null) state.drains = []
    return new Promise((resolve) => {
      state.drains.push({ writes, resolve })
    })
  }

  write(data) {
    this._writableState.updateNextTick()
    return this._writableState.push(data)
  }

  end(data) {
    this._writableState.updateNextTick()
    this._writableState.end(data)
    return this
  }
}

class Duplex extends Readable {
  // and Writable
  constructor(opts) {
    super(opts)

    this._duplexState = OPENING | (this._duplexState & READ_READ_AHEAD)
    this._writableState = new WritableState(this, opts)

    if (opts) {
      if (opts.writev) this._writev = opts.writev
      if (opts.write) this._write = opts.write
      if (opts.final) this._final = opts.final
    }
  }

  cork() {
    this._duplexState |= WRITE_CORKED
  }

  uncork() {
    this._duplexState &= WRITE_NOT_CORKED
    this._writableState.updateNextTick()
  }

  _writev(batch, cb) {
    cb(null)
  }

  _write(data, cb) {
    this._writableState.autoBatch(data, cb)
  }

  _final(cb) {
    cb(null)
  }

  write(data) {
    this._writableState.updateNextTick()
    return this._writableState.push(data)
  }

  end(data) {
    this._writableState.updateNextTick()
    this._writableState.end(data)
    return this
  }
}

class Transform extends Duplex {
  constructor(opts) {
    super(opts)
    this._transformState = new TransformState(this)

    if (opts) {
      if (opts.transform) this._transform = opts.transform
      if (opts.flush) this._flush = opts.flush
    }
  }

  _write(data, cb) {
    if (this._readableState.buffered >= this._readableState.highWaterMark) {
      this._transformState.data = data
    } else {
      this._transform(data, this._transformState.afterTransform)
    }
  }

  _read(cb) {
    if (this._transformState.data !== null) {
      const data = this._transformState.data
      this._transformState.data = null
      cb(null)
      this._transform(data, this._transformState.afterTransform)
    } else {
      cb(null)
    }
  }

  destroy(err) {
    super.destroy(err)
    if (this._transformState.data !== null) {
      this._transformState.data = null
      this._transformState.afterTransform()
    }
  }

  _transform(data, cb) {
    cb(null, data)
  }

  _flush(cb) {
    cb(null)
  }

  _final(cb) {
    this._transformState.afterFinal = cb
    this._flush(transformAfterFlush.bind(this))
  }
}

class PassThrough extends Transform {}

function transformAfterFlush(err, data) {
  const cb = this._transformState.afterFinal
  if (err) return cb(err)

  if (data !== null && data !== undefined) this.push(data)
  this.push(null)
  cb(null)
}

function pipelinePromise(...streams) {
  return new Promise((resolve, reject) => {
    return pipeline(...streams, (err) => {
      if (err) return reject(err)
      resolve()
    })
  })
}

function pipeline(stream, ...streams) {
  const all = Array.isArray(stream) ? [...stream, ...streams] : [stream, ...streams]
  const done = all.length && typeof all[all.length - 1] === 'function' ? all.pop() : null

  if (all.length < 2) throw StreamError.BAD_ARGUMENT('Pipeline requires at least 2 streams')

  let src = all[0]
  let dest = null
  let error = null

  for (let i = 1; i < all.length; i++) {
    dest = all[i]

    if (isStreamx(src)) {
      src.pipe(dest, onerror)
    } else {
      errorHandle(src, true, i > 1, onerror)
      src.pipe(dest)
    }

    src = dest
  }

  if (done) {
    let fin = false

    const autoDestroy =
      isStreamx(dest) || !!(dest._writableState && dest._writableState.autoDestroy)

    dest.on('error', (err) => {
      if (error === null) error = err
    })

    dest.on('finish', () => {
      fin = true
      if (!autoDestroy) done(error)
    })

    if (autoDestroy) {
      dest.on('close', () => done(error || (fin ? null : StreamError.PREMATURE_CLOSE())))
    }
  }

  return dest

  function errorHandle(s, rd, wr, onerror) {
    s.on('error', onerror)
    s.on('close', onclose)

    function onclose() {
      if (rd && s._readableState && !s._readableState.ended) {
        return onerror(StreamError.PREMATURE_CLOSE())
      }
      if (wr && s._writableState && !s._writableState.ended) {
        return onerror(StreamError.PREMATURE_CLOSE())
      }
    }
  }

  function onerror(err) {
    if (!err || error) return
    error = err

    for (const s of all) {
      s.destroy(err)
    }
  }
}

function echo(s) {
  return s
}

function isStream(stream) {
  return !!stream._readableState || !!stream._writableState
}

function isStreamx(stream) {
  return typeof stream._duplexState === 'number' && isStream(stream)
}

function isEnding(stream) {
  return !!stream._readableState && stream._readableState.ending
}

function isEnded(stream) {
  return !!stream._readableState && stream._readableState.ended
}

function isFinishing(stream) {
  return !!stream._writableState && stream._writableState.ending
}

function isFinished(stream) {
  return !!stream._writableState && stream._writableState.ended
}

function getStreamError(stream, opts = {}) {
  const err =
    (stream._readableState && stream._readableState.error) ||
    (stream._writableState && stream._writableState.error)

  // avoid implicit errors by default
  return !opts.all && StreamError.isStreamDestroyed(err) ? null : err
}

function isReadStreamx(stream) {
  return isStreamx(stream) && stream.readable
}

function isDisturbed(stream) {
  return (
    (stream._duplexState & OPENING) !== OPENING ||
    (stream._duplexState & DESTROYING) === DESTROYING ||
    (stream._duplexState & ACTIVE_OR_TICKING) !== 0
  )
}

function isTypedArray(data) {
  return typeof data === 'object' && data !== null && typeof data.byteLength === 'number'
}

function defaultByteLength(data) {
  return isTypedArray(data) ? data.byteLength : 1024
}

function noop() {}

function abort() {
  this.destroy(StreamError.ABORTED())
}

function isWritev(s) {
  return s._writev !== Writable.prototype._writev && s._writev !== Duplex.prototype._writev
}

module.exports = {
  pipeline,
  pipelinePromise,
  isStream,
  isStreamx,
  isEnding,
  isEnded,
  isFinishing,
  isFinished,
  isDisturbed,
  getStreamError,
  Stream,
  Writable,
  Readable,
  Duplex,
  Transform,
  // Export PassThrough for compatibility with Node.js core's stream module
  PassThrough
}
module.exports = class StreamError extends Error {
  constructor(msg, code, fn = StreamError) {
    super(msg)

    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  static isStreamDestroyed(err) {
    return err && err.code === 'STREAM_DESTROYED'
  }

  static isPrematureClose(err) {
    return err && err.code === 'PREMATURE_CLOSE'
  }

  static isAborted(err) {
    return err && err.code === 'ABORTED'
  }

  static isBadArgument(err) {
    return err && err.code === 'BAD_ARGUMENT'
  }

  get name() {
    return 'StreamError'
  }

  static STREAM_DESTROYED() {
    return new StreamError('Stream was destroyed', 'STREAM_DESTROYED', StreamError.STREAM_DESTROYED)
  }

  static PREMATURE_CLOSE(msg = 'Premature close') {
    return new StreamError(msg, 'PREMATURE_CLOSE', StreamError.PREMATURE_CLOSE)
  }

  static ABORTED() {
    return new StreamError('Stream aborted', 'ABORTED', StreamError.ABORTED)
  }

  static BAD_ARGUMENT(msg = 'Bad argument') {
    return new StreamError(msg, 'BAD_ARGUMENT', StreamError.BAD_ARGUMENT)
  }
}
{
  "name": "streamx",
  "version": "2.28.0",
  "description": "An iteration of the Node.js core streams with a series of improvements",
  "main": "index.js",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./errors": {
      "types": "./lib/errors.d.ts",
      "default": "./lib/errors"
    }
  },
  "dependencies": {
    "events-universal": "^1.0.0",
    "fast-fifo": "^1.3.2",
    "text-decoder": "^1.1.0"
  },
  "devDependencies": {
    "b4a": "^1.6.6",
    "brittle": "^3.1.1",
    "end-of-stream": "^1.4.4",
    "lunte": "^1.8.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "runtime.d.ts",
    "lib"
  ],
  "scripts": {
    "format": "prettier . --write",
    "test": "brittle test/all.js && brittle-bare test/all.js",
    "lint": "prettier . --check && lunte"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/streamx.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/streamx/issues"
  },
  "homepage": "https://github.com/mafintosh/streamx"
}
const { Readable } = require('streamx')

module.exports = function (s, forks = 2) {
  const streams = new Array(forks)
  const status = new Array(forks).fill(true)

  let ended = false

  for (let i = 0; i < forks; i++) {
    streams[i] = new Readable({
      read (cb) {
        const check = !status[i]
        status[i] = true
        if (check && allReadable()) s.resume()
        cb(null)
      }
    })
  }

  s.on('end', function () {
    ended = true
    for (const stream of streams) stream.push(null)
  })

  s.on('error', function (err) {
    for (const stream of streams) stream.destroy(err)
  })

  s.on('close', function () {
    if (ended) return
    for (const stream of streams) stream.destroy()
  })

  s.on('data', function (data) {
    let needsPause = false
    for (let i = 0; i < streams.length; i++) {
      if (!(status[i] = streams[i].push(data))) {
        needsPause = true
      }
    }
    if (needsPause) s.pause()
  })

  return streams

  function allReadable () {
    for (let j = 0; j < status.length; j++) {
      if (!status[j]) return false
    }
    return true
  }
}
{
  "name": "teex",
  "version": "1.0.1",
  "description": "Turn a readable stream into multiple readable streamx streams",
  "main": "index.js",
  "dependencies": {
    "streamx": "^2.12.5"
  },
  "devDependencies": {
    "standard": "^14.3.4",
    "tape": "^5.0.1"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/teex.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/teex/issues"
  },
  "homepage": "https://github.com/mafintosh/teex"
}
const PassThroughDecoder = require('./lib/pass-through-decoder')
const UTF8Decoder = require('./lib/utf8-decoder')

module.exports = class TextDecoder {
  constructor(encoding = 'utf8') {
    this.encoding = normalizeEncoding(encoding)

    switch (this.encoding) {
      case 'utf8':
        this.decoder = new UTF8Decoder()
        break
      case 'utf16le':
      case 'base64':
        throw new Error('Unsupported encoding: ' + this.encoding)
      default:
        this.decoder = new PassThroughDecoder(this.encoding)
    }
  }

  get remaining() {
    return this.decoder.remaining
  }

  push(data) {
    if (typeof data === 'string') return data
    return this.decoder.decode(data)
  }

  // For Node.js compatibility
  write(data) {
    return this.push(data)
  }

  end(data) {
    let result = ''
    if (data) result = this.push(data)
    result += this.decoder.flush()
    return result
  }
}

function normalizeEncoding(encoding) {
  encoding = encoding.toLowerCase()

  switch (encoding) {
    case 'utf8':
    case 'utf-8':
      return 'utf8'
    case 'ucs2':
    case 'ucs-2':
    case 'utf16le':
    case 'utf-16le':
      return 'utf16le'
    case 'latin1':
    case 'binary':
      return 'latin1'
    case 'base64':
    case 'ascii':
    case 'hex':
      return encoding
    default:
      throw new Error('Unknown encoding: ' + encoding)
  }
}
const b4a = require('b4a')

module.exports = class PassThroughDecoder {
  constructor(encoding) {
    this.encoding = encoding
  }

  get remaining() {
    return 0
  }

  decode(data) {
    return b4a.toString(data, this.encoding)
  }

  flush() {
    return ''
  }
}
const b4a = require('b4a')

/**
 * https://encoding.spec.whatwg.org/#utf-8-decoder
 */
module.exports = class UTF8Decoder {
  constructor() {
    this._reset()
  }

  get remaining() {
    return this.bytesSeen
  }

  decode(data) {
    if (data.byteLength === 0) return ''

    if (this.bytesNeeded === 0 && trailingIncomplete(data, 0) === 0) {
      this.bytesSeen = trailingBytesSeen(data)
      return b4a.toString(data, 'utf8')
    }

    let result = ''
    let start = 0

    if (this.bytesNeeded > 0) {
      while (start < data.byteLength) {
        const byte = data[start]

        if (byte < this.lowerBoundary || byte > this.upperBoundary) {
          result += '\ufffd'
          this._reset()
          break
        }

        this.lowerBoundary = 0x80
        this.upperBoundary = 0xbf
        this.codePoint = (this.codePoint << 6) | (byte & 0x3f)
        this.bytesSeen++
        start++

        if (this.bytesSeen === this.bytesNeeded) {
          result += String.fromCodePoint(this.codePoint)
          this._reset()
          break
        }
      }

      if (this.bytesNeeded > 0) return result
    }

    const trailing = trailingIncomplete(data, start)
    const end = data.byteLength - trailing

    if (end > start) result += b4a.toString(data, 'utf8', start, end)

    for (let i = end; i < data.byteLength; i++) {
      const byte = data[i]

      if (this.bytesNeeded === 0) {
        if (byte <= 0x7f) {
          this.bytesSeen = 0
          result += String.fromCharCode(byte)
        } else if (byte >= 0xc2 && byte <= 0xdf) {
          this.bytesNeeded = 2
          this.bytesSeen = 1
          this.codePoint = byte & 0x1f
        } else if (byte >= 0xe0 && byte <= 0xef) {
          if (byte === 0xe0) this.lowerBoundary = 0xa0
          else if (byte === 0xed) this.upperBoundary = 0x9f
          this.bytesNeeded = 3
          this.bytesSeen = 1
          this.codePoint = byte & 0xf
        } else if (byte >= 0xf0 && byte <= 0xf4) {
          if (byte === 0xf0) this.lowerBoundary = 0x90
          else if (byte === 0xf4) this.upperBoundary = 0x8f
          this.bytesNeeded = 4
          this.bytesSeen = 1
          this.codePoint = byte & 0x7
        } else {
          this.bytesSeen = 1
          result += '\ufffd'
        }

        continue
      }

      if (byte < this.lowerBoundary || byte > this.upperBoundary) {
        result += '\ufffd'
        i--
        this._reset()

        continue
      }

      this.lowerBoundary = 0x80
      this.upperBoundary = 0xbf

      this.codePoint = (this.codePoint << 6) | (byte & 0x3f)
      this.bytesSeen++

      if (this.bytesSeen === this.bytesNeeded) {
        result += String.fromCodePoint(this.codePoint)
        this._reset()
      }
    }

    return result
  }

  flush() {
    const result = this.bytesNeeded > 0 ? '\ufffd' : ''
    this._reset()
    return result
  }

  _reset() {
    this.codePoint = 0
    this.bytesNeeded = 0
    this.bytesSeen = 0
    this.lowerBoundary = 0x80
    this.upperBoundary = 0xbf
  }
}

function trailingIncomplete(data, start) {
  const len = data.byteLength
  if (len <= start) return 0

  const limit = Math.max(start, len - 4)

  let i = len - 1
  while (i > limit && (data[i] & 0xc0) === 0x80) i--

  if (i < start) return 0

  const byte = data[i]

  let needed
  if (byte <= 0x7f) return 0
  if (byte >= 0xc2 && byte <= 0xdf) needed = 2
  else if (byte >= 0xe0 && byte <= 0xef) needed = 3
  else if (byte >= 0xf0 && byte <= 0xf4) needed = 4
  else return 0

  const available = len - i
  return available < needed ? available : 0
}

function trailingBytesSeen(data) {
  const len = data.byteLength
  if (len === 0) return 0

  const last = data[len - 1]

  if (last <= 0x7f) return 0
  if ((last & 0xc0) !== 0x80) return 1

  const limit = Math.max(0, len - 4)

  let i = len - 2
  while (i >= limit && (data[i] & 0xc0) === 0x80) i--

  if (i < 0) return 1

  const first = data[i]

  let needed
  if (first >= 0xc2 && first <= 0xdf) needed = 2
  else if (first >= 0xe0 && first <= 0xef) needed = 3
  else if (first >= 0xf0 && first <= 0xf4) needed = 4
  else return 1

  if (len - i !== needed) return 1

  if (needed >= 3) {
    const second = data[i + 1]
    if (first === 0xe0 && second < 0xa0) return 1
    if (first === 0xed && second > 0x9f) return 1
    if (first === 0xf0 && second < 0x90) return 1
    if (first === 0xf4 && second > 0x8f) return 1
  }

  return 0
}
{
  "name": "text-decoder",
  "version": "1.2.7",
  "description": "Streaming text decoder that preserves multibyte Unicode characters",
  "exports": {
    "./package": "./package.json",
    ".": "./index.js"
  },
  "files": [
    "index.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/text-decoder.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/text-decoder/issues"
  },
  "homepage": "https://github.com/holepunchto/text-decoder#readme",
  "dependencies": {
    "b4a": "^1.6.4"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  }
}
const { runtime, platform, arch, version } =
  typeof Bare !== 'undefined'
    ? {
        runtime: 'bare',
        platform: global.Bare.platform,
        arch: global.Bare.arch,
        version: global.Bare.version
      }
    : typeof process !== 'undefined'
      ? {
          runtime: 'node',
          platform: global.process.platform,
          arch: global.process.arch,
          version: global.process.version
        }
      : typeof Window !== 'undefined'
        ? { runtime: 'browser', platform: 'unknown', arch: 'unknown', version: 'unknown' }
        : { runtime: 'unknown', platform: 'unknown', arch: 'unknown', version: 'unknown' }

exports.runtime = runtime
exports.version = version
exports.platform = platform
exports.arch = arch
exports.isBare = runtime === 'bare'
exports.isBareKit = exports.isBare && typeof BareKit !== 'undefined'
exports.isPear = typeof Pear !== 'undefined'
exports.isNode = runtime === 'node'
exports.isBrowser = runtime === 'browser'
exports.isWindows = platform === 'win32'
exports.isLinux = platform === 'linux'
exports.isMac = platform === 'darwin'
exports.isIOS = platform === 'ios' || platform === 'ios-simulator'
exports.isAndroid = platform === 'android'
exports.isElectron = typeof process !== 'undefined' && !!global.process.versions?.electron
exports.isElectronRenderer = exports.isElectron && global.process.type === 'renderer'
exports.isElectronWorker = exports.isElectron && global.process.type === 'worker'
{
  "name": "which-runtime",
  "version": "1.4.0",
  "description": "Detect if you are in Bare or Node and which os etc",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte .",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/which-runtime.git"
  },
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/which-runtime/issues"
  },
  "homepage": "https://github.com/holepunchto/which-runtime",
  "devDependencies": {
    "brittle": "^3.0.0",
    "lunte": "^1.4.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
{
  "name": "hyper-proto-peer",
  "version": "0.3.123",
  "description": "Self-custody, P2P-native atproto peer \u2014 holds the user's key + content as Hypercores and authors+signs its own repo. The source of truth in the peer/bridge split (Model B); atproto-bridge projects it to bsky.",
  "type": "module",
  "main": "lib/peer.js",
  "bin": {
    "hyper-proto-peer": "index.js"
  },
  "scripts": {
    "test": "bare test/all.js",
    "start": "bare index.js",
    "postinstall": "node scripts/bare-deps.mjs",
    "test:e2e": "bare test/e2e-federation.test.js"
  },
  "pgh": {
    "bin": "hyper-proto-peer",
    "upgrade": "pgh://1dd36bdfa9cb7f7d84adbd07f017e7200f7f90a3a546cd0761fac2a1f8a13e86/hyper-proto-peer",
    "entrypoint": "index.js",
    "type": "daemon",
    "runtime": "bare",
    "autostart": true,
    "depends": [
      "pgh-sidecar"
    ],
    "defaults": {
      "env": {
        "PEER_STORAGE": "${HOME}/.config/hyper-proto-peer/data"
      }
    },
    "readiness": {
      "type": "pidfile",
      "timeoutMs": 30000
    },
    "service": {
      "requiresNetwork": true
    },
    "systemd": {
      "user": true,
      "enable": true,
      "restart": "on-failure"
    }
  },
  "dependencies": {
    "@ipld/dag-cbor": "^9.2.1",
    "atproto-did-peer": "file:../atproto-did-peer",
    "atproto-identity": "file:../atproto-identity",
    "atproto-repo": "file:../atproto-repo",
    "atproto-store": "file:../atproto-store",
    "atproto-room": "file:../atproto-room",
    "autobase": "7.28.1",
    "b4a": "^1.6.0",
    "bare-fetch": "^3.0.1",
    "bare-fs": "^4.7.1",
    "bare-os": "^3.9.1",
    "bare-path": "^3.0.1",
    "bare-process": "^4.2.1",
    "compact-encoding": "^2.16.0",
    "corestore": "^7.10.0",
    "hypercore": "^11.33.1",
    "hypercore-crypto": "^3.0.0",
    "hypercore-storage": "^3.1.2",
    "hyperdb": "^6.7.0",
    "hyperdispatch": "^1.6.0",
    "hyperschema": "^1.21.0",
    "hyperswarm": "^4.17.0",
    "keet-identity-key": "^3.2.0",
    "protomux-rpc": "^1.10.0",
    "protomux-wakeup": "^2.9.0",
    "hyper-svc": "file:../hyper-svc",
    "hyper-overlay": "file:../hyper-overlay"
  },
  "devDependencies": {
    "@hyperswarm/testnet": "^3.1.4",
    "@noble/curves": "^1.6.0",
    "brittle": "^4.0.2"
  }
}
/**
 * hyper-svc — reusable per-app daemon library
 *
 * RPC transports: UDS, HTTP, and Hyperswarm (Protomux channel).
 * Replication: Hyperswarm topic join + corestore/autobase/mux replicate.
 */

export { Service } from './lib/service.js'
export { Client } from './lib/client.js'
export { encodeFrame, FrameDecoder } from './lib/frame.js'
export { attachRpcServer, attachRpcClient } from './lib/transports/swarm-rpc.js'
/**
 * Client — RPC client for hyper-svc daemons.
 *
 * Local-only. Connects via UDS (preferred) or HTTP. Both transports speak the
 * same JSON-RPC-ish protocol; the wire format differs (length-prefixed frames
 * for UDS, POST /rpc/<method> for HTTP) but the call signature is identical.
 *
 * Discovery: try UDS first (if a path is provided and the socket is reachable),
 * fall back to HTTP. Explicit transport selection is also supported.
 *
 * Usage:
 *
 *   const client = await Client.discover({
 *     uds: '/tmp/pear-git.sock',
 *     http: 'http://127.0.0.1:4040'
 *   })
 *
 *   const orgs = await client.call('list-orgs', { limit: 10 })
 *
 *   await client.close()
 */

import http from '#node:http'
import { URL } from '#node:url'
import b4a from 'b4a'
import { stat } from '#node:fs/promises'
import { udsBackend } from './uds-backend.js'
import Hyperswarm from 'hyperswarm'
import Protomux from 'protomux'
import crypto from 'hypercore-crypto'
import { encodeFrame, FrameDecoder } from './frame.js'
import { attachRpcClient } from './transports/swarm-rpc.js'

export class Client {
  /**
   * Discover and connect to a running hyper-svc daemon.
   *
   * @param {object} opts
   * @param {string} [opts.uds] - UDS socket path. Tried first.
   * @param {string} [opts.http] - HTTP base URL (e.g. 'http://127.0.0.1:4040'). Fallback.
   * @param {'uds'|'http'} [opts.prefer] - explicit override
   * @returns {Promise<Client>}
   */
  static async discover (opts = {}) {
    const prefer = opts.prefer

    if (prefer === 'uds') {
      if (!opts.uds) throw new Error('discover({ prefer: "uds" }) requires opts.uds')
      return Client.connectUds(opts.uds)
    }
    if (prefer === 'http') {
      if (!opts.http) throw new Error('discover({ prefer: "http" }) requires opts.http')
      return Client.connectHttp(opts.http)
    }

    // Auto: UDS first if reachable, then HTTP
    if (opts.uds) {
      const reachable = await udsReachable(opts.uds)
      if (reachable) return Client.connectUds(opts.uds)
    }
    if (opts.http) {
      return Client.connectHttp(opts.http)
    }

    const tried = []
    if (opts.uds) tried.push(`uds:${opts.uds}`)
    if (opts.http) tried.push(`http:${opts.http}`)
    throw new Error(`no daemon reachable (tried: ${tried.join(', ') || 'nothing — pass uds and/or http'})`)
  }

  static async connectUds (path) {
    const { backend, name } = await udsBackend(path)
    const sock = backend.createConnection(name)
    await new Promise((resolve, reject) => {
      sock.once('connect', () => {
        sock.removeListener('error', reject)
        resolve()
      })
      sock.once('error', reject)
    })
    return new Client({ kind: 'uds', sock })
  }

  static connectHttp (base) {
    return new Client({ kind: 'http', base: base.replace(/\/+$/, '') })
  }

  /**
   * Connect to a remote daemon via Hyperswarm. Joins the topic derived from
   * `serverKey`, waits for a connection, attaches a Protomux RPC channel, and
   * (when `opts.verify` is given) confirms the peer that answered is the one
   * that was asked for.
   *
   * ⚠ `serverKey` IS NOT AN IDENTITY — IT IS ONLY A RENDEZVOUS ADDRESS.
   *
   * The topic is `hash(serverKey + salt)`, and SwarmTransport.listen() creates
   * its Hyperswarm with NO keyPair, so a server's Noise key is random per
   * process and never equals the `serverKey` clients use to find it. Anything
   * joined to that topic as a server can therefore answer, and there is no
   * cryptographic binding to check `conn.remotePublicKey` against.
   *
   * That is not hypothetical. In a pear-git-v3 fleet, a mirror joins its
   * ORIGIN's topic (the topic travels in the deployment bundle), so it is a
   * server on the exact topic clients use to reach the origin. Measured
   * 2026-08-08: `connectSwarm({serverKey: <tabertron>})` issued ON stortron was
   * answered by STORTRON ITSELF 6 times out of 6. It asked itself for the
   * origin's release index, got its own, and every artifact fetch then failed
   * with "no holder" — a wrong ANSWER, not a transport error, so nothing looked
   * broken. resync-from-origin on the same path hung twice for 300 s.
   *
   * `opts.verify` closes that hole at the application layer, where identity
   * actually lives. It receives a connected Client and returns truthy to accept.
   * Rejected peers are destroyed and the wait continues until `timeout`, so a
   * caller reaches the intended daemon or fails loudly, never silently talks to
   * the wrong one. It is layered as a callback rather than a built-in `status`
   * check because hyper-svc is generic — which handler proves identity is the
   * consumer's business, and this stays compatible with servers of any version.
   *
   * @param {object} opts
   * @param {string|Buffer} opts.serverKey - rendezvous key; derives the topic
   * @param {string} [opts.topicSalt='pear-git-v3'] - salt for topic derivation
   * @param {object} [opts.swarm] - Hyperswarm constructor options (e.g. testnet bootstrap)
   * @param {number} [opts.timeout=30000] - total ms to find an ACCEPTED peer
   * @param {(client: Client) => Promise<boolean>} [opts.verify] - identity gate
   * @returns {Promise<Client>}
   */
  static async connectSwarm (opts = {}) {
    if (!opts.serverKey) throw new Error('connectSwarm requires opts.serverKey')
    const serverKey = typeof opts.serverKey === 'string'
      ? b4a.from(opts.serverKey, 'hex')
      : opts.serverKey
    const salt = opts.topicSalt || 'pear-git-v3'
    const topic = crypto.hash(b4a.concat([serverKey, b4a.from(salt)]))
    const timeout = opts.timeout || 30_000
    const verify = typeof opts.verify === 'function' ? opts.verify : null

    const swarm = new Hyperswarm(opts.swarm || {})
    const discovery = swarm.join(topic, { server: false, client: true })

    let rejected = 0
    let client = null
    try {
      client = await new Promise((resolve, reject) => {
        let settled = false
        // NOTE: onConnection stays attached for the swarm's whole life — it is
        // deliberately NOT removed here. Connections can still arrive after a
        // peer is accepted, and a NoiseSecretStream with no 'error' listener
        // throws on reset, so detaching left later arrivals unguarded and
        // crashed the process at teardown with ECONNRESET. The listener dies
        // with the swarm when the returned Client is closed.
        const finish = (fn, arg) => {
          if (settled) return
          settled = true
          clearTimeout(timer)
          fn(arg)
        }
        const timer = setTimeout(() => {
          finish(reject, new Error('swarm-rpc: connection timeout' +
            (rejected ? ' (' + rejected + ' peer(s) answered but failed verification — ' +
              'the requested serverKey is a topic, not an identity, so other peers on ' +
              'that topic can answer)' : '')))
        }, timeout)

        const onConnection = (c) => {
          // Routine, and load-bearing: a NoiseSecretStream with no 'error'
          // listener throws on ECONNRESET, and this path DESTROYS connections
          // by design (every peer that fails verification, plus any that arrive
          // after one is accepted). Without this the first rejected peer takes
          // the whole process down. SwarmTransport._onConnection takes the same
          // posture server-side.
          c.on('error', () => {})
          if (settled) { try { c.destroy() } catch {} ; return }
          const candidate = new Client({
            kind: 'swarm',
            swarm,
            conn: c,
            rpc: attachRpcClient(Protomux.from(c))
          })
          if (!verify) return finish(resolve, candidate)

          // Verified off the critical path: keep listening while this runs, so a
          // slow or lying peer cannot stall a good one behind it.
          Promise.resolve()
            .then(() => verify(candidate))
            .then((ok) => {
              if (ok) return finish(resolve, candidate)
              rejected++
              try { c.destroy() } catch {}
            })
            .catch(() => {
              rejected++
              try { c.destroy() } catch {}
            })
        }

        swarm.on('connection', onConnection)
        discovery.flushed().catch((err) => finish(reject, err))
      })
    } catch (err) {
      // Destroy the swarm on EVERY failure path. It used to be left running: a
      // Hyperswarm holds the event loop open, so each failed connect leaked one
      // and the process never exited. That is what hung pear-git-v3's
      // basic.test.js when a mirror's origin was unreachable — 123/123 tests
      // passed, then the run never terminated.
      try { await swarm.destroy() } catch {}
      throw err
    }

    return client
  }

  constructor (opts) {
    this._kind = opts.kind
    this._sock = opts.sock || null
    this._base = opts.base || null
    this._swarm = opts.swarm || null
    this._conn = opts.conn || null
    this._rpc = opts.rpc || null
    this._closed = false

    // UDS pending request map (id → {resolve, reject})
    this._pending = new Map()
    this._nextId = 1

    if (this._kind === 'uds') {
      this._decoder = new FrameDecoder((frame) => this._onFrame(frame))
      this._sock.on('data', (chunk) => {
        try {
          this._decoder.push(chunk)
        } catch (err) {
          this._failAll(err)
          this._down()
        }
      })
      // EVENT-DRIVEN disconnect detection (fleet reconciliation contract). When the peer daemon
      // restarts (the common case: an OTA/`pgh app restart` of hpp/pgv3/etc.), the cached client's
      // socket dies. Previously 'close' only `_failAll`'d the pending map but NEVER set `_closed`,
      // and there was no 'end' handler at all — so `client.closed` stayed FALSE and long-lived
      // consumers (favela-web Writer, pgh sidecar lookups) kept handing back a DEAD client, whose
      // calls hang or reject "connection closed" forever with nothing to trigger a reconnect. Mark
      // the client CLOSED on close/end/error so `.closed` is truthy → consumers reconcile (reconnect
      // a fresh Client) on their next call. 'end' is load-bearing under bare-net (allowHalfOpen: on
      // peer-end it fires 'end' but not 'close'), so we destroy to force teardown — same posture as
      // the server-side half-open fix (hyper-svc 0.1.3).
      this._sock.on('close', () => this._down())
      this._sock.on('end', () => this._down())
      this._sock.on('error', () => this._down())
    }
  }

  get kind () { return this._kind }
  get closed () { return this._closed }

  /**
   * Make an RPC call. Throws on transport errors or remote handler errors.
   * @param {string} method
   * @param {any} [params]
   */
  async call (method, params = {}) {
    if (this._closed) throw new Error('client closed')

    if (this._kind === 'uds') return this._callUds(method, params)
    if (this._kind === 'http') return this._callHttp(method, params)
    if (this._kind === 'swarm') return this._rpc.call(method, params)
    throw new Error('unknown client kind: ' + this._kind)
  }

  _callUds (method, params) {
    const id = this._nextId++
    return new Promise((resolve, reject) => {
      this._pending.set(id, { resolve, reject })
      try {
        this._sock.write(encodeFrame({ id, method, params }))
      } catch (err) {
        this._pending.delete(id)
        reject(err)
      }
    })
  }

  _onFrame (frame) {
    if (frame == null || (typeof frame.id !== 'number' && typeof frame.id !== 'string')) {
      // Malformed response, can't match it to a caller
      return
    }
    const pending = this._pending.get(frame.id)
    if (!pending) return
    this._pending.delete(frame.id)

    if (frame.error) {
      pending.reject(new Error(frame.error))
    } else {
      pending.resolve(frame.result)
    }
  }

  _failAll (err) {
    for (const [, pending] of this._pending) pending.reject(err)
    this._pending.clear()
  }

  // The socket died (peer restarted / errored / half-open end). Mark the client CLOSED so any
  // consumer's `.closed` check reconnects, fail every in-flight call, and force teardown. Idempotent.
  _down () {
    if (this._closed) return
    this._closed = true
    this._failAll(new Error('connection closed'))
    if (this._sock) { try { this._sock.destroy() } catch {} }
  }

  async _callHttp (method, params) {
    const url = new URL(`${this._base}/rpc/${encodeURIComponent(method)}`)
    return new Promise((resolve, reject) => {
      const body = JSON.stringify(params)
      const req = http.request({
        method: 'POST',
        hostname: url.hostname,
        port: url.port || 80,
        path: url.pathname + url.search,
        headers: {
          'Content-Type': 'application/json',
          'Content-Length': b4a.byteLength(body)
        }
      }, (res) => {
        const parts = []
        res.on('data', (c) => parts.push(c))
        res.on('end', () => {
          const text = b4a.concat(parts).toString('utf8')
          let parsed
          try {
            parsed = JSON.parse(text)
          } catch {
            return reject(new Error(`bad JSON response (status ${res.statusCode}): ${text.slice(0, 200)}`))
          }
          if (res.statusCode >= 200 && res.statusCode < 300) {
            return resolve(parsed.result)
          }
          return reject(new Error(parsed.error || `HTTP ${res.statusCode}`))
        })
        res.on('error', reject)
      })
      req.on('error', reject)
      req.write(body)
      req.end()
    })
  }

  async close () {
    if (this._closed) return
    this._closed = true
    if (this._sock) {
      this._failAll(new Error('client closed'))
      try { this._sock.destroy() } catch {}
      this._sock = null
    }
    if (this._rpc) {
      try { this._rpc.close() } catch {}
      this._rpc = null
    }
    if (this._conn) {
      try { this._conn.destroy() } catch {}
      this._conn = null
    }
    if (this._swarm) {
      try { await this._swarm.destroy() } catch {}
      this._swarm = null
    }
  }
}

async function udsReachable (path) {
  const { backend, name, abstract } = await udsBackend(path)
  // Pathname sockets: verify the file exists and is actually a socket first.
  // Abstract sockets have no filesystem entry — skip straight to the connect probe.
  if (!abstract) {
    try {
      const s = await stat(path)
      if (!s.isSocket()) return false
    } catch {
      return false
    }
  }
  // Try a real connect — covers stale sockets where the daemon crashed
  return new Promise((resolve) => {
    const sock = backend.createConnection(name)
    sock.once('connect', () => {
      sock.destroy()
      resolve(true)
    })
    sock.once('error', () => {
      sock.destroy()
      resolve(false)
    })
  })
}
/**
 * Length-prefixed JSON framing.
 *
 * Wire format: [4 bytes BE length][JSON payload].
 *
 * One frame = one JSON object. Multiple frames can be pipelined on a single
 * stream — FrameDecoder handles incremental reads where a frame may arrive
 * across multiple data chunks.
 */

import b4a from 'b4a'

const MAX_FRAME = 16 * 1024 * 1024 // 16 MiB hard cap to avoid runaway buffers

export function encodeFrame (obj) {
  const json = JSON.stringify(obj)
  const payload = b4a.from(json, 'utf8')
  if (payload.length > MAX_FRAME) {
    throw new Error(`Frame too large: ${payload.length} > ${MAX_FRAME}`)
  }
  const frame = b4a.alloc(4 + payload.length)
  frame.writeUInt32BE(payload.length, 0)
  payload.copy(frame, 4)
  return frame
}

export class FrameDecoder {
  /**
   * @param {(obj: any) => void} onFrame - called once per complete frame
   */
  constructor (onFrame) {
    if (typeof onFrame !== 'function') throw new Error('onFrame is required')
    this._onFrame = onFrame
    this._buf = b4a.alloc(0)
  }

  /**
   * Feed a chunk into the decoder. Calls onFrame for each complete frame.
   * Throws if a frame exceeds MAX_FRAME or contains invalid JSON.
   */
  push (chunk) {
    this._buf = b4a.concat([this._buf, chunk])

    while (this._buf.length >= 4) {
      const len = this._buf.readUInt32BE(0)
      if (len > MAX_FRAME) {
        throw new Error(`Frame too large: ${len} > ${MAX_FRAME}`)
      }
      if (this._buf.length < 4 + len) break // wait for more bytes

      const payload = this._buf.subarray(4, 4 + len)
      this._buf = this._buf.subarray(4 + len)

      const json = b4a.toString(payload, 'utf8')
      const obj = JSON.parse(json) // throws on bad JSON
      this._onFrame(obj)
    }
  }

  /** Number of bytes currently buffered (waiting for the rest of a frame). */
  get pending () { return this._buf.length }
}
/**
 * Service — reusable per-app daemon library.
 *
 * One instance per app process. Owns:
 *   - Generic RPC handler registry (svc.handle)
 *   - Module mounts (svc.mount) with optional swarm replication
 *   - UDS, HTTP, and Hyperswarm transport instances (whichever the consumer enables)
 *
 * The consumer's corestore is passed in (or one is implied via swarm.corestore).
 * The Service does NOT create or own storage — that's the app's job.
 *
 * Local-only RPC. Peers exchange data via swarm replication, never commands.
 *
 * Usage:
 *
 *   const svc = new Service({
 *     name: 'pear-git',
 *     corestore: store,
 *     uds: '/tmp/pear-git.sock',
 *     http: { port: 4040 },
 *     swarm: { topic: '...32 bytes hex...' }
 *   })
 *
 *   svc.mount('orgs', new HyperOrgs(store, { namespace: 'orgs' }))
 *
 *   svc.handle('list-orgs', async (ctx, params) => {
 *     return svc.modules.orgs.list()
 *   })
 *
 *   await svc.listen()
 */

import process from '#node:process'
import ReadyResource from 'ready-resource'
import { UdsServer } from './transports/uds.js'
import { HttpServer } from './transports/http.js'
import { SwarmTransport } from './transports/swarm.js'

class NoSuchMethodError extends Error {
  constructor (method) {
    super(`unknown method: ${method}`)
    this.code = 'ENOMETHOD'
  }
}

class AnonymousDeniedError extends Error {
  constructor (method) {
    super(`anonymous access denied: ${method}`)
    this.code = 'EDENIED'
    this.status = 403
  }
}

/**
 * Default "is this caller anonymous?" predicate.
 *
 * Deliberately conservative — anything that is not clearly an authenticated
 * caller counts as anonymous. Consumers whose ctx carries richer identity
 * (pear-git-v3 has four distinct shapes) should pass their own via
 * opts.isAnonymous rather than widen this one.
 */
function defaultIsAnonymous (ctx) {
  if (!ctx) return true
  if (ctx.transport === 'uds') return false // local operator holds the socket
  return !ctx.identity
}

export class Service extends ReadyResource {
  /**
   * @param {object} opts
   * @param {string} opts.name - service name (used for default UDS path, logging)
   * @param {object} [opts.corestore] - required if swarm transport is enabled
   * @param {string} [opts.uds] - UDS socket path. Pass null/undefined to disable.
   * @param {object} [opts.http] - HTTP transport options { port, host }. Disable by omitting.
   * @param {object} [opts.swarm] - Swarm options { topic, swarm? }. Disable by omitting.
   */
  constructor (opts = {}) {
    super()
    if (!opts.name) throw new Error('Service requires opts.name')

    this._name = opts.name
    this._corestore = opts.corestore || null
    this._handlers = new Map()
    this._mounts = new Map()

    // Anonymous-dispatch policy (pear-git org #12).
    //
    // Every registered handler used to be callable by anyone, over HTTP and
    // over swarm-rpc, with no allowlist and no auth gate — so each new
    // svc.handle() was silently world-callable, and a daemon behind a public
    // reverse proxy exposed its entire RPC surface to the internet.
    //
    // Default stays 'allow' so the existing consumers (pear-git-v3, hypernote,
    // hyper-social-web, pgh-sidecar) are untouched until they opt in. Under
    // 'deny', a handler must declare `{ anonymous: true }` at registration to
    // be reachable by an unauthenticated caller.
    //
    // Opt-in at REGISTRATION rather than via a separate allowlist table: with
    // ~100 handlers a table drifts out of step with the handler set, whereas a
    // flag cannot. And the drift direction is safe — a handler nobody marked
    // is DENIED, which surfaces as a visible 403 rather than a silent hole.
    this._anonymousPolicy = opts.anonymousPolicy === 'deny' ? 'deny' : 'allow'
    this._isAnonymous = typeof opts.isAnonymous === 'function'
      ? opts.isAnonymous
      : defaultIsAnonymous
    // Called with ({ method, ctx }) whenever a dispatch is refused, so the
    // consumer can record denials alongside its own audit trail.
    this._onDeny = typeof opts.onDeny === 'function' ? opts.onDeny : null
    this._anonymousAllowed = new Set()

    this._udsOpt = opts.uds || null
    this._httpOpt = opts.http || null
    this._swarmOpt = opts.swarm || null

    this._uds = null
    this._http = null
    this._swarm = null

    if (this._swarmOpt && !this._corestore) {
      throw new Error('Service: swarm transport requires opts.corestore')
    }

    // Instantiate transports eagerly so apps can register HTTP routes,
    // grab the UDS path, etc., BEFORE calling listen().
    const dispatch = (method, params, ctx) => this.dispatch(method, params, ctx)

    if (this._udsOpt) {
      this._uds = new UdsServer({ path: this._udsOpt, dispatch })
    }
    if (this._httpOpt) {
      this._http = new HttpServer({
        port: this._httpOpt.port,
        host: this._httpOpt.host,
        prefix: this._httpOpt.prefix,
        ctxFactory: this._httpOpt.ctxFactory,
        dispatch
      })
    }
    if (this._swarmOpt) {
      this._swarm = new SwarmTransport({
        topic: this._swarmOpt.topic,
        corestore: this._corestore,
        mounts: () => this._listMounts(),
        dispatch: this._swarmOpt.rpc !== false ? dispatch : null,
        swarm: this._swarmOpt.swarm,
        server: this._swarmOpt.server,
        client: this._swarmOpt.client
      })
    }
  }

  // ── Properties ──────────────────────────────────────────────

  get name () { return this._name }
  get corestore () { return this._corestore }

  /** Read-only handle to the UDS transport (or null if disabled). */
  get uds () { return this._uds }

  /** Read-only handle to the HTTP transport (or null if disabled). */
  get http () { return this._http }

  /** Read-only handle to the swarm transport (or null if disabled). */
  get swarm () { return this._swarm }

  /**
   * Mounted modules, accessible by name. Use `svc.modules.orgs` after
   * `svc.mount('orgs', orgsInstance)`.
   */
  get modules () {
    // Lazily build a property-style accessor object on top of the map
    if (!this._modulesProxy) {
      const map = this._mounts
      this._modulesProxy = new Proxy({}, {
        get (_target, prop) {
          const m = map.get(prop)
          return m ? m.instance : undefined
        },
        has (_target, prop) {
          return map.has(prop)
        },
        ownKeys () {
          return Array.from(map.keys())
        },
        getOwnPropertyDescriptor (_target, prop) {
          if (map.has(prop)) {
            return { enumerable: true, configurable: true, value: map.get(prop).instance }
          }
        }
      })
    }
    return this._modulesProxy
  }

  /** Map iteration: list mount entries as { name, instance }. */
  _listMounts () {
    const out = []
    for (const [name, m] of this._mounts) out.push({ name, instance: m.instance })
    return out
  }

  // ── Registration ────────────────────────────────────────────

  /**
   * Register an RPC handler. The handler is invoked from any RPC transport
   * with `(ctx, params)` and should return a JSON-serializable result.
   *
   * @param {string} name - method name (e.g. "list-orgs")
   * @param {(ctx: object, params: any) => Promise<any>|any} fn
   */
  handle (name, fn, opts = {}) {
    if (typeof name !== 'string' || !name) throw new Error('handle requires a name')
    if (typeof fn !== 'function') throw new Error('handle requires a function')
    if (this._handlers.has(name)) throw new Error(`handler "${name}" already registered`)
    this._handlers.set(name, fn)
    // `anonymous: true` opts this method IN to unauthenticated dispatch when
    // the service runs anonymousPolicy: 'deny'. Absent = denied, which is the
    // safe default for a handler nobody has classified yet.
    if (opts && opts.anonymous === true) this._anonymousAllowed.add(name)
  }

  /** Is this method callable by an unauthenticated caller? */
  allowsAnonymous (name) { return this._anonymousAllowed.has(name) }

  /** Methods explicitly opted in to anonymous dispatch, sorted. */
  listAnonymous () { return Array.from(this._anonymousAllowed).sort() }

  /** Whether a handler is registered. */
  hasHandler (name) { return this._handlers.has(name) }

  /** List registered handler names. */
  listHandlers () { return Array.from(this._handlers.keys()).sort() }

  /**
   * Mount a module instance. Modules are accessible via `svc.modules.<name>`.
   * If the module exposes a `.base` (Autobase consumer) and the swarm
   * transport is enabled, the base is replicated on every swarm connection.
   *
   * @param {string} name
   * @param {object} instance
   */
  mount (name, instance) {
    if (typeof name !== 'string' || !name) throw new Error('mount requires a name')
    if (!instance) throw new Error('mount requires an instance')
    if (this._mounts.has(name)) throw new Error(`mount "${name}" already registered`)
    this._mounts.set(name, { instance })
  }

  /** Whether a module is mounted. */
  hasMount (name) { return this._mounts.has(name) }

  /** List mounted module names. */
  listMounts () { return Array.from(this._mounts.keys()).sort() }

  // ── Dispatch ────────────────────────────────────────────────

  /**
   * Dispatch a method call to its handler. Used by all RPC transports.
   * Throws NoSuchMethodError (code: 'ENOMETHOD') if the method isn't registered.
   */
  async dispatch (method, params, ctx) {
    const handler = this._handlers.get(method)
    if (!handler) throw new NoSuchMethodError(method)

    // Anonymous gate (#12). Runs for EVERY transport, because the surface was
    // open on all of them — HTTP via a public reverse proxy, and swarm-rpc to
    // any peer that knows the topic.
    //
    // Ordered after the ENOMETHOD check on purpose: an unknown method should
    // still say so, otherwise the gate turns every typo into a 403 and makes
    // the API undebuggable. It leaks only which method names exist, which the
    // handler list already exposes.
    if (this._anonymousPolicy === 'deny' && !this._anonymousAllowed.has(method)) {
      let anon = true
      try {
        anon = this._isAnonymous(ctx)
      } catch {
        anon = true // a predicate that throws must fail CLOSED
      }
      if (anon) {
        if (this._onDeny) {
          try { this._onDeny({ method, ctx, reason: 'anonymous' }) } catch {}
        }
        throw new AnonymousDeniedError(method)
      }
    }

    return handler(ctx || {}, params)
  }

  // ── Lifecycle ───────────────────────────────────────────────

  async _open () {
    if (this._uds) await this._uds.listen()
    if (this._http) await this._http.listen()
    if (this._swarm) await this._swarm.listen()
  }

  /**
   * Alias for `ready()` — feels more natural for a daemon ("start listening").
   */
  async listen () {
    await this.ready()
  }

  async _close () {
    const errors = []
    if (this._swarm) try { await this._swarm.close() } catch (e) { errors.push(e) }
    if (this._http) try { await this._http.close() } catch (e) { errors.push(e) }
    if (this._uds) try { await this._uds.close() } catch (e) { errors.push(e) }
    this._swarm = null
    this._http = null
    this._uds = null
    if (errors.length) {
      const msg = errors.map(e => e.message).join('; ')
      throw new Error('Service close errors: ' + msg)
    }
  }
}
/**
 * HTTP transport for hyper-svc.
 *
 * Local-only RPC. Browsers (or curl, or any HTTP client) on the same machine
 * POST a JSON body to /rpc/<method> and receive a JSON response.
 *
 * Wire protocol:
 *   POST /rpc/<method>
 *   Content-Type: application/json
 *   { ...params... }
 *
 *   →  200 application/json  { result: ... }
 *      400 application/json  { error: ... }   (bad request / handler threw)
 *      404 application/json  { error: 'unknown method' }
 *
 * Other routes are NOT handled by hyper-svc — apps wire their own SSR pages
 * via the underlying http.Server (exposed as `.server` on this class). Any
 * request not matching POST /rpc/<method> falls through to user-registered
 * 'request' listeners or, if none, returns 404.
 */

import http from '#node:http'
import b4a from 'b4a'

export class HttpServer {
  /**
   * @param {object} opts
   * @param {number} [opts.port=0] - 0 = random port
   * @param {string} [opts.host='127.0.0.1'] - bind address (local-only by default)
   * @param {string} [opts.prefix=''] - URL prefix to strip before matching /rpc/* (e.g. '/git')
   * @param {(method: string, params: any, ctx: object) => Promise<any>} opts.dispatch - request handler
   */
  constructor (opts = {}) {
    if (typeof opts.dispatch !== 'function') throw new Error('HttpServer requires opts.dispatch')

    this._port = opts.port || 0
    this._host = opts.host || '127.0.0.1'
    this._dispatch = opts.dispatch
    // Optional URL prefix (e.g. '/git') stripped before matching /rpc/*. Set
    // when the daemon is reverse-proxied OR accessed directly under a path
    // prefix that the browser bakes into outgoing fetch URLs. Without this,
    // direct (non-proxied) hits to `<host>/<prefix>/rpc/*` fall through both
    // hyper-svc's listener (which only matches '/rpc/') and the consumer's
    // listener (which strips the prefix and skips '/rpc/' assuming hyper-svc
    // already handled it) — neither responds and the request hangs.
    this._prefix = normalizePrefix(opts.prefix)
    // Optional consumer-provided ctx builder. Called per /rpc/* request to
    // populate fields like identity from request headers/cookies. Receives
    // (req) and may return either an object or a Promise<object>. The
    // returned fields are merged into the default ctx ({ transport: 'http',
    // identity: null, req, res }).
    this._ctxFactory = typeof opts.ctxFactory === 'function' ? opts.ctxFactory : null
    this._listening = false

    // Create the server eagerly so apps can register routes BEFORE listen().
    // Our /rpc/* listener is installed first so it has first dibs on requests.
    this._server = http.createServer()
    this._server.on('request', (req, res) => this._onRequest(req, res))
  }

  /**
   * Update or set the ctxFactory after construction. Useful when the
   * factory needs references that don't exist at constructor time
   * (e.g. session stores created by the consumer in a later step).
   */
  setCtxFactory (fn) {
    if (fn != null && typeof fn !== 'function') {
      throw new Error('ctxFactory must be a function or null')
    }
    this._ctxFactory = fn
  }

  /** Underlying http.Server. Apps register their own routes here. */
  get server () { return this._server }
  get listening () { return this._listening }
  get port () {
    if (!this._listening || !this._server) return null
    const addr = this._server.address()
    return addr ? addr.port : null
  }
  get host () { return this._host }

  async listen () {
    if (this._listening) return

    await new Promise((resolve, reject) => {
      this._server.once('error', reject)
      this._server.listen(this._port, this._host, () => {
        this._server.removeListener('error', reject)
        resolve()
      })
    })

    this._listening = true
  }

  async _onRequest (req, res) {
    // Compute the path with the configured prefix removed. Don't mutate
    // req.url — consumers' own request listeners may have their own
    // prefix-stripping logic and should see the original.
    let path = req.url
    if (this._prefix && path.startsWith(this._prefix)) {
      const rest = path.slice(this._prefix.length)
      // Only treat as a prefix match when the next char is '/' (or end of
      // URL). Otherwise '/gitfoo' would falsely match prefix '/git'.
      if (rest === '' || rest[0] === '/' || rest[0] === '?') {
        path = rest || '/'
      }
    }

    if (req.method === 'POST' && path.startsWith('/rpc/')) {
      const method = path.slice('/rpc/'.length).split('?')[0]
      let body
      try {
        body = await collectBody(req)
      } catch (err) {
        return jsonError(res, 400, 'failed to read body: ' + err.message)
      }

      let params = {}
      if (body.length > 0) {
        try {
          params = JSON.parse(b4a.toString(body, 'utf8'))
        } catch {
          return jsonError(res, 400, 'request body must be JSON')
        }
      }

      let ctx = {
        transport: 'http',
        identity: null, // anonymous by default — apps populate via ctxFactory
        req,
        res
      }

      if (this._ctxFactory) {
        try {
          const extra = await this._ctxFactory(req)
          if (extra && typeof extra === 'object') {
            ctx = { ...ctx, ...extra }
          }
        } catch (err) {
          return jsonError(res, 500, 'ctxFactory failed: ' + (err.message || String(err)))
        }
      }

      try {
        const result = await this._dispatch(method, params, ctx)
        if (result === undefined) {
          return jsonOk(res, { result: null })
        }
        return jsonOk(res, { result })
      } catch (err) {
        if (err && err.code === 'ENOMETHOD') {
          return jsonError(res, 404, err.message)
        }
        // An anonymous-gate denial is an authorization outcome, not a bad
        // request — surface it as 403 so callers (and the audit trail) can
        // tell "you may not" from "you sent nonsense".
        if (err && err.code === 'EDENIED') {
          return jsonError(res, err.status || 403, err.message)
        }
        return jsonError(res, 400, err.message || String(err))
      }
    }

    // Not an /rpc/ request. App-owned routes live in OTHER 'request'
    // listeners (registered on this._server by the consumer). If at least
    // one other listener is present, leave the response to them — they're
    // responsible for handling and 404-ing as needed.
    //
    // If we're the ONLY 'request' listener, nobody else will handle this,
    // so we 404 it synchronously. Doing this synchronously avoids a race
    // where setImmediate fires before an async user handler can respond.
    if (this._server.listenerCount('request') <= 1) {
      res.writeHead(404, { 'Content-Type': 'text/plain' })
      res.end('Not found')
    }
    // Otherwise: leave the response to the user's listener.
  }

  async close () {
    if (!this._server || !this._listening) {
      this._listening = false
      return
    }
    await new Promise((resolve) => this._server.close(() => resolve()))
    this._listening = false
  }
}

function collectBody (req) {
  return new Promise((resolve, reject) => {
    const parts = []
    req.on('data', (c) => parts.push(c))
    req.on('end', () => resolve(b4a.concat(parts)))
    req.on('error', reject)
  })
}

function jsonOk (res, body) {
  res.writeHead(200, { 'Content-Type': 'application/json' })
  res.end(JSON.stringify(body))
}

function jsonError (res, status, message) {
  res.writeHead(status, { 'Content-Type': 'application/json' })
  res.end(JSON.stringify({ error: message }))
}

function normalizePrefix (p) {
  if (!p || typeof p !== 'string') return ''
  // Strip trailing slashes so '/git/' and '/git' behave identically.
  let s = p.replace(/\/+$/, '')
  // A bare '/' is not a real prefix.
  if (s === '' || s === '/') return ''
  // Require a leading slash so callers can't accidentally pass 'git'.
  if (s[0] !== '/') s = '/' + s
  return s
}
/**
 * Swarm-RPC transport for hyper-svc.
 *
 * Adds a Protomux RPC channel on every Hyperswarm connection. Requests
 * and responses use the same length-prefixed JSON framing as UDS (see
 * frame.js), multiplexed over the Noise-encrypted swarm stream.
 *
 * This transport extends the existing SwarmTransport (replication) with
 * request/response dispatch. A single swarm connection carries:
 *   1. Hypercore/Autobase replication (corestore.replicate)
 *   2. Module mux channels (attachProtocol)
 *   3. RPC frames (this module)
 *
 * Wire protocol over Protomux:
 *   Channel: 'hyper-svc-rpc'
 *   Message type 0 (request):  { id, method, params }
 *   Message type 1 (response): { id, result } | { id, error }
 *
 * Auth: the caller's Noise public key is available on the connection.
 * For pear-git-v3, envelope auth (Phase 2a) is layered on top — the
 * RPC payload itself is a signed envelope, verified by the dispatch
 * handler. The transport just provides the Noise tunnel.
 */

import Protomux from 'protomux'
import c from 'compact-encoding'
import b4a from 'b4a'

const PROTOCOL = 'hyper-svc-rpc'

/**
 * Attach an RPC channel to a Protomux instance (one per swarm connection).
 *
 * Server-side: receives requests, calls dispatch, sends responses.
 *
 * @param {Protomux} mux — the protomux for this connection
 * @param {Function} dispatch — (method, params, ctx) => result
 * @param {object} [opts]
 * @param {Buffer} [opts.remotePublicKey] — peer's Noise pubkey (for ctx)
 * @returns {{ channel, close: () => void }}
 */
export function attachRpcServer (mux, dispatch, opts = {}) {
  const channel = mux.createChannel({
    protocol: PROTOCOL,
    onopen () {},
    onclose () {}
  })

  if (!channel) return null // protocol already claimed on this mux

  const requestType = channel.addMessage({
    encoding: c.json,
    onmessage (msg) {
      handleRequest(msg, channel, responseType, dispatch, opts)
    }
  })

  const responseType = channel.addMessage({
    encoding: c.json,
    onmessage () {} // server doesn't receive responses
  })

  channel.open()

  return { channel, close: () => channel.close() }
}

/**
 * Attach an RPC channel to a Protomux instance (client-side).
 *
 * Client-side: sends requests, receives responses.
 *
 * @param {Protomux} mux
 * @returns {{ call: (method, params) => Promise<any>, close: () => void }}
 */
export function attachRpcClient (mux) {
  let nextId = 1
  const pending = new Map() // id → { resolve, reject }

  const channel = mux.createChannel({
    protocol: PROTOCOL,
    onopen () {},
    onclose () {
      // Reject all pending calls on channel close.
      for (const [id, p] of pending) {
        p.reject(new Error('swarm-rpc channel closed'))
        pending.delete(id)
      }
    }
  })

  if (!channel) throw new Error('swarm-rpc: protocol already claimed')

  const requestType = channel.addMessage({
    encoding: c.json,
    onmessage () {} // client doesn't receive requests
  })

  const responseType = channel.addMessage({
    encoding: c.json,
    onmessage (msg) {
      const p = pending.get(msg.id)
      if (!p) return // stale or unknown id
      pending.delete(msg.id)
      if (msg.error) {
        const err = new Error(msg.error)
        err.code = msg.code || null
        p.reject(err)
      } else {
        p.resolve(msg.result)
      }
    }
  })

  channel.open()

  return {
    call (method, params) {
      return new Promise((resolve, reject) => {
        const id = nextId++
        pending.set(id, { resolve, reject })
        requestType.send({ id, method, params })
      })
    },
    close () {
      channel.close()
    }
  }
}

// --- internals ---

async function handleRequest (msg, channel, responseType, dispatch, opts) {
  const { id, method, params } = msg
  if (!id || !method) {
    responseType.send({ id: id || 0, error: 'invalid request (missing id or method)' })
    return
  }

  const ctx = {
    transport: 'swarm-rpc',
    identity: {
      type: 'swarm',
      remotePublicKey: opts.remotePublicKey
        ? b4a.toString(opts.remotePublicKey, 'hex')
        : null,
      trust: 'network'
    }
  }

  try {
    const result = await dispatch(method, params || {}, ctx)
    responseType.send({ id, result: result !== undefined ? result : null })
  } catch (err) {
    responseType.send({
      id,
      error: err.message || String(err),
      code: err.code || null
    })
  }
}
/**
 * Hyperswarm transport for hyper-svc.
 *
 * Joins a topic, and on every connection:
 *   1. corestore.replicate(conn) — replicates all hypercores in the corestore
 *   2. for each mounted module exposing a `.base` (Autobase consumer), also
 *      base.replicate(conn) — belt-and-suspenders against the autobase
 *      replication gotcha (corestore.replicate alone is unreliable in tests
 *      and we don't want to chase that bug in production)
 *   3. for each mounted module exposing `attachProtocol(mux)` (mux-based
 *      protocols like hyper-overlay), lazily build `Protomux.from(conn)`
 *      once per connection and call attachProtocol on each consumer.
 *      Protomux.from reuses any protomux already attached by corestore/autobase
 *      replication, so channels multiplex cleanly over the same transport.
 *
 * No RPC over swarm today — modules communicate either via replication or
 * via their own mux channels. Adding a new mux-based protocol only requires
 * exposing `attachProtocol(mux)` on the mounted module.
 */

import Hyperswarm from 'hyperswarm'
import Protomux from 'protomux'
import b4a from 'b4a'
import { attachRpcServer } from './swarm-rpc.js'

export class SwarmTransport {
  /**
   * @param {object} opts
   * @param {Buffer|string} opts.topic - 32-byte topic to join (hex string or buffer)
   * @param {object} opts.corestore - corestore to replicate
   * @param {() => Iterable<{ name: string, instance: object }>} opts.mounts - returns the current mount list (called on each connection so late mounts work)
   * @param {Function} [opts.dispatch] - RPC dispatch function. When provided, a swarm-RPC Protomux channel is attached to every connection.
   * @param {object} [opts.swarm] - hyperswarm options (e.g., bootstrap nodes for testnet)
   * @param {boolean} [opts.server=true]
   * @param {boolean} [opts.client=true]
   */
  constructor (opts = {}) {
    if (!opts.topic) throw new Error('SwarmTransport requires opts.topic')
    if (!opts.corestore) throw new Error('SwarmTransport requires opts.corestore')
    if (typeof opts.mounts !== 'function') throw new Error('SwarmTransport requires opts.mounts (function)')

    this._topic = typeof opts.topic === 'string' ? b4a.from(opts.topic, 'hex') : opts.topic
    if (this._topic.length !== 32) throw new Error('topic must be 32 bytes')

    this._corestore = opts.corestore
    this._getMounts = opts.mounts
    this._dispatch = opts.dispatch || null
    this._swarmOpts = opts.swarm || {}
    this._joinAsServer = opts.server !== false
    this._joinAsClient = opts.client !== false

    this._swarm = null
    this._discovery = null
    this._listening = false
    this._connections = new Set()
  }

  get topic () { return this._topic }
  get listening () { return this._listening }
  get swarm () { return this._swarm }
  get connections () { return this._connections.size }

  async listen () {
    if (this._listening) return

    this._swarm = new Hyperswarm(this._swarmOpts)
    this._swarm.on('connection', (conn, info) => this._onConnection(conn, info))

    this._discovery = this._swarm.join(this._topic, {
      server: this._joinAsServer,
      client: this._joinAsClient
    })
    await this._discovery.flushed()
    this._listening = true
  }

  /**
   * Join an ADDITIONAL topic on this same shared swarm (Keet activateRoom
   * pattern — one Hyperswarm, many topics). Used to rendezvous for a
   * specific room (per-org / per-repo autobase) by its discoveryKey, so
   * peers find each other for that room without needing the daemon's
   * identity topic. Replication still rides the single `_onConnection`
   * (corestore.replicate + per-mount replicate). Deduped + idempotent.
   *
   * @param {Buffer|string} topic - 32-byte discoveryKey (hex or buffer)
   * @param {object} [opts] - { server=true, client=true }
   * @returns {object|null} the PeerDiscovery handle (or existing one)
   */
  joinTopic (topic, opts = {}) {
    if (!this._swarm) return null // not listening yet
    const t = typeof topic === 'string' ? b4a.from(topic, 'hex') : topic
    if (!t || t.length !== 32) return null
    const key = b4a.toString(t, 'hex')
    if (!this._extraTopics) this._extraTopics = new Map()
    if (this._extraTopics.has(key)) return this._extraTopics.get(key)
    const { server = true, client = true } = opts
    const disc = this._swarm.join(t, { server, client })
    this._extraTopics.set(key, disc)
    return disc
  }

  /** discoveryKeys of every additional room topic joined via joinTopic. */
  get joinedRoomTopics () {
    return this._extraTopics ? Array.from(this._extraTopics.keys()) : []
  }

  _onConnection (conn, info) {
    this._connections.add(conn)
    conn.on('close', () => this._connections.delete(conn))
    conn.on('error', () => { /* connection errors are routine — ignore */ })

    // Always replicate the corestore. Hypercore handles muxing internally.
    try {
      this._corestore.replicate(conn)
    } catch (err) {
      // Don't crash on replication setup errors — log via stderr
      // eslint-disable-next-line no-console
      console.error('[hyper-svc/swarm] corestore.replicate failed:', err.message)
    }

    // Belt and suspenders: also call base.replicate on every mounted Autobase
    // consumer. This is the documented workaround for the test-time gotcha
    // where corestore.replicate alone doesn't propagate writer cores.
    //
    // In the same pass, wire up mux-based protocols: any mount exposing
    // `attachProtocol(mux)` (hyper-overlay and future consumers) gets attached
    // to a single Protomux per connection. Protomux.from reuses any protomux
    // corestore/autobase replication already set up.
    let mux = null
    for (const { name, instance } of this._getMounts()) {
      if (!instance) continue

      // A mount may expose `replicate(conn)` to replicate its own
      // autobase(s) — required for MULTI-autobase mounts (e.g. per-org
      // HyperOrgs) whose single `.base` getter is undefined or THROWS.
      // Otherwise fall back to the single-autobase `.base.replicate`.
      // The whole access is wrapped: a throwing `.base` getter must
      // never abort the daemon on an incoming connection.
      try {
        if (typeof instance.replicate === 'function') {
          instance.replicate(conn)
        } else {
          const base = instance.base
          if (base && typeof base.replicate === 'function') base.replicate(conn)
        }
      } catch (err) {
        // eslint-disable-next-line no-console
        console.error(`[hyper-svc/swarm] ${name} replicate failed:`, err.message)
      }

      if (typeof instance.attachProtocol === 'function') {
        if (!mux) {
          try {
            mux = Protomux.from(conn)
          } catch (err) {
            // eslint-disable-next-line no-console
            console.error('[hyper-svc/swarm] Protomux.from failed:', err.message)
          }
        }
        if (mux) {
          try {
            instance.attachProtocol(mux)
          } catch (err) {
            // eslint-disable-next-line no-console
            console.error(`[hyper-svc/swarm] ${name}.attachProtocol failed:`, err.message)
          }
        }
      }
    }

    // Swarm-RPC channel — attach only when dispatch is configured.
    // Multiplexes cleanly over the same Noise stream as replication
    // and module protocols above.
    if (this._dispatch) {
      if (!mux) {
        try {
          mux = Protomux.from(conn)
        } catch (err) {
          // eslint-disable-next-line no-console
          console.error('[hyper-svc/swarm] Protomux.from failed (rpc):', err.message)
        }
      }
      if (mux) {
        try {
          attachRpcServer(mux, this._dispatch, {
            remotePublicKey: conn.remotePublicKey || null
          })
        } catch (err) {
          // eslint-disable-next-line no-console
          console.error('[hyper-svc/swarm] attachRpcServer failed:', err.message)
        }
      }
    }
  }

  async close () {
    if (!this._swarm) return
    for (const conn of this._connections) {
      try { conn.destroy() } catch {}
    }
    this._connections.clear()
    try { await this._swarm.destroy() } catch {}
    this._swarm = null
    this._discovery = null
    this._listening = false
  }
}
/**
 * UDS (Unix Domain Socket) transport for hyper-svc.
 *
 * Local-only RPC. Trusts the local user. CLIs on the same machine connect
 * to ~/.local/share/<name>/svc.sock (or wherever the daemon was told to bind)
 * and exchange length-prefixed JSON frames.
 *
 * Wire protocol per connection:
 *   client → server: { id, method, params }
 *   server → client: { id, result }   OR   { id, error }
 *
 * Multiple in-flight requests are matched by id. Server is fully async —
 * a slow handler doesn't block other requests on the same connection.
 */

import process from '#node:process'
import { unlink, stat } from '#node:fs/promises'
import { encodeFrame, FrameDecoder } from '../frame.js'
import { udsBackend, isAbstract } from '../uds-backend.js'

export class UdsServer {
  /**
   * @param {object} opts
   * @param {string} opts.path - filesystem path for the UNIX socket
   * @param {(method: string, params: any, ctx: object) => Promise<any>} opts.dispatch - request handler
   */
  constructor (opts = {}) {
    if (!opts.path) throw new Error('UdsServer requires opts.path')
    if (typeof opts.dispatch !== 'function') throw new Error('UdsServer requires opts.dispatch')

    this._path = opts.path
    this._dispatch = opts.dispatch
    this._server = null
    this._connections = new Set()
    this._listening = false

    // Idle-connection reaper. `allowHalfOpen:false` + the end/error handlers
    // below clean up when a client CLOSES or EXITS. But a caller that opens a
    // connection and then neither closes it nor exits (a long-lived process
    // that forgets Client.close()) leaves the accepted socket ESTAB forever —
    // the OS never delivers an end/close the server can react to. Unbounded,
    // this grew pgh-sidecar to ~348k ESTAB unix sockets / ~22GB (2026-07-05).
    // Sweep and destroy connections idle past _idleTimeout with no request in
    // flight. Request/response callers reset the timer on every frame, so only
    // genuinely dead connections are reaped. Set idleTimeout:0 to disable.
    this._idleTimeout = opts.idleTimeout === undefined ? 120000 : opts.idleTimeout
    this._sweepTimer = null
  }

  get path () { return this._path }
  get listening () { return this._listening }

  async listen () {
    if (this._listening) return

    // Select the transport: #node:net for pathname sockets (unchanged), or
    // bare-abstract-socket for an '@'-prefixed abstract name. `name` is the
    // bind name with the '@' stripped.
    const { backend, name, abstract } = await udsBackend(this._path)

    // Best-effort cleanup of a stale socket FILE (server crashed without
    // unlinking). Abstract sockets have no filesystem entry (the kernel frees
    // the name when the socket closes), so this applies to pathname sockets only.
    if (!abstract) {
      // ONLY remove if it's actually a socket — never touch regular files / dirs.
      try {
        const s = await stat(this._path)
        if (s.isSocket()) {
          // Try to connect first — if a daemon is already running, refuse to clobber.
          const inUse = await this._probe()
          if (inUse) throw new Error(`socket ${this._path} is already in use`)
          await unlink(this._path)
        }
      } catch (err) {
        if (err.code !== 'ENOENT' && err.message.indexOf('already in use') === -1) {
          // stat failed for some reason other than missing — ignore, let listen() fail naturally
        }
        if (err.message && err.message.indexOf('already in use') !== -1) throw err
      }
    }

    // allowHalfOpen:false is CRITICAL. bare-net defaults it to true (unlike
    // Node), which means when a client disconnects the accepted socket never
    // sees 'end' and never releases — the fd AND its 64KB read buffer leak.
    // With false, peer disconnect surfaces as 'end', which _onConnection
    // turns into a destroy() so the socket fully closes. See the fd-leak that
    // grew pgh-sidecar to ~205k open sockets / 14GB RSS (2026-06-09).
    // (bare-abstract-socket honours the same allowHalfOpen:false on accept.)
    this._server = backend.createServer({ allowHalfOpen: false }, (sock) => this._onConnection(sock))

    await new Promise((resolve, reject) => {
      this._server.once('error', reject)
      this._server.listen(name, () => {
        this._server.removeListener('error', reject)
        resolve()
      })
    })

    this._listening = true

    if (this._idleTimeout > 0) {
      const sweepEvery = Math.max(1000, Math.min(30000, Math.floor(this._idleTimeout / 2)))
      this._sweepTimer = setInterval(() => this._reapIdle(), sweepEvery)
      // Don't let the reaper keep the process alive on its own.
      if (this._sweepTimer && typeof this._sweepTimer.unref === 'function') this._sweepTimer.unref()
    }
  }

  // Destroy connections idle past _idleTimeout with no request in flight.
  // destroy() fires 'close', which removes the socket from _connections.
  _reapIdle () {
    const now = Date.now()
    for (const sock of this._connections) {
      if ((sock._inflight || 0) > 0) continue
      if (now - (sock._lastActive || 0) > this._idleTimeout) {
        try { sock.destroy() } catch {}
      }
    }
  }

  async _probe () {
    const { backend, name } = await udsBackend(this._path)
    return new Promise((resolve) => {
      const sock = backend.createConnection(name)
      sock.once('connect', () => {
        sock.destroy()
        resolve(true)
      })
      sock.once('error', () => {
        sock.destroy()
        resolve(false)
      })
    })
  }

  _onConnection (sock) {
    this._connections.add(sock)
    sock._lastActive = Date.now()
    sock._inflight = 0
    sock.on('close', () => this._connections.delete(sock))

    // Peer closed their write side (client finished + disconnected). bare-net
    // does NOT emit 'close' on its own here — we must destroy() to release the
    // fd and drop the socket (and its read buffer) from _connections. Safe even
    // mid-dispatch: a late _handleRequest write is already wrapped in try/catch.
    sock.on('end', () => { try { sock.destroy() } catch {} })

    const decoder = new FrameDecoder((req) => this._handleRequest(sock, req))

    sock.on('data', (chunk) => {
      sock._lastActive = Date.now()
      try {
        decoder.push(chunk)
      } catch (err) {
        // Bad frame — close the connection rather than try to recover
        try { sock.destroy(err) } catch {}
      }
    })

    // Abrupt disconnect (ECONNRESET, or the client process killed / timed out
    // mid-request). bare-net does NOT emit 'close' on its own (see the 'end'
    // note above) — and unlike a clean FIN there is no 'end' either — so we
    // MUST destroy() here to release the fd + 64KB read buffer and drop the
    // socket from _connections. Without this, every abrupt client disconnect
    // leaks a half-open socket (the 0.1.3 'end'-only fix covered clean closes
    // but not this path — the cause of the 6645-socket accumulation seen when
    // a client hammers the UDS with timed-out/killed calls).
    sock.on('error', () => { try { sock.destroy() } catch {} })
  }

  async _handleRequest (sock, req) {
    const id = req && req.id
    if (typeof id !== 'number' && typeof id !== 'string') {
      // Malformed — best effort error response, but the client probably can't match it
      try {
        sock.write(encodeFrame({ id: null, error: 'request missing id' }))
      } catch {}
      return
    }

    const ctx = {
      transport: 'uds',
      identity: { type: 'local', userId: process.env.USER || null, trust: 'local' }
    }

    // Mark in-flight so the idle reaper never destroys a socket mid-dispatch,
    // even if the handler runs longer than _idleTimeout.
    sock._inflight = (sock._inflight || 0) + 1
    try {
      const result = await this._dispatch(req.method, req.params, ctx)
      try {
        sock.write(encodeFrame({ id, result }))
      } catch {}
    } catch (err) {
      try {
        sock.write(encodeFrame({ id, error: err.message || String(err) }))
      } catch {}
    } finally {
      sock._inflight = Math.max(0, (sock._inflight || 1) - 1)
      sock._lastActive = Date.now()
    }
  }

  async close () {
    if (!this._server) return
    if (this._sweepTimer) { clearInterval(this._sweepTimer); this._sweepTimer = null }
    for (const sock of this._connections) {
      try { sock.destroy() } catch {}
    }
    this._connections.clear()
    await new Promise((resolve) => this._server.close(() => resolve()))
    this._server = null
    this._listening = false

    // Clean up the socket file (best-effort). Abstract sockets have no fs entry.
    if (!isAbstract(this._path)) {
      try { await unlink(this._path) } catch {}
    }
  }
}
/**
 * UDS backend selection.
 *
 * A socket "path" beginning with '@' names a Linux ABSTRACT-namespace socket
 * (no filesystem entry) instead of a pathname socket. Abstract sockets are the
 * only UNIX-socket option when SELinux denies the shell domain from creating
 * pathname sockets — e.g. an unrooted Android phone (celltron) running the
 * daemon under proot, where bind(AF_UNIX, "/path.sock") returns EACCES.
 *
 * For every non-'@' path we use #node:net exactly as before — byte-for-byte
 * unchanged behavior. bare-abstract-socket is imported LAZILY (dynamic import,
 * only at the async call sites below) so pathname deployments never load the
 * native addon.
 */

import net from '#node:net'

let _abstract = null

async function loadAbstract () {
  if (_abstract === null) {
    const m = await import('bare-abstract-socket')
    _abstract = m.default || m
  }
  return _abstract
}

// True if `path` names an abstract-namespace socket (leading '@').
export function isAbstract (path) {
  return typeof path === 'string' && path.length > 1 && path[0] === '@'
}

// Resolve the transport backend + the name to bind/connect. The returned
// `backend` exposes net-compatible createServer(opts, onConnection) and
// createConnection(name). For abstract paths the leading '@' is stripped
// (bare-abstract-socket adds the actual leading NUL).
export async function udsBackend (path) {
  if (isAbstract(path)) {
    return { backend: await loadAbstract(), name: path.slice(1), abstract: true }
  }
  return { backend: net, name: path, abstract: false }
}
const { Pull, Push, HEADERBYTES, KEYBYTES, ABYTES } = require('sodium-secretstream')
const sodium = require('sodium-universal')
const crypto = require('hypercore-crypto')
const { Duplex, Writable, getStreamError } = require('streamx')
const b4a = require('b4a')
const Timeout = require('timeout-refresh')
const unslab = require('unslab')
const Bridge = require('./lib/bridge')
const Handshake = require('./lib/handshake')

const IDHEADERBYTES = HEADERBYTES + 32
const [NS_INITIATOR, NS_RESPONDER, NS_SEND] = crypto.namespace('hyperswarm/secret-stream', 3)
const MAX_ATOMIC_WRITE = 256 * 256 * 256 - 1

module.exports = class NoiseSecretStream extends Duplex {
  constructor(isInitiator, rawStream, opts = {}) {
    super({ mapWritable: toBuffer })

    if (typeof isInitiator !== 'boolean') {
      throw new Error('isInitiator should be a boolean')
    }

    this.noiseStream = this
    this.isInitiator = isInitiator
    this.rawStream = null

    this.publicKey = opts.publicKey || null
    this.remotePublicKey = opts.remotePublicKey || null
    this.handshakeHash = null
    this.connected = false
    this.keepAlive = opts.keepAlive || 0
    this.timeout = 0
    this.enableSend = opts.enableSend !== false

    // pointer for upstream to set data here if they want
    this.userData = null

    let openedDone = null
    this.opened = new Promise((resolve) => {
      openedDone = resolve
    })

    this.rawBytesWritten = 0
    this.rawBytesRead = 0

    // metadata used by 'hyperdht'
    this.relay = null
    this.puncher = null

    // unwrapped raw stream
    this._rawStream = null

    // handshake state
    this._handshake = null
    this._handshakePattern = opts.pattern || null
    this._handshakeDone = null

    // message parsing state
    this._state = 0
    this._len = 0
    this._tmp = 1
    this._message = null

    this._openedDone = openedDone
    this._startDone = null
    this._drainDone = null
    this._outgoingPlain = null
    this._outgoingWrapped = null
    this._utp = null
    this._setup = true
    this._ended = 2
    this._encrypt = null
    this._decrypt = null
    this._timeoutTimer = null
    this._keepAliveTimer = null
    this._sendState = null

    if (opts.autoStart !== false) this.start(rawStream, opts)

    // wiggle it to trigger open immediately (TODO add streamx option for this)
    this.resume()
    this.pause()
  }

  static keyPair(seed) {
    return Handshake.keyPair(seed)
  }

  static id(handshakeHash, isInitiator, id) {
    return streamId(handshakeHash, isInitiator, id)
  }

  setTimeout(ms) {
    if (!ms) ms = 0

    this._clearTimeout()
    this.timeout = ms

    if (!ms || this.rawStream === null) return

    this._timeoutTimer = Timeout.once(ms, destroyTimeout, this)
    this._timeoutTimer.unref()
  }

  setKeepAlive(ms) {
    if (!ms) ms = 0

    this._clearKeepAlive()

    this.keepAlive = ms

    if (!ms || this.rawStream === null) return

    this._keepAliveTimer = Timeout.on(ms, sendKeepAlive, this)
    this._keepAliveTimer.unref()
  }

  sendKeepAlive() {
    const empty = this.alloc(0)
    this.write(empty)
  }

  start(rawStream, opts = {}) {
    if (rawStream) {
      this.rawStream = rawStream
      this._rawStream = rawStream
      if (typeof this.rawStream.setContentSize === 'function') {
        this._utp = rawStream
      }
    } else {
      this.rawStream = new Bridge(this)
      this._rawStream = this.rawStream.reverse
    }

    this.rawStream.on('error', this._onrawerror.bind(this))
    this.rawStream.on('close', this._onrawclose.bind(this))

    this._startHandshake(opts.handshake, opts.keyPair || null)
    this._continueOpen(null)

    if (this.destroying) return

    if (opts.data) this._onrawdata(opts.data)
    if (opts.ended) this._onrawend()

    if (this.keepAlive > 0 && this._keepAliveTimer === null) {
      this.setKeepAlive(this.keepAlive)
    }

    if (this.timeout > 0 && this._timeoutTimer === null) {
      this.setTimeout(this.timeout)
    }
  }

  async flush() {
    if ((await this.opened) === false) return false
    if ((await Writable.drained(this)) === false) return false
    if (this.destroying) return false

    if (this.rawStream !== null && this.rawStream.flush) {
      return await this.rawStream.flush()
    }

    return true
  }

  _continueOpen(err) {
    if (err) this.destroy(err)
    if (this._startDone === null) return
    const done = this._startDone
    this._startDone = null
    this._open(done)
  }

  _onkeypairpromise(p) {
    const self = this
    const cont = this._continueOpen.bind(this)

    p.then(onkeypair, cont)

    function onkeypair(kp) {
      self._onkeypair(kp)
      cont(null)
    }
  }

  _onkeypair(keyPair) {
    const pattern = this._handshakePattern || 'XX'
    const remotePublicKey = this.remotePublicKey

    this._handshake = new Handshake(this.isInitiator, keyPair, remotePublicKey, pattern)
    this.publicKey = this._handshake.keyPair.publicKey
  }

  _startHandshake(handshake, keyPair) {
    if (handshake) {
      const { tx, rx, hash, publicKey, remotePublicKey } = handshake
      this._setupSecretStream(tx, rx, hash, publicKey, remotePublicKey)
      return
    }

    if (!keyPair) keyPair = Handshake.keyPair()

    if (typeof keyPair.then === 'function') {
      this._onkeypairpromise(keyPair)
    } else {
      this._onkeypair(keyPair)
    }
  }

  _onrawerror(err) {
    this.destroy(err)
  }

  _onrawclose() {
    if (this._ended !== 0) this.destroy()
  }

  _onrawdata(data) {
    let offset = 0

    if (this._timeoutTimer !== null) {
      this._timeoutTimer.refresh()
    }

    do {
      switch (this._state) {
        case 0: {
          while (this._tmp !== 0x1000000 && offset < data.byteLength) {
            const v = data[offset++]
            this._len += this._tmp * v
            this._tmp *= 256
          }

          if (this._tmp === 0x1000000) {
            this._tmp = 0
            this._state = 1
            const unprocessed = data.byteLength - offset
            if (unprocessed < this._len && this._utp !== null)
              this._utp.setContentSize(this._len - unprocessed)
          }

          break
        }

        case 1: {
          const missing = this._len - this._tmp
          const end = missing + offset

          if (this._message === null && end <= data.byteLength) {
            this._message = data.subarray(offset, end)
            offset += missing
            this._incoming()
            break
          }

          const unprocessed = data.byteLength - offset

          if (this._message === null) {
            this._message = b4a.allocUnsafe(this._len)
          }

          b4a.copy(data, this._message, this._tmp, offset)
          this._tmp += unprocessed

          if (end <= data.byteLength) {
            offset += missing
            this._incoming()
          } else {
            offset += unprocessed
          }

          break
        }
      }
    } while (offset < data.byteLength && !this.destroying)
  }

  _onrawend() {
    this._ended--
    this.push(null)
  }

  _onrawdrain() {
    const drain = this._drainDone
    if (drain === null) return
    this._drainDone = null
    drain()
  }

  _read(cb) {
    this.rawStream.resume()
    cb(null)
  }

  _incoming() {
    const message = this._message

    this._state = 0
    this._len = 0
    this._tmp = 1
    this._message = null

    if (this._setup === true) {
      if (this._handshake) {
        this._onhandshakert(this._handshake.recv(message))
      } else {
        if (message.byteLength !== IDHEADERBYTES) {
          this.destroy(new Error('Invalid header message received'))
          return
        }

        const remoteId = message.subarray(0, 32)
        const expectedId = streamId(this.handshakeHash, !this.isInitiator)
        const header = message.subarray(32)

        if (!b4a.equals(expectedId, remoteId)) {
          this.destroy(new Error('Invalid header received'))
          return
        }

        this._decrypt.init(header)
        this._setup = false // setup is now done
      }
      return
    }

    if (message.byteLength < ABYTES) {
      this.destroy(new Error('Invalid message received'))
      return
    }

    this.rawBytesRead += message.byteLength

    const plain = message.subarray(1, message.byteLength - ABYTES + 1)

    try {
      this._decrypt.next(message, plain)
    } catch (err) {
      this.destroy(err)
      return
    }

    // If keep alive is selective, eat the empty buffers (ie assume the other side has it enabled also)
    if (plain.byteLength === 0 && this.keepAlive !== 0) return

    if (this.push(plain) === false) {
      this.rawStream.pause()
    }
  }

  _onhandshakert(h) {
    if (this._handshakeDone === null) return

    if (h !== null) {
      if (h.data) this._rawStream.write(h.data)
      if (!h.tx) return
    }

    const done = this._handshakeDone
    const publicKey = this._handshake.keyPair.publicKey

    this._handshakeDone = null
    this._handshake = null

    if (h === null) return done(new Error('Noise handshake failed'))

    this._setupSecretStream(h.tx, h.rx, h.hash, publicKey, h.remotePublicKey)
    this._resolveOpened(true)
    done(null)
  }

  _setupSecretStream(tx, rx, handshakeHash, publicKey, remotePublicKey) {
    const buf = b4a.allocUnsafeSlow(3 + IDHEADERBYTES)
    writeUint24le(IDHEADERBYTES, buf)

    this._encrypt = new Push(unslab(tx.subarray(0, KEYBYTES)), undefined, buf.subarray(3 + 32))
    this._decrypt = new Pull(unslab(rx.subarray(0, KEYBYTES)))

    this.publicKey = publicKey
    this.remotePublicKey = remotePublicKey
    this.handshakeHash = handshakeHash

    const id = buf.subarray(3, 3 + 32)
    streamId(handshakeHash, this.isInitiator, id)

    // initialize secretbox state for unordered messages
    this._setupSecretSend(handshakeHash)

    this.emit('handshake')
    // if rawStream is a bridge, also emit it there
    if (this.rawStream !== this._rawStream) this.rawStream.emit('handshake')

    if (this.destroying) return

    this._rawStream.write(buf)
  }

  _setupSecretSend(handshakeHash) {
    this._sendState = b4a.allocUnsafeSlow(32 + 32 + 8 + 8)
    const encrypt = this._sendState.subarray(0, 32) // secrets
    const decrypt = this._sendState.subarray(32, 64)
    const counter = this._sendState.subarray(64, 72) // nonce
    const initial = this._sendState.subarray(72)

    const inputs = this.isInitiator
      ? [
          [NS_INITIATOR, NS_SEND],
          [NS_RESPONDER, NS_SEND]
        ]
      : [
          [NS_RESPONDER, NS_SEND],
          [NS_INITIATOR, NS_SEND]
        ]

    sodium.crypto_generichash_batch(encrypt, inputs[0], handshakeHash)
    sodium.crypto_generichash_batch(decrypt, inputs[1], handshakeHash)

    sodium.randombytes_buf(initial)
    counter.set(initial)
  }

  _open(cb) {
    // no autostart or no handshake yet
    if (this._rawStream === null || (this._handshake === null && this._encrypt === null)) {
      this._startDone = cb
      return
    }

    this._rawStream.on('data', this._onrawdata.bind(this))
    this._rawStream.on('end', this._onrawend.bind(this))
    this._rawStream.on('drain', this._onrawdrain.bind(this))

    if (this.enableSend) this._rawStream.on('message', this._onmessage.bind(this))

    if (this._encrypt !== null) {
      this._resolveOpened(true)
      return cb(null)
    }

    this._handshakeDone = cb

    if (this.isInitiator) this._onhandshakert(this._handshake.send())
  }

  _predestroy() {
    if (this.rawStream) {
      const error = getStreamError(this)
      this.rawStream.destroy(error)
    }

    if (this._startDone !== null) {
      const done = this._startDone
      this._startDone = null
      done(new Error('Stream destroyed'))
    }

    if (this._handshakeDone !== null) {
      const done = this._handshakeDone
      this._handshakeDone = null
      done(new Error('Stream destroyed'))
    }

    if (this._drainDone !== null) {
      const done = this._drainDone
      this._drainDone = null
      done(new Error('Stream destroyed'))
    }
  }

  _write(data, cb) {
    let wrapped = this._outgoingWrapped

    if (data !== this._outgoingPlain) {
      wrapped = b4a.allocUnsafe(data.byteLength + 3 + ABYTES)
      wrapped.set(data, 4)
    } else {
      this._outgoingWrapped = this._outgoingPlain = null
    }

    if (wrapped.byteLength - 3 > MAX_ATOMIC_WRITE) {
      return cb(
        new Error(
          'Message is too large for an atomic write. Max size is ' + MAX_ATOMIC_WRITE + ' bytes.'
        )
      )
    }
    this.rawBytesWritten += wrapped.byteLength

    writeUint24le(wrapped.byteLength - 3, wrapped)
    // offset 4 so we can do it in-place
    this._encrypt.next(wrapped.subarray(4, 4 + data.byteLength), wrapped.subarray(3))

    if (this._keepAliveTimer !== null) this._keepAliveTimer.refresh()

    if (this._rawStream.write(wrapped) === false) {
      this._drainDone = cb
    } else {
      cb(null)
    }
  }

  _final(cb) {
    this._clearKeepAlive()
    this._ended--
    this._rawStream.end()
    cb(null)
  }

  _resolveOpened(val) {
    if (this._openedDone === null) return
    const opened = this._openedDone
    this._openedDone = null
    opened(val)
    if (!val) return
    this.connected = true
    this.emit('connect')
  }

  _clearTimeout() {
    if (this._timeoutTimer === null) return
    this._timeoutTimer.destroy()
    this._timeoutTimer = null
    this.timeout = 0
  }

  _clearKeepAlive() {
    if (this._keepAliveTimer === null) return
    this._keepAliveTimer.destroy()
    this._keepAliveTimer = null
    this.keepAlive = 0
  }

  _destroy(cb) {
    this._clearKeepAlive()
    this._clearTimeout()
    this._resolveOpened(false)
    cb(null)
  }

  _boxMessage(buffer) {
    const MB = sodium.crypto_secretbox_MACBYTES // 16
    const NB = sodium.crypto_secretbox_NONCEBYTES // 24

    const counter = this._sendState.subarray(64, 72)
    sodium.sodium_increment(counter)
    if (b4a.equals(counter, this._sendState.subarray(72))) {
      this.destroy(new Error('udp send nonce exchausted'))
      return
    }

    const secret = this._sendState.subarray(0, 32)
    const envelope = b4a.allocUnsafe(8 + MB + buffer.byteLength)
    const nonce = envelope.subarray(0, NB)
    const ciphertext = envelope.subarray(8)

    b4a.fill(nonce, 0) // pad suffix
    nonce.set(counter)

    sodium.crypto_secretbox_easy(ciphertext, buffer, nonce, secret)
    return envelope
  }

  send(buffer) {
    if (!this._sendState) return
    if (!this.rawStream?.send) return // udx-stream expected

    const message = this._boxMessage(buffer)
    return this.rawStream.send(message)
  }

  trySend(buffer) {
    if (!this._sendState) return
    if (!this.rawStream?.trySend) return // udx-stream expected

    const message = this._boxMessage(buffer)
    this.rawStream.trySend(message)
  }

  _onmessage(buffer) {
    if (!this._sendState) return // messages before handshake are dropped

    const MB = sodium.crypto_secretbox_MACBYTES // 16
    const NB = sodium.crypto_secretbox_NONCEBYTES // 24

    if (buffer.byteLength < NB) return // Invalid message

    const nonce = b4a.allocUnsafe(NB)
    b4a.fill(nonce, 0)
    nonce.set(buffer.subarray(0, 8))

    const secret = this._sendState.subarray(32, 64)
    const ciphertext = buffer.subarray(8)
    const plain = buffer.subarray(8, buffer.byteLength - MB)

    if (ciphertext.byteLength < MB) return // invalid message

    const success = sodium.crypto_secretbox_open_easy(plain, ciphertext, nonce, secret)

    if (success) this.emit('message', plain)
  }

  alloc(len) {
    const buf = b4a.allocUnsafe(len + 3 + ABYTES)
    this._outgoingWrapped = buf
    this._outgoingPlain = buf.subarray(4, buf.byteLength - ABYTES + 1)
    return this._outgoingPlain
  }

  toJSON() {
    return {
      isInitiator: this.isInitiator,
      publicKey: this.publicKey && b4a.toString(this.publicKey, 'hex'),
      remotePublicKey: this.remotePublicKey && b4a.toString(this.remotePublicKey, 'hex'),
      connected: this.connected,
      destroying: this.destroying,
      destroyed: this.destroyed,
      rawStream: this.rawStream && this.rawStream.toJSON ? this.rawStream.toJSON() : null
    }
  }
}

function writeUint24le(n, buf) {
  buf[0] = n & 255
  buf[1] = (n >>> 8) & 255
  buf[2] = (n >>> 16) & 255
}

function streamId(handshakeHash, isInitiator, out = b4a.allocUnsafe(32)) {
  sodium.crypto_generichash(out, isInitiator ? NS_INITIATOR : NS_RESPONDER, handshakeHash)
  return out
}

function toBuffer(data) {
  return typeof data === 'string' ? b4a.from(data) : data
}

function destroyTimeout() {
  this.destroy(new Error('Stream timed out'))
}

function sendKeepAlive() {
  const empty = this.alloc(0)
  this.write(empty)
}
const { Duplex, Writable } = require('streamx')

class ReversePassThrough extends Duplex {
  constructor(s) {
    super()
    this._stream = s
    this._ondrain = null
  }

  _write(data, cb) {
    if (this._stream.push(data) === false) {
      this._stream._ondrain = cb
    } else {
      cb(null)
    }
  }

  _final(cb) {
    this._stream.push(null)
    cb(null)
  }

  _read(cb) {
    const ondrain = this._ondrain
    this._ondrain = null
    if (ondrain) ondrain()
    cb(null)
  }
}

module.exports = class Bridge extends Duplex {
  constructor(noiseStream) {
    super()

    this.noiseStream = noiseStream

    this._ondrain = null
    this.reverse = new ReversePassThrough(this)
  }

  get publicKey() {
    return this.noiseStream.publicKey
  }

  get remotePublicKey() {
    return this.noiseStream.remotePublicKey
  }

  get handshakeHash() {
    return this.noiseStream.handshakeHash
  }

  flush() {
    return Writable.drained(this)
  }

  _read(cb) {
    const ondrain = this._ondrain
    this._ondrain = null
    if (ondrain) ondrain()
    cb(null)
  }

  _write(data, cb) {
    if (this.reverse.push(data) === false) {
      this.reverse._ondrain = cb
    } else {
      cb(null)
    }
  }

  _final(cb) {
    this.reverse.push(null)
    cb(null)
  }
}
const sodium = require('sodium-universal')
const curve = require('noise-curve-ed')
const Noise = require('noise-handshake')
const b4a = require('b4a')

const EMPTY = b4a.alloc(0)

module.exports = class Handshake {
  constructor(isInitiator, keyPair, remotePublicKey, pattern) {
    this.isInitiator = isInitiator
    this.keyPair = keyPair
    this.noise = new Noise(pattern, isInitiator, keyPair, { curve })
    this.noise.initialise(EMPTY, remotePublicKey)
    this.destroyed = false
  }

  static keyPair(seed) {
    const publicKey = b4a.alloc(32)
    const secretKey = b4a.alloc(64)
    if (seed) sodium.crypto_sign_seed_keypair(publicKey, secretKey, seed)
    else sodium.crypto_sign_keypair(publicKey, secretKey)
    return { publicKey, secretKey }
  }

  recv(data) {
    try {
      this.noise.recv(data)
      if (this.noise.complete) return this._return(null)
      return this.send()
    } catch {
      this.destroy()
      return null
    }
  }

  // note that the data returned here is framed so we don't have to do an extra copy
  // when sending it...
  send() {
    try {
      const data = this.noise.send()
      const wrap = b4a.allocUnsafe(data.byteLength + 3)

      writeUint24le(data.byteLength, wrap)
      wrap.set(data, 3)

      return this._return(wrap)
    } catch {
      this.destroy()
      return null
    }
  }

  destroy() {
    if (this.destroyed) return
    this.destroyed = true
  }

  _return(data) {
    const tx = this.noise.complete ? b4a.toBuffer(this.noise.tx) : null
    const rx = this.noise.complete ? b4a.toBuffer(this.noise.rx) : null
    const hash = this.noise.complete ? b4a.toBuffer(this.noise.hash) : null
    const remotePublicKey = this.noise.complete ? b4a.toBuffer(this.noise.rs) : null

    return {
      data,
      remotePublicKey,
      hash,
      tx,
      rx
    }
  }
}

function writeUint24le(n, buf) {
  buf[0] = n & 255
  buf[1] = (n >>> 8) & 255
  buf[2] = (n >>> 16) & 255
}
{
  "name": "@hyperswarm/secret-stream",
  "version": "6.9.1",
  "description": "Secret stream backed by Noise and libsodium's secretstream",
  "main": "index.js",
  "files": [
    "index.js",
    "lib/**.js"
  ],
  "dependencies": {
    "b4a": "^1.1.0",
    "hypercore-crypto": "^3.3.1",
    "noise-curve-ed": "^2.0.1",
    "noise-handshake": "^4.0.0",
    "sodium-secretstream": "^1.1.0",
    "sodium-universal": "^5.0.0",
    "streamx": "^2.14.0",
    "timeout-refresh": "^2.0.0",
    "unslab": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "udx-native": "^1.13.2"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check .",
    "test": "brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/hyperswarm-secret-stream.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/hyperswarm-secret-stream/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperswarm-secret-stream"
}
const Cache = require('xache')

module.exports = class AdaptiveTimeout {
  constructor(opts = {}) {
    this._cache = new Cache({
      maxSize: opts.maxSize || 65536,
      maxAge: opts.maxAge || 10 * 60 * 1000 // 10 minutes
    })
    this._fallback = opts.fallback || AdaptiveTimeout.TimeoutExponential
    this._min = opts.min ?? 300
    this._max = opts.max || 4000
    this._jitter = opts.jitter ?? 256
  }

  // Default - aggressive ramp
  static TimeoutAggressive = [500, 750, 1000, 1500, 2000]

  // Linear - steady increase
  static TimeoutLinear = [500, 1000, 1500, 2000, 2500]

  // Exponential - slow start, rapid backoff
  static TimeoutExponential = [250, 500, 1000, 2000, 4000]

  // Gentle - conservative, patient
  static TimeoutGentle = [1000, 1250, 1500, 1750, 2000]

  // Fast - rapid fire retries
  static TimeoutFast = [200, 400, 600, 800, 1000]

  // U-shape - long, short, long
  static TimeoutUShape = [1500, 750, 500, 750, 1500]

  // Inverse U - short, long, short
  static TimeoutInverseU = [500, 1000, 1500, 1000, 500]

  // Sawtooth - alternating fast/slow
  static TimeoutSawtooth = [500, 1500, 500, 1500, 500]

  // Plateau - quick ramp then steady
  static TimeoutPlateau = [500, 1000, 2000, 2000, 2000]

  // Logarithmic - diminishing increases
  static TimeoutLogarithmic = [500, 1000, 1300, 1500, 1600]

  getValue(key) {
    return this._cache.get(key)
  }

  put(key, value) {
    let p = this._cache.get(key)

    if (!p) {
      p = { avg: value, variance: value >> 1 }
    } else {
      // blend 75% old + 25% new deviation
      p.variance += (Math.abs(p.avg - value) - p.variance) >> 2
      // blend 87.5% old + 12.5% new sample
      p.avg += (value - p.avg) >> 3
    }

    this._cache.set(key, p)

    return p
  }

  get(key, attempt = 1) {
    const p = this._cache.get(key)
    const jitter = (Math.random() * this._jitter) | 0

    if (p) {
      // known - use adaptive with linear backoff
      const base = p.avg + (p.variance << 1)
      const backoff = base * attempt
      return Math.min(Math.max(backoff + jitter, this._min), this._max)
    } else {
      // unknown - use aggressive fallback
      const base = this._fallback[Math.min(attempt - 1, this._fallback.length - 1)]
      return base + jitter
    }
  }

  has(key) {
    return this._cache.has(key)
  }

  delete(key) {
    return this._cache.delete(key)
  }

  clear() {
    this._cache.clear()
  }
}
{
  "name": "adaptive-timeout",
  "version": "1.0.1",
  "description": "adaptive-timeout",
  "main": "index.js",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    }
  },
  "files": [
    "package.json",
    "index.js",
    "index.d.ts"
  ],
  "devDependencies": {
    "brittle": "^3.19.0",
    "lunte": "^1.2.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && lunte && brittle-bare test/index.js",
    "lint": "lunte"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/adaptive-timeout.git"
  },
  "author": "Holepunch Inc",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/adaptive-timeout/issues"
  },
  "homepage": "https://github.com/holepunchto/adaptive-timeout",
  "dependencies": {
    "xache": "^1.2.1"
  }
}
function isBuffer(value) {
  return Buffer.isBuffer(value) || value instanceof Uint8Array
}

function isEncoding(encoding) {
  return Buffer.isEncoding(encoding)
}

function alloc(size, fill, encoding) {
  return Buffer.alloc(size, fill, encoding)
}

function allocUnsafe(size) {
  return Buffer.allocUnsafe(size)
}

function allocUnsafeSlow(size) {
  return Buffer.allocUnsafeSlow(size)
}

function byteLength(string, encoding) {
  return Buffer.byteLength(string, encoding)
}

function compare(a, b) {
  return Buffer.compare(a, b)
}

function concat(buffers, totalLength) {
  return Buffer.concat(buffers, totalLength)
}

function copy(source, target, targetStart, start, end) {
  return toBuffer(source).copy(target, targetStart, start, end)
}

function equals(a, b) {
  return toBuffer(a).equals(b)
}

function fill(buffer, value, offset, end, encoding) {
  return toBuffer(buffer).fill(value, offset, end, encoding)
}

function from(value, encodingOrOffset, length) {
  return Buffer.from(value, encodingOrOffset, length)
}

function includes(buffer, value, byteOffset, encoding) {
  return toBuffer(buffer).includes(value, byteOffset, encoding)
}

function indexOf(buffer, value, byfeOffset, encoding) {
  return toBuffer(buffer).indexOf(value, byfeOffset, encoding)
}

function lastIndexOf(buffer, value, byteOffset, encoding) {
  return toBuffer(buffer).lastIndexOf(value, byteOffset, encoding)
}

function swap16(buffer) {
  return toBuffer(buffer).swap16()
}

function swap32(buffer) {
  return toBuffer(buffer).swap32()
}

function swap64(buffer) {
  return toBuffer(buffer).swap64()
}

function toBuffer(buffer) {
  if (Buffer.isBuffer(buffer)) return buffer
  return Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

function toString(buffer, encoding, start, end) {
  return toBuffer(buffer).toString(encoding, start, end)
}

function write(buffer, string, offset, length, encoding) {
  return toBuffer(buffer).write(string, offset, length, encoding)
}

function readDoubleBE(buffer, offset) {
  return toBuffer(buffer).readDoubleBE(offset)
}

function readDoubleLE(buffer, offset) {
  return toBuffer(buffer).readDoubleLE(offset)
}

function readFloatBE(buffer, offset) {
  return toBuffer(buffer).readFloatBE(offset)
}

function readFloatLE(buffer, offset) {
  return toBuffer(buffer).readFloatLE(offset)
}

function readInt32BE(buffer, offset) {
  return toBuffer(buffer).readInt32BE(offset)
}

function readInt32LE(buffer, offset) {
  return toBuffer(buffer).readInt32LE(offset)
}

function readUInt32BE(buffer, offset) {
  return toBuffer(buffer).readUInt32BE(offset)
}

function readUInt32LE(buffer, offset) {
  return toBuffer(buffer).readUInt32LE(offset)
}

function writeDoubleBE(buffer, value, offset) {
  return toBuffer(buffer).writeDoubleBE(value, offset)
}

function writeDoubleLE(buffer, value, offset) {
  return toBuffer(buffer).writeDoubleLE(value, offset)
}

function writeFloatBE(buffer, value, offset) {
  return toBuffer(buffer).writeFloatBE(value, offset)
}

function writeFloatLE(buffer, value, offset) {
  return toBuffer(buffer).writeFloatLE(value, offset)
}

function writeInt32BE(buffer, value, offset) {
  return toBuffer(buffer).writeInt32BE(value, offset)
}

function writeInt32LE(buffer, value, offset) {
  return toBuffer(buffer).writeInt32LE(value, offset)
}

function writeUInt32BE(buffer, value, offset) {
  return toBuffer(buffer).writeUInt32BE(value, offset)
}

function writeUInt32LE(buffer, value, offset) {
  return toBuffer(buffer).writeUInt32LE(value, offset)
}

module.exports = {
  isBuffer,
  isEncoding,
  alloc,
  allocUnsafe,
  allocUnsafeSlow,
  byteLength,
  compare,
  concat,
  copy,
  equals,
  fill,
  from,
  includes,
  indexOf,
  lastIndexOf,
  swap16,
  swap32,
  swap64,
  toBuffer,
  toString,
  write,
  readDoubleBE,
  readDoubleLE,
  readFloatBE,
  readFloatLE,
  readInt32BE,
  readInt32LE,
  readUInt32BE,
  readUInt32LE,
  writeDoubleBE,
  writeDoubleLE,
  writeFloatBE,
  writeFloatLE,
  writeInt32BE,
  writeInt32LE,
  writeUInt32BE,
  writeUInt32LE
}
{
  "name": "b4a",
  "version": "1.8.1",
  "description": "Bridging the gap between buffers and typed arrays",
  "exports": {
    "./package": "./package.json",
    ".": {
      "react-native": "./react-native.js",
      "browser": "./browser.js",
      "default": "./index.js"
    }
  },
  "files": [
    "browser.js",
    "index.js",
    "react-native.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:bare && npm run test:node",
    "test:bare": "brittle-bare --coverage test.mjs",
    "test:node": "brittle-node --coverage test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/b4a.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/b4a/issues"
  },
  "homepage": "https://github.com/holepunchto/b4a#readme",
  "devDependencies": {
    "brittle": "^3.5.2",
    "lunte": "^1.7.0",
    "nanobench": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "react-native-b4a": "*"
  },
  "peerDependenciesMeta": {
    "react-native-b4a": {
      "optional": true
    }
  }
}
module.exports = require.addon()
const binding = require('./binding')

module.exports = binding.abort
{
  "name": "bare-abort",
  "version": "2.0.13",
  "description": "Cause abnormal program termination and generate a crash report",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-abort.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-abort/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-abort#readme",
  "devDependencies": {
    "cmake-bare": "^1.1.7",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  }
}
const ESC = '\x1b'
const CSI = ESC + '['
const SGR = (n) => CSI + n + 'm'

exports.constants = {
  ESC,
  CSI,
  SGR
}

// https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_(Control_Sequence_Introducer)_sequences

exports.cursorHide = CSI + '?25l'
exports.cursorShow = CSI + '?25h'

exports.cursorUp = function cursorUp(n = 1) {
  return CSI + n + 'A'
}

exports.cursorDown = function cursorDown(n = 1) {
  return CSI + n + 'B'
}

exports.cursorForward = function cursorForward(n = 1) {
  return CSI + n + 'C'
}

exports.cursorBack = function cursorBack(n = 1) {
  return CSI + n + 'D'
}

exports.cursorNextLine = function cursorNextLine(n = 1) {
  return CSI + n + 'E'
}

exports.cursorPreviousLine = function cursorPreviousLine(n = 1) {
  return CSI + n + 'F'
}

exports.cursorPosition = function cursorPosition(column, row = 0) {
  if (row === 0) return CSI + (column + 1) + 'G'

  return CSI + (row + 1) + ';' + (column + 1) + 'H'
}

exports.eraseDisplayEnd = CSI + 'J'
exports.eraseDisplayStart = CSI + '1J'
exports.eraseDisplay = CSI + '2J'
exports.eraseLineEnd = CSI + 'K'
exports.eraseLineStart = CSI + '1K'
exports.eraseLine = CSI + '2K'

exports.scrollUp = function scrollUp(n = 1) {
  return CSI + n + 'S'
}

exports.scrollDown = function scrollDown(n = 1) {
  return CSI + n + 'T'
}

// https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_(Select_Graphic_Rendition)_parameters

exports.modifierReset = SGR(0)
exports.modifierBold = SGR(1)
exports.modifierDim = SGR(2)
exports.modifierItalic = SGR(3)
exports.modifierUnderline = SGR(4)
exports.modifierNormal = SGR(22)
exports.modifierNotItalic = SGR(23)
exports.modifierNotUnderline = SGR(24)

// https://en.wikipedia.org/wiki/ANSI_escape_code#Colors

exports.colorBlack = SGR(30)
exports.colorRed = SGR(31)
exports.colorGreen = SGR(32)
exports.colorYellow = SGR(33)
exports.colorBlue = SGR(34)
exports.colorMagenta = SGR(35)
exports.colorCyan = SGR(36)
exports.colorWhite = SGR(37)
exports.colorDefault = SGR(39)
exports.colorBrightBlack = SGR(90)
exports.colorBrightRed = SGR(91)
exports.colorBrightGreen = SGR(92)
exports.colorBrightYellow = SGR(93)
exports.colorBrightBlue = SGR(94)
exports.colorBrightMagenta = SGR(95)
exports.colorBrightCyan = SGR(96)
exports.colorBrightWhite = SGR(97)
{
  "name": "bare-ansi-escapes",
  "version": "2.2.3",
  "description": "Parse and produce ANSI escape sequences",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./key-decoder": {
      "types": "./key-decoder.d.ts",
      "default": "./key-decoder.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "key-decoder.js",
    "key-decoder.d.ts"
  ],
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-ansi-escapes.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-ansi-escapes/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-ansi-escapes#readme",
  "dependencies": {
    "bare-stream": "^2.6.5"
  },
  "devDependencies": {
    "bare-buffer": "^3.0.2",
    "brittle": "^3.3.2",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  },
  "peerDependencies": {
    "bare-buffer": "*"
  },
  "peerDependenciesMeta": {
    "bare-buffer": {
      "optional": true
    }
  }
}
const inspect = require('bare-inspect')

class AssertionError extends Error {
  constructor(opts = {}) {
    let { message = null, actual, expected, operator } = opts

    if (message === null) {
      message = `${inspect(actual)} ${operator} ${inspect(expected)}`
    }

    super(message)

    this.actual = actual
    this.expected = expected
    this.operator = operator
  }

  get name() {
    return 'AssertionError'
  }

  get code() {
    'ASSERTION'
  }
}

function assertFail(opts, fn) {
  if (opts.message instanceof Error) throw opts.message

  const err = new AssertionError(opts)

  if (Error.captureStackTrace) Error.captureStackTrace(err, fn)

  throw err
}

module.exports = exports = function assert(actual, message) {
  if (actual) return

  assertFail({ message, actual, expected: true, operator: '==' }, assert)
}

exports.AssertionError = AssertionError

exports.fail = function fail(message) {
  if (message === undefined) message = 'Failed'

  assertFail({ message, operator: 'fail' }, fail)
}

exports.ok = function ok(actual, message) {
  if (actual) return

  assertFail({ message, actual, expected: true, operator: '==' }, ok)
}

exports.notOk = function ok(actual, message) {
  if (!actual) return

  assertFail({ message, actual, expected: false, operator: '==' }, ok)
}

exports.equal = function equal(actual, expected, message) {
  if (actual == expected || (actual !== actual && expected !== expected)) {
    return
  }

  assertFail({ message, actual, expected, operator: '==' }, equal)
}

exports.notEqual = function notEqual(actual, expected, message) {
  if (actual != expected && (actual === actual || expected === expected)) {
    return
  }

  assertFail({ message, actual, expected, operator: '!=' }, notEqual)
}

exports.strictEqual = function strictEqual(actual, expected, message) {
  if (Object.is(actual, expected)) return

  assertFail(
    { message, actual, expected, operator: 'strictEqual' },
    strictEqual
  )
}

exports.notStrictEqual = function notStrictEqual(actual, expected, message) {
  if (!Object.is(actual, expected)) return

  assertFail(
    { message, actual, expected, operator: 'notStrictEqual' },
    notStrictEqual
  )
}
{
  "name": "bare-assert",
  "version": "1.2.0",
  "description": "Assertion library for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts"
  ],
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-assert.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-assert/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-assert#readme",
  "dependencies": {
    "bare-inspect": "^3.1.2"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  }
}
module.exports = require.addon()
const binding = require('./binding')

exports.Resolver = class DNSResolver {
  constructor() {
    this._handle = binding.initResolver()
  }

  resolveTxt(hostname, cb = noop) {
    binding.resolveTxt(this._handle, hostname, cb, this)
  }

  destroy() {
    binding.destroyResolver(this._handle)
    this._handle = null
  }

  static global = new this()
}

function onlookup(err, addresses) {
  const req = this

  if (err) return req.cb(err, null, 0)

  const { address, family } = addresses[0]

  return req.cb(null, address, family)
}

function onlookupall(err, addresses) {
  const req = this

  if (err) return req.cb(err, null)

  return req.cb(null, addresses)
}

exports.lookup = function lookup(hostname, opts = {}, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  let { family = 0, all = false } = opts

  if (typeof family === 'string') {
    switch (family) {
      case 'IPv4':
        family = 4
        break
      case 'IPv6':
        family = 6
        break
      default:
        family = 0
    }
  }

  const req = {
    cb,
    handle: null
  }

  req.handle = binding.lookup(
    hostname,
    family || 0,
    all,
    req,
    all ? onlookupall : onlookup
  )
}

exports.resolveTxt = function resolveTxt(hostname, cb) {
  exports.Resolver.global.resolveTxt(hostname, cb)
}

function noop() {}
{
  "name": "bare-dns",
  "version": "2.1.4",
  "description": "Domain name resolution for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-dns.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-dns/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-dns",
  "engines": {
    "bare": ">=1.7.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "cmake-bare": "^1.1.6",
    "cmake-fetch": "^1.3.0",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
const os = require('bare-os')

module.exports = new Proxy(Object.create(null), {
  ownKeys (target) {
    return os.getEnvKeys()
  },

  get (target, property) {
    if (typeof property !== 'string') return

    return os.getEnv(property)
  },

  has (target, property) {
    if (typeof property !== 'string') return false

    return os.hasEnv(property)
  },

  set (target, property, value) {
    if (typeof property !== 'string') return

    const type = typeof value

    if (type !== 'string' && type !== 'number' && type !== 'boolean') {
      throw new Error('Environment variable must be of type string, number, or boolean')
    }

    value = String(value)

    os.setEnv(property, value)

    return true
  },

  deleteProperty (target, property) {
    if (typeof property !== 'string') return

    os.unsetEnv(property)
  },

  getOwnPropertyDescriptor (target, property) {
    return {
      value: this.get(target, property),
      enumerable: true,
      configurable: true,
      writable: true
    }
  }
})
{
  "name": "bare-env",
  "version": "3.0.0",
  "description": "Environment variable support for JavaScript",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "scripts": {
    "test": "standard && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-env.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-env/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-env#readme",
  "dependencies": {
    "bare-os": "^3.0.1"
  },
  "devDependencies": {
    "brittle": "^3.2.1",
    "standard": "^17.0.0"
  }
}
const errors = require('./lib/errors')

class EventListener {
  constructor() {
    this.list = []
    this.count = 0
  }

  append(ctx, name, fn, once) {
    this.count++
    ctx.emit('newListener', name, fn) // Emit BEFORE adding
    this.list.push([fn, once])
  }

  prepend(ctx, name, fn, once) {
    this.count++
    ctx.emit('newListener', name, fn) // Emit BEFORE adding
    this.list.unshift([fn, once])
  }

  remove(ctx, name, fn) {
    for (let i = 0, n = this.list.length; i < n; i++) {
      const l = this.list[i]

      if (l[0] === fn) {
        this.list.splice(i, 1)

        if (this.count === 1) delete ctx._events[name]

        ctx.emit('removeListener', name, fn) // Emit AFTER removing

        this.count--
        return
      }
    }
  }

  removeAll(ctx, name) {
    const list = [...this.list]
    this.list = []

    if (this.count === list.length) delete ctx._events[name]

    for (let i = list.length - 1; i >= 0; i--) {
      ctx.emit('removeListener', name, list[i][0]) // Emit AFTER removing
    }

    this.count -= list.length
  }

  emit(ctx, name, ...args) {
    const list = [...this.list]

    for (let i = 0, n = list.length; i < n; i++) {
      const l = list[i]

      if (l[1] === true) this.remove(ctx, name, l[0])

      Reflect.apply(l[0], ctx, args)
    }

    return list.length > 0
  }
}

function appendListener(ctx, name, fn, once) {
  if (ctx._events === undefined) ctx._events = Object.create(null)
  const e = ctx._events[name] || (ctx._events[name] = new EventListener())
  e.append(ctx, name, fn, once)
  return ctx
}

function prependListener(ctx, name, fn, once) {
  if (ctx._events === undefined) ctx._events = Object.create(null)
  const e = ctx._events[name] || (ctx._events[name] = new EventListener())
  e.prepend(ctx, name, fn, once)
  return ctx
}

function removeListener(ctx, name, fn) {
  if (ctx._events === undefined) return ctx
  const e = ctx._events[name]
  if (e !== undefined) e.remove(ctx, name, fn)
  return ctx
}

function throwUnhandledError(...args) {
  let err

  if (args.length > 0) err = args[0]

  if (err instanceof Error === false) err = errors.UNHANDLED_ERROR(err)

  if (Error.captureStackTrace) {
    Error.captureStackTrace(err, exports.prototype.emit)
  }

  queueMicrotask(() => {
    throw err
  })
}

module.exports = exports = class EventEmitter {
  constructor() {
    this._events = Object.create(null)
  }

  addListener(name, fn) {
    return appendListener(this, name, fn, false)
  }

  addOnceListener(name, fn) {
    return appendListener(this, name, fn, true)
  }

  prependListener(name, fn) {
    return prependListener(this, name, fn, false)
  }

  prependOnceListener(name, fn) {
    return prependListener(this, name, fn, true)
  }

  removeListener(name, fn) {
    return removeListener(this, name, fn)
  }

  on(name, fn) {
    return appendListener(this, name, fn, false)
  }

  once(name, fn) {
    return appendListener(this, name, fn, true)
  }

  off(name, fn) {
    return removeListener(this, name, fn)
  }

  emit(name, ...args) {
    if (name === 'error' && this._events !== undefined && this._events.error === undefined) {
      throwUnhandledError(...args)
    }

    if (this._events === undefined) return false
    const e = this._events[name]
    return e === undefined ? false : e.emit(this, name, ...args)
  }

  listeners(name) {
    if (this._events === undefined) return []
    const e = this._events[name]
    return e === undefined ? [] : [...e.list]
  }

  listenerCount(name) {
    if (this._events === undefined) return 0
    const e = this._events[name]
    return e === undefined ? 0 : e.list.length
  }

  getMaxListeners() {
    return EventEmitter.defaultMaxListeners
  }

  setMaxListeners(n) {}

  removeAllListeners(name) {
    if (arguments.length === 0) {
      for (const key of Reflect.ownKeys(this._events)) {
        if (key === 'removeListener') continue
        this.removeAllListeners(key)
      }
      this.removeAllListeners('removeListener')
    } else {
      const e = this._events[name]
      if (e !== undefined) e.removeAll(this, name)
    }
    return this
  }
}

exports.EventEmitter = exports

exports.errors = errors

exports.defaultMaxListeners = 10

exports.on = function on(emitter, name, opts = {}) {
  const { signal } = opts

  if (signal && signal.aborted) {
    throw errors.OPERATION_ABORTED(signal.reason)
  }

  let error = null
  let done = false

  const events = []
  const promises = []

  if (name !== 'error') emitter.on('error', onerror)

  if (signal) signal.addEventListener('abort', onabort)

  emitter.on(name, onevent)

  return {
    next() {
      if (events.length) {
        return Promise.resolve({ value: events.shift(), done: false })
      }

      if (error) {
        const err = error

        error = null

        return Promise.reject(err)
      }

      if (done) return onclose()

      return new Promise((resolve, reject) => promises.push({ resolve, reject }))
    },

    return() {
      return onclose()
    },

    throw(err) {
      return onerror(err)
    },

    [Symbol.asyncIterator]() {
      return this
    }
  }

  function onevent(...args) {
    if (promises.length) {
      promises.shift().resolve({ value: args, done: false })
    } else {
      events.push(args)
    }
  }

  function onerror(err) {
    emitter.off(name, onevent).off('error', onerror)

    if (promises.length) {
      promises.shift().reject(err)
    } else {
      error = err
    }

    return Promise.resolve({ done: true })
  }

  function onabort() {
    signal.removeEventListener('abort', onabort)

    onerror(errors.OPERATION_ABORTED(signal.reason))
  }

  function onclose() {
    emitter.off(name, onevent)

    if (name !== 'error') emitter.off('error', onerror)

    if (signal) signal.removeEventListener('abort', onabort)

    done = true

    if (promises.length) promises.shift().resolve({ done: true })

    return Promise.resolve({ done: true })
  }
}

exports.once = function once(emitter, name, opts = {}) {
  const { signal } = opts

  if (signal && signal.aborted) {
    return Promise.reject(errors.OPERATION_ABORTED(signal.reason))
  }

  return new Promise((resolve, reject) => {
    if (name !== 'error') emitter.on('error', onerror)

    if (signal) signal.addEventListener('abort', onabort)

    emitter.once(name, onevent)

    function onevent(...args) {
      if (name !== 'error') emitter.off('error', onerror)

      if (signal) signal.removeEventListener('abort', onabort)

      resolve(args)
    }

    function onerror(err) {
      emitter.off(name, onevent)

      if (name !== 'error') emitter.off('error', onerror)

      reject(err)
    }

    function onabort() {
      signal.removeEventListener('abort', onabort)

      onerror(errors.OPERATION_ABORTED(signal.reason))
    }
  })
}

exports.forward = function forward(from, to, names, opts = {}) {
  if (typeof names === 'string') names = [names]

  const { emit = to.emit.bind(to) } = opts

  const listeners = names.map(
    (name) =>
      function onevent(...args) {
        emit(name, ...args)
      }
  )

  to.on('newListener', (name) => {
    const i = names.indexOf(name)

    if (i !== -1 && to.listenerCount(name) === 0) {
      from.on(name, listeners[i])
    }
  }).on('removeListener', (name) => {
    const i = names.indexOf(name)

    if (i !== -1 && to.listenerCount(name) === 0) {
      from.off(name, listeners[i])
    }
  })
}

exports.listenerCount = function listenerCount(emitter, name) {
  return emitter.listenerCount(name)
}

exports.getMaxListeners = function getMaxListeners(emitter) {
  if (typeof emitter.getMaxListeners === 'function') {
    return emitter.getMaxListeners()
  }

  return exports.defaultMaxListeners
}

exports.setMaxListeners = function setMaxListeners(n, ...emitters) {
  if (emitters.length === 0) exports.defaultMaxListeners = n
  else {
    for (const emitter of emitters) {
      if (typeof emitter.setMaxListeners === 'function') {
        emitter.setMaxListeners(n)
      }
    }
  }
}
module.exports = class EventEmitterError extends Error {
  constructor(msg, code, fn = EventEmitterError, opts) {
    super(`${code}: ${msg}`, opts)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'EventEmitterError'
  }

  static OPERATION_ABORTED(cause, msg = 'Operation aborted') {
    return new EventEmitterError(msg, 'OPERATION_ABORTED', EventEmitterError.OPERATION_ABORTED, {
      cause
    })
  }

  static UNHANDLED_ERROR(cause, msg = 'Unhandled error') {
    return new EventEmitterError(msg, 'UNHANDLED_ERROR', EventEmitterError.UNHANDLED_ERROR, {
      cause
    })
  }
}
{
  "name": "bare-events",
  "version": "2.8.2",
  "description": "Event emitters for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    },
    "./web": {
      "types": "./web.d.ts",
      "default": "./web.js"
    },
    "./errors": "./lib/errors.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "global.js",
    "global.d.ts",
    "web.js",
    "web.d.ts",
    "lib"
  ],
  "scripts": {
    "test": "npm run lint && npm run test:bare && npm run test:node",
    "test:bare": "bare test.js",
    "test:node": "node test.js",
    "lint": "prettier . --check"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-events.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-events/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-events#readme",
  "devDependencies": {
    "bare-abort-controller": "^1.0.0",
    "brittle": "^3.3.2",
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^2.0.0",
    "uncaughts": "^1.1.1"
  },
  "peerDependencies": {
    "bare-abort-controller": "*"
  },
  "peerDependenciesMeta": {
    "bare-abort-controller": {
      "optional": true
    }
  }
}
module.exports = require.addon()
const FIFO = require('fast-fifo')
const EventEmitter = require('bare-events')
const path = require('bare-path')
const { isURL, fileURLToPath } = require('bare-url')
const { Readable, Writable } = require('bare-stream')
const binding = require('./binding')
const constants = require('./lib/constants')
const FileError = require('./lib/errors')

const isWindows = Bare.platform === 'win32'

exports.constants = constants

class FileRequest {
  static borrow() {
    if (this._free.length > 0) return this._free.pop()
    return new FileRequest()
  }

  static return(req) {
    if (this._free.length < 32) this._free.push(req.reset())
    else req.destroy()
  }

  constructor() {
    this._reset()
    this._handle = binding.requestInit(this, this._onresult)
  }

  get handle() {
    return this._handle
  }

  retain(value) {
    this._retain = value // Tie the lifetime of `value` to the lifetime of `this`
  }

  reset() {
    if (this._handle === null) return this

    binding.requestReset(this._handle)

    this._reset()

    return this
  }

  destroy() {
    if (this._handle === null) return this

    binding.requestDestroy(this._handle)

    this._reset()
    this._handle = null

    return this
  }

  then(resolve, reject) {
    return this._promise.then(resolve, reject)
  }

  return() {
    if (this._handle === null) return this

    FileRequest.return(this)

    return this
  }

  _reset() {
    this._promise = new Promise((resolve, reject) => {
      this._resolve = resolve
      this._reject = reject
    })
    this._retain = null
  }

  _onresult(err, status) {
    if (err) this._reject(err)
    else this._resolve(status)
  }
}

FileRequest._free = []

function ok(result, cb) {
  if (typeof result === 'function') {
    cb = result
    result = undefined
  }

  if (cb) cb(null, result)
  else return result
}

function fail(err, cb) {
  if (cb) cb(err)
  else throw err
}

function done(err, result, cb) {
  if (typeof result === 'function') {
    cb = result
    result = undefined
  }

  if (err) fail(err, cb)
  else return ok(result, cb)
}

async function open(filepath, flags = 'r', mode = 0o666, cb) {
  if (typeof flags === 'function') {
    cb = flags
    flags = 'r'
    mode = 0o666
  } else if (typeof mode === 'function') {
    cb = mode
    mode = 0o666
  }

  if (typeof flags === 'string') flags = toFlags(flags)
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let fd
  let err = null
  try {
    binding.open(req.handle, filepath, flags, mode)

    fd = await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'open',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, fd, cb)
}

function openSync(filepath, flags = 'r', mode = 0o666) {
  if (typeof flags === 'string') flags = toFlags(flags)
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    return binding.openSync(req.handle, filepath, flags, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'open',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function close(fd, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.close(req.handle, fd)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'close', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function closeSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.closeSync(req.handle, fd)
  } catch (e) {
    throw new FileError(e.message, { operation: 'close', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function access(filepath, mode = constants.F_OK, cb) {
  if (typeof mode === 'function') {
    cb = mode
    mode = constants.F_OK
  }

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.access(req.handle, filepath, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'access',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function accessSync(filepath, mode = constants.F_OK) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.accessSync(req.handle, filepath, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'access',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function exists(filepath, cb) {
  let ok = true
  try {
    await access(filepath)
  } catch {
    ok = false
  }

  return done(null, ok, cb)
}

function existsSync(filepath) {
  try {
    accessSync(filepath)
  } catch {
    return false
  }

  return true
}

async function read(fd, buffer, offset = 0, len = buffer.byteLength - offset, pos = -1, cb) {
  if (typeof offset === 'function') {
    cb = offset
    offset = 0
    len = buffer.byteLength
    pos = -1
  } else if (typeof len === 'function') {
    cb = len
    len = buffer.byteLength - offset
    pos = -1
  } else if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.read(req.handle, fd, buffer, offset, len, pos)

    req.retain(buffer)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'read', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function readSync(fd, buffer, offset = 0, len = buffer.byteLength - offset, pos = -1) {
  const req = FileRequest.borrow()

  try {
    return binding.readSync(req.handle, fd, buffer, offset, len, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'read', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function readv(fd, buffers, pos = -1, cb) {
  if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.readv(req.handle, fd, buffers, pos)

    req.retain(buffers)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'readv', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function readvSync(fd, buffers, pos = -1) {
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  try {
    return binding.readvSync(req.handle, fd, buffers, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'readv', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function write(fd, data, offset, len, pos = -1, cb) {
  if (typeof data === 'string') {
    let encoding = len
    cb = pos
    pos = offset

    if (typeof pos === 'function') {
      cb = pos
      pos = -1
      encoding = 'utf8'
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = 'utf8'
    }

    if (typeof pos === 'string') {
      encoding = pos
      pos = -1
    }

    data = Buffer.from(data, encoding)
    offset = 0
    len = data.byteLength
  } else if (typeof offset === 'function') {
    cb = offset
    offset = 0
    len = data.byteLength
    pos = -1
  } else if (typeof len === 'function') {
    cb = len
    len = data.byteLength - offset
    pos = -1
  } else if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof offset !== 'number') offset = 0
  if (typeof len !== 'number') len = data.byteLength - offset
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.write(req.handle, fd, data, offset, len, pos)

    req.retain(data)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'write', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function writeSync(fd, data, offset, len, pos = -1) {
  if (typeof data === 'string') {
    let encoding = len
    pos = offset

    if (typeof pos === 'string') {
      encoding = pos
      pos = -1
    }

    data = Buffer.from(data, encoding)
    offset = 0
    len = data.byteLength
  }

  if (typeof offset !== 'number') offset = 0
  if (typeof len !== 'number') len = data.byteLength - offset
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  try {
    return binding.writeSync(req.handle, fd, data, offset, len, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'write', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function writev(fd, buffers, pos = -1, cb) {
  if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.writev(req.handle, fd, buffers, pos)

    req.retain(buffers)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'writev', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function writevSync(fd, buffers, pos = -1) {
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  try {
    return binding.writevSync(req.handle, fd, buffers, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'writev', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function stat(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.stat(req.handle, filepath)

    await req

    st = new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'stat', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function statSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.statSync(req.handle, filepath)

    return new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'stat', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function lstat(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.lstat(req.handle, filepath)

    await req

    st = new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'lstat', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function lstatSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.lstatSync(req.handle, filepath)

    return new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'lstat', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function fstat(fd, cb) {
  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.fstat(req.handle, fd)

    await req

    st = new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'fstat', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function fstatSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.fstatSync(req.handle, fd)

    return new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'fstat', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function statfs(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.statfs(req.handle, filepath)

    await req

    st = new StatFs(...binding.requestResultStatfs(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'statfs', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function statfsSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.statfsSync(req.handle, filepath)

    return new StatFs(...binding.requestResultStatfs(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'statfs', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function ftruncate(fd, len = 0, cb) {
  if (typeof len === 'function') {
    cb = len
    len = 0
  }

  if (typeof len !== 'number') len = 0

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.ftruncate(req.handle, fd, len)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'ftruncate', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function ftruncateSync(fd, len = 0) {
  if (typeof len !== 'number') len = 0

  const req = FileRequest.borrow()

  try {
    binding.ftruncateSync(req.handle, fd, len)
  } catch (e) {
    throw new FileError(e.message, { operation: 'ftruncate', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function truncate(filepath, len, cb) {
  let fd = -1
  let err

  try {
    fd = await open(filepath, 'r+')

    await ftruncate(fd, len)
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) await close(fd)
  }

  return done(err, cb)
}

function truncateSync(filepath, len) {
  let fd = -1
  let err

  try {
    fd = openSync(filepath, 'r+')

    ftruncateSync(fd, len)
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) closeSync(fd)
  }
}

async function chmod(filepath, mode, cb) {
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.chmod(req.handle, filepath, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'chmod',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function chmodSync(filepath, mode) {
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.chmodSync(req.handle, filepath, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'chmod',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function fchmod(fd, mode, cb) {
  if (typeof mode === 'string') mode = toMode(mode)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fchmod(req.handle, fd, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fchmod', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fchmodSync(fd, mode) {
  if (typeof mode === 'string') mode = toMode(mode)

  const req = FileRequest.borrow()

  try {
    binding.fchmodSync(req.handle, fd, mode)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fchmod', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function chown(filepath, uid, gid, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.chown(req.handle, filepath, uid, gid)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'chown', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function chownSync(filepath, uid, gid) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.chownSync(req.handle, filepath, uid, gid)
  } catch (e) {
    throw new FileError(e.message, { operation: 'chownSync', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function lchown(filepath, uid, gid, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.lchown(req.handle, filepath, uid, gid)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'lchown', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function lchownSync(filepath, uid, gid) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.lchownSync(req.handle, filepath, uid, gid)
  } catch (e) {
    throw new FileError(e.message, { operation: 'lchownSync', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function fchown(fd, uid, gid, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fchown(req.handle, fd, uid, gid)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fchown', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fchownSync(fd, uid, gid) {
  const req = FileRequest.borrow()

  try {
    binding.fchownSync(req.handle, fd, uid, gid)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fchownSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function utimes(filepath, atime, mtime, cb) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.utimes(req.handle, filepath, atime, mtime)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'utimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function utimesSync(filepath, atime, mtime) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.utimesSync(req.handle, filepath, atime, mtime)
  } catch (e) {
    throw new FileError(e.message, { operation: 'utimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function lutimes(filepath, atime, mtime, cb) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.lutimes(req.handle, filepath, atime, mtime)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'lutimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function lutimesSync(filepath, atime, mtime) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.lutimesSync(req.handle, filepath, atime, mtime)
  } catch (e) {
    throw new FileError(e.message, { operation: 'lutimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function futimes(fd, atime, mtime, cb) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.futimes(req.handle, fd, atime, mtime)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'futimes', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function futimesSync(fd, atime, mtime) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  const req = FileRequest.borrow()

  try {
    binding.futimesSync(req.handle, fd, atime, mtime)
  } catch (e) {
    throw new FileError(e.message, { operation: 'futimesSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function link(src, dst, cb) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.link(req.handle, src, dst)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'link', code: e.code, path: src, destination: dst })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function linkSync(src, dst) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  try {
    binding.linkSync(req.handle, src, dst)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'linkSync',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }
}

async function mkdir(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = { mode: 0o777 }
  }

  if (typeof opts === 'number') opts = { mode: opts }
  else if (!opts) opts = {}

  const mode = typeof opts.mode === 'number' ? opts.mode : 0o777

  filepath = toNamespacedPath(filepath)

  if (opts.recursive) {
    let err = null
    try {
      try {
        await mkdir(filepath, { mode })
      } catch (err) {
        if (err.code !== 'ENOENT') {
          if (!(await stat(filepath)).isDirectory()) throw err
        } else {
          while (filepath.endsWith(path.sep)) filepath = filepath.slice(0, -1)
          const i = filepath.lastIndexOf(path.sep)
          if (i <= 0) throw err

          await mkdir(filepath.slice(0, i), { mode, recursive: true })

          try {
            await mkdir(filepath, { mode })
          } catch (err) {
            if (!(await stat(filepath)).isDirectory()) throw err
          }
        }
      }
    } catch (e) {
      err = e
    }

    return done(err, cb)
  }

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.mkdir(req.handle, filepath, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'mkdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function mkdirSync(filepath, opts) {
  if (typeof opts === 'number') opts = { mode: opts }
  else if (!opts) opts = {}

  const mode = typeof opts.mode === 'number' ? opts.mode : 0o777

  filepath = toNamespacedPath(filepath)

  if (opts.recursive) {
    try {
      mkdirSync(filepath, { mode })
    } catch (err) {
      if (err.code !== 'ENOENT') {
        if (!statSync(filepath).isDirectory()) throw err
      } else {
        while (filepath.endsWith(path.sep)) filepath = filepath.slice(0, -1)
        const i = filepath.lastIndexOf(path.sep)
        if (i <= 0) throw err

        mkdirSync(filepath.slice(0, i), { mode, recursive: true })

        try {
          mkdirSync(filepath, { mode })
        } catch (err) {
          if (!statSync(filepath).isDirectory()) throw err
        }
      }
    }

    return
  }

  const req = FileRequest.borrow()

  try {
    binding.mkdirSync(req.handle, filepath, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'mkdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function mkdtemp(prefix, cb) {
  prefix = toNamespacedPath(prefix)

  const req = FileRequest.borrow()

  let res
  let err = null
  try {
    binding.mkdtemp(req.handle, prefix + 'XXXXXX')

    await req

    res = binding.requestResultPath(req.handle)
  } catch (e) {
    err = new FileError(e.message, { operation: 'mkdtemp', code: e.code, path: prefix })
  } finally {
    req.return()
  }

  return done(err, res, cb)
}

function mkdtempSync(prefix) {
  prefix = toNamespacedPath(prefix)

  const req = FileRequest.borrow()

  try {
    binding.mkdtempSync(req.handle, prefix + 'XXXXXX')

    return binding.requestResultPath(req.handle)
  } catch (e) {
    throw new FileError(e.message, { operation: 'mkdtempSync', code: e.code, path: prefix })
  } finally {
    req.return()
  }
}

async function rmdir(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.rmdir(req.handle, filepath)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'rmdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function rmdirSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.rmdirSync(req.handle, filepath)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'rmdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function rm(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  let err = null
  try {
    const st = await lstat(filepath)

    if (st.isDirectory()) {
      if (opts.recursive) {
        try {
          await rmdir(filepath)
        } catch (err) {
          if (err.code !== 'ENOTEMPTY') throw err

          const files = await readdir(filepath)

          for (const file of files) {
            await rm(filepath + path.sep + file, opts)
          }

          await rmdir(filepath)
        }
      } else {
        throw new FileError('is a directory', {
          operation: 'rm',
          code: 'EISDIR',
          path: filepath
        })
      }
    } else {
      await unlink(filepath)
    }
  } catch (e) {
    if (e.code !== 'ENOENT' || !opts.force) err = e
  }

  return done(err, cb)
}

function rmSync(filepath, opts) {
  if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  try {
    const st = lstatSync(filepath)

    if (st.isDirectory()) {
      if (opts.recursive) {
        try {
          rmdirSync(filepath)
        } catch (err) {
          if (err.code !== 'ENOTEMPTY') throw err

          const files = readdirSync(filepath)

          for (const file of files) {
            rmSync(filepath + path.sep + file, opts)
          }

          rmdirSync(filepath)
        }
      } else {
        throw new FileError('is a directory', {
          operation: 'rm',
          code: 'EISDIR',
          path: filepath
        })
      }
    } else {
      unlinkSync(filepath)
    }
  } catch (err) {
    if (err.code !== 'ENOENT' || !opts.force) throw err
  }
}

async function unlink(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.unlink(req.handle, filepath)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'unlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function unlinkSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.unlinkSync(req.handle, filepath)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'unlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function rename(src, dst, cb) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.rename(req.handle, src, dst)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'rename',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function renameSync(src, dst) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  try {
    binding.renameSync(req.handle, src, dst)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'rename',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }
}

async function copyFile(src, dst, mode = 0, cb) {
  if (typeof mode === 'function') {
    cb = mode
    mode = 0
  }

  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.copyfile(req.handle, src, dst, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'copyfile',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function copyFileSync(src, dst, mode = 0) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  try {
    binding.copyfileSync(req.handle, src, dst, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'copyfile',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }
}

async function cp(src, dst, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (!opts) opts = {}

  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  let err = null
  try {
    const st = await lstat(src)

    if (st.isDirectory()) {
      if (opts.recursive !== true) {
        throw new FileError('is a directory', { operation: 'cp', code: 'EISDIR', path: src })
      }

      try {
        await lstat(dst)
      } catch (e) {
        if (e.code !== 'ENOENT') throw e

        await mkdir(dst, { mode: st.mode, recursive: true })
      }

      const dir = await opendir(src)
      for await (const { name } of dir) {
        await cp(path.join(src, name), path.join(dst, name), opts)
      }
    } else if (st.isFile()) {
      await copyFile(src, dst)
      await chmod(dst, st.mode)
    }
  } catch (e) {
    err = e
  }

  return done(err, cb)
}

function cpSync(src, dst, opts = {}) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const st = lstatSync(src)

  if (st.isDirectory()) {
    if (opts.recursive !== true) {
      throw new FileError('is a directory', { operation: 'cp', code: 'EISDIR', path: src })
    }

    try {
      lstatSync(dst)
    } catch (e) {
      if (e.code !== 'ENOENT') throw e

      mkdirSync(dst, { mode: st.mode, recursive: true })
    }

    const dir = opendirSync(src)
    for (const { name } of dir) {
      cpSync(path.join(src, name), path.join(dst, name), opts)
    }
  } else if (st.isFile()) {
    copyFileSync(src, dst)
    chmodSync(dst, st.mode)
  }
}

async function realpath(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let res
  let err = null
  try {
    binding.realpath(req.handle, filepath)

    await req

    res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'realpath',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, res, cb)
}

function realpathSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.realpathSync(req.handle, filepath)

    let res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)

    return res
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'realpath',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function readlink(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let res
  let err = null
  try {
    binding.readlink(req.handle, filepath)

    await req

    res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'readlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, res, cb)
}

function readlinkSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.readlinkSync(req.handle, filepath)

    let res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)

    return res
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'readlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function fsync(fd, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fsync(req.handle, fd)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fsync', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fsyncSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.fsyncSync(req.handle, fd)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fsyncSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function fdatasync(fd, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fdatasync(req.handle, fd)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fdatasync', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fdatasyncSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.fdatasyncSync(req.handle, fd)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fdatasyncSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

function normalizeSymlinkTarget(target, type, filepath) {
  if (isWindows) {
    if (type === constants.UV_FS_SYMLINK_JUNCTION) target = path.resolve(filepath, '..', target)

    if (path.isAbsolute(target)) return path.toNamespacedPath(target)

    return target.replace(/\//g, path.sep)
  }

  return target
}

async function symlink(target, filepath, type, cb) {
  if (typeof type === 'function') {
    cb = type
    type = null
  }

  filepath = toNamespacedPath(filepath)

  if (typeof type === 'string') {
    switch (type) {
      case 'dir':
        type = constants.UV_FS_SYMLINK_DIR
        break
      case 'junction':
        type = constants.UV_FS_SYMLINK_JUNCTION
        break
      case 'file':
      default:
        type = 0
        break
    }
  } else if (typeof type !== 'number') {
    if (isWindows) {
      target = path.resolve(filepath, '..', target)

      try {
        type = (await stat(target)).isDirectory()
          ? constants.UV_FS_SYMLINK_DIR
          : constants.UV_FS_SYMLINK_JUNCTION
      } catch {
        type = 0
      }
    } else {
      type = 0
    }
  }

  target = normalizeSymlinkTarget(target, type, filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.symlink(req.handle, target, filepath, type)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'symlink',
      code: e.code,
      path: target,
      destination: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function symlinkSync(target, filepath, type) {
  filepath = toNamespacedPath(filepath)

  if (typeof type === 'string') {
    switch (type) {
      case 'dir':
        type = constants.UV_FS_SYMLINK_DIR
        break
      case 'junction':
        type = constants.UV_FS_SYMLINK_JUNCTION
        break
      case 'file':
      default:
        type = 0
        break
    }
  } else if (typeof type !== 'number') {
    if (isWindows) {
      target = path.resolve(filepath, '..', target)

      try {
        type = statSync(target).isDirectory()
          ? constants.UV_FS_SYMLINK_DIR
          : constants.UV_FS_SYMLINK_JUNCTION
      } catch {
        type = 0
      }
    } else {
      type = 0
    }
  }

  target = normalizeSymlinkTarget(target, type, filepath)

  const req = FileRequest.borrow()

  try {
    binding.symlinkSync(req.handle, target, filepath, type)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'symlink',
      code: e.code,
      path: target,
      destination: filepath
    })
  } finally {
    req.return()
  }
}

async function opendir(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let dir
  let err = null
  try {
    binding.opendir(req.handle, filepath)

    await req

    dir = new Dir(filepath, binding.requestResultDir(req.handle), opts)
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'opendir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, dir, cb)
}

function opendirSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.opendirSync(req.handle, filepath)

    return new Dir(filepath, binding.requestResultDir(req.handle), opts)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'opendir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function readdir(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { withFileTypes = false, recursive = false } = opts

  filepath = toNamespacedPath(filepath)

  const queue = [filepath]
  let result = []
  let err = null
  try {
    while (queue.length !== 0) {
      const dir = await opendir(queue.pop())

      for await (const entry of dir) {
        const entryPath = path.join(entry.parentPath, entry.name)

        if (withFileTypes) {
          result.push(entry)
        } else {
          result.push(path.relative(filepath, entryPath))
        }

        if (recursive && entry.isDirectory()) queue.push(entryPath)
      }
    }
  } catch (e) {
    result = []
    err = e
  }

  return done(err, result, cb)
}

function readdirSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { withFileTypes = false, recursive = false } = opts

  filepath = toNamespacedPath(filepath)

  const queue = [filepath]
  const result = []

  while (queue.length !== 0) {
    const dir = opendirSync(queue.pop(), opts)

    for (const entry of dir) {
      const entryPath = path.join(entry.parentPath, entry.name)

      if (withFileTypes) {
        result.push(entry)
      } else {
        result.push(path.relative(filepath, entryPath))
      }

      if (recursive && entry.isDirectory()) queue.push(entryPath)
    }
  }

  return result
}

async function readFile(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'buffer' } = opts

  let fd = -1
  let buffer = null
  let err = null
  try {
    fd = await open(filepath, opts.flag || 'r')

    const st = await fstat(fd)

    let len = 0

    if (st.size === 0) {
      const buffers = []

      while (true) {
        buffer = Buffer.allocUnsafe(8192)
        const r = await read(fd, buffer)
        len += r
        if (r === 0) break
        buffers.push(buffer.subarray(0, r))
      }

      buffer = Buffer.concat(buffers)
    } else {
      buffer = Buffer.allocUnsafe(st.size)

      while (true) {
        const r = await read(fd, len ? buffer.subarray(len) : buffer)
        len += r
        if (r === 0 || len === buffer.byteLength) break
      }

      if (len !== buffer.byteLength) buffer = buffer.subarray(0, len)
    }

    if (encoding !== 'buffer') buffer = buffer.toString(encoding)
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) await close(fd)
  }

  return done(err, buffer, cb)
}

function readFileSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'buffer' } = opts

  let fd = -1
  try {
    fd = openSync(filepath, opts.flag || 'r')

    const st = fstatSync(fd)

    let buffer
    let len = 0

    if (st.size === 0) {
      const buffers = []

      while (true) {
        buffer = Buffer.allocUnsafe(8192)
        const r = readSync(fd, buffer)
        len += r
        if (r === 0) break
        buffers.push(buffer.subarray(0, r))
      }

      buffer = Buffer.concat(buffers)
    } else {
      buffer = Buffer.allocUnsafe(st.size)

      while (true) {
        const r = readSync(fd, len ? buffer.subarray(len) : buffer)
        len += r
        if (r === 0 || len === buffer.byteLength) break
      }

      if (len !== buffer.byteLength) buffer = buffer.subarray(0, len)
    }

    if (encoding !== 'buffer') buffer = buffer.toString(encoding)

    return buffer
  } finally {
    if (fd !== -1) closeSync(fd)
  }
}

async function writeFile(filepath, data, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (typeof data === 'string') data = Buffer.from(data, opts.encoding)

  let fd = -1
  let len = 0
  let err = null
  try {
    fd = await open(filepath, opts.flag || 'w', opts.mode || 0o666)

    while (true) {
      len += await write(fd, len ? data.subarray(len) : data)
      if (len === data.byteLength) break
    }
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) await close(fd)
  }

  return done(err, len, cb)
}

function writeFileSync(filepath, data, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (typeof data === 'string') data = Buffer.from(data, opts.encoding)

  let fd = -1
  try {
    fd = openSync(filepath, opts.flag || 'w', opts.mode || 0o666)

    let len = 0

    while (true) {
      len += writeSync(fd, len ? data.subarray(len) : data)
      if (len === data.byteLength) break
    }
  } finally {
    if (fd !== -1) closeSync(fd)
  }
}

function appendFile(filepath, data, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (!opts.flag) opts = { ...opts, flag: 'a' }

  return writeFile(filepath, data, opts, cb)
}

function appendFileSync(filepath, data, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (!opts.flag) opts = { ...opts, flag: 'a' }

  return writeFileSync(filepath, data, opts)
}

function watch(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  return new Watcher(filepath, opts, cb)
}

class Stats {
  constructor(
    dev,
    mode,
    nlink,
    uid,
    gid,
    rdev,
    blksize,
    ino,
    size,
    blocks,
    atimeMs,
    mtimeMs,
    ctimeMs,
    birthtimeMs
  ) {
    this.dev = dev
    this.mode = mode
    this.nlink = nlink
    this.uid = uid
    this.gid = gid
    this.rdev = rdev
    this.blksize = blksize
    this.ino = ino
    this.size = size
    this.blocks = blocks
    this.atimeMs = atimeMs
    this.mtimeMs = mtimeMs
    this.ctimeMs = ctimeMs
    this.birthtimeMs = birthtimeMs
    this.atime = new Date(atimeMs)
    this.mtime = new Date(mtimeMs)
    this.ctime = new Date(ctimeMs)
    this.birthtime = new Date(birthtimeMs)
  }

  isDirectory() {
    return (this.mode & constants.S_IFMT) === constants.S_IFDIR
  }

  isFile() {
    return (this.mode & constants.S_IFMT) === constants.S_IFREG
  }

  isBlockDevice() {
    return (this.mode & constants.S_IFMT) === constants.S_IFBLK
  }

  isCharacterDevice() {
    return (this.mode & constants.S_IFMT) === constants.S_IFCHR
  }

  isFIFO() {
    return (this.mode & constants.S_IFMT) === constants.S_IFIFO
  }

  isSymbolicLink() {
    return (this.mode & constants.S_IFMT) === constants.S_IFLNK
  }

  isSocket() {
    return (this.mode & constants.S_IFMT) === constants.S_IFSOCK
  }
}

class StatFs {
  constructor(type, bsize, blocks, bfree, bavail, files, ffree) {
    this.type = type
    this.bsize = bsize
    this.blocks = blocks
    this.bfree = bfree
    this.bavail = bavail
    this.files = files
    this.ffree = ffree
  }
}

class Dir {
  constructor(path, handle, opts = {}) {
    const { encoding = 'utf8', bufferSize = 32 } = opts

    this.path = path

    this._encoding = encoding
    this._capacity = bufferSize
    this._buffer = new FIFO()
    this._ended = false
    this._handle = handle
  }

  async read(cb) {
    if (this._buffer.length) return ok(this._buffer.shift(), cb)
    if (this._ended) return ok(null, cb)

    const req = FileRequest.borrow()

    let entries
    let err = null
    try {
      req.retain(binding.readdir(req.handle, this._handle, this._capacity))

      await req

      entries = binding.requestResultDirents(req.handle)
    } catch (e) {
      err = new FileError(e.message, {
        operation: 'readdir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    if (err) return fail(err, cb)

    if (entries.length === 0) {
      this._ended = true

      return ok(null, cb)
    }

    for (const entry of entries) {
      let name = Buffer.from(entry.name)

      if (this._encoding !== 'buffer') name = name.toString(this._encoding)

      this._buffer.push(new Dirent(this.path, name, entry.type))
    }

    return ok(this._buffer.shift(), cb)
  }

  readSync() {
    if (this._buffer.length) return this._buffer.shift()
    if (this._ended) return null

    const req = FileRequest.borrow()

    let entries
    try {
      req.retain(binding.readdirSync(req.handle, this._handle, this._capacity))

      entries = binding.requestResultDirents(req.handle)
    } catch (e) {
      throw new FileError(e.message, {
        operation: 'readdir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    if (entries.length === 0) {
      this._ended = true

      return null
    }

    for (const entry of entries) {
      let name = Buffer.from(entry.name)

      if (this._encoding !== 'buffer') name = name.toString(this._encoding)

      this._buffer.push(new Dirent(this.path, name, entry.type))
    }

    return this._buffer.shift()
  }

  async close(cb) {
    const req = FileRequest.borrow()

    let err = null
    try {
      binding.closedir(req.handle, this._handle)

      await req
    } catch (e) {
      err = new FileError(e.message, {
        operation: 'closedir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    this._handle = null

    return done(err, cb)
  }

  closeSync() {
    const req = FileRequest.borrow()

    try {
      binding.closedirSync(req.handle, this._handle)
    } catch (e) {
      throw new FileError(e.message, {
        operation: 'closedir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    this._handle = null
  }

  [Symbol.dispose]() {
    this.closeSync()
  }

  async [Symbol.asyncDispose]() {
    await this.close()
  }

  *[Symbol.iterator]() {
    while (true) {
      const entry = this.readSync()
      if (entry === null) break
      yield entry
    }

    this.closeSync()
  }

  async *[Symbol.asyncIterator]() {
    while (true) {
      const entry = await this.read()
      if (entry === null) break
      yield entry
    }

    await this.close()
  }
}

class Dirent {
  constructor(parentPath, name, type) {
    this.parentPath = parentPath
    this.name = name
    this.type = type
  }

  isFile() {
    return this.type === constants.UV_DIRENT_FILE
  }

  isDirectory() {
    return this.type === constants.UV_DIRENT_DIR
  }

  isSymbolicLink() {
    return this.type === constants.UV_DIRENT_LINK
  }

  isFIFO() {
    return this.type === constants.UV_DIRENT_FIFO
  }

  isSocket() {
    return this.type === constants.UV_DIRENT_SOCKET
  }

  isCharacterDevice() {
    return this.type === constants.UV_DIRENT_CHAR
  }

  isBlockDevice() {
    return this.type === constants.UV_DIRENT_BLOCK
  }
}

class FileReadStream extends Readable {
  constructor(path, opts = {}) {
    const { eagerOpen = true } = opts

    super({ eagerOpen, ...opts })

    this.path = path
    this.fd = typeof opts.fd === 'number' ? opts.fd : -1
    this.flags = opts.flags || 'r'
    this.mode = opts.mode || 0o666

    this._offset = opts.start || 0
    this._missing = 0

    if (opts.length) {
      this._missing = opts.length
    } else if (typeof opts.end === 'number') {
      this._missing = opts.end - this._offset + 1
    } else {
      this._missing = -1
    }
  }

  async _open(cb) {
    let err

    if (this.fd === -1) {
      err = null
      try {
        this.fd = await open(this.path, this.flags, this.mode)
      } catch (e) {
        err = e
      }

      if (err) return cb(err)
    }

    let st
    err = null
    try {
      st = await fstat(this.fd)
    } catch (e) {
      err = e
    }

    if (err) return cb(err)

    if (this._missing === -1) this._missing = st.size

    if (st.size < this._offset) {
      this._offset = st.size
      this._missing = 0
    } else if (st.size < this._offset + this._missing) {
      this._missing = st.size - this._offset
    }

    cb(null)
  }

  async _read(size) {
    if (this._missing <= 0) return this.push(null)

    const data = Buffer.allocUnsafe(Math.min(this._missing, size))

    let len
    let err = null
    try {
      len = await read(this.fd, data, 0, data.byteLength, this._offset)
    } catch (e) {
      err = e
    }

    if (err) return this.destroy(err)

    if (len === 0) return this.push(null)

    if (this._missing < len) len = this._missing

    this._missing -= len
    this._offset += len

    this.push(data.subarray(0, len))
  }

  async _destroy(err, cb) {
    if (this.fd === -1) return cb(err)

    try {
      await close(this.fd)
    } catch (e) {
      err = err || e
    }

    cb(err)
  }
}

class FileWriteStream extends Writable {
  constructor(path, opts = {}) {
    const { eagerOpen = true } = opts

    super({ eagerOpen, ...opts })

    this.path = path
    this.fd = typeof opts.fd === 'number' ? opts.fd : -1
    this.flags = opts.flags || 'w'
    this.mode = opts.mode || 0o666
  }

  async _open(cb) {
    if (this.fd !== -1) return cb(null)

    let err = null
    try {
      this.fd = await open(this.path, this.flags, this.mode)
    } catch (e) {
      err = e
    }

    cb(err)
  }

  async _writev(batch, cb) {
    let err = null
    try {
      await writev(
        this.fd,
        batch.map(({ chunk }) => chunk)
      )
    } catch (e) {
      err = e
    }

    cb(err)
  }

  async _destroy(err, cb) {
    if (this.fd === -1) return cb(err)

    try {
      await close(this.fd)
    } catch (e) {
      err = err || e
    }

    cb(err)
  }
}

class Watcher extends EventEmitter {
  constructor(path, opts, onchange) {
    if (typeof opts === 'function') {
      onchange = opts
      opts = {}
    }

    if (!opts) opts = {}

    const { persistent = true, recursive = false, encoding = 'utf8' } = opts

    super()

    this._closed = false
    this._encoding = encoding
    this._handle = binding.watcherInit(path, recursive, this, this._onevent, this._onclose)

    if (!persistent) this.unref()

    if (onchange) this.on('change', onchange)
  }

  close() {
    if (this._closed) return
    this._closed = true

    binding.watcherClose(this._handle)
  }

  ref() {
    if (this._handle) binding.watcherRef(this._handle)
    return this
  }

  unref() {
    if (this._handle) binding.watcherUnref(this._handle)
    return this
  }

  [Symbol.asyncIterator]() {
    const buffer = []
    let done = false
    let error = null
    let next = null

    this.on('change', (eventType, filename) => {
      if (next) {
        next.resolve({ done: false, value: { eventType, filename } })
        next = null
      } else {
        buffer.push({ eventType, filename })
      }
    })
      .on('error', (err) => {
        done = true
        error = err

        if (next) {
          next.reject(error)
          next = null
        }
      })
      .on('close', () => {
        done = true

        if (next) {
          next.resolve({ done })
          next = null
        }
      })

    return {
      next: () =>
        new Promise((resolve, reject) => {
          if (error) return reject(error)

          if (buffer.length) return resolve({ done: false, value: buffer.shift() })

          if (done) return resolve({ done })

          next = { resolve, reject }
        })
    }
  }

  _onevent(err, events, filename) {
    if (err) {
      this.close()
      this.emit('error', err)
    } else {
      const path =
        this._encoding === 'buffer'
          ? Buffer.from(filename)
          : Buffer.from(filename).toString(this._encoding)

      if (events & binding.UV_RENAME) {
        this.emit('change', 'rename', path)
      }

      if (events & binding.UV_CHANGE) {
        this.emit('change', 'change', path)
      }
    }
  }

  _onclose() {
    this._handle = null

    this.emit('close')
  }
}

exports.access = access
exports.appendFile = appendFile
exports.chmod = chmod
exports.chown = chown
exports.close = close
exports.copyFile = copyFile
exports.cp = cp
exports.exists = exists
exports.fchmod = fchmod
exports.fchown = fchown
exports.fdatasync = fdatasync
exports.fstat = fstat
exports.fsync = fsync
exports.ftruncate = ftruncate
exports.futimes = futimes
exports.lchown = lchown
exports.lutimes = lutimes
exports.link = link
exports.lstat = lstat
exports.mkdir = mkdir
exports.mkdtemp = mkdtemp
exports.open = open
exports.opendir = opendir
exports.read = read
exports.readFile = readFile
exports.readdir = readdir
exports.readlink = readlink
exports.readv = readv
exports.realpath = realpath
exports.rename = rename
exports.rm = rm
exports.rmdir = rmdir
exports.stat = stat
exports.statfs = statfs
exports.symlink = symlink
exports.truncate = truncate
exports.unlink = unlink
exports.utimes = utimes
exports.watch = watch
exports.write = write
exports.writeFile = writeFile
exports.writev = writev

exports.accessSync = accessSync
exports.appendFileSync = appendFileSync
exports.chmodSync = chmodSync
exports.chownSync = chownSync
exports.closeSync = closeSync
exports.copyFileSync = copyFileSync
exports.cpSync = cpSync
exports.existsSync = existsSync
exports.fchmodSync = fchmodSync
exports.fchownSync = fchownSync
exports.fdatasyncSync = fdatasyncSync
exports.fstatSync = fstatSync
exports.fsyncSync = fsyncSync
exports.ftruncateSync = ftruncateSync
exports.futimesSync = futimesSync
exports.lchownSync = lchownSync
exports.lutimesSync = lutimesSync
exports.linkSync = linkSync
exports.lstatSync = lstatSync
exports.mkdirSync = mkdirSync
exports.mkdtempSync = mkdtempSync
exports.openSync = openSync
exports.opendirSync = opendirSync
exports.readFileSync = readFileSync
exports.readSync = readSync
exports.readdirSync = readdirSync
exports.readlinkSync = readlinkSync
exports.readvSync = readvSync
exports.realpathSync = realpathSync
exports.renameSync = renameSync
exports.rmSync = rmSync
exports.rmdirSync = rmdirSync
exports.statSync = statSync
exports.statfsSync = statfsSync
exports.symlinkSync = symlinkSync
exports.truncateSync = truncateSync
exports.unlinkSync = unlinkSync
exports.utimesSync = utimesSync
exports.writeFileSync = writeFileSync
exports.writeSync = writeSync
exports.writevSync = writevSync

exports.promises = require('./promises')

exports.Stats = Stats
exports.StatFs = StatFs
exports.Dir = Dir
exports.Dirent = Dirent
exports.Watcher = Watcher

exports.ReadStream = FileReadStream

exports.createReadStream = function createReadStream(path, opts) {
  return new FileReadStream(path, opts)
}

exports.WriteStream = FileWriteStream

exports.createWriteStream = function createWriteStream(path, opts) {
  return new FileWriteStream(path, opts)
}

function toNamespacedPath(filepath) {
  if (typeof filepath !== 'string') {
    if (isURL(filepath)) filepath = fileURLToPath(filepath)
    else filepath = filepath.toString()
  }

  return path.toNamespacedPath(filepath)
}

function toFlags(flags) {
  switch (flags) {
    case 'r':
      return constants.O_RDONLY
    case 'rs': // Fall through.
    case 'sr':
      return constants.O_RDONLY | constants.O_SYNC
    case 'r+':
      return constants.O_RDWR
    case 'rs+': // Fall through.
    case 'sr+':
      return constants.O_RDWR | constants.O_SYNC

    case 'w':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_WRONLY
    case 'wx': // Fall through.
    case 'xw':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_WRONLY | constants.O_EXCL

    case 'w+':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_RDWR
    case 'wx+': // Fall through.
    case 'xw+':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_RDWR | constants.O_EXCL

    case 'a':
      return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY
    case 'ax': // Fall through.
    case 'xa':
      return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY | constants.O_EXCL
    case 'as': // Fall through.
    case 'sa':
      return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY | constants.O_SYNC

    case 'a+':
      return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR
    case 'ax+': // Fall through.
    case 'xa+':
      return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR | constants.O_EXCL
    case 'as+': // Fall through.
    case 'sa+':
      return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR | constants.O_SYNC
    default:
      return 0
  }
}

function toMode(mode) {
  return parseInt(mode, 8)
}
const binding = require('../binding')

module.exports = {
  O_RDWR: binding.O_RDWR,
  O_RDONLY: binding.O_RDONLY,
  O_WRONLY: binding.O_WRONLY,
  O_CREAT: binding.O_CREAT,
  O_TRUNC: binding.O_TRUNC,
  O_APPEND: binding.O_APPEND,

  F_OK: binding.F_OK || 0,
  R_OK: binding.R_OK || 0,
  W_OK: binding.W_OK || 0,
  X_OK: binding.X_OK || 0,

  S_IFMT: binding.S_IFMT,
  S_IFREG: binding.S_IFREG,
  S_IFDIR: binding.S_IFDIR,
  S_IFCHR: binding.S_IFCHR,
  S_IFLNK: binding.S_IFLNK,
  S_IFBLK: binding.S_IFBLK || 0,
  S_IFIFO: binding.S_IFIFO || 0,
  S_IFSOCK: binding.S_IFSOCK || 0,

  S_IRUSR: binding.S_IRUSR || 0,
  S_IWUSR: binding.S_IWUSR || 0,
  S_IXUSR: binding.S_IXUSR || 0,
  S_IRGRP: binding.S_IRGRP || 0,
  S_IWGRP: binding.S_IWGRP || 0,
  S_IXGRP: binding.S_IXGRP || 0,
  S_IROTH: binding.S_IROTH || 0,
  S_IWOTH: binding.S_IWOTH || 0,
  S_IXOTH: binding.S_IXOTH || 0,

  UV_DIRENT_UNKNOWN: binding.UV_DIRENT_UNKNOWN,
  UV_DIRENT_FILE: binding.UV_DIRENT_FILE,
  UV_DIRENT_DIR: binding.UV_DIRENT_DIR,
  UV_DIRENT_LINK: binding.UV_DIRENT_LINK,
  UV_DIRENT_FIFO: binding.UV_DIRENT_FIFO,
  UV_DIRENT_SOCKET: binding.UV_DIRENT_SOCKET,
  UV_DIRENT_CHAR: binding.UV_DIRENT_CHAR,
  UV_DIRENT_BLOCK: binding.UV_DIRENT_BLOCK,

  COPYFILE_EXCL: binding.UV_FS_COPYFILE_EXCL,
  COPYFILE_FICLONE: binding.UV_FS_COPYFILE_FICLONE,
  COPYFILE_FICLONE_FORCE: binding.UV_FS_COPYFILE_FICLONE_FORCE,
  UV_FS_SYMLINK_DIR: binding.UV_FS_SYMLINK_DIR,
  UV_FS_SYMLINK_JUNCTION: binding.UV_FS_SYMLINK_JUNCTION
}
const os = require('bare-os')

module.exports = class FileError extends Error {
  constructor(msg, opts = {}) {
    const { code, operation = null, path = null, destination = null, fd = -1 } = opts

    if (operation !== null) msg += describe(operation, opts)

    super(`${code}: ${msg}`)

    this.code = code

    if (operation !== null) this.operation = operation
    if (path !== null) this.path = path
    if (destination !== null) this.destination = destination
    if (fd !== -1) this.fd = fd
  }

  get name() {
    return 'FileError'
  }

  // For Node.js compatibility
  get errno() {
    return os.constants.errnos[this.code]
  }

  // For Node.js compatibility
  get syscall() {
    return this.operation
  }

  // For Node.js compatibility
  get dest() {
    return this.destination
  }
}

function describe(operation, opts) {
  const { path = null, destination = null, fd = -1 } = opts

  let result = `, ${operation}`

  if (path !== null) {
    result += ` ${JSON.stringify(path)}`

    if (destination !== null) {
      result += ` -> ${JSON.stringify(destination)}`
    }
  } else if (fd !== -1) {
    result += ` ${fd}`
  }

  return result
}
{
  "name": "bare-fs",
  "version": "4.7.2",
  "description": "Native file system operations for Bare",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./promises": {
      "types": "./promises.d.ts",
      "default": "./promises.js"
    },
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "promises.js",
    "promises.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-fs.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-fs/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-fs#readme",
  "engines": {
    "bare": ">=1.16.0"
  },
  "dependencies": {
    "bare-events": "^2.5.4",
    "bare-path": "^3.0.0",
    "bare-stream": "^2.6.4",
    "bare-url": "^2.2.2",
    "fast-fifo": "^1.3.2"
  },
  "devDependencies": {
    "bare-buffer": "^3.0.2",
    "bare-crypto": "^1.11.2",
    "brittle": "^3.1.1",
    "cmake-bare": "^1.1.7",
    "lunte": "^1.6.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "bare-buffer": "*"
  },
  "peerDependenciesMeta": {
    "bare-buffer": {
      "optional": true
    }
  }
}
const EventEmitter = require('bare-events')
const fs = require('.')

class FileHandle extends EventEmitter {
  constructor(fd) {
    super()

    this.fd = fd
  }

  async close() {
    await fs.close(this.fd)

    this.fd = -1
    this.emit('close')
  }

  async read(buffer, ...args) {
    return {
      bytesRead: await fs.read(this.fd, buffer, ...args),
      buffer
    }
  }

  async readv(buffers, ...args) {
    return {
      bytesRead: await fs.readv(this.fd, buffers, ...args),
      buffers
    }
  }

  async write(buffer, ...args) {
    return {
      bytesWritten: await fs.write(this.fd, buffer, ...args),
      buffer
    }
  }

  async writev(buffers, ...args) {
    return {
      bytesWritten: await fs.writev(this.fd, buffers, ...args),
      buffers
    }
  }

  async stat() {
    return fs.fstat(this.fd)
  }

  async chmod(mode) {
    await fs.fchmod(this.fd, mode)
  }

  async chown(uid, gid) {
    await fs.fchown(this.fd, uid, gid)
  }

  async datasync() {
    return fs.fdatasync(this.fd)
  }

  async sync() {
    return fs.fsync(this.fd)
  }

  async truncate(len) {
    await fs.ftruncate(this.fd, len)
  }

  async utimes(atime, mtime) {
    await fs.futimes(this.fd, atime, mtime)
  }

  createReadStream(opts) {
    return fs.createReadStream(null, { ...opts, fd: this.fd })
  }

  createWriteStream(opts) {
    return fs.createWriteStream(null, { ...opts, fd: this.fd })
  }

  async [Symbol.asyncDispose]() {
    await this.close()
  }
}

exports.open = async function open(filepath, flags, mode) {
  return new FileHandle(await fs.open(filepath, flags, mode))
}

exports.access = fs.access
exports.appendFile = fs.appendFile
exports.chmod = fs.chmod
exports.chown = fs.chown
exports.constants = fs.constants
exports.copyFile = fs.copyFile
exports.cp = fs.cp
exports.lchown = fs.lchown
exports.lutimes = fs.lutimes
exports.link = fs.link
exports.lstat = fs.lstat
exports.mkdir = fs.mkdir
exports.mkdtemp = fs.mkdtemp
exports.opendir = fs.opendir
exports.readFile = fs.readFile
exports.readdir = fs.readdir
exports.readlink = fs.readlink
exports.realpath = fs.realpath
exports.rename = fs.rename
exports.rm = fs.rm
exports.rmdir = fs.rmdir
exports.stat = fs.stat
exports.statfs = fs.statfs
exports.truncate = fs.truncate
exports.symlink = fs.symlink
exports.unlink = fs.unlink
exports.utimes = fs.utimes
exports.watch = fs.watch
exports.writeFile = fs.writeFile
module.exports = require.addon()
const binding = require('./binding')

module.exports = exports = function hrtime(past) {
  let now = binding.hrtime()

  if (past) now -= BigInt(past[0]) * 1000000000n + BigInt(past[1])

  return [Number(now / 1000000000n), Number(now % 1000000000n)]
}

exports.bigint = function hrtime() {
  return binding.hrtime()
}
{
  "name": "bare-hrtime",
  "version": "2.1.1",
  "description": "High-resolution timers for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-hrtime.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-hrtime/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-hrtime#readme",
  "devDependencies": {
    "brittle": "^3.2.1",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  }
}
const errors = require('./lib/errors')

const constants = {
  REQUEST: 1,
  RESPONSE: 2,
  DATA: 3,
  END: 4
}

const TAB = 0x09
const LF = 0x0a
const CR = 0x0d
const SP = 0x20
const ZERO = 0x30
const NINE = 0x39
const UPPER_A = 0x41
const UPPER_F = 0x46
const UPPER_Z = 0x5a
const LOWER_A = 0x61
const LOWER_F = 0x66
const COLON = 0x3a

const MAX_CHUNK_SIZE_LENGTH = 16

// Header states
const FIRST_TOKEN = 0
const REQUEST_URL = 1
const REQUEST_VERSION = 2
const STATUS_CODE = 3
const STATUS_REASON = 4
const FIRST_LINE_LF = 5
const HEADER_START = 6
const HEADER_NAME = 7
const HEADER_VALUE_WS = 8
const HEADER_VALUE = 9
const HEADER_LINE_LF = 10
const HEADER_END_LF = 11

// Body states
const BODY = 12
const CHUNK_SIZE = 13
const CHUNK_SIZE_LF = 14
const CHUNK_DATA = 15
const CHUNK_EXTENSION = 16

// Trailing states
const LAST_CHUNK_LF = 17
const TRAILER_CR = 18
const TRAILER_LF = 19

module.exports = exports = class HTTPParser {
  constructor(opts = {}) {
    const { maxHeaderSize = 16384, maxHeadersCount = 2000 } = opts

    this._maxHeaderSize = maxHeaderSize
    this._maxHeadersCount = maxHeadersCount
    this._state = FIRST_TOKEN
    this._buffer = []
    this._bufferIndex = 0
    this._byteIndex = 0
    this._buffered = 0
    this._accumulator = []

    this._isResponse = false
    this._method = ''
    this._url = ''
    this._version = ''
    this._code = 0
    this._reason = ''

    this._headerName = ''
    this._headers = {}
    this._headerCount = 0
    this._headerSize = 0

    this._remaining = 0
  }

  *push(data, encoding) {
    if (typeof data === 'string') data = Buffer.from(data, encoding)

    this._buffer.push(data)
    this._buffered += data.byteLength

    yield* this._parse()

    this._compact()
  }

  end() {
    const buffers = this._buffer
    const bufferIndex = this._bufferIndex
    const byteIndex = this._byteIndex

    this._buffer = []
    this._bufferIndex = 0
    this._byteIndex = 0
    this._buffered = 0

    if (bufferIndex >= buffers.length) return Buffer.alloc(0)

    buffers[bufferIndex] = buffers[bufferIndex].subarray(byteIndex)

    const remaining = buffers.slice(bufferIndex)

    if (remaining.length === 0) return Buffer.alloc(0)
    if (remaining.length === 1) return remaining[0]

    return Buffer.concat(remaining)
  }

  _compact() {
    if (this._bufferIndex > 0) {
      this._buffer = this._buffer.slice(this._bufferIndex)
      this._bufferIndex = 0
    }

    if (this._byteIndex > 0 && this._buffer.length > 0) {
      this._buffer[0] = this._buffer[0].subarray(this._byteIndex)
      this._byteIndex = 0
    }
  }

  _consume(n) {
    this._buffered -= n

    const current = this._buffer[this._bufferIndex]

    if (this._byteIndex + n <= current.byteLength) {
      const slice = current.subarray(this._byteIndex, this._byteIndex + n)

      this._byteIndex += n

      if (this._byteIndex >= current.byteLength) {
        this._bufferIndex++
        this._byteIndex = 0
      }

      return slice
    }

    const result = Buffer.allocUnsafe(n)

    let written = 0

    while (written < n) {
      const buffer = this._buffer[this._bufferIndex]
      const available = buffer.byteLength - this._byteIndex
      const take = Math.min(available, n - written)

      buffer.copy(result, written, this._byteIndex, this._byteIndex + take)

      written += take

      this._byteIndex += take

      if (this._byteIndex >= buffer.byteLength) {
        this._bufferIndex++
        this._byteIndex = 0
      }
    }

    return result
  }

  _buildString() {
    const string = String.fromCharCode.apply(null, this._accumulator)

    this._accumulator = []

    return string
  }

  _checkHeaderSize() {
    if (++this._headerSize > this._maxHeaderSize) {
      throw errors.INVALID_MESSAGE('Header exceeds limit of ' + this._maxHeaderSize + ' bytes')
    }
  }

  _storeHeader(name, value) {
    let end = value.length

    while (end > 0 && (value.charCodeAt(end - 1) === SP || value.charCodeAt(end - 1) === TAB)) {
      end--
    }

    if (end < value.length) value = value.substring(0, end)

    this._headerCount++

    if (this._headerCount > this._maxHeadersCount) {
      throw errors.INVALID_MESSAGE('Header count exceeds limit of ' + this._maxHeadersCount)
    }

    switch (name) {
      case '__proto__':
      case 'constructor':
      case 'prototype':
        throw errors.INVALID_HEADER("Unsafe header name '" + name + "'")

      case 'host':
      case 'content-length':
      case 'transfer-encoding':
        if (name in this._headers) {
          throw errors.INVALID_HEADER("Duplicate header '" + name + "'")
        }

        this._headers[name] = value
        break

      default:
        const delimiter = name === 'cookie' ? '; ' : ', '

        if (name in this._headers) {
          this._headers[name] += delimiter + value
        } else {
          this._headers[name] = value
        }
    }
  }

  *_parse() {
    while (true) {
      if (this._state === BODY) {
        if (this._buffered === 0) return

        const available = Math.min(this._buffered, this._remaining)
        const data = this._consume(available)

        this._remaining -= available

        const ended = this._remaining === 0

        if (ended) this._state = FIRST_TOKEN

        yield { type: constants.DATA, data }

        if (ended) yield { type: constants.END }

        continue
      }

      if (this._state === CHUNK_DATA) {
        if (this._buffered < this._remaining) return

        const consumed = this._consume(this._remaining)

        if (consumed[this._remaining - 2] !== CR || consumed[this._remaining - 1] !== LF) {
          throw errors.INVALID_MESSAGE('Expected CRLF after chunk data')
        }

        const data = consumed.subarray(0, this._remaining - 2)

        this._remaining = 0
        this._state = CHUNK_SIZE

        yield { type: constants.DATA, data }

        continue
      }

      if (this._buffered === 0) return

      const byte = this._buffer[this._bufferIndex][this._byteIndex++]

      this._buffered--

      if (this._byteIndex >= this._buffer[this._bufferIndex].byteLength) {
        this._bufferIndex++
        this._byteIndex = 0
      }

      switch (this._state) {
        case FIRST_TOKEN: {
          this._checkHeaderSize()

          if (byte === SP) {
            const token = this._buildString()

            if (token.length === 0) throw errors.INVALID_MESSAGE()

            this._isResponse = token.startsWith('HTTP/')

            if (this._isResponse) {
              if (token !== 'HTTP/1.0' && token !== 'HTTP/1.1') {
                throw errors.INVALID_MESSAGE()
              }

              this._version = token
              this._state = STATUS_CODE
            } else {
              this._method = token
              this._state = REQUEST_URL
            }
          } else if (byte === CR) {
            throw errors.INVALID_MESSAGE()
          } else if (isTokenByte(byte)) {
            this._accumulator.push(byte)
          } else if (
            byte === 0x2f &&
            this._accumulator.length === 4 &&
            this._accumulator[0] === 0x48 &&
            this._accumulator[1] === 0x54 &&
            this._accumulator[2] === 0x54 &&
            this._accumulator[3] === 0x50
          ) {
            this._accumulator.push(byte)
          } else {
            throw errors.INVALID_MESSAGE()
          }

          break
        }

        case REQUEST_URL: {
          this._checkHeaderSize()

          if (byte === SP) {
            this._url = this._buildString()

            if (this._url.length === 0) throw errors.INVALID_MESSAGE()

            this._state = REQUEST_VERSION
          } else if (byte === CR) {
            throw errors.INVALID_MESSAGE()
          } else if (byte >= 0x21 && byte !== 0x7f) {
            this._accumulator.push(byte)
          } else {
            throw errors.INVALID_MESSAGE()
          }

          break
        }

        case REQUEST_VERSION: {
          this._checkHeaderSize()

          if (byte === CR) {
            this._version = this._buildString()

            if (this._version !== 'HTTP/1.0' && this._version !== 'HTTP/1.1') {
              throw errors.INVALID_MESSAGE()
            }

            this._state = FIRST_LINE_LF
          } else if (byte >= 0x21 && byte !== 0x7f) {
            this._accumulator.push(byte)
          } else {
            throw errors.INVALID_MESSAGE()
          }

          break
        }

        case STATUS_CODE: {
          this._checkHeaderSize()

          if (byte === SP) {
            if (this._accumulator.length === 0) throw errors.INVALID_MESSAGE()

            let code = 0

            for (let i = 0, n = this._accumulator.length; i < n; i++) {
              code = code * 10 + this._accumulator[i]
            }

            this._accumulator = []

            if (code < 100 || code > 999) throw errors.INVALID_MESSAGE()

            this._code = code
            this._state = STATUS_REASON
          } else if (byte >= ZERO && byte <= NINE) {
            this._accumulator.push(byte - ZERO)
          } else {
            throw errors.INVALID_MESSAGE()
          }

          break
        }

        case STATUS_REASON: {
          this._checkHeaderSize()

          if (byte === CR) {
            this._reason = this._buildString()
            this._state = FIRST_LINE_LF
          } else if (isFieldByte(byte)) {
            this._accumulator.push(byte)
          } else {
            throw errors.INVALID_MESSAGE()
          }

          break
        }

        case FIRST_LINE_LF: {
          if (byte !== LF) throw errors.INVALID_MESSAGE()

          this._headers = {}
          this._headerCount = 0
          this._state = HEADER_START

          break
        }

        case HEADER_START: {
          this._checkHeaderSize()

          if (byte === CR) {
            this._state = HEADER_END_LF
          } else if (byte !== COLON && isTokenByte(byte)) {
            this._accumulator.push(byte >= UPPER_A && byte <= UPPER_Z ? byte + 0x20 : byte)
            this._state = HEADER_NAME
          } else {
            throw errors.INVALID_HEADER()
          }

          break
        }

        case HEADER_NAME: {
          this._checkHeaderSize()

          if (byte === COLON) {
            this._headerName = this._buildString()
            this._state = HEADER_VALUE_WS
          } else if (byte !== COLON && isTokenByte(byte)) {
            this._accumulator.push(byte >= UPPER_A && byte <= UPPER_Z ? byte + 0x20 : byte)
          } else {
            throw errors.INVALID_HEADER()
          }

          break
        }

        case HEADER_VALUE_WS: {
          this._checkHeaderSize()

          if (byte === SP || byte === TAB) break

          if (byte === CR) {
            this._storeHeader(this._headerName, '')
            this._headerName = ''
            this._state = HEADER_LINE_LF

            break
          }

          if (!isFieldByte(byte)) throw errors.INVALID_HEADER()

          this._accumulator.push(byte)
          this._state = HEADER_VALUE

          break
        }

        case HEADER_VALUE: {
          this._checkHeaderSize()

          if (byte === CR) {
            this._storeHeader(this._headerName, this._buildString())
            this._headerName = ''
            this._state = HEADER_LINE_LF
          } else if (isFieldByte(byte)) {
            this._accumulator.push(byte)
          } else {
            throw errors.INVALID_HEADER()
          }

          break
        }

        case HEADER_LINE_LF: {
          if (byte !== LF) throw errors.INVALID_HEADER()

          this._state = HEADER_START

          break
        }

        case HEADER_END_LF: {
          if (byte !== LF) throw errors.INVALID_MESSAGE()

          const headers = this._headers

          if (this._isResponse) {
            yield {
              type: constants.RESPONSE,
              version: this._version,
              code: this._code,
              reason: this._reason,
              headers
            }
          } else {
            if (this._version === 'HTTP/1.1' && !('host' in headers)) {
              throw errors.INVALID_HEADER("Header 'Host' is missing")
            }

            yield {
              type: constants.REQUEST,
              version: this._version,
              method: this._method,
              url: this._url,
              headers
            }
          }

          const transferEncoding = headers['transfer-encoding']
          const contentLength = headers['content-length']

          const encodings = transferEncoding ? transferEncoding.split(',') : null

          const lastEncoding = encodings
            ? encodings[encodings.length - 1].trim().toLowerCase()
            : null

          if (lastEncoding === 'chunked') {
            if (contentLength) {
              throw errors.INVALID_MESSAGE(
                "Conflicting 'Content-Length' and 'Transfer-Encoding' headers"
              )
            }

            this._state = CHUNK_SIZE
            this._headerSize = 0

            continue
          }

          if (contentLength) {
            if (contentLength.length === 0) throw errors.INVALID_CONTENT_LENGTH()

            let length = 0

            for (let i = 0, n = contentLength.length; i < n; i++) {
              const c = contentLength.charCodeAt(i)

              if (c < ZERO || c > NINE) throw errors.INVALID_CONTENT_LENGTH()

              length = length * 10 + (c - ZERO)
            }

            if (!Number.isSafeInteger(length) || length < 0) {
              throw errors.INVALID_CONTENT_LENGTH()
            }

            if (length === 0) {
              this._state = FIRST_TOKEN
              this._headerSize = 0

              yield { type: constants.END }
            } else {
              this._state = BODY
              this._remaining = length
              this._headerSize = 0
            }
          } else {
            this._state = FIRST_TOKEN
            this._headerSize = 0

            yield { type: constants.END }
          }

          break
        }

        case CHUNK_SIZE: {
          if (byte === CR || byte === 0x3b) {
            if (this._accumulator.length === 0) throw errors.INVALID_CHUNK_LENGTH()

            let length = 0

            for (let i = 0, n = this._accumulator.length; i < n; i++) {
              length = length * 16 + this._accumulator[i]
            }

            this._accumulator = []

            if (!Number.isSafeInteger(length)) throw errors.INVALID_CHUNK_LENGTH()

            if (byte === 0x3b) {
              this._remaining = length
              this._state = CHUNK_EXTENSION
            } else if (length === 0) {
              this._state = LAST_CHUNK_LF
            } else {
              this._remaining = length + 2
              this._state = CHUNK_SIZE_LF
            }
          } else if (isHex(byte)) {
            if (this._accumulator.length >= MAX_CHUNK_SIZE_LENGTH) {
              throw errors.INVALID_CHUNK_LENGTH()
            }

            this._accumulator.push(hexValue(byte))
          } else {
            throw errors.INVALID_CHUNK_LENGTH()
          }

          break
        }

        case CHUNK_EXTENSION: {
          this._checkHeaderSize()

          if (byte === CR) {
            if (this._remaining === 0) {
              this._state = LAST_CHUNK_LF
            } else {
              this._remaining += 2
              this._state = CHUNK_SIZE_LF
            }
          } else if (!isFieldByte(byte)) {
            throw errors.INVALID_CHUNK_LENGTH()
          }

          break
        }

        case CHUNK_SIZE_LF: {
          if (byte !== LF) throw errors.INVALID_CHUNK_LENGTH()

          this._state = CHUNK_DATA

          break
        }

        case LAST_CHUNK_LF: {
          if (byte !== LF) throw errors.INVALID_CHUNK_LENGTH()

          this._state = TRAILER_CR

          break
        }

        case TRAILER_CR: {
          if (byte !== CR) throw errors.INVALID_MESSAGE()

          this._state = TRAILER_LF

          break
        }

        case TRAILER_LF: {
          if (byte !== LF) throw errors.INVALID_MESSAGE()

          this._state = FIRST_TOKEN
          this._headerSize = 0

          yield { type: constants.END }

          break
        }

        default:
          throw errors.INVALID_MESSAGE()
      }
    }
  }
}

exports.constants = constants

const TOKEN_BYTES = Buffer.from([
  // 0x00-0x1f (control characters) + 0x20 (space)
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  // 0x21-0x41: ! " # $ % & ' ( ) * + , - . / 0-9 : ; < = > ? @ A
  1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1,
  // 0x42-0x62: B-Z [ \ ] ^ _ ` a b
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1,
  // 0x63-0x7f: c-z { | } ~ DEL
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0
])

function isTokenByte(b) {
  return TOKEN_BYTES[b] === 1
}

function isFieldByte(b) {
  return b === TAB || (b >= 0x20 && b <= 0x7e)
}

function isHex(b) {
  return (
    (b >= ZERO && b <= NINE) || (b >= UPPER_A && b <= UPPER_F) || (b >= LOWER_A && b <= LOWER_F)
  )
}

function hexValue(b) {
  if (b >= ZERO && b <= NINE) return b - ZERO
  if (b >= UPPER_A && b <= UPPER_F) return b - UPPER_A + 10
  return b - LOWER_A + 10
}
module.exports = class HTTPParserError extends Error {
  constructor(msg, fn = HTTPParserError, code = fn.name) {
    super(`${code}: ${msg}`)

    this.code = code

    if (Error.captureStackTrace) Error.captureStackTrace(this, fn)
  }

  get name() {
    return 'HTTPParserError'
  }

  static INVALID_MESSAGE(msg = 'Invalid HTTP message') {
    return new HTTPParserError(msg, HTTPParserError.INVALID_MESSAGE)
  }

  static INVALID_HEADER(msg = 'Invalid HTTP header') {
    return new HTTPParserError(msg, HTTPParserError.INVALID_HEADER)
  }

  static INVALID_CONTENT_LENGTH(msg = 'Invalid HTTP Content-Length') {
    return new HTTPParserError(msg, HTTPParserError.INVALID_CONTENT_LENGTH)
  }

  static INVALID_CHUNK_LENGTH(msg = 'Invalid HTTP chunk length') {
    return new HTTPParserError(msg, HTTPParserError.INVALID_CHUNK_LENGTH)
  }
}
{
  "name": "bare-http-parser",
  "version": "1.1.3",
  "description": "Streaming HTTP request and response parser for Bare",
  "exports": {
    "./package": "./package.json",
    ".": "./index.js",
    "./errors": "./lib/errors.js"
  },
  "files": [
    "index.js",
    "lib"
  ],
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-http-parser.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-http-parser/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-http-parser#readme",
  "devDependencies": {
    "brittle": "^3.3.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  }
}
exports.IncomingMessage = require('./lib/incoming-message')
exports.OutgoingMessage = require('./lib/outgoing-message')

exports.Agent = require('./lib/agent')
exports.globalAgent = exports.Agent.global

exports.Server = require('./lib/server')
exports.ServerResponse = require('./lib/server-response')
exports.ServerConnection = require('./lib/server-connection')

exports.ClientRequest = require('./lib/client-request')
exports.ClientConnection = require('./lib/client-connection')

exports.constants = require('./lib/constants')
exports.errors = require('./lib/errors')

exports.METHODS = Object.values(exports.constants.method) // For Node.js compatibility
exports.STATUS_CODES = exports.constants.status // For Node.js compatibility

exports.createServer = function createServer(opts, onrequest) {
  return new exports.Server(opts, onrequest)
}

exports.request = function request(url, opts, onresponse) {
  if (typeof opts === 'function') {
    onresponse = opts
    opts = {}
  }

  if (typeof url === 'string') url = new URL(url)

  if (isURL(url)) {
    opts = opts ? { ...url, ...opts } : { ...url }

    opts.host = url.hostname
    opts.path = url.pathname + url.search
    opts.port = url.port ? parseInt(url.port, 10) : defaultPort(url)
  } else {
    opts = url ? { ...url } : {}

    // For Node.js compatibility
    opts.host = opts.hostname || opts.host
    opts.port = typeof opts.port === 'string' ? parseInt(opts.port, 10) : opts.port
  }

  return new exports.ClientRequest(opts, onresponse)
}

exports.get = function get(url, opts, onresponse) {
  const req = exports.request(url, opts, onresponse)
  req.end()
  return req
}

// https://url.spec.whatwg.org/#default-port
function defaultPort(url) {
  switch (url.protocol) {
    case 'ftp:':
      return 21
    case 'http:':
    case 'ws:':
      return 80
    case 'https:':
    case 'wss:':
      return 443
  }

  return null
}

// https://url.spec.whatwg.org/#api
function isURL(url) {
  return (
    url !== null &&
    typeof url === 'object' &&
    typeof url.protocol === 'string' &&
    typeof url.hostname === 'string' &&
    typeof url.pathname === 'string' &&
    typeof url.search === 'string'
  )
}
const EventEmitter = require('bare-events')
const tcp = require('bare-tcp')
const HTTPClientConnection = require('./client-connection')
const errors = require('./errors')

class HTTPSocketSet {
  constructor() {
    this._sockets = new Map()
    this._size = 0
  }

  get size() {
    return this._size
  }

  add(name, socket) {
    const sockets = this._sockets.get(name)

    this._size++

    if (sockets === undefined) this._sockets.set(name, [socket])
    else sockets.push(socket)
  }

  pop(name) {
    const sockets = this._sockets.get(name)
    if (sockets === undefined || sockets.length === 0) return null

    this._size--

    const last = sockets.pop()

    if (sockets.length === 0) this._sockets.delete(name)

    return last
  }

  delete(name, socket) {
    const sockets = this._sockets.get(name)
    if (sockets === undefined) return

    const i = sockets.indexOf(socket)
    if (i === -1) return

    this._size--

    const last = sockets.pop()
    if (last !== socket) sockets[i] = last

    if (sockets.length === 0) this._sockets.delete(name)
  }

  *sockets() {
    for (const sockets of this._sockets.values()) {
      yield* sockets
    }
  }

  *[Symbol.iterator]() {
    for (const [name, sockets] of this._sockets) {
      for (const socket of sockets) yield [name, socket]
    }
  }
}

class HTTPAgent extends EventEmitter {
  constructor(opts = {}) {
    super()

    const { keepAlive = false, keepAliveMsecs = 1000, defaultPort = 80 } = opts

    this._suspended = false
    this._resuming = null

    this._sockets = new HTTPSocketSet()
    this._freeSockets = new HTTPSocketSet()

    this._keepAlive = typeof keepAlive === 'number' ? keepAlive : keepAlive ? keepAliveMsecs : -1
    this._defaultPort = defaultPort

    this._opts = { ...opts }
  }

  get suspended() {
    return this._suspended
  }

  get resumed() {
    return this._resuming ? this._resuming.promise : null
  }

  get sockets() {
    return this._sockets.sockets()
  }

  get freeSockets() {
    return this._freeSockets.sockets()
  }

  get defaultPort() {
    return this._defaultPort
  }

  createConnection(opts) {
    if (this._suspended) throw errors.AGENT_SUSPENDED()

    return tcp.createConnection(opts)
  }

  reuseSocket(socket, req) {
    socket.ref()
  }

  keepSocketAlive(socket) {
    if (this._keepAlive === -1) return false

    socket.setKeepAlive(true, this._keepAlive)
    socket.unref()

    return true
  }

  getName(opts) {
    return `${opts.host}:${opts.port}`
  }

  addRequest(req, opts) {
    opts = { ...opts, ...this._opts }

    const name = this.getName(opts)

    let socket = this._freeSockets.pop(name)

    if (socket) this.reuseSocket(socket, req)
    else {
      const agent = this

      socket = this.createConnection(opts)

      socket
        .on('error', noop) // someone needs to handle it
        .on('free', onfree)
        .on('end', onremove)
        .on('finish', onremove)
        .on('close', onremove)
        .on('timeout', ontimeout)

      function onfree() {
        if (socket.destroyed) return

        if (agent.keepSocketAlive(socket)) {
          agent._freeSockets.add(name, socket)
        } else {
          socket.end()
        }

        agent.emit('free', socket)
      }

      function onremove() {
        socket.off('free', onfree)

        agent._sockets.delete(name, socket)
        agent._freeSockets.delete(name, socket)

        if (agent._sockets.size === 0) HTTPAgent._agents.delete(agent)
      }

      function ontimeout() {
        socket.destroy()

        agent._freeSockets.delete(name, socket)
      }
    }

    if (this._sockets.size === 0) HTTPAgent._agents.add(this)

    this._sockets.add(name, socket)

    req._socket = socket

    const connection = HTTPClientConnection.from(socket, opts)

    connection._req = req
  }

  suspend() {
    if (this._suspended) return

    this._resuming = Promise.withResolvers()
    this._suspended = true

    this.destroy()
  }

  resume() {
    if (this._resuming === null) return

    this._resuming.resolve()
    this._resuming = null
    this._suspended = false
  }

  destroy() {
    for (const socket of this._sockets.sockets()) socket.destroy()
  }

  static _agents = new Set()

  static _onidle() {
    for (const agent of this._agents) {
      agent.destroy()
    }
  }
}

HTTPAgent.global = new HTTPAgent({ keepAlive: 1000, timeout: 5000 })

module.exports = HTTPAgent

Bare.on('idle', HTTPAgent._onidle.bind(HTTPAgent))

function noop() {}
const HTTPParser = require('bare-http-parser')
const HTTPIncomingMessage = require('./incoming-message')
const errors = require('./errors')

const {
  constants: { RESPONSE, DATA, END }
} = HTTPParser

const EMPTY = Buffer.alloc(0)

module.exports = class HTTPClientConnection {
  static _connections = new WeakMap()

  static for(socket) {
    return this._connections.get(socket) || null
  }

  static from(socket, opts) {
    return this.for(socket) || new this(socket, opts)
  }

  constructor(socket, opts = {}) {
    const { IncomingMessage = HTTPIncomingMessage } = opts

    this._socket = socket

    this._req = null
    this._res = null

    this._IncomingMessage = IncomingMessage

    this._parser = new HTTPParser()
    this._idle = true

    this._onerror = this._onerror.bind(this)
    this._onclose = this._onclose.bind(this)
    this._onend = this._onend.bind(this)
    this._ondata = this._ondata.bind(this)
    this._ondrain = this._ondrain.bind(this)
    this._ontimeout = this._ontimeout.bind(this)

    socket
      .on('error', this._onerror)
      .on('close', this._onclose)
      .on('end', this._onend)
      .on('data', this._ondata)
      .on('drain', this._ondrain)
      .on('timeout', this._ontimeout)

    HTTPClientConnection._connections.set(socket, this)
  }

  get socket() {
    return this._socket
  }

  get req() {
    return this._req
  }

  get res() {
    return this._res
  }

  get idle() {
    return this._idle
  }

  _onerror(err) {
    if (this._req) this._req.destroy(err)
  }

  _onclose() {
    if (this._req) this._req.destroy()
  }

  _onend() {
    if (this._req) this._req.destroy(errors.CONNECTION_LOST())
  }

  _ondata(data) {
    this._idle = false

    try {
      for (const op of this._parser.push(data)) {
        switch (op.type) {
          case RESPONSE:
            this._req.on('close', () => {
              this._req = null
            })

            this._res = new this._IncomingMessage(this._socket, {
              headers: op.headers,
              statusCode: op.code,
              statusMessage: op.reason
            })

            this._res.on('close', () => {
              this._res = null
              this._idle = true

              this._socket.emit('free')
            })

            if (op.headers.connection && op.headers.connection.toLowerCase() === 'upgrade') {
              return this._onupgrade(this._parser.end())
            }

            this._req.emit('response', this._res)
            break

          case DATA:
            this._res.push(op.data)
            break

          case END:
            if (this._res) {
              this._res._socket = null
              this._res.push(null)
            }

            if (this._req) {
              this._req._socket = null
              this._req.destroy()
            }
            break
        }
      }
    } catch (err) {
      this._socket.destroy(err)
    }
  }

  _onupgrade(data) {
    this._detach()

    const res = this._res
    const req = this._req

    res._upgrade = req._upgrade = true

    const upgraded = req.emit('upgrade', res, this._socket, data || EMPTY)

    res.push(null)
    req.destroy()

    if (!upgraded) this._socket.destroy()
  }

  _ontimeout() {
    if (this._req) this._req.emit('timeout')
  }

  _ondrain() {
    if (this._req) this._req._continueWrite()
  }

  _detach() {
    this._socket
      .off('error', this._onerror)
      .off('close', this._onclose)
      .off('end', this._onend)
      .off('data', this._ondata)
      .off('drain', this._ondrain)
      .off('timeout', this._ontimeout)

    HTTPClientConnection._connections.delete(this._socket)
  }
}
const HTTPAgent = require('./agent')
const HTTPOutgoingMessage = require('./outgoing-message')

const CHUNK_DELIMITER = Buffer.from('\r\n')
const CHUNK_TERMINATOR = Buffer.from('0\r\n\r\n')

module.exports = class HTTPClientRequest extends HTTPOutgoingMessage {
  constructor(opts = {}, onresponse = null) {
    if (typeof opts === 'function') {
      onresponse = opts
      opts = {}
    }

    opts = opts ? { ...opts } : {}

    const agent = opts.agent === false ? new HTTPAgent() : opts.agent || HTTPAgent.global
    const method = opts.method || 'GET'
    const path = opts.path || '/'
    const defaultPort = opts.defaultPort || (agent && agent.defaultPort) || 80
    const host = (opts.host = opts.host || 'localhost')
    const port = (opts.port = opts.port || defaultPort)
    const headers = { host: hostHeader(host, port, defaultPort), ...opts.headers }

    super()

    agent.addRequest(this, opts)

    this._headers = headers
    this._method = method
    this._path = path

    this._chunked = method !== 'GET' && method !== 'HEAD'

    this._pendingWrite = null
    this._pendingFinal = null

    if (onresponse) this.once('response', onresponse)
  }

  get method() {
    return this._method
  }

  get path() {
    return this._path
  }

  // For Node.js compatibility
  abort() {
    return this.destroy()
  }

  _header() {
    let h = `${this._method} ${this._path} HTTP/1.1\r\n`

    let upgrade = false

    for (const name of Object.keys(this._headers)) {
      const n = name.toLowerCase()
      const v = this._headers[name]

      if (n === 'content-length') this._chunked = false
      if (n === 'connection' && v && v.toLowerCase() === 'upgrade') upgrade = true

      h += `${httpCase(n)}: ${v}\r\n`
    }

    if (upgrade) this._chunked = false

    if (this._chunked) h += 'Transfer-Encoding: chunked\r\n'

    h += '\r\n'

    return h
  }

  _write(data, encoding, cb) {
    if (this._headersSent === false) this.flushHeaders()

    if (this._chunked) {
      this._socket.write(Buffer.from(data.byteLength.toString(16)))
      this._socket.write(CHUNK_DELIMITER)
    }

    let flushed = this._socket.write(data)

    if (this._chunked) flushed = this._socket.write(CHUNK_DELIMITER)

    if (flushed) cb(null)
    else this._pendingWrite = cb
  }

  _final(cb) {
    if (this._headersSent === false) this.flushHeaders()

    if (this._chunked) this._socket.write(CHUNK_TERMINATOR)

    this._pendingFinal = cb
  }

  _predestroy() {
    super._predestroy()

    this._continueWrite()
    this._continueFinal()
  }

  _continueWrite() {
    if (this._pendingWrite === null) return
    const cb = this._pendingWrite
    this._pendingWrite = null
    cb(null)
  }

  _continueFinal() {
    if (this._pendingFinal === null) return
    const cb = this._pendingFinal
    this._pendingFinal = null
    cb(null)
  }
}

function httpCase(n) {
  let s = ''
  for (const part of n.split('-')) {
    s += (s ? '-' : '') + part.slice(0, 1).toUpperCase() + part.slice(1)
  }
  return s
}

function hostHeader(host, port, defaultPort) {
  const i = host.indexOf(':')

  if (i !== -1 && host.includes(':', i + 1) && host.charCodeAt(0) !== 91 /* [ */) {
    host = `[${host}]`
  }

  if (port && +port !== defaultPort) {
    host += ':' + port
  }

  return host
}
module.exports = {
  method: {
    GET: 'GET',
    HEAD: 'HEAD',
    POST: 'POST',
    PUT: 'PUT',
    DELETE: 'DELETE',
    CONNECT: 'CONNECT',
    OPTIONS: 'OPTIONS',
    TRACE: 'TRACE',
    PATCH: 'PATCH'
  },
  status: {
    100: 'Continue',
    101: 'Switching Protocols',
    102: 'Processing',
    103: 'Early Hints',
    200: 'OK',
    201: 'Created',
    202: 'Accepted',
    203: 'Non-Authoritative Information',
    204: 'No Content',
    205: 'Reset Content',
    206: 'Partial Content',
    207: 'Multi-Status',
    208: 'Already Reported',
    226: 'IM Used',
    300: 'Multiple Choices',
    301: 'Moved Permanently',
    302: 'Found',
    303: 'See Other',
    304: 'Not Modified',
    305: 'Use Proxy',
    307: 'Temporary Redirect',
    308: 'Permanent Redirect',
    400: 'Bad Request',
    401: 'Unauthorized',
    402: 'Payment Required',
    403: 'Forbidden',
    404: 'Not Found',
    405: 'Method Not Allowed',
    406: 'Not Acceptable',
    407: 'Proxy Authentication Required',
    408: 'Request Timeout',
    409: 'Conflict',
    410: 'Gone',
    411: 'Length Required',
    412: 'Precondition Failed',
    413: 'Payload Too Large',
    414: 'URI Too Long',
    415: 'Unsupported Media Type',
    416: 'Range Not Satisfiable',
    417: 'Expectation Failed',
    418: "I'm a Teapot",
    421: 'Misdirected Request',
    422: 'Unprocessable Entity',
    423: 'Locked',
    424: 'Failed Dependency',
    425: 'Too Early',
    426: 'Upgrade Required',
    428: 'Precondition Required',
    429: 'Too Many Requests',
    431: 'Request Header Fields Too Large',
    451: 'Unavailable For Legal Reasons',
    500: 'Internal Server Error',
    501: 'Not Implemented',
    502: 'Bad Gateway',
    503: 'Service Unavailable',
    504: 'Gateway Timeout',
    505: 'HTTP Version Not Supported',
    506: 'Variant Also Negotiates',
    507: 'Insufficient Storage',
    508: 'Loop Detected',
    509: 'Bandwidth Limit Exceeded',
    510: 'Not Extended',
    511: 'Network Authentication Required'
  }
}
module.exports = class HTTPError extends Error {
  constructor(msg, fn = HTTPError, code = fn.name) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'HTTPError'
  }

  static NOT_IMPLEMENTED(msg = 'Method not implemented') {
    return new HTTPError(msg, HTTPError.NOT_IMPLEMENTED)
  }

  static CONNECTION_LOST(msg = 'Socket hung up') {
    return new HTTPError(msg, HTTPError.CONNECTION_LOST)
  }

  static AGENT_SUSPENDED(msg = 'Agent is suspended') {
    return new HTTPError(msg, HTTPError.AGENT_SUSPENDED)
  }
}
const { Readable } = require('bare-stream')

module.exports = class HTTPIncomingMessage extends Readable {
  constructor(socket = null, opts = {}) {
    super()

    this._socket = socket
    this._upgrade = false
    this._headers = opts.headers || {}

    // Server options
    this._method = opts.method || ''
    this._url = opts.url || ''

    // Client options
    this._statusCode = opts.statusCode || 0
    this._statusMessage = opts.statusMessage || ''
  }

  get socket() {
    return this._socket
  }

  get upgrade() {
    return this._upgrade
  }

  get headers() {
    return this._headers
  }

  set headers(value) {
    this._headers = value
  }

  get method() {
    return this._method
  }

  set method(value) {
    this._method = value
  }

  get url() {
    return this._url
  }

  set url(value) {
    this._url = value
  }

  get statusCode() {
    return this._statusCode
  }

  set statusCode(value) {
    this._statusCode = value
  }

  get statusMessage() {
    return this._statusMessage
  }

  set statusMessage(value) {
    this._statusMessage = value
  }

  get httpVersion() {
    return '1.1'
  }

  getHeader(name) {
    return this._headers[name.toLowerCase()]
  }

  getHeaders() {
    return { ...this._headers }
  }

  hasHeader(name) {
    return name.toLowerCase() in this._headers
  }

  setTimeout(ms, ontimeout) {
    if (ontimeout) this.once('timeout', ontimeout)

    this._socket.setTimeout(ms)

    return this
  }

  _predestroy() {
    if (this._upgrade === false && this._socket !== null) this._socket.destroy()
  }
}
const { Writable } = require('bare-stream')
const errors = require('./errors')

module.exports = class HTTPOutgoingMessage extends Writable {
  constructor(socket = null) {
    super()

    this._socket = socket
    this._upgrade = false
    this._headersSent = false
    this._headers = {}
  }

  get socket() {
    return this._socket
  }

  get upgrade() {
    return this._upgrade
  }

  get headersSent() {
    return this._headersSent
  }

  get headers() {
    return this._headers
  }

  set headers(value) {
    this._headers = value
  }

  getHeader(name) {
    return this._headers[name.toLowerCase()]
  }

  getHeaders() {
    return { ...this._headers }
  }

  hasHeader(name) {
    return name.toLowerCase() in this._headers
  }

  setHeader(name, value) {
    this._headers[name.toLowerCase()] = value
  }

  flushHeaders() {
    if (this._headersSent === true || this._socket === null) return

    this._socket.write(Buffer.from(this._header()))
    this._headersSent = true
  }

  setTimeout(ms, ontimeout) {
    if (ontimeout) this.once('timeout', ontimeout)

    this._socket.setTimeout(ms)

    return this
  }

  _header() {
    throw errors.NOT_IMPLEMENTED()
  }

  _predestroy() {
    if (this._upgrade === false && this._socket !== null) this._socket.destroy()
  }
}
const { isEnded, isFinished, getStreamError } = require('bare-stream')
const HTTPParser = require('bare-http-parser')
const HTTPIncomingMessage = require('./incoming-message')
const HTTPServerResponse = require('./server-response')

const {
  constants: { REQUEST, DATA, END }
} = HTTPParser

const EMPTY = Buffer.alloc(0)

module.exports = class HTTPServerConnection {
  static _connections = new WeakMap()

  static for(socket) {
    return this._connections.get(socket) || null
  }

  constructor(server, socket, opts = {}) {
    const { IncomingMessage = HTTPIncomingMessage, ServerResponse = HTTPServerResponse } = opts

    this._server = server
    this._socket = socket

    this._req = null
    this._res = null

    this._IncomingMessage = IncomingMessage
    this._ServerResponse = ServerResponse

    this._parser = new HTTPParser()
    this._idle = true

    this._onclose = this._onclose.bind(this)
    this._ondata = this._ondata.bind(this)
    this._ondrain = this._ondrain.bind(this)
    this._ontimeout = this._ontimeout.bind(this)

    socket
      .on('error', noop)
      .on('close', this._onclose)
      .on('data', this._ondata)
      .on('drain', this._ondrain)
      .on('timeout', this._ontimeout)

    HTTPServerConnection._connections.set(socket, this)

    if (this._server.timeout) socket.setTimeout(this._server.timeout)
  }

  get server() {
    return this._server
  }

  get socket() {
    return this._socket
  }

  get req() {
    return this._req
  }

  get res() {
    return this._res
  }

  get idle() {
    return this._idle
  }

  _onclose() {
    if (this._req && !isEnded(this._req)) this._req.destroy()
    if (this._res && !isFinished(this._res)) this._res.destroy()

    const err = getStreamError(this._socket)
    if (err) this._socket.destroy(err)
  }

  _ondata(data) {
    this._idle = false

    try {
      for (const op of this._parser.push(data)) {
        switch (op.type) {
          case REQUEST:
            this._req = new this._IncomingMessage(this._socket, {
              headers: op.headers,
              method: op.method,
              url: op.url
            })

            this._req.on('close', () => {
              this._req = null

              this._idle = true

              if (this._server.closing) this._socket.destroy()
            })

            // Eagerly open the request stream
            this._req.resume()
            this._req.pause()

            if (op.headers.connection && op.headers.connection.toLowerCase() === 'upgrade') {
              return this._onupgrade(this._parser.end())
            }

            this._res = new this._ServerResponse(this._socket, this._req)

            this._res.on('close', () => {
              this._res = null
            })

            this._server.emit('request', this._req, this._res)
            break

          case DATA:
            this._req.push(op.data)
            break

          case END:
            if (this._req) {
              this._req._socket = null
              this._req.push(null)
            }
            break
        }
      }
    } catch (err) {
      this._socket.destroy(err)
    }
  }

  _onupgrade(data) {
    this._detach()

    const req = this._req

    req._upgrade = true

    const upgraded = this._server.emit('upgrade', req, this._socket, data || EMPTY)

    req.push(null)

    if (!upgraded) this._socket.destroy()
  }

  _ontimeout() {
    const reqTimeout = this._req && this._req.emit('timeout')
    const resTimeout = this._res && this._res.emit('timeout')
    const serverTimeout = this._server.emit('timeout', this._socket)

    if (!reqTimeout && !resTimeout && !serverTimeout) this._socket.destroy()
  }

  _ondrain() {
    if (this._res) this._res._continueWrite()
  }

  _detach() {
    this._socket
      .off('error', noop)
      .off('close', this._onclose)
      .off('data', this._ondata)
      .off('drain', this._ondrain)
      .off('timeout', this._ontimeout)

    HTTPServerConnection._connections.delete(this._socket)
  }
}

function noop() {}
const { isFinishing } = require('bare-stream')
const HTTPOutgoingMessage = require('./outgoing-message')
const constants = require('./constants')

const CHUNK_DELIMITER = Buffer.from('\r\n')
const CHUNK_TERMINATOR = Buffer.from('0\r\n\r\n')

module.exports = class HTTPServerResponse extends HTTPOutgoingMessage {
  constructor(socket, req) {
    super(socket)

    this._req = req

    this._statusCode = 200
    this._statusMessage = null

    this._chunked = true
    this._close = req.headers.connection === 'close'
    this._onlyHeaders = req.method === 'HEAD'

    this._pendingWrite = null
  }

  get req() {
    return this._req
  }

  get statusCode() {
    return this._statusCode
  }

  set statusCode(value) {
    this._statusCode = value
  }

  get statusMessage() {
    return this._statusMessage
  }

  set statusMessage(value) {
    this._statusMessage = value
  }

  writeHead(statusCode, statusMessage = null, headers = {}) {
    if (typeof statusMessage === 'object' && statusMessage !== null) {
      headers = statusMessage
      statusMessage = null
    }

    this._statusCode = statusCode
    this._statusMessage = statusMessage || null

    if (headers) this._headers = { ...this._headers, ...headers }
  }

  _header() {
    let h =
      'HTTP/1.1 ' +
      this._statusCode +
      ' ' +
      (this._statusMessage === null ? constants.status[this._statusCode] : this._statusMessage) +
      '\r\n'

    for (const name of Object.keys(this._headers)) {
      const n = name.toLowerCase()
      const v = this._headers[name]

      if (n === 'content-length') this._chunked = false
      if (n === 'connection' && v && v.toLowerCase() === 'close') this._close = true

      h += httpCase(n) + ': ' + v + '\r\n'
    }

    if (this._chunked) h += 'Transfer-Encoding: chunked\r\n'

    h += '\r\n'

    return h
  }

  _write(data, encoding, cb) {
    if (this._headersSent === false) {
      if (isFinishing(this)) {
        this.setHeader(
          'Content-Length',
          (data.byteLength + this._writableState.buffered).toString()
        )
      }

      this.flushHeaders()
    }

    if (this._onlyHeaders === true) return cb(null)

    if (this._chunked) {
      this._socket.write(Buffer.from(data.byteLength.toString(16)))
      this._socket.write(CHUNK_DELIMITER)
    }

    let flushed = this._socket.write(data)

    if (this._chunked) flushed = this._socket.write(CHUNK_DELIMITER)

    if (flushed) cb(null)
    else this._pendingWrite = cb
  }

  _final(cb) {
    if (this._headersSent === false) {
      this.setHeader('Content-Length', '0')
      this.flushHeaders()
    }

    if (this._chunked && this._onlyHeaders === false) this._socket.write(CHUNK_TERMINATOR)

    if (this._close) this._socket.end()

    cb(null)
  }

  _predestroy() {
    super._predestroy()

    this._req.destroy()

    this._continueWrite()
  }

  _continueWrite() {
    if (this._pendingWrite === null) return
    const cb = this._pendingWrite
    this._pendingWrite = null
    cb(null)
  }
}

function httpCase(n) {
  let s = ''
  for (const part of n.split('-')) {
    s += (s ? '-' : '') + part.slice(0, 1).toUpperCase() + part.slice(1)
  }
  return s
}
const TCPServer = require('bare-tcp').Server
const HTTPServerConnection = require('./server-connection')

module.exports = class HTTPServer extends TCPServer {
  constructor(opts = {}, onrequest) {
    if (typeof opts === 'function') {
      onrequest = opts
      opts = {}
    }

    super({ allowHalfOpen: false })

    this._timeout = 0

    this.on('connection', (socket) => {
      new HTTPServerConnection(this, socket, opts)
    })

    if (onrequest) this.on('request', onrequest)
  }

  get timeout() {
    return this._timeout || undefined // For Node.js compatibility
  }

  setTimeout(ms = 0, ontimeout) {
    if (ontimeout) this.on('timeout', ontimeout)

    this._timeout = ms

    return this
  }

  close(onclose) {
    super.close(onclose)

    for (const socket of this.connections) {
      const connection = HTTPServerConnection.for(socket)

      if (connection === null || connection.idle) {
        socket.destroy()
      }
    }

    return this
  }
}
{
  "name": "bare-http1",
  "version": "4.5.6",
  "description": "Native HTTP/1 library for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    },
    "./errors": {
      "types": "./lib/errors.d.ts",
      "default": "./lib/errors.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-http1.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-http1/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-http1#readme",
  "dependencies": {
    "bare-events": "^2.6.0",
    "bare-http-parser": "^1.1.1",
    "bare-stream": "^2.10.0",
    "bare-tcp": "^2.2.0"
  },
  "devDependencies": {
    "bare-buffer": "^3.0.2",
    "bare-url": "^2.1.3",
    "brittle": "^3.3.0",
    "lunte": "^1.6.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "bare-buffer": "*",
    "bare-url": "*"
  },
  "peerDependenciesMeta": {
    "bare-buffer": {
      "optional": true
    },
    "bare-url": {
      "optional": true
    }
  }
}
module.exports = require.addon()
const ansiEscapes = require('bare-ansi-escapes')
const getType = require('bare-type')
const binding = require('./binding')

const PLAIN_KEY = /^[a-zA-Z_][a-zA-Z_0-9]*$/

const defaultDepth = 2
const defaultBreakLength = 80
const defaultMaxArrayLength = 40

module.exports = exports = function inspect(value, opts = {}) {
  const {
    colors = false,
    depth = defaultDepth,
    breakLength = defaultBreakLength,
    stylize = defaultStylize(colors)
  } = opts

  const references = new InspectRefMap()

  const tree = inspectValue(value, 0, {
    colors,
    depth,
    breakLength,
    stylize,
    references
  })

  return tree.toString()
}

exports.styles = {
  bigint: ansiEscapes.colorYellow,
  boolean: ansiEscapes.colorYellow,
  date: ansiEscapes.colorMagenta,
  module: ansiEscapes.modifierUnderline,
  name: ansiEscapes.modifierReset,
  null: ansiEscapes.modifierBold,
  number: ansiEscapes.colorYellow,
  regexp: ansiEscapes.colorRed,
  special: ansiEscapes.colorCyan,
  string: ansiEscapes.colorGreen,
  symbol: ansiEscapes.colorGreen,
  undefined: ansiEscapes.colorBrightBlack
}

const styles = exports.styles

function defaultStylize(colors) {
  return function stylize(value, style) {
    const color = colors && styles[style]

    if (color) return color + value + ansiEscapes.modifierReset

    return value
  }
}

class InspectRefMap {
  constructor() {
    this.refs = new WeakMap()
    this.ids = new WeakMap()
    this.nextId = 1
  }

  has(object) {
    return this.refs.has(object)
  }

  get(object) {
    return this.refs.get(object) || null
  }

  set(object, ref) {
    this.refs.set(object, ref)
  }

  id(object) {
    let id = this.ids.get(object)
    if (id) return id

    id = this.nextId++
    this.ids.set(object, id)

    return id
  }
}

class InspectNode {
  constructor(depth, length, opts) {
    const { breakLength = defaultBreakLength, breakAlways = false } = opts

    this.depth = depth
    this.length = length
    this.breakLength = breakLength
    this.breakAlways = breakAlways
  }

  pad(n, string) {
    return string.padStart(n, ' ')
  }

  indent(n, string) {
    return '  '.repeat(n) + string
  }
}

class InspectRef extends InspectNode {
  constructor(depth, opts) {
    super(depth, '[circular *]'.length, opts)

    this.refs = opts.references
    this.count = 0
    this.circular = false
    this.color = opts.colors && styles.special
  }

  get id() {
    return this.refs.id(this)
  }

  increment() {
    return ++this.count
  }

  decrement() {
    return --this.count
  }

  toString(opts = {}) {
    const { offset = 0, pad = 0, indent = 0 } = opts

    let value = this.pad(pad, '[circular *' + this.id + ']')

    if (this.color) value = this.color + value + ansiEscapes.modifierReset

    return offset ? value : this.indent(indent, value)
  }
}

class InspectLeaf extends InspectNode {
  constructor(value, color, depth, opts) {
    const length = value.length

    if (value.includes('\n')) {
      value = value.replaceAll('\n', '\n' + '  '.repeat(depth))

      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.value = value
    this.color = opts.colors && color
  }

  toString(opts = {}) {
    const { offset = 0, pad = 0, indent = 0 } = opts

    let value = this.pad(pad, this.value)

    if (this.color) value = this.color + value + ansiEscapes.modifierReset

    return offset ? value : this.indent(indent, value)
  }
}

class InspectPair extends InspectNode {
  constructor(delim, left, right, depth, opts) {
    const length = left.length + delim.length + right.length

    if (left.breakAlways || right.breakAlways) {
      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.delim = delim
    this.left = left
    this.right = right
  }

  toString(opts = {}) {
    const { indent = 0 } = opts

    return this.indent(
      indent,
      this.left +
        this.delim +
        this.right.toString({
          indent,
          offset: this.left.length + this.delim.length
        })
    )
  }
}

class InspectSuspension extends InspectNode {
  constructor(overflow, depth, opts) {
    const label = `... ${overflow} more`

    super(depth, label.length, opts)

    this.label = label
  }

  toString(opts = {}) {
    const { indent = 0 } = opts

    return this.indent(indent, this.label)
  }
}

class InspectSequence extends InspectNode {
  constructor(header, footer, delim, values, ref, depth, opts) {
    const { tabulate = false } = opts

    const length =
      (ref.circular ? '<ref *>'.length + 1 : 0) +
      header.length +
      values.reduce(
        (length, value, i) =>
          length + value.length + (i === 0 ? 0 : delim.length),
        0
      ) +
      footer.length

    if (values.some((value) => value.breakAlways)) {
      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.header = header
    this.footer = footer
    this.delim = delim
    this.values = values
    this.ref = ref
    this.tabulate = tabulate
  }

  toString(opts = {}) {
    const { offset = 0, indent = 0 } = opts

    const split =
      this.breakAlways ||
      (this.values.length &&
        (offset + this.length > this.breakLength ||
          indent * 2 + this.length > this.breakLength))

    let header = this.header

    if (this.ref.circular) {
      header = '<ref *' + this.ref.id + '> ' + header
    }

    if (this.values.length === 0) {
      header = header.trimEnd()
    }

    if (offset === 0) {
      header = this.indent(indent, header)
    }

    if (split) {
      header = header.trimEnd() + '\n'
    }

    let string = header

    let columns = 1
    let pad = 0

    if (this.tabulate) {
      const widest = this.values.reduce(
        (length, value) =>
          value.breakAlways ? length : Math.max(length, value.length),
        0
      )

      if (widest) {
        columns = Math.max(
          columns,
          Math.floor(
            (this.breakLength - indent * 2) / (widest + this.delim.length)
          )
        )

        if (columns > 1) pad = widest
      }
    }

    for (let i = 0, n = this.values.length, offset = 0; i < n; i++) {
      const value = this.values[i]

      if (split) {
        let part

        if (i % columns === 0 || value.breakAlways) {
          part = value.toString({ indent: indent + 1, pad })
        } else {
          part = value.toString({ pad })
        }

        string += part

        if (i < n - 1) {
          if (i % columns === columns - 1 || this.values[i + 1].breakAlways) {
            string += this.delim.trimEnd() + '\n'
          } else {
            string += this.delim
          }
        }
      } else {
        if (i > 0) string += this.delim

        string += value.toString({ offset })

        offset += value.length
      }
    }

    let footer = this.footer

    if (this.values.length === 0) {
      footer = footer.trimStart()
    }

    if (split) {
      string += '\n' + this.indent(indent, footer.trimStart())
    } else {
      string += footer
    }

    return string
  }
}

function inspectValue(value, depth, opts) {
  const type = getType(value)

  if (type.isUndefined()) return inspectUndefined(depth, opts)
  if (type.isNull()) return inspectNull(depth, opts)
  if (type.isBoolean()) return inspectBoolean(value, depth, opts)
  if (type.isNumber()) return inspectNumber(value, depth, opts)
  if (type.isBigInt()) return inspectBigInt(value, depth, opts)
  if (type.isString()) return inspectString(value, depth, opts)
  if (type.isSymbol()) return inspectSymbol(value, depth, opts)
  if (type.isObject()) return inspectObject(type, value, depth, opts)
  if (type.isFunction()) return inspectFunction(type, value, depth, opts)
  if (type.isExternal()) return inspectExternal(value, opts, opts)
}

function inspectUndefined(depth, opts) {
  return new InspectLeaf('undefined', styles.undefined, depth, opts)
}

function inspectNull(depth, opts) {
  return new InspectLeaf('null', styles.null, depth, opts)
}

function inspectBoolean(value, depth, opts) {
  return new InspectLeaf(value.toString(), styles.boolean, depth, opts)
}

function inspectNumber(value, depth, opts) {
  let string

  if (Object.is(value, -0)) {
    string = '-0'
  } else {
    string = value.toString(10)
  }

  return new InspectLeaf(string, styles.number, depth, opts)
}

function inspectBigInt(value, depth, opts) {
  return new InspectLeaf(value.toString(10) + 'n', styles.bigint, depth, opts)
}

const STRING_ESCAPES =
  /[\ud800-\udbff][\udc00-\udfff]|[\u0000-\u001f'\\\ud800-\udfff]/g

function inspectString(value, depth, opts) {
  // https://tc39.es/ecma262/multipage/structured-data.html#sec-quotejsonstring
  const string = value.replace(STRING_ESCAPES, (match) => {
    if (match.length === 2) return match

    switch (match) {
      case "'":
        return "\\'"
      case '\\':
        return '\\\\'
      case '\b':
        return '\\b'
      case '\t':
        return '\\t'
      case '\n':
        return '\\n'
      case '\f':
        return '\\f'
      case '\r':
        return '\\r'
      default:
        return '\\u' + match.charCodeAt(0).toString(16).padStart(4, '0')
    }
  })

  return new InspectLeaf("'" + string + "'", styles.string, depth, opts)
}

function inspectSymbol(value, depth, opts) {
  return new InspectLeaf(value.toString(), styles.symbol, depth, opts)
}

function inspectKey(value, depth, opts) {
  if (PLAIN_KEY.test(value)) {
    return new InspectLeaf(value, null, depth, opts)
  } else {
    return inspectValue(value, depth, opts)
  }
}

function inspectObject(type, object, depth, opts) {
  const refs = opts.references

  let ref = refs.get(object)
  if (ref === null) {
    ref = new InspectRef(depth, opts)
    refs.set(object, ref)
  } else if (ref.count) {
    ref.circular = true
    return ref
  }

  const maxDepth = typeof opts.depth === 'number' ? opts.depth : Infinity

  if (maxDepth < depth) {
    const constructor = object.constructor

    return new InspectLeaf(
      '[' +
        (constructor && constructor.name ? constructor.name : 'Object') +
        ']',
      styles.special,
      depth,
      opts
    )
  }

  const inspect =
    object[Symbol.for('bare.inspect')] ||
    object[Symbol.for('nodejs.util.inspect.custom')]

  if (typeof inspect === 'function') {
    const value = inspect.call(
      object,
      typeof opts.depth === 'number' ? opts.depth - depth : null,
      {
        colors: opts.colors,
        breakLength: opts.breakLength,
        stylize: opts.stylize
      },
      exports
    )

    if (typeof value === 'object' && value !== null) {
      refs.set(value, ref)
    }

    if (typeof value !== 'string') {
      return inspectValue(value, depth, opts)
    }

    return new InspectLeaf(value, null, depth, opts)
  }

  if (type.isArray()) return inspectArray(object, ref, depth, opts)
  if (type.isDate()) return inspectDate(object, ref, depth, opts)
  if (type.isRegExp()) return inspectRegExp(object, ref, depth, opts)
  if (type.isError()) return inspectError(object, ref, depth, opts)
  if (type.isPromise()) return inspectPromise(object, ref, depth, opts)
  if (type.isMap()) return inspectMap(object, ref, depth, opts)
  if (type.isSet()) return inspectSet(object, ref, depth, opts)
  if (type.isWeakMap()) return inspectWeakMap(object, ref, depth, opts)
  if (type.isWeakSet()) return inspectWeakSet(object, ref, depth, opts)
  if (type.isWeakRef()) return inspectWeakRef(object, ref, depth, opts)
  if (type.isArrayBuffer()) return inspectArrayBuffer(object, ref, depth, opts)
  if (type.isSharedArrayBuffer())
    return inspectSharedArrayBuffer(object, ref, depth, opts)
  if (type.isTypedArray()) return inspectTypedArray(object, ref, depth, opts)
  if (type.isDataView()) return inspectDataView(object, ref, depth, opts)

  ref.increment()

  const values = []

  for (const key in object) {
    if (key === 'constructor') continue

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(object[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  let header = '{ '

  const tag = object[Symbol.toStringTag]

  if (tag) header = '[' + tag + '] ' + header

  if (object.constructor) {
    const name = object.constructor.name

    if (name && name !== 'Object') {
      header = object.constructor.name + ' ' + header
    }
  }

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectArray(array, ref, depth, opts) {
  const { maxArrayLength = defaultMaxArrayLength } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxArrayLength, 0)

  for (let i = 0, n = array.length; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(array.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(inspectValue(array[i], depth + 1, opts))
  }

  for (const key of binding.getOwnNonIndexPropertyNames(array)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(array[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  let header = '[ '

  if (array.constructor.name !== 'Array') {
    header = array.constructor.name + '(' + array.length + ') ' + header
  }

  return new InspectSequence(header, ' ]', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectDate(date, ref, depth, opts) {
  return new InspectLeaf(date.toISOString(), styles.date, depth, opts)
}

function inspectRegExp(regExp, ref, depth, opts) {
  return new InspectLeaf(regExp.toString(), styles.regexp, depth, opts)
}

function inspectError(error, ref, depth, opts) {
  let header

  if ('stack' in error) {
    header = error.stack

    if (depth > 0) {
      header = header.replaceAll('\n', '\n' + '  '.repeat(depth))
    }
  } else {
    header = error.toString()
  }

  const builtins = ['cause']

  if (error.name === 'AggregateError') {
    builtins.push('errors')
  } else if (error.name === 'SuppressedError') {
    builtins.push('error', 'suppressed')
  }

  const values = []

  for (const key of builtins) {
    if (key in error === false) continue

    values.push(
      new InspectPair(
        ': ',
        new InspectLeaf('[' + key + ']', null, depth + 1, opts),
        inspectValue(error[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key in error) {
    if (key === 'constructor' || builtins.includes(key)) continue

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(error[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  if (values.length === 0) return new InspectLeaf(header, null, depth, opts)

  return new InspectSequence(
    header + ' {',
    ' }',
    ', ',
    values,
    ref,
    depth,
    opts
  )
}

function inspectPromise(promise, ref, depth, opts) {
  ref.increment()

  const state = binding.getPromiseState(promise)

  const values = []

  switch (state) {
    case 0: // Pending
      values.push(new InspectLeaf('<pending>', styles.special, depth, opts))
      break

    case 1: // Fulfilled
      values.push(inspectValue(binding.getPromiseResult(promise), depth, opts))
      break

    case 2: // Rejected
      values.push(
        new InspectLeaf('<rejected>', styles.special, depth, opts),
        inspectValue(binding.getPromiseResult(promise), depth, opts)
      )
  }

  ref.decrement()

  const header = promise.constructor.name + ' { '

  return new InspectSequence(header, ' }', ' ', values, ref, depth, opts)
}

function inspectMap(map, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxMapLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = maxMapLength

  for (const entry of map) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(map.size - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )
      break
    }

    values.push(
      new InspectPair(
        ' => ',
        inspectValue(entry[0], depth + 1, opts),
        inspectValue(entry[1], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key in map) {
    if (key === 'constructor') continue

    const value = inspectValue(map[key], depth + 1, opts)

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        value,
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = map.constructor.name + '(' + map.size + ') { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectSet(set, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxSetLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = maxSetLength

  for (const entry of set) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(set.size - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )
      break
    }

    values.push(inspectValue(entry, depth + 1, opts))
  }

  for (const key in set) {
    if (key === 'constructor') continue

    const value = inspectValue(set[key], depth + 1, opts)

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        value,
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = set.constructor.name + '(' + set.size + ') { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectWeakMap(weakMap, ref, depth, opts) {
  const header = weakMap.constructor.name + ' { '

  return new InspectSequence(
    header,
    ' }',
    ' ',
    [new InspectLeaf('<items unknown>', styles.special, depth + 1, opts)],
    ref,
    depth,
    opts
  )
}

function inspectWeakSet(weakSet, ref, depth, opts) {
  const header = weakSet.constructor.name + ' { '

  return new InspectSequence(
    header,
    ' }',
    ' ',
    [new InspectLeaf('<items unknown>', styles.special, depth + 1, opts)],
    ref,
    depth,
    opts
  )
}

function inspectWeakRef(weakRef, ref, depth, opts) {
  const target = weakRef.deref()

  let value

  if (target === undefined) {
    value = new InspectLeaf('<cleared>', styles.special, depth + 1, opts)
  } else {
    value = inspectValue(target, depth + 1, opts)
  }

  const header = weakRef.constructor.name + ' { '

  return new InspectSequence(header, ' }', ' ', [value], ref, depth, opts)
}

function inspectArrayBuffer(arrayBuffer, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(arrayBuffer[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = arrayBuffer.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectSharedArrayBuffer(sharedArrayBuffer, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(sharedArrayBuffer[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = sharedArrayBuffer.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectTypedArray(typedArray, ref, depth, opts) {
  if (Buffer.isBuffer(typedArray)) {
    return inspectBuffer(typedArray, ref, depth, opts)
  }

  const {
    maxArrayLength = defaultMaxArrayLength,
    maxTypedArrayLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxTypedArrayLength, 0)

  for (let i = 0, n = typedArray.length; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(typedArray.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(inspectValue(typedArray[i], depth + 1, opts))
  }

  for (const key of binding.getOwnNonIndexPropertyNames(typedArray)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(typedArray[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = typedArray.constructor.name + '(' + typedArray.length + ') [ '

  return new InspectSequence(header, ' ]', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectBuffer(buffer, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxBufferLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxBufferLength, 0)

  for (let i = 0, n = buffer.byteLength; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(buffer.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(
      new InspectLeaf(
        buffer[i].toString(16).padStart(2, '0'),
        null,
        depth + 1,
        opts
      )
    )
  }

  for (const key of binding.getOwnNonIndexPropertyNames(buffer)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(buffer[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  return new InspectSequence('<Buffer ', '>', ' ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectDataView(dataView, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength', 'byteOffset', 'buffer']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(dataView[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key of binding.getOwnNonIndexPropertyNames(dataView)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(dataView[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = dataView.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectFunction(type, fn, depth, opts) {
  if (fn.toString().startsWith('class')) return inspectClass(fn, depth, opts)

  let tag = 'function'

  if (type.isGeneratorFunction()) tag = 'generator ' + tag
  if (type.isAsyncFunction()) tag = 'async ' + tag

  return new InspectLeaf(
    '[' + tag + ' ' + (fn.name ? fn.name : '(anonymous)') + ']',
    styles.special,
    depth,
    opts
  )
}

function inspectClass(ctor, depth, opts) {
  return new InspectLeaf(
    '[class ' + (ctor.name ? ctor.name : '(anonymous)') + ']',
    styles.special,
    depth,
    opts
  )
}

function inspectExternal(external, depth, opts) {
  return new InspectLeaf(
    '[external 0x' + binding.getExternal(external).toString(16) + ']',
    styles.special,
    depth,
    opts
  )
}
{
  "name": "bare-inspect",
  "version": "3.1.4",
  "description": "Inspect objects as strings for debugging",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-inspect.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-inspect/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-inspect#readme",
  "engines": {
    "bare": ">=1.18.0"
  },
  "dependencies": {
    "bare-ansi-escapes": "^2.1.0",
    "bare-type": "^1.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
const EventEmitter = require('bare-events')
const { Duplex } = require('bare-stream')
const tcp = require('bare-tcp')
const pipe = require('bare-pipe')

const defaultReadBufferSize = 65536

const constants = exports.constants = {
  type: {
    TCP: 1,
    IPC: 2
  },
  state: {
    UNREFED: 0x1
  }
}

const Socket = exports.Socket = class NetSocket extends Duplex {
  constructor (opts = {}) {
    super({ eagerOpen: true })

    const {
      readBufferSize = defaultReadBufferSize,
      allowHalfOpen = true
    } = opts

    this._opts = { readBufferSize, allowHalfOpen }
    this._type = 0
    this._state = 0
    this._socket = null

    this._pendingWrite = null
    this._pendingFinal = null
  }

  get connecting () {
    return this._socket !== null && this._socket.connecting
  }

  get pending () {
    return this._socket === null || this._socket.pending
  }

  connect (...args) {
    let opts = {}
    let onconnect

    // connect(path[, onconnect])
    if (typeof args[0] === 'string') {
      opts.path = args[0]
      onconnect = args[1]
    // connect(port[, host][, onconnect])
    } else if (typeof args[0] === 'number') {
      opts.port = args[0]

      if (typeof args[1] === 'function') {
        onconnect = args[1]
      } else {
        opts.host = args[1]
        onconnect = args[2]
      }
    // connect(opts[, onconnect])
    } else {
      opts = args[0] || {}
      onconnect = args[1]
    }

    opts = { ...opts, ...this._opts }

    if (opts.path) {
      this._attach(constants.type.IPC, pipe.createConnection(opts))
    } else {
      this._attach(constants.type.TCP, tcp.createConnection(opts))
    }

    if (onconnect) this.once('connect', onconnect)

    return this
  }

  ref () {
    this._state &= ~constants.state.UNREFED
    if (this._socket !== null) this._socket.ref()
  }

  unref () {
    this._state |= constants.state.UNREFED
    if (this._socket !== null) this._socket.unref()
  }

  _attach (type, socket) {
    this._type = type
    this._socket = socket

    this._socket
      .on('connect', this._onconnect.bind(this))
      .on('error', this._onerror.bind(this))
      .on('close', this._onclose.bind(this))
      .on('end', this._onend.bind(this))
      .on('data', this._ondata.bind(this))
      .on('drain', this._ondrain.bind(this))

    if (this._state & constants.state.UNREFED) this._socket.unref()

    return this
  }

  _write (data, encoding, cb) {
    if (this._socket !== null && this._socket.write(data)) cb(null)
    else this._pendingWrite = cb
  }

  _final (cb) {
    if (this._socket === null) return cb(null)
    this._pendingFinal = cb
    this._socket.end()
  }

  _predestroy () {
    if (this._socket === null) return
    this._socket.destroy()
  }

  _onconnect () {
    this._ondrain() // Flush any pending writes

    this.emit('connect')
  }

  _onerror (err) {
    this.destroy(err)
  }

  _onend () {
    if (this._pendingFinal === null) return
    const cb = this._pendingFinal
    this._pendingFinal = null
    cb(null)
  }

  _onclose () {
    this.push(null)
  }

  _ondata (data) {
    this.push(data)
  }

  _ondrain () {
    if (this._pendingWrite === null) return
    const cb = this._pendingWrite
    this._pendingWrite = null
    cb(null)
  }
}

const Server = exports.Server = class NetServer extends EventEmitter {
  constructor (opts = {}, onconnection) {
    if (typeof opts === 'function') {
      onconnection = opts
      opts = {}
    }

    super()

    const {
      readBufferSize = defaultReadBufferSize,
      allowHalfOpen = true
    } = opts

    this._opts = { readBufferSize, allowHalfOpen }
    this._type = 0
    this._state = 0
    this._server = null

    if (onconnection) this.on('connection', onconnection)
  }

  get listening () {
    return this._server !== null && this._server.listening
  }

  address () {
    return this._server === null ? null : this._server.address()
  }

  listen (...args) {
    let opts = {}
    let onlistening

    // listen(path[, backlog][, onlistening])
    if (typeof args[0] === 'string') {
      opts.path = args[0]

      if (typeof args[1] === 'function') {
        onlistening = args[1]
      } else {
        opts.backlog = args[1]
        onlistening = args[2]
      }
    // listen([port[, host[, backlog]]][, onlistening])
    } else {
      if (typeof args[0] === 'function') {
        onlistening = args[0]
      } else {
        opts.port = args[0]

        if (typeof args[1] === 'function') {
          onlistening = args[1]
        } else {
          opts.host = args[1]

          if (typeof args[2] === 'function') {
            onlistening = args[2]
          } else {
            opts.backlog = args[2]
            onlistening = args[3]
          }
        }
      }
    }

    opts = { ...opts, ...this._opts }

    if (opts.path) {
      this._attach(constants.type.IPC, pipe.createServer(opts))
    } else {
      this._attach(constants.type.TCP, tcp.createServer(opts))
    }

    this._server.listen(opts)

    if (onlistening) this.once('listening', onlistening)

    return this
  }

  close (onclose) {
    if (onclose) this.once('close', onclose)
    this._server.close()
  }

  ref () {
    this._state &= ~constants.state.UNREFED
    if (this._server !== null) this._server.ref()
  }

  unref () {
    this._state |= constants.state.UNREFED
    if (this._server !== null) this._server.unref()
  }

  _attach (type, server) {
    this._type = type
    this._server = server

    this._server
      .on('listening', this._onlistening.bind(this))
      .on('connection', this._onconnection.bind(this))
      .on('error', this._onerror.bind(this))
      .on('close', this._onclose.bind(this))

    if (this._state & constants.state.UNREFED) this._server.unref()

    return this
  }

  _onlistening () {
    this.emit('listening')
  }

  _onconnection (socket) {
    this.emit('connection', new Socket(this._opts)._attach(this._type, socket))
  }

  _onerror (err) {
    this.emit('error', err)
  }

  _onclose () {
    this.emit('close')
  }
}

exports.isIP = tcp.isIP
exports.isIPv4 = tcp.isIPv4
exports.isIPv6 = tcp.isIPv6

exports.createConnection = function createConnection (...args) {
  let opts = {}
  let onconnect

  // createConnection(path[, onconnect])
  if (typeof args[0] === 'string') {
    opts.path = args[0]
    onconnect = args[1]
  // createConnection(port[, host][, onconnect])
  } else if (typeof args[0] === 'number') {
    opts.port = args[0]

    if (typeof args[1] === 'function') {
      onconnect = args[1]
    } else {
      opts.host = args[1]
      onconnect = args[2]
    }
  // createConnection(opts[, onconnect])
  } else {
    opts = args[0] || {}
    onconnect = args[1]
  }

  return new Socket(opts).connect(opts, onconnect)
}

exports.createServer = function createServer (opts, onconnection) {
  return new Server(opts, onconnection)
}
module.exports = require.addon()
const binding = require('./binding')

function onlookup (err, addresses) {
  const req = this

  if (err) return req.cb(err, null, 0)

  const { address, family } = addresses[0]

  return req.cb(null, address, family)
}

function onlookupall (err, addresses) {
  const req = this

  if (err) return req.cb(err, null)

  return req.cb(null, addresses)
}

exports.lookup = function lookup (hostname, opts = {}, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  let {
    family = 0,
    all = false
  } = opts

  if (typeof family === 'string') {
    switch (family) {
      case 'IPv4': family = 4
        break
      case 'IPv6': family = 6
        break
      default: family = 0
    }
  }

  const req = {
    cb,
    handle: null
  }

  req.handle = binding.lookup(hostname, family || 0, all, req, all ? onlookupall : onlookup)
}
{
  "name": "bare-dns",
  "version": "1.0.5",
  "description": "Domain name resolution for JavaScript",
  "exports": {
    ".": "./index.js",
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "standard && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-dns.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-dns/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-dns",
  "devDependencies": {
    "brittle": "^3.3.2",
    "cmake-bare": "^1.1.6",
    "standard": "^17.1.0"
  }
}
module.exports = require.addon()
/* global Bare */
const EventEmitter = require('bare-events')
const { Duplex } = require('bare-stream')
const binding = require('./binding')
const constants = require('./lib/constants')
const errors = require('./lib/errors')

const defaultReadBufferSize = 65536

const Pipe = module.exports = exports = class Pipe extends Duplex {
  constructor (path, opts = {}) {
    super({ eagerOpen: true })

    if (typeof path === 'object' && path !== null) {
      opts = path
      path = null
    }

    const {
      readBufferSize = defaultReadBufferSize,
      allowHalfOpen = true
    } = opts

    this._state = 0

    this._allowHalfOpen = allowHalfOpen

    this._fd = -1
    this._path = null

    this._pendingOpen = null
    this._pendingWrite = null
    this._pendingFinal = null
    this._pendingDestroy = null

    this._buffer = Buffer.alloc(readBufferSize)

    this._handle = binding.init(this._buffer, this,
      noop,
      this._onconnect,
      this._onwrite,
      this._onfinal,
      this._onread,
      this._onclose
    )

    if (typeof path === 'number') {
      this.open(path)
    } else if (typeof path === 'string') {
      this.connect(path)
    }

    Pipe._pipes.add(this)
  }

  get connecting () {
    return (this._state & constants.state.CONNECTING) !== 0
  }

  get pending () {
    return (this._state & constants.state.CONNECTED) === 0
  }

  get readyState () {
    if (this._state & constants.state.READABLE && this._state & constants.state.WRITABLE) {
      return 'open'
    }

    if (this._state & constants.state.READABLE) {
      return 'readOnly'
    }

    if (this._state & constants.state.WRITABLE) {
      return 'writeOnly'
    }

    return 'opening'
  }

  open (fd, opts = {}, onconnect) {
    if (typeof opts === 'function') {
      onconnect = opts
      opts = {}
    }

    if (typeof fd === 'object' && fd !== null) {
      opts = fd || {}
      fd = opts.fd
    }

    try {
      const status = binding.open(this._handle, fd)

      this._state |= constants.state.CONNECTED
      this._fd = fd

      if (status & binding.READABLE) {
        this._state |= constants.state.READABLE
      } else {
        this.push(null)
      }

      if (status & binding.WRITABLE) {
        this._state |= constants.state.WRITABLE
      } else {
        this.end()
      }

      if (onconnect) this.once('connect', onconnect)

      queueMicrotask(() => this.emit('connect'))
    } catch (err) {
      queueMicrotask(() => {
        if (this._pendingOpen) this._pendingOpen(err)
        else this.destroy(err)
      })
    }

    return this
  }

  connect (path, opts = {}, onconnect) {
    if (this._state & constants.state.CONNECTING || this._state & constants.state.CONNECTED) {
      throw errors.PIPE_ALREADY_CONNECTED('Pipe is already connected')
    }

    this._state |= constants.state.CONNECTING

    if (typeof opts === 'function') {
      onconnect = opts
      opts = {}
    }

    if (typeof path === 'object' && path !== null) {
      opts = path || {}
      path = opts.path
    }

    try {
      binding.connect(this._handle, path)

      this._path = path

      if (onconnect) this.once('connect', onconnect)
    } catch (err) {
      queueMicrotask(() => {
        if (this._pendingOpen) this._pendingOpen(err)
        else this.destroy(err)
      })
    }

    return this
  }

  ref () {
    binding.ref(this._handle)
  }

  unref () {
    binding.unref(this._handle)
  }

  _open (cb) {
    if (this._state & constants.state.CONNECTED) return cb(null)
    this._pendingOpen = cb
  }

  _read () {
    if ((this._state & constants.state.READING) === 0) {
      this._state |= constants.state.READING
      binding.resume(this._handle)
    }
  }

  _writev (batch, cb) {
    this._pendingWrite = [cb, batch]
    binding.writev(this._handle, batch.map(({ chunk }) => chunk))
  }

  _final (cb) {
    if (this._state & constants.state.READABLE && this._state & constants.state.WRITABLE) {
      this._pendingFinal = cb
      binding.end(this._handle)
    } else {
      cb(null)
    }
  }

  _predestroy () {
    if (this._state & constants.state.CLOSING) return
    this._state |= constants.state.CLOSING
    binding.close(this._handle)
    Pipe._pipes.delete(this)
  }

  _destroy (err, cb) {
    if (this._state & constants.state.CLOSING) return cb(err)
    this._state |= constants.state.CLOSING
    this._pendingDestroy = cb
    binding.close(this._handle)
    Pipe._pipes.delete(this)
  }

  _continueOpen (err) {
    if (this._pendingOpen === null) return
    const cb = this._pendingOpen
    this._pendingOpen = null
    cb(err)
  }

  _continueWrite (err) {
    if (this._pendingWrite === null) return
    const cb = this._pendingWrite[0]
    this._pendingWrite = null
    cb(err)
  }

  _continueFinal (err) {
    if (this._pendingFinal === null) return
    const cb = this._pendingFinal
    this._pendingFinal = null
    cb(err)
  }

  _continueDestroy () {
    if (this._pendingDestroy === null) return
    const cb = this._pendingDestroy
    this._pendingDestroy = null
    cb(null)
  }

  _onconnect (err) {
    if (err) {
      if (this._pendingOpen) this._continueOpen(err)
      else this.destroy(err)
      return
    }

    this._state |= constants.state.CONNECTED | constants.state.READABLE | constants.state.WRITABLE
    this._state &= ~constants.state.CONNECTING
    this._continueOpen()

    this.emit('connect')
  }

  _onread (err, read) {
    if (err) {
      this.destroy(err)
      return
    }

    if (read === 0) {
      this.push(null)
      if (this._allowHalfOpen === false) this.end()
      return
    }

    const copy = Buffer.allocUnsafe(read)
    copy.set(this._buffer.subarray(0, read))

    if (this.push(copy) === false && this.destroying === false) {
      this._state &= ~constants.state.READING
      binding.pause(this._handle)
    }
  }

  _onwrite (err) {
    this._continueWrite(err)
  }

  _onfinal (err) {
    this._continueFinal(err)
  }

  _onclose () {
    this._handle = null
    this._continueDestroy()
  }

  _onspawn (readable, writable) {
    this._state |= constants.state.CONNECTED

    if (readable) {
      this._state |= constants.state.READABLE
    } else {
      this.push(null)
    }

    if (writable) {
      this._state |= constants.state.WRITABLE
    } else {
      this.end()
    }

    this._continueOpen()
  }

  static _pipes = new Set()
}

exports.Pipe = exports

exports.pipe = function pipe () {
  return binding.pipe()
}

const Server = exports.Server = class PipeServer extends EventEmitter {
  constructor (opts = {}, onconnection) {
    if (typeof opts === 'function') {
      onconnection = opts
      opts = {}
    }

    super()

    const {
      readBufferSize = defaultReadBufferSize,
      allowHalfOpen = true
    } = opts

    this._state = 0

    this._readBufferSize = readBufferSize
    this._allowHalfOpen = allowHalfOpen

    this._path = null
    this._connections = new Set()

    this._error = null
    this._handle = null

    if (onconnection) this.on('connection', onconnection)

    PipeServer._servers.add(this)
  }

  get listening () {
    return (this._state & constants.state.BOUND) !== 0
  }

  address () {
    if ((this._state & constants.state.BOUND) === 0) {
      return null
    }

    return this._path
  }

  listen (path, backlog = 511, opts = {}, onlistening) {
    if (this._state & constants.state.BINDING || this._state & constants.state.BOUND) {
      throw errors.SERVER_ALREADY_LISTENING('Server is already listening')
    }

    if (this._state & constants.state.CLOSING) {
      throw errors.SERVER_IS_CLOSED('Server is closed')
    }

    this._state |= constants.state.BINDING

    if (typeof backlog === 'function') {
      onlistening = backlog
      backlog = 511
    } else if (typeof opts === 'function') {
      onlistening = opts
      opts = {}
    }

    if (typeof path === 'object' && path !== null) {
      opts = path || {}
      path = opts.path
      backlog = opts.backlog || 511
    }

    this._handle = binding.init(empty, this,
      this._onconnection,
      noop,
      noop,
      noop,
      noop,
      this._onclose
    )

    if (this._state & constants.state.UNREFED) binding.unref(this._handle)

    try {
      binding.bind(this._handle, path, backlog)

      this._path = path
      this._state |= constants.state.BOUND
      this._state &= ~constants.state.BINDING

      if (onlistening) this.once('listening', onlistening)

      queueMicrotask(() => this.emit('listening'))
    } catch (err) {
      this._error = err

      binding.close(this._handle)
    }

    return this
  }

  close (onclose) {
    if (onclose) this.once('close', onclose)
    if (this._state & constants.state.CLOSING) return
    this._state |= constants.state.CLOSING
    this._closeMaybe()
  }

  ref () {
    this._state &= ~constants.state.UNREFED
    if (this._handle !== null) binding.ref(this._handle)
  }

  unref () {
    this._state |= constants.state.UNREFED
    if (this._handle !== null) binding.unref(this._handle)
  }

  _closeMaybe () {
    if ((this._state & constants.state.CLOSING) && this._connections.size === 0) {
      if (this._handle !== null) binding.close(this._handle)
      else queueMicrotask(() => this.emit('close'))
      PipeServer._servers.delete(this)
    }
  }

  _onconnection (err) {
    if (err) {
      this.emit('error', err)
      return
    }

    if (this._state & constants.state.CLOSING) return

    const pipe = new Pipe({
      readBufferSize: this._readBufferSize,
      allowHalfOpen: this._allowHalfOpen
    })

    try {
      binding.accept(this._handle, pipe._handle)

      pipe._path = this._path
      pipe._state |= constants.state.CONNECTED | constants.state.READABLE | constants.state.WRITABLE

      this._connections.add(pipe)

      pipe.on('close', () => {
        this._connections.delete(pipe)
        this._closeMaybe()
      })

      this.emit('connection', pipe)
    } catch (err) {
      pipe.destroy()

      throw err
    }
  }

  _onclose () {
    const err = this._error

    this._state &= ~constants.state.BINDING
    this._error = null
    this._handle = null

    if (err) this.emit('error', err)
    else this.emit('close')
  }

  static _servers = new Set()
}

exports.constants = constants
exports.errors = errors

exports.createConnection = function createConnection (path, opts, onconnect) {
  if (typeof opts === 'function') {
    onconnect = opts
    opts = {}
  }

  if (typeof path === 'object' && path !== null) {
    opts = path || {}
    path = opts.path
  }

  return new Pipe(opts).connect(path, opts, onconnect)
}

exports.createServer = function createServer (opts, onconnection) {
  return new Server(opts, onconnection)
}

Bare
  .on('exit', () => {
    for (const pipe of Pipe._pipes) {
      pipe.destroy()
    }

    for (const server of Server._servers) {
      server.close()
    }
  })

const empty = Buffer.alloc(0)

function noop () {}
module.exports = {
  state: {
    CONNECTING: 0x1,
    CONNECTED: 0x2,
    BINDING: 0x4,
    BOUND: 0x8,
    READING: 0x10,
    CLOSING: 0x20,
    READABLE: 0x40,
    WRITABLE: 0x80
  }
}
module.exports = class PipeError extends Error {
  constructor (msg, code, fn = PipeError) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name () {
    return 'PipeError'
  }

  static PIPE_ALREADY_CONNECTED (msg) {
    return new PipeError(msg, 'PIPE_ALREADY_CONNECTED', PipeError.PIPE_ALREADY_CONNECTED)
  }

  static SERVER_ALREADY_LISTENING (msg) {
    return new PipeError(msg, 'SERVER_ALREADY_LISTENING', PipeError.SERVER_ALREADY_LISTENING)
  }

  static SERVER_IS_CLOSED (msg) {
    return new PipeError(msg, 'SERVER_IS_CLOSED', PipeError.SERVER_IS_CLOSED)
  }
}
{
  "name": "bare-pipe",
  "version": "3.3.8",
  "description": "Native I/O pipes for JavaScript",
  "exports": {
    ".": "./index.js",
    "./package": "./package.json",
    "./constants": "./lib/constants.js",
    "./errors": "./lib/errors.js"
  },
  "files": [
    "index.js",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "standard && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-pipe.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-pipe/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-pipe#readme",
  "dependencies": {
    "bare-events": "^2.0.0",
    "bare-stream": "^2.0.0"
  },
  "devDependencies": {
    "bare-path": "^3.0.0",
    "brittle": "^3.2.1",
    "cmake-bare": "^1.1.6",
    "standard": "^17.0.0"
  }
}
module.exports = require.addon()
/* global Bare */
const EventEmitter = require('bare-events')
const { Duplex } = require('bare-stream')
const dns = require('bare-dns')
const binding = require('./binding')
const constants = require('./lib/constants')
const errors = require('./lib/errors')
const ip = require('./lib/ip')

const defaultReadBufferSize = 65536

const Socket = exports.Socket = class TCPSocket extends Duplex {
  constructor (opts = {}) {
    super({ eagerOpen: true })

    const {
      readBufferSize = defaultReadBufferSize,
      allowHalfOpen = true
    } = opts

    this._state = 0

    this._allowHalfOpen = allowHalfOpen

    this._remotePort = -1
    this._remoteHost = null
    this._remoteFamily = 0

    this._pendingOpen = null
    this._pendingWrite = null
    this._pendingFinal = null
    this._pendingDestroy = null

    this._timer = null
    this._timeout = 0

    this._buffer = Buffer.alloc(readBufferSize)

    this._handle = binding.init(this._buffer, this,
      noop,
      this._onconnect,
      this._onread,
      this._onwrite,
      this._onfinal,
      this._onclose
    )

    TCPSocket._sockets.add(this)
  }

  get connecting () {
    return (this._state & constants.state.CONNECTING) !== 0
  }

  get pending () {
    return (this._state & constants.state.CONNECTED) === 0
  }

  get timeout () {
    return this._timeout || undefined // For Node.js compatibility
  }

  connect (port, host = 'localhost', opts = {}, onconnect) {
    if (this._state & constants.state.CONNECTING || this._state & constants.state.CONNECTED) {
      throw errors.SOCKET_ALREADY_CONNECTED('Socket is already connected')
    }

    this._state |= constants.state.CONNECTING

    if (typeof host === 'function') {
      onconnect = host
      host = 'localhost'
    } else if (typeof opts === 'function') {
      onconnect = opts
      opts = {}
    }

    let family = 0

    if (typeof port === 'object' && port !== null) {
      opts = port || {}
      port = opts.port || 0
      host = opts.host || 'localhost'
      family = opts.family || 0
    }

    if (!host) host = 'localhost'

    const type = ip.isIP(host)

    if (type === 0) {
      const {
        lookup = dns.lookup,
        hints
      } = opts

      lookup(host, { family, hints }, (err, address, family) => {
        this.emit('lookup', err, address, family, host)

        this._state &= ~constants.state.CONNECTING

        if (err) {
          if (this._pendingOpen) this._continueOpen(err)
          else this.destroy(err)
          return
        }

        if (this._handle !== null) {
          this.connect(port, address, { ...opts, family }, onconnect)
        }
      })

      return this
    }

    family = type

    try {
      binding.connect(this._handle, port, host, family)

      if (opts.keepAlive === true) this.setKeepAlive(opts.keepAlive, opts.keepAliveInitialDelay)
      if (opts.noDelay === true) this.setNoDelay()
      if (opts.timeout) this.setTimeout(opts.timeout)

      this._remotePort = port
      this._remoteHost = host
      this._remoteFamily = family

      if (onconnect) this.once('connect', onconnect)
    } catch (err) {
      queueMicrotask(() => {
        if (this._pendingOpen) this._pendingOpen(err)
        else this.destroy(err)
      })
    }

    return this
  }

  setKeepAlive (enable = false, delay = 0) {
    if (typeof enable === 'number') {
      delay = enable
      enable = false
    }

    delay = Math.floor(delay / 1000)

    if (delay === 0) enable = false

    binding.keepalive(this._handle, enable, delay)

    return this
  }

  setNoDelay (enable = true) {
    binding.nodelay(this._handle, enable)

    return this
  }

  setTimeout (ms, ontimeout) {
    if (ms === 0) {
      clearTimeout(this._timer)
      this._timer = null
    } else {
      if (ontimeout) this.once('timeout', ontimeout)

      this._timer = setTimeout(() => this.emit('timeout'), ms)
      this._timer.unref()
    }

    this._timeout = ms

    return this
  }

  ref () {
    binding.ref(this._handle)
  }

  unref () {
    binding.unref(this._handle)
  }

  _open (cb) {
    if (this._state & constants.state.CONNECTED) return cb(null)
    this._pendingOpen = cb
  }

  _read () {
    if ((this._state & constants.state.READING) === 0) {
      this._state |= constants.state.READING
      binding.resume(this._handle)
    }
  }

  _writev (batch, cb) {
    this._pendingWrite = [cb, batch]
    binding.writev(this._handle, batch.map(({ chunk }) => chunk))
  }

  _final (cb) {
    this._pendingFinal = cb
    binding.end(this._handle)
  }

  _predestroy () {
    if (this._state & constants.state.CLOSING) return
    this._state |= constants.state.CLOSING
    binding.close(this._handle)
    TCPSocket._sockets.delete(this)
  }

  _destroy (err, cb) {
    if (this._state & constants.state.CLOSING) return cb(err)
    this._state |= constants.state.CLOSING
    this._pendingDestroy = cb
    binding.close(this._handle)
    TCPSocket._sockets.delete(this)
  }

  _continueOpen (err) {
    if (this._pendingOpen === null) return
    const cb = this._pendingOpen
    this._pendingOpen = null
    cb(err)
  }

  _continueWrite (err) {
    if (this._pendingWrite === null) return
    const cb = this._pendingWrite[0]
    this._pendingWrite = null
    cb(err)
  }

  _continueFinal (err) {
    if (this._pendingFinal === null) return
    const cb = this._pendingFinal
    this._pendingFinal = null
    cb(err)
  }

  _continueDestroy () {
    if (this._pendingDestroy === null) return
    const cb = this._pendingDestroy
    this._pendingDestroy = null
    cb(null)
  }

  _onconnect (err) {
    if (err) {
      if (this._pendingOpen) this._continueOpen(err)
      else this.destroy(err)
      return
    }

    this._state |= constants.state.CONNECTED
    this._state &= ~constants.state.CONNECTING
    this._continueOpen()

    this.emit('connect')
  }

  _onread (err, read) {
    if (this._timer) this._timer.refresh()

    if (err) {
      this.destroy(err)
      return
    }

    if (read === 0) {
      this.push(null)
      if (this._allowHalfOpen === false) this.end()
      return
    }

    const copy = Buffer.allocUnsafe(read)
    copy.set(this._buffer.subarray(0, read))

    if (this.push(copy) === false && this.destroying === false) {
      this._state &= ~constants.state.READING
      binding.pause(this._handle)
    }
  }

  _onwrite (err) {
    if (this._timer) this._timer.refresh()

    this._continueWrite(err)
  }

  _onfinal (err) {
    this._continueFinal(err)
  }

  _onclose () {
    clearTimeout(this._timer)

    this._handle = null
    this._continueDestroy()
  }

  static _sockets = new Set()
}

const Server = exports.Server = class TCPServer extends EventEmitter {
  constructor (opts = {}, onconnection) {
    if (typeof opts === 'function') {
      onconnection = opts
      opts = {}
    }

    super()

    const {
      readBufferSize = defaultReadBufferSize,
      allowHalfOpen = true
    } = opts

    this._state = 0

    this._readBufferSize = readBufferSize
    this._allowHalfOpen = allowHalfOpen

    this._keepAlive = opts.keepAlive
    this._keepAliveDelay = opts.keepAliveInitialDelay
    this._noDelay = opts.noDelay

    this._port = -1
    this._host = null
    this._family = 0
    this._connections = new Set()

    this._error = null
    this._handle = null

    if (onconnection) this.on('connection', onconnection)

    TCPServer._servers.add(this)
  }

  get listening () {
    return (this._state & constants.state.BOUND) !== 0
  }

  address () {
    if ((this._state & constants.state.BOUND) === 0) {
      return null
    }

    return {
      address: this._host,
      family: `IPv${this._family}`,
      port: this._port
    }
  }

  listen (port = 0, host = 'localhost', backlog = 511, opts = {}, onlistening) {
    if (this._state & constants.state.BINDING || this._state & constants.state.BOUND) {
      throw errors.SERVER_ALREADY_LISTENING('Server is already listening')
    }

    if (this._state & constants.state.CLOSING) {
      throw errors.SERVER_IS_CLOSED('Server is closed')
    }

    this._state |= constants.state.BINDING

    if (typeof port === 'function') {
      onlistening = port
      port = 0
    } else if (typeof host === 'function') {
      onlistening = host
      host = 'localhost'
    } else if (typeof backlog === 'function') {
      onlistening = backlog
      backlog = 511
    } else if (typeof opts === 'function') {
      onlistening = opts
      opts = {}
    }

    let family = 0

    if (typeof port === 'object' && port !== null) {
      opts = port || {}
      port = opts.port || 0
      host = opts.host || 'localhost'
      family = opts.family || 0
      backlog = opts.backlog || 511
    }

    if (!host) host = 'localhost'
    if (!backlog) backlog = 511

    const type = ip.isIP(host)

    if (type === 0) {
      const {
        lookup = dns.lookup,
        hints
      } = opts

      lookup(host, { family, hints }, (err, address, family) => {
        if (this._state & constants.state.CLOSING) return

        this.emit('lookup', err, address, family, host)

        this._state &= ~constants.state.BINDING

        if (err) return this.emit('error', err)

        this.listen(port, address, backlog, { ...opts, family }, onlistening)
      })

      return this
    }

    family = type

    this._handle = binding.init(empty, this,
      this._onconnection,
      noop,
      noop,
      noop,
      noop,
      this._onclose
    )

    if (this._state & constants.state.UNREFED) binding.unref(this._handle)

    try {
      this._port = binding.bind(this._handle, port, host, backlog, family)
      this._host = host
      this._family = family
      this._state |= constants.state.BOUND
      this._state &= ~constants.state.BINDING

      if (onlistening) this.once('listening', onlistening)

      queueMicrotask(() => this.emit('listening'))
    } catch (err) {
      this._error = err

      binding.close(this._handle)
    }

    return this
  }

  close (onclose) {
    if (onclose) this.once('close', onclose)
    if (this._state & constants.state.CLOSING) return
    this._state |= constants.state.CLOSING
    this._closeMaybe()
  }

  ref () {
    this._state &= ~constants.state.UNREFED
    if (this._handle !== null) binding.ref(this._handle)
  }

  unref () {
    this._state |= constants.state.UNREFED
    if (this._handle !== null) binding.unref(this._handle)
  }

  _closeMaybe () {
    if ((this._state & constants.state.CLOSING) && this._connections.size === 0) {
      if (this._handle !== null) binding.close(this._handle)
      else queueMicrotask(() => this.emit('close'))
      TCPServer._servers.delete(this)
    }
  }

  _onconnection (err) {
    if (err) {
      this.emit('error', err)
      return
    }

    if (this._state & constants.state.CLOSING) return

    const socket = new Socket({
      readBufferSize: this._readBufferSize,
      allowHalfOpen: this._allowHalfOpen
    })

    try {
      binding.accept(this._handle, socket._handle)

      socket._state |= constants.state.CONNECTED

      this._connections.add(socket)

      if (this._keepAlive === true) socket.setKeepAlive(this._keepAlive, this._keepAliveDelay)
      if (this._noDelay === true) socket.setNoDelay()

      socket.on('close', () => {
        this._connections.delete(socket)
        this._closeMaybe()
      })

      this.emit('connection', socket)
    } catch (err) {
      socket.destroy()

      throw err
    }
  }

  _onclose () {
    const err = this._error

    this._state &= ~constants.state.BINDING
    this._error = null
    this._handle = null

    if (err) this.emit('error', err)
    else this.emit('close')
  }

  static _servers = new Set()
}

exports.constants = constants
exports.errors = errors

exports.isIP = ip.isIP
exports.isIPv4 = ip.isIPv4
exports.isIPv6 = ip.isIPv6

exports.createConnection = function createConnection (port, host, opts, onconnect) {
  if (typeof host === 'function') {
    onconnect = host
    host = 'localhost'
  } else if (typeof opts === 'function') {
    onconnect = opts
    opts = {}
  }

  if (typeof port === 'object' && port !== null) {
    opts = port || {}
    port = opts.port || 0
    host = opts.host || 'localhost'
  }

  return new Socket(opts).connect(port, host, opts, onconnect)
}

// For Node.js compatibility
exports.connect = exports.createConnection

exports.createServer = function createServer (opts, onconnection) {
  return new Server(opts, onconnection)
}

Bare
  .on('exit', () => {
    for (const socket of Socket._sockets) {
      socket.destroy()
    }

    for (const server of Server._servers) {
      server.close()
    }
  })

const empty = Buffer.alloc(0)

function noop () {}
module.exports = {
  state: {
    CONNECTING: 0x1,
    CONNECTED: 0x2,
    BINDING: 0x4,
    BOUND: 0x8,
    READING: 0x10,
    CLOSING: 0x20,
    UNREFED: 0x40
  }
}
module.exports = class TCPError extends Error {
  constructor (msg, code, fn = TCPError) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name () {
    return 'TCPError'
  }

  static SOCKET_ALREADY_CONNECTED (msg) {
    return new TCPError(msg, 'SOCKET_ALREADY_CONNECTED', TCPError.SOCKET_ALREADY_CONNECTED)
  }

  static SERVER_ALREADY_LISTENING (msg) {
    return new TCPError(msg, 'SERVER_ALREADY_LISTENING', TCPError.SERVER_ALREADY_LISTENING)
  }

  static SERVER_IS_CLOSED (msg) {
    return new TCPError(msg, 'SERVER_IS_CLOSED', TCPError.SERVER_IS_CLOSED)
  }

  static INVALID_HOST (msg = 'Unrecognizable host format') {
    return new TCPError(msg, 'INVALID_HOST', TCPError.INVALID_HOST)
  }
}
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

const v4Seg = '(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])'
const v4Str = `(${v4Seg}[.]){3}${v4Seg}`
const IPv4Pattern = new RegExp(`^${v4Str}$`)

const v6Seg = '(?:[0-9a-fA-F]{1,4})'
const IPv6Pattern = new RegExp('^(' +
  `(?:${v6Seg}:){7}(?:${v6Seg}|:)|` +
  `(?:${v6Seg}:){6}(?:${v4Str}|:${v6Seg}|:)|` +
  `(?:${v6Seg}:){5}(?::${v4Str}|(:${v6Seg}){1,2}|:)|` +
  `(?:${v6Seg}:){4}(?:(:${v6Seg}){0,1}:${v4Str}|(:${v6Seg}){1,3}|:)|` +
  `(?:${v6Seg}:){3}(?:(:${v6Seg}){0,2}:${v4Str}|(:${v6Seg}){1,4}|:)|` +
  `(?:${v6Seg}:){2}(?:(:${v6Seg}){0,3}:${v4Str}|(:${v6Seg}){1,5}|:)|` +
  `(?:${v6Seg}:){1}(?:(:${v6Seg}){0,4}:${v4Str}|(:${v6Seg}){1,6}|:)|` +
  `(?::((?::${v6Seg}){0,5}:${v4Str}|(?::${v6Seg}){1,7}|:))` +
')(%[0-9a-zA-Z-.:]{1,})?$')

const isIPv4 = exports.isIPv4 = function isIPv4 (host) {
  return IPv4Pattern.test(host)
}

const isIPv6 = exports.isIPv6 = function isIPv6 (host) {
  return IPv6Pattern.test(host)
}

exports.isIP = function isIP (host) {
  if (isIPv4(host)) return 4
  if (isIPv6(host)) return 6
  return 0
}
{
  "name": "bare-tcp",
  "version": "1.9.1",
  "description": "Native TCP sockets for JavaScript",
  "exports": {
    ".": "./index.js",
    "./package": "./package.json",
    "./constants": "./lib/constants.js",
    "./errors": "./lib/errors.js"
  },
  "files": [
    "index.js",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "standard && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-tcp.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-tcp/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-tcp#readme",
  "dependencies": {
    "bare-dns": "^1.0.0",
    "bare-events": "^2.2.2",
    "bare-stream": "^2.0.0"
  },
  "devDependencies": {
    "brittle": "^3.5.0",
    "cmake-bare": "^1.1.6",
    "standard": "^17.1.0"
  }
}
{
  "name": "bare-net",
  "version": "1.0.1",
  "description": "TCP and IPC servers and clients for JavaScript",
  "exports": {
    ".": "./index.js",
    "./package": "./package.json"
  },
  "files": [
    "index.js"
  ],
  "scripts": {
    "test": "standard && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-net.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-net/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-net#readme",
  "dependencies": {
    "bare-events": "^2.2.2",
    "bare-pipe": "^3.2.0",
    "bare-stream": "^2.0.0",
    "bare-tcp": "^1.4.0"
  },
  "devDependencies": {
    "brittle": "^3.3.0",
    "standard": "^17.0.0"
  }
}
module.exports = require.addon()
const binding = require('./binding')
const errors = require('./lib/errors')
const constants = require('./lib/constants')

exports.constants = constants
exports.errors = errors

exports.EOL = binding.platform === 'win32' ? '\r\n' : '\n'

exports.devNull = binding.platform === 'win32' ? '\\\\.\\nul' : '/dev/null'

exports.platform = function platform() {
  return binding.platform
}

exports.arch = function arch() {
  return binding.arch
}

exports.type = binding.type
exports.version = binding.version
exports.release = binding.release
exports.machine = binding.machine
exports.execPath = binding.execPath
exports.pid = binding.pid
exports.ppid = binding.ppid
exports.cwd = binding.cwd
exports.chdir = binding.chdir
exports.tmpdir = binding.tmpdir
exports.homedir = binding.homedir
exports.hostname = binding.hostname
exports.userInfo = binding.userInfo
exports.groupInfo = binding.groupInfo

exports.networkInterfaces = function networkInterfaces() {
  const result = {}

  for (const entry of binding.networkInterfaces()) {
    const { name, ...properties } = entry

    if (result[name]) result[name].push(properties)
    else result[name] = [properties]
  }

  return result
}

exports.kill = function kill(pid, signal = constants.signals.SIGTERM) {
  if (typeof signal === 'string') {
    if (signal in constants.signals === false) {
      throw errors.UNKNOWN_SIGNAL('Unknown signal: ' + signal)
    }

    signal = constants.signals[signal]
  }

  binding.kill(pid, signal)
}

exports.endianness = function endianness() {
  return binding.isLittleEndian ? 'LE' : 'BE'
}

exports.availableParallelism = binding.availableParallelism

exports.cpuUsage = function cpuUsage(previous) {
  const current = binding.cpuUsage()

  if (previous) {
    return {
      user: current.user - previous.user,
      system: current.system - previous.system
    }
  }

  return current
}

exports.threadCpuUsage = function threadCpuUsage(previous) {
  const current = binding.threadCpuUsage()

  if (previous) {
    return {
      user: current.user - previous.user,
      system: current.system - previous.system
    }
  }

  return current
}

exports.resourceUsage = binding.resourceUsage
exports.memoryUsage = binding.memoryUsage
exports.freemem = binding.freemem
exports.totalmem = binding.totalmem
exports.availableMemory = binding.availableMemory
exports.constrainedMemory = binding.constrainedMemory
exports.uptime = binding.uptime
exports.loadavg = binding.loadavg
exports.cpus = binding.cpus

exports.getProcessTitle = binding.getProcessTitle

exports.setProcessTitle = function setProcessTitle(title) {
  if (typeof title !== 'string') title = title.toString()

  if (title.length >= 256) {
    throw errors.TITLE_OVERFLOW('Process title is too long')
  }

  binding.setProcessTitle(title)
}

exports.getPriority = function getPriority(pid = 0) {
  return binding.getPriority(pid)
}

exports.setPriority = function setPriority(pid, priority) {
  if (priority === undefined) {
    priority = pid
    pid = 0
  }

  binding.setPriority(pid, priority)
}

exports.getEnvKeys = binding.getEnvKeys
exports.getEnv = binding.getEnv
exports.hasEnv = binding.hasEnv
exports.setEnv = binding.setEnv
exports.unsetEnv = binding.unsetEnv
const binding = require('../binding')

module.exports = {
  signals: binding.signals,
  errnos: binding.errnos,
  priority: binding.priority
}
module.exports = class OSError extends Error {
  constructor(msg, fn = OSError, code = fn.name) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'OSError'
  }

  static UNKNOWN_SIGNAL(msg) {
    return new OSError(msg, OSError.UNKNOWN_SIGNAL)
  }

  static TITLE_OVERFLOW(msg) {
    return new OSError(msg, OSError.TITLE_OVERFLOW)
  }
}
{
  "name": "bare-os",
  "version": "3.9.1",
  "description": "Operating system utilities for Bare",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    },
    "./errors": {
      "types": "./lib/errors.d.ts",
      "default": "./lib/errors.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-os.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-os/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-os#readme",
  "engines": {
    "bare": ">=1.14.0"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "cmake-bare": "^1.1.6",
    "lunte": "^1.6.0",
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
/* global Bare */

// This export SHOULD NOT be shortened in any way as having the full
// `module.exports = require(...)` statement is crucial for synthesizing
// ESM exports.

if (Bare.platform === 'win32') {
  module.exports = require('./lib/win32')
} else {
  module.exports = require('./lib/posix')
}
module.exports = {
  CHAR_UPPERCASE_A: 0x41,
  CHAR_LOWERCASE_A: 0x61,
  CHAR_UPPERCASE_Z: 0x5a,
  CHAR_LOWERCASE_Z: 0x7a,
  CHAR_DOT: 0x2e,
  CHAR_FORWARD_SLASH: 0x2f,
  CHAR_BACKWARD_SLASH: 0x5c,
  CHAR_COLON: 0x3a,
  CHAR_QUESTION_MARK: 0x3f
}
const os = require('bare-os')

const { normalizeString } = require('./shared')
const {
  CHAR_DOT,
  CHAR_FORWARD_SLASH
} = require('./constants')

function isPosixPathSeparator (code) {
  return code === CHAR_FORWARD_SLASH
}

exports.win32 = require('./win32')
exports.posix = exports

exports.sep = '/'
exports.delimiter = ':'

exports.resolve = function resolve (...args) {
  let resolvedPath = ''
  let resolvedAbsolute = false

  for (let i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) {
    const path = i >= 0 ? args[i] : os.cwd()

    if (path.length === 0) {
      continue
    }

    resolvedPath = `${path}/${resolvedPath}`
    resolvedAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH
  }

  resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute, '/', isPosixPathSeparator)

  if (resolvedAbsolute) {
    return `/${resolvedPath}`
  }

  return resolvedPath.length > 0 ? resolvedPath : '.'
}

exports.normalize = function normalize (path) {
  if (path.length === 0) return '.'

  const isAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH
  const trailingSeparator = path.charCodeAt(path.length - 1) === CHAR_FORWARD_SLASH

  path = normalizeString(path, !isAbsolute, '/', isPosixPathSeparator)

  if (path.length === 0) {
    if (isAbsolute) return '/'
    return trailingSeparator ? './' : '.'
  }

  if (trailingSeparator) path += '/'

  return isAbsolute ? `/${path}` : path
}

exports.isAbsolute = function isAbsolute (path) {
  return path.length > 0 && path.charCodeAt(0) === CHAR_FORWARD_SLASH
}

exports.join = function join (...args) {
  if (args.length === 0) return '.'
  let joined
  for (let i = 0; i < args.length; ++i) {
    const arg = args[i]
    if (arg.length > 0) {
      if (joined === undefined) joined = arg
      else joined += `/${arg}`
    }
  }
  if (joined === undefined) return '.'
  return exports.normalize(joined)
}

exports.relative = function relative (from, to) {
  if (from === to) return ''

  from = exports.resolve(from)
  to = exports.resolve(to)

  if (from === to) return ''

  const fromStart = 1
  const fromEnd = from.length
  const fromLen = fromEnd - fromStart
  const toStart = 1
  const toLen = to.length - toStart

  const length = (fromLen < toLen ? fromLen : toLen)
  let lastCommonSep = -1
  let i = 0
  for (; i < length; i++) {
    const fromCode = from.charCodeAt(fromStart + i)
    if (fromCode !== to.charCodeAt(toStart + i)) {
      break
    } else if (fromCode === CHAR_FORWARD_SLASH) {
      lastCommonSep = i
    }
  }
  if (i === length) {
    if (toLen > length) {
      if (to.charCodeAt(toStart + i) === CHAR_FORWARD_SLASH) {
        return to.substring(toStart + i + 1)
      }
      if (i === 0) {
        return to.substring(toStart + i)
      }
    } else if (fromLen > length) {
      if (from.charCodeAt(fromStart + i) === CHAR_FORWARD_SLASH) {
        lastCommonSep = i
      } else if (i === 0) {
        lastCommonSep = 0
      }
    }
  }

  let out = ''
  for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
    if (i === fromEnd || from.charCodeAt(i) === CHAR_FORWARD_SLASH) {
      out += out.length === 0 ? '..' : '/..'
    }
  }

  return `${out}${to.substring(toStart + lastCommonSep)}`
}

exports.toNamespacedPath = function toNamespacedPath (path) {
  return path
}

exports.dirname = function dirname (path) {
  if (path.length === 0) return '.'
  const hasRoot = path.charCodeAt(0) === CHAR_FORWARD_SLASH
  let end = -1
  let matchedSlash = true
  for (let i = path.length - 1; i >= 1; --i) {
    if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) {
      if (!matchedSlash) {
        end = i
        break
      }
    } else {
      matchedSlash = false
    }
  }

  if (end === -1) return hasRoot ? '/' : '.'
  if (hasRoot && end === 1) return '//'
  return path.substring(0, end)
}

exports.basename = function basename (path, suffix) {
  let start = 0
  let end = -1
  let matchedSlash = true

  if (suffix !== undefined && suffix.length > 0 && suffix.length <= path.length) {
    if (suffix === path) { return '' }
    let extIdx = suffix.length - 1
    let firstNonSlashEnd = -1
    for (let i = path.length - 1; i >= 0; --i) {
      const code = path.charCodeAt(i)
      if (code === CHAR_FORWARD_SLASH) {
        if (!matchedSlash) {
          start = i + 1
          break
        }
      } else {
        if (firstNonSlashEnd === -1) {
          matchedSlash = false
          firstNonSlashEnd = i + 1
        }
        if (extIdx >= 0) {
          if (code === suffix.charCodeAt(extIdx)) {
            if (--extIdx === -1) {
              end = i
            }
          } else {
            extIdx = -1
            end = firstNonSlashEnd
          }
        }
      }
    }

    if (start === end) end = firstNonSlashEnd
    else if (end === -1) end = path.length
    return path.substring(start, end)
  }

  for (let i = path.length - 1; i >= 0; --i) {
    if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) {
      if (!matchedSlash) {
        start = i + 1
        break
      }
    } else if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
  }

  if (end === -1) return ''
  return path.substring(start, end)
}

exports.extname = function extname (path) {
  let startDot = -1
  let startPart = 0
  let end = -1
  let matchedSlash = true
  let preDotState = 0
  for (let i = path.length - 1; i >= 0; --i) {
    const code = path.charCodeAt(i)
    if (code === CHAR_FORWARD_SLASH) {
      if (!matchedSlash) {
        startPart = i + 1
        break
      }
      continue
    }
    if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
    if (code === CHAR_DOT) {
      if (startDot === -1) startDot = i
      else if (preDotState !== 1) preDotState = 1
    } else if (startDot !== -1) {
      preDotState = -1
    }
  }

  if (startDot === -1 || end === -1 || preDotState === 0 || (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1)) {
    return ''
  }
  return path.substring(startDot, end)
}
const {
  CHAR_DOT,
  CHAR_FORWARD_SLASH
} = require('./constants')

exports.normalizeString = function normalizeString (path, allowAboveRoot, separator, isPathSeparator) {
  let res = ''
  let lastSegmentLength = 0
  let lastSlash = -1
  let dots = 0
  let code = 0
  for (let i = 0; i <= path.length; ++i) {
    if (i < path.length) {
      code = path.charCodeAt(i)
    } else if (isPathSeparator(code)) {
      break
    } else {
      code = CHAR_FORWARD_SLASH
    }

    if (isPathSeparator(code)) {
      if (lastSlash === i - 1 || dots === 1) ;
      else if (dots === 2) {
        if (res.length < 2 || lastSegmentLength !== 2 || res.charCodeAt(res.length - 1) !== CHAR_DOT || res.charCodeAt(res.length - 2) !== CHAR_DOT) {
          if (res.length > 2) {
            const lastSlashIndex = res.lastIndexOf(separator)
            if (lastSlashIndex === -1) {
              res = ''
              lastSegmentLength = 0
            } else {
              res = res.substring(0, lastSlashIndex)
              lastSegmentLength =
                res.length - 1 - res.lastIndexOf(separator)
            }
            lastSlash = i
            dots = 0
            continue
          } else if (res.length !== 0) {
            res = ''
            lastSegmentLength = 0
            lastSlash = i
            dots = 0
            continue
          }
        }
        if (allowAboveRoot) {
          res += res.length > 0 ? `${separator}..` : '..'
          lastSegmentLength = 2
        }
      } else {
        if (res.length > 0) {
          res += `${separator}${path.substring(lastSlash + 1, i)}`
        } else {
          res = path.substring(lastSlash + 1, i)
        }
        lastSegmentLength = i - lastSlash - 1
      }
      lastSlash = i
      dots = 0
    } else if (code === CHAR_DOT && dots !== -1) {
      ++dots
    } else {
      dots = -1
    }
  }
  return res
}
const os = require('bare-os')

const { normalizeString } = require('./shared')
const {
  CHAR_UPPERCASE_A,
  CHAR_LOWERCASE_A,
  CHAR_UPPERCASE_Z,
  CHAR_LOWERCASE_Z,
  CHAR_DOT,
  CHAR_FORWARD_SLASH,
  CHAR_BACKWARD_SLASH,
  CHAR_COLON,
  CHAR_QUESTION_MARK
} = require('./constants')

function isWindowsPathSeparator (code) {
  return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH
}

function isWindowsDeviceRoot (code) {
  return (code >= CHAR_UPPERCASE_A && code <= CHAR_UPPERCASE_Z) ||
         (code >= CHAR_LOWERCASE_A && code <= CHAR_LOWERCASE_Z)
}

exports.posix = require('./posix')
exports.win32 = exports

exports.sep = '\\'
exports.delimiter = ';'

exports.resolve = function resolve (...args) {
  let resolvedDevice = ''
  let resolvedTail = ''
  let resolvedAbsolute = false

  for (let i = args.length - 1; i >= -1; i--) {
    let path
    if (i >= 0) {
      path = args[i]

      if (path.length === 0) continue
    } else if (resolvedDevice.length === 0) {
      path = os.cwd()
    } else {
      path = os.getEnv(`=${resolvedDevice}`) || os.cwd()

      if (path === undefined || (path.substring(0, 2).toLowerCase() !== resolvedDevice.toLowerCase() && path.charCodeAt(2) === CHAR_BACKWARD_SLASH)) {
        path = `${resolvedDevice}\\`
      }
    }

    const len = path.length
    let rootEnd = 0
    let device = ''
    let isAbsolute = false
    const code = path.charCodeAt(0)

    if (len === 1) {
      if (isWindowsPathSeparator(code)) {
        rootEnd = 1
        isAbsolute = true
      }
    } else if (isWindowsPathSeparator(code)) {
      isAbsolute = true

      if (isWindowsPathSeparator(path.charCodeAt(1))) {
        let j = 2
        let last = j
        while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
          j++
        }
        if (j < len && j !== last) {
          const firstPart = path.substring(last, j)
          last = j
          while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
            j++
          }
          if (j < len && j !== last) {
            last = j
            while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
              j++
            }
            if (j === len || j !== last) {
              device = `\\\\${firstPart}\\${path.substring(last, j)}`
              rootEnd = j
            }
          }
        }
      } else {
        rootEnd = 1
      }
    } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
      device = path.substring(0, 2)
      rootEnd = 2
      if (len > 2 && isWindowsPathSeparator(path.charCodeAt(2))) {
        isAbsolute = true
        rootEnd = 3
      }
    }

    if (device.length > 0) {
      if (resolvedDevice.length > 0) {
        if (device.toLowerCase() !== resolvedDevice.toLowerCase()) { continue }
      } else {
        resolvedDevice = device
      }
    }

    if (resolvedAbsolute) {
      if (resolvedDevice.length > 0) { break }
    } else {
      resolvedTail = `${path.substring(rootEnd)}\\${resolvedTail}`
      resolvedAbsolute = isAbsolute
      if (isAbsolute && resolvedDevice.length > 0) {
        break
      }
    }
  }

  resolvedTail = normalizeString(resolvedTail, !resolvedAbsolute, '\\', isWindowsPathSeparator)

  return resolvedAbsolute ? `${resolvedDevice}\\${resolvedTail}` : `${resolvedDevice}${resolvedTail}` || '.'
}

exports.normalize = function normalize (path) {
  const len = path.length
  if (len === 0) return '.'
  let rootEnd = 0
  let device
  let isAbsolute = false
  const code = path.charCodeAt(0)

  if (len === 1) {
    return code === CHAR_FORWARD_SLASH ? '\\' : path
  }

  if (isWindowsPathSeparator(code)) {
    isAbsolute = true

    if (isWindowsPathSeparator(path.charCodeAt(1))) {
      let j = 2
      let last = j
      while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
        j++
      }
      if (j < len && j !== last) {
        const firstPart = path.substring(last, j)
        last = j
        while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
          j++
        }
        if (j < len && j !== last) {
          last = j
          while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
            j++
          }
          if (j === len) {
            return `\\\\${firstPart}\\${path.substring(last)}\\`
          }
          if (j !== last) {
            device = `\\\\${firstPart}\\${path.substring(last, j)}`
            rootEnd = j
          }
        }
      }
    } else {
      rootEnd = 1
    }
  } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
    device = path.substring(0, 2)
    rootEnd = 2
    if (len > 2 && isWindowsPathSeparator(path.charCodeAt(2))) {
      isAbsolute = true
      rootEnd = 3
    }
  }

  let tail = rootEnd < len ? normalizeString(path.substring(rootEnd), !isAbsolute, '\\', isWindowsPathSeparator) : ''
  if (tail.length === 0 && !isAbsolute) {
    tail = '.'
  }
  if (tail.length > 0 && isWindowsPathSeparator(path.charCodeAt(len - 1))) {
    tail += '\\'
  }
  if (device === undefined) {
    return isAbsolute ? `\\${tail}` : tail
  }
  return isAbsolute ? `${device}\\${tail}` : `${device}${tail}`
}

exports.isAbsolute = function isAbsolute (path) {
  const len = path.length
  if (len === 0) return false

  const code = path.charCodeAt(0)

  return isWindowsPathSeparator(code) || (len > 2 && isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON && isWindowsPathSeparator(path.charCodeAt(2)))
}

exports.join = function join (...args) {
  if (args.length === 0) return '.'

  let joined
  let firstPart
  for (let i = 0; i < args.length; ++i) {
    const arg = args[i]
    if (arg.length > 0) {
      if (joined === undefined) joined = firstPart = arg
      else joined += `\\${arg}`
    }
  }

  if (joined === undefined) return '.'

  let needsReplace = true
  let slashCount = 0
  if (isWindowsPathSeparator(firstPart.charCodeAt(0))) {
    ++slashCount
    const firstLen = firstPart.length
    if (firstLen > 1 && isWindowsPathSeparator(firstPart.charCodeAt(1))) {
      ++slashCount
      if (firstLen > 2) {
        if (isWindowsPathSeparator(firstPart.charCodeAt(2))) {
          ++slashCount
        } else {
          needsReplace = false
        }
      }
    }
  }
  if (needsReplace) {
    while (slashCount < joined.length && isWindowsPathSeparator(joined.charCodeAt(slashCount))) {
      slashCount++
    }

    if (slashCount >= 2) {
      joined = `\\${joined.substring(slashCount)}`
    }
  }

  return exports.normalize(joined)
}

exports.relative = function relative (from, to) {
  if (from === to) return ''

  const fromOrig = exports.resolve(from)
  const toOrig = exports.resolve(to)

  if (fromOrig === toOrig) return ''

  from = fromOrig.toLowerCase()
  to = toOrig.toLowerCase()

  if (from === to) return ''

  let fromStart = 0
  while (fromStart < from.length && from.charCodeAt(fromStart) === CHAR_BACKWARD_SLASH) {
    fromStart++
  }
  let fromEnd = from.length
  while (fromEnd - 1 > fromStart && from.charCodeAt(fromEnd - 1) === CHAR_BACKWARD_SLASH) {
    fromEnd--
  }
  const fromLen = fromEnd - fromStart

  let toStart = 0
  while (toStart < to.length && to.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) {
    toStart++
  }
  let toEnd = to.length
  while (toEnd - 1 > toStart && to.charCodeAt(toEnd - 1) === CHAR_BACKWARD_SLASH) {
    toEnd--
  }
  const toLen = toEnd - toStart

  const length = fromLen < toLen ? fromLen : toLen
  let lastCommonSep = -1
  let i = 0
  for (; i < length; i++) {
    const fromCode = from.charCodeAt(fromStart + i)
    if (fromCode !== to.charCodeAt(toStart + i)) {
      break
    } else if (fromCode === CHAR_BACKWARD_SLASH) {
      lastCommonSep = i
    }
  }

  if (i !== length) {
    if (lastCommonSep === -1) return toOrig
  } else {
    if (toLen > length) {
      if (to.charCodeAt(toStart + i) === CHAR_BACKWARD_SLASH) {
        return toOrig.substring(toStart + i + 1)
      }
      if (i === 2) {
        return toOrig.substring(toStart + i)
      }
    }
    if (fromLen > length) {
      if (from.charCodeAt(fromStart + i) === CHAR_BACKWARD_SLASH) {
        lastCommonSep = i
      } else if (i === 2) {
        lastCommonSep = 3
      }
    }
    if (lastCommonSep === -1) lastCommonSep = 0
  }

  let out = ''
  for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
    if (i === fromEnd || from.charCodeAt(i) === CHAR_BACKWARD_SLASH) {
      out += out.length === 0 ? '..' : '\\..'
    }
  }

  toStart += lastCommonSep

  if (out.length > 0) {
    return `${out}${toOrig.substring(toStart, toEnd)}`
  }
  if (toOrig.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) {
    ++toStart
  }
  return toOrig.substring(toStart, toEnd)
}

exports.toNamespacedPath = function toNamespacedPath (path) {
  if (path.length === 0) return path

  const resolvedPath = exports.resolve(path)

  if (resolvedPath.length <= 2) return path

  if (resolvedPath.charCodeAt(0) === CHAR_BACKWARD_SLASH) {
    if (resolvedPath.charCodeAt(1) === CHAR_BACKWARD_SLASH) {
      const code = resolvedPath.charCodeAt(2)
      if (code !== CHAR_QUESTION_MARK && code !== CHAR_DOT) {
        return `\\\\?\\UNC\\${resolvedPath.substring(2)}`
      }
    }
  } else if (
    isWindowsDeviceRoot(resolvedPath.charCodeAt(0)) &&
      resolvedPath.charCodeAt(1) === CHAR_COLON &&
      resolvedPath.charCodeAt(2) === CHAR_BACKWARD_SLASH
  ) {
    return `\\\\?\\${resolvedPath}`
  }

  return path
}

exports.dirname = function dirname (path) {
  const len = path.length
  if (len === 0) return '.'
  let rootEnd = -1
  let offset = 0
  const code = path.charCodeAt(0)

  if (len === 1) {
    return isWindowsPathSeparator(code) ? path : '.'
  }

  if (isWindowsPathSeparator(code)) {
    rootEnd = offset = 1

    if (isWindowsPathSeparator(path.charCodeAt(1))) {
      let j = 2
      let last = j
      while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
        j++
      }
      if (j < len && j !== last) {
        last = j
        while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
          j++
        }
        if (j < len && j !== last) {
          last = j
          while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
            j++
          }
          if (j === len) {
            return path
          }
          if (j !== last) {
            rootEnd = offset = j + 1
          }
        }
      }
    }
  } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
    rootEnd = len > 2 && isWindowsPathSeparator(path.charCodeAt(2)) ? 3 : 2
    offset = rootEnd
  }

  let end = -1
  let matchedSlash = true
  for (let i = len - 1; i >= offset; --i) {
    if (isWindowsPathSeparator(path.charCodeAt(i))) {
      if (!matchedSlash) {
        end = i
        break
      }
    } else {
      matchedSlash = false
    }
  }

  if (end === -1) {
    if (rootEnd === -1) return '.'

    end = rootEnd
  }
  return path.substring(0, end)
}

exports.basename = function basename (path, suffix) {
  let start = 0
  let end = -1
  let matchedSlash = true

  if (path.length >= 2 && isWindowsDeviceRoot(path.charCodeAt(0)) && path.charCodeAt(1) === CHAR_COLON) {
    start = 2
  }

  if (suffix !== undefined && suffix.length > 0 && suffix.length <= path.length) {
    if (suffix === path) return ''
    let extIdx = suffix.length - 1
    let firstNonSlashEnd = -1
    for (let i = path.length - 1; i >= start; --i) {
      const code = path.charCodeAt(i)
      if (isWindowsPathSeparator(code)) {
        if (!matchedSlash) {
          start = i + 1
          break
        }
      } else {
        if (firstNonSlashEnd === -1) {
          matchedSlash = false
          firstNonSlashEnd = i + 1
        }
        if (extIdx >= 0) {
          if (code === suffix.charCodeAt(extIdx)) {
            if (--extIdx === -1) {
              end = i
            }
          } else {
            extIdx = -1
            end = firstNonSlashEnd
          }
        }
      }
    }

    if (start === end) end = firstNonSlashEnd
    else if (end === -1) end = path.length
    return path.substring(start, end)
  }
  for (let i = path.length - 1; i >= start; --i) {
    if (isWindowsPathSeparator(path.charCodeAt(i))) {
      if (!matchedSlash) {
        start = i + 1
        break
      }
    } else if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
  }

  if (end === -1) return ''
  return path.substring(start, end)
}

exports.extname = function extname (path) {
  let start = 0
  let startDot = -1
  let startPart = 0
  let end = -1
  let matchedSlash = true
  let preDotState = 0

  if (path.length >= 2 && path.charCodeAt(1) === CHAR_COLON && isWindowsDeviceRoot(path.charCodeAt(0))) {
    start = startPart = 2
  }

  for (let i = path.length - 1; i >= start; --i) {
    const code = path.charCodeAt(i)
    if (isWindowsPathSeparator(code)) {
      if (!matchedSlash) {
        startPart = i + 1
        break
      }
      continue
    }
    if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
    if (code === CHAR_DOT) {
      if (startDot === -1) startDot = i
      else if (preDotState !== 1) preDotState = 1
    } else if (startDot !== -1) {
      preDotState = -1
    }
  }

  if (startDot === -1 || end === -1 || preDotState === 0 || (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1)) {
    return ''
  }
  return path.substring(startDot, end)
}
{
  "name": "bare-path",
  "version": "3.0.0",
  "description": "Path manipulation library for JavaScript",
  "exports": {
    ".": "./index.js",
    "./package": "./package.json",
    "./posix": "./lib/posix.js",
    "./win32": "./lib/win32.js"
  },
  "files": [
    "index.js",
    "lib",
    "NOTICE"
  ],
  "scripts": {
    "test": "standard && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-path.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-path/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-path#readme",
  "dependencies": {
    "bare-os": "^3.0.1"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "standard": "^17.0.0"
  }
}
module.exports = require.addon()
const EventEmitter = require('bare-events')
const { Duplex } = require('bare-stream')
const binding = require('./binding')
const constants = require('./lib/constants')
const errors = require('./lib/errors')

const defaultReadBufferSize = 65536
const empty = Buffer.alloc(0)

module.exports = exports = class Pipe extends Duplex {
  constructor(path, opts = {}) {
    if (typeof path === 'object' && path !== null) {
      opts = path
      path = null
    }

    const { readBufferSize = defaultReadBufferSize, allowHalfOpen = true, eagerOpen = true } = opts

    super({ eagerOpen })

    this._state = 0

    this._allowHalfOpen = allowHalfOpen

    this._fd = -1
    this._path = null

    this._pendingOpen = null
    this._pendingWrite = null
    this._pendingFinal = null
    this._pendingDestroy = null

    this._buffer = Buffer.alloc(readBufferSize)

    this._handle = binding.init(
      this._buffer,
      this,
      noop,
      this._onconnect,
      this._onwrite,
      this._onfinal,
      this._onread,
      this._onclose
    )

    if (typeof path === 'number') {
      this.open(path)
    } else if (typeof path === 'string') {
      this.connect(path)
    }
  }

  get connecting() {
    return (this._state & constants.state.CONNECTING) !== 0
  }

  get pending() {
    return (this._state & constants.state.CONNECTED) === 0
  }

  get readyState() {
    if (this._state & constants.state.READABLE && this._state & constants.state.WRITABLE) {
      return 'open'
    }

    if (this._state & constants.state.READABLE) {
      return 'readOnly'
    }

    if (this._state & constants.state.WRITABLE) {
      return 'writeOnly'
    }

    return 'opening'
  }

  open(fd, opts = {}, onconnect) {
    if (typeof opts === 'function') {
      onconnect = opts
      opts = {}
    }

    if (typeof fd === 'object' && fd !== null) {
      opts = fd || {}
      fd = opts.fd
    }

    try {
      const status = binding.open(this._handle, fd)

      this._state |= constants.state.CONNECTED
      this._fd = fd

      if (status & binding.READABLE) {
        this._state |= constants.state.READABLE
      } else {
        this.push(null)
      }

      if (status & binding.WRITABLE) {
        this._state |= constants.state.WRITABLE
      } else {
        this.end()
      }

      if (onconnect) this.once('connect', onconnect)

      queueMicrotask(() => this.emit('connect'))
    } catch (err) {
      queueMicrotask(() => {
        if (this._pendingOpen) this._pendingOpen(err)
        else this.destroy(err)
      })
    }

    return this
  }

  connect(path, opts = {}, onconnect) {
    if (this._state & constants.state.CONNECTING || this._state & constants.state.CONNECTED) {
      throw errors.PIPE_ALREADY_CONNECTED('Pipe is already connected')
    }

    this._state |= constants.state.CONNECTING

    if (typeof opts === 'function') {
      onconnect = opts
      opts = {}
    }

    if (typeof path === 'object' && path !== null) {
      opts = path || {}
      path = opts.path
    }

    try {
      binding.connect(this._handle, path)

      this._path = path

      if (onconnect) this.once('connect', onconnect)
    } catch (err) {
      queueMicrotask(() => {
        if (this._pendingOpen) this._pendingOpen(err)
        else this.destroy(err)
      })
    }

    return this
  }

  ref() {
    binding.ref(this._handle)

    return this
  }

  unref() {
    binding.unref(this._handle)

    return this
  }

  _open(cb) {
    if (this._state & constants.state.CONNECTED) return cb(null)

    this._pendingOpen = cb
  }

  _read() {
    if ((this._state & constants.state.READING) === 0) {
      this._state |= constants.state.READING

      binding.resume(this._handle)
    }
  }

  _writev(batch, cb) {
    this._pendingWrite = [cb, batch]

    binding.writev(
      this._handle,
      batch.map(({ chunk }) => chunk)
    )
  }

  _final(cb) {
    if (this._state & constants.state.READABLE && this._state & constants.state.WRITABLE) {
      this._pendingFinal = cb

      binding.end(this._handle)
    } else {
      cb(null)
    }
  }

  _predestroy() {
    if (this._state & constants.state.CLOSING) return
    this._state |= constants.state.CLOSING

    binding.close(this._handle)
  }

  _destroy(err, cb) {
    if (this._state & constants.state.CLOSING) return cb(err)
    this._state |= constants.state.CLOSING

    this._pendingDestroy = cb

    binding.close(this._handle)
  }

  _continueOpen(err) {
    if (this._pendingOpen === null) return
    const cb = this._pendingOpen
    this._pendingOpen = null
    cb(err)
  }

  _continueWrite(err) {
    if (this._pendingWrite === null) return
    const cb = this._pendingWrite[0]
    this._pendingWrite = null
    cb(err)
  }

  _continueFinal(err) {
    if (this._pendingFinal === null) return
    const cb = this._pendingFinal
    this._pendingFinal = null
    cb(err)
  }

  _continueDestroy() {
    if (this._pendingDestroy === null) return
    const cb = this._pendingDestroy
    this._pendingDestroy = null
    cb(null)
  }

  _onconnect(err) {
    if (err) {
      if (this._pendingOpen) this._continueOpen(err)
      else this.destroy(err)
      return
    }

    this._state |= constants.state.CONNECTED | constants.state.READABLE | constants.state.WRITABLE
    this._state &= ~constants.state.CONNECTING
    this._continueOpen()

    this.emit('connect')
  }

  _onread(err, read) {
    if (err) {
      this.destroy(err)
      return
    }

    if (read === 0) {
      this.push(null)
      if (this._allowHalfOpen === false) this.end()
      return
    }

    const copy = Buffer.allocUnsafe(read)
    copy.set(this._buffer.subarray(0, read))

    if (this.push(copy) === false && this.destroying === false) {
      this._state &= ~constants.state.READING

      binding.pause(this._handle)
    }
  }

  _onwrite(err) {
    this._continueWrite(err)
  }

  _onfinal(err) {
    this._continueFinal(err === null || err.code === 'ENOTCONN' ? null : err)
  }

  _onclose() {
    this._continueDestroy()
  }

  _onspawn(readable, writable) {
    this._state |= constants.state.CONNECTED

    if (readable) {
      this._state |= constants.state.READABLE
    } else {
      this.push(null)
    }

    if (writable) {
      this._state |= constants.state.WRITABLE
    } else {
      this.end()
    }

    this._continueOpen()
  }
}

exports.Pipe = exports

exports.pipe = function pipe() {
  return binding.pipe()
}

exports.Server = class PipeServer extends EventEmitter {
  constructor(opts = {}, onconnection) {
    if (typeof opts === 'function') {
      onconnection = opts
      opts = {}
    }

    super()

    const {
      readBufferSize = defaultReadBufferSize,
      allowHalfOpen = true,
      pauseOnConnect = false
    } = opts

    this._state = 0

    this._readBufferSize = readBufferSize
    this._allowHalfOpen = allowHalfOpen
    this._pauseOnConnect = pauseOnConnect

    this._path = null
    this._connections = new Set()

    this._error = null
    this._handle = null

    if (onconnection) this.on('connection', onconnection)
  }

  get listening() {
    return (this._state & constants.state.BOUND) !== 0
  }

  address() {
    if ((this._state & constants.state.BOUND) === 0) {
      return null
    }

    return this._path
  }

  listen(path, backlog = 511, opts = {}, onlistening) {
    if (this._state & constants.state.BINDING || this._state & constants.state.BOUND) {
      throw errors.SERVER_ALREADY_LISTENING('Server is already listening')
    }

    if (this._state & constants.state.CLOSING) {
      throw errors.SERVER_IS_CLOSED('Server is closed')
    }

    this._state |= constants.state.BINDING

    if (typeof backlog === 'function') {
      onlistening = backlog
      backlog = 511
    } else if (typeof opts === 'function') {
      onlistening = opts
      opts = {}
    }

    if (typeof path === 'object' && path !== null) {
      opts = path || {}
      path = opts.path
      backlog = opts.backlog || 511
    }

    this._handle = binding.init(
      empty,
      this,
      this._onconnection,
      noop,
      noop,
      noop,
      noop,
      this._onclose
    )

    if (this._state & constants.state.UNREFED) binding.unref(this._handle)

    try {
      binding.bind(this._handle, path, backlog)

      this._path = path
      this._state |= constants.state.BOUND
      this._state &= ~constants.state.BINDING

      if (onlistening) this.once('listening', onlistening)

      queueMicrotask(() => this.emit('listening'))
    } catch (err) {
      this._error = err

      binding.close(this._handle)
    }

    return this
  }

  close(onclose) {
    if (onclose) this.once('close', onclose)

    if (this._state & constants.state.CLOSING) return
    this._state |= constants.state.CLOSING

    this._closeMaybe()

    return this
  }

  ref() {
    this._state &= ~constants.state.UNREFED

    if (this._handle !== null) binding.ref(this._handle)

    return this
  }

  unref() {
    this._state |= constants.state.UNREFED

    if (this._handle !== null) binding.unref(this._handle)

    return this
  }

  _closeMaybe() {
    if (this._state & constants.state.CLOSING && this._connections.size === 0) {
      if (this._handle !== null) binding.close(this._handle)
      else queueMicrotask(() => this.emit('close'))
    }
  }

  _onconnection(err) {
    if (err) {
      this.emit('error', err)
      return
    }

    if (this._state & constants.state.CLOSING) return

    const pipe = new exports.Pipe({
      readBufferSize: this._readBufferSize,
      allowHalfOpen: this._allowHalfOpen,
      eagerOpen: !this._pauseOnConnect
    })

    try {
      binding.accept(this._handle, pipe._handle)

      pipe._path = this._path
      pipe._state |= constants.state.CONNECTED | constants.state.READABLE | constants.state.WRITABLE

      this._connections.add(pipe)

      pipe.on('close', () => {
        this._connections.delete(pipe)
        this._closeMaybe()
      })

      this.emit('connection', pipe)
    } catch (err) {
      pipe.destroy()

      throw err
    }
  }

  _onclose() {
    const err = this._error

    this._state &= ~constants.state.BINDING
    this._error = null
    this._handle = null

    if (err) this.emit('error', err)
    else this.emit('close')
  }
}

exports.constants = constants
exports.errors = errors

exports.createConnection = function createConnection(path, opts, onconnect) {
  if (typeof opts === 'function') {
    onconnect = opts
    opts = {}
  }

  if (typeof path === 'object' && path !== null) {
    opts = path || {}
    path = opts.path
  }

  return new exports.Pipe(opts).connect(path, opts, onconnect)
}

exports.createServer = function createServer(opts, onconnection) {
  return new exports.Server(opts, onconnection)
}

function noop() {}
module.exports = {
  state: {
    CONNECTING: 0x1,
    CONNECTED: 0x2,
    BINDING: 0x4,
    BOUND: 0x8,
    READING: 0x10,
    CLOSING: 0x20,
    READABLE: 0x40,
    WRITABLE: 0x80,
    UNREFED: 0x100
  }
}
module.exports = class PipeError extends Error {
  constructor(msg, fn = PipeError, code = fn.name) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'PipeError'
  }

  static PIPE_ALREADY_CONNECTED(msg) {
    return new PipeError(msg, PipeError.PIPE_ALREADY_CONNECTED)
  }

  static SERVER_ALREADY_LISTENING(msg) {
    return new PipeError(msg, PipeError.SERVER_ALREADY_LISTENING)
  }

  static SERVER_IS_CLOSED(msg) {
    return new PipeError(msg, PipeError.SERVER_IS_CLOSED)
  }
}
{
  "name": "bare-pipe",
  "version": "4.1.5",
  "description": "Native I/O pipes for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    },
    "./errors": {
      "types": "./lib/errors.d.ts",
      "default": "./lib/errors.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-pipe.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-pipe/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-pipe#readme",
  "engines": {
    "bare": ">=1.16.0"
  },
  "dependencies": {
    "bare-events": "^2.0.0",
    "bare-stream": "^2.0.0"
  },
  "devDependencies": {
    "bare-path": "^3.0.0",
    "brittle": "^3.2.1",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  }
}
const abort = require('bare-abort')
const EventEmitter = require('bare-events')
const Signal = require('bare-signals')
const os = require('bare-os')
const env = require('bare-env')
const hrtime = require('bare-hrtime')
const stdio = require('bare-stdio')

class Process extends EventEmitter {
  constructor() {
    super()

    this._startTime = hrtime.bigint()

    EventEmitter.forward(Bare, this, [
      'uncaughtException',
      'unhandledRejection',
      'beforeExit',
      'exit',
      'suspend',
      'wakeup',
      'idle',
      'resume'
    ])

    const signals = new Signal.Emitter()

    signals.unref()

    EventEmitter.forward(signals, this, Object.keys(os.constants.signals))
  }

  get stdin() {
    return stdio.in
  }

  get stdout() {
    return stdio.out
  }

  get stderr() {
    return stdio.err
  }

  get platform() {
    return os.platform()
  }

  get arch() {
    return os.arch()
  }

  get title() {
    return os.getProcessTitle()
  }

  set title(title) {
    os.setProcessTitle(title)
  }

  get pid() {
    return os.pid()
  }

  get ppid() {
    return os.ppid()
  }

  get argv() {
    return Bare.argv
  }

  get execPath() {
    return os.execPath()
  }

  get exitCode() {
    return Bare.exitCode
  }

  set exitCode(code) {
    Bare.exitCode = code
  }

  get version() {
    return Bare.version
  }

  get versions() {
    return Bare.versions
  }

  get env() {
    return env
  }

  get hrtime() {
    return hrtime
  }

  abort() {
    abort()
  }

  exit(code) {
    Bare.exit(code)
  }

  suspend() {
    Bare.suspend()
  }

  resume() {
    Bare.resume()
  }

  cwd() {
    return os.cwd()
  }

  chdir(directory) {
    os.chdir(directory)
  }

  kill(pid, signal) {
    os.kill(pid, signal)
  }

  uptime() {
    return Number(hrtime.bigint() - this._startTime) / 1e9
  }

  cpuUsage(previous) {
    return os.cpuUsage(previous)
  }

  threadCpuUsage(previous) {
    return os.threadCpuUsage(previous)
  }

  resourceUsage() {
    return os.resourceUsage()
  }

  availableMemory() {
    return os.availableMemory()
  }

  constrainedMemory() {
    return os.constrainedMemory()
  }

  memoryUsage() {
    return os.memoryUsage()
  }

  nextTick(cb, ...args) {
    queueMicrotask(cb.bind(null, ...args))
  }

  [Symbol.for('bare.inspect')]() {
    return {
      __proto__: { constructor: Process },

      platform: this.platform,
      arch: this.arch,
      title: this.title,
      pid: this.pid,
      ppid: this.ppid,
      argv: this.argv,
      execPath: this.execPath,
      exitCode: this.exitCode,
      version: this.version,
      versions: this.versions,
      env: this.env
    }
  }
}

module.exports = new Process()
{
  "name": "bare-process",
  "version": "4.4.1",
  "description": "Node.js-compatible process control for Bare",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "global.js",
    "global.d.ts"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-process.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-process/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-process#readme",
  "dependencies": {
    "bare-abort": "^2.0.13",
    "bare-env": "^3.0.0",
    "bare-events": "^2.3.1",
    "bare-hrtime": "^2.0.0",
    "bare-os": "^3.7.1",
    "bare-signals": "^4.0.0",
    "bare-stdio": "^1.0.1"
  },
  "devDependencies": {
    "brittle": "^3.2.1",
    "lunte": "^1.6.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = require.addon()
const EventEmitter = require('bare-events')
const os = require('bare-os')
const binding = require('./binding')
const errors = require('./lib/errors')

const signals = os.constants.signals

module.exports = exports = class Signal extends EventEmitter {
  constructor(signum) {
    super()

    if (typeof signum === 'string') {
      if (signum in signals === false) {
        throw errors.UNKNOWN_SIGNAL(`Unknown signal '${signum}'`)
      }

      signum = signals[signum]
    }

    this._signum = signum
    this._closing = null
    this._handle = binding.init(this, this._onsignal, this._onclose)
  }

  start() {
    if (this._closing) throw errors.SIGNAL_CLOSED('Signal is closed')
    binding.start(this._handle, this._signum)
    return this
  }

  stop() {
    if (this._closing) return this
    binding.stop(this._handle)
    return this
  }

  ref() {
    if (this._closing) return this
    binding.ref(this._handle)
    return this
  }

  unref() {
    if (this._closing) return this
    binding.unref(this._handle)
    return this
  }

  close() {
    if (this._closing) return this._closing
    this._closing = EventEmitter.once(this, 'close')

    binding.close(this._handle)

    return this._closing
  }

  _onsignal() {
    this.emit('signal', this._signum)
  }

  _onclose() {
    this._handle = null

    this.emit('close')
  }

  static send(signum, pid = os.pid()) {
    os.kill(pid, signum)
  }
}

exports.Emitter = require('./lib/emitter')

exports.constants = signals
exports.errors = errors
const EventEmitter = require('bare-events')
const Signal = require('..')

module.exports = class SignalEmitter extends EventEmitter {
  constructor() {
    super()

    this._signals = new Map()
    this._unrefed = false

    this.on('newListener', this._onnewlistener).on(
      'removeListener',
      this._onremovelistener
    )
  }

  ref() {
    this._unrefed = false
    for (const signal of this._signals.values()) signal.ref()
    return this
  }

  unref() {
    this._unrefed = true
    for (const signal of this._signals.values()) signal.unref()
    return this
  }

  _onnewlistener(name) {
    if (name === 'newListener' || name === 'removeListener') return

    if (this.listenerCount(name) === 0) {
      const signal = new Signal(name)

      signal.on('signal', this._onsignal.bind(this, name)).start()

      if (this._unrefed) signal.unref()

      this._signals.set(name, signal)
    }
  }

  _onremovelistener(name) {
    if (name === 'newListener' || name === 'removeListener') return

    if (this.listenerCount(name) === 0) {
      const signal = this._signals.get(name)

      if (this._unrefed) signal.ref()

      signal.close()

      this._signals.delete(name)
    }
  }

  _onsignal(name) {
    this.emit(name, name, Signal.constants[name])
  }
}
module.exports = class SignalError extends Error {
  constructor(msg, fn = SignalError, code = fn.name) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'SignalError'
  }

  static UNKNOWN_SIGNAL(msg) {
    return new SignalError(msg, SignalError.UNKNOWN_SIGNAL)
  }

  static SIGNAL_CLOSED(msg) {
    return new SignalError(msg, SignalError.SIGNAL_CLOSED)
  }
}
{
  "name": "bare-signals",
  "version": "4.2.0",
  "description": "Native signal handling for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./errors": "./lib/errors.js",
    "./emitter": "./lib/emitter.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-signals.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-signals/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-signals#readme",
  "engines": {
    "bare": ">=1.7.0"
  },
  "dependencies": {
    "bare-events": "^2.5.3",
    "bare-os": "^3.3.1"
  },
  "devDependencies": {
    "brittle": "^3.2.1",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
module.exports = require.addon()
const fs = require('bare-fs')
const tty = require('bare-tty')
const Pipe = require('bare-pipe')
const binding = require('./binding')

const { TTY, NAMED_PIPE } = binding

class IO {
  constructor() {
    this._in = null
    this._out = null
    this._err = null
  }

  get in() {
    if (this._in === null) {
      switch (binding.guessType(0)) {
        case TTY:
          this._in = new tty.ReadStream(0)
          break
        case NAMED_PIPE:
          this._in = new Pipe(0, { eagerOpen: false })
          break
        default:
          this._in = fs.createReadStream(null, { fd: 0, eagerOpen: false })
      }
    }

    return this._in
  }

  get out() {
    if (this._out === null) {
      switch (binding.guessType(1)) {
        case TTY:
          this._out = new tty.WriteStream(1)
          break
        case NAMED_PIPE:
          this._out = new Pipe(1, { eagerOpen: false })
          this._out.unref()
          break
        default:
          this._out = fs.createWriteStream(null, { fd: 1, eagerOpen: false })
      }
    }

    return this._out
  }

  get err() {
    if (this._err === null) {
      switch (binding.guessType(2)) {
        case TTY:
          this._err = new tty.WriteStream(2)
          break
        case NAMED_PIPE:
          this._err = new Pipe(2, { eagerOpen: false })
          this._err.unref()
          break
        default:
          this._err = fs.createWriteStream(null, { fd: 2, eagerOpen: false })
      }
    }

    return this._err
  }
}

module.exports = new IO()
{
  "name": "bare-stdio",
  "version": "1.0.2",
  "description": "Standard input/output streams for Bare",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./constants": "./lib/constants.js",
    "./errors": "./lib/errors.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-stdio.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-stdio/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-stdio#readme",
  "dependencies": {
    "bare-fs": "^4.5.2",
    "bare-pipe": "^4.1.5",
    "bare-tty": "^5.0.3"
  },
  "devDependencies": {
    "bare-os": "^3.6.2",
    "bare-path": "^3.0.0",
    "bare-subprocess": "^3.1.4",
    "brittle": "^3.19.1",
    "cmake-bare": "^1.7.7",
    "lunte": "^1.4.0",
    "prettier": "^3.8.1",
    "prettier-config-holepunch": "^2.0.0",
    "tt-native": "^1.1.1"
  }
}
const stream = require('streamx')
const { ReadableStream, WritableStream } = require('./web')

const defaultEncoding = 'utf8'

module.exports = exports = stream.Stream

exports.pipeline = stream.pipeline

exports.isStream = stream.isStream
exports.isEnding = stream.isEnding
exports.isEnded = stream.isEnded
exports.isFinishing = stream.isFinishing
exports.isFinished = stream.isFinished
exports.isDisturbed = stream.isDisturbed

exports.isErrored = function isErrored(stream) {
  return exports.getStreamError(stream) !== null
}

exports.isReadable = function isReadable(stream) {
  return stream.readable && !stream.destroying && !exports.isEnded(stream)
}

exports.isWritable = function isWritable(stream) {
  return stream.writable && !stream.destroying && !exports.isFinishing(stream)
}

exports.getStreamError = stream.getStreamError

exports.addAbortSignal = function addAbortSignal(signal, stream) {
  function onAbort() {
    stream.destroy(signal.reason)
  }

  if (signal.aborted) onAbort()
  else signal.addEventListener('abort', onAbort)

  return stream
}

exports.Stream = exports

exports.Readable = class Readable extends stream.Readable {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthReadable: null,
      map: null,
      mapReadable: null
    })

    if (this._construct) this._open = this._construct

    if (this._read !== stream.Readable.prototype._read) {
      this._read = read.bind(this, this._read)
    }

    if (this._destroy !== stream.Stream.prototype._destroy) {
      this._destroy = destroy.bind(this, this._destroy)
    }
  }

  get closed() {
    return !exports.isReadable(this)
  }

  get errored() {
    return stream.getStreamError(this)
  }

  push(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = Buffer.from(chunk, encoding || defaultEncoding)
    }

    return super.push(chunk)
  }

  unshift(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = Buffer.from(chunk, encoding || defaultEncoding)
    }

    super.unshift(chunk)
  }

  static fromWeb(readableStream, opts = {}) {
    const stream = readableStream._stream

    if (opts.encoding) stream.setEncoding(opts.encoding)
    if (opts.signal) exports.addAbortSignal(opts.signal, stream)

    return stream
  }

  static toWeb(readable, opts = {}) {
    return new ReadableStream(readable, opts.strategy)
  }

  async [Symbol.asyncDispose]() {
    if (!this.destroyed) this.destroy()

    await new Promise((resolve) => exports.finished(this, resolve))
  }
}

exports.Writable = class Writable extends stream.Writable {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthWritable,
      map: null,
      mapWritable: null
    })

    if (this._construct) this._open = this._construct

    if (this._write !== stream.Writable.prototype._write) {
      this._write = write.bind(this, this._write)
    }

    if (this._destroy !== stream.Stream.prototype._destroy) {
      this._destroy = destroy.bind(this, this._destroy)
    }
  }

  get closed() {
    return !exports.isWritable(this)
  }

  get errored() {
    return stream.getStreamError(this)
  }

  write(chunk, encoding, cb) {
    if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = Buffer.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result = super.write({ chunk, encoding })

    if (cb) stream.Writable.drained(this).then(() => cb(null), cb)

    return result
  }

  end(chunk, encoding, cb) {
    if (typeof chunk === 'function') {
      cb = chunk
      chunk = null
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = Buffer.from(chunk, encoding || defaultEncoding)
    } else {
      encoding = 'buffer'
    }

    const result =
      chunk !== undefined && chunk !== null ? super.end({ chunk, encoding }) : super.end()

    if (cb) this.once('finish', () => cb(null))

    return result
  }

  static fromWeb(writableStream, opts = {}) {
    const stream = writableStream._stream

    if (opts.signal) exports.addAbortSignal(opts.signal, stream)

    return stream
  }

  static toWeb(writable) {
    return new WritableStream(writable)
  }

  async [Symbol.asyncDispose]() {
    if (!this.destroyed) this.destroy()

    await new Promise((resolve) => exports.finished(this, resolve))
  }
}

exports.Duplex = class Duplex extends stream.Duplex {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthReadable: null,
      byteLengthWritable,
      map: null,
      mapReadable: null,
      mapWritable: null
    })

    if (this._construct) this._open = this._construct

    if (this._read !== stream.Readable.prototype._read) {
      this._read = read.bind(this, this._read)
    }

    if (this._write !== stream.Duplex.prototype._write) {
      this._write = write.bind(this, this._write)
    }

    if (this._destroy !== stream.Stream.prototype._destroy) {
      this._destroy = destroy.bind(this, this._destroy)
    }
  }

  push(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = Buffer.from(chunk, encoding || defaultEncoding)
    }

    return super.push(chunk)
  }

  unshift(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = Buffer.from(chunk, encoding || defaultEncoding)
    }

    super.unshift(chunk)
  }

  write(chunk, encoding, cb) {
    if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = Buffer.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result = super.write({ chunk, encoding })

    if (cb) stream.Writable.drained(this).then(() => cb(null), cb)

    return result
  }

  end(chunk, encoding, cb) {
    if (typeof chunk === 'function') {
      cb = chunk
      chunk = null
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = Buffer.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result =
      chunk !== undefined && chunk !== null ? super.end({ chunk, encoding }) : super.end()

    if (cb) this.once('finish', () => cb(null))

    return result
  }

  static fromWeb({ readable: readableStream, writable: writableStream }, opts) {
    const readable = exports.Readable.fromWeb(readableStream, opts)
    const writable = exports.Writable.fromWeb(writableStream, opts)

    const duplex = new exports.Duplex({
      write(data, encoding, cb) {
        writable.write(data, encoding, cb)
      }
    })

    readable
      .on('data', (data) => duplex.push(data))
      .on('end', () => duplex.push(null))
      .on('error', (err) => duplex.destroy(err))

    writable.on('finish', () => duplex.end()).on('error', (err) => duplex.destroy(err))

    return duplex
  }

  static toWeb(duplex) {
    const readableStream = exports.Readable.toWeb(duplex)
    const writableStream = exports.Writable.toWeb(duplex)

    return { readable: readableStream, writable: writableStream }
  }
}

class DuplexSide extends exports.Duplex {
  constructor(opts) {
    super(opts)

    this._otherSide = null
    this._cb = null
  }

  _read() {
    const cb = this._cb
    if (!cb) return

    this._cb = null
    cb()
  }

  _write(chunk, encoding, cb) {
    this._otherSide.push(chunk, encoding)
    this._otherSide._cb = cb
  }

  _final(cb) {
    this._otherSide.on('end', cb)
    this._otherSide.push(null)
  }
}

exports.duplexPair = function duplexPair(opts) {
  const sideA = new DuplexSide(opts)
  const sideB = new DuplexSide(opts)

  sideA._otherSide = sideB
  sideB._otherSide = sideA

  return [sideA, sideB]
}

exports.Transform = class Transform extends stream.Transform {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthReadable: null,
      byteLengthWritable,
      map: null,
      mapReadable: null,
      mapWritable: null
    })

    if (this._transform !== stream.Transform.prototype._transform) {
      this._transform = transform.bind(this, this._transform)
    } else {
      this._transform = passthrough
    }
  }

  push(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = Buffer.from(chunk, encoding || defaultEncoding)
    }

    return super.push(chunk)
  }

  unshift(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = Buffer.from(chunk, encoding || defaultEncoding)
    }

    super.unshift(chunk)
  }

  write(chunk, encoding, cb) {
    if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = Buffer.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result = super.write({ chunk, encoding })

    if (cb) stream.Writable.drained(this).then(() => cb(null), cb)

    return result
  }

  end(chunk, encoding, cb) {
    if (typeof chunk === 'function') {
      cb = chunk
      chunk = null
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = Buffer.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result =
      chunk !== undefined && chunk !== null ? super.end({ chunk, encoding }) : super.end()

    if (cb) this.once('finish', () => cb(null))

    return result
  }
}

exports.PassThrough = class PassThrough extends exports.Transform {}

exports.finished = function finished(stream, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (!opts) opts = {}

  const { cleanup = false } = opts

  const done = () => {
    cb(exports.getStreamError(stream, { all: true }))

    if (cleanup) detach()
  }

  const detach = () => {
    stream.off('close', done)
    stream.off('error', noop)
  }

  if (stream.destroyed) {
    done()
  } else {
    stream.on('close', done)
    stream.on('error', noop)
  }

  return detach
}

function read(read, cb) {
  read.call(this, 65536)

  cb(null)
}

function write(write, data, cb) {
  write.call(this, data.chunk, data.encoding, cb)
}

function transform(transform, data, cb) {
  transform.call(this, data.chunk, data.encoding, cb)
}

function destroy(destroy, cb) {
  destroy.call(this, exports.getStreamError(this), cb)
}

function passthrough(data, cb) {
  cb(null, data.chunk)
}

function byteLengthWritable(data) {
  return data.chunk.byteLength
}

function noop() {}
{
  "name": "bare-stream",
  "version": "2.13.1",
  "description": "Streaming data for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./promises": "./promises.js",
    "./web": {
      "types": "./web.d.ts",
      "default": "./web.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "promises.js",
    "web.js",
    "web.d.ts",
    "global.js",
    "global.d.ts"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-stream.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-stream/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-stream#readme",
  "dependencies": {
    "streamx": "^2.25.0",
    "teex": "^1.0.1"
  },
  "devDependencies": {
    "bare-abort-controller": "^1.1.0",
    "bare-buffer": "^3.0.0",
    "bare-events": "^2.5.4",
    "brittle": "^3.5.2",
    "lunte": "^1.6.0",
    "prettier": "^3.3.3",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "bare-abort-controller": "*",
    "bare-buffer": "*",
    "bare-events": "*"
  },
  "peerDependenciesMeta": {
    "bare-abort-controller": {
      "optional": true
    },
    "bare-buffer": {
      "optional": true
    },
    "bare-events": {
      "optional": true
    }
  }
}
const { Readable, Writable, Transform, getStreamError, isStreamx, isDisturbed } = require('streamx')
const tee = require('teex')

const readableKind = Symbol.for('bare.stream.readable.kind')
const writableKind = Symbol.for('bare.stream.writable.kind')
const transformKind = Symbol.for('bare.stream.transform.kind')

// https://streams.spec.whatwg.org/#readablestreamdefaultreader
exports.ReadableStreamDefaultReader = class ReadableStreamDefaultReader {
  constructor(stream) {
    this._stream = stream
    this._stream._stream.once('close', onclose).once('error', onerror)

    const closed = Promise.withResolvers()

    // Avoid unhandled exceptions
    closed.promise.catch(noop)

    this._closed = closed

    function onclose() {
      closed.resolve()
    }

    function onerror(err) {
      closed.reject(err)
    }
  }

  get closed() {
    return this._closed.promise
  }

  read() {
    const stream = this._stream._stream

    return new Promise((resolve, reject) => {
      const err = getStreamError(stream)

      if (err) return reject(err)

      if (stream.destroyed) {
        return resolve({ value: undefined, done: true })
      }

      const value = stream.read()

      if (value !== null) {
        return resolve({ value, done: false })
      }

      stream.once('readable', onreadable).once('close', onclose).once('error', onerror)

      function onreadable() {
        const value = stream.read()

        ondone(null, value === null ? { value: undefined, done: true } : { value, done: false })
      }

      function onclose() {
        ondone(null, { value: undefined, done: true })
      }

      function onerror(err) {
        ondone(err, null)
      }

      function ondone(err, value) {
        stream.off('readable', onreadable).off('close', onclose).off('error', onerror)

        if (err) reject(err)
        else resolve(value)
      }
    })
  }

  releaseLock() {
    this._closed.reject(new TypeError('Reader was released'))
    this._stream._releaseLock()
    this._stream = null
  }

  cancel(reason = new TypeError('Stream was cancelled')) {
    const stream = this._stream._stream

    if (stream.destroyed) return Promise.resolve()

    return new Promise((resolve) =>
      stream.once('close', resolve).once('error', noop).destroy(reason)
    )
  }
}

// https://streams.spec.whatwg.org/#readablestreamdefaultcontroller
exports.ReadableStreamDefaultController = class ReadableStreamDefaultController {
  constructor(stream) {
    this._stream = stream
  }

  get desiredSize() {
    const stream = this._stream._stream

    return stream._readableState.highWaterMark - stream._readableState.buffered
  }

  enqueue(data) {
    this._stream._stream.push(data)
  }

  close() {
    this._stream._stream.push(null)
  }

  error(err) {
    this._stream._stream.destroy(err)
  }
}

// https://streams.spec.whatwg.org/#readablestream
class ReadableStream {
  static get [readableKind]() {
    return 0 // Compatibility version
  }

  static from(iterable) {
    return new ReadableStream(Readable.from(iterable))
  }

  constructor(underlyingSource = {}, queuingStrategy) {
    if (isStreamx(underlyingSource)) {
      this._stream = underlyingSource
    } else {
      if (queuingStrategy === undefined) {
        queuingStrategy = new exports.CountQueuingStrategy()
      }

      const { start, pull, cancel } = underlyingSource
      const { highWaterMark = 1, size = defaultSize } = queuingStrategy

      this._stream = new Readable({ highWaterMark, byteLength: size })

      const controller = new exports.ReadableStreamDefaultController(this)

      try {
        let starting = Promise.resolve()

        if (start) starting = forwardError(start.call(this, controller), controller)

        if (pull) {
          this._stream._read = this._read.bind(this, starting, pull.bind(this, controller))
        }

        if (cancel) {
          this._stream.once('error', cancel.bind(this))
        }
      } catch (err) {
        controller.error(err)
      }
    }

    this._reader = null
  }

  get [readableKind]() {
    return ReadableStream[readableKind]
  }

  get locked() {
    return this._reader !== null
  }

  getReader() {
    if (this.locked) throw new TypeError('Stream is locked')

    this._reader = new exports.ReadableStreamDefaultReader(this)

    return this._reader
  }

  cancel(reason = new TypeError('Stream was cancelled')) {
    const stream = this._stream

    if (stream.destroyed) return Promise.resolve()

    if (this.locked) return Promise.reject(new TypeError('Stream is locked'))

    return new Promise((resolve) =>
      stream.once('close', resolve).once('error', noop).destroy(reason)
    )
  }

  tee() {
    const [a, b] = tee(this._stream)

    return [new ReadableStream(a), new ReadableStream(b)]
  }

  pipeTo(destination) {
    return new Promise((resolve, reject) =>
      this._stream.pipe(destination._stream, (err) => {
        err ? reject(err) : resolve()
      })
    )
  }

  [Symbol.asyncIterator]() {
    return this._stream[Symbol.asyncIterator]()
  }

  _releaseLock() {
    this._reader = null
  }

  async _read(starting, pull, cb) {
    await starting

    let err = null
    try {
      await pull()
    } catch (e) {
      err = e
    }
    cb(err)
  }
}

function defaultSize() {
  return 1
}

exports.ReadableStream = ReadableStream

// https://streams.spec.whatwg.org/#countqueuingstrategy
exports.CountQueuingStrategy = class CountQueuingStrategy {
  constructor(opts = {}) {
    const { highWaterMark = 1 } = opts

    this.highWaterMark = highWaterMark
  }

  size(chunk) {
    return 1
  }
}

// https://streams.spec.whatwg.org/#bytelengthqueuingstrategy
exports.ByteLengthQueuingStrategy = class ByteLengthQueuingStrategy {
  constructor(opts = {}) {
    const { highWaterMark = 16384 } = opts

    this.highWaterMark = highWaterMark
  }

  size(chunk) {
    return chunk.byteLength
  }
}

exports.isReadableStream = function isReadableStream(value) {
  if (value instanceof ReadableStream) return true

  return (
    typeof value === 'object' &&
    value !== null &&
    value[readableKind] === ReadableStream[readableKind]
  )
}

// https://streams.spec.whatwg.org/#readablestream-errored
exports.isReadableStreamErrored = function isReadableStreamErrored(stream) {
  return getStreamError(stream._stream) !== null
}

// https://streams.spec.whatwg.org/#is-readable-stream-disturbed
exports.isReadableStreamDisturbed = function isReadableStreamDisturbed(stream) {
  return isDisturbed(stream._stream)
}

// https://streams.spec.whatwg.org/#writablestreamdefaultwriter
exports.WritableStreamDefaultWriter = class WritableStreamDefaultWriter {
  constructor(stream) {
    this._stream = stream
    this._stream._stream.once('close', onclose).once('error', onerror)

    const closed = Promise.withResolvers()

    // Avoid unhandled exceptions
    closed.promise.catch(noop)

    this._closed = closed

    function onclose() {
      closed.resolve()
    }

    function onerror(err) {
      closed.reject(err)
    }
  }

  get desiredSize() {
    const stream = this._stream._stream

    return stream._writableState.highWaterMark - stream._writableState.buffered
  }

  get closed() {
    return this._closed.promise
  }

  get ready() {
    const stream = this._stream._stream

    if (getStreamError(stream)) return Promise.reject()

    return Writable.drained(stream).then()
  }

  async write(chunk) {
    const stream = this._stream._stream

    let err = getStreamError(stream)
    if (err) return Promise.reject(err)

    stream.write(chunk)

    await Writable.drained(stream)

    err = getStreamError(stream)
    if (err) return Promise.reject(err)
  }

  releaseLock() {
    this._closed.reject(new TypeError('Writer was released'))
    this._stream._releaseLock()
    this._stream = null
  }

  close() {
    const stream = this._stream._stream

    if (stream.destroyed) return Promise.resolve()

    return new Promise((resolve) => stream.once('close', resolve).end())
  }

  abort(reason = new TypeError('Stream was aborted')) {
    const stream = this._stream._stream

    if (stream.destroyed) return Promise.resolve()

    return new Promise((resolve) => stream.once('close', resolve).destroy(reason))
  }
}

// https://streams.spec.whatwg.org/#writablestreamdefaultcontroller
exports.WritableStreamDefaultController = class WritableStreamDefaultController {
  constructor(stream) {
    this._stream = stream
  }

  error(err) {
    this._stream._stream.destroy(err)
  }
}

// https://streams.spec.whatwg.org/#writablestream
class WritableStream {
  static get [writableKind]() {
    return 0 // Compatibility version
  }

  constructor(underlyingSink = {}, queuingStrategy = {}) {
    if (isStreamx(underlyingSink)) {
      this._stream = underlyingSink
    } else {
      if (queuingStrategy === undefined) {
        queuingStrategy = new exports.CountQueuingStrategy()
      }

      const { start, write, close, abort } = underlyingSink
      const { highWaterMark = 1, size = defaultSize } = queuingStrategy

      this._stream = new Writable({ highWaterMark, byteLength: size })

      const controller = new exports.WritableStreamDefaultController(this)

      this._controller = controller

      try {
        let starting = Promise.resolve()

        if (start) starting = forwardError(start.call(this, controller), controller)

        if (write) {
          this._stream._write = this._write.bind(this, starting, write.bind(this))
        }

        if (close) {
          this._stream._destroy = this._destroy.bind(this, close.call(this))
        }

        if (abort) {
          this._stream.once('error', abort.bind(this))
        }
      } catch (err) {
        controller.error(err)
      }
    }

    this._writer = null
  }

  get [writableKind]() {
    return WritableStream[writableKind]
  }

  get locked() {
    return this._writer !== null
  }

  getWriter() {
    if (this.locked) throw new TypeError('Stream is locked')

    this._writer = new exports.WritableStreamDefaultWriter(this)

    return this._writer
  }

  abort(reason = new TypeError('Stream was aborted')) {
    if (this._stream.destroyed) return Promise.resolve()

    if (this.locked) return Promise.reject(new TypeError('Stream is locked'))

    return new Promise((resolve) => this._stream.once('close', resolve).destroy(reason))
  }

  close() {
    if (this._stream.destroyed) return Promise.resolve()

    if (this.locked) return Promise.reject(new TypeError('Stream is locked'))

    return new Promise((resolve) => this._stream.once('close', resolve).end())
  }

  _releaseLock() {
    this._writer = null
  }

  async _write(starting, write, data, cb) {
    await starting

    let err = null
    try {
      await write(data, this._controller)
    } catch (e) {
      err = e
    }
    cb(err)
  }

  async _destroy(closing, cb) {
    let err = null
    try {
      await closing
    } catch (e) {
      err = e
    }
    cb(err)
  }
}

exports.WritableStream = WritableStream

exports.isWritableStream = function isWritableStream(value) {
  if (value instanceof WritableStream) return true

  return (
    typeof value === 'object' &&
    value !== null &&
    value[writableKind] === WritableStream[writableKind]
  )
}

// https://streams.spec.whatwg.org/#transformstreamdefaultcontroller
exports.TransformStreamDefaultController = class TransformStreamDefaultController {
  constructor(stream) {
    this._stream = stream
  }

  get desiredSize() {
    const stream = this._stream._stream

    return stream._readableState.highWaterMark - stream._readableState.buffered
  }

  enqueue(data) {
    this._stream._stream.push(data)
  }

  error(err) {
    this._stream._stream.destroy(err)
  }

  terminate() {
    const stream = this._stream._stream

    stream.push(null)
    stream.destroy(new TypeError('Stream has been terminated'))
  }
}

// https://streams.spec.whatwg.org/#transformstream
class TransformStream {
  static get [transformKind]() {
    return 0 // Compatibility version
  }

  constructor(transformer = {}, writableStrategy = {}, readableStrategy = {}) {
    if (isStreamx(transformer)) {
      this._stream = transformer
    } else {
      const { start, transform, flush } = transformer

      this._stream = new Transform({ ...writableStrategy, ...readableStrategy })

      const controller = new exports.TransformStreamDefaultController(this)

      this._controller = controller

      try {
        let starting = Promise.resolve()

        if (start) starting = forwardError(start.call(this, controller), controller)

        if (transform) {
          this._stream._transform = this._transform.bind(this, starting, transform.bind(this))
        }

        if (flush) {
          this._stream._flush = this._flush.bind(this, flush.call(this, this._controller))
        }
      } catch (err) {
        controller.error(err)
      }
    }

    this._writable = new WritableStream(this._stream)
    this._readable = new ReadableStream(this._stream)
  }

  get [transformKind]() {
    return TransformStream[transformKind]
  }

  get writable() {
    return this._writable
  }

  get readable() {
    return this._readable
  }

  async _transform(starting, transform, data, cb) {
    await starting

    let err = null
    try {
      await transform(data, this._controller)
    } catch (e) {
      err = e
    }
    cb(err)
  }

  async _flush(flush, cb) {
    let err = null
    try {
      await flush
    } catch (e) {
      err = e
    }
    cb(err)
  }
}

exports.TransformStream = TransformStream

exports.isTransformStream = function isTransformStream(value) {
  if (value instanceof TransformStream) return true

  return (
    typeof value === 'object' &&
    value !== null &&
    value[transformKind] === TransformStream[transformKind]
  )
}

async function forwardError(promise, controller) {
  try {
    await promise
  } catch (err) {
    controller.error(err)
  }
}

function noop() {}
module.exports = require.addon()
const EventEmitter = require('bare-events')
const { Duplex } = require('bare-stream')
const dns = require('bare-dns')
const binding = require('./binding')
const constants = require('./lib/constants')
const errors = require('./lib/errors')
const ip = require('./lib/ip')

const defaultReadBufferSize = 65536
const empty = Buffer.alloc(0)

exports.Socket = class TCPSocket extends Duplex {
  constructor(opts = {}) {
    const { readBufferSize = defaultReadBufferSize, allowHalfOpen = true, eagerOpen = true } = opts

    super({ eagerOpen })

    this._state = 0

    this._allowHalfOpen = allowHalfOpen

    this._keepAlive = 0
    this._keepAliveInitialDelay = 0
    this._noDelay = 0

    this._localAddress = null
    this._remoteAddress = null

    this._pendingOpen = null
    this._pendingWrite = null
    this._pendingFinal = null
    this._pendingDestroy = null

    this._timer = null
    this._timeout = 0

    this._buffer = Buffer.alloc(readBufferSize)

    this._addresses = null
    this._errors = null

    this._handle = binding.init(
      this._buffer,
      this,
      noop,
      this._onconnect,
      this._onreset,
      this._onread,
      this._onwrite,
      this._onfinal,
      this._onclose
    )
  }

  get connecting() {
    return (this._state & constants.state.CONNECTING) !== 0
  }

  get pending() {
    return (this._state & constants.state.CONNECTED) === 0
  }

  get timeout() {
    return this._timeout || undefined // For Node.js compatibility
  }

  get readyState() {
    if (this._state & constants.state.CONNECTED) {
      return 'open'
    }

    return 'opening'
  }

  get localAddress() {
    if (this._localAddress) return this._localAddress.address
  }

  get localFamily() {
    if (this._localAddress) return `IPv${this._localAddress.family}`
  }

  get localPort() {
    if (this._localAddress) return this._localAddress.port
  }

  get remoteAddress() {
    if (this._remoteAddress) return this._remoteAddress.address
  }

  get remoteFamily() {
    if (this._remoteAddress) return `IPv${this._remoteAddress.family}`
  }

  get remotePort() {
    if (this._remoteAddress) return this._remoteAddress.port
  }

  connect(port, host = 'localhost', opts = {}, onconnect) {
    if (this._state & constants.state.CONNECTING || this._state & constants.state.CONNECTED) {
      throw errors.SOCKET_ALREADY_CONNECTED('Socket is already connected')
    }

    this._state |= constants.state.CONNECTING

    if (typeof host === 'function') {
      onconnect = host
      host = 'localhost'
    } else if (typeof opts === 'function') {
      onconnect = opts
      opts = {}
    }

    let family = 0

    if (typeof port === 'object' && port !== null) {
      opts = port || {}
      port = opts.port || 0
      host = opts.host || 'localhost'
      family = opts.family || 0
    }

    if (!host) host = 'localhost'

    const {
      lookup = dns.lookup,
      hints,
      keepAlive = false,
      keepAliveInitialDelay = 0,
      noDelay = false,
      timeout
    } = opts

    const type = ip.isIP(host)

    if (type === 0) {
      lookup(host, { all: true, family, hints }, (err, addresses) => {
        if (this._state & constants.state.CLOSING) return

        this._state &= ~constants.state.CONNECTING

        if (err || addresses.length === 0) {
          if (!err) {
            err = new Error(`No address found for host "${host}"`)
            err.code = 'ENOTFOUND'
          }

          this.emit('lookup', err, null, 0, host)

          if (this._pendingOpen) this._continueOpen(err)
          else this.destroy(err)
          return
        }

        for (const { address, family } of addresses) {
          this.emit('lookup', null, address, family, host)
        }

        const [{ address, family }, ...rest] = addresses

        if (rest.length > 0) {
          this._addresses = rest.map(({ address, family }) => [
            port,
            address,
            { ...opts, family },
            onconnect
          ])

          this._errors = []
        }

        this.connect(port, address, { ...opts, family }, onconnect)
      })

      return this
    }

    family = type

    try {
      binding.connect(this._handle, port, host, family)

      if (keepAlive) {
        this._keepAlive = keepAlive
        this._keepAliveInitialDelay = keepAliveInitialDelay
      }
      if (noDelay) this._noDelay = noDelay
      if (timeout) this.setTimeout(timeout)

      if (onconnect) this.once('connect', onconnect)
    } catch (err) {
      queueMicrotask(() => {
        if (this._pendingOpen) this._pendingOpen(err)
        else this.destroy(err)
      })
    }

    return this
  }

  setKeepAlive(enable = false, delay = 0) {
    if (typeof enable === 'number') {
      delay = enable
      enable = false
    }

    delay = Math.floor(delay / 1000)

    if (delay === 0) enable = false

    binding.keepalive(this._handle, enable, delay)

    return this
  }

  setNoDelay(enable = true) {
    binding.nodelay(this._handle, enable)

    return this
  }

  setTimeout(ms, ontimeout) {
    if (ms === 0) {
      clearTimeout(this._timer)

      this._timer = null
    } else {
      if (ontimeout) this.once('timeout', ontimeout)

      this._timer = setTimeout(() => this.emit('timeout'), ms)
      this._timer.unref()
    }

    this._timeout = ms

    return this
  }

  ref() {
    binding.ref(this._handle)

    return this
  }

  unref() {
    binding.unref(this._handle)

    return this
  }

  _open(cb) {
    if (this._state & constants.state.CONNECTED) return cb(null)

    this._pendingOpen = cb
  }

  _read() {
    if ((this._state & constants.state.READING) === 0) {
      this._state |= constants.state.READING

      binding.resume(this._handle)
    }
  }

  _writev(batch, cb) {
    this._pendingWrite = [cb, batch]

    binding.writev(
      this._handle,
      batch.map(({ chunk }) => chunk)
    )
  }

  _final(cb) {
    this._pendingFinal = cb

    binding.end(this._handle)
  }

  _predestroy() {
    if (this._state & constants.state.CLOSING) return
    this._state |= constants.state.CLOSING

    binding.close(this._handle)
  }

  _destroy(err, cb) {
    if (this._state & constants.state.CLOSING) return cb(err)
    this._state |= constants.state.CLOSING

    this._pendingDestroy = cb

    binding.close(this._handle)
  }

  _continueOpen(err) {
    if (this._pendingOpen === null) return
    const cb = this._pendingOpen
    this._pendingOpen = null
    cb(err)
  }

  _continueWrite(err) {
    if (this._pendingWrite === null) return
    const cb = this._pendingWrite[0]
    this._pendingWrite = null
    cb(err)
  }

  _continueFinal(err) {
    if (this._pendingFinal === null) return
    const cb = this._pendingFinal
    this._pendingFinal = null
    cb(err)
  }

  _continueDestroy() {
    if (this._pendingDestroy === null) return
    const cb = this._pendingDestroy
    this._pendingDestroy = null
    cb(null)
  }

  _reset() {
    this._state = 0

    this._localAddress = null
    this._remoteAddress = null

    binding.reset(this._handle)
  }

  _onconnect(err) {
    if (err) {
      if (this._addresses !== null) {
        this._errors.push(err)

        if (this._addresses.length > 0) return this._reset()

        err = this._errors.length === 1 ? this._errors[0] : new AggregateError(this._errors)
      }

      if (this._pendingOpen) this._continueOpen(err)
      else this.destroy(err)
      return
    }

    if (this._keepAlive) this.setKeepAlive(this._keepAlive, this._keepAliveInitialDelay)
    if (this._noDelay) this.setNoDelay()

    this._localAddress = binding.address(this._handle, true)
    this._remoteAddress = binding.address(this._handle, false)

    this._state |= constants.state.CONNECTED
    this._state &= ~constants.state.CONNECTING
    this._continueOpen()

    this.emit('connect')
  }

  _onreset(err) {
    if (err) {
      this._errors.push(err)
      this.destroy(this._errors.length === 1 ? this._errors[0] : new AggregateError(this._errors))
      return
    }

    this.connect(...this._addresses.shift())
  }

  _onread(err, read) {
    if (this._timer) this._timer.refresh()

    if (err) {
      this.destroy(err)
      return
    }

    if (read === 0) {
      this.push(null)
      if (this._allowHalfOpen === false) this.end()
      return
    }

    const copy = Buffer.allocUnsafe(read)
    copy.set(this._buffer.subarray(0, read))

    if (this.push(copy) === false && this.destroying === false) {
      this._state &= ~constants.state.READING

      binding.pause(this._handle)
    }
  }

  _onwrite(err) {
    if (this._timer) this._timer.refresh()

    this._continueWrite(err)
  }

  _onfinal(err) {
    this._continueFinal(err)
  }

  _onclose() {
    clearTimeout(this._timer)

    this._continueOpen()
    this._continueDestroy()
  }
}

exports.Server = class TCPServer extends EventEmitter {
  constructor(opts = {}, onconnection) {
    if (typeof opts === 'function') {
      onconnection = opts
      opts = {}
    }

    super()

    const {
      readBufferSize = defaultReadBufferSize,
      allowHalfOpen = true,
      keepAlive = false,
      keepAliveInitialDelay = 0,
      noDelay = false,
      pauseOnConnect = false
    } = opts

    this._state = 0

    this._readBufferSize = readBufferSize
    this._allowHalfOpen = allowHalfOpen
    this._keepAlive = keepAlive
    this._keepAliveInitialDelay = keepAliveInitialDelay
    this._noDelay = noDelay
    this._pauseOnConnect = pauseOnConnect

    this._address = null
    this._connections = new Set()

    this._error = null
    this._handle = null

    if (onconnection) this.on('connection', onconnection)
  }

  get listening() {
    return (this._state & constants.state.BOUND) !== 0
  }

  get closing() {
    return (this._state & constants.state.CLOSING) !== 0
  }

  get connections() {
    return this._connections
  }

  address() {
    if ((this._state & constants.state.BOUND) === 0) return null

    const { address, family, port } = this._address

    return { address, family: `IPv${family}`, port }
  }

  listen(port = 0, host = 'localhost', backlog = 511, opts = {}, onlistening) {
    if (this._state & constants.state.BINDING || this._state & constants.state.BOUND) {
      throw errors.SERVER_ALREADY_LISTENING('Server is already listening')
    }

    if (this._state & constants.state.CLOSING) {
      throw errors.SERVER_IS_CLOSED('Server is closed')
    }

    this._state |= constants.state.BINDING

    if (typeof port === 'function') {
      onlistening = port
      port = 0
    } else if (typeof host === 'function') {
      onlistening = host
      host = 'localhost'
    } else if (typeof backlog === 'function') {
      onlistening = backlog
      backlog = 511
    } else if (typeof opts === 'function') {
      onlistening = opts
      opts = {}
    }

    let family = 0

    if (typeof port === 'object' && port !== null) {
      opts = port || {}
      port = opts.port || 0
      host = opts.host || 'localhost'
      family = opts.family || 0
      backlog = opts.backlog || 511
    }

    if (!host) host = 'localhost'
    if (!backlog) backlog = 511

    const { lookup = dns.lookup, hints } = opts

    const type = ip.isIP(host)

    if (type === 0) {
      lookup(host, { family, hints }, (err, address, family) => {
        if (this._state & constants.state.CLOSING) return

        this.emit('lookup', err, address, family, host)

        this._state &= ~constants.state.BINDING

        if (err) return this.emit('error', err)

        this.listen(port, address, backlog, { ...opts, family }, onlistening)
      })

      return this
    }

    family = type

    this._handle = binding.init(
      empty,
      this,
      this._onconnection,
      noop,
      noop,
      noop,
      noop,
      noop,
      this._onclose
    )

    if (this._state & constants.state.UNREFED) binding.unref(this._handle)

    try {
      binding.bind(this._handle, port, host, backlog, family)

      this._address = binding.address(this._handle, true)

      this._state |= constants.state.BOUND
      this._state &= ~constants.state.BINDING

      if (onlistening) this.once('listening', onlistening)

      queueMicrotask(() => this.emit('listening'))
    } catch (err) {
      this._error = err

      binding.close(this._handle)
    }

    return this
  }

  close(onclose) {
    if (onclose) this.once('close', onclose)

    if (this._state & constants.state.CLOSING) return this
    this._state |= constants.state.CLOSING

    this._closeMaybe()

    return this
  }

  ref() {
    this._state &= ~constants.state.UNREFED

    if (this._handle !== null) binding.ref(this._handle)

    return this
  }

  unref() {
    this._state |= constants.state.UNREFED

    if (this._handle !== null) binding.unref(this._handle)

    return this
  }

  _closeMaybe() {
    if (this._state & constants.state.CLOSING && this._connections.size === 0) {
      if (this._handle !== null) binding.close(this._handle)
      else queueMicrotask(() => this.emit('close'))
    }
  }

  _onconnection(err) {
    if (err) {
      this.emit('error', err)
      return
    }

    if (this._state & constants.state.CLOSING) return

    const socket = new exports.Socket({
      readBufferSize: this._readBufferSize,
      allowHalfOpen: this._allowHalfOpen,
      eagerOpen: !this._pauseOnConnect
    })

    try {
      binding.accept(this._handle, socket._handle)

      socket._localAddress = binding.address(socket._handle, true)
      socket._remoteAddress = binding.address(socket._handle, false)

      socket._state |= constants.state.CONNECTED

      this._connections.add(socket)

      if (this._keepAlive) socket.setKeepAlive(this._keepAlive, this._keepAliveInitialDelay)
      if (this._noDelay) socket.setNoDelay()

      socket.on('close', () => {
        this._connections.delete(socket)
        this._closeMaybe()
      })

      this.emit('connection', socket)
    } catch (err) {
      socket.destroy()

      this.emit('error', err)
    }
  }

  _onclose() {
    const err = this._error

    this._state &= ~constants.state.BINDING
    this._error = null
    this._handle = null
    this._address = null

    if (err) this.emit('error', err)
    else this.emit('close')
  }
}

exports.constants = constants
exports.errors = errors

exports.isIP = ip.isIP
exports.isIPv4 = ip.isIPv4
exports.isIPv6 = ip.isIPv6

exports.createConnection = function createConnection(port, host, opts, onconnect) {
  if (typeof host === 'function') {
    onconnect = host
    host = 'localhost'
  } else if (typeof opts === 'function') {
    onconnect = opts
    opts = {}
  }

  if (typeof port === 'object' && port !== null) {
    opts = port || {}
    port = opts.port || 0
    host = opts.host || 'localhost'
  }

  return new exports.Socket(opts).connect(port, host, opts, onconnect)
}

// For Node.js compatibility
exports.connect = exports.createConnection

exports.createServer = function createServer(opts, onconnection) {
  return new exports.Server(opts, onconnection)
}

function noop() {}
module.exports = {
  state: {
    CONNECTING: 0x1,
    CONNECTED: 0x2,
    BINDING: 0x4,
    BOUND: 0x8,
    READING: 0x10,
    CLOSING: 0x20,
    UNREFED: 0x40
  }
}
module.exports = class TCPError extends Error {
  constructor(msg, fn = TCPError, code = fn.name) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'TCPError'
  }

  static SOCKET_ALREADY_CONNECTED(msg) {
    return new TCPError(msg, TCPError.SOCKET_ALREADY_CONNECTED)
  }

  static SERVER_ALREADY_LISTENING(msg) {
    return new TCPError(msg, TCPError.SERVER_ALREADY_LISTENING)
  }

  static SERVER_IS_CLOSED(msg) {
    return new TCPError(msg, TCPError.SERVER_IS_CLOSED)
  }

  static INVALID_HOST(msg = 'Unrecognizable host format') {
    return new TCPError(msg, TCPError.INVALID_HOST)
  }
}
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

const v4Seg = '(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])'
const v4Str = `(${v4Seg}[.]){3}${v4Seg}`
const IPv4Pattern = new RegExp(`^${v4Str}$`)

const v6Seg = '(?:[0-9a-fA-F]{1,4})'
const IPv6Pattern = new RegExp(
  '^(' +
    `(?:${v6Seg}:){7}(?:${v6Seg}|:)|` +
    `(?:${v6Seg}:){6}(?:${v4Str}|:${v6Seg}|:)|` +
    `(?:${v6Seg}:){5}(?::${v4Str}|(:${v6Seg}){1,2}|:)|` +
    `(?:${v6Seg}:){4}(?:(:${v6Seg}){0,1}:${v4Str}|(:${v6Seg}){1,3}|:)|` +
    `(?:${v6Seg}:){3}(?:(:${v6Seg}){0,2}:${v4Str}|(:${v6Seg}){1,4}|:)|` +
    `(?:${v6Seg}:){2}(?:(:${v6Seg}){0,3}:${v4Str}|(:${v6Seg}){1,5}|:)|` +
    `(?:${v6Seg}:){1}(?:(:${v6Seg}){0,4}:${v4Str}|(:${v6Seg}){1,6}|:)|` +
    `(?::((?::${v6Seg}){0,5}:${v4Str}|(?::${v6Seg}){1,7}|:))` +
    ')(%[0-9a-zA-Z-.:]{1,})?$'
)

const isIPv4 = (exports.isIPv4 = function isIPv4(host) {
  return IPv4Pattern.test(host)
})

const isIPv6 = (exports.isIPv6 = function isIPv6(host) {
  return IPv6Pattern.test(host)
})

exports.isIP = function isIP(host) {
  if (isIPv4(host)) return 4
  if (isIPv6(host)) return 6
  return 0
}
{
  "name": "bare-tcp",
  "version": "2.2.12",
  "description": "Native TCP sockets for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./constants": "./lib/constants.js",
    "./errors": "./lib/errors.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-tcp.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-tcp/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-tcp#readme",
  "engines": {
    "bare": ">=1.16.0"
  },
  "dependencies": {
    "bare-dns": "^2.0.4",
    "bare-events": "^2.5.4",
    "bare-stream": "^2.6.4"
  },
  "devDependencies": {
    "brittle": "^3.5.0",
    "cmake-bare": "^1.1.6",
    "lunte": "^1.6.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = require.addon()
const { Readable, Writable } = require('bare-stream')
const Signal = require('bare-signals')
const binding = require('./binding')
const constants = require('./lib/constants')

const defaultReadBufferSize = 65536
const empty = Buffer.alloc(0)

exports.ReadStream = class TTYReadStream extends Readable {
  constructor(fd, opts = {}) {
    super()

    const { readBufferSize = defaultReadBufferSize, allowHalfOpen = true } = opts

    this._fd = fd
    this._state = 0
    this._allowHalfOpen = allowHalfOpen
    this._buffer = Buffer.alloc(readBufferSize)

    this._pendingDestroy = null

    this._handle = binding.init(fd, this._buffer, this, noop, this._onread, this._onclose)
  }

  get fd() {
    return this._fd
  }

  get isTTY() {
    return true
  }

  setMode(mode) {
    binding.setMode(this._handle, mode)
    return this
  }

  setRawMode(enabled) {
    return this.setMode(enabled ? constants.mode.RAW : constants.mode.NORMAL)
  }

  _read() {
    if ((this._state & constants.state.READING) === 0) {
      this._state |= constants.state.READING

      binding.resume(this._handle)
    }
  }

  _predestroy() {
    if (this._state & constants.state.CLOSING) return
    this._state |= constants.state.CLOSING

    binding.close(this._handle)
  }

  _destroy(err, cb) {
    if (this._state & constants.state.CLOSING) return cb(err)
    this._state |= constants.state.CLOSING

    this._pendingDestroy = cb

    binding.close(this._handle)
  }

  _continueDestroy() {
    if (this._pendingDestroy === null) return
    const cb = this._pendingDestroy
    this._pendingDestroy = null
    cb(null)
  }

  _onread(err, read) {
    if (err) {
      this.destroy(err)
      return
    }

    if (read === 0) {
      this.push(null)
      if (this._allowHalfOpen === false) this.end()
      return
    }

    const copy = Buffer.allocUnsafe(read)
    copy.set(this._buffer.subarray(0, read))

    if (this.push(copy) === false && this.destroying === false) {
      this._state &= ~constants.state.READING

      binding.pause(this._handle)
    }
  }

  _onclose() {
    this._handle = null

    this._continueDestroy()
  }
}

exports.WriteStream = class TTYWriteStream extends Writable {
  constructor(fd, opts = {}) {
    super()

    this._fd = fd
    this._state = 0
    this._size = null

    this._pendingWrite = null
    this._pendingDestroy = null

    this._handle = binding.init(fd, empty, this, this._onwrite, noop, this._onclose)

    this._size = this.getWindowSize()

    if (TTYWriteStream._streams.size === 0) TTYWriteStream._resize.start()

    TTYWriteStream._streams.add(this)
  }

  get fd() {
    return this._fd
  }

  get isTTY() {
    return true
  }

  get columns() {
    return this._size[0]
  }

  get rows() {
    return this._size[1]
  }

  getWindowSize() {
    return binding.getWindowSize(this._handle)
  }

  _writev(batch, cb) {
    this._pendingWrite = [cb, batch]

    binding.writev(
      this._handle,
      batch.map(({ chunk }) => chunk)
    )
  }

  _predestroy() {
    if (this._state & constants.state.CLOSING) return
    this._state |= constants.state.CLOSING

    binding.close(this._handle)

    TTYWriteStream._streams.delete(this)

    if (TTYWriteStream._streams.size === 0) TTYWriteStream._resize.stop()
  }

  _destroy(err, cb) {
    if (this._state & constants.state.CLOSING) return cb(err)
    this._state |= constants.state.CLOSING

    this._pendingDestroy = cb

    binding.close(this._handle)

    TTYWriteStream._streams.delete(this)

    if (TTYWriteStream._streams.size === 0) TTYWriteStream._resize.stop()
  }

  _continueWrite(err) {
    if (this._pendingWrite === null) return
    const cb = this._pendingWrite[0]
    this._pendingWrite = null
    cb(err)
  }

  _continueDestroy() {
    if (this._pendingDestroy === null) return
    const cb = this._pendingDestroy
    this._pendingDestroy = null
    cb(null)
  }

  _onwrite(err) {
    this._continueWrite(err)
  }

  _onclose() {
    this._handle = null

    this._continueDestroy()
  }

  _onresize() {
    this._size = this.getWindowSize()

    this.emit('resize')
  }

  static _streams = new Set()

  static _resize = new Signal('SIGWINCH')
}

exports.constants = constants

exports.isTTY = binding.isTTY

exports.isatty = exports.isTTY // For Node.js compatibility

exports.WriteStream._resize
  .on('signal', () => {
    for (const stream of exports.WriteStream._streams) {
      stream._onresize()
    }
  })
  .unref()

function noop() {}
const binding = require('../binding')

module.exports = exports = {
  mode: {
    NORMAL: binding.MODE_NORMAL,
    RAW: binding.MODE_RAW,
    IO: binding.MODE_IO || 0
  },

  state: {
    READING: 0x1,
    CLOSING: 0x2
  }
}

/** @deprecated Use `mode.NORMAL` */
exports.MODE_NORMAL = exports.mode.NORMAL
/** @deprecated Use `mode.RAW` */
exports.MODE_RAW = exports.mode.RAW
/** @deprecated Use `mode.IO` */
exports.MODE_IO = exports.mode.IO
{
  "name": "bare-tty",
  "version": "5.1.0",
  "description": "Native TTY streams for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./constants": "./lib/constants.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-tty.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-tty/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-tty#readme",
  "engines": {
    "bare": ">=1.16.0"
  },
  "dependencies": {
    "bare-events": "^2.2.0",
    "bare-signals": "^4.0.0",
    "bare-stream": "^2.0.0"
  },
  "devDependencies": {
    "brittle": "^3.2.1",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = require.addon()
const binding = require('./binding')

const t = binding.constants

class Type {
  constructor(type) {
    this._type = type
  }

  isUndefined() {
    return this._type === t.UNDEFINED
  }

  isNull() {
    return this._type === t.NULL
  }

  isBoolean() {
    return this._type === t.BOOLEAN
  }

  isNumber() {
    return (this._type & 0xff) === t.NUMBER
  }

  isInt32() {
    return (this._type & (0xff | t.INT32)) === (t.NUMBER | t.INT32)
  }

  isUint32() {
    return (this._type & (0xff | t.UINT32)) === (t.NUMBER | t.UINT32)
  }

  isString() {
    return this._type === t.STRING
  }

  isSymbol() {
    return this._type === t.SYMBOL
  }

  isObject() {
    return (this._type & 0xff) === t.OBJECT
  }

  isArray() {
    return this._type === (t.OBJECT | t.ARRAY)
  }

  isArguments() {
    return this._type === (t.OBJECT | t.ARGUMENTS)
  }

  isDate() {
    return this._type === (t.OBJECT | t.DATE)
  }

  isRegExp() {
    return this._type === (t.OBJECT | t.REGEXP)
  }

  isError() {
    return this._type === (t.OBJECT | t.ERROR)
  }

  isPromise() {
    return this._type === (t.OBJECT | t.PROMISE)
  }

  isProxy() {
    return this._type === (t.OBJECT | t.PROXY)
  }

  isGenerator() {
    return this._type === (t.OBJECT | t.GENERATOR)
  }

  isMap() {
    return this._type === (t.OBJECT | t.MAP)
  }

  isSet() {
    return this._type === (t.OBJECT | t.SET)
  }

  isWeakMap() {
    return this._type === (t.OBJECT | t.WEAK_MAP)
  }

  isWeakSet() {
    return this._type === (t.OBJECT | t.WEAK_SET)
  }

  isWeakRef() {
    return this._type === (t.OBJECT | t.WEAK_REF)
  }

  isArrayBuffer() {
    return this._type === (t.OBJECT | t.ARRAYBUFFER)
  }

  isSharedArrayBuffer() {
    return this._type === (t.OBJECT | t.SHAREDARRAYBUFFER)
  }

  isTypedArray() {
    return (this._type & 0xffff) === (t.OBJECT | t.TYPEDARRAY)
  }

  isInt8Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT8ARRAY)
  }

  isUint8Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT8ARRAY)
  }

  isUint8ClampedArray() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT8CLAMPEDARRAY)
  }

  isInt16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT16ARRAY)
  }

  isUint16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT16ARRAY)
  }

  isInt32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT32ARRAY)
  }

  isUint32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT32ARRAY)
  }

  isFloat16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT16ARRAY)
  }

  isFloat32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT32ARRAY)
  }

  isFloat64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT64ARRAY)
  }

  isBigInt64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.BIGINT64ARRAY)
  }

  isBigUint64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.BIGUINT64ARRAY)
  }

  isDataView() {
    return this._type === (t.OBJECT | t.DATAVIEW)
  }

  isModuleNamespace() {
    return this._type === (t.OBJECT | t.MODULE_NAMESPACE)
  }

  isFunction() {
    return (this._type & 0xff) === t.FUNCTION
  }

  isAsyncFunction() {
    return (
      (this._type & (0xff | t.ASYNC_FUNCTION)) ===
      (t.FUNCTION | t.ASYNC_FUNCTION)
    )
  }

  isGeneratorFunction() {
    return (
      (this._type & (0xff | t.GENERATOR_FUNCTION)) ===
      (t.FUNCTION | t.GENERATOR_FUNCTION)
    )
  }

  isExternal() {
    return this._type === t.EXTERNAL
  }

  isBigInt() {
    return this._type === t.BIGINT
  }
}

module.exports = exports = function type(value) {
  switch (typeof value) {
    case 'undefined':
      return new Type(t.UNDEFINED)
    case 'boolean':
      return new Type(t.BOOLEAN)
    case 'number':
      return new Type(
        Number.isSafeInteger(value) ? binding.type(value) : t.NUMBER
      )
    case 'string':
      return new Type(t.STRING)
    case 'symbol':
      return new Type(t.SYMBOL)
    case 'object':
      return new Type(value === null ? t.NULL : binding.type(value))
    case 'function':
      return new Type(binding.type(value))
    case 'bigint':
      return new Type(t.BIGINT)
  }
}

exports.createTag = function createTag(...components) {
  const tag = new Uint32Array(4)
  for (let i = 0; i < 4; i++) tag[i] = components[i] || 0
  return tag
}

exports.addTag = function addTag(object, tag) {
  binding.addTag(object, tag)
}

exports.checkTag = function checkTag(object, tag) {
  return binding.checkTag(object, tag)
}
{
  "name": "bare-type",
  "version": "1.1.0",
  "description": "Cross-realm type predicates for Bare",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-type.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-type/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-type#readme",
  "engines": {
    "bare": ">=1.2.0"
  },
  "devDependencies": {
    "brittle": "^3.4.0",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
module.exports = require.addon()
const path = require('bare-path')
const binding = require('./binding')
const errors = require('./lib/errors')
const URLSearchParams = require('./lib/url-search-params')

const kind = Symbol.for('bare.url.kind')

const isWindows = Bare.platform === 'win32'

class URL {
  static get [kind]() {
    return 0 // Compatibility version
  }

  constructor(input, base, opts = {}) {
    if (arguments.length === 0) throw errors.INVALID_URL()

    input = String(input)

    if (base !== undefined) base = String(base)

    this._components = new Uint32Array(8)

    this._parse(input, base, opts.throw !== false)

    if (this._href) this._params = new URLSearchParams(this.search, this)
  }

  get [kind]() {
    return URL[kind]
  }

  // https://url.spec.whatwg.org/#dom-url-href

  get href() {
    return this._href
  }

  set href(value) {
    this._update(value)

    this._params._parse(this.search)
  }

  // https://url.spec.whatwg.org/#dom-url-protocol

  get protocol() {
    return this._slice(0, this._components[0]) + ':'
  }

  set protocol(value) {
    this._update(this._replace(value.replace(/:+$/, ''), 0, this._components[0]))
  }

  // https://url.spec.whatwg.org/#dom-url-username

  get username() {
    return this._slice(this._components[0] + 3 /* :// */, this._components[1])
  }

  set username(value) {
    if (cannotHaveCredentialsOrPort(this)) {
      return
    }

    if (this.username === '') value += '@'

    this._update(this._replace(value, this._components[0] + 3 /* :// */, this._components[1]))
  }

  // https://url.spec.whatwg.org/#dom-url-password

  get password() {
    return this._href.slice(this._components[1] + 1 /* : */, this._components[2] - 1 /* @ */)
  }

  set password(value) {
    if (cannotHaveCredentialsOrPort(this)) {
      return
    }

    let start = this._components[1] + 1 /* : */
    let end = this._components[2] - 1 /* @ */

    if (this.password === '') {
      value = ':' + value
      start--
    }

    if (this.username === '') {
      value += '@'
      end++
    }

    this._update(this._replace(value, start, end))
  }

  // https://url.spec.whatwg.org/#dom-url-host

  get host() {
    return this._slice(this._components[2], this._components[5])
  }

  set host(value) {
    if (hasOpaquePath(this)) {
      return
    }

    this._update(
      this._replace(value, this._components[2], this._components[value.includes(':') ? 5 : 3])
    )
  }

  // https://url.spec.whatwg.org/#dom-url-hostname

  get hostname() {
    return this._slice(this._components[2], this._components[3])
  }

  set hostname(value) {
    if (hasOpaquePath(this)) {
      return
    }

    this._update(this._replace(value, this._components[2], this._components[3]))
  }

  // https://url.spec.whatwg.org/#dom-url-port

  get port() {
    return this._slice(this._components[3] + 1 /* : */, this._components[5])
  }

  set port(value) {
    if (cannotHaveCredentialsOrPort(this)) {
      return
    }

    let start = this._components[3] + 1 /* : */

    if (this.port === '') {
      value = ':' + value
      start--
    }

    this._update(this._replace(value, start, this._components[5]))
  }

  // https://url.spec.whatwg.org/#dom-url-pathname

  get pathname() {
    return this._slice(this._components[5], this._components[6] - 1 /* ? */)
  }

  set pathname(value) {
    if (hasOpaquePath(this)) {
      return
    }

    if (value[0] !== '/' && value[0] !== '\\') {
      value = '/' + value
    }

    this._update(this._replace(value, this._components[5], this._components[6] - 1 /* ? */))
  }

  // https://url.spec.whatwg.org/#dom-url-search

  get search() {
    return this._slice(this._components[6] - 1 /* ? */, this._components[7] - 1 /* # */)
  }

  set search(value) {
    if (value && value[0] !== '?') value = '?' + value

    this._update(
      this._replace(value, this._components[6] - 1 /* ? */, this._components[7] - 1 /* # */)
    )

    this._params._parse(this.search)
  }

  // https://url.spec.whatwg.org/#dom-url-searchparams

  get searchParams() {
    return this._params
  }

  // https://url.spec.whatwg.org/#dom-url-hash

  get hash() {
    return this._slice(this._components[7] - 1 /* # */)
  }

  set hash(value) {
    if (value && value[0] !== '#') value = '#' + value

    this._update(this._replace(value, this._components[7] - 1 /* # */))
  }

  toString() {
    return this._href
  }

  toJSON() {
    return this._href
  }

  [Symbol.for('bare.inspect')]() {
    return {
      __proto__: { constructor: URL },

      href: this.href,
      protocol: this.protocol,
      username: this.username,
      password: this.password,
      host: this.host,
      hostname: this.hostname,
      port: this.port,
      pathname: this.pathname,
      search: this.search,
      searchParams: this.searchParams,
      hash: this.hash
    }
  }

  _slice(start, end = this._href.length) {
    return this._href.slice(start, end)
  }

  _replace(replacement, start, end = this._href.length) {
    return this._slice(0, start) + replacement + this._slice(end)
  }

  _parse(input, base, shouldThrow) {
    try {
      this._href = binding.parse(
        String(input),
        base ? String(base) : null,
        this._components,
        shouldThrow
      )
    } catch (err) {
      if (err instanceof TypeError) throw err

      throw errors.INVALID_URL(`Invalid URL '${input}'`, input)
    }
  }

  _update(input) {
    try {
      this._parse(input, null, true)
    } catch (err) {
      if (err instanceof TypeError) throw err
    }
  }
}

module.exports = exports = URL

// https://url.spec.whatwg.org/#url-opaque-path
function hasOpaquePath(url) {
  return url.pathname[0] !== '/'
}

// https://url.spec.whatwg.org/#cannot-have-a-username-password-port
function cannotHaveCredentialsOrPort(url) {
  return url.hostname === '' || url.protocol === 'file:'
}

exports.URL = URL
exports.URLSearchParams = URLSearchParams

exports.errors = errors

exports.isURL = function isURL(value) {
  if (value instanceof URL) return true

  return typeof value === 'object' && value !== null && value[kind] === URL[kind]
}

exports.isURLSearchParams = URLSearchParams.isURLSearchParams

// https://url.spec.whatwg.org/#dom-url-parse
exports.parse = function parse(input, base) {
  const url = new URL(input, base, { throw: false })
  return url._href ? url : null
}

// https://url.spec.whatwg.org/#dom-url-canparse
exports.canParse = function canParse(input, base) {
  return binding.canParse(String(input), base ? String(base) : null)
}

exports.fileURLToPath = function fileURLToPath(url) {
  if (typeof url === 'string') {
    url = new URL(url)
  }

  if (url.protocol !== 'file:') {
    throw errors.INVALID_URL_SCHEME('The URL must use the file: protocol')
  }

  if (isWindows) {
    if (/%2f|%5c/i.test(url.pathname)) {
      throw errors.INVALID_FILE_URL_PATH(
        'The file: URL path must not include encoded \\ or / characters'
      )
    }
  } else {
    if (url.hostname) {
      throw errors.INVALID_FILE_URL_HOST("The file: URL host must be 'localhost' or empty")
    }

    if (/%2f/i.test(url.pathname)) {
      throw errors.INVALID_FILE_URL_PATH('The file: URL path must not include encoded / characters')
    }
  }

  const pathname = path.normalize(decodeURIComponent(url.pathname))

  if (isWindows) {
    if (url.hostname) return '\\\\' + url.hostname + pathname

    const letter = pathname.charCodeAt(1) | 0x20

    if (letter < 0x61 /* a */ || letter > 0x7a /* z */ || pathname.charCodeAt(2) !== 0x3a /* : */) {
      throw errors.INVALID_FILE_URL_PATH('The file: URL path must be absolute')
    }

    return pathname.slice(1)
  }

  return pathname
}

exports.pathToFileURL = function pathToFileURL(pathname) {
  let resolved = path.resolve(pathname)

  if (pathname[pathname.length - 1] === '/') {
    resolved += '/'
  } else if (isWindows && pathname[pathname.length - 1] === '\\') {
    resolved += '\\'
  }

  resolved = resolved
    .replaceAll('%', '%25') // Must be first
    .replaceAll('#', '%23')
    .replaceAll('?', '%3f')
    .replaceAll('\n', '%0a')
    .replaceAll('\r', '%0d')
    .replaceAll('\t', '%09')

  if (!isWindows) {
    resolved = resolved.replaceAll('\\', '%5c')
  }

  return new URL('file:' + resolved)
}

exports.format = function format(parts) {
  const { protocol, auth, host, hostname, port, pathname, search, query, hash, slashes } = parts

  let result = ''

  if (typeof protocol === 'string') {
    result += protocol

    if (protocol[protocol.length - 1] !== ':') {
      result += ':'
    }

    if (slashes === true || /https?|ftp|gopher|file/.test(protocol)) {
      result += '//'
    }
  }

  if (typeof auth === 'string') {
    if (host || hostname) result += auth + '@'
  }

  if (typeof host === 'string') result += host
  else {
    result += hostname

    if (port) result += ':' + port
  }

  if (typeof pathname === 'string' && pathname !== '') {
    if (pathname[0] !== '/') result += '/'
    result += pathname
  }

  if (typeof search === 'string') {
    if (search[0] !== '?') result += '?'
    result += search
  } else if (typeof query === 'object' && query !== null) {
    result += '?' + new URLSearchParams(query)
  }

  if (typeof hash === 'string') {
    if (hash[0] !== '#') result += '#'
    result += hash
  }

  return result
}
module.exports = class URLError extends Error {
  constructor(msg, fn = URLError, code = fn.name) {
    super(`${code}: ${msg}`)

    this.code = code

    if (Error.captureStackTrace) Error.captureStackTrace(this, fn)
  }

  get name() {
    return 'URLError'
  }

  static INVALID_URL(msg, input) {
    const err = new URLError(msg, URLError.INVALID_URL)

    err.input = input

    return err
  }

  static INVALID_URL_SCHEME(msg = 'Invalid URL') {
    return new URLError(msg, URLError.INVALID_URL_SCHEME)
  }

  static INVALID_FILE_URL_HOST(msg = 'Invalid file: URL host') {
    return new URLError(msg, URLError.INVALID_FILE_URL_HOST)
  }

  static INVALID_FILE_URL_PATH(msg = 'Invalid file: URL path') {
    return new URLError(msg, URLError.INVALID_FILE_URL_PATH)
  }
}
const kind = Symbol.for('bare.url.search-params.kind')

class URLSearchParams {
  static _urls = new WeakMap()

  static get [kind]() {
    return 0 // Compatibility version
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-urlsearchparams
  constructor(init, url = null) {
    this._params = new Map()

    if (url) URLSearchParams._urls.set(this, url)

    if (typeof init === 'string') {
      this._parse(init)
    } else if (init) {
      for (const [name, value] of typeof init[Symbol.iterator] === 'function'
        ? init
        : Object.entries(init)) {
        this.append(name, value)
      }
    }
  }

  get [kind]() {
    return URLSearchParams[kind]
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-size
  get size() {
    return this._params.length
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-append
  append(name, value = null) {
    if (value === null) return

    let list = this._params.get(name)

    if (list === undefined) {
      list = []
      this._params.set(name, list)
    }

    list.push(value)

    this._update()
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-delete
  delete(name, value = null) {
    if (value === null) this._params.delete(name)
    else {
      let list = this._params.get(name)

      if (list === undefined) return

      list = list.filter((found) => found !== value)

      if (list.length === 0) this._params.delete(name)
      else this._params.set(name, list)
    }

    this._update()
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-get
  get(name) {
    const list = this._params.get(name)

    if (list === undefined) return null

    return list[0]
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-getall
  getAll(name) {
    const list = this._params.get(name)

    if (list === undefined) return []

    return Array.from(list)
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-has
  has(name, value = null) {
    const list = this._params.get(name)

    if (list === undefined) return false

    if (value === null) return true

    return list.includes(value)
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-set
  set(name, value = null) {
    if (value === null) this._params.delete(name)
    else this._params.set(name, [value])

    this._update()
  }

  toString() {
    return this._serialize()
  }

  toJSON() {
    return [...this]
  }

  *[Symbol.iterator]() {
    for (const [name, values] of this._params) {
      for (const value of values) yield [name, value]
    }
  }

  [Symbol.for('bare.inspect')]() {
    const object = {
      __proto__: { constructor: URLSearchParams }
    }

    for (const [name, values] of this._params) {
      if (values.length === 1) object[name] = values[0]
      else object[name] = values
    }

    return object
  }

  // https://url.spec.whatwg.org/#concept-urlsearchparams-update
  _update() {
    const url = URLSearchParams._urls.get(this)

    if (url === undefined) return

    url.search = this._serialize()
  }

  // https://url.spec.whatwg.org/#concept-urlencoded-parser
  _parse(input) {
    if (input[0] === '?') input = input.substring(1)

    this._params = new Map()

    for (let sequence of input.split('&')) {
      if (sequence.length === 0) continue

      sequence = sequence.replace(/\+/g, ' ')

      let i = sequence.indexOf('=')
      if (i === -1) i = sequence.length

      const name = decodeURIComponent(sequence.substring(0, i))
      const value = decodeURIComponent(sequence.substring(i + 1, sequence.length))

      let list = this._params.get(name)

      if (list === undefined) {
        list = []
        this._params.set(name, list)
      }

      list.push(value)
    }
  }

  // https://url.spec.whatwg.org/#concept-urlencoded-serializer
  _serialize() {
    let output = ''

    for (let [name, values] of this._params) {
      name = encodeURIComponent(name)

      for (const value of values) {
        if (output) output += '&'

        output += name + '=' + encodeURIComponent(value)
      }
    }

    return output
  }
}

module.exports = exports = URLSearchParams

exports.isURLSearchParams = function isURLSearchParams(value) {
  if (value instanceof URLSearchParams) return true

  return typeof value === 'object' && value !== null && value[kind] === URLSearchParams[kind]
}
{
  "name": "bare-url",
  "version": "2.4.2",
  "description": "WHATWG URL implementation for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "global.js",
    "global.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-url.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-url/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-url",
  "dependencies": {
    "bare-path": "^3.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "cmake-bare": "^1.1.6",
    "cmake-fetch": "^1.0.0",
    "lunte": "^1.6.0",
    "prettier": "^3.3.3",
    "prettier-config-holepunch": "^2.0.0"
  }
}
const b4a = require('b4a')

function byteLength (size) {
  return Math.ceil(size / 8)
}

function get (buffer, bit) {
  const n = buffer.BYTES_PER_ELEMENT * 8

  const offset = bit & (n - 1)
  const i = (bit - offset) / n

  return (buffer[i] & (1 << offset)) !== 0
}

function set (buffer, bit, value = true) {
  const n = buffer.BYTES_PER_ELEMENT * 8

  const offset = bit & (n - 1)
  const i = (bit - offset) / n
  const mask = 1 << offset

  if (value) {
    if ((buffer[i] & mask) !== 0) return false
  } else {
    if ((buffer[i] & mask) === 0) return false
  }

  buffer[i] ^= mask
  return true
}

function setRange (buffer, start, end, value = true) {
  const n = buffer.BYTES_PER_ELEMENT * 8

  let remaining = end - start
  let offset = start & (n - 1)
  let i = (start - offset) / n

  let changed = false

  while (remaining > 0) {
    const mask = (2 ** Math.min(remaining, n - offset) - 1) << offset

    if (value) {
      if ((buffer[i] & mask) !== mask) {
        buffer[i] |= mask
        changed = true
      }
    } else {
      if ((buffer[i] & mask) !== 0) {
        buffer[i] &= ~mask
        changed = true
      }
    }

    remaining -= n - offset
    offset = 0
    i++
  }

  return changed
}

function fill (buffer, value, start = 0, end = buffer.byteLength * 8) {
  const n = buffer.BYTES_PER_ELEMENT * 8
  let i, j

  {
    const offset = start & (n - 1)
    i = (start - offset) / n

    if (offset !== 0) {
      const mask = (2 ** Math.min(n - offset, end - start) - 1) << offset

      if (value) buffer[i] |= mask
      else buffer[i] &= ~mask

      i++
    }
  }

  {
    const offset = end & (n - 1)
    j = (end - offset) / n

    if (offset !== 0 && j >= i) {
      const mask = (2 ** offset) - 1

      if (value) buffer[j] |= mask
      else buffer[j] &= ~mask
    }
  }

  return buffer.fill(value ? (2 ** n) - 1 : 0, i, j)
}

function toggle (buffer, bit) {
  const n = buffer.BYTES_PER_ELEMENT * 8

  const offset = bit & (n - 1)
  const i = (bit - offset) / n
  const mask = 1 << offset

  buffer[i] ^= mask
  return (buffer[i] & mask) !== 0
}

function remove (buffer, bit) {
  return set(buffer, bit, false)
}

function removeRange (buffer, start, end) {
  return setRange(buffer, start, end, false)
}

function indexOf (buffer, value, position = 0) {
  for (let i = position, n = buffer.byteLength * 8; i < n; i++) {
    if (get(buffer, i) === value) return i
  }

  return -1
}

function lastIndexOf (buffer, value, position = buffer.byteLength * 8 - 1) {
  for (let i = position; i >= 0; i--) {
    if (get(buffer, i) === value) return i
  }

  return -1
}

function of (...bits) {
  return from(bits)
}

function from (bits) {
  const buffer = b4a.alloc(byteLength(bits.length))
  for (let i = 0; i < bits.length; i++) set(buffer, i, bits[i])
  return buffer
}

function * iterator (buffer) {
  for (let i = 0, n = buffer.byteLength * 8; i < n; i++) yield get(buffer, i)
}

module.exports = {
  byteLength,
  get,
  set,
  setRange,
  fill,
  toggle,
  remove,
  removeRange,
  indexOf,
  lastIndexOf,
  of,
  from,
  iterator
}
{
  "name": "bits-to-bytes",
  "version": "1.3.0",
  "description": "Functions for doing bit manipulation of typed arrays",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "scripts": {
    "test": "standard && brittle test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bits-to-bytes.git"
  },
  "author": "Kasper Isager Dalsgarð <kasper@funktionel.co>",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/holepunchto/bits-to-bytes/issues"
  },
  "homepage": "https://github.com/holepunchto/bits-to-bytes#readme",
  "dependencies": {
    "b4a": "^1.5.0"
  },
  "devDependencies": {
    "brittle": "^2.3.1",
    "standard": "^17.0.0"
  }
}
const EventEmitter = require('events')
const Protomux = require('protomux')
const { Readable } = require('streamx')
const sodium = require('sodium-universal')
const b4a = require('b4a')
const c = require('compact-encoding')
const bitfield = require('compact-encoding-bitfield')
const bits = require('bits-to-bytes')
const errors = require('./lib/errors')

exports.Server = class BlindRelayServer extends EventEmitter {
  constructor(opts = {}) {
    super()

    const { createStream } = opts

    this._createStream = createStream
    this._pairing = new Map()
    this._sessions = new Set()
    this.stats = createStats(this)
  }

  get sessions() {
    return this._sessions[Symbol.iterator]()
  }

  accept(stream, opts) {
    const session = new BlindRelaySession(this, stream, opts)

    this._sessions.add(session)
    this.stats.sessions.accepted++

    return session
  }

  async close() {
    const ending = []

    for (const session of this._sessions) {
      ending.push(session.end())
    }

    await Promise.all(ending)

    this._pairing.clear()
  }

  _activePairings() {
    const active = new Set()

    for (const session of this._sessions) {
      for (const token of session._links.keys()) {
        active.add(token)
      }
    }

    return active.size
  }

  _activeStreams() {
    let active = 0

    for (const session of this._sessions) {
      active += session._links.size
    }

    return active
  }
}

class BlindRelaySession extends EventEmitter {
  constructor(server, stream, opts = {}) {
    super()

    const { id, handshake, handshakeEncoding } = opts

    this._server = server
    this._mux = Protomux.from(stream)

    this._channel = this._mux.createChannel({
      protocol: 'blind-relay',
      id,
      handshake: handshake ? handshakeEncoding || c.raw : null,
      onopen: this._onopen.bind(this),
      onclose: this._onclose.bind(this),
      ondestroy: this._ondestroy.bind(this)
    })

    this._pair = this._channel.addMessage({
      encoding: m.pair,
      onmessage: this._onpair.bind(this)
    })

    this._unpair = this._channel.addMessage({
      encoding: m.unpair,
      onmessage: this._onunpair.bind(this)
    })

    this._ending = null
    this._destroyed = false
    this._error = null
    this._pairing = new Set()
    this._links = new Map()

    this._onerror = (err) => {
      this._server.stats.streams.errors++
      this.emit('error', err)
    }

    this._channel.open(handshake)
  }

  get closed() {
    return this._channel.closed
  }

  get mux() {
    return this._mux
  }

  get stream() {
    return this._mux.stream
  }

  _onopen() {
    this._server.stats.sessions.opened++
    this.emit('open')
  }

  _onclose() {
    this._ending = Promise.resolve()

    const err = this._error || errors.CHANNEL_CLOSED()
    this._server.stats.pairings.cancelled += this._pairing.size

    for (const token of this._pairing) {
      this._server._pairing.delete(token.toString('hex'))
    }

    for (const link of this._links.values()) {
      link.destroy(err)
    }

    this._pairing.clear()
    this._links.clear()

    this._server._sessions.delete(this)
    this._server.stats.sessions.closed++

    this.emit('close')
  }

  _ondestroy() {
    this._destroyed = true
    this.emit('destroy')
  }

  _onpair({ isInitiator, token, id: remoteId }) {
    const keyString = token.toString('hex')

    let pair = this._server._pairing.get(keyString)

    if (pair === undefined) {
      pair = new BlindRelayPair(token)
      this._server._pairing.set(keyString, pair)
    } else if (pair.links[+isInitiator]) return

    this._pairing.add(keyString)
    this._server.stats.pairings.requested++

    pair.links[+isInitiator] = new BlindRelayLink(this, isInitiator, remoteId)

    if (!pair.paired) return

    this._server._pairing.delete(keyString)
    this._server.stats.pairings.matched++

    // 1st pass: Create the raw streams needed for each end of the link.
    for (const link of pair.links) {
      link.createStream()
    }

    // 2nd pass: Connect the raw streams and set up handlers.
    for (const link of pair.links) {
      link.remote = pair.remote(link.isInitiator)
      link.activate(keyString)
    }

    // 3rd pass: Let either end of the link know the streams were set up.
    for (const { isInitiator, session, remoteId, stream } of pair.links) {
      session._pair.send({
        isInitiator,
        token,
        id: stream.id,
        seq: 0
      })

      session._endMaybe()

      session.emit('pair', isInitiator, token, stream, remoteId)
    }
  }

  _onunpair({ token }) {
    const keyString = token.toString('hex')

    const pair = this._server._pairing.get(keyString)

    if (pair) {
      for (const link of pair.links) {
        if (link) link.session._pairing.delete(keyString)
      }

      this._server.stats.pairings.cancelled++
      return this._server._pairing.delete(keyString)
    }

    const link = this._links.get(keyString)

    if (link) {
      link.destroyPair(errors.PAIRING_CANCELLED())
      this._server.stats.pairings.cancelled++
    }
  }

  cork() {
    this._channel.cork()
  }

  uncork() {
    this._channel.uncork()
  }

  async end() {
    if (this._ending) return this._ending

    this._ending = EventEmitter.once(this, 'close')
    this._endMaybe()

    return this._ending
  }

  _endMaybe() {
    if (this._ending && this._pairing.size === 0) {
      this._channel.close()
    }
  }

  destroy(err) {
    if (this._destroyed) return
    this._destroyed = true

    this._error = err || errors.CHANNEL_DESTROYED()
    this._channel.close()
  }
}

class BlindRelayPair {
  constructor(token) {
    this.token = token
    this.links = [null, null]
  }

  get paired() {
    return this.links[0] !== null && this.links[1] !== null
  }

  remote(isInitiator) {
    return this.links[isInitiator ? 0 : 1]
  }
}

class BlindRelayLink {
  constructor(session, isInitiator, remoteId) {
    this.session = session
    this.isInitiator = isInitiator
    this.remoteId = remoteId
    this.stream = null
    this.remote = null
    this.keyString = null
    this._onclose = null
  }

  createStream() {
    if (this.stream) return

    this.stream = this.session._server._createStream({
      firewall: this._onfirewall.bind(this)
    })
  }

  activate(keyString) {
    const stream = this.stream

    this.keyString = keyString
    this._onclose = () => {
      if (this.stream !== stream) return

      this.stream = null
      unlink(this)
      this.session._links.delete(keyString)
      this.session._server.stats.streams.closed++
    }

    stream.on('error', this.session._onerror).on('close', this._onclose).relayTo(this.remote.stream)

    this.session._pairing.delete(keyString)
    this.session._links.set(keyString, this)
    this.session._server.stats.streams.opened++
  }

  destroy(err) {
    const stream = this.stream

    if (!stream) return

    this.stream = null

    stream.off('close', this._onclose)
    this._onclose = null

    stream.off('error', this.session._onerror)
    unlink(this)
    this.session._links.delete(this.keyString)
    this.session._server.stats.streams.closed++
    stream.on('error', noop).destroy(err)
  }

  destroyPair(err) {
    const remote = this.remote

    this.destroy(err)
    if (remote) remote.destroy(err)
  }

  _onfirewall(socket, port, host) {
    this.stream.connect(socket, this.remoteId, port, host)

    return false
  }
}

exports.Client = class BlindRelayClient extends EventEmitter {
  static _clients = new WeakMap()

  static from(stream, opts) {
    let client = this._clients.get(stream)
    if (client) return client
    client = new this(stream, opts)
    this._clients.set(stream, client)
    return client
  }

  constructor(stream, opts = {}) {
    super()

    const { id, handshake, handshakeEncoding } = opts

    this._mux = Protomux.from(stream)

    this._channel = this._mux.createChannel({
      protocol: 'blind-relay',
      id,
      handshake: handshake ? handshakeEncoding || c.raw : null,
      onopen: this._onopen.bind(this),
      onclose: this._onclose.bind(this),
      ondestroy: this._ondestroy.bind(this)
    })

    this._pair = this._channel.addMessage({
      encoding: m.pair,
      onmessage: this._onpair.bind(this)
    })

    this._unpair = this._channel.addMessage({
      encoding: m.unpair
    })

    this._ending = false
    this._destroyed = false
    this._error = null
    this._requests = new Map()

    this._channel.open(handshake)
  }

  get closed() {
    return this._channel.closed
  }

  get mux() {
    return this._mux
  }

  get stream() {
    return this._mux.stream
  }

  get requests() {
    return this._requests.values()
  }

  _onopen() {
    this.emit('open')
  }

  _onclose() {
    this._ending = Promise.resolve()

    const err = this._error || errors.CHANNEL_CLOSED()

    for (const request of this._requests.values()) {
      request.destroy(err)
    }

    this._requests.clear()

    this.constructor._clients.delete(this.stream)

    this.emit('close')
  }

  _ondestroy() {
    this._destroyed = true
    this.emit('destroy')
  }

  _onpair({ isInitiator, token, id: remoteId }) {
    const request = this._requests.get(token.toString('hex'))

    if (request === undefined || request.isInitiator !== isInitiator) return

    request.push(remoteId)
    request.push(null)

    this.emit('pair', request.isInitiator, request.token, request.stream, remoteId)
  }

  pair(isInitiator, token, stream) {
    if (this._destroyed) throw errors.CHANNEL_DESTROYED()

    const keyString = token.toString('hex')

    if (this._requests.has(keyString)) throw errors.ALREADY_PAIRING()

    const request = new BlindRelayRequest(this, isInitiator, token, stream)

    this._requests.set(keyString, request)

    return request
  }

  unpair(token) {
    if (this._destroyed) throw errors.CHANNEL_DESTROYED()

    const request = this._requests.get(token.toString('hex'))

    if (request) request.destroy(errors.PAIRING_CANCELLED())

    this._unpair.send({ token })
  }

  cork() {
    this._channel.cork()
  }

  uncork() {
    this._channel.uncork()
  }

  async end() {
    if (this._ending) return this._ending

    this._ending = EventEmitter.once(this, 'close')
    this._endMaybe()

    return this._ending
  }

  _endMaybe() {
    if (this._ending && this._requests.size === 0) {
      this._channel.close()
    }
  }

  destroy(err) {
    if (this._destroyed) return
    this._destroyed = true

    this._error = err || errors.CHANNEL_DESTROYED()
    this._channel.close()
  }
}

class BlindRelayRequest extends Readable {
  constructor(client, isInitiator, token, stream) {
    super()

    this.client = client
    this.isInitiator = isInitiator
    this.token = token
    this.stream = stream
  }

  _open(cb) {
    if (this.client._destroyed) return cb(errors.CHANNEL_DESTROYED())

    this.client._pair.send({
      isInitiator: this.isInitiator,
      token: this.token,
      id: this.stream.id,
      seq: 0
    })

    cb(null)
  }

  _destroy(cb) {
    this.client._requests.delete(this.token.toString('hex'))

    cb(null)

    this.client._endMaybe()
  }
}

exports.token = function token(buf = b4a.allocUnsafe(32)) {
  sodium.randombytes_buf(buf)
  return buf
}

function noop() {}

function unlink(link) {
  const remote = link.remote

  link.remote = null

  if (remote && remote.remote === link) {
    remote.remote = null
  }
}

function createStats(server) {
  const stats = {
    sessions: {
      accepted: 0,
      opened: 0,
      closed: 0
    },
    pairings: {
      requested: 0,
      matched: 0,
      cancelled: 0
    },
    streams: {
      opened: 0,
      closed: 0,
      errors: 0
    }
  }

  Object.defineProperties(stats.sessions, {
    active: {
      enumerable: true,
      get() {
        return server._sessions.size
      }
    }
  })

  Object.defineProperties(stats.pairings, {
    pending: {
      enumerable: true,
      get() {
        return server._pairing.size
      }
    },
    active: {
      enumerable: true,
      get() {
        return server._activePairings()
      }
    }
  })

  Object.defineProperties(stats.streams, {
    active: {
      enumerable: true,
      get() {
        return server._activeStreams()
      }
    }
  })

  return stats
}

const m = (exports.messages = {})

const flags = bitfield(7)

m.pair = {
  preencode(state, m) {
    flags.preencode(state)
    c.fixed32.preencode(state, m.token)
    c.uint.preencode(state, m.id)
    c.uint.preencode(state, m.seq)
  },
  encode(state, m) {
    flags.encode(state, bits.of(m.isInitiator))
    c.fixed32.encode(state, m.token)
    c.uint.encode(state, m.id)
    c.uint.encode(state, m.seq)
  },
  decode(state) {
    const [isInitiator] = bits.iterator(flags.decode(state))

    return {
      isInitiator,
      token: c.fixed32.decode(state),
      id: c.uint.decode(state),
      seq: c.uint.decode(state)
    }
  }
}

m.unpair = {
  preencode(state, m) {
    flags.preencode(state)
    c.fixed32.preencode(state, m.token)
  },
  encode(state, m) {
    flags.encode(state, bits.of())
    c.fixed32.encode(state, m.token)
  },
  decode(state) {
    flags.decode(state)

    return {
      token: c.fixed32.decode(state)
    }
  }
}
module.exports = class BlindRelayError extends Error {
  constructor(msg, code, fn = BlindRelayError) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'BlindRelayError'
  }

  static DUPLICATE_CHANNEL(msg = 'Duplicate channel') {
    return new BlindRelayError(msg, 'DUPLICATE_CHANNEL', BlindRelayError.DUPLICATE_CHANNEL)
  }

  static CHANNEL_CLOSED(msg = 'Channel closed') {
    return new BlindRelayError(msg, 'CHANNEL_CLOSED', BlindRelayError.CHANNEL_CLOSED)
  }

  static CHANNEL_DESTROYED(msg = 'Channel destroyed') {
    return new BlindRelayError(msg, 'CHANNEL_DESTROYED', BlindRelayError.CHANNEL_DESTROYED)
  }

  static ALREADY_PAIRING(msg = 'Already pairing') {
    return new BlindRelayError(msg, 'ALREADY_PAIRING', BlindRelayError.ALREADY_PAIRING)
  }

  static PAIRING_CANCELLED(msg = 'Pairing cancelled') {
    return new BlindRelayError(msg, 'PAIRING_CANCELLED', BlindRelayError.PAIRING_CANCELLED)
  }
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return uint24.decode(state) + 0x1000000 * uint32.decode(state)
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return uint32.decode(state) + 0x100000000 * uint32.decode(state)
  }
})

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "2.19.2",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    if (b.byteLength === 0) return null
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "blind-relay",
  "version": "1.5.0",
  "description": "Blind relay for UDX over Protomux channels",
  "main": "index.js",
  "files": [
    "index.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:bare",
    "test:bare": "brittle-bare --coverage test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/blind-relay.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/blind-relay/issues"
  },
  "homepage": "https://github.com/holepunchto/blind-relay#readme",
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "dependencies": {
    "b4a": "^1.6.4",
    "bare-events": "^2.2.0",
    "bits-to-bytes": "^1.3.0",
    "compact-encoding": "^2.12.0",
    "compact-encoding-bitfield": "^1.0.0",
    "protomux": "^3.5.1",
    "sodium-universal": "^5.0.0",
    "streamx": "^2.15.1"
  },
  "devDependencies": {
    "brittle": "^3.2.1",
    "hyperdht": "^6.6.1",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "udx-native": "^1.6.1"
  }
}
// https://ipinfo.io/bogon

const b4a = require('b4a')
const c = require('compact-encoding')
const net = require('compact-encoding-net')

module.exports = exports = function isBogon (ip) {
  return isBogonIP(ensureBuffer(ip))
}

exports.isBogon = exports

exports.isPrivate = function isPrivate (ip) {
  return isPrivateIP(ensureBuffer(ip))
}

exports.isReserved = function isReserved (ip) {
  return isReservedIP(ensureBuffer(ip))
}

function isBogonIP (ip) {
  return isPrivateIP(ip) || isReservedIP(ip)
}

function isPrivateIP (ip) {
  return ip.byteLength === 4 ? isPrivateIPv4(ip) : false // IPv6 has no private IPs
}

function isPrivateIPv4 (ip) {
  return (
    // 10.0.0.0/8  Private-use networks
    (ip[0] === 10) ||
    // 100.64.0.0/10 Carrier-grade NAT
    (ip[0] === 100 && ip[1] >= 64 && ip[1] <= 127) ||
    // 127.0.0.0/8 Loopback + Name collision occurrence (127.0.53.53)
    (ip[0] === 127) ||
    // 169.254.0.0/16  Link local
    (ip[0] === 169 && ip[1] === 254) ||
    // 172.16.0.0/12 Private-use networks
    (ip[0] === 172 && ip[1] >= 16 && ip[1] <= 31) ||
    // 192.168.0.0/16  Private-use networks
    (ip[0] === 192 && ip[1] === 168)
  )
}

function isReservedIP (ip) {
  return ip.byteLength === 4 ? isReservedIPv4(ip) : isReservedIPv6(ip)
}

function isReservedIPv4 (ip) {
  return (
    // 0.0.0.0/8 "This" network
    (ip[0] === 0) ||
    // 192.0.0.0/24  IETF protocol assignments
    (ip[0] === 192 && ip[1] === 0 && ip[2] === 0) ||
    // 192.0.2.0/24  TEST-NET-1
    (ip[0] === 192 && ip[1] === 0 && ip[2] === 2) ||
    // 198.18.0.0/15 Network interconnect device benchmark testing
    (ip[0] === 198 && ip[1] >= 18 && ip[1] <= 19) ||
    // 198.51.100.0/24 TEST-NET-2
    (ip[0] === 198 && ip[1] === 51 && ip[2] === 100) ||
    // 203.0.113.0/24  TEST-NET-3
    (ip[0] === 203 && ip[1] === 0 && ip[2] === 113) ||
    // 224.0.0.0/4 Multicast
    (ip[0] >= 224 && ip[0] <= 239) ||
    // 240.0.0.0/4 Reserved for future use
    (ip[0] >= 240) ||
    // 255.255.255.255/32
    (ip[0] === 255 && ip[1] === 255 && ip[2] === 255 && ip[3] === 255)
  )
}

function isReservedIPv6 (ip) {
  return (
    // ::/128 Node-scope unicast unspecified address
    // ::1/128 Node-scope unicast loopback address
    (
      ip[0] === 0 && ip[1] === 0 && ip[2] === 0 && ip[3] === 0 && ip[4] === 0 &&
      ip[5] === 0 && ip[6] === 0 && ip[7] === 0 && ip[8] === 0 && ip[9] === 0 &&
      ip[10] === 0 && ip[11] === 0 && ip[12] === 0 && ip[13] === 0 && ip[14] === 0 &&
      ip[15] <= 1
    ) ||
    // ::ffff:0:0/96 IPv4-mapped addresses
    // ::/96 IPv4-compatible addresses
    (
      ip[0] === 0 && ip[1] === 0 && ip[2] === 0 && ip[3] === 0 && ip[4] === 0 &&
      ip[5] === 0 && ip[6] === 0 && ip[7] === 0 && ip[8] === 0 && ip[9] === 0 &&
      (ip[10] === 0 || ip[10] === 0xff) &&
      (ip[11] === 0 || ip[11] === 0xff)
    ) ||
    // 100::/64 Remotely triggered black hole addresses
    (ip[0] === 0x01 && ip[1] === 0 && ip[2] === 0 && ip[3] === 0 && ip[4] === 0 && ip[5] === 0 && ip[6] === 0 && ip[7] === 0) ||
    // 2001:10::/28 Overlay routable cryptographic hash identifiers (ORCHID)
    (ip[0] === 0x20 && ip[1] === 0x01 && ip[2] === 0 && ip[3] >= 0x10 && ip[3] <= 0x1f) ||
    // 2001:20::/28 Overlay routable cryptographic hash identifiers version 2 (ORCHIDv2)
    (ip[0] === 0x20 && ip[1] === 0x01 && ip[2] === 0 && ip[3] >= 0x20 && ip[3] <= 0x2f) ||
    // 2001:db8::/32 Documentation prefix
    (ip[0] === 0x20 && ip[1] === 0x01 && ip[2] === 0x0d && ip[3] === 0xb8) ||
    // fc00::/7 Unique local addresses (ULA)
    (ip[0] >= 0xfc && ip[0] <= 0xfd) ||
    // fe80::/10 Link-local unicast
    (ip[0] === 0xfe && ip[1] >= 0x80 && ip[1] <= 0xbf) ||
    // ff00::/8 Multicast
    (ip[0] === 0xff)
  )
}

const state = c.state(0, 0, b4a.allocUnsafe(1 /* family */ + 16))

function ensureBuffer (ip) {
  if (b4a.isBuffer(ip)) return ip

  net.ip.preencode(state, ip)
  net.ip.encode(state, ip)

  const buffer = state.buffer.subarray(1 /* family */, state.end)

  state.start = 0
  state.end = 0

  return buffer
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return uint24.decode(state) + 0x1000000 * uint32.decode(state)
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return uint32.decode(state) + 0x100000000 * uint32.decode(state)
  }
})

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "2.19.2",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    if (b.byteLength === 0) return null
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "bogon",
  "version": "1.2.0",
  "description": "Check if an IP is a bogon",
  "main": "index.js",
  "scripts": {
    "test": "standard && brittle test.mjs"
  },
  "dependencies": {
    "compact-encoding": "^2.11.0",
    "compact-encoding-net": "^1.2.0"
  },
  "devDependencies": {
    "brittle": "^3.0.4",
    "nanobench": "^2.1.1",
    "standard": "^17.0.0"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/bogon.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/bogon/issues"
  },
  "homepage": "https://github.com/mafintosh/bogon"
}
const c = require('compact-encoding')

module.exports = function bitfield (length) {
  if (length > 64) throw new RangeError('Bitfield cannot be larger than 64 bits')

  let byteLength
  if (length < 8) byteLength = 1
  else if (length <= 16) byteLength = 2
  else if (length <= 32) byteLength = 4
  else byteLength = 8

  return {
    preencode (state) {
      state.end++ // Length byte, used for data when byteLength === 1

      if (byteLength === 1) ;
      else if (byteLength === 2) c.uint16.preencode(state)
      else if (byteLength === 4) c.uint32.preencode(state)
      else c.uint64.preencode(state)
    },

    encode (state, b) {
      if (byteLength === 1) ;
      else if (byteLength === 2) c.uint8.encode(state, 0xfd)
      else if (byteLength === 4) c.uint8.encode(state, 0xfe)
      else c.uint8.encode(state, 0xff)

      if (typeof b === 'number') {
        if (byteLength === 1) c.uint8.encode(state, b)
        else if (byteLength === 2) c.uint16.encode(state, b)
        else if (byteLength === 4) c.uint32.encode(state, b)
        else c.uint64.encode(state, b)
      } else {
        state.buffer.set(b, state.start)

        if (b.byteLength < byteLength) {
          // Zero-fill the rest of the byte length.
          state.buffer.fill(
            0,
            state.start + b.byteLength,
            state.start + byteLength
          )
        }

        state.start += byteLength
      }
    },

    decode (state) {
      const byte = state.buffer[state.start]

      let byteLength
      if (byte <= 0xfc) byteLength = 1
      else if (byte === 0xfd) byteLength = 2
      else if (byte === 0xfe) byteLength = 4
      else byteLength = 8

      if (byteLength > 1) state.start++ // Skip the length byte

      if (state.end - state.start < byteLength) throw new Error('Out of bounds')

      const b = state.buffer.subarray(state.start, (state.start += byteLength))

      return length <= 8 ? b.subarray(0, 1) : b
    }
  }
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return uint24.decode(state) + 0x1000000 * uint32.decode(state)
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return uint32.decode(state) + 0x100000000 * uint32.decode(state)
  }
})

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "2.19.2",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    if (b.byteLength === 0) return null
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "compact-encoding-bitfield",
  "version": "1.0.0",
  "description": "Compact codec for bitfields",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "scripts": {
    "test": "standard && brittle test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/compact-encoding/compact-encoding-bitfield.git"
  },
  "author": "Kasper Isager Dalsgarð <kasper@funktionel.co>",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/compact-encoding/compact-encoding-bitfield/issues"
  },
  "homepage": "https://github.com/compact-encoding/compact-encoding-bitfield#readme",
  "dependencies": {
    "compact-encoding": "^2.4.1"
  },
  "devDependencies": {
    "brittle": "^1.3.5",
    "standard": "^16.0.3"
  },
  "standard": {
    "ignore": [
      "__snapshots__/**"
    ]
  }
}
const c = require('compact-encoding')

const port = c.uint16

const address = (host, family) => {
  return {
    preencode (state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode (state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode (state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = {
  preencode (state) {
    state.end += 4
  },
  encode (state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (i < string.length && (c = string.charCodeAt(i++)) !== /* . */ 0x2e) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode (state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] + '.' +
      state.buffer[state.start++] + '.' +
      state.buffer[state.start++] + '.' +
      state.buffer[state.start++]
    )
  }
}

const ipv4Address = address(ipv4, 4)

const ipv6 = {
  preencode (state) {
    state.end += 16
  },
  encode (state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (i < string.length && (c = string.charCodeAt(i++)) !== /* : */ 0x3a) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode (state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (state.buffer[state.start++] * 256 + state.buffer[state.start++]).toString(16) + ':' +
      (state.buffer[state.start++] * 256 + state.buffer[state.start++]).toString(16) + ':' +
      (state.buffer[state.start++] * 256 + state.buffer[state.start++]).toString(16) + ':' +
      (state.buffer[state.start++] * 256 + state.buffer[state.start++]).toString(16) + ':' +
      (state.buffer[state.start++] * 256 + state.buffer[state.start++]).toString(16) + ':' +
      (state.buffer[state.start++] * 256 + state.buffer[state.start++]).toString(16) + ':' +
      (state.buffer[state.start++] * 256 + state.buffer[state.start++]).toString(16) + ':' +
      (state.buffer[state.start++] * 256 + state.buffer[state.start++]).toString(16)
    )
  }
}

const ipv6Address = address(ipv6, 6)

const ip = {
  preencode (state, string) {
    const family = string.includes(':') ? 6 : 4
    c.uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode (state, string) {
    const family = string.includes(':') ? 6 : 4
    c.uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode (state) {
    const family = c.uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
}

const ipAddress = {
  preencode (state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode (state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode (state) {
    const family = c.uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

module.exports = {
  port,
  ipv4,
  ipv4Address,
  ipv6,
  ipv6Address,
  ip,
  ipAddress
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return uint24.decode(state) + 0x1000000 * uint32.decode(state)
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return uint32.decode(state) + 0x100000000 * uint32.decode(state)
  }
})

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "2.19.2",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    if (b.byteLength === 0) return null
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "compact-encoding-net",
  "version": "1.2.0",
  "description": "Compact codecs for net types",
  "main": "index.js",
  "scripts": {
    "test": "standard && brittle test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/compact-encoding/compact-encoding-net.git"
  },
  "author": "Kasper Isager Dalsgarð <kasper@funktionel.co>",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/compact-encoding/compact-encoding-net/issues"
  },
  "homepage": "https://github.com/compact-encoding/compact-encoding-net#readme",
  "dependencies": {
    "compact-encoding": "^2.4.1"
  },
  "devDependencies": {
    "brittle": "^1.3.5",
    "nanobench": "^2.1.1",
    "standard": "^16.0.3"
  }
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return uint24.decode(state) + 0x1000000 * uint32.decode(state)
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return uint32.decode(state) + 0x100000000 * uint32.decode(state)
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return 0x100000000 * uint32be.decode(state) + uint32be.decode(state)
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.2.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
const { EventEmitter } = require('events')
const Table = require('kademlia-routing-table')
const TOS = require('time-ordered-set')
const UDX = require('udx-native')
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const NatSampler = require('nat-sampler')
const b4a = require('b4a')
const NetworkHealth = require('./lib/health')
const IO = require('./lib/io')
const Query = require('./lib/query')
const Session = require('./lib/session')
const peer = require('./lib/peer')
const { UNKNOWN_COMMAND, INVALID_TOKEN } = require('./lib/errors')
const { PING, PING_NAT, FIND_NODE, DOWN_HINT, DELAYED_PING } = require('./lib/commands')

const TMP = b4a.allocUnsafe(32)
const TICK_INTERVAL = 5000
const SLEEPING_INTERVAL = 3 * TICK_INTERVAL
const STABLE_TICKS = 240 // if nothing major bad happens in ~20mins we can consider this node stable (if nat is friendly)
const MORE_STABLE_TICKS = 3 * STABLE_TICKS
const REFRESH_TICKS = 60 // refresh every ~5min when idle
const RECENT_NODE = 12 // we've heard from a node less than 1min ago
const OLD_NODE = 360 // if an node has been around more than 30 min we consider it old

const DEFAULTS = {
  concurrency: 10,
  maxWindow: IO.DEFAULT_MAX_WINDOW,
  maxPingDelay: 10_000
}

class DHT extends EventEmitter {
  constructor(opts = {}) {
    super()

    this.bootstrapNodes = opts.bootstrap === false ? [] : (opts.bootstrap || []).map(parseNode)
    this.table = new Table(randomBytes(32))
    this.nodes = new TOS()
    this.udx = opts.udx || new UDX()
    this.io = new IO(this.table, this.udx, {
      ...opts,
      onrequest: this._onrequest.bind(this),
      onresponse: this._onresponse.bind(this),
      ontimeout: this._ontimeout.bind(this)
    })
    this.health = new NetworkHealth(this)

    this.concurrency = opts.concurrency || DEFAULTS.concurrency
    this.maxPingDelay = opts.maxPingDelay || DEFAULTS.maxPingDelay
    this.bootstrapped = false
    this.ephemeral = true
    this.firewalled = this.io.firewalled
    this.adaptive = typeof opts.ephemeral !== 'boolean' && opts.adaptive !== false
    this.destroyed = false
    this.suspended = false
    this.online = true
    this.degraded = false
    this.stats = {
      queries: { active: 0, total: 0 },
      requests: this.io.stats.requests,
      commands: {
        ping: this.io.stats.commands[PING],
        pingNat: this.io.stats.commands[PING_NAT],
        findNode: this.io.stats.commands[FIND_NODE],
        downHint: this.io.stats.commands[DOWN_HINT]
      }
    }

    this._nat = new NatSampler()
    this._quickFirewall = opts.quickFirewall !== false
    this._forcePersistent = opts.ephemeral === false
    this._repinging = 0
    this._checks = 0
    this._tick = randomOffset(100) // make sure to random offset all the network ticks
    this._refreshTicks = randomOffset(REFRESH_TICKS)
    this._stableTicks = this.adaptive ? STABLE_TICKS : 0
    this._tickInterval = setInterval(this._ontick.bind(this), TICK_INTERVAL)
    this._lastTick = Date.now()
    this._lastHost = null
    this._filterNode = opts.filterNode || opts.addNode || null // opts.addNode is deprecating, use opts.filterNode instead
    this._onrow = (row) => row.on('full', (node) => this._onfullrow(node, row))
    this._nonePersistentSamples = []
    this._bootstrapping = this._bootstrap()
    this._bootstrapping.catch(noop)
    this._sendDownHints = opts.sendDownHints !== false
    this._downHintsRateLimit =
      opts.downHintsRateLimit !== undefined ? opts.downHintsRateLimit : 10 * 5
    this._downHintsSentPerTick = 0
    this._pendingTimers = new Set()

    this.table.on('row', this._onrow)

    this.io.networkInterfaces.on('change', (interfaces) => this._onnetworkchange(interfaces))

    if (opts.nodes) {
      for (let i = opts.nodes.length - 1; i >= 0; i--) {
        this.addNode(opts.nodes[i])
      }
    }
  }

  static DEFAULTS = DEFAULTS

  static bootstrapper(port, host, opts) {
    if (!port) throw new Error('Port is required')
    if (!host) throw new Error('Host is required')
    if (host === '0.0.0.0' || host === '::') throw new Error('Invalid host')
    if (!UDX.isIPv4(host)) throw new Error('Host must be a IPv4 address')

    const dht = new this({
      port,
      ephemeral: false,
      firewalled: false,
      anyPort: false,
      bootstrap: [],
      ...opts
    })
    dht._nat.add(host, port)
    return dht
  }

  get id() {
    return this.ephemeral ? null : this.table.id
  }

  get host() {
    return this._nat.host
  }

  get port() {
    return this._nat.port
  }

  get randomized() {
    return this._nat.host !== null && this._nat.port === 0
  }

  get socket() {
    return this.firewalled ? this.io.clientSocket : this.io.serverSocket
  }

  get config() {
    return {
      concurrency: this.concurrency,
      maxWindow: this.io.congestion._maxWindow,
      randomPunchInterval: this._randomPunchInterval,
      connectionKeepAlive: this.connectionKeepAlive,
      sendDownHints: this._sendDownHints,
      downHintsRateLimit: this._downHintsRateLimit
    }
  }

  onmessage(socket, buf, rinfo) {
    if (buf.byteLength > 1) this.io.onmessage(socket, buf, rinfo)
  }

  bind() {
    return this.io.bind()
  }

  async suspend({ log = noop } = {}) {
    log('Suspending waiting for io bind...')
    await this.io.bind()
    log('Done, continuing')
    if (this.suspended || this.destroyed) return
    this.suspended = true
    clearInterval(this._tickInterval)
    log('Done, suspending io')
    await this.io.suspend({ log })
    log('Done, dht suspended')
    this.emit('suspend')
  }

  async resume({ log = noop } = {}) {
    if (!this.suspended || this.destroyed) return
    this.suspended = false
    this._tickInterval = setInterval(this._ontick.bind(this), TICK_INTERVAL)
    this._onwakeup()
    log('Resuming io')
    await this.io.resume()
    log('Done, dht resumed')
    this.io.networkInterfaces.on('change', (interfaces) => this._onnetworkchange(interfaces))
    this.refresh()
    this.emit('resume')
  }

  address() {
    const socket = this.socket
    return socket ? socket.address() : null
  }

  localAddress() {
    if (!this.io.serverSocket) return null

    return {
      host: localIP(this.udx),
      port: this.io.serverSocket.address().port
    }
  }

  remoteAddress() {
    if (!this.host) return null
    if (!this.port) return null
    if (this.firewalled) return null
    if (!this.io.serverSocket) return null

    const port = this.io.serverSocket.address().port
    if (port !== this.port) return null

    return {
      host: this.host,
      port
    }
  }

  addNode({ host, port }) {
    this._addNode({
      id: peer.id(host, port),
      port,
      host,
      token: null,
      to: null,
      sampled: 0,
      added: this._tick,
      pinged: 0,
      seen: 0,
      downHints: 0,
      prev: null,
      next: null
    })
  }

  toArray(opts) {
    const limit = opts && opts.limit
    if (limit === 0) return []
    return this.nodes.toArray({ limit, reverse: true }).map(({ host, port }) => ({ host, port }))
  }

  async fullyBootstrapped() {
    return this._bootstrapping
  }

  ready() {
    // Deprecating, use fullyBootstrapped instead (removed on next major)
    return this.fullyBootstrapped()
  }

  findNode(target, opts) {
    if (this.destroyed) throw new Error('Node destroyed')
    this._refreshTicks = REFRESH_TICKS
    return new Query(this, target, true, FIND_NODE, null, opts)
  }

  query({ target, command, value }, opts) {
    if (this.destroyed) throw new Error('Node destroyed')
    this._refreshTicks = REFRESH_TICKS
    return new Query(this, target, false, command, value || null, opts)
  }

  ping({ host, port }, opts) {
    let value = null

    if (opts && opts.size && opts.size > 0) value = b4a.alloc(opts.size)

    const req = this.io.createRequest(
      { id: null, host, port },
      null,
      true,
      PING,
      null,
      value,
      (opts && opts.session) || null,
      opts && opts.ttl
    )
    return this._requestToPromise(req, opts)
  }

  delayedPing({ host, port }, delayMs, opts) {
    if (delayMs > this.maxPingDelay) {
      throw new Error(`Delay exceeds max delay: ${this.maxPingDelay}ms`)
    }

    const value = b4a.allocUnsafe(4)
    c.uint32.encode({ start: 0, end: 4, buffer: value }, delayMs)

    const req = this.io.createRequest(
      { id: null, host, port },
      null,
      true,
      DELAYED_PING,
      null,
      value,
      (opts && opts.session) || null,
      opts && opts.ttl
    )
    // add 1 second to the timeout to account for network overhead
    req.timeout = delayMs + 1_000
    return this._requestToPromise(req, opts)
  }

  async rttStats() {
    const stats = {
      successes: 0,
      errors: 0,
      responses: {
        avgRtt: 0,
        errors: 0,
        avgCloserNodes: 0
      },
      closestReplies: {
        avgRtt: 0,
        errors: 0,
        avgCloserNodes: 0
      }
    }

    if (this.nodes.latest) {
      const q = this.findNode(this.nodes.latest.id)

      let responseCount = 0
      let closestCount = 0

      for await (const msg of q) {
        stats.responses.avgRtt += msg.rtt
        stats.responses.errors += msg.error
        stats.responses.avgCloserNodes += msg.closerNodes?.length || 0
        responseCount++
      }
      stats.responses.avgRtt /= responseCount
      stats.responses.avgCloserNodes /= responseCount

      for await (const msg of q.closestReplies) {
        stats.closestReplies.avgRtt += msg.rtt
        stats.closestReplies.errors += msg.error
        stats.closestReplies.avgCloserNodes += msg.closerNodes?.length || 0
        closestCount++
      }
      stats.closestReplies.avgRtt /= closestCount
      stats.closestReplies.avgCloserNodes /= closestCount

      stats.successes = q.successes
      stats.errors = q.errors
    }

    return stats
  }

  request({ token = null, command, target = null, value = null }, { host, port }, opts) {
    const req = this.io.createRequest(
      { id: null, host, port },
      token,
      false,
      command,
      target,
      value,
      (opts && opts.session) || null,
      opts && opts.ttl
    )
    return this._requestToPromise(req, opts)
  }

  session() {
    return new Session(this)
  }

  _requestToPromise(req, opts) {
    if (req === null) return Promise.reject(new Error('Node destroyed'))

    if (opts && opts.socket) req.socket = opts.socket
    if (opts && opts.retry === false) req.retries = 0

    return new Promise((resolve, reject) => {
      req.onresponse = resolve
      req.onerror = reject
      req.send()
    })
  }

  async _bootstrap() {
    const self = this

    await Promise.resolve() // wait a tick, so apis can be used from the outside
    await this.io.bind()

    this.emit('listening')

    // TODO: some papers describe more advanced ways of bootstrapping - we should prob look into that

    let first = this.firewalled && this._quickFirewall && !this._forcePersistent
    let testNat = false

    const onlyFirewall = !this._forcePersistent

    for (let i = 0; i < 2; i++) {
      await this._backgroundQuery(this.table.id).on('data', ondata).finished()

      if (this.bootstrapped || (!testNat && !this._forcePersistent)) break
      if (!(await this._updateNetworkState(onlyFirewall))) break
    }

    if (this.bootstrapped) return
    this.bootstrapped = true

    this.emit('ready')

    function ondata(data) {
      // Simple QUICK nat heuristic.
      // If we get ONE positive nat ping before the bootstrap query finishes
      // then we always to a nat test, no matter if we are adaptive...
      // This should be expanded in the future to try more than one node etc, not always hit the first etc
      // If this fails, then nbd, as the onstable hook will pick it up later.

      if (!first) return
      first = false

      const value = b4a.allocUnsafe(2)
      c.uint16.encode({ start: 0, end: 2, buffer: value }, self.io.serverSocket.address().port)

      self._request(
        data.from,
        false,
        true,
        PING_NAT,
        null,
        value,
        null,
        () => {
          testNat = true
        },
        noop
      )
    }
  }

  refresh() {
    const node = this.table.random()
    this._backgroundQuery(node ? node.id : this.table.id).on('error', noop)
  }

  async destroy() {
    const emitClose = !this.destroyed
    this.destroyed = true
    clearInterval(this._tickInterval)
    for (const timer of this._pendingTimers) {
      clearTimeout(timer)
    }
    await this.io.destroy()
    if (emitClose) this.emit('close')
  }

  _request(to, force, internal, command, target, value, session, onresponse, onerror) {
    if (internal && !this._sendDownHints && command === DOWN_HINT) return null
    const req = this.io.createRequest(to, null, internal, command, target, value, session)
    if (req === null) return null

    req.onresponse = onresponse
    req.onerror = onerror
    req.send(force)

    return req
  }

  _natAdd(host, port) {
    const prevHost = this._nat.host
    const prevPort = this._nat.port

    this._nat.add(host, port)

    if (prevHost === this._nat.host && prevPort === this._nat.port) return

    this.emit('nat-update', this._nat.host, this._nat.port)
  }

  // we don't check that this is a bootstrap node but we limit the sample size to very few nodes, so fine
  _sampleBootstrapMaybe(from, to) {
    if (this._nonePersistentSamples.length >= Math.max(1, this.bootstrapNodes.length)) return
    const id = from.host + ':' + from.port
    if (this._nonePersistentSamples.indexOf(id) > -1) return
    this._nonePersistentSamples.push(id)
    this._natAdd(to.host, to.port)
  }

  _addNodeFromNetwork(sample, from, to) {
    if (this._filterNode !== null && !this._filterNode(from)) {
      return
    }

    if (from.id === null) {
      this._sampleBootstrapMaybe(from, to)
      return
    }

    const oldNode = this.table.get(from.id)

    // refresh it, if we've seen this before
    if (oldNode) {
      if (sample && (oldNode.sampled === 0 || this._tick - oldNode.sampled >= OLD_NODE)) {
        oldNode.to = to
        oldNode.sampled = this._tick
        this._natAdd(to.host, to.port)
      }

      oldNode.pinged = oldNode.seen = this._tick
      this.nodes.add(oldNode)
      return
    }

    this._addNode({
      id: from.id,
      port: from.port,
      host: from.host,
      to,
      sampled: 0,
      added: this._tick,
      pinged: this._tick, // last time we interacted with them
      seen: this._tick, // last time we heard from them
      downHints: 0,
      prev: null,
      next: null
    })
  }

  _addNode(node) {
    if (this.nodes.has(node) || b4a.equals(node.id, this.table.id)) return

    node.added = node.pinged = node.seen = this._tick

    if (!this.table.add(node)) return
    this.nodes.add(node)

    if (node.to && node.sampled === 0) {
      node.sampled = this._tick
      this._natAdd(node.to.host, node.to.port)
    }

    this.emit('add-node', node)
  }

  _removeStaleNode(node, lastSeen) {
    if (node.seen <= lastSeen) this._removeNode(node)
  }

  _removeNode(node) {
    if (!this.nodes.has(node)) return

    this.table.remove(node.id)
    this.nodes.remove(node)

    this.emit('remove-node', node)
  }

  _onwakeup() {
    this._tick += 2 * OLD_NODE // bump the tick enough that everything appears old.
    this._tick += 8 - (this._tick & 7) - 2 // triggers a series of pings in two ticks
    this._stableTicks = MORE_STABLE_TICKS
    this._refreshTicks = 1 // triggers a refresh next tick (allow network time to wake up also)
    this._lastHost = null // clear network cache check
    this.health.reset()

    if (this.adaptive) {
      // TODO: re-enable this as soon as we find out why this is over triggering in some edge cases
      // this.firewalled = true
      // this.io.firewalled = true

      if (!this.ephemeral) {
        this.ephemeral = true
        this.io.ephemeral = true
        this.emit('ephemeral')
      }
    }

    this.emit('wakeup')
  }

  _onfullrow(newNode, row) {
    if (!this.bootstrapped || this._repinging >= 3) return

    let oldest = null
    for (const node of row.nodes) {
      if (node.pinged === this._tick) continue
      if (
        oldest === null ||
        oldest.pinged > node.pinged ||
        (oldest.pinged === node.pinged && oldest.added > node.added)
      ) {
        oldest = node
      }
    }

    if (oldest === null) return
    if (this._tick - oldest.pinged < RECENT_NODE && this._tick - oldest.added > OLD_NODE) return

    this._repingAndSwap(newNode, oldest)
  }

  _onnetworkchange(interfaces) {
    this.emit('network-change', interfaces)
    this.emit('network-update')
  }

  _repingAndSwap(newNode, oldNode) {
    const self = this
    const lastSeen = oldNode.seen

    oldNode.pinged = this._tick

    this._repinging++
    this._request(
      { id: null, host: oldNode.host, port: oldNode.port },
      false,
      true,
      PING,
      null,
      null,
      null,
      onsuccess,
      onswap
    )

    function onsuccess(m) {
      if (oldNode.seen <= lastSeen) return onswap()
      self._repinging--
    }

    function onswap(e) {
      self._repinging--
      self._removeNode(oldNode)
      self._addNode(newNode)
    }
  }

  _onrequest(req, external) {
    if (req.from.id !== null) {
      this._addNodeFromNetwork(!external, req.from, req.to)
    }

    if (req.internal) {
      switch (req.command) {
        // standard keep alive call
        case PING: {
          req.sendReply(0, null, false, false)
          return
        }
        case DELAYED_PING: {
          this._ondelayedping(req)
          return
        }
        // check if the other side can receive a message to their other socket
        case PING_NAT: {
          if (req.value === null || req.value.byteLength < 2) return
          const port = c.uint16.decode({ start: 0, end: 2, buffer: req.value })
          if (port === 0) return
          req.from.port = port
          req.sendReply(0, null, false, false)
          return
        }
        // empty dht reply back
        case FIND_NODE: {
          if (!req.target) return
          req.sendReply(0, null, false, true)
          return
        }
        // "this is node you sent me is down" - let's try to ping it
        case DOWN_HINT: {
          if (req.value === null || req.value.byteLength < 6) return
          if (this._checks < 10) {
            sodium.crypto_generichash(TMP, req.value.subarray(0, 6))
            const node = this.table.get(TMP)
            if (node && (node.pinged < this._tick || node.downHints === 0)) {
              node.downHints++
              this._check(node)
            }
          }
          req.sendReply(0, null, false, false)
          return
        }
      }

      req.sendReply(UNKNOWN_COMMAND, null, false, req.target !== null)
      return
    }

    // ask the user to handle it or reply back with a bad command
    if (this.onrequest(req) === false) {
      req.sendReply(UNKNOWN_COMMAND, null, false, req.target !== null)
    }
  }

  onrequest(req) {
    return this.emit('request', req)
  }

  _ondelayedping(req) {
    if (req.value === null || req.value.byteLength < 4) return
    const delayMs = c.uint32.decode({ start: 0, end: 4, buffer: req.value })
    if (delayMs > this.maxPingDelay) return
    const timer = setTimeout(() => {
      if (this.destroyed) return
      this._pendingTimers.delete(timer)
      req.sendReply(0, null, false, false)
    }, delayMs)
    this._pendingTimers.add(timer)
  }

  _onresponse(res, external) {
    this._addNodeFromNetwork(!external, res.from, res.to)
  }

  _ontimeout(req) {
    if (!req.to.id) return
    const node = this.table.get(req.to.id)
    if (node) this._removeNode(node)
  }

  _pingSome() {
    let cnt = this.io.inflight.length > 2 ? 3 : 5
    let oldest = this.nodes.oldest

    // tiny dht, pinged the bootstrap again
    if (!oldest) {
      this.refresh()
      return
    }

    // we've recently pinged the oldest one, so only trigger a couple of repings
    if (this._tick - oldest.pinged < RECENT_NODE) {
      cnt = 2
    }

    while (cnt--) {
      if (!oldest || this._tick === oldest.pinged) continue
      this._check(oldest)
      oldest = oldest.next
    }
  }

  _check(node) {
    node.pinged = this._tick

    const lastSeen = node.seen
    const onresponse = () => {
      this._checks--
      this._removeStaleNode(node, lastSeen)
    }
    const onerror = () => {
      this._checks--
      this._removeNode(node)
    }

    this._checks++
    this._request(
      { id: null, host: node.host, port: node.port },
      false,
      true,
      PING,
      null,
      null,
      null,
      onresponse,
      onerror
    )
  }

  _ontick() {
    const time = Date.now()

    if (time - this._lastTick > SLEEPING_INTERVAL && this.suspended === false) {
      this._onwakeup()
    } else {
      this._tick++
    }

    this._lastTick = time

    if (!this.bootstrapped || this.suspended) return

    if (this.adaptive && this.ephemeral && --this._stableTicks <= 0) {
      if (this._lastHost === this._nat.host) {
        // do not recheck the same network...
        this._stableTicks = MORE_STABLE_TICKS
      } else {
        this._updateNetworkState() // the promise returned here never fails so just ignore it
      }
    }

    if ((this._tick & 7) === 0) {
      this._pingSome()
    }

    if (
      ((this._tick & 63) === 0 && this.nodes.length < this.table.k) ||
      --this._refreshTicks <= 0
    ) {
      this.refresh()
    }

    this._downHintsSentPerTick = 0
    this.health.update()
  }

  async _updateNetworkState(onlyFirewall = false) {
    if (!this.ephemeral) return false
    if (onlyFirewall && !this.firewalled) return false

    const { host, port } = this._nat

    if (!onlyFirewall) {
      // remember what host we checked and reset the counter
      this._stableTicks = MORE_STABLE_TICKS
      this._lastHost = host
    }

    // check if we have a consistent host and port
    if (host === null || port === 0) {
      return false
    }

    const natSampler = this.firewalled ? new NatSampler() : this._nat

    // ask remote nodes to ping us on our server socket to see if we have the port open
    const firewalled = this.firewalled && (await this._checkIfFirewalled(natSampler))
    if (firewalled) return false

    this.firewalled = this.io.firewalled = false

    // incase it's called in parallel for some reason, or if our nat status somehow changed
    if (!this.ephemeral || host !== this._nat.host || port !== this._nat.port) return false
    // if the firewall probe returned a different host / non consistent port, bail as well
    if (natSampler.host !== host || natSampler.port === 0) return false

    const id = peer.id(natSampler.host, natSampler.port)

    if (!onlyFirewall) {
      this.ephemeral = this.io.ephemeral = false
    }

    if (natSampler !== this._nat) {
      const prevHost = this._nat.host
      const prevPort = this._nat.port

      this._nonePersistentSamples = []
      this._nat = natSampler

      if (prevHost !== this._nat.host || prevPort !== this._nat.port) {
        this.emit('nat-update', this._nat.host, this._nat.port)
      }
    }

    // TODO: we should make this a bit more defensive in terms of using more
    // resources to make sure that the new routing table contains as many alive nodes
    // as possible, vs blindly copying them over...

    // all good! copy over the old routing table to the new one
    if (!b4a.equals(this.table.id, id)) {
      const nodes = this.table.toArray()

      this.table = this.io.table = new Table(id)

      for (const node of nodes) {
        if (b4a.equals(node.id, id)) continue
        if (!this.table.add(node)) this.nodes.remove(node)
      }

      this.table.on('row', this._onrow)

      // we need to rebootstrap/refresh since we updated our id
      if (this.bootstrapped) this.refresh()
    }

    if (!this.ephemeral) {
      this.emit('persistent')
    }

    return true
  }

  async *_resolveBootstrapNodes() {
    for (let { host, port } of this.bootstrapNodes) {
      let doLookup = false

      if (host.indexOf('@') === -1) {
        doLookup = true
      } else {
        const [suggestedIP, fallbackHost] = host.split('@')
        try {
          await this.ping({ host: suggestedIP, port })
          host = suggestedIP
        } catch {
          host = fallbackHost
          doLookup = true
        }
      }

      if (doLookup) {
        try {
          host = UDX.isIPv4(host) ? host : (await this.udx.lookup(host, { family: 4 })).host
        } catch {
          continue
        }
      }

      yield {
        id: peer.id(host, port),
        host,
        port
      }
    }
  }

  async _addBootstrapNodes(nodes) {
    for await (const node of this._resolveBootstrapNodes()) {
      nodes.push(node)
    }
  }

  async _checkIfFirewalled(natSampler = new NatSampler()) {
    const nodes = []
    for (let node = this.nodes.latest; node && nodes.length < 5; node = node.prev) {
      nodes.push(node)
    }

    if (nodes.length < 5) await this._addBootstrapNodes(nodes)
    // if no nodes are available, including bootstrappers - bail
    if (nodes.length === 0) return true

    const hosts = new Set()
    const value = b4a.allocUnsafe(2)

    c.uint16.encode({ start: 0, end: 2, buffer: value }, this.io.serverSocket.address().port)

    // double check they actually came on the server socket...
    this.io.serverSocket.on('message', onmessage)

    const pongs = await requestAll(this, true, PING_NAT, value, nodes)

    let count = 0
    for (const res of pongs) {
      if (hosts.has(res.from.host)) {
        count++
        natSampler.add(res.to.host, res.to.port)
      }
    }

    this.io.serverSocket.removeListener('message', onmessage)

    // if we got no or very few replies, consider it a fluke
    if (count < (nodes.length >= 5 ? 3 : 1)) return true

    // check that the server socket has the same ip as the client socket
    if (natSampler.host === null || this._nat.host !== natSampler.host) return true

    // check that the local port of the server socket is the same as the remote port
    // TODO: we might want a flag to opt out of this heuristic for specific remapped port servers
    if (natSampler.port === 0 || natSampler.port !== this.io.serverSocket.address().port) {
      return true
    }

    return false

    function onmessage(_, { host }) {
      hosts.add(host)
    }
  }

  _backgroundQuery(target) {
    this._refreshTicks = REFRESH_TICKS

    const backgroundCon = Math.min(this.concurrency, Math.max(2, (this.concurrency / 8) | 0))
    const q = new Query(this, target, true, FIND_NODE, null, {
      concurrency: backgroundCon
    })

    q.on('data', () => {
      // yield to other traffic
      q.concurrency = this.io.inflight.length < 3 ? this.concurrency : backgroundCon
    })

    return q
  }

  // called by health
  _online() {
    if (this.online && !this.degraded) return
    this.online = true
    this.degraded = false
    this.emit('network-update')
  }

  // called by health
  _degraded() {
    if (this.degraded) return
    this.online = true
    this.degraded = true
    this.emit('network-update')
  }

  // called by health
  _offline() {
    if (!this.online) return
    this.online = false
    this.degraded = false
    this.emit('network-update')
  }
}

DHT.OK = 0
DHT.ERROR_UNKNOWN_COMMAND = UNKNOWN_COMMAND
DHT.ERROR_INVALID_TOKEN = INVALID_TOKEN

module.exports = DHT

function localIP(udx, family = 4) {
  let host = null

  for (const n of udx.networkInterfaces()) {
    if (n.family !== family || n.internal) continue

    // mac really likes en0, mb a better way but this shouldnt be bad anywhere so return now
    if (n.name === 'en0') return n.host

    // otherwise pick the first non internal host (let the loop continue in case we see en0)
    if (host === null) host = n.host
  }

  return host || (family === 4 ? '127.0.0.1' : '::1')
}

function parseNode(s) {
  if (typeof s === 'object') return s
  if (typeof s === 'number') return { host: '127.0.0.1', port: s }
  const [host, port] = s.split(':')
  if (!port) throw new Error('Bootstrap node format is host:port')

  return {
    host,
    port: Number(port)
  }
}

function randomBytes(n) {
  const b = b4a.alloc(n)
  sodium.randombytes_buf(b)
  return b
}

function randomOffset(n) {
  return n - ((Math.random() * 0.5 * n) | 0)
}

function requestAll(dht, internal, command, value, nodes) {
  let missing = nodes.length
  const replies = []

  return new Promise((resolve) => {
    for (const node of nodes) {
      const req = dht._request(
        node,
        false,
        internal,
        command,
        null,
        value,
        null,
        onsuccess,
        onerror
      )
      if (!req) return resolve(replies)
    }

    function onsuccess(res) {
      replies.push(res)
      if (--missing === 0) resolve(replies)
    }

    function onerror() {
      if (--missing === 0) resolve(replies)
    }
  })
}

function noop() {}
exports.PING = 0
exports.PING_NAT = 1
exports.FIND_NODE = 2
exports.DOWN_HINT = 3
exports.DELAYED_PING = 4
module.exports = class DHTError extends Error {
  constructor(msg, code, fn = DHTError) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'DHTError'
  }

  static UNKNOWN_COMMAND = 1
  static INVALID_TOKEN = 2

  static REQUEST_TIMEOUT(msg = 'Request timed out') {
    return new DHTError(msg, 'REQUEST_TIMEOUT', DHTError.REQUEST_TIMEOUT)
  }

  static REQUEST_DESTROYED(msg = 'Request destroyed') {
    return new DHTError(msg, 'REQUEST_DESTROYED', DHTError.REQUEST_DESTROYED)
  }

  static IO_SUSPENDED(msg = 'I/O suspended') {
    return new DHTError(msg, 'IO_SUSPENDED', DHTError.IO_SUSPENDED)
  }
}
const MAX_HEALTH_WINDOW = 4
const OFFLINE_THRESHOLD = 2
const IDLE_THRESHOLD = 4
const DEGRADED_TIMEOUT_RATE_THRESHOLD = 0.5

module.exports = class NetworkHealth {
  constructor(dht) {
    this._dht = dht
    this._window = []
    this._head = -1
    this._offlineTicks = 0
    this._degradedTicks = 0
    this._healthyTicks = 0
    this.online = true
    this.degraded = false
  }

  get oldest() {
    return this._window[this._tail]
  }

  get previous() {
    return this._window[(this._head - 1 + MAX_HEALTH_WINDOW) % MAX_HEALTH_WINDOW]
  }

  get newest() {
    return this._window[this._head]
  }

  get responses() {
    if (!this.newest || !this.previous) return 0
    return this.newest.responses - this.previous.responses
  }

  get timeouts() {
    if (!this.newest || !this.previous) return 0
    return this.newest.timeouts - this.previous.timeouts
  }

  get timeoutsRate() {
    if (this.timeouts === 0) return 0
    return this.timeouts / (this.responses + this.timeouts)
  }

  get cold() {
    return this._window.length < MAX_HEALTH_WINDOW
  }

  get idle() {
    return this.responses + this.timeouts < IDLE_THRESHOLD
  }

  get stats() {
    return {
      online: this.online,
      degraded: this.degraded,
      cold: this.cold,
      idle: this.idle,
      responses: this.responses,
      timeouts: this.timeouts,
      timeoutsRate: this.timeoutsRate
    }
  }

  get _tail() {
    return (this._head + 1) % MAX_HEALTH_WINDOW
  }

  reset() {
    this._window = []
    this._head = -1
    this._offlineTicks = 0
    this._degradedTicks = 0
    this._healthyTicks = 0
    this.online = true
    this.degraded = false
    this._dht._online()
  }

  update() {
    // update counters before dropping oldest
    if (this.oldest?.degraded) this._degradedTicks--
    else if (this.oldest?.degraded === false) this._healthyTicks--

    // move window
    this._head = this._tail
    this._window[this._head] = {
      responses: this._dht.stats.requests.responses,
      timeouts: this._dht.stats.requests.timeouts
    }

    // skip state changes
    if (this.cold || this.idle) return

    // update newest
    this.newest.offline = this.responses === 0
    this.newest.degraded =
      !this.newest.offline && this.timeoutsRate > DEGRADED_TIMEOUT_RATE_THRESHOLD

    // update counters
    if (this.newest.offline) this._offlineTicks++
    else {
      this._offlineTicks = 0
      if (this.newest.degraded) this._degradedTicks++
      else this._healthyTicks++
    }

    // check online/offline
    if (!this.newest.offline) this.online = true
    else if (this._offlineTicks >= OFFLINE_THRESHOLD) this.online = false

    // check degraded
    if (!this.online || this._healthyTicks === MAX_HEALTH_WINDOW) this.degraded = false
    else if (this._degradedTicks === MAX_HEALTH_WINDOW) this.degraded = true

    // fire events
    if (this.online && !this.degraded) this._dht._online()
    else if (this.degraded) this._dht._degraded()
    else this._dht._offline()
  }
}
const FIFO = require('fast-fifo')
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const b4a = require('b4a')
const AdaptiveTimeout = require('adaptive-timeout')
const peer = require('./peer')
const { INVALID_TOKEN, REQUEST_TIMEOUT, REQUEST_DESTROYED, IO_SUSPENDED } = require('./errors')

const VERSION = 0b11
const RESPONSE_ID = (0b0001 << 4) | VERSION
const REQUEST_ID = (0b0000 << 4) | VERSION
const EMPTY_ARRAY = []
const MAX_WINDOW = 80

module.exports = class IO {
  constructor(
    table,
    udx,
    {
      maxWindow = MAX_WINDOW,
      port = 0,
      host = '0.0.0.0',
      anyPort = true,
      firewalled = true,
      onrequest,
      onresponse = noop,
      ontimeout = noop,
      adaptiveTimeout
    } = {}
  ) {
    this.table = table
    this.udx = udx
    this.inflight = []
    this.clientSocket = null
    this.serverSocket = null
    this.firewalled = firewalled !== false
    this.ephemeral = true
    this.congestion = new CongestionWindow(maxWindow)
    this.networkInterfaces = udx.watchNetworkInterfaces()
    this.suspended = false

    this.stats = {
      requests: {
        active: 0,
        total: 0,
        responses: 0,
        timeouts: 0,
        retries: 0
      },
      commands: [
        { tx: 0, rx: 0 }, // tx = transmitted, rx = received
        { tx: 0, rx: 0 },
        { tx: 0, rx: 0 },
        { tx: 0, rx: 0 }
      ]
    }

    this.onrequest = onrequest
    this.onresponse = onresponse
    this.ontimeout = ontimeout

    this._pending = new FIFO()
    this._rotateSecrets = 10
    this._tid = (Math.random() * 65536) | 0
    this._secrets = null
    this._drainInterval = null
    this._destroying = null
    this._binding = null

    // port can be a number or a range [start, to]
    this.portRange = port.length ? port : port === 0 ? [0, 0] : [port, port + 5]

    this._host = host
    this._anyPort = anyPort !== false
    this._boundServerPort = 0
    this._boundClientPort = 0

    this._adt = adaptiveTimeout ? new AdaptiveTimeout(adaptiveTimeout) : null
  }

  static DEFAULT_MAX_WINDOW = MAX_WINDOW

  onmessage(socket, buffer, { host, port }) {
    if (buffer.byteLength < 2 || !(port > 0 && port < 65536) || this.suspended === true) return

    const from = { id: null, host, port }
    const state = { start: 1, end: buffer.byteLength, buffer }
    const expectedSocket = this.firewalled ? this.clientSocket : this.serverSocket
    const external = socket !== expectedSocket

    if (buffer[0] === REQUEST_ID) {
      const req = Request.decode(this, socket, from, state)
      if (req === null) return
      if (
        req.token !== null &&
        !b4a.equals(req.token, this.token(req.from, 1)) &&
        !b4a.equals(req.token, this.token(req.from, 0))
      ) {
        req.error(INVALID_TOKEN, { token: true })
        return
      }
      this.onrequest(req, external)
      return
    }

    if (buffer[0] === RESPONSE_ID) {
      const res = decodeReply(from, state)
      if (res === null) return

      for (let i = 0; i < this.inflight.length; i++) {
        const req = this.inflight[i]
        if (req.tid !== res.tid) continue

        res.rtt = Date.now() - req._timestamp

        if (this._adt && req.sent <= 2) {
          this._adt.put(`${req.to.host}:${req.to.port}`, res.rtt)
        }

        if (i === this.inflight.length - 1) this.inflight.pop()
        else this.inflight[i] = this.inflight.pop()

        if (req.session) req.session._detach(req)

        // TODO: Auto retry here if errors.INVALID_TOKEN is returned?

        if (req._timeout) {
          clearTimeout(req._timeout)
          req._timeout = null
        }

        this.congestion.recv()

        if (req.internal && req.command < this.stats.commands.length) {
          this.stats.commands[req.command].rx++
        }

        this.stats.requests.active--
        this.stats.requests.responses++

        this.onresponse(res, external)
        req.onresponse(res, req)
        break
      }
    }
  }

  token(addr, i) {
    if (this._secrets === null) {
      const buf = b4a.alloc(64)
      this._secrets = [buf.subarray(0, 32), buf.subarray(32, 64)]
      sodium.randombytes_buf(this._secrets[0])
      sodium.randombytes_buf(this._secrets[1])
    }

    const token = b4a.allocUnsafe(32)
    sodium.crypto_generichash(token, b4a.from(addr.host), this._secrets[i])
    return token
  }

  async destroy() {
    if (this._destroying) return this._destroying
    this._destroying = this._destroy()
    return this._destroying
  }

  async _destroy() {
    // simplifies timing to await the bind here also, although it might be unneeded
    await this.bind()
    await this._clear(false)
  }

  async _clear(suspended) {
    if (this._drainInterval) {
      clearInterval(this._drainInterval)
      this._drainInterval = null
    }

    while (this.inflight.length) {
      const req = this.inflight.pop()
      if (req._timeout) clearTimeout(req._timeout)
      req._timeout = null
      req.destroyed = true

      if (req.session) req.session._detach(req)

      this.congestion.recv()
      this.stats.requests.active--

      req.onerror(suspended ? IO_SUSPENDED() : REQUEST_DESTROYED(), req)
    }

    await Promise.allSettled([this.serverSocket.close(), this.clientSocket.close()])

    this.networkInterfaces.destroy()
  }

  async suspend() {
    this.suspended = true
    await this._clear(true)

    this.congestion.clear()

    if (this._drainInterval) {
      clearInterval(this._drainInterval)
      this._drainInterval = null
    }
  }

  async _rebind(binding) {
    if (binding) await binding
    if (this._destroying) return this._destroying
    await this._bindSockets()
    this.networkInterfaces = this.udx.watchNetworkInterfaces()
  }

  resume() {
    this.suspended = false
    const binding = this._binding
    this._binding = this._rebind(binding)
    return this._binding
  }

  bind() {
    if (this._binding) return this._binding
    this._binding = this._bindSockets()
    return this._binding
  }

  async _bindSockets() {
    const serverSocket = this.udx.createSocket()

    const candidatePorts = []

    // Retrying previous port always has precedence
    if (this._boundServerPort) candidatePorts.push(this._boundServerPort)

    for (let i = this.portRange[0]; i < this.portRange[1]; i++) candidatePorts.push(i)

    for (const port of candidatePorts) {
      if (serverSocket.bound) break

      try {
        serverSocket.bind(port, this._host)
      } catch (err) {
        if (!this._anyPort) {
          await serverSocket.close()
          throw err
        }
      }
    }

    if (!serverSocket.bound) {
      try {
        serverSocket.bind(0, this._host)
      } catch (err) {
        await serverSocket.close()
        throw err
      }
    }

    const clientSocket = this.udx.createSocket()

    try {
      clientSocket.bind(this._boundClientPort || 0, this._host)
    } catch {
      try {
        clientSocket.bind(0, this._host)
      } catch (err) {
        await serverSocket.close()
        await clientSocket.close()
        throw err
      }
    }

    this._boundServerPort = serverSocket.address().port
    this._boundClientPort = clientSocket.address().port

    this.clientSocket = clientSocket
    this.serverSocket = serverSocket

    this.serverSocket.on('message', this.onmessage.bind(this, this.serverSocket))
    this.clientSocket.on('message', this.onmessage.bind(this, this.clientSocket))

    if (this._drainInterval === null) {
      this._drainInterval = setInterval(this._drain.bind(this), 750)
      if (this._drainInterval.unref) this._drainInterval.unref()
    }

    for (const req of this.inflight) {
      if (!req.socket) req.socket = this.firewalled ? this.clientSocket : this.serverSocket
      req.sent = 0
      req.send(false)
    }
  }

  _drain() {
    if (this._secrets !== null && --this._rotateSecrets === 0) {
      this._rotateSecrets = 10
      const tmp = this._secrets[0]
      this._secrets[0] = this._secrets[1]
      this._secrets[1] = tmp
      sodium.crypto_generichash(tmp, tmp)
    }

    this.congestion.drain()

    while (!this.congestion.isFull()) {
      const p = this._pending.shift()
      if (p === undefined) return
      p._sendNow()
    }
  }

  createRequest(to, token, internal, command, target, value, session, ttl) {
    if (this._destroying !== null) return null

    if (this._tid === 65536) this._tid = 0

    const tid = this._tid++
    const socket = this.firewalled ? this.clientSocket : this.serverSocket

    const req = new Request(
      this,
      socket,
      tid,
      null,
      to,
      token,
      internal,
      command,
      target,
      value,
      session,
      ttl || 0
    )
    this.inflight.push(req)
    if (session) session._attach(req)

    if (internal && command < this.stats.commands.length) {
      this.stats.commands[command].tx++
    }

    this.stats.requests.active++
    this.stats.requests.total++

    return req
  }
}

class Request {
  constructor(io, socket, tid, from, to, token, internal, command, target, value, session, ttl) {
    this.socket = socket
    this.tid = tid
    this.from = from
    this.to = to
    this.token = token
    this.command = command
    this.target = target
    this.value = value
    this.internal = internal
    this.session = session
    this.ttl = ttl
    this.index = -1
    this.sent = 0
    this.retries = 3
    this.destroyed = false
    this.timeout = 0

    this.oncycle = noop
    this.onerror = noop
    this.onresponse = noop

    this._buffer = null
    this._io = io
    this._timeout = null
    this._timestamp = Date.now()
  }

  static decode(io, socket, from, state) {
    try {
      const flags = c.uint.decode(state)
      const tid = c.uint16.decode(state)
      const to = peer.ipv4.decode(state)
      const id = flags & 1 ? c.fixed32.decode(state) : null
      const token = flags & 2 ? c.fixed32.decode(state) : null
      const internal = (flags & 4) !== 0
      const command = c.uint.decode(state)
      const target = flags & 8 ? c.fixed32.decode(state) : null
      const value = flags & 16 ? c.buffer.decode(state) : null

      if (id !== null) from.id = validateId(id, from)

      return new Request(
        io,
        socket,
        tid,
        from,
        to,
        token,
        internal,
        command,
        target,
        value,
        null,
        0
      )
    } catch {
      return null
    }
  }

  reply(value, opts = {}) {
    const socket = opts.socket || this.socket
    const to = opts.to || this.from
    this._sendReply(0, value || null, opts.token !== false, opts.closerNodes !== false, to, socket)
  }

  error(code, opts = {}) {
    const socket = opts.socket || this.socket
    const to = opts.to || this.from
    this._sendReply(code, null, opts.token === true, opts.closerNodes !== false, to, socket)
  }

  relay(value, to, opts) {
    const socket = (opts && opts.socket) || this.socket
    const buffer = this._encodeRequest(null, value, to, socket)
    socket.trySend(buffer, to.port, to.host, this.ttl)
  }

  send(force = false) {
    if (this.destroyed) return

    if (this.socket === null) return
    if (this._buffer === null) {
      this._buffer = this._encodeRequest(this.token, this.value, this.to, this.socket)
    }

    if (!force && this._io.congestion.isFull()) {
      this._io._pending.push(this)
      return
    }

    this._sendNow()
  }

  sendReply(error, value, token, hasCloserNodes) {
    this._sendReply(error, value, token, hasCloserNodes, this.from, this.socket, null)
  }

  _sendNow() {
    if (this.destroyed) return
    this.sent++
    this._io.congestion.send()
    this.socket.trySend(this._buffer, this.to.port, this.to.host, this.ttl)
    if (this._timeout) clearTimeout(this._timeout)
    const value =
      this.timeout || this._io._adt?.get(`${this.to.host}:${this.to.port}`, this.sent) || 1000
    this._timeout = setTimeout(oncycle, value, this)
  }

  destroy(err) {
    if (this.destroyed) return
    this.destroyed = true

    if (this._timeout) {
      clearTimeout(this._timeout)
      this._timeout = null
    }

    const i = this._io.inflight.indexOf(this)
    if (i === -1) return

    if (i === this._io.inflight.length - 1) this._io.inflight.pop()
    else this._io.inflight[i] = this._io.inflight.pop()

    if (this.session) this.session._detach(this)

    this._io.stats.requests.active--
    this._io.congestion.recv()

    this.onerror(err || REQUEST_DESTROYED(), this)
  }

  _sendReply(error, value, token, hasCloserNodes, from, socket) {
    if (socket === null || this.destroyed) return

    const id = this._io.ephemeral === false && socket === this._io.serverSocket
    const closerNodes =
      this.target !== null && hasCloserNodes ? this._io.table.closest(this.target) : EMPTY_ARRAY
    const state = { start: 0, end: 1 + 1 + 6 + 2, buffer: null } // (type | version) + flags + to + tid

    if (id) state.end += 32
    if (token) state.end += 32
    if (closerNodes.length > 0) peer.ipv4Array.preencode(state, closerNodes)
    if (error > 0) c.uint.preencode(state, error)
    if (value) c.buffer.preencode(state, value)

    state.buffer = b4a.allocUnsafe(state.end)
    state.buffer[state.start++] = RESPONSE_ID
    state.buffer[state.start++] =
      (id ? 1 : 0) |
      (token ? 2 : 0) |
      (closerNodes.length > 0 ? 4 : 0) |
      (error > 0 ? 8 : 0) |
      (value ? 16 : 0)

    c.uint16.encode(state, this.tid)
    peer.ipv4.encode(state, from)

    if (id) c.fixed32.encode(state, this._io.table.id)
    if (token) c.fixed32.encode(state, this._io.token(from, 1))
    if (closerNodes.length > 0) peer.ipv4Array.encode(state, closerNodes)
    if (error > 0) c.uint.encode(state, error)
    if (value) c.buffer.encode(state, value)

    socket.trySend(state.buffer, from.port, from.host, this.ttl)
  }

  _encodeRequest(token, value, to, socket) {
    const id = this._io.ephemeral === false && socket === this._io.serverSocket
    const state = { start: 0, end: 1 + 1 + 6 + 2, buffer: null } // (type | version) + flags + to + tid

    if (id) state.end += 32
    if (token) state.end += 32

    c.uint.preencode(state, this.command)

    if (this.target) state.end += 32
    if (value) c.buffer.preencode(state, value)

    state.buffer = b4a.allocUnsafe(state.end)
    state.buffer[state.start++] = REQUEST_ID
    state.buffer[state.start++] =
      (id ? 1 : 0) |
      (token ? 2 : 0) |
      (this.internal ? 4 : 0) |
      (this.target ? 8 : 0) |
      (value ? 16 : 0)

    c.uint16.encode(state, this.tid)
    peer.ipv4.encode(state, to)

    if (id) c.fixed32.encode(state, this._io.table.id)
    if (token) c.fixed32.encode(state, token)

    c.uint.encode(state, this.command)

    if (this.target) c.fixed32.encode(state, this.target)
    if (value) c.buffer.encode(state, value)

    return state.buffer
  }
}

class CongestionWindow {
  constructor(maxWindow) {
    this._i = 0
    this._total = 0
    this._window = [0, 0, 0, 0]
    this._maxWindow = maxWindow
  }

  clear() {
    this._i = 0
    this._total = 0
    this._window = [0, 0, 0, 0]
  }

  isFull() {
    return this._total >= 2 * this._maxWindow || this._window[this._i] >= this._maxWindow
  }

  recv() {
    if (this._window[this._i] > 0) {
      this._window[this._i]--
      this._total--
    }
  }

  send() {
    this._total++
    this._window[this._i]++
  }

  drain() {
    this._i = (this._i + 1) & 3
    this._total -= this._window[this._i]
    this._window[this._i] = 0 // clear oldest
  }
}

function noop() {}

function oncycle(req) {
  req._timeout = null
  req.oncycle(req)
  if (req.sent > req.retries) {
    req._io.stats.requests.timeouts++
    req.destroy(REQUEST_TIMEOUT())
    req._io.ontimeout(req)
  } else {
    req._io.stats.requests.retries++
    req.send()
  }
}

function decodeReply(from, state) {
  try {
    const flags = c.uint.decode(state)
    const tid = c.uint16.decode(state)
    const to = peer.ipv4.decode(state)
    const id = flags & 1 ? c.fixed32.decode(state) : null
    const token = flags & 2 ? c.fixed32.decode(state) : null
    const closerNodes = flags & 4 ? peer.ipv4Array.decode(state) : null
    const error = flags & 8 ? c.uint.decode(state) : 0
    const value = flags & 16 ? c.buffer.decode(state) : null

    if (id !== null) from.id = validateId(id, from)

    return { tid, rtt: 0, from, to, token, closerNodes, error, value }
  } catch {
    return null
  }
}

function validateId(id, from) {
  const expected = peer.id(from.host, from.port)
  return b4a.equals(expected, id) ? expected : null
}
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const net = require('compact-encoding-net')
const b4a = require('b4a')

const ipv4 = {
  ...net.ipv4Address,
  decode(state) {
    const ip = net.ipv4Address.decode(state)
    return {
      id: null, // populated by the callee
      host: ip.host,
      port: ip.port
    }
  }
}

module.exports = { id, ipv4, ipv4Array: c.array(ipv4) }

function id(host, port, out = b4a.allocUnsafeSlow(32)) {
  const addr = out.subarray(0, 6)
  ipv4.encode({ start: 0, end: 6, buffer: addr }, { host, port })
  sodium.crypto_generichash(out, addr)
  return out
}
const { Readable, getStreamError } = require('streamx')
const b4a = require('b4a')
const peer = require('./peer')
const { DOWN_HINT } = require('./commands')

const DONE = []
const DOWN = []

module.exports = class Query extends Readable {
  constructor(dht, target, internal, command, value, opts = {}) {
    super()

    dht.stats.queries.total++
    dht.stats.queries.active++

    this.force = !!opts.force
    this.dht = dht
    this.k = this.dht.table.k
    this.target = target
    this.internal = internal
    this.command = command
    this.value = value
    this.errors = 0
    this.successes = 0
    this.concurrency = opts.concurrency || this.dht.concurrency
    this.inflight = 0
    this.map = opts.map || defaultMap
    this.retries =
      opts.retries === 0 ? 0 : opts.retries || (this.internal && command === DOWN_HINT ? 3 : 5)
    this.closestReplies = []

    this._slow = 0
    this._slowdown = false
    this._seen = new Map()
    this._pending = []
    this._fromTable = false
    this._commit = opts.commit === true ? autoCommit : opts.commit || null
    this._commiting = false
    this._session = opts.session || dht.session()
    this._autoDestroySession = !opts.session
    this._onlyClosestNodes = false

    this._onvisitbound = this._onvisit.bind(this)
    this._onerrorbound = this._onerror.bind(this)
    this._oncyclebound = this._oncycle.bind(this)

    const nodes = opts.nodes || opts.closestNodes
    const replies = opts.replies || opts.closestReplies

    // add them reverse as we pop below
    if (nodes) {
      for (let i = nodes.length - 1; i >= 0; i--) {
        const node = nodes[i]
        this._addPending(
          {
            id: node.id || peer.id(node.host, node.port),
            host: node.host,
            port: node.port
          },
          null
        )
      }
    } else if (replies) {
      for (let i = replies.length - 1; i >= 0; i--) {
        this._addPending(replies[i].from, null)
      }
    }

    if (opts.onlyClosestNodes) this._onlyClosestNodes = true
  }

  get closestNodes() {
    const nodes = new Array(this.closestReplies.length)

    for (let i = 0; i < nodes.length; i++) {
      nodes[i] = this.closestReplies[i].from
    }

    return nodes
  }

  finished() {
    return new Promise((resolve, reject) => {
      if (this.destroyed) {
        const error = getStreamError(this)
        if (error) reject(error)
        else resolve()
        return
      }

      const self = this
      let error = null

      this.resume()
      this.on('error', onerror)
      this.on('close', onclose)

      function onclose() {
        self.removeListener('error', onerror)
        self.removeListener('close', onclose)
        if (error) reject(error)
        else resolve()
      }

      function onerror(err) {
        error = err
      }
    })
  }

  _addFromTable() {
    if (this._pending.length >= this.k) return
    this._fromTable = true

    const closest = this.dht.table.closest(this.target, this.k - this._pending.length)

    for (const node of closest) {
      this._addPending({ id: node.id, host: node.host, port: node.port }, null)
    }
  }

  async _open(cb) {
    this._addFromTable()
    if (this._pending.length >= this.k) return cb(null)

    for await (const node of this.dht._resolveBootstrapNodes()) {
      this._addPending(node, null)
    }

    cb(null)
  }

  _isCloser(id) {
    return (
      this.closestReplies.length < this.k ||
      this._compare(id, this.closestReplies[this.closestReplies.length - 1].from.id) < 0
    )
  }

  _addPending(node, ref) {
    if (this._onlyClosestNodes) return false

    const addr = node.host + ':' + node.port
    const refs = this._seen.get(addr)
    const isCloser = this._isCloser(node.id)

    if (refs === DONE) {
      return isCloser
    }

    if (refs === DOWN) {
      if (ref) this._downHint(ref, node)
      return isCloser
    }

    if (refs) {
      if (ref !== null) refs.push(ref)
      return isCloser
    }

    if (!isCloser) {
      return false
    }

    this._seen.set(addr, ref === null ? [] : [ref])
    this._pending.push(node)

    return true
  }

  _read(cb) {
    this._readMore()
    cb(null)
  }

  _readMore() {
    if (this.destroying || this._commiting) return

    const concurrency = (this._slowdown ? 3 : this.concurrency) + this._slow

    while (this.inflight < concurrency && this._pending.length > 0) {
      const next = this._pending.pop()
      if (next && next.id && !this._isCloser(next.id)) continue
      this._visit(next)
    }

    // if reusing closest nodes, slow down after the first readMore tick to allow
    // the closest node a chance to reply before going broad to question more
    if (!this._fromTable && this.successes === 0 && this.errors === 0) {
      this._slowdown = true
    }

    if (this._pending.length > 0) return

    // if no inflight OR all the queries we are waiting on are marked as slow and we have a full result.
    if (
      this.inflight === 0 ||
      (this._slow === this.inflight && this.closestReplies.length >= this.k)
    ) {
      // if more than 3/4 failed and we only used cached nodes, try again from the routing table
      if (!this._fromTable && this.successes < this.k / 4) {
        this._addFromTable()
        this._readMore()
        return
      }

      this._flush()
    }
  }

  _flush() {
    if (this._commiting) return
    this._commiting = true

    if (this._commit === null) {
      this.push(null)
      return
    }

    const p = []
    for (const m of this.closestReplies) p.push(this._commit(m, this.dht, this))
    this._endAfterCommit(p)
  }

  _endAfterCommit(ps) {
    if (!ps.length) {
      this.destroy(new Error('Too few nodes responded'))
      return
    }

    const self = this

    let pending = ps.length
    let success = 0

    for (const p of ps) p.then(ondone, onerror)

    function ondone() {
      success++
      if (--pending === 0) self.push(null)
    }

    function onerror(err) {
      if (--pending > 0) return
      if (success) self.push(null)
      else self.destroy(err)
    }
  }

  _dec(req) {
    if (req.oncycle === noop) {
      this._slow--
    } else {
      req.oncycle = noop
    }
    this.inflight--
  }

  _onvisit(m, req) {
    this._dec(req)

    const addr = req.to.host + ':' + req.to.port
    this._seen.set(addr, DONE)

    if (this._commiting) return

    if (m.error === 0) this.successes++
    else this.errors++

    if (m.error === 0 && m.from.id !== null && this._isCloser(m.from.id)) this._pushClosest(m)

    if (m.closerNodes !== null) {
      for (const node of m.closerNodes) {
        node.id = peer.id(node.host, node.port)
        if (this.dht._filterNode !== null && !this.dht._filterNode(node)) continue
        if (b4a.equals(node.id, this.dht.table.id)) continue
        // TODO: we could continue here instead of breaking to ensure that one of the nodes in the closer list
        // is later marked as DOWN that we gossip that back
        if (!this._addPending(node, m.from)) break
      }
    }

    if (!this._fromTable && this.successes + this.errors >= this.concurrency) {
      this._slowdown = false
    }

    if (m.error !== 0) {
      this._readMore()
      return
    }

    const data = this.map(m)
    if (!data || this.push(data) !== false) {
      this._readMore()
    }
  }

  _onerror(err, req) {
    const addr = req.to.host + ':' + req.to.port
    const refs = this._seen.get(addr)

    if (err.code === 'REQUEST_TIMEOUT') {
      this._seen.set(addr, DOWN)
      for (const node of refs) this._downHint(node, req.to)
    }

    this._dec(req)
    this.errors++
    this._readMore()
  }

  _oncycle(req) {
    req.oncycle = noop
    this._slow++
    this._readMore()
  }

  _downHint(node, down) {
    // Check rate limit
    if (
      this.dht._downHintsRateLimit !== -1 &&
      this.dht._downHintsSentPerTick >= this.dht._downHintsRateLimit
    ) {
      return null
    }

    this.dht._downHintsSentPerTick++

    const state = { start: 0, end: 6, buffer: b4a.allocUnsafe(6) }
    peer.ipv4.encode(state, down)
    this.dht._request(node, false, true, DOWN_HINT, null, state.buffer, this._session, noop, noop)
  }

  _pushClosest(m) {
    this.closestReplies.push(m)
    for (let i = this.closestReplies.length - 2; i >= 0; i--) {
      const prev = this.closestReplies[i]
      const cmp = this._compare(prev.from.id, m.from.id)
      // if sorted, done!
      if (cmp < 0) break
      // if dup, splice it out (rare)
      if (cmp === 0) {
        this.closestReplies.splice(i + 1, 1)
        break
      }
      // swap and continue down
      this.closestReplies[i + 1] = prev
      this.closestReplies[i] = m
    }
    if (this.closestReplies.length > this.k) this.closestReplies.pop()
  }

  _compare(a, b) {
    for (let i = 0; i < a.length; i++) {
      if (a[i] === b[i]) continue
      const t = this.target[i]
      return (t ^ a[i]) - (t ^ b[i])
    }
    return 0
  }

  _visit(to) {
    this.inflight++

    const req = this.dht._request(
      to,
      this.force,
      this.internal,
      this.command,
      this.target,
      this.value,
      this._session,
      this._onvisitbound,
      this._onerrorbound
    )
    if (req === null) {
      this.destroy(new Error('Node was destroyed'))
      return
    }
    req.retries = this.retries
    req.oncycle = this._oncyclebound
    if (this.force) req.retries = 0
  }

  _destroy(cb) {
    this.dht.stats.queries.active--
    if (this._autoDestroySession) this._session.destroy()
    cb(null)
  }
}

function autoCommit(reply, dht, query) {
  if (!reply.token) return Promise.reject(new Error('No token received for closest node'))
  return dht.request(
    {
      token: reply.token,
      target: query.target,
      command: query.command,
      value: query.value
    },
    reply.from
  )
}

function defaultMap(m) {
  return m
}

function noop() {}
module.exports = class Session {
  constructor(dht) {
    this.dht = dht
    this.inflight = []
  }

  _attach(req) {
    req.index = this.inflight.push(req) - 1
  }

  _detach(req) {
    const i = req.index
    if (i === -1) return
    req.index = -1

    if (i === this.inflight.length - 1) this.inflight.pop()
    else {
      const req = (this.inflight[i] = this.inflight.pop())
      req.index = i
    }
  }

  query({ target, command, value }, opts = {}) {
    return this.dht.query({ target, command, value }, { ...opts, session: this })
  }

  request({ token, command, target, value }, { host, port }, opts = {}) {
    return this.dht.request(
      { token, command, target, value },
      { host, port },
      { ...opts, session: this }
    )
  }

  ping({ host, port }, opts = {}) {
    return this.dht.ping({ host, port }, { ...opts, session: this })
  }

  destroy(err) {
    while (this.inflight.length) {
      const req = this.inflight[0]
      // prevent destroyed requests from contributing to congestion counts
      this.dht.io.congestion.recv()
      req.destroy(err)
    }
  }
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return uint24.decode(state) + 0x1000000 * uint32.decode(state)
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return uint32.decode(state) + 0x100000000 * uint32.decode(state)
  }
})

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "2.19.2",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    if (b.byteLength === 0) return null
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "dht-rpc",
  "version": "6.26.4",
  "description": "Make RPC calls over a Kademlia based DHT",
  "main": "index.js",
  "files": [
    "index.js",
    "lib/*.js"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "dependencies": {
    "adaptive-timeout": "^1.0.1",
    "b4a": "^1.6.1",
    "bare-events": "^2.2.0",
    "compact-encoding": "^2.11.0",
    "compact-encoding-net": "^1.2.0",
    "fast-fifo": "^1.1.0",
    "kademlia-routing-table": "^1.0.1",
    "nat-sampler": "^1.0.1",
    "sodium-universal": "^5.0.0",
    "streamx": "^2.13.2",
    "time-ordered-set": "^2.0.0",
    "udx-native": "^1.5.3"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "test-suspend": "^1.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "test": "npm run test:node && npm run test:bare",
    "test:bare": "brittle-bare --coverage test.js",
    "lint": "prettier --check . && lunte",
    "test:node": "brittle-node --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/dht-rpc.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/dht-rpc/issues"
  },
  "homepage": "https://github.com/holepunchto/dht-rpc#"
}
module.exports = require('bare-events')
{
  "name": "events-universal",
  "version": "1.0.1",
  "description": "Universal wrapper for the Node.js events module",
  "exports": {
    "./package": "./package.json",
    ".": {
      "bare": "./bare.js",
      "react-native": "./react-native.js",
      "default": "./default.js"
    }
  },
  "files": [
    "index.js",
    "default.js",
    "bare.js",
    "react-native.js"
  ],
  "scripts": {
    "test": "prettier . --check"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/events-universal.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/events-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/events-universal#readme",
  "dependencies": {
    "bare-events": "^2.7.0"
  },
  "devDependencies": {
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^1.0.0"
  }
}
module.exports = class FixedFIFO {
  constructor (hwm) {
    if (!(hwm > 0) || ((hwm - 1) & hwm) !== 0) throw new Error('Max size for a FixedFIFO should be a power of two')
    this.buffer = new Array(hwm)
    this.mask = hwm - 1
    this.top = 0
    this.btm = 0
    this.next = null
  }

  clear () {
    this.top = this.btm = 0
    this.next = null
    this.buffer.fill(undefined)
  }

  push (data) {
    if (this.buffer[this.top] !== undefined) return false
    this.buffer[this.top] = data
    this.top = (this.top + 1) & this.mask
    return true
  }

  shift () {
    const last = this.buffer[this.btm]
    if (last === undefined) return undefined
    this.buffer[this.btm] = undefined
    this.btm = (this.btm + 1) & this.mask
    return last
  }

  peek () {
    return this.buffer[this.btm]
  }

  isEmpty () {
    return this.buffer[this.btm] === undefined
  }
}
const FixedFIFO = require('./fixed-size')

module.exports = class FastFIFO {
  constructor (hwm) {
    this.hwm = hwm || 16
    this.head = new FixedFIFO(this.hwm)
    this.tail = this.head
    this.length = 0
  }

  clear () {
    this.head = this.tail
    this.head.clear()
    this.length = 0
  }

  push (val) {
    this.length++
    if (!this.head.push(val)) {
      const prev = this.head
      this.head = prev.next = new FixedFIFO(2 * this.head.buffer.length)
      this.head.push(val)
    }
  }

  shift () {
    if (this.length !== 0) this.length--
    const val = this.tail.shift()
    if (val === undefined && this.tail.next) {
      const next = this.tail.next
      this.tail.next = null
      this.tail = next
      return this.tail.shift()
    }

    return val
  }

  peek () {
    const val = this.tail.peek()
    if (val === undefined && this.tail.next) return this.tail.next.peek()
    return val
  }

  isEmpty () {
    return this.length === 0
  }
}
{
  "name": "fast-fifo",
  "version": "1.3.2",
  "description": "A fast fifo implementation similar to the one powering nextTick in Node.js core",
  "main": "index.js",
  "files": [
    "./index.js",
    "./fixed-size.js"
  ],
  "dependencies": {},
  "devDependencies": {
    "standard": "^17.1.0",
    "brittle": "^3.3.2"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/fast-fifo.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/fast-fifo/issues"
  },
  "homepage": "https://github.com/mafintosh/fast-fifo"
}
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const b4a = require('b4a')

// https://en.wikipedia.org/wiki/Merkle_tree#Second_preimage_attack
const LEAF_TYPE = b4a.from([0])
const PARENT_TYPE = b4a.from([1])
const ROOT_TYPE = b4a.from([2])

const HYPERCORE = b4a.from('hypercore')

exports.keyPair = function (seed) {
  // key pairs might stay around for a while, so better not to use a default slab to avoid retaining it completely
  const slab = b4a.allocUnsafeSlow(sodium.crypto_sign_PUBLICKEYBYTES + sodium.crypto_sign_SECRETKEYBYTES)
  const publicKey = slab.subarray(0, sodium.crypto_sign_PUBLICKEYBYTES)
  const secretKey = slab.subarray(sodium.crypto_sign_PUBLICKEYBYTES)

  if (seed) sodium.crypto_sign_seed_keypair(publicKey, secretKey, seed)
  else sodium.crypto_sign_keypair(publicKey, secretKey)

  return {
    publicKey,
    secretKey
  }
}

exports.validateKeyPair = function (keyPair) {
  const pk = b4a.allocUnsafe(sodium.crypto_sign_PUBLICKEYBYTES)
  sodium.crypto_sign_ed25519_sk_to_pk(pk, keyPair.secretKey)
  return b4a.equals(pk, keyPair.publicKey)
}

exports.sign = function (message, secretKey) {
  // Dedicated slab for the signature, to avoid retaining unneeded mem and for security
  const signature = b4a.allocUnsafeSlow(sodium.crypto_sign_BYTES)
  sodium.crypto_sign_detached(signature, message, secretKey)
  return signature
}

exports.verify = function (message, signature, publicKey) {
  if (signature.byteLength !== sodium.crypto_sign_BYTES) return false
  if (publicKey.byteLength !== sodium.crypto_sign_PUBLICKEYBYTES) return false
  return sodium.crypto_sign_verify_detached(signature, message, publicKey)
}

exports.encrypt = function (message, publicKey) {
  const ciphertext = b4a.alloc(message.byteLength + sodium.crypto_box_SEALBYTES)
  sodium.crypto_box_seal(ciphertext, message, publicKey)
  return ciphertext
}

exports.decrypt = function (ciphertext, keyPair) {
  if (ciphertext.byteLength < sodium.crypto_box_SEALBYTES) return null

  const plaintext = b4a.alloc(ciphertext.byteLength - sodium.crypto_box_SEALBYTES)

  if (!sodium.crypto_box_seal_open(plaintext, ciphertext, keyPair.publicKey, keyPair.secretKey)) {
    return null
  }

  return plaintext
}

exports.encryptionKeyPair = function (seed) {
  const publicKey = b4a.alloc(sodium.crypto_box_PUBLICKEYBYTES)
  const secretKey = b4a.alloc(sodium.crypto_box_SECRETKEYBYTES)

  if (seed) {
    sodium.crypto_box_seed_keypair(publicKey, secretKey, seed)
  } else {
    sodium.crypto_box_keypair(publicKey, secretKey)
  }

  return {
    publicKey,
    secretKey
  }
}

exports.data = function (data) {
  const out = b4a.allocUnsafe(32)

  sodium.crypto_generichash_batch(out, [
    LEAF_TYPE,
    c.encode(c.uint64, data.byteLength),
    data
  ])

  return out
}

exports.parent = function (a, b) {
  if (a.index > b.index) {
    const tmp = a
    a = b
    b = tmp
  }

  const out = b4a.allocUnsafe(32)

  sodium.crypto_generichash_batch(out, [
    PARENT_TYPE,
    c.encode(c.uint64, a.size + b.size),
    a.hash,
    b.hash
  ])

  return out
}

exports.tree = function (roots, out) {
  const buffers = new Array(3 * roots.length + 1)
  let j = 0

  buffers[j++] = ROOT_TYPE

  for (let i = 0; i < roots.length; i++) {
    const r = roots[i]
    buffers[j++] = r.hash
    buffers[j++] = c.encode(c.uint64, r.index)
    buffers[j++] = c.encode(c.uint64, r.size)
  }

  if (!out) out = b4a.allocUnsafe(32)
  sodium.crypto_generichash_batch(out, buffers)
  return out
}

exports.hash = function (data, out) {
  if (!out) out = b4a.allocUnsafe(32)
  if (!Array.isArray(data)) data = [data]

  sodium.crypto_generichash_batch(out, data)

  return out
}

exports.randomBytes = function (n) {
  const buf = b4a.allocUnsafe(n)
  sodium.randombytes_buf(buf)
  return buf
}

exports.discoveryKey = function (key) {
  if (!key || key.byteLength !== 32) throw new Error('Must pass a 32 byte buffer')
  // Discovery keys might stay around for a while, so better not to use slab memory (for better gc)
  const digest = b4a.allocUnsafeSlow(32)
  sodium.crypto_generichash(digest, HYPERCORE, key)
  return digest
}

if (sodium.sodium_free) {
  exports.free = function (secureBuf) {
    if (secureBuf.secure) sodium.sodium_free(secureBuf)
  }
} else {
  exports.free = function () {}
}

exports.namespace = function (name, count) {
  const ids = typeof count === 'number' ? range(count) : count

  // Namespaces are long-lived, so better to use a dedicated slab
  const buf = b4a.allocUnsafeSlow(32 * ids.length)

  const list = new Array(ids.length)

  // ns is emhemeral, so default slab
  const ns = b4a.allocUnsafe(33)
  sodium.crypto_generichash(ns.subarray(0, 32), typeof name === 'string' ? b4a.from(name) : name)

  for (let i = 0; i < list.length; i++) {
    list[i] = buf.subarray(32 * i, 32 * i + 32)
    ns[32] = ids[i]
    sodium.crypto_generichash(list[i], ns)
  }

  return list
}

function range (count) {
  const arr = new Array(count)
  for (let i = 0; i < count; i++) arr[i] = i
  return arr
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return uint24.decode(state) + 0x1000000 * uint32.decode(state)
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return uint32.decode(state) + 0x100000000 * uint32.decode(state)
  }
})

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "2.19.2",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    if (b.byteLength === 0) return null
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "hypercore-crypto",
  "version": "3.6.1",
  "description": "The crypto primitives used in hypercore, extracted into a separate module",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.6.6",
    "compact-encoding": "^2.15.0",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "brittle": "^3.5.0",
    "standard": "^17.1.0"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/hypercore-crypto.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/hypercore-crypto/issues"
  },
  "homepage": "https://github.com/mafintosh/hypercore-crypto"
}
const z32 = require('z32')
const b4a = require('b4a')

module.exports = {
  encode,
  decode,
  normalize,
  isValid
}

function encode (key) {
  if (!b4a.isBuffer(key)) throw new Error('Key must be a Buffer')
  if (key.byteLength !== 32) throw new Error('Key must be 32-bytes long')
  return z32.encode(key)
}

function decode (id) {
  if (b4a.isBuffer(id)) {
    if (id.byteLength !== 32) throw new Error('ID must be 32-bytes long')
    return id
  }
  if (typeof id === 'string') {
    if (id.startsWith('pear://')) id = id.slice(7).split('/')[0]
    if (id.length === 52) return z32.decode(id)
    if (id.length === 64) {
      const buf = b4a.from(id, 'hex')
      if (buf.byteLength === 32) return buf
    }
  }
  throw new Error('Invalid Hypercore key')
}

function normalize (any) {
  return encode(decode(any))
}

function isValid (any) {
  try {
    decode(any)
    return true
  } catch {
    return false
  }
}
{
  "name": "hypercore-id-encoding",
  "version": "1.3.0",
  "description": "Convert Hypercore keys to/from z-base32 or hex",
  "main": "index.js",
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.5.3",
    "z32": "^1.0.0"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "hypercore": "^10.0.0",
    "random-access-memory": "^6.0.0",
    "standard": "^17.1.0"
  },
  "license": "Apache-2.0",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/hypercore-id-encoding.git"
  },
  "keywords": [],
  "author": "",
  "bugs": {
    "url": "https://github.com/holepunchto/hypercore-id-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/hypercore-id-encoding#readme"
}
const c = require('compact-encoding')
const { getEncoding } = require('./spec/hyperschema')

const HyperdhtAddress = getEncoding('@hyperdht/address')

function decode(buf) {
  const addr = c.decode(HyperdhtAddress, buf)
  return addr
}

function encode(key, nodes) {
  return c.encode(HyperdhtAddress, { key, nodes })
}

module.exports = { decode, encode }
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return uint24.decode(state) + 0x1000000 * uint32.decode(state)
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return uint32.decode(state) + 0x100000000 * uint32.decode(state)
  }
})

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "2.19.2",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    if (b.byteLength === 0) return null
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "hyperdht-address",
  "version": "1.0.1",
  "description": "hyperdht-address",
  "main": "index.js",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    }
  },
  "files": [
    "package.json",
    "index.js",
    "index.d.ts",
    "spec"
  ],
  "devDependencies": {
    "b4a": "^1.8.0",
    "brittle": "^3.19.0",
    "lunte": "^1.2.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && lunte && brittle-bare test/index.js",
    "lint": "lunte"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/hyperdht-address.git"
  },
  "author": "Holepunch Inc",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/hyperdht-address/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperdht-address",
  "dependencies": {
    "compact-encoding": "^2.19.0",
    "hyperschema": "^1.20.1"
  }
}
// This file is autogenerated by the hyperschema compiler
// Schema Version: 2
/* eslint-disable camelcase */
/* eslint-disable quotes */
/* eslint-disable space-before-function-paren */

const { c } = require('hyperschema/runtime')

const VERSION = 2

// eslint-disable-next-line no-unused-vars
let version = VERSION

// @hyperdht/address.nodes
const encoding0_1 = c.array(c.ipv4Address)

// @hyperdht/address
const encoding0 = {
  preencode(state, m) {
    c.fixed32.preencode(state, m.key)
    state.end++ // max flag is 1 so always one byte

    if (version >= 2 && m.nodes) encoding0_1.preencode(state, m.nodes)
  },
  encode(state, m) {
    const flags = version >= 2 && m.nodes ? 1 : 0

    c.fixed32.encode(state, m.key)
    c.uint.encode(state, flags)

    if (version >= 2 && m.nodes) encoding0_1.encode(state, m.nodes)
  },
  decode(state) {
    const r0 = c.fixed32.decode(state)
    const flags = state.start < state.end ? c.uint.decode(state) : 0

    return {
      key: r0,
      nodes: version >= 2 && (flags & 1) !== 0 ? encoding0_1.decode(state) : null
    }
  }
}

function setVersion(v) {
  version = v
}

function encode(name, value, v = VERSION) {
  version = v
  return c.encode(getEncoding(name), value)
}

function decode(name, buffer, v = VERSION) {
  version = v
  return c.decode(getEncoding(name), buffer)
}

function getEnum(name) {
  switch (name) {
    default:
      throw new Error('Enum not found ' + name)
  }
}

function getEncoding(name) {
  switch (name) {
    case '@hyperdht/address':
      return encoding0
    default:
      throw new Error('Encoder not found ' + name)
  }
}

function getStruct(name, v = VERSION) {
  const enc = getEncoding(name)
  return {
    preencode(state, m) {
      version = v
      enc.preencode(state, m)
    },
    encode(state, m) {
      version = v
      enc.encode(state, m)
    },
    decode(state) {
      version = v
      return enc.decode(state)
    }
  }
}

const resolveStruct = getStruct // compat

module.exports = {
  resolveStruct,
  getStruct,
  getEnum,
  getEncoding,
  encode,
  decode,
  setVersion,
  version
}
const DHT = require('dht-rpc')
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const b4a = require('b4a')
const safetyCatch = require('safety-catch')
const m = require('./lib/messages')
const SocketPool = require('./lib/socket-pool')
const Persistent = require('./lib/persistent')
const Router = require('./lib/router')
const Cache = require('xache')
const Server = require('./lib/server')
const connect = require('./lib/connect')
const { FIREWALL, BOOTSTRAP_NODES, KNOWN_NODES, COMMANDS } = require('./lib/constants')
const { hash, createKeyPair } = require('./lib/crypto')
const RawStreamSet = require('./lib/raw-stream-set')
const ConnectionPool = require('./lib/connection-pool')
const { STREAM_NOT_CONNECTED } = require('./lib/errors')

const DEFAULTS = {
  ...DHT.DEFAULTS,
  connectionKeepAlive: 5000,
  randomPunchInterval: 20000
}

class HyperDHT extends DHT {
  constructor(opts = {}) {
    const port = opts.port || 49737
    const bootstrap = opts.bootstrap || BOOTSTRAP_NODES
    const nodes = opts.nodes || KNOWN_NODES

    super({ ...opts, port, bootstrap, nodes, filterNode })

    const { router, relayAddresses, persistent } = defaultCacheOpts(opts)

    this.defaultKeyPair = opts.keyPair || createKeyPair(opts.seed)
    this.listening = new Set()
    this.connectionKeepAlive =
      opts.connectionKeepAlive === false
        ? 0
        : opts.connectionKeepAlive || DEFAULTS.connectionKeepAlive

    // stats is inherited from dht-rpc so fwd the ones from there
    this.stats = {
      punches: { consistent: 0, random: 0, open: 0 },
      relaying: { attempts: 0, successes: 0, aborts: 0 },
      ...this.stats
    }
    this.rawStreams = new RawStreamSet(this)
    this.plugins = new Map()

    this._router = new Router(this, router)
    this._socketPool = new SocketPool(this, opts.host || '0.0.0.0')
    this._persistent = null
    this._validatedLocalAddresses = new Map()
    this._relayAddressesCache = new Cache(relayAddresses)

    this._deferRandomPunch = !!opts.deferRandomPunch
    this._lastRandomPunch = this._deferRandomPunch ? Date.now() : 0
    this._connectable = true
    this._randomPunchInterval = opts.randomPunchInterval || DEFAULTS.randomPunchInterval // min 20s between random punches...
    this._randomPunches = 0
    this._randomPunchLimit = 1 // set to one for extra safety for now

    this.once('persistent', () => {
      this._persistent = new Persistent(this, persistent)
      for (const plugin of this.plugins.values()) plugin.onpersistent()
    })

    this.on('network-change', () => {
      for (const server of this.listening) server.refresh()
    })

    this.on('network-update', () => {
      if (!this.online) return
      for (const server of this.listening) server.notifyOnline()
    })
  }

  static DEFAULTS = DEFAULTS

  connect(remotePublicKey, opts) {
    return connect(this, remotePublicKey, opts)
  }

  createServer(opts, onconnection) {
    if (typeof opts === 'function') return this.createServer({}, opts)
    if (opts && opts.onconnection) onconnection = opts.onconnection
    const s = new Server(this, opts)
    if (onconnection) s.on('connection', onconnection)
    return s
  }

  pool() {
    return new ConnectionPool(this)
  }

  async resume({ log = noop } = {}) {
    if (this._deferRandomPunch) this._lastRandomPunch = Date.now()
    await super.resume({ log })
    const resuming = []
    for (const server of this.listening) resuming.push(server.resume())
    log('Resuming hyperdht servers')
    await Promise.allSettled(resuming)
    log('Done, hyperdht fully resumed')
  }

  async suspend({ log = noop } = {}) {
    this._connectable = false // just so nothing gets connected during suspension
    const suspending = []
    for (const server of this.listening) suspending.push(server.suspend())
    log('Suspending all hyperdht servers')
    await Promise.allSettled(suspending)
    log('Done, clearing all raw streams')
    await this.rawStreams.clear()
    log('Done, suspending dht-rpc')
    await super.suspend({ log })
    log('Done, clearing raw streams again')
    await this.rawStreams.clear()
    log('Done, hyperdht fully suspended')
    this._connectable = true
  }

  async destroy({ force = false } = {}) {
    if (!force) {
      const closing = []
      for (const server of this.listening) closing.push(server.close())
      await Promise.allSettled(closing)
    }
    this._router.destroy()
    if (this._persistent) this._persistent.destroy()
    for (const plugin of this.plugins.values()) plugin.destroy()
    await this.rawStreams.clear()
    await this._socketPool.destroy()
    await super.destroy()
  }

  async validateLocalAddresses(addresses) {
    const list = []
    const socks = []
    const waiting = []

    for (const addr of addresses) {
      const { host } = addr

      if (this._validatedLocalAddresses.has(host)) {
        if (await this._validatedLocalAddresses.get(host)) {
          list.push(addr)
        }
        continue
      }

      const sock = this.udx.createSocket()
      try {
        sock.bind(0, host)
      } catch {
        this._validatedLocalAddresses.set(host, Promise.resolve(false))
        continue
      }

      socks.push(sock)

      // semi terrible heuristic until we proper fix local connections by racing them to the remote...
      const promise = new Promise((resolve) => {
        sock.on('message', () => resolve(true))
        setTimeout(() => resolve(false), 500)
        sock.trySend(b4a.alloc(1), sock.address().port, addr.host)
      })

      this._validatedLocalAddresses.set(host, promise)
      waiting.push(addr)
    }

    for (const addr of waiting) {
      const { host } = addr
      if (this._validatedLocalAddresses.has(host)) {
        if (await this._validatedLocalAddresses.get(host)) {
          list.push(addr)
        }
        continue
      }
    }

    for (const sock of socks) await sock.close()

    return list
  }

  findPeer(publicKey, opts = {}) {
    const target = opts.hash === false ? publicKey : hash(publicKey)
    opts = { ...opts, map: mapFindPeer }
    return this.query({ target, command: COMMANDS.FIND_PEER, value: null }, opts)
  }

  lookup(target, opts = {}) {
    opts = { ...opts, map: mapLookup }
    return this.query({ target, command: COMMANDS.LOOKUP, value: null }, opts)
  }

  lookupAndUnannounce(target, keyPair, opts = {}) {
    const unannounces = []
    const dht = this
    const userCommit = opts.commit || noop
    const signUnannounce = opts.signUnannounce || Persistent.signUnannounce

    if (this._persistent !== null) {
      // unlink self
      this._persistent.unannounce(target, keyPair.publicKey)
    }

    opts = { ...opts, map, commit }
    return this.query({ target, command: COMMANDS.LOOKUP, value: null }, opts)

    async function commit(reply, dht, query) {
      await Promise.all(unannounces) // can never fail, caught below
      return userCommit(reply, dht, query)
    }

    function map(reply) {
      const data = mapLookup(reply)

      if (!data || !data.token) return data

      let found = data.peers.length >= 20
      for (let i = 0; !found && i < data.peers.length; i++) {
        found = b4a.equals(data.peers[i].publicKey, keyPair.publicKey)
      }

      if (!found) return data

      if (!data.from.id) return data

      unannounces.push(
        dht
          ._requestUnannounce(keyPair, dht, target, data.token, data.from, signUnannounce)
          .catch(safetyCatch)
      )

      return data
    }
  }

  unannounce(target, keyPair, opts = {}) {
    return this.lookupAndUnannounce(target, keyPair, opts).finished()
  }

  announce(target, keyPair, relayAddresses, opts = {}) {
    const signAnnounce = opts.signAnnounce || Persistent.signAnnounce
    const bump = opts.bump || 0

    opts = { ...opts, commit }

    return opts.clear ? this.lookupAndUnannounce(target, keyPair, opts) : this.lookup(target, opts)

    function commit(reply, dht) {
      return dht._requestAnnounce(
        keyPair,
        dht,
        target,
        reply.token,
        reply.from,
        relayAddresses,
        signAnnounce,
        bump
      )
    }
  }

  async immutableGet(target, opts = {}) {
    opts = { ...opts, map: mapImmutable }

    const query = this.query({ target, command: COMMANDS.IMMUTABLE_GET, value: null }, opts)
    const check = b4a.allocUnsafe(32)

    for await (const node of query) {
      const { value } = node
      sodium.crypto_generichash(check, value)
      if (b4a.equals(check, target)) return node
    }

    return null
  }

  async immutablePut(value, opts = {}) {
    const target = b4a.allocUnsafe(32)
    sodium.crypto_generichash(target, value)

    opts = {
      ...opts,
      map: mapImmutable,
      commit(reply, dht) {
        return dht.request(
          { token: reply.token, target, command: COMMANDS.IMMUTABLE_PUT, value },
          reply.from
        )
      }
    }

    const query = this.query({ target, command: COMMANDS.IMMUTABLE_GET, value: null }, opts)
    await query.finished()

    return { hash: target, closestNodes: query.closestNodes }
  }

  async mutableGet(publicKey, opts = {}) {
    let refresh = opts.refresh || null
    let signed = null
    let result = null

    opts = { ...opts, map: mapMutable, commit: refresh ? commit : null }

    const target = b4a.allocUnsafe(32)
    sodium.crypto_generichash(target, publicKey)

    const userSeq = opts.seq || 0
    const query = this.query(
      { target, command: COMMANDS.MUTABLE_GET, value: c.encode(c.uint, userSeq) },
      opts
    )
    const latest = opts.latest !== false

    for await (const node of query) {
      if (result && node.seq <= result.seq) continue
      if (
        node.seq < userSeq ||
        !Persistent.verifyMutable(node.signature, node.seq, node.value, publicKey)
      )
        continue
      if (!latest) return node
      if (!result || node.seq > result.seq) result = node
    }

    return result

    function commit(reply, dht) {
      if (!signed && result && refresh) {
        if (refresh(result)) {
          signed = c.encode(m.mutablePutRequest, {
            publicKey,
            seq: result.seq,
            value: result.value,
            signature: result.signature
          })
        } else {
          refresh = null
        }
      }

      return signed
        ? dht.request(
            { token: reply.token, target, command: COMMANDS.MUTABLE_PUT, value: signed },
            reply.from
          )
        : Promise.resolve(null)
    }
  }

  async mutablePut(keyPair, value, opts = {}) {
    const signMutable = opts.signMutable || Persistent.signMutable

    const target = b4a.allocUnsafe(32)
    sodium.crypto_generichash(target, keyPair.publicKey)

    const seq = opts.seq || 0
    const signature = await signMutable(seq, value, keyPair)

    const signed = c.encode(m.mutablePutRequest, {
      publicKey: keyPair.publicKey,
      seq,
      value,
      signature
    })

    opts = {
      ...opts,
      map: mapMutable,
      commit(reply, dht) {
        return dht.request(
          { token: reply.token, target, command: COMMANDS.MUTABLE_PUT, value: signed },
          reply.from
        )
      }
    }

    // use seq = 0, for the query part here, as we don't care about the actual values
    const query = this.query(
      { target, command: COMMANDS.MUTABLE_GET, value: c.encode(c.uint, 0) },
      opts
    )
    await query.finished()

    return { publicKey: keyPair.publicKey, closestNodes: query.closestNodes, seq, signature }
  }

  onrequest(req) {
    switch (req.command) {
      case COMMANDS.PEER_HANDSHAKE: {
        this._router.onpeerhandshake(req)
        return true
      }
      case COMMANDS.PEER_HOLEPUNCH: {
        this._router.onpeerholepunch(req)
        return true
      }
    }

    if (this._persistent === null || this.id === null) return false

    switch (req.command) {
      case COMMANDS.FIND_PEER: {
        this._persistent.onfindpeer(req)
        return true
      }
      case COMMANDS.LOOKUP: {
        this._persistent.onlookup(req)
        return true
      }
      case COMMANDS.ANNOUNCE: {
        this._persistent.onannounce(req)
        return true
      }
      case COMMANDS.UNANNOUNCE: {
        this._persistent.onunannounce(req)
        return true
      }
      case COMMANDS.MUTABLE_PUT: {
        this._persistent.onmutableput(req)
        return true
      }
      case COMMANDS.MUTABLE_GET: {
        this._persistent.onmutableget(req)
        return true
      }
      case COMMANDS.IMMUTABLE_PUT: {
        this._persistent.onimmutableput(req)
        return true
      }
      case COMMANDS.IMMUTABLE_GET: {
        this._persistent.onimmutableget(req)
        return true
      }
      case COMMANDS.PLUGIN: {
        this._persistent.onplugin(req)
        return true
      }
    }

    return false
  }

  static keyPair(seed) {
    return createKeyPair(seed)
  }

  static hash(data) {
    return hash(data)
  }

  static connectRawStream(encryptedStream, rawStream, remoteId) {
    const stream = encryptedStream.rawStream

    if (!stream.connected) throw STREAM_NOT_CONNECTED()

    rawStream.connect(stream.socket, remoteId, stream.remotePort, stream.remoteHost)
  }

  createRawStream(opts) {
    return this.rawStreams.add(opts)
  }

  async _requestAnnounce(keyPair, dht, target, token, from, relayAddresses, sign, bump) {
    const ann = {
      peer: {
        publicKey: keyPair.publicKey,
        relayAddresses: relayAddresses || []
      },
      refresh: null,
      signature: null,
      bump
    }

    ann.signature = await sign(target, token, from.id, ann, keyPair)

    const value = c.encode(m.announce, ann)

    return dht.request(
      {
        token,
        target,
        command: COMMANDS.ANNOUNCE,
        value
      },
      from
    )
  }

  async _requestUnannounce(keyPair, dht, target, token, from, sign) {
    const unann = {
      peer: {
        publicKey: keyPair.publicKey,
        relayAddresses: []
      },
      signature: null
    }

    unann.signature = await sign(target, token, from.id, unann, keyPair)

    const value = c.encode(m.announce, unann)

    return dht.request(
      {
        token,
        target,
        command: COMMANDS.UNANNOUNCE,
        value
      },
      from
    )
  }

  register(name, plugin) {
    this.plugins.set(name, plugin)
    plugin.onregister(this)
  }
}

HyperDHT.BOOTSTRAP = BOOTSTRAP_NODES
HyperDHT.FIREWALL = FIREWALL

module.exports = HyperDHT

function mapLookup(node) {
  if (!node.value) return null

  try {
    const l = c.decode(m.lookupRawReply, node.value)

    return {
      token: node.token,
      from: node.from,
      to: node.to,
      peers: l.peers,
      bump: l.bump
    }
  } catch {
    return null
  }
}

function mapFindPeer(node) {
  if (!node.value) return null

  try {
    return {
      token: node.token,
      from: node.from,
      to: node.to,
      peer: c.decode(m.peer, node.value)
    }
  } catch {
    return null
  }
}

function mapImmutable(node) {
  if (!node.value) return null

  return {
    token: node.token,
    from: node.from,
    to: node.to,
    value: node.value
  }
}

function mapMutable(node) {
  if (!node.value) return null

  try {
    const { seq, value, signature } = c.decode(m.mutableGetResponse, node.value)

    return {
      token: node.token,
      from: node.from,
      to: node.to,
      seq,
      value,
      signature
    }
  } catch {
    return null
  }
}

function noop() {}

function filterNode(node) {
  // always skip these testnet nodes that got mixed in by accident, until they get updated
  return (
    !(node.port === 49738 && (node.host === '134.209.28.98' || node.host === '167.99.142.185')) &&
    !(node.port === 9400 && node.host === '35.233.47.252') &&
    !(node.host === '150.136.142.116')
  )
}

const defaultMaxSize = 65536
const defaultMaxAge = 20 * 60 * 1000 // 20 minutes

function defaultCacheOpts(opts) {
  const maxSize = opts.maxSize || defaultMaxSize
  const maxAge = opts.maxAge || defaultMaxAge

  return {
    router: {
      forwards: { maxSize, maxAge }
    },
    relayAddresses: { maxSize: Math.min(maxSize, 512), maxAge: 0 },
    persistent: {
      records: { maxSize, maxAge },
      refreshes: { maxSize, maxAge },
      mutables: {
        maxSize: (maxSize / 2) | 0,
        maxAge: opts.maxAge || 48 * 60 * 60 * 1000 // 48 hours
      },
      immutables: {
        maxSize: (maxSize / 2) | 0,
        maxAge: opts.maxAge || 48 * 60 * 60 * 1000 // 48 hours
      },
      bumps: { maxSize, maxAge }
    }
  }
}
const safetyCatch = require('safety-catch')
const c = require('compact-encoding')
const Signal = require('signal-promise')
const { encodeUnslab } = require('./encode')
const Sleeper = require('./sleeper')
const m = require('./messages')
const Persistent = require('./persistent')
const { COMMANDS } = require('./constants')

const MIN_ACTIVE = 3

module.exports = class Announcer {
  constructor(dht, keyPair, target, opts = {}) {
    this.dht = dht
    this.keyPair = keyPair
    this.target = target
    this.relays = []
    this.relayAddresses = []
    this.stopped = false
    this.suspended = false
    this.record = encodeUnslab(m.peer, { publicKey: keyPair.publicKey, relayAddresses: [] })
    this.online = new Signal()

    this._refreshing = false
    this._closestNodes = null
    this._active = null
    this._sleeper = new Sleeper()
    this._resumed = new Signal()
    this._signAnnounce = opts.signAnnounce || Persistent.signAnnounce
    this._signUnannounce = opts.signUnannounce || Persistent.signUnannounce
    this._updating = null
    this._activeQuery = null
    this._unannouncing = null

    this._serverRelays = [new Map(), new Map(), new Map()]
  }

  isRelay(addr) {
    const id = addr.host + ':' + addr.port
    const [a, b, c] = this._serverRelays
    return a.has(id) || b.has(id) || c.has(id)
  }

  async suspend({ log = noop } = {}) {
    if (this.suspended) return
    this.suspended = true

    log('Suspending announcer')

    // Suspend has its own sleep logic
    // so we don't want to hang on this one
    this.online.notify()

    if (this._activeQuery) this._activeQuery.destroy()

    this._sleeper.resume()
    if (this._updating) await this._updating
    log('Suspending announcer (post update)')

    if (this.suspended === false || this.stopped) return

    log('Suspending announcer (pre unannounce)')
    await this._unannounceCurrent()
    log('Suspending announcer (post unannounce)')
  }

  resume() {
    if (!this.suspended) return
    this.suspended = false

    this.refresh()
    this._sleeper.resume()
    this._resumed.notify()
  }

  refresh() {
    if (this.stopped) return
    this._refreshing = true
  }

  async start() {
    if (this.stopped) return
    this._active = this._runUpdate()
    await this._active
    if (this.stopped) return
    this._active = this._background()
  }

  async stop() {
    this.stopped = true
    this.online.notify() // Break out of the _background loop if we're offline
    this._sleeper.resume()
    this._resumed.notify()
    await this._active
    await this._unannounceCurrent()
  }

  async _unannounceCurrent() {
    while (this._unannouncing !== null) await this._unannouncing
    const un = (this._unannouncing = this._unannounceAll(this._serverRelays[2].values()))
    await this._unannouncing
    if (un === this._unannouncing) this._unannouncing = null
  }

  async _background() {
    while (!this.dht.destroyed && !this.stopped) {
      try {
        this._refreshing = false

        // ~5min +-
        for (let i = 0; i < 100 && !this.stopped && !this._refreshing && !this.suspended; i++) {
          const pings = []

          for (const node of this._serverRelays[2].values()) {
            pings.push(this.dht.ping(node))
          }

          const active = await resolved(pings)
          if (active < Math.min(pings.length, MIN_ACTIVE)) {
            this.refresh() // we lost too many relay nodes, retry all
          }

          if (this.stopped) return

          if (!this.suspended && !this._refreshing) await this._sleeper.pause(3000)
        }

        while (!this.stopped && this.suspended) await this._resumed.wait()

        if (!this.stopped) await this._runUpdate()

        while (!this.dht.online && !this.stopped && !this.suspended) {
          // Being offline can make _background repeat very quickly
          // So wait until we're back online
          await this.online.wait()
        }
      } catch (err) {
        safetyCatch(err)
      }
    }
  }

  async _runUpdate() {
    this._updating = this._update()
    await this._updating
    this._updating = null
  }

  async _update() {
    while (this._unannouncing) await this._unannouncing

    this._cycle()

    const q = (this._activeQuery = this.dht.findPeer(this.target, {
      hash: false,
      nodes: this._closestNodes
    }))

    try {
      await q.finished()
    } catch {
      // ignore failures...
    }

    this._activeQuery = null

    if (this.stopped || this.suspended) return

    const ann = []
    const replies = pickBest(q.closestReplies)

    const relays = []
    const relayAddresses = []

    if (!this.dht.firewalled) {
      const addr = this.dht.remoteAddress()
      if (addr) relayAddresses.push(addr)
    }

    for (const msg of replies) {
      ann.push(this._commit(msg, relays, relayAddresses))
    }

    await Promise.allSettled(ann)
    if (this.stopped || this.suspended) return

    this._closestNodes = q.closestNodes
    this.relays = relays
    this.relayAddresses = relayAddresses

    const removed = []
    for (const [key, value] of this._serverRelays[1]) {
      if (!this._serverRelays[2].has(key)) removed.push(value)
    }

    await this._unannounceAll(removed)
  }

  _unannounceAll(relays) {
    const unann = []
    for (const r of relays) unann.push(this._unannounce(r))
    return Promise.allSettled(unann)
  }

  async _unannounce(to) {
    const unann = {
      peer: {
        publicKey: this.keyPair.publicKey,
        relayAddresses: []
      },
      refresh: null,
      signature: null
    }

    const { from, token, value } = await this.dht.request(
      {
        token: null,
        command: COMMANDS.FIND_PEER,
        target: this.target,
        value: null
      },
      to
    )

    if (!token || !from.id || !value) return

    unann.signature = await this._signUnannounce(this.target, token, from.id, unann, this.keyPair)

    await this.dht.request(
      {
        token,
        command: COMMANDS.UNANNOUNCE,
        target: this.target,
        value: c.encode(m.announce, unann)
      },
      to
    )
  }

  async _commit(msg, relays, relayAddresses) {
    const ann = {
      peer: {
        publicKey: this.keyPair.publicKey,
        relayAddresses: []
      },
      refresh: null,
      signature: null
    }

    ann.signature = await this._signAnnounce(this.target, msg.token, msg.from.id, ann, this.keyPair)

    const res = await this.dht.request(
      {
        token: msg.token,
        command: COMMANDS.ANNOUNCE,
        target: this.target,
        value: c.encode(m.announce, ann)
      },
      msg.from
    )

    if (res.error !== 0) return

    if (relayAddresses.length < 3) relayAddresses.push({ host: msg.from.host, port: msg.from.port })
    relays.push({ relayAddress: msg.from, peerAddress: msg.to })

    this._serverRelays[2].set(msg.from.host + ':' + msg.from.port, msg.from)
  }

  _cycle() {
    const tmp = this._serverRelays[0]
    this._serverRelays[0] = this._serverRelays[1]
    this._serverRelays[1] = this._serverRelays[2]
    this._serverRelays[2] = tmp
    tmp.clear()
  }
}

function resolved(ps) {
  let replied = 0
  let ticks = ps.length + 1

  return new Promise((resolve) => {
    for (const p of ps) p.then(push, tick)
    tick()

    function push(v) {
      replied++
      tick()
    }

    function tick() {
      if (--ticks === 0) resolve(replied)
    }
  })
}

function pickBest(replies) {
  // TODO: pick the ones closest to us RTT wise
  return replies.slice(0, 3)
}

function noop() {}
const NoiseSecretStream = require('@hyperswarm/secret-stream')
const b4a = require('b4a')
const relay = require('blind-relay')
const { isReserved, isBogon } = require('bogon')
const safetyCatch = require('safety-catch')
const unslab = require('unslab')
const Semaphore = require('./semaphore')
const NoiseWrap = require('./noise-wrap')
const SecurePayload = require('./secure-payload')
const Holepuncher = require('./holepuncher')
const Sleeper = require('./sleeper')
const { FIREWALL, ERROR } = require('./constants')
const { unslabbedHash } = require('./crypto')
const {
  CANNOT_HOLEPUNCH,
  HANDSHAKE_INVALID,
  HOLEPUNCH_ABORTED,
  HOLEPUNCH_INVALID,
  HOLEPUNCH_PROBE_TIMEOUT,
  HOLEPUNCH_DOUBLE_RANDOMIZED_NATS,
  PEER_CONNECTION_FAILED,
  PEER_NOT_FOUND,
  REMOTE_ABORTED,
  REMOTE_NOT_HOLEPUNCHABLE,
  REMOTE_NOT_HOLEPUNCHING,
  SERVER_ERROR,
  SERVER_INCOMPATIBLE,
  RELAY_ABORTED,
  SUSPENDED
} = require('./errors')
const { decode } = require('hypercore-id-encoding')
const HyperDHTAddress = require('hyperdht-address')

module.exports = function connect(dht, publicKey, opts = {}) {
  const pool = opts.pool || null

  const { key, nodes: providedNodes } = HyperDHTAddress.decode(
    b4a.isBuffer(publicKey) ? publicKey : decode(publicKey)
  )
  publicKey = key

  if (pool && pool.has(publicKey)) return pool.get(publicKey)

  publicKey = unslab(publicKey)

  opts.relayAddresses = opts.relayAddresses || providedNodes || []
  const keyPair = opts.keyPair || dht.defaultKeyPair
  const relayThrough = selectRelay(opts.relayThrough || null)
  const encryptedSocket = (opts.createSecretStream || defaultCreateSecretStream)(true, null, {
    publicKey: keyPair.publicKey,
    remotePublicKey: publicKey,
    autoStart: false,
    keepAlive: dht.connectionKeepAlive
  })

  // in case a socket is made during suspended state, destroy it immediately
  if (dht.suspended || !dht._connectable) {
    encryptedSocket.destroy(SUSPENDED())
    return encryptedSocket
  }

  if (pool) pool._attachStream(encryptedSocket, false)

  const id = b4a.toString(publicKey, 'hex')
  const c = {
    id,
    dht,
    session: dht.session(),
    relayAddresses: opts.relayAddresses,
    remoteRelayAddresses: [],
    pool,
    round: 0,
    target: unslabbedHash(publicKey),
    remotePublicKey: publicKey,
    reusableSocket: !!opts.reusableSocket,
    handshake: (opts.createHandshake || defaultCreateHandshake)(keyPair, publicKey),
    request: null,
    requesting: false,
    lan: opts.localConnection !== false,
    firewall: FIREWALL.UNKNOWN,
    rawStream: dht.createRawStream({ framed: true, firewall }),
    connect: null,
    query: null,
    puncher: null,
    payload: null,
    passiveConnectTimeout: null,
    serverSocket: null,
    serverAddress: null,
    onsocket: null,
    sleeper: new Sleeper(),
    encryptedSocket,

    // Relay state
    relayTimeout: null,
    relayThrough,
    relayToken: relayThrough ? relay.token() : null,
    relaySocket: null,
    relayClient: null,
    relayPaired: false,
    relayKeepAlive: opts.relayKeepAlive || 5000
  }

  // If the raw stream receives an error signal pre connect (ie from the firewall hook), make sure
  // to forward that to the encrypted socket for proper teardown
  c.rawStream.on('error', autoDestroy)
  c.rawStream.once('connect', () => {
    c.rawStream.removeListener('error', autoDestroy)
  })

  encryptedSocket.on('close', function () {
    if (c.passiveConnectTimeout) clearPassiveConnectTimeout(c)
    if (c.query) c.query.destroy()
    if (c.puncher) c.puncher.destroy()
    if (c.rawStream) c.rawStream.destroy()
    c.session.destroy()
    c.sleeper.resume()
  })

  // Safe to run in the background - never throws
  if (dht.suspended) encryptedSocket.destroy(SUSPENDED())
  else connectAndHolepunch(c, opts)

  return encryptedSocket

  function autoDestroy(err) {
    maybeDestroyEncryptedSocket(c, err)
  }

  function firewall(socket, port, host) {
    // Check if the traffic originated from the socket on which we're expecting relay traffic. If so,
    // we haven't hole punched yet and the other side is just sending us traffic through the relay.
    if (c.relaySocket && isRelay(c.relaySocket, socket, port, host)) {
      return false
    }

    if (c.onsocket) {
      c.onsocket(socket, port, host)
    } else {
      c.serverSocket = socket
      c.serverAddress = { port, host }
    }
    return false
  }
}

function isDone(c) {
  // we are destroying or the puncher is connected - done
  if (c.encryptedSocket.destroying || !!(c.puncher && c.puncher.connected)) {
    return true
  }
  // not destroying, but no raw stream - def not done
  if (c.encryptedSocket.rawStream === null) {
    return false
  }
  // we are relayed, but the puncher is not done yet
  if (c.relaySocket && !!(c.puncher && !c.puncher.connected && !c.puncher.destroyed)) {
    return false
  }
  // we are done
  return true
}

async function retryRoute(c, route) {
  const ref = c.dht._socketPool.lookup(route.socket)

  if (!ref) {
    if (route.socket === c.dht.socket) {
      await connectThroughNode(c, route.address, c.dht.socket)
    }
    return
  }

  ref.active()

  try {
    await connectThroughNode(c, route.address, route.socket)
  } catch {
    // if error, just ignore, and continue through the existing strat
  }

  ref.inactive()
}

async function connectAndHolepunch(c, opts) {
  const route = c.reusableSocket ? c.dht._socketPool.routes.get(c.remotePublicKey) : null

  if (route) {
    await retryRoute(c, route)
    if (isDone(c)) return
  }

  await findAndConnect(c, opts)
  if (isDone(c)) return

  if (!c.connect) {
    // TODO: just a quick fix for now, should retry prob
    maybeDestroyEncryptedSocket(c, HANDSHAKE_INVALID())
    return
  }

  await holepunch(c, opts)
}

function getFirstRemoteAddress(addrs, serverAddress) {
  for (const addr of addrs) {
    if (isBogon(addr.host)) continue
    return addr
  }

  return serverAddress
}

async function holepunch(c, opts) {
  let { relayAddress, serverAddress, clientAddress, payload } = c.connect

  const remoteHolepunchable = !!(payload.holepunch && payload.holepunch.relays.length)

  const relayed = diffAddress(serverAddress, relayAddress)

  if (payload.firewall === FIREWALL.OPEN || (relayed && !remoteHolepunchable)) {
    const addr = getFirstRemoteAddress(payload.addresses4, serverAddress)
    if (addr) {
      const socket = c.dht.socket
      c.dht.stats.punches.open++
      c.onsocket(socket, addr.port, addr.host)
      return
    }
    // TODO: check all addresses also obvs
  }

  const onabort = () => {
    c.session.destroy()
    maybeDestroyEncryptedSocket(c, HOLEPUNCH_ABORTED())
  }

  if (c.firewall === FIREWALL.OPEN) {
    c.passiveConnectTimeout = setTimeout(onabort, 10000)
    return
  }

  // TODO: would be better to just try local addrs in the background whilst continuing with other strategies...
  if (c.lan && relayed && clientAddress.host === serverAddress.host) {
    const serverAddresses = payload.addresses4.filter(onlyNonReserved)

    if (serverAddresses.length > 0) {
      const myAddresses = Holepuncher.localAddresses(c.dht.io.serverSocket)
      const addr = Holepuncher.matchAddress(myAddresses, serverAddresses) || serverAddresses[0]

      const socket = c.dht.io.serverSocket
      try {
        await c.dht.ping(addr)
      } catch {
        maybeDestroyEncryptedSocket(c, HOLEPUNCH_ABORTED())
        return
      }
      c.onsocket(socket, addr.port, addr.host)
      return
    }
  }

  if (!remoteHolepunchable) {
    maybeDestroyEncryptedSocket(c, CANNOT_HOLEPUNCH())
    return
  }

  c.puncher = new Holepuncher(c.dht, c.session, true, payload.firewall)

  c.puncher.onconnect = c.onsocket
  c.puncher.onabort = onabort

  const serverRelay = pickServerRelay(payload.holepunch.relays, relayAddress)

  // Begin holepunching!

  let probe
  try {
    probe = await probeRound(c, opts.fastOpen === false ? null : serverAddress, serverRelay, true)
  } catch (err) {
    destroyPuncher(c)
    // TODO: we should retry here with some of the other relays, bail for now
    maybeDestroyEncryptedSocket(c, err)
    return
  }

  if (isDone(c) || !probe) return
  const { token, peerAddress } = probe

  // If the relay the server picked is the same as the relay the client picked,
  // then we can use the peerAddress that round one indicates the server wants to use.
  // This shaves off a roundtrip if the server chose to reroll its socket due to some NAT
  // issue with the first one it picked (ie mobile nat inconsistencies...).
  // If the relays were different, then the server would not have a UDP session open on this address
  // to the client relay, which round2 uses.
  if (
    !diffAddress(serverRelay.relayAddress, relayAddress) &&
    diffAddress(serverAddress, peerAddress)
  ) {
    serverAddress = peerAddress
    await c.puncher.openSession(serverAddress)
    if (isDone(c)) return
  }

  // TODO: still continue here if a local connection might work, but then do not holepunch...
  if (
    opts.holepunch &&
    !opts.holepunch(
      c.puncher.remoteFirewall,
      c.puncher.nat.firewall,
      c.puncher.remoteAddresses,
      c.puncher.nat.addresses
    )
  ) {
    await abort(c, serverRelay, HOLEPUNCH_ABORTED('Client aborted holepunch'))
    return
  }

  try {
    await roundPunch(c, serverAddress, token, relayAddress, serverRelay, false)
  } catch (err) {
    destroyPuncher(c)
    // TODO: retry with another relay?
    maybeDestroyEncryptedSocket(c, err)
  }
}

async function connectThroughNodes(c, addresses, socket) {
  for (const address of addresses) {
    if (isDone(c) || c.connect) return

    c.remoteRelayAddresses.push(address)
    await connectThroughNode(c, address, socket)
  }
}

async function findAndConnect(c, opts) {
  let attempts = 0
  let relayAddresses =
    opts.relayAddresses && opts.relayAddresses.length ? opts.relayAddresses : null

  if (!relayAddresses) {
    const cachedRelayAddresses = c.dht._relayAddressesCache.get(c.id)
    if (cachedRelayAddresses) relayAddresses = cachedRelayAddresses
  }

  if (c.dht._persistent) {
    // check if we know the route ourself...
    const route = c.dht._router.get(c.target)
    if (route && route.relay !== null) {
      relayAddresses = [{ host: route.relay.host, port: route.relay.port }]
    }
  }

  // 2 is how many parallel connect attempts we want to do, we can make this configurable
  const preConnect = relayAddresses !== null && relayAddresses.length > 0
  const sem = new Semaphore(preConnect ? 3 : 2)
  const signal = sem.signal.bind(sem)
  const tries = relayAddresses !== null ? 2 : 1

  if (preConnect) {
    await sem.wait()
    connectThroughNodes(c, relayAddresses, null).then(signal, signal)
  }

  try {
    for (let i = 0; i < tries && !isDone(c) && !c.connect; i++) {
      c.query = c.dht.findPeer(c.target, {
        hash: false,
        session: c.session,
        nodes: relayAddresses,
        retries: 3
      })

      for await (const data of c.query) {
        await sem.wait()
        if (isDone(c)) return

        if (c.connect) {
          sem.signal()
          break
        }

        // Skip node already run via preConnect
        if (preConnect && relayAddresses && isRelayAddress(relayAddresses, data)) {
          sem.signal()
          continue
        }

        c.remoteRelayAddresses.push(data.from)
        attempts++
        connectThroughNode(c, data.from, null).then(signal, signal)
      }

      relayAddresses = null

      if (attempts > 0) await sem.flush()
    }

    c.query = null
    if (isDone(c)) return

    // flush the semaphore
    await sem.flush()
    if (isDone(c)) return
  } catch (err) {
    c.query = null
    maybeDestroyEncryptedSocket(c, err)
    return
  }

  if (!c.connect) {
    maybeDestroyEncryptedSocket(c, attempts ? PEER_CONNECTION_FAILED() : PEER_NOT_FOUND())
  }
}

async function connectThroughNode(c, address, socket) {
  if (!c.requesting) {
    // If we have a stable server address, send it over now
    const addr = c.dht.remoteAddress()
    const localAddrs = c.lan ? Holepuncher.localAddresses(c.dht.io.serverSocket) : null
    const addresses4 = []

    if (addr) addresses4.push(addr)
    if (localAddrs) addresses4.push(...localAddrs)

    c.firewall = addr ? FIREWALL.OPEN : FIREWALL.UNKNOWN
    c.requesting = true
    c.request = await c.handshake.send({
      error: ERROR.NONE,
      firewall: c.firewall,
      holepunch: null,
      addresses4,
      addresses6: [],
      udx: {
        reusableSocket: c.reusableSocket,
        id: c.rawStream.id,
        seq: 0
      },
      secretStream: {},
      relayThrough: c.relayThrough ? { publicKey: c.relayThrough, token: c.relayToken } : null
    })
    if (isDone(c)) return
  }

  const { serverAddress, clientAddress, relayed, noise } = await c.dht._router.peerHandshake(
    c.target,
    { noise: c.request, socket, session: c.session },
    address
  )
  if (isDone(c) || c.connect) return

  const payload = await c.handshake.recv(noise)
  if (isDone(c) || !payload) return

  if (payload.version !== 1) {
    maybeDestroyEncryptedSocket(c, SERVER_INCOMPATIBLE())
    return
  }
  if (payload.error !== ERROR.NONE) {
    maybeDestroyEncryptedSocket(c, SERVER_ERROR())
    return
  }
  if (!payload.udx) {
    maybeDestroyEncryptedSocket(c, SERVER_ERROR('Server did not send UDX data'))
    return
  }

  const hs = c.handshake.final()

  c.handshake = null
  c.request = null
  c.requesting = false
  c.connect = {
    relayed,
    relayAddress: address,
    clientAddress,
    serverAddress,
    payload
  }

  c.payload = new SecurePayload(hs.holepunchSecret)

  c.onsocket = function (socket, port, host) {
    if (c.rawStream === null) return // Already hole punched

    if (c.rawStream.connected) {
      const remoteChanging = c.rawStream.changeRemote(socket, c.connect.payload.udx.id, port, host)

      if (remoteChanging) remoteChanging.catch(safetyCatch)
    } else {
      // cache the relay addrs for a future reconnect, we prefer the remote one so they
      // can give us the correct ones from their pov
      if (payload.relayAddresses && payload.relayAddresses.length) {
        c.dht._relayAddressesCache.set(c.id, payload.relayAddresses)
      } else if (c.remoteRelayAddresses.length) {
        c.dht._relayAddressesCache.set(c.id, c.remoteRelayAddresses)
      }

      c.rawStream.connect(socket, c.connect.payload.udx.id, port, host)
      c.encryptedSocket.start(c.rawStream, { handshake: hs })
    }

    if (c.reusableSocket && payload.udx.reusableSocket) {
      c.dht._socketPool.routes.add(c.remotePublicKey, c.rawStream)
    }

    if (c.puncher) {
      c.puncher.onabort = noop
      c.puncher.destroy()
    }

    if (c.passiveConnectTimeout) {
      clearPassiveConnectTimeout(c)
    }

    c.rawStream = null
  }

  if (payload.relayThrough || c.relayThrough) {
    relayConnection(c, c.relayThrough, payload, hs)
  }

  if (c.serverSocket) {
    c.onsocket(c.serverSocket, c.serverAddress.port, c.serverAddress.host)
    return
  }

  if (!relayed) {
    c.onsocket(socket || c.dht.socket, address.port, address.host)
  }

  c.session.destroy()
}

async function updateHolepunch(c, peerAddress, relayAddr, payload) {
  const holepunch = await c.dht._router.peerHolepunch(
    c.target,
    {
      id: c.connect.payload.holepunch.id,
      payload: c.payload.encrypt(payload),
      peerAddress,
      socket: c.puncher.socket,
      session: c.session
    },
    relayAddr
  )

  if (isDone(c)) return null

  const remotePayload = c.payload.decrypt(holepunch.payload)
  if (!remotePayload) {
    throw HOLEPUNCH_INVALID()
  }

  const { error, firewall, punching, addresses, remoteToken } = remotePayload

  if (error === ERROR.TRY_LATER && c.relayToken && payload.punching) {
    return {
      tryLater: true,
      ...holepunch,
      payload: remotePayload
    }
  }

  if (error !== ERROR.NONE) {
    throw REMOTE_ABORTED('Remote aborted with error code ' + error)
  }

  const echoed = !!(remoteToken && payload.token && b4a.equals(remoteToken, payload.token))

  c.puncher.updateRemote({
    punching,
    firewall,
    addresses,
    verified: echoed ? peerAddress.host : null
  })

  return {
    tryLater: false,
    ...holepunch,
    payload: remotePayload
  }
}

async function probeRound(c, serverAddress, serverRelay, retry) {
  // Open a quick low ttl session against what we think is the server
  if (serverAddress) await c.puncher.openSession(serverAddress)

  if (isDone(c)) return null

  const reply = await updateHolepunch(c, serverRelay.peerAddress, serverRelay.relayAddress, {
    error: ERROR.NONE,
    firewall: c.puncher.nat.firewall,
    round: c.round++,
    connected: false,
    punching: false,
    addresses: c.puncher.nat.addresses,
    remoteAddress: serverAddress,
    token: null,
    remoteToken: null
  })

  if (isDone(c) || !reply) return null

  const { peerAddress } = reply
  const { address, token } = reply.payload

  c.puncher.nat.add(reply.to, reply.from)

  // Open another quick low ttl session against what the server says their address is,
  // if they haven't said they are random yet
  if (
    c.puncher.remoteFirewall < FIREWALL.RANDOM &&
    address &&
    address.host &&
    address.port &&
    diffAddress(address, serverAddress)
  ) {
    await c.puncher.openSession(address)
    if (isDone(c)) return null
  }

  // If the remote told us they didn't know their nat firewall yet, give them a chance to figure it out
  // They might say this to see if the "fast mode" punch comes through first.
  if (c.puncher.remoteFirewall === FIREWALL.UNKNOWN) {
    await c.sleeper.pause(1000)
    if (isDone(c)) return null
  }

  let stable = await c.puncher.analyze(false)
  if (isDone(c)) return null

  // If the socket seems unstable, try to make it stable by setting the "allowReopen" flag
  // Mostly relevant for mobile networks
  if (!stable) {
    stable = await c.puncher.analyze(true)
    if (isDone(c)) return null
    if (stable) return probeRound(c, serverAddress, serverRelay, false)
  }

  if ((c.puncher.remoteFirewall === FIREWALL.UNKNOWN || !token) && retry) {
    return probeRound(c, serverAddress, serverRelay, false)
  }

  if (
    c.puncher.remoteFirewall === FIREWALL.UNKNOWN ||
    c.puncher.nat.firewall === FIREWALL.UNKNOWN
  ) {
    await abort(c, serverRelay, HOLEPUNCH_PROBE_TIMEOUT())
    return null
  }

  if (c.puncher.remoteFirewall >= FIREWALL.RANDOM && c.puncher.nat.firewall >= FIREWALL.RANDOM) {
    await abort(c, serverRelay, HOLEPUNCH_DOUBLE_RANDOMIZED_NATS())
    return null
  }

  return { token, peerAddress }
}

async function roundPunch(c, serverAddress, remoteToken, clientRelay, serverRelay, delayed) {
  // We are gossiping our final NAT status to the other peer now
  // so make sure we don't update our local view for now as that can make things weird
  c.puncher.nat.freeze()

  const isRandom =
    c.puncher.remoteFirewall >= FIREWALL.RANDOM || c.puncher.nat.firewall >= FIREWALL.RANDOM
  if (isRandom) {
    while (
      c.dht._randomPunches >= c.dht._randomPunchLimit ||
      Date.now() - c.dht._lastRandomPunch < c.dht._randomPunchInterval
    ) {
      // if no relay can help, bail
      if (!c.relayToken) throw HOLEPUNCH_ABORTED()

      if (!delayed) {
        delayed = true
        await updateHolepunch(c, serverAddress, clientRelay, {
          error: ERROR.NONE,
          firewall: c.puncher.nat.firewall,
          round: c.round++,
          connected: false,
          punching: false,
          addresses: c.puncher.nat.addresses,
          remoteAddress: null,
          token: c.payload.token(serverAddress),
          remoteToken
        })
        if (isDone(c)) return
      }

      await tryLater(c)
      if (isDone(c)) return
    }
  }

  // increment now, so we can commit to punching
  if (isRandom) c.dht._randomPunches++

  let reply

  try {
    // if delayed switch to the servers chosen relay - we validated anyway
    reply = await updateHolepunch(
      c,
      delayed ? serverRelay.peerAddress : serverAddress,
      delayed ? serverRelay.relayAddress : clientRelay,
      {
        error: ERROR.NONE,
        firewall: c.puncher.nat.firewall,
        round: c.round++,
        connected: false,
        punching: true,
        addresses: c.puncher.nat.addresses,
        remoteAddress: null,
        token: delayed ? null : c.payload.token(serverAddress),
        remoteToken
      }
    )
  } finally {
    // decrement as punch increments for us
    if (isRandom) c.dht._randomPunches--
  }

  if (isDone(c)) return
  if (!reply) return

  if (reply.tryLater) {
    await tryLater(c)
    if (isDone(c)) return
    return roundPunch(c, serverAddress, remoteToken, clientRelay, serverRelay, true)
  }

  if (!c.puncher.remoteHolepunching) {
    throw REMOTE_NOT_HOLEPUNCHING()
  }

  if (!(await c.puncher.punch())) {
    throw REMOTE_NOT_HOLEPUNCHABLE()
  }
}

async function tryLater(c) {
  if (!c.relayToken) throw HOLEPUNCH_ABORTED()
  await c.sleeper.pause(10000 + Math.round(Math.random() * 10000))
}

function maybeDestroyEncryptedSocket(c, err) {
  if (isDone(c)) return
  if (c.encryptedSocket.rawStream) return
  if (c.relaySocket) return // waiting for the relay
  if (c.puncher && !c.puncher.destroyed) return // waiting for the puncher
  c.session.destroy()
  c.encryptedSocket.destroy(err)
}

async function abort(c, { peerAddress, relayAddress }, err) {
  try {
    await updateHolepunch(c, peerAddress, relayAddress, {
      error: ERROR.ABORTED,
      firewall: FIREWALL.UNKNOWN,
      round: c.round++,
      connected: false,
      punching: false,
      addresses: null,
      remoteAddress: null,
      token: null,
      remoteToken: null
    })
  } catch (err) {
    safetyCatch(err)
  }

  destroyPuncher(c)
  maybeDestroyEncryptedSocket(c, err)
}

function relayConnection(c, relayThrough, payload, hs) {
  let isInitiator
  let publicKey
  let token

  if (payload.relayThrough) {
    isInitiator = false
    publicKey = payload.relayThrough.publicKey
    token = payload.relayThrough.token
  } else {
    isInitiator = true
    publicKey = relayThrough
    token = c.relayToken
  }

  c.relayToken = token
  c.relaySocket = c.dht.connect(publicKey)
  c.relaySocket.setKeepAlive(c.relayKeepAlive)
  c.relayClient = relay.Client.from(c.relaySocket, { id: c.relaySocket.publicKey })
  c.relayTimeout = setTimeout(onabort, 15000, null)

  c.relayClient.pair(isInitiator, token, c.rawStream).on('error', onabort).on('data', ondata)

  function ondata(remoteId) {
    if (c.relayTimeout) clearRelayTimeout(c)
    if (c.rawStream === null) {
      onabort(null)
      return
    }

    c.relayPaired = true

    const { remotePort, remoteHost, socket } = c.relaySocket.rawStream

    c.rawStream
      .on('close', () => c.relaySocket.destroy())
      .connect(socket, remoteId, remotePort, remoteHost)

    c.encryptedSocket.start(c.rawStream, { handshake: hs })
  }

  function onabort(err) {
    if (c.relayTimeout) clearRelayTimeout(c)
    const socket = c.relaySocket
    c.relayToken = null
    c.relaySocket = null
    if (socket) socket.destroy()
    maybeDestroyEncryptedSocket(c, err || RELAY_ABORTED())
  }
}

function clearPassiveConnectTimeout(c) {
  clearTimeout(c.passiveConnectTimeout)
  c.passiveConnectTimeout = null
}

function clearRelayTimeout(c) {
  clearTimeout(c.relayTimeout)
  c.relayTimeout = null
}

function destroyPuncher(c) {
  if (c.puncher) c.puncher.destroy()
  c.session.destroy()
}

function pickServerRelay(relays, clientRelay) {
  for (const r of relays) {
    if (!diffAddress(r.relayAddress, clientRelay)) return r
  }
  return relays[0]
}

function diffAddress(a, b) {
  return a.host !== b.host || a.port !== b.port
}

function defaultCreateHandshake(keyPair, remotePublicKey) {
  return new NoiseWrap(keyPair, remotePublicKey)
}

function defaultCreateSecretStream(isInitiator, rawStream, opts) {
  return new NoiseSecretStream(isInitiator, rawStream, opts)
}

function onlyNonReserved(addr) {
  return !isReserved(addr.host)
}

function isRelay(relaySocket, socket, port, host) {
  const stream = relaySocket.rawStream
  if (!stream) return false
  if (stream.socket !== socket) return false
  return port === stream.remotePort && host === stream.remoteHost
}

function selectRelay(relayThrough) {
  if (typeof relayThrough === 'function') relayThrough = relayThrough()
  if (relayThrough === null) return null
  if (Array.isArray(relayThrough))
    return relayThrough[Math.floor(Math.random() * relayThrough.length)]
  return relayThrough
}

function isRelayAddress(relayAddresses, data) {
  for (const node of relayAddresses) {
    if (node.host === data.from.host && node.port === data.from.port) return true
  }

  return false
}

function noop() {}
const EventEmitter = require('events')
const b4a = require('b4a')
const errors = require('./errors')

module.exports = class ConnectionPool extends EventEmitter {
  constructor(dht) {
    super()

    this._dht = dht
    this._servers = new Map()
    this._connecting = new Map()
    this._connections = new Map()
  }

  _attachServer(server) {
    const keyString = b4a.toString(server.publicKey, 'hex')

    this._servers.set(keyString, server)

    server
      .on('close', () => {
        this._servers.delete(keyString)
      })
      .on('connection', (socket) => {
        this._attachStream(socket, true)
      })
  }

  _attachStream(stream, opened) {
    const existing = this.get(stream.remotePublicKey)

    if (existing) {
      const keepNew =
        stream.isInitiator === existing.isInitiator ||
        b4a.compare(stream.publicKey, stream.remotePublicKey) > 0

      if (keepNew) {
        let closed = false

        const onclose = () => {
          closed = true
        }

        existing
          .on('error', noop)
          .on('close', () => {
            if (closed) return

            stream.off('error', noop).off('close', onclose)

            this._attachStream(stream, opened)
          })
          .destroy(errors.DUPLICATE_CONNECTION())

        stream.on('error', noop).on('close', onclose)
      } else {
        stream.on('error', noop).destroy(errors.DUPLICATE_CONNECTION())
      }

      return
    }

    const session = new ConnectionRef(this, stream)

    const keyString = b4a.toString(stream.remotePublicKey, 'hex')

    if (opened) {
      this._connections.set(keyString, session)

      stream.on('close', () => {
        this._connections.delete(keyString)
      })

      this.emit('connection', stream, session)
    } else {
      this._connecting.set(keyString, session)

      stream
        .on('error', noop)
        .on('close', () => {
          if (opened) this._connections.delete(keyString)
          else this._connecting.delete(keyString)
        })
        .on('open', () => {
          opened = true

          this._connecting.delete(keyString)
          this._connections.set(keyString, session)

          stream.off('error', noop)

          this.emit('connection', stream, session)
        })
    }

    return session
  }

  get connecting() {
    return this._connecting.size
  }

  get connections() {
    return this._connections.values()
  }

  has(publicKey) {
    const keyString = b4a.toString(publicKey, 'hex')

    return this._connections.has(keyString) || this._connecting.has(keyString)
  }

  get(publicKey) {
    const keyString = b4a.toString(publicKey, 'hex')

    const existing = this._connections.get(keyString) || this._connecting.get(keyString)

    return existing?._stream || null
  }
}

class ConnectionRef {
  constructor(pool, stream) {
    this._pool = pool
    this._stream = stream
    this._refs = 0
  }

  active() {
    this._refs++
  }

  inactive() {
    this._refs--
  }

  release() {
    this._stream.destroy()
  }
}

function noop() {}
const crypto = require('hypercore-crypto')

const COMMANDS = (exports.COMMANDS = {
  PEER_HANDSHAKE: 0,
  PEER_HOLEPUNCH: 1,
  FIND_PEER: 2,
  LOOKUP: 3,
  ANNOUNCE: 4,
  UNANNOUNCE: 5,
  MUTABLE_PUT: 6,
  MUTABLE_GET: 7,
  IMMUTABLE_PUT: 8,
  IMMUTABLE_GET: 9,
  PLUGIN: 10
})

exports.BOOTSTRAP_NODES = global.Pear?.config.dht?.bootstrap || [
  '88.99.3.86@node1.hyperdht.org:49737',
  '142.93.90.113@node2.hyperdht.org:49737',
  '138.68.147.8@node3.hyperdht.org:49737'
]

exports.KNOWN_NODES = global.Pear?.config.dht?.nodes || []

exports.FIREWALL = {
  UNKNOWN: 0,
  OPEN: 1,
  CONSISTENT: 2,
  RANDOM: 3
}

exports.ERROR = {
  // noise / connection related
  NONE: 0,
  ABORTED: 1,
  VERSION_MISMATCH: 2,
  TRY_LATER: 3,
  // dht related
  SEQ_REUSED: 16,
  SEQ_TOO_LOW: 17
}

const [
  NS_ANNOUNCE,
  NS_UNANNOUNCE,
  NS_MUTABLE_PUT,
  NS_PEER_HANDSHAKE,
  NS_PEER_HOLEPUNCH,
  NS_PLUGIN
] = crypto.namespace('hyperswarm/dht', [
  COMMANDS.ANNOUNCE,
  COMMANDS.UNANNOUNCE,
  COMMANDS.MUTABLE_PUT,
  COMMANDS.PEER_HANDSHAKE,
  COMMANDS.PEER_HOLEPUNCH,
  COMMANDS.PLUGIN
])

exports.NS = {
  ANNOUNCE: NS_ANNOUNCE,
  UNANNOUNCE: NS_UNANNOUNCE,
  MUTABLE_PUT: NS_MUTABLE_PUT,
  PEER_HANDSHAKE: NS_PEER_HANDSHAKE,
  PEER_HOLEPUNCH: NS_PEER_HOLEPUNCH,
  PLUGIN: NS_PLUGIN
}
const sodium = require('sodium-universal')
const b4a = require('b4a')

function hash(data) {
  const out = b4a.allocUnsafe(32)
  sodium.crypto_generichash(out, data)
  return out
}

function unslabbedHash(data) {
  const out = b4a.allocUnsafeSlow(32)
  sodium.crypto_generichash(out, data)
  return out
}

function createKeyPair(seed) {
  const publicKey = b4a.alloc(32)
  const secretKey = b4a.alloc(64)
  if (seed) sodium.crypto_sign_seed_keypair(publicKey, secretKey, seed)
  else sodium.crypto_sign_keypair(publicKey, secretKey)
  return { publicKey, secretKey }
}

module.exports = {
  hash,
  unslabbedHash,
  createKeyPair
}
const b4a = require('b4a')
const cenc = require('compact-encoding')

function encodeUnslab(enc, m) {
  // Faster than unslab(c.encode(enc, data)) because it avoids the mem copy.
  // Makes sense to put in compact-encoding when we need it in other modules too
  const state = cenc.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafeSlow(state.end)
  enc.encode(state, m)
  return state.buffer
}

module.exports = {
  encodeUnslab
}
module.exports = class DHTError extends Error {
  constructor(msg, code, fn = DHTError) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'DHTError'
  }

  static BAD_HANDSHAKE_REPLY(msg = 'Bad handshake reply') {
    return new DHTError(msg, 'BAD_HANDSHAKE_REPLY', DHTError.BAD_HANDSHAKE_REPLY)
  }

  static BAD_HOLEPUNCH_REPLY(msg = 'Bad holepunch reply') {
    return new DHTError(msg, 'BAD_HOLEPUNCH_REPLY', DHTError.BAD_HOLEPUNCH_REPLY)
  }

  static HOLEPUNCH_ABORTED(msg = 'Holepunch aborted') {
    return new DHTError(msg, 'HOLEPUNCH_ABORTED', DHTError.HOLEPUNCH_ABORTED)
  }

  static HOLEPUNCH_INVALID(msg = 'Invalid holepunch payload') {
    return new DHTError(msg, 'HOLEPUNCH_INVALID', DHTError.HOLEPUNCH_INVALID)
  }

  static HOLEPUNCH_PROBE_TIMEOUT(msg = 'Holepunching probe did not finish in time') {
    return new DHTError(msg, 'HOLEPUNCH_PROBE_TIMEOUT', DHTError.HOLEPUNCH_PROBE_TIMEOUT)
  }

  static HOLEPUNCH_DOUBLE_RANDOMIZED_NATS(msg = 'Both remote and local NATs are randomized') {
    return new DHTError(
      msg,
      'HOLEPUNCH_DOUBLE_RANDOMIZED_NATS',
      DHTError.HOLEPUNCH_DOUBLE_RANDOMIZED_NATS
    )
  }

  static CANNOT_HOLEPUNCH(msg = 'Cannot holepunch to remote') {
    return new DHTError(msg, 'CANNOT_HOLEPUNCH', DHTError.CANNOT_HOLEPUNCH)
  }

  static REMOTE_NOT_HOLEPUNCHING(msg = 'Remote is not holepunching') {
    return new DHTError(msg, 'REMOTE_NOT_HOLEPUNCHING', DHTError.REMOTE_NOT_HOLEPUNCHING)
  }

  static REMOTE_NOT_HOLEPUNCHABLE(msg = 'Remote is not holepunchable') {
    return new DHTError(msg, 'REMOTE_NOT_HOLEPUNCHABLE', DHTError.REMOTE_NOT_HOLEPUNCHABLE)
  }

  static REMOTE_ABORTED(msg = 'Remote aborted') {
    return new DHTError(msg, 'REMOTE_ABORTED', DHTError.REMOTE_ABORTED)
  }

  static HANDSHAKE_UNFINISHED(msg = 'Handshake did not finish') {
    return new DHTError(msg, 'HANDSHAKE_UNFINISHED', DHTError.HANDSHAKE_UNFINISHED)
  }

  static HANDSHAKE_INVALID(msg = 'Received invalid handshake') {
    return new DHTError(msg, 'HANDSHAKE_INVALID', DHTError.HANDSHAKE_INVALID)
  }

  static ALREADY_LISTENING(msg = 'Already listening') {
    return new DHTError(msg, 'ALREADY_LISTENING', DHTError.ALREADY_LISTENING)
  }

  static KEYPAIR_ALREADY_USED(msg = 'Keypair already used') {
    return new DHTError(msg, 'KEYPAIR_ALREADY_USED', DHTError.KEYPAIR_ALREADY_USED)
  }

  static NODE_DESTROYED(msg = 'Node destroyed') {
    return new DHTError(msg, 'NODE_DESTROYED', DHTError.NODE_DESTROYED)
  }

  static PEER_CONNECTION_FAILED(msg = 'Could not connect to peer') {
    return new DHTError(msg, 'PEER_CONNECTION_FAILED', DHTError.PEER_CONNECTION_FAILED)
  }

  static PEER_NOT_FOUND(msg = 'Peer not found') {
    return new DHTError(msg, 'PEER_NOT_FOUND', DHTError.PEER_NOT_FOUND)
  }

  static STREAM_NOT_CONNECTED(msg = 'Stream is not connected') {
    return new DHTError(msg, 'STREAM_NOT_CONNECTED', DHTError.STREAM_DISCONNECTED)
  }

  static SERVER_INCOMPATIBLE(msg = 'Server is using an incompatible version') {
    return new DHTError(msg, 'SERVER_INCOMPATIBLE', DHTError.SERVER_INCOMPATIBLE)
  }

  static SERVER_ERROR(msg = 'Server returned an error') {
    return new DHTError(msg, 'SERVER_ERROR', DHTError.SERVER_ERROR)
  }

  static DUPLICATE_CONNECTION(msg = 'Duplicate connection') {
    return new DHTError(msg, 'DUPLICATE_CONNECTION', DHTError.DUPLICATE_CONNECTION)
  }

  static RELAY_ABORTED(msg = 'Relay aborted') {
    return new DHTError(msg, 'RELAY_ABORTED', DHTError.RELAY_ABORTED)
  }

  static SUSPENDED(msg = 'Suspended') {
    return new DHTError(msg, 'SUSPENDED', DHTError.SUSPENDED)
  }
}
const b4a = require('b4a')
const Nat = require('./nat')
const Sleeper = require('./sleeper')
const { FIREWALL } = require('./constants')

const BIRTHDAY_SOCKETS = 256
const HOLEPUNCH = b4a.from([0])
const HOLEPUNCH_TTL = 5
const DEFAULT_TTL = 64
const MAX_REOPENS = 3

module.exports = class Holepuncher {
  constructor(dht, session, isInitiator, remoteFirewall = FIREWALL.UNKNOWN) {
    const holder = dht._socketPool.acquire()

    this.dht = dht
    this.session = session

    this.nat = new Nat(dht, session, holder.socket)
    this.nat.autoSample()

    this.isInitiator = isInitiator

    // events
    this.onconnect = noop
    this.onabort = noop

    this.punching = false
    this.connected = false
    this.destroyed = false
    this.randomized = false

    // track remote state
    this.remoteFirewall = remoteFirewall
    this.remoteAddresses = []
    this.remoteHolepunching = false

    this._sleeper = new Sleeper()
    this._reopening = null
    this._timeout = null
    this._punching = null
    this._allHolders = []
    this._holder = this._addRef(holder)
  }

  get socket() {
    return this._holder.socket
  }

  updateRemote({ punching, firewall, addresses, verified }) {
    const remoteAddresses = []

    if (addresses) {
      for (const addr of addresses) {
        remoteAddresses.push({
          host: addr.host,
          port: addr.port,
          verified: verified === addr.host || this._isVerified(addr.host)
        })
      }
    }

    this.remoteFirewall = firewall
    this.remoteAddresses = remoteAddresses
    this.remoteHolepunching = punching
  }

  _isVerified(host) {
    for (const addr of this.remoteAddresses) {
      if (addr.verified && addr.host === host) {
        return true
      }
    }
    return false
  }

  ping(addr, socket = this._holder.socket) {
    return holepunch(socket, addr, false)
  }

  openSession(addr, socket = this._holder.socket) {
    return holepunch(socket, addr, true)
  }

  async analyze(allowReopen) {
    await this.nat.analyzing
    if (this._unstable()) {
      if (!allowReopen) return false
      if (!this._reopening) this._reopening = this._reopen()
      return this._reopening
    }
    return true
  }

  _unstable() {
    // TODO!!: We need an additional heuristic here... If we were NOT random in the past we should also do this.
    const firewall = this.nat.firewall
    return (
      (this.remoteFirewall >= FIREWALL.RANDOM && firewall >= FIREWALL.RANDOM) ||
      firewall === FIREWALL.UNKNOWN
    )
  }

  _reset() {
    const prev = this._holder

    this._allHolders.pop()
    this._holder = this._addRef(this.dht._socketPool.acquire())

    prev.release()
    this.nat.destroy()

    this.nat = new Nat(this.dht, this.session, this._holder.socket)
    // TODO: maybe make auto sampling configurable somehow?
    this.nat.autoSample()
  }

  _addRef(ref) {
    this._allHolders.push(ref)
    ref.onholepunchmessage = (msg, rinfo) => this._onholepunchmessage(msg, rinfo, ref)
    return ref
  }

  _onholepunchmessage(_, addr, ref) {
    if (!this.isInitiator) {
      // TODO: we don't need this if we had a way to connect a socket to many hosts
      holepunch(ref.socket, addr, false) // never fails
      return
    }

    if (this.connected) return

    this.connected = true
    this.punching = false

    for (const r of this._allHolders) {
      if (r === ref) continue
      r.release()
    }

    this._allHolders[0] = ref
    while (this._allHolders.length > 1) this._allHolders.pop()

    this._decrementRandomized()
    this.onconnect(ref.socket, addr.port, addr.host)
  }

  _done() {
    return this.destroyed || this.connected
  }

  async _reopen() {
    for (let i = 0; this._unstable() && i < MAX_REOPENS && !this._done() && !this.punching; i++) {
      this._reset()
      await this.nat.analyzing
    }

    return coerceFirewall(this.nat.firewall) === FIREWALL.CONSISTENT
  }

  punch() {
    if (!this._punching) this._punching = this._punch()
    return this._punching
  }

  async _punch() {
    if (this._done() || !this.remoteAddresses.length) return false

    this.punching = true

    // Coerce into consistency for now. Obvs we could make this this more efficient if we use that info
    // but that's seldomly used since those will just use tcp most of the time.

    const local = coerceFirewall(this.nat.firewall)
    const remote = coerceFirewall(this.remoteFirewall)

    // Note that most of these async functions are meant to run in the background
    // which is why we don't await them here and why they are not allowed to throw

    let remoteVerifiedAddress = null
    for (const addr of this.remoteAddresses) {
      if (addr.verified) {
        remoteVerifiedAddress = addr
        break
      }
    }

    if (local === FIREWALL.CONSISTENT && remote === FIREWALL.CONSISTENT) {
      this.dht.stats.punches.consistent++
      this._consistentProbe()
      return true
    }

    if (!remoteVerifiedAddress) return false

    if (local === FIREWALL.CONSISTENT && remote >= FIREWALL.RANDOM) {
      this.dht.stats.punches.random++
      this._incrementRandomized()
      this._randomProbes(remoteVerifiedAddress)
      return true
    }

    if (local >= FIREWALL.RANDOM && remote === FIREWALL.CONSISTENT) {
      this.dht.stats.punches.random++
      this._incrementRandomized()
      await this._openBirthdaySockets(remoteVerifiedAddress)
      if (this.punching) this._keepAliveRandomNat(remoteVerifiedAddress)
      return true
    }

    return false
  }

  // Note that this never throws so it is safe to run in the background
  async _consistentProbe() {
    // Here we do the sleep first because the "fast open" mode in the server just fired a ping
    if (!this.isInitiator) await this._sleeper.pause(1000)

    let tries = 0

    while (this.punching && tries++ < 10) {
      for (const addr of this.remoteAddresses) {
        // only try unverified addresses every 4 ticks
        if (!addr.verified && (tries & 3) !== 0) continue
        await holepunch(this._holder.socket, addr, false)
      }
      if (this.punching) await this._sleeper.pause(1000)
    }

    this._autoDestroy()
  }

  // Note that this never throws so it is safe to run in the background
  async _randomProbes(remoteAddr) {
    let tries = 1750 // ~35s

    while (this.punching && tries-- > 0) {
      const addr = { host: remoteAddr.host, port: randomPort() }
      await holepunch(this._holder.socket, addr, false)
      if (this.punching) await this._sleeper.pause(20)
    }

    this._autoDestroy()
  }

  // Note that this never throws so it is safe to run in the background
  async _keepAliveRandomNat(remoteAddr) {
    let i = 0
    let lowTTLRounds = 1

    // TODO: experiment with this here. We just bursted all the messages in
    // openOtherSockets to ensure the sockets are open, so it's potentially
    // a good idea to slow down for a bit.
    await this._sleeper.pause(100)

    let tries = 1750 // ~35s

    while (this.punching && tries-- > 0) {
      if (i === this._allHolders.length) {
        i = 0
        if (lowTTLRounds > 0) lowTTLRounds--
      }

      await holepunch(this._allHolders[i++].socket, remoteAddr, lowTTLRounds > 0)
      if (this.punching) await this._sleeper.pause(20)
    }

    this._autoDestroy()
  }

  async _openBirthdaySockets(remoteAddr) {
    while (this.punching && this._allHolders.length < BIRTHDAY_SOCKETS) {
      const ref = this._addRef(this.dht._socketPool.acquire())
      await holepunch(ref.socket, remoteAddr, HOLEPUNCH_TTL)
    }
  }

  _autoDestroy() {
    if (!this.connected) this.destroy()
  }

  _incrementRandomized() {
    if (!this.randomized) {
      this.randomized = true
      this.dht._randomPunches++
    }
  }

  _decrementRandomized() {
    if (this.randomized) {
      this.dht._lastRandomPunch = Date.now()
      this.randomized = false
      this.dht._randomPunches--
    }
  }

  destroy() {
    if (this.destroyed) return
    this.destroyed = true
    this.punching = false

    for (const ref of this._allHolders) ref.release()
    this._allHolders = []
    this.nat.destroy()

    if (!this.connected) {
      this._decrementRandomized()
      this.onabort()
    }
  }

  static ping(socket, addr) {
    return holepunch(socket, addr, false)
  }

  static localAddresses(socket) {
    return localAddresses(socket)
  }

  static matchAddress(myAddresses, externalAddresses) {
    return matchAddress(myAddresses, externalAddresses)
  }
}

function holepunch(socket, addr, lowTTL) {
  return socket.send(HOLEPUNCH, addr.port, addr.host, lowTTL ? HOLEPUNCH_TTL : DEFAULT_TTL)
}

function randomPort() {
  return (1000 + Math.random() * 64536) | 0
}

function coerceFirewall(fw) {
  return fw === FIREWALL.OPEN ? FIREWALL.CONSISTENT : fw
}

function localAddresses(socket) {
  const addrs = []
  const { host, port } = socket.address()

  if (host === '127.0.0.1') return [{ host, port }]

  for (const n of socket.udx.networkInterfaces()) {
    if (n.family !== 4 || n.internal) continue

    addrs.push({ host: n.host, port })
  }

  if (addrs.length === 0) {
    addrs.push({ host: '127.0.0.1', port })
  }

  return addrs
}

function matchAddress(localAddresses, remoteLocalAddresses) {
  if (remoteLocalAddresses.length === 0) return null

  let best = { segment: 1, addr: null }

  for (const localAddress of localAddresses) {
    // => 192.168.122.238
    const a = localAddress.host.split('.')

    for (const remoteAddress of remoteLocalAddresses) {
      // => 192.168.0.23
      // => 192.168.122.1
      const b = remoteAddress.host.split('.')

      // Matches 192.*.*.*
      if (a[0] === b[0]) {
        if (best.segment === 1) best = { segment: 2, addr: remoteAddress }

        // Matches 192.168.*.*
        if (a[1] === b[1]) {
          if (best.segment === 2) best = { segment: 3, addr: remoteAddress }

          // Matches 192.168.122.*
          if (a[2] === b[2]) return remoteAddress
        }
      }
    }
  }

  return best.addr
}

function noop() {}
const c = require('compact-encoding')

const ipv4 = {
  ...c.ipv4Address,
  decode(state) {
    const ip = c.ipv4Address.decode(state)
    return {
      host: ip.host,
      port: ip.port
    }
  }
}

const ipv4Array = c.array(ipv4)

const ipv6 = {
  ...c.ipv6Address,
  decode(state) {
    const ip = c.ipv6Address.decode(state)
    return {
      host: ip.host,
      port: ip.port
    }
  }
}

const ipv6Array = c.array(ipv6)

exports.handshake = {
  preencode(state, m) {
    state.end += 1 + 1 + (m.peerAddress ? 6 : 0) + (m.relayAddress ? 6 : 0)
    c.buffer.preencode(state, m.noise)
  },
  encode(state, m) {
    const flags = (m.peerAddress ? 1 : 0) | (m.relayAddress ? 2 : 0)

    c.uint.encode(state, flags)
    c.uint.encode(state, m.mode)
    c.buffer.encode(state, m.noise)

    if (m.peerAddress) ipv4.encode(state, m.peerAddress)
    if (m.relayAddress) ipv4.encode(state, m.relayAddress)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      mode: c.uint.decode(state),
      noise: c.buffer.decode(state),
      peerAddress: flags & 1 ? ipv4.decode(state) : null,
      relayAddress: flags & 2 ? ipv4.decode(state) : null
    }
  }
}

const relayInfo = {
  preencode(state, m) {
    state.end += 12
  },
  encode(state, m) {
    ipv4.encode(state, m.relayAddress)
    ipv4.encode(state, m.peerAddress)
  },
  decode(state) {
    return {
      relayAddress: ipv4.decode(state),
      peerAddress: ipv4.decode(state)
    }
  }
}

const relayInfoArray = c.array(relayInfo)

const holepunchInfo = {
  preencode(state, m) {
    c.uint.preencode(state, m.id)
    relayInfoArray.preencode(state, m.relays)
  },
  encode(state, m) {
    c.uint.encode(state, m.id)
    relayInfoArray.encode(state, m.relays)
  },
  decode(state) {
    return {
      id: c.uint.decode(state),
      relays: relayInfoArray.decode(state)
    }
  }
}

const udxInfo = {
  preencode(state, m) {
    state.end += 2 // version + features
    c.uint.preencode(state, m.id)
    c.uint.preencode(state, m.seq)
  },
  encode(state, m) {
    c.uint.encode(state, 1)
    c.uint.encode(state, m.reusableSocket ? 1 : 0)
    c.uint.encode(state, m.id)
    c.uint.encode(state, m.seq)
  },
  decode(state) {
    const version = c.uint.decode(state)
    const features = c.uint.decode(state)

    return {
      version,
      reusableSocket: (features & 1) !== 0,
      id: c.uint.decode(state),
      seq: c.uint.decode(state)
    }
  }
}

const secretStreamInfo = {
  preencode(state, m) {
    c.uint.preencode(state, 1)
  },
  encode(state, m) {
    c.uint.encode(state, 1)
  },
  decode(state) {
    return {
      version: c.uint.decode(state)
    }
  }
}

const relayThroughInfo = {
  preencode(state, m) {
    c.uint.preencode(state, 1) // version
    c.uint.preencode(state, 0) // flags
    c.fixed32.preencode(state, m.publicKey)
    c.fixed32.preencode(state, m.token)
  },
  encode(state, m) {
    c.uint.encode(state, 1)
    c.uint.encode(state, 0)
    c.fixed32.encode(state, m.publicKey)
    c.fixed32.encode(state, m.token)
  },
  decode(state) {
    const version = c.uint.decode(state)
    c.uint.decode(state)

    return {
      version,
      publicKey: c.fixed32.decode(state),
      token: c.fixed32.decode(state)
    }
  }
}

exports.noisePayload = {
  preencode(state, m) {
    state.end += 4 // version + flags + error + firewall
    if (m.holepunch) holepunchInfo.preencode(state, m.holepunch)
    if (m.addresses4 && m.addresses4.length) ipv4Array.preencode(state, m.addresses4)
    if (m.addresses6 && m.addresses6.length) ipv6Array.preencode(state, m.addresses6)
    if (m.udx) udxInfo.preencode(state, m.udx)
    if (m.secretStream) secretStreamInfo.preencode(state, m.secretStream)
    if (m.relayThrough) relayThroughInfo.preencode(state, m.relayThrough)
    if (m.relayAddresses) ipv4Array.preencode(state, m.relayAddresses)
  },
  encode(state, m) {
    let flags = 0

    if (m.holepunch) flags |= 1
    if (m.addresses4 && m.addresses4.length) flags |= 2
    if (m.addresses6 && m.addresses6.length) flags |= 4
    if (m.udx) flags |= 8
    if (m.secretStream) flags |= 16
    if (m.relayThrough) flags |= 32
    if (m.relayAddresses) flags |= 64

    c.uint.encode(state, 1) // version
    c.uint.encode(state, flags)
    c.uint.encode(state, m.error)
    c.uint.encode(state, m.firewall)

    if (m.holepunch) holepunchInfo.encode(state, m.holepunch)
    if (m.addresses4 && m.addresses4.length) ipv4Array.encode(state, m.addresses4)
    if (m.addresses6 && m.addresses6.length) ipv6Array.encode(state, m.addresses6)
    if (m.udx) udxInfo.encode(state, m.udx)
    if (m.secretStream) secretStreamInfo.encode(state, m.secretStream)
    if (m.relayThrough) relayThroughInfo.encode(state, m.relayThrough)
    if (m.relayAddresses) ipv4Array.encode(state, m.relayAddresses)
  },
  decode(state) {
    const version = c.uint.decode(state)

    if (version !== 1) {
      // Do not attempt to decode but return this back to the user so they can
      // actually handle it
      return {
        version,
        error: 0,
        firewall: 0,
        holepunch: null,
        addresses4: [],
        addresses6: [],
        udx: null,
        secretStream: null,
        relayThrough: null,
        relayAddresses: null
      }
    }

    const flags = c.uint.decode(state)

    return {
      version,
      error: c.uint.decode(state),
      firewall: c.uint.decode(state),
      holepunch: (flags & 1) !== 0 ? holepunchInfo.decode(state) : null,
      addresses4: (flags & 2) !== 0 ? ipv4Array.decode(state) : [],
      addresses6: (flags & 4) !== 0 ? ipv6Array.decode(state) : [],
      udx: (flags & 8) !== 0 ? udxInfo.decode(state) : null,
      secretStream: (flags & 16) !== 0 ? secretStreamInfo.decode(state) : null,
      relayThrough: (flags & 32) !== 0 ? relayThroughInfo.decode(state) : null,
      relayAddresses: (flags & 64) !== 0 ? ipv4Array.decode(state) : null
    }
  }
}

exports.holepunch = {
  preencode(state, m) {
    state.end += 2
    c.uint.preencode(state, m.id)
    c.buffer.preencode(state, m.payload)
    if (m.peerAddress) ipv4.preencode(state, m.peerAddress)
  },
  encode(state, m) {
    const flags = m.peerAddress ? 1 : 0
    c.uint.encode(state, flags)
    c.uint.encode(state, m.mode)
    c.uint.encode(state, m.id)
    c.buffer.encode(state, m.payload)
    if (m.peerAddress) ipv4.encode(state, m.peerAddress)
  },
  decode(state) {
    const flags = c.uint.decode(state)
    return {
      mode: c.uint.decode(state),
      id: c.uint.decode(state),
      payload: c.buffer.decode(state),
      peerAddress: flags & 1 ? ipv4.decode(state) : null
    }
  }
}

exports.holepunchPayload = {
  preencode(state, m) {
    state.end += 4 // flags + error + firewall + round
    if (m.addresses) ipv4Array.preencode(state, m.addresses)
    if (m.remoteAddress) state.end += 6
    if (m.token) state.end += 32
    if (m.remoteToken) state.end += 32
  },
  encode(state, m) {
    const flags =
      (m.connected ? 1 : 0) |
      (m.punching ? 2 : 0) |
      (m.addresses ? 4 : 0) |
      (m.remoteAddress ? 8 : 0) |
      (m.token ? 16 : 0) |
      (m.remoteToken ? 32 : 0)

    c.uint.encode(state, flags)
    c.uint.encode(state, m.error)
    c.uint.encode(state, m.firewall)
    c.uint.encode(state, m.round)

    if (m.addresses) ipv4Array.encode(state, m.addresses)
    if (m.remoteAddress) ipv4.encode(state, m.remoteAddress)
    if (m.token) c.fixed32.encode(state, m.token)
    if (m.remoteToken) c.fixed32.encode(state, m.remoteToken)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      error: c.uint.decode(state),
      firewall: c.uint.decode(state),
      round: c.uint.decode(state),
      connected: (flags & 1) !== 0,
      punching: (flags & 2) !== 0,
      addresses: (flags & 4) !== 0 ? ipv4Array.decode(state) : null,
      remoteAddress: (flags & 8) !== 0 ? ipv4.decode(state) : null,
      token: (flags & 16) !== 0 ? c.fixed32.decode(state) : null,
      remoteToken: (flags & 32) !== 0 ? c.fixed32.decode(state) : null
    }
  }
}

const peer = (exports.peer = {
  preencode(state, m) {
    state.end += 32
    ipv4Array.preencode(state, m.relayAddresses)
  },
  encode(state, m) {
    c.fixed32.encode(state, m.publicKey)
    ipv4Array.encode(state, m.relayAddresses)
  },
  decode(state) {
    return {
      publicKey: c.fixed32.decode(state),
      relayAddresses: ipv4Array.decode(state)
    }
  }
})

const peers = (exports.peers = c.array(peer))

const rawPeers = c.array(c.raw)

exports.lookupRawReply = {
  preencode(state, m) {
    rawPeers.preencode(state, m.peers)
    c.uint.preencode(state, m.bump)
  },
  encode(state, m) {
    rawPeers.encode(state, m.peers)
    c.uint.encode(state, m.bump)
  },
  decode(state) {
    return {
      peers: peers.decode(state),
      bump: state.start < state.end ? c.uint.decode(state) : 0
    }
  }
}

exports.announce = {
  preencode(state, m) {
    state.end++ // flags
    if (m.peer) peer.preencode(state, m.peer)
    if (m.refresh) state.end += 32
    if (m.signature) state.end += 64
    if (m.bump) c.uint.preencode(state, m.bump)
  },
  encode(state, m) {
    const flags = (m.peer ? 1 : 0) | (m.refresh ? 2 : 0) | (m.signature ? 4 : 0) | (m.bump ? 8 : 0)
    c.uint.encode(state, flags)
    if (m.peer) peer.encode(state, m.peer)
    if (m.refresh) c.fixed32.encode(state, m.refresh)
    if (m.signature) c.fixed64.encode(state, m.signature)
    if (m.bump) c.uint.encode(state, m.bump)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      peer: (flags & 1) !== 0 ? peer.decode(state) : null,
      refresh: (flags & 2) !== 0 ? c.fixed32.decode(state) : null,
      signature: (flags & 4) !== 0 ? c.fixed64.decode(state) : null,
      bump: (flags & 8) !== 0 ? c.uint.decode(state) : 0
    }
  }
}

exports.mutableSignable = {
  preencode(state, m) {
    c.uint.preencode(state, m.seq)
    c.buffer.preencode(state, m.value)
  },
  encode(state, m) {
    c.uint.encode(state, m.seq)
    c.buffer.encode(state, m.value)
  },
  decode(state) {
    return {
      seq: c.uint.decode(state),
      value: c.buffer.decode(state)
    }
  }
}

exports.mutablePutRequest = {
  preencode(state, m) {
    c.fixed32.preencode(state, m.publicKey)
    c.uint.preencode(state, m.seq)
    c.buffer.preencode(state, m.value)
    c.fixed64.preencode(state, m.signature)
  },
  encode(state, m) {
    c.fixed32.encode(state, m.publicKey)
    c.uint.encode(state, m.seq)
    c.buffer.encode(state, m.value)
    c.fixed64.encode(state, m.signature)
  },
  decode(state) {
    return {
      publicKey: c.fixed32.decode(state),
      seq: c.uint.decode(state),
      value: c.buffer.decode(state),
      signature: c.fixed64.decode(state)
    }
  }
}

exports.mutableGetResponse = {
  preencode(state, m) {
    c.uint.preencode(state, m.seq)
    c.buffer.preencode(state, m.value)
    c.fixed64.preencode(state, m.signature)
  },
  encode(state, m) {
    c.uint.encode(state, m.seq)
    c.buffer.encode(state, m.value)
    c.fixed64.encode(state, m.signature)
  },
  decode(state) {
    return {
      seq: c.uint.decode(state),
      value: c.buffer.decode(state),
      signature: c.fixed64.decode(state)
    }
  }
}

exports.pluginRequest = {
  preencode(state, m) {
    c.string.preencode(state, m.plugin)
    c.uint.preencode(state, m.version)
    c.uint.preencode(state, m.command)
    c.buffer.preencode(state, m.value)
  },
  encode(state, m) {
    c.string.encode(state, m.plugin)
    c.uint.encode(state, m.version)
    c.uint.encode(state, m.command)
    c.buffer.encode(state, m.value)
  },
  decode(state) {
    return {
      plugin: c.string.decode(state),
      version: c.uint.decode(state),
      command: c.uint.decode(state),
      value: c.buffer.decode(state)
    }
  }
}
const { FIREWALL } = require('../lib/constants')

module.exports = class Nat {
  constructor(dht, session, socket) {
    this._samplesHost = []
    this._samplesFull = []
    this._visited = new Map()
    this._resolve = null
    this._minSamples = 4
    this._autoSampling = false

    this.dht = dht
    this.session = session
    this.socket = socket

    this.sampled = 0
    this.firewall = dht.firewalled ? FIREWALL.UNKNOWN : FIREWALL.OPEN
    this.addresses = null

    this.analyzing = new Promise((resolve) => {
      this._resolve = resolve
    })
  }

  autoSample(retry = true) {
    if (this._autoSampling) return
    this._autoSampling = true

    const self = this
    const socket = this.socket
    const maxPings = this._minSamples

    let skip = this.dht.nodes.length >= 8 ? 5 : 0
    let pending = 0

    // TODO: it would be best to pick the nodes to help us based on latency to us
    // That should reduce connect latency in general. We should investigate tracking that later on.

    // TODO 2: try to pick nodes with different IPs as well, as that'll help multi IP cell connections...
    // If we expose this from the nat sampler then the DHT should be able to help us filter out scams as well...

    for (
      let node = this.dht.nodes.latest;
      node && this.sampled + pending < maxPings;
      node = node.prev
    ) {
      if (skip > 0) {
        skip--
        continue
      }

      const ref = node.host + ':' + node.port

      if (this._visited.has(ref)) continue
      this._visited.set(ref, 1)

      pending++
      this.session.ping(node, { socket, retry: false }).then(onpong, onskip)
    }

    pending++
    onskip()

    function onpong(res) {
      self.add(res.to, res.from)
      onskip()
    }

    function onskip() {
      if (--pending === 0 && self.sampled < self._minSamples) {
        if (retry) {
          self._autoSampling = false
          self.autoSample(false)
          return
        }
        self._resolve()
      }
    }
  }

  destroy() {
    this._autoSampling = true
    this._minSamples = 0
    this._resolve()
  }

  unfreeze() {
    this.frozen = false
    this._updateFirewall()
    this._updateAddresses()
  }

  freeze() {
    this.frozen = true
  }

  _updateFirewall() {
    if (!this.dht.firewalled) {
      this.firewall = FIREWALL.OPEN
      return
    }

    if (this.sampled < 3) return

    const max = this._samplesFull[0].hits

    if (max >= 3) {
      this.firewall = FIREWALL.CONSISTENT
      return
    }

    if (max === 1) {
      this.firewall = FIREWALL.RANDOM
      return
    }

    // else max === 2

    // 1 host, >= 4 total samples ie, 2 bad ones -> random
    if (this._samplesHost.length === 1 && this.sampled > 3) {
      this.firewall = FIREWALL.RANDOM
      return
    }

    // double hit on two different ips -> assume consistent
    if (this._samplesHost.length > 1 && this._samplesFull[1].hits > 1) {
      this.firewall = FIREWALL.CONSISTENT
      return
    }

    // (4 is just means - all the samples we expect) - no decision - assume random
    if (this.sampled > 4) {
      this.firewall = FIREWALL.RANDOM
    }
  }

  _updateAddresses() {
    if (this.firewall === FIREWALL.UNKNOWN) {
      this.addresses = null
      return
    }

    if (this.firewall === FIREWALL.RANDOM) {
      this.addresses = [this._samplesHost[0]]
      return
    }

    if (this.firewall === FIREWALL.CONSISTENT) {
      this.addresses = []
      for (const addr of this._samplesFull) {
        if (addr.hits >= 2 || this.addresses.length < 2) this.addresses.push(addr)
      }
    }
  }

  update() {
    if (this.dht.firewalled && this.firewall === FIREWALL.OPEN) {
      this.firewall = FIREWALL.UNKNOWN
    }
    this._updateFirewall()
    this._updateAddresses()
  }

  add(addr, from) {
    const ref = from.host + ':' + from.port

    if (this._visited.get(ref) === 2) return
    this._visited.set(ref, 2)

    addSample(this._samplesHost, addr.host, 0)
    addSample(this._samplesFull, addr.host, addr.port)

    if ((++this.sampled >= 3 || !this.dht.firewalled) && !this.frozen) {
      this.update()
    }

    if (this.firewall === FIREWALL.CONSISTENT || this.firewall === FIREWALL.OPEN) {
      this._resolve()
    } else if (this.sampled >= this._minSamples) {
      this._resolve()
    }
  }
}

function addSample(samples, host, port) {
  for (let i = 0; i < samples.length; i++) {
    const s = samples[i]

    if (s.port !== port || s.host !== host) continue
    s.hits++

    for (; i > 0; i--) {
      const prev = samples[i - 1]
      if (prev.hits >= s.hits) return
      samples[i - 1] = s
      samples[i] = prev
    }

    return
  }

  samples.push({
    host,
    port,
    hits: 1
  })
}
const NoiseSecretStream = require('@hyperswarm/secret-stream')
const NoiseHandshake = require('noise-handshake')
const curve = require('noise-curve-ed')
const c = require('compact-encoding')
const b4a = require('b4a')
const sodium = require('sodium-universal')
const m = require('./messages')
const { NS } = require('./constants')
const { HANDSHAKE_UNFINISHED } = require('./errors')

const NOISE_PROLOUGE = NS.PEER_HANDSHAKE

module.exports = class NoiseWrap {
  constructor(keyPair, remotePublicKey) {
    this.isInitiator = !!remotePublicKey
    this.remotePublicKey = remotePublicKey
    this.keyPair = keyPair
    this.handshake = new NoiseHandshake('IK', this.isInitiator, keyPair, { curve })
    this.handshake.initialise(NOISE_PROLOUGE, remotePublicKey)
  }

  send(payload) {
    const buf = c.encode(m.noisePayload, payload)
    return this.handshake.send(buf)
  }

  recv(buf) {
    const payload = c.decode(m.noisePayload, this.handshake.recv(buf))
    this.remotePublicKey = b4a.toBuffer(this.handshake.rs)
    return payload
  }

  final() {
    if (!this.handshake.complete) throw HANDSHAKE_UNFINISHED()

    const holepunchSecret = b4a.allocUnsafe(32)

    sodium.crypto_generichash(holepunchSecret, NS.PEER_HOLEPUNCH, this.handshake.hash)

    return {
      isInitiator: this.isInitiator,
      publicKey: this.keyPair.publicKey,
      streamId: this.streamId,
      remotePublicKey: this.remotePublicKey,
      remoteId: NoiseSecretStream.id(this.handshake.hash, !this.isInitiator),
      holepunchSecret,
      hash: b4a.toBuffer(this.handshake.hash),
      rx: b4a.toBuffer(this.handshake.rx),
      tx: b4a.toBuffer(this.handshake.tx)
    }
  }
}
const c = require('compact-encoding')
const sodium = require('sodium-universal')
const RecordCache = require('record-cache')
const Cache = require('xache')
const b4a = require('b4a')
const unslab = require('unslab')

const { encodeUnslab } = require('./encode')
const m = require('./messages')
const { NS, ERROR } = require('./constants')

const EMPTY = b4a.alloc(0)
const TMP = b4a.allocUnsafe(32)
const MAX_BUMP_DRIFT = 60_000

module.exports = class Persistent {
  constructor(dht, opts) {
    this.dht = dht
    this.records = new RecordCache(opts.records)
    this.bumps = new Cache(opts.bumps)
    this.refreshes = new Cache(opts.refreshes)
    this.mutables = new Cache(opts.mutables)
    this.immutables = new Cache(opts.immutables)
  }

  onlookup(req) {
    if (!req.target) return

    const k = b4a.toString(req.target, 'hex')
    const records = this.records.get(k, 20)
    const bump = this.bumps.get(k) || 0
    const fwd = this.dht._router.get(k)

    if (fwd && records.length < 20) records.push(fwd.record)

    req.reply(records.length ? c.encode(m.lookupRawReply, { peers: records, bump }) : null)
  }

  onfindpeer(req) {
    if (!req.target) return
    const fwd = this.dht._router.get(req.target)
    req.reply(fwd ? fwd.record : null)
  }

  unannounce(target, publicKey) {
    const k = b4a.toString(target, 'hex')
    sodium.crypto_generichash(TMP, publicKey)

    if (b4a.equals(TMP, target)) this.dht._router.delete(k)
    this.records.remove(k, publicKey)
  }

  onunannounce(req) {
    if (!req.target || !req.token) return

    const unann = decode(m.announce, req.value)
    if (unann === null) return

    const { peer, signature } = unann
    if (!peer || !signature) return

    const signable = annSignable(req.target, req.token, this.dht.id, unann, NS.UNANNOUNCE)

    if (!sodium.crypto_sign_verify_detached(signature, signable, peer.publicKey)) {
      return
    }

    this.unannounce(req.target, peer.publicKey)
    req.reply(null, { token: false, closerNodes: false })
  }

  _onrefresh(token, req) {
    sodium.crypto_generichash(TMP, token)
    const activeRefresh = b4a.toString(TMP, 'hex')

    const r = this.refreshes.get(activeRefresh)
    if (!r) return

    const { announceSelf, k, record } = r
    const publicKey = record.subarray(0, 32)

    if (announceSelf) {
      this.dht._router.set(k, {
        relay: req.from,
        record,
        onconnect: null,
        onholepunch: null
      })
      this.records.remove(k, publicKey)
    } else {
      this.records.add(k, publicKey, record)
    }

    this.refreshes.delete(activeRefresh)
    this.refreshes.set(b4a.toString(token, 'hex'), r)

    req.reply(null, { token: false, closerNodes: false })
  }

  onannounce(req) {
    if (!req.target || !req.token || !this.dht.id) return

    const ann = decode(m.announce, req.value)
    if (ann === null) return

    const { peer, refresh, signature, bump } = ann

    if (!peer) {
      if (!refresh) return
      this._onrefresh(refresh, req)
      return
    }

    const signable = annSignable(req.target, req.token, this.dht.id, ann, NS.ANNOUNCE)

    if (!signature || !sodium.crypto_sign_verify_detached(signature, signable, peer.publicKey)) {
      return
    }

    // TODO: it would be potentially be more optimal to allow more than 3 addresses here for a findPeer response
    // and only use max 3 for a lookup reply
    if (peer.relayAddresses.length > 3) {
      peer.relayAddresses = peer.relayAddresses.slice(0, 3)
    }

    sodium.crypto_generichash(TMP, peer.publicKey)

    const k = b4a.toString(req.target, 'hex')
    const announceSelf = b4a.equals(TMP, req.target)
    const record = encodeUnslab(m.peer, peer)

    if (announceSelf) {
      this.dht._router.set(k, {
        relay: req.from,
        record,
        onconnect: null,
        onholepunch: null
      })
      this.records.remove(k, peer.publicKey)
    } else {
      const currentBump = this.bumps.get(k) || 0
      if (bump > currentBump && bump <= Date.now() + MAX_BUMP_DRIFT) this.bumps.set(k, bump)
      this.records.add(k, peer.publicKey, record)
    }

    if (refresh) {
      this.refreshes.set(b4a.toString(refresh, 'hex'), { k, record, announceSelf })
    }

    req.reply(null, { token: false, closerNodes: false })
  }

  onmutableget(req) {
    if (!req.target || !req.value) return

    let seq = 0
    try {
      seq = c.decode(c.uint, req.value)
    } catch {
      return
    }

    const k = b4a.toString(req.target, 'hex')
    const value = this.mutables.get(k)

    if (!value) {
      req.reply(null)
      return
    }

    const localSeq = c.decode(c.uint, value)
    req.reply(localSeq < seq ? null : value)
  }

  onmutableput(req) {
    if (!req.target || !req.token || !req.value) return

    const p = decode(m.mutablePutRequest, req.value)
    if (!p) return

    const { publicKey, seq, value, signature } = p

    const hash = b4a.allocUnsafe(32)
    sodium.crypto_generichash(hash, publicKey)
    if (!b4a.equals(hash, req.target)) return

    if (!value || !verifyMutable(signature, seq, value, publicKey)) return

    const k = b4a.toString(hash, 'hex')
    const local = this.mutables.get(k)

    if (local) {
      const existing = c.decode(m.mutableGetResponse, local)
      if (existing.value && existing.seq === seq && b4a.compare(value, existing.value) !== 0) {
        req.error(ERROR.SEQ_REUSED)
        return
      }
      if (seq < existing.seq) {
        req.error(ERROR.SEQ_TOO_LOW)
        return
      }
    }

    this.mutables.set(k, encodeUnslab(m.mutableGetResponse, { seq, value, signature }))
    req.reply(null)
  }

  onimmutableget(req) {
    if (!req.target) return

    const k = b4a.toString(req.target, 'hex')
    const value = this.immutables.get(k)

    req.reply(value || null)
  }

  onimmutableput(req) {
    if (!req.target || !req.token || !req.value) return

    const hash = b4a.alloc(32)
    sodium.crypto_generichash(hash, req.value)
    if (!b4a.equals(hash, req.target)) return

    const k = b4a.toString(hash, 'hex')
    this.immutables.set(k, unslab(req.value))

    req.reply(null)
  }

  onplugin(req) {
    if (!req.value) return

    const plugreq = decode(m.pluginRequest, req.value)
    if (plugreq === null) return

    const p = this.dht.plugins.get(plugreq.plugin)
    if (!p || p.version !== plugreq.version) return

    p.onrequest(plugreq, req)
  }

  destroy() {
    this.records.destroy()
    this.refreshes.destroy()
    this.mutables.destroy()
    this.immutables.destroy()
  }

  static signMutable(seq, value, keyPair) {
    const signable = b4a.allocUnsafe(32 + 32)
    const hash = signable.subarray(32)

    signable.set(NS.MUTABLE_PUT, 0)

    sodium.crypto_generichash(hash, c.encode(m.mutableSignable, { seq, value }))
    return sign(signable, keyPair)
  }

  static verifyMutable(signature, seq, value, publicKey) {
    return verifyMutable(signature, seq, value, publicKey)
  }

  static signAnnounce(target, token, id, ann, keyPair) {
    return sign(annSignable(target, token, id, ann, NS.ANNOUNCE), keyPair)
  }

  static signUnannounce(target, token, id, ann, keyPair) {
    return sign(annSignable(target, token, id, ann, NS.UNANNOUNCE), keyPair)
  }
}

function verifyMutable(signature, seq, value, publicKey) {
  const signable = b4a.allocUnsafe(32 + 32)
  const hash = signable.subarray(32)

  signable.set(NS.MUTABLE_PUT, 0)

  sodium.crypto_generichash(hash, c.encode(m.mutableSignable, { seq, value }))
  return sodium.crypto_sign_verify_detached(signature, signable, publicKey)
}

function annSignable(target, token, id, ann, ns) {
  const signable = b4a.allocUnsafe(32 + 32)
  const hash = signable.subarray(32)

  signable.set(ns, 0)

  sodium.crypto_generichash_batch(hash, [
    target,
    id,
    token,
    c.encode(m.peer, ann.peer), // note that this is the partial encoding of the announce message so we could just use that for perf
    ann.refresh || EMPTY
  ])

  return signable
}

function sign(signable, keyPair) {
  if (keyPair.sign) {
    return keyPair.sign(signable)
  }
  const secretKey = keyPair.secretKey ? keyPair.secretKey : keyPair
  const signature = b4a.allocUnsafe(64)
  sodium.crypto_sign_detached(signature, signable, secretKey)
  return signature
}

function decode(enc, val) {
  try {
    return val && c.decode(enc, val)
  } catch (err) {
    return null
  }
}
module.exports = class RawStreamSet {
  constructor(dht) {
    this._dht = dht

    this._prefix = 16 - 1 // 16 is the default stream-set side in udx
    this._streams = new Map()
  }

  get size() {
    return this._streams.size
  }

  [Symbol.iterator]() {
    return this._streams.values()
  }

  add(opts) {
    const self = this

    // TODO: we should prob have a udx helper for id generation, given the slight complexity
    // of the below. requires a PRNG in udx tho.

    let id = 0

    while (true) {
      id = (Math.random() * 0x100000000) >>> 0

      if (this._streams.has(id & this._prefix)) continue
      break
    }

    // always have ~50% change of rolling a free one
    if (2 * this._streams.size >= this._prefix) {
      // ie 0b11111 = 0b1111 + 1 + 0b1111
      this._prefix = 2 * this._prefix + 1

      // move the prefixes over
      const next = new Map()
      for (const stream of this._streams.values()) {
        next.set(stream.id & this._prefix, stream)
      }
      this._streams = next
    }

    const stream = this._dht.udx.createStream(id, opts)
    this._streams.set(id & this._prefix, stream)

    stream.on('close', onclose)

    return stream

    function onclose() {
      self._streams.delete(id & self._prefix)
    }
  }

  async clear() {
    const destroying = []

    for (const stream of this._streams.values()) {
      destroying.push(new Promise((resolve) => stream.once('close', resolve).destroy()))
    }

    await Promise.allSettled(destroying)
  }
}
const c = require('compact-encoding')
const Cache = require('xache')
const safetyCatch = require('safety-catch')
const b4a = require('b4a')
const { handshake, holepunch } = require('./messages')
const { COMMANDS } = require('./constants')
const { BAD_HANDSHAKE_REPLY, BAD_HOLEPUNCH_REPLY } = require('./errors')

const FROM_CLIENT = 0
const FROM_SERVER = 1
const FROM_RELAY = 2
const FROM_SECOND_RELAY = 3
const REPLY = 4

// TODO: While the current design is very trustless in regards to clients/servers trusting the DHT,
// we should add a bunch of rate limits everywhere, especially including here to avoid bad users
// using a DHT node to relay traffic indiscriminately using the connect/holepunch messages.
// That's mostly from an abuse POV as none of the messsages do amplication.

module.exports = class Router {
  constructor(dht, opts) {
    this.dht = dht
    this.forwards = new Cache(opts.forwards)
  }

  set(target, state) {
    if (state.onpeerhandshake) {
      this.forwards.retain(toString(target), state)
    } else {
      this.forwards.set(toString(target), state)
    }
  }

  get(target) {
    return this.forwards.get(toString(target))
  }

  delete(target) {
    this.forwards.delete(toString(target))
  }

  destroy() {
    this.forwards.destroy()
  }

  async peerHandshake(target, { noise, peerAddress, relayAddress, socket, session }, to) {
    const dht = this.dht

    const requestValue = c.encode(handshake, {
      mode: FROM_CLIENT,
      noise,
      peerAddress,
      relayAddress
    })

    const res = await dht.request(
      { command: COMMANDS.PEER_HANDSHAKE, target, value: requestValue },
      to,
      { socket, session }
    )

    const hs = decode(handshake, res.value)
    if (
      !hs ||
      hs.mode !== REPLY ||
      to.host !== res.from.host ||
      to.port !== res.from.port ||
      !hs.noise
    ) {
      throw BAD_HANDSHAKE_REPLY()
    }

    return {
      noise: hs.noise,
      relayed: !!hs.peerAddress,
      serverAddress: hs.peerAddress || to,
      clientAddress: res.to
    }
  }

  async onpeerhandshake(req) {
    const hs = req.value && decode(handshake, req.value)
    if (!hs) return

    const { mode, noise, peerAddress, relayAddress } = hs

    const state = req.target && this.get(req.target)
    const isServer = !!(state && state.onpeerhandshake)
    const relay = state && state.relay

    if (isServer) {
      let reply = null
      try {
        reply = noise && (await state.onpeerhandshake({ noise, peerAddress }, req))
      } catch (e) {
        safetyCatch(e)
        return
      }
      if (!reply || !reply.noise) return
      const opts = { socket: reply.socket, closerNodes: false, token: false }

      switch (mode) {
        case FROM_CLIENT: {
          req.reply(
            c.encode(handshake, { mode: REPLY, noise: reply.noise, peerAddress: null }),
            opts
          )
          return
        }
        case FROM_RELAY: {
          req.relay(
            c.encode(handshake, { mode: FROM_SERVER, noise: reply.noise, peerAddress }),
            req.from,
            opts
          )
          return
        }
        case FROM_SECOND_RELAY: {
          if (!relayAddress) return
          req.relay(
            c.encode(handshake, { mode: FROM_SERVER, noise: reply.noise, peerAddress }),
            relayAddress,
            opts
          )
          return // eslint-disable-line
        }
      }
    } else {
      switch (mode) {
        case FROM_CLIENT: {
          // TODO: if no relay is known route closer to the target instead of timing out
          if (!noise) return
          if (!relay && !relayAddress) {
            // help the user route
            req.reply(null, { token: false, closerNodes: true })
            return
          }
          req.relay(
            c.encode(handshake, {
              mode: FROM_RELAY,
              noise,
              peerAddress: req.from,
              relayAddress: null
            }),
            relayAddress || relay
          )
          return
        }
        case FROM_RELAY: {
          if (!relay || !noise) return
          req.relay(
            c.encode(handshake, {
              mode: FROM_SECOND_RELAY,
              noise,
              peerAddress,
              relayAddress: req.from
            }),
            relay
          )
          return
        }
        case FROM_SERVER: {
          if (!peerAddress || !noise) return
          req.reply(
            c.encode(handshake, { mode: REPLY, noise, peerAddress: req.from, relayAddress: null }),
            { to: peerAddress, closerNodes: false, token: false }
          )
          return // eslint-disable-line
        }
      }
    }
  }

  async peerHolepunch(target, { id, payload, peerAddress, socket, session }, to) {
    const dht = this.dht
    const requestValue = c.encode(holepunch, {
      mode: FROM_CLIENT,
      id,
      payload,
      peerAddress
    })

    const res = await dht.request(
      { command: COMMANDS.PEER_HOLEPUNCH, target, value: requestValue },
      to,
      { socket, session }
    )

    const hp = decode(holepunch, res.value)
    if (!hp || hp.mode !== REPLY || to.host !== res.from.host || to.port !== res.from.port) {
      throw BAD_HOLEPUNCH_REPLY()
    }

    return {
      from: res.from,
      to: res.to,
      payload: hp.payload,
      peerAddress: hp.peerAddress || to
    }
  }

  async onpeerholepunch(req) {
    const hp = req.value && decode(holepunch, req.value)
    if (!hp) return

    const { mode, id, payload, peerAddress } = hp

    const state = req.target && this.get(req.target)
    const isServer = !!(state && state.onpeerholepunch)
    const relay = state && state.relay

    switch (mode) {
      case FROM_CLIENT: {
        if (!peerAddress && !relay) return
        req.relay(
          c.encode(holepunch, { mode: FROM_RELAY, id, payload, peerAddress: req.from }),
          peerAddress || relay
        )
        return
      }
      case FROM_RELAY: {
        if (!isServer || !peerAddress) return
        let reply = null
        try {
          reply = await state.onpeerholepunch({ id, payload, peerAddress }, req)
        } catch (e) {
          safetyCatch(e)
          return
        }
        if (!reply) return
        const opts = { socket: reply.socket, closerNodes: false, token: false }
        req.relay(
          c.encode(holepunch, { mode: FROM_SERVER, id: 0, payload: reply.payload, peerAddress }),
          req.from,
          opts
        )
        return
      }
      case FROM_SERVER: {
        req.reply(c.encode(holepunch, { mode: REPLY, id, payload, peerAddress: req.from }), {
          to: peerAddress,
          closerNodes: false,
          token: false
        })
        return // eslint-disable-line
      }
    }
  }
}

function decode(enc, val) {
  try {
    return c.decode(enc, val)
  } catch {
    return null
  }
}

function toString(t) {
  return typeof t === 'string' ? t : b4a.toString(t, 'hex')
}
const sodium = require('sodium-universal')
const b4a = require('b4a')
const { holepunchPayload } = require('./messages')

module.exports = class HolepunchPayload {
  constructor(holepunchSecret) {
    this._sharedSecret = holepunchSecret
    this._localSecret = b4a.allocUnsafe(32)

    sodium.randombytes_buf(this._localSecret)
  }

  decrypt(buffer) {
    const state = { start: 24, end: buffer.byteLength - 16, buffer }

    if (state.end <= state.start) return null

    const nonce = buffer.subarray(0, 24)
    const msg = state.buffer.subarray(state.start, state.end)
    const cipher = state.buffer.subarray(state.start)

    if (!sodium.crypto_secretbox_open_easy(msg, cipher, nonce, this._sharedSecret)) return null

    try {
      return holepunchPayload.decode(state)
    } catch {
      return null
    }
  }

  encrypt(payload) {
    const state = { start: 24, end: 24, buffer: null }
    holepunchPayload.preencode(state, payload)
    state.buffer = b4a.allocUnsafe(state.end + 16)

    const nonce = state.buffer.subarray(0, 24)
    const msg = state.buffer.subarray(state.start, state.end)
    const cipher = state.buffer.subarray(state.start)

    holepunchPayload.encode(state, payload)
    sodium.randombytes_buf(nonce)
    sodium.crypto_secretbox_easy(cipher, msg, nonce, this._sharedSecret)

    return state.buffer
  }

  token(addr) {
    const out = b4a.allocUnsafe(32)
    sodium.crypto_generichash(out, b4a.from(addr.host), this._localSecret)
    return out
  }
}
const DONE = Promise.resolve(true)
const DESTROYED = Promise.resolve(false)

module.exports = class Semaphore {
  constructor(limit = 1) {
    this.limit = limit
    this.active = 0
    this.waiting = []

    this.flushedPromise = null
    this.flushedResolve = null

    this.destroyed = false

    this._onwait = this._queueWaiting.bind(this)
    this._onflush = this._queueFlushed.bind(this)
  }

  _queueWaiting(resolve) {
    this.waiting.push(resolve)
  }

  _queueFlushed(resolve) {
    this.flushedResolve = resolve
  }

  wait() {
    if (this.destroyed === true) return DESTROYED

    if (this.active < this.limit && this.waiting.length === 0) {
      this.active++
      return DONE
    }

    return new Promise(this._onwait)
  }

  signal() {
    if (this.destroyed === true) return

    this.active--
    while (this.active < this.limit && this.waiting.length > 0 && this.destroyed === false) {
      this.active++
      this.waiting.shift()(true)
    }

    if (this.active === 0 && this.flushedResolve) {
      const resolve = this.flushedResolve
      this.flushedResolve = null
      this.flushedPromise = null
      resolve(true)
    }
  }

  async flush() {
    if (this.destroyed === true) return
    if (this.active === 0) return
    if (this.flushedPromise) return this.flushedPromise
    this.flushedPromise = new Promise(this._onflush)
    return this.flushedPromise
  }

  destroy() {
    this.destroyed = true
    this.active = 0
    while (this.waiting.length) this.waiting.pop()(false)
    if (this.flushedResolve) this.flushedResolve(false)
  }
}
const { EventEmitter } = require('events')
const safetyCatch = require('safety-catch')
const NoiseSecretStream = require('@hyperswarm/secret-stream')
const b4a = require('b4a')
const relay = require('blind-relay')
const NoiseWrap = require('./noise-wrap')
const Announcer = require('./announcer')
const { FIREWALL, ERROR } = require('./constants')
const { unslabbedHash } = require('./crypto')
const SecurePayload = require('./secure-payload')
const Holepuncher = require('./holepuncher')
const { isPrivate } = require('bogon')
const { ALREADY_LISTENING, NODE_DESTROYED, KEYPAIR_ALREADY_USED } = require('./errors')

const HANDSHAKE_CLEAR_WAIT = 10000
const HANDSHAKE_INITIAL_TIMEOUT = 10000

module.exports = class Server extends EventEmitter {
  constructor(dht, opts = {}) {
    super()

    this.dht = dht
    this.target = null

    this.closed = false
    this.firewall = opts.firewall || (() => false)
    this.holepunch = opts.holepunch || (() => true)
    this.relayThrough = opts.relayThrough || null
    this.relayKeepAlive = opts.relayKeepAlive || 5000
    this.pool = opts.pool || null
    this.createHandshake = opts.createHandshake || defaultCreateHandshake
    this.createSecretStream = opts.createSecretStream || defaultCreateSecretStream
    this.suspended = false
    this.handshakeClearWait = opts.handshakeClearWait || HANDSHAKE_CLEAR_WAIT

    this._shareLocalAddress = opts.shareLocalAddress !== false
    this._reusableSocket = !!opts.reusableSocket
    this._neverPunch = opts.holepunch === false // useful for fully disabling punching
    this._keyPair = null
    this._announcer = null
    this._connects = new Map()
    this._holepunches = []
    this._listening = null
    this._closing = null
  }

  get listening() {
    return this._listening !== null
  }

  get publicKey() {
    return this._keyPair && this._keyPair.publicKey
  }

  get relayAddresses() {
    return this._announcer ? this._announcer.relayAddresses : []
  }

  onconnection(encryptedSocket) {
    this.emit('connection', encryptedSocket)
  }

  async suspend({ log = noop } = {}) {
    log('Suspending hyperdht server')
    if (this._listening !== null) await this._listening
    log('Suspending hyperdht server (post listening)')
    this.suspended = true
    this._clearAll()
    return this._announcer ? this._announcer.suspend({ log }) : Promise.resolve()
  }

  async resume() {
    if (this._listening !== null) await this._listening
    this.suspended = false
    return this._announcer ? this._announcer.resume() : Promise.resolve()
  }

  address() {
    if (!this._keyPair) return null

    return {
      publicKey: this._keyPair.publicKey,
      host: this.dht.host,
      port: this.dht.port
    }
  }

  close() {
    if (this._closing) return this._closing
    this._closing = this._close()
    return this._closing
  }

  _gc() {
    this.dht.listening.delete(this)
    if (this.target) this.dht._router.delete(this.target)
  }

  async _stopListening() {
    try {
      if (this._announcer) await this._announcer.stop()
    } catch {
      // ignore
    }

    this._announcer = null
    this._listening = null
    this._keyPair = null
  }

  async _close() {
    if (this._listening === null) {
      this.closed = true
      this.emit('close')
      return
    }

    try {
      await this._listening
    } catch (err) {
      safetyCatch(err)
    }

    this._gc()
    this._clearAll()

    await this._stopListening()

    this.closed = true
    this.emit('close')
  }

  _clearAll() {
    while (this._holepunches.length > 0) {
      const h = this._holepunches.pop()
      if (h && h.puncher) h.puncher.destroy()
      if (h && h.clearing) clearTimeout(h.clearing)
      if (h && h.prepunching) clearTimeout(h.prepunching)
      if (h && h.rawStream) h.rawStream.destroy()
    }

    this._connects.clear()
  }

  async listen(keyPair = this.dht.defaultKeyPair, opts = {}) {
    if (this._listening !== null) throw ALREADY_LISTENING()
    if (this.dht.destroyed) throw NODE_DESTROYED()

    this._listening = this._listen(keyPair, opts)
    await this._listening
    return this
  }

  async _listen(keyPair, opts) {
    // From now on, the DHT object which created me is responsible for closing me
    this.dht.listening.add(this)

    try {
      await this.dht.bind()
      if (this._closing) return

      for (const s of this.dht.listening) {
        if (s._keyPair && b4a.equals(s._keyPair.publicKey, keyPair.publicKey)) {
          throw KEYPAIR_ALREADY_USED()
        }
      }

      this.target = unslabbedHash(keyPair.publicKey)
      this._keyPair = keyPair
      this._announcer = new Announcer(this.dht, keyPair, this.target, opts)

      this.dht._router.set(this.target, {
        relay: null,
        record: this._announcer.record,
        onpeerhandshake: this._onpeerhandshake.bind(this),
        onpeerholepunch: this._onpeerholepunch.bind(this)
      })

      // warm it up for now
      this._localAddresses().catch(safetyCatch)

      await this._announcer.start()
    } catch (err) {
      await this._stopListening()
      this._gc()
      throw err
    }

    if (this._closing) return
    if (this.suspended) await this._announcer.suspend()

    if (this._closing) return
    if (this.dht.destroyed) throw NODE_DESTROYED()

    if (this.pool) this.pool._attachServer(this)

    this.emit('listening')
  }

  refresh() {
    if (this._announcer && !this.suspended) this._announcer.refresh()
  }

  notifyOnline() {
    if (this._announcer) this._announcer.online.notify()
  }

  _localAddresses() {
    return this.dht.validateLocalAddresses(Holepuncher.localAddresses(this.dht.io.serverSocket))
  }

  async _addHandshake(k, noise, clientAddress, { from, to: serverAddress, socket }, direct) {
    let id = this._holepunches.indexOf(null)
    if (id === -1) id = this._holepunches.push(null) - 1

    const hs = {
      round: 0,
      reply: null,
      puncher: null,
      payload: null,
      rawStream: null,
      encryptedSocket: null,
      prepunching: null,
      firewalled: true,
      clearing: null,
      onsocket: null,
      aborted: false,

      // Relay state
      relayTimeout: null,
      relayToken: null,
      relaySocket: null,
      relayClient: null,
      relayPaired: false
    }

    this._holepunches[id] = hs

    const handshake = this.createHandshake(this._keyPair, null)

    let remotePayload
    try {
      remotePayload = await handshake.recv(noise)
    } catch (err) {
      safetyCatch(err)
      this._clearLater(hs, id, k)
      return null
    }

    if (this._closing || this.suspended) return null

    try {
      hs.firewalled = await this.firewall(handshake.remotePublicKey, remotePayload, clientAddress)
    } catch (err) {
      safetyCatch(err)
    }

    if (this._closing || this.suspended) return null

    if (hs.firewalled) {
      this._clearLater(hs, id, k)
      return null
    }

    const error =
      remotePayload.version === 1
        ? remotePayload.udx
          ? ERROR.NONE
          : ERROR.ABORTED
        : ERROR.VERSION_MISMATCH

    const addresses = []
    const ourRemoteAddr = this.dht.remoteAddress()
    const ourLocalAddrs = this._shareLocalAddress ? await this._localAddresses() : null

    if (this._closing || this.suspended) return null

    if (ourRemoteAddr) addresses.push(ourRemoteAddr)
    if (ourLocalAddrs) addresses.push(...ourLocalAddrs)

    if (error === ERROR.NONE) {
      hs.rawStream = this.dht.createRawStream({
        framed: true,
        firewall(socket, port, host) {
          if (!(port > 0 && port < 65536)) return true

          // Check if the traffic originated from the socket on which we're expecting relay traffic. If so,
          // we haven't hole punched yet and the other side is just sending us traffic through the relay.
          if (hs.relaySocket && isRelay(hs.relaySocket, socket, port, host)) {
            return false
          }

          hs.onsocket(socket, port, host)
          return false
        }
      })

      hs.rawStream.on('error', autoDestroy)

      // Handles the case where onsocket is never called, but the stream got setup
      // This can happen on a relayed connection which never connects directly
      // (onsocket is called there only when the direct connection is established)
      const onrawstreamclose = () => {
        if (this._closing) return
        this._clearLater(hs, id, k)
      }
      hs.rawStream.on('close', onrawstreamclose)

      hs.onsocket = (socket, port, host) => {
        if (hs.rawStream === null) return // Already hole punched

        this._clearLater(hs, id, k)

        if (hs.prepunching) {
          clearTimeout(hs.prepunching)
          hs.prepunching = null
        }

        if (this._reusableSocket && remotePayload.udx.reusableSocket) {
          this.dht._socketPool.routes.add(handshake.remotePublicKey, hs.rawStream)
        }

        hs.rawStream.removeListener('error', autoDestroy)
        hs.rawStream.removeListener('close', onrawstreamclose)

        if (hs.rawStream.connected) {
          const remoteChanging = hs.rawStream.changeRemote(socket, remotePayload.udx.id, port, host)

          if (remoteChanging) remoteChanging.catch(safetyCatch)
        } else {
          hs.rawStream.connect(socket, remotePayload.udx.id, port, host)
          hs.encryptedSocket = this.createSecretStream(false, hs.rawStream, {
            handshake: h,
            keepAlive: this.dht.connectionKeepAlive
          })

          this.onconnection(hs.encryptedSocket)
        }

        if (hs.puncher) {
          hs.puncher.onabort = noop
          hs.puncher.destroy()
        }

        hs.rawStream = null
      }

      function autoDestroy() {
        if (hs.puncher) hs.puncher.destroy()
      }
    }

    const relayAddresses = this.relayAddresses
    const relayThrough = selectRelay(this.relayThrough)

    if (relayThrough) hs.relayToken = relay.token()

    try {
      hs.reply = await handshake.send({
        error,
        firewall: ourRemoteAddr ? FIREWALL.OPEN : FIREWALL.UNKNOWN,
        holepunch: ourRemoteAddr ? null : { id, relays: this._announcer.relays },
        addresses4: addresses,
        addresses6: null,
        udx: {
          reusableSocket: this._reusableSocket,
          id: hs.rawStream ? hs.rawStream.id : 0,
          seq: 0
        },
        secretStream: {},
        relayThrough: relayThrough ? { publicKey: relayThrough, token: hs.relayToken } : null,
        relayAddresses: relayAddresses.length ? relayAddresses : null
      })
    } catch (err) {
      safetyCatch(err)
      if (hs.rawStream) hs.rawStream.destroy()
      this._clearLater(hs, id, k)
      return null
    }

    if (this._closing || this.suspended) {
      if (hs.rawStream) hs.rawStream.destroy()
      return null
    }

    const h = handshake.final()

    if (error !== ERROR.NONE) {
      if (hs.rawStream) hs.rawStream.destroy()
      this._clearLater(hs, id, k)
      return hs
    }

    if (remotePayload.firewall === FIREWALL.OPEN || direct) {
      const sock = direct ? socket : this.dht.socket
      this.dht.stats.punches.open++
      hs.onsocket(sock, clientAddress.port, clientAddress.host)
      return hs
    }

    if (relayThrough || remotePayload.relayThrough) {
      this._relayConnection(hs, relayThrough, remotePayload, h)
    }

    const onabort = () => {
      hs.aborted = true
      if (hs.prepunching) clearTimeout(hs.prepunching)
      hs.prepunching = null
      if (hs.rawStream.destroyed) {
        this._clearLater(hs, id, k)
        return
      }

      hs.rawStream.on('close', () => this._clearLater(hs, id, k))
      if (hs.relayToken === null) hs.rawStream.destroy()
    }

    if (!direct && clientAddress.host === serverAddress.host) {
      const clientAddresses = remotePayload.addresses4.filter(onlyPrivateHosts)

      if (clientAddresses.length > 0 && this._shareLocalAddress) {
        const myAddresses = await this._localAddresses()
        const addr = Holepuncher.matchAddress(myAddresses, clientAddresses)

        if (addr) {
          hs.prepunching = setTimeout(onabort, HANDSHAKE_INITIAL_TIMEOUT)
          return hs
        }
      }
    }

    if (this._closing || this.suspended) return null

    if (ourRemoteAddr || this._neverPunch) {
      hs.prepunching = setTimeout(onabort, HANDSHAKE_INITIAL_TIMEOUT)
      return hs
    }

    hs.payload = new SecurePayload(h.holepunchSecret)
    hs.puncher = new Holepuncher(this.dht, this.dht.session(), false, remotePayload.firewall)

    hs.puncher.onconnect = hs.onsocket
    hs.puncher.onabort = onabort
    hs.prepunching = setTimeout(hs.puncher.destroy.bind(hs.puncher), HANDSHAKE_INITIAL_TIMEOUT)

    return hs
  }

  _clearLater(hs, id, k) {
    if (hs.clearing) return
    hs.clearing = setTimeout(() => this._clear(hs, id, k), this.handshakeClearWait)
  }

  _clear(hs, id, k) {
    if (id >= this._holepunches.length || this._holepunches[id] !== hs) return
    if (hs.clearing) clearTimeout(hs.clearing)

    this._holepunches[id] = null
    while (
      this._holepunches.length > 0 &&
      this._holepunches[this._holepunches.length - 1] === null
    ) {
      this._holepunches.pop()
    }
    this._connects.delete(k)
  }

  async _onpeerhandshake({ noise, peerAddress }, req) {
    const k = b4a.toString(noise, 'hex')

    // The next couple of statements MUST run within the same tick to prevent
    // a malicious peer from flooding us with handshakes.
    let p = this._connects.get(k)
    if (!p) {
      p = this._addHandshake(k, noise, peerAddress || req.from, req, !peerAddress)
      this._connects.set(k, p)
    }

    const h = await p
    if (!h) return null

    if (this._closing !== null || this.suspended) return null

    return { socket: h.puncher && h.puncher.socket, noise: h.reply }
  }

  async _onpeerholepunch({ id, peerAddress, payload }, req) {
    const h = id < this._holepunches.length ? this._holepunches[id] : null
    if (!h) return null

    if (!peerAddress || this._closing !== null || this.suspended) return null

    const p = h.puncher
    if (!p || !p.socket) return this._abort(h) // not opened

    const remotePayload = h.payload.decrypt(payload)
    if (!remotePayload) return null

    const isServerRelay = this._announcer.isRelay(req.from)
    const { error, firewall, round, punching, addresses, remoteAddress, remoteToken } =
      remotePayload

    if (error !== ERROR.NONE) {
      // We actually do not need to set the round here, but just do it for consistency.
      if (round >= h.round) h.round = round
      return this._abort(h)
    }

    const token = h.payload.token(peerAddress)
    const echoed = isServerRelay && !!remoteToken && b4a.equals(token, remoteToken)

    // Update our heuristics here
    if (req.socket === p.socket) {
      p.nat.add(req.to, req.from)
    }

    if (round >= h.round) {
      h.round = round
      p.updateRemote({ punching, firewall, addresses, verified: echoed ? peerAddress.host : null })
    }

    // Wait for the analyzer to reach a conclusion...
    let stable = await p.analyze(false)
    if (p.destroyed) return null

    if (!p.remoteHolepunching && !stable) {
      stable = await p.analyze(true)
      if (p.destroyed) return null
      if (!stable) return this._abort(h)
    }

    // Fast mode! If we are consistent and the remote has opened a session to us (remoteAddress)
    // then fire a quick punch back. Note the await here just waits for the udp socket to flush.
    if (
      isConsistent(p.nat.firewall) &&
      remoteAddress &&
      hasSameAddr(p.nat.addresses, remoteAddress)
    ) {
      await p.ping(peerAddress)
      if (p.destroyed) return null
    }

    // Remote said they are punching (or willing to), so we will punch as well.
    // Note that this returns when the punching has STARTED, so no guarantee
    // we will have a connection after this promise etc.
    if (p.remoteHolepunching) {
      // TODO: still continue here if a local connection might work, but then do not holepunch...
      if (!this.holepunch(p.remoteFirewall, p.nat.firewall, p.remoteAddresses, p.nat.addresses)) {
        return p.destroyed ? null : this._abort(h)
      }

      if (h.prepunching) {
        clearTimeout(h.prepunching)
        h.prepunching = null
      }

      if (p.remoteFirewall >= FIREWALL.RANDOM || p.nat.firewall >= FIREWALL.RANDOM) {
        if (
          this.dht._randomPunches >= this.dht._randomPunchLimit ||
          Date.now() - this.dht._lastRandomPunch < this.dht._randomPunchInterval
        ) {
          if (!h.relayToken) return this._abort(h, ERROR.TRY_LATER)
          return {
            socket: p.socket,
            payload: h.payload.encrypt({
              error: ERROR.TRY_LATER,
              firewall: p.nat.firewall,
              round: h.round,
              connected: p.connected,
              punching: p.punching,
              addresses: p.nat.addresses,
              remoteAddress: null,
              token: isServerRelay ? token : null,
              remoteToken: remotePayload.token
            })
          }
        }
      }

      const punching = await p.punch()
      if (p.destroyed) return null
      if (!punching) return this._abort(h)
    }

    // Freeze that analysis as soon as we have a result we are giving to the other peer
    if (p.nat.firewall !== FIREWALL.UNKNOWN) {
      p.nat.freeze()
    }

    return {
      socket: p.socket,
      payload: h.payload.encrypt({
        error: ERROR.NONE,
        firewall: p.nat.firewall,
        round: h.round,
        connected: p.connected,
        punching: p.punching,
        addresses: p.nat.addresses,
        remoteAddress: null,
        token: isServerRelay ? token : null,
        remoteToken: remotePayload.token
      })
    }
  }

  _abort(h, error = ERROR.ABORTED) {
    if (!h.payload) {
      if (h.puncher) h.puncher.destroy()
      return null
    }

    const payload = h.payload.encrypt({
      error,
      firewall: FIREWALL.UNKNOWN,
      round: h.round,
      connected: false,
      punching: false,
      addresses: null,
      remoteAddress: null,
      token: null,
      remoteToken: null
    })

    h.puncher.destroy()

    return { socket: this.dht.socket, payload }
  }

  _relayConnection(hs, relayThrough, remotePayload, h) {
    this.dht.stats.relaying.attempts++

    let isInitiator
    let publicKey
    let token

    if (relayThrough) {
      isInitiator = true
      publicKey = relayThrough
      token = hs.relayToken
    } else {
      isInitiator = false
      publicKey = remotePayload.relayThrough.publicKey
      token = remotePayload.relayThrough.token
    }

    hs.relayToken = token
    hs.relaySocket = this.dht.connect(publicKey)
    hs.relaySocket.setKeepAlive(this.relayKeepAlive)
    hs.relayClient = relay.Client.from(hs.relaySocket, { id: hs.relaySocket.publicKey })
    hs.relayTimeout = setTimeout(onabort, 15000)

    hs.relayClient
      .pair(isInitiator, token, hs.rawStream)
      .on('error', onabort)
      .on('data', (remoteId) => {
        if (hs.relayTimeout) clearRelayTimeout(hs)
        if (hs.rawStream === null) {
          onabort(null)
          return
        }

        hs.relayPaired = true
        this.dht.stats.relaying.successes++

        if (hs.prepunching) clearTimeout(hs.prepunching)
        hs.prepunching = null

        const { remotePort, remoteHost, socket } = hs.relaySocket.rawStream

        hs.rawStream
          .on('close', () => hs.relaySocket.destroy())
          .connect(socket, remoteId, remotePort, remoteHost)

        hs.encryptedSocket = this.createSecretStream(false, hs.rawStream, { handshake: h })

        this.onconnection(hs.encryptedSocket)
      })

    const dht = this.dht
    function onabort() {
      if (!hs.relayPaired) dht.stats.relaying.aborts++
      if (hs.relayTimeout) clearRelayTimeout(hs)
      const socket = hs.relaySocket
      hs.relayToken = null
      hs.relaySocket = null
      if (socket) socket.destroy()
      if (hs.aborted && hs.rawStream) hs.rawStream.destroy()
    }
  }
}

function clearRelayTimeout(hs) {
  clearTimeout(hs.relayTimeout)
  hs.relayTimeout = null
}

function isConsistent(fw) {
  return fw === FIREWALL.OPEN || fw === FIREWALL.CONSISTENT
}

function hasSameAddr(addrs, other) {
  if (addrs === null) return false

  for (const addr of addrs) {
    if (addr.port === other.port && addr.host === other.host) return true
  }
  return false
}

function defaultCreateHandshake(keyPair, remotePublicKey) {
  return new NoiseWrap(keyPair, remotePublicKey)
}

function defaultCreateSecretStream(isInitiator, rawStream, opts) {
  return new NoiseSecretStream(isInitiator, rawStream, opts)
}

function onlyPrivateHosts(addr) {
  return isPrivate(addr.host)
}

function isRelay(relaySocket, socket, port, host) {
  const stream = relaySocket.rawStream
  if (!stream) return false
  if (stream.socket !== socket) return false
  return port === stream.remotePort && host === stream.remoteHost
}

function selectRelay(relayThrough) {
  if (typeof relayThrough === 'function') relayThrough = relayThrough()
  if (relayThrough === null) return null
  if (Array.isArray(relayThrough)) {
    return relayThrough[Math.floor(Math.random() * relayThrough.length)]
  }
  return relayThrough
}

function noop() {}
module.exports = class Sleeper {
  constructor() {
    this._timeout = null
    this._resolve = null

    this._start = (resolve) => {
      this._resolve = resolve
    }

    this._trigger = () => {
      if (this._resolve === null) return
      const resolve = this._resolve
      this._timeout = null
      this._resolve = null
      resolve()
    }
  }

  pause(ms) {
    const p = new Promise(this._start)
    if (this._timeout !== null) {
      clearTimeout(this._timeout)
      this._trigger()
    }
    this._timeout = setTimeout(this._trigger, ms)
    return p
  }

  resume() {
    if (this._timeout !== null) {
      clearTimeout(this._timeout)
      this._trigger()
    }
  }
}
const b4a = require('b4a')

const LINGER_TIME = 3000

module.exports = class SocketPool {
  constructor(dht, host) {
    this._dht = dht
    this._sockets = new Map()
    this._lingering = new Set() // updated by the ref
    this._host = host

    this.routes = new SocketRoutes(this)
  }

  _onmessage(ref, data, address) {
    this._dht.onmessage(ref.socket, data, address)
  }

  _add(ref) {
    this._sockets.set(ref.socket, ref)
  }

  _remove(ref) {
    this._sockets.delete(ref.socket)
    this._lingering.delete(ref)
  }

  lookup(socket) {
    return this._sockets.get(socket) || null
  }

  setReusable(socket, bool) {
    const ref = this.lookup(socket)
    if (ref) ref.reusable = bool
  }

  acquire() {
    // TODO: Enable socket reuse
    return new SocketRef(this)
  }

  async destroy() {
    const closing = []

    for (const ref of this._sockets.values()) {
      ref._unlinger()
      closing.push(ref.socket.close())
    }

    await Promise.allSettled(closing)
  }
}

class SocketRoutes {
  constructor(pool) {
    this._pool = pool
    this._routes = new Map()
  }

  add(publicKey, rawStream) {
    if (rawStream.socket) this._onconnect(publicKey, rawStream)
    else rawStream.on('connect', this._onconnect.bind(this, publicKey, rawStream))
  }

  get(publicKey) {
    const id = b4a.toString(publicKey, 'hex')
    const route = this._routes.get(id)
    if (!route) return null
    return route
  }

  _onconnect(publicKey, rawStream) {
    const id = b4a.toString(publicKey, 'hex')
    const socket = rawStream.socket

    let route = this._routes.get(id)

    if (!route) {
      const gc = () => {
        if (this._routes.get(id) === route) this._routes.delete(id)
        socket.removeListener('close', gc)
      }

      route = {
        socket,
        address: { host: rawStream.remoteHost, port: rawStream.remotePort },
        gc
      }

      this._routes.set(id, route)
      socket.on('close', gc)
    }

    this._pool.setReusable(socket, true)

    rawStream.on('error', () => {
      this._pool.setReusable(socket, false)
      if (!route) route = this._routes.get(id)
      if (route && route.socket === socket) route.gc()
    })
  }
}

// TODO: we should just make some "user data" object on udx to allow to attach this info
class SocketRef {
  constructor(pool) {
    this._pool = pool

    // Events
    this.onholepunchmessage = noop

    // Whether it should teardown immediately or wait a bit
    this.reusable = false

    this.socket = pool._dht.udx.createSocket()
    this.socket
      .on('close', this._onclose.bind(this))
      .on('message', this._onmessage.bind(this))
      .on('idle', this._onidle.bind(this))
      .on('busy', this._onbusy.bind(this))
      .bind(0, this._pool._host)

    this._refs = 1
    this._released = false
    this._closed = false

    this._timeout = null
    this._wasBusy = false

    this._pool._add(this)
  }

  _onclose() {
    this._pool._remove(this)
  }

  _onmessage(data, address) {
    if (data.byteLength > 1) {
      this._pool._onmessage(this, data, address)
    } else {
      this.onholepunchmessage(data, address, this)
    }
  }

  _onidle() {
    this._closeMaybe()
  }

  _onbusy() {
    this._wasBusy = true
    this._unlinger()
  }

  _reset() {
    this.onholepunchmessage = noop
  }

  _closeMaybe() {
    if (this._refs === 0 && this.socket.idle && !this._timeout) this._close()
  }

  _lingeringClose() {
    this._pool._lingering.delete(this)
    this._timeout = null
    this._closeMaybe()
  }

  _close() {
    this._unlinger()

    if (this.reusable && this._wasBusy) {
      this._wasBusy = false
      this._pool._lingering.add(this)
      this._timeout = setTimeout(this._lingeringClose.bind(this), LINGER_TIME)
      return
    }

    this._closed = true
    this.socket.close()
  }

  _unlinger() {
    if (this._timeout !== null) {
      clearTimeout(this._timeout)
      this._pool._lingering.delete(this)
      this._timeout = null
    }
  }

  get free() {
    return this._refs === 0
  }

  active() {
    this._refs++
    this._unlinger()
  }

  inactive() {
    this._refs--
    this._closeMaybe()
  }

  address() {
    return this.socket.address()
  }

  release() {
    if (this._released) return

    this._released = true
    this._reset()

    this._refs--
    this._closeMaybe()
  }
}

function noop() {}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return uint24.decode(state) + 0x1000000 * uint32.decode(state)
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return uint32.decode(state) + 0x100000000 * uint32.decode(state)
  }
})

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "2.19.2",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    if (b.byteLength === 0) return null
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "hyperdht",
  "version": "6.31.0",
  "description": "The DHT powering Hyperswarm",
  "main": "index.js",
  "browser": "browser.js",
  "bin": {
    "hyperdht": "./bin.js"
  },
  "files": [
    "index.js",
    "browser.js",
    "testnet.js",
    "bin.js",
    "lib/**.js"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    },
    "child_process": {
      "bare": "bare-node-child-process",
      "default": "child_process"
    }
  },
  "dependencies": {
    "@hyperswarm/secret-stream": "^6.6.2",
    "b4a": "^1.3.1",
    "bare-events": "^2.2.0",
    "blind-relay": "^1.3.0",
    "bogon": "^1.0.0",
    "compact-encoding": "^2.4.1",
    "dht-rpc": "^6.15.1",
    "hypercore-crypto": "^3.3.0",
    "hypercore-id-encoding": "^1.2.0",
    "hyperdht-address": "^1.0.1",
    "noise-curve-ed": "^2.0.0",
    "noise-handshake": "^4.0.0",
    "record-cache": "^1.1.1",
    "safety-catch": "^1.0.1",
    "signal-promise": "^1.0.3",
    "sodium-universal": "^5.0.1",
    "streamx": "^2.16.1",
    "unslab": "^1.3.0",
    "xache": "^1.1.0"
  },
  "devDependencies": {
    "bare-node-child-process": "^1.0.1",
    "brittle": "^3.0.0",
    "graceful-goodbye": "^1.3.0",
    "newline-decoder": "^1.0.2",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "test": "prettier --check . && node test/all.js",
    "test:bare": "bare test/all.js",
    "test:generate": "brittle -r test/all.js test/*.js",
    "integration": "brittle test/integration/*.js",
    "end-to-end": "brittle test/end-to-end/*.js"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "directories": {
    "lib": "lib",
    "test": "test"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/hyperdht.git"
  },
  "keywords": [],
  "bugs": {
    "url": "https://github.com/holepunchto/hyperdht/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperdht#readme"
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return uint24.decode(state) + 0x1000000 * uint32.decode(state)
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return uint32.decode(state) + 0x100000000 * uint32.decode(state)
  }
})

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "2.19.2",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    if (b.byteLength === 0) return null
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "hyperschema",
  "version": "1.20.1",
  "description": "Create registries of declarative compact-encoding schemas",
  "files": [
    "lib/*.js",
    "builder.mjs",
    "builder.cjs",
    "runtime.mjs",
    "runtime.cjs",
    "primitives.mjs",
    "primitives.cjs"
  ],
  "exports": {
    "./package": "./package.json",
    ".": {
      "import": "./builder.mjs",
      "default": "./builder.cjs"
    },
    "./runtime": {
      "import": "./runtime.mjs",
      "default": "./runtime.cjs"
    },
    "./primitives": {
      "import": "./primitives.mjs",
      "default": "./primitives.cjs"
    }
  },
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    }
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test/index.js",
    "test:bare": "prettier . --check && bare test/index.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/hyperschema.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/hyperschema/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperschema#readme",
  "dependencies": {
    "bare-fs": "^4.0.1",
    "compact-encoding": "^2.19.0",
    "generate-object-property": "^2.0.0",
    "generate-string": "^1.0.1"
  },
  "devDependencies": {
    "brittle": "^3.7.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "test-tmp": "^1.3.0"
  }
}
module.exports = {
  c: require('compact-encoding')
}
const { EventEmitter } = require('events')
const { getStreamError } = require('streamx')
const DHT = require('hyperdht')
const spq = require('shuffled-priority-queue')
const b4a = require('b4a')
const unslab = require('unslab')

const PeerInfo = require('./lib/peer-info')
const RetryTimer = require('./lib/retry-timer')
const ConnectionSet = require('./lib/connection-set')
const PeerDiscovery = require('./lib/peer-discovery')

const MAX_PEERS = 64
const MAX_PARALLEL = 3
const MAX_CLIENT_CONNECTIONS = Infinity // TODO: Change
const MAX_SERVER_CONNECTIONS = Infinity

const ERR_MISSING_TOPIC = 'Topic is required and must be a 32-byte buffer'
const ERR_DESTROYED = 'Swarm has been destroyed'
const ERR_DUPLICATE = 'Duplicate connection'
const ERR_FIREWALL = 'Peer is firewalled'

module.exports = class Hyperswarm extends EventEmitter {
  constructor(opts = {}) {
    super()
    const {
      seed,
      relayThrough,
      keyPair = DHT.keyPair(seed),
      maxPeers = MAX_PEERS,
      maxClientConnections = MAX_CLIENT_CONNECTIONS,
      maxServerConnections = MAX_SERVER_CONNECTIONS,
      maxParallel = MAX_PARALLEL,
      firewall = allowAll
    } = opts
    this.keyPair = keyPair

    this.dht =
      opts.dht ||
      new DHT({
        bootstrap: opts.bootstrap,
        nodes: opts.nodes,
        port: opts.port,
        deferRandomPunch: opts.deferRandomPunch,
        randomPunchInterval: opts.randomPunchInterval
      })
    this.server = this.dht.createServer(
      {
        firewall: this._handleFirewall.bind(this),
        relayThrough: this._maybeRelayConnection.bind(this),
        handshakeClearWait: opts.handshakeClearWait
      },
      this._handleServerConnection.bind(this)
    )

    this.destroyed = false
    this.suspended = false
    this.maxPeers = maxPeers
    this.maxClientConnections = maxClientConnections
    this.maxServerConnections = maxServerConnections
    this.maxParallel = maxParallel
    this.relayThrough = relayThrough ? toRelayFunction(relayThrough) : null

    this.connecting = 0
    this.connections = new Set()
    this.peers = new Map()
    this.explicitPeers = new Set()
    this.listening = null
    this.stats = {
      updates: 0,
      connects: {
        client: {
          opened: 0,
          closed: 0,
          attempted: 0
        },
        server: {
          // Note: there is no notion of 'attempts' for server connections
          opened: 0,
          closed: 0
        }
      },
      bannedPeers: 0
    }

    this._discovery = new Map()
    this._timer = new RetryTimer(this._requeue.bind(this), {
      backoffs: opts.backoffs,
      jitter: opts.jitter
    })
    this._queue = spq()

    this._allConnections = new ConnectionSet()
    this._pendingFlushes = []
    this._flushTick = 0

    this._drainingQueue = false
    this._clientConnections = 0
    this._serverConnections = 0
    this._firewall = firewall

    this.dht.on('network-change', this._handleNetworkChange.bind(this))
    this.dht.on('network-update', this._handleNetworkUpdate.bind(this))
    this.on('update', this._handleUpdate)
  }

  _maybeRelayConnection(force) {
    if (!this.relayThrough) return null
    return this.relayThrough(force, this)
  }

  _enqueue(peerInfo) {
    if (peerInfo.queued) return
    peerInfo.queued = true
    peerInfo._flushTick = this._flushTick
    this._queue.add(peerInfo)

    this._attemptClientConnections()
  }

  _requeue(batch) {
    if (this.suspended) return
    for (const peerInfo of batch) {
      peerInfo.waiting = false

      if (
        peerInfo._updatePriority() === false ||
        this._allConnections.has(peerInfo.publicKey) ||
        peerInfo.queued
      ) {
        continue
      }
      peerInfo.queued = true
      peerInfo._flushTick = this._flushTick
      this._queue.add(peerInfo)
    }

    this._attemptClientConnections()
  }

  _flushMaybe(peerInfo) {
    for (let i = 0; i < this._pendingFlushes.length; i++) {
      const flush = this._pendingFlushes[i]
      if (peerInfo._flushTick > flush.tick) continue
      if (--flush.missing > 0) continue
      flush.onflush(true)
      this._pendingFlushes.splice(i--, 1)
    }
  }

  _withinMaxPeers() {
    const e = this.explicitPeers.size
    const factor = e === 0 ? 1 : e < 2 ? 2 : e < 4 ? 3 : 4
    return factor * this._allConnections.size < this.maxPeers
  }

  _flushAllMaybe() {
    if (
      this.connecting > 0 ||
      (this._withinMaxPeers() && this._clientConnections < this.maxClientConnections)
    ) {
      return false
    }

    while (this._pendingFlushes.length) {
      const flush = this._pendingFlushes.pop()
      flush.onflush(true)
    }

    return true
  }

  _shouldConnectExplicit() {
    return !this.destroyed && !this.suspended && this.connecting < this.maxParallel
  }

  _shouldConnect() {
    return (
      !this.destroyed &&
      !this.suspended &&
      this.connecting < this.maxParallel &&
      this._withinMaxPeers() &&
      this._clientConnections < this.maxClientConnections
    )
  }

  _shouldRequeue(peerInfo) {
    if (this.suspended) return false
    if (peerInfo.explicit) return true
    for (const topic of peerInfo.topics) {
      if (this._discovery.has(b4a.toString(topic, 'hex')) && !this.destroyed) {
        return true
      }
    }
    return false
  }

  _connect(peerInfo, queued) {
    if (peerInfo.banned || this._allConnections.has(peerInfo.publicKey)) {
      if (queued) this._flushMaybe(peerInfo)
      return
    }

    // TODO: Support async firewalling at some point.
    if (this._handleFirewall(peerInfo.publicKey, null)) {
      if (queued) this._flushMaybe(peerInfo)
      return
    }

    const relayThrough = this._maybeRelayConnection(peerInfo.forceRelaying)
    const conn = this.dht.connect(peerInfo.publicKey, {
      relayAddresses: peerInfo.relayAddresses,
      keyPair: this.keyPair,
      relayThrough
    })
    this._allConnections.add(conn)

    this.stats.connects.client.attempted++

    this.connecting++
    this._clientConnections++
    let opened = false

    const onerror = (err) => {
      if (this.relayThrough && shouldForceRelaying(err.code)) {
        peerInfo.forceRelaying = true
        // Reset the attempts in order to fast connect to relay
        peerInfo.attempts = 0
      }
    }

    // Removed once a connection is opened
    conn.on('error', onerror)

    conn.on('open', () => {
      opened = true
      this.stats.connects.client.opened++

      this._connectDone()
      this.connections.add(conn)
      conn.removeListener('error', onerror)
      peerInfo._connected()
      peerInfo.client = true
      this.emit('connection', conn, peerInfo)
      if (queued) this._flushMaybe(peerInfo)

      this.emit('update')
    })
    conn.on('close', () => {
      if (!opened) this._connectDone()
      this.stats.connects.client.closed++

      const err = getStreamError(conn)
      if (shouldBan(err)) {
        this._banPeer(peerInfo, true, err)
      }

      this.connections.delete(conn)
      this._allConnections.delete(conn)
      this._clientConnections--
      peerInfo._disconnected()

      peerInfo.waiting = this._shouldRequeue(peerInfo) && this._timer.add(peerInfo)
      this._maybeDeletePeer(peerInfo)

      if (!opened && queued) this._flushMaybe(peerInfo)

      this._attemptClientConnections()

      this.emit('update')
    })

    this.emit('update')
  }

  _connectDone() {
    this.connecting--

    if (this.connecting < this.maxParallel) this._attemptClientConnections()
    if (this.connecting === 0) this._flushAllMaybe()
  }

  // Called when the PeerQueue indicates a connection should be attempted.
  _attemptClientConnections() {
    // Guard against re-entries - unsure if it still needed but doesn't hurt
    if (this._drainingQueue || this.suspended) return
    this._drainingQueue = true

    for (const peerInfo of this.explicitPeers) {
      if (!this._shouldConnectExplicit()) break
      if (
        peerInfo.attempts >= 5 ||
        Date.now() - peerInfo.disconnectedTime < peerInfo.attempts * 1000
      ) {
        continue
      }
      this._connect(peerInfo, false)
    }

    while (this._queue.length && this._shouldConnect()) {
      const peerInfo = this._queue.shift()
      peerInfo.queued = false
      this._connect(peerInfo, true)
    }
    this._drainingQueue = false
    if (this.connecting === 0) this._flushAllMaybe()
  }

  _handleFirewall(remotePublicKey, payload) {
    if (b4a.equals(remotePublicKey, this.keyPair.publicKey)) return true

    let peerInfo = this.peers.get(b4a.toString(remotePublicKey, 'hex'))
    if (peerInfo && peerInfo.banned) return true

    const firewalled = this._firewall(remotePublicKey, payload)
    if (firewalled) {
      if (!peerInfo) peerInfo = this._upsertPeer(remotePublicKey)
      this._banPeer(peerInfo, true, new Error(ERR_FIREWALL))
    }

    return firewalled
  }

  _handleServerConnectionSwap(existing, conn) {
    let closed = false

    existing.on('close', () => {
      if (closed) return

      conn.removeListener('error', noop)
      conn.removeListener('close', onclose)

      this._handleServerConnection(conn)
    })

    conn.on('error', noop)
    conn.on('close', onclose)

    function onclose() {
      closed = true
    }
  }

  // Called when the DHT receives a new server connection.
  _handleServerConnection(conn) {
    if (this.destroyed || this.suspended) {
      // TODO: Investigate why a final server connection can be received after close
      conn.on('error', noop)
      return conn.destroy(ERR_DESTROYED)
    }

    const existing = this._allConnections.get(conn.remotePublicKey)

    if (existing) {
      // If both connections are from the same peer,
      // - pick the new one if the existing stream is already established (has sent and received bytes),
      //   because the other client must have lost that connection and be reconnecting
      // - otherwise, pick the one thats expected to initiate in a tie break
      const existingIsOutdated = existing.rawBytesRead > 0 && existing.rawBytesWritten > 0
      const expectedInitiator = b4a.compare(conn.publicKey, conn.remotePublicKey) > 0
      const keepNew = existingIsOutdated || expectedInitiator === conn.isInitiator

      if (keepNew === false) {
        existing.sendKeepAlive()
        conn.on('error', noop)
        conn.destroy(new Error(ERR_DUPLICATE))
        return
      }

      existing.on('error', noop)
      existing.destroy(new Error(ERR_DUPLICATE))
      this._handleServerConnectionSwap(existing, conn)
      return
    }

    // When reaching here, the connection will always be 'opened' next tick
    this.stats.connects.server.opened++

    const peerInfo = this._upsertPeer(conn.remotePublicKey, null)

    this.connections.add(conn)
    this._allConnections.add(conn)
    this._serverConnections++

    conn.on('close', () => {
      const err = getStreamError(conn)
      if (shouldBan(err)) {
        this._banPeer(peerInfo, true, err)
      }

      this.connections.delete(conn)
      this._allConnections.delete(conn)
      this._serverConnections--
      this.stats.connects.server.closed++

      this._maybeDeletePeer(peerInfo)

      this._attemptClientConnections()

      this.emit('update')
    })
    peerInfo.client = false
    this.emit('connection', conn, peerInfo)

    this.emit('update')
  }

  _upsertPeer(publicKey, relayAddresses) {
    if (b4a.equals(publicKey, this.keyPair.publicKey)) return null
    const keyString = b4a.toString(publicKey, 'hex')
    let peerInfo = this.peers.get(keyString)

    if (peerInfo) {
      peerInfo.relayAddresses = relayAddresses // new is always better
      return peerInfo
    }

    peerInfo = new PeerInfo({
      publicKey,
      relayAddresses
    })

    this.peers.set(keyString, peerInfo)
    return peerInfo
  }

  _handleUpdate() {
    this.stats.updates++
  }

  _maybeDeletePeer(peerInfo) {
    if (!peerInfo.shouldGC()) return

    const hasActiveConn = this._allConnections.has(peerInfo.publicKey)
    if (hasActiveConn) return

    const keyString = b4a.toString(peerInfo.publicKey, 'hex')
    this.peers.delete(keyString)
  }

  /*
   * Called when a peer is actively discovered during a lookup.
   *
   * Three conditions:
   *  1. Not a known peer -- insert into queue
   *  2. A known peer with normal priority -- do nothing
   *  3. A known peer with low priority -- bump priority, because it's been rediscovered
   */
  _handlePeer(peer, topic) {
    const peerInfo = this._upsertPeer(peer.publicKey, peer.relayAddresses)
    if (peerInfo) peerInfo._topic(topic)
    if (!peerInfo || this._allConnections.has(peer.publicKey)) return
    if (!peerInfo.prioritized || peerInfo.server) peerInfo._reset()
    if (peerInfo._updatePriority()) {
      this._enqueue(peerInfo)
    }
  }

  async _handleNetworkUpdate() {
    if (!this.online) return
    this._handleNetworkChange()
  }

  async _handleNetworkChange() {
    if (this.suspended) return

    // prioritize figuring out if existing connections are dead
    for (const conn of this._allConnections) {
      conn.sendKeepAlive()
    }

    const refreshes = []

    for (const discovery of this._discovery.values()) {
      refreshes.push(discovery.refresh())
    }

    await Promise.allSettled(refreshes)
  }

  _banPeer(peerInfo, banned, err) {
    peerInfo.ban(banned)
    this.stats.bannedPeers++
    this.emit('ban', peerInfo, err)
  }

  status(key) {
    return this._discovery.get(b4a.toString(key, 'hex')) || null
  }

  listen() {
    if (!this.listening) {
      if (this.destroyed) throw new Error('Swarm destroyed')
      this.listening = this.server.listen(this.keyPair)
    }
    return this.listening
  }

  // Object that exposes a cancellation method (destroy)
  // TODO: When you rejoin, it should reannounce + bump lookup priority
  join(topic, opts = {}) {
    if (this.destroyed) throw new Error('Swarm destroyed')
    if (!topic) throw new Error(ERR_MISSING_TOPIC)
    topic = unslab(topic)

    const topicString = b4a.toString(topic, 'hex')

    let discovery = this._discovery.get(topicString)

    if (discovery && !discovery.destroyed) {
      return discovery.session(opts)
    }

    discovery = new PeerDiscovery(this, topic, {
      limit: opts.limit,
      wait: discovery ? discovery.destroy() : null,
      suspended: this.suspended,
      onpeer: (peer) => this._handlePeer(peer, topic)
    })
    this._discovery.set(topicString, discovery)
    return discovery.session(opts)
  }

  // Returns a promise
  async leave(topic) {
    if (!topic) throw new Error(ERR_MISSING_TOPIC)
    const topicString = b4a.toString(topic, 'hex')
    if (!this._discovery.has(topicString)) return Promise.resolve()

    const discovery = this._discovery.get(topicString)

    try {
      await discovery.destroy()
    } catch {
      // ignore, prop network
    }

    if (this._discovery.get(topicString) === discovery) {
      this._discovery.delete(topicString)
    }
  }

  joinPeer(publicKey) {
    const peerInfo = this._upsertPeer(publicKey, null)
    if (!peerInfo) return
    if (!this.explicitPeers.has(peerInfo)) {
      peerInfo.explicit = true
      this.explicitPeers.add(peerInfo)
    }
    if (this._allConnections.has(publicKey)) return
    if (peerInfo._updatePriority()) {
      this._enqueue(peerInfo)
    }
  }

  leavePeer(publicKey) {
    const keyString = b4a.toString(publicKey, 'hex')
    if (!this.peers.has(keyString)) return

    const peerInfo = this.peers.get(keyString)
    peerInfo.explicit = false
    this.explicitPeers.delete(peerInfo)
    this._maybeDeletePeer(peerInfo)
  }

  // Returns a promise
  async flush() {
    const allFlushed = [...this._discovery.values()].map((v) => v.flushed())
    await Promise.all(allFlushed)
    if (this._flushAllMaybe()) return true
    const pendingSize = this._allConnections.size - this.connections.size
    if (!this._queue.length && !pendingSize) return true
    return new Promise((resolve) => {
      this._pendingFlushes.push({
        onflush: resolve,
        missing: this._queue.length + pendingSize,
        tick: this._flushTick++
      })
    })
  }

  async clear() {
    const cleared = Promise.allSettled([...this._discovery.values()].map((d) => d.destroy()))
    this._discovery.clear()
    return cleared
  }

  async destroy({ force } = {}) {
    if (this.destroyed && !force) return
    this.destroyed = true

    this._timer.destroy()

    if (!force) await this.clear()

    await this.server.close()

    while (this._pendingFlushes.length) {
      const flush = this._pendingFlushes.pop()
      flush.onflush(false)
    }

    await this.dht.destroy({ force })
  }

  async suspend({ log = noop } = {}) {
    if (this.suspended) return

    const promises = []

    promises.push(this.server.suspend({ log }))

    for (const discovery of this._discovery.values()) {
      promises.push(discovery.suspend({ log }))
    }

    const pending = []
    for (const connection of this._allConnections) {
      connection.destroy()
      pending.push(new Promise((resolve) => connection.on('close', resolve)))
    }

    this.suspended = true

    log('Suspending server and discovery... (' + promises.length + ')')
    await Promise.allSettled(promises)
    log('Done, suspending the dht...')
    await this.dht.suspend({ log })
    log('Done, swarm fully suspended')

    await Promise.all(pending)

    // reset queue
    this._timer.destroy()
    this._timer = new RetryTimer(this._requeue.bind(this), {
      backoffs: this._timer.backoffs,
      jitter: this._timer.jitter
    })
    this._queue = spq()
  }

  async resume({ log = noop } = {}) {
    if (!this.suspended) return

    log('Resuming the dht')
    await this.dht.resume()
    log('Done, resuming the server')
    await this.server.resume()
    log('Done, all discovery')

    for (const discovery of this._discovery.values()) {
      discovery.resume()
    }

    this.suspended = false
    this._attemptClientConnections()
  }

  topics() {
    return this._discovery.values()
  }
}

function noop() {}

function allowAll() {
  return false
}

function shouldForceRelaying(code) {
  return (
    code === 'HOLEPUNCH_ABORTED' ||
    code === 'HOLEPUNCH_DOUBLE_RANDOMIZED_NATS' ||
    code === 'REMOTE_NOT_HOLEPUNCHABLE'
  )
}

function shouldBan() {
  // return !!err && err.name === 'HypercoreError' && err.code === 'INVALID_OPERATION'
  return false
}

function toRelayFunction(relayThrough) {
  return typeof relayThrough === 'function'
    ? relayThrough
    : (force, swarm) => (force || swarm.dht.randomized ? relayThrough : null)
}
module.exports = class BulkTimer {
  constructor(time, fn) {
    this._time = time
    this._fn = fn
    this._interval = null
    this._next = []
    this._pending = []
    this._destroyed = false
  }

  destroy() {
    if (this._destroyed) return
    this._destroyed = true
    clearInterval(this._interval)
    this._interval = null
  }

  _ontick() {
    if (!this._next.length && !this._pending.length) return
    if (this._next.length) this._fn(this._next)
    this._next = this._pending
    this._pending = []
  }

  add(info) {
    if (this._destroyed) return
    if (!this._interval) {
      this._interval = setInterval(this._ontick.bind(this), Math.floor(this._time * 0.66))
    }

    this._pending.push(info)
  }
}
const b4a = require('b4a')

module.exports = class ConnectionSet {
  constructor() {
    this._byPublicKey = new Map()
  }

  [Symbol.iterator]() {
    return this._byPublicKey.values()
  }

  get size() {
    return this._byPublicKey.size
  }

  has(publicKey) {
    return this._byPublicKey.has(toHex(publicKey))
  }

  get(publicKey) {
    return this._byPublicKey.get(toHex(publicKey))
  }

  add(connection) {
    this._byPublicKey.set(b4a.toString(connection.remotePublicKey, 'hex'), connection)
  }

  delete(connection) {
    const keyString = b4a.toString(connection.remotePublicKey, 'hex')
    const existing = this._byPublicKey.get(keyString)
    if (existing !== connection) return
    this._byPublicKey.delete(keyString)
  }
}

function toHex(b) {
  return typeof b === 'string' ? b : b4a.toString(b, 'hex')
}
const safetyCatch = require('safety-catch')
const b4a = require('b4a')

const REFRESH_INTERVAL = 1000 * 60 * 10 // 10 min
const RANDOM_JITTER = 1000 * 60 * 2 // 2 min
const DELAY_GRACE_PERIOD = 1000 * 30 // 30s

const MAX_DISCOVERY_CACHE = 64

module.exports = class PeerDiscovery {
  constructor(
    swarm,
    topic,
    { limit = Infinity, wait = null, suspended = false, onpeer = noop, onerror = safetyCatch }
  ) {
    this.limit = limit
    this.swarm = swarm
    this.topic = topic
    this.isClient = false
    this.isServer = false
    this.destroyed = false
    this.destroying = null
    this.suspended = suspended

    this._sessions = []
    this._clientSessions = 0
    this._serverSessions = 0

    this._onpeer = onpeer
    this._onerror = onerror

    this._discovered = new Set()
    this._activeQuery = null
    this._timer = null
    this._currentRefresh = null
    this._closestNodes = null
    this._firstAnnounce = true
    this._needsUnannounce = false
    this._refreshes = 0
    this._wait = wait
  }

  session({ server = true, client = true, limit = Infinity, onerror = safetyCatch }) {
    if (this.destroyed) throw new Error('PeerDiscovery is destroyed')
    const session = new PeerDiscoverySession(this)
    session.refresh({ server, client, limit }).catch(onerror)
    this._sessions.push(session)
    return session
  }

  _refreshLater(eager) {
    const jitter = Math.round(Math.random() * RANDOM_JITTER)
    const delay = !eager ? REFRESH_INTERVAL + jitter : jitter

    if (this._timer) clearTimeout(this._timer)

    const startTime = Date.now()
    this._timer = setTimeout(() => {
      // If your laptop went to sleep, and is coming back online...
      const overdue = Date.now() - startTime > delay + DELAY_GRACE_PERIOD
      if (overdue) this._refreshLater(true)
      else this.refresh().catch(this._onerror)
    }, delay)
  }

  _isActive() {
    return !this.destroyed && !this.suspended
  }

  // TODO: Allow announce to be an argument to this
  // TODO: Maybe announce should be a setter?
  async _refresh() {
    if (this.suspended) return
    const clock = ++this._refreshes

    if (this._wait) {
      await this._wait
      this._wait = null
      if (clock !== this._refreshes || !this._isActive()) return
    }

    const clear = this.isServer && this._firstAnnounce
    if (clear) this._firstAnnounce = false

    const opts = {
      clear,
      closestNodes: this._closestNodes
    }

    if (this.isServer) {
      await this.swarm.listen()
      // if a parallel refresh is happening, yield to the new one
      if (clock !== this._refreshes || !this._isActive()) return
      this._needsUnannounce = true
    }

    let limit = this.limit

    if (limit < Infinity && limit > 0) {
      for (const id of this._discovered) {
        if (!this.swarm.connections.has(id)) continue
        if (--limit === 0) break
      }
    }

    this._discovered.clear()

    const announcing = this.isServer
    const query = (this._activeQuery = announcing
      ? this.swarm.dht.announce(
          this.topic,
          this.swarm.keyPair,
          this.swarm.server.relayAddresses,
          opts
        )
      : this._needsUnannounce
        ? this.swarm.dht.lookupAndUnannounce(this.topic, this.swarm.keyPair, opts)
        : this.swarm.dht.lookup(this.topic, opts))

    try {
      for await (const data of this._activeQuery) {
        if (!this.isClient || !this._isActive()) continue
        for (const peer of data.peers) {
          if (limit < Infinity) {
            const id = b4a.toString(peer.publicKey, 'hex')

            if (this._discovered.size < MAX_DISCOVERY_CACHE) {
              this._discovered.add(id)
            }

            if (limit === 0) continue

            // there is a chance it has updated a connection during discovery and we go over
            // the limit - thats acceptable to avoid a complexity spiral here.
            if (!this.swarm.connections.has(id)) limit--
          }

          this._onpeer(peer, data)
        }
      }
    } catch (err) {
      if (this._isActive()) throw err
    } finally {
      if (this._activeQuery === query) {
        this._activeQuery = null
        if (!this.destroyed && !this.suspended) this._refreshLater(false)
      }
    }

    // This is set at the very end, when the query completes successfully.
    this._closestNodes = query.closestNodes

    if (clock !== this._refreshes) return

    // In this is the latest query, unannounce has been fulfilled as well
    if (!announcing) this._needsUnannounce = false
  }

  async refresh() {
    if (this.destroyed) throw new Error('PeerDiscovery is destroyed')

    const server = this._serverSessions > 0
    const client = this._clientSessions > 0

    if (this.suspended) return

    if (server === this.isServer && client === this.isClient) {
      if (this._currentRefresh) return this._currentRefresh
      this._currentRefresh = this._refresh()
    } else {
      if (this._activeQuery) this._activeQuery.destroy()
      this.isServer = server
      this.isClient = client
      this._currentRefresh = this._refresh()
    }

    const refresh = this._currentRefresh
    try {
      await refresh
    } catch {
      return false
    } finally {
      if (refresh === this._currentRefresh) {
        this._currentRefresh = null
      }
    }

    return true
  }

  async flushed() {
    if (this.swarm.listening) await this.swarm.listening

    try {
      await this._currentRefresh
      return true
    } catch {
      return false
    }
  }

  async _destroyMaybe() {
    if (this.destroyed) return

    try {
      if (this._sessions.length === 0) await this.swarm.leave(this.topic)
      else if (this._serverSessions === 0 && this._needsUnannounce) await this.refresh()
    } catch (err) {
      // ignore network failures here, as we are tearing down
      safetyCatch(err)
    }
  }

  destroy() {
    if (this.destroying) return this.destroying
    this.destroying = this._destroy()
    return this.destroying
  }

  async _abort(log) {
    const id = log === noop ? '' : b4a.toString(this.topic, 'hex')

    log('Aborting discovery', id)
    if (this._wait) await this._wait
    log('Aborting discovery (post wait)', id)

    if (this._activeQuery) {
      this._activeQuery.destroy()
      this._activeQuery = null
    }
    if (this._timer) {
      clearTimeout(this._timer)
      this._timer = null
    }

    let nodes = this._closestNodes

    if (this._currentRefresh) {
      try {
        await this._currentRefresh
      } catch {
        // If the destroy causes the refresh to fail, suppress it.
      }
    }

    log('Aborting discovery (post refresh)', id)
    if (this._isActive()) return

    if (!nodes) nodes = this._closestNodes
    else if (this._closestNodes !== nodes) {
      const len = nodes.length
      for (const newer of this._closestNodes) {
        if (newer.id && !hasNode(nodes, len, newer)) nodes.push(newer)
      }
    }

    if (this._needsUnannounce) {
      log('Unannouncing discovery', id)
      if (nodes && nodes.length) {
        await this.swarm.dht.unannounce(this.topic, this.swarm.keyPair, {
          closestNodes: nodes,
          onlyClosestNodes: true,
          force: true
        })
      }
      this._needsUnannounce = false
      log('Unannouncing discovery (done)', id)
    }
  }

  _destroy() {
    if (this.destroyed) return
    this.destroyed = true
    return this._abort(noop)
  }

  async suspend({ log = noop } = {}) {
    if (this.suspended) return
    this.suspended = true
    try {
      await this._abort(log)
    } catch {
      // ignore
    }
  }

  resume() {
    if (!this.suspended) return
    this.suspended = false
    this.refresh().catch(noop)
  }
}

class PeerDiscoverySession {
  constructor(discovery) {
    this.discovery = discovery
    this.isClient = false
    this.isServer = false
    this.destroyed = false
  }

  get swarm() {
    return this.discovery.swarm
  }

  get topic() {
    return this.discovery.topic
  }

  async refresh({ client = this.isClient, server = this.isServer, limit = Infinity } = {}) {
    if (this.destroyed) throw new Error('PeerDiscovery is destroyed')
    if (!client && !server) throw new Error('Cannot refresh with neither client nor server option')

    if (client !== this.isClient) {
      this.isClient = client
      this.discovery._clientSessions += client ? 1 : -1
    }

    if (server !== this.isServer) {
      this.isServer = server
      this.discovery._serverSessions += server ? 1 : -1
    }

    this.discovery.limit = limit

    return this.discovery.refresh()
  }

  async flushed() {
    return this.discovery.flushed()
  }

  async destroy() {
    if (this.destroyed) return
    this.destroyed = true

    if (this.isClient) this.discovery._clientSessions--
    if (this.isServer) this.discovery._serverSessions--

    const index = this.discovery._sessions.indexOf(this)
    const head = this.discovery._sessions.pop()

    if (head !== this) this.discovery._sessions[index] = head

    return this.discovery._destroyMaybe()
  }
}

function hasNode(nodes, len, node) {
  for (let i = 0; i < len; i++) {
    const existing = nodes[i]
    if (existing.id && b4a.equals(existing.id, node.id)) return true
  }

  return false
}

function noop() {}
const { EventEmitter } = require('events')
const b4a = require('b4a')
const unslab = require('unslab')

const MIN_CONNECTION_TIME = 15000

const VERY_LOW_PRIORITY = 0
const LOW_PRIORITY = 1
const NORMAL_PRIORITY = 2
const HIGH_PRIORITY = 3
const VERY_HIGH_PRIORITY = 4

module.exports = class PeerInfo extends EventEmitter {
  constructor({ publicKey, relayAddresses }) {
    super()

    this.publicKey = unslab(publicKey)
    this.relayAddresses = relayAddresses

    this.reconnecting = true
    this.proven = false
    this.connectedTime = -1
    this.disconnectedTime = 0
    this.banned = false
    this.tried = false
    this.explicit = false
    this.waiting = false
    this.forceRelaying = false

    // Set by the Swarm
    this.queued = false
    this.client = false
    this.topics = [] // TODO: remove on next major (check with mafintosh for context)

    this.attempts = 0
    this.priority = NORMAL_PRIORITY

    // Used by shuffled-priority-queue
    this._index = 0

    // Used for flush management
    this._flushTick = 0

    // Used for topic multiplexing
    this._seenTopics = new Set()
  }

  get server() {
    return !this.client
  }

  get prioritized() {
    return this.priority >= NORMAL_PRIORITY
  }

  _getPriority() {
    const peerIsStale = this.tried && !this.proven
    if (peerIsStale || this.attempts > 3) return VERY_LOW_PRIORITY
    if (this.attempts === 3) return LOW_PRIORITY
    if (this.attempts === 2) return HIGH_PRIORITY
    if (this.attempts === 1) return VERY_HIGH_PRIORITY
    return NORMAL_PRIORITY
  }

  _connected() {
    this.proven = true
    this.connectedTime = Date.now()
  }

  _disconnected() {
    this.disconnectedTime = Date.now()
    if (this.connectedTime > -1) {
      if (this.disconnectedTime - this.connectedTime >= MIN_CONNECTION_TIME) this.attempts = 0 // fast retry
      this.connectedTime = -1
    }
    this.attempts++
  }

  _deprioritize() {
    this.attempts = 3
  }

  _reset() {
    this.client = false
    this.proven = false
    this.tried = false
    this.attempts = 0
  }

  _updatePriority() {
    if (this.explicit && this.attempts > 3) this._deprioritize()
    if (this.banned || this.queued || this.attempts > 3) return false
    this.priority = this._getPriority()
    return true
  }

  _topic(topic) {
    const topicString = b4a.toString(topic, 'hex')
    if (this._seenTopics.has(topicString)) return
    this._seenTopics.add(topicString)
    this.topics.push(topic)
    this.emit('topic', topic)
  }

  reconnect(val) {
    this.reconnecting = !!val
  }

  ban(val) {
    this.banned = !!val
  }

  shouldGC() {
    return !(this.banned || this.queued || this.explicit || this.waiting)
  }
}
const BulkTimer = require('./bulk-timer')

const BACKOFF_JITTER = 500
const BACKOFF_S = 1000 + Math.round(BACKOFF_JITTER * Math.random())
const BACKOFF_M = 5000 + Math.round(2 * BACKOFF_JITTER * Math.random())
const BACKOFF_L = 15000 + Math.round(4 * BACKOFF_JITTER * Math.random())
const BACKOFF_X = 1000 * 60 * 10 + Math.round(240 * BACKOFF_JITTER * Math.random())

module.exports = class RetryTimer {
  constructor(
    push,
    { backoffs = [BACKOFF_S, BACKOFF_M, BACKOFF_L, BACKOFF_X], jitter = BACKOFF_JITTER } = {}
  ) {
    this.jitter = jitter
    this.backoffs = backoffs

    this._sTimer = new BulkTimer(backoffs[0] + Math.round(jitter * Math.random()), push)
    this._mTimer = new BulkTimer(backoffs[1] + Math.round(jitter * Math.random()), push)
    this._lTimer = new BulkTimer(backoffs[2] + Math.round(jitter * Math.random()), push)
    this._xTimer = new BulkTimer(backoffs[3] + Math.round(jitter * Math.random()), push)
  }

  _selectRetryTimer(peerInfo) {
    if (peerInfo.banned || !peerInfo.reconnecting) return null

    if (peerInfo.attempts > 3) {
      return peerInfo.explicit ? this._xTimer : null
    }

    if (peerInfo.attempts === 0) return this._sTimer
    if (peerInfo.proven) {
      switch (peerInfo.attempts) {
        case 1:
          return this._sTimer
        case 2:
          return this._mTimer
        case 3:
          return this._lTimer
      }
    } else {
      switch (peerInfo.attempts) {
        case 1:
          return this._mTimer
        case 2:
          return this._lTimer
        case 3:
          return this._lTimer
      }
    }

    return null
  }

  add(peerInfo) {
    const timer = this._selectRetryTimer(peerInfo)
    if (!timer) return false

    timer.add(peerInfo)
    return true
  }

  destroy() {
    this._sTimer.destroy()
    this._mTimer.destroy()
    this._lTimer.destroy()
    this._xTimer.destroy()
  }
}
{
  "name": "hyperswarm",
  "version": "4.17.0",
  "description": "A distributed networking stack for connecting peers",
  "files": [
    "index.js",
    "lib/**.js"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    },
    "process": {
      "bare": "bare-process",
      "default": "process"
    }
  },
  "dependencies": {
    "b4a": "^1.3.1",
    "bare-events": "^2.2.0",
    "hyperdht": "^6.21.0",
    "safety-catch": "^1.0.2",
    "shuffled-priority-queue": "^2.1.0",
    "streamx": "^2.22.1",
    "unslab": "^1.3.0"
  },
  "devDependencies": {
    "bare-process": "^4.2.2",
    "brittle": "^3.0.2",
    "hypercore-crypto": "^3.4.0",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "which-runtime": "^1.3.2"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:generate": "brittle -r test/all.js test/*.js",
    "test:node": "brittle-node --coverage test/*.js",
    "test:bare": "bare test/all.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/hyperswarm.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "contributors": [
    "David Mark Clements (@davidmarkclem)",
    "Andrew Osheroff (@andrewosh)"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/hyperswarm/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperswarm"
}
const { EventEmitter } = require('events')

module.exports = class RoutingTable extends EventEmitter {
  constructor (id, opts) {
    if (!opts) opts = {}

    super()

    this.id = id
    this.k = opts.k || 20
    this.size = 0
    this.rows = new Array(id.length * 8)
  }

  add (node) {
    const i = this._diff(node.id)

    let row = this.rows[i]

    if (!row) {
      row = this.rows[i] = new Row(this, i)
      this.emit('row', row)
    }

    const len = row.nodes.length
    if (!row.add(node, this.k)) return false

    this.size += row.nodes.length - len
    return true
  }

  remove (id) {
    const i = this._diff(id)
    const row = this.rows[i]
    if (!row) return false
    if (!row.remove(id)) return false
    this.size--
    return true
  }

  get (id) {
    const i = this._diff(id)
    const row = this.rows[i]
    if (!row) return null
    return row.get(id)
  }

  has (id) {
    return this.get(id) !== null
  }

  random () {
    let n = (Math.random() * this.size) | 0

    for (let i = 0; i < this.rows.length; i++) {
      const r = this.rows[i]
      if (!r) continue
      if (n < r.nodes.length) return r.nodes[n]
      n -= r.nodes.length
    }

    return null
  }

  closest (id, k) {
    if (!k) k = this.k

    const result = []
    const d = this._diff(id)

    // push close nodes
    for (let i = d; i >= 0 && result.length < k; i--) this._pushNodes(i, k, result)

    // if we don't have enough close nodes, populate from other rows, re the paper
    for (let i = d + 1; i < this.rows.length && result.length < k; i++) this._pushNodes(i, k, result)

    return result
  }

  _pushNodes (i, k, result) {
    const row = this.rows[i]
    if (!row) return

    const missing = Math.min(k - result.length, row.nodes.length)
    for (let j = 0; j < missing; j++) result.push(row.nodes[j])
  }

  toArray () {
    return this.closest(this.id, Infinity)
  }

  _diff (id) {
    for (let i = 0; i < id.length; i++) {
      const a = id[i]
      const b = this.id[i]

      if (a !== b) return i * 8 + Math.clz32(a ^ b) - 24
    }

    return this.rows.length - 1
  }
}

class Row extends EventEmitter {
  constructor (table, index) {
    super()

    this.data = null // can be used be upstream for whatevs
    this.byteOffset = index >> 3
    this.index = index
    this.table = table
    this.nodes = []
  }

  add (node) {
    const id = node.id

    let l = 0
    let r = this.nodes.length - 1

    while (l <= r) {
      const m = (l + r) >> 1
      const c = this.compare(id, this.nodes[m].id)

      if (c === 0) {
        this.nodes[m] = node
        return true
      }

      if (c < 0) r = m - 1
      else l = m + 1
    }

    if (this.nodes.length >= this.table.k) {
      this.emit('full', node)
      return false
    }

    this.insert(l, node)
    return true
  }

  remove (id) {
    let l = 0
    let r = this.nodes.length - 1

    while (l <= r) {
      const m = (l + r) >> 1
      const c = this.compare(id, this.nodes[m].id)

      if (c === 0) {
        this.splice(m)
        return true
      }

      if (c < 0) r = m - 1
      else l = m + 1
    }

    return false
  }

  get (id) {
    let l = 0
    let r = this.nodes.length - 1

    while (l <= r) {
      const m = (l + r) >> 1
      const node = this.nodes[m]
      const c = this.compare(id, node.id)

      if (c === 0) return node
      if (c < 0) r = m - 1
      else l = m + 1
    }

    return null
  }

  insert (i, node) {
    this.nodes.push(node) // push node or null or whatevs, just trying to not be polymorphic
    for (let j = this.nodes.length - 1; j > i; j--) this.nodes[j] = this.nodes[j - 1]
    this.nodes[i] = node
    this.emit('add', node)
  }

  splice (i) {
    for (; i < this.nodes.length - 1; i++) this.nodes[i] = this.nodes[i + 1]
    this.emit('remove', this.nodes.pop())
  }

  // very likely they diverge after a couple of bytes so a simple impl, like this is prop fastest vs Buffer.compare
  compare (a, b) {
    for (let i = this.byteOffset; i < a.length; i++) {
      const ai = a[i]
      const bi = b[i]
      if (ai === bi) continue
      return ai < bi ? -1 : 1
    }
    return 0
  }
}
{
  "name": "kademlia-routing-table",
  "version": "1.0.6",
  "description": "XOR based routing table used for P2P networks such as a Kademlia DHT.",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "dependencies": {
    "bare-events": "^2.2.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "standard": "^17.1.0"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "keywords": [
    "kademlia",
    "p2p",
    "k-bucket",
    "k-buckets",
    "xor",
    "routing",
    "distributed",
    "systems"
  ],
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/kademlia-routing-table.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/kademlia-routing-table/issues"
  },
  "homepage": "https://github.com/mafintosh/kademlia-routing-table"
}
module.exports = assert

class AssertionError extends Error {}
AssertionError.prototype.name = 'AssertionError'

/**
 * Minimal assert function
 * @param  {any} t Value to check if falsy
 * @param  {string=} m Optional assertion error message
 * @throws {AssertionError}
 */
function assert (t, m) {
  if (!t) {
    var err = new AssertionError(m)
    if (Error.captureStackTrace) Error.captureStackTrace(err, assert)
    throw err
  }
}
{
  "name": "nanoassert",
  "version": "2.0.0",
  "description": "Nanoscale assertion module",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "tape": "^4.9.1"
  },
  "scripts": {
    "test": "tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/emilbayes/nanoassert.git"
  },
  "keywords": [
    "assert",
    "unassert",
    "power-assert",
    "tiny",
    "nano",
    "pico"
  ],
  "author": "Emil Bay <github@tixz.dk>",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/emilbayes/nanoassert/issues"
  },
  "homepage": "https://github.com/emilbayes/nanoassert#readme"
}
module.exports = class NatSampler {
  constructor () {
    this.host = null
    this.port = 0
    this.size = 0

    this._a = null
    this._b = null
    this._threshold = 0
    this._top = 0
    this._samples = []
  }

  add (host, port) {
    const a = this._bump(host, port, 2)
    const b = this._bump(host, 0, 1)

    if (this._samples.length < 32) {
      this.size++
      this._threshold = this.size - (this.size < 4 ? 0 : this.size < 8 ? 1 : this.size < 12 ? 2 : 3)
      this._samples.push(a, b)
      this._top += 2
    } else {
      if (this._top === 32) this._top = 0

      const oa = this._samples[this._top]
      this._samples[this._top++] = a
      oa.hits--

      const ob = this._samples[this._top]
      this._samples[this._top++] = b
      ob.hits--
    }

    if (this._a === null || this._a.hits < a.hits) this._a = a
    if (this._b === null || this._b.hits < b.hits) this._b = b

    if (this._a.hits >= this._threshold) {
      this.host = this._a.host
      this.port = this._a.port
    } else if (this._b.hits >= this._threshold) {
      this.host = this._b.host
      this.port = 0
    } else {
      this.host = null
      this.port = 0
    }

    return a.hits
  }

  _bump (host, port, inc) {
    for (let i = 0; i < 4; i++) {
      const j = (this._top - inc - (2 * i)) & 31
      if (j >= this._samples.length) return { host, port, hits: 1 }
      const s = this._samples[j]
      if (s.port === port && s.host === host) {
        s.hits++
        return s
      }
    }
    return { host, port, hits: 1 }
  }
}
{
  "name": "nat-sampler",
  "version": "1.0.1",
  "description": "Sample addresses to figure out if a host + port is consistent",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^16.0.3",
    "tape": "^5.2.2"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/nat-sampler.git"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/nat-sampler/issues"
  },
  "homepage": "https://github.com/mafintosh/nat-sampler"
}
/* eslint-disable camelcase */
const sodium = require('sodium-universal')
const assert = require('nanoassert')
const b4a = require('b4a')

const DHLEN = sodium.crypto_scalarmult_ed25519_BYTES
const PKLEN = sodium.crypto_scalarmult_ed25519_BYTES
const SCALARLEN = sodium.crypto_scalarmult_ed25519_BYTES
const SKLEN = sodium.crypto_sign_SECRETKEYBYTES
const ALG = 'Ed25519'

module.exports = {
  DHLEN,
  PKLEN,
  SCALARLEN,
  SKLEN,
  ALG,
  name: ALG,
  generateKeyPair,
  dh
}

function generateKeyPair (privKey) {
  if (privKey) return generateSeedKeyPair(privKey.subarray(0, 32))

  const keyPair = {}
  keyPair.secretKey = b4a.alloc(SKLEN)
  keyPair.publicKey = b4a.alloc(PKLEN)

  sodium.crypto_sign_keypair(keyPair.publicKey, keyPair.secretKey)
  return keyPair
}

function generateSeedKeyPair (seed) {
  const keyPair = {}
  keyPair.secretKey = b4a.alloc(SKLEN)
  keyPair.publicKey = b4a.alloc(PKLEN)

  sodium.crypto_sign_seed_keypair(keyPair.publicKey, keyPair.secretKey, seed)
  return keyPair
}

function dh (publicKey, { scalar, secretKey }) {
  // tweaked keys expose scalar directly
  if (!scalar) {
    assert(secretKey.byteLength === SKLEN)

    // libsodium stores seed not actual scalar
    const sk = b4a.alloc(64)
    sodium.crypto_hash_sha512(sk, secretKey.subarray(0, 32))
    sk[0] &= 248
    sk[31] &= 127
    sk[31] |= 64

    scalar = sk.subarray(0, 32)
  }

  assert(scalar.byteLength === SCALARLEN)
  assert(publicKey.byteLength === PKLEN)

  const output = b4a.alloc(DHLEN)

  // we clamp if necessary above
  sodium.crypto_scalarmult_ed25519_noclamp(
    output,
    scalar,
    publicKey
  )

  return output
}
{
  "name": "noise-curve-ed",
  "version": "2.1.0",
  "description": "Ed25519 elliptic curve operations for [`noise-handshake`](https://github.com/chm-diederichs/noise-handshake)",
  "main": "index.js",
  "scripts": {
    "test": "npx standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/chm-diederichs/noise-curve-ed.git"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/chm-diederichs/noise-curve-ed/issues"
  },
  "homepage": "https://github.com/chm-diederichs/noise-curve-ed#readme",
  "dependencies": {
    "b4a": "^1.1.0",
    "nanoassert": "^2.0.0",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "noise-handshake": "^3.0.0",
    "standard": "^16.0.3",
    "tape": "^5.2.2"
  }
}
const sodium = require('sodium-universal')
const b4a = require('b4a')

module.exports = class CipherState {
  constructor (key) {
    this.key = key || null
    this.nonce = 0
    this.CIPHER_ALG = 'ChaChaPoly'
  }

  initialiseKey (key) {
    this.key = key
    this.nonce = 0
  }

  setNonce (nonce) {
    this.nonce = nonce
  }

  encrypt (plaintext, ad) {
    if (!this.hasKey) return plaintext
    if (!ad) ad = b4a.alloc(0)

    const ciphertext = encryptWithAD(this.key, this.nonce, ad, plaintext)
    if (ciphertext.length > 65535) throw new Error(`ciphertext length of ${ciphertext.length} exceeds maximum Noise message length of 65535`)
    this.nonce++

    return ciphertext
  }

  decrypt (ciphertext, ad) {
    if (!this.hasKey) return ciphertext
    if (!ad) ad = b4a.alloc(0)
    if (ciphertext.length > 65535) throw new Error(`ciphertext length of ${ciphertext.length} exceeds maximum Noise message length of 65535`)

    const plaintext = decryptWithAD(this.key, this.nonce, ad, ciphertext)
    this.nonce++

    return plaintext
  }

  get hasKey () {
    return this.key !== null
  }

  _clear () {
    sodium.sodium_memzero(this.key)
    this.key = null
    this.nonce = null
  }

  static get MACBYTES () {
    return 16
  }

  static get NONCEBYTES () {
    return 8
  }

  static get KEYBYTES () {
    return 32
  }
}

function encryptWithAD (key, counter, additionalData, plaintext) {
  // for our purposes, additionalData will always be a pubkey so we encode from hex
  if (!b4a.isBuffer(additionalData)) additionalData = b4a.from(additionalData, 'hex')
  if (!b4a.isBuffer(plaintext)) plaintext = b4a.from(plaintext, 'hex')

  const nonce = b4a.alloc(sodium.crypto_aead_chacha20poly1305_ietf_NPUBBYTES)
  const view = new DataView(nonce.buffer, nonce.byteOffset, nonce.byteLength)
  view.setUint32(4, counter, true)

  const ciphertext = b4a.alloc(plaintext.byteLength + sodium.crypto_aead_chacha20poly1305_ietf_ABYTES)

  sodium.crypto_aead_chacha20poly1305_ietf_encrypt(ciphertext, plaintext, additionalData, null, nonce, key)
  return ciphertext
}

function decryptWithAD (key, counter, additionalData, ciphertext) {
  // for our purposes, additionalData will always be a pubkey so we encode from hex
  if (!b4a.isBuffer(additionalData)) additionalData = b4a.from(additionalData, 'hex')
  if (!b4a.isBuffer(ciphertext)) ciphertext = b4a.from(ciphertext, 'hex')

  const nonce = b4a.alloc(sodium.crypto_aead_chacha20poly1305_ietf_NPUBBYTES)
  const view = new DataView(nonce.buffer, nonce.byteOffset, nonce.byteLength)
  view.setUint32(4, counter, true)

  const plaintext = b4a.alloc(ciphertext.byteLength - sodium.crypto_aead_chacha20poly1305_ietf_ABYTES)

  sodium.crypto_aead_chacha20poly1305_ietf_decrypt(plaintext, null, ciphertext, additionalData, nonce, key)
  return plaintext
}
/* eslint-disable camelcase */
const {
  crypto_kx_SEEDBYTES,
  crypto_kx_keypair,
  crypto_kx_seed_keypair,
  crypto_scalarmult_BYTES,
  crypto_scalarmult_SCALARBYTES,
  crypto_scalarmult,
  crypto_scalarmult_base
} = require('sodium-universal')

const assert = require('nanoassert')
const b4a = require('b4a')

const DHLEN = crypto_scalarmult_BYTES
const PKLEN = crypto_scalarmult_BYTES
const SKLEN = crypto_scalarmult_SCALARBYTES
const SEEDLEN = crypto_kx_SEEDBYTES
const ALG = '25519'

module.exports = {
  DHLEN,
  PKLEN,
  SKLEN,
  SEEDLEN,
  ALG,
  generateKeyPair,
  generateSeedKeyPair,
  dh
}

function generateKeyPair (privKey) {
  const keyPair = {}

  keyPair.secretKey = privKey || b4a.alloc(SKLEN)
  keyPair.publicKey = b4a.alloc(PKLEN)

  if (privKey) {
    crypto_scalarmult_base(keyPair.publicKey, keyPair.secretKey)
  } else {
    crypto_kx_keypair(keyPair.publicKey, keyPair.secretKey)
  }

  return keyPair
}

function generateSeedKeyPair (seed) {
  assert(seed.byteLength === SKLEN)

  const keyPair = {}
  keyPair.secretKey = b4a.alloc(SKLEN)
  keyPair.publicKey = b4a.alloc(PKLEN)

  crypto_kx_seed_keypair(keyPair.publicKey, keyPair.secretKey, seed)
  return keyPair
}

function dh (publicKey, { secretKey }) {
  assert(secretKey.byteLength === SKLEN)
  assert(publicKey.byteLength === PKLEN)

  const output = b4a.alloc(DHLEN)

  crypto_scalarmult(
    output,
    secretKey,
    publicKey
  )

  return output
}
const hmacBlake2b = require('./hmac')
const b4a = require('b4a')

const HASHLEN = 64

module.exports = {
  hkdf,
  HASHLEN
}

// HMAC-based Extract-and-Expand KDF
// https://www.ietf.org/rfc/rfc5869.txt

function hkdf (salt, inputKeyMaterial, info = '', length = 2 * HASHLEN) {
  const pseudoRandomKey = hkdfExtract(salt, inputKeyMaterial)
  return hkdfExpand(pseudoRandomKey, info, length)
}

function hkdfExtract (salt, inputKeyMaterial) {
  const hmac = b4a.alloc(HASHLEN)
  return hmacDigest(hmac, salt, inputKeyMaterial)
}

function hkdfExpand (key, info, length) {
  // Put in dedicated slab to avoid keeping shared slab from being gc'ed
  const buffer = b4a.allocUnsafeSlow(length)

  const infoBuf = b4a.from(info)
  let prev = infoBuf

  const result = []
  for (let i = 0; i < length; i += HASHLEN) {
    const pos = b4a.from([(i / HASHLEN) + 1])

    const out = buffer.subarray(i, i + HASHLEN)
    result.push(out)

    prev = hmacDigest(out, key, [prev, infoBuf, pos])
  }

  return result
}

function hmacDigest (out, key, input) {
  hmacBlake2b(out, input, key)
  return out
}
/* eslint-disable camelcase */
const b4a = require('b4a')
const { sodium_memzero, crypto_generichash, crypto_generichash_batch } = require('sodium-universal')

const HASHLEN = 64
const BLOCKLEN = 128
const scratch = b4a.alloc(BLOCKLEN * 3)
const HMACKey = scratch.subarray(BLOCKLEN * 0, BLOCKLEN * 1)
const OuterKeyPad = scratch.subarray(BLOCKLEN * 1, BLOCKLEN * 2)
const InnerKeyPad = scratch.subarray(BLOCKLEN * 2, BLOCKLEN * 3)

// Post-fill is done in the cases where someone caught an exception that
// happened before we were able to clear data at the end

module.exports = function hmac (out, batch, key) {
  if (key.byteLength > BLOCKLEN) {
    crypto_generichash(HMACKey.subarray(0, HASHLEN), key)
    sodium_memzero(HMACKey.subarray(HASHLEN))
  } else {
    // Covers key <= BLOCKLEN
    HMACKey.set(key)
    sodium_memzero(HMACKey.subarray(key.byteLength))
  }

  for (let i = 0; i < HMACKey.byteLength; i++) {
    OuterKeyPad[i] = 0x5c ^ HMACKey[i]
    InnerKeyPad[i] = 0x36 ^ HMACKey[i]
  }
  sodium_memzero(HMACKey)

  crypto_generichash_batch(out, [InnerKeyPad].concat(batch))
  sodium_memzero(InnerKeyPad)
  crypto_generichash_batch(out, [OuterKeyPad, out])
  sodium_memzero(OuterKeyPad)
}

module.exports.BYTES = HASHLEN
module.exports.KEYBYTES = BLOCKLEN
const assert = require('nanoassert')
const b4a = require('b4a')

const SymmetricState = require('./symmetric-state')
const { HASHLEN } = require('./hkdf')

const PRESHARE_IS = Symbol('initiator static key preshared')
const PRESHARE_RS = Symbol('responder static key preshared')

const TOK_PSK = Symbol('psk')

const TOK_S = Symbol('s')
const TOK_E = Symbol('e')

const TOK_ES = Symbol('es')
const TOK_SE = Symbol('se')
const TOK_EE = Symbol('ee')
const TOK_SS = Symbol('ss')

const HANDSHAKES = Object.freeze({
  NN: [
    [TOK_E],
    [TOK_E, TOK_EE]
  ],
  NNpsk0: [
    [TOK_PSK, TOK_E],
    [TOK_E, TOK_EE]
  ],
  XX: [
    [TOK_E],
    [TOK_E, TOK_EE, TOK_S, TOK_ES],
    [TOK_S, TOK_SE]
  ],
  XXpsk0: [
    [TOK_PSK, TOK_E],
    [TOK_E, TOK_EE, TOK_S, TOK_ES],
    [TOK_S, TOK_SE]
  ],
  IK: [
    PRESHARE_RS,
    [TOK_E, TOK_ES, TOK_S, TOK_SS],
    [TOK_E, TOK_EE, TOK_SE]
  ],
  XK: [
    PRESHARE_RS,
    [TOK_E, TOK_ES],
    [TOK_E, TOK_EE],
    [TOK_S, TOK_SE]
  ]
})

class Writer {
  constructor () {
    this.size = 0
    this.buffers = []
  }

  push (b) {
    this.size += b.byteLength
    this.buffers.push(b)
  }

  end () {
    const all = b4a.alloc(this.size)
    let offset = 0
    for (const b of this.buffers) {
      all.set(b, offset)
      offset += b.byteLength
    }
    return all
  }
}

class Reader {
  constructor (buf) {
    this.offset = 0
    this.buffer = buf
  }

  shift (n) {
    const start = this.offset
    const end = this.offset += n
    if (end > this.buffer.byteLength) throw new Error('Insufficient bytes')
    return this.buffer.subarray(start, end)
  }

  end () {
    return this.shift(this.buffer.byteLength - this.offset)
  }
}

module.exports = class NoiseState extends SymmetricState {
  constructor (pattern, initiator, staticKeypair, opts = {}) {
    super(opts)

    this.s = staticKeypair || this.curve.generateKeyPair()
    this.e = null

    this.psk = null
    if (opts && opts.psk) this.psk = opts.psk

    this.re = null
    this.rs = null

    this.pattern = pattern
    this.handshake = HANDSHAKES[this.pattern].slice()

    this.isPskHandshake = !!this.psk && hasPskToken(this.handshake)

    this.protocol = b4a.from([
      'Noise',
      this.pattern,
      this.DH_ALG,
      this.CIPHER_ALG,
      'BLAKE2b'
    ].join('_'))

    this.initiator = initiator
    this.complete = false

    this.rx = null
    this.tx = null
    this.hash = null
  }

  initialise (prologue, remoteStatic) {
    if (this.protocol.byteLength <= HASHLEN) this.digest.set(this.protocol)
    else this.mixHash(this.protocol)

    this.chainingKey = b4a.from(this.digest)

    this.mixHash(prologue)

    while (!Array.isArray(this.handshake[0])) {
      const message = this.handshake.shift()

      // handshake steps should be as arrays, only
      // preshare tokens are provided otherwise
      assert(message === PRESHARE_RS || message === PRESHARE_IS,
        'Unexpected pattern')

      const takeRemoteKey = this.initiator
        ? message === PRESHARE_RS
        : message === PRESHARE_IS

      if (takeRemoteKey) this.rs = remoteStatic

      const key = takeRemoteKey ? this.rs : this.s.publicKey
      assert(key != null, 'Remote pubkey required')

      this.mixHash(key)
    }
  }

  final () {
    const [k1, k2] = this.split()

    this.tx = this.initiator ? k1 : k2
    this.rx = this.initiator ? k2 : k1

    this.complete = true
    this.hash = this.getHandshakeHash()

    this._clear()
  }

  recv (buf) {
    const r = new Reader(buf)

    for (const pattern of this.handshake.shift()) {
      switch (pattern) {
        case TOK_PSK :
          this.mixKeyAndHash(this.psk)
          break

        case TOK_E :
          this.re = r.shift(this.curve.PKLEN)
          this.mixHash(this.re)
          if (this.isPskHandshake) this.mixKeyNormal(this.re)
          break

        case TOK_S : {
          const klen = this.hasKey ? this.curve.PKLEN + 16 : this.curve.PKLEN
          this.rs = this.decryptAndHash(r.shift(klen))
          break
        }

        case TOK_EE :
        case TOK_ES :
        case TOK_SE :
        case TOK_SS : {
          const useStatic = keyPattern(pattern, this.initiator)

          const localKey = useStatic.local ? this.s : this.e
          const remoteKey = useStatic.remote ? this.rs : this.re

          this.mixKey(remoteKey, localKey)
          break
        }

        default :
          throw new Error('Unexpected message')
      }
    }

    const payload = this.decryptAndHash(r.end())

    if (!this.handshake.length) this.final()
    return payload
  }

  send (payload = b4a.alloc(0)) {
    const w = new Writer()

    for (const pattern of this.handshake.shift()) {
      switch (pattern) {
        case TOK_PSK :
          this.mixKeyAndHash(this.psk)
          break

        case TOK_E :
          if (this.e === null) this.e = this.curve.generateKeyPair()
          this.mixHash(this.e.publicKey)
          if (this.isPskHandshake) this.mixKeyNormal(this.e.publicKey)
          w.push(this.e.publicKey)
          break

        case TOK_S :
          w.push(this.encryptAndHash(this.s.publicKey))
          break

        case TOK_ES :
        case TOK_SE :
        case TOK_EE :
        case TOK_SS : {
          const useStatic = keyPattern(pattern, this.initiator)

          const localKey = useStatic.local ? this.s : this.e
          const remoteKey = useStatic.remote ? this.rs : this.re

          this.mixKey(remoteKey, localKey)
          break
        }

        default :
          throw new Error('Unexpected message')
      }
    }

    w.push(this.encryptAndHash(payload))
    const response = w.end()

    if (!this.handshake.length) this.final()
    return response
  }

  _clear () {
    super._clear()

    this.e.secretKey.fill(0)
    this.e.publicKey.fill(0)

    this.re.fill(0)

    this.e = null
    this.re = null
  }
}

function keyPattern (pattern, initiator) {
  const ret = {
    local: false,
    remote: false
  }

  switch (pattern) {
    case TOK_EE:
      return ret

    case TOK_ES:
      ret.local ^= !initiator
      ret.remote ^= initiator
      return ret

    case TOK_SE:
      ret.local ^= initiator
      ret.remote ^= !initiator
      return ret

    case TOK_SS:
      ret.local ^= 1
      ret.remote ^= 1
      return ret
  }
}

function hasPskToken (handshake) {
  return handshake.some(x => {
    return Array.isArray(x) && x.indexOf(TOK_PSK) !== -1
  })
}
{
  "name": "noise-handshake",
  "version": "4.2.0",
  "description": "Noise protocol handshake",
  "main": "noise.js",
  "files": [
    "*.js"
  ],
  "scripts": {
    "test": "standard && brittle test/*.js"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/noise-handshake.git"
  },
  "dependencies": {
    "b4a": "^1.1.0",
    "nanoassert": "^2.0.0",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "noise-protocol": "chm-diederichs/noise-protocol.git#xx-ephemeral-key",
    "standard": "^16.0.3"
  }
}
const sodium = require('sodium-universal')
const assert = require('nanoassert')
const b4a = require('b4a')
const CipherState = require('./cipher')
const curve = require('./dh')
const { HASHLEN, hkdf } = require('./hkdf')

module.exports = class SymmetricState extends CipherState {
  constructor (opts = {}) {
    super()

    this.curve = opts.curve || curve
    this.digest = b4a.alloc(HASHLEN)
    this.chainingKey = null
    this.offset = 0

    this.DH_ALG = this.curve.ALG
  }

  mixHash (data) {
    accumulateDigest(this.digest, data)
  }

  mixKeyAndHash (key) {
    const [ck, tempH, tempK] = hkdf(this.chainingKey, key, '', 3 * HASHLEN)
    this.chainingKey = ck
    this.mixHash(tempH)
    this.initialiseKey(tempK.subarray(0, 32))
  }

  mixKeyNormal (key) {
    const [ck, tempK] = hkdf(this.chainingKey, key)
    this.chainingKey = ck
    this.initialiseKey(tempK.subarray(0, 32))
  }

  mixKey (remoteKey, localKey) {
    const dh = this.curve.dh(remoteKey, localKey)
    const hkdfResult = hkdf(this.chainingKey, dh)
    this.chainingKey = hkdfResult[0]
    this.initialiseKey(hkdfResult[1].subarray(0, 32))
  }

  encryptAndHash (plaintext) {
    const ciphertext = this.encrypt(plaintext, this.digest)
    accumulateDigest(this.digest, ciphertext)
    return ciphertext
  }

  decryptAndHash (ciphertext) {
    const plaintext = this.decrypt(ciphertext, this.digest)
    accumulateDigest(this.digest, ciphertext)
    return plaintext
  }

  getHandshakeHash (out) {
    if (!out) return this.getHandshakeHash(b4a.alloc(HASHLEN))
    assert(out.byteLength === HASHLEN, `output must be ${HASHLEN} bytes`)

    out.set(this.digest)
    return out
  }

  split () {
    const res = hkdf(this.chainingKey, b4a.alloc(0))
    return res.map(k => k.subarray(0, 32))
  }

  _clear () {
    super._clear()

    sodium.sodium_memzero(this.digest)
    sodium.sodium_memzero(this.chainingKey)

    this.digest = null
    this.chainingKey = null
    this.offset = null

    this.curve = null
  }

  static get alg () {
    return CipherState.alg + '_BLAKE2b'
  }
}

function accumulateDigest (digest, input) {
  const toHash = b4a.concat([digest, input])
  sodium.crypto_generichash(digest, toHash)
}
const b4a = require('b4a')
const c = require('compact-encoding')
const queueTick = require('queue-tick')
const safetyCatch = require('safety-catch')
const unslab = require('unslab')

const MAX_BUFFERED = 32768
const MAX_BACKLOG = Infinity // TODO: impl "open" backpressure
const MAX_BATCH = 8 * 1024 * 1024

class Channel {
  constructor(
    mux,
    info,
    userData,
    protocol,
    aliases,
    id,
    handshake,
    messages,
    onopen,
    onclose,
    ondestroy,
    ondrain
  ) {
    this.userData = userData
    this.protocol = protocol
    this.aliases = aliases
    this.id = id
    this.handshake = null
    this.messages = []

    this.opened = false
    this.closed = false
    this.destroyed = false

    this.onopen = onopen
    this.onclose = onclose
    this.ondestroy = ondestroy
    this.ondrain = ondrain

    this._handshake = handshake
    this._mux = mux
    this._info = info
    this._localId = 0
    this._remoteId = 0
    this._active = 0
    this._extensions = null

    this._decBound = this._dec.bind(this)
    this._decAndDestroyBound = this._decAndDestroy.bind(this)

    this._openedPromise = null
    this._openedResolve = null

    this._destroyedPromise = null
    this._destroyedResolve = null

    for (const m of messages) this.addMessage(m)
  }

  get drained() {
    return this._mux.drained
  }

  fullyOpened() {
    if (this.opened) return Promise.resolve(true)
    if (this.closed) return Promise.resolve(false)
    if (this._openedPromise) return this._openedPromise

    this._openedPromise = new Promise((resolve) => {
      this._openedResolve = resolve
    })
    return this._openedPromise
  }

  fullyClosed() {
    if (this.destroyed) return Promise.resolve()
    if (this._destroyedPromise) return this._destroyedPromise

    this._destroyedPromise = new Promise((resolve) => {
      this._destroyedResolve = resolve
    })
    return this._destroyedPromise
  }

  open(handshake) {
    const id = this._mux._free.length > 0 ? this._mux._free.pop() : this._mux._local.push(null) - 1

    this._info.opened++
    this._info.lastChannel = this
    this._localId = id + 1
    this._mux._local[id] = this

    if (this._remoteId === 0) {
      this._info.outgoing.push(this._localId)
    }

    const state = { buffer: null, start: 2, end: 2 }

    c.uint.preencode(state, this._localId)
    c.string.preencode(state, this.protocol)
    c.optionalBuffer.preencode(state, this.id)
    if (this._handshake) this._handshake.preencode(state, handshake)

    state.buffer = this._mux._alloc(state.end)

    state.buffer[0] = 0
    state.buffer[1] = 1
    c.uint.encode(state, this._localId)
    c.string.encode(state, this.protocol)
    c.optionalBuffer.encode(state, this.id)
    if (this._handshake) this._handshake.encode(state, handshake)

    this._mux._write0(state.buffer)
  }

  _dec() {
    if (--this._active === 0 && this.closed === true) this._destroy()
  }

  _decAndDestroy(err) {
    this._dec()
    this._mux._safeDestroy(err)
  }

  _fullyOpenSoon() {
    this._mux._remote[this._remoteId - 1].session = this
    queueTick(this._fullyOpenOrDestroy.bind(this))
  }

  _fullyOpenOrDestroy() {
    try {
      this._fullyOpen()
    } catch (err) {
      this._mux._safeDestroyBound(err)
    }
  }

  _fullyOpen() {
    if (this.opened === true || this.closed === true) return

    const remote = this._mux._remote[this._remoteId - 1]

    this.handshake = this._handshake ? this._handshake.decode(remote.state) : null
    this._track(this.onopen(this.handshake, this))

    remote.session = this
    remote.state = null
    if (remote.pending !== null) this._drain(remote)
    if (this._mux._destroying === true) return

    this.opened = true
    this._resolveOpen(true)
  }

  _resolveOpen(opened) {
    if (this._openedResolve !== null) {
      this._openedResolve(opened)
      this._openedResolve = this._openedPromise = null
    }
  }

  _resolveDestroyed() {
    if (this._destroyedResolve !== null) {
      this._destroyedResolve()
      this._destroyedResolve = this._destroyedPromise = null
    }
  }

  _drain(remote) {
    for (let i = 0; i < remote.pending.length; i++) {
      const p = remote.pending[i]
      this._mux._buffered -= byteSize(p.state)
      this._recv(p.type, p.state)
      if (this._mux._destroying === true) return
    }

    remote.pending = null
    this._mux._resumeMaybe()
  }

  _track(p) {
    if (isPromise(p) === true) {
      this._active++
      return p.then(this._decBound, this._decAndDestroyBound)
    }

    return null
  }

  _close(isRemote) {
    if (this.closed === true) return
    this.closed = true

    this._info.opened--
    if (this._info.lastChannel === this) this._info.lastChannel = null

    if (this._remoteId > 0) {
      this._mux._remote[this._remoteId - 1] = null
      this._remoteId = 0
      // If remote has acked, we can reuse the local id now
      // otherwise, we need to wait for the "ack" to arrive
      this._mux._free.push(this._localId - 1)
    }

    this._mux._local[this._localId - 1] = null
    this._localId = 0

    this._mux._gc(this._info)
    this._track(this.onclose(isRemote, this))

    if (this._active === 0) this._destroy()

    this._resolveOpen(false)
  }

  _destroy() {
    if (this.destroyed === true) return
    this.destroyed = true
    this._track(this.ondestroy(this))
    this._resolveDestroyed()
  }

  _recv(type, state) {
    if (type < this.messages.length) {
      const m = this.messages[type]
      const p = m.recv(state, this)
      if (m.autoBatch === true) return p
    }
    return null
  }

  cork() {
    this._mux.cork()
  }

  uncork() {
    this._mux.uncork()
  }

  close() {
    if (this.closed === true) return

    const state = { buffer: null, start: 2, end: 2 }

    c.uint.preencode(state, this._localId)

    state.buffer = this._mux._alloc(state.end)

    state.buffer[0] = 0
    state.buffer[1] = 3
    c.uint.encode(state, this._localId)

    this._close(false)
    this._mux._write0(state.buffer)
  }

  addMessage(opts) {
    if (!opts) return this._skipMessage()

    const type = this.messages.length
    const autoBatch = opts.autoBatch !== false
    const encoding = opts.encoding || c.raw
    const onmessage = opts.onmessage || noop

    const s = this
    const typeLen = encodingLength(c.uint, type)

    const m = {
      type,
      autoBatch,
      encoding,
      onmessage,
      recv(state, session) {
        return session._track(m.onmessage(encoding.decode(state), session))
      },
      send(m, session = s) {
        if (session.closed === true) return false

        const mux = session._mux
        const state = { buffer: null, start: 0, end: typeLen }

        if (mux._batch !== null) {
          encoding.preencode(state, m)
          state.buffer = mux._alloc(state.end)

          c.uint.encode(state, type)
          encoding.encode(state, m)

          mux._pushBatch(session._localId, state.buffer)
          return true
        }

        c.uint.preencode(state, session._localId)
        encoding.preencode(state, m)

        state.buffer = mux._alloc(state.end)

        c.uint.encode(state, session._localId)
        c.uint.encode(state, type)
        encoding.encode(state, m)

        mux.drained = mux.stream.write(state.buffer)

        return mux.drained
      }
    }

    this.messages.push(m)

    return m
  }

  _skipMessage() {
    const type = this.messages.length
    const m = {
      type,
      encoding: c.raw,
      onmessage: noop,
      recv(state, session) {},
      send(m, session) {}
    }

    this.messages.push(m)
    return m
  }
}

module.exports = class Protomux {
  constructor(stream, { alloc } = {}) {
    if (stream.userData === null) stream.userData = this

    this.isProtomux = true
    this.stream = stream
    this.corked = 0
    this.drained = true

    this._alloc =
      alloc || (typeof stream.alloc === 'function' ? stream.alloc.bind(stream) : b4a.allocUnsafe)
    this._safeDestroyBound = this._safeDestroy.bind(this)
    this._uncorkBound = this.uncork.bind(this)

    this._remoteBacklog = 0
    this._buffered = 0
    this._paused = false
    this._remote = []
    this._local = []
    this._free = []
    this._batch = null
    this._batchState = null

    this._infos = new Map()
    this._notify = new Map()
    // stream.destroyed flips asynchronously on streamx-based transports.
    this._destroying = false

    this.stream.on('data', this._ondata.bind(this))
    this.stream.on('drain', this._ondrain.bind(this))
    this.stream.on('end', this._onend.bind(this))
    this.stream.on('error', noop) // we handle this in "close"
    this.stream.on('close', this._shutdown.bind(this))
  }

  static from(stream, opts) {
    if (stream.userData && stream.userData.isProtomux) return stream.userData
    if (stream.isProtomux) return stream
    return new this(stream, opts)
  }

  static isProtomux(mux) {
    return typeof mux === 'object' && mux.isProtomux === true
  }

  *[Symbol.iterator]() {
    for (const session of this._local) {
      if (session !== null) yield session
    }
  }

  isIdle() {
    return this._local.length === this._free.length
  }

  cork() {
    if (++this.corked === 1) {
      this._batch = []
      this._batchState = { buffer: null, start: 0, end: 1 }
    }
  }

  uncork() {
    if (--this.corked === 0) {
      this._sendBatch(this._batch, this._batchState)
      this._batch = null
      this._batchState = null
    }
  }

  getLastChannel({ protocol, id = null }) {
    const key = toKey(protocol, id)
    const info = this._infos.get(key)
    if (info) return info.lastChannel
    return null
  }

  pair({ protocol, id = null }, notify) {
    this._notify.set(toKey(protocol, id), notify)
  }

  unpair({ protocol, id = null }) {
    this._notify.delete(toKey(protocol, id))
  }

  opened({ protocol, id = null }) {
    const key = toKey(protocol, id)
    const info = this._infos.get(key)
    return info ? info.opened > 0 : false
  }

  createChannel({
    userData = null,
    protocol,
    aliases = [],
    id = null,
    unique = true,
    handshake = null,
    messages = [],
    onopen = noop,
    onclose = noop,
    ondestroy = noop,
    ondrain = noop
  }) {
    if (this.stream.destroyed) return null

    const info = this._get(protocol, id, aliases)
    if (unique && info.opened > 0) return null

    if (info.incoming.length === 0) {
      return new Channel(
        this,
        info,
        userData,
        protocol,
        aliases,
        id,
        handshake,
        messages,
        onopen,
        onclose,
        ondestroy,
        ondrain
      )
    }

    this._remoteBacklog--

    const remoteId = info.incoming.shift()
    const r = this._remote[remoteId - 1]
    if (r === null) return null

    const session = new Channel(
      this,
      info,
      userData,
      protocol,
      aliases,
      id,
      handshake,
      messages,
      onopen,
      onclose,
      ondestroy,
      ondrain
    )

    session._remoteId = remoteId
    session._fullyOpenSoon()

    return session
  }

  _pushBatch(localId, buffer) {
    if (this._batchState.end >= MAX_BATCH) {
      this._sendBatch(this._batch, this._batchState)
      this._batch = []
      this._batchState = { buffer: null, start: 0, end: 1 }
    }

    if (this._batch.length === 0 || this._batch[this._batch.length - 1].localId !== localId) {
      this._batchState.end++
      c.uint.preencode(this._batchState, localId)
    }
    c.buffer.preencode(this._batchState, buffer)
    this._batch.push({ localId, buffer })
  }

  _sendBatch(batch, state) {
    if (batch.length === 0) return

    let prev = batch[0].localId

    state.buffer = this._alloc(state.end)
    state.buffer[state.start++] = 0
    state.buffer[state.start++] = 0

    c.uint.encode(state, prev)

    for (let i = 0; i < batch.length; i++) {
      const b = batch[i]
      if (prev !== b.localId) {
        state.buffer[state.start++] = 0
        c.uint.encode(state, (prev = b.localId))
      }
      c.buffer.encode(state, b.buffer)
    }

    this.drained = this.stream.write(state.buffer)
  }

  _get(protocol, id, aliases = []) {
    const key = toKey(protocol, id)

    let info = this._infos.get(key)
    if (info) return info

    info = {
      key,
      protocol,
      aliases: [],
      id,
      pairing: 0,
      opened: 0,
      incoming: [],
      outgoing: [],
      lastChannel: null
    }
    this._infos.set(key, info)

    for (const alias of aliases) {
      const key = toKey(alias, id)
      info.aliases.push(key)

      this._infos.set(key, info)
    }

    return info
  }

  _gc(info) {
    if (info.opened === 0 && info.outgoing.length === 0 && info.incoming.length === 0) {
      this._infos.delete(info.key)

      for (const alias of info.aliases) this._infos.delete(alias)
    }
  }

  _ondata(buffer) {
    if (buffer.byteLength === 0) return // ignore empty frames...
    try {
      const state = { buffer, start: 0, end: buffer.byteLength }
      this._decode(c.uint.decode(state), state)
    } catch (err) {
      this._safeDestroy(err)
    }
  }

  _ondrain() {
    this.drained = true

    for (const s of this._local) {
      if (s !== null) s._track(s.ondrain(s))
    }
  }

  _onend() {
    // TODO: support half open mode for the users who wants that here
    this.stream.end()
  }

  _decode(remoteId, state) {
    const type = c.uint.decode(state)

    if (remoteId === 0) {
      return this._oncontrolsession(type, state)
    }

    const r = remoteId <= this._remote.length ? this._remote[remoteId - 1] : null

    // if the channel is closed ignore - could just be a pipeline message...
    if (r === null) return null

    if (r.pending !== null) {
      this._bufferMessage(r, type, state)
      return null
    }

    return r.session._recv(type, state)
  }

  _oncontrolsession(type, state) {
    switch (type) {
      case 0:
        this._onbatch(state)
        break

      case 1:
        // return the promise back up as this has sideeffects so we can batch reply
        return this._onopensession(state)

      case 2:
        this._onrejectsession(state)
        break

      case 3:
        this._onclosesession(state)
        break
    }

    return null
  }

  _bufferMessage(r, type, { buffer, start, end }) {
    const state = { buffer, start, end } // copy
    r.pending.push({ type, state })
    this._buffered += byteSize(state)
    this._pauseMaybe()
  }

  _pauseMaybe() {
    if (this._paused === true || this._buffered <= MAX_BUFFERED) return
    this._paused = true
    this.stream.pause()
  }

  _resumeMaybe() {
    if (this._paused === false || this._buffered > MAX_BUFFERED) return
    this._paused = false
    this.stream.resume()
  }

  _onbatch(state) {
    const end = state.end
    let remoteId = c.uint.decode(state)

    let waiting = null

    while (state.end > state.start) {
      const len = c.uint.decode(state)
      if (len === 0) {
        remoteId = c.uint.decode(state)
        continue
      }
      state.end = state.start + len
      // if batch contains more than one message, cork it so we reply back with a batch
      if (end !== state.end && waiting === null) {
        waiting = []
        this.cork()
      }
      const p = this._decode(remoteId, state)
      if (waiting !== null && p !== null) waiting.push(p)
      state.start = state.end
      state.end = end
    }

    if (waiting !== null) {
      // the waiting promises are not allowed to throw but we destroy the stream in case we are wrong
      Promise.all(waiting).then(this._uncorkBound, this._safeDestroyBound)
    }
  }

  _onopensession(state) {
    const remoteId = c.uint.decode(state)
    const protocol = c.string.decode(state)
    const id = unslab(c.optionalBuffer.decode(state))

    // remote tried to open the control session - auto reject for now
    // as we can use as an explicit control protocol declaration if we need to
    if (remoteId === 0) {
      this._rejectSession(0)
      return null
    }

    const rid = remoteId - 1
    const info = this._get(protocol, id)

    // allow the remote to grow the ids by one
    if (this._remote.length === rid) {
      this._remote.push(null)
    }

    if (rid >= this._remote.length || this._remote[rid] !== null) {
      throw new Error('Invalid open message')
    }

    if (info.outgoing.length > 0) {
      const localId = info.outgoing.shift()
      const session = this._local[localId - 1]

      if (session === null) {
        // we already closed the channel - ignore
        this._free.push(localId - 1)
        return null
      }

      this._remote[rid] = { state, pending: null, session: null }

      session._remoteId = remoteId
      session._fullyOpen()
      return null
    }

    const copyState = { buffer: state.buffer, start: state.start, end: state.end }
    this._remote[rid] = { state: copyState, pending: [], session: null }

    if (++this._remoteBacklog > MAX_BACKLOG) {
      throw new Error('Remote exceeded backlog')
    }

    info.pairing++
    info.incoming.push(remoteId)

    return this._requestSession(protocol, id, info).catch(this._safeDestroyBound)
  }

  _onrejectsession(state) {
    const localId = c.uint.decode(state)

    // TODO: can be done smarter...
    for (const info of this._infos.values()) {
      const i = info.outgoing.indexOf(localId)
      if (i === -1) continue

      info.outgoing.splice(i, 1)

      const session = this._local[localId - 1]

      this._free.push(localId - 1)
      if (session !== null) session._close(true)

      this._gc(info)
      return
    }

    throw new Error('Invalid reject message')
  }

  _onclosesession(state) {
    const remoteId = c.uint.decode(state)

    if (remoteId === 0) return // ignore

    const rid = remoteId - 1
    const r = rid < this._remote.length ? this._remote[rid] : null

    if (r === null) return

    if (r.session !== null) r.session._close(true)
  }

  async _requestSession(protocol, id, info) {
    const notify = this._notify.get(toKey(protocol, id)) || this._notify.get(toKey(protocol, null))

    if (notify) await notify(id)

    if (--info.pairing > 0) return

    while (info.incoming.length > 0) {
      this._rejectSession(info, info.incoming.shift())
    }

    this._gc(info)
  }

  _rejectSession(info, remoteId) {
    if (remoteId > 0) {
      const r = this._remote[remoteId - 1]

      if (r.pending !== null) {
        for (let i = 0; i < r.pending.length; i++) {
          this._buffered -= byteSize(r.pending[i].state)
        }
      }

      this._remote[remoteId - 1] = null
      this._resumeMaybe()
    }

    const state = { buffer: null, start: 2, end: 2 }

    c.uint.preencode(state, remoteId)

    state.buffer = this._alloc(state.end)

    state.buffer[0] = 0
    state.buffer[1] = 2
    c.uint.encode(state, remoteId)

    this._write0(state.buffer)
  }

  _write0(buffer) {
    if (this._batch !== null) {
      this._pushBatch(0, buffer.subarray(1))
      return
    }

    this.drained = this.stream.write(buffer)
  }

  destroy(err) {
    this._destroying = true
    this.stream.destroy(err)
  }

  _safeDestroy(err) {
    safetyCatch(err)
    this._destroying = true
    this.stream.destroy(err)
  }

  _shutdown() {
    this._destroying = true
    for (const s of this._local) {
      if (s !== null) s._close(true)
    }
  }
}

function noop() {}

function toKey(protocol, id) {
  return protocol + '##' + (id ? b4a.toString(id, 'hex') : '')
}

function byteSize(state) {
  return 512 + (state.end - state.start)
}

function isPromise(p) {
  return !!(p && typeof p.then === 'function')
}

function encodingLength(enc, val) {
  const state = { buffer: null, start: 0, end: 0 }
  enc.preencode(state, val)
  return state.end
}
{
  "name": "protomux",
  "version": "3.11.0",
  "description": "Multiplex multiple message oriented protocols over a stream",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.3.1",
    "compact-encoding": "^3.0.0",
    "queue-tick": "^1.0.0",
    "safety-catch": "^1.0.1",
    "unslab": "^1.3.0"
  },
  "devDependencies": {
    "@hyperswarm/secret-stream": "^6.0.0",
    "brittle": "^3.0.0",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/protomux.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/protomux/issues"
  },
  "homepage": "https://github.com/holepunchto/protomux"
}
{
  "name": "queue-tick",
  "version": "1.0.1",
  "description": "Next tick shim that prefers process.nextTick over queueMicrotask for compat",
  "main": "./process-next-tick.js",
  "browser": "./queue-microtask.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^16.0.3",
    "tape": "^5.3.1"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/queue-tick.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/queue-tick/issues"
  },
  "homepage": "https://github.com/mafintosh/queue-tick"
}
module.exports = (typeof process !== 'undefined' && typeof process.nextTick === 'function')
  ? process.nextTick.bind(process)
  : require('./queue-microtask')
module.exports = typeof queueMicrotask === 'function' ? queueMicrotask : (fn) => Promise.resolve().then(fn)
const EventEmitter = require('events')

module.exports = class ReadyResource extends EventEmitter {
  constructor () {
    super()

    this.opening = null
    this.closing = null

    this.opened = false
    this.closed = false
  }

  ready () {
    if (this.opening !== null) return this.opening
    this.opening = open(this)
    return this.opening
  }

  close () {
    if (this.closing !== null) return this.closing
    this.closing = close(this)
    return this.closing
  }

  async _open () {
    // add impl here
  }

  async _close () {
    // add impl here
  }
}

async function open (self) {
  // open after close
  if (self.closing !== null) return

  try {
    await self._open()
  } catch (err) {
    self.close() // safe to run in bg
    throw err
  }

  self.opened = true
  self.emit('ready')
}

async function close (self) {
  try {
    if (self.opened === false && self.opening !== null) await self.opening
  } catch {
    // ignore errors on closing
  }
  if (self.opened === true || self.opening === null) await self._close()
  self.closed = true
  self.emit('close')
}
{
  "name": "ready-resource",
  "version": "1.2.0",
  "description": "Modern single resource management",
  "main": "index.js",
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "types": "index.d.ts",
  "files": [
    "index.js",
    "index.d.ts"
  ],
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "devDependencies": {
    "brittle": "^3.1.0",
    "standard": "^17.0.0"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/ready-resource.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/ready-resource/issues"
  },
  "homepage": "https://github.com/holepunchto/ready-resource",
  "dependencies": {
    "bare-events": "^2.2.0"
  }
}
const b4a = require('b4a')

var EMPTY = []

module.exports = RecordCache

function RecordSet () {
  this.list = []
  this.map = new Map()
}

RecordSet.prototype.add = function (record, value) {
  var k = toString(record)
  var r = this.map.get(k)
  if (r) return false

  r = {index: this.list.length, record: value || record}
  this.list.push(r)
  this.map.set(k, r)
  return true
}

RecordSet.prototype.remove = function (record) {
  var k = toString(record)
  var r = this.map.get(k)
  if (!r) return false

  swap(this.list, r.index, this.list.length - 1)
  this.list.pop()
  this.map.delete(k)
  return true
}

function RecordStore () {
  this.records = new Map()
  this.size = 0
}

RecordStore.prototype.add = function (name, record, value) {
  var r = this.records.get(name)

  if (!r) {
    r = new RecordSet()
    this.records.set(name, r)
  }

  if (r.add(record, value)) {
    this.size++
    return true
  }

  return false
}

RecordStore.prototype.remove = function (name, record, value) {
  var r = this.records.get(name)
  if (!r) return false

  if (r.remove(record, value)) {
    this.size--
    if (!r.map.size) this.records.delete(name)
    return true
  }

  return false
}

RecordStore.prototype.get = function (name) {
  var r = this.records.get(name)
  return r ? r.list : EMPTY
}

function RecordCache (opts) {
  if (!(this instanceof RecordCache)) return new RecordCache(opts)
  if (!opts) opts = {}

  this.maxSize = opts.maxSize || Infinity
  this.maxAge = opts.maxAge || 0

  this._onstale = opts.onStale || opts.onstale || null
  this._fresh = new RecordStore()
  this._stale = new RecordStore()
  this._interval = null
  this._gced = false

  if (this.maxAge && this.maxAge < Infinity) {
    // 2/3 gives us a span of 0.66-1.33 maxAge or avg maxAge
    var tick = Math.ceil(2 / 3 * this.maxAge)
    this._interval = setInterval(this._gcAuto.bind(this), tick)
    if (this._interval.unref) this._interval.unref()
  }
}

Object.defineProperty(RecordCache.prototype, 'size', {
  get: function () {
    return this._fresh.size + this._stale.size
  }
})

RecordCache.prototype.add = function (name, record, value) {
  this._stale.remove(name, record, value)
  if (this._fresh.add(name, record, value) && this._fresh.size > this.maxSize) {
    this._gc()
  }
}

RecordCache.prototype.remove = function (name, record, value) {
  this._fresh.remove(name, record, value)
  this._stale.remove(name, record, value)
}

RecordCache.prototype.get = function (name, n) {
  var a = this._fresh.get(name)
  var b = this._stale.get(name)
  var aLen = a.length
  var bLen = b.length
  var len = aLen + bLen

  if (n > len || !n) n = len
  var result = new Array(n)

  for (var i = 0; i < n; i++) {
    var j = Math.floor(Math.random() * (aLen + bLen))
    if (j < aLen) {
      result[i] = a[j].record
      swap(a, j, --aLen)
    } else {
      j -= aLen
      result[i] = b[j].record
      swap(b, j, --bLen)
    }
  }

  return result
}

RecordCache.prototype._gcAuto = function () {
  if (!this._gced) this._gc()
  this._gced = false
}

RecordCache.prototype._gc = function () {
  if (this._onstale && this._stale.size > 0) this._onstale(this._stale)
  this._stale = this._fresh
  this._fresh = new RecordStore()
  this._gced = true
}

RecordCache.prototype.clear = function () {
  this._gc()
  this._gc()
}

RecordCache.prototype.destroy = function () {
  this.clear()
  clearInterval(this._interval)
  this._interval = null
}

function toString (record) {
  return b4a.isBuffer(record) ? b4a.toString(record, 'hex') : record
}

function swap (list, a, b) {
  var tmp = list[a]
  tmp.index = b
  list[b].index = a
  list[a] = list[b]
  list[b] = tmp
}
{
  "name": "record-cache",
  "version": "1.2.0",
  "description": "Cache optimised for record like things",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.3.1"
  },
  "devDependencies": {
    "standard": "^10.0.3",
    "tape": "^4.8.0"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/record-cache.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/record-cache/issues"
  },
  "homepage": "https://github.com/mafintosh/record-cache"
}
module.exports = require.addon.bind(require)
{
  "name": "require-addon",
  "version": "1.2.0",
  "description": "Import native addons across JavaScript runtimes",
  "exports": {
    "./package": "./package.json",
    ".": {
      "bare": "./lib/bare.js",
      "node": "./lib/node.js",
      "default": "./lib/default.js"
    }
  },
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    },
    "url": {
      "bare": "bare-url",
      "default": "url"
    }
  },
  "files": [
    "lib"
  ],
  "scripts": {
    "test": "npm run lint && npm run test:bare && npm run test:node",
    "test:bare": "bare test.js",
    "test:node": "node test.js",
    "lint": "prettier --check .",
    "format": "prettier --write ."
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/require-addon.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/require-addon/issues"
  },
  "homepage": "https://github.com/holepunchto/require-addon#readme",
  "engines": {
    "bare": ">=1.10.0"
  },
  "dependencies": {
    "bare-addon-resolve": "^1.3.0"
  },
  "devDependencies": {
    "bare-bundle": "^1.8.1",
    "bare-bundle-evaluate": "^1.1.0",
    "bare-fs": "^4.0.0",
    "bare-path": "^3.0.0",
    "bare-url": "^2.1.0",
    "brittle": "^3.7.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = safetyCatch

function isActuallyUncaught (err) {
  if (!err) return false
  return err instanceof TypeError ||
    err instanceof SyntaxError ||
    err instanceof ReferenceError ||
    err instanceof EvalError ||
    err instanceof RangeError ||
    err instanceof URIError ||
    err.code === 'ERR_ASSERTION' ||
    err.name === 'AssertionError'
}

function throwErrorNT (err) {
  queueMicrotask(() => { throw err })
}

function safetyCatch (err) {
  if (isActuallyUncaught(err)) {
    throwErrorNT(err)
    throw err
  }
}
{
  "name": "safety-catch",
  "version": "1.0.3",
  "description": "Small module that makes sure your catch, caught an actual error and not a programming mistake or assertion",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {},
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/safety-catch.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/safety-catch/issues"
  },
  "homepage": "https://github.com/mafintosh/safety-catch"
}
const set = require('unordered-set')

module.exports = opts => new ShuffledPriorityQueue(opts)

class ShuffledPriorityQueue {
  constructor (opts) {
    this.priorities = []
    this.equals = (opts && opts.equals) || null
  }

  get length () {
    return this.priorities.reduce(add, 0)
  }

  [Symbol.iterator] () {
    return new Iterator(this)
  }

  head () {
    for (let i = this.priorities.length - 1; i >= 0; i--) {
      const q = this.priorities[i]
      if (q.length) return shuffle(q, 0)
    }
    return null
  }

  tail () {
    for (let i = 0; i < this.priorities.length; i++) {
      const q = this.priorities[i]
      if (q.length) return shuffle(q, 0)
    }
    return null
  }

  prev (prev) {
    if (!prev) return this.tail()
    return next(this.priorities, prev, 1)
  }

  next (prev) {
    if (!prev) return this.head()
    return next(this.priorities, prev, -1)
  }

  shift () {
    return this.remove(this.head())
  }

  pop () {
    return this.remove(this.tail())
  }

  add (val) {
    const prio = val.priority || 0
    while (prio >= this.priorities.length) this.priorities.push([])
    set.add(this.priorities[prio], val)
    return val
  }

  remove (val) {
    if (!val) return null

    if (val._index === undefined) {
      val = this.find(val)
      if (!val) return null
    }

    return set.remove(this.priorities[val.priority || 0], val)
  }

  has (val) {
    if (val._index === undefined) return this.find(val)
    const priority = val.priority || 0
    if (priority >= this.priorities.length) return false
    return set.has(this.priorities[priority], val)
  }

  find (val) {
    if (val._index !== undefined) return val

    const prio = val.priority || 0
    const qs = this.priorities
    if (prio >= qs.length) return null

    const q = qs[prio]

    for (let i = 0; i < q.length; i++) {
      if (this.equals(q[i], val)) return q[i]
    }

    return null
  }
}

class Iterator {
  constructor (queue) {
    this.prev = null
    this.queue = queue
  }

  next () {
    const next = this.queue.next(this.prev)
    this.prev = next
    return { done: !next, value: next }
  }
}

function shuffle (q, i) {
  const ran = i + Math.floor(Math.random() * (q.length - i))
  set.swap(q, q[ran], q[i])
  return q[i]
}

function next (queues, prev, inc) {
  let i = prev.priority || 0
  let j = (prev._index || 0) + 1

  while (true) {
    if (i < 0 || i >= queues.length) return null
    const q = queues[i]

    if (j >= q.length) {
      i += inc
      j = 0
      continue
    }

    return shuffle(q, j)
  }
}

function add (len, b) {
  return len + b.length
}
{
  "name": "shuffled-priority-queue",
  "version": "2.1.0",
  "description": "A priority queue that shuffles elements with the same priority.",
  "main": "index.js",
  "scripts": {
    "test": "standard && tape test.js"
  },
  "dependencies": {
    "unordered-set": "^2.0.1"
  },
  "devDependencies": {
    "standard": "^12.0.1",
    "tape": "^4.9.1"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/shuffled-priority-queue.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/shuffled-priority-queue/issues"
  },
  "homepage": "https://github.com/mafintosh/shuffled-priority-queue"
}
module.exports = class Signal {
  constructor () {
    this._resolve = null
    this._reject = null
    this._promise = null
    this._bind = bind.bind(this)
    this._onerror = clear.bind(this)
    this._onsuccess = clear.bind(this, null)
    this._timers = new Set()
  }

  wait (max) {
    if (!this._promise) {
      this._promise = new Promise(this._bind)
      this._promise.then(this._onsuccess).catch(this._onerror)
    }
    if (max) return this._sleep(max)
    return this._promise
  }

  _sleep (max) {
    const s = new Promise((resolve, reject) => {
      const done = () => {
        this._timers.delete(state)
        resolve(true)
      }
      const id = setTimeout(done, max)
      const state = { id, resolve, reject }
      this._timers.add(state)
    })

    return s
  }

  notify (err) {
    if (!this._promise) return
    const resolve = this._resolve
    const reject = this._reject
    this._promise = null
    if (err) reject(err)
    else resolve(true)
  }
}

function clear (err) {
  for (const { id, resolve, reject } of this._timers) {
    clearTimeout(id)
    if (err) reject(err)
    else resolve(true)
  }
  this._timers.clear()
}

function bind (resolve, reject) {
  this._resolve = resolve
  this._reject = reject
}
{
  "name": "signal-promise",
  "version": "1.0.3",
  "description": "Simple wait/notify promise with optional max wait time",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {},
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/signal-promise.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/signal-promise/issues"
  },
  "homepage": "https://github.com/mafintosh/signal-promise"
}
require.addon = require('require-addon')
module.exports = require.addon('.', __filename)
const assert = require('assert')
const binding = require('./binding')
const { isNode } = require('which-runtime')

const OPTIONAL = Buffer.from(new ArrayBuffer(0))

module.exports = exports = { ...binding }

// memory

exports.sodium_memzero = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  binding.sodium_memzero(buf)
}

exports.sodium_mlock = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  const res = binding.sodium_mlock(buf)

  if (res !== 0) throw new Error('memory lock failed')
}

exports.sodium_munlock = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  const res = binding.sodium_munlock(buf)

  if (res !== 0) throw new Error('memory unlock failed')
}

exports.sodium_malloc = function (size) {
  assert(size >= 0, 'invalid size')

  const buf = Buffer.from(binding.sodium_malloc(size))
  buf.secure = true
  return buf
}

exports.sodium_free = function (buf) {
  if (!buf || !buf.secure) return

  binding.sodium_free(buf.buffer)
}

exports.sodium_mprotect_noaccess = function (buf) {
  const res = binding.sodium_mprotect_noaccess(buf.buffer)

  if (res !== 0) throw new Error('failed to lock buffer')
}

exports.sodium_mprotect_readonly = function (buf) {
  const res = binding.sodium_mprotect_readonly(buf.buffer)

  if (res !== 0) throw new Error('failed to unlock buffer')
}

exports.sodium_mprotect_readwrite = function (buf) {
  const res = binding.sodium_mprotect_readwrite(buf.buffer)

  if (res !== 0) throw new Error('failed to unlock buffer')
}

// crypto_randombytes

exports.randombytes_buf = function (buffer) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')

  binding.randombytes_buf(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

exports.randombytes_buf_deterministic = function (buffer, seed) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    seed.byteLength === binding.randombytes_SEEDBYTES,
    "seed must be 'randombytes_SEEDBYTES' bytes"
  )

  binding.randombytes_buf_deterministic(
    buffer.buffer,
    buffer.byteOffset,
    buffer.byteLength,

    seed.buffer,
    seed.byteOffset,
    seed.byteLength
  )
}

// sodium_helpers

exports.sodium_memcmp = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  return binding.sodium_memcmp(a, b)
}

exports.sodium_add = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  binding.sodium_add(a, b)
}

exports.sodium_sub = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  binding.sodium_sub(a, b)
}

exports.sodium_compare = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  return binding.sodium_compare(a, b)
}

exports.sodium_is_zero = function (buffer, length) {
  if (length === undefined) length = buffer.byteLength

  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(length >= 0 && length <= buffer.byteLength, 'invalid length')

  return binding.sodium_is_zero(buffer, length)
}

exports.sodium_pad = function (buffer, unpaddedBuflen, blockSize) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(unpaddedBuflen <= buffer.byteLength, 'unpadded length cannot exceed buffer length')
  assert(blockSize <= buffer.byteLength, 'block size cannot exceed buffer length')
  assert(blockSize >= 1, 'block size must be at least 1 byte')
  assert(
    buffer.byteLength >= unpaddedBuflen + (blockSize - (unpaddedBuflen % blockSize)),
    'buf not long enough'
  )

  return binding.sodium_pad(buffer, unpaddedBuflen, blockSize)
}

exports.sodium_unpad = function (buffer, paddedBuflen, blockSize) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(paddedBuflen <= buffer.byteLength, 'unpadded length cannot exceed buffer length')
  assert(blockSize <= buffer.byteLength, 'block size cannot exceed buffer length')
  assert(blockSize >= 1, 'block size must be at least 1 byte')

  return binding.sodium_unpad(buffer, paddedBuflen, blockSize)
}

// crypto_sign

exports.crypto_sign_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )
  assert(
    seed.byteLength === binding.crypto_sign_SEEDBYTES,
    "seed must be 'crypto_sign_SEEDBYTES' bytes"
  )

  const res = binding.crypto_sign_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign = function (sm, m, sk) {
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sm.byteLength === binding.crypto_sign_BYTES + m.byteLength,
    "sm must be 'm.byteLength + crypto_sign_BYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign(sm, m, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_open = function (m, sm, pk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sm.byteLength >= binding.crypto_sign_BYTES,
    "sm must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    m.byteLength === sm.byteLength - binding.crypto_sign_BYTES,
    "m must be 'sm.byteLength - crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_open(m, sm, pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_open = function (m, sm, pk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sm.byteLength >= binding.crypto_sign_BYTES,
    "sm must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    m.byteLength === sm.byteLength - binding.crypto_sign_BYTES,
    "m must be 'sm.byteLength - crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  return binding.crypto_sign_open(m, sm, pk)
}

exports.crypto_sign_detached = function (sig, m, sk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(sig.byteLength === binding.crypto_sign_BYTES, "sig must be 'crypto_sign_BYTES' bytes")
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_detached(sig, m, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_verify_detached = function (sig, m, pk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sig.byteLength >= binding.crypto_sign_BYTES,
    "sig must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  return binding.crypto_sign_verify_detached(
    sig.buffer,
    sig.byteOffset,
    sig.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    pk.buffer,
    pk.byteOffset,
    pk.byteLength
  )
}

exports.crypto_sign_ed25519_sk_to_pk = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_sk_to_pk(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_ed25519_pk_to_curve25519 = function (x25519pk, ed25519pk) {
  assert(ArrayBuffer.isView(x25519pk), 'x25519pk must be a typed array')
  assert(ArrayBuffer.isView(ed25519pk), 'ed25519pk must be a typed array')
  assert(
    x25519pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "x25519pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    ed25519pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "ed25519pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_pk_to_curve25519(x25519pk, ed25519pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_ed25519_sk_to_curve25519 = function (x25519sk, ed25519sk) {
  assert(ArrayBuffer.isView(x25519sk), 'x25519sk must be a typed array')
  assert(ArrayBuffer.isView(ed25519sk), 'ed25519sk must be a typed array')
  assert(
    x25519sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "x25519sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const edLen = ed25519sk.byteLength

  assert(
    edLen === binding.crypto_sign_SECRETKEYBYTES || edLen === binding.crypto_box_SECRETKEYBYTES,
    "ed25519sk must be 'crypto_sign_SECRETKEYBYTES' or 'crypto_sign_SECRETKEYBYTES - crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_sk_to_curve25519(x25519sk, ed25519sk)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_box

exports.crypto_box_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    seed.byteLength === binding.crypto_box_SEEDBYTES,
    "seed must be 'crypto_box_SEEDBYTES' bytes"
  )

  const res = binding.crypto_box_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_easy = function (c, m, n, pk, sk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength === m.byteLength + exports.crypto_box_MACBYTES,
    "c must be 'm.byteLength + crypto_box_MACBYTES' bytes"
  )
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_easy(c, m, n, pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_detached = function (c, mac, m, n, pk, sk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(mac.byteLength === exports.crypto_box_MACBYTES, "mac must be 'crypto_box_MACBYTES' bytes")
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_detached(c, mac, m, n, pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_open_easy = function (m, c, n, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength >= exports.crypto_box_MACBYTES,
    "c must be at least 'crypto_box_MACBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - exports.crypto_box_MACBYTES,
    "m must be 'c.byteLength - crypto_box_MACBYTES' bytes"
  )
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_open_easy(m, c, n, pk, sk)
}

exports.crypto_box_open_detached = function (m, c, mac, n, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(mac.byteLength === exports.crypto_box_MACBYTES, "mac must be 'crypto_box_MACBYTES' bytes")
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_open_detached(m, c, mac, n, pk, sk)
}

exports.crypto_box_seal = function (c, m, pk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    c.byteLength === m.byteLength + exports.crypto_box_SEALBYTES,
    "c must be 'm.byteLength + crypto_box_SEALBYTES' bytes"
  )
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_box_seal(c, m, pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_seal_open = function (m, c, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength >= exports.crypto_box_SEALBYTES,
    "c must be at least 'crypto_box_SEALBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - exports.crypto_box_SEALBYTES,
    "m must be 'c.byteLength - crypto_box_SEALBYTES' bytes"
  )
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_seal_open(
    m.buffer,
    m.byteOffset,
    m.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    pk.buffer,
    pk.byteOffset,
    pk.byteLength,

    sk.buffer,
    sk.byteOffset,
    sk.byteLength
  )
}

// crypto_secretbox

exports.crypto_secretbox_easy = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_secretbox_MACBYTES,
    "c must be 'm.byteLength + crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretbox_easy(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretbox_open_easy = function (m, c, n, k) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    c.byteLength >= binding.crypto_secretbox_MACBYTES,
    "c must be at least 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - binding.crypto_secretbox_MACBYTES,
    "m must be 'c.byteLength - crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  return binding.crypto_secretbox_open_easy(m, c, n, k)
}

exports.crypto_secretbox_detached = function (c, mac, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    mac.byteLength === binding.crypto_secretbox_MACBYTES,
    "mac must be 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretbox_detached(c, mac, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretbox_open_detached = function (m, c, mac, n, k) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(
    mac.byteLength === binding.crypto_secretbox_MACBYTES,
    "mac must be 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  return binding.crypto_secretbox_open_detached(m, c, mac, n, k)
}

// crypto_generichash

exports.crypto_generichash = function (output, input, key) {
  if (!key) key = OPTIONAL

  assert(ArrayBuffer.isView(output), 'output must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    output.byteLength >= binding.crypto_generichash_BYTES_MIN &&
      output.byteLength <= binding.crypto_generichash_BYTES_MAX,
    'output must be between crypto_generichash_BYTES_MIN and crypto_generichash_BYTES_MAX bytes'
  )

  if (key !== OPTIONAL) {
    assert(ArrayBuffer.isView(key), 'key must be a typed array')
    assert(
      key.byteLength >= binding.crypto_generichash_KEYBYTES_MIN &&
        key.byteLength <= binding.crypto_generichash_KEYBYTES_MAX,
      'key must be between crypto_generichash_KEYBYTES_MIN and crypto_generichash_KEYBYTES_MAX bytes'
    )
  }

  const res = binding.crypto_generichash(
    output.buffer,
    output.byteOffset,
    output.byteLength,

    input.buffer,
    input.byteOffset,
    input.byteLength,

    key.buffer,
    key.byteOffset,
    key.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_batch = function (output, batch, key) {
  assert(ArrayBuffer.isView(output), 'output must be a typed array')

  if (isNode || batch.length < 4) {
    const res = binding.crypto_generichash_batch(output, batch, !!key, key || OPTIONAL)
    if (res !== 0) throw new Error('status: ' + res)
  } else {
    const state = Buffer.alloc(binding.crypto_generichash_STATEBYTES)

    exports.crypto_generichash_init(state, key, output.byteLength)

    for (const buf of batch) {
      exports.crypto_generichash_update(state, buf)
    }

    exports.crypto_generichash_final(state, output)
  }
}

exports.crypto_generichash_keygen = function (key) {
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(
    key.byteLength === binding.crypto_generichash_KEYBYTES,
    "key must be 'crypto_generichash_KEYBYTES' bytes"
  )

  const res = binding.crypto_generichash_keygen(key.buffer, key.byteOffset, key.byteLength)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_init = function (state, key, outputLength) {
  if (!key) key = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_init(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    key.buffer,
    key.byteOffset,
    key.byteLength,

    outputLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_update(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    input.buffer,
    input.byteOffset,
    input.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_final = function (state, output) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(output), 'output must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_final(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    output.buffer,
    output.byteOffset,
    output.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

// secretstream

exports.crypto_secretstream_xchacha20poly1305_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  binding.crypto_secretstream_xchacha20poly1305_keygen(k.buffer, k.byteOffset, k.byteLength)
}

exports.crypto_secretstream_xchacha20poly1305_init_push = function (state, header, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(header), 'header must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    header.byteLength === binding.crypto_secretstream_xchacha20poly1305_HEADERBYTES,
    "header must be 'crypto_secretstream_xchacha20poly1305_HEADERBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_init_push(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    header.buffer,
    header.byteOffset,
    header.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretstream_xchacha20poly1305_init_pull = function (state, header, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(header), 'header must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    header.byteLength === binding.crypto_secretstream_xchacha20poly1305_HEADERBYTES,
    "header must be 'crypto_secretstream_xchacha20poly1305_HEADERBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_init_pull(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    header.buffer,
    header.byteOffset,
    header.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretstream_xchacha20poly1305_push = function (state, c, m, ad, tag) {
  if (!ad) ad = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    c.byteLength === m.byteLength + binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "c must be 'm.byteLength + crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_push(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    ad.buffer,
    ad.byteOffset,
    ad.byteLength,

    tag
  )

  if (res < 0) throw new Error('push failed')

  return res
}

exports.crypto_secretstream_xchacha20poly1305_pull = function (state, m, tag, c, ad) {
  if (!ad) ad = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(tag), 'tag must be a typed array')
  assert(tag.byteLength === 1, 'tag must be 1 byte')

  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    c.byteLength >= binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "c must be at least 'crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "m must be 'c.byteLength - crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_pull(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    tag.buffer,
    tag.byteOffset,
    tag.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    ad.buffer,
    ad.byteOffset,
    ad.byteLength
  )

  if (res < 0) throw new Error('pull failed')

  return res
}

exports.crypto_secretstream_xchacha20poly1305_rekey = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )

  binding.crypto_secretstream_xchacha20poly1305_rekey(
    state.buffer,
    state.byteOffset,
    state.byteLength
  )
}

// crypto_stream

exports.crypto_stream = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xor(
    c.buffer,
    c.byteOffset,
    c.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    n.buffer,
    n.byteOffset,
    n.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_auth

exports.crypto_auth = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(out.byteLength === binding.crypto_auth_BYTES, "out must be 'crypto_auth_BYTES' bytes")
  assert(k.byteLength === binding.crypto_auth_KEYBYTES, "k must be 'crypto_auth_KEYBYTES' bytes")

  const res = binding.crypto_auth(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_auth_verify = function (h, input, k) {
  assert(ArrayBuffer.isView(h), 'h must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(h.byteLength === binding.crypto_auth_BYTES, "h must be 'crypto_auth_BYTES' bytes")
  assert(k.byteLength === binding.crypto_auth_KEYBYTES, "k must be 'crypto_auth_KEYBYTES' bytes")

  return binding.crypto_auth_verify(h, input, k)
}

// crypto_onetimeauth

exports.crypto_onetimeauth = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    out.byteLength === binding.crypto_onetimeauth_BYTES,
    "out must be 'crypto_onetimeauth_BYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_init = function (state, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_init(state, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )
  assert(
    out.byteLength === binding.crypto_onetimeauth_BYTES,
    "out must be 'crypto_onetimeauth_BYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_verify = function (h, input, k) {
  assert(ArrayBuffer.isView(h), 'h must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    h.byteLength === binding.crypto_onetimeauth_BYTES,
    "h must be 'crypto_onetimeauth_BYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  return binding.crypto_onetimeauth_verify(h, input, k)
}

// crypto_pwhash

exports.crypto_pwhash = function (out, passwd, salt, opslimit, memlimit, alg) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_BYTES_MIN,
    "out must be at least 'crypto_pwhash_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_BYTES_MAX,
    "out must be at most 'crypto_pwhash_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_SALTBYTES,
    "salt must be 'crypto_pwhash_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )
  assert(alg >= 1 && alg <= 2, 'alg must be either Argon2i 1.3 or Argon2id 1.3')

  const res = binding.crypto_pwhash(out, passwd, salt, opslimit, memlimit, alg)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_async = function (
  out,
  passwd,
  salt,
  opslimit,
  memlimit,
  alg,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_BYTES_MIN,
    "out must be at least 'crypto_pwhash_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_BYTES_MAX,
    "out must be at most 'crypto_pwhash_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_SALTBYTES,
    "salt must be 'crypto_pwhash_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )
  assert(alg >= 1 && alg <= 2, 'alg must be either Argon2i 1.3 or Argon2id 1.3')

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    opslimit,
    memlimit,
    alg,

    done
  )

  return promise
}

exports.crypto_pwhash_str = function (out, passwd, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_STRBYTES,
    "out must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(typeof opslimit === 'number', 'opslimit must be a number')
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(typeof memlimit === 'number', 'memlimit must be a number')
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_str(out, passwd, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_str_async = function (out, passwd, opslimit, memlimit, callback = undefined) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_STRBYTES,
    "out must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(typeof opslimit === 'number', 'opslimit must be a number')
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(typeof memlimit === 'number', 'memlimit must be a number')
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_str_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_str_verify = function (str, passwd) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )

  return binding.crypto_pwhash_str_verify(str, passwd)
}

exports.crypto_pwhash_str_verify_async = function (str, passwd, callback = undefined) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  const [done, promise] = checkStatus(callback, true)

  binding.crypto_pwhash_str_verify_async(
    str.buffer,
    str.byteOffset,
    str.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    done
  )

  return promise
}

exports.crypto_pwhash_str_needs_rehash = function (str, opslimit, memlimit) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  return binding.crypto_pwhash_str_needs_rehash(str, opslimit, memlimit)
}

exports.crypto_pwhash_scryptsalsa208sha256 = function (out, passwd, salt, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MIN,
    "out must be at least 'crypto_pwhash_scryptsalsa208sha256_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MAX,
    "out must be at most 'crypto_pwhash_scryptsalsa208sha256_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_SALTBYTES,
    "salt must be 'crypto_pwhash_scryptsalsa208sha256_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_scryptsalsa208sha256(out, passwd, salt, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_scryptsalsa208sha256_async = function (
  out,
  passwd,
  salt,
  opslimit,
  memlimit,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MIN,
    "out must be at least 'crypto_pwhash_scryptsalsa208sha256_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MAX,
    "out must be at most 'crypto_pwhash_scryptsalsa208sha256_BYTES_MAX' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    salt.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_SALTBYTES,
    "salt must be 'crypto_pwhash_scryptsalsa208sha256_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_scryptsalsa208sha256_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str_async = function (
  out,
  passwd,
  opslimit,
  memlimit,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "out must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_scryptsalsa208sha256_str_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str = function (out, passwd, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "out must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_scryptsalsa208sha256_str(out, passwd, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_scryptsalsa208sha256_str_verify_async = function (
  str,
  passwd,
  callback = undefined
) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  const [done, promise] = checkStatus(callback, true)

  binding.crypto_pwhash_scryptsalsa208sha256_str_verify_async(
    str.buffer,
    str.byteOffset,
    str.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str_verify = function (str, passwd) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  return binding.crypto_pwhash_scryptsalsa208sha256_str_verify(str, passwd)
}

exports.crypto_pwhash_scryptsalsa208sha256_str_needs_rehash = function (str, opslimit, memlimit) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  return binding.crypto_pwhash_scryptsalsa208sha256_str_needs_rehash(str, opslimit, memlimit)
}

// crypto_kx

exports.crypto_kx_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "pk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "sk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    pk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "pk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "sk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    seed.byteLength === binding.crypto_kx_SEEDBYTES,
    "seed must be 'crypto_kx_SEEDBYTES' bytes"
  )

  const res = binding.crypto_kx_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_client_session_keys = function (rx, tx, clientPk, clientSk, serverPk) {
  if (!rx) rx = undefined
  if (!tx) tx = undefined

  assert(rx || tx, 'at least one session key must be specified')

  if (rx) {
    assert(ArrayBuffer.isView(rx), 'rx must be a typed array')
    assert(
      rx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "rx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  if (tx) {
    assert(ArrayBuffer.isView(tx), 'tx must be a typed array')
    assert(
      tx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "tx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  assert(ArrayBuffer.isView(clientPk), 'clientPk must be a typed array')
  assert(ArrayBuffer.isView(clientSk), 'clientSk must be a typed array')
  assert(ArrayBuffer.isView(serverPk), 'serverPk must be a typed array')
  assert(
    clientPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "clientPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    clientSk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "clientSk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    serverPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "serverPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_client_session_keys(rx, tx, clientPk, clientSk, serverPk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_server_session_keys = function (rx, tx, serverPk, serverSk, clientPk) {
  if (!rx) rx = undefined
  if (!tx) tx = undefined

  assert(rx || tx, 'at least one session key must be specified')

  if (rx) {
    assert(ArrayBuffer.isView(rx), 'rx must be a typed array')
    assert(
      rx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "rx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  if (tx) {
    assert(ArrayBuffer.isView(tx), 'tx must be a typed array')
    assert(
      tx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "tx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  assert(ArrayBuffer.isView(serverPk), 'serverPk must be a typed array')
  assert(ArrayBuffer.isView(serverSk), 'serverSk must be a typed array')
  assert(ArrayBuffer.isView(clientPk), 'clientPk must be a typed array')
  assert(
    serverPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "serverPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    serverSk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "serverSk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    clientPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "clientPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_server_session_keys(rx, tx, serverPk, serverSk, clientPk)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_scalarmult

exports.crypto_scalarmult_base = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_BYTES,
    "q must be 'crypto_scalarmult_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_SCALARBYTES,
    "n must be 'crypto_scalarmult_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_base(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_BYTES,
    "q must be 'crypto_scalarmult_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_SCALARBYTES,
    "n must be 'crypto_scalarmult_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_BYTES,
    "p must be 'crypto_scalarmult_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_base = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_base(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519 = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "p must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_is_valid_point = function (p) {
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )

  return binding.crypto_core_ed25519_is_valid_point(p)
}

exports.crypto_core_ed25519_from_uniform = function (p, r) {
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_UNIFORMBYTES,
    "r must be 'crypto_core_ed25519_UNIFORMBYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_from_uniform(p, r)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_base_noclamp = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_base_noclamp(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_noclamp = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "p must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_noclamp(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_core

exports.crypto_core_ed25519_add = function (r, p, q) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_BYTES,
    "r must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_core_ed25519_BYTES,
    "q must be 'crypto_core_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_add(r, p, q)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_sub = function (r, p, q) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_BYTES,
    "r must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_core_ed25519_BYTES,
    "q must be 'crypto_core_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_sub(r, p, q)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_scalar_random = function (r) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "r must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_random(r)
}

exports.crypto_core_ed25519_scalar_reduce = function (r, s) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "r must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_NONREDUCEDSCALARBYTES,
    "s must be 'crypto_core_ed25519_NONREDUCEDSCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_reduce(r, s)
}

exports.crypto_core_ed25519_scalar_invert = function (recip, s) {
  assert(ArrayBuffer.isView(recip), 'recip must be a typed array')
  assert(
    recip.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "recip must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_invert(recip, s)
}

exports.crypto_core_ed25519_scalar_negate = function (neg, s) {
  assert(ArrayBuffer.isView(neg), 'neg must be a typed array')
  assert(
    neg.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "neg must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_negate(neg, s)
}

exports.crypto_core_ed25519_scalar_complement = function (comp, s) {
  assert(ArrayBuffer.isView(comp), 'comp must be a typed array')
  assert(
    comp.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "comp must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_complement(comp, s)
}

exports.crypto_core_ed25519_scalar_add = function (z, x, y) {
  assert(ArrayBuffer.isView(z), 'z must be a typed array')
  assert(
    z.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "z must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(x), 'x must be a typed array')
  assert(
    x.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "x must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(y), 'y must be a typed array')
  assert(
    y.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "y must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_add(z, x, y)
}

exports.crypto_core_ed25519_scalar_sub = function (z, x, y) {
  assert(ArrayBuffer.isView(z), 'z must be a typed array')
  assert(
    z.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "z must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(x), 'x must be a typed array')
  assert(
    x.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "x must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(y), 'y must be a typed array')
  assert(
    y.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "y must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_sub(z, x, y)
}

// crypto_shorthash

exports.crypto_shorthash = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_shorthash_BYTES,
    "out must be 'crypto_shorthash_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_shorthash_KEYBYTES,
    "k must be 'crypto_shorthash_KEYBYTES' bytes"
  )

  const res = binding.crypto_shorthash(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_kdf

exports.crypto_kdf_keygen = function (key) {
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(key.byteLength === binding.crypto_kdf_KEYBYTES, "key must be 'crypto_kdf_KEYBYTES' bytes")

  binding.crypto_kdf_keygen(key)
}

exports.crypto_kdf_derive_from_key = function (subkey, subkeyId, ctx, key) {
  assert(ArrayBuffer.isView(subkey), 'subkey must be a typed array')
  assert(
    subkey.byteLength >= binding.crypto_kdf_BYTES_MIN,
    "subkey must be at least 'crypto_kdf_BYTES_MIN' bytes"
  )
  assert(
    subkey.byteLength <= binding.crypto_kdf_BYTES_MAX,
    "subkey must be at most 'crypto_kdf_BYTES_MAX' bytes"
  )
  assert(ArrayBuffer.isView(ctx), 'ctx must be a typed array')
  assert(
    ctx.byteLength === binding.crypto_kdf_CONTEXTBYTES,
    "ctx must be 'crypto_kdf_CONTEXTBYTES' bytes"
  )
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(key.byteLength === binding.crypto_kdf_KEYBYTES, "key must be 'crypto_kdf_KEYBYTES' bytes")

  const res = binding.crypto_kdf_derive_from_key(subkey, subkeyId, ctx, key)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_hash

exports.crypto_hash = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(out.byteLength === binding.crypto_hash_BYTES, "out must be 'crypto_hash_BYTES' bytes")

  const res = binding.crypto_hash(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256 = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha256_BYTES,
    "out must be 'crypto_hash_sha256_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha256(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_init = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_init(state)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha256_BYTES,
    "out must be 'crypto_hash_sha256_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512 = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha512_BYTES,
    "out must be 'crypto_hash_sha512_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha512(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_init = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_init(state)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha512_BYTES,
    "out must be 'crypto_hash_sha512_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_aead

exports.crypto_aead_xchacha20poly1305_ietf_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  binding.crypto_aead_xchacha20poly1305_ietf_keygen(k)
}

exports.crypto_aead_xchacha20poly1305_ietf_encrypt = function (c, m, ad, nsec, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "c must be 'm.byteLength + crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(c.byteLength <= 0xffffffff, 'c.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_encrypt(c, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_decrypt = function (m, nsec, c, ad, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "m must be 'c.byteLength - crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(m.byteLength <= 0xffffffff, 'm.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_decrypt(m, c, ad, npub, k)

  if (res < 0) throw new Error('could not verify data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_encrypt_detached = function (
  c,
  mac,
  m,
  ad,
  nsec,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_encrypt_detached(c, mac, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_decrypt_detached = function (
  m,
  nsec,
  c,
  mac,
  ad,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_decrypt_detached(m, c, mac, ad, npub, k)

  if (res !== 0) throw new Error('could not verify data')
}

exports.crypto_aead_chacha20poly1305_ietf_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  binding.crypto_aead_chacha20poly1305_ietf_keygen(k)
}

exports.crypto_aead_chacha20poly1305_ietf_encrypt = function (c, m, ad, nsec, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "c must be 'm.byteLength + crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(c.byteLength <= 0xffffffff, 'c.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_encrypt(c, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_decrypt = function (m, nsec, c, ad, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "m must be 'c.byteLength - crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(m.byteLength <= 0xffffffff, 'm.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_decrypt(m, c, ad, npub, k)

  if (res < 0) throw new Error('could not verify data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_encrypt_detached = function (
  c,
  mac,
  m,
  ad,
  nsec,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_encrypt_detached(c, mac, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_decrypt_detached = function (
  m,
  nsec,
  c,
  mac,
  ad,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_decrypt_detached(m, c, mac, ad, npub, k)

  if (res !== 0) throw new Error('could not verify data')
}

// crypto_stream

exports.crypto_stream_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  binding.crypto_stream_xor_wrap_init(state, n, k)
}

exports.crypto_stream_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_xor_wrap_update(state, c, m)
}

exports.crypto_stream_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_xor_wrap_final(state)
}

exports.crypto_stream_chacha20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  binding.crypto_stream_chacha20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_chacha20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_chacha20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_chacha20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_chacha20_xor_wrap_final(state)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  binding.crypto_stream_chacha20_ietf_xor_wrap_init(state, n, k)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_chacha20_ietf_xor_wrap_update(state, c, m)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_chacha20_ietf_xor_wrap_final(state)
}

exports.crypto_stream_xchacha20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  binding.crypto_stream_xchacha20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_xchacha20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_xchacha20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_xchacha20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_xchacha20_xor_wrap_final(state)
}

exports.crypto_stream_salsa20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  binding.crypto_stream_salsa20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_salsa20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_salsa20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_salsa20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_salsa20_xor_wrap_final(state)
}

// experimental

exports.extension_tweak_ed25519_base = function (n, p, ns) {
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.extension_tweak_ed25519_BYTES,
    "p must be 'extension_tweak_ed25519_BYTES' bytes"
  )

  binding.extension_tweak_ed25519_base(n, p, ns)
}

exports.extension_tweak_ed25519_sign_detached = function (sig, m, scalar, pk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(sig.byteLength === binding.crypto_sign_BYTES, "sig must be 'crypto_sign_BYTES' bytes")
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  if (pk) {
    assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
    assert(
      pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
      "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
    )
  }

  const res = binding.extension_tweak_ed25519_sign_detached(sig, m, scalar, pk)

  if (res !== 0) throw new Error('failed to compute signature')
}

exports.extension_tweak_ed25519_sk_to_scalar = function (n, sk) {
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  binding.extension_tweak_ed25519_sk_to_scalar(n, sk)
}

exports.extension_tweak_ed25519_scalar = function (scalarOut, scalar, ns) {
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_scalar(scalarOut, scalar, ns)
}

exports.extension_tweak_ed25519_pk = function (tpk, pk, ns) {
  assert(ArrayBuffer.isView(tpk), 'tpk must be a typed array')
  assert(
    tpk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "tpk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_pk(tpk, pk, ns)

  if (res !== 0) throw new Error('failed to tweak public key')
}

exports.extension_tweak_ed25519_keypair = function (pk, scalarOut, scalarIn, ns) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.extension_tweak_ed25519_BYTES,
    "pk must be 'extension_tweak_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarIn), 'scalarIn must be a typed array')
  assert(
    scalarIn.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarIn must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_keypair(pk, scalarOut, scalarIn, ns)
}

exports.extension_tweak_ed25519_scalar_add = function (scalarOut, scalar, n) {
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_scalar_add(scalarOut, scalar, n)
}

exports.extension_tweak_ed25519_pk_add = function (tpk, pk, p) {
  assert(ArrayBuffer.isView(tpk), 'tpk must be a typed array')
  assert(
    tpk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "tpk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "p must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_pk_add(tpk, pk, p)

  if (res !== 0) throw new Error('failed to add tweak to public key')
}

exports.extension_tweak_ed25519_keypair_add = function (pk, scalarOut, scalarIn, tweak) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.extension_tweak_ed25519_BYTES,
    "pk must be 'extension_tweak_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarIn), 'scalarIn must be a typed array')
  assert(
    scalarIn.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarIn must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(tweak), 'tweak must be a typed array')
  assert(
    tweak.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "tweak must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_keypair_add(pk, scalarOut, scalarIn, tweak)

  if (res !== 0) throw new Error('failed to add tweak to keypair')
}

exports.extension_pbkdf2_sha512_async = function (out, passwd, salt, iter, outlen, callback) {
  assert(
    iter >= binding.extension_pbkdf2_sha512_ITERATIONS_MIN,
    "iter must be at least 'extension_pbkdf2_sha512_ITERATIONS_MIN'"
  )
  assert(
    outlen <= binding.extension_pbkdf2_sha512_BYTES_MAX,
    "outlen must be at most 'extension_pbkdf2_sha512_BYTES_MAX'"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(out.byteLength >= outlen, "out must be at least 'outlen' bytes")
  assert(out.byteLength > 0, 'out must not be empty')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(salt.byteLength > 0, 'salt must not be empty')

  const [done, promise] = checkStatus(callback)

  binding.extension_pbkdf2_sha512_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    iter,
    outlen,

    done
  )

  return promise
}

exports.extension_pbkdf2_sha512 = function (out, passwd, salt, iter, outlen) {
  assert(
    iter >= binding.extension_pbkdf2_sha512_ITERATIONS_MIN,
    "iter must be at least 'extension_pbkdf2_sha512_ITERATIONS_MIN'"
  )
  assert(
    outlen <= binding.extension_pbkdf2_sha512_BYTES_MAX,
    "outlen must be at most 'extension_pbkdf2_sha512_BYTES_MAX'"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(out.byteLength >= outlen, "out must be at least 'outlen' bytes")
  assert(out.byteLength > 0, 'out must not be empty')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(salt.byteLength > 0, 'salt must not be empty')

  const res = binding.extension_pbkdf2_sha512(out, passwd, salt, iter, outlen)

  if (res !== 0) throw new Error('failed to add tweak to public key')
}

function checkStatus(callback, booleanResult = false) {
  let done, promise

  if (typeof callback === 'function') {
    done = function (status) {
      if (booleanResult) callback(null, status === 0)
      else if (status === 0) callback(null)
      else callback(new Error('status: ' + status))
    }
  } else {
    promise = new Promise(function (resolve, reject) {
      done = function (status) {
        if (booleanResult) resolve(status === 0)
        else if (status === 0) resolve()
        else reject(new Error('status: ' + status))
      }
    })
  }

  return [done, promise]
}
{
  "name": "sodium-native",
  "version": "5.1.0",
  "description": "Low level bindings for libsodium",
  "main": "index.js",
  "files": [
    "index.js",
    "binding.cc",
    "binding.js",
    "extensions",
    "prebuilds",
    "CMakeLists.txt"
  ],
  "imports": {
    "assert": {
      "bare": "bare-assert",
      "node": "assert"
    }
  },
  "addon": true,
  "dependencies": {
    "bare-assert": "^1.2.0",
    "require-addon": "^1.1.0",
    "which-runtime": "^1.2.1"
  },
  "devDependencies": {
    "bare-compat-napi": "^1.3.5",
    "brittle": "^3.16.2",
    "cmake-bare": "^1.6.1",
    "cmake-fetch": "^1.4.3",
    "cmake-napi": "^1.2.1",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "test": "prettier . --check && npm run test:node && npm run test:bare",
    "test:node": "node test/all.js",
    "test:bare": "bare test/all.js"
  },
  "standard": {
    "ignore": [
      "/test/fixtures/*.js"
    ]
  },
  "engines": {
    "bare": ">=1.16.0"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sodium-native.git"
  },
  "contributors": [
    "Emil Bay <github@tixz.dk> (http://bayes.dk)",
    "Mathias Buus <mathiasbuus@gmail.com> (https://mafinto.sh)",
    "Christophe Diederichs <chm-diederichs@hyperdivision.dk>"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/sodium-native/issues"
  },
  "homepage": "https://github.com/holepunchto/sodium-native"
}
const sodium = require('sodium-universal')
const b4a = require('b4a')

const ABYTES = sodium.crypto_secretstream_xchacha20poly1305_ABYTES
const TAG_MESSAGE = sodium.crypto_secretstream_xchacha20poly1305_TAG_MESSAGE
const TAG_FINAL = sodium.crypto_secretstream_xchacha20poly1305_TAG_FINAL
const STATEBYTES = sodium.crypto_secretstream_xchacha20poly1305_STATEBYTES
const HEADERBYTES = sodium.crypto_secretstream_xchacha20poly1305_HEADERBYTES
const KEYBYTES = sodium.crypto_secretstream_xchacha20poly1305_KEYBYTES
const TAG_FINAL_BYTE = b4a.isBuffer(TAG_FINAL) ? TAG_FINAL[0] : TAG_FINAL

const EMPTY = b4a.alloc(0)
const TAG = b4a.alloc(1)

class Push {
  constructor (key, state = b4a.allocUnsafeSlow(STATEBYTES), header = b4a.allocUnsafeSlow(HEADERBYTES)) {
    if (!TAG_FINAL) throw new Error('JavaScript sodium version needs to support crypto_secretstream_xchacha20poly')

    this.key = key
    this.state = state
    this.header = header

    sodium.crypto_secretstream_xchacha20poly1305_init_push(this.state, this.header, this.key)
  }

  next (message, cipher = b4a.allocUnsafe(message.byteLength + ABYTES)) {
    sodium.crypto_secretstream_xchacha20poly1305_push(this.state, cipher, message, null, TAG_MESSAGE)
    return cipher
  }

  final (message = EMPTY, cipher = b4a.allocUnsafe(ABYTES)) {
    sodium.crypto_secretstream_xchacha20poly1305_push(this.state, cipher, message, null, TAG_FINAL)
    return cipher
  }
}

class Pull {
  constructor (key, state = b4a.allocUnsafeSlow(STATEBYTES)) {
    if (!TAG_FINAL) throw new Error('JavaScript sodium version needs to support crypto_secretstream_xchacha20poly')

    this.key = key
    this.state = state
    this.final = false
  }

  init (header) {
    sodium.crypto_secretstream_xchacha20poly1305_init_pull(this.state, header, this.key)
  }

  next (cipher, message = b4a.allocUnsafe(cipher.byteLength - ABYTES)) {
    sodium.crypto_secretstream_xchacha20poly1305_pull(this.state, message, TAG, cipher, null)
    this.final = TAG[0] === TAG_FINAL_BYTE
    return message
  }
}

function keygen (buf = b4a.alloc(KEYBYTES)) {
  sodium.crypto_secretstream_xchacha20poly1305_keygen(buf)
  return buf
}

module.exports = {
  keygen,
  KEYBYTES,
  ABYTES,
  STATEBYTES,
  HEADERBYTES,
  Push,
  Pull
}
{
  "name": "sodium-secretstream",
  "version": "1.2.0",
  "description": "Wraps libsodiums secretstream in a higher level abstraction",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.1.1",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "standard": "^17.0.0"
  },
  "scripts": {
    "test": "standard"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/sodium-secretstream.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/sodium-secretstream/issues"
  },
  "homepage": "https://github.com/mafintosh/sodium-secretstream"
}
module.exports = require('sodium-native')
{
  "name": "sodium-universal",
  "version": "5.0.1",
  "description": "Universal wrapper for sodium-javascript and sodium-native working in Node.js and the Browser",
  "main": "index.js",
  "dependencies": {
    "sodium-native": "^5.0.1"
  },
  "peerDependencies": {
    "sodium-javascript": "~0.8.0"
  },
  "peerDependenciesMeta": {
    "sodium-javascript": {
      "optional": true
    }
  },
  "scripts": {
    "prepublish": "./build-scripts/generate.js"
  },
  "browser": {
    "sodium-native": "sodium-javascript"
  },
  "browserify": {
    "transform": [
      "./build-scripts/transform.js"
    ]
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sodium-universal.git"
  },
  "keywords": [
    "libsodium",
    "sodium",
    "sodium-native",
    "sodium-javascript",
    "browserify"
  ],
  "contributors": [
    "Emil Bay <github@tixz.dk> (http://bayes.dk)",
    "Mathias Buus <mathiasbuus@gmail.com> (https://mafinto.sh)",
    "Christophe Diederichs <chm-diederichs@hyperdivision.dk>"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/sodium-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/sodium-universal#readme"
}
const { EventEmitter } = require('events-universal')
const STREAM_DESTROYED = new Error('Stream was destroyed')
const PREMATURE_CLOSE = new Error('Premature close')

const FIFO = require('fast-fifo')
const TextDecoder = require('text-decoder')

// if we do a future major, expect queue microtask to be there always, for now a bit defensive
const qmt =
  typeof queueMicrotask === 'undefined' ? (fn) => global.process.nextTick(fn) : queueMicrotask

// 29 bits used total (4 from shared, 14 from read, and 11 from write)
const MAX = (1 << 29) - 1

// Shared state
const OPENING = 0b0001
const PREDESTROYING = 0b0010
const DESTROYING = 0b0100
const DESTROYED = 0b1000

const NOT_OPENING = MAX ^ OPENING
const NOT_PREDESTROYING = MAX ^ PREDESTROYING

// Read state (4 bit offset from shared state)
const READ_ACTIVE = 0b00000000000001 << 4
const READ_UPDATING = 0b00000000000010 << 4
const READ_PRIMARY = 0b00000000000100 << 4
const READ_QUEUED = 0b00000000001000 << 4
const READ_RESUMED = 0b00000000010000 << 4
const READ_PIPE_DRAINED = 0b00000000100000 << 4
const READ_ENDING = 0b00000001000000 << 4
const READ_EMIT_DATA = 0b00000010000000 << 4
const READ_EMIT_READABLE = 0b00000100000000 << 4
const READ_EMITTED_READABLE = 0b00001000000000 << 4
const READ_DONE = 0b00010000000000 << 4
const READ_NEXT_TICK = 0b00100000000000 << 4
const READ_NEEDS_PUSH = 0b01000000000000 << 4
const READ_READ_AHEAD = 0b10000000000000 << 4

// Combined read state
const READ_FLOWING = READ_RESUMED | READ_PIPE_DRAINED
const READ_ACTIVE_AND_NEEDS_PUSH = READ_ACTIVE | READ_NEEDS_PUSH
const READ_PRIMARY_AND_ACTIVE = READ_PRIMARY | READ_ACTIVE
const READ_EMIT_READABLE_AND_QUEUED = READ_EMIT_READABLE | READ_QUEUED
const READ_RESUMED_READ_AHEAD = READ_RESUMED | READ_READ_AHEAD

const READ_NOT_ACTIVE = MAX ^ READ_ACTIVE
const READ_NON_PRIMARY = MAX ^ READ_PRIMARY
const READ_NON_PRIMARY_AND_PUSHED = MAX ^ (READ_PRIMARY | READ_NEEDS_PUSH)
const READ_PUSHED = MAX ^ READ_NEEDS_PUSH
const READ_PAUSED = MAX ^ READ_RESUMED
const READ_NOT_QUEUED = MAX ^ (READ_QUEUED | READ_EMITTED_READABLE)
const READ_NOT_ENDING = MAX ^ READ_ENDING
const READ_PIPE_NOT_DRAINED = MAX ^ READ_FLOWING
const READ_NOT_NEXT_TICK = MAX ^ READ_NEXT_TICK
const READ_NOT_UPDATING = MAX ^ READ_UPDATING
const READ_NO_READ_AHEAD = MAX ^ READ_READ_AHEAD
const READ_PAUSED_NO_READ_AHEAD = MAX ^ READ_RESUMED_READ_AHEAD

// Write state (18 bit offset, 4 bit offset from shared state and 14 from read state)
const WRITE_ACTIVE = 0b00000000001 << 18
const WRITE_UPDATING = 0b00000000010 << 18
const WRITE_PRIMARY = 0b00000000100 << 18
const WRITE_QUEUED = 0b00000001000 << 18
const WRITE_UNDRAINED = 0b00000010000 << 18
const WRITE_DONE = 0b00000100000 << 18
const WRITE_EMIT_DRAIN = 0b00001000000 << 18
const WRITE_NEXT_TICK = 0b00010000000 << 18
const WRITE_WRITING = 0b00100000000 << 18
const WRITE_FINISHING = 0b01000000000 << 18
const WRITE_CORKED = 0b10000000000 << 18

const WRITE_NOT_ACTIVE = MAX ^ (WRITE_ACTIVE | WRITE_WRITING)
const WRITE_NON_PRIMARY = MAX ^ WRITE_PRIMARY
const WRITE_NOT_FINISHING = MAX ^ (WRITE_ACTIVE | WRITE_FINISHING)
const WRITE_DRAINED = MAX ^ WRITE_UNDRAINED
const WRITE_NOT_QUEUED = MAX ^ WRITE_QUEUED
const WRITE_NOT_NEXT_TICK = MAX ^ WRITE_NEXT_TICK
const WRITE_NOT_UPDATING = MAX ^ WRITE_UPDATING
const WRITE_NOT_CORKED = MAX ^ WRITE_CORKED

// Combined shared state
const ACTIVE = READ_ACTIVE | WRITE_ACTIVE
const NOT_ACTIVE = MAX ^ ACTIVE
const DONE = READ_DONE | WRITE_DONE
const DESTROY_STATUS = DESTROYING | DESTROYED | PREDESTROYING
const OPEN_STATUS = DESTROY_STATUS | OPENING
const AUTO_DESTROY = DESTROY_STATUS | DONE
const NON_PRIMARY = WRITE_NON_PRIMARY & READ_NON_PRIMARY
const ACTIVE_OR_TICKING = WRITE_NEXT_TICK | READ_NEXT_TICK
const TICKING = ACTIVE_OR_TICKING & NOT_ACTIVE
const IS_OPENING = OPEN_STATUS | TICKING

// Combined shared state and read state
const READ_PRIMARY_STATUS = OPEN_STATUS | READ_ENDING | READ_DONE
const READ_STATUS = OPEN_STATUS | READ_DONE | READ_QUEUED
const READ_ENDING_STATUS = OPEN_STATUS | READ_ENDING | READ_QUEUED
const READ_READABLE_STATUS = OPEN_STATUS | READ_EMIT_READABLE | READ_QUEUED | READ_EMITTED_READABLE
const SHOULD_NOT_READ =
  OPEN_STATUS | READ_ACTIVE | READ_ENDING | READ_DONE | READ_NEEDS_PUSH | READ_READ_AHEAD
const READ_BACKPRESSURE_STATUS = DESTROY_STATUS | READ_ENDING | READ_DONE
const READ_UPDATE_SYNC_STATUS = READ_UPDATING | OPEN_STATUS | READ_NEXT_TICK | READ_PRIMARY
const READ_NEXT_TICK_OR_OPENING = READ_NEXT_TICK | OPENING

// Combined write state
const WRITE_PRIMARY_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_DONE
const WRITE_QUEUED_AND_UNDRAINED = WRITE_QUEUED | WRITE_UNDRAINED
const WRITE_QUEUED_AND_ACTIVE = WRITE_QUEUED | WRITE_ACTIVE
const WRITE_DRAIN_STATUS = WRITE_QUEUED | WRITE_UNDRAINED | OPEN_STATUS | WRITE_ACTIVE
const WRITE_STATUS = OPEN_STATUS | WRITE_ACTIVE | WRITE_QUEUED | WRITE_CORKED
const WRITE_PRIMARY_AND_ACTIVE = WRITE_PRIMARY | WRITE_ACTIVE
const WRITE_ACTIVE_AND_WRITING = WRITE_ACTIVE | WRITE_WRITING
const WRITE_FINISHING_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_QUEUED_AND_ACTIVE | WRITE_DONE
const WRITE_BACKPRESSURE_STATUS = WRITE_UNDRAINED | DESTROY_STATUS | WRITE_FINISHING | WRITE_DONE
const WRITE_UPDATE_SYNC_STATUS = WRITE_UPDATING | OPEN_STATUS | WRITE_NEXT_TICK | WRITE_PRIMARY
const WRITE_DROP_DATA = WRITE_FINISHING | WRITE_DONE | DESTROY_STATUS

const asyncIterator = Symbol.asyncIterator || Symbol('asyncIterator')

class WritableState {
  constructor(
    stream,
    { highWaterMark = 16384, map = null, mapWritable, byteLength, byteLengthWritable } = {}
  ) {
    this.stream = stream
    this.queue = new FIFO()
    this.highWaterMark = highWaterMark
    this.buffered = 0
    this.error = null
    this.pipeline = null
    this.drains = null // if we add more seldomly used helpers we might them into a subobject so its a single ptr
    this.byteLength = byteLengthWritable || byteLength || defaultByteLength
    this.map = mapWritable || map
    this.afterWrite = afterWrite.bind(this)
    this.afterUpdateNextTick = updateWriteNT.bind(this)
  }

  get ending() {
    return (this.stream._duplexState & WRITE_FINISHING) !== 0
  }

  get ended() {
    return (this.stream._duplexState & WRITE_DONE) !== 0
  }

  push(data) {
    if ((this.stream._duplexState & WRITE_DROP_DATA) !== 0) return false
    if (this.map !== null) data = this.map(data)

    this.buffered += this.byteLength(data)
    this.queue.push(data)

    if (this.buffered < this.highWaterMark) {
      this.stream._duplexState |= WRITE_QUEUED
      return true
    }

    this.stream._duplexState |= WRITE_QUEUED_AND_UNDRAINED
    return false
  }

  shift() {
    const data = this.queue.shift()

    this.buffered -= this.byteLength(data)
    if (this.buffered === 0) this.stream._duplexState &= WRITE_NOT_QUEUED

    return data
  }

  end(data) {
    if (typeof data === 'function') this.stream.once('finish', data)
    else if (data !== undefined && data !== null) this.push(data)
    this.stream._duplexState = (this.stream._duplexState | WRITE_FINISHING) & WRITE_NON_PRIMARY
  }

  autoBatch(data, cb) {
    const buffer = []
    const stream = this.stream

    buffer.push(data)
    while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED_AND_ACTIVE) {
      buffer.push(stream._writableState.shift())
    }

    if ((stream._duplexState & OPEN_STATUS) !== 0) return cb(null)
    stream._writev(buffer, cb)
  }

  update() {
    const stream = this.stream

    stream._duplexState |= WRITE_UPDATING

    do {
      while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED) {
        const data = this.shift()
        stream._duplexState |= WRITE_ACTIVE_AND_WRITING
        stream._write(data, this.afterWrite)
      }

      if ((stream._duplexState & WRITE_PRIMARY_AND_ACTIVE) === 0) this.updateNonPrimary()
    } while (this.continueUpdate() === true)

    stream._duplexState &= WRITE_NOT_UPDATING
  }

  updateNonPrimary() {
    const stream = this.stream

    if ((stream._duplexState & WRITE_FINISHING_STATUS) === WRITE_FINISHING) {
      stream._duplexState = stream._duplexState | WRITE_ACTIVE
      stream._final(afterFinal.bind(this))
      return
    }

    if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
      if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
        stream._duplexState |= ACTIVE
        stream._destroy(afterDestroy.bind(this))
      }
      return
    }

    if ((stream._duplexState & IS_OPENING) === OPENING) {
      stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING
      stream._open(afterOpen.bind(this))
    }
  }

  continueUpdate() {
    if ((this.stream._duplexState & WRITE_NEXT_TICK) === 0) return false
    this.stream._duplexState &= WRITE_NOT_NEXT_TICK
    return true
  }

  updateCallback() {
    if ((this.stream._duplexState & WRITE_UPDATE_SYNC_STATUS) === WRITE_PRIMARY) this.update()
    else this.updateNextTick()
  }

  updateNextTick() {
    if ((this.stream._duplexState & WRITE_NEXT_TICK) !== 0) return
    this.stream._duplexState |= WRITE_NEXT_TICK
    if ((this.stream._duplexState & WRITE_UPDATING) === 0) qmt(this.afterUpdateNextTick)
  }
}

class ReadableState {
  constructor(
    stream,
    { highWaterMark = 16384, map = null, mapReadable, byteLength, byteLengthReadable } = {}
  ) {
    this.stream = stream
    this.queue = new FIFO()
    this.highWaterMark = highWaterMark === 0 ? 1 : highWaterMark
    this.buffered = 0
    this.readAhead = highWaterMark > 0
    this.error = null
    this.pipeline = null
    this.byteLength = byteLengthReadable || byteLength || defaultByteLength
    this.map = mapReadable || map
    this.pipeTo = null
    this.afterRead = afterRead.bind(this)
    this.afterUpdateNextTick = updateReadNT.bind(this)
  }

  get ending() {
    return (this.stream._duplexState & READ_ENDING) !== 0
  }

  get ended() {
    return (this.stream._duplexState & READ_DONE) !== 0
  }

  pipe(pipeTo, cb) {
    if (this.pipeTo !== null) throw new Error('Can only pipe to one destination')
    if (typeof cb !== 'function') cb = null

    this.stream._duplexState |= READ_PIPE_DRAINED
    this.pipeTo = pipeTo
    this.pipeline = new Pipeline(this.stream, pipeTo, cb)

    if (cb) this.stream.on('error', noop) // We already error handle this so supress crashes

    if (isStreamx(pipeTo)) {
      pipeTo._writableState.pipeline = this.pipeline
      if (cb) pipeTo.on('error', noop) // We already error handle this so supress crashes
      pipeTo.on('finish', this.pipeline.finished.bind(this.pipeline)) // TODO: just call finished from pipeTo itself
    } else {
      const onerror = this.pipeline.done.bind(this.pipeline, pipeTo)
      const onclose = this.pipeline.done.bind(this.pipeline, pipeTo, null) // onclose has a weird bool arg
      pipeTo.on('error', onerror)
      pipeTo.on('close', onclose)
      pipeTo.on('finish', this.pipeline.finished.bind(this.pipeline))
    }

    pipeTo.on('drain', afterDrain.bind(this))
    this.stream.emit('piping', pipeTo)
    pipeTo.emit('pipe', this.stream)
  }

  push(data) {
    const stream = this.stream

    if (data === null) {
      this.highWaterMark = 0
      stream._duplexState = (stream._duplexState | READ_ENDING) & READ_NON_PRIMARY_AND_PUSHED
      return false
    }

    if (this.map !== null) {
      data = this.map(data)
      if (data === null) {
        stream._duplexState &= READ_PUSHED
        return this.buffered < this.highWaterMark
      }
    }

    this.buffered += this.byteLength(data)
    this.queue.push(data)

    stream._duplexState = (stream._duplexState | READ_QUEUED) & READ_PUSHED

    return this.buffered < this.highWaterMark
  }

  shift() {
    const data = this.queue.shift()

    this.buffered -= this.byteLength(data)
    if (this.buffered === 0) this.stream._duplexState &= READ_NOT_QUEUED
    return data
  }

  unshift(data) {
    const pending = [this.map !== null ? this.map(data) : data]
    while (this.buffered > 0) pending.push(this.shift())

    for (let i = 0; i < pending.length - 1; i++) {
      const data = pending[i]
      this.buffered += this.byteLength(data)
      this.queue.push(data)
    }

    this.push(pending[pending.length - 1])
  }

  read() {
    const stream = this.stream

    if ((stream._duplexState & READ_STATUS) === READ_QUEUED) {
      const data = this.shift()
      if (this.pipeTo !== null && this.pipeTo.write(data) === false)
        stream._duplexState &= READ_PIPE_NOT_DRAINED
      if ((stream._duplexState & READ_EMIT_DATA) !== 0) stream.emit('data', data)
      return data
    }

    if (this.readAhead === false) {
      stream._duplexState |= READ_READ_AHEAD
      this.updateNextTick()
    }

    return null
  }

  drain() {
    const stream = this.stream

    while (
      (stream._duplexState & READ_STATUS) === READ_QUEUED &&
      (stream._duplexState & READ_FLOWING) !== 0
    ) {
      const data = this.shift()
      if (this.pipeTo !== null && this.pipeTo.write(data) === false)
        stream._duplexState &= READ_PIPE_NOT_DRAINED
      if ((stream._duplexState & READ_EMIT_DATA) !== 0) stream.emit('data', data)
    }
  }

  update() {
    const stream = this.stream

    stream._duplexState |= READ_UPDATING

    do {
      this.drain()

      while (
        this.buffered < this.highWaterMark &&
        (stream._duplexState & SHOULD_NOT_READ) === READ_READ_AHEAD
      ) {
        stream._duplexState |= READ_ACTIVE_AND_NEEDS_PUSH
        stream._read(this.afterRead)
        this.drain()
      }

      if ((stream._duplexState & READ_READABLE_STATUS) === READ_EMIT_READABLE_AND_QUEUED) {
        stream._duplexState |= READ_EMITTED_READABLE
        stream.emit('readable')
      }

      if ((stream._duplexState & READ_PRIMARY_AND_ACTIVE) === 0) this.updateNonPrimary()
    } while (this.continueUpdate() === true)

    stream._duplexState &= READ_NOT_UPDATING
  }

  updateNonPrimary() {
    const stream = this.stream

    if ((stream._duplexState & READ_ENDING_STATUS) === READ_ENDING) {
      stream._duplexState = (stream._duplexState | READ_DONE) & READ_NOT_ENDING
      stream.emit('end')
      if ((stream._duplexState & AUTO_DESTROY) === DONE) stream._duplexState |= DESTROYING
      if (this.pipeTo !== null) this.pipeTo.end()
    }

    if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
      if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
        stream._duplexState |= ACTIVE
        stream._destroy(afterDestroy.bind(this))
      }
      return
    }

    if ((stream._duplexState & IS_OPENING) === OPENING) {
      stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING
      stream._open(afterOpen.bind(this))
    }
  }

  continueUpdate() {
    if ((this.stream._duplexState & READ_NEXT_TICK) === 0) return false
    this.stream._duplexState &= READ_NOT_NEXT_TICK
    return true
  }

  updateCallback() {
    if ((this.stream._duplexState & READ_UPDATE_SYNC_STATUS) === READ_PRIMARY) this.update()
    else this.updateNextTick()
  }

  updateNextTickIfOpen() {
    if ((this.stream._duplexState & READ_NEXT_TICK_OR_OPENING) !== 0) return
    this.stream._duplexState |= READ_NEXT_TICK
    if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick)
  }

  updateNextTick() {
    if ((this.stream._duplexState & READ_NEXT_TICK) !== 0) return
    this.stream._duplexState |= READ_NEXT_TICK
    if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick)
  }
}

class TransformState {
  constructor(stream) {
    this.data = null
    this.afterTransform = afterTransform.bind(stream)
    this.afterFinal = null
  }
}

class Pipeline {
  constructor(src, dst, cb) {
    this.from = src
    this.to = dst
    this.afterPipe = cb
    this.error = null
    this.pipeToFinished = false
  }

  finished() {
    this.pipeToFinished = true
  }

  done(stream, err) {
    if (err) this.error = err

    if (stream === this.to) {
      this.to = null

      if (this.from !== null) {
        if ((this.from._duplexState & READ_DONE) === 0 || !this.pipeToFinished) {
          this.from.destroy(this.error || new Error('Writable stream closed prematurely'))
        }
        return
      }
    }

    if (stream === this.from) {
      this.from = null

      if (this.to !== null) {
        if ((stream._duplexState & READ_DONE) === 0) {
          this.to.destroy(this.error || new Error('Readable stream closed before ending'))
        }
        return
      }
    }

    if (this.afterPipe !== null) this.afterPipe(this.error)
    this.to = this.from = this.afterPipe = null
  }
}

function afterDrain() {
  this.stream._duplexState |= READ_PIPE_DRAINED
  this.updateCallback()
}

function afterFinal(err) {
  const stream = this.stream
  if (err) stream.destroy(err)
  if ((stream._duplexState & DESTROY_STATUS) === 0) {
    stream._duplexState |= WRITE_DONE
    stream.emit('finish')
  }
  if ((stream._duplexState & AUTO_DESTROY) === DONE) {
    stream._duplexState |= DESTROYING
  }

  stream._duplexState &= WRITE_NOT_FINISHING

  // no need to wait the extra tick here, so we short circuit that
  if ((stream._duplexState & WRITE_UPDATING) === 0) this.update()
  else this.updateNextTick()
}

function afterDestroy(err) {
  const stream = this.stream

  if (!err && this.error !== STREAM_DESTROYED) err = this.error
  if (err) stream.emit('error', err)
  stream._duplexState |= DESTROYED
  stream.emit('close')

  const rs = stream._readableState
  const ws = stream._writableState

  if (rs !== null && rs.pipeline !== null) rs.pipeline.done(stream, err)

  if (ws !== null) {
    while (ws.drains !== null && ws.drains.length > 0) ws.drains.shift().resolve(false)
    if (ws.pipeline !== null) ws.pipeline.done(stream, err)
  }
}

function afterWrite(err) {
  const stream = this.stream

  if (err) stream.destroy(err)
  stream._duplexState &= WRITE_NOT_ACTIVE

  if (this.drains !== null) tickDrains(this.drains)

  if ((stream._duplexState & WRITE_DRAIN_STATUS) === WRITE_UNDRAINED) {
    stream._duplexState &= WRITE_DRAINED
    if ((stream._duplexState & WRITE_EMIT_DRAIN) === WRITE_EMIT_DRAIN) {
      stream.emit('drain')
    }
  }

  this.updateCallback()
}

function afterRead(err) {
  if (err) this.stream.destroy(err)
  this.stream._duplexState &= READ_NOT_ACTIVE
  if (this.readAhead === false && (this.stream._duplexState & READ_RESUMED) === 0)
    this.stream._duplexState &= READ_NO_READ_AHEAD
  this.updateCallback()
}

function updateReadNT() {
  if ((this.stream._duplexState & READ_UPDATING) === 0) {
    this.stream._duplexState &= READ_NOT_NEXT_TICK
    this.update()
  }
}

function updateWriteNT() {
  if ((this.stream._duplexState & WRITE_UPDATING) === 0) {
    this.stream._duplexState &= WRITE_NOT_NEXT_TICK
    this.update()
  }
}

function tickDrains(drains) {
  for (let i = 0; i < drains.length; i++) {
    // drains.writes are monotonic, so if one is 0 its always the first one
    if (--drains[i].writes === 0) {
      drains.shift().resolve(true)
      i--
    }
  }
}

function afterOpen(err) {
  const stream = this.stream

  if (err) stream.destroy(err)

  if ((stream._duplexState & DESTROYING) === 0) {
    if ((stream._duplexState & READ_PRIMARY_STATUS) === 0) stream._duplexState |= READ_PRIMARY
    if ((stream._duplexState & WRITE_PRIMARY_STATUS) === 0) stream._duplexState |= WRITE_PRIMARY
    stream.emit('open')
  }

  stream._duplexState &= NOT_ACTIVE

  if (stream._writableState !== null) {
    stream._writableState.updateCallback()
  }

  if (stream._readableState !== null) {
    stream._readableState.updateCallback()
  }
}

function afterTransform(err, data) {
  if (data !== undefined && data !== null) this.push(data)
  this._writableState.afterWrite(err)
}

function newListener(name) {
  if (this._readableState !== null) {
    if (name === 'data') {
      this._duplexState |= READ_EMIT_DATA | READ_RESUMED_READ_AHEAD
      this._readableState.updateNextTick()
    }
    if (name === 'readable') {
      this._duplexState |= READ_EMIT_READABLE
      this._readableState.updateNextTick()
    }
  }

  if (this._writableState !== null) {
    if (name === 'drain') {
      this._duplexState |= WRITE_EMIT_DRAIN
      this._writableState.updateNextTick()
    }
  }
}

class Stream extends EventEmitter {
  constructor(opts) {
    super()

    this._duplexState = 0
    this._readableState = null
    this._writableState = null

    if (opts) {
      if (opts.open) this._open = opts.open
      if (opts.destroy) this._destroy = opts.destroy
      if (opts.predestroy) this._predestroy = opts.predestroy
      if (opts.signal) {
        opts.signal.addEventListener('abort', abort.bind(this))
      }
    }

    this.on('newListener', newListener)
  }

  _open(cb) {
    cb(null)
  }

  _destroy(cb) {
    cb(null)
  }

  _predestroy() {
    // does nothing
  }

  get readable() {
    return this._readableState !== null ? true : undefined
  }

  get writable() {
    return this._writableState !== null ? true : undefined
  }

  get destroyed() {
    return (this._duplexState & DESTROYED) !== 0
  }

  get destroying() {
    return (this._duplexState & DESTROY_STATUS) !== 0
  }

  destroy(err) {
    if ((this._duplexState & DESTROY_STATUS) === 0) {
      if (!err) err = STREAM_DESTROYED
      this._duplexState = (this._duplexState | DESTROYING) & NON_PRIMARY

      if (this._readableState !== null) {
        this._readableState.highWaterMark = 0
        this._readableState.error = err
      }
      if (this._writableState !== null) {
        this._writableState.highWaterMark = 0
        this._writableState.error = err
      }

      this._duplexState |= PREDESTROYING
      this._predestroy()
      this._duplexState &= NOT_PREDESTROYING

      if (this._readableState !== null) this._readableState.updateNextTick()
      if (this._writableState !== null) this._writableState.updateNextTick()
    }
  }
}

class Readable extends Stream {
  constructor(opts) {
    super(opts)

    this._duplexState |= OPENING | WRITE_DONE | READ_READ_AHEAD
    this._readableState = new ReadableState(this, opts)

    if (opts) {
      if (this._readableState.readAhead === false) this._duplexState &= READ_NO_READ_AHEAD
      if (opts.read) this._read = opts.read
      if (opts.eagerOpen) this._readableState.updateNextTick()
      if (opts.encoding) this.setEncoding(opts.encoding)
    }
  }

  setEncoding(encoding) {
    const dec = new TextDecoder(encoding)
    const map = this._readableState.map || echo
    this._readableState.map = mapOrSkip
    return this

    function mapOrSkip(data) {
      const next = dec.push(data)
      return next === '' && (data.byteLength !== 0 || dec.remaining > 0) ? null : map(next)
    }
  }

  _read(cb) {
    cb(null)
  }

  pipe(dest, cb) {
    this._readableState.updateNextTick()
    this._readableState.pipe(dest, cb)
    return dest
  }

  read() {
    this._readableState.updateNextTick()
    return this._readableState.read()
  }

  push(data) {
    this._readableState.updateNextTickIfOpen()
    return this._readableState.push(data)
  }

  unshift(data) {
    this._readableState.updateNextTickIfOpen()
    return this._readableState.unshift(data)
  }

  resume() {
    this._duplexState |= READ_RESUMED_READ_AHEAD
    this._readableState.updateNextTick()
    return this
  }

  pause() {
    this._duplexState &=
      this._readableState.readAhead === false ? READ_PAUSED_NO_READ_AHEAD : READ_PAUSED
    return this
  }

  static _fromAsyncIterator(ite, opts) {
    let destroy

    const rs = new Readable({
      ...opts,
      read(cb) {
        ite.next().then(push).then(cb.bind(null, null)).catch(cb)
      },
      predestroy() {
        destroy = ite.return()
      },
      destroy(cb) {
        if (!destroy) return cb(null)
        destroy.then(cb.bind(null, null)).catch(cb)
      }
    })

    return rs

    function push(data) {
      if (data.done) rs.push(null)
      else rs.push(data.value)
    }
  }

  static from(data, opts) {
    if (isReadStreamx(data)) return data
    if (data[asyncIterator]) return this._fromAsyncIterator(data[asyncIterator](), opts)
    if (!Array.isArray(data)) data = data === undefined ? [] : [data]

    let i = 0
    return new Readable({
      ...opts,
      read(cb) {
        this.push(i === data.length ? null : data[i++])
        cb(null)
      }
    })
  }

  static isBackpressured(rs) {
    return (
      (rs._duplexState & READ_BACKPRESSURE_STATUS) !== 0 ||
      rs._readableState.buffered >= rs._readableState.highWaterMark
    )
  }

  static isPaused(rs) {
    return (rs._duplexState & READ_RESUMED) === 0
  }

  [asyncIterator]() {
    const stream = this

    let error = null
    let promiseResolve = null
    let promiseReject = null

    this.on('error', (err) => {
      error = err
    })
    this.on('readable', onreadable)
    this.on('close', onclose)

    return {
      [asyncIterator]() {
        return this
      },
      next() {
        return new Promise(function (resolve, reject) {
          promiseResolve = resolve
          promiseReject = reject
          const data = stream.read()
          if (data !== null) ondata(data)
          else if ((stream._duplexState & DESTROYED) !== 0) ondata(null)
        })
      },
      return() {
        return destroy(null)
      },
      throw(err) {
        return destroy(err)
      }
    }

    function onreadable() {
      if (promiseResolve !== null) ondata(stream.read())
    }

    function onclose() {
      if (promiseResolve !== null) ondata(null)
    }

    function ondata(data) {
      if (promiseReject === null) return
      if (error) promiseReject(error)
      else if (data === null && (stream._duplexState & READ_DONE) === 0)
        promiseReject(STREAM_DESTROYED)
      else promiseResolve({ value: data, done: data === null })
      promiseReject = promiseResolve = null
    }

    function destroy(err) {
      stream.destroy(err)
      return new Promise((resolve, reject) => {
        if (stream._duplexState & DESTROYED) return resolve({ value: undefined, done: true })
        stream.once('close', function () {
          if (err) reject(err)
          else resolve({ value: undefined, done: true })
        })
      })
    }
  }
}

class Writable extends Stream {
  constructor(opts) {
    super(opts)

    this._duplexState |= OPENING | READ_DONE
    this._writableState = new WritableState(this, opts)

    if (opts) {
      if (opts.writev) this._writev = opts.writev
      if (opts.write) this._write = opts.write
      if (opts.final) this._final = opts.final
      if (opts.eagerOpen) this._writableState.updateNextTick()
    }
  }

  cork() {
    this._duplexState |= WRITE_CORKED
  }

  uncork() {
    this._duplexState &= WRITE_NOT_CORKED
    this._writableState.updateNextTick()
  }

  _writev(batch, cb) {
    cb(null)
  }

  _write(data, cb) {
    this._writableState.autoBatch(data, cb)
  }

  _final(cb) {
    cb(null)
  }

  static isBackpressured(ws) {
    return (ws._duplexState & WRITE_BACKPRESSURE_STATUS) !== 0
  }

  static drained(ws) {
    if (ws.destroyed) return Promise.resolve(false)
    const state = ws._writableState
    const pending = isWritev(ws) ? Math.min(1, state.queue.length) : state.queue.length
    const writes = pending + (ws._duplexState & WRITE_WRITING ? 1 : 0)
    if (writes === 0) return Promise.resolve(true)
    if (state.drains === null) state.drains = []
    return new Promise((resolve) => {
      state.drains.push({ writes, resolve })
    })
  }

  write(data) {
    this._writableState.updateNextTick()
    return this._writableState.push(data)
  }

  end(data) {
    this._writableState.updateNextTick()
    this._writableState.end(data)
    return this
  }
}

class Duplex extends Readable {
  // and Writable
  constructor(opts) {
    super(opts)

    this._duplexState = OPENING | (this._duplexState & READ_READ_AHEAD)
    this._writableState = new WritableState(this, opts)

    if (opts) {
      if (opts.writev) this._writev = opts.writev
      if (opts.write) this._write = opts.write
      if (opts.final) this._final = opts.final
    }
  }

  cork() {
    this._duplexState |= WRITE_CORKED
  }

  uncork() {
    this._duplexState &= WRITE_NOT_CORKED
    this._writableState.updateNextTick()
  }

  _writev(batch, cb) {
    cb(null)
  }

  _write(data, cb) {
    this._writableState.autoBatch(data, cb)
  }

  _final(cb) {
    cb(null)
  }

  write(data) {
    this._writableState.updateNextTick()
    return this._writableState.push(data)
  }

  end(data) {
    this._writableState.updateNextTick()
    this._writableState.end(data)
    return this
  }
}

class Transform extends Duplex {
  constructor(opts) {
    super(opts)
    this._transformState = new TransformState(this)

    if (opts) {
      if (opts.transform) this._transform = opts.transform
      if (opts.flush) this._flush = opts.flush
    }
  }

  _write(data, cb) {
    if (this._readableState.buffered >= this._readableState.highWaterMark) {
      this._transformState.data = data
    } else {
      this._transform(data, this._transformState.afterTransform)
    }
  }

  _read(cb) {
    if (this._transformState.data !== null) {
      const data = this._transformState.data
      this._transformState.data = null
      cb(null)
      this._transform(data, this._transformState.afterTransform)
    } else {
      cb(null)
    }
  }

  destroy(err) {
    super.destroy(err)
    if (this._transformState.data !== null) {
      this._transformState.data = null
      this._transformState.afterTransform()
    }
  }

  _transform(data, cb) {
    cb(null, data)
  }

  _flush(cb) {
    cb(null)
  }

  _final(cb) {
    this._transformState.afterFinal = cb
    this._flush(transformAfterFlush.bind(this))
  }
}

class PassThrough extends Transform {}

function transformAfterFlush(err, data) {
  const cb = this._transformState.afterFinal
  if (err) return cb(err)
  if (data !== null && data !== undefined) this.push(data)
  this.push(null)
  cb(null)
}

function pipelinePromise(...streams) {
  return new Promise((resolve, reject) => {
    return pipeline(...streams, (err) => {
      if (err) return reject(err)
      resolve()
    })
  })
}

function pipeline(stream, ...streams) {
  const all = Array.isArray(stream) ? [...stream, ...streams] : [stream, ...streams]
  const done = all.length && typeof all[all.length - 1] === 'function' ? all.pop() : null

  if (all.length < 2) throw new Error('Pipeline requires at least 2 streams')

  let src = all[0]
  let dest = null
  let error = null

  for (let i = 1; i < all.length; i++) {
    dest = all[i]

    if (isStreamx(src)) {
      src.pipe(dest, onerror)
    } else {
      errorHandle(src, true, i > 1, onerror)
      src.pipe(dest)
    }

    src = dest
  }

  if (done) {
    let fin = false

    const autoDestroy =
      isStreamx(dest) || !!(dest._writableState && dest._writableState.autoDestroy)

    dest.on('error', (err) => {
      if (error === null) error = err
    })

    dest.on('finish', () => {
      fin = true
      if (!autoDestroy) done(error)
    })

    if (autoDestroy) {
      dest.on('close', () => done(error || (fin ? null : PREMATURE_CLOSE)))
    }
  }

  return dest

  function errorHandle(s, rd, wr, onerror) {
    s.on('error', onerror)
    s.on('close', onclose)

    function onclose() {
      if (rd && s._readableState && !s._readableState.ended) return onerror(PREMATURE_CLOSE)
      if (wr && s._writableState && !s._writableState.ended) return onerror(PREMATURE_CLOSE)
    }
  }

  function onerror(err) {
    if (!err || error) return
    error = err

    for (const s of all) {
      s.destroy(err)
    }
  }
}

function echo(s) {
  return s
}

function isStream(stream) {
  return !!stream._readableState || !!stream._writableState
}

function isStreamx(stream) {
  return typeof stream._duplexState === 'number' && isStream(stream)
}

function isEnding(stream) {
  return !!stream._readableState && stream._readableState.ending
}

function isEnded(stream) {
  return !!stream._readableState && stream._readableState.ended
}

function isFinishing(stream) {
  return !!stream._writableState && stream._writableState.ending
}

function isFinished(stream) {
  return !!stream._writableState && stream._writableState.ended
}

function getStreamError(stream, opts = {}) {
  const err =
    (stream._readableState && stream._readableState.error) ||
    (stream._writableState && stream._writableState.error)

  // avoid implicit errors by default
  return !opts.all && err === STREAM_DESTROYED ? null : err
}

function isReadStreamx(stream) {
  return isStreamx(stream) && stream.readable
}

function isDisturbed(stream) {
  return (
    (stream._duplexState & OPENING) !== OPENING ||
    (stream._duplexState & DESTROYING) === DESTROYING ||
    (stream._duplexState & ACTIVE_OR_TICKING) !== 0
  )
}

function isTypedArray(data) {
  return typeof data === 'object' && data !== null && typeof data.byteLength === 'number'
}

function defaultByteLength(data) {
  return isTypedArray(data) ? data.byteLength : 1024
}

function noop() {}

function abort() {
  this.destroy(new Error('Stream aborted.'))
}

function isWritev(s) {
  return s._writev !== Writable.prototype._writev && s._writev !== Duplex.prototype._writev
}

module.exports = {
  pipeline,
  pipelinePromise,
  isStream,
  isStreamx,
  isEnding,
  isEnded,
  isFinishing,
  isFinished,
  isDisturbed,
  getStreamError,
  Stream,
  Writable,
  Readable,
  Duplex,
  Transform,
  // Export PassThrough for compatibility with Node.js core's stream module
  PassThrough
}
{
  "name": "streamx",
  "version": "2.25.0",
  "description": "An iteration of the Node.js core streams with a series of improvements",
  "main": "index.js",
  "dependencies": {
    "events-universal": "^1.0.0",
    "fast-fifo": "^1.3.2",
    "text-decoder": "^1.1.0"
  },
  "devDependencies": {
    "b4a": "^1.6.6",
    "brittle": "^3.1.1",
    "end-of-stream": "^1.4.4",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "files": [
    "index.js"
  ],
  "scripts": {
    "format": "prettier --write .",
    "test": "prettier --check . && node test/all.js",
    "test:bare": "bare test/all.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/streamx.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/streamx/issues"
  },
  "homepage": "https://github.com/mafintosh/streamx"
}
const { Readable } = require('streamx')

module.exports = function (s, forks = 2) {
  const streams = new Array(forks)
  const status = new Array(forks).fill(true)

  let ended = false

  for (let i = 0; i < forks; i++) {
    streams[i] = new Readable({
      read (cb) {
        const check = !status[i]
        status[i] = true
        if (check && allReadable()) s.resume()
        cb(null)
      }
    })
  }

  s.on('end', function () {
    ended = true
    for (const stream of streams) stream.push(null)
  })

  s.on('error', function (err) {
    for (const stream of streams) stream.destroy(err)
  })

  s.on('close', function () {
    if (ended) return
    for (const stream of streams) stream.destroy()
  })

  s.on('data', function (data) {
    let needsPause = false
    for (let i = 0; i < streams.length; i++) {
      if (!(status[i] = streams[i].push(data))) {
        needsPause = true
      }
    }
    if (needsPause) s.pause()
  })

  return streams

  function allReadable () {
    for (let j = 0; j < status.length; j++) {
      if (!status[j]) return false
    }
    return true
  }
}
{
  "name": "teex",
  "version": "1.0.1",
  "description": "Turn a readable stream into multiple readable streamx streams",
  "main": "index.js",
  "dependencies": {
    "streamx": "^2.12.5"
  },
  "devDependencies": {
    "standard": "^14.3.4",
    "tape": "^5.0.1"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/teex.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/teex/issues"
  },
  "homepage": "https://github.com/mafintosh/teex"
}
const PassThroughDecoder = require('./lib/pass-through-decoder')
const UTF8Decoder = require('./lib/utf8-decoder')

module.exports = class TextDecoder {
  constructor(encoding = 'utf8') {
    this.encoding = normalizeEncoding(encoding)

    switch (this.encoding) {
      case 'utf8':
        this.decoder = new UTF8Decoder()
        break
      case 'utf16le':
      case 'base64':
        throw new Error('Unsupported encoding: ' + this.encoding)
      default:
        this.decoder = new PassThroughDecoder(this.encoding)
    }
  }

  get remaining() {
    return this.decoder.remaining
  }

  push(data) {
    if (typeof data === 'string') return data
    return this.decoder.decode(data)
  }

  // For Node.js compatibility
  write(data) {
    return this.push(data)
  }

  end(data) {
    let result = ''
    if (data) result = this.push(data)
    result += this.decoder.flush()
    return result
  }
}

function normalizeEncoding(encoding) {
  encoding = encoding.toLowerCase()

  switch (encoding) {
    case 'utf8':
    case 'utf-8':
      return 'utf8'
    case 'ucs2':
    case 'ucs-2':
    case 'utf16le':
    case 'utf-16le':
      return 'utf16le'
    case 'latin1':
    case 'binary':
      return 'latin1'
    case 'base64':
    case 'ascii':
    case 'hex':
      return encoding
    default:
      throw new Error('Unknown encoding: ' + encoding)
  }
}
const b4a = require('b4a')

module.exports = class PassThroughDecoder {
  constructor(encoding) {
    this.encoding = encoding
  }

  get remaining() {
    return 0
  }

  decode(data) {
    return b4a.toString(data, this.encoding)
  }

  flush() {
    return ''
  }
}
const b4a = require('b4a')

/**
 * https://encoding.spec.whatwg.org/#utf-8-decoder
 */
module.exports = class UTF8Decoder {
  constructor() {
    this._reset()
  }

  get remaining() {
    return this.bytesSeen
  }

  decode(data) {
    if (data.byteLength === 0) return ''

    if (this.bytesNeeded === 0 && trailingIncomplete(data, 0) === 0) {
      this.bytesSeen = trailingBytesSeen(data)
      return b4a.toString(data, 'utf8')
    }

    let result = ''
    let start = 0

    if (this.bytesNeeded > 0) {
      while (start < data.byteLength) {
        const byte = data[start]

        if (byte < this.lowerBoundary || byte > this.upperBoundary) {
          result += '\ufffd'
          this._reset()
          break
        }

        this.lowerBoundary = 0x80
        this.upperBoundary = 0xbf
        this.codePoint = (this.codePoint << 6) | (byte & 0x3f)
        this.bytesSeen++
        start++

        if (this.bytesSeen === this.bytesNeeded) {
          result += String.fromCodePoint(this.codePoint)
          this._reset()
          break
        }
      }

      if (this.bytesNeeded > 0) return result
    }

    const trailing = trailingIncomplete(data, start)
    const end = data.byteLength - trailing

    if (end > start) result += b4a.toString(data, 'utf8', start, end)

    for (let i = end; i < data.byteLength; i++) {
      const byte = data[i]

      if (this.bytesNeeded === 0) {
        if (byte <= 0x7f) {
          this.bytesSeen = 0
          result += String.fromCharCode(byte)
        } else if (byte >= 0xc2 && byte <= 0xdf) {
          this.bytesNeeded = 2
          this.bytesSeen = 1
          this.codePoint = byte & 0x1f
        } else if (byte >= 0xe0 && byte <= 0xef) {
          if (byte === 0xe0) this.lowerBoundary = 0xa0
          else if (byte === 0xed) this.upperBoundary = 0x9f
          this.bytesNeeded = 3
          this.bytesSeen = 1
          this.codePoint = byte & 0xf
        } else if (byte >= 0xf0 && byte <= 0xf4) {
          if (byte === 0xf0) this.lowerBoundary = 0x90
          else if (byte === 0xf4) this.upperBoundary = 0x8f
          this.bytesNeeded = 4
          this.bytesSeen = 1
          this.codePoint = byte & 0x7
        } else {
          this.bytesSeen = 1
          result += '\ufffd'
        }

        continue
      }

      if (byte < this.lowerBoundary || byte > this.upperBoundary) {
        result += '\ufffd'
        i--
        this._reset()

        continue
      }

      this.lowerBoundary = 0x80
      this.upperBoundary = 0xbf

      this.codePoint = (this.codePoint << 6) | (byte & 0x3f)
      this.bytesSeen++

      if (this.bytesSeen === this.bytesNeeded) {
        result += String.fromCodePoint(this.codePoint)
        this._reset()
      }
    }

    return result
  }

  flush() {
    const result = this.bytesNeeded > 0 ? '\ufffd' : ''
    this._reset()
    return result
  }

  _reset() {
    this.codePoint = 0
    this.bytesNeeded = 0
    this.bytesSeen = 0
    this.lowerBoundary = 0x80
    this.upperBoundary = 0xbf
  }
}

function trailingIncomplete(data, start) {
  const len = data.byteLength
  if (len <= start) return 0

  const limit = Math.max(start, len - 4)

  let i = len - 1
  while (i > limit && (data[i] & 0xc0) === 0x80) i--

  if (i < start) return 0

  const byte = data[i]

  let needed
  if (byte <= 0x7f) return 0
  if (byte >= 0xc2 && byte <= 0xdf) needed = 2
  else if (byte >= 0xe0 && byte <= 0xef) needed = 3
  else if (byte >= 0xf0 && byte <= 0xf4) needed = 4
  else return 0

  const available = len - i
  return available < needed ? available : 0
}

function trailingBytesSeen(data) {
  const len = data.byteLength
  if (len === 0) return 0

  const last = data[len - 1]

  if (last <= 0x7f) return 0
  if ((last & 0xc0) !== 0x80) return 1

  const limit = Math.max(0, len - 4)

  let i = len - 2
  while (i >= limit && (data[i] & 0xc0) === 0x80) i--

  if (i < 0) return 1

  const first = data[i]

  let needed
  if (first >= 0xc2 && first <= 0xdf) needed = 2
  else if (first >= 0xe0 && first <= 0xef) needed = 3
  else if (first >= 0xf0 && first <= 0xf4) needed = 4
  else return 1

  if (len - i !== needed) return 1

  if (needed >= 3) {
    const second = data[i + 1]
    if (first === 0xe0 && second < 0xa0) return 1
    if (first === 0xed && second > 0x9f) return 1
    if (first === 0xf0 && second < 0x90) return 1
    if (first === 0xf4 && second > 0x8f) return 1
  }

  return 0
}
{
  "name": "text-decoder",
  "version": "1.2.7",
  "description": "Streaming text decoder that preserves multibyte Unicode characters",
  "exports": {
    "./package": "./package.json",
    ".": "./index.js"
  },
  "files": [
    "index.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/text-decoder.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/text-decoder/issues"
  },
  "homepage": "https://github.com/holepunchto/text-decoder#readme",
  "dependencies": {
    "b4a": "^1.6.4"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  }
}
module.exports = class TimeOrderedSet {
  constructor () {
    this.oldest = null
    this.latest = null
    this.length = 0
  }

  has (node) {
    return !!(node.next || node.prev) || node === this.oldest
  }

  add (node) {
    if (this.has(node)) this.remove(node)

    if (!this.latest && !this.oldest) {
      this.latest = this.oldest = node
      node.prev = node.next = null
    } else {
      this.latest.next = node
      node.prev = this.latest
      node.next = null
      this.latest = node
    }

    this.length++

    return node
  }

  remove (node) {
    if (!this.has(node)) return node

    if (this.oldest !== node && this.latest !== node) {
      node.prev.next = node.next
      node.next.prev = node.prev
    } else {
      if (this.oldest === node) {
        this.oldest = node.next
        if (this.oldest) this.oldest.prev = null
      }
      if (this.latest === node) {
        this.latest = node.prev
        if (this.latest) this.latest.next = null
      }
    }

    node.next = node.prev = null
    this.length--

    return node
  }

  toArray ({ limit = Infinity, reverse = false } = {}) {
    const list = []

    if (reverse) {
      let node = this.latest
      while (node && limit--) {
        list.push(node)
        node = node.prev
      }
    } else {
      let node = this.oldest
      while (node && limit--) {
        list.push(node)
        node = node.next
      }
    }

    return list
  }
}
{
  "name": "time-ordered-set",
  "version": "2.0.1",
  "description": "Efficiently maintain a set of nodes ordered by the time they were added to the set",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "devDependencies": {
    "brittle": "^3.0.0",
    "standard": "^17.1.2"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/time-ordered-set.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/time-ordered-set/issues"
  },
  "homepage": "https://github.com/mafintosh/time-ordered-set"
}
module.exports = class TimerBrowser {
  constructor (ms, fn, ctx = null, interval = false) {
    this.ms = ms
    this.ontimeout = fn
    this.context = ctx || null
    this.interval = interval
    this.done = false

    this._timer = interval
      ? setInterval(callInterval, ms, this)
      : setTimeout(callTimeout, ms, this)
  }

  unref () {}

  ref () {}

  refresh () {
    if (this.done) return

    if (this.interval) {
      clearInterval(this._timer)
      this._timer = setInterval(callInterval, this.ms, this)
    } else {
      clearTimeout(this._timer)
      this._timer = setTimeout(callTimeout, this.ms, this)
    }
  }

  destroy () {
    this.done = true
    this.ontimeout = null

    if (this.interval) clearInterval(this._timer)
    else clearTimeout(this._timer)
  }

  static once (ms, fn, ctx) {
    return new this(ms, fn, ctx, false)
  }

  static on (ms, fn, ctx) {
    return new this(ms, fn, ctx, true)
  }
}

function callTimeout (self) {
  self.done = true
  self.ontimeout.call(self.context)
}

function callInterval (self) {
  self.ontimeout.call(self.context)
}
module.exports = isNode()
  ? require('./node')
  : require('./browser')

function isNode () {
  const to = setTimeout(function () {}, 1000)
  clearTimeout(to)
  return !!to.refresh
}
module.exports = class Timer {
  constructor (ms, fn, ctx = null, interval = false) {
    this.ms = ms
    this.ontimeout = fn
    this.context = ctx
    this.interval = interval
    this.done = false

    this._timer = interval
      ? setInterval(callInterval, ms, this)
      : setTimeout(callTimeout, ms, this)
  }

  unref () {
    this._timer.unref()
  }

  ref () {
    this._timer.ref()
  }

  refresh () {
    if (this.done !== true) this._timer.refresh()
  }

  destroy () {
    this.done = true
    this.ontimeout = null
    if (this.interval) clearInterval(this._timer)
    else clearTimeout(this._timer)
  }

  static once (ms, fn, ctx) {
    return new this(ms, fn, ctx, false)
  }

  static on (ms, fn, ctx) {
    return new this(ms, fn, ctx, true)
  }
}

function callTimeout (self) {
  self.done = true
  self.ontimeout.call(self.context)
}

function callInterval (self) {
  self.ontimeout.call(self.context)
}
{
  "name": "timeout-refresh",
  "version": "2.0.1",
  "description": "Efficiently refresh a timer",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^16.0.4",
    "tape": "^5.5.2"
  },
  "browser": "./browser.js",
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/timeout-refresh.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/timeout-refresh/issues"
  },
  "homepage": "https://github.com/mafintosh/timeout-refresh"
}
require.addon = require('require-addon')

module.exports = require.addon('.', __filename)
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

const v4Seg = '(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])'
const v4Str = `(${v4Seg}[.]){3}${v4Seg}`
const IPv4Pattern = new RegExp(`^${v4Str}$`)

const v6Seg = '(?:[0-9a-fA-F]{1,4})'
const IPv6Pattern = new RegExp(
  '^(' +
    `(?:${v6Seg}:){7}(?:${v6Seg}|:)|` +
    `(?:${v6Seg}:){6}(?:${v4Str}|:${v6Seg}|:)|` +
    `(?:${v6Seg}:){5}(?::${v4Str}|(:${v6Seg}){1,2}|:)|` +
    `(?:${v6Seg}:){4}(?:(:${v6Seg}){0,1}:${v4Str}|(:${v6Seg}){1,3}|:)|` +
    `(?:${v6Seg}:){3}(?:(:${v6Seg}){0,2}:${v4Str}|(:${v6Seg}){1,4}|:)|` +
    `(?:${v6Seg}:){2}(?:(:${v6Seg}){0,3}:${v4Str}|(:${v6Seg}){1,5}|:)|` +
    `(?:${v6Seg}:){1}(?:(:${v6Seg}){0,4}:${v4Str}|(:${v6Seg}){1,6}|:)|` +
    `(?::((?::${v6Seg}){0,5}:${v4Str}|(?::${v6Seg}){1,7}|:))` +
    ')(%[0-9a-zA-Z-.:]{1,})?$'
)

const isIPv4 = (exports.isIPv4 = function isIPv4(host) {
  return IPv4Pattern.test(host)
})

const isIPv6 = (exports.isIPv6 = function isIPv6(host) {
  return IPv6Pattern.test(host)
})

exports.isIP = function isIP(host) {
  if (isIPv4(host)) return 4
  if (isIPv6(host)) return 6
  return 0
}
const events = require('events')
const b4a = require('b4a')
const binding = require('../binding')

module.exports = class NetworkInterfaces extends events.EventEmitter {
  constructor(udx) {
    super()

    this._handle = b4a.alloc(binding.sizeof_udx_napi_interface_event_t)
    this._watching = false
    this._destroying = null

    binding.udx_napi_interface_event_init(
      udx._handle,
      this._handle,
      this,
      this._onevent,
      this._onclose
    )

    this.interfaces = binding.udx_napi_interface_event_get_addrs(this._handle)
  }

  _onclose() {
    this.emit('close')
  }

  _onevent() {
    this.interfaces = binding.udx_napi_interface_event_get_addrs(this._handle)

    this.emit('change', this.interfaces)
  }

  watch() {
    if (this._watching) return this
    this._watching = true

    binding.udx_napi_interface_event_start(this._handle)

    return this
  }

  unwatch() {
    if (!this._watching) return this
    this._watching = false

    binding.udx_napi_interface_event_stop(this._handle)

    return this
  }

  async destroy() {
    if (this._destroying) return this._destroying
    this._destroying = events.once(this, 'close')

    binding.udx_napi_interface_event_close(this._handle)

    return this._destroying
  }

  [Symbol.iterator]() {
    return this.interfaces[Symbol.iterator]()
  }
}
const events = require('events')
const b4a = require('b4a')
const binding = require('../binding')
const ip = require('./ip')

module.exports = class UDXSocket extends events.EventEmitter {
  constructor(udx, opts = {}) {
    super()

    this.udx = udx

    this._handle = b4a.alloc(binding.sizeof_udx_napi_socket_t)
    this._inited = false
    this._host = null
    this._family = 0
    this._ipv6Only = opts.ipv6Only === true
    this._reuseAddress = opts.reuseAddress === true
    this._port = 0
    this._reqs = []
    this._free = []
    this._closing = null
    this._closed = false

    this._view64 = new BigUint64Array(
      this._handle.buffer,
      this._handle.byteOffset,
      this._handle.byteLength >> 3
    )

    this.streams = new Set()

    this.userData = null
  }

  get bound() {
    return this._port !== 0
  }

  get closing() {
    return this._closing !== null
  }

  get idle() {
    return this.streams.size === 0
  }

  get busy() {
    return this.streams.size > 0
  }

  get bytesTransmitted() {
    if (this._inited !== true) return 0
    return Number(this._view64[binding.offsetof_udx_socket_t_bytes_tx >> 3])
  }

  get packetsTransmitted() {
    if (this._inited !== true) return 0
    return Number(this._view64[binding.offsetof_udx_socket_t_packets_tx >> 3])
  }

  get bytesReceived() {
    if (this._inited !== true) return 0
    return Number(this._view64[binding.offsetof_udx_socket_t_bytes_rx >> 3])
  }

  get packetsReceived() {
    if (this._inited !== true) return 0
    return Number(this._view64[binding.offsetof_udx_socket_t_packets_rx >> 3])
  }

  get packetsDroppedByKernel() {
    if (this._inited !== true) return 0
    return Number(this._view64[binding.offsetof_udx_socket_t_packets_dropped_by_kernel >> 3])
  }

  toJSON() {
    return {
      bound: this.bound,
      closing: this.closing,
      streams: this.streams.size,
      address: this.address(),
      ipv6Only: this._ipv6Only,
      reuseAddress: this._reuseAddress,
      idle: this.idle,
      busy: this.busy
    }
  }

  _init() {
    if (this._inited) return

    binding.udx_napi_socket_init(
      this.udx._handle,
      this._handle,
      this,
      this._onsend,
      this._onmessage,
      this._onclose,
      this._reallocMessage
    )

    this._inited = true
  }

  _onsend(id, err) {
    const req = this._reqs[id]

    const onflush = req.onflush

    req.buffer = null
    req.onflush = null

    this._free.push(id)

    onflush(err >= 0)

    // gc the free list
    if (this._free.length >= 16 && this._free.length === this._reqs.length) {
      this._free = []
      this._reqs = []
    }
  }

  _onmessage(len, port, host, family) {
    this.emit('message', this.udx._consumeMessage(len), { host, family, port })
    return this.udx._buffer
  }

  _onclose() {
    this.emit('close')
  }

  _reallocMessage() {
    return this.udx._reallocMessage()
  }

  _onidle() {
    this.emit('idle')
  }

  _onbusy() {
    this.emit('busy')
  }

  _addStream(stream) {
    if (this.streams.has(stream)) return false
    this.streams.add(stream)
    if (this.streams.size === 1) this._onbusy()
    return true
  }

  _removeStream(stream) {
    if (!this.streams.has(stream)) return false
    this.streams.delete(stream)
    const closed = this._closeMaybe()
    if (this.idle && !closed) this._onidle()
    return true
  }

  address() {
    if (!this.bound) return null
    return { host: this._host, family: this._family, port: this._port }
  }

  bind(port, host) {
    if (this.bound) throw new Error('Already bound')
    if (this.closing) throw new Error('Socket is closed')

    if (!port) port = 0

    let flags = 0
    if (this._ipv6Only) flags |= binding.UV_UDP_IPV6ONLY
    if (this._reuseAddress) flags |= binding.UV_UDP_REUSEADDR

    let family

    if (host) {
      family = ip.isIP(host)
      if (!family) throw new Error(`${host} is not a valid IP address`)

      if (!this._inited) this._init()

      this._port = binding.udx_napi_socket_bind(this._handle, port, host, family, flags)
    } else {
      if (!this._inited) this._init()

      try {
        host = '::'
        family = 6
        this._port = binding.udx_napi_socket_bind(this._handle, port, host, family, flags)
      } catch {
        host = '0.0.0.0'
        family = 4
        this._port = binding.udx_napi_socket_bind(this._handle, port, host, family, flags)
      }
    }

    this._host = host
    this._family = family

    this.emit('listening')
  }

  async close() {
    if (this._closing) return this._closing
    this._closing = new Promise((resolve) => this.once('close', resolve))
    this._closeMaybe()
    return this._closing
  }

  _closeMaybe() {
    if (this._closed || this._closing === null) return this._closed

    if (!this._inited) {
      this._closed = true
      this.emit('close')
      return true
    }

    if (this.idle) {
      binding.udx_napi_socket_close(this._handle)
      this._closed = true
    }

    return this._closed
  }

  setTTL(ttl) {
    if (!this._inited) throw new Error('Socket not active')
    binding.udx_napi_socket_set_ttl(this._handle, ttl)
  }

  getRecvBufferSize() {
    if (!this._inited) throw new Error('Socket not active')
    return binding.udx_napi_socket_get_recv_buffer_size(this._handle)
  }

  setRecvBufferSize(size) {
    if (!this._inited) throw new Error('Socket not active')
    return binding.udx_napi_socket_set_recv_buffer_size(this._handle, size)
  }

  getSendBufferSize() {
    if (!this._inited) throw new Error('Socket not active')
    return binding.udx_napi_socket_get_send_buffer_size(this._handle)
  }

  setSendBufferSize(size) {
    if (!this._inited) throw new Error('Socket not active')
    return binding.udx_napi_socket_set_send_buffer_size(this._handle, size)
  }

  addMembership(group, ifaceAddress) {
    if (!this._inited) throw new Error('Socket not active')
    return binding.udx_napi_socket_set_membership(this._handle, group, ifaceAddress || '', true)
  }

  dropMembership(group, ifaceAddress) {
    if (!this._inited) throw new Error('Socket not active')
    return binding.udx_napi_socket_set_membership(this._handle, group, ifaceAddress || '', false)
  }

  async send(buffer, port, host, ttl) {
    if (this.closing) return false

    if (!host) host = '127.0.0.1'

    const family = ip.isIP(host)
    if (!family) throw new Error(`${host} is not a valid IP address`)

    if (!this.bound) this.bind(0)

    const id = this._allocSend()
    const req = this._reqs[id]

    req.buffer = buffer

    const promise = new Promise((resolve) => {
      req.onflush = resolve
    })

    binding.udx_napi_socket_send_ttl(
      this._handle,
      req.handle,
      id,
      buffer,
      port,
      host,
      family,
      ttl || 0
    )

    return promise
  }

  trySend(buffer, port, host, ttl) {
    if (this.closing) return

    if (!host) host = '127.0.0.1'

    const family = ip.isIP(host)
    if (!family) throw new Error(`${host} is not a valid IP address`)

    if (!this.bound) this.bind(0)

    const id = this._allocSend()
    const req = this._reqs[id]

    req.buffer = buffer
    req.onflush = noop

    binding.udx_napi_socket_send_ttl(
      this._handle,
      req.handle,
      id,
      buffer,
      port,
      host,
      family,
      ttl || 0
    )
  }

  _allocSend() {
    if (this._free.length > 0) return this._free.pop()
    const handle = b4a.allocUnsafe(binding.sizeof_udx_socket_send_t)
    return this._reqs.push({ handle, buffer: null, onflush: null }) - 1
  }
}

function noop() {}
const streamx = require('streamx')
const b4a = require('b4a')
const binding = require('../binding')
const ip = require('./ip')

const MAX_PACKET = 2048
const BUFFER_SIZE = 65536 + MAX_PACKET

module.exports = class UDXStream extends streamx.Duplex {
  constructor(udx, id, opts = {}) {
    super({ mapWritable: toBuffer, eagerOpen: true })

    this.udx = udx
    this.socket = null

    this._handle = b4a.alloc(binding.sizeof_udx_napi_stream_t)
    this._view = new Uint32Array(
      this._handle.buffer,
      this._handle.byteOffset,
      this._handle.byteLength >> 2
    )
    this._view16 = new Uint16Array(
      this._handle.buffer,
      this._handle.byteOffset,
      this._handle.byteLength >> 1
    )
    this._view64 = new BigUint64Array(
      this._handle.buffer,
      this._handle.byteOffset,
      this._handle.byteLength >> 3
    )

    this._wreqs = []
    this._wfree = []

    this._sreqs = []
    this._sfree = []
    this._closed = false

    this._flushing = 0
    this._flushes = []

    this._buffer = null
    this._reallocData()

    this._onwrite = null
    this._ondestroy = null
    this._firewall = opts.firewall || firewallAll

    this._remoteChanging = null
    this._previousSocket = null

    this.id = id
    this.remoteId = 0
    this.remoteHost = null
    this.remoteFamily = 0
    this.remotePort = 0

    this.userData = null

    binding.udx_napi_stream_init(
      this.udx._handle,
      this._handle,
      id,
      opts.framed ? 1 : 0,
      this,
      this._ondata,
      this._onend,
      this._ondrain,
      this._onack,
      this._onsend,
      this._onmessage,
      this._onclose,
      this._onfirewall,
      this._onremotechanged,
      this._reallocData,
      this._reallocMessage
    )

    if (opts.seq) binding.udx_napi_stream_set_seq(this._handle, opts.seq)

    binding.udx_napi_stream_recv_start(this._handle, this._buffer)
  }

  get connected() {
    return this.socket !== null
  }

  get mtu() {
    return this._view16[binding.offsetof_udx_stream_t_mtu >> 1]
  }

  get rtt() {
    return this._view[binding.offsetof_udx_stream_t_srtt >> 2]
  }

  get cwnd() {
    return this._view[binding.offsetof_udx_stream_t_cwnd >> 2]
  }

  get rtoCount() {
    return this._view16[binding.offsetof_udx_stream_t_rto_count >> 1]
  }

  get retransmits() {
    return this._view16[binding.offsetof_udx_stream_t_retransmit_count >> 1]
  }

  get fastRecoveries() {
    return this._view16[binding.offsetof_udx_stream_t_fast_recovery_count >> 1]
  }

  get inflight() {
    return this._view[binding.offsetof_udx_stream_t_inflight >> 2]
  }

  get bytesTransmitted() {
    return Number(this._view64[binding.offsetof_udx_stream_t_bytes_tx >> 3])
  }

  get packetsTransmitted() {
    return Number(this._view64[binding.offsetof_udx_stream_t_packets_tx >> 3])
  }

  get bytesReceived() {
    return Number(this._view64[binding.offsetof_udx_stream_t_bytes_rx >> 3])
  }

  get packetsReceived() {
    return Number(this._view64[binding.offsetof_udx_stream_t_packets_rx >> 3])
  }

  get localHost() {
    return this.socket ? this.socket.address().host : null
  }

  get localFamily() {
    return this.socket ? this.socket.address().family : 0
  }

  get localPort() {
    return this.socket ? this.socket.address().port : 0
  }

  setInteractive(bool) {
    if (!this._closed) return
    binding.udx_napi_stream_set_mode(this._handle, bool ? 0 : 1)
  }

  connect(socket, remoteId, port, host, opts = {}) {
    if (this._closed) return

    if (this.connected) throw new Error('Already connected')
    if (socket.closing) throw new Error('Socket is closed')

    if (typeof host === 'object') {
      opts = host
      host = null
    }

    if (!host) host = '127.0.0.1'

    const family = ip.isIP(host)
    if (!family) throw new Error(`${host} is not a valid IP address`)
    if (!(port > 0 && port < 65536)) throw new Error(`${port} is not a valid port`)

    if (!socket.bound) socket.bind(0)

    this.remoteId = remoteId
    this.remotePort = port
    this.remoteHost = host
    this.remoteFamily = family
    this.socket = socket

    if (opts.ack) binding.udx_napi_stream_set_ack(this._handle, opts.ack)

    binding.udx_napi_stream_connect(this._handle, socket._handle, remoteId, port, host, family)

    this.socket._addStream(this)

    this.emit('connect')
  }

  changeRemote(socket, remoteId, port, host) {
    if (this._remoteChanging) throw new Error('Remote already changing')

    if (!this.connected) throw new Error('Not yet connected')
    if (socket.closing) throw new Error('Socket is closed')

    if (this.socket.udx !== socket.udx) {
      throw new Error('Cannot change to a socket on another UDX instance')
    }

    if (!host) host = '127.0.0.1'

    const family = ip.isIP(host)
    if (!family) throw new Error(`${host} is not a valid IP address`)
    if (!(port > 0 && port < 65536)) throw new Error(`${port} is not a valid port`)

    if (this.socket !== socket) this._previousSocket = this.socket

    this.remoteId = remoteId
    this.remotePort = port
    this.remoteHost = host
    this.remoteFamily = family
    this.socket = socket

    this._remoteChanging = new Promise((resolve, reject) => {
      const onchanged = () => {
        this.off('close', onclose)
        resolve()
      }

      const onclose = () => {
        this.off('remote-changed', onchanged)
        reject(new Error('Stream is closed'))
      }

      this.once('remote-changed', onchanged).once('close', onclose)
    })

    binding.udx_napi_stream_change_remote(
      this._handle,
      socket._handle,
      remoteId,
      port,
      host,
      family
    )

    this.socket._addStream(this)

    return this._remoteChanging
  }

  relayTo(destination) {
    if (this._closed) return

    binding.udx_napi_stream_relay_to(this._handle, destination._handle)
  }

  async send(buffer) {
    if (!this.connected || this._closed) return false

    const id = this._allocSend()
    const req = this._sreqs[id]

    req.buffer = buffer

    const promise = new Promise((resolve) => {
      req.onflush = resolve
    })

    binding.udx_napi_stream_send(this._handle, req.handle, id, buffer)

    return promise
  }

  trySend(buffer) {
    if (!this.connected || this._closed) return

    const id = this._allocSend()
    const req = this._sreqs[id]

    req.buffer = buffer
    req.onflush = noop

    binding.udx_napi_stream_send(this._handle, req.handle, id, buffer)
  }

  async flush() {
    if ((await streamx.Writable.drained(this)) === false) return false
    if (this.destroying) return false

    const missing = this._wreqs.length - this._wfree.length
    if (missing === 0) return true

    return new Promise((resolve) => {
      this._flushes.push({ flush: this._flushing++, missing, resolve })
    })
  }

  toJSON() {
    return {
      id: this.id,
      connected: this.connected,
      destroying: this.destroying,
      destroyed: this.destroyed,
      remoteId: this.remoteId,
      remoteHost: this.remoteHost,
      remoteFamily: this.remoteFamily,
      remotePort: this.remotePort,
      mtu: this.mtu,
      rtt: this.rtt,
      cwnd: this.cwnd,
      inflight: this.inflight,
      socket: this.socket ? this.socket.toJSON() : null
    }
  }

  _read(cb) {
    cb(null)
  }

  _writeContinue(err) {
    if (this._onwrite === null) return
    const cb = this._onwrite
    this._onwrite = null
    cb(err)
  }

  _destroyContinue(err) {
    if (this._ondestroy === null) return
    const cb = this._ondestroy
    this._ondestroy = null
    cb(err)
  }

  _writev(buffers, cb) {
    if (!this.connected)
      throw customError('Writing while not connected not currently supported', 'ERR_ASSERTION')

    let drained = true

    if (buffers.length === 1) {
      const id = this._allocWrite(1)
      const req = this._wreqs[id]

      req.flush = this._flushing
      req.buffer = buffers[0]

      drained = binding.udx_napi_stream_write(this._handle, req.handle, id, req.buffer) !== 0
    } else {
      const id = this._allocWrite(nextBatchSize(buffers.length))
      const req = this._wreqs[id]

      req.flush = this._flushing
      req.buffers = buffers

      drained = binding.udx_napi_stream_writev(this._handle, req.handle, id, req.buffers) !== 0
    }

    if (drained) cb(null)
    else this._onwrite = cb
  }

  _final(cb) {
    const id = this._allocWrite(1)
    const req = this._wreqs[id]

    req.flush = this._flushes
    req.buffer = b4a.allocUnsafe(0)

    const drained =
      binding.udx_napi_stream_write_end(this._handle, req.handle, id, req.buffer) !== 0

    if (drained) cb(null)
    else this._onwrite = cb
  }

  _predestroy() {
    if (!this._closed) binding.udx_napi_stream_destroy(this._handle)
    this._closed = true
    this._writeContinue(null)
  }

  _destroy(cb) {
    if (this.connected) this._ondestroy = cb
    else cb(null)
  }

  _ondata(read) {
    this.push(this._consumeData(read))
    return this._buffer
  }

  _onend(read) {
    if (read > 0) this.push(this._consumeData(read))
    this.push(null)
  }

  _ondrain() {
    this._writeContinue(null)
  }

  _flushAck(flush) {
    for (let i = this._flushes.length - 1; i >= 0; i--) {
      const f = this._flushes[i]
      if (f.flush < flush) break
      f.missing--
    }

    while (this._flushes.length > 0 && this._flushes[0].missing === 0) {
      this._flushes.shift().resolve(true)
    }
  }

  _onack(id) {
    const req = this._wreqs[id]

    req.buffers = req.buffer = null
    this._wfree.push(id)

    if (this._flushes.length > 0) this._flushAck(req.flush)

    // gc the free list
    if (this._wfree.length >= 64 && this._wfree.length === this._wreqs.length) {
      this._wfree = []
      this._wreqs = []
    }
  }

  _onsend(id, err) {
    const req = this._sreqs[id]

    const onflush = req.onflush

    req.buffer = null
    req.onflush = null

    this._sfree.push(id)

    onflush(err >= 0)

    // gc the free list
    if (this._sfree.length >= 16 && this._sfree.length === this._sreqs.length) {
      this._sfree = []
      this._sreqs = []
    }
  }

  _onmessage(len) {
    this.emit('message', this.udx._consumeMessage(len))
    return this.udx._buffer
  }

  _onclose(err) {
    this._closed = true

    if (this.socket) {
      this.socket._removeStream(this)
      this.socket = null
    }

    if (this._previousSocket) {
      this._previousSocket._removeStream(this)
      this._previousSocket = null
    }

    // no error, we don't need to do anything
    if (!err) return this._destroyContinue(null)

    if (this._ondestroy === null) this.destroy(err)
    else this._destroyContinue(err)
  }

  _onfirewall(socket, port, host, family) {
    return this._firewall(socket, port, host, family) ? 1 : 0
  }

  _onremotechanged() {
    if (this._previousSocket) {
      this._previousSocket._removeStream(this)
      this._previousSocket = null
    }

    this._remoteChanging = null
    this.emit('remote-changed')
  }

  _consumeData(len) {
    const next = this._buffer.subarray(0, len)
    this._buffer = this._buffer.subarray(len)
    if (this._buffer.byteLength < MAX_PACKET) this._reallocData()
    return next
  }

  _reallocData() {
    this._buffer = b4a.allocUnsafe(BUFFER_SIZE)
    return this._buffer
  }

  _reallocMessage() {
    return this.udx._reallocMessage()
  }

  _allocWrite(size) {
    if (this._wfree.length === 0) {
      const handle = b4a.allocUnsafe(binding.udx_napi_stream_write_sizeof(size))
      return (
        this._wreqs.push({
          handle,
          size,
          buffers: null,
          buffer: null,
          flush: 0
        }) - 1
      )
    }

    const free = this._wfree.pop()
    if (size === 1) return free

    const next = this._wreqs[free]
    if (next.size < size) {
      next.handle = b4a.allocUnsafe(binding.udx_napi_stream_write_sizeof(size))
      next.size = size
    }

    return free
  }

  _allocSend() {
    if (this._sfree.length > 0) return this._sfree.pop()
    const handle = b4a.allocUnsafe(binding.sizeof_udx_stream_send_t)
    return this._sreqs.push({ handle, buffer: null, resolve: null, reject: null }) - 1
  }
}

function noop() {}

function toBuffer(data) {
  return typeof data === 'string' ? b4a.from(data) : data
}

function firewallAll(socket, port, host) {
  return true
}

function customError(message, code) {
  const error = new Error(message)
  error.code = code
  return error
}

function nextBatchSize(n) {
  // try to coerce the the writevs into sameish size
  if (n === 1) return 1
  // group all < 8 to the same size, low mem overhead but save some small allocs
  if (n < 8) return 8
  if (n < 16) return 16
  if (n < 32) return 32
  if (n < 64) return 64
  return n
}
const b4a = require('b4a')
const binding = require('../binding')
const ip = require('./ip')
const Socket = require('./socket')
const Stream = require('./stream')
const NetworkInterfaces = require('./network-interfaces')

const MAX_MESSAGE = 4096
const BUFFER_SIZE = 65536 + MAX_MESSAGE

module.exports = class UDX {
  constructor() {
    this._handle = b4a.alloc(binding.sizeof_udx_napi_t)
    this._watchers = new Set()
    this._view64 = new BigUint64Array(
      this._handle.buffer,
      this._handle.byteOffset,
      this._handle.byteLength >> 3
    )

    this._buffer = null
    this._reallocMessage()

    binding.udx_napi_init(this._handle, this._buffer)
  }

  static isIPv4(host) {
    return ip.isIPv4(host)
  }

  static isIPv6(host) {
    return ip.isIPv6(host)
  }

  static isIP(host) {
    return ip.isIP(host)
  }

  get bytesTransmitted() {
    return Number(this._view64[binding.offsetof_udx_t_bytes_tx >> 3])
  }

  get packetsTransmitted() {
    return Number(this._view64[binding.offsetof_udx_t_packets_tx >> 3])
  }

  get bytesReceived() {
    return Number(this._view64[binding.offsetof_udx_t_bytes_rx >> 3])
  }

  get packetsReceived() {
    return Number(this._view64[binding.offsetof_udx_t_packets_rx >> 3])
  }

  get packetsDroppedByKernel() {
    return Number(this._view64[binding.offsetof_udx_t_packets_dropped_by_kernel >> 3])
  }

  _consumeMessage(len) {
    const next = this._buffer.subarray(0, len)
    this._buffer = this._buffer.subarray(len)
    if (this._buffer.byteLength < MAX_MESSAGE) this._reallocMessage()
    return next
  }

  _reallocMessage() {
    // TODO: move reallocation to native
    this._buffer = b4a.allocUnsafe(BUFFER_SIZE)
    return this._buffer
  }

  createSocket(opts) {
    return new Socket(this, opts)
  }

  createStream(id, opts) {
    return new Stream(this, id, opts)
  }

  networkInterfaces() {
    let [watcher = null] = this._watchers
    if (watcher) return watcher.interfaces

    watcher = new NetworkInterfaces(this)
    watcher.destroy()

    return watcher.interfaces
  }

  watchNetworkInterfaces(onchange) {
    const watcher = new NetworkInterfaces(this)

    this._watchers.add(watcher)
    watcher.on('close', () => {
      this._watchers.delete(watcher)
    })

    if (onchange) watcher.on('change', onchange)

    return watcher.watch()
  }

  async lookup(host, opts = {}) {
    const { family = 0 } = opts

    const req = b4a.alloc(binding.sizeof_udx_napi_lookup_t)
    const ctx = {
      req,
      resolve: null,
      reject: null
    }

    const promise = new Promise((resolve, reject) => {
      ctx.resolve = resolve
      ctx.reject = reject
    })

    binding.udx_napi_lookup(this._handle, req, host, family, ctx, onlookup)

    return promise
  }
}

function onlookup(err, host, family) {
  if (err) this.reject(err)
  else this.resolve({ host, family })
}
{
  "name": "udx-native",
  "version": "1.19.2",
  "description": "udx is reliable, multiplexed, and congestion-controlled streams over udp",
  "main": "lib/udx.js",
  "files": [
    "lib",
    "prebuilds",
    "binding.cc",
    "binding.js",
    "CMakeLists.txt"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "addon": true,
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check .",
    "test": "npm run lint && npm run test:bare && npm run test:node",
    "test:node": "node test/all.js",
    "test:bare": "bare test/all.js",
    "test:all": "brittle test/*.js test/slow/*.js",
    "test:generate": "brittle -r test/all.js test/*.js",
    "bench": "brittle test/bench/*.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/udx-native.git"
  },
  "keywords": [
    "tcp",
    "udp",
    "stream",
    "reliable"
  ],
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/udx-native/issues"
  },
  "homepage": "https://github.com/holepunchto/udx-native#readme",
  "engines": {
    "bare": ">=1.17.4"
  },
  "dependencies": {
    "b4a": "^1.5.0",
    "bare-events": "^2.2.0",
    "require-addon": "^1.1.0",
    "streamx": "^2.22.0"
  },
  "devDependencies": {
    "bare-compat-napi": "^1.3.0",
    "brittle": "^3.1.0",
    "cmake-bare": "^1.1.10",
    "cmake-fetch": "^1.0.1",
    "cmake-napi": "^1.0.5",
    "is-ci": "^3.0.1",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "tiny-byte-size": "^1.1.0"
  }
}
exports.add = add
exports.has = has
exports.remove = remove
exports.swap = swap

function add (list, item) {
  if (has(list, item)) return item
  item._index = list.length
  list.push(item)
  return item
}

function has (list, item) {
  return item._index < list.length && list[item._index] === item
}

function remove (list, item) {
  if (!has(list, item)) return null

  var last = list.pop()
  if (last !== item) {
    list[item._index] = last
    last._index = item._index
  }

  return item
}

function swap (list, a, b) {
  if (!has(list, a) || !has(list, b)) return
  var tmp = a._index
  a._index = b._index
  list[a._index] = a
  b._index = tmp
  list[b._index] = b
}
{
  "name": "unordered-set",
  "version": "2.0.1",
  "description": "A couple of functions that make it easy to maintain an unordered set as an array in an efficient way",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^6.0.4",
    "tape": "^4.4.0"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/unordered-set.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/unordered-set/issues"
  },
  "homepage": "https://github.com/mafintosh/unordered-set"
}
const b4a = require('b4a')

unslab.all = all
unslab.is = is

module.exports = unslab

function unslab (buf) {
  if (buf === null || buf.buffer.byteLength === buf.byteLength) return buf
  const copy = b4a.allocUnsafeSlow(buf.byteLength)
  copy.set(buf, 0)
  return copy
}

function is (buf) {
  return buf.buffer.byteLength !== buf.byteLength
}

function all (list) {
  let size = 0
  for (let i = 0; i < list.length; i++) {
    const buf = list[i]
    size += buf === null || buf.buffer.byteLength === buf.byteLength ? 0 : buf.byteLength
  }

  const copy = b4a.allocUnsafeSlow(size)
  const result = new Array(list.length)

  let offset = 0
  for (let i = 0; i < list.length; i++) {
    let buf = list[i]

    if (buf !== null && buf.buffer.byteLength !== buf.byteLength) {
      copy.set(buf, offset)
      buf = copy.subarray(offset, offset += buf.byteLength)
    }

    result[i] = buf
  }

  return result
}
{
  "name": "unslab",
  "version": "1.3.0",
  "description": "Unslab some slab'ed buffers",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.6.6"
  },
  "devDependencies": {
    "brittle": "^3.5.2",
    "standard": "^17.1.0"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/unslab.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/unslab/issues"
  },
  "homepage": "https://github.com/holepunchto/unslab"
}
const { runtime, platform, arch } = typeof Bare !== 'undefined'
  ? { runtime: 'bare', platform: global.Bare.platform, arch: global.Bare.arch }
  : typeof process !== 'undefined'
    ? { runtime: 'node', platform: global.process.platform, arch: global.process.arch }
    : typeof Window !== 'undefined'
      ? { runtime: 'browser', platform: 'unknown', arch: 'unknown' }
      : { runtime: 'unknown', platform: 'unknown', arch: 'unknown' }

exports.runtime = runtime
exports.platform = platform
exports.arch = arch
exports.isBare = runtime === 'bare'
exports.isBareKit = exports.isBare && typeof BareKit !== 'undefined'
exports.isPear = typeof Pear !== 'undefined'
exports.isNode = runtime === 'node'
exports.isBrowser = runtime === 'browser'
exports.isWindows = platform === 'win32'
exports.isLinux = platform === 'linux'
exports.isMac = platform === 'darwin'
exports.isIOS = platform === 'ios' || platform === 'ios-simulator'
exports.isAndroid = platform === 'android'
exports.isElectron = typeof process !== 'undefined' && !!global.process.versions?.electron
exports.isElectronRenderer = exports.isElectron && global.process.type === 'renderer'
exports.isElectronWorker = exports.isElectron && global.process.type === 'worker'
{
  "name": "which-runtime",
  "version": "1.3.2",
  "description": "Detect if you are in Bare or Node and which os etc",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {},
  "devDependencies": {
    "standard": "^17.0.0"
  },
  "scripts": {
    "test": "standard"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/which-runtime.git"
  },
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/which-runtime/issues"
  },
  "homepage": "https://github.com/holepunchto/which-runtime"
}
module.exports = class MaxCache {
  constructor ({ maxSize, maxAge, createMap, ongc }) {
    this.maxSize = maxSize
    this.maxAge = maxAge
    this.ongc = ongc || null

    this._createMap = createMap || defaultCreateMap
    this._latest = this._createMap()
    this._oldest = this._createMap()
    this._retained = this._createMap()
    this._gced = false
    this._interval = null

    if (this.maxAge > 0 && this.maxAge < Infinity) {
      const tick = Math.ceil(2 / 3 * this.maxAge)
      this._interval = setInterval(this._gcAuto.bind(this), tick)
      if (this._interval.unref) this._interval.unref()
    }
  }

  * [Symbol.iterator] () {
    for (const it of [this._latest, this._oldest, this._retained]) {
      yield * it
    }
  }

  * keys () {
    for (const it of [this._latest, this._oldest, this._retained]) {
      yield * it.keys()
    }
  }

  * values () {
    for (const it of [this._latest, this._oldest, this._retained]) {
      yield * it.values()
    }
  }

  destroy () {
    this.clear()
    clearInterval(this._interval)
    this._interval = null
  }

  clear () {
    this._gced = true
    this._latest.clear()
    this._oldest.clear()
    this._retained.clear()
  }

  set (k, v) {
    if (this._retained.has(k)) return this
    this._latest.set(k, v)
    this._oldest.delete(k) || this._retained.delete(k)
    if (this._latest.size >= this.maxSize) this._gc()
    return this
  }

  retain (k, v) {
    this._retained.set(k, v)
    this._latest.delete(k) || this._oldest.delete(k)
    return this
  }

  delete (k) {
    return this._latest.delete(k) || this._oldest.delete(k) || this._retained.delete(k)
  }

  has (k) {
    return this._latest.has(k) || this._oldest.has(k) || this._retained.has(k)
  }

  get (k) {
    if (this._latest.has(k)) {
      return this._latest.get(k)
    }

    if (this._oldest.has(k)) {
      const v = this._oldest.get(k)
      this._latest.set(k, v)
      this._oldest.delete(k)
      return v
    }

    if (this._retained.has(k)) {
      return this._retained.get(k)
    }

    return null
  }

  _gcAuto () {
    if (!this._gced) this._gc()
    this._gced = false
  }

  _gc () {
    this._gced = true
    if (this.ongc !== null && this._oldest.size > 0) this.ongc(this._oldest)
    this._oldest = this._latest
    this._latest = this._createMap()
  }
}

function defaultCreateMap () {
  return new Map()
}
{
  "name": "xache",
  "version": "1.2.1",
  "description": "Yet another auto expiring, max sizable cache",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "devDependencies": {
    "brittle": "^3.3.2",
    "standard": "^17.1.0"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/xache.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/xache/issues"
  },
  "homepage": "https://github.com/mafintosh/xache"
}
const b4a = require('b4a')

const ALPHABET = 'ybndrfg8ejkmcpqxot1uwisza345h769'
const MIN = 0x31 // 1
const MAX = 0x7a // z
const REVERSE = new Int8Array(1 + MAX - MIN)

REVERSE.fill(-1)

for (let i = 0; i < ALPHABET.length; i++) {
  const v = ALPHABET.charCodeAt(i) - MIN
  REVERSE[v] = i
}

exports.encode = encode
exports.decode = decode
exports.ALPHABET = ALPHABET

function decode (s, out) {
  let pb = 0
  let ps = 0

  const r = s.length & 7
  const q = (s.length - r) / 8

  if (!out) out = b4a.allocUnsafe(Math.ceil(s.length * 5 / 8))

  // 0 5 2 7 4 1 6 3 (+5 mod 8)
  for (let i = 0; i < q; i++) {
    const a = quintet(s, ps++)
    const b = quintet(s, ps++)
    const c = quintet(s, ps++)
    const d = quintet(s, ps++)
    const e = quintet(s, ps++)
    const f = quintet(s, ps++)
    const g = quintet(s, ps++)
    const h = quintet(s, ps++)

    out[pb++] = (a << 3) | (b >>> 2)
    out[pb++] = ((b & 0b11) << 6) | (c << 1) | (d >>> 4)
    out[pb++] = ((d & 0b1111) << 4) | (e >>> 1)
    out[pb++] = ((e & 0b1) << 7) | (f << 2) | (g >>> 3)
    out[pb++] = ((g & 0b111) << 5) | h
  }

  if (r === 0) return out.subarray(0, pb)

  const a = quintet(s, ps++)
  const b = quintet(s, ps++)

  out[pb++] = (a << 3) | (b >>> 2)

  if (r <= 2) return out.subarray(0, pb)

  const c = quintet(s, ps++)
  const d = quintet(s, ps++)

  out[pb++] = ((b & 0b11) << 6) | (c << 1) | (d >>> 4)

  if (r <= 4) return out.subarray(0, pb)

  const e = quintet(s, ps++)

  out[pb++] = ((d & 0b1111) << 4) | (e >>> 1)

  if (r <= 5) return out.subarray(0, pb)

  const f = quintet(s, ps++)
  const g = quintet(s, ps++)

  out[pb++] = ((e & 0b1) << 7) | (f << 2) | (g >>> 3)

  if (r <= 7) return out.subarray(0, pb)

  const h = quintet(s, ps++)

  out[pb++] = ((g & 0b111) << 5) | h

  return out.subarray(0, pb)
}

function encode (buf) {
  if (typeof buf === 'string') buf = b4a.from(buf)

  const max = buf.byteLength * 8

  let s = ''

  for (let p = 0; p < max; p += 5) {
    const i = p >>> 3
    const j = p & 7

    if (j <= 3) {
      s += ALPHABET[(buf[i] >>> (3 - j)) & 0b11111]
      continue
    }

    const of = j - 3
    const h = (buf[i] << of) & 0b11111
    const l = (i >= buf.byteLength ? 0 : buf[i + 1]) >>> (8 - of)

    s += ALPHABET[h | l]
  }

  return s
}

function quintet (s, i) {
  if (i > s.length) {
    return 0
  }

  const v = s.charCodeAt(i)

  if (v < MIN || v > MAX) {
    throw Error('Invalid character in base32 input: "' + s[i] + '" at position ' + i)
  }

  const bits = REVERSE[v - MIN]

  if (bits === -1) {
    throw Error('Invalid character in base32 input: "' + s[i] + '" at position ' + i)
  }

  return bits
}
{
  "name": "z32",
  "version": "1.1.0",
  "description": "Encode & decode z-base32",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.5.3"
  },
  "devDependencies": {
    "base-x": "^4.0.0",
    "base32": "0.0.7",
    "brittle": "^3.1.3",
    "nanobench": "^3.0.0",
    "rfc4648": "^1.5.2",
    "standard": "^17.0.0"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/z32.git"
  },
  "scripts": {
    "test": "standard && brittle test.js",
    "bench": "node benchmark.js"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/z32/issues"
  },
  "homepage": "https://github.com/mafintosh/z32"
}
{
  "name": "hyper-svc",
  "version": "0.1.9",
  "description": "Reusable per-app daemon library \u2014 UDS + HTTP for local RPC, Hyperswarm for peer mirroring",
  "type": "module",
  "main": "index.js",
  "scripts": {
    "test": "brittle test/*.test.js",
    "test:bare": "bare ./node_modules/.bin/brittle test/*.test.js"
  },
  "engines": {
    "node": ">=18",
    "bare": ">=1.0"
  },
  "imports": {
    "#node:fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "#node:fs/promises": {
      "bare": "bare-fs/promises",
      "default": "fs/promises"
    },
    "#node:path": {
      "bare": "bare-path",
      "default": "path"
    },
    "#node:os": {
      "bare": "bare-os",
      "default": "os"
    },
    "#node:url": {
      "bare": "bare-url",
      "default": "url"
    },
    "#node:events": {
      "bare": "bare-events",
      "default": "events"
    },
    "#node:stream": {
      "bare": "bare-stream",
      "default": "stream"
    },
    "#node:net": {
      "bare": "bare-net",
      "default": "net"
    },
    "#node:http": {
      "bare": "bare-http1",
      "default": "http"
    },
    "#node:process": {
      "bare": "bare-process",
      "default": "process"
    }
  },
  "dependencies": {
    "b4a": "^1.6.0",
    "bare-events": "^2.0.0",
    "bare-fs": "^4.7.2",
    "bare-http1": "^4.0.0",
    "bare-net": "^1.0.0",
    "bare-os": "^3.0.0",
    "bare-path": "^3.0.0",
    "bare-process": "^4.0.0",
    "bare-stream": "^2.0.0",
    "bare-url": "^2.0.0",
    "compact-encoding": "^3.2.0",
    "hypercore-crypto": "^3.0.0",
    "hyperswarm": "^4.0.0",
    "protomux": "^3.0.0",
    "ready-resource": "^1.0.0",
    "bare-abstract-socket": "^1.0.0"
  },
  "devDependencies": {
    "@hyperswarm/testnet": "^3.0.0",
    "brittle": "^3.0.0",
    "corestore": "^7.0.0",
    "hyper-rooms": "file:../hyper-rooms"
  },
  "overrides": {}
}
const codecs = require('codecs')
const { Readable } = require('streamx')
const mutexify = require('mutexify/promise')
const b4a = require('b4a')
const safetyCatch = require('safety-catch')
const ReadyResource = require('ready-resource')
const debounce = require('debounceify')
const Rache = require('rache')
const rrp = require('resolve-reject-promise')

const { all: unslabAll } = require('unslab')

const RangeIterator = require('./iterators/range')
const HistoryIterator = require('./iterators/history')
const DiffIterator = require('./iterators/diff')
const LocalBlockIterator = require('./iterators/local')
const Extension = require('./lib/extension')
const { YoloIndex, Node, Header } = require('./lib/messages')
const { BLOCK_NOT_AVAILABLE, DECODING_ERROR } = require('hypercore-errors')

const T = 5
const MIN_KEYS = T - 1
const MAX_CHILDREN = MIN_KEYS * 2 + 1

const SEP = b4a.alloc(1)
const EMPTY = b4a.alloc(0)

class Key {
  constructor(seq, value) {
    this.seq = seq
    this.value = value
  }
}

class Child {
  constructor(seq, offset, value) {
    this.seq = seq
    this.offset = offset
    this.value = value
  }
}

class Cache {
  constructor(rache) {
    this.keys = rache
    this.length = 0
  }

  get(seq) {
    return this.keys.get(seq) || null
  }

  set(seq, key) {
    this.keys.set(seq, key)
    if (seq >= this.length) this.length = seq + 1
  }

  gc(length) {
    // if we need to "work" more than 128 ticks, just bust the cache...
    if (this.length - length > 128) {
      this.keys.clear()
    } else {
      for (let i = length; i < this.length; i++) {
        this.keys.delete(i)
      }
    }

    this.length = length
  }

  clear() {
    this.keys.clear()
  }
}

class Pointers {
  constructor(decoded) {
    this.levels = decoded.levels.map((l) => {
      const children = []
      const keys = []

      for (let i = 0; i < l.keys.length; i++) {
        keys.push(new Key(l.keys[i], null))
      }

      for (let i = 0; i < l.children.length; i += 2) {
        children.push(new Child(l.children[i], l.children[i + 1], null))
      }

      return { keys, children }
    })
  }

  get(i) {
    return this.levels[i]
  }

  hasKey(seq) {
    for (const lvl of this.levels) {
      for (const key of lvl.keys) {
        if (key.seq === seq) return true
      }
    }
    return false
  }
}

function inflate(entry) {
  if (entry.inflated === null) {
    entry.inflated = YoloIndex.decode(entry.index)
    entry.index = null
  }
  return new Pointers(entry.inflated)
}

function deflate(index) {
  const levels = index.map((l) => {
    const keys = []
    const children = []

    for (let i = 0; i < l.value.keys.length; i++) {
      keys.push(l.value.keys[i].seq)
    }

    for (let i = 0; i < l.value.children.length; i++) {
      children.push(l.value.children[i].seq, l.value.children[i].offset)
    }

    return { keys, children }
  })

  return YoloIndex.encode({ levels })
}

class TreeNode {
  constructor(block, keys, children, offset) {
    this.block = block
    this.offset = offset
    this.keys = keys
    this.children = children
    this.changed = false

    this.preload()
  }

  preload() {
    if (this.block === null) return

    const core = getBackingCore(this.block.tree.core)
    if (!core) return

    const bitfield = core.core.bitfield
    const blocks = []

    for (let i = 0; i < this.keys.length; i++) {
      const k = this.keys[i]
      if (k.value) continue
      if (k.seq >= core.signedLength || (bitfield && bitfield.get(k.seq))) continue
      blocks.push(k.seq)
    }
    for (let i = 0; i < this.children.length; i++) {
      const c = this.children[i]
      if (c.value) continue
      if (c.seq >= core.signedLength || (bitfield && bitfield.get(c.seq))) continue
      blocks.push(c.seq)
    }

    if (blocks.length) core.download({ blocks })
  }

  async insertKey(key, value, child, node, encoding, cas) {
    let s = 0
    let e = this.keys.length
    let c

    while (s < e) {
      const mid = (s + e) >> 1
      c = b4a.compare(key.value, await this.getKey(mid))

      if (c === 0) {
        if (cas) {
          const prev = await this.getKeyNode(mid)
          if (!(await cas(prev.final(encoding), node))) return true
        }
        if (!this.block.tree.tree.alwaysDuplicate) {
          const prev = await this.getKeyNode(mid)
          if (sameValue(prev.value, value)) return true
        }
        this.changed = true
        this.keys[mid] = key
        return true
      }

      if (c < 0) e = mid
      else s = mid + 1
    }

    const i = c < 0 ? e : s
    this.keys.splice(i, 0, key)
    if (child) this.children.splice(i + 1, 0, new Child(0, 0, child))
    this.changed = true

    return this.keys.length < MAX_CHILDREN
  }

  removeKey(index) {
    this.keys.splice(index, 1)
    if (this.children.length) {
      this.children[index + 1].seq = 0 // mark as freed
      this.children.splice(index + 1, 1)
    }
    this.changed = true
  }

  async siblings(parent) {
    for (let i = 0; i < parent.children.length; i++) {
      if (parent.children[i].value === this) {
        const [left, right] = await Promise.all([
          i ? parent.getChildNode(i - 1) : null,
          i < parent.children.length - 1 ? parent.getChildNode(i + 1) : null
        ])
        return { left, index: i, right }
      }
    }

    throw new Error('Bad parent')
  }

  merge(node, median) {
    this.changed = true
    this.keys.push(median)
    for (let i = 0; i < node.keys.length; i++) this.keys.push(node.keys[i])
    for (let i = 0; i < node.children.length; i++) this.children.push(node.children[i])
  }

  async split() {
    const len = this.keys.length >> 1
    const right = TreeNode.create(this.block)

    while (right.keys.length < len) right.keys.push(this.keys.pop())
    right.keys.reverse()

    await this.getKey(this.keys.length - 1) // make sure the median is loaded
    const median = this.keys.pop()

    if (this.children.length) {
      while (right.children.length < len + 1) right.children.push(this.children.pop())
      right.children.reverse()
    }

    this.changed = true

    return {
      left: this,
      median,
      right
    }
  }

  getKeyNode(index) {
    return this.block.tree.getBlock(this.keys[index].seq)
  }

  async getChildNode(index) {
    const child = this.children[index]
    if (child.value) return child.value
    const block =
      child.seq === this.block.seq ? this.block : await this.block.tree.getBlock(child.seq)
    return (child.value = block.getTreeNode(child.offset))
  }

  setKey(index, key) {
    this.keys[index] = key
    this.changed = true
  }

  async getKey(index) {
    const key = this.keys[index]
    if (key.value) return key.value
    const k = key.seq === this.block.seq ? this.block.key : await this.block.tree.getKey(key.seq)
    return (key.value = k)
  }

  indexChanges(index, seq) {
    const offset = index.push(null) - 1
    this.changed = false

    for (const child of this.children) {
      if (!child.value || !child.value.changed) continue
      child.seq = seq
      child.offset = child.value.indexChanges(index, seq)
      index[child.offset] = child
    }

    return offset
  }

  updateChildren(seq, block) {
    for (const child of this.children) {
      if (!child.value || child.seq !== seq) continue
      child.value.block = block
      child.value.updateChildren(seq, block)
    }
  }

  static create(block) {
    const node = new TreeNode(block, [], [], 0)
    node.changed = true
    return node
  }
}

class BlockEntry {
  constructor(seq, tree, entry) {
    this.seq = seq
    this.tree = tree
    this.index = null
    this.entry = entry
    this.key = entry.key
    this.value = entry.value
  }

  isTarget(key) {
    return b4a.equals(this.key, key)
  }

  inflate() {
    if (this.index === null) {
      this.index = inflate(this.entry)
    }
  }

  isDeletion() {
    if (this.value !== null) return false

    if (this.index === null) {
      this.index = inflate(this.entry)
    }

    return !this.index.hasKey(this.seq)
  }

  final(encoding) {
    return {
      seq: this.seq,
      key: encoding.key ? encoding.key.decode(this.key) : this.key,
      value: this.value && (encoding.value ? encoding.value.decode(this.value) : this.value)
    }
  }

  getTreeNode(offset) {
    if (this.index === null) {
      this.index = inflate(this.entry)
    }
    const entry = this.index.get(offset)
    return new TreeNode(this, entry.keys, entry.children, offset)
  }
}

class CacheLock {
  constructor() {
    this.map = new Map()
  }

  enter(seq) {
    const pending = this.map.get(seq)

    if (!pending) {
      this.map.set(seq, [])
      return Promise.resolve()
    }

    const { resolve, promise } = rrp()
    pending.push(resolve)
    return promise
  }

  exit(seq) {
    const pending = this.map.get(seq)
    if (!pending.length) {
      this.map.delete(seq)
      return
    }

    pending.pop()()
  }
}

class BatchEntry extends BlockEntry {
  constructor(seq, tree, key, value, index) {
    super(seq, tree, { key, value, index: null, inflated: null })
    this.pendingIndex = index
  }

  isTarget(key) {
    return false
  }

  getTreeNode(offset) {
    return this.pendingIndex[offset].value
  }
}

class Hyperbee extends ReadyResource {
  constructor(core, opts = {}) {
    super()
    // this.feed is now deprecated, and will be this.core going forward
    this.feed = core
    this.core = core

    this.keyEncoding = opts.keyEncoding ? codecs(opts.keyEncoding) : null
    this.valueEncoding = opts.valueEncoding ? codecs(opts.valueEncoding) : null
    this.extension = opts.extension !== false ? getExtension(this, opts) : null
    this.metadata = opts.metadata || null
    this.lock = opts.lock || mutexify()
    this.sep = opts.sep || SEP
    this.readonly = !!opts.readonly
    this.prefix = opts.prefix || null

    // In a future version, this should be false by default
    this.alwaysDuplicate = opts.alwaysDuplicate !== false

    this._unprefixedKeyEncoding = this.keyEncoding
    this._sub = !!this.prefix
    this._checkout = opts.checkout || 0
    this._view = !!opts._view

    this._onappendBound = this._view ? null : this._onappend.bind(this)
    this._ontruncateBound = this._view ? null : this._ontruncate.bind(this)
    this._watchers = this._onappendBound ? [] : null
    this._entryWatchers = this._onappendBound ? [] : null
    this._sessions = opts.sessions !== false

    this._keyCache = null
    this._nodeCache = null
    this._cacheLock = new CacheLock()

    this._batches = []

    if (this._watchers) {
      this.core.on('append', this._onappendBound)
      this.core.on('truncate', this._ontruncateBound)
    }

    if (this.prefix && opts._sub) {
      this.keyEncoding = prefixEncoding(this.prefix, this.keyEncoding)
    }

    this.ready().catch(safetyCatch)
  }

  async _open() {
    if (this.core.opened === false) await this.core.ready()
    // bump the internal ranges since the nodes are small
    if (this._watchers && this.core.replicator.setInflightRange) {
      this.core.replicator.setInflightRange(256, 512)
    }

    // snapshot
    if (this._checkout === -1) this._checkout = Math.max(1, this.core.length)

    const baseCache = Rache.from(this.core.globalCache)
    this._keyCache = new Cache(baseCache)
    this._nodeCache = new Cache(Rache.from(baseCache))
  }

  get version() {
    return Math.max(1, this._checkout || this.core.length)
  }

  get id() {
    return this.core.id
  }

  get key() {
    return this.core.key
  }

  get discoveryKey() {
    return this.core.discoveryKey
  }

  get writable() {
    return this.core.writable
  }

  get readable() {
    return this.core.readable
  }

  replicate(isInitiator, opts) {
    return this.core.replicate(isInitiator, opts)
  }

  update(opts) {
    return this.core.update(opts)
  }

  peek(range, opts) {
    return iteratorPeek(this.createRangeIterator(range, { ...opts, limit: 1 }))
  }

  createRangeIterator(range, opts = {}) {
    // backwards compat range arg
    opts = opts ? { ...opts, ...range } : range

    const extension = opts.extension === false && opts.limit !== 0 ? null : this.extension
    const keyEncoding = opts.keyEncoding ? codecs(opts.keyEncoding) : this.keyEncoding

    if (extension) {
      const { onseq, onwait } = opts
      let version = 0
      let next = 0

      opts = encRange(keyEncoding, {
        ...opts,
        sub: this._sub,
        onseq(seq) {
          if (!version) version = seq + 1
          if (next) next--
          if (onseq) onseq(seq)
        },
        onwait(seq) {
          if (!next) {
            next = Extension.BATCH_SIZE
            extension.iterator(ite.snapshot(version))
          }
          if (onwait) onwait(seq)
        }
      })
    } else {
      opts = encRange(keyEncoding, { ...opts, sub: this._sub })
    }

    const ite = new RangeIterator(
      new Batch(this, this._makeSnapshot(), null, false, opts),
      null,
      opts
    )
    return ite
  }

  createReadStream(range, opts) {
    const signal = (opts && opts.signal) || null
    return iteratorToStream(this.createRangeIterator(range, opts), signal)
  }

  createHistoryStream(opts) {
    const session = opts && opts.live ? this.core.session() : this._makeSnapshot()
    const signal = (opts && opts.signal) || null
    return iteratorToStream(
      new HistoryIterator(new Batch(this, session, null, false, opts), opts),
      signal
    )
  }

  createDiffStream(right, range, opts) {
    if (typeof right === 'number') right = this.checkout(Math.max(1, right), { reuseSession: true })

    // backwards compat range arg
    opts = opts ? { ...opts, ...range } : range

    const signal = (opts && opts.signal) || null

    const keyEncoding = opts && opts.keyEncoding ? codecs(opts.keyEncoding) : this.keyEncoding
    if (keyEncoding) opts = encRange(keyEncoding, { ...opts, sub: this._sub })

    let done
    let closing
    let ite

    const left = this

    const rs = new Readable({
      signal,
      eagerOpen: true,
      async open(cb) {
        try {
          if (right.opened === false) await right.ready()
          if (left.opened === false) await left.ready()
        } catch (err) {
          cb(err)
          return
        }

        if (closing) {
          cb(null)
          return
        }

        if (left.core.closing || right.core.closing) {
          cb(new Error('Bee closed'))
          return
        }

        const snapshot = right.version > left.version ? right._makeSnapshot() : left._makeSnapshot()

        done = cb
        ite = new DiffIterator(
          new Batch(left, snapshot, null, false, opts),
          new Batch(right, snapshot, null, false, opts),
          opts
        )
        ite.open().then(fin, fin)
      },
      read(cb) {
        done = cb
        ite.next().then(push, fin)
      },
      predestroy() {
        if (!ite) {
          closing = Promise.resolve()
        } else {
          closing = ite.close()
          closing.catch(noop)
        }
      },
      destroy(cb) {
        done = cb
        if (!closing) closing = ite.close()
        closing.then(fin, fin)
      }
    })

    return rs

    function fin(err) {
      done(err)
    }

    function push(val) {
      rs.push(val)
      done(null)
    }
  }

  get(key, opts) {
    const b = new Batch(this, this._makeSnapshot(), null, true, opts)
    return b.get(key)
  }

  getBySeq(seq, opts) {
    const b = new Batch(this, this._makeSnapshot(), null, true, opts)
    return b.getBySeq(seq)
  }

  put(key, value, opts) {
    const b = new Batch(this, this.core, null, true, opts)
    return b.put(key, value, opts)
  }

  batch(opts) {
    return new Batch(this, this.core, mutexify(), true, opts)
  }

  del(key, opts) {
    const b = new Batch(this, this.core, null, true, opts)
    return b.del(key, opts)
  }

  watch(range, opts) {
    if (!this._watchers) throw new Error('Can only watch the main bee instance')
    return new Watcher(this, range, opts)
  }

  async getAndWatch(key, opts) {
    if (!this._watchers) throw new Error('Can only watch the main bee instance')

    const watcher = new EntryWatcher(this, key, opts)
    await watcher._debouncedUpdate()

    if (this.closing) {
      await watcher.close()
      throw new Error('Bee closed')
    }

    return watcher
  }

  _onappend() {
    for (const watcher of this._watchers) {
      watcher._onappend()
    }

    for (const watcher of this._entryWatchers) {
      watcher._onappend()
    }
  }

  _ontruncate(length) {
    for (const watcher of this._watchers) {
      watcher._ontruncate()
    }

    for (const watcher of this._entryWatchers) {
      watcher._ontruncate()
    }

    this._nodeCache.gc(length)
    this._keyCache.gc(length)
  }

  _makeSnapshot() {
    if (this._sessions === false) return this.core
    // TODO: better if we could encapsulate this in hypercore in the future
    return this._checkout <= this.core.length || this._checkout <= 1
      ? this.core.snapshot()
      : this.core.session({ snapshot: false })
  }

  async clearUnlinked(options = {}) {
    await this.ready()

    const { gte = 0, lt = this.version - 1, batchSize = 4096, wait = true } = options
    const checkout = this.version

    let prev = this.batch({ wait: false, checkout: gte })
    let b = this.batch({ wait, checkout })

    const iteBatch = this.batch({ wait: false, checkout })
    const ite = new LocalBlockIterator(iteBatch, { gte, lt })
    await ite.open()

    let ticks = 0

    while (true) {
      const data = await ite.next()
      if (!data) break

      if (!(await isLinked(b, data))) {
        if (b.core.closing || this.core.closing || this.closing) break
        await this.core.clear(data.seq)
      }

      const prevNode = await prev.get(data.key, { finalize: false }).catch(toNull)

      if (prevNode && !(await isLinked(b, prevNode))) {
        if (b.core.closing || this.core.closing || this.closing) break
        await this.core.clear(prevNode.seq)
      }

      if (ticks++ >= batchSize) {
        ticks = 0
        await prev.close()
        await b.close()

        prev = this.batch({ wait: false, checkout: gte })
        b = this.batch({ wait, checkout })
      }
    }

    if (b.core.closing || this.core.closing || this.closing) throw new Error('Core is closed')

    await b.close()
    await prev.close()
    await ite.close()
    await iteBatch.close()

    return lt
  }

  checkout(version, opts = {}) {
    if (version === 0) version = 1

    // same as above, just checkout isn't set yet...
    const snap =
      opts.reuseSession || this._sessions === false
        ? this.core
        : version <= this.core.length || version <= 1
          ? this.core.snapshot()
          : this.core.session({ snapshot: false })

    return new Hyperbee(snap, {
      _view: true,
      _sub: false,
      prefix: this.prefix,
      sep: this.sep,
      lock: this.lock,
      checkout: version,
      keyEncoding: opts.keyEncoding || this.keyEncoding,
      valueEncoding: opts.valueEncoding || this.valueEncoding,
      extension: this.extension !== null ? this.extension : false
    })
  }

  snapshot(opts) {
    return this.checkout(
      this.core.opened === false || this._checkout <= 0 ? -1 : Math.max(1, this.version),
      opts
    )
  }

  sub(prefix, opts = {}) {
    let sep = opts.sep || this.sep
    if (!b4a.isBuffer(sep)) sep = b4a.from(sep)

    prefix = b4a.concat([this.prefix || EMPTY, b4a.from(prefix), sep])

    const valueEncoding = codecs(opts.valueEncoding || this.valueEncoding)
    const keyEncoding = codecs(opts.keyEncoding || this._unprefixedKeyEncoding)

    return new Hyperbee(this.core, {
      _view: true,
      _sub: true,
      prefix,
      sep: this.sep,
      lock: this.lock,
      checkout: this._checkout,
      valueEncoding,
      keyEncoding,
      extension: this.extension !== null ? this.extension : false,
      metadata: this.metadata
    })
  }

  async getHeader(opts) {
    const blk = await this.core.get(0, opts)
    try {
      return blk && Header.decode(blk)
    } catch {
      throw DECODING_ERROR()
    }
  }

  async _close() {
    if (!this._view) {
      if (this._keyCache) this._keyCache.clear()
      if (this._nodeCache) this._nodeCache.clear()
    }

    if (this._watchers) {
      this.core.off('append', this._onappendBound)
      this.core.off('truncate', this._ontruncateBound)

      while (this._watchers.length) {
        await this._watchers[this._watchers.length - 1].close()
      }
    }

    if (this._entryWatchers) {
      while (this._entryWatchers.length) {
        await this._entryWatchers[this._entryWatchers.length - 1].close()
      }
    }

    while (this._batches.length) {
      await this._batches[this._batches.length - 1].close()
    }

    return this.core.close()
  }

  static async isHyperbee(core, opts) {
    await core.ready()

    const blk0 = await core.get(0, opts)
    if (blk0 === null) throw BLOCK_NOT_AVAILABLE()

    try {
      return Header.decode(blk0).protocol === 'hyperbee'
    } catch (err) {
      // undecodable
      return false
    }
  }
}

class Batch {
  constructor(tree, core, batchLock, cache, options = {}) {
    this.tree = tree
    // this.feed is now deprecated, and will be this.core going forward
    this.feed = core
    this.core = core
    this.index = tree._batches.push(this) - 1
    this.blocks = cache ? new Map() : null
    this.autoFlush = !batchLock
    this.maxBlocksCached = options.maxBlocksCached || 128
    this.rootSeq = 0
    this.root = null
    this.length = 0
    this.checkout = options.checkout === undefined ? -1 : options.checkout
    this.options = options
    this.locked = null
    this.batchLock = batchLock
    this.onseq = this.options.onseq || noop
    this.appending = null
    this.isSnapshot = this.core !== this.tree.core
    this.shouldUpdate = this.options.update !== false
    this.updating = null
    this.encoding = {
      key: options.keyEncoding ? codecs(options.keyEncoding) : tree.keyEncoding,
      value: options.valueEncoding ? codecs(options.valueEncoding) : tree.valueEncoding
    }
  }

  async ready() {
    if (this.core.opened === false) await this.core.ready()
    if (this.tree.opened === false) await this.tree.ready()
  }

  async lock() {
    if (this.tree.readonly) throw new Error('Hyperbee is marked as read-only')
    if (this.locked === null) this.locked = await this.tree.lock()
  }

  get version() {
    if (this.checkout !== -1) return Math.max(1, this.checkout)
    return Math.max(1, this.tree._checkout || this.core.length + this.length)
  }

  async getRoot(ensureHeader) {
    await this.ready()
    if (ensureHeader) {
      if (this.core.length === 0 && this.core.writable && !this.tree.readonly) {
        await this.core.append(
          Header.encode({
            protocol: 'hyperbee',
            metadata: this.tree.metadata
          })
        )
      }
    }
    if (this.tree._checkout === 0 && this.checkout === -1 && this.shouldUpdate) {
      if (this.updating === null) this.updating = this.core.update()
      await this.updating
    }
    if (this.version < 2) return null
    return (await this.getBlock(this.version - 1)).getTreeNode(0)
  }

  async getKey(seq) {
    await this.tree._cacheLock.enter(seq)

    try {
      const k = this.core.fork === this.tree.core.fork ? this.tree._keyCache.get(seq) : null
      if (k !== null) return k
      const key = (await this._getBlock(seq)).key
      if (this.core.fork === this.tree.core.fork) this.tree._keyCache.set(seq, key)
      return key
    } finally {
      this.tree._cacheLock.exit(seq)
    }
  }

  async _getNode(seq) {
    const cached =
      this.tree._nodeCache !== null && this.core.fork === this.tree.core.fork
        ? this.tree._nodeCache.get(seq)
        : null
    if (cached !== null) return cached
    const entry = await this.core.get(seq, {
      ...this.options,
      valueEncoding: Node
    })
    if (entry === null) throw BLOCK_NOT_AVAILABLE()
    const wrap = copyEntry(entry)
    if (this.core.fork === this.tree.core.fork && this.tree._nodeCache !== null) {
      this.tree._nodeCache.set(seq, wrap)
    }
    return wrap
  }

  async getBlock(seq) {
    if (this.rootSeq === 0) this.rootSeq = seq
    await this.tree._cacheLock.enter(seq)

    try {
      return await this._getBlock(seq)
    } finally {
      this.tree._cacheLock.exit(seq)
    }
  }

  async _getBlock(seq) {
    let b = this.blocks && this.blocks.get(seq)
    if (b) return b
    this.onseq(seq)
    const entry = await this._getNode(seq)
    b = this.blocks && this.blocks.get(seq)
    if (b) return b
    b = new BlockEntry(seq, this, entry)
    if (this.blocks && this.blocks.size - this.length < this.maxBlocksCached) {
      this.blocks.set(seq, b)
    }
    return b
  }

  _onwait(key) {
    this.options.onwait = null
    this.tree.extension.get(this.rootSeq + 1, key)
  }

  _getEncoding(opts) {
    if (!opts) return this.encoding
    return {
      key: opts.keyEncoding ? codecs(opts.keyEncoding) : this.encoding.key,
      value: opts.valueEncoding ? codecs(opts.valueEncoding) : this.encoding.value
    }
  }

  peek(range, opts) {
    return iteratorPeek(this.createRangeIterator(range, { ...opts, limit: 1 }))
  }

  createRangeIterator(range, opts = {}) {
    // backwards compat range arg
    opts = opts ? { ...opts, ...range } : range

    const encoding = this._getEncoding(opts)
    return new RangeIterator(
      this,
      encoding,
      encRange(encoding.key, { ...opts, sub: this.tree._sub })
    )
  }

  createReadStream(range, opts) {
    const signal = (opts && opts.signal) || null
    return iteratorToStream(this.createRangeIterator(range, opts), signal)
  }

  async getBySeq(seq, opts) {
    const encoding = this._getEncoding(opts)

    try {
      const block = (await this.getBlock(seq)).final(encoding)
      return { key: block.key, value: block.value }
    } finally {
      await this._closeSnapshot()
    }
  }

  async get(key, opts) {
    const encoding = this._getEncoding(opts)
    const finalize = opts ? opts.finalize !== false : true

    try {
      return await this._get(key, encoding, finalize)
    } finally {
      await this._closeSnapshot()
    }
  }

  async _get(key, encoding, finalize) {
    key = enc(encoding.key, key)

    if (this.tree.extension !== null && this.options.extension !== false) {
      this.options.onwait = this._onwait.bind(this, key)
    }

    let node = await this.getRoot(false)
    if (!node) return null

    while (true) {
      if (node.block.isTarget(key)) {
        return node.block.isDeletion() ? null : finalize ? node.block.final(encoding) : node.block
      }

      let s = 0
      let e = node.keys.length
      let c

      while (s < e) {
        const mid = (s + e) >> 1

        c = b4a.compare(key, await node.getKey(mid))

        if (c === 0) {
          const block = await this.getBlock(node.keys[mid].seq)
          return finalize ? block.final(encoding) : block
        }

        if (c < 0) e = mid
        else s = mid + 1
      }

      if (!node.children.length) return null

      const i = c < 0 ? e : s
      node = await node.getChildNode(i)
    }
  }

  async links(key, seq) {
    let node = await this.getRoot(false)
    if (!node) return false

    if (node.block.seq === seq) return true

    while (true) {
      if (node.block.isTarget(key)) return false

      let s = 0
      let e = node.keys.length
      let c

      while (s < e) {
        const mid = (s + e) >> 1

        if (node.keys[mid].seq === seq) return true
        c = b4a.compare(key, await node.getKey(mid))

        if (c === 0) return false

        if (c < 0) e = mid
        else s = mid + 1
      }

      if (!node.children.length) return false

      const i = c < 0 ? e : s
      node = await node.getChildNode(i)
      if (node.block.seq === seq) return true
    }
  }

  async put(key, value, opts) {
    const release = this.batchLock ? await this.batchLock() : null

    const cas = (opts && opts.cas) || null
    const encoding = this._getEncoding(opts)

    if (!this.locked) await this.lock()
    if (!release) return this._put(key, value, encoding, cas)

    try {
      return await this._put(key, value, encoding, cas)
    } finally {
      release()
    }
  }

  async _put(key, value, encoding, cas) {
    const newNode = {
      seq: 0,
      key,
      value
    }
    key = enc(encoding.key, key)
    value = enc(encoding.value, value)

    const stack = []

    let root
    let node = (root = await this.getRoot(true))
    if (!node) node = root = TreeNode.create(null)

    const seq = (newNode.seq = this.core.length + this.length)
    const target = new Key(seq, key)

    while (node.children.length) {
      stack.push(node)
      node.changed = true // changed, but compressible

      let s = 0
      let e = node.keys.length
      let c

      while (s < e) {
        const mid = (s + e) >> 1
        c = b4a.compare(target.value, await node.getKey(mid))

        if (c === 0) {
          if (cas) {
            const prev = await node.getKeyNode(mid)
            if (!(await cas(prev.final(encoding), newNode))) return this._unlockMaybe()
          }
          if (!this.tree.alwaysDuplicate) {
            const prev = await node.getKeyNode(mid)
            if (sameValue(prev.value, value)) return this._unlockMaybe()
          }
          node.setKey(mid, target)
          return this._append(root, seq, key, value)
        }

        if (c < 0) e = mid
        else s = mid + 1
      }

      const i = c < 0 ? e : s
      node = await node.getChildNode(i)
    }

    let needsSplit = !(await node.insertKey(target, value, null, newNode, encoding, cas))
    if (!node.changed) return this._unlockMaybe()

    while (needsSplit) {
      const parent = stack.pop()
      const { median, right } = await node.split()

      if (parent) {
        needsSplit = !(await parent.insertKey(median, value, right, null, encoding, null))
        node = parent
      } else {
        root = TreeNode.create(node.block)
        root.changed = true
        root.keys.push(median)
        root.children.push(new Child(0, 0, node), new Child(0, 0, right))
        needsSplit = false
      }
    }

    return this._append(root, seq, key, value)
  }

  async del(key, opts) {
    const release = this.batchLock ? await this.batchLock() : null
    const cas = (opts && opts.cas) || null
    const encoding = this._getEncoding(opts)

    if (!this.locked) await this.lock()
    if (!release) return this._del(key, encoding, cas)

    try {
      return await this._del(key, encoding, cas)
    } finally {
      release()
    }
  }

  async _del(key, encoding, cas) {
    const delNode = {
      seq: 0,
      key,
      value: null
    }

    key = enc(encoding.key, key)

    const stack = []

    let node = await this.getRoot(true)
    if (!node) return this._unlockMaybe()

    const seq = (delNode.seq = this.core.length + this.length)

    while (true) {
      stack.push(node)

      let s = 0
      let e = node.keys.length
      let c

      while (s < e) {
        const mid = (s + e) >> 1
        c = b4a.compare(key, await node.getKey(mid))

        if (c === 0) {
          if (cas) {
            const prev = await node.getKeyNode(mid)
            if (!(await cas(prev.final(encoding), delNode))) return this._unlockMaybe()
          }
          if (node.children.length) await setKeyToNearestLeaf(node, mid, stack)
          else node.removeKey(mid)
          // we mark these as changed late, so we don't rewrite them if it is a 404
          for (const node of stack) node.changed = true
          return this._append(await rebalance(stack), seq, key, null)
        }

        if (c < 0) e = mid
        else s = mid + 1
      }

      if (!node.children.length) return this._unlockMaybe()

      const i = c < 0 ? e : s
      node = await node.getChildNode(i)
    }
  }

  async _closeSnapshot() {
    if (this.isSnapshot) {
      await this.core.close()
      this._finalize()
    }
  }

  async close() {
    if (this.isSnapshot) return this._closeSnapshot()

    this.root = null
    if (this.blocks) this.blocks.clear()
    this.length = 0
    this._unlock()
  }

  destroy() {
    // compat, remove later
    this.close().catch(noop)
  }

  toBlocks() {
    if (this.appending) return this.appending

    const batch = new Array(this.length)

    for (let i = 0; i < this.length; i++) {
      const seq = this.core.length + i
      const { pendingIndex, key, value } = this.blocks.get(seq)

      if (i < this.length - 1) {
        pendingIndex[0] = null
        let j = 0

        while (j < pendingIndex.length) {
          const idx = pendingIndex[j]
          if (idx !== null && idx.seq === seq) {
            idx.offset = j++
            continue
          }
          if (j === pendingIndex.length - 1) pendingIndex.pop()
          else pendingIndex[j] = pendingIndex.pop()
        }
      }

      batch[i] = Node.encode({
        key,
        value,
        index: deflate(pendingIndex)
      })
    }

    this.appending = batch
    return batch
  }

  flush() {
    if (!this.length) return this.close()

    const batch = this.toBlocks()

    this.root = null
    this.blocks.clear()
    this.length = 0

    return this._appendBatch(batch)
  }

  _unlockMaybe() {
    if (this.autoFlush) this._unlock()
  }

  _unlock() {
    const locked = this.locked
    this.locked = null
    if (locked !== null) locked()
    this._finalize()
  }

  _finalize() {
    // technically finalize can be called more than once, so here we just check if we already have been removed
    if (this.index >= this.tree._batches.length || this.tree._batches[this.index] !== this) return
    const top = this.tree._batches.pop()
    if (top === this) return
    top.index = this.index
    this.tree._batches[top.index] = top
  }

  _append(root, seq, key, value) {
    const index = []
    root.indexChanges(index, seq)
    index[0] = new Child(seq, 0, root)

    if (!this.autoFlush) {
      const block = new BatchEntry(seq, this, key, value, index)
      root.block = block
      this.root = root
      this.length++
      this.blocks.set(seq, block)

      root.updateChildren(seq, block)
      return
    }

    return this._appendBatch(
      Node.encode({
        key,
        value,
        index: deflate(index)
      })
    )
  }

  async _appendBatch(raw) {
    try {
      await this.core.append(raw)
    } finally {
      this._unlock()
    }
  }
}

class EntryWatcher extends ReadyResource {
  constructor(bee, key, opts = {}) {
    super()

    this.keyEncoding = opts.keyEncoding || bee.keyEncoding
    this.valueEncoding = opts.valueEncoding || bee.valueEncoding

    this.index = bee._entryWatchers.push(this) - 1
    this.bee = bee

    this.key = key
    this.node = null

    this._forceUpdate = false
    this._debouncedUpdate = debounce(this._processUpdate.bind(this))
  }

  _close() {
    const top = this.bee._entryWatchers.pop()
    if (top !== this) {
      top.index = this.index
      this.bee._entryWatchers[top.index] = top
    }
  }

  _onappend() {
    this._debouncedUpdate()
  }

  _ontruncate() {
    this._forceUpdate = true
    this._debouncedUpdate()
  }

  async _processUpdate() {
    const force = this._forceUpdate
    this._forceUpdate = false

    let newNode
    try {
      newNode = await this.bee.get(this.key, {
        keyEncoding: this.keyEncoding,
        valueEncoding: this.valueEncoding
      })
    } catch (e) {
      if (e.code === 'SNAPSHOT_NOT_AVAILABLE') {
        // There was a truncate event before the get resolved
        // So this handler will run again anyway
        return
      } else if (this.bee.closing) {
        this.close().catch(safetyCatch)
        return
      }
      this.emit('error', e)
      return
    }

    if (force || newNode?.seq !== this.node?.seq) {
      this.node = newNode
      this.emit('update')
    }
  }
}

class Watcher extends ReadyResource {
  constructor(bee, range, opts = {}) {
    super()

    this.keyEncoding = opts.keyEncoding || bee.keyEncoding
    this.valueEncoding = opts.valueEncoding || bee.valueEncoding
    this.index = bee._watchers.push(this) - 1
    this.bee = bee
    this.core = bee.core

    this.latestDiff = 0
    this.range = range
    this.map = opts.map || defaultWatchMap

    this.current = null
    this.previous = null
    this.currentMapped = null
    this.previousMapped = null
    this.stream = null

    this._lock = mutexify()
    this._flowing = false
    this._resolveOnChange = null
    this._differ = opts.differ || defaultDiffer
    this._eager = !!opts.eager
    this._onchange = opts.onchange || null

    this.on('newListener', autoFlowOnUpdate)

    this.ready().catch(safetyCatch)
  }

  async _consume() {
    if (this._flowing) return
    try {
      for await (const _ of this) {
      } // eslint-disable-line
    } catch {}
  }

  async _open() {
    await this.bee.ready()

    const opts = {
      keyEncoding: this.keyEncoding,
      valueEncoding: this.valueEncoding
    }

    // Point from which to start watching
    this.current = this._eager ? this.bee.checkout(1, opts) : this.bee.snapshot(opts)
    await this.current.ready()

    if (this._onchange) {
      if (this._eager) await this._onchange()
      this._consume()
    }
  }

  [Symbol.asyncIterator]() {
    this._flowing = true
    return this
  }

  _ontruncate() {
    this._onappend()
  }

  _onappend() {
    const resolve = this._resolveOnChange
    this._resolveOnChange = null
    if (resolve) resolve()
  }

  async _waitForChanges() {
    if (this.current.version < this.bee.version || this.closing) return

    await new Promise((resolve) => {
      this._resolveOnChange = resolve
    })
  }

  async next() {
    try {
      return await this._next()
    } catch (err) {
      if (this.closing) return { value: undefined, done: true }
      await this.close()
      throw err
    }
  }

  async _next() {
    const release = await this._lock()

    try {
      if (this.closing) return { value: undefined, done: true }

      if (!this.opened) await this.ready()

      while (true) {
        await this._waitForChanges()

        if (this.closing) return { value: undefined, done: true }

        await this._closePrevious()
        this.previous = this.current.snapshot()

        await this._closeCurrent()
        this.current = this.bee.snapshot({
          keyEncoding: this.keyEncoding,
          valueEncoding: this.valueEncoding
        })

        await this.current.ready()
        await this.previous.ready()

        if (this.current.core.fork !== this.previous.core.fork) {
          return await this._yield()
        }

        this.stream = this._differ(this.current, this.previous, this.range)

        try {
          for await (const data of this.stream) {
            // eslint-disable-line
            return await this._yield()
          }
        } finally {
          this.stream = null
        }
      }
    } finally {
      release()
    }
  }

  async _yield() {
    this.currentMapped = this.map(this.current)
    this.previousMapped = this.map(this.previous)

    if (this._onchange) {
      try {
        await this._onchange()
      } catch (err) {
        safetyCatch(err)
      }
    }

    this.emit('update')
    return { done: false, value: [this.currentMapped, this.previousMapped] }
  }

  async return() {
    await this.close()
    return { done: true }
  }

  async _close() {
    const top = this.bee._watchers.pop()
    if (top !== this) {
      top.index = this.index
      this.bee._watchers[top.index] = top
    }

    if (this.stream && !this.stream.destroying) {
      this.stream.destroy()
    }

    this._onappend() // Continue execution being closed

    await this._closeCurrent().catch(safetyCatch)
    await this._closePrevious().catch(safetyCatch)

    const release = await this._lock()
    release()
  }

  destroy() {
    return this.close()
  }

  async _closeCurrent() {
    if (this.currentMapped) await this.currentMapped.close()
    if (this.current) await this.current.close()
    this.current = this.currentMapped = null
  }

  async _closePrevious() {
    if (this.previousMapped) await this.previousMapped.close()
    if (this.previous) await this.previous.close()
    this.previous = this.previousMapped = null
  }
}

function autoFlowOnUpdate(name) {
  if (name === 'update') this._consume()
}

function defaultWatchMap(snapshot) {
  return snapshot
}

async function leafSize(node, goLeft) {
  while (node.children.length) node = await node.getChildNode(goLeft ? 0 : node.children.length - 1)
  return node.keys.length
}

async function setKeyToNearestLeaf(node, index, stack) {
  let [left, right] = await Promise.all([node.getChildNode(index), node.getChildNode(index + 1)])
  const [ls, rs] = await Promise.all([leafSize(left, false), leafSize(right, true)])

  if (ls < rs) {
    // if fewer leaves on the left
    stack.push(right)
    while (right.children.length) stack.push((right = right.children[0].value))
    node.keys[index] = right.keys.shift()
  } else {
    // if fewer leaves on the right
    stack.push(left)
    while (left.children.length) stack.push((left = left.children[left.children.length - 1].value))
    node.keys[index] = left.keys.pop()
  }
}

async function rebalance(stack) {
  const root = stack[0]

  while (stack.length > 1) {
    const node = stack.pop()
    const parent = stack[stack.length - 1]

    if (node.keys.length >= MIN_KEYS) return root

    let { left, index, right } = await node.siblings(parent)

    // maybe borrow from left sibling?
    if (left && left.keys.length > MIN_KEYS) {
      left.changed = true
      node.keys.unshift(parent.keys[index - 1])
      if (left.children.length) node.children.unshift(left.children.pop())
      parent.keys[index - 1] = left.keys.pop()
      return root
    }

    // maybe borrow from right sibling?
    if (right && right.keys.length > MIN_KEYS) {
      right.changed = true
      node.keys.push(parent.keys[index])
      if (right.children.length) node.children.push(right.children.shift())
      parent.keys[index] = right.keys.shift()
      return root
    }

    // merge node with another sibling
    if (left) {
      index--
      right = node
    } else {
      left = node
    }

    left.merge(right, parent.keys[index])
    parent.removeKey(index)
  }

  // check if the tree shrunk
  if (!root.keys.length && root.children.length) return root.getChildNode(0)
  return root
}

function iteratorToStream(ite, signal) {
  let done
  let closing

  const rs = new Readable({
    signal,
    open(cb) {
      done = cb
      ite.open().then(fin, fin)
    },
    read(cb) {
      done = cb
      ite.next().then(push, fin)
    },
    predestroy() {
      closing = ite.close()
      closing.catch(noop)
    },
    destroy(cb) {
      done = cb
      if (!closing) closing = ite.close()
      closing.then(fin, fin)
    }
  })

  return rs

  function fin(err) {
    done(err)
  }

  function push(val) {
    rs.push(val)
    done(null)
  }
}

async function iteratorPeek(ite) {
  try {
    await ite.open()
    return await ite.next()
  } finally {
    await ite.close()
  }
}

function encRange(e, opts) {
  if (!e) return opts

  if (e.encodeRange) {
    const r = e.encodeRange({
      gt: opts.gt,
      gte: opts.gte,
      lt: opts.lt,
      lte: opts.lte
    })
    opts.gt = r.gt
    opts.gte = r.gte
    opts.lt = r.lt
    opts.lte = r.lte
    return opts
  }

  if (opts.gt !== undefined) opts.gt = enc(e, opts.gt)
  if (opts.gte !== undefined) opts.gte = enc(e, opts.gte)
  if (opts.lt !== undefined) opts.lt = enc(e, opts.lt)
  if (opts.lte !== undefined) opts.lte = enc(e, opts.lte)
  if (opts.sub && !opts.gt && !opts.gte) opts.gt = enc(e, SEP)
  if (opts.sub && !opts.lt && !opts.lte) opts.lt = bump(enc(e, EMPTY))

  return opts
}

function bump(key) {
  // key should have been copied by enc above before hitting this
  key[key.length - 1]++
  return key
}

function enc(e, v) {
  if (v === undefined || v === null) return null
  if (e !== null) return e.encode(v)
  if (typeof v === 'string') return b4a.from(v)
  return v
}

function prefixEncoding(prefix, keyEncoding) {
  return {
    encode(key) {
      return b4a.concat([prefix, b4a.isBuffer(key) ? key : enc(keyEncoding, key)])
    },
    decode(key) {
      const sliced = key.slice(prefix.length, key.length)
      return keyEncoding ? keyEncoding.decode(sliced) : sliced
    }
  }
}

function copyEntry(entry) {
  let key = entry.key
  let value = entry.value
  let index = entry.index

  // key, value and index all refer to the same buffer (one hypercore block)
  // If together they are larger than half the buffer's byteLength,
  // this means that they got their own private slab (see Buffer.allocUnsafe docs)
  // so no need to unslab
  const size =
    key.byteLength +
    (value === null ? 0 : value.byteLength) +
    (index === null ? 0 : index.byteLength)
  if (2 * size < key.buffer.byteLength) {
    const [newKey, newValue, newIndex] = unslabAll([entry.key, entry.value, entry.index])
    key = newKey
    value = newValue
    index = newIndex
  }

  return {
    key,
    value,
    index,
    inflated: null
  }
}

function defaultDiffer(currentSnap, previousSnap, opts) {
  return currentSnap.createDiffStream(previousSnap, opts)
}

function toNull() {
  return null
}

function getBackingCore(core) {
  if (core.core) return core
  if (core.getBackingCore) return core.getBackingCore().session
  return null
}

function sameValue(a, b) {
  return a === b || (a !== null && b !== null && b4a.equals(a, b))
}

function noop() {}

function getExtension(db, opts) {
  if (opts.extension === false) return null
  if (opts.extension && opts.extension !== true) return opts.extension
  return Extension.register(db)
}

async function isLinked(batch, block) {
  const seq = block.seq
  block.inflate()

  const keys = [block.key]
  const wait = batch.options.wait

  for (const l of block.index.levels) {
    if (!l.keys.length) continue
    batch.options.wait = false
    try {
      keys.push(await batch.getKey(l.keys[0].seq))
    } catch {}
    batch.options.wait = wait
  }

  for (const k of keys) {
    if (await batch.links(k, seq)) return true
  }

  if (batch.core.closing) throw new Error('Core is closed')

  return false
}

module.exports = Hyperbee
const b4a = require('b4a')

class SubTree {
  constructor(node, parent) {
    this.node = node
    this.parent = parent

    this.isKey = node.children.length === 0
    this.i = this.isKey ? 1 : 0
    this.n = 0

    const child = this.isKey ? null : this.node.children[0]
    this.seq = child !== null ? child.seq : this.node.keys[0].seq
    this.offset = child !== null ? child.offset : 0
  }

  next() {
    this.i++
    this.isKey = (this.i & 1) === 1
    if (!this.isKey && !this.node.children.length) this.i++
    return this.update()
  }

  async bisect(key, incl) {
    let s = 0
    let e = this.node.keys.length
    let c

    while (s < e) {
      const mid = (s + e) >> 1
      c = cmp(key, await this.node.getKey(mid))

      if (c === 0) {
        if (incl) this.i = mid * 2 + 1
        else this.i = mid * 2 + (this.node.children.length ? 2 : 3)
        return true
      }

      if (c < 0) e = mid
      else s = mid + 1
    }

    const i = c < 0 ? e : s
    this.i = 2 * i + (this.node.children.length ? 0 : 1)
    return this.node.children.length === 0
  }

  update() {
    this.isKey = (this.i & 1) === 1
    this.n = this.i >> 1
    if (this.n >= (this.isKey ? this.node.keys.length : this.node.children.length)) return false
    const child = this.isKey ? null : this.node.children[this.n]
    this.seq = child !== null ? child.seq : this.node.keys[this.n].seq
    this.offset = child !== null ? child.offset : 0
    return true
  }

  async key() {
    return this.n < this.node.keys.length
      ? this.node.getKey(this.n)
      : this.parent && this.parent.key()
  }

  async compare(tree) {
    const [a, b] = await Promise.all([this.key(), tree.key()])
    return cmp(a, b)
  }
}

class TreeIterator {
  constructor(batch, opts) {
    this.batch = batch
    this.stack = []
    this.lt = opts.lt || opts.lte || null
    this.lte = !!opts.lte
    this.gt = opts.gt || opts.gte || null
    this.gte = !!opts.gte
    this.seeking = !!this.gt
    this.encoding = opts.encoding || batch.encoding
  }

  async open() {
    const node = await this.batch.getRoot(false)
    if (!node || !node.keys.length) return
    const tree = new SubTree(node, null)
    if (this.seeking && !(await this._seek(tree))) return
    this.stack.push(tree)
  }

  async _seek(tree) {
    const done = await tree.bisect(this.gt, this.gte)
    const oob = !tree.update()
    if (done || oob) {
      this.seeking = false
      if (oob) return false
    }
    return true
  }

  peek() {
    if (!this.stack.length) return null
    return this.stack[this.stack.length - 1]
  }

  skip() {
    if (!this.stack.length) return
    if (!this.stack[this.stack.length - 1].next()) this.stack.pop()
  }

  async nextKey() {
    let n = null
    while (this.stack.length && n === null) n = await this.next()
    if (n === null) return null
    if (!this.lt) return n.final(this.encoding)

    const c = cmp(n.key, this.lt)
    if (this.lte ? c <= 0 : c < 0) return n.final(this.encoding)
    this.stack = []
    return null
  }

  async next() {
    if (!this.stack.length) return null

    const top = this.stack[this.stack.length - 1]
    const { isKey, n, seq } = top

    if (!top.next()) {
      this.stack.pop()
    }

    if (isKey) {
      this.seeking = false
      return this.batch.getBlock(seq)
    }

    const child = await top.node.getChildNode(n)
    top.node.children[n] = null // unlink to save memory
    const tree = new SubTree(child, top)
    if (this.seeking && !(await this._seek(tree))) return null
    this.stack.push(tree)

    return null
  }

  close() {
    return this.batch._closeSnapshot()
  }
}

module.exports = class DiffIterator {
  constructor(left, right, opts = {}) {
    this.left = new TreeIterator(left, opts)
    this.right = new TreeIterator(right, opts)
    this.limit = typeof opts.limit === 'number' ? opts.limit : -1
  }

  async open() {
    await Promise.all([this.left.open(), this.right.open()])
  }

  async next() {
    if (this.limit === 0) return null
    const res = await this._next()
    if (!res || (res.left === null && res.right === null)) return null
    this.limit--
    return res
  }

  async _next() {
    const a = this.left
    const b = this.right

    while (true) {
      const [l, r] = await Promise.all([a.peek(), b.peek()])

      if (!l && !r) return null
      if (!l) return { left: null, right: await b.nextKey() }
      if (!r) return { left: await a.nextKey(), right: null }

      if (l.seq === r.seq && l.isKey === r.isKey && l.offset === r.offset) {
        a.skip()
        b.skip()
        continue
      }

      const c = await l.compare(r)

      if (l.isKey && !r.isKey) {
        await b.next()
        continue
      }

      if (!l.isKey && r.isKey) {
        await a.next()
        continue
      }

      if (l.isKey && r.isKey) {
        if (c === 0) return { left: await a.nextKey(), right: await b.nextKey() }
        if (c < 0) return { left: await a.nextKey(), right: null }
        return { left: null, right: await b.nextKey() }
      }

      if (c === 0) await Promise.all([a.next(), b.next()])
      else if (c < 0) await b.next()
      else await a.next()
    }
  }

  async close() {
    await Promise.all([this.left.close(), this.right.close()])
  }
}

function cmp(a, b) {
  if (!a) return b ? 1 : 0
  if (!b) return a ? -1 : 0
  return b4a.compare(a, b)
}
module.exports = class HistoryIterator {
  constructor(batch, opts = {}) {
    this.batch = batch
    this.options = opts
    this.live = !!opts.live
    this.gte = 0
    this.lt = 0
    this.reverse = !!opts.reverse
    this.limit = typeof opts.limit === 'number' ? opts.limit : -1
    this.encoding = opts.encoding || batch.encoding
    if (this.live && this.reverse) {
      throw new Error('Cannot have both live and reverse enabled')
    }
  }

  async open() {
    await this.batch.getRoot(false) // does the update dance
    this.gte = gte(this.options, this.batch.version)
    this.lt = this.live ? Infinity : lt(this.options, this.batch.version)
  }

  async next() {
    if (this.limit === 0) return null
    if (this.limit > 0) this.limit--

    if (this.gte >= this.lt) return null

    if (this.reverse) {
      if (this.lt <= 1) return null
      return final(await this.batch.getBlock(--this.lt), this.encoding)
    }

    return final(await this.batch.getBlock(this.gte++), this.encoding)
  }

  close() {
    return this.batch._closeSnapshot()
  }
}

function final(node, encoding) {
  const type = node.isDeletion() ? 'del' : 'put'
  return { type, ...node.final(encoding) }
}

function gte(opts, version) {
  if (opts.gt) return (opts.gt < 0 ? opts.gt + version : opts.gt) + 1
  const gte = opts.gte || opts.since || 1
  return gte < 0 ? gte + version : gte
}

function lt(opts, version) {
  if (opts.lte === 0 || opts.lt === 0 || opts.end === 0) return 0
  if (opts.lte) return (opts.lte < 0 ? opts.lte + version : opts.lte) + 1
  const lt = opts.lt || opts.end || version
  return lt < 0 ? lt + version : lt
}
module.exports = class LocalBlocksIterator {
  constructor(batch, opts = {}) {
    this.batch = batch
    this.options = opts
    this.gte = 0
    this.lt = 0
    this.limit = typeof opts.limit === 'number' ? opts.limit : -1
  }

  async open() {
    await this.batch.getRoot(false) // does the update dance
    this.gte = gte(this.options, this.batch.version)
    this.lt = lt(this.options, this.batch.version)
  }

  async next() {
    if (this.limit === 0) return null
    if (this.limit > 0) this.limit--

    while (this.gte < this.lt) {
      try {
        return await this.batch.getBlock(this.gte++)
      } catch {
        continue
      }
    }

    return null
  }

  close() {
    return this.batch._closeSnapshot()
  }
}

function gte(opts, version) {
  if (opts.gt) return (opts.gt < 0 ? opts.gt + version : opts.gt) + 1
  const gte = opts.gte || opts.since || 1
  return gte < 0 ? gte + version : gte
}

function lt(opts, version) {
  if (opts.lte === 0 || opts.lt === 0 || opts.end === 0) return 0
  if (opts.lte) return (opts.lte < 0 ? opts.lte + version : opts.lte) + 1
  const lt = opts.lt || opts.end || version
  return lt < 0 ? lt + version : lt
}
const b4a = require('b4a')

module.exports = class RangeIterator {
  constructor(batch, encoding, opts = {}) {
    this.batch = batch
    this.stack = []
    this.opened = false
    this.encoding = encoding || batch.encoding

    this._limit = typeof opts.limit === 'number' ? opts.limit : -1
    this._gIncl = !opts.gt
    this._gKey = opts.gt || opts.gte || null
    this._lIncl = !opts.lt
    this._lKey = opts.lt || opts.lte || null
    this._reverse = !!opts.reverse
    this._version = 0
    this._checkpoint = opts.checkpoint && opts.checkpoint.length ? opts.checkpoint : null
    this._nexting = false
    this._closed = false
  }

  snapshot(version = this.batch.version) {
    const checkpoint = []
    for (const s of this.stack) {
      let { node, i } = s
      if (this._nexting && s === this.stack[this.stack.length - 1]) {
        i = this._reverse ? i + 1 : i - 1
      }
      if (!node.block) continue
      if (i < 0) continue
      checkpoint.push(node.block.seq, node.offset, i)
    }

    return {
      version,
      gte: this._gIncl ? this._gKey : null,
      gt: this._gIncl ? null : this._gKey,
      lte: this._lIncl ? this._lKey : null,
      lt: this._lIncl ? null : this._lKey,
      limit: this._limit,
      reverse: this._reverse,
      ended: this.opened && !checkpoint.length,
      checkpoint: this.opened ? checkpoint : []
    }
  }

  async open() {
    await this._open()
    this.opened = true
  }

  async _open() {
    if (this._checkpoint) {
      for (let j = 0; j < this._checkpoint.length; j += 3) {
        const seq = this._checkpoint[j]
        const offset = this._checkpoint[j + 1]
        const i = this._checkpoint[j + 2]
        this.stack.push({
          node: (await this.batch.getBlock(seq)).getTreeNode(offset),
          i
        })
      }
      return
    }

    this._nexting = true

    let node = await this.batch.getRoot(false)
    if (!node) {
      this._nexting = false
      return
    }

    const incl = this._reverse ? this._lIncl : this._gIncl
    const start = this._reverse ? this._lKey : this._gKey

    if (!start) {
      this.stack.push({ node, i: this._reverse ? node.keys.length << 1 : 0 })
      this._nexting = false
      this._preloadQuery()
      return
    }

    while (true) {
      const entry = { node, i: this._reverse ? node.keys.length << 1 : 0 }

      let s = 0
      let e = node.keys.length
      let c

      while (s < e) {
        const mid = (s + e) >> 1
        c = b4a.compare(start, await node.getKey(mid))

        if (c === 0) {
          if (incl) entry.i = mid * 2 + 1
          else entry.i = mid * 2 + (this._reverse ? 0 : 2)
          this.stack.push(entry)
          this._nexting = false
          this._preloadQuery()
          return
        }

        if (c < 0) e = mid
        else s = mid + 1
      }

      const i = c < 0 ? e : s
      entry.i = 2 * i + (this._reverse ? -1 : 1)

      if (entry.i >= 0 && entry.i <= node.keys.length << 1) this.stack.push(entry)
      if (!node.children.length) {
        this._nexting = false
        this._preloadQuery()
        return
      }

      node = await node.getChildNode(i)
    }
  }

  _preloadQuery() {
    const max = { nodes: 0, max: 2048 }

    if (this._limit === -1 && !this._reverse && this.stack.length) {
      for (const s of this.stack) {
        const k = (s.i - (s.i & 1)) / 2
        this._preload(s.node, k + 1, this._lKey, max).catch(noop)
      }
    }
  }

  async _preload(node, i, end, max) {
    for (; i < node.keys.length; i++) {
      const key = node.keys[i]
      const block = await this.batch.getBlock(key.seq)
      if (this._closed) return
      const c = end ? b4a.compare(block.key, end) : -1
      if (c >= 0 || max.nodes >= max.max || i >= node.children.length) return
      max.nodes++
      const next = await node.getChildNode(i)
      if (this._closed) return
      this._preload(next, 0, end, max).catch(noop)
    }

    if (node.children.length && max.nodes < max.max) {
      const next = await node.getChildNode(node.children.length - 1)
      if (this._closed) return
      this._preload(next, 0, end, max).catch(noop)
    }
  }

  async next() {
    // TODO: this nexting flag is only needed if someone asks for a snapshot during
    // a lookup (ie the extension, pretty important...).
    // A better solution would be to refactor this so top.i is incremented eagerly
    // to get the current block instead of the way it is done now (++i vs i++)
    this._nexting = true

    const end = this._reverse ? this._gKey : this._lKey
    const incl = this._reverse ? this._gIncl : this._lIncl

    while (this.stack.length && (this._limit === -1 || this._limit > 0)) {
      const top = this.stack[this.stack.length - 1]
      const isKey = (top.i & 1) === 1
      const n = this._reverse ? (top.i < 0 ? top.node.keys.length : top.i-- >> 1) : top.i++ >> 1

      if (!isKey) {
        if (!top.node.children.length) continue
        const node = await top.node.getChildNode(n)
        if (top.node.block.seq < this.batch.core.length) {
          top.node.children[n].value = null // unlink it to save memory
        }
        this.stack.push({ i: this._reverse ? node.keys.length << 1 : 0, node })
        continue
      }

      if (n >= top.node.keys.length) {
        this.stack.pop()
        continue
      }

      const key = top.node.keys[n]
      const block = await this.batch.getBlock(key.seq)
      if (end) {
        const c = b4a.compare(block.key, end)
        if (c === 0 ? !incl : this._reverse ? c < 0 : c > 0) {
          this._limit = 0
          break
        }
      }
      if (this._limit > 0) this._limit--
      this._nexting = false
      return block.final(this.encoding)
    }

    this._nexting = false
    return null
  }

  close() {
    this._closed = true
    return this.batch._closeSnapshot()
  }
}

function noop() {}
const { Extension } = require('./messages')

// const MAX_ACTIVE = 32
const FLUSH_BATCH = 128
const MAX_PASSIVE_BATCH = 2048
const MAX_ACTIVE_BATCH = MAX_PASSIVE_BATCH + FLUSH_BATCH

class Batch {
  constructor(outgoing, from) {
    this.blocks = []
    this.start = 0
    this.end = 0
    this.outgoing = outgoing
    this.from = from
  }

  push(seq) {
    const len = this.blocks.push(seq)
    if (len === 1 || seq < this.start) this.start = seq
    if (len === 1 || seq >= this.end) this.end = seq + 1
    if (len >= FLUSH_BATCH) {
      this.send()
      this.clear()
    }
  }

  send() {
    if (!this.blocks.length) return
    this.outgoing.send(
      Extension.encode({
        cache: { blocks: this.blocks, start: this.start, end: this.end }
      }),
      this.from
    )
  }

  clear() {
    this.start = this.end = 0
    this.blocks = []
  }
}

class HyperbeeExtension {
  constructor(db) {
    this.encoding = null
    this.outgoing = null
    this.db = db
    this.active = 0
  }

  get(version, key) {
    this.outgoing.broadcast(Extension.encode({ get: { version, key } }))
  }

  iterator(snapshot) {
    if (snapshot.ended) return
    if (snapshot.limit === 0) return
    if (snapshot.limit === -1) snapshot.limit = 0
    this.outgoing.broadcast(Extension.encode({ iterator: snapshot }))
  }

  onmessage(buf, from) {
    // TODO: handle max active extension messages
    // this.active++

    const message = decode(buf)
    if (!message) return

    if (message.cache) this.oncache(message.cache, from)
    if (message.get) this.onget(message.get, from)
    if (message.iterator) this.oniterator(message.iterator, from)
  }

  oncache(message, from) {
    if (!message.blocks.length) return
    this.db.core.download(message)
  }

  onget(message, from) {
    if (!message.version || message.version > this.db.version) return

    const b = new Batch(this.outgoing, from)
    const db = this.db.checkout(message.version)

    db.get(message.key, {
      extension: false,
      wait: false,
      update: false,
      onseq
    }).then(done, done)

    function done() {
      db.close().catch(noop)
      b.send()
    }

    function onseq(seq) {
      b.push(seq)
    }
  }

  async oniterator(message, from) {
    if (!message.version || message.version > this.db.version) return

    const b = new Batch(this.outgoing, from)
    const seqs = new Set()

    let skip = message.checkpoint.length
    let work = 0

    const db = this.db.checkout(message.version)
    const ite = db.createRangeIterator({
      ...message,
      wait: false,
      extension: false,
      update: false,
      limit: message.limit === 0 ? -1 : message.limit,
      onseq(seq) {
        if (skip && skip--) return
        if (seqs.has(seq)) return
        work++
        seqs.add(seq)
        b.push(seq)
      }
    })

    try {
      await ite.open()
      // eslint-disable-next-line no-unmodified-loop-condition
      while (work < MAX_ACTIVE_BATCH) {
        if (!(await ite.next())) break
      }
    } catch (_) {
      // do nothing
    } finally {
      ite.close().catch(noop)
      db.close().catch(noop)
      b.send()
    }
  }

  static register(db) {
    const e = new this(db)
    e.outgoing = db.core.registerExtension('hyperbee', e)
    return e
  }
}

HyperbeeExtension.BATCH_SIZE = MAX_PASSIVE_BATCH

module.exports = HyperbeeExtension

function decode(buf) {
  try {
    return Extension.decode(buf)
  } catch (err) {
    return null
  }
}

function noop() {}
// This file is auto generated by the protocol-buffers compiler

/* eslint-disable quotes */
/* eslint-disable indent */
/* eslint-disable no-redeclare */
/* eslint-disable camelcase */
/* eslint-disable no-var */

// Remember to `npm install --save protocol-buffers-encodings`
var encodings = require('protocol-buffers-encodings')
var b4a = require('b4a')
var varint = encodings.varint
var skip = encodings.skip

var YoloIndex = exports.YoloIndex = {
  buffer: true,
  encodingLength: null,
  encode: null,
  decode: null
}

var Header = exports.Header = {
  buffer: true,
  encodingLength: null,
  encode: null,
  decode: null
}

var Node = exports.Node = {
  buffer: true,
  encodingLength: null,
  encode: null,
  decode: null
}

var Extension = exports.Extension = {
  buffer: true,
  encodingLength: null,
  encode: null,
  decode: null
}

defineYoloIndex()
defineHeader()
defineNode()
defineExtension()

function defineYoloIndex () {
  var Level = YoloIndex.Level = {
    buffer: true,
    encodingLength: null,
    encode: null,
    decode: null
  }

  defineLevel()

  function defineLevel () {
    Level.encodingLength = encodingLength
    Level.encode = encode
    Level.decode = decode

    function encodingLength (obj) {
      var length = 0
      if (defined(obj.keys)) {
        var packedLen = 0
        for (var i = 0; i < obj.keys.length; i++) {
          if (!defined(obj.keys[i])) continue
          var len = encodings.varint.encodingLength(obj.keys[i])
          packedLen += len
        }
        if (packedLen) {
          length += 1 + packedLen + varint.encodingLength(packedLen)
        }
      }
      if (defined(obj.children)) {
        var packedLen = 0
        for (var i = 0; i < obj.children.length; i++) {
          if (!defined(obj.children[i])) continue
          var len = encodings.varint.encodingLength(obj.children[i])
          packedLen += len
        }
        if (packedLen) {
          length += 1 + packedLen + varint.encodingLength(packedLen)
        }
      }
      return length
    }

    function encode (obj, buf, offset) {
      if (!offset) offset = 0
      if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
      var oldOffset = offset
      if (defined(obj.keys)) {
        var packedLen = 0
        for (var i = 0; i < obj.keys.length; i++) {
          if (!defined(obj.keys[i])) continue
          packedLen += encodings.varint.encodingLength(obj.keys[i])
        }
        if (packedLen) {
          buf[offset++] = 10
          varint.encode(packedLen, buf, offset)
          offset += varint.encode.bytes
        }
        for (var i = 0; i < obj.keys.length; i++) {
          if (!defined(obj.keys[i])) continue
          encodings.varint.encode(obj.keys[i], buf, offset)
          offset += encodings.varint.encode.bytes
        }
      }
      if (defined(obj.children)) {
        var packedLen = 0
        for (var i = 0; i < obj.children.length; i++) {
          if (!defined(obj.children[i])) continue
          packedLen += encodings.varint.encodingLength(obj.children[i])
        }
        if (packedLen) {
          buf[offset++] = 18
          varint.encode(packedLen, buf, offset)
          offset += varint.encode.bytes
        }
        for (var i = 0; i < obj.children.length; i++) {
          if (!defined(obj.children[i])) continue
          encodings.varint.encode(obj.children[i], buf, offset)
          offset += encodings.varint.encode.bytes
        }
      }
      encode.bytes = offset - oldOffset
      return buf
    }

    function decode (buf, offset, end) {
      if (!offset) offset = 0
      if (!end) end = buf.length
      if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
      var oldOffset = offset
      var obj = {
        keys: [],
        children: []
      }
      while (true) {
        if (end <= offset) {
          decode.bytes = offset - oldOffset
          return obj
        }
        var prefix = varint.decode(buf, offset)
        offset += varint.decode.bytes
        var tag = prefix >> 3
        switch (tag) {
          case 1:
          var packedEnd = varint.decode(buf, offset)
          offset += varint.decode.bytes
          packedEnd += offset
          while (offset < packedEnd) {
            obj.keys.push(encodings.varint.decode(buf, offset))
            offset += encodings.varint.decode.bytes
          }
          break
          case 2:
          var packedEnd = varint.decode(buf, offset)
          offset += varint.decode.bytes
          packedEnd += offset
          while (offset < packedEnd) {
            obj.children.push(encodings.varint.decode(buf, offset))
            offset += encodings.varint.decode.bytes
          }
          break
          default:
          offset = skip(prefix & 7, buf, offset)
        }
      }
    }
  }

  YoloIndex.encodingLength = encodingLength
  YoloIndex.encode = encode
  YoloIndex.decode = decode

  function encodingLength (obj) {
    var length = 0
    if (defined(obj.levels)) {
      for (var i = 0; i < obj.levels.length; i++) {
        if (!defined(obj.levels[i])) continue
        var len = Level.encodingLength(obj.levels[i])
        length += varint.encodingLength(len)
        length += 1 + len
      }
    }
    return length
  }

  function encode (obj, buf, offset) {
    if (!offset) offset = 0
    if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
    var oldOffset = offset
    if (defined(obj.levels)) {
      for (var i = 0; i < obj.levels.length; i++) {
        if (!defined(obj.levels[i])) continue
        buf[offset++] = 10
        varint.encode(Level.encodingLength(obj.levels[i]), buf, offset)
        offset += varint.encode.bytes
        Level.encode(obj.levels[i], buf, offset)
        offset += Level.encode.bytes
      }
    }
    encode.bytes = offset - oldOffset
    return buf
  }

  function decode (buf, offset, end) {
    if (!offset) offset = 0
    if (!end) end = buf.length
    if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
    var oldOffset = offset
    var obj = {
      levels: []
    }
    while (true) {
      if (end <= offset) {
        decode.bytes = offset - oldOffset
        return obj
      }
      var prefix = varint.decode(buf, offset)
      offset += varint.decode.bytes
      var tag = prefix >> 3
      switch (tag) {
        case 1:
        var len = varint.decode(buf, offset)
        offset += varint.decode.bytes
        obj.levels.push(Level.decode(buf, offset, offset + len))
        offset += Level.decode.bytes
        break
        default:
        offset = skip(prefix & 7, buf, offset)
      }
    }
  }
}

function defineHeader () {
  var Metadata = Header.Metadata = {
    buffer: true,
    encodingLength: null,
    encode: null,
    decode: null
  }

  defineMetadata()

  function defineMetadata () {
    Metadata.encodingLength = encodingLength
    Metadata.encode = encode
    Metadata.decode = decode

    function encodingLength (obj) {
      var length = 0
      if (defined(obj.contentFeed)) {
        var len = encodings.bytes.encodingLength(obj.contentFeed)
        length += 1 + len
      }
      if (defined(obj.userData)) {
        var len = encodings.bytes.encodingLength(obj.userData)
        length += 1 + len
      }
      return length
    }

    function encode (obj, buf, offset) {
      if (!offset) offset = 0
      if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
      var oldOffset = offset
      if (defined(obj.contentFeed)) {
        buf[offset++] = 10
        encodings.bytes.encode(obj.contentFeed, buf, offset)
        offset += encodings.bytes.encode.bytes
      }
      if (defined(obj.userData)) {
        buf[offset++] = 18
        encodings.bytes.encode(obj.userData, buf, offset)
        offset += encodings.bytes.encode.bytes
      }
      encode.bytes = offset - oldOffset
      return buf
    }

    function decode (buf, offset, end) {
      if (!offset) offset = 0
      if (!end) end = buf.length
      if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
      var oldOffset = offset
      var obj = {
        contentFeed: null,
        userData: null
      }
      while (true) {
        if (end <= offset) {
          decode.bytes = offset - oldOffset
          return obj
        }
        var prefix = varint.decode(buf, offset)
        offset += varint.decode.bytes
        var tag = prefix >> 3
        switch (tag) {
          case 1:
          obj.contentFeed = encodings.bytes.decode(buf, offset)
          offset += encodings.bytes.decode.bytes
          break
          case 2:
          obj.userData = encodings.bytes.decode(buf, offset)
          offset += encodings.bytes.decode.bytes
          break
          default:
          offset = skip(prefix & 7, buf, offset)
        }
      }
    }
  }

  Header.encodingLength = encodingLength
  Header.encode = encode
  Header.decode = decode

  function encodingLength (obj) {
    var length = 0
    if (!defined(obj.protocol)) throw new Error("protocol is required")
    var len = encodings.string.encodingLength(obj.protocol)
    length += 1 + len
    if (defined(obj.metadata)) {
      var len = Metadata.encodingLength(obj.metadata)
      length += varint.encodingLength(len)
      length += 1 + len
    }
    return length
  }

  function encode (obj, buf, offset) {
    if (!offset) offset = 0
    if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
    var oldOffset = offset
    if (!defined(obj.protocol)) throw new Error("protocol is required")
    buf[offset++] = 10
    encodings.string.encode(obj.protocol, buf, offset)
    offset += encodings.string.encode.bytes
    if (defined(obj.metadata)) {
      buf[offset++] = 18
      varint.encode(Metadata.encodingLength(obj.metadata), buf, offset)
      offset += varint.encode.bytes
      Metadata.encode(obj.metadata, buf, offset)
      offset += Metadata.encode.bytes
    }
    encode.bytes = offset - oldOffset
    return buf
  }

  function decode (buf, offset, end) {
    if (!offset) offset = 0
    if (!end) end = buf.length
    if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
    var oldOffset = offset
    var obj = {
      protocol: "",
      metadata: null
    }
    var found0 = false
    while (true) {
      if (end <= offset) {
        if (!found0) throw new Error("Decoded message is not valid")
        decode.bytes = offset - oldOffset
        return obj
      }
      var prefix = varint.decode(buf, offset)
      offset += varint.decode.bytes
      var tag = prefix >> 3
      switch (tag) {
        case 1:
        obj.protocol = encodings.string.decode(buf, offset)
        offset += encodings.string.decode.bytes
        found0 = true
        break
        case 2:
        var len = varint.decode(buf, offset)
        offset += varint.decode.bytes
        obj.metadata = Metadata.decode(buf, offset, offset + len)
        offset += Metadata.decode.bytes
        break
        default:
        offset = skip(prefix & 7, buf, offset)
      }
    }
  }
}

function defineNode () {
  Node.encodingLength = encodingLength
  Node.encode = encode
  Node.decode = decode

  function encodingLength (obj) {
    var length = 0
    if (!defined(obj.index)) throw new Error("index is required")
    var len = encodings.bytes.encodingLength(obj.index)
    length += 1 + len
    if (!defined(obj.key)) throw new Error("key is required")
    var len = encodings.bytes.encodingLength(obj.key)
    length += 1 + len
    if (defined(obj.value)) {
      var len = encodings.bytes.encodingLength(obj.value)
      length += 1 + len
    }
    return length
  }

  function encode (obj, buf, offset) {
    if (!offset) offset = 0
    if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
    var oldOffset = offset
    if (!defined(obj.index)) throw new Error("index is required")
    buf[offset++] = 10
    encodings.bytes.encode(obj.index, buf, offset)
    offset += encodings.bytes.encode.bytes
    if (!defined(obj.key)) throw new Error("key is required")
    buf[offset++] = 18
    encodings.bytes.encode(obj.key, buf, offset)
    offset += encodings.bytes.encode.bytes
    if (defined(obj.value)) {
      buf[offset++] = 26
      encodings.bytes.encode(obj.value, buf, offset)
      offset += encodings.bytes.encode.bytes
    }
    encode.bytes = offset - oldOffset
    return buf
  }

  function decode (buf, offset, end) {
    if (!offset) offset = 0
    if (!end) end = buf.length
    if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
    var oldOffset = offset
    var obj = {
      index: null,
      key: null,
      value: null
    }
    var found0 = false
    var found1 = false
    while (true) {
      if (end <= offset) {
        if (!found0 || !found1) throw new Error("Decoded message is not valid")
        decode.bytes = offset - oldOffset
        return obj
      }
      var prefix = varint.decode(buf, offset)
      offset += varint.decode.bytes
      var tag = prefix >> 3
      switch (tag) {
        case 1:
        obj.index = encodings.bytes.decode(buf, offset)
        offset += encodings.bytes.decode.bytes
        found0 = true
        break
        case 2:
        obj.key = encodings.bytes.decode(buf, offset)
        offset += encodings.bytes.decode.bytes
        found1 = true
        break
        case 3:
        obj.value = encodings.bytes.decode(buf, offset)
        offset += encodings.bytes.decode.bytes
        break
        default:
        offset = skip(prefix & 7, buf, offset)
      }
    }
  }
}

function defineExtension () {
  var Get = Extension.Get = {
    buffer: true,
    encodingLength: null,
    encode: null,
    decode: null
  }

  var Iterator = Extension.Iterator = {
    buffer: true,
    encodingLength: null,
    encode: null,
    decode: null
  }

  var Cache = Extension.Cache = {
    buffer: true,
    encodingLength: null,
    encode: null,
    decode: null
  }

  defineGet()
  defineIterator()
  defineCache()

  function defineGet () {
    Get.encodingLength = encodingLength
    Get.encode = encode
    Get.decode = decode

    function encodingLength (obj) {
      var length = 0
      if (defined(obj.version)) {
        var len = encodings.varint.encodingLength(obj.version)
        length += 1 + len
      }
      if (defined(obj.key)) {
        var len = encodings.bytes.encodingLength(obj.key)
        length += 1 + len
      }
      return length
    }

    function encode (obj, buf, offset) {
      if (!offset) offset = 0
      if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
      var oldOffset = offset
      if (defined(obj.version)) {
        buf[offset++] = 8
        encodings.varint.encode(obj.version, buf, offset)
        offset += encodings.varint.encode.bytes
      }
      if (defined(obj.key)) {
        buf[offset++] = 18
        encodings.bytes.encode(obj.key, buf, offset)
        offset += encodings.bytes.encode.bytes
      }
      encode.bytes = offset - oldOffset
      return buf
    }

    function decode (buf, offset, end) {
      if (!offset) offset = 0
      if (!end) end = buf.length
      if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
      var oldOffset = offset
      var obj = {
        version: 0,
        key: null
      }
      while (true) {
        if (end <= offset) {
          decode.bytes = offset - oldOffset
          return obj
        }
        var prefix = varint.decode(buf, offset)
        offset += varint.decode.bytes
        var tag = prefix >> 3
        switch (tag) {
          case 1:
          obj.version = encodings.varint.decode(buf, offset)
          offset += encodings.varint.decode.bytes
          break
          case 2:
          obj.key = encodings.bytes.decode(buf, offset)
          offset += encodings.bytes.decode.bytes
          break
          default:
          offset = skip(prefix & 7, buf, offset)
        }
      }
    }
  }

  function defineIterator () {
    Iterator.encodingLength = encodingLength
    Iterator.encode = encode
    Iterator.decode = decode

    function encodingLength (obj) {
      var length = 0
      if (defined(obj.version)) {
        var len = encodings.varint.encodingLength(obj.version)
        length += 1 + len
      }
      if (defined(obj.gte)) {
        var len = encodings.bytes.encodingLength(obj.gte)
        length += 1 + len
      }
      if (defined(obj.gt)) {
        var len = encodings.bytes.encodingLength(obj.gt)
        length += 1 + len
      }
      if (defined(obj.lte)) {
        var len = encodings.bytes.encodingLength(obj.lte)
        length += 1 + len
      }
      if (defined(obj.lt)) {
        var len = encodings.bytes.encodingLength(obj.lt)
        length += 1 + len
      }
      if (defined(obj.limit)) {
        var len = encodings.varint.encodingLength(obj.limit)
        length += 1 + len
      }
      if (defined(obj.reverse)) {
        var len = encodings.bool.encodingLength(obj.reverse)
        length += 1 + len
      }
      if (defined(obj.checkpoint)) {
        var packedLen = 0
        for (var i = 0; i < obj.checkpoint.length; i++) {
          if (!defined(obj.checkpoint[i])) continue
          var len = encodings.varint.encodingLength(obj.checkpoint[i])
          packedLen += len
        }
        if (packedLen) {
          length += 1 + packedLen + varint.encodingLength(packedLen)
        }
      }
      return length
    }

    function encode (obj, buf, offset) {
      if (!offset) offset = 0
      if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
      var oldOffset = offset
      if (defined(obj.version)) {
        buf[offset++] = 8
        encodings.varint.encode(obj.version, buf, offset)
        offset += encodings.varint.encode.bytes
      }
      if (defined(obj.gte)) {
        buf[offset++] = 18
        encodings.bytes.encode(obj.gte, buf, offset)
        offset += encodings.bytes.encode.bytes
      }
      if (defined(obj.gt)) {
        buf[offset++] = 26
        encodings.bytes.encode(obj.gt, buf, offset)
        offset += encodings.bytes.encode.bytes
      }
      if (defined(obj.lte)) {
        buf[offset++] = 34
        encodings.bytes.encode(obj.lte, buf, offset)
        offset += encodings.bytes.encode.bytes
      }
      if (defined(obj.lt)) {
        buf[offset++] = 42
        encodings.bytes.encode(obj.lt, buf, offset)
        offset += encodings.bytes.encode.bytes
      }
      if (defined(obj.limit)) {
        buf[offset++] = 48
        encodings.varint.encode(obj.limit, buf, offset)
        offset += encodings.varint.encode.bytes
      }
      if (defined(obj.reverse)) {
        buf[offset++] = 56
        encodings.bool.encode(obj.reverse, buf, offset)
        offset += encodings.bool.encode.bytes
      }
      if (defined(obj.checkpoint)) {
        var packedLen = 0
        for (var i = 0; i < obj.checkpoint.length; i++) {
          if (!defined(obj.checkpoint[i])) continue
          packedLen += encodings.varint.encodingLength(obj.checkpoint[i])
        }
        if (packedLen) {
          buf[offset++] = 66
          varint.encode(packedLen, buf, offset)
          offset += varint.encode.bytes
        }
        for (var i = 0; i < obj.checkpoint.length; i++) {
          if (!defined(obj.checkpoint[i])) continue
          encodings.varint.encode(obj.checkpoint[i], buf, offset)
          offset += encodings.varint.encode.bytes
        }
      }
      encode.bytes = offset - oldOffset
      return buf
    }

    function decode (buf, offset, end) {
      if (!offset) offset = 0
      if (!end) end = buf.length
      if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
      var oldOffset = offset
      var obj = {
        version: 0,
        gte: null,
        gt: null,
        lte: null,
        lt: null,
        limit: 0,
        reverse: false,
        checkpoint: []
      }
      while (true) {
        if (end <= offset) {
          decode.bytes = offset - oldOffset
          return obj
        }
        var prefix = varint.decode(buf, offset)
        offset += varint.decode.bytes
        var tag = prefix >> 3
        switch (tag) {
          case 1:
          obj.version = encodings.varint.decode(buf, offset)
          offset += encodings.varint.decode.bytes
          break
          case 2:
          obj.gte = encodings.bytes.decode(buf, offset)
          offset += encodings.bytes.decode.bytes
          break
          case 3:
          obj.gt = encodings.bytes.decode(buf, offset)
          offset += encodings.bytes.decode.bytes
          break
          case 4:
          obj.lte = encodings.bytes.decode(buf, offset)
          offset += encodings.bytes.decode.bytes
          break
          case 5:
          obj.lt = encodings.bytes.decode(buf, offset)
          offset += encodings.bytes.decode.bytes
          break
          case 6:
          obj.limit = encodings.varint.decode(buf, offset)
          offset += encodings.varint.decode.bytes
          break
          case 7:
          obj.reverse = encodings.bool.decode(buf, offset)
          offset += encodings.bool.decode.bytes
          break
          case 8:
          var packedEnd = varint.decode(buf, offset)
          offset += varint.decode.bytes
          packedEnd += offset
          while (offset < packedEnd) {
            obj.checkpoint.push(encodings.varint.decode(buf, offset))
            offset += encodings.varint.decode.bytes
          }
          break
          default:
          offset = skip(prefix & 7, buf, offset)
        }
      }
    }
  }

  function defineCache () {
    Cache.encodingLength = encodingLength
    Cache.encode = encode
    Cache.decode = decode

    function encodingLength (obj) {
      var length = 0
      if (!defined(obj.start)) throw new Error("start is required")
      var len = encodings.varint.encodingLength(obj.start)
      length += 1 + len
      if (!defined(obj.end)) throw new Error("end is required")
      var len = encodings.varint.encodingLength(obj.end)
      length += 1 + len
      if (defined(obj.blocks)) {
        var packedLen = 0
        for (var i = 0; i < obj.blocks.length; i++) {
          if (!defined(obj.blocks[i])) continue
          var len = encodings.varint.encodingLength(obj.blocks[i])
          packedLen += len
        }
        if (packedLen) {
          length += 1 + packedLen + varint.encodingLength(packedLen)
        }
      }
      return length
    }

    function encode (obj, buf, offset) {
      if (!offset) offset = 0
      if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
      var oldOffset = offset
      if (!defined(obj.start)) throw new Error("start is required")
      buf[offset++] = 8
      encodings.varint.encode(obj.start, buf, offset)
      offset += encodings.varint.encode.bytes
      if (!defined(obj.end)) throw new Error("end is required")
      buf[offset++] = 16
      encodings.varint.encode(obj.end, buf, offset)
      offset += encodings.varint.encode.bytes
      if (defined(obj.blocks)) {
        var packedLen = 0
        for (var i = 0; i < obj.blocks.length; i++) {
          if (!defined(obj.blocks[i])) continue
          packedLen += encodings.varint.encodingLength(obj.blocks[i])
        }
        if (packedLen) {
          buf[offset++] = 26
          varint.encode(packedLen, buf, offset)
          offset += varint.encode.bytes
        }
        for (var i = 0; i < obj.blocks.length; i++) {
          if (!defined(obj.blocks[i])) continue
          encodings.varint.encode(obj.blocks[i], buf, offset)
          offset += encodings.varint.encode.bytes
        }
      }
      encode.bytes = offset - oldOffset
      return buf
    }

    function decode (buf, offset, end) {
      if (!offset) offset = 0
      if (!end) end = buf.length
      if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
      var oldOffset = offset
      var obj = {
        start: 0,
        end: 0,
        blocks: []
      }
      var found0 = false
      var found1 = false
      while (true) {
        if (end <= offset) {
          if (!found0 || !found1) throw new Error("Decoded message is not valid")
          decode.bytes = offset - oldOffset
          return obj
        }
        var prefix = varint.decode(buf, offset)
        offset += varint.decode.bytes
        var tag = prefix >> 3
        switch (tag) {
          case 1:
          obj.start = encodings.varint.decode(buf, offset)
          offset += encodings.varint.decode.bytes
          found0 = true
          break
          case 2:
          obj.end = encodings.varint.decode(buf, offset)
          offset += encodings.varint.decode.bytes
          found1 = true
          break
          case 3:
          var packedEnd = varint.decode(buf, offset)
          offset += varint.decode.bytes
          packedEnd += offset
          while (offset < packedEnd) {
            obj.blocks.push(encodings.varint.decode(buf, offset))
            offset += encodings.varint.decode.bytes
          }
          break
          default:
          offset = skip(prefix & 7, buf, offset)
        }
      }
    }
  }

  Extension.encodingLength = encodingLength
  Extension.encode = encode
  Extension.decode = decode

  function encodingLength (obj) {
    var length = 0
    if (defined(obj.cache)) {
      var len = Cache.encodingLength(obj.cache)
      length += varint.encodingLength(len)
      length += 1 + len
    }
    if (defined(obj.get)) {
      var len = Get.encodingLength(obj.get)
      length += varint.encodingLength(len)
      length += 1 + len
    }
    if (defined(obj.iterator)) {
      var len = Iterator.encodingLength(obj.iterator)
      length += varint.encodingLength(len)
      length += 1 + len
    }
    return length
  }

  function encode (obj, buf, offset) {
    if (!offset) offset = 0
    if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
    var oldOffset = offset
    if (defined(obj.cache)) {
      buf[offset++] = 10
      varint.encode(Cache.encodingLength(obj.cache), buf, offset)
      offset += varint.encode.bytes
      Cache.encode(obj.cache, buf, offset)
      offset += Cache.encode.bytes
    }
    if (defined(obj.get)) {
      buf[offset++] = 18
      varint.encode(Get.encodingLength(obj.get), buf, offset)
      offset += varint.encode.bytes
      Get.encode(obj.get, buf, offset)
      offset += Get.encode.bytes
    }
    if (defined(obj.iterator)) {
      buf[offset++] = 26
      varint.encode(Iterator.encodingLength(obj.iterator), buf, offset)
      offset += varint.encode.bytes
      Iterator.encode(obj.iterator, buf, offset)
      offset += Iterator.encode.bytes
    }
    encode.bytes = offset - oldOffset
    return buf
  }

  function decode (buf, offset, end) {
    if (!offset) offset = 0
    if (!end) end = buf.length
    if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
    var oldOffset = offset
    var obj = {
      cache: null,
      get: null,
      iterator: null
    }
    while (true) {
      if (end <= offset) {
        decode.bytes = offset - oldOffset
        return obj
      }
      var prefix = varint.decode(buf, offset)
      offset += varint.decode.bytes
      var tag = prefix >> 3
      switch (tag) {
        case 1:
        var len = varint.decode(buf, offset)
        offset += varint.decode.bytes
        obj.cache = Cache.decode(buf, offset, offset + len)
        offset += Cache.decode.bytes
        break
        case 2:
        var len = varint.decode(buf, offset)
        offset += varint.decode.bytes
        obj.get = Get.decode(buf, offset, offset + len)
        offset += Get.decode.bytes
        break
        case 3:
        var len = varint.decode(buf, offset)
        offset += varint.decode.bytes
        obj.iterator = Iterator.decode(buf, offset, offset + len)
        offset += Iterator.decode.bytes
        break
        default:
        offset = skip(prefix & 7, buf, offset)
      }
    }
  }
}

function defined (val) {
  return val !== null && val !== undefined && (typeof val !== 'number' || !isNaN(val))
}
{
  "name": "hyperbee",
  "version": "2.27.3",
  "description": "An append-only B-tree running on a Hypercore.",
  "main": "index.js",
  "files": [
    "index.js",
    "lib/**.js",
    "iterators/**.js"
  ],
  "dependencies": {
    "b4a": "^1.6.0",
    "codecs": "^3.0.0",
    "debounceify": "^1.0.0",
    "hypercore-errors": "^1.0.0",
    "mutexify": "^1.4.0",
    "protocol-buffers-encodings": "^1.2.0",
    "rache": "^1.0.0",
    "ready-resource": "^1.0.0",
    "resolve-reject-promise": "^1.1.0",
    "safety-catch": "^1.0.2",
    "streamx": "^2.12.4",
    "unslab": "^1.2.0"
  },
  "devDependencies": {
    "bare-process": "^4.2.2",
    "brittle": "^3.1.0",
    "hypercore": "^11.0.0",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "protocol-buffers": "^4.2.0",
    "sub-encoder": "^1.0.6",
    "tree-to-string": "^1.1.1"
  },
  "imports": {
    "process": {
      "bare": "bare-process",
      "default": "process"
    }
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test/*.js",
    "test:bare": "brittle-bare test/*.js",
    "protobuf": "protocol-buffers schema.proto -o ./lib/messages.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/hyperbee.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/hyperbee/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperbee"
}
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const b4a = require('b4a')

// https://en.wikipedia.org/wiki/Merkle_tree#Second_preimage_attack
const LEAF_TYPE = b4a.from([0])
const PARENT_TYPE = b4a.from([1])
const ROOT_TYPE = b4a.from([2])

const HYPERCORE = b4a.from('hypercore')

exports.keyPair = function (seed) {
  // key pairs might stay around for a while, so better not to use a default slab to avoid retaining it completely
  const slab = b4a.allocUnsafeSlow(
    sodium.crypto_sign_PUBLICKEYBYTES + sodium.crypto_sign_SECRETKEYBYTES
  )
  const publicKey = slab.subarray(0, sodium.crypto_sign_PUBLICKEYBYTES)
  const secretKey = slab.subarray(sodium.crypto_sign_PUBLICKEYBYTES)

  if (seed) sodium.crypto_sign_seed_keypair(publicKey, secretKey, seed)
  else sodium.crypto_sign_keypair(publicKey, secretKey)

  return {
    publicKey,
    secretKey
  }
}

exports.validateKeyPair = function (keyPair) {
  const pk = b4a.allocUnsafe(sodium.crypto_sign_PUBLICKEYBYTES)
  sodium.crypto_sign_ed25519_sk_to_pk(pk, keyPair.secretKey)
  return b4a.equals(pk, keyPair.publicKey)
}

exports.sign = function (message, secretKey) {
  // Dedicated slab for the signature, to avoid retaining unneeded mem and for security
  const signature = b4a.allocUnsafeSlow(sodium.crypto_sign_BYTES)
  sodium.crypto_sign_detached(signature, message, secretKey)
  return signature
}

exports.verify = function (message, signature, publicKey) {
  if (signature.byteLength !== sodium.crypto_sign_BYTES) return false
  if (publicKey.byteLength !== sodium.crypto_sign_PUBLICKEYBYTES) return false
  return sodium.crypto_sign_verify_detached(signature, message, publicKey)
}

exports.encrypt = function (message, publicKey) {
  const ciphertext = b4a.alloc(message.byteLength + sodium.crypto_box_SEALBYTES)
  sodium.crypto_box_seal(ciphertext, message, publicKey)
  return ciphertext
}

exports.decrypt = function (ciphertext, keyPair) {
  if (ciphertext.byteLength < sodium.crypto_box_SEALBYTES) return null

  const plaintext = b4a.alloc(ciphertext.byteLength - sodium.crypto_box_SEALBYTES)

  if (!sodium.crypto_box_seal_open(plaintext, ciphertext, keyPair.publicKey, keyPair.secretKey)) {
    return null
  }

  return plaintext
}

exports.encryptionKeyPair = function (seed) {
  const publicKey = b4a.alloc(sodium.crypto_box_PUBLICKEYBYTES)
  const secretKey = b4a.alloc(sodium.crypto_box_SECRETKEYBYTES)

  if (seed) {
    sodium.crypto_box_seed_keypair(publicKey, secretKey, seed)
  } else {
    sodium.crypto_box_keypair(publicKey, secretKey)
  }

  return {
    publicKey,
    secretKey
  }
}

exports.data = function (data) {
  const out = b4a.allocUnsafe(32)

  sodium.crypto_generichash_batch(out, [LEAF_TYPE, c.encode(c.uint64, data.byteLength), data])

  return out
}

exports.parent = function (a, b) {
  if (a.index > b.index) {
    const tmp = a
    a = b
    b = tmp
  }

  const out = b4a.allocUnsafe(32)

  sodium.crypto_generichash_batch(out, [
    PARENT_TYPE,
    c.encode(c.uint64, a.size + b.size),
    a.hash,
    b.hash
  ])

  return out
}

exports.tree = function (roots, out) {
  const buffers = new Array(3 * roots.length + 1)
  let j = 0

  buffers[j++] = ROOT_TYPE

  for (let i = 0; i < roots.length; i++) {
    const r = roots[i]
    buffers[j++] = r.hash
    buffers[j++] = c.encode(c.uint64, r.index)
    buffers[j++] = c.encode(c.uint64, r.size)
  }

  if (!out) out = b4a.allocUnsafe(32)
  sodium.crypto_generichash_batch(out, buffers)
  return out
}

exports.hash = function (data, out) {
  if (!out) out = b4a.allocUnsafe(32)
  if (!Array.isArray(data)) data = [data]

  sodium.crypto_generichash_batch(out, data)

  return out
}

exports.randomBytes = function (n) {
  const buf = b4a.allocUnsafe(n)
  sodium.randombytes_buf(buf)
  return buf
}

exports.discoveryKey = function (key) {
  if (!key || key.byteLength !== 32) throw new Error('Must pass a 32 byte buffer')
  // Discovery keys might stay around for a while, so better not to use slab memory (for better gc)
  const digest = b4a.allocUnsafeSlow(32)
  sodium.crypto_generichash(digest, HYPERCORE, key)
  return digest
}

if (sodium.sodium_free) {
  exports.free = function (secureBuf) {
    if (secureBuf.secure) sodium.sodium_free(secureBuf)
  }
} else {
  exports.free = function () {}
}

exports.namespace = function (name, count) {
  const ids = typeof count === 'number' ? range(count) : count

  // Namespaces are long-lived, so better to use a dedicated slab
  const buf = b4a.allocUnsafeSlow(32 * ids.length)

  const list = new Array(ids.length)

  // ns is ephemeral, so default slab
  const ns = b4a.allocUnsafe(33)
  sodium.crypto_generichash(ns.subarray(0, 32), typeof name === 'string' ? b4a.from(name) : name)

  for (let i = 0; i < list.length; i++) {
    list[i] = buf.subarray(32 * i, 32 * i + 32)
    ns[32] = ids[i]
    sodium.crypto_generichash(list[i], ns)
  }

  return list
}

function range(count) {
  const arr = new Array(count)
  for (let i = 0; i < count; i++) arr[i] = i
  return arr
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "hypercore-crypto",
  "version": "3.7.0",
  "description": "The crypto primitives used in hypercore, extracted into a separate module",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.6.6",
    "compact-encoding": "^3.0.0",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "brittle": "^3.5.0",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/hypercore-crypto.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/hypercore-crypto/issues"
  },
  "homepage": "https://github.com/mafintosh/hypercore-crypto"
}
const IdEnc = require('hypercore-id-encoding')

module.exports = class HypercoreError extends Error {
  constructor (msg, code, fn = HypercoreError, discoveryKey = null) {
    if (discoveryKey) msg = `${msg} (discovery key: ${IdEnc.normalize(discoveryKey)})`
    super(`${code}: ${msg}`)

    this.code = code
    this.discoveryKey = discoveryKey

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name () {
    return 'HypercoreError'
  }

  static ASSERTION (msg, discoveryKey = null) { // ERR_ASSERTION is picked up by safety-catch also
    return new HypercoreError(msg, 'ERR_ASSERTION', HypercoreError.ASSERT, discoveryKey)
  }

  static BAD_ARGUMENT (msg, discoveryKey = null) {
    return new HypercoreError(msg, 'BAD_ARGUMENT', HypercoreError.BAD_ARGUMENT, discoveryKey)
  }

  static STORAGE_EMPTY (msg, discoveryKey = null) {
    return new HypercoreError(msg, 'STORAGE_EMPTY', HypercoreError.STORAGE_EMPTY, discoveryKey)
  }

  static STORAGE_CONFLICT (msg, discoveryKey = null) {
    return new HypercoreError(msg, 'STORAGE_CONFLICT', HypercoreError.STORAGE_CONFLICT, discoveryKey)
  }

  static INVALID_SIGNATURE (msg, discoveryKey = null) {
    return new HypercoreError(msg, 'INVALID_SIGNATURE', HypercoreError.INVALID_SIGNATURE, discoveryKey)
  }

  static INVALID_CAPABILITY (msg, discoveryKey = null) {
    return new HypercoreError(msg, 'INVALID_CAPABILITY', HypercoreError.INVALID_CAPABILITY, discoveryKey)
  }

  static INVALID_CHECKSUM (msg = 'Invalid checksum', discoveryKey = null) {
    return new HypercoreError(msg, 'INVALID_CHECKSUM', HypercoreError.INVALID_CHECKSUM, discoveryKey)
  }

  static INVALID_OPERATION (msg, discoveryKey = null) {
    return new HypercoreError(msg, 'INVALID_OPERATION', HypercoreError.INVALID_OPERATION, discoveryKey)
  }

  static INVALID_PROOF (msg = 'Proof not verifiable', discoveryKey = null) {
    return new HypercoreError(msg, 'INVALID_PROOF', HypercoreError.INVALID_PROOF, discoveryKey)
  }

  static BLOCK_NOT_AVAILABLE (msg = 'Block is not available', discoveryKey = null) {
    return new HypercoreError(msg, 'BLOCK_NOT_AVAILABLE', HypercoreError.BLOCK_NOT_AVAILABLE, discoveryKey)
  }

  static SNAPSHOT_NOT_AVAILABLE (msg = 'Snapshot is not available', discoveryKey = null) {
    return new HypercoreError(msg, 'SNAPSHOT_NOT_AVAILABLE', HypercoreError.SNAPSHOT_NOT_AVAILABLE, discoveryKey)
  }

  static REQUEST_CANCELLED (msg = 'Request was cancelled', discoveryKey = null) {
    return new HypercoreError(msg, 'REQUEST_CANCELLED', HypercoreError.REQUEST_CANCELLED, discoveryKey)
  }

  static REQUEST_TIMEOUT (msg = 'Request timed out', discoveryKey = null) {
    return new HypercoreError(msg, 'REQUEST_TIMEOUT', HypercoreError.REQUEST_TIMEOUT, discoveryKey)
  }

  static SESSION_NOT_WRITABLE (msg = 'Session is not writable', discoveryKey = null) {
    return new HypercoreError(msg, 'SESSION_NOT_WRITABLE', HypercoreError.SESSION_NOT_WRITABLE, discoveryKey)
  }

  static SESSION_CLOSED (msg = 'Session is closed', discoveryKey = null) {
    return new HypercoreError(msg, 'SESSION_CLOSED', HypercoreError.SESSION_CLOSED, discoveryKey)
  }

  static BATCH_UNFLUSHED (msg = 'Batch not yet flushed', discoveryKey = null) {
    return new HypercoreError(msg, 'BATCH_UNFLUSHED', HypercoreError.BATCH_UNFLUSHED, discoveryKey)
  }

  static BATCH_ALREADY_EXISTS (msg = 'Batch already exists', discoveryKey = null) {
    return new HypercoreError(msg, 'BATCH_ALREADY_EXISTS', HypercoreError.BATCH_ALREADY_EXISTS, discoveryKey)
  }

  static BATCH_ALREADY_FLUSHED (msg = 'Batch has already been flushed', discoveryKey = null) {
    return new HypercoreError(msg, 'BATCH_ALREADY_FLUSHED', HypercoreError.BATCH_ALREADY_FLUSHED, discoveryKey)
  }

  static OPLOG_CORRUPT (msg = 'Oplog file appears corrupt or out of date', discoveryKey = null) {
    return new HypercoreError(msg, 'OPLOG_CORRUPT', HypercoreError.OPLOG_CORRUPT, discoveryKey)
  }

  static OPLOG_HEADER_OVERFLOW (msg = 'Oplog header exceeds page size', discoveryKey = null) {
    return new HypercoreError(msg, 'OPLOG_HEADER_OVERFLOW', HypercoreError.OPLOG_HEADER_OVERFLOW, discoveryKey)
  }

  static INVALID_OPLOG_VERSION (msg = 'Invalid header version', discoveryKey = null) {
    return new HypercoreError(msg, 'INVALID_OPLOG_VERSION', HypercoreError.INVALID_OPLOG_VERSION, discoveryKey)
  }

  static WRITE_FAILED (msg = 'Write to storage failed', discoveryKey = null) {
    return new HypercoreError(msg, 'WRITE_FAILED', HypercoreError.WRITE_FAILED, discoveryKey)
  }

  static DECODING_ERROR (msg = 'Decoding error', discoveryKey = null) {
    return new HypercoreError(msg, 'DECODING_ERROR', HypercoreError.DECODING_ERROR, discoveryKey)
  }

  static SESSION_MOVED (msg = 'Session moved', discoveryKey = null) {
    return new HypercoreError(msg, 'SESSION_MOVED', HypercoreError.SESSION_MOVED, discoveryKey)
  }
}
{
  "name": "hypercore-errors",
  "version": "1.5.0",
  "description": "Hypercore errors",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/hypercore-errors.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/hypercore-errors/issues"
  },
  "homepage": "https://github.com/holepunchto/hypercore-errors#readme",
  "devDependencies": {
    "b4a": "^1.6.7",
    "brittle": "^3.1.3",
    "standard": "^17.0.0"
  },
  "dependencies": {
    "hypercore-id-encoding": "^1.3.0"
  }
}
const z32 = require('z32')
const b4a = require('b4a')

module.exports = {
  encode,
  decode,
  normalize,
  isValid
}

function encode (key) {
  if (!b4a.isBuffer(key)) throw new Error('Key must be a Buffer')
  if (key.byteLength !== 32) throw new Error('Key must be 32-bytes long')
  return z32.encode(key)
}

function decode (id) {
  if (b4a.isBuffer(id)) {
    if (id.byteLength !== 32) throw new Error('ID must be 32-bytes long')
    return id
  }
  if (typeof id === 'string') {
    if (id.startsWith('pear://')) id = id.slice(7).split('/')[0]
    if (id.length === 52) return z32.decode(id)
    if (id.length === 64) {
      const buf = b4a.from(id, 'hex')
      if (buf.byteLength === 32) return buf
    }
  }
  throw new Error('Invalid Hypercore key')
}

function normalize (any) {
  return encode(decode(any))
}

function isValid (any) {
  try {
    decode(any)
    return true
  } catch {
    return false
  }
}
{
  "name": "hypercore-id-encoding",
  "version": "1.3.0",
  "description": "Convert Hypercore keys to/from z-base32 or hex",
  "main": "index.js",
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.5.3",
    "z32": "^1.0.0"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "hypercore": "^10.0.0",
    "random-access-memory": "^6.0.0",
    "standard": "^17.1.0"
  },
  "license": "Apache-2.0",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/hypercore-id-encoding.git"
  },
  "keywords": [],
  "author": "",
  "bugs": {
    "url": "https://github.com/holepunchto/hypercore-id-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/hypercore-id-encoding#readme"
}
function headLegacyMap(m) {
  return {
    version: 2, // version bumped from 1
    cores: m.allocated.cores,
    datas: m.allocated.datas,
    groups: 0,
    seed: m.seed,
    defaultDiscoveryKey: m.defaultDiscoveryKey
  }
}

module.exports = {
  headLegacyMap
}
// This file is autogenerated by the hyperschema compiler
// Schema Version: 2
/* eslint-disable camelcase */
/* eslint-disable quotes */
/* eslint-disable space-before-function-paren */

const { c } = require('hyperschema/runtime')
const external0 = require('../../external.js')

const VERSION = 2

// eslint-disable-next-line no-unused-vars
let version = VERSION

// @corestore/allocated
const encoding0 = {
  preencode(state, m) {
    c.uint.preencode(state, m.cores)
    c.uint.preencode(state, m.datas)
  },
  encode(state, m) {
    c.uint.encode(state, m.cores)
    c.uint.encode(state, m.datas)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const r1 = c.uint.decode(state)

    return {
      cores: r0,
      datas: r1
    }
  }
}

// @corestore/head-v1
const encoding1 = {
  preencode(state, m) {
    state.end++ // max flag is 4 so always one byte

    if (m.allocated) encoding0.preencode(state, m.allocated)
    if (m.seed) c.fixed32.preencode(state, m.seed)
    if (m.defaultDiscoveryKey) c.fixed32.preencode(state, m.defaultDiscoveryKey)
  },
  encode(state, m) {
    const flags = (m.allocated ? 1 : 0) | (m.seed ? 2 : 0) | (m.defaultDiscoveryKey ? 4 : 0)

    c.uint.encode(state, flags)

    if (m.allocated) encoding0.encode(state, m.allocated)
    if (m.seed) c.fixed32.encode(state, m.seed)
    if (m.defaultDiscoveryKey) c.fixed32.encode(state, m.defaultDiscoveryKey)
  },
  decode(state) {
    const v = c.uint.decode(state)
    const flags = c.uint.decode(state)

    return {
      version: v,
      allocated: (flags & 1) !== 0 ? encoding0.decode(state) : null,
      seed: (flags & 2) !== 0 ? c.fixed32.decode(state) : null,
      defaultDiscoveryKey: (flags & 4) !== 0 ? c.fixed32.decode(state) : null
    }
  }
}

// @corestore/head-v2
const encoding2 = {
  preencode(state, m) {
    c.uint.preencode(state, m.cores)
    c.uint.preencode(state, m.datas)
    c.uint.preencode(state, m.groups)
    state.end++ // max flag is 2 so always one byte

    if (m.seed) c.fixed32.preencode(state, m.seed)
    if (m.defaultDiscoveryKey) c.fixed32.preencode(state, m.defaultDiscoveryKey)
  },
  encode(state, m) {
    const flags = (m.seed ? 1 : 0) | (m.defaultDiscoveryKey ? 2 : 0)

    c.uint.encode(state, m.cores)
    c.uint.encode(state, m.datas)
    c.uint.encode(state, m.groups)
    c.uint.encode(state, flags)

    if (m.seed) c.fixed32.encode(state, m.seed)
    if (m.defaultDiscoveryKey) c.fixed32.encode(state, m.defaultDiscoveryKey)
  },
  decode(state) {
    const v = c.uint.decode(state)
    const r0 = c.uint.decode(state)
    const r1 = c.uint.decode(state)
    const r2 = c.uint.decode(state)
    const flags = c.uint.decode(state)

    return {
      version: v,
      cores: r0,
      datas: r1,
      groups: r2,
      seed: (flags & 1) !== 0 ? c.fixed32.decode(state) : null,
      defaultDiscoveryKey: (flags & 2) !== 0 ? c.fixed32.decode(state) : null
    }
  }
}

// @corestore/head
const encoding3 = {
  preencode(state, m) {
    c.uint.preencode(state, m.version)
    switch (m.version) {
      case 0:
      case 1:
        encoding1.preencode(state, m)
        break
      case 2:
        encoding2.preencode(state, m)
        break
      default:
        throw new Error('Unsupported version')
    }
  },
  encode(state, m) {
    c.uint.encode(state, m.version)
    switch (m.version) {
      case 0:
      case 1:
        encoding1.encode(state, m)
        break
      case 2:
        encoding2.encode(state, m)
        break
      default:
        throw new Error('Unsupported version')
    }
  },
  decode(state) {
    const start = state.start
    const v = c.uint.decode(state)
    state.start = start
    switch (v) {
      case 0:
      case 1: {
        const decoded = encoding1.decode(state)
        const map = external0.headLegacyMap
        return map(decoded)
      }
      case 2: {
        const decoded = encoding2.decode(state)
        return decoded
      }
      default:
        throw new Error('Unsupported version')
    }
  }
}

// @corestore/alias
const encoding4 = {
  preencode(state, m) {
    c.string.preencode(state, m.name)
    c.fixed32.preencode(state, m.namespace)
  },
  encode(state, m) {
    c.string.encode(state, m.name)
    c.fixed32.encode(state, m.namespace)
  },
  decode(state) {
    const r0 = c.string.decode(state)
    const r1 = c.fixed32.decode(state)

    return {
      name: r0,
      namespace: r1
    }
  }
}

// @corestore/core
const encoding5 = {
  preencode(state, m) {
    c.uint.preencode(state, m.version)
    c.uint.preencode(state, m.corePointer)
    c.uint.preencode(state, m.dataPointer)
    state.end++ // max flag is 1 so always one byte

    if (m.alias) encoding4.preencode(state, m.alias)
  },
  encode(state, m) {
    const flags = m.alias ? 1 : 0

    c.uint.encode(state, m.version)
    c.uint.encode(state, m.corePointer)
    c.uint.encode(state, m.dataPointer)
    c.uint.encode(state, flags)

    if (m.alias) encoding4.encode(state, m.alias)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const r1 = c.uint.decode(state)
    const r2 = c.uint.decode(state)
    const flags = c.uint.decode(state)

    return {
      version: r0,
      corePointer: r1,
      dataPointer: r2,
      alias: (flags & 1) !== 0 ? encoding4.decode(state) : null
    }
  }
}

const encoding6_enum = {
  blake2b: 'blake2b'
}

// @core/hashes enum
const encoding6 = {
  preencode(state, m) {
    state.end++ // max enum is 0 so always one byte
  },
  encode(state, m) {
    switch (m) {
      case 'blake2b':
        c.uint.encode(state, 0)
        break
      default:
        throw new Error('Unknown enum')
    }
  },
  decode(state) {
    switch (c.uint.decode(state)) {
      case 0:
        return 'blake2b'
      default:
        return null
    }
  }
}

const encoding7_enum = {
  ed25519: 'ed25519'
}

// @core/signatures enum
const encoding7 = {
  preencode(state, m) {
    state.end++ // max enum is 0 so always one byte
  },
  encode(state, m) {
    switch (m) {
      case 'ed25519':
        c.uint.encode(state, 0)
        break
      default:
        throw new Error('Unknown enum')
    }
  },
  decode(state) {
    switch (c.uint.decode(state)) {
      case 0:
        return 'ed25519'
      default:
        return null
    }
  }
}

// @core/tree-node
const encoding8 = {
  preencode(state, m) {
    c.uint.preencode(state, m.index)
    c.uint.preencode(state, m.size)
    c.fixed32.preencode(state, m.hash)
  },
  encode(state, m) {
    c.uint.encode(state, m.index)
    c.uint.encode(state, m.size)
    c.fixed32.encode(state, m.hash)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const r1 = c.uint.decode(state)
    const r2 = c.fixed32.decode(state)

    return {
      index: r0,
      size: r1,
      hash: r2
    }
  }
}

// @core/signer
const encoding9 = {
  preencode(state, m) {
    encoding7.preencode(state, m.signature)
    c.fixed32.preencode(state, m.namespace)
    c.fixed32.preencode(state, m.publicKey)
  },
  encode(state, m) {
    encoding7.encode(state, m.signature)
    c.fixed32.encode(state, m.namespace)
    c.fixed32.encode(state, m.publicKey)
  },
  decode(state) {
    const r0 = encoding7.decode(state)
    const r1 = c.fixed32.decode(state)
    const r2 = c.fixed32.decode(state)

    return {
      signature: r0,
      namespace: r1,
      publicKey: r2
    }
  }
}

// @core/prologue
const encoding10 = {
  preencode(state, m) {
    c.fixed32.preencode(state, m.hash)
    c.uint.preencode(state, m.length)
  },
  encode(state, m) {
    c.fixed32.encode(state, m.hash)
    c.uint.encode(state, m.length)
  },
  decode(state) {
    const r0 = c.fixed32.decode(state)
    const r1 = c.uint.decode(state)

    return {
      hash: r0,
      length: r1
    }
  }
}

// @core/manifest.signers
const encoding11_4 = c.array(encoding9)
// @core/manifest.linked
const encoding11_6 = c.array(c.fixed32)

// @core/manifest
const encoding11 = {
  preencode(state, m) {
    c.uint.preencode(state, m.version)
    state.end++ // max flag is 8 so always one byte
    encoding6.preencode(state, m.hash)
    c.uint.preencode(state, m.quorum)
    encoding11_4.preencode(state, m.signers)

    if (m.prologue) encoding10.preencode(state, m.prologue)
    if (m.linked) encoding11_6.preencode(state, m.linked)
    if (m.userData) c.buffer.preencode(state, m.userData)
  },
  encode(state, m) {
    const flags =
      (m.allowPatch ? 1 : 0) | (m.prologue ? 2 : 0) | (m.linked ? 4 : 0) | (m.userData ? 8 : 0)

    c.uint.encode(state, m.version)
    c.uint.encode(state, flags)
    encoding6.encode(state, m.hash)
    c.uint.encode(state, m.quorum)
    encoding11_4.encode(state, m.signers)

    if (m.prologue) encoding10.encode(state, m.prologue)
    if (m.linked) encoding11_6.encode(state, m.linked)
    if (m.userData) c.buffer.encode(state, m.userData)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const flags = c.uint.decode(state)

    return {
      version: r0,
      hash: encoding6.decode(state),
      quorum: c.uint.decode(state),
      allowPatch: (flags & 1) !== 0,
      signers: encoding11_4.decode(state),
      prologue: (flags & 2) !== 0 ? encoding10.decode(state) : null,
      linked: (flags & 4) !== 0 ? encoding11_6.decode(state) : null,
      userData: (flags & 8) !== 0 ? c.buffer.decode(state) : null
    }
  }
}

// @core/keyPair
const encoding12 = {
  preencode(state, m) {
    c.buffer.preencode(state, m.publicKey)
    c.optionalBuffer.preencode(state, m.secretKey)
  },
  encode(state, m) {
    c.buffer.encode(state, m.publicKey)
    c.optionalBuffer.encode(state, m.secretKey)
  },
  decode(state) {
    const r0 = c.buffer.decode(state)
    const r1 = c.optionalBuffer.decode(state)

    return {
      publicKey: r0,
      secretKey: r1
    }
  }
}

// @core/group
const encoding13 = {
  preencode(state, m) {
    state.end++ // max flag is 2 so always one byte

    if (m.key) c.fixed32.preencode(state, m.key)
    if (m.pointer) c.uint.preencode(state, m.pointer)
  },
  encode(state, m) {
    const flags = (m.key ? 1 : 0) | (m.pointer ? 2 : 0)

    c.uint.encode(state, flags)

    if (m.key) c.fixed32.encode(state, m.key)
    if (m.pointer) c.uint.encode(state, m.pointer)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      key: (flags & 1) !== 0 ? c.fixed32.decode(state) : null,
      pointer: (flags & 2) !== 0 ? c.uint.decode(state) : 0
    }
  }
}

// @core/auth.manifest
const encoding14_2 = c.frame(encoding11)

// @core/auth
const encoding14 = {
  preencode(state, m) {
    c.fixed32.preencode(state, m.key)
    c.fixed32.preencode(state, m.discoveryKey)
    state.end++ // max flag is 4 so always one byte

    if (m.manifest) encoding14_2.preencode(state, m.manifest)
    if (m.keyPair) encoding12.preencode(state, m.keyPair)
    if (m.encryptionKey) c.buffer.preencode(state, m.encryptionKey)
  },
  encode(state, m) {
    const flags = (m.manifest ? 1 : 0) | (m.keyPair ? 2 : 0) | (m.encryptionKey ? 4 : 0)

    c.fixed32.encode(state, m.key)
    c.fixed32.encode(state, m.discoveryKey)
    c.uint.encode(state, flags)

    if (m.manifest) encoding14_2.encode(state, m.manifest)
    if (m.keyPair) encoding12.encode(state, m.keyPair)
    if (m.encryptionKey) c.buffer.encode(state, m.encryptionKey)
  },
  decode(state) {
    const r0 = c.fixed32.decode(state)
    const r1 = c.fixed32.decode(state)
    const flags = c.uint.decode(state)

    return {
      key: r0,
      discoveryKey: r1,
      manifest: (flags & 1) !== 0 ? encoding14_2.decode(state) : null,
      keyPair: (flags & 2) !== 0 ? encoding12.decode(state) : null,
      encryptionKey: (flags & 4) !== 0 ? c.buffer.decode(state) : null
    }
  }
}

// @core/head
const encoding15 = {
  preencode(state, m) {
    c.uint.preencode(state, m.fork)
    c.uint.preencode(state, m.length)
    c.fixed32.preencode(state, m.rootHash)
    c.optionalBuffer.preencode(state, m.signature)
    state.end++ // max flag is 1 so always one byte

    if (version >= 2 && m.timestamp) c.uint64.preencode(state, m.timestamp)
  },
  encode(state, m) {
    const flags = version >= 2 && m.timestamp ? 1 : 0

    c.uint.encode(state, m.fork)
    c.uint.encode(state, m.length)
    c.fixed32.encode(state, m.rootHash)
    c.optionalBuffer.encode(state, m.signature)
    c.uint.encode(state, flags)

    if (version >= 2 && m.timestamp) c.uint64.encode(state, m.timestamp)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const r1 = c.uint.decode(state)
    const r2 = c.fixed32.decode(state)
    const r3 = c.optionalBuffer.decode(state)
    const flags = state.start < state.end ? c.uint.decode(state) : 0

    return {
      fork: r0,
      length: r1,
      rootHash: r2,
      signature: r3,
      timestamp: version >= 2 && (flags & 1) !== 0 ? c.uint64.decode(state) : 0
    }
  }
}

// @core/hints
const encoding16 = {
  preencode(state, m) {
    state.end++ // max flag is 4 so always one byte

    if (m.contiguousLength) c.uint.preencode(state, m.contiguousLength)
    if (m.remoteContiguousLength) c.uint.preencode(state, m.remoteContiguousLength)
    if (m.recovering) c.uint.preencode(state, m.recovering)
  },
  encode(state, m) {
    const flags =
      (m.contiguousLength ? 1 : 0) | (m.remoteContiguousLength ? 2 : 0) | (m.recovering ? 4 : 0)

    c.uint.encode(state, flags)

    if (m.contiguousLength) c.uint.encode(state, m.contiguousLength)
    if (m.remoteContiguousLength) c.uint.encode(state, m.remoteContiguousLength)
    if (m.recovering) c.uint.encode(state, m.recovering)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      contiguousLength: (flags & 1) !== 0 ? c.uint.decode(state) : 0,
      remoteContiguousLength: (flags & 2) !== 0 ? c.uint.decode(state) : 0,
      recovering: (flags & 4) !== 0 ? c.uint.decode(state) : 0
    }
  }
}

// @core/session
const encoding17 = {
  preencode(state, m) {
    c.string.preencode(state, m.name)
    c.uint.preencode(state, m.dataPointer)
  },
  encode(state, m) {
    c.string.encode(state, m.name)
    c.uint.encode(state, m.dataPointer)
  },
  decode(state) {
    const r0 = c.string.decode(state)
    const r1 = c.uint.decode(state)

    return {
      name: r0,
      dataPointer: r1
    }
  }
}

// @core/sessions
const encoding18 = c.array(encoding17)

// @core/dependency
const encoding19 = {
  preencode(state, m) {
    c.uint.preencode(state, m.dataPointer)
    c.uint.preencode(state, m.length)
  },
  encode(state, m) {
    c.uint.encode(state, m.dataPointer)
    c.uint.encode(state, m.length)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const r1 = c.uint.decode(state)

    return {
      dataPointer: r0,
      length: r1
    }
  }
}

function setVersion(v) {
  version = v
}

function encode(name, value, v = VERSION) {
  version = v
  return c.encode(getEncoding(name), value)
}

function decode(name, buffer, v = VERSION) {
  version = v
  return c.decode(getEncoding(name), buffer)
}

function getEnum(name) {
  switch (name) {
    case '@core/hashes':
      return encoding6_enum
    case '@core/signatures':
      return encoding7_enum
    default:
      throw new Error('Enum not found ' + name)
  }
}

function getEncoding(name) {
  switch (name) {
    case '@corestore/allocated':
      return encoding0
    case '@corestore/head-v1':
      return encoding1
    case '@corestore/head-v2':
      return encoding2
    case '@corestore/head':
      return encoding3
    case '@corestore/alias':
      return encoding4
    case '@corestore/core':
      return encoding5
    case '@core/hashes':
      return encoding6
    case '@core/signatures':
      return encoding7
    case '@core/tree-node':
      return encoding8
    case '@core/signer':
      return encoding9
    case '@core/prologue':
      return encoding10
    case '@core/manifest':
      return encoding11
    case '@core/keyPair':
      return encoding12
    case '@core/group':
      return encoding13
    case '@core/auth':
      return encoding14
    case '@core/head':
      return encoding15
    case '@core/hints':
      return encoding16
    case '@core/session':
      return encoding17
    case '@core/sessions':
      return encoding18
    case '@core/dependency':
      return encoding19
    default:
      throw new Error('Encoder not found ' + name)
  }
}

function getStruct(name, v = VERSION) {
  const enc = getEncoding(name)
  return {
    preencode(state, m) {
      version = v
      enc.preencode(state, m)
    },
    encode(state, m) {
      version = v
      enc.encode(state, m)
    },
    decode(state) {
      version = v
      return enc.decode(state)
    }
  }
}

const resolveStruct = getStruct // compat

module.exports = {
  resolveStruct,
  getStruct,
  getEnum,
  getEncoding,
  encode,
  decode,
  setVersion,
  version
}
const RocksDB = require('rocksdb-native')
const rrp = require('resolve-reject-promise')
const ScopeLock = require('scope-lock')
const DeviceFile = require('device-file')
const path = require('path')
const fs = require('fs')
const Xache = require('xache')

const View = require('./lib/view.js')

const VERSION = 2
const COLUMN_FAMILY = 'corestore'

const { store, core } = require('./lib/keys.js')

const { CorestoreRX, CorestoreTX, CoreTX, CoreRX } = require('./lib/tx.js')

const {
  createCoreStream,
  createAliasStream,
  createDiscoveryKeyStream,
  createBlockStream,
  createBitfieldStream,
  createUserDataStream,
  createTreeNodeStream,
  createMarkStream,
  createLocalStream,
  createGroupUpdateStream
} = require('./lib/streams.js')

const EMPTY = new View()

class Atom {
  constructor(db) {
    this.db = db
    this.view = new View()
    this.flushedPromise = null
    this.flushing = false
    this.preflushes = []
    this.flushes = []
  }

  preflush(fn) {
    this.preflushes.push(fn)
  }

  onflush(fn) {
    this.flushes.push(fn)
  }

  flushed() {
    if (!this.flushing) return Promise.resolve()
    if (this.flushedPromise !== null) return this.flushedPromise.promise
    this.flushedPromise = rrp()
    return this.flushedPromise.promise
  }

  _resolve() {
    const f = this.flushedPromise
    this.flushedPromise = null
    f.resolve()
  }

  async flush() {
    if (this.flushing) throw new Error('Atom already flushing')
    this.flushing = true

    try {
      const plen = this.preflushes.length
      for (let i = 0; i < plen; i++) this.preflushes[i]()

      await View.flush(this.view.changes, this.db)

      const promises = []
      const len = this.flushes.length // in case of reentry
      for (let i = 0; i < len; i++) promises.push(this.flushes[i]())

      await Promise.all(promises)
    } finally {
      this.view.reset()
      this.flushing = false
      if (this.flushedPromise !== null) this._resolve()
    }
  }
}

class HypercoreStorage {
  constructor(store, db, treeCache, core, view, atom) {
    this.store = store
    this.db = db
    this.core = core
    this.view = view
    this.atom = atom

    this.view.readStart()
    this.treeCache = treeCache
  }

  get readOnly() {
    return this.store.readOnly
  }

  get dependencies() {
    return this.core.dependencies
  }

  getDependencyLength() {
    return this.core.dependencies.length
      ? this.core.dependencies[this.core.dependencies.length - 1].length
      : -1
  }

  getDependency(length) {
    for (let i = this.core.dependencies.length - 1; i >= 0; i--) {
      const dep = this.core.dependencies[i]
      if (dep.length < length) return dep
    }

    return null
  }

  setDependencyHead(dep) {
    if (dep === null) {
      this.core.dependencies = []
      return
    }

    const deps = this.core.dependencies

    for (let i = deps.length - 1; i >= 0; i--) {
      const d = deps[i]

      if (d.dataPointer !== dep.dataPointer) continue

      // check if nothing changed
      if (d.length === dep.length && i === deps.length - 1) return

      this.core = {
        corePointer: this.core.corePointer,
        dataPointer: this.core.dataPointer,
        dependencies: deps.slice(0, i + 1)
      }

      this.core.dependencies[i] = {
        dataPointer: dep.dataPointer,
        length: dep.length
      }
      return // updated head so done
    }

    this.core.dependencies = [
      {
        dataPointer: dep.dataPointer,
        length: dep.length
      }
    ]
  }

  // TODO: this might have to be async if the dependents have changed, but prop ok for now
  updateDependencyLength(length, truncated) {
    const deps = this.core.dependencies

    const i = this.findDependencyIndex(length, truncated)
    if (i === -1) throw new Error('Dependency not found')

    this.core = {
      corePointer: this.core.corePointer,
      dataPointer: this.core.dataPointer,
      dependencies: deps.slice(0, i + 1)
    }

    if (this.core.dependencies[i].length !== length) {
      this.core.dependencies[i] = {
        dataPointer: deps[i].dataPointer,
        length
      }
    }
  }

  findDependencyIndex(length, truncated) {
    const deps = this.core.dependencies

    if (truncated) {
      for (let i = 0; i < deps.length; i++) {
        if (deps[i].length >= length) return i
      }

      return -1
    }

    for (let i = deps.length - 1; i >= 0; i--) {
      if (deps[i].length <= length) return i
    }

    return -1
  }

  get snapshotted() {
    return this.db._snapshot !== null
  }

  snapshot() {
    return new HypercoreStorage(
      this.store,
      this.db.snapshot(),
      this.treeCache,
      this.core,
      this.view.snapshot(),
      this.atom
    )
  }

  compact() {
    return Promise.all([
      this.db.compactRange(core.core(this.core.corePointer), core.core(this.core.corePointer)),
      this.db.compactRange(core.data(this.core.dataPointer), core.data(this.core.dataPointer))
    ])
  }

  atomize(atom) {
    if (this.atom && this.atom !== atom) {
      throw new Error('Cannot atomize and atomized session with a new atom')
    }

    return new HypercoreStorage(
      this.store,
      this.db.session(),
      this.treeCache,
      this.core,
      atom.view,
      atom
    )
  }

  createAtom() {
    return this.store.createAtom()
  }

  createBlockStream(opts) {
    return createBlockStream(this.core, this.db, this.view, opts)
  }

  createTreeNodeStream(opts) {
    return createTreeNodeStream(this.core, this.db, this.view, opts)
  }

  createBitfieldStream(opts) {
    return createBitfieldStream(this.core, this.db, this.view, opts)
  }

  createUserDataStream(opts) {
    return createUserDataStream(this.core, this.db, this.view, opts)
  }

  createMarkStream(opts) {
    return createMarkStream(this.core, this.db, this.view, opts)
  }

  createLocalStream(opts) {
    return createLocalStream(this.core, this.db, this.view, opts)
  }

  async resumeSession(name) {
    const rx = this.read()
    const existingSessionsPromise = rx.getSessions()

    rx.tryFlush()
    const existingSessions = await existingSessionsPromise

    const sessions = existingSessions || []
    const session = getSession(sessions, name, false)

    if (session === null) return null

    const core = {
      corePointer: this.core.corePointer,
      dataPointer: session.dataPointer,
      dependencies: []
    }

    const coreRx = new CoreRX(core, this.db, this.view, this.treeCache, this.store.stats, -1)

    const dependencyPromise = coreRx.getDependency()
    coreRx.tryFlush()

    const dependency = await dependencyPromise
    if (dependency) core.dependencies = this._addDependency(dependency)

    return new HypercoreStorage(
      this.store,
      this.db.session(),
      this.treeCache,
      core,
      this.atom ? this.view : new View(),
      this.atom
    )
  }

  async createSession(name, head) {
    const rx = this.read()

    const existingSessionsPromise = rx.getSessions()
    const existingHeadPromise = rx.getHead()

    rx.tryFlush()

    const [existingSessions, existingHead] = await Promise.all([
      existingSessionsPromise,
      existingHeadPromise
    ])
    if (head === null) head = existingHead

    if (existingHead !== null && head.length > existingHead.length) {
      throw new Error('Invalid head passed, ahead of core')
    }

    const sessions = existingSessions || []
    const session = getSession(sessions, name, true)
    const fresh = session.dataPointer === -1

    if (fresh) {
      session.dataPointer = await this.store._allocData()
    }

    const tx = this.write()

    tx.setSessions(sessions)

    const length = head === null ? 0 : head.length
    const core = {
      corePointer: this.core.corePointer,
      dataPointer: session.dataPointer,
      dependencies: this._addDependency({
        dataPointer: this.core.dataPointer,
        length
      })
    }

    const coreTx = new CoreTX(core, this.db, tx.view, tx.changes)

    if (length > 0) coreTx.setHead(head)
    coreTx.setDependency(core.dependencies[core.dependencies.length - 1])

    if (!fresh) {
      // nuke all existing state...
      coreTx.deleteBlockRange(0, -1)
      coreTx.deleteTreeNodeRange(0, -1)
      coreTx.deleteBitfieldPageRange(0, -1)
    }

    await tx.flush()

    return new HypercoreStorage(
      this.store,
      this.db.session(),
      this.treeCache,
      core,
      this.atom ? this.view : new View(),
      this.atom
    )
  }

  async createAtomicSession(atom, head) {
    const length = head === null ? 0 : head.length
    const core = {
      corePointer: this.core.corePointer,
      dataPointer: this.core.dataPointer,
      dependencies: this._addDependency(null)
    }

    const coreTx = new CoreTX(core, this.db, atom.view, [])

    if (length > 0) coreTx.setHead(head)

    await coreTx.flush()

    return this.atomize(atom)
  }

  _addDependency(dep) {
    const deps = []

    for (let i = 0; i < this.core.dependencies.length; i++) {
      const d = this.core.dependencies[i]

      if (dep !== null && d.length > dep.length) {
        if (d.dataPointer !== dep.dataPointer) {
          deps.push({ dataPointer: d.dataPointer, length: dep.length })
        }
        return deps
      }

      deps.push(d)
    }

    if (
      dep !== null &&
      (deps.length === 0 || deps[deps.length - 1].dataPointer !== dep.dataPointer)
    ) {
      deps.push(dep)
    }
    return deps
  }

  async deleteSessions() {
    const rx = this.read()
    const existingSessionsPromise = rx.getSessions()
    rx.tryFlush()

    const existingSessions = await existingSessionsPromise

    // Remove batches
    const coreTx = this.write()
    coreTx.setSessions([]) // Clear sessions record
    await coreTx.flush()

    const tx = this.db.write({ autoDestroy: true })

    for (const { dataPointer } of existingSessions) {
      const start = core.data(dataPointer)
      const end = core.data(dataPointer + 1)
      tx.tryDeleteRange(start, end)
    }

    await tx.flush()
  }

  read(fork = -1) {
    let treeCache = null
    if (!this.atom) treeCache = this.treeCache

    return new CoreRX(this.core, this.db, this.view, treeCache, this.store.stats, fork)
  }

  write() {
    return new CoreTX(this.core, this.db, this.atom ? this.view : null, [])
  }

  close() {
    if (this.view !== null) {
      this.view.readStop()
      this.view = null
    }

    return this.db.close()
  }

  static async export(ptr, db, { batches = false } = {}) {
    const rx = new CoreRX(ptr, db, EMPTY, null, null, -1)

    const core = {
      head: null,
      auth: null,
      sessions: [],
      data: null
    }

    const sessionsPromise = rx.getSessions()
    const headPromise = rx.getHead()
    const authPromise = rx.getAuth()

    rx.tryFlush()

    const [sessions, head, auth] = await Promise.all([sessionsPromise, headPromise, authPromise])

    core.head = head
    core.auth = { ...auth, keyPair: null }
    if (sessions) core.sessions = sessions.map((s) => s.name)

    const data = []

    data.push(exportData(ptr, db))

    if (batches) {
      for (const { dataPointer } of sessions) {
        data.push(exportData({ dataPointer, dependencies: [] }, db))
      }
    }

    core.data = await Promise.all(data)

    return core
  }

  static isParentStorage(storage, parent) {
    const last = getLastDependency(storage)
    return !!last && last.dataPointer === parent.core.dataPointer
  }
}

class CorestoreStorage {
  constructor(db, opts = {}) {
    const storage = typeof db === 'string' ? db : null

    this.bootstrap = storage !== null
    this.path = storage !== null ? storage : path.join(db.path, '..')
    this.alwaysRecover = !!opts.alwaysRecover
    this.readOnly = !!opts.readOnly
    this.allowBackup = !!opts.allowBackup
    this.deviceFile = null
    this.wait = !!opts.wait

    // tmp sync fix for simplicty since not super deployed yet
    if (this.bootstrap && !this.readOnly) tmpFixStorage(this.path)

    this.id = opts.id || null
    this.view = null
    this.enters = 0
    this.lock = new ScopeLock()
    this.flushing = null
    this.version = 0
    this.migrating = null

    if ((this.bootstrap && !this.readOnly && !this.allowBackup) || this.wait) {
      const corestoreFile = path.join(this.path, 'CORESTORE')

      this.deviceFile = new DeviceFile(corestoreFile, {
        lock: true,
        wait: this.wait,
        data: { id: this.id }
      })
    }

    const dbPath = path.join(this.path, 'db')

    this.stats = {
      treeCache: {
        hits: 0,
        misses: 0,
        parallel: 0,
        skips: 0
      }
    }
    this.rocks = storage === null ? db : new RocksDB(dbPath, { ...opts, lock: this.deviceFile })
    this.db = createColumnFamily(this.rocks, opts)

    const { treeCache = { maxSize: 8192 } } = opts
    this.treeCache = new Xache(treeCache)
  }

  get opened() {
    return this.db.opened
  }

  get closed() {
    return this.db.closed
  }

  async ready() {
    if (this.version === 0) await this._migrateStore()
    return this.db.ready()
  }

  compact(opts) {
    return this.db.compactRange(opts)
  }

  async audit() {
    for await (const { core } of this.createCoreStream()) {
      const coreRx = new CoreRX(core, this.db, EMPTY, this.treeCache, this.stats, -1)
      const authPromise = coreRx.getAuth()

      coreRx.tryFlush()

      const auth = await authPromise

      if (!auth.manifest || auth.manifest.version > 0) continue
      if (auth.manifest.linked === null) continue

      auth.manifest.linked = null
      const coreTx = new CoreTX(core, this.db, null, [])
      coreTx.setAuth(auth)
      await coreTx.flush()
    }
  }

  async deleteCore(ptr) {
    const rx = new CoreRX(ptr, this.db, EMPTY, this.treeCache, this.stats, -1)

    const authPromise = rx.getAuth()
    const sessionsPromise = rx.getSessions()

    rx.tryFlush()

    const auth = await authPromise
    const sessions = await sessionsPromise

    // no core stored here
    if (!auth) return

    const tx = this.db.write({ autoDestroy: true })

    tx.tryDelete(store.core(auth.discoveryKey))

    // clear core
    const start = core.core(ptr.corePointer)
    const end = core.core(ptr.corePointer + 1)
    tx.tryDeleteRange(start, end)

    if (sessions) {
      for (const { dataPointer } of sessions) {
        const start = core.data(dataPointer)
        const end = core.data(dataPointer + 1)
        tx.tryDeleteRange(start, end)
      }
    }

    return tx.flush()
  }

  static isCoreStorage(db) {
    return isCorestoreStorage(db)
  }

  static from(db) {
    if (isCorestoreStorage(db)) return db
    return new this(db)
  }

  async _flush() {
    while (this.enters > 0) {
      await this.lock.lock()
      await this.lock.unlock()
    }
  }

  async _maybeRecover(view) {
    const r = path.join(this.db.path, 'RECOVERING')
    if (!(await fileExists(r))) return
    await this.setRecovering(view)
    await fs.promises.unlink(r)
  }

  _maybeRecoverLater(err) {
    if (!shouldRecover(err) && !this.alwaysRecover) return
    fs.writeFileSync(path.join(this.db.path, 'RECOVERING'), '')
    for (const file of fs.readdirSync(this.db.path)) {
      if (file.endsWith('.log')) fs.unlinkSync(path.join(this.db.path, file))
    }
  }

  // runs pre any other mutation and read
  async _migrateStore() {
    const view = await this._enter()

    try {
      if (this.version === VERSION) return

      await this._preopen

      try {
        await this.db.ready()
      } catch (err) {
        this._maybeRecoverLater(err)
        throw err
      }

      await this._maybeRecover(view)

      const rx = new CorestoreRX(this.db, view)
      const headPromise = rx.getHead()

      rx.tryFlush()
      const head = await headPromise

      const version = head === null ? 0 : head.version
      if (version === VERSION) {
        this.version = VERSION
        return
      }

      const target = { version: VERSION, dryRun: false }

      switch (version) {
        case 0: {
          await require('./migrations/0').store(this, target)
          break
        }
        case 1: {
          // implicit migration on write
          break
        }
        default: {
          throw new Error(
            'Unsupported version: ' + version + ' - you should probably upgrade your dependencies'
          )
        }
      }

      this.version = VERSION
    } finally {
      await this._exit()
    }
  }

  // runs pre the core is returned to the user
  async _migrateCore(core, discoveryKey, version, locked) {
    const view = locked ? this.view : await this._enter()
    try {
      if (version === VERSION) return

      const target = { version: VERSION, dryRun: false }

      switch (version) {
        case 0: {
          await require('./migrations/0').core(core, target)
          break
        }
        case 1: {
          await require('./migrations/1').core(core, target)
          break
        }
        default: {
          throw new Error(
            'Unsupported version: ' + version + ' - you should probably upgrade your dependencies'
          )
        }
      }

      if (locked === false) return

      // if its locked, then move the core state into the memview
      // in case the core is reopened from the memview, pre flush

      const rx = new CorestoreRX(this.db, EMPTY)
      const tx = new CorestoreTX(view)

      const corePromise = rx.getCore(discoveryKey)
      rx.tryFlush()

      tx.putCore(discoveryKey, await corePromise)
      tx.apply()
    } finally {
      if (!locked) await this._exit()
    }
  }

  async _enter() {
    this.enters++
    await this.lock.lock()
    if (this.view === null) this.view = new View()
    return this.view
  }

  async _exit() {
    this.enters--

    if (this.flushing === null) this.flushing = rrp()
    const flushed = this.flushing.promise

    if (this.enters === 0 || this.view.size() > 128) {
      try {
        await View.flush(this.view.changes, this.db)
        this.flushing.resolve()
      } catch (err) {
        this.flushing.reject(err)
      } finally {
        this.flushing = null
        this.view = null
      }
    }

    this.lock.unlock()
    return flushed
  }

  // when used with core catches this isnt transactional for simplicity, HOWEVER, its just a number
  // so worth the tradeoff
  async _allocData() {
    let dataPointer = 0

    const view = await this._enter()
    const tx = new CorestoreTX(view)

    try {
      const head = await this._getHead(view)

      dataPointer = head.datas++

      tx.setHead(head)
      tx.apply()
    } finally {
      await this._exit()
    }

    return dataPointer
  }

  // exposes here so migrations can easily access the head in an init state
  async _getHead(view) {
    const rx = new CorestoreRX(this.db, view)
    const headPromise = rx.getHead()
    rx.tryFlush()

    const head = await headPromise
    return head === null ? initStoreHead() : head
  }

  createAtom() {
    return new Atom(this.db)
  }

  async flush() {
    await this.rocks.flush()
  }

  async close() {
    if (this.db.closed) return
    await this._flush()
    await this.db.close()
    await this.rocks.close()
    this.treeCache.destroy()
    if (this.deviceFile) await this.deviceFile.close()
  }

  async clear() {
    if (this.version === 0) await this._migrateStore()

    const view = await this._enter()
    const tx = new CorestoreTX(view)

    tx.clear()
    tx.apply()

    await this._exit()
  }

  createCoreStream() {
    // TODO: be nice to run the mgiration here also, but too much plumbing atm
    return createCoreStream(this.db, EMPTY)
  }

  createAliasStream(namespace) {
    // TODO: be nice to run the mgiration here also, but too much plumbing atm
    return createAliasStream(this.db, EMPTY, namespace)
  }

  createDiscoveryKeyStream(namespace) {
    return createDiscoveryKeyStream(this.db, EMPTY, namespace)
  }

  createGroupUpdateStream(group, { since, reverse } = {}) {
    return createGroupUpdateStream(this.db, EMPTY, group, { gte: since, reverse })
  }

  async getAlias(alias) {
    if (this.version === 0) await this._migrateStore()

    const rx = new CorestoreRX(this.db, EMPTY)
    const discoveryKeyPromise = rx.getCoreByAlias(alias)
    rx.tryFlush()
    return discoveryKeyPromise
  }

  async getSeed() {
    if (this.version === 0) await this._migrateStore()

    const rx = new CorestoreRX(this.db, EMPTY)
    const headPromise = rx.getHead()

    rx.tryFlush()

    const head = await headPromise
    return head === null ? null : head.seed
  }

  async getGroup(topic) {
    if (this.version === 0) await this._migrateStore()

    const rx = new CorestoreRX(this.db, EMPTY)
    const groupPromise = rx.getGroup(topic)
    rx.tryFlush()
    return groupPromise
  }

  async setSeed(seed, { overwrite = true } = {}) {
    if (this.version === 0) await this._migrateStore()

    const view = await this._enter()
    const tx = new CorestoreTX(view)

    try {
      const rx = new CorestoreRX(this.db, view)
      const headPromise = rx.getHead()

      rx.tryFlush()

      const head = (await headPromise) || initStoreHead()

      if (head.seed === null || overwrite) head.seed = seed
      tx.setHead(head)
      tx.apply()

      return head.seed
    } finally {
      await this._exit()
    }
  }

  async setRecovering(view = null) {
    const recovering = Date.now()
    let keys = []

    for await (const data of this.createDiscoveryKeyStream()) {
      keys.push(data)
      if (keys.length > 16 * 1024) {
        await this._flushRecovering(recovering, view, keys)
        keys = []
      }
    }

    if (keys.length) await this._flushRecovering(recovering, view, keys)
  }

  async _flushRecovering(recovering, view, keys) {
    const own = !view
    if (own) view = await this._enter()
    const tx = new CorestoreTX(view)

    try {
      const infos = await this._getInfos(keys, { auth: false, head: false, hints: true })
      for (const inf of infos) {
        tx.setCoreHints(inf.core, { ...inf.hints, recovering })
      }
      tx.apply()
    } finally {
      if (own) await this._exit()
    }
  }

  async getDefaultDiscoveryKey() {
    if (this.version === 0) await this._migrateStore()

    const rx = new CorestoreRX(this.db, EMPTY)
    const headPromise = rx.getHead()

    rx.tryFlush()

    const head = await headPromise
    return head === null ? null : head.defaultDiscoveryKey
  }

  async setDefaultDiscoveryKey(discoveryKey, { overwrite = true } = {}) {
    if (this.version === 0) await this._migrateStore()

    const view = await this._enter()
    const tx = new CorestoreTX(view)

    try {
      const rx = new CorestoreRX(this.db, view)
      const headPromise = rx.getHead()

      rx.tryFlush()

      const head = (await headPromise) || initStoreHead()

      if (head.defaultDiscoveryKey === null || overwrite) head.defaultDiscoveryKey = discoveryKey
      tx.setHead(head)
      tx.apply()

      return head.defaultDiscoveryKey
    } finally {
      await this._exit()
    }
  }

  async hasCore(discoveryKey, { ifMigrated = false } = {}) {
    if (this.version === 0) await this._migrateStore()

    const rx = new CorestoreRX(this.db, EMPTY)
    const promise = rx.getCore(discoveryKey)

    rx.tryFlush()

    const core = await promise

    if (core === null) return false
    if (core.version === 0 && ifMigrated) return false

    return true
  }

  async getAuth(discoveryKey) {
    if (this.version === 0) await this._migrateStore()

    const rx = new CorestoreRX(this.db, EMPTY)
    const corePromise = rx.getCore(discoveryKey)

    rx.tryFlush()

    const core = await corePromise
    if (core === null) return null

    const read = this.db.read({ autoDestroy: true })
    const authPromise = CoreRX.getAuth(read, core)

    read.tryFlush()

    return authPromise
  }

  async getInfo(discoveryKey, opts) {
    return (await this.getInfos([discoveryKey], opts))[0]
  }

  async getInfos(discoveryKeys, opts) {
    if (this.version === 0) await this._migrateStore()
    return this._getInfos(discoveryKeys, opts)
  }

  async _getInfos(discoveryKeys, { auth = true, head = true, hints = true } = {}) {
    const rx = new CorestoreRX(this.db, EMPTY)
    const corePromises = new Array(discoveryKeys.length)

    for (let i = 0; i < discoveryKeys.length; i++) {
      corePromises[i] = rx.getCore(discoveryKeys[i])
    }

    rx.tryFlush()

    const cores = await Promise.all(corePromises)
    const read = this.db.read({ autoDestroy: true })

    const resultPromises = new Array(cores.length)

    for (let i = 0; i < cores.length; i++) {
      resultPromises[i] = cores[i]
        ? getInfoFromBatch(read, cores[i], discoveryKeys[i], auth, head, hints)
        : null
    }

    read.tryFlush()

    return Promise.all(resultPromises)
  }

  async suspend({ log = noop } = {}) {
    await log('Suspending hypercore storage...')
    await this.db.suspend()
    await log('db suspended')
    if (this.deviceFile) {
      await log('suspend deviceFile')
      await this.deviceFile.suspend()
      await log('deviceFile suspended')
    }
  }

  async resume() {
    if (this.deviceFile) await this.deviceFile.resume()
    await this.db.resume()
  }

  async resumeCore(discoveryKey) {
    if (this.version === 0) await this._migrateStore()

    if (!discoveryKey) {
      discoveryKey = await this.getDefaultDiscoveryKey()
      if (!discoveryKey) return null
    }

    const rx = new CorestoreRX(this.db, EMPTY)
    const corePromise = rx.getCore(discoveryKey)

    rx.tryFlush()
    const core = await corePromise

    if (core === null) return null
    return this._resumeFromPointers(EMPTY, discoveryKey, false, core)
  }

  async export(discoveryKey, opts) {
    const rx = new CorestoreRX(this.db, EMPTY)
    const corePromise = rx.getCore(discoveryKey)

    rx.tryFlush()
    const core = await corePromise
    if (core === null) return null

    let { dataPointer, corePointer } = core

    const ptr = { corePointer, dataPointer, dependencies: [] }

    while (true) {
      const rx = new CoreRX(
        { dataPointer, corePointer: 0, dependencies: [] },
        this.db,
        EMPTY,
        this.treeCache,
        this.stats,
        -1
      )
      const dependencyPromise = rx.getDependency()
      rx.tryFlush()
      const dependency = await dependencyPromise
      if (!dependency) break
      ptr.dependencies.push(dependency)
      dataPointer = dependency.dataPointer
    }

    const session = this.db.session()
    try {
      return await HypercoreStorage.export(ptr, session, opts)
    } finally {
      await session.close()
    }
  }

  async _resumeFromPointers(view, discoveryKey, create, { version, corePointer, dataPointer }) {
    const core = { corePointer, dataPointer, dependencies: [] }

    while (true) {
      const rx = new CoreRX(
        { dataPointer, corePointer: 0, dependencies: [] },
        this.db,
        view,
        this.treeCache,
        this.stats,
        -1
      )
      const dependencyPromise = rx.getDependency()
      rx.tryFlush()
      const dependency = await dependencyPromise
      if (!dependency) break
      core.dependencies.push(dependency)
      dataPointer = dependency.dataPointer
    }

    const result = new HypercoreStorage(this, this.db.session(), this.treeCache, core, EMPTY, null)

    if (version < VERSION) await this._migrateCore(result, discoveryKey, version, create)
    return result
  }

  // not allowed to throw validation errors as its a shared tx!
  async _create(
    view,
    { key, manifest, keyPair, encryptionKey, discoveryKey, alias, userData, core: ptrs }
  ) {
    const rx = new CorestoreRX(this.db, view)
    const tx = new CorestoreTX(view)

    const corePromise = rx.getCore(discoveryKey)
    const headPromise = rx.getHead()

    rx.tryFlush()

    let [core, head] = await Promise.all([corePromise, headPromise])
    if (core) return this._resumeFromPointers(view, discoveryKey, true, core)

    if (head === null) head = initStoreHead()
    if (head.defaultDiscoveryKey === null) head.defaultDiscoveryKey = discoveryKey

    const corePointer = ptrs ? ptrs.corePointer : head.cores++
    const dataPointer = ptrs ? ptrs.dataPointer : head.datas++

    core = { version: VERSION, corePointer, dataPointer, alias }

    tx.setHead(head)
    tx.putCore(discoveryKey, core)
    if (alias) tx.putCoreByAlias(alias, discoveryKey)

    const ptr = { corePointer, dataPointer, dependencies: [] }
    const ctx = new CoreTX(ptr, this.db, view, tx.changes)

    ctx.setAuth({
      key,
      discoveryKey,
      manifest,
      keyPair,
      encryptionKey
    })

    if (userData) {
      for (const { key, value } of userData) {
        ctx.putUserData(key, value)
      }
    }

    tx.apply()

    return new HypercoreStorage(this, this.db.session(), this.treeCache, ptr, EMPTY, null)
  }

  async createCore(data) {
    if (this.version === 0) await this._migrateStore()

    const view = await this._enter()

    try {
      return await this._create(view, data)
    } finally {
      await this._exit()
    }
  }

  // not allowed to throw validation errors as its a shared tx!
  async _createGroup(view, topic) {
    const rx = new CorestoreRX(this.db, view)
    const tx = new CorestoreTX(view)

    const groupPromise = rx.getGroup(topic)
    const headPromise = rx.getHead()

    rx.tryFlush()

    let group = await groupPromise
    if (group !== null) {
      return {
        key: topic,
        pointer: group
      }
    }

    let head = await headPromise
    if (head === null) head = initStoreHead()

    group = head.groups++

    tx.putGroup(topic, group)
    tx.setHead(head)
    tx.apply()

    return {
      key: topic,
      pointer: group
    }
  }

  async createGroup(topic) {
    if (this.version === 0) await this._migrateStore()

    const view = await this._enter()

    try {
      return await this._createGroup(view, topic)
    } finally {
      await this._exit()
    }
  }

  static isParentStorage(storage, parent) {
    return HypercoreStorage.isParentStorage(storage, parent)
  }
}

module.exports = CorestoreStorage

function initStoreHead() {
  return {
    version: 0, // cause we wanna run the migration
    datas: 0,
    cores: 0,
    groups: 0,
    seed: null,
    defaultDiscoveryKey: null
  }
}

function getSession(sessions, name, alloc) {
  for (let i = 0; i < sessions.length; i++) {
    if (sessions[i].name === name) return sessions[i]
  }

  if (!alloc) return null

  const result = { name, dataPointer: -1 }
  sessions.push(result)
  return result
}

function isCorestoreStorage(s) {
  return typeof s === 'object' && !!s && typeof s.setDefaultDiscoveryKey === 'function'
}

function createColumnFamily(db, opts = {}) {
  const {
    tableCacheIndexAndFilterBlocks = true,
    blockCache = true,
    optimizeFiltersForMemory = false,
    blobFileSize = 256 * 1024 * 1024,
    blobGarbageCollectionAgeCutOff = 0.25,
    blobGarbageCollectionForceThreshold = 1.0
  } = opts

  const col = new RocksDB.ColumnFamily(COLUMN_FAMILY, {
    enableBlobFiles: true,
    minBlobSize: 4096,
    blobFileSize,
    enableBlobGarbageCollection: true,
    tableBlockSize: 8192,
    tableCacheIndexAndFilterBlocks,
    tableFormatVersion: 6,
    optimizeFiltersForMemory,
    blockCache,
    blobGarbageCollectionAgeCutOff,
    blobGarbageCollectionForceThreshold
  })

  return db.columnFamily(col)
}

function getLastDependency(storage) {
  return storage.dependencies.length ? storage.dependencies[storage.dependencies.length - 1] : null
}

// TODO: remove in like 3-6 mo
function tmpFixStorage(p) {
  // if CORESTORE file is written, new format
  if (fs.existsSync(path.join(p, 'CORESTORE'))) return

  let files = []

  try {
    files = fs.readdirSync(p)
  } catch {}

  const notRocks = new Set([
    'CORESTORE',
    'primary-key',
    'cores',
    'app-preferences',
    'cache',
    'preferences.json',
    'db',
    'clone',
    'core',
    'notifications'
  ])

  for (const f of files) {
    if (notRocks.has(f)) continue

    try {
      fs.mkdirSync(path.join(p, 'db'))
    } catch {}

    fs.renameSync(path.join(p, f), path.join(p, 'db', f))
  }
}

async function exportData(ptr, db, opts) {
  // just need dataPointer
  const reads = [
    toArray(createBlockStream(ptr, db, EMPTY, opts)),
    toArray(createTreeNodeStream(ptr, db, EMPTY, opts)),
    toArray(createBitfieldStream(ptr, db, EMPTY, opts))
  ]

  const [blocks, tree, bitfield] = await Promise.all(reads)

  return {
    blocks,
    tree,
    bitfield
  }
}

async function toArray(stream) {
  const all = []
  for await (const e of stream) all.push(e)
  return all
}

async function fileExists(path) {
  try {
    await fs.promises.stat(path)
    return true
  } catch {
    return false
  }
}

function shouldRecover(err) {
  return err.message.toLowerCase().indexOf('sequence number is being set backwards') > -1
}

function noop() {}

async function getInfoFromBatch(db, c, discoveryKey, getAuth, getHead, getHints) {
  const authPromise = getAuth ? CoreRX.getAuth(db, c) : null
  const headPromise = getHead ? CoreRX.getHead(db, c) : null
  const hintsPromise = getHints ? CoreRX.getHints(db, c) : null

  // ensure no uncaughts
  if (authPromise) authPromise.catch(noop)
  if (headPromise) headPromise.catch(noop)
  if (hintsPromise) hintsPromise.catch(noop)

  return {
    discoveryKey,
    core: c,
    auth: await authPromise,
    head: await headPromise,
    hints: await hintsPromise
  }
}
const { Readable, getStreamError } = require('streamx')
const { core } = require('./keys')

module.exports = class BlockStream extends Readable {
  constructor(core, db, updates, start, end, reverse) {
    super()

    this.core = core
    this.db = db
    this.updates = updates
    this.start = start
    this.end = end
    this.reverse = reverse === true

    this._drained = true
    this._consumed = 0
    this._stream = null
    this._oncloseBound = this._onclose.bind(this)
    this._maybeDrainBound = this._maybeDrain.bind(this)

    this._update()
  }

  _update() {
    if (this._consumed > this.core.dependencies.length) return

    const deps = this.core.dependencies
    const index = this._findDependencyIndex(deps)

    const curr = index < deps.length ? deps[index] : null
    const prev = index > 0 && index - 1 < deps.length ? deps[index - 1] : null

    const start = prev && prev.length > this.start ? prev.length : this.start
    const end = curr && (this.end === -1 || curr.length < this.end) ? curr.length : this.end

    const ptr = curr ? curr.dataPointer : this.core.dataPointer

    this._makeStream(core.block(ptr, start), core.block(ptr, end))
  }

  _findDependencyIndex(deps) {
    if (!this.reverse) return this._consumed++

    let i = deps.length - this._consumed++
    while (i > 0) {
      if (deps[i - 1].length <= this.end) return i
      i--
      this._consumed++
    }

    return 0
  }

  _predestroy() {
    if (this._stream !== null) this._stream.destroy()
  }

  _read(cb) {
    this._drained = this._onreadable()
    cb(null)
  }

  _maybeDrain() {
    if (this._drained === true) return
    this._drained = this._onreadable()
  }

  _onreadable() {
    if (this._stream === null) {
      this.push(null)
      return true
    }

    let data = this._stream.read()

    if (data === null) return false

    do {
      this.push(data)
      data = this._stream.read()
    } while (data !== null)

    return true
  }

  _onclose() {
    if (this.destroying) return

    const err = getStreamError(this._stream)

    if (err !== null) {
      this.destroy(err)
      return
    }

    // empty the current stream
    if (this._onreadable() === true) this._drained = true

    this._stream = null

    this._update()
    this._maybeDrain()
  }

  _makeStream(start, end) {
    this._stream = this.updates.iterator(this.db, start, end, this.reverse)
    this._stream.on('readable', this._maybeDrainBound)
    this._stream.on('error', noop)
    this._stream.on('close', this._oncloseBound)
  }
}

function noop() {}
const { Readable } = require('streamx')

// used for returned a stream that just errors (during read during teardown)

module.exports = class CloseErrorStream extends Readable {
  constructor(err) {
    super()
    this.error = err
  }

  _open(cb) {
    cb(this.error)
  }
}
const { UINT, STRING } = require('index-encoder')
const c = require('compact-encoding')
const b4a = require('b4a')

const TL_HEAD = 0
const TL_CORE_BY_DKEY = 1
const TL_CORE_BY_ALIAS = 2
const TL_CORE = 3
const TL_DATA = 4
const TL_GROUP_BY_TOPIC = 5
const TL_GROUP = 6

const TL_END = TL_GROUP + 1

const CORE_AUTH = 0
const CORE_SESSIONS = 1
const CORE_GROUP = 2

const DATA_HEAD = 0
const DATA_DEPENDENCY = 1
const DATA_HINTS = 2
const DATA_BLOCK = 3
const DATA_TREE = 4
const DATA_BITFIELD = 5
const DATA_USER_DATA = 6
const DATA_LOCAL = 7
const DATA_MARK = 8

const slab = { buffer: b4a.allocUnsafe(65536), start: 0, end: 0 }

const store = {}
const core = {}
const group = {}

store.clear = function () {
  const state = alloc()
  let start = state.start
  UINT.encode(state, 0)
  const a = state.buffer.subarray(start, state.start)
  start = state.start
  UINT.encode(state, TL_END)
  const b = state.buffer.subarray(start, state.start)
  return [a, b]
}

store.head = function () {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_HEAD)
  return state.buffer.subarray(start, state.start)
}

store.core = function (discoveryKey) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE_BY_DKEY)
  c.fixed32.encode(state, discoveryKey)
  return state.buffer.subarray(start, state.start)
}

store.coreStart = function () {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE_BY_DKEY)
  return state.buffer.subarray(start, state.start)
}

store.coreEnd = function () {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE_BY_DKEY + 1)
  return state.buffer.subarray(start, state.start)
}

store.coreByAlias = function ({ namespace, name }) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE_BY_ALIAS)
  c.fixed32.encode(state, namespace)
  STRING.encode(state, name)
  return state.buffer.subarray(start, state.start)
}

store.coreByAliasStart = function (namespace) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE_BY_ALIAS)
  if (namespace) c.fixed32.encode(state, namespace)
  return state.buffer.subarray(start, state.start)
}

store.coreByAliasEnd = function (namespace) {
  const state = alloc()
  const start = state.start

  if (namespace) {
    UINT.encode(state, TL_CORE_BY_ALIAS)
    c.fixed32.encode(state, namespace)
    state.buffer[state.start++] = 0xff
  } else {
    UINT.encode(state, TL_CORE_BY_ALIAS + 1)
  }

  return state.buffer.subarray(start, state.start)
}

store.alias = function (buffer) {
  const state = { buffer, start: 0, end: buffer.byteLength }
  UINT.decode(state) // ns
  const namespace = c.fixed32.decode(state)
  const name = STRING.decode(state)
  return { namespace, name }
}

store.discoveryKey = function (buffer) {
  const state = { buffer, start: 0, end: buffer.byteLength }
  UINT.decode(state) // ns
  return c.fixed32.decode(state)
}

core.core = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE)
  UINT.encode(state, ptr)
  return state.buffer.subarray(start, state.start)
}

core.data = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  return state.buffer.subarray(start, state.start)
}

core.auth = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE)
  UINT.encode(state, ptr)
  UINT.encode(state, CORE_AUTH)
  return state.buffer.subarray(start, state.start)
}

core.group = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE)
  UINT.encode(state, ptr)
  UINT.encode(state, CORE_GROUP)
  return state.buffer.subarray(start, state.start)
}

core.sessions = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE)
  UINT.encode(state, ptr)
  UINT.encode(state, CORE_SESSIONS)
  return state.buffer.subarray(start, state.start)
}

core.head = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_HEAD)
  return state.buffer.subarray(start, state.start)
}

core.dependency = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_DEPENDENCY)
  return state.buffer.subarray(start, state.start)
}

core.hints = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_HINTS)
  return state.buffer.subarray(start, state.start)
}

core.block = function (ptr, index) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_BLOCK)
  UINT.encode(state, index)
  return state.buffer.subarray(start, state.start)
}

core.tree = function (ptr, index) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_TREE)
  UINT.encode(state, index)
  return state.buffer.subarray(start, state.start)
}

core.bitfield = function (ptr, index, type) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_BITFIELD)
  UINT.encode(state, index)
  UINT.encode(state, type)
  return state.buffer.subarray(start, state.start)
}

core.userData = function (ptr, key) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_USER_DATA)
  STRING.encode(state, key)
  return state.buffer.subarray(start, state.start)
}

core.userDataEnd = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_USER_DATA + 1)
  return state.buffer.subarray(start, state.start)
}

core.mark = function (ptr, index) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_MARK)
  UINT.encode(state, index)
  return state.buffer.subarray(start, state.start)
}

core.local = function (ptr, key) {
  if (key.byteLength > 2048) {
    throw new Error('local keys has an upper limit of 2048 bytes atm')
  }

  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_LOCAL)

  state.buffer.set(key, state.start)
  state.start += key.byteLength
  return state.buffer.subarray(start, state.start)
}

core.localEnd = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_LOCAL + 1)
  return state.buffer.subarray(start, state.start)
}

core.blockIndex = function (buffer) {
  const state = { buffer, start: 0, end: buffer.byteLength }
  UINT.decode(state) // ns
  UINT.decode(state) // ptr
  UINT.decode(state) // type
  return UINT.decode(state)
}

core.bitfieldIndexAndType = function (buffer) {
  const state = { buffer, start: 0, end: buffer.byteLength }
  UINT.decode(state) // ns
  UINT.decode(state) // ptr
  UINT.decode(state) // type
  return [UINT.decode(state), UINT.decode(state)]
}

core.userDataKey = function (buffer) {
  const state = { buffer, start: 0, end: buffer.byteLength }
  UINT.decode(state) // ns
  UINT.decode(state) // ptr
  UINT.decode(state) // type
  return STRING.decode(state)
}

core.markKey = function (buffer) {
  const state = { buffer, start: 0, end: buffer.byteLength }
  UINT.decode(state) // ns
  UINT.decode(state) // ptr
  UINT.decode(state) // type
  return UINT.decode(state)
}

core.localKey = function (buffer) {
  const state = { buffer, start: 0, end: buffer.byteLength }
  UINT.decode(state) // ns
  UINT.decode(state) // ptr
  UINT.decode(state) // type
  return state.buffer.subarray(state.start, state.end)
}

group.topic = function (topic) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_GROUP_BY_TOPIC)
  c.fixed32.encode(state, topic)
  return state.buffer.subarray(start, state.start)
}

group.entry = function (group, timestamp, ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_GROUP)
  UINT.encode(state, group)
  c.uint64be.encode(state, timestamp)
  UINT.encode(state, ptr)
  return state.buffer.subarray(start, state.start)
}

module.exports = { store, core, group }

function alloc() {
  if (slab.buffer.byteLength - slab.start < 4096) {
    slab.buffer = b4a.allocUnsafe(slab.buffer.byteLength)
    slab.start = 0
  }
  return slab
}
const b4a = require('b4a')
const BlockDependencyStream = require('./block-dependency-stream.js')
const { core, store, group } = require('./keys.js')
const schema = require('../encoding/spec/hyperschema')

const CORESTORE_CORE = schema.getEncoding('@corestore/core')
const CORE_TREE_NODE = schema.getEncoding('@core/tree-node')
const EMPTY = b4a.alloc(0)

module.exports = {
  createBlockStream,
  createBitfieldStream,
  createUserDataStream,
  createCoreStream,
  createAliasStream,
  createDiscoveryKeyStream,
  createTreeNodeStream,
  createMarkStream,
  createLocalStream,
  createGroupUpdateStream
}

function createCoreStream(db, view) {
  const start = store.coreStart()
  const end = store.coreEnd()

  const ite = view.iterator(db, start, end, false)

  ite._readableState.map = mapCore
  return ite
}

function createDiscoveryKeyStream(db, view, namespace) {
  const start = namespace ? store.coreByAliasStart(namespace) : store.coreStart()
  const end = namespace ? store.coreByAliasEnd(namespace) : store.coreEnd()

  const ite = view.iterator(db, start, end, false)

  ite._readableState.map = namespace ? mapNamespaceDiscoveryKeys : mapAllDiscoveryKeys
  return ite
}

function createAliasStream(db, view, namespace) {
  const start = store.coreByAliasStart(namespace)
  const end = store.coreByAliasEnd(namespace)

  const ite = view.iterator(db, start, end, false)

  ite._readableState.map = mapAlias
  return ite
}

function createGroupUpdateStream(db, view, groupID, { gte = 0, reverse = true } = {}) {
  const start = group.entry(groupID, gte, 0)
  const end = group.entry(groupID + 1, 0, 0)

  const ite = view.iterator(db, start, end, reverse)

  ite._readableState.map = mapGroupUpdate
  return ite
}

function createBlockIterator(ptr, db, view, start, end, reverse) {
  if (ptr.dependencies.length > 0) {
    return new BlockDependencyStream(ptr, db, view, start, end, reverse)
  }

  const s = core.block(ptr.dataPointer, start)
  const e = core.block(ptr.dataPointer, end === -1 ? Infinity : end)
  return view.iterator(db, s, e, reverse)
}

function createBlockStream(
  ptr,
  db,
  view,
  { gt = -1, gte = gt + 1, lte = -1, lt = lte === -1 ? -1 : lte + 1, reverse = false } = {}
) {
  const ite = createBlockIterator(ptr, db, view, gte, lt, reverse)

  ite._readableState.map = mapBlock
  return ite
}

function createBitfieldStream(
  ptr,
  db,
  view,
  { gt = -1, gte = gt + 1, lte = -1, lt = lte === -1 ? -1 : lte + 1, reverse = false } = {}
) {
  const s = core.bitfield(ptr.dataPointer, gte, 0)
  const e = core.bitfield(ptr.dataPointer, lt === -1 ? Infinity : lt, 0)
  const ite = view.iterator(db, s, e, false)

  ite._readableState.map = mapBitfield
  return ite
}

// NOTE: this does not do dependency lookups atm
function createTreeNodeStream(
  ptr,
  db,
  view,
  { gt = -1, gte = gt + 1, lte = -1, lt = lte === -1 ? -1 : lte + 1, reverse = false } = {}
) {
  const s = core.tree(ptr.dataPointer, gte, 0)
  const e = core.tree(ptr.dataPointer, lt === -1 ? Infinity : lt, 0)
  const ite = view.iterator(db, s, e, false)

  ite._readableState.map = mapTreeNode
  return ite
}

function createUserDataStream(
  ptr,
  db,
  view,
  { gt = null, gte = '', lte = null, lt = null, reverse = false } = {}
) {
  if (gt !== null || lte !== null) {
    throw new Error('gt and lte not yet supported for user data streams')
  }

  const s = core.userData(ptr.dataPointer, gte)
  const e = lt === null ? core.userDataEnd(ptr.dataPointer) : core.userData(ptr.dataPointer, lt)
  const ite = view.iterator(db, s, e, false)

  ite._readableState.map = mapUserData
  return ite
}

function createMarkStream(
  ptr,
  db,
  view,
  { gt = -1, gte = gt + 1, lte = -1, lt = lte === -1 ? -1 : lte + 1, reverse = false } = {}
) {
  const s = core.mark(ptr.dataPointer, gte)
  const e = core.mark(ptr.dataPointer, lt === -1 ? Infinity : lt)
  const ite = view.iterator(db, s, e, reverse)

  ite._readableState.map = mapMark
  return ite
}

function createLocalStream(
  ptr,
  db,
  view,
  { gt = null, gte = EMPTY, lte = null, lt = null, reverse = false } = {}
) {
  if (gt !== null || lte !== null) throw new Error('gt and lte not yet supported for local streams')

  const s = core.local(ptr.dataPointer, gte)
  const e = lt === null ? core.localEnd(ptr.dataPointer) : core.local(ptr.dataPointer, lt)
  const ite = view.iterator(db, s, e, false)

  ite._readableState.map = mapLocal
  return ite
}

function mapBitfield(data) {
  const [index, type] = core.bitfieldIndexAndType(data.key)
  if (type !== 0) return null // ignore for now
  return { index, page: data.value }
}

function mapMark(data) {
  const index = core.markKey(data.key)
  return { index, page: data.value }
}

function mapLocal(data) {
  const key = core.localKey(data.key)
  return { key, value: data.value }
}

function mapGroupUpdate(data) {
  return data.value
}

function mapUserData(data) {
  const key = core.userDataKey(data.key)
  return { key, value: data.value }
}

function mapCore(data) {
  const discoveryKey = store.discoveryKey(data.key)
  const core = CORESTORE_CORE.decode({
    start: 0,
    end: data.value.byteLength,
    buffer: data.value
  })
  return { discoveryKey, core }
}

function mapAllDiscoveryKeys(data) {
  return store.discoveryKey(data.key)
}

function mapNamespaceDiscoveryKeys(data) {
  return data.value
}

function mapAlias(data) {
  const alias = store.alias(data.key)
  return { alias, discoveryKey: data.value }
}

function mapBlock(data) {
  return { index: core.blockIndex(data.key), value: data.value }
}

function mapTreeNode(data) {
  return CORE_TREE_NODE.decode({
    start: 0,
    end: data.value.byteLength,
    buffer: data.value
  })
}
const b4a = require('b4a')
const c = require('compact-encoding')
const flat = require('flat-tree')

const schema = require('../encoding/spec/hyperschema')
const { store, core, group } = require('./keys.js')
const View = require('./view.js')

const CORESTORE_HEAD = schema.getEncoding('@corestore/head')
const CORESTORE_CORE = schema.getEncoding('@corestore/core')
const CORESTORE_GROUP = c.uint

const CORE_AUTH = schema.getEncoding('@core/auth')
const CORE_GROUP = schema.getEncoding('@core/group')
const CORE_SESSIONS = schema.getEncoding('@core/sessions')
const CORE_HEAD = schema.getEncoding('@core/head')
const CORE_TREE_NODE = schema.getEncoding('@core/tree-node')
const CORE_DEPENDENCY = schema.getEncoding('@core/dependency')
const CORE_HINTS = schema.getEncoding('@core/hints')

class CoreTX {
  constructor(core, db, view, changes) {
    if (db.snapshotted) throw new Error('Cannot open core tx on snapshot')
    this.core = core
    this.db = db
    this.view = view
    this.changes = changes
  }

  setAuth(auth) {
    this.changes.push([core.auth(this.core.corePointer), encode(CORE_AUTH, auth), null])
  }

  setSessions(sessions) {
    this.changes.push([core.sessions(this.core.corePointer), encode(CORE_SESSIONS, sessions), null])
  }

  setHead(head) {
    this.changes.push([core.head(this.core.dataPointer), encode(CORE_HEAD, head), null])
  }

  deleteHead() {
    this.changes.push([core.head(this.core.dataPointer), null, null])
  }

  setDependency(dep) {
    this.changes.push([core.dependency(this.core.dataPointer), encode(CORE_DEPENDENCY, dep), null])
  }

  setGroup(group) {
    this.changes.push([core.group(this.core.dataPointer), encode(CORE_GROUP, group), null])
  }

  deleteGroup() {
    this.changes.push([core.group(this.core.dataPointer), null, null])
  }

  setHints(hints) {
    this.changes.push([core.hints(this.core.dataPointer), encode(CORE_HINTS, hints), null])
  }

  putBlock(index, data) {
    this.changes.push([core.block(this.core.dataPointer, index), data, null])
  }

  deleteBlock(index) {
    this.changes.push([core.block(this.core.dataPointer, index), null, null])
  }

  deleteBlockRange(start, end) {
    this.changes.push([
      core.block(this.core.dataPointer, start),
      null,
      core.block(this.core.dataPointer, end === -1 ? Infinity : end)
    ])
  }

  putBitfieldPage(index, data) {
    this.changes.push([core.bitfield(this.core.dataPointer, index, 0), data, null])
  }

  deleteBitfieldPage(index) {
    this.changes.push([core.bitfield(this.core.dataPointer, index, 0), null, null])
  }

  deleteBitfieldPageRange(start, end) {
    this.changes.push([
      core.bitfield(this.core.dataPointer, start, 0),
      null,
      core.bitfield(this.core.dataPointer, end === -1 ? Infinity : end, 0)
    ])
  }

  putTreeNode(node) {
    this.changes.push([
      core.tree(this.core.dataPointer, node.index),
      encode(CORE_TREE_NODE, node),
      null
    ])
  }

  deleteTreeNode(index) {
    this.changes.push([core.tree(this.core.dataPointer, index), null, null])
  }

  deleteTreeNodeRange(start, end) {
    this.changes.push([
      core.tree(this.core.dataPointer, start),
      null,
      core.tree(this.core.dataPointer, end === -1 ? Infinity : end)
    ])
  }

  putUserData(key, value) {
    const buffer = typeof value === 'string' ? b4a.from(value) : value
    this.changes.push([core.userData(this.core.dataPointer, key), buffer, null])
  }

  deleteUserData(key) {
    this.changes.push([core.userData(this.core.dataPointer, key), null, null])
  }

  putMark(index, data) {
    this.changes.push([core.mark(this.core.dataPointer, index), data, null])
  }

  deleteMark(index) {
    this.changes.push([core.mark(this.core.dataPointer, index), null, null])
  }

  deleteMarkRange(start, end) {
    this.changes.push([
      core.mark(this.core.dataPointer, start),
      null,
      core.mark(this.core.dataPointer, end === -1 ? Infinity : end)
    ])
  }

  putLocal(key, value) {
    this.changes.push([core.local(this.core.dataPointer, key), value, null])
  }

  deleteLocal(key) {
    this.changes.push([core.local(this.core.dataPointer, key), null, null])
  }

  deleteLocalRange(start, end) {
    this.changes.push([
      core.local(this.core.dataPointer, start),
      null,
      end === null ? core.localEnd(this.core.dataPointer) : core.local(this.core.dataPointer, end)
    ])
  }

  putGroupUpdate(groupPtr, timestamp, key) {
    this.changes.push([group.entry(groupPtr, timestamp, this.core.corePointer), key, null])
  }

  deleteGroupUpdate(groupPtr, timestamp) {
    this.changes.push([group.entry(groupPtr, timestamp, this.core.corePointer), null, null])
  }

  flush() {
    const changes = this.changes
    if (changes === null) return Promise.resolve(!this.view)

    this.changes = null

    if (this.view) {
      this.view.apply(changes)
      return Promise.resolve(false)
    }

    return View.flush(changes, this.db)
  }
}

class CoreRX {
  constructor(core, db, view, treeCache, stats, fork) {
    this.core = core
    this.read = db.read({ autoDestroy: true })
    this.view = view
    this.treeCache = treeCache
    this.fork = fork
    this.stats = stats

    view.readStart()
  }

  static async getAuth(db, c) {
    return decode(CORE_AUTH, await db.get(core.auth(c.corePointer)))
  }

  async getAuth() {
    return decode(CORE_AUTH, await this.view.get(this.read, core.auth(this.core.corePointer)))
  }

  async getSessions() {
    return decode(
      CORE_SESSIONS,
      await this.view.get(this.read, core.sessions(this.core.corePointer))
    )
  }

  static async getHead(db, c) {
    return decode(CORE_HEAD, await db.get(core.head(c.dataPointer)))
  }

  async getHead() {
    return decode(CORE_HEAD, await this.view.get(this.read, core.head(this.core.dataPointer)))
  }

  async getDependency() {
    return decode(
      CORE_DEPENDENCY,
      await this.view.get(this.read, core.dependency(this.core.dataPointer))
    )
  }

  async getGroup() {
    return await decode(
      CORE_GROUP,
      await this.view.get(this.read, core.group(this.core.corePointer))
    )
  }

  static async getHints(db, c) {
    return decode(CORE_HINTS, await db.get(core.hints(c.dataPointer)))
  }

  async getHints() {
    return decode(CORE_HINTS, await this.view.get(this.read, core.hints(this.core.dataPointer)))
  }

  getBlock(index) {
    const dep = findBlockDependency(this.core.dependencies, index)
    const data = dep === null ? this.core.dataPointer : dep.dataPointer
    return this.view.get(this.read, core.block(data, index))
  }

  getBitfieldPage(index) {
    return this.view.get(this.read, core.bitfield(this.core.dataPointer, index, 0))
  }

  async _resolveTreeCache(key, promise, entry) {
    try {
      const value = decode(CORE_TREE_NODE, await promise)
      const cached = this.treeCache.get(key)

      // preflight is gone; no-op
      if (cached !== entry) return value

      if (value !== null) {
        // replace cached entry with value
        this.treeCache.set(key, { pending: null, value })
      } else {
        // discard non-existing values
        this.treeCache.delete(key)
      }

      return value
    } catch (err) {
      // cleanup
      const cached = this.treeCache.get(key)
      if (cached === entry) {
        this.treeCache.delete(key)
      }

      throw err
    }
  }

  async getTreeNode(index) {
    const dep = findTreeDependency(this.core.dependencies, index)
    const data = dep === null ? this.core.dataPointer : dep.dataPointer

    if (!this.treeCache || this.fork < 0) {
      if (this.stats !== null) this.stats.treeCache.skips++
      // no-cache
      return decode(CORE_TREE_NODE, await this.view.get(this.read, core.tree(data, index)))
    }

    const key = `${data}:${index}:${this.fork}`
    let entry = this.treeCache.get(key)
    if (entry) {
      if (entry.pending) {
        if (this.stats !== null) this.stats.treeCache.parallel++
        return entry.pending
      }

      if (this.stats !== null) this.stats.treeCache.hits++
      return entry.value
    }

    if (this.stats !== null) this.stats.treeCache.misses++

    const promise = this.view.get(this.read, core.tree(data, index))
    entry = { pending: null, value: null }
    entry.pending = this._resolveTreeCache(key, promise, entry)
    this.treeCache.set(key, entry)

    return entry.pending
  }

  async hasTreeNode(index) {
    return (await this.getTreeNode(index)) !== null
  }

  getUserData(key) {
    return this.view.get(this.read, core.userData(this.core.dataPointer, key))
  }

  getMark(index) {
    return this.view.get(this.read, core.mark(this.core.dataPointer, index))
  }

  getLocal(key) {
    return this.view.get(this.read, core.local(this.core.dataPointer, key))
  }

  tryFlush() {
    this.read.tryFlush()
    this._free()
  }

  destroy() {
    this.read.destroy()
    this._free()
  }

  _free() {
    if (this.view === null) return
    this.view.readStop()
    this.view = null
  }
}

class CorestoreTX {
  constructor(view) {
    this.view = view
    this.changes = []
  }

  setHead(head) {
    this.changes.push([store.head(), encode(CORESTORE_HEAD, head), null])
  }

  setCoreHints(c, hints) {
    this.changes.push([core.hints(c.dataPointer), encode(CORE_HINTS, hints), null])
  }

  putCore(discoveryKey, ptr) {
    this.changes.push([store.core(discoveryKey), encode(CORESTORE_CORE, ptr), null])
  }

  putCoreByAlias(alias, discoveryKey) {
    this.changes.push([store.coreByAlias(alias), discoveryKey, null])
  }

  putGroup(topic, groupPtr) {
    this.changes.push([group.topic(topic), encode(CORESTORE_GROUP, groupPtr), null])
  }

  deleteGroup(topic) {
    this.changes.push([group.topic(topic), null, null])
  }

  clear() {
    const [start, end] = store.clear()
    this.changes.push([start, null, end])
  }

  apply() {
    if (this.changes === null) return
    this.view.apply(this.changes)
    this.changes = null
  }
}

class CorestoreRX {
  constructor(db, view) {
    this.read = db.read({ autoDestroy: true })
    this.view = view

    view.readStart()
  }

  async getHeadRaw(db) {
    return await this.view.get(this.read, store.head())
  }

  async getHead() {
    return decode(CORESTORE_HEAD, await this.view.get(this.read, store.head()))
  }

  async getCore(discoveryKey) {
    return decode(CORESTORE_CORE, await this.view.get(this.read, store.core(discoveryKey)))
  }

  getCoreByAlias(alias) {
    return this.view.get(this.read, store.coreByAlias(alias))
  }

  async getGroup(topic) {
    return decode(CORESTORE_GROUP, await this.view.get(this.read, group.topic(topic)))
  }

  tryFlush() {
    this.read.tryFlush()
    this._free()
  }

  destroy() {
    this.read.destroy()
    this._free()
  }

  _free() {
    if (this.view === null) return
    this.view.readStop()
    this.view = null
  }
}

module.exports = { CorestoreTX, CorestoreRX, CoreTX, CoreRX }

function findBlockDependency(dependencies, index) {
  for (let i = 0; i < dependencies.length; i++) {
    const dep = dependencies[i]
    if (index < dep.length) return dep
  }

  return null
}

function findTreeDependency(dependencies, index) {
  for (let i = 0; i < dependencies.length; i++) {
    const dep = dependencies[i]
    if (flat.rightSpan(index) <= (dep.length - 1) * 2) return dep
  }

  return null
}

function decode(enc, buffer) {
  if (buffer === null) return null
  return enc.decode({ start: 0, end: buffer.byteLength, buffer })
}

function encode(enc, m) {
  // TODO: use fancy slab for small messages
  const state = { start: 0, end: 0, buffer: null }
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}
const { Readable, getStreamError } = require('streamx')
const CloseErrorStream = require('./close-error-stream.js')
const b4a = require('b4a')

class OverlayStream extends Readable {
  constructor(stream, start, end, reverse, changes, cleared) {
    super()

    this.start = start
    this.end = end
    this.reverse = reverse
    this.changes = changes
    this.cleared = cleared
    this.change = 0
    this.range = 0

    this._stream = stream
    this._drained = false

    this._stream.on('readable', this._drainMaybe.bind(this))
    this._stream.on('error', noop)
    this._stream.on('close', this._onclose.bind(this))
  }

  _drainMaybe() {
    if (this._drained === true) return
    this._drained = this._onreadable()
  }

  _onclose() {
    if (this.destroying) return

    const err = getStreamError(this._stream)

    if (err !== null) {
      this.destroy(err)
      return
    }

    while (this.change < this.changes.length) {
      const c = this.changes[this.change++]
      const key = c[0]
      const value = c[1]

      if (value !== null && this._inRange(key)) this.push({ key, value })
    }

    this.push(null)
    this._stream = null
  }

  _onreadable() {
    let data = this._stream.read()
    if (data === null) return false

    let drained = false

    do {
      if (this._push(data) === true) drained = true
      data = this._stream.read()
    } while (data !== null)

    return drained
  }

  _read(cb) {
    this._drained = this._onreadable()
    cb(null)
  }

  _predestroy() {
    this._stream.destroy()
  }

  _push(entry) {
    const key = entry.key

    while (this.range < this.cleared.length) {
      const c = this.cleared[this.range]

      // we moved past the range
      if (this.reverse ? b4a.compare(key, c[0]) < 0 : b4a.compare(c[2], key) <= 0) {
        this.range++
        continue
      }

      // we didnt move past and are in, drop
      if (b4a.compare(c[0], key) <= 0 && b4a.compare(key, c[2]) < 0) {
        return false
      }

      break
    }

    let updated = false

    while (this.change < this.changes.length) {
      const c = this.changes[this.change]
      const key = c[0]
      const value = typeof c[1] === 'string' ? b4a.from(c[1]) : c[1]
      const cmp = b4a.compare(key, entry.key)

      // same value, if not deleted, return new one
      if (cmp === 0) {
        this.change++
        if (value === null || this._inRange(key) === false) return updated
        this.push({ key, value })
        return true
      }

      // we moved past the change, push it
      if (this.reverse ? cmp > 0 : cmp < 0) {
        this.change++
        if (value === null || this._inRange(key) === false) continue
        this.push({ key, value })
        updated = true
        continue
      }

      this.push(entry)
      return true
    }

    this.push(entry)
    return true
  }

  _inRange(key) {
    return b4a.compare(this.start, key) <= 0 && b4a.compare(key, this.end) < 0
  }
}

class Overlay {
  constructor() {
    this.indexed = 0
    this.changes = null
    this.cleared = null
    this.reverse = false
  }

  update(view, reverse) {
    if (view.indexed === this.indexed) return

    const changes = view.map === null ? [] : [...view.map.values()]
    const cleared = view.cleared === null ? [] : view.cleared.slice(0)

    const cmp = reverse ? cmpChangeReverse : cmpChange

    changes.sort(cmp)
    cleared.sort(cmp)

    this.indexed = view.indexed
    this.changes = changes
    this.cleared = cleared
    this.reverse = reverse
  }

  createStream(stream, start, end, reverse) {
    return new OverlayStream(
      stream,
      start,
      end,
      reverse,
      this.reverse === reverse ? this.changes : reverseArray(this.changes),
      this.reverse === reverse ? this.cleared : reverseArray(this.cleared)
    )
  }
}

class View {
  constructor() {
    this.map = null
    this.indexed = 0
    this.changes = null
    this.cleared = null
    this.overlay = null
    this.snap = null
    this.readers = 0
  }

  snapshot() {
    if (this._attached()) return this.snap.snapshot()

    const snap = new View()

    snap.map = this.map
    snap.indexed = this.indexed
    snap.changes = this.changes
    snap.cleared = this.cleared

    if (this._frozen()) return snap

    this.readers++
    snap.snap = this

    return snap
  }

  readStart() {
    if (this.snap !== null) this.readers++
  }

  readStop() {
    if (this.snap !== null && --this.readers === 0) this.snap.readers--
  }

  size() {
    return this.changes === null ? 0 : this.changes.length
  }

  updated() {
    return this.changes === null
  }

  get(read, key) {
    return this.changes === null ? read.get(key) : this._indexAndGet(read, key)
  }

  reset() {
    this.indexed = 0
    this.snap = this.map = this.changes = this.cleared = this.overlay = null
  }

  iterator(db, start, end, reverse) {
    if (dbClosing(db)) return new CloseErrorStream(new Error('RocksDB session is closed'))

    const stream = db.iterator({ gte: start, lt: end, reverse })
    if (this.changes === null) return stream

    this._index()

    if (this.overlay === null) this.overlay = new Overlay()
    this.overlay.update(this, reverse)
    return this.overlay.createStream(stream, start, end, reverse)
  }

  _indexAndGet(read, key) {
    this._index()
    const change = this.map.get(b4a.toString(key, 'hex'))

    if (change === undefined) {
      return this.cleared === null ? read.get(key) : this._readAndMaybeDrop(read, key)
    }

    return Promise.resolve(change[1])
  }

  async _readAndMaybeDrop(read, key) {
    const cleared = this.cleared // in case its cleared
    const value = await read.get(key)
    if (value === null) return null

    for (let i = 0; i < cleared.length; i++) {
      const c = cleared[i]
      // check if in range
      if (b4a.compare(c[0], key) <= 0 && b4a.compare(key, c[2]) < 0) return null
    }

    return value
  }

  _attached() {
    return this.snap !== null && this.changes === this.snap.changes
  }

  _frozen() {
    return this.changes === null || (this.snap !== null && this.changes !== this.snap.changes)
  }

  _index() {
    // if we are a snap and we are still attached (ie no mutations), simply copy the refs
    if (this._attached()) {
      this.snap._index()
      this.map = this.snap.map
      this.cleared = this.snap.cleared
      this.indexed = this.snap.indexed
      return
    }

    if (this.map === null) this.map = new Map()
    if (this.changes.length === this.indexed) return

    while (this.indexed < this.changes.length) {
      const c = this.changes[this.indexed++]

      if (c[2] === null) this.map.set(b4a.toString(c[0], 'hex'), c)
      else this._indexRange(c)
    }
  }

  _indexRange(range) {
    const s = b4a.toString(range[0], 'hex')
    const e = b4a.toString(range[2], 'hex')

    for (const [key, c] of this.map) {
      if (s <= key && key < e) this.map.set(key, [c[0], null, null])
    }

    if (this.cleared === null) this.cleared = []
    this.cleared.push(range)
  }

  apply(changes) {
    if (this.snap !== null) throw new Error('Illegal to push changes to a snapshot')

    if (this.readers !== 0 && this.changes !== null) {
      this.changes = this.changes.slice(0)
      this.cleared = this.cleared === null ? null : this.cleared.slice(0)
      this.map = this.map === null ? null : new Map([...this.map])
    }

    if (this.changes === null) {
      this.changes = changes
      return
    }

    for (let i = 0; i < changes.length; i++) {
      this.changes.push(changes[i])
    }
  }

  static async flush(changes, db) {
    if (changes === null) return true

    const w = db.write({ autoDestroy: true })

    for (const [start, value, end] of changes) {
      if (end !== null) w.tryDeleteRange(start, end)
      else if (value !== null) w.tryPut(start, value)
      else w.tryDelete(start)
    }

    await w.flush()

    return true
  }
}

module.exports = View

function cmpChange(a, b) {
  const c = b4a.compare(a[0], b[0])
  return c === 0 ? b4a.compare(a[2], b[2]) : c
}

function cmpChangeReverse(a, b) {
  return cmpChange(b, a)
}

function noop() {}

function reverseArray(list) {
  const r = new Array(list.length)
  for (let i = 0; i < list.length; i++) r[r.length - 1 - i] = list[i]
  return r
}

// TODO: expose from rocks instead
function dbClosing(db) {
  return db._state.closing || db._index === -1
}
const fs = require('fs')
const path = require('path')
const { Readable } = require('streamx')
const b4a = require('b4a')
const flat = require('flat-tree')
const crypto = require('hypercore-crypto')
const c = require('compact-encoding')
const m = require('./messages.js')
const View = require('../../lib/view.js')
const { CorestoreTX, CoreTX, CorestoreRX } = require('../../lib/tx.js')

const EMPTY_NODE = b4a.alloc(40)
const EMPTY_PAGE = b4a.alloc(4096)

let TREE_01_SKIP = null
let TREE_04_SKIP = null
let TREE_16_SKIP = null

class CoreListStream extends Readable {
  constructor (storage) {
    super()

    this.storage = storage
    this.stack = []
  }

  async _open (cb) {
    for (const a of await readdir(path.join(this.storage, 'cores'))) {
      for (const b of await readdir(path.join(this.storage, 'cores', a))) {
        for (const dkey of await readdir(path.join(this.storage, 'cores', a, b))) {
          this.stack.push(path.join(this.storage, 'cores', a, b, dkey))
        }
      }
    }

    cb(null)
  }

  async _read (cb) {
    while (true) {
      const next = this.stack.pop()
      if (!next) {
        this.push(null)
        break
      }

      const oplog = path.join(next, 'oplog')
      const result = await readOplog(oplog)
      if (!result) continue

      this.push(result)
      break
    }

    cb(null)
  }
}

function decodeOplogHeader (state) {
  c.uint32.decode(state) // cksum, ignore for now

  const l = c.uint32.decode(state)
  const length = l >> 2
  const headerBit = l & 1
  const partialBit = l & 2

  if (state.end - state.start < length) return null

  const end = state.start + length
  const result = { header: headerBit, partial: partialBit !== 0, byteLength: length + 8, message: null }

  try {
    result.message = m.oplog.header.decode({ start: state.start, end, buffer: state.buffer })
  } catch {
    return null
  }

  state.start = end
  return result
}

function decodeOplogEntry (state) {
  if (state.end - state.start < 8) return null

  c.uint32.decode(state) // cksum, ignore for now

  const l = c.uint32.decode(state)
  const length = l >>> 2
  const headerBit = l & 1
  const partialBit = l & 2

  if (state.end - state.start < length) return null

  const end = state.start + length

  const result = { header: headerBit, partial: partialBit !== 0, byteLength: length + 8, message: null }

  try {
    result.message = m.oplog.entry.decode({ start: state.start, end, buffer: state.buffer })
  } catch {
    return null
  }

  state.start = end

  return result
}

module.exports = { store, core }

async function store (storage, { version, dryRun = true, gc = true }) {
  const stream = new CoreListStream(storage.path)
  const view = new View()

  const tx = new CorestoreTX(view)
  const head = await storage._getHead(view)
  const primaryKeyFile = path.join(storage.path, 'primary-key')

  const primaryKey = await readFile(primaryKeyFile)

  if (!head.seed) head.seed = primaryKey

  for await (const data of stream) {
    const key = data.header.key
    const discoveryKey = crypto.discoveryKey(data.header.key)
    const files = getFiles(data.path)

    if (head.defaultDiscoveryKey === null) head.defaultDiscoveryKey = discoveryKey

    const core = {
      version: 0, // need later migration
      corePointer: head.allocated.cores++,
      dataPointer: head.allocated.datas++,
      alias: null
    }

    const ptr = { version: 0, corePointer: core.corePointer, dataPointer: core.dataPointer, dependencies: [] }
    const ctx = new CoreTX(ptr, storage.db, view, [])
    const userData = new Map()
    const treeNodes = new Map()

    const auth = {
      key,
      discoveryKey,
      manifest: data.header.manifest,
      keyPair: data.header.keyPair,
      encryptionKey: null
    }

    const tree = {
      length: 0,
      fork: 0,
      rootHash: null,
      signature: null
    }

    if (data.header.tree && data.header.tree.length) {
      tree.length = data.header.tree.length
      tree.fork = data.header.tree.fork
      tree.rootHash = data.header.tree.rootHash
      tree.signature = data.header.tree.signature
    }

    for (const { key, value } of data.header.userData) {
      userData.set(key, value)
    }

    for (const e of data.entries) {
      if (e.userData) userData.set(e.userData.key, e.userData.value)

      if (e.treeNodes) {
        for (const node of e.treeNodes) {
          treeNodes.set(node.index, node)
          ctx.putTreeNode(node)
        }
      }

      if (e.treeUpgrade) {
        if (e.treeUpgrade.ancestors !== tree.length) {
          throw new Error('Unflushed truncations not migrate-able atm')
        }

        tree.length = e.treeUpgrade.length
        tree.fork = e.treeUpgrade.fork
        tree.rootHash = null
        tree.signature = e.treeUpgrade.signature
      }
    }

    if (userData.has('corestore/name') && userData.has('corestore/namespace')) {
      core.alias = {
        name: b4a.toString(userData.get('corestore/name')),
        namespace: userData.get('corestore/namespace')
      }
      userData.delete('corestore/name')
      userData.delete('corestore/namespace')
    }

    for (const [key, value] of userData) {
      ctx.putUserData(key, value)
    }

    ctx.setAuth(auth)

    const getTreeNode = (index) => (treeNodes.get(index) || getTreeNodeFromFile(files.tree, index))

    if (tree.length) {
      if (tree.rootHash === null) tree.rootHash = crypto.tree(await getRoots(tree.length, getTreeNode))
      ctx.setHead(tree)
    }

    tx.putCore(discoveryKey, core)
    if (core.alias) tx.putCoreByAlias(core.alias, discoveryKey)

    await ctx.flush()
  }

  head.version = version
  tx.setHead(head)
  tx.apply()

  if (dryRun) return

  await View.flush(view.changes, storage.db)

  if (gc) await rm(primaryKeyFile)
}

class BlockSlicer {
  constructor (filename) {
    this.stream = fs.createReadStream(filename)
    this.closed = new Promise(resolve => this.stream.once('close', resolve))
    this.offset = 0
    this.overflow = null
  }

  async take (offset, size) {
    let buffer = null
    if (offset < this.offset) throw new Error('overread')

    while (true) {
      let data = null

      if (this.overflow) {
        data = this.overflow
        this.overflow = null
      } else {
        data = this.stream.read()

        if (!data) {
          await new Promise(resolve => this.stream.once('readable', resolve))
          continue
        }
      }

      let chunk = null

      if (this.offset === offset || buffer) {
        chunk = data
      } else if (this.offset + data.byteLength > offset) {
        chunk = data.subarray(offset - this.offset)
      }

      this.offset += data.byteLength
      if (!chunk) continue

      if (buffer) buffer = b4a.concat([buffer, chunk])
      else buffer = chunk

      if (buffer.byteLength < size) continue

      const result = buffer.subarray(0, size)
      this.overflow = size === buffer.byteLength ? null : buffer.subarray(result.byteLength)
      this.offset -= (this.overflow ? this.overflow.byteLength : 0)
      return result
    }
  }

  close () {
    this.stream.on('error', noop)
    this.stream.destroy()
    return this.closed
  }
}

class TreeSlicer {
  constructor () {
    this.buffer = null
    this.offset = 0
  }

  get size () {
    return this.buffer === null ? 0 : this.buffer.byteLength
  }

  push (data) {
    if (this.buffer === null) this.buffer = data
    else this.buffer = b4a.concat([this.buffer, data])
    this.offset += data.byteLength
  }

  skip () {
    let skipped = 0

    if (TREE_01_SKIP === null) {
      TREE_16_SKIP = b4a.alloc(16 * 40 * 100)
      TREE_04_SKIP = TREE_16_SKIP.subarray(0, 4 * 40 * 100)
      TREE_01_SKIP = TREE_16_SKIP.subarray(0, 1 * 40 * 100)
    }

    while (true) {
      if (this.buffer.byteLength >= TREE_16_SKIP.byteLength) {
        if (b4a.equals(this.buffer.subarray(0, TREE_16_SKIP.byteLength), TREE_16_SKIP)) {
          this.buffer = this.buffer.subarray(TREE_16_SKIP.byteLength)
          skipped += 1600
          continue
        }
      }

      if (this.buffer.byteLength >= TREE_04_SKIP.byteLength) {
        if (b4a.equals(this.buffer.subarray(0, TREE_04_SKIP.byteLength), TREE_04_SKIP)) {
          this.buffer = this.buffer.subarray(TREE_04_SKIP.byteLength)
          skipped += 400
          continue
        }
      }

      if (this.buffer.byteLength >= TREE_01_SKIP.byteLength) {
        if (b4a.equals(this.buffer.subarray(0, TREE_01_SKIP.byteLength), TREE_01_SKIP)) {
          this.buffer = this.buffer.subarray(TREE_01_SKIP.byteLength)
          skipped += 100
          continue
        }
      }
      break
    }

    return skipped
  }

  take () {
    const len = 40

    if (len <= this.size) {
      const chunk = this.buffer.subarray(0, len)
      this.buffer = this.buffer.subarray(len)
      return chunk
    }

    return null
  }
}

async function core (core, { version, dryRun = true, gc = true }) {
  if (dryRun) return // dryRun mode not supported atm

  const rx = core.read()

  const promises = [rx.getAuth(), rx.getHead()]
  rx.tryFlush()

  const [auth, head] = await Promise.all(promises)

  if (!auth) return

  const dk = b4a.toString(auth.discoveryKey, 'hex')
  const files = getFiles(path.join(core.store.path, 'cores', dk.slice(0, 2), dk.slice(2, 4), dk))

  if (head === null || head.length === 0) {
    await commitCoreMigration(auth, core, version)
    if (gc) await runGC()
    return // no data
  }

  const oplog = await readOplog(files.oplog)
  if (!oplog) {
    const writable = !!auth.keyPair

    if (writable) {
      throw new Error('No oplog available writable core for ' + files.oplog + ', length = ' + (head ? head.length : 0))
    }

    // if not writable, just nuke it to recover, some bad state happened here, prop corruption from earlier versions
    const w = core.write()

    w.deleteBlockRange(0, -1)
    w.deleteTreeNodeRange(0, -1)
    w.deleteBitfieldPageRange(0, -1)
    w.deleteHead()

    await w.flush()

    await commitCoreMigration(auth, core, version)
    if (gc) await runGC()
    return // no data
  }

  const treeData = new TreeSlicer()

  let treeIndex = 0

  if (await exists(files.tree)) {
    for await (const data of fs.createReadStream(files.tree)) {
      treeData.push(data)

      let write = null

      while (true) {
        const skip = treeData.skip()
        treeIndex += skip

        const buf = treeData.take()
        if (buf === null) break

        const index = treeIndex++
        if (b4a.equals(buf, EMPTY_NODE)) continue

        if (write === null) write = core.write()
        write.putTreeNode(decodeTreeNode(index, buf))
      }

      if (write !== null) await write.flush()
    }
  }

  const buf = []
  if (await exists(files.bitfield)) {
    for await (const data of fs.createReadStream(files.bitfield)) {
      buf.push(data)
    }
  }

  let bitfield = b4a.concat(buf)
  if (bitfield.byteLength & 4095) bitfield = b4a.concat([bitfield, b4a.alloc(4096 - (bitfield.byteLength & 4095))])

  const pages = new Map()
  const headerBits = new Map()

  const roots = await getRootsFromStorage(core, head.length)

  for (const e of oplog.entries) {
    if (!e.bitfield) continue

    for (let i = 0; i < e.bitfield.length; i++) {
      headerBits.set(i + e.bitfield.start, !e.bitfield.drop)
    }
  }

  let batch = []

  const cache = new Map()
  const blocks = new BlockSlicer(files.data)

  for (const index of allBits(bitfield)) {
    if (headerBits.get(index) === false) continue
    if (index >= head.length) continue

    setBitInPage(index)

    batch.push(index)
    if (batch.length < 1024) continue

    await writeBlocksBatch()
    continue
  }

  if (batch.length) await writeBlocksBatch()

  await blocks.close()

  const w = core.write()

  for (const [index, bit] of headerBits) {
    if (!bit) continue
    if (index >= head.length) continue

    setBitInPage(index)

    const blk = await getBlockFromFile(files.data, core, index, roots, cache)
    w.putBlock(index, blk)
  }

  for (const [index, page] of pages) {
    w.putBitfieldPage(index, b4a.from(page.buffer, page.byteOffset, page.byteLength))
  }

  await w.flush()

  let contiguousLength = 0
  for await (const data of core.createBlockStream()) {
    if (data.index === contiguousLength) contiguousLength++
    else break
  }

  if (contiguousLength) {
    const w = core.write()
    w.setHints({ contiguousLength })
    await w.flush()
  }

  await commitCoreMigration(auth, core, version)

  if (gc) await runGC()

  async function runGC () {
    await rm(files.path)
    await rmdir(path.join(files.path, '..'))
    await rmdir(path.join(files.path, '../..'))
    await rmdir(path.join(core.store.path, 'cores'))
  }

  function setBitInPage (index) {
    const n = index & 32767
    const p = (index - n) / 32768

    let page = pages.get(p)

    if (!page) {
      page = new Uint32Array(1024)
      pages.set(p, page)
    }

    const o = n & 31
    const b = (n - o) / 32
    const v = 1 << o

    page[b] |= v
  }

  async function writeBlocksBatch () {
    const read = core.read()
    const promises = []
    for (const index of batch) promises.push(getByteRangeFromStorage(read, 2 * index, roots, cache))
    read.tryFlush()

    const r = await Promise.all(promises)
    const tx = core.write()

    for (let i = 0; i < r.length; i++) {
      const index = batch[i]
      const [offset, size] = r[i]

      const blk = await blocks.take(offset, size)
      tx.putBlock(index, blk)
    }

    batch = []
    if (cache.size > 16384) cache.clear()

    await tx.flush()
  }
}

async function commitCoreMigration (auth, core, version) {
  const view = new View()
  const rx = new CorestoreRX(core.db, view)

  const storeCorePromise = rx.getCore(auth.discoveryKey)
  rx.tryFlush()

  const storeCore = await storeCorePromise

  storeCore.version = version

  const tx = new CorestoreTX(view)

  tx.putCore(auth.discoveryKey, storeCore)
  tx.apply()

  await View.flush(view.changes, core.db)
}

async function getBlockFromFile (file, core, index, roots, cache) {
  const rx = core.read()
  const promise = getByteRangeFromStorage(rx, 2 * index, roots, cache)
  rx.tryFlush()
  const [offset, size] = await promise

  return new Promise(function (resolve) {
    readAll(file, size, offset, function (err, buf) {
      if (err) return resolve(null)
      resolve(buf)
    })
  })
}

function getFiles (dir) {
  return {
    path: dir,
    oplog: path.join(dir, 'oplog'),
    data: path.join(dir, 'data'),
    tree: path.join(dir, 'tree'),
    bitfield: path.join(dir, 'bitfield')
  }
}

async function getRootsFromStorage (core, length) {
  const all = []
  const rx = core.read()
  for (const index of flat.fullRoots(2 * length)) {
    all.push(rx.getTreeNode(index))
  }
  rx.tryFlush()
  return Promise.all(all)
}

async function getRoots (length, getTreeNode) {
  const all = []
  for (const index of flat.fullRoots(2 * length)) {
    all.push(await getTreeNode(index))
  }
  return all
}

function getCached (read, cache, index) {
  if (cache.has(index)) return cache.get(index)
  const p = read.getTreeNode(index)
  cache.set(index, p)
  return p
}

async function getByteRangeFromStorage (read, index, roots, cache) {
  const promises = [getCached(read, cache, index), getByteOffsetFromStorage(read, index, roots, cache)]
  const [node, offset] = await Promise.all(promises)
  if (!node) throw new Error('Node not found during migration: ' + index)
  return [offset, node.size]
}

async function getByteOffsetFromStorage (rx, index, roots, cache) {
  if (index === 0) return 0
  if ((index & 1) === 1) index = flat.leftSpan(index)

  let head = 0
  let offset = 0

  for (const node of roots) { // all async ticks happen once we find the root so safe
    head += 2 * ((node.index - head) + 1)

    if (index >= head) {
      offset += node.size
      continue
    }

    const ite = flat.iterator(node.index)
    const promises = []

    while (ite.index !== index) {
      if (index < ite.index) {
        ite.leftChild()
      } else {
        promises.push(getCached(rx, cache, ite.leftChild()))
        ite.sibling()
      }
    }

    const nodes = await Promise.all(promises)
    for (const node of nodes) offset += node.size

    return offset
  }

  throw new Error('Failed to find offset')
}

function decodeTreeNode (index, buf) {
  return { index, size: c.decode(c.uint64, buf), hash: buf.subarray(8) }
}

async function getTreeNodeFromFile (file, index) {
  return new Promise(function (resolve) {
    readAll(file, 40, index * 40, function (err, buf) {
      if (err) return resolve(null)
      resolve(decodeTreeNode(index, buf))
    })
  })
}

function readAll (filename, length, pos, cb) {
  const buf = b4a.alloc(length)

  fs.open(filename, 'r', function (err, fd) {
    if (err) return cb(err)

    let offset = 0

    fs.read(fd, buf, offset, buf.byteLength, pos, function loop (err, read) {
      if (err) return done(err)
      if (read === 0) return done(new Error('Partial read'))
      offset += read
      if (offset === buf.byteLength) return done(null, buf)
      fs.read(fd, offset, buf.byteLength - offset, buf, pos + offset, loop)
    })

    function done (err, value) {
      fs.close(fd, () => cb(err, value))
    }
  })
}

async function readdir (dir) {
  try {
    return await fs.promises.readdir(dir)
  } catch {
    return []
  }
}

async function exists (file) {
  try {
    await fs.promises.stat(file)
    return true
  } catch {
    return false
  }
}

async function readFile (file) {
  try {
    return await fs.promises.readFile(file)
  } catch {
    return null
  }
}

async function rm (dir) {
  try {
    await fs.promises.rm(dir, { recursive: true })
  } catch {}
}

async function rmdir (dir) {
  try {
    await fs.promises.rmdir(dir)
  } catch {}
}

function * allBits (buffer) {
  for (let i = 0; i < buffer.byteLength; i += EMPTY_PAGE.byteLength) {
    const page = buffer.subarray(i, i + EMPTY_NODE.byteLength)
    if (b4a.equals(page, EMPTY_PAGE)) continue

    const view = new Uint32Array(page.buffer, page.byteOffset, EMPTY_PAGE.byteLength / 4)

    for (let j = 0; j < view.length; j++) {
      const n = view[j]
      if (n === 0) continue

      for (let k = 0; k < 32; k++) {
        const m = 1 << k
        if (n & m) yield i * 8 + j * 32 + k
      }
    }
  }
}

function readOplog (oplog) {
  return new Promise(function (resolve) {
    fs.readFile(oplog, function (err, buffer) {
      if (err) return resolve(null)

      const state = { start: 0, end: buffer.byteLength, buffer }
      const headers = [1, 0]

      const h1 = decodeOplogHeader(state)
      state.start = 4096

      const h2 = decodeOplogHeader(state)
      state.start = 4096 * 2

      if (!h1 && !h2) return resolve(null)

      if (h1 && !h2) {
        headers[0] = h1.header
        headers[1] = h1.header
      } else if (!h1 && h2) {
        headers[0] = (h2.header + 1) & 1
        headers[1] = h2.header
      } else {
        headers[0] = h1.header
        headers[1] = h2.header
      }

      const header = (headers[0] + headers[1]) & 1
      const result = { path: path.dirname(oplog), header: null, entries: [] }
      const decoded = []

      result.header = header ? h2.message : h1.message

      if (result.header.external) {
        fs.readFile(path.join(oplog, '../header'), function (err, buffer) {
          if (err) return resolve(null)
          const start = result.header.external.start
          const end = start + result.header.external.length
          result.header = m.oplog.header.decode({ buffer, start, end })
          finish()
        })
        return
      }

      finish()

      function finish () {
        while (true) {
          const entry = decodeOplogEntry(state)
          if (!entry) break
          if (entry.header !== header) break

          decoded.push(entry)
        }

        while (decoded.length > 0 && decoded[decoded.length - 1].partial) decoded.pop()

        for (const e of decoded) {
          result.entries.push(e.message)
        }

        resolve(result)
      }
    })
  })
}

function noop () {}
// needed here for compat, copied from old hypercore, do not change this

const c = require('compact-encoding')
const b4a = require('b4a')

const EMPTY = b4a.alloc(0)
const DEFAULT_NAMESPACE = b4a.from('4144eea531e483d54e0c14f4ca68e0644f355343ff6fcb0f005200e12cd747cb', 'hex')

const hashes = {
  preencode (state, m) {
    state.end++ // small uint
  },
  encode (state, m) {
    if (m === 'blake2b') {
      c.uint.encode(state, 0)
      return
    }

    throw new Error('Unknown hash: ' + m)
  },
  decode (state) {
    const n = c.uint.decode(state)
    if (n === 0) return 'blake2b'
    throw new Error('Unknown hash id: ' + n)
  }
}

const signatures = {
  preencode (state, m) {
    state.end++ // small uint
  },
  encode (state, m) {
    if (m === 'ed25519') {
      c.uint.encode(state, 0)
      return
    }

    throw new Error('Unknown signature: ' + m)
  },
  decode (state) {
    const n = c.uint.decode(state)
    if (n === 0) return 'ed25519'
    throw new Error('Unknown signature id: ' + n)
  }
}

const signer = {
  preencode (state, m) {
    signatures.preencode(state, m.signature)
    c.fixed32.preencode(state, m.namespace)
    c.fixed32.preencode(state, m.publicKey)
  },
  encode (state, m) {
    signatures.encode(state, m.signature)
    c.fixed32.encode(state, m.namespace)
    c.fixed32.encode(state, m.publicKey)
  },
  decode (state) {
    return {
      signature: signatures.decode(state),
      namespace: c.fixed32.decode(state),
      publicKey: c.fixed32.decode(state)
    }
  }
}

const signerArray = c.array(signer)

const prologue = {
  preencode (state, p) {
    c.fixed32.preencode(state, p.hash)
    c.uint.preencode(state, p.length)
  },
  encode (state, p) {
    c.fixed32.encode(state, p.hash)
    c.uint.encode(state, p.length)
  },
  decode (state) {
    return {
      hash: c.fixed32.decode(state),
      length: c.uint.decode(state)
    }
  }
}

const manifestv0 = {
  preencode (state, m) {
    hashes.preencode(state, m.hash)
    state.end++ // type

    if (m.prologue && m.signers.length === 0) {
      c.fixed32.preencode(state, m.prologue.hash)
      return
    }

    if (m.quorum === 1 && m.signers.length === 1 && !m.allowPatch) {
      signer.preencode(state, m.signers[0])
    } else {
      state.end++ // flags
      c.uint.preencode(state, m.quorum)
      signerArray.preencode(state, m.signers)
    }
  },
  encode (state, m) {
    hashes.encode(state, m.hash)

    if (m.prologue && m.signers.length === 0) {
      c.uint.encode(state, 0)
      c.fixed32.encode(state, m.prologue.hash)
      return
    }

    if (m.quorum === 1 && m.signers.length === 1 && !m.allowPatch) {
      c.uint.encode(state, 1)
      signer.encode(state, m.signers[0])
    } else {
      c.uint.encode(state, 2)
      c.uint.encode(state, m.allowPatch ? 1 : 0)
      c.uint.encode(state, m.quorum)
      signerArray.encode(state, m.signers)
    }
  },
  decode (state) {
    const hash = hashes.decode(state)
    const type = c.uint.decode(state)

    if (type > 2) throw new Error('Unknown type: ' + type)

    if (type === 0) {
      return {
        version: 0,
        hash,
        allowPatch: false,
        quorum: 0,
        signers: [],
        prologue: {
          hash: c.fixed32.decode(state),
          length: 0
        }
      }
    }

    if (type === 1) {
      return {
        version: 0,
        hash,
        allowPatch: false,
        quorum: 1,
        signers: [signer.decode(state)],
        prologue: null
      }
    }

    const flags = c.uint.decode(state)

    return {
      version: 0,
      hash,
      allowPatch: (flags & 1) !== 0,
      quorum: c.uint.decode(state),
      signers: signerArray.decode(state),
      prologue: null
    }
  }
}

const manifest = exports.manifest = {
  preencode (state, m) {
    state.end++ // version
    if (m.version === 0) return manifestv0.preencode(state, m)

    state.end++ // flags
    hashes.preencode(state, m.hash)

    c.uint.preencode(state, m.quorum)
    signerArray.preencode(state, m.signers)
    if (m.prologue) prologue.preencode(state, m.prologue)
  },
  encode (state, m) {
    c.uint.encode(state, m.version)
    if (m.version === 0) return manifestv0.encode(state, m)

    c.uint.encode(state, (m.allowPatch ? 1 : 0) | (m.prologue ? 2 : 0) | (m.unencrypted ? 4 : 0))
    hashes.encode(state, m.hash)

    c.uint.encode(state, m.quorum)
    signerArray.encode(state, m.signers)
    if (m.prologue) prologue.encode(state, m.prologue)
  },
  decode (state) {
    const v = c.uint.decode(state)
    if (v === 0) return manifestv0.decode(state)
    if (v !== 1) throw new Error('Unknown version: ' + v)

    const flags = c.uint.decode(state)
    const hash = hashes.decode(state)
    const quorum = c.uint.decode(state)
    const signers = signerArray.decode(state)
    const unencrypted = (flags & 4) !== 0

    return {
      version: 1,
      hash,
      allowPatch: (flags & 1) !== 0,
      quorum,
      signers,
      prologue: (flags & 2) === 0 ? null : prologue.decode(state),
      unencrypted
    }
  }
}

const node = {
  preencode (state, n) {
    c.uint.preencode(state, n.index)
    c.uint.preencode(state, n.size)
    c.fixed32.preencode(state, n.hash)
  },
  encode (state, n) {
    c.uint.encode(state, n.index)
    c.uint.encode(state, n.size)
    c.fixed32.encode(state, n.hash)
  },
  decode (state) {
    return {
      index: c.uint.decode(state),
      size: c.uint.decode(state),
      hash: c.fixed32.decode(state)
    }
  }
}

const nodeArray = c.array(node)

const wire = exports.wire = {}

wire.handshake = {
  preencode (state, m) {
    c.uint.preencode(state, 1)
    c.fixed32.preencode(state, m.capability)
  },
  encode (state, m) {
    c.uint.encode(state, m.seeks ? 1 : 0)
    c.fixed32.encode(state, m.capability)
  },
  decode (state) {
    const flags = c.uint.decode(state)
    return {
      seeks: (flags & 1) !== 0,
      capability: c.fixed32.decode(state)
    }
  }
}

const requestBlock = {
  preencode (state, b) {
    c.uint.preencode(state, b.index)
    c.uint.preencode(state, b.nodes)
  },
  encode (state, b) {
    c.uint.encode(state, b.index)
    c.uint.encode(state, b.nodes)
  },
  decode (state) {
    return {
      index: c.uint.decode(state),
      nodes: c.uint.decode(state)
    }
  }
}

const requestSeek = {
  preencode (state, s) {
    c.uint.preencode(state, s.bytes)
    c.uint.preencode(state, s.padding)
  },
  encode (state, s) {
    c.uint.encode(state, s.bytes)
    c.uint.encode(state, s.padding)
  },
  decode (state) {
    return {
      bytes: c.uint.decode(state),
      padding: c.uint.decode(state)
    }
  }
}

const requestUpgrade = {
  preencode (state, u) {
    c.uint.preencode(state, u.start)
    c.uint.preencode(state, u.length)
  },
  encode (state, u) {
    c.uint.encode(state, u.start)
    c.uint.encode(state, u.length)
  },
  decode (state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

wire.request = {
  preencode (state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.id)
    c.uint.preencode(state, m.fork)

    if (m.block) requestBlock.preencode(state, m.block)
    if (m.hash) requestBlock.preencode(state, m.hash)
    if (m.seek) requestSeek.preencode(state, m.seek)
    if (m.upgrade) requestUpgrade.preencode(state, m.upgrade)
    if (m.priority) c.uint.preencode(state, m.priority)
  },
  encode (state, m) {
    const flags = (m.block ? 1 : 0) | (m.hash ? 2 : 0) | (m.seek ? 4 : 0) | (m.upgrade ? 8 : 0) | (m.manifest ? 16 : 0) | (m.priority ? 32 : 0)

    c.uint.encode(state, flags)
    c.uint.encode(state, m.id)
    c.uint.encode(state, m.fork)

    if (m.block) requestBlock.encode(state, m.block)
    if (m.hash) requestBlock.encode(state, m.hash)
    if (m.seek) requestSeek.encode(state, m.seek)
    if (m.upgrade) requestUpgrade.encode(state, m.upgrade)
    if (m.priority) c.uint.encode(state, m.priority)
  },
  decode (state) {
    const flags = c.uint.decode(state)

    return {
      id: c.uint.decode(state),
      fork: c.uint.decode(state),
      block: flags & 1 ? requestBlock.decode(state) : null,
      hash: flags & 2 ? requestBlock.decode(state) : null,
      seek: flags & 4 ? requestSeek.decode(state) : null,
      upgrade: flags & 8 ? requestUpgrade.decode(state) : null,
      manifest: (flags & 16) !== 0,
      priority: flags & 32 ? c.uint.decode(state) : 0
    }
  }
}

wire.cancel = {
  preencode (state, m) {
    c.uint.preencode(state, m.request)
  },
  encode (state, m) {
    c.uint.encode(state, m.request)
  },
  decode (state, m) {
    return {
      request: c.uint.decode(state)
    }
  }
}

const dataUpgrade = {
  preencode (state, u) {
    c.uint.preencode(state, u.start)
    c.uint.preencode(state, u.length)
    nodeArray.preencode(state, u.nodes)
    nodeArray.preencode(state, u.additionalNodes)
    c.optionalBuffer.preencode(state, u.signature)
  },
  encode (state, u) {
    c.uint.encode(state, u.start)
    c.uint.encode(state, u.length)
    nodeArray.encode(state, u.nodes)
    nodeArray.encode(state, u.additionalNodes)
    c.optionalBuffer.encode(state, u.signature)
  },
  decode (state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state),
      nodes: nodeArray.decode(state),
      additionalNodes: nodeArray.decode(state),
      signature: c.optionalBuffer.decode(state)
    }
  }
}

const dataSeek = {
  preencode (state, s) {
    c.uint.preencode(state, s.bytes)
    nodeArray.preencode(state, s.nodes)
  },
  encode (state, s) {
    c.uint.encode(state, s.bytes)
    nodeArray.encode(state, s.nodes)
  },
  decode (state) {
    return {
      bytes: c.uint.decode(state),
      nodes: nodeArray.decode(state)
    }
  }
}

const dataBlock = {
  preencode (state, b) {
    c.uint.preencode(state, b.index)
    c.optionalBuffer.preencode(state, b.value)
    nodeArray.preencode(state, b.nodes)
  },
  encode (state, b) {
    c.uint.encode(state, b.index)
    c.optionalBuffer.encode(state, b.value)
    nodeArray.encode(state, b.nodes)
  },
  decode (state) {
    return {
      index: c.uint.decode(state),
      value: c.optionalBuffer.decode(state) || EMPTY,
      nodes: nodeArray.decode(state)
    }
  }
}

const dataHash = {
  preencode (state, b) {
    c.uint.preencode(state, b.index)
    nodeArray.preencode(state, b.nodes)
  },
  encode (state, b) {
    c.uint.encode(state, b.index)
    nodeArray.encode(state, b.nodes)
  },
  decode (state) {
    return {
      index: c.uint.decode(state),
      nodes: nodeArray.decode(state)
    }
  }
}

wire.data = {
  preencode (state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.request)
    c.uint.preencode(state, m.fork)

    if (m.block) dataBlock.preencode(state, m.block)
    if (m.hash) dataHash.preencode(state, m.hash)
    if (m.seek) dataSeek.preencode(state, m.seek)
    if (m.upgrade) dataUpgrade.preencode(state, m.upgrade)
    if (m.manifest) manifest.preencode(state, m.manifest)
  },
  encode (state, m) {
    const flags = (m.block ? 1 : 0) | (m.hash ? 2 : 0) | (m.seek ? 4 : 0) | (m.upgrade ? 8 : 0) | (m.manifest ? 16 : 0)

    c.uint.encode(state, flags)
    c.uint.encode(state, m.request)
    c.uint.encode(state, m.fork)

    if (m.block) dataBlock.encode(state, m.block)
    if (m.hash) dataHash.encode(state, m.hash)
    if (m.seek) dataSeek.encode(state, m.seek)
    if (m.upgrade) dataUpgrade.encode(state, m.upgrade)
    if (m.manifest) manifest.encode(state, m.manifest)
  },
  decode (state) {
    const flags = c.uint.decode(state)

    return {
      request: c.uint.decode(state),
      fork: c.uint.decode(state),
      block: flags & 1 ? dataBlock.decode(state) : null,
      hash: flags & 2 ? dataHash.decode(state) : null,
      seek: flags & 4 ? dataSeek.decode(state) : null,
      upgrade: flags & 8 ? dataUpgrade.decode(state) : null,
      manifest: flags & 16 ? manifest.decode(state) : null
    }
  }
}

wire.noData = {
  preencode (state, m) {
    c.uint.preencode(state, m.request)
  },
  encode (state, m) {
    c.uint.encode(state, m.request)
  },
  decode (state, m) {
    return {
      request: c.uint.decode(state)
    }
  }
}

wire.want = {
  preencode (state, m) {
    c.uint.preencode(state, m.start)
    c.uint.preencode(state, m.length)
  },
  encode (state, m) {
    c.uint.encode(state, m.start)
    c.uint.encode(state, m.length)
  },
  decode (state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

wire.unwant = {
  preencode (state, m) {
    c.uint.preencode(state, m.start)
    c.uint.preencode(state, m.length)
  },
  encode (state, m) {
    c.uint.encode(state, m.start)
    c.uint.encode(state, m.length)
  },
  decode (state, m) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

wire.range = {
  preencode (state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.start)
    if (m.length !== 1) c.uint.preencode(state, m.length)
  },
  encode (state, m) {
    c.uint.encode(state, (m.drop ? 1 : 0) | (m.length === 1 ? 2 : 0))
    c.uint.encode(state, m.start)
    if (m.length !== 1) c.uint.encode(state, m.length)
  },
  decode (state) {
    const flags = c.uint.decode(state)

    return {
      drop: (flags & 1) !== 0,
      start: c.uint.decode(state),
      length: (flags & 2) !== 0 ? 1 : c.uint.decode(state)
    }
  }
}

wire.bitfield = {
  preencode (state, m) {
    c.uint.preencode(state, m.start)
    c.uint32array.preencode(state, m.bitfield)
  },
  encode (state, m) {
    c.uint.encode(state, m.start)
    c.uint32array.encode(state, m.bitfield)
  },
  decode (state, m) {
    return {
      start: c.uint.decode(state),
      bitfield: c.uint32array.decode(state)
    }
  }
}

wire.sync = {
  preencode (state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.fork)
    c.uint.preencode(state, m.length)
    c.uint.preencode(state, m.remoteLength)
  },
  encode (state, m) {
    c.uint.encode(state, (m.canUpgrade ? 1 : 0) | (m.uploading ? 2 : 0) | (m.downloading ? 4 : 0) | (m.hasManifest ? 8 : 0))
    c.uint.encode(state, m.fork)
    c.uint.encode(state, m.length)
    c.uint.encode(state, m.remoteLength)
  },
  decode (state) {
    const flags = c.uint.decode(state)

    return {
      fork: c.uint.decode(state),
      length: c.uint.decode(state),
      remoteLength: c.uint.decode(state),
      canUpgrade: (flags & 1) !== 0,
      uploading: (flags & 2) !== 0,
      downloading: (flags & 4) !== 0,
      hasManifest: (flags & 8) !== 0
    }
  }
}

wire.reorgHint = {
  preencode (state, m) {
    c.uint.preencode(state, m.from)
    c.uint.preencode(state, m.to)
    c.uint.preencode(state, m.ancestors)
  },
  encode (state, m) {
    c.uint.encode(state, m.from)
    c.uint.encode(state, m.to)
    c.uint.encode(state, m.ancestors)
  },
  decode (state) {
    return {
      from: c.uint.encode(state),
      to: c.uint.encode(state),
      ancestors: c.uint.encode(state)
    }
  }
}

wire.extension = {
  preencode (state, m) {
    c.string.preencode(state, m.name)
    c.raw.preencode(state, m.message)
  },
  encode (state, m) {
    c.string.encode(state, m.name)
    c.raw.encode(state, m.message)
  },
  decode (state) {
    return {
      name: c.string.decode(state),
      message: c.raw.decode(state)
    }
  }
}

const keyValue = {
  preencode (state, p) {
    c.string.preencode(state, p.key)
    c.optionalBuffer.preencode(state, p.value)
  },
  encode (state, p) {
    c.string.encode(state, p.key)
    c.optionalBuffer.encode(state, p.value)
  },
  decode (state) {
    return {
      key: c.string.decode(state),
      value: c.optionalBuffer.decode(state)
    }
  }
}

const treeUpgrade = {
  preencode (state, u) {
    c.uint.preencode(state, u.fork)
    c.uint.preencode(state, u.ancestors)
    c.uint.preencode(state, u.length)
    c.optionalBuffer.preencode(state, u.signature)
  },
  encode (state, u) {
    c.uint.encode(state, u.fork)
    c.uint.encode(state, u.ancestors)
    c.uint.encode(state, u.length)
    c.optionalBuffer.encode(state, u.signature)
  },
  decode (state) {
    return {
      fork: c.uint.decode(state),
      ancestors: c.uint.decode(state),
      length: c.uint.decode(state),
      signature: c.optionalBuffer.decode(state)
    }
  }
}

const bitfieldUpdate = { // TODO: can maybe be folded into a HAVE later on with the most recent spec
  preencode (state, b) {
    state.end++ // flags
    c.uint.preencode(state, b.start)
    c.uint.preencode(state, b.length)
  },
  encode (state, b) {
    state.buffer[state.start++] = b.drop ? 1 : 0
    c.uint.encode(state, b.start)
    c.uint.encode(state, b.length)
  },
  decode (state) {
    const flags = c.uint.decode(state)
    return {
      drop: (flags & 1) !== 0,
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

const oplog = exports.oplog = {}

oplog.entry = {
  preencode (state, m) {
    state.end++ // flags
    if (m.userData) keyValue.preencode(state, m.userData)
    if (m.treeNodes) nodeArray.preencode(state, m.treeNodes)
    if (m.treeUpgrade) treeUpgrade.preencode(state, m.treeUpgrade)
    if (m.bitfield) bitfieldUpdate.preencode(state, m.bitfield)
  },
  encode (state, m) {
    const s = state.start++
    let flags = 0

    if (m.userData) {
      flags |= 1
      keyValue.encode(state, m.userData)
    }
    if (m.treeNodes) {
      flags |= 2
      nodeArray.encode(state, m.treeNodes)
    }
    if (m.treeUpgrade) {
      flags |= 4
      treeUpgrade.encode(state, m.treeUpgrade)
    }
    if (m.bitfield) {
      flags |= 8
      bitfieldUpdate.encode(state, m.bitfield)
    }

    state.buffer[s] = flags
  },
  decode (state) {
    const flags = c.uint.decode(state)
    return {
      userData: (flags & 1) !== 0 ? keyValue.decode(state) : null,
      treeNodes: (flags & 2) !== 0 ? nodeArray.decode(state) : null,
      treeUpgrade: (flags & 4) !== 0 ? treeUpgrade.decode(state) : null,
      bitfield: (flags & 8) !== 0 ? bitfieldUpdate.decode(state) : null
    }
  }
}

const keyPair = {
  preencode (state, kp) {
    c.optionalBuffer.preencode(state, kp.publicKey)
    c.optionalBuffer.preencode(state, kp.secretKey)
  },
  encode (state, kp) {
    c.optionalBuffer.encode(state, kp.publicKey)
    c.optionalBuffer.encode(state, kp.secretKey)
  },
  decode (state) {
    return {
      publicKey: c.optionalBuffer.decode(state),
      secretKey: c.optionalBuffer.decode(state)
    }
  }
}

const reorgHint = {
  preencode (state, r) {
    c.uint.preencode(state, r.from)
    c.uint.preencode(state, r.to)
    c.uint.preencode(state, r.ancestors)
  },
  encode (state, r) {
    c.uint.encode(state, r.from)
    c.uint.encode(state, r.to)
    c.uint.encode(state, r.ancestors)
  },
  decode (state) {
    return {
      from: c.uint.decode(state),
      to: c.uint.decode(state),
      ancestors: c.uint.decode(state)
    }
  }
}

const reorgHintArray = c.array(reorgHint)

const hints = {
  preencode (state, h) {
    reorgHintArray.preencode(state, h.reorgs)
    c.uint.preencode(state, h.contiguousLength)
  },
  encode (state, h) {
    reorgHintArray.encode(state, h.reorgs)
    c.uint.encode(state, h.contiguousLength)
  },
  decode (state) {
    return {
      reorgs: reorgHintArray.decode(state),
      contiguousLength: state.start < state.end ? c.uint.decode(state) : 0
    }
  }
}

const treeHeader = {
  preencode (state, t) {
    c.uint.preencode(state, t.fork)
    c.uint.preencode(state, t.length)
    c.optionalBuffer.preencode(state, t.rootHash)
    c.optionalBuffer.preencode(state, t.signature)
  },
  encode (state, t) {
    c.uint.encode(state, t.fork)
    c.uint.encode(state, t.length)
    c.optionalBuffer.encode(state, t.rootHash)
    c.optionalBuffer.encode(state, t.signature)
  },
  decode (state) {
    return {
      fork: c.uint.decode(state),
      length: c.uint.decode(state),
      rootHash: c.optionalBuffer.decode(state),
      signature: c.optionalBuffer.decode(state)
    }
  }
}

const types = {
  preencode (state, t) {
    c.string.preencode(state, t.tree)
    c.string.preencode(state, t.bitfield)
    c.string.preencode(state, t.signer)
  },
  encode (state, t) {
    c.string.encode(state, t.tree)
    c.string.encode(state, t.bitfield)
    c.string.encode(state, t.signer)
  },
  decode (state) {
    return {
      tree: c.string.decode(state),
      bitfield: c.string.decode(state),
      signer: c.string.decode(state)
    }
  }
}

const externalHeader = {
  preencode (state, m) {
    c.uint.preencode(state, m.start)
    c.uint.preencode(state, m.length)
  },
  encode (state, m) {
    c.uint.encode(state, m.start)
    c.uint.encode(state, m.length)
  },
  decode (state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

const keyValueArray = c.array(keyValue)

oplog.header = {
  preencode (state, h) {
    state.end += 2 // version + flags
    if (h.external) {
      externalHeader.preencode(state, h.external)
      return
    }
    c.fixed32.preencode(state, h.key)
    if (h.manifest) manifest.preencode(state, h.manifest)
    if (h.keyPair) keyPair.preencode(state, h.keyPair)
    keyValueArray.preencode(state, h.userData)
    treeHeader.preencode(state, h.tree)
    hints.preencode(state, h.hints)
  },
  encode (state, h) {
    c.uint.encode(state, 1)
    if (h.external) {
      c.uint.encode(state, 1) // ONLY set the first big for clarity
      externalHeader.encode(state, h.external)
      return
    }
    c.uint.encode(state, (h.manifest ? 2 : 0) | (h.keyPair ? 4 : 0))
    c.fixed32.encode(state, h.key)
    if (h.manifest) manifest.encode(state, h.manifest)
    if (h.keyPair) keyPair.encode(state, h.keyPair)
    keyValueArray.encode(state, h.userData)
    treeHeader.encode(state, h.tree)
    hints.encode(state, h.hints)
  },
  decode (state) {
    const version = c.uint.decode(state)

    if (version > 1) {
      throw new Error('Invalid header version. Expected <= 1, got ' + version)
    }

    if (version === 0) {
      const old = {
        types: types.decode(state),
        userData: keyValueArray.decode(state),
        tree: treeHeader.decode(state),
        signer: keyPair.decode(state),
        hints: hints.decode(state)
      }

      return {
        external: null,
        key: old.signer.publicKey,
        manifest: {
          version: 0,
          hash: old.types.tree,
          allowPatch: false,
          quorum: 1,
          signers: [{
            signature: old.types.signer,
            namespace: DEFAULT_NAMESPACE,
            publicKey: old.signer.publicKey
          }],
          prologue: null
        },
        keyPair: old.signer.secretKey ? old.signer : null,
        userData: old.userData,
        tree: old.tree,
        hints: old.hints
      }
    }

    const flags = c.uint.decode(state)

    if (flags & 1) {
      return {
        external: externalHeader.decode(state),
        key: null,
        manifest: null,
        keyPair: null,
        userData: null,
        tree: null,
        hints: null
      }
    }

    return {
      external: null,
      key: c.fixed32.decode(state),
      manifest: (flags & 2) !== 0 ? manifest.decode(state) : null,
      keyPair: (flags & 4) !== 0 ? keyPair.decode(state) : null,
      userData: keyValueArray.decode(state),
      tree: treeHeader.decode(state),
      hints: hints.decode(state)
    }
  }
}

const uintArray = c.array(c.uint)

const multisigInput = {
  preencode (state, inp) {
    c.uint.preencode(state, inp.signer)
    c.fixed64.preencode(state, inp.signature)
    c.uint.preencode(state, inp.patch)
  },
  encode (state, inp) {
    c.uint.encode(state, inp.signer)
    c.fixed64.encode(state, inp.signature)
    c.uint.encode(state, inp.patch)
  },
  decode (state) {
    return {
      signer: c.uint.decode(state),
      signature: c.fixed64.decode(state),
      patch: c.uint.decode(state)
    }
  }
}

const patchEncodingv0 = {
  preencode (state, n) {
    c.uint.preencode(state, n.start)
    c.uint.preencode(state, n.length)
    uintArray.preencode(state, n.nodes)
  },
  encode (state, n) {
    c.uint.encode(state, n.start)
    c.uint.encode(state, n.length)
    uintArray.encode(state, n.nodes)
  },
  decode (state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state),
      nodes: uintArray.decode(state)
    }
  }
}

const multisigInputv0 = {
  preencode (state, n) {
    state.end++
    c.uint.preencode(state, n.signer)
    c.fixed64.preencode(state, n.signature)
    if (n.patch) patchEncodingv0.preencode(state, n.patch)
  },
  encode (state, n) {
    c.uint.encode(state, n.patch ? 1 : 0)
    c.uint.encode(state, n.signer)
    c.fixed64.encode(state, n.signature)
    if (n.patch) patchEncodingv0.encode(state, n.patch)
  },
  decode (state) {
    const flags = c.uint.decode(state)
    return {
      signer: c.uint.decode(state),
      signature: c.fixed64.decode(state),
      patch: (flags & 1) ? patchEncodingv0.decode(state) : null
    }
  }
}

const multisigInputArrayv0 = c.array(multisigInputv0)
const multisigInputArray = c.array(multisigInput)

const compactNode = {
  preencode (state, n) {
    c.uint.preencode(state, n.index)
    c.uint.preencode(state, n.size)
    c.fixed32.preencode(state, n.hash)
  },
  encode (state, n) {
    c.uint.encode(state, n.index)
    c.uint.encode(state, n.size)
    c.fixed32.encode(state, n.hash)
  },
  decode (state) {
    return {
      index: c.uint.decode(state),
      size: c.uint.decode(state),
      hash: c.fixed32.decode(state)
    }
  }
}

const compactNodeArray = c.array(compactNode)

exports.multiSignaturev0 = {
  preencode (state, s) {
    multisigInputArrayv0.preencode(state, s.proofs)
    compactNodeArray.preencode(state, s.patch)
  },
  encode (state, s) {
    multisigInputArrayv0.encode(state, s.proofs)
    compactNodeArray.encode(state, s.patch)
  },
  decode (state) {
    return {
      proofs: multisigInputArrayv0.decode(state),
      patch: compactNodeArray.decode(state)
    }
  }
}

exports.multiSignature = {
  preencode (state, s) {
    multisigInputArray.preencode(state, s.proofs)
    compactNodeArray.preencode(state, s.patch)
  },
  encode (state, s) {
    multisigInputArray.encode(state, s.proofs)
    compactNodeArray.encode(state, s.patch)
  },
  decode (state) {
    return {
      proofs: multisigInputArray.decode(state),
      patch: compactNodeArray.decode(state)
    }
  }
}
const c = require('compact-encoding')
const schema = require('../../encoding/spec/hyperschema')
const { core: coreKey } = require('../../lib/keys.js')
const View = require('../../lib/view.js')

const CORE_AUTH = schema.getEncoding('@core/auth')

const { CorestoreRX, CorestoreTX } = require('../../lib/tx.js')

async function core (core, { version, dryRun = false } = {}) {
  if (dryRun) return // dryRun mode not supported atm

  const rx = core.db.read({ autoDestroy: true })
  const storedAuthPromise = rx.get(coreKey.auth(core.core.corePointer))

  rx.tryFlush()

  const storedAuth = await storedAuthPromise
  if (!storedAuth) return

  const auth = c.decode(CORE_AUTH, storedAuth)
  await commitCoreMigration(auth, core, version)
}

module.exports = { core }

async function commitCoreMigration (auth, core, version) {
  const view = new View()
  const rx = new CorestoreRX(core.db, view)

  const storeCorePromise = rx.getCore(auth.discoveryKey)
  rx.tryFlush()

  const storeCore = await storeCorePromise

  storeCore.version = version

  const tx = new CorestoreTX(view)
  tx.putCore(auth.discoveryKey, storeCore)
  tx.apply()

  await View.flush(view.changes, core.db)
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "hypercore-storage",
  "version": "3.2.0",
  "main": "index.js",
  "files": [
    "index.js",
    "lib/*.js",
    "encoding/*",
    "migrations/0/*.js",
    "migrations/1/*.js"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:bare": "brittle-bare test/all.js",
    "test:generate": "brittle -r test/all.js test/*.js",
    "test:node": "brittle-node test/all.js"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "description": "Storage engine for Hypercore",
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "fs/*": {
      "bare": "bare-fs/*",
      "default": "fs/*"
    },
    "os": {
      "bare": "bare-os",
      "default": "os"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    }
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/hypercore-storage.git"
  },
  "bugs": {
    "url": "https://github.com/holepunchto/hypercore-storage/issues"
  },
  "homepage": "https://github.com/holepunchto/hypercore-storage#readme",
  "dependencies": {
    "b4a": "^1.6.7",
    "bare-path": "^3.0.0",
    "compact-encoding": "^3.1.0",
    "device-file": "^2.1.2",
    "flat-tree": "^1.12.1",
    "hypercore-crypto": "^3.4.2",
    "hyperschema": "^1.21.0",
    "index-encoder": "^3.3.2",
    "resolve-reject-promise": "^1.0.0",
    "rocksdb-native": "^3.11.0",
    "scope-lock": "^1.2.4",
    "streamx": "^2.21.1",
    "xache": "^1.2.1"
  },
  "devDependencies": {
    "bare-os": "^3.9.1",
    "brittle": "^3.7.0",
    "hypercore-storage-2.9.0": "npm:hypercore-storage@^2.9.0",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "test-tmp": "^1.3.1"
  }
}
const { EventEmitter } = require('events')
const isOptions = require('is-options')
const crypto = require('hypercore-crypto')
const CoreStorage = require('hypercore-storage')
const c = require('compact-encoding')
const b4a = require('b4a')
const NoiseSecretStream = require('@hyperswarm/secret-stream')
const Protomux = require('protomux')
const id = require('hypercore-id-encoding')
const safetyCatch = require('safety-catch')
const unslab = require('unslab')
const flat = require('flat-tree')
const assert = require('nanoassert')

const { SMALL_WANTS } = require('./lib/feature-flags')
const { UPDATE_COMPAT } = require('./lib/wants')
const MarkBitfield = require('./lib/mark-bitfield')

const inspect = require('./lib/inspect')
const Core = require('./lib/core')
const Info = require('./lib/info')
const Download = require('./lib/download')
const DefaultEncryption = require('./lib/default-encryption')
const caps = require('./lib/caps')
const Replicator = require('./lib/replicator')
const { manifestHash, createManifest } = require('./lib/verifier')
const { ReadStream, WriteStream, ByteStream } = require('./lib/streams')
const { MerkleTree } = require('./lib/merkle-tree')
const { proof, verify } = require('./lib/fully-remote-proof')
const {
  ASSERTION,
  BAD_ARGUMENT,
  SESSION_CLOSED,
  SESSION_MOVED,
  SESSION_NOT_WRITABLE,
  SNAPSHOT_NOT_AVAILABLE,
  DECODING_ERROR,
  REQUEST_CANCELLED
} = require('hypercore-errors')

// Hypercore actually does not have any notion of max/min block sizes
// but we enforce 15mb to ensure smooth replication (each block is transmitted atomically)
const MAX_SUGGESTED_BLOCK_SIZE = 15 * 1024 * 1024

class Hypercore extends EventEmitter {
  constructor(storage, key, opts) {
    super()

    if (isOptions(storage) && !storage.db) {
      opts = storage
      storage = null
      key = opts.key || null
    } else if (isOptions(key)) {
      opts = key
      key = opts.key || null
    }

    if (key && typeof key === 'string') key = id.decode(key)
    if (!opts) opts = {}

    if (!storage) storage = opts.storage

    this.core = null
    this.state = null
    this.encryption = null
    this.extensions = new Map()

    this.valueEncoding = null
    this.encodeBatch = null
    this.activeRequests = []
    this.sessions = null
    this.ongc = null

    this.keyPair = opts.keyPair || null
    this.readable = true
    this.writable = false
    this.exclusive = false
    this.opened = false
    this.closed = false
    this.weak = !!opts.weak
    this.snapshotted = !!opts.snapshot
    this.onseq = opts.onseq || null
    this.onwait = opts.onwait || null
    this.wait = opts.wait !== false
    this.timeout = opts.timeout || 0
    this.preload = null
    this.closing = null
    this.opening = null

    this._readonly = opts.writable === false
    this._preappend = preappend.bind(this)
    this._snapshot = null
    this._findingPeers = 0
    this._active = opts.weak ? !!opts.active : opts.active !== false

    this.waits = 0

    // Mark & Sweep GC
    this._marking = false
    this._marks = null

    this._sessionIndex = -1
    this._stateIndex = -1 // maintained by session state
    this._monitorIndex = -1 // maintained by replication state

    this.opening = this._open(storage, key, opts)
    this.opening.catch(safetyCatch)

    this.on('newListener', maybeAddMonitor)
  }

  [Symbol.for('nodejs.util.inspect.custom')](depth, opts) {
    return inspect(this, depth, opts)
  }

  static MAX_SUGGESTED_BLOCK_SIZE = MAX_SUGGESTED_BLOCK_SIZE

  static DefaultEncryption = DefaultEncryption

  static SMALL_WANTS = SMALL_WANTS

  static enable(flag) {
    const enableCompat = (flag & SMALL_WANTS) === 0
    UPDATE_COMPAT(enableCompat)
  }

  static setRecoveryPeers(peers) {
    Core.setRecoveryPeers(peers)
  }

  static key(manifest, { compat, version, namespace } = {}) {
    if (b4a.isBuffer(manifest)) {
      manifest = { version, signers: [{ publicKey: manifest, namespace }] }
    }
    return compat ? manifest.signers[0].publicKey : manifestHash(createManifest(manifest))
  }

  static discoveryKey(key) {
    return crypto.discoveryKey(key)
  }

  static blockEncryptionKey(key, encryptionKey) {
    return DefaultEncryption.blockEncryptionKey(key, encryptionKey)
  }

  static getProtocolMuxer(stream) {
    return stream.noiseStream.userData
  }

  static createCore(storage, opts) {
    return new Core(Hypercore.defaultStorage(storage), { autoClose: false, ...opts })
  }

  static createProtocolStream(isInitiator, opts = {}) {
    let outerStream = Protomux.isProtomux(isInitiator)
      ? isInitiator.stream
      : isStream(isInitiator)
        ? isInitiator
        : opts.stream

    let noiseStream = null

    if (outerStream) {
      noiseStream = outerStream.noiseStream
    } else {
      noiseStream = new NoiseSecretStream(isInitiator, null, opts)
      outerStream = noiseStream.rawStream
    }
    if (!noiseStream) throw BAD_ARGUMENT('Invalid stream', this.discoveryKey)

    if (!noiseStream.userData) {
      const protocol = Protomux.from(noiseStream)

      if (opts.keepAlive !== false && noiseStream.keepAlive === 0) {
        noiseStream.setKeepAlive(5000)
      }
      noiseStream.userData = protocol
    }

    if (opts.ondiscoverykey) {
      const ondiscoverykey = createDiscoveryKeyHandler(opts.ondiscoverykey)
      noiseStream.userData.pair({ protocol: 'hypercore/alpha' }, ondiscoverykey)
    }

    return outerStream
  }

  static defaultStorage(storage, opts = {}) {
    if (CoreStorage.isCoreStorage(storage)) return storage

    const directory = storage
    return new CoreStorage(directory, opts)
  }

  static clearRequests(session, err) {
    Replicator.clearRequests(session, err)
  }

  static destroyRequests(session, err) {
    if (isRequestsDestroyed(session)) return
    Replicator.clearRequests(session, err)
    session.push(null) // mark as dead
  }

  static async treeHashFromStorage(session, length = session.length) {
    const roots = await MerkleTree.getRoots(session.state, length)
    return crypto.tree(roots)
  }

  snapshot(opts) {
    return this.session({ ...opts, snapshot: true })
  }

  compact() {
    return this.core.compact()
  }

  session(opts = {}) {
    if (this.closing) {
      // This makes the closing logic a lot easier. If this turns out to be a problem
      // in practice, open an issue and we'll try to make a solution for it.
      throw SESSION_CLOSED('Cannot make sessions on a closing core', this.discoveryKey)
    }
    if (opts.checkout !== undefined && !opts.name && !opts.atom) {
      throw ASSERTION('Checkouts are only supported on atoms or named sessions', this.discoveryKey)
    }

    const wait = opts.wait === false ? false : this.wait
    const writable = opts.writable === undefined ? !this._readonly : opts.writable === true
    const onwait = opts.onwait === undefined ? this.onwait : opts.onwait
    const onseq = opts.onseq === undefined ? this.onseq : opts.onseq
    const timeout = opts.timeout === undefined ? this.timeout : opts.timeout
    const weak = opts.weak === undefined ? this.weak : opts.weak
    const marking = this._marking
    const marks = this._marks
    const Clz = opts.class || Hypercore
    const s = new Clz(null, this.key, {
      ...opts,
      wait,
      onwait,
      onseq,
      timeout,
      writable,
      weak,
      parent: this
    })
    s._marking = marking
    s._marks = marks

    return s
  }

  async setEncryptionKey(key, opts) {
    if (!this.opened) await this.opening
    const encryption = this._getEncryptionProvider({ key, block: !!(opts && opts.block) })
    return this.setEncryption(encryption)
  }

  async setEncryption(encryption) {
    if (!this.opened) await this.opening

    if (encryption === null) {
      this.encryption = encryption
      return
    }

    if (!isEncryptionProvider(encryption)) {
      throw ASSERTION('Provider does not satisfy HypercoreEncryption interface', this.discoveryKey)
    }

    this.encryption = encryption
  }

  async setGroup(topic) {
    if (!this.opened) await this.opening
    return this.core.setGroup(topic)
  }

  setKeyPair(keyPair) {
    this.keyPair = keyPair
  }

  setActive(bool) {
    const active = !!bool
    if (active === this._active || this.closing) return
    this._active = active
    if (!this.opened) return
    this.core.replicator.updateActivity(this._active ? 1 : -1)
  }

  async _open(storage, key, opts) {
    const preload = opts.preload || (opts.parent && opts.parent.preload)

    if (preload) {
      this.sessions = [] // in case someone looks at it like with peers
      this.preload = preload
      opts = { ...opts, ...(await this.preload) }
      this.preload = null
    }

    const parent = opts.parent || null
    const core = opts.core || (parent && parent.core)
    const sessions = opts.sessions || (parent && parent.sessions)
    const ongc = opts.ongc || (parent && parent.ongc)

    if (core) this.core = core
    if (ongc) this.ongc = ongc
    if (sessions) this.sessions = sessions

    if (this.sessions === null) this.sessions = []
    this._sessionIndex = this.sessions.push(this) - 1

    if (this.core === null) initOnce(this, storage, key, opts)
    if (this._monitorIndex === -2) this.core.addMonitor(this)

    try {
      await this._openSession(opts)
    } catch (err) {
      if (this.core.autoClose && this.core.hasSession() === false) await this.core.close()

      if (this.exclusive) this.core.unlockExclusive()

      this.core.removeMonitor(this)
      this._removeSession()

      if (this.state !== null) this.state.removeSession(this)

      this.closed = true
      this.emit('close')
      throw err
    }

    // Setup automatic recovery if in repair mode
    if (this.core._repairMode) {
      const recoverTreeNodeFromPeersBound = this.recoverTreeNodeFromPeers.bind(this)
      this.once('repaired', () => {
        this.off('peer-add', recoverTreeNodeFromPeersBound)
      })
      this.on('peer-add', recoverTreeNodeFromPeersBound)
    }

    this.emit('ready')

    // if we are a weak session the core might have closed...
    if (this.core.closing) this.close().catch(safetyCatch)
  }

  _removeSession() {
    if (this._sessionIndex === -1) return
    const head = this.sessions.pop()
    if (head !== this) this.sessions[(head._sessionIndex = this._sessionIndex)] = head
    this._sessionIndex = -1
    if (this.ongc !== null) this.ongc(this)
  }

  async _openSession(opts) {
    if (this.core.opened === false) await this.core.ready()

    if (this.keyPair === null) this.keyPair = opts.keyPair || this.core.header.keyPair

    const parent = opts.parent || null
    if (parent && parent.encryption) this.encryption = parent.encryption

    const e = getEncryptionOption(opts)
    if (!this.encryption) this.encryption = this._getEncryptionProvider(e)

    this.writable = this._isWritable()

    if (opts.valueEncoding) {
      this.valueEncoding = c.from(opts.valueEncoding)
    }
    if (opts.encodeBatch) {
      this.encodeBatch = opts.encodeBatch
    }

    // one session sets for pushOnly for all
    if (opts.pushOnly === true) {
      this.core.replicator.setPushOnly(true)
    }

    if (parent) {
      if (parent._stateIndex === -1) await parent.ready()
      if (!this.keyPair) this.keyPair = parent.keyPair

      const ps = parent.state

      if (ps) {
        const shouldSnapshot = this.snapshotted && !ps.isSnapshot()
        this.state = shouldSnapshot ? await ps.snapshot() : ps.ref()
      }

      if (this.snapshotted && this.core && !this._snapshot) {
        this._updateSnapshot()
      }
    }

    if (opts.exclusive && opts.writable !== false) {
      this.exclusive = true
      await this.core.lockExclusive()
    }

    const parentState = parent ? parent.state : this.core.state
    const checkout = opts.checkout === undefined ? -1 : opts.checkout
    const state = this.state

    if (opts.atom) {
      this.state = await parentState.createSession(null, false, opts.atom)
      if (state) state.unref()
    } else if (opts.name) {
      // todo: need to make named sessions safe before ready
      // atm we always copy the state in passCapabilities
      this.state = await parentState.createSession(opts.name, !!opts.overwrite, null)
      if (state) state.unref() // ref'ed above in setup session
    }

    if (this.state && checkout !== -1) {
      if (!opts.name && !opts.atom) {
        throw ASSERTION('Checkouts must be named or atomized', this.discoveryKey)
      }
      if (checkout > this.state.length) {
        throw ASSERTION(
          `Invalid checkout ${checkout} for ${opts.name}, length is ${this.state.length}`,
          this.discoveryKey
        )
      }
      if (this.state.prologue && checkout < this.state.prologue.length) {
        throw ASSERTION(
          `Invalid checkout ${checkout} for ${opts.name}, prologue length is ${this.state.prologue.length}`,
          this.discoveryKey
        )
      }
      if (checkout < this.state.length) await this.state.truncate(checkout, this.fork)
    }

    if (this.state === null) {
      this.state = this.core.state.ref()
    }

    this.writable = this._isWritable()

    if (this.snapshotted && this.core) this._updateSnapshot()

    this.state.addSession(this)
    // TODO: we need to rework the core reference flow, as the state and session do not always agree now due to moveTo
    this.core = this.state.core // in case it was wrong...

    if (opts.userData) {
      const tx = this.state.storage.write()
      for (const [key, value] of Object.entries(opts.userData)) {
        tx.putUserData(key, value)
      }
      await tx.flush()
    }

    if (opts.manifest && !this.core.header.manifest) {
      await this.core.setManifest(createManifest(opts.manifest))
    }

    this.core.replicator.updateActivity(this._active ? 1 : 0)

    this.opened = true
  }

  get replicator() {
    return this.core === null ? null : this.core.replicator
  }

  _getSnapshot() {
    return {
      length: this.state.length,
      byteLength: this.state.byteLength,
      fork: this.state.fork
    }
  }

  _updateSnapshot() {
    const prev = this._snapshot
    const next = (this._snapshot = this._getSnapshot())

    if (!prev) return true
    return prev.length !== next.length || prev.fork !== next.fork
  }

  _isWritable() {
    if (this._readonly) return false
    if (this.state && !this.state.isDefault()) return true
    return !!(this.keyPair && this.keyPair.secretKey)
  }

  close({ error } = {}) {
    if (this.closing) return this.closing

    this.closing = this._close(error || null)
    return this.closing
  }

  clearRequests(activeRequests, error) {
    if (!activeRequests.length) return
    if (this.core) this.core.replicator.clearRequests(activeRequests, error)
  }

  async _close(error) {
    if (this.opened === false) {
      try {
        await this.opening
      } catch (err) {
        if (!this.closed) throw err
      }
    }

    if (this.closed === true) return

    this.core.removeMonitor(this)
    this.state.removeSession(this)
    this._removeSession()

    this.readable = false
    this.writable = false
    this.opened = false

    const gc = []
    for (const ext of this.extensions.values()) {
      if (ext.session === this) gc.push(ext)
    }
    for (const ext of gc) ext.destroy()

    this.core.replicator.findingPeers -= this._findingPeers
    this.core.replicator.clearRequests(this.activeRequests, error)
    this.core.replicator.updateActivity(this._active ? -1 : 0)

    this._findingPeers = 0

    this.state.unref()

    if (this.exclusive) this.core.unlockExclusive()

    if (this.core.hasSession()) {
      // emit "fake" close as this is a session
      this.closed = true
      this.emit('close')
      return
    }

    if (this.core.autoClose) await this.core.close()

    this.closed = true
    this.emit('close')
  }

  async commit(session, opts) {
    await this.ready()
    await session.ready()

    return this.state.commit(session.state, { keyPair: this.keyPair, ...opts })
  }

  replicate(isInitiator, opts = {}) {
    // Only limitation here is that ondiscoverykey doesn't work atm when passing a muxer directly,
    // because it doesn't really make a lot of sense.
    if (Protomux.isProtomux(isInitiator)) return this._attachToMuxer(isInitiator)

    // if same stream is passed twice, ignore the 2nd one before we make sessions etc
    if (isStream(isInitiator) && this._isAttached(isInitiator)) return isInitiator

    const protocolStream = Hypercore.createProtocolStream(isInitiator, opts)
    const noiseStream = protocolStream.noiseStream
    const protocol = noiseStream.userData

    this._attachToMuxer(protocol)

    return protocolStream
  }

  _isAttached(stream) {
    return (
      stream.userData &&
      this.core &&
      this.core.replicator &&
      this.core.replicator.attached(stream.userData)
    )
  }

  _attachToMuxer(mux) {
    if (this.opened) {
      this.core.replicator.attachTo(mux)
    } else {
      this.opening.then(() => this.core.replicator.attachTo(mux), mux.destroy.bind(mux))
    }

    return mux
  }

  get id() {
    return this.core === null ? null : this.core.id
  }

  get key() {
    return this.core === null ? null : this.core.key
  }

  get discoveryKey() {
    return this.core === null ? null : this.core.discoveryKey
  }

  get manifest() {
    return this.core === null ? null : this.core.manifest
  }

  get length() {
    if (this._snapshot) return this._snapshot.length
    return this.opened === false ? 0 : this.state.length
  }

  get signedLength() {
    return this.opened === false ? 0 : this.state.signedLength()
  }

  /**
   * Deprecated. Use `const { byteLength } = await core.info()`.
   */
  get byteLength() {
    if (this.opened === false) return 0
    if (this._snapshot) return this._snapshot.byteLength
    return this.state.byteLength - this.state.length * this.padding
  }

  get remoteContiguousLength() {
    if (this.opened === false) return 0
    return Math.min(this.core.state.length, this.core.header.hints.remoteContiguousLength)
  }

  get contiguousLength() {
    if (this.opened === false) return 0
    return Math.min(this.core.state.length, this.core.header.hints.contiguousLength)
  }

  get contiguousByteLength() {
    return 0
  }

  get fork() {
    if (this.opened === false) return 0
    return this.state.fork
  }

  get padding() {
    if (this.encryption && this.key && this.manifest) {
      return this.encryption.padding(this.core, this.length)
    }

    return 0
  }

  get peers() {
    return this.opened === false ? [] : this.core.replicator.peers
  }

  get globalCache() {
    return this.opened === false ? null : this.core.globalCache
  }

  get recovering() {
    return this.opened === false ? 0 : this.core.header.hints.recovering
  }

  ready() {
    return this.opening
  }

  async recover() {
    if (this.opened === false) await this.opening
    return this.state.waitForRecovery()
  }

  async setUserData(key, value) {
    if (this.opened === false) await this.opening
    const existing = await this.getUserData(key)
    if (existing && b4a.isBuffer(value) && b4a.equals(existing, value)) return
    await this.state.setUserData(key, value)
  }

  async getUserData(key) {
    if (this.opened === false) await this.opening
    const batch = this.state.storage.read()
    const p = batch.getUserData(key)
    batch.tryFlush()
    return p
  }

  transferSession(core) {
    // todo: validate we can move

    if (this.weak === false) {
      this.core.activeSessions--
      core.activeSessions++
    }

    if (this._monitorIndex >= 0) {
      this.core.removeMonitor(this)
      core.addMonitor(this)
    }

    const old = this.core

    this.core = core

    old.replicator.clearRequests(this.activeRequests, SESSION_MOVED())

    this.emit('migrate', this.key)
  }

  findingPeers() {
    this._findingPeers++
    if (this.core !== null && !this.closing) this.core.replicator.findingPeers++

    let once = true

    return () => {
      if (this.closing || !once) return
      once = false
      this._findingPeers--
      if (this.core !== null && --this.core.replicator.findingPeers === 0) {
        this.core.replicator.queueUpdateAll()
      }
    }
  }

  async info(opts) {
    if (this.opened === false) await this.opening

    return Info.from(this, opts)
  }

  async update(opts) {
    if (this.opened === false) await this.opening
    if (this.closing !== null) return false
    if (this.snapshotted) return false

    if (this.writable && (!opts || opts.force !== true)) return false

    const remoteWait = this._shouldWait(opts, this.core.replicator.findingPeers > 0)

    let upgraded = false

    if (await this.core.replicator.applyPendingReorg()) {
      upgraded = true
    }

    if (!upgraded && remoteWait) {
      const activeRequests = (opts && opts.activeRequests) || this.activeRequests
      if (isRequestsDestroyed(activeRequests)) throw REQUEST_CANCELLED()

      const req = this.core.replicator.addUpgrade(activeRequests)

      try {
        upgraded = await req.promise
      } catch (err) {
        if (isSessionMoved(err)) return this.update(opts)
        throw err
      }
    }

    if (!upgraded) return false
    return true
  }

  async seek(bytes, opts) {
    if (this.opened === false) await this.opening
    if (!isValidIndex(bytes)) throw ASSERTION('seek is invalid', this.discoveryKey)

    const activeRequests = (opts && opts.activeRequests) || this.activeRequests
    if (isRequestsDestroyed(activeRequests)) throw REQUEST_CANCELLED()

    if (this.encryption && !this.core.manifest) {
      const req = this.replicator.addUpgrade(activeRequests)
      try {
        await req.promise
      } catch (err) {
        if (isSessionMoved(err)) return this.seek(bytes, opts)
        throw err
      }
    }

    const s = MerkleTree.seek(this.state, bytes, this.padding)

    const offset = await s.update()
    if (offset) return offset

    if (this.closing !== null) {
      throw SESSION_CLOSED('cannot seek on a closed session', this.discoveryKey)
    }

    if (!this._shouldWait(opts, this.wait)) return null

    if (isRequestsDestroyed(activeRequests)) throw REQUEST_CANCELLED()
    const req = this.core.replicator.addSeek(activeRequests, s)

    const timeout = opts && opts.timeout !== undefined ? opts.timeout : this.timeout
    if (timeout) req.context.setTimeout(req, timeout)

    try {
      return await req.promise
    } catch (err) {
      if (isSessionMoved(err)) return this.seek(bytes, opts)
      throw err
    }
  }

  async has(start, end = start + 1) {
    if (this.opened === false) await this.opening
    if (!isValidIndex(start) || !isValidIndex(end)) {
      throw ASSERTION('has range is invalid', this.discoveryKey)
    }

    if (this.state.isDefault()) {
      if (end === start + 1) return this.core.bitfield.get(start)

      const i = this.core.bitfield.firstUnset(start)
      return i === -1 || i >= end
    }

    if (end === start + 1) {
      const rx = this.state.storage.read()
      const block = rx.getBlock(start)
      rx.tryFlush()

      return (await block) !== null
    }

    let count = 0

    const stream = this.state.storage.createBlockStream({ gte: start, lt: end })
    for await (const block of stream) {
      if (block === null) return false
      count++
    }

    return count === end - start
  }

  async get(index, opts) {
    if (this.opened === false) await this.opening
    if (!isValidIndex(index)) throw ASSERTION('block index is invalid', this.discoveryKey)

    if (this.closing !== null) {
      throw SESSION_CLOSED('cannot get on a closed session', this.discoveryKey)
    }

    const encoding =
      (opts && opts.valueEncoding && c.from(opts.valueEncoding)) || this.valueEncoding

    if (this.onseq !== null) this.onseq(index, this)
    if (this._marking) await this.markBlock(index)

    const req = this._get(index, opts)

    let block = await req
    if (!block) return null

    if (opts && opts.raw) return block

    if (this.encryption && (!opts || opts.decrypt !== false)) {
      // Copy the block as it might be shared with other sessions.
      block = b4a.from(block)

      await this.encryption.decrypt(index, block, this.core)
    }

    return this._decode(encoding, block, index)
  }

  async clear(start, end = start + 1, opts) {
    if (this.opened === false) await this.opening
    if (this.closing !== null) {
      throw SESSION_CLOSED('cannot clear on a closed session', this.discoveryKey)
    }

    if (typeof end === 'object') {
      opts = end
      end = start + 1
    }

    if (!isValidIndex(start) || !isValidIndex(end)) {
      throw ASSERTION('clear range is invalid', this.discoveryKey)
    }

    const cleared = opts && opts.diff ? { blocks: 0 } : null

    if (start >= end) return cleared
    if (start >= this.length) return cleared

    await this.state.clear(start, end, cleared)

    return cleared
  }

  async purge() {
    await this._closeAllSessions(null)
    await this.core.purge()
  }

  async _get(index, opts) {
    const block = await readBlock(this.state.storage.read(), index)

    if (block !== null) return block

    if (this.closing !== null) {
      throw SESSION_CLOSED('cannot get on a closed session', this.discoveryKey)
    }

    // snapshot should check if core has block
    if (this._snapshot !== null) {
      checkSnapshot(this, index)
      const coreBlock = await readBlock(this.core.state.storage.read(), index)

      checkSnapshot(this, index)
      if (coreBlock !== null) return coreBlock
    }

    // lets check the bitfield to see if we got it during the above async calls
    // this is the last resort before replication, so always safe.
    if (this.core.bitfield.get(index)) {
      const coreBlock = await readBlock(this.state.storage.read(), index)
      // TODO: this should not be needed, only needed atm in case we are doing a moveTo during this (we should fix)
      if (coreBlock !== null) return coreBlock
    }

    if (!this._shouldWait(opts, this.wait)) return null

    this.waits++
    if (opts && opts.onwait) opts.onwait(index, this)
    if (this.onwait) this.onwait(index, this)

    const activeRequests = (opts && opts.activeRequests) || this.activeRequests
    if (isRequestsDestroyed(activeRequests)) throw REQUEST_CANCELLED()

    const force = opts ? opts.force === true : false
    const req = this.core.replicator.addBlock(activeRequests, index, force)
    req.snapshot = index < this.length

    const timeout = opts && opts.timeout !== undefined ? opts.timeout : this.timeout
    if (timeout) req.context.setTimeout(req, timeout)

    let replicatedBlock = null

    try {
      replicatedBlock = await req.promise
    } catch (err) {
      if (isSessionMoved(err)) return this._get(index, opts)
      throw err
    }

    if (this._snapshot !== null) checkSnapshot(this, index)
    return maybeUnslab(replicatedBlock)
  }

  _shouldWait(opts, defaultValue) {
    if (opts) {
      if (opts.wait === false) return false
      if (opts.wait === true) return true
    }
    return defaultValue
  }

  _setupMarks() {
    if (this._marks === null) {
      const storage = this.snapshotted ? this.core.state.storage : this.state.storage
      this._marks = new MarkBitfield(storage)
    }
  }

  async markBlock(start, end = start + 1) {
    if (this.opened === false) await this.opening

    this._setupMarks()

    // TODO support as single rocks batch
    const setPromises = []
    for (let i = start; i < end; i++) {
      setPromises.push(this._marks.set(i, true))
    }

    return Promise.all(setPromises)
  }

  async clearMarkings() {
    if (this.opened === false) await this.opening

    this._setupMarks()

    await this._marks.clear()
    this._marks = null
  }

  async startMarking() {
    if (this._marking) {
      throw ASSERTION("Hypercore cannot be gc'ed when already in gc mode", this.discoveryKey)
    }
    if (this.state && this.state.name) {
      throw ASSERTION("Hypercore cannot be gc'ed when a named session", this.discoveryKey)
    }
    if (this.state && this.state.storage.atom) {
      throw ASSERTION("Hypercore cannot be gc'ed when an atomic session", this.discoveryKey)
    }
    if (this.opened === false) await this.opening
    await this.clearMarkings()

    this._marking = true
  }

  async sweep({ batchSize = 1000 } = {}) {
    if (this.opened === false) await this.opening

    assert(!this.snapshotted, 'Cannot sweep a snapshot')

    // No marks - load from storage
    this._setupMarks()

    let clearing = []
    let prevIndex = this.length
    for await (const index of this._marks.createMarkStream({ reverse: true })) {
      if (index + 1 === prevIndex) {
        prevIndex = index
        continue
      }
      clearing.push(this.clear(index + 1, prevIndex))
      if (clearing.length >= batchSize) {
        await Promise.all(clearing)
        clearing = []
      }
      prevIndex = index
    }
    // Clear range from the very start if not marked
    if (prevIndex > 0) clearing.push(this.clear(0, prevIndex))
    await Promise.all(clearing)

    this._marking = false
    await this.clearMarkings()
  }

  createReadStream(opts) {
    return new ReadStream(this, opts)
  }

  createWriteStream() {
    return new WriteStream(this)
  }

  createByteStream(opts) {
    return new ByteStream(this, opts)
  }

  download(range) {
    return new Download(this, range)
  }

  // TODO: get rid of this / deprecate it?
  undownload(range) {
    range.destroy(null)
  }

  // TODO: get rid of this / deprecate it?
  cancel(request) {
    // Do nothing for now
  }

  async truncate(newLength = 0, opts = {}) {
    if (this.opened === false) await this.opening
    if (this.closing) throw SESSION_CLOSED('Cannot append to a closed session', this.discoveryKey)

    const {
      fork = this.state.fork + 1,
      keyPair = this.keyPair,
      signature = null
    } = typeof opts === 'number' ? { fork: opts } : opts

    const isDefault = this.state === this.core.state
    const writable = !this._readonly && !!(signature || (keyPair && keyPair.secretKey))
    if (isDefault && writable === false && (newLength > 0 || fork !== this.state.fork)) {
      throw SESSION_NOT_WRITABLE('cannot append to a non-writable core', this.discoveryKey)
    }

    await this.state.truncate(newLength, fork, { keyPair, signature })

    // TODO: Should propagate from an event triggered by the oplog
    if (this.state === this.core.state) this.core.replicator.updateAll()
  }

  async append(blocks, opts = {}) {
    if (this.opened === false) await this.opening
    if (this.closing) throw SESSION_CLOSED('Cannot append to a closed session', this.discoveryKey)

    const isDefault = this.state === this.core.state
    const defaultKeyPair = this.state.name === null ? this.keyPair : null

    const { keyPair = defaultKeyPair, signature = null, maxLength, postappend = null } = opts
    const writable =
      !isDefault || !!signature || !!(keyPair && keyPair.secretKey) || opts.writable === true

    if (this._readonly || writable === false) {
      throw SESSION_NOT_WRITABLE('cannot append to a readonly core', this.discoveryKey)
    }

    blocks = Array.isArray(blocks) ? blocks : [blocks]

    const preappend = this.encryption && this._preappend

    const buffers = this.encodeBatch !== null ? this.encodeBatch(blocks) : new Array(blocks.length)

    if (this.encodeBatch === null) {
      for (let i = 0; i < blocks.length; i++) {
        buffers[i] = this._encode(this.valueEncoding, blocks[i])
      }
    }
    for (const b of buffers) {
      if (b.byteLength > MAX_SUGGESTED_BLOCK_SIZE) {
        throw BAD_ARGUMENT(
          'Appended block exceeds the maximum suggested block size',
          this.discoveryKey
        )
      }
    }

    return this.state.append(buffers, { keyPair, signature, preappend, postappend, maxLength })
  }

  async signable(length = -1, fork = -1) {
    if (this.opened === false) await this.opening
    if (length === -1) length = this.length
    if (fork === -1) fork = this.fork

    return caps.treeSignable(this.key, await this.treeHash(length), length, fork)
  }

  async treeHash(length = -1) {
    if (this.opened === false) await this.opening
    if (length === -1) length = this.length
    if (length > 0 && !(await this.has(length - 1))) await this.get(length - 1)

    const roots = await MerkleTree.getRoots(this.state, length)
    return crypto.tree(roots)
  }

  async missingNodes(index) {
    if (this.opened === false) await this.opening
    return await MerkleTree.missingNodes(this.core.state, 2 * index, this.core.state.length)
  }

  async proof(opts) {
    if (this.opened === false) await this.opening
    const rx = this.state.storage.read()
    const proofPromise = MerkleTree.proof(this.state, rx, opts)
    const blockPromise = opts && opts.block ? rx.getBlock(opts.block.index) : null
    rx.tryFlush()
    const [proof, block] = await Promise.all([proofPromise, blockPromise])
    const settled = await proof.settle()
    if (block) settled.block.value = block
    return settled
  }

  async applyProof(proof, from) {
    if (this.opened === false) await this.opening
    return this.core.verify(proof, from)
  }

  async verifyFullyRemote(proof) {
    if (this.opened === false) await this.opening
    const batch = await MerkleTree.verifyFullyRemote(this.state, proof)
    await this.core._verifyBatchUpgrade(batch, proof.manifest)
    return batch
  }

  generateRemoteProofForTreeNode(treeNodeIndex) {
    const blockProofIndex = flat.rightSpan(treeNodeIndex) / 2
    return proof(this, {
      index: blockProofIndex,
      // + 1 to length so the block is included
      upgrade: { start: 0, length: blockProofIndex + 1 }
    })
  }

  async recoverFromRemoteProof(remoteProof) {
    this.core.replicator.setPushOnly(true)
    this.core._repairMode = true

    await this.core.state.mutex.lock()

    try {
      const p = await verify(this.core.db, remoteProof)
      if (!p) return false

      const tx = this.core.storage.write()
      for (const node of p.proof.upgrade.nodes) {
        tx.putTreeNode(node)
      }
      await tx.flush()

      const succeed = p.proof.upgrade.nodes.length !== 0
      if (succeed) {
        this.core.replicator.setPushOnly(false)
      }
      return succeed
    } finally {
      this.core.state.mutex.unlock()
    }
  }

  recoverTreeNodeFromPeers() {
    this.core.replicator.setPushOnly(true)

    for (const peer of this.core.replicator.peers) {
      const req = {
        id: 0,
        fork: this.fork,
        upgrade: {
          start: 0,
          length: this.length
        }
      }
      peer.wireRequest.send(req)
    }
  }

  registerExtension(name, handlers = {}) {
    if (this.extensions.has(name)) {
      const ext = this.extensions.get(name)
      ext.handlers = handlers
      ext.encoding = c.from(handlers.encoding || c.buffer)
      ext.session = this
      return ext
    }

    const ext = {
      name,
      handlers,
      encoding: c.from(handlers.encoding || c.buffer),
      session: this,
      send(message, peer) {
        const buffer = c.encode(this.encoding, message)
        peer.extension(name, buffer)
      },
      broadcast(message) {
        const buffer = c.encode(this.encoding, message)
        for (const peer of this.session.peers) {
          peer.extension(name, buffer)
        }
      },
      destroy() {
        for (const peer of this.session.peers) {
          if (peer.extensions.get(name) === ext) peer.extensions.delete(name)
        }
        this.session.extensions.delete(name)
      },
      _onmessage(state, peer) {
        const m = this.encoding.decode(state)
        if (this.handlers.onmessage) this.handlers.onmessage(m, peer)
      }
    }

    this.extensions.set(name, ext)

    if (this.core === null) this._monitorIndex = -2
    else this.core.addMonitor(this)

    for (const peer of this.peers) {
      peer.extensions.set(name, ext)
    }

    return ext
  }

  _encode(enc, val) {
    const state = { start: this.padding, end: this.padding, buffer: null }

    if (b4a.isBuffer(val)) {
      if (state.start === 0) return val
      state.end += val.byteLength
    } else if (enc) {
      enc.preencode(state, val)
    } else {
      val = b4a.from(val)
      if (state.start === 0) return val
      state.end += val.byteLength
    }

    state.buffer = b4a.allocUnsafe(state.end)

    if (enc) enc.encode(state, val)
    else state.buffer.set(val, state.start)

    return state.buffer
  }

  _decode(enc, block, index) {
    if (this.encryption) block = block.subarray(this.encryption.padding(this.core, index))
    try {
      if (enc) return c.decode(enc, block)
    } catch (err) {
      throw DECODING_ERROR(err.message, this.discoveryKey)
    }
    return block
  }

  _getEncryptionProvider(e) {
    if (isEncryptionProvider(e)) return e
    if (!e || !e.key) return null
    return new DefaultEncryption(e.key, this.key, { block: e.block, compat: this.core.compat })
  }
}

module.exports = Hypercore

function isStream(s) {
  return typeof s === 'object' && s && typeof s.pipe === 'function'
}

async function preappend(blocks) {
  const offset = this.state.length
  const fork = this.state.encryptionFork

  for (let i = 0; i < blocks.length; i++) {
    await this.encryption.encrypt(offset + i, blocks[i], fork, this.core)
  }
}

function isValidIndex(index) {
  return index === 0 || index > 0
}

function maybeUnslab(block) {
  // Unslab only when it takes up less then half the slab
  return block !== null && 2 * block.byteLength < block.buffer.byteLength ? unslab(block) : block
}

function checkSnapshot(snapshot, index) {
  if (index >= snapshot.state.snapshotCompatLength) {
    throw SNAPSHOT_NOT_AVAILABLE(
      `snapshot at index ${index} not available (max compat length ${snapshot.state.snapshotCompatLength})`,
      snapshot.discoveryKey
    )
  }
}

function readBlock(rx, index) {
  const promise = rx.getBlock(index)
  rx.tryFlush()
  return promise
}

function initOnce(session, storage, key, opts) {
  if (storage === null) storage = opts.storage || null
  if (key === null) key = opts.key || null

  session.core = new Core(Hypercore.defaultStorage(storage), {
    preopen: opts.preopen,
    eagerUpgrade: opts.eagerUpgrade !== false,
    notDownloadingLinger: opts.notDownloadingLinger,
    allowFork: opts.allowFork !== false,
    allowPush: !!opts.allowPush,
    pushOnly: !!opts.pushOnly,
    alwaysLatestBlock: !!opts.allowLatestBlock,
    inflightRange: opts.inflightRange,
    compat: opts.compat === true,
    force: opts.force,
    createIfMissing: opts.createIfMissing,
    discoveryKey: opts.discoveryKey,
    overwrite: opts.overwrite,
    key,
    keyPair: opts.keyPair,
    legacy: opts.legacy,
    manifest: opts.manifest,
    group: opts.group,
    globalCache: opts.globalCache || null // session is a temp option, not to be relied on unless you know what you are doing (no semver guarantees)
  })
}

function maybeAddMonitor(name) {
  if (name === 'append' || name === 'truncate') return
  if (this._monitorIndex >= 0 || this.closing) return

  if (this.core === null) {
    this._monitorIndex = -2
  } else {
    this.core.addMonitor(this)
  }
}

function isSessionMoved(err) {
  return err.code === 'SESSION_MOVED'
}

function getEncryptionOption(opts) {
  // old style, supported for now but will go away
  if (opts.encryptionKey) return { key: opts.encryptionKey, block: !!opts.isBlockKey }
  if (!opts.encryption) return null
  return b4a.isBuffer(opts.encryption) ? { key: opts.encryption } : opts.encryption
}

function isEncryptionProvider(e) {
  return e && isFunction(e.padding) && isFunction(e.encrypt) && isFunction(e.decrypt)
}

function isFunction(fn) {
  return !!fn && typeof fn === 'function'
}

function createDiscoveryKeyHandler(fn) {
  return ondiscoverykey
  function ondiscoverykey(id) {
    if (!id || id.byteLength !== 32) throw BAD_ARGUMENT('Invalid discovery key')
    return fn(id)
  }
}

function isRequestsDestroyed(activeRequests) {
  // TODO: move this to an object instead so we can store a property in next major
  return activeRequests.length > 0 && activeRequests[0] === null
}
const crypto = require('hypercore-crypto')
const flat = require('flat-tree')
const b4a = require('b4a')
const { MerkleTree } = require('./merkle-tree')

module.exports = async function auditCore(
  core,
  { tree = true, blocks = true, bitfield = true, dryRun = false } = {}
) {
  const length = core.state.length
  const stats = {
    treeNodes: 0,
    blocks: 0,
    bits: 0,
    droppedTreeNodes: 0,
    droppedBlocks: 0,
    droppedBits: 0,
    corrupt: false
  }

  // audit the tree
  if (tree) {
    let tx = null

    const roots = await MerkleTree.getRootsFromStorage(core.state.storage, length)
    const stack = []

    for (const r of roots) {
      if (r === null) {
        if (!dryRun) {
          const storage = core.state.storage
          await storage.store.deleteCore(storage.core)
          return null
        }

        stats.corrupt = true
      }

      stack.push(r)
    }

    stats.treeNodes += roots.length

    while (stack.length > 0) {
      const node = stack.pop()

      if ((node.index & 1) === 0) continue

      const [left, right] = flat.children(node.index)

      const rx = core.state.storage.read()
      const leftNodePromise = rx.getTreeNode(left)
      const rightNodePromise = rx.getTreeNode(right)

      rx.tryFlush()

      const [leftNode, rightNode] = await Promise.all([leftNodePromise, rightNodePromise])

      if (isBadTree(node, leftNode, rightNode)) {
        if (!tx && !stats.corrupt) tx = core.state.storage.write()
        const [l, r] = flat.spans(node.index)
        tx.deleteTreeNodeRange(l, r + 1)
        stats.droppedTreeNodes++
        continue
      }

      if (!leftNode) continue

      stats.treeNodes += 2
      stack.push(leftNode, rightNode)
    }

    if (tx && !dryRun) await tx.flush()
  }

  // audit the blocks
  if (blocks) {
    let tx = null

    for await (const block of core.state.storage.createBlockStream()) {
      if (!core.bitfield.get(block.index)) {
        if (!tx && !stats.corrupt) tx = core.state.storage.write()
        tx.deleteBlock(block.index)
        stats.droppedBlocks++
      }

      const rx = core.state.storage.read()
      const treeNodePromise = rx.getTreeNode(2 * block.index)

      rx.tryFlush()

      const treeNode = await treeNodePromise

      if (isBadBlock(treeNode, block.value)) {
        if (!tx && !stats.corrupt) tx = core.state.storage.write()
        tx.deleteBlock(block.index)
        stats.droppedBlocks++
        continue
      }

      stats.blocks++
    }

    if (tx && !dryRun) await tx.flush()
  }

  if (bitfield) {
    let tx = null

    for (const index of allBits(core.bitfield)) {
      const rx = core.state.storage.read()
      const blockPromise = rx.getBlock(index)

      rx.tryFlush()

      const block = await blockPromise
      if (!block) {
        stats.droppedBits++
        if (dryRun) continue

        if (!tx && !stats.corrupt) tx = core.state.storage.write()

        core.bitfield.set(index, false)

        const page = core.bitfield.getBitfield(index)
        if (page.bitfield) tx.putBitfieldPage(page.index, page.bitfield)
        else tx.deleteBitfieldPage(page.index)
        continue
      }

      stats.bits++
    }

    if (tx && !dryRun) await tx.flush()
  }

  return stats
}

function isBadBlock(node, block) {
  if (!node) return true
  const hash = crypto.data(block)
  return !b4a.equals(hash, node.hash) || node.size !== block.byteLength
}

function isBadTree(parent, left, right) {
  if (!left && !right) return false
  if (!left || !right) return true
  const hash = crypto.parent(left, right)
  return !b4a.equals(hash, parent.hash) || parent.size !== left.size + right.size
}

function* allBits(bitfield) {
  let i = 0
  if (bitfield.get(0)) yield 0
  while (true) {
    i = bitfield.findFirst(true, i + 1)
    if (i === -1) break
    yield i
  }
}
const b4a = require('b4a')
const quickbit = require('./compat').quickbit

module.exports = class BitInterlude {
  constructor() {
    this.ranges = []
  }

  contiguousLength(from) {
    for (const r of this.ranges) {
      if (r.start > from) break
      if (!r.value && r.start <= from) return r.start
    }

    // TODO: be smarter
    while (this.get(from) === true) from++
    return from
  }

  get(index) {
    let start = 0
    let end = this.ranges.length

    while (start < end) {
      const mid = (start + end) >> 1
      const r = this.ranges[mid]

      if (index < r.start) {
        end = mid
        continue
      }

      if (index >= r.end) {
        if (mid === start) break
        start = mid
        continue
      }

      return r.value
    }

    return false
  }

  setRange(start, end, value) {
    if (start === end) return

    let r = null

    for (let i = 0; i < this.ranges.length; i++) {
      r = this.ranges[i]

      // if already inside, stop
      if (r.start <= start && end <= r.end) {
        if (value === r.value) return

        const ranges = mergeRanges(r, { start, end, value })
        this.ranges.splice(i, 1, ...ranges)

        return
      }

      // we wanna overun the interval
      if (start > r.end) {
        continue
      }

      // we overran but this interval is ending after us, move it back
      if (end >= r.start && end <= r.end) {
        r.start = r.value === value ? start : end
        if (r.value !== value) this.ranges.splice(i, 0, { start, end, value })
        return
      }

      // we overran but our start is contained in this interval, move start back
      if (start >= r.start && start <= r.end) {
        if (r.value !== value) {
          r.end = start // Crop current comparison

          // If there's a next range
          if (this.ranges.length - 1 > i) {
            const next = this.ranges[i + 1]
            // If the same, go next
            if (next.value === value) continue
            // Else we overlap so update next range
            if (next.start < end) next.start = end
          }

          this.ranges.splice(++i, 0, { start, end, value })
          return
        }

        start = r.start
      }

      let remove = 0

      for (let j = i; j < this.ranges.length; j++) {
        const n = this.ranges[j]
        if (n.start > end || n.value !== value) break
        if (n.start <= end && n.end > end) end = n.end
        remove++
      }

      this.ranges.splice(i, remove, { start, end, value })
      return
    }

    if (r !== null) {
      if (start <= r.end && end > r.end) {
        r.end = end
        return
      }

      // we never
      if (r.end > start) return
    }

    this.ranges.push({ start, end, value })
  }

  flush(tx, bitfield) {
    if (!this.ranges.length) return []

    let index = this.ranges[0].start
    const final = this.ranges[this.ranges.length - 1].end

    let i = 0

    while (index < final) {
      const page = bitfield.getBitfield(index) // read only
      const pageIndex = page ? page.index : bitfield.getPageIndex(index)

      const buf = b4a.allocUnsafe(bitfield.getPageByteLength())

      if (page) {
        const src = page.bitfield // Uint32Array
        buf.set(b4a.from(src.buffer, src.byteOffset, src.byteLength), 0)
      } else {
        b4a.fill(buf, 0)
      }

      const last = (pageIndex + 1) * (buf.byteLength << 3)
      const offset = pageIndex * (buf.byteLength << 3)

      let hasValue = false

      while (i < this.ranges.length) {
        const { start, end, value } = this.ranges[i]

        if (!hasValue && value) hasValue = true

        const from = start < index ? index : start
        const to = end < last ? end : last

        quickbit.fill(buf, value, from - offset, to - offset)

        index = to

        if (to === last) break

        i++
      }

      if (page || hasValue) tx.putBitfieldPage(pageIndex, buf)
    }

    return this.ranges
  }
}

function mergeRanges(a, b) {
  const ranges = []
  if (a.start < b.start) ranges.push({ start: a.start, end: b.start, value: a.value })
  ranges.push({ start: b.start, end: b.end, value: b.value })
  if (b.end < a.end) ranges.push({ start: b.end, end: a.end, value: a.value })

  return ranges
}
const BigSparseArray = require('big-sparse-array')
const b4a = require('b4a')
const quickbit = require('./compat').quickbit

const BITS_PER_PAGE = 32768
const BYTES_PER_PAGE = BITS_PER_PAGE / 8
const WORDS_PER_PAGE = BYTES_PER_PAGE / 4
const BITS_PER_SEGMENT = 2097152
const BYTES_PER_SEGMENT = BITS_PER_SEGMENT / 8
const WORDS_PER_SEGMENT = BYTES_PER_SEGMENT / 4
const INITIAL_WORDS_PER_SEGMENT = 1024
const PAGES_PER_SEGMENT = BITS_PER_SEGMENT / BITS_PER_PAGE
const SEGMENT_GROWTH_FACTOR = 4

class BitfieldPage {
  constructor(index, segment) {
    this.index = index
    this.offset = index * BYTES_PER_PAGE - segment.offset
    this.bitfield = null
    this.segment = segment

    segment.add(this)
  }

  get tree() {
    return this.segment.tree
  }

  get(index, dirty) {
    return quickbit.get(this.bitfield, index)
  }

  set(index, val) {
    if (quickbit.set(this.bitfield, index, val)) {
      this.tree.update(this.offset * 8 + index)
    }
  }

  setRange(start, end, val) {
    quickbit.fill(this.bitfield, val, start, end)

    let i = Math.floor(start / 128)
    const n = i + Math.ceil((end - start) / 128)

    while (i <= n) this.tree.update(this.offset * 8 + i++ * 128)
  }

  findFirst(val, position) {
    return quickbit.findFirst(this.bitfield, val, position)
  }

  findLast(val, position) {
    return quickbit.findLast(this.bitfield, val, position)
  }

  count(start, length, val) {
    const end = start + length

    let i = start
    let c = 0

    while (length > 0) {
      const l = this.findFirst(val, i)
      if (l === -1 || l >= end) return c

      const h = this.findFirst(!val, l + 1)
      if (h === -1 || h >= end) return c + end - l

      c += h - l
      length -= h - i
      i = h
    }

    return c
  }
}

class BitfieldSegment {
  constructor(index, bitfield) {
    this.index = index
    this.offset = index * BYTES_PER_SEGMENT
    this.tree = quickbit.Index.from(bitfield, BYTES_PER_SEGMENT)
    this.pages = new Array(PAGES_PER_SEGMENT)
  }

  get bitfield() {
    return this.tree.field
  }

  add(page) {
    const i = page.index - this.index * PAGES_PER_SEGMENT
    this.pages[i] = page

    const start = i * WORDS_PER_PAGE
    const end = start + WORDS_PER_PAGE

    if (end >= this.bitfield.length) this.reallocate(end)

    page.bitfield = this.bitfield.subarray(start, end)
  }

  reallocate(length) {
    let target = this.bitfield.length
    while (target < length) target *= SEGMENT_GROWTH_FACTOR

    const bitfield = new Uint32Array(target)
    bitfield.set(this.bitfield)

    this.tree = quickbit.Index.from(bitfield, BYTES_PER_SEGMENT)

    for (let i = 0; i < this.pages.length; i++) {
      const page = this.pages[i]
      if (!page) continue

      const start = i * WORDS_PER_PAGE
      const end = start + WORDS_PER_PAGE

      page.bitfield = bitfield.subarray(start, end)
    }
  }

  findFirst(val, position) {
    position = this.tree.skipFirst(!val, position)

    let j = position & (BITS_PER_PAGE - 1)
    let i = (position - j) / BITS_PER_PAGE

    if (i >= PAGES_PER_SEGMENT) return -1

    while (i < this.pages.length) {
      const p = this.pages[i]

      let index = -1

      if (p) index = p.findFirst(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_PAGE + index

      j = 0
      i++
    }

    return -1
  }

  findLast(val, position) {
    position = this.tree.skipLast(!val, position)

    let j = position & (BITS_PER_PAGE - 1)
    let i = (position - j) / BITS_PER_PAGE

    if (i >= PAGES_PER_SEGMENT) return -1

    while (i >= 0) {
      const p = this.pages[i]

      let index = -1

      if (p) index = p.findLast(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_PAGE + index

      j = BITS_PER_PAGE - 1
      i--
    }

    return -1
  }
}

module.exports = class Bitfield {
  static BITS_PER_PAGE = BITS_PER_PAGE
  static BYTES_PER_PAGE = BYTES_PER_PAGE

  constructor(buffer) {
    this.resumed = !!(buffer && buffer.byteLength >= 0)

    this._pages = new BigSparseArray()
    this._segments = new BigSparseArray()

    const view = this.resumed
      ? new Uint32Array(buffer.buffer, buffer.byteOffset, Math.floor(buffer.byteLength / 4))
      : new Uint32Array(INITIAL_WORDS_PER_SEGMENT)

    for (let i = 0; i < view.length; i += WORDS_PER_SEGMENT) {
      let bitfield = view.subarray(i, i + WORDS_PER_SEGMENT)
      let length = WORDS_PER_SEGMENT

      if (i === 0) {
        length = INITIAL_WORDS_PER_SEGMENT
        while (length < bitfield.length) length *= SEGMENT_GROWTH_FACTOR
      }

      if (bitfield.length !== length) {
        const copy = new Uint32Array(length)
        copy.set(bitfield, 0)
        bitfield = copy
      }

      const segment = new BitfieldSegment(i / WORDS_PER_SEGMENT, bitfield)
      this._segments.set(segment.index, segment)

      for (let j = 0; j < bitfield.length; j += WORDS_PER_PAGE) {
        const page = new BitfieldPage((i + j) / WORDS_PER_PAGE, segment)
        this._pages.set(page.index, page)
      }
    }
  }

  static from(bitfield) {
    return new Bitfield(bitfield.toBuffer(bitfield._pages.maxLength * BITS_PER_PAGE))
  }

  toBuffer(length) {
    const pages = Math.ceil(length / BITS_PER_PAGE)
    const buffer = b4a.allocUnsafe(pages * BYTES_PER_PAGE)

    for (let i = 0; i < pages; i++) {
      const page = this._pages.get(i)
      const offset = i * BYTES_PER_PAGE

      if (page) {
        const buf = b4a.from(
          page.bitfield.buffer,
          page.bitfield.byteOffset,
          page.bitfield.byteLength
        )

        buffer.set(buf, offset)
      } else {
        buffer.fill(0, offset, offset + BYTES_PER_PAGE)
      }
    }

    return buffer
  }

  getBitfield(index) {
    const i = this.getPageIndex(index)

    const p = this._pages.get(i)
    return p || null
  }

  merge(bitfield, length) {
    let i = 0

    while (i < length) {
      const start = bitfield.firstSet(i)
      if (start === -1) break

      i = bitfield.firstUnset(start)

      if (i === -1 || i > length) i = length

      this.setRange(start, i, true)

      if (i >= length) break
    }
  }

  get(index) {
    const j = index & (BITS_PER_PAGE - 1)
    const i = (index - j) / BITS_PER_PAGE

    const p = this._pages.get(i)

    return p ? p.get(j) : false
  }

  getPageByteLength() {
    return BYTES_PER_PAGE
  }

  getPageIndex(index) {
    const j = index & (BITS_PER_PAGE - 1)
    return (index - j) / BITS_PER_PAGE
  }

  getPage(index, create) {
    const i = this.getPageIndex(index)

    let p = this._pages.get(i)

    if (p) return p

    if (!create) return null

    const k = Math.floor(i / PAGES_PER_SEGMENT)
    const s =
      this._segments.get(k) ||
      this._segments.set(
        k,
        new BitfieldSegment(
          k,
          new Uint32Array(k === 0 ? INITIAL_WORDS_PER_SEGMENT : WORDS_PER_SEGMENT)
        )
      )

    p = this._pages.set(i, new BitfieldPage(i, s))

    return p
  }

  set(index, val) {
    const j = index & (BITS_PER_PAGE - 1)
    const i = (index - j) / BITS_PER_PAGE

    let p = this._pages.get(i)

    if (!p && val) {
      const k = Math.floor(i / PAGES_PER_SEGMENT)
      const s =
        this._segments.get(k) ||
        this._segments.set(
          k,
          new BitfieldSegment(
            k,
            new Uint32Array(k === 0 ? INITIAL_WORDS_PER_SEGMENT : WORDS_PER_SEGMENT)
          )
        )

      p = this._pages.set(i, new BitfieldPage(i, s))
    }

    if (p) p.set(j, val)
  }

  setRange(start, end, val) {
    let j = start & (BITS_PER_PAGE - 1)
    let i = (start - j) / BITS_PER_PAGE

    while (start < end) {
      let p = this._pages.get(i)

      if (!p && val) {
        const k = Math.floor(i / PAGES_PER_SEGMENT)
        const s =
          this._segments.get(k) ||
          this._segments.set(
            k,
            new BitfieldSegment(
              k,
              new Uint32Array(k === 0 ? INITIAL_WORDS_PER_SEGMENT : WORDS_PER_SEGMENT)
            )
          )

        p = this._pages.set(i, new BitfieldPage(i, s))
      }

      const offset = i * BITS_PER_PAGE
      const last = Math.min(end - offset, BITS_PER_PAGE)
      const range = last - j

      if (p) p.setRange(j, last, val)

      j = 0
      i++
      start += range
    }
  }

  findFirst(val, position) {
    let j = position & (BITS_PER_SEGMENT - 1)
    let i = (position - j) / BITS_PER_SEGMENT

    while (i < this._segments.maxLength) {
      const s = this._segments.get(i)

      let index = -1

      if (s) index = s.findFirst(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_SEGMENT + index

      j = 0
      i++
    }

    return val ? -1 : this._segments.maxLength * BITS_PER_SEGMENT
  }

  firstSet(position) {
    return this.findFirst(true, position)
  }

  firstUnset(position) {
    return this.findFirst(false, position)
  }

  findLast(val, position) {
    let j = position & (BITS_PER_SEGMENT - 1)
    let i = (position - j) / BITS_PER_SEGMENT

    while (i >= 0) {
      const s = this._segments.get(i)

      let index = -1

      if (s) index = s.findLast(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_SEGMENT + index

      j = BITS_PER_SEGMENT - 1
      i--
    }

    return -1
  }

  lastSet(position) {
    return this.findLast(true, position)
  }

  lastUnset(position) {
    return this.findLast(false, position)
  }

  hasUnset(start, length) {
    const end = start + length

    let j = start & (BITS_PER_SEGMENT - 1)
    let i = (start - j) / BITS_PER_SEGMENT

    while (i < this._segments.maxLength) {
      const s = this._segments.get(i)
      const index = s ? s.findFirst(false, j) : j
      if (index !== -1) return i * BITS_PER_SEGMENT + index < end

      j = 0
      i++

      if (i * BITS_PER_SEGMENT >= end) return false
    }

    return true
  }

  hasSet(start, length) {
    const end = start + length

    let j = start & (BITS_PER_SEGMENT - 1)
    let i = (start - j) / BITS_PER_SEGMENT

    while (i < this._segments.maxLength) {
      const s = this._segments.get(i)

      let index = -1

      if (s) index = s.findFirst(true, j)

      if (index !== -1) return i * BITS_PER_SEGMENT + index < end

      j = 0
      i++

      if (i * BITS_PER_SEGMENT >= end) return false
    }

    return false
  }

  count(start, length, val) {
    let j = start & (BITS_PER_PAGE - 1)
    let i = (start - j) / BITS_PER_PAGE
    let c = 0

    while (length > 0) {
      const p = this._pages.get(i)

      const end = Math.min(j + length, BITS_PER_PAGE)
      const range = end - j

      if (p) c += p.count(j, range, val)
      else if (!val) c += range

      j = 0
      i++
      length -= range
    }

    return c
  }

  countSet(start, length) {
    return this.count(start, length, true)
  }

  countUnset(start, length) {
    return this.count(start, length, false)
  }

  *want(start, length) {
    if (start & 31) {
      const d = start & 31
      start -= d
      length += d
    }

    let j = start & (BITS_PER_SEGMENT - 1)
    let i = (start - j) / BITS_PER_SEGMENT

    while (length > 0) {
      const s = this._segments.get(i)

      if (s) {
        let end = Math.min(j + length, BITS_PER_SEGMENT)
        if (end & 31) end += 32 - (end & 31)

        yield {
          start: i * BITS_PER_SEGMENT + j,
          bitfield: s.bitfield.subarray(j / 32, end / 32)
        }
      }

      j = 0
      i++
      length -= BITS_PER_SEGMENT
    }
  }

  clear(tx) {
    return tx.deleteBitfieldPageRange(0, -1)
  }

  onupdate(ranges) {
    for (const { start, end, value } of ranges) {
      this.setRange(start, end, value)
    }
  }

  static async open(storage, length) {
    if (length === 0) return new Bitfield(storage, null)

    const pages = Math.ceil(length / BITS_PER_PAGE)
    const buffer = b4a.alloc(pages * BYTES_PER_PAGE)
    const stream = storage.createBitfieldStream({ lt: pages })

    for await (const { index, page } of stream) {
      buffer.set(page, index * BYTES_PER_PAGE)
    }

    return new Bitfield(buffer)
  }
}
const crypto = require('hypercore-crypto')
const sodium = require('sodium-universal')
const b4a = require('b4a')
const c = require('compact-encoding')

// TODO: rename this to "crypto" and move everything hashing related etc in here
// Also lets move the tree stuff from hypercore-crypto here

const [
  TREE,
  REPLICATE_INITIATOR,
  REPLICATE_RESPONDER,
  MANIFEST,
  DEFAULT_NAMESPACE,
  DEFAULT_ENCRYPTION
] = crypto.namespace('hypercore', 6)

exports.MANIFEST = MANIFEST
exports.DEFAULT_NAMESPACE = DEFAULT_NAMESPACE
exports.DEFAULT_ENCRYPTION = DEFAULT_ENCRYPTION

exports.replicate = function (isInitiator, key, handshakeHash) {
  const out = b4a.allocUnsafe(32)
  sodium.crypto_generichash_batch(
    out,
    [isInitiator ? REPLICATE_INITIATOR : REPLICATE_RESPONDER, key],
    handshakeHash
  )
  return out
}

exports.treeSignable = function (manifestHash, treeHash, length, fork) {
  const state = { start: 0, end: 112, buffer: b4a.allocUnsafe(112) }
  c.fixed32.encode(state, TREE)
  c.fixed32.encode(state, manifestHash)
  c.fixed32.encode(state, treeHash)
  c.uint64.encode(state, length)
  c.uint64.encode(state, fork)
  return state.buffer
}

exports.treeSignableCompat = function (hash, length, fork, noHeader) {
  const end = noHeader ? 48 : 80
  const state = { start: 0, end, buffer: b4a.allocUnsafe(end) }
  if (!noHeader) c.fixed32.encode(state, TREE) // ultra legacy mode, kill in future major
  c.fixed32.encode(state, hash)
  c.uint64.encode(state, length)
  c.uint64.encode(state, fork)
  return state.buffer
}
// Export the appropriate version of `quickbit-universal` as the plain import
// may resolve to an older version in some environments
let quickbit = require('quickbit-universal')
if (
  typeof quickbit.findFirst !== 'function' ||
  typeof quickbit.findLast !== 'function' ||
  typeof quickbit.clear !== 'function'
) {
  // This should always load the fallback from the locally installed version
  quickbit = require('quickbit-universal/fallback')
}
exports.quickbit = quickbit
const crypto = require('hypercore-crypto')
const flat = require('flat-tree')
const b4a = require('b4a')
const quickbit = require('quickbit-universal')
const Bitfield = require('./bitfield')

const MAX_BATCH_USED = 4 * 1024 * 1024
const MIN_BATCH_USED = 512 * 1024

// just in its own file as its a bit involved

module.exports = copyPrologue

async function copyPrologue(src, dst) {
  const prologue = dst.header.manifest.prologue

  if (src.length < prologue.length || prologue.length === 0) return

  const stack = []
  const roots = flat.fullRoots(prologue.length * 2)
  const batch = { roots, first: true, last: false, contig: 0, used: 0, tree: [], blocks: [] }

  for (let i = 0; i < roots.length; i++) {
    const node = roots[i]
    batch.tree.push(node)
    stack.push(node)
  }

  let lastPage = -1
  let lastBlock = -1

  for await (const data of src.storage.createBlockStream({
    gte: 0,
    lt: prologue.length,
    reverse: true
  })) {
    if (walkTree(stack, data.index * 2, batch) === false) {
      throw new Error('Missing block or tree node for ' + data.index)
    }

    batch.contig = data.index + 1 === lastBlock ? batch.contig + 1 : 1
    lastBlock = data.index

    const page = getBitfieldPage(data.index)
    batch.blocks.push(data)

    if (lastPage !== page) batch.used += 4096
    batch.used += Math.max(data.value.byteLength, 128) // 128 is just a sanity number to avoid mega batches

    // always safe to partially flush so we do that ondemand to reduce memory usage...
    if ((batch.used >= MIN_BATCH_USED && page !== lastPage) || batch.used >= MAX_BATCH_USED) {
      await flushBatch(prologue, src, dst, batch)
    }

    lastPage = page
  }

  if (lastBlock !== 0) batch.contig = 0

  batch.last = true
  await flushBatch(prologue, src, dst, batch)
}

async function flushBatch(prologue, src, dst, batch) {
  const nodePromises = []

  const srcReader = src.storage.read()
  for (const index of batch.tree) {
    nodePromises.push(srcReader.getTreeNode(index))
  }
  srcReader.tryFlush()

  const nodes = await Promise.all(nodePromises)

  const pagePromises = []
  const dstReader = dst.storage.read()

  const headPromise = batch.first ? dstReader.getHead() : null
  if (headPromise) headPromise.catch(noop)

  let lastPage = -1
  for (const { index } of batch.blocks) {
    const page = getBitfieldPage(index)
    if (page === lastPage) continue
    lastPage = page
    pagePromises.push(dstReader.getBitfieldPage(page))
  }

  dstReader.tryFlush()

  const pages = await Promise.all(pagePromises)
  const head = headPromise === null ? null : await headPromise
  const userData = []

  // reads done!

  if (batch.first) {
    const roots = nodes.slice(0, batch.roots.length)

    for (const node of roots) {
      if (!node) throw new Error('Missing nodes for prologue hash')
    }

    const treeHash = crypto.tree(roots)
    if (!b4a.equals(treeHash, prologue.hash)) throw new Error('Prologue does not match source')
  }

  if (batch.first) {
    for await (const data of src.storage.createUserDataStream()) userData.push(data)
  }

  for (let i = 0; i < pages.length; i++) {
    if (!pages[i]) pages[i] = b4a.alloc(4096)
  }

  const tx = dst.storage.write()

  for (const node of nodes) tx.putTreeNode(node)

  lastPage = -1
  let pageIndex = -1

  for (const { index, value } of batch.blocks) {
    const page = getBitfieldPage(index)

    if (page !== lastPage) {
      lastPage = page
      pageIndex++
      // queue the page now, we mutate it below but its the same ref
      tx.putBitfieldPage(pageIndex, pages[pageIndex])
    }

    const pageBuffer = pages[pageIndex]
    quickbit.set(pageBuffer, getBitfieldOffset(index), true)
    tx.putBlock(index, value)
  }

  for (const { key, value } of userData) {
    tx.putUserData(key, value)
  }

  let upgraded = batch.first && !head
  if (upgraded) {
    tx.setHead(prologueToTree(prologue))
  }

  await tx.flush()

  if (upgraded) {
    const roots = nodes.slice(0, batch.roots.length)
    dst.state.setRoots(roots)
    dst.header.tree = prologueToTree(prologue)
  }

  if (userData.length > 0) {
    dst.header.userData = userData.concat(dst.header.userData)
  }

  if (batch.contig) {
    // TODO: we need to persist this somehow
    dst.header.hints.contiguousLength = batch.contig
  }

  let start = 0
  let length = 0

  // update in memory bitfield
  for (const { index } of batch.blocks) {
    if (start === 0 || start - 1 === index) {
      length++
    } else {
      if (length > 0) signalReplicator(dst, upgraded, start, length)
      upgraded = false
      length = 1
    }

    start = index
    dst.bitfield.set(index, true)
  }

  if (length > 0) signalReplicator(dst, upgraded, start, length)

  // unlink
  batch.tree = []
  batch.blocks = []
  batch.first = false
  batch.used = 0
}

function signalReplicator(core, upgraded, start, length) {
  if (upgraded) {
    core.replicator.cork()
    core.replicator.onhave(start, length, false)
    core.replicator.onupgrade()
    core.replicator.uncork()
  } else {
    core.replicator.onhave(start, length, false)
  }
}

function prologueToTree(prologue) {
  return {
    fork: 0,
    length: prologue.length,
    rootHash: prologue.hash,
    signature: null
  }
}

function getBitfieldPage(index) {
  return Math.floor(index / Bitfield.BITS_PER_PAGE)
}

function getBitfieldOffset(index) {
  return index & (Bitfield.BITS_PER_PAGE - 1)
}

function walkTree(stack, target, batch) {
  while (stack.length > 0) {
    const node = stack.pop()

    if ((node & 1) === 0) {
      if (node === target) return true
      continue
    }

    const ite = flat.iterator(node)
    if (!ite.contains(target)) continue

    while ((ite.index & 1) !== 0) {
      const left = ite.leftChild()
      const right = ite.sibling() // is right child

      batch.tree.push(left, right)

      if (ite.contains(target)) stack.push(left)
      else ite.sibling()
    }

    if (ite.index === target) return true
  }

  return false
}

function noop() {}
const crypto = require('hypercore-crypto')
const b4a = require('b4a')
const unslab = require('unslab')
const z32 = require('z32')
const Mutex = require('./mutex')
const { MerkleTree, ReorgBatch } = require('./merkle-tree')
const BitInterlude = require('./bit-interlude')
const Bitfield = require('./bitfield')
const RemoteBitfield = require('./remote-bitfield')
const {
  BAD_ARGUMENT,
  STORAGE_EMPTY,
  STORAGE_CONFLICT,
  INVALID_SIGNATURE,
  INVALID_CHECKSUM
} = require('hypercore-errors')
const Verifier = require('./verifier')
const audit = require('./audit')
const copyPrologue = require('./copy-prologue')
const SessionState = require('./session-state')
const Replicator = require('./replicator')

module.exports = class Core {
  constructor(db, opts = {}) {
    this.db = db
    this.storage = null
    this.replicator = new Replicator(this, opts)
    this.sessionStates = []
    this.monitors = []
    this.activeSessions = 0
    this.gc = 0 // corestore uses this to main a gc strike pool

    this.id = opts.key ? z32.encode(opts.key) : null
    this.key = opts.key || null
    this.discoveryKey = opts.discoveryKey || (opts.key && crypto.discoveryKey(opts.key)) || null
    this.manifest = null
    this.opening = null
    this.closing = null
    this.exclusive = null

    this.preupdate = null
    this.header = null
    this.compat = false
    this.bitfield = null
    this.verifier = null
    this.truncating = 0
    this.skipBitfield = null
    this.globalCache = opts.globalCache || null
    this.autoClose = opts.autoClose !== false
    this.onidle = noop
    this.ongroupupdate = noop

    this.state = null
    this.opened = false
    this.destroyed = false
    this.closed = false

    this.hintsChanged = false
    this.remoteContiguousLengthChanged = false

    this._bitfield = null
    this._verifies = null
    this._verifiesFlushed = null
    this._legacy = !!opts.legacy
    this._repairMode = false

    this.opening = this._open(opts)
    this.opening.catch(noop)
  }

  static setRecoveryPeers(peers) {
    SessionState.RECOVERY_PEERS = peers
  }

  ready() {
    return this.opening
  }

  addMonitor(s) {
    if (s._monitorIndex >= 0) return
    s._monitorIndex = this.monitors.push(s) - 1
  }

  removeMonitor(s) {
    if (s._monitorIndex < 0) return
    const head = this.monitors.pop()
    if (head !== s) this.monitors[(head._monitorIndex = s._monitorIndex)] = head
    s._monitorIndex = -1
  }

  emitRemoteContiguousLength() {
    if (!this.remoteContiguousLengthChanged) return
    this.remoteContiguousLengthChanged = false

    const length = this.header.hints.remoteContiguousLength

    for (let i = this.monitors.length - 1; i >= 0; i--) {
      this.monitors[i].emit('remote-contiguous-length', length)
    }
  }

  emitManifest() {
    for (let i = this.monitors.length - 1; i >= 0; i--) {
      this.monitors[i].emit('manifest')
    }
  }

  createUserDataStream(opts, session = this.state) {
    return session.storage.createUserDataStream(opts)
  }

  allSessions() {
    const sessions = []
    for (const state of this.sessionStates) {
      if (state.sessions.length) sessions.push(...state.sessions)
    }
    return sessions
  }

  hasSession() {
    return this.activeSessions !== 0
  }

  compact() {
    const compacting = []
    for (const s of this.sessionStates) {
      compacting.push(s.storage.compact())
    }
    return Promise.all(compacting)
  }

  checkIfIdle() {
    if (!this.opened || this.destroyed === true || this.hasSession() === true) return
    if (this.replicator.idle() === false) return
    if (this.state === null || this.state.mutex.idle() === false) return
    this.onidle()
  }

  async lockExclusive() {
    if (this.exclusive === null) this.exclusive = new Mutex()
    await this.exclusive.lock()
  }

  unlockExclusive() {
    if (this.exclusive !== null) this.exclusive.unlock()
  }

  async _open(opts) {
    try {
      await this._tryOpen(opts)
    } catch (err) {
      this.onidle()
      throw err
    }

    this.opened = true
  }

  async _tryOpen(opts) {
    if (opts.preopen) await opts.preopen // just a hook to allow exclusive access here...

    let storage = await this.db.resumeCore(this.discoveryKey)

    let overwrite = opts.overwrite === true

    const force = opts.force === true
    const createIfMissing = opts.createIfMissing !== false
    // kill this flag soon
    const legacy = !!opts.legacy

    // default to true for now if no manifest is provided
    let compat = opts.compat === true || (opts.compat !== false && !opts.manifest)

    let header = storage ? parseHeader(await getCoreInfo(storage)) : null

    const hadManifest = !!header && !!header.manifest && !!header.key
    const hadKeyPair = !!header && !!header.keyPair

    if (force && opts.key && header && !b4a.equals(header.key, opts.key)) {
      overwrite = true
    }

    if (!header && opts.discoveryKey && !(opts.key || opts.manifest)) {
      throw STORAGE_EMPTY('No Hypercore is stored here', this.discoveryKey)
    }

    if (!header || overwrite) {
      if (!createIfMissing) {
        throw STORAGE_EMPTY('No Hypercore is stored here', this.discoveryKey)
      }

      if (compat) {
        if (opts.key && opts.keyPair && !b4a.equals(opts.key, opts.keyPair.publicKey)) {
          throw BAD_ARGUMENT('Key must match publicKey when in compat mode', this.discoveryKey)
        }
      }

      const keyPair = opts.keyPair || (opts.key ? null : crypto.keyPair())

      const defaultManifest =
        !opts.manifest &&
        (!!opts.compat || !opts.key || !!(keyPair && b4a.equals(opts.key, keyPair.publicKey)))
      const manifest = defaultManifest
        ? Verifier.defaultSignerManifest(opts.key || keyPair.publicKey)
        : Verifier.createManifest(opts.manifest)

      header = {
        key: opts.key || (compat ? manifest.signers[0].publicKey : Verifier.manifestHash(manifest)),
        manifest,
        keyPair: keyPair
          ? { publicKey: keyPair.publicKey, secretKey: keyPair.secretKey || null }
          : null,
        frozen: false,
        tree: {
          fork: 0,
          length: 0,
          rootHash: null,
          signature: null,
          timestamp: 0
        },
        group: null,
        hints: {
          reorgs: [],
          contiguousLength: 0,
          remoteContiguousLength: 0,
          recovering: 0
        }
      }

      const discoveryKey = opts.discoveryKey || crypto.discoveryKey(header.key)

      storage = await this.db.createCore({
        key: header.key,
        manifest,
        keyPair,
        frozen: false,
        discoveryKey,
        userData: opts.userData || [],
        alias: opts.alias || null
      })
    }

    // unslab the long lived buffers to avoid keeping the slab alive
    header.key = unslab(header.key)

    if (header.tree) {
      header.tree.rootHash = unslab(header.tree.rootHash)
      header.tree.signature = unslab(header.tree.signature)
    }

    if (header.keyPair) {
      header.keyPair.publicKey = unslab(header.keyPair.publicKey)
      header.keyPair.secretKey = unslab(header.keyPair.secretKey)
    }

    if (header.keyPair) {
      header.keyPair.publicKey = unslab(header.keyPair.publicKey)
      header.keyPair.secretKey = unslab(header.keyPair.secretKey)
    }

    if (opts.manifest) {
      // if we provide a manifest and no key, verify that the stored key is the same
      if (
        !opts.key &&
        !Verifier.isValidManifest(header.key, Verifier.createManifest(opts.manifest))
      ) {
        throw STORAGE_CONFLICT('Manifest does not hash to provided key', this.discoveryKey)
      }

      if (!header.manifest) header.manifest = opts.manifest
    }

    if (opts.key && !b4a.equals(header.key, opts.key)) {
      throw STORAGE_CONFLICT('Another Hypercore is stored here', this.discoveryKey)
    }

    // if we signalled compat, but already now this core isn't disable it
    if (compat && header.manifest && !Verifier.isCompat(header.key, header.manifest)) {
      compat = false
    } else if (!compat && header.manifest && Verifier.isCompat(header.key, header.manifest)) {
      compat = true
    }

    const prologue = header.manifest ? header.manifest.prologue : null

    const bitfield = await Bitfield.open(storage, header.tree.length)

    const treeInfo = {
      fork: header.tree.fork,
      length: header.tree.length,
      signature: header.tree.signature,
      roots: await maybeGetRootsFromStorage(storage, header.tree.length),
      prologue
    }

    this._repairMode = !treeInfo.roots.length && treeInfo.length && !overwrite
    // Set push only mode if in repair mode
    if (this._repairMode) {
      this.replicator.setPushOnly(true)
    }

    if (opts.group) {
      if (!header.group) header.group = await this.db.createGroup(opts.group)
      else if (!b4a.equals(header.group.key, opts.group)) {
        throw STORAGE_CONFLICT(
          'Core is already register to group: ' + b4a.toString(header.group.key, 'hex')
        )
      }

      const tx = storage.write()
      tx.setGroup(header.group)
      await tx.flush()
    }

    if (overwrite) {
      const tx = storage.write()
      tx.deleteTreeNodeRange(0, -1)
      tx.deleteBlockRange(0, -1)
      bitfield.clear(tx)
      await tx.flush()
    }

    const len = bitfield.findFirst(false, header.hints.contiguousLength)
    if (header.hints.contiguousLength !== len && !storage.readOnly) {
      header.hints.contiguousLength = len
      const tx = storage.write()
      tx.setHints(header.hints)
      await tx.flush()
    }

    // to unslab
    if (header.manifest) {
      header.manifest = Verifier.createManifest(header.manifest)
      if (!hadManifest || (header.keyPair && !hadKeyPair)) {
        const tx = storage.write()
        tx.setAuth({
          key: header.key,
          discoveryKey: crypto.discoveryKey(header.key),
          manifest: header.manifest,
          keyPair: header.keyPair
        })
        await tx.flush()
      }
    }

    const verifier = header.manifest
      ? new Verifier(header.key, header.manifest, { crypto, legacy })
      : null

    this.storage = storage
    this.header = header
    this.compat = compat
    this.bitfield = bitfield
    this.verifier = verifier
    this.state = new SessionState(this, null, storage, treeInfo, null)

    if (this.key === null) this.key = this.header.key
    if (this.discoveryKey === null) this.discoveryKey = crypto.discoveryKey(this.key)
    if (this.id === null) this.id = z32.encode(this.key)
    if (this.manifest === null) this.manifest = this.header.manifest
  }

  async audit(opts) {
    await this.state.mutex.lock()

    try {
      return await audit(this, opts)
    } finally {
      this.state._unlock()
    }
  }

  async setGroup(group) {
    await this.state.mutex.lock()
    try {
      if (!this.header.group) this.header.group = await this.db.createGroup(group)
      else if (!b4a.equals(this.header.group.key, group)) {
        throw STORAGE_CONFLICT(
          'Core is already register to group: ' + b4a.toString(this.header.group.key, 'hex')
        )
      }

      const tx = this.storage.write()
      tx.setGroup(this.header.group)
      await tx.flush()
    } finally {
      this.state.mutex.unlock()
    }
  }

  async setManifest(manifest) {
    await this.state.mutex.lock()

    try {
      if (manifest && this.header.manifest === null) {
        if (!Verifier.isValidManifest(this.header.key, manifest)) {
          throw INVALID_CHECKSUM('Manifest hash does not match', this.discoveryKey)
        }

        const tx = this.state.createWriteBatch()
        this._setManifest(tx, Verifier.createManifest(manifest), null)
        await this.state.flush()
      }
    } finally {
      this.state._unlock()
    }
  }

  _setManifest(tx, manifest, keyPair) {
    if (!manifest && b4a.equals(keyPair.publicKey, this.header.key)) {
      manifest = Verifier.defaultSignerManifest(this.header.key)
    }
    if (!manifest) return

    const verifier = new Verifier(this.header.key, manifest, { legacy: this._legacy })

    if (verifier.prologue) this.state.prologue = Object.assign({}, verifier.prologue)

    this.manifest = this.header.manifest = manifest

    tx.setAuth({
      key: this.header.key,
      discoveryKey: this.discoveryKey,
      manifest,
      keyPair: this.header.keyPair
      // TODO: encryptionKey?
    })

    this.compat = verifier.compat
    this.verifier = verifier

    this.replicator.onupgrade()
    this.emitManifest()
  }

  async copyPrologue(src) {
    await this.state.mutex.lock()

    try {
      await src.mutex.lock()
    } catch (err) {
      this.state.mutex.unlock()
      throw err
    }

    try {
      await copyPrologue(src, this)
    } finally {
      src.mutex.unlock()
      this.state.mutex.unlock()
      this.checkIfIdle()
    }
  }

  flushed() {
    return this.state.flushed()
  }

  async _validateCommit(state, treeLength) {
    if (this.state.length > state.length) {
      return false // TODO: partial commit and truncation possible in the future
    }

    if (this.state.length > treeLength) {
      for (const root of this.state.roots) {
        const batchRoot = await MerkleTree.get(state, root.index)
        if (batchRoot.size !== root.size || !b4a.equals(batchRoot.hash, root.hash)) {
          return false
        }
      }
    }

    if (this.verifier === null) {
      return false // easier to assert than upsert
    }

    return true
  }

  _verifyBatchUpgrade(batch, manifest) {
    if (!this.header.manifest) {
      // compat, drop at some point
      if (!manifest) manifest = Verifier.defaultSignerManifest(this.header.key)

      if (
        !manifest ||
        !(
          Verifier.isValidManifest(this.header.key, manifest) ||
          Verifier.isCompat(this.header.key, manifest)
        )
      ) {
        throw INVALID_SIGNATURE('Proof contains an invalid manifest', this.discoveryKey) // TODO: proper error type
      }
    }

    const verifier =
      this.verifier ||
      new Verifier(this.header.key, Verifier.createManifest(manifest), { legacy: this._legacy })

    if (!verifier.verify(batch, batch.signature)) {
      throw INVALID_SIGNATURE('Proof contains an invalid signature', this.discoveryKey)
    }

    return manifest
  }

  async _verifyExclusive({ batch, bitfield, value, manifest }) {
    manifest = this._verifyBatchUpgrade(batch, manifest)

    if (
      !(await this.state._verifyBlock(
        batch,
        bitfield,
        value,
        this.header.manifest ? null : manifest
      ))
    ) {
      return false
    }

    if (!batch.upgraded && bitfield) {
      this.replicator.onhave(bitfield.start, bitfield.length, bitfield.drop)
    }

    return true
  }

  async _verifyShared() {
    if (!this._verifies.length) return false

    await this.state.mutex.lock()

    const tx = this.state.createWriteBatch()

    const verifies = this._verifies
    this._verifies = null
    this._verified = null

    try {
      for (const { batch, bitfield, value } of verifies) {
        if (!batch.commitable()) continue

        if (bitfield) {
          tx.putBlock(bitfield.start, value)
        }
      }

      const bits = new BitInterlude()

      for (let i = 0; i < verifies.length; i++) {
        const { batch, bitfield, manifest } = verifies[i]

        if (!batch.commitable()) {
          verifies[i] = null // signal that we cannot commit this one
          continue
        }

        if (bitfield) {
          bits.setRange(bitfield.start, bitfield.start + 1, true)
        }

        // if we got a manifest AND its strictly a non compat one, lets store it
        if (manifest && this.header.manifest === null) {
          if (!Verifier.isValidManifest(this.header.key, manifest)) {
            throw INVALID_CHECKSUM('Manifest hash does not match', this.discoveryKey)
          }
          this._setManifest(tx, manifest, null)
        }

        if (batch.commitable()) batch.commit(tx)
      }

      const ranges = bits.flush(tx, this.bitfield)

      await this.state.flush()

      for (const { start, end, value } of ranges) {
        this._setBitfieldRanges(start, end, value)
      }

      for (let i = 0; i < verifies.length; i++) {
        const bitfield = verifies[i] && verifies[i].bitfield
        if (bitfield) {
          this.updateContiguousLength(bitfield)
          this.replicator.onhave(bitfield.start, bitfield.length, bitfield.drop)
        }
      }

      if (this.hintsChanged) await this.flushHints()
    } finally {
      this.state._clearActiveBatch()
      this.state.mutex.unlock()
    }

    return verifies[0] !== null
  }

  async flushHints() {
    if (!this.hintsChanged) return
    this.hintsChanged = false // we unset this immediately as a "debounce"

    const tx = this.state.storage.write()

    tx.setHints({
      contiguousLength: this.header.hints.contiguousLength,
      remoteContiguousLength: this.header.hints.remoteContiguousLength,
      recovering: this.header.hints.recovering
    })

    await tx.flush()
  }

  async checkConflict(proof, from) {
    if (this.state.length < proof.upgrade.length || proof.fork !== this.state.fork) {
      // out of date this proof - ignore for now
      return false
    }

    // sanity check -> no manifest, no way to verify
    if (!this.header.manifest) {
      return false
    }

    const batch = MerkleTree.verifyFullyRemote(this.state, proof)

    try {
      this._verifyBatchUpgrade(batch, proof.manifest)
    } catch {
      return true
    }

    const roots = await maybeGetRootsFromStorage(this.storage, proof.upgrade.length)
    const remoteTreeHash = crypto.tree(proof.upgrade.nodes)
    const localTreeHash = crypto.tree(roots)

    try {
      const rx = this.state.storage.read()
      const treeProofPromise = MerkleTree.proof(this.state, rx, {
        block: null,
        hash: null,
        seek: null,
        upgrade: {
          start: 0,
          length: proof.upgrade.length
        }
      })

      rx.tryFlush()

      const treeProof = await treeProofPromise

      const verifyBatch = MerkleTree.verifyFullyRemote(this.state, await treeProof.settle())
      this._verifyBatchUpgrade(verifyBatch, this.header.manifest)
    } catch (err) {
      if (err.code !== 'INVALID_OPERATION') return true

      return !(await this._repairTreeNodes(proof))
    }

    // both proofs are valid, now check if they forked
    if (b4a.equals(localTreeHash, remoteTreeHash)) return false

    await this.state.mutex.lock()

    try {
      const tx = this.state.createWriteBatch()

      this.header.frozen = true

      tx.setAuth({
        key: this.header.key,
        discoveryKey: this.discoveryKey,
        manifest: this.header.manifest,
        keyPair: this.header.keyPair,
        frozen: true
      })

      await this.state.flush()
    } finally {
      this.state.mutex.unlock()
    }

    // tmp log so we can see these
    const id = b4a.toString(this.discoveryKey, 'hex')
    console.log(
      '[hypercore] conflict detected in ' +
        id +
        ' (writable=' +
        !!this.header.keyPair +
        ',quorum=' +
        this.header.manifest.quorum +
        ')'
    )
    await this._onconflict(proof)
    return true
  }

  async _repairTreeNodes(proof) {
    if (!this._repairMode) return false

    await this.state.mutex.lock()

    for (let i = this.monitors.length - 1; i >= 0; i--) {
      this.monitors[i].emit('repairing', proof)
    }

    try {
      const batch = MerkleTree.verifyFullyRemote(this.state, proof)
      this._verifyBatchUpgrade(batch, proof.manifest)
    } catch {
      this.state.mutex.unlock()
      for (let i = this.monitors.length - 1; i >= 0; i--) {
        this.monitors[i].emit('repair-failed')
      }
      return false
    }

    // Attempt to repair local merkle tree with remote roots
    const atom = this.storage.createAtom()
    const atomized = this.storage.atomize(atom)
    const tx = atomized.write()
    for (const node of proof.upgrade.nodes) {
      tx.putTreeNode(node)
    }
    await tx.flush()

    // Try local proof again
    try {
      const rx = atomized.read()
      const treeProofPromise = MerkleTree.proof(this.state, rx, {
        block: null,
        hash: null,
        seek: null,
        upgrade: {
          start: 0,
          length: proof.upgrade.length
        }
      })

      rx.tryFlush()

      const treeProof = await treeProofPromise

      const verifyBatch = MerkleTree.verifyFullyRemote(this.state, await treeProof.settle())
      this._verifyBatchUpgrade(verifyBatch, this.header.manifest)
    } catch (err) {
      this.state.mutex.unlock()
      for (let i = this.monitors.length - 1; i >= 0; i--) {
        this.monitors[i].emit('repair-failed')
      }
      return false
    }

    await atom.flush()

    for (let i = this.monitors.length - 1; i >= 0; i--) {
      this.monitors[i].emit('repaired', proof)
    }
    this.replicator.setPushOnly(false)
    this.state.mutex.unlock()
    return true
  }

  async verifyReorg(proof) {
    const batch = new ReorgBatch(this.state)
    await MerkleTree.reorg(this.state, proof, batch)
    const manifest = this._verifyBatchUpgrade(batch, proof.manifest)

    if (manifest && !this.header.manifest) {
      await this.state.mutex.lock()
      try {
        if (manifest && this.header.manifest === null) {
          const tx = this.state.createWriteBatch()
          this._setManifest(tx, Verifier.createManifest(manifest), null)
          await this.state.flush()
        }
      } finally {
        this.state._unlock()
      }
    }

    return batch
  }

  async verify(proof, from) {
    // We cannot apply "other forks" atm.
    // We should probably still try and they are likely super similar for non upgrades
    // but this is easy atm (and the above layer will just retry)
    if (proof.fork !== this.state.fork) return false

    const batch = await MerkleTree.verify(this.state, proof)

    if (batch.upgraded && batch.length <= this.state.length) {
      await batch.downgrade()
    }

    if (!batch.commitable()) {
      return false
    }

    const value = (proof.block && proof.block.value) || null
    const op = {
      batch,
      bitfield: value && { drop: false, start: proof.block.index, length: 1 },
      value,
      manifest: proof.manifest,
      from
    }

    if (batch.upgraded) {
      return this._verifyExclusive(op)
    }

    if (this._verifies !== null) {
      const verifies = this._verifies
      const i = verifies.push(op)
      await this._verified
      return verifies[i] !== null
    }

    this._verifies = [op]
    this._verified = this._verifyShared()

    return this._verified
  }

  async reorg(batch) {
    if (!batch.commitable()) return false

    this.truncating++

    try {
      await this.state.reorg(batch)
    } finally {
      this.truncating--
    }

    return true
  }

  openSkipBitfield() {
    if (this.skipBitfield !== null) return this.skipBitfield
    this.skipBitfield = new RemoteBitfield()
    const buf = this.bitfield.toBuffer(this.state.length)
    const bitfield = new Uint32Array(buf.buffer, buf.byteOffset, buf.byteLength / 4)
    this.skipBitfield.insert(0, bitfield)
    return this.skipBitfield
  }

  _setBitfieldRanges(start, end, value) {
    this.bitfield.setRange(start, end, value)
    if (this.skipBitfield !== null) this.skipBitfield.setRange(start, end, value)
  }

  close() {
    if (!this.closing) this.closing = this._close()
    return this.closing
  }

  updateContiguousLength(bitfield) {
    const contig = updateContigBatch(this.header.hints.contiguousLength, bitfield, this.bitfield)

    if (contig.length !== -1 && contig.length !== this.header.hints.contiguousLength) {
      this.header.hints.contiguousLength = contig.length
      this.hintsChanged = true
    }
  }

  updateRemoteContiguousLength(length) {
    this.header.hints.remoteContiguousLength = length
    this.hintsChanged = true
    this.remoteContiguousLengthChanged = true
  }

  onappend(tree, bitfield) {
    this.header.tree = tree

    if (!bitfield) {
      this.replicator.onupgrade()
      return
    }

    this.replicator.cork()

    const { start, length, drop } = bitfield

    this._setBitfieldRanges(start, start + length, true)
    this.updateContiguousLength({ start, length, drop: false })

    this.replicator.onupgrade()
    this.replicator.onhave(start, length, drop)
    this.replicator.uncork()
  }

  ontruncate(tree, { start, length }) {
    if (tree) this.header.tree = tree

    this.replicator.cork()

    this.replicator.ontruncate(start, length)
    this.replicator.onhave(start, length, true)
    this.replicator.onupgrade()
    this.replicator.uncork()

    for (const sessionState of this.sessionStates) {
      if (start < sessionState.snapshotCompatLength) sessionState.snapshotCompatLength = start
    }

    this._setBitfieldRanges(start, start + length, false)
    this.updateContiguousLength({ start, length, drop: true })
  }

  async _onconflict(proof) {
    await this.replicator.onconflict()

    for (let i = this.monitors.length - 1; i >= 0; i--) {
      const s = this.monitors[i]
      s.emit('conflict', proof.upgrade.length, proof.fork, proof)
    }

    const err = new Error('Two conflicting signatures exist for length ' + proof.upgrade.length)
    await this.closeAllSessions(err)
  }

  async closeAllSessions(err) {
    // this.sessions modifies itself when a session closes
    // This way we ensure we indeed iterate over all sessions
    const sessions = this.allSessions()

    const all = []
    for (const s of sessions) all.push(s.close({ error: err, force: false })) // force false or else infinite recursion
    await Promise.allSettled(all)
  }

  async destroy() {
    if (this.destroyed === true) return
    this.destroyed = true

    if (this.hasSession() === true) throw new Error('Cannot destroy while sessions are open')

    const weakSessions = this.allSessions()

    if (this.replicator) this.replicator.destroy()
    if (this.state) await this.state.close()

    // close all pending weak sessions...
    for (const s of weakSessions) s.close().catch(noop)
  }

  async _close() {
    if (this.opened === false) await this.opening
    if (this.hasSession() === true) throw new Error('Cannot close while sessions are open')

    if (this.replicator) await this.replicator.close()

    await this.destroy()
    if (this.autoClose) await this.storage.store.close()

    this.closed = true
  }
}

function updateContigBatch(start, upd, bitfield) {
  const end = upd.start + upd.length

  let c = start

  if (upd.drop) {
    // If we dropped a block in the current contig range, "downgrade" it
    if (c > upd.start) {
      c = upd.start
    }
  } else {
    if (c <= end && c >= upd.start) {
      c = end
      while (bitfield.get(c)) c++
    }
  }

  if (c === start) {
    return {
      length: -1
    }
  }

  if (c > start) {
    return {
      length: c
    }
  }

  return {
    length: c
  }
}

function getDefaultTree() {
  return {
    fork: 0,
    length: 0,
    rootHash: null,
    signature: null,
    timestamp: 0
  }
}

function parseHeader(info) {
  if (!info) return null

  return {
    key: info.key,
    manifest: info.manifest,
    external: null,
    keyPair: info.keyPair,
    tree: info.head || getDefaultTree(),
    group: info.group,
    hints: {
      reorgs: [],
      contiguousLength: info.hints ? info.hints.contiguousLength : 0,
      remoteContiguousLength: info.hints ? info.hints.remoteContiguousLength : 0,
      recovering: info.hints ? info.hints.recovering : 0
    }
  }
}

async function maybeGetRootsFromStorage(storage, length) {
  try {
    return length ? await MerkleTree.getRootsFromStorage(storage, length) : []
  } catch (err) {
    if (err.code !== 'INVALID_OPERATION') throw err
    // If INVALID_OPERATION, a root is likely missing so load empty roots to try to recover
    return []
  }
}

function noop() {}

async function getCoreInfo(storage) {
  const r = storage.read()

  const auth = r.getAuth()
  const head = r.getHead()
  const hints = r.getHints()
  const group = r.getGroup()

  r.tryFlush()

  const [authInfo, headInfo, hintsInfo, groupInfo] = await Promise.all([auth, head, hints, group])
  return {
    ...authInfo,
    head: headInfo,
    hints: hintsInfo,
    group: groupInfo
  }
}
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const b4a = require('b4a')
const { DEFAULT_ENCRYPTION } = require('./caps')

const nonce = b4a.alloc(sodium.crypto_stream_NONCEBYTES)

module.exports = class DefaultEncryption {
  static PADDING = 8

  constructor(encryptionKey, hypercoreKey, opts = {}) {
    this.key = encryptionKey
    this.compat = opts.compat === true

    const keys = DefaultEncryption.deriveKeys(encryptionKey, hypercoreKey, opts)

    this.blockKey = keys.block
    this.blindingKey = keys.blinding
  }

  static deriveKeys(encryptionKey, hypercoreKey, { block = false, compat = false } = {}) {
    const subKeys = b4a.alloc(2 * sodium.crypto_stream_KEYBYTES)

    const blockKey = block ? encryptionKey : subKeys.subarray(0, sodium.crypto_stream_KEYBYTES)
    const blindingKey = subKeys.subarray(sodium.crypto_stream_KEYBYTES)

    if (!block) {
      if (compat) {
        sodium.crypto_generichash_batch(blockKey, [encryptionKey], hypercoreKey)
      } else {
        sodium.crypto_generichash_batch(blockKey, [DEFAULT_ENCRYPTION, hypercoreKey, encryptionKey])
      }
    }

    sodium.crypto_generichash(blindingKey, blockKey)

    return {
      blinding: blindingKey,
      block: blockKey
    }
  }

  static blockEncryptionKey(hypercoreKey, encryptionKey) {
    const blockKey = b4a.alloc(sodium.crypto_stream_KEYBYTES)
    sodium.crypto_generichash_batch(blockKey, [DEFAULT_ENCRYPTION, hypercoreKey, encryptionKey])
    return blockKey
  }

  static encrypt(index, block, fork, blockKey, blindingKey) {
    const padding = block.subarray(0, DefaultEncryption.PADDING)
    block = block.subarray(DefaultEncryption.PADDING)

    c.uint64.encode({ start: 0, end: 8, buffer: padding }, fork)
    c.uint64.encode({ start: 0, end: 8, buffer: nonce }, index)

    // Zero out any previous padding.
    nonce.fill(0, 8, 8 + padding.byteLength)

    // Blind the fork ID, possibly risking reusing the nonce on a reorg of the
    // Hypercore. This is fine as the blinding is best-effort and the latest
    // fork ID shared on replication anyway.
    sodium.crypto_stream_xor(padding, padding, nonce, blindingKey)

    nonce.set(padding, 8)

    // The combination of a (blinded) fork ID and a block index is unique for a
    // given Hypercore and is therefore a valid nonce for encrypting the block.
    sodium.crypto_stream_xor(block, block, nonce, blockKey)
  }

  static decrypt(index, block, blockKey) {
    const padding = block.subarray(0, DefaultEncryption.PADDING)
    block = block.subarray(DefaultEncryption.PADDING)

    c.uint64.encode({ start: 0, end: 8, buffer: nonce }, index)

    nonce.set(padding, 8)

    // Decrypt the block using the blinded fork ID.
    sodium.crypto_stream_xor(block, block, nonce, blockKey)
  }

  encrypt(index, block, fork, core) {
    if (core.compat !== this.compat) this._reload(core)
    return DefaultEncryption.encrypt(index, block, fork, this.blockKey, this.blindingKey)
  }

  decrypt(index, block, core) {
    if (core.compat !== this.compat) this._reload(core)
    return DefaultEncryption.decrypt(index, block, this.blockKey)
  }

  padding() {
    return DefaultEncryption.PADDING
  }

  _reload(core) {
    const block = b4a.equals(this.key, this.blockKey)
    const keys = DefaultEncryption.deriveKeys(this.key, core.key, { block, compat: core.compat })

    this.blockKey = keys.blockKey
    this.blindingKey = keys.blindingKey
  }
}
module.exports = class Download {
  constructor(session, range) {
    this.session = session
    this.range = range
    this.request = null
    this.opened = false
    this.opening = this._open()
    this.opening.catch(noop)
  }

  ready() {
    return this.opening
  }

  async _open() {
    if (this.session.opened === false) await this.session.opening
    this._download()
    this.opened = true
  }

  async done() {
    await this.ready()

    try {
      return await this.request.promise
    } catch (err) {
      if (isSessionMoved(err)) return this._download()
      throw err
    }
  }

  _download() {
    const activeRequests = (this.range && this.range.activeRequests) || this.session.activeRequests
    this.request = this.session.core.replicator.addRange(activeRequests, this.range)
    this.request.promise.catch(noop)
    return this.request.promise
  }

  /**
   * Deprecated. Use `range.done()`.
   */
  downloaded() {
    return this.done()
  }

  destroy() {
    this._destroyBackground().catch(noop)
  }

  async _destroyBackground() {
    if (this.opened === false) await this.ready()
    if (this.request.context) this.request.context.detach(this.request)
  }
}

function noop() {}

function isSessionMoved(err) {
  return err.code === 'SESSION_MOVED'
}
module.exports = {
  SMALL_WANTS: 1
}
// this helper is for fully remote proofs, is like in a push notification where no other context exists

const { MerkleTree } = require('./merkle-tree.js')
const messages = require('./messages.js')
const b4a = require('b4a')
const c = require('compact-encoding')
const crypto = require('hypercore-crypto')
const flat = require('flat-tree')

class SlimSession {
  constructor(storage, auth, head, roots) {
    this.fork = head ? head.fork : 0
    this.roots = roots
    this.length = head ? head.length : 0
    this.signature = head ? head.signature : null
    this.ancestors = this.length
    this.byteLength = 0
    this.prologue = auth.manifest.prologue
    this.storage = storage

    for (let i = 0; i < roots.length; i++) this.byteLength += roots[i].size
  }
}

module.exports = { verify, proof }

async function verify(storage, buffer, { referrer = null } = {}) {
  const state = { buffer, start: 0, end: buffer.byteLength }

  const discoveryKey = c.fixed32.decode(state)
  const proof = messages.wire.data.decode(state)

  const result = {
    key: null,
    discoveryKey,
    newer: true,
    length: 0,
    proof,
    block: null
  }

  const core = await storage.resumeCore(discoveryKey)
  if (core === null) return null

  let rx = core.read()
  const authPromise = rx.getAuth()
  const headPromise = rx.getHead()
  const referrerPromise = rx.getUserData('referrer')

  rx.tryFlush()

  const [auth, head, ref] = await Promise.all([authPromise, headPromise, referrerPromise])

  if (auth === null) return null

  if (referrer && (!ref || !b4a.equals(ref, referrer))) return null

  rx = core.read()

  const rootPromises = []

  for (const index of flat.fullRoots(head ? 2 * head.length : 0)) {
    rootPromises.push(rx.getTreeNode(index))
  }

  rx.tryFlush()

  let roots = await Promise.all(rootPromises)
  if (roots.some(isNull)) roots = []

  const length = head ? head.length : 0

  if (!auth.manifest || !auth.manifest.signers.length) return null

  const batch = await MerkleTree.verifyFullyRemote(new SlimSession(core, auth, head, roots), proof)
  const publicKey = auth.manifest.signers[0].publicKey

  let signable = null
  let signature = null

  if (auth.manifest.version === 0) {
    signable = batch.signable(auth.manifest.signers[0].namespace)
    signature = batch.signature
  } else {
    if (batch.signature[0] !== 1) return null
    if (batch.signature[1] !== 0) return null

    signable = batch.signable(auth.key)
    signature = batch.signature.subarray(2, 66)
  }

  if (!crypto.verify(signable, signature, publicKey)) {
    return null
  }

  result.key = auth.key
  result.discoveryKey = discoveryKey
  result.newer = batch.length > length
  result.length = batch.length
  result.block = proof.block

  return result
}

async function proof(sender, { index, block = null, upgrade = null } = {}) {
  const proof = await sender.proof({
    block: block ? { index, nodes: 0 } : null,
    upgrade: upgrade ? upgrade : { start: 0, length: sender.length }
  })

  if (block) proof.block.value = block
  proof.manifest = sender.core.header.manifest

  const state = { buffer: null, start: 0, end: 0 }
  const data = { request: 0, ...proof }

  c.fixed32.preencode(state, sender.discoveryKey)
  messages.wire.data.preencode(state, data)

  state.buffer = b4a.allocUnsafe(state.end)

  c.fixed32.encode(state, sender.discoveryKey)
  messages.wire.data.encode(state, data)

  return state.buffer
}

function isNull(x) {
  return x === null
}
const TICKS = 16

module.exports = class HotswapQueue {
  constructor() {
    this.priorities = [[], [], []]
  }

  *pick(peer) {
    for (let i = 0; i < this.priorities.length; i++) {
      // try first one more than second one etc etc
      let ticks = (this.priorities.length - i) * TICKS
      const queue = this.priorities[i]

      for (let j = 0; j < queue.length; j++) {
        const r = j + Math.floor(Math.random() * queue.length - j)
        const a = queue[j]
        const b = queue[r]

        if (r !== j) {
          queue[(b.hotswap.index = j)] = b
          queue[(a.hotswap.index = r)] = a
        }

        if (hasInflight(b, peer)) continue

        yield b

        if (--ticks <= 0) break
      }
    }
  }

  add(block) {
    if (block.hotswap !== null) this.remove(block)
    if (block.inflight.length === 0 || block.inflight.length >= 3) return

    // TODO: also use other stuff to determine queue prio
    const queue = this.priorities[block.inflight.length - 1]

    const index = queue.push(block) - 1
    block.hotswap = { ref: this, queue, index }
  }

  remove(block) {
    const hotswap = block.hotswap
    if (hotswap === null) return

    block.hotswap = null
    const head = hotswap.queue.pop()
    if (head === block) return
    hotswap.queue[(head.hotswap.index = hotswap.index)] = head
  }
}

function hasInflight(block, peer) {
  for (let j = 0; j < block.inflight.length; j++) {
    if (block.inflight[j].peer === peer) return true
  }
  return false
}
module.exports = class Info {
  constructor(opts = {}) {
    this.key = opts.key
    this.discoveryKey = opts.discoveryKey
    this.length = opts.length || 0
    this.contiguousLength = opts.contiguousLength || 0
    this.byteLength = opts.byteLength || 0
    this.fork = opts.fork || 0
    this.padding = opts.padding || 0
    this.storage = opts.storage || null
  }

  static async from(session, opts = {}) {
    return new Info({
      key: session.key,
      discoveryKey: session.discoveryKey,
      length: session.length,
      contiguousLength: session.contiguousLength,
      byteLength: session.byteLength,
      fork: session.fork,
      padding: session.padding,
      storage: opts.storage ? await this.storage(session) : null
    })
  }

  static async storage(session) {
    const { oplog, tree, blocks, bitfield } = session.core
    try {
      return {
        oplog: await Info.bytesUsed(oplog.storage),
        tree: await Info.bytesUsed(tree.storage),
        blocks: await Info.bytesUsed(blocks.storage),
        bitfield: await Info.bytesUsed(bitfield.storage)
      }
    } catch {
      return null
    }
  }

  static bytesUsed(file) {
    return new Promise((resolve, reject) => {
      file.stat((err, st) => {
        if (err) {
          resolve(0) // prob just file not found (TODO, improve)
        } else if (typeof st.blocks !== 'number') {
          reject(new Error('cannot determine bytes used'))
        } else {
          resolve(st.blocks * 512)
        }
      })
    })
  }
}
const b4a = require('b4a')

module.exports = function (core, depth, opts) {
  let indent = ''
  if (typeof opts.indentationLvl === 'number') {
    while (indent.length < opts.indentationLvl) indent += ' '
  }

  let peers = ''
  const min = Math.min(core.peers.length, 5)

  for (let i = 0; i < min; i++) {
    const peer = core.peers[i]

    peers += `${indent}    Peer(\n`
    peers += `${indent}      remotePublicKey: ${opts.stylize(toHex(peer.remotePublicKey), 'string')}\n`
    peers += `${indent}      remoteLength: ${opts.stylize(peer.remoteLength, 'number')}\n`
    peers += `${indent}      remoteFork: ${opts.stylize(peer.remoteFork, 'number')}\n`
    peers += `${indent}      remoteCanUpgrade: ${opts.stylize(peer.remoteCanUpgrade, 'boolean')}\n`
    peers += `${indent}    )\n`
  }

  if (core.peers.length > 5) {
    peers += `${indent}  ... and ${core.peers.length - 5} more\n`
  }

  if (peers) peers = `[\n${peers}${indent}  ]`
  else peers = `[ ${opts.stylize(0, 'number')} ]`

  return (
    `${core.constructor.name}(\n` +
    `${indent}  id: ${opts.stylize(core.id, 'string')}\n` +
    `${indent}  key: ${opts.stylize(toHex(core.key), 'string')}\n` +
    `${indent}  discoveryKey: ${opts.stylize(toHex(core.discoveryKey), 'string')}\n` +
    `${indent}  opened: ${opts.stylize(core.opened, 'boolean')}\n` +
    `${indent}  closed: ${opts.stylize(core.closed, 'boolean')}\n` +
    `${indent}  snapshotted: ${opts.stylize(core.snapshotted, 'boolean')}\n` +
    `${indent}  writable: ${opts.stylize(core.writable, 'boolean')}\n` +
    `${indent}  length: ${opts.stylize(core.length, 'number')}\n` +
    `${indent}  fork: ${opts.stylize(core.fork, 'number')}\n` +
    `${indent}  sessions: [ ${opts.stylize(core.sessions.length, 'number')} ]\n` +
    `${indent}  activeRequests: [ ${opts.stylize(core.activeRequests.length, 'number')} ]\n` +
    `${indent}  peers: ${peers}\n` +
    `${indent})`
  )
}

function toHex(buf) {
  return buf && b4a.toString(buf, 'hex')
}
const BigSparseArray = require('big-sparse-array')
const { Transform } = require('streamx')
const quickbit = require('./compat').quickbit
const b4a = require('b4a')

const BITS_PER_PAGE = 32768
const BYTES_PER_PAGE = BITS_PER_PAGE / 8

class MarkPage {
  constructor() {
    this.bitfield = null
    this.loaded = new Promise((resolve) => {
      this.load = resolve
    })
  }

  setBitfield(bitfield) {
    this.bitfield = bitfield
    this.load()
  }

  get(index) {
    return quickbit.get(this.bitfield, index)
  }

  set(index, val) {
    quickbit.set(this.bitfield, index, val)
  }
}

module.exports = class MarkBitfield {
  static BITS_PER_PAGE = BITS_PER_PAGE
  static BYTES_PER_PAGE = BYTES_PER_PAGE

  constructor(storage) {
    this.storage = storage
    this._pages = new BigSparseArray()
  }

  async loadPage(pageIndex) {
    const p = this._pages.set(pageIndex, new MarkPage())
    const rx = this.storage.read()
    const pageBuf = rx.getMark(pageIndex)
    rx.tryFlush()
    const bitfield = (await pageBuf) ?? b4a.alloc(BYTES_PER_PAGE)
    await p.setBitfield(bitfield)
    return p
  }

  async get(index) {
    const j = index & (BITS_PER_PAGE - 1)
    const i = (index - j) / BITS_PER_PAGE

    let p = this._pages.get(i)
    if (!p) p = await this.loadPage(i)

    return p.get(j)
  }

  async set(index, val) {
    const j = index & (BITS_PER_PAGE - 1)
    const i = (index - j) / BITS_PER_PAGE

    let p = this._pages.get(i)

    if (!p && val) p = await this.loadPage(i)

    if (p) {
      await p.loaded
      p.set(j, val)
      const tx = this.storage.write()
      tx.putMark(i, p.bitfield)
      await tx.flush()
    }
  }

  async clear() {
    const tx = this.storage.write()
    tx.deleteMarkRange(0, -1)
    await tx.flush()
    this._pages = new BigSparseArray()
  }

  createMarkStream({ reverse = false } = {}) {
    return this.storage.createMarkStream({ reverse }).pipe(
      new Transform({
        transform({ index, page }, cb) {
          let bitIndex = reverse
            ? quickbit.findLast(page, true, BITS_PER_PAGE)
            : quickbit.findFirst(page, true, 0)
          while (bitIndex !== -1) {
            const blockIndex = index * BITS_PER_PAGE + bitIndex
            this.push(blockIndex)

            // Account for `bitIndex` being either causing infinite loop
            if (bitIndex === 0 && reverse) break

            bitIndex = reverse
              ? quickbit.findLast(page, true, bitIndex - 1)
              : quickbit.findFirst(page, true, bitIndex + 1)
          }

          cb(null)
        }
      })
    )
  }
}
const flat = require('flat-tree')
const crypto = require('hypercore-crypto')
const b4a = require('b4a')
const unslab = require('unslab')
const caps = require('./caps')
const {
  INVALID_PROOF,
  INVALID_CHECKSUM,
  INVALID_OPERATION,
  BAD_ARGUMENT,
  ASSERTION
} = require('hypercore-errors')

class NodeQueue {
  constructor(nodes, extra = null) {
    this.i = 0
    this.nodes = nodes
    this.extra = extra
    this.length = nodes.length + (this.extra === null ? 0 : 1)
  }

  shift(index) {
    if (this.extra !== null && this.extra.index === index) {
      const node = this.extra
      this.extra = null
      this.length--
      return node
    }

    if (this.i >= this.nodes.length) {
      throw INVALID_OPERATION('Expected node ' + index + ', got (nil)')
    }

    const node = this.nodes[this.i++]
    if (node.index !== index) {
      throw INVALID_OPERATION('Expected node ' + index + ', got node ' + node.index)
    }

    this.length--
    return node
  }
}

class MerkleTreeBatch {
  constructor(session) {
    this.fork = session.fork
    this.roots = [...session.roots]
    this.length = session.length
    this.signature = session.signature
    this.ancestors = session.length
    this.byteLength = session.byteLength
    this.prologue = session.prologue
    this.hashCached = null

    this.committed = false
    this.truncated = false
    this.treeLength = session.length
    this.treeFork = session.fork
    this.storage = session.storage
    this.session = session
    this.nodes = []
    this.upgraded = false
  }

  checkout(length, additionalRoots) {
    const roots = []
    let r = 0

    const head = 2 * length - 2
    const gaps = new Set()
    const all = new Map()

    // additional roots is so the original roots can be passed (we mutate the array in appendRoot)
    if (additionalRoots) {
      for (const node of additionalRoots) all.set(node.index, node)
    }

    for (const node of this.nodes) all.set(node.index, node)

    for (const index of flat.fullRoots(head + 2)) {
      const left = flat.leftSpan(index)
      if (left !== 0) gaps.add(left - 1)

      if (r < this.roots.length && this.roots[r].index === index) {
        roots.push(this.roots[r++])
        continue
      }
      const node = all.get(index)
      if (!node) throw new BAD_ARGUMENT('root missing for given length')
      roots.push(node)
    }

    this.roots = roots
    this.length = length
    this.byteLength = totalSize(roots)
    this.hashCached = null
    this.signature = null

    for (let i = 0; i < this.nodes.length; i++) {
      const index = this.nodes[i].index
      if (index <= head && !gaps.has(index)) continue
      const last = this.nodes.pop()
      if (i < this.nodes.length) this.nodes[i--] = last
    }
  }

  prune(length) {
    if (length === 0) return

    const head = 2 * length - 2
    const gaps = new Set()

    // TODO: make a function for this in flat-tree
    for (const index of flat.fullRoots(head + 2)) {
      const left = flat.leftSpan(index)
      if (left !== 0) gaps.add(left - 1)
    }

    for (let i = 0; i < this.nodes.length; i++) {
      const index = this.nodes[i].index
      if (index > head || gaps.has(index)) continue
      const last = this.nodes.pop()
      if (i < this.nodes.length) this.nodes[i--] = last
    }
  }

  clone() {
    const b = new MerkleTreeBatch(this.session)

    b.fork = this.fork
    b.roots = [...this.roots]
    b.length = this.length
    b.byteLength = this.byteLength
    b.signature = this.signature
    b.treeLength = this.treeLength
    b.treeFork = this.treeFork
    b.tree = this.tree
    b.nodes = [...this.nodes]
    b.upgraded = this.upgraded

    return b
  }

  hash() {
    if (this.hashCached === null) this.hashCached = unslab(crypto.tree(this.roots))
    return this.hashCached
  }

  signable(manifestHash) {
    return caps.treeSignable(manifestHash, this.hash(), this.length, this.fork)
  }

  signableCompat(noHeader) {
    return caps.treeSignableCompat(this.hash(), this.length, this.fork, noHeader)
  }

  get(index) {
    if (index >= this.length * 2) {
      return null
    }

    for (const n of this.nodes) {
      if (n.index === index) return n
    }

    return getTreeNodeFromStorage(this.session.storage, index)
  }

  // deprecated, use sssion proof instead
  proof(batch, { block, hash, seek, upgrade }) {
    return generateProof(this.session, batch, block, hash, seek, upgrade)
  }

  verifyUpgrade(proof) {
    const unverified = verifyTree(proof, this.nodes)

    if (!proof.upgrade) throw INVALID_OPERATION('Expected upgrade proof')

    return verifyUpgrade(proof, unverified, this)
  }

  addNodesUnsafe(nodes) {
    for (let i = 0; i < nodes.length; i++) {
      this.nodes.push(nodes[i])
    }
  }

  append(buf) {
    const head = this.length * 2
    const ite = flat.iterator(head)
    const node = blockNode(head, buf)

    this.appendRoot(node, ite)
  }

  appendRoot(node, ite) {
    node = unslabNode(node)
    this.hashCached = null
    this.upgraded = true
    this.length += ite.factor / 2
    this.byteLength += node.size
    this.roots.push(node)
    this.nodes.push(node)

    while (this.roots.length > 1) {
      const a = this.roots[this.roots.length - 1]
      const b = this.roots[this.roots.length - 2]

      // TODO: just have a peek sibling instead? (pretty sure it's always the left sib as well)
      if (ite.sibling() !== b.index) {
        ite.sibling() // unset so it always points to last root
        break
      }

      const node = unslabNode(parentNode(ite.parent(), a, b))
      this.nodes.push(node)
      this.roots.pop()
      this.roots.pop()
      this.roots.push(node)
    }
  }

  commitable() {
    return (
      this.treeFork === this.session.fork &&
      (this.upgraded
        ? this.treeLength === this.session.length
        : this.treeLength <= this.session.length)
    )
  }

  commit(tx) {
    if (tx === undefined) throw INVALID_OPERATION('No database batch was passed')

    if (this.session.core._repairMode) {
      throw ASSERTION('Cannot commit while repair mode is on')
    }

    if (!this.commitable()) {
      throw INVALID_OPERATION('Tree was modified during batch, refusing to commit')
    }

    if (this.upgraded) this._commitUpgrade(tx)

    for (let i = 0; i < this.nodes.length; i++) {
      const node = this.nodes[i]
      tx.putTreeNode(node)
    }

    this.committed = true

    return this
  }

  _commitUpgrade(tx) {
    // TODO: If easy to detect, we should refuse an trunc+append here without a fork id
    // change. Will only happen on user error so mostly to prevent that.

    if (this.ancestors < this.treeLength) {
      tx.deleteTreeNodeRange(this.ancestors * 2, this.treeLength * 2)

      if (this.ancestors > 0) {
        const head = this.ancestors * 2
        const ite = flat.iterator(head - 2)

        while (true) {
          if (ite.contains(head) && ite.index < head) {
            tx.deleteTreeNode(ite.index)
          }
          if (ite.offset === 0) break
          ite.parent()
        }

        this.truncated = true
      }
    }
  }

  seek(bytes, padding) {
    return new ByteSeeker(this, this, bytes, padding)
  }

  byteRange(index) {
    const rx = this.storage.read()
    const range = getByteRange(this, index, rx)
    rx.tryFlush()

    return range
  }

  byteOffset(index) {
    if (index === 2 * this.length) return this.byteLength

    const rx = this.storage.read()
    const offset = getByteOffset(this, index, rx)
    rx.tryFlush()

    return offset
  }

  async downgrade() {
    if (!this.upgraded) return true

    const rx = this.storage.read()
    const nodePromises = []

    for (const r of this.roots) {
      nodePromises.push(rx.getTreeNode(r.index))
    }

    rx.tryFlush()

    const nodes = await Promise.all(nodePromises)

    for (let i = 0; i < this.roots.length; i++) {
      const root = this.roots[i]
      const node = nodes[i]

      if (!node) return false
      if (!b4a.equals(node.hash, root.hash)) return false
    }

    this.upgraded = false
    return true
  }

  async restore(length) {
    if (length === this.length) return this

    const roots = unslabNodes(await MerkleTree.getRootsFromStorage(this.storage, length))

    this.roots = roots
    this.length = length
    this.byteLength = totalSize(roots)
    this.ancestors = length

    for (const node of roots) this.byteLength += node.size

    return this
  }
}

class ReorgBatch extends MerkleTreeBatch {
  constructor(session) {
    super(session)

    this.roots = []
    this.length = 0
    this.byteLength = 0
    this.diff = null
    this.ancestors = 0
    // We set upgraded because reorgs are signed so hit will
    // hit the same code paths (like the treeLength check in commit)
    this.upgraded = true
    this.want = {
      nodes: 0,
      start: 0,
      end: 0
    }
  }

  get finished() {
    return this.want === null
  }

  update(proof) {
    if (this.want === null) return true

    const nodes = []
    const root = verifyTree(proof, nodes)

    if (root === null || !b4a.equals(root.hash, this.diff.hash)) return false

    this.nodes.push(...nodes)
    return this._update(nodes)
  }

  async _update(nodes) {
    const n = new Map()
    for (const node of nodes) n.set(node.index, node)

    let diff = null
    const ite = flat.iterator(this.diff.index)
    const startingDiff = this.diff

    while ((ite.index & 1) !== 0) {
      const left = n.get(ite.leftChild())
      if (!left) break

      const existing = await getTreeNodeFromStorage(this.session.storage, left.index)
      if (!existing || !b4a.equals(existing.hash, left.hash)) {
        diff = left
      } else {
        diff = n.get(ite.sibling())
      }
    }

    if ((this.diff.index & 1) === 0) return true
    if (diff === null) return false
    if (startingDiff !== this.diff) return false

    return this._updateDiffRoot(diff)
  }

  _updateDiffRoot(diff) {
    if (this.want === null) return true

    const spans = flat.spans(diff.index)
    const start = spans[0] / 2
    const end = Math.min(this.treeLength, spans[1] / 2 + 1)
    const len = end - start

    this.ancestors = start
    this.diff = diff

    if ((diff.index & 1) === 0 || this.want.start >= this.treeLength || len <= 0) {
      this.want = null
      return true
    }

    this.want.start = start
    this.want.end = end
    this.want.nodes = log2(spans[1] - spans[0] + 2) - 1

    return false
  }
}

class ByteSeeker {
  constructor(session, bytes, padding = 0) {
    this.session = session
    this.bytes = bytes
    this.padding = padding

    const size = session.byteLength - session.length * padding

    this.start = bytes >= size ? session.length : 0
    this.end = bytes < size ? session.length : 0
  }

  async _seek(bytes) {
    if (!bytes) return [0, 0]

    for (const node of this.session.roots) {
      // all async ticks happen once we find the root so safe
      const size = getUnpaddedSize(node, this.padding, null)

      if (bytes === size) return [flat.rightSpan(node.index) + 2, 0]
      if (bytes > size) {
        bytes -= size
        continue
      }

      const ite = flat.iterator(node.index)

      while ((ite.index & 1) !== 0) {
        const l = await getTreeNodeFromStorage(this.session.storage, ite.leftChild())

        if (l) {
          const size = getUnpaddedSize(l, this.padding, ite)

          if (size === bytes) return [ite.rightSpan() + 2, 0]
          if (size > bytes) continue
          bytes -= size
          ite.sibling()
        } else {
          ite.parent()
          return [ite.index, bytes]
        }
      }

      return [ite.index, bytes]
    }

    return null
  }

  async update() {
    // TODO: combine _seek and this, much simpler
    const res = await this._seek(this.bytes)
    if (!res) return null
    if ((res[0] & 1) === 0) return [res[0] / 2, res[1]]

    const span = flat.spans(res[0])
    this.start = span[0] / 2
    this.end = span[1] / 2 + 1

    return null
  }
}

class TreeProof {
  constructor(session, block, hash, seek, upgrade) {
    this.fork = session.fork
    this.signature = session.signature

    this.block = block
    this.hash = hash
    this.seek = seek
    this.upgrade = upgrade

    this.pending = {
      node: null,
      seek: null,
      upgrade: null,
      additionalUpgrade: null
    }
  }

  async settle() {
    const result = {
      fork: this.fork,
      block: null,
      hash: null,
      seek: null,
      upgrade: null,
      manifest: null
    }

    const [pNode, pSeek, pUpgrade, pAdditional] = await settleProof(this.pending)

    if (this.block) {
      if (pNode === null) throw INVALID_OPERATION('Invalid block request')
      result.block = {
        index: this.block.index,
        value: null, // populated upstream, alloc it here for simplicity
        nodes: pNode
      }
    } else if (this.hash) {
      if (pNode === null) throw INVALID_OPERATION('Invalid block request')
      result.hash = {
        index: this.hash.index,
        nodes: pNode
      }
    }

    if (this.seek && pSeek !== null) {
      result.seek = {
        bytes: this.seek.bytes,
        nodes: pSeek
      }
    }

    if (this.upgrade) {
      result.upgrade = {
        start: this.upgrade.start,
        length: this.upgrade.length,
        nodes: pUpgrade,
        additionalNodes: pAdditional || [],
        signature: this.signature
      }
    }

    return result
  }
}

class MerkleTree {
  static hash(s) {
    return unslab(crypto.tree(s.roots))
  }

  static signable(s, namespace) {
    return caps.treeSignable(namespace, MerkleTree.hash(s), s.length, s.fork)
  }

  static size(roots) {
    return totalSize(roots)
  }

  static span(roots) {
    return totalSpan(roots)
  }

  static getRoots(session, length) {
    return MerkleTree.getRootsFromStorage(session.storage, length)
  }

  static getRootsFromStorage(storage, length) {
    const indexes = flat.fullRoots(2 * length)
    const roots = new Array(indexes.length)
    const rx = storage.read()

    for (let i = 0; i < indexes.length; i++) {
      roots[i] = getTreeNodeOrError(rx, indexes[i])
    }

    rx.tryFlush()

    return Promise.all(roots)
  }

  static async upgradeable(session, length) {
    const indexes = flat.fullRoots(2 * length)
    const roots = new Array(indexes.length)
    const rx = session.storage.read()

    for (let i = 0; i < indexes.length; i++) {
      roots[i] = rx.getTreeNode(indexes[i])
    }

    rx.tryFlush()

    for (const node of await Promise.all(roots)) {
      if (node === null) return false
    }

    return true
  }

  static seek(session, bytes, padding) {
    return new ByteSeeker(session, bytes, padding)
  }

  static get(session, index) {
    return getTreeNodeFromStorage(session.storage, index)
  }

  static async truncate(session, length, batch, fork = batch.fork) {
    const head = length * 2
    const fullRoots = flat.fullRoots(head)

    for (let i = 0; i < fullRoots.length; i++) {
      const root = fullRoots[i]
      if (i < batch.roots.length && batch.roots[i].index === root) continue

      while (batch.roots.length > i) batch.roots.pop()
      batch.roots.push(unslabNode(await getTreeNodeFromStorageOrError(session.storage, root)))
    }

    while (batch.roots.length > fullRoots.length) {
      batch.roots.pop()
    }

    batch.fork = fork
    batch.length = length
    batch.ancestors = length
    batch.byteLength = totalSize(batch.roots)
    batch.upgraded = true

    return batch
  }

  static async reorg(session, proof, batch) {
    let unverified = null

    if (proof.block || proof.hash || proof.seek) {
      unverified = verifyTree(proof, batch.nodes)
    }

    if (!verifyUpgrade(proof, unverified, batch)) {
      throw INVALID_PROOF('Fork proof not verifiable')
    }

    for (const root of batch.roots) {
      const existing = await getTreeNodeFromStorage(session.storage, root.index)
      if (existing && b4a.equals(existing.hash, root.hash)) continue
      batch._updateDiffRoot(root)
      break
    }

    if (batch.diff !== null) {
      await batch._update(batch.nodes)
    } else {
      batch.want = null
      batch.ancestors = batch.length
    }

    return batch
  }

  static verifyFullyRemote(session, proof) {
    // TODO: impl this less hackishly
    const batch = new MerkleTreeBatch(session)

    batch.fork = proof.fork
    batch.roots = []
    batch.length = 0
    batch.ancestors = 0
    batch.byteLength = 0

    let unverified = verifyTree(proof, batch.nodes)

    if (proof.upgrade) {
      if (verifyUpgrade(proof, unverified, batch)) {
        unverified = null
      }
    }

    return batch
  }

  static async verify(session, proof) {
    const batch = new MerkleTreeBatch(session)

    let unverified = verifyTree(proof, batch.nodes)

    if (proof.upgrade) {
      if (verifyUpgrade(proof, unverified, batch)) {
        unverified = null
      }
    }

    if (unverified) {
      const verified = await getTreeNodeFromStorageOrError(session.storage, unverified.index)
      if (!b4a.equals(verified.hash, unverified.hash)) {
        throw INVALID_CHECKSUM('Invalid checksum at node ' + unverified.index)
      }
    }

    return batch
  }

  static proof(session, rx, { block, hash, seek, upgrade }) {
    return generateProof(session, rx, block, hash, seek, upgrade)
  }

  static maxMissingNodes(index, length) {
    const head = 2 * length
    const ite = flat.iterator(index)

    // See iterator.rightSpan()
    const iteRightSpan = ite.index + ite.factor / 2 - 1
    // If the index is not in the current tree, we do not know how many missing nodes there are...
    if (iteRightSpan >= head) return 0

    for (const r of flat.fullRoots(head)) {
      if (r === index) return 0
    }

    // need missing nodes not inclusive of index
    ite.parent()

    let cnt = 0
    while (!ite.contains(head)) {
      cnt++
      ite.parent()
    }

    return cnt
  }

  static async missingNodes(session, index, length) {
    const head = 2 * length
    const ite = flat.iterator(index)

    // See iterator.rightSpan()
    const iteRightSpan = ite.index + ite.factor / 2 - 1
    // If the index is not in the current tree, we do not know how many missing nodes there are...
    if (iteRightSpan >= head) return 0

    let cnt = 0
    // TODO: we could prop use a read batch here and do this in blocks of X for perf
    while (!ite.contains(head) && !(await hasTreeNode(session.storage, ite.index))) {
      cnt++
      if (cnt >= 1024) {
        throw ASSERTION('Bad arguments to missingNodes index=' + index + ' at length=' + length)
      }
      ite.parent()
    }

    return cnt
  }

  static byteOffset(session, index) {
    return getByteOffsetSession(session, index, null)
  }

  static byteRange(session, index) {
    const rx = session.storage.read()
    const offset = getByteOffsetSession(session, index, rx)
    const size = getNodeSize(index, rx)
    rx.tryFlush()
    return Promise.all([offset, size])
  }

  static upgradeLength(proof) {
    const extra = proof.additionalNodes

    if (extra.length) {
      const last = extra[extra.length - 1]
      const index = flat.rightSpan(last.index)
      return index / 2 + 1
    }

    return proof.start + proof.length
  }
}

module.exports = {
  MerkleTreeBatch,
  ReorgBatch,
  MerkleTree
}

async function getNodeSize(index, rx) {
  return (await getTreeNodeOrError(rx, index)).size
}

async function getByteOffsetSession(session, index, rx) {
  if (index === 2 * session.length) return session.byteLength

  const treeNodes =
    rx === null
      ? await getByteOffsetBatchFlush(session.roots, index, session.storage.read())
      : await getByteOffsetBatch(session.roots, index, rx)

  let offset = 0
  for (const node of treeNodes) offset += node.size

  return offset
}

async function getByteOffset(tree, index, rx) {
  if (index === 2 * tree.length) return tree.byteLength

  const treeNodes = await getByteOffsetBatch(tree.roots, index, rx)

  let offset = 0
  for (const node of treeNodes) offset += node.size

  return offset
}

function getByteOffsetBatchFlush(roots, index, rx) {
  const treeNodes = getByteOffsetBatch(roots, index, rx)
  rx.tryFlush()
  return treeNodes
}

function getByteOffsetBatch(roots, index, rx) {
  if ((index & 1) === 1) index = flat.leftSpan(index)

  let head = 0
  let cnt = 0

  const promises = []

  for (const node of roots) {
    // all async ticks happen once we find the root so safe
    head += 2 * (node.index - head + 1)

    if (index >= head) {
      promises.push(node.size)
      continue
    }

    const ite = flat.iterator(node.index)

    while (ite.index !== index) {
      if (++cnt >= 1024) throw ASSERTION('Bad getByteOffsetSession index=' + index)

      if (index < ite.index) {
        ite.leftChild()
      } else {
        promises.push(getTreeNodeOrError(rx, ite.leftChild()))
        ite.sibling()
      }
    }

    return Promise.all(promises)
  }

  throw ASSERTION('Failed to find offset')
}

function getByteRange(tree, index, rx) {
  const head = 2 * tree.length
  if (((index & 1) === 0 ? index : flat.rightSpan(index)) >= head) {
    throw BAD_ARGUMENT('Index is out of bounds')
  }

  const offset = getByteOffset(tree, index, rx)
  const size = getNodeSize(index, rx)

  return Promise.all([offset, size])
}

// All the methods needed for proof verification

function verifyTree({ block, hash, seek }, nodes) {
  const untrustedNode = block
    ? { index: 2 * block.index, value: block.value, nodes: block.nodes }
    : hash
      ? { index: hash.index, value: null, nodes: hash.nodes }
      : null

  if (untrustedNode === null && (!seek || !seek.nodes.length)) return null

  let root = null

  if (seek && seek.nodes.length) {
    const ite = flat.iterator(seek.nodes[0].index)
    const q = new NodeQueue(seek.nodes)

    root = q.shift(ite.index)
    nodes.push(root)

    while (q.length > 0) {
      const node = q.shift(ite.sibling())

      root = parentNode(ite.parent(), root, node)
      nodes.push(node)
      nodes.push(root)
    }
  }

  if (untrustedNode === null) return root

  const ite = flat.iterator(untrustedNode.index)
  const blockHash = untrustedNode.value && blockNode(ite.index, untrustedNode.value)

  const q = new NodeQueue(untrustedNode.nodes, root)

  root = blockHash || q.shift(ite.index)
  nodes.push(root)

  while (q.length > 0) {
    const node = q.shift(ite.sibling())

    root = parentNode(ite.parent(), root, node)
    nodes.push(node)
    nodes.push(root)
  }

  return root
}

function verifyUpgrade({ fork, upgrade }, blockRoot, batch) {
  const prologue = batch.prologue

  if (prologue) {
    const { start, length } = upgrade
    if (start < prologue.length && (start !== 0 || length < prologue.length)) {
      throw INVALID_PROOF('Upgrade does not satisfy prologue')
    }
  }

  const q = new NodeQueue(upgrade.nodes, blockRoot)

  let grow = batch.roots.length > 0
  let i = 0

  const to = 2 * (upgrade.start + upgrade.length)
  const ite = flat.iterator(0)

  for (; ite.fullRoot(to); ite.nextTree()) {
    if (i < batch.roots.length && batch.roots[i].index === ite.index) {
      i++
      continue
    }

    if (grow) {
      grow = false
      const root = ite.index
      if (i < batch.roots.length) {
        ite.seek(batch.roots[batch.roots.length - 1].index)
        while (ite.index !== root) {
          batch.appendRoot(q.shift(ite.sibling()), ite)
        }
        continue
      }
    }

    batch.appendRoot(q.shift(ite.index), ite)
  }

  if (prologue && batch.length === prologue.length) {
    if (!b4a.equals(prologue.hash, batch.hash())) {
      throw INVALID_PROOF('Invalid hash')
    }
  }

  const extra = upgrade.additionalNodes

  ite.seek(batch.roots[batch.roots.length - 1].index)
  i = 0

  while (i < extra.length && extra[i].index === ite.sibling()) {
    batch.appendRoot(extra[i++], ite)
  }

  while (i < extra.length) {
    const node = extra[i++]

    while (node.index !== ite.index) {
      if (ite.factor === 2) throw INVALID_OPERATION('Unexpected node: ' + node.index)
      ite.leftChild()
    }

    batch.appendRoot(node, ite)
    ite.sibling()
  }

  batch.signature = unslab(upgrade.signature)
  batch.fork = fork

  return q.extra === null
}

async function seekFromHead(session, head, bytes, padding) {
  const roots = flat.fullRoots(head)

  for (let i = 0; i < roots.length; i++) {
    const root = roots[i]
    const node = await getTreeNodeFromStorage(session.storage, root)
    const size = getUnpaddedSize(node, padding, null)

    if (bytes === size) return root
    if (bytes > size) {
      bytes -= size
      continue
    }

    return seekTrustedTree(session, root, bytes, padding)
  }

  return head
}

// trust that bytes are within the root tree and find the block at bytes

async function seekTrustedTree(session, root, bytes, padding) {
  if (!bytes) return root

  const ite = flat.iterator(root)
  let cnt = 0

  while ((ite.index & 1) !== 0) {
    if (++cnt >= 1024) throw ASSERTION('Bad seekTrusted bytes=' + bytes + ', paddding=' + padding)
    const l = await getTreeNodeFromStorage(session.storage, ite.leftChild())

    if (l) {
      const size = getUnpaddedSize(l, padding, ite)
      if (size === bytes) return ite.index
      if (size > bytes) continue
      bytes -= size
      ite.sibling()
    } else {
      ite.parent()
      return ite.index
    }
  }

  return ite.index
}

// try to find the block at bytes without trusting that is *is* within the root passed

async function seekUntrustedTree(session, root, bytes, padding) {
  const offset =
    (await getByteOffsetSession(session, root, null)) -
    (padding ? (padding * flat.leftSpan(root)) / 2 : 0)

  if (offset > bytes) throw INVALID_OPERATION('Invalid seek')
  if (offset === bytes) return root

  bytes -= offset

  const node = await getTreeNodeFromStorageOrError(session.storage, root)

  if (getUnpaddedSize(node, padding, null) <= bytes) throw INVALID_OPERATION('Invalid seek')

  return seekTrustedTree(session, root, bytes, padding)
}

// Below is proof production, ie, construct proofs to verify a request
// Note, that all these methods are sync as we can statically infer which nodes
// are needed for the remote to verify given they arguments they passed us

function seekProof(session, rx, seekRoot, root, p) {
  const ite = flat.iterator(seekRoot)
  let cnt = 0

  p.seek = []
  p.seek.push(getTreeNodeOrError(rx, ite.index))

  while (ite.index !== root) {
    if (++cnt >= 1024) throw ASSERTION('Bad seekProof seekRoot=' + seekRoot + ', root=' + root)
    ite.sibling()
    p.seek.push(getTreeNodeOrError(rx, ite.index))
    ite.parent()
  }
}

function blockAndSeekProof(session, rx, node, seek, seekRoot, root, p) {
  if (!node) return seekProof(session, rx, seekRoot, root, p)

  const ite = flat.iterator(node.index)
  let cnt = 0

  p.node = []
  if (!node.value) p.node.push(getTreeNodeOrError(rx, ite.index))

  while (ite.index !== root) {
    if (++cnt >= 1024) {
      throw ASSERTION('Bad blockAndSeekProof seekRoot=' + seekRoot + ', root=' + root)
    }
    ite.sibling()

    if (seek && ite.contains(seekRoot) && ite.index !== seekRoot) {
      seekProof(session, rx, seekRoot, ite.index, p)
    } else {
      p.node.push(getTreeNodeOrError(rx, ite.index))
    }

    ite.parent()
  }
}

function upgradeProof(session, rx, node, seek, from, to, subTree, p) {
  if (from === 0) p.upgrade = []

  for (const ite = flat.iterator(0); ite.fullRoot(to); ite.nextTree()) {
    // check if they already have the node
    if (ite.index + ite.factor / 2 < from) continue

    // connect existing tree
    if (p.upgrade === null && ite.contains(from - 2)) {
      p.upgrade = []

      const root = ite.index
      const target = from - 2
      let cnt = 0

      ite.seek(target)

      while (ite.index !== root) {
        if (++cnt >= 1024) throw ASSERTION('Bad upgradeProof target=' + target + ', root=' + root)

        ite.sibling()
        if (ite.index > target) {
          if (p.node === null && p.seek === null && ite.contains(subTree)) {
            blockAndSeekProof(session, rx, node, seek, subTree, ite.index, p)
          } else {
            p.upgrade.push(getTreeNodeOrError(rx, ite.index))
          }
        }
        ite.parent()
      }

      continue
    }

    if (p.upgrade === null) {
      p.upgrade = []
    }

    // if the subtree included is a child of this tree, include that one
    // instead of a dup node
    if (p.node === null && p.seek === null && ite.contains(subTree)) {
      blockAndSeekProof(session, rx, node, seek, subTree, ite.index, p)
      continue
    }

    // add root (can be optimised since the root might be in tree.roots)
    p.upgrade.push(getTreeNodeOrError(rx, ite.index))
  }
}

function additionalUpgradeProof(session, rx, from, to, p) {
  if (from === 0) p.additionalUpgrade = []

  for (const ite = flat.iterator(0); ite.fullRoot(to); ite.nextTree()) {
    // check if they already have the node
    if (ite.index + ite.factor / 2 < from) continue

    // connect existing tree
    if (p.additionalUpgrade === null && ite.contains(from - 2)) {
      p.additionalUpgrade = []

      const root = ite.index
      const target = from - 2
      let cnt = 0

      ite.seek(target)

      while (ite.index !== root) {
        if (++cnt >= 1024) {
          throw ASSERTION(
            'Bad arguments to additionalUpgradeProof root=' + root + ' target=' + target
          )
        }
        ite.sibling()
        if (ite.index > target) {
          p.additionalUpgrade.push(getTreeNodeOrError(rx, ite.index))
        }
        ite.parent()
      }

      continue
    }

    if (p.additionalUpgrade === null) {
      p.additionalUpgrade = []
    }

    // add root (can be optimised since the root is in tree.roots)
    p.additionalUpgrade.push(getTreeNodeOrError(rx, ite.index))
  }
}

function nodesToRoot(index, nodes, head) {
  const ite = flat.iterator(index)

  for (let i = 0; i < nodes; i++) {
    ite.parent()
    if (ite.contains(head)) throw INVALID_OPERATION('Nodes is out of bounds')
  }

  return ite.index
}

function totalSize(nodes) {
  let s = 0
  for (const node of nodes) s += node.size
  return s
}

function totalSpan(nodes) {
  let s = 0
  for (const node of nodes) s += 2 * (node.index - s + 1)
  return s
}

function blockNode(index, value) {
  return { index, size: value.byteLength, hash: crypto.data(value) }
}

function parentNode(index, a, b) {
  return { index, size: a.size + b.size, hash: crypto.parent(a, b) }
}

function log2(n) {
  let res = 1

  while (n > 2) {
    n /= 2
    res++
  }

  return res
}

function normalizeIndexed(block, hash) {
  if (block) {
    return {
      value: true,
      index: block.index * 2,
      nodes: block.nodes,
      lastIndex: block.index
    }
  }
  if (hash) {
    return {
      value: false,
      index: hash.index,
      nodes: hash.nodes,
      lastIndex: flat.rightSpan(hash.index) / 2
    }
  }
  return null
}

async function getTreeNodeOrError(rx, index) {
  const node = await rx.getTreeNode(index)
  if (node === null) {
    throw INVALID_OPERATION('Expected tree node ' + index + ' from storage, got (nil)')
  }
  return node
}

function getTreeNodeFromStorageOrError(storage, index) {
  const rx = storage.read()
  const p = getTreeNodeOrError(rx, index)
  rx.tryFlush()
  return p
}

function getTreeNodeFromStorage(storage, index) {
  const rx = storage.read()
  const node = rx.getTreeNode(index)
  rx.tryFlush()
  return node
}

function hasTreeNode(storage, index) {
  const rx = storage.read()
  const has = rx.hasTreeNode(index)
  rx.tryFlush()
  return has
}

async function settleProof(p) {
  const result = [
    p.node && Promise.all(p.node),
    p.seek && Promise.all(p.seek),
    p.upgrade && Promise.all(p.upgrade),
    p.additionalUpgrade && Promise.all(p.additionalUpgrade)
  ]

  try {
    return await Promise.all(result)
  } catch (err) {
    if (p.node) await Promise.allSettled(p.node)
    if (p.seek) await Promise.allSettled(p.seek)
    if (p.upgrade) await Promise.allSettled(p.upgrade)
    if (p.additionalUpgrade) await Promise.allSettled(p.additionalUpgrade)
    throw err
  }
}

// tree can be either the merkle tree or a merkle tree batch
async function generateProof(session, rx, block, hash, seek, upgrade) {
  // Important that this does not throw inbetween making the promise arrays
  // and finalise being called, otherwise there will be lingering promises in the background

  if (session.prologue && upgrade) {
    upgrade.start = upgrade.start < session.prologue.length ? 0 : upgrade.start
    upgrade.length =
      upgrade.start < session.prologue.length ? session.prologue.length : upgrade.length
  }

  const head = 2 * session.length
  const from = upgrade ? upgrade.start * 2 : 0
  const to = upgrade ? from + upgrade.length * 2 : head
  const node = normalizeIndexed(block, hash)

  // can't do anything as we have no data...
  if (head === 0) return new TreeProof(session, null, null, null, null)

  if (from >= to || to > head) {
    throw INVALID_OPERATION('Invalid upgrade')
  }
  if (seek && upgrade && node !== null && node.index >= from) {
    throw INVALID_OPERATION('Cannot both do a seek and block/hash request when upgrading')
  }

  let subTree = head

  const p = new TreeProof(session, block, hash, seek, upgrade)

  if (node !== null && (!upgrade || node.lastIndex < upgrade.start)) {
    subTree = nodesToRoot(node.index, node.nodes, to)
    const seekRoot = seek
      ? await seekUntrustedTree(session, subTree, seek.bytes, seek.padding)
      : head
    blockAndSeekProof(session, rx, node, seek, seekRoot, subTree, p.pending)
  } else if ((node || seek) && upgrade) {
    subTree = seek ? await seekFromHead(session, to, seek.bytes, seek.padding) : node.index
  }

  if (upgrade) {
    upgradeProof(session, rx, node, seek, from, to, subTree, p.pending)
    if (head > to) additionalUpgradeProof(session, rx, to, head, p.pending)
  }

  return p
}

function getUnpaddedSize(node, padding, ite) {
  return padding === 0
    ? node.size
    : node.size - padding * (ite ? ite.countLeaves() : flat.countLeaves(node.index))
}

function unslabNodes(nodes) {
  for (const node of nodes) unslabNode(node)
  return nodes
}

function unslabNode(node) {
  if (node === null) return node
  node.hash = unslab(node.hash)
  return node
}
const c = require('compact-encoding')
const { DEFAULT_NAMESPACE } = require('./caps')
const { INVALID_OPLOG_VERSION } = require('hypercore-errors')
const unslab = require('unslab')

const MANIFEST_PATCH = 0b00000001
const MANIFEST_PROLOGUE = 0b00000010
const MANIFEST_LINKED = 0b00000100
const MANIFEST_USER_DATA = 0b00001000

const hashes = {
  preencode(state, m) {
    state.end++ // small uint
  },
  encode(state, m) {
    if (m === 'blake2b') {
      c.uint.encode(state, 0)
      return
    }

    throw new Error('Unknown hash: ' + m)
  },
  decode(state) {
    const n = c.uint.decode(state)
    if (n === 0) return 'blake2b'
    throw new Error('Unknown hash id: ' + n)
  }
}

const signatures = {
  preencode(state, m) {
    state.end++ // small uint
  },
  encode(state, m) {
    if (m === 'ed25519') {
      c.uint.encode(state, 0)
      return
    }

    throw new Error('Unknown signature: ' + m)
  },
  decode(state) {
    const n = c.uint.decode(state)
    if (n === 0) return 'ed25519'
    throw new Error('Unknown signature id: ' + n)
  }
}

const signer = {
  preencode(state, m) {
    signatures.preencode(state, m.signature)
    c.fixed32.preencode(state, m.namespace)
    c.fixed32.preencode(state, m.publicKey)
  },
  encode(state, m) {
    signatures.encode(state, m.signature)
    c.fixed32.encode(state, m.namespace)
    c.fixed32.encode(state, m.publicKey)
  },
  decode(state) {
    return {
      signature: signatures.decode(state),
      namespace: c.fixed32.decode(state),
      publicKey: c.fixed32.decode(state)
    }
  }
}

const signerArray = c.array(signer)

const prologue = {
  preencode(state, p) {
    c.fixed32.preencode(state, p.hash)
    c.uint.preencode(state, p.length)
  },
  encode(state, p) {
    c.fixed32.encode(state, p.hash)
    c.uint.encode(state, p.length)
  },
  decode(state) {
    return {
      hash: c.fixed32.decode(state),
      length: c.uint.decode(state)
    }
  }
}

const manifestv0 = {
  preencode(state, m) {
    hashes.preencode(state, m.hash)
    state.end++ // type

    if (m.prologue && m.signers.length === 0) {
      c.fixed32.preencode(state, m.prologue.hash)
      return
    }

    if (m.quorum === 1 && m.signers.length === 1 && !m.allowPatch) {
      signer.preencode(state, m.signers[0])
    } else {
      state.end++ // flags
      c.uint.preencode(state, m.quorum)
      signerArray.preencode(state, m.signers)
    }
  },
  encode(state, m) {
    hashes.encode(state, m.hash)

    if (m.prologue && m.signers.length === 0) {
      c.uint.encode(state, 0)
      c.fixed32.encode(state, m.prologue.hash)
      return
    }

    if (m.quorum === 1 && m.signers.length === 1 && !m.allowPatch) {
      c.uint.encode(state, 1)
      signer.encode(state, m.signers[0])
    } else {
      c.uint.encode(state, 2)
      c.uint.encode(state, m.allowPatch ? 1 : 0)
      c.uint.encode(state, m.quorum)
      signerArray.encode(state, m.signers)
    }
  },
  decode(state) {
    const hash = hashes.decode(state)
    const type = c.uint.decode(state)

    if (type > 2) throw new Error('Unknown type: ' + type)

    if (type === 0) {
      return {
        version: 0,
        hash,
        allowPatch: false,
        quorum: 0,
        signers: [],
        prologue: {
          hash: c.fixed32.decode(state),
          length: 0
        },
        linked: null,
        userData: null
      }
    }

    if (type === 1) {
      return {
        version: 0,
        hash,
        allowPatch: false,
        quorum: 1,
        signers: [signer.decode(state)],
        prologue: null,
        linked: null,
        userData: null
      }
    }

    const flags = c.uint.decode(state)

    return {
      version: 0,
      hash,
      allowPatch: (flags & 1) !== 0,
      quorum: c.uint.decode(state),
      signers: signerArray.decode(state),
      prologue: null,
      linked: null,
      userData: null
    }
  }
}

const fixed32Array = c.array(c.fixed32)

const manifest = (exports.manifest = {
  preencode(state, m) {
    state.end++ // version

    if (m.version === 0) return manifestv0.preencode(state, m)

    state.end++ // flags
    hashes.preencode(state, m.hash)

    c.uint.preencode(state, m.quorum)
    signerArray.preencode(state, m.signers)

    if (m.prologue) prologue.preencode(state, m.prologue)
    if (m.linked) fixed32Array.preencode(state, m.linked)
    if (m.userData) c.buffer.preencode(state, m.userData)
  },
  encode(state, m) {
    c.uint.encode(state, m.version)

    if (m.version === 0) return manifestv0.encode(state, m)

    let flags = 0
    if (m.allowPatch) flags |= MANIFEST_PATCH
    if (m.prologue) flags |= MANIFEST_PROLOGUE
    if (m.linked) flags |= MANIFEST_LINKED
    if (m.userData) flags |= MANIFEST_USER_DATA

    c.uint.encode(state, flags)
    hashes.encode(state, m.hash)

    c.uint.encode(state, m.quorum)
    signerArray.encode(state, m.signers)

    if (m.prologue) prologue.encode(state, m.prologue)
    if (m.linked) fixed32Array.encode(state, m.linked)
    if (m.userData) c.buffer.encode(state, m.userData)
  },
  decode(state) {
    const version = c.uint.decode(state)

    if (version === 0) return manifestv0.decode(state)
    if (version > 2) throw new Error('Unknown version: ' + version)

    const flags = c.uint.decode(state)
    const hash = hashes.decode(state)
    const quorum = c.uint.decode(state)
    const signers = signerArray.decode(state)

    const hasPatch = (flags & MANIFEST_PATCH) !== 0
    const hasPrologue = (flags & MANIFEST_PROLOGUE) !== 0
    const hasLinked = (flags & MANIFEST_LINKED) !== 0
    const hasUserData = (flags & MANIFEST_USER_DATA) !== 0

    return {
      version,
      hash,
      allowPatch: hasPatch,
      quorum,
      signers,
      prologue: hasPrologue ? prologue.decode(state) : null,
      linked: hasLinked ? fixed32Array.decode(state) : null,
      userData: hasUserData ? c.buffer.decode(state) : null
    }
  }
})

const node = {
  preencode(state, n) {
    c.uint.preencode(state, n.index)
    c.uint.preencode(state, n.size)
    c.fixed32.preencode(state, n.hash)
  },
  encode(state, n) {
    c.uint.encode(state, n.index)
    c.uint.encode(state, n.size)
    c.fixed32.encode(state, n.hash)
  },
  decode(state) {
    return {
      index: c.uint.decode(state),
      size: c.uint.decode(state),
      hash: c.fixed32.decode(state)
    }
  }
}

const nodeArray = c.array(node)

const wire = (exports.wire = {})

wire.handshake = {
  preencode(state, m) {
    c.uint.preencode(state, 1)
    c.fixed32.preencode(state, m.capability)
  },
  encode(state, m) {
    c.uint.encode(state, m.seeks ? 1 : 0)
    c.fixed32.encode(state, m.capability)
  },
  decode(state) {
    const flags = c.uint.decode(state)
    return {
      seeks: (flags & 1) !== 0,
      capability: unslab(c.fixed32.decode(state))
    }
  }
}

const requestBlock = {
  preencode(state, b) {
    c.uint.preencode(state, b.index)
    c.uint.preencode(state, b.nodes)
  },
  encode(state, b) {
    c.uint.encode(state, b.index)
    c.uint.encode(state, b.nodes)
  },
  decode(state) {
    return {
      index: c.uint.decode(state),
      nodes: c.uint.decode(state)
    }
  }
}

const requestSeek = {
  preencode(state, s) {
    c.uint.preencode(state, s.bytes)
    c.uint.preencode(state, s.padding)
  },
  encode(state, s) {
    c.uint.encode(state, s.bytes)
    c.uint.encode(state, s.padding)
  },
  decode(state) {
    return {
      bytes: c.uint.decode(state),
      padding: c.uint.decode(state)
    }
  }
}

const requestUpgrade = {
  preencode(state, u) {
    c.uint.preencode(state, u.start)
    c.uint.preencode(state, u.length)
  },
  encode(state, u) {
    c.uint.encode(state, u.start)
    c.uint.encode(state, u.length)
  },
  decode(state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

wire.request = {
  preencode(state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.id)
    c.uint.preencode(state, m.fork)

    if (m.block) requestBlock.preencode(state, m.block)
    if (m.hash) requestBlock.preencode(state, m.hash)
    if (m.seek) requestSeek.preencode(state, m.seek)
    if (m.upgrade) requestUpgrade.preencode(state, m.upgrade)
    if (m.priority) c.uint.preencode(state, m.priority)
  },
  encode(state, m) {
    const flags =
      (m.block ? 1 : 0) |
      (m.hash ? 2 : 0) |
      (m.seek ? 4 : 0) |
      (m.upgrade ? 8 : 0) |
      (m.manifest ? 16 : 0) |
      (m.priority ? 32 : 0)

    c.uint.encode(state, flags)
    c.uint.encode(state, m.id)
    c.uint.encode(state, m.fork)

    if (m.block) requestBlock.encode(state, m.block)
    if (m.hash) requestBlock.encode(state, m.hash)
    if (m.seek) requestSeek.encode(state, m.seek)
    if (m.upgrade) requestUpgrade.encode(state, m.upgrade)
    if (m.priority) c.uint.encode(state, m.priority)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      id: c.uint.decode(state),
      fork: c.uint.decode(state),
      block: flags & 1 ? requestBlock.decode(state) : null,
      hash: flags & 2 ? requestBlock.decode(state) : null,
      seek: flags & 4 ? requestSeek.decode(state) : null,
      upgrade: flags & 8 ? requestUpgrade.decode(state) : null,
      manifest: (flags & 16) !== 0,
      priority: flags & 32 ? c.uint.decode(state) : 0
    }
  }
}

wire.cancel = {
  preencode(state, m) {
    c.uint.preencode(state, m.request)
  },
  encode(state, m) {
    c.uint.encode(state, m.request)
  },
  decode(state, m) {
    return {
      request: c.uint.decode(state)
    }
  }
}

const dataUpgrade = {
  preencode(state, u) {
    c.uint.preencode(state, u.start)
    c.uint.preencode(state, u.length)
    nodeArray.preencode(state, u.nodes)
    nodeArray.preencode(state, u.additionalNodes)
    c.optionalBuffer.preencode(state, u.signature)
  },
  encode(state, u) {
    c.uint.encode(state, u.start)
    c.uint.encode(state, u.length)
    nodeArray.encode(state, u.nodes)
    nodeArray.encode(state, u.additionalNodes)
    c.optionalBuffer.encode(state, u.signature)
  },
  decode(state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state),
      nodes: nodeArray.decode(state),
      additionalNodes: nodeArray.decode(state),
      signature: c.optionalBuffer.decode(state)
    }
  }
}

const dataSeek = {
  preencode(state, s) {
    c.uint.preencode(state, s.bytes)
    nodeArray.preencode(state, s.nodes)
  },
  encode(state, s) {
    c.uint.encode(state, s.bytes)
    nodeArray.encode(state, s.nodes)
  },
  decode(state) {
    return {
      bytes: c.uint.decode(state),
      nodes: nodeArray.decode(state)
    }
  }
}

const dataBlock = {
  preencode(state, b) {
    c.uint.preencode(state, b.index)
    c.buffer.preencode(state, b.value)
    nodeArray.preencode(state, b.nodes)
  },
  encode(state, b) {
    c.uint.encode(state, b.index)
    c.buffer.encode(state, b.value)
    nodeArray.encode(state, b.nodes)
  },
  decode(state) {
    return {
      index: c.uint.decode(state),
      value: c.buffer.decode(state),
      nodes: nodeArray.decode(state)
    }
  }
}

const dataHash = {
  preencode(state, b) {
    c.uint.preencode(state, b.index)
    nodeArray.preencode(state, b.nodes)
  },
  encode(state, b) {
    c.uint.encode(state, b.index)
    nodeArray.encode(state, b.nodes)
  },
  decode(state) {
    return {
      index: c.uint.decode(state),
      nodes: nodeArray.decode(state)
    }
  }
}

wire.data = {
  preencode(state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.request)
    c.uint.preencode(state, m.fork)

    if (m.block) dataBlock.preencode(state, m.block)
    if (m.hash) dataHash.preencode(state, m.hash)
    if (m.seek) dataSeek.preencode(state, m.seek)
    if (m.upgrade) dataUpgrade.preencode(state, m.upgrade)
    if (m.manifest) manifest.preencode(state, m.manifest)
  },
  encode(state, m) {
    const flags =
      (m.block ? 1 : 0) |
      (m.hash ? 2 : 0) |
      (m.seek ? 4 : 0) |
      (m.upgrade ? 8 : 0) |
      (m.manifest ? 16 : 0)

    c.uint.encode(state, flags)
    c.uint.encode(state, m.request)
    c.uint.encode(state, m.fork)

    if (m.block) dataBlock.encode(state, m.block)
    if (m.hash) dataHash.encode(state, m.hash)
    if (m.seek) dataSeek.encode(state, m.seek)
    if (m.upgrade) dataUpgrade.encode(state, m.upgrade)
    if (m.manifest) manifest.encode(state, m.manifest)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      request: c.uint.decode(state),
      fork: c.uint.decode(state),
      block: flags & 1 ? dataBlock.decode(state) : null,
      hash: flags & 2 ? dataHash.decode(state) : null,
      seek: flags & 4 ? dataSeek.decode(state) : null,
      upgrade: flags & 8 ? dataUpgrade.decode(state) : null,
      manifest: flags & 16 ? manifest.decode(state) : null
    }
  }
}

wire.noData = {
  preencode(state, m) {
    c.uint.preencode(state, m.request)
    c.uint.preencode(state, m.reason ? 1 : 0)
    if (m.reason) c.uint.preencode(state, m.reason)
  },
  encode(state, m) {
    c.uint.encode(state, m.request)
    c.uint.encode(state, m.reason ? 1 : 0)
    if (m.reason) c.uint.encode(state, m.reason)
  },
  decode(state, m) {
    const request = c.uint.decode(state)
    const flags = state.start < state.end ? c.uint.decode(state) : 0
    return {
      request,
      reason: flags & 1 ? c.uint.decode(state) : 0
    }
  }
}

// TODO: we should move to having these have a handle like in data, easier since they
// allocate state in practice
wire.want = {
  preencode(state, m) {
    c.uint.preencode(state, m.start)
    c.uint.preencode(state, m.length)

    const flags = m.any ? 1 : 0
    if (flags !== 0) c.uint.preencode(state, flags)
  },
  encode(state, m) {
    c.uint.encode(state, m.start)
    c.uint.encode(state, m.length)

    const flags = m.any ? 1 : 0
    if (flags !== 0) c.uint.encode(state, flags)
  },
  decode(state) {
    const start = c.uint.decode(state)
    const length = c.uint.decode(state)
    const flags = state.start < state.end ? c.uint.decode(state) : 0

    return {
      start,
      length,
      any: (flags & 1) !== 0
    }
  }
}

wire.unwant = {
  preencode(state, m) {
    c.uint.preencode(state, m.start)
    c.uint.preencode(state, m.length)

    const flags = m.any ? 1 : 0
    if (flags !== 0) c.uint.preencode(state, flags)
  },
  encode(state, m) {
    c.uint.encode(state, m.start)
    c.uint.encode(state, m.length)

    const flags = m.any ? 1 : 0
    if (flags !== 0) c.uint.encode(state, flags)
  },
  decode(state, m) {
    const start = c.uint.decode(state)
    const length = c.uint.decode(state)
    const flags = state.start < state.end ? c.uint.decode(state) : 0

    return {
      start,
      length,
      any: (flags & 1) !== 0
    }
  }
}

wire.range = {
  preencode(state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.start)
    if (m.length !== 1) c.uint.preencode(state, m.length)
  },
  encode(state, m) {
    c.uint.encode(state, (m.drop ? 1 : 0) | (m.length === 1 ? 2 : 0))
    c.uint.encode(state, m.start)
    if (m.length !== 1) c.uint.encode(state, m.length)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      drop: (flags & 1) !== 0,
      start: c.uint.decode(state),
      length: (flags & 2) !== 0 ? 1 : c.uint.decode(state)
    }
  }
}

wire.bitfield = {
  preencode(state, m) {
    c.uint.preencode(state, m.start)
    c.uint32array.preencode(state, m.bitfield)
  },
  encode(state, m) {
    c.uint.encode(state, m.start)
    c.uint32array.encode(state, m.bitfield)
  },
  decode(state, m) {
    return {
      start: c.uint.decode(state),
      bitfield: c.uint32array.decode(state)
    }
  }
}

wire.sync = {
  preencode(state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.fork)
    c.uint.preencode(state, m.length)
    c.uint.preencode(state, m.remoteLength)
  },
  encode(state, m) {
    c.uint.encode(
      state,
      (m.canUpgrade ? 1 : 0) |
        (m.uploading ? 2 : 0) |
        (m.downloading ? 4 : 0) |
        (m.hasManifest ? 8 : 0) |
        (m.allowPush ? 16 : 0)
    )
    c.uint.encode(state, m.fork)
    c.uint.encode(state, m.length)
    c.uint.encode(state, m.remoteLength)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      fork: c.uint.decode(state),
      length: c.uint.decode(state),
      remoteLength: c.uint.decode(state),
      canUpgrade: (flags & 1) !== 0,
      uploading: (flags & 2) !== 0,
      downloading: (flags & 4) !== 0,
      hasManifest: (flags & 8) !== 0,
      allowPush: (flags & 16) !== 0
    }
  }
}

wire.reorgHint = {
  preencode(state, m) {
    c.uint.preencode(state, m.from)
    c.uint.preencode(state, m.to)
    c.uint.preencode(state, m.ancestors)
  },
  encode(state, m) {
    c.uint.encode(state, m.from)
    c.uint.encode(state, m.to)
    c.uint.encode(state, m.ancestors)
  },
  decode(state) {
    return {
      from: c.uint.decode(state),
      to: c.uint.decode(state),
      ancestors: c.uint.decode(state)
    }
  }
}

wire.extension = {
  preencode(state, m) {
    c.string.preencode(state, m.name)
    c.raw.preencode(state, m.message)
  },
  encode(state, m) {
    c.string.encode(state, m.name)
    c.raw.encode(state, m.message)
  },
  decode(state) {
    return {
      name: c.string.decode(state),
      message: c.raw.decode(state)
    }
  }
}

const keyValue = {
  preencode(state, p) {
    c.string.preencode(state, p.key)
    c.buffer.preencode(state, p.value)
  },
  encode(state, p) {
    c.string.encode(state, p.key)
    c.buffer.encode(state, p.value)
  },
  decode(state) {
    return {
      key: c.string.decode(state),
      value: c.buffer.decode(state)
    }
  }
}

const treeUpgrade = {
  preencode(state, u) {
    c.uint.preencode(state, u.fork)
    c.uint.preencode(state, u.ancestors)
    c.uint.preencode(state, u.length)
    c.buffer.preencode(state, u.signature)
  },
  encode(state, u) {
    c.uint.encode(state, u.fork)
    c.uint.encode(state, u.ancestors)
    c.uint.encode(state, u.length)
    c.buffer.encode(state, u.signature)
  },
  decode(state) {
    return {
      fork: c.uint.decode(state),
      ancestors: c.uint.decode(state),
      length: c.uint.decode(state),
      signature: c.buffer.decode(state)
    }
  }
}

const bitfieldUpdate = {
  // TODO: can maybe be folded into a HAVE later on with the most recent spec
  preencode(state, b) {
    state.end++ // flags
    c.uint.preencode(state, b.start)
    c.uint.preencode(state, b.length)
  },
  encode(state, b) {
    state.buffer[state.start++] = b.drop ? 1 : 0
    c.uint.encode(state, b.start)
    c.uint.encode(state, b.length)
  },
  decode(state) {
    const flags = c.uint.decode(state)
    return {
      drop: (flags & 1) !== 0,
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

const oplog = (exports.oplog = {})

oplog.entry = {
  preencode(state, m) {
    state.end++ // flags
    if (m.userData) keyValue.preencode(state, m.userData)
    if (m.treeNodes) nodeArray.preencode(state, m.treeNodes)
    if (m.treeUpgrade) treeUpgrade.preencode(state, m.treeUpgrade)
    if (m.bitfield) bitfieldUpdate.preencode(state, m.bitfield)
  },
  encode(state, m) {
    const s = state.start++
    let flags = 0

    if (m.userData) {
      flags |= 1
      keyValue.encode(state, m.userData)
    }
    if (m.treeNodes) {
      flags |= 2
      nodeArray.encode(state, m.treeNodes)
    }
    if (m.treeUpgrade) {
      flags |= 4
      treeUpgrade.encode(state, m.treeUpgrade)
    }
    if (m.bitfield) {
      flags |= 8
      bitfieldUpdate.encode(state, m.bitfield)
    }

    state.buffer[s] = flags
  },
  decode(state) {
    const flags = c.uint.decode(state)
    return {
      userData: (flags & 1) !== 0 ? keyValue.decode(state) : null,
      treeNodes: (flags & 2) !== 0 ? nodeArray.decode(state) : null,
      treeUpgrade: (flags & 4) !== 0 ? treeUpgrade.decode(state) : null,
      bitfield: (flags & 8) !== 0 ? bitfieldUpdate.decode(state) : null
    }
  }
}

const keyPair = {
  preencode(state, kp) {
    c.buffer.preencode(state, kp.publicKey)
    c.buffer.preencode(state, kp.secretKey)
  },
  encode(state, kp) {
    c.buffer.encode(state, kp.publicKey)
    c.buffer.encode(state, kp.secretKey)
  },
  decode(state) {
    return {
      publicKey: c.buffer.decode(state),
      secretKey: c.buffer.decode(state)
    }
  }
}

const reorgHint = {
  preencode(state, r) {
    c.uint.preencode(state, r.from)
    c.uint.preencode(state, r.to)
    c.uint.preencode(state, r.ancestors)
  },
  encode(state, r) {
    c.uint.encode(state, r.from)
    c.uint.encode(state, r.to)
    c.uint.encode(state, r.ancestors)
  },
  decode(state) {
    return {
      from: c.uint.decode(state),
      to: c.uint.decode(state),
      ancestors: c.uint.decode(state)
    }
  }
}

const reorgHintArray = c.array(reorgHint)

const hints = {
  preencode(state, h) {
    reorgHintArray.preencode(state, h.reorgs)
    c.uint.preencode(state, h.contiguousLength)
  },
  encode(state, h) {
    reorgHintArray.encode(state, h.reorgs)
    c.uint.encode(state, h.contiguousLength)
  },
  decode(state) {
    return {
      reorgs: reorgHintArray.decode(state),
      contiguousLength: state.start < state.end ? c.uint.decode(state) : 0
    }
  }
}

const treeHeader = {
  preencode(state, t) {
    c.uint.preencode(state, t.fork)
    c.uint.preencode(state, t.length)
    c.buffer.preencode(state, t.rootHash)
    c.buffer.preencode(state, t.signature)
  },
  encode(state, t) {
    c.uint.encode(state, t.fork)
    c.uint.encode(state, t.length)
    c.buffer.encode(state, t.rootHash)
    c.buffer.encode(state, t.signature)
  },
  decode(state) {
    return {
      fork: c.uint.decode(state),
      length: c.uint.decode(state),
      rootHash: c.buffer.decode(state),
      signature: c.buffer.decode(state)
    }
  }
}

const types = {
  preencode(state, t) {
    c.string.preencode(state, t.tree)
    c.string.preencode(state, t.bitfield)
    c.string.preencode(state, t.signer)
  },
  encode(state, t) {
    c.string.encode(state, t.tree)
    c.string.encode(state, t.bitfield)
    c.string.encode(state, t.signer)
  },
  decode(state) {
    return {
      tree: c.string.decode(state),
      bitfield: c.string.decode(state),
      signer: c.string.decode(state)
    }
  }
}

const externalHeader = {
  preencode(state, m) {
    c.uint.preencode(state, m.start)
    c.uint.preencode(state, m.length)
  },
  encode(state, m) {
    c.uint.encode(state, m.start)
    c.uint.encode(state, m.length)
  },
  decode(state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

const keyValueArray = c.array(keyValue)

oplog.header = {
  preencode(state, h) {
    state.end += 2 // version + flags
    if (h.external) {
      externalHeader.preencode(state, h.external)
      return
    }
    c.fixed32.preencode(state, h.key)
    if (h.manifest) manifest.preencode(state, h.manifest)
    if (h.keyPair) keyPair.preencode(state, h.keyPair)
    keyValueArray.preencode(state, h.userData)
    treeHeader.preencode(state, h.tree)
    hints.preencode(state, h.hints)
  },
  encode(state, h) {
    c.uint.encode(state, 1)
    if (h.external) {
      c.uint.encode(state, 1) // ONLY set the first big for clarity
      externalHeader.encode(state, h.external)
      return
    }
    c.uint.encode(state, (h.manifest ? 2 : 0) | (h.keyPair ? 4 : 0))
    c.fixed32.encode(state, h.key)
    if (h.manifest) manifest.encode(state, h.manifest)
    if (h.keyPair) keyPair.encode(state, h.keyPair)
    keyValueArray.encode(state, h.userData)
    treeHeader.encode(state, h.tree)
    hints.encode(state, h.hints)
  },
  decode(state) {
    const version = c.uint.decode(state)

    if (version > 1) {
      throw INVALID_OPLOG_VERSION('Invalid header version. Expected <= 1, got ' + version)
    }

    if (version === 0) {
      const old = {
        types: types.decode(state),
        userData: keyValueArray.decode(state),
        tree: treeHeader.decode(state),
        signer: keyPair.decode(state),
        hints: hints.decode(state)
      }

      return {
        external: null,
        key: old.signer.publicKey,
        manifest: {
          version: 0,
          hash: old.types.tree,
          allowPatch: false,
          quorum: 1,
          signers: [
            {
              signature: old.types.signer,
              namespace: DEFAULT_NAMESPACE,
              publicKey: old.signer.publicKey
            }
          ],
          prologue: null,
          linked: null,
          userData: null
        },
        keyPair: old.signer.secretKey ? old.signer : null,
        userData: old.userData,
        tree: old.tree,
        hints: old.hints
      }
    }

    const flags = c.uint.decode(state)

    if (flags & 1) {
      return {
        external: externalHeader.decode(state),
        key: null,
        manifest: null,
        keyPair: null,
        userData: null,
        tree: null,
        hints: null
      }
    }

    return {
      external: null,
      key: c.fixed32.decode(state),
      manifest: (flags & 2) !== 0 ? manifest.decode(state) : null,
      keyPair: (flags & 4) !== 0 ? keyPair.decode(state) : null,
      userData: keyValueArray.decode(state),
      tree: treeHeader.decode(state),
      hints: hints.decode(state)
    }
  }
}

const uintArray = c.array(c.uint)

const multisigInput = {
  preencode(state, inp) {
    c.uint.preencode(state, inp.signer)
    c.fixed64.preencode(state, inp.signature)
    c.uint.preencode(state, inp.patch)
  },
  encode(state, inp) {
    c.uint.encode(state, inp.signer)
    c.fixed64.encode(state, inp.signature)
    c.uint.encode(state, inp.patch)
  },
  decode(state) {
    return {
      signer: c.uint.decode(state),
      signature: c.fixed64.decode(state),
      patch: c.uint.decode(state)
    }
  }
}

const patchEncodingv0 = {
  preencode(state, n) {
    c.uint.preencode(state, n.start)
    c.uint.preencode(state, n.length)
    uintArray.preencode(state, n.nodes)
  },
  encode(state, n) {
    c.uint.encode(state, n.start)
    c.uint.encode(state, n.length)
    uintArray.encode(state, n.nodes)
  },
  decode(state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state),
      nodes: uintArray.decode(state)
    }
  }
}

const multisigInputv0 = {
  preencode(state, n) {
    state.end++
    c.uint.preencode(state, n.signer)
    c.fixed64.preencode(state, n.signature)
    if (n.patch) patchEncodingv0.preencode(state, n.patch)
  },
  encode(state, n) {
    c.uint.encode(state, n.patch ? 1 : 0)
    c.uint.encode(state, n.signer)
    c.fixed64.encode(state, n.signature)
    if (n.patch) patchEncodingv0.encode(state, n.patch)
  },
  decode(state) {
    const flags = c.uint.decode(state)
    return {
      signer: c.uint.decode(state),
      signature: c.fixed64.decode(state),
      patch: flags & 1 ? patchEncodingv0.decode(state) : null
    }
  }
}

const multisigInputArrayv0 = c.array(multisigInputv0)
const multisigInputArray = c.array(multisigInput)

const compactNode = {
  preencode(state, n) {
    c.uint.preencode(state, n.index)
    c.uint.preencode(state, n.size)
    c.fixed32.preencode(state, n.hash)
  },
  encode(state, n) {
    c.uint.encode(state, n.index)
    c.uint.encode(state, n.size)
    c.fixed32.encode(state, n.hash)
  },
  decode(state) {
    return {
      index: c.uint.decode(state),
      size: c.uint.decode(state),
      hash: c.fixed32.decode(state)
    }
  }
}

const compactNodeArray = c.array(compactNode)

exports.multiSignaturev0 = {
  preencode(state, s) {
    multisigInputArrayv0.preencode(state, s.proofs)
    compactNodeArray.preencode(state, s.patch)
  },
  encode(state, s) {
    multisigInputArrayv0.encode(state, s.proofs)
    compactNodeArray.encode(state, s.patch)
  },
  decode(state) {
    return {
      proofs: multisigInputArrayv0.decode(state),
      patch: compactNodeArray.decode(state)
    }
  }
}

exports.multiSignature = {
  preencode(state, s) {
    multisigInputArray.preencode(state, s.proofs)
    compactNodeArray.preencode(state, s.patch)
  },
  encode(state, s) {
    multisigInputArray.encode(state, s.proofs)
    compactNodeArray.encode(state, s.patch)
  },
  decode(state) {
    return {
      proofs: multisigInputArray.decode(state),
      patch: compactNodeArray.decode(state)
    }
  }
}
const c = require('compact-encoding')
const b4a = require('b4a')
const flat = require('flat-tree')
const { MerkleTree } = require('./merkle-tree')
const { multiSignature, multiSignaturev0 } = require('./messages')

module.exports = {
  assemblev0,
  assemble,
  inflatev0,
  inflate,
  partialSignature,
  signableLength
}

function inflatev0(data) {
  return c.decode(multiSignaturev0, data)
}

function inflate(data) {
  return c.decode(multiSignature, data)
}

async function partialSignature(
  core,
  signer,
  from,
  to = core.state.length,
  signature = core.state.signature
) {
  if (from > core.state.length) return null
  const nodes = to <= from ? null : await upgradeNodes(core, from, to)

  if (signature.byteLength !== 64) {
    signature = c.decode(multiSignature, signature).proofs[0].signature
  }

  return {
    signer,
    signature,
    patch: nodes ? to - from : 0,
    nodes
  }
}

async function upgradeNodes(core, from, to) {
  const rx = core.state.storage.read()
  let p = null
  try {
    p = await MerkleTree.proof(core.state, rx, { upgrade: { start: from, length: to - from } })
  } catch (err) {
    rx.destroy()
    throw err
  }
  rx.tryFlush()
  return (await p.settle()).upgrade.nodes
}

function signableLength(lengths, quorum) {
  if (quorum <= 0) quorum = 1
  if (quorum > lengths.length) return 0

  return lengths.sort(cmp)[quorum - 1]
}

function cmp(a, b) {
  return b - a
}

function assemblev0(inputs) {
  const proofs = []
  const patch = []

  for (const u of inputs) {
    proofs.push(compressProof(u, patch))
  }

  return c.encode(multiSignaturev0, { proofs, patch })
}

function assemble(inputs) {
  const proofs = []
  const patch = []
  const seen = new Set()

  for (const u of inputs) {
    if (u.nodes) {
      for (const node of u.nodes) {
        if (seen.has(node.index)) continue
        seen.add(node.index)
        patch.push(node)
      }
    }

    proofs.push({
      signer: u.signer,
      signature: u.signature,
      patch: u.patch
    })
  }

  return c.encode(multiSignature, { proofs, patch })
}

function compareNode(a, b) {
  if (a.index !== b.index) return false
  if (a.size !== b.size) return false
  return b4a.equals(a.hash, b.hash)
}

function compressProof(proof, nodes) {
  return {
    signer: proof.signer,
    signature: proof.signature,
    patch: proof.patch ? compressUpgrade(proof, nodes) : null
  }
}

function compressUpgrade(p, nodes) {
  const u = {
    start: flat.rightSpan(p.nodes[p.nodes.length - 1].index) / 2 + 1,
    length: p.patch,
    nodes: []
  }

  for (const node of p.nodes) {
    let present = false
    for (let i = 0; i < nodes.length; i++) {
      if (!compareNode(nodes[i], node)) continue

      u.nodes.push(i)
      present = true
      break
    }

    if (present) continue
    u.nodes.push(nodes.push(node) - 1)
  }

  return u
}
module.exports = class Mutex {
  constructor() {
    this.locked = false
    this.destroyed = false

    this._destroying = null
    this._destroyError = null
    this._queue = []
    this._enqueue = (resolve, reject) => this._queue.push([resolve, reject])
  }

  idle() {
    return this._queue.length === 0 && this.locked === false
  }

  lock() {
    if (this.destroyed) {
      return Promise.reject(this._destroyError || new Error('Mutex has been destroyed'))
    }
    if (this.locked) return new Promise(this._enqueue)
    this.locked = true
    return Promise.resolve()
  }

  unlock() {
    if (!this._queue.length) {
      this.locked = false
      return
    }
    this._queue.shift()[0]()
  }

  destroy(err) {
    if (!this._destroying) {
      this._destroying = this.locked ? this.lock().catch(() => {}) : Promise.resolve()
    }

    this.destroyed = true
    if (err) this._destroyError = err

    if (err) {
      while (this._queue.length) this._queue.shift()[1](err)
    }

    return this._destroying
  }
}
const FIFO = require('fast-fifo')

module.exports = class ReceiverQueue {
  constructor() {
    this.queue = new FIFO()
    this.priority = []
    this.requests = new Map()
    this.length = 0
  }

  push(req) {
    // TODO: use a heap at some point if we wanna support multiple prios
    if (req.priority > 0) this.priority.push(req)
    else this.queue.push(req)

    this.requests.set(req.id, req)
    this.length++
  }

  shift() {
    while (this.priority.length > 0) {
      const msg = this.priority.pop()
      const req = this._processRequest(msg)
      if (req !== null) return req
    }

    while (this.queue.length > 0) {
      const msg = this.queue.shift()
      const req = this._processRequest(msg)
      if (req !== null) return req
    }

    return null
  }

  _processRequest(req) {
    if (req.block || req.hash || req.seek || req.upgrade || req.manifest) {
      this.requests.delete(req.id)
      this.length--
      return req
    }

    return null
  }

  clear() {
    this.queue.clear()
    this.priority = []
    this.length = 0
    this.requests.clear()
  }

  delete(id) {
    const req = this.requests.get(id)
    if (!req) return

    req.block = null
    req.hash = null
    req.seek = null
    req.upgrade = null
    req.manifest = false

    this.requests.delete(id)
    this.length--

    if (this.length === 0) {
      this.queue.clear()
      this.priority = []
    }
  }
}
const BigSparseArray = require('big-sparse-array')
const quickbit = require('./compat').quickbit

const BITS_PER_PAGE = 32768
const BYTES_PER_PAGE = BITS_PER_PAGE / 8
const WORDS_PER_PAGE = BYTES_PER_PAGE / 4
const BITS_PER_SEGMENT = 2097152
const BYTES_PER_SEGMENT = BITS_PER_SEGMENT / 8
const PAGES_PER_SEGMENT = BITS_PER_SEGMENT / BITS_PER_PAGE

class RemoteBitfieldPage {
  constructor(index, bitfield, segment) {
    this.index = index
    this.offset = index * BYTES_PER_PAGE - segment.offset
    this.bitfield = bitfield
    this.segment = segment

    segment.add(this)
  }

  get tree() {
    return this.segment.tree
  }

  get(index) {
    return quickbit.get(this.bitfield, index)
  }

  set(index, val) {
    if (quickbit.set(this.bitfield, index, val)) {
      this.tree.update(this.offset * 8 + index)
    }
  }

  setRange(start, end, val) {
    quickbit.fill(this.bitfield, val, start, end)

    let i = Math.floor(start / 128)
    const n = i + Math.ceil((end - start) / 128)

    while (i <= n) this.tree.update(this.offset * 8 + i++ * 128)
  }

  findFirst(val, position) {
    return quickbit.findFirst(this.bitfield, val, position)
  }

  findLast(val, position) {
    return quickbit.findLast(this.bitfield, val, position)
  }

  insert(start, bitfield) {
    this.bitfield.set(bitfield, start / 32)
    this.segment.refresh()
  }

  clear(start, bitfield) {
    quickbit.clear(this.bitfield, { field: bitfield, offset: start })
  }
}

class RemoteBitfieldSegment {
  constructor(index) {
    this.index = index
    this.offset = index * BYTES_PER_SEGMENT
    this.tree = quickbit.Index.from([], BYTES_PER_SEGMENT)
    this.pages = new Array(PAGES_PER_SEGMENT)
    this.pagesLength = 0
  }

  get chunks() {
    return this.tree.chunks
  }

  refresh() {
    this.tree = quickbit.Index.from(this.tree.chunks, BYTES_PER_SEGMENT)
  }

  add(page) {
    const pageIndex = page.index - this.index * PAGES_PER_SEGMENT
    if (pageIndex >= this.pagesLength) this.pagesLength = pageIndex + 1

    this.pages[pageIndex] = page

    const chunk = { field: page.bitfield, offset: page.offset }

    this.chunks.push(chunk)

    for (let i = this.chunks.length - 2; i >= 0; i--) {
      const prev = this.chunks[i]
      if (prev.offset <= chunk.offset) break
      this.chunks[i] = chunk
      this.chunks[i + 1] = prev
    }
  }

  findFirst(val, position) {
    position = this.tree.skipFirst(!val, position)

    let j = position & (BITS_PER_PAGE - 1)
    let i = (position - j) / BITS_PER_PAGE

    if (i >= PAGES_PER_SEGMENT) return -1

    while (i < this.pagesLength) {
      const p = this.pages[i]

      let index = -1

      if (p) index = p.findFirst(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_PAGE + index

      j = 0
      i++
    }

    return val || this.pagesLength === PAGES_PER_SEGMENT ? -1 : this.pagesLength * BITS_PER_PAGE
  }

  findLast(val, position) {
    position = this.tree.skipLast(!val, position)

    let j = position & (BITS_PER_PAGE - 1)
    let i = (position - j) / BITS_PER_PAGE

    if (i >= PAGES_PER_SEGMENT) return -1

    while (i >= 0) {
      const p = this.pages[i]

      let index = -1

      if (p) index = p.findLast(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_PAGE + index

      j = BITS_PER_PAGE - 1
      i--
    }

    return -1
  }
}

module.exports = class RemoteBitfield {
  static BITS_PER_PAGE = BITS_PER_PAGE
  static BITS_PER_SEGMENT = BITS_PER_SEGMENT

  constructor() {
    this._pages = new BigSparseArray()
    this._segments = new BigSparseArray()
    this._maxSegments = 0
  }

  getBitfield(index) {
    const j = index & (BITS_PER_PAGE - 1)
    const i = (index - j) / BITS_PER_PAGE

    const p = this._pages.get(i)
    return p || null
  }

  get(index) {
    const j = index & (BITS_PER_PAGE - 1)
    const i = (index - j) / BITS_PER_PAGE

    const p = this._pages.get(i)

    return p ? p.get(j) : false
  }

  set(index, val) {
    const j = index & (BITS_PER_PAGE - 1)
    const i = (index - j) / BITS_PER_PAGE

    let p = this._pages.get(i)

    if (!p && val) {
      const k = Math.floor(i / PAGES_PER_SEGMENT)
      const s = this._segments.get(k) || this._segments.set(k, new RemoteBitfieldSegment(k))
      if (this._maxSegments <= k) this._maxSegments = k + 1

      p = this._pages.set(i, new RemoteBitfieldPage(i, new Uint32Array(WORDS_PER_PAGE), s))
    }

    if (p) p.set(j, val)
  }

  setRange(start, end, val) {
    let j = start & (BITS_PER_PAGE - 1)
    let i = (start - j) / BITS_PER_PAGE

    while (start < end) {
      let p = this._pages.get(i)

      if (!p && val) {
        const k = Math.floor(i / PAGES_PER_SEGMENT)
        const s = this._segments.get(k) || this._segments.set(k, new RemoteBitfieldSegment(k))
        if (this._maxSegments <= k) this._maxSegments = k + 1

        p = this._pages.set(i, new RemoteBitfieldPage(i, new Uint32Array(WORDS_PER_PAGE), s))
      }

      const offset = i * BITS_PER_PAGE
      const last = Math.min(end - offset, BITS_PER_PAGE)
      const range = last - j

      if (p) p.setRange(j, last, val)

      j = 0
      i++
      start += range
    }
  }

  findFirst(val, position) {
    let j = position & (BITS_PER_SEGMENT - 1)
    let i = (position - j) / BITS_PER_SEGMENT

    while (i < this._maxSegments) {
      const s = this._segments.get(i)

      let index = -1

      if (s) index = s.findFirst(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_SEGMENT + index

      j = 0
      i++
    }

    // For the val === false case, we always return at least
    // the 'position', also if nothing was found
    return val ? -1 : Math.max(position, this._maxSegments * BITS_PER_SEGMENT)
  }

  firstSet(position) {
    return this.findFirst(true, position)
  }

  firstUnset(position) {
    return this.findFirst(false, position)
  }

  findLast(val, position) {
    let j = position & (BITS_PER_SEGMENT - 1)
    let i = (position - j) / BITS_PER_SEGMENT

    while (i >= 0) {
      const s = this._segments.get(i)

      let index = -1

      if (s) index = s.findLast(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_SEGMENT + index

      j = BITS_PER_SEGMENT - 1
      i--
    }

    return -1
  }

  lastSet(position) {
    return this.findLast(true, position)
  }

  lastUnset(position) {
    return this.findLast(false, position)
  }

  insert(start, bitfield) {
    if (start % 32 !== 0) return false

    let length = bitfield.byteLength * 8

    let j = start & (BITS_PER_PAGE - 1)
    let i = (start - j) / BITS_PER_PAGE

    while (length > 0) {
      let p = this._pages.get(i)

      if (!p) {
        const k = Math.floor(i / PAGES_PER_SEGMENT)
        const s = this._segments.get(k) || this._segments.set(k, new RemoteBitfieldSegment(k))
        if (this._maxSegments <= k) this._maxSegments = k + 1

        p = this._pages.set(i, new RemoteBitfieldPage(i, new Uint32Array(WORDS_PER_PAGE), s))
      }

      const end = Math.min(j + length, BITS_PER_PAGE)
      const range = end - j

      p.insert(j, bitfield.subarray(0, range / 32))

      bitfield = bitfield.subarray(range / 32)

      j = 0
      i++
      length -= range
    }

    return true
  }

  clear(start, bitfield) {
    if (start % 32 !== 0) return false

    let length = bitfield.byteLength * 8

    let j = start & (BITS_PER_PAGE - 1)
    let i = (start - j) / BITS_PER_PAGE

    while (length > 0) {
      let p = this._pages.get(i)

      if (!p) {
        const k = Math.floor(i / PAGES_PER_SEGMENT)
        const s = this._segments.get(k) || this._segments.set(k, new RemoteBitfieldSegment(k))
        if (this._maxSegments <= k) this._maxSegments = k + 1

        p = this._pages.set(i, new RemoteBitfieldPage(i, new Uint32Array(WORDS_PER_PAGE), s))
      }

      const end = Math.min(j + length, BITS_PER_PAGE)
      const range = end - j

      p.clear(j, bitfield.subarray(0, range / 32))

      bitfield = bitfield.subarray(range / 32)

      j = 0
      i++
      length -= range
    }

    return true
  }
}
/* DEV DOCS
  Every hypercore has one Replicator object managing its connections to other peers.
  There is one Peer object per peer connected to the Hypercore.
  Hypercores do not know about other hypercores, so when a peer is connected to multiple cores, there exists one Peer object per core.

  Hypercore indicates block should be downloaded through methods like Replicator.addRange or Replicator.addBlock
  Hypercore calls Replicator.updateActivity every time a hypercore session opens/closes
  Replicator.updateActivity ensures the Hypercore is downloading blocks as expected
  Replicator keeps track of:
    - Which blocks need to be downloaded (Replicator._blocks)
    - Which blocks currently have inflight requests (Replicator._inflight)

  Blocks are requested from remote peers by Peer objects. The flow is:
    - The replicator's updatePeer method gets called
    - The replicator detects whether the Peer can accept more requests (for example by checking if it's maxed out on inflight blocks)
    - The replicator then tells the Peer what to request (e.g. Peer_requestRange or Peer._requestBlock methods)

  The Peer object is responsible for tracking
    - Which blocks does the Peer have available (tracked in remoteBitfield)
    - Which blocks are you actively looking for from this peer (tracked in missingBlocks)
    - How many blocks are currently inflight (tracked in inflight)
  The Peer uses this information to decide which blocks to request from the peer in response to _requestRange requests and the like.
*/

const b4a = require('b4a')
const safetyCatch = require('safety-catch')
const RandomIterator = require('random-array-iterator')
const flatTree = require('flat-tree')
const Mutex = require('./mutex')
const ReceiverQueue = require('./receiver-queue')
const HotswapQueue = require('./hotswap-queue')
const RemoteBitfield = require('./remote-bitfield')
const { MerkleTree } = require('./merkle-tree')
const w = require('./wants')
const { LocalWants, RemoteWants } = w
const {
  REQUEST_CANCELLED,
  REQUEST_TIMEOUT,
  INVALID_CAPABILITY,
  SNAPSHOT_NOT_AVAILABLE,
  ASSERTION
} = require('hypercore-errors')
const m = require('./messages')
const caps = require('./caps')

const DEFAULT_MAX_INFLIGHT = [16, 512]
const SCALE_LATENCY = 50
const NOT_DOWNLOADING_SLACK = (20000 + Math.random() * 20000) | 0
const MAX_PEERS_UPGRADE = 3
const LAST_BLOCKS = 256
const MAX_RANGES = 64
const MIN_PEER_UPDATE_ALL = 40

const NOT_AVAILABLE = 1
const INVALID_REQUEST = 2
const MAX_INVALID_REQUESTS = 64
const MAX_BACKOFFS = MAX_INVALID_REQUESTS / 2

const PRIORITY = {
  NORMAL: 0,
  HIGH: 1,
  VERY_HIGH: 2,
  CANCELLED: 255 // reserved to mark cancellation
}

class Attachable {
  constructor(replicator) {
    this.replicator = replicator
    this.resolved = false
    this.processing = false
    this.refs = []
    this.wants = null
  }

  addWant(w) {
    if (this.wants === null) this.wants = new Set()
    this.wants.add(w)
  }

  removeWant(w) {
    if (this.wants === null) return
    this.wants.delete(w)
  }

  attach(session) {
    const r = {
      context: this,
      session,
      sindex: 0,
      rindex: 0,
      snapshot: true,
      resolve: null,
      reject: null,
      promise: null,
      timeout: null
    }

    r.sindex = session.push(r) - 1
    r.rindex = this.refs.push(r) - 1
    r.promise = new Promise((resolve, reject) => {
      r.resolve = resolve
      r.reject = reject
    })

    return r
  }

  detach(r, err = null) {
    if (r.context !== this) return false

    this._detach(r)
    this._cancel(r, err)
    this.gc()

    return true
  }

  _detach(r) {
    const rh = this.refs.pop()
    const sh = r.session.pop()

    if (r.rindex < this.refs.length) this.refs[(rh.rindex = r.rindex)] = rh
    if (r.sindex < r.session.length) r.session[(sh.sindex = r.sindex)] = sh

    destroyRequestTimeout(r)
    r.context = null

    return r
  }

  gc() {
    if (this.refs.length > 0 || this.processing) return
    this._unref()

    if (this.wants === null) return

    const wants = this.wants
    this.wants = null

    let update = null

    for (const w of wants) {
      if (w.any) {
        const removed = w.wants.removeAnyRange(w.start, w.length, this)
        if (!removed) continue
        if (update === null) update = new Set()
        update.add(w.wants.peer)
        // TODO: should also use a free list for simplicity
        w.wants.peer.wireUnwant.send(removed)
        continue
      }

      if (w.wants.removeBatch(w.start, this)) {
        if (update === null) update = new Set()
        update.add(w.wants.peer)
      }
    }

    if (update === null) return
    for (const peer of update) {
      this.replicator.updatePeer(peer)
    }
  }

  processed() {
    this.processing = false
    this.gc()
  }

  _cancel(r, err) {
    r.reject(err || REQUEST_CANCELLED())
  }

  _unref() {
    // overwrite me
  }

  resolve(val) {
    this.resolved = true
    while (this.refs.length > 0) {
      this._detach(this.refs[this.refs.length - 1]).resolve(val)
    }
    this.gc()
  }

  reject(err) {
    this.resolved = true
    while (this.refs.length > 0) {
      this._detach(this.refs[this.refs.length - 1]).reject(err)
    }
    this.gc()
  }

  setTimeout(r, ms) {
    destroyRequestTimeout(r)
    r.timeout = setTimeout(onrequesttimeout, ms, r)
  }
}

class BlockRequest extends Attachable {
  constructor(replicator, tracker, index, priority, force) {
    super(replicator)

    this.index = index
    this.priority = priority
    this.inflight = []
    this.queued = false
    this.hotswap = null
    this.tracker = tracker
    this.force = force
  }

  _unref() {
    if (this.resolved) return
    this.queued = false

    for (const req of this.inflight) {
      req.peer._cancelRequest(req)
    }

    this.tracker.remove(this.index)
    removeHotswap(this)
  }
}

class RangeBatchRequest extends Attachable {
  constructor(replicator, batch) {
    super(replicator)

    this.batch = batch
    this.index = 0
  }
}

class RangeRequest extends Attachable {
  constructor(replicator, ranges, start, end, linear, blocks) {
    super(replicator)

    this.start = start
    this.end = end
    this.linear = linear
    this.blocks = blocks
    this.ranges = ranges
    this.batches = []

    ranges.push(this)

    if (this.end === -1) {
      this.replicator._alwaysLatestBlock++
    }

    // As passed by the user, immut
    this.userStart = start
    this.userEnd = end
  }

  addBatch(batch) {
    for (let i = 0; i < this.batches.length; i++) {
      const b = this.batches[i]
      if (b.batch === batch) return false
    }
    const b = new RangeBatchRequest(this.replicator, batch)
    b.index = this.batches.length
    this.batches.push(b)
    return true
  }

  removeBatch(batch) {
    const head = this.batches.pop()

    if (head !== batch) {
      head.index = batch.index
      this.batches[head.index] = head
    }

    batch.gc()
  }

  _unref() {
    const rangeIndex = this.ranges.indexOf(this)
    if (rangeIndex === -1) return

    const h = this.ranges.pop()
    if (h !== this) {
      this.ranges[rangeIndex] = h
    }

    if (this.end === -1) {
      this.replicator._alwaysLatestBlock--
    }

    while (this.batches.length) {
      this.batches.pop().gc()
    }
  }

  _cancel(r) {
    r.resolve(false)
  }
}

class UpgradeRequest extends Attachable {
  constructor(replicator, fork, length) {
    super(replicator)

    this.fork = fork
    this.length = length
    this.inflight = []
  }

  _unref() {
    if (this.resolved) return
    if (this.replicator.eagerUpgrade === true || this.inflight.length > 0) return
    this.replicator._upgrade = null
  }

  _cancel(r) {
    r.resolve(false)
  }
}

class SeekRequest extends Attachable {
  constructor(replicator, seeks, seeker) {
    super(replicator)

    this.seeker = seeker
    this.inflight = []
    this.seeks = seeks
  }

  _unref() {
    if (this.resolved) return
    if (this.inflight.length > 0) return
    const i = this.seeks.indexOf(this)
    if (i === -1) return
    const h = this.seeks.pop()
    if (i < this.seeks.length) this.seeks[i] = h
  }
}

class ForkRequest extends Attachable {
  constructor(replicator, fork) {
    super(replicator)
    this.fork = fork
    this.inflight = []
    this.batch = null
  }
}

class InflightTracker {
  constructor() {
    this._requests = []
    this._free = []
    this._active = 0
  }

  get idle() {
    return this._active === 0
  }

  *[Symbol.iterator]() {
    for (const req of this._requests) {
      if (req !== null) yield req
    }
  }

  add(req) {
    const id = this._free.length ? this._free.pop() : this._requests.push(null)
    req.id = id
    this._requests[id - 1] = req
    this._active++
    return req
  }

  get(id) {
    return id <= this._requests.length ? this._requests[id - 1] : null
  }

  remove(id, roundtrip) {
    if (id > this._requests.length) return
    if (this._requests[id - 1]) this._active--
    this._requests[id - 1] = null
    if (roundtrip === true) this._free.push(id)
  }

  reusable(id) {
    this._free.push(id)
  }
}

class BlockTracker {
  constructor(replicator) {
    this._replicator = replicator
    this._map = new Map()
  }

  [Symbol.iterator]() {
    return this._map.values()
  }

  isEmpty() {
    return this._map.size === 0
  }

  has(index) {
    return this._map.has(index)
  }

  get(index) {
    return this._map.get(index) || null
  }

  add(index, priority, force) {
    let b = this._map.get(index)
    if (b) return b

    b = new BlockRequest(this._replicator, this, index, priority, force)
    this._map.set(index, b)

    return b
  }

  remove(index) {
    const b = this.get(index)
    this._map.delete(index)
    return b
  }
}

class RoundtripQueue {
  constructor() {
    this.queue = []
    this.tick = 0
  }

  clear() {
    const ids = new Array(this.queue.length)
    for (let i = 0; i < ids.length; i++) {
      ids[i] = this.queue[i][1]
    }

    this.queue = []

    return ids
  }

  add(id) {
    this.queue.push([++this.tick, id])
  }

  flush(tick) {
    let flushed = null

    for (let i = 0; i < this.queue.length; i++) {
      if (this.queue[i][0] > tick) break
      if (flushed === null) flushed = []
      flushed.push(this.queue[i][1])
    }

    if (flushed !== null) this.queue.splice(0, flushed.length)
    return flushed
  }
}

class ProofRequest {
  constructor(msg, proof, block, manifest) {
    this.msg = msg
    this.proof = proof
    this.block = block
    this.manifest = manifest
  }

  async fulfill() {
    if (this.proof === null) return null

    const [proof, block] = await Promise.all([this.proof.settle(), this.block])

    if (this.manifest) proof.manifest = this.manifest
    if (!block && proof.block) return null

    if (block) proof.block.value = block
    return proof
  }
}

class Peer {
  constructor(replicator, protomux, channel, inflightRange) {
    this.core = replicator.core
    this.replicator = replicator
    this.stream = protomux.stream
    this.protomux = protomux
    this.remotePublicKey = this.stream.remotePublicKey
    this.remoteSupportsSeeks = false
    this.inflightRange = inflightRange
    this.fullyDownloadedSignaled = 0

    this.paused = false
    this.removed = false

    this.channel = channel
    this.channel.userData = this

    this.wireSync = this.channel.messages[0]
    this.wireRequest = this.channel.messages[1]
    this.wireCancel = this.channel.messages[2]
    this.wireData = this.channel.messages[3]
    this.wireNoData = this.channel.messages[4]
    this.wireWant = this.channel.messages[5]
    this.wireUnwant = this.channel.messages[6]
    this.wireBitfield = this.channel.messages[7]
    this.wireRange = this.channel.messages[8]
    this.wireExtension = this.channel.messages[9]

    // Same stats as replicator, but for this specific peer
    this.stats = {
      wireSync: { tx: 0, rx: 0 },
      wireRequest: { tx: 0, rx: 0 },
      wireCancel: { tx: 0, rx: 0 },
      wireData: { tx: 0, rx: 0 },
      wireWant: { tx: 0, rx: 0 },
      wireUnwant: { tx: 0, rx: 0 },
      wireBitfield: { tx: 0, rx: 0 },
      wireRange: { tx: 0, rx: 0 },
      wireExtension: { tx: 0, rx: 0 },
      hotswaps: 0,
      invalidData: 0,
      invalidRequests: 0,
      backoffs: 0,
      notAvailableBackoffs: 0
    }

    this.receiverQueue = new ReceiverQueue()
    this.receiverBusy = false

    // most often not used, so made on demand
    this.roundtripQueue = null

    this.inflight = 0
    this.dataProcessing = 0

    this.canUpgrade = true

    this.needsSync = false
    this.syncsProcessing = 0
    this.lastUpgradableLength = 0
    this.lastUpgradableFork = 0

    this._remoteContiguousLength = 0

    // TODO: tweak pipelining so that data sent BEFORE remoteOpened is not cap verified!
    // we might wanna tweak that with some crypto, ie use the cap to encrypt it...
    // or just be aware of that, to only push non leaky data

    this.remoteOpened = false
    this.remoteBitfield = new RemoteBitfield()
    this.missingBlocks = new RemoteBitfield()

    this.pushedLength = 0

    this.remoteFork = 0
    this.remoteLength = 0
    this.remoteCanUpgrade = false
    this.remoteUploading = true
    this.remoteDownloading = true
    this.remoteSynced = false
    this.remoteHasManifest = false
    this.remoteAllowPush = false
    this.remoteRequests = new Map()

    this.segmentsWanted = new Set()
    this.broadcastedNonSparse = false

    this.wants = new LocalWants(this)
    this.remoteWants = new RemoteWants(this)

    this.lengthAcked = 0

    this.extensions = new Map()
    this.lastExtensionSent = ''
    this.lastExtensionRecv = ''

    replicator._ifAvailable++
    replicator._active++
  }

  get remoteContiguousLength() {
    return this.remoteBitfield.findFirst(false, this._remoteContiguousLength)
  }

  getMaxInflight() {
    const stream = this.stream.rawStream
    if (!stream.udx) return Math.min(this.inflightRange[1], this.inflightRange[0] * 3)

    const scale =
      stream.rtt <= SCALE_LATENCY
        ? 1
        : (stream.rtt / SCALE_LATENCY) * Math.min(1, 2 / this.replicator.peers.length)
    return Math.max(
      this.inflightRange[0],
      Math.round(Math.min(this.inflightRange[1], this.inflightRange[0] * scale))
    )
  }

  getMaxHotswapInflight() {
    const inf = this.getMaxInflight()
    return Math.max(16, inf / 2)
  }

  signalUpgrade() {
    if (this._shouldUpdateCanUpgrade() === true) this._updateCanUpgradeAndSync()
    else this.sendSync()
  }

  _markInflight(index) {
    this.missingBlocks.set(index, false)
  }

  broadcastRange(start, length, drop) {
    if (!this.isActive()) return

    if (drop) this._unclearLocalRange(start, length)
    else this._clearLocalRange(start, length)

    const fullyContig = this.core.header.hints.contiguousLength === this.core.state.length

    if (start + LAST_BLOCKS < this.core.state.length && !drop && !fullyContig) {
      if (!this.remoteWants.hasRange(start, length)) return
    }

    let force = false
    if (fullyContig && !drop) {
      start = 0
      length = this.core.state.length

      // Always send the broadcast when we switch from sparse to fully contiguous, so remote knows too
      if (this.fullyDownloadedSignaled < length) {
        this.fullyDownloadedSignaled = length
        force = true
      }
    }

    // TODO: consider also adding early-returns on the drop===true case
    if (!force && !drop) {
      // No need to broadcast if the remote already has this range

      if (this._remoteContiguousLength >= start + length) return

      if (length === 1) {
        if (this.remoteBitfield.get(start)) return
      } else {
        if (this.remoteBitfield.firstUnset(start) >= start + length) return
      }
    }

    this.wireRange.send({
      drop,
      start,
      length
    })
    incrementTx(this.stats.wireRange, this.replicator.stats.wireRange)
  }

  extension(name, message) {
    this.wireExtension.send({ name: name === this.lastExtensionSent ? '' : name, message })
    incrementTx(this.stats.wireExtension, this.replicator.stats.wireExtension)
    this.lastExtensionSent = name
  }

  onextension(message) {
    const name = message.name || this.lastExtensionRecv
    this.lastExtensionRecv = name
    const ext = this.extensions.get(name)
    if (ext) {
      ext._onmessage({ start: 0, end: message.message.byteLength, buffer: message.message }, this)
    }
  }

  sendSync() {
    // Skip syncs if in repair mode
    if (this.core._repairMode) return

    if (this.syncsProcessing !== 0) {
      this.needsSync = true
      return
    }

    if (this.core.state.fork !== this.remoteFork) {
      this.canUpgrade = false
    }

    this.needsSync = false

    this.wireSync.send({
      fork: this.core.state.fork,
      length: this.core.state.length,
      remoteLength: this.core.state.fork === this.remoteFork ? this.remoteLength : 0,
      canUpgrade: this.canUpgrade,
      uploading: true,
      downloading: this.replicator.isDownloading(),
      hasManifest: !!this.core.header.manifest && this.core.compat === false,
      allowPush: this.replicator.isAllowingPush()
    })
    incrementTx(this.stats.wireSync, this.replicator.stats.wireSync)
  }

  onopen({ seeks, capability }) {
    const expected = caps.replicate(
      this.stream.isInitiator === false,
      this.core.key,
      this.stream.handshakeHash
    )

    if (b4a.equals(capability, expected) !== true) {
      // TODO: change this to a rejection instead, less leakage
      throw INVALID_CAPABILITY('Remote sent an invalid replication capability')
    }

    if (this.remoteOpened === true) return
    this.remoteOpened = true
    this.remoteSupportsSeeks = seeks

    this.protomux.cork()

    this.sendSync()

    const contig = Math.min(this.core.state.length, this.core.header.hints.contiguousLength)
    if (contig > 0) {
      this.broadcastRange(0, contig, false)

      if (contig === this.core.state.length) {
        this.broadcastedNonSparse = true
      }
    }

    this.replicator._ifAvailable--
    this.replicator._addPeer(this)

    this.protomux.uncork()

    this.core.checkIfIdle()
  }

  onclose(isRemote) {
    // we might have signalled to the remote that we are done (ie not downloading) and the remote might agree on that
    // if that happens, the channel might be closed by the remote. if so just renegotiate it.
    // TODO: add a CLOSE_REASON to mux to we can make this cleaner...
    const reopen =
      isRemote === true &&
      this.remoteOpened === true &&
      this.remoteDownloading === false &&
      this.remoteUploading === true &&
      this.replicator.downloading === true

    if (this.remoteOpened === false) {
      this.replicator._ifAvailable--
      this.replicator.queueUpdateAll()
      return
    }

    this.remoteOpened = false
    this.removed = true
    this.remoteRequests.clear() // cancel all
    this.receiverQueue.clear()

    if (this.roundtripQueue !== null) {
      for (const id of this.roundtripQueue.clear()) this.replicator._inflight.reusable(id)
    }

    this.replicator._removePeer(this)

    if (reopen) {
      this.replicator._makePeer(this.protomux)
    }
  }

  closeIfIdle() {
    if (this.remoteDownloading === false && this.replicator.isDownloading() === false) {
      // idling, shut it down...
      this.channel.close()
      return true
    }

    return false
  }

  async onsync(msg) {
    const {
      fork,
      length,
      remoteLength,
      canUpgrade,
      uploading,
      downloading,
      hasManifest,
      allowPush
    } = msg

    const lengthChanged = length !== this.remoteLength
    const sameFork = fork === this.core.state.fork

    this.remoteSynced = true
    this.remoteFork = fork
    this.remoteLength = length
    this.remoteCanUpgrade = canUpgrade
    this.remoteUploading = uploading
    this.remoteDownloading = downloading
    this.remoteHasManifest = hasManifest
    this.remoteAllowPush = allowPush

    if (this.closeIfIdle()) return

    this.lengthAcked = sameFork ? remoteLength : 0
    this.syncsProcessing++

    this.replicator._updateFork(this)

    if (this.remoteLength > this.core.state.length && this.lengthAcked === this.core.state.length) {
      if (this.replicator._addUpgradeMaybe() !== null) this._update()
    }

    const upgrade =
      lengthChanged === false || sameFork === false
        ? this.canUpgrade && sameFork
        : await this._canUpgrade(length, fork)

    if (length === this.remoteLength && fork === this.core.state.fork) {
      this.canUpgrade = upgrade
      if (upgrade) {
        this.lastUpgradableFork = fork
        this.lastUpgradableLength = length
      }
    }

    if (--this.syncsProcessing !== 0) return // ie not latest

    if (
      this.needsSync === true ||
      (this.core.state.fork === this.remoteFork && this.core.state.length > this.remoteLength)
    ) {
      this.signalUpgrade()
    }

    this._update()
  }

  _shouldUpdateCanUpgrade() {
    return (
      this.core.state.fork === this.remoteFork &&
      this.core.state.length > this.remoteLength &&
      this.canUpgrade === false &&
      this.syncsProcessing === 0
    )
  }

  async _updateCanUpgradeAndSync() {
    const { length, fork } = this.core.state

    const remoteLength = this.remoteLength
    const remoteFork = this.remoteFork
    const canUpgrade = await this._canUpgrade(this.remoteLength, this.remoteFork)

    if (
      this.syncsProcessing > 0 ||
      length !== this.core.state.length ||
      fork !== this.core.state.fork
    ) {
      return
    }
    if (remoteLength !== this.remoteLength || remoteFork !== this.remoteFork) {
      return
    }
    if (canUpgrade === this.canUpgrade) {
      return
    }

    this.canUpgrade = canUpgrade
    if (canUpgrade) {
      this.lastUpgradableLength = this.remoteLength
      this.lastUpgradableFork = this.remoteFork
    }

    this.sendSync()
  }

  // Safe to call in the background - never fails
  async _canUpgrade(remoteLength, remoteFork) {
    if (remoteFork !== this.core.state.fork) return false

    if (remoteLength === 0) return true
    if (remoteLength >= this.core.state.length) return false

    try {
      // Rely on caching to make sure this is cheap...
      const canUpgrade = await MerkleTree.upgradeable(this.core.state, remoteLength)

      if (remoteFork !== this.core.state.fork) return false

      return canUpgrade
    } catch {
      return false
    }
  }

  async _getProof(batch, msg, pushing) {
    let block = null

    if (msg.block) {
      const index = msg.block.index

      if (!pushing && (msg.fork !== this.core.state.fork || !this.core.bitfield.get(index))) {
        return new ProofRequest(msg, null, null, null)
      }

      block = batch.getBlock(index)
      block.catch(noop)
    }

    const manifest = msg.manifest && !this.core.compat ? this.core.header.manifest : null

    try {
      const proof = await MerkleTree.proof(this.core.state, batch, msg)
      return new ProofRequest(msg, proof, block, manifest)
    } catch (err) {
      batch.destroy()

      this.replicator._oninvalidrequest(err, msg, this)

      if (this.stats.invalidRequests >= MAX_INVALID_REQUESTS) throw err

      await backoff(this.stats.invalidRequests)
      return null
    }
  }

  async onrequest(msg) {
    const size = this.remoteRequests.size
    this.remoteRequests.set(msg.id, msg)

    // if size didnt change -> id overwrite -> old one is deleted, cancel current and re-add
    if (size === this.remoteRequests.size) {
      this._cancel(msg.id)
      this.remoteRequests.set(msg.id, msg)
    }

    if (!this.protomux.drained || this.receiverQueue.length) {
      this.receiverQueue.push(msg)
      return
    }

    if (this.replicator.destroyed) return

    await this._handleRequest(msg)
  }

  oncancel(msg) {
    this._cancel(msg.request)
  }

  _cancel(id) {
    this.remoteRequests.delete(id)
    this.receiverQueue.delete(id)
  }

  ondrain() {
    return this._handleRequests()
  }

  async _handleRequests() {
    if (this.receiverBusy || this.replicator.destroyed) return
    this.receiverBusy = true
    this.protomux.cork()

    while (
      this.remoteOpened &&
      this.protomux.drained &&
      this.receiverQueue.length > 0 &&
      !this.removed
    ) {
      const msg = this.receiverQueue.shift()
      await this._handleRequest(msg)
    }

    this.protomux.uncork()
    this.receiverBusy = false
  }

  async push(index) {
    if (!this.remoteAllowPush) return
    if (!this.remoteDownloading) return
    if (this.core.state.length <= index) return
    if (this.core.state.fork !== this.remoteFork) return
    if (this.remoteBitfield.get(index)) return

    const msg = {
      id: 0,
      fork: this.core.state.fork,
      block: null,
      hash: null,
      seek: null,
      upgrade: null,
      manifest: this.remoteLength === 0,
      priority: 0
    }

    await this.replicator._txLock.lock()
    try {
      const remoteLength = Math.max(this.remoteLength, this.pushedLength)

      msg.block = {
        index,
        nodes: MerkleTree.maxMissingNodes(2 * index, remoteLength)
      }

      if (index >= remoteLength) {
        msg.upgrade = {
          start: remoteLength,
          length: this.core.state.length - remoteLength
        }
      }

      let req = null
      const batch = this.core.storage.read(this.core.state.fork)
      try {
        req = await this._getProof(batch, msg, true)
      } catch (err) {
        this.replicator._oninvalidrequest(err, msg, this)
        return
      }

      if (req === null) return
      batch.tryFlush()

      await this._fulfillRequest(req, true)
    } finally {
      this.replicator._txLock.unlock()
    }
  }

  async _handleRequest(msg) {
    const locked = !!msg.upgrade && this.remoteAllowPush

    if (locked) {
      // ensure contig push proofs
      await this.replicator._txLock.lock()
      const end = msg.upgrade.start + msg.upgrade.length

      if (this.pushedLength < end) {
        msg.upgrade.start = this.pushedLength
        msg.upgrade.length = end - this.pushedLength
      }
    }

    try {
      const batch = this.core.storage.read(this.core.state.fork)

      // TODO: could still be answerable if (index, fork) is an ancestor of the current fork
      const req =
        msg.fork === this.core.state.fork
          ? await this._getProof(batch, msg, false)
          : new ProofRequest(msg, null, null, null)

      if (req === null) {
        this.wireNoData.send({ request: msg.id, reason: INVALID_REQUEST })
        return
      }

      batch.tryFlush()

      await this._fulfillRequest(req, false)
    } finally {
      if (locked) this.replicator._txLock.unlock()
    }
  }

  async _fulfillRequest(req, pushing) {
    if (this.core._repairMode) {
      // if cancelled do not reply
      if (this.remoteRequests.get(req.msg.id) !== req.msg) {
        return
      }

      // sync from now on, so safe to delete from the map
      this.remoteRequests.delete(req.msg.id)

      // If cutting off the fulfillment, ensure promise is caught.
      // While repairing merkle tree nodes can be `nil` so can throw.
      req.fulfill().catch(safetyCatch)
      return
    }

    const proof = await req.fulfill()

    if (!pushing) {
      // if cancelled do not reply
      if (this.remoteRequests.get(req.msg.id) !== req.msg) {
        return
      }

      // sync from now on, so safe to delete from the map
      this.remoteRequests.delete(req.msg.id)
    } else if (!this.remoteAllowPush) {
      // if pushing but remote disabled it, just drop it
      return
    }

    if (!this.isActive() && proof.block !== null) {
      return
    }

    if (proof === null) {
      if (req.msg.manifest && this.core.header.manifest) {
        const manifest = this.core.header.manifest
        this.wireData.send({
          request: req.msg.id,
          fork: this.core.state.fork,
          block: null,
          hash: null,
          seek: null,
          upgrade: null,
          manifest
        })
        incrementTx(this.stats.wireData, this.replicator.stats.wireData)
        return
      }

      this.wireNoData.send({ request: req.msg.id, reason: NOT_AVAILABLE })
      return
    }

    if (proof.block !== null) {
      this.replicator._onupload(proof.block.index, proof.block.value.byteLength, this)
    }

    if (proof.upgrade) {
      const remoteLength = MerkleTree.upgradeLength(proof.upgrade)
      if (remoteLength > this.pushedLength) this.pushedLength = remoteLength
    }

    this.wireData.send({
      request: req.msg.id,
      fork: req.msg.fork,
      block: proof.block,
      hash: proof.hash,
      seek: proof.seek,
      upgrade: proof.upgrade,
      manifest: proof.manifest
    })
    incrementTx(this.stats.wireData, this.replicator.stats.wireData)
  }

  _cancelRequest(req) {
    if (req.priority === PRIORITY.CANCELLED) return
    // mark as cancelled also and avoid re-entry
    req.priority = PRIORITY.CANCELLED

    this.inflight--
    this.replicator._requestDone(req.id, false)

    // clear inflight state
    if (isBlockRequest(req)) this.replicator._unmarkInflight(req.block.index)
    if (isUpgradeRequest(req)) this.replicator._clearInflightUpgrade(req)

    if (this.roundtripQueue === null) this.roundtripQueue = new RoundtripQueue()
    this.roundtripQueue.add(req.id)
    this.wireCancel.send({ request: req.id })
    incrementTx(this.stats.wireCancel, this.replicator.stats.wireCancel)
  }

  _checkIfConflict() {
    this.paused = true

    const length = Math.min(this.core.state.length, this.remoteLength)
    if (length === 0) return // pause and ignore

    this.wireRequest.send({
      id: 0, // TODO: use an more explicit id for this eventually...
      fork: this.remoteFork,
      block: null,
      hash: null,
      seek: null,
      upgrade: {
        start: 0,
        length
      }
    })

    incrementTx(this.stats.wireRequest, this.replicator.stats.wireRequest)
  }

  _unmarkInflightBlockRequest(req, data) {
    if (isBlockRequest(req)) this.replicator._unmarkInflight(req.block.index)
    else if (data.block && !req) this.replicator._unmarkInflight(data.block.index)
  }

  async ondata(data) {
    if (data.request !== 0 && !data.upgrade) return this._handleData(data)

    await this.replicator._rxLock.lock()
    try {
      await this._handleData(data)
    } finally {
      this.replicator._rxLock.unlock()
    }
  }

  async _handleData(data) {
    // always allow a fork conflict proof to be sent
    if (data.request === 0 && data.upgrade && data.upgrade.start === 0) {
      if (await this.core.checkConflict(data, this)) return
      this.paused = false
    }

    const req = data.request > 0 ? this.replicator._inflight.get(data.request) : null
    const reorg = data.fork > this.core.state.fork

    // no push atm, TODO: check if this satisfies another pending request
    // allow reorg pushes tho as those are not written to storage so we'll take all the help we can get
    if (req === null && reorg === false && !this.replicator.allowPush) {
      return
    }

    // Skip accepting data if in repair mode to avoid corruption
    if (this.core._repairMode) {
      this.replicator._onnodata(this, req, NOT_AVAILABLE)
      return
    }

    if (req === null && reorg === false && data.block) {
      // mark this as inflight to avoid parallel requests
      this.replicator._markInflight(data.block.index)
    }

    if (req !== null) {
      if (req.peer !== this) return
      this._onrequestroundtrip(req)
    }

    try {
      if (reorg === true) return await this.replicator._onreorgdata(this, req, data)
    } catch (err) {
      safetyCatch(err)
      this._unmarkInflightBlockRequest(req, data)

      this.paused = true
      this.replicator._oninvaliddata(err, req, data, this)
      return
    }

    this.dataProcessing++
    if (isBlockRequest(req)) this.replicator._markProcessing(req.block.index)

    try {
      if (!this.replicator._matchingRequest(req, data) || !(await this.core.verify(data, this))) {
        this.replicator._onnodata(this, req, 0)
        return
      }
    } catch (err) {
      safetyCatch(err)
      this._unmarkInflightBlockRequest(req, data)

      if (err.code === 'WRITE_FAILED') {
        // For example, we don't want to keep pulling data when storage is full
        // TODO: notify the user somehow
        this.paused = true
        return
      }

      if (this.core.closed && !isCriticalError(err)) return

      if (err.code !== 'INVALID_OPERATION') {
        // might be a fork, verify
        this._checkIfConflict()
      }

      // if push mode, we MIGHT get an occasional bad message
      // no need to mega bail for that. TODO: rate limit instead as a general thing
      if (!this.replicator.allowPush) {
        this.paused = true
      }

      this.replicator._onnodata(this, req, 0)
      this.replicator._oninvaliddata(err, req, data, this)
      return
    } finally {
      if (isBlockRequest(req)) this.replicator._markProcessed(req.block.index)
      this.dataProcessing--
    }

    this.replicator._ondata(this, req, data)

    if (this._shouldUpdateCanUpgrade() === true) {
      this._updateCanUpgradeAndSync()
    }
  }

  onnodata({ request, reason }) {
    const req = request > 0 ? this.replicator._inflight.get(request) : null

    if (req === null || req.peer !== this) {
      this.replicator.queueUpdateAll()
      return
    }

    this._onrequestroundtrip(req)
    this.replicator._onnodata(this, req, reason)
  }

  _onrequestroundtrip(req) {
    if (req.priority === PRIORITY.CANCELLED) return
    // to avoid re-entry we also just mark it as cancelled
    req.priority = PRIORITY.CANCELLED

    this.inflight--
    this.replicator._requestDone(req.id, true)
    if (this.roundtripQueue === null) return
    const flushed = this.roundtripQueue.flush(req.rt)
    if (flushed === null) return
    for (const id of flushed) this.replicator._inflight.reusable(id)
  }

  onwant(range) {
    if (!this.remoteWants.add(range)) return
    this.replicator._onwant(this, range.start, range.length, range.any)
  }

  onunwant(range) {
    this.remoteWants.remove(range)
  }

  onbitfield({ start, bitfield }) {
    if (start < this._remoteContiguousLength) this._remoteContiguousLength = start // bitfield is always the truth
    this.remoteBitfield.insert(start, bitfield)
    this.missingBlocks.insert(start, bitfield)
    this._clearLocalRange(start, bitfield.byteLength * 8)
    this._update()
  }

  _clearLocalRange(start, length) {
    const bitfield = this.core.skipBitfield === null ? this.core.bitfield : this.core.skipBitfield

    if (length === 1) {
      this.missingBlocks.set(start, this._remoteHasBlock(start) && !bitfield.get(start))
      return
    }

    const contig = Math.min(this.core.state.length, this.core.header.hints.contiguousLength)

    if (start + length < contig) {
      this.missingBlocks.setRange(start, contig, false)
      return
    }

    const rem = start & 32767
    if (rem > 0) {
      start -= rem
      length += rem
    }

    const end = start + Math.min(length, this.core.state.length)
    while (start < end) {
      const local = bitfield.getBitfield(start)

      if (local && local.bitfield) {
        this.missingBlocks.clear(start, local.bitfield)
      }

      start += 32768
    }
  }

  _resetMissingBlock(index) {
    const bitfield = this.core.skipBitfield === null ? this.core.bitfield : this.core.skipBitfield
    this.missingBlocks.set(index, this._remoteHasBlock(index) && !bitfield.get(index))
  }

  _unclearLocalRange(start, length) {
    if (length === 1) {
      this._resetMissingBlock(start)
      return
    }

    const rem = start & (RemoteBitfield.BITS_PER_SEGMENT - 1)
    if (rem > 0) {
      start -= rem
      length += rem
    }

    const fixedStart = start

    const end = start + Math.min(length, this.remoteLength)
    while (start < end) {
      const remote = this.remoteBitfield.getBitfield(start)
      if (remote && remote.bitfield) {
        this.missingBlocks.insert(start, remote.bitfield)
      }

      start += RemoteBitfield.BITS_PER_SEGMENT
    }

    this._clearLocalRange(fixedStart, length)
  }

  async onrange({ drop, start, length }) {
    const has = drop === false

    if (drop === true && start < this._remoteContiguousLength) {
      this._remoteContiguousLength = start
    }

    if (start === 0 && drop === false) {
      if (length > this._remoteContiguousLength) {
        this._remoteContiguousLength = length
        if (
          this.remoteFork === this.core.state.fork &&
          length > this.core.header.hints.remoteContiguousLength
        ) {
          this.core.updateRemoteContiguousLength(length)
        }
      }
    } else if (length === 1) {
      const bitfield = this.core.skipBitfield === null ? this.core.bitfield : this.core.skipBitfield
      this.remoteBitfield.set(start, has)
      this.missingBlocks.set(start, has && !bitfield.get(start))
    } else {
      const rangeStart = this.remoteBitfield.findFirst(!has, start)
      const rangeEnd = length + start

      if (rangeStart !== -1 && rangeStart < rangeEnd) {
        this.remoteBitfield.setRange(rangeStart, rangeEnd, has)
        this.missingBlocks.setRange(rangeStart, rangeEnd, has)
        if (has) this._clearLocalRange(rangeStart, rangeEnd - rangeStart)
      }
    }

    if (this.core.hintsChanged) await this.core.flushHints()
    if (drop === false) this._update()

    this.core.emitRemoteContiguousLength()
  }

  onreorghint() {
    // TODO
  }

  _update() {
    // TODO: if this is in a batch or similar it would be better to defer it
    // we could do that with nextTick/microtick mb? (combined with a property on the session to signal read buffer mb)
    this.replicator.updatePeer(this)
  }

  async _onconflict() {
    this.protomux.cork()
    if (this.remoteLength > 0 && this.core.state.fork === this.remoteFork) {
      await this.onrequest({
        id: 0,
        fork: this.core.state.fork,
        block: null,
        hash: null,
        seek: null,
        upgrade: {
          start: 0,
          length: Math.min(this.core.state.length, this.remoteLength)
        }
      })
    }
    this.channel.close()
    this.protomux.uncork()
  }

  _makeRequest(needsUpgrade, priority, minLength) {
    if (needsUpgrade === true && this.replicator._shouldUpgrade(this) === false) {
      return null
    }

    // ensure that the remote has signalled they have the length we request
    if (this.remoteLength < minLength) {
      return null
    }

    if (needsUpgrade === false && this.replicator._autoUpgrade(this) === true) {
      needsUpgrade = true
    }

    return {
      peer: this,
      rt: this.roundtripQueue === null ? 0 : this.roundtripQueue.tick,
      id: 0,
      fork: this.remoteFork,
      block: null,
      hash: null,
      seek: null,
      upgrade:
        needsUpgrade === false
          ? null
          : { start: this.core.state.length, length: this.remoteLength - this.core.state.length },
      // remote manifest check can be removed eventually...
      manifest: this.core.header.manifest === null && this.remoteHasManifest === true,
      priority,
      timestamp: Date.now(),
      elapsed: 0
    }
  }

  _requestManifest() {
    const req = this._makeRequest(false, 0, 0)
    if (req === null) return

    this._send(req)
  }

  _includeLastBlock() {
    if (this.replicator._alwaysLatestBlock === 0) return null

    const index = this.remoteLength - 1

    // only valid if its an OOB get
    if (index < this.core.state.length) return null

    // do the normal checks
    if (!this._remoteHasBlock(index)) return null
    if (!this._canRequest(index, false)) return null

    // atm we only ever do one upgrade request in parallel, if that changes
    // then we should add some check here for inflights to avoid over requesting
    const b = this.replicator._blocks.add(index, PRIORITY.NORMAL, false)
    return b
  }

  _requestUpgrade(u) {
    if (this.replicator.pushOnly) return false

    const req = this._makeRequest(true, 0, 0)
    if (req === null) return false

    const b = this._includeLastBlock()

    if (b) this._sendBlockRequest(req, b)
    else this._send(req)

    return true
  }

  _requestSeek(s) {
    // if replicator is updating the seeks etc, bail and wait for it to drain
    if (this.replicator._updatesPending > 0) return false
    if (this.replicator.pushOnly) return false

    const { length, fork } = this.core.state

    if (fork !== this.remoteFork) return false

    if (s.seeker.start >= length) {
      const req = this._makeRequest(true, 0, 0)

      // We need an upgrade for the seek, if non can be provided, skip
      if (req === null) return false

      req.seek = this.remoteSupportsSeeks
        ? { bytes: s.seeker.bytes, padding: s.seeker.padding }
        : null

      s.inflight.push(req)
      this._send(req)

      return true
    }

    const len = s.seeker.end - s.seeker.start
    const off = s.seeker.start + Math.floor(Math.random() * len)

    for (let i = 0; i < len; i++) {
      let index = off + i
      if (index > s.seeker.end) index -= len

      if (this._remoteHasBlock(index) === false) continue
      if (this.core.bitfield.get(index) === true) continue
      if (!this._canRequest(index, false)) continue

      // Check if this block is currently inflight - if so pick another
      const b = this.replicator._blocks.get(index)
      if (b !== null && b.inflight.length > 0) continue

      // Block is not inflight, but we only want the hash, check if that is inflight
      const h = this.replicator._hashes.add(index, PRIORITY.NORMAL, false)
      if (h.inflight.length > 0) continue

      const req = this._makeRequest(false, h.priority, index + 1)
      if (req === null) continue

      const nodes = flatTree.depth(s.seeker.start + s.seeker.end - 1)

      req.hash = { index: 2 * index, nodes }
      req.seek = this.remoteSupportsSeeks
        ? { bytes: s.seeker.bytes, padding: s.seeker.padding }
        : null

      s.inflight.push(req)
      h.inflight.push(req)
      this._send(req)

      return true
    }

    this._maybeWantAnyRange(s.seeker.start, len, s)
    return false
  }

  _canRequest(index, force) {
    if (!(index >= 0)) throw ASSERTION('bad index to _canRequest: ' + index)

    if (!force && this.replicator.pushOnly) {
      return false
    }

    if (this.remoteLength >= this.core.state.length) {
      return true
    }

    if (index < this.lastUpgradableLength && this.lastUpgradableFork === this.core.state.fork) {
      return true
    }

    if (this.canUpgrade && this.syncsProcessing === 0) {
      return true
    }

    return false
  }

  _remoteHasBlock(index) {
    return index < this._remoteContiguousLength || this.remoteBitfield.get(index) === true
  }

  _sendBlockRequest(req, b) {
    if (this.core._repairMode) return

    req.block = { index: b.index, nodes: 0 }
    this.replicator._markInflight(b.index)

    b.inflight.push(req)
    this.replicator.hotswaps.add(b)
    this._send(req)
  }

  _requestBlock(b) {
    const { length, fork } = this.core.state

    if (this._remoteHasBlock(b.index) === false || fork !== this.remoteFork) {
      if (!this.core.bitfield.get(b.index)) this._maybeWant(b.index, b)
      return false
    }

    if (!this._canRequest(b.index, b.force)) return false

    const req = this._makeRequest(b.index >= length, b.priority, b.index + 1)
    if (req === null) return false

    this._sendBlockRequest(req, b)

    return true
  }

  _maybeWant(index, handle) {
    if (index < this.remoteContiguousLength) return

    const res = this.wants.add(index, handle)
    if (!res) return

    const batch = res.want && res.unwant
    if (batch) this.protomux.cork()

    if (res.unwant) {
      this.wireUnwant.send(res.unwant)
      incrementTx(this.stats.wireUnwant, this.replicator.stats.wireUnwant)
    }
    if (res.want) {
      this.wireWant.send(res.want)
      incrementTx(this.stats.wireWant, this.replicator.stats.wireWant)
    }

    if (batch) this.protomux.uncork()
  }

  _maybeWantAnyRange(start, length, handle) {
    if (handle.wants) {
      for (const w of handle.wants) {
        if ((w.start !== start || w.length !== length) && w.any) {
          const req = this.wants.removeAnyRange(w.start, w.length, handle)
          if (req) this.wireUnwant.send(req)
        }
      }
    }

    if (start + length <= this.remoteContiguousLength) return

    const req = this.wants.addAnyRange(start, length, handle)
    if (req) this.wireWant.send(req)
  }

  _requestRangeBlock(index, length) {
    if (this.core.bitfield.get(index) === true || !this._canRequest(index, false)) return false

    const b = this.replicator._blocks.add(index, PRIORITY.NORMAL, false)
    if (b.inflight.length > 0) {
      this.missingBlocks.set(index, false) // in case we missed some states just set them ondemand, nbd
      return false
    }

    const req = this._makeRequest(index >= length, b.priority, index + 1)

    // If the request cannot be satisfied, dealloc the block request if no one is subscribed to it
    if (req === null) {
      b.gc()
      return false
    }

    this._sendBlockRequest(req, b)

    // Don't think this will ever happen, as the pending queue is drained before the range queue
    // but doesn't hurt to check this explicitly here also.
    if (b.queued) b.queued = false
    return true
  }

  _findNext(i) {
    if (i < this._remoteContiguousLength) {
      if (this.core.skipBitfield === null) this.replicator._openSkipBitfield()
      i = this.core.skipBitfield.findFirst(false, i)
      if (i < this._remoteContiguousLength && i > -1) return i
      i = this._remoteContiguousLength
    }

    return this.missingBlocks.findFirst(true, i)
  }

  _addRangeBatch(r, offset, end) {
    const { WANT_BATCH } = w
    while (offset < end) {
      const next = this.core.bitfield.findFirst(false, offset)
      if (next === -1 || next >= end) return false

      const b = (next - (next & (WANT_BATCH - 1))) / WANT_BATCH

      if (r.addBatch(b)) return true

      offset = (b + 1) * WANT_BATCH
    }

    return false
  }

  _populateRangeBatches(r) {
    const { WANT_BATCH } = w
    for (let i = r.batches.length - 1; i >= 0; i--) {
      const b = r.batches[i]
      const minStart = b.batch * WANT_BATCH
      const maxEnd = minStart + WANT_BATCH

      const start = Math.max(r.start, minStart)
      const end = Math.min(r.end === -1 ? maxEnd : r.end, maxEnd)

      if (start < end && this.core.bitfield.hasUnset(start, end - start)) continue

      r.removeBatch(b)
    }

    while (r.batches.length < 3) {
      const end = r.end === -1 ? this.core.state.length : r.end
      if (end <= r.start) return

      const len = end - r.start
      const off = r.start + (r.linear ? 0 : Math.floor(Math.random() * len))

      if (!this._addRangeBatch(r, off, end) && !this._addRangeBatch(r, r.start, end)) break
    }
  }

  _requestRangeBatch(start, end, length) {
    let tries = this.inflight

    do {
      start = this._findNext(start)
      if (start === -1 || start >= end) break

      if (this._requestRangeBlock(start, length)) return true
      start++
    } while (tries-- > 0)

    return false
  }

  _getValidEnd(maxEnd) {
    // if we can upgrade the remote, or the remote is ahead, then all the remotes blocks are valid
    // otherwise truncate to the last length the remote has acked for us
    const maxLocalLength =
      this.canUpgrade || this.remoteLength >= this.core.state.length
        ? this.core.state.length
        : this.core.state.fork === this.lastUpgradableFork
          ? Math.min(this.lastUpgradableLength, this.core.state.length)
          : 0

    return Math.min(
      maxLocalLength,
      Math.min(maxEnd === -1 ? this.remoteLength : maxEnd, this.remoteLength)
    )
  }

  _requestRange(r) {
    const { WANT_BATCH } = w
    if (this.syncsProcessing > 0) return false

    const { length, fork } = this.core.state

    if (r.blocks) {
      for (let i = r.start; i < r.end; i++) {
        const index = r.blocks[i]
        const has = index < this._remoteContiguousLength || this.missingBlocks.get(index) === true
        if (has === true && this._requestRangeBlock(index, length)) return true
        this._maybeWant(index, r)
      }

      return false
    }

    this._populateRangeBatches(r)

    const end = this._getValidEnd(r.end)

    if (end <= r.start || fork !== this.remoteFork) return false

    for (let i = 0; i < r.batches.length; i++) {
      const b = r.batches[i]

      const batchStart = Math.max(b.batch * WANT_BATCH, r.start)
      const batchEnd = Math.min((b.batch + 1) * WANT_BATCH, end)
      const len = batchEnd - batchStart
      const off = batchStart + (r.linear ? 0 : Math.floor(Math.random() * len))

      if (
        this._requestRangeBatch(off, end, length) ||
        this._requestRangeBatch(batchStart, off, length)
      ) {
        return true
      }

      this._maybeWant(batchStart, b)
    }

    // Here we should consider making an OOB request (ie if the remote says they have a newer block)
    // but the upgrade code already does that, so no big deal for now

    return false
  }

  _requestForkProof(f) {
    if (!this.remoteLength) return
    if (this.replicator.pushOnly) return

    const req = this._makeRequest(false, 0, 0)
    if (req === null) return

    req.upgrade = { start: 0, length: this.remoteLength }
    req.manifest = !this.core.header.manifest

    f.inflight.push(req)
    this._send(req)
  }

  _requestForkRange(f) {
    if (f.fork !== this.remoteFork || f.batch.want === null) return false
    if (this.replicator.pushOnly) return false

    const end = Math.min(f.batch.want.end, this.remoteLength)
    if (end < f.batch.want.start) return false

    const len = end - f.batch.want.start
    const off = f.batch.want.start + Math.floor(Math.random() * len)

    for (let i = 0; i < len; i++) {
      let index = off + i
      if (index >= end) index -= len

      if (this._remoteHasBlock(index) === false) continue

      const req = this._makeRequest(false, 0, 0)
      if (req === null) return false

      req.hash = { index: 2 * index, nodes: f.batch.want.nodes }

      f.inflight.push(req)
      this._send(req)

      return true
    }

    this._maybeWantAnyRange(f.batch.want.start, len, f)
    return false
  }

  isActive() {
    if (this.paused || this.removed || this.core.header.frozen) return false
    return true
  }

  async _send(req) {
    const fork = this.core.state.fork

    this.inflight++
    this.replicator._inflight.add(req)

    if (req.upgrade !== null && req.fork === fork) {
      const u = this.replicator._addUpgrade()
      u.inflight.push(req)
    }

    try {
      if (req.block !== null && req.fork === fork) {
        req.block.nodes = await MerkleTree.missingNodes(
          this.core.state,
          2 * req.block.index,
          this.core.state.length
        )
        if (req.priority === PRIORITY.CANCELLED) return
      }
      if (req.hash !== null && req.fork === fork && req.hash.nodes === 0) {
        req.hash.nodes = await MerkleTree.missingNodes(
          this.core.state,
          req.hash.index,
          this.core.state.length
        )
        if (req.priority === PRIORITY.CANCELLED) return

        // nodes === 0, we already have it, bail
        if (req.hash.nodes === 0 && (req.hash.index & 1) === 0) {
          this.inflight--
          this.replicator._resolveHashLocally(this, req)
          return
        }
      }
    } catch (err) {
      this.stream.destroy(err)
      return
    }

    this.wireRequest.send(req)
    incrementTx(this.stats.wireRequest, this.replicator.stats.wireRequest)
  }
}

module.exports = class Replicator {
  static Peer = Peer // hack to be able to access Peer from outside this module

  constructor(
    core,
    {
      notDownloadingLinger = NOT_DOWNLOADING_SLACK,
      eagerUpgrade = true,
      allowFork = true,
      allowPush = false,
      alwaysLatestBlock = false,
      inflightRange = null
    } = {}
  ) {
    this.core = core
    this.eagerUpgrade = eagerUpgrade
    this.allowFork = allowFork
    this.allowPush = allowPush
    this.ondownloading = null // optional external hook for monitoring downloading status
    this.peers = []
    this.findingPeers = 0 // updatable from the outside
    this.destroyed = false
    this.downloading = false
    this.pushOnly = false
    this.activeSessions = 0

    this.hotswaps = new HotswapQueue()
    this.inflightRange = inflightRange || DEFAULT_MAX_INFLIGHT

    // Note: nodata and unwant not currently tracked
    // tx = transmitted, rx = received
    this.stats = {
      wireSync: { tx: 0, rx: 0 },
      wireRequest: { tx: 0, rx: 0 },
      wireCancel: { tx: 0, rx: 0 },
      wireData: { tx: 0, rx: 0 },
      wireWant: { tx: 0, rx: 0 },
      wireUnwant: { tx: 0, rx: 0 },
      wireBitfield: { tx: 0, rx: 0 },
      wireRange: { tx: 0, rx: 0 },
      wireExtension: { tx: 0, rx: 0 },
      hotswaps: 0,
      invalidData: 0,
      invalidRequests: 0,
      backoffs: 0,
      notAvailableBackoffs: 0
    }

    this._attached = new Set()
    this._inflight = new InflightTracker()
    this._blocks = new BlockTracker(this)
    this._hashes = new BlockTracker(this)

    this._alwaysLatestBlock = alwaysLatestBlock ? 1 : 0
    this._queued = []

    this._seeks = []
    this._upgrade = null
    this._reorgs = []
    this._ranges = []

    this._rxLock = new Mutex()
    this._txLock = new Mutex()

    this._hadPeers = false
    this._active = 0
    this._ifAvailable = 0
    this._updatesPending = 0
    this._applyingReorg = null
    this._manifestPeer = null
    this._notDownloadingLinger = notDownloadingLinger
    this._notDownloadingTimer = null

    this._updateAllBump = null
    this._updateAllBound = this.updateAll.bind(this)

    const self = this
    this._onstreamclose = onstreamclose

    function onstreamclose() {
      self.detachFrom(this.userData)
    }
  }

  setInflightRange(min, max) {
    const def = this.inflightRange
    this.inflightRange = [min, max]
    for (const peer of this.peers) {
      if (peer.inflightRange !== def) continue
      peer.inflightRange = this.inflightRange
    }
  }

  updateActivity(inc, session) {
    this.activeSessions += inc
    this.setDownloading(this.activeSessions !== 0, session)
  }

  isDownloading() {
    return this.downloading || !this._inflight.idle
  }

  async push(index) {
    const all = []
    for (const peer of this.peers) {
      all.push(peer.push(index))
    }
    await Promise.all(all)
  }

  setAllowPush(allowPush) {
    if (allowPush === this.allowPush) return
    this.allowPush = allowPush
    for (const peer of this.peers) peer.sendSync()
  }

  isAllowingPush() {
    if (!this.allowPush) return false
    if (this._notDownloadingTimer) return false
    return this.downloading
  }

  setPushOnly(pushOnly) {
    if (pushOnly === this.pushOnly) return
    this.pushOnly = pushOnly
  }

  setDownloading(downloading) {
    const allowPush = this.isAllowingPush()
    const linger = this._notDownloadingLinger

    if (this._notDownloadingTimer) {
      clearTimeout(this._notDownloadingTimer)
      this._notDownloadingTimer = null
    }

    if (this.destroyed) return

    if (downloading || linger === 0) {
      if (!this._setDownloadingNow(downloading)) this.signalAllowPush(allowPush)
      return
    }

    this._notDownloadingTimer = setTimeout(setNotDownloadingLater, linger, this)
    if (this._notDownloadingTimer.unref) this._notDownloadingTimer.unref()
    this.signalAllowPush(allowPush)
  }

  signalAllowPush(allowPush) {
    if (allowPush === this.isAllowingPush()) return
    for (const peer of this.peers) peer.signalUpgrade()
  }

  _setDownloadingNow(downloading) {
    this._notDownloadingTimer = null

    if (this.downloading === downloading) return false
    this.downloading = downloading

    if (!downloading && this.isDownloading()) return false

    for (const peer of this.peers) peer.signalUpgrade()

    if (downloading) {
      // restart channel if needed...
      for (const protomux of this._attached) {
        if (!protomux.stream.handshakeHash) continue
        if (protomux.opened({ protocol: 'hypercore/alpha', id: this.core.discoveryKey })) continue
        this._makePeer(protomux, true)
      }
    } else {
      for (const peer of this.peers) peer.closeIfIdle()
    }

    if (this.ondownloading !== null && downloading) this.ondownloading()
    return true
  }

  cork() {
    for (const peer of this.peers) peer.protomux.cork()
  }

  uncork() {
    for (const peer of this.peers) peer.protomux.uncork()
  }

  // Called externally when a range of new blocks has been processed/removed
  onhave(start, length, drop = false) {
    for (const peer of this.peers) peer.broadcastRange(start, length, drop)
  }

  // Called externally when a truncation upgrade has been processed
  ontruncate(newLength, truncated) {
    const notify = []

    for (const blk of this._blocks) {
      if (blk.index < newLength) continue
      notify.push(blk)
    }

    for (const blk of notify) {
      for (const r of blk.refs) {
        if (r.snapshot === false) continue
        blk.detach(r, SNAPSHOT_NOT_AVAILABLE())
      }
    }

    for (const peer of this.peers) {
      peer.fullyDownloadedSignaled = Math.min(newLength, peer.fullyDownloadedSignaled)
      peer._unclearLocalRange(newLength, truncated)
    }
  }

  // Called externally when a upgrade has been processed
  onupgrade() {
    for (const peer of this.peers) peer.signalUpgrade()
    if (this._blocks.isEmpty() === false) this._resolveBlocksLocally()
    if (this._upgrade !== null) this._resolveUpgradeRequest(null)
    if (!this._blocks.isEmpty() || this._ranges.length !== 0 || this._seeks.length !== 0) {
      this._updateNonPrimary(true)
    }
  }

  // Called externally when a conflict has been detected and verified
  async onconflict() {
    const all = []
    for (const peer of this.peers) {
      all.push(peer._onconflict())
    }
    await Promise.allSettled(all)
  }

  async applyPendingReorg() {
    if (this._applyingReorg !== null) {
      await this._applyingReorg
      return true
    }

    for (let i = this._reorgs.length - 1; i >= 0; i--) {
      const f = this._reorgs[i]
      if (f.batch !== null && f.batch.finished) {
        await this._applyReorg(f)
        return true
      }
    }

    return false
  }

  addUpgrade(session) {
    if (this._upgrade !== null) {
      const ref = this._upgrade.attach(session)
      this._checkUpgradeIfAvailable()
      return ref
    }

    const ref = this._addUpgrade().attach(session)

    this.queueUpdateAll()

    return ref
  }

  addBlock(session, index, force) {
    const b = this._blocks.add(index, PRIORITY.HIGH, force)
    const ref = b.attach(session)

    this._queueBlock(b)
    this.queueUpdateAll()

    return ref
  }

  addSeek(session, seeker) {
    const s = new SeekRequest(this, this._seeks, seeker)
    const ref = s.attach(session)

    this._seeks.push(s)
    this.queueUpdateAll()

    return ref
  }

  addRange(
    session,
    { start = 0, end = -1, length = toLength(start, end), blocks = null, linear = false } = {}
  ) {
    if (blocks !== null) {
      // if using blocks, start, end just acts as frames around the blocks array
      start = 0
      end = length = blocks.length
    }

    const r = new RangeRequest(
      this,
      this._ranges,
      start,
      length === -1 ? -1 : start + length,
      linear,
      blocks
    )

    const ref = r.attach(session)

    // Trigger this to see if this is already resolved...
    // Also auto compresses the range based on local bitfield
    clampRange(this.core, r)

    if (r.end !== -1 && r.start >= r.end) {
      this._resolveRangeRequest(r)
      return ref
    }

    this.queueUpdateAll()

    return ref
  }

  cancel(ref) {
    ref.context.detach(ref, null)
  }

  static clearRequests(session, err) {
    if (session.length === 0) return
    if (session.length === 1 && session[0] === null) return

    const updated = new Set()

    while (session.length > 0) {
      const ref = session[session.length - 1]
      updated.add(ref.context.replicator)
      ref.context.detach(ref, err)
    }

    for (const replicator of updated) {
      replicator.queueUpdateAll()
    }
  }

  clearRequests(session, err = null) {
    let cleared = false
    while (session.length > 0) {
      const ref = session[session.length - 1]
      ref.context.detach(ref, err)
      cleared = true
    }

    if (cleared) this.queueUpdateAll()
  }

  _matchingRequest(req, data) {
    if (this.allowPush) {
      return true
    }
    if (data.block !== null && (req.block === null || req.block.index !== data.block.index)) {
      return false
    }
    if (data.hash !== null && (req.hash === null || req.hash.index !== data.hash.index)) {
      return false
    }
    if (data.seek !== null && (req.seek === null || req.seek.bytes !== data.seek.bytes)) {
      return false
    }
    if (data.upgrade !== null && req.upgrade === null) {
      return false
    }
    return req.fork === data.fork
  }

  _addUpgradeMaybe() {
    return this.eagerUpgrade === true ? this._addUpgrade() : this._upgrade
  }

  // TODO: this function is OVER called atm, at each updatePeer/updateAll
  // instead its more efficient to only call it when the conditions in here change - ie on sync/add/remove peer
  // Do this when we have more tests.
  _checkUpgradeIfAvailable() {
    if (this._ifAvailable > 0 && this.peers.length < MAX_PEERS_UPGRADE) return
    if (this._upgrade === null || this._upgrade.refs.length === 0) return
    if (this._hadPeers === false && this.findingPeers > 0) return

    const maxPeers = Math.min(this.peers.length, MAX_PEERS_UPGRADE)

    // check if a peer can upgrade us

    for (let i = 0; i < maxPeers; i++) {
      const peer = this.peers[i]

      if (peer.remoteSynced === false) return

      if (this.core.state.length === 0 && peer.remoteLength > 0) return

      if (peer.remoteLength <= this._upgrade.length || peer.remoteFork !== this._upgrade.fork) {
        continue
      }

      if (peer.syncsProcessing > 0) return

      if (peer.lengthAcked !== this.core.state.length && peer.remoteFork === this.core.state.fork) {
        return
      }

      if (peer.remoteCanUpgrade === true) return
    }

    // check if reorgs in progress...

    if (this._applyingReorg !== null) return

    // TODO: we prob should NOT wait for inflight reorgs here, seems better to just resolve the upgrade
    // and then apply the reorg on the next call in case it's slow - needs some testing in practice

    for (let i = 0; i < this._reorgs.length; i++) {
      const r = this._reorgs[i]
      if (r.inflight.length > 0) return
    }

    // if something is inflight, wait for that first
    if (this._upgrade.inflight.length > 0) return

    // nothing to do, indicate no update avail

    const u = this._upgrade
    this._upgrade = null
    u.resolve(false)
  }

  _addUpgrade() {
    if (this._upgrade !== null) return this._upgrade

    // TODO: needs a reorg: true/false flag to indicate if the user requested a reorg
    this._upgrade = new UpgradeRequest(this, this.core.state.fork, this.core.state.length)

    return this._upgrade
  }

  _addReorg(fork, peer) {
    if (this.allowFork === false) return null

    // TODO: eager gc old reorgs from the same peer
    // not super important because they'll get gc'ed when the request finishes
    // but just spam the remote can do ...

    for (const f of this._reorgs) {
      if (f.fork > fork && f.batch !== null) return null
      if (f.fork === fork) return f
    }

    const f = new ForkRequest(this, fork)

    this._reorgs.push(f)

    // maintain sorted by fork
    let i = this._reorgs.length - 1
    while (i > 0 && this._reorgs[i - 1].fork > fork) {
      this._reorgs[i] = this._reorgs[i - 1]
      this._reorgs[--i] = f
    }

    return f
  }

  _shouldUpgrade(peer) {
    if (this._upgrade !== null && this._upgrade.inflight.length > 0) return false
    return (
      peer.remoteCanUpgrade === true &&
      peer.remoteLength > this.core.state.length &&
      peer.lengthAcked === this.core.state.length
    )
  }

  _autoUpgrade(peer) {
    return (
      this._upgrade !== null &&
      peer.remoteFork === this.core.state.fork &&
      this._shouldUpgrade(peer)
    )
  }

  _addPeer(peer) {
    this._hadPeers = true
    this.peers.push(peer)
    this.updatePeer(peer)
    this._onpeerupdate(true, peer)
  }

  _requestDone(id, roundtrip) {
    this._inflight.remove(id, roundtrip)
    if (this.isDownloading() === true) return
    for (const peer of this.peers) peer.signalUpgrade()
  }

  _removePeer(peer) {
    this.peers.splice(this.peers.indexOf(peer), 1)
    peer.wants.destroy()

    if (this._manifestPeer === peer) this._manifestPeer = null

    let inflight = false
    for (const req of this._inflight) {
      if (req.peer !== peer) continue
      inflight = true
      this._inflight.remove(req.id, true)
      this._clearRequest(peer, req)
    }

    this._onpeerupdate(false, peer)
    if (inflight) {
      this.queueUpdateAll()
    } else {
      this._checkUpgradeIfAvailable()
    }
  }

  _queueBlock(b) {
    if (b.inflight.length > 0 || b.queued === true) return
    b.queued = true
    this._queued.push(b)
  }

  _resolveHashLocally(peer, req) {
    this._requestDone(req.id, false)
    this._resolveBlockRequest(this._hashes, req.hash.index / 2, null, req)
    this.updatePeer(peer)
  }

  // Runs in the background - not allowed to throw
  async _resolveBlocksLocally() {
    // TODO: check if fork compat etc. Requires that we pass down truncation info

    const clear = []
    const blocks = []

    const reader = this.core.storage.read()
    for (const b of this._blocks) {
      if (this.core.bitfield.get(b.index) === false) continue
      blocks.push(this._resolveLocalBlock(b, reader, clear))
    }
    reader.tryFlush()

    await Promise.all(blocks)

    if (!clear.length) return

    // Currently the block tracker does not support deletes during iteration, so we make
    // sure to clear them afterwards.
    for (const b of clear) {
      this._blocks.remove(b.index)
      removeHotswap(b)
    }
  }

  async _resolveLocalBlock(b, reader, resolved) {
    try {
      b.resolve(await reader.getBlock(b.index))
    } catch (err) {
      b.reject(err)
      return
    }

    resolved.push(b)
  }

  _resolveBlockRequest(tracker, index, value, req) {
    const b = tracker.remove(index)
    if (b === null) return false

    removeInflight(b.inflight, req)
    removeHotswap(b)
    b.queued = false

    b.resolve(value)

    if (b.inflight.length > 0) {
      // if anything is still inflight, cancel it
      for (let i = b.inflight.length - 1; i >= 0; i--) {
        const req = b.inflight[i]
        req.peer._cancelRequest(req)
      }
    }

    return true
  }

  _resolveUpgradeRequest(req) {
    if (req !== null) removeInflight(this._upgrade.inflight, req)

    if (
      this.core.state.length === this._upgrade.length &&
      this.core.state.fork === this._upgrade.fork
    ) {
      return false
    }

    const u = this._upgrade
    this._upgrade = null
    u.resolve(true)

    return true
  }

  _resolveRangeRequest(req) {
    req.resolve(true)
    req.gc()
  }

  _clearInflightBlock(tracker, req) {
    const isBlock = tracker === this._blocks
    const index = isBlock === true ? req.block.index : req.hash.index / 2
    const b = tracker.get(index)

    if (b === null || removeInflight(b.inflight, req) === false) return

    if (removeHotswap(b) === true && b.inflight.length > 0) {
      this.hotswaps.add(b)
    }

    if (b.refs.length > 0 && isBlock === true) {
      this._queueBlock(b)
      return
    }

    b.gc()
  }

  _clearInflightUpgrade(req) {
    if (this._upgrade === null || removeInflight(this._upgrade.inflight, req) === false) return
    this._upgrade.gc()
  }

  _clearInflightSeeks(req) {
    for (const s of this._seeks) {
      if (removeInflight(s.inflight, req) === false) continue
      s.gc()
    }
  }

  _clearInflightReorgs(req) {
    for (const r of this._reorgs) {
      removeInflight(r.inflight, req)
    }
  }

  _clearOldReorgs(fork) {
    for (let i = 0; i < this._reorgs.length; i++) {
      const f = this._reorgs[i]
      if (f.fork >= fork) continue
      if (i === this._reorgs.length - 1) this._reorgs.pop()
      else this._reorgs[i] = this._reorgs.pop()
      i--
    }
  }

  // "slow" updates here - async but not allowed to ever throw
  async _updateNonPrimary(updateAll) {
    // Check if running, if so skip it and the running one will issue another update for us (debounce)
    while (++this._updatesPending === 1) {
      let len = Math.min(MAX_RANGES, this._ranges.length)

      for (let i = 0; i < len; i++) {
        const r = this._ranges[i]

        clampRange(this.core, r)

        if (r.end !== -1 && r.start >= r.end) {
          this._resolveRangeRequest(r)
          i--
          if (len > this._ranges.length) len--
          if (this._ranges.length === MAX_RANGES) updateAll = true
        }
      }

      for (let i = 0; i < this._seeks.length; i++) {
        const s = this._seeks[i]

        let err = null
        let res = null

        try {
          res = await s.seeker.update()
        } catch (error) {
          err = error
        }

        if (!res && !err) continue

        if (i < this._seeks.length - 1) this._seeks[i] = this._seeks.pop()
        else this._seeks.pop()

        i--

        if (err) s.reject(err)
        else s.resolve(res)
      }

      // No additional updates scheduled - break
      if (--this._updatesPending === 0) break
      // Debounce the additional updates - continue
      this._updatesPending = 0
    }

    if (this._inflight.idle || updateAll) this.queueUpdateAll()
  }

  _clearRequest(peer, req) {
    if (req.block !== null) {
      this._clearInflightBlock(this._blocks, req)
      this._unmarkInflight(req.block.index)
    }

    if (req.hash !== null) {
      this._clearInflightBlock(this._hashes, req)
    }

    if (req.upgrade !== null && this._upgrade !== null) {
      this._clearInflightUpgrade(req)
    }

    if (this._seeks.length > 0) {
      this._clearInflightSeeks(req)
    }

    if (this._reorgs.length > 0) {
      this._clearInflightReorgs(req)
    }
  }

  _onnodata(peer, req, reason) {
    if (reason === NOT_AVAILABLE) {
      peer.stats.notAvailableBackoffs++
      this.stats.notAvailableBackoffs++

      if (peer.stats.notAvailableBackoffs >= MAX_BACKOFFS) {
        peer.paused = true
      }
    }

    if (reason === INVALID_REQUEST) {
      peer.stats.backoffs++
      this.stats.backoffs++

      if (peer.stats.backoffs >= MAX_BACKOFFS) {
        peer.paused = true
      }
    }

    if (req) {
      this._clearRequest(peer, req)
    }

    this.queueUpdateAll()
  }

  _openSkipBitfield() {
    // technically the skip bitfield gets bits cleared if .clear() is called
    // also which might be in inflight also, but that just results in that section being overcalled shortly
    // worst case, so ok for now

    const bitfield = this.core.openSkipBitfield()

    for (const req of this._inflight) {
      if (req.block) bitfield.set(req.block.index, true) // skip
    }
  }

  _markProcessing(index) {
    const b = this._blocks.get(index)
    if (b) {
      b.processing = true
      return
    }

    const h = this._hashes.get(index)
    if (h) h.processing = true
  }

  _markProcessed(index) {
    const b = this._blocks.get(index)
    if (b) return b.processed()

    const h = this._hashes.get(index)
    if (h) h.processed()
  }

  _markInflight(index) {
    if (this.core.skipBitfield !== null) this.core.skipBitfield.set(index, true)
    for (const peer of this.peers) peer._markInflight(index)
  }

  _unmarkInflight(index) {
    if (this.core.skipBitfield !== null) {
      this.core.skipBitfield.set(index, this.core.bitfield.get(index))
    }
    for (const peer of this.peers) peer._resetMissingBlock(index)
  }

  _ondata(peer, req, data) {
    if (req) {
      req.elapsed = Date.now() - req.timestamp
    }

    if (data.block !== null) {
      this._resolveBlockRequest(this._blocks, data.block.index, data.block.value, req)
      this._ondownload(data.block.index, data.block.value.byteLength, peer, req)
    }

    if (data.hash !== null && (data.hash.index & 1) === 0) {
      this._resolveBlockRequest(this._hashes, data.hash.index / 2, null, req)
    }

    if (this._upgrade !== null) {
      this._resolveUpgradeRequest(req)
    }

    if (this._seeks.length > 0) {
      this._clearInflightSeeks(req)
    }

    if (this._reorgs.length > 0) {
      this._clearInflightReorgs(req)
    }

    if (this._manifestPeer === peer && this.core.header.manifest !== null) {
      this._manifestPeer = null
    }

    if (this._seeks.length > 0 || this._ranges.length > 0) {
      this._updateNonPrimary(this._seeks.length > 0)
    }

    this.updatePeer(peer)
  }

  _onwant(peer, start, length, any) {
    if (!peer.isActive()) return

    const contig = Math.min(this.core.state.length, this.core.header.hints.contiguousLength)

    if (start + length < contig || this.core.state.length === contig || (any && start < contig)) {
      peer.wireRange.send({
        drop: false,
        start: 0,
        length: contig
      })
      incrementTx(peer.stats.wireRange, this.stats.wireRange)
      return
    }

    length = Math.min(length, this.core.state.length - start)

    if (any) {
      const bit = this.core.bitfield.firstSet(start)
      if (bit > -1 && bit < start + length) {
        peer.wireRange.send({
          drop: false,
          start: bit,
          length: 1
        })
      }
      return
    }

    for (const msg of this.core.bitfield.want(start, length)) {
      peer.wireBitfield.send(msg)
      incrementTx(peer.stats.wireBitfield, this.stats.wireBitfield)
    }
  }

  async _onreorgdata(peer, req, data) {
    const newBatch = data.upgrade && (await this.core.verifyReorg(data))
    const f = this._addReorg(data.fork, peer)

    if (f === null) {
      this.queueUpdateAll()
      return
    }

    removeInflight(f.inflight, req)

    if (f.batch) {
      await f.batch.update(data)
    } else if (data.upgrade) {
      f.batch = newBatch

      // Remove "older" reorgs in progress as we just verified this one.
      this._clearOldReorgs(f.fork)
    }

    if (f.batch && f.batch.finished) {
      if (this._addUpgradeMaybe() !== null) {
        await this._applyReorg(f)
      }
    }

    this.queueUpdateAll()
  }

  // Never throws, allowed to run in the background
  async _applyReorg(f) {
    // TODO: more optimal here to check if potentially a better reorg
    // is available, ie higher fork, and request that one first.
    // This will request that one after this finishes, which is fine, but we
    // should investigate the complexity in going the other way

    const u = this._upgrade
    const old = this._reorgs

    this._reorgs = [] // clear all as the nodes are against the old tree - easier
    this._applyingReorg = this.core.reorg(f.batch, null) // TODO: null should be the first/last peer?

    try {
      await this._applyingReorg
    } catch (err) {
      this._upgrade = null
      u.reject(err)
    }

    this._applyingReorg = null

    if (this._upgrade !== null) {
      this._resolveUpgradeRequest(null)
    }

    for (const peer of this.peers) this._updateFork(peer)

    // TODO: all the remaining is a tmp workaround until we have a flag/way for ANY_FORK
    for (const r of this._ranges) {
      r.start = r.userStart
      r.end = r.userEnd
    }

    for (const f of old) f.resolve()
    f.resolve()

    this.queueUpdateAll()
  }

  _maybeUpdate() {
    return this._upgrade !== null && this._upgrade.inflight.length === 0
  }

  _maybeRequestManifest() {
    return this.core.header.manifest === null && this._manifestPeer === null
  }

  _updateFork(peer) {
    if (
      this._applyingReorg !== null ||
      this.allowFork === false ||
      peer.remoteFork <= this.core.state.fork
    ) {
      return false
    }

    const f = this._addReorg(peer.remoteFork, peer)

    // TODO: one per peer is better
    if (f !== null && f.batch === null && f.inflight.length === 0) {
      return peer._requestForkProof(f)
    }

    return false
  }

  _updateHotswap(peer) {
    const maxHotswaps = peer.getMaxHotswapInflight()
    if (!peer.isActive() || peer.inflight >= maxHotswaps) return

    for (const b of this.hotswaps.pick(peer)) {
      if (peer._requestBlock(b) === false) continue
      peer.stats.hotswaps++
      peer.replicator.stats.hotswaps++
      if (peer.inflight >= maxHotswaps) break
    }
  }

  _updatePeer(peer) {
    if (!peer.isActive() || peer.inflight >= peer.getMaxInflight() || !peer.remoteUploading) {
      return false
    }

    // Eagerly request the manifest even if the remote length is 0. If not 0 we'll get as part of the upgrade request...
    if (
      this._maybeRequestManifest() === true &&
      peer.remoteLength === 0 &&
      peer.remoteHasManifest === true
    ) {
      this._manifestPeer = peer
      peer._requestManifest()
    }

    for (const s of this._seeks) {
      if (s.inflight.length > 0) continue // TODO: one per peer is better
      if (peer._requestSeek(s) === true) {
        return true
      }
    }

    // Implied that any block in the queue should be requested, no matter how many inflights
    const blks = new RandomIterator(this._queued)

    for (const b of blks) {
      if (b.queued === false || peer._requestBlock(b) === true) {
        b.queued = false
        blks.dequeue()
        return true
      }
    }

    return false
  }

  _updatePeerNonPrimary(peer) {
    if (!peer.isActive() || peer.inflight >= peer.getMaxInflight() || !peer.remoteUploading) {
      return false
    }

    const ranges = new RandomIterator(this._ranges)
    let tried = 0

    for (const r of ranges) {
      if (peer._requestRange(r) === true) {
        return true
      }
      if (++tried >= MAX_RANGES) break
    }

    // Iterate from newest fork to oldest fork...
    for (let i = this._reorgs.length - 1; i >= 0; i--) {
      const f = this._reorgs[i]
      if (f.batch !== null && f.inflight.length === 0 && peer._requestForkRange(f) === true) {
        return true
      }
    }

    if (this._maybeUpdate() === true && peer._requestUpgrade(this._upgrade) === true) {
      return true
    }

    return false
  }

  updatePeer(peer) {
    // Quick shortcut to wait for flushing reorgs - not needed but less waisted requests
    if (this._applyingReorg !== null) return

    while (this._updatePeer(peer) === true);
    while (this._updatePeerNonPrimary(peer) === true);

    if (this.peers.length > 1 && this._blocks.isEmpty() === false) {
      this._updateHotswap(peer)
    }

    this._checkUpgradeIfAvailable()
  }

  updateSubset() {
    return this.updateAll(false)
  }

  updateAll(all = true) {
    // Clear queued scan if a full scan
    if (this._updateAllBump !== null && all) {
      clearTimeout(this._updateAllBump)
      this._updateAllBump = null
    }

    // Quick shortcut to wait for flushing reorgs - not needed but less waisted requests
    if (this._applyingReorg !== null) return

    const peers = new RandomIterator(this.peers)

    const limit = all ? peers.length : MIN_PEER_UPDATE_ALL
    let tried = 0
    for (const peer of peers) {
      tried++
      if (this._updatePeer(peer) === true) {
        peers.requeue()
      }
      if (tried >= limit) break
    }

    // Check if we can skip the non primary check fully
    if (this._maybeUpdate() === false && this._ranges.length === 0 && this._reorgs.length === 0) {
      this._checkUpgradeIfAvailable()
      return
    }

    tried = 0
    for (const peer of peers.restart()) {
      tried++
      if (this._updatePeerNonPrimary(peer) === true) {
        peers.requeue()
      }
      if (tried >= limit) break
    }

    this._checkUpgradeIfAvailable()
  }

  getUpdateAllDelay(peers) {
    return Math.min(3000, Math.max(100, (peers.length - MIN_PEER_UPDATE_ALL) * 5))
  }

  queueUpdateAll() {
    if (this.peers.length < MIN_PEER_UPDATE_ALL) return this.updateAll()

    // Immediately scan subset
    this.updateSubset()

    // Schedule full scan
    if (this._updateAllBump !== null) return //skip if already scheduled
    this._updateAllBump = setTimeout(this._updateAllBound, this.getUpdateAllDelay(this.peers))
  }

  onpeerdestroy() {
    if (--this._active === 0) this.core.checkIfIdle()
  }

  attached(protomux) {
    return this._attached.has(protomux)
  }

  attachTo(protomux) {
    if (this.core.closed) return

    const makePeer = this._makePeer.bind(this, protomux)

    this._attached.add(protomux)
    protomux.pair({ protocol: 'hypercore/alpha', id: this.core.discoveryKey }, makePeer)
    protomux.stream.setMaxListeners(0)
    protomux.stream.on('close', this._onstreamclose)

    this._ifAvailable++
    this._active++

    protomux.stream.opened.then((opened) => {
      this._ifAvailable--
      this._active--

      if (opened && !this.destroyed) makePeer()
      this._checkUpgradeIfAvailable()

      this.core.checkIfIdle()
    })
  }

  detachFrom(protomux) {
    if (this._attached.delete(protomux)) {
      protomux.stream.removeListener('close', this._onstreamclose)
      protomux.unpair({ protocol: 'hypercore/alpha', id: this.core.discoveryKey })
    }
  }

  idle() {
    return this.peers.length === 0 && this._active === 0
  }

  close() {
    const waiting = []

    for (const peer of this.peers) {
      waiting.push(peer.channel.fullyClosed())
    }

    this.destroy()
    return Promise.all(waiting)
  }

  destroy() {
    if (this.destroyed) return
    this.destroyed = true

    if (this._notDownloadingTimer) {
      clearTimeout(this._notDownloadingTimer)
      this._notDownloadingTimer = null
    }

    if (this._updateAllBump) {
      clearTimeout(this._updateAllBump)
      this._updateAllBump = null
    }

    while (this.peers.length) {
      const peer = this.peers[this.peers.length - 1]
      this.detachFrom(peer.protomux)
      peer.channel.close() // peer is removed from array in onclose
    }

    for (const protomux of this._attached) {
      this.detachFrom(protomux)
    }
  }

  _makePeer(protomux) {
    const replicator = this
    if (protomux.opened({ protocol: 'hypercore/alpha', id: this.core.discoveryKey })) {
      return onnochannel()
    }

    const channel = protomux.createChannel({
      userData: null,
      protocol: 'hypercore/alpha',
      aliases: ['hypercore'],
      id: this.core.discoveryKey,
      handshake: m.wire.handshake,
      messages: [
        { encoding: m.wire.sync, onmessage: onwiresync },
        { encoding: m.wire.request, onmessage: onwirerequest },
        { encoding: m.wire.cancel, onmessage: onwirecancel },
        { encoding: m.wire.data, onmessage: onwiredata },
        { encoding: m.wire.noData, onmessage: onwirenodata },
        { encoding: m.wire.want, onmessage: onwirewant },
        { encoding: m.wire.unwant, onmessage: onwireunwant },
        { encoding: m.wire.bitfield, onmessage: onwirebitfield },
        { encoding: m.wire.range, onmessage: onwirerange },
        { encoding: m.wire.extension, onmessage: onwireextension }
      ],
      onopen: onwireopen,
      onclose: onwireclose,
      ondrain: onwiredrain,
      ondestroy: onwiredestroy
    })

    if (channel === null) return onnochannel()

    const peer = new Peer(replicator, protomux, channel, this.inflightRange)
    const stream = protomux.stream

    peer.channel.open({
      seeks: true,
      capability: caps.replicate(stream.isInitiator, this.core.key, stream.handshakeHash)
    })

    return true

    function onnochannel() {
      return false
    }
  }

  _onpeerupdate(added, peer) {
    const name = added ? 'peer-add' : 'peer-remove'
    const sessions = this.core.monitors

    for (let i = sessions.length - 1; i >= 0; i--) {
      sessions[i].emit(name, peer)

      if (added) {
        for (const ext of sessions[i].extensions.values()) {
          peer.extensions.set(ext.name, ext)
        }
      }
    }
  }

  _ondownload(index, byteLength, from, req) {
    const sessions = this.core.monitors

    for (let i = sessions.length - 1; i >= 0; i--) {
      const s = sessions[i]
      s.emit('download', index, byteLength - s.padding, from, req)
    }
  }

  _onupload(index, byteLength, from) {
    const sessions = this.core.monitors

    for (let i = sessions.length - 1; i >= 0; i--) {
      const s = sessions[i]
      s.emit('upload', index, byteLength - s.padding, from)
    }
  }

  _oninvaliddata(err, req, res, from) {
    const sessions = this.core.monitors

    this.stats.invalidData++
    from.stats.invalidData++
    for (let i = 0; i < sessions.length; i++) {
      sessions[i].emit('verification-error', err, req, res, from)
    }
  }

  _oninvalidrequest(err, req, from) {
    const sessions = this.core.monitors

    from.stats.invalidRequests++
    this.stats.invalidRequests++
    for (let i = 0; i < sessions.length; i++) {
      sessions[i].emit('invalid-request', err, req, from)
    }
  }
}

function removeHotswap(block) {
  if (block.hotswap === null) return false
  block.hotswap.ref.remove(block)
  return true
}

function removeInflight(inf, req) {
  const i = inf.indexOf(req)
  if (i === -1) return false
  if (i < inf.length - 1) inf[i] = inf.pop()
  else inf.pop()
  return true
}

function toLength(start, end) {
  return end === -1 ? -1 : end < start ? 0 : end - start
}

function clampRange(core, r) {
  if (r.blocks === null) {
    const start = core.bitfield.firstUnset(r.start)

    if (r.end === -1) r.start = start === -1 ? core.state.length : start
    else if (start === -1 || start >= r.end) r.start = r.end
    else {
      r.start = start

      const end = core.bitfield.lastUnset(r.end - 1)

      if (end === -1 || start >= end + 1) r.end = r.start
      else r.end = end + 1
    }
  } else {
    while (r.start < r.end && core.bitfield.get(r.blocks[r.start])) r.start++
    while (r.start < r.end && core.bitfield.get(r.blocks[r.end - 1])) r.end--
  }
}

function onrequesttimeout(req) {
  if (req.context) req.context.detach(req, REQUEST_TIMEOUT())
}

function destroyRequestTimeout(req) {
  if (req.timeout !== null) {
    clearTimeout(req.timeout)
    req.timeout = null
  }
}

function isCriticalError(err) {
  // TODO: expose .critical or similar on the hypercore errors that are critical (if all not are)
  return err.name === 'HypercoreError'
}

function onwireopen(m, c) {
  return c.userData.onopen(m)
}

function onwireclose(isRemote, c) {
  return c.userData.onclose(isRemote)
}

function onwiredestroy(c) {
  c.userData.replicator.onpeerdestroy()
}

function onwiredrain(c) {
  return c.userData.ondrain()
}

function onwiresync(m, c) {
  incrementRx(c.userData.stats.wireSync, c.userData.replicator.stats.wireSync)
  return c.userData.onsync(m)
}

function onwirerequest(m, c) {
  incrementRx(c.userData.stats.wireRequest, c.userData.replicator.stats.wireRequest)
  return c.userData.onrequest(m)
}

function onwirecancel(m, c) {
  incrementRx(c.userData.stats.wireCancel, c.userData.replicator.stats.wireCancel)
  return c.userData.oncancel(m)
}

function onwiredata(m, c) {
  incrementRx(c.userData.stats.wireData, c.userData.replicator.stats.wireData)
  return c.userData.ondata(m)
}

function onwirenodata(m, c) {
  return c.userData.onnodata(m)
}

function onwirewant(m, c) {
  incrementRx(c.userData.stats.wireWant, c.userData.replicator.stats.wireWant)
  return c.userData.onwant(m)
}

function onwireunwant(m, c) {
  return c.userData.onunwant(m)
}

function onwirebitfield(m, c) {
  incrementRx(c.userData.stats.wireBitfield, c.userData.replicator.stats.wireBitfield)
  return c.userData.onbitfield(m)
}

function onwirerange(m, c) {
  incrementRx(c.userData.stats.wireRange, c.userData.replicator.stats.wireRange)
  return c.userData.onrange(m)
}

function onwireextension(m, c) {
  incrementRx(c.userData.stats.wireExtension, c.userData.replicator.stats.wireExtension)
  return c.userData.onextension(m)
}

function setNotDownloadingLater(repl, session) {
  repl._setDownloadingNow(false, session)
}

function isBlockRequest(req) {
  return req !== null && req.block !== null
}

function isUpgradeRequest(req) {
  return req !== null && req.upgrade !== null
}

function incrementTx(stats1, stats2) {
  stats1.tx++
  stats2.tx++
}

function incrementRx(stats1, stats2) {
  stats1.rx++
  stats2.rx++
}

function noop() {}

function backoff(times) {
  const sleep = times < 2 ? 200 : times < 5 ? 500 : times < 40 ? 1000 : 5000
  return new Promise((resolve) => setTimeout(resolve, sleep))
}
const crypto = require('hypercore-crypto')
const b4a = require('b4a')
const assert = require('nanoassert')
const flat = require('flat-tree')
const quickbit = require('quickbit-universal')
const HypercoreStorage = require('hypercore-storage')

const {
  INVALID_OPERATION,
  INVALID_SIGNATURE,
  ASSERTION,
  SESSION_CLOSED,
  SESSION_NOT_WRITABLE
} = require('hypercore-errors')

const Mutex = require('./mutex')
const Bitfield = require('./bitfield')
const { MerkleTree, MerkleTreeBatch } = require('./merkle-tree')

class SessionState {
  constructor(core, parent, storage, treeInfo, name) {
    this.core = core
    this.index = this.core.sessionStates.push(this) - 1

    this.storage = storage
    this.name = name
    this.sessions = []

    // small hack to close old storages as late as possible.
    // TODO: add a read lock so we can avoid that
    this.lingers = null

    this.parent = parent
    this.atomized = null
    this.mutex = new Mutex()

    // merkle state
    this.roots = treeInfo.roots.length ? treeInfo.roots : []
    this.fork = treeInfo.fork || 0
    this.length = this.roots.length ? MerkleTree.span(this.roots) / 2 : treeInfo.length
    this.byteLength = MerkleTree.size(this.roots)
    this.prologue = treeInfo.prologue || null
    this.signature = treeInfo.signature || null

    this.snapshotCompatLength = this.isSnapshot()
      ? Math.min(this.length, this.core.state.length)
      : -1
    this.lastTruncation = null
    this.groupUpdated = false

    this.active = 0

    this._activeTx = null
    this._pendingBitfield = null

    this.ref()
  }

  static RECOVERY_PEERS = null

  isSnapshot() {
    return this.storage.snapshotted
  }

  isDefault() {
    return this.core.state === this || this.isAtomicDefault()
  }

  isAtomicDefault() {
    return !!this.storage.atom && !!this.parent && this.parent.isDefault()
  }

  createTreeBatch() {
    return new MerkleTreeBatch(this)
  }

  addSession(s) {
    if (s._stateIndex !== -1) return
    s._stateIndex = this.sessions.push(s) - 1
    if (s.weak === false) this.core.activeSessions++
  }

  removeSession(s) {
    if (s._stateIndex === -1) return
    const head = this.sessions.pop()
    if (head !== s) this.sessions[(head._stateIndex = s._stateIndex)] = head
    s._stateIndex = -1
    if (s.weak === false) this.core.activeSessions--
    this.core.checkIfIdle()
  }

  flushedLength() {
    if (this.isDefault() || this.isSnapshot()) return this.length
    const deps = this.storage.dependencies
    if (deps.length) return deps[deps.length - 1].length
    return 0
  }

  signedLength() {
    const l = Math.min(this.flushedLength(), this.core.state.length)
    return this.isSnapshot() && l > this.snapshotCompatLength ? this.snapshotCompatLength : l
  }

  unref() {
    if (--this.active > 0) return
    this.close().catch(noop) // technically async, but only for the last db session
  }

  ref() {
    this.active++
    return this
  }

  hash() {
    return MerkleTree.hash(this)
  }

  setRoots(roots) {
    this.roots = roots
    this.length = MerkleTree.span(roots) / 2
    this.byteLength = MerkleTree.size(roots)
  }

  get encryptionFork() {
    return this.core.header.tree.fork
  }

  async _updateSnapshotStorage(storage) {
    if (!this.atomized || !this.atomized.flushing) return this.treeInfo()
    while (this.atomized.flushing) await this.atomized.flushed()

    let rx = storage.read()
    const headPromise = rx.getHead()
    const authPromise = rx.getAuth()
    const depPromise = rx.getDependency()

    rx.tryFlush()
    const [head, auth, dep] = await Promise.all([headPromise, authPromise, depPromise])

    storage.setDependencyHead(dep)

    const fork = head ? head.fork : 0
    const length = head ? head.length : 0

    rx = storage.read()
    const rootPromises = []
    for (const r of flat.fullRoots(length * 2)) {
      rootPromises.push(rx.getTreeNode(r))
    }

    rx.tryFlush()

    const roots = await Promise.all(rootPromises)

    // dbl check if we are hitting an regression from earler
    for (const root of roots) {
      if (root === null) {
        throw new Error(
          'Bad snapshot from atomized session, id = ' +
            this.core.id +
            ' length = ' +
            length +
            ' fork = ' +
            fork
        )
      }
    }

    return {
      fork,
      roots,
      length,
      prologue: auth.manifest && auth.manifest.prologue,
      signature: head && head.signature
    }
  }

  treeInfo() {
    return {
      fork: this.fork,
      roots: this.roots.slice(),
      length: this.length,
      prologue: this.prologue,
      signature: this.signature
    }
  }

  async close() {
    if (this.index === -1) return

    this.active = 0
    this.mutex.destroy(new Error('Closed')).catch(noop)
    if (this.parent && this.parent.atomized) this.parent.atomized = null

    const closing = this.storage.close()

    const head = this.core.sessionStates.pop()
    if (head !== this) this.core.sessionStates[(head.index = this.index)] = head

    this.index = -1
    this.core.checkIfIdle()

    if (this.lingers !== null) {
      for (const storage of this.lingers) await storage.close()
    }

    return closing
  }

  async snapshot() {
    const storage = this.storage.snapshot()
    const treeInfo = await this._updateSnapshotStorage(storage)

    return new SessionState(this.core, null, storage, treeInfo, this.name)
  }

  updateDependency(tx, length) {
    const dependency = updateDependency(this, length, false)
    if (dependency) tx.setDependency(dependency)
    return dependency
  }

  updateGroupIndex(tx, tree) {
    const { pointer } = this.core.header.group

    tx.deleteGroupUpdate(pointer, this.core.header.tree.timestamp)
    tx.putGroupUpdate(pointer, tree.timestamp, this.core.header.key)

    this.groupUpdated = true
  }

  _clearActiveBatch() {
    this._activeTx = null
  }

  createWriteBatch() {
    assert(!this._activeTx && !this.storage.snapshotted)

    this._activeTx = this.storage.write()
    return this._activeTx
  }

  _unlock() {
    this._clearActiveBatch()
    this.mutex.unlock()
    this.core.checkIfIdle()
  }

  _flushHooks() {
    if (!this.groupUpdated) return
    this.groupUpdated = false
    this.core.ongroupupdate(this.core.header.group.key, {
      key: this.core.key,
      length: this.length,
      fork: this.fork
    })
  }

  async flush() {
    const tx = this._activeTx
    this._activeTx = null

    try {
      if (!(await tx.flush())) return false
    } finally {
      this._clearActiveBatch()
    }

    this.lastTruncation = null
    return true
  }

  _precommit(state) {
    assert(
      state.parent === this && state.storage.core.dataPointer === this.storage.core.dataPointer,
      'Atomic state must flush to parent'
    )
  }

  async _commit() {
    await this.mutex.lock()

    try {
      const bitfield = this._pendingBitfield
      this._pendingBitfield = null
      this.lastTruncation = null
      await this.parent._oncommit(this, bitfield)
    } finally {
      this.mutex.unlock()
    }
  }

  async _oncommit(src, bitfield) {
    await this.mutex.lock()

    try {
      const currLength = this.length

      // load dependency into memory
      const rx = this.storage.read()
      const dependencyPromise = rx.getDependency()

      rx.tryFlush()

      const dependency = await dependencyPromise

      this.fork = src.fork
      this.length = src.length
      this.byteLength = src.byteLength
      this.roots = src.roots.slice()
      this.signature = src.signature

      const tree = {
        fork: this.fork,
        length: this.length,
        rootHash: this.hash(),
        signature: this.signature,
        timestamp: Date.now()
      }

      if (this.isDefault() && this.core.header.group) {
        const tx = this.createWriteBatch()
        this.updateGroupIndex(tx, tree)
        await this.flush()
        this._flushHooks()
      }

      if (dependency) this.storage.setDependencyHead(dependency)

      const b = bitfield

      if (b && b.truncated && b.start < currLength) {
        this.ontruncate(tree, b.start, currLength, true)
        if (!b || b.appends === 0) return
      }

      const append = b ? { start: b.start, length: b.appends, drop: false } : null

      this.onappend(tree, append, true)

      if (this.core.hintsChanged && this.isDefault()) await this.core.flushHints()
    } finally {
      this._unlock()
    }
  }

  async setUserData(key, value) {
    await this.mutex.lock()

    try {
      const tx = this.createWriteBatch()
      tx.putUserData(key, value)

      return await this.flush()
    } finally {
      this._unlock()
    }
  }

  async _verifyBlock(batch, bitfield, value, manifest, from) {
    await this.mutex.lock()

    try {
      if (batch.upgraded && batch.length <= this.length) {
        await batch.downgrade()
      }

      if (!batch.commitable()) {
        return false
      }

      if (this.core.preupdate !== null) {
        await this.core.preupdate(batch, this.core.header.key)
      }

      const tx = this.createWriteBatch()

      if (bitfield) {
        tx.putBlock(bitfield.start, value)
      }

      if (bitfield && this.isDefault()) {
        await storeBitfieldRange(this.storage, tx, bitfield.start, bitfield.start + 1, true)
      }

      if (manifest) this.core._setManifest(tx, manifest, null)

      assert(batch.commitable(), 'Should still be commitable')
      batch.commit(tx)

      const head = {
        fork: batch.fork,
        length: batch.length,
        rootHash: batch.hash(),
        signature: batch.signature,
        timestamp: Date.now()
      }

      if (batch.upgraded) {
        tx.setHead(head)

        if (this.core.header.group) {
          this.updateGroupIndex(tx, head)
        }
      }

      const flushed = await this.flush()

      if (batch.upgraded) {
        this.roots = batch.roots
        this.length = batch.length
        this.byteLength = batch.byteLength
        this.fork = batch.fork
        this.signature = batch.signature

        this.onappend(head, bitfield, flushed)
      }

      if (this.core.hintsChanged && this.isDefault()) await this.core.flushHints()
    } finally {
      this._unlock()
    }

    return true
  }

  async truncate(length, fork, { signature, keyPair } = {}) {
    if (!keyPair && this.isDefault()) keyPair = this.core.header.keyPair

    await this.mutex.lock()

    try {
      if (this.prologue && length < this.prologue.length) {
        throw INVALID_OPERATION('Truncation breaks prologue', this.core.discoveryKey)
      }
      if (length > this.length) {
        throw INVALID_OPERATION(
          'Not a truncation, ' + length + ' must be less or equal to ' + this.length,
          this.core.discoveryKey
        )
      }

      const batch = this.createTreeBatch()
      await MerkleTree.truncate(this, length, batch, fork)

      if (signature) {
        batch.signature = signature
        this.core._verifyBatchUpgrade(batch)
      } else if (keyPair) {
        batch.signature = this.core.verifier.sign(batch, keyPair)
      }

      const tx = this.createWriteBatch()

      // upsert compat manifest
      if (this.core.verifier === null && keyPair) this.core._setManifest(tx, null, keyPair)

      const { dependency, tree, roots } = await this._truncate(tx, batch)

      for (const sessionState of this.core.sessionStates) {
        if (
          sessionState.isSnapshot() &&
          sessionState.name === this.name &&
          length < sessionState.snapshotCompatLength
        ) {
          sessionState.snapshotCompatLength = length
        }
      }

      const flushed = await this.flush()

      this.fork = tree.fork
      this.length = tree.length
      this.byteLength = MerkleTree.size(roots)
      this.roots = roots
      this.signature = tree.signature

      if (dependency) this.storage.setDependencyHead(dependency)

      this.ontruncate(tree, tree.length, batch.treeLength, flushed)

      if (this.core.hintsChanged && this.isDefault()) await this.core.flushHints()
    } finally {
      this._unlock()
    }
  }

  async reorg(batch) {
    await this.mutex.lock()

    const storage = this.createWriteBatch()

    try {
      if (!batch.commitable()) return false

      const { dependency, tree } = await this._truncate(storage, batch)

      const flushed = await this.flush()

      this.fork = batch.fork
      this.length = batch.length
      this.byteLength = batch.byteLength
      this.roots = batch.roots
      this.signature = batch.signature

      if (dependency) this.storage.setDependencyHead(dependency)

      this.ontruncate(tree, batch.ancestors, batch.treeLength, flushed)

      if (this.core.hintsChanged && this.isDefault()) await this.core.flushHints()
    } finally {
      this._unlock()
    }
  }

  async _truncate(storage, batch) {
    storage.deleteBlockRange(batch.ancestors, batch.treeLength)

    assert(batch.commitable(), 'Batch must be commitable')

    const tree = {
      fork: batch.fork,
      length: batch.length,
      rootHash: batch.hash(),
      signature: batch.signature,
      timestamp: Date.now()
    }

    if (this.isDefault() && this.core.header.group) {
      this.updateGroupIndex(storage, tree)
    }

    storage.setHead(tree)
    batch.commit(storage)

    const truncated = batch.length < this.flushedLength()
    const dependency = truncated ? updateDependency(this, batch.length, true) : null

    if (dependency) storage.setDependency(dependency)

    if (this.isDefault()) {
      await storeBitfieldRange(this.storage, storage, batch.ancestors, batch.treeLength, false)
      if (batch.ancestors < this.core.header.hints.contiguousLength) {
        this.core.header.hints.remoteContiguousLength = Math.min(
          batch.length,
          this.core.header.hints.remoteContiguousLength
        )
        storage.setHints({
          contiguousLength: batch.ancestors,
          remoteContiguousLength: this.core.header.hints.remoteContiguousLength
        })
      }
    }

    return { dependency, tree, roots: batch.roots }
  }

  async clear(start, end, cleared) {
    await this.mutex.lock()

    try {
      const tx = this.createWriteBatch()

      const ite = flat.iterator(start * 2)
      while (!isRootIndex(ite.index, this.roots)) {
        const a = ite.index
        const b = ite.sibling()
        ite.parent()

        const [left, right] = flat.spans(b)
        const s = left / 2
        const e = right / 2 + 1
        const has = s <= start && e <= end ? false : this.core.bitfield.hasSet(s, e - s)
        if (has) break

        tx.deleteTreeNode(a)
        tx.deleteTreeNode(b)
      }

      if (this.isDefault()) {
        await storeBitfieldRange(this.storage, tx, start, end, false)
        if (start < this.core.header.hints.contiguousLength) {
          tx.setHints({
            contiguousLength: start,
            remoteContiguousLength: this.core.header.hints.remoteContiguousLength
          })
        }
      }

      if (end - start === 1) tx.deleteBlock(start)
      else tx.deleteBlockRange(start, end)

      const dependency = start < this.flushedLength() ? updateDependency(this, start, true) : null

      const flushed = await this.flush()

      if (dependency) this.storage.setDependencyHead(dependency)

      // todo: atomic event handle
      if (this.isDefault() && flushed) {
        const length = end - start

        this.core.updateContiguousLength({ start, length, drop: true })
        this.core._setBitfieldRanges(start, end, false)
        this.core.replicator.onhave(start, length, true)

        if (this.core.hintsChanged) await this.core.flushHints()
      }
    } finally {
      this._unlock()
    }
  }

  // simple tool to wait for other peers to catch us up
  async waitForRecovery() {
    const length = this.length
    const replicator = this.core.replicator

    while (!this.closing) {
      let peers = getRecoveryPeers(replicator.peers)

      if (peers.length < 1) {
        await new Promise((resolve) => setTimeout(resolve, 5000))
        continue
      }

      let restart = false

      for (let i = 0; i < 32; i++) {
        await new Promise((resolve) => setTimeout(resolve, 250))

        peers = getRecoveryPeers(replicator.peers)

        if (this.closing || !validateRecoveryPeers(peers, this.length)) {
          restart = true
          break
        }
      }

      if (restart) continue

      if (this.length !== length) {
        throw SESSION_NOT_WRITABLE('core recovered during append')
      }

      this.core.header.hints.recovering = 0
      this.core.hintsChanged = true

      await this.mutex.lock()
      try {
        await this.core.flushHints()
        return
      } finally {
        this.mutex.unlock()
      }
    }

    throw SESSION_CLOSED('Cannot recover a closed session', this.discoveryKey)
  }

  async append(values, { signature, keyPair, preappend, postappend, maxLength = -1 } = {}) {
    if (!keyPair && this.isDefault()) keyPair = this.core.header.keyPair

    if (this.isDefault() && this.core.header.hints.recovering) await this.waitForRecovery()

    await this.mutex.lock()

    try {
      if (maxLength >= 0 && this.length + values.length > maxLength) {
        return { length: this.length, byteLength: this.byteLength }
      }

      const tx = this.createWriteBatch()

      // upsert compat manifest
      if (this.core.verifier === null && keyPair) this.core._setManifest(tx, null, keyPair)

      if (preappend) await preappend(values)

      if (!values.length) {
        await this.flush()
        return { length: this.length, byteLength: this.byteLength }
      }

      const batch = this.createTreeBatch()
      for (const val of values) batch.append(val)

      // only multisig can have prologue so signature is always present
      if (this.prologue && batch.length < this.prologue.length) {
        throw INVALID_OPERATION('Append is not consistent with prologue', this.core.discoveryKey)
      }

      if (signature) {
        batch.signature = signature
        this.core._verifyBatchUpgrade(batch)
      } else if (keyPair) {
        batch.signature = this.core.verifier.sign(batch, keyPair)
      }

      batch.commit(tx)

      const tree = {
        fork: batch.fork,
        length: batch.length,
        rootHash: batch.hash(),
        signature: batch.signature,
        timestamp: Date.now()
      }

      tx.setHead(tree)

      if (this.isDefault()) {
        await storeBitfieldRange(this.storage, tx, batch.ancestors, batch.length, true)
        if (this.length === this.core.header.hints.contiguousLength) {
          tx.setHints({
            contiguousLength: this.length + values.length,
            remoteContiguousLength: this.core.header.hints.remoteContiguousLength
          })
        }

        if (this.core.header.group) {
          this.updateGroupIndex(tx, tree)
        }
      }

      for (let i = 0; i < values.length; i++) {
        tx.putBlock(this.length + i, values[i])
      }

      const bitfield = {
        drop: false,
        start: batch.ancestors,
        length: values.length
      }

      const flushed = await this.flush()

      this.fork = batch.fork
      this.roots = batch.roots
      this.length = batch.length
      this.byteLength = batch.byteLength
      this.signature = batch.signature

      if (postappend) await postappend(values)

      this.onappend(tree, bitfield, flushed)

      if (this.core.hintsChanged && this.isDefault()) await this.core.flushHints()

      return { length: this.length, byteLength: this.byteLength }
    } finally {
      this._unlock()
    }
  }

  onappend(tree, bitfield, flushed) {
    if (!flushed) this._updateBitfield(bitfield)
    else if (this.isDefault()) this.core.onappend(tree, bitfield)

    for (let i = this.sessions.length - 1; i >= 0; i--) {
      this.sessions[i].emit('append')
    }

    this._flushHooks()
  }

  ontruncate(tree, to, from, flushed) {
    const bitfield = { start: to, length: from - to, drop: true }

    this.lastTruncation = { from, to }

    if (!flushed) this._updateBitfield(bitfield)
    else if (this.isDefault()) this.core.ontruncate(tree, bitfield)

    for (const sessionState of this.core.sessionStates) {
      if (
        sessionState.isSnapshot() &&
        sessionState.name === this.name &&
        to < sessionState.snapshotCompatLength
      ) {
        sessionState.snapshotCompatLength = to
      }
    }

    for (let i = this.sessions.length - 1; i >= 0; i--) {
      this.sessions[i].emit('truncate', to, tree.fork)
    }

    this._flushHooks()
  }

  _updateBitfield(bitfield, flushed) {
    if (!bitfield) return

    const p = this._pendingBitfield
    const b = bitfield

    if (b.drop) {
      // truncation must be from end
      if (p && b.start + b.length !== p.start + p.appends) {
        throw INVALID_OPERATION('Atomic truncations must be contiguous', this.core.discoveryKey)
      }

      // actual truncation
      if (p === null || b.start < p.start) {
        this._pendingBitfield = { truncated: true, start: b.start, appends: 0 }
        return
      }

      // just clearing batch data
      p.appends = b.start - p.start

      // we cleared the current batch
      if (p.appends === 0) this._pendingBitfield = null

      return
    }

    if (p === null) {
      this._pendingBitfield = { truncated: false, start: b.start, appends: b.length }
      return
    }

    if (b.start !== p.start + p.appends) {
      throw INVALID_OPERATION('Atomic operations must be contiguous', this.core.discoveryKey)
    }

    p.appends += b.length
  }

  async catchup(length) {
    assert(!this.isDefault(), 'Cannot catchup signed state') // TODO: make this check better

    await this.mutex.lock()

    try {
      const origLength = this.length

      let sharedLength = 0
      for (let i = this.storage.dependencies.length - 1; i >= 0; i--) {
        const dep = this.storage.dependencies[i]
        if (dep.dataPointer === this.core.state.storage.core.dataPointer) {
          sharedLength = dep.length
          break
        }
      }

      const tx = this.createWriteBatch()
      const rx = this.core.state.storage.read()
      const rootPromises = []

      for (const root of flat.fullRoots(length * 2)) {
        rootPromises.push(rx.getTreeNode(root))
      }

      rx.tryFlush()

      const roots = await Promise.all(rootPromises)
      const truncating = sharedLength < origLength

      for (const node of roots) {
        if (node === null) {
          throw INVALID_OPERATION(
            'Invalid catchup length, tree nodes not available',
            this.core.discoveryKey
          )
        }
      }

      const fork = truncating ? this.fork + 1 : this.fork

      // overwrite it atm, TODO: keep what we can connect to the tree
      tx.deleteBlockRange(0, -1)
      tx.deleteTreeNodeRange(0, -1)
      tx.deleteBitfieldPageRange(0, -1)

      const tree = {
        fork,
        length,
        rootHash: crypto.tree(roots),
        signature: null,
        timestamp: Date.now()
      }

      // never default state so do not update group index
      tx.setHead(tree)

      // prop a better way to do this
      const dep = updateDependency(this, sharedLength, true)
      dep.length = length

      tx.setDependency(dep)

      const flushed = await this.flush()

      this.storage.setDependencyHead(dep)

      this.fork = tree.fork
      this.roots = roots
      this.length = tree.length
      this.byteLength = MerkleTree.size(roots)

      if (truncating) this.ontruncate(tree, sharedLength, origLength, flushed)
      if (sharedLength < length) this.onappend(tree, null, flushed)

      if (this.core.hintsChanged && this.isDefault()) await this.core.flushHints()
    } finally {
      this._unlock()
    }
  }

  async _overwrite(source, fork, length, treeLength, signature) {
    const blockPromises = []
    const treePromises = []
    const rootPromises = []

    const rx = source.storage.read()

    for (const root of flat.fullRoots(length * 2)) {
      rootPromises.push(rx.getTreeNode(root))
    }

    for (const index of flat.patch(treeLength * 2, length * 2)) {
      treePromises.push(rx.getTreeNode(index))
    }

    for (let i = treeLength; i < length; i++) {
      treePromises.push(rx.getTreeNode(i * 2))
      treePromises.push(rx.getTreeNode(i * 2 + 1))
      blockPromises.push(rx.getBlock(i))
    }

    rx.tryFlush()

    const [blocks, nodes, roots] = await Promise.all([
      Promise.all(blockPromises),
      Promise.all(treePromises),
      Promise.all(rootPromises)
    ])

    if (this.core.destroyed) throw new Error('Core destroyed')

    if (signature) {
      const batch = this.createTreeBatch()
      batch.roots = roots
      batch.length = length

      if (!this.core.verifier.verify(batch, signature)) {
        throw INVALID_SIGNATURE(
          'Signature is not valid over committed tree',
          this.core.discoveryKey
        )
      }
    }

    const tx = this.createWriteBatch()

    // truncate existing tree
    if (treeLength < this.length) {
      tx.deleteBlockRange(treeLength, this.length)
    }

    for (const root of roots) tx.putTreeNode(root)

    // no nodes will be copied in shallow mode
    for (const node of nodes) {
      if (node !== null) tx.putTreeNode(node)
    }

    for (let i = 0; i < blocks.length; i++) {
      assert(blocks[i] !== null, 'has block')
      tx.putBlock(i + treeLength, blocks[i])
    }

    const totalLength = Math.max(length, this.length)

    if (totalLength > treeLength) {
      const firstPage = getBitfieldPage(treeLength)
      const lastPage = getBitfieldPage(totalLength - 1)

      const srx = this.storage.read()
      const bitfieldPagePromise = srx.getBitfieldPage(firstPage)
      srx.tryFlush()

      const bitfieldPage = await bitfieldPagePromise

      let index = treeLength

      for (let i = firstPage; i <= lastPage; i++) {
        const page = b4a.alloc(Bitfield.BYTES_PER_PAGE)
        tx.putBitfieldPage(i, page)

        // copy existing bits in
        if (i === firstPage && bitfieldPage) page.set(bitfieldPage)

        if (index < length) {
          index = fillBitfieldPage(page, index, length, i, true)
          if (index < length) continue
        }

        if (index < this.length) {
          index = fillBitfieldPage(page, index, this.length, i, false)
        }
      }
    }

    const tree = {
      fork,
      length,
      rootHash: crypto.tree(roots),
      signature,
      timestamp: Date.now()
    }

    if (this.isDefault() && this.core.header.group) {
      this.updateGroupIndex(tx, tree)
    }

    const upgraded = treeLength < this.length || this.length < length || tree.fork !== this.fork

    if (upgraded) tx.setHead(tree)

    const flushed = await this.flush()

    this.fork = tree.fork
    this.roots = roots
    this.length = length
    this.byteLength = MerkleTree.size(roots)
    this.signature = signature

    return { tree, flushed }
  }

  static isParent(state, parent) {
    // atomic batches have parent set
    if (state.parent && state.parent === parent) return true

    return HypercoreStorage.isParentStorage(state.storage, parent.storage)
  }

  async commit(state, { signature, keyPair, length = state.length, treeLength = -1 } = {}) {
    assert(
      this.isDefault() || (this.parent && this.parent.isDefault()),
      'Can only commit into default state'
    )

    assert(SessionState.isParent(state, this), 'Cannot commit across cores')

    if (this.core._repairMode) {
      throw ASSERTION('Cannot commit while repair mode is on')
    }

    if (this.core.header.hints.recovering) await this.waitForRecovery()

    let srcLocked = false
    await this.mutex.lock()

    try {
      await state.mutex.lock()
      srcLocked = true

      if (treeLength === -1) treeLength = state.flushedLength()

      if (!(await this.core._validateCommit(state, treeLength))) return null
      if (this.length > length) return null

      if (this.length < length && !signature) {
        if (!keyPair) keyPair = this.core.header.keyPair
        const batch = state.createTreeBatch()
        if (length !== batch.length) await batch.restore(length)
        signature = this.core.verifier.sign(batch, keyPair)
      }

      const { tree, flushed } = await this._overwrite(
        state,
        this.fork,
        length,
        treeLength,
        signature
      )

      // gc blocks from source
      if (treeLength < length) {
        const tx = state.createWriteBatch()

        tx.deleteBlockRange(treeLength, length)
        const dependency = state.updateDependency(tx, length)

        await state.flush(tx)

        if (dependency) state.storage.setDependencyHead(dependency)
      }

      const bitfield = { start: treeLength, length: length - treeLength, drop: false }
      this.onappend(tree, bitfield, flushed)

      return {
        length: this.length,
        byteLength: this.byteLength
      }
    } finally {
      if (srcLocked) state._unlock()
      this._unlock()
    }
  }

  async _getTreeHeadAt(length) {
    if (length === null) return this.treeInfo()

    const head = getDefaultTree()

    head.length = length

    const roots = await MerkleTree.getRootsFromStorage(this.storage, length)
    const rootHash = crypto.tree(roots)

    head.fork = this.fork
    head.rootHash = rootHash

    if (length === this.length) head.signature = this.signature

    return head
  }

  _moveToCore(core, truncated, appended) {
    const head = this.core.sessionStates.pop()
    if (head !== this) this.core.sessionStates[(head.index = this.index)] = head

    this.core = core
    this.index = this.core.sessionStates.push(this) - 1

    for (let i = this.sessions.length - 1; i >= 0; i--) {
      const s = this.sessions[i]
      const manifest = s.manifest
      s.transferSession(this.core)
      if (!manifest && s.manifest) s.emit('manifest')
      if (truncated) s.emit('truncate', truncated.to, truncated.fork)
      if (appended) s.emit('append')
    }
  }

  async moveTo(core, length) {
    const state = core.state

    await this.mutex.lock()

    try {
      // if (state.storage && (await state.storage.resumeSession(this.name)) !== null) {
      //   throw STORAGE_CONFLICT('Batch has already been created')
      // }

      const treeLength = this.length

      let truncated = null
      let appended = false

      if (!this.isSnapshot()) {
        if (this.lingers === null) this.lingers = []
        this.lingers.push(this.storage)

        const resumed = await state.storage.resumeSession(this.name)

        const truncation = length < this.length ? await truncateAndFlush(this, length) : null
        const treeInfo = truncation
          ? truncation.tree
          : resumed
            ? null
            : await state._getTreeHeadAt(this.length)

        const fork = truncation ? this.fork + 1 : this.fork

        // todo: validate treeInfo

        let storage = null

        if (resumed) {
          storage = resumed
        } else {
          treeInfo.fork = fork
          storage = await state.storage.createSession(this.name, treeInfo)
        }

        const roots = await MerkleTree.getRootsFromStorage(storage, length)

        this.storage = storage
        this.prologue = state.prologue
        this.fork = fork
        this.length = length
        this.byteLength = MerkleTree.size(roots)
        this.roots = roots

        if (truncation) {
          const { dependency } = truncation

          if (dependency) this.storage.setDependencyHead(dependency)
          truncated = { to: treeLength, fork }
        }

        if (this.length > treeLength) {
          appended = true
        }
      }

      for (let i = this.core.sessionStates.length - 1; i >= 0; i--) {
        const state = this.core.sessionStates[i]
        if (state === this) continue
        if (state.name === this.name) state._moveToCore(core.core)
      }

      this._moveToCore(core.core, truncated, appended)
    } finally {
      this._unlock()
    }
  }

  async createSession(name, overwrite, atom) {
    await this.mutex.lock()

    try {
      let storage = null
      let treeInfo = null

      if (!atom && !overwrite && this.storage) {
        storage = await this.storage.resumeSession(name)

        if (storage !== null) treeInfo = (await getCoreHead(storage)) || getDefaultTree()
      }

      const length = treeInfo ? treeInfo.length : this.length

      if (storage === null) {
        treeInfo = await this._getTreeHeadAt(length)

        if (atom) {
          storage = await this.storage.createAtomicSession(atom, treeInfo)
        } else {
          storage = await this.storage.createSession(name, treeInfo)
        }
      }

      if (this.atomized && atom) {
        throw new Error('Session already atomized')
      }

      const head = {
        fork: this.fork,
        roots:
          length === this.length
            ? this.roots.slice()
            : await MerkleTree.getRootsFromStorage(storage, length),
        length,
        prologue: this.prologue,
        signature: length === this.length ? this.signature : null
      }

      const state = new SessionState(
        this.core,
        atom ? this : null,
        storage,
        head,
        atom ? this.name : name
      )

      if (atom) {
        this.atomized = atom
        atom.preflush(this._precommit.bind(this, state))
        atom.onflush(state._commit.bind(state))
      }

      return state
    } finally {
      this._unlock()
    }
  }
}

module.exports = SessionState

function noop() {}

function getBitfieldPage(index) {
  return Math.floor(index / Bitfield.BITS_PER_PAGE)
}

function fillBitfieldPage(page, start, end, pageIndex, value) {
  const offset = pageIndex * Bitfield.BITS_PER_PAGE
  const max = offset + Bitfield.BITS_PER_PAGE

  const index = max < end ? max : end

  const from = start - offset
  const to = index - offset

  quickbit.fill(page, value, from, to)

  return index
}

async function storeBitfieldRange(storage, tx, from, to, value) {
  if (from >= to) return

  const firstPage = getBitfieldPage(from)
  const lastPage = getBitfieldPage(to - 1)

  let index = from

  const rx = storage.read()

  const promises = []
  for (let i = firstPage; i <= lastPage; i++) {
    promises.push(rx.getBitfieldPage(i))
  }

  rx.tryFlush()

  const pages = await Promise.all(promises)
  const cnt = lastPage - firstPage + 1

  for (let i = 0; i < cnt; i++) {
    const pageIndex = i + firstPage
    if (!pages[i]) pages[i] = b4a.alloc(Bitfield.BYTES_PER_PAGE)

    index = fillBitfieldPage(pages[i], index, to, pageIndex, value)
    tx.putBitfieldPage(pageIndex, pages[i])
  }
}

async function truncateAndFlush(s, length) {
  const batch = s.createTreeBatch()
  await MerkleTree.truncate(s, length, batch, s.fork)
  const tx = s.createWriteBatch()

  const info = await s._truncate(tx, batch)
  const flushed = await s.flush()

  return {
    tree: info.tree,
    roots: info.roots,
    dependency: info.dependency,
    flushed
  }
}

function updateDependency(state, length, truncated) {
  const i = state.storage.findDependencyIndex(length, truncated)
  if (i === -1) return null // skip default state and overlays of default

  return {
    dataPointer: state.storage.dependencies[i].dataPointer,
    length
  }
}

function getDefaultTree() {
  return {
    fork: 0,
    length: 0,
    rootHash: null,
    signature: null
  }
}

function getCoreHead(storage) {
  const b = storage.read()
  const p = b.getHead()
  b.tryFlush()
  return p
}

function isRootIndex(index, roots) {
  for (const node of roots) {
    if (node.index === index) return true
  }

  return false
}

function getRecoveryPeers(peers) {
  if (!SessionState.RECOVERY_PEERS) return peers

  const actual = []

  for (const p of peers) {
    for (const r of SessionState.RECOVERY_PEERS) {
      if (b4a.equals(p.remotePublicKey, r)) {
        actual.push(p)
        break
      }
    }
  }

  return actual
}

function validateRecoveryPeers(peers, length) {
  if (peers.length < 1) return false

  for (const p of peers) {
    if (p.remoteLength > length) return false
    if (p.remoteLength === 0 && !p.remoteSynced) return false
  }

  return true
}
const { Writable, Readable } = require('streamx')

class ReadStream extends Readable {
  constructor(core, opts = {}) {
    super()

    this.core = core
    this.start = opts.start || 0
    this.end = typeof opts.end === 'number' ? opts.end : -1
    this.snapshot = !opts.live && opts.snapshot !== false
    this.live = this.end === -1 ? !!opts.live : false
    this.wait = typeof opts.wait === 'boolean' ? opts.wait : this.core.wait
    this.timeout = opts.timeout || core.timeout
  }

  _open(cb) {
    this._openP().then(cb, cb)
  }

  _read(cb) {
    this._readP().then(cb, cb)
  }

  async _openP() {
    if (this.end === -1) await this.core.update()
    else await this.core.ready()
    if (this.snapshot && this.end === -1) this.end = this.core.length
  }

  async _readP() {
    const end = this.live ? -1 : this.end === -1 ? this.core.length : this.end
    if (end >= 0 && this.start >= end) {
      this.push(null)
      return
    }

    this.push(await this.core.get(this.start++, { wait: this.wait, timeout: this.timeout }))
  }
}

exports.ReadStream = ReadStream

class WriteStream extends Writable {
  constructor(core) {
    super()
    this.core = core
  }

  _writev(batch, cb) {
    this._writevP(batch).then(cb, cb)
  }

  async _writevP(batch) {
    await this.core.append(batch)
  }
}

exports.WriteStream = WriteStream

class ByteStream extends Readable {
  constructor(core, opts = {}) {
    super()

    this._core = core
    this._index = 0
    this._range = null

    this._byteOffset = opts.byteOffset || 0
    this._byteLength = typeof opts.byteLength === 'number' ? opts.byteLength : -1
    this._prefetch = typeof opts.prefetch === 'number' ? opts.prefetch : 32

    this._applyOffset = this._byteOffset > 0
  }

  _open(cb) {
    this._openp().then(cb, cb)
  }

  _read(cb) {
    this._readp().then(cb, cb)
  }

  async _openp() {
    if (this._byteLength === -1) {
      await this._core.update()
      this._byteLength = Math.max(this._core.byteLength - this._byteOffset, 0)
    }
  }

  async _readp() {
    let data = null

    if (this._byteLength === 0) {
      this.push(null)
      return
    }

    let relativeOffset = 0

    if (this._applyOffset) {
      this._applyOffset = false

      const [block, byteOffset] = await this._core.seek(this._byteOffset)

      this._index = block
      relativeOffset = byteOffset
    }

    this._predownload(this._index + 1)
    data = await this._core.get(this._index++, { valueEncoding: 'binary' })

    if (relativeOffset > 0) data = data.subarray(relativeOffset)

    if (data.byteLength > this._byteLength) data = data.subarray(0, this._byteLength)
    this._byteLength -= data.byteLength

    this.push(data)
    if (this._byteLength === 0) this.push(null)
  }

  _predownload(index) {
    if (this._range) this._range.destroy()
    this._range = this._core.download({ start: index, end: index + this._prefetch, linear: true })
  }

  _destroy(cb) {
    if (this._range) this._range.destroy()
    cb(null)
  }
}

exports.ByteStream = ByteStream
const crypto = require('hypercore-crypto')
const b4a = require('b4a')
const c = require('compact-encoding')
const flat = require('flat-tree')
const { BAD_ARGUMENT } = require('hypercore-errors')
const unslab = require('unslab')

const m = require('./messages')
const multisig = require('./multisig')
const caps = require('./caps')

class Signer {
  constructor(
    manifestHash,
    version,
    index,
    { signature = 'ed25519', publicKey, namespace = caps.DEFAULT_NAMESPACE } = {}
  ) {
    if (!publicKey) throw BAD_ARGUMENT('public key is required for a signer')
    if (signature !== 'ed25519') throw BAD_ARGUMENT('Only Ed25519 signatures are supported')

    this.manifestHash = manifestHash
    this.version = version
    this.signer = index
    this.signature = signature
    this.publicKey = publicKey
    this.namespace = namespace
  }

  _ctx() {
    return this.version === 0 ? this.namespace : this.manifestHash
  }

  verify(batch, signature) {
    return crypto.verify(batch.signable(this._ctx()), signature, this.publicKey)
  }

  sign(batch, keyPair) {
    return crypto.sign(batch.signable(this._ctx()), keyPair.secretKey)
  }
}

class CompatSigner extends Signer {
  constructor(index, signer, legacy) {
    super(null, 0, index, signer)
    this.legacy = legacy
  }

  verify(batch, signature) {
    return crypto.verify(batch.signableCompat(this.legacy), signature, this.publicKey)
  }

  sign(batch, keyPair) {
    return crypto.sign(batch.signableCompat(this.legacy), keyPair.secretKey)
  }
}

module.exports = class Verifier {
  constructor(
    manifestHash,
    manifest,
    { compat = isCompat(manifestHash, manifest), legacy = false } = {}
  ) {
    const self = this

    this.manifestHash = manifestHash
    this.compat = compat || manifest === null
    this.version = this.compat ? 0 : typeof manifest.version === 'number' ? manifest.version : 1
    this.hash = manifest.hash || 'blake2b'
    this.allowPatch = !this.compat && !!manifest.allowPatch
    this.quorum = this.compat ? 1 : defaultQuorum(manifest)

    this.signers = manifest.signers ? manifest.signers.map(createSigner) : []
    this.prologue = this.compat ? null : manifest.prologue || null

    function createSigner(signer, index) {
      return self.compat
        ? new CompatSigner(index, signer, legacy)
        : new Signer(manifestHash, self.version, index, signer)
    }
  }

  _verifyCompat(batch, signature) {
    if (!signature) return false

    if (this.compat || (!this.allowPatch && this.signers.length === 1)) {
      return !!signature && this.signers[0].verify(batch, signature)
    }

    return this._verifyMulti(batch, signature)
  }

  _inflate(signature) {
    if (this.version >= 1) return multisig.inflate(signature)
    const { proofs, patch } = multisig.inflatev0(signature)

    return {
      proofs: proofs.map(proofToVersion1),
      patch
    }
  }

  _verifyMulti(batch, signature) {
    if (!signature || this.quorum === 0) return false

    const { proofs, patch } = this._inflate(signature)
    if (proofs.length < this.quorum) return false

    const tried = new Uint8Array(this.signers.length)
    const nodes = this.allowPatch && patch.length ? toMap(patch) : null

    for (let i = 0; i < this.quorum; i++) {
      const inp = proofs[i]

      let tree = batch

      if (inp.patch && this.allowPatch) {
        tree = batch.clone()

        const upgrade = generateUpgrade(nodes, batch.length, inp.patch)
        const proof = {
          fork: tree.fork,
          block: null,
          hash: null,
          seek: null,
          upgrade,
          manifest: null
        }

        try {
          if (!tree.verifyUpgrade(proof)) return false
        } catch {
          return false
        }
      }

      if (inp.signer >= this.signers.length || tried[inp.signer]) return false
      tried[inp.signer] = 1

      const s = this.signers[inp.signer]
      if (!s.verify(tree, inp.signature)) return false
    }

    return true
  }

  verify(batch, signature) {
    if (this.version === 0) {
      return this._verifyCompat(batch, signature)
    }

    if (this.prologue !== null && batch.length <= this.prologue.length) {
      return batch.length === this.prologue.length && b4a.equals(batch.hash(), this.prologue.hash)
    }

    return this._verifyMulti(batch, signature)
  }

  // TODO: better api for this that is more ... multisig-ey
  sign(batch, keyPair) {
    if (!keyPair || !keyPair.secretKey) throw BAD_ARGUMENT('No key pair was passed')

    for (const s of this.signers) {
      if (b4a.equals(s.publicKey, keyPair.publicKey)) {
        const signature = s.sign(batch, keyPair)
        if (this.signers.length !== 1 || this.version === 0) return signature
        return this.assemble([{ signer: 0, signature, patch: 0, nodes: null }])
      }
    }

    throw BAD_ARGUMENT('Public key is not a declared signer')
  }

  assemble(inputs) {
    return this.version === 0 ? multisig.assemblev0(inputs) : multisig.assemble(inputs)
  }

  static manifestHash(manifest) {
    return manifestHash(manifest)
  }

  static encodeManifest(manifest) {
    return c.encode(m.manifest, manifest)
  }

  static decodeManifest(manifest) {
    return c.decode(m.manifest, manifest)
  }

  static defaultSignerManifest(publicKey) {
    return {
      version: 1,
      hash: 'blake2b',
      allowPatch: false,
      quorum: 1,
      signers: [
        {
          signature: 'ed25519',
          namespace: caps.DEFAULT_NAMESPACE,
          publicKey
        }
      ],
      prologue: null,
      linked: null,
      userData: null
    }
  }

  static fromManifest(manifest, opts) {
    const m = this.createManifest(manifest)
    return new this(manifestHash(m), m, opts)
  }

  static createManifest(inp) {
    if (!inp) return null

    if (inp.quorum && inp.quorum < 0) throw BAD_ARGUMENT('Quorum cannot be negative')
    if (inp.quorum && inp.signers && inp.quorum > inp.signers.length) {
      throw BAD_ARGUMENT('Quorum should not be higher than the number of signers')
    }

    const manifest = {
      version: getManifestVersion(inp), // defaults to v1
      hash: 'blake2b',
      allowPatch: !!inp.allowPatch,
      quorum: defaultQuorum(inp),
      signers: inp.signers ? inp.signers.map(parseSigner) : [],
      prologue: null,
      linked: null,
      userData: inp.userData || null
    }

    if (inp.hash && inp.hash !== 'blake2b') throw BAD_ARGUMENT('Only Blake2b hashes are supported')

    if (inp.prologue) {
      if (
        !(b4a.isBuffer(inp.prologue.hash) && inp.prologue.hash.byteLength === 32) ||
        !(inp.prologue.length >= 0)
      ) {
        throw BAD_ARGUMENT('Invalid prologue')
      }

      manifest.prologue = inp.prologue
      manifest.prologue.hash = unslab(manifest.prologue.hash)
    }

    if (manifest.userData !== null && manifest.version < 2) {
      throw BAD_ARGUMENT('Invalid field: userData')
    }

    if (inp.linked && inp.linked.length) {
      if (manifest.version < 2) throw BAD_ARGUMENT('Invalid field: linked')

      for (const key of inp.linked) {
        if (!(b4a.isBuffer(key) && key.byteLength === 32)) {
          throw BAD_ARGUMENT('Invalid key')
        }
      }

      manifest.linked = inp.linked
    }

    return manifest
  }

  static isValidManifest(key, manifest) {
    return b4a.equals(key, manifestHash(manifest))
  }

  static isCompat(key, manifest) {
    return isCompat(key, manifest)
  }

  static sign(manifest, batch, keyPair, opts) {
    return Verifier.fromManifest(manifest, opts).sign(batch, keyPair)
  }
}

function toMap(nodes) {
  const m = new Map()
  for (const node of nodes) m.set(node.index, node)
  return m
}

function isCompat(key, manifest) {
  return !!(
    manifest &&
    manifest.signers.length === 1 &&
    b4a.equals(key, manifest.signers[0].publicKey)
  )
}

function defaultQuorum(man) {
  if (typeof man.quorum === 'number') return man.quorum
  if (!man.signers || !man.signers.length) return 0
  return (man.signers.length >> 1) + 1
}

function generateUpgrade(patch, start, length) {
  const upgrade = { start, length, nodes: null, additionalNodes: [], signature: null }

  const from = start * 2
  const to = from + length * 2

  for (const ite = flat.iterator(0); ite.fullRoot(to); ite.nextTree()) {
    if (ite.index + ite.factor / 2 < from) continue

    if (upgrade.nodes === null && ite.contains(from - 2)) {
      upgrade.nodes = []

      const root = ite.index
      const target = from - 2

      ite.seek(target)

      while (ite.index !== root) {
        ite.sibling()
        if (ite.index > target) upgrade.nodes.push(patch.get(ite.index))
        ite.parent()
      }

      continue
    }

    if (upgrade.nodes === null) upgrade.nodes = []
    upgrade.nodes.push(patch.get(ite.index))
  }

  if (upgrade.nodes === null) upgrade.nodes = []
  return upgrade
}

function parseSigner(signer) {
  validateSigner(signer)
  return {
    signature: 'ed25519',
    namespace: unslab(signer.namespace || caps.DEFAULT_NAMESPACE),
    publicKey: unslab(signer.publicKey)
  }
}

function validateSigner(signer) {
  if (!signer || !signer.publicKey) throw BAD_ARGUMENT('Signer missing public key')
  if (signer.signature && signer.signature !== 'ed25519') {
    throw BAD_ARGUMENT('Only Ed25519 signatures are supported')
  }
}

function manifestHash(manifest) {
  const state = { start: 0, end: 32, buffer: null }
  m.manifest.preencode(state, manifest)
  state.buffer = b4a.allocUnsafe(state.end)
  c.raw.encode(state, caps.MANIFEST)
  m.manifest.encode(state, manifest)
  return crypto.hash(state.buffer)
}

function proofToVersion1(proof) {
  return {
    signer: proof.signer,
    signature: proof.signature,
    patch: proof.patch ? proof.patch.length : 0
  }
}

function getManifestVersion(inp) {
  if (typeof inp.version === 'number') return inp.version
  if (inp.linked && inp.linked.length) return 2
  if (inp.userData) return 2
  return 1
}
let COMPAT = true
let BATCH_UINTS = COMPAT ? 65536 : 128
let BATCH_BYTES = BATCH_UINTS * 4
let BATCH = BATCH_BYTES * 8 // in bits
const MAX_REMOTE_BATCHES = 4
const MAX_RANGE = 8 * 256 * 1024
const MIN_RANGE = 32 // 4bit ints
const MAX = 512
const MAX_ANY = 16

class LocalWants {
  constructor(peer) {
    this.destroyed = false
    this.peer = peer
    this.wants = new Map()
    this.free = new Set()
    this.any = null
  }

  add(index, handle) {
    const b = (index - (index & (BATCH - 1))) / BATCH
    return this.addBatch(b, handle)
  }

  addAnyRange(start, length, handle) {
    if (this.destroyed) return null
    if (this.any === null) this.any = []

    if (COMPAT) {
      let r = start & (BATCH - 1)
      start -= r
      length += r
      r = length & (BATCH - 1)
      if (r) length = length - r + BATCH
    }

    for (let i = 0; i < this.any.length; i++) {
      const w = this.any[i]
      if (w.start === start && w.length === length) {
        w.handles.add(handle)
        handle.addWant(w)
        return null
      }
    }

    const w = { wants: this, start, length, any: true, handles: new Set([handle]) }
    this.any.push(w)
    handle.addWant(w)

    return { start, length, any: !COMPAT }
  }

  removeAnyRange(start, length, handle) {
    if (this.any === null) return null

    for (let i = 0; i < this.any.length; i++) {
      const w = this.any[i]
      if (w.start !== start || w.length !== length) continue

      w.handles.delete(handle)
      handle.removeWant(w)
      if (w.handles.size > 0) return null

      const head = this.any.pop()
      if (head !== w) this.any[i] = head
      return { start, length, any: !COMPAT }
    }

    return null
  }

  addBatch(index, handle) {
    if (this.destroyed) return null
    let w = this.wants.get(index)

    if (w) {
      const size = w.handles.size
      w.handles.add(handle)
      if (w.handles.size !== size) {
        handle.addWant(w)
      }
      return null
    }

    // start here is the batch number for simplicity....
    w = { wants: this, start: index, length: 0, any: false, handles: new Set([handle]) }

    if (this.free.has(index)) {
      this.free.delete(index)
      this.wants.set(index, w)
      handle.addWant(w)
      return null
    }

    let unwant = null
    if (this.wants.size + this.free.size === MAX) {
      if (this.free.size === 0) {
        return null
      }
      unwant = this._unwant()
    }

    this.wants.set(index, w)
    handle.addWant(w)

    return {
      want: { start: index * BATCH, length: BATCH, any: false },
      unwant
    }
  }

  remove(index, handle) {
    const b = (index - (index & (BATCH - 1))) / BATCH
    return this.removeBatch(b, handle)
  }

  removeBatch(index, handle) {
    if (this.destroyed) return false

    const w = this.wants.get(index)
    if (!w) {
      return false
    }

    w.handles.delete(handle)
    handle.removeWant(w)

    if (w.handles.size === 0) {
      this.free.add(index)
      this.wants.delete(index)
      return this.free.size === 1 && this.wants.size === MAX - 1
    }

    return false
  }

  destroy() {
    if (this.destroyed) return
    this.destroyed = true

    for (const w of this.wants.values()) {
      for (const handle of w.handles) {
        handle.removeWant(w)
      }
    }

    this.wants.clear()
  }

  _unwant() {
    for (const index of this.free) {
      this.free.delete(index)
      return { start: index * BATCH, length: BATCH, any: false }
    }
    return null
  }
}

class RemoteWants {
  constructor() {
    this.any = null
    this.all = false
    this.size = 0
    this.batches = []
  }

  hasAny(start, length) {
    for (let i = 0; i < this.any.length; i++) {
      const a = this.any[i]
      const e = start + length
      const end = a.start + a.length

      if (a.start <= start && start < end) return true
      if (a.start < e && e <= end) return true
    }

    return this.all
  }

  hasRange(start, length) {
    if (this.any !== null && this.hasAny(start, length)) return true
    if (length === 1) return this.has(start)

    let smallest = -1

    for (let i = 0; i < this.batches.length; i++) {
      const b = this.batches[i]
      if (b.length < smallest || smallest === -1) smallest = b.length
    }

    if (smallest === -1) return this.all

    const r = start & (smallest - 1)
    const end = start + length

    let max = 3

    for (let i = start - r; i < end; i += smallest) {
      if (max-- === 0) return true // just to save work
      if (this.has(i)) return true
    }

    return this.all
  }

  has(index) {
    for (let i = 0; i < this.batches.length; i++) {
      const b = this.batches[i]
      const block = (index - (index & (b.length - 1))) / b.length
      if (b.ranges.has(block)) return true
    }

    return this.all
  }

  add(range) {
    if (range.any) {
      if (this.any === null) this.any = []
      if (this.any.length < MAX_ANY) this.any.push(range)
      else this.all = true
      return true
    }

    if (range.length > MAX_RANGE) return false

    if (!validateBatchRange(range)) {
      this.all = true
      return true
    }

    if (this.size >= MAX) {
      this.all = true
      return true
    }

    for (let i = 0; i < this.batches.length; i++) {
      const b = this.batches[i]
      if (b.length === range.length) {
        b.ranges.add(range.start / range.length)
        this.size++
        return true
      }
    }

    if (this.batches.length >= MAX_REMOTE_BATCHES) {
      this.all = true
      return true
    }

    this.batches.push({
      length: range.length,
      ranges: new Set([range.start / range.length])
    })
    this.size++

    return true
  }

  remove(range) {
    if (range.any) {
      if (this.any === null) return false

      for (let i = 0; i < this.any.length; i++) {
        const a = this.any[i]

        if (a.start === range.start && a.length === range.length) {
          const head = this.any.pop()
          if (head !== a) this.any[i] = head
          return true
        }
      }

      return false
    }

    if (!validateBatchRange(range)) return false

    for (let i = 0; i < this.batches.length; i++) {
      const b = this.batches[i]
      if (b.length !== range.length) continue

      const size = b.ranges.size
      b.ranges.delete(range.start / range.length)
      if (b.ranges.size !== size) this.size--

      if (b.ranges.size === 0) {
        const head = this.batches.pop()
        if (head !== b) this.batches[i] = head
      }

      return true
    }

    return false
  }
}

function UPDATE_COMPAT(isCompat) {
  COMPAT = isCompat
  BATCH_UINTS = COMPAT ? 65536 : 128
  BATCH_BYTES = BATCH_UINTS * 4
  BATCH = BATCH_BYTES * 8 // in bits
  exports.WANT_BATCH = BATCH
}

exports.LocalWants = LocalWants
exports.RemoteWants = RemoteWants
exports.WANT_BATCH = BATCH
exports.UPDATE_COMPAT = UPDATE_COMPAT

function validateBatchRange(range) {
  if (range.length > MAX_RANGE || range.length < MIN_RANGE) {
    return false
  }
  // check if power of two
  if ((range.length & (range.length - 1)) !== 0) {
    return false
  }
  // start must be a multiple of the length
  if (range.start & (range.length - 1)) {
    return false
  }

  return true
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "hypercore",
  "version": "11.34.0",
  "description": "Hypercore is a secure, distributed append-only log",
  "main": "index.js",
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "brittle test/all.js",
    "test:bare": "bare test/all.js",
    "test:generate": "brittle -r test/all.js test/*.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/hypercore.git"
  },
  "contributors": [
    {
      "name": "Mathias Buus",
      "email": "mathiasbuus@gmail.com",
      "url": "https://mafinto.sh"
    },
    {
      "name": "Andrew Osheroff",
      "email": "andrewosh@gmail.com",
      "url": "https://andrewosh.com"
    }
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/hypercore/issues"
  },
  "homepage": "https://github.com/holepunchto/hypercore#readme",
  "files": [
    "index.js",
    "errors.js",
    "messages.js",
    "lib/**.js"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "dependencies": {
    "@hyperswarm/secret-stream": "^6.0.0",
    "b4a": "^1.1.0",
    "bare-events": "^2.2.0",
    "big-sparse-array": "^1.0.3",
    "compact-encoding": "^3.0.0",
    "fast-fifo": "^1.3.0",
    "flat-tree": "^1.9.0",
    "hypercore-crypto": "^3.2.1",
    "hypercore-errors": "^1.5.0",
    "hypercore-id-encoding": "^1.2.0",
    "hypercore-storage": "^3.2.0",
    "is-options": "^1.0.1",
    "nanoassert": "^2.0.0",
    "protomux": "^3.5.0",
    "quickbit-universal": "^2.2.0",
    "random-array-iterator": "^1.0.0",
    "safety-catch": "^1.0.1",
    "sodium-universal": "^5.0.1",
    "streamx": "^2.12.4",
    "unslab": "^1.3.0",
    "z32": "^1.0.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "debugging-stream": "^3.1.0",
    "hyperswarm": "^4.3.6",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "rache": "^1.0.0",
    "range-parser": "^1.2.1",
    "resolve-reject-promise": "^1.1.0",
    "speedometer": "^1.1.0",
    "test-tmp": "^1.0.2",
    "tiny-byte-size": "^1.1.0",
    "udx-native": "^1.6.1",
    "uncaughts": "^1.1.0"
  }
}
const c = require('compact-encoding')
const { getEncoding } = require('./spec/hyperschema')

const HyperdhtAddress = getEncoding('@hyperdht/address')

function decode(buf) {
  const addr = c.decode(HyperdhtAddress, buf)
  return addr
}

function encode(key, nodes) {
  return c.encode(HyperdhtAddress, { key, nodes })
}

module.exports = { decode, encode }
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "hyperdht-address",
  "version": "1.1.1",
  "description": "hyperdht-address",
  "main": "index.js",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    }
  },
  "files": [
    "package.json",
    "index.js",
    "index.d.ts",
    "spec"
  ],
  "devDependencies": {
    "b4a": "^1.8.0",
    "brittle": "^3.19.0",
    "lunte": "^1.2.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && lunte && brittle-bare test/index.js",
    "lint": "lunte"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/hyperdht-address.git"
  },
  "author": "Holepunch Inc",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/hyperdht-address/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperdht-address",
  "dependencies": {
    "compact-encoding": "^3.0.0",
    "hyperschema": "^1.20.1"
  }
}
// This file is autogenerated by the hyperschema compiler
// Schema Version: 2
/* eslint-disable camelcase */
/* eslint-disable quotes */
/* eslint-disable space-before-function-paren */

const { c } = require('hyperschema/runtime')

const VERSION = 2

// eslint-disable-next-line no-unused-vars
let version = VERSION

// @hyperdht/address.nodes
const encoding0_1 = c.array(c.ipv4Address)

// @hyperdht/address
const encoding0 = {
  preencode(state, m) {
    c.fixed32.preencode(state, m.key)
    state.end++ // max flag is 1 so always one byte

    if (version >= 2 && m.nodes) encoding0_1.preencode(state, m.nodes)
  },
  encode(state, m) {
    const flags = version >= 2 && m.nodes ? 1 : 0

    c.fixed32.encode(state, m.key)
    c.uint.encode(state, flags)

    if (version >= 2 && m.nodes) encoding0_1.encode(state, m.nodes)
  },
  decode(state) {
    const r0 = c.fixed32.decode(state)
    const flags = state.start < state.end ? c.uint.decode(state) : 0

    return {
      key: r0,
      nodes: version >= 2 && (flags & 1) !== 0 ? encoding0_1.decode(state) : null
    }
  }
}

function setVersion(v) {
  version = v
}

function encode(name, value, v = VERSION) {
  version = v
  return c.encode(getEncoding(name), value)
}

function decode(name, buffer, v = VERSION) {
  version = v
  return c.decode(getEncoding(name), buffer)
}

function getEnum(name) {
  switch (name) {
    default:
      throw new Error('Enum not found ' + name)
  }
}

function getEncoding(name) {
  switch (name) {
    case '@hyperdht/address':
      return encoding0
    default:
      throw new Error('Encoder not found ' + name)
  }
}

function getStruct(name, v = VERSION) {
  const enc = getEncoding(name)
  return {
    preencode(state, m) {
      version = v
      enc.preencode(state, m)
    },
    encode(state, m) {
      version = v
      enc.encode(state, m)
    },
    decode(state) {
      version = v
      return enc.decode(state)
    }
  }
}

const resolveStruct = getStruct // compat

module.exports = {
  resolveStruct,
  getStruct,
  getEnum,
  getEncoding,
  encode,
  decode,
  setVersion,
  version
}
const DHT = require('dht-rpc')
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const b4a = require('b4a')
const safetyCatch = require('safety-catch')
const m = require('./lib/messages')
const SocketPool = require('./lib/socket-pool')
const Persistent = require('./lib/persistent')
const Router = require('./lib/router')
const Cache = require('xache')
const Server = require('./lib/server')
const connect = require('./lib/connect')
const { FIREWALL, BOOTSTRAP_NODES, COMMANDS } = require('./lib/constants')
const { hash, createKeyPair } = require('./lib/crypto')
const RawStreamSet = require('./lib/raw-stream-set')
const ConnectionPool = require('./lib/connection-pool')
const { STREAM_NOT_CONNECTED } = require('./lib/errors')

const DEFAULTS = {
  ...DHT.DEFAULTS,
  connectionKeepAlive: 5000,
  randomPunchInterval: 20000
}

class HyperDHT extends DHT {
  constructor(opts = {}) {
    const port = opts.port || 49737
    const bootstrap = opts.bootstrap || BOOTSTRAP_NODES
    const nodes = opts.nodes || []

    super({ ...opts, port, bootstrap, nodes, filterNode })

    const { router, relayAddresses, persistent } = defaultCacheOpts(opts)

    this.defaultKeyPair = opts.keyPair || createKeyPair(opts.seed)
    this.listening = new Set()
    this.connectionKeepAlive =
      opts.connectionKeepAlive === false
        ? 0
        : opts.connectionKeepAlive || DEFAULTS.connectionKeepAlive

    // stats is inherited from dht-rpc so fwd the ones from there
    this.stats = {
      punches: { consistent: 0, random: 0, open: 0 },
      relaying: { attempts: 0, successes: 0, aborts: 0 },
      ...this.stats
    }
    this.rawStreams = new RawStreamSet(this)
    this.plugins = new Map()

    this._router = new Router(this, router)
    this._socketPool = new SocketPool(this, opts.host || '0.0.0.0')
    this._persistent = null
    this._validatedLocalAddresses = new Map()
    this._relayAddressesCache = new Cache(relayAddresses)

    this._deferRandomPunch = !!opts.deferRandomPunch
    this._lastRandomPunch = this._deferRandomPunch ? Date.now() : 0
    this._connectable = true
    this._randomPunchInterval = opts.randomPunchInterval || DEFAULTS.randomPunchInterval // min 20s between random punches...
    this._randomPunches = 0
    this._randomPunchLimit = 1 // set to one for extra safety for now

    this.once('persistent', () => {
      this._persistent = new Persistent(this, persistent)
      for (const plugin of this.plugins.values()) plugin.onpersistent()
    })

    this.on('network-change', () => {
      for (const server of this.listening) server.refresh()
    })

    this.on('network-update', () => {
      if (!this.online) return
      for (const server of this.listening) server.notifyOnline()
    })
  }

  static DEFAULTS = DEFAULTS

  connect(remotePublicKey, opts) {
    return connect(this, remotePublicKey, opts)
  }

  createServer(opts, onconnection) {
    if (typeof opts === 'function') return this.createServer({}, opts)
    if (opts && opts.onconnection) onconnection = opts.onconnection
    const s = new Server(this, opts)
    if (onconnection) s.on('connection', onconnection)
    return s
  }

  pool() {
    return new ConnectionPool(this)
  }

  async resume({ log = noop } = {}) {
    if (this._deferRandomPunch) this._lastRandomPunch = Date.now()
    await super.resume({ log })
    const resuming = []
    for (const server of this.listening) resuming.push(server.resume())
    log('Resuming hyperdht servers')
    await Promise.allSettled(resuming)
    log('Done, hyperdht fully resumed')
  }

  async suspend({ log = noop } = {}) {
    this._connectable = false // just so nothing gets connected during suspension
    const suspending = []
    for (const server of this.listening) suspending.push(server.suspend())
    log('Suspending all hyperdht servers')
    await Promise.allSettled(suspending)
    log('Done, clearing all raw streams')
    await this.rawStreams.clear()
    log('Done, suspending dht-rpc')
    await super.suspend({ log })
    log('Done, clearing raw streams again')
    await this.rawStreams.clear()
    log('Done, hyperdht fully suspended')
    this._connectable = true
  }

  async destroy({ force = false } = {}) {
    if (!force) {
      const closing = []
      for (const server of this.listening) closing.push(server.close())
      await Promise.allSettled(closing)
    }
    this._router.destroy()
    if (this._persistent) this._persistent.destroy()
    for (const plugin of this.plugins.values()) plugin.destroy()
    await this.rawStreams.clear()
    await this._socketPool.destroy()
    await super.destroy()
  }

  async validateLocalAddresses(addresses) {
    const list = []
    const socks = []
    const waiting = []

    for (const addr of addresses) {
      const { host } = addr

      if (this._validatedLocalAddresses.has(host)) {
        if (await this._validatedLocalAddresses.get(host)) {
          list.push(addr)
        }
        continue
      }

      const sock = this.udx.createSocket()
      try {
        sock.bind(0, host)
      } catch {
        this._validatedLocalAddresses.set(host, Promise.resolve(false))
        continue
      }

      socks.push(sock)

      // semi terrible heuristic until we proper fix local connections by racing them to the remote...
      const promise = new Promise((resolve) => {
        sock.on('message', () => resolve(true))
        setTimeout(() => resolve(false), 500)
        sock.trySend(b4a.alloc(1), sock.address().port, addr.host)
      })

      this._validatedLocalAddresses.set(host, promise)
      waiting.push(addr)
    }

    for (const addr of waiting) {
      const { host } = addr
      if (this._validatedLocalAddresses.has(host)) {
        if (await this._validatedLocalAddresses.get(host)) {
          list.push(addr)
        }
        continue
      }
    }

    for (const sock of socks) await sock.close()

    return list
  }

  findPeer(publicKey, opts = {}) {
    const target = opts.hash === false ? publicKey : hash(publicKey)
    opts = { ...opts, map: mapFindPeer }
    return this.query({ target, command: COMMANDS.FIND_PEER, value: null }, opts)
  }

  lookup(target, opts = {}) {
    opts = { ...opts, map: mapLookup }
    return this.query({ target, command: COMMANDS.LOOKUP, value: null }, opts)
  }

  lookupAndUnannounce(target, keyPair, opts = {}) {
    const unannounces = []
    const dht = this
    const userCommit = opts.commit || noop
    const signUnannounce = opts.signUnannounce || Persistent.signUnannounce

    if (this._persistent !== null) {
      // unlink self
      this._persistent.unannounce(target, keyPair.publicKey)
    }

    opts = { ...opts, map, commit }
    return this.query({ target, command: COMMANDS.LOOKUP, value: null }, opts)

    async function commit(reply, dht, query) {
      await Promise.all(unannounces) // can never fail, caught below
      return userCommit(reply, dht, query)
    }

    function map(reply) {
      const data = mapLookup(reply)

      if (!data || !data.token) return data

      let found = data.peers.length >= 20
      for (let i = 0; !found && i < data.peers.length; i++) {
        found = b4a.equals(data.peers[i].publicKey, keyPair.publicKey)
      }

      if (!found) return data

      if (!data.from.id) return data

      unannounces.push(
        dht
          ._requestUnannounce(keyPair, dht, target, data.token, data.from, signUnannounce)
          .catch(safetyCatch)
      )

      return data
    }
  }

  unannounce(target, keyPair, opts = {}) {
    return this.lookupAndUnannounce(target, keyPair, opts).finished()
  }

  announce(target, keyPair, relayAddresses, opts = {}) {
    const signAnnounce = opts.signAnnounce || Persistent.signAnnounce
    const bump = opts.bump || 0

    opts = { ...opts, commit }

    return opts.clear ? this.lookupAndUnannounce(target, keyPair, opts) : this.lookup(target, opts)

    function commit(reply, dht) {
      return dht._requestAnnounce(
        keyPair,
        dht,
        target,
        reply.token,
        reply.from,
        relayAddresses,
        signAnnounce,
        bump
      )
    }
  }

  async immutableGet(target, opts = {}) {
    opts = { ...opts, map: mapImmutable }

    const query = this.query({ target, command: COMMANDS.IMMUTABLE_GET, value: null }, opts)
    const check = b4a.allocUnsafe(32)

    for await (const node of query) {
      const { value } = node
      sodium.crypto_generichash(check, value)
      if (b4a.equals(check, target)) return node
    }

    return null
  }

  async immutablePut(value, opts = {}) {
    const target = b4a.allocUnsafe(32)
    sodium.crypto_generichash(target, value)

    opts = {
      ...opts,
      map: mapImmutable,
      commit(reply, dht) {
        return dht.request(
          { token: reply.token, target, command: COMMANDS.IMMUTABLE_PUT, value },
          reply.from
        )
      }
    }

    const query = this.query({ target, command: COMMANDS.IMMUTABLE_GET, value: null }, opts)
    await query.finished()

    return { hash: target, closestNodes: query.closestNodes }
  }

  async mutableGet(publicKey, opts = {}) {
    let refresh = opts.refresh || null
    let signed = null
    let result = null

    opts = { ...opts, map: mapMutable, commit: refresh ? commit : null }

    const target = b4a.allocUnsafe(32)
    sodium.crypto_generichash(target, publicKey)

    const userSeq = opts.seq || 0
    const query = this.query(
      { target, command: COMMANDS.MUTABLE_GET, value: c.encode(c.uint, userSeq) },
      opts
    )
    const latest = opts.latest !== false

    for await (const node of query) {
      if (result && node.seq <= result.seq) continue
      if (
        node.seq < userSeq ||
        !Persistent.verifyMutable(node.signature, node.seq, node.value, publicKey)
      )
        continue
      if (!latest) return node
      if (!result || node.seq > result.seq) result = node
    }

    return result

    function commit(reply, dht) {
      if (!signed && result && refresh) {
        if (refresh(result)) {
          signed = c.encode(m.mutablePutRequest, {
            publicKey,
            seq: result.seq,
            value: result.value,
            signature: result.signature
          })
        } else {
          refresh = null
        }
      }

      return signed
        ? dht.request(
            { token: reply.token, target, command: COMMANDS.MUTABLE_PUT, value: signed },
            reply.from
          )
        : Promise.resolve(null)
    }
  }

  async mutablePut(keyPair, value, opts = {}) {
    const signMutable = opts.signMutable || Persistent.signMutable

    const target = b4a.allocUnsafe(32)
    sodium.crypto_generichash(target, keyPair.publicKey)

    const seq = opts.seq || 0
    const signature = await signMutable(seq, value, keyPair)

    const signed = c.encode(m.mutablePutRequest, {
      publicKey: keyPair.publicKey,
      seq,
      value,
      signature
    })

    opts = {
      ...opts,
      map: mapMutable,
      commit(reply, dht) {
        return dht.request(
          { token: reply.token, target, command: COMMANDS.MUTABLE_PUT, value: signed },
          reply.from
        )
      }
    }

    // use seq = 0, for the query part here, as we don't care about the actual values
    const query = this.query(
      { target, command: COMMANDS.MUTABLE_GET, value: c.encode(c.uint, 0) },
      opts
    )
    await query.finished()

    return { publicKey: keyPair.publicKey, closestNodes: query.closestNodes, seq, signature }
  }

  onrequest(req) {
    switch (req.command) {
      case COMMANDS.PEER_HANDSHAKE: {
        this._router.onpeerhandshake(req)
        return true
      }
      case COMMANDS.PEER_HOLEPUNCH: {
        this._router.onpeerholepunch(req)
        return true
      }
    }

    if (this._persistent === null || this.id === null) return false

    switch (req.command) {
      case COMMANDS.FIND_PEER: {
        this._persistent.onfindpeer(req)
        return true
      }
      case COMMANDS.LOOKUP: {
        this._persistent.onlookup(req)
        return true
      }
      case COMMANDS.ANNOUNCE: {
        this._persistent.onannounce(req)
        return true
      }
      case COMMANDS.UNANNOUNCE: {
        this._persistent.onunannounce(req)
        return true
      }
      case COMMANDS.MUTABLE_PUT: {
        this._persistent.onmutableput(req)
        return true
      }
      case COMMANDS.MUTABLE_GET: {
        this._persistent.onmutableget(req)
        return true
      }
      case COMMANDS.IMMUTABLE_PUT: {
        this._persistent.onimmutableput(req)
        return true
      }
      case COMMANDS.IMMUTABLE_GET: {
        this._persistent.onimmutableget(req)
        return true
      }
      case COMMANDS.PLUGIN: {
        this._persistent.onplugin(req)
        return true
      }
    }

    return false
  }

  static keyPair(seed) {
    return createKeyPair(seed)
  }

  static hash(data) {
    return hash(data)
  }

  static connectRawStream(encryptedStream, rawStream, remoteId) {
    const stream = encryptedStream.rawStream

    if (!stream.connected) throw STREAM_NOT_CONNECTED()

    rawStream.connect(stream.socket, remoteId, stream.remotePort, stream.remoteHost)
  }

  createRawStream(opts) {
    return this.rawStreams.add(opts)
  }

  async _requestAnnounce(keyPair, dht, target, token, from, relayAddresses, sign, bump) {
    const ann = {
      peer: {
        publicKey: keyPair.publicKey,
        relayAddresses: relayAddresses || []
      },
      refresh: null,
      signature: null,
      bump
    }

    ann.signature = await sign(target, token, from.id, ann, keyPair)

    const value = c.encode(m.announce, ann)

    return dht.request(
      {
        token,
        target,
        command: COMMANDS.ANNOUNCE,
        value
      },
      from
    )
  }

  async _requestUnannounce(keyPair, dht, target, token, from, sign) {
    const unann = {
      peer: {
        publicKey: keyPair.publicKey,
        relayAddresses: []
      },
      signature: null
    }

    unann.signature = await sign(target, token, from.id, unann, keyPair)

    const value = c.encode(m.announce, unann)

    return dht.request(
      {
        token,
        target,
        command: COMMANDS.UNANNOUNCE,
        value
      },
      from
    )
  }

  register(name, plugin) {
    this.plugins.set(name, plugin)
    plugin.onregister(this)
  }
}

HyperDHT.BOOTSTRAP = BOOTSTRAP_NODES
HyperDHT.FIREWALL = FIREWALL

module.exports = HyperDHT

function mapLookup(node) {
  if (!node.value) return null

  try {
    const l = c.decode(m.lookupRawReply, node.value)

    return {
      token: node.token,
      from: node.from,
      to: node.to,
      peers: l.peers,
      bump: l.bump
    }
  } catch {
    return null
  }
}

function mapFindPeer(node) {
  if (!node.value) return null

  try {
    return {
      token: node.token,
      from: node.from,
      to: node.to,
      peer: c.decode(m.peer, node.value)
    }
  } catch {
    return null
  }
}

function mapImmutable(node) {
  if (!node.value) return null

  return {
    token: node.token,
    from: node.from,
    to: node.to,
    value: node.value
  }
}

function mapMutable(node) {
  if (!node.value) return null

  try {
    const { seq, value, signature } = c.decode(m.mutableGetResponse, node.value)

    return {
      token: node.token,
      from: node.from,
      to: node.to,
      seq,
      value,
      signature
    }
  } catch {
    return null
  }
}

function noop() {}

function filterNode(node) {
  // always skip these testnet nodes that got mixed in by accident, until they get updated
  return (
    !(node.port === 49738 && (node.host === '134.209.28.98' || node.host === '167.99.142.185')) &&
    !(node.port === 9400 && node.host === '35.233.47.252') &&
    !(node.host === '150.136.142.116')
  )
}

const defaultMaxSize = 65536
const defaultMaxAge = 20 * 60 * 1000 // 20 minutes

function defaultCacheOpts(opts) {
  const maxSize = opts.maxSize || defaultMaxSize
  const maxAge = opts.maxAge || defaultMaxAge

  return {
    router: {
      forwards: { maxSize, maxAge }
    },
    relayAddresses: { maxSize: Math.min(maxSize, 512), maxAge: 0 },
    persistent: {
      records: { maxSize, maxAge },
      refreshes: { maxSize, maxAge },
      mutables: {
        maxSize: (maxSize / 2) | 0,
        maxAge: opts.maxAge || 48 * 60 * 60 * 1000 // 48 hours
      },
      immutables: {
        maxSize: (maxSize / 2) | 0,
        maxAge: opts.maxAge || 48 * 60 * 60 * 1000 // 48 hours
      },
      bumps: { maxSize, maxAge }
    }
  }
}
const safetyCatch = require('safety-catch')
const c = require('compact-encoding')
const Signal = require('signal-promise')
const { encodeUnslab } = require('./encode')
const Sleeper = require('./sleeper')
const m = require('./messages')
const Persistent = require('./persistent')
const { COMMANDS } = require('./constants')

const MIN_ACTIVE = 3

module.exports = class Announcer {
  constructor(dht, keyPair, target, opts = {}) {
    this.dht = dht
    this.keyPair = keyPair
    this.target = target
    this.relays = []
    this.relayAddresses = []
    this.stopped = false
    this.suspended = false
    this.record = encodeUnslab(m.peer, { publicKey: keyPair.publicKey, relayAddresses: [] })
    this.online = new Signal()

    this._refreshing = false
    this._closestNodes = null
    this._active = null
    this._sleeper = new Sleeper()
    this._resumed = new Signal()
    this._signAnnounce = opts.signAnnounce || Persistent.signAnnounce
    this._signUnannounce = opts.signUnannounce || Persistent.signUnannounce
    this._updating = null
    this._activeQuery = null
    this._unannouncing = null

    this._serverRelays = [new Map(), new Map(), new Map()]
  }

  isRelay(addr) {
    const id = addr.host + ':' + addr.port
    const [a, b, c] = this._serverRelays
    return a.has(id) || b.has(id) || c.has(id)
  }

  async suspend({ log = noop } = {}) {
    if (this.suspended) return
    this.suspended = true

    log('Suspending announcer')

    // Suspend has its own sleep logic
    // so we don't want to hang on this one
    this.online.notify()

    if (this._activeQuery) this._activeQuery.destroy()

    this._sleeper.resume()
    if (this._updating) await this._updating
    log('Suspending announcer (post update)')

    if (this.suspended === false || this.stopped) return

    log('Suspending announcer (pre unannounce)')
    await this._unannounceCurrent()
    log('Suspending announcer (post unannounce)')
  }

  resume() {
    if (!this.suspended) return
    this.suspended = false

    this.refresh()
    this._sleeper.resume()
    this._resumed.notify()
  }

  refresh() {
    if (this.stopped) return
    this._refreshing = true
  }

  async start() {
    if (this.stopped) return
    this._active = this._runUpdate()
    await this._active
    if (this.stopped) return
    this._active = this._background()
  }

  async stop() {
    this.stopped = true
    this.online.notify() // Break out of the _background loop if we're offline
    this._sleeper.resume()
    this._resumed.notify()
    await this._active
    await this._unannounceCurrent()
  }

  async _unannounceCurrent() {
    while (this._unannouncing !== null) await this._unannouncing
    const un = (this._unannouncing = this._unannounceAll(this._serverRelays[2].values()))
    await this._unannouncing
    if (un === this._unannouncing) this._unannouncing = null
  }

  async _background() {
    while (!this.dht.destroyed && !this.stopped) {
      try {
        this._refreshing = false

        // ~5min +-
        for (let i = 0; i < 100 && !this.stopped && !this._refreshing && !this.suspended; i++) {
          const pings = []

          for (const node of this._serverRelays[2].values()) {
            pings.push(this.dht.ping(node))
          }

          const active = await resolved(pings)
          if (active < Math.min(pings.length, MIN_ACTIVE)) {
            this.refresh() // we lost too many relay nodes, retry all
          }

          if (this.stopped) return

          if (!this.suspended && !this._refreshing) await this._sleeper.pause(3000)
        }

        while (!this.stopped && this.suspended) await this._resumed.wait()

        if (!this.stopped) await this._runUpdate()

        while (!this.dht.online && !this.stopped && !this.suspended) {
          // Being offline can make _background repeat very quickly
          // So wait until we're back online
          await this.online.wait()
        }
      } catch (err) {
        safetyCatch(err)
      }
    }
  }

  async _runUpdate() {
    this._updating = this._update()
    await this._updating
    this._updating = null
  }

  async _update() {
    while (this._unannouncing) await this._unannouncing

    this._cycle()

    const q = (this._activeQuery = this.dht.findPeer(this.target, {
      hash: false,
      nodes: this._closestNodes
    }))

    try {
      await q.finished()
    } catch {
      // ignore failures...
    }

    this._activeQuery = null

    if (this.stopped || this.suspended) return

    const ann = []
    const replies = pickBest(q.closestReplies)

    const relays = []
    const relayAddresses = []

    if (!this.dht.firewalled) {
      const addr = this.dht.remoteAddress()
      if (addr) relayAddresses.push(addr)
    }

    for (const msg of replies) {
      ann.push(this._commit(msg, relays, relayAddresses))
    }

    await Promise.allSettled(ann)
    if (this.stopped || this.suspended) return

    this._closestNodes = q.closestNodes
    this.relays = relays
    this.relayAddresses = relayAddresses

    const removed = []
    for (const [key, value] of this._serverRelays[1]) {
      if (!this._serverRelays[2].has(key)) removed.push(value)
    }

    await this._unannounceAll(removed)
  }

  _unannounceAll(relays) {
    const unann = []
    for (const r of relays) unann.push(this._unannounce(r))
    return Promise.allSettled(unann)
  }

  async _unannounce(to) {
    const unann = {
      peer: {
        publicKey: this.keyPair.publicKey,
        relayAddresses: []
      },
      refresh: null,
      signature: null
    }

    const { from, token, value } = await this.dht.request(
      {
        token: null,
        command: COMMANDS.FIND_PEER,
        target: this.target,
        value: null
      },
      to
    )

    if (!token || !from.id || !value) return

    unann.signature = await this._signUnannounce(this.target, token, from.id, unann, this.keyPair)

    await this.dht.request(
      {
        token,
        command: COMMANDS.UNANNOUNCE,
        target: this.target,
        value: c.encode(m.announce, unann)
      },
      to
    )
  }

  async _commit(msg, relays, relayAddresses) {
    const ann = {
      peer: {
        publicKey: this.keyPair.publicKey,
        relayAddresses: []
      },
      refresh: null,
      signature: null
    }

    ann.signature = await this._signAnnounce(this.target, msg.token, msg.from.id, ann, this.keyPair)

    const res = await this.dht.request(
      {
        token: msg.token,
        command: COMMANDS.ANNOUNCE,
        target: this.target,
        value: c.encode(m.announce, ann)
      },
      msg.from
    )

    if (res.error !== 0) return

    if (relayAddresses.length < 3) relayAddresses.push({ host: msg.from.host, port: msg.from.port })
    relays.push({ relayAddress: msg.from, peerAddress: msg.to })

    this._serverRelays[2].set(msg.from.host + ':' + msg.from.port, msg.from)
  }

  _cycle() {
    const tmp = this._serverRelays[0]
    this._serverRelays[0] = this._serverRelays[1]
    this._serverRelays[1] = this._serverRelays[2]
    this._serverRelays[2] = tmp
    tmp.clear()
  }
}

function resolved(ps) {
  let replied = 0
  let ticks = ps.length + 1

  return new Promise((resolve) => {
    for (const p of ps) p.then(push, tick)
    tick()

    function push(v) {
      replied++
      tick()
    }

    function tick() {
      if (--ticks === 0) resolve(replied)
    }
  })
}

function pickBest(replies) {
  // TODO: pick the ones closest to us RTT wise
  return replies.slice(0, 3)
}

function noop() {}
const NoiseSecretStream = require('@hyperswarm/secret-stream')
const b4a = require('b4a')
const relay = require('blind-relay')
const { isReserved, isBogon } = require('bogon')
const safetyCatch = require('safety-catch')
const unslab = require('unslab')
const Semaphore = require('./semaphore')
const NoiseWrap = require('./noise-wrap')
const SecurePayload = require('./secure-payload')
const Holepuncher = require('./holepuncher')
const Sleeper = require('./sleeper')
const {
  clearRelayTimeout,
  confirmDirectUpgrade,
  destroyRelayConnection
} = require('./relay-connection')
const { FIREWALL, ERROR } = require('./constants')
const { unslabbedHash } = require('./crypto')
const {
  CANNOT_HOLEPUNCH,
  HANDSHAKE_INVALID,
  HOLEPUNCH_ABORTED,
  HOLEPUNCH_INVALID,
  HOLEPUNCH_PROBE_TIMEOUT,
  HOLEPUNCH_DOUBLE_RANDOMIZED_NATS,
  PEER_CONNECTION_FAILED,
  PEER_NOT_FOUND,
  REMOTE_ABORTED,
  REMOTE_NOT_HOLEPUNCHABLE,
  REMOTE_NOT_HOLEPUNCHING,
  SERVER_ERROR,
  SERVER_INCOMPATIBLE,
  RELAY_ABORTED,
  SUSPENDED
} = require('./errors')
const { decode } = require('hypercore-id-encoding')
const HyperDHTAddress = require('hyperdht-address')

module.exports = function connect(dht, publicKey, opts = {}) {
  const pool = opts.pool || null

  const { key, nodes: providedNodes } = HyperDHTAddress.decode(
    b4a.isBuffer(publicKey) ? publicKey : decode(publicKey)
  )
  publicKey = key

  if (pool && pool.has(publicKey)) return pool.get(publicKey)

  publicKey = unslab(publicKey)

  opts.relayAddresses = opts.relayAddresses || providedNodes || []
  const keyPair = opts.keyPair || dht.defaultKeyPair
  const relayThrough = selectRelay(opts.relayThrough || null)
  const encryptedSocket = (opts.createSecretStream || defaultCreateSecretStream)(true, null, {
    publicKey: keyPair.publicKey,
    remotePublicKey: publicKey,
    autoStart: false,
    keepAlive: dht.connectionKeepAlive
  })

  // in case a socket is made during suspended state, destroy it immediately
  if (dht.suspended || !dht._connectable) {
    encryptedSocket.destroy(SUSPENDED())
    return encryptedSocket
  }

  if (pool) pool._attachStream(encryptedSocket, false)

  const id = b4a.toString(publicKey, 'hex')
  const c = {
    id,
    dht,
    session: dht.session(),
    relayAddresses: opts.relayAddresses,
    remoteRelayAddresses: [],
    pool,
    round: 0,
    target: unslabbedHash(publicKey),
    remotePublicKey: publicKey,
    reusableSocket: !!opts.reusableSocket,
    handshake: (opts.createHandshake || defaultCreateHandshake)(keyPair, publicKey),
    request: null,
    requesting: false,
    lan: opts.localConnection !== false,
    firewall: FIREWALL.UNKNOWN,
    rawStream: dht.createRawStream({ framed: true, firewall }),
    connect: null,
    query: null,
    puncher: null,
    payload: null,
    passiveConnectTimeout: null,
    serverSocket: null,
    serverAddress: null,
    onsocket: null,
    sleeper: new Sleeper(),
    encryptedSocket,

    // Relay state
    relayTimeout: null,
    relayThrough,
    relayToken: relayThrough ? relay.token() : null,
    relaySocket: null,
    relayClient: null,
    relayPaired: false,
    validUpgrade: true,
    relayKeepAlive: opts.relayKeepAlive || 5000
  }

  // If the raw stream receives an error signal pre connect (ie from the firewall hook), make sure
  // to forward that to the encrypted socket for proper teardown
  c.rawStream.on('error', autoDestroy)
  c.rawStream.once('connect', () => {
    c.rawStream.removeListener('error', autoDestroy)
  })

  encryptedSocket.on('close', function () {
    if (c.passiveConnectTimeout) clearPassiveConnectTimeout(c)
    if (c.query) c.query.destroy()
    if (c.puncher) c.puncher.destroy()
    if (c.rawStream) c.rawStream.destroy()
    c.session.destroy()
    c.sleeper.resume()
  })

  // Safe to run in the background - never throws
  if (dht.suspended) encryptedSocket.destroy(SUSPENDED())
  else connectAndHolepunch(c, opts)

  return encryptedSocket

  function autoDestroy(err) {
    maybeDestroyEncryptedSocket(c, err)
  }

  function firewall(socket, port, host) {
    // Check if the traffic originated from the socket on which we're expecting relay traffic. If so,
    // we haven't hole punched yet and the other side is just sending us traffic through the relay.
    if (c.relaySocket && isRelay(c.relaySocket, socket, port, host)) {
      c.validUpgrade = false
      return false
    }

    c.validUpgrade = true
    if (c.onsocket) {
      c.onsocket(socket, port, host)
    } else {
      c.serverSocket = socket
      c.serverAddress = { port, host }
    }
    return false
  }
}

function isDone(c) {
  // we are destroying or the puncher is connected - done
  if (c.encryptedSocket.destroying || !!(c.puncher && c.puncher.connected)) {
    return true
  }
  // not destroying, but no raw stream - def not done
  if (c.encryptedSocket.rawStream === null) {
    return false
  }
  // we are relayed, but the puncher is not done yet
  if (c.relaySocket && !!(c.puncher && !c.puncher.connected && !c.puncher.destroyed)) {
    return false
  }
  // we are done
  return true
}

async function retryRoute(c, route) {
  const ref = c.dht._socketPool.lookup(route.socket)

  if (!ref) {
    if (route.socket === c.dht.socket) {
      await connectThroughNode(c, route.address, c.dht.socket)
    }
    return
  }

  ref.active()

  try {
    await connectThroughNode(c, route.address, route.socket)
  } catch {
    // if error, just ignore, and continue through the existing strat
  }

  ref.inactive()
}

async function connectAndHolepunch(c, opts) {
  const route = c.reusableSocket ? c.dht._socketPool.routes.get(c.remotePublicKey) : null

  if (route) {
    await retryRoute(c, route)
    if (isDone(c)) return
  }

  await findAndConnect(c, opts)
  if (isDone(c)) return

  if (!c.connect) {
    // TODO: just a quick fix for now, should retry prob
    maybeDestroyEncryptedSocket(c, HANDSHAKE_INVALID())
    return
  }

  await holepunch(c, opts)
}

function getFirstRemoteAddress(addrs, serverAddress) {
  for (const addr of addrs) {
    if (isBogon(addr.host)) continue
    return addr
  }

  return serverAddress
}

async function holepunch(c, opts) {
  let { relayAddress, serverAddress, clientAddress, payload } = c.connect

  const remoteHolepunchable = !!(payload.holepunch && payload.holepunch.relays.length)
  const relayed = diffAddress(serverAddress, relayAddress)

  if (payload.firewall === FIREWALL.OPEN || (relayed && !remoteHolepunchable)) {
    const addr = getFirstRemoteAddress(payload.addresses4, serverAddress)
    if (addr) {
      const socket = c.dht.socket
      c.dht.stats.punches.open++
      c.onsocket(socket, addr.port, addr.host)
      return
    }
    // TODO: check all addresses also obvs
  }

  const onabort = () => {
    c.session.destroy()
    maybeDestroyEncryptedSocket(c, HOLEPUNCH_ABORTED())
  }

  if (c.firewall === FIREWALL.OPEN) {
    c.passiveConnectTimeout = setTimeout(onabort, 10000)
    return
  }

  // Race the LAN shortcut with normal holepunch when possible. A blocked LAN ping
  // should not abort a connection that can still holepunch. If the remote is not
  // holepunchable, the LAN ping is the only remaining path.
  if (c.lan && relayed && clientAddress.host === serverAddress.host) {
    const serverAddresses = payload.addresses4.filter(onlyNonReserved)

    if (serverAddresses.length > 0) {
      const myAddresses = Holepuncher.localAddresses(c.dht.io.serverSocket)
      const addr = Holepuncher.matchAddress(myAddresses, serverAddresses) || serverAddresses[0]

      const socket = c.dht.io.serverSocket
      c.dht.ping(addr).then(onlanconnect, onlanerror)
      if (!remoteHolepunchable) return

      function onlanconnect() {
        // LAN and holepunch completions both converge through onsocket,
        // which claims c.rawStream once and ignores later winners.
        if (isDone(c)) return
        c.onsocket(socket, addr.port, addr.host)
      }

      function onlanerror() {
        if (!remoteHolepunchable) {
          maybeDestroyEncryptedSocket(c, HOLEPUNCH_ABORTED())
        }
      }
    }
  }

  if (!remoteHolepunchable) {
    maybeDestroyEncryptedSocket(c, CANNOT_HOLEPUNCH())
    return
  }

  c.puncher = new Holepuncher(c.dht, c.session, true, payload.firewall)

  c.puncher.onconnect = c.onsocket
  c.puncher.onabort = onabort

  const serverRelay = pickServerRelay(payload.holepunch.relays, relayAddress)

  // Begin holepunching!

  let probe
  try {
    probe = await probeRound(c, opts.fastOpen === false ? null : serverAddress, serverRelay, true)
  } catch (err) {
    destroyPuncher(c)
    // TODO: we should retry here with some of the other relays, bail for now
    maybeDestroyEncryptedSocket(c, err)
    return
  }

  if (isDone(c) || !probe) return
  const { token, peerAddress } = probe

  // If the relay the server picked is the same as the relay the client picked,
  // then we can use the peerAddress that round one indicates the server wants to use.
  // This shaves off a roundtrip if the server chose to reroll its socket due to some NAT
  // issue with the first one it picked (ie mobile nat inconsistencies...).
  // If the relays were different, then the server would not have a UDP session open on this address
  // to the client relay, which round2 uses.
  if (
    !diffAddress(serverRelay.relayAddress, relayAddress) &&
    diffAddress(serverAddress, peerAddress)
  ) {
    serverAddress = peerAddress
    await c.puncher.openSession(serverAddress)
    if (isDone(c)) return
  }

  // TODO: still continue here if a local connection might work, but then do not holepunch...
  if (
    opts.holepunch &&
    !opts.holepunch(
      c.puncher.remoteFirewall,
      c.puncher.nat.firewall,
      c.puncher.remoteAddresses,
      c.puncher.nat.addresses
    )
  ) {
    await abort(c, serverRelay, HOLEPUNCH_ABORTED('Client aborted holepunch'))
    return
  }

  try {
    await roundPunch(c, serverAddress, token, relayAddress, serverRelay, false)
  } catch (err) {
    destroyPuncher(c)
    // TODO: retry with another relay?
    maybeDestroyEncryptedSocket(c, err)
  }
}

async function connectThroughNodes(c, addresses, socket) {
  for (const address of addresses) {
    if (isDone(c) || c.connect) return

    c.remoteRelayAddresses.push(address)
    await connectThroughNode(c, address, socket)
  }
}

async function findAndConnect(c, opts) {
  let attempts = 0
  let relayAddresses =
    opts.relayAddresses && opts.relayAddresses.length ? opts.relayAddresses : null

  if (!relayAddresses) {
    const cachedRelayAddresses = c.dht._relayAddressesCache.get(c.id)
    if (cachedRelayAddresses) relayAddresses = cachedRelayAddresses
  }

  if (c.dht._persistent) {
    // check if we know the route ourself...
    const route = c.dht._router.get(c.target)
    if (route && route.relay !== null) {
      relayAddresses = [{ host: route.relay.host, port: route.relay.port }]
    }
  }

  // 2 is how many parallel connect attempts we want to do, we can make this configurable
  const preConnect = relayAddresses !== null && relayAddresses.length > 0
  const sem = new Semaphore(preConnect ? 3 : 2)
  const signal = sem.signal.bind(sem)
  const tries = relayAddresses !== null ? 2 : 1

  if (preConnect) {
    await sem.wait()
    connectThroughNodes(c, relayAddresses, null).then(signal, signal)
  }

  try {
    for (let i = 0; i < tries && !isDone(c) && !c.connect; i++) {
      c.query = c.dht.findPeer(c.target, {
        hash: false,
        session: c.session,
        nodes: relayAddresses,
        retries: 3
      })

      for await (const data of c.query) {
        await sem.wait()
        if (isDone(c)) return

        if (c.connect) {
          sem.signal()
          break
        }

        // Skip node already run via preConnect
        if (preConnect && relayAddresses && isRelayAddress(relayAddresses, data)) {
          sem.signal()
          continue
        }

        c.remoteRelayAddresses.push(data.from)
        attempts++
        connectThroughNode(c, data.from, null).then(signal, signal)
      }

      relayAddresses = null

      if (attempts > 0) await sem.flush()
    }

    c.query = null
    if (isDone(c)) return

    // flush the semaphore
    await sem.flush()
    if (isDone(c)) return
  } catch (err) {
    c.query = null
    maybeDestroyEncryptedSocket(c, err)
    return
  }

  if (!c.connect) {
    maybeDestroyEncryptedSocket(c, attempts ? PEER_CONNECTION_FAILED() : PEER_NOT_FOUND())
  }
}

async function connectThroughNode(c, address, socket) {
  if (!c.requesting) {
    // If we have a stable server address, send it over now
    const addr = c.dht.remoteAddress()
    const localAddrs = c.lan ? Holepuncher.localAddresses(c.dht.io.serverSocket) : null
    const addresses4 = []

    if (addr) addresses4.push(addr)
    if (localAddrs) addresses4.push(...localAddrs)

    c.firewall = addr ? FIREWALL.OPEN : FIREWALL.UNKNOWN
    c.requesting = true
    c.request = await c.handshake.send({
      error: ERROR.NONE,
      firewall: c.firewall,
      holepunch: null,
      addresses4,
      addresses6: [],
      udx: {
        reusableSocket: c.reusableSocket,
        id: c.rawStream.id,
        seq: 0
      },
      secretStream: {},
      relayThrough: c.relayThrough ? { publicKey: c.relayThrough, token: c.relayToken } : null
    })
    if (isDone(c)) return
  }

  const { serverAddress, clientAddress, relayed, noise } = await c.dht._router.peerHandshake(
    c.target,
    { noise: c.request, socket, session: c.session },
    address
  )
  if (isDone(c) || c.connect) return

  const payload = await c.handshake.recv(noise)
  if (isDone(c) || !payload) return

  if (payload.version !== 1) {
    maybeDestroyEncryptedSocket(c, SERVER_INCOMPATIBLE())
    return
  }
  if (payload.error !== ERROR.NONE) {
    maybeDestroyEncryptedSocket(c, SERVER_ERROR())
    return
  }
  if (!payload.udx) {
    maybeDestroyEncryptedSocket(c, SERVER_ERROR('Server did not send UDX data'))
    return
  }

  const hs = c.handshake.final()

  c.handshake = null
  c.request = null
  c.requesting = false
  c.connect = {
    relayed,
    relayAddress: address,
    clientAddress,
    serverAddress,
    payload
  }

  c.payload = new SecurePayload(hs.holepunchSecret)

  c.onsocket = function (socket, port, host) {
    if (c.rawStream === null) return // Already hole punched

    if (c.rawStream.connected) {
      const rawStream = c.rawStream
      const remoteChanging = rawStream.changeRemote(socket, c.connect.payload.udx.id, port, host)
      confirmDirectUpgrade(c, rawStream, remoteChanging)
    } else {
      // cache the relay addrs for a future reconnect, we prefer the remote one so they
      // can give us the correct ones from their pov
      if (payload.relayAddresses && payload.relayAddresses.length) {
        c.dht._relayAddressesCache.set(c.id, payload.relayAddresses)
      } else if (c.remoteRelayAddresses.length) {
        c.dht._relayAddressesCache.set(c.id, c.remoteRelayAddresses)
      }

      c.rawStream.connect(socket, c.connect.payload.udx.id, port, host)
      c.encryptedSocket.start(c.rawStream, { handshake: hs })
    }

    if (c.reusableSocket && payload.udx.reusableSocket) {
      c.dht._socketPool.routes.add(c.remotePublicKey, c.rawStream)
    }

    if (c.puncher) {
      c.puncher.onabort = noop
      c.puncher.destroy()
    }

    if (c.passiveConnectTimeout) {
      clearPassiveConnectTimeout(c)
    }

    c.rawStream = null
  }

  if (payload.relayThrough || c.relayThrough) {
    relayConnection(c, c.relayThrough, payload, hs)
  }

  if (c.serverSocket) {
    c.onsocket(c.serverSocket, c.serverAddress.port, c.serverAddress.host)
    return
  }

  if (!relayed) {
    c.onsocket(socket || c.dht.socket, address.port, address.host)
  }

  c.session.destroy()
}

async function updateHolepunch(c, peerAddress, relayAddr, payload) {
  const holepunch = await c.dht._router.peerHolepunch(
    c.target,
    {
      id: c.connect.payload.holepunch.id,
      payload: c.payload.encrypt(payload),
      peerAddress,
      socket: c.puncher.socket,
      session: c.session
    },
    relayAddr
  )

  if (isDone(c)) return null

  const remotePayload = c.payload.decrypt(holepunch.payload)
  if (!remotePayload) {
    throw HOLEPUNCH_INVALID()
  }

  const { error, firewall, punching, addresses, remoteToken } = remotePayload

  if (error === ERROR.TRY_LATER && c.relayToken && payload.punching) {
    return {
      tryLater: true,
      ...holepunch,
      payload: remotePayload
    }
  }

  if (error !== ERROR.NONE) {
    throw REMOTE_ABORTED('Remote aborted with error code ' + error)
  }

  const echoed = !!(remoteToken && payload.token && b4a.equals(remoteToken, payload.token))

  c.puncher.updateRemote({
    punching,
    firewall,
    addresses,
    verified: echoed ? peerAddress.host : null
  })

  return {
    tryLater: false,
    ...holepunch,
    payload: remotePayload
  }
}

async function probeRound(c, serverAddress, serverRelay, retry) {
  // Open a quick low ttl session against what we think is the server
  if (serverAddress) await c.puncher.openSession(serverAddress)

  if (isDone(c)) return null

  const reply = await updateHolepunch(c, serverRelay.peerAddress, serverRelay.relayAddress, {
    error: ERROR.NONE,
    firewall: c.puncher.nat.firewall,
    round: c.round++,
    connected: false,
    punching: false,
    addresses: c.puncher.nat.addresses,
    remoteAddress: serverAddress,
    token: null,
    remoteToken: null
  })

  if (isDone(c) || !reply) return null

  const { peerAddress } = reply
  const { address, token } = reply.payload

  c.puncher.nat.add(reply.to, reply.from)

  // Open another quick low ttl session against what the server says their address is,
  // if they haven't said they are random yet
  if (
    c.puncher.remoteFirewall < FIREWALL.RANDOM &&
    address &&
    address.host &&
    address.port &&
    diffAddress(address, serverAddress)
  ) {
    await c.puncher.openSession(address)
    if (isDone(c)) return null
  }

  // If the remote told us they didn't know their nat firewall yet, give them a chance to figure it out
  // They might say this to see if the "fast mode" punch comes through first.
  if (c.puncher.remoteFirewall === FIREWALL.UNKNOWN) {
    await c.sleeper.pause(1000)
    if (isDone(c)) return null
  }

  let stable = await c.puncher.analyze(false)
  if (isDone(c)) return null

  // If the socket seems unstable, try to make it stable by setting the "allowReopen" flag
  // Mostly relevant for mobile networks
  if (!stable) {
    stable = await c.puncher.analyze(true)
    if (isDone(c)) return null
    if (stable) return probeRound(c, serverAddress, serverRelay, false)
  }

  if ((c.puncher.remoteFirewall === FIREWALL.UNKNOWN || !token) && retry) {
    return probeRound(c, serverAddress, serverRelay, false)
  }

  if (
    c.puncher.remoteFirewall === FIREWALL.UNKNOWN ||
    c.puncher.nat.firewall === FIREWALL.UNKNOWN
  ) {
    await abort(c, serverRelay, HOLEPUNCH_PROBE_TIMEOUT())
    return null
  }

  if (c.puncher.remoteFirewall >= FIREWALL.RANDOM && c.puncher.nat.firewall >= FIREWALL.RANDOM) {
    await abort(c, serverRelay, HOLEPUNCH_DOUBLE_RANDOMIZED_NATS())
    return null
  }

  return { token, peerAddress }
}

async function roundPunch(c, serverAddress, remoteToken, clientRelay, serverRelay, delayed) {
  // We are gossiping our final NAT status to the other peer now
  // so make sure we don't update our local view for now as that can make things weird
  c.puncher.nat.freeze()

  const isRandom =
    c.puncher.remoteFirewall >= FIREWALL.RANDOM || c.puncher.nat.firewall >= FIREWALL.RANDOM
  if (isRandom) {
    while (
      c.dht._randomPunches >= c.dht._randomPunchLimit ||
      Date.now() - c.dht._lastRandomPunch < c.dht._randomPunchInterval
    ) {
      // if no relay can help, bail
      if (!c.relayToken) throw HOLEPUNCH_ABORTED()

      if (!delayed) {
        delayed = true
        await updateHolepunch(c, serverAddress, clientRelay, {
          error: ERROR.NONE,
          firewall: c.puncher.nat.firewall,
          round: c.round++,
          connected: false,
          punching: false,
          addresses: c.puncher.nat.addresses,
          remoteAddress: null,
          token: c.payload.token(serverAddress),
          remoteToken
        })
        if (isDone(c)) return
      }

      await tryLater(c)
      if (isDone(c)) return
    }
  }

  // increment now, so we can commit to punching
  if (isRandom) c.dht._randomPunches++

  let reply

  try {
    // if delayed switch to the servers chosen relay - we validated anyway
    reply = await updateHolepunch(
      c,
      delayed ? serverRelay.peerAddress : serverAddress,
      delayed ? serverRelay.relayAddress : clientRelay,
      {
        error: ERROR.NONE,
        firewall: c.puncher.nat.firewall,
        round: c.round++,
        connected: false,
        punching: true,
        addresses: c.puncher.nat.addresses,
        remoteAddress: null,
        token: delayed ? null : c.payload.token(serverAddress),
        remoteToken
      }
    )
  } finally {
    // decrement as punch increments for us
    if (isRandom) c.dht._randomPunches--
  }

  if (isDone(c)) return
  if (!reply) return

  if (reply.tryLater) {
    await tryLater(c)
    if (isDone(c)) return
    return roundPunch(c, serverAddress, remoteToken, clientRelay, serverRelay, true)
  }

  if (!c.puncher.remoteHolepunching) {
    throw REMOTE_NOT_HOLEPUNCHING()
  }

  if (!(await c.puncher.punch())) {
    throw REMOTE_NOT_HOLEPUNCHABLE()
  }
}

async function tryLater(c) {
  if (!c.relayToken) throw HOLEPUNCH_ABORTED()
  await c.sleeper.pause(10000 + Math.round(Math.random() * 10000))
}

function maybeDestroyEncryptedSocket(c, err) {
  if (isDone(c)) return
  if (c.encryptedSocket.rawStream) return
  if (c.relaySocket) return // waiting for the relay
  if (c.puncher && !c.puncher.destroyed) return // waiting for the puncher
  c.session.destroy()
  c.encryptedSocket.destroy(err)
}

async function abort(c, { peerAddress, relayAddress }, err) {
  try {
    await updateHolepunch(c, peerAddress, relayAddress, {
      error: ERROR.ABORTED,
      firewall: FIREWALL.UNKNOWN,
      round: c.round++,
      connected: false,
      punching: false,
      addresses: null,
      remoteAddress: null,
      token: null,
      remoteToken: null
    })
  } catch (err) {
    safetyCatch(err)
  }

  destroyPuncher(c)
  maybeDestroyEncryptedSocket(c, err)
}

function relayConnection(c, relayThrough, payload, hs) {
  let isInitiator
  let publicKey
  let token

  if (payload.relayThrough) {
    isInitiator = false
    publicKey = payload.relayThrough.publicKey
    token = payload.relayThrough.token
  } else {
    isInitiator = true
    publicKey = relayThrough
    token = c.relayToken
  }

  c.relayToken = token
  c.relaySocket = c.dht.connect(publicKey)
  c.relaySocket.setKeepAlive(c.relayKeepAlive)
  c.relayClient = relay.Client.from(c.relaySocket, { id: c.relaySocket.publicKey })
  c.relayTimeout = setTimeout(onabort, 15000, null)

  c.relayClient.pair(isInitiator, token, c.rawStream).on('error', onabort).on('data', ondata)

  function ondata(remoteId) {
    if (c.relayTimeout) clearRelayTimeout(c)
    if (c.rawStream === null) {
      onabort(null)
      return
    }

    c.relayPaired = true

    const { remotePort, remoteHost, socket } = c.relaySocket.rawStream

    c.rawStream
      .on('close', () => destroyRelayConnection(c))
      .connect(socket, remoteId, remotePort, remoteHost)

    c.encryptedSocket.start(c.rawStream, { handshake: hs })
  }

  function onabort(err) {
    destroyRelayConnection(c)
    maybeDestroyEncryptedSocket(c, err || RELAY_ABORTED())
  }
}

function clearPassiveConnectTimeout(c) {
  clearTimeout(c.passiveConnectTimeout)
  c.passiveConnectTimeout = null
}

function destroyPuncher(c) {
  if (c.puncher) c.puncher.destroy()
  c.session.destroy()
}

function pickServerRelay(relays, clientRelay) {
  for (const r of relays) {
    if (!diffAddress(r.relayAddress, clientRelay)) return r
  }
  return relays[0]
}

function diffAddress(a, b) {
  return a.host !== b.host || a.port !== b.port
}

function defaultCreateHandshake(keyPair, remotePublicKey) {
  return new NoiseWrap(keyPair, remotePublicKey)
}

function defaultCreateSecretStream(isInitiator, rawStream, opts) {
  return new NoiseSecretStream(isInitiator, rawStream, opts)
}

function onlyNonReserved(addr) {
  return !isReserved(addr.host)
}

function isRelay(relaySocket, socket, port, host) {
  const stream = relaySocket.rawStream
  if (!stream) return false
  if (stream.socket !== socket) return false
  return port === stream.remotePort && host === stream.remoteHost
}

function selectRelay(relayThrough) {
  if (typeof relayThrough === 'function') relayThrough = relayThrough()
  if (relayThrough === null) return null
  if (Array.isArray(relayThrough))
    return relayThrough[Math.floor(Math.random() * relayThrough.length)]
  return relayThrough
}

function isRelayAddress(relayAddresses, data) {
  for (const node of relayAddresses) {
    if (node.host === data.from.host && node.port === data.from.port) return true
  }

  return false
}

function noop() {}
const EventEmitter = require('events')
const b4a = require('b4a')
const errors = require('./errors')

module.exports = class ConnectionPool extends EventEmitter {
  constructor(dht) {
    super()

    this._dht = dht
    this._servers = new Map()
    this._connecting = new Map()
    this._connections = new Map()
  }

  _attachServer(server) {
    const keyString = b4a.toString(server.publicKey, 'hex')

    this._servers.set(keyString, server)

    server
      .on('close', () => {
        this._servers.delete(keyString)
      })
      .on('connection', (socket) => {
        this._attachStream(socket, true)
      })
  }

  _attachStream(stream, opened) {
    const existing = this.get(stream.remotePublicKey)

    if (existing) {
      const keepNew =
        stream.isInitiator === existing.isInitiator ||
        b4a.compare(stream.publicKey, stream.remotePublicKey) > 0

      if (keepNew) {
        let closed = false

        const onclose = () => {
          closed = true
        }

        existing
          .on('error', noop)
          .on('close', () => {
            if (closed) return

            stream.off('error', noop).off('close', onclose)

            this._attachStream(stream, opened)
          })
          .destroy(errors.DUPLICATE_CONNECTION())

        stream.on('error', noop).on('close', onclose)
      } else {
        stream.on('error', noop).destroy(errors.DUPLICATE_CONNECTION())
      }

      return
    }

    const session = new ConnectionRef(this, stream)

    const keyString = b4a.toString(stream.remotePublicKey, 'hex')

    if (opened) {
      this._connections.set(keyString, session)

      stream.on('close', () => {
        this._connections.delete(keyString)
      })

      this.emit('connection', stream, session)
    } else {
      this._connecting.set(keyString, session)

      stream
        .on('error', noop)
        .on('close', () => {
          if (opened) this._connections.delete(keyString)
          else this._connecting.delete(keyString)
        })
        .on('open', () => {
          opened = true

          this._connecting.delete(keyString)
          this._connections.set(keyString, session)

          stream.off('error', noop)

          this.emit('connection', stream, session)
        })
    }

    return session
  }

  get connecting() {
    return this._connecting.size
  }

  get connections() {
    return this._connections.values()
  }

  has(publicKey) {
    const keyString = b4a.toString(publicKey, 'hex')

    return this._connections.has(keyString) || this._connecting.has(keyString)
  }

  get(publicKey) {
    const keyString = b4a.toString(publicKey, 'hex')

    const existing = this._connections.get(keyString) || this._connecting.get(keyString)

    return existing?._stream || null
  }
}

class ConnectionRef {
  constructor(pool, stream) {
    this._pool = pool
    this._stream = stream
    this._refs = 0
  }

  active() {
    this._refs++
  }

  inactive() {
    this._refs--
  }

  release() {
    this._stream.destroy()
  }
}

function noop() {}
const crypto = require('hypercore-crypto')

const COMMANDS = (exports.COMMANDS = {
  PEER_HANDSHAKE: 0,
  PEER_HOLEPUNCH: 1,
  FIND_PEER: 2,
  LOOKUP: 3,
  ANNOUNCE: 4,
  UNANNOUNCE: 5,
  MUTABLE_PUT: 6,
  MUTABLE_GET: 7,
  IMMUTABLE_PUT: 8,
  IMMUTABLE_GET: 9,
  PLUGIN: 10
})

exports.BOOTSTRAP_NODES = [
  '88.99.3.86@node1.hyperdht.org:49737',
  '142.93.90.113@node2.hyperdht.org:49737',
  '138.68.147.8@node3.hyperdht.org:49737'
]

exports.FIREWALL = {
  UNKNOWN: 0,
  OPEN: 1,
  CONSISTENT: 2,
  RANDOM: 3
}

exports.ERROR = {
  // noise / connection related
  NONE: 0,
  ABORTED: 1,
  VERSION_MISMATCH: 2,
  TRY_LATER: 3,
  // dht related
  SEQ_REUSED: 16,
  SEQ_TOO_LOW: 17
}

const [
  NS_ANNOUNCE,
  NS_UNANNOUNCE,
  NS_MUTABLE_PUT,
  NS_PEER_HANDSHAKE,
  NS_PEER_HOLEPUNCH,
  NS_PLUGIN
] = crypto.namespace('hyperswarm/dht', [
  COMMANDS.ANNOUNCE,
  COMMANDS.UNANNOUNCE,
  COMMANDS.MUTABLE_PUT,
  COMMANDS.PEER_HANDSHAKE,
  COMMANDS.PEER_HOLEPUNCH,
  COMMANDS.PLUGIN
])

exports.NS = {
  ANNOUNCE: NS_ANNOUNCE,
  UNANNOUNCE: NS_UNANNOUNCE,
  MUTABLE_PUT: NS_MUTABLE_PUT,
  PEER_HANDSHAKE: NS_PEER_HANDSHAKE,
  PEER_HOLEPUNCH: NS_PEER_HOLEPUNCH,
  PLUGIN: NS_PLUGIN
}
const sodium = require('sodium-universal')
const b4a = require('b4a')

function hash(data) {
  const out = b4a.allocUnsafe(32)
  sodium.crypto_generichash(out, data)
  return out
}

function unslabbedHash(data) {
  const out = b4a.allocUnsafeSlow(32)
  sodium.crypto_generichash(out, data)
  return out
}

function createKeyPair(seed) {
  const publicKey = b4a.alloc(32)
  const secretKey = b4a.alloc(64)
  if (seed) sodium.crypto_sign_seed_keypair(publicKey, secretKey, seed)
  else sodium.crypto_sign_keypair(publicKey, secretKey)
  return { publicKey, secretKey }
}

module.exports = {
  hash,
  unslabbedHash,
  createKeyPair
}
const b4a = require('b4a')
const cenc = require('compact-encoding')

function encodeUnslab(enc, m) {
  // Faster than unslab(c.encode(enc, data)) because it avoids the mem copy.
  // Makes sense to put in compact-encoding when we need it in other modules too
  const state = cenc.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafeSlow(state.end)
  enc.encode(state, m)
  return state.buffer
}

module.exports = {
  encodeUnslab
}
module.exports = class DHTError extends Error {
  constructor(msg, code, fn = DHTError) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'DHTError'
  }

  static BAD_HANDSHAKE_REPLY(msg = 'Bad handshake reply') {
    return new DHTError(msg, 'BAD_HANDSHAKE_REPLY', DHTError.BAD_HANDSHAKE_REPLY)
  }

  static BAD_HOLEPUNCH_REPLY(msg = 'Bad holepunch reply') {
    return new DHTError(msg, 'BAD_HOLEPUNCH_REPLY', DHTError.BAD_HOLEPUNCH_REPLY)
  }

  static HOLEPUNCH_ABORTED(msg = 'Holepunch aborted') {
    return new DHTError(msg, 'HOLEPUNCH_ABORTED', DHTError.HOLEPUNCH_ABORTED)
  }

  static HOLEPUNCH_INVALID(msg = 'Invalid holepunch payload') {
    return new DHTError(msg, 'HOLEPUNCH_INVALID', DHTError.HOLEPUNCH_INVALID)
  }

  static HOLEPUNCH_PROBE_TIMEOUT(msg = 'Holepunching probe did not finish in time') {
    return new DHTError(msg, 'HOLEPUNCH_PROBE_TIMEOUT', DHTError.HOLEPUNCH_PROBE_TIMEOUT)
  }

  static HOLEPUNCH_DOUBLE_RANDOMIZED_NATS(msg = 'Both remote and local NATs are randomized') {
    return new DHTError(
      msg,
      'HOLEPUNCH_DOUBLE_RANDOMIZED_NATS',
      DHTError.HOLEPUNCH_DOUBLE_RANDOMIZED_NATS
    )
  }

  static CANNOT_HOLEPUNCH(msg = 'Cannot holepunch to remote') {
    return new DHTError(msg, 'CANNOT_HOLEPUNCH', DHTError.CANNOT_HOLEPUNCH)
  }

  static REMOTE_NOT_HOLEPUNCHING(msg = 'Remote is not holepunching') {
    return new DHTError(msg, 'REMOTE_NOT_HOLEPUNCHING', DHTError.REMOTE_NOT_HOLEPUNCHING)
  }

  static REMOTE_NOT_HOLEPUNCHABLE(msg = 'Remote is not holepunchable') {
    return new DHTError(msg, 'REMOTE_NOT_HOLEPUNCHABLE', DHTError.REMOTE_NOT_HOLEPUNCHABLE)
  }

  static REMOTE_ABORTED(msg = 'Remote aborted') {
    return new DHTError(msg, 'REMOTE_ABORTED', DHTError.REMOTE_ABORTED)
  }

  static HANDSHAKE_UNFINISHED(msg = 'Handshake did not finish') {
    return new DHTError(msg, 'HANDSHAKE_UNFINISHED', DHTError.HANDSHAKE_UNFINISHED)
  }

  static HANDSHAKE_INVALID(msg = 'Received invalid handshake') {
    return new DHTError(msg, 'HANDSHAKE_INVALID', DHTError.HANDSHAKE_INVALID)
  }

  static ALREADY_LISTENING(msg = 'Already listening') {
    return new DHTError(msg, 'ALREADY_LISTENING', DHTError.ALREADY_LISTENING)
  }

  static KEYPAIR_ALREADY_USED(msg = 'Keypair already used') {
    return new DHTError(msg, 'KEYPAIR_ALREADY_USED', DHTError.KEYPAIR_ALREADY_USED)
  }

  static NODE_DESTROYED(msg = 'Node destroyed') {
    return new DHTError(msg, 'NODE_DESTROYED', DHTError.NODE_DESTROYED)
  }

  static PEER_CONNECTION_FAILED(msg = 'Could not connect to peer') {
    return new DHTError(msg, 'PEER_CONNECTION_FAILED', DHTError.PEER_CONNECTION_FAILED)
  }

  static PEER_NOT_FOUND(msg = 'Peer not found') {
    return new DHTError(msg, 'PEER_NOT_FOUND', DHTError.PEER_NOT_FOUND)
  }

  static STREAM_NOT_CONNECTED(msg = 'Stream is not connected') {
    return new DHTError(msg, 'STREAM_NOT_CONNECTED', DHTError.STREAM_NOT_CONNECTED)
  }

  static SERVER_INCOMPATIBLE(msg = 'Server is using an incompatible version') {
    return new DHTError(msg, 'SERVER_INCOMPATIBLE', DHTError.SERVER_INCOMPATIBLE)
  }

  static SERVER_ERROR(msg = 'Server returned an error') {
    return new DHTError(msg, 'SERVER_ERROR', DHTError.SERVER_ERROR)
  }

  static DUPLICATE_CONNECTION(msg = 'Duplicate connection') {
    return new DHTError(msg, 'DUPLICATE_CONNECTION', DHTError.DUPLICATE_CONNECTION)
  }

  static RELAY_ABORTED(msg = 'Relay aborted') {
    return new DHTError(msg, 'RELAY_ABORTED', DHTError.RELAY_ABORTED)
  }

  static SUSPENDED(msg = 'Suspended') {
    return new DHTError(msg, 'SUSPENDED', DHTError.SUSPENDED)
  }
}
const b4a = require('b4a')
const Nat = require('./nat')
const Sleeper = require('./sleeper')
const { FIREWALL } = require('./constants')

const BIRTHDAY_SOCKETS = 256
const HOLEPUNCH = b4a.from([0])
const HOLEPUNCH_TTL = 5
const DEFAULT_TTL = 64
const MAX_REOPENS = 3

module.exports = class Holepuncher {
  constructor(dht, session, isInitiator, remoteFirewall = FIREWALL.UNKNOWN) {
    const holder = dht._socketPool.acquire()

    this.dht = dht
    this.session = session

    this.nat = new Nat(dht, session, holder.socket)
    this.nat.autoSample()

    this.isInitiator = isInitiator

    // events
    this.onconnect = noop
    this.onabort = noop

    this.punching = false
    this.connected = false
    this.destroyed = false
    this.randomized = false

    // track remote state
    this.remoteFirewall = remoteFirewall
    this.remoteAddresses = []
    this.remoteHolepunching = false

    this._sleeper = new Sleeper()
    this._reopening = null
    this._timeout = null
    this._punching = null
    this._allHolders = []
    this._holder = this._addRef(holder)
  }

  get socket() {
    return this._holder.socket
  }

  updateRemote({ punching, firewall, addresses, verified }) {
    const remoteAddresses = []

    if (addresses) {
      for (const addr of addresses) {
        remoteAddresses.push({
          host: addr.host,
          port: addr.port,
          verified: verified === addr.host || this._isVerified(addr.host)
        })
      }
    }

    this.remoteFirewall = firewall
    this.remoteAddresses = remoteAddresses
    this.remoteHolepunching = punching
  }

  _isVerified(host) {
    for (const addr of this.remoteAddresses) {
      if (addr.verified && addr.host === host) {
        return true
      }
    }
    return false
  }

  ping(addr, socket = this._holder.socket) {
    return holepunch(socket, addr, false)
  }

  openSession(addr, socket = this._holder.socket) {
    return holepunch(socket, addr, true)
  }

  async analyze(allowReopen) {
    await this.nat.analyzing
    if (this._unstable()) {
      if (!allowReopen) return false
      if (!this._reopening) this._reopening = this._reopen()
      return this._reopening
    }
    return true
  }

  _unstable() {
    // TODO!!: We need an additional heuristic here... If we were NOT random in the past we should also do this.
    const firewall = this.nat.firewall
    return (
      (this.remoteFirewall >= FIREWALL.RANDOM && firewall >= FIREWALL.RANDOM) ||
      firewall === FIREWALL.UNKNOWN
    )
  }

  _reset() {
    const prev = this._holder

    this._allHolders.pop()
    this._holder = this._addRef(this.dht._socketPool.acquire())

    prev.release()
    this.nat.destroy()

    this.nat = new Nat(this.dht, this.session, this._holder.socket)
    // TODO: maybe make auto sampling configurable somehow?
    this.nat.autoSample()
  }

  _addRef(ref) {
    this._allHolders.push(ref)
    ref.onholepunchmessage = (msg, rinfo) => this._onholepunchmessage(msg, rinfo, ref)
    return ref
  }

  _onholepunchmessage(_, addr, ref) {
    if (!this.isInitiator) {
      // TODO: we don't need this if we had a way to connect a socket to many hosts
      holepunch(ref.socket, addr, false) // never fails
      return
    }

    if (this.connected) return

    this.connected = true
    this.punching = false

    for (const r of this._allHolders) {
      if (r === ref) continue
      r.release()
    }

    this._allHolders[0] = ref
    while (this._allHolders.length > 1) this._allHolders.pop()

    this._decrementRandomized()
    this.onconnect(ref.socket, addr.port, addr.host)
  }

  _done() {
    return this.destroyed || this.connected
  }

  async _reopen() {
    for (let i = 0; this._unstable() && i < MAX_REOPENS && !this._done() && !this.punching; i++) {
      this._reset()
      await this.nat.analyzing
    }

    return coerceFirewall(this.nat.firewall) === FIREWALL.CONSISTENT
  }

  punch() {
    if (!this._punching) this._punching = this._punch()
    return this._punching
  }

  async _punch() {
    if (this._done() || !this.remoteAddresses.length) return false

    this.punching = true

    // Coerce into consistency for now. Obvs we could make this this more efficient if we use that info
    // but that's seldomly used since those will just use tcp most of the time.

    const local = coerceFirewall(this.nat.firewall)
    const remote = coerceFirewall(this.remoteFirewall)

    // Note that most of these async functions are meant to run in the background
    // which is why we don't await them here and why they are not allowed to throw

    let remoteVerifiedAddress = null
    for (const addr of this.remoteAddresses) {
      if (addr.verified) {
        remoteVerifiedAddress = addr
        break
      }
    }

    if (local === FIREWALL.CONSISTENT && remote === FIREWALL.CONSISTENT) {
      this.dht.stats.punches.consistent++
      this._consistentProbe()
      return true
    }

    if (!remoteVerifiedAddress) return false

    if (local === FIREWALL.CONSISTENT && remote >= FIREWALL.RANDOM) {
      this.dht.stats.punches.random++
      this._incrementRandomized()
      this._randomProbes(remoteVerifiedAddress)
      return true
    }

    if (local >= FIREWALL.RANDOM && remote === FIREWALL.CONSISTENT) {
      this.dht.stats.punches.random++
      this._incrementRandomized()
      await this._openBirthdaySockets(remoteVerifiedAddress)
      if (this.punching) this._keepAliveRandomNat(remoteVerifiedAddress)
      return true
    }

    return false
  }

  // Note that this never throws so it is safe to run in the background
  async _consistentProbe() {
    // Here we do the sleep first because the "fast open" mode in the server just fired a ping
    if (!this.isInitiator) await this._sleeper.pause(1000)

    let tries = 0

    while (this.punching && tries++ < 10) {
      for (const addr of this.remoteAddresses) {
        // only try unverified addresses every 4 ticks
        if (!addr.verified && (tries & 3) !== 0) continue
        await holepunch(this._holder.socket, addr, false)
      }
      if (this.punching) await this._sleeper.pause(1000)
    }

    this._autoDestroy()
  }

  // Note that this never throws so it is safe to run in the background
  async _randomProbes(remoteAddr) {
    let tries = 1750 // ~35s

    while (this.punching && tries-- > 0) {
      const addr = { host: remoteAddr.host, port: randomPort() }
      await holepunch(this._holder.socket, addr, false)
      if (this.punching) await this._sleeper.pause(20)
    }

    this._autoDestroy()
  }

  // Note that this never throws so it is safe to run in the background
  async _keepAliveRandomNat(remoteAddr) {
    let i = 0
    let lowTTLRounds = 1

    // TODO: experiment with this here. We just bursted all the messages in
    // openOtherSockets to ensure the sockets are open, so it's potentially
    // a good idea to slow down for a bit.
    await this._sleeper.pause(100)

    let tries = 1750 // ~35s

    while (this.punching && tries-- > 0) {
      if (i === this._allHolders.length) {
        i = 0
        if (lowTTLRounds > 0) lowTTLRounds--
      }

      await holepunch(this._allHolders[i++].socket, remoteAddr, lowTTLRounds > 0)
      if (this.punching) await this._sleeper.pause(20)
    }

    this._autoDestroy()
  }

  async _openBirthdaySockets(remoteAddr) {
    while (this.punching && this._allHolders.length < BIRTHDAY_SOCKETS) {
      const ref = this._addRef(this.dht._socketPool.acquire())
      await holepunch(ref.socket, remoteAddr, HOLEPUNCH_TTL)
    }
  }

  _autoDestroy() {
    if (!this.connected) this.destroy()
  }

  _incrementRandomized() {
    if (!this.randomized) {
      this.randomized = true
      this.dht._randomPunches++
    }
  }

  _decrementRandomized() {
    if (this.randomized) {
      this.dht._lastRandomPunch = Date.now()
      this.randomized = false
      this.dht._randomPunches--
    }
  }

  destroy() {
    if (this.destroyed) return
    this.destroyed = true
    this.punching = false

    for (const ref of this._allHolders) ref.release()
    this._allHolders = []
    this.nat.destroy()

    if (!this.connected) {
      this._decrementRandomized()
      this.onabort()
    }
  }

  static ping(socket, addr) {
    return holepunch(socket, addr, false)
  }

  static localAddresses(socket) {
    return localAddresses(socket)
  }

  static matchAddress(myAddresses, externalAddresses) {
    return matchAddress(myAddresses, externalAddresses)
  }
}

function holepunch(socket, addr, lowTTL) {
  return socket.send(HOLEPUNCH, addr.port, addr.host, lowTTL ? HOLEPUNCH_TTL : DEFAULT_TTL)
}

function randomPort() {
  return (1000 + Math.random() * 64536) | 0
}

function coerceFirewall(fw) {
  return fw === FIREWALL.OPEN ? FIREWALL.CONSISTENT : fw
}

function localAddresses(socket) {
  const addrs = []
  const { host, port } = socket.address()

  if (host === '127.0.0.1') return [{ host, port }]

  for (const n of socket.udx.networkInterfaces()) {
    if (n.family !== 4 || n.internal) continue

    addrs.push({ host: n.host, port })
  }

  if (addrs.length === 0) {
    addrs.push({ host: '127.0.0.1', port })
  }

  return addrs
}

function matchAddress(localAddresses, remoteLocalAddresses) {
  if (remoteLocalAddresses.length === 0) return null

  let best = { segment: 1, addr: null }

  for (const localAddress of localAddresses) {
    // => 192.168.122.238
    const a = localAddress.host.split('.')

    for (const remoteAddress of remoteLocalAddresses) {
      // => 192.168.0.23
      // => 192.168.122.1
      const b = remoteAddress.host.split('.')

      // Matches 192.*.*.*
      if (a[0] === b[0]) {
        if (best.segment === 1) best = { segment: 2, addr: remoteAddress }

        // Matches 192.168.*.*
        if (a[1] === b[1]) {
          if (best.segment === 2) best = { segment: 3, addr: remoteAddress }

          // Matches 192.168.122.*
          if (a[2] === b[2]) return remoteAddress
        }
      }
    }
  }

  return best.addr
}

function noop() {}
const c = require('compact-encoding')

const ipv4 = {
  ...c.ipv4Address,
  decode(state) {
    const ip = c.ipv4Address.decode(state)
    return {
      host: ip.host,
      port: ip.port
    }
  }
}

const ipv4Array = c.array(ipv4)

const ipv6 = {
  ...c.ipv6Address,
  decode(state) {
    const ip = c.ipv6Address.decode(state)
    return {
      host: ip.host,
      port: ip.port
    }
  }
}

const ipv6Array = c.array(ipv6)

exports.handshake = {
  preencode(state, m) {
    state.end += 1 + 1 + (m.peerAddress ? 6 : 0) + (m.relayAddress ? 6 : 0)
    c.buffer.preencode(state, m.noise)
  },
  encode(state, m) {
    const flags = (m.peerAddress ? 1 : 0) | (m.relayAddress ? 2 : 0)

    c.uint.encode(state, flags)
    c.uint.encode(state, m.mode)
    c.buffer.encode(state, m.noise)

    if (m.peerAddress) ipv4.encode(state, m.peerAddress)
    if (m.relayAddress) ipv4.encode(state, m.relayAddress)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      mode: c.uint.decode(state),
      noise: c.buffer.decode(state),
      peerAddress: flags & 1 ? ipv4.decode(state) : null,
      relayAddress: flags & 2 ? ipv4.decode(state) : null
    }
  }
}

const relayInfo = {
  preencode(state, m) {
    state.end += 12
  },
  encode(state, m) {
    ipv4.encode(state, m.relayAddress)
    ipv4.encode(state, m.peerAddress)
  },
  decode(state) {
    return {
      relayAddress: ipv4.decode(state),
      peerAddress: ipv4.decode(state)
    }
  }
}

const relayInfoArray = c.array(relayInfo)

const holepunchInfo = {
  preencode(state, m) {
    c.uint.preencode(state, m.id)
    relayInfoArray.preencode(state, m.relays)
  },
  encode(state, m) {
    c.uint.encode(state, m.id)
    relayInfoArray.encode(state, m.relays)
  },
  decode(state) {
    return {
      id: c.uint.decode(state),
      relays: relayInfoArray.decode(state)
    }
  }
}

const udxInfo = {
  preencode(state, m) {
    state.end += 2 // version + features
    c.uint.preencode(state, m.id)
    c.uint.preencode(state, m.seq)
  },
  encode(state, m) {
    c.uint.encode(state, 1)
    c.uint.encode(state, m.reusableSocket ? 1 : 0)
    c.uint.encode(state, m.id)
    c.uint.encode(state, m.seq)
  },
  decode(state) {
    const version = c.uint.decode(state)
    const features = c.uint.decode(state)

    return {
      version,
      reusableSocket: (features & 1) !== 0,
      id: c.uint.decode(state),
      seq: c.uint.decode(state)
    }
  }
}

const secretStreamInfo = {
  preencode(state, m) {
    c.uint.preencode(state, 1)
  },
  encode(state, m) {
    c.uint.encode(state, 1)
  },
  decode(state) {
    return {
      version: c.uint.decode(state)
    }
  }
}

const relayThroughInfo = {
  preencode(state, m) {
    c.uint.preencode(state, 1) // version
    c.uint.preencode(state, 0) // flags
    c.fixed32.preencode(state, m.publicKey)
    c.fixed32.preencode(state, m.token)
  },
  encode(state, m) {
    c.uint.encode(state, 1)
    c.uint.encode(state, 0)
    c.fixed32.encode(state, m.publicKey)
    c.fixed32.encode(state, m.token)
  },
  decode(state) {
    const version = c.uint.decode(state)
    c.uint.decode(state)

    return {
      version,
      publicKey: c.fixed32.decode(state),
      token: c.fixed32.decode(state)
    }
  }
}

exports.noisePayload = {
  preencode(state, m) {
    state.end += 4 // version + flags + error + firewall
    if (m.holepunch) holepunchInfo.preencode(state, m.holepunch)
    if (m.addresses4 && m.addresses4.length) ipv4Array.preencode(state, m.addresses4)
    if (m.addresses6 && m.addresses6.length) ipv6Array.preencode(state, m.addresses6)
    if (m.udx) udxInfo.preencode(state, m.udx)
    if (m.secretStream) secretStreamInfo.preencode(state, m.secretStream)
    if (m.relayThrough) relayThroughInfo.preencode(state, m.relayThrough)
    if (m.relayAddresses) ipv4Array.preencode(state, m.relayAddresses)
  },
  encode(state, m) {
    let flags = 0

    if (m.holepunch) flags |= 1
    if (m.addresses4 && m.addresses4.length) flags |= 2
    if (m.addresses6 && m.addresses6.length) flags |= 4
    if (m.udx) flags |= 8
    if (m.secretStream) flags |= 16
    if (m.relayThrough) flags |= 32
    if (m.relayAddresses) flags |= 64

    c.uint.encode(state, 1) // version
    c.uint.encode(state, flags)
    c.uint.encode(state, m.error)
    c.uint.encode(state, m.firewall)

    if (m.holepunch) holepunchInfo.encode(state, m.holepunch)
    if (m.addresses4 && m.addresses4.length) ipv4Array.encode(state, m.addresses4)
    if (m.addresses6 && m.addresses6.length) ipv6Array.encode(state, m.addresses6)
    if (m.udx) udxInfo.encode(state, m.udx)
    if (m.secretStream) secretStreamInfo.encode(state, m.secretStream)
    if (m.relayThrough) relayThroughInfo.encode(state, m.relayThrough)
    if (m.relayAddresses) ipv4Array.encode(state, m.relayAddresses)
  },
  decode(state) {
    const version = c.uint.decode(state)

    if (version !== 1) {
      // Do not attempt to decode but return this back to the user so they can
      // actually handle it
      return {
        version,
        error: 0,
        firewall: 0,
        holepunch: null,
        addresses4: [],
        addresses6: [],
        udx: null,
        secretStream: null,
        relayThrough: null,
        relayAddresses: null
      }
    }

    const flags = c.uint.decode(state)

    return {
      version,
      error: c.uint.decode(state),
      firewall: c.uint.decode(state),
      holepunch: (flags & 1) !== 0 ? holepunchInfo.decode(state) : null,
      addresses4: (flags & 2) !== 0 ? ipv4Array.decode(state) : [],
      addresses6: (flags & 4) !== 0 ? ipv6Array.decode(state) : [],
      udx: (flags & 8) !== 0 ? udxInfo.decode(state) : null,
      secretStream: (flags & 16) !== 0 ? secretStreamInfo.decode(state) : null,
      relayThrough: (flags & 32) !== 0 ? relayThroughInfo.decode(state) : null,
      relayAddresses: (flags & 64) !== 0 ? ipv4Array.decode(state) : null
    }
  }
}

exports.holepunch = {
  preencode(state, m) {
    state.end += 2
    c.uint.preencode(state, m.id)
    c.buffer.preencode(state, m.payload)
    if (m.peerAddress) ipv4.preencode(state, m.peerAddress)
  },
  encode(state, m) {
    const flags = m.peerAddress ? 1 : 0
    c.uint.encode(state, flags)
    c.uint.encode(state, m.mode)
    c.uint.encode(state, m.id)
    c.buffer.encode(state, m.payload)
    if (m.peerAddress) ipv4.encode(state, m.peerAddress)
  },
  decode(state) {
    const flags = c.uint.decode(state)
    return {
      mode: c.uint.decode(state),
      id: c.uint.decode(state),
      payload: c.buffer.decode(state),
      peerAddress: flags & 1 ? ipv4.decode(state) : null
    }
  }
}

exports.holepunchPayload = {
  preencode(state, m) {
    state.end += 4 // flags + error + firewall + round
    if (m.addresses) ipv4Array.preencode(state, m.addresses)
    if (m.remoteAddress) state.end += 6
    if (m.token) state.end += 32
    if (m.remoteToken) state.end += 32
  },
  encode(state, m) {
    const flags =
      (m.connected ? 1 : 0) |
      (m.punching ? 2 : 0) |
      (m.addresses ? 4 : 0) |
      (m.remoteAddress ? 8 : 0) |
      (m.token ? 16 : 0) |
      (m.remoteToken ? 32 : 0)

    c.uint.encode(state, flags)
    c.uint.encode(state, m.error)
    c.uint.encode(state, m.firewall)
    c.uint.encode(state, m.round)

    if (m.addresses) ipv4Array.encode(state, m.addresses)
    if (m.remoteAddress) ipv4.encode(state, m.remoteAddress)
    if (m.token) c.fixed32.encode(state, m.token)
    if (m.remoteToken) c.fixed32.encode(state, m.remoteToken)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      error: c.uint.decode(state),
      firewall: c.uint.decode(state),
      round: c.uint.decode(state),
      connected: (flags & 1) !== 0,
      punching: (flags & 2) !== 0,
      addresses: (flags & 4) !== 0 ? ipv4Array.decode(state) : null,
      remoteAddress: (flags & 8) !== 0 ? ipv4.decode(state) : null,
      token: (flags & 16) !== 0 ? c.fixed32.decode(state) : null,
      remoteToken: (flags & 32) !== 0 ? c.fixed32.decode(state) : null
    }
  }
}

const peer = (exports.peer = {
  preencode(state, m) {
    state.end += 32
    ipv4Array.preencode(state, m.relayAddresses)
  },
  encode(state, m) {
    c.fixed32.encode(state, m.publicKey)
    ipv4Array.encode(state, m.relayAddresses)
  },
  decode(state) {
    return {
      publicKey: c.fixed32.decode(state),
      relayAddresses: ipv4Array.decode(state)
    }
  }
})

const peers = (exports.peers = c.array(peer))

const rawPeers = c.array(c.raw)

exports.lookupRawReply = {
  preencode(state, m) {
    rawPeers.preencode(state, m.peers)
    c.uint.preencode(state, m.bump)
  },
  encode(state, m) {
    rawPeers.encode(state, m.peers)
    c.uint.encode(state, m.bump)
  },
  decode(state) {
    return {
      peers: peers.decode(state),
      bump: state.start < state.end ? c.uint.decode(state) : 0
    }
  }
}

exports.announce = {
  preencode(state, m) {
    state.end++ // flags
    if (m.peer) peer.preencode(state, m.peer)
    if (m.refresh) state.end += 32
    if (m.signature) state.end += 64
    if (m.bump) c.uint.preencode(state, m.bump)
  },
  encode(state, m) {
    const flags = (m.peer ? 1 : 0) | (m.refresh ? 2 : 0) | (m.signature ? 4 : 0) | (m.bump ? 8 : 0)
    c.uint.encode(state, flags)
    if (m.peer) peer.encode(state, m.peer)
    if (m.refresh) c.fixed32.encode(state, m.refresh)
    if (m.signature) c.fixed64.encode(state, m.signature)
    if (m.bump) c.uint.encode(state, m.bump)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      peer: (flags & 1) !== 0 ? peer.decode(state) : null,
      refresh: (flags & 2) !== 0 ? c.fixed32.decode(state) : null,
      signature: (flags & 4) !== 0 ? c.fixed64.decode(state) : null,
      bump: (flags & 8) !== 0 ? c.uint.decode(state) : 0
    }
  }
}

exports.mutableSignable = {
  preencode(state, m) {
    c.uint.preencode(state, m.seq)
    c.buffer.preencode(state, m.value)
  },
  encode(state, m) {
    c.uint.encode(state, m.seq)
    c.buffer.encode(state, m.value)
  },
  decode(state) {
    return {
      seq: c.uint.decode(state),
      value: c.buffer.decode(state)
    }
  }
}

exports.mutablePutRequest = {
  preencode(state, m) {
    c.fixed32.preencode(state, m.publicKey)
    c.uint.preencode(state, m.seq)
    c.buffer.preencode(state, m.value)
    c.fixed64.preencode(state, m.signature)
  },
  encode(state, m) {
    c.fixed32.encode(state, m.publicKey)
    c.uint.encode(state, m.seq)
    c.buffer.encode(state, m.value)
    c.fixed64.encode(state, m.signature)
  },
  decode(state) {
    return {
      publicKey: c.fixed32.decode(state),
      seq: c.uint.decode(state),
      value: c.buffer.decode(state),
      signature: c.fixed64.decode(state)
    }
  }
}

exports.mutableGetResponse = {
  preencode(state, m) {
    c.uint.preencode(state, m.seq)
    c.buffer.preencode(state, m.value)
    c.fixed64.preencode(state, m.signature)
  },
  encode(state, m) {
    c.uint.encode(state, m.seq)
    c.buffer.encode(state, m.value)
    c.fixed64.encode(state, m.signature)
  },
  decode(state) {
    return {
      seq: c.uint.decode(state),
      value: c.buffer.decode(state),
      signature: c.fixed64.decode(state)
    }
  }
}

exports.pluginRequest = {
  preencode(state, m) {
    c.string.preencode(state, m.plugin)
    c.uint.preencode(state, m.version)
    c.uint.preencode(state, m.command)
    state.end++ // max flag is 1 so always one byte

    if (m.value) c.buffer.preencode(state, m.value)
  },
  encode(state, m) {
    const flags = m.value ? 1 : 0

    c.string.encode(state, m.plugin)
    c.uint.encode(state, m.version)
    c.uint.encode(state, m.command)
    c.uint.encode(state, flags)

    if (m.value) c.buffer.encode(state, m.value)
  },
  decode(state) {
    const r0 = c.string.decode(state)
    const r1 = c.uint.decode(state)
    const r2 = c.uint.decode(state)
    const flags = c.uint.decode(state)

    return {
      plugin: r0,
      version: r1,
      command: r2,
      value: (flags & 1) !== 0 ? c.buffer.decode(state) : null
    }
  }
}
const { FIREWALL } = require('../lib/constants')

module.exports = class Nat {
  constructor(dht, session, socket) {
    this._samplesHost = []
    this._samplesFull = []
    this._visited = new Map()
    this._resolve = null
    this._minSamples = 4
    this._autoSampling = false

    this.dht = dht
    this.session = session
    this.socket = socket

    this.sampled = 0
    this.firewall = dht.firewalled ? FIREWALL.UNKNOWN : FIREWALL.OPEN
    this.addresses = null

    this.analyzing = new Promise((resolve) => {
      this._resolve = resolve
    })
  }

  autoSample(retry = true) {
    if (this._autoSampling) return
    this._autoSampling = true

    const self = this
    const socket = this.socket
    const maxPings = this._minSamples

    let skip = this.dht.nodes.length >= 8 ? 5 : 0
    let pending = 0

    // TODO: it would be best to pick the nodes to help us based on latency to us
    // That should reduce connect latency in general. We should investigate tracking that later on.

    // TODO 2: try to pick nodes with different IPs as well, as that'll help multi IP cell connections...
    // If we expose this from the nat sampler then the DHT should be able to help us filter out scams as well...

    for (
      let node = this.dht.nodes.latest;
      node && this.sampled + pending < maxPings;
      node = node.prev
    ) {
      if (skip > 0) {
        skip--
        continue
      }

      const ref = node.host + ':' + node.port

      if (this._visited.has(ref)) continue
      this._visited.set(ref, 1)

      pending++
      this.session.ping(node, { socket, retry: false }).then(onpong, onskip)
    }

    pending++
    onskip()

    function onpong(res) {
      self.add(res.to, res.from)
      onskip()
    }

    function onskip() {
      if (--pending === 0 && self.sampled < self._minSamples) {
        if (retry) {
          self._autoSampling = false
          self.autoSample(false)
          return
        }
        self._resolve()
      }
    }
  }

  destroy() {
    this._autoSampling = true
    this._minSamples = 0
    this._resolve()
  }

  unfreeze() {
    this.frozen = false
    this._updateFirewall()
    this._updateAddresses()
  }

  freeze() {
    this.frozen = true
  }

  _updateFirewall() {
    if (!this.dht.firewalled) {
      this.firewall = FIREWALL.OPEN
      return
    }

    if (this.sampled < 3) return

    const max = this._samplesFull[0].hits

    if (max >= 3) {
      this.firewall = FIREWALL.CONSISTENT
      return
    }

    if (max === 1) {
      this.firewall = FIREWALL.RANDOM
      return
    }

    // else max === 2

    // 1 host, >= 4 total samples ie, 2 bad ones -> random
    if (this._samplesHost.length === 1 && this.sampled > 3) {
      this.firewall = FIREWALL.RANDOM
      return
    }

    // double hit on two different ips -> assume consistent
    if (this._samplesHost.length > 1 && this._samplesFull[1].hits > 1) {
      this.firewall = FIREWALL.CONSISTENT
      return
    }

    // (4 is just means - all the samples we expect) - no decision - assume random
    if (this.sampled > 4) {
      this.firewall = FIREWALL.RANDOM
    }
  }

  _updateAddresses() {
    if (this.firewall === FIREWALL.UNKNOWN) {
      this.addresses = null
      return
    }

    if (this.firewall === FIREWALL.RANDOM) {
      this.addresses = [this._samplesHost[0]]
      return
    }

    if (this.firewall === FIREWALL.CONSISTENT) {
      this.addresses = []
      for (const addr of this._samplesFull) {
        if (addr.hits >= 2 || this.addresses.length < 2) this.addresses.push(addr)
      }
    }
  }

  update() {
    if (this.dht.firewalled && this.firewall === FIREWALL.OPEN) {
      this.firewall = FIREWALL.UNKNOWN
    }
    this._updateFirewall()
    this._updateAddresses()
  }

  add(addr, from) {
    const ref = from.host + ':' + from.port

    if (this._visited.get(ref) === 2) return
    this._visited.set(ref, 2)

    addSample(this._samplesHost, addr.host, 0)
    addSample(this._samplesFull, addr.host, addr.port)

    if ((++this.sampled >= 3 || !this.dht.firewalled) && !this.frozen) {
      this.update()
    }

    if (this.firewall === FIREWALL.CONSISTENT || this.firewall === FIREWALL.OPEN) {
      this._resolve()
    } else if (this.sampled >= this._minSamples) {
      this._resolve()
    }
  }
}

function addSample(samples, host, port) {
  for (let i = 0; i < samples.length; i++) {
    const s = samples[i]

    if (s.port !== port || s.host !== host) continue
    s.hits++

    for (; i > 0; i--) {
      const prev = samples[i - 1]
      if (prev.hits >= s.hits) return
      samples[i - 1] = s
      samples[i] = prev
    }

    return
  }

  samples.push({
    host,
    port,
    hits: 1
  })
}
const NoiseSecretStream = require('@hyperswarm/secret-stream')
const NoiseHandshake = require('noise-handshake')
const curve = require('noise-curve-ed')
const c = require('compact-encoding')
const b4a = require('b4a')
const sodium = require('sodium-universal')
const m = require('./messages')
const { NS } = require('./constants')
const { HANDSHAKE_UNFINISHED } = require('./errors')

const NOISE_PROLOUGE = NS.PEER_HANDSHAKE

module.exports = class NoiseWrap {
  constructor(keyPair, remotePublicKey) {
    this.isInitiator = !!remotePublicKey
    this.remotePublicKey = remotePublicKey
    this.keyPair = keyPair
    this.handshake = new NoiseHandshake('IK', this.isInitiator, keyPair, { curve })
    this.handshake.initialise(NOISE_PROLOUGE, remotePublicKey)
  }

  send(payload) {
    const buf = c.encode(m.noisePayload, payload)
    return this.handshake.send(buf)
  }

  recv(buf) {
    const payload = c.decode(m.noisePayload, this.handshake.recv(buf))
    this.remotePublicKey = b4a.toBuffer(this.handshake.rs)
    return payload
  }

  final() {
    if (!this.handshake.complete) throw HANDSHAKE_UNFINISHED()

    const holepunchSecret = b4a.allocUnsafe(32)

    sodium.crypto_generichash(holepunchSecret, NS.PEER_HOLEPUNCH, this.handshake.hash)

    return {
      isInitiator: this.isInitiator,
      publicKey: this.keyPair.publicKey,
      streamId: this.streamId,
      remotePublicKey: this.remotePublicKey,
      remoteId: NoiseSecretStream.id(this.handshake.hash, !this.isInitiator),
      holepunchSecret,
      hash: b4a.toBuffer(this.handshake.hash),
      rx: b4a.toBuffer(this.handshake.rx),
      tx: b4a.toBuffer(this.handshake.tx)
    }
  }
}
const c = require('compact-encoding')
const sodium = require('sodium-universal')
const RecordCache = require('record-cache')
const Cache = require('xache')
const b4a = require('b4a')
const unslab = require('unslab')

const { encodeUnslab } = require('./encode')
const m = require('./messages')
const { NS, ERROR } = require('./constants')

const EMPTY = b4a.alloc(0)
const TMP = b4a.allocUnsafe(32)
const MAX_BUMP_DRIFT = 60_000

module.exports = class Persistent {
  constructor(dht, opts) {
    this.dht = dht
    this.records = new RecordCache(opts.records)
    this.bumps = new Cache(opts.bumps)
    this.refreshes = new Cache(opts.refreshes)
    this.mutables = new Cache(opts.mutables)
    this.immutables = new Cache(opts.immutables)
  }

  onlookup(req) {
    if (!req.target) return

    const k = b4a.toString(req.target, 'hex')
    const records = this.records.get(k, 20)
    const bump = this.bumps.get(k) || 0
    const fwd = this.dht._router.get(k)

    if (fwd && records.length < 20) records.push(fwd.record)

    req.reply(records.length ? c.encode(m.lookupRawReply, { peers: records, bump }) : null)
  }

  onfindpeer(req) {
    if (!req.target) return
    const fwd = this.dht._router.get(req.target)
    req.reply(fwd ? fwd.record : null)
  }

  unannounce(target, publicKey) {
    const k = b4a.toString(target, 'hex')
    sodium.crypto_generichash(TMP, publicKey)

    if (b4a.equals(TMP, target)) this.dht._router.delete(k)
    this.records.remove(k, publicKey)
  }

  onunannounce(req) {
    if (!req.target || !req.token) return

    const unann = decode(m.announce, req.value)
    if (unann === null) return

    const { peer, signature } = unann
    if (!peer || !signature) return

    const signable = annSignable(req.target, req.token, this.dht.id, unann, NS.UNANNOUNCE)

    if (!sodium.crypto_sign_verify_detached(signature, signable, peer.publicKey)) {
      return
    }

    this.unannounce(req.target, peer.publicKey)
    req.reply(null, { token: false, closerNodes: false })
  }

  _onrefresh(token, req) {
    sodium.crypto_generichash(TMP, token)
    const activeRefresh = b4a.toString(TMP, 'hex')

    const r = this.refreshes.get(activeRefresh)
    if (!r) return

    const { announceSelf, k, record } = r
    const publicKey = record.subarray(0, 32)

    if (announceSelf) {
      this.dht._router.set(k, {
        relay: req.from,
        record,
        onconnect: null,
        onholepunch: null
      })
      this.records.remove(k, publicKey)
    } else {
      this.records.add(k, publicKey, record)
    }

    this.refreshes.delete(activeRefresh)
    this.refreshes.set(b4a.toString(token, 'hex'), r)

    req.reply(null, { token: false, closerNodes: false })
  }

  onannounce(req) {
    if (!req.target || !req.token || !this.dht.id) return

    const ann = decode(m.announce, req.value)
    if (ann === null) return

    const { peer, refresh, signature, bump } = ann

    if (!peer) {
      if (!refresh) return
      this._onrefresh(refresh, req)
      return
    }

    const signable = annSignable(req.target, req.token, this.dht.id, ann, NS.ANNOUNCE)

    if (!signature || !sodium.crypto_sign_verify_detached(signature, signable, peer.publicKey)) {
      return
    }

    // TODO: it would be potentially be more optimal to allow more than 3 addresses here for a findPeer response
    // and only use max 3 for a lookup reply
    if (peer.relayAddresses.length > 3) {
      peer.relayAddresses = peer.relayAddresses.slice(0, 3)
    }

    sodium.crypto_generichash(TMP, peer.publicKey)

    const k = b4a.toString(req.target, 'hex')
    const announceSelf = b4a.equals(TMP, req.target)
    const record = encodeUnslab(m.peer, peer)

    if (announceSelf) {
      this.dht._router.set(k, {
        relay: req.from,
        record,
        onconnect: null,
        onholepunch: null
      })
      this.records.remove(k, peer.publicKey)
    } else {
      const currentBump = this.bumps.get(k) || 0
      if (bump > currentBump && bump <= Date.now() + MAX_BUMP_DRIFT) this.bumps.set(k, bump)
      this.records.add(k, peer.publicKey, record)
    }

    if (refresh) {
      this.refreshes.set(b4a.toString(refresh, 'hex'), { k, record, announceSelf })
    }

    req.reply(null, { token: false, closerNodes: false })
  }

  onmutableget(req) {
    if (!req.target || !req.value) return

    let seq = 0
    try {
      seq = c.decode(c.uint, req.value)
    } catch {
      return
    }

    const k = b4a.toString(req.target, 'hex')
    const value = this.mutables.get(k)

    if (!value) {
      req.reply(null)
      return
    }

    const localSeq = c.decode(c.uint, value)
    req.reply(localSeq < seq ? null : value)
  }

  onmutableput(req) {
    if (!req.target || !req.token || !req.value) return

    const p = decode(m.mutablePutRequest, req.value)
    if (!p) return

    const { publicKey, seq, value, signature } = p

    const hash = b4a.allocUnsafe(32)
    sodium.crypto_generichash(hash, publicKey)
    if (!b4a.equals(hash, req.target)) return

    if (!value || !verifyMutable(signature, seq, value, publicKey)) return

    const k = b4a.toString(hash, 'hex')
    const local = this.mutables.get(k)

    if (local) {
      const existing = c.decode(m.mutableGetResponse, local)
      if (existing.value && existing.seq === seq && b4a.compare(value, existing.value) !== 0) {
        req.error(ERROR.SEQ_REUSED)
        return
      }
      if (seq < existing.seq) {
        req.error(ERROR.SEQ_TOO_LOW)
        return
      }
    }

    this.mutables.set(k, encodeUnslab(m.mutableGetResponse, { seq, value, signature }))
    req.reply(null)
  }

  onimmutableget(req) {
    if (!req.target) return

    const k = b4a.toString(req.target, 'hex')
    const value = this.immutables.get(k)

    req.reply(value || null)
  }

  onimmutableput(req) {
    if (!req.target || !req.token || !req.value) return

    const hash = b4a.alloc(32)
    sodium.crypto_generichash(hash, req.value)
    if (!b4a.equals(hash, req.target)) return

    const k = b4a.toString(hash, 'hex')
    this.immutables.set(k, unslab(req.value))

    req.reply(null)
  }

  onplugin(req) {
    if (!req.value) return

    const plugreq = decode(m.pluginRequest, req.value)
    if (plugreq === null) return

    const p = this.dht.plugins.get(plugreq.plugin)
    if (!p || p.version !== plugreq.version) return

    p.onrequest(plugreq, req)
  }

  destroy() {
    this.records.destroy()
    this.refreshes.destroy()
    this.mutables.destroy()
    this.immutables.destroy()
  }

  static signMutable(seq, value, keyPair) {
    const signable = b4a.allocUnsafe(32 + 32)
    const hash = signable.subarray(32)

    signable.set(NS.MUTABLE_PUT, 0)

    sodium.crypto_generichash(hash, c.encode(m.mutableSignable, { seq, value }))
    return sign(signable, keyPair)
  }

  static verifyMutable(signature, seq, value, publicKey) {
    return verifyMutable(signature, seq, value, publicKey)
  }

  static signAnnounce(target, token, id, ann, keyPair) {
    return sign(annSignable(target, token, id, ann, NS.ANNOUNCE), keyPair)
  }

  static signUnannounce(target, token, id, ann, keyPair) {
    return sign(annSignable(target, token, id, ann, NS.UNANNOUNCE), keyPair)
  }
}

function verifyMutable(signature, seq, value, publicKey) {
  const signable = b4a.allocUnsafe(32 + 32)
  const hash = signable.subarray(32)

  signable.set(NS.MUTABLE_PUT, 0)

  sodium.crypto_generichash(hash, c.encode(m.mutableSignable, { seq, value }))
  return sodium.crypto_sign_verify_detached(signature, signable, publicKey)
}

function annSignable(target, token, id, ann, ns) {
  const signable = b4a.allocUnsafe(32 + 32)
  const hash = signable.subarray(32)

  signable.set(ns, 0)

  sodium.crypto_generichash_batch(hash, [
    target,
    id,
    token,
    c.encode(m.peer, ann.peer), // note that this is the partial encoding of the announce message so we could just use that for perf
    ann.refresh || EMPTY
  ])

  return signable
}

function sign(signable, keyPair) {
  if (keyPair.sign) {
    return keyPair.sign(signable)
  }
  const secretKey = keyPair.secretKey ? keyPair.secretKey : keyPair
  const signature = b4a.allocUnsafe(64)
  sodium.crypto_sign_detached(signature, signable, secretKey)
  return signature
}

function decode(enc, val) {
  try {
    return val && c.decode(enc, val)
  } catch (err) {
    return null
  }
}
module.exports = class RawStreamSet {
  constructor(dht) {
    this._dht = dht

    this._prefix = 16 - 1 // 16 is the default stream-set side in udx
    this._streams = new Map()
  }

  get size() {
    return this._streams.size
  }

  [Symbol.iterator]() {
    return this._streams.values()
  }

  add(opts) {
    const self = this

    // TODO: we should prob have a udx helper for id generation, given the slight complexity
    // of the below. requires a PRNG in udx tho.

    let id = 0

    while (true) {
      id = (Math.random() * 0x100000000) >>> 0

      if (this._streams.has(id & this._prefix)) continue
      break
    }

    // always have ~50% change of rolling a free one
    if (2 * this._streams.size >= this._prefix) {
      // ie 0b11111 = 0b1111 + 1 + 0b1111
      this._prefix = 2 * this._prefix + 1

      // move the prefixes over
      const next = new Map()
      for (const stream of this._streams.values()) {
        next.set(stream.id & this._prefix, stream)
      }
      this._streams = next
    }

    const stream = this._dht.udx.createStream(id, opts)
    this._streams.set(id & this._prefix, stream)

    stream.on('close', onclose)

    return stream

    function onclose() {
      self._streams.delete(id & self._prefix)
    }
  }

  async clear() {
    const destroying = []

    for (const stream of this._streams.values()) {
      destroying.push(new Promise((resolve) => stream.once('close', resolve).destroy()))
    }

    await Promise.allSettled(destroying)
  }
}
const b4a = require('b4a')
const safetyCatch = require('safety-catch')

exports.clearRelayTimeout = clearRelayTimeout
exports.closeRelayConnection = closeRelayConnection
exports.confirmDirectUpgrade = confirmDirectUpgrade
exports.destroyRelayConnection = destroyRelayConnection

function clearRelayTimeout(connectionOrHandshake) {
  clearTimeout(connectionOrHandshake.relayTimeout)
  connectionOrHandshake.relayTimeout = null
}

function closeRelayConnection(connectionOrHandshake) {
  const socket = resetRelayConnection(connectionOrHandshake)

  if (socket) socket.end()
}

function confirmDirectUpgrade(connectionOrHandshake, rawStream, remoteChanging) {
  const cleanup = () => {
    rawStream.off('data', ondirect)
    rawStream.off('message', ondirect)
    rawStream.off('close', cleanup)
  }

  function ondirect() {
    if (!connectionOrHandshake.validUpgrade) {
      // reset, aka assume from direct
      connectionOrHandshake.validUpgrade = true
      return
    }

    cleanup()
    closeRelayConnection(connectionOrHandshake)
  }

  const confirm = () => {
    rawStream.on('data', ondirect)
    rawStream.on('message', ondirect)
    rawStream.once('close', cleanup)

    // Use a raw UDX message to make the peer observe the direct path without
    // writing application data into the secret stream.
    if (rawStream.trySend) rawStream.trySend(b4a.alloc(0))
  }

  if (!remoteChanging) {
    confirm()
    return
  }

  remoteChanging.then(confirm).catch(safetyCatch)
}

function destroyRelayConnection(connectionOrHandshake) {
  const socket = resetRelayConnection(connectionOrHandshake)

  if (socket) socket.destroy()
}

function resetRelayConnection(connectionOrHandshake) {
  if (connectionOrHandshake.relayTimeout) clearRelayTimeout(connectionOrHandshake)

  const socket = connectionOrHandshake.relaySocket
  // Drop relay references so the app connection no longer keeps relay state alive.
  connectionOrHandshake.relayToken = null
  connectionOrHandshake.relaySocket = null
  connectionOrHandshake.relayClient = null

  return socket
}
const c = require('compact-encoding')
const Cache = require('xache')
const safetyCatch = require('safety-catch')
const b4a = require('b4a')
const { handshake, holepunch } = require('./messages')
const { COMMANDS } = require('./constants')
const { BAD_HANDSHAKE_REPLY, BAD_HOLEPUNCH_REPLY } = require('./errors')

const FROM_CLIENT = 0
const FROM_SERVER = 1
const FROM_RELAY = 2
const FROM_SECOND_RELAY = 3
const REPLY = 4

// TODO: While the current design is very trustless in regards to clients/servers trusting the DHT,
// we should add a bunch of rate limits everywhere, especially including here to avoid bad users
// using a DHT node to relay traffic indiscriminately using the connect/holepunch messages.
// That's mostly from an abuse POV as none of the messsages do amplication.

module.exports = class Router {
  constructor(dht, opts) {
    this.dht = dht
    this.forwards = new Cache(opts.forwards)
  }

  set(target, state) {
    if (state.onpeerhandshake) {
      this.forwards.retain(toString(target), state)
    } else {
      this.forwards.set(toString(target), state)
    }
  }

  get(target) {
    return this.forwards.get(toString(target))
  }

  delete(target) {
    this.forwards.delete(toString(target))
  }

  destroy() {
    this.forwards.destroy()
  }

  async peerHandshake(target, { noise, peerAddress, relayAddress, socket, session }, to) {
    const dht = this.dht

    const requestValue = c.encode(handshake, {
      mode: FROM_CLIENT,
      noise,
      peerAddress,
      relayAddress
    })

    const res = await dht.request(
      { command: COMMANDS.PEER_HANDSHAKE, target, value: requestValue },
      to,
      { socket, session }
    )

    const hs = decode(handshake, res.value)
    if (
      !hs ||
      hs.mode !== REPLY ||
      to.host !== res.from.host ||
      to.port !== res.from.port ||
      !hs.noise
    ) {
      throw BAD_HANDSHAKE_REPLY()
    }

    return {
      noise: hs.noise,
      relayed: !!hs.peerAddress,
      serverAddress: hs.peerAddress || to,
      clientAddress: res.to
    }
  }

  async onpeerhandshake(req) {
    const hs = req.value && decode(handshake, req.value)
    if (!hs) return

    const { mode, noise, peerAddress, relayAddress } = hs

    const state = req.target && this.get(req.target)
    const isServer = !!(state && state.onpeerhandshake)
    const relay = state && state.relay

    if (isServer) {
      let reply = null
      try {
        reply = noise && (await state.onpeerhandshake({ noise, peerAddress }, req))
      } catch (e) {
        safetyCatch(e)
        return
      }
      if (!reply || !reply.noise) return
      const opts = { socket: reply.socket, closerNodes: false, token: false }

      switch (mode) {
        case FROM_CLIENT: {
          req.reply(
            c.encode(handshake, { mode: REPLY, noise: reply.noise, peerAddress: null }),
            opts
          )
          return
        }
        case FROM_RELAY: {
          req.relay(
            c.encode(handshake, { mode: FROM_SERVER, noise: reply.noise, peerAddress }),
            req.from,
            opts
          )
          return
        }
        case FROM_SECOND_RELAY: {
          if (!relayAddress) return
          req.relay(
            c.encode(handshake, { mode: FROM_SERVER, noise: reply.noise, peerAddress }),
            relayAddress,
            opts
          )
          return // eslint-disable-line
        }
      }
    } else {
      switch (mode) {
        case FROM_CLIENT: {
          // TODO: if no relay is known route closer to the target instead of timing out
          if (!noise) return
          if (!relay && !relayAddress) {
            // help the user route
            req.reply(null, { token: false, closerNodes: true })
            return
          }
          req.relay(
            c.encode(handshake, {
              mode: FROM_RELAY,
              noise,
              peerAddress: req.from,
              relayAddress: null
            }),
            relayAddress || relay
          )
          return
        }
        case FROM_RELAY: {
          if (!relay || !noise) return
          req.relay(
            c.encode(handshake, {
              mode: FROM_SECOND_RELAY,
              noise,
              peerAddress,
              relayAddress: req.from
            }),
            relay
          )
          return
        }
        case FROM_SERVER: {
          if (!peerAddress || !noise) return
          req.reply(
            c.encode(handshake, { mode: REPLY, noise, peerAddress: req.from, relayAddress: null }),
            { to: peerAddress, closerNodes: false, token: false }
          )
          return // eslint-disable-line
        }
      }
    }
  }

  async peerHolepunch(target, { id, payload, peerAddress, socket, session }, to) {
    const dht = this.dht
    const requestValue = c.encode(holepunch, {
      mode: FROM_CLIENT,
      id,
      payload,
      peerAddress
    })

    const res = await dht.request(
      { command: COMMANDS.PEER_HOLEPUNCH, target, value: requestValue },
      to,
      { socket, session }
    )

    const hp = decode(holepunch, res.value)
    if (!hp || hp.mode !== REPLY || to.host !== res.from.host || to.port !== res.from.port) {
      throw BAD_HOLEPUNCH_REPLY()
    }

    return {
      from: res.from,
      to: res.to,
      payload: hp.payload,
      peerAddress: hp.peerAddress || to
    }
  }

  async onpeerholepunch(req) {
    const hp = req.value && decode(holepunch, req.value)
    if (!hp) return

    const { mode, id, payload, peerAddress } = hp

    const state = req.target && this.get(req.target)
    const isServer = !!(state && state.onpeerholepunch)
    const relay = state && state.relay

    switch (mode) {
      case FROM_CLIENT: {
        if (!peerAddress && !relay) return
        req.relay(
          c.encode(holepunch, { mode: FROM_RELAY, id, payload, peerAddress: req.from }),
          peerAddress || relay
        )
        return
      }
      case FROM_RELAY: {
        if (!isServer || !peerAddress) return
        let reply = null
        try {
          reply = await state.onpeerholepunch({ id, payload, peerAddress }, req)
        } catch (e) {
          safetyCatch(e)
          return
        }
        if (!reply) return
        const opts = { socket: reply.socket, closerNodes: false, token: false }
        req.relay(
          c.encode(holepunch, { mode: FROM_SERVER, id: 0, payload: reply.payload, peerAddress }),
          req.from,
          opts
        )
        return
      }
      case FROM_SERVER: {
        req.reply(c.encode(holepunch, { mode: REPLY, id, payload, peerAddress: req.from }), {
          to: peerAddress,
          closerNodes: false,
          token: false
        })
        return // eslint-disable-line
      }
    }
  }
}

function decode(enc, val) {
  try {
    return c.decode(enc, val)
  } catch {
    return null
  }
}

function toString(t) {
  return typeof t === 'string' ? t : b4a.toString(t, 'hex')
}
const sodium = require('sodium-universal')
const b4a = require('b4a')
const { holepunchPayload } = require('./messages')

module.exports = class HolepunchPayload {
  constructor(holepunchSecret) {
    this._sharedSecret = holepunchSecret
    this._localSecret = b4a.allocUnsafe(32)

    sodium.randombytes_buf(this._localSecret)
  }

  decrypt(buffer) {
    const state = { start: 24, end: buffer.byteLength - 16, buffer }

    if (state.end <= state.start) return null

    const nonce = buffer.subarray(0, 24)
    const msg = state.buffer.subarray(state.start, state.end)
    const cipher = state.buffer.subarray(state.start)

    if (!sodium.crypto_secretbox_open_easy(msg, cipher, nonce, this._sharedSecret)) return null

    try {
      return holepunchPayload.decode(state)
    } catch {
      return null
    }
  }

  encrypt(payload) {
    const state = { start: 24, end: 24, buffer: null }
    holepunchPayload.preencode(state, payload)
    state.buffer = b4a.allocUnsafe(state.end + 16)

    const nonce = state.buffer.subarray(0, 24)
    const msg = state.buffer.subarray(state.start, state.end)
    const cipher = state.buffer.subarray(state.start)

    holepunchPayload.encode(state, payload)
    sodium.randombytes_buf(nonce)
    sodium.crypto_secretbox_easy(cipher, msg, nonce, this._sharedSecret)

    return state.buffer
  }

  token(addr) {
    const out = b4a.allocUnsafe(32)
    sodium.crypto_generichash(out, b4a.from(addr.host), this._localSecret)
    return out
  }
}
const DONE = Promise.resolve(true)
const DESTROYED = Promise.resolve(false)

module.exports = class Semaphore {
  constructor(limit = 1) {
    this.limit = limit
    this.active = 0
    this.waiting = []

    this.flushedPromise = null
    this.flushedResolve = null

    this.destroyed = false

    this._onwait = this._queueWaiting.bind(this)
    this._onflush = this._queueFlushed.bind(this)
  }

  _queueWaiting(resolve) {
    this.waiting.push(resolve)
  }

  _queueFlushed(resolve) {
    this.flushedResolve = resolve
  }

  wait() {
    if (this.destroyed === true) return DESTROYED

    if (this.active < this.limit && this.waiting.length === 0) {
      this.active++
      return DONE
    }

    return new Promise(this._onwait)
  }

  signal() {
    if (this.destroyed === true) return

    this.active--
    while (this.active < this.limit && this.waiting.length > 0 && this.destroyed === false) {
      this.active++
      this.waiting.shift()(true)
    }

    if (this.active === 0 && this.flushedResolve) {
      const resolve = this.flushedResolve
      this.flushedResolve = null
      this.flushedPromise = null
      resolve(true)
    }
  }

  async flush() {
    if (this.destroyed === true) return
    if (this.active === 0) return
    if (this.flushedPromise) return this.flushedPromise
    this.flushedPromise = new Promise(this._onflush)
    return this.flushedPromise
  }

  destroy() {
    this.destroyed = true
    this.active = 0
    while (this.waiting.length) this.waiting.pop()(false)
    if (this.flushedResolve) this.flushedResolve(false)
  }
}
const { EventEmitter } = require('events')
const safetyCatch = require('safety-catch')
const NoiseSecretStream = require('@hyperswarm/secret-stream')
const b4a = require('b4a')
const relay = require('blind-relay')
const NoiseWrap = require('./noise-wrap')
const Announcer = require('./announcer')
const { FIREWALL, ERROR } = require('./constants')
const { unslabbedHash } = require('./crypto')
const SecurePayload = require('./secure-payload')
const Holepuncher = require('./holepuncher')
const {
  clearRelayTimeout,
  confirmDirectUpgrade,
  destroyRelayConnection
} = require('./relay-connection')
const { isPrivate } = require('bogon')
const { ALREADY_LISTENING, NODE_DESTROYED, KEYPAIR_ALREADY_USED } = require('./errors')

const HANDSHAKE_CLEAR_WAIT = 10000
const HANDSHAKE_INITIAL_TIMEOUT = 10000

module.exports = class Server extends EventEmitter {
  constructor(dht, opts = {}) {
    super()

    this.dht = dht
    this.target = null

    this.closed = false
    this.firewall = opts.firewall || (() => false)
    this.holepunch = opts.holepunch || (() => true)
    this.relayThrough = opts.relayThrough || null
    this.relayKeepAlive = opts.relayKeepAlive || 5000
    this.pool = opts.pool || null
    this.createHandshake = opts.createHandshake || defaultCreateHandshake
    this.createSecretStream = opts.createSecretStream || defaultCreateSecretStream
    this.suspended = false
    this.handshakeClearWait = opts.handshakeClearWait || HANDSHAKE_CLEAR_WAIT

    this._shareLocalAddress = opts.shareLocalAddress !== false
    this._reusableSocket = !!opts.reusableSocket
    this._neverPunch = opts.holepunch === false // useful for fully disabling punching
    this._keyPair = null
    this._announcer = null
    this._connects = new Map()
    this._holepunches = []
    this._listening = null
    this._closing = null
  }

  get listening() {
    return this._listening !== null
  }

  get publicKey() {
    return this._keyPair && this._keyPair.publicKey
  }

  get relayAddresses() {
    return this._announcer ? this._announcer.relayAddresses : []
  }

  onconnection(encryptedSocket) {
    this.emit('connection', encryptedSocket)
  }

  async suspend({ log = noop } = {}) {
    log('Suspending hyperdht server')
    if (this._listening !== null) await this._listening
    log('Suspending hyperdht server (post listening)')
    this.suspended = true
    this._clearAll()
    return this._announcer ? this._announcer.suspend({ log }) : Promise.resolve()
  }

  async resume() {
    if (this._listening !== null) await this._listening
    this.suspended = false
    return this._announcer ? this._announcer.resume() : Promise.resolve()
  }

  address() {
    if (!this._keyPair) return null

    return {
      publicKey: this._keyPair.publicKey,
      host: this.dht.host,
      port: this.dht.port
    }
  }

  close() {
    if (this._closing) return this._closing
    this._closing = this._close()
    return this._closing
  }

  _gc() {
    this.dht.listening.delete(this)
    if (this.target) this.dht._router.delete(this.target)
  }

  async _stopListening() {
    try {
      if (this._announcer) await this._announcer.stop()
    } catch {
      // ignore
    }

    this._announcer = null
    this._listening = null
    this._keyPair = null
  }

  async _close() {
    if (this._listening === null) {
      this.closed = true
      this.emit('close')
      return
    }

    try {
      await this._listening
    } catch (err) {
      safetyCatch(err)
    }

    this._gc()
    this._clearAll()

    await this._stopListening()

    this.closed = true
    this.emit('close')
  }

  _clearAll() {
    while (this._holepunches.length > 0) {
      const h = this._holepunches.pop()
      if (h && h.puncher) h.puncher.destroy()
      if (h && h.clearing) clearTimeout(h.clearing)
      if (h && h.prepunching) clearTimeout(h.prepunching)
      if (h && h.rawStream) h.rawStream.destroy()
    }

    this._connects.clear()
  }

  async listen(keyPair = this.dht.defaultKeyPair, opts = {}) {
    if (this._listening !== null) throw ALREADY_LISTENING()
    if (this.dht.destroyed) throw NODE_DESTROYED()

    this._listening = this._listen(keyPair, opts)
    await this._listening
    return this
  }

  async _listen(keyPair, opts) {
    // From now on, the DHT object which created me is responsible for closing me
    this.dht.listening.add(this)

    try {
      await this.dht.bind()
      if (this._closing) return

      for (const s of this.dht.listening) {
        if (s._keyPair && b4a.equals(s._keyPair.publicKey, keyPair.publicKey)) {
          throw KEYPAIR_ALREADY_USED()
        }
      }

      this.target = unslabbedHash(keyPair.publicKey)
      this._keyPair = keyPair
      this._announcer = new Announcer(this.dht, keyPair, this.target, opts)

      this.dht._router.set(this.target, {
        relay: null,
        record: this._announcer.record,
        onpeerhandshake: this._onpeerhandshake.bind(this),
        onpeerholepunch: this._onpeerholepunch.bind(this)
      })

      // warm it up for now
      this._localAddresses().catch(safetyCatch)

      await this._announcer.start()
    } catch (err) {
      await this._stopListening()
      this._gc()
      throw err
    }

    if (this._closing) return
    if (this.suspended) await this._announcer.suspend()

    if (this._closing) return
    if (this.dht.destroyed) throw NODE_DESTROYED()

    if (this.pool) this.pool._attachServer(this)

    this.emit('listening')
  }

  refresh() {
    if (this._announcer && !this.suspended) this._announcer.refresh()
  }

  notifyOnline() {
    if (this._announcer) this._announcer.online.notify()
  }

  _localAddresses() {
    return this.dht.validateLocalAddresses(Holepuncher.localAddresses(this.dht.io.serverSocket))
  }

  async _addHandshake(k, noise, clientAddress, { to: serverAddress, socket }, direct) {
    let id = this._holepunches.indexOf(null)
    if (id === -1) id = this._holepunches.push(null) - 1

    const hs = {
      round: 0,
      reply: null,
      puncher: null,
      payload: null,
      rawStream: null,
      encryptedSocket: null,
      prepunching: null,
      firewalled: true,
      clearing: null,
      replyFromPuncher: false,
      onsocket: null,
      aborted: false,

      // Relay state
      relayTimeout: null,
      relayToken: null,
      relaySocket: null,
      relayClient: null,
      relayPaired: false,
      validUpgrade: true
    }

    this._holepunches[id] = hs

    const handshake = this.createHandshake(this._keyPair, null)

    let remotePayload
    try {
      remotePayload = await handshake.recv(noise)
    } catch (err) {
      safetyCatch(err)
      this._clearLater(hs, id, k)
      return null
    }

    if (this._closing || this.suspended) return null

    try {
      hs.firewalled = await this.firewall(handshake.remotePublicKey, remotePayload, clientAddress)
    } catch (err) {
      safetyCatch(err)
    }

    if (this._closing || this.suspended) return null

    if (hs.firewalled) {
      this._clearLater(hs, id, k)
      return null
    }

    const error =
      remotePayload.version === 1
        ? remotePayload.udx
          ? ERROR.NONE
          : ERROR.ABORTED
        : ERROR.VERSION_MISMATCH

    const addresses = []
    const ourRemoteAddr = this.dht.remoteAddress()
    const ourLocalAddrs = this._shareLocalAddress ? await this._localAddresses() : null

    if (this._closing || this.suspended) return null

    if (ourRemoteAddr) addresses.push(ourRemoteAddr)
    if (ourLocalAddrs) addresses.push(...ourLocalAddrs)

    if (error === ERROR.NONE) {
      hs.rawStream = this.dht.createRawStream({
        framed: true,
        firewall(socket, port, host) {
          if (!(port > 0 && port < 65536)) return true

          // Check if the traffic originated from the socket on which we're expecting relay traffic. If so,
          // we haven't hole punched yet and the other side is just sending us traffic through the relay.
          if (hs.relaySocket && isRelay(hs.relaySocket, socket, port, host)) {
            hs.validUpgrade = false
            return false
          }

          hs.onsocket(socket, port, host)
          hs.validUpgrade = true
          return false
        }
      })

      hs.rawStream.on('error', autoDestroy)

      // Handles the case where onsocket is never called, but the stream got setup
      // This can happen on a relayed connection which never connects directly
      // (onsocket is called there only when the direct connection is established)
      const onrawstreamclose = () => {
        if (this._closing) return
        this._clearLater(hs, id, k)
      }
      hs.rawStream.on('close', onrawstreamclose)

      hs.onsocket = (socket, port, host) => {
        if (hs.rawStream === null) return // Already hole punched

        this._clearLater(hs, id, k)

        if (hs.prepunching) {
          clearTimeout(hs.prepunching)
          hs.prepunching = null
        }

        if (this._reusableSocket && remotePayload.udx.reusableSocket) {
          this.dht._socketPool.routes.add(handshake.remotePublicKey, hs.rawStream)
        }

        hs.rawStream.removeListener('error', autoDestroy)
        hs.rawStream.removeListener('close', onrawstreamclose)

        if (hs.rawStream.connected) {
          const rawStream = hs.rawStream
          const remoteChanging = rawStream.changeRemote(socket, remotePayload.udx.id, port, host)
          confirmDirectUpgrade(hs, rawStream, remoteChanging)
        } else {
          hs.rawStream.connect(socket, remotePayload.udx.id, port, host)
          hs.encryptedSocket = this.createSecretStream(false, hs.rawStream, {
            handshake: h,
            keepAlive: this.dht.connectionKeepAlive
          })

          this.onconnection(hs.encryptedSocket)
        }

        if (hs.puncher) {
          hs.puncher.onabort = noop
          hs.puncher.destroy()
        }

        hs.rawStream = null
      }

      function autoDestroy() {
        if (hs.puncher) hs.puncher.destroy()
      }
    }

    const relayAddresses = this.relayAddresses
    const relayThrough = selectRelay(this.relayThrough)

    if (relayThrough) hs.relayToken = relay.token()

    try {
      hs.reply = await handshake.send({
        error,
        firewall: ourRemoteAddr ? FIREWALL.OPEN : FIREWALL.UNKNOWN,
        holepunch: ourRemoteAddr ? null : { id, relays: this._announcer.relays },
        addresses4: addresses,
        addresses6: null,
        udx: {
          reusableSocket: this._reusableSocket,
          id: hs.rawStream ? hs.rawStream.id : 0,
          seq: 0
        },
        secretStream: {},
        relayThrough: relayThrough ? { publicKey: relayThrough, token: hs.relayToken } : null,
        relayAddresses: relayAddresses.length ? relayAddresses : null
      })
    } catch (err) {
      safetyCatch(err)
      if (hs.rawStream) hs.rawStream.destroy()
      this._clearLater(hs, id, k)
      return null
    }

    if (this._closing || this.suspended) {
      if (hs.rawStream) hs.rawStream.destroy()
      return null
    }

    const h = handshake.final()

    if (error !== ERROR.NONE) {
      if (hs.rawStream) hs.rawStream.destroy()
      this._clearLater(hs, id, k)
      return hs
    }

    if (remotePayload.firewall === FIREWALL.OPEN || direct) {
      const sock = direct ? socket : this.dht.socket
      this.dht.stats.punches.open++
      hs.onsocket(sock, clientAddress.port, clientAddress.host)
      return hs
    }

    if (relayThrough || remotePayload.relayThrough) {
      this._relayConnection(hs, relayThrough, remotePayload, h)
    }

    const onabort = () => {
      hs.aborted = true
      if (hs.prepunching) clearTimeout(hs.prepunching)
      hs.prepunching = null
      if (hs.puncher) {
        hs.puncher.onabort = noop
        hs.puncher.destroy()
      }
      if (hs.rawStream.destroyed) {
        this._clearLater(hs, id, k)
        return
      }

      hs.rawStream.on('close', () => this._clearLater(hs, id, k))
      if (hs.relayToken === null) hs.rawStream.destroy()
    }

    if (!direct && clientAddress.host === serverAddress.host) {
      const clientAddresses = remotePayload.addresses4.filter((addr) => isPrivate(addr.host))

      if (clientAddresses.length > 0 && this._shareLocalAddress) {
        const myAddresses = await this._localAddresses()
        const addr = Holepuncher.matchAddress(myAddresses, clientAddresses)

        if (addr) {
          hs.payload = new SecurePayload(h.holepunchSecret)
          setupHolepuncher(this.dht, hs, remotePayload.firewall, onabort)
          hs.prepunching = setTimeout(onabort, HANDSHAKE_INITIAL_TIMEOUT)
          return hs
        }
      }
    }

    if (this._closing || this.suspended) return null

    if (ourRemoteAddr || this._neverPunch) {
      hs.prepunching = setTimeout(onabort, HANDSHAKE_INITIAL_TIMEOUT)
      return hs
    }

    hs.payload = new SecurePayload(h.holepunchSecret)
    setupHolepuncher(this.dht, hs, remotePayload.firewall, onabort)
    hs.replyFromPuncher = true
    hs.prepunching = setTimeout(hs.puncher.destroy.bind(hs.puncher), HANDSHAKE_INITIAL_TIMEOUT)

    return hs
  }

  _clearLater(hs, id, k) {
    if (hs.clearing) return
    hs.clearing = setTimeout(() => this._clear(hs, id, k), this.handshakeClearWait)
  }

  _clear(hs, id, k) {
    if (id >= this._holepunches.length || this._holepunches[id] !== hs) return
    if (hs.clearing) clearTimeout(hs.clearing)

    this._holepunches[id] = null
    while (
      this._holepunches.length > 0 &&
      this._holepunches[this._holepunches.length - 1] === null
    ) {
      this._holepunches.pop()
    }
    this._connects.delete(k)
  }

  async _onpeerhandshake({ noise, peerAddress }, req) {
    const k = b4a.toString(noise, 'hex')

    // The next couple of statements MUST run within the same tick to prevent
    // a malicious peer from flooding us with handshakes.
    let p = this._connects.get(k)
    if (!p) {
      p = this._addHandshake(k, noise, peerAddress || req.from, req, !peerAddress)
      this._connects.set(k, p)
    }

    const h = await p
    if (!h) return null

    if (this._closing !== null || this.suspended) return null

    // Routed handshake replies advertise the socket they are sent from as the
    // server address. Same-LAN prepunch also creates a puncher, but it must
    // keep advertising the normal server socket so the LAN shortcut can open.
    return { socket: h.replyFromPuncher ? h.puncher.socket : null, noise: h.reply }
  }

  async _onpeerholepunch({ id, peerAddress, payload }, req) {
    const h = id < this._holepunches.length ? this._holepunches[id] : null
    if (!h) return null

    if (!peerAddress || this._closing !== null || this.suspended) return null
    if (!h.payload) return this._abort(h) // not opened

    const remotePayload = h.payload.decrypt(payload)
    if (!remotePayload) return null

    const p = h.puncher
    if (!p || !p.socket) return this._abort(h) // not opened

    const isServerRelay = this._announcer.isRelay(req.from)
    const { error, firewall, round, punching, addresses, remoteAddress, remoteToken } =
      remotePayload

    if (error !== ERROR.NONE) {
      // We actually do not need to set the round here, but just do it for consistency.
      if (round >= h.round) h.round = round
      return this._abort(h)
    }

    const token = h.payload.token(peerAddress)
    const echoed = isServerRelay && !!remoteToken && b4a.equals(token, remoteToken)

    // Update our heuristics here
    if (req.socket === p.socket) {
      p.nat.add(req.to, req.from)
    }

    if (round >= h.round) {
      h.round = round
      p.updateRemote({ punching, firewall, addresses, verified: echoed ? peerAddress.host : null })
    }

    // Wait for the analyzer to reach a conclusion...
    let stable = await p.analyze(false)
    if (p.destroyed) return null

    if (!p.remoteHolepunching && !stable) {
      stable = await p.analyze(true)
      if (p.destroyed) return null
      if (!stable) return this._abort(h)
    }

    // Fast mode! If we are consistent and the remote has opened a session to us (remoteAddress)
    // then fire a quick punch back. Note the await here just waits for the udp socket to flush.
    if (
      isConsistent(p.nat.firewall) &&
      remoteAddress &&
      hasSameAddr(p.nat.addresses, remoteAddress)
    ) {
      await p.ping(peerAddress)
      if (p.destroyed) return null
    }

    // Remote said they are punching (or willing to), so we will punch as well.
    // Note that this returns when the punching has STARTED, so no guarantee
    // we will have a connection after this promise etc.
    if (p.remoteHolepunching) {
      // TODO: still continue here if a local connection might work, but then do not holepunch...
      if (!this.holepunch(p.remoteFirewall, p.nat.firewall, p.remoteAddresses, p.nat.addresses)) {
        return p.destroyed ? null : this._abort(h)
      }

      if (h.prepunching) {
        clearTimeout(h.prepunching)
        h.prepunching = null
      }

      if (p.remoteFirewall >= FIREWALL.RANDOM || p.nat.firewall >= FIREWALL.RANDOM) {
        if (
          this.dht._randomPunches >= this.dht._randomPunchLimit ||
          Date.now() - this.dht._lastRandomPunch < this.dht._randomPunchInterval
        ) {
          if (!h.relayToken) return this._abort(h, ERROR.TRY_LATER)
          return {
            socket: p.socket,
            payload: h.payload.encrypt({
              error: ERROR.TRY_LATER,
              firewall: p.nat.firewall,
              round: h.round,
              connected: p.connected,
              punching: p.punching,
              addresses: p.nat.addresses,
              remoteAddress: null,
              token: isServerRelay ? token : null,
              remoteToken: remotePayload.token
            })
          }
        }
      }

      const punching = await p.punch()
      if (p.destroyed) return null
      if (!punching) return this._abort(h)
    }

    // Freeze that analysis as soon as we have a result we are giving to the other peer
    if (p.nat.firewall !== FIREWALL.UNKNOWN) {
      p.nat.freeze()
    }

    return {
      socket: p.socket,
      payload: h.payload.encrypt({
        error: ERROR.NONE,
        firewall: p.nat.firewall,
        round: h.round,
        connected: p.connected,
        punching: p.punching,
        addresses: p.nat.addresses,
        remoteAddress: null,
        token: isServerRelay ? token : null,
        remoteToken: remotePayload.token
      })
    }
  }

  _abort(h, error = ERROR.ABORTED) {
    if (!h.payload) {
      if (h.puncher) h.puncher.destroy()
      return null
    }

    const payload = h.payload.encrypt({
      error,
      firewall: FIREWALL.UNKNOWN,
      round: h.round,
      connected: false,
      punching: false,
      addresses: null,
      remoteAddress: null,
      token: null,
      remoteToken: null
    })

    if (h.puncher) h.puncher.destroy()

    return { socket: this.dht.socket, payload }
  }

  _relayConnection(hs, relayThrough, remotePayload, h) {
    this.dht.stats.relaying.attempts++

    let isInitiator
    let publicKey
    let token

    if (relayThrough) {
      isInitiator = true
      publicKey = relayThrough
      token = hs.relayToken
    } else {
      isInitiator = false
      publicKey = remotePayload.relayThrough.publicKey
      token = remotePayload.relayThrough.token
    }

    hs.relayToken = token
    hs.relaySocket = this.dht.connect(publicKey)
    hs.relaySocket.setKeepAlive(this.relayKeepAlive)
    hs.relayClient = relay.Client.from(hs.relaySocket, { id: hs.relaySocket.publicKey })
    hs.relayTimeout = setTimeout(onabort, 15000)

    hs.relayClient
      .pair(isInitiator, token, hs.rawStream)
      .on('error', onabort)
      .on('data', (remoteId) => {
        if (hs.relayTimeout) clearRelayTimeout(hs)
        if (hs.rawStream === null) {
          onabort(null)
          return
        }

        hs.relayPaired = true
        this.dht.stats.relaying.successes++

        if (hs.prepunching) clearTimeout(hs.prepunching)
        hs.prepunching = null

        const { remotePort, remoteHost, socket } = hs.relaySocket.rawStream

        hs.rawStream
          .on('close', () => destroyRelayConnection(hs))
          .connect(socket, remoteId, remotePort, remoteHost)

        hs.encryptedSocket = this.createSecretStream(false, hs.rawStream, {
          handshake: h,
          keepAlive: this.dht.connectionKeepAlive
        })

        this.onconnection(hs.encryptedSocket)
      })

    const dht = this.dht
    function onabort() {
      if (!hs.relayPaired) dht.stats.relaying.aborts++
      destroyRelayConnection(hs)
      if (hs.aborted && hs.rawStream) hs.rawStream.destroy()
    }
  }
}

function isConsistent(fw) {
  return fw === FIREWALL.OPEN || fw === FIREWALL.CONSISTENT
}

function hasSameAddr(addrs, other) {
  if (addrs === null) return false

  for (const addr of addrs) {
    if (addr.port === other.port && addr.host === other.host) return true
  }
  return false
}

function defaultCreateHandshake(keyPair, remotePublicKey) {
  return new NoiseWrap(keyPair, remotePublicKey)
}

function defaultCreateSecretStream(isInitiator, rawStream, opts) {
  return new NoiseSecretStream(isInitiator, rawStream, opts)
}

function setupHolepuncher(dht, hs, remoteFirewall, onabort) {
  if (hs.puncher) return

  hs.puncher = new Holepuncher(dht, dht.session(), false, remoteFirewall)
  hs.puncher.onconnect = hs.onsocket
  hs.puncher.onabort = onabort
}

function isRelay(relaySocket, socket, port, host) {
  const stream = relaySocket.rawStream
  if (!stream) return false
  if (stream.socket !== socket) return false
  return port === stream.remotePort && host === stream.remoteHost
}

function selectRelay(relayThrough) {
  if (typeof relayThrough === 'function') relayThrough = relayThrough()
  if (relayThrough === null) return null
  if (Array.isArray(relayThrough)) {
    return relayThrough[Math.floor(Math.random() * relayThrough.length)]
  }
  return relayThrough
}

function noop() {}
module.exports = class Sleeper {
  constructor() {
    this._timeout = null
    this._resolve = null

    this._start = (resolve) => {
      this._resolve = resolve
    }

    this._trigger = () => {
      if (this._resolve === null) return
      const resolve = this._resolve
      this._timeout = null
      this._resolve = null
      resolve()
    }
  }

  pause(ms) {
    const p = new Promise(this._start)
    if (this._timeout !== null) {
      clearTimeout(this._timeout)
      this._trigger()
    }
    this._timeout = setTimeout(this._trigger, ms)
    return p
  }

  resume() {
    if (this._timeout !== null) {
      clearTimeout(this._timeout)
      this._trigger()
    }
  }
}
const b4a = require('b4a')

const LINGER_TIME = 3000

module.exports = class SocketPool {
  constructor(dht, host) {
    this._dht = dht
    this._sockets = new Map()
    this._lingering = new Set() // updated by the ref
    this._host = host

    this.routes = new SocketRoutes(this)
  }

  _onmessage(ref, data, address) {
    this._dht.onmessage(ref.socket, data, address)
  }

  _add(ref) {
    this._sockets.set(ref.socket, ref)
  }

  _remove(ref) {
    this._sockets.delete(ref.socket)
    this._lingering.delete(ref)
  }

  lookup(socket) {
    return this._sockets.get(socket) || null
  }

  setReusable(socket, bool) {
    const ref = this.lookup(socket)
    if (ref) ref.reusable = bool
  }

  acquire() {
    // TODO: Enable socket reuse
    return new SocketRef(this)
  }

  async destroy() {
    const closing = []

    for (const ref of this._sockets.values()) {
      ref._unlinger()
      closing.push(ref.socket.close())
    }

    await Promise.allSettled(closing)
  }
}

class SocketRoutes {
  constructor(pool) {
    this._pool = pool
    this._routes = new Map()
  }

  add(publicKey, rawStream) {
    if (rawStream.socket) this._onconnect(publicKey, rawStream)
    else rawStream.on('connect', this._onconnect.bind(this, publicKey, rawStream))
  }

  get(publicKey) {
    const id = b4a.toString(publicKey, 'hex')
    const route = this._routes.get(id)
    if (!route) return null
    return route
  }

  _onconnect(publicKey, rawStream) {
    const id = b4a.toString(publicKey, 'hex')
    const socket = rawStream.socket

    let route = this._routes.get(id)

    if (!route) {
      const gc = () => {
        if (this._routes.get(id) === route) this._routes.delete(id)
        socket.removeListener('close', gc)
      }

      route = {
        socket,
        address: { host: rawStream.remoteHost, port: rawStream.remotePort },
        gc
      }

      this._routes.set(id, route)
      socket.on('close', gc)
    }

    this._pool.setReusable(socket, true)

    rawStream.on('error', () => {
      this._pool.setReusable(socket, false)
      if (!route) route = this._routes.get(id)
      if (route && route.socket === socket) route.gc()
    })
  }
}

// TODO: we should just make some "user data" object on udx to allow to attach this info
class SocketRef {
  constructor(pool) {
    this._pool = pool

    // Events
    this.onholepunchmessage = noop

    // Whether it should teardown immediately or wait a bit
    this.reusable = false

    this.socket = pool._dht.udx.createSocket()
    this.socket
      .on('close', this._onclose.bind(this))
      .on('message', this._onmessage.bind(this))
      .on('idle', this._onidle.bind(this))
      .on('busy', this._onbusy.bind(this))
      .bind(0, this._pool._host)

    this._refs = 1
    this._released = false
    this._closed = false

    this._timeout = null
    this._wasBusy = false

    this._pool._add(this)
  }

  _onclose() {
    this._pool._remove(this)
  }

  _onmessage(data, address) {
    if (data.byteLength > 1) {
      this._pool._onmessage(this, data, address)
    } else {
      this.onholepunchmessage(data, address, this)
    }
  }

  _onidle() {
    this._closeMaybe()
  }

  _onbusy() {
    this._wasBusy = true
    this._unlinger()
  }

  _reset() {
    this.onholepunchmessage = noop
  }

  _closeMaybe() {
    if (this._refs === 0 && this.socket.idle && !this._timeout) this._close()
  }

  _lingeringClose() {
    this._pool._lingering.delete(this)
    this._timeout = null
    this._closeMaybe()
  }

  _close() {
    this._unlinger()

    if (this.reusable && this._wasBusy) {
      this._wasBusy = false
      this._pool._lingering.add(this)
      this._timeout = setTimeout(this._lingeringClose.bind(this), LINGER_TIME)
      return
    }

    this._closed = true
    this.socket.close()
  }

  _unlinger() {
    if (this._timeout !== null) {
      clearTimeout(this._timeout)
      this._pool._lingering.delete(this)
      this._timeout = null
    }
  }

  get free() {
    return this._refs === 0
  }

  active() {
    this._refs++
    this._unlinger()
  }

  inactive() {
    this._refs--
    this._closeMaybe()
  }

  address() {
    return this.socket.address()
  }

  release() {
    if (this._released) return

    this._released = true
    this._reset()

    this._refs--
    this._closeMaybe()
  }
}

function noop() {}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "hyperdht",
  "version": "6.33.0",
  "description": "The DHT powering Hyperswarm",
  "main": "index.js",
  "browser": "browser.js",
  "bin": {
    "hyperdht": "./bin.js"
  },
  "files": [
    "index.js",
    "browser.js",
    "testnet.js",
    "bin.js",
    "lib/**.js"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    },
    "child_process": {
      "bare": "bare-node-child-process",
      "default": "child_process"
    }
  },
  "dependencies": {
    "@hyperswarm/secret-stream": "^6.6.2",
    "b4a": "^1.3.1",
    "bare-events": "^2.2.0",
    "blind-relay": "^1.3.0",
    "bogon": "^1.0.0",
    "compact-encoding": "^3.0.0",
    "dht-rpc": "^6.15.1",
    "hypercore-crypto": "^3.3.0",
    "hypercore-id-encoding": "^1.2.0",
    "hyperdht-address": "^1.0.1",
    "noise-curve-ed": "^2.0.0",
    "noise-handshake": "^4.0.0",
    "record-cache": "^1.1.1",
    "safety-catch": "^1.0.1",
    "signal-promise": "^1.0.3",
    "sodium-universal": "^5.0.1",
    "streamx": "^2.16.1",
    "unslab": "^1.3.0",
    "xache": "^1.1.0"
  },
  "devDependencies": {
    "bare-node-child-process": "^1.0.1",
    "brittle": "^3.0.0",
    "graceful-goodbye": "^1.3.0",
    "newline-decoder": "^1.0.2",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "test": "prettier --check . && node test/all.js",
    "test:bare": "bare test/all.js",
    "test:generate": "brittle -r test/all.js test/*.js",
    "integration": "brittle test/integration/*.js",
    "end-to-end": "brittle test/end-to-end/*.js"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "directories": {
    "lib": "lib",
    "test": "test"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/hyperdht.git"
  },
  "keywords": [],
  "bugs": {
    "url": "https://github.com/holepunchto/hyperdht/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperdht#readme"
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "hyperschema",
  "version": "1.21.0",
  "description": "Create registries of declarative compact-encoding schemas",
  "files": [
    "lib/*.js",
    "builder.mjs",
    "builder.cjs",
    "runtime.mjs",
    "runtime.cjs",
    "primitives.mjs",
    "primitives.cjs"
  ],
  "exports": {
    "./package": "./package.json",
    ".": {
      "import": "./builder.mjs",
      "default": "./builder.cjs"
    },
    "./runtime": {
      "import": "./runtime.mjs",
      "default": "./runtime.cjs"
    },
    "./primitives": {
      "import": "./primitives.mjs",
      "default": "./primitives.cjs"
    }
  },
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    }
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test/index.js",
    "test:bare": "prettier . --check && bare test/index.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/hyperschema.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/hyperschema/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperschema#readme",
  "dependencies": {
    "bare-fs": "^4.0.1",
    "compact-encoding": "^3.0.0",
    "generate-object-property": "^2.0.0",
    "generate-string": "^1.0.1"
  },
  "devDependencies": {
    "brittle": "^3.7.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "test-tmp": "^1.3.0"
  }
}
module.exports = {
  c: require('compact-encoding')
}
const { EventEmitter } = require('events')
const { getStreamError } = require('streamx')
const DHT = require('hyperdht')
const spq = require('shuffled-priority-queue')
const b4a = require('b4a')
const unslab = require('unslab')

const PeerInfo = require('./lib/peer-info')
const RetryTimer = require('./lib/retry-timer')
const ConnectionSet = require('./lib/connection-set')
const PeerDiscovery = require('./lib/peer-discovery')

const MAX_PEERS = 64
const MAX_PARALLEL = 3
const MAX_CLIENT_CONNECTIONS = Infinity // TODO: Change
const MAX_SERVER_CONNECTIONS = Infinity

const ERR_MISSING_TOPIC = 'Topic is required and must be a 32-byte buffer'
const ERR_DESTROYED = 'Swarm has been destroyed'
const ERR_DUPLICATE = 'Duplicate connection'
const ERR_FIREWALL = 'Peer is firewalled'

module.exports = class Hyperswarm extends EventEmitter {
  constructor(opts = {}) {
    super()
    const {
      seed,
      relayThrough,
      keyPair = DHT.keyPair(seed),
      maxPeers = MAX_PEERS,
      maxClientConnections = MAX_CLIENT_CONNECTIONS,
      maxServerConnections = MAX_SERVER_CONNECTIONS,
      maxParallel = MAX_PARALLEL,
      firewall = allowAll
    } = opts
    this.keyPair = keyPair

    this.dht =
      opts.dht ||
      new DHT({
        bootstrap: opts.bootstrap,
        nodes: opts.nodes,
        port: opts.port,
        deferRandomPunch: opts.deferRandomPunch,
        randomPunchInterval: opts.randomPunchInterval
      })
    this.server = this.dht.createServer(
      {
        firewall: this._handleFirewall.bind(this),
        relayThrough: this._maybeRelayConnection.bind(this),
        handshakeClearWait: opts.handshakeClearWait
      },
      this._handleServerConnection.bind(this)
    )

    this.destroyed = false
    this.suspended = false
    this.maxPeers = maxPeers
    this.maxClientConnections = maxClientConnections
    this.maxServerConnections = maxServerConnections
    this.maxParallel = maxParallel
    this.relayThrough = relayThrough ? toRelayFunction(relayThrough) : null

    this.connecting = 0
    this.connections = new Set()
    this.peers = new Map()
    this.explicitPeers = new Set()
    this.listening = null
    this.stats = {
      updates: 0,
      connects: {
        client: {
          opened: 0,
          closed: 0,
          attempted: 0
        },
        server: {
          // Note: there is no notion of 'attempts' for server connections
          opened: 0,
          closed: 0
        }
      },
      bannedPeers: 0
    }

    this._discovery = new Map()
    this._timer = new RetryTimer(this._requeue.bind(this), {
      backoffs: opts.backoffs,
      jitter: opts.jitter
    })
    this._queue = spq()

    this._allConnections = new ConnectionSet()
    this._pendingFlushes = []
    this._flushTick = 0

    this._drainingQueue = false
    this._clientConnections = 0
    this._serverConnections = 0
    this._firewall = firewall

    this.dht.on('network-change', this._handleNetworkChange.bind(this))
    this.dht.on('network-update', this._handleNetworkUpdate.bind(this))
    this.on('update', this._handleUpdate)
  }

  _maybeRelayConnection(force) {
    if (!this.relayThrough) return null
    return this.relayThrough(force, this)
  }

  _enqueue(peerInfo) {
    if (peerInfo.queued) return
    peerInfo.queued = true
    peerInfo._flushTick = this._flushTick
    this._queue.add(peerInfo)

    this._attemptClientConnections()
  }

  _requeue(batch) {
    if (this.suspended) return
    for (const peerInfo of batch) {
      peerInfo.waiting = false

      if (
        peerInfo._updatePriority() === false ||
        this._allConnections.has(peerInfo.publicKey) ||
        peerInfo.queued
      ) {
        continue
      }
      peerInfo.queued = true
      peerInfo._flushTick = this._flushTick
      this._queue.add(peerInfo)
    }

    this._attemptClientConnections()
  }

  _flushMaybe(peerInfo) {
    for (let i = 0; i < this._pendingFlushes.length; i++) {
      const flush = this._pendingFlushes[i]
      if (peerInfo._flushTick > flush.tick) continue
      if (--flush.missing > 0) continue
      flush.onflush(true)
      this._pendingFlushes.splice(i--, 1)
    }
  }

  _withinMaxPeers() {
    const e = this.explicitPeers.size
    const factor = e === 0 ? 1 : e < 2 ? 2 : e < 4 ? 3 : 4
    return factor * this._allConnections.size < this.maxPeers
  }

  _flushAllMaybe() {
    if (
      this.connecting > 0 ||
      (this._withinMaxPeers() && this._clientConnections < this.maxClientConnections)
    ) {
      return false
    }

    while (this._pendingFlushes.length) {
      const flush = this._pendingFlushes.pop()
      flush.onflush(true)
    }

    return true
  }

  _shouldConnectExplicit() {
    return !this.destroyed && !this.suspended && this.connecting < this.maxParallel
  }

  _shouldConnect() {
    return (
      !this.destroyed &&
      !this.suspended &&
      this.connecting < this.maxParallel &&
      this._withinMaxPeers() &&
      this._clientConnections < this.maxClientConnections
    )
  }

  _shouldRequeue(peerInfo) {
    if (this.suspended) return false
    if (peerInfo.explicit) return true
    for (const topic of peerInfo.topics) {
      if (this._discovery.has(b4a.toString(topic, 'hex')) && !this.destroyed) {
        return true
      }
    }
    return false
  }

  _connect(peerInfo, queued) {
    if (peerInfo.banned || this._allConnections.has(peerInfo.publicKey)) {
      if (queued) this._flushMaybe(peerInfo)
      return
    }

    // TODO: Support async firewalling at some point.
    if (this._handleFirewall(peerInfo.publicKey, null)) {
      if (queued) this._flushMaybe(peerInfo)
      return
    }

    const relayThrough = this._maybeRelayConnection(peerInfo.forceRelaying)
    const conn = this.dht.connect(peerInfo.publicKey, {
      relayAddresses: peerInfo.relayAddresses,
      keyPair: this.keyPair,
      relayThrough
    })
    this._allConnections.add(conn)

    this.stats.connects.client.attempted++

    this.connecting++
    this._clientConnections++
    let opened = false

    const onerror = (err) => {
      if (this.relayThrough && shouldForceRelaying(err.code)) {
        peerInfo.forceRelaying = true
        // Reset the attempts in order to fast connect to relay
        peerInfo.attempts = 0
      }
    }

    // Removed once a connection is opened
    conn.on('error', onerror)

    conn.on('open', () => {
      opened = true
      this.stats.connects.client.opened++

      this._connectDone()
      this.connections.add(conn)
      conn.removeListener('error', onerror)
      peerInfo._connected()
      peerInfo.client = true
      this.emit('connection', conn, peerInfo)
      if (queued) this._flushMaybe(peerInfo)

      this.emit('update')
    })
    conn.on('close', () => {
      if (!opened) this._connectDone()
      this.stats.connects.client.closed++

      const err = getStreamError(conn)
      if (shouldBan(err)) {
        this._banPeer(peerInfo, true, err)
      }

      this.connections.delete(conn)
      this._allConnections.delete(conn)
      this._clientConnections--
      peerInfo._disconnected()

      peerInfo.waiting = this._shouldRequeue(peerInfo) && this._timer.add(peerInfo)
      this._maybeDeletePeer(peerInfo)

      if (!opened && queued) this._flushMaybe(peerInfo)

      this._attemptClientConnections()

      this.emit('update')
    })

    this.emit('update')
  }

  _connectDone() {
    this.connecting--

    if (this.connecting < this.maxParallel) this._attemptClientConnections()
    if (this.connecting === 0) this._flushAllMaybe()
  }

  // Called when the PeerQueue indicates a connection should be attempted.
  _attemptClientConnections() {
    // Guard against re-entries - unsure if it still needed but doesn't hurt
    if (this._drainingQueue || this.suspended) return
    this._drainingQueue = true

    for (const peerInfo of this.explicitPeers) {
      if (!this._shouldConnectExplicit()) break
      if (
        peerInfo.attempts >= 5 ||
        Date.now() - peerInfo.disconnectedTime < peerInfo.attempts * 1000
      ) {
        continue
      }
      this._connect(peerInfo, false)
    }

    while (this._queue.length && this._shouldConnect()) {
      const peerInfo = this._queue.shift()
      peerInfo.queued = false
      this._connect(peerInfo, true)
    }
    this._drainingQueue = false
    if (this.connecting === 0) this._flushAllMaybe()
  }

  _handleFirewall(remotePublicKey, payload) {
    if (b4a.equals(remotePublicKey, this.keyPair.publicKey)) return true

    let peerInfo = this.peers.get(b4a.toString(remotePublicKey, 'hex'))
    if (peerInfo && peerInfo.banned) return true

    const firewalled = this._firewall(remotePublicKey, payload)
    if (firewalled) {
      if (!peerInfo) peerInfo = this._upsertPeer(remotePublicKey)
      this._banPeer(peerInfo, true, new Error(ERR_FIREWALL))
    }

    return firewalled
  }

  _handleServerConnectionSwap(existing, conn) {
    let closed = false

    existing.on('close', () => {
      if (closed) return

      conn.removeListener('error', noop)
      conn.removeListener('close', onclose)

      this._handleServerConnection(conn)
    })

    conn.on('error', noop)
    conn.on('close', onclose)

    function onclose() {
      closed = true
    }
  }

  // Called when the DHT receives a new server connection.
  _handleServerConnection(conn) {
    if (this.destroyed || this.suspended) {
      // TODO: Investigate why a final server connection can be received after close
      conn.on('error', noop)
      return conn.destroy(ERR_DESTROYED)
    }

    const existing = this._allConnections.get(conn.remotePublicKey)

    if (existing) {
      // If both connections are from the same peer,
      // - pick the new one if the existing stream is already established (has sent and received bytes),
      //   because the other client must have lost that connection and be reconnecting
      // - otherwise, pick the one thats expected to initiate in a tie break
      const existingIsOutdated = existing.rawBytesRead > 0 && existing.rawBytesWritten > 0
      const expectedInitiator = b4a.compare(conn.publicKey, conn.remotePublicKey) > 0
      const keepNew = existingIsOutdated || expectedInitiator === conn.isInitiator

      if (keepNew === false) {
        existing.sendKeepAlive()
        conn.on('error', noop)
        conn.destroy(new Error(ERR_DUPLICATE))
        return
      }

      existing.on('error', noop)
      existing.destroy(new Error(ERR_DUPLICATE))
      this._handleServerConnectionSwap(existing, conn)
      return
    }

    // When reaching here, the connection will always be 'opened' next tick
    this.stats.connects.server.opened++

    const peerInfo = this._upsertPeer(conn.remotePublicKey, null)

    this.connections.add(conn)
    this._allConnections.add(conn)
    this._serverConnections++

    conn.on('close', () => {
      const err = getStreamError(conn)
      if (shouldBan(err)) {
        this._banPeer(peerInfo, true, err)
      }

      this.connections.delete(conn)
      this._allConnections.delete(conn)
      this._serverConnections--
      this.stats.connects.server.closed++

      this._maybeDeletePeer(peerInfo)

      this._attemptClientConnections()

      this.emit('update')
    })
    peerInfo.client = false
    this.emit('connection', conn, peerInfo)

    this.emit('update')
  }

  _upsertPeer(publicKey, relayAddresses) {
    if (b4a.equals(publicKey, this.keyPair.publicKey)) return null
    const keyString = b4a.toString(publicKey, 'hex')
    let peerInfo = this.peers.get(keyString)

    if (peerInfo) {
      peerInfo.relayAddresses = relayAddresses // new is always better
      return peerInfo
    }

    peerInfo = new PeerInfo({
      publicKey,
      relayAddresses
    })

    this.peers.set(keyString, peerInfo)
    return peerInfo
  }

  _handleUpdate() {
    this.stats.updates++
  }

  _maybeDeletePeer(peerInfo) {
    if (!peerInfo.shouldGC()) return

    const hasActiveConn = this._allConnections.has(peerInfo.publicKey)
    if (hasActiveConn) return

    const keyString = b4a.toString(peerInfo.publicKey, 'hex')
    this.peers.delete(keyString)
  }

  /*
   * Called when a peer is actively discovered during a lookup.
   *
   * Three conditions:
   *  1. Not a known peer -- insert into queue
   *  2. A known peer with normal priority -- do nothing
   *  3. A known peer with low priority -- bump priority, because it's been rediscovered
   */
  _handlePeer(peer, topic) {
    const peerInfo = this._upsertPeer(peer.publicKey, peer.relayAddresses)
    if (peerInfo) peerInfo._topic(topic)
    if (!peerInfo || this._allConnections.has(peer.publicKey)) return
    if (!peerInfo.prioritized || peerInfo.server) peerInfo._reset()
    if (peerInfo._updatePriority()) {
      this._enqueue(peerInfo)
    }
  }

  async _handleNetworkUpdate() {
    if (!this.online) return
    this._handleNetworkChange()
  }

  async _handleNetworkChange() {
    if (this.suspended) return

    // prioritize figuring out if existing connections are dead
    for (const conn of this._allConnections) {
      conn.sendKeepAlive()
    }

    const refreshes = []

    for (const discovery of this._discovery.values()) {
      refreshes.push(discovery.refresh())
    }

    await Promise.allSettled(refreshes)
  }

  _banPeer(peerInfo, banned, err) {
    peerInfo.ban(banned)
    this.stats.bannedPeers++
    this.emit('ban', peerInfo, err)
  }

  status(key) {
    return this._discovery.get(b4a.toString(key, 'hex')) || null
  }

  listen() {
    if (!this.listening) {
      if (this.destroyed) throw new Error('Swarm destroyed')
      this.listening = this.server.listen(this.keyPair)
    }
    return this.listening
  }

  // Object that exposes a cancellation method (destroy)
  // TODO: When you rejoin, it should reannounce + bump lookup priority
  join(topic, opts = {}) {
    if (this.destroyed) throw new Error('Swarm destroyed')
    if (!topic) throw new Error(ERR_MISSING_TOPIC)
    topic = unslab(topic)

    const topicString = b4a.toString(topic, 'hex')

    let discovery = this._discovery.get(topicString)

    if (discovery && !discovery.destroyed) {
      return discovery.session(opts)
    }

    discovery = new PeerDiscovery(this, topic, {
      limit: opts.limit,
      wait: discovery ? discovery.destroy() : null,
      suspended: this.suspended,
      onpeer: (peer) => this._handlePeer(peer, topic)
    })
    this._discovery.set(topicString, discovery)
    return discovery.session(opts)
  }

  // Returns a promise
  async leave(topic) {
    if (!topic) throw new Error(ERR_MISSING_TOPIC)
    const topicString = b4a.toString(topic, 'hex')
    if (!this._discovery.has(topicString)) return Promise.resolve()

    const discovery = this._discovery.get(topicString)

    try {
      await discovery.destroy()
    } catch {
      // ignore, prop network
    }

    if (this._discovery.get(topicString) === discovery) {
      this._discovery.delete(topicString)
    }
  }

  joinPeer(publicKey) {
    const peerInfo = this._upsertPeer(publicKey, null)
    if (!peerInfo) return
    if (!this.explicitPeers.has(peerInfo)) {
      peerInfo.explicit = true
      this.explicitPeers.add(peerInfo)
    }
    if (this._allConnections.has(publicKey)) return
    if (peerInfo._updatePriority()) {
      this._enqueue(peerInfo)
    }
  }

  leavePeer(publicKey) {
    const keyString = b4a.toString(publicKey, 'hex')
    if (!this.peers.has(keyString)) return

    const peerInfo = this.peers.get(keyString)
    peerInfo.explicit = false
    this.explicitPeers.delete(peerInfo)
    this._maybeDeletePeer(peerInfo)
  }

  // Returns a promise
  async flush() {
    const allFlushed = [...this._discovery.values()].map((v) => v.flushed())
    await Promise.all(allFlushed)
    if (this._flushAllMaybe()) return true
    const pendingSize = this._allConnections.size - this.connections.size
    if (!this._queue.length && !pendingSize) return true
    return new Promise((resolve) => {
      this._pendingFlushes.push({
        onflush: resolve,
        missing: this._queue.length + pendingSize,
        tick: this._flushTick++
      })
    })
  }

  async clear() {
    const cleared = Promise.allSettled([...this._discovery.values()].map((d) => d.destroy()))
    this._discovery.clear()
    return cleared
  }

  async destroy({ force } = {}) {
    if (this.destroyed && !force) return
    this.destroyed = true

    this._timer.destroy()

    if (!force) await this.clear()

    await this.server.close()

    while (this._pendingFlushes.length) {
      const flush = this._pendingFlushes.pop()
      flush.onflush(false)
    }

    await this.dht.destroy({ force })
  }

  async suspend({ log = noop } = {}) {
    if (this.suspended) return

    const promises = []

    promises.push(this.server.suspend({ log }))

    for (const discovery of this._discovery.values()) {
      promises.push(discovery.suspend({ log }))
    }

    const pending = []
    for (const connection of this._allConnections) {
      connection.destroy()
      pending.push(new Promise((resolve) => connection.on('close', resolve)))
    }

    this.suspended = true

    log('Suspending server and discovery... (' + promises.length + ')')
    await Promise.allSettled(promises)
    log('Done, suspending the dht...')
    await this.dht.suspend({ log })
    log('Done, swarm fully suspended')

    await Promise.all(pending)

    // reset queue
    this._timer.destroy()
    this._timer = new RetryTimer(this._requeue.bind(this), {
      backoffs: this._timer.backoffs,
      jitter: this._timer.jitter
    })
    this._queue = spq()
  }

  async resume({ log = noop } = {}) {
    if (!this.suspended) return

    log('Resuming the dht')
    await this.dht.resume()
    log('Done, resuming the server')
    await this.server.resume()
    log('Done, all discovery')

    for (const discovery of this._discovery.values()) {
      discovery.resume()
    }

    this.suspended = false
    this._attemptClientConnections()
  }

  topics() {
    return this._discovery.values()
  }
}

function noop() {}

function allowAll() {
  return false
}

function shouldForceRelaying(code) {
  return (
    code === 'HOLEPUNCH_ABORTED' ||
    code === 'HOLEPUNCH_DOUBLE_RANDOMIZED_NATS' ||
    code === 'REMOTE_NOT_HOLEPUNCHABLE'
  )
}

function shouldBan() {
  // return !!err && err.name === 'HypercoreError' && err.code === 'INVALID_OPERATION'
  return false
}

function toRelayFunction(relayThrough) {
  return typeof relayThrough === 'function'
    ? relayThrough
    : (force, swarm) => (force || swarm.dht.randomized ? relayThrough : null)
}
module.exports = class BulkTimer {
  constructor(time, fn) {
    this._time = time
    this._fn = fn
    this._interval = null
    this._next = []
    this._pending = []
    this._destroyed = false
  }

  destroy() {
    if (this._destroyed) return
    this._destroyed = true
    clearInterval(this._interval)
    this._interval = null
  }

  _ontick() {
    if (!this._next.length && !this._pending.length) return
    if (this._next.length) this._fn(this._next)
    this._next = this._pending
    this._pending = []
  }

  add(info) {
    if (this._destroyed) return
    if (!this._interval) {
      this._interval = setInterval(this._ontick.bind(this), Math.floor(this._time * 0.66))
    }

    this._pending.push(info)
  }
}
const b4a = require('b4a')

module.exports = class ConnectionSet {
  constructor() {
    this._byPublicKey = new Map()
  }

  [Symbol.iterator]() {
    return this._byPublicKey.values()
  }

  get size() {
    return this._byPublicKey.size
  }

  has(publicKey) {
    return this._byPublicKey.has(toHex(publicKey))
  }

  get(publicKey) {
    return this._byPublicKey.get(toHex(publicKey))
  }

  add(connection) {
    this._byPublicKey.set(b4a.toString(connection.remotePublicKey, 'hex'), connection)
  }

  delete(connection) {
    const keyString = b4a.toString(connection.remotePublicKey, 'hex')
    const existing = this._byPublicKey.get(keyString)
    if (existing !== connection) return
    this._byPublicKey.delete(keyString)
  }
}

function toHex(b) {
  return typeof b === 'string' ? b : b4a.toString(b, 'hex')
}
const safetyCatch = require('safety-catch')
const b4a = require('b4a')

const REFRESH_INTERVAL = 1000 * 60 * 10 // 10 min
const RANDOM_JITTER = 1000 * 60 * 2 // 2 min
const DELAY_GRACE_PERIOD = 1000 * 30 // 30s

const MAX_DISCOVERY_CACHE = 64

module.exports = class PeerDiscovery {
  constructor(
    swarm,
    topic,
    { limit = Infinity, wait = null, suspended = false, onpeer = noop, onerror = safetyCatch }
  ) {
    this.limit = limit
    this.swarm = swarm
    this.topic = topic
    this.isClient = false
    this.isServer = false
    this.destroyed = false
    this.destroying = null
    this.suspended = suspended

    this._sessions = []
    this._clientSessions = 0
    this._serverSessions = 0

    this._onpeer = onpeer
    this._onerror = onerror

    this._discovered = new Set()
    this._activeQuery = null
    this._timer = null
    this._currentRefresh = null
    this._closestNodes = null
    this._firstAnnounce = true
    this._needsUnannounce = false
    this._refreshes = 0
    this._wait = wait
  }

  session({ server = true, client = true, limit = Infinity, onerror = safetyCatch }) {
    if (this.destroyed) throw new Error('PeerDiscovery is destroyed')
    const session = new PeerDiscoverySession(this)
    session.refresh({ server, client, limit }).catch(onerror)
    this._sessions.push(session)
    return session
  }

  _refreshLater(eager) {
    const jitter = Math.round(Math.random() * RANDOM_JITTER)
    const delay = !eager ? REFRESH_INTERVAL + jitter : jitter

    if (this._timer) clearTimeout(this._timer)

    const startTime = Date.now()
    this._timer = setTimeout(() => {
      // If your laptop went to sleep, and is coming back online...
      const overdue = Date.now() - startTime > delay + DELAY_GRACE_PERIOD
      if (overdue) this._refreshLater(true)
      else this.refresh().catch(this._onerror)
    }, delay)
  }

  _isActive() {
    return !this.destroyed && !this.suspended
  }

  // TODO: Allow announce to be an argument to this
  // TODO: Maybe announce should be a setter?
  async _refresh() {
    if (this.suspended) return
    const clock = ++this._refreshes

    if (this._wait) {
      await this._wait
      this._wait = null
      if (clock !== this._refreshes || !this._isActive()) return
    }

    const clear = this.isServer && this._firstAnnounce
    if (clear) this._firstAnnounce = false

    const opts = {
      clear,
      closestNodes: this._closestNodes
    }

    if (this.isServer) {
      await this.swarm.listen()
      // if a parallel refresh is happening, yield to the new one
      if (clock !== this._refreshes || !this._isActive()) return
      this._needsUnannounce = true
    }

    let limit = this.limit

    if (limit < Infinity && limit > 0) {
      for (const id of this._discovered) {
        if (!this.swarm.connections.has(id)) continue
        if (--limit === 0) break
      }
    }

    this._discovered.clear()

    const announcing = this.isServer
    const query = (this._activeQuery = announcing
      ? this.swarm.dht.announce(
          this.topic,
          this.swarm.keyPair,
          this.swarm.server.relayAddresses,
          opts
        )
      : this._needsUnannounce
        ? this.swarm.dht.lookupAndUnannounce(this.topic, this.swarm.keyPair, opts)
        : this.swarm.dht.lookup(this.topic, opts))

    try {
      for await (const data of this._activeQuery) {
        if (!this.isClient || !this._isActive()) continue
        for (const peer of data.peers) {
          if (limit < Infinity) {
            const id = b4a.toString(peer.publicKey, 'hex')

            if (this._discovered.size < MAX_DISCOVERY_CACHE) {
              this._discovered.add(id)
            }

            if (limit === 0) continue

            // there is a chance it has updated a connection during discovery and we go over
            // the limit - thats acceptable to avoid a complexity spiral here.
            if (!this.swarm.connections.has(id)) limit--
          }

          this._onpeer(peer, data)
        }
      }
    } catch (err) {
      if (this._isActive()) throw err
    } finally {
      if (this._activeQuery === query) {
        this._activeQuery = null
        if (!this.destroyed && !this.suspended) this._refreshLater(false)
      }
    }

    // This is set at the very end, when the query completes successfully.
    this._closestNodes = query.closestNodes

    if (clock !== this._refreshes) return

    // In this is the latest query, unannounce has been fulfilled as well
    if (!announcing) this._needsUnannounce = false
  }

  async refresh() {
    if (this.destroyed) throw new Error('PeerDiscovery is destroyed')

    const server = this._serverSessions > 0
    const client = this._clientSessions > 0

    if (this.suspended) return

    if (server === this.isServer && client === this.isClient) {
      if (this._currentRefresh) return this._currentRefresh
      this._currentRefresh = this._refresh()
    } else {
      if (this._activeQuery) this._activeQuery.destroy()
      this.isServer = server
      this.isClient = client
      this._currentRefresh = this._refresh()
    }

    const refresh = this._currentRefresh
    try {
      await refresh
    } catch {
      return false
    } finally {
      if (refresh === this._currentRefresh) {
        this._currentRefresh = null
      }
    }

    return true
  }

  async flushed() {
    if (this.swarm.listening) await this.swarm.listening

    try {
      await this._currentRefresh
      return true
    } catch {
      return false
    }
  }

  async _destroyMaybe() {
    if (this.destroyed) return

    try {
      if (this._sessions.length === 0) await this.swarm.leave(this.topic)
      else if (this._serverSessions === 0 && this._needsUnannounce) await this.refresh()
    } catch (err) {
      // ignore network failures here, as we are tearing down
      safetyCatch(err)
    }
  }

  destroy() {
    if (this.destroying) return this.destroying
    this.destroying = this._destroy()
    return this.destroying
  }

  async _abort(log) {
    const id = log === noop ? '' : b4a.toString(this.topic, 'hex')

    log('Aborting discovery', id)
    if (this._wait) await this._wait
    log('Aborting discovery (post wait)', id)

    if (this._activeQuery) {
      this._activeQuery.destroy()
      this._activeQuery = null
    }
    if (this._timer) {
      clearTimeout(this._timer)
      this._timer = null
    }

    let nodes = this._closestNodes

    if (this._currentRefresh) {
      try {
        await this._currentRefresh
      } catch {
        // If the destroy causes the refresh to fail, suppress it.
      }
    }

    log('Aborting discovery (post refresh)', id)
    if (this._isActive()) return

    if (!nodes) nodes = this._closestNodes
    else if (this._closestNodes !== nodes) {
      const len = nodes.length
      for (const newer of this._closestNodes) {
        if (newer.id && !hasNode(nodes, len, newer)) nodes.push(newer)
      }
    }

    if (this._needsUnannounce) {
      log('Unannouncing discovery', id)
      if (nodes && nodes.length) {
        await this.swarm.dht.unannounce(this.topic, this.swarm.keyPair, {
          closestNodes: nodes,
          onlyClosestNodes: true,
          force: true
        })
      }
      this._needsUnannounce = false
      log('Unannouncing discovery (done)', id)
    }
  }

  _destroy() {
    if (this.destroyed) return
    this.destroyed = true
    return this._abort(noop)
  }

  async suspend({ log = noop } = {}) {
    if (this.suspended) return
    this.suspended = true
    try {
      await this._abort(log)
    } catch {
      // ignore
    }
  }

  resume() {
    if (!this.suspended) return
    this.suspended = false
    this.refresh().catch(noop)
  }
}

class PeerDiscoverySession {
  constructor(discovery) {
    this.discovery = discovery
    this.isClient = false
    this.isServer = false
    this.destroyed = false
  }

  get swarm() {
    return this.discovery.swarm
  }

  get topic() {
    return this.discovery.topic
  }

  async refresh({ client = this.isClient, server = this.isServer, limit = Infinity } = {}) {
    if (this.destroyed) throw new Error('PeerDiscovery is destroyed')
    if (!client && !server) throw new Error('Cannot refresh with neither client nor server option')

    if (client !== this.isClient) {
      this.isClient = client
      this.discovery._clientSessions += client ? 1 : -1
    }

    if (server !== this.isServer) {
      this.isServer = server
      this.discovery._serverSessions += server ? 1 : -1
    }

    this.discovery.limit = limit

    return this.discovery.refresh()
  }

  async flushed() {
    return this.discovery.flushed()
  }

  async destroy() {
    if (this.destroyed) return
    this.destroyed = true

    if (this.isClient) this.discovery._clientSessions--
    if (this.isServer) this.discovery._serverSessions--

    const index = this.discovery._sessions.indexOf(this)
    const head = this.discovery._sessions.pop()

    if (head !== this) this.discovery._sessions[index] = head

    return this.discovery._destroyMaybe()
  }
}

function hasNode(nodes, len, node) {
  for (let i = 0; i < len; i++) {
    const existing = nodes[i]
    if (existing.id && b4a.equals(existing.id, node.id)) return true
  }

  return false
}

function noop() {}
const { EventEmitter } = require('events')
const b4a = require('b4a')
const unslab = require('unslab')

const MIN_CONNECTION_TIME = 15000

const VERY_LOW_PRIORITY = 0
const LOW_PRIORITY = 1
const NORMAL_PRIORITY = 2
const HIGH_PRIORITY = 3
const VERY_HIGH_PRIORITY = 4

module.exports = class PeerInfo extends EventEmitter {
  constructor({ publicKey, relayAddresses }) {
    super()

    this.publicKey = unslab(publicKey)
    this.relayAddresses = relayAddresses

    this.reconnecting = true
    this.proven = false
    this.connectedTime = -1
    this.disconnectedTime = 0
    this.banned = false
    this.tried = false
    this.explicit = false
    this.waiting = false
    this.forceRelaying = false

    // Set by the Swarm
    this.queued = false
    this.client = false
    this.topics = [] // TODO: remove on next major (check with mafintosh for context)

    this.attempts = 0
    this.priority = NORMAL_PRIORITY

    // Used by shuffled-priority-queue
    this._index = 0

    // Used for flush management
    this._flushTick = 0

    // Used for topic multiplexing
    this._seenTopics = new Set()
  }

  get server() {
    return !this.client
  }

  get prioritized() {
    return this.priority >= NORMAL_PRIORITY
  }

  _getPriority() {
    const peerIsStale = this.tried && !this.proven
    if (peerIsStale || this.attempts > 3) return VERY_LOW_PRIORITY
    if (this.attempts === 3) return LOW_PRIORITY
    if (this.attempts === 2) return HIGH_PRIORITY
    if (this.attempts === 1) return VERY_HIGH_PRIORITY
    return NORMAL_PRIORITY
  }

  _connected() {
    this.proven = true
    this.connectedTime = Date.now()
  }

  _disconnected() {
    this.disconnectedTime = Date.now()
    if (this.connectedTime > -1) {
      if (this.disconnectedTime - this.connectedTime >= MIN_CONNECTION_TIME) this.attempts = 0 // fast retry
      this.connectedTime = -1
    }
    this.attempts++
  }

  _deprioritize() {
    this.attempts = 3
  }

  _reset() {
    this.client = false
    this.proven = false
    this.tried = false
    this.attempts = 0
  }

  _updatePriority() {
    if (this.explicit && this.attempts > 3) this._deprioritize()
    if (this.banned || this.queued || this.attempts > 3) return false
    this.priority = this._getPriority()
    return true
  }

  _topic(topic) {
    const topicString = b4a.toString(topic, 'hex')
    if (this._seenTopics.has(topicString)) return
    this._seenTopics.add(topicString)
    this.topics.push(topic)
    this.emit('topic', topic)
  }

  reconnect(val) {
    this.reconnecting = !!val
  }

  ban(val) {
    this.banned = !!val
  }

  shouldGC() {
    return !(this.banned || this.queued || this.explicit || this.waiting)
  }
}
const BulkTimer = require('./bulk-timer')

const BACKOFF_JITTER = 500
const BACKOFF_S = 1000 + Math.round(BACKOFF_JITTER * Math.random())
const BACKOFF_M = 5000 + Math.round(2 * BACKOFF_JITTER * Math.random())
const BACKOFF_L = 15000 + Math.round(4 * BACKOFF_JITTER * Math.random())
const BACKOFF_X = 1000 * 60 * 10 + Math.round(240 * BACKOFF_JITTER * Math.random())

module.exports = class RetryTimer {
  constructor(
    push,
    { backoffs = [BACKOFF_S, BACKOFF_M, BACKOFF_L, BACKOFF_X], jitter = BACKOFF_JITTER } = {}
  ) {
    this.jitter = jitter
    this.backoffs = backoffs

    this._sTimer = new BulkTimer(backoffs[0] + Math.round(jitter * Math.random()), push)
    this._mTimer = new BulkTimer(backoffs[1] + Math.round(jitter * Math.random()), push)
    this._lTimer = new BulkTimer(backoffs[2] + Math.round(jitter * Math.random()), push)
    this._xTimer = new BulkTimer(backoffs[3] + Math.round(jitter * Math.random()), push)
  }

  _selectRetryTimer(peerInfo) {
    if (peerInfo.banned || !peerInfo.reconnecting) return null

    if (peerInfo.attempts > 3) {
      return peerInfo.explicit ? this._xTimer : null
    }

    if (peerInfo.attempts === 0) return this._sTimer
    if (peerInfo.proven) {
      switch (peerInfo.attempts) {
        case 1:
          return this._sTimer
        case 2:
          return this._mTimer
        case 3:
          return this._lTimer
      }
    } else {
      switch (peerInfo.attempts) {
        case 1:
          return this._mTimer
        case 2:
          return this._lTimer
        case 3:
          return this._lTimer
      }
    }

    return null
  }

  add(peerInfo) {
    const timer = this._selectRetryTimer(peerInfo)
    if (!timer) return false

    timer.add(peerInfo)
    return true
  }

  destroy() {
    this._sTimer.destroy()
    this._mTimer.destroy()
    this._lTimer.destroy()
    this._xTimer.destroy()
  }
}
{
  "name": "hyperswarm",
  "version": "4.17.0",
  "description": "A distributed networking stack for connecting peers",
  "files": [
    "index.js",
    "lib/**.js"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    },
    "process": {
      "bare": "bare-process",
      "default": "process"
    }
  },
  "dependencies": {
    "b4a": "^1.3.1",
    "bare-events": "^2.2.0",
    "hyperdht": "^6.21.0",
    "safety-catch": "^1.0.2",
    "shuffled-priority-queue": "^2.1.0",
    "streamx": "^2.22.1",
    "unslab": "^1.3.0"
  },
  "devDependencies": {
    "bare-process": "^4.2.2",
    "brittle": "^3.0.2",
    "hypercore-crypto": "^3.4.0",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "which-runtime": "^1.3.2"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:generate": "brittle -r test/all.js test/*.js",
    "test:node": "brittle-node --coverage test/*.js",
    "test:bare": "bare test/all.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/hyperswarm.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "contributors": [
    "David Mark Clements (@davidmarkclem)",
    "Andrew Osheroff (@andrewosh)"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/hyperswarm/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperswarm"
}
const b4a = require('b4a')

const EMPTY = b4a.alloc(0)
const MAX = b4a.from([0xff])
const BUFFER = {}

BUFFER.preencode = function (state, buf) {
  if (buf === null) buf = EMPTY

  let i = 0
  let extra = 3

  while ((i = b4a.indexOf(buf, 0x00, i)) > -1) {
    i++
    extra++
  }

  state.end += buf.byteLength + extra
}

BUFFER.encode = function (state, buf) {
  if (buf === null) buf = EMPTY

  state.buffer[state.start++] = 0x00

  let prev = 0
  let i = 0

  while ((i = b4a.indexOf(buf, 0x00, i)) > -1) {
    const slice = buf.subarray(prev, ++i)

    state.buffer.set(slice, state.start)
    state.start += slice.byteLength
    state.buffer[state.start++] = 0x02
    prev = i
  }

  const slice = buf.subarray(prev)

  state.buffer.set(slice, state.start)
  state.start += slice.byteLength

  state.buffer[state.start++] = 0x00
  state.buffer[state.start++] = 0x01
}

BUFFER.decode = function (state) {
  if (state.start >= state.end) throw new Error('Out of bounds')
  if (state.buffer[state.start++] !== 0x00) {
    throw new Error('Invalid start of string')
  }

  let escaped = null

  let prev = state.start
  let i = state.start

  while ((i = b4a.indexOf(state.buffer, 0x00, i)) > -1) {
    const next = ++i < state.end ? state.buffer[i] : 0x00

    i++

    if (next === 0x01) {
      break
    }

    if (next === 0x02) {
      if (escaped === null) escaped = []
      escaped.push(state.buffer.subarray(prev, i - 1))
      prev = i
      continue
    }

    throw new Error('Unknown value in terminator')
  }

  if (i === -1) {
    throw new Error('No terminator found')
  }

  state.start = i
  const last = state.buffer.subarray(prev, i - 2)
  if (escaped === null) return last

  escaped.push(last)
  return b4a.concat(escaped)
}

// TODO: can be optimised a lot

const STRING = {}

STRING.preencode = function (state, str) {
  BUFFER.preencode(state, b4a.from(str || ''))
}

STRING.encode = function (state, str) {
  BUFFER.encode(state, b4a.from(str || ''))
}

STRING.decode = function (state, str) {
  return b4a.toString(BUFFER.decode(state))
}

const UINT = {}

UINT.preencode = function (state, n) {
  state.end += n <= 0xfb ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : n === Infinity ? 1 : 9
}

UINT.encode = function (state, n) {
  if (n === Infinity) {
    state.buffer[state.start++] = 0xff
    return
  }

  if (n <= 0xfb) {
    state.buffer[state.start++] = n
    return
  }

  if (n <= 0xffff) {
    state.buffer[state.start++] = 0xfc
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
    return
  }

  if (n <= 0xffffffff) {
    state.buffer[state.start++] = 0xfd
    encodeUint32(state, n)
    return
  }

  if (Number.isSafeInteger(n)) {
    state.buffer[state.start++] = 0xfe

    const r = Math.floor(n / 0x100000000)
    encodeUint32(state, r)
    encodeUint32(state, n)
    return
  }

  throw new Error('Invalid number ' + n)
}

UINT.decode = function (state) {
  if (state.start >= state.end) throw new Error('Out of bounds')

  const a = state.buffer[state.start++]

  if (a <= 0xfb) return a

  if (a === 0xfc) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] * 0x100 + state.buffer[state.start++]
  }

  if (a === 0xfd) {
    return decodeUint32(state)
  }

  if (a === 0xfe) {
    return decodeUint32(state) * 0x100000000 + decodeUint32(state)
  }

  return Infinity
}

const INT = {}

INT.preencode = function (state, n) {
  // One asymmetric condition
  if (n >= -0xff && n < 0) {
    state.end += 2
    return
  }
  n = Math.abs(n)
  state.end += n <= 0xf6 ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : n === Infinity ? 1 : 9
}

INT.encode = function (state, n) {
  if (n === Infinity) {
    state.buffer[state.start++] = 0xff
    return
  }

  if (n === -Infinity) {
    state.buffer[state.start++] = 0x00
    return
  }

  // Negative 64 bit
  if (n < -0xffffffff) {
    if (!Number.isSafeInteger(n)) throw new Error('Invalid number ' + n)
    state.buffer[state.start++] = 0x01

    const r = Math.floor(-n / 0x100000000)
    encodeUint32(state, -r + 0xffffffff)
    encodeUint32(state, -(-n % 0x100000000) + 0xffffffff)
    return
  }

  // Negative 32 bit
  if (n < -0xffff) {
    state.buffer[state.start++] = 0x02

    n += 0xffffffff
    encodeUint32(state, n)
    return
  }

  // Negative 16bit
  if (n < -0xff) {
    state.buffer[state.start++] = 0x03

    n += 0xffff
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
    return
  }

  // Negative 8bit
  if (n < 0) {
    state.buffer[state.start++] = 0x04

    n += 0xff
    state.buffer[state.start++] = n
    return
  }

  // Remainder of 8bit space for positive int
  if (n <= 0xf6) {
    state.buffer[state.start++] = n + 0x05
    return
  }

  // Positive 16bit
  if (n <= 0xffff) {
    state.buffer[state.start++] = 0xfc
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
    return
  }

  // Positive 32bit
  if (n <= 0xffffffff) {
    state.buffer[state.start++] = 0xfd
    encodeUint32(state, n)
    return
  }

  // Positive 64bit
  if (Number.isSafeInteger(n)) {
    state.buffer[state.start++] = 0xfe

    const r = Math.floor(n / 0x100000000)
    encodeUint32(state, r)
    encodeUint32(state, n)
    return
  }

  throw new Error('Invalid number ' + n)
}

INT.decode = function (state) {
  if (state.start >= state.end) throw new Error('Out of bounds')

  const a = state.buffer[state.start++]

  if (a === 0x00) return -Infinity

  if (a === 0x01) {
    // Split (2^64 - 1) into its 32 bit components
    // r * 0x100000000 + n - (2^64 - 1)
    // r * 0x100000000 + n - (0xffffffff * 0x100000000) - 0xffffffff
    // (r - 0xffffffff) * 0x100000000 + n - 0xffffffff
    return (decodeUint32(state) - 0xffffffff) * 0x100000000 + decodeUint32(state) - 0xffffffff
  }

  if (a === 0x02) {
    return decodeUint32(state) - 0xffffffff
  }

  if (a === 0x03) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] * 0x100 + state.buffer[state.start++] - 0xffff
  }

  if (a === 0x04) return state.buffer[state.start++] - 0xff

  if (a <= 0xfb) return a - 0x05

  if (a === 0xfc) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] * 0x100 + state.buffer[state.start++]
  }

  if (a === 0xfd) {
    return decodeUint32(state)
  }

  if (a === 0xfe) {
    return decodeUint32(state) * 0x100000000 + decodeUint32(state)
  }

  return Infinity
}

const DATE = {}

DATE.preencode = (state, d) => INT.preencode(state, d.getTime())
DATE.encode = (state, d) => INT.encode(state, d.getTime())
DATE.decode = (state) => new Date(INT.decode(state))

const BOOL = {}

BOOL.preencode = (state, b) => UINT.preencode(state, b ? 1 : 0)
BOOL.encode = (state, b) => UINT.encode(state, b ? 1 : 0)
BOOL.decode = (state) => !!UINT.decode(state)

module.exports = class IndexEncoder {
  constructor(encodings, { prefix = -1 } = {}) {
    this.encodings = encodings
    this.prefix = prefix
  }

  static BUFFER = BUFFER
  static STRING = STRING
  static UINT = UINT
  static INT = INT
  static DATE = DATE
  static BOOL = BOOL

  static lookup(c) {
    switch (c) {
      case 'uint':
        return UINT
      case 'uint8':
        return UINT
      case 'uint16':
        return UINT
      case 'uint24':
        return UINT
      case 'uint32':
        return UINT
      case 'uint40':
        return UINT
      case 'uint48':
        return UINT
      case 'uint56':
        return UINT
      case 'uint64':
        return UINT
      case 'int':
        return INT
      case 'int8':
        return INT
      case 'int16':
        return INT
      case 'int24':
        return INT
      case 'int32':
        return INT
      case 'int40':
        return INT
      case 'int48':
        return INT
      case 'int56':
        return INT
      case 'int64':
        return INT
      case 'string':
        return STRING
      case 'utf8':
        return STRING
      case 'ascii':
        return STRING
      case 'hex':
        return STRING
      case 'base64':
        return STRING
      case 'fixed32':
        return BUFFER
      case 'fixed64':
        return BUFFER
      case 'buffer':
        return BUFFER
      case 'date':
        return DATE
      case 'bool':
        return BOOL
    }

    throw new Error('Unknown type')
  }

  encode(keys) {
    return this._encode(keys, false)
  }

  _encode(keys, terminate) {
    if (b4a.isBuffer(keys)) return keys

    const state = { start: 0, end: 0, buffer: null }

    if (this.prefix !== -1) UINT.preencode(state, this.prefix)
    for (let i = 0; i < keys.length; i++) {
      this.encodings[i].preencode(state, keys[i])
    }

    if (terminate && keys.length < this.encodings.length) {
      state.end++
    }

    state.buffer = b4a.allocUnsafe(state.end)

    if (this.prefix !== -1) UINT.encode(state, this.prefix)
    for (let i = 0; i < keys.length; i++) {
      this.encodings[i].encode(state, keys[i])
    }

    if (terminate && keys.length < this.encodings.length) {
      state.buffer[state.start++] = MAX[0]
    }

    return state.buffer
  }

  decode(buffer) {
    const state = { start: 0, end: buffer.byteLength, buffer }
    const result = []

    if (this.prefix !== -1) UINT.decode(state)
    for (const enc of this.encodings) {
      const key = state.start < state.end ? enc.decode(state) : enc === UINT ? 0 : null
      result.push(key)
    }

    return result
  }

  encodeRange({ gt, gte, lt, lte }) {
    const range = {
      gt: gt && this._encode(gt, true),
      gte: gte && this._encode(gte, false),
      lt: lt && this._encode(lt, false),
      lte: lte && this._encode(lte, true)
    }

    if (this.prefix !== -1) {
      if (!gt && !gte) range.gte = encodeUint(this.prefix)
      if (!lt && !lte) range.lt = encodeUint(this.prefix + 1)
    }

    return range
  }
}

function encodeUint(n) {
  const state = { start: 0, end: 0, buffer: null }
  UINT.preencode(state, n)
  state.buffer = b4a.allocUnsafe(state.end)
  UINT.encode(state, n)
  return state.buffer
}

function encodeUint32(state, n) {
  state.buffer[state.start++] = n >>> 24
  state.buffer[state.start++] = n >>> 16
  state.buffer[state.start++] = n >>> 8
  state.buffer[state.start++] = n
}

function decodeUint32(state) {
  if (state.end - state.start < 4) throw new Error('Out of bounds')
  return (
    state.buffer[state.start++] * 0x1000000 +
    state.buffer[state.start++] * 0x10000 +
    state.buffer[state.start++] * 0x100 +
    state.buffer[state.start++]
  )
}
{
  "name": "index-encoder",
  "version": "3.5.0",
  "description": "Encode multiple values into sorted keys",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.6.4"
  },
  "devDependencies": {
    "brittle": "^3.2.1",
    "hyperbee": "^2.10.5",
    "hypercore": "^11.0.0",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/index-encoder.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/index-encoder/issues"
  },
  "homepage": "https://github.com/holepunchto/index-encoder"
}
const b4a = require('b4a')

module.exports = function isOptions (opts) {
  return typeof opts === 'object' && opts && !b4a.isBuffer(opts)
}
{
  "name": "is-options",
  "version": "1.0.2",
  "description": "Easily check if input is an options map",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.1.1"
  },
  "devDependencies": {
    "standard": "^11.0.1",
    "tape": "^4.9.0"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/is-options.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/is-options/issues"
  },
  "homepage": "https://github.com/mafintosh/is-options"
}
const { EventEmitter } = require('events')

module.exports = class RoutingTable extends EventEmitter {
  constructor (id, opts) {
    if (!opts) opts = {}

    super()

    this.id = id
    this.k = opts.k || 20
    this.size = 0
    this.rows = new Array(id.length * 8)
  }

  add (node) {
    const i = this._diff(node.id)

    let row = this.rows[i]

    if (!row) {
      row = this.rows[i] = new Row(this, i)
      this.emit('row', row)
    }

    const len = row.nodes.length
    if (!row.add(node, this.k)) return false

    this.size += row.nodes.length - len
    return true
  }

  remove (id) {
    const i = this._diff(id)
    const row = this.rows[i]
    if (!row) return false
    if (!row.remove(id)) return false
    this.size--
    return true
  }

  get (id) {
    const i = this._diff(id)
    const row = this.rows[i]
    if (!row) return null
    return row.get(id)
  }

  has (id) {
    return this.get(id) !== null
  }

  random () {
    let n = (Math.random() * this.size) | 0

    for (let i = 0; i < this.rows.length; i++) {
      const r = this.rows[i]
      if (!r) continue
      if (n < r.nodes.length) return r.nodes[n]
      n -= r.nodes.length
    }

    return null
  }

  closest (id, k) {
    if (!k) k = this.k

    const result = []
    const d = this._diff(id)

    // push close nodes
    for (let i = d; i >= 0 && result.length < k; i--) this._pushNodes(i, k, result)

    // if we don't have enough close nodes, populate from other rows, re the paper
    for (let i = d + 1; i < this.rows.length && result.length < k; i++) this._pushNodes(i, k, result)

    return result
  }

  _pushNodes (i, k, result) {
    const row = this.rows[i]
    if (!row) return

    const missing = Math.min(k - result.length, row.nodes.length)
    for (let j = 0; j < missing; j++) result.push(row.nodes[j])
  }

  toArray () {
    return this.closest(this.id, Infinity)
  }

  _diff (id) {
    for (let i = 0; i < id.length; i++) {
      const a = id[i]
      const b = this.id[i]

      if (a !== b) return i * 8 + Math.clz32(a ^ b) - 24
    }

    return this.rows.length - 1
  }
}

class Row extends EventEmitter {
  constructor (table, index) {
    super()

    this.data = null // can be used be upstream for whatevs
    this.byteOffset = index >> 3
    this.index = index
    this.table = table
    this.nodes = []
  }

  add (node) {
    const id = node.id

    let l = 0
    let r = this.nodes.length - 1

    while (l <= r) {
      const m = (l + r) >> 1
      const c = this.compare(id, this.nodes[m].id)

      if (c === 0) {
        this.nodes[m] = node
        return true
      }

      if (c < 0) r = m - 1
      else l = m + 1
    }

    if (this.nodes.length >= this.table.k) {
      this.emit('full', node)
      return false
    }

    this.insert(l, node)
    return true
  }

  remove (id) {
    let l = 0
    let r = this.nodes.length - 1

    while (l <= r) {
      const m = (l + r) >> 1
      const c = this.compare(id, this.nodes[m].id)

      if (c === 0) {
        this.splice(m)
        return true
      }

      if (c < 0) r = m - 1
      else l = m + 1
    }

    return false
  }

  get (id) {
    let l = 0
    let r = this.nodes.length - 1

    while (l <= r) {
      const m = (l + r) >> 1
      const node = this.nodes[m]
      const c = this.compare(id, node.id)

      if (c === 0) return node
      if (c < 0) r = m - 1
      else l = m + 1
    }

    return null
  }

  insert (i, node) {
    this.nodes.push(node) // push node or null or whatevs, just trying to not be polymorphic
    for (let j = this.nodes.length - 1; j > i; j--) this.nodes[j] = this.nodes[j - 1]
    this.nodes[i] = node
    this.emit('add', node)
  }

  splice (i) {
    for (; i < this.nodes.length - 1; i++) this.nodes[i] = this.nodes[i + 1]
    this.emit('remove', this.nodes.pop())
  }

  // very likely they diverge after a couple of bytes so a simple impl, like this is prop fastest vs Buffer.compare
  compare (a, b) {
    for (let i = this.byteOffset; i < a.length; i++) {
      const ai = a[i]
      const bi = b[i]
      if (ai === bi) continue
      return ai < bi ? -1 : 1
    }
    return 0
  }
}
{
  "name": "kademlia-routing-table",
  "version": "1.0.6",
  "description": "XOR based routing table used for P2P networks such as a Kademlia DHT.",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "dependencies": {
    "bare-events": "^2.2.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "standard": "^17.1.0"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "keywords": [
    "kademlia",
    "p2p",
    "k-bucket",
    "k-buckets",
    "xor",
    "routing",
    "distributed",
    "systems"
  ],
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/kademlia-routing-table.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/kademlia-routing-table/issues"
  },
  "homepage": "https://github.com/mafintosh/kademlia-routing-table"
}
import { coerce } from '../bytes.js';
import basex from '../vendor/base-x.js';
/**
 * Class represents both BaseEncoder and MultibaseEncoder meaning it
 * can be used to encode to multibase or base encode without multibase
 * prefix.
 */
class Encoder {
    name;
    prefix;
    baseEncode;
    constructor(name, prefix, baseEncode) {
        this.name = name;
        this.prefix = prefix;
        this.baseEncode = baseEncode;
    }
    encode(bytes) {
        if (bytes instanceof Uint8Array) {
            return `${this.prefix}${this.baseEncode(bytes)}`;
        }
        else {
            throw Error('Unknown type, must be binary type');
        }
    }
}
/**
 * Class represents both BaseDecoder and MultibaseDecoder so it could be used
 * to decode multibases (with matching prefix) or just base decode strings
 * with corresponding base encoding.
 */
class Decoder {
    name;
    prefix;
    baseDecode;
    prefixCodePoint;
    constructor(name, prefix, baseDecode) {
        this.name = name;
        this.prefix = prefix;
        const prefixCodePoint = prefix.codePointAt(0);
        /* c8 ignore next 3 */
        if (prefixCodePoint === undefined) {
            throw new Error('Invalid prefix character');
        }
        this.prefixCodePoint = prefixCodePoint;
        this.baseDecode = baseDecode;
    }
    decode(text) {
        if (typeof text === 'string') {
            if (text.codePointAt(0) !== this.prefixCodePoint) {
                throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);
            }
            return this.baseDecode(text.slice(this.prefix.length));
        }
        else {
            throw Error('Can only multibase decode strings');
        }
    }
    or(decoder) {
        return or(this, decoder);
    }
}
class ComposedDecoder {
    decoders;
    constructor(decoders) {
        this.decoders = decoders;
    }
    or(decoder) {
        return or(this, decoder);
    }
    decode(input) {
        const prefix = input[0];
        const decoder = this.decoders[prefix];
        if (decoder != null) {
            return decoder.decode(input);
        }
        else {
            throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);
        }
    }
}
export function or(left, right) {
    return new ComposedDecoder({
        ...(left.decoders ?? { [left.prefix]: left }),
        ...(right.decoders ?? { [right.prefix]: right })
    });
}
export class Codec {
    name;
    prefix;
    baseEncode;
    baseDecode;
    encoder;
    decoder;
    constructor(name, prefix, baseEncode, baseDecode) {
        this.name = name;
        this.prefix = prefix;
        this.baseEncode = baseEncode;
        this.baseDecode = baseDecode;
        this.encoder = new Encoder(name, prefix, baseEncode);
        this.decoder = new Decoder(name, prefix, baseDecode);
    }
    encode(input) {
        return this.encoder.encode(input);
    }
    decode(input) {
        return this.decoder.decode(input);
    }
}
export function from({ name, prefix, encode, decode }) {
    return new Codec(name, prefix, encode, decode);
}
export function baseX({ name, prefix, alphabet }) {
    const { encode, decode } = basex(alphabet, name);
    return from({
        prefix,
        name,
        encode,
        decode: (text) => coerce(decode(text))
    });
}
function decode(string, alphabetIdx, bitsPerChar, name) {
    // Count the padding bytes:
    let end = string.length;
    while (string[end - 1] === '=') {
        --end;
    }
    // Allocate the output:
    const out = new Uint8Array((end * bitsPerChar / 8) | 0);
    // Parse the data:
    let bits = 0; // Number of bits currently in the buffer
    let buffer = 0; // Bits waiting to be written out, MSB first
    let written = 0; // Next byte to write
    for (let i = 0; i < end; ++i) {
        // Read one character from the string:
        const value = alphabetIdx[string[i]];
        if (value === undefined) {
            throw new SyntaxError(`Non-${name} character`);
        }
        // Append the bits to the buffer:
        buffer = (buffer << bitsPerChar) | value;
        bits += bitsPerChar;
        // Write out some bits if the buffer has a byte's worth:
        if (bits >= 8) {
            bits -= 8;
            out[written++] = 0xff & (buffer >> bits);
        }
    }
    // Verify that we have received just enough bits:
    if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {
        throw new SyntaxError('Unexpected end of data');
    }
    return out;
}
function encode(data, alphabet, bitsPerChar) {
    const pad = alphabet[alphabet.length - 1] === '=';
    const mask = (1 << bitsPerChar) - 1;
    let out = '';
    let bits = 0; // Number of bits currently in the buffer
    let buffer = 0; // Bits waiting to be written out, MSB first
    for (let i = 0; i < data.length; ++i) {
        // Slurp data into the buffer:
        buffer = (buffer << 8) | data[i];
        bits += 8;
        // Write out as much as we can:
        while (bits > bitsPerChar) {
            bits -= bitsPerChar;
            out += alphabet[mask & (buffer >> bits)];
        }
    }
    // Partial character:
    if (bits !== 0) {
        out += alphabet[mask & (buffer << (bitsPerChar - bits))];
    }
    // Add padding characters until we hit a byte boundary:
    if (pad) {
        while (((out.length * bitsPerChar) & 7) !== 0) {
            out += '=';
        }
    }
    return out;
}
function createAlphabetIdx(alphabet) {
    // Build the character lookup table:
    const alphabetIdx = {};
    for (let i = 0; i < alphabet.length; ++i) {
        alphabetIdx[alphabet[i]] = i;
    }
    return alphabetIdx;
}
/**
 * RFC4648 Factory
 */
export function rfc4648({ name, prefix, bitsPerChar, alphabet }) {
    const alphabetIdx = createAlphabetIdx(alphabet);
    return from({
        prefix,
        name,
        encode(input) {
            return encode(input, alphabet, bitsPerChar);
        },
        decode(input) {
            return decode(input, alphabetIdx, bitsPerChar, name);
        }
    });
}
//# sourceMappingURL=base.js.mapimport { rfc4648 } from './base.js';
export const base32 = rfc4648({
    prefix: 'b',
    name: 'base32',
    alphabet: 'abcdefghijklmnopqrstuvwxyz234567',
    bitsPerChar: 5
});
export const base32upper = rfc4648({
    prefix: 'B',
    name: 'base32upper',
    alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',
    bitsPerChar: 5
});
export const base32pad = rfc4648({
    prefix: 'c',
    name: 'base32pad',
    alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',
    bitsPerChar: 5
});
export const base32padupper = rfc4648({
    prefix: 'C',
    name: 'base32padupper',
    alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',
    bitsPerChar: 5
});
export const base32hex = rfc4648({
    prefix: 'v',
    name: 'base32hex',
    alphabet: '0123456789abcdefghijklmnopqrstuv',
    bitsPerChar: 5
});
export const base32hexupper = rfc4648({
    prefix: 'V',
    name: 'base32hexupper',
    alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',
    bitsPerChar: 5
});
export const base32hexpad = rfc4648({
    prefix: 't',
    name: 'base32hexpad',
    alphabet: '0123456789abcdefghijklmnopqrstuv=',
    bitsPerChar: 5
});
export const base32hexpadupper = rfc4648({
    prefix: 'T',
    name: 'base32hexpadupper',
    alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',
    bitsPerChar: 5
});
export const base32z = rfc4648({
    prefix: 'h',
    name: 'base32z',
    alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',
    bitsPerChar: 5
});
//# sourceMappingURL=base32.js.mapimport { baseX } from './base.js';
export const base36 = baseX({
    prefix: 'k',
    name: 'base36',
    alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'
});
export const base36upper = baseX({
    prefix: 'K',
    name: 'base36upper',
    alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
});
//# sourceMappingURL=base36.js.mapimport { baseX } from './base.js';
export const base58btc = baseX({
    name: 'base58btc',
    prefix: 'z',
    alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
});
export const base58flickr = baseX({
    name: 'base58flickr',
    prefix: 'Z',
    alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'
});
//# sourceMappingURL=base58.js.mapexport const empty = new Uint8Array(0);
export function toHex(d) {
    return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '');
}
export function fromHex(hex) {
    const hexes = hex.match(/../g);
    return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty;
}
export function equals(aa, bb) {
    if (aa === bb) {
        return true;
    }
    if (aa.byteLength !== bb.byteLength) {
        return false;
    }
    for (let ii = 0; ii < aa.byteLength; ii++) {
        if (aa[ii] !== bb[ii]) {
            return false;
        }
    }
    return true;
}
export function coerce(o) {
    if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') {
        return o;
    }
    if (o instanceof ArrayBuffer) {
        return new Uint8Array(o);
    }
    if (ArrayBuffer.isView(o)) {
        return new Uint8Array(o.buffer, o.byteOffset, o.byteLength);
    }
    throw new Error('Unknown type, must be binary type');
}
export function isBinary(o) {
    return o instanceof ArrayBuffer || ArrayBuffer.isView(o);
}
export function fromString(str) {
    return new TextEncoder().encode(str);
}
export function toString(b) {
    return new TextDecoder().decode(b);
}
//# sourceMappingURL=bytes.js.mapimport { base32 } from './bases/base32.js';
import { base36 } from './bases/base36.js';
import { base58btc } from './bases/base58.js';
import { coerce } from './bytes.js';
import * as Digest from './hashes/digest.js';
import * as varint from './varint.js';
// This way TS will also expose all the types from module
export * from './link/interface.js';
export function format(link, base) {
    const { bytes, version } = link;
    switch (version) {
        case 0:
            return toStringV0(bytes, baseCache(link), base ?? base58btc.encoder);
        default:
            return toStringV1(bytes, baseCache(link), (base ?? base32.encoder));
    }
}
export function toJSON(link) {
    return {
        '/': format(link)
    };
}
export function fromJSON(json) {
    return CID.parse(json['/']);
}
const cache = new WeakMap();
function baseCache(cid) {
    const baseCache = cache.get(cid);
    if (baseCache == null) {
        const baseCache = new Map();
        cache.set(cid, baseCache);
        return baseCache;
    }
    return baseCache;
}
export class CID {
    code;
    version;
    multihash;
    bytes;
    '/';
    /**
     * @param version - Version of the CID
     * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
     * @param multihash - (Multi)hash of the of the content.
     */
    constructor(version, code, multihash, bytes) {
        this.code = code;
        this.version = version;
        this.multihash = multihash;
        this.bytes = bytes;
        // flag to serializers that this is a CID and
        // should be treated specially
        this['/'] = bytes;
    }
    /**
     * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`
     * please either use `CID.asCID(cid)` or switch to new signalling mechanism
     *
     * @deprecated
     */
    get asCID() {
        return this;
    }
    // ArrayBufferView
    get byteOffset() {
        return this.bytes.byteOffset;
    }
    // ArrayBufferView
    get byteLength() {
        return this.bytes.byteLength;
    }
    toV0() {
        switch (this.version) {
            case 0: {
                return this;
            }
            case 1: {
                const { code, multihash } = this;
                if (code !== DAG_PB_CODE) {
                    throw new Error('Cannot convert a non dag-pb CID to CIDv0');
                }
                // sha2-256
                if (multihash.code !== SHA_256_CODE) {
                    throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0');
                }
                return (CID.createV0(multihash));
            }
            default: {
                throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);
            }
        }
    }
    toV1() {
        switch (this.version) {
            case 0: {
                const { code, digest } = this.multihash;
                const multihash = Digest.create(code, digest);
                return (CID.createV1(this.code, multihash));
            }
            case 1: {
                return this;
            }
            default: {
                throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);
            }
        }
    }
    equals(other) {
        return CID.equals(this, other);
    }
    static equals(self, other) {
        const unknown = other;
        return (unknown != null &&
            self.code === unknown.code &&
            self.version === unknown.version &&
            Digest.equals(self.multihash, unknown.multihash));
    }
    toString(base) {
        return format(this, base);
    }
    toJSON() {
        return { '/': format(this) };
    }
    link() {
        return this;
    }
    [Symbol.toStringTag] = 'CID';
    // Legacy
    [Symbol.for('nodejs.util.inspect.custom')]() {
        return `CID(${this.toString()})`;
    }
    /**
     * Takes any input `value` and returns a `CID` instance if it was
     * a `CID` otherwise returns `null`. If `value` is instanceof `CID`
     * it will return value back. If `value` is not instance of this CID
     * class, but is compatible CID it will return new instance of this
     * `CID` class. Otherwise returns null.
     *
     * This allows two different incompatible versions of CID library to
     * co-exist and interop as long as binary interface is compatible.
     */
    static asCID(input) {
        if (input == null) {
            return null;
        }
        const value = input;
        if (value instanceof CID) {
            // If value is instance of CID then we're all set.
            return value;
        }
        else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {
            // If value isn't instance of this CID class but `this.asCID === this` or
            // `value['/'] === value.bytes` is true it is CID instance coming from a
            // different implementation (diff version or duplicate). In that case we
            // rebase it to this `CID` implementation so caller is guaranteed to get
            // instance with expected API.
            const { version, code, multihash, bytes } = value;
            return new CID(version, code, multihash, bytes ?? encodeCID(version, code, multihash.bytes));
        }
        else if (value[cidSymbol] === true) {
            // If value is a CID from older implementation that used to be tagged via
            // symbol we still rebase it to the this `CID` implementation by
            // delegating that to a constructor.
            const { version, multihash, code } = value;
            const digest = Digest.decode(multihash);
            return CID.create(version, code, digest);
        }
        else {
            // Otherwise value is not a CID (or an incompatible version of it) in
            // which case we return `null`.
            return null;
        }
    }
    /**
     * @param version - Version of the CID
     * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
     * @param digest - (Multi)hash of the of the content.
     */
    static create(version, code, digest) {
        if (typeof code !== 'number') {
            throw new Error('String codecs are no longer supported');
        }
        if (!(digest.bytes instanceof Uint8Array)) {
            throw new Error('Invalid digest');
        }
        switch (version) {
            case 0: {
                if (code !== DAG_PB_CODE) {
                    throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);
                }
                else {
                    return new CID(version, code, digest, digest.bytes);
                }
            }
            case 1: {
                const bytes = encodeCID(version, code, digest.bytes);
                return new CID(version, code, digest, bytes);
            }
            default: {
                throw new Error('Invalid version');
            }
        }
    }
    /**
     * Simplified version of `create` for CIDv0.
     */
    static createV0(digest) {
        return CID.create(0, DAG_PB_CODE, digest);
    }
    /**
     * Simplified version of `create` for CIDv1.
     *
     * @param code - Content encoding format code.
     * @param digest - Multihash of the content.
     */
    static createV1(code, digest) {
        return CID.create(1, code, digest);
    }
    /**
     * Decoded a CID from its binary representation. The byte array must contain
     * only the CID with no additional bytes.
     *
     * An error will be thrown if the bytes provided do not contain a valid
     * binary representation of a CID.
     */
    static decode(bytes) {
        const [cid, remainder] = CID.decodeFirst(bytes);
        if (remainder.length !== 0) {
            throw new Error('Incorrect length');
        }
        return cid;
    }
    /**
     * Decoded a CID from its binary representation at the beginning of a byte
     * array.
     *
     * Returns an array with the first element containing the CID and the second
     * element containing the remainder of the original byte array. The remainder
     * will be a zero-length byte array if the provided bytes only contained a
     * binary CID representation.
     */
    static decodeFirst(bytes) {
        const specs = CID.inspectBytes(bytes);
        const prefixSize = specs.size - specs.multihashSize;
        const multihashBytes = coerce(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));
        if (multihashBytes.byteLength !== specs.multihashSize) {
            throw new Error('Incorrect length');
        }
        const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);
        const digest = new Digest.Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);
        const cid = specs.version === 0
            ? CID.createV0(digest)
            : CID.createV1(specs.codec, digest);
        return [cid, bytes.subarray(specs.size)];
    }
    /**
     * Inspect the initial bytes of a CID to determine its properties.
     *
     * Involves decoding up to 4 varints. Typically this will require only 4 to 6
     * bytes but for larger multicodec code values and larger multihash digest
     * lengths these varints can be quite large. It is recommended that at least
     * 10 bytes be made available in the `initialBytes` argument for a complete
     * inspection.
     */
    static inspectBytes(initialBytes) {
        let offset = 0;
        const next = () => {
            const [i, length] = varint.decode(initialBytes.subarray(offset));
            offset += length;
            return i;
        };
        let version = next();
        let codec = DAG_PB_CODE;
        if (version === 18) {
            // CIDv0
            version = 0;
            offset = 0;
        }
        else {
            codec = next();
        }
        if (version !== 0 && version !== 1) {
            throw new RangeError(`Invalid CID version ${version}`);
        }
        const prefixSize = offset;
        const multihashCode = next(); // multihash code
        const digestSize = next(); // multihash length
        const size = offset + digestSize;
        const multihashSize = size - prefixSize;
        return { version, codec, multihashCode, digestSize, multihashSize, size };
    }
    /**
     * Takes cid in a string representation and creates an instance. If `base`
     * decoder is not provided will use a default from the configuration. It will
     * throw an error if encoding of the CID is not compatible with supplied (or
     * a default decoder).
     */
    static parse(source, base) {
        const [prefix, bytes] = parseCIDtoBytes(source, base);
        const cid = CID.decode(bytes);
        if (cid.version === 0 && source[0] !== 'Q') {
            throw Error('Version 0 CID string must not include multibase prefix');
        }
        // Cache string representation to avoid computing it on `this.toString()`
        baseCache(cid).set(prefix, source);
        return cid;
    }
}
function parseCIDtoBytes(source, base) {
    switch (source[0]) {
        // CIDv0 is parsed differently
        case 'Q': {
            const decoder = base ?? base58btc;
            return [
                base58btc.prefix,
                decoder.decode(`${base58btc.prefix}${source}`)
            ];
        }
        case base58btc.prefix: {
            const decoder = base ?? base58btc;
            return [base58btc.prefix, decoder.decode(source)];
        }
        case base32.prefix: {
            const decoder = base ?? base32;
            return [base32.prefix, decoder.decode(source)];
        }
        case base36.prefix: {
            const decoder = base ?? base36;
            return [base36.prefix, decoder.decode(source)];
        }
        default: {
            if (base == null) {
                throw Error('To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided');
            }
            return [source[0], base.decode(source)];
        }
    }
}
function toStringV0(bytes, cache, base) {
    const { prefix } = base;
    if (prefix !== base58btc.prefix) {
        throw Error(`Cannot string encode V0 in ${base.name} encoding`);
    }
    const cid = cache.get(prefix);
    if (cid == null) {
        const cid = base.encode(bytes).slice(1);
        cache.set(prefix, cid);
        return cid;
    }
    else {
        return cid;
    }
}
function toStringV1(bytes, cache, base) {
    const { prefix } = base;
    const cid = cache.get(prefix);
    if (cid == null) {
        const cid = base.encode(bytes);
        cache.set(prefix, cid);
        return cid;
    }
    else {
        return cid;
    }
}
const DAG_PB_CODE = 0x70;
const SHA_256_CODE = 0x12;
function encodeCID(version, code, multihash) {
    const codeOffset = varint.encodingLength(version);
    const hashOffset = codeOffset + varint.encodingLength(code);
    const bytes = new Uint8Array(hashOffset + multihash.byteLength);
    varint.encodeTo(version, bytes, 0);
    varint.encodeTo(code, bytes, codeOffset);
    bytes.set(multihash, hashOffset);
    return bytes;
}
const cidSymbol = Symbol.for('@ipld/js-cid/CID');
//# sourceMappingURL=cid.js.mapimport { coerce, equals as equalBytes } from '../bytes.js';
import * as varint from '../varint.js';
/**
 * Creates a multihash digest.
 */
export function create(code, digest) {
    const size = digest.byteLength;
    const sizeOffset = varint.encodingLength(code);
    const digestOffset = sizeOffset + varint.encodingLength(size);
    const bytes = new Uint8Array(digestOffset + size);
    varint.encodeTo(code, bytes, 0);
    varint.encodeTo(size, bytes, sizeOffset);
    bytes.set(digest, digestOffset);
    return new Digest(code, size, digest, bytes);
}
/**
 * Turns bytes representation of multihash digest into an instance.
 */
export function decode(multihash) {
    const bytes = coerce(multihash);
    const [code, sizeOffset] = varint.decode(bytes);
    const [size, digestOffset] = varint.decode(bytes.subarray(sizeOffset));
    const digest = bytes.subarray(sizeOffset + digestOffset);
    if (digest.byteLength !== size) {
        throw new Error('Incorrect length');
    }
    return new Digest(code, size, digest, bytes);
}
export function equals(a, b) {
    if (a === b) {
        return true;
    }
    else {
        const data = b;
        return (a.code === data.code &&
            a.size === data.size &&
            data.bytes instanceof Uint8Array &&
            equalBytes(a.bytes, data.bytes));
    }
}
/**
 * Represents a multihash digest which carries information about the
 * hashing algorithm and an actual hash digest.
 */
export class Digest {
    code;
    size;
    digest;
    bytes;
    /**
     * Creates a multihash digest.
     */
    constructor(code, size, digest, bytes) {
        this.code = code;
        this.size = size;
        this.digest = digest;
        this.bytes = bytes;
    }
}
/**
 * Used to check that the passed multihash has the passed code
 */
export function hasCode(digest, code) {
    return digest.code === code;
}
//# sourceMappingURL=digest.js.mapexport {};
//# sourceMappingURL=interface.js.mapimport varint from './vendor/varint.js';
export function decode(data, offset = 0) {
    const code = varint.decode(data, offset);
    return [code, varint.decode.bytes];
}
export function encodeTo(int, target, offset = 0) {
    varint.encode(int, target, offset);
    return target;
}
export function encodingLength(int) {
    return varint.encodingLength(int);
}
//# sourceMappingURL=varint.js.map/* eslint-disable */
// base-x encoding / decoding
// Copyright (c) 2018 base-x contributors
// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)
// Distributed under the MIT software license, see the accompanying
// file LICENSE or http://www.opensource.org/licenses/mit-license.php.
/**
 * @param {string} ALPHABET
 * @param {any} name
 */
function base(ALPHABET, name) {
    if (ALPHABET.length >= 255) {
        throw new TypeError('Alphabet too long');
    }
    var BASE_MAP = new Uint8Array(256);
    for (var j = 0; j < BASE_MAP.length; j++) {
        BASE_MAP[j] = 255;
    }
    for (var i = 0; i < ALPHABET.length; i++) {
        var x = ALPHABET.charAt(i);
        var xc = x.charCodeAt(0);
        if (BASE_MAP[xc] !== 255) {
            throw new TypeError(x + ' is ambiguous');
        }
        BASE_MAP[xc] = i;
    }
    var BASE = ALPHABET.length;
    var LEADER = ALPHABET.charAt(0);
    var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up
    var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up
    /**
     * @param {any[] | Iterable<number>} source
     */
    function encode(source) {
        // @ts-ignore
        if (source instanceof Uint8Array)
            ;
        else if (ArrayBuffer.isView(source)) {
            source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
        }
        else if (Array.isArray(source)) {
            source = Uint8Array.from(source);
        }
        if (!(source instanceof Uint8Array)) {
            throw new TypeError('Expected Uint8Array');
        }
        if (source.length === 0) {
            return '';
        }
        // Skip & count leading zeroes.
        var zeroes = 0;
        var length = 0;
        var pbegin = 0;
        var pend = source.length;
        while (pbegin !== pend && source[pbegin] === 0) {
            pbegin++;
            zeroes++;
        }
        // Allocate enough space in big-endian base58 representation.
        var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;
        var b58 = new Uint8Array(size);
        // Process the bytes.
        while (pbegin !== pend) {
            var carry = source[pbegin];
            // Apply "b58 = b58 * 256 + ch".
            var i = 0;
            for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {
                carry += (256 * b58[it1]) >>> 0;
                b58[it1] = (carry % BASE) >>> 0;
                carry = (carry / BASE) >>> 0;
            }
            if (carry !== 0) {
                throw new Error('Non-zero carry');
            }
            length = i;
            pbegin++;
        }
        // Skip leading zeroes in base58 result.
        var it2 = size - length;
        while (it2 !== size && b58[it2] === 0) {
            it2++;
        }
        // Translate the result into a string.
        var str = LEADER.repeat(zeroes);
        for (; it2 < size; ++it2) {
            str += ALPHABET.charAt(b58[it2]);
        }
        return str;
    }
    /**
     * @param {string | string[]} source
     */
    function decodeUnsafe(source) {
        if (typeof source !== 'string') {
            throw new TypeError('Expected String');
        }
        if (source.length === 0) {
            return new Uint8Array();
        }
        var psz = 0;
        // Skip leading spaces.
        if (source[psz] === ' ') {
            return;
        }
        // Skip and count leading '1's.
        var zeroes = 0;
        var length = 0;
        while (source[psz] === LEADER) {
            zeroes++;
            psz++;
        }
        // Allocate enough space in big-endian base256 representation.
        var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.
        var b256 = new Uint8Array(size);
        // Process the characters.
        while (source[psz]) {
            // Decode character
            var carry = BASE_MAP[source.charCodeAt(psz)];
            // Invalid character
            if (carry === 255) {
                return;
            }
            var i = 0;
            for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {
                carry += (BASE * b256[it3]) >>> 0;
                b256[it3] = (carry % 256) >>> 0;
                carry = (carry / 256) >>> 0;
            }
            if (carry !== 0) {
                throw new Error('Non-zero carry');
            }
            length = i;
            psz++;
        }
        // Skip trailing spaces.
        if (source[psz] === ' ') {
            return;
        }
        // Skip leading zeroes in b256.
        var it4 = size - length;
        while (it4 !== size && b256[it4] === 0) {
            it4++;
        }
        var vch = new Uint8Array(zeroes + (size - it4));
        var j = zeroes;
        while (it4 !== size) {
            vch[j++] = b256[it4++];
        }
        return vch;
    }
    /**
     * @param {string | string[]} string
     */
    function decode(string) {
        var buffer = decodeUnsafe(string);
        if (buffer) {
            return buffer;
        }
        throw new Error(`Non-${name} character`);
    }
    return {
        encode: encode,
        decodeUnsafe: decodeUnsafe,
        decode: decode
    };
}
var src = base;
var _brrp__multiformats_scope_baseX = src;
export default _brrp__multiformats_scope_baseX;
//# sourceMappingURL=base-x.js.map/* eslint-disable */
var encode_1 = encode;
var MSB = 0x80, REST = 0x7F, MSBALL = ~REST, INT = Math.pow(2, 31);
/**
 * @param {number} num
 * @param {number[]} out
 * @param {number} offset
 */
function encode(num, out, offset) {
    out = out || [];
    offset = offset || 0;
    var oldOffset = offset;
    while (num >= INT) {
        out[offset++] = (num & 0xFF) | MSB;
        num /= 128;
    }
    while (num & MSBALL) {
        out[offset++] = (num & 0xFF) | MSB;
        num >>>= 7;
    }
    out[offset] = num | 0;
    // @ts-ignore
    encode.bytes = offset - oldOffset + 1;
    return out;
}
var decode = read;
var MSB$1 = 0x80, REST$1 = 0x7F;
/**
 * @param {string | any[]} buf
 * @param {number} offset
 */
function read(buf, offset) {
    var res = 0, offset = offset || 0, shift = 0, counter = offset, b, l = buf.length;
    do {
        if (counter >= l) {
            // @ts-ignore
            read.bytes = 0;
            throw new RangeError('Could not decode varint');
        }
        b = buf[counter++];
        res += shift < 28
            ? (b & REST$1) << shift
            : (b & REST$1) * Math.pow(2, shift);
        shift += 7;
    } while (b >= MSB$1);
    // @ts-ignore
    read.bytes = counter - offset;
    return res;
}
var N1 = Math.pow(2, 7);
var N2 = Math.pow(2, 14);
var N3 = Math.pow(2, 21);
var N4 = Math.pow(2, 28);
var N5 = Math.pow(2, 35);
var N6 = Math.pow(2, 42);
var N7 = Math.pow(2, 49);
var N8 = Math.pow(2, 56);
var N9 = Math.pow(2, 63);
var length = function (/** @type {number} */ value) {
    return (value < N1 ? 1
        : value < N2 ? 2
            : value < N3 ? 3
                : value < N4 ? 4
                    : value < N5 ? 5
                        : value < N6 ? 6
                            : value < N7 ? 7
                                : value < N8 ? 8
                                    : value < N9 ? 9
                                        : 10);
};
var varint = {
    encode: encode_1,
    decode: decode,
    encodingLength: length
};
var _brrp_varint = varint;
export default _brrp_varint;
//# sourceMappingURL=varint.js.map{
  "name": "multiformats",
  "version": "13.4.2",
  "description": "Interface for multihash, multicodec, multibase and CID",
  "author": "Mikeal Rogers <mikeal.rogers@gmail.com> (https://www.mikealrogers.com/)",
  "license": "Apache-2.0 OR MIT",
  "homepage": "https://github.com/multiformats/js-multiformats#readme",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/multiformats/js-multiformats.git"
  },
  "bugs": {
    "url": "https://github.com/multiformats/js-multiformats/issues"
  },
  "publishConfig": {
    "access": "public",
    "provenance": true
  },
  "keywords": [
    "ipfs",
    "ipld",
    "multiformats"
  ],
  "type": "module",
  "types": "./dist/src/index.d.ts",
  "typesVersions": {
    "*": {
      "*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ],
      "src/*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ]
    }
  },
  "files": [
    "src",
    "dist",
    "!dist/test",
    "!**/*.tsbuildinfo"
  ],
  "exports": {
    ".": {
      "types": "./dist/src/index.d.ts",
      "import": "./dist/src/index.js"
    },
    "./bases/base10": {
      "types": "./dist/src/bases/base10.d.ts",
      "import": "./dist/src/bases/base10.js"
    },
    "./bases/base16": {
      "types": "./dist/src/bases/base16.d.ts",
      "import": "./dist/src/bases/base16.js"
    },
    "./bases/base2": {
      "types": "./dist/src/bases/base2.d.ts",
      "import": "./dist/src/bases/base2.js"
    },
    "./bases/base256emoji": {
      "types": "./dist/src/bases/base256emoji.d.ts",
      "import": "./dist/src/bases/base256emoji.js"
    },
    "./bases/base32": {
      "types": "./dist/src/bases/base32.d.ts",
      "import": "./dist/src/bases/base32.js"
    },
    "./bases/base36": {
      "types": "./dist/src/bases/base36.d.ts",
      "import": "./dist/src/bases/base36.js"
    },
    "./bases/base58": {
      "types": "./dist/src/bases/base58.d.ts",
      "import": "./dist/src/bases/base58.js"
    },
    "./bases/base64": {
      "types": "./dist/src/bases/base64.d.ts",
      "import": "./dist/src/bases/base64.js"
    },
    "./bases/base8": {
      "types": "./dist/src/bases/base8.d.ts",
      "import": "./dist/src/bases/base8.js"
    },
    "./bases/identity": {
      "types": "./dist/src/bases/identity.d.ts",
      "import": "./dist/src/bases/identity.js"
    },
    "./bases/interface": {
      "types": "./dist/src/bases/interface.d.ts",
      "import": "./dist/src/bases/interface.js"
    },
    "./basics": {
      "types": "./dist/src/basics.d.ts",
      "import": "./dist/src/basics.js"
    },
    "./block": {
      "types": "./dist/src/block.d.ts",
      "import": "./dist/src/block.js"
    },
    "./block/interface": {
      "types": "./dist/src/block/interface.d.ts",
      "import": "./dist/src/block/interface.js"
    },
    "./bytes": {
      "types": "./dist/src/bytes.d.ts",
      "import": "./dist/src/bytes.js"
    },
    "./cid": {
      "types": "./dist/src/cid.d.ts",
      "import": "./dist/src/cid.js"
    },
    "./codecs/interface": {
      "types": "./dist/src/codecs/interface.d.ts",
      "import": "./dist/src/codecs/interface.js"
    },
    "./codecs/json": {
      "types": "./dist/src/codecs/json.d.ts",
      "import": "./dist/src/codecs/json.js"
    },
    "./codecs/raw": {
      "types": "./dist/src/codecs/raw.d.ts",
      "import": "./dist/src/codecs/raw.js"
    },
    "./hashes/digest": {
      "types": "./dist/src/hashes/digest.d.ts",
      "import": "./dist/src/hashes/digest.js"
    },
    "./hashes/hasher": {
      "types": "./dist/src/hashes/hasher.d.ts",
      "import": "./dist/src/hashes/hasher.js"
    },
    "./hashes/identity": {
      "types": "./dist/src/hashes/identity.d.ts",
      "import": "./dist/src/hashes/identity.js"
    },
    "./hashes/interface": {
      "types": "./dist/src/hashes/interface.d.ts",
      "import": "./dist/src/hashes/interface.js"
    },
    "./hashes/sha1": {
      "types": "./dist/types/src/hashes/sha1.d.ts",
      "browser": "./dist/src/hashes/sha1-browser.js",
      "import": "./dist/src/hashes/sha1.js"
    },
    "./hashes/sha2": {
      "types": "./dist/src/hashes/sha2.d.ts",
      "browser": "./dist/src/hashes/sha2-browser.js",
      "import": "./dist/src/hashes/sha2.js"
    },
    "./interface": {
      "types": "./dist/src/interface.d.ts",
      "import": "./dist/src/interface.js"
    },
    "./link": {
      "types": "./dist/src/link.d.ts",
      "import": "./dist/src/link.js"
    },
    "./link/interface": {
      "types": "./dist/src/link/interface.d.ts",
      "import": "./dist/src/link/interface.js"
    },
    "./traversal": {
      "types": "./dist/src/traversal.d.ts",
      "import": "./dist/src/traversal.js"
    }
  },
  "eslintConfig": {
    "extends": "ipfs",
    "parserOptions": {
      "project": true,
      "sourceType": "module"
    }
  },
  "release": {
    "branches": [
      "master"
    ],
    "plugins": [
      [
        "@semantic-release/commit-analyzer",
        {
          "preset": "conventionalcommits",
          "releaseRules": [
            {
              "breaking": true,
              "release": "major"
            },
            {
              "revert": true,
              "release": "patch"
            },
            {
              "type": "feat",
              "release": "minor"
            },
            {
              "type": "fix",
              "release": "patch"
            },
            {
              "type": "docs",
              "release": "patch"
            },
            {
              "type": "test",
              "release": "patch"
            },
            {
              "type": "deps",
              "release": "patch"
            },
            {
              "scope": "no-release",
              "release": false
            }
          ]
        }
      ],
      [
        "@semantic-release/release-notes-generator",
        {
          "preset": "conventionalcommits",
          "presetConfig": {
            "types": [
              {
                "type": "feat",
                "section": "Features"
              },
              {
                "type": "fix",
                "section": "Bug Fixes"
              },
              {
                "type": "chore",
                "section": "Trivial Changes"
              },
              {
                "type": "docs",
                "section": "Documentation"
              },
              {
                "type": "deps",
                "section": "Dependencies"
              },
              {
                "type": "test",
                "section": "Tests"
              }
            ]
          }
        }
      ],
      "@semantic-release/changelog",
      "@semantic-release/npm",
      "@semantic-release/github",
      [
        "@semantic-release/git",
        {
          "assets": [
            "CHANGELOG.md",
            "package.json"
          ]
        }
      ]
    ]
  },
  "scripts": {
    "clean": "aegir clean",
    "lint": "aegir lint",
    "build": "aegir build",
    "release": "aegir release",
    "docs": "aegir docs",
    "test": "npm run lint && npm run test:node && npm run test:chrome",
    "test:node": "aegir test -t node --cov",
    "test:chrome": "aegir test -t browser --cov",
    "test:chrome-webworker": "aegir test -t webworker",
    "test:firefox": "aegir test -t browser -- --browser firefox",
    "test:firefox-webworker": "aegir test -t webworker -- --browser firefox",
    "test:electron-main": "aegir test -t electron-main"
  },
  "devDependencies": {
    "@stablelib/sha256": "^2.0.0",
    "@stablelib/sha512": "^2.0.0",
    "@types/node": "^25.0.0",
    "aegir": "^47.0.7",
    "buffer": "^6.0.3",
    "cids": "^1.1.9",
    "crypto-hash": "^4.0.0"
  },
  "aegir": {
    "test": {
      "target": [
        "node",
        "browser"
      ]
    }
  },
  "browser": {
    "./hashes/sha1": "./dist/src/hashes/sha1-browser.js",
    "./dist/src/hashes/sha1.js": "./dist/src/hashes/sha1-browser.js",
    "./hashes/sha2": "./dist/src/hashes/sha2-browser.js",
    "./dist/src/hashes/sha2.js": "./dist/src/hashes/sha2-browser.js"
  }
}
var queueTick = require('queue-tick')

var mutexify = function () {
  var queue = []
  var used = null

  var call = function () {
    used(release)
  }

  var acquire = function (fn) {
    if (used) return queue.push(fn)
    used = fn
    acquire.locked = true
    queueTick(call)
    return 0
  }

  acquire.locked = false

  var release = function (fn, err, value) {
    used = null
    acquire.locked = false
    if (queue.length) acquire(queue.shift())
    if (fn) fn(err, value)
  }

  return acquire
}

module.exports = mutexify
{
  "name": "mutexify",
  "version": "1.4.0",
  "description": "mutex lock for javascript",
  "main": "index.js",
  "dependencies": {
    "queue-tick": "^1.0.0"
  },
  "devDependencies": {
    "standard": "^14.3.3",
    "tape": "^3.0.2"
  },
  "scripts": {
    "test": "tape test.js",
    "posttest": "npm run lint",
    "lint": "standard"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/mutexify.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/mutexify/issues"
  },
  "keywords": [
    "mutex",
    "lock"
  ],
  "homepage": "https://github.com/mafintosh/mutexify"
}
var mutexify = require('.')

var mutexifyPromise = function () {
  var lock = mutexify()

  var acquire = function () {
    return new Promise(lock)
  }

  Object.defineProperty(acquire, 'locked', {
    get: function () { return lock.locked },
    enumerable: true
  })

  return acquire
}

module.exports = mutexifyPromise
module.exports = assert

class AssertionError extends Error {}
AssertionError.prototype.name = 'AssertionError'

/**
 * Minimal assert function
 * @param  {any} t Value to check if falsy
 * @param  {string=} m Optional assertion error message
 * @throws {AssertionError}
 */
function assert (t, m) {
  if (!t) {
    var err = new AssertionError(m)
    if (Error.captureStackTrace) Error.captureStackTrace(err, assert)
    throw err
  }
}
{
  "name": "nanoassert",
  "version": "2.0.0",
  "description": "Nanoscale assertion module",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "tape": "^4.9.1"
  },
  "scripts": {
    "test": "tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/emilbayes/nanoassert.git"
  },
  "keywords": [
    "assert",
    "unassert",
    "power-assert",
    "tiny",
    "nano",
    "pico"
  ],
  "author": "Emil Bay <github@tixz.dk>",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/emilbayes/nanoassert/issues"
  },
  "homepage": "https://github.com/emilbayes/nanoassert#readme"
}
module.exports = class NatSampler {
  constructor () {
    this.host = null
    this.port = 0
    this.size = 0

    this._a = null
    this._b = null
    this._threshold = 0
    this._top = 0
    this._samples = []
  }

  add (host, port) {
    const a = this._bump(host, port, 2)
    const b = this._bump(host, 0, 1)

    if (this._samples.length < 32) {
      this.size++
      this._threshold = this.size - (this.size < 4 ? 0 : this.size < 8 ? 1 : this.size < 12 ? 2 : 3)
      this._samples.push(a, b)
      this._top += 2
    } else {
      if (this._top === 32) this._top = 0

      const oa = this._samples[this._top]
      this._samples[this._top++] = a
      oa.hits--

      const ob = this._samples[this._top]
      this._samples[this._top++] = b
      ob.hits--
    }

    if (this._a === null || this._a.hits < a.hits) this._a = a
    if (this._b === null || this._b.hits < b.hits) this._b = b

    if (this._a.hits >= this._threshold) {
      this.host = this._a.host
      this.port = this._a.port
    } else if (this._b.hits >= this._threshold) {
      this.host = this._b.host
      this.port = 0
    } else {
      this.host = null
      this.port = 0
    }

    return a.hits
  }

  _bump (host, port, inc) {
    for (let i = 0; i < 4; i++) {
      const j = (this._top - inc - (2 * i)) & 31
      if (j >= this._samples.length) return { host, port, hits: 1 }
      const s = this._samples[j]
      if (s.port === port && s.host === host) {
        s.hits++
        return s
      }
    }
    return { host, port, hits: 1 }
  }
}
{
  "name": "nat-sampler",
  "version": "1.0.1",
  "description": "Sample addresses to figure out if a host + port is consistent",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^16.0.3",
    "tape": "^5.2.2"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/nat-sampler.git"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/nat-sampler/issues"
  },
  "homepage": "https://github.com/mafintosh/nat-sampler"
}
/* eslint-disable camelcase */
const sodium = require('sodium-universal')
const assert = require('nanoassert')
const b4a = require('b4a')

const DHLEN = sodium.crypto_scalarmult_ed25519_BYTES
const PKLEN = sodium.crypto_scalarmult_ed25519_BYTES
const SCALARLEN = sodium.crypto_scalarmult_ed25519_BYTES
const SKLEN = sodium.crypto_sign_SECRETKEYBYTES
const ALG = 'Ed25519'

module.exports = {
  DHLEN,
  PKLEN,
  SCALARLEN,
  SKLEN,
  ALG,
  name: ALG,
  generateKeyPair,
  dh
}

function generateKeyPair (privKey) {
  if (privKey) return generateSeedKeyPair(privKey.subarray(0, 32))

  const keyPair = {}
  keyPair.secretKey = b4a.alloc(SKLEN)
  keyPair.publicKey = b4a.alloc(PKLEN)

  sodium.crypto_sign_keypair(keyPair.publicKey, keyPair.secretKey)
  return keyPair
}

function generateSeedKeyPair (seed) {
  const keyPair = {}
  keyPair.secretKey = b4a.alloc(SKLEN)
  keyPair.publicKey = b4a.alloc(PKLEN)

  sodium.crypto_sign_seed_keypair(keyPair.publicKey, keyPair.secretKey, seed)
  return keyPair
}

function dh (publicKey, { scalar, secretKey }) {
  // tweaked keys expose scalar directly
  if (!scalar) {
    assert(secretKey.byteLength === SKLEN)

    // libsodium stores seed not actual scalar
    const sk = b4a.alloc(64)
    sodium.crypto_hash_sha512(sk, secretKey.subarray(0, 32))
    sk[0] &= 248
    sk[31] &= 127
    sk[31] |= 64

    scalar = sk.subarray(0, 32)
  }

  assert(scalar.byteLength === SCALARLEN)
  assert(publicKey.byteLength === PKLEN)

  const output = b4a.alloc(DHLEN)

  // we clamp if necessary above
  sodium.crypto_scalarmult_ed25519_noclamp(
    output,
    scalar,
    publicKey
  )

  return output
}
{
  "name": "noise-curve-ed",
  "version": "2.1.0",
  "description": "Ed25519 elliptic curve operations for [`noise-handshake`](https://github.com/chm-diederichs/noise-handshake)",
  "main": "index.js",
  "scripts": {
    "test": "npx standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/chm-diederichs/noise-curve-ed.git"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/chm-diederichs/noise-curve-ed/issues"
  },
  "homepage": "https://github.com/chm-diederichs/noise-curve-ed#readme",
  "dependencies": {
    "b4a": "^1.1.0",
    "nanoassert": "^2.0.0",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "noise-handshake": "^3.0.0",
    "standard": "^16.0.3",
    "tape": "^5.2.2"
  }
}
const sodium = require('sodium-universal')
const b4a = require('b4a')

module.exports = class CipherState {
  constructor (key) {
    this.key = key || null
    this.nonce = 0
    this.CIPHER_ALG = 'ChaChaPoly'
  }

  initialiseKey (key) {
    this.key = key
    this.nonce = 0
  }

  setNonce (nonce) {
    this.nonce = nonce
  }

  encrypt (plaintext, ad) {
    if (!this.hasKey) return plaintext
    if (!ad) ad = b4a.alloc(0)

    const ciphertext = encryptWithAD(this.key, this.nonce, ad, plaintext)
    if (ciphertext.length > 65535) throw new Error(`ciphertext length of ${ciphertext.length} exceeds maximum Noise message length of 65535`)
    this.nonce++

    return ciphertext
  }

  decrypt (ciphertext, ad) {
    if (!this.hasKey) return ciphertext
    if (!ad) ad = b4a.alloc(0)
    if (ciphertext.length > 65535) throw new Error(`ciphertext length of ${ciphertext.length} exceeds maximum Noise message length of 65535`)

    const plaintext = decryptWithAD(this.key, this.nonce, ad, ciphertext)
    this.nonce++

    return plaintext
  }

  get hasKey () {
    return this.key !== null
  }

  _clear () {
    sodium.sodium_memzero(this.key)
    this.key = null
    this.nonce = null
  }

  static get MACBYTES () {
    return 16
  }

  static get NONCEBYTES () {
    return 8
  }

  static get KEYBYTES () {
    return 32
  }
}

function encryptWithAD (key, counter, additionalData, plaintext) {
  // for our purposes, additionalData will always be a pubkey so we encode from hex
  if (!b4a.isBuffer(additionalData)) additionalData = b4a.from(additionalData, 'hex')
  if (!b4a.isBuffer(plaintext)) plaintext = b4a.from(plaintext, 'hex')

  const nonce = b4a.alloc(sodium.crypto_aead_chacha20poly1305_ietf_NPUBBYTES)
  const view = new DataView(nonce.buffer, nonce.byteOffset, nonce.byteLength)
  view.setUint32(4, counter, true)

  const ciphertext = b4a.alloc(plaintext.byteLength + sodium.crypto_aead_chacha20poly1305_ietf_ABYTES)

  sodium.crypto_aead_chacha20poly1305_ietf_encrypt(ciphertext, plaintext, additionalData, null, nonce, key)
  return ciphertext
}

function decryptWithAD (key, counter, additionalData, ciphertext) {
  // for our purposes, additionalData will always be a pubkey so we encode from hex
  if (!b4a.isBuffer(additionalData)) additionalData = b4a.from(additionalData, 'hex')
  if (!b4a.isBuffer(ciphertext)) ciphertext = b4a.from(ciphertext, 'hex')

  const nonce = b4a.alloc(sodium.crypto_aead_chacha20poly1305_ietf_NPUBBYTES)
  const view = new DataView(nonce.buffer, nonce.byteOffset, nonce.byteLength)
  view.setUint32(4, counter, true)

  const plaintext = b4a.alloc(ciphertext.byteLength - sodium.crypto_aead_chacha20poly1305_ietf_ABYTES)

  sodium.crypto_aead_chacha20poly1305_ietf_decrypt(plaintext, null, ciphertext, additionalData, nonce, key)
  return plaintext
}
/* eslint-disable camelcase */
const {
  crypto_kx_SEEDBYTES,
  crypto_kx_keypair,
  crypto_kx_seed_keypair,
  crypto_scalarmult_BYTES,
  crypto_scalarmult_SCALARBYTES,
  crypto_scalarmult,
  crypto_scalarmult_base
} = require('sodium-universal')

const assert = require('nanoassert')
const b4a = require('b4a')

const DHLEN = crypto_scalarmult_BYTES
const PKLEN = crypto_scalarmult_BYTES
const SKLEN = crypto_scalarmult_SCALARBYTES
const SEEDLEN = crypto_kx_SEEDBYTES
const ALG = '25519'

module.exports = {
  DHLEN,
  PKLEN,
  SKLEN,
  SEEDLEN,
  ALG,
  generateKeyPair,
  generateSeedKeyPair,
  dh
}

function generateKeyPair (privKey) {
  const keyPair = {}

  keyPair.secretKey = privKey || b4a.alloc(SKLEN)
  keyPair.publicKey = b4a.alloc(PKLEN)

  if (privKey) {
    crypto_scalarmult_base(keyPair.publicKey, keyPair.secretKey)
  } else {
    crypto_kx_keypair(keyPair.publicKey, keyPair.secretKey)
  }

  return keyPair
}

function generateSeedKeyPair (seed) {
  assert(seed.byteLength === SKLEN)

  const keyPair = {}
  keyPair.secretKey = b4a.alloc(SKLEN)
  keyPair.publicKey = b4a.alloc(PKLEN)

  crypto_kx_seed_keypair(keyPair.publicKey, keyPair.secretKey, seed)
  return keyPair
}

function dh (publicKey, { secretKey }) {
  assert(secretKey.byteLength === SKLEN)
  assert(publicKey.byteLength === PKLEN)

  const output = b4a.alloc(DHLEN)

  crypto_scalarmult(
    output,
    secretKey,
    publicKey
  )

  return output
}
const hmacBlake2b = require('./hmac')
const b4a = require('b4a')

const HASHLEN = 64

module.exports = {
  hkdf,
  HASHLEN
}

// HMAC-based Extract-and-Expand KDF
// https://www.ietf.org/rfc/rfc5869.txt

function hkdf (salt, inputKeyMaterial, info = '', length = 2 * HASHLEN) {
  const pseudoRandomKey = hkdfExtract(salt, inputKeyMaterial)
  return hkdfExpand(pseudoRandomKey, info, length)
}

function hkdfExtract (salt, inputKeyMaterial) {
  const hmac = b4a.alloc(HASHLEN)
  return hmacDigest(hmac, salt, inputKeyMaterial)
}

function hkdfExpand (key, info, length) {
  // Put in dedicated slab to avoid keeping shared slab from being gc'ed
  const buffer = b4a.allocUnsafeSlow(length)

  const infoBuf = b4a.from(info)
  let prev = infoBuf

  const result = []
  for (let i = 0; i < length; i += HASHLEN) {
    const pos = b4a.from([(i / HASHLEN) + 1])

    const out = buffer.subarray(i, i + HASHLEN)
    result.push(out)

    prev = hmacDigest(out, key, [prev, infoBuf, pos])
  }

  return result
}

function hmacDigest (out, key, input) {
  hmacBlake2b(out, input, key)
  return out
}
/* eslint-disable camelcase */
const b4a = require('b4a')
const { sodium_memzero, crypto_generichash, crypto_generichash_batch } = require('sodium-universal')

const HASHLEN = 64
const BLOCKLEN = 128
const scratch = b4a.alloc(BLOCKLEN * 3)
const HMACKey = scratch.subarray(BLOCKLEN * 0, BLOCKLEN * 1)
const OuterKeyPad = scratch.subarray(BLOCKLEN * 1, BLOCKLEN * 2)
const InnerKeyPad = scratch.subarray(BLOCKLEN * 2, BLOCKLEN * 3)

// Post-fill is done in the cases where someone caught an exception that
// happened before we were able to clear data at the end

module.exports = function hmac (out, batch, key) {
  if (key.byteLength > BLOCKLEN) {
    crypto_generichash(HMACKey.subarray(0, HASHLEN), key)
    sodium_memzero(HMACKey.subarray(HASHLEN))
  } else {
    // Covers key <= BLOCKLEN
    HMACKey.set(key)
    sodium_memzero(HMACKey.subarray(key.byteLength))
  }

  for (let i = 0; i < HMACKey.byteLength; i++) {
    OuterKeyPad[i] = 0x5c ^ HMACKey[i]
    InnerKeyPad[i] = 0x36 ^ HMACKey[i]
  }
  sodium_memzero(HMACKey)

  crypto_generichash_batch(out, [InnerKeyPad].concat(batch))
  sodium_memzero(InnerKeyPad)
  crypto_generichash_batch(out, [OuterKeyPad, out])
  sodium_memzero(OuterKeyPad)
}

module.exports.BYTES = HASHLEN
module.exports.KEYBYTES = BLOCKLEN
const assert = require('nanoassert')
const b4a = require('b4a')

const SymmetricState = require('./symmetric-state')
const { HASHLEN } = require('./hkdf')

const PRESHARE_IS = Symbol('initiator static key preshared')
const PRESHARE_RS = Symbol('responder static key preshared')

const TOK_PSK = Symbol('psk')

const TOK_S = Symbol('s')
const TOK_E = Symbol('e')

const TOK_ES = Symbol('es')
const TOK_SE = Symbol('se')
const TOK_EE = Symbol('ee')
const TOK_SS = Symbol('ss')

const HANDSHAKES = Object.freeze({
  NN: [
    [TOK_E],
    [TOK_E, TOK_EE]
  ],
  NNpsk0: [
    [TOK_PSK, TOK_E],
    [TOK_E, TOK_EE]
  ],
  XX: [
    [TOK_E],
    [TOK_E, TOK_EE, TOK_S, TOK_ES],
    [TOK_S, TOK_SE]
  ],
  XXpsk0: [
    [TOK_PSK, TOK_E],
    [TOK_E, TOK_EE, TOK_S, TOK_ES],
    [TOK_S, TOK_SE]
  ],
  IK: [
    PRESHARE_RS,
    [TOK_E, TOK_ES, TOK_S, TOK_SS],
    [TOK_E, TOK_EE, TOK_SE]
  ],
  XK: [
    PRESHARE_RS,
    [TOK_E, TOK_ES],
    [TOK_E, TOK_EE],
    [TOK_S, TOK_SE]
  ]
})

class Writer {
  constructor () {
    this.size = 0
    this.buffers = []
  }

  push (b) {
    this.size += b.byteLength
    this.buffers.push(b)
  }

  end () {
    const all = b4a.alloc(this.size)
    let offset = 0
    for (const b of this.buffers) {
      all.set(b, offset)
      offset += b.byteLength
    }
    return all
  }
}

class Reader {
  constructor (buf) {
    this.offset = 0
    this.buffer = buf
  }

  shift (n) {
    const start = this.offset
    const end = this.offset += n
    if (end > this.buffer.byteLength) throw new Error('Insufficient bytes')
    return this.buffer.subarray(start, end)
  }

  end () {
    return this.shift(this.buffer.byteLength - this.offset)
  }
}

module.exports = class NoiseState extends SymmetricState {
  constructor (pattern, initiator, staticKeypair, opts = {}) {
    super(opts)

    this.s = staticKeypair || this.curve.generateKeyPair()
    this.e = null

    this.psk = null
    if (opts && opts.psk) this.psk = opts.psk

    this.re = null
    this.rs = null

    this.pattern = pattern
    this.handshake = HANDSHAKES[this.pattern].slice()

    this.isPskHandshake = !!this.psk && hasPskToken(this.handshake)

    this.protocol = b4a.from([
      'Noise',
      this.pattern,
      this.DH_ALG,
      this.CIPHER_ALG,
      'BLAKE2b'
    ].join('_'))

    this.initiator = initiator
    this.complete = false

    this.rx = null
    this.tx = null
    this.hash = null
  }

  initialise (prologue, remoteStatic) {
    if (this.protocol.byteLength <= HASHLEN) this.digest.set(this.protocol)
    else this.mixHash(this.protocol)

    this.chainingKey = b4a.from(this.digest)

    this.mixHash(prologue)

    while (!Array.isArray(this.handshake[0])) {
      const message = this.handshake.shift()

      // handshake steps should be as arrays, only
      // preshare tokens are provided otherwise
      assert(message === PRESHARE_RS || message === PRESHARE_IS,
        'Unexpected pattern')

      const takeRemoteKey = this.initiator
        ? message === PRESHARE_RS
        : message === PRESHARE_IS

      if (takeRemoteKey) this.rs = remoteStatic

      const key = takeRemoteKey ? this.rs : this.s.publicKey
      assert(key != null, 'Remote pubkey required')

      this.mixHash(key)
    }
  }

  final () {
    const [k1, k2] = this.split()

    this.tx = this.initiator ? k1 : k2
    this.rx = this.initiator ? k2 : k1

    this.complete = true
    this.hash = this.getHandshakeHash()

    this._clear()
  }

  recv (buf) {
    const r = new Reader(buf)

    for (const pattern of this.handshake.shift()) {
      switch (pattern) {
        case TOK_PSK :
          this.mixKeyAndHash(this.psk)
          break

        case TOK_E :
          this.re = r.shift(this.curve.PKLEN)
          this.mixHash(this.re)
          if (this.isPskHandshake) this.mixKeyNormal(this.re)
          break

        case TOK_S : {
          const klen = this.hasKey ? this.curve.PKLEN + 16 : this.curve.PKLEN
          this.rs = this.decryptAndHash(r.shift(klen))
          break
        }

        case TOK_EE :
        case TOK_ES :
        case TOK_SE :
        case TOK_SS : {
          const useStatic = keyPattern(pattern, this.initiator)

          const localKey = useStatic.local ? this.s : this.e
          const remoteKey = useStatic.remote ? this.rs : this.re

          this.mixKey(remoteKey, localKey)
          break
        }

        default :
          throw new Error('Unexpected message')
      }
    }

    const payload = this.decryptAndHash(r.end())

    if (!this.handshake.length) this.final()
    return payload
  }

  send (payload = b4a.alloc(0)) {
    const w = new Writer()

    for (const pattern of this.handshake.shift()) {
      switch (pattern) {
        case TOK_PSK :
          this.mixKeyAndHash(this.psk)
          break

        case TOK_E :
          if (this.e === null) this.e = this.curve.generateKeyPair()
          this.mixHash(this.e.publicKey)
          if (this.isPskHandshake) this.mixKeyNormal(this.e.publicKey)
          w.push(this.e.publicKey)
          break

        case TOK_S :
          w.push(this.encryptAndHash(this.s.publicKey))
          break

        case TOK_ES :
        case TOK_SE :
        case TOK_EE :
        case TOK_SS : {
          const useStatic = keyPattern(pattern, this.initiator)

          const localKey = useStatic.local ? this.s : this.e
          const remoteKey = useStatic.remote ? this.rs : this.re

          this.mixKey(remoteKey, localKey)
          break
        }

        default :
          throw new Error('Unexpected message')
      }
    }

    w.push(this.encryptAndHash(payload))
    const response = w.end()

    if (!this.handshake.length) this.final()
    return response
  }

  _clear () {
    super._clear()

    this.e.secretKey.fill(0)
    this.e.publicKey.fill(0)

    this.re.fill(0)

    this.e = null
    this.re = null
  }
}

function keyPattern (pattern, initiator) {
  const ret = {
    local: false,
    remote: false
  }

  switch (pattern) {
    case TOK_EE:
      return ret

    case TOK_ES:
      ret.local ^= !initiator
      ret.remote ^= initiator
      return ret

    case TOK_SE:
      ret.local ^= initiator
      ret.remote ^= !initiator
      return ret

    case TOK_SS:
      ret.local ^= 1
      ret.remote ^= 1
      return ret
  }
}

function hasPskToken (handshake) {
  return handshake.some(x => {
    return Array.isArray(x) && x.indexOf(TOK_PSK) !== -1
  })
}
{
  "name": "noise-handshake",
  "version": "4.2.0",
  "description": "Noise protocol handshake",
  "main": "noise.js",
  "files": [
    "*.js"
  ],
  "scripts": {
    "test": "standard && brittle test/*.js"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/noise-handshake.git"
  },
  "dependencies": {
    "b4a": "^1.1.0",
    "nanoassert": "^2.0.0",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "noise-protocol": "chm-diederichs/noise-protocol.git#xx-ephemeral-key",
    "standard": "^16.0.3"
  }
}
const sodium = require('sodium-universal')
const assert = require('nanoassert')
const b4a = require('b4a')
const CipherState = require('./cipher')
const curve = require('./dh')
const { HASHLEN, hkdf } = require('./hkdf')

module.exports = class SymmetricState extends CipherState {
  constructor (opts = {}) {
    super()

    this.curve = opts.curve || curve
    this.digest = b4a.alloc(HASHLEN)
    this.chainingKey = null
    this.offset = 0

    this.DH_ALG = this.curve.ALG
  }

  mixHash (data) {
    accumulateDigest(this.digest, data)
  }

  mixKeyAndHash (key) {
    const [ck, tempH, tempK] = hkdf(this.chainingKey, key, '', 3 * HASHLEN)
    this.chainingKey = ck
    this.mixHash(tempH)
    this.initialiseKey(tempK.subarray(0, 32))
  }

  mixKeyNormal (key) {
    const [ck, tempK] = hkdf(this.chainingKey, key)
    this.chainingKey = ck
    this.initialiseKey(tempK.subarray(0, 32))
  }

  mixKey (remoteKey, localKey) {
    const dh = this.curve.dh(remoteKey, localKey)
    const hkdfResult = hkdf(this.chainingKey, dh)
    this.chainingKey = hkdfResult[0]
    this.initialiseKey(hkdfResult[1].subarray(0, 32))
  }

  encryptAndHash (plaintext) {
    const ciphertext = this.encrypt(plaintext, this.digest)
    accumulateDigest(this.digest, ciphertext)
    return ciphertext
  }

  decryptAndHash (ciphertext) {
    const plaintext = this.decrypt(ciphertext, this.digest)
    accumulateDigest(this.digest, ciphertext)
    return plaintext
  }

  getHandshakeHash (out) {
    if (!out) return this.getHandshakeHash(b4a.alloc(HASHLEN))
    assert(out.byteLength === HASHLEN, `output must be ${HASHLEN} bytes`)

    out.set(this.digest)
    return out
  }

  split () {
    const res = hkdf(this.chainingKey, b4a.alloc(0))
    return res.map(k => k.subarray(0, 32))
  }

  _clear () {
    super._clear()

    sodium.sodium_memzero(this.digest)
    sodium.sodium_memzero(this.chainingKey)

    this.digest = null
    this.chainingKey = null
    this.offset = null

    this.curve = null
  }

  static get alg () {
    return CipherState.alg + '_BLAKE2b'
  }
}

function accumulateDigest (digest, input) {
  const toHash = b4a.concat([digest, input])
  sodium.crypto_generichash(digest, toHash)
}
var varint = require('varint')
var svarint = require('signed-varint')
var b4a = require('b4a')

exports.make = encoder

exports.name = function (enc) {
  var keys = Object.keys(exports)
  for (var i = 0; i < keys.length; i++) {
    if (exports[keys[i]] === enc) return keys[i]
  }
  return null
}

exports.skip = function (type, buffer, offset) {
  switch (type) {
    case 0:
      varint.decode(buffer, offset)
      return offset + varint.decode.bytes

    case 1:
      return offset + 8

    case 2:
      var len = varint.decode(buffer, offset)
      return offset + varint.decode.bytes + len

    case 3:
    case 4:
      throw new Error('Groups are not supported')

    case 5:
      return offset + 4
  }

  throw new Error('Unknown wire type: ' + type)
}

exports.bytes = encoder(2,
  function encode (val, buffer, offset) {
    var oldOffset = offset
    var len = bufferLength(val)

    varint.encode(len, buffer, offset)
    offset += varint.encode.bytes

    if (b4a.isBuffer(val)) b4a.copy(val, buffer, offset)
    else b4a.write(buffer, val, offset, len)
    offset += len

    encode.bytes = offset - oldOffset
    return buffer
  },
  function decode (buffer, offset) {
    var oldOffset = offset

    var len = varint.decode(buffer, offset)
    offset += varint.decode.bytes

    var val = buffer.subarray(offset, offset + len)
    offset += val.length

    decode.bytes = offset - oldOffset
    return val
  },
  function encodingLength (val) {
    var len = bufferLength(val)
    return varint.encodingLength(len) + len
  }
)

exports.string = encoder(2,
  function encode (val, buffer, offset) {
    var oldOffset = offset
    var len = b4a.byteLength(val)

    varint.encode(len, buffer, offset, 'utf-8')
    offset += varint.encode.bytes

    b4a.write(buffer, val, offset, len)
    offset += len

    encode.bytes = offset - oldOffset
    return buffer
  },
  function decode (buffer, offset) {
    var oldOffset = offset

    var len = varint.decode(buffer, offset)
    offset += varint.decode.bytes

    var val = b4a.toString(buffer, 'utf-8', offset, offset + len)
    offset += len

    decode.bytes = offset - oldOffset
    return val
  },
  function encodingLength (val) {
    var len = b4a.byteLength(val)
    return varint.encodingLength(len) + len
  }
)

exports.bool = encoder(0,
  function encode (val, buffer, offset) {
    buffer[offset] = val ? 1 : 0
    encode.bytes = 1
    return buffer
  },
  function decode (buffer, offset) {
    var bool = buffer[offset] > 0
    decode.bytes = 1
    return bool
  },
  function encodingLength () {
    return 1
  }
)

exports.int32 = encoder(0,
  function encode (val, buffer, offset) {
    varint.encode(val < 0 ? val + 4294967296 : val, buffer, offset)
    encode.bytes = varint.encode.bytes
    return buffer
  },
  function decode (buffer, offset) {
    var val = varint.decode(buffer, offset)
    decode.bytes = varint.decode.bytes
    return val > 2147483647 ? val - 4294967296 : val
  },
  function encodingLength (val) {
    return varint.encodingLength(val < 0 ? val + 4294967296 : val)
  }
)

exports.int64 = encoder(0,
  function encode (val, buffer, offset) {
    if (val < 0) {
      var last = offset + 9
      varint.encode(val * -1, buffer, offset)
      offset += varint.encode.bytes - 1
      buffer[offset] = buffer[offset] | 0x80
      while (offset < last - 1) {
        offset++
        buffer[offset] = 0xff
      }
      buffer[last] = 0x01
      encode.bytes = 10
    } else {
      varint.encode(val, buffer, offset)
      encode.bytes = varint.encode.bytes
    }
    return buffer
  },
  function decode (buffer, offset) {
    var val = varint.decode(buffer, offset)
    if (val >= Math.pow(2, 63)) {
      var limit = 9
      while (buffer[offset + limit - 1] === 0xff) limit--
      limit = limit || 9
      var subset = b4a.allocUnsafe(limit)
      b4a.copy(buffer, subset, 0, offset, offset + limit)
      subset[limit - 1] = subset[limit - 1] & 0x7f
      val = -1 * varint.decode(subset, 0)
      decode.bytes = 10
    } else {
      decode.bytes = varint.decode.bytes
    }
    return val
  },
  function encodingLength (val) {
    return val < 0 ? 10 : varint.encodingLength(val)
  }
)

exports.sint32 =
exports.sint64 = encoder(0,
  svarint.encode,
  svarint.decode,
  svarint.encodingLength
)

exports.uint32 =
exports.uint64 =
exports.enum =
exports.varint = encoder(0,
  varint.encode,
  varint.decode,
  varint.encodingLength
)

// we cannot represent these in javascript so we just use buffers
exports.fixed64 =
exports.sfixed64 = encoder(1,
  function encode (val, buffer, offset) {
    b4a.copy(val, buffer, offset)
    encode.bytes = 8
    return buffer
  },
  function decode (buffer, offset) {
    var val = buffer.subarray(offset, offset + 8)
    decode.bytes = 8
    return val
  },
  function encodingLength () {
    return 8
  }
)

exports.double = encoder(1,
  function encode (val, buffer, offset) {
    b4a.writeDoubleLE(buffer, val, offset)
    encode.bytes = 8
    return buffer
  },
  function decode (buffer, offset) {
    var val = b4a.readDoubleLE(buffer, offset)
    decode.bytes = 8
    return val
  },
  function encodingLength () {
    return 8
  }
)

exports.fixed32 = encoder(5,
  function encode (val, buffer, offset) {
    b4a.writeUInt32LE(buffer, val, offset)
    encode.bytes = 4
    return buffer
  },
  function decode (buffer, offset) {
    var val = b4a.readUInt32LE(buffer, offset)
    decode.bytes = 4
    return val
  },
  function encodingLength () {
    return 4
  }
)

exports.sfixed32 = encoder(5,
  function encode (val, buffer, offset) {
    b4a.writeInt32LE(buffer, val, offset)
    encode.bytes = 4
    return buffer
  },
  function decode (buffer, offset) {
    var val = b4a.readInt32LE(buffer, offset)
    decode.bytes = 4
    return val
  },
  function encodingLength () {
    return 4
  }
)

exports.float = encoder(5,
  function encode (val, buffer, offset) {
    b4a.writeFloatLE(buffer, val, offset)
    encode.bytes = 4
    return buffer
  },
  function decode (buffer, offset) {
    var val = b4a.readFloatLE(buffer, offset)
    decode.bytes = 4
    return val
  },
  function encodingLength () {
    return 4
  }
)

function encoder (type, encode, decode, encodingLength) {
  encode.bytes = decode.bytes = 0

  return {
    type: type,
    encode: encode,
    decode: decode,
    encodingLength: encodingLength
  }
}

function bufferLength (val) {
  return b4a.isBuffer(val) ? val.length : b4a.byteLength(val)
}
{
  "name": "protocol-buffers-encodings",
  "version": "1.2.0",
  "description": "Base encodings for protocol-buffers",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.6.0",
    "signed-varint": "^2.0.1",
    "varint": "5.0.0"
  },
  "devDependencies": {
    "standard": "^14.3.4",
    "tape": "^5.0.1"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/protocol-buffers-encodings.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/protocol-buffers-encodings/issues"
  },
  "homepage": "https://github.com/mafintosh/protocol-buffers-encodings"
}
const EventEmitter = require('events')
const Protomux = require('protomux')
const c = require('compact-encoding')
const bitfield = require('compact-encoding-bitfield')
const bits = require('bits-to-bytes')
const safetyCatch = require('safety-catch')
const errors = require('./lib/errors')

module.exports = class ProtomuxRPC extends EventEmitter {
  constructor(stream, options = {}) {
    super()

    const {
      id,
      protocol = 'protomux-rpc',
      valueEncoding = c.optionalBuffer,
      handshake = null,
      handshakeEncoding
    } = options

    this._mux = Protomux.from(stream)
    this._defaultValueEncoding = valueEncoding

    this._id = 1
    this._ending = null
    this._destroyed = false
    this._error = null
    this._responding = 0

    this._requests = new Map()
    this._responders = new Map()

    this._channel = this._mux.createChannel({
      protocol,
      id,
      handshake: handshake === null ? null : handshakeEncoding || c.raw,
      onopen: this._onopen.bind(this),
      onclose: this._onclose.bind(this),
      ondestroy: this._ondestroy.bind(this)
    })

    if (this._channel === null) throw errors.DUPLICATE_CHANNEL()

    this._request = this._channel.addMessage({
      encoding: request,
      onmessage: this._onrequest.bind(this)
    })

    this._response = this._channel.addMessage({
      encoding: response,
      onmessage: this._onresponse.bind(this)
    })

    this._channel.open(handshake)
  }

  _onopen(handshake) {
    this.emit('open', handshake)
  }

  _onclose() {
    this._ending = Promise.resolve()

    const err = this._error || errors.CHANNEL_CLOSED()

    for (const request of this._requests.values()) {
      request.reject(err)
      if (request.timeout) clearTimeout(request.timeout)
    }

    this._requests.clear()
    this._responders.clear()

    this.emit('close')
  }

  _ondestroy() {
    this._destroyed = true
    this.emit('destroy')
  }

  async _onrequest({ id, method, value }) {
    let error = null

    const responder = this._responders.get(method)

    if (responder === undefined) error = errors.UNKNOWN_METHOD(`Unknown method '${method}'`)
    else {
      const {
        valueEncoding = this._defaultValueEncoding,
        requestEncoding = valueEncoding,
        responseEncoding = valueEncoding
      } = responder.options

      this._responding++

      try {
        if (requestEncoding) value = c.decode(requestEncoding, value)

        try {
          value = await responder.handler(value)
        } catch (err) {
          safetyCatch(err)

          error = errors.REQUEST_ERROR('Request failed', err)
        }
      } catch (err) {
        safetyCatch(err)

        error = errors.DECODE_ERROR('Could not decode request', err)
      }

      this._responding--

      if (!error && responseEncoding && id) {
        try {
          value = c.encode(responseEncoding, value)
        } catch (err) {
          safetyCatch(err)

          error = errors.ENCODE_ERROR('Could not encode response', err)
        }
      }
    }

    if (id) this._response.send({ id, error, value })

    this._endMaybe()
  }

  _onresponse({ id, error, value }) {
    if (id === 0) return

    const request = this._requests.get(id)

    if (request === undefined) return

    this._requests.delete(id)

    if (request.timeout) clearTimeout(request.timeout)

    if (error) request.reject(error)
    else {
      const { valueEncoding = this._defaultValueEncoding, responseEncoding = valueEncoding } =
        request.options

      try {
        if (responseEncoding) value = c.decode(responseEncoding, value)

        request.resolve(value)
      } catch (err) {
        safetyCatch(err)

        request.reject(errors.DECODE_ERROR('Could not decode response', err))
      }
    }

    this._endMaybe()
  }

  _ontimeout(id, timeout) {
    const request = this._requests.get(id)

    if (request === undefined) return

    this._requests.delete(id)

    request.reject(errors.TIMEOUT_EXCEEDED(`timeout of ${timeout}ms exceeded`))

    this._endMaybe()
  }

  get opened() {
    return this._channel.opened
  }

  get closed() {
    return this._channel.closed
  }

  get mux() {
    return this._mux
  }

  get stream() {
    return this._mux.stream
  }

  async fullyOpened() {
    await this._channel.fullyOpened()
  }

  respond(method, options, handler) {
    if (typeof options === 'function') {
      handler = options
      options = {}
    }

    this._responders.set(method, { options, handler })

    return this
  }

  unrespond(method) {
    this._responders.delete(method)

    return this
  }

  async request(method, value, options = {}) {
    if (this.closed) throw errors.CHANNEL_CLOSED()

    const {
      valueEncoding = this._defaultValueEncoding,
      requestEncoding = valueEncoding,
      timeout = -1
    } = options

    if (requestEncoding) value = c.encode(requestEncoding, value)

    const id = this._id++

    this._request.send({ id, method, value })

    return new Promise((resolve, reject) =>
      this._requests.set(id, {
        options,
        resolve,
        reject,
        timeout: timeout > 0 && setTimeout(this._ontimeout.bind(this, id, timeout), timeout)
      })
    )
  }

  event(method, value, options = {}) {
    if (this.closed) throw errors.CHANNEL_CLOSED()

    const { valueEncoding = this._defaultValueEncoding, requestEncoding = valueEncoding } = options

    if (requestEncoding) value = c.encode(requestEncoding, value)

    this._request.send({ id: 0, method, value })
  }

  cork() {
    this._channel.cork()
  }

  uncork() {
    this._channel.uncork()
  }

  async end() {
    if (this._ending) return this._ending

    this._ending = EventEmitter.once(this, 'close')
    this._endMaybe()

    return this._ending
  }

  _endMaybe() {
    if (this._ending && this._responding === 0 && this._requests.size === 0) {
      this._channel.close()
    }
  }

  destroy(err) {
    if (this._destroyed) return
    this._destroyed = true

    this._error = err || errors.CHANNEL_DESTROYED()
    this._channel.close()
  }
}

const request = {
  preencode(state, m) {
    c.uint.preencode(state, m.id)
    c.string.preencode(state, m.method)
    c.raw.preencode(state, m.value)
  },
  encode(state, m) {
    c.uint.encode(state, m.id)
    c.string.encode(state, m.method)
    c.raw.encode(state, m.value)
  },
  decode(state) {
    return {
      id: c.uint.decode(state),
      method: c.string.decode(state),
      value: c.raw.decode(state)
    }
  }
}

const flags = bitfield(1)

const response = {
  preencode(state, m) {
    flags.preencode(state)

    c.uint.preencode(state, m.id)

    if (m.error) {
      c.string.preencode(state, m.error.message.replace(m.error.code + ': ', ''))

      if (m.error.code) c.string.preencode(state, m.error.code)

      if (m.error.cause) {
        const cause = m.error.cause

        c.string.preencode(state, cause.message)
        c.string.preencode(state, cause.code || '')

        if (cause.context) c.string.preencode(state, cause.context)
      }
    } else {
      c.raw.preencode(state, m.value)
    }
  },
  encode(state, m) {
    flags.encode(
      state,
      bits.of(
        !!m.error,
        !!(m.error && m.error.code),
        !!(m.error && m.error.cause),
        !!(m.error && m.error.cause && m.error.cause.context)
      )
    )

    c.uint.encode(state, m.id)

    if (m.error) {
      c.string.encode(state, m.error.message.replace(m.error.code + ': ', ''))

      if (m.error.code) c.string.encode(state, m.error.code)

      if (m.error.cause) {
        const cause = m.error.cause

        c.string.encode(state, cause.message)
        c.string.encode(state, cause.code || '')

        if (cause.context) c.string.encode(state, cause.context)
      }
    } else {
      c.raw.encode(state, m.value)
    }
  },
  decode(state) {
    const [hasError, hasErrorCode, hasErrorCause, hasErrorContext] = bits.iterator(
      flags.decode(state)
    )

    const id = c.uint.decode(state)

    let error = null
    let value = null

    if (hasError) {
      const message = c.string.decode(state)
      const code = hasErrorCode ? c.string.decode(state) : null

      let cause
      if (hasErrorCause) {
        cause = new Error(c.string.decode(state))

        const code = c.string.decode(state)
        if (code) cause.code = code

        const context = hasErrorContext ? c.string.decode(state) : null
        if (context) cause.context = context
      }

      switch (code) {
        case 'UNKNOWN_METHOD':
          error = errors.UNKNOWN_METHOD(message)
          break
        case 'REQUEST_ERROR':
          error = errors.REQUEST_ERROR(message, cause)
          break
        case 'DECODE_ERROR':
          error = errors.DECODE_ERROR(message, cause)
          break
        case 'ENCODE_ERROR':
          error = errors.ENCODE_ERROR(message, cause)
          break
        default:
          error = new Error(message, { cause })
      }
    } else {
      value = c.raw.decode(state)
    }

    return {
      id,
      error,
      value
    }
  }
}
module.exports = class RPCError extends Error {
  constructor(msg, code, fn = RPCError, { cause } = {}) {
    super(`${code}: ${msg}`, { cause })
    this.code = code

    if (Error.captureStackTrace) Error.captureStackTrace(this, fn)
  }

  get name() {
    return 'RPCError'
  }

  static DUPLICATE_CHANNEL(msg = 'duplicate channel') {
    return new RPCError(msg, 'DUPLICATE_CHANNEL', RPCError.DUPLICATE_CHANNEL)
  }

  static CHANNEL_CLOSED(msg = 'channel closed') {
    return new RPCError(msg, 'CHANNEL_CLOSED', RPCError.CHANNEL_CLOSED)
  }

  static CHANNEL_DESTROYED(msg = 'channel destroyed') {
    return new RPCError(msg, 'CHANNEL_DESTROYED', RPCError.CHANNEL_DESTROYED)
  }

  static REQUEST_ERROR(msg, cause) {
    return new RPCError(msg, 'REQUEST_ERROR', RPCError.REQUEST_ERROR, { cause })
  }

  static TIMEOUT_EXCEEDED(msg) {
    return new RPCError(msg, 'TIMEOUT_EXCEEDED', RPCError.TIMEOUT_EXCEEDED)
  }

  static UNKNOWN_METHOD(msg) {
    return new RPCError(msg, 'UNKNOWN_METHOD', RPCError.UNKNOWN_METHOD)
  }

  static DECODE_ERROR(msg, cause) {
    return new RPCError(msg, 'DECODE_ERROR', RPCError.DECODE_ERROR, { cause })
  }

  static ENCODE_ERROR(msg, cause) {
    return new RPCError(msg, 'ENCODE_ERROR', RPCError.ENCODE_ERROR, { cause })
  }
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "protomux-rpc",
  "version": "1.10.0",
  "description": "RPC over Protomux channels",
  "main": "index.js",
  "files": [
    "index.js",
    "lib"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "exports": {
    "./package": "./package.json",
    ".": "./index.js",
    "./errors": "./lib/errors.js"
  },
  "scripts": {
    "test": "prettier . --check && brittle test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/protomux-rpc.git"
  },
  "author": "Kasper Isager Dalsgarð <kasper@funktionel.co>",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/protomux-rpc/issues"
  },
  "homepage": "https://github.com/holepunchto/protomux-rpc#readme",
  "dependencies": {
    "bits-to-bytes": "^1.0.0",
    "compact-encoding": "^3.0.0",
    "compact-encoding-bitfield": "^1.0.0",
    "protomux": "^3.7.0",
    "safety-catch": "^1.0.2"
  },
  "optionalDependencies": {
    "bare-events": "^2.2.0"
  },
  "devDependencies": {
    "brittle": "^3.3.0",
    "prettier": "^3.7.4",
    "prettier-config-holepunch": "^2.0.0",
    "streamx": "^2.12.4"
  }
}
const b4a = require('b4a')
const c = require('compact-encoding')
const queueTick = require('queue-tick')
const safetyCatch = require('safety-catch')
const unslab = require('unslab')

const MAX_BUFFERED = 32768
const MAX_BACKLOG = Infinity // TODO: impl "open" backpressure
const MAX_BATCH = 8 * 1024 * 1024

class Channel {
  constructor(
    mux,
    info,
    userData,
    protocol,
    aliases,
    id,
    handshake,
    messages,
    onopen,
    onclose,
    ondestroy,
    ondrain
  ) {
    this.userData = userData
    this.protocol = protocol
    this.aliases = aliases
    this.id = id
    this.handshake = null
    this.messages = []

    this.opened = false
    this.closed = false
    this.destroyed = false

    this.onopen = onopen
    this.onclose = onclose
    this.ondestroy = ondestroy
    this.ondrain = ondrain

    this._handshake = handshake
    this._mux = mux
    this._info = info
    this._localId = 0
    this._remoteId = 0
    this._active = 0
    this._extensions = null

    this._decBound = this._dec.bind(this)
    this._decAndDestroyBound = this._decAndDestroy.bind(this)

    this._openedPromise = null
    this._openedResolve = null

    this._destroyedPromise = null
    this._destroyedResolve = null

    for (const m of messages) this.addMessage(m)
  }

  get drained() {
    return this._mux.drained
  }

  fullyOpened() {
    if (this.opened) return Promise.resolve(true)
    if (this.closed) return Promise.resolve(false)
    if (this._openedPromise) return this._openedPromise

    this._openedPromise = new Promise((resolve) => {
      this._openedResolve = resolve
    })
    return this._openedPromise
  }

  fullyClosed() {
    if (this.destroyed) return Promise.resolve()
    if (this._destroyedPromise) return this._destroyedPromise

    this._destroyedPromise = new Promise((resolve) => {
      this._destroyedResolve = resolve
    })
    return this._destroyedPromise
  }

  open(handshake) {
    const id = this._mux._free.length > 0 ? this._mux._free.pop() : this._mux._local.push(null) - 1

    this._info.opened++
    this._info.lastChannel = this
    this._localId = id + 1
    this._mux._local[id] = this

    if (this._remoteId === 0) {
      this._info.outgoing.push(this._localId)
    }

    const state = { buffer: null, start: 2, end: 2 }

    c.uint.preencode(state, this._localId)
    c.string.preencode(state, this.protocol)
    c.optionalBuffer.preencode(state, this.id)
    if (this._handshake) this._handshake.preencode(state, handshake)

    state.buffer = this._mux._alloc(state.end)

    state.buffer[0] = 0
    state.buffer[1] = 1
    c.uint.encode(state, this._localId)
    c.string.encode(state, this.protocol)
    c.optionalBuffer.encode(state, this.id)
    if (this._handshake) this._handshake.encode(state, handshake)

    this._mux._write0(state.buffer)
  }

  _dec() {
    if (--this._active === 0 && this.closed === true) this._destroy()
  }

  _decAndDestroy(err) {
    this._dec()
    this._mux._safeDestroy(err)
  }

  _fullyOpenSoon() {
    this._mux._remote[this._remoteId - 1].session = this
    queueTick(this._fullyOpenOrDestroy.bind(this))
  }

  _fullyOpenOrDestroy() {
    try {
      this._fullyOpen()
    } catch (err) {
      this._mux._safeDestroyBound(err)
    }
  }

  _fullyOpen() {
    if (this.opened === true || this.closed === true) return

    const remote = this._mux._remote[this._remoteId - 1]

    this.handshake = this._handshake ? this._handshake.decode(remote.state) : null
    this._track(this.onopen(this.handshake, this))

    remote.session = this
    remote.state = null
    if (remote.pending !== null) this._drain(remote)
    if (this._mux._destroying === true) return

    this.opened = true
    this._resolveOpen(true)
  }

  _resolveOpen(opened) {
    if (this._openedResolve !== null) {
      this._openedResolve(opened)
      this._openedResolve = this._openedPromise = null
    }
  }

  _resolveDestroyed() {
    if (this._destroyedResolve !== null) {
      this._destroyedResolve()
      this._destroyedResolve = this._destroyedPromise = null
    }
  }

  _drain(remote) {
    for (let i = 0; i < remote.pending.length; i++) {
      const p = remote.pending[i]
      this._mux._buffered -= byteSize(p.state)
      this._recv(p.type, p.state)
      if (this._mux._destroying === true) return
    }

    remote.pending = null
    this._mux._resumeMaybe()
  }

  _track(p) {
    if (isPromise(p) === true) {
      this._active++
      return p.then(this._decBound, this._decAndDestroyBound)
    }

    return null
  }

  _close(isRemote) {
    if (this.closed === true) return
    this.closed = true

    this._info.opened--
    if (this._info.lastChannel === this) this._info.lastChannel = null

    if (this._remoteId > 0) {
      this._mux._remote[this._remoteId - 1] = null
      this._remoteId = 0
      // If remote has acked, we can reuse the local id now
      // otherwise, we need to wait for the "ack" to arrive
      this._mux._free.push(this._localId - 1)
    }

    this._mux._local[this._localId - 1] = null
    this._localId = 0

    this._mux._gc(this._info)
    this._track(this.onclose(isRemote, this))

    if (this._active === 0) this._destroy()

    this._resolveOpen(false)
  }

  _destroy() {
    if (this.destroyed === true) return
    this.destroyed = true
    this._track(this.ondestroy(this))
    this._resolveDestroyed()
  }

  _recv(type, state) {
    if (type < this.messages.length) {
      const m = this.messages[type]
      const p = m.recv(state, this)
      if (m.autoBatch === true) return p
    }
    return null
  }

  cork() {
    this._mux.cork()
  }

  uncork() {
    this._mux.uncork()
  }

  close() {
    if (this.closed === true) return

    const state = { buffer: null, start: 2, end: 2 }

    c.uint.preencode(state, this._localId)

    state.buffer = this._mux._alloc(state.end)

    state.buffer[0] = 0
    state.buffer[1] = 3
    c.uint.encode(state, this._localId)

    this._close(false)
    this._mux._write0(state.buffer)
  }

  addMessage(opts) {
    if (!opts) return this._skipMessage()

    const type = this.messages.length
    const autoBatch = opts.autoBatch !== false
    const encoding = opts.encoding || c.raw
    const onmessage = opts.onmessage || noop

    const s = this
    const typeLen = encodingLength(c.uint, type)

    const m = {
      type,
      autoBatch,
      encoding,
      onmessage,
      recv(state, session) {
        return session._track(m.onmessage(encoding.decode(state), session))
      },
      send(m, session = s) {
        if (session.closed === true) return false

        const mux = session._mux
        const state = { buffer: null, start: 0, end: typeLen }

        if (mux._batch !== null) {
          encoding.preencode(state, m)
          state.buffer = mux._alloc(state.end)

          c.uint.encode(state, type)
          encoding.encode(state, m)

          mux._pushBatch(session._localId, state.buffer)
          return true
        }

        c.uint.preencode(state, session._localId)
        encoding.preencode(state, m)

        state.buffer = mux._alloc(state.end)

        c.uint.encode(state, session._localId)
        c.uint.encode(state, type)
        encoding.encode(state, m)

        mux.drained = mux.stream.write(state.buffer)

        return mux.drained
      }
    }

    this.messages.push(m)

    return m
  }

  _skipMessage() {
    const type = this.messages.length
    const m = {
      type,
      encoding: c.raw,
      onmessage: noop,
      recv(state, session) {},
      send(m, session) {}
    }

    this.messages.push(m)
    return m
  }
}

module.exports = class Protomux {
  constructor(stream, { alloc } = {}) {
    if (stream.userData === null) stream.userData = this

    this.isProtomux = true
    this.stream = stream
    this.corked = 0
    this.drained = true

    this._alloc =
      alloc || (typeof stream.alloc === 'function' ? stream.alloc.bind(stream) : b4a.allocUnsafe)
    this._safeDestroyBound = this._safeDestroy.bind(this)
    this._uncorkBound = this.uncork.bind(this)

    this._remoteBacklog = 0
    this._buffered = 0
    this._paused = false
    this._remote = []
    this._local = []
    this._free = []
    this._batch = null
    this._batchState = null

    this._infos = new Map()
    this._notify = new Map()
    // stream.destroyed flips asynchronously on streamx-based transports.
    this._destroying = false

    this.stream.on('data', this._ondata.bind(this))
    this.stream.on('drain', this._ondrain.bind(this))
    this.stream.on('end', this._onend.bind(this))
    this.stream.on('error', noop) // we handle this in "close"
    this.stream.on('close', this._shutdown.bind(this))
  }

  static from(stream, opts) {
    if (stream.userData && stream.userData.isProtomux) return stream.userData
    if (stream.isProtomux) return stream
    return new this(stream, opts)
  }

  static isProtomux(mux) {
    return typeof mux === 'object' && mux.isProtomux === true
  }

  *[Symbol.iterator]() {
    for (const session of this._local) {
      if (session !== null) yield session
    }
  }

  isIdle() {
    return this._local.length === this._free.length
  }

  cork() {
    if (++this.corked === 1) {
      this._batch = []
      this._batchState = { buffer: null, start: 0, end: 1 }
    }
  }

  uncork() {
    if (--this.corked === 0) {
      this._sendBatch(this._batch, this._batchState)
      this._batch = null
      this._batchState = null
    }
  }

  getLastChannel({ protocol, id = null }) {
    const key = toKey(protocol, id)
    const info = this._infos.get(key)
    if (info) return info.lastChannel
    return null
  }

  pair({ protocol, id = null }, notify) {
    this._notify.set(toKey(protocol, id), notify)
  }

  unpair({ protocol, id = null }) {
    this._notify.delete(toKey(protocol, id))
  }

  opened({ protocol, id = null }) {
    const key = toKey(protocol, id)
    const info = this._infos.get(key)
    return info ? info.opened > 0 : false
  }

  createChannel({
    userData = null,
    protocol,
    aliases = [],
    id = null,
    unique = true,
    handshake = null,
    messages = [],
    onopen = noop,
    onclose = noop,
    ondestroy = noop,
    ondrain = noop
  }) {
    if (this.stream.destroyed) return null

    const info = this._get(protocol, id, aliases)
    if (unique && info.opened > 0) return null

    if (info.incoming.length === 0) {
      return new Channel(
        this,
        info,
        userData,
        protocol,
        aliases,
        id,
        handshake,
        messages,
        onopen,
        onclose,
        ondestroy,
        ondrain
      )
    }

    this._remoteBacklog--

    const remoteId = info.incoming.shift()
    const r = this._remote[remoteId - 1]
    if (r === null) return null

    const session = new Channel(
      this,
      info,
      userData,
      protocol,
      aliases,
      id,
      handshake,
      messages,
      onopen,
      onclose,
      ondestroy,
      ondrain
    )

    session._remoteId = remoteId
    session._fullyOpenSoon()

    return session
  }

  _pushBatch(localId, buffer) {
    if (this._batchState.end >= MAX_BATCH) {
      this._sendBatch(this._batch, this._batchState)
      this._batch = []
      this._batchState = { buffer: null, start: 0, end: 1 }
    }

    if (this._batch.length === 0 || this._batch[this._batch.length - 1].localId !== localId) {
      this._batchState.end++
      c.uint.preencode(this._batchState, localId)
    }
    c.buffer.preencode(this._batchState, buffer)
    this._batch.push({ localId, buffer })
  }

  _sendBatch(batch, state) {
    if (batch.length === 0) return

    let prev = batch[0].localId

    state.buffer = this._alloc(state.end)
    state.buffer[state.start++] = 0
    state.buffer[state.start++] = 0

    c.uint.encode(state, prev)

    for (let i = 0; i < batch.length; i++) {
      const b = batch[i]
      if (prev !== b.localId) {
        state.buffer[state.start++] = 0
        c.uint.encode(state, (prev = b.localId))
      }
      c.buffer.encode(state, b.buffer)
    }

    this.drained = this.stream.write(state.buffer)
  }

  _get(protocol, id, aliases = []) {
    const key = toKey(protocol, id)

    let info = this._infos.get(key)
    if (info) return info

    info = {
      key,
      protocol,
      aliases: [],
      id,
      pairing: 0,
      opened: 0,
      incoming: [],
      outgoing: [],
      lastChannel: null
    }
    this._infos.set(key, info)

    for (const alias of aliases) {
      const key = toKey(alias, id)
      info.aliases.push(key)

      this._infos.set(key, info)
    }

    return info
  }

  _gc(info) {
    if (info.opened === 0 && info.outgoing.length === 0 && info.incoming.length === 0) {
      this._infos.delete(info.key)

      for (const alias of info.aliases) this._infos.delete(alias)
    }
  }

  _ondata(buffer) {
    if (buffer.byteLength === 0) return // ignore empty frames...
    try {
      const state = { buffer, start: 0, end: buffer.byteLength }
      this._decode(c.uint.decode(state), state)
    } catch (err) {
      this._safeDestroy(err)
    }
  }

  _ondrain() {
    this.drained = true

    for (const s of this._local) {
      if (s !== null) s._track(s.ondrain(s))
    }
  }

  _onend() {
    // TODO: support half open mode for the users who wants that here
    this.stream.end()
  }

  _decode(remoteId, state) {
    const type = c.uint.decode(state)

    if (remoteId === 0) {
      return this._oncontrolsession(type, state)
    }

    const r = remoteId <= this._remote.length ? this._remote[remoteId - 1] : null

    // if the channel is closed ignore - could just be a pipeline message...
    if (r === null) return null

    if (r.pending !== null) {
      this._bufferMessage(r, type, state)
      return null
    }

    return r.session._recv(type, state)
  }

  _oncontrolsession(type, state) {
    switch (type) {
      case 0:
        this._onbatch(state)
        break

      case 1:
        // return the promise back up as this has sideeffects so we can batch reply
        return this._onopensession(state)

      case 2:
        this._onrejectsession(state)
        break

      case 3:
        this._onclosesession(state)
        break
    }

    return null
  }

  _bufferMessage(r, type, { buffer, start, end }) {
    const state = { buffer, start, end } // copy
    r.pending.push({ type, state })
    this._buffered += byteSize(state)
    this._pauseMaybe()
  }

  _pauseMaybe() {
    if (this._paused === true || this._buffered <= MAX_BUFFERED) return
    this._paused = true
    this.stream.pause()
  }

  _resumeMaybe() {
    if (this._paused === false || this._buffered > MAX_BUFFERED) return
    this._paused = false
    this.stream.resume()
  }

  _onbatch(state) {
    const end = state.end
    let remoteId = c.uint.decode(state)

    let waiting = null

    while (state.end > state.start) {
      const len = c.uint.decode(state)
      if (len === 0) {
        remoteId = c.uint.decode(state)
        continue
      }
      state.end = state.start + len
      // if batch contains more than one message, cork it so we reply back with a batch
      if (end !== state.end && waiting === null) {
        waiting = []
        this.cork()
      }
      const p = this._decode(remoteId, state)
      if (waiting !== null && p !== null) waiting.push(p)
      state.start = state.end
      state.end = end
    }

    if (waiting !== null) {
      // the waiting promises are not allowed to throw but we destroy the stream in case we are wrong
      Promise.all(waiting).then(this._uncorkBound, this._safeDestroyBound)
    }
  }

  _onopensession(state) {
    const remoteId = c.uint.decode(state)
    const protocol = c.string.decode(state)
    const id = unslab(c.optionalBuffer.decode(state))

    // remote tried to open the control session - auto reject for now
    // as we can use as an explicit control protocol declaration if we need to
    if (remoteId === 0) {
      this._rejectSession(0)
      return null
    }

    const rid = remoteId - 1
    const info = this._get(protocol, id)

    // allow the remote to grow the ids by one
    if (this._remote.length === rid) {
      this._remote.push(null)
    }

    if (rid >= this._remote.length || this._remote[rid] !== null) {
      throw new Error('Invalid open message')
    }

    if (info.outgoing.length > 0) {
      const localId = info.outgoing.shift()
      const session = this._local[localId - 1]

      if (session === null) {
        // we already closed the channel - ignore
        this._free.push(localId - 1)
        return null
      }

      this._remote[rid] = { state, pending: null, session: null }

      session._remoteId = remoteId
      session._fullyOpen()
      return null
    }

    const copyState = { buffer: state.buffer, start: state.start, end: state.end }
    this._remote[rid] = { state: copyState, pending: [], session: null }

    if (++this._remoteBacklog > MAX_BACKLOG) {
      throw new Error('Remote exceeded backlog')
    }

    info.pairing++
    info.incoming.push(remoteId)

    return this._requestSession(protocol, id, info).catch(this._safeDestroyBound)
  }

  _onrejectsession(state) {
    const localId = c.uint.decode(state)

    // TODO: can be done smarter...
    for (const info of this._infos.values()) {
      const i = info.outgoing.indexOf(localId)
      if (i === -1) continue

      info.outgoing.splice(i, 1)

      const session = this._local[localId - 1]

      this._free.push(localId - 1)
      if (session !== null) session._close(true)

      this._gc(info)
      return
    }

    throw new Error('Invalid reject message')
  }

  _onclosesession(state) {
    const remoteId = c.uint.decode(state)

    if (remoteId === 0) return // ignore

    const rid = remoteId - 1
    const r = rid < this._remote.length ? this._remote[rid] : null

    if (r === null) return

    if (r.session !== null) r.session._close(true)
  }

  async _requestSession(protocol, id, info) {
    const notify = this._notify.get(toKey(protocol, id)) || this._notify.get(toKey(protocol, null))

    if (notify) await notify(id)

    if (--info.pairing > 0) return

    while (info.incoming.length > 0) {
      this._rejectSession(info, info.incoming.shift())
    }

    this._gc(info)
  }

  _rejectSession(info, remoteId) {
    if (remoteId > 0) {
      const r = this._remote[remoteId - 1]

      if (r.pending !== null) {
        for (let i = 0; i < r.pending.length; i++) {
          this._buffered -= byteSize(r.pending[i].state)
        }
      }

      this._remote[remoteId - 1] = null
      this._resumeMaybe()
    }

    const state = { buffer: null, start: 2, end: 2 }

    c.uint.preencode(state, remoteId)

    state.buffer = this._alloc(state.end)

    state.buffer[0] = 0
    state.buffer[1] = 2
    c.uint.encode(state, remoteId)

    this._write0(state.buffer)
  }

  _write0(buffer) {
    if (this._batch !== null) {
      this._pushBatch(0, buffer.subarray(1))
      return
    }

    this.drained = this.stream.write(buffer)
  }

  destroy(err) {
    this._destroying = true
    this.stream.destroy(err)
  }

  _safeDestroy(err) {
    safetyCatch(err)
    this._destroying = true
    this.stream.destroy(err)
  }

  _shutdown() {
    this._destroying = true
    for (const s of this._local) {
      if (s !== null) s._close(true)
    }
  }
}

function noop() {}

function toKey(protocol, id) {
  return protocol + '##' + (id ? b4a.toString(id, 'hex') : '')
}

function byteSize(state) {
  return 512 + (state.end - state.start)
}

function isPromise(p) {
  return !!(p && typeof p.then === 'function')
}

function encodingLength(enc, val) {
  const state = { buffer: null, start: 0, end: 0 }
  enc.preencode(state, val)
  return state.end
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "protomux",
  "version": "3.11.0",
  "description": "Multiplex multiple message oriented protocols over a stream",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.3.1",
    "compact-encoding": "^3.0.0",
    "queue-tick": "^1.0.0",
    "safety-catch": "^1.0.1",
    "unslab": "^1.3.0"
  },
  "devDependencies": {
    "@hyperswarm/secret-stream": "^6.0.0",
    "brittle": "^3.0.0",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/protomux.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/protomux/issues"
  },
  "homepage": "https://github.com/holepunchto/protomux"
}
{
  "name": "queue-tick",
  "version": "1.0.1",
  "description": "Next tick shim that prefers process.nextTick over queueMicrotask for compat",
  "main": "./process-next-tick.js",
  "browser": "./queue-microtask.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^16.0.3",
    "tape": "^5.3.1"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/queue-tick.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/queue-tick/issues"
  },
  "homepage": "https://github.com/mafintosh/queue-tick"
}
module.exports = (typeof process !== 'undefined' && typeof process.nextTick === 'function')
  ? process.nextTick.bind(process)
  : require('./queue-microtask')
module.exports = typeof queueMicrotask === 'function' ? queueMicrotask : (fn) => Promise.resolve().then(fn)
require.addon = require('require-addon')

module.exports = require.addon('.', __filename)
const binding = require('./binding')

exports.get = function get(field, bit) {
  const n = field.byteLength * 8

  if (bit < 0) bit += n
  if (bit < 0 || bit >= n) return false

  return binding.quickbit_napi_get(toBuffer(field), bit) !== 0
}

exports.set = function set(field, bit, value = true) {
  const n = field.byteLength * 8

  if (bit < 0) bit += n
  if (bit < 0 || bit >= n) return false

  return binding.quickbit_napi_set(toBuffer(field), bit, value ? 1 : 0) !== 0
}

exports.fill = function fill(
  field,
  value,
  start = 0,
  end = field.byteLength * 8
) {
  const n = field.byteLength * 8

  if (start < 0) start += n
  if (end < 0) end += n
  if (start < 0 || start >= field.byteLength * 8 || start >= end) return field

  binding.quickbit_napi_fill(toBuffer(field), value ? 1 : 0, start, end)
  return field
}

exports.clear = function clear(field, ...chunks) {
  binding.quickbit_napi_clear(toBuffer(field), chunks.map(toBufferChunk))
}

exports.findFirst = function findFirst(field, value, position = 0) {
  const n = field.byteLength * 8

  if (position < 0) position += n
  if (position < 0) position = 0
  if (position >= n) return -1

  return binding.quickbit_napi_find_first(
    toBuffer(field),
    value ? 1 : 0,
    position
  )
}

exports.findLast = function findLast(
  field,
  value,
  position = field.byteLength * 8 - 1
) {
  const n = field.byteLength * 8

  if (position < 0) position += n
  if (position < 0) return -1
  if (position >= n) position = n - 1

  return binding.quickbit_napi_find_last(
    toBuffer(field),
    value ? 1 : 0,
    position
  )
}

function toBuffer(field) {
  if (field.BYTES_PER_ELEMENT === 1) return field
  return new Uint8Array(field.buffer, field.byteOffset, field.byteLength)
}

function toBufferChunk(chunk) {
  return { field: toBuffer(chunk.field), offset: chunk.offset }
}

class Index {
  static from(fieldOrChunks, byteLength = -1) {
    if (Array.isArray(fieldOrChunks)) {
      return new SparseIndex(fieldOrChunks, byteLength)
    } else {
      return new DenseIndex(fieldOrChunks, byteLength)
    }
  }

  constructor(byteLength) {
    this._byteLength = byteLength
    this.handle = Buffer.allocUnsafe(binding.sizeof_quickbit_index_t)
  }

  get byteLength() {
    return this._byteLength
  }

  skipFirst(value, position = 0) {
    const n = this.byteLength * 8

    if (position < 0) position += n
    if (position < 0) position = 0
    if (position >= n) return n - 1

    return binding.quickbit_napi_skip_first(
      this.handle,
      this.byteLength,
      value ? 1 : 0,
      position
    )
  }

  skipLast(value, position = this.byteLength * 8 - 1) {
    const n = this.byteLength * 8

    if (position < 0) position += n
    if (position < 0) return 0
    if (position >= n) position = n - 1

    return binding.quickbit_napi_skip_last(
      this.handle,
      this.byteLength,
      value ? 1 : 0,
      position
    )
  }
}

exports.Index = Index

class DenseIndex extends Index {
  constructor(field, byteLength) {
    super(byteLength)
    this.field = field

    binding.quickbit_napi_index_init(this.handle, toBuffer(this.field))
  }

  get byteLength() {
    if (this._byteLength !== -1) return this._byteLength
    return this.field.byteLength
  }

  update(bit) {
    const n = this.byteLength * 8

    if (bit < 0) bit += n
    if (bit < 0 || bit >= n) return false

    return (
      binding.quickbit_napi_index_update(
        this.handle,
        toBuffer(this.field),
        bit
      ) !== 0
    )
  }
}

function selectChunk(chunks, offset) {
  for (let i = 0; i < chunks.length; i++) {
    const next = chunks[i]

    const start = next.offset
    const end = next.offset + next.field.byteLength

    if (offset >= start && offset + 16 <= end) {
      return next
    }
  }

  return null
}

class SparseIndex extends Index {
  constructor(chunks, byteLength) {
    super(byteLength)
    this.chunks = chunks

    binding.quickbit_napi_index_init_sparse(
      this.handle,
      this.chunks.map(toBufferChunk)
    )
  }

  get byteLength() {
    if (this._byteLength !== -1) return this._byteLength
    const last = this.chunks[this.chunks.length - 1]
    return last ? last.offset + last.field.byteLength : 0
  }

  update(bit) {
    const n = this.byteLength * 8

    if (bit < 0) bit += n
    if (bit < 0 || bit >= n) return false

    const j = Math.floor(bit / 128)

    const offset = j * 16

    const chunk = selectChunk(this.chunks, offset)

    if (chunk === null) return false

    return (
      binding.quickbit_napi_index_update_sparse(
        this.handle,
        toBuffer(chunk.field),
        chunk.offset,
        bit
      ) !== 0
    )
  }
}
{
  "name": "quickbit-native",
  "version": "2.4.8",
  "description": "libquickbit JavaScript bindings for Node.js",
  "main": "index.js",
  "files": [
    "index.js",
    "macros.h",
    "binding.cc",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "npm run lint && npm run test:bare && npm run test:node",
    "test:bare": "bare test.mjs",
    "test:node": "node test.mjs",
    "lint": "prettier . --check"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/quickbit-native.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/quickbit-native/issues"
  },
  "homepage": "https://github.com/holepunchto/quickbit-native#readme",
  "dependencies": {
    "require-addon": "^1.1.0"
  },
  "devDependencies": {
    "b4a": "^1.6.7",
    "bare-compat-napi": "^1.3.2",
    "brittle": "^3.1.0",
    "cmake-bare": "^1.1.7",
    "cmake-fetch": "^1.1.0",
    "cmake-napi": "^1.0.2",
    "prettier": "^3.5.3",
    "prettier-config-standard": "^7.0.0"
  }
}
const simdle = require('simdle-universal')

const INDEX_LEN = (16 /* root */ + 128 * 16 /* children */) * 2

const get = exports.get = function get (field, bit) {
  const n = field.byteLength * 8

  if (bit < 0) bit += n
  if (bit < 0 || bit >= n) return false

  const m = field.BYTES_PER_ELEMENT * 8

  const offset = bit & (m - 1)
  const i = (bit - offset) / m

  return (field[i] & (1 << offset)) !== 0
}

const set = exports.set = function set (field, bit, value = true) {
  const n = field.byteLength * 8

  if (bit < 0) bit += n
  if (bit < 0 || bit >= n) return false

  const m = field.BYTES_PER_ELEMENT * 8

  const offset = bit & (m - 1)
  const i = (bit - offset) / m
  const mask = 1 << offset

  if (value) {
    if ((field[i] & mask) !== 0) return false
  } else {
    if ((field[i] & mask) === 0) return false
  }

  field[i] ^= mask

  return true
}

exports.fill = function fill (field, value, start = 0, end = field.byteLength * 8) {
  const n = field.byteLength * 8

  if (start < 0) start += n
  if (end < 0) end += n
  if (start < 0 || start >= field.byteLength * 8 || start >= end) return field

  const m = field.BYTES_PER_ELEMENT * 8

  let i, j

  {
    const offset = start & (m - 1)
    i = (start - offset) / m

    if (offset !== 0) {
      let shift = m - offset
      if (end - start < shift) shift = end - start

      const mask = ((1 << shift) - 1) << offset

      if (value) field[i] |= mask
      else field[i] &= ~mask

      i++
    }
  }

  {
    const offset = end & (m - 1)
    j = (end - offset) / m

    if (offset !== 0 && j >= i) {
      const mask = (1 << offset) - 1

      if (value) field[j] |= mask
      else field[j] &= ~mask
    }
  }

  if (i < j) field.fill(value ? (2 ** m) - 1 : 0, i, j)

  return field
}

exports.clear = function clear (field, ...chunks) {
  const n = field.byteLength

  for (const chunk of chunks) {
    if (chunk.offset >= n) continue

    const m = chunk.field.byteLength

    let i = chunk.offset
    let j = 0

    while (((i & 15) !== 0 || (j & 15) !== 0) && i < n && j < m) {
      field[i] = field[i] & ~chunk.field[j]
      i++
      j++
    }

    if (i + 15 < n && j + 15 < m) {
      const len = Math.min(n - (n & 15) - i, m - (m & 15) - j)

      simdle.clear(field.subarray(i, i + len), chunk.field.subarray(j, j + len), field.subarray(i, i + len))
    }

    while (i < n && j < m) {
      field[i] = field[i] & ~chunk.field[j]
      i++
      j++
    }
  }
}

function bitOffset (bit, offset) {
  return !bit ? offset : (INDEX_LEN * 8 / 2) + offset
}

function byteOffset (bit, offset) {
  return !bit ? offset : (INDEX_LEN / 2) + offset
}

exports.findFirst = function findFirst (field, value, position = 0) {
  const n = field.byteLength * 8

  if (position < 0) position += n
  if (position < 0) position = 0
  if (position >= n) return -1

  value = !!value

  for (let i = position; i < n; i++) {
    if (get(field, i) === value) return i
  }

  return -1
}

exports.findLast = function findLast (field, value, position = field.byteLength * 8 - 1) {
  const n = field.byteLength * 8

  if (position < 0) position += n
  if (position < 0) return -1
  if (position >= n) position = n - 1

  value = !!value

  for (let i = position; i >= 0; i--) {
    if (get(field, i) === value) return i
  }

  return -1
}

const Index = exports.Index = class Index {
  static from (fieldOrChunks, byteLength = -1) {
    if (Array.isArray(fieldOrChunks)) {
      return new SparseIndex(fieldOrChunks, byteLength)
    } else {
      return new DenseIndex(fieldOrChunks, byteLength)
    }
  }

  constructor (byteLength) {
    this._byteLength = byteLength
    this.handle = new Uint32Array(INDEX_LEN / 4)
  }

  get byteLength () {
    return this._byteLength
  }

  skipFirst (value, position = 0) {
    const n = this.byteLength * 8

    if (position < 0) position += n
    if (position < 0) position = 0
    if (position >= n) return n - 1

    let i = Math.floor(position / 16384)

    if (i > 127) return position

    while (i <= 127 && get(this.handle, bitOffset(value, i))) {
      i++
    }

    if (i === 128) return n - 1

    let k = i * 16384
    let j = 0

    if (position > k) j = Math.floor((position - k) / 128)

    while (j <= 127 && get(this.handle, bitOffset(value, i * 128 + j + 128))) {
      j++
      k += 128
    }

    if (j === 128 && i !== 127) return this.skipFirst(value, (i + 1) * 16384)

    if (k > position) position = k

    return position < n ? position : n - 1
  }

  skipLast (value, position = this.byteLength * 8 - 1) {
    const n = this.byteLength * 8

    if (position < 0) position += n
    if (position < 0) return 0
    if (position >= n) position = n - 1

    let i = Math.floor(position / 16384)

    if (i > 127) return position

    while (i >= 0 && get(this.handle, bitOffset(value, i))) {
      i--
    }

    if (i === -1) return 0

    let k = ((i + 1) * 16384) - 1
    let j = 127

    if (position < k) j = 128 - Math.ceil((k - position) / 128)

    while (j >= 0 && get(this.handle, bitOffset(value, i * 128 + j + 128))) {
      j--
      k -= 128
    }

    if (j === -1 && i !== 0) return this.skipLast(value, i * 16384 - 1)

    if (k < position) position = k

    return position
  }
}

class DenseIndex extends Index {
  constructor (field, byteLength) {
    super(byteLength)
    this.field = field

    const m = field.BYTES_PER_ELEMENT

    for (let i = 0; i < 128; i++) {
      for (let j = 0; j < 128; j++) {
        const offset = (i * 128 + j) * 16
        let allz = true
        let allo = false

        if (offset + 16 <= this.field.byteLength) {
          const vec = this.field.subarray(offset / m, (offset + 16) / m)

          allz = simdle.allz(vec)
          allo = simdle.allo(vec)
        }

        const k = i * 128 + 128 + j

        set(this.handle, bitOffset(false, k), allz)
        set(this.handle, bitOffset(true, k), allo)
      }

      {
        const offset = byteOffset(false, i * 16 + 16) / 4
        const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

        set(this.handle, bitOffset(false, i), allo)
      }

      {
        const offset = byteOffset(true, i * 16 + 16) / 4
        const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

        set(this.handle, bitOffset(true, i), allo)
      }
    }
  }

  get byteLength () {
    if (this._byteLength !== -1) return this._byteLength
    return this.field.byteLength
  }

  update (bit) {
    const n = this.byteLength * 8

    if (bit < 0) bit += n
    if (bit < 0 || bit >= n) return false

    const m = this.field.BYTES_PER_ELEMENT

    const i = Math.floor(bit / 16384)
    const j = Math.floor(bit / 128)

    const offset = (j * 16) / m
    const vec = this.field.subarray(offset, offset + (16 / m))

    const allz = simdle.allz(vec)
    const allo = simdle.allo(vec)

    let changed = false

    if (set(this.handle, bitOffset(false, 128 + j), allz)) {
      changed = true

      const offset = byteOffset(false, i * 16 + 16) / 4
      const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

      set(this.handle, bitOffset(false, i), allo)
    }

    if (set(this.handle, bitOffset(true, 128 + j), allo)) {
      changed = true

      const offset = byteOffset(true, i * 16 + 16) / 4
      const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

      set(this.handle, bitOffset(true, i), allo)
    }

    return changed
  }
}

function selectChunk (chunks, offset) {
  for (let i = 0; i < chunks.length; i++) {
    const next = chunks[i]

    const start = next.offset
    const end = next.offset + next.field.byteLength

    if (offset >= start && offset + 16 <= end) {
      return next
    }
  }

  return null
}

class SparseIndex extends Index {
  constructor (chunks, byteLength) {
    super(byteLength)
    this.chunks = chunks

    for (let i = 0; i < 128; i++) {
      for (let j = 0; j < 128; j++) {
        const offset = (i * 128 + j) * 16
        let allz = true
        let allo = false

        const chunk = selectChunk(this.chunks, offset)

        if (chunk !== null) {
          const m = chunk.field.BYTES_PER_ELEMENT

          const vec = chunk.field.subarray((offset - chunk.offset) / m, (offset - chunk.offset + 16) / m)

          allz = simdle.allz(vec)
          allo = simdle.allo(vec)
        }

        const k = i * 128 + 128 + j

        set(this.handle, bitOffset(false, k), allz)
        set(this.handle, bitOffset(true, k), allo)
      }

      {
        const offset = byteOffset(false, i * 16 + 16) / 4
        const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

        set(this.handle, bitOffset(false, i), allo)
      }

      {
        const offset = byteOffset(true, i * 16 + 16) / 4
        const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

        set(this.handle, bitOffset(true, i), allo)
      }
    }
  }

  get byteLength () {
    if (this._byteLength !== -1) return this._byteLength
    const last = this.chunks[this.chunks.length - 1]
    return last ? last.offset + last.field.byteLength : 0
  }

  update (bit) {
    const n = this.byteLength * 8

    if (bit < 0) bit += n
    if (bit < 0 || bit >= n) return false

    const i = Math.floor(bit / 16384)
    const j = Math.floor(bit / 128)

    const offset = j * 16

    const chunk = selectChunk(this.chunks, offset)

    if (chunk === null) return false

    const m = chunk.field.BYTES_PER_ELEMENT

    const vec = chunk.field.subarray((offset - chunk.offset) / m, (offset - chunk.offset + 16) / m)

    const allz = simdle.allz(vec)
    const allo = simdle.allo(vec)

    let changed = false

    if (set(this.handle, bitOffset(false, 128 + j), allz)) {
      changed = true

      const offset = byteOffset(false, i * 16 + 16) / 4
      const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

      set(this.handle, bitOffset(false, i), allo)
    }

    if (set(this.handle, bitOffset(true, 128 + j), allo)) {
      changed = true

      const offset = byteOffset(true, i * 16 + 16) / 4
      const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

      set(this.handle, bitOffset(true, i), allo)
    }

    return changed
  }
}
const fallback = require('./fallback')

try {
  const native = require('quickbit-native')

  // These functions are faster in JavaScript
  exports.get = fallback.get
  exports.set = fallback.set
  exports.fill = fallback.fill

  // These functions are faster in C
  exports.clear = native.clear
  exports.findFirst = native.findFirst
  exports.findLast = native.findLast
  exports.Index = native.Index
} catch {
  module.exports = fallback
}
{
  "name": "quickbit-universal",
  "version": "2.2.0",
  "description": "Universal wrapper for libquickbit with a JavaScript fallback",
  "main": "index.js",
  "files": [
    "fallback.js",
    "index.js"
  ],
  "browser": {
    "./index.js": "./fallback.js"
  },
  "scripts": {
    "test": "standard && brittle test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/quickbit-universal.git"
  },
  "author": "Kasper Isager Dalsgarð <kasper@funktionel.co>",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/holepunchto/quickbit-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/quickbit-universal#readme",
  "dependencies": {
    "b4a": "^1.6.0",
    "simdle-universal": "^1.1.0"
  },
  "optionalDependencies": {
    "quickbit-native": "^2.2.0"
  },
  "devDependencies": {
    "brittle": "^3.1.0",
    "standard": "^17.0.0"
  }
}
class CacheEntry {
  constructor (key, index, map) {
    this.key = key
    this.index = index
    this.map = map
  }
}

class CacheValue {
  constructor (entry, value) {
    this.entry = entry
    this.value = value
  }
}

class Rache {
  constructor ({ maxSize = 65536, parent = null } = {}) {
    this.maxSize = parent?.maxSize || maxSize

    this._array = parent?._array || []
    this._map = new Map()
  }

  static from (cache) {
    return cache ? new this({ parent: cache }) : new this()
  }

  get globalSize () {
    return this._array.length
  }

  get size () {
    return this._map.size
  }

  sub () {
    return new Rache({ parent: this })
  }

  set (key, value) { // ~constant time
    const existing = this._map.get(key)
    if (existing !== undefined) {
      existing.value = value
      return
    }

    if (this._array.length >= this.maxSize) this._gc()

    const entry = new CacheEntry(key, this._array.length, this._map)
    this._array.push(entry)
    const cacheValue = new CacheValue(entry, value)
    this._map.set(key, cacheValue)
  }

  delete (key) {
    const existing = this._map.get(key)
    if (existing === undefined) return false

    this._delete(existing.entry.index)
    return true
  }

  get (key) {
    const existing = this._map.get(key)
    return existing === undefined ? undefined : existing.value
  }

  * [Symbol.iterator] () {
    for (const [key, { value }] of this._map) {
      yield [key, value]
    }
  }

  keys () {
    return this._map.keys()
  }

  * values () {
    for (const { value } of this._map.values()) {
      yield value
    }
  }

  clear () {
    // The entries in map linger on in _array,
    // so on top of clearing the map, we also kill the ref,
    // so that any gc running later on the old map won't interfere
    // (in case a new entry was added with the same key as a cleared entry)

    this._map.clear()
    this._map = new Map()
  }

  destroy () {
    this._map = null
    this._array = null
  }

  _gc () {
    this._delete(Math.floor(Math.random() * this._array.length))
  }

  _delete (index) { // ~constant time
    if (index >= this._array.length) throw new Error('Cannot delete unused index (logic bug?)')

    const head = this._array.pop()
    let removed = head

    if (index < this._array.length) {
      removed = this._array[index]
      head.index = index
      this._array[index] = head
    }

    removed.map.delete(removed.key)
  }
}

module.exports = Rache
{
  "name": "rache",
  "version": "1.0.0",
  "description": "Random-eviction cache",
  "main": "index.js",
  "scripts": {
    "test": "standard && brittle test.js --coverage"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/rache.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/rache/issues"
  },
  "homepage": "https://github.com/holepunchto/rache#readme",
  "files": [
    "index.js"
  ],
  "dependencies": {},
  "devDependencies": {
    "brittle": "^3.5.2",
    "standard": "^17.1.0"
  }
}
module.exports = class RandomArrayIterator {
  constructor (values) {
    this.values = values
    this.start = 0
    this.length = this.values.length
  }

  next () {
    if (this.length === 0) {
      if (this.start === 0) return { done: true, value: undefined }
      this.length = this.start
      this.start = 0
    }

    const i = this.start + ((Math.random() * this.length) | 0)
    const j = this.start + --this.length
    const value = this.values[i]

    this.values[i] = this.values[j]
    this.values[j] = value

    return { done: false, value }
  }

  dequeue () {
    this.values[this.start + this.length] = this.values[this.values.length - 1]
    this.values.pop()
  }

  requeue () {
    const i = this.start + this.length
    const value = this.values[i]
    this.values[i] = this.values[this.start]
    this.values[this.start++] = value
  }

  restart () {
    this.start = 0
    this.length = this.values.length
    return this
  }

  [Symbol.iterator] () {
    return this
  }
}
{
  "name": "random-array-iterator",
  "version": "1.0.0",
  "description": "An iterator to iterate an array in random order with controls to requeue or dequeue elements during the iteration",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^16.0.3",
    "tape": "^5.0.1"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/random-array-iterator.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/random-array-iterator/issues"
  },
  "homepage": "https://github.com/mafintosh/random-array-iterator"
}
const EventEmitter = require('events')

module.exports = class ReadyResource extends EventEmitter {
  constructor () {
    super()

    this.opening = null
    this.closing = null

    this.opened = false
    this.closed = false
  }

  ready () {
    if (this.opening !== null) return this.opening
    this.opening = open(this)
    return this.opening
  }

  close () {
    if (this.closing !== null) return this.closing
    this.closing = close(this)
    return this.closing
  }

  async _open () {
    // add impl here
  }

  async _close () {
    // add impl here
  }
}

async function open (self) {
  // open after close
  if (self.closing !== null) return

  try {
    await self._open()
  } catch (err) {
    self.close() // safe to run in bg
    throw err
  }

  self.opened = true
  self.emit('ready')
}

async function close (self) {
  try {
    if (self.opened === false && self.opening !== null) await self.opening
  } catch {
    // ignore errors on closing
  }
  if (self.opened === true || self.opening === null) await self._close()
  self.closed = true
  self.emit('close')
}
{
  "name": "ready-resource",
  "version": "1.2.0",
  "description": "Modern single resource management",
  "main": "index.js",
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "types": "index.d.ts",
  "files": [
    "index.js",
    "index.d.ts"
  ],
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "devDependencies": {
    "brittle": "^3.1.0",
    "standard": "^17.0.0"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/ready-resource.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/ready-resource/issues"
  },
  "homepage": "https://github.com/holepunchto/ready-resource",
  "dependencies": {
    "bare-events": "^2.2.0"
  }
}
const b4a = require('b4a')

var EMPTY = []

module.exports = RecordCache

function RecordSet () {
  this.list = []
  this.map = new Map()
}

RecordSet.prototype.add = function (record, value) {
  var k = toString(record)
  var r = this.map.get(k)
  if (r) return false

  r = {index: this.list.length, record: value || record}
  this.list.push(r)
  this.map.set(k, r)
  return true
}

RecordSet.prototype.remove = function (record) {
  var k = toString(record)
  var r = this.map.get(k)
  if (!r) return false

  swap(this.list, r.index, this.list.length - 1)
  this.list.pop()
  this.map.delete(k)
  return true
}

function RecordStore () {
  this.records = new Map()
  this.size = 0
}

RecordStore.prototype.add = function (name, record, value) {
  var r = this.records.get(name)

  if (!r) {
    r = new RecordSet()
    this.records.set(name, r)
  }

  if (r.add(record, value)) {
    this.size++
    return true
  }

  return false
}

RecordStore.prototype.remove = function (name, record, value) {
  var r = this.records.get(name)
  if (!r) return false

  if (r.remove(record, value)) {
    this.size--
    if (!r.map.size) this.records.delete(name)
    return true
  }

  return false
}

RecordStore.prototype.get = function (name) {
  var r = this.records.get(name)
  return r ? r.list : EMPTY
}

function RecordCache (opts) {
  if (!(this instanceof RecordCache)) return new RecordCache(opts)
  if (!opts) opts = {}

  this.maxSize = opts.maxSize || Infinity
  this.maxAge = opts.maxAge || 0

  this._onstale = opts.onStale || opts.onstale || null
  this._fresh = new RecordStore()
  this._stale = new RecordStore()
  this._interval = null
  this._gced = false

  if (this.maxAge && this.maxAge < Infinity) {
    // 2/3 gives us a span of 0.66-1.33 maxAge or avg maxAge
    var tick = Math.ceil(2 / 3 * this.maxAge)
    this._interval = setInterval(this._gcAuto.bind(this), tick)
    if (this._interval.unref) this._interval.unref()
  }
}

Object.defineProperty(RecordCache.prototype, 'size', {
  get: function () {
    return this._fresh.size + this._stale.size
  }
})

RecordCache.prototype.add = function (name, record, value) {
  this._stale.remove(name, record, value)
  if (this._fresh.add(name, record, value) && this._fresh.size > this.maxSize) {
    this._gc()
  }
}

RecordCache.prototype.remove = function (name, record, value) {
  this._fresh.remove(name, record, value)
  this._stale.remove(name, record, value)
}

RecordCache.prototype.get = function (name, n) {
  var a = this._fresh.get(name)
  var b = this._stale.get(name)
  var aLen = a.length
  var bLen = b.length
  var len = aLen + bLen

  if (n > len || !n) n = len
  var result = new Array(n)

  for (var i = 0; i < n; i++) {
    var j = Math.floor(Math.random() * (aLen + bLen))
    if (j < aLen) {
      result[i] = a[j].record
      swap(a, j, --aLen)
    } else {
      j -= aLen
      result[i] = b[j].record
      swap(b, j, --bLen)
    }
  }

  return result
}

RecordCache.prototype._gcAuto = function () {
  if (!this._gced) this._gc()
  this._gced = false
}

RecordCache.prototype._gc = function () {
  if (this._onstale && this._stale.size > 0) this._onstale(this._stale)
  this._stale = this._fresh
  this._fresh = new RecordStore()
  this._gced = true
}

RecordCache.prototype.clear = function () {
  this._gc()
  this._gc()
}

RecordCache.prototype.destroy = function () {
  this.clear()
  clearInterval(this._interval)
  this._interval = null
}

function toString (record) {
  return b4a.isBuffer(record) ? b4a.toString(record, 'hex') : record
}

function swap (list, a, b) {
  var tmp = list[a]
  tmp.index = b
  list[b].index = a
  list[a] = list[b]
  list[b] = tmp
}
{
  "name": "record-cache",
  "version": "1.2.0",
  "description": "Cache optimised for record like things",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.3.1"
  },
  "devDependencies": {
    "standard": "^10.0.3",
    "tape": "^4.8.0"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/record-cache.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/record-cache/issues"
  },
  "homepage": "https://github.com/mafintosh/record-cache"
}
module.exports = class RefCounter {
  constructor() {
    this.count = 0

    this._onidle = null
    this._idle = null
  }

  isIdle() {
    return this.count === 0
  }

  idle() {
    if (this.count === 0) return Promise.resolve()
    if (this._idle !== null) return this._idle

    this._idle = new Promise((resolve) => {
      this._onidle = resolve
    })

    return this._idle
  }

  inc() {
    this.count++
  }

  dec() {
    if (--this.count > 0) return

    if (this._onidle !== null) {
      const resolve = this._onidle
      this._idle = null
      this._onidle = null
      resolve()
    }
  }
}
{
  "name": "refcounter",
  "version": "1.0.0",
  "description": "Simple refcounter",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {},
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/refcounter.git"
  },
  "author": "Holepunch Inc",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/refcounter/issues"
  },
  "homepage": "https://github.com/holepunchto/refcounter"
}
module.exports = require.addon.bind(require)
{
  "name": "require-addon",
  "version": "1.2.0",
  "description": "Import native addons across JavaScript runtimes",
  "exports": {
    "./package": "./package.json",
    ".": {
      "bare": "./lib/bare.js",
      "node": "./lib/node.js",
      "default": "./lib/default.js"
    }
  },
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    },
    "url": {
      "bare": "bare-url",
      "default": "url"
    }
  },
  "files": [
    "lib"
  ],
  "scripts": {
    "test": "npm run lint && npm run test:bare && npm run test:node",
    "test:bare": "bare test.js",
    "test:node": "node test.js",
    "lint": "prettier --check .",
    "format": "prettier --write ."
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/require-addon.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/require-addon/issues"
  },
  "homepage": "https://github.com/holepunchto/require-addon#readme",
  "engines": {
    "bare": ">=1.10.0"
  },
  "dependencies": {
    "bare-addon-resolve": "^1.3.0"
  },
  "devDependencies": {
    "bare-bundle": "^1.8.1",
    "bare-bundle-evaluate": "^1.1.0",
    "bare-fs": "^4.0.0",
    "bare-path": "^3.0.0",
    "bare-url": "^2.1.0",
    "brittle": "^3.7.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
let tmpResolve = null
let tmpReject = null

if (Promise.withResolvers) {
  module.exports = Promise.withResolvers.bind(Promise)
} else {
  module.exports = function resolveRejectPromise () {
    const promise = new Promise(setTmp)
    const result = { promise, resolve: tmpResolve, reject: tmpReject }
    tmpResolve = tmpReject = null
    return result
  }
}

function setTmp (resolve, reject) {
  tmpResolve = resolve
  tmpReject = reject
}
{
  "name": "resolve-reject-promise",
  "version": "1.1.0",
  "description": "Create an inverted promise with no function allocs",
  "main": "index.js",
  "scripts": {
    "test": "standard"
  },
  "devDependencies": {
    "standard": "^17.1.2"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/resolve-reject-promise.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/resolve-reject-promise/issues"
  },
  "homepage": "https://github.com/mafintosh/resolve-reject-promise"
}
const resources = new Map()

exports.add = function(resource, teardown) {
  resources.set(resource, teardown)
}

exports.remove = function(resource) {
  resources.delete(resource)
}

if (global.Bare) global.Bare.on('exit', run)
else global.process.on('exit', run)

function run() {
  for (const [resource, teardown] of resources) {
    teardown(resource)
  }
}
{
  "name": "resource-on-exit",
  "version": "1.0.0",
  "description": "Register sync teardown handlers for a resource",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {},
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/bare-teardown.git"
  },
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-teardown/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-teardown"
}
require.addon = require('require-addon')

module.exports = require.addon('.', __filename)
const ColumnFamily = require('./lib/column-family')
const Iterator = require('./lib/iterator')
const Snapshot = require('./lib/snapshot')
const State = require('./lib/state')
const { BloomFilterPolicy, RibbonFilterPolicy } = require('./lib/filter-policy')
const constants = require('./lib/constants')

class RocksDB {
  constructor(path, opts = {}) {
    const {
      columnFamily,
      state = new State(this, path, opts),
      snapshot = null,
      keyEncoding = null,
      valueEncoding = null
    } = opts

    this._state = state
    this._snapshot = snapshot
    this._columnFamily = state.getColumnFamily(columnFamily)
    this._keyEncoding = keyEncoding
    this._valueEncoding = valueEncoding
    this._index = -1

    this._state.addSession(this)
  }

  get opened() {
    return this._state.opened
  }

  get closed() {
    return this.isRoot() ? this._state.closed : this._index === -1
  }

  get path() {
    return this._state.path
  }

  get stats() {
    return this._state.stats
  }

  get snapshotted() {
    return this._snapshot !== null
  }

  get defaultColumnFamily() {
    return this._columnFamily
  }

  session({
    columnFamily = this._columnFamily,
    snapshot = this._snapshot !== null,
    keyEncoding = this._keyEncoding,
    valueEncoding = this._valueEncoding
  } = {}) {
    maybeClosed(this)

    return new RocksDB(null, {
      state: this._state,
      columnFamily,
      snapshot: snapshot ? this._snapshot || new Snapshot(this._state) : null,
      keyEncoding,
      valueEncoding
    })
  }

  columnFamily(name, opts) {
    return this.session({ ...opts, columnFamily: name })
  }

  snapshot() {
    return this.session({ snapshot: true })
  }

  isRoot() {
    return this === this._state.db
  }

  ready() {
    return this._state.ready()
  }

  async close({ force } = {}) {
    if (!this._state.opened) await this._state.ready()

    if (this._index !== -1) this._state.removeSession(this)

    if (force) {
      while (this._state.sessions.length > 0) {
        await this._state.sessions[this._state.sessions.length - 1].close()
      }
    }

    return this.isRoot() ? this._state.close() : Promise.resolve()
  }

  suspend() {
    maybeClosed(this)

    return this._state.suspend()
  }

  resume() {
    maybeClosed(this)

    return this._state.resume()
  }

  isIdle() {
    return this._state.handles.isIdle()
  }

  idle() {
    return this._state.handles.idle()
  }

  iterator(range, opts) {
    maybeClosed(this)

    return new Iterator(this, { ...range, ...opts })
  }

  async *keys(range, opts) {
    for await (const { key } of this.iterator(range, {
      ...opts,
      values: false
    })) {
      yield key
    }
  }

  async peek(range, opts) {
    for await (const value of this.iterator({ ...range, ...opts, limit: 1 })) {
      return value
    }

    return null
  }

  read(opts) {
    maybeClosed(this)

    return this._state.createReadBatch(this, opts)
  }

  write(opts) {
    maybeClosed(this)

    return this._state.createWriteBatch(this, opts)
  }

  flush(opts) {
    maybeClosed(this)

    return this._state.flush(this, opts)
  }

  async get(key, opts) {
    const batch = this.read({ ...opts, capacity: 1, autoDestroy: true })
    const value = batch.get(key)
    batch.tryFlush()
    return value
  }

  async put(key, value, opts) {
    const batch = this.write({ ...opts, capacity: 1, autoDestroy: true })
    batch.tryPut(key, value)
    await batch.flush()
  }

  async delete(key, opts) {
    const batch = this.write({ ...opts, capacity: 1, autoDestroy: true })
    batch.tryDelete(key)
    await batch.flush()
  }

  async deleteRange(start, end, opts) {
    const batch = this.write({ ...opts, capacity: 1, autoDestroy: true })
    batch.tryDeleteRange(start, end)
    await batch.flush()
  }

  async compact(opts = {}) {
    maybeClosed(this)

    await this._state.compact(this, opts)
  }

  async compactRange(start = null, end = null, opts = {}) {
    if (typeof end === 'object' && end !== null) {
      opts = end
      end = null
    } else if (typeof start === 'object' && start !== null) {
      opts = start
      start = null
      end = null
    }

    await this._state.compactRange(this, start, end, opts)
  }

  async approximateSize(start, end, opts = {}) {
    return this._state.approximateSize(this, start, end, opts)
  }

  async currentWalFile() {
    maybeClosed(this)

    return this._state.currentWalFile()
  }

  async getStatsLevel() {
    maybeClosed(this)

    return this._state.getStatsLevel()
  }

  async setStatsLevel(level) {
    maybeClosed(this)

    await this._state.setStatsLevel(level)
  }

  async getProperty(name) {
    maybeClosed(this)

    return this._state.getProperty(name)
  }

  _ref() {
    if (this._snapshot) this._snapshot.ref()
    this._state.handles.inc()
  }

  _unref() {
    if (this._snapshot) this._snapshot.unref()
    this._state.handles.dec()
  }

  diagnostics() {
    return this._state.diagnostics()
  }
}

module.exports = exports = RocksDB

exports.constants = constants

exports.ColumnFamily = ColumnFamily
exports.BloomFilterPolicy = BloomFilterPolicy
exports.RibbonFilterPolicy = RibbonFilterPolicy

function maybeClosed(db) {
  if (db._state.closing || db._index === -1) throw new Error('RocksDB session is closed')
}
const c = require('compact-encoding')
const binding = require('../binding')

const empty = Buffer.alloc(0)
const resolved = Promise.resolve()

class RocksDBBatch {
  constructor(db, opts = {}) {
    const { capacity = 8, autoDestroy = false } = opts

    db._ref()

    this._db = db
    this._destroyed = false
    this._capacity = capacity
    this._operations = []
    this._promises = []

    this._enqueuePromise = this._enqueuePromise.bind(this)

    this._request = null
    this._resolve = null
    this._reject = null

    this._handle = null
    this._buffer = null
    this._autoDestroy = autoDestroy
    this._stats = null

    this._resetStats()

    if (db._state.opened === true) this.ready()
  }

  _reuse(db, opts = {}) {
    const { autoDestroy = false } = opts

    db._ref()

    this._db = db
    this._destroyed = false
    this._autoDestroy = autoDestroy
  }

  _onfinished(err) {
    const resolve = this._resolve
    const reject = this._reject

    if (this._request) this._db._state.io.dec()

    this._operations = []
    this._promises = []
    this._request = null
    this._resolve = null
    this._reject = null

    this._resetStats()

    if (this._autoDestroy === true) this.destroy()

    if (reject !== null && err) reject(err)
    else if (resolve !== null) resolve()
  }

  _resize() {
    if (this._operations.length <= this._capacity) return false

    while (this._operations.length > this._capacity) {
      this._capacity *= 2
    }

    return true
  }

  async ready() {
    if (this._handle !== null) return

    if (this._db._state.opened === false) await this._db._state.ready()

    this._init()
  }

  destroy() {
    if (this._request) throw new Error('Request in progress')
    if (this._destroyed) return

    this._destroyed = true

    if (this._promises.length) this._abort()

    this._db._unref()
    this._onfree()
  }

  _onfree() {
    this._resetStats()
    this._db._state.freeBatch(this, false)
    this._db = null
  }

  _abort() {
    for (let i = 0; i < this._promises.length; i++) {
      const promise = this._promises[i]
      if (promise !== null) promise.reject(new Error('Batch is destroyed'))
    }

    this._onfinished(new Error('Batch is destroyed'))
  }

  _resetStats() {}

  async flush() {
    if (this._request) throw new Error('Request in progress')
    if (this._destroyed) throw new Error('Batch is destroyed')

    this._request = new Promise((resolve, reject) => {
      this._resolve = resolve
      this._reject = reject
    })

    this._flush()

    return this._request
  }

  tryFlush() {
    if (this._request) throw new Error('Request in progress')
    if (this._destroyed) throw new Error('Batch is destroyed')

    this._request = resolved

    this._flush()
  }

  async _flush() {
    if (this._handle === null) await this.ready()

    this._db._state.io.inc()

    if (this._db._state.resumed !== null) {
      const resumed = await this._db._state.resumed.promise

      if (!resumed) {
        if (this._destroyed) {
          this._db._state.io.dec()
        } else {
          this._destroyed = true
          this._abort()
          this._db._unref()
        }
      }
    }
  }

  _enqueuePromise(resolve, reject) {
    this._promises.push({ resolve, reject })
  }

  _encodeKey(k) {
    if (this._db._keyEncoding) return c.encode(this._db._keyEncoding, k)
    if (typeof k === 'string') return Buffer.from(k)
    return k
  }

  _encodeValue(v) {
    if (this._db._valueEncoding) return c.encode(this._db._valueEncoding, v)
    if (v === null) return empty
    if (typeof v === 'string') return Buffer.from(v)
    return v
  }

  _decodeValue(b) {
    if (this._db._valueEncoding) return c.decode(this._db._valueEncoding, b)
    return b
  }
}

exports.ReadBatch = class RocksDBReadBatch extends RocksDBBatch {
  constructor(db, opts = {}) {
    super(db, opts)

    const { asyncIO = false, fillCache = true } = opts

    this._asyncIO = asyncIO
    this._fillCache = fillCache
  }

  _init() {
    this._handle = binding.readInit()
    this._buffer = binding.readBuffer(this._handle, this._capacity)
  }

  _resize() {
    if (super._resize() && this._handle !== null) {
      this._buffer = binding.readBuffer(this._handle, this._capacity)
    }
  }

  async _flush() {
    await super._flush()

    if (this._destroyed) return

    try {
      binding.read(
        this._db._state._handle,
        this._handle,
        this._operations,
        this._db._snapshot ? this._db._snapshot._handle : undefined,
        this._asyncIO,
        this._fillCache,
        this,
        this._onread
      )
    } catch (err) {
      this._db._state.io.dec()
      throw err
    }

    this._db._state.stats.gets += this._stats.gets
    this._db._state.stats.readBatches++
  }

  _onread(errs, values) {
    let applied = true

    for (let i = 0, n = this._promises.length; i < n; i++) {
      const err = errs[i]
      if (err) applied = false

      const promise = this._promises[i]
      if (promise === null) continue

      if (err) promise.reject(err)
      else promise.resolve(values[i] ? this._decodeValue(Buffer.from(values[i])) : null)
    }

    this._onfinished(applied ? null : new AggregateError(errs, 'Batch was not applied'))
  }

  _resetStats() {
    this._stats = { gets: 0 }
  }

  get(key) {
    if (this._request) throw new Error('Request already in progress')
    this._stats.gets++

    const promise = new Promise(this._enqueuePromise)

    this._operations.push(new RocksDBGet(this._encodeKey(key), this._db._columnFamily))

    this._resize()

    return promise
  }
}

exports.WriteBatch = class RocksDBWriteBatch extends RocksDBBatch {
  _init() {
    this._handle = binding.writeInit()
    this._buffer = binding.writeBuffer(this._handle, this._capacity)
  }

  _resize() {
    if (super._resize() && this._handle !== null) {
      this._buffer = binding.writeBuffer(this._handle, this._capacity)
    }
  }

  _onfree() {
    this._resetStats()
    this._db._state.freeBatch(this, true)
    this._db = null
  }

  async _flush() {
    await super._flush()

    if (this._destroyed) return

    try {
      binding.write(this._db._state._handle, this._handle, this._operations, this, this._onwrite)
    } catch (err) {
      this._db._state.io.dec()
      throw err
    }

    this._db._state.stats.puts += this._stats.puts
    this._db._state.stats.deletes += this._stats.deletes
    this._db._state.stats.rangeDeletes += this._stats.rangeDeletes
    this._db._state.stats.writeBatches++
  }

  _onwrite(err) {
    const applied = !err

    for (let i = 0, n = this._promises.length; i < n; i++) {
      const promise = this._promises[i]
      if (promise === null) continue

      if (err) promise.reject(err)
      else promise.resolve()
    }

    this._onfinished(applied ? null : new Error('Batch was not applied', { cause: err }))
  }

  _resetStats() {
    this._stats = { puts: 0, deletes: 0, rangeDeletes: 0 }
  }

  put(key, value) {
    if (this._request) throw new Error('Request already in progress')
    this._stats.puts++

    const promise = new Promise(this._enqueuePromise)

    this._operations.push(
      new RocksDBPut(this._encodeKey(key), this._encodeValue(value), this._db._columnFamily)
    )

    this._resize()

    return promise
  }

  tryPut(key, value) {
    if (this._request) throw new Error('Request already in progress')
    this._stats.puts++

    this._operations.push(
      new RocksDBPut(this._encodeKey(key), this._encodeValue(value), this._db._columnFamily)
    )

    this._promises.push(null)

    this._resize()
  }

  delete(key) {
    if (this._request) throw new Error('Request already in progress')
    this._stats.deletes++

    const promise = new Promise(this._enqueuePromise)

    this._operations.push(new RocksDBDelete(this._encodeKey(key), this._db._columnFamily))

    this._resize()

    return promise
  }

  tryDelete(key) {
    if (this._request) throw new Error('Request already in progress')
    this._stats.deletes++

    this._operations.push(new RocksDBDelete(this._encodeKey(key), this._db._columnFamily))

    this._promises.push(null)

    this._resize()
  }

  deleteRange(start, end) {
    if (this._request) throw new Error('Request already in progress')
    this._stats.rangeDeletes++

    const promise = new Promise(this._enqueuePromise)

    this._operations.push(
      new RocksDBDeleteRange(this._encodeKey(start), this._encodeKey(end), this._db._columnFamily)
    )

    this._resize()

    return promise
  }

  tryDeleteRange(start, end) {
    if (this._request) throw new Error('Request already in progress')
    this._stats.rangeDeletes++

    this._operations.push(
      new RocksDBDeleteRange(this._encodeKey(start), this._encodeKey(end), this._db._columnFamily)
    )

    this._promises.push(null)

    this._resize()
  }
}

class RocksDBGet {
  constructor(key, columnFamily) {
    this.key = key
    this.columnFamily = columnFamily._handle
  }

  get type() {
    return binding.GET
  }
}

class RocksDBPut {
  constructor(key, value, columnFamily) {
    this.key = key
    this.value = value
    this.columnFamily = columnFamily._handle
  }

  get type() {
    return binding.PUT
  }
}

class RocksDBDelete {
  constructor(key, columnFamily) {
    this.key = key
    this.columnFamily = columnFamily._handle
  }

  get type() {
    return binding.DELETE
  }
}

class RocksDBDeleteRange {
  constructor(start, end, columnFamily) {
    this.start = start
    this.end = end
    this.columnFamily = columnFamily._handle
  }

  get type() {
    return binding.DELETE_RANGE
  }
}
const binding = require('../binding')
const constants = require('./constants')
const { BloomFilterPolicy } = require('./filter-policy')

class RocksDBColumnFamily {
  constructor(name, opts = {}) {
    const {
      // Blob options
      enableBlobFiles = false,
      minBlobSize = 0,
      blobFileSize = 0,
      enableBlobGarbageCollection = true,
      // Block table options
      tableBlockSize = 8192,
      tableCacheIndexAndFilterBlocks = true,
      tableFormatVersion = 6,
      optimizeFiltersForMemory = false,
      blockCache = true,
      filterPolicy = new BloomFilterPolicy(10),
      topLevelIndexPinningTier = constants.pinningTier.ALL,
      partitionPinningTier = constants.pinningTier.ALL,
      unpartitionedPinningTier = constants.pinningTier.ALL,
      optimizeFiltersForHits = false,
      numLevels = 7,
      maxWriteBufferNumber = 2,
      blobGarbageCollectionAgeCutOff = 0.25,
      blobGarbageCollectionForceThreshold = 1.0
    } = opts

    this._name = name
    this._flushing = null
    this._options = {
      enableBlobFiles,
      minBlobSize,
      blobFileSize,
      enableBlobGarbageCollection,
      tableBlockSize,
      tableCacheIndexAndFilterBlocks,
      tableFormatVersion,
      optimizeFiltersForMemory,
      blockCache,
      filterPolicy,
      topLevelIndexPinningTier,
      partitionPinningTier,
      unpartitionedPinningTier,
      optimizeFiltersForHits,
      numLevels,
      maxWriteBufferNumber,
      blobGarbageCollectionAgeCutOff,
      blobGarbageCollectionForceThreshold
    }

    const filterPolicyArguments = [0, 0, 0]

    if (filterPolicy !== null) {
      filterPolicyArguments[0] = filterPolicy.type

      switch (filterPolicy.type) {
        case 1: // Bloom filter policy
          filterPolicyArguments[1] = filterPolicy.bitsPerKey
          break
        case 2: // Ribbon filter policy
          filterPolicyArguments[1] = filterPolicy.bloomEquivalentBitsPerKey
          filterPolicyArguments[2] = filterPolicy.bloomBeforeLevel

          break
      }
    }

    this._handle = binding.columnFamilyInit(
      name,
      enableBlobFiles,
      minBlobSize,
      blobFileSize,
      enableBlobGarbageCollection,
      tableBlockSize,
      tableCacheIndexAndFilterBlocks,
      tableFormatVersion,
      optimizeFiltersForMemory,
      blockCache === false,
      ...filterPolicyArguments,
      topLevelIndexPinningTier,
      partitionPinningTier,
      unpartitionedPinningTier,
      optimizeFiltersForHits,
      numLevels,
      maxWriteBufferNumber,
      blobGarbageCollectionAgeCutOff,
      blobGarbageCollectionForceThreshold
    )
  }

  cloneSettings(name) {
    return new RocksDBColumnFamily(name, this._options)
  }

  get name() {
    return this._name
  }

  destroy() {
    if (this._handle === null) return

    binding.columnFamilyDestroy(this._handle)

    this._handle = null
  }
}

module.exports = RocksDBColumnFamily
module.exports = {
  pinningTier: {
    NONE: 0,
    FLUSHED_AND_SIMILAR: 1,
    ALL: 2
  },
  garbageCollectionPolicy: {
    DEFAULT: 0,
    FORCE: 1,
    DISABLE: 2
  },
  bottommostLevelCompaction: {
    NONE: 0,
    SKIP: 1,
    FORCE: 2
  },
  walRecoveryMode: {
    TOLERATE_CORRUPTED_TAIL_RECORDS: 0,
    ABSOLUTE_CONSISTENCY: 1,
    POINT_IN_TIME: 2,
    SKIP_ANY_CORRUPTED_RECORDS: 3
  },
  statsLevel: {
    DISABLE_ALL: 0,
    EXCEPT_HISTOGRAM_OR_TIMERS: 1,
    EXCEPT_TIMERS: 2,
    EXCEPT_DETAILED_TIMERS: 3,
    EXCEPT_TIME_FOR_MUTEX: 4,
    ALL: 5
  },
  walFileType: {
    ARCHIVED: 0,
    ALIVE: 1
  }
}
exports.BloomFilterPolicy = class RocksDBBloomFilterPolicy {
  get type() {
    return 1
  }

  constructor(bitsPerKey) {
    this.bitsPerKey = bitsPerKey
  }
}

exports.RibbonFilterPolicy = class RocksDBRibbonFilterPolicy {
  get type() {
    return 2
  }

  constructor(bloomEquivalentBitsPerKey, bloomBeforeLevel = 0) {
    this.bloomEquivalentBitsPerKey = bloomEquivalentBitsPerKey
    this.bloomBeforeLevel = bloomBeforeLevel
  }
}
const { Readable } = require('streamx')
const c = require('compact-encoding')
const binding = require('../binding')

const empty = Buffer.alloc(0)

module.exports = class RocksDBIterator extends Readable {
  constructor(db, opts = {}) {
    const {
      gt = null,
      gte = null,
      lt = null,
      lte = null,
      reverse = false,
      values = true,
      limit = Infinity,
      capacity = 8
    } = opts

    super()

    db._ref()

    this._db = db

    this._gt = gt ? this._encodeKey(gt) : empty
    this._gte = gte ? this._encodeKey(gte) : empty
    this._lt = lt ? this._encodeKey(lt) : empty
    this._lte = lte ? this._encodeKey(lte) : empty

    this._reverse = reverse
    this._values = values
    this._limit = limit < 0 ? Infinity : limit
    this._capacity = capacity
    this._opened = false

    this._pendingOpen = null
    this._pendingRead = null
    this._pendingDestroy = null

    this._buffer = null
    this._handle = null

    if (this._db._state.opened === true) this.ready()
  }

  _onopen(err) {
    const cb = this._pendingOpen
    this._pendingOpen = null
    this._opened = true
    this._db._state.io.dec()
    cb(err)
  }

  _onread(err, keys, values) {
    const cb = this._pendingRead
    this._pendingRead = null
    this._db._state.io.dec()
    if (err) return cb(err)

    const n = keys.length

    this._limit -= n

    for (let i = 0; i < n; i++) {
      this.push({
        key: this._decodeKey(Buffer.from(keys[i])),
        value: this._values ? this._decodeValue(Buffer.from(values[i])) : null
      })
    }

    if (n < this._capacity) this.push(null)

    cb(null)
  }

  _onclose(err) {
    const cb = this._pendingDestroy
    this._pendingDestroy = null
    this._db._state.io.dec()
    this._db._unref()
    cb(err)
  }

  _resize() {
    if (this._handle !== null) {
      this._buffer = binding.iteratorBuffer(this._handle, this._capacity)
    }
  }

  async ready() {
    if (this._handle !== null) return

    if (this._db._state.opened === false) await this._db._state.ready()

    this._init()
  }

  _init() {
    this._handle = binding.iteratorInit()
    this._buffer = binding.iteratorBuffer(this._handle, this._capacity)
  }

  async _open(cb) {
    await this.ready()

    this._db._state.io.inc()

    if (this._db._state.resumed !== null) {
      const resumed = await this._db._state.resumed.promise

      if (!resumed) {
        this._db._state.io.dec()

        return cb(new Error('RocksDB session is closed'))
      }
    }

    this._pendingOpen = cb

    try {
      binding.iteratorOpen(
        this._db._state._handle,
        this._handle,
        this._db._columnFamily._handle,
        this._gt,
        this._gte,
        this._lt,
        this._lte,
        this._reverse,
        !this._values, // Keys only
        this._db._snapshot ? this._db._snapshot._handle : undefined,
        this,
        this._onopen,
        this._onclose,
        this._onread
      )
    } catch (err) {
      this._db._state.io.dec()

      cb(err)
    }
  }

  async _read(cb) {
    this._db._state.io.inc()

    if (this._db._state.resumed !== null) {
      const resumed = await this._db._state.resumed.promise

      if (!resumed) {
        this._db._state.io.dec()

        return cb(new Error('RocksDB session is closed'))
      }
    }

    this._pendingRead = cb

    try {
      binding.iteratorRead(this._handle, Math.min(this._capacity, this._limit))
    } catch (err) {
      this._db._state.io.dec()

      cb(err)
    }
  }

  async _destroy(cb) {
    await this.ready()

    this._db._state.io.inc()

    if (this._opened === false) {
      this._db._state.io.dec()
      this._db._unref()

      return cb(null)
    }

    this._pendingDestroy = cb

    try {
      binding.iteratorClose(this._handle)
    } catch (err) {
      this._db._state.io.dec()
      this._db._unref()

      cb(err)
    }
  }

  _encodeKey(k) {
    if (this._db._keyEncoding !== null) return c.encode(this._db._keyEncoding, k)
    if (typeof k === 'string') return Buffer.from(k)
    return k
  }

  _decodeKey(b) {
    if (this._db._keyEncoding !== null) return c.decode(this._db._keyEncoding, b)
    return b
  }

  _decodeValue(b) {
    if (this._db._valueEncoding !== null) return c.decode(this._db._valueEncoding, b)
    return b
  }
}
const binding = require('../binding')

module.exports = class RocksDBSnapshot {
  constructor(state) {
    this._state = state

    this._handle = null
    this._refs = 0

    if (state.deferSnapshotInit === false) this._init()
  }

  _init() {
    this._handle = binding.snapshotCreate(this._state._handle)
  }

  ref() {
    this._refs++
  }

  unref() {
    if (--this._refs > 0) return

    if (this._handle === null) return

    binding.snapshotDestroy(this._handle)

    this._handle = null
  }
}
const ReadyResource = require('ready-resource')
const RefCounter = require('refcounter')
const rrp = require('resolve-reject-promise')
const SignalPromise = require('signal-promise')
const c = require('compact-encoding')
const { ReadBatch, WriteBatch } = require('./batch')
const ColumnFamily = require('./column-family')
const binding = require('../binding')
const constants = require('./constants')

const MAX_BATCH_REUSE = 64
const empty = Buffer.alloc(0)

module.exports = class RocksDBState extends ReadyResource {
  constructor(db, path, opts) {
    super()

    const {
      columnFamily = new ColumnFamily('default', opts),
      columnFamilies = [],
      readOnly = false,
      createIfMissing = true,
      createMissingColumnFamilies = true,
      maxBackgroundJobs = 6,
      bytesPerSync = 1048576,
      maxOpenFiles = -1,
      useDirectReads = false,
      avoidUnnecessaryBlockingIO = false,
      skipStatsUpdateOnOpen = false,
      useDirectIOForFlushAndCompaction = false,
      maxFileOpeningThreads = 16,
      lock = null,
      walRecoveryMode = constants.walRecoveryMode.POINT_IN_TIME,
      bestEffortsRecovery = false,
      enableStatistics = false,
      statsLevel = constants.statsLevel.EXCEPT_HISTOGRAM_OR_TIMERS,
      walTtlSeconds = 0,
      walSizeLimitMegabytes = 0,
      avoidFlushDuringShutdown = false,
      walFilterPrefixes = []
    } = opts

    this.path = path
    this.db = db
    this.handles = new RefCounter()
    this.io = new RefCounter()
    this.sessions = []
    this.columnFamilies = [columnFamily]
    this.deferSnapshotInit = true
    this.resumed = null
    this.stats = {
      gets: 0,
      puts: 0,
      deletes: 0,
      rangeDeletes: 0,
      readBatches: 0,
      writeBatches: 0
    }

    this._suspended = false
    this._suspending = false
    this._updating = false
    this._updatingSignal = new SignalPromise()
    this._columnsFlushed = false
    this._lock = lock
    this._readBatches = []
    this._writeBatches = []

    for (const columnFamily of columnFamilies) {
      this.columnFamilies.push(
        typeof columnFamily === 'string' ? new ColumnFamily(columnFamily, opts) : columnFamily
      )
    }

    this._handle = binding.init(
      readOnly,
      createIfMissing,
      createMissingColumnFamilies,
      maxBackgroundJobs,
      bytesPerSync,
      maxOpenFiles,
      useDirectReads,
      avoidUnnecessaryBlockingIO,
      skipStatsUpdateOnOpen,
      useDirectIOForFlushAndCompaction,
      maxFileOpeningThreads,
      walRecoveryMode,
      bestEffortsRecovery,
      enableStatistics,
      statsLevel,
      walTtlSeconds,
      walSizeLimitMegabytes,
      avoidFlushDuringShutdown,
      walFilterPrefixes.map(encodePrefix)
    )
  }

  createReadBatch(db, opts) {
    if (this._readBatches.length === 0) return new ReadBatch(db, opts)
    const batch = this._readBatches.pop()
    batch._reuse(db, opts)
    return batch
  }

  createWriteBatch(db, opts) {
    if (this._writeBatches.length === 0) return new WriteBatch(db, opts)
    const batch = this._writeBatches.pop()
    batch._reuse(db, opts)
    return batch
  }

  freeBatch(batch, writable) {
    if (batch._capacity > 16) return
    const queue = writable ? this._writeBatches : this._readBatches
    if (queue.length >= MAX_BATCH_REUSE) return
    queue.push(batch)
  }

  addSession(db) {
    db._index = this.sessions.push(db) - 1
    if (db._snapshot) db._snapshot.ref()
  }

  removeSession(db) {
    const head = this.sessions.pop()
    if (head !== db) this.sessions[(head._index = db._index)] = head
    db._index = -1
    if (db._snapshot) db._snapshot.unref()
  }

  upsertColumnFamily(c) {
    if (typeof c === 'string') {
      let col = this.getColumnFamilyByName(c)
      if (col) return col
      col = this.columnFamilies[0].cloneSettings(c)
      this.columnFamilies.push(col)
      return col
    }

    if (this.columnFamilies.includes(c)) return c
    this.columnFamilies.push(c)
    return c
  }

  getColumnFamily(c) {
    if (!c) return this.columnFamilies[0]
    if (!this._columnsFlushed) return this.upsertColumnFamily(c)

    if (typeof c !== 'string') return c

    const col = this.getColumnFamilyByName(c)
    if (col === null) throw new Error('Unknown column family')
    return col
  }

  getColumnFamilyByName(name) {
    for (const col of this.columnFamilies) {
      if (col.name === name) return col
    }
    return null
  }

  async _open() {
    await Promise.resolve() // Allow column families to populate if on-demand

    if (this._lock) await this._lock.ready()

    const req = { resolve: null, reject: null, handle: null }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    this._columnsFlushed = true

    const lock = this._lock === null ? -1 : this._lock.transfer()

    req.handle = binding.open(
      this._handle,
      this,
      this.path,
      this.columnFamilies.map((c) => c._handle),
      lock,
      req,
      onopen
    )

    await promise

    this.deferSnapshotInit = false

    for (const session of this.sessions) {
      if (session._snapshot) session._snapshot._init()
    }

    function onopen(err) {
      if (err) req.reject(err)
      else req.resolve()
    }
  }

  async _close() {
    while (this._updating) await this._updatingSignal.wait()
    if (this.resumed) this.resumed.resolve(false)

    while (!this.io.isIdle()) await this.io.idle()
    while (!this.handles.isIdle()) await this.handles.idle()

    while (this.sessions.length > 0) {
      await this.sessions[this.sessions.length - 1].close()
    }

    for (const columnFamily of this.columnFamilies) columnFamily.destroy()

    const req = { resolve: null, reject: null, handle: null }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    req.handle = binding.close(this._handle, req, onclose)

    try {
      await promise
    } finally {
      if (this._lock) await this._lock.close()
    }

    function onclose(err) {
      if (err) req.reject(err)
      else req.resolve()
    }
  }

  async flush(db, opts) {
    if (this.opened === false) await this.ready()

    this.io.inc()

    if (this.resumed !== null) {
      const resumed = await this.resumed.promise

      if (!resumed) {
        this.io.dec()

        throw new Error('RocksDB session is closed')
      }
    }

    const req = { resolve: null, reject: null, handle: null }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    try {
      req.handle = binding.flush(this._handle, db._columnFamily._handle, req, onflush)

      await promise
    } finally {
      this.io.dec()
    }

    function onflush(err) {
      if (err) req.reject(err)
      else req.resolve()
    }
  }

  suspend() {
    this._suspending = true
    return this.update()
  }

  resume() {
    this._suspending = false
    return this.update()
  }

  async update() {
    while (this._updating) await this._updatingSignal.wait()
    if (this._suspending === this._suspended || this.closing) return
    this._updating = true
    try {
      if (this._suspending) await this._suspend()
      else await this._resume()
    } finally {
      this._updating = false
      this._updatingSignal.notify()
    }
  }

  async _suspend() {
    if (this._suspended === true) return

    while (!this.io.isIdle()) await this.io.idle()

    this.io.inc()
    this.resumed = rrp()

    const req = { resolve: null, reject: null, handle: null }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    try {
      req.handle = binding.suspend(this._handle, req, onsuspend)

      await promise

      this._suspended = true
    } finally {
      this.io.dec()
    }

    function onsuspend(err) {
      if (err) req.reject(err)
      else req.resolve()
    }
  }

  async _resume() {
    if (this._suspended === false) return

    const req = { resolve: null, reject: null, handle: null }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    req.handle = binding.resume(this._handle, req, onresume)

    await promise

    this._suspended = false

    const resumed = this.resumed
    this.resumed = null
    resumed.resolve(true)

    function onresume(err) {
      if (err) req.reject(err)
      else req.resolve()
    }
  }

  async compact(db, opts) {
    if (this.opened === false) await this.ready()

    this.io.inc()

    const {
      exclusive = false,
      blobGarbageCollectionPolicy = constants.garbageCollectionPolicy.DEFAULT,
      blobGarbageCollectionAgeCutoff = 0.25,
      bottommostLevelCompaction = constants.bottommostLevelCompaction.NONE
    } = opts

    const req = { resolve: null, reject: null, handle: null }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    try {
      req.handle = binding.compact(
        this._handle,
        db._columnFamily._handle,
        exclusive,
        blobGarbageCollectionPolicy,
        blobGarbageCollectionAgeCutoff,
        bottommostLevelCompaction,
        req,
        oncompact
      )

      await promise
    } finally {
      this.io.dec()
    }

    function oncompact(err) {
      if (err) req.reject(err)
      else req.resolve()
    }
  }

  async compactRange(db, start, end, opts) {
    if (this.opened === false) await this.ready()

    this.io.inc()

    const {
      exclusive = false,
      blobGarbageCollectionPolicy = constants.garbageCollectionPolicy.DEFAULT,
      blobGarbageCollectionAgeCutoff = 0.25,
      bottommostLevelCompaction = constants.bottommostLevelCompaction.NONE
    } = opts

    start = this._encodeKey(start)
    end = this._encodeKey(end)

    const req = { resolve: null, reject: null, handle: null, start, end }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    try {
      req.handle = binding.compactRange(
        this._handle,
        db._columnFamily._handle,
        start,
        end,
        exclusive,
        blobGarbageCollectionPolicy,
        blobGarbageCollectionAgeCutoff,
        bottommostLevelCompaction,
        req,
        oncompactrange
      )

      await promise
    } finally {
      this.io.dec()
    }

    function oncompactrange(err) {
      if (err) req.reject(err)
      else req.resolve()
    }
  }

  async approximateSize(db, start, end, opts) {
    if (this.opened === false) await this.ready()

    this.io.inc()

    const { includeMemtables = false, includeFiles = true, filesSizeErrorMargin = -1 } = opts

    start = this._encodeKey(start)
    end = this._encodeKey(end)

    const req = { resolve: null, reject: null, handle: null, start, end }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    try {
      req.handle = binding.approximateSize(
        this._handle,
        db._columnFamily._handle,
        start,
        end,
        includeMemtables,
        includeFiles,
        filesSizeErrorMargin,
        req,
        onapproximatesize
      )

      return await promise
    } finally {
      this.io.dec()
    }

    function onapproximatesize(err, result) {
      if (err) req.reject(err)
      else req.resolve(result)
    }
  }

  async currentWalFile() {
    if (this.opened === false) await this.ready()

    this.io.inc()

    const req = { resolve: null, reject: null, handle: null }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    try {
      req.handle = binding.currentWalFile(this._handle, req, oncurrentwalfile)

      return await promise
    } finally {
      this.io.dec()
    }

    function oncurrentwalfile(err, path, number, type, startSequence, size) {
      if (err) req.reject(err)
      else req.resolve({ path, number, type, startSequence, size })
    }
  }

  async getStatsLevel() {
    if (this.opened === false) await this.ready()

    return binding.statsLevelGet(this._handle)
  }

  async setStatsLevel(level) {
    if (this.opened === false) await this.ready()

    binding.statsLevelSet(this._handle, level)
  }

  async getProperty(name) {
    if (this.opened === false) await this.ready()

    return binding.propertyGet(this._handle, name)
  }

  _encodeKey(k) {
    if (this.db._keyEncoding) return c.encode(this.db._keyEncoding, k)
    if (typeof k === 'string') return Buffer.from(k)
    if (k === null) return empty
    return k
  }

  diagnostics() {
    return {
      suspended: this._suspended,
      suspending: this._suspending,
      updating: this._updating,
      resumedPending: this.resumed !== null,
      io: this.io.count,
      handles: this.handles.count,
      sessions: this.sessions.length
    }
  }
}

function encodePrefix(prefix) {
  if (typeof prefix === 'string') return Buffer.from(prefix)
  return prefix
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "rocksdb-native",
  "version": "3.17.2",
  "description": "librocksdb bindings for JavaScript",
  "exports": {
    ".": "./index.js",
    "./package": "./package.json"
  },
  "imports": {
    "crypto": {
      "bare": "bare-crypto",
      "default": "crypto"
    },
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    }
  },
  "files": [
    "index.js",
    "binding.cc",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds",
    "!prebuilds/android-*/**/*.node"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:bare && npm run test:node",
    "test:bare": "brittle-bare --coverage test.js",
    "test:node": "brittle-node --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/rocksdb-native.git"
  },
  "author": "Holepunch Inc",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/rocksdb-native/issues"
  },
  "homepage": "https://github.com/holepunchto/rocksdb-native",
  "engines": {
    "bare": ">=1.16.0"
  },
  "dependencies": {
    "compact-encoding": "^3.0.0",
    "ready-resource": "^1.0.0",
    "refcounter": "^1.0.0",
    "require-addon": "^1.0.2",
    "resolve-reject-promise": "^1.1.0",
    "signal-promise": "^1.0.3",
    "streamx": "^2.16.1"
  },
  "devDependencies": {
    "bare-compat-napi": "^1.3.0",
    "bare-crypto": "^1.12.0",
    "bare-fs": "^4.5.0",
    "bare-path": "^3.0.0",
    "brittle": "^3.5.0",
    "cmake-bare": "^1.1.14",
    "cmake-fetch": "^1.0.1",
    "cmake-napi": "^1.0.6",
    "fd-lock": "^2.0.0",
    "lunte": "^1.8.0",
    "paparam": "^1.9.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = safetyCatch

function isActuallyUncaught (err) {
  if (!err) return false
  return err instanceof TypeError ||
    err instanceof SyntaxError ||
    err instanceof ReferenceError ||
    err instanceof EvalError ||
    err instanceof RangeError ||
    err instanceof URIError ||
    err.code === 'ERR_ASSERTION' ||
    err.name === 'AssertionError'
}

function throwErrorNT (err) {
  queueMicrotask(() => { throw err })
}

function safetyCatch (err) {
  if (isActuallyUncaught(err)) {
    throwErrorNT(err)
    throw err
  }
}
{
  "name": "safety-catch",
  "version": "1.0.3",
  "description": "Small module that makes sure your catch, caught an actual error and not a programming mistake or assertion",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {},
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/safety-catch.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/safety-catch/issues"
  },
  "homepage": "https://github.com/mafintosh/safety-catch"
}
let tmpResolve = null

module.exports = class ScopeLock {
  constructor ({ debounce = false } = {}) {
    this.debounce = debounce
    this.waiting = []
    this.locked = false
    this.skip = 0
    this.destroyed = false
  }

  flush () {
    if (this.locked === false && this.waiting.length === 0) return Promise.resolve(this.destroyed === false)

    const promise = new Promise(setTmpResolve)
    const resolve = tmpResolve

    tmpResolve = null
    this.waiting.push({ lock: false, resolve })

    return promise
  }

  destroy () {
    this.destroyed = true
  }

  lock () {
    const promise = new Promise(setTmpResolve)
    const resolve = tmpResolve

    tmpResolve = null

    if (this.locked === true) {
      this.waiting.push({ lock: true, resolve })
      return promise
    }

    if (this.destroyed === true) {
      resolve(false)
      return promise
    }

    this.locked = true
    resolve(true)

    return promise
  }

  unlock () {
    if (this.destroyed === true) {
      for (let i = 0; i < this.waiting.length; i++) {
        this.waiting[i].resolve(false)
      }
      this.waiting = []
      this.skip = 0
      this.locked = false
      return
    }

    if (this.skip !== 0) {
      for (let i = 0; i < this.skip; i++) {
        const { lock, resolve } = this.waiting[i]
        resolve(lock === false)
      }

      this.waiting = this.waiting.slice(this.skip)
      this.skip = 0
    }

    while (this.waiting.length > 0 && this.waiting[0].lock === false) {
      this.waiting.shift().resolve(true)
    }

    if (this.waiting.length === 0) {
      this.locked = false
      return
    }

    const { resolve } = this.waiting.shift()
    if (this.debounce === true) this.skip = this.waiting.length

    resolve(true)
  }
}

function setTmpResolve (resolve) {
  tmpResolve = resolve
}
{
  "name": "scope-lock",
  "version": "1.2.4",
  "description": "Some concurrency semantics around entering scopes",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "devDependencies": {
    "brittle": "^3.7.0",
    "standard": "^17.1.2"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/scope-lock.git"
  },
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/scope-lock/issues"
  },
  "homepage": "https://github.com/holepunchto/scope-lock"
}
const set = require('unordered-set')

module.exports = opts => new ShuffledPriorityQueue(opts)

class ShuffledPriorityQueue {
  constructor (opts) {
    this.priorities = []
    this.equals = (opts && opts.equals) || null
  }

  get length () {
    return this.priorities.reduce(add, 0)
  }

  [Symbol.iterator] () {
    return new Iterator(this)
  }

  head () {
    for (let i = this.priorities.length - 1; i >= 0; i--) {
      const q = this.priorities[i]
      if (q.length) return shuffle(q, 0)
    }
    return null
  }

  tail () {
    for (let i = 0; i < this.priorities.length; i++) {
      const q = this.priorities[i]
      if (q.length) return shuffle(q, 0)
    }
    return null
  }

  prev (prev) {
    if (!prev) return this.tail()
    return next(this.priorities, prev, 1)
  }

  next (prev) {
    if (!prev) return this.head()
    return next(this.priorities, prev, -1)
  }

  shift () {
    return this.remove(this.head())
  }

  pop () {
    return this.remove(this.tail())
  }

  add (val) {
    const prio = val.priority || 0
    while (prio >= this.priorities.length) this.priorities.push([])
    set.add(this.priorities[prio], val)
    return val
  }

  remove (val) {
    if (!val) return null

    if (val._index === undefined) {
      val = this.find(val)
      if (!val) return null
    }

    return set.remove(this.priorities[val.priority || 0], val)
  }

  has (val) {
    if (val._index === undefined) return this.find(val)
    const priority = val.priority || 0
    if (priority >= this.priorities.length) return false
    return set.has(this.priorities[priority], val)
  }

  find (val) {
    if (val._index !== undefined) return val

    const prio = val.priority || 0
    const qs = this.priorities
    if (prio >= qs.length) return null

    const q = qs[prio]

    for (let i = 0; i < q.length; i++) {
      if (this.equals(q[i], val)) return q[i]
    }

    return null
  }
}

class Iterator {
  constructor (queue) {
    this.prev = null
    this.queue = queue
  }

  next () {
    const next = this.queue.next(this.prev)
    this.prev = next
    return { done: !next, value: next }
  }
}

function shuffle (q, i) {
  const ran = i + Math.floor(Math.random() * (q.length - i))
  set.swap(q, q[ran], q[i])
  return q[i]
}

function next (queues, prev, inc) {
  let i = prev.priority || 0
  let j = (prev._index || 0) + 1

  while (true) {
    if (i < 0 || i >= queues.length) return null
    const q = queues[i]

    if (j >= q.length) {
      i += inc
      j = 0
      continue
    }

    return shuffle(q, j)
  }
}

function add (len, b) {
  return len + b.length
}
{
  "name": "shuffled-priority-queue",
  "version": "2.1.0",
  "description": "A priority queue that shuffles elements with the same priority.",
  "main": "index.js",
  "scripts": {
    "test": "standard && tape test.js"
  },
  "dependencies": {
    "unordered-set": "^2.0.1"
  },
  "devDependencies": {
    "standard": "^12.0.1",
    "tape": "^4.9.1"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/shuffled-priority-queue.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/shuffled-priority-queue/issues"
  },
  "homepage": "https://github.com/mafintosh/shuffled-priority-queue"
}
module.exports = class Signal {
  constructor () {
    this._resolve = null
    this._reject = null
    this._promise = null
    this._bind = bind.bind(this)
    this._onerror = clear.bind(this)
    this._onsuccess = clear.bind(this, null)
    this._timers = new Set()
  }

  wait (max) {
    if (!this._promise) {
      this._promise = new Promise(this._bind)
      this._promise.then(this._onsuccess).catch(this._onerror)
    }
    if (max) return this._sleep(max)
    return this._promise
  }

  _sleep (max) {
    const s = new Promise((resolve, reject) => {
      const done = () => {
        this._timers.delete(state)
        resolve(true)
      }
      const id = setTimeout(done, max)
      const state = { id, resolve, reject }
      this._timers.add(state)
    })

    return s
  }

  notify (err) {
    if (!this._promise) return
    const resolve = this._resolve
    const reject = this._reject
    this._promise = null
    if (err) reject(err)
    else resolve(true)
  }
}

function clear (err) {
  for (const { id, resolve, reject } of this._timers) {
    clearTimeout(id)
    if (err) reject(err)
    else resolve(true)
  }
  this._timers.clear()
}

function bind (resolve, reject) {
  this._resolve = resolve
  this._reject = reject
}
{
  "name": "signal-promise",
  "version": "1.0.3",
  "description": "Simple wait/notify promise with optional max wait time",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {},
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/signal-promise.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/signal-promise/issues"
  },
  "homepage": "https://github.com/mafintosh/signal-promise"
}
var varint = require('varint')
exports.encode = function encode (v, b, o) {
  v = v >= 0 ? v*2 : v*-2 - 1
  var r = varint.encode(v, b, o)
  encode.bytes = varint.encode.bytes
  return r
}
exports.decode = function decode (b, o) {
  var v = varint.decode(b, o)
  decode.bytes = varint.decode.bytes
  return v & 1 ? (v+1) / -2 : v / 2
}

exports.encodingLength = function (v) {
  return varint.encodingLength(v >= 0 ? v*2 : v*-2 - 1)
}
{
  "name": "signed-varint",
  "description": "efficiently store signed integers in varint",
  "version": "2.0.1",
  "homepage": "https://github.com/dominictarr/signed-varint",
  "repository": {
    "type": "git",
    "url": "git://github.com/dominictarr/signed-varint.git"
  },
  "dependencies": {
    "varint": "~5.0.0"
  },
  "devDependencies": {
    "tape": "~2.12.3"
  },
  "scripts": {
    "test": "node test.js"
  },
  "author": "Dominic Tarr <dominic.tarr@gmail.com> (http://dominictarr.com)",
  "license": "MIT"
}
require.addon = require('require-addon')

module.exports = require.addon('.', __filename)
const binding = require('./binding')
const b4a = require('b4a')

function predicate(u8, u16, u32) {
  return function predicate(buf) {
    if (buf.byteLength % 16 !== 0) {
      throw new Error('Buffer length must be a multiple of 16')
    }

    const n = buf.BYTES_PER_ELEMENT

    if (n === 1) return u8(buf)
    if (n === 2) return u16(buf)
    return u32(buf)
  }
}

function unary(u8, u16, u32) {
  return function unary(buf, result = b4a.allocUnsafe(buf.byteLength)) {
    if (buf.byteLength % 16 !== 0) {
      throw new Error('Buffer length must be a multiple of 16')
    }

    if (buf.byteLength !== result.byteLength) {
      throw new Error('Length of result buffer is insufficient')
    }

    const n = buf.BYTES_PER_ELEMENT

    if (n === 1) u8(buf, result)
    else if (n === 2) u16(buf, result)
    else u32(buf, result)

    return result
  }
}

function binary(u8, u16, u32) {
  return function binary(a, b, result = b4a.allocUnsafe(a.byteLength)) {
    if (a.byteLength % 16 !== 0) {
      throw new Error('Buffer length must be a multiple of 16')
    }

    if (a.byteLength !== b.byteLength || a.byteLength !== result.byteLength) {
      throw new Error('Buffers must be the same length')
    }

    const n = a.BYTES_PER_ELEMENT

    if (n === 1) u8(a, b, result)
    else if (n === 2) u16(a, b, result)
    else u32(a, b, result)

    return result
  }
}

function reduce(u8, u16, u32) {
  return function reduce(buf) {
    if (buf.byteLength % 16 !== 0) {
      throw new Error('Buffer length must be a multiple of 16')
    }

    const n = buf.BYTES_PER_ELEMENT

    if (n === 1) return u8(buf)
    if (n === 2) return u16(buf)
    return u32(buf)
  }
}

exports.allo = predicate(
  binding.simdle_native_allo_v128_u8,
  binding.simdle_native_allo_v128_u16,
  binding.simdle_native_allo_v128_u32
)

exports.allz = predicate(
  binding.simdle_native_allz_v128_u8,
  binding.simdle_native_allz_v128_u16,
  binding.simdle_native_allz_v128_u32
)

exports.and = binary(
  binding.simdle_native_and_v128_u8,
  binding.simdle_native_and_v128_u16,
  binding.simdle_native_and_v128_u32
)

exports.clear = binary(
  binding.simdle_native_clear_v128_u8,
  binding.simdle_native_clear_v128_u16,
  binding.simdle_native_clear_v128_u32
)

exports.clo = unary(
  binding.simdle_native_clo_v128_u8,
  binding.simdle_native_clo_v128_u16,
  binding.simdle_native_clo_v128_u32
)

exports.clz = unary(
  binding.simdle_native_clz_v128_u8,
  binding.simdle_native_clz_v128_u16,
  binding.simdle_native_clz_v128_u32
)

exports.cnt = unary(
  binding.simdle_native_cnt_v128_u8,
  binding.simdle_native_cnt_v128_u16,
  binding.simdle_native_cnt_v128_u32
)

exports.cto = unary(
  binding.simdle_native_cto_v128_u8,
  binding.simdle_native_cto_v128_u16,
  binding.simdle_native_cto_v128_u32
)

exports.ctz = unary(
  binding.simdle_native_ctz_v128_u8,
  binding.simdle_native_ctz_v128_u16,
  binding.simdle_native_ctz_v128_u32
)

exports.not = unary(
  binding.simdle_native_not_v128_u8,
  binding.simdle_native_not_v128_u16,
  binding.simdle_native_not_v128_u32
)

exports.or = binary(
  binding.simdle_native_or_v128_u8,
  binding.simdle_native_or_v128_u16,
  binding.simdle_native_or_v128_u32
)

exports.sum = reduce(
  binding.simdle_native_sum_v128_u8,
  binding.simdle_native_sum_v128_u16,
  binding.simdle_native_sum_v128_u32
)

exports.xor = binary(
  binding.simdle_native_xor_v128_u8,
  binding.simdle_native_xor_v128_u16,
  binding.simdle_native_xor_v128_u32
)
{
  "name": "simdle-native",
  "version": "1.3.9",
  "description": "libsimdle JavaScript bindings for Node.js",
  "main": "index.js",
  "files": [
    "index.js",
    "binding.cc",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check .",
    "test": "npm run lint && npm run test:bare && npm run test:node",
    "test:bare": "bare test.mjs",
    "test:node": "node test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/simdle-native.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/simdle-native/issues"
  },
  "homepage": "https://github.com/holepunchto/simdle-native#readme",
  "dependencies": {
    "b4a": "^1.6.0",
    "require-addon": "^1.1.0"
  },
  "devDependencies": {
    "bare-compat-napi": "^1.3.2",
    "brittle": "^3.1.0",
    "cmake-bare": "^1.1.7",
    "cmake-fetch": "^1.1.0",
    "cmake-napi": "^1.0.2",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  }
}
const b4a = require('b4a')
const scalar = require('./scalar')

function view (buf, n) {
  if (n === buf.BYTES_PER_ELEMENT) return buf

  let TypedArray

  if (n === 1) TypedArray = Uint8Array
  else if (n === 2) TypedArray = Uint16Array
  else TypedArray = Uint32Array

  return new TypedArray(buf.buffer, buf.byteOffset, buf.byteLength / n)
}

function unary (u8, u16 = u8, u32 = u16) {
  return function unary (buf, result = b4a.allocUnsafe(buf.byteLength)) {
    if (buf.byteLength % 16 !== 0) {
      throw new Error('Buffer length must be a multiple of 16')
    }

    if (buf.byteLength !== result.byteLength) {
      throw new Error('Length of result buffer is insufficient')
    }

    const n = buf.BYTES_PER_ELEMENT

    if (n === 1) u8(buf, view(result, n))
    else if (n === 2) u16(buf, view(result, n))
    else u32(buf, view(result, n))

    return result
  }
}

function binary (u8, u16 = u8, u32 = u16) {
  return function binary (a, b, result = b4a.allocUnsafe(a.byteLength)) {
    if (a.byteLength % 16 !== 0) {
      throw new Error('Buffer length must be a multiple of 16')
    }

    if (a.byteLength !== b.byteLength || a.byteLength !== result.byteLength) {
      throw new Error('Buffers must be the same length')
    }

    const n = a.BYTES_PER_ELEMENT

    if (n === 1) u8(a, b, view(result, n))
    else if (n === 2) u16(a, b, view(result, n))
    else u32(a, b, view(result, n))

    return result
  }
}

function reduce (u8, u16 = u8, u32 = u16) {
  return function reduce (buf) {
    if (buf.byteLength % 16 !== 0) {
      throw new Error('Buffer length must be a multiple of 16')
    }

    const n = buf.BYTES_PER_ELEMENT

    if (n === 1) return u8(buf)
    if (n === 2) return u16(buf)
    return u32(buf)
  }
}

exports.allo = function allo (buf) {
  if (buf.byteLength % 16 !== 0) {
    throw new Error('Buffer length must be a multiple of 16')
  }

  const m = 2 ** (buf.BYTES_PER_ELEMENT * 8) - 1

  for (let i = 0, n = buf.length; i < n; i++) {
    if (buf[i] !== m) return false
  }

  return true
}

exports.allz = function allz (buf) {
  if (buf.byteLength % 16 !== 0) {
    throw new Error('Buffer length must be a multiple of 16')
  }

  for (let i = 0, n = buf.length; i < n; i++) {
    if (buf[i] !== 0) return false
  }

  return true
}

exports.and = binary(
  (a, b, result) => {
    for (let i = 0, n = result.length; i < n; i++) {
      result[i] = a[i] & b[i]
    }
  }
)

exports.clear = binary(
  (a, b, result) => {
    for (let i = 0, n = result.length; i < n; i++) {
      result[i] = a[i] & ~b[i]
    }
  }
)

exports.clo = unary(
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = 24 - scalar.clo(buf[i])
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = 16 - scalar.clo(buf[i])
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = scalar.clo(buf[i])
    }
  }
)

exports.clz = unary(
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = 24 - scalar.clz(buf[i])
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = 16 - scalar.clz(buf[i])
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = scalar.clz(buf[i])
    }
  }
)

exports.cnt = unary(
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = scalar.cnt(buf[i]) & 0xff
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = scalar.cnt(buf[i]) & 0xffff
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = scalar.cnt(buf[i])
    }
  }
)

exports.cto = unary(
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = Math.min(scalar.cto(buf[i]), 8)
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = Math.min(scalar.cto(buf[i]), 16)
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = scalar.cto(buf[i])
    }
  }
)

exports.ctz = unary(
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = Math.min(scalar.ctz(buf[i]), 8)
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = Math.min(scalar.ctz(buf[i]), 16)
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = scalar.ctz(buf[i])
    }
  }
)

exports.not = unary(
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = ~buf[i]
    }
  }
)

exports.or = binary(
  (a, b, result) => {
    for (let i = 0, n = result.length; i < n; i++) {
      result[i] = a[i] | b[i]
    }
  }
)

exports.sum = reduce(
  (buf) => {
    let result = 0n

    for (let i = 0, n = buf.length; i < n; i++) {
      result += BigInt(buf[i])
    }

    return result
  }
)

exports.xor = binary(
  (a, b, result) => {
    for (let i = 0, n = result.length; i < n; i++) {
      result[i] = a[i] ^ b[i]
    }
  }
)
try {
  module.exports = require('simdle-native')
} catch {
  module.exports = require('./fallback')
}
{
  "name": "simdle-universal",
  "version": "1.1.2",
  "description": "Universal wrapper for libsimdle with a JavaScript fallback",
  "main": "index.js",
  "files": [
    "fallback.js",
    "index.js",
    "scalar.js"
  ],
  "browser": {
    "./index.js": "./fallback.js"
  },
  "scripts": {
    "test": "standard && brittle test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/simdle-universal.git"
  },
  "author": "Kasper Isager Dalsgarð <kasper@funktionel.co>",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/holepunchto/simdle-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/simdle-universal#readme",
  "dependencies": {
    "b4a": "^1.6.0"
  },
  "optionalDependencies": {
    "simdle-native": "^1.1.1"
  },
  "devDependencies": {
    "brittle": "^3.1.0",
    "standard": "^17.0.0"
  }
}
const clz = exports.clz = function clz (n) {
  return Math.clz32(n)
}

exports.clo = function clo (n) {
  return clz(~n)
}

const ctz = exports.ctz = function ctz (n) {
  return 32 - (n === 0 ? 0 : (clz(n & -n) + 1))
}

exports.cto = function cto (n) {
  return ctz(~n)
}

exports.cnt = function cnt (n) {
  n = n - ((n >>> 1) & 0x55555555)
  n = (n & 0x33333333) + ((n >>> 2) & 0x33333333)
  n = (n + (n >>> 4)) & 0x0f0f0f0f
  n = (n * 0x01010101) >>> 24
  return n
}
require.addon = require('require-addon')
module.exports = require.addon('.', __filename)
const assert = require('assert')
const binding = require('./binding')
const { isNode } = require('which-runtime')

const OPTIONAL = Buffer.from(new ArrayBuffer(0))

module.exports = exports = { ...binding }

// memory

exports.sodium_memzero = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  binding.sodium_memzero(buf)
}

exports.sodium_mlock = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  const res = binding.sodium_mlock(buf)

  if (res !== 0) throw new Error('memory lock failed')
}

exports.sodium_munlock = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  const res = binding.sodium_munlock(buf)

  if (res !== 0) throw new Error('memory unlock failed')
}

exports.sodium_malloc = function (size) {
  assert(size >= 0, 'invalid size')

  const buf = Buffer.from(binding.sodium_malloc(size))
  buf.secure = true
  return buf
}

exports.sodium_free = function (buf) {
  if (!buf || !buf.secure) return

  binding.sodium_free(buf.buffer)
}

exports.sodium_mprotect_noaccess = function (buf) {
  const res = binding.sodium_mprotect_noaccess(buf.buffer)

  if (res !== 0) throw new Error('failed to lock buffer')
}

exports.sodium_mprotect_readonly = function (buf) {
  const res = binding.sodium_mprotect_readonly(buf.buffer)

  if (res !== 0) throw new Error('failed to unlock buffer')
}

exports.sodium_mprotect_readwrite = function (buf) {
  const res = binding.sodium_mprotect_readwrite(buf.buffer)

  if (res !== 0) throw new Error('failed to unlock buffer')
}

// crypto_randombytes

exports.randombytes_buf = function (buffer) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')

  binding.randombytes_buf(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

exports.randombytes_buf_deterministic = function (buffer, seed) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    seed.byteLength === binding.randombytes_SEEDBYTES,
    "seed must be 'randombytes_SEEDBYTES' bytes"
  )

  binding.randombytes_buf_deterministic(
    buffer.buffer,
    buffer.byteOffset,
    buffer.byteLength,

    seed.buffer,
    seed.byteOffset,
    seed.byteLength
  )
}

// sodium_helpers

exports.sodium_memcmp = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  return binding.sodium_memcmp(a, b)
}

exports.sodium_add = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  binding.sodium_add(a, b)
}

exports.sodium_sub = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  binding.sodium_sub(a, b)
}

exports.sodium_compare = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  return binding.sodium_compare(a, b)
}

exports.sodium_is_zero = function (buffer, length) {
  if (length === undefined) length = buffer.byteLength

  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(length >= 0 && length <= buffer.byteLength, 'invalid length')

  return binding.sodium_is_zero(buffer, length)
}

exports.sodium_pad = function (buffer, unpaddedBuflen, blockSize) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(unpaddedBuflen <= buffer.byteLength, 'unpadded length cannot exceed buffer length')
  assert(blockSize <= buffer.byteLength, 'block size cannot exceed buffer length')
  assert(blockSize >= 1, 'block size must be at least 1 byte')
  assert(
    buffer.byteLength >= unpaddedBuflen + (blockSize - (unpaddedBuflen % blockSize)),
    'buf not long enough'
  )

  return binding.sodium_pad(buffer, unpaddedBuflen, blockSize)
}

exports.sodium_unpad = function (buffer, paddedBuflen, blockSize) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(paddedBuflen <= buffer.byteLength, 'unpadded length cannot exceed buffer length')
  assert(blockSize <= buffer.byteLength, 'block size cannot exceed buffer length')
  assert(blockSize >= 1, 'block size must be at least 1 byte')

  return binding.sodium_unpad(buffer, paddedBuflen, blockSize)
}

// crypto_sign

exports.crypto_sign_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )
  assert(
    seed.byteLength === binding.crypto_sign_SEEDBYTES,
    "seed must be 'crypto_sign_SEEDBYTES' bytes"
  )

  const res = binding.crypto_sign_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign = function (sm, m, sk) {
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sm.byteLength === binding.crypto_sign_BYTES + m.byteLength,
    "sm must be 'm.byteLength + crypto_sign_BYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign(sm, m, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_open = function (m, sm, pk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sm.byteLength >= binding.crypto_sign_BYTES,
    "sm must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    m.byteLength === sm.byteLength - binding.crypto_sign_BYTES,
    "m must be 'sm.byteLength - crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_open(m, sm, pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_open = function (m, sm, pk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sm.byteLength >= binding.crypto_sign_BYTES,
    "sm must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    m.byteLength === sm.byteLength - binding.crypto_sign_BYTES,
    "m must be 'sm.byteLength - crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  return binding.crypto_sign_open(m, sm, pk)
}

exports.crypto_sign_detached = function (sig, m, sk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(sig.byteLength === binding.crypto_sign_BYTES, "sig must be 'crypto_sign_BYTES' bytes")
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_detached(sig, m, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_verify_detached = function (sig, m, pk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sig.byteLength >= binding.crypto_sign_BYTES,
    "sig must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  return binding.crypto_sign_verify_detached(
    sig.buffer,
    sig.byteOffset,
    sig.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    pk.buffer,
    pk.byteOffset,
    pk.byteLength
  )
}

exports.crypto_sign_ed25519_sk_to_pk = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_sk_to_pk(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_ed25519_pk_to_curve25519 = function (x25519pk, ed25519pk) {
  assert(ArrayBuffer.isView(x25519pk), 'x25519pk must be a typed array')
  assert(ArrayBuffer.isView(ed25519pk), 'ed25519pk must be a typed array')
  assert(
    x25519pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "x25519pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    ed25519pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "ed25519pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_pk_to_curve25519(x25519pk, ed25519pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_ed25519_sk_to_curve25519 = function (x25519sk, ed25519sk) {
  assert(ArrayBuffer.isView(x25519sk), 'x25519sk must be a typed array')
  assert(ArrayBuffer.isView(ed25519sk), 'ed25519sk must be a typed array')
  assert(
    x25519sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "x25519sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const edLen = ed25519sk.byteLength

  assert(
    edLen === binding.crypto_sign_SECRETKEYBYTES || edLen === binding.crypto_box_SECRETKEYBYTES,
    "ed25519sk must be 'crypto_sign_SECRETKEYBYTES' or 'crypto_sign_SECRETKEYBYTES - crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_sk_to_curve25519(x25519sk, ed25519sk)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_box

exports.crypto_box_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    seed.byteLength === binding.crypto_box_SEEDBYTES,
    "seed must be 'crypto_box_SEEDBYTES' bytes"
  )

  const res = binding.crypto_box_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_easy = function (c, m, n, pk, sk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength === m.byteLength + exports.crypto_box_MACBYTES,
    "c must be 'm.byteLength + crypto_box_MACBYTES' bytes"
  )
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_easy(c, m, n, pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_detached = function (c, mac, m, n, pk, sk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(mac.byteLength === exports.crypto_box_MACBYTES, "mac must be 'crypto_box_MACBYTES' bytes")
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_detached(c, mac, m, n, pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_open_easy = function (m, c, n, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength >= exports.crypto_box_MACBYTES,
    "c must be at least 'crypto_box_MACBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - exports.crypto_box_MACBYTES,
    "m must be 'c.byteLength - crypto_box_MACBYTES' bytes"
  )
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_open_easy(m, c, n, pk, sk)
}

exports.crypto_box_open_detached = function (m, c, mac, n, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(mac.byteLength === exports.crypto_box_MACBYTES, "mac must be 'crypto_box_MACBYTES' bytes")
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_open_detached(m, c, mac, n, pk, sk)
}

exports.crypto_box_seal = function (c, m, pk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    c.byteLength === m.byteLength + exports.crypto_box_SEALBYTES,
    "c must be 'm.byteLength + crypto_box_SEALBYTES' bytes"
  )
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_box_seal(c, m, pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_seal_open = function (m, c, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength >= exports.crypto_box_SEALBYTES,
    "c must be at least 'crypto_box_SEALBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - exports.crypto_box_SEALBYTES,
    "m must be 'c.byteLength - crypto_box_SEALBYTES' bytes"
  )
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_seal_open(
    m.buffer,
    m.byteOffset,
    m.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    pk.buffer,
    pk.byteOffset,
    pk.byteLength,

    sk.buffer,
    sk.byteOffset,
    sk.byteLength
  )
}

// crypto_secretbox

exports.crypto_secretbox_easy = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_secretbox_MACBYTES,
    "c must be 'm.byteLength + crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretbox_easy(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretbox_open_easy = function (m, c, n, k) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    c.byteLength >= binding.crypto_secretbox_MACBYTES,
    "c must be at least 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - binding.crypto_secretbox_MACBYTES,
    "m must be 'c.byteLength - crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  return binding.crypto_secretbox_open_easy(m, c, n, k)
}

exports.crypto_secretbox_detached = function (c, mac, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    mac.byteLength === binding.crypto_secretbox_MACBYTES,
    "mac must be 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretbox_detached(c, mac, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretbox_open_detached = function (m, c, mac, n, k) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(
    mac.byteLength === binding.crypto_secretbox_MACBYTES,
    "mac must be 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  return binding.crypto_secretbox_open_detached(m, c, mac, n, k)
}

// crypto_generichash

exports.crypto_generichash = function (output, input, key) {
  if (!key) key = OPTIONAL

  assert(ArrayBuffer.isView(output), 'output must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    output.byteLength >= binding.crypto_generichash_BYTES_MIN &&
      output.byteLength <= binding.crypto_generichash_BYTES_MAX,
    'output must be between crypto_generichash_BYTES_MIN and crypto_generichash_BYTES_MAX bytes'
  )

  if (key !== OPTIONAL) {
    assert(ArrayBuffer.isView(key), 'key must be a typed array')
    assert(
      key.byteLength >= binding.crypto_generichash_KEYBYTES_MIN &&
        key.byteLength <= binding.crypto_generichash_KEYBYTES_MAX,
      'key must be between crypto_generichash_KEYBYTES_MIN and crypto_generichash_KEYBYTES_MAX bytes'
    )
  }

  const res = binding.crypto_generichash(
    output.buffer,
    output.byteOffset,
    output.byteLength,

    input.buffer,
    input.byteOffset,
    input.byteLength,

    key.buffer,
    key.byteOffset,
    key.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_batch = function (output, batch, key) {
  assert(ArrayBuffer.isView(output), 'output must be a typed array')

  if (isNode || batch.length < 4) {
    const res = binding.crypto_generichash_batch(output, batch, !!key, key || OPTIONAL)
    if (res !== 0) throw new Error('status: ' + res)
  } else {
    const state = Buffer.alloc(binding.crypto_generichash_STATEBYTES)

    exports.crypto_generichash_init(state, key, output.byteLength)

    for (const buf of batch) {
      exports.crypto_generichash_update(state, buf)
    }

    exports.crypto_generichash_final(state, output)
  }
}

exports.crypto_generichash_keygen = function (key) {
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(
    key.byteLength === binding.crypto_generichash_KEYBYTES,
    "key must be 'crypto_generichash_KEYBYTES' bytes"
  )

  const res = binding.crypto_generichash_keygen(key.buffer, key.byteOffset, key.byteLength)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_init = function (state, key, outputLength) {
  if (!key) key = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_init(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    key.buffer,
    key.byteOffset,
    key.byteLength,

    outputLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_update(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    input.buffer,
    input.byteOffset,
    input.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_final = function (state, output) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(output), 'output must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_final(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    output.buffer,
    output.byteOffset,
    output.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

// secretstream

exports.crypto_secretstream_xchacha20poly1305_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  binding.crypto_secretstream_xchacha20poly1305_keygen(k.buffer, k.byteOffset, k.byteLength)
}

exports.crypto_secretstream_xchacha20poly1305_init_push = function (state, header, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(header), 'header must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    header.byteLength === binding.crypto_secretstream_xchacha20poly1305_HEADERBYTES,
    "header must be 'crypto_secretstream_xchacha20poly1305_HEADERBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_init_push(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    header.buffer,
    header.byteOffset,
    header.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretstream_xchacha20poly1305_init_pull = function (state, header, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(header), 'header must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    header.byteLength === binding.crypto_secretstream_xchacha20poly1305_HEADERBYTES,
    "header must be 'crypto_secretstream_xchacha20poly1305_HEADERBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_init_pull(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    header.buffer,
    header.byteOffset,
    header.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretstream_xchacha20poly1305_push = function (state, c, m, ad, tag) {
  if (!ad) ad = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    c.byteLength === m.byteLength + binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "c must be 'm.byteLength + crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_push(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    ad.buffer,
    ad.byteOffset,
    ad.byteLength,

    tag
  )

  if (res < 0) throw new Error('push failed')

  return res
}

exports.crypto_secretstream_xchacha20poly1305_pull = function (state, m, tag, c, ad) {
  if (!ad) ad = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(tag), 'tag must be a typed array')
  assert(tag.byteLength === 1, 'tag must be 1 byte')

  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    c.byteLength >= binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "c must be at least 'crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "m must be 'c.byteLength - crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_pull(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    tag.buffer,
    tag.byteOffset,
    tag.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    ad.buffer,
    ad.byteOffset,
    ad.byteLength
  )

  if (res < 0) throw new Error('pull failed')

  return res
}

exports.crypto_secretstream_xchacha20poly1305_rekey = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )

  binding.crypto_secretstream_xchacha20poly1305_rekey(
    state.buffer,
    state.byteOffset,
    state.byteLength
  )
}

// crypto_stream

exports.crypto_stream = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xor(
    c.buffer,
    c.byteOffset,
    c.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    n.buffer,
    n.byteOffset,
    n.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_auth

exports.crypto_auth = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(out.byteLength === binding.crypto_auth_BYTES, "out must be 'crypto_auth_BYTES' bytes")
  assert(k.byteLength === binding.crypto_auth_KEYBYTES, "k must be 'crypto_auth_KEYBYTES' bytes")

  const res = binding.crypto_auth(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_auth_verify = function (h, input, k) {
  assert(ArrayBuffer.isView(h), 'h must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(h.byteLength === binding.crypto_auth_BYTES, "h must be 'crypto_auth_BYTES' bytes")
  assert(k.byteLength === binding.crypto_auth_KEYBYTES, "k must be 'crypto_auth_KEYBYTES' bytes")

  return binding.crypto_auth_verify(h, input, k)
}

// crypto_onetimeauth

exports.crypto_onetimeauth = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    out.byteLength === binding.crypto_onetimeauth_BYTES,
    "out must be 'crypto_onetimeauth_BYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_init = function (state, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_init(state, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )
  assert(
    out.byteLength === binding.crypto_onetimeauth_BYTES,
    "out must be 'crypto_onetimeauth_BYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_verify = function (h, input, k) {
  assert(ArrayBuffer.isView(h), 'h must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    h.byteLength === binding.crypto_onetimeauth_BYTES,
    "h must be 'crypto_onetimeauth_BYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  return binding.crypto_onetimeauth_verify(h, input, k)
}

// crypto_pwhash

exports.crypto_pwhash = function (out, passwd, salt, opslimit, memlimit, alg) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_BYTES_MIN,
    "out must be at least 'crypto_pwhash_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_BYTES_MAX,
    "out must be at most 'crypto_pwhash_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_SALTBYTES,
    "salt must be 'crypto_pwhash_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )
  assert(alg >= 1 && alg <= 2, 'alg must be either Argon2i 1.3 or Argon2id 1.3')

  const res = binding.crypto_pwhash(out, passwd, salt, opslimit, memlimit, alg)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_async = function (
  out,
  passwd,
  salt,
  opslimit,
  memlimit,
  alg,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_BYTES_MIN,
    "out must be at least 'crypto_pwhash_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_BYTES_MAX,
    "out must be at most 'crypto_pwhash_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_SALTBYTES,
    "salt must be 'crypto_pwhash_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )
  assert(alg >= 1 && alg <= 2, 'alg must be either Argon2i 1.3 or Argon2id 1.3')

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    opslimit,
    memlimit,
    alg,

    done
  )

  return promise
}

exports.crypto_pwhash_str = function (out, passwd, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_STRBYTES,
    "out must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(typeof opslimit === 'number', 'opslimit must be a number')
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(typeof memlimit === 'number', 'memlimit must be a number')
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_str(out, passwd, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_str_async = function (out, passwd, opslimit, memlimit, callback = undefined) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_STRBYTES,
    "out must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(typeof opslimit === 'number', 'opslimit must be a number')
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(typeof memlimit === 'number', 'memlimit must be a number')
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_str_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_str_verify = function (str, passwd) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )

  return binding.crypto_pwhash_str_verify(str, passwd)
}

exports.crypto_pwhash_str_verify_async = function (str, passwd, callback = undefined) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  const [done, promise] = checkStatus(callback, true)

  binding.crypto_pwhash_str_verify_async(
    str.buffer,
    str.byteOffset,
    str.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    done
  )

  return promise
}

exports.crypto_pwhash_str_needs_rehash = function (str, opslimit, memlimit) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  return binding.crypto_pwhash_str_needs_rehash(str, opslimit, memlimit)
}

exports.crypto_pwhash_scryptsalsa208sha256 = function (out, passwd, salt, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MIN,
    "out must be at least 'crypto_pwhash_scryptsalsa208sha256_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MAX,
    "out must be at most 'crypto_pwhash_scryptsalsa208sha256_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_SALTBYTES,
    "salt must be 'crypto_pwhash_scryptsalsa208sha256_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_scryptsalsa208sha256(out, passwd, salt, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_scryptsalsa208sha256_async = function (
  out,
  passwd,
  salt,
  opslimit,
  memlimit,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MIN,
    "out must be at least 'crypto_pwhash_scryptsalsa208sha256_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MAX,
    "out must be at most 'crypto_pwhash_scryptsalsa208sha256_BYTES_MAX' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    salt.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_SALTBYTES,
    "salt must be 'crypto_pwhash_scryptsalsa208sha256_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_scryptsalsa208sha256_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str_async = function (
  out,
  passwd,
  opslimit,
  memlimit,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "out must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_scryptsalsa208sha256_str_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str = function (out, passwd, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "out must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_scryptsalsa208sha256_str(out, passwd, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_scryptsalsa208sha256_str_verify_async = function (
  str,
  passwd,
  callback = undefined
) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  const [done, promise] = checkStatus(callback, true)

  binding.crypto_pwhash_scryptsalsa208sha256_str_verify_async(
    str.buffer,
    str.byteOffset,
    str.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str_verify = function (str, passwd) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  return binding.crypto_pwhash_scryptsalsa208sha256_str_verify(str, passwd)
}

exports.crypto_pwhash_scryptsalsa208sha256_str_needs_rehash = function (str, opslimit, memlimit) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  return binding.crypto_pwhash_scryptsalsa208sha256_str_needs_rehash(str, opslimit, memlimit)
}

// crypto_kx

exports.crypto_kx_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "pk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "sk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    pk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "pk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "sk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    seed.byteLength === binding.crypto_kx_SEEDBYTES,
    "seed must be 'crypto_kx_SEEDBYTES' bytes"
  )

  const res = binding.crypto_kx_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_client_session_keys = function (rx, tx, clientPk, clientSk, serverPk) {
  if (!rx) rx = undefined
  if (!tx) tx = undefined

  assert(rx || tx, 'at least one session key must be specified')

  if (rx) {
    assert(ArrayBuffer.isView(rx), 'rx must be a typed array')
    assert(
      rx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "rx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  if (tx) {
    assert(ArrayBuffer.isView(tx), 'tx must be a typed array')
    assert(
      tx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "tx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  assert(ArrayBuffer.isView(clientPk), 'clientPk must be a typed array')
  assert(ArrayBuffer.isView(clientSk), 'clientSk must be a typed array')
  assert(ArrayBuffer.isView(serverPk), 'serverPk must be a typed array')
  assert(
    clientPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "clientPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    clientSk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "clientSk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    serverPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "serverPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_client_session_keys(rx, tx, clientPk, clientSk, serverPk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_server_session_keys = function (rx, tx, serverPk, serverSk, clientPk) {
  if (!rx) rx = undefined
  if (!tx) tx = undefined

  assert(rx || tx, 'at least one session key must be specified')

  if (rx) {
    assert(ArrayBuffer.isView(rx), 'rx must be a typed array')
    assert(
      rx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "rx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  if (tx) {
    assert(ArrayBuffer.isView(tx), 'tx must be a typed array')
    assert(
      tx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "tx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  assert(ArrayBuffer.isView(serverPk), 'serverPk must be a typed array')
  assert(ArrayBuffer.isView(serverSk), 'serverSk must be a typed array')
  assert(ArrayBuffer.isView(clientPk), 'clientPk must be a typed array')
  assert(
    serverPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "serverPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    serverSk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "serverSk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    clientPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "clientPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_server_session_keys(rx, tx, serverPk, serverSk, clientPk)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_scalarmult

exports.crypto_scalarmult_base = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_BYTES,
    "q must be 'crypto_scalarmult_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_SCALARBYTES,
    "n must be 'crypto_scalarmult_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_base(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_BYTES,
    "q must be 'crypto_scalarmult_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_SCALARBYTES,
    "n must be 'crypto_scalarmult_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_BYTES,
    "p must be 'crypto_scalarmult_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_base = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_base(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519 = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "p must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_is_valid_point = function (p) {
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )

  return binding.crypto_core_ed25519_is_valid_point(p)
}

exports.crypto_core_ed25519_from_uniform = function (p, r) {
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_UNIFORMBYTES,
    "r must be 'crypto_core_ed25519_UNIFORMBYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_from_uniform(p, r)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_base_noclamp = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_base_noclamp(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_noclamp = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "p must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_noclamp(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_core

exports.crypto_core_ed25519_add = function (r, p, q) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_BYTES,
    "r must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_core_ed25519_BYTES,
    "q must be 'crypto_core_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_add(r, p, q)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_sub = function (r, p, q) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_BYTES,
    "r must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_core_ed25519_BYTES,
    "q must be 'crypto_core_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_sub(r, p, q)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_scalar_random = function (r) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "r must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_random(r)
}

exports.crypto_core_ed25519_scalar_reduce = function (r, s) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "r must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_NONREDUCEDSCALARBYTES,
    "s must be 'crypto_core_ed25519_NONREDUCEDSCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_reduce(r, s)
}

exports.crypto_core_ed25519_scalar_invert = function (recip, s) {
  assert(ArrayBuffer.isView(recip), 'recip must be a typed array')
  assert(
    recip.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "recip must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_invert(recip, s)
}

exports.crypto_core_ed25519_scalar_negate = function (neg, s) {
  assert(ArrayBuffer.isView(neg), 'neg must be a typed array')
  assert(
    neg.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "neg must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_negate(neg, s)
}

exports.crypto_core_ed25519_scalar_complement = function (comp, s) {
  assert(ArrayBuffer.isView(comp), 'comp must be a typed array')
  assert(
    comp.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "comp must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_complement(comp, s)
}

exports.crypto_core_ed25519_scalar_add = function (z, x, y) {
  assert(ArrayBuffer.isView(z), 'z must be a typed array')
  assert(
    z.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "z must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(x), 'x must be a typed array')
  assert(
    x.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "x must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(y), 'y must be a typed array')
  assert(
    y.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "y must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_add(z, x, y)
}

exports.crypto_core_ed25519_scalar_sub = function (z, x, y) {
  assert(ArrayBuffer.isView(z), 'z must be a typed array')
  assert(
    z.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "z must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(x), 'x must be a typed array')
  assert(
    x.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "x must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(y), 'y must be a typed array')
  assert(
    y.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "y must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_sub(z, x, y)
}

// crypto_shorthash

exports.crypto_shorthash = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_shorthash_BYTES,
    "out must be 'crypto_shorthash_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_shorthash_KEYBYTES,
    "k must be 'crypto_shorthash_KEYBYTES' bytes"
  )

  const res = binding.crypto_shorthash(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_kdf

exports.crypto_kdf_keygen = function (key) {
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(key.byteLength === binding.crypto_kdf_KEYBYTES, "key must be 'crypto_kdf_KEYBYTES' bytes")

  binding.crypto_kdf_keygen(key)
}

exports.crypto_kdf_derive_from_key = function (subkey, subkeyId, ctx, key) {
  assert(ArrayBuffer.isView(subkey), 'subkey must be a typed array')
  assert(
    subkey.byteLength >= binding.crypto_kdf_BYTES_MIN,
    "subkey must be at least 'crypto_kdf_BYTES_MIN' bytes"
  )
  assert(
    subkey.byteLength <= binding.crypto_kdf_BYTES_MAX,
    "subkey must be at most 'crypto_kdf_BYTES_MAX' bytes"
  )
  assert(ArrayBuffer.isView(ctx), 'ctx must be a typed array')
  assert(
    ctx.byteLength === binding.crypto_kdf_CONTEXTBYTES,
    "ctx must be 'crypto_kdf_CONTEXTBYTES' bytes"
  )
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(key.byteLength === binding.crypto_kdf_KEYBYTES, "key must be 'crypto_kdf_KEYBYTES' bytes")

  const res = binding.crypto_kdf_derive_from_key(subkey, subkeyId, ctx, key)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_hash

exports.crypto_hash = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(out.byteLength === binding.crypto_hash_BYTES, "out must be 'crypto_hash_BYTES' bytes")

  const res = binding.crypto_hash(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256 = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha256_BYTES,
    "out must be 'crypto_hash_sha256_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha256(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_init = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_init(state)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha256_BYTES,
    "out must be 'crypto_hash_sha256_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512 = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha512_BYTES,
    "out must be 'crypto_hash_sha512_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha512(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_init = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_init(state)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha512_BYTES,
    "out must be 'crypto_hash_sha512_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_aead

exports.crypto_aead_xchacha20poly1305_ietf_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  binding.crypto_aead_xchacha20poly1305_ietf_keygen(k)
}

exports.crypto_aead_xchacha20poly1305_ietf_encrypt = function (c, m, ad, nsec, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "c must be 'm.byteLength + crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(c.byteLength <= 0xffffffff, 'c.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_encrypt(c, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_decrypt = function (m, nsec, c, ad, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "m must be 'c.byteLength - crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(m.byteLength <= 0xffffffff, 'm.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_decrypt(m, c, ad, npub, k)

  if (res < 0) throw new Error('could not verify data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_encrypt_detached = function (
  c,
  mac,
  m,
  ad,
  nsec,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_encrypt_detached(c, mac, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_decrypt_detached = function (
  m,
  nsec,
  c,
  mac,
  ad,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_decrypt_detached(m, c, mac, ad, npub, k)

  if (res !== 0) throw new Error('could not verify data')
}

exports.crypto_aead_chacha20poly1305_ietf_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  binding.crypto_aead_chacha20poly1305_ietf_keygen(k)
}

exports.crypto_aead_chacha20poly1305_ietf_encrypt = function (c, m, ad, nsec, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "c must be 'm.byteLength + crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(c.byteLength <= 0xffffffff, 'c.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_encrypt(c, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_decrypt = function (m, nsec, c, ad, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "m must be 'c.byteLength - crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(m.byteLength <= 0xffffffff, 'm.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_decrypt(m, c, ad, npub, k)

  if (res < 0) throw new Error('could not verify data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_encrypt_detached = function (
  c,
  mac,
  m,
  ad,
  nsec,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_encrypt_detached(c, mac, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_decrypt_detached = function (
  m,
  nsec,
  c,
  mac,
  ad,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_decrypt_detached(m, c, mac, ad, npub, k)

  if (res !== 0) throw new Error('could not verify data')
}

// crypto_stream

exports.crypto_stream_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  binding.crypto_stream_xor_wrap_init(state, n, k)
}

exports.crypto_stream_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_xor_wrap_update(state, c, m)
}

exports.crypto_stream_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_xor_wrap_final(state)
}

exports.crypto_stream_chacha20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  binding.crypto_stream_chacha20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_chacha20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_chacha20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_chacha20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_chacha20_xor_wrap_final(state)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  binding.crypto_stream_chacha20_ietf_xor_wrap_init(state, n, k)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_chacha20_ietf_xor_wrap_update(state, c, m)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_chacha20_ietf_xor_wrap_final(state)
}

exports.crypto_stream_xchacha20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  binding.crypto_stream_xchacha20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_xchacha20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_xchacha20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_xchacha20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_xchacha20_xor_wrap_final(state)
}

exports.crypto_stream_salsa20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  binding.crypto_stream_salsa20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_salsa20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_salsa20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_salsa20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_salsa20_xor_wrap_final(state)
}

// experimental

exports.extension_tweak_ed25519_base = function (n, p, ns) {
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.extension_tweak_ed25519_BYTES,
    "p must be 'extension_tweak_ed25519_BYTES' bytes"
  )

  binding.extension_tweak_ed25519_base(n, p, ns)
}

exports.extension_tweak_ed25519_sign_detached = function (sig, m, scalar, pk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(sig.byteLength === binding.crypto_sign_BYTES, "sig must be 'crypto_sign_BYTES' bytes")
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  if (pk) {
    assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
    assert(
      pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
      "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
    )
  }

  const res = binding.extension_tweak_ed25519_sign_detached(sig, m, scalar, pk)

  if (res !== 0) throw new Error('failed to compute signature')
}

exports.extension_tweak_ed25519_sk_to_scalar = function (n, sk) {
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  binding.extension_tweak_ed25519_sk_to_scalar(n, sk)
}

exports.extension_tweak_ed25519_scalar = function (scalarOut, scalar, ns) {
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_scalar(scalarOut, scalar, ns)
}

exports.extension_tweak_ed25519_pk = function (tpk, pk, ns) {
  assert(ArrayBuffer.isView(tpk), 'tpk must be a typed array')
  assert(
    tpk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "tpk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_pk(tpk, pk, ns)

  if (res !== 0) throw new Error('failed to tweak public key')
}

exports.extension_tweak_ed25519_keypair = function (pk, scalarOut, scalarIn, ns) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.extension_tweak_ed25519_BYTES,
    "pk must be 'extension_tweak_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarIn), 'scalarIn must be a typed array')
  assert(
    scalarIn.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarIn must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_keypair(pk, scalarOut, scalarIn, ns)
}

exports.extension_tweak_ed25519_scalar_add = function (scalarOut, scalar, n) {
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_scalar_add(scalarOut, scalar, n)
}

exports.extension_tweak_ed25519_pk_add = function (tpk, pk, p) {
  assert(ArrayBuffer.isView(tpk), 'tpk must be a typed array')
  assert(
    tpk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "tpk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "p must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_pk_add(tpk, pk, p)

  if (res !== 0) throw new Error('failed to add tweak to public key')
}

exports.extension_tweak_ed25519_keypair_add = function (pk, scalarOut, scalarIn, tweak) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.extension_tweak_ed25519_BYTES,
    "pk must be 'extension_tweak_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarIn), 'scalarIn must be a typed array')
  assert(
    scalarIn.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarIn must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(tweak), 'tweak must be a typed array')
  assert(
    tweak.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "tweak must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_keypair_add(pk, scalarOut, scalarIn, tweak)

  if (res !== 0) throw new Error('failed to add tweak to keypair')
}

exports.extension_pbkdf2_sha512_async = function (out, passwd, salt, iter, outlen, callback) {
  assert(
    iter >= binding.extension_pbkdf2_sha512_ITERATIONS_MIN,
    "iter must be at least 'extension_pbkdf2_sha512_ITERATIONS_MIN'"
  )
  assert(
    outlen <= binding.extension_pbkdf2_sha512_BYTES_MAX,
    "outlen must be at most 'extension_pbkdf2_sha512_BYTES_MAX'"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(out.byteLength >= outlen, "out must be at least 'outlen' bytes")
  assert(out.byteLength > 0, 'out must not be empty')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(salt.byteLength > 0, 'salt must not be empty')

  const [done, promise] = checkStatus(callback)

  binding.extension_pbkdf2_sha512_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    iter,
    outlen,

    done
  )

  return promise
}

exports.extension_pbkdf2_sha512 = function (out, passwd, salt, iter, outlen) {
  assert(
    iter >= binding.extension_pbkdf2_sha512_ITERATIONS_MIN,
    "iter must be at least 'extension_pbkdf2_sha512_ITERATIONS_MIN'"
  )
  assert(
    outlen <= binding.extension_pbkdf2_sha512_BYTES_MAX,
    "outlen must be at most 'extension_pbkdf2_sha512_BYTES_MAX'"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(out.byteLength >= outlen, "out must be at least 'outlen' bytes")
  assert(out.byteLength > 0, 'out must not be empty')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(salt.byteLength > 0, 'salt must not be empty')

  const res = binding.extension_pbkdf2_sha512(out, passwd, salt, iter, outlen)

  if (res !== 0) throw new Error('failed to add tweak to public key')
}

function checkStatus(callback, booleanResult = false) {
  let done, promise

  if (typeof callback === 'function') {
    done = function (status) {
      if (booleanResult) callback(null, status === 0)
      else if (status === 0) callback(null)
      else callback(new Error('status: ' + status))
    }
  } else {
    promise = new Promise(function (resolve, reject) {
      done = function (status) {
        if (booleanResult) resolve(status === 0)
        else if (status === 0) resolve()
        else reject(new Error('status: ' + status))
      }
    })
  }

  return [done, promise]
}
{
  "name": "sodium-native",
  "version": "5.1.0",
  "description": "Low level bindings for libsodium",
  "main": "index.js",
  "files": [
    "index.js",
    "binding.cc",
    "binding.js",
    "extensions",
    "prebuilds",
    "CMakeLists.txt"
  ],
  "imports": {
    "assert": {
      "bare": "bare-assert",
      "node": "assert"
    }
  },
  "addon": true,
  "dependencies": {
    "bare-assert": "^1.2.0",
    "require-addon": "^1.1.0",
    "which-runtime": "^1.2.1"
  },
  "devDependencies": {
    "bare-compat-napi": "^1.3.5",
    "brittle": "^3.16.2",
    "cmake-bare": "^1.6.1",
    "cmake-fetch": "^1.4.3",
    "cmake-napi": "^1.2.1",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "test": "prettier . --check && npm run test:node && npm run test:bare",
    "test:node": "node test/all.js",
    "test:bare": "bare test/all.js"
  },
  "standard": {
    "ignore": [
      "/test/fixtures/*.js"
    ]
  },
  "engines": {
    "bare": ">=1.16.0"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sodium-native.git"
  },
  "contributors": [
    "Emil Bay <github@tixz.dk> (http://bayes.dk)",
    "Mathias Buus <mathiasbuus@gmail.com> (https://mafinto.sh)",
    "Christophe Diederichs <chm-diederichs@hyperdivision.dk>"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/sodium-native/issues"
  },
  "homepage": "https://github.com/holepunchto/sodium-native"
}
const sodium = require('sodium-universal')
const b4a = require('b4a')

const ABYTES = sodium.crypto_secretstream_xchacha20poly1305_ABYTES
const TAG_MESSAGE = sodium.crypto_secretstream_xchacha20poly1305_TAG_MESSAGE
const TAG_FINAL = sodium.crypto_secretstream_xchacha20poly1305_TAG_FINAL
const STATEBYTES = sodium.crypto_secretstream_xchacha20poly1305_STATEBYTES
const HEADERBYTES = sodium.crypto_secretstream_xchacha20poly1305_HEADERBYTES
const KEYBYTES = sodium.crypto_secretstream_xchacha20poly1305_KEYBYTES
const TAG_FINAL_BYTE = b4a.isBuffer(TAG_FINAL) ? TAG_FINAL[0] : TAG_FINAL

const EMPTY = b4a.alloc(0)
const TAG = b4a.alloc(1)

class Push {
  constructor (key, state = b4a.allocUnsafeSlow(STATEBYTES), header = b4a.allocUnsafeSlow(HEADERBYTES)) {
    if (!TAG_FINAL) throw new Error('JavaScript sodium version needs to support crypto_secretstream_xchacha20poly')

    this.key = key
    this.state = state
    this.header = header

    sodium.crypto_secretstream_xchacha20poly1305_init_push(this.state, this.header, this.key)
  }

  next (message, cipher = b4a.allocUnsafe(message.byteLength + ABYTES)) {
    sodium.crypto_secretstream_xchacha20poly1305_push(this.state, cipher, message, null, TAG_MESSAGE)
    return cipher
  }

  final (message = EMPTY, cipher = b4a.allocUnsafe(ABYTES)) {
    sodium.crypto_secretstream_xchacha20poly1305_push(this.state, cipher, message, null, TAG_FINAL)
    return cipher
  }
}

class Pull {
  constructor (key, state = b4a.allocUnsafeSlow(STATEBYTES)) {
    if (!TAG_FINAL) throw new Error('JavaScript sodium version needs to support crypto_secretstream_xchacha20poly')

    this.key = key
    this.state = state
    this.final = false
  }

  init (header) {
    sodium.crypto_secretstream_xchacha20poly1305_init_pull(this.state, header, this.key)
  }

  next (cipher, message = b4a.allocUnsafe(cipher.byteLength - ABYTES)) {
    sodium.crypto_secretstream_xchacha20poly1305_pull(this.state, message, TAG, cipher, null)
    this.final = TAG[0] === TAG_FINAL_BYTE
    return message
  }
}

function keygen (buf = b4a.alloc(KEYBYTES)) {
  sodium.crypto_secretstream_xchacha20poly1305_keygen(buf)
  return buf
}

module.exports = {
  keygen,
  KEYBYTES,
  ABYTES,
  STATEBYTES,
  HEADERBYTES,
  Push,
  Pull
}
{
  "name": "sodium-secretstream",
  "version": "1.2.0",
  "description": "Wraps libsodiums secretstream in a higher level abstraction",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.1.1",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "standard": "^17.0.0"
  },
  "scripts": {
    "test": "standard"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/sodium-secretstream.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/sodium-secretstream/issues"
  },
  "homepage": "https://github.com/mafintosh/sodium-secretstream"
}
module.exports = require('sodium-native')
{
  "name": "sodium-universal",
  "version": "5.0.1",
  "description": "Universal wrapper for sodium-javascript and sodium-native working in Node.js and the Browser",
  "main": "index.js",
  "dependencies": {
    "sodium-native": "^5.0.1"
  },
  "peerDependencies": {
    "sodium-javascript": "~0.8.0"
  },
  "peerDependenciesMeta": {
    "sodium-javascript": {
      "optional": true
    }
  },
  "scripts": {
    "prepublish": "./build-scripts/generate.js"
  },
  "browser": {
    "sodium-native": "sodium-javascript"
  },
  "browserify": {
    "transform": [
      "./build-scripts/transform.js"
    ]
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sodium-universal.git"
  },
  "keywords": [
    "libsodium",
    "sodium",
    "sodium-native",
    "sodium-javascript",
    "browserify"
  ],
  "contributors": [
    "Emil Bay <github@tixz.dk> (http://bayes.dk)",
    "Mathias Buus <mathiasbuus@gmail.com> (https://mafinto.sh)",
    "Christophe Diederichs <chm-diederichs@hyperdivision.dk>"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/sodium-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/sodium-universal#readme"
}
const { EventEmitter } = require('events-universal')
const FIFO = require('fast-fifo')
const TextDecoder = require('text-decoder')

const StreamError = require('./lib/errors.js')

// if we do a future major, expect queue microtask to be there always, for now a bit defensive
const qmt =
  typeof queueMicrotask === 'undefined' ? (fn) => global.process.nextTick(fn) : queueMicrotask

// 29 bits used total (4 from shared, 14 from read, and 11 from write)
const MAX = (1 << 29) - 1

// Shared state
const OPENING = 0b0001
const PREDESTROYING = 0b0010
const DESTROYING = 0b0100
const DESTROYED = 0b1000

const NOT_OPENING = MAX ^ OPENING
const NOT_PREDESTROYING = MAX ^ PREDESTROYING

// Read state (4 bit offset from shared state)
const READ_ACTIVE = 0b00000000000001 << 4
const READ_UPDATING = 0b00000000000010 << 4
const READ_PRIMARY = 0b00000000000100 << 4
const READ_QUEUED = 0b00000000001000 << 4
const READ_RESUMED = 0b00000000010000 << 4
const READ_PIPE_DRAINED = 0b00000000100000 << 4
const READ_ENDING = 0b00000001000000 << 4
const READ_EMIT_DATA = 0b00000010000000 << 4
const READ_EMIT_READABLE = 0b00000100000000 << 4
const READ_EMITTED_READABLE = 0b00001000000000 << 4
const READ_DONE = 0b00010000000000 << 4
const READ_NEXT_TICK = 0b00100000000000 << 4
const READ_NEEDS_PUSH = 0b01000000000000 << 4
const READ_READ_AHEAD = 0b10000000000000 << 4

// Combined read state
const READ_FLOWING = READ_RESUMED | READ_PIPE_DRAINED
const READ_ACTIVE_AND_NEEDS_PUSH = READ_ACTIVE | READ_NEEDS_PUSH
const READ_PRIMARY_AND_ACTIVE = READ_PRIMARY | READ_ACTIVE
const READ_EMIT_READABLE_AND_QUEUED = READ_EMIT_READABLE | READ_QUEUED
const READ_RESUMED_READ_AHEAD = READ_RESUMED | READ_READ_AHEAD

const READ_NOT_ACTIVE = MAX ^ READ_ACTIVE
const READ_NON_PRIMARY = MAX ^ READ_PRIMARY
const READ_NON_PRIMARY_AND_PUSHED = MAX ^ (READ_PRIMARY | READ_NEEDS_PUSH)
const READ_PUSHED = MAX ^ READ_NEEDS_PUSH
const READ_PAUSED = MAX ^ READ_RESUMED
const READ_NOT_QUEUED = MAX ^ (READ_QUEUED | READ_EMITTED_READABLE)
const READ_NOT_ENDING = MAX ^ READ_ENDING
const READ_PIPE_NOT_DRAINED = MAX ^ READ_FLOWING
const READ_NOT_NEXT_TICK = MAX ^ READ_NEXT_TICK
const READ_NOT_UPDATING = MAX ^ READ_UPDATING
const READ_NO_READ_AHEAD = MAX ^ READ_READ_AHEAD
const READ_PAUSED_NO_READ_AHEAD = MAX ^ READ_RESUMED_READ_AHEAD

// Write state (18 bit offset, 4 bit offset from shared state and 14 from read state)
const WRITE_ACTIVE = 0b00000000001 << 18
const WRITE_UPDATING = 0b00000000010 << 18
const WRITE_PRIMARY = 0b00000000100 << 18
const WRITE_QUEUED = 0b00000001000 << 18
const WRITE_UNDRAINED = 0b00000010000 << 18
const WRITE_DONE = 0b00000100000 << 18
const WRITE_EMIT_DRAIN = 0b00001000000 << 18
const WRITE_NEXT_TICK = 0b00010000000 << 18
const WRITE_WRITING = 0b00100000000 << 18
const WRITE_FINISHING = 0b01000000000 << 18
const WRITE_CORKED = 0b10000000000 << 18

const WRITE_NOT_ACTIVE = MAX ^ (WRITE_ACTIVE | WRITE_WRITING)
const WRITE_NON_PRIMARY = MAX ^ WRITE_PRIMARY
const WRITE_NOT_FINISHING = MAX ^ (WRITE_ACTIVE | WRITE_FINISHING)
const WRITE_DRAINED = MAX ^ WRITE_UNDRAINED
const WRITE_NOT_QUEUED = MAX ^ WRITE_QUEUED
const WRITE_NOT_NEXT_TICK = MAX ^ WRITE_NEXT_TICK
const WRITE_NOT_UPDATING = MAX ^ WRITE_UPDATING
const WRITE_NOT_CORKED = MAX ^ WRITE_CORKED

// Combined shared state
const ACTIVE = READ_ACTIVE | WRITE_ACTIVE
const NOT_ACTIVE = MAX ^ ACTIVE
const DONE = READ_DONE | WRITE_DONE
const DESTROY_STATUS = DESTROYING | DESTROYED | PREDESTROYING
const OPEN_STATUS = DESTROY_STATUS | OPENING
const AUTO_DESTROY = DESTROY_STATUS | DONE
const NON_PRIMARY = WRITE_NON_PRIMARY & READ_NON_PRIMARY
const ACTIVE_OR_TICKING = WRITE_NEXT_TICK | READ_NEXT_TICK
const TICKING = ACTIVE_OR_TICKING & NOT_ACTIVE
const IS_OPENING = OPEN_STATUS | TICKING

// Combined shared state and read state
const READ_PRIMARY_STATUS = OPEN_STATUS | READ_ENDING | READ_DONE
const READ_STATUS = OPEN_STATUS | READ_DONE | READ_QUEUED
const READ_ENDING_STATUS = OPEN_STATUS | READ_ENDING | READ_QUEUED
const READ_READABLE_STATUS = OPEN_STATUS | READ_EMIT_READABLE | READ_QUEUED | READ_EMITTED_READABLE
const SHOULD_NOT_READ =
  OPEN_STATUS | READ_ACTIVE | READ_ENDING | READ_DONE | READ_NEEDS_PUSH | READ_READ_AHEAD
const READ_BACKPRESSURE_STATUS = DESTROY_STATUS | READ_ENDING | READ_DONE
const READ_UPDATE_SYNC_STATUS = READ_UPDATING | OPEN_STATUS | READ_NEXT_TICK | READ_PRIMARY
const READ_NEXT_TICK_OR_OPENING = READ_NEXT_TICK | OPENING

// Combined write state
const WRITE_PRIMARY_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_DONE
const WRITE_QUEUED_AND_UNDRAINED = WRITE_QUEUED | WRITE_UNDRAINED
const WRITE_QUEUED_AND_ACTIVE = WRITE_QUEUED | WRITE_ACTIVE
const WRITE_DRAIN_STATUS = WRITE_QUEUED | WRITE_UNDRAINED | OPEN_STATUS | WRITE_ACTIVE
const WRITE_STATUS = OPEN_STATUS | WRITE_ACTIVE | WRITE_QUEUED | WRITE_CORKED
const WRITE_PRIMARY_AND_ACTIVE = WRITE_PRIMARY | WRITE_ACTIVE
const WRITE_ACTIVE_AND_WRITING = WRITE_ACTIVE | WRITE_WRITING
const WRITE_FINISHING_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_QUEUED_AND_ACTIVE | WRITE_DONE
const WRITE_BACKPRESSURE_STATUS = WRITE_UNDRAINED | DESTROY_STATUS | WRITE_FINISHING | WRITE_DONE
const WRITE_UPDATE_SYNC_STATUS = WRITE_UPDATING | OPEN_STATUS | WRITE_NEXT_TICK | WRITE_PRIMARY
const WRITE_DROP_DATA = WRITE_FINISHING | WRITE_DONE | DESTROY_STATUS

const asyncIterator = Symbol.asyncIterator || Symbol('asyncIterator')

class WritableState {
  constructor(
    stream,
    { highWaterMark = 16384, map = null, mapWritable, byteLength, byteLengthWritable } = {}
  ) {
    this.stream = stream
    this.queue = new FIFO()
    this.highWaterMark = highWaterMark
    this.buffered = 0
    this.error = null
    this.pipeline = null
    this.drains = null // if we add more seldomly used helpers we might them into a subobject so its a single ptr
    this.byteLength = byteLengthWritable || byteLength || defaultByteLength
    this.map = mapWritable || map
    this.afterWrite = afterWrite.bind(this)
    this.afterUpdateNextTick = updateWriteNT.bind(this)
  }

  get ending() {
    return (this.stream._duplexState & WRITE_FINISHING) !== 0
  }

  get ended() {
    return (this.stream._duplexState & WRITE_DONE) !== 0
  }

  push(data) {
    if ((this.stream._duplexState & WRITE_DROP_DATA) !== 0) return false
    if (this.map !== null) data = this.map(data)

    this.buffered += this.byteLength(data)
    this.queue.push(data)

    if (this.buffered < this.highWaterMark) {
      this.stream._duplexState |= WRITE_QUEUED
      return true
    }

    this.stream._duplexState |= WRITE_QUEUED_AND_UNDRAINED
    return false
  }

  shift() {
    const data = this.queue.shift()

    this.buffered -= this.byteLength(data)
    if (this.buffered === 0) this.stream._duplexState &= WRITE_NOT_QUEUED

    return data
  }

  end(data) {
    if (typeof data === 'function') {
      this.stream.once('finish', data)
    } else if (data !== undefined && data !== null) {
      this.push(data)
    }

    this.stream._duplexState = (this.stream._duplexState | WRITE_FINISHING) & WRITE_NON_PRIMARY
  }

  autoBatch(data, cb) {
    const buffer = []
    const stream = this.stream

    buffer.push(data)
    while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED_AND_ACTIVE) {
      buffer.push(stream._writableState.shift())
    }

    if ((stream._duplexState & OPEN_STATUS) !== 0) return cb(null)
    stream._writev(buffer, cb)
  }

  update() {
    const stream = this.stream

    stream._duplexState |= WRITE_UPDATING

    do {
      while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED) {
        const data = this.shift()
        stream._duplexState |= WRITE_ACTIVE_AND_WRITING
        stream._write(data, this.afterWrite)
      }

      if ((stream._duplexState & WRITE_PRIMARY_AND_ACTIVE) === 0) this.updateNonPrimary()
    } while (this.continueUpdate() === true)

    stream._duplexState &= WRITE_NOT_UPDATING
  }

  updateNonPrimary() {
    const stream = this.stream

    if ((stream._duplexState & WRITE_FINISHING_STATUS) === WRITE_FINISHING) {
      stream._duplexState = stream._duplexState | WRITE_ACTIVE
      stream._final(afterFinal.bind(this))
      return
    }

    if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
      if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
        stream._duplexState |= ACTIVE
        stream._destroy(afterDestroy.bind(this))
      }
      return
    }

    if ((stream._duplexState & IS_OPENING) === OPENING) {
      stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING
      stream._open(afterOpen.bind(this))
    }
  }

  continueUpdate() {
    if ((this.stream._duplexState & WRITE_NEXT_TICK) === 0) return false
    this.stream._duplexState &= WRITE_NOT_NEXT_TICK
    return true
  }

  updateCallback() {
    if ((this.stream._duplexState & WRITE_UPDATE_SYNC_STATUS) === WRITE_PRIMARY) {
      this.update()
    } else {
      this.updateNextTick()
    }
  }

  updateNextTick() {
    if ((this.stream._duplexState & WRITE_NEXT_TICK) !== 0) return
    this.stream._duplexState |= WRITE_NEXT_TICK
    if ((this.stream._duplexState & WRITE_UPDATING) === 0) qmt(this.afterUpdateNextTick)
  }
}

class ReadableState {
  constructor(
    stream,
    { highWaterMark = 16384, map = null, mapReadable, byteLength, byteLengthReadable } = {}
  ) {
    this.stream = stream
    this.queue = new FIFO()
    this.highWaterMark = highWaterMark === 0 ? 1 : highWaterMark
    this.buffered = 0
    this.readAhead = highWaterMark > 0
    this.error = null
    this.pipeline = null
    this.byteLength = byteLengthReadable || byteLength || defaultByteLength
    this.map = mapReadable || map
    this.pipeTo = null
    this.afterRead = afterRead.bind(this)
    this.afterUpdateNextTick = updateReadNT.bind(this)
  }

  get ending() {
    return (this.stream._duplexState & READ_ENDING) !== 0
  }

  get ended() {
    return (this.stream._duplexState & READ_DONE) !== 0
  }

  pipe(pipeTo, cb) {
    if (this.pipeTo !== null) throw StreamError.BAD_ARGUMENT('Can only pipe to one destination')
    if (typeof cb !== 'function') cb = null

    this.stream._duplexState |= READ_PIPE_DRAINED
    this.pipeTo = pipeTo
    this.pipeline = new Pipeline(this.stream, pipeTo, cb)

    if (cb) this.stream.on('error', noop) // We already error handle this so supress crashes

    if (isStreamx(pipeTo)) {
      pipeTo._writableState.pipeline = this.pipeline
      if (cb) pipeTo.on('error', noop) // We already error handle this so supress crashes
      pipeTo.on('finish', this.pipeline.finished.bind(this.pipeline)) // TODO: just call finished from pipeTo itself
    } else {
      const onerror = this.pipeline.done.bind(this.pipeline, pipeTo)
      const onclose = this.pipeline.done.bind(this.pipeline, pipeTo, null) // onclose has a weird bool arg
      pipeTo.on('error', onerror)
      pipeTo.on('close', onclose)
      pipeTo.on('finish', this.pipeline.finished.bind(this.pipeline))
    }

    pipeTo.on('drain', afterDrain.bind(this))
    this.stream.emit('piping', pipeTo)
    pipeTo.emit('pipe', this.stream)
  }

  push(data) {
    const stream = this.stream

    if (data === null) {
      this.highWaterMark = 0
      stream._duplexState = (stream._duplexState | READ_ENDING) & READ_NON_PRIMARY_AND_PUSHED
      return false
    }

    if (this.map !== null) {
      data = this.map(data)
      if (data === null) {
        stream._duplexState &= READ_PUSHED
        return this.buffered < this.highWaterMark
      }
    }

    this.buffered += this.byteLength(data)
    this.queue.push(data)

    stream._duplexState = (stream._duplexState | READ_QUEUED) & READ_PUSHED

    return this.buffered < this.highWaterMark
  }

  shift() {
    const data = this.queue.shift()

    this.buffered -= this.byteLength(data)
    if (this.buffered === 0) {
      this.stream._duplexState &= READ_NOT_QUEUED
    }

    return data
  }

  unshift(data) {
    const pending = [this.map !== null ? this.map(data) : data]
    while (this.buffered > 0) pending.push(this.shift())

    for (let i = 0; i < pending.length - 1; i++) {
      const data = pending[i]
      this.buffered += this.byteLength(data)
      this.queue.push(data)
    }

    this.push(pending[pending.length - 1])
  }

  read() {
    const stream = this.stream

    if ((stream._duplexState & READ_STATUS) === READ_QUEUED) {
      const data = this.shift()

      if (this.pipeTo !== null && this.pipeTo.write(data) === false) {
        stream._duplexState &= READ_PIPE_NOT_DRAINED
      }

      if ((stream._duplexState & READ_EMIT_DATA) !== 0) {
        stream.emit('data', data)
      }

      return data
    }

    if (this.readAhead === false) {
      stream._duplexState |= READ_READ_AHEAD
      this.updateNextTick()
    }

    return null
  }

  drain() {
    const stream = this.stream

    while (
      (stream._duplexState & READ_STATUS) === READ_QUEUED &&
      (stream._duplexState & READ_FLOWING) !== 0
    ) {
      const data = this.shift()

      if (this.pipeTo !== null && this.pipeTo.write(data) === false) {
        stream._duplexState &= READ_PIPE_NOT_DRAINED
      }

      if ((stream._duplexState & READ_EMIT_DATA) !== 0) {
        stream.emit('data', data)
      }
    }
  }

  update() {
    const stream = this.stream

    stream._duplexState |= READ_UPDATING

    do {
      this.drain()

      while (
        this.buffered < this.highWaterMark &&
        (stream._duplexState & SHOULD_NOT_READ) === READ_READ_AHEAD
      ) {
        stream._duplexState |= READ_ACTIVE_AND_NEEDS_PUSH
        stream._read(this.afterRead)
        this.drain()
      }

      if ((stream._duplexState & READ_READABLE_STATUS) === READ_EMIT_READABLE_AND_QUEUED) {
        stream._duplexState |= READ_EMITTED_READABLE
        stream.emit('readable')
      }

      if ((stream._duplexState & READ_PRIMARY_AND_ACTIVE) === 0) {
        this.updateNonPrimary()
      }
    } while (this.continueUpdate() === true)

    stream._duplexState &= READ_NOT_UPDATING
  }

  updateNonPrimary() {
    const stream = this.stream

    if ((stream._duplexState & READ_ENDING_STATUS) === READ_ENDING) {
      stream._duplexState = (stream._duplexState | READ_DONE) & READ_NOT_ENDING
      stream.emit('end')

      if ((stream._duplexState & AUTO_DESTROY) === DONE) {
        stream._duplexState |= DESTROYING
      }

      if (this.pipeTo !== null) {
        this.pipeTo.end()
      }
    }

    if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
      if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
        stream._duplexState |= ACTIVE
        stream._destroy(afterDestroy.bind(this))
      }
      return
    }

    if ((stream._duplexState & IS_OPENING) === OPENING) {
      stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING
      stream._open(afterOpen.bind(this))
    }
  }

  continueUpdate() {
    if ((this.stream._duplexState & READ_NEXT_TICK) === 0) return false
    this.stream._duplexState &= READ_NOT_NEXT_TICK
    return true
  }

  updateCallback() {
    if ((this.stream._duplexState & READ_UPDATE_SYNC_STATUS) === READ_PRIMARY) {
      this.update()
    } else {
      this.updateNextTick()
    }
  }

  updateNextTickIfOpen() {
    if ((this.stream._duplexState & READ_NEXT_TICK_OR_OPENING) !== 0) return
    this.stream._duplexState |= READ_NEXT_TICK
    if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick)
  }

  updateNextTick() {
    if ((this.stream._duplexState & READ_NEXT_TICK) !== 0) return
    this.stream._duplexState |= READ_NEXT_TICK
    if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick)
  }
}

class TransformState {
  constructor(stream) {
    this.data = null
    this.afterTransform = afterTransform.bind(stream)
    this.afterFinal = null
  }
}

class Pipeline {
  constructor(src, dst, cb) {
    this.from = src
    this.to = dst
    this.afterPipe = cb
    this.error = null
    this.pipeToFinished = false
  }

  finished() {
    this.pipeToFinished = true
  }

  done(stream, err) {
    if (err) this.error = err

    if (stream === this.to) {
      this.to = null

      if (this.from !== null) {
        if ((this.from._duplexState & READ_DONE) === 0 || !this.pipeToFinished) {
          this.from.destroy(this.error || StreamError.PREMATURE_CLOSE('Writable stream closed'))
        }
        return
      }
    }

    if (stream === this.from) {
      this.from = null

      if (this.to !== null) {
        if ((stream._duplexState & READ_DONE) === 0) {
          this.to.destroy(this.error || StreamError.PREMATURE_CLOSE('Readable stream closed'))
        }
        return
      }
    }

    if (this.afterPipe !== null) this.afterPipe(this.error)
    this.to = this.from = this.afterPipe = null
  }
}

function afterDrain() {
  this.stream._duplexState |= READ_PIPE_DRAINED
  this.updateCallback()
}

function afterFinal(err) {
  const stream = this.stream
  if (err) stream.destroy(err)

  if ((stream._duplexState & DESTROY_STATUS) === 0) {
    stream._duplexState |= WRITE_DONE
    stream.emit('finish')
  }

  if ((stream._duplexState & AUTO_DESTROY) === DONE) {
    stream._duplexState |= DESTROYING
  }

  stream._duplexState &= WRITE_NOT_FINISHING

  // no need to wait the extra tick here, so we short circuit that
  if ((stream._duplexState & WRITE_UPDATING) === 0) {
    this.update()
  } else {
    this.updateNextTick()
  }
}

function afterDestroy(err) {
  const stream = this.stream

  if (!err && !StreamError.isStreamDestroyed(this.error)) err = this.error
  if (err) stream.emit('error', err)

  stream._duplexState |= DESTROYED
  stream.emit('close')

  const rs = stream._readableState
  const ws = stream._writableState

  if (rs !== null && rs.pipeline !== null) {
    rs.pipeline.done(stream, err)
  }

  if (ws !== null) {
    while (ws.drains !== null && ws.drains.length > 0) {
      ws.drains.shift().resolve(false)
    }

    if (ws.pipeline !== null) {
      ws.pipeline.done(stream, err)
    }
  }
}

function afterWrite(err) {
  const stream = this.stream

  if (err) stream.destroy(err)
  stream._duplexState &= WRITE_NOT_ACTIVE

  if (this.drains !== null) tickDrains(this.drains)

  if ((stream._duplexState & WRITE_DRAIN_STATUS) === WRITE_UNDRAINED) {
    stream._duplexState &= WRITE_DRAINED

    if ((stream._duplexState & WRITE_EMIT_DRAIN) === WRITE_EMIT_DRAIN) {
      stream.emit('drain')
    }
  }

  this.updateCallback()
}

function afterRead(err) {
  if (err) this.stream.destroy(err)
  this.stream._duplexState &= READ_NOT_ACTIVE

  if (this.readAhead === false && (this.stream._duplexState & READ_RESUMED) === 0) {
    this.stream._duplexState &= READ_NO_READ_AHEAD
  }

  this.updateCallback()
}

function updateReadNT() {
  if ((this.stream._duplexState & READ_UPDATING) === 0) {
    this.stream._duplexState &= READ_NOT_NEXT_TICK
    this.update()
  }
}

function updateWriteNT() {
  if ((this.stream._duplexState & WRITE_UPDATING) === 0) {
    this.stream._duplexState &= WRITE_NOT_NEXT_TICK
    this.update()
  }
}

function tickDrains(drains) {
  for (let i = 0; i < drains.length; i++) {
    // drains.writes are monotonic, so if one is 0 its always the first one
    if (--drains[i].writes === 0) {
      drains.shift().resolve(true)
      i--
    }
  }
}

function afterOpen(err) {
  const stream = this.stream

  if (err) stream.destroy(err)

  if ((stream._duplexState & DESTROYING) === 0) {
    if ((stream._duplexState & READ_PRIMARY_STATUS) === 0) {
      stream._duplexState |= READ_PRIMARY
    }

    if ((stream._duplexState & WRITE_PRIMARY_STATUS) === 0) {
      stream._duplexState |= WRITE_PRIMARY
    }

    stream.emit('open')
  }

  stream._duplexState &= NOT_ACTIVE

  if (stream._writableState !== null) {
    stream._writableState.updateCallback()
  }

  if (stream._readableState !== null) {
    stream._readableState.updateCallback()
  }
}

function afterTransform(err, data) {
  if (data !== undefined && data !== null) this.push(data)
  this._writableState.afterWrite(err)
}

function newListener(name) {
  if (this._readableState !== null) {
    if (name === 'data') {
      this._duplexState |= READ_EMIT_DATA | READ_RESUMED_READ_AHEAD
      this._readableState.updateNextTick()
    }
    if (name === 'readable') {
      this._duplexState |= READ_EMIT_READABLE
      this._readableState.updateNextTick()
    }
  }

  if (this._writableState !== null) {
    if (name === 'drain') {
      this._duplexState |= WRITE_EMIT_DRAIN
      this._writableState.updateNextTick()
    }
  }
}

class Stream extends EventEmitter {
  constructor(opts) {
    super()

    this._duplexState = 0
    this._readableState = null
    this._writableState = null

    if (opts) {
      if (opts.open) this._open = opts.open
      if (opts.destroy) this._destroy = opts.destroy
      if (opts.predestroy) this._predestroy = opts.predestroy
      if (opts.signal) opts.signal.addEventListener('abort', abort.bind(this))
    }

    this.on('newListener', newListener)
  }

  _open(cb) {
    cb(null)
  }

  _destroy(cb) {
    cb(null)
  }

  _predestroy() {
    // does nothing
  }

  get readable() {
    return this._readableState !== null ? true : undefined
  }

  get writable() {
    return this._writableState !== null ? true : undefined
  }

  get destroyed() {
    return (this._duplexState & DESTROYED) !== 0
  }

  get destroying() {
    return (this._duplexState & DESTROY_STATUS) !== 0
  }

  destroy(err) {
    if ((this._duplexState & DESTROY_STATUS) === 0) {
      if (!err) err = StreamError.STREAM_DESTROYED()
      this._duplexState = (this._duplexState | DESTROYING) & NON_PRIMARY

      if (this._readableState !== null) {
        this._readableState.highWaterMark = 0
        this._readableState.error = err
      }

      if (this._writableState !== null) {
        this._writableState.highWaterMark = 0
        this._writableState.error = err
      }

      this._duplexState |= PREDESTROYING
      this._predestroy()
      this._duplexState &= NOT_PREDESTROYING

      if (this._readableState !== null) {
        this._readableState.updateNextTick()
      }

      if (this._writableState !== null) {
        this._writableState.updateNextTick()
      }
    }
  }
}

class Readable extends Stream {
  constructor(opts) {
    super(opts)

    this._duplexState |= OPENING | WRITE_DONE | READ_READ_AHEAD
    this._readableState = new ReadableState(this, opts)

    if (opts) {
      if (this._readableState.readAhead === false) this._duplexState &= READ_NO_READ_AHEAD
      if (opts.read) this._read = opts.read
      if (opts.eagerOpen) this._readableState.updateNextTick()
      if (opts.encoding) this.setEncoding(opts.encoding)
    }
  }

  static deferred(fn, opts) {
    const out = new PassThrough(opts)

    fn()
      .then((src) => {
        if (src === null) return out.end()
        if (out.destroying) return
        pipeline(src, out, noop)
      })
      .catch((err) => out.destroy(err))

    return out
  }

  setEncoding(encoding) {
    const dec = new TextDecoder(encoding)
    const map = this._readableState.map || echo
    this._readableState.map = mapOrSkip
    return this

    function mapOrSkip(data) {
      const next = dec.push(data)
      return next === '' && (data.byteLength !== 0 || dec.remaining > 0) ? null : map(next)
    }
  }

  _read(cb) {
    cb(null)
  }

  pipe(dest, cb) {
    this._readableState.updateNextTick()
    this._readableState.pipe(dest, cb)
    return dest
  }

  read() {
    this._readableState.updateNextTick()
    return this._readableState.read()
  }

  push(data) {
    this._readableState.updateNextTickIfOpen()
    return this._readableState.push(data)
  }

  unshift(data) {
    this._readableState.updateNextTickIfOpen()
    return this._readableState.unshift(data)
  }

  resume() {
    this._duplexState |= READ_RESUMED_READ_AHEAD
    this._readableState.updateNextTick()
    return this
  }

  pause() {
    this._duplexState &=
      this._readableState.readAhead === false ? READ_PAUSED_NO_READ_AHEAD : READ_PAUSED
    return this
  }

  static _fromAsyncIterator(ite, opts) {
    let destroy

    const rs = new Readable({
      ...opts,
      read(cb) {
        ite.next().then(push).then(cb.bind(null, null)).catch(cb)
      },
      predestroy() {
        destroy = ite.return()
      },
      destroy(cb) {
        if (!destroy) return cb(null)
        destroy.then(cb.bind(null, null)).catch(cb)
      }
    })

    return rs

    function push(data) {
      if (data.done) rs.push(null)
      else rs.push(data.value)
    }
  }

  static from(data, opts) {
    if (isReadStreamx(data)) return data
    if (data[asyncIterator]) return this._fromAsyncIterator(data[asyncIterator](), opts)
    if (!Array.isArray(data)) data = data === undefined ? [] : [data]

    let i = 0
    return new Readable({
      ...opts,
      read(cb) {
        this.push(i === data.length ? null : data[i++])
        cb(null)
      }
    })
  }

  static isBackpressured(rs) {
    return (
      (rs._duplexState & READ_BACKPRESSURE_STATUS) !== 0 ||
      rs._readableState.buffered >= rs._readableState.highWaterMark
    )
  }

  static isPaused(rs) {
    return (rs._duplexState & READ_RESUMED) === 0
  }

  [asyncIterator]() {
    const stream = this

    let error = null
    let promiseResolve = null
    let promiseReject = null

    this.on('error', (err) => {
      error = err
    })
    this.on('readable', onreadable)
    this.on('close', onclose)

    return {
      [asyncIterator]() {
        return this
      },
      next() {
        return new Promise(function (resolve, reject) {
          promiseResolve = resolve
          promiseReject = reject
          const data = stream.read()
          if (data !== null) ondata(data)
          else if ((stream._duplexState & DESTROYED) !== 0) ondata(null)
        })
      },
      return() {
        return destroy(null)
      },
      throw(err) {
        return destroy(err)
      }
    }

    function onreadable() {
      if (promiseResolve !== null) ondata(stream.read())
    }

    function onclose() {
      if (promiseResolve !== null) ondata(null)
    }

    function ondata(data) {
      if (promiseReject === null) return
      if (error) {
        promiseReject(error)
      } else if (data === null && (stream._duplexState & READ_DONE) === 0) {
        promiseReject(StreamError.STREAM_DESTROYED())
      } else {
        promiseResolve({ value: data, done: data === null })
      }
      promiseReject = promiseResolve = null
    }

    function destroy(err) {
      stream.destroy(err)
      return new Promise((resolve, reject) => {
        if (stream._duplexState & DESTROYED) return resolve({ value: undefined, done: true })
        stream.once('close', function () {
          if (err) reject(err)
          else resolve({ value: undefined, done: true })
        })
      })
    }
  }
}

class Writable extends Stream {
  constructor(opts) {
    super(opts)

    this._duplexState |= OPENING | READ_DONE
    this._writableState = new WritableState(this, opts)

    if (opts) {
      if (opts.writev) this._writev = opts.writev
      if (opts.write) this._write = opts.write
      if (opts.final) this._final = opts.final
      if (opts.eagerOpen) this._writableState.updateNextTick()
    }
  }

  cork() {
    this._duplexState |= WRITE_CORKED
  }

  uncork() {
    this._duplexState &= WRITE_NOT_CORKED
    this._writableState.updateNextTick()
  }

  _writev(batch, cb) {
    cb(null)
  }

  _write(data, cb) {
    this._writableState.autoBatch(data, cb)
  }

  _final(cb) {
    cb(null)
  }

  static isBackpressured(ws) {
    return (ws._duplexState & WRITE_BACKPRESSURE_STATUS) !== 0
  }

  static drained(ws) {
    if (ws.destroyed) return Promise.resolve(false)

    const state = ws._writableState
    const pending = isWritev(ws) ? Math.min(1, state.queue.length) : state.queue.length
    const writes = pending + (ws._duplexState & WRITE_WRITING ? 1 : 0)
    if (writes === 0) return Promise.resolve(true)

    if (state.drains === null) state.drains = []
    return new Promise((resolve) => {
      state.drains.push({ writes, resolve })
    })
  }

  write(data) {
    this._writableState.updateNextTick()
    return this._writableState.push(data)
  }

  end(data) {
    this._writableState.updateNextTick()
    this._writableState.end(data)
    return this
  }
}

class Duplex extends Readable {
  // and Writable
  constructor(opts) {
    super(opts)

    this._duplexState = OPENING | (this._duplexState & READ_READ_AHEAD)
    this._writableState = new WritableState(this, opts)

    if (opts) {
      if (opts.writev) this._writev = opts.writev
      if (opts.write) this._write = opts.write
      if (opts.final) this._final = opts.final
    }
  }

  cork() {
    this._duplexState |= WRITE_CORKED
  }

  uncork() {
    this._duplexState &= WRITE_NOT_CORKED
    this._writableState.updateNextTick()
  }

  _writev(batch, cb) {
    cb(null)
  }

  _write(data, cb) {
    this._writableState.autoBatch(data, cb)
  }

  _final(cb) {
    cb(null)
  }

  write(data) {
    this._writableState.updateNextTick()
    return this._writableState.push(data)
  }

  end(data) {
    this._writableState.updateNextTick()
    this._writableState.end(data)
    return this
  }
}

class Transform extends Duplex {
  constructor(opts) {
    super(opts)
    this._transformState = new TransformState(this)

    if (opts) {
      if (opts.transform) this._transform = opts.transform
      if (opts.flush) this._flush = opts.flush
    }
  }

  _write(data, cb) {
    if (this._readableState.buffered >= this._readableState.highWaterMark) {
      this._transformState.data = data
    } else {
      this._transform(data, this._transformState.afterTransform)
    }
  }

  _read(cb) {
    if (this._transformState.data !== null) {
      const data = this._transformState.data
      this._transformState.data = null
      cb(null)
      this._transform(data, this._transformState.afterTransform)
    } else {
      cb(null)
    }
  }

  destroy(err) {
    super.destroy(err)
    if (this._transformState.data !== null) {
      this._transformState.data = null
      this._transformState.afterTransform()
    }
  }

  _transform(data, cb) {
    cb(null, data)
  }

  _flush(cb) {
    cb(null)
  }

  _final(cb) {
    this._transformState.afterFinal = cb
    this._flush(transformAfterFlush.bind(this))
  }
}

class PassThrough extends Transform {}

function transformAfterFlush(err, data) {
  const cb = this._transformState.afterFinal
  if (err) return cb(err)

  if (data !== null && data !== undefined) this.push(data)
  this.push(null)
  cb(null)
}

function pipelinePromise(...streams) {
  return new Promise((resolve, reject) => {
    return pipeline(...streams, (err) => {
      if (err) return reject(err)
      resolve()
    })
  })
}

function pipeline(stream, ...streams) {
  const all = Array.isArray(stream) ? [...stream, ...streams] : [stream, ...streams]
  const done = all.length && typeof all[all.length - 1] === 'function' ? all.pop() : null

  if (all.length < 2) throw StreamError.BAD_ARGUMENT('Pipeline requires at least 2 streams')

  let src = all[0]
  let dest = null
  let error = null

  for (let i = 1; i < all.length; i++) {
    dest = all[i]

    if (isStreamx(src)) {
      src.pipe(dest, onerror)
    } else {
      errorHandle(src, true, i > 1, onerror)
      src.pipe(dest)
    }

    src = dest
  }

  if (done) {
    let fin = false

    const autoDestroy =
      isStreamx(dest) || !!(dest._writableState && dest._writableState.autoDestroy)

    dest.on('error', (err) => {
      if (error === null) error = err
    })

    dest.on('finish', () => {
      fin = true
      if (!autoDestroy) done(error)
    })

    if (autoDestroy) {
      dest.on('close', () => done(error || (fin ? null : StreamError.PREMATURE_CLOSE())))
    }
  }

  return dest

  function errorHandle(s, rd, wr, onerror) {
    s.on('error', onerror)
    s.on('close', onclose)

    function onclose() {
      if (rd && s._readableState && !s._readableState.ended) {
        return onerror(StreamError.PREMATURE_CLOSE())
      }
      if (wr && s._writableState && !s._writableState.ended) {
        return onerror(StreamError.PREMATURE_CLOSE())
      }
    }
  }

  function onerror(err) {
    if (!err || error) return
    error = err

    for (const s of all) {
      s.destroy(err)
    }
  }
}

function echo(s) {
  return s
}

function isStream(stream) {
  return !!stream._readableState || !!stream._writableState
}

function isStreamx(stream) {
  return typeof stream._duplexState === 'number' && isStream(stream)
}

function isEnding(stream) {
  return !!stream._readableState && stream._readableState.ending
}

function isEnded(stream) {
  return !!stream._readableState && stream._readableState.ended
}

function isFinishing(stream) {
  return !!stream._writableState && stream._writableState.ending
}

function isFinished(stream) {
  return !!stream._writableState && stream._writableState.ended
}

function getStreamError(stream, opts = {}) {
  const err =
    (stream._readableState && stream._readableState.error) ||
    (stream._writableState && stream._writableState.error)

  // avoid implicit errors by default
  return !opts.all && StreamError.isStreamDestroyed(err) ? null : err
}

function isReadStreamx(stream) {
  return isStreamx(stream) && stream.readable
}

function isDisturbed(stream) {
  return (
    (stream._duplexState & OPENING) !== OPENING ||
    (stream._duplexState & DESTROYING) === DESTROYING ||
    (stream._duplexState & ACTIVE_OR_TICKING) !== 0
  )
}

function isTypedArray(data) {
  return typeof data === 'object' && data !== null && typeof data.byteLength === 'number'
}

function defaultByteLength(data) {
  return isTypedArray(data) ? data.byteLength : 1024
}

function noop() {}

function abort() {
  this.destroy(StreamError.ABORTED())
}

function isWritev(s) {
  return s._writev !== Writable.prototype._writev && s._writev !== Duplex.prototype._writev
}

module.exports = {
  pipeline,
  pipelinePromise,
  isStream,
  isStreamx,
  isEnding,
  isEnded,
  isFinishing,
  isFinished,
  isDisturbed,
  getStreamError,
  Stream,
  Writable,
  Readable,
  Duplex,
  Transform,
  // Export PassThrough for compatibility with Node.js core's stream module
  PassThrough
}
module.exports = class StreamError extends Error {
  constructor(msg, code, fn = StreamError) {
    super(msg)

    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  static isStreamDestroyed(err) {
    return err && err.code === 'STREAM_DESTROYED'
  }

  static isPrematureClose(err) {
    return err && err.code === 'PREMATURE_CLOSE'
  }

  static isAborted(err) {
    return err && err.code === 'ABORTED'
  }

  static isBadArgument(err) {
    return err && err.code === 'BAD_ARGUMENT'
  }

  get name() {
    return 'StreamError'
  }

  static STREAM_DESTROYED() {
    return new StreamError('Stream was destroyed', 'STREAM_DESTROYED', StreamError.STREAM_DESTROYED)
  }

  static PREMATURE_CLOSE(msg = 'Premature close') {
    return new StreamError(msg, 'PREMATURE_CLOSE', StreamError.PREMATURE_CLOSE)
  }

  static ABORTED() {
    return new StreamError('Stream aborted', 'ABORTED', StreamError.ABORTED)
  }

  static BAD_ARGUMENT(msg = 'Bad argument') {
    return new StreamError(msg, 'BAD_ARGUMENT', StreamError.BAD_ARGUMENT)
  }
}
{
  "name": "streamx",
  "version": "2.28.0",
  "description": "An iteration of the Node.js core streams with a series of improvements",
  "main": "index.js",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./errors": {
      "types": "./lib/errors.d.ts",
      "default": "./lib/errors"
    }
  },
  "dependencies": {
    "events-universal": "^1.0.0",
    "fast-fifo": "^1.3.2",
    "text-decoder": "^1.1.0"
  },
  "devDependencies": {
    "b4a": "^1.6.6",
    "brittle": "^3.1.1",
    "end-of-stream": "^1.4.4",
    "lunte": "^1.8.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "runtime.d.ts",
    "lib"
  ],
  "scripts": {
    "format": "prettier . --write",
    "test": "brittle test/all.js && brittle-bare test/all.js",
    "lint": "prettier . --check && lunte"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/streamx.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/streamx/issues"
  },
  "homepage": "https://github.com/mafintosh/streamx"
}
const { Readable } = require('streamx')

module.exports = function (s, forks = 2) {
  const streams = new Array(forks)
  const status = new Array(forks).fill(true)

  let ended = false

  for (let i = 0; i < forks; i++) {
    streams[i] = new Readable({
      read (cb) {
        const check = !status[i]
        status[i] = true
        if (check && allReadable()) s.resume()
        cb(null)
      }
    })
  }

  s.on('end', function () {
    ended = true
    for (const stream of streams) stream.push(null)
  })

  s.on('error', function (err) {
    for (const stream of streams) stream.destroy(err)
  })

  s.on('close', function () {
    if (ended) return
    for (const stream of streams) stream.destroy()
  })

  s.on('data', function (data) {
    let needsPause = false
    for (let i = 0; i < streams.length; i++) {
      if (!(status[i] = streams[i].push(data))) {
        needsPause = true
      }
    }
    if (needsPause) s.pause()
  })

  return streams

  function allReadable () {
    for (let j = 0; j < status.length; j++) {
      if (!status[j]) return false
    }
    return true
  }
}
{
  "name": "teex",
  "version": "1.0.1",
  "description": "Turn a readable stream into multiple readable streamx streams",
  "main": "index.js",
  "dependencies": {
    "streamx": "^2.12.5"
  },
  "devDependencies": {
    "standard": "^14.3.4",
    "tape": "^5.0.1"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/teex.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/teex/issues"
  },
  "homepage": "https://github.com/mafintosh/teex"
}
const PassThroughDecoder = require('./lib/pass-through-decoder')
const UTF8Decoder = require('./lib/utf8-decoder')

module.exports = class TextDecoder {
  constructor(encoding = 'utf8') {
    this.encoding = normalizeEncoding(encoding)

    switch (this.encoding) {
      case 'utf8':
        this.decoder = new UTF8Decoder()
        break
      case 'utf16le':
      case 'base64':
        throw new Error('Unsupported encoding: ' + this.encoding)
      default:
        this.decoder = new PassThroughDecoder(this.encoding)
    }
  }

  get remaining() {
    return this.decoder.remaining
  }

  push(data) {
    if (typeof data === 'string') return data
    return this.decoder.decode(data)
  }

  // For Node.js compatibility
  write(data) {
    return this.push(data)
  }

  end(data) {
    let result = ''
    if (data) result = this.push(data)
    result += this.decoder.flush()
    return result
  }
}

function normalizeEncoding(encoding) {
  encoding = encoding.toLowerCase()

  switch (encoding) {
    case 'utf8':
    case 'utf-8':
      return 'utf8'
    case 'ucs2':
    case 'ucs-2':
    case 'utf16le':
    case 'utf-16le':
      return 'utf16le'
    case 'latin1':
    case 'binary':
      return 'latin1'
    case 'base64':
    case 'ascii':
    case 'hex':
      return encoding
    default:
      throw new Error('Unknown encoding: ' + encoding)
  }
}
const b4a = require('b4a')

module.exports = class PassThroughDecoder {
  constructor(encoding) {
    this.encoding = encoding
  }

  get remaining() {
    return 0
  }

  decode(data) {
    return b4a.toString(data, this.encoding)
  }

  flush() {
    return ''
  }
}
const b4a = require('b4a')

/**
 * https://encoding.spec.whatwg.org/#utf-8-decoder
 */
module.exports = class UTF8Decoder {
  constructor() {
    this._reset()
  }

  get remaining() {
    return this.bytesSeen
  }

  decode(data) {
    if (data.byteLength === 0) return ''

    if (this.bytesNeeded === 0 && trailingIncomplete(data, 0) === 0) {
      this.bytesSeen = trailingBytesSeen(data)
      return b4a.toString(data, 'utf8')
    }

    let result = ''
    let start = 0

    if (this.bytesNeeded > 0) {
      while (start < data.byteLength) {
        const byte = data[start]

        if (byte < this.lowerBoundary || byte > this.upperBoundary) {
          result += '\ufffd'
          this._reset()
          break
        }

        this.lowerBoundary = 0x80
        this.upperBoundary = 0xbf
        this.codePoint = (this.codePoint << 6) | (byte & 0x3f)
        this.bytesSeen++
        start++

        if (this.bytesSeen === this.bytesNeeded) {
          result += String.fromCodePoint(this.codePoint)
          this._reset()
          break
        }
      }

      if (this.bytesNeeded > 0) return result
    }

    const trailing = trailingIncomplete(data, start)
    const end = data.byteLength - trailing

    if (end > start) result += b4a.toString(data, 'utf8', start, end)

    for (let i = end; i < data.byteLength; i++) {
      const byte = data[i]

      if (this.bytesNeeded === 0) {
        if (byte <= 0x7f) {
          this.bytesSeen = 0
          result += String.fromCharCode(byte)
        } else if (byte >= 0xc2 && byte <= 0xdf) {
          this.bytesNeeded = 2
          this.bytesSeen = 1
          this.codePoint = byte & 0x1f
        } else if (byte >= 0xe0 && byte <= 0xef) {
          if (byte === 0xe0) this.lowerBoundary = 0xa0
          else if (byte === 0xed) this.upperBoundary = 0x9f
          this.bytesNeeded = 3
          this.bytesSeen = 1
          this.codePoint = byte & 0xf
        } else if (byte >= 0xf0 && byte <= 0xf4) {
          if (byte === 0xf0) this.lowerBoundary = 0x90
          else if (byte === 0xf4) this.upperBoundary = 0x8f
          this.bytesNeeded = 4
          this.bytesSeen = 1
          this.codePoint = byte & 0x7
        } else {
          this.bytesSeen = 1
          result += '\ufffd'
        }

        continue
      }

      if (byte < this.lowerBoundary || byte > this.upperBoundary) {
        result += '\ufffd'
        i--
        this._reset()

        continue
      }

      this.lowerBoundary = 0x80
      this.upperBoundary = 0xbf

      this.codePoint = (this.codePoint << 6) | (byte & 0x3f)
      this.bytesSeen++

      if (this.bytesSeen === this.bytesNeeded) {
        result += String.fromCodePoint(this.codePoint)
        this._reset()
      }
    }

    return result
  }

  flush() {
    const result = this.bytesNeeded > 0 ? '\ufffd' : ''
    this._reset()
    return result
  }

  _reset() {
    this.codePoint = 0
    this.bytesNeeded = 0
    this.bytesSeen = 0
    this.lowerBoundary = 0x80
    this.upperBoundary = 0xbf
  }
}

function trailingIncomplete(data, start) {
  const len = data.byteLength
  if (len <= start) return 0

  const limit = Math.max(start, len - 4)

  let i = len - 1
  while (i > limit && (data[i] & 0xc0) === 0x80) i--

  if (i < start) return 0

  const byte = data[i]

  let needed
  if (byte <= 0x7f) return 0
  if (byte >= 0xc2 && byte <= 0xdf) needed = 2
  else if (byte >= 0xe0 && byte <= 0xef) needed = 3
  else if (byte >= 0xf0 && byte <= 0xf4) needed = 4
  else return 0

  const available = len - i
  return available < needed ? available : 0
}

function trailingBytesSeen(data) {
  const len = data.byteLength
  if (len === 0) return 0

  const last = data[len - 1]

  if (last <= 0x7f) return 0
  if ((last & 0xc0) !== 0x80) return 1

  const limit = Math.max(0, len - 4)

  let i = len - 2
  while (i >= limit && (data[i] & 0xc0) === 0x80) i--

  if (i < 0) return 1

  const first = data[i]

  let needed
  if (first >= 0xc2 && first <= 0xdf) needed = 2
  else if (first >= 0xe0 && first <= 0xef) needed = 3
  else if (first >= 0xf0 && first <= 0xf4) needed = 4
  else return 1

  if (len - i !== needed) return 1

  if (needed >= 3) {
    const second = data[i + 1]
    if (first === 0xe0 && second < 0xa0) return 1
    if (first === 0xed && second > 0x9f) return 1
    if (first === 0xf0 && second < 0x90) return 1
    if (first === 0xf4 && second > 0x8f) return 1
  }

  return 0
}
{
  "name": "text-decoder",
  "version": "1.2.7",
  "description": "Streaming text decoder that preserves multibyte Unicode characters",
  "exports": {
    "./package": "./package.json",
    ".": "./index.js"
  },
  "files": [
    "index.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/text-decoder.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/text-decoder/issues"
  },
  "homepage": "https://github.com/holepunchto/text-decoder#readme",
  "dependencies": {
    "b4a": "^1.6.4"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  }
}
module.exports = class TimeOrderedSet {
  constructor () {
    this.oldest = null
    this.latest = null
    this.length = 0
  }

  has (node) {
    return !!(node.next || node.prev) || node === this.oldest
  }

  add (node) {
    if (this.has(node)) this.remove(node)

    if (!this.latest && !this.oldest) {
      this.latest = this.oldest = node
      node.prev = node.next = null
    } else {
      this.latest.next = node
      node.prev = this.latest
      node.next = null
      this.latest = node
    }

    this.length++

    return node
  }

  remove (node) {
    if (!this.has(node)) return node

    if (this.oldest !== node && this.latest !== node) {
      node.prev.next = node.next
      node.next.prev = node.prev
    } else {
      if (this.oldest === node) {
        this.oldest = node.next
        if (this.oldest) this.oldest.prev = null
      }
      if (this.latest === node) {
        this.latest = node.prev
        if (this.latest) this.latest.next = null
      }
    }

    node.next = node.prev = null
    this.length--

    return node
  }

  toArray ({ limit = Infinity, reverse = false } = {}) {
    const list = []

    if (reverse) {
      let node = this.latest
      while (node && limit--) {
        list.push(node)
        node = node.prev
      }
    } else {
      let node = this.oldest
      while (node && limit--) {
        list.push(node)
        node = node.next
      }
    }

    return list
  }
}
{
  "name": "time-ordered-set",
  "version": "2.0.1",
  "description": "Efficiently maintain a set of nodes ordered by the time they were added to the set",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "devDependencies": {
    "brittle": "^3.0.0",
    "standard": "^17.1.2"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/time-ordered-set.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/time-ordered-set/issues"
  },
  "homepage": "https://github.com/mafintosh/time-ordered-set"
}
module.exports = class TimerBrowser {
  constructor (ms, fn, ctx = null, interval = false) {
    this.ms = ms
    this.ontimeout = fn
    this.context = ctx || null
    this.interval = interval
    this.done = false

    this._timer = interval
      ? setInterval(callInterval, ms, this)
      : setTimeout(callTimeout, ms, this)
  }

  unref () {}

  ref () {}

  refresh () {
    if (this.done) return

    if (this.interval) {
      clearInterval(this._timer)
      this._timer = setInterval(callInterval, this.ms, this)
    } else {
      clearTimeout(this._timer)
      this._timer = setTimeout(callTimeout, this.ms, this)
    }
  }

  destroy () {
    this.done = true
    this.ontimeout = null

    if (this.interval) clearInterval(this._timer)
    else clearTimeout(this._timer)
  }

  static once (ms, fn, ctx) {
    return new this(ms, fn, ctx, false)
  }

  static on (ms, fn, ctx) {
    return new this(ms, fn, ctx, true)
  }
}

function callTimeout (self) {
  self.done = true
  self.ontimeout.call(self.context)
}

function callInterval (self) {
  self.ontimeout.call(self.context)
}
module.exports = isNode()
  ? require('./node')
  : require('./browser')

function isNode () {
  const to = setTimeout(function () {}, 1000)
  clearTimeout(to)
  return !!to.refresh
}
module.exports = class Timer {
  constructor (ms, fn, ctx = null, interval = false) {
    this.ms = ms
    this.ontimeout = fn
    this.context = ctx
    this.interval = interval
    this.done = false

    this._timer = interval
      ? setInterval(callInterval, ms, this)
      : setTimeout(callTimeout, ms, this)
  }

  unref () {
    this._timer.unref()
  }

  ref () {
    this._timer.ref()
  }

  refresh () {
    if (this.done !== true) this._timer.refresh()
  }

  destroy () {
    this.done = true
    this.ontimeout = null
    if (this.interval) clearInterval(this._timer)
    else clearTimeout(this._timer)
  }

  static once (ms, fn, ctx) {
    return new this(ms, fn, ctx, false)
  }

  static on (ms, fn, ctx) {
    return new this(ms, fn, ctx, true)
  }
}

function callTimeout (self) {
  self.done = true
  self.ontimeout.call(self.context)
}

function callInterval (self) {
  self.ontimeout.call(self.context)
}
{
  "name": "timeout-refresh",
  "version": "2.0.1",
  "description": "Efficiently refresh a timer",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^16.0.4",
    "tape": "^5.5.2"
  },
  "browser": "./browser.js",
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/timeout-refresh.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/timeout-refresh/issues"
  },
  "homepage": "https://github.com/mafintosh/timeout-refresh"
}
require.addon = require('require-addon')

module.exports = require.addon('.', __filename)
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

const v4Seg = '(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])'
const v4Str = `(${v4Seg}[.]){3}${v4Seg}`
const IPv4Pattern = new RegExp(`^${v4Str}$`)

const v6Seg = '(?:[0-9a-fA-F]{1,4})'
const IPv6Pattern = new RegExp(
  '^(' +
    `(?:${v6Seg}:){7}(?:${v6Seg}|:)|` +
    `(?:${v6Seg}:){6}(?:${v4Str}|:${v6Seg}|:)|` +
    `(?:${v6Seg}:){5}(?::${v4Str}|(:${v6Seg}){1,2}|:)|` +
    `(?:${v6Seg}:){4}(?:(:${v6Seg}){0,1}:${v4Str}|(:${v6Seg}){1,3}|:)|` +
    `(?:${v6Seg}:){3}(?:(:${v6Seg}){0,2}:${v4Str}|(:${v6Seg}){1,4}|:)|` +
    `(?:${v6Seg}:){2}(?:(:${v6Seg}){0,3}:${v4Str}|(:${v6Seg}){1,5}|:)|` +
    `(?:${v6Seg}:){1}(?:(:${v6Seg}){0,4}:${v4Str}|(:${v6Seg}){1,6}|:)|` +
    `(?::((?::${v6Seg}){0,5}:${v4Str}|(?::${v6Seg}){1,7}|:))` +
    ')(%[0-9a-zA-Z-.:]{1,})?$'
)

const isIPv4 = (exports.isIPv4 = function isIPv4(host) {
  return IPv4Pattern.test(host)
})

const isIPv6 = (exports.isIPv6 = function isIPv6(host) {
  return IPv6Pattern.test(host)
})

exports.isIP = function isIP(host) {
  if (isIPv4(host)) return 4
  if (isIPv6(host)) return 6
  return 0
}
const events = require('events')
const b4a = require('b4a')
const binding = require('../binding')

module.exports = class NetworkInterfaces extends events.EventEmitter {
  constructor(udx) {
    super()

    this._handle = b4a.alloc(binding.sizeof_udx_napi_interface_event_t)
    this._watching = false
    this._destroying = null

    binding.udx_napi_interface_event_init(
      udx._handle,
      this._handle,
      this,
      this._onevent,
      this._onclose
    )

    this.interfaces = binding.udx_napi_interface_event_get_addrs(this._handle)
  }

  _onclose() {
    this.emit('close')
  }

  _onevent() {
    this.interfaces = binding.udx_napi_interface_event_get_addrs(this._handle)

    this.emit('change', this.interfaces)
  }

  watch() {
    if (this._watching) return this
    this._watching = true

    binding.udx_napi_interface_event_start(this._handle)

    return this
  }

  unwatch() {
    if (!this._watching) return this
    this._watching = false

    binding.udx_napi_interface_event_stop(this._handle)

    return this
  }

  async destroy() {
    if (this._destroying) return this._destroying
    this._destroying = events.once(this, 'close')

    binding.udx_napi_interface_event_close(this._handle)

    return this._destroying
  }

  [Symbol.iterator]() {
    return this.interfaces[Symbol.iterator]()
  }
}
const events = require('events')
const b4a = require('b4a')
const binding = require('../binding')
const ip = require('./ip')

module.exports = class UDXSocket extends events.EventEmitter {
  constructor(udx, opts = {}) {
    super()

    this.udx = udx

    this._handle = b4a.alloc(binding.sizeof_udx_napi_socket_t)
    this._inited = false
    this._host = null
    this._family = 0
    this._ipv6Only = opts.ipv6Only === true
    this._reuseAddress = opts.reuseAddress === true
    this._port = 0
    this._reqs = []
    this._free = []
    this._closing = null
    this._closed = false

    this._view64 = new BigUint64Array(
      this._handle.buffer,
      this._handle.byteOffset,
      this._handle.byteLength >> 3
    )

    this.streams = new Set()

    this.userData = null
  }

  get bound() {
    return this._port !== 0
  }

  get closing() {
    return this._closing !== null
  }

  get idle() {
    return this.streams.size === 0
  }

  get busy() {
    return this.streams.size > 0
  }

  get bytesTransmitted() {
    if (this._inited !== true) return 0
    return Number(this._view64[binding.offsetof_udx_socket_t_bytes_tx >> 3])
  }

  get packetsTransmitted() {
    if (this._inited !== true) return 0
    return Number(this._view64[binding.offsetof_udx_socket_t_packets_tx >> 3])
  }

  get bytesReceived() {
    if (this._inited !== true) return 0
    return Number(this._view64[binding.offsetof_udx_socket_t_bytes_rx >> 3])
  }

  get packetsReceived() {
    if (this._inited !== true) return 0
    return Number(this._view64[binding.offsetof_udx_socket_t_packets_rx >> 3])
  }

  get packetsDroppedByKernel() {
    if (this._inited !== true) return 0
    return Number(this._view64[binding.offsetof_udx_socket_t_packets_dropped_by_kernel >> 3])
  }

  toJSON() {
    return {
      bound: this.bound,
      closing: this.closing,
      streams: this.streams.size,
      address: this.address(),
      ipv6Only: this._ipv6Only,
      reuseAddress: this._reuseAddress,
      idle: this.idle,
      busy: this.busy
    }
  }

  _init() {
    if (this._inited) return

    binding.udx_napi_socket_init(
      this.udx._handle,
      this._handle,
      this,
      this._onsend,
      this._onmessage,
      this._onclose,
      this._reallocMessage
    )

    this._inited = true
  }

  _onsend(id, err) {
    const req = this._reqs[id]

    const onflush = req.onflush

    req.buffer = null
    req.onflush = null

    this._free.push(id)

    onflush(err >= 0)

    // gc the free list
    if (this._free.length >= 16 && this._free.length === this._reqs.length) {
      this._free = []
      this._reqs = []
    }
  }

  _onmessage(len, port, host, family) {
    this.emit('message', this.udx._consumeMessage(len), { host, family, port })
    return this.udx._buffer
  }

  _onclose() {
    this.emit('close')
  }

  _reallocMessage() {
    return this.udx._reallocMessage()
  }

  _onidle() {
    this.emit('idle')
  }

  _onbusy() {
    this.emit('busy')
  }

  _addStream(stream) {
    if (this.streams.has(stream)) return false
    this.streams.add(stream)
    if (this.streams.size === 1) this._onbusy()
    return true
  }

  _removeStream(stream) {
    if (!this.streams.has(stream)) return false
    this.streams.delete(stream)
    const closed = this._closeMaybe()
    if (this.idle && !closed) this._onidle()
    return true
  }

  address() {
    if (!this.bound) return null
    return { host: this._host, family: this._family, port: this._port }
  }

  bind(port, host) {
    if (this.bound) throw new Error('Already bound')
    if (this.closing) throw new Error('Socket is closed')

    if (!port) port = 0

    let flags = 0
    if (this._ipv6Only) flags |= binding.UV_UDP_IPV6ONLY
    if (this._reuseAddress) flags |= binding.UV_UDP_REUSEADDR

    let family

    if (host) {
      family = ip.isIP(host)
      if (!family) throw new Error(`${host} is not a valid IP address`)

      if (!this._inited) this._init()

      this._port = binding.udx_napi_socket_bind(this._handle, port, host, family, flags)
    } else {
      if (!this._inited) this._init()

      try {
        host = '::'
        family = 6
        this._port = binding.udx_napi_socket_bind(this._handle, port, host, family, flags)
      } catch {
        host = '0.0.0.0'
        family = 4
        this._port = binding.udx_napi_socket_bind(this._handle, port, host, family, flags)
      }
    }

    this._host = host
    this._family = family

    this.emit('listening')
  }

  async close() {
    if (this._closing) return this._closing
    this._closing = new Promise((resolve) => this.once('close', resolve))
    this._closeMaybe()
    return this._closing
  }

  _closeMaybe() {
    if (this._closed || this._closing === null) return this._closed

    if (!this._inited) {
      this._closed = true
      this.emit('close')
      return true
    }

    if (this.idle) {
      binding.udx_napi_socket_close(this._handle)
      this._closed = true
    }

    return this._closed
  }

  setTTL(ttl) {
    if (!this._inited) throw new Error('Socket not active')
    binding.udx_napi_socket_set_ttl(this._handle, ttl)
  }

  getRecvBufferSize() {
    if (!this._inited) throw new Error('Socket not active')
    return binding.udx_napi_socket_get_recv_buffer_size(this._handle)
  }

  setRecvBufferSize(size) {
    if (!this._inited) throw new Error('Socket not active')
    return binding.udx_napi_socket_set_recv_buffer_size(this._handle, size)
  }

  getSendBufferSize() {
    if (!this._inited) throw new Error('Socket not active')
    return binding.udx_napi_socket_get_send_buffer_size(this._handle)
  }

  setSendBufferSize(size) {
    if (!this._inited) throw new Error('Socket not active')
    return binding.udx_napi_socket_set_send_buffer_size(this._handle, size)
  }

  addMembership(group, ifaceAddress) {
    if (!this._inited) throw new Error('Socket not active')
    return binding.udx_napi_socket_set_membership(this._handle, group, ifaceAddress || '', true)
  }

  dropMembership(group, ifaceAddress) {
    if (!this._inited) throw new Error('Socket not active')
    return binding.udx_napi_socket_set_membership(this._handle, group, ifaceAddress || '', false)
  }

  async send(buffer, port, host, ttl) {
    if (this.closing) return false

    if (!host) host = '127.0.0.1'

    const family = ip.isIP(host)
    if (!family) throw new Error(`${host} is not a valid IP address`)

    if (!this.bound) this.bind(0)

    const id = this._allocSend()
    const req = this._reqs[id]

    req.buffer = buffer

    const promise = new Promise((resolve) => {
      req.onflush = resolve
    })

    binding.udx_napi_socket_send_ttl(
      this._handle,
      req.handle,
      id,
      buffer,
      port,
      host,
      family,
      ttl || 0
    )

    return promise
  }

  trySend(buffer, port, host, ttl) {
    if (this.closing) return

    if (!host) host = '127.0.0.1'

    const family = ip.isIP(host)
    if (!family) throw new Error(`${host} is not a valid IP address`)

    if (!this.bound) this.bind(0)

    const id = this._allocSend()
    const req = this._reqs[id]

    req.buffer = buffer
    req.onflush = noop

    binding.udx_napi_socket_send_ttl(
      this._handle,
      req.handle,
      id,
      buffer,
      port,
      host,
      family,
      ttl || 0
    )
  }

  _allocSend() {
    if (this._free.length > 0) return this._free.pop()
    const handle = b4a.allocUnsafe(binding.sizeof_udx_socket_send_t)
    return this._reqs.push({ handle, buffer: null, onflush: null }) - 1
  }
}

function noop() {}
const streamx = require('streamx')
const b4a = require('b4a')
const binding = require('../binding')
const ip = require('./ip')

const MAX_PACKET = 2048
const BUFFER_SIZE = 65536 + MAX_PACKET

module.exports = class UDXStream extends streamx.Duplex {
  constructor(udx, id, opts = {}) {
    super({ mapWritable: toBuffer, eagerOpen: true })

    this.udx = udx
    this.socket = null

    this._handle = b4a.alloc(binding.sizeof_udx_napi_stream_t)
    this._view = new Uint32Array(
      this._handle.buffer,
      this._handle.byteOffset,
      this._handle.byteLength >> 2
    )
    this._view16 = new Uint16Array(
      this._handle.buffer,
      this._handle.byteOffset,
      this._handle.byteLength >> 1
    )
    this._view64 = new BigUint64Array(
      this._handle.buffer,
      this._handle.byteOffset,
      this._handle.byteLength >> 3
    )

    this._wreqs = []
    this._wfree = []

    this._sreqs = []
    this._sfree = []
    this._closed = false

    this._flushing = 0
    this._flushes = []

    this._buffer = null
    this._reallocData()

    this._onwrite = null
    this._ondestroy = null
    this._firewall = opts.firewall || firewallAll

    this._remoteChanging = null
    this._previousSocket = null

    this.id = id
    this.remoteId = 0
    this.remoteHost = null
    this.remoteFamily = 0
    this.remotePort = 0

    this.userData = null

    binding.udx_napi_stream_init(
      this.udx._handle,
      this._handle,
      id,
      opts.framed ? 1 : 0,
      this,
      this._ondata,
      this._onend,
      this._ondrain,
      this._onack,
      this._onsend,
      this._onmessage,
      this._onclose,
      this._onfirewall,
      this._onremotechanged,
      this._reallocData,
      this._reallocMessage
    )

    if (opts.seq) binding.udx_napi_stream_set_seq(this._handle, opts.seq)

    binding.udx_napi_stream_recv_start(this._handle, this._buffer)
  }

  get connected() {
    return this.socket !== null
  }

  get mtu() {
    return this._view16[binding.offsetof_udx_stream_t_mtu >> 1]
  }

  get rtt() {
    return this._view[binding.offsetof_udx_stream_t_srtt >> 2]
  }

  get cwnd() {
    return this._view[binding.offsetof_udx_stream_t_cwnd >> 2]
  }

  get rtoCount() {
    return this._view16[binding.offsetof_udx_stream_t_rto_count >> 1]
  }

  get retransmits() {
    return this._view16[binding.offsetof_udx_stream_t_retransmit_count >> 1]
  }

  get bbrState() {
    const view = new Uint8Array(
      this._handle.buffer,
      this._handle.byteOffset,
      this._handle.byteLength
    )
    return view[binding.offsetof_udx_stream_t_bbr_state]
  }

  get bbrBandwidth() {
    return binding.udx_napi_stream_get_bw(this._handle)
  }

  get fastRecoveries() {
    return this._view16[binding.offsetof_udx_stream_t_fast_recovery_count >> 1]
  }

  get inflight() {
    return this._view[binding.offsetof_udx_stream_t_inflight >> 2]
  }

  get bytesTransmitted() {
    return Number(this._view64[binding.offsetof_udx_stream_t_bytes_tx >> 3])
  }

  get packetsTransmitted() {
    return Number(this._view64[binding.offsetof_udx_stream_t_packets_tx >> 3])
  }

  get bytesReceived() {
    return Number(this._view64[binding.offsetof_udx_stream_t_bytes_rx >> 3])
  }

  get packetsReceived() {
    return Number(this._view64[binding.offsetof_udx_stream_t_packets_rx >> 3])
  }

  get localHost() {
    return this.socket ? this.socket.address().host : null
  }

  get localFamily() {
    return this.socket ? this.socket.address().family : 0
  }

  get localPort() {
    return this.socket ? this.socket.address().port : 0
  }

  setInteractive(bool) {
    if (!this._closed) return
    binding.udx_napi_stream_set_mode(this._handle, bool ? 0 : 1)
  }

  connect(socket, remoteId, port, host, opts = {}) {
    if (this._closed) return

    if (this.connected) throw new Error('Already connected')
    if (socket.closing) throw new Error('Socket is closed')

    if (typeof host === 'object') {
      opts = host
      host = null
    }

    if (!host) host = '127.0.0.1'

    const family = ip.isIP(host)
    if (!family) throw new Error(`${host} is not a valid IP address`)
    if (!(port > 0 && port < 65536)) throw new Error(`${port} is not a valid port`)

    if (!socket.bound) socket.bind(0)

    this.remoteId = remoteId
    this.remotePort = port
    this.remoteHost = host
    this.remoteFamily = family
    this.socket = socket

    if (opts.ack) binding.udx_napi_stream_set_ack(this._handle, opts.ack)

    binding.udx_napi_stream_connect(this._handle, socket._handle, remoteId, port, host, family)

    this.socket._addStream(this)

    this.emit('connect')
  }

  changeRemote(socket, remoteId, port, host) {
    if (this._remoteChanging) throw new Error('Remote already changing')

    if (!this.connected) throw new Error('Not yet connected')
    if (socket.closing) throw new Error('Socket is closed')

    if (this.socket.udx !== socket.udx) {
      throw new Error('Cannot change to a socket on another UDX instance')
    }

    if (!host) host = '127.0.0.1'

    const family = ip.isIP(host)
    if (!family) throw new Error(`${host} is not a valid IP address`)
    if (!(port > 0 && port < 65536)) throw new Error(`${port} is not a valid port`)

    if (this.socket !== socket) this._previousSocket = this.socket

    this.remoteId = remoteId
    this.remotePort = port
    this.remoteHost = host
    this.remoteFamily = family
    this.socket = socket

    this._remoteChanging = new Promise((resolve, reject) => {
      const onchanged = () => {
        this.off('close', onclose)
        resolve()
      }

      const onclose = () => {
        this.off('remote-changed', onchanged)
        reject(new Error('Stream is closed'))
      }

      this.once('remote-changed', onchanged).once('close', onclose)
    })

    binding.udx_napi_stream_change_remote(
      this._handle,
      socket._handle,
      remoteId,
      port,
      host,
      family
    )

    this.socket._addStream(this)

    return this._remoteChanging
  }

  relayTo(destination) {
    if (this._closed) return

    binding.udx_napi_stream_relay_to(this._handle, destination._handle)
  }

  async send(buffer) {
    if (!this.connected || this._closed) return false

    const id = this._allocSend()
    const req = this._sreqs[id]

    req.buffer = buffer

    const promise = new Promise((resolve) => {
      req.onflush = resolve
    })

    binding.udx_napi_stream_send(this._handle, req.handle, id, buffer)

    return promise
  }

  trySend(buffer) {
    if (!this.connected || this._closed) return

    const id = this._allocSend()
    const req = this._sreqs[id]

    req.buffer = buffer
    req.onflush = noop

    binding.udx_napi_stream_send(this._handle, req.handle, id, buffer)
  }

  async flush() {
    if ((await streamx.Writable.drained(this)) === false) return false
    if (this.destroying) return false

    const missing = this._wreqs.length - this._wfree.length
    if (missing === 0) return true

    return new Promise((resolve) => {
      this._flushes.push({ flush: this._flushing++, missing, resolve })
    })
  }

  toJSON() {
    return {
      id: this.id,
      connected: this.connected,
      destroying: this.destroying,
      destroyed: this.destroyed,
      remoteId: this.remoteId,
      remoteHost: this.remoteHost,
      remoteFamily: this.remoteFamily,
      remotePort: this.remotePort,
      mtu: this.mtu,
      rtt: this.rtt,
      cwnd: this.cwnd,
      inflight: this.inflight,
      socket: this.socket ? this.socket.toJSON() : null
    }
  }

  _read(cb) {
    cb(null)
  }

  _writeContinue(err) {
    if (this._onwrite === null) return
    const cb = this._onwrite
    this._onwrite = null
    cb(err)
  }

  _destroyContinue(err) {
    if (this._ondestroy === null) return
    const cb = this._ondestroy
    this._ondestroy = null
    cb(err)
  }

  _writev(buffers, cb) {
    if (!this.connected) {
      throw customError('Writing while not connected not currently supported', 'ERR_ASSERTION')
    }

    let drained = true

    if (buffers.length === 1) {
      const id = this._allocWrite(1)
      const req = this._wreqs[id]

      req.flush = this._flushing
      req.buffer = buffers[0]

      drained = binding.udx_napi_stream_write(this._handle, req.handle, id, req.buffer) !== 0
    } else {
      const id = this._allocWrite(nextBatchSize(buffers.length))
      const req = this._wreqs[id]

      req.flush = this._flushing
      req.buffers = buffers

      drained = binding.udx_napi_stream_writev(this._handle, req.handle, id, req.buffers) !== 0
    }

    if (drained) cb(null)
    else this._onwrite = cb
  }

  _final(cb) {
    const id = this._allocWrite(1)
    const req = this._wreqs[id]

    req.flush = this._flushes
    req.buffer = b4a.allocUnsafe(0)

    const drained =
      binding.udx_napi_stream_write_end(this._handle, req.handle, id, req.buffer) !== 0

    if (drained) cb(null)
    else this._onwrite = cb
  }

  _predestroy() {
    if (!this._closed) binding.udx_napi_stream_destroy(this._handle)
    this._closed = true
    this._writeContinue(null)
  }

  _destroy(cb) {
    if (this.connected) this._ondestroy = cb
    else cb(null)
  }

  _ondata(read) {
    this.push(this._consumeData(read))
    return this._buffer
  }

  _onend(read) {
    if (read > 0) this.push(this._consumeData(read))
    this.push(null)
  }

  _ondrain() {
    this._writeContinue(null)
  }

  _flushAck(flush) {
    for (let i = this._flushes.length - 1; i >= 0; i--) {
      const f = this._flushes[i]
      if (f.flush < flush) break
      f.missing--
    }

    while (this._flushes.length > 0 && this._flushes[0].missing === 0) {
      this._flushes.shift().resolve(true)
    }
  }

  _onack(id) {
    const req = this._wreqs[id]

    req.buffers = req.buffer = null
    this._wfree.push(id)

    if (this._flushes.length > 0) this._flushAck(req.flush)

    // gc the free list
    if (this._wfree.length >= 64 && this._wfree.length === this._wreqs.length) {
      this._wfree = []
      this._wreqs = []
    }
  }

  _onsend(id, err) {
    const req = this._sreqs[id]

    const onflush = req.onflush

    req.buffer = null
    req.onflush = null

    this._sfree.push(id)

    onflush(err >= 0)

    // gc the free list
    if (this._sfree.length >= 16 && this._sfree.length === this._sreqs.length) {
      this._sfree = []
      this._sreqs = []
    }
  }

  _onmessage(len) {
    this.emit('message', this.udx._consumeMessage(len))
    return this.udx._buffer
  }

  _onclose(err) {
    this._closed = true

    if (this.socket) {
      this.socket._removeStream(this)
      this.socket = null
    }

    if (this._previousSocket) {
      this._previousSocket._removeStream(this)
      this._previousSocket = null
    }

    // no error, we don't need to do anything
    if (!err) return this._destroyContinue(null)

    if (this._ondestroy === null) this.destroy(err)
    else this._destroyContinue(err)
  }

  _onfirewall(socket, port, host, family) {
    if (port <= 0 || port > 65535) return 1
    return this._firewall(socket, port, host, family) ? 1 : 0
  }

  _onremotechanged() {
    if (this._previousSocket) {
      this._previousSocket._removeStream(this)
      this._previousSocket = null
    }

    this._remoteChanging = null
    this.emit('remote-changed')
  }

  _consumeData(len) {
    const next = this._buffer.subarray(0, len)
    this._buffer = this._buffer.subarray(len)
    if (this._buffer.byteLength < MAX_PACKET) this._reallocData()
    return next
  }

  _reallocData() {
    this._buffer = b4a.allocUnsafe(BUFFER_SIZE)
    return this._buffer
  }

  _reallocMessage() {
    return this.udx._reallocMessage()
  }

  _allocWrite(size) {
    if (this._wfree.length === 0) {
      const handle = b4a.allocUnsafe(binding.udx_napi_stream_write_sizeof(size))
      return (
        this._wreqs.push({
          handle,
          size,
          buffers: null,
          buffer: null,
          flush: 0
        }) - 1
      )
    }

    const free = this._wfree.pop()
    if (size === 1) return free

    const next = this._wreqs[free]
    if (next.size < size) {
      next.handle = b4a.allocUnsafe(binding.udx_napi_stream_write_sizeof(size))
      next.size = size
    }

    return free
  }

  _allocSend() {
    if (this._sfree.length > 0) return this._sfree.pop()
    const handle = b4a.allocUnsafe(binding.sizeof_udx_stream_send_t)
    return this._sreqs.push({ handle, buffer: null, resolve: null, reject: null }) - 1
  }
}

function noop() {}

function toBuffer(data) {
  return typeof data === 'string' ? b4a.from(data) : data
}

function firewallAll(socket, port, host) {
  return true
}

function customError(message, code) {
  const error = new Error(message)
  error.code = code
  return error
}

function nextBatchSize(n) {
  // try to coerce the the writevs into sameish size
  if (n === 1) return 1
  // group all < 8 to the same size, low mem overhead but save some small allocs
  if (n < 8) return 8
  if (n < 16) return 16
  if (n < 32) return 32
  if (n < 64) return 64
  return n
}
const b4a = require('b4a')
const binding = require('../binding')
const ip = require('./ip')
const Socket = require('./socket')
const Stream = require('./stream')
const NetworkInterfaces = require('./network-interfaces')

const MAX_MESSAGE = 4096
const BUFFER_SIZE = 65536 + MAX_MESSAGE

module.exports = class UDX {
  constructor() {
    this._handle = b4a.alloc(binding.sizeof_udx_napi_t)
    this._watchers = new Set()
    this._view64 = new BigUint64Array(
      this._handle.buffer,
      this._handle.byteOffset,
      this._handle.byteLength >> 3
    )

    this._buffer = null
    this._reallocMessage()

    binding.udx_napi_init(this._handle, this._buffer)
  }

  static isIPv4(host) {
    return ip.isIPv4(host)
  }

  static isIPv6(host) {
    return ip.isIPv6(host)
  }

  static isIP(host) {
    return ip.isIP(host)
  }

  get bytesTransmitted() {
    return Number(this._view64[binding.offsetof_udx_t_bytes_tx >> 3])
  }

  get packetsTransmitted() {
    return Number(this._view64[binding.offsetof_udx_t_packets_tx >> 3])
  }

  get bytesReceived() {
    return Number(this._view64[binding.offsetof_udx_t_bytes_rx >> 3])
  }

  get packetsReceived() {
    return Number(this._view64[binding.offsetof_udx_t_packets_rx >> 3])
  }

  get packetsDroppedByKernel() {
    return Number(this._view64[binding.offsetof_udx_t_packets_dropped_by_kernel >> 3])
  }

  _consumeMessage(len) {
    const next = this._buffer.subarray(0, len)
    this._buffer = this._buffer.subarray(len)
    if (this._buffer.byteLength < MAX_MESSAGE) this._reallocMessage()
    return next
  }

  _reallocMessage() {
    // TODO: move reallocation to native
    this._buffer = b4a.allocUnsafe(BUFFER_SIZE)
    return this._buffer
  }

  createSocket(opts) {
    return new Socket(this, opts)
  }

  createStream(id, opts) {
    return new Stream(this, id, opts)
  }

  networkInterfaces() {
    let [watcher = null] = this._watchers
    if (watcher) return watcher.interfaces

    watcher = new NetworkInterfaces(this)
    watcher.destroy()

    return watcher.interfaces
  }

  watchNetworkInterfaces(onchange) {
    const watcher = new NetworkInterfaces(this)

    this._watchers.add(watcher)
    watcher.on('close', () => {
      this._watchers.delete(watcher)
    })

    if (onchange) watcher.on('change', onchange)

    return watcher.watch()
  }

  async lookup(host, opts = {}) {
    const { family = 0 } = opts

    const req = b4a.alloc(binding.sizeof_udx_napi_lookup_t)
    const ctx = {
      req,
      resolve: null,
      reject: null
    }

    const promise = new Promise((resolve, reject) => {
      ctx.resolve = resolve
      ctx.reject = reject
    })

    binding.udx_napi_lookup(this._handle, req, host, family, ctx, onlookup)

    return promise
  }
}

function onlookup(err, host, family) {
  if (err) this.reject(err)
  else this.resolve({ host, family })
}
{
  "name": "udx-native",
  "version": "1.20.7",
  "description": "udx is reliable, multiplexed, and congestion-controlled streams over udp",
  "main": "lib/udx.js",
  "files": [
    "lib",
    "prebuilds",
    "binding.cc",
    "binding.js",
    "CMakeLists.txt"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "addon": true,
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node --coverage test/*.js",
    "test:bare": "brittle-bare --coverage test/*.js",
    "test:all": "brittle test/*.js test/slow/*.js",
    "test:generate": "brittle -r test/all.js test/*.js",
    "bench": "brittle test/bench/*.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/udx-native.git"
  },
  "keywords": [
    "tcp",
    "udp",
    "stream",
    "reliable"
  ],
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/udx-native/issues"
  },
  "homepage": "https://github.com/holepunchto/udx-native#readme",
  "engines": {
    "bare": ">=1.17.4"
  },
  "dependencies": {
    "b4a": "^1.5.0",
    "bare-events": "^2.2.0",
    "require-addon": "^1.1.0",
    "streamx": "^2.22.0"
  },
  "devDependencies": {
    "bare-compat-napi": "^1.3.0",
    "brittle": "^3.1.0",
    "cmake-bare": "^1.1.10",
    "cmake-fetch": "^1.0.1",
    "cmake-napi": "^1.0.5",
    "is-ci": "^3.0.1",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "tiny-byte-size": "^1.1.0"
  }
}
exports.add = add
exports.has = has
exports.remove = remove
exports.swap = swap

function add (list, item) {
  if (has(list, item)) return item
  item._index = list.length
  list.push(item)
  return item
}

function has (list, item) {
  return item._index < list.length && list[item._index] === item
}

function remove (list, item) {
  if (!has(list, item)) return null

  var last = list.pop()
  if (last !== item) {
    list[item._index] = last
    last._index = item._index
  }

  return item
}

function swap (list, a, b) {
  if (!has(list, a) || !has(list, b)) return
  var tmp = a._index
  a._index = b._index
  list[a._index] = a
  b._index = tmp
  list[b._index] = b
}
{
  "name": "unordered-set",
  "version": "2.0.1",
  "description": "A couple of functions that make it easy to maintain an unordered set as an array in an efficient way",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^6.0.4",
    "tape": "^4.4.0"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/unordered-set.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/unordered-set/issues"
  },
  "homepage": "https://github.com/mafintosh/unordered-set"
}
const b4a = require('b4a')

unslab.all = all
unslab.is = is

module.exports = unslab

function unslab (buf) {
  if (buf === null || buf.buffer.byteLength === buf.byteLength) return buf
  const copy = b4a.allocUnsafeSlow(buf.byteLength)
  copy.set(buf, 0)
  return copy
}

function is (buf) {
  return buf.buffer.byteLength !== buf.byteLength
}

function all (list) {
  let size = 0
  for (let i = 0; i < list.length; i++) {
    const buf = list[i]
    size += buf === null || buf.buffer.byteLength === buf.byteLength ? 0 : buf.byteLength
  }

  const copy = b4a.allocUnsafeSlow(size)
  const result = new Array(list.length)

  let offset = 0
  for (let i = 0; i < list.length; i++) {
    let buf = list[i]

    if (buf !== null && buf.buffer.byteLength !== buf.byteLength) {
      copy.set(buf, offset)
      buf = copy.subarray(offset, offset += buf.byteLength)
    }

    result[i] = buf
  }

  return result
}
{
  "name": "unslab",
  "version": "1.3.0",
  "description": "Unslab some slab'ed buffers",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.6.6"
  },
  "devDependencies": {
    "brittle": "^3.5.2",
    "standard": "^17.1.0"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/unslab.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/unslab/issues"
  },
  "homepage": "https://github.com/holepunchto/unslab"
}
module.exports = read

var MSB = 0x80
  , REST = 0x7F

function read(buf, offset) {
  var res    = 0
    , offset = offset || 0
    , shift  = 0
    , counter = offset
    , b
    , l = buf.length

  do {
    if (counter >= l) {
      read.bytes = 0
      throw new RangeError('Could not decode varint')
    }
    b = buf[counter++]
    res += shift < 28
      ? (b & REST) << shift
      : (b & REST) * Math.pow(2, shift)
    shift += 7
  } while (b >= MSB)

  read.bytes = counter - offset

  return res
}
module.exports = encode

var MSB = 0x80
  , REST = 0x7F
  , MSBALL = ~REST
  , INT = Math.pow(2, 31)

function encode(num, out, offset) {
  out = out || []
  offset = offset || 0
  var oldOffset = offset

  while(num >= INT) {
    out[offset++] = (num & 0xFF) | MSB
    num /= 128
  }
  while(num & MSBALL) {
    out[offset++] = (num & 0xFF) | MSB
    num >>>= 7
  }
  out[offset] = num | 0
  
  encode.bytes = offset - oldOffset + 1
  
  return out
}
module.exports = {
    encode: require('./encode.js')
  , decode: require('./decode.js')
  , encodingLength: require('./length.js')
}

var N1 = Math.pow(2,  7)
var N2 = Math.pow(2, 14)
var N3 = Math.pow(2, 21)
var N4 = Math.pow(2, 28)
var N5 = Math.pow(2, 35)
var N6 = Math.pow(2, 42)
var N7 = Math.pow(2, 49)
var N8 = Math.pow(2, 56)
var N9 = Math.pow(2, 63)

module.exports = function (value) {
  return (
    value < N1 ? 1
  : value < N2 ? 2
  : value < N3 ? 3
  : value < N4 ? 4
  : value < N5 ? 5
  : value < N6 ? 6
  : value < N7 ? 7
  : value < N8 ? 8
  : value < N9 ? 9
  :              10
  )
}
{
  "name": "varint",
  "version": "5.0.0",
  "description": "protobuf-style varint bytes - use msb to create integer values of varying sizes",
  "main": "index.js",
  "scripts": {
    "test": "node test.js"
  },
  "repository": {
    "type": "git",
    "url": "git://github.com/chrisdickinson/varint.git"
  },
  "keywords": [
    "varint",
    "protobuf",
    "encode",
    "decode"
  ],
  "author": "Chris Dickinson <chris@neversaw.us>",
  "license": "MIT",
  "devDependencies": {
    "tape": "~2.12.3"
  }
}
const { runtime, platform, arch, version } =
  typeof Bare !== 'undefined'
    ? {
        runtime: 'bare',
        platform: global.Bare.platform,
        arch: global.Bare.arch,
        version: global.Bare.version
      }
    : typeof process !== 'undefined'
      ? {
          runtime: 'node',
          platform: global.process.platform,
          arch: global.process.arch,
          version: global.process.version
        }
      : typeof Window !== 'undefined'
        ? { runtime: 'browser', platform: 'unknown', arch: 'unknown', version: 'unknown' }
        : { runtime: 'unknown', platform: 'unknown', arch: 'unknown', version: 'unknown' }

exports.runtime = runtime
exports.version = version
exports.platform = platform
exports.arch = arch
exports.isBare = runtime === 'bare'
exports.isBareKit = exports.isBare && typeof BareKit !== 'undefined'
exports.isPear = typeof Pear !== 'undefined'
exports.isNode = runtime === 'node'
exports.isBrowser = runtime === 'browser'
exports.isWindows = platform === 'win32'
exports.isLinux = platform === 'linux'
exports.isMac = platform === 'darwin'
exports.isIOS = platform === 'ios' || platform === 'ios-simulator'
exports.isAndroid = platform === 'android'
exports.isElectron = typeof process !== 'undefined' && !!global.process.versions?.electron
exports.isElectronRenderer = exports.isElectron && global.process.type === 'renderer'
exports.isElectronWorker = exports.isElectron && global.process.type === 'worker'
{
  "name": "which-runtime",
  "version": "1.4.0",
  "description": "Detect if you are in Bare or Node and which os etc",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte .",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/which-runtime.git"
  },
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/which-runtime/issues"
  },
  "homepage": "https://github.com/holepunchto/which-runtime",
  "devDependencies": {
    "brittle": "^3.0.0",
    "lunte": "^1.4.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = class MaxCache {
  constructor ({ maxSize, maxAge, createMap, ongc }) {
    this.maxSize = maxSize
    this.maxAge = maxAge
    this.ongc = ongc || null

    this._createMap = createMap || defaultCreateMap
    this._latest = this._createMap()
    this._oldest = this._createMap()
    this._retained = this._createMap()
    this._gced = false
    this._interval = null

    if (this.maxAge > 0 && this.maxAge < Infinity) {
      const tick = Math.ceil(2 / 3 * this.maxAge)
      this._interval = setInterval(this._gcAuto.bind(this), tick)
      if (this._interval.unref) this._interval.unref()
    }
  }

  * [Symbol.iterator] () {
    for (const it of [this._latest, this._oldest, this._retained]) {
      yield * it
    }
  }

  * keys () {
    for (const it of [this._latest, this._oldest, this._retained]) {
      yield * it.keys()
    }
  }

  * values () {
    for (const it of [this._latest, this._oldest, this._retained]) {
      yield * it.values()
    }
  }

  destroy () {
    this.clear()
    clearInterval(this._interval)
    this._interval = null
  }

  clear () {
    this._gced = true
    this._latest.clear()
    this._oldest.clear()
    this._retained.clear()
  }

  set (k, v) {
    if (this._retained.has(k)) return this
    this._latest.set(k, v)
    this._oldest.delete(k) || this._retained.delete(k)
    if (this._latest.size >= this.maxSize) this._gc()
    return this
  }

  retain (k, v) {
    this._retained.set(k, v)
    this._latest.delete(k) || this._oldest.delete(k)
    return this
  }

  delete (k) {
    return this._latest.delete(k) || this._oldest.delete(k) || this._retained.delete(k)
  }

  has (k) {
    return this._latest.has(k) || this._oldest.has(k) || this._retained.has(k)
  }

  get (k) {
    if (this._latest.has(k)) {
      return this._latest.get(k)
    }

    if (this._oldest.has(k)) {
      const v = this._oldest.get(k)
      this._latest.set(k, v)
      this._oldest.delete(k)
      return v
    }

    if (this._retained.has(k)) {
      return this._retained.get(k)
    }

    return null
  }

  _gcAuto () {
    if (!this._gced) this._gc()
    this._gced = false
  }

  _gc () {
    this._gced = true
    if (this.ongc !== null && this._oldest.size > 0) this.ongc(this._oldest)
    this._oldest = this._latest
    this._latest = this._createMap()
  }
}

function defaultCreateMap () {
  return new Map()
}
{
  "name": "xache",
  "version": "1.2.1",
  "description": "Yet another auto expiring, max sizable cache",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "devDependencies": {
    "brittle": "^3.3.2",
    "standard": "^17.1.0"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/xache.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/xache/issues"
  },
  "homepage": "https://github.com/mafintosh/xache"
}
const b4a = require('b4a')

const ALPHABET = 'ybndrfg8ejkmcpqxot1uwisza345h769'
const MIN = 0x31 // 1
const MAX = 0x7a // z
const REVERSE = new Int8Array(1 + MAX - MIN)

REVERSE.fill(-1)

for (let i = 0; i < ALPHABET.length; i++) {
  const v = ALPHABET.charCodeAt(i) - MIN
  REVERSE[v] = i
}

exports.encode = encode
exports.decode = decode
exports.ALPHABET = ALPHABET

function decode (s, out) {
  let pb = 0
  let ps = 0

  const r = s.length & 7
  const q = (s.length - r) / 8

  if (!out) out = b4a.allocUnsafe(Math.ceil(s.length * 5 / 8))

  // 0 5 2 7 4 1 6 3 (+5 mod 8)
  for (let i = 0; i < q; i++) {
    const a = quintet(s, ps++)
    const b = quintet(s, ps++)
    const c = quintet(s, ps++)
    const d = quintet(s, ps++)
    const e = quintet(s, ps++)
    const f = quintet(s, ps++)
    const g = quintet(s, ps++)
    const h = quintet(s, ps++)

    out[pb++] = (a << 3) | (b >>> 2)
    out[pb++] = ((b & 0b11) << 6) | (c << 1) | (d >>> 4)
    out[pb++] = ((d & 0b1111) << 4) | (e >>> 1)
    out[pb++] = ((e & 0b1) << 7) | (f << 2) | (g >>> 3)
    out[pb++] = ((g & 0b111) << 5) | h
  }

  if (r === 0) return out.subarray(0, pb)

  const a = quintet(s, ps++)
  const b = quintet(s, ps++)

  out[pb++] = (a << 3) | (b >>> 2)

  if (r <= 2) return out.subarray(0, pb)

  const c = quintet(s, ps++)
  const d = quintet(s, ps++)

  out[pb++] = ((b & 0b11) << 6) | (c << 1) | (d >>> 4)

  if (r <= 4) return out.subarray(0, pb)

  const e = quintet(s, ps++)

  out[pb++] = ((d & 0b1111) << 4) | (e >>> 1)

  if (r <= 5) return out.subarray(0, pb)

  const f = quintet(s, ps++)
  const g = quintet(s, ps++)

  out[pb++] = ((e & 0b1) << 7) | (f << 2) | (g >>> 3)

  if (r <= 7) return out.subarray(0, pb)

  const h = quintet(s, ps++)

  out[pb++] = ((g & 0b111) << 5) | h

  return out.subarray(0, pb)
}

function encode (buf) {
  if (typeof buf === 'string') buf = b4a.from(buf)

  const max = buf.byteLength * 8

  let s = ''

  for (let p = 0; p < max; p += 5) {
    const i = p >>> 3
    const j = p & 7

    if (j <= 3) {
      s += ALPHABET[(buf[i] >>> (3 - j)) & 0b11111]
      continue
    }

    const of = j - 3
    const h = (buf[i] << of) & 0b11111
    const l = (i >= buf.byteLength ? 0 : buf[i + 1]) >>> (8 - of)

    s += ALPHABET[h | l]
  }

  return s
}

function quintet (s, i) {
  if (i > s.length) {
    return 0
  }

  const v = s.charCodeAt(i)

  if (v < MIN || v > MAX) {
    throw Error('Invalid character in base32 input: "' + s[i] + '" at position ' + i)
  }

  const bits = REVERSE[v - MIN]

  if (bits === -1) {
    throw Error('Invalid character in base32 input: "' + s[i] + '" at position ' + i)
  }

  return bits
}
{
  "name": "z32",
  "version": "1.1.0",
  "description": "Encode & decode z-base32",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.5.3"
  },
  "devDependencies": {
    "base-x": "^4.0.0",
    "base32": "0.0.7",
    "brittle": "^3.1.3",
    "nanobench": "^3.0.0",
    "rfc4648": "^1.5.2",
    "standard": "^17.0.0"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/z32.git"
  },
  "scripts": {
    "test": "standard && brittle test.js",
    "bench": "node benchmark.js"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/z32/issues"
  },
  "homepage": "https://github.com/mafintosh/z32"
}
{
  "name": "favela-web",
  "version": "0.3.89",
  "description": "favela-web \u2014 the web/SSR surface of Favela, the native P2P-local, community-owned social client + appview over the self-custody atproto stack (hyper-proto-peer). One of the Favela surfaces (alongside favela-cli and favela-native). bsky is an optional POSSE export, not the home. See DESIGN.md.",
  "type": "module",
  "main": "bin/favela-web.js",
  "bin": {
    "favela-web": "bin/favela-web.js"
  },
  "pgh": {
    "bin": "favela-web",
    "stage": {
      "ignore": [
        "data/"
      ]
    },
    "upgrade": "pgh://1dd36bdfa9cb7f7d84adbd07f017e7200f7f90a3a546cd0761fac2a1f8a13e86/favela-web",
    "entrypoint": "bin/favela-web.js",
    "type": "daemon",
    "runtime": "bare",
    "autostart": true,
    "depends": [
      "pgh-sidecar"
    ],
    "defaults": {
      "env": {
        "FAVELA_PORT": "4041",
        "FAVELA_HOST": "0.0.0.0",
        "FAVELA_EXTERNAL_URL": "https://pds.7rnx.net",
        "FAVELA_COMMUNITY_ROOMS": "loser-club=91ce4dbcb6b4fe0cfa489582cb9931923c05e0d14cf0a5c939d8334edefe21ed",
        "ATPROTO_OVERLAY_ROOT": "${HOME}/.config/hyper-proto-peer/data/atproto-repo",
        "FAVELA_STORE_ROOT": "${HOME}/.config/favela-web/data",
        "FAVELA_SPACEDUST": "1",
        "FAVELA_RETENTION_BUDGET": "268435456",
        "FAVELA_AP_BRIDGE": "https://ap.7rnx.net"
      }
    },
    "readiness": {
      "type": "http",
      "port": "4041",
      "timeoutMs": 120000
    },
    "service": {
      "port": 4041,
      "host": "0.0.0.0",
      "requiresNetwork": true
    },
    "systemd": {
      "user": true,
      "enable": true,
      "restart": "on-failure"
    }
  },
  "scripts": {
    "spike:seam": "node spike/atcute-seam.mjs",
    "spike:p2p": "node spike/p2p-read.mjs",
    "web": "bare bin/favela-web.js",
    "test": "node test/render.test.mjs && node test/static-assets.test.mjs && node test/resize-plan.test.mjs && node test/notifications.test.mjs && node test/ap-followers.test.mjs && node test/reach.test.mjs && node test/edit.test.mjs && node test/facets.test.mjs && node test/mutes.test.mjs && node test/search.test.mjs && node test/threadgate.test.mjs && node test/bookmarks.test.mjs && node test/postgate.test.mjs && node test/lists.test.mjs && node test/cli-reachable.test.mjs && node test/strongref.test.mjs && node test/lens-import.test.mjs && node test/lens-thread-extract.test.mjs && node test/fronts-diag.test.mjs && node test/gate-policy.test.mjs && node test/sessions.test.mjs && node test/check.test.mjs && node test/auth.test.mjs && node test/browser-auth-client.test.mjs && node test/communities.test.mjs && node test/feedgen.test.mjs && node test/feed-reactor.test.mjs && node test/labeler-export.test.mjs && node test/label-firehose.test.mjs && node test/pairing.test.mjs && node test/writer.test.mjs && node test/blob-serve.test.mjs && node test/blobs.test.mjs && node test/spacedust.test.mjs && node test/spacedust-failclosed.test.mjs && node test/link-drain.test.mjs && node test/record-verify.test.mjs && node test/constellation.test.mjs && node test/retention.test.mjs && node test/hosted-dids.test.mjs && node test/repair-bytes.test.mjs && node test/repo-sync.test.mjs && node test/blob-refs.test.mjs && node test/inbound.test.mjs && node test/followers.test.mjs && node test/repair-strongrefs.test.mjs && node test/conformance.test.mjs && node test/dns-txt.test.mjs && node test/interaction-codec.test.js",
    "test:ws": "bare test/subscribe-labels-ws.test.mjs",
    "test:bare": "bare test/appview.test.mjs && bare test/appview-ingest.test.mjs && bare test/appview-dedup.test.mjs && bare test/appview-no-clobber.test.mjs && bare test/appview-blocks.test.mjs && bare test/appview-thread.test.mjs && bare test/appview-author-filter.test.mjs && bare test/appview-collections.test.mjs && bare test/bounded-fetch.test.mjs",
    "spike:pack": "bare spike/mobile-pack-probe.mjs",
    "gen:static": "node scripts/gen-static-assets.mjs"
  },
  "dependencies": {
    "@atcute/client": "^5.1.1",
    "@ipld/dag-cbor": "^9.2.7",
    "atproto-did-peer": "file:../atproto-did-peer",
    "atproto-identity": "file:../atproto-identity",
    "atproto-repo": "file:../atproto-repo",
    "atproto-room": "file:../atproto-room",
    "atproto-store": "file:../atproto-store",
    "b4a": "^1.8.1",
    "bare-fetch": "^3.0.1",
    "bare-http1": "^4.0.0",
    "bare-net": "^2.3.2",
    "bare-process": "^4.0.0",
    "bare-ws": "^3.0.0",
    "blind-pairing": "^2.3.1",
    "compact-encoding": "^2.19.0",
    "corestore": "^7.4.0",
    "favela-community": "file:../favela-community",
    "hyper-identity": "file:../packages/hyper-identity",
    "hyper-proto-peer": "file:../hyper-proto-peer",
    "hyper-svc": "file:../hyper-svc",
    "hyperbee": "^2.20.0",
    "hypercore-crypto": "^3.4.0",
    "hyperswarm": "^4.11.0",
    "protomux-rpc": "^1.10.0"
  }
}
// GENERATED by scripts/gen-static-assets.mjs — DO NOT EDIT.
//
// web/static/ as a module, so the browser scripts survive bundling. lib/static.js reads the filesystem
// first (unchanged for servers) and falls back to this map, which is the only copy that exists inside
// favela-android's worklet bundle. Regenerate with `npm run gen:static`; test/static-assets.test.mjs
// fails if this drifts from web/static/.
export const STATIC_ASSETS = {
  "actions.js": "// Responsive like / repost / follow — progressive enhancement over the plain forms.\n//\n// THE PROBLEM. Every one of these is a real <form method=\"POST\"> that redirects back to `return`. That is\n// what makes them work with scripting off, and it stays the fallback — but with JS on it means a FULL PAGE\n// RELOAD to toggle a heart: the timeline is re-fetched and re-rendered, scroll position is lost, and on a\n// slow P2P read the whole page stalls behind one click. The affordance felt broken even though it worked.\n//\n// The server already speaks JSON on these routes (`content-type: application/json` -> {ok, liked,\n// likeCount} / {ok, reposted, repostCount} / {ok, following}) instead of redirecting. Nothing server-side\n// was needed; only this.\n//\n// OPTIMISTIC, THEN RECONCILED. The button flips immediately — a P2P write can take a moment and a control\n// that does nothing for 400ms reads as broken. If the request fails we put the ORIGINAL state back and say\n// so, rather than leaving a lie on screen. The server's returned count is authoritative and overwrites the\n// optimistic guess, so a concurrent like from another device self-corrects on the next click.\n//\n// Delegated on document, so posts swapped in by the live refresh keep working with nothing to re-bind.\nimport { toast } from './toast.js'\n\n// Naming the action in the message matters: \"failed\" on its own does not tell you WHICH of three\n// controls in a row it was, and the button has already reverted by the time you read it.\nconst LABEL = { '/api/like': 'like', '/api/repost': 'repost', '/api/follow': 'follow' }\n\nconst ROUTES = {\n  '/api/like': { btn: '.likebtn', on: 'liked', count: 'likeCount', countEl: '.likes', active: '♥', idle: '♡' },\n  '/api/repost': { btn: '.rpbtn', on: 'reposted', count: 'repostCount', countEl: '.rps', active: '⇄', idle: '⇄' },\n  '/api/follow': { btn: '.followbtn', on: 'following', count: null, countEl: null, active: 'following ✓', idle: 'follow' }\n}\n\nfunction setState (btn, spec, isOn, count) {\n  btn.classList.toggle('on', !!isOn)\n  if (spec.active !== spec.idle || spec.count === null) btn.textContent = isOn ? spec.active : spec.idle\n  btn.title = spec.count === null ? (isOn ? 'unfollow' : 'follow') : (isOn ? 'undo' : 'do')\n  btn.setAttribute('aria-pressed', isOn ? 'true' : 'false')\n  if (!spec.countEl) return\n  // The count lives OUTSIDE the button, as a sibling in the same form. Absent at zero by design, so it has\n  // to be created when a count appears and removed when it returns to zero — otherwise a freshly-liked\n  // post shows a heart with no number, or a stale \"0\" lingers.\n  const form = btn.closest('form')\n  if (!form) return\n  let el = form.querySelector(spec.countEl)\n  const n = Number(count)\n  if (!Number.isFinite(n) || n <= 0) { if (el) el.remove(); return }\n  if (!el) {\n    el = document.createElement('span')\n    el.className = spec.countEl.slice(1)\n    btn.insertAdjacentElement('afterend', el)\n  }\n  el.textContent = String(n)\n}\n\ndocument.addEventListener('submit', async (e) => {\n  const form = e.target\n  if (!form || !form.action) return\n  const path = new URL(form.action, location.href).pathname\n  const spec = ROUTES[path]\n  if (!spec) return\n  const btn = form.querySelector(spec.btn)\n  if (!btn) return\n\n  e.preventDefault()\n  const data = new FormData(form)\n  const wasOn = btn.classList.contains('on')\n  const countEl = spec.countEl ? form.querySelector(spec.countEl) : null\n  const wasCount = countEl ? Number(countEl.textContent) || 0 : 0\n\n  // Optimistic flip. A P2P write is not instant and the click must feel like it landed.\n  setState(btn, spec, !wasOn, wasOn ? wasCount - 1 : wasCount + 1)\n  btn.disabled = true\n\n  try {\n    const body = {}\n    for (const [k, v] of data.entries()) body[k] = v\n    const res = await fetch(path, {\n      method: 'POST',\n      headers: { 'content-type': 'application/json' },\n      body: JSON.stringify(body)\n    })\n    const out = await res.json().catch(() => null)\n    if (!res.ok || !out || out.ok !== true) throw new Error((out && out.error) || ('HTTP ' + res.status))\n    // The server's answer wins over the optimistic guess.\n    setState(btn, spec, out[spec.on], spec.count ? out[spec.count] : null)\n  } catch (err) {\n    setState(btn, spec, wasOn, wasCount) // put it back — never leave a lie on screen\n    btn.classList.add('failed')\n    const why = String((err && err.message) || 'failed')\n    btn.title = why\n    // ...and SAY it. The flash + title alone meant a failed write was invisible on touch (no hover) and\n    // to assistive tech, so a revert read as \"my tap didn't register\" and people tapped again.\n    toast(`${LABEL[path] || 'action'} failed — ${why}`)\n    setTimeout(() => btn.classList.remove('failed'), 1200)\n  } finally {\n    btn.disabled = false\n  }\n})\n\n// ── lightbox ─────────────────────────────────────────────────────────────────────────────────────\n// Each image is a real <a> to its own bytes, so with no JS a click opens the full-size picture — already\n// better than the inline-only view. With JS we keep the reader on the page instead.\n//\n// It must be a link regardless: the whole post is a stretched anchor to its thread, so an image with no\n// element of its own would open the thread rather than the picture.\nlet lb = null\nfunction closeLb () {\n  if (!lb) return\n  lb.remove(); lb = null\n  document.removeEventListener('keydown', onKey)\n  document.body.style.overflow = ''\n}\nfunction onKey (e) { if (e.key === 'Escape') closeLb() }\n\ndocument.addEventListener('click', (e) => {\n  const a = e.target.closest && e.target.closest('a.lb')\n  if (!a) return\n  // Let the browser do its normal thing for new-tab/window intents — never hijack a modified click.\n  if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey || e.button !== 0) return\n  e.preventDefault()\n  e.stopPropagation() // do not also trigger the post's whole-entry navigation\n\n  closeLb()\n  lb = document.createElement('div')\n  lb.className = 'lbox'\n  lb.setAttribute('role', 'dialog')\n  lb.setAttribute('aria-modal', 'true')\n  const alt = a.getAttribute('data-alt') || ''\n  lb.setAttribute('aria-label', alt || 'image')\n  const img = document.createElement('img')\n  img.src = a.getAttribute('href')\n  img.alt = alt\n  lb.appendChild(img)\n  // ALT TEXT IS SHOWN, not just carried in the attribute. Someone wrote it to describe the image; a\n  // viewer is the one place there is room to actually display it.\n  if (alt) {\n    const cap = document.createElement('p')\n    cap.className = 'lbalt'\n    cap.textContent = alt\n    lb.appendChild(cap)\n  }\n  const close = document.createElement('button')\n  close.className = 'lbclose'\n  close.setAttribute('aria-label', 'close')\n  close.textContent = '✕'\n  lb.appendChild(close)\n\n  // Click anywhere outside the image closes — the expected gesture, and the only one available on touch.\n  lb.addEventListener('click', (ev) => { if (ev.target !== img) closeLb() })\n  document.body.appendChild(lb)\n  document.body.style.overflow = 'hidden' // no scrolling the page behind the overlay\n  document.addEventListener('keydown', onKey)\n  close.focus()\n})\n",
  "atproto-client.js": "// AtprotoClient — secp256k1 / ES256K identity for the browser (the atproto-native \"pgv3 method\").\n//\n// The browser analog of pear-git-v3's anproto-client.js, but for atproto's own key world: secp256k1\n// signing keys and ES256K signed assertions (NOT ed25519/anproto, NOT keet). A browser holds a\n// per-origin SUB-KEY; the DID's #atproto key DELEGATES it (a signed assertion minted once by the\n// keyholder, the hpp); on login the sub-key signs the server's fresh challenge and favela verifies\n// KEYLESSLY against the DID's PLC-published key (atproto-identity/lib/web-auth.js). favela holds no key.\n//\n// Byte-compatible with the SERVER's atproto-identity/lib/auth.js: signAssertion here produces the SAME\n// `<b64url(head)>.<b64url(body)>.<b64url(sig)>` ES256K JWT the server's verifyAssertion consumes. We use\n// the standalone @noble/secp256k1 (vendored, pure-JS, works on plain HTTP) — its compact low-S sigs and\n// compressed pubkeys interoperate exactly with the server's @noble/curves secp256k1 (same author,\n// same RFC6979/low-S). Proven by test/browser-auth-client.test.mjs.\n//\n// Universal (browser / Node / Bare): base64 falls back to Buffer when btoa is absent, so the same file\n// unit-tests under Node. generateSubKey() is browser-only (needs crypto.getRandomValues).\n\nimport * as secp from './vendor/noble-secp256k1.js'\nimport { sha256 } from './vendor/sha256-pure.js'\n\n// ── HMAC-SHA256 from the pure-JS sha256 — wired into noble so its RFC6979 deterministic signer runs\n//    SYNC with no crypto.subtle dependency (works on plain HTTP LAN). Mirrors how pgv3's anproto-client\n//    wires ed.etc.sha512Sync from a pure sha512. ──\nconst HMAC_BLOCK = 64 // sha256 block size\nfunction hmacSha256 (key, msg) {\n  let k = key\n  if (k.length > HMAC_BLOCK) k = sha256(k)\n  const block = new Uint8Array(HMAC_BLOCK)\n  block.set(k)\n  const ipad = new Uint8Array(HMAC_BLOCK)\n  const opad = new Uint8Array(HMAC_BLOCK)\n  for (let i = 0; i < HMAC_BLOCK; i++) { ipad[i] = block[i] ^ 0x36; opad[i] = block[i] ^ 0x5c }\n  const inner = sha256(concatBytes(ipad, msg))\n  return sha256(concatBytes(opad, inner))\n}\nsecp.etc.hmacSha256Sync = (key, ...msgs) => hmacSha256(key, concatBytes(...msgs))\n\n// ── encoding helpers (universal) ──\nfunction concatBytes (...arrs) {\n  let n = 0\n  for (const a of arrs) n += a.length\n  const out = new Uint8Array(n)\n  let o = 0\n  for (const a of arrs) { out.set(a, o); o += a.length }\n  return out\n}\nfunction utf8 (str) { return new TextEncoder().encode(str) }\nfunction bytesToHex (bytes) { return Array.from(bytes).map((b) => b.toString(16).padStart(2, '0')).join('') }\nfunction hexToBytes (hex) {\n  const clean = String(hex).toLowerCase().replace(/[^0-9a-f]/g, '')\n  const out = new Uint8Array(clean.length >> 1)\n  for (let i = 0; i < out.length; i++) out[i] = parseInt(clean.substr(i * 2, 2), 16)\n  return out\n}\n// base64url over bytes, matching the server's b64url (base64 → +/ to -_, strip padding).\nfunction b64url (bytes) {\n  let b64\n  if (typeof btoa !== 'undefined') {\n    let bin = ''\n    for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i])\n    b64 = btoa(bin)\n  } else {\n    b64 = Buffer.from(bytes).toString('base64')\n  }\n  return b64.replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\n}\n\n// Generate a fresh browser sub-key (secp256k1). Browser-only: randomPrivateKey → crypto.getRandomValues.\n// Returns { privHex, subKey } where subKey is the 33-byte COMPRESSED pubkey hex (what delegate() names).\nexport function generateSubKey () {\n  const priv = secp.utils.randomPrivateKey()\n  const pub = secp.getPublicKey(priv, true) // compressed\n  return { privHex: bytesToHex(priv), subKey: bytesToHex(pub) }\n}\n\n// The compressed-pubkey hex for a private key (used to re-derive subKey from a stored priv).\nexport function subKeyOf (privHex) { return bytesToHex(secp.getPublicKey(hexToBytes(privHex), true)) }\n\n// Sign an ES256K assertion — byte-for-byte the server's atproto-identity signAssertion shape:\n//   head = b64url(utf8(JSON({alg:'ES256K',typ:'JWT'}))), body = b64url(utf8(JSON(payload))),\n//   sig  = low-S compact secp256k1 over sha256(utf8(head.body)); token = head.body.sig.\nexport function signAssertion (payload, privHex) {\n  const head = b64url(utf8(JSON.stringify({ alg: 'ES256K', typ: 'JWT' })))\n  const body = b64url(utf8(JSON.stringify(payload)))\n  const signingInput = `${head}.${body}`\n  const digest = sha256(utf8(signingInput))\n  const sig = secp.sign(digest, hexToBytes(privHex)).toCompactRawBytes()\n  return `${signingInput}.${b64url(sig)}`\n}\n\nexport { bytesToHex, hexToBytes }\nexport default { generateSubKey, subKeyOf, signAssertion }\n",
  "browser-identity.js": "// AtprotoIdentity — the browser sign-in client for favela (the atproto-native \"pgv3 method\").\n//\n// Mirrors pear-git-v3's browser-identity.js, adapted from ed25519/TOFU to atproto's DELEGATED model:\n//   - A per-origin secp256k1 SUB-KEY lives in localStorage; its secret NEVER leaves the browser.\n//   - favela is NOT TOFU (unlike pgv3): the sub-key is powerless until the DID's #atproto key\n//     DELEGATES it. That delegation is minted by the KEYHOLDER (the hpp `delegate` RPC) out-of-band —\n//     the browser is \"paired\" to a DID once by storing { did, delegation }, then logs in repeatedly\n//     until the delegation expires (default 30d). This is the atproto analog of pgv3 registering a\n//     device under the root identity.\n//   - Login: GET /api/auth/challenge → the sub-key signs it (ES256K) → POST /api/auth/login. The\n//     server sets an HttpOnly session cookie (favela_session), so SSR navigation is authenticated.\n//     favela verifies keylessly against the DID's PLC-published key; it holds no key of ours.\n//\n// The pairing (obtaining a delegation) is deliberately out-of-band for now: on your own machine, where\n// your hpp holds the DID key, run its `delegate` RPC for THIS browser's sub-key and paste the result.\n// A one-click in-browser \"authorize this device\" needs the hpp reachable from the browser — deferred.\n\nimport { generateSubKey, subKeyOf, signAssertion } from './atproto-client.js'\n\nconst SUBKEY_KEY = 'favela-subkey'       // { privHex, subKey } — the browser's secp256k1 sub-key\nconst PAIRING_KEY = 'favela-pairing'     // { did, delegation, handle? } — the DID that delegated it\n\nexport class AtprotoIdentity {\n  constructor (opts = {}) {\n    this._baseUrl = opts.baseUrl || ''\n    this._subkey = null\n  }\n\n  // Get or generate the persistent per-origin sub-key. Secret stays in localStorage.\n  getSubKey () {\n    if (this._subkey) return this._subkey\n    if (typeof localStorage !== 'undefined') {\n      const raw = localStorage.getItem(SUBKEY_KEY)\n      if (raw) {\n        try {\n          const kp = JSON.parse(raw)\n          if (kp && kp.privHex) {\n            // Re-derive subKey from the secret so a hand-edited/legacy record can't desync pub↔priv.\n            this._subkey = { privHex: kp.privHex, subKey: subKeyOf(kp.privHex) }\n            return this._subkey\n          }\n        } catch {}\n      }\n    }\n    this._subkey = generateSubKey()\n    if (typeof localStorage !== 'undefined') localStorage.setItem(SUBKEY_KEY, JSON.stringify(this._subkey))\n    return this._subkey\n  }\n\n  // The compressed sub-key pubkey hex — this is what you feed to the hpp `delegate` RPC.\n  subKeyHex () { return this.getSubKey().subKey }\n\n  // The stored pairing { did, delegation, handle? }, or null if this browser isn't paired yet.\n  getPairing () {\n    if (typeof localStorage === 'undefined') return null\n    try { return JSON.parse(localStorage.getItem(PAIRING_KEY) || 'null') } catch { return null }\n  }\n\n  isPaired () { const p = this.getPairing(); return !!(p && p.did && p.delegation) }\n\n  // Pair this browser to a DID by storing the hpp-minted delegation. Light client-side sanity only —\n  // the real cryptographic check (the delegation names THIS sub-key and is signed by the DID's PLC key)\n  // happens server-side on every login, so a bad paste simply fails login, it never grants access.\n  pair ({ did, delegation, handle } = {}) {\n    if (!did || !/^did:/.test(String(did))) throw new Error('a valid did: is required')\n    if (!delegation || String(delegation).split('.').length !== 3) throw new Error('delegation must be an ES256K assertion (head.body.sig)')\n    const rec = { did: String(did), delegation: String(delegation), handle: handle ? String(handle) : null }\n    if (typeof localStorage !== 'undefined') localStorage.setItem(PAIRING_KEY, JSON.stringify(rec))\n    return rec\n  }\n\n  // Ensure a live favela session. Returns { did, handle } on success. Throws if not paired or if the\n  // server rejects the proof (expired/revoked delegation, bad sub-key, PLC unreachable). Cookies are\n  // HttpOnly so we ask the server \"who am I?\" via /api/auth/me rather than reading document.cookie.\n  async signIn () {\n    const pairing = this.getPairing()\n    if (!pairing || !pairing.did || !pairing.delegation) throw new Error('this browser is not paired to a DID yet')\n    const { challenge } = await this._fetch('/api/auth/challenge')\n    if (!challenge) throw new Error('challenge missing')\n    const { privHex, subKey } = this.getSubKey()\n    const nowSec = Math.floor(Date.now() / 1000)\n    const sig = signAssertion({ challenge, iat: nowSec, exp: nowSec + 300 }, privHex) // 5-min proof\n    const out = await this._fetch('/api/auth/login', {\n      method: 'POST',\n      body: { did: pairing.did, subKey, challenge, sig, delegation: pairing.delegation, handle: pairing.handle || undefined }\n    })\n    return { did: out.did, handle: out.handle || pairing.handle || null }\n  }\n\n  // hpp-INITIATED pairing (the fix for the backwards flow): paste the ONE hash-URL invite the hpp minted\n  // (via `favela-pair`). The browser generates a sub-key + signs a challenge (proving it holds the secret);\n  // favela-web joins the invite's blind-pairing tunnel, has the hpp delegate the sub-key, and mints the\n  // session — no manual delegation shuttle. Accepts the raw invite hex OR a `…/login#pair=<invite>` URL.\n  // Returns { did, handle } on success.\n  async pairWithInvite (invite) {\n    const inv = String(invite || '').trim().replace(/^.*[#?&]pair=/, '')\n    if (!/^[0-9a-f]{20,}$/i.test(inv)) throw new Error('paste the pairing invite the hpp printed (favela-pair)')\n    const { challenge } = await this._fetch('/api/auth/challenge')\n    if (!challenge) throw new Error('challenge missing')\n    const { privHex, subKey } = this.getSubKey()\n    const nowSec = Math.floor(Date.now() / 1000)\n    const sig = signAssertion({ challenge, iat: nowSec, exp: nowSec + 300 }, privHex) // 5-min proof\n    const out = await this._fetch('/api/auth/pair', { method: 'POST', body: { invite: inv, subKey, challenge, sig } })\n    // PERSIST the delegation locally (localStorage favela-pairing) so isPaired() stays true across a\n    // favela-web restart — the browser then re-signs-in SILENTLY with the stored delegation (signIn),\n    // instead of falling back to the paste-invite screen. This is the pgv3-parity persistence fix.\n    if (out.delegation) this.pair({ did: out.did, delegation: out.delegation, handle: out.handle })\n    return { did: out.did, handle: out.handle || null }\n  }\n\n  // Current session identity per the server (reads the HttpOnly cookie), or null.\n  async whoami () {\n    try { const me = await this._fetch('/api/auth/me'); return me && me.did ? me : null } catch { return null }\n  }\n\n  async logout () {\n    try { await this._fetch('/api/auth/logout', { method: 'POST' }) } catch {}\n  }\n\n  // Forget the pairing (unpair this browser from the DID). The sub-key is kept so re-pairing the SAME\n  // sub-key can reuse an existing delegation; call forgetSubKey() to rotate the key entirely.\n  unpair () { if (typeof localStorage !== 'undefined') localStorage.removeItem(PAIRING_KEY) }\n  forgetSubKey () { if (typeof localStorage !== 'undefined') localStorage.removeItem(SUBKEY_KEY); this._subkey = null }\n\n  async _fetch (path, opts = {}) {\n    const init = { headers: { Accept: 'application/json' }, credentials: 'same-origin' }\n    if (opts.method) init.method = opts.method\n    if (opts.body) {\n      init.method = init.method || 'POST'\n      init.headers['Content-Type'] = 'application/json'\n      init.body = JSON.stringify(opts.body)\n    }\n    const res = await fetch(this._baseUrl + path, init)\n    if (!res.ok) {\n      let msg = ''\n      try { const j = await res.json(); msg = j.error || '' } catch { try { msg = await res.text() } catch {} }\n      throw new Error(msg || `${res.status}`)\n    }\n    return res.json()\n  }\n}\n\nexport default AtprotoIdentity\n",
  "compose.js": "// Composer image attachments — progressive enhancement.\n//\n// The composer is a plain <form method=POST action=/api/post> that works with NO JS. This script only\n// ADDS the ability to attach images: it reveals the picker, uploads each file to /api/upload (which\n// returns an atproto blob ref), and — only when there is at least one image — submits the post as JSON\n// so the refs can travel. With no images selected the native form submit is left completely alone, so\n// the no-JS path is never regressed.\n//\n// bsky caps app.bsky.embed.images at 4 and REJECTS a longer array outright, so the cap is enforced here\n// too: a record the relay refuses would federate as nothing while looking fine locally.\n\nimport { MAX_BYTES, resizePlan, aspectRatioOf } from './resize-plan.js'\n\nconst MAX_IMAGES = 4\n\n// Shrink a picture to something the lexicon accepts, and report the dimensions it ended up with.\n//\n// ⛔ REFUSING WAS THE BUG. This used to alert \"the limit is 1024 KB\" and skip the file — half the real\n// ceiling, and hopeless once the phone's composer could open the camera on 2026-08-18, because a phone\n// camera JPEG is 3–12 MB. Every photo taken through favela bounced. The fix is not a bigger number; it\n// is doing what every other client does and resizing the picture.\n//\n// ⚠ Re-encodes to JPEG, so transparency is lost on a PNG large enough to need shrinking. Accepted: the\n// byte ceiling is a hard protocol limit and a >2 MB PNG is a photo or a screenshot, not an icon. Images\n// that already fit are passed through UNTOUCHED, so nothing small is ever re-encoded.\nasync function prepare (file) {\n  const bitmap = await createImageBitmap(file)\n  const { width, height } = bitmap\n  const plan = resizePlan({ width, height, bytes: file.size, type: file.type })\n  if (!plan.needed) { bitmap.close(); return { blob: file, width, height } }\n\n  const canvas = document.createElement('canvas')\n  canvas.width = plan.width\n  canvas.height = plan.height\n  canvas.getContext('2d').drawImage(bitmap, 0, 0, plan.width, plan.height)\n  bitmap.close()\n\n  // Step the quality down only as far as needed. Stops at the first size that fits, so a picture barely\n  // over the line keeps almost all of its quality.\n  let out = null\n  for (const q of [0.9, 0.82, 0.72, 0.6, 0.45]) {\n    out = await new Promise((resolve) => canvas.toBlob(resolve, 'image/jpeg', q))\n    if (out && out.size <= MAX_BYTES) break\n  }\n  return { blob: out || file, width: plan.width, height: plan.height }\n}\n\nconst form = document.querySelector('form.composer')\nif (form) {\n  const controls = document.getElementById('img-controls')\n  const picker = document.getElementById('post-image')\n  const preview = document.getElementById('img-preview')\n  const attached = [] // { blob, alt, name, url }\n\n  if (controls) controls.hidden = false // only shown once JS is confirmed present\n\n  const draw = () => {\n    if (!preview) return\n    preview.innerHTML = ''\n    attached.forEach((a, i) => {\n      const wrap = document.createElement('span')\n      wrap.className = 'thumb'\n      const im = document.createElement('img')\n      im.src = a.url; im.alt = a.name\n      const alt = document.createElement('input')\n      alt.type = 'text'; alt.placeholder = 'alt text (describe the image)'; alt.value = a.alt || ''\n      alt.addEventListener('input', () => { a.alt = alt.value })\n      const rm = document.createElement('button')\n      rm.type = 'button'; rm.textContent = '✕'; rm.title = 'remove'\n      rm.addEventListener('click', () => { URL.revokeObjectURL(a.url); attached.splice(i, 1); draw() })\n      wrap.append(im, alt, rm)\n      preview.append(wrap)\n    })\n  }\n\n  if (picker) {\n    picker.addEventListener('change', async () => {\n      const files = [...(picker.files || [])]\n      picker.value = ''\n      for (const f of files) {\n        if (attached.length >= MAX_IMAGES) { alert(`bsky allows at most ${MAX_IMAGES} images per post`); break }\n        try {\n          // Resize BEFORE the size check, so the check is a last resort rather than the policy.\n          let up = f\n          let ratio = null\n          try {\n            const prepared = await prepare(f)\n            up = prepared.blob\n            ratio = aspectRatioOf(prepared.width, prepared.height)\n          } catch (e) {\n            alert(`could not read ${f.name}: ${e.message}`)\n            continue\n          }\n          // Only reachable if even the lowest quality could not fit — say so honestly rather than\n          // blaming the file for being large.\n          if (up.size > MAX_BYTES) {\n            alert(`${f.name} is still ${Math.round(up.size / 1024)} KB after resizing — the limit is ${Math.round(MAX_BYTES / 1024)} KB`)\n            continue\n          }\n          const res = await fetch('/api/upload', { method: 'POST', headers: { 'content-type': up.type || f.type || 'application/octet-stream' }, body: up })\n          const body = await res.json().catch(() => ({}))\n          if (!res.ok) { alert(body.error || `upload failed (${res.status})`); continue }\n          // aspectRatio is what bsky lays the image out with. writer.js has always accepted it\n          // (`images = [{ blob, alt?, aspectRatio? }]`) and this client never sent it, so every favela\n          // image has been laid out from a guess.\n          attached.push({ blob: body.blob, alt: '', name: f.name, url: URL.createObjectURL(up), aspectRatio: ratio })\n          draw()\n        } catch (e) { alert('upload failed: ' + e.message) }\n      }\n    })\n  }\n\n  form.addEventListener('submit', async (ev) => {\n    if (!attached.length) return // no images -> leave the native no-JS form submit untouched\n    ev.preventDefault()\n    const text = form.querySelector('textarea[name=text]').value\n    const scope = form.querySelector('select[name=scope]').value\n    try {\n      const res = await fetch('/api/post', {\n        method: 'POST',\n        headers: { 'content-type': 'application/json' },\n        body: JSON.stringify({ text, scope, images: attached.map((a) => ({ blob: a.blob, alt: a.alt, ...(a.aspectRatio ? { aspectRatio: a.aspectRatio } : {}) })) })\n      })\n      const body = await res.json().catch(() => ({}))\n      if (!res.ok) { alert(body.error || `post failed (${res.status})`); return }\n      attached.forEach((a) => URL.revokeObjectURL(a.url))\n      attached.length = 0\n      window.location.href = '/' // same destination the no-JS form redirect lands on\n    } catch (e) { alert('post failed: ' + e.message) }\n  })\n}\n\n// ── character budget ─────────────────────────────────────────────────────────────────────────────\n//\n// atproto caps a post at 300 GRAPHEMES, not 300 JS string units. Without a counter the limit is\n// invisible until the PDS rejects the write — after the user has typed the whole thing. Counting in\n// graphemes matters: an emoji or a family sequence is one character to a reader and several UTF-16\n// code units to `.length`, so a naive count tells people they are over when they are not.\nconst ta = document.querySelector('.composer textarea[name=\"text\"]')\nconst cc = document.getElementById('charcount')\nconst postBtn = document.getElementById('post-btn')\nconst LIMIT = 300\n\nconst seg = (typeof Intl !== 'undefined' && Intl.Segmenter) ? new Intl.Segmenter(undefined, { granularity: 'grapheme' }) : null\n// [...str] at least splits on code POINTS (so astral characters count once) — still wrong for combining\n// sequences, but never wrong in the direction that blocks a legal post.\nfunction graphemes (s) { return seg ? [...seg.segment(s)].length : [...String(s)].length }\n\nfunction updateCount () {\n  if (!ta || !cc) return\n  const n = graphemes(ta.value)\n  const left = LIMIT - n\n  // Stay quiet until it is nearly relevant — a counter that is always shouting is ignored.\n  cc.textContent = left > 50 ? '' : String(left)\n  cc.classList.toggle('over', left < 0)\n  if (postBtn) postBtn.disabled = left < 0 || ta.value.trim().length === 0\n}\n\nif (ta) {\n  ta.addEventListener('input', updateCount)\n  updateCount()\n  // Guard the no-JS-shaped submit path too: with the button disabled this is belt-and-braces, but a\n  // form can still be submitted with Enter from some controls.\n  const form = ta.closest('form')\n  if (form) form.addEventListener('submit', (e) => {\n    if (graphemes(ta.value) > LIMIT) { e.preventDefault(); updateCount() }\n  })\n}\n",
  "draft.js": "// Draft recovery — keep what you typed when a write fails.\n//\n// THE PROBLEM. A post goes through hpp over P2P, and that can fail: the daemon is restarting, the peer\n// is unreachable, the record cannot be signed yet. When it did, the browser navigated to a redirect and\n// the text was simply GONE. Losing someone's words because the network blinked is the worst small bug a\n// client can have, and it is entirely avoidable.\n//\n// Deliberately dumb: the value is mirrored to localStorage as you type, restored on load, and cleared\n// only once a post has actually SUCCEEDED. Nothing is scheduled, nothing is synced, and if scripting is\n// off the composer behaves exactly as it did before.\nconst KEY = 'favela.draft'\n\nfunction fields () {\n  // The main composer and the reply box are the same shape; both are worth protecting, keyed apart so a\n  // half-written reply does not reappear in the timeline composer.\n  return [...document.querySelectorAll('form.composer textarea[name=\"text\"], form.replyf textarea[name=\"text\"]')]\n}\nconst keyFor = (ta) => KEY + ':' + (ta.closest('form.replyf') ? 'reply:' + location.pathname : 'composer')\n\nfor (const ta of fields()) {\n  const k = keyFor(ta)\n  // Restore first — but never clobber something the server already put there (a quote preview, an edit).\n  if (!ta.value) {\n    let saved = null\n    try { saved = localStorage.getItem(k) } catch {}\n    if (saved) {\n      ta.value = saved\n      const note = document.createElement('p')\n      note.className = 'draftnote'\n      note.textContent = 'restored an unsent draft'\n      const clear = document.createElement('button')\n      clear.type = 'button'\n      clear.className = 'devbtn'\n      clear.textContent = 'discard'\n      clear.addEventListener('click', () => {\n        ta.value = ''\n        try { localStorage.removeItem(k) } catch {}\n        note.remove()\n      })\n      note.appendChild(document.createTextNode(' '))\n      note.appendChild(clear)\n      ta.insertAdjacentElement('beforebegin', note)\n    }\n  }\n  ta.addEventListener('input', () => {\n    try { if (ta.value) localStorage.setItem(k, ta.value); else localStorage.removeItem(k) } catch {}\n  })\n  // Clear ONLY on a real success. A plain form navigates away on submit, so we cannot see the outcome\n  // here — instead the server sets ?posted=1 on the redirect, and that is the signal. Clearing on submit\n  // would throw the text away in exactly the case this exists for: the write that failed.\n  const form = ta.closest('form')\n  if (form) form.addEventListener('submit', () => { try { sessionStorage.setItem(KEY + '.pending', k) } catch {} })\n}\n\n// On load: if we arrived from a successful post, drop the draft it came from.\ntry {\n  const params = new URLSearchParams(location.search)\n  const pending = sessionStorage.getItem(KEY + '.pending')\n  if (params.get('posted') === '1' && pending) {\n    localStorage.removeItem(pending)\n    sessionStorage.removeItem(KEY + '.pending')\n  }\n} catch {}\n",
  "login.js": "// favela /login controller — drives the DID web sign-in DOM against the live /api/auth/* routes.\n// Loaded as an ES module by the SSR /login page. All crypto is client-side (the sub-key secret never\n// leaves the browser); this file is only glue between the AtprotoIdentity client and the page elements.\nimport { AtprotoIdentity } from './browser-identity.js'\n\nconst id = new AtprotoIdentity()\nlet autoSignInTried = false // pgv3-parity: attempt a silent re-sign-in once per page load\nconst $ = (sel) => document.querySelector(sel)\nconst show = (el, on) => { if (el) el.style.display = on ? '' : 'none' }\nfunction status (msg, kind) {\n  const el = $('#status')\n  if (!el) return\n  el.textContent = msg || ''\n  el.className = kind || ''\n}\n\nasync function render () {\n  const subKey = id.subKeyHex()\n  const skEl = $('#subkey')\n  if (skEl) skEl.textContent = subKey\n\n  let session = await id.whoami()\n  const pairing = id.getPairing()\n\n  // pgv3-parity: hold a delegation but no live session (e.g. favela-web restarted + cleared its\n  // in-memory sessions)? Silently re-sign-in with the stored delegation — never fall back to\n  // paste-invite. Try once per load; on failure (expired/revoked delegation) fall through to the\n  // manual sign-in / pair boxes below.\n  if (!session && id.isPaired() && !autoSignInTried) {\n    autoSignInTried = true\n    try { await id.signIn(); session = await id.whoami() } catch {}\n  }\n\n  // Signed in → show the session + a link home.\n  show($('#session-box'), !!session)\n  if (session) {\n    const who = $('#session-who')\n    if (who) who.textContent = session.handle ? `@${session.handle}` : session.did\n  }\n\n  // Paired (delegation stored) but not signed in → offer sign-in.\n  show($('#signin-box'), !session && id.isPaired())\n  if (!session && pairing) {\n    const p = $('#paired-did')\n    if (p) p.textContent = pairing.handle ? `@${pairing.handle} (${pairing.did})` : pairing.did\n  }\n\n  // Not paired → show the pairing instructions + form.\n  show($('#pair-box'), !session && !id.isPaired())\n}\n\n// Pair: paste the ONE hash-URL invite the hpp minted (favela-pair). favela-web joins the tunnel, has the\n// hpp delegate this browser's sub-key, and signs us in — no manual delegation shuttle.\nasync function onPair (e) {\n  e.preventDefault()\n  const field = ($('#pair-invite') && $('#pair-invite').value.trim()) || ''\n  const invite = field || (location.hash || '').replace(/^.*[#?&]pair=/, '')\n  try {\n    status('Pairing over the tunnel (this can take a few seconds)…')\n    const s = await id.pairWithInvite(invite)\n    status('Signed in as ' + (s.handle ? '@' + s.handle : s.did) + '.', 'ok')\n    await render()\n    setTimeout(() => { window.location.href = '/' }, 600)\n  } catch (err) {\n    status(err.message || 'pairing failed', 'err')\n    await render()\n  }\n}\n\nasync function onSignIn () {\n  status('Signing in…')\n  try {\n    await id.signIn()\n    status('Signed in.', 'ok')\n    setTimeout(() => { window.location.href = '/' }, 400)\n  } catch (err) {\n    status(err.message || 'sign-in failed', 'err')\n    // A stale/expired delegation can't be recovered by retrying — surface the unpair option.\n    show($('#pair-box'), true)\n  }\n}\n\nasync function onLogout () {\n  await id.logout()\n  status('Signed out.')\n  await render()\n}\n\nasync function onUnpair () {\n  id.unpair()\n  status('Unpaired this browser.')\n  await render()\n}\n\nasync function onCopy () {\n  try { await navigator.clipboard.writeText(id.subKeyHex()); status('Sub-key copied.', 'ok') } catch { status('Copy failed — select it manually.', 'err') }\n}\n\nwindow.addEventListener('DOMContentLoaded', () => {\n  // Prefill the invite from a `…/login#pair=<invite>` link the hpp printed.\n  const fromHash = (location.hash || '').replace(/^.*[#?&]pair=/, '')\n  const inviteField = $('#pair-invite'); if (inviteField && fromHash && fromHash !== location.hash) inviteField.value = fromHash\n  const pairForm = $('#pair-form'); if (pairForm) pairForm.addEventListener('submit', onPair)\n  const signinBtn = $('#signin-btn'); if (signinBtn) signinBtn.addEventListener('click', onSignIn)\n  const logoutBtn = $('#logout-btn'); if (logoutBtn) logoutBtn.addEventListener('click', onLogout)\n  const unpairBtn = $('#unpair-btn'); if (unpairBtn) unpairBtn.addEventListener('click', onUnpair)\n  const copyBtn = $('#copy-subkey'); if (copyBtn) copyBtn.addEventListener('click', onCopy)\n  render().catch((e) => status(e.message, 'err'))\n})\n",
  "notifications.js": "// Notifications — fetched BY THE BROWSER, never by the server.\n//\n// WHY IT LIVES HERE AND NOT ON THE SERVER. hpp's get-service-auth has two gates, and the second is\n// `sessions.verifyAccess(token)` — a bearer from a real login. Its comment says why in as many words:\n// without it \"an allowlisted bridge could mint tokens for anyone at any time with nobody present\". A\n// minted token authenticates AS the DID, signed by the same #atproto key that signs every repo commit,\n// so it is a signing oracle and it is right that it needs a present user.\n//\n// That leaves the question of where the bearer lives. Putting it on favela-web would mean the server\n// holds a credential for you, which is exactly what \"favela never holds anything of yours\" is supposed\n// to rule out. So the BROWSER holds it — the same place that already holds your delegated sub-key\n// secret — and favela-web stays keyless and credential-free. It renders the shell and nothing else;\n// every authenticated byte here moves between your browser and the PDS.\n//\n// ⚠ THE PASSWORD IS NEVER STORED. It is used once, in memory, to mint a session, and then dropped. Only\n// the JWTs persist, and they expire. An app password is also revocable independently of your account\n// password, which is the point of app passwords.\n//\n// This is the one page in favela that requires JavaScript. Notifications are inherently authenticated\n// and per-viewer; there is no meaningful server-rendered version when the server deliberately holds no\n// credential. Everything else still works with scripting off.\n\nconst PDS = document.querySelector('meta[name=\"favela-pds\"]')?.content || 'https://pds.7rnx.net'\nconst KEY = 'favela.notif.session'\n\nconst $ = (id) => document.getElementById(id)\nconst out = $('notif-list')\nconst status = $('notif-status')\nconst form = $('notif-login')\n\nfunction say (msg, cls) { if (status) { status.textContent = msg; status.className = cls || '' } }\n\nfunction loadSession () {\n  try { return JSON.parse(localStorage.getItem(KEY) || 'null') } catch { return null }\n}\nfunction saveSession (s) {\n  try { localStorage.setItem(KEY, JSON.stringify(s)) } catch { /* private mode — session lasts this page */ }\n}\nfunction clearSession () {\n  try { localStorage.removeItem(KEY) } catch {}\n}\n\nasync function xrpc (nsid, { method = 'GET', body = null, bearer = null, params = null } = {}) {\n  const url = new URL(`${PDS.replace(/\\/$/, '')}/xrpc/${nsid}`)\n  if (params) for (const [k, v] of Object.entries(params)) url.searchParams.set(k, String(v))\n  const headers = {}\n  if (body) headers['content-type'] = 'application/json'\n  if (bearer) headers.authorization = `Bearer ${bearer}`\n  const res = await fetch(url, { method, headers, body: body ? JSON.stringify(body) : undefined })\n  const text = await res.text()\n  let json = null\n  try { json = text ? JSON.parse(text) : null } catch { /* non-JSON error body */ }\n  if (!res.ok) throw Object.assign(new Error((json && (json.message || json.error)) || `HTTP ${res.status}`), { status: res.status })\n  return json\n}\n\n// A refresh token is used with the REFRESH token as bearer, not the access one — a detail that silently\n// fails as a 401 loop if you get it wrong.\nasync function refresh (session) {\n  const r = await xrpc('com.atproto.server.refreshSession', { method: 'POST', bearer: session.refreshJwt })\n  const next = { ...session, accessJwt: r.accessJwt, refreshJwt: r.refreshJwt }\n  saveSession(next)\n  return next\n}\n\nconst REASON = {\n  like: 'liked your post', repost: 'reposted your post', follow: 'followed you',\n  mention: 'mentioned you', reply: 'replied to you', quote: 'quoted your post',\n  'starterpack-joined': 'joined via your starter pack'\n}\n\nfunction rowFor (n) {\n  const el = document.createElement('article')\n  el.className = 'notif' + (n.isRead ? '' : ' unread')\n  const who = (n.author && (n.author.displayName || n.author.handle)) || (n.author && n.author.did) || 'someone'\n  const av = document.createElement('span')\n  if (n.author && typeof n.author.avatar === 'string' && /^https:\\/\\//i.test(n.author.avatar)) {\n    const img = document.createElement('img')\n    img.className = 'pfp'; img.src = n.author.avatar; img.alt = ''; img.width = 36; img.height = 36\n    img.referrerPolicy = 'no-referrer'\n    av.replaceWith(img); el.appendChild(img)\n  } else {\n    av.className = 'pfp none'; av.setAttribute('aria-hidden', 'true'); el.appendChild(av)\n  }\n  const txt = document.createElement('div')\n  txt.className = 'ntext'\n  const strong = document.createElement('strong')\n  strong.textContent = who\n  txt.appendChild(strong)\n  // textContent throughout: these are remote strings and must never be parsed as markup.\n  txt.appendChild(document.createTextNode(' ' + (REASON[n.reason] || n.reason)))\n  if (n.record && typeof n.record.text === 'string' && n.record.text) {\n    const q = document.createElement('div')\n    q.className = 'nquote'\n    q.textContent = n.record.text.slice(0, 180)\n    txt.appendChild(q)\n  }\n  const meta = document.createElement('div')\n  meta.className = 'meta'\n  if (n.indexedAt) {\n    const t = document.createElement('time')\n    t.dateTime = n.indexedAt\n    t.textContent = new Date(n.indexedAt).toLocaleString()\n    meta.appendChild(t)\n  }\n  // Link to OUR view of the subject where we can address it — the uri identifies the record, and favela\n  // renders it if this node holds it.\n  const subject = n.reasonSubject || n.uri\n  const m = /^at:\\/\\/(did:[^/]+)\\/[^/]+\\/(.+)$/.exec(String(subject || ''))\n  if (m) {\n    const a = document.createElement('a')\n    a.href = `/post/${encodeURIComponent(m[1])}/${encodeURIComponent(m[2])}`\n    a.textContent = ' open here'\n    meta.appendChild(a)\n  }\n  txt.appendChild(meta)\n  el.appendChild(txt)\n  return el\n}\n\nasync function load (session) {\n  say('loading…')\n  let s = session\n  let body\n  try {\n    body = await xrpc('app.bsky.notification.listNotifications', { bearer: s.accessJwt, params: { limit: 40 } })\n  } catch (e) {\n    if (e.status !== 401) throw e\n    // One refresh attempt, then give up rather than loop.\n    s = await refresh(s)\n    body = await xrpc('app.bsky.notification.listNotifications', { bearer: s.accessJwt, params: { limit: 40 } })\n  }\n  const list = (body && body.notifications) || []\n  out.innerHTML = ''\n  if (!list.length) { say('nothing new', ''); return }\n  for (const n of list) out.appendChild(rowFor(n))\n  const unread = list.filter((n) => !n.isRead).length\n  say(`${list.length} notification${list.length === 1 ? '' : 's'}${unread ? ` · ${unread} unread` : ''}`, 'ok')\n}\n\nasync function boot () {\n  const s = loadSession()\n  if (!s || !s.accessJwt) { if (form) form.hidden = false; say('sign in to load notifications'); return }\n  if (form) form.hidden = true\n  try { await load(s) } catch (e) {\n    // A dead session is not an error to shout about — offer the form again.\n    clearSession()\n    if (form) form.hidden = false\n    say((e && e.message) || 'could not load notifications', 'err')\n  }\n}\n\nif (form) {\n  form.addEventListener('submit', async (e) => {\n    e.preventDefault()\n    const identifier = $('notif-handle').value.trim()\n    const password = $('notif-pass').value\n    if (!identifier || !password) { say('handle and app password required', 'err'); return }\n    say('signing in…')\n    try {\n      const r = await xrpc('com.atproto.server.createSession', { method: 'POST', body: { identifier, password } })\n      // Only the JWTs are kept. The password is not stored, not logged, and goes out of scope here.\n      saveSession({ did: r.did, handle: r.handle, accessJwt: r.accessJwt, refreshJwt: r.refreshJwt })\n      $('notif-pass').value = ''\n      form.hidden = true\n      await load(loadSession())\n    } catch (err) {\n      say((err && err.message) || 'sign-in failed', 'err')\n    }\n  })\n}\n\nconst signout = $('notif-signout')\nif (signout) {\n  signout.addEventListener('click', () => {\n    clearSession()\n    out.innerHTML = ''\n    if (form) form.hidden = false\n    say('signed out of notifications on this browser')\n  })\n}\n\nboot()\n",
  "report.js": "// Report a post or account to a moderation service (com.atproto.moderation.createReport).\n//\n// SAME CREDENTIAL RULE AS NOTIFICATIONS, for the same reason: createReport is user-scoped, so it needs a\n// bearer, and favela-web deliberately holds none. The browser sends it, reusing the session notifications\n// already established — one login, not two. If there is no session, the control says so and points at\n// /notifications rather than silently doing nothing.\n//\n// Reports go to the PDS's moderation service. They are NOT public records and nothing is written to the\n// user's repo; this is a message to a moderator, which is why it needs no signing key.\nconst PDS = document.querySelector('meta[name=\"favela-pds\"]')?.content || 'https://pds.7rnx.net'\nconst KEY = 'favela.notif.session'\n\nconst REASONS = [\n  ['com.atproto.moderation.defs#reasonSpam', 'spam'],\n  ['com.atproto.moderation.defs#reasonViolation', 'rule violation'],\n  ['com.atproto.moderation.defs#reasonMisleading', 'misleading'],\n  ['com.atproto.moderation.defs#reasonSexual', 'unwanted sexual content'],\n  ['com.atproto.moderation.defs#reasonRude', 'rude or harassing'],\n  ['com.atproto.moderation.defs#reasonOther', 'other']\n]\n\nconst session = () => { try { return JSON.parse(localStorage.getItem(KEY) || 'null') } catch { return null } }\n\nfunction panel (uri, cid, anchor) {\n  const box = document.createElement('form')\n  box.className = 'reportbox'\n  const s = session()\n  if (!s || !s.accessJwt) {\n    box.innerHTML = '<p class=\"empty\">Reporting needs a signed-in session. <a href=\"/notifications\">sign in →</a></p>'\n    return box\n  }\n  const sel = document.createElement('select')\n  sel.setAttribute('aria-label', 'reason')\n  for (const [v, label] of REASONS) {\n    const o = document.createElement('option'); o.value = v; o.textContent = label; sel.appendChild(o)\n  }\n  const note = document.createElement('input')\n  note.type = 'text'; note.placeholder = 'anything the moderator should know (optional)'\n  note.setAttribute('aria-label', 'details')\n  const send = document.createElement('button')\n  send.type = 'submit'; send.textContent = 'send report'\n  const status = document.createElement('span')\n  status.className = 'empty'; status.setAttribute('aria-live', 'polite')\n  box.append(sel, note, send, status)\n\n  box.addEventListener('submit', async (e) => {\n    e.preventDefault()\n    send.disabled = true\n    status.textContent = 'sending…'\n    try {\n      // A post is reported as a strongRef (uri AND cid); an account as a repoRef with just the did.\n      const subject = cid\n        ? { $type: 'com.atproto.repo.strongRef', uri, cid }\n        : { $type: 'com.atproto.admin.defs#repoRef', did: uri }\n      const res = await fetch(`${PDS.replace(/\\/$/, '')}/xrpc/com.atproto.moderation.createReport`, {\n        method: 'POST',\n        headers: { 'content-type': 'application/json', authorization: `Bearer ${s.accessJwt}` },\n        body: JSON.stringify({ reasonType: sel.value, reason: note.value || undefined, subject })\n      })\n      const body = await res.json().catch(() => null)\n      if (!res.ok) throw new Error((body && (body.message || body.error)) || `HTTP ${res.status}`)\n      status.textContent = 'reported — thank you'\n      sel.disabled = note.disabled = true\n    } catch (err) {\n      status.textContent = (err && err.message) || 'report failed'\n      send.disabled = false\n    }\n  })\n  return box\n}\n\ndocument.addEventListener('click', (e) => {\n  const btn = e.target.closest && e.target.closest('.reportbtn')\n  if (!btn) return\n  e.preventDefault()\n  e.stopPropagation() // never trigger the post's whole-entry navigation\n  const existing = btn.parentElement.querySelector('.reportbox')\n  if (existing) { existing.remove(); return } // a second click closes it\n  btn.parentElement.appendChild(panel(btn.dataset.uri, btn.dataset.cid || null, btn))\n})\n",
  "resize-plan.js": "// Should this picture be re-encoded before upload, and to what size?\n//\n// ⛔ THE LIMIT IS THE LEXICON'S, NOT OURS. app.bsky.embed.images specifies\n//\n//   \"blob\": { \"accept\": [\"image/*\"], \"maxSize\": 2000000 }\n//\n// so 2,000,000 bytes is the ceiling, with at most 4 images per post and `alt` required. compose.js used\n// to enforce 1024*1024 — about half — with no justification anywhere in the source, and it REFUSED\n// oversize files rather than shrinking them. Once the phone's composer could open the camera (2026-08-18)\n// that made \"attach a photo\" a dead end by construction: a phone camera JPEG is 3–12 MB, so it failed\n// both the old cap and the real one. Raising the number alone fixes nothing; the picture has to shrink.\n//\n// Pure and DOM-free on purpose. The canvas work that acts on this lives in compose.js, where a browser is\n// required to test it; the decision — which is where the arithmetic errors live — is tested under node\n// (test/resize-plan.test.mjs).\n\n// The protocol ceiling, quoted rather than chosen.\nexport const MAX_BYTES = 2000000\n\n// Longest edge after scaling. Not from the lexicon — there is no dimension limit in atproto — but a\n// 4000px photo carries far more detail than any feed renders, and shrinking pixels is what makes the\n// byte ceiling reachable without destroying quality through compression alone.\nexport const MAX_EDGE = 2000\n\n/**\n * @param {{width:number, height:number, bytes:number, type:string}} file\n * @returns {{needed:boolean, width:number, height:number, reason:string}}\n */\nexport function resizePlan ({ width = 0, height = 0, bytes = 0, type = '' } = {}) {\n  const isImage = String(type).startsWith('image/')\n  // Canvas re-encoding a non-image produces a broken picture silently, so decline and let the caller\n  // reject it with a real message.\n  if (!isImage) return { needed: false, width, height, reason: 'not an image' }\n\n  const longest = Math.max(width, height)\n  const overEdge = longest > MAX_EDGE && longest > 0\n  const overBytes = bytes > MAX_BYTES\n\n  if (!overEdge && !overBytes) return { needed: false, width, height, reason: 'within limits' }\n\n  // Scale only when the picture is genuinely oversized in PIXELS. When it is merely heavy — a large JPEG\n  // at modest dimensions — keep every pixel and let re-encoding do the work; throwing away detail to fix\n  // a compression problem degrades the image for no reason.\n  if (!overEdge) return { needed: true, width, height, reason: 'over the byte ceiling' }\n\n  const scale = MAX_EDGE / longest\n  return {\n    needed: true,\n    width: Math.max(1, Math.round(width * scale)),\n    height: Math.max(1, Math.round(height * scale)),\n    reason: overBytes ? 'oversized and over the byte ceiling' : 'oversized'\n  }\n}\n\n/**\n * The `aspectRatio` field of app.bsky.embed.images#image — what bsky lays the image out with, and what\n * we have never sent, so every favela image has been laid out from a guess.\n *\n * Null rather than a zero ratio when the dimensions are unknown: no claim beats a wrong one.\n */\nexport function aspectRatioOf (width, height) {\n  const w = Math.round(Number(width) || 0)\n  const h = Math.round(Number(height) || 0)\n  if (w <= 0 || h <= 0) return null\n  return { width: w, height: h }\n}\n",
  "settings.js": "// Avatar upload — progressive enhancement for /settings.\n//\n// This exists because a lost avatar is otherwise UNRECOVERABLE: the blob bytes are gone from every\n// node (cdn 404, get-blob null, blobs/ empty), so nothing can restore it except the owner re-uploading.\n// Doing so also lands the first blob in the content-addressed OverlayBlobStore, so the migration off\n// the legacy Hyperbee blob store happens as a side effect.\n//\n// The bytes are POSTed RAW (no multipart): the server reads them binary-safe and derives the mime from\n// magic bytes, so there is no parser and no header to trust. favela never holds a key — it relays to\n// the local hpp, which stores the blob and signs the profile update.\n\nconst file = document.getElementById('avatar-file')\nconst status = document.getElementById('avatar-status')\nconst img = document.querySelector('.avatar')\n\nconst MAX = 1024 * 1024\n\nfunction say (msg, cls) {\n  if (!status) return\n  status.textContent = msg\n  status.className = cls || ''\n}\n\nif (file) {\n  file.addEventListener('change', async () => {\n    const f = file.files && file.files[0]\n    if (!f) return\n    // Check client-side too so the user gets an instant, specific message instead of a 413 round-trip.\n    if (f.size > MAX) { say(`that image is ${Math.round(f.size / 1024)} KB — the limit is 1024 KB`, 'err'); file.value = ''; return }\n    say('uploading…')\n    try {\n      const res = await fetch('/api/avatar', {\n        method: 'POST',\n        headers: { 'content-type': f.type || 'application/octet-stream' },\n        body: f\n      })\n      const body = await res.json().catch(() => ({}))\n      if (!res.ok) { say(body.error || `upload failed (${res.status})`, 'err'); return }\n      say('avatar updated — your hpp signed the profile record', 'ok')\n      // Show the new image immediately. Blobs are content-addressed and served immutable, so the new\n      // cid is a genuinely different URL — no cache-busting hack needed.\n      if (img && body.cid) {\n        const url = `/xrpc/com.atproto.sync.getBlob?did=${encodeURIComponent(body.did)}&cid=${encodeURIComponent(body.cid)}`\n        if (img.tagName === 'IMG') { img.src = url } else {\n          const n = document.createElement('img')\n          n.className = 'avatar'; n.src = url; n.alt = 'current avatar'\n          img.replaceWith(n)\n        }\n      }\n    } catch (e) {\n      say('upload failed: ' + e.message, 'err')\n    } finally {\n      file.value = ''\n    }\n  })\n}\n\n// ── Devices: mint a join code, and revoke/restore paired browsers ────────────────────────────────\n//\n// `favela-web pair` could already mint an invite; the browser could only CONSUME one. So adding a\n// second device meant shell access to the box running favela-web — the wrong requirement for \"sign in\n// on my phone\". This closes the loop entirely in the UI: generate here, paste at /login there.\n//\n// The list itself is server-rendered, so with JS off you can still SEE your devices; only the two\n// actions live here. Same posture as the avatar upload above.\n\nconst devStatus = document.getElementById('dev-status')\nconst pairBtn = document.getElementById('pair-new')\nconst pairOut = document.getElementById('pair-out')\nconst pairUrl = document.getElementById('pair-url')\nconst pairCode = document.getElementById('pair-code')\nconst pairCopy = document.getElementById('pair-copy')\nconst pairLabel = document.getElementById('pair-label')\n\nfunction devSay (msg, cls) {\n  if (!devStatus) return\n  devStatus.textContent = msg\n  devStatus.className = cls || ''\n}\n\nif (pairBtn) {\n  pairBtn.addEventListener('click', async () => {\n    pairBtn.disabled = true\n    devSay('minting a join code — your hpp is signing it…')\n    try {\n      const res = await fetch('/api/devices/pair', {\n        method: 'POST',\n        headers: { 'content-type': 'application/json' },\n        body: JSON.stringify({ label: pairLabel ? pairLabel.value : '' })\n      })\n      const body = await res.json().catch(() => ({}))\n      if (!res.ok) { devSay(body.error || `could not mint a join code (${res.status})`, 'err'); return }\n      pairCode.textContent = body.inviteHex\n      pairUrl.textContent = body.loginUrl\n      pairUrl.href = body.loginUrl\n      pairOut.hidden = false\n      // State the expiry as a duration rather than a timestamp — the code dies on first use OR at the\n      // TTL, and \"5 minutes\" is the fact that changes what the user does next.\n      const mins = Math.max(1, Math.round((body.expiresAt - Date.now()) / 60000))\n      devSay(`join code ready — valid for ~${mins} min, or until it is used once`, 'ok')\n    } catch (e) {\n      devSay('could not mint a join code: ' + e.message, 'err')\n    } finally {\n      pairBtn.disabled = false\n    }\n  })\n}\n\nif (pairCopy) {\n  pairCopy.addEventListener('click', async () => {\n    try {\n      await navigator.clipboard.writeText(pairCode.textContent || '')\n      devSay('join code copied', 'ok')\n    } catch {\n      // Clipboard is permission-gated and absent over plain http on some browsers. The code is on the\n      // page either way, so say so rather than failing silently.\n      devSay('could not copy — select the code above and copy it manually', 'err')\n    }\n  })\n}\n\n// Revoke/restore. Delegated from the list so it keeps working if rows are ever re-rendered.\ndocument.querySelectorAll('.dev .devbtn').forEach((btn) => {\n  btn.addEventListener('click', async () => {\n    const row = btn.closest('.dev')\n    const subKey = row && row.dataset.subkey\n    if (!subKey) return\n    const restore = btn.dataset.action === 'restore'\n    btn.disabled = true\n    devSay(restore ? 'restoring…' : 'revoking…')\n    try {\n      const res = await fetch('/api/devices/revoke', {\n        method: 'POST',\n        headers: { 'content-type': 'application/json' },\n        body: JSON.stringify({ subKey, restore })\n      })\n      const body = await res.json().catch(() => ({}))\n      if (!res.ok) { devSay(body.error || `failed (${res.status})`, 'err'); return }\n      // Flip the row in place. A revoke is persistent + replicated, so the next page load agrees —\n      // this is just avoiding a reload, not inventing state.\n      row.classList.toggle('revoked', !restore)\n      btn.dataset.action = restore ? 'revoke' : 'restore'\n      btn.textContent = restore ? 'revoke' : 'restore'\n      devSay(restore ? 'device restored — it can sign in again' : 'device revoked — its sessions are dead', 'ok')\n    } catch (e) {\n      devSay('failed: ' + e.message, 'err')\n    } finally {\n      btn.disabled = false\n    }\n  })\n})\n\n// ── name + bio counters ──────────────────────────────────────────────────────────────────────────\n//\n// The form itself is a plain POST that works with scripting off; these counters are enhancement only.\n// atproto caps displayName at 64 GRAPHEMES and description at 256 — counted the same way the composer\n// does, because .length over-counts emoji and would warn about a legal value.\nconst pfSeg = (typeof Intl !== 'undefined' && Intl.Segmenter) ? new Intl.Segmenter(undefined, { granularity: 'grapheme' }) : null\nconst pfCount = (s) => pfSeg ? [...pfSeg.segment(s)].length : [...String(s)].length\n\nfunction wireCounter (fieldId, ccId, limit) {\n  const el = document.getElementById(fieldId)\n  const cc = document.getElementById(ccId)\n  if (!el || !cc) return\n  const upd = () => {\n    const left = limit - pfCount(el.value)\n    cc.textContent = left > Math.min(20, limit / 4) ? '' : left + ' left'\n    cc.classList.toggle('over', left < 0)\n  }\n  el.addEventListener('input', upd)\n  upd()\n  return () => limit - pfCount(el.value) >= 0\n}\n\nconst nameOk = wireCounter('pf-name', 'pf-name-cc', 64)\nconst bioOk = wireCounter('pf-bio', 'pf-bio-cc', 256)\nconst proform = document.querySelector('.proform')\nif (proform) {\n  // Block a submit that the server would reject anyway, so the user sees it before a round-trip.\n  proform.addEventListener('submit', (e) => {\n    if ((nameOk && !nameOk()) || (bioOk && !bioOk())) e.preventDefault()\n  })\n}\n\n// ── banner ───────────────────────────────────────────────────────────────────────────────────────\n// Same flow as the avatar above, against /api/banner. Kept as its own handler and its own route rather\n// than a shared one with a flag, so a bug in either cannot write the other's profile field.\nconst bfile = document.getElementById('banner-file')\nconst bstatus = document.getElementById('banner-status')\n\nfunction bsay (msg, cls) {\n  if (!bstatus) return\n  bstatus.textContent = msg\n  bstatus.className = cls || ''\n}\n\nif (bfile) {\n  bfile.addEventListener('change', async () => {\n    const f = bfile.files && bfile.files[0]\n    if (!f) return\n    if (f.size > MAX) { bsay(`that image is ${Math.round(f.size / 1024)} KB — the limit is 1024 KB`, 'err'); bfile.value = ''; return }\n    bsay('uploading…')\n    try {\n      const res = await fetch('/api/banner', {\n        method: 'POST',\n        headers: { 'content-type': f.type || 'application/octet-stream' },\n        body: f\n      })\n      const body = await res.json().catch(() => ({}))\n      if (!res.ok) { bsay(body.error || `upload failed (${res.status})`, 'err'); return }\n      bsay('banner updated — your hpp signed the profile record', 'ok')\n      // Content-addressed, so the new cid is a different URL — nothing to cache-bust.\n      if (body.cid) {\n        const url = `/xrpc/com.atproto.sync.getBlob?did=${encodeURIComponent(body.did)}&cid=${encodeURIComponent(body.cid)}`\n        let holder = document.querySelector('.profbanner.small')\n        if (!holder) {\n          holder = document.createElement('div')\n          holder.className = 'profbanner small'\n          const anchor = bfile.closest('section')\n          if (anchor) anchor.insertBefore(holder, anchor.querySelector('p:has(.imgpick)') || anchor.lastElementChild)\n        }\n        holder.innerHTML = ''\n        const n = document.createElement('img')\n        n.src = url; n.alt = 'current banner'\n        holder.appendChild(n)\n      }\n    } catch (e) {\n      bsay((e && e.message) || 'upload failed', 'err')\n    }\n  })\n}\n",
  "toast.js": "// toast — the one place a failure gets SAID.\n//\n// THE PROBLEM. Every client-side write already handles its own failure correctly: actions.js puts the\n// original state back rather than leaving a lie on screen. But the only place it says WHY is a `title`\n// attribute and a 1.2s red flash. A `title` needs a hover, so on touch it does not exist at all, and no\n// screen reader announces it. So the honest state of things was: the write failed, the UI silently\n// reverted, and the user's reasonable reading is \"my tap didn't register\" — they tap again.\n//\n// Silent failure is the worst class of bug in this codebase and we keep re-learning it (hyper-social #24,\n// #26: \"everything we control reports success\"). A control that reverts without saying why is the same\n// mistake at the UI layer.\n//\n// SHAPE. One shared live region, appended once, reused. `role=\"status\"` + `aria-live=\"polite\"` so it is\n// announced without stealing focus; assertive is reserved for errors, which ARE interruptions.\n//\n// Deliberately NOT a dependency of the no-JS path: this file only ever runs as progressive enhancement,\n// and nothing renders differently when it is absent. If it fails to load, the pre-existing flash + title\n// behaviour is still there — this is additive.\n\nlet host = null\n\nfunction ensureHost () {\n  if (host && host.isConnected) return host\n  host = document.createElement('div')\n  host.className = 'toasts'\n  // The region must exist in the DOM BEFORE the message is written into it, or assistive tech may not\n  // announce a node that appeared already-populated. Hence a persistent host with children swapped in.\n  host.setAttribute('role', 'status')\n  host.setAttribute('aria-live', 'polite')\n  document.body.appendChild(host)\n  return host\n}\n\n// msg  — plain text, never HTML (it carries server error strings, which are untrusted)\n// kind — 'error' | 'info'. Errors are assertive and linger; info is polite and brief.\nexport function toast (msg, { kind = 'error', ms = null } = {}) {\n  const text = String(msg == null ? '' : msg).trim()\n  if (!text) return\n  const h = ensureHost()\n  h.setAttribute('aria-live', kind === 'error' ? 'assertive' : 'polite')\n\n  const el = document.createElement('div')\n  el.className = 'toast ' + (kind === 'error' ? 'toast-err' : 'toast-info')\n  el.textContent = text // textContent, NOT innerHTML — this string comes off the wire\n\n  // A dismiss control, because an error that vanishes on a timer is unreadable to anyone who reads\n  // slowly, and one that never vanishes is litter. Both: it auto-dismisses, and you can kill it early.\n  const close = document.createElement('button')\n  close.className = 'toast-x'\n  close.setAttribute('aria-label', 'dismiss')\n  close.textContent = '✕'\n  close.addEventListener('click', () => el.remove())\n  el.appendChild(close)\n\n  h.appendChild(el)\n  const life = Number.isFinite(ms) ? ms : (kind === 'error' ? 6000 : 3000)\n  setTimeout(() => { el.remove() }, life)\n  // Never let the region grow without bound if something fails in a loop.\n  while (h.children.length > 4) h.removeChild(h.firstChild)\n}\n\nexport default toast\n",
  "vendor/noble-secp256k1.js": "/*! noble-secp256k1 - MIT License (c) 2019 Paul Miller (paulmillr.com) */\n/**\n * 4KB JS implementation of secp256k1 signatures & ECDH. Compliant with RFC6979.\n * @module\n */\nconst B256 = 2n ** 256n;\nconst P = B256 - 0x1000003d1n; // curve's field prime\nconst N = B256 - 0x14551231950b75fc4402da1732fc9bebfn; // curve (group) order\nconst Gx = 0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798n; // base point x\nconst Gy = 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8n; // base point y\n/**\n * secp256k1 curve parameters. Equation is x³ + ax + b.\n * Gx and Gy are generator coordinates. p is field order, n is group order.\n */\nconst CURVE = {\n    p: P, n: N, a: 0n, b: 7n, Gx, Gy\n}; // exported variables incl. a, b\nconst fLen = 32; // field / group byte length\nconst curve = (x) => M(M(x * x) * x + CURVE.b); // x³ + ax + b weierstrass formula; a=0\nconst err = (m = '') => { throw new Error(m); }; // error helper, messes-up stack trace\nconst isB = (n) => typeof n === 'bigint'; // is big integer\nconst isS = (s) => typeof s === 'string'; // is string\nconst fe = (n) => isB(n) && 0n < n && n < P; // is field element (invertible)\nconst ge = (n) => isB(n) && 0n < n && n < N; // is group element\nconst isu8 = (a) => (a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array'));\nconst au8 = (a, l) => // assert is Uint8Array (of specific length)\n !isu8(a) || (typeof l === 'number' && l > 0 && a.length !== l) ?\n    err('Uint8Array expected') : a;\nconst u8n = (data) => new Uint8Array(data); // creates Uint8Array\nconst toU8 = (a, len) => au8(isS(a) ? h2b(a) : u8n(au8(a)), len); // norm(hex/u8a) to u8a\nconst M = (a, b = P) => {\n    const r = a % b;\n    return r >= 0n ? r : b + r;\n};\nconst aPoint = (p) => (p instanceof Point ? p : err('Point expected')); // is 3d point\n/** Point in 3d xyz projective coordinates. 3d takes less inversions than 2d. */\nclass Point {\n    constructor(px, py, pz) {\n        this.px = px;\n        this.py = py;\n        this.pz = pz;\n        Object.freeze(this);\n    }\n    /** Create 3d xyz point from 2d xy. (0, 0) => (0, 1, 0), not (0, 0, 1) */\n    static fromAffine(p) {\n        return ((p.x === 0n) && (p.y === 0n)) ? I : new Point(p.x, p.y, 1n);\n    }\n    /** Convert Uint8Array or hex string to Point. */\n    static fromHex(hex) {\n        hex = toU8(hex); // convert hex string to Uint8Array\n        let p = undefined;\n        const head = hex[0], tail = hex.subarray(1); // first byte is prefix, rest is data\n        const x = slc(tail, 0, fLen), len = hex.length; // next 32 bytes are x coordinate\n        if (len === 33 && [0x02, 0x03].includes(head)) { // compressed points: 33b, start\n            if (!fe(x))\n                err('Point hex invalid: x not FE'); // with byte 0x02 or 0x03. Check if 0<x<P\n            let y = sqrt(curve(x)); // x³ + ax + b is right side of equation\n            const isYOdd = (y & 1n) === 1n; // y² is equivalent left-side. Calculate y²:\n            const headOdd = (head & 1) === 1; // y = √y²; there are two solutions: y, -y\n            if (headOdd !== isYOdd)\n                y = M(-y); // determine proper solution\n            p = new Point(x, y, 1n); // create point\n        } // Uncompressed points: 65b, start with 0x04\n        if (len === 65 && head === 0x04)\n            p = new Point(x, slc(tail, fLen, 2 * fLen), 1n);\n        return p ? p.ok() : err('Point invalid: not on curve'); // Verify the result\n    }\n    /** Create point from a private key. */\n    static fromPrivateKey(k) { return G.mul(toPriv(k)); }\n    get x() { return this.aff().x; } // .x, .y will call expensive toAffine:\n    get y() { return this.aff().y; } // should be used with care.\n    /** Equality check: compare points P&Q. */\n    equals(other) {\n        const { px: X1, py: Y1, pz: Z1 } = this;\n        const { px: X2, py: Y2, pz: Z2 } = aPoint(other); // isPoint() checks class equality\n        const X1Z2 = M(X1 * Z2), X2Z1 = M(X2 * Z1);\n        const Y1Z2 = M(Y1 * Z2), Y2Z1 = M(Y2 * Z1);\n        return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;\n    }\n    /** Flip point over y coordinate. */\n    negate() { return new Point(this.px, M(-this.py), this.pz); }\n    /** Point doubling: P+P, complete formula. */\n    double() { return this.add(this); }\n    /**\n     * Point addition: P+Q, complete, exception-free formula\n     * (Renes-Costello-Batina, algo 1 of [2015/1060](https://eprint.iacr.org/2015/1060)).\n     * Cost: 12M + 0S + 3*a + 3*b3 + 23add.\n     */\n    add(other) {\n        const { px: X1, py: Y1, pz: Z1 } = this;\n        const { px: X2, py: Y2, pz: Z2 } = aPoint(other);\n        const { a, b } = CURVE;\n        let X3 = 0n, Y3 = 0n, Z3 = 0n;\n        const b3 = M(b * 3n);\n        let t0 = M(X1 * X2), t1 = M(Y1 * Y2), t2 = M(Z1 * Z2), t3 = M(X1 + Y1); // step 1\n        let t4 = M(X2 + Y2); // step 5\n        t3 = M(t3 * t4);\n        t4 = M(t0 + t1);\n        t3 = M(t3 - t4);\n        t4 = M(X1 + Z1);\n        let t5 = M(X2 + Z2); // step 10\n        t4 = M(t4 * t5);\n        t5 = M(t0 + t2);\n        t4 = M(t4 - t5);\n        t5 = M(Y1 + Z1);\n        X3 = M(Y2 + Z2); // step 15\n        t5 = M(t5 * X3);\n        X3 = M(t1 + t2);\n        t5 = M(t5 - X3);\n        Z3 = M(a * t4);\n        X3 = M(b3 * t2); // step 20\n        Z3 = M(X3 + Z3);\n        X3 = M(t1 - Z3);\n        Z3 = M(t1 + Z3);\n        Y3 = M(X3 * Z3);\n        t1 = M(t0 + t0); // step 25\n        t1 = M(t1 + t0);\n        t2 = M(a * t2);\n        t4 = M(b3 * t4);\n        t1 = M(t1 + t2);\n        t2 = M(t0 - t2); // step 30\n        t2 = M(a * t2);\n        t4 = M(t4 + t2);\n        t0 = M(t1 * t4);\n        Y3 = M(Y3 + t0);\n        t0 = M(t5 * t4); // step 35\n        X3 = M(t3 * X3);\n        X3 = M(X3 - t0);\n        t0 = M(t3 * t1);\n        Z3 = M(t5 * Z3);\n        Z3 = M(Z3 + t0); // step 40\n        return new Point(X3, Y3, Z3);\n    }\n    mul(n, safe = true) {\n        if (!safe && n === 0n)\n            return I; // in unsafe mode, allow zero\n        if (!ge(n))\n            err('scalar invalid'); // must be 0 < n < CURVE.n\n        if (this.equals(G))\n            return wNAF(n).p; // use precomputes for base point\n        let p = I, f = G; // init result point & fake point\n        for (let d = this; n > 0n; d = d.double(), n >>= 1n) { // double-and-add ladder\n            if (n & 1n)\n                p = p.add(d); // if bit is present, add to point\n            else if (safe)\n                f = f.add(d); // if not, add to fake for timing safety\n        }\n        return p;\n    }\n    mulAddQUns(R, u1, u2) {\n        return this.mul(u1, false).add(R.mul(u2, false)).ok(); // Unsafe: do NOT use for stuff related\n    } // to private keys. Doesn't use Shamir trick\n    /** Convert point to 2d xy affine point. (x, y, z) ∋ (x=x/z, y=y/z) */\n    toAffine() {\n        const { px: x, py: y, pz: z } = this;\n        if (this.equals(I))\n            return { x: 0n, y: 0n }; // fast-path for zero point\n        if (z === 1n)\n            return { x, y }; // if z is 1, pass affine coordinates as-is\n        const iz = inv(z, P); // z^-1: invert z\n        if (M(z * iz) !== 1n)\n            err('inverse invalid'); // (z * z^-1) must be 1, otherwise bad math\n        return { x: M(x * iz), y: M(y * iz) }; // x = x*z^-1; y = y*z^-1\n    }\n    /** Checks if the point is valid and on-curve. */\n    assertValidity() {\n        const { x, y } = this.aff(); // convert to 2d xy affine point.\n        if (!fe(x) || !fe(y))\n            err('Point invalid: x or y'); // x and y must be in range 0 < n < P\n        return M(y * y) === curve(x) ? // y² = x³ + ax + b, must be equal\n            this : err('Point invalid: not on curve');\n    }\n    multiply(n) { return this.mul(n); } // Aliases to compress code\n    aff() { return this.toAffine(); }\n    ok() { return this.assertValidity(); }\n    toHex(isCompressed = true) {\n        const { x, y } = this.aff(); // convert to 2d xy affine point\n        const head = isCompressed ? ((y & 1n) === 0n ? '02' : '03') : '04'; // 0x02, 0x03, 0x04 prefix\n        return head + n2h(x) + (isCompressed ? '' : n2h(y)); // prefix||x and ||y\n    }\n    toRawBytes(isCompressed = true) {\n        return h2b(this.toHex(isCompressed)); // re-use toHex(), convert hex to bytes\n    }\n}\n/** Generator / base point */\nPoint.BASE = new Point(Gx, Gy, 1n);\n/** Identity / zero point */\nPoint.ZERO = new Point(0n, 1n, 0n);\nconst { BASE: G, ZERO: I } = Point; // Generator, identity points\nconst padh = (n, pad) => n.toString(16).padStart(pad, '0');\nconst b2h = (b) => Array.from(au8(b)).map(e => padh(e, 2)).join(''); // bytes to hex\nconst C = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 }; // ASCII characters\nconst _ch = (ch) => {\n    if (ch >= C._0 && ch <= C._9)\n        return ch - C._0; // '2' => 50-48\n    if (ch >= C.A && ch <= C.F)\n        return ch - (C.A - 10); // 'B' => 66-(65-10)\n    if (ch >= C.a && ch <= C.f)\n        return ch - (C.a - 10); // 'b' => 98-(97-10)\n    return;\n};\nconst h2b = (hex) => {\n    const e = 'hex invalid';\n    if (!isS(hex))\n        return err(e);\n    const hl = hex.length, al = hl / 2;\n    if (hl % 2)\n        return err(e);\n    const array = u8n(al);\n    for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) { // treat each char as ASCII\n        const n1 = _ch(hex.charCodeAt(hi)); // parse first char, multiply it by 16\n        const n2 = _ch(hex.charCodeAt(hi + 1)); // parse second char\n        if (n1 === undefined || n2 === undefined)\n            return err(e);\n        array[ai] = n1 * 16 + n2; // example: 'A9' => 10*16 + 9\n    }\n    return array;\n};\nconst b2n = (b) => BigInt('0x' + (b2h(b) || '0')); // bytes to number\nconst slc = (b, from, to) => b2n(b.slice(from, to)); // slice bytes num\nconst n2b = (num) => {\n    return isB(num) && num >= 0n && num < B256 ? h2b(padh(num, 2 * fLen)) : err('bigint expected');\n};\nconst n2h = (num) => b2h(n2b(num)); // number to 32b hex\nconst concatB = (...arrs) => {\n    const r = u8n(arrs.reduce((sum, a) => sum + au8(a).length, 0)); // create u8a of summed length\n    let pad = 0; // walk through each array,\n    arrs.forEach(a => { r.set(a, pad); pad += a.length; }); // ensure they have proper type\n    return r;\n};\nconst inv = (num, md) => {\n    if (num === 0n || md <= 0n)\n        err('no inverse n=' + num + ' mod=' + md); // no neg exponent for now\n    let a = M(num, md), b = md, x = 0n, y = 1n, u = 1n, v = 0n;\n    while (a !== 0n) { // uses euclidean gcd algorithm\n        const q = b / a, r = b % a; // not constant-time\n        const m = x - u * q, n = y - v * q;\n        b = a, a = r, x = u, y = v, u = m, v = n;\n    }\n    return b === 1n ? M(x, md) : err('no inverse'); // b is gcd at this point\n};\nconst sqrt = (n) => {\n    let r = 1n; // So, a special, fast case. Paper: \"Square Roots from 1;24,51,10 to Dan Shanks\".\n    for (let num = n, e = (P + 1n) / 4n; e > 0n; e >>= 1n) { // powMod: modular exponentiation.\n        if (e & 1n)\n            r = (r * num) % P; // Uses exponentiation by squaring.\n        num = (num * num) % P; // Not constant-time.\n    }\n    return M(r * r) === n ? r : err('sqrt invalid'); // check if result is valid\n};\nconst toPriv = (p) => {\n    if (!isB(p))\n        p = b2n(toU8(p, fLen)); // convert to bigint when bytes\n    return ge(p) ? p : err('private key invalid 3'); // check if bigint is in range\n};\nconst high = (n) => n > (N >> 1n); // if a number is bigger than CURVE.n/2\n/** Creates 33/65-byte public key from 32-byte private key. */\nconst getPublicKey = (privKey, isCompressed = true) => {\n    return Point.fromPrivateKey(privKey).toRawBytes(isCompressed);\n};\n/** ECDSA Signature class. Supports only compact 64-byte representation, not DER. */\nclass Signature {\n    constructor(r, s, recovery) {\n        this.r = r;\n        this.s = s;\n        this.recovery = recovery;\n        this.assertValidity(); // recovery bit is optional when\n    } // constructed outside.\n    /** Create signature from 64b compact (r || s) representation. */\n    static fromCompact(hex) {\n        hex = toU8(hex, 64); // compact repr is (32b r)||(32b s)\n        return new Signature(slc(hex, 0, fLen), slc(hex, fLen, 2 * fLen));\n    }\n    assertValidity() { return ge(this.r) && ge(this.s) ? this : err(); } // 0 < r or s < CURVE.n\n    /** Create new signature, with added recovery bit. */\n    addRecoveryBit(rec) {\n        return new Signature(this.r, this.s, rec);\n    }\n    hasHighS() { return high(this.s); }\n    normalizeS() {\n        return high(this.s) ? new Signature(this.r, M(-this.s, N), this.recovery) : this;\n    }\n    /** ECDSA public key recovery. Requires msg hash and recovery id. */\n    recoverPublicKey(msgh) {\n        const { r, s, recovery: rec } = this; // secg.org/sec1-v2.pdf 4.1.6\n        if (![0, 1, 2, 3].includes(rec))\n            err('recovery id invalid'); // check recovery id\n        const h = bits2int_modN(toU8(msgh, fLen)); // Truncate hash\n        const radj = rec === 2 || rec === 3 ? r + N : r; // If rec was 2 or 3, q.x is bigger than n\n        if (radj >= P)\n            err('q.x invalid'); // ensure q.x is still a field element\n        const head = (rec & 1) === 0 ? '02' : '03'; // head is 0x02 or 0x03\n        const R = Point.fromHex(head + n2h(radj)); // concat head + hex repr of r\n        const ir = inv(radj, N); // r^-1\n        const u1 = M(-h * ir, N); // -hr^-1\n        const u2 = M(s * ir, N); // sr^-1\n        return G.mulAddQUns(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1)\n    }\n    /** Uint8Array 64b compact (r || s) representation. */\n    toCompactRawBytes() { return h2b(this.toCompactHex()); }\n    /** Hex string 64b compact (r || s) representation. */\n    toCompactHex() { return n2h(this.r) + n2h(this.s); }\n}\nconst bits2int = (bytes) => {\n    const delta = bytes.length * 8 - 256; // RFC suggests optional truncating via bits2octets\n    if (delta > 1024)\n        err('msg invalid'); // our CUSTOM check, \"just-in-case\"\n    const num = b2n(bytes); // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which\n    return delta > 0 ? num >> BigInt(delta) : num; // matches bits2int. bits2int can produce res>N.\n};\nconst bits2int_modN = (bytes) => {\n    return M(bits2int(bytes), N); // with 0: BAD for trunc as per RFC vectors\n};\nconst i2o = (num) => n2b(num); // int to octets\nconst cr = () => // We support: 1) browsers 2) node.js 19+ 3) deno, other envs with crypto\n typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;\nlet _hmacSync; // Can be redefined by use in utils; built-ins don't provide it\nconst optS = { lowS: true }; // opts for sign()\nconst optV = { lowS: true }; // standard opts for verify()\nconst prepSig = (msgh, priv, opts = optS) => {\n    if (['der', 'recovered', 'canonical'].some(k => k in opts))\n        err('option not supported'); // legacy opts\n    let { lowS } = opts; // generates low-s sigs by default\n    if (lowS == null)\n        lowS = true; // RFC6979 3.2: we skip step A\n    const h1i = bits2int_modN(toU8(msgh)); // msg bigint\n    const h1o = i2o(h1i); // msg octets\n    const d = toPriv(priv); // validate private key, convert to bigint\n    const seed = [i2o(d), h1o]; // Step D of RFC6979 3.2\n    let ent = opts.extraEntropy; // RFC6979 3.6: additional k' (optional)\n    if (ent) // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')\n        seed.push(ent === true ? etc.randomBytes(fLen) : toU8(ent)); // true == fetch from CSPRNG\n    const m = h1i; // convert msg to bigint\n    const k2sig = (kBytes) => {\n        const k = bits2int(kBytes); // RFC6979 method.\n        if (!ge(k))\n            return; // Check 0 < k < CURVE.n\n        const ik = inv(k, N); // k^-1 mod n, NOT mod P\n        const q = G.mul(k).aff(); // q = Gk\n        const r = M(q.x, N); // r = q.x mod n\n        if (r === 0n)\n            return; // r=0 invalid\n        const s = M(ik * M(m + M(d * r, N), N), N); // s = k^-1(m + rd) mod n\n        if (s === 0n)\n            return; // s=0 invalid\n        let normS = s; // normalized S\n        let rec = (q.x === r ? 0 : 2) | Number(q.y & 1n); // recovery bit\n        if (lowS && high(s)) { // if lowS was passed, ensure s is always\n            normS = M(-s, N); // in the bottom half of CURVE.n\n            rec ^= 1;\n        }\n        return new Signature(r, normS, rec); // use normS, not s\n    };\n    return { seed: concatB(...seed), k2sig };\n};\nfunction hmacDrbg(asynchronous) {\n    let v = u8n(fLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n    let k = u8n(fLen); // Steps B, C of RFC6979 3.2: set hashLen, in our case always same\n    let i = 0; // Iterations counter, will throw when over 1000\n    const reset = () => { v.fill(1); k.fill(0); i = 0; };\n    const _e = 'drbg: tried 1000 values';\n    if (asynchronous) { // asynchronous=true\n        const h = (...b) => etc.hmacSha256Async(k, v, ...b); // hmac(k)(v, ...values)\n        const reseed = async (seed = u8n()) => {\n            k = await h(u8n([0x00]), seed); // k = hmac(K || V || 0x00 || seed)\n            v = await h(); // v = hmac(K || V)\n            if (seed.length === 0)\n                return;\n            k = await h(u8n([0x01]), seed); // k = hmac(K || V || 0x01 || seed)\n            v = await h(); // v = hmac(K || V)\n        };\n        const gen = async () => {\n            if (i++ >= 1000)\n                err(_e);\n            v = await h(); // v = hmac(K || V)\n            return v;\n        };\n        return async (seed, pred) => {\n            reset(); // the returned fn, don't, it's: 1. slower (JIT). 2. unsafe (async race conditions)\n            await reseed(seed); // Steps D-G\n            let res = undefined; // Step H: grind until k is in [1..n-1]\n            while (!(res = pred(await gen())))\n                await reseed(); // test predicate until it returns ok\n            reset();\n            return res;\n        };\n    }\n    else {\n        const h = (...b) => {\n            const f = _hmacSync;\n            if (!f)\n                err('etc.hmacSha256Sync not set');\n            return f(k, v, ...b); // hmac(k)(v, ...values)\n        };\n        const reseed = (seed = u8n()) => {\n            k = h(u8n([0x00]), seed); // k = hmac(k || v || 0x00 || seed)\n            v = h(); // v = hmac(k || v)\n            if (seed.length === 0)\n                return;\n            k = h(u8n([0x01]), seed); // k = hmac(k || v || 0x01 || seed)\n            v = h(); // v = hmac(k || v)\n        };\n        const gen = () => {\n            if (i++ >= 1000)\n                err(_e);\n            v = h(); // v = hmac(k || v)\n            return v;\n        };\n        return (seed, pred) => {\n            reset();\n            reseed(seed); // Steps D-G\n            let res = undefined; // Step H: grind until k is in [1..n-1]\n            while (!(res = pred(gen())))\n                reseed(); // test predicate until it returns ok\n            reset();\n            return res;\n        };\n    }\n}\n;\n/** ECDSA signature generation. via secg.org/sec1-v2.pdf 4.1.2 + RFC6979 deterministic k. */\n/**\n * Sign a msg hash using secp256k1. Async.\n * It is advised to use `extraEntropy: true` (from RFC6979 3.6) to prevent fault attacks.\n * Worst case: if randomness source for extraEntropy is bad, it would be as secure as if\n * the option has not been used.\n * @param msgh - message HASH, not message itself e.g. sha256(message)\n * @param priv - private key\n * @param opts - `lowS: true` to prevent malleability (s >= CURVE.n/2), `extraEntropy: boolean | Hex` to improve sig security.\n */\nconst signAsync = async (msgh, priv, opts = optS) => {\n    const { seed, k2sig } = prepSig(msgh, priv, opts); // Extract arguments for hmac-drbg\n    return hmacDrbg(true)(seed, k2sig); // Re-run drbg until k2sig returns ok\n};\n/**\n * Sign a msg hash using secp256k1.\n * It is advised to use `extraEntropy: true` (from RFC6979 3.6) to prevent fault attacks.\n * Worst case: if randomness source for extraEntropy is bad, it would be as secure as if\n * the option has not been used.\n * @param msgh - message HASH, not message itself e.g. sha256(message)\n * @param priv - private key\n * @param opts - `lowS: true` to prevent malleability (s >= CURVE.n/2), `extraEntropy: boolean | Hex` to improve sig security.\n * @example\n * const sig = sign(sha256('hello'), privKey, { extraEntropy: true }).toCompactRawBytes();\n */\nconst sign = (msgh, priv, opts = optS) => {\n    const { seed, k2sig } = prepSig(msgh, priv, opts); // Extract arguments for hmac-drbg\n    return hmacDrbg(false)(seed, k2sig); // Re-run drbg until k2sig returns ok\n};\n/**\n * Verify a signature using secp256k1.\n * @param sig - signature, 64-byte or Signature instance\n * @param msgh - message HASH, not message itself e.g. sha256(message)\n * @param pub - public key\n * @param opts - { lowS: true } is default, prohibits s >= CURVE.n/2 to prevent malleability\n */\nconst verify = (sig, msgh, pub, opts = optV) => {\n    let { lowS } = opts; // ECDSA signature verification\n    if (lowS == null)\n        lowS = true; // Default lowS=true\n    if ('strict' in opts)\n        err('option not supported'); // legacy param\n    let sig_, h, P; // secg.org/sec1-v2.pdf 4.1.4\n    const rs = sig && typeof sig === 'object' && 'r' in sig; // Previous ver supported DER sigs. We\n    if (!rs && (toU8(sig).length !== 2 * fLen)) // throw error when DER is suspected now.\n        err('signature must be 64 bytes');\n    try {\n        sig_ = rs ? new Signature(sig.r, sig.s).assertValidity() : Signature.fromCompact(sig);\n        h = bits2int_modN(toU8(msgh)); // Truncate hash\n        P = pub instanceof Point ? pub.ok() : Point.fromHex(pub); // Validate public key\n    }\n    catch (e) {\n        return false;\n    } // Check sig for validity in both cases\n    if (!sig_)\n        return false;\n    const { r, s } = sig_;\n    if (lowS && high(s))\n        return false; // lowS bans sig.s >= CURVE.n/2\n    let R;\n    try {\n        const is = inv(s, N); // s^-1\n        const u1 = M(h * is, N); // u1 = hs^-1 mod n\n        const u2 = M(r * is, N); // u2 = rs^-1 mod n\n        R = G.mulAddQUns(P, u1, u2).aff(); // R = u1⋅G + u2⋅P\n    }\n    catch (error) {\n        return false;\n    }\n    if (!R)\n        return false; // stop if R is identity / zero point\n    const v = M(R.x, N); // R.x must be in N's field, not P's\n    return v === r; // mod(R.x, n) == r\n};\n/**\n * Elliptic Curve Diffie-Hellman (ECDH) on secp256k1.\n * Result is **NOT hashed**. Use hash on it if you need.\n * @param privA private key A\n * @param pubB public key B\n * @param isCompressed 33-byte or 65-byte output\n * @returns public key C\n */\nconst getSharedSecret = (privA, pubB, isCompressed = true) => {\n    return Point.fromHex(pubB).mul(toPriv(privA)).toRawBytes(isCompressed); // ECDH\n};\nconst hashToPrivateKey = (hash) => {\n    hash = toU8(hash); // produces private keys with modulo bias\n    if (hash.length < fLen + 8 || hash.length > 1024)\n        err('expected 40-1024b'); // being neglible.\n    const num = M(b2n(hash), N - 1n); // takes n+8 bytes\n    return n2b(num + 1n); // returns (hash mod n-1)+1\n};\n/** Math, hex, byte helpers. Not in `utils` because utils share API with noble-curves. */\nconst etc = {\n    hexToBytes: h2b,\n    bytesToHex: b2h,\n    concatBytes: concatB,\n    bytesToNumberBE: b2n,\n    numberToBytesBE: n2b,\n    mod: M,\n    invert: inv, // math utilities\n    hmacSha256Async: async (key, ...msgs) => {\n        const c = cr(); // async HMAC-SHA256, no sync built-in!\n        const s = c && c.subtle; // For React Native support, see README.\n        if (!s)\n            return err('etc.hmacSha256Async or crypto.subtle must be defined'); // Uses webcrypto built-in cryptography.\n        const k = await s.importKey('raw', key, { name: 'HMAC', hash: { name: 'SHA-256' } }, false, ['sign']);\n        return u8n(await s.sign('HMAC', k, concatB(...msgs)));\n    },\n    hmacSha256Sync: _hmacSync, // For TypeScript. Actual logic is below\n    hashToPrivateKey: hashToPrivateKey,\n    randomBytes: (len = 32) => {\n        const crypto = cr(); // Must be shimmed in node.js <= 18 to prevent error. See README.\n        if (!crypto || !crypto.getRandomValues)\n            err('crypto.getRandomValues must be defined');\n        return crypto.getRandomValues(u8n(len));\n    },\n};\n/** Curve-specific utilities for private keys. */\nconst utils = {\n    normPrivateKeyToScalar: toPriv,\n    isValidPrivateKey: (key) => { try {\n        return !!toPriv(key);\n    }\n    catch (e) {\n        return false;\n    } },\n    randomPrivateKey: () => hashToPrivateKey(etc.randomBytes(fLen + 16)), // FIPS 186 B.4.1.\n    precompute: (w = 8, p = G) => { p.multiply(3n); w; return p; }, // no-op\n};\nObject.defineProperties(etc, { hmacSha256Sync: {\n        configurable: false, get() { return _hmacSync; }, set(f) { if (!_hmacSync)\n            _hmacSync = f; },\n    } });\nconst W = 8; // Precomputes-related code. W = window size\nconst precompute = () => {\n    const points = []; // 10x sign(), 2x verify(). To achieve this,\n    const windows = 256 / W + 1; // app needs to spend 40ms+ to calculate\n    let p = G, b = p; // a lot of points related to base point G.\n    for (let w = 0; w < windows; w++) { // Points are stored in array and used\n        b = p; // any time Gx multiplication is done.\n        points.push(b); // They consume 16-32 MiB of RAM.\n        for (let i = 1; i < 2 ** (W - 1); i++) {\n            b = b.add(p);\n            points.push(b);\n        }\n        p = b.double(); // Precomputes don't speed-up getSharedKey,\n    } // which multiplies user point by scalar,\n    return points; // when precomputes are using base point\n};\nlet Gpows = undefined; // precomputes for base point G\nconst wNAF = (n) => {\n    // Compared to other point mult methods,\n    const comp = Gpows || (Gpows = precompute()); // stores 2x less points using subtraction\n    const neg = (cnd, p) => { let n = p.negate(); return cnd ? n : p; }; // negate\n    let p = I, f = G; // f must be G, or could become I in the end\n    const windows = 1 + 256 / W; // W=8 17 windows\n    const wsize = 2 ** (W - 1); // W=8 128 window size\n    const mask = BigInt(2 ** W - 1); // W=8 will create mask 0b11111111\n    const maxNum = 2 ** W; // W=8 256\n    const shiftBy = BigInt(W); // W=8 8\n    for (let w = 0; w < windows; w++) {\n        const off = w * wsize;\n        let wbits = Number(n & mask); // extract W bits.\n        n >>= shiftBy; // shift number by W bits.\n        if (wbits > wsize) {\n            wbits -= maxNum;\n            n += 1n;\n        } // split if bits > max: +224 => 256-32\n        const off1 = off, off2 = off + Math.abs(wbits) - 1; // offsets, evaluate both\n        const cnd1 = w % 2 !== 0, cnd2 = wbits < 0; // conditions, evaluate both\n        if (wbits === 0) {\n            f = f.add(neg(cnd1, comp[off1])); // bits are 0: add garbage to fake point\n        }\n        else { //          ^ can't add off2, off2 = I\n            p = p.add(neg(cnd2, comp[off2])); // bits are 1: add to result point\n        }\n    }\n    return { p, f }; // return both real and fake points for JIT\n}; // !! you can disable precomputes by commenting-out call of the wNAF() inside Point#mul()\nexport { getPublicKey, sign, signAsync, verify, CURVE, // Remove the export to easily use in REPL\ngetSharedSecret, etc, utils, Point as ProjectivePoint, Signature }; // envs like browser console\n",
  "vendor/sha256-pure.js": "/**\n * Pure-JS SHA-256 — public domain implementation.\n * Used as a fallback when crypto.subtle is unavailable (plain HTTP).\n *\n * Input: Uint8Array\n * Output: Uint8Array (32 bytes)\n *\n * Adapted from the well-known compact SHA-256 reference (FIPS 180-4).\n */\n\nexport function sha256 (bytes) {\n  // Initial hash values (FIPS 180-4 §5.3.3)\n  const H = new Uint32Array([\n    0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,\n    0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19\n  ])\n\n  // Round constants (FIPS 180-4 §4.2.2)\n  const K = new Uint32Array([\n    0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n    0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n    0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n    0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n    0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n    0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n    0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n    0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n  ])\n\n  // 1. Pad the message (FIPS 180-4 §5.1.1): append 0x80, zero-pad, append 64-bit BE length.\n  const bitLen = bytes.length * 8\n  // k such that (L + 1 + k) ≡ 448 (mod 512) where L = bytes.length * 8\n  const padded = new Uint8Array(Math.ceil((bytes.length + 9) / 64) * 64)\n  padded.set(bytes, 0)\n  padded[bytes.length] = 0x80\n  // 64-bit BE length in the last 8 bytes\n  const dv = new DataView(padded.buffer)\n  // JS numbers can't hold 64 bits exactly for big inputs, but for our\n  // sub-4GB inputs we can set hi=0 and lo=bitLen directly.\n  dv.setUint32(padded.length - 8, Math.floor(bitLen / 0x100000000), false)\n  dv.setUint32(padded.length - 4, bitLen >>> 0, false)\n\n  // 2. Process each 512-bit (64-byte) chunk.\n  const W = new Uint32Array(64)\n  for (let chunk = 0; chunk < padded.length; chunk += 64) {\n    for (let i = 0; i < 16; i++) {\n      W[i] = dv.getUint32(chunk + i * 4, false)\n    }\n    for (let i = 16; i < 64; i++) {\n      const s0 = rotr(W[i - 15], 7) ^ rotr(W[i - 15], 18) ^ (W[i - 15] >>> 3)\n      const s1 = rotr(W[i - 2], 17) ^ rotr(W[i - 2], 19) ^ (W[i - 2] >>> 10)\n      W[i] = (W[i - 16] + s0 + W[i - 7] + s1) >>> 0\n    }\n\n    let a = H[0], b = H[1], c = H[2], d = H[3]\n    let e = H[4], f = H[5], g = H[6], h = H[7]\n\n    for (let i = 0; i < 64; i++) {\n      const S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)\n      const ch = (e & f) ^ (~e & g)\n      const t1 = (h + S1 + ch + K[i] + W[i]) >>> 0\n      const S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)\n      const maj = (a & b) ^ (a & c) ^ (b & c)\n      const t2 = (S0 + maj) >>> 0\n\n      h = g\n      g = f\n      f = e\n      e = (d + t1) >>> 0\n      d = c\n      c = b\n      b = a\n      a = (t1 + t2) >>> 0\n    }\n\n    H[0] = (H[0] + a) >>> 0\n    H[1] = (H[1] + b) >>> 0\n    H[2] = (H[2] + c) >>> 0\n    H[3] = (H[3] + d) >>> 0\n    H[4] = (H[4] + e) >>> 0\n    H[5] = (H[5] + f) >>> 0\n    H[6] = (H[6] + g) >>> 0\n    H[7] = (H[7] + h) >>> 0\n  }\n\n  // 3. Emit 32-byte big-endian digest.\n  const out = new Uint8Array(32)\n  const outDv = new DataView(out.buffer)\n  for (let i = 0; i < 8; i++) outDv.setUint32(i * 4, H[i], false)\n  return out\n}\n\nfunction rotr (x, n) {\n  return ((x >>> n) | (x << (32 - n))) >>> 0\n}\n"
}
/**
 * Tree — content-addressable directory hashing for hyper-overlay
 *
 * A tree is a canonical serialization of a directory's immediate entries.
 * Each entry is one of: file, subdirectory, symlink. The tree's identity
 * is blake2b-256 of its canonical bytes.
 *
 * Format (P.10 Phase 0.5a):
 *
 *   tree := "pgh-tree-1\n" ||
 *           varint(n_entries) ||
 *           entry[0] || ... || entry[n-1]
 *
 *   entry := u8(kind)  ||           // 0=file, 1=dir, 2=symlink
 *            u8(exec)  ||           // 0 or 1; always 0 for dir/symlink
 *            varint(name_len) || name ||  // UTF-8 NFC, no NUL, no "/"
 *            32_bytes(child_hash)
 *
 *   tree_hash := blake2b-256(tree_bytes)
 *
 * Identity fields (in the hash): kind, exec-bit, name, child_hash.
 * Explicitly excluded: mtime, size, uid/gid, full mode.
 *
 * Entries MUST be sorted byte-wise by name (after NFC normalization).
 * Encoders emit sorted; decoders reject unsorted trees.
 *
 * Symlinks: child_hash = blake2b-256 of the target path bytes (not followed).
 * Empty directories: zero-entry tree, valid, deterministic.
 */

import fs from '#fs'
import path from '#path'
import crypto from 'hypercore-crypto'
import c from 'compact-encoding'

// ── Constants ─────────────────────────────────────────────────

export const MAGIC = Buffer.from('pgh-tree-1\n', 'utf8')
export const KIND_FILE = 0
export const KIND_DIR = 1
export const KIND_SYMLINK = 2

// Windows reserved device names (case-insensitive, with or without extension)
const WINDOWS_RESERVED = new Set([
  'CON', 'PRN', 'AUX', 'NUL',
  'COM1', 'COM2', 'COM3', 'COM4', 'COM5', 'COM6', 'COM7', 'COM8', 'COM9',
  'LPT1', 'LPT2', 'LPT3', 'LPT4', 'LPT5', 'LPT6', 'LPT7', 'LPT8', 'LPT9'
])

// Chars forbidden in filenames on Windows (beyond format-layer rules)
// eslint-disable-next-line no-control-regex
const WINDOWS_FORBIDDEN = /[\\:*?"<>|\x00-\x1f]/

// Default skip list for walkTree — minimal, just obvious platform cruft.
// Consumers that want more (e.g. .git for pgh publish) pass their own.
export const DEFAULT_SKIP = new Set(['.DS_Store', 'Thumbs.db'])

// ── Name validation (format layer) ────────────────────────────

/**
 * Normalize a filename for hashing and validate format-layer rules.
 * Throws on unrepresentable names. Returns the canonical form.
 *
 * @param {string} name - single path component (no "/")
 * @returns {string} NFC-normalized name
 */
export function normalizeName (name) {
  if (typeof name !== 'string') {
    throw new Error('tree entry name must be string, got ' + typeof name)
  }
  if (name.length === 0) {
    throw new Error('tree entry name cannot be empty')
  }
  if (name === '.' || name === '..') {
    throw new Error('tree entry name cannot be "." or ".."')
  }
  if (name.indexOf('/') !== -1) {
    throw new Error('tree entry name cannot contain "/": ' + JSON.stringify(name))
  }
  if (name.indexOf('\x00') !== -1) {
    throw new Error('tree entry name cannot contain NUL: ' + JSON.stringify(name))
  }

  const normalized = name.normalize('NFC')

  // Verify the normalized form is valid UTF-8 that round-trips through
  // Buffer (catches lone surrogates and other malformed sequences).
  const asBytes = Buffer.from(normalized, 'utf8')
  if (asBytes.toString('utf8') !== normalized) {
    throw new Error('tree entry name is not valid UTF-8: ' + JSON.stringify(name))
  }

  return normalized
}

// ── Consumer-policy layer ─────────────────────────────────────

/**
 * Check a name against Windows compatibility rules.
 * Does NOT throw — returns a reason string (or null if the name is OK).
 * Used by pgh publish for strict cross-platform validation.
 *
 * @param {string} name
 * @returns {string|null} reason if incompatible, null if OK
 */
export function windowsIncompatibleReason (name) {
  if (WINDOWS_FORBIDDEN.test(name)) {
    return 'contains Windows-forbidden character (\\:*?"<>| or control code)'
  }
  const trimmed = name.replace(/\.+$/, '').replace(/ +$/, '')
  if (trimmed !== name) {
    return 'trailing "." or space (Windows strips these silently)'
  }
  // Reserved device names apply with any extension: AUX.log, PRN.txt etc.
  const base = name.split('.')[0].toUpperCase()
  if (WINDOWS_RESERVED.has(base)) {
    return `"${base}" is a reserved Windows device name (even with extension)`
  }
  return null
}

// ── Canonical encoding ────────────────────────────────────────

/**
 * Encode a single entry to its canonical byte representation.
 *
 * @param {object} state - compact-encoding state
 * @param {{kind: number, exec: number, name: string, childHash: Buffer|string}} e
 */
function encodeEntry (state, e) {
  if (e.kind !== KIND_FILE && e.kind !== KIND_DIR && e.kind !== KIND_SYMLINK) {
    throw new Error('invalid entry kind: ' + e.kind)
  }
  if (e.exec !== 0 && e.exec !== 1) {
    throw new Error('entry exec must be 0 or 1')
  }
  if (e.kind !== KIND_FILE && e.exec !== 0) {
    throw new Error('non-file entry must have exec=0')
  }

  const hash = toBuffer32(e.childHash)

  c.uint8.encode(state, e.kind)
  c.uint8.encode(state, e.exec)
  c.string.encode(state, e.name) // compact-encoding: varint len + utf8 bytes
  state.buffer.set(hash, state.start)
  state.start += 32
}

function preencodeEntry (state, e) {
  c.uint8.preencode(state, e.kind)
  c.uint8.preencode(state, e.exec)
  c.string.preencode(state, e.name)
  state.end += 32
}

/**
 * Serialize a list of entries to canonical tree bytes.
 * Entries are sorted + normalized as a side-effect of the call.
 *
 * @param {Array<{kind: number, exec: number, name: string, childHash: Buffer|string}>} entries
 * @returns {Buffer}
 */
export function encodeTree (entries) {
  const normalized = entries.map(e => ({
    kind: e.kind,
    exec: e.exec || 0,
    name: normalizeName(e.name),
    childHash: e.childHash
  }))
  normalized.sort(compareEntries)

  // Sanity: no duplicate names after normalization
  for (let i = 1; i < normalized.length; i++) {
    if (normalized[i].name === normalized[i - 1].name) {
      throw new Error('duplicate entry name after NFC normalization: ' + normalized[i].name)
    }
  }

  const state = { start: 0, end: 0, buffer: null }
  state.end += MAGIC.length
  c.uint.preencode(state, normalized.length)
  for (const e of normalized) preencodeEntry(state, e)

  state.buffer = Buffer.alloc(state.end)

  state.buffer.set(MAGIC, state.start)
  state.start += MAGIC.length
  c.uint.encode(state, normalized.length)
  for (const e of normalized) encodeEntry(state, e)

  return state.buffer
}

/**
 * Byte-wise comparator for entry names (after NFC normalization).
 */
function compareEntries (a, b) {
  const ab = Buffer.from(a.name, 'utf8')
  const bb = Buffer.from(b.name, 'utf8')
  return Buffer.compare(ab, bb)
}

/**
 * Decode canonical tree bytes back to an entries list.
 * Rejects unsorted or malformed trees.
 *
 * @param {Buffer} buf
 * @returns {Array<{kind: number, exec: number, name: string, childHash: string}>}
 */
export function decodeTree (buf) {
  if (!Buffer.isBuffer(buf)) throw new Error('decodeTree expects a Buffer')
  if (buf.length < MAGIC.length) throw new Error('tree too short')
  if (buf.compare(MAGIC, 0, MAGIC.length, 0, MAGIC.length) !== 0) {
    throw new Error('tree magic mismatch (expected "pgh-tree-1")')
  }

  const state = { start: MAGIC.length, end: buf.length, buffer: buf }
  const count = c.uint.decode(state)
  const entries = []

  let prevName = null
  for (let i = 0; i < count; i++) {
    const kind = c.uint8.decode(state)
    const exec = c.uint8.decode(state)
    const name = c.string.decode(state)

    if (state.start + 32 > state.end) throw new Error('truncated tree: missing hash bytes')
    const childHash = buf.subarray(state.start, state.start + 32).toString('hex')
    state.start += 32

    // Validate format rules on read — reject invalid trees rather than silently accept
    const normalized = normalizeName(name)
    if (normalized !== name) {
      throw new Error('tree entry name not NFC-normalized: ' + JSON.stringify(name))
    }
    if (kind !== KIND_FILE && exec !== 0) {
      throw new Error('non-file entry with exec=1 is invalid')
    }
    if (prevName !== null) {
      const cmp = Buffer.compare(Buffer.from(prevName, 'utf8'), Buffer.from(name, 'utf8'))
      if (cmp === 0) throw new Error('tree has duplicate entry: ' + name)
      if (cmp > 0) throw new Error('tree entries not sorted: ' + prevName + ' before ' + name)
    }
    prevName = name

    entries.push({ kind, exec, name, childHash })
  }

  if (state.start !== state.end) throw new Error('tree has trailing bytes after entries')

  return entries
}

/**
 * Compute the tree hash of an entries list.
 *
 * @param {Array<{kind: number, exec: number, name: string, childHash: Buffer|string}>} entries
 * @returns {string} hex-encoded blake2b-256
 */
export function computeTreeHash (entries) {
  const buf = encodeTree(entries)
  return crypto.data(buf).toString('hex')
}

// ── Helpers ───────────────────────────────────────────────────

function toBuffer32 (hashOrBuf) {
  if (Buffer.isBuffer(hashOrBuf)) {
    if (hashOrBuf.length !== 32) throw new Error('childHash buffer must be 32 bytes')
    return hashOrBuf
  }
  if (typeof hashOrBuf !== 'string') {
    throw new Error('childHash must be Buffer or hex string')
  }
  if (hashOrBuf.length !== 64) throw new Error('childHash hex string must be 64 chars')
  return Buffer.from(hashOrBuf, 'hex')
}

// ── Filesystem walk ───────────────────────────────────────────

/**
 * Walk a directory recursively, producing tree hashes bottom-up.
 *
 * Returns a nested object keyed by path, where each entry has:
 *   { hash: hex, entries: [{kind, exec, name, childHash, size?}] }
 *
 * File entries carry their content hash as childHash (blake2b of bytes).
 * Dir entries carry the subtree hash.
 * Symlink entries carry blake2b of the link target bytes.
 *
 * @param {string} rootDir - absolute path to scan
 * @param {object} [opts]
 * @param {Set<string>} [opts.skip] - basenames to skip (default: DEFAULT_SKIP)
 * @param {(relPath: string, baseName: string) => boolean} [opts.matcher]
 *   Optional gitignore-style matcher. Returns true to EXCLUDE an entry.
 *   Receives the path relative to rootDir plus the basename. Applies to
 *   all kinds (file/dir/symlink). Used by `pgh publish` for publishIgnore.
 * @returns {Map<string, {hash: string, entries: Array, size: number}>}
 *          map keyed by relative path ('' = root); root tree is at key ''
 */
export function walkTree (rootDir, opts = {}) {
  const skip = opts.skip || DEFAULT_SKIP
  const matcher = opts.matcher || null
  const trees = new Map()

  function visit (relPath) {
    const absPath = relPath === '' ? rootDir : path.join(rootDir, relPath)
    const raw = fs.readdirSync(absPath)
    const entries = []
    let totalSize = 0

    for (const name of raw) {
      if (skip.has(name)) continue

      const entryAbs = path.join(absPath, name)
      const entryRel = relPath === '' ? name : relPath + '/' + name

      if (matcher && matcher(entryRel, name)) continue

      let stat
      try {
        stat = fs.lstatSync(entryAbs)
      } catch {
        continue
      }

      if (stat.isSymbolicLink()) {
        const target = fs.readlinkSync(entryAbs)
        const targetBytes = Buffer.from(target, 'utf8')
        const childHash = crypto.data(targetBytes).toString('hex')
        entries.push({
          kind: KIND_SYMLINK,
          exec: 0,
          name: normalizeName(name),
          childHash,
          size: targetBytes.length,
          linkTarget: target
        })
        totalSize += targetBytes.length
      } else if (stat.isDirectory()) {
        visit(entryRel)
        const sub = trees.get(entryRel)
        if (!sub) continue
        entries.push({
          kind: KIND_DIR,
          exec: 0,
          name: normalizeName(name),
          childHash: sub.hash,
          size: sub.size
        })
        totalSize += sub.size
      } else if (stat.isFile()) {
        const content = fs.readFileSync(entryAbs)
        const childHash = crypto.data(content).toString('hex')
        // Executable bit from stat.mode — works on POSIX; Windows always 0
        const exec = (stat.mode & 0o100) ? 1 : 0
        entries.push({
          kind: KIND_FILE,
          exec,
          name: normalizeName(name),
          childHash,
          size: stat.size
        })
        totalSize += stat.size
      }
      // device files, sockets, fifos: silently skipped (unrepresentable)
    }

    entries.sort(compareEntries)
    const hash = computeTreeHash(entries)
    trees.set(relPath, { hash, entries, size: totalSize })
  }

  visit('')
  return trees
}

// ── Publish-time validation (consumer policy) ─────────────────

/**
 * Scan entries (recursively via walkTree output) for cross-platform-hostile
 * names. Returns an array of {path, name, reason} for every problem found.
 * Does NOT throw — caller decides how to present.
 *
 * @param {Map<string, {hash: string, entries: Array}>} trees - from walkTree
 * @returns {Array<{path: string, name: string, reason: string}>}
 */
export function validateForPublish (trees) {
  const problems = []
  for (const [relPath, tree] of trees) {
    for (const e of tree.entries) {
      const reason = windowsIncompatibleReason(e.name)
      if (reason) {
        problems.push({
          path: relPath ? relPath + '/' + e.name : e.name,
          name: e.name,
          reason
        })
      }
    }
  }
  return problems
}
function isBuffer(value) {
  return Buffer.isBuffer(value) || value instanceof Uint8Array
}

function isEncoding(encoding) {
  return Buffer.isEncoding(encoding)
}

function alloc(size, fill, encoding) {
  return Buffer.alloc(size, fill, encoding)
}

function allocUnsafe(size) {
  return Buffer.allocUnsafe(size)
}

function allocUnsafeSlow(size) {
  return Buffer.allocUnsafeSlow(size)
}

function byteLength(string, encoding) {
  return Buffer.byteLength(string, encoding)
}

function compare(a, b) {
  return Buffer.compare(a, b)
}

function concat(buffers, totalLength) {
  return Buffer.concat(buffers, totalLength)
}

function copy(source, target, targetStart, start, end) {
  return toBuffer(source).copy(target, targetStart, start, end)
}

function equals(a, b) {
  return toBuffer(a).equals(b)
}

function fill(buffer, value, offset, end, encoding) {
  return toBuffer(buffer).fill(value, offset, end, encoding)
}

function from(value, encodingOrOffset, length) {
  return Buffer.from(value, encodingOrOffset, length)
}

function includes(buffer, value, byteOffset, encoding) {
  return toBuffer(buffer).includes(value, byteOffset, encoding)
}

function indexOf(buffer, value, byfeOffset, encoding) {
  return toBuffer(buffer).indexOf(value, byfeOffset, encoding)
}

function lastIndexOf(buffer, value, byteOffset, encoding) {
  return toBuffer(buffer).lastIndexOf(value, byteOffset, encoding)
}

function swap16(buffer) {
  return toBuffer(buffer).swap16()
}

function swap32(buffer) {
  return toBuffer(buffer).swap32()
}

function swap64(buffer) {
  return toBuffer(buffer).swap64()
}

function toBuffer(buffer) {
  if (Buffer.isBuffer(buffer)) return buffer
  return Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

function toString(buffer, encoding, start, end) {
  return toBuffer(buffer).toString(encoding, start, end)
}

function write(buffer, string, offset, length, encoding) {
  return toBuffer(buffer).write(string, offset, length, encoding)
}

function readDoubleBE(buffer, offset) {
  return toBuffer(buffer).readDoubleBE(offset)
}

function readDoubleLE(buffer, offset) {
  return toBuffer(buffer).readDoubleLE(offset)
}

function readFloatBE(buffer, offset) {
  return toBuffer(buffer).readFloatBE(offset)
}

function readFloatLE(buffer, offset) {
  return toBuffer(buffer).readFloatLE(offset)
}

function readInt32BE(buffer, offset) {
  return toBuffer(buffer).readInt32BE(offset)
}

function readInt32LE(buffer, offset) {
  return toBuffer(buffer).readInt32LE(offset)
}

function readUInt32BE(buffer, offset) {
  return toBuffer(buffer).readUInt32BE(offset)
}

function readUInt32LE(buffer, offset) {
  return toBuffer(buffer).readUInt32LE(offset)
}

function writeDoubleBE(buffer, value, offset) {
  return toBuffer(buffer).writeDoubleBE(value, offset)
}

function writeDoubleLE(buffer, value, offset) {
  return toBuffer(buffer).writeDoubleLE(value, offset)
}

function writeFloatBE(buffer, value, offset) {
  return toBuffer(buffer).writeFloatBE(value, offset)
}

function writeFloatLE(buffer, value, offset) {
  return toBuffer(buffer).writeFloatLE(value, offset)
}

function writeInt32BE(buffer, value, offset) {
  return toBuffer(buffer).writeInt32BE(value, offset)
}

function writeInt32LE(buffer, value, offset) {
  return toBuffer(buffer).writeInt32LE(value, offset)
}

function writeUInt32BE(buffer, value, offset) {
  return toBuffer(buffer).writeUInt32BE(value, offset)
}

function writeUInt32LE(buffer, value, offset) {
  return toBuffer(buffer).writeUInt32LE(value, offset)
}

module.exports = {
  isBuffer,
  isEncoding,
  alloc,
  allocUnsafe,
  allocUnsafeSlow,
  byteLength,
  compare,
  concat,
  copy,
  equals,
  fill,
  from,
  includes,
  indexOf,
  lastIndexOf,
  swap16,
  swap32,
  swap64,
  toBuffer,
  toString,
  write,
  readDoubleBE,
  readDoubleLE,
  readFloatBE,
  readFloatLE,
  readInt32BE,
  readInt32LE,
  readUInt32BE,
  readUInt32LE,
  writeDoubleBE,
  writeDoubleLE,
  writeFloatBE,
  writeFloatLE,
  writeInt32BE,
  writeInt32LE,
  writeUInt32BE,
  writeUInt32LE
}
{
  "name": "b4a",
  "version": "1.8.1",
  "description": "Bridging the gap between buffers and typed arrays",
  "exports": {
    "./package": "./package.json",
    ".": {
      "react-native": "./react-native.js",
      "browser": "./browser.js",
      "default": "./index.js"
    }
  },
  "files": [
    "browser.js",
    "index.js",
    "react-native.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:bare && npm run test:node",
    "test:bare": "brittle-bare --coverage test.mjs",
    "test:node": "brittle-node --coverage test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/b4a.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/b4a/issues"
  },
  "homepage": "https://github.com/holepunchto/b4a#readme",
  "devDependencies": {
    "brittle": "^3.5.2",
    "lunte": "^1.7.0",
    "nanobench": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "react-native-b4a": "*"
  },
  "peerDependenciesMeta": {
    "react-native-b4a": {
      "optional": true
    }
  }
}
const ESC = '\x1b'
const CSI = ESC + '['
const SGR = (n) => CSI + n + 'm'

exports.constants = {
  ESC,
  CSI,
  SGR
}

// https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_(Control_Sequence_Introducer)_sequences

exports.cursorHide = CSI + '?25l'
exports.cursorShow = CSI + '?25h'

exports.cursorUp = function cursorUp(n = 1) {
  return CSI + n + 'A'
}

exports.cursorDown = function cursorDown(n = 1) {
  return CSI + n + 'B'
}

exports.cursorForward = function cursorForward(n = 1) {
  return CSI + n + 'C'
}

exports.cursorBack = function cursorBack(n = 1) {
  return CSI + n + 'D'
}

exports.cursorNextLine = function cursorNextLine(n = 1) {
  return CSI + n + 'E'
}

exports.cursorPreviousLine = function cursorPreviousLine(n = 1) {
  return CSI + n + 'F'
}

exports.cursorPosition = function cursorPosition(column, row = 0) {
  if (row === 0) return CSI + (column + 1) + 'G'

  return CSI + (row + 1) + ';' + (column + 1) + 'H'
}

exports.eraseDisplayEnd = CSI + 'J'
exports.eraseDisplayStart = CSI + '1J'
exports.eraseDisplay = CSI + '2J'
exports.eraseLineEnd = CSI + 'K'
exports.eraseLineStart = CSI + '1K'
exports.eraseLine = CSI + '2K'

exports.scrollUp = function scrollUp(n = 1) {
  return CSI + n + 'S'
}

exports.scrollDown = function scrollDown(n = 1) {
  return CSI + n + 'T'
}

// https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_(Select_Graphic_Rendition)_parameters

exports.modifierReset = SGR(0)
exports.modifierBold = SGR(1)
exports.modifierDim = SGR(2)
exports.modifierItalic = SGR(3)
exports.modifierUnderline = SGR(4)
exports.modifierNormal = SGR(22)
exports.modifierNotItalic = SGR(23)
exports.modifierNotUnderline = SGR(24)

// https://en.wikipedia.org/wiki/ANSI_escape_code#Colors

exports.colorBlack = SGR(30)
exports.colorRed = SGR(31)
exports.colorGreen = SGR(32)
exports.colorYellow = SGR(33)
exports.colorBlue = SGR(34)
exports.colorMagenta = SGR(35)
exports.colorCyan = SGR(36)
exports.colorWhite = SGR(37)
exports.colorDefault = SGR(39)
exports.colorBrightBlack = SGR(90)
exports.colorBrightRed = SGR(91)
exports.colorBrightGreen = SGR(92)
exports.colorBrightYellow = SGR(93)
exports.colorBrightBlue = SGR(94)
exports.colorBrightMagenta = SGR(95)
exports.colorBrightCyan = SGR(96)
exports.colorBrightWhite = SGR(97)
{
  "name": "bare-ansi-escapes",
  "version": "2.2.3",
  "description": "Parse and produce ANSI escape sequences",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./key-decoder": {
      "types": "./key-decoder.d.ts",
      "default": "./key-decoder.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "key-decoder.js",
    "key-decoder.d.ts"
  ],
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-ansi-escapes.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-ansi-escapes/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-ansi-escapes#readme",
  "dependencies": {
    "bare-stream": "^2.6.5"
  },
  "devDependencies": {
    "bare-buffer": "^3.0.2",
    "brittle": "^3.3.2",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  },
  "peerDependencies": {
    "bare-buffer": "*"
  },
  "peerDependenciesMeta": {
    "bare-buffer": {
      "optional": true
    }
  }
}
const inspect = require('bare-inspect')

class AssertionError extends Error {
  constructor(opts = {}) {
    let { message = null, actual, expected, operator } = opts

    if (message === null) {
      message = `${inspect(actual)} ${operator} ${inspect(expected)}`
    }

    super(message)

    this.actual = actual
    this.expected = expected
    this.operator = operator
  }

  get name() {
    return 'AssertionError'
  }

  get code() {
    'ASSERTION'
  }
}

function assertFail(opts, fn) {
  if (opts.message instanceof Error) throw opts.message

  const err = new AssertionError(opts)

  if (Error.captureStackTrace) Error.captureStackTrace(err, fn)

  throw err
}

module.exports = exports = function assert(actual, message) {
  if (actual) return

  assertFail({ message, actual, expected: true, operator: '==' }, assert)
}

exports.AssertionError = AssertionError

exports.fail = function fail(message) {
  if (message === undefined) message = 'Failed'

  assertFail({ message, operator: 'fail' }, fail)
}

exports.ok = function ok(actual, message) {
  if (actual) return

  assertFail({ message, actual, expected: true, operator: '==' }, ok)
}

exports.notOk = function ok(actual, message) {
  if (!actual) return

  assertFail({ message, actual, expected: false, operator: '==' }, ok)
}

exports.equal = function equal(actual, expected, message) {
  if (actual == expected || (actual !== actual && expected !== expected)) {
    return
  }

  assertFail({ message, actual, expected, operator: '==' }, equal)
}

exports.notEqual = function notEqual(actual, expected, message) {
  if (actual != expected && (actual === actual || expected === expected)) {
    return
  }

  assertFail({ message, actual, expected, operator: '!=' }, notEqual)
}

exports.strictEqual = function strictEqual(actual, expected, message) {
  if (Object.is(actual, expected)) return

  assertFail(
    { message, actual, expected, operator: 'strictEqual' },
    strictEqual
  )
}

exports.notStrictEqual = function notStrictEqual(actual, expected, message) {
  if (!Object.is(actual, expected)) return

  assertFail(
    { message, actual, expected, operator: 'notStrictEqual' },
    notStrictEqual
  )
}
{
  "name": "bare-assert",
  "version": "1.2.0",
  "description": "Assertion library for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts"
  ],
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-assert.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-assert/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-assert#readme",
  "dependencies": {
    "bare-inspect": "^3.1.2"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  }
}
const errors = require('./lib/errors')

class EventListener {
  constructor() {
    this.list = []
    this.count = 0
  }

  append(ctx, name, fn, once) {
    this.count++
    ctx.emit('newListener', name, fn) // Emit BEFORE adding
    this.list.push([fn, once])
  }

  prepend(ctx, name, fn, once) {
    this.count++
    ctx.emit('newListener', name, fn) // Emit BEFORE adding
    this.list.unshift([fn, once])
  }

  remove(ctx, name, fn) {
    for (let i = 0, n = this.list.length; i < n; i++) {
      const l = this.list[i]

      if (l[0] === fn) {
        this.list.splice(i, 1)

        if (this.count === 1) delete ctx._events[name]

        ctx.emit('removeListener', name, fn) // Emit AFTER removing

        this.count--
        return
      }
    }
  }

  removeAll(ctx, name) {
    const list = [...this.list]
    this.list = []

    if (this.count === list.length) delete ctx._events[name]

    for (let i = list.length - 1; i >= 0; i--) {
      ctx.emit('removeListener', name, list[i][0]) // Emit AFTER removing
    }

    this.count -= list.length
  }

  emit(ctx, name, ...args) {
    const list = [...this.list]

    for (let i = 0, n = list.length; i < n; i++) {
      const l = list[i]

      if (l[1] === true) this.remove(ctx, name, l[0])

      Reflect.apply(l[0], ctx, args)
    }

    return list.length > 0
  }
}

function appendListener(ctx, name, fn, once) {
  if (ctx._events === undefined) ctx._events = Object.create(null)
  const e = ctx._events[name] || (ctx._events[name] = new EventListener())
  e.append(ctx, name, fn, once)
  return ctx
}

function prependListener(ctx, name, fn, once) {
  if (ctx._events === undefined) ctx._events = Object.create(null)
  const e = ctx._events[name] || (ctx._events[name] = new EventListener())
  e.prepend(ctx, name, fn, once)
  return ctx
}

function removeListener(ctx, name, fn) {
  if (ctx._events === undefined) return ctx
  const e = ctx._events[name]
  if (e !== undefined) e.remove(ctx, name, fn)
  return ctx
}

function throwUnhandledError(...args) {
  let err

  if (args.length > 0) err = args[0]

  if (err instanceof Error === false) err = errors.UNHANDLED_ERROR(err)

  if (Error.captureStackTrace) {
    Error.captureStackTrace(err, exports.prototype.emit)
  }

  queueMicrotask(() => {
    throw err
  })
}

module.exports = exports = class EventEmitter {
  constructor() {
    this._events = Object.create(null)
  }

  addListener(name, fn) {
    return appendListener(this, name, fn, false)
  }

  addOnceListener(name, fn) {
    return appendListener(this, name, fn, true)
  }

  prependListener(name, fn) {
    return prependListener(this, name, fn, false)
  }

  prependOnceListener(name, fn) {
    return prependListener(this, name, fn, true)
  }

  removeListener(name, fn) {
    return removeListener(this, name, fn)
  }

  on(name, fn) {
    return appendListener(this, name, fn, false)
  }

  once(name, fn) {
    return appendListener(this, name, fn, true)
  }

  off(name, fn) {
    return removeListener(this, name, fn)
  }

  emit(name, ...args) {
    if (name === 'error' && this._events !== undefined && this._events.error === undefined) {
      throwUnhandledError(...args)
    }

    if (this._events === undefined) return false
    const e = this._events[name]
    return e === undefined ? false : e.emit(this, name, ...args)
  }

  listeners(name) {
    if (this._events === undefined) return []
    const e = this._events[name]
    return e === undefined ? [] : [...e.list]
  }

  rawListeners(name) {
    if (this._events === undefined) return []
    const e = this._events[name]
    return e === undefined ? [] : e.list.map((l) => l[0])
  }

  eventNames() {
    if (this._events === undefined) return []
    return Reflect.ownKeys(this._events)
  }

  listenerCount(name) {
    if (this._events === undefined) return 0
    const e = this._events[name]
    return e === undefined ? 0 : e.list.length
  }

  getMaxListeners() {
    return EventEmitter.defaultMaxListeners
  }

  setMaxListeners(n) {}

  removeAllListeners(name) {
    if (arguments.length === 0) {
      for (const key of Reflect.ownKeys(this._events)) {
        if (key === 'removeListener') continue
        this.removeAllListeners(key)
      }
      this.removeAllListeners('removeListener')
    } else {
      const e = this._events[name]
      if (e !== undefined) e.removeAll(this, name)
    }
    return this
  }
}

exports.EventEmitter = exports

exports.errors = errors

exports.defaultMaxListeners = 10

exports.on = function on(emitter, name, opts = {}) {
  const { signal } = opts

  if (signal && signal.aborted) {
    throw errors.OPERATION_ABORTED(signal.reason)
  }

  let error = null
  let done = false

  const events = []
  const promises = []

  if (name !== 'error') emitter.on('error', onerror)

  if (signal) signal.addEventListener('abort', onabort)

  emitter.on(name, onevent)

  return {
    next() {
      if (events.length) {
        return Promise.resolve({ value: events.shift(), done: false })
      }

      if (error) {
        const err = error

        error = null

        return Promise.reject(err)
      }

      if (done) return onclose()

      return new Promise((resolve, reject) => promises.push({ resolve, reject }))
    },

    return() {
      return onclose()
    },

    throw(err) {
      return onerror(err)
    },

    [Symbol.asyncIterator]() {
      return this
    }
  }

  function onevent(...args) {
    if (promises.length) {
      promises.shift().resolve({ value: args, done: false })
    } else {
      events.push(args)
    }
  }

  function onerror(err) {
    emitter.off(name, onevent).off('error', onerror)

    if (promises.length) {
      promises.shift().reject(err)
    } else {
      error = err
    }

    return Promise.resolve({ done: true })
  }

  function onabort() {
    signal.removeEventListener('abort', onabort)

    onerror(errors.OPERATION_ABORTED(signal.reason))
  }

  function onclose() {
    emitter.off(name, onevent)

    if (name !== 'error') emitter.off('error', onerror)

    if (signal) signal.removeEventListener('abort', onabort)

    done = true

    if (promises.length) promises.shift().resolve({ done: true })

    return Promise.resolve({ done: true })
  }
}

exports.once = function once(emitter, name, opts = {}) {
  const { signal } = opts

  if (signal && signal.aborted) {
    return Promise.reject(errors.OPERATION_ABORTED(signal.reason))
  }

  return new Promise((resolve, reject) => {
    if (name !== 'error') emitter.on('error', onerror)

    if (signal) signal.addEventListener('abort', onabort)

    emitter.once(name, onevent)

    function onevent(...args) {
      if (name !== 'error') emitter.off('error', onerror)

      if (signal) signal.removeEventListener('abort', onabort)

      resolve(args)
    }

    function onerror(err) {
      emitter.off(name, onevent)

      if (name !== 'error') emitter.off('error', onerror)

      reject(err)
    }

    function onabort() {
      signal.removeEventListener('abort', onabort)

      onerror(errors.OPERATION_ABORTED(signal.reason))
    }
  })
}

exports.forward = function forward(from, to, names, opts = {}) {
  if (typeof names === 'string') names = [names]

  const { emit = to.emit.bind(to) } = opts

  const listeners = names.map(
    (name) =>
      function onevent(...args) {
        emit(name, ...args)
      }
  )

  to.on('newListener', (name) => {
    const i = names.indexOf(name)

    if (i !== -1 && to.listenerCount(name) === 0) {
      from.on(name, listeners[i])
    }
  }).on('removeListener', (name) => {
    const i = names.indexOf(name)

    if (i !== -1 && to.listenerCount(name) === 0) {
      from.off(name, listeners[i])
    }
  })
}

exports.listenerCount = function listenerCount(emitter, name) {
  return emitter.listenerCount(name)
}

exports.getMaxListeners = function getMaxListeners(emitter) {
  if (typeof emitter.getMaxListeners === 'function') {
    return emitter.getMaxListeners()
  }

  return exports.defaultMaxListeners
}

exports.setMaxListeners = function setMaxListeners(n, ...emitters) {
  if (emitters.length === 0) exports.defaultMaxListeners = n
  else {
    for (const emitter of emitters) {
      if (typeof emitter.setMaxListeners === 'function') {
        emitter.setMaxListeners(n)
      }
    }
  }
}
module.exports = class EventEmitterError extends Error {
  constructor(msg, code, fn = EventEmitterError, opts) {
    super(`${code}: ${msg}`, opts)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'EventEmitterError'
  }

  static OPERATION_ABORTED(cause, msg = 'Operation aborted') {
    return new EventEmitterError(msg, 'OPERATION_ABORTED', EventEmitterError.OPERATION_ABORTED, {
      cause
    })
  }

  static UNHANDLED_ERROR(cause, msg = 'Unhandled error') {
    return new EventEmitterError(msg, 'UNHANDLED_ERROR', EventEmitterError.UNHANDLED_ERROR, {
      cause
    })
  }
}
{
  "name": "bare-events",
  "version": "2.9.1",
  "description": "Event emitters for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    },
    "./web": {
      "types": "./web.d.ts",
      "default": "./web.js"
    },
    "./errors": "./lib/errors.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "global.js",
    "global.d.ts",
    "web.js",
    "web.d.ts",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:bare && npm run test:node",
    "test:bare": "brittle-bare --coverage test.js",
    "test:node": "brittle-node --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-events.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-events/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-events#readme",
  "devDependencies": {
    "bare-abort-controller": "^1.0.0",
    "brittle": "^3.3.2",
    "lunte": "^1.8.0",
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^2.0.0",
    "uncaughts": "^1.1.1"
  },
  "peerDependencies": {
    "bare-abort-controller": "*"
  },
  "peerDependenciesMeta": {
    "bare-abort-controller": {
      "optional": true
    }
  }
}
module.exports = require.addon()
const FIFO = require('fast-fifo')
const EventEmitter = require('bare-events')
const path = require('bare-path')
const { isURL, fileURLToPath } = require('bare-url')
const { Readable, Writable } = require('bare-stream')
const binding = require('./binding')
const constants = require('./lib/constants')
const FileError = require('./lib/errors')

const isWindows = Bare.platform === 'win32'

exports.constants = constants

class FileRequest {
  static borrow() {
    if (this._free.length > 0) return this._free.pop()
    return new FileRequest()
  }

  static return(req) {
    if (this._free.length < 32) this._free.push(req.reset())
    else req.destroy()
  }

  constructor() {
    this._reset()
    this._handle = binding.requestInit(this, this._onresult)
  }

  get handle() {
    return this._handle
  }

  retain(value) {
    this._retain = value // Tie the lifetime of `value` to the lifetime of `this`
  }

  reset() {
    if (this._handle === null) return this

    binding.requestReset(this._handle)

    this._reset()

    return this
  }

  destroy() {
    if (this._handle === null) return this

    binding.requestDestroy(this._handle)

    this._reset()
    this._handle = null

    return this
  }

  then(resolve, reject) {
    return this._promise.then(resolve, reject)
  }

  return() {
    if (this._handle === null) return this

    FileRequest.return(this)

    return this
  }

  _reset() {
    this._promise = new Promise((resolve, reject) => {
      this._resolve = resolve
      this._reject = reject
    })
    this._retain = null
  }

  _onresult(err, status) {
    if (err) this._reject(err)
    else this._resolve(status)
  }
}

FileRequest._free = []

function ok(result, cb) {
  if (typeof result === 'function') {
    cb = result
    result = undefined
  }

  if (cb) cb(null, result)
  else return result
}

function fail(err, cb) {
  if (cb) cb(err)
  else throw err
}

function done(err, result, cb) {
  if (typeof result === 'function') {
    cb = result
    result = undefined
  }

  if (err) fail(err, cb)
  else return ok(result, cb)
}

async function open(filepath, flags = 'r', mode = 0o666, cb) {
  if (typeof flags === 'function') {
    cb = flags
    flags = 'r'
    mode = 0o666
  } else if (typeof mode === 'function') {
    cb = mode
    mode = 0o666
  }

  if (typeof flags === 'string') flags = toFlags(flags)
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let fd
  let err = null
  try {
    binding.open(req.handle, filepath, flags, mode)

    fd = await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'open',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, fd, cb)
}

function openSync(filepath, flags = 'r', mode = 0o666) {
  if (typeof flags === 'string') flags = toFlags(flags)
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    return binding.openSync(req.handle, filepath, flags, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'open',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function close(fd, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.close(req.handle, fd)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'close', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function closeSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.closeSync(req.handle, fd)
  } catch (e) {
    throw new FileError(e.message, { operation: 'close', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function access(filepath, mode = constants.F_OK, cb) {
  if (typeof mode === 'function') {
    cb = mode
    mode = constants.F_OK
  }

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.access(req.handle, filepath, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'access',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function accessSync(filepath, mode = constants.F_OK) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.accessSync(req.handle, filepath, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'access',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function exists(filepath, cb) {
  let ok = true
  try {
    await access(filepath)
  } catch {
    ok = false
  }

  return done(null, ok, cb)
}

function existsSync(filepath) {
  try {
    accessSync(filepath)
  } catch {
    return false
  }

  return true
}

async function read(fd, buffer, offset = 0, len = buffer.byteLength - offset, pos = -1, cb) {
  if (typeof offset === 'function') {
    cb = offset
    offset = 0
    len = buffer.byteLength
    pos = -1
  } else if (typeof len === 'function') {
    cb = len
    len = buffer.byteLength - offset
    pos = -1
  } else if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.read(req.handle, fd, buffer, offset, len, pos)

    req.retain(buffer)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'read', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function readSync(fd, buffer, offset = 0, len = buffer.byteLength - offset, pos = -1) {
  const req = FileRequest.borrow()

  try {
    return binding.readSync(req.handle, fd, buffer, offset, len, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'read', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function readv(fd, buffers, pos = -1, cb) {
  if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.readv(req.handle, fd, buffers, pos)

    req.retain(buffers)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'readv', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function readvSync(fd, buffers, pos = -1) {
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  try {
    return binding.readvSync(req.handle, fd, buffers, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'readv', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function write(fd, data, offset, len, pos = -1, cb) {
  if (typeof data === 'string') {
    let encoding = len
    cb = pos
    pos = offset

    if (typeof pos === 'function') {
      cb = pos
      pos = -1
      encoding = 'utf8'
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = 'utf8'
    }

    if (typeof pos === 'string') {
      encoding = pos
      pos = -1
    }

    data = Buffer.from(data, encoding)
    offset = 0
    len = data.byteLength
  } else if (typeof offset === 'function') {
    cb = offset
    offset = 0
    len = data.byteLength
    pos = -1
  } else if (typeof len === 'function') {
    cb = len
    len = data.byteLength - offset
    pos = -1
  } else if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof offset !== 'number') offset = 0
  if (typeof len !== 'number') len = data.byteLength - offset
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.write(req.handle, fd, data, offset, len, pos)

    req.retain(data)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'write', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function writeSync(fd, data, offset, len, pos = -1) {
  if (typeof data === 'string') {
    let encoding = len
    pos = offset

    if (typeof pos === 'string') {
      encoding = pos
      pos = -1
    }

    data = Buffer.from(data, encoding)
    offset = 0
    len = data.byteLength
  }

  if (typeof offset !== 'number') offset = 0
  if (typeof len !== 'number') len = data.byteLength - offset
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  try {
    return binding.writeSync(req.handle, fd, data, offset, len, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'write', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function writev(fd, buffers, pos = -1, cb) {
  if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.writev(req.handle, fd, buffers, pos)

    req.retain(buffers)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'writev', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function writevSync(fd, buffers, pos = -1) {
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  try {
    return binding.writevSync(req.handle, fd, buffers, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'writev', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function stat(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.stat(req.handle, filepath)

    await req

    st = new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'stat', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function statSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.statSync(req.handle, filepath)

    return new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'stat', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function lstat(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.lstat(req.handle, filepath)

    await req

    st = new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'lstat', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function lstatSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.lstatSync(req.handle, filepath)

    return new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'lstat', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function fstat(fd, cb) {
  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.fstat(req.handle, fd)

    await req

    st = new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'fstat', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function fstatSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.fstatSync(req.handle, fd)

    return new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'fstat', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function statfs(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.statfs(req.handle, filepath)

    await req

    st = new StatFs(...binding.requestResultStatfs(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'statfs', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function statfsSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.statfsSync(req.handle, filepath)

    return new StatFs(...binding.requestResultStatfs(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'statfs', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function ftruncate(fd, len = 0, cb) {
  if (typeof len === 'function') {
    cb = len
    len = 0
  }

  if (typeof len !== 'number') len = 0

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.ftruncate(req.handle, fd, len)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'ftruncate', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function ftruncateSync(fd, len = 0) {
  if (typeof len !== 'number') len = 0

  const req = FileRequest.borrow()

  try {
    binding.ftruncateSync(req.handle, fd, len)
  } catch (e) {
    throw new FileError(e.message, { operation: 'ftruncate', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function truncate(filepath, len, cb) {
  let fd = -1
  let err

  try {
    fd = await open(filepath, 'r+')

    await ftruncate(fd, len)
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) await close(fd)
  }

  return done(err, cb)
}

function truncateSync(filepath, len) {
  let fd = -1
  let err

  try {
    fd = openSync(filepath, 'r+')

    ftruncateSync(fd, len)
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) closeSync(fd)
  }
}

async function chmod(filepath, mode, cb) {
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.chmod(req.handle, filepath, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'chmod',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function chmodSync(filepath, mode) {
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.chmodSync(req.handle, filepath, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'chmod',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function fchmod(fd, mode, cb) {
  if (typeof mode === 'string') mode = toMode(mode)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fchmod(req.handle, fd, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fchmod', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fchmodSync(fd, mode) {
  if (typeof mode === 'string') mode = toMode(mode)

  const req = FileRequest.borrow()

  try {
    binding.fchmodSync(req.handle, fd, mode)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fchmod', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function chown(filepath, uid, gid, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.chown(req.handle, filepath, uid, gid)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'chown', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function chownSync(filepath, uid, gid) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.chownSync(req.handle, filepath, uid, gid)
  } catch (e) {
    throw new FileError(e.message, { operation: 'chownSync', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function lchown(filepath, uid, gid, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.lchown(req.handle, filepath, uid, gid)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'lchown', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function lchownSync(filepath, uid, gid) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.lchownSync(req.handle, filepath, uid, gid)
  } catch (e) {
    throw new FileError(e.message, { operation: 'lchownSync', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function fchown(fd, uid, gid, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fchown(req.handle, fd, uid, gid)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fchown', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fchownSync(fd, uid, gid) {
  const req = FileRequest.borrow()

  try {
    binding.fchownSync(req.handle, fd, uid, gid)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fchownSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function utimes(filepath, atime, mtime, cb) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.utimes(req.handle, filepath, atime, mtime)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'utimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function utimesSync(filepath, atime, mtime) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.utimesSync(req.handle, filepath, atime, mtime)
  } catch (e) {
    throw new FileError(e.message, { operation: 'utimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function lutimes(filepath, atime, mtime, cb) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.lutimes(req.handle, filepath, atime, mtime)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'lutimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function lutimesSync(filepath, atime, mtime) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.lutimesSync(req.handle, filepath, atime, mtime)
  } catch (e) {
    throw new FileError(e.message, { operation: 'lutimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function futimes(fd, atime, mtime, cb) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.futimes(req.handle, fd, atime, mtime)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'futimes', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function futimesSync(fd, atime, mtime) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  const req = FileRequest.borrow()

  try {
    binding.futimesSync(req.handle, fd, atime, mtime)
  } catch (e) {
    throw new FileError(e.message, { operation: 'futimesSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function link(src, dst, cb) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.link(req.handle, src, dst)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'link', code: e.code, path: src, destination: dst })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function linkSync(src, dst) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  try {
    binding.linkSync(req.handle, src, dst)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'linkSync',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }
}

async function mkdir(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = { mode: 0o777 }
  }

  if (typeof opts === 'number') opts = { mode: opts }
  else if (!opts) opts = {}

  const mode = typeof opts.mode === 'number' ? opts.mode : 0o777

  filepath = toNamespacedPath(filepath)

  if (opts.recursive) {
    let err = null
    try {
      try {
        await mkdir(filepath, { mode })
      } catch (err) {
        if (err.code !== 'ENOENT') {
          if (!(await stat(filepath)).isDirectory()) throw err
        } else {
          while (filepath.endsWith(path.sep)) filepath = filepath.slice(0, -1)
          const i = filepath.lastIndexOf(path.sep)
          if (i <= 0) throw err

          await mkdir(filepath.slice(0, i), { mode, recursive: true })

          try {
            await mkdir(filepath, { mode })
          } catch (err) {
            if (!(await stat(filepath)).isDirectory()) throw err
          }
        }
      }
    } catch (e) {
      err = e
    }

    return done(err, cb)
  }

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.mkdir(req.handle, filepath, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'mkdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function mkdirSync(filepath, opts) {
  if (typeof opts === 'number') opts = { mode: opts }
  else if (!opts) opts = {}

  const mode = typeof opts.mode === 'number' ? opts.mode : 0o777

  filepath = toNamespacedPath(filepath)

  if (opts.recursive) {
    try {
      mkdirSync(filepath, { mode })
    } catch (err) {
      if (err.code !== 'ENOENT') {
        if (!statSync(filepath).isDirectory()) throw err
      } else {
        while (filepath.endsWith(path.sep)) filepath = filepath.slice(0, -1)
        const i = filepath.lastIndexOf(path.sep)
        if (i <= 0) throw err

        mkdirSync(filepath.slice(0, i), { mode, recursive: true })

        try {
          mkdirSync(filepath, { mode })
        } catch (err) {
          if (!statSync(filepath).isDirectory()) throw err
        }
      }
    }

    return
  }

  const req = FileRequest.borrow()

  try {
    binding.mkdirSync(req.handle, filepath, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'mkdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function mkdtemp(prefix, cb) {
  prefix = toNamespacedPath(prefix)

  const req = FileRequest.borrow()

  let res
  let err = null
  try {
    binding.mkdtemp(req.handle, prefix + 'XXXXXX')

    await req

    res = binding.requestResultPath(req.handle)
  } catch (e) {
    err = new FileError(e.message, { operation: 'mkdtemp', code: e.code, path: prefix })
  } finally {
    req.return()
  }

  return done(err, res, cb)
}

function mkdtempSync(prefix) {
  prefix = toNamespacedPath(prefix)

  const req = FileRequest.borrow()

  try {
    binding.mkdtempSync(req.handle, prefix + 'XXXXXX')

    return binding.requestResultPath(req.handle)
  } catch (e) {
    throw new FileError(e.message, { operation: 'mkdtempSync', code: e.code, path: prefix })
  } finally {
    req.return()
  }
}

async function rmdir(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.rmdir(req.handle, filepath)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'rmdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function rmdirSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.rmdirSync(req.handle, filepath)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'rmdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function rm(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  let err = null
  try {
    const st = await lstat(filepath)

    if (st.isDirectory()) {
      if (opts.recursive) {
        try {
          await rmdir(filepath)
        } catch (err) {
          if (err.code !== 'ENOTEMPTY') throw err

          const files = await readdir(filepath)

          for (const file of files) {
            await rm(filepath + path.sep + file, opts)
          }

          await rmdir(filepath)
        }
      } else {
        throw new FileError('is a directory', {
          operation: 'rm',
          code: 'EISDIR',
          path: filepath
        })
      }
    } else {
      await unlink(filepath)
    }
  } catch (e) {
    if (e.code !== 'ENOENT' || !opts.force) err = e
  }

  return done(err, cb)
}

function rmSync(filepath, opts) {
  if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  try {
    const st = lstatSync(filepath)

    if (st.isDirectory()) {
      if (opts.recursive) {
        try {
          rmdirSync(filepath)
        } catch (err) {
          if (err.code !== 'ENOTEMPTY') throw err

          const files = readdirSync(filepath)

          for (const file of files) {
            rmSync(filepath + path.sep + file, opts)
          }

          rmdirSync(filepath)
        }
      } else {
        throw new FileError('is a directory', {
          operation: 'rm',
          code: 'EISDIR',
          path: filepath
        })
      }
    } else {
      unlinkSync(filepath)
    }
  } catch (err) {
    if (err.code !== 'ENOENT' || !opts.force) throw err
  }
}

async function unlink(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.unlink(req.handle, filepath)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'unlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function unlinkSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.unlinkSync(req.handle, filepath)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'unlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function rename(src, dst, cb) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.rename(req.handle, src, dst)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'rename',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function renameSync(src, dst) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  try {
    binding.renameSync(req.handle, src, dst)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'rename',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }
}

async function copyFile(src, dst, mode = 0, cb) {
  if (typeof mode === 'function') {
    cb = mode
    mode = 0
  }

  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.copyfile(req.handle, src, dst, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'copyfile',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function copyFileSync(src, dst, mode = 0) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  try {
    binding.copyfileSync(req.handle, src, dst, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'copyfile',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }
}

async function cp(src, dst, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (!opts) opts = {}

  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  let err = null
  try {
    const st = await lstat(src)

    if (st.isDirectory()) {
      if (opts.recursive !== true) {
        throw new FileError('is a directory', { operation: 'cp', code: 'EISDIR', path: src })
      }

      try {
        await lstat(dst)
      } catch (e) {
        if (e.code !== 'ENOENT') throw e

        await mkdir(dst, { mode: st.mode, recursive: true })
      }

      const dir = await opendir(src)
      for await (const { name } of dir) {
        await cp(path.join(src, name), path.join(dst, name), opts)
      }
    } else if (st.isFile()) {
      await copyFile(src, dst)
      await chmod(dst, st.mode)
    }
  } catch (e) {
    err = e
  }

  return done(err, cb)
}

function cpSync(src, dst, opts = {}) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const st = lstatSync(src)

  if (st.isDirectory()) {
    if (opts.recursive !== true) {
      throw new FileError('is a directory', { operation: 'cp', code: 'EISDIR', path: src })
    }

    try {
      lstatSync(dst)
    } catch (e) {
      if (e.code !== 'ENOENT') throw e

      mkdirSync(dst, { mode: st.mode, recursive: true })
    }

    const dir = opendirSync(src)
    for (const { name } of dir) {
      cpSync(path.join(src, name), path.join(dst, name), opts)
    }
  } else if (st.isFile()) {
    copyFileSync(src, dst)
    chmodSync(dst, st.mode)
  }
}

async function realpath(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let res
  let err = null
  try {
    binding.realpath(req.handle, filepath)

    await req

    res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'realpath',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, res, cb)
}

function realpathSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.realpathSync(req.handle, filepath)

    let res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)

    return res
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'realpath',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function readlink(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let res
  let err = null
  try {
    binding.readlink(req.handle, filepath)

    await req

    res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'readlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, res, cb)
}

function readlinkSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.readlinkSync(req.handle, filepath)

    let res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)

    return res
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'readlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function fsync(fd, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fsync(req.handle, fd)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fsync', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fsyncSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.fsyncSync(req.handle, fd)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fsyncSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function fdatasync(fd, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fdatasync(req.handle, fd)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fdatasync', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fdatasyncSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.fdatasyncSync(req.handle, fd)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fdatasyncSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

function normalizeSymlinkTarget(target, type, filepath) {
  if (isWindows) {
    if (type === constants.UV_FS_SYMLINK_JUNCTION) target = path.resolve(filepath, '..', target)

    if (path.isAbsolute(target)) return path.toNamespacedPath(target)

    return target.replace(/\//g, path.sep)
  }

  return target
}

async function symlink(target, filepath, type, cb) {
  if (typeof type === 'function') {
    cb = type
    type = null
  }

  filepath = toNamespacedPath(filepath)

  if (typeof type === 'string') {
    switch (type) {
      case 'dir':
        type = constants.UV_FS_SYMLINK_DIR
        break
      case 'junction':
        type = constants.UV_FS_SYMLINK_JUNCTION
        break
      case 'file':
      default:
        type = 0
        break
    }
  } else if (typeof type !== 'number') {
    if (isWindows) {
      target = path.resolve(filepath, '..', target)

      try {
        type = (await stat(target)).isDirectory()
          ? constants.UV_FS_SYMLINK_DIR
          : constants.UV_FS_SYMLINK_JUNCTION
      } catch {
        type = 0
      }
    } else {
      type = 0
    }
  }

  target = normalizeSymlinkTarget(target, type, filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.symlink(req.handle, target, filepath, type)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'symlink',
      code: e.code,
      path: target,
      destination: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function symlinkSync(target, filepath, type) {
  filepath = toNamespacedPath(filepath)

  if (typeof type === 'string') {
    switch (type) {
      case 'dir':
        type = constants.UV_FS_SYMLINK_DIR
        break
      case 'junction':
        type = constants.UV_FS_SYMLINK_JUNCTION
        break
      case 'file':
      default:
        type = 0
        break
    }
  } else if (typeof type !== 'number') {
    if (isWindows) {
      target = path.resolve(filepath, '..', target)

      try {
        type = statSync(target).isDirectory()
          ? constants.UV_FS_SYMLINK_DIR
          : constants.UV_FS_SYMLINK_JUNCTION
      } catch {
        type = 0
      }
    } else {
      type = 0
    }
  }

  target = normalizeSymlinkTarget(target, type, filepath)

  const req = FileRequest.borrow()

  try {
    binding.symlinkSync(req.handle, target, filepath, type)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'symlink',
      code: e.code,
      path: target,
      destination: filepath
    })
  } finally {
    req.return()
  }
}

async function opendir(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let dir
  let err = null
  try {
    binding.opendir(req.handle, filepath)

    await req

    dir = new Dir(filepath, binding.requestResultDir(req.handle), opts)
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'opendir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, dir, cb)
}

function opendirSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.opendirSync(req.handle, filepath)

    return new Dir(filepath, binding.requestResultDir(req.handle), opts)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'opendir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function readdir(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { withFileTypes = false, recursive = false } = opts

  filepath = toNamespacedPath(filepath)

  const queue = [filepath]
  let result = []
  let err = null
  try {
    while (queue.length !== 0) {
      const dir = await opendir(queue.pop())

      for await (const entry of dir) {
        const entryPath = path.join(entry.parentPath, entry.name)

        if (withFileTypes) {
          result.push(entry)
        } else {
          result.push(path.relative(filepath, entryPath))
        }

        if (recursive && entry.isDirectory()) queue.push(entryPath)
      }
    }
  } catch (e) {
    result = []
    err = e
  }

  return done(err, result, cb)
}

function readdirSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { withFileTypes = false, recursive = false } = opts

  filepath = toNamespacedPath(filepath)

  const queue = [filepath]
  const result = []

  while (queue.length !== 0) {
    const dir = opendirSync(queue.pop(), opts)

    for (const entry of dir) {
      const entryPath = path.join(entry.parentPath, entry.name)

      if (withFileTypes) {
        result.push(entry)
      } else {
        result.push(path.relative(filepath, entryPath))
      }

      if (recursive && entry.isDirectory()) queue.push(entryPath)
    }
  }

  return result
}

async function readFile(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'buffer' } = opts

  let fd = -1
  let buffer = null
  let err = null
  try {
    fd = await open(filepath, opts.flag || 'r')

    const st = await fstat(fd)

    let len = 0

    if (st.size === 0) {
      const buffers = []

      while (true) {
        buffer = Buffer.allocUnsafe(8192)
        const r = await read(fd, buffer)
        len += r
        if (r === 0) break
        buffers.push(buffer.subarray(0, r))
      }

      buffer = Buffer.concat(buffers)
    } else {
      buffer = Buffer.allocUnsafe(st.size)

      while (true) {
        const r = await read(fd, len ? buffer.subarray(len) : buffer)
        len += r
        if (r === 0 || len === buffer.byteLength) break
      }

      if (len !== buffer.byteLength) buffer = buffer.subarray(0, len)
    }

    if (encoding !== 'buffer') buffer = buffer.toString(encoding)
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) await close(fd)
  }

  return done(err, buffer, cb)
}

function readFileSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'buffer' } = opts

  let fd = -1
  try {
    fd = openSync(filepath, opts.flag || 'r')

    const st = fstatSync(fd)

    let buffer
    let len = 0

    if (st.size === 0) {
      const buffers = []

      while (true) {
        buffer = Buffer.allocUnsafe(8192)
        const r = readSync(fd, buffer)
        len += r
        if (r === 0) break
        buffers.push(buffer.subarray(0, r))
      }

      buffer = Buffer.concat(buffers)
    } else {
      buffer = Buffer.allocUnsafe(st.size)

      while (true) {
        const r = readSync(fd, len ? buffer.subarray(len) : buffer)
        len += r
        if (r === 0 || len === buffer.byteLength) break
      }

      if (len !== buffer.byteLength) buffer = buffer.subarray(0, len)
    }

    if (encoding !== 'buffer') buffer = buffer.toString(encoding)

    return buffer
  } finally {
    if (fd !== -1) closeSync(fd)
  }
}

async function writeFile(filepath, data, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (typeof data === 'string') data = Buffer.from(data, opts.encoding)

  let fd = -1
  let len = 0
  let err = null
  try {
    fd = await open(filepath, opts.flag || 'w', opts.mode || 0o666)

    while (true) {
      len += await write(fd, len ? data.subarray(len) : data)
      if (len === data.byteLength) break
    }
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) await close(fd)
  }

  return done(err, len, cb)
}

function writeFileSync(filepath, data, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (typeof data === 'string') data = Buffer.from(data, opts.encoding)

  let fd = -1
  try {
    fd = openSync(filepath, opts.flag || 'w', opts.mode || 0o666)

    let len = 0

    while (true) {
      len += writeSync(fd, len ? data.subarray(len) : data)
      if (len === data.byteLength) break
    }
  } finally {
    if (fd !== -1) closeSync(fd)
  }
}

function appendFile(filepath, data, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (!opts.flag) opts = { ...opts, flag: 'a' }

  return writeFile(filepath, data, opts, cb)
}

function appendFileSync(filepath, data, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (!opts.flag) opts = { ...opts, flag: 'a' }

  return writeFileSync(filepath, data, opts)
}

function watch(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  return new Watcher(filepath, opts, cb)
}

class Stats {
  constructor(
    dev,
    mode,
    nlink,
    uid,
    gid,
    rdev,
    blksize,
    ino,
    size,
    blocks,
    atimeMs,
    mtimeMs,
    ctimeMs,
    birthtimeMs
  ) {
    this.dev = dev
    this.mode = mode
    this.nlink = nlink
    this.uid = uid
    this.gid = gid
    this.rdev = rdev
    this.blksize = blksize
    this.ino = ino
    this.size = size
    this.blocks = blocks
    this.atimeMs = atimeMs
    this.mtimeMs = mtimeMs
    this.ctimeMs = ctimeMs
    this.birthtimeMs = birthtimeMs
    this.atime = new Date(atimeMs)
    this.mtime = new Date(mtimeMs)
    this.ctime = new Date(ctimeMs)
    this.birthtime = new Date(birthtimeMs)
  }

  isDirectory() {
    return (this.mode & constants.S_IFMT) === constants.S_IFDIR
  }

  isFile() {
    return (this.mode & constants.S_IFMT) === constants.S_IFREG
  }

  isBlockDevice() {
    return (this.mode & constants.S_IFMT) === constants.S_IFBLK
  }

  isCharacterDevice() {
    return (this.mode & constants.S_IFMT) === constants.S_IFCHR
  }

  isFIFO() {
    return (this.mode & constants.S_IFMT) === constants.S_IFIFO
  }

  isSymbolicLink() {
    return (this.mode & constants.S_IFMT) === constants.S_IFLNK
  }

  isSocket() {
    return (this.mode & constants.S_IFMT) === constants.S_IFSOCK
  }
}

class StatFs {
  constructor(type, bsize, blocks, bfree, bavail, files, ffree) {
    this.type = type
    this.bsize = bsize
    this.blocks = blocks
    this.bfree = bfree
    this.bavail = bavail
    this.files = files
    this.ffree = ffree
  }
}

class Dir {
  constructor(path, handle, opts = {}) {
    const { encoding = 'utf8', bufferSize = 32 } = opts

    this.path = path

    this._encoding = encoding
    this._capacity = bufferSize
    this._buffer = new FIFO()
    this._ended = false
    this._handle = handle
  }

  async read(cb) {
    if (this._buffer.length) return ok(this._buffer.shift(), cb)
    if (this._ended) return ok(null, cb)

    const req = FileRequest.borrow()

    let entries
    let err = null
    try {
      req.retain(binding.readdir(req.handle, this._handle, this._capacity))

      await req

      entries = binding.requestResultDirents(req.handle)
    } catch (e) {
      err = new FileError(e.message, {
        operation: 'readdir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    if (err) return fail(err, cb)

    if (entries.length === 0) {
      this._ended = true

      return ok(null, cb)
    }

    for (const entry of entries) {
      let name = Buffer.from(entry.name)

      if (this._encoding !== 'buffer') name = name.toString(this._encoding)

      this._buffer.push(new Dirent(this.path, name, entry.type))
    }

    return ok(this._buffer.shift(), cb)
  }

  readSync() {
    if (this._buffer.length) return this._buffer.shift()
    if (this._ended) return null

    const req = FileRequest.borrow()

    let entries
    try {
      req.retain(binding.readdirSync(req.handle, this._handle, this._capacity))

      entries = binding.requestResultDirents(req.handle)
    } catch (e) {
      throw new FileError(e.message, {
        operation: 'readdir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    if (entries.length === 0) {
      this._ended = true

      return null
    }

    for (const entry of entries) {
      let name = Buffer.from(entry.name)

      if (this._encoding !== 'buffer') name = name.toString(this._encoding)

      this._buffer.push(new Dirent(this.path, name, entry.type))
    }

    return this._buffer.shift()
  }

  async close(cb) {
    const req = FileRequest.borrow()

    let err = null
    try {
      binding.closedir(req.handle, this._handle)

      await req
    } catch (e) {
      err = new FileError(e.message, {
        operation: 'closedir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    this._handle = null

    return done(err, cb)
  }

  closeSync() {
    const req = FileRequest.borrow()

    try {
      binding.closedirSync(req.handle, this._handle)
    } catch (e) {
      throw new FileError(e.message, {
        operation: 'closedir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    this._handle = null
  }

  [Symbol.dispose]() {
    this.closeSync()
  }

  async [Symbol.asyncDispose]() {
    await this.close()
  }

  *[Symbol.iterator]() {
    while (true) {
      const entry = this.readSync()
      if (entry === null) break
      yield entry
    }

    this.closeSync()
  }

  async *[Symbol.asyncIterator]() {
    while (true) {
      const entry = await this.read()
      if (entry === null) break
      yield entry
    }

    await this.close()
  }
}

class Dirent {
  constructor(parentPath, name, type) {
    this.parentPath = parentPath
    this.name = name
    this.type = type
  }

  isFile() {
    return this.type === constants.UV_DIRENT_FILE
  }

  isDirectory() {
    return this.type === constants.UV_DIRENT_DIR
  }

  isSymbolicLink() {
    return this.type === constants.UV_DIRENT_LINK
  }

  isFIFO() {
    return this.type === constants.UV_DIRENT_FIFO
  }

  isSocket() {
    return this.type === constants.UV_DIRENT_SOCKET
  }

  isCharacterDevice() {
    return this.type === constants.UV_DIRENT_CHAR
  }

  isBlockDevice() {
    return this.type === constants.UV_DIRENT_BLOCK
  }
}

class FileReadStream extends Readable {
  constructor(path, opts = {}) {
    const { eagerOpen = true } = opts

    super({ eagerOpen, ...opts })

    this.path = path
    this.fd = typeof opts.fd === 'number' ? opts.fd : -1
    this.flags = opts.flags || 'r'
    this.mode = opts.mode || 0o666

    this._offset = opts.start || 0
    this._missing = 0

    if (opts.length) {
      this._missing = opts.length
    } else if (typeof opts.end === 'number') {
      this._missing = opts.end - this._offset + 1
    } else {
      this._missing = -1
    }
  }

  async _open(cb) {
    let err

    if (this.fd === -1) {
      err = null
      try {
        this.fd = await open(this.path, this.flags, this.mode)
      } catch (e) {
        err = e
      }

      if (err) return cb(err)
    }

    let st
    err = null
    try {
      st = await fstat(this.fd)
    } catch (e) {
      err = e
    }

    if (err) return cb(err)

    if (this._missing === -1) this._missing = st.size

    if (st.size < this._offset) {
      this._offset = st.size
      this._missing = 0
    } else if (st.size < this._offset + this._missing) {
      this._missing = st.size - this._offset
    }

    cb(null)
  }

  async _read(size) {
    if (this._missing <= 0) return this.push(null)

    const data = Buffer.allocUnsafe(Math.min(this._missing, size))

    let len
    let err = null
    try {
      len = await read(this.fd, data, 0, data.byteLength, this._offset)
    } catch (e) {
      err = e
    }

    if (err) return this.destroy(err)

    if (len === 0) return this.push(null)

    if (this._missing < len) len = this._missing

    this._missing -= len
    this._offset += len

    this.push(data.subarray(0, len))
  }

  async _destroy(err, cb) {
    if (this.fd === -1) return cb(err)

    try {
      await close(this.fd)
    } catch (e) {
      err = err || e
    }

    cb(err)
  }
}

class FileWriteStream extends Writable {
  constructor(path, opts = {}) {
    const { eagerOpen = true } = opts

    super({ eagerOpen, ...opts })

    this.path = path
    this.fd = typeof opts.fd === 'number' ? opts.fd : -1
    this.flags = opts.flags || 'w'
    this.mode = opts.mode || 0o666
  }

  async _open(cb) {
    if (this.fd !== -1) return cb(null)

    let err = null
    try {
      this.fd = await open(this.path, this.flags, this.mode)
    } catch (e) {
      err = e
    }

    cb(err)
  }

  async _writev(batch, cb) {
    let err = null
    try {
      await writev(
        this.fd,
        batch.map(({ chunk }) => chunk)
      )
    } catch (e) {
      err = e
    }

    cb(err)
  }

  async _destroy(err, cb) {
    if (this.fd === -1) return cb(err)

    try {
      await close(this.fd)
    } catch (e) {
      err = err || e
    }

    cb(err)
  }
}

class Watcher extends EventEmitter {
  constructor(path, opts, onchange) {
    if (typeof opts === 'function') {
      onchange = opts
      opts = {}
    }

    if (!opts) opts = {}

    const { persistent = true, recursive = false, encoding = 'utf8' } = opts

    super()

    this._closed = false
    this._encoding = encoding
    this._handle = binding.watcherInit(path, recursive, this, this._onevent, this._onclose)

    if (!persistent) this.unref()

    if (onchange) this.on('change', onchange)
  }

  close() {
    if (this._closed) return
    this._closed = true

    binding.watcherClose(this._handle)
  }

  ref() {
    if (this._handle) binding.watcherRef(this._handle)
    return this
  }

  unref() {
    if (this._handle) binding.watcherUnref(this._handle)
    return this
  }

  [Symbol.asyncIterator]() {
    const buffer = []
    let done = false
    let error = null
    let next = null

    this.on('change', (eventType, filename) => {
      if (next) {
        next.resolve({ done: false, value: { eventType, filename } })
        next = null
      } else {
        buffer.push({ eventType, filename })
      }
    })
      .on('error', (err) => {
        done = true
        error = err

        if (next) {
          next.reject(error)
          next = null
        }
      })
      .on('close', () => {
        done = true

        if (next) {
          next.resolve({ done })
          next = null
        }
      })

    return {
      next: () =>
        new Promise((resolve, reject) => {
          if (error) return reject(error)

          if (buffer.length) return resolve({ done: false, value: buffer.shift() })

          if (done) return resolve({ done })

          next = { resolve, reject }
        })
    }
  }

  _onevent(err, events, filename) {
    if (err) {
      this.close()
      this.emit('error', err)
    } else {
      const path =
        this._encoding === 'buffer'
          ? Buffer.from(filename)
          : Buffer.from(filename).toString(this._encoding)

      if (events & binding.UV_RENAME) {
        this.emit('change', 'rename', path)
      }

      if (events & binding.UV_CHANGE) {
        this.emit('change', 'change', path)
      }
    }
  }

  _onclose() {
    this._handle = null

    this.emit('close')
  }
}

exports.access = access
exports.appendFile = appendFile
exports.chmod = chmod
exports.chown = chown
exports.close = close
exports.copyFile = copyFile
exports.cp = cp
exports.exists = exists
exports.fchmod = fchmod
exports.fchown = fchown
exports.fdatasync = fdatasync
exports.fstat = fstat
exports.fsync = fsync
exports.ftruncate = ftruncate
exports.futimes = futimes
exports.lchown = lchown
exports.lutimes = lutimes
exports.link = link
exports.lstat = lstat
exports.mkdir = mkdir
exports.mkdtemp = mkdtemp
exports.open = open
exports.opendir = opendir
exports.read = read
exports.readFile = readFile
exports.readdir = readdir
exports.readlink = readlink
exports.readv = readv
exports.realpath = realpath
exports.rename = rename
exports.rm = rm
exports.rmdir = rmdir
exports.stat = stat
exports.statfs = statfs
exports.symlink = symlink
exports.truncate = truncate
exports.unlink = unlink
exports.utimes = utimes
exports.watch = watch
exports.write = write
exports.writeFile = writeFile
exports.writev = writev

exports.accessSync = accessSync
exports.appendFileSync = appendFileSync
exports.chmodSync = chmodSync
exports.chownSync = chownSync
exports.closeSync = closeSync
exports.copyFileSync = copyFileSync
exports.cpSync = cpSync
exports.existsSync = existsSync
exports.fchmodSync = fchmodSync
exports.fchownSync = fchownSync
exports.fdatasyncSync = fdatasyncSync
exports.fstatSync = fstatSync
exports.fsyncSync = fsyncSync
exports.ftruncateSync = ftruncateSync
exports.futimesSync = futimesSync
exports.lchownSync = lchownSync
exports.lutimesSync = lutimesSync
exports.linkSync = linkSync
exports.lstatSync = lstatSync
exports.mkdirSync = mkdirSync
exports.mkdtempSync = mkdtempSync
exports.openSync = openSync
exports.opendirSync = opendirSync
exports.readFileSync = readFileSync
exports.readSync = readSync
exports.readdirSync = readdirSync
exports.readlinkSync = readlinkSync
exports.readvSync = readvSync
exports.realpathSync = realpathSync
exports.renameSync = renameSync
exports.rmSync = rmSync
exports.rmdirSync = rmdirSync
exports.statSync = statSync
exports.statfsSync = statfsSync
exports.symlinkSync = symlinkSync
exports.truncateSync = truncateSync
exports.unlinkSync = unlinkSync
exports.utimesSync = utimesSync
exports.writeFileSync = writeFileSync
exports.writeSync = writeSync
exports.writevSync = writevSync

exports.promises = require('./promises')

exports.Stats = Stats
exports.StatFs = StatFs
exports.Dir = Dir
exports.Dirent = Dirent
exports.Watcher = Watcher

exports.ReadStream = FileReadStream

exports.createReadStream = function createReadStream(path, opts) {
  return new FileReadStream(path, opts)
}

exports.WriteStream = FileWriteStream

exports.createWriteStream = function createWriteStream(path, opts) {
  return new FileWriteStream(path, opts)
}

function toNamespacedPath(filepath) {
  if (typeof filepath !== 'string') {
    if (isURL(filepath)) filepath = fileURLToPath(filepath)
    else filepath = filepath.toString()
  }

  return path.toNamespacedPath(filepath)
}

function toFlags(flags) {
  switch (flags) {
    case 'r':
      return constants.O_RDONLY
    case 'rs': // Fall through.
    case 'sr':
      return constants.O_RDONLY | constants.O_SYNC
    case 'r+':
      return constants.O_RDWR
    case 'rs+': // Fall through.
    case 'sr+':
      return constants.O_RDWR | constants.O_SYNC

    case 'w':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_WRONLY
    case 'wx': // Fall through.
    case 'xw':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_WRONLY | constants.O_EXCL

    case 'w+':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_RDWR
    case 'wx+': // Fall through.
    case 'xw+':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_RDWR | constants.O_EXCL

    case 'a':
      return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY
    case 'ax': // Fall through.
    case 'xa':
      return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY | constants.O_EXCL
    case 'as': // Fall through.
    case 'sa':
      return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY | constants.O_SYNC

    case 'a+':
      return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR
    case 'ax+': // Fall through.
    case 'xa+':
      return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR | constants.O_EXCL
    case 'as+': // Fall through.
    case 'sa+':
      return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR | constants.O_SYNC
    default:
      return 0
  }
}

function toMode(mode) {
  return parseInt(mode, 8)
}
const binding = require('../binding')

module.exports = {
  O_RDWR: binding.O_RDWR,
  O_RDONLY: binding.O_RDONLY,
  O_WRONLY: binding.O_WRONLY,
  O_CREAT: binding.O_CREAT,
  O_TRUNC: binding.O_TRUNC,
  O_APPEND: binding.O_APPEND,

  F_OK: binding.F_OK || 0,
  R_OK: binding.R_OK || 0,
  W_OK: binding.W_OK || 0,
  X_OK: binding.X_OK || 0,

  S_IFMT: binding.S_IFMT,
  S_IFREG: binding.S_IFREG,
  S_IFDIR: binding.S_IFDIR,
  S_IFCHR: binding.S_IFCHR,
  S_IFLNK: binding.S_IFLNK,
  S_IFBLK: binding.S_IFBLK || 0,
  S_IFIFO: binding.S_IFIFO || 0,
  S_IFSOCK: binding.S_IFSOCK || 0,

  S_IRUSR: binding.S_IRUSR || 0,
  S_IWUSR: binding.S_IWUSR || 0,
  S_IXUSR: binding.S_IXUSR || 0,
  S_IRGRP: binding.S_IRGRP || 0,
  S_IWGRP: binding.S_IWGRP || 0,
  S_IXGRP: binding.S_IXGRP || 0,
  S_IROTH: binding.S_IROTH || 0,
  S_IWOTH: binding.S_IWOTH || 0,
  S_IXOTH: binding.S_IXOTH || 0,

  UV_DIRENT_UNKNOWN: binding.UV_DIRENT_UNKNOWN,
  UV_DIRENT_FILE: binding.UV_DIRENT_FILE,
  UV_DIRENT_DIR: binding.UV_DIRENT_DIR,
  UV_DIRENT_LINK: binding.UV_DIRENT_LINK,
  UV_DIRENT_FIFO: binding.UV_DIRENT_FIFO,
  UV_DIRENT_SOCKET: binding.UV_DIRENT_SOCKET,
  UV_DIRENT_CHAR: binding.UV_DIRENT_CHAR,
  UV_DIRENT_BLOCK: binding.UV_DIRENT_BLOCK,

  COPYFILE_EXCL: binding.UV_FS_COPYFILE_EXCL,
  COPYFILE_FICLONE: binding.UV_FS_COPYFILE_FICLONE,
  COPYFILE_FICLONE_FORCE: binding.UV_FS_COPYFILE_FICLONE_FORCE,
  UV_FS_SYMLINK_DIR: binding.UV_FS_SYMLINK_DIR,
  UV_FS_SYMLINK_JUNCTION: binding.UV_FS_SYMLINK_JUNCTION
}
const os = require('bare-os')

module.exports = class FileError extends Error {
  constructor(msg, opts = {}) {
    const { code, operation = null, path = null, destination = null, fd = -1 } = opts

    if (operation !== null) msg += describe(operation, opts)

    super(`${code}: ${msg}`)

    this.code = code

    if (operation !== null) this.operation = operation
    if (path !== null) this.path = path
    if (destination !== null) this.destination = destination
    if (fd !== -1) this.fd = fd
  }

  get name() {
    return 'FileError'
  }

  // For Node.js compatibility
  get errno() {
    return os.constants.errnos[this.code]
  }

  // For Node.js compatibility
  get syscall() {
    return this.operation
  }

  // For Node.js compatibility
  get dest() {
    return this.destination
  }
}

function describe(operation, opts) {
  const { path = null, destination = null, fd = -1 } = opts

  let result = `, ${operation}`

  if (path !== null) {
    result += ` ${JSON.stringify(path)}`

    if (destination !== null) {
      result += ` -> ${JSON.stringify(destination)}`
    }
  } else if (fd !== -1) {
    result += ` ${fd}`
  }

  return result
}
{
  "name": "bare-fs",
  "version": "4.7.2",
  "description": "Native file system operations for Bare",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./promises": {
      "types": "./promises.d.ts",
      "default": "./promises.js"
    },
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "promises.js",
    "promises.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-fs.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-fs/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-fs#readme",
  "engines": {
    "bare": ">=1.16.0"
  },
  "dependencies": {
    "bare-events": "^2.5.4",
    "bare-path": "^3.0.0",
    "bare-stream": "^2.6.4",
    "bare-url": "^2.2.2",
    "fast-fifo": "^1.3.2"
  },
  "devDependencies": {
    "bare-buffer": "^3.0.2",
    "bare-crypto": "^1.11.2",
    "brittle": "^3.1.1",
    "cmake-bare": "^1.1.7",
    "lunte": "^1.6.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "bare-buffer": "*"
  },
  "peerDependenciesMeta": {
    "bare-buffer": {
      "optional": true
    }
  }
}
const EventEmitter = require('bare-events')
const fs = require('.')

class FileHandle extends EventEmitter {
  constructor(fd) {
    super()

    this.fd = fd
  }

  async close() {
    await fs.close(this.fd)

    this.fd = -1
    this.emit('close')
  }

  async read(buffer, ...args) {
    return {
      bytesRead: await fs.read(this.fd, buffer, ...args),
      buffer
    }
  }

  async readv(buffers, ...args) {
    return {
      bytesRead: await fs.readv(this.fd, buffers, ...args),
      buffers
    }
  }

  async write(buffer, ...args) {
    return {
      bytesWritten: await fs.write(this.fd, buffer, ...args),
      buffer
    }
  }

  async writev(buffers, ...args) {
    return {
      bytesWritten: await fs.writev(this.fd, buffers, ...args),
      buffers
    }
  }

  async stat() {
    return fs.fstat(this.fd)
  }

  async chmod(mode) {
    await fs.fchmod(this.fd, mode)
  }

  async chown(uid, gid) {
    await fs.fchown(this.fd, uid, gid)
  }

  async datasync() {
    return fs.fdatasync(this.fd)
  }

  async sync() {
    return fs.fsync(this.fd)
  }

  async truncate(len) {
    await fs.ftruncate(this.fd, len)
  }

  async utimes(atime, mtime) {
    await fs.futimes(this.fd, atime, mtime)
  }

  createReadStream(opts) {
    return fs.createReadStream(null, { ...opts, fd: this.fd })
  }

  createWriteStream(opts) {
    return fs.createWriteStream(null, { ...opts, fd: this.fd })
  }

  async [Symbol.asyncDispose]() {
    await this.close()
  }
}

exports.open = async function open(filepath, flags, mode) {
  return new FileHandle(await fs.open(filepath, flags, mode))
}

exports.access = fs.access
exports.appendFile = fs.appendFile
exports.chmod = fs.chmod
exports.chown = fs.chown
exports.constants = fs.constants
exports.copyFile = fs.copyFile
exports.cp = fs.cp
exports.lchown = fs.lchown
exports.lutimes = fs.lutimes
exports.link = fs.link
exports.lstat = fs.lstat
exports.mkdir = fs.mkdir
exports.mkdtemp = fs.mkdtemp
exports.opendir = fs.opendir
exports.readFile = fs.readFile
exports.readdir = fs.readdir
exports.readlink = fs.readlink
exports.realpath = fs.realpath
exports.rename = fs.rename
exports.rm = fs.rm
exports.rmdir = fs.rmdir
exports.stat = fs.stat
exports.statfs = fs.statfs
exports.truncate = fs.truncate
exports.symlink = fs.symlink
exports.unlink = fs.unlink
exports.utimes = fs.utimes
exports.watch = fs.watch
exports.writeFile = fs.writeFile
module.exports = require.addon()
const ansiEscapes = require('bare-ansi-escapes')
const getType = require('bare-type')
const binding = require('./binding')

const PLAIN_KEY = /^[a-zA-Z_][a-zA-Z_0-9]*$/

const defaultDepth = 2
const defaultBreakLength = 80
const defaultMaxArrayLength = 40

module.exports = exports = function inspect(value, opts = {}) {
  const {
    colors = false,
    depth = defaultDepth,
    breakLength = defaultBreakLength,
    stylize = defaultStylize(colors)
  } = opts

  const references = new InspectRefMap()

  const tree = inspectValue(value, 0, {
    colors,
    depth,
    breakLength,
    stylize,
    references
  })

  return tree.toString()
}

exports.styles = {
  bigint: ansiEscapes.colorYellow,
  boolean: ansiEscapes.colorYellow,
  date: ansiEscapes.colorMagenta,
  module: ansiEscapes.modifierUnderline,
  name: ansiEscapes.modifierReset,
  null: ansiEscapes.modifierBold,
  number: ansiEscapes.colorYellow,
  regexp: ansiEscapes.colorRed,
  special: ansiEscapes.colorCyan,
  string: ansiEscapes.colorGreen,
  symbol: ansiEscapes.colorGreen,
  undefined: ansiEscapes.colorBrightBlack
}

const styles = exports.styles

function defaultStylize(colors) {
  return function stylize(value, style) {
    const color = colors && styles[style]

    if (color) return color + value + ansiEscapes.modifierReset

    return value
  }
}

class InspectRefMap {
  constructor() {
    this.refs = new WeakMap()
    this.ids = new WeakMap()
    this.nextId = 1
  }

  has(object) {
    return this.refs.has(object)
  }

  get(object) {
    return this.refs.get(object) || null
  }

  set(object, ref) {
    this.refs.set(object, ref)
  }

  id(object) {
    let id = this.ids.get(object)
    if (id) return id

    id = this.nextId++
    this.ids.set(object, id)

    return id
  }
}

class InspectNode {
  constructor(depth, length, opts) {
    const { breakLength = defaultBreakLength, breakAlways = false } = opts

    this.depth = depth
    this.length = length
    this.breakLength = breakLength
    this.breakAlways = breakAlways
  }

  pad(n, string) {
    return string.padStart(n, ' ')
  }

  indent(n, string) {
    return '  '.repeat(n) + string
  }
}

class InspectRef extends InspectNode {
  constructor(depth, opts) {
    super(depth, '[circular *]'.length, opts)

    this.refs = opts.references
    this.count = 0
    this.circular = false
    this.color = opts.colors && styles.special
  }

  get id() {
    return this.refs.id(this)
  }

  increment() {
    return ++this.count
  }

  decrement() {
    return --this.count
  }

  toString(opts = {}) {
    const { offset = 0, pad = 0, indent = 0 } = opts

    let value = this.pad(pad, '[circular *' + this.id + ']')

    if (this.color) value = this.color + value + ansiEscapes.modifierReset

    return offset ? value : this.indent(indent, value)
  }
}

class InspectLeaf extends InspectNode {
  constructor(value, color, depth, opts) {
    const length = value.length

    if (value.includes('\n')) {
      value = value.replaceAll('\n', '\n' + '  '.repeat(depth))

      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.value = value
    this.color = opts.colors && color
  }

  toString(opts = {}) {
    const { offset = 0, pad = 0, indent = 0 } = opts

    let value = this.pad(pad, this.value)

    if (this.color) value = this.color + value + ansiEscapes.modifierReset

    return offset ? value : this.indent(indent, value)
  }
}

class InspectPair extends InspectNode {
  constructor(delim, left, right, depth, opts) {
    const length = left.length + delim.length + right.length

    if (left.breakAlways || right.breakAlways) {
      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.delim = delim
    this.left = left
    this.right = right
  }

  toString(opts = {}) {
    const { indent = 0 } = opts

    return this.indent(
      indent,
      this.left +
        this.delim +
        this.right.toString({
          indent,
          offset: this.left.length + this.delim.length
        })
    )
  }
}

class InspectSuspension extends InspectNode {
  constructor(overflow, depth, opts) {
    const label = `... ${overflow} more`

    super(depth, label.length, opts)

    this.label = label
  }

  toString(opts = {}) {
    const { indent = 0 } = opts

    return this.indent(indent, this.label)
  }
}

class InspectSequence extends InspectNode {
  constructor(header, footer, delim, values, ref, depth, opts) {
    const { tabulate = false } = opts

    const length =
      (ref.circular ? '<ref *>'.length + 1 : 0) +
      header.length +
      values.reduce(
        (length, value, i) =>
          length + value.length + (i === 0 ? 0 : delim.length),
        0
      ) +
      footer.length

    if (values.some((value) => value.breakAlways)) {
      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.header = header
    this.footer = footer
    this.delim = delim
    this.values = values
    this.ref = ref
    this.tabulate = tabulate
  }

  toString(opts = {}) {
    const { offset = 0, indent = 0 } = opts

    const split =
      this.breakAlways ||
      (this.values.length &&
        (offset + this.length > this.breakLength ||
          indent * 2 + this.length > this.breakLength))

    let header = this.header

    if (this.ref.circular) {
      header = '<ref *' + this.ref.id + '> ' + header
    }

    if (this.values.length === 0) {
      header = header.trimEnd()
    }

    if (offset === 0) {
      header = this.indent(indent, header)
    }

    if (split) {
      header = header.trimEnd() + '\n'
    }

    let string = header

    let columns = 1
    let pad = 0

    if (this.tabulate) {
      const widest = this.values.reduce(
        (length, value) =>
          value.breakAlways ? length : Math.max(length, value.length),
        0
      )

      if (widest) {
        columns = Math.max(
          columns,
          Math.floor(
            (this.breakLength - indent * 2) / (widest + this.delim.length)
          )
        )

        if (columns > 1) pad = widest
      }
    }

    for (let i = 0, n = this.values.length, offset = 0; i < n; i++) {
      const value = this.values[i]

      if (split) {
        let part

        if (i % columns === 0 || value.breakAlways) {
          part = value.toString({ indent: indent + 1, pad })
        } else {
          part = value.toString({ pad })
        }

        string += part

        if (i < n - 1) {
          if (i % columns === columns - 1 || this.values[i + 1].breakAlways) {
            string += this.delim.trimEnd() + '\n'
          } else {
            string += this.delim
          }
        }
      } else {
        if (i > 0) string += this.delim

        string += value.toString({ offset })

        offset += value.length
      }
    }

    let footer = this.footer

    if (this.values.length === 0) {
      footer = footer.trimStart()
    }

    if (split) {
      string += '\n' + this.indent(indent, footer.trimStart())
    } else {
      string += footer
    }

    return string
  }
}

function inspectValue(value, depth, opts) {
  const type = getType(value)

  if (type.isUndefined()) return inspectUndefined(depth, opts)
  if (type.isNull()) return inspectNull(depth, opts)
  if (type.isBoolean()) return inspectBoolean(value, depth, opts)
  if (type.isNumber()) return inspectNumber(value, depth, opts)
  if (type.isBigInt()) return inspectBigInt(value, depth, opts)
  if (type.isString()) return inspectString(value, depth, opts)
  if (type.isSymbol()) return inspectSymbol(value, depth, opts)
  if (type.isObject()) return inspectObject(type, value, depth, opts)
  if (type.isFunction()) return inspectFunction(type, value, depth, opts)
  if (type.isExternal()) return inspectExternal(value, opts, opts)
}

function inspectUndefined(depth, opts) {
  return new InspectLeaf('undefined', styles.undefined, depth, opts)
}

function inspectNull(depth, opts) {
  return new InspectLeaf('null', styles.null, depth, opts)
}

function inspectBoolean(value, depth, opts) {
  return new InspectLeaf(value.toString(), styles.boolean, depth, opts)
}

function inspectNumber(value, depth, opts) {
  let string

  if (Object.is(value, -0)) {
    string = '-0'
  } else {
    string = value.toString(10)
  }

  return new InspectLeaf(string, styles.number, depth, opts)
}

function inspectBigInt(value, depth, opts) {
  return new InspectLeaf(value.toString(10) + 'n', styles.bigint, depth, opts)
}

const STRING_ESCAPES =
  /[\ud800-\udbff][\udc00-\udfff]|[\u0000-\u001f'\\\ud800-\udfff]/g

function inspectString(value, depth, opts) {
  // https://tc39.es/ecma262/multipage/structured-data.html#sec-quotejsonstring
  const string = value.replace(STRING_ESCAPES, (match) => {
    if (match.length === 2) return match

    switch (match) {
      case "'":
        return "\\'"
      case '\\':
        return '\\\\'
      case '\b':
        return '\\b'
      case '\t':
        return '\\t'
      case '\n':
        return '\\n'
      case '\f':
        return '\\f'
      case '\r':
        return '\\r'
      default:
        return '\\u' + match.charCodeAt(0).toString(16).padStart(4, '0')
    }
  })

  return new InspectLeaf("'" + string + "'", styles.string, depth, opts)
}

function inspectSymbol(value, depth, opts) {
  return new InspectLeaf(value.toString(), styles.symbol, depth, opts)
}

function inspectKey(value, depth, opts) {
  if (PLAIN_KEY.test(value)) {
    return new InspectLeaf(value, null, depth, opts)
  } else {
    return inspectValue(value, depth, opts)
  }
}

function inspectObject(type, object, depth, opts) {
  const refs = opts.references

  let ref = refs.get(object)
  if (ref === null) {
    ref = new InspectRef(depth, opts)
    refs.set(object, ref)
  } else if (ref.count) {
    ref.circular = true
    return ref
  }

  const maxDepth = typeof opts.depth === 'number' ? opts.depth : Infinity

  if (maxDepth < depth) {
    const constructor = object.constructor

    return new InspectLeaf(
      '[' +
        (constructor && constructor.name ? constructor.name : 'Object') +
        ']',
      styles.special,
      depth,
      opts
    )
  }

  const inspect =
    object[Symbol.for('bare.inspect')] ||
    object[Symbol.for('nodejs.util.inspect.custom')]

  if (typeof inspect === 'function') {
    const value = inspect.call(
      object,
      typeof opts.depth === 'number' ? opts.depth - depth : null,
      {
        colors: opts.colors,
        breakLength: opts.breakLength,
        stylize: opts.stylize
      },
      exports
    )

    if (typeof value === 'object' && value !== null) {
      refs.set(value, ref)
    }

    if (typeof value !== 'string') {
      return inspectValue(value, depth, opts)
    }

    return new InspectLeaf(value, null, depth, opts)
  }

  if (type.isArray()) return inspectArray(object, ref, depth, opts)
  if (type.isDate()) return inspectDate(object, ref, depth, opts)
  if (type.isRegExp()) return inspectRegExp(object, ref, depth, opts)
  if (type.isError()) return inspectError(object, ref, depth, opts)
  if (type.isPromise()) return inspectPromise(object, ref, depth, opts)
  if (type.isMap()) return inspectMap(object, ref, depth, opts)
  if (type.isSet()) return inspectSet(object, ref, depth, opts)
  if (type.isWeakMap()) return inspectWeakMap(object, ref, depth, opts)
  if (type.isWeakSet()) return inspectWeakSet(object, ref, depth, opts)
  if (type.isWeakRef()) return inspectWeakRef(object, ref, depth, opts)
  if (type.isArrayBuffer()) return inspectArrayBuffer(object, ref, depth, opts)
  if (type.isSharedArrayBuffer())
    return inspectSharedArrayBuffer(object, ref, depth, opts)
  if (type.isTypedArray()) return inspectTypedArray(object, ref, depth, opts)
  if (type.isDataView()) return inspectDataView(object, ref, depth, opts)

  ref.increment()

  const values = []

  for (const key in object) {
    if (key === 'constructor') continue

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(object[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  let header = '{ '

  const tag = object[Symbol.toStringTag]

  if (tag) header = '[' + tag + '] ' + header

  if (object.constructor) {
    const name = object.constructor.name

    if (name && name !== 'Object') {
      header = object.constructor.name + ' ' + header
    }
  }

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectArray(array, ref, depth, opts) {
  const { maxArrayLength = defaultMaxArrayLength } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxArrayLength, 0)

  for (let i = 0, n = array.length; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(array.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(inspectValue(array[i], depth + 1, opts))
  }

  for (const key of binding.getOwnNonIndexPropertyNames(array)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(array[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  let header = '[ '

  if (array.constructor.name !== 'Array') {
    header = array.constructor.name + '(' + array.length + ') ' + header
  }

  return new InspectSequence(header, ' ]', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectDate(date, ref, depth, opts) {
  return new InspectLeaf(date.toISOString(), styles.date, depth, opts)
}

function inspectRegExp(regExp, ref, depth, opts) {
  return new InspectLeaf(regExp.toString(), styles.regexp, depth, opts)
}

function inspectError(error, ref, depth, opts) {
  let header

  if ('stack' in error) {
    header = error.stack

    if (depth > 0) {
      header = header.replaceAll('\n', '\n' + '  '.repeat(depth))
    }
  } else {
    header = error.toString()
  }

  const builtins = ['cause']

  if (error.name === 'AggregateError') {
    builtins.push('errors')
  } else if (error.name === 'SuppressedError') {
    builtins.push('error', 'suppressed')
  }

  const values = []

  for (const key of builtins) {
    if (key in error === false) continue

    values.push(
      new InspectPair(
        ': ',
        new InspectLeaf('[' + key + ']', null, depth + 1, opts),
        inspectValue(error[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key in error) {
    if (key === 'constructor' || builtins.includes(key)) continue

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(error[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  if (values.length === 0) return new InspectLeaf(header, null, depth, opts)

  return new InspectSequence(
    header + ' {',
    ' }',
    ', ',
    values,
    ref,
    depth,
    opts
  )
}

function inspectPromise(promise, ref, depth, opts) {
  ref.increment()

  const state = binding.getPromiseState(promise)

  const values = []

  switch (state) {
    case 0: // Pending
      values.push(new InspectLeaf('<pending>', styles.special, depth, opts))
      break

    case 1: // Fulfilled
      values.push(inspectValue(binding.getPromiseResult(promise), depth, opts))
      break

    case 2: // Rejected
      values.push(
        new InspectLeaf('<rejected>', styles.special, depth, opts),
        inspectValue(binding.getPromiseResult(promise), depth, opts)
      )
  }

  ref.decrement()

  const header = promise.constructor.name + ' { '

  return new InspectSequence(header, ' }', ' ', values, ref, depth, opts)
}

function inspectMap(map, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxMapLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = maxMapLength

  for (const entry of map) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(map.size - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )
      break
    }

    values.push(
      new InspectPair(
        ' => ',
        inspectValue(entry[0], depth + 1, opts),
        inspectValue(entry[1], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key in map) {
    if (key === 'constructor') continue

    const value = inspectValue(map[key], depth + 1, opts)

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        value,
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = map.constructor.name + '(' + map.size + ') { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectSet(set, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxSetLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = maxSetLength

  for (const entry of set) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(set.size - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )
      break
    }

    values.push(inspectValue(entry, depth + 1, opts))
  }

  for (const key in set) {
    if (key === 'constructor') continue

    const value = inspectValue(set[key], depth + 1, opts)

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        value,
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = set.constructor.name + '(' + set.size + ') { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectWeakMap(weakMap, ref, depth, opts) {
  const header = weakMap.constructor.name + ' { '

  return new InspectSequence(
    header,
    ' }',
    ' ',
    [new InspectLeaf('<items unknown>', styles.special, depth + 1, opts)],
    ref,
    depth,
    opts
  )
}

function inspectWeakSet(weakSet, ref, depth, opts) {
  const header = weakSet.constructor.name + ' { '

  return new InspectSequence(
    header,
    ' }',
    ' ',
    [new InspectLeaf('<items unknown>', styles.special, depth + 1, opts)],
    ref,
    depth,
    opts
  )
}

function inspectWeakRef(weakRef, ref, depth, opts) {
  const target = weakRef.deref()

  let value

  if (target === undefined) {
    value = new InspectLeaf('<cleared>', styles.special, depth + 1, opts)
  } else {
    value = inspectValue(target, depth + 1, opts)
  }

  const header = weakRef.constructor.name + ' { '

  return new InspectSequence(header, ' }', ' ', [value], ref, depth, opts)
}

function inspectArrayBuffer(arrayBuffer, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(arrayBuffer[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = arrayBuffer.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectSharedArrayBuffer(sharedArrayBuffer, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(sharedArrayBuffer[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = sharedArrayBuffer.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectTypedArray(typedArray, ref, depth, opts) {
  if (Buffer.isBuffer(typedArray)) {
    return inspectBuffer(typedArray, ref, depth, opts)
  }

  const {
    maxArrayLength = defaultMaxArrayLength,
    maxTypedArrayLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxTypedArrayLength, 0)

  for (let i = 0, n = typedArray.length; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(typedArray.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(inspectValue(typedArray[i], depth + 1, opts))
  }

  for (const key of binding.getOwnNonIndexPropertyNames(typedArray)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(typedArray[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = typedArray.constructor.name + '(' + typedArray.length + ') [ '

  return new InspectSequence(header, ' ]', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectBuffer(buffer, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxBufferLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxBufferLength, 0)

  for (let i = 0, n = buffer.byteLength; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(buffer.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(
      new InspectLeaf(
        buffer[i].toString(16).padStart(2, '0'),
        null,
        depth + 1,
        opts
      )
    )
  }

  for (const key of binding.getOwnNonIndexPropertyNames(buffer)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(buffer[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  return new InspectSequence('<Buffer ', '>', ' ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectDataView(dataView, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength', 'byteOffset', 'buffer']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(dataView[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key of binding.getOwnNonIndexPropertyNames(dataView)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(dataView[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = dataView.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectFunction(type, fn, depth, opts) {
  if (fn.toString().startsWith('class')) return inspectClass(fn, depth, opts)

  let tag = 'function'

  if (type.isGeneratorFunction()) tag = 'generator ' + tag
  if (type.isAsyncFunction()) tag = 'async ' + tag

  return new InspectLeaf(
    '[' + tag + ' ' + (fn.name ? fn.name : '(anonymous)') + ']',
    styles.special,
    depth,
    opts
  )
}

function inspectClass(ctor, depth, opts) {
  return new InspectLeaf(
    '[class ' + (ctor.name ? ctor.name : '(anonymous)') + ']',
    styles.special,
    depth,
    opts
  )
}

function inspectExternal(external, depth, opts) {
  return new InspectLeaf(
    '[external 0x' + binding.getExternal(external).toString(16) + ']',
    styles.special,
    depth,
    opts
  )
}
{
  "name": "bare-inspect",
  "version": "3.1.4",
  "description": "Inspect objects as strings for debugging",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-inspect.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-inspect/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-inspect#readme",
  "engines": {
    "bare": ">=1.18.0"
  },
  "dependencies": {
    "bare-ansi-escapes": "^2.1.0",
    "bare-type": "^1.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
module.exports = require.addon()
const binding = require('./binding')
const errors = require('./lib/errors')
const constants = require('./lib/constants')

exports.constants = constants
exports.errors = errors

exports.EOL = binding.platform === 'win32' ? '\r\n' : '\n'

exports.devNull = binding.platform === 'win32' ? '\\\\.\\nul' : '/dev/null'

exports.platform = function platform() {
  return binding.platform
}

exports.arch = function arch() {
  return binding.arch
}

exports.type = binding.type
exports.version = binding.version
exports.release = binding.release
exports.machine = binding.machine
exports.execPath = binding.execPath
exports.pid = binding.pid
exports.ppid = binding.ppid
exports.cwd = binding.cwd
exports.chdir = binding.chdir
exports.tmpdir = binding.tmpdir
exports.homedir = binding.homedir
exports.hostname = binding.hostname
exports.userInfo = binding.userInfo
exports.groupInfo = binding.groupInfo

exports.networkInterfaces = function networkInterfaces() {
  const result = {}

  for (const entry of binding.networkInterfaces()) {
    const { name, ...properties } = entry

    if (result[name]) result[name].push(properties)
    else result[name] = [properties]
  }

  return result
}

exports.kill = function kill(pid, signal = constants.signals.SIGTERM) {
  if (typeof signal === 'string') {
    if (signal in constants.signals === false) {
      throw errors.UNKNOWN_SIGNAL('Unknown signal: ' + signal)
    }

    signal = constants.signals[signal]
  }

  binding.kill(pid, signal)
}

exports.endianness = function endianness() {
  return binding.isLittleEndian ? 'LE' : 'BE'
}

exports.availableParallelism = binding.availableParallelism

exports.cpuUsage = function cpuUsage(previous) {
  const current = binding.cpuUsage()

  if (previous) {
    return {
      user: current.user - previous.user,
      system: current.system - previous.system
    }
  }

  return current
}

exports.threadCpuUsage = function threadCpuUsage(previous) {
  const current = binding.threadCpuUsage()

  if (previous) {
    return {
      user: current.user - previous.user,
      system: current.system - previous.system
    }
  }

  return current
}

exports.resourceUsage = binding.resourceUsage
exports.memoryUsage = binding.memoryUsage
exports.freemem = binding.freemem
exports.totalmem = binding.totalmem
exports.availableMemory = binding.availableMemory
exports.constrainedMemory = binding.constrainedMemory
exports.uptime = binding.uptime
exports.loadavg = binding.loadavg
exports.cpus = binding.cpus

exports.getProcessTitle = binding.getProcessTitle

exports.setProcessTitle = function setProcessTitle(title) {
  if (typeof title !== 'string') title = title.toString()

  if (title.length >= 256) {
    throw errors.TITLE_OVERFLOW('Process title is too long')
  }

  binding.setProcessTitle(title)
}

exports.getPriority = function getPriority(pid = 0) {
  return binding.getPriority(pid)
}

exports.setPriority = function setPriority(pid, priority) {
  if (priority === undefined) {
    priority = pid
    pid = 0
  }

  binding.setPriority(pid, priority)
}

exports.getEnvKeys = binding.getEnvKeys
exports.getEnv = binding.getEnv
exports.hasEnv = binding.hasEnv
exports.setEnv = binding.setEnv
exports.unsetEnv = binding.unsetEnv
const binding = require('../binding')

module.exports = {
  signals: binding.signals,
  errnos: binding.errnos,
  priority: binding.priority
}
module.exports = class OSError extends Error {
  constructor(msg, fn = OSError, code = fn.name) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'OSError'
  }

  static UNKNOWN_SIGNAL(msg) {
    return new OSError(msg, OSError.UNKNOWN_SIGNAL)
  }

  static TITLE_OVERFLOW(msg) {
    return new OSError(msg, OSError.TITLE_OVERFLOW)
  }
}
{
  "name": "bare-os",
  "version": "3.9.1",
  "description": "Operating system utilities for Bare",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    },
    "./errors": {
      "types": "./lib/errors.d.ts",
      "default": "./lib/errors.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-os.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-os/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-os#readme",
  "engines": {
    "bare": ">=1.14.0"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "cmake-bare": "^1.1.6",
    "lunte": "^1.6.0",
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
// This export SHOULD NOT be shortened in any way as having the full
// `module.exports = require(...)` statement is crucial for synthesizing
// ESM exports.

if (Bare.platform === 'win32') {
  module.exports = require('./lib/win32')
} else {
  module.exports = require('./lib/posix')
}
module.exports = {
  CHAR_UPPERCASE_A: 0x41,
  CHAR_LOWERCASE_A: 0x61,
  CHAR_UPPERCASE_Z: 0x5a,
  CHAR_LOWERCASE_Z: 0x7a,
  CHAR_DOT: 0x2e,
  CHAR_FORWARD_SLASH: 0x2f,
  CHAR_BACKWARD_SLASH: 0x5c,
  CHAR_COLON: 0x3a,
  CHAR_QUESTION_MARK: 0x3f
}
const os = require('bare-os')

const { normalizeString } = require('./shared')
const { CHAR_DOT, CHAR_FORWARD_SLASH } = require('./constants')

function isPosixPathSeparator(code) {
  return code === CHAR_FORWARD_SLASH
}

exports.win32 = require('./win32')
exports.posix = exports

exports.sep = '/'
exports.delimiter = ':'

exports.resolve = function resolve(...args) {
  let resolvedPath = ''
  let resolvedAbsolute = false

  for (let i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) {
    const path = i >= 0 ? args[i] : os.cwd()

    if (path.length === 0) {
      continue
    }

    resolvedPath = `${path}/${resolvedPath}`
    resolvedAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH
  }

  resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute, '/', isPosixPathSeparator)

  if (resolvedAbsolute) {
    return `/${resolvedPath}`
  }

  return resolvedPath.length > 0 ? resolvedPath : '.'
}

exports.normalize = function normalize(path) {
  if (path.length === 0) return '.'

  const isAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH
  const trailingSeparator = path.charCodeAt(path.length - 1) === CHAR_FORWARD_SLASH

  path = normalizeString(path, !isAbsolute, '/', isPosixPathSeparator)

  if (path.length === 0) {
    if (isAbsolute) return '/'
    return trailingSeparator ? './' : '.'
  }

  if (trailingSeparator) path += '/'

  return isAbsolute ? `/${path}` : path
}

exports.isAbsolute = function isAbsolute(path) {
  return path.length > 0 && path.charCodeAt(0) === CHAR_FORWARD_SLASH
}

exports.join = function join(...args) {
  if (args.length === 0) return '.'
  let joined
  for (let i = 0; i < args.length; ++i) {
    const arg = args[i]
    if (arg.length > 0) {
      if (joined === undefined) joined = arg
      else joined += `/${arg}`
    }
  }
  if (joined === undefined) return '.'
  return exports.normalize(joined)
}

exports.relative = function relative(from, to) {
  if (from === to) return ''

  from = exports.resolve(from)
  to = exports.resolve(to)

  if (from === to) return ''

  const fromStart = 1
  const fromEnd = from.length
  const fromLen = fromEnd - fromStart
  const toStart = 1
  const toLen = to.length - toStart

  const length = fromLen < toLen ? fromLen : toLen
  let lastCommonSep = -1
  let i = 0
  for (; i < length; i++) {
    const fromCode = from.charCodeAt(fromStart + i)
    if (fromCode !== to.charCodeAt(toStart + i)) {
      break
    } else if (fromCode === CHAR_FORWARD_SLASH) {
      lastCommonSep = i
    }
  }
  if (i === length) {
    if (toLen > length) {
      if (to.charCodeAt(toStart + i) === CHAR_FORWARD_SLASH) {
        return to.substring(toStart + i + 1)
      }
      if (i === 0) {
        return to.substring(toStart + i)
      }
    } else if (fromLen > length) {
      if (from.charCodeAt(fromStart + i) === CHAR_FORWARD_SLASH) {
        lastCommonSep = i
      } else if (i === 0) {
        lastCommonSep = 0
      }
    }
  }

  let out = ''
  for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
    if (i === fromEnd || from.charCodeAt(i) === CHAR_FORWARD_SLASH) {
      out += out.length === 0 ? '..' : '/..'
    }
  }

  return `${out}${to.substring(toStart + lastCommonSep)}`
}

exports.toNamespacedPath = function toNamespacedPath(path) {
  return path
}

exports.dirname = function dirname(path) {
  if (path.length === 0) return '.'
  const hasRoot = path.charCodeAt(0) === CHAR_FORWARD_SLASH
  let end = -1
  let matchedSlash = true
  for (let i = path.length - 1; i >= 1; --i) {
    if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) {
      if (!matchedSlash) {
        end = i
        break
      }
    } else {
      matchedSlash = false
    }
  }

  if (end === -1) return hasRoot ? '/' : '.'
  if (hasRoot && end === 1) return '//'
  return path.substring(0, end)
}

exports.basename = function basename(path, suffix) {
  let start = 0
  let end = -1
  let matchedSlash = true

  if (suffix !== undefined && suffix.length > 0 && suffix.length <= path.length) {
    if (suffix === path) {
      return ''
    }
    let extIdx = suffix.length - 1
    let firstNonSlashEnd = -1
    for (let i = path.length - 1; i >= 0; --i) {
      const code = path.charCodeAt(i)
      if (code === CHAR_FORWARD_SLASH) {
        if (!matchedSlash) {
          start = i + 1
          break
        }
      } else {
        if (firstNonSlashEnd === -1) {
          matchedSlash = false
          firstNonSlashEnd = i + 1
        }
        if (extIdx >= 0) {
          if (code === suffix.charCodeAt(extIdx)) {
            if (--extIdx === -1) {
              end = i
            }
          } else {
            extIdx = -1
            end = firstNonSlashEnd
          }
        }
      }
    }

    if (start === end) end = firstNonSlashEnd
    else if (end === -1) end = path.length
    return path.substring(start, end)
  }

  for (let i = path.length - 1; i >= 0; --i) {
    if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) {
      if (!matchedSlash) {
        start = i + 1
        break
      }
    } else if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
  }

  if (end === -1) return ''
  return path.substring(start, end)
}

exports.extname = function extname(path) {
  let startDot = -1
  let startPart = 0
  let end = -1
  let matchedSlash = true
  let preDotState = 0
  for (let i = path.length - 1; i >= 0; --i) {
    const code = path.charCodeAt(i)
    if (code === CHAR_FORWARD_SLASH) {
      if (!matchedSlash) {
        startPart = i + 1
        break
      }
      continue
    }
    if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
    if (code === CHAR_DOT) {
      if (startDot === -1) startDot = i
      else if (preDotState !== 1) preDotState = 1
    } else if (startDot !== -1) {
      preDotState = -1
    }
  }

  if (
    startDot === -1 ||
    end === -1 ||
    preDotState === 0 ||
    (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1)
  ) {
    return ''
  }
  return path.substring(startDot, end)
}
const { CHAR_DOT, CHAR_FORWARD_SLASH } = require('./constants')

exports.normalizeString = function normalizeString(
  path,
  allowAboveRoot,
  separator,
  isPathSeparator
) {
  let res = ''
  let lastSegmentLength = 0
  let lastSlash = -1
  let dots = 0
  let code = 0
  for (let i = 0; i <= path.length; ++i) {
    if (i < path.length) {
      code = path.charCodeAt(i)
    } else if (isPathSeparator(code)) {
      break
    } else {
      code = CHAR_FORWARD_SLASH
    }

    if (isPathSeparator(code)) {
      if (lastSlash === i - 1 || dots === 1);
      else if (dots === 2) {
        if (
          res.length < 2 ||
          lastSegmentLength !== 2 ||
          res.charCodeAt(res.length - 1) !== CHAR_DOT ||
          res.charCodeAt(res.length - 2) !== CHAR_DOT
        ) {
          if (res.length > 2) {
            const lastSlashIndex = res.lastIndexOf(separator)
            if (lastSlashIndex === -1) {
              res = ''
              lastSegmentLength = 0
            } else {
              res = res.substring(0, lastSlashIndex)
              lastSegmentLength = res.length - 1 - res.lastIndexOf(separator)
            }
            lastSlash = i
            dots = 0
            continue
          } else if (res.length !== 0) {
            res = ''
            lastSegmentLength = 0
            lastSlash = i
            dots = 0
            continue
          }
        }
        if (allowAboveRoot) {
          res += res.length > 0 ? `${separator}..` : '..'
          lastSegmentLength = 2
        }
      } else {
        if (res.length > 0) {
          res += `${separator}${path.substring(lastSlash + 1, i)}`
        } else {
          res = path.substring(lastSlash + 1, i)
        }
        lastSegmentLength = i - lastSlash - 1
      }
      lastSlash = i
      dots = 0
    } else if (code === CHAR_DOT && dots !== -1) {
      ++dots
    } else {
      dots = -1
    }
  }
  return res
}
const os = require('bare-os')

const { normalizeString } = require('./shared')
const {
  CHAR_UPPERCASE_A,
  CHAR_LOWERCASE_A,
  CHAR_UPPERCASE_Z,
  CHAR_LOWERCASE_Z,
  CHAR_DOT,
  CHAR_FORWARD_SLASH,
  CHAR_BACKWARD_SLASH,
  CHAR_COLON,
  CHAR_QUESTION_MARK
} = require('./constants')

function isWindowsPathSeparator(code) {
  return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH
}

function isWindowsDeviceRoot(code) {
  return (
    (code >= CHAR_UPPERCASE_A && code <= CHAR_UPPERCASE_Z) ||
    (code >= CHAR_LOWERCASE_A && code <= CHAR_LOWERCASE_Z)
  )
}

exports.posix = require('./posix')
exports.win32 = exports

exports.sep = '\\'
exports.delimiter = ';'

exports.resolve = function resolve(...args) {
  let resolvedDevice = ''
  let resolvedTail = ''
  let resolvedAbsolute = false

  for (let i = args.length - 1; i >= -1; i--) {
    let path
    if (i >= 0) {
      path = args[i]

      if (path.length === 0) continue
    } else if (resolvedDevice.length === 0) {
      path = os.cwd()
    } else {
      path = os.getEnv(`=${resolvedDevice}`) || os.cwd()

      if (
        path === undefined ||
        (path.substring(0, 2).toLowerCase() !== resolvedDevice.toLowerCase() &&
          path.charCodeAt(2) === CHAR_BACKWARD_SLASH)
      ) {
        path = `${resolvedDevice}\\`
      }
    }

    const len = path.length
    let rootEnd = 0
    let device = ''
    let isAbsolute = false
    const code = path.charCodeAt(0)

    if (len === 1) {
      if (isWindowsPathSeparator(code)) {
        rootEnd = 1
        isAbsolute = true
      }
    } else if (isWindowsPathSeparator(code)) {
      isAbsolute = true

      if (isWindowsPathSeparator(path.charCodeAt(1))) {
        let j = 2
        let last = j
        while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
          j++
        }
        if (j < len && j !== last) {
          const firstPart = path.substring(last, j)
          last = j
          while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
            j++
          }
          if (j < len && j !== last) {
            last = j
            while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
              j++
            }
            if (j === len || j !== last) {
              device = `\\\\${firstPart}\\${path.substring(last, j)}`
              rootEnd = j
            }
          }
        }
      } else {
        rootEnd = 1
      }
    } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
      device = path.substring(0, 2)
      rootEnd = 2
      if (len > 2 && isWindowsPathSeparator(path.charCodeAt(2))) {
        isAbsolute = true
        rootEnd = 3
      }
    }

    if (device.length > 0) {
      if (resolvedDevice.length > 0) {
        if (device.toLowerCase() !== resolvedDevice.toLowerCase()) {
          continue
        }
      } else {
        resolvedDevice = device
      }
    }

    if (resolvedAbsolute) {
      if (resolvedDevice.length > 0) {
        break
      }
    } else {
      resolvedTail = `${path.substring(rootEnd)}\\${resolvedTail}`
      resolvedAbsolute = isAbsolute
      if (isAbsolute && resolvedDevice.length > 0) {
        break
      }
    }
  }

  resolvedTail = normalizeString(resolvedTail, !resolvedAbsolute, '\\', isWindowsPathSeparator)

  return resolvedAbsolute
    ? `${resolvedDevice}\\${resolvedTail}`
    : `${resolvedDevice}${resolvedTail}` || '.'
}

exports.normalize = function normalize(path) {
  const len = path.length
  if (len === 0) return '.'
  let rootEnd = 0
  let device
  let isAbsolute = false
  const code = path.charCodeAt(0)

  if (len === 1) {
    return code === CHAR_FORWARD_SLASH ? '\\' : path
  }

  if (isWindowsPathSeparator(code)) {
    isAbsolute = true

    if (isWindowsPathSeparator(path.charCodeAt(1))) {
      let j = 2
      let last = j
      while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
        j++
      }
      if (j < len && j !== last) {
        const firstPart = path.substring(last, j)
        last = j
        while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
          j++
        }
        if (j < len && j !== last) {
          last = j
          while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
            j++
          }
          if (j === len) {
            return `\\\\${firstPart}\\${path.substring(last)}\\`
          }
          if (j !== last) {
            device = `\\\\${firstPart}\\${path.substring(last, j)}`
            rootEnd = j
          }
        }
      }
    } else {
      rootEnd = 1
    }
  } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
    device = path.substring(0, 2)
    rootEnd = 2
    if (len > 2 && isWindowsPathSeparator(path.charCodeAt(2))) {
      isAbsolute = true
      rootEnd = 3
    }
  }

  let tail =
    rootEnd < len
      ? normalizeString(path.substring(rootEnd), !isAbsolute, '\\', isWindowsPathSeparator)
      : ''
  if (tail.length === 0 && !isAbsolute) {
    tail = '.'
  }
  if (tail.length > 0 && isWindowsPathSeparator(path.charCodeAt(len - 1))) {
    tail += '\\'
  }
  if (device === undefined) {
    return isAbsolute ? `\\${tail}` : tail
  }
  return isAbsolute ? `${device}\\${tail}` : `${device}${tail}`
}

exports.isAbsolute = function isAbsolute(path) {
  const len = path.length
  if (len === 0) return false

  const code = path.charCodeAt(0)

  return (
    isWindowsPathSeparator(code) ||
    (len > 2 &&
      isWindowsDeviceRoot(code) &&
      path.charCodeAt(1) === CHAR_COLON &&
      isWindowsPathSeparator(path.charCodeAt(2)))
  )
}

exports.join = function join(...args) {
  if (args.length === 0) return '.'

  let joined
  let firstPart
  for (let i = 0; i < args.length; ++i) {
    const arg = args[i]
    if (arg.length > 0) {
      if (joined === undefined) joined = firstPart = arg
      else joined += `\\${arg}`
    }
  }

  if (joined === undefined) return '.'

  let needsReplace = true
  let slashCount = 0
  if (isWindowsPathSeparator(firstPart.charCodeAt(0))) {
    ++slashCount
    const firstLen = firstPart.length
    if (firstLen > 1 && isWindowsPathSeparator(firstPart.charCodeAt(1))) {
      ++slashCount
      if (firstLen > 2) {
        if (isWindowsPathSeparator(firstPart.charCodeAt(2))) {
          ++slashCount
        } else {
          needsReplace = false
        }
      }
    }
  }
  if (needsReplace) {
    while (slashCount < joined.length && isWindowsPathSeparator(joined.charCodeAt(slashCount))) {
      slashCount++
    }

    if (slashCount >= 2) {
      joined = `\\${joined.substring(slashCount)}`
    }
  }

  return exports.normalize(joined)
}

exports.relative = function relative(from, to) {
  if (from === to) return ''

  const fromOrig = exports.resolve(from)
  const toOrig = exports.resolve(to)

  if (fromOrig === toOrig) return ''

  from = fromOrig.toLowerCase()
  to = toOrig.toLowerCase()

  if (from === to) return ''

  let fromStart = 0
  while (fromStart < from.length && from.charCodeAt(fromStart) === CHAR_BACKWARD_SLASH) {
    fromStart++
  }
  let fromEnd = from.length
  while (fromEnd - 1 > fromStart && from.charCodeAt(fromEnd - 1) === CHAR_BACKWARD_SLASH) {
    fromEnd--
  }
  const fromLen = fromEnd - fromStart

  let toStart = 0
  while (toStart < to.length && to.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) {
    toStart++
  }
  let toEnd = to.length
  while (toEnd - 1 > toStart && to.charCodeAt(toEnd - 1) === CHAR_BACKWARD_SLASH) {
    toEnd--
  }
  const toLen = toEnd - toStart

  const length = fromLen < toLen ? fromLen : toLen
  let lastCommonSep = -1
  let i = 0
  for (; i < length; i++) {
    const fromCode = from.charCodeAt(fromStart + i)
    if (fromCode !== to.charCodeAt(toStart + i)) {
      break
    } else if (fromCode === CHAR_BACKWARD_SLASH) {
      lastCommonSep = i
    }
  }

  if (i !== length) {
    if (lastCommonSep === -1) return toOrig
  } else {
    if (toLen > length) {
      if (to.charCodeAt(toStart + i) === CHAR_BACKWARD_SLASH) {
        return toOrig.substring(toStart + i + 1)
      }
      if (i === 2) {
        return toOrig.substring(toStart + i)
      }
    }
    if (fromLen > length) {
      if (from.charCodeAt(fromStart + i) === CHAR_BACKWARD_SLASH) {
        lastCommonSep = i
      } else if (i === 2) {
        lastCommonSep = 3
      }
    }
    if (lastCommonSep === -1) lastCommonSep = 0
  }

  let out = ''
  for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
    if (i === fromEnd || from.charCodeAt(i) === CHAR_BACKWARD_SLASH) {
      out += out.length === 0 ? '..' : '\\..'
    }
  }

  toStart += lastCommonSep

  if (out.length > 0) {
    return `${out}${toOrig.substring(toStart, toEnd)}`
  }
  if (toOrig.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) {
    ++toStart
  }
  return toOrig.substring(toStart, toEnd)
}

exports.toNamespacedPath = function toNamespacedPath(path) {
  if (path.length === 0) return path

  const resolvedPath = exports.resolve(path)

  if (resolvedPath.length <= 2) return path

  if (resolvedPath.charCodeAt(0) === CHAR_BACKWARD_SLASH) {
    if (resolvedPath.charCodeAt(1) === CHAR_BACKWARD_SLASH) {
      const code = resolvedPath.charCodeAt(2)
      if (code !== CHAR_QUESTION_MARK && code !== CHAR_DOT) {
        return `\\\\?\\UNC\\${resolvedPath.substring(2)}`
      }
    }
  } else if (
    isWindowsDeviceRoot(resolvedPath.charCodeAt(0)) &&
    resolvedPath.charCodeAt(1) === CHAR_COLON &&
    resolvedPath.charCodeAt(2) === CHAR_BACKWARD_SLASH
  ) {
    return `\\\\?\\${resolvedPath}`
  }

  return path
}

exports.dirname = function dirname(path) {
  const len = path.length
  if (len === 0) return '.'
  let rootEnd = -1
  let offset = 0
  const code = path.charCodeAt(0)

  if (len === 1) {
    return isWindowsPathSeparator(code) ? path : '.'
  }

  if (isWindowsPathSeparator(code)) {
    rootEnd = offset = 1

    if (isWindowsPathSeparator(path.charCodeAt(1))) {
      let j = 2
      let last = j
      while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
        j++
      }
      if (j < len && j !== last) {
        last = j
        while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
          j++
        }
        if (j < len && j !== last) {
          last = j
          while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
            j++
          }
          if (j === len) {
            return path
          }
          if (j !== last) {
            rootEnd = offset = j + 1
          }
        }
      }
    }
  } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
    rootEnd = len > 2 && isWindowsPathSeparator(path.charCodeAt(2)) ? 3 : 2
    offset = rootEnd
  }

  let end = -1
  let matchedSlash = true
  for (let i = len - 1; i >= offset; --i) {
    if (isWindowsPathSeparator(path.charCodeAt(i))) {
      if (!matchedSlash) {
        end = i
        break
      }
    } else {
      matchedSlash = false
    }
  }

  if (end === -1) {
    if (rootEnd === -1) return '.'

    end = rootEnd
  }
  return path.substring(0, end)
}

exports.basename = function basename(path, suffix) {
  let start = 0
  let end = -1
  let matchedSlash = true

  if (
    path.length >= 2 &&
    isWindowsDeviceRoot(path.charCodeAt(0)) &&
    path.charCodeAt(1) === CHAR_COLON
  ) {
    start = 2
  }

  if (suffix !== undefined && suffix.length > 0 && suffix.length <= path.length) {
    if (suffix === path) return ''
    let extIdx = suffix.length - 1
    let firstNonSlashEnd = -1
    for (let i = path.length - 1; i >= start; --i) {
      const code = path.charCodeAt(i)
      if (isWindowsPathSeparator(code)) {
        if (!matchedSlash) {
          start = i + 1
          break
        }
      } else {
        if (firstNonSlashEnd === -1) {
          matchedSlash = false
          firstNonSlashEnd = i + 1
        }
        if (extIdx >= 0) {
          if (code === suffix.charCodeAt(extIdx)) {
            if (--extIdx === -1) {
              end = i
            }
          } else {
            extIdx = -1
            end = firstNonSlashEnd
          }
        }
      }
    }

    if (start === end) end = firstNonSlashEnd
    else if (end === -1) end = path.length
    return path.substring(start, end)
  }
  for (let i = path.length - 1; i >= start; --i) {
    if (isWindowsPathSeparator(path.charCodeAt(i))) {
      if (!matchedSlash) {
        start = i + 1
        break
      }
    } else if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
  }

  if (end === -1) return ''
  return path.substring(start, end)
}

exports.extname = function extname(path) {
  let start = 0
  let startDot = -1
  let startPart = 0
  let end = -1
  let matchedSlash = true
  let preDotState = 0

  if (
    path.length >= 2 &&
    path.charCodeAt(1) === CHAR_COLON &&
    isWindowsDeviceRoot(path.charCodeAt(0))
  ) {
    start = startPart = 2
  }

  for (let i = path.length - 1; i >= start; --i) {
    const code = path.charCodeAt(i)
    if (isWindowsPathSeparator(code)) {
      if (!matchedSlash) {
        startPart = i + 1
        break
      }
      continue
    }
    if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
    if (code === CHAR_DOT) {
      if (startDot === -1) startDot = i
      else if (preDotState !== 1) preDotState = 1
    } else if (startDot !== -1) {
      preDotState = -1
    }
  }

  if (
    startDot === -1 ||
    end === -1 ||
    preDotState === 0 ||
    (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1)
  ) {
    return ''
  }
  return path.substring(startDot, end)
}
{
  "name": "bare-path",
  "version": "3.0.1",
  "description": "Path manipulation library for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./posix": "./lib/posix.js",
    "./win32": "./lib/win32.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "lib",
    "NOTICE"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-path.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-path/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-path#readme",
  "dependencies": {
    "bare-os": "^3.0.1"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "lunte": "^1.8.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
const b4a = require('b4a')
const stream = require('streamx')
const { ReadableStream, WritableStream } = require('./web')

const defaultEncoding = 'utf8'

module.exports = exports = stream.Stream

exports.pipeline = stream.pipeline

exports.isStream = stream.isStream
exports.isEnding = stream.isEnding
exports.isEnded = stream.isEnded
exports.isFinishing = stream.isFinishing
exports.isFinished = stream.isFinished
exports.isDisturbed = stream.isDisturbed

exports.isErrored = function isErrored(stream) {
  return exports.getStreamError(stream) !== null
}

exports.isReadable = function isReadable(stream) {
  return stream.readable && !stream.destroying && !exports.isEnded(stream)
}

exports.isWritable = function isWritable(stream) {
  return stream.writable && !stream.destroying && !exports.isFinishing(stream)
}

exports.getStreamError = stream.getStreamError

exports.addAbortSignal = function addAbortSignal(signal, stream) {
  function onAbort() {
    stream.destroy(signal.reason)
  }

  if (signal.aborted) onAbort()
  else signal.addEventListener('abort', onAbort)

  return stream
}

exports.Stream = exports

exports.Readable = class Readable extends stream.Readable {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthReadable: null,
      map: null,
      mapReadable: null
    })

    if (this._construct) this._open = this._construct

    if (this._read !== stream.Readable.prototype._read) {
      this._read = read.bind(this, this._read)
    }

    if (this._destroy !== stream.Stream.prototype._destroy) {
      this._destroy = destroy.bind(this, this._destroy)
    }
  }

  get closed() {
    return !exports.isReadable(this)
  }

  get errored() {
    return stream.getStreamError(this)
  }

  push(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    return super.push(chunk)
  }

  unshift(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    super.unshift(chunk)
  }

  static fromWeb(readableStream, opts = {}) {
    const stream = readableStream._stream

    if (opts.encoding) stream.setEncoding(opts.encoding)
    if (opts.signal) exports.addAbortSignal(opts.signal, stream)

    return stream
  }

  static toWeb(readable, opts = {}) {
    return new ReadableStream(readable, opts.strategy)
  }

  async [Symbol.asyncDispose]() {
    if (!this.destroyed) this.destroy()

    await new Promise((resolve) => exports.finished(this, resolve))
  }
}

exports.Writable = class Writable extends stream.Writable {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthWritable,
      map: null,
      mapWritable: null
    })

    if (this._construct) this._open = this._construct

    if (this._write !== stream.Writable.prototype._write) {
      this._write = write.bind(this, this._write)
    }

    if (this._destroy !== stream.Stream.prototype._destroy) {
      this._destroy = destroy.bind(this, this._destroy)
    }
  }

  get closed() {
    return !exports.isWritable(this)
  }

  get errored() {
    return stream.getStreamError(this)
  }

  write(chunk, encoding, cb) {
    if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result = super.write({ chunk, encoding })

    if (cb) stream.Writable.drained(this).then(() => cb(null), cb)

    return result
  }

  end(chunk, encoding, cb) {
    if (typeof chunk === 'function') {
      cb = chunk
      chunk = null
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    } else {
      encoding = 'buffer'
    }

    const result =
      chunk !== undefined && chunk !== null ? super.end({ chunk, encoding }) : super.end()

    if (cb) this.once('finish', () => cb(null))

    return result
  }

  static fromWeb(writableStream, opts = {}) {
    const stream = writableStream._stream

    if (opts.signal) exports.addAbortSignal(opts.signal, stream)

    return stream
  }

  static toWeb(writable) {
    return new WritableStream(writable)
  }

  async [Symbol.asyncDispose]() {
    if (!this.destroyed) this.destroy()

    await new Promise((resolve) => exports.finished(this, resolve))
  }
}

exports.Duplex = class Duplex extends stream.Duplex {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthReadable: null,
      byteLengthWritable,
      map: null,
      mapReadable: null,
      mapWritable: null
    })

    if (this._construct) this._open = this._construct

    if (this._read !== stream.Readable.prototype._read) {
      this._read = read.bind(this, this._read)
    }

    if (this._write !== stream.Duplex.prototype._write) {
      this._write = write.bind(this, this._write)
    }

    if (this._destroy !== stream.Stream.prototype._destroy) {
      this._destroy = destroy.bind(this, this._destroy)
    }
  }

  push(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    return super.push(chunk)
  }

  unshift(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    super.unshift(chunk)
  }

  write(chunk, encoding, cb) {
    if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result = super.write({ chunk, encoding })

    if (cb) stream.Writable.drained(this).then(() => cb(null), cb)

    return result
  }

  end(chunk, encoding, cb) {
    if (typeof chunk === 'function') {
      cb = chunk
      chunk = null
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result =
      chunk !== undefined && chunk !== null ? super.end({ chunk, encoding }) : super.end()

    if (cb) this.once('finish', () => cb(null))

    return result
  }

  static fromWeb({ readable: readableStream, writable: writableStream }, opts) {
    const readable = exports.Readable.fromWeb(readableStream, opts)
    const writable = exports.Writable.fromWeb(writableStream, opts)

    const duplex = new exports.Duplex({
      write(data, encoding, cb) {
        writable.write(data, encoding, cb)
      }
    })

    readable
      .on('data', (data) => duplex.push(data))
      .on('end', () => duplex.push(null))
      .on('error', (err) => duplex.destroy(err))

    writable.on('finish', () => duplex.end()).on('error', (err) => duplex.destroy(err))

    return duplex
  }

  static toWeb(duplex) {
    const readableStream = exports.Readable.toWeb(duplex)
    const writableStream = exports.Writable.toWeb(duplex)

    return { readable: readableStream, writable: writableStream }
  }
}

class DuplexSide extends exports.Duplex {
  constructor(opts) {
    super(opts)

    this._otherSide = null
    this._cb = null
  }

  _read() {
    const cb = this._cb
    if (!cb) return

    this._cb = null
    cb()
  }

  _write(chunk, encoding, cb) {
    this._otherSide.push(chunk, encoding)
    this._otherSide._cb = cb
  }

  _final(cb) {
    this._otherSide.on('end', cb)
    this._otherSide.push(null)
  }
}

exports.duplexPair = function duplexPair(opts) {
  const sideA = new DuplexSide(opts)
  const sideB = new DuplexSide(opts)

  sideA._otherSide = sideB
  sideB._otherSide = sideA

  return [sideA, sideB]
}

exports.Transform = class Transform extends stream.Transform {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthReadable: null,
      byteLengthWritable,
      map: null,
      mapReadable: null,
      mapWritable: null
    })

    if (this._transform !== stream.Transform.prototype._transform) {
      this._transform = transform.bind(this, this._transform)
    } else {
      this._transform = passthrough
    }
  }

  push(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    return super.push(chunk)
  }

  unshift(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    super.unshift(chunk)
  }

  write(chunk, encoding, cb) {
    if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result = super.write({ chunk, encoding })

    if (cb) stream.Writable.drained(this).then(() => cb(null), cb)

    return result
  }

  end(chunk, encoding, cb) {
    if (typeof chunk === 'function') {
      cb = chunk
      chunk = null
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result =
      chunk !== undefined && chunk !== null ? super.end({ chunk, encoding }) : super.end()

    if (cb) this.once('finish', () => cb(null))

    return result
  }
}

exports.PassThrough = class PassThrough extends exports.Transform {}

exports.finished = function finished(stream, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (!opts) opts = {}

  const { cleanup = false } = opts

  const done = () => {
    cb(exports.getStreamError(stream, { all: true }))

    if (cleanup) detach()
  }

  const detach = () => {
    stream.off('close', done)
    stream.off('error', noop)
  }

  if (stream.destroyed) {
    done()
  } else {
    stream.on('close', done)
    stream.on('error', noop)
  }

  return detach
}

function read(read, cb) {
  read.call(this, 65536)

  cb(null)
}

function write(write, data, cb) {
  write.call(this, data.chunk, data.encoding, cb)
}

function transform(transform, data, cb) {
  transform.call(this, data.chunk, data.encoding, cb)
}

function destroy(destroy, cb) {
  destroy.call(this, exports.getStreamError(this), cb)
}

function passthrough(data, cb) {
  cb(null, data.chunk)
}

function byteLengthWritable(data) {
  return data.chunk.byteLength
}

function noop() {}
{
  "name": "bare-stream",
  "version": "2.13.3",
  "description": "Streaming data for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./promises": "./promises.js",
    "./web": {
      "types": "./web.d.ts",
      "default": "./web.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "promises.js",
    "web.js",
    "web.d.ts",
    "global.js",
    "global.d.ts"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-stream.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-stream/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-stream#readme",
  "dependencies": {
    "b4a": "^1.8.1",
    "streamx": "^2.25.0",
    "teex": "^1.0.1"
  },
  "devDependencies": {
    "bare-abort-controller": "^1.1.0",
    "bare-buffer": "^3.0.0",
    "bare-events": "^2.5.4",
    "brittle": "^3.5.2",
    "lunte": "^1.6.0",
    "prettier": "^3.3.3",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "bare-abort-controller": "*",
    "bare-buffer": "*",
    "bare-events": "*"
  },
  "peerDependenciesMeta": {
    "bare-abort-controller": {
      "optional": true
    },
    "bare-buffer": {
      "optional": true
    },
    "bare-events": {
      "optional": true
    }
  }
}
const { Readable, Writable, Transform, getStreamError, isStreamx, isDisturbed } = require('streamx')
const tee = require('teex')

const readableKind = Symbol.for('bare.stream.readable.kind')
const writableKind = Symbol.for('bare.stream.writable.kind')
const transformKind = Symbol.for('bare.stream.transform.kind')

// https://streams.spec.whatwg.org/#readablestreamdefaultreader
exports.ReadableStreamDefaultReader = class ReadableStreamDefaultReader {
  constructor(stream) {
    this._stream = stream
    this._stream._stream.once('close', onclose).once('error', onerror)

    const closed = Promise.withResolvers()

    // Avoid unhandled exceptions
    closed.promise.catch(noop)

    this._closed = closed

    function onclose() {
      closed.resolve()
    }

    function onerror(err) {
      closed.reject(err)
    }
  }

  get closed() {
    return this._closed.promise
  }

  read() {
    const stream = this._stream._stream

    return new Promise((resolve, reject) => {
      const err = getStreamError(stream)

      if (err) return reject(err)

      if (stream.destroyed) {
        return resolve({ value: undefined, done: true })
      }

      const value = stream.read()

      if (value !== null) {
        return resolve({ value, done: false })
      }

      stream.once('readable', onreadable).once('close', onclose).once('error', onerror)

      function onreadable() {
        const value = stream.read()

        ondone(null, value === null ? { value: undefined, done: true } : { value, done: false })
      }

      function onclose() {
        ondone(null, { value: undefined, done: true })
      }

      function onerror(err) {
        ondone(err, null)
      }

      function ondone(err, value) {
        stream.off('readable', onreadable).off('close', onclose).off('error', onerror)

        if (err) reject(err)
        else resolve(value)
      }
    })
  }

  releaseLock() {
    this._closed.reject(new TypeError('Reader was released'))
    this._stream._releaseLock()
    this._stream = null
  }

  cancel(reason = new TypeError('Stream was cancelled')) {
    const stream = this._stream._stream

    if (stream.destroyed) return Promise.resolve()

    return new Promise((resolve) =>
      stream.once('close', resolve).once('error', noop).destroy(reason)
    )
  }
}

// https://streams.spec.whatwg.org/#readablestreamdefaultcontroller
exports.ReadableStreamDefaultController = class ReadableStreamDefaultController {
  constructor(stream) {
    this._stream = stream
  }

  get desiredSize() {
    const stream = this._stream._stream

    return stream._readableState.highWaterMark - stream._readableState.buffered
  }

  enqueue(data) {
    this._stream._stream.push(data)
  }

  close() {
    this._stream._stream.push(null)
  }

  error(err) {
    this._stream._stream.destroy(err)
  }
}

// https://streams.spec.whatwg.org/#readablestream
class ReadableStream {
  static get [readableKind]() {
    return 0 // Compatibility version
  }

  static from(iterable) {
    return new ReadableStream(Readable.from(iterable))
  }

  constructor(underlyingSource = {}, queuingStrategy) {
    if (isStreamx(underlyingSource)) {
      this._stream = underlyingSource
    } else {
      if (queuingStrategy === undefined) {
        queuingStrategy = new exports.CountQueuingStrategy()
      }

      const { start, pull, cancel } = underlyingSource
      const { highWaterMark = 1, size = defaultSize } = queuingStrategy

      this._stream = new Readable({ highWaterMark, byteLength: size })

      const controller = new exports.ReadableStreamDefaultController(this)

      try {
        let starting = Promise.resolve()

        if (start) starting = forwardError(start.call(this, controller), controller)

        if (pull) {
          this._stream._read = this._read.bind(this, starting, pull.bind(this, controller))
        }

        if (cancel) {
          this._stream.once('error', cancel.bind(this))
        }
      } catch (err) {
        controller.error(err)
      }
    }

    this._reader = null
  }

  get [readableKind]() {
    return ReadableStream[readableKind]
  }

  get locked() {
    return this._reader !== null
  }

  getReader() {
    if (this.locked) throw new TypeError('Stream is locked')

    this._reader = new exports.ReadableStreamDefaultReader(this)

    return this._reader
  }

  cancel(reason = new TypeError('Stream was cancelled')) {
    const stream = this._stream

    if (stream.destroyed) return Promise.resolve()

    if (this.locked) return Promise.reject(new TypeError('Stream is locked'))

    return new Promise((resolve) =>
      stream.once('close', resolve).once('error', noop).destroy(reason)
    )
  }

  tee() {
    const [a, b] = tee(this._stream)

    return [new ReadableStream(a), new ReadableStream(b)]
  }

  pipeTo(destination) {
    return new Promise((resolve, reject) =>
      this._stream.pipe(destination._stream, (err) => {
        err ? reject(err) : resolve()
      })
    )
  }

  [Symbol.asyncIterator]() {
    return this._stream[Symbol.asyncIterator]()
  }

  _releaseLock() {
    this._reader = null
  }

  async _read(starting, pull, cb) {
    await starting

    let err = null
    try {
      await pull()
    } catch (e) {
      err = e
    }
    cb(err)
  }
}

function defaultSize() {
  return 1
}

exports.ReadableStream = ReadableStream

// https://streams.spec.whatwg.org/#countqueuingstrategy
exports.CountQueuingStrategy = class CountQueuingStrategy {
  constructor(opts = {}) {
    const { highWaterMark = 1 } = opts

    this.highWaterMark = highWaterMark
  }

  size(chunk) {
    return 1
  }
}

// https://streams.spec.whatwg.org/#bytelengthqueuingstrategy
exports.ByteLengthQueuingStrategy = class ByteLengthQueuingStrategy {
  constructor(opts = {}) {
    const { highWaterMark = 16384 } = opts

    this.highWaterMark = highWaterMark
  }

  size(chunk) {
    return chunk.byteLength
  }
}

exports.isReadableStream = function isReadableStream(value) {
  if (value instanceof ReadableStream) return true

  return (
    typeof value === 'object' &&
    value !== null &&
    value[readableKind] === ReadableStream[readableKind]
  )
}

// https://streams.spec.whatwg.org/#readablestream-errored
exports.isReadableStreamErrored = function isReadableStreamErrored(stream) {
  return getStreamError(stream._stream) !== null
}

// https://streams.spec.whatwg.org/#is-readable-stream-disturbed
exports.isReadableStreamDisturbed = function isReadableStreamDisturbed(stream) {
  return isDisturbed(stream._stream)
}

// https://streams.spec.whatwg.org/#writablestreamdefaultwriter
exports.WritableStreamDefaultWriter = class WritableStreamDefaultWriter {
  constructor(stream) {
    this._stream = stream
    this._stream._stream.once('close', onclose).once('error', onerror)

    const closed = Promise.withResolvers()

    // Avoid unhandled exceptions
    closed.promise.catch(noop)

    this._closed = closed

    function onclose() {
      closed.resolve()
    }

    function onerror(err) {
      closed.reject(err)
    }
  }

  get desiredSize() {
    const stream = this._stream._stream

    return stream._writableState.highWaterMark - stream._writableState.buffered
  }

  get closed() {
    return this._closed.promise
  }

  get ready() {
    const stream = this._stream._stream

    if (getStreamError(stream)) return Promise.reject()

    return Writable.drained(stream).then()
  }

  async write(chunk) {
    const stream = this._stream._stream

    let err = getStreamError(stream)
    if (err) return Promise.reject(err)

    stream.write(chunk)

    await Writable.drained(stream)

    err = getStreamError(stream)
    if (err) return Promise.reject(err)
  }

  releaseLock() {
    this._closed.reject(new TypeError('Writer was released'))
    this._stream._releaseLock()
    this._stream = null
  }

  close() {
    const stream = this._stream._stream

    if (stream.destroyed) return Promise.resolve()

    return new Promise((resolve) => stream.once('close', resolve).end())
  }

  abort(reason = new TypeError('Stream was aborted')) {
    const stream = this._stream._stream

    if (stream.destroyed) return Promise.resolve()

    return new Promise((resolve) => stream.once('close', resolve).destroy(reason))
  }
}

// https://streams.spec.whatwg.org/#writablestreamdefaultcontroller
exports.WritableStreamDefaultController = class WritableStreamDefaultController {
  constructor(stream) {
    this._stream = stream
  }

  error(err) {
    this._stream._stream.destroy(err)
  }
}

// https://streams.spec.whatwg.org/#writablestream
class WritableStream {
  static get [writableKind]() {
    return 0 // Compatibility version
  }

  constructor(underlyingSink = {}, queuingStrategy = {}) {
    if (isStreamx(underlyingSink)) {
      this._stream = underlyingSink
    } else {
      if (queuingStrategy === undefined) {
        queuingStrategy = new exports.CountQueuingStrategy()
      }

      const { start, write, close, abort } = underlyingSink
      const { highWaterMark = 1, size = defaultSize } = queuingStrategy

      this._stream = new Writable({ highWaterMark, byteLength: size })

      const controller = new exports.WritableStreamDefaultController(this)

      this._controller = controller

      try {
        let starting = Promise.resolve()

        if (start) starting = forwardError(start.call(this, controller), controller)

        if (write) {
          this._stream._write = this._write.bind(this, starting, write.bind(this))
        }

        if (close) {
          this._stream._destroy = this._destroy.bind(this, close.call(this))
        }

        if (abort) {
          this._stream.once('error', abort.bind(this))
        }
      } catch (err) {
        controller.error(err)
      }
    }

    this._writer = null
  }

  get [writableKind]() {
    return WritableStream[writableKind]
  }

  get locked() {
    return this._writer !== null
  }

  getWriter() {
    if (this.locked) throw new TypeError('Stream is locked')

    this._writer = new exports.WritableStreamDefaultWriter(this)

    return this._writer
  }

  abort(reason = new TypeError('Stream was aborted')) {
    if (this._stream.destroyed) return Promise.resolve()

    if (this.locked) return Promise.reject(new TypeError('Stream is locked'))

    return new Promise((resolve) => this._stream.once('close', resolve).destroy(reason))
  }

  close() {
    if (this._stream.destroyed) return Promise.resolve()

    if (this.locked) return Promise.reject(new TypeError('Stream is locked'))

    return new Promise((resolve) => this._stream.once('close', resolve).end())
  }

  _releaseLock() {
    this._writer = null
  }

  async _write(starting, write, data, cb) {
    await starting

    let err = null
    try {
      await write(data, this._controller)
    } catch (e) {
      err = e
    }
    cb(err)
  }

  async _destroy(closing, cb) {
    let err = null
    try {
      await closing
    } catch (e) {
      err = e
    }
    cb(err)
  }
}

exports.WritableStream = WritableStream

exports.isWritableStream = function isWritableStream(value) {
  if (value instanceof WritableStream) return true

  return (
    typeof value === 'object' &&
    value !== null &&
    value[writableKind] === WritableStream[writableKind]
  )
}

// https://streams.spec.whatwg.org/#transformstreamdefaultcontroller
exports.TransformStreamDefaultController = class TransformStreamDefaultController {
  constructor(stream) {
    this._stream = stream
  }

  get desiredSize() {
    const stream = this._stream._stream

    return stream._readableState.highWaterMark - stream._readableState.buffered
  }

  enqueue(data) {
    this._stream._stream.push(data)
  }

  error(err) {
    this._stream._stream.destroy(err)
  }

  terminate() {
    const stream = this._stream._stream

    stream.push(null)
    stream.destroy(new TypeError('Stream has been terminated'))
  }
}

// https://streams.spec.whatwg.org/#transformstream
class TransformStream {
  static get [transformKind]() {
    return 0 // Compatibility version
  }

  constructor(transformer = {}, writableStrategy = {}, readableStrategy = {}) {
    if (isStreamx(transformer)) {
      this._stream = transformer
    } else {
      const { start, transform, flush } = transformer

      this._stream = new Transform({ ...writableStrategy, ...readableStrategy })

      const controller = new exports.TransformStreamDefaultController(this)

      this._controller = controller

      try {
        let starting = Promise.resolve()

        if (start) starting = forwardError(start.call(this, controller), controller)

        if (transform) {
          this._stream._transform = this._transform.bind(this, starting, transform.bind(this))
        }

        if (flush) {
          this._stream._flush = this._flush.bind(this, flush.call(this, this._controller))
        }
      } catch (err) {
        controller.error(err)
      }
    }

    this._writable = new WritableStream(this._stream)
    this._readable = new ReadableStream(this._stream)
  }

  get [transformKind]() {
    return TransformStream[transformKind]
  }

  get writable() {
    return this._writable
  }

  get readable() {
    return this._readable
  }

  async _transform(starting, transform, data, cb) {
    await starting

    let err = null
    try {
      await transform(data, this._controller)
    } catch (e) {
      err = e
    }
    cb(err)
  }

  async _flush(flush, cb) {
    let err = null
    try {
      await flush
    } catch (e) {
      err = e
    }
    cb(err)
  }
}

exports.TransformStream = TransformStream

exports.isTransformStream = function isTransformStream(value) {
  if (value instanceof TransformStream) return true

  return (
    typeof value === 'object' &&
    value !== null &&
    value[transformKind] === TransformStream[transformKind]
  )
}

async function forwardError(promise, controller) {
  try {
    await promise
  } catch (err) {
    controller.error(err)
  }
}

function noop() {}
module.exports = require.addon()
const binding = require('./binding')

const t = binding.constants

class Type {
  constructor(type) {
    this._type = type
  }

  isUndefined() {
    return this._type === t.UNDEFINED
  }

  isNull() {
    return this._type === t.NULL
  }

  isBoolean() {
    return this._type === t.BOOLEAN
  }

  isNumber() {
    return (this._type & 0xff) === t.NUMBER
  }

  isInt32() {
    return (this._type & (0xff | t.INT32)) === (t.NUMBER | t.INT32)
  }

  isUint32() {
    return (this._type & (0xff | t.UINT32)) === (t.NUMBER | t.UINT32)
  }

  isString() {
    return this._type === t.STRING
  }

  isSymbol() {
    return this._type === t.SYMBOL
  }

  isObject() {
    return (this._type & 0xff) === t.OBJECT
  }

  isArray() {
    return this._type === (t.OBJECT | t.ARRAY)
  }

  isArguments() {
    return this._type === (t.OBJECT | t.ARGUMENTS)
  }

  isDate() {
    return this._type === (t.OBJECT | t.DATE)
  }

  isRegExp() {
    return this._type === (t.OBJECT | t.REGEXP)
  }

  isError() {
    return this._type === (t.OBJECT | t.ERROR)
  }

  isPromise() {
    return this._type === (t.OBJECT | t.PROMISE)
  }

  isProxy() {
    return this._type === (t.OBJECT | t.PROXY)
  }

  isGenerator() {
    return this._type === (t.OBJECT | t.GENERATOR)
  }

  isMap() {
    return this._type === (t.OBJECT | t.MAP)
  }

  isSet() {
    return this._type === (t.OBJECT | t.SET)
  }

  isWeakMap() {
    return this._type === (t.OBJECT | t.WEAK_MAP)
  }

  isWeakSet() {
    return this._type === (t.OBJECT | t.WEAK_SET)
  }

  isWeakRef() {
    return this._type === (t.OBJECT | t.WEAK_REF)
  }

  isArrayBuffer() {
    return this._type === (t.OBJECT | t.ARRAYBUFFER)
  }

  isSharedArrayBuffer() {
    return this._type === (t.OBJECT | t.SHAREDARRAYBUFFER)
  }

  isTypedArray() {
    return (this._type & 0xffff) === (t.OBJECT | t.TYPEDARRAY)
  }

  isInt8Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT8ARRAY)
  }

  isUint8Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT8ARRAY)
  }

  isUint8ClampedArray() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT8CLAMPEDARRAY)
  }

  isInt16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT16ARRAY)
  }

  isUint16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT16ARRAY)
  }

  isInt32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT32ARRAY)
  }

  isUint32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT32ARRAY)
  }

  isFloat16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT16ARRAY)
  }

  isFloat32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT32ARRAY)
  }

  isFloat64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT64ARRAY)
  }

  isBigInt64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.BIGINT64ARRAY)
  }

  isBigUint64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.BIGUINT64ARRAY)
  }

  isDataView() {
    return this._type === (t.OBJECT | t.DATAVIEW)
  }

  isModuleNamespace() {
    return this._type === (t.OBJECT | t.MODULE_NAMESPACE)
  }

  isFunction() {
    return (this._type & 0xff) === t.FUNCTION
  }

  isAsyncFunction() {
    return (
      (this._type & (0xff | t.ASYNC_FUNCTION)) ===
      (t.FUNCTION | t.ASYNC_FUNCTION)
    )
  }

  isGeneratorFunction() {
    return (
      (this._type & (0xff | t.GENERATOR_FUNCTION)) ===
      (t.FUNCTION | t.GENERATOR_FUNCTION)
    )
  }

  isExternal() {
    return this._type === t.EXTERNAL
  }

  isBigInt() {
    return this._type === t.BIGINT
  }
}

module.exports = exports = function type(value) {
  switch (typeof value) {
    case 'undefined':
      return new Type(t.UNDEFINED)
    case 'boolean':
      return new Type(t.BOOLEAN)
    case 'number':
      return new Type(
        Number.isSafeInteger(value) ? binding.type(value) : t.NUMBER
      )
    case 'string':
      return new Type(t.STRING)
    case 'symbol':
      return new Type(t.SYMBOL)
    case 'object':
      return new Type(value === null ? t.NULL : binding.type(value))
    case 'function':
      return new Type(binding.type(value))
    case 'bigint':
      return new Type(t.BIGINT)
  }
}

exports.createTag = function createTag(...components) {
  const tag = new Uint32Array(4)
  for (let i = 0; i < 4; i++) tag[i] = components[i] || 0
  return tag
}

exports.addTag = function addTag(object, tag) {
  binding.addTag(object, tag)
}

exports.checkTag = function checkTag(object, tag) {
  return binding.checkTag(object, tag)
}
{
  "name": "bare-type",
  "version": "1.1.0",
  "description": "Cross-realm type predicates for Bare",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-type.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-type/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-type#readme",
  "engines": {
    "bare": ">=1.2.0"
  },
  "devDependencies": {
    "brittle": "^3.4.0",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
module.exports = require.addon()
const path = require('bare-path')
const binding = require('./binding')
const errors = require('./lib/errors')
const URLSearchParams = require('./lib/url-search-params')

const kind = Symbol.for('bare.url.kind')

const isWindows = Bare.platform === 'win32'

class URL {
  static get [kind]() {
    return 0 // Compatibility version
  }

  constructor(input, base, opts = {}) {
    if (arguments.length === 0) throw errors.INVALID_URL()

    input = String(input)

    if (base !== undefined) base = String(base)

    this._components = new Uint32Array(8)

    this._parse(input, base, opts.throw !== false)

    if (this._href) this._params = new URLSearchParams(this.search, this)
  }

  get [kind]() {
    return URL[kind]
  }

  // https://url.spec.whatwg.org/#dom-url-href

  get href() {
    return this._href
  }

  set href(value) {
    this._update(value)

    this._params._parse(this.search)
  }

  // https://url.spec.whatwg.org/#dom-url-protocol

  get protocol() {
    return this._slice(0, this._components[0]) + ':'
  }

  set protocol(value) {
    this._update(this._replace(value.replace(/:+$/, ''), 0, this._components[0]))
  }

  // https://url.spec.whatwg.org/#dom-url-username

  get username() {
    return this._slice(this._components[0] + 3 /* :// */, this._components[1])
  }

  set username(value) {
    if (cannotHaveCredentialsOrPort(this)) {
      return
    }

    if (this.username === '') value += '@'

    this._update(this._replace(value, this._components[0] + 3 /* :// */, this._components[1]))
  }

  // https://url.spec.whatwg.org/#dom-url-password

  get password() {
    return this._href.slice(this._components[1] + 1 /* : */, this._components[2] - 1 /* @ */)
  }

  set password(value) {
    if (cannotHaveCredentialsOrPort(this)) {
      return
    }

    let start = this._components[1] + 1 /* : */
    let end = this._components[2] - 1 /* @ */

    if (this.password === '') {
      value = ':' + value
      start--
    }

    if (this.username === '') {
      value += '@'
      end++
    }

    this._update(this._replace(value, start, end))
  }

  // https://url.spec.whatwg.org/#dom-url-host

  get host() {
    return this._slice(this._components[2], this._components[5])
  }

  set host(value) {
    if (hasOpaquePath(this)) {
      return
    }

    this._update(
      this._replace(value, this._components[2], this._components[value.includes(':') ? 5 : 3])
    )
  }

  // https://url.spec.whatwg.org/#dom-url-hostname

  get hostname() {
    return this._slice(this._components[2], this._components[3])
  }

  set hostname(value) {
    if (hasOpaquePath(this)) {
      return
    }

    this._update(this._replace(value, this._components[2], this._components[3]))
  }

  // https://url.spec.whatwg.org/#dom-url-port

  get port() {
    return this._slice(this._components[3] + 1 /* : */, this._components[5])
  }

  set port(value) {
    if (cannotHaveCredentialsOrPort(this)) {
      return
    }

    let start = this._components[3] + 1 /* : */

    if (this.port === '') {
      value = ':' + value
      start--
    }

    this._update(this._replace(value, start, this._components[5]))
  }

  // https://url.spec.whatwg.org/#dom-url-pathname

  get pathname() {
    return this._slice(this._components[5], this._components[6] - 1 /* ? */)
  }

  set pathname(value) {
    if (hasOpaquePath(this)) {
      return
    }

    if (value[0] !== '/' && value[0] !== '\\') {
      value = '/' + value
    }

    this._update(this._replace(value, this._components[5], this._components[6] - 1 /* ? */))
  }

  // https://url.spec.whatwg.org/#dom-url-search

  get search() {
    return this._slice(this._components[6] - 1 /* ? */, this._components[7] - 1 /* # */)
  }

  set search(value) {
    if (value && value[0] !== '?') value = '?' + value

    this._update(
      this._replace(value, this._components[6] - 1 /* ? */, this._components[7] - 1 /* # */)
    )

    this._params._parse(this.search)
  }

  // https://url.spec.whatwg.org/#dom-url-searchparams

  get searchParams() {
    return this._params
  }

  // https://url.spec.whatwg.org/#dom-url-hash

  get hash() {
    return this._slice(this._components[7] - 1 /* # */)
  }

  set hash(value) {
    if (value && value[0] !== '#') value = '#' + value

    this._update(this._replace(value, this._components[7] - 1 /* # */))
  }

  toString() {
    return this._href
  }

  toJSON() {
    return this._href
  }

  [Symbol.for('bare.inspect')]() {
    return {
      __proto__: { constructor: URL },

      href: this.href,
      protocol: this.protocol,
      username: this.username,
      password: this.password,
      host: this.host,
      hostname: this.hostname,
      port: this.port,
      pathname: this.pathname,
      search: this.search,
      searchParams: this.searchParams,
      hash: this.hash
    }
  }

  _slice(start, end = this._href.length) {
    return this._href.slice(start, end)
  }

  _replace(replacement, start, end = this._href.length) {
    return this._slice(0, start) + replacement + this._slice(end)
  }

  _parse(input, base, shouldThrow) {
    try {
      this._href = binding.parse(
        String(input),
        base ? String(base) : null,
        this._components,
        shouldThrow
      )
    } catch (err) {
      if (err instanceof TypeError) throw err

      throw errors.INVALID_URL(`Invalid URL '${input}'`, input)
    }
  }

  _update(input) {
    try {
      this._parse(input, null, true)
    } catch (err) {
      if (err instanceof TypeError) throw err
    }
  }
}

module.exports = exports = URL

// https://url.spec.whatwg.org/#url-opaque-path
function hasOpaquePath(url) {
  return url.pathname[0] !== '/'
}

// https://url.spec.whatwg.org/#cannot-have-a-username-password-port
function cannotHaveCredentialsOrPort(url) {
  return url.hostname === '' || url.protocol === 'file:'
}

exports.URL = URL
exports.URLSearchParams = URLSearchParams

exports.errors = errors

exports.isURL = function isURL(value) {
  if (value instanceof URL) return true

  return typeof value === 'object' && value !== null && value[kind] === URL[kind]
}

exports.isURLSearchParams = URLSearchParams.isURLSearchParams

// https://url.spec.whatwg.org/#dom-url-parse
exports.parse = function parse(input, base) {
  const url = new URL(input, base, { throw: false })
  return url._href ? url : null
}

// https://url.spec.whatwg.org/#dom-url-canparse
exports.canParse = function canParse(input, base) {
  return binding.canParse(String(input), base ? String(base) : null)
}

exports.fileURLToPath = function fileURLToPath(url) {
  if (typeof url === 'string') {
    url = new URL(url)
  }

  if (url.protocol !== 'file:') {
    throw errors.INVALID_URL_SCHEME('The URL must use the file: protocol')
  }

  if (isWindows) {
    if (/%2f|%5c/i.test(url.pathname)) {
      throw errors.INVALID_FILE_URL_PATH(
        'The file: URL path must not include encoded \\ or / characters'
      )
    }
  } else {
    if (url.hostname) {
      throw errors.INVALID_FILE_URL_HOST("The file: URL host must be 'localhost' or empty")
    }

    if (/%2f/i.test(url.pathname)) {
      throw errors.INVALID_FILE_URL_PATH('The file: URL path must not include encoded / characters')
    }
  }

  if (/%00/i.test(url.pathname)) {
    throw errors.INVALID_FILE_URL_PATH('The file: URL path must not include encoded NUL characters')
  }

  const pathname = path.normalize(decodeURIComponent(url.pathname))

  if (isWindows) {
    if (url.hostname) return '\\\\' + url.hostname + pathname

    const letter = pathname.charCodeAt(1) | 0x20

    if (letter < 0x61 /* a */ || letter > 0x7a /* z */ || pathname.charCodeAt(2) !== 0x3a /* : */) {
      throw errors.INVALID_FILE_URL_PATH('The file: URL path must be absolute')
    }

    return pathname.slice(1)
  }

  return pathname
}

exports.pathToFileURL = function pathToFileURL(pathname) {
  let resolved = path.resolve(pathname)

  if (pathname[pathname.length - 1] === '/') {
    resolved += '/'
  } else if (isWindows && pathname[pathname.length - 1] === '\\') {
    resolved += '\\'
  }

  resolved = resolved
    .replaceAll('%', '%25') // Must be first
    .replaceAll('#', '%23')
    .replaceAll('?', '%3f')
    .replaceAll('\n', '%0a')
    .replaceAll('\r', '%0d')
    .replaceAll('\t', '%09')

  if (!isWindows) {
    resolved = resolved.replaceAll('\\', '%5c')
  }

  return new URL('file:' + resolved)
}

exports.format = function format(parts) {
  const { protocol, auth, host, hostname, port, pathname, search, query, hash, slashes } = parts

  let result = ''

  if (typeof protocol === 'string') {
    result += protocol

    if (protocol[protocol.length - 1] !== ':') {
      result += ':'
    }

    if (slashes === true || /https?|ftp|gopher|file/.test(protocol)) {
      result += '//'
    }
  }

  if (typeof auth === 'string') {
    if (host || hostname) result += auth + '@'
  }

  if (typeof host === 'string') result += host
  else {
    result += hostname

    if (port) result += ':' + port
  }

  if (typeof pathname === 'string' && pathname !== '') {
    if (pathname[0] !== '/') result += '/'
    result += pathname
  }

  if (typeof search === 'string') {
    if (search[0] !== '?') result += '?'
    result += search
  } else if (typeof query === 'object' && query !== null) {
    result += '?' + new URLSearchParams(query)
  }

  if (typeof hash === 'string') {
    if (hash[0] !== '#') result += '#'
    result += hash
  }

  return result
}
module.exports = class URLError extends Error {
  constructor(msg, fn = URLError, code = fn.name) {
    super(`${code}: ${msg}`)

    this.code = code

    if (Error.captureStackTrace) Error.captureStackTrace(this, fn)
  }

  get name() {
    return 'URLError'
  }

  static INVALID_URL(msg, input) {
    const err = new URLError(msg, URLError.INVALID_URL)

    err.input = input

    return err
  }

  static INVALID_URL_SCHEME(msg = 'Invalid URL') {
    return new URLError(msg, URLError.INVALID_URL_SCHEME)
  }

  static INVALID_FILE_URL_HOST(msg = 'Invalid file: URL host') {
    return new URLError(msg, URLError.INVALID_FILE_URL_HOST)
  }

  static INVALID_FILE_URL_PATH(msg = 'Invalid file: URL path') {
    return new URLError(msg, URLError.INVALID_FILE_URL_PATH)
  }
}
const kind = Symbol.for('bare.url.search-params.kind')

class URLSearchParams {
  static _urls = new WeakMap()

  static get [kind]() {
    return 0 // Compatibility version
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-urlsearchparams
  constructor(init, url = null) {
    this._params = new Map()

    if (url) URLSearchParams._urls.set(this, url)

    if (typeof init === 'string') {
      this._parse(init)
    } else if (init) {
      for (const [name, value] of typeof init[Symbol.iterator] === 'function'
        ? init
        : Object.entries(init)) {
        this.append(name, value)
      }
    }
  }

  get [kind]() {
    return URLSearchParams[kind]
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-size
  get size() {
    return this._params.length
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-append
  append(name, value = null) {
    if (value === null) return

    let list = this._params.get(name)

    if (list === undefined) {
      list = []
      this._params.set(name, list)
    }

    list.push(value)

    this._update()
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-delete
  delete(name, value = null) {
    if (value === null) this._params.delete(name)
    else {
      let list = this._params.get(name)

      if (list === undefined) return

      list = list.filter((found) => found !== value)

      if (list.length === 0) this._params.delete(name)
      else this._params.set(name, list)
    }

    this._update()
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-get
  get(name) {
    const list = this._params.get(name)

    if (list === undefined) return null

    return list[0]
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-getall
  getAll(name) {
    const list = this._params.get(name)

    if (list === undefined) return []

    return Array.from(list)
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-has
  has(name, value = null) {
    const list = this._params.get(name)

    if (list === undefined) return false

    if (value === null) return true

    return list.includes(value)
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-set
  set(name, value = null) {
    if (value === null) this._params.delete(name)
    else this._params.set(name, [value])

    this._update()
  }

  toString() {
    return this._serialize()
  }

  toJSON() {
    return [...this]
  }

  *[Symbol.iterator]() {
    for (const [name, values] of this._params) {
      for (const value of values) yield [name, value]
    }
  }

  [Symbol.for('bare.inspect')]() {
    const object = {
      __proto__: { constructor: URLSearchParams }
    }

    for (const [name, values] of this._params) {
      if (values.length === 1) object[name] = values[0]
      else object[name] = values
    }

    return object
  }

  // https://url.spec.whatwg.org/#concept-urlsearchparams-update
  _update() {
    const url = URLSearchParams._urls.get(this)

    if (url === undefined) return

    url.search = this._serialize()
  }

  // https://url.spec.whatwg.org/#concept-urlencoded-parser
  _parse(input) {
    if (input[0] === '?') input = input.substring(1)

    this._params = new Map()

    for (let sequence of input.split('&')) {
      if (sequence.length === 0) continue

      sequence = sequence.replace(/\+/g, ' ')

      let i = sequence.indexOf('=')
      if (i === -1) i = sequence.length

      const name = decodeURIComponent(sequence.substring(0, i))
      const value = decodeURIComponent(sequence.substring(i + 1, sequence.length))

      let list = this._params.get(name)

      if (list === undefined) {
        list = []
        this._params.set(name, list)
      }

      list.push(value)
    }
  }

  // https://url.spec.whatwg.org/#concept-urlencoded-serializer
  _serialize() {
    let output = ''

    for (let [name, values] of this._params) {
      name = encodeURIComponent(name)

      for (const value of values) {
        if (output) output += '&'

        output += name + '=' + encodeURIComponent(value)
      }
    }

    return output
  }
}

module.exports = exports = URLSearchParams

exports.isURLSearchParams = function isURLSearchParams(value) {
  if (value instanceof URLSearchParams) return true

  return typeof value === 'object' && value !== null && value[kind] === URLSearchParams[kind]
}
{
  "name": "bare-url",
  "version": "2.4.5",
  "description": "WHATWG URL implementation for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "global.js",
    "global.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-url.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-url/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-url",
  "dependencies": {
    "bare-path": "^3.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "cmake-bare": "^1.1.6",
    "cmake-fetch": "^1.0.0",
    "lunte": "^1.6.0",
    "prettier": "^3.3.3",
    "prettier-config-holepunch": "^2.0.0"
  }
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return uint24.decode(state) + 0x1000000 * uint32.decode(state)
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return uint32.decode(state) + 0x100000000 * uint32.decode(state)
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return 0x100000000 * uint32be.decode(state) + uint32be.decode(state)
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.2.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
module.exports = require('bare-events')
{
  "name": "events-universal",
  "version": "1.0.1",
  "description": "Universal wrapper for the Node.js events module",
  "exports": {
    "./package": "./package.json",
    ".": {
      "bare": "./bare.js",
      "react-native": "./react-native.js",
      "default": "./default.js"
    }
  },
  "files": [
    "index.js",
    "default.js",
    "bare.js",
    "react-native.js"
  ],
  "scripts": {
    "test": "prettier . --check"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/events-universal.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/events-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/events-universal#readme",
  "dependencies": {
    "bare-events": "^2.7.0"
  },
  "devDependencies": {
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^1.0.0"
  }
}
module.exports = class FixedFIFO {
  constructor (hwm) {
    if (!(hwm > 0) || ((hwm - 1) & hwm) !== 0) throw new Error('Max size for a FixedFIFO should be a power of two')
    this.buffer = new Array(hwm)
    this.mask = hwm - 1
    this.top = 0
    this.btm = 0
    this.next = null
  }

  clear () {
    this.top = this.btm = 0
    this.next = null
    this.buffer.fill(undefined)
  }

  push (data) {
    if (this.buffer[this.top] !== undefined) return false
    this.buffer[this.top] = data
    this.top = (this.top + 1) & this.mask
    return true
  }

  shift () {
    const last = this.buffer[this.btm]
    if (last === undefined) return undefined
    this.buffer[this.btm] = undefined
    this.btm = (this.btm + 1) & this.mask
    return last
  }

  peek () {
    return this.buffer[this.btm]
  }

  isEmpty () {
    return this.buffer[this.btm] === undefined
  }
}
const FixedFIFO = require('./fixed-size')

module.exports = class FastFIFO {
  constructor (hwm) {
    this.hwm = hwm || 16
    this.head = new FixedFIFO(this.hwm)
    this.tail = this.head
    this.length = 0
  }

  clear () {
    this.head = this.tail
    this.head.clear()
    this.length = 0
  }

  push (val) {
    this.length++
    if (!this.head.push(val)) {
      const prev = this.head
      this.head = prev.next = new FixedFIFO(2 * this.head.buffer.length)
      this.head.push(val)
    }
  }

  shift () {
    if (this.length !== 0) this.length--
    const val = this.tail.shift()
    if (val === undefined && this.tail.next) {
      const next = this.tail.next
      this.tail.next = null
      this.tail = next
      return this.tail.shift()
    }

    return val
  }

  peek () {
    const val = this.tail.peek()
    if (val === undefined && this.tail.next) return this.tail.next.peek()
    return val
  }

  isEmpty () {
    return this.length === 0
  }
}
{
  "name": "fast-fifo",
  "version": "1.3.2",
  "description": "A fast fifo implementation similar to the one powering nextTick in Node.js core",
  "main": "index.js",
  "files": [
    "./index.js",
    "./fixed-size.js"
  ],
  "dependencies": {},
  "devDependencies": {
    "standard": "^17.1.0",
    "brittle": "^3.3.2"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/fast-fifo.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/fast-fifo/issues"
  },
  "homepage": "https://github.com/mafintosh/fast-fifo"
}
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const b4a = require('b4a')

// https://en.wikipedia.org/wiki/Merkle_tree#Second_preimage_attack
const LEAF_TYPE = b4a.from([0])
const PARENT_TYPE = b4a.from([1])
const ROOT_TYPE = b4a.from([2])

const HYPERCORE = b4a.from('hypercore')

exports.keyPair = function (seed) {
  // key pairs might stay around for a while, so better not to use a default slab to avoid retaining it completely
  const slab = b4a.allocUnsafeSlow(
    sodium.crypto_sign_PUBLICKEYBYTES + sodium.crypto_sign_SECRETKEYBYTES
  )
  const publicKey = slab.subarray(0, sodium.crypto_sign_PUBLICKEYBYTES)
  const secretKey = slab.subarray(sodium.crypto_sign_PUBLICKEYBYTES)

  if (seed) sodium.crypto_sign_seed_keypair(publicKey, secretKey, seed)
  else sodium.crypto_sign_keypair(publicKey, secretKey)

  return {
    publicKey,
    secretKey
  }
}

exports.validateKeyPair = function (keyPair) {
  const pk = b4a.allocUnsafe(sodium.crypto_sign_PUBLICKEYBYTES)
  sodium.crypto_sign_ed25519_sk_to_pk(pk, keyPair.secretKey)
  return b4a.equals(pk, keyPair.publicKey)
}

exports.sign = function (message, secretKey) {
  // Dedicated slab for the signature, to avoid retaining unneeded mem and for security
  const signature = b4a.allocUnsafeSlow(sodium.crypto_sign_BYTES)
  sodium.crypto_sign_detached(signature, message, secretKey)
  return signature
}

exports.verify = function (message, signature, publicKey) {
  if (signature.byteLength !== sodium.crypto_sign_BYTES) return false
  if (publicKey.byteLength !== sodium.crypto_sign_PUBLICKEYBYTES) return false
  return sodium.crypto_sign_verify_detached(signature, message, publicKey)
}

exports.encrypt = function (message, publicKey) {
  const ciphertext = b4a.alloc(message.byteLength + sodium.crypto_box_SEALBYTES)
  sodium.crypto_box_seal(ciphertext, message, publicKey)
  return ciphertext
}

exports.decrypt = function (ciphertext, keyPair) {
  if (ciphertext.byteLength < sodium.crypto_box_SEALBYTES) return null

  const plaintext = b4a.alloc(ciphertext.byteLength - sodium.crypto_box_SEALBYTES)

  if (!sodium.crypto_box_seal_open(plaintext, ciphertext, keyPair.publicKey, keyPair.secretKey)) {
    return null
  }

  return plaintext
}

exports.encryptionKeyPair = function (seed) {
  const publicKey = b4a.alloc(sodium.crypto_box_PUBLICKEYBYTES)
  const secretKey = b4a.alloc(sodium.crypto_box_SECRETKEYBYTES)

  if (seed) {
    sodium.crypto_box_seed_keypair(publicKey, secretKey, seed)
  } else {
    sodium.crypto_box_keypair(publicKey, secretKey)
  }

  return {
    publicKey,
    secretKey
  }
}

exports.data = function (data) {
  const out = b4a.allocUnsafe(32)

  sodium.crypto_generichash_batch(out, [LEAF_TYPE, c.encode(c.uint64, data.byteLength), data])

  return out
}

exports.parent = function (a, b) {
  if (a.index > b.index) {
    const tmp = a
    a = b
    b = tmp
  }

  const out = b4a.allocUnsafe(32)

  sodium.crypto_generichash_batch(out, [
    PARENT_TYPE,
    c.encode(c.uint64, a.size + b.size),
    a.hash,
    b.hash
  ])

  return out
}

exports.tree = function (roots, out) {
  const buffers = new Array(3 * roots.length + 1)
  let j = 0

  buffers[j++] = ROOT_TYPE

  for (let i = 0; i < roots.length; i++) {
    const r = roots[i]
    buffers[j++] = r.hash
    buffers[j++] = c.encode(c.uint64, r.index)
    buffers[j++] = c.encode(c.uint64, r.size)
  }

  if (!out) out = b4a.allocUnsafe(32)
  sodium.crypto_generichash_batch(out, buffers)
  return out
}

exports.hash = function (data, out) {
  if (!out) out = b4a.allocUnsafe(32)
  if (!Array.isArray(data)) data = [data]

  sodium.crypto_generichash_batch(out, data)

  return out
}

exports.randomBytes = function (n) {
  const buf = b4a.allocUnsafe(n)
  sodium.randombytes_buf(buf)
  return buf
}

exports.discoveryKey = function (key) {
  if (!key || key.byteLength !== 32) throw new Error('Must pass a 32 byte buffer')
  // Discovery keys might stay around for a while, so better not to use slab memory (for better gc)
  const digest = b4a.allocUnsafeSlow(32)
  sodium.crypto_generichash(digest, HYPERCORE, key)
  return digest
}

if (sodium.sodium_free) {
  exports.free = function (secureBuf) {
    if (secureBuf.secure) sodium.sodium_free(secureBuf)
  }
} else {
  exports.free = function () {}
}

exports.namespace = function (name, count) {
  const ids = typeof count === 'number' ? range(count) : count

  // Namespaces are long-lived, so better to use a dedicated slab
  const buf = b4a.allocUnsafeSlow(32 * ids.length)

  const list = new Array(ids.length)

  // ns is ephemeral, so default slab
  const ns = b4a.allocUnsafe(33)
  sodium.crypto_generichash(ns.subarray(0, 32), typeof name === 'string' ? b4a.from(name) : name)

  for (let i = 0; i < list.length; i++) {
    list[i] = buf.subarray(32 * i, 32 * i + 32)
    ns[32] = ids[i]
    sodium.crypto_generichash(list[i], ns)
  }

  return list
}

function range(count) {
  const arr = new Array(count)
  for (let i = 0; i < count; i++) arr[i] = i
  return arr
}
{
  "name": "hypercore-crypto",
  "version": "3.7.0",
  "description": "The crypto primitives used in hypercore, extracted into a separate module",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.6.6",
    "compact-encoding": "^3.0.0",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "brittle": "^3.5.0",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/hypercore-crypto.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/hypercore-crypto/issues"
  },
  "homepage": "https://github.com/mafintosh/hypercore-crypto"
}
module.exports = require.addon.bind(require)
{
  "name": "require-addon",
  "version": "1.2.0",
  "description": "Import native addons across JavaScript runtimes",
  "exports": {
    "./package": "./package.json",
    ".": {
      "bare": "./lib/bare.js",
      "node": "./lib/node.js",
      "default": "./lib/default.js"
    }
  },
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    },
    "url": {
      "bare": "bare-url",
      "default": "url"
    }
  },
  "files": [
    "lib"
  ],
  "scripts": {
    "test": "npm run lint && npm run test:bare && npm run test:node",
    "test:bare": "bare test.js",
    "test:node": "node test.js",
    "lint": "prettier --check .",
    "format": "prettier --write ."
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/require-addon.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/require-addon/issues"
  },
  "homepage": "https://github.com/holepunchto/require-addon#readme",
  "engines": {
    "bare": ">=1.10.0"
  },
  "dependencies": {
    "bare-addon-resolve": "^1.3.0"
  },
  "devDependencies": {
    "bare-bundle": "^1.8.1",
    "bare-bundle-evaluate": "^1.1.0",
    "bare-fs": "^4.0.0",
    "bare-path": "^3.0.0",
    "bare-url": "^2.1.0",
    "brittle": "^3.7.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
require.addon = require('require-addon')
module.exports = require.addon('.', __filename)
const assert = require('assert')
const binding = require('./binding')
const { isNode } = require('which-runtime')

const OPTIONAL = Buffer.from(new ArrayBuffer(0))

module.exports = exports = { ...binding }

// memory

exports.sodium_memzero = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  binding.sodium_memzero(buf)
}

exports.sodium_mlock = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  const res = binding.sodium_mlock(buf)

  if (res !== 0) throw new Error('memory lock failed')
}

exports.sodium_munlock = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  const res = binding.sodium_munlock(buf)

  if (res !== 0) throw new Error('memory unlock failed')
}

exports.sodium_malloc = function (size) {
  assert(size >= 0, 'invalid size')

  const buf = Buffer.from(binding.sodium_malloc(size))
  buf.secure = true
  return buf
}

exports.sodium_free = function (buf) {
  if (!buf || !buf.secure) return

  binding.sodium_free(buf.buffer)
}

exports.sodium_mprotect_noaccess = function (buf) {
  const res = binding.sodium_mprotect_noaccess(buf.buffer)

  if (res !== 0) throw new Error('failed to lock buffer')
}

exports.sodium_mprotect_readonly = function (buf) {
  const res = binding.sodium_mprotect_readonly(buf.buffer)

  if (res !== 0) throw new Error('failed to unlock buffer')
}

exports.sodium_mprotect_readwrite = function (buf) {
  const res = binding.sodium_mprotect_readwrite(buf.buffer)

  if (res !== 0) throw new Error('failed to unlock buffer')
}

// crypto_randombytes

exports.randombytes_buf = function (buffer) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')

  binding.randombytes_buf(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

exports.randombytes_buf_deterministic = function (buffer, seed) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    seed.byteLength === binding.randombytes_SEEDBYTES,
    "seed must be 'randombytes_SEEDBYTES' bytes"
  )

  binding.randombytes_buf_deterministic(
    buffer.buffer,
    buffer.byteOffset,
    buffer.byteLength,

    seed.buffer,
    seed.byteOffset,
    seed.byteLength
  )
}

// sodium_helpers

exports.sodium_memcmp = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  return binding.sodium_memcmp(a, b)
}

exports.sodium_add = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  binding.sodium_add(a, b)
}

exports.sodium_sub = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  binding.sodium_sub(a, b)
}

exports.sodium_compare = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  return binding.sodium_compare(a, b)
}

exports.sodium_is_zero = function (buffer, length) {
  if (length === undefined) length = buffer.byteLength

  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(length >= 0 && length <= buffer.byteLength, 'invalid length')

  return binding.sodium_is_zero(buffer, length)
}

exports.sodium_pad = function (buffer, unpaddedBuflen, blockSize) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(unpaddedBuflen <= buffer.byteLength, 'unpadded length cannot exceed buffer length')
  assert(blockSize <= buffer.byteLength, 'block size cannot exceed buffer length')
  assert(blockSize >= 1, 'block size must be at least 1 byte')
  assert(
    buffer.byteLength >= unpaddedBuflen + (blockSize - (unpaddedBuflen % blockSize)),
    'buf not long enough'
  )

  return binding.sodium_pad(buffer, unpaddedBuflen, blockSize)
}

exports.sodium_unpad = function (buffer, paddedBuflen, blockSize) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(paddedBuflen <= buffer.byteLength, 'unpadded length cannot exceed buffer length')
  assert(blockSize <= buffer.byteLength, 'block size cannot exceed buffer length')
  assert(blockSize >= 1, 'block size must be at least 1 byte')

  return binding.sodium_unpad(buffer, paddedBuflen, blockSize)
}

// crypto_sign

exports.crypto_sign_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )
  assert(
    seed.byteLength === binding.crypto_sign_SEEDBYTES,
    "seed must be 'crypto_sign_SEEDBYTES' bytes"
  )

  const res = binding.crypto_sign_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign = function (sm, m, sk) {
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sm.byteLength === binding.crypto_sign_BYTES + m.byteLength,
    "sm must be 'm.byteLength + crypto_sign_BYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign(sm, m, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_open = function (m, sm, pk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sm.byteLength >= binding.crypto_sign_BYTES,
    "sm must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    m.byteLength === sm.byteLength - binding.crypto_sign_BYTES,
    "m must be 'sm.byteLength - crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_open(m, sm, pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_open = function (m, sm, pk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sm.byteLength >= binding.crypto_sign_BYTES,
    "sm must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    m.byteLength === sm.byteLength - binding.crypto_sign_BYTES,
    "m must be 'sm.byteLength - crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  return binding.crypto_sign_open(m, sm, pk)
}

exports.crypto_sign_detached = function (sig, m, sk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(sig.byteLength === binding.crypto_sign_BYTES, "sig must be 'crypto_sign_BYTES' bytes")
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_detached(sig, m, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_verify_detached = function (sig, m, pk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sig.byteLength >= binding.crypto_sign_BYTES,
    "sig must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  return binding.crypto_sign_verify_detached(
    sig.buffer,
    sig.byteOffset,
    sig.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    pk.buffer,
    pk.byteOffset,
    pk.byteLength
  )
}

exports.crypto_sign_ed25519_sk_to_pk = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_sk_to_pk(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_ed25519_pk_to_curve25519 = function (x25519pk, ed25519pk) {
  assert(ArrayBuffer.isView(x25519pk), 'x25519pk must be a typed array')
  assert(ArrayBuffer.isView(ed25519pk), 'ed25519pk must be a typed array')
  assert(
    x25519pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "x25519pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    ed25519pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "ed25519pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_pk_to_curve25519(x25519pk, ed25519pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_ed25519_sk_to_curve25519 = function (x25519sk, ed25519sk) {
  assert(ArrayBuffer.isView(x25519sk), 'x25519sk must be a typed array')
  assert(ArrayBuffer.isView(ed25519sk), 'ed25519sk must be a typed array')
  assert(
    x25519sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "x25519sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const edLen = ed25519sk.byteLength

  assert(
    edLen === binding.crypto_sign_SECRETKEYBYTES || edLen === binding.crypto_box_SECRETKEYBYTES,
    "ed25519sk must be 'crypto_sign_SECRETKEYBYTES' or 'crypto_sign_SECRETKEYBYTES - crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_sk_to_curve25519(x25519sk, ed25519sk)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_box

exports.crypto_box_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    seed.byteLength === binding.crypto_box_SEEDBYTES,
    "seed must be 'crypto_box_SEEDBYTES' bytes"
  )

  const res = binding.crypto_box_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_easy = function (c, m, n, pk, sk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength === m.byteLength + exports.crypto_box_MACBYTES,
    "c must be 'm.byteLength + crypto_box_MACBYTES' bytes"
  )
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_easy(c, m, n, pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_detached = function (c, mac, m, n, pk, sk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(mac.byteLength === exports.crypto_box_MACBYTES, "mac must be 'crypto_box_MACBYTES' bytes")
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_detached(c, mac, m, n, pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_open_easy = function (m, c, n, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength >= exports.crypto_box_MACBYTES,
    "c must be at least 'crypto_box_MACBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - exports.crypto_box_MACBYTES,
    "m must be 'c.byteLength - crypto_box_MACBYTES' bytes"
  )
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_open_easy(m, c, n, pk, sk)
}

exports.crypto_box_open_detached = function (m, c, mac, n, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(mac.byteLength === exports.crypto_box_MACBYTES, "mac must be 'crypto_box_MACBYTES' bytes")
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_open_detached(m, c, mac, n, pk, sk)
}

exports.crypto_box_seal = function (c, m, pk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    c.byteLength === m.byteLength + exports.crypto_box_SEALBYTES,
    "c must be 'm.byteLength + crypto_box_SEALBYTES' bytes"
  )
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_box_seal(c, m, pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_seal_open = function (m, c, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength >= exports.crypto_box_SEALBYTES,
    "c must be at least 'crypto_box_SEALBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - exports.crypto_box_SEALBYTES,
    "m must be 'c.byteLength - crypto_box_SEALBYTES' bytes"
  )
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_seal_open(
    m.buffer,
    m.byteOffset,
    m.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    pk.buffer,
    pk.byteOffset,
    pk.byteLength,

    sk.buffer,
    sk.byteOffset,
    sk.byteLength
  )
}

// crypto_secretbox

exports.crypto_secretbox_easy = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_secretbox_MACBYTES,
    "c must be 'm.byteLength + crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretbox_easy(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretbox_open_easy = function (m, c, n, k) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    c.byteLength >= binding.crypto_secretbox_MACBYTES,
    "c must be at least 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - binding.crypto_secretbox_MACBYTES,
    "m must be 'c.byteLength - crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  return binding.crypto_secretbox_open_easy(m, c, n, k)
}

exports.crypto_secretbox_detached = function (c, mac, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    mac.byteLength === binding.crypto_secretbox_MACBYTES,
    "mac must be 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretbox_detached(c, mac, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretbox_open_detached = function (m, c, mac, n, k) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(
    mac.byteLength === binding.crypto_secretbox_MACBYTES,
    "mac must be 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  return binding.crypto_secretbox_open_detached(m, c, mac, n, k)
}

// crypto_generichash

exports.crypto_generichash = function (output, input, key) {
  if (!key) key = OPTIONAL

  assert(ArrayBuffer.isView(output), 'output must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    output.byteLength >= binding.crypto_generichash_BYTES_MIN &&
      output.byteLength <= binding.crypto_generichash_BYTES_MAX,
    'output must be between crypto_generichash_BYTES_MIN and crypto_generichash_BYTES_MAX bytes'
  )

  if (key !== OPTIONAL) {
    assert(ArrayBuffer.isView(key), 'key must be a typed array')
    assert(
      key.byteLength >= binding.crypto_generichash_KEYBYTES_MIN &&
        key.byteLength <= binding.crypto_generichash_KEYBYTES_MAX,
      'key must be between crypto_generichash_KEYBYTES_MIN and crypto_generichash_KEYBYTES_MAX bytes'
    )
  }

  const res = binding.crypto_generichash(
    output.buffer,
    output.byteOffset,
    output.byteLength,

    input.buffer,
    input.byteOffset,
    input.byteLength,

    key.buffer,
    key.byteOffset,
    key.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_batch = function (output, batch, key) {
  assert(ArrayBuffer.isView(output), 'output must be a typed array')

  if (isNode || batch.length < 4) {
    const res = binding.crypto_generichash_batch(output, batch, !!key, key || OPTIONAL)
    if (res !== 0) throw new Error('status: ' + res)
  } else {
    const state = Buffer.alloc(binding.crypto_generichash_STATEBYTES)

    exports.crypto_generichash_init(state, key, output.byteLength)

    for (const buf of batch) {
      exports.crypto_generichash_update(state, buf)
    }

    exports.crypto_generichash_final(state, output)
  }
}

exports.crypto_generichash_keygen = function (key) {
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(
    key.byteLength === binding.crypto_generichash_KEYBYTES,
    "key must be 'crypto_generichash_KEYBYTES' bytes"
  )

  const res = binding.crypto_generichash_keygen(key.buffer, key.byteOffset, key.byteLength)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_init = function (state, key, outputLength) {
  if (!key) key = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_init(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    key.buffer,
    key.byteOffset,
    key.byteLength,

    outputLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_update(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    input.buffer,
    input.byteOffset,
    input.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_final = function (state, output) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(output), 'output must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_final(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    output.buffer,
    output.byteOffset,
    output.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

// secretstream

exports.crypto_secretstream_xchacha20poly1305_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  binding.crypto_secretstream_xchacha20poly1305_keygen(k.buffer, k.byteOffset, k.byteLength)
}

exports.crypto_secretstream_xchacha20poly1305_init_push = function (state, header, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(header), 'header must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    header.byteLength === binding.crypto_secretstream_xchacha20poly1305_HEADERBYTES,
    "header must be 'crypto_secretstream_xchacha20poly1305_HEADERBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_init_push(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    header.buffer,
    header.byteOffset,
    header.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretstream_xchacha20poly1305_init_pull = function (state, header, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(header), 'header must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    header.byteLength === binding.crypto_secretstream_xchacha20poly1305_HEADERBYTES,
    "header must be 'crypto_secretstream_xchacha20poly1305_HEADERBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_init_pull(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    header.buffer,
    header.byteOffset,
    header.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretstream_xchacha20poly1305_push = function (state, c, m, ad, tag) {
  if (!ad) ad = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    c.byteLength === m.byteLength + binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "c must be 'm.byteLength + crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_push(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    ad.buffer,
    ad.byteOffset,
    ad.byteLength,

    tag
  )

  if (res < 0) throw new Error('push failed')

  return res
}

exports.crypto_secretstream_xchacha20poly1305_pull = function (state, m, tag, c, ad) {
  if (!ad) ad = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(tag), 'tag must be a typed array')
  assert(tag.byteLength === 1, 'tag must be 1 byte')

  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    c.byteLength >= binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "c must be at least 'crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "m must be 'c.byteLength - crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_pull(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    tag.buffer,
    tag.byteOffset,
    tag.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    ad.buffer,
    ad.byteOffset,
    ad.byteLength
  )

  if (res < 0) throw new Error('pull failed')

  return res
}

exports.crypto_secretstream_xchacha20poly1305_rekey = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )

  binding.crypto_secretstream_xchacha20poly1305_rekey(
    state.buffer,
    state.byteOffset,
    state.byteLength
  )
}

// crypto_stream

exports.crypto_stream = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xor(
    c.buffer,
    c.byteOffset,
    c.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    n.buffer,
    n.byteOffset,
    n.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_auth

exports.crypto_auth = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(out.byteLength === binding.crypto_auth_BYTES, "out must be 'crypto_auth_BYTES' bytes")
  assert(k.byteLength === binding.crypto_auth_KEYBYTES, "k must be 'crypto_auth_KEYBYTES' bytes")

  const res = binding.crypto_auth(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_auth_verify = function (h, input, k) {
  assert(ArrayBuffer.isView(h), 'h must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(h.byteLength === binding.crypto_auth_BYTES, "h must be 'crypto_auth_BYTES' bytes")
  assert(k.byteLength === binding.crypto_auth_KEYBYTES, "k must be 'crypto_auth_KEYBYTES' bytes")

  return binding.crypto_auth_verify(h, input, k)
}

// crypto_onetimeauth

exports.crypto_onetimeauth = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    out.byteLength === binding.crypto_onetimeauth_BYTES,
    "out must be 'crypto_onetimeauth_BYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_init = function (state, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_init(state, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )
  assert(
    out.byteLength === binding.crypto_onetimeauth_BYTES,
    "out must be 'crypto_onetimeauth_BYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_verify = function (h, input, k) {
  assert(ArrayBuffer.isView(h), 'h must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    h.byteLength === binding.crypto_onetimeauth_BYTES,
    "h must be 'crypto_onetimeauth_BYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  return binding.crypto_onetimeauth_verify(h, input, k)
}

// crypto_pwhash

exports.crypto_pwhash = function (out, passwd, salt, opslimit, memlimit, alg) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_BYTES_MIN,
    "out must be at least 'crypto_pwhash_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_BYTES_MAX,
    "out must be at most 'crypto_pwhash_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_SALTBYTES,
    "salt must be 'crypto_pwhash_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )
  assert(alg >= 1 && alg <= 2, 'alg must be either Argon2i 1.3 or Argon2id 1.3')

  const res = binding.crypto_pwhash(out, passwd, salt, opslimit, memlimit, alg)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_async = function (
  out,
  passwd,
  salt,
  opslimit,
  memlimit,
  alg,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_BYTES_MIN,
    "out must be at least 'crypto_pwhash_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_BYTES_MAX,
    "out must be at most 'crypto_pwhash_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_SALTBYTES,
    "salt must be 'crypto_pwhash_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )
  assert(alg >= 1 && alg <= 2, 'alg must be either Argon2i 1.3 or Argon2id 1.3')

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    opslimit,
    memlimit,
    alg,

    done
  )

  return promise
}

exports.crypto_pwhash_str = function (out, passwd, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_STRBYTES,
    "out must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(typeof opslimit === 'number', 'opslimit must be a number')
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(typeof memlimit === 'number', 'memlimit must be a number')
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_str(out, passwd, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_str_async = function (out, passwd, opslimit, memlimit, callback = undefined) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_STRBYTES,
    "out must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(typeof opslimit === 'number', 'opslimit must be a number')
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(typeof memlimit === 'number', 'memlimit must be a number')
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_str_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_str_verify = function (str, passwd) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )

  return binding.crypto_pwhash_str_verify(str, passwd)
}

exports.crypto_pwhash_str_verify_async = function (str, passwd, callback = undefined) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  const [done, promise] = checkStatus(callback, true)

  binding.crypto_pwhash_str_verify_async(
    str.buffer,
    str.byteOffset,
    str.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    done
  )

  return promise
}

exports.crypto_pwhash_str_needs_rehash = function (str, opslimit, memlimit) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  return binding.crypto_pwhash_str_needs_rehash(str, opslimit, memlimit)
}

exports.crypto_pwhash_scryptsalsa208sha256 = function (out, passwd, salt, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MIN,
    "out must be at least 'crypto_pwhash_scryptsalsa208sha256_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MAX,
    "out must be at most 'crypto_pwhash_scryptsalsa208sha256_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_SALTBYTES,
    "salt must be 'crypto_pwhash_scryptsalsa208sha256_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_scryptsalsa208sha256(out, passwd, salt, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_scryptsalsa208sha256_async = function (
  out,
  passwd,
  salt,
  opslimit,
  memlimit,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MIN,
    "out must be at least 'crypto_pwhash_scryptsalsa208sha256_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MAX,
    "out must be at most 'crypto_pwhash_scryptsalsa208sha256_BYTES_MAX' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    salt.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_SALTBYTES,
    "salt must be 'crypto_pwhash_scryptsalsa208sha256_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_scryptsalsa208sha256_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str_async = function (
  out,
  passwd,
  opslimit,
  memlimit,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "out must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_scryptsalsa208sha256_str_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str = function (out, passwd, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "out must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_scryptsalsa208sha256_str(out, passwd, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_scryptsalsa208sha256_str_verify_async = function (
  str,
  passwd,
  callback = undefined
) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  const [done, promise] = checkStatus(callback, true)

  binding.crypto_pwhash_scryptsalsa208sha256_str_verify_async(
    str.buffer,
    str.byteOffset,
    str.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str_verify = function (str, passwd) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  return binding.crypto_pwhash_scryptsalsa208sha256_str_verify(str, passwd)
}

exports.crypto_pwhash_scryptsalsa208sha256_str_needs_rehash = function (str, opslimit, memlimit) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  return binding.crypto_pwhash_scryptsalsa208sha256_str_needs_rehash(str, opslimit, memlimit)
}

// crypto_kx

exports.crypto_kx_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "pk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "sk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    pk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "pk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "sk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    seed.byteLength === binding.crypto_kx_SEEDBYTES,
    "seed must be 'crypto_kx_SEEDBYTES' bytes"
  )

  const res = binding.crypto_kx_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_client_session_keys = function (rx, tx, clientPk, clientSk, serverPk) {
  if (!rx) rx = undefined
  if (!tx) tx = undefined

  assert(rx || tx, 'at least one session key must be specified')

  if (rx) {
    assert(ArrayBuffer.isView(rx), 'rx must be a typed array')
    assert(
      rx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "rx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  if (tx) {
    assert(ArrayBuffer.isView(tx), 'tx must be a typed array')
    assert(
      tx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "tx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  assert(ArrayBuffer.isView(clientPk), 'clientPk must be a typed array')
  assert(ArrayBuffer.isView(clientSk), 'clientSk must be a typed array')
  assert(ArrayBuffer.isView(serverPk), 'serverPk must be a typed array')
  assert(
    clientPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "clientPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    clientSk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "clientSk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    serverPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "serverPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_client_session_keys(rx, tx, clientPk, clientSk, serverPk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_server_session_keys = function (rx, tx, serverPk, serverSk, clientPk) {
  if (!rx) rx = undefined
  if (!tx) tx = undefined

  assert(rx || tx, 'at least one session key must be specified')

  if (rx) {
    assert(ArrayBuffer.isView(rx), 'rx must be a typed array')
    assert(
      rx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "rx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  if (tx) {
    assert(ArrayBuffer.isView(tx), 'tx must be a typed array')
    assert(
      tx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "tx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  assert(ArrayBuffer.isView(serverPk), 'serverPk must be a typed array')
  assert(ArrayBuffer.isView(serverSk), 'serverSk must be a typed array')
  assert(ArrayBuffer.isView(clientPk), 'clientPk must be a typed array')
  assert(
    serverPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "serverPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    serverSk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "serverSk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    clientPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "clientPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_server_session_keys(rx, tx, serverPk, serverSk, clientPk)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_scalarmult

exports.crypto_scalarmult_base = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_BYTES,
    "q must be 'crypto_scalarmult_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_SCALARBYTES,
    "n must be 'crypto_scalarmult_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_base(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_BYTES,
    "q must be 'crypto_scalarmult_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_SCALARBYTES,
    "n must be 'crypto_scalarmult_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_BYTES,
    "p must be 'crypto_scalarmult_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_base = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_base(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519 = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "p must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_is_valid_point = function (p) {
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )

  return binding.crypto_core_ed25519_is_valid_point(p)
}

exports.crypto_core_ed25519_from_uniform = function (p, r) {
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_UNIFORMBYTES,
    "r must be 'crypto_core_ed25519_UNIFORMBYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_from_uniform(p, r)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_base_noclamp = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_base_noclamp(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_noclamp = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "p must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_noclamp(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_core

exports.crypto_core_ed25519_add = function (r, p, q) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_BYTES,
    "r must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_core_ed25519_BYTES,
    "q must be 'crypto_core_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_add(r, p, q)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_sub = function (r, p, q) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_BYTES,
    "r must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_core_ed25519_BYTES,
    "q must be 'crypto_core_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_sub(r, p, q)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_scalar_random = function (r) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "r must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_random(r)
}

exports.crypto_core_ed25519_scalar_reduce = function (r, s) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "r must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_NONREDUCEDSCALARBYTES,
    "s must be 'crypto_core_ed25519_NONREDUCEDSCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_reduce(r, s)
}

exports.crypto_core_ed25519_scalar_invert = function (recip, s) {
  assert(ArrayBuffer.isView(recip), 'recip must be a typed array')
  assert(
    recip.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "recip must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_invert(recip, s)
}

exports.crypto_core_ed25519_scalar_negate = function (neg, s) {
  assert(ArrayBuffer.isView(neg), 'neg must be a typed array')
  assert(
    neg.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "neg must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_negate(neg, s)
}

exports.crypto_core_ed25519_scalar_complement = function (comp, s) {
  assert(ArrayBuffer.isView(comp), 'comp must be a typed array')
  assert(
    comp.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "comp must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_complement(comp, s)
}

exports.crypto_core_ed25519_scalar_add = function (z, x, y) {
  assert(ArrayBuffer.isView(z), 'z must be a typed array')
  assert(
    z.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "z must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(x), 'x must be a typed array')
  assert(
    x.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "x must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(y), 'y must be a typed array')
  assert(
    y.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "y must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_add(z, x, y)
}

exports.crypto_core_ed25519_scalar_sub = function (z, x, y) {
  assert(ArrayBuffer.isView(z), 'z must be a typed array')
  assert(
    z.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "z must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(x), 'x must be a typed array')
  assert(
    x.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "x must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(y), 'y must be a typed array')
  assert(
    y.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "y must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_sub(z, x, y)
}

// crypto_shorthash

exports.crypto_shorthash = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_shorthash_BYTES,
    "out must be 'crypto_shorthash_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_shorthash_KEYBYTES,
    "k must be 'crypto_shorthash_KEYBYTES' bytes"
  )

  const res = binding.crypto_shorthash(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_kdf

exports.crypto_kdf_keygen = function (key) {
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(key.byteLength === binding.crypto_kdf_KEYBYTES, "key must be 'crypto_kdf_KEYBYTES' bytes")

  binding.crypto_kdf_keygen(key)
}

exports.crypto_kdf_derive_from_key = function (subkey, subkeyId, ctx, key) {
  assert(ArrayBuffer.isView(subkey), 'subkey must be a typed array')
  assert(
    subkey.byteLength >= binding.crypto_kdf_BYTES_MIN,
    "subkey must be at least 'crypto_kdf_BYTES_MIN' bytes"
  )
  assert(
    subkey.byteLength <= binding.crypto_kdf_BYTES_MAX,
    "subkey must be at most 'crypto_kdf_BYTES_MAX' bytes"
  )
  assert(ArrayBuffer.isView(ctx), 'ctx must be a typed array')
  assert(
    ctx.byteLength === binding.crypto_kdf_CONTEXTBYTES,
    "ctx must be 'crypto_kdf_CONTEXTBYTES' bytes"
  )
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(key.byteLength === binding.crypto_kdf_KEYBYTES, "key must be 'crypto_kdf_KEYBYTES' bytes")

  const res = binding.crypto_kdf_derive_from_key(subkey, subkeyId, ctx, key)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_hash

exports.crypto_hash = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(out.byteLength === binding.crypto_hash_BYTES, "out must be 'crypto_hash_BYTES' bytes")

  const res = binding.crypto_hash(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256 = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha256_BYTES,
    "out must be 'crypto_hash_sha256_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha256(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_init = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_init(state)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha256_BYTES,
    "out must be 'crypto_hash_sha256_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512 = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha512_BYTES,
    "out must be 'crypto_hash_sha512_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha512(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_init = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_init(state)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha512_BYTES,
    "out must be 'crypto_hash_sha512_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_aead

exports.crypto_aead_xchacha20poly1305_ietf_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  binding.crypto_aead_xchacha20poly1305_ietf_keygen(k)
}

exports.crypto_aead_xchacha20poly1305_ietf_encrypt = function (c, m, ad, nsec, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "c must be 'm.byteLength + crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(c.byteLength <= 0xffffffff, 'c.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_encrypt(c, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_decrypt = function (m, nsec, c, ad, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "m must be 'c.byteLength - crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(m.byteLength <= 0xffffffff, 'm.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_decrypt(m, c, ad, npub, k)

  if (res < 0) throw new Error('could not verify data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_encrypt_detached = function (
  c,
  mac,
  m,
  ad,
  nsec,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_encrypt_detached(c, mac, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_decrypt_detached = function (
  m,
  nsec,
  c,
  mac,
  ad,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_decrypt_detached(m, c, mac, ad, npub, k)

  if (res !== 0) throw new Error('could not verify data')
}

exports.crypto_aead_chacha20poly1305_ietf_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  binding.crypto_aead_chacha20poly1305_ietf_keygen(k)
}

exports.crypto_aead_chacha20poly1305_ietf_encrypt = function (c, m, ad, nsec, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "c must be 'm.byteLength + crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(c.byteLength <= 0xffffffff, 'c.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_encrypt(c, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_decrypt = function (m, nsec, c, ad, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "m must be 'c.byteLength - crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(m.byteLength <= 0xffffffff, 'm.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_decrypt(m, c, ad, npub, k)

  if (res < 0) throw new Error('could not verify data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_encrypt_detached = function (
  c,
  mac,
  m,
  ad,
  nsec,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_encrypt_detached(c, mac, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_decrypt_detached = function (
  m,
  nsec,
  c,
  mac,
  ad,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_decrypt_detached(m, c, mac, ad, npub, k)

  if (res !== 0) throw new Error('could not verify data')
}

// crypto_stream

exports.crypto_stream_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  binding.crypto_stream_xor_wrap_init(state, n, k)
}

exports.crypto_stream_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_xor_wrap_update(state, c, m)
}

exports.crypto_stream_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_xor_wrap_final(state)
}

exports.crypto_stream_chacha20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  binding.crypto_stream_chacha20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_chacha20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_chacha20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_chacha20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_chacha20_xor_wrap_final(state)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  binding.crypto_stream_chacha20_ietf_xor_wrap_init(state, n, k)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_chacha20_ietf_xor_wrap_update(state, c, m)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_chacha20_ietf_xor_wrap_final(state)
}

exports.crypto_stream_xchacha20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  binding.crypto_stream_xchacha20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_xchacha20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_xchacha20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_xchacha20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_xchacha20_xor_wrap_final(state)
}

exports.crypto_stream_salsa20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  binding.crypto_stream_salsa20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_salsa20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_salsa20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_salsa20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_salsa20_xor_wrap_final(state)
}

// experimental

exports.extension_tweak_ed25519_base = function (n, p, ns) {
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.extension_tweak_ed25519_BYTES,
    "p must be 'extension_tweak_ed25519_BYTES' bytes"
  )

  binding.extension_tweak_ed25519_base(n, p, ns)
}

exports.extension_tweak_ed25519_sign_detached = function (sig, m, scalar, pk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(sig.byteLength === binding.crypto_sign_BYTES, "sig must be 'crypto_sign_BYTES' bytes")
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  if (pk) {
    assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
    assert(
      pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
      "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
    )
  }

  const res = binding.extension_tweak_ed25519_sign_detached(sig, m, scalar, pk)

  if (res !== 0) throw new Error('failed to compute signature')
}

exports.extension_tweak_ed25519_sk_to_scalar = function (n, sk) {
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  binding.extension_tweak_ed25519_sk_to_scalar(n, sk)
}

exports.extension_tweak_ed25519_scalar = function (scalarOut, scalar, ns) {
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_scalar(scalarOut, scalar, ns)
}

exports.extension_tweak_ed25519_pk = function (tpk, pk, ns) {
  assert(ArrayBuffer.isView(tpk), 'tpk must be a typed array')
  assert(
    tpk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "tpk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_pk(tpk, pk, ns)

  if (res !== 0) throw new Error('failed to tweak public key')
}

exports.extension_tweak_ed25519_keypair = function (pk, scalarOut, scalarIn, ns) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.extension_tweak_ed25519_BYTES,
    "pk must be 'extension_tweak_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarIn), 'scalarIn must be a typed array')
  assert(
    scalarIn.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarIn must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_keypair(pk, scalarOut, scalarIn, ns)
}

exports.extension_tweak_ed25519_scalar_add = function (scalarOut, scalar, n) {
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_scalar_add(scalarOut, scalar, n)
}

exports.extension_tweak_ed25519_pk_add = function (tpk, pk, p) {
  assert(ArrayBuffer.isView(tpk), 'tpk must be a typed array')
  assert(
    tpk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "tpk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "p must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_pk_add(tpk, pk, p)

  if (res !== 0) throw new Error('failed to add tweak to public key')
}

exports.extension_tweak_ed25519_keypair_add = function (pk, scalarOut, scalarIn, tweak) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.extension_tweak_ed25519_BYTES,
    "pk must be 'extension_tweak_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarIn), 'scalarIn must be a typed array')
  assert(
    scalarIn.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarIn must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(tweak), 'tweak must be a typed array')
  assert(
    tweak.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "tweak must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_keypair_add(pk, scalarOut, scalarIn, tweak)

  if (res !== 0) throw new Error('failed to add tweak to keypair')
}

exports.extension_pbkdf2_sha512_async = function (out, passwd, salt, iter, outlen, callback) {
  assert(
    iter >= binding.extension_pbkdf2_sha512_ITERATIONS_MIN,
    "iter must be at least 'extension_pbkdf2_sha512_ITERATIONS_MIN'"
  )
  assert(
    outlen <= binding.extension_pbkdf2_sha512_BYTES_MAX,
    "outlen must be at most 'extension_pbkdf2_sha512_BYTES_MAX'"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(out.byteLength >= outlen, "out must be at least 'outlen' bytes")
  assert(out.byteLength > 0, 'out must not be empty')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(salt.byteLength > 0, 'salt must not be empty')

  const [done, promise] = checkStatus(callback)

  binding.extension_pbkdf2_sha512_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    iter,
    outlen,

    done
  )

  return promise
}

exports.extension_pbkdf2_sha512 = function (out, passwd, salt, iter, outlen) {
  assert(
    iter >= binding.extension_pbkdf2_sha512_ITERATIONS_MIN,
    "iter must be at least 'extension_pbkdf2_sha512_ITERATIONS_MIN'"
  )
  assert(
    outlen <= binding.extension_pbkdf2_sha512_BYTES_MAX,
    "outlen must be at most 'extension_pbkdf2_sha512_BYTES_MAX'"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(out.byteLength >= outlen, "out must be at least 'outlen' bytes")
  assert(out.byteLength > 0, 'out must not be empty')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(salt.byteLength > 0, 'salt must not be empty')

  const res = binding.extension_pbkdf2_sha512(out, passwd, salt, iter, outlen)

  if (res !== 0) throw new Error('failed to add tweak to public key')
}

function checkStatus(callback, booleanResult = false) {
  let done, promise

  if (typeof callback === 'function') {
    done = function (status) {
      if (booleanResult) callback(null, status === 0)
      else if (status === 0) callback(null)
      else callback(new Error('status: ' + status))
    }
  } else {
    promise = new Promise(function (resolve, reject) {
      done = function (status) {
        if (booleanResult) resolve(status === 0)
        else if (status === 0) resolve()
        else reject(new Error('status: ' + status))
      }
    })
  }

  return [done, promise]
}
{
  "name": "sodium-native",
  "version": "5.1.0",
  "description": "Low level bindings for libsodium",
  "main": "index.js",
  "files": [
    "index.js",
    "binding.cc",
    "binding.js",
    "extensions",
    "prebuilds",
    "CMakeLists.txt"
  ],
  "imports": {
    "assert": {
      "bare": "bare-assert",
      "node": "assert"
    }
  },
  "addon": true,
  "dependencies": {
    "bare-assert": "^1.2.0",
    "require-addon": "^1.1.0",
    "which-runtime": "^1.2.1"
  },
  "devDependencies": {
    "bare-compat-napi": "^1.3.5",
    "brittle": "^3.16.2",
    "cmake-bare": "^1.6.1",
    "cmake-fetch": "^1.4.3",
    "cmake-napi": "^1.2.1",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "test": "prettier . --check && npm run test:node && npm run test:bare",
    "test:node": "node test/all.js",
    "test:bare": "bare test/all.js"
  },
  "standard": {
    "ignore": [
      "/test/fixtures/*.js"
    ]
  },
  "engines": {
    "bare": ">=1.16.0"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sodium-native.git"
  },
  "contributors": [
    "Emil Bay <github@tixz.dk> (http://bayes.dk)",
    "Mathias Buus <mathiasbuus@gmail.com> (https://mafinto.sh)",
    "Christophe Diederichs <chm-diederichs@hyperdivision.dk>"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/sodium-native/issues"
  },
  "homepage": "https://github.com/holepunchto/sodium-native"
}
module.exports = require('sodium-native')
{
  "name": "sodium-universal",
  "version": "5.0.1",
  "description": "Universal wrapper for sodium-javascript and sodium-native working in Node.js and the Browser",
  "main": "index.js",
  "dependencies": {
    "sodium-native": "^5.0.1"
  },
  "peerDependencies": {
    "sodium-javascript": "~0.8.0"
  },
  "peerDependenciesMeta": {
    "sodium-javascript": {
      "optional": true
    }
  },
  "scripts": {
    "prepublish": "./build-scripts/generate.js"
  },
  "browser": {
    "sodium-native": "sodium-javascript"
  },
  "browserify": {
    "transform": [
      "./build-scripts/transform.js"
    ]
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sodium-universal.git"
  },
  "keywords": [
    "libsodium",
    "sodium",
    "sodium-native",
    "sodium-javascript",
    "browserify"
  ],
  "contributors": [
    "Emil Bay <github@tixz.dk> (http://bayes.dk)",
    "Mathias Buus <mathiasbuus@gmail.com> (https://mafinto.sh)",
    "Christophe Diederichs <chm-diederichs@hyperdivision.dk>"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/sodium-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/sodium-universal#readme"
}
const { EventEmitter } = require('events-universal')
const FIFO = require('fast-fifo')
const TextDecoder = require('text-decoder')

const StreamError = require('./lib/errors.js')

// if we do a future major, expect queue microtask to be there always, for now a bit defensive
const qmt =
  typeof queueMicrotask === 'undefined' ? (fn) => global.process.nextTick(fn) : queueMicrotask

// 29 bits used total (4 from shared, 14 from read, and 11 from write)
const MAX = (1 << 29) - 1

// Shared state
const OPENING = 0b0001
const PREDESTROYING = 0b0010
const DESTROYING = 0b0100
const DESTROYED = 0b1000

const NOT_OPENING = MAX ^ OPENING
const NOT_PREDESTROYING = MAX ^ PREDESTROYING

// Read state (4 bit offset from shared state)
const READ_ACTIVE = 0b00000000000001 << 4
const READ_UPDATING = 0b00000000000010 << 4
const READ_PRIMARY = 0b00000000000100 << 4
const READ_QUEUED = 0b00000000001000 << 4
const READ_RESUMED = 0b00000000010000 << 4
const READ_PIPE_DRAINED = 0b00000000100000 << 4
const READ_ENDING = 0b00000001000000 << 4
const READ_EMIT_DATA = 0b00000010000000 << 4
const READ_EMIT_READABLE = 0b00000100000000 << 4
const READ_EMITTED_READABLE = 0b00001000000000 << 4
const READ_DONE = 0b00010000000000 << 4
const READ_NEXT_TICK = 0b00100000000000 << 4
const READ_NEEDS_PUSH = 0b01000000000000 << 4
const READ_READ_AHEAD = 0b10000000000000 << 4

// Combined read state
const READ_FLOWING = READ_RESUMED | READ_PIPE_DRAINED
const READ_ACTIVE_AND_NEEDS_PUSH = READ_ACTIVE | READ_NEEDS_PUSH
const READ_PRIMARY_AND_ACTIVE = READ_PRIMARY | READ_ACTIVE
const READ_EMIT_READABLE_AND_QUEUED = READ_EMIT_READABLE | READ_QUEUED
const READ_RESUMED_READ_AHEAD = READ_RESUMED | READ_READ_AHEAD

const READ_NOT_ACTIVE = MAX ^ READ_ACTIVE
const READ_NON_PRIMARY = MAX ^ READ_PRIMARY
const READ_NON_PRIMARY_AND_PUSHED = MAX ^ (READ_PRIMARY | READ_NEEDS_PUSH)
const READ_PUSHED = MAX ^ READ_NEEDS_PUSH
const READ_PAUSED = MAX ^ READ_RESUMED
const READ_NOT_QUEUED = MAX ^ (READ_QUEUED | READ_EMITTED_READABLE)
const READ_NOT_ENDING = MAX ^ READ_ENDING
const READ_PIPE_NOT_DRAINED = MAX ^ READ_FLOWING
const READ_NOT_NEXT_TICK = MAX ^ READ_NEXT_TICK
const READ_NOT_UPDATING = MAX ^ READ_UPDATING
const READ_NO_READ_AHEAD = MAX ^ READ_READ_AHEAD
const READ_PAUSED_NO_READ_AHEAD = MAX ^ READ_RESUMED_READ_AHEAD

// Write state (18 bit offset, 4 bit offset from shared state and 14 from read state)
const WRITE_ACTIVE = 0b00000000001 << 18
const WRITE_UPDATING = 0b00000000010 << 18
const WRITE_PRIMARY = 0b00000000100 << 18
const WRITE_QUEUED = 0b00000001000 << 18
const WRITE_UNDRAINED = 0b00000010000 << 18
const WRITE_DONE = 0b00000100000 << 18
const WRITE_EMIT_DRAIN = 0b00001000000 << 18
const WRITE_NEXT_TICK = 0b00010000000 << 18
const WRITE_WRITING = 0b00100000000 << 18
const WRITE_FINISHING = 0b01000000000 << 18
const WRITE_CORKED = 0b10000000000 << 18

const WRITE_NOT_ACTIVE = MAX ^ (WRITE_ACTIVE | WRITE_WRITING)
const WRITE_NON_PRIMARY = MAX ^ WRITE_PRIMARY
const WRITE_NOT_FINISHING = MAX ^ (WRITE_ACTIVE | WRITE_FINISHING)
const WRITE_DRAINED = MAX ^ WRITE_UNDRAINED
const WRITE_NOT_QUEUED = MAX ^ WRITE_QUEUED
const WRITE_NOT_NEXT_TICK = MAX ^ WRITE_NEXT_TICK
const WRITE_NOT_UPDATING = MAX ^ WRITE_UPDATING
const WRITE_NOT_CORKED = MAX ^ WRITE_CORKED

// Combined shared state
const ACTIVE = READ_ACTIVE | WRITE_ACTIVE
const NOT_ACTIVE = MAX ^ ACTIVE
const DONE = READ_DONE | WRITE_DONE
const DESTROY_STATUS = DESTROYING | DESTROYED | PREDESTROYING
const OPEN_STATUS = DESTROY_STATUS | OPENING
const AUTO_DESTROY = DESTROY_STATUS | DONE
const NON_PRIMARY = WRITE_NON_PRIMARY & READ_NON_PRIMARY
const ACTIVE_OR_TICKING = WRITE_NEXT_TICK | READ_NEXT_TICK
const TICKING = ACTIVE_OR_TICKING & NOT_ACTIVE
const IS_OPENING = OPEN_STATUS | TICKING

// Combined shared state and read state
const READ_PRIMARY_STATUS = OPEN_STATUS | READ_ENDING | READ_DONE
const READ_STATUS = OPEN_STATUS | READ_DONE | READ_QUEUED
const READ_ENDING_STATUS = OPEN_STATUS | READ_ENDING | READ_QUEUED
const READ_READABLE_STATUS = OPEN_STATUS | READ_EMIT_READABLE | READ_QUEUED | READ_EMITTED_READABLE
const SHOULD_NOT_READ =
  OPEN_STATUS | READ_ACTIVE | READ_ENDING | READ_DONE | READ_NEEDS_PUSH | READ_READ_AHEAD
const READ_BACKPRESSURE_STATUS = DESTROY_STATUS | READ_ENDING | READ_DONE
const READ_UPDATE_SYNC_STATUS = READ_UPDATING | OPEN_STATUS | READ_NEXT_TICK | READ_PRIMARY
const READ_NEXT_TICK_OR_OPENING = READ_NEXT_TICK | OPENING

// Combined write state
const WRITE_PRIMARY_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_DONE
const WRITE_QUEUED_AND_UNDRAINED = WRITE_QUEUED | WRITE_UNDRAINED
const WRITE_QUEUED_AND_ACTIVE = WRITE_QUEUED | WRITE_ACTIVE
const WRITE_DRAIN_STATUS = WRITE_QUEUED | WRITE_UNDRAINED | OPEN_STATUS | WRITE_ACTIVE
const WRITE_STATUS = OPEN_STATUS | WRITE_ACTIVE | WRITE_QUEUED | WRITE_CORKED
const WRITE_PRIMARY_AND_ACTIVE = WRITE_PRIMARY | WRITE_ACTIVE
const WRITE_ACTIVE_AND_WRITING = WRITE_ACTIVE | WRITE_WRITING
const WRITE_FINISHING_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_QUEUED_AND_ACTIVE | WRITE_DONE
const WRITE_BACKPRESSURE_STATUS = WRITE_UNDRAINED | DESTROY_STATUS | WRITE_FINISHING | WRITE_DONE
const WRITE_UPDATE_SYNC_STATUS = WRITE_UPDATING | OPEN_STATUS | WRITE_NEXT_TICK | WRITE_PRIMARY
const WRITE_DROP_DATA = WRITE_FINISHING | WRITE_DONE | DESTROY_STATUS

const asyncIterator = Symbol.asyncIterator || Symbol('asyncIterator')

class WritableState {
  constructor(
    stream,
    { highWaterMark = 16384, map = null, mapWritable, byteLength, byteLengthWritable } = {}
  ) {
    this.stream = stream
    this.queue = new FIFO()
    this.highWaterMark = highWaterMark
    this.buffered = 0
    this.error = null
    this.pipeline = null
    this.drains = null // if we add more seldomly used helpers we might them into a subobject so its a single ptr
    this.byteLength = byteLengthWritable || byteLength || defaultByteLength
    this.map = mapWritable || map
    this.afterWrite = afterWrite.bind(this)
    this.afterUpdateNextTick = updateWriteNT.bind(this)
  }

  get ending() {
    return (this.stream._duplexState & WRITE_FINISHING) !== 0
  }

  get ended() {
    return (this.stream._duplexState & WRITE_DONE) !== 0
  }

  push(data) {
    if ((this.stream._duplexState & WRITE_DROP_DATA) !== 0) return false
    if (this.map !== null) data = this.map(data)

    this.buffered += this.byteLength(data)
    this.queue.push(data)

    if (this.buffered < this.highWaterMark) {
      this.stream._duplexState |= WRITE_QUEUED
      return true
    }

    this.stream._duplexState |= WRITE_QUEUED_AND_UNDRAINED
    return false
  }

  shift() {
    const data = this.queue.shift()

    this.buffered -= this.byteLength(data)
    if (this.buffered === 0) this.stream._duplexState &= WRITE_NOT_QUEUED

    return data
  }

  end(data) {
    if (typeof data === 'function') {
      this.stream.once('finish', data)
    } else if (data !== undefined && data !== null) {
      this.push(data)
    }

    this.stream._duplexState = (this.stream._duplexState | WRITE_FINISHING) & WRITE_NON_PRIMARY
  }

  autoBatch(data, cb) {
    const buffer = []
    const stream = this.stream

    buffer.push(data)
    while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED_AND_ACTIVE) {
      buffer.push(stream._writableState.shift())
    }

    if ((stream._duplexState & OPEN_STATUS) !== 0) return cb(null)
    stream._writev(buffer, cb)
  }

  update() {
    const stream = this.stream

    stream._duplexState |= WRITE_UPDATING

    do {
      while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED) {
        const data = this.shift()
        stream._duplexState |= WRITE_ACTIVE_AND_WRITING
        stream._write(data, this.afterWrite)
      }

      if ((stream._duplexState & WRITE_PRIMARY_AND_ACTIVE) === 0) this.updateNonPrimary()
    } while (this.continueUpdate() === true)

    stream._duplexState &= WRITE_NOT_UPDATING
  }

  updateNonPrimary() {
    const stream = this.stream

    if ((stream._duplexState & WRITE_FINISHING_STATUS) === WRITE_FINISHING) {
      stream._duplexState = stream._duplexState | WRITE_ACTIVE
      stream._final(afterFinal.bind(this))
      return
    }

    if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
      if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
        stream._duplexState |= ACTIVE
        stream._destroy(afterDestroy.bind(this))
      }
      return
    }

    if ((stream._duplexState & IS_OPENING) === OPENING) {
      stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING
      stream._open(afterOpen.bind(this))
    }
  }

  continueUpdate() {
    if ((this.stream._duplexState & WRITE_NEXT_TICK) === 0) return false
    this.stream._duplexState &= WRITE_NOT_NEXT_TICK
    return true
  }

  updateCallback() {
    if ((this.stream._duplexState & WRITE_UPDATE_SYNC_STATUS) === WRITE_PRIMARY) {
      this.update()
    } else {
      this.updateNextTick()
    }
  }

  updateNextTick() {
    if ((this.stream._duplexState & WRITE_NEXT_TICK) !== 0) return
    this.stream._duplexState |= WRITE_NEXT_TICK
    if ((this.stream._duplexState & WRITE_UPDATING) === 0) qmt(this.afterUpdateNextTick)
  }
}

class ReadableState {
  constructor(
    stream,
    { highWaterMark = 16384, map = null, mapReadable, byteLength, byteLengthReadable } = {}
  ) {
    this.stream = stream
    this.queue = new FIFO()
    this.highWaterMark = highWaterMark === 0 ? 1 : highWaterMark
    this.buffered = 0
    this.readAhead = highWaterMark > 0
    this.error = null
    this.pipeline = null
    this.byteLength = byteLengthReadable || byteLength || defaultByteLength
    this.map = mapReadable || map
    this.pipeTo = null
    this.afterRead = afterRead.bind(this)
    this.afterUpdateNextTick = updateReadNT.bind(this)
  }

  get ending() {
    return (this.stream._duplexState & READ_ENDING) !== 0
  }

  get ended() {
    return (this.stream._duplexState & READ_DONE) !== 0
  }

  pipe(pipeTo, cb) {
    if (this.pipeTo !== null) throw StreamError.BAD_ARGUMENT('Can only pipe to one destination')
    if (typeof cb !== 'function') cb = null

    this.stream._duplexState |= READ_PIPE_DRAINED
    this.pipeTo = pipeTo
    this.pipeline = new Pipeline(this.stream, pipeTo, cb)

    if (cb) this.stream.on('error', noop) // We already error handle this so supress crashes

    if (isStreamx(pipeTo)) {
      pipeTo._writableState.pipeline = this.pipeline
      if (cb) pipeTo.on('error', noop) // We already error handle this so supress crashes
      pipeTo.on('finish', this.pipeline.finished.bind(this.pipeline)) // TODO: just call finished from pipeTo itself
    } else {
      const onerror = this.pipeline.done.bind(this.pipeline, pipeTo)
      const onclose = this.pipeline.done.bind(this.pipeline, pipeTo, null) // onclose has a weird bool arg
      pipeTo.on('error', onerror)
      pipeTo.on('close', onclose)
      pipeTo.on('finish', this.pipeline.finished.bind(this.pipeline))
    }

    pipeTo.on('drain', afterDrain.bind(this))
    this.stream.emit('piping', pipeTo)
    pipeTo.emit('pipe', this.stream)
  }

  push(data) {
    const stream = this.stream

    if (data === null) {
      this.highWaterMark = 0
      stream._duplexState = (stream._duplexState | READ_ENDING) & READ_NON_PRIMARY_AND_PUSHED
      return false
    }

    if (this.map !== null) {
      data = this.map(data)
      if (data === null) {
        stream._duplexState &= READ_PUSHED
        return this.buffered < this.highWaterMark
      }
    }

    this.buffered += this.byteLength(data)
    this.queue.push(data)

    stream._duplexState = (stream._duplexState | READ_QUEUED) & READ_PUSHED

    return this.buffered < this.highWaterMark
  }

  shift() {
    const data = this.queue.shift()

    this.buffered -= this.byteLength(data)
    if (this.buffered === 0) {
      this.stream._duplexState &= READ_NOT_QUEUED
    }

    return data
  }

  unshift(data) {
    const pending = [this.map !== null ? this.map(data) : data]
    while (this.buffered > 0) pending.push(this.shift())

    for (let i = 0; i < pending.length - 1; i++) {
      const data = pending[i]
      this.buffered += this.byteLength(data)
      this.queue.push(data)
    }

    this.push(pending[pending.length - 1])
  }

  read() {
    const stream = this.stream

    if ((stream._duplexState & READ_STATUS) === READ_QUEUED) {
      const data = this.shift()

      if (this.pipeTo !== null && this.pipeTo.write(data) === false) {
        stream._duplexState &= READ_PIPE_NOT_DRAINED
      }

      if ((stream._duplexState & READ_EMIT_DATA) !== 0) {
        stream.emit('data', data)
      }

      return data
    }

    if (this.readAhead === false) {
      stream._duplexState |= READ_READ_AHEAD
      this.updateNextTick()
    }

    return null
  }

  drain() {
    const stream = this.stream

    while (
      (stream._duplexState & READ_STATUS) === READ_QUEUED &&
      (stream._duplexState & READ_FLOWING) !== 0
    ) {
      const data = this.shift()

      if (this.pipeTo !== null && this.pipeTo.write(data) === false) {
        stream._duplexState &= READ_PIPE_NOT_DRAINED
      }

      if ((stream._duplexState & READ_EMIT_DATA) !== 0) {
        stream.emit('data', data)
      }
    }
  }

  update() {
    const stream = this.stream

    stream._duplexState |= READ_UPDATING

    do {
      this.drain()

      while (
        this.buffered < this.highWaterMark &&
        (stream._duplexState & SHOULD_NOT_READ) === READ_READ_AHEAD
      ) {
        stream._duplexState |= READ_ACTIVE_AND_NEEDS_PUSH
        stream._read(this.afterRead)
        this.drain()
      }

      if ((stream._duplexState & READ_READABLE_STATUS) === READ_EMIT_READABLE_AND_QUEUED) {
        stream._duplexState |= READ_EMITTED_READABLE
        stream.emit('readable')
      }

      if ((stream._duplexState & READ_PRIMARY_AND_ACTIVE) === 0) {
        this.updateNonPrimary()
      }
    } while (this.continueUpdate() === true)

    stream._duplexState &= READ_NOT_UPDATING
  }

  updateNonPrimary() {
    const stream = this.stream

    if ((stream._duplexState & READ_ENDING_STATUS) === READ_ENDING) {
      stream._duplexState = (stream._duplexState | READ_DONE) & READ_NOT_ENDING
      stream.emit('end')

      if ((stream._duplexState & AUTO_DESTROY) === DONE) {
        stream._duplexState |= DESTROYING
      }

      if (this.pipeTo !== null) {
        this.pipeTo.end()
      }
    }

    if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
      if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
        stream._duplexState |= ACTIVE
        stream._destroy(afterDestroy.bind(this))
      }
      return
    }

    if ((stream._duplexState & IS_OPENING) === OPENING) {
      stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING
      stream._open(afterOpen.bind(this))
    }
  }

  continueUpdate() {
    if ((this.stream._duplexState & READ_NEXT_TICK) === 0) return false
    this.stream._duplexState &= READ_NOT_NEXT_TICK
    return true
  }

  updateCallback() {
    if ((this.stream._duplexState & READ_UPDATE_SYNC_STATUS) === READ_PRIMARY) {
      this.update()
    } else {
      this.updateNextTick()
    }
  }

  updateNextTickIfOpen() {
    if ((this.stream._duplexState & READ_NEXT_TICK_OR_OPENING) !== 0) return
    this.stream._duplexState |= READ_NEXT_TICK
    if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick)
  }

  updateNextTick() {
    if ((this.stream._duplexState & READ_NEXT_TICK) !== 0) return
    this.stream._duplexState |= READ_NEXT_TICK
    if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick)
  }
}

class TransformState {
  constructor(stream) {
    this.data = null
    this.afterTransform = afterTransform.bind(stream)
    this.afterFinal = null
  }
}

class Pipeline {
  constructor(src, dst, cb) {
    this.from = src
    this.to = dst
    this.afterPipe = cb
    this.error = null
    this.pipeToFinished = false
  }

  finished() {
    this.pipeToFinished = true
  }

  done(stream, err) {
    if (err) this.error = err

    if (stream === this.to) {
      this.to = null

      if (this.from !== null) {
        if ((this.from._duplexState & READ_DONE) === 0 || !this.pipeToFinished) {
          this.from.destroy(this.error || StreamError.PREMATURE_CLOSE('Writable stream closed'))
        }
        return
      }
    }

    if (stream === this.from) {
      this.from = null

      if (this.to !== null) {
        if ((stream._duplexState & READ_DONE) === 0) {
          this.to.destroy(this.error || StreamError.PREMATURE_CLOSE('Readable stream closed'))
        }
        return
      }
    }

    if (this.afterPipe !== null) this.afterPipe(this.error)
    this.to = this.from = this.afterPipe = null
  }
}

function afterDrain() {
  this.stream._duplexState |= READ_PIPE_DRAINED
  this.updateCallback()
}

function afterFinal(err) {
  const stream = this.stream
  if (err) stream.destroy(err)

  if ((stream._duplexState & DESTROY_STATUS) === 0) {
    stream._duplexState |= WRITE_DONE
    stream.emit('finish')
  }

  if ((stream._duplexState & AUTO_DESTROY) === DONE) {
    stream._duplexState |= DESTROYING
  }

  stream._duplexState &= WRITE_NOT_FINISHING

  // no need to wait the extra tick here, so we short circuit that
  if ((stream._duplexState & WRITE_UPDATING) === 0) {
    this.update()
  } else {
    this.updateNextTick()
  }
}

function afterDestroy(err) {
  const stream = this.stream

  if (!err && !StreamError.isStreamDestroyed(this.error)) err = this.error
  if (err) stream.emit('error', err)

  stream._duplexState |= DESTROYED
  stream.emit('close')

  const rs = stream._readableState
  const ws = stream._writableState

  if (rs !== null && rs.pipeline !== null) {
    rs.pipeline.done(stream, err)
  }

  if (ws !== null) {
    while (ws.drains !== null && ws.drains.length > 0) {
      ws.drains.shift().resolve(false)
    }

    if (ws.pipeline !== null) {
      ws.pipeline.done(stream, err)
    }
  }
}

function afterWrite(err) {
  const stream = this.stream

  if (err) stream.destroy(err)
  stream._duplexState &= WRITE_NOT_ACTIVE

  if (this.drains !== null) tickDrains(this.drains)

  if ((stream._duplexState & WRITE_DRAIN_STATUS) === WRITE_UNDRAINED) {
    stream._duplexState &= WRITE_DRAINED

    if ((stream._duplexState & WRITE_EMIT_DRAIN) === WRITE_EMIT_DRAIN) {
      stream.emit('drain')
    }
  }

  this.updateCallback()
}

function afterRead(err) {
  if (err) this.stream.destroy(err)
  this.stream._duplexState &= READ_NOT_ACTIVE

  if (this.readAhead === false && (this.stream._duplexState & READ_RESUMED) === 0) {
    this.stream._duplexState &= READ_NO_READ_AHEAD
  }

  this.updateCallback()
}

function updateReadNT() {
  if ((this.stream._duplexState & READ_UPDATING) === 0) {
    this.stream._duplexState &= READ_NOT_NEXT_TICK
    this.update()
  }
}

function updateWriteNT() {
  if ((this.stream._duplexState & WRITE_UPDATING) === 0) {
    this.stream._duplexState &= WRITE_NOT_NEXT_TICK
    this.update()
  }
}

function tickDrains(drains) {
  for (let i = 0; i < drains.length; i++) {
    // drains.writes are monotonic, so if one is 0 its always the first one
    if (--drains[i].writes === 0) {
      drains.shift().resolve(true)
      i--
    }
  }
}

function afterOpen(err) {
  const stream = this.stream

  if (err) stream.destroy(err)

  if ((stream._duplexState & DESTROYING) === 0) {
    if ((stream._duplexState & READ_PRIMARY_STATUS) === 0) {
      stream._duplexState |= READ_PRIMARY
    }

    if ((stream._duplexState & WRITE_PRIMARY_STATUS) === 0) {
      stream._duplexState |= WRITE_PRIMARY
    }

    stream.emit('open')
  }

  stream._duplexState &= NOT_ACTIVE

  if (stream._writableState !== null) {
    stream._writableState.updateCallback()
  }

  if (stream._readableState !== null) {
    stream._readableState.updateCallback()
  }
}

function afterTransform(err, data) {
  if (data !== undefined && data !== null) this.push(data)
  this._writableState.afterWrite(err)
}

function newListener(name) {
  if (this._readableState !== null) {
    if (name === 'data') {
      this._duplexState |= READ_EMIT_DATA | READ_RESUMED_READ_AHEAD
      this._readableState.updateNextTick()
    }
    if (name === 'readable') {
      this._duplexState |= READ_EMIT_READABLE
      this._readableState.updateNextTick()
    }
  }

  if (this._writableState !== null) {
    if (name === 'drain') {
      this._duplexState |= WRITE_EMIT_DRAIN
      this._writableState.updateNextTick()
    }
  }
}

class Stream extends EventEmitter {
  constructor(opts) {
    super()

    this._duplexState = 0
    this._readableState = null
    this._writableState = null

    if (opts) {
      if (opts.open) this._open = opts.open
      if (opts.destroy) this._destroy = opts.destroy
      if (opts.predestroy) this._predestroy = opts.predestroy
      if (opts.signal) opts.signal.addEventListener('abort', abort.bind(this))
    }

    this.on('newListener', newListener)
  }

  _open(cb) {
    cb(null)
  }

  _destroy(cb) {
    cb(null)
  }

  _predestroy() {
    // does nothing
  }

  get readable() {
    return this._readableState !== null ? true : undefined
  }

  get writable() {
    return this._writableState !== null ? true : undefined
  }

  get destroyed() {
    return (this._duplexState & DESTROYED) !== 0
  }

  get destroying() {
    return (this._duplexState & DESTROY_STATUS) !== 0
  }

  destroy(err) {
    if ((this._duplexState & DESTROY_STATUS) === 0) {
      if (!err) err = StreamError.STREAM_DESTROYED()
      this._duplexState = (this._duplexState | DESTROYING) & NON_PRIMARY

      if (this._readableState !== null) {
        this._readableState.highWaterMark = 0
        this._readableState.error = err
      }

      if (this._writableState !== null) {
        this._writableState.highWaterMark = 0
        this._writableState.error = err
      }

      this._duplexState |= PREDESTROYING
      this._predestroy()
      this._duplexState &= NOT_PREDESTROYING

      if (this._readableState !== null) {
        this._readableState.updateNextTick()
      }

      if (this._writableState !== null) {
        this._writableState.updateNextTick()
      }
    }
  }
}

class Readable extends Stream {
  constructor(opts) {
    super(opts)

    this._duplexState |= OPENING | WRITE_DONE | READ_READ_AHEAD
    this._readableState = new ReadableState(this, opts)

    if (opts) {
      if (this._readableState.readAhead === false) this._duplexState &= READ_NO_READ_AHEAD
      if (opts.read) this._read = opts.read
      if (opts.eagerOpen) this._readableState.updateNextTick()
      if (opts.encoding) this.setEncoding(opts.encoding)
    }
  }

  static deferred(fn, opts) {
    const out = new PassThrough(opts)

    fn()
      .then((src) => {
        if (src === null) return out.end()
        if (out.destroying) return
        pipeline(src, out, noop)
      })
      .catch((err) => out.destroy(err))

    return out
  }

  setEncoding(encoding) {
    const dec = new TextDecoder(encoding)
    const map = this._readableState.map || echo
    this._readableState.map = mapOrSkip
    return this

    function mapOrSkip(data) {
      const next = dec.push(data)
      return next === '' && (data.byteLength !== 0 || dec.remaining > 0) ? null : map(next)
    }
  }

  _read(cb) {
    cb(null)
  }

  pipe(dest, cb) {
    this._readableState.updateNextTick()
    this._readableState.pipe(dest, cb)
    return dest
  }

  read() {
    this._readableState.updateNextTick()
    return this._readableState.read()
  }

  push(data) {
    this._readableState.updateNextTickIfOpen()
    return this._readableState.push(data)
  }

  unshift(data) {
    this._readableState.updateNextTickIfOpen()
    return this._readableState.unshift(data)
  }

  resume() {
    this._duplexState |= READ_RESUMED_READ_AHEAD
    this._readableState.updateNextTick()
    return this
  }

  pause() {
    this._duplexState &=
      this._readableState.readAhead === false ? READ_PAUSED_NO_READ_AHEAD : READ_PAUSED
    return this
  }

  static _fromAsyncIterator(ite, opts) {
    let destroy

    const rs = new Readable({
      ...opts,
      read(cb) {
        ite.next().then(push).then(cb.bind(null, null)).catch(cb)
      },
      predestroy() {
        destroy = ite.return()
      },
      destroy(cb) {
        if (!destroy) return cb(null)
        destroy.then(cb.bind(null, null)).catch(cb)
      }
    })

    return rs

    function push(data) {
      if (data.done) rs.push(null)
      else rs.push(data.value)
    }
  }

  static from(data, opts) {
    if (isReadStreamx(data)) return data
    if (data[asyncIterator]) return this._fromAsyncIterator(data[asyncIterator](), opts)
    if (!Array.isArray(data)) data = data === undefined ? [] : [data]

    let i = 0
    return new Readable({
      ...opts,
      read(cb) {
        this.push(i === data.length ? null : data[i++])
        cb(null)
      }
    })
  }

  static isBackpressured(rs) {
    return (
      (rs._duplexState & READ_BACKPRESSURE_STATUS) !== 0 ||
      rs._readableState.buffered >= rs._readableState.highWaterMark
    )
  }

  static isPaused(rs) {
    return (rs._duplexState & READ_RESUMED) === 0
  }

  [asyncIterator]() {
    const stream = this

    let error = null
    let promiseResolve = null
    let promiseReject = null

    this.on('error', (err) => {
      error = err
    })
    this.on('readable', onreadable)
    this.on('close', onclose)

    return {
      [asyncIterator]() {
        return this
      },
      next() {
        return new Promise(function (resolve, reject) {
          promiseResolve = resolve
          promiseReject = reject
          const data = stream.read()
          if (data !== null) ondata(data)
          else if ((stream._duplexState & DESTROYED) !== 0) ondata(null)
        })
      },
      return() {
        return destroy(null)
      },
      throw(err) {
        return destroy(err)
      }
    }

    function onreadable() {
      if (promiseResolve !== null) ondata(stream.read())
    }

    function onclose() {
      if (promiseResolve !== null) ondata(null)
    }

    function ondata(data) {
      if (promiseReject === null) return
      if (error) {
        promiseReject(error)
      } else if (data === null && (stream._duplexState & READ_DONE) === 0) {
        promiseReject(StreamError.STREAM_DESTROYED())
      } else {
        promiseResolve({ value: data, done: data === null })
      }
      promiseReject = promiseResolve = null
    }

    function destroy(err) {
      stream.destroy(err)
      return new Promise((resolve, reject) => {
        if (stream._duplexState & DESTROYED) return resolve({ value: undefined, done: true })
        stream.once('close', function () {
          if (err) reject(err)
          else resolve({ value: undefined, done: true })
        })
      })
    }
  }
}

class Writable extends Stream {
  constructor(opts) {
    super(opts)

    this._duplexState |= OPENING | READ_DONE
    this._writableState = new WritableState(this, opts)

    if (opts) {
      if (opts.writev) this._writev = opts.writev
      if (opts.write) this._write = opts.write
      if (opts.final) this._final = opts.final
      if (opts.eagerOpen) this._writableState.updateNextTick()
    }
  }

  cork() {
    this._duplexState |= WRITE_CORKED
  }

  uncork() {
    this._duplexState &= WRITE_NOT_CORKED
    this._writableState.updateNextTick()
  }

  _writev(batch, cb) {
    cb(null)
  }

  _write(data, cb) {
    this._writableState.autoBatch(data, cb)
  }

  _final(cb) {
    cb(null)
  }

  static isBackpressured(ws) {
    return (ws._duplexState & WRITE_BACKPRESSURE_STATUS) !== 0
  }

  static drained(ws) {
    if (ws.destroyed) return Promise.resolve(false)

    const state = ws._writableState
    const pending = isWritev(ws) ? Math.min(1, state.queue.length) : state.queue.length
    const writes = pending + (ws._duplexState & WRITE_WRITING ? 1 : 0)
    if (writes === 0) return Promise.resolve(true)

    if (state.drains === null) state.drains = []
    return new Promise((resolve) => {
      state.drains.push({ writes, resolve })
    })
  }

  write(data) {
    this._writableState.updateNextTick()
    return this._writableState.push(data)
  }

  end(data) {
    this._writableState.updateNextTick()
    this._writableState.end(data)
    return this
  }
}

class Duplex extends Readable {
  // and Writable
  constructor(opts) {
    super(opts)

    this._duplexState = OPENING | (this._duplexState & READ_READ_AHEAD)
    this._writableState = new WritableState(this, opts)

    if (opts) {
      if (opts.writev) this._writev = opts.writev
      if (opts.write) this._write = opts.write
      if (opts.final) this._final = opts.final
    }
  }

  cork() {
    this._duplexState |= WRITE_CORKED
  }

  uncork() {
    this._duplexState &= WRITE_NOT_CORKED
    this._writableState.updateNextTick()
  }

  _writev(batch, cb) {
    cb(null)
  }

  _write(data, cb) {
    this._writableState.autoBatch(data, cb)
  }

  _final(cb) {
    cb(null)
  }

  write(data) {
    this._writableState.updateNextTick()
    return this._writableState.push(data)
  }

  end(data) {
    this._writableState.updateNextTick()
    this._writableState.end(data)
    return this
  }
}

class Transform extends Duplex {
  constructor(opts) {
    super(opts)
    this._transformState = new TransformState(this)

    if (opts) {
      if (opts.transform) this._transform = opts.transform
      if (opts.flush) this._flush = opts.flush
    }
  }

  _write(data, cb) {
    if (this._readableState.buffered >= this._readableState.highWaterMark) {
      this._transformState.data = data
    } else {
      this._transform(data, this._transformState.afterTransform)
    }
  }

  _read(cb) {
    if (this._transformState.data !== null) {
      const data = this._transformState.data
      this._transformState.data = null
      cb(null)
      this._transform(data, this._transformState.afterTransform)
    } else {
      cb(null)
    }
  }

  destroy(err) {
    super.destroy(err)
    if (this._transformState.data !== null) {
      this._transformState.data = null
      this._transformState.afterTransform()
    }
  }

  _transform(data, cb) {
    cb(null, data)
  }

  _flush(cb) {
    cb(null)
  }

  _final(cb) {
    this._transformState.afterFinal = cb
    this._flush(transformAfterFlush.bind(this))
  }
}

class PassThrough extends Transform {}

function transformAfterFlush(err, data) {
  const cb = this._transformState.afterFinal
  if (err) return cb(err)

  if (data !== null && data !== undefined) this.push(data)
  this.push(null)
  cb(null)
}

function pipelinePromise(...streams) {
  return new Promise((resolve, reject) => {
    return pipeline(...streams, (err) => {
      if (err) return reject(err)
      resolve()
    })
  })
}

function pipeline(stream, ...streams) {
  const all = Array.isArray(stream) ? [...stream, ...streams] : [stream, ...streams]
  const done = all.length && typeof all[all.length - 1] === 'function' ? all.pop() : null

  if (all.length < 2) throw StreamError.BAD_ARGUMENT('Pipeline requires at least 2 streams')

  let src = all[0]
  let dest = null
  let error = null

  for (let i = 1; i < all.length; i++) {
    dest = all[i]

    if (isStreamx(src)) {
      src.pipe(dest, onerror)
    } else {
      errorHandle(src, true, i > 1, onerror)
      src.pipe(dest)
    }

    src = dest
  }

  if (done) {
    let fin = false

    const autoDestroy =
      isStreamx(dest) || !!(dest._writableState && dest._writableState.autoDestroy)

    dest.on('error', (err) => {
      if (error === null) error = err
    })

    dest.on('finish', () => {
      fin = true
      if (!autoDestroy) done(error)
    })

    if (autoDestroy) {
      dest.on('close', () => done(error || (fin ? null : StreamError.PREMATURE_CLOSE())))
    }
  }

  return dest

  function errorHandle(s, rd, wr, onerror) {
    s.on('error', onerror)
    s.on('close', onclose)

    function onclose() {
      if (rd && s._readableState && !s._readableState.ended) {
        return onerror(StreamError.PREMATURE_CLOSE())
      }
      if (wr && s._writableState && !s._writableState.ended) {
        return onerror(StreamError.PREMATURE_CLOSE())
      }
    }
  }

  function onerror(err) {
    if (!err || error) return
    error = err

    for (const s of all) {
      s.destroy(err)
    }
  }
}

function echo(s) {
  return s
}

function isStream(stream) {
  return !!stream._readableState || !!stream._writableState
}

function isStreamx(stream) {
  return typeof stream._duplexState === 'number' && isStream(stream)
}

function isEnding(stream) {
  return !!stream._readableState && stream._readableState.ending
}

function isEnded(stream) {
  return !!stream._readableState && stream._readableState.ended
}

function isFinishing(stream) {
  return !!stream._writableState && stream._writableState.ending
}

function isFinished(stream) {
  return !!stream._writableState && stream._writableState.ended
}

function getStreamError(stream, opts = {}) {
  const err =
    (stream._readableState && stream._readableState.error) ||
    (stream._writableState && stream._writableState.error)

  // avoid implicit errors by default
  return !opts.all && StreamError.isStreamDestroyed(err) ? null : err
}

function isReadStreamx(stream) {
  return isStreamx(stream) && stream.readable
}

function isDisturbed(stream) {
  return (
    (stream._duplexState & OPENING) !== OPENING ||
    (stream._duplexState & DESTROYING) === DESTROYING ||
    (stream._duplexState & ACTIVE_OR_TICKING) !== 0
  )
}

function isTypedArray(data) {
  return typeof data === 'object' && data !== null && typeof data.byteLength === 'number'
}

function defaultByteLength(data) {
  return isTypedArray(data) ? data.byteLength : 1024
}

function noop() {}

function abort() {
  this.destroy(StreamError.ABORTED())
}

function isWritev(s) {
  return s._writev !== Writable.prototype._writev && s._writev !== Duplex.prototype._writev
}

module.exports = {
  pipeline,
  pipelinePromise,
  isStream,
  isStreamx,
  isEnding,
  isEnded,
  isFinishing,
  isFinished,
  isDisturbed,
  getStreamError,
  Stream,
  Writable,
  Readable,
  Duplex,
  Transform,
  // Export PassThrough for compatibility with Node.js core's stream module
  PassThrough
}
module.exports = class StreamError extends Error {
  constructor(msg, code, fn = StreamError) {
    super(msg)

    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  static isStreamDestroyed(err) {
    return err && err.code === 'STREAM_DESTROYED'
  }

  static isPrematureClose(err) {
    return err && err.code === 'PREMATURE_CLOSE'
  }

  static isAborted(err) {
    return err && err.code === 'ABORTED'
  }

  static isBadArgument(err) {
    return err && err.code === 'BAD_ARGUMENT'
  }

  get name() {
    return 'StreamError'
  }

  static STREAM_DESTROYED() {
    return new StreamError('Stream was destroyed', 'STREAM_DESTROYED', StreamError.STREAM_DESTROYED)
  }

  static PREMATURE_CLOSE(msg = 'Premature close') {
    return new StreamError(msg, 'PREMATURE_CLOSE', StreamError.PREMATURE_CLOSE)
  }

  static ABORTED() {
    return new StreamError('Stream aborted', 'ABORTED', StreamError.ABORTED)
  }

  static BAD_ARGUMENT(msg = 'Bad argument') {
    return new StreamError(msg, 'BAD_ARGUMENT', StreamError.BAD_ARGUMENT)
  }
}
{
  "name": "streamx",
  "version": "2.28.0",
  "description": "An iteration of the Node.js core streams with a series of improvements",
  "main": "index.js",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./errors": {
      "types": "./lib/errors.d.ts",
      "default": "./lib/errors"
    }
  },
  "dependencies": {
    "events-universal": "^1.0.0",
    "fast-fifo": "^1.3.2",
    "text-decoder": "^1.1.0"
  },
  "devDependencies": {
    "b4a": "^1.6.6",
    "brittle": "^3.1.1",
    "end-of-stream": "^1.4.4",
    "lunte": "^1.8.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "runtime.d.ts",
    "lib"
  ],
  "scripts": {
    "format": "prettier . --write",
    "test": "brittle test/all.js && brittle-bare test/all.js",
    "lint": "prettier . --check && lunte"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/streamx.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/streamx/issues"
  },
  "homepage": "https://github.com/mafintosh/streamx"
}
const { Readable } = require('streamx')

module.exports = function (s, forks = 2) {
  const streams = new Array(forks)
  const status = new Array(forks).fill(true)

  let ended = false

  for (let i = 0; i < forks; i++) {
    streams[i] = new Readable({
      read (cb) {
        const check = !status[i]
        status[i] = true
        if (check && allReadable()) s.resume()
        cb(null)
      }
    })
  }

  s.on('end', function () {
    ended = true
    for (const stream of streams) stream.push(null)
  })

  s.on('error', function (err) {
    for (const stream of streams) stream.destroy(err)
  })

  s.on('close', function () {
    if (ended) return
    for (const stream of streams) stream.destroy()
  })

  s.on('data', function (data) {
    let needsPause = false
    for (let i = 0; i < streams.length; i++) {
      if (!(status[i] = streams[i].push(data))) {
        needsPause = true
      }
    }
    if (needsPause) s.pause()
  })

  return streams

  function allReadable () {
    for (let j = 0; j < status.length; j++) {
      if (!status[j]) return false
    }
    return true
  }
}
{
  "name": "teex",
  "version": "1.0.1",
  "description": "Turn a readable stream into multiple readable streamx streams",
  "main": "index.js",
  "dependencies": {
    "streamx": "^2.12.5"
  },
  "devDependencies": {
    "standard": "^14.3.4",
    "tape": "^5.0.1"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/teex.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/teex/issues"
  },
  "homepage": "https://github.com/mafintosh/teex"
}
const PassThroughDecoder = require('./lib/pass-through-decoder')
const UTF8Decoder = require('./lib/utf8-decoder')

module.exports = class TextDecoder {
  constructor(encoding = 'utf8') {
    this.encoding = normalizeEncoding(encoding)

    switch (this.encoding) {
      case 'utf8':
        this.decoder = new UTF8Decoder()
        break
      case 'utf16le':
      case 'base64':
        throw new Error('Unsupported encoding: ' + this.encoding)
      default:
        this.decoder = new PassThroughDecoder(this.encoding)
    }
  }

  get remaining() {
    return this.decoder.remaining
  }

  push(data) {
    if (typeof data === 'string') return data
    return this.decoder.decode(data)
  }

  // For Node.js compatibility
  write(data) {
    return this.push(data)
  }

  end(data) {
    let result = ''
    if (data) result = this.push(data)
    result += this.decoder.flush()
    return result
  }
}

function normalizeEncoding(encoding) {
  encoding = encoding.toLowerCase()

  switch (encoding) {
    case 'utf8':
    case 'utf-8':
      return 'utf8'
    case 'ucs2':
    case 'ucs-2':
    case 'utf16le':
    case 'utf-16le':
      return 'utf16le'
    case 'latin1':
    case 'binary':
      return 'latin1'
    case 'base64':
    case 'ascii':
    case 'hex':
      return encoding
    default:
      throw new Error('Unknown encoding: ' + encoding)
  }
}
const b4a = require('b4a')

module.exports = class PassThroughDecoder {
  constructor(encoding) {
    this.encoding = encoding
  }

  get remaining() {
    return 0
  }

  decode(data) {
    return b4a.toString(data, this.encoding)
  }

  flush() {
    return ''
  }
}
const b4a = require('b4a')

/**
 * https://encoding.spec.whatwg.org/#utf-8-decoder
 */
module.exports = class UTF8Decoder {
  constructor() {
    this._reset()
  }

  get remaining() {
    return this.bytesSeen
  }

  decode(data) {
    if (data.byteLength === 0) return ''

    if (this.bytesNeeded === 0 && trailingIncomplete(data, 0) === 0) {
      this.bytesSeen = trailingBytesSeen(data)
      return b4a.toString(data, 'utf8')
    }

    let result = ''
    let start = 0

    if (this.bytesNeeded > 0) {
      while (start < data.byteLength) {
        const byte = data[start]

        if (byte < this.lowerBoundary || byte > this.upperBoundary) {
          result += '\ufffd'
          this._reset()
          break
        }

        this.lowerBoundary = 0x80
        this.upperBoundary = 0xbf
        this.codePoint = (this.codePoint << 6) | (byte & 0x3f)
        this.bytesSeen++
        start++

        if (this.bytesSeen === this.bytesNeeded) {
          result += String.fromCodePoint(this.codePoint)
          this._reset()
          break
        }
      }

      if (this.bytesNeeded > 0) return result
    }

    const trailing = trailingIncomplete(data, start)
    const end = data.byteLength - trailing

    if (end > start) result += b4a.toString(data, 'utf8', start, end)

    for (let i = end; i < data.byteLength; i++) {
      const byte = data[i]

      if (this.bytesNeeded === 0) {
        if (byte <= 0x7f) {
          this.bytesSeen = 0
          result += String.fromCharCode(byte)
        } else if (byte >= 0xc2 && byte <= 0xdf) {
          this.bytesNeeded = 2
          this.bytesSeen = 1
          this.codePoint = byte & 0x1f
        } else if (byte >= 0xe0 && byte <= 0xef) {
          if (byte === 0xe0) this.lowerBoundary = 0xa0
          else if (byte === 0xed) this.upperBoundary = 0x9f
          this.bytesNeeded = 3
          this.bytesSeen = 1
          this.codePoint = byte & 0xf
        } else if (byte >= 0xf0 && byte <= 0xf4) {
          if (byte === 0xf0) this.lowerBoundary = 0x90
          else if (byte === 0xf4) this.upperBoundary = 0x8f
          this.bytesNeeded = 4
          this.bytesSeen = 1
          this.codePoint = byte & 0x7
        } else {
          this.bytesSeen = 1
          result += '\ufffd'
        }

        continue
      }

      if (byte < this.lowerBoundary || byte > this.upperBoundary) {
        result += '\ufffd'
        i--
        this._reset()

        continue
      }

      this.lowerBoundary = 0x80
      this.upperBoundary = 0xbf

      this.codePoint = (this.codePoint << 6) | (byte & 0x3f)
      this.bytesSeen++

      if (this.bytesSeen === this.bytesNeeded) {
        result += String.fromCodePoint(this.codePoint)
        this._reset()
      }
    }

    return result
  }

  flush() {
    const result = this.bytesNeeded > 0 ? '\ufffd' : ''
    this._reset()
    return result
  }

  _reset() {
    this.codePoint = 0
    this.bytesNeeded = 0
    this.bytesSeen = 0
    this.lowerBoundary = 0x80
    this.upperBoundary = 0xbf
  }
}

function trailingIncomplete(data, start) {
  const len = data.byteLength
  if (len <= start) return 0

  const limit = Math.max(start, len - 4)

  let i = len - 1
  while (i > limit && (data[i] & 0xc0) === 0x80) i--

  if (i < start) return 0

  const byte = data[i]

  let needed
  if (byte <= 0x7f) return 0
  if (byte >= 0xc2 && byte <= 0xdf) needed = 2
  else if (byte >= 0xe0 && byte <= 0xef) needed = 3
  else if (byte >= 0xf0 && byte <= 0xf4) needed = 4
  else return 0

  const available = len - i
  return available < needed ? available : 0
}

function trailingBytesSeen(data) {
  const len = data.byteLength
  if (len === 0) return 0

  const last = data[len - 1]

  if (last <= 0x7f) return 0
  if ((last & 0xc0) !== 0x80) return 1

  const limit = Math.max(0, len - 4)

  let i = len - 2
  while (i >= limit && (data[i] & 0xc0) === 0x80) i--

  if (i < 0) return 1

  const first = data[i]

  let needed
  if (first >= 0xc2 && first <= 0xdf) needed = 2
  else if (first >= 0xe0 && first <= 0xef) needed = 3
  else if (first >= 0xf0 && first <= 0xf4) needed = 4
  else return 1

  if (len - i !== needed) return 1

  if (needed >= 3) {
    const second = data[i + 1]
    if (first === 0xe0 && second < 0xa0) return 1
    if (first === 0xed && second > 0x9f) return 1
    if (first === 0xf0 && second < 0x90) return 1
    if (first === 0xf4 && second > 0x8f) return 1
  }

  return 0
}
{
  "name": "text-decoder",
  "version": "1.2.7",
  "description": "Streaming text decoder that preserves multibyte Unicode characters",
  "exports": {
    "./package": "./package.json",
    ".": "./index.js"
  },
  "files": [
    "index.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/text-decoder.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/text-decoder/issues"
  },
  "homepage": "https://github.com/holepunchto/text-decoder#readme",
  "dependencies": {
    "b4a": "^1.6.4"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  }
}
const { runtime, platform, arch, version } =
  typeof Bare !== 'undefined'
    ? {
        runtime: 'bare',
        platform: global.Bare.platform,
        arch: global.Bare.arch,
        version: global.Bare.version
      }
    : typeof process !== 'undefined'
      ? {
          runtime: 'node',
          platform: global.process.platform,
          arch: global.process.arch,
          version: global.process.version
        }
      : typeof Window !== 'undefined'
        ? { runtime: 'browser', platform: 'unknown', arch: 'unknown', version: 'unknown' }
        : { runtime: 'unknown', platform: 'unknown', arch: 'unknown', version: 'unknown' }

exports.runtime = runtime
exports.version = version
exports.platform = platform
exports.arch = arch
exports.isBare = runtime === 'bare'
exports.isBareKit = exports.isBare && typeof BareKit !== 'undefined'
exports.isPear = typeof Pear !== 'undefined'
exports.isNode = runtime === 'node'
exports.isBrowser = runtime === 'browser'
exports.isWindows = platform === 'win32'
exports.isLinux = platform === 'linux'
exports.isMac = platform === 'darwin'
exports.isIOS = platform === 'ios' || platform === 'ios-simulator'
exports.isAndroid = platform === 'android'
exports.isElectron = typeof process !== 'undefined' && !!global.process.versions?.electron
exports.isElectronRenderer = exports.isElectron && global.process.type === 'renderer'
exports.isElectronWorker = exports.isElectron && global.process.type === 'worker'
{
  "name": "which-runtime",
  "version": "1.4.0",
  "description": "Detect if you are in Bare or Node and which os etc",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte .",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/which-runtime.git"
  },
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/which-runtime/issues"
  },
  "homepage": "https://github.com/holepunchto/which-runtime",
  "devDependencies": {
    "brittle": "^3.0.0",
    "lunte": "^1.4.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
{
  "name": "hyper-overlay",
  "version": "0.3.13",
  "description": "Content-addressed P2P file distribution over Protomux — FastCDC chunking, multi-source fetch, resumable transfers, zero blob duplication. Files live on disk; the overlay is a thin index and transfer protocol.",
  "type": "module",
  "main": "index.js",
  "imports": {
    "#fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "#path": {
      "bare": "bare-path",
      "default": "path"
    },
    "#os": {
      "bare": "bare-os",
      "default": "os"
    },
    "#zlib": {
      "bare": "bare-zlib",
      "default": "zlib"
    }
  },
  "exports": {
    ".": "./index.js",
    "./overlay": "./lib/overlay.js",
    "./protocol": "./lib/protocol.js",
    "./messages": "./lib/messages.js",
    "./chunker": "./lib/chunker.js",
    "./chunk-scheduler": "./lib/chunk-scheduler.js",
    "./transfer": "./lib/transfer.js",
    "./file-index": "./lib/file-index.js",
    "./sync-engine": "./lib/sync-engine.js",
    "./tree": "./lib/tree.js",
    "./pointer": "./lib/pointer.js",
    "./ignore": "./lib/ignore.js",
    "./manifest": "./lib/manifest.js",
    "./package.json": "./package.json"
  },
  "scripts": {
    "test": "brittle-bare test/*.test.js test/integration/*.test.js",
    "test:node": "brittle-node test/*.test.js"
  },
  "engines": {
    "bare": ">=1.16.0"
  },
  "license": "AGPL-3.0",
  "keywords": [
    "p2p",
    "hypercore",
    "hyperbee",
    "protomux",
    "overlay",
    "content-addressed",
    "deduplication",
    "file-transfer",
    "fastcdc",
    "chunking",
    "multi-source",
    "resumable",
    "bare"
  ],
  "dependencies": {
    "b4a": "^1.0.0",
    "bare-fs": "^4.7.2",
    "bare-os": "^3.8.7",
    "bare-path": "^3.0.0",
    "bare-zlib": "^1.3.3",
    "compact-encoding": "^3.2.0",
    "corestore": "^7.0.0",
    "hyperbee": "^2.0.0",
    "hypercore-crypto": "^3.0.0",
    "protomux": "^3.0.0",
    "ready-resource": "^1.0.0",
    "sodium-universal": "^5.0.1",
    "streamx": "^2.0.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "hyperswarm": "^4.0.0",
    "@hyperswarm/testnet": "^3.1.4"
  }
}
// adopt — admit ANOTHER DEVICE into an existing DID over a blind-pairing tunnel instead of a file.
//
// Lives in hpp (not in a client) because ANY node holding the DID must be able to mint an invite for the
// next device — desktop or phone, symmetrically. That is keet's model: `addDevice`
// (contract/members/index.js) is available to any active member and the adder gains nothing by
// performing it. While this lived in the phone's tree, only the phone could mint.
//
// ⛔ THIS ADDS A TRANSPORT, NOT A CEREMONY. hyper-proto-peer's `coowner-invite` / `coowner-join` already
// do the whole cryptographic job, and do it correctly:
//   - chained attestation root -> existing -> joiner, with NO ROOT MNEMONIC anywhere (a node deliberately
//     never stores one; only the root's PUBLIC key, which every node already carries)
//   - the inviter pins `forceCreator` on itself, so growing the roster cannot silently demote it
//   - the joiner is written with `joiner: true` and WITHOUT `indexer` — a plain writer
// Those two lines are the loser-club fork and the N=2 quorum trap, already solved. Re-implementing any of
// it here would be writing a second, worse copy. This module only replaces the hand-off.
//
// WHAT WAS ACTUALLY MISSING. The existing ceremony moves the bundle as a FILE between two machines:
//     joiner$   hyper-proto-peer coowner-join <did>                  -> prints its device PUBLIC key
//     existing$ hyper-proto-peer coowner-invite <did> --device <hex> -> writes a bundle file
//     joiner$   hyper-proto-peer coowner-join <did> --bundle <file>
// That is fine between two servers you have shells on. It is useless for a phone: there is no shell, no
// scp, and the bundle CARRIES THE SHARED SIGNING KEY — so "move this secret by hand" is the worst
// possible instruction to give a user.
//
// The blind-pairing tunnel is strictly better than the file it replaces: one-time, owner-minted,
// end-to-end encrypted over the DHT, and the secret never touches a filesystem either side.
//
// ⚠ `coownerInvite` MUTATES THE LOCAL CONFIG (adds the member, pins forceCreator) as well as returning
// the bundle. So it must be called only AFTER the human approves — never speculatively on connection.
import { createPairInvite, joinPairInvite } from 'atproto-room/lib/pairing.js'
import { coownerInvite, coownerJoin } from './coowner.js'

// ── EXISTING DEVICE (desktop, or any already-attested device — NOT necessarily the root) ─────────────
//
// approve({ devicePublicKey, did }) -> boolean. Called when a phone reaches the tunnel and BEFORE any
// config is touched. Return false and the pairing is refused with the config untouched.
//
// Returns { inviteHex, waitForPeer, close } — same shape as createPairInvite, so a CLI or a UI can show
// the invite as text or a QR and then await the result.
export async function mintAdoptInvite ({ did, approve, configFile = null, swarm = null } = {}) {
  if (!did) throw new Error('mintAdoptInvite requires { did }')
  if (typeof approve !== 'function') throw new Error('mintAdoptInvite requires approve({ devicePublicKey, did }) -> boolean')

  let result = null

  const source = await createPairInvite({
    swarm,
    // The candidate's hello carries its device PUBLIC key. Same field the browser flow uses for a
    // sub-key — the tunnel does not care what the bytes mean, only this handler does.
    onSubkey: async (devicePublicKey) => {
      const ok = await approve({ devicePublicKey, did })
      if (!ok) {
        // Refusing must leave NOTHING behind: no roster entry, no forceCreator, no backup file.
        // Returning an error object rather than throwing keeps the tunnel's own teardown clean.
        return { error: 'refused by the device owner' }
      }
      // Only now does anything mutate. coownerInvite adds the member, pins our creator role, writes the
      // config (leaving a .bak), and hands back the bundle.
      const r = await coownerInvite({ did, devicePublicKey, configFile })
      result = { members: r.members, backup: r.backup, devicePublicKey }
      return r.bundle
    }
  })

  return {
    inviteHex: source.inviteHex,
    async waitForPeer () {
      await source.waitForPeer()
      return result // null iff refused
    },
    close: () => source.close()
  }
}

// ── PHONE ────────────────────────────────────────────────────────────────────────────────────────────
//
// Two calls, because the device key must exist before there is anything to attest:
//   1. coownerJoin({ did })          — mints a device mnemonic if absent, returns its PUBLIC key.
//                                      The mnemonic is written to config and never leaves the phone.
//   2. joinPairInvite(...)           — sends that public key up the tunnel, gets the bundle back.
//   3. coownerJoin({ did, bundle })  — writes the entry, sets joiner:true, leaves indexer unset.
//
// Step 3 is what makes the phone a NODE rather than a client: the bundle carries the shared #atproto
// signing key, so from here the phone materialises and signs its own commits.
// `did` is OPTIONAL and normally omitted — the invite alone is the whole handoff. The device mints its
// key knowing nothing (a keypair is derived from a mnemonic, not from an identity), sends the public
// half up the tunnel, and learns the DID from the bundle that comes back — which coownerJoin then
// cross-checks. Same shape as favela-web's browser join (bin/favela-web.js:962). Pass `did` only to
// ASSERT which identity you expect; a mismatch then throws instead of joining the wrong one.
export async function joinAdoptInvite ({ did = null, inviteHex, configFile = null, swarm = null, onStep = () => {} } = {}) {
  if (!inviteHex) throw new Error('joinAdoptInvite requires { inviteHex }')

  const pre = await coownerJoin({ did, configFile })
  onStep('device key ready', { devicePublicKey: pre.devicePublicKey })

  const bundle = await joinPairInvite(inviteHex, { subKey: pre.devicePublicKey, swarm })
  if (!bundle || bundle.error) throw new Error('adopt refused: ' + ((bundle && bundle.error) || 'no bundle'))
  onStep('bundle received', { did: bundle.did })

  const joined = await coownerJoin({ did: did || bundle.did, bundle, configFile })
  onStep('joined', { members: joined.entry.members })

  // The caller restarts the node; boot picks the entry up. Deliberately not restarting here — a pairing
  // function that also manages process lifecycle is two things.
  return { devicePublicKey: pre.devicePublicKey, entry: joined.entry, backup: joined.backup }
}
// Config — a file (${HOME}/.config/hyper-proto-peer/config.json) overlaid by PEER_* env, with
// defaults. One place decides storage/handle/pds/adopt so the daemon is config-driven (a normal
// pgh app), not purely env-driven. Env wins over file wins over default, so the pgh manifest's
// defaults.env and an operator's config.json both work.
//
// SECRETS STAY OUT OF GIT: the adopt device signing key (adoptDevicePrivHex) and the root
// mnemonic live in the operator's config.json on the box (or env at provision time) — NEVER in
// the committed manifest. The self-custody key is written to the vault (<storage>/peer-identity.json)
// on first boot and reloaded thereafter; config.json is only consulted to MINT the vault.

import fs from 'bare-fs'
import os from 'bare-os'
import path from 'bare-path'

const DEFAULT_DIR = path.join(os.homedir(), '.config', 'hyper-proto-peer')

function expand (v) {
  if (typeof v !== 'string') return v
  return v.replace(/\$\{HOME\}/g, os.homedir()).replace(/^~(?=\/|$)/, os.homedir())
}

// Normalize a WRITERS allowlist (Phase-2 write path): the hex Noise pubkeys of clients
// authorized to call the peer's `apply-write` RPC. Accepts an env comma-string
// (PEER_WRITERS) or a file array/comma-string (`writers`) → lowercased hex list, or null.
function normalizeWriters (raw) {
  if (!raw) return null
  const list = Array.isArray(raw) ? raw : String(raw).split(',')
  const set = list.map((s) => String(s).trim().toLowerCase()).filter(Boolean)
  return set.length ? set : null
}

// Normalize the device roster to [{ key: <hex>, role: 1 }] (all devices role-equal). Accepts a
// comma-string of hex pubkeys or an array of hex strings / {key,role} objects.
export function normalizeMembers (raw) {
  if (!raw) return null
  const list = Array.isArray(raw) ? raw : String(raw).split(',')
  const out = []
  for (const m of list) {
    const key = (typeof m === 'object' && m ? m.key : m)
    const hex = String(key || '').trim().toLowerCase()
    if (hex) out.push({ key: hex, role: 1 })
  }
  return out.length ? out : null
}

export function configPath () {
  return process.env.PEER_CONFIG || path.join(DEFAULT_DIR, 'config.json')
}

export function loadConfig () {
  let file = {}
  const p = configPath()
  try { file = JSON.parse(fs.readFileSync(p, 'utf8')) } catch { /* absent/invalid → defaults */ }

  const env = process.env
  const pick = (fileKey, envKey, def) => {
    if (env[envKey] != null && env[envKey] !== '') return env[envKey]
    if (file[fileKey] != null) return file[fileKey]
    return def
  }

  const storage = expand(pick('storage', 'PEER_STORAGE', path.join(DEFAULT_DIR, 'data')))
  const cfg = {
    storage,
    handle: pick('handle', 'PEER_HANDLE', 'peer.local'),
    pdsUrl: pick('pdsUrl', 'PEER_PDS_URL', 'https://pds.local'),
    appPassword: pick('appPassword', 'PEER_APP_PASSWORD', null),
    // WRITERS allowlist: hex Noise pubkeys allowed to call apply-write. Null (default) =
    // no remote writers → apply-write is NOT registered (secure default; the peer still
    // authors its own commits). See index.js (canWrite wiring) + lib/peer.js apply-write.
    writers: normalizeWriters(pick('writers', 'PEER_WRITERS', null)),
    // ADOPT an existing published DID (migration): presence of adoptDid + adoptDidKey +
    // adoptDevicePrivHex triggers Peer.adopt on first boot (only if no vault yet). adoptCar is
    // an optional path to a repo CAR whose records are imported (re-authored under the peer key).
    adoptDid: pick('adoptDid', 'ADOPT_DID', null),
    adoptDidKey: pick('adoptDidKey', 'ADOPT_DID_KEY', null),
    adoptDevicePrivHex: pick('adoptDevicePrivHex', 'ADOPT_DEVICE_PRIV_HEX', null),
    adoptCar: expand(pick('adoptCar', 'ADOPT_CAR', null)),
    // INIT a fresh self-custody identity (onboarding): the hyperident root recovery seed. Only
    // used when there is no vault AND no adopt block. Never stored in the vault.
    rootMnemonic: pick('rootMnemonic', 'PEER_ROOT_MNEMONIC', null),
    // MULTI-DEVICE swarm mode (atproto-base): boot a SwarmDevice (N attested devices of one DID
    // share the repo) instead of the single-tenant peer. Needs rootMnemonic (identity/shared-key
    // root) + deviceMnemonic (this device's keet identity, attested to the root).
    swarm: /^(1|true|yes)$/i.test(String(pick('swarm', 'PEER_SWARM', ''))),
    // ONE-TIME firehose repair: clear a malformed __commit__ log + re-emit a clean continuation from
    // the adoptCar baseline (guarded by a durable marker, so it's safe to leave set). See
    // bootSwarmDevice/SwarmDevice.resetFirehose. Set PEER_RESET_FIREHOSE=1 (or config resetFirehose).
    resetFirehose: /^(1|true|yes)$/i.test(String(pick('resetFirehose', 'PEER_RESET_FIREHOSE', ''))),
    deviceMnemonic: pick('deviceMnemonic', 'PEER_DEVICE_MNEMONIC', null),
    // The provisioned device BUNDLE (atproto-base-REVOCATION.md §4): a swarm device boots from these
    // — the received DID + shared signing key + root->device attestation + root identity pubkey —
    // NOT the root mnemonic (which it must never hold). Produced by provisionDevice() on the root.
    did: pick('did', 'PEER_DID', null),
    signingKey: pick('signingKey', 'PEER_SIGNING_KEY', null),
    deviceProof: pick('deviceProof', 'PEER_DEVICE_PROOF', null),
    rootIdentityKey: pick('rootIdentityKey', 'PEER_ROOT_IDENTITY_KEY', null),
    // bsky-login secrets (the peer is the sole auth authority): scrypt hash of the app-password +
    // the HMAC secret for session JWTs. Carried in the swarm config because the swarm boots from the
    // bundle, not the single-tenant vault. Enables com.atproto.server.createSession via the keyless
    // bridge. See lib/sessions.js + serve-membrane.js.
    appPasswordHash: pick('appPasswordHash', 'PEER_APP_PASSWORD_HASH', null),
    jwtSecret: pick('jwtSecret', 'PEER_JWT_SECRET', null),
    // The device ROSTER (co-equal multi-writer): the hex keet-identity pubkeys of ALL attested
    // devices of this DID. Each device is admitted iff it proves attestation AND is in this set.
    // Absent → self-only (this device signs; others can read/replicate but not co-sign). Accepts a
    // PEER_MEMBERS comma-string or a `members` file array of hex strings / {key,role} objects.
    members: normalizeMembers(pick('members', 'PEER_MEMBERS', null)),
    // MULTI-DID (multi-tenant) mode: a `dids` array in config.json — each entry a full per-DID bundle
    // { did, signingKey, deviceMnemonic, deviceProof, rootIdentityKey, handle, pdsUrl?, members?,
    // writers?, adopt? }. Present + swarm → index.js boots bootMultiDevice (ONE daemon, N DIDs, one
    // shared Corestore/swarm/wakeup). Absent → the single-DID path (this config's own did fields). A
    // user's own DID + the communities they co-own live here as separate entries.
    // Normalize each per-DID roster the same way the single-DID path does — bootMultiDevice passes
    // dids[] verbatim to bootSwarmDevice, whose projectMembers needs [{key,role}], NOT a raw
    // "hex,hex" comma-string. Without this a fresh multi-DID StateBase crashes on the roster encode.
    dids: Array.isArray(file.dids) ? file.dids.map((d) => ({ ...d, members: normalizeMembers(d && d.members) })) : null,
    configPath: p
  }
  return cfg
}
// conflict-watch — make hypercore conflicts VISIBLE.
//
// WHY THIS EXISTS. When two copies of one core disagree, hypercore freezes the core, closes every session
// on it with "Two conflicting signatures exist for length N", and stops replicating it. The only trace it
// leaves anywhere is a `console.log` at hypercore/lib/core.js:685 that upstream literally labels
// `// tmp log so we can see these`. Nothing in this stack listens for the `conflict` event — not hpp, not
// atproto-room, not autobase 7.28.1 — so no diagnostic surface can report one. loser-club logged conflicts
// on core 4a6f1b30 for weeks while `diag` reported a perfectly healthy node, because a healthy-looking node
// is exactly what a conflict produces: the served view stays correct, one core just silently stops syncing.
//
// PER-PROCESS BY DESIGN, and this is not a limitation. `checkConflict` sets `header.frozen = true` and
// writes it through `setAuth`, but the `@core/auth` encoding has no `frozen` field
// (hypercore-storage/encoding/spec/hyperschema/index.js:440) — it is dropped on encode and never read back.
// So hypercore's own conflict state is in-memory for the life of the process, and a registry that outlived
// the process would claim a freeze the running daemon does not actually have. "Conflicts seen since boot"
// is the honest window, and it is the same window hypercore itself uses.
//
// WHY IT HOOKS THE INTERNAL CORE. The `conflict` event is emitted on a Core's monitors
// (core.js:916-919), and most cores in this daemon are opened by AUTOBASE, not by us — we never see those
// sessions, so there is nothing of ours to attach a listener to. `corestore.watch(fn)` fires for every core
// opened in the store (and its namespaces, which share one core tracker), which is the only hook that
// reaches all of them. It yields the internal Core, so registration goes through `addMonitor` rather than
// `.on()`. That is an internal API: `test/conflict-watch.test.js` drives a REAL conflict between two cores
// end to end, so if upstream ever changes how conflicts are emitted this fails loudly instead of quietly
// reporting zero forever — which would be worse than not having it at all.
import b4a from 'b4a'

const hex = (b) => (b ? b4a.toString(b, 'hex') : null)

// Bounded: a conflicting core that keeps being re-offered must not grow this without limit. Records are
// keyed by core+length and counted, so a repeating conflict stays ONE row with a rising count.
const MAX_RECORDS = 256
const records = new Map()
const watched = new WeakSet()

export function recordConflict ({ discoveryKey, key, length, fork, writable, quorum, store }) {
  const id = discoveryKey + '@' + length
  const existing = records.get(id)
  if (existing) {
    existing.count++
    existing.lastSeenAt = new Date().toISOString()
    return existing
  }
  if (records.size >= MAX_RECORDS) return null
  const rec = {
    discoveryKey,
    key,
    length,
    fork,
    // Whether THIS machine can sign the forked core — the difference between "our key authored two
    // histories" and "someone else's fork arrived here", which is the first question triage asks.
    writable,
    quorum,
    store,
    count: 1,
    firstSeenAt: new Date().toISOString(),
    lastSeenAt: new Date().toISOString()
  }
  records.set(id, rec)
  return rec
}

function attach (core, store) {
  if (watched.has(core)) return
  watched.add(core)

  // A monitor is anything with `emit` and a `_monitorIndex` slot (core.js:79-89). Deliberately NOT a
  // Hypercore session: opening a session per core just to observe would keep every core alive and change
  // the very lifecycle we are trying to observe.
  // The FULL monitor contract, taken from every site that touches `core.monitors`: `emit` (core.js:98,
  // 104, 704-757, 917; replicator.js:3196-3240), `extensions` as a Map — iterated on every peer-add
  // (replicator.js:3199) — and a numeric `padding`, subtracted from byte counts on download/upload
  // (replicator.js:3211, 3220). Omitting the last two is not a silent degradation: it throws inside
  // replication and takes the connection down, which is how the first version of this was caught.
  const monitor = {
    _monitorIndex: -1,
    extensions: new Map(),
    padding: 0,
    emit (name, length, fork) {
      if (name !== 'conflict') return
      recordConflict({
        discoveryKey: hex(core.discoveryKey),
        key: hex(core.key),
        length,
        fork,
        writable: !!(core.header && core.header.keyPair),
        quorum: core.header && core.header.manifest ? core.header.manifest.quorum : null,
        store
      })
      // Keep the upstream line too — it is what every existing incident log was grepped for, and a report
      // that silently replaced it would break the habit before the new surface has earned trust.
      console.log(JSON.stringify({
        msg: 'CONFLICT — core froze and stopped replicating (in-memory only; returns on restart)',
        store,
        discoveryKey: hex(core.discoveryKey),
        key: hex(core.key),
        length,
        fork
      }))
    }
  }

  try { core.addMonitor(monitor) } catch { watched.delete(core) }
}

// Attach to every core this corestore opens, now and later. Namespaces share the root's core tracker, so
// watching the root covers `store.namespace(...)` opens too — no need to watch each namespace.
export function watchStore (store, label) {
  if (!store || typeof store.watch !== 'function') return store
  store.watch((core) => attach(core, label))
  return store
}

// The report `diag` collects. `seenSinceBoot` is stated rather than implied because a zero here means
// "none since this process started", NOT "none ever" — and a restart is exactly when they re-fire.
export function conflictDiag () {
  const all = [...records.values()].sort((a, b) => b.count - a.count)
  return {
    seenSinceBoot: all.length,
    total: all.reduce((n, r) => n + r.count, 0),
    truncated: records.size >= MAX_RECORDS,
    conflicts: all
  }
}

export function _reset () { records.clear() }
// coowner — admit another machine as a co-owner of a DID, as a COMMAND rather than a hand-edit.
//
// Co-owning a DID needs four things to line up on two machines: the joiner has its own device keypair,
// an existing co-owner has ATTESTED that keypair to the DID's root identity, both configs list both
// device keys in the roster, and the joiner holds the shared #atproto signing key. Done by hand that is
// four edits across two boxes with a secret in the middle — every one a chance to typo a hex string into
// a room that then silently refuses admission. It is also the exact operation anyone adding a second
// machine will need, so it belongs in the tool.
//
// The ceremony (mirrors pgv3's `pgh device invite` / `pgh device join` shape):
//
//   joiner$   hyper-proto-peer coowner-join <did>                  -> prints its device PUBLIC key
//   existing$ hyper-proto-peer coowner-invite <did> --device <hex> -> prints a bundle, adds the key locally
//   joiner$   hyper-proto-peer coowner-join <did> --bundle <file>  -> writes its dids entry
//   (restart both daemons)
//
// NO ROOT MNEMONIC IS INVOLVED. The invite is signed by the existing co-owner's own device key via
// keet's chained attestation (atproto-identity attestDeviceViaDevice): root -> existing -> joiner. The
// root mnemonic is deliberately never stored on a node, and this ceremony does not need it — only the
// root's PUBLIC key, which every node already carries as rootIdentityKey.
//
// THE BUNDLE CARRIES THE SHARED SIGNING KEY. That is inherent: a co-owner materializes the DID's signed
// commits, so it must hold the shared #atproto key (SwarmDevice's privateKey). Treat a bundle file as a
// secret — write it to a private path, move it over a trusted channel, delete it after joining.
//
// The joiner is admitted as a PLAIN WRITER, never an indexer (StateBaseV3's default). Two indexers is the
// N=2 quorum trap: the majority becomes 2, one loss freezes indexedLength, and the room forks. One
// indexer plus plain writers is the shape a 2-peer room wants.

import fs from 'bare-fs'
import b4a from 'b4a'
import IdentityKey from 'keet-identity-key'
import { deviceKeetKeyPair, attestDeviceViaDevice } from 'atproto-identity/lib/device-chain.js'
import { configPath } from './config.js'

const hex = (u8) => b4a.toString(b4a.from(u8), 'hex')

// ⛔ AN ABSENT CONFIG IS NOT AN ERROR — IT IS WHERE EVERY JOINER STARTS. A phone on first run has an
// hpp directory and no config file, so turning ENOENT into a hard failure meant the pairing ceremony
// died on its first line, before the tunnel even opened ("coowner: cannot read config at
// /data/user/0/to.favela.android/files/hpp/config.json (ENOENT…)").
//
// A MALFORMED config is still a hard failure, and deliberately so: silently replacing a corrupt file
// would discard a device's mnemonic and roster — the one thing that cannot be regenerated (a fresh key
// orphans an attestation and leaves the machine permanently unadmitted). Missing means "new"; unreadable
// means "stop".
// Exported for lib/mint.js, which writes the same `dids[]` file for a device that CREATES an identity
// rather than joining one. Shared rather than reimplemented on purpose: the ENOENT-is-not-an-error rule
// above and the backup-before-write rule below are both load-bearing, and a second copy would drift.
export function readConfigFile (p) {
  let raw
  try { raw = fs.readFileSync(p, 'utf8') } catch (e) {
    if (e && (e.code === 'ENOENT' || /ENOENT/.test(e.message || ''))) return {}
    throw new Error('coowner: cannot read config at ' + p + ' (' + e.message + ')')
  }
  try { return JSON.parse(raw) } catch (e) { throw new Error('coowner: cannot read config at ' + p + ' (' + e.message + ')') }
}

// Never write a config without leaving the previous one on disk. A mistyped roster locks a machine out
// of a room, and the old file is the fastest way back.
export function writeConfigFile (p, cfg) {
  const backup = p + '.bak.' + Math.floor(Date.now() / 1000)
  try { fs.copyFileSync(p, backup) } catch {}
  fs.writeFileSync(p, JSON.stringify(cfg, null, 2) + '\n')
  return backup
}

const findEntry = (cfg, did) => (cfg.dids || []).find((d) => d.did === did) || null

// Add a device key to a DID entry's roster, idempotently. The roster is the set of device ids that MAY be
// admitted; admission itself is still proof-gated, so listing a key grants nothing on its own.
function addMember (entry, deviceHex) {
  // ⛔ THE ROSTER IS NOT ALWAYS AN ARRAY. On disk it is an array of hex strings, an array of {key,role}
  // objects, OR a comma-separated string — wj62 in production is the string form. `config.js
  // normalizeMembers` accepts all three, but that is the BOOT path; this file reads the config with its
  // own raw JSON.parse, so it must accept them too. An `Array.isArray` gate treated a populated string
  // roster as EMPTY, which made `coownerInvite` rewrite it as [self, joiner] and silently DROP every
  // other device — a truncation performed by the command whose job is to grow the roster.
  // Control: test/coowner-members-string.test.mjs.
  const raw = entry.members
  const list = Array.isArray(raw) ? raw : (typeof raw === 'string' ? raw.split(',') : [])
  const cur = list.map((m) => String((typeof m === 'object' && m ? m.key : m) || '').trim()).filter(Boolean)
  const norm = cur.map((m) => m.toLowerCase())
  // A roster that was ABSENT means "self only" (bootSwarmDevice defaults to [{key:self}]), so the first
  // explicit roster must name the existing device too or it would silently drop it.
  if (!norm.length) return { members: null, added: false, needsSelf: true }
  if (norm.includes(String(deviceHex).toLowerCase())) return { members: cur, added: false }
  cur.push(String(deviceHex).toLowerCase())
  return { members: cur, added: true }
}

// ── coowner-invite (run on an EXISTING co-owner) ────────────────────────────────────────────────────
// Attest the joiner's device key against this DID's root (chained through OUR device), add it to our
// roster, and emit the bundle the joiner needs. Returns { bundle, backup, members }.
export async function coownerInvite ({ did, devicePublicKey, configFile = null } = {}) {
  if (!did) throw new Error('coowner-invite: <did> required')
  if (!/^[0-9a-fA-F]{64}$/.test(String(devicePublicKey || ''))) throw new Error('coowner-invite: --device <64-hex device public key> required')
  const p = configFile || configPath()
  const cfg = readConfigFile(p)
  const entry = findEntry(cfg, did)
  if (!entry) throw new Error('coowner-invite: this machine does not host ' + did + ' (no dids entry)')
  if (!entry.deviceMnemonic || !entry.deviceProof) throw new Error('coowner-invite: our entry lacks deviceMnemonic/deviceProof — cannot vouch for another device')
  if (!entry.signingKey || !entry.rootIdentityKey) throw new Error('coowner-invite: our entry lacks signingKey/rootIdentityKey — incomplete bundle')

  const parent = await deviceKeetKeyPair(entry.deviceMnemonic)
  const selfHex = hex(parent.publicKey)
  const childProof = attestDeviceViaDevice({
    parentKeyPair: parent,
    parentProof: b4a.from(entry.deviceProof, 'hex'),
    devicePublicKey: b4a.from(String(devicePublicKey), 'hex')
  })

  // Roster: both devices. An absent roster meant self-only, so seed it with US before adding THEM.
  const r = addMember(entry, devicePublicKey)
  const members = r.needsSelf ? [selfHex, String(devicePublicKey).toLowerCase()] : r.members
  entry.members = members

  // PIN OUR CREATOR ROLE. The creator election is `lowest-keyed member == self`, so growing the roster can
  // silently demote us: if the joiner's key sorts below ours we would stop opening the roomSeed-derived
  // genesis writer and ABANDON it, while the joiner claims it. That is the loser-club fork, reproduced in
  // test/coowner-join-role.test.js. A room's creator is a property of the room, not of key ordering.
  //
  // Only if we are not ourselves a joiner: chains nest, so a joiner can legitimately vouch for the next
  // machine, but it must never claim the genesis — that stays with whoever bootstrapped the room.
  //
  // ⛔ BUT INVITING IS NOT A CLAIM TO THE GENESIS. Keet is the reference here: `addDevice`
  // (contract/members/index.js) verifies the attestation, addWriters the device, and gives the ADDER
  // nothing — no role moves, because keet has no creator election at all (its room key IS the autobase
  // key, so there is no roomSeed-derived genesis writer to claim or abandon). Our election is a local
  // construct, so the pin must be too: it may only ever RE-STATE a role this node already holds.
  //
  // Two nodes are wrongly captured by a bare `!entry.joiner`:
  //   - one forced non-creator by `resyncStore` (device-node.js:178) — a RUNTIME flag, invisible here,
  //     which is tabertron's posture for wj62. state-base.js:406 checks _forceCreator BEFORE
  //     _forceNonCreator, so writing the pin would WIN and the DID would have two creators.
  //   - one carrying an explicit `forceCreator: false`, which is a decision on file.
  // Both must be able to invite the next device without changing who holds the genesis.
  if (!entry.joiner && entry.forceCreator !== false) entry.forceCreator = true
  const backup = writeConfigFile(p, cfg)

  return {
    backup,
    members,
    bundle: {
      did,
      handle: entry.handle || null,
      pdsUrl: entry.pdsUrl || null,
      signingKey: entry.signingKey,       // SECRET — the shared #atproto key a co-owner signs with
      rootIdentityKey: entry.rootIdentityKey,
      deviceProof: hex(childProof),        // root -> us -> joiner
      storeBackend: entry.storeBackend || null,
      members
    }
  }
}

// ── coowner-join (run on the JOINER) ───────────────────────────────────────────────────────────────
// Without --bundle: ensure this machine has a device mnemonic for the DID and print its PUBLIC key (the
// mnemonic stays here and is never printed). With --bundle: write the full dids entry.
// Idempotent: an existing mnemonic is REUSED, never regenerated — regenerating would orphan an already
// attested key and leave the machine permanently unadmitted.
//
// ⛔ THE DID IS OPTIONAL. A device keypair is derived from a mnemonic and nothing else
// (`deviceKeetKeyPair(mnemonic)` takes no DID), so a device can mint its key BEFORE it knows which
// identity it is joining — which is what lets a single opaque invite be the whole handoff. favela-web's
// browser join already works this way (bin/favela-web.js:962): generate locally, send only the invite,
// take the identity from what comes back. Without this, the phone had to be TOLD a DID that the bundle
// then hands back anyway (and that `:140` below already cross-checks).
//
// The mnemonic therefore lives at CONFIG ROOT — it identifies the DEVICE, not one of its rooms — with a
// per-DID mnemonic still winning when present. That ordering is load-bearing: an existing per-DID key
// may already be attested, and replacing it would orphan the attestation and leave the machine
// permanently unadmitted (the same hazard the "never regenerate" rule above guards).
export async function coownerJoin ({ did = null, bundle = null, configFile = null } = {}) {
  const p = configFile || configPath()
  const cfg = readConfigFile(p)
  if (!Array.isArray(cfg.dids)) cfg.dids = []
  // A bundle names its own DID; the caller need not.
  if (!did && bundle && bundle.did) did = bundle.did
  if (!did && bundle) throw new Error('coowner-join: bundle carries no did')
  let entry = did ? findEntry(cfg, did) : null

  // Key selection, most-specific first: an already-attested per-DID key, else this device's own.
  if (entry && entry.deviceMnemonic) {
    // keep it — never regenerate
  } else if (!cfg.deviceMnemonic) {
    cfg.deviceMnemonic = IdentityKey.generateMnemonic()
  }
  const mnemonic = (entry && entry.deviceMnemonic) || cfg.deviceMnemonic

  // With no DID at all we are in step 1 of the ceremony: mint/reuse the key, report it, write nothing
  // else. The entry cannot exist yet — the bundle that names the DID has not arrived.
  if (!did) {
    const kp0 = await deviceKeetKeyPair(mnemonic)
    const backup0 = writeConfigFile(p, cfg)
    return { devicePublicKey: hex(kp0.publicKey), joined: false, backup: backup0, entry: null }
  }

  if (!entry) {
    entry = { did }
    cfg.dids.push(entry)
  }
  const kp = await deviceKeetKeyPair(mnemonic)
  const devicePublicKey = hex(kp.publicKey)

  if (bundle) {
    if (bundle.did && bundle.did !== did) throw new Error('coowner-join: bundle is for ' + bundle.did + ', not ' + did)
    if (!bundle.deviceProof || !bundle.signingKey || !bundle.rootIdentityKey) throw new Error('coowner-join: bundle must carry deviceProof, signingKey and rootIdentityKey')
    entry.deviceProof = bundle.deviceProof
    entry.signingKey = bundle.signingKey
    entry.rootIdentityKey = bundle.rootIdentityKey
    if (bundle.handle) entry.handle = bundle.handle
    if (bundle.pdsUrl) entry.pdsUrl = bundle.pdsUrl
    if (bundle.storeBackend) entry.storeBackend = bundle.storeBackend
    if (Array.isArray(bundle.members) && bundle.members.length) {
      const set = bundle.members.map((m) => String(typeof m === 'object' && m ? m.key : m).toLowerCase())
      if (!set.includes(devicePublicKey)) set.push(devicePublicKey)
      entry.members = set
    }
    // JOINER POSTURE (load-bearing). Without this the joiner elects itself creator whenever its key sorts
    // below the incumbent's, opens the roomSeed-derived genesis writer empty-and-writable in its fresh
    // store, and the boot-write block authors a rival genesis — the loser-club fork. `joiner` makes it
    // forceNonCreator AND converge-only at boot (no migratePointers/restore/adopt/fresh-account), so it
    // takes the existing line by replication and the forward-only sign() picks up at the tip.
    // Proven two-node in test/coowner-join-role.test.js, control included.
    entry.joiner = true
    // A joiner must never also be pinned as creator — exactly one node holds the genesis.
    delete entry.forceCreator
    // Deliberately NOT set: `indexer`. The joiner is a plain writer — see the header (N=2 quorum trap).
  }

  const backup = writeConfigFile(p, cfg)
  return { devicePublicKey, joined: !!bundle, backup, entry: { did, handle: entry.handle || null, storeBackend: entry.storeBackend || null, members: entry.members || null } }
}

// CLI arg helpers shared by index.js's subcommand dispatch.
export function coownerCli (sub, args) {
  const did = args.find((a) => a.startsWith('did:'))
  const flag = (name) => { const i = args.indexOf(name); return i < 0 ? null : args[i + 1] }
  if (sub === 'coowner-invite') return coownerInvite({ did, devicePublicKey: flag('--device'), configFile: flag('--config') })
  const bundleFile = flag('--bundle')
  let bundle = null
  if (bundleFile) bundle = JSON.parse(fs.readFileSync(bundleFile, 'utf8'))
  return coownerJoin({ did, bundle, configFile: flag('--config') })
}
// atproto-base device boot — the ROOT provisions devices; a DEVICE boots from its bundle, never the
// root mnemonic (atproto-base-REVOCATION.md §4). provisionDevice (root-side) creates the swarm
// identity + attests a device; bootSwarmDevice (device-side) brings the device up from the received
// { did, signingKey, deviceProof, rootIdentityKey } + its own deviceMnemonic.

import crypto from 'hypercore-crypto'
import b4a from 'b4a'
import fs from 'bare-fs'
import process from 'bare-process' // for the OTA respawn exit — Bare has no global process

// Set by the daemon entrypoint, which owns close() and therefore the exit. Kept module-level rather than
// threaded through bootMultiDevice -> bootSwarmDevice because the UDS surface is created deep inside the
// per-device boot and the only thing it needs is "tell whoever owns the process".
let otaHandler = null
export function setOtaHandler (fn) { otaHandler = typeof fn === 'function' ? fn : null }
import Hyperswarm from 'hyperswarm'
import ProtomuxWakeup from 'protomux-wakeup'
import Protomux from 'protomux'
import { CID } from 'multiformats/cid'
import { join } from 'bare-path'
import { createSwarmIdentity } from 'atproto-identity'
import { StateBaseV3 } from 'atproto-room/lib/state-base.js'
import { SwarmDevice } from './swarm-device.js'
import { nextRetry } from './reconcile-retry.js'
import { serveDevice } from './serve-device.js'
import { serveDeviceUds } from './serve-device-uds.js'
import { serveMembrane } from 'atproto-room/lib/serve-membrane.js'
import { BlobStore } from 'atproto-store/lib/blob-store.js'
import { OverlayBlobStore } from 'atproto-store/lib/overlay-blob-store.js'
import { BlobPointerStore } from 'atproto-store/lib/blob-pointer-store.js'
import { DualBlobStore } from './dual-blob-store.js'
import { OverlayRepoStore } from 'atproto-store/lib/overlay-repo-store.js'
import { HyperOverlay } from 'hyper-overlay'
import { openCorestore } from 'atproto-store/lib/corestore.js'
// Every corestore is wrapped so a hypercore conflict is RECORDED, not just console.logged by upstream.
// See lib/conflict-watch.js — nothing in this stack listened for the `conflict` event before this.
import { watchStore } from './conflict-watch.js'
import { AccountRegistry } from 'atproto-store/lib/account-registry.js'
import { loadOrCreateSwarmKeyPair } from './swarm-keypair.js'
import { normalizeMembers } from './config.js'
import { makeSessions } from './sessions.js'
import { readCar, loadCommit, listRecords } from 'atproto-repo/lib/repo.js'

// Read an existing repo CAR (e.g. wj62's, exported via the bridge) into the { records, head } shape
// bootSwarmDevice's `adopt` option consumes — so a config `adoptCar` path continue-migrates a live
// account into the swarm.
export async function readAdoptRepo (carBytes) {
  const car = await readCar(carBytes)
  const lc = loadCommit(car)
  const sc = lc.value
  const records = listRecords(car).map((r) => { const i = r.key.indexOf('/'); return { collection: r.key.slice(0, i), rkey: r.key.slice(i + 1), record: r.value } })
  return { records, head: { rev: sc.rev, commitCid: lc.cid, dataCid: sc.data, signedCommit: sc } }
}
import { makeAttest, makeVerifyAttest, attestDeviceChain, deviceKeetKeyPair, rootIdentityPublicKey } from 'atproto-room/lib/membership.js'

const NS = (s) => b4a.from('atproto-base/v1/' + s)

// provisionDevice — ROOT-side: create the swarm identity + attest ONE device, producing the bundle
// the device boots from. The root holds the mnemonic (recovery + signing keys); the device receives
// { did, signingKey, deviceProof, rootIdentityKey } — NEVER the root, so it can't derive the recovery
// key or self-recover. signingKey is the sensitive part and should be delivered encrypted (the
// broadcast-encryption slice); this just assembles the bundle. Also returns the signed genesis op
// (for PLC registration) + recoveryKey stays with the root (NOT in the bundle).
export async function provisionDevice ({ rootMnemonic, devicePublicKey, handle, pdsUrl } = {}) {
  if (!rootMnemonic || !devicePublicKey) throw new Error('provisionDevice: rootMnemonic + devicePublicKey required')
  const devPub = typeof devicePublicKey === 'string' ? b4a.from(devicePublicKey, 'hex') : devicePublicKey
  const id = createSwarmIdentity(rootMnemonic, { handle, pdsUrl })
  const deviceProof = await attestDeviceChain({ rootMnemonic, devicePublicKey: devPub })
  const rootPub = await rootIdentityPublicKey(rootMnemonic)
  return {
    did: id.did,
    signingKey: b4a.toString(id.signingKey.privateKey, 'hex'),
    deviceProof: b4a.toString(b4a.from(deviceProof), 'hex'),
    rootIdentityKey: b4a.toString(rootPub, 'hex'),
    handle,
    pdsUrl,
    signedOp: id.signedOp // for PLC registration (root-side; NOT needed to boot a device)
  }
}

// provisionAdoptedDevice — ROOT-side, ADOPT-INTO-SWARM: provision a device for an EXISTING DID with
// a GIVEN #atproto signing key (e.g. wj62's raw adopted key from its vault) + a SEPARATE keet
// membership root that governs device attestation. The atproto identity (did + signing key + its PLC
// registration) is UNCHANGED — no PLC op; the keet root is new and only decides which devices may
// sign. Returns the { did, signingKey, deviceProof, rootIdentityKey } bundle bootSwarmDevice consumes.
export async function provisionAdoptedDevice ({ did, signingKey, keetRootMnemonic, devicePublicKey } = {}) {
  if (!did || !signingKey || !keetRootMnemonic || !devicePublicKey) throw new Error('provisionAdoptedDevice: did, signingKey, keetRootMnemonic, devicePublicKey required')
  const devPub = typeof devicePublicKey === 'string' ? b4a.from(devicePublicKey, 'hex') : devicePublicKey
  const deviceProof = await attestDeviceChain({ rootMnemonic: keetRootMnemonic, devicePublicKey: devPub })
  const rootPub = await rootIdentityPublicKey(keetRootMnemonic)
  return {
    did,
    signingKey: typeof signingKey === 'string' ? signingKey : b4a.toString(signingKey, 'hex'),
    deviceProof: b4a.toString(b4a.from(deviceProof), 'hex'),
    rootIdentityKey: b4a.toString(rootPub, 'hex')
  }
}

// `joiner` — this device is JOINING an existing room, not bootstrapping one. It must never claim the
// deterministic genesis writer and must write NOTHING at boot; it converges by replication and the
// forward-only sign() picks up from the tip.
//
// This exists because the creator election is `lowest-keyed member == self` (state-base.js _amCreator),
// so admitting a device whose key sorts BELOW the existing creator's silently flips the role: the joiner
// elects itself creator, opens the roomSeed-derived gsKeyPair EMPTY-and-writable in its fresh store and
// authors a rival genesis, while the incumbent — no longer lowest — opens keyPair=null and ABANDONS the
// genesis writer it had been using. Both halves are wrong and neither errors. Observed in production
// admitting a second machine to loser-club: the joiner came up amCreator=true with its own 1-record head
// while the incumbent logged "stays a PLAIN WRITER". Membership is cryptographic and worked perfectly;
// the ROLE is what broke.
//
// So a room's creator is an explicit property, not an emergent consequence of key ordering: the joiner
// sets `joiner` and the incumbent sets `forceCreator`. Same shape as the resync path, which already had
// to solve exactly this for a creator rejoining from a fresh store.
export async function bootSwarmDevice ({ storage, deviceMnemonic, did, signingKey, deviceProof, rootIdentityKey, handle, pdsUrl, swarm = true, swarmOpts = null, signIntervalMs = 2000, members = null, control = null, writers = null, adopt = null, resetFirehose = false, appPasswordHash = null, jwtSecret = null, shared = null, records = null, federationHeartbeatMs = 0, primary = false, storeBackend = null, resyncStore = null, forceCreator = false, joiner = false, projectRepoCore = true, onRelease = null } = {}) {
  if (typeof storage !== 'string') throw new Error('bootSwarmDevice: storage path required')
  if (!deviceMnemonic) throw new Error("bootSwarmDevice: deviceMnemonic (this device's own identity) required")
  if (!did || !signingKey || !deviceProof || !rootIdentityKey) throw new Error('bootSwarmDevice: provisioned bundle (did, signingKey, deviceProof, rootIdentityKey) required — run provisionDevice on the root')

  // RECEIVED material — the shared signing key, the root identity pubkey, and this device's
  // attestation. NONE of it is the root mnemonic (so this device cannot derive the recovery key).
  const sharedKey = typeof signingKey === 'string' ? b4a.from(signingKey, 'hex') : signingKey
  const rootPub = typeof rootIdentityKey === 'string' ? b4a.from(rootIdentityKey, 'hex') : rootIdentityKey
  const proof = typeof deviceProof === 'string' ? b4a.from(deviceProof, 'hex') : deviceProof

  // members-only room secrets — derivable only by devices that hold the DID + shared signing key
  const roomKey = crypto.hash([NS('room-key'), b4a.from(did)])
  const roomSeed = crypto.hash([NS('room-seed'), b4a.from(sharedKey)])
  const encryptionKey = crypto.hash([NS('enc'), b4a.from(sharedKey)])

  // this device's OWN keet identity + the root→device attestation it was provisioned with
  const deviceKp = await deviceKeetKeyPair(deviceMnemonic)
  const self = b4a.toString(deviceKp.publicKey, 'hex')
  // NORMALISE AT THE BOUNDARY, do not trust the caller to have done it. `members` reaches here in three
  // shapes — [{key,role}], an array of hex strings, or a "hex,hex" comma-string — and projectMembers
  // understands only the first (state-base.js reads `m.key`, so a plain string yields undefined and is
  // skipped, producing an EMPTY map). loadConfig normalises, so every node booting through it is fine;
  // a caller that parses config.json itself is not. favela-android did exactly that, and its roster
  // silently evaporated: the room refused to project, logging "empty roster would wipe 3 existing
  // member(s)" every 30s while its config plainly listed three. Third instance of this trap in this
  // codebase (see coowner.js) — hence fixing it where the value is CONSUMED, not in each reader.
  // Idempotent for already-normalised input, which is what every fleet node passes today.
  const roster = normalizeMembers(members) || [{ key: self, role: 1 }]

  // ── PRE-CUTOVER DID: keep the StateBase WHERE IT ALREADY IS ──────────────────────────────────────
  // `primary` already means "this DID predates the multi-DID cutover on this box, keep its paths
  // stable" — it preserves the flat control.sock, swarm-keypair and membrane. It did NOT cover the
  // StateBase, which relocated from its own corestore at <storage>/statebase into a namespace of the
  // shared store. That relocation is not cosmetic: StateBaseV3 derives its local writer from the
  // corestore's primaryKey (own store) vs the shared store's primaryKey + roomKey namespace, so moving
  // it gives the DID a DIFFERENT writer on an EMPTY base. The creator's genesis writer is deterministic,
  // so it re-opens empty-and-writable and the boot-write block authors a fresh genesis — i.e. the DID's
  // history is left behind in the old directory.
  //
  // wj62 survived that relocation only because it had a CO-OWNER to backfill from. A single-homed DID has
  // no such peer, which is the entire reason ashatron could not move onto the unified path. Keeping the
  // StateBase in place removes the need for a peer: the writer identity and history are untouched, and
  // only the boot path changes. The daemon replicates this store explicitly (see _statebaseStore on the
  // returned node), exactly as it already does for a resync side store. Nothing is moved, copied or
  // deleted — the fix is to STOP relocating.
  const legacyStatebasePath = join(storage, 'statebase')
  const keepLocalStatebase = !!shared && !!primary && !resyncStore && fs.existsSync(legacyStatebasePath)
  if (keepLocalStatebase) console.log(JSON.stringify({ msg: 'pre-cutover DID: keeping its StateBase in place (own corestore) instead of re-homing to the shared store', did, path: legacyStatebasePath }))
  const sb = new StateBaseV3((keepLocalStatebase || !shared) ? legacyStatebasePath : null, roomKey, {
    roomSeed,
    encryptionKey,
    // Multi-DID: open on the daemon's SHARED Corestore (a per-DID namespace) + SHARED wakeup, and
    // create no swarm of our own — the daemon owns store+swarm+wakeup and drives replication
    // (bootMultiDevice). Single-DID keeps its own per-room store + swarm exactly as before.
    network: shared ? false : swarm,
    // RESYNC (fresh-corestore re-join): a poisoned autobase local writer lives in the SHARED store,
    // keyed by that store's primaryKey — a fresh namespace re-derives the SAME poisoned writer (pgv3 #4).
    // resyncStore is a DEDICATED per-DID Corestore (its own primaryKey → a CLEAN local writer) that joins
    // the SAME base (roomKey-derived key) as a fresh replica of the group's healthy state. Only the
    // StateBase base re-homes here; the overlay/membrane/control keypair stay on shared.store (below), so
    // the bridge-facing serverKey/coords are unchanged — the resync is transparent to the bridge. The old
    // poisoned cores stay on disk in shared.store (nothing deleted). Read-only until re-admitted (the tick
    // loop's ensureAdmitted rings the doorbell; a current indexer addWriters the fresh local key).
    // keepLocalStatebase: pass NO store so StateBaseV3 opens its own Corestore at the legacy path,
    // preserving the writer identity derived from that store's primaryKey.
    store: resyncStore || ((shared && !keepLocalStatebase) ? shared.store : undefined),
    // RESYNC heal: force this fresh-corestore re-join to open as a NON-creator (fresh local writer), so
    // the deterministic genesis writer becomes a REMOTE writer that linearizes — instead of an
    // un-sheddable local writer autobase won't linearize (diagnostic 1). Mirrors keet's fresh-writer rejoin.
    // A JOINER takes the same posture as a resync: never elect as creator, so the roomSeed-derived
    // gsKeyPair stays with the incumbent and becomes a REMOTE writer here that replicates + linearizes.
    // Without this, a joiner whose key sorts below the incumbent's wins the election and authors a rival
    // genesis (see the `joiner` note on bootSwarmDevice).
    forceNonCreator: !!resyncStore || !!joiner,
    // assume-genesis heal: a healthy co-owner re-assumes the deterministic genesis writer/indexer after
    // the original creator abandoned it via a resync. Mutually exclusive with resync (resync wins).
    forceCreator: forceCreator && !resyncStore,
    wakeup: shared ? shared.wakeup : undefined,
    swarmOpts,
    selfKey: deviceKp.publicKey,
    attest: makeAttest(deviceKp, proof),
    verifyAttest: makeVerifyAttest(rootPub),
    getMembers: async () => roster
  })
  await sb.ready()
  // Project the roster into __members__ so admission is attestation-gated. The CREATOR (lowest-key
  // member — StateBaseV3._amCreator) persists it; peers replicate it. ONE call: StateBaseV3 retains
  // the roster and re-projects EVENT-DRIVEN + self-terminating (on its promote-timer tick + every new
  // swarm connection) until __members__ lands in its view. This REPLACES the old bounded 12-try boot
  // loop, which gave up before writability settled whenever the creator became writable AFTER the
  // ~13s window (re-adopt + swarm flap) → __members__ never landed → admission verifiedRole=null →
  // members held their own lines (the wj62 fork; hyper-social #9, pear-git #4 lineage).
  //
  // ⚠ Keeps the BOOT-HANG fix: NO `sb.get('__members__')` base.update() poll here (that could hang a
  // freshly-admitted plain writer) — this call is non-blocking, boot proceeds, projection self-drives
  // in the background. A non-creator's call no-ops (peers replicate __members__).
  //
  // RESYNC anti-fork (part 2): on a fresh-corestore re-join the CREATOR's projectMembers would WRITE
  // __members__ into its EMPTY genesis core (base.local == base.key for the creator) BEFORE replication
  // backfills it — the same fork the boot-write gate below prevents (diagnosed via localLen=2 on the
  // supposedly converge-only side store, test/resync-creator-convergence.test.js). __members__ already
  // exists in the network (the base was admitting writers before), so it REPLICATES in; the creator must
  // NOT re-project it on a resync. Skip entirely — write nothing until the genesis core has backfilled.
  if (!resyncStore) await sb.projectMembers(roster).catch(() => {})

  // firehose:true — sign() persists each signed #commit into the shared __commit__ log, which the
  // membrane surface projects + serves to the bridge (Phase D). Without it there is nothing to front.
  // Optional file-based record store (records-as-files, O(current) — off the append-only StateBase).
  // Flag-gated (storeBackend:'overlay'); reserved "__" keys stay on the StateBase. Records are LOCAL
  // deduped files. hyper-overlay is pure content-addressed STORAGE/distribution here (dedup + serve
  // bytes by hash); it does NOT converge trees. Cross-device convergence is the atproto firehose:
  // the non-signer ingests the signer's firehose and writes record bytes to these files (task B).
  let recordStore = null
  let recordOverlay = null
  let repoRoot = null
  if (storeBackend === 'overlay') {
    repoRoot = join(storage, 'atproto-repo', b4a.toString(roomKey, 'hex').slice(0, 16))
    // HyperOverlay = content-addressed store for record bytes (+ blobs). Keyed by roomKey so N DIDs'
    // overlays coexist on the daemon's ONE shared connection for content SERVING (per-DID channel id).
    // Uses the shared corestore (namespaced) when multi-DID, else a dedicated one.
    const ovStore = shared ? shared.store : watchStore(openCorestore(join(storage, 'atproto-repo-overlay')), 'atproto-repo-overlay')
    recordOverlay = new HyperOverlay(ovStore, { namespace: 'atproto-repo-overlay:' + did, key: roomKey, destDir: join(repoRoot, '.fetch') })
    await recordOverlay.ready()
    recordStore = await new OverlayRepoStore(repoRoot, { overlay: recordOverlay }).ready()
    console.log(JSON.stringify({ msg: 'record store: overlay (content-addressed files)', did, path: repoRoot }))
  }
  const device = new SwarmDevice(sb, { did, privateKey: sharedKey, self, firehose: true, recordStore })
  // NO unconditional boot claim: that let a booting device STEAL a still-valid lease before it had
  // replicated the current holder's lease (the split-brain root cause). The sign loop claims lazily
  // + safely via renewOrClaim (claim ONLY if the lease is free/TTL-lapsed), after replication has had
  // ticks to converge. The creator's fresh-account bootstrap force-signs its initial commit below.

  // adopt-into-swarm continuity: the writable (creator/origin) device imports the existing repo's
  // records + head so the swarm CONTINUES the chain (next sign: prev = adopted commit, prevData =
  // adopted data root) instead of re-authoring. Records replicate to peers via StateBaseV3. See
  // atproto-pds-ref §2/§7. adopt = { records:[{collection,rkey,record}], head:{rev, commitCid,
  // dataCid} } (CIDs may be strings — parsed here).
  // RESYNC (creator-aware anti-fork gate) — CONVERGE-ONLY boot, write NOTHING. A fresh-corestore re-join
  // is a REPLICA of an EXISTING base whose authoritative pointers + #commits already live in the network;
  // this device's local record FILES may be STALE. The block below appends to base.local (migratePointers
  // backfills file-pointers; restore/adopt/fresh seed head + commits). For the CREATOR that append is fatal:
  // its genesis writer key is DETERMINISTIC (_gsKeyPair), so a fresh corestore re-opens the SAME writer
  // EMPTY and immediately `writable` (NOT shed — test/resync-creator-fork.repro.mjs 4/4). Appending stale
  // file-pointers into that empty genesis core BEFORE replication backfills it FORKS the writer (the
  // df0c052a split-brain, docs/POSTMORTEM-2026-07-21-stortron-wj62-poison-heal.md). The heal: write nothing
  // at boot → base.local backfills from the healthy peer (proven test/creator-writer-backfill.probe.mjs 7/7)
  // → the base converges by replication → the tick loop's FORWARD-ONLY-gated sign() continues the ONE chain
  // at the tip. The network is authoritative for a resynced replica; nothing is deleted (files stay on disk),
  // and a converged migratePointers would be a no-op anyway (idempotent — pointers already replicated in).
  // A JOINER boots converge-only for the same reason a resync does: the authoritative pointers and
  // #commits already exist in the network, so anything written here before replication backfills is a
  // fork. Critically this also suppresses the FRESH-ACCOUNT bootstrap below — on a joiner the log reads
  // empty at boot, so that branch would author an initial commit and a rival head. That is exactly what
  // happened admitting a second machine to loser-club: it came up holding one self-authored record.
  if (resyncStore || joiner) {
    console.log(JSON.stringify({ msg: (resyncStore ? 'resync' : 'joiner') + ': converge-only boot — skipping all local writes (migratePointers/restore/adopt/fresh-account) until replication converges; forward-only sign() continues the chain', did }))
  } else if (sb.base.writable) {
    const cid = (v) => (typeof v === 'string' ? CID.parse(v) : v)
    // STEP 2a MIGRATION (files-only → pointers) — MUST run before any listRecords() below. A repo
    // written by the previous files-only backend (OverlayRepoSubstrate) has its record BYTES on disk
    // but NO pointers in the shared autobase; under PointerSubstrate listRecords() would read ZERO,
    // so the adopt/restore/fresh branch below would mis-classify a populated repo as empty AND the
    // first sign() would wipe it (the wj62 hazard). Backfill a {$oid,size} pointer per un-pointed
    // record file first (idempotent, writable-only, never clobbers a converged pointer/tombstone).
    // The sign() anti-wipe guard is the belt-and-suspenders backstop if this hasn't completed yet.
    // STEP 2a-0 MIGRATION (INLINE records → pointers) — MUST run before migratePointers and before any
    // listRecords() below, because it covers the one shape that would otherwise WIPE the repo.
    //
    // A DID written through the legacy substrate holds full RECORDS in the autobase where {$oid,size}
    // pointers belong, and no record FILES at all. Under PointerSubstrate that reads as an EMPTY record
    // set — _resolve passes ptr.$oid (undefined) to ensureLocal, which falls back to the local file, and
    // with no file it returns null so the key is dropped. The anti-wipe guard in sign() does NOT catch
    // this: it only aborts when record FILES exist, and here there are none. So the first sign() after
    // flipping such a DID to storeBackend:'overlay' would materialize an empty MST root and publish a
    // delete-every-record commit. That is e2jev's exact state (hyper-social#16 P1).
    //
    // migrateInline is the fix and its fromInline branch handles precisely this case — it writes the file
    // FROM the inline copy, then publishes the pointer. Content is preserved rather than chosen: the
    // pointer addresses the bytes that already resolve, asserted by hash, and it REFUSES any key whose
    // oid would change. Writable-only; peers converge the pointers by replication.
    //
    // MARKER-GUARDED (__inline_migrated__) because unlike backfill this REWRITES autobase entries, which
    // must not happen implicitly on every start. Idempotent regardless (a converted entry has $oid and is
    // skipped), so the marker is belt-and-braces, not the only protection.
    try {
      const inlineDone = await sb.get('__inline_migrated__').catch(() => null)
      if (!inlineDone) {
        const mi = await device.migrateInlinePointers()
        if (mi && !mi.skipped) {
          await sb.set('__inline_migrated__', { ts: Date.now(), converted: mi.converted, fromInline: mi.fromInline, total: mi.total })
          if (mi.converted || mi.mismatched || mi.failed) {
            console.log(JSON.stringify({ msg: 'step-2a-0: inline records converted to fetchable pointers', did, ...mi }))
          }
        }
      }
    } catch (e) { console.error(JSON.stringify({ msg: 'step-2a-0: inline migration failed — NOT flipping this DID is safer than signing an empty set', did, error: e.message })) }
    try {
      const mig = await device.migratePointers()
      if (mig && mig.written) console.log(JSON.stringify({ msg: 'step-2a: backfilled files-only records into pointers', did, ...mig }))
    } catch (e) { console.error(JSON.stringify({ msg: 'step-2a: pointer backfill failed (anti-wipe guard still protects)', did, error: e.message })) }
    // ONE-TIME firehose repair (resetFirehose flag): if the shared __commit__ log accumulated malformed
    // frames (full-set re-authors from before the restore fix, which a relay rejects on prevData), clear
    // it + re-emit a single clean continuation from the adoptCar baseline. Guarded by the durable
    // __firehose_reset__ marker so it fires EXACTLY once across the swarm (the origin does it; peers see
    // the marker + skip). NB: also move each device's membrane corestore aside before this boot so the
    // derived firehose Hypercore is rebuilt from the now-clean log (operational step in the runbook).
    const resetDone = resetFirehose ? await sb.get('__firehose_reset__').catch(() => null) : true
    if (resetFirehose && !resetDone && adopt && adopt.head) {
      const head = { rev: adopt.head.rev, commitCid: cid(adopt.head.commitCid), dataCid: cid(adopt.head.dataCid), signedCommit: adopt.head.signedCommit || null }
      const h = await device.resetFirehose(adopt.records || [], head)
      await sb.set('__firehose_reset__', { ts: Date.now(), rev: h ? h.rev : null })
      console.log(JSON.stringify({ msg: 'firehose reset: cleared malformed frames + re-emitted clean continuation', did, from: adopt.head.rev, rev: h ? h.rev : null }))
    } else {
      const existing = await device.repo.listRecords()
      if (existing.length === 0 && adopt && adopt.head) {
        // FIRST cutover only (empty repo): import the existing DID's repo so the swarm CONTINUES its
        // chain instead of re-authoring. On a RESTART the records are already in the shared state, so we
        // must NOT re-adopt (that resets head to the ORIGINAL adopted rev → the next sign re-emits the
        // posts) — we restore instead.
        const head = { rev: adopt.head.rev, commitCid: cid(adopt.head.commitCid), dataCid: cid(adopt.head.dataCid), signedCommit: adopt.head.signedCommit || null }
        try {
          await device.adopt(adopt.records || [], head)
          console.log(JSON.stringify({ msg: 'adopted repo into swarm', did, rev: head.rev, records: (adopt.records || []).length }))
          // Emit ONE baseline #commit frame so the membrane projects immediately — without this an
          // adopted repo with no subsequent write has an empty firehose log and the bridge can't front
          // it (getRepo/getLatestCommit fail) until the first post. See device.emitBaseline().
          const b = await device.emitBaseline()
          if (b) console.log(JSON.stringify({ msg: 'baseline firehose frame emitted (adopted repo is membrane-frontable)', did, rev: b.rev }))
        } catch (e) { console.log(JSON.stringify({ msg: 'adopt FAILED', error: e.message })) }
      } else if (existing.length > 0) {
        // RESTART with existing signed state: re-seed head + the diff baseline from the shared __commit__
        // log so the firehose stays INCREMENTAL (no full-set re-author) and the chain continues.
        const h = await device.restore()
        console.log(JSON.stringify({ msg: 'restored signed head', did, rev: h ? h.rev : null, records: existing.length }))
      } else {
        // FRESH empty account (no adopt, no existing state): author + sign an INITIAL commit so the
        // repo is non-empty and verifiable. A bridge authenticates a peer by replaying its signed
        // commit against the DID key and refuses to front an empty repo (PeerFront.discover), so
        // without this a brand-new swarm account is never frontable — and it can't post its way out
        // (the composer posts THROUGH the bridge). Mirrors the single-tenant path (index.js:112). Only
        // the writable creator authors it; peers receive the commit via __commit__ replication.
        await device.putRecord('app.bsky.feed.post', 'self.hello', {
          $type: 'app.bsky.feed.post',
          text: `hello from ${handle || did}`,
          createdAt: new Date().toISOString()
        })
        const h = await device.sign({ force: true }) // creator bootstrap: sole writable device, no other signer → force-sign is safe (boot claim removed)
        console.log(JSON.stringify({ msg: 'authored initial signed commit (fresh swarm account)', did, rev: h ? h.rev : null }))
      }
    }
  }

  // Ensure per-DID bootstrap records (a community's app.bsky.feed.generator / labeler.service etc.),
  // then sign — folds serve-loser-club.mjs's record-authoring into the supervised daemon. Writable
  // devices only (creator/lease-holder; a plain writer re-authors after admission). Idempotent.
  if (sb.base.writable && !resyncStore && Array.isArray(records) && records.length) {
    let wrote = 0
    for (const r of records) {
      try { const ex = await device.repo.getRecord(r.collection, r.rkey); if (!ex) { await device.putRecord(r.collection, r.rkey, r.record); wrote++ } } catch (e) { console.error(JSON.stringify({ msg: 'bootstrap record failed', did, collection: r.collection, rkey: r.rkey, error: e.message })) }
    }
    if (wrote) { try { await device.sign({ force: true }) } catch {} ; console.log(JSON.stringify({ msg: 'bootstrap records authored', did, wrote })) }
  }

  // sign loop: while we hold the lease, renew + materialize the linearized view into the chain, then
  // re-project the new commit + records into the membrane-served cores so the bridge sees it.
  let membraneServing = null
  // EVENT-DRIVEN sign/project — ZERO polling timer (was setInterval(signIntervalMs), the append-frequency
  // anti-pattern). One sb.watch(tick) fires on every StateBase advance — a local write OR a replicated
  // #commit (view apply) — AND on a signer-presence change (co-owner connect/disconnect →
  // SignerPresence.onChange → sb._fireWatchers). So the lease-holder re-materializes and EVERY device's
  // membrane re-projects exactly when there is something to do, never on an idle clock.
  //
  // The tick body is unchanged in effect but guarded + NON-BLOCKING (sign() reads the autoUpdate
  // snapshot; returns null on an unchanged data root; membrane.sync is incremental from seq.length), so
  // an idle event appends NOTHING. FAILOVER is opportunistic (the zero-timer design): a departed signer's
  // grace expiry is noticed on the next write/replication/presence event — acceptable latency, no data
  // loss (the write is durable in the log; it just materializes into a signed commit a beat later).
  // ensureAdmitted (re-admission doorbell) runs when not writable; requestWriter re-rings internally.
  // BYTE convergence for EVERY device, signer or not. sign() resolves record bytes as a side effect of
  // listRecords({now:true}) — but it returns at the ELECTION GATE first, so a non-signing co-owner
  // never pulled a single record byte and drifted toward "only what I authored" while its pointer set
  // stayed correct (see SwarmDevice.reconcileBytes). Runs on its OWN coalescing guard and is never
  // awaited by the tick, so a large backlog drains without delaying signing or stacking passes.
  // Bounded passes, and it stops as soon as a pass makes no progress — the next event retries.
  // Hoisted so the reconcile runner can reach the blob store: `blobs` below is block-scoped inside
  // `if (controlEnabled)`, and reconcile() is defined before it. Null until the blob stores exist.
  let blobStore = null
  let reconciling = false

  // ⛔ A FAILED FETCH IS NOT "NOTHING TO DO", AND THAT COST A POST. The pass loop below used to break on
  // `!r.fetched`, which collapses two opposite outcomes: "everything resolved" and "I tried and could not
  // reach the bytes". The comment said the next event would retry — and events are the ONLY driver here
  // (zero polling, by design: sb.watch on a StateBase advance or a presence change, plus reconcile() on
  // overlay attach when a peer connects). For the MOST RECENTLY converged pointer the advance that would
  // retry it has already happened, so a single transient miss leaves that record unresolved until some
  // unrelated write or a new peer connection shakes it loose.
  //
  // Measured on the handset 2026-08-18: a post converged at 21:26, its one fetch failed, and nothing
  // retried for 13 minutes. At the next boot the same fetch failed once more and SUCCEEDED 3 seconds
  // later — the miss was transient all along (the peer had not registered the oid yet: hyper-overlay's
  // oid→disk map is in-memory and rebuilt per boot, atproto-store invariant #5). Downstream, favela-web's
  // appview correctly refuses to author bytes hpp owns, so the record indexed but could not render: every
  // layer behaving as designed, and the post invisible.
  //
  // So retry on FAILURE specifically, bounded and self-disarming:
  //   - one pending retry at a time, never a queue (a burst of events must not stack timers)
  //   - exponential backoff, because a peer that is genuinely absent must not be hammered
  //   - a clean pass disarms and resets the budget, so steady state is still zero timers
  //   - a real EVENT resets the budget too: the world changed, so the previous exhaustion is stale
  //   - unref'd, because a convergence retry must never be the reason a process stays alive
  // The arithmetic and the budget live in lib/reconcile-retry.js (pure, tested in
  // test/reconcile-retry.test.mjs). This owns only the timer — and unrefs it, because a convergence
  // retry must never be the reason a process stays alive.
  let retryTimer = null
  let retryDelay = 0
  let retryAttempts = 0

  const reconcile = async ({ fromRetry = false } = {}) => {
    if (reconciling) return
    reconciling = true
    if (retryTimer) { clearTimeout(retryTimer); retryTimer = null }
    let failedRecords = 0
    let failedBlobs = 0
    try {
      for (let pass = 0; pass < 64; pass++) {
        const r = await device.reconcileBytes()
        if (!r || r.skipped) break
        failedRecords = r.failed || 0
        if (!r.more || !r.fetched) break // resolved everything reachable this pass
      }
      // BLOBS converge on the same events. reconcileBytes walks the RECORD pointer set and skips
      // `__`-prefixed keys, so `__blob__/<cid>` could never be covered by it — without this, a blob's
      // pointer replicates but its bytes only ever move when something happens to call get-blob.
      if (blobStore && typeof blobStore.reconcileBlobs === 'function') {
        for (let pass = 0; pass < 64; pass++) {
          const b = await blobStore.reconcileBlobs()
          if (!b || b.skipped) break
          failedBlobs = b.failed || 0
          if (!b.more || !b.fetched) break
        }
      }
    } catch {} finally { reconciling = false }

    const d = nextRetry({ failed: failedRecords, failedBlobs, fromRetry, attempts: retryAttempts, delay: retryDelay })
    retryAttempts = d.attempts
    retryDelay = d.delay
    if (d.giveUp) {
      console.log(JSON.stringify({ msg: 'reconcile: giving up until the next event', did: device.did, records: failedRecords, blobs: failedBlobs, attempts: d.attempts }))
      return
    }
    if (!d.arm) return
    console.log(JSON.stringify({ msg: 'reconcile: bytes unresolved — retry armed', did: device.did, records: failedRecords, blobs: failedBlobs, attempt: d.attempts, inMs: d.delay }))
    retryTimer = setTimeout(() => { retryTimer = null; reconcile({ fromRetry: true }).catch(() => {}) }, d.delay)
    if (retryTimer.unref) retryTimer.unref()
  }

  let ticking = false
  let tickAgain = false
  const tick = async () => {
    if (ticking) { tickAgain = true; return } // coalesce bursts; re-run once if one arrived mid-flight
    ticking = true
    try {
      if (sb.base && !sb.base.writable) { try { await sb.ensureAdmitted() } catch {} }
      reconcile() // deliberately NOT awaited — byte convergence must not gate signing (or vice versa)
      await device.sign()
      if (membraneServing) await membraneServing.sync()
    } catch {}
    finally { ticking = false; if (tickAgain) { tickAgain = false; tick() } }
  }
  let unwatch = null
  if (signIntervalMs > 0) { // >0 = enable the (now event-driven) sign loop; 0 = disabled (tests drive sign() manually)
    unwatch = (typeof sb.watch === 'function') ? sb.watch(() => { tick() }) : null
    tick() // initial pass at boot (materialize any pending intents + project the membrane)
  }

  // Federation heartbeat — folds serve-loser-club.mjs's keep-alive into the daemon. A non-archival
  // relay only indexes LIVE #commits (atproto-bridge POSTMORTEM), so a low-activity account goes stale
  // once it stops emitting. Periodically write a fresh marker (net.favela.federation/self, a non-bsky
  // collection that never pollutes the public feed); the sign loop above materializes it into a #commit.
  let hbTimer = null
  if (federationHeartbeatMs > 0) {
    let hn = 0
    const heartbeat = async () => { try { hn++; await device.putRecord('net.favela.federation', 'self', { $type: 'net.favela.federation', seq: hn }) } catch {} }
    await heartbeat() // emit one now
    hbTimer = setInterval(heartbeat, federationHeartbeatMs)
    if (hbTimer && typeof hbTimer.unref === 'function') hbTimer.unref()
  }

  // control surface: a SEPARATE Hyperswarm so a client/app can submit writes to + observe this
  // device (StateBaseV3's own swarm only replicates the intent-log between devices). Reuses
  // swarmOpts (testnet bootstrap in tests). writers = allowlist of client Noise pubkeys; null =
  // read-only (secure default, matching lib/peer.js). Enabled by default when networked; pass
  // control:false to suppress. Returns { serverKey, discoveryTopic }.
  const controlEnabled = control == null ? swarm : control
  let serving = null
  let controlSwarm = null
  let membraneStore = null
  let udsServing = null
  if (controlEnabled) {
    // PERSISTENT control/serving keypair (same rationale as lib/swarm-keypair.js for the single-tenant
    // peer): the control+membrane surface is what the keyless bridge fronts. A RANDOM keypair per boot
    // (`new Hyperswarm()`) makes every restart a NEW serverKey — the bridge's old connection dies and
    // Hyperswarm can't retry the same DHT identity, so fronts go stale until a slow topic re-query. A
    // STABLE serverKey (persisted in <storage>/swarm-keypair.json) lets the bridge reconnect promptly on
    // restart → the swarm is restart-safe with no bridge bounce. repoKey/firehoseKey are already stable
    // (DID-named cores on a persisted corestore), so this closes the last rotating coordinate.
    // Per-DID sub-paths when hosted by the multi-DID daemon (bootMultiDevice): the control keypair
    // (this DID's bridge-facing serverKey) + the local UDS are per-DID so N DIDs don't collide; the
    // membrane cores share the daemon's ONE Corestore (a per-DID namespace). EXCEPT the `primary` DID
    // (the machine's own user DID, e.g. wj62): it keeps the FLAT control.sock + swarm-keypair + membrane
    // so its bridge-facing serverKey/coords and its co-located client's UDS stay STABLE across the
    // single-DID→multi-DID cutover (only its StateBase re-homes into the shared store). So a migrated
    // primary DID's clients (favela-web Writer) and the bridge see no change.
    const perDid = shared && !primary
    const ctlDir = perDid ? join(storage, 'dids', b4a.toString(roomKey, 'hex').slice(0, 16)) : storage
    if (perDid) fs.mkdirSync(ctlDir, { recursive: true })
    controlSwarm = new Hyperswarm({ ...(swarmOpts || {}), keyPair: loadOrCreateSwarmKeyPair(ctlDir) })
    // membrane surface (Phase D): project __commit__ + records into cores + serve get-coords on the
    // SAME peer-facing swarm, so the keyless membrane (atproto-bridge) fronts this device by DID.
    membraneStore = perDid ? shared.store.namespace('membrane:' + did) : watchStore(openCorestore(join(storage, 'membrane')), 'membrane')
    // Blobs (avatars/images), SHARED by both surfaces — blobs live in the PEER; the keyless bridge only
    // relays. get-blob is public (bsky reads avatars); upload-blob is authed. On an overlay-backed DID, write
    // NEW blobs to a content-addressed OverlayBlobStore (files under the shared repoRoot/blobs — ONE copy,
    // shared with a co-located consumer like favela-web) and DUAL-READ: fall back to the legacy Hyperbee
    // BlobStore for pre-migration blobs so existing avatars don't 404 (no bulk rewrite; old blobs age out).
    // Legacy-only for non-overlay DIDs. Same drop-in put/get/has API either way — serveDevice/Membrane unchanged.
    const legacyBlobs = await new BlobStore(membraneStore, { name: 'membrane-blobs:' + did }).ready()
    let blobs = legacyBlobs
    if (storeBackend === 'overlay' && repoRoot && recordOverlay) {
      const overlayBlobs = await new OverlayBlobStore(join(repoRoot, 'blobs'), { overlay: recordOverlay, indexStore: membraneStore, name: 'overlay-blobs:' + did }).ready()
      // The overlay bee ({mimeType,size,oid}) is NODE-LOCAL — it lives on membraneStore and never
      // replicates — and OverlayBlobStore.get() reads it FIRST, returning null before it looks at the
      // file or the overlay. So without this wrapper an upload here leaves the FILE fetchable by oid
      // from anywhere while the cid->oid mapping stays on this node forever, and a co-owner cannot
      // derive it (the atproto blob CID and the overlay oid are different hashes). The blob then
      // serves or 404s depending on which co-owner the bridge fronts. BlobPointerStore publishes
      // `__blob__/<cid>` = {$oid,size,mimeType} into the SHARED state — the same pointers-in-the-
      // autobase/bytes-in-the-overlay design PointerSubstrate already uses for records. Reserved "__"
      // key: splitKey rejects it, so it can never reach a signed commit.
      blobs = new DualBlobStore(new BlobPointerStore(sb, overlayBlobs, { did }), legacyBlobs)
      console.log(JSON.stringify({ msg: 'blob store: overlay content-addressed files + shared pointers + legacy dual-read', did, path: join(repoRoot, 'blobs') }))
    }
    // ⛔ ALWAYS, NOT ONLY ON THE OVERLAY PATH. This assignment lived inside the `if` above, so a DID
    // with no `storeBackend: 'overlay'` — which is every DID minted by favela-host, since it sets none
    // — returned `blobs: null` from bootMultiDevice while `legacyBlobs` was right here, working, and
    // already handed to serveDevice and serveMembrane. The two stores share a drop-in put/get/has API
    // by design, so there was never a reason for the handle to report one and not the other.
    //
    // ⚠ IT ONLY BITES AN IN-PROCESS CONSUMER, which is why it survived: every socket surface takes
    // `blobs` directly from this scope. The returned field exists precisely FOR the in-process case
    // (see the note where this node is returned), and that is the one case it got wrong.
    //
    // Measured: a handset published 11 posts to its atproto repo and NONE of them carried an image.
    // The same posts reached the fediverse with their jpegs attached, because that projection never
    // asks this object for a blob store. upload-blob threw 'this node has no blob store', BskySink
    // caught it and returned null, and each post went as text with a loss line nobody reads.
    blobStore = blobs
    // LOCAL UDS control surface — bring it up EARLY (before serveDevice/serveMembrane, whose sync/ready can
    // stall on an un-converged base's base.update), so a co-located client (favela-web) can ALWAYS reach the
    // device over local IPC even while convergence lags. Owner-gated by the filesystem → no writer-allowlist.
    try {
      // OTA respawn. This used to call `this.close()` — but this is inside bootSwarmDevice, a plain
      // FUNCTION, so in an ES module `this` is undefined and it threw a TypeError that serve-device-uds's
      // try/catch swallowed: the handler logged "respawning" and then silently did nothing, which is
      // exactly how it shipped in 0.3.100-0.3.103. The process lifecycle belongs to index.js (it owns
      // `daemon` and its close), so it registers the handler and this only signals.
      udsServing = await serveDeviceUds(device, {
        uds: join(ctlDir, 'control.sock'),
        blobs,
        // EXPLICIT handler first. The module-global `otaHandler` below is a fallback kept for callers
        // that still use setOtaHandler(), but it is NOT the primary path any more: a module-level
        // variable is only shared if index.js and this file resolve to the SAME module instance, and
        // under pgh's content-addressed node_modules a specifier can resolve to two realpaths — Bare
        // caches by realpath, so each copy gets its OWN `otaHandler`, one set and the other read. That
        // is consistent with what shipped: 0.3.105 logged "release-ready", called through, and found
        // null. Threading the function through the call cannot be defeated that way.
        onRelease: (ver) => {
          if (typeof onRelease === 'function') return onRelease(ver)
          if (otaHandler) return otaHandler(ver)
          console.error(JSON.stringify({ msg: 'ota: release-ready arrived but NO respawn handler is registered — this daemon will not self-update' }))
        }
      })
      console.log(JSON.stringify({ msg: 'device UDS control surface', uds: join(ctlDir, 'control.sock') }))
    } catch (e) { console.error(JSON.stringify({ msg: 'UDS control surface failed (swarm surface still up)', error: e.message })) }
    const allow = Array.isArray(writers) ? writers.map((w) => String(w).toLowerCase()).filter(Boolean) : null
    const canWrite = allow && allow.length ? (hex) => allow.includes(String(hex).toLowerCase()) : null
    // bsky-login: the peer is the auth authority — build the session minter/verifier from the carried
    // appPasswordHash + jwtSecret so the membrane serve can answer the bridge's create/refresh-session.
    // Constructed BEFORE serveDevice because the device surface's get-service-auth gates on
    // sessions.verifyAccess — the bridge forwards the end user's bearer for exactly that. Pure factory,
    // no I/O, so the ordering is free.
    const sessions = makeSessions({ did, handle, appPasswordHash, jwtSecret })
    serving = serveDevice(device, controlSwarm, { canWrite, blobs, sessions })
    // ⛔ TIME-BOXED, because `ready()` on BOTH surfaces is `Promise.all([topic.flushed(), …])` — the DHT
    // ANNOUNCE completing, which is not the same thing as the surface working. `swarm.join()` has already
    // registered the topics and connections are served meanwhile: on the phone five `device control
    // connection`s were logged while boot was still sitting inside this await. On a workstation the flush
    // returns in milliseconds; behind carrier-grade NAT it can take minutes or never resolve, and awaiting
    // it wedged bootSwarmDevice → bootMultiDevice never returned → favela-android never sent `ready` and
    // the app sat on its splash screen with a node that was, in fact, up (hyper-social #40).
    //
    // So boot proceeds and the announce finishes in the background. Nothing is skipped and nothing is
    // swallowed silently: a timeout says so, naming the surface. The membrane projection is time-boxed on
    // the same reasoning — the event-driven tick re-syncs on the next StateBase advance anyway, so a slow
    // first pass costs a beat of freshness, never correctness.
    const awaitOrContinue = async (what, promise, ms = 15000) => {
      let timer = null
      const timeout = new Promise((resolve) => { timer = setTimeout(() => resolve('__timeout__'), ms); if (timer && timer.unref) timer.unref() })
      const outcome = await Promise.race([promise.then(() => '__ok__', (e) => e), timeout])
      clearTimeout(timer)
      if (outcome === '__timeout__') console.error(JSON.stringify({ msg: 'boot continued WITHOUT waiting for ' + what + ' — it is still in progress in the background; the surface already accepts connections', did, waitedMs: ms }))
      else if (outcome !== '__ok__') console.error(JSON.stringify({ msg: what + ' failed (boot continues)', did, error: (outcome && outcome.message) || String(outcome) }))
      return outcome === '__ok__'
    }
    await awaitOrContinue('the control-surface DHT announce', serving.ready())
    // projectRepoCore comes straight off the DID's config entry (bootMultiDevice spreads `...entry`),
    // exactly like storeBackend. FALSE = the stateless virtual device: no membrane-repo Hyperbee is
    // opened, record bytes exist only as the content-addressed files, and a consumer derives the repo
    // via the get-repo-car RPC (proven byte-identical in test/derive-vs-project). Defaults TRUE so
    // nothing changes until a DID is explicitly flipped — rolled out one DID and one node at a time.
    // Flipping back is instant: the existing core on disk is untouched, just not opened.
    membraneServing = await serveMembrane(device, { corestore: membraneStore, swarm: controlSwarm, did, handle, sessions, blobs, projectRepoCore })
    await awaitOrContinue('the membrane DHT announce', membraneServing.ready())
    // sync() reads the device's __commit__ log through the StateBase. On a device that is not yet admitted
    // (roster projected by another machine — #40 §6) that base may never advance, so this too is bounded.
    await awaitOrContinue('the initial membrane projection', membraneServing.sync(), 30000)
  }

  const close = async () => {
    if (unwatch) { try { unwatch() } catch {} } // stop the event-driven sign/project subscription
    if (hbTimer) clearInterval(hbTimer)
    if (serving) { try { serving.close() } catch {} }
    if (membraneServing) { try { membraneServing.close() } catch {} }
    if (udsServing) { try { await udsServing.close() } catch {} }
    if (controlSwarm) { try { await controlSwarm.destroy() } catch {} }
    if (membraneStore) { try { await membraneStore.close() } catch {} }
    if (recordStore) { try { await recordStore.close() } catch {} }
    if (recordOverlay) { try { await recordOverlay.close() } catch {} }
    try { await sb.close() } catch {}
  }

  // `reconcile` is exposed so the daemon can also trigger byte convergence on OVERLAY PEER ATTACH —
  // the moment bytes become reachable is not a StateBase event, so sb.watch alone would leave a
  // just-connected peer sitting on fetchable bytes until something else happened to fire.
  // _statebaseStore: a pre-cutover DID's OWN corestore, kept in place. It sits OUTSIDE the daemon's
  // shared store.replicate(conn), so — exactly like a resync side store — the daemon must replicate it
  // explicitly or the DID would never sync with anyone. Reported separately from _sideStore because
  // StateBaseV3 owns this one and closes it itself (sb.close); double-closing a resync store is what
  // _sideStore's own close path is for.
  // `blobs` is exposed because an IN-PROCESS consumer needs it: favela-android runs this daemon inside
  // the app, so its UI reaches blobs through the object rather than the `upload-blob`/`get-blob` RPCs the
  // co-located (favela-web over UDS) and remote (bridge over swarm) consumers use. Same store, no surface.
  // `uds` is the LOCAL control socket path (or null if that surface failed to come up). Exposed because
  // the co-located consumer needs to NAME it: favela-web reaches this device over that socket, and the
  // only alternative is for the caller to re-derive `<storage>/dids/<roomId>/control.sock` from hpp's
  // internal directory layout — a private path rebuilt by hand in another repo, which breaks the day this
  // moves and surfaces as "writes are disabled" nowhere near the cause. hpp knows the path; hpp says it.
  return { device, sb, did, self, blobs: blobStore, control: serving, membrane: membraneServing, controlSwarm, overlay: recordOverlay, repoRoot, reconcile, close, uds: udsServing ? udsServing.uds : null, _sideStore: resyncStore, _statebaseStore: keepLocalStatebase ? sb.store : null }
}

// ── RESYNC (fresh-corestore re-join) index ────────────────────────────────────────────────────────
// A per-DID directive persisted at <storage>/statebase-resync/index.json ({ "<did>": gen }). When a DID
// carries a gen, bootMultiDevice opens its StateBase from a FRESH Corestore at
// <storage>/statebase-resync/<did16>-r<gen> (its own primaryKey → a CLEAN local writer) instead of the
// poisoned shared-store base — the durable, restart-surviving heal for a poisoned autobase local writer
// (the SIGABRT in ApplyState._appendLocalNodes). Generic: any hosted DID, keyed by DID (mirrors pgv3's
// per-repo forceResync). resyncDid() BUMPS the gen; the daemon reopens on next boot — a poisoned base
// can't be live-closed (it aborts on apply), so boot-reopen (never opening the poisoned base) is the
// correct shape. Nothing is deleted: the old poisoned cores stay on disk in the shared store.
//
// ⛔ DO NOT "SIMPLIFY" THIS INTO autobase's setLocal(key,{keyPair}) WRITER ROTATION. That undocumented
// API (autobase/index.js:489) looks like it should replace the whole second-Corestore apparatus below —
// rotate onto a fresh keypair in place, drop the side store, drop the _sideStore.replicate ordering in
// bootMultiDevice. Characterized against 7.28.1 (2026-08-12) and it does NOT work here, for three
// independent reasons:
//   1. NOT A CLEAN SLATE. _rotateLocalWriter calls LocalState.moveTo(old,new), which copies the
//      linearizer updates AND the autobase/boot record onto the new writer, and the base stays in the
//      same store with its stale view cores. The fresh primaryKey is the whole point of a side store.
//   2. IT ASSERTS ON AN INDEXER. _rotateLocalWriter nulls localWriter before _updateLinearizer calls
//      _clearLocalIndexer, which asserts localWriter !== null — a bare AssertionError with an EMPTY
//      message, leaving a half-rotated base. A poisoned node is usually the creator, i.e. the sole
//      indexer. Even with that fixed, rotating the sole indexer leaves the room with ZERO indexers.
//   3. IT DE-ADMITS ANYWAY. The rotated key is not in the writer set, so an indexer still has to
//      addWriter it — the same online-indexer dependency the fresh-corestore re-join already has.
// So the second Corestore + the side-store replication ordering are load-bearing, not incidental.
// Evidence + probes: memory/reference_autobase-setlocal-writer-rotation, pear-git#35.
const RESYNC_DIR = 'statebase-resync'
const did16For = (did) => b4a.toString(crypto.hash([NS('room-key'), b4a.from(did)]), 'hex').slice(0, 16)

// Attaching a DID's overlay content protocol to a connection was wrapped in a bare `try {} catch {}` at
// BOTH attach sites. If it ever throws, that DID silently loses byte transfer on that connection — the
// pointers still converge via the autobase, so the repo looks fine while the BYTES never move, and
// `fetchFile` later reports only a generic null. Byte resolution gates signing, so this is a silent
// failure on a load-bearing path (hyper-social #13, lesson 3). Deduped per did+reason so a flapping
// swarm cannot spam the log.
// Record the OUTCOME of an attach, not just its exceptions. attachProtocol returns silently on every
// internal guard, so "no exception" never meant "attached" — that misreading cost a day. Logged once
// per did+peerCount, so it is quiet in steady state but re-reports the moment connectivity changes.
const _attachSeen = new Set()
function logOverlayAttachResult (did, overlay) {
  let peers = null
  try { peers = overlay.peerCount } catch {}
  const k = did + ':' + peers
  if (_attachSeen.has(k)) return
  _attachSeen.add(k)
  try {
    console.log(JSON.stringify({
      msg: peers > 0
        ? 'overlay attached — byte transfer is live for this DID on this connection'
        : 'overlay attachProtocol returned but peerCount is 0 — NO byte transfer on this connection',
      did, overlayPeers: peers
    }))
  } catch {}
}

const _attachFails = new Set()
function logOverlayAttachFail (did, err) {
  const reason = (err && err.message) || String(err)
  const k = did + ':' + reason
  if (_attachFails.has(k)) return
  _attachFails.add(k)
  try { console.error(JSON.stringify({ msg: 'overlay attachProtocol FAILED — this DID will not move record BYTES on this connection (pointers still converge, so the repo will look healthy)', did, error: reason })) } catch {}
}
const resyncSidePath = (storage, did, gen) => join(storage, RESYNC_DIR, did16For(did) + '-r' + gen)
export function readResyncIndex (storage) {
  try { return JSON.parse(fs.readFileSync(join(storage, RESYNC_DIR, 'index.json'), 'utf8')) } catch { return {} }
}
// Mark a DID for a fresh-corestore re-join on the next daemon boot (bumps its gen). Returns the new gen
// + the side-store path. The daemon must be restarted to apply (the poisoned base is not live-closable).
export function resyncDid (storage, did) {
  if (!storage || !did) throw new Error('resyncDid: storage + did required')
  const idx = readResyncIndex(storage)
  const gen = (idx[did] || 0) + 1
  idx[did] = gen
  fs.mkdirSync(join(storage, RESYNC_DIR), { recursive: true })
  fs.writeFileSync(join(storage, RESYNC_DIR, 'index.json'), JSON.stringify(idx, null, 2) + '\n')
  return { gen, sidePath: resyncSidePath(storage, did, gen) }
}

// bootMultiDevice — the MULTI-DID (multi-tenant) hpp daemon. Serves N self-custody DIDs from ONE
// process over ONE shared Corestore (one dir, one RocksDB lock — each DID is a namespace), ONE
// Hyperswarm + ONE ProtomuxWakeup for StateBase replication (the keet multi-room pattern), plus a
// per-DID control/membrane surface (each DID's own bridge-facing serverKey + local UDS). This is a
// user's own DID + the communities they co-own, all in one supervised daemon — retiring the bespoke
// per-community scripts. Foundation proven in atproto-room/test/multi-did.test.js.
// dids = [{ deviceMnemonic, did, signingKey, deviceProof, rootIdentityKey, handle, pdsUrl, members,
//           writers, adopt?, resetFirehose?, appPasswordHash?, jwtSecret? }].
//
// `deviceMnemonic` (the top-level one) is the DEVICE-SCOPED fallback — this machine's own keet identity,
// used by any entry that does not carry its own. A device key is derived from a mnemonic and NOTHING
// else (`deviceKeetKeyPair` takes no DID), so `coownerJoin` mints it at config ROOT and writes a `dids`
// entry WITHOUT one — that is what lets a phone mint its key before it knows which DID it is joining.
// Boot must read it the same way or a genuinely-joined DID dies on "deviceMnemonic required" and the
// daemon serves ZERO DIDs while its config, roster and attestation are all perfect (hyper-social #40 §3).
// Precedence is coownerJoin's, exactly: per-DID first (it may already be attested, and replacing it
// orphans the attestation), else device-scoped. Proof: test/coowner-join-boots.test.js.
export async function bootMultiDevice ({ storage, dids = [], deviceMnemonic = null, swarmOpts = null, signIntervalMs = 2000, onRelease = null } = {}) {
  if (typeof storage !== 'string') throw new Error('bootMultiDevice: storage path required')
  if (!Array.isArray(dids) || dids.length === 0) throw new Error('bootMultiDevice: at least one DID required')

  // ONE shared substrate for every DID's StateBase (+ per-DID membrane namespaces of the same store).
  const store = watchStore(openCorestore(join(storage, 'store')), 'store')
  await store.ready()
  // RESYNC directives: DIDs whose StateBase must open from a fresh side corestore (healed poisoned base).
  const resyncIdx = readResyncIndex(storage)
  const wakeup = new ProtomuxWakeup()
  const swarm = new Hyperswarm({ ...(swarmOpts || {}), keyPair: loadOrCreateSwarmKeyPair(join(storage, 'statebase-swarm')) })
  // `nodes` is declared BEFORE the connection handler so the handler's closure can attach each hosted
  // DID's signer-presence on every connection (S1 multi-DID). It is only ever pushed to (never reassigned),
  // so the closure always sees the current roster.
  const nodes = []

  // keet muxing: ONE store.replicate + ONE wakeup.addStream per connection carries EVERY DID's cores
  // AND every DID's optimistic/pending-writer announcements — so admission works for all DIDs over one
  // connection (proven: atproto-room/test/multi-did.test.js). No per-base replicate/wakeup.
  swarm.on('connection', (conn) => {
    conn.on('error', () => {})
    try { wakeup.addStream(conn) } catch {}
    // SIDE STORES REPLICATE FIRST — before the shared store below. Corestore keys hypercore channels by
    // DISCOVERY KEY on a Protomux that is SHARED per stream, so when two corestores on one connection both
    // hold the same core, whichever replicates FIRST claims (hypercore/alpha, discoveryKey) and the other's
    // attach is a duplicate that Protomux answers with null. The loser then syncs with NOBODY while looking
    // perfectly healthy locally: length 0, no error, no conflict — the hardest possible shape to diagnose.
    // Reproduced both ways in test/side-store-channel-priority.test.js.
    //
    // For a DID whose base lives in a side store, that side store is the AUTHORITATIVE copy and anything
    // left in the shared store is the abandoned pre-resync one, so the side store must win. Ordering is the
    // whole fix. (A stale core merely sitting ON DISK in the shared store does not collide — corestore does
    // not auto-open cores on remote interest — so this bites only when something opens it in-process too.)
    for (const n of nodes) { if (n._sideStore) { try { n._sideStore.replicate(conn) } catch {} } }
    // A PRE-CUTOVER DID's StateBase lives in its OWN corestore (kept in place rather than re-homed), so
    // like a resync side store it is outside store.replicate below and must be replicated explicitly —
    // otherwise that DID silently syncs with nobody while looking perfectly healthy locally.
    for (const n of nodes) { if (n._statebaseStore) { try { n._statebaseStore.replicate(conn) } catch {} } }
    try { store.replicate(conn) } catch {}
    // S1 multi-DID signer election: the StateBases run network:false (no swarm of their own) so their
    // internal per-connection presence handshake never fires here — the daemon must drive it. Attach EACH
    // hosted DID's ephemeral presence over this one shared connection; per-DID channel ids (roomKey) keep
    // them from colliding (attachSignerPresence passes id=this._roomKey). Without this, every co-owner of a
    // shared DID sees only itself present → holdsSigner()==true for all → they all sign → FORK. Double-attach
    // (a node booting while this connection exists) is a safe no-op (protomux returns null on the duplicate).
    for (const n of nodes) { try { n.sb.attachSignerPresence(conn) } catch {} }
    // Record CONVERGENCE is the StateBase autobase: a tiny {$oid,size} POINTER per record replicates
    // symmetrically like any control key (PointerSubstrate). hyper-overlay is the DISTRIBUTION layer —
    // it serves the record BYTES by content-hash (oid). Attach each overlay-backed DID's content
    // protocol here so a follower resolving the converged pointer set (store.ensureLocal) can pull the
    // bytes from a peer by oid. Per-DID channel ids (roomKey) let N overlays coexist on this one mux.
    const mux = Protomux.from(conn)
    for (const n of nodes) { if (n.overlay) { try { n.overlay.attachProtocol(mux); logOverlayAttachResult(n.did, n.overlay); if (n.reconcile) n.reconcile() } catch (err) { logOverlayAttachFail(n.did, err) } } }
  })
  const shared = { store, swarm, wakeup }

  // DID-manager (atproto account-manager analog): the durable roster of hosted DIDs — one Hyperbee on
  // the shared store, so a restart re-opens exactly the DIDs this node hosts.
  const registry = await new AccountRegistry(store, { name: 'hpp-dids' }).ready()

  for (const d of dids) {
    try {
      // RESYNC: if this DID is flagged, open its StateBase from a FRESH per-DID Corestore (clean local
      // writer) instead of the poisoned shared-store base. The daemon owns + closes this side store.
      let resyncStore = null
      if (resyncIdx[d.did]) {
        resyncStore = watchStore(openCorestore(resyncSidePath(storage, d.did, resyncIdx[d.did])), 'statebase-resync')
        await resyncStore.ready()
        console.log(JSON.stringify({ msg: 'multi-did: RESYNC — opening DID from a fresh side corestore', did: d.did, gen: resyncIdx[d.did], sidePath: resyncSidePath(storage, d.did, resyncIdx[d.did]) }))
      }
      // Per-DID adoptCar (notary-revival rebuild): a rebuilt DID's config entry may carry adoptCar (the
      // path to its authoritative CAR exported by `rebuild-did`) + forceCreator. Load it into `adopt`
      // {records, head} so the healthy node AUTHORS the genesis from the snapshot. COEXISTENCE RULE
      // (rebuild-2node-transition.test.js): the OLD base must be OFF the swarm first — a rebuild belongs
      // in FRESH storage (or a daemon that no longer hosts the old copy), never alongside the old cores.
      let entry = d
      if (d.adoptCar && !d.adopt) {
        try { entry = { ...d, adopt: await readAdoptRepo(fs.readFileSync(d.adoptCar)) }; console.log(JSON.stringify({ msg: 'multi-did: adoptCar loaded for rebuild', did: d.did, car: d.adoptCar, records: entry.adopt.records.length, rev: entry.adopt.head.rev })) } catch (e) { console.error(JSON.stringify({ msg: 'multi-did: adoptCar load FAILED', did: d.did, car: d.adoptCar, error: e.message })) }
      }
      // deviceMnemonic AFTER the spread, and explicit rather than relying on spread order: an entry may
      // carry the key with an undefined value, which would silently win and re-throw the original error.
      const node = await bootSwarmDevice({ storage, ...entry, deviceMnemonic: entry.deviceMnemonic || deviceMnemonic, swarm: true, swarmOpts, signIntervalMs, shared, resyncStore, onRelease })
      swarm.join(node.sb.base.discoveryKey, { server: true, client: true }) // daemon joins each DID's StateBase topic
      // resync side store: replicate on connections already open (future ones via the connection handler).
      if (node._sideStore) for (const conn of swarm.connections) { try { node._sideStore.replicate(conn) } catch {} }
      // Same catch-up for a kept-in-place StateBase on a DID that booted AFTER connections were open.
      if (node._statebaseStore) for (const conn of swarm.connections) { try { node._statebaseStore.replicate(conn) } catch {} }
      try { await registry.put(node.did, { did: node.did, handle: d.handle || null, active: true, addedAt: Date.now() }) } catch {}
      nodes.push(node)
      // A DID booting AFTER connections are already open: the connection handler ran before this node was in
      // `nodes`, so attach it to every existing connection now (the reverse of the handler's forward-attach).
      for (const conn of swarm.connections) { try { node.sb.attachSignerPresence(conn) } catch {} }
      // A DID booting AFTER connections exist: attach its overlay content protocol to each open conn too.
      if (node.overlay) for (const conn of swarm.connections) { try { node.overlay.attachProtocol(Protomux.from(conn)); logOverlayAttachResult(node.did, node.overlay); if (node.reconcile) node.reconcile() } catch (err) { logOverlayAttachFail(node.did, err) } }
      console.log(JSON.stringify({ msg: 'multi-did: serving DID', did: node.did, handle: d.handle || null, controlKey: node.control ? node.control.serverKey : null }))
    } catch (e) {
      // WITH THE STACK. A per-DID boot failure is reported by MESSAGE alone on every node in the fleet,
      // including a phone with no filesystem access and no debugger — so `Cannot read properties of
      // undefined (reading 'length')` named a JS idiom and nothing else, and localizing it meant guessing
      // at shapes and rebuilding an APK per guess. The message is the one thing that cannot identify the
      // site; the stack is free and is the whole diagnosis.
      console.error(JSON.stringify({ msg: 'multi-did: failed to boot DID', did: d.did, error: e.message, stack: e.stack }))
    }
  }
  await swarm.flush().catch(() => {})
  console.log(JSON.stringify({ msg: 'multi-did hpp serving', dids: nodes.length, storage }))

  const byDid = new Map(nodes.map((n) => [n.did, n]))
  const close = async () => {
    for (const n of nodes) { try { await n.close() } catch {} }
    for (const n of nodes) { if (n._sideStore) { try { await n._sideStore.close() } catch {} } } // daemon owns resync side stores
    try { await swarm.destroy() } catch {}
    try { await registry.close() } catch {}
    try { await store.close() } catch {}
  }
  return { nodes, byDid, shared, registry, close }
}
// DualBlobStore — write-new / read-both migration wrapper for a DID's blob store.
//
// Writes go to the content-addressed OverlayBlobStore (real files, FastCDC-deduped, servable by oid, and —
// under a shared blob root — ONE physical copy shared with a co-located consumer like favela-web). Reads
// try the overlay store first, then FALL BACK to the LEGACY Hyperbee BlobStore for blobs uploaded BEFORE
// the overlay swap (e.g. existing avatars) — so nothing 404s during the transition. No bulk rewrite of live
// data: old blobs serve from the legacy store and age out naturally (a re-upload lands in the overlay).
//
// Drop-in: same public surface as BlobStore / OverlayBlobStore (ready / put / get / has / close).
export class DualBlobStore {
  constructor (overlayStore, legacyStore) {
    if (!overlayStore) throw new Error('DualBlobStore: overlayStore required')
    this._new = overlayStore
    this._old = legacyStore || null
  }

  async ready () { return this } // the caller readies both underlying stores before constructing this

  // NEW blobs -> the content-addressed overlay store only (never the legacy balloon).
  put (bytes, mimeType) { return this._new.put(bytes, mimeType) }

  // Read the overlay store first; fall back to the legacy store for pre-migration blobs.
  async get (cidStr) {
    const r = await this._new.get(cidStr)
    if (r) return r
    return this._old ? this._old.get(cidStr) : null
  }

  async has (cidStr) {
    if (await this._new.has(cidStr)) return true
    return this._old ? this._old.has(cidStr) : false
  }

  // ── operator repair (pass-through to the overlay side; the legacy bee needs neither) ──────────────
  // Re-register the blob FILES so peers can fetch them by oid. The legacy Hyperbee store keeps its bytes
  // as bee values, which replicate as core blocks — it has no oid index to repair.
  // Inventory for listBlobs. Delegates to the overlay/pointer store only: the LEGACY store predates
  // pointers entirely, so it has no published set to enumerate and including it would report blobs the
  // rest of the network cannot fetch.
  async list (opts) {
    if (typeof this._new.list !== 'function') return { cids: [], cursor: null, skipped: 'not-supported' }
    return this._new.list(opts)
  }

  async reindexOverlay () {
    if (typeof this._new.reindexOverlay !== 'function') return { skipped: 'not-supported' }
    return this._new.reindexOverlay()
  }

  // Publish shared pointers for local blobs that were never announced. WRITABLE-ONLY — the caller gates
  // on base.writable (sb.set appends to the autobase).
  async backfillPointers () {
    if (typeof this._new.backfill !== 'function') return { skipped: 'not-supported' }
    return this._new.backfill()
  }

  // Pull blobs this node lacks but the swarm has announced (`__blob__/<cid>`). PULL-ONLY, so it is safe
  // on a non-writable replica. The legacy store is untouched: it holds pre-migration blobs that have no
  // shared pointer and no oid, so there is nothing there to converge.
  async reconcileBlobs (opts) {
    if (typeof this._new.reconcile !== 'function') return { skipped: 'not-supported' }
    return this._new.reconcile(opts)
  }

  async close () {
    try { await this._new.close() } catch {}
    try { if (this._old) await this._old.close() } catch {}
  }
}
// The invite ceremony, driven from a terminal — and shaped so a bridge web UI can drive the same thing.
//
// atproto-identity/lib/hosting.js is the pure half: given the head op it returns a signed update that
// claims a handle and names a PDS. This adds the three things a real ceremony needs around it — find the
// current head, get the recovery key out of wherever it lives, and SHOW what is about to happen before
// anything permanent occurs.
//
// ⛔ THE SUBMIT IS THE IRREVERSIBLE HALF, SO IT IS OPT-IN. Every function here previews by default and
// only submits when explicitly told to. A PLC append cannot be undone, edited or hidden; a ceremony whose
// default action is "write to a global public log" is the wrong default for a person AND for a web UI,
// where the same button gets double-clicked. Preview → confirm is the shape both want.
//
// ⛔ THE MNEMONIC IS NEVER AN ARGUMENT. Anything in argv is in `ps` for every user on the box, and in
// shell history. It comes from a FILE, or from the sealed vault the phone already produces — which is
// the path that matters, because it is the one where the secret was never typed anywhere.
//
// WHAT A WEB UI WOULD REUSE: describeChange (the preview it renders), resolveSigner (the unlock step),
// and hosting.js's attach/detach. What it would NOT reuse is the operator half — adding the DID to the
// bridge's frontedDids — because that is the OTHER side of the ceremony and the whole point is that
// neither side can complete it alone.

import { deriveAtprotoKey, ATPROTO_RECOVERY_PATH } from 'atproto-identity'
import { PlcDirectory } from 'atproto-identity/lib/plc-directory.js'
import { openVault } from 'atproto-identity/lib/vault.js'
import { attachHosting, detachHosting } from 'atproto-identity/lib/hosting.js'

/**
 * A human-readable account of what an op changes about a DID document.
 *
 * Pure, so the preview a person approves is computed the same way whatever renders it — a terminal now,
 * a bridge web UI later. Reporting only what CHANGES is deliberate: a full document dump buries the one
 * line that matters, and this is the moment someone decides whether to append to a permanent log.
 */
export function describeChange (prevSignedOp, nextOp) {
  const before = prevSignedOp || {}
  const akaOf = (o) => ((o && o.alsoKnownAs) || []).join(', ') || '(none)'
  const pdsOf = (o) => (o && o.services && o.services.atproto_pds && o.services.atproto_pds.endpoint) || '(none)'
  const changes = []
  if (akaOf(before) !== akaOf(nextOp)) changes.push({ field: 'handle', from: akaOf(before), to: akaOf(nextOp) })
  if (pdsOf(before) !== pdsOf(nextOp)) changes.push({ field: 'pds', from: pdsOf(before), to: pdsOf(nextOp) })

  // Carried-forward fields are worth ASSERTING in the preview rather than assuming. A PLC op replaces the
  // whole document, so "unchanged" is a property of this particular op, not a law — and silently dropping
  // a rotation key is the one mistake nobody recovers from.
  const kept = {
    rotationKeys: JSON.stringify(before.rotationKeys) === JSON.stringify(nextOp.rotationKeys),
    verificationMethods: JSON.stringify(before.verificationMethods) === JSON.stringify(nextOp.verificationMethods)
  }
  return { changes, kept, prev: nextOp.prev }
}

/**
 * Get the recovery private key from wherever the holder keeps it.
 *
 * Two sources, and the vault is the one that matters: it is what `mint` seals on the phone, so the
 * secret can travel to another device without ever being typed. The mnemonic file exists because paper
 * is the other real backup and someone recovering from it has nothing else.
 *
 * ⛔ NOT FROM argv. See the header — argv is world-readable in ps.
 */
export function resolveSigner ({ mnemonic = null, vault = null, passphrase = null, did = null } = {}) {
  let phrase = mnemonic
  if (!phrase && vault) {
    if (!passphrase) throw new Error('hosting: a sealed vault needs its passphrase')
    if (!did) throw new Error('hosting: opening a vault needs the DID it was sealed for')
    // openVault fails identically for a wrong passphrase, a tampered blob and the wrong identity — by
    // design, so a failure does not tell an attacker which half they got right.
    phrase = openVault({ envelope: vault, passphrase, did })
  }
  if (!phrase) throw new Error('hosting: no recovery mnemonic — pass --mnemonic-file or --vault')
  const key = deriveAtprotoKey(String(phrase).trim(), ATPROTO_RECOVERY_PATH)
  return { privateKey: key.privateKey, didKey: key.didKey }
}

function directory (plcUrl) {
  return new PlcDirectory(plcUrl ? { baseUrl: plcUrl } : {})
}

/** What the directory currently says about this identity. */
export async function hostingShow ({ did, plcUrl = null } = {}) {
  if (!did) throw new Error('hostingShow: did required')
  const head = await directory(plcUrl).getHead(did)
  return {
    did,
    handle: ((head && head.alsoKnownAs) || [])[0] || null,
    pds: (head && head.services && head.services.atproto_pds && head.services.atproto_pds.endpoint) || null,
    rotationKeys: (head && head.rotationKeys) || [],
    head
  }
}

/**
 * Accept an invite: claim `handle`, name `pdsUrl`.
 *
 * Previews unless `submit` is true. Returns the signed op either way, so a caller that wants to show it,
 * store it, or hand it to a person for a second look can — the op is only meaningful once appended, and
 * holding it costs nothing.
 */
export async function hostingAttach ({ did, handle, pdsUrl, signer, plcUrl = null, submit = false } = {}) {
  if (!did) throw new Error('hostingAttach: did required')
  const plc = directory(plcUrl)
  const prevSignedOp = await plc.getHead(did)
  const op = attachHosting({ prevSignedOp, handle, pdsUrl, signerPrivateKey: signer.privateKey })
  const preview = describeChange(prevSignedOp, op)
  if (!submit) return { submitted: false, op, preview }
  const data = await plc.submitUpdate({ did, signedOp: op })
  return { submitted: true, op, preview, data }
}

/** Leave hosting, returning the identity to P2P-only. Same preview-by-default rule. */
export async function hostingDetach ({ did, signer, plcUrl = null, submit = false } = {}) {
  if (!did) throw new Error('hostingDetach: did required')
  const plc = directory(plcUrl)
  const prevSignedOp = await plc.getHead(did)
  const op = detachHosting({ prevSignedOp, signerPrivateKey: signer.privateKey })
  const preview = describeChange(prevSignedOp, op)
  if (!submit) return { submitted: false, op, preview }
  const data = await plc.submitUpdate({ did, signedOp: op })
  return { submitted: true, op, preview, data }
}

/** Render a preview the way the CLI prints it. Exported so the shape is testable. */
export function formatPreview ({ did, preview, submitted }) {
  const lines = []
  lines.push((submitted ? 'APPENDED to the PLC log for ' : 'WOULD append to the PLC log for ') + did)
  for (const c of preview.changes) lines.push('  ' + c.field + ': ' + c.from + '  ->  ' + c.to)
  if (!preview.changes.length) lines.push('  (no changes)')
  lines.push('  rotation keys: ' + (preview.kept.rotationKeys ? 'unchanged' : '⛔ CHANGED'))
  lines.push('  signing key:   ' + (preview.kept.verificationMethods ? 'unchanged' : '⛔ CHANGED'))
  if (!submitted) lines.push('\nThis is PERMANENT and PUBLIC once submitted. Re-run with --yes to append it.')
  return lines.join('\n')
}

/**
 * The `hosting-*` subcommands.
 *
 * ⛔ PREVIEW IS THE DEFAULT AND --yes IS THE ONLY WAY PAST IT. A PLC append is permanent, public and
 * unerasable, so the ceremony shows the exact change and stops. That is also the shape a web UI wants:
 * render the preview, then a confirm button posts the same call with submit:true.
 */
export async function hostingCommand (argv) {
  const sub = argv[0]
  const flag = (n) => { const i = argv.indexOf('--' + n); return i < 0 ? null : argv[i + 1] }
  const has = (n) => argv.includes('--' + n)
  const did = argv.find((a) => a.startsWith('did:'))
  const plcUrl = flag('plc')

  if (!did) {
    console.error('usage:\n' +
      '  hyper-proto-peer hosting-show   <did> [--plc <url>]\n' +
      '  hyper-proto-peer hosting-attach <did> --handle <h> --pds <url> (--mnemonic-file <f> | --vault <f> --passphrase-file <f>) [--yes]\n' +
      '  hyper-proto-peer hosting-detach <did> (--mnemonic-file <f> | --vault <f> --passphrase-file <f>) [--yes]\n\n' +
      'The secret is read from a FILE, never from the command line — argv is visible in ps.')
    return 1
  }

  if (typeof globalThis.fetch !== 'function') await import('bare-fetch/global')
  const fs = await import('bare-fs')

  if (sub === 'hosting-show') {
    const s = await hostingShow({ did, plcUrl })
    console.log(JSON.stringify({ did: s.did, handle: s.handle, pds: s.pds, rotationKeys: s.rotationKeys }, null, 2))
    return 0
  }

  const read = (p) => fs.default.readFileSync(p, 'utf8').trim()
  let signer
  try {
    signer = resolveSigner({
      mnemonic: flag('mnemonic-file') ? read(flag('mnemonic-file')) : null,
      vault: flag('vault') ? JSON.parse(read(flag('vault'))) : null,
      passphrase: flag('passphrase-file') ? read(flag('passphrase-file')) : null,
      did
    })
  } catch (e) { console.error(e.message); return 1 }

  const submit = has('yes')
  const r = sub === 'hosting-detach'
    ? await hostingDetach({ did, signer, plcUrl, submit })
    : await hostingAttach({ did, handle: flag('handle'), pdsUrl: flag('pds'), signer, plcUrl, submit })

  console.log(formatPreview({ did, preview: r.preview, submitted: r.submitted }))
  if (r.submitted) {
    console.log('\nNext, on the machine running the bridge: add this DID to `frontedDids` in its config.')
    console.log('That half is the OPERATOR\'s and cannot be done from here — which is the point.')
  }
  return 0
}
// MINT — create a NEW atproto identity on the device that will use it.
//
// The symmetric half of lib/coowner.js. coownerJoin copies an EXISTING DID onto a second device; this
// creates the first one. Without it a node could only ever receive an identity, which left the origin
// of every identity outside the product: `bin/hpp-onboard.js` on a server with a hyperident and a shell.
// A handset has neither, so a second test phone was blocked on a step that could not be performed on it
// (hyper-social #54 §8).
//
// This is hpp-onboard's fresh-mint path — the same createSwarmIdentity + provisionDevice — writing the
// MULTI-DID `dids[]` entry that bootMultiDevice reads, rather than the single-DID server config.
//
// ── P2P-ONLY BY DEFAULT ──────────────────────────────────────────────────────────────────────────
// No handle, no PDS. Creating an identity and joining someone's infrastructure are different decisions,
// and requiring both at once is what made minting undecidable — you could not have a DID without first
// answering "whose server are you on?". The domain handle and the service endpoint arrive LATER, as a
// PLC update op, when an invite from atproto-bridge or ap-bridge is accepted. That ordering is forced,
// not chosen: an update op must chain onto a genesis already in the log.
//
// ── ⛔ CUSTODY: THE ROOT MNEMONIC MUST NOT STAY HERE ──────────────────────────────────────────────
// The root is the recovery authority — it can rotate the DID's signing key and therefore revoke every
// device. device-node.js is explicit that a device gets { did, signingKey, deviceProof, rootIdentityKey }
// and NEVER the root, "so it can't derive the recovery key or self-recover". Minting on the device is
// the one moment the root exists there. So it is RETURNED and never written: the caller shows it once
// and seals it into the vault (atproto-identity/lib/vault.js), and nothing persists it in the config.
// test/mint.test.mjs asserts the config does not contain it.
//
// ── WHAT THIS DOES NOT DO ────────────────────────────────────────────────────────────────────────
// It does not touch the network. Submitting the genesis to the PLC directory is a PERMANENT, PUBLIC,
// IRREVERSIBLE append to a global log, and it is a separate call for that reason — the same split
// hpp-onboard makes with --submit. A mint that cannot reach the directory still produces a working P2P
// identity, and the op can be re-derived from the mnemonic and submitted later (see the determinism
// test): submission is recoverable, so it must not be able to fail the part that isn't.
import b4a from 'b4a'
import IdentityKey from 'keet-identity-key'
import { deviceKeetKeyPair } from 'atproto-room/lib/membership.js'
import { PlcDirectory } from 'atproto-identity/lib/plc-directory.js'
import { provisionDevice } from './device-node.js'
import { readConfigFile, writeConfigFile } from './coowner.js'
import { configPath } from './config.js'

const hex = (u8) => b4a.toString(b4a.from(u8), 'hex')

/**
 * Create a new identity and write the dids[] entry this device boots from.
 *
 * @param {object} opts
 * @param {string} [opts.rootMnemonic] the recovery root. Omitted, a fresh one is generated — the normal
 *   case. Passing one is for tests and for re-minting a known identity.
 * @param {string} [opts.configFile] defaults to the usual PEER_CONFIG / ~/.config path.
 * @param {string|null} [opts.handle] leave null for P2P-only. Naming one here mints a DIFFERENT DID.
 * @param {string|null} [opts.pdsUrl] as above.
 * @param {function} [opts.onStep] progress, mirroring joinAdoptInvite's reporting.
 * @returns {{did, rootMnemonic, devicePublicKey, signedOp, entry}}
 */
export async function mintIdentity ({ rootMnemonic = null, configFile = null, handle = null, pdsUrl = null, onStep = () => {} } = {}) {
  const p = configFile || configPath()
  const cfg = readConfigFile(p)
  if (!Array.isArray(cfg.dids)) cfg.dids = []

  // ⛔ REFUSE RATHER THAN ADD. A device that already holds an identity is not asking to mint a second
  // one — it has arrived here by a routing mistake or a double-tap, and the cost of being wrong is
  // asymmetric: minting is cheap to repeat and impossible to undo, and a stray second entry would have
  // this node signing as an identity nobody else in the room knows about.
  if (cfg.dids.length) {
    throw new Error('mint: this device already has an identity (' + cfg.dids[0].did + ') — refusing to mint another')
  }

  const root = rootMnemonic || IdentityKey.generateMnemonic()
  onStep('generating this device\'s key')
  // DEVICE-SCOPED, and a different secret from the root. The device key is what the roster admits; the
  // root is what attests it. Conflating them would put the recovery authority on every device.
  const deviceMnemonic = IdentityKey.generateMnemonic()
  const deviceKp = await deviceKeetKeyPair(deviceMnemonic)
  const devicePublicKey = hex(deviceKp.publicKey)

  onStep('creating the identity')
  const bundle = await provisionDevice({ rootMnemonic: root, devicePublicKey, handle, pdsUrl })

  const entry = {
    did: bundle.did,
    deviceMnemonic,
    deviceProof: bundle.deviceProof,
    signingKey: bundle.signingKey,
    rootIdentityKey: bundle.rootIdentityKey,
    // The roster this device will be admitted against. It contains itself and nothing else: it is the
    // only device that exists. Co-owners are added later by the invite ceremony.
    members: [devicePublicKey],
    // ⛔ EXPLICIT, BECAUSE THE DEFAULT IS THE LEGACY BACKEND. bootSwarmDevice defaults storeBackend to
    // null and `if (storeBackend === 'overlay')` is the only thing that builds the OverlayRepoStore and
    // record overlay. Omitting it boots the DID on the legacy inline substrate — records in the autobase
    // where {$oid,size} pointers belong, and no record files — which reads as an EMPTY record set under
    // PointerSubstrate. device-node.js spells out the consequence: the first sign() after flipping such
    // a DID to 'overlay' materializes an empty MST root and publishes a delete-every-record commit, and
    // the anti-wipe guard cannot catch it because that guard looks for record FILES and there are none.
    //
    // Every live DID in the fleet is 'overlay'. A minted identity that omitted this logged
    // "firehose-only (noRepo) DID" and silently could not post — observed on a handset 2026-08-25. A
    // fresh identity has no history to migrate, so starting on the current backend is free and skips
    // the one migration that can destroy a repo.
    storeBackend: 'overlay',
    // THE FIRST DEVICE HOLDS THE GENESIS. This is the opposite posture from coownerJoin's `joiner`, and
    // it is explicit for the reason recorded there: the creator election is "lowest-keyed member ==
    // self", so leaving the role to emerge from key ordering silently flips it when a device joins whose
    // key sorts lower. A room's creator is a property, not an accident.
    forceCreator: true
  }
  // handle / pdsUrl are deliberately ABSENT rather than null — an entry that says nothing about
  // infrastructure is different from one that says "none", and the invite will add the real values.
  if (handle) entry.handle = handle
  if (pdsUrl) entry.pdsUrl = pdsUrl

  cfg.dids.push(entry)
  writeConfigFile(p, cfg)
  onStep('identity written — restart to sign')

  return {
    did: bundle.did,
    // ⛔ SHOW ONCE, SEAL, FORGET. Never persisted here. See the custody note above.
    rootMnemonic: root,
    devicePublicKey,
    signedOp: bundle.signedOp,
    entry: { did: bundle.did, members: entry.members }
  }
}

/**
 * Submit a minted genesis to the PLC directory.
 *
 * ⛔ PERMANENT AND PUBLIC. This appends to a global append-only log. There is no delete, and a test
 * identity is forever. Kept separate from mintIdentity so that the irreversible act is always its own
 * explicit call, and so a mint without network still succeeds.
 *
 * Safe to retry: the directory accepts a re-submission of the identical genesis, and the op can be
 * re-derived from the root mnemonic alone if this device is gone.
 */
/**
 * Install a global `fetch`, from THIS package's dependency tree.
 *
 * ⛔ WHY IT LIVES HERE AND NOT IN THE CALLER. `bare-fetch` pulls in bare-tls and bare-zlib, which are
 * NATIVE. An Android bundle names the sonames it needs and the APK must supply them — and the app's
 * own tree resolves bare-tls 3.1.10 while the APK carries 3.1.7. A caller importing bare-fetch itself
 * therefore demands a library that does not exist on the device: measured, as a failed build, and the
 * failure mode had it shipped is a bundle that dies at dlopen and is condemned for ever.
 *
 * Resolving it from here keeps the version the same one every other network path in this package
 * already uses, which is the one the APK was built against.
 */
export async function ensureFetch () {
  if (typeof globalThis.fetch !== 'function') await import('bare-fetch/global')
  return typeof globalThis.fetch === 'function'
}

export async function submitMintedGenesis ({ did, signedOp, plcUrl = null, onStep = () => {} } = {}) {
  if (!did || !signedOp) throw new Error('submitMintedGenesis requires { did, signedOp }')
  // Bare has no global fetch and PlcDirectory needs one for the POST. Installed lazily so that minting
  // — which is offline — never drags the network stack in. Same approach as hpp-onboard.
  if (typeof globalThis.fetch !== 'function') await import('bare-fetch/global')
  onStep('registering in the global directory')
  const plc = new PlcDirectory(plcUrl ? { baseUrl: plcUrl } : {})
  const data = await plc.submitGenesis({ did, signedOp })
  onStep('registered')
  return { did, submitted: true, alsoKnownAs: (data && data.alsoKnownAs) || [], services: (data && data.services) || {} }
}
// The retry decision for byte convergence — pure, so it can be tested without booting a device.
//
// ⛔ WHY THIS IS ITS OWN MODULE. The rule it replaces lived inside a closure in `bootSwarmDevice`, where
// nothing could reach it, and it was wrong in a way no test could have caught there: the pass loop ended
// with `if (!r.fetched) break`, which treats "everything resolved" and "I tried and could not reach the
// bytes" as the same outcome. The driver is deliberately zero-polling — it runs on a StateBase advance, a
// signer-presence change, or a peer's overlay attach — so "wait for an event" meant the most recently
// converged pointer waited for an event that had already happened.
//
// Measured on the handset 2026-08-18: a post converged at 21:26, its one fetch failed, nothing retried
// for 13 minutes; at the next boot the same fetch failed once and succeeded 3 seconds later. Transient
// all along. See test/reconcile-retry.test.mjs, whose first test pins the old decision.
//
// The caller owns the timer (and must unref it — a convergence retry may never be the reason a process
// stays alive). This owns only the arithmetic and the budget.

/**
 * @param {object}  opts
 * @param {number}  opts.failed        records that could not be fetched this pass
 * @param {number}  [opts.failedBlobs] blobs that could not be fetched this pass (same class of fault:
 *                                     reconcileBytes skips `__`-prefixed keys, so blobs converge in a
 *                                     separate pass and would otherwise be the half that never retries)
 * @param {boolean} opts.fromRetry     true when this pass WAS a retry; false when an event drove it
 * @param {number}  opts.attempts      retries already spent in this run of failures
 * @param {number}  opts.delay         the delay used last time, 0 if none
 * @param {number}  [opts.baseMs]
 * @param {number}  [opts.maxMs]
 * @param {number}  [opts.maxAttempts]
 * @returns {{arm: boolean, delay: number, attempts: number, giveUp: boolean}}
 */
export function nextRetry ({
  failed = 0,
  failedBlobs = 0,
  fromRetry = false,
  attempts = 0,
  delay = 0,
  baseMs = 5000,
  maxMs = 300000,
  maxAttempts = 8
} = {}) {
  // AN EVENT IS NEW INFORMATION; A RETRY IS THE SAME INFORMATION AGAIN. Only the former earns a fresh
  // budget — otherwise a node that hit a bad patch would spend its attempts once and never try again, no
  // matter what changed afterwards (a peer arriving is exactly such a change, and it arrives as an event).
  if (!fromRetry) { attempts = 0; delay = 0 }

  if (!failed && !failedBlobs) return { arm: false, delay: 0, attempts: 0, giveUp: false }

  // Bounded. A peer that genuinely does not hold these bytes must not be asked forever — but the caller
  // is TOLD, because the defect this module exists to fix was precisely a node giving up in silence.
  if (attempts >= maxAttempts) return { arm: false, delay, attempts, giveUp: true }

  return {
    arm: true,
    delay: delay ? Math.min(delay * 2, maxMs) : baseMs,
    attempts: attempts + 1,
    giveUp: false
  }
}
// serveDeviceUds — a LOCAL hyper-svc control surface for a SwarmDevice over a UNIX SOCKET, so a
// CO-LOCATED client (favela-web on the same box) reaches the device instantly via local IPC instead of a
// DHT rendezvous + hole-punch. The swarm surface (serve-device.js) stays for the REMOTE keyless bridge.
//
// AUTH: a UDS connection is owner-gated by the filesystem (only a local process with access to the socket
// path can connect), so the local surface is TRUSTED WITHOUT the writer-allowlist — the same model pgh /
// pgv3 / atproto-bridge use for their local hyper-svc sockets. (The swarm surface keeps canWrite because
// remote peers are untrusted.) Same op set as serveDevice; a client calls `c.call('<op>', params)`.
import b4a from 'b4a'
import fs from 'bare-fs'
import { Service } from 'hyper-svc'
import { conflictDiag } from './conflict-watch.js'

export async function serveDeviceUds (device, { uds, blobs = null, onRelease = null } = {}) {
  if (!uds) throw new Error('serveDeviceUds: uds path required')
  const svc = new Service({ name: 'hyper-proto-peer', uds })

  // OTA — the app half of the push contract. The sidecar performs the FULL install (tree + dep closure +
  // materialize) and then calls this; our only job is to exit cleanly so the supervisor respawns onto the
  // new tree. Injected rather than exiting here: this module serves a device and must not own the
  // process lifecycle.
  //
  // ⚠ NOT pgh-runtime's fetch path — it fetches root trees WITHOUT dep closures, which produces a broken
  // install (the MODULE_NOT_FOUND respawn loop that took the membrane down on 2026-07-31).
  if (onRelease) {
    svc.handle('release-ready', async (ctx, params = {}) => {
      const ver = (params && params.version) || '?'
      console.log(JSON.stringify({ msg: 'ota: release-ready — sidecar installed; respawning', version: ver }))
      // ⛔ A BARE catch {} here is what hid this twice. The handler logged "respawning", threw a
      // TypeError (0.3.100-0.3.103: `this` undefined), and the silence read as success on every surface.
      setImmediate(() => {
        try { onRelease(ver) } catch (e) {
          console.error(JSON.stringify({ msg: 'ota: respawn handler THREW — the daemon did NOT respawn', version: ver, error: (e && e.message) || String(e) }))
        }
      })
      return { ok: true, willRespawn: true }
    })
  }

  svc.handle('get-state', async () => device.state())
  // conflict-diag: hypercore conflicts seen SINCE BOOT. A conflict freezes a core and stops it
  // replicating while the served view stays correct, so a forked node looks healthy on every other
  // surface — loser-club logged conflicts for weeks under a clean `diag`. Per-process because
  // hypercore's own freeze is: `frozen` is never persisted, so a restart re-arms and re-detects it.
  svc.handle('conflict-diag', async () => conflictDiag())
  // members-diag: read-only membership/admission diagnostic (why a writer can't be admitted). reproject-
  // members: force-re-project __members__ (writable creator only). Both non-secret, UDS is owner-gated.
  svc.handle('members-diag', async () => device.membersDiag())
  // pointer-diag: does this node's LOCAL byte set match the converged pointer set? Hashes each record
  // file and compares it to the pointer's $oid. Read-only (no writes, no fetches), so it is safe on a
  // live daemon. This is the check that was missing when two wj62 co-owners held identical converged
  // pointers but different bytes for one record — invisible from every surface until two signed CARs
  // were diffed by hand. UDS-gated like the rest; it reads record keys + hashes, no record content.
  svc.handle('pointer-diag', async (ctx, op = {}) => device.pointerDiag(op || {}))
  // migrate-inline-pointers: OPERATOR MIGRATION for a DID whose autobase holds full RECORDS where
  // { $oid, size } pointers belong (written through the legacy substrate, now running the pointer
  // design). Such a repo reads fine locally and is unfetchable by every peer, so the DID cannot be
  // co-owned until this runs. Writable-only, idempotent, preserves published content (the pointer
  // addresses the bytes that already resolve, asserted by hash). WRITES — hence operator-triggered
  // over the owner-gated UDS rather than anything automatic.
  svc.handle('migrate-inline-pointers', async () => device.migrateInlinePointers())
  svc.handle('reproject-members', async () => device.reprojectMembers())
  // get-repo-car: export this device's current signed repo as an atproto CAR (com.atproto.sync.getRepo
  // shape). The input a PEER needs for fork recovery (fetch the authoritative node's CAR → reconcileFromCar
  // into a fresh line). Public (UDS is filesystem-owner-gated). Bytes as hex, matching get-blob.
  svc.handle('get-repo-car', async () => { const r = await device.exportCar(); return { car: b4a.toString(r.carBytes, 'hex'), commitCid: r.commitCid, dataCid: r.dataCid, rev: r.rev, recordCount: r.recordCount } })
  svc.handle('apply-write', async (ctx, op) => device.applyWrite(op))
  // get-record: read ONE record back. get-state lists {collection, rkey} and no values, so a client
  // could see THAT a record exists and never what it says — which makes "is what I would write
  // already there?" unanswerable, and the only alternative is a local fingerprint that drifts from
  // the repo. A projector reconciling desired-against-actual needs the actual.
  //
  // Read-only and UDS-gated like the diagnostics beside it. Returns null rather than throwing for an
  // absent record: "not written yet" is an ordinary state for a caller deciding whether to write.
  svc.handle('get-record', async (ctx, { collection, rkey } = {}) => {
    if (!collection || !rkey) throw new Error('get-record: collection and rkey required')
    try { return (await device.repo.getRecord(collection, rkey)) || null } catch { return null }
  })
  // reconcile-bytes: ATTEMPT to pull the authoritative bytes for every converged pointer this node
  // cannot resolve. The daemon already runs this on a loop; exposing it gives an operator a way to
  // demand one NOW and read the result, which is what makes "is this record recoverable?" answerable.
  // `repair-pointers` depends on exactly that: a record is only unrecoverable once a real fetch has
  // been attempted and failed, and tombstoning one that was merely un-fetched would destroy content a
  // peer still holds. PULL-ONLY — never appends to the autobase, so it is safe on a non-writable
  // replica and cannot alter the record set.
  svc.handle('reconcile-bytes', async (ctx, op = {}) => device.reconcileBytes(op || {}))
  // reindex-overlay: OPERATOR REPAIR for a node whose overlay index is missing or stale. Re-registers
  // every record file AND every blob file so peers can fetch them by oid, then announces any local blob
  // that never got a shared pointer. Byte resolution gates signing, so an impoverished index silently
  // stops this device signing — this is the way to fix that without a restart.
  //
  // UDS-ONLY BY DESIGN: it re-hashes every file, so exposing it on the peer-facing swarm surface would
  // hand any remote peer a free CPU-exhaustion trigger. The UDS is filesystem-owner-gated, which is the
  // right authority for an operator action. Purely additive — re-registration re-asserts identical
  // entries and the pointer backfill never clobbers one a co-owner already published.
  svc.handle('reindex-overlay', async () => {
    const records = await device.reindexOverlay()
    let blobFiles = { skipped: 'no-blob-store' }
    let pointers = { skipped: 'no-blob-store' }
    if (blobs) {
      if (typeof blobs.reindexOverlay === 'function') blobFiles = await blobs.reindexOverlay()
      // Pointer backfill APPENDS to the autobase, so only an admitted writer may run it; peers converge
      // the pointers by replication instead (same gate as migratePointers).
      if (typeof blobs.backfillPointers === 'function') {
        const writable = !!(device.sb && device.sb.base && device.sb.base.writable)
        pointers = writable ? await blobs.backfillPointers() : { skipped: 'not-writable' }
      }
    }
    return { records, blobs: blobFiles, pointers }
  })
  // get-service-auth — mint a short-lived ES256K service-auth JWT so the KEYLESS membrane can make a
  // USER-SCOPED AppView read as this account (the bridge's proxyToAppView already calls a serviceAuth
  // hook and attaches the Bearer; it simply had nothing to call). The primitive is
  // SwarmDevice.getServiceAuth — deliberately general, since it is atproto's com.atproto.server
  // .getServiceAuth. The AUTHORITY BOUNDARY is here, at the exposed capability.
  //
  // A minted token authenticates AS the DID, signed by the same #atproto key that signs every repo
  // commit (verified: it matches the key published in both hosted DIDs' PLC documents). So this handler
  // is a signing oracle and is constrained accordingly:
  //
  //   - lxm is REQUIRED and ALLOWLISTED. The primitive treats lxm as optional, and a token with no lxm
  //     is valid for ANY method at that audience — a far broader grant than anything we need. One entry
  //     for now; widening it must be a visible edit to this list, not a caller's choice.
  //   - aud must look like a DID (the AppView's service DID, e.g. did:web:api.bsky.app).
  //   - TTL is capped short. A leaked token then expires on its own.
  //   - UDS ONLY. This is deliberately NOT added to lib/serve-device.js's swarm surface: that is
  //     reachable by any peer that knows the DID, and pointer-diag is already writer-gated there for a
  //     much weaker reason (CPU cost). A remotely-reachable signing oracle would be the single worst
  //     thing on that surface. The UDS is owner-gated by filesystem permissions.
  const SERVICE_AUTH_LXM = ['app.bsky.notification.listNotifications']
  const SERVICE_AUTH_MAX_TTL_SEC = 120
  svc.handle('get-service-auth', async (ctx, op = {}) => {
    const aud = op && op.aud
    const lxm = op && op.lxm
    if (typeof aud !== 'string' || !aud.startsWith('did:')) throw new Error('get-service-auth: aud must be a service DID')
    if (typeof lxm !== 'string' || !lxm) throw new Error('get-service-auth: lxm required (a token without one is valid for ANY method)')
    if (!SERVICE_AUTH_LXM.includes(lxm)) throw new Error(`get-service-auth: lxm "${lxm}" is not allowlisted (allowed: ${SERVICE_AUTH_LXM.join(', ')})`)
    const now = Math.floor(Date.now() / 1000)
    const ttl = Math.min(Number(op.ttlSec) > 0 ? Number(op.ttlSec) : SERVICE_AUTH_MAX_TTL_SEC, SERVICE_AUTH_MAX_TTL_SEC)
    // Log the GRANT, never the token.
    console.log(JSON.stringify({ msg: 'service-auth minted', did: device.did, aud, lxm, ttlSec: ttl }))
    return device.getServiceAuth({ aud, lxm, exp: now + ttl })
  })
  svc.handle('delegate', async (ctx, op) => device.delegate(op || {}))
  svc.handle('list-devices', async () => ({ devices: await device.listDevices() }))
  svc.handle('revoke-device', async (ctx, op = {}) => {
    if (!op.subKey) throw new Error('revoke-device: subKey required')
    return op.restore ? device.restoreDevice(op.subKey) : device.revokeDevice(op.subKey, { reason: op.reason || null })
  })
  svc.handle('is-device-revoked', async (ctx, op = {}) => ({ revoked: await device.isDeviceRevoked(op.subKey) }))
  if (blobs) {
    // get-blob: local read counterpart to upload-blob — the co-located client (favela-web) renders images it
    // uploaded. The UDS had upload-blob but no read path, so locally-stored blobs were unreadable. Public (a
    // UDS connection is already filesystem-owner-gated). Returns { mimeType, size, bytes(hex) } or null.
    svc.handle('list-blobs', async (ctx, { limit, cursor } = {}) => {
      if (!blobs || typeof blobs.list !== 'function') return { cids: [], cursor: null, skipped: 'not-supported' }
      return blobs.list({ limit, cursor })
    })
    svc.handle('get-blob', async (ctx, { cid } = {}) => {
      if (!cid) throw new Error('get-blob: cid required')
      const blob = await blobs.get(String(cid))
      if (!blob) return null
      return { cid: String(cid), mimeType: blob.mimeType, size: blob.size, bytes: b4a.toString(blob.bytes, 'hex') }
    })
    // ⛔ A PATH IS ACCEPTED AS WELL AS BYTES, and for a co-located client it is the better one. This
    // is a unix socket: both ends are on one machine, and hex-encoding a picture to hand it to a
    // process that will write it straight back to disk doubles it in transit for nothing. favela-peer
    // settled the same question the same way ("PATHS cross this socket, never bytes"), and a client
    // that has to hex-encode needs a buffer library it may not otherwise depend on — which is a
    // MODULE_NOT_FOUND at boot waiting to happen, not a detail.
    //
    // Bytes stay supported: a REMOTE client has no shared filesystem and no path to offer.
    svc.handle('upload-blob', async (ctx, { bytes, path, mimeType } = {}) => {
      if (!bytes && !path) throw new Error('upload-blob: bytes (hex) or path required')
      let buf
      if (path) {
        try { buf = fs.readFileSync(path) } catch { throw new Error('upload-blob: no file at ' + path) }
      } else {
        buf = b4a.from(bytes, 'hex')
      }
      if (!buf || !buf.length) throw new Error('upload-blob: that file is empty')
      const { cid, size } = await blobs.put(buf, mimeType || 'application/octet-stream')
      return { cid: cid.toString(), mimeType: mimeType || 'application/octet-stream', size }
    })
  }

  await svc.listen()
  return { uds, close: async () => { try { await svc.close() } catch {} } }
}
// serveDevice — the swarm control surface for a SwarmDevice, the multi-device analog of
// peer.serve (lib/peer.js). It is SEPARATE from StateBaseV3's own replication swarm (that one
// converges the intent-log between the DEVICES); this one lets a CLIENT/APP submit writes to,
// and observe, a running device.
//
// Mirrors the single-tenant peer-signs-over-RPC channel exactly: a ProtomuxRPC muxed over each
// Hyperswarm connection, protocol 'hyper-proto-peer/device/v1'. The device joins BOTH its own
// serverKey topic (address one specific device) and the DID discovery topic (reach ANY device of
// the DID — any of them accepts a write into the shared log). Ops:
//   get-state    -> always: observable snapshot { did, self, holdsLease, head, records } (keys only)
//   apply-write  -> gated by canWrite(remotePubKeyHex): device.applyWrite(op) into the shared log
// canWrite is an allowlist of authorized client Noise pubkeys (config PEER_WRITERS), null = no
// remote writers (secure default), exactly as lib/peer.js. The device NEVER hands over the shared
// signing key; a caller only requests the write, the device owns the intent-log.

import b4a from 'b4a'
import c from 'compact-encoding'
import ProtomuxRPC from 'protomux-rpc'
import { discoveryTopic } from 'atproto-identity/lib/discovery.js'
import { conflictDiag } from './conflict-watch.js'

const DEVICE_PROTOCOL = 'hyper-proto-peer/device/v1'

// Methods a service-auth token may be minted for. ONE entry deliberately: this is the narrowest thing
// that makes listNotifications work, and every addition widens what a minted token can do at the AppView.
const SERVICE_AUTH_LXM = ['app.bsky.notification.listNotifications']
const SERVICE_AUTH_TTL_SEC = 120

export function serveDevice (device, swarm, { canWrite = null, blobs = null, sessions = null } = {}) {
  const serverKey = b4a.toString(swarm.keyPair.publicKey, 'hex')
  const onconn = (conn) => {
    const rk = conn.remotePublicKey ? b4a.toString(conn.remotePublicKey, 'hex') : null
    console.log(JSON.stringify({ msg: 'device control connection', from: rk, did: device.did }))
    conn.on('close', () => console.log(JSON.stringify({ msg: 'device control closed', from: rk })))
    const rpc = new ProtomuxRPC(conn, { protocol: DEVICE_PROTOCOL, valueEncoding: c.json })
    // get-state: always available — read-only observability (record keys, lease, head). No secret.
    rpc.respond('get-state', async () => device.state())
    // conflict-diag: hypercore conflicts seen since boot. Same public read surface as get-state — it
    // carries discovery keys, lengths and counts, no record content and no key material.
    rpc.respond('conflict-diag', async () => conflictDiag())
    // members-diag: read-only membership/admission diagnostic. reproject-members: force-re-project
    // __members__ (writable creator only). Read/idempotent; same public surface as get-state.
    rpc.respond('members-diag', async () => device.membersDiag())
    rpc.respond('reproject-members', async () => device.reprojectMembers())
    // get-repo-car: export the signed repo as an atproto CAR (getRepo shape) — what a PEER fetches for
    // fork recovery (reconcileFromCar into a fresh line). Public read (like get-state/get-blob). Bytes hex.
    rpc.respond('get-repo-car', async () => { const r = await device.exportCar(); return { car: b4a.toString(r.carBytes, 'hex'), commitCid: r.commitCid, dataCid: r.dataCid, rev: r.rev, recordCount: r.recordCount } })
    // get-blob: PUBLIC read (bsky fetches avatars/embedded images unauthenticated) — the counterpart to the
    // writer-gated upload-blob. The keyless bridge relays this (peer-front.getBlob) and streams the bytes to
    // bsky; server-bare.js expects { mimeType, bytes(hex) } or null (→ 404). This responder was MISSING:
    // blobs could be uploaded but never read back, so every getBlob 404'd regardless of who held the bytes.
    if (blobs) {
      // list-blobs: the DID's published blob inventory. READ-ONLY and ungated like get-blob — it returns
      // content addresses the peer already serves by CID, so it grants no access that get-blob does not.
      // This is what makes ORPHAN detection possible: a blob referenced by no record cannot be found by
      // walking records, only by asking the authority what it has (spec/convergence.md §6).
      rpc.respond('list-blobs', async ({ limit, cursor } = {}) => {
        if (typeof blobs.list !== 'function') return { cids: [], cursor: null, skipped: 'not-supported' }
        return blobs.list({ limit, cursor })
      })
      rpc.respond('get-blob', async ({ cid } = {}) => {
        if (!cid) throw new Error('get-blob: cid required')
        const blob = await blobs.get(String(cid))
        if (!blob) return null
        return { cid: String(cid), mimeType: blob.mimeType, size: blob.size, bytes: b4a.toString(blob.bytes, 'hex') }
      })
    }
    if (canWrite) {
      // pointer-diag: WRITER-GATED, unlike get-state/members-diag above. It is a READ, but it hashes every
      // record file, so publishing it to any peer that knows the DID would hand out a free
      // CPU-exhaustion trigger — the same reason reindex-overlay stays UDS-only. Gating it on the existing
      // trusted-key allowlist is what lets an operator ask a REMOTE node "do your bytes match your
      // pointers?" (hyper-proto-peer diag --remote) without an ssh session, while keeping the cost behind
      // a key. `limit` bounds the entries returned; the walk itself is bounded by the record set.
      rpc.respond('pointer-diag', async (op = {}) => {
        const remote = conn.remotePublicKey ? b4a.toString(conn.remotePublicKey, 'hex') : null
        if (!remote || !canWrite(remote)) throw new Error(`unauthorized: caller may not run pointer-diag for ${device.did}`)
        return device.pointerDiag(op || {})
      })
      // get-service-auth — mint a short-lived ES256K service-auth JWT so the KEYLESS membrane can make a
      // USER-SCOPED AppView read AS this account. This is the missing link in a chain that was otherwise
      // built end to end: atproto-did-peer declares the RPC (did-peer.js:379), the bridge's server-bare
      // wires a token cache and calls front.getServiceAuth, and proxyToAppView attaches the Bearer — but
      // nothing here answered, so every user-scoped read silently fell back to the public proxy. That is
      // why app.bsky.notification.listNotifications never worked.
      //
      // TWO GATES, both required. They answer different questions and neither is sufficient:
      //   canWrite(remote)             — may this PEER ask at all? (PEER_WRITERS Noise allowlist; this
      //                                  handler is only REGISTERED when configured, so it fails closed
      //                                  by not existing, matching pointer-diag/apply-write above)
      //   sessions.verifyAccess(token) — is a real USER logged in? The bridge forwards the end user's
      //                                  bearer precisely so this can be checked. Without it an
      //                                  allowlisted bridge could mint tokens for anyone at any time with
      //                                  nobody present.
      //
      // A minted token authenticates AS the DID, signed by the same #atproto key that signs every repo
      // commit (verified against both hosted DIDs' PLC documents). So it is a signing oracle, and beyond
      // the two gates it is constrained: lxm REQUIRED and allowlisted (the primitive treats lxm as
      // optional, and a token without one is valid for ANY method at that audience), aud must be a DID,
      // TTL capped short. Widening the allowlist is a visible edit here, not a caller's choice.
      //
      // REFUSES when sessions are unconfigured (canLogin false). That is correct rather than a limitation:
      // wj62/e2jev are accounts with appPasswordHash+jwtSecret, while a co-owned community feed like
      // loser-club has neither because nobody logs in AS the feed — so there is no user whose
      // notifications these would be, and it keeps the public unauthenticated proxy, which is right for a
      // feed. (A community inbox would want the WRITER SET as its authority, not a bearer — separate
      // decision.)
      rpc.respond('get-service-auth', async (op = {}) => {
        const remote = conn.remotePublicKey ? b4a.toString(conn.remotePublicKey, 'hex') : null
        if (!remote || !canWrite(remote)) throw new Error(`unauthorized: caller may not mint service auth for ${device.did}`)
        if (!sessions || !sessions.canLogin) throw new Error(`get-service-auth: sessions not configured for ${device.did} — refusing to mint ungated`)
        const { aud, lxm, token } = op || {}
        if (typeof aud !== 'string' || !aud.startsWith('did:')) throw new Error('get-service-auth: aud must be a service DID')
        if (typeof lxm !== 'string' || !lxm) throw new Error('get-service-auth: lxm required (a token without one is valid for ANY method)')
        if (!SERVICE_AUTH_LXM.includes(lxm)) throw new Error(`get-service-auth: lxm "${lxm}" is not allowlisted`)
        sessions.verifyAccess(token) // throws unless a valid, in-scope access JWT for THIS did
        const now = Math.floor(Date.now() / 1000)
        // Log the GRANT, never the token.
        console.log(JSON.stringify({ msg: 'service-auth minted (device surface)', did: device.did, aud, lxm, from: remote.slice(0, 12), ttlSec: SERVICE_AUTH_TTL_SEC }))
        return device.getServiceAuth({ aud, lxm, exp: now + SERVICE_AUTH_TTL_SEC })
      })
      rpc.respond('apply-write', async (op) => {
        const remote = conn.remotePublicKey ? b4a.toString(conn.remotePublicKey, 'hex') : null
        if (!remote || !canWrite(remote)) throw new Error(`unauthorized: caller may not write to ${device.did}`)
        return device.applyWrite(op)
      })
      // delegate: writer-gated (same allowlist as apply-write). Authorize a browser sub-key for DID
      // web sign-in — the #atproto key signs a delegation the keyless verifier (favela) checks vs PLC.
      // Privileged (a new device authorization), so it rides the canWrite allowlist, like apply-write.
      rpc.respond('delegate', async (op) => {
        const remote = conn.remotePublicKey ? b4a.toString(conn.remotePublicKey, 'hex') : null
        if (!remote || !canWrite(remote)) throw new Error(`unauthorized: caller may not delegate for ${device.did}`)
        return device.delegate(op)
      })
      // device registry (Option 3): list / revoke / query the DID's delegated browser sub-keys. Records
      // live as reserved StateBase entries (never public); revocation is a replicated tombstone the
      // keyless verifier (favela login) enforces. All writer-gated (same allowlist as delegate).
      rpc.respond('list-devices', async () => {
        const remote = conn.remotePublicKey ? b4a.toString(conn.remotePublicKey, 'hex') : null
        if (!remote || !canWrite(remote)) throw new Error(`unauthorized: caller may not list devices for ${device.did}`)
        return { devices: await device.listDevices() }
      })
      rpc.respond('revoke-device', async (op) => {
        const remote = conn.remotePublicKey ? b4a.toString(conn.remotePublicKey, 'hex') : null
        if (!remote || !canWrite(remote)) throw new Error(`unauthorized: caller may not revoke devices for ${device.did}`)
        if (!op || !op.subKey) throw new Error('revoke-device: subKey required')
        return op.restore ? device.restoreDevice(op.subKey) : device.revokeDevice(op.subKey, { reason: op.reason || null })
      })
      rpc.respond('is-device-revoked', async (op) => {
        const remote = conn.remotePublicKey ? b4a.toString(conn.remotePublicKey, 'hex') : null
        if (!remote || !canWrite(remote)) throw new Error(`unauthorized: caller may not query devices for ${device.did}`)
        if (!op || !op.subKey) throw new Error('is-device-revoked: subKey required')
        return { revoked: await device.isDeviceRevoked(op.subKey) }
      })
      // upload-blob: writer-gated (same allowlist as apply-write). Stores content-addressed bytes into
      // the peer's shared BlobStore so get-blob (membrane surface) can serve them. bytes are hex in the
      // c.json RPC value. Returns { cid, mimeType, size } — the caller builds the blob ref for a record.
      if (blobs) {
        rpc.respond('upload-blob', async ({ bytes, mimeType } = {}) => {
          const remote = conn.remotePublicKey ? b4a.toString(conn.remotePublicKey, 'hex') : null
          if (!remote || !canWrite(remote)) throw new Error(`unauthorized: caller may not write to ${device.did}`)
          if (!bytes) throw new Error('upload-blob: bytes (hex) required')
          const { cid, size } = await blobs.put(b4a.from(bytes, 'hex'), mimeType || 'application/octet-stream')
          return { cid: cid.toString(), mimeType: mimeType || 'application/octet-stream', size }
        })
      }
    }
  }
  swarm.on('connection', onconn)
  const keyTopic = swarm.keyPair.publicKey
  const didTopic = discoveryTopic(device.did)
  const dKey = swarm.join(keyTopic, { server: true, client: false })
  const dDid = swarm.join(didTopic, { server: true, client: false })
  return {
    serverKey,
    discoveryTopic: b4a.toString(didTopic, 'hex'),
    ready: () => Promise.all([dKey.flushed(), dDid.flushed()]),
    close: () => swarm.off('connection', onconn)
  }
}

export { DEVICE_PROTOCOL }
// Session auth for the swarm's bsky-login path. The PEER is the sole auth authority: it verifies the
// app-password against `appPasswordHash` and mints/verifies JWTs with the peer-held `jwtSecret`. The
// keyless bridge relays create-session/refresh-session over RPC but never sees credentials or the
// secret. Mirrors lib/peer.js's session logic exactly, so a bsky client logging in against the swarm
// behaves identically to the single-tenant peer. Secrets are carried in the swarm config (both
// devices), since the swarm boots from the config bundle, not the single-tenant vault.

import { verifyPassword, signJwt, verifyJwt } from 'atproto-identity/lib/auth.js'

const ACCESS_TTL_SEC = 2 * 60 * 60        // 2h — standard atproto access-token lifetime
const REFRESH_TTL_SEC = 90 * 24 * 60 * 60 // 90d — standard atproto refresh-token lifetime

export function makeSessions ({ did, handle, appPasswordHash, jwtSecret } = {}) {
  const canLogin = !!(jwtSecret && appPasswordHash)
  const nowSec = () => Math.floor(Date.now() / 1000)
  const mint = () => {
    const n = nowSec(); const base = { sub: did }
    return {
      did,
      handle,
      accessJwt: signJwt({ ...base, scope: 'com.atproto.access', exp: n + ACCESS_TTL_SEC }, jwtSecret),
      refreshJwt: signJwt({ ...base, scope: 'com.atproto.refresh', exp: n + REFRESH_TTL_SEC }, jwtSecret)
    }
  }
  return {
    canLogin,
    // com.atproto.server.createSession — verify the app-password, mint tokens.
    createSession ({ identifier, password } = {}) {
      if (!canLogin) throw new Error('createSession: sessions not configured on this peer')
      if (identifier && identifier !== handle && identifier !== did) throw new Error('createSession: unknown identifier')
      if (!password || !verifyPassword(password, appPasswordHash)) throw new Error('createSession: invalid credentials')
      return mint()
    },
    // com.atproto.server.refreshSession — re-mint from a valid refresh token.
    refreshSession (refreshJwt) {
      if (!canLogin) throw new Error('refreshSession: sessions not configured on this peer')
      const payload = verifyJwt(refreshJwt, jwtSecret, { nowSec: nowSec() })
      if (payload.scope !== 'com.atproto.refresh') throw new Error('refreshSession: not a refresh token')
      return mint()
    },
    // Verify an access token (for the write path): throws unless a valid, in-scope access JWT for this DID.
    verifyAccess (accessJwt) {
      if (!canLogin) throw new Error('verifyAccess: sessions not configured on this peer')
      const payload = verifyJwt(accessJwt, jwtSecret, { nowSec: nowSec() })
      if (payload.scope !== 'com.atproto.access') throw new Error('verifyAccess: not an access token')
      if (payload.sub && payload.sub !== did) throw new Error('verifyAccess: token subject mismatch')
      return payload
    }
  }
}
// SwarmDevice — one device of the swarm: the composition that IS atproto-base at the daemon
// level. It wraps the shared StateBaseV3 intent-log with the repo-op layer (RepoBase), the
// single-signer lease, and the shared-key signer. Every attested device writes repo intents into
// the shared autobase; whichever device currently holds the lease materializes the linearized
// view into the ONE canonical signed atproto commit chain, continuing from the last signed head.
//
// Construct the StateBaseV3 elsewhere (with the membership admission opts from lib/membership.js —
// getMembers/attest/verifyAttest/selfKey — and the members-only roomSeed/encryptionKey) and pass
// it in. `privateKey` is the SHARED #atproto signing key (distributed to attested devices).

import { RepoBase, isTombstone } from 'atproto-room/lib/repo-base.js'
import { PointerSubstrate } from 'atproto-store/lib/pointer-substrate.js'
import { Lease } from 'atproto-room/lib/lease.js'
import { materialize, buildCommitWrite } from 'atproto-room/lib/signer.js'
import { getRepoFromCommit } from 'atproto-store/lib/read-view.js'
import { tidNow, nextRev } from 'atproto-store/lib/tid.js'
import { signAssertion } from 'atproto-identity/lib/auth.js'
import b4a from 'b4a'
import { CID } from 'multiformats/cid'
import * as dagCbor from '@ipld/dag-cbor'

// The firehose lives in the SAME shared StateBaseV3 (option a): each lease-holder sign() writes the
// signed #commit under __commit__/<rev>. It replicates to every device + the keyless membrane reads
// it there — no separate Hypercore, no fork hazard, continuous across lease hand-offs. RepoBase
// skips the reserved "__" namespace so these entries never leak into the signed repo.
const FIREHOSE_PREFIX = '__commit__/'
import { encodeReceipt, receiptEpoch } from 'atproto-room/lib/membership.js'

// StateBaseV3's durable banned-identity set + minimum-epoch receipt (see state-base.js).
// atproto-base-REVOCATION.md §3/§6.
const REMOVED_SET = '__removed__'
const RECEIPT_KEY = '__receipt__'
const PREFS_KEY = '__prefs__' // private bsky preferences (birthdate etc.); reserved → never in the public repo
const DEVICE_PREFIX = '__device__/' // delegated browser sub-key registry (reserved → never in the public repo)
const DEVICE_REVOKED_PREFIX = '__device_revoked__/' // per-sub-key revocation tombstone (reserved → never public)
// The rev from which record deletions are guaranteed to leave a TOMBSTONE. Paths whose create frame
// predates it may have been hard-deleted by an older build, so for those the forward-only gate keeps
// the legacy "absent == deleted" reading; at or after it, absence can only mean "not replicated to me"
// and the gate fails safe. Unset => every path is legacy => behaviour identical to before tombstones.
const TOMBSTONE_EPOCH = '__tombstone_epoch__'

// Serialize a buildCommitWrite result into a JSON-safe firehose entry (binary as hex) — the shape
// StateBaseV3 stores + the membrane reconstructs a subscribeRepos #commit from.
function serializeEntry (write, seq) {
  const hex = (u8) => b4a.toString(b4a.from(u8), 'hex')
  return {
    seq,
    // The REAL wall-clock emission time, recorded once by the signer into the shared __commit__ log.
    // The membrane used to recompute the frame's `time` from the rev (revTime) so that every device
    // projected a byte-identical frame — fine while revs were wall-clock TIDs, but revs are now a
    // deterministic prev+1µs chain, so a derived time freezes near the FIRST commit and recedes
    // further from reality with every commit. Relays read `time` as liveness metadata and this fleet
    // already has to fight non-archival relays dropping accounts that look stale.
    // Recording it here keeps BOTH properties: it is real, and it is identical on every device
    // because they all replicate and read the same stored fact instead of each deriving it.
    // `time` is frame metadata only — never part of the signed commit (atproto-store firehose.js:37).
    time: new Date().toISOString(),
    rev: write.rev,
    since: write.since,
    prev: write.signedCommit.prev ? write.signedCommit.prev.toString() : null,
    prevData: write.prevData ? write.prevData.toString() : null, // prev MST root (for the #commit frame)
    commitCid: write.commitCid.toString(),
    commit: hex(write.commitBlock.bytes),
    ops: write.ops.map((o) => ({ action: o.action, path: o.path, cid: o.cid ? o.cid.toString() : null, prev: o.prev ? o.prev.toString() : null })),
    blocks: write.newBlocks.map((b) => ({ cid: b.cid.toString(), bytes: hex(b.bytes) }))
  }
}

export class SwarmDevice {
  constructor (statebase, { did, privateKey, self, ttlMs = 15000, clock, firehose = false, recordStore = null } = {}) {
    if (!did || !privateKey || !self) throw new Error('SwarmDevice: did, privateKey, self required')
    this.sb = statebase
    this.did = did
    this.privateKey = privateKey
    // Records: when `recordStore` (an OverlayRepoStore) is given, use the POINTER design — a tiny
    // {$oid,size} pointer per record in the shared StateBase autobase (so the record SET converges
    // symmetrically across attested devices, like the default path) while the record BYTES live as
    // deduped overlay files (O(current), off the append-only log; the firehose no longer carries them
    // once 2b lands). Else the legacy path stores full records in the StateBase. Reserved "__" keys
    // (firehose __commit__, admission, prefs) ALWAYS stay on the StateBase directly (this.sb). RepoBase
    // sees the same records either way, so sign()/materialize are unchanged. See
    // docs/SYNTHESIS-storage-consensus-append-2026-07-19.md (Step 2a).
    // ⚠ A repo previously written files-only (OverlayRepoSubstrate) has bytes-on-disk but NO pointers —
    // migratePointers() below backfills them at boot so sign() never reads an empty set + wipes (wj62).
    this.repo = new RepoBase(recordStore ? new PointerSubstrate(statebase, recordStore) : statebase, { did })
    this._recordStore = recordStore
    this.lease = new Lease(statebase, { self, ttlMs })
    this._clock = clock // optional injectable micros clock for deterministic revs in tests
    this.firehose = firehose // when true, sign() persists the signed #commit into __commit__/<rev>
    this._lastRecords = [] // record set at the last sign — the `before` side of the #commit diff
    this.head = null // { rev, commitCid, dataCid, signedCommit } — the last signed commit
  }

  // Tolerant snapshot reads. The substrate contract is only { set, del, get, list } (RepoBase's
  // documented interface, and all test/serve-device.test.js's memKV implements) — getNow/listNow are a
  // StateBaseV3 extension for non-blocking reads. RepoBase already falls back this way; reading them
  // off this.sb directly does not, which broke get-state on a minimal substrate.
  _listNow (prefix = '') { return (typeof this.sb.listNow === 'function') ? this.sb.listNow(prefix) : this.sb.list(prefix) }
  _getNow (key) { return (typeof this.sb.getNow === 'function') ? this.sb.getNow(key) : this.sb.get(key) }

  // ── writes: any attested device appends repo intents to the shared log ──
  putRecord (collection, rkey, record) { return this.repo.putRecord(collection, rkey, record) }
  deleteRecord (collection, rkey) { return this.repo.deleteRecord(collection, rkey) }

  // ── Step 2a migration: backfill files-only records into autobase pointers ──
  // Idempotent, WRITABLE-ONLY. A repo previously written files-only (OverlayRepoSubstrate) has record
  // BYTES on disk but no pointers in the shared autobase, so under PointerSubstrate the pointer set
  // reads empty — the wj62-wipe hazard. This writes a {$oid,size} pointer per un-pointed record file
  // so listRecords() reflects the real set BEFORE the boot path decides adopt/restore/fresh and before
  // the first sign(). No-op unless the record substrate is a PointerSubstrate (has backfill) AND this
  // device is a writable (admitted) writer — only the creator can append pointers; peers converge them
  // by replication. Delegates to PointerSubstrate.backfill (never clobbers a converged pointer/tombstone).
  async migratePointers () {
    const sub = this.repo.sb
    if (!sub || typeof sub.backfill !== 'function') return { skipped: 'not-pointer-substrate' }
    if (!(this.sb.base && this.sb.base.writable)) return { skipped: 'not-writable' }
    const r = await sub.backfill()
    if (r.written) console.log(JSON.stringify({ msg: 'migratePointers: backfilled files-only records into pointers', did: this.did, ...r }))
    return r
  }

  // ── MIGRATION: inline records → pointers (the loser-club shape) ─────────────────────────────────
  // A DID written through the LEGACY substrate but now running the pointer design has full RECORDS
  // sitting in the autobase where { $oid, size } pointers belong. It reads perfectly here and is
  // UNFETCHABLE BY EVERY PEER — _resolve has no oid to fetch by, so it falls back to the local file.
  // A co-owner converges the keys and can never turn them into bytes, which is why loser-club (3
  // records, all inline) cannot be co-owned at all until this runs.
  //
  // Distinct from migratePointers/backfill, which covers the opposite gap (bytes on disk, NO entry in
  // the autobase) and deliberately skips any key that already has a value — an inline record is such a
  // value, so backfill can never convert one.
  //
  // Content is PRESERVED, not chosen: the pointer addresses the bytes that already resolve (the local
  // file), asserted by hash, so the signed repo does not change. WRITABLE-ONLY (it appends pointers;
  // peers converge them by replication). Idempotent. Nothing deleted. Operator-triggered, not a boot
  // step: it rewrites autobase entries, which is not something to do implicitly on every start.
  async migrateInlinePointers () {
    const sub = this.repo.sb
    if (!sub || typeof sub.migrateInline !== 'function') return { skipped: 'not-pointer-substrate' }
    if (!(this.sb.base && this.sb.base.writable)) return { skipped: 'not-writable' }
    const r = await sub.migrateInline()
    console.log(JSON.stringify({ msg: 'migrateInlinePointers: inline records converted to fetchable pointers', did: this.did, ...r }))
    return r
  }

  // EXPLICIT REPAIR for a store whose overlay INDEX is missing or stale — re-hashes and re-registers
  // every record file so peers can fetch it by oid. Distinct from the boot path: OverlayRepoStore.ready()
  // only re-seeds the in-memory path maps from an already-healthy index, which is cheap enough to run
  // every boot; this walks and re-hashes everything, which is not (it is the cold-start cost that made
  // pgh-sidecar take ~190s to bind its socket), so it stays operator-triggered.
  //
  // Why it is worth exposing: byte resolution GATES SIGNING — the forward-only gate skips while a
  // converged pointer's bytes are unresolved — so an impoverished index silently stops this device
  // signing at all. Measured on tabertron: 51 of ~131 record paths indexed. The capability shipped in
  // atproto-store with NO trigger (no RPC, no CLI), i.e. unreachable; this is that trigger.
  async reindexOverlay () {
    if (!this._recordStore || typeof this._recordStore.reindexOverlay !== 'function') return { skipped: 'no-record-store' }
    const r = await this._recordStore.reindexOverlay()
    console.log(JSON.stringify({ msg: 'reindexOverlay: record files re-registered as servable-by-oid', did: this.did, ...r }))
    return r
  }

  // ── PEER-LEVEL BYTE CONVERGENCE — the missing half of the design ────────────────────────────────
  // The autobase guarantees POINTER convergence: every co-owner agrees on WHICH records exist. Byte
  // convergence had no equivalent. The ONLY path that resolves record bytes is sign()'s
  // listRecords({now:true}) — and sign() returns at the ELECTION GATE (holdsSigner, above) before it
  // ever gets there. So a co-owner that is not the current signer never fetched a single record byte:
  // its byte set grew only from what it authored locally, while its pointer set stayed correct and
  // agreeing. Both nodes therefore report a healthy, identical record set while silently diverging —
  // "co-owned on paper, single-homed in practice". Measured on wj62: 125 vs 124 posts, each node
  // holding one the other lacked, and a record unresolved for 75+ hours that appeared instantly the
  // moment anything called a byte-resolving read.
  //
  // PULL-ONLY: this never appends to the autobase, so it is safe on a NON-WRITABLE replica — which is
  // precisely the device that needs it. Idempotent (ensureLocal short-circuits on a local hit) and
  // bounded per pass (`more` tells the caller to keep going) so a backlog never blocks signing.
  // Re-seeding is automatic — hyper-overlay re-registers what it fetches (overlay.js fetchFile), so a
  // peer that catches up becomes a server for the next one.
  async reconcileBytes ({ limit = 32 } = {}) {
    if (!this._recordStore || typeof this._recordStore.ensureLocal !== 'function') return { skipped: 'no-record-store' }
    let raw
    try { raw = await this._listNow('') } catch (e) { return { skipped: 'list-failed', error: e.message } }
    let checked = 0; let missing = 0; let stale = 0; let fetched = 0; let failed = 0; let more = false
    for (const [k, ptr] of Object.entries(raw)) {
      const i = k.indexOf('/')
      if (i <= 0 || k.startsWith('__')) continue // reserved/control key — never a record
      if (isTombstone(ptr)) continue // deleted — there are no bytes to pull
      checked++
      const collection = k.slice(0, i)
      const rkey = k.slice(i + 1)
      let have = null
      try { have = await this._recordStore.get(collection, rkey) } catch {}
      if (have != null) {
        // PRESENCE IS NOT AGREEMENT. This used to `continue` on any local file, so a SUPERSEDED copy
        // was indistinguishable from the converged one and byte convergence silently skipped exactly
        // the records that had diverged — the wj62 profile/avatar case, invisible to this pass by
        // construction. Verify the local bytes against the pointer; only a match is convergence.
        let ok = true
        if (ptr && ptr.$oid && typeof this._recordStore.localOid === 'function') {
          const h = await this._recordStore.localOid(collection, rkey)
          ok = !h || h.oid === ptr.$oid // only a POSITIVE mismatch is staleness; unhashable => leave alone
        }
        if (ok) continue
        stale++ // fall through: ensureLocal now re-fetches the authoritative bytes over a stale file
      } else missing++
      if (fetched + failed >= limit) { more = true; continue } // bounded pass; caller continues
      const rec = await this._recordStore.ensureLocal(collection, rkey, ptr && ptr.$oid)
      if (rec != null) fetched++; else failed++
    }
    // Quiet in steady state, reports on change — a peer that is simply up to date says nothing, and a
    // peer that is stuck says so once rather than on every event.
    const sig = checked + ':' + missing + ':' + stale + ':' + fetched + ':' + failed
    if ((fetched || missing || stale) && sig !== this._lastReconcileSig) {
      console.log(JSON.stringify({ msg: 'reconcileBytes: resolving converged pointers into local bytes', did: this.did, checked, missing, stale, fetched, failed, more }))
    }
    this._lastReconcileSig = sig
    return { checked, missing, stale, fetched, failed, more }
  }

  // ── READ-ONLY INTEGRITY DIAGNOSTIC: does my local byte set match the converged pointer set? ──────
  // The autobase converges POINTERS ({$oid,size} per record); the signed repo is built from the BYTES
  // those pointers resolve to. Nothing checked that the two agree, because ensureLocal returns a local
  // file hit without ever comparing it to the pointer's $oid (overlay-repo-store.js) — so a node
  // holding a SUPERSEDED copy of a record resolves it happily, never re-fetches, and signs it as truth.
  //
  // That is not hypothetical: on wj62 both co-owners held the SAME 139 converged pointers, both
  // resolved all 139, and still produced different signed repos — they differed on exactly one record
  // (app.bsky.actor.profile/self, two different avatar blob refs). The signed content therefore FLIPPED
  // on every signer change, republishing the profile with a different avatar each time. Diagnosing it
  // required fetching two signed CARs and diffing them by hand; this answers the same question on ONE
  // node in one call, which is the difference between minutes and days.
  //
  // reconcileBytes cannot see this class of fault by construction: it fetches only records with NO
  // local bytes (`if (have != null) continue`), so a stale-but-present file is invisible to it too.
  //
  // Pure read: hashes local files, reads the pointer snapshot, writes nothing, fetches nothing. Returns
  // { checked, ok, stale, missing, unresolvable, tombstones, entries[] } where entries lists only the
  // NON-ok records: state 'stale' (local bytes hash != the pointer's $oid — the silent divergence),
  // 'missing' (pointer converged, no local bytes — normal on a lagging peer, reconcileBytes fetches it),
  // or 'no-oid' (a pointer carrying no $oid, e.g. a legacy inline record under a pointer substrate).
  async pointerDiag ({ prefix = '', limit = 0 } = {}) {
    if (!this._recordStore || typeof this._recordStore.localOid !== 'function') return { skipped: 'no-record-store' }
    let raw
    try { raw = await this._listNow(prefix) } catch (e) { return { skipped: 'list-failed', error: e.message } }
    let checked = 0; let ok = 0; let stale = 0; let missing = 0; let unresolvable = 0; let tombstones = 0
    const entries = []
    for (const [k, ptr] of Object.entries(raw)) {
      const i = k.indexOf('/')
      if (i <= 0 || k.startsWith('__')) continue // reserved/control key — never a record
      if (isTombstone(ptr)) { tombstones++; continue }
      checked++
      const collection = k.slice(0, i)
      const rkey = k.slice(i + 1)
      const ptrOid = ptr && ptr.$oid ? String(ptr.$oid) : null
      const local = await this._recordStore.localOid(collection, rkey)
      let state
      if (!ptrOid) { state = 'no-oid'; unresolvable++ } else if (!local) { state = 'missing'; missing++ } else if (local.oid !== ptrOid) { state = 'stale'; stale++ } else { state = 'ok'; ok++ }
      if (state === 'ok') continue
      if (limit && entries.length >= limit) continue
      // pointerFields: the FIELD NAMES of the raw autobase value (never its content). A pointer should
      // be exactly ['$oid','size']; anything else is a malformed or wrong-shaped entry, and the field
      // names say which — e.g. ['$type','displayName',…] means an INLINE RECORD was written where a
      // pointer belongs (a legacy-substrate write against an overlay-backed DID), which reads fine
      // locally and is unfetchable by every other node. loser-club sits in exactly that state and the
      // shape was not knowable from any surface, so diagnosing it meant guessing. Names only, capped.
      entries.push({
        key: k,
        state,
        pointerOid: ptrOid,
        pointerSize: (ptr && ptr.size) || null,
        pointerFields: (ptr && typeof ptr === 'object') ? Object.keys(ptr).slice(0, 12) : typeof ptr,
        localOid: local ? local.oid : null,
        localSize: local ? local.size : null
      })
    }
    if (stale) {
      console.error(JSON.stringify({
        msg: 'pointerDiag: LOCAL BYTES DIVERGE FROM THE CONVERGED POINTER — this node resolves these records to superseded bytes and will sign them as truth; ensureLocal never re-fetches because a local file is present',
        did: this.did, stale, checked, keys: entries.filter((e) => e.state === 'stale').map((e) => e.key).slice(0, 10)
      }))
    }
    return { did: this.did, checked, ok, stale, missing, unresolvable, tombstones, entries }
  }

  // Install the tombstone epoch: from this rev on, every deletion leaves a tombstone, so the
  // forward-only gate may treat a missing pointer as "not replicated" rather than "deleted" — the
  // fail-safe that stops a lagging co-owner publishing a delete for a live record.
  //
  // ⚠ Install this only when NO deletion is pending-but-unsigned anywhere in the group: such a delete
  // left no tombstone and its create frame is at/after the epoch, so the gate would classify it as
  // "behind" forever and wedge the chain. Audit first — .probe-delete-audit.mjs replays every #commit
  // op read-only over P2P and shows whether any delete is outstanding. Idempotent + writable-only;
  // never lowers an existing epoch.
  async ensureTombstoneEpoch () {
    if (!(this.sb.base && this.sb.base.writable)) return { skipped: 'not-writable' }
    const cur = await this.sb.get(TOMBSTONE_EPOCH).catch(() => null)
    if (cur && cur.rev) return { already: cur.rev }
    if (!this.head) await this.restore()
    const rev = this.head ? this.head.rev : ''
    await this.sb.set(TOMBSTONE_EPOCH, { rev })
    return { installed: rev }
  }

  // ── lease: become / stay the active signer ──
  claimLease () { return this.lease.claim() }
  renewLease () { return this.lease.renew() }
  renewOrClaimLease () { return this.lease.renewOrClaim() } // safe per-tick: renew, else claim iff free
  holdsLease () { return this.lease.holds() }

  // ── revocation (atproto-base-REVOCATION §6) ──
  // Ban a device by its keet identity hex: records it in the shared REMOVED_SET, drops it from the
  // roster, and removeWriters it (apply-side). Only takes effect if THIS device is a role-1 member —
  // the apply guard authorizes by the caller's writer. After this, the banned device can neither
  // write nor re-admit. NB: also PLC-rotate the shared #atproto key (root, recovery key) to kill any
  // exfiltrated signing-key copy — that closes layer B; this closes layer A.
  banDevice (identityHex) { return this.sb.banDevice(String(identityHex)) }

  // The durable banned-identity set { identityHex: { ts } } from the shared state.
  async removed () { const m = await this.sb.get(REMOVED_SET); return m || {} }

  // Bump the minimum attestation epoch: after this, any device whose attestation epoch is below
  // `epoch` is rejected on admission — re-attest survivors at >= epoch to keep them. Invalidates all
  // stale/revoked proofs at once (atproto-base-REVOCATION §3). Only a role-1 member's bump takes.
  bumpEpoch (epoch) { return this.sb.bumpEpoch(b4a.toString(encodeReceipt(epoch), 'hex')) }

  // The current minimum attestation epoch (0 = no restriction).
  async minEpoch () { const h = await this.sb.get(RECEIPT_KEY); return h ? receiptEpoch(b4a.from(h, 'hex')) : 0 }

  // DETERMINISTIC continuation (the atproto-base merge): rev is a pure function of the CURRENT head
  // — which sign() has already re-anchored to the network-latest #commit via the forward-only gate —
  // so two co-owners continuing the same chain over the same finalized set produce byte-identical
  // commits instead of diverging on wall-clock. Genesis (no head yet) still mints a time-plausible
  // TID; an injected clock (tests) still wins for reproducibility.
  _nextRev () {
    if (this._clock) return tidNow(0, this._clock)
    if (this.head && this.head.rev) return nextRev(this.head.rev)
    return tidNow()
  }

  // Materialize the current linearized view into the NEXT canonical commit — only if we hold the
  // lease (or force, for a bootstrap/test). Continue-from-head: prev = last commit CID, rev
  // monotonic. Returns the new head, or null if we don't hold the lease or the view is unchanged.
  async sign ({ force = false } = {}) {
    // Lazy restore FIRST (before the election gate) so the currency-aware election knows whether WE are
    // caught up: re-seed head + the diff baseline from the shared firehose so we CONTINUE the chain
    // incrementally instead of re-authoring the full record set (which breaks relay/AppView MST continuity).
    if (!this.head) await this.restore()
    // NETWORK HEAD (highest-rev __commit__ frame) — computed ONCE, used by BOTH the signer election and the
    // forward-only gate below. Non-blocking (listNow).
    let frames = null
    let net = null
    if (this.firehose) {
      frames = Object.values(await this.sb.listNow(FIREHOSE_PREFIX)).filter((f) => f && f.rev)
      for (const f of frames) if (!net || f.rev > net.rev) net = f
    }
    // Feed our current currency into the presence election + announce it to peers (setSignerHead).
    if (this.sb.setSignerHead) this.sb.setSignerHead(this.head ? this.head.rev : null)
    // S1 election, CURRENCY-AWARE: gate on the StateBase's PRESENCE election (replaces the old __lease__
    // ts-heartbeat), but exclude a co-owner BEHIND the network head (netHead=net.rev) — else the lowest-key
    // -but-behind holder is gate-blocked below while the caught-up peer defers → the chain FREEZES (the
    // stortron aftermath). A behind self returns here so the caught-up peer signs. A substrate without
    // holdsSigner (unit mocks / a single-writer repo) defaults to signing. See signer-presence.js.
    if (!force && this.sb.holdsSigner && !this.sb.holdsSigner(undefined, net ? net.rev : null)) return null
    // NON-BLOCKING read (Phase-2 #6, extended to the WRITE-materialization path): sign() must not
    // await a full base.update() drain — that can hang indefinitely on an un-converged replica and
    // FREEZE posting (the liveness reads got getNow/listNow; this path was the last blocking one). The
    // autoUpdate snapshot reflects the linearized tip incl. our own admitted writes; a just-arrived
    // write not yet in the snapshot is simply materialized on the next sign trigger (eventual).
    const records = await this.repo.listRecords(null, { now: true })
    if (!this.head && records.length === 0) return null // fresh repo, nothing to sign yet (was implicit under the lease gate)
    // ANTI-WIPE GUARD (Step 2a migration safety). A previously-signed repo (head != null) whose record
    // set reads EMPTY, while the underlying overlay store still holds record FILES, is the files-only →
    // pointer migration reading a not-yet-backfilled pointer set — NOT a genuine "all records deleted".
    // Materializing it would advance head to an empty MST root and emit a delete-every-record commit to
    // the relay (the wj62 wipe). Skip until migratePointers() populates the pointers; a genuinely empty
    // repo has no record files either, so this never blocks a legitimate empty state. `force` (bootstrap/
    // tests) bypasses. See docs/SYNTHESIS-storage-consensus-append-2026-07-19.md (Step 2a wipe hazard).
    if (!force && this.head && records.length === 0) {
      if (this._recordStore) {
        const files = await this._recordStore.records()
        if (files.length > 0) {
          console.error(JSON.stringify({ msg: 'sign: anti-wipe guard — pointer set empty but record files present; skipping until 2a backfill', did: this.did, files: files.length }))
          return null
        }
      }
      // SECOND ARM — INLINE entries. The files check above is BLIND to a legacy repo being flipped to the
      // pointer substrate: its records sit INLINE in the statebase with no files at all, so the record set
      // reads empty AND files.length is 0, and the guard would wave through a delete-every-record commit.
      // That is e2jev's exact state (hyper-social#16 P1). The boot-time inline migration (step 2a-0) is
      // what repairs it; this is the fail-closed backstop for when that has not run or did not finish —
      // an empty read with un-migrated records still in the log is never a genuine "all records deleted".
      const raw = await this._listNow('').catch(() => ({}))
      let inline = 0
      for (const [k, v] of Object.entries(raw)) {
        const i = k.indexOf('/')
        if (i <= 0 || k.startsWith('__')) continue // reserved/control key — never a record
        if (isTombstone(v)) continue // a real deletion, which this guard must not block
        if (v && typeof v === 'object' && !v.$oid) inline++
      }
      if (inline > 0) {
        console.error(JSON.stringify({ msg: 'sign: anti-wipe guard — pointer set empty but INLINE records present in the log; skipping until the 2a-0 inline migration converts them', did: this.did, inline }))
        return null
      }
    }
    // ── FORWARD-ONLY SIGN GATE (anti-re-fork) ──────────────────────────────────────────────────────
    // Re-anchor to the NETWORK-LATEST signed commit before continuing the chain, and never sign while
    // BEHIND it. A stale/rejoined signer (lowest-key election winner with a lagging view) must not cause
    // either regression that produced the stortron/tabertron split-brain:
    //   (1) REV regression — continuing from our own stale in-memory head (or restore()'s last-by-SEQ,
    //       which a fork can order behind by rev) publishes a rev ≤ one already served. Fix: adopt the
    //       HIGHEST-REV __commit__ frame as head; _nextRev() is monotonic so the next rev exceeds it.
    //   (2) CONTENT regression — signing our current (partially-replicated) view forward from that head
    //       would DROP records the net head already served (a delete-those-records commit). Fix: replay
    //       the log's ops up to net head for its record key set; if our view is missing ANY, SKIP this
    //       sign — a later tick (after more replication) catches up. A superset (our new records ∪ net's)
    //       is fine and signs forward. This is keet's "a behind peer silently catches up", made safe for
    //       our external (relay) projection. Non-blocking (listNow); `force` (bootstrap/reconcile/tests
    //       that own head deliberately) bypasses, matching the anti-wipe guard convention above.
    if (!force && this.firehose && net) { // frames/net computed once at the top (shared with the election)
      if (!this.head || net.rev > this.head.rev) {
        // (1) adopt the network-latest head so we continue FORWARD from it, never from a stale head.
        const signedCommit = dagCbor.decode(b4a.from(net.commit, 'hex'))
        this.head = { rev: net.rev, commitCid: CID.parse(net.commitCid), dataCid: signedCommit.data, signedCommit }
        this._lastRecords = records
        if (this.sb.setSignerHead) this.sb.setSignerHead(this.head.rev) // re-anchored → update our currency
      }
      // (2) net head's record key set = replay every #commit op up to net, in rev order. Keyed by the
      // rev that last CREATED each path, so the tombstone-epoch check below can tell a legacy
      // hard-delete (pre-epoch) from a pointer that simply has not replicated to us (post-epoch).
      const netKeys = new Map() // path -> rev of its most recent create/update frame
      for (const f of frames.filter((f) => f.rev <= net.rev).sort((a, b) => (a.rev < b.rev ? -1 : 1))) {
        for (const op of (f.ops || [])) { if (op.action === 'delete') netKeys.delete(op.path); else netKeys.set(op.path, f.rev) }
      }
      const curKeys = new Set(records.map((r) => r.collection + '/' + r.rkey))
      // A netKey missing from our resolved view is one of two very different states, and the gate must NOT
      // conflate them (doing so is the DELETE-THE-TIP WEDGE — see test/delete-tip-wedge.repro):
      //   - LEGITIMATE DELETE: the record's POINTER was tombstoned (del-entry converged into the shared
      //     autobase) → the record is genuinely gone → sign the delete forward. Dropping it is the intended
      //     mutation, not a content regression. (Without this, a sole writer that deletes its most-recent
      //     record can NEVER sign the delete — the create frame keeps the key in netKeys forever.)
      //   - BEHIND (content regression risk): the POINTER is still linearized but its bytes aren't fetched
      //     into the view yet → we're lagging replication → SKIP, else we'd tell the relay to delete a
      //     record that is actually live. The raw pointer set (this.sb, pre-byte-resolution) distinguishes
      //     them: pointer ABSENT → deleted; pointer PRESENT → behind.
      // Absence is AMBIGUOUS in a replicated log, so it is no longer treated as evidence of deletion:
      // a TOMBSTONE ({$deleted:true}, written by RepoBase.deleteRecord) is the positive signal. Three
      // states, and only the first may be signed forward:
      //   tombstone present  -> genuinely deleted           -> sign the delete forward
      //   live pointer, unresolved (bytes unfetched)        -> behind -> SKIP
      //   nothing at all (the pointer itself hasn't arrived) -> behind -> SKIP  <-- was misread as a
      //     delete, which let a lagging co-owner publish a delete for a record that is actually live.
      // LEGACY: records deleted before tombstones existed left no marker, so a path whose create frame
      // predates __tombstone_epoch__ keeps the old "absent == deleted" reading — otherwise those would
      // wedge the chain forever (the delete-tip wedge). With no epoch set, every path is legacy and
      // behaviour is byte-for-byte what it was; installing the epoch switches on the fail-safe.
      const rawMap = await this._listNow('')
      const rawKeys = new Set(); const tombKeys = new Set()
      for (const rk of Object.keys(rawMap)) {
        if (rk.indexOf('/') <= 0 || rk.startsWith('__')) continue
        if (isTombstone(rawMap[rk])) tombKeys.add(rk); else rawKeys.add(rk)
      }
      const epoch = await this._getNow(TOMBSTONE_EPOCH).catch(() => null)
      for (const [k, createdAt] of netKeys) {
        if (curKeys.has(k)) continue
        if (tombKeys.has(k)) continue // explicit tombstone → legitimate delete, sign it forward
        if (!rawKeys.has(k) && !(epoch && epoch.rev && createdAt >= epoch.rev)) continue // legacy hard-delete
        console.error(JSON.stringify({ msg: 'sign: forward-only gate — view behind network head, skipping until replicated', did: this.did, missing: k, reason: rawKeys.has(k) ? 'pointer present, bytes unreplicated' : 'pointer not replicated', netRev: net.rev, have: curKeys.size, need: netKeys.size }))
        return null
      }
    }
    const rev = this._nextRev()
    const prev = this.head ? this.head.commitCid : null
    const out = materialize(records, { did: this.did, rev, prev, privateKey: this.privateKey })
    if (this.head && out.dataCid.equals(this.head.dataCid)) return null // no new intents
    // persist the #commit into the shared firehose log (option a) BEFORE advancing head, so every
    // device + the membrane sees each signed commit. seq = position in the rev-ordered log (single
    // writer = the lease-holder, so no seq race). The diff is _lastRecords -> records.
    if (this.firehose) {
      const since = this.head ? this.head.rev : null
      const write = buildCommitWrite(this._lastRecords, records, { did: this.did, rev, prev, since, privateKey: this.privateKey })
      // Only append a #commit frame when the diff is non-empty. A 0-op frame can only arise from the
      // rare restart-with-unsigned-pending-write edge (baseline == current yet head.dataCid differs);
      // emitting it would be a malformed commit. head still advances below so we don't re-trigger.
      if (write.ops.length > 0) {
        // listNow (non-blocking): __commit__ is single-writer (the lease/signer holder), so the
        // autoUpdate snapshot already reflects THIS signer's own firehose entries — the seq count is
        // accurate without a blocking base.update() drain. Matches the non-blocking listRecords above.
        const existing = await this.sb.listNow(FIREHOSE_PREFIX)
        await this.sb.set(FIREHOSE_PREFIX + rev, serializeEntry(write, Object.keys(existing).length + 1))
      }
    }
    this._lastRecords = records
    this.head = { rev, commitCid: out.commitCid, dataCid: out.dataCid, signedCommit: out.signedCommit, recordBlocks: out.recordBlocks }
    if (this.sb.setSignerHead) this.sb.setSignerHead(this.head.rev) // announce our advanced currency to peers
    return this.head
  }

  // Read the firehose #commit log (seq-ordered) from the shared state — the sequence the membrane
  // relays as subscribeRepos. Any device (or the membrane) reads the same entries via replication.
  async firehoseLog () {
    const map = await this.sb.list(FIREHOSE_PREFIX)
    return Object.values(map).sort((a, b) => a.seq - b.seq)
  }

  // Re-seed head + the diff baseline from the shared __commit__ log after a (re)start. Without this,
  // a reboot resets `head`/`_lastRecords` and the next sign re-authors the FULL record set as creates
  // (the ops=[9,9,..,12] firehose bug) — breaking relay/AppView MST continuity. The head is the LAST
  // signed #commit (decoded from the log, so its exact commitCid/dataCid are preserved for the next
  // prev-link); the baseline is the current (quiescent) record set — the sign loop runs every couple
  // seconds so at any restart it equals the record set that head represents. Returns the restored head,
  // or null if nothing has been signed yet (truly fresh — the caller then authors the first commit).
  async restore () {
    const log = await this.firehoseLog()
    if (!log.length) return null
    const last = log[log.length - 1]
    const signedCommit = dagCbor.decode(b4a.from(last.commit, 'hex'))
    this.head = { rev: last.rev, commitCid: CID.parse(last.commitCid), dataCid: signedCommit.data, signedCommit }
    // Re-seed the diff baseline from the HEAD's firehose record set, NOT the current pointer view. A record
    // deleted-but-not-yet-signed (the DELETE-THE-TIP WEDGE) is ABSENT from the view yet MUST remain in the
    // baseline so the next sign emits the proper delete op — and its bytes are already gone from the overlay
    // store, so the firehose #commit blocks are the only surviving copy. Falls back to the view if any
    // referenced block is missing (partial replication); the forward-only gate still guards a real regression.
    this._lastRecords = (await this._recordsFromFirehose(log)) || await this.repo.listRecords()
    return this.head
  }

  // Replay the firehose (#commit ops in rev order, resolving each create/update to its record block) to
  // reconstruct the record set the HEAD commits to — the surviving copy of a record whose overlay bytes
  // were deleted. Returns [{collection, rkey, record}], or null if a referenced block is missing (the
  // caller then degrades to the pointer view).
  async _recordsFromFirehose (log) {
    const byKey = new Map()
    for (const entry of log.slice().sort((a, b) => (a.rev < b.rev ? -1 : 1))) {
      const blocks = new Map((entry.blocks || []).map((b) => [b.cid, b.bytes]))
      for (const op of (entry.ops || [])) {
        if (op.action === 'delete') { byKey.delete(op.path); continue }
        const hex = op.cid ? blocks.get(op.cid) : null
        if (!hex) return null // referenced record block absent — cannot faithfully reconstruct
        byKey.set(op.path, dagCbor.decode(b4a.from(hex, 'hex')))
      }
    }
    const out = []
    for (const [path, record] of byKey) { const i = path.indexOf('/'); out.push({ collection: path.slice(0, i), rkey: path.slice(i + 1), record }) }
    return out
  }

  // ── adopt an existing DID's repo into the swarm (continuity migration) ──
  // Import an existing single-tenant repo's records + head so the swarm CONTINUES its commit chain
  // (next sign: prev = the adopted commit, prevData = the adopted data root, rev monotonic) rather
  // than re-authoring it. Hard-guards continuity: the imported records MUST reproduce the adopted
  // commit's data root (else the import is incomplete and would fork/re-author — the migration wall,
  // atproto-pds-ref §2/§7). Only meaningful on a writable (creator) device. records: [{collection,
  // rkey, record}]; head: { rev, commitCid, dataCid, signedCommit? }.
  async adopt (records, head) {
    if (!head || !head.commitCid || !head.dataCid || !head.rev) throw new Error('adopt: head { rev, commitCid, dataCid } required')
    for (const r of records) await this.repo.putRecord(r.collection, r.rkey, r.record)
    const cur = await this.repo.listRecords()
    const mv = materialize(cur, { did: this.did, rev: head.rev, prev: null, privateKey: this.privateKey })
    if (!mv.dataCid.equals(head.dataCid)) throw new Error('adopt: imported records do not reproduce the adopted data root — import incomplete (would re-author wj62)')
    this._lastRecords = cur
    this.head = { rev: head.rev, commitCid: head.commitCid, dataCid: head.dataCid, signedCommit: head.signedCommit || null }
    return this.head
  }

  // ── emit the ADOPTED head as a baseline #commit frame (adopt frontability) ──
  // adopt() sets head + records but writes NO __commit__ frame, and the adopted repo's data root is
  // unchanged so the next sign() is a no-op (returns null on out.dataCid == head.dataCid). Result: an
  // adopted account with no subsequent write has an EMPTY firehose log, so serveMembrane.sync() early-
  // returns (log.length <= seq.length) and projects NEITHER the repo NOR the firehose core → the keyless
  // bridge can't front it (getRepo/getLatestCommit both fail) until the first record-changing post emits
  // a frame. This closes that gap: write ONE baseline frame for the CURRENT head so the membrane projects
  // immediately. buildCommitWrite over ([] -> current records) with the adopted head's rev+prev reproduces
  // the adopted commit byte-for-byte (RFC6979-deterministic), so the served commitCid IS the canonical
  // head. Idempotent (no-op if the log already has frames). Writable creator only. Returns the head or null.
  async emitBaseline () {
    if (!this.firehose || !this.head || !this.head.signedCommit) return null
    const existing = await this.sb.listNow(FIREHOSE_PREFIX)
    if (Object.keys(existing).length > 0) return null // already have frames — no baseline needed
    const prev = this.head.signedCommit.prev || null
    const write = buildCommitWrite([], this._lastRecords, { did: this.did, rev: this.head.rev, prev, since: null, privateKey: this.privateKey })
    if (!write.commitCid.equals(this.head.commitCid)) throw new Error('emitBaseline: rebuilt commit CID != adopted head — refusing to emit an inconsistent baseline frame')
    await this.sb.set(FIREHOSE_PREFIX + this.head.rev, serializeEntry(write, 1))
    return this.head
  }

  // ── PART D: reconcile a divergent line onto an authoritative signed CAR (fork recovery) ──
  // An autobase-level fork of a shared DID (two divergent authored lines, SAME base.key) CANNOT be
  // merged in place — the oplog is append-only and a fresh NAMESPACE re-derives the same primaryKey
  // writer (pear-git #4). The recovery is to re-adopt the NETWORK-AUTHORITATIVE signed repo (its CAR)
  // into a FRESH line, then UNION any record that only landed on the LOSING line so nothing is lost.
  // Run this on a device backed by a FRESH corestore (own primaryKey → clean writer). The caller passes
  // the parsed CAR (`{records, head}` from readAdoptRepo) + the loser's record set. Steps: adopt the CAR
  // (the anti-re-author guard proves the records reproduce its data root), union in each loser-only
  // record (by collection/rkey — additive ONLY, never a delete), then sign FORWARD (rev > CAR rev,
  // prev = CAR commit) so the relay accepts a monotonic continuation. Returns { head, adopted, unioned,
  // total }. Deletion story: NOTHING is dropped — a record on the losing line the winner lacks is kept.
  async reconcileFromCar ({ records, head } = {}, loserRecords = []) {
    if (!Array.isArray(records) || !head) throw new Error('reconcileFromCar: { records, head } (from readAdoptRepo) required')
    await this.adopt(records, head) // head = CAR head, _lastRecords = CAR records; guards against re-author
    const have = new Set(records.map((r) => r.collection + '/' + r.rkey))
    let unioned = 0
    for (const r of loserRecords) {
      if (!r || !r.collection || !r.rkey) continue
      const key = r.collection + '/' + r.rkey
      if (!have.has(key)) { await this.putRecord(r.collection, r.rkey, r.record); unioned++ } // loser-only → KEEP it
    }
    // Sign FORWARD only when we actually added records; else the adopted CAR head IS the reconciled
    // state (loser was a strict subset) and re-signing an identical set would be a no-op.
    const newHead = unioned > 0 ? await this.sign({ force: true }) : this.head
    return { head: newHead, adopted: records.length, unioned, total: records.length + unioned }
  }

  // ── export the current signed repo as an atproto CAR (com.atproto.sync.getRepo shape) ──
  // The input to reconcileFromCar on a PEER (fork recovery: fetch the authoritative node's CAR → adopt
  // it into a fresh line) and to any getRepo consumer. Rebuilds the MST from the current record set
  // (DAG-CBOR is canonical, so re-encoding is byte-exact) and reuses read-view's getRepoFromCommit,
  // which ASSERTS the rebuilt MST root == the signed head's data root — refusing to serve a repo that
  // doesn't match its own signature. Uses the head's EXISTING signature; never re-signs. Returns
  // { carBytes, commitCid, dataCid, rev, recordCount }.
  async exportCar () {
    if (!this.head) await this.restore()
    if (!this.head || !this.head.signedCommit) throw new Error('exportCar: no signed head to export (nothing signed yet)')
    const recs = await this.repo.listRecords()
    // Shim the record set into the { records()->[{key,bytes,record}] } shape getRepoFromCommit consumes.
    const shim = { records: async () => recs.map((r) => ({ key: r.collection + '/' + r.rkey, bytes: dagCbor.encode(r.record), record: r.record })) }
    const { carBytes, commitCid, dataCid } = await getRepoFromCommit(shim, this.head.signedCommit)
    return { carBytes, commitCid: commitCid.toString(), dataCid: dataCid.toString(), rev: this.head.rev, recordCount: recs.length }
  }

  // ── ONE-TIME MIGRATION REPAIR ONLY — not routine recovery (atproto-base) ──
  // ⚠ This REWRITES the firehose log, which is NOT what atproto expects: atproto firehoses are
  // APPEND-ONLY with forward-only consumer cursors, and the idiomatic recovery from bad/discontinuous
  // frames is to emit a #sync re-baseline → the relay/AppView resync via getRepo (the desync→resync
  // path; see atproto specs/sync + docs/firehose-recovery.md). The bridge already does this
  // (atproto-bridge control.js `emit-sync` + `set-seq-base`), and it is what heals a relay in
  // practice. Reach for THAT, not this. resetFirehose exists solely to repair a log that accumulated
  // MALFORMED frames from before the restore/dedup fixes (full-set re-authors whose prevData doesn't
  // chain) — a one-shot historical cleanup during the wj62 migration. With restore()+the bridge dedup
  // fix in place, new frames stay well-formed, so this should never be needed again.
  //
  // Mechanics: clear the __commit__ log, re-seed head + baseline from a known-good migration head (the
  // single-tenant adoptCar — the last commit the relay validly holds), then a forced sign diffs the
  // CURRENT record set against it → one incremental #commit continuing the chain. Writable only;
  // marker-guarded (__firehose_reset__) so it runs exactly once. Returns the clean head.
  async resetFirehose (baselineRecords, baselineHead) {
    if (!baselineHead || !baselineHead.commitCid || !baselineHead.dataCid || !baselineHead.rev) throw new Error('resetFirehose: baselineHead { rev, commitCid, dataCid } required')
    const log = await this.sb.list(FIREHOSE_PREFIX)
    for (const key of Object.keys(log)) await this.sb.del(key)
    this.head = { rev: baselineHead.rev, commitCid: baselineHead.commitCid, dataCid: baselineHead.dataCid, signedCommit: baselineHead.signedCommit || null }
    this._lastRecords = baselineRecords
    return this.sign({ force: true })
  }

  // ── control surface: submit a write, observe convergence ──
  // applyWrite mirrors the single-tenant apply-write (lib/peer.js _attachRpc): a client/app hands a
  // repo op to ANY device, which appends it to the shared intent-log; whichever device holds the
  // lease materializes it into the signed chain on its next pass. Returns the post-write record
  // count so a caller can confirm the intent landed on THIS device (it replicates to the others).
  async applyWrite ({ action = 'create', collection, rkey, record } = {}) {
    if (action === 'delete') await this.repo.deleteRecord(collection, rkey)
    else await this.repo.putRecord(collection, rkey, record)
    // recordCount from RAW pointer keys (StateBase), NOT this.repo.listRecords(): the latter RESOLVES every
    // record's bytes via ensureLocal (an overlay fetch-by-oid that HANGS when a co-owner lacks the bytes
    // locally) — which wedged apply-write for 20s ("UDS call timed out"). The write is already durable
    // (putRecord appended the pointer); the count is only an ack, so count pointers without resolving bytes.
    // this.sb.list (StateBaseV3, drained) gives the RAW pointer set — no PointerSubstrate byte resolution
    // (the original went through this.repo.listRecords, resolving bytes). base.update itself was never the
    // hang (get-state's {now} read skips it and still hung on ensureLocal); dropping the resolution is the fix.
    let recordCount = 0
    try { for (const k of Object.keys(await this.sb.list(''))) if (k.indexOf('/') > 0 && !k.startsWith('__')) recordCount++ } catch {}
    return { ok: true, action, collection, rkey, recordCount }
  }

  // com.atproto.server.getServiceAuth — mint an ES256K inter-service JWT signed by the shared
  // #atproto key (the SAME key that signs the repo's commits), so the KEYLESS membrane can proxy
  // user-scoped AppView reads (getTimeline/listNotifications/getProfiles) authenticated AS this
  // account. { iss:did, aud:<appview did>, exp, lxm:<method> }. signAssertion IS the atproto
  // service-auth shape (atproto-identity/lib/auth.js). exp is short (default 10min, ≤1h w/ lxm).
  getServiceAuth ({ aud, lxm, exp } = {}) {
    if (!aud) throw new Error('getServiceAuth: aud required')
    const now = Math.floor(Date.now() / 1000)
    const e = exp || (now + 600)
    const payload = { iss: this.did, aud, exp: e }
    if (lxm) payload.lxm = lxm
    return { token: signAssertion(payload, this.privateKey), exp: e }
  }

  // delegate — authorize a browser SUB-KEY to act as this DID for web sign-in: sign an ES256K
  // assertion { iss:did, sub:<subKey hex>, exp } with the shared #atproto key. This is the atproto
  // analog of adding a device — the DID's own key vouches for the sub-key, and a keyless verifier
  // (favela web-auth) checks it against the DID's PLC-published key. The browser then signs login
  // challenges with the sub-key. subKey = a 33-byte compressed secp256k1 pubkey (hex).
  //
  // PERSISTENT + REVOCABLE (Option 3): ttlSec defaults to effectively-permanent (10y) — the exp is a
  // backstop, NOT the control. A delegated browser stays valid until EXPLICITLY revoked (revokeDevice),
  // matching pgv3's persistent-until-revoked model. We ALSO record the sub-key in the device registry
  // (addDevice) so it can be listed + revoked; revocation is enforced by the verifier (isDeviceRevoked),
  // not by expiry. Privileged: gated by serveDevice's canWrite.
  async delegate ({ subKey, ttlSec = 10 * 365 * 24 * 3600, label = null } = {}) {
    if (!subKey || !/^[0-9a-fA-F]{66}$/.test(String(subKey))) throw new Error('delegate: subKey (33-byte compressed secp256k1 pubkey hex) required')
    const sub = String(subKey).toLowerCase()
    const now = Math.floor(Date.now() / 1000)
    const exp = now + Number(ttlSec)
    const delegation = signAssertion({ iss: this.did, sub, iat: now, exp }, this.privateKey)
    // Record in the persistent registry (reserved StateBase key; never public). FIRE-AND-FORGET: addDevice
    // does sb.set → _ensureWritable → base.update, which can BLOCK on an un-converged plain writer. The
    // delegation is cryptographically valid regardless, so we must NOT block (and thus hang pairing) on the
    // write — record in the background if/when the base is writable; listing/revocation pick it up then.
    this.addDevice(sub, { label }).catch((e) => console.error(JSON.stringify({ msg: 'addDevice on delegate failed (delegation still valid)', error: e.message })))
    return { did: this.did, subKey: sub, delegation, exp }
  }

  // state — the observable snapshot the read-RPC returns: who we are, whether we're the active
  // signer + who holds the lease, the last signed head, and the current linearized record set
  // (keys only). This is how a peer/test verifies convergence: submit to device A, read state on
  // device B, compare the record sets.
  async state () {
    // NON-BLOCKING (Phase-2 #6): get-state must NEVER hang — it is the liveness probe favela-web +
    // the CLI use. Both reads below avoid base.update(): listRecords({now}) reads the autoUpdate
    // snapshot, and lease.current() is snapshot-based. On the live tabertron (writable=false,
    // un-converged) the blocking versions hung this call for >8s.
    // RAW pointer scan — never RESOLVE bytes here. This is the same trap applyWrite escaped (see its
    // note below): under PointerSubstrate, repo.listRecords() calls store.ensureLocal() per record, an
    // overlay fetch-by-oid that BLOCKS when this node lacks the bytes locally. That made get-state —
    // the liveness probe favela-web and the CLI depend on — time out on wj62 (~129 records) while
    // 3-record loser-club answered in 35ms, with members-diag responding in 3ms on both. collection and
    // rkey come straight off the pointer key, so the returned shape is unchanged.
    const records = []
    for (const [k, v] of Object.entries(await this._listNow(''))) {
      const i = k.indexOf('/')
      if (i <= 0 || k.startsWith('__')) continue
      if (isTombstone(v)) continue // deleted records are absent from state, as before
      records.push({ collection: k.slice(0, i), rkey: k.slice(i + 1) })
    }
    const cur = await this.lease.current()
    return {
      did: this.did,
      self: this.lease.self,
      // ⚠ LEGACY. The __lease__ ts-heartbeat was REPLACED by the StateBase presence election (see the
      // gate in sign(), ~line 358). These three are reported for continuity only and do NOT indicate
      // whether this node signs — holdsLease is False on healthy signing nodes. Read holdsSigner.
      holdsLease: await this.lease.holds(),
      leaseHolder: cur ? cur.holder : null,
      leaseEpoch: cur ? cur.epoch : null,
      // The field that ACTUALLY gates signing: the presence election. Null when the substrate has no
      // presence (unit mocks / single-writer), where sign() defaults to signing.
      holdsSigner: (() => { try { return this.sb.holdsSigner ? !!this.sb.holdsSigner() : null } catch { return null } })(),
      indexers: (this.sb.base && this.sb.base.linearizer && this.sb.base.linearizer.indexers) ? this.sb.base.linearizer.indexers.length : null,
      writable: !!(this.sb.base && this.sb.base.writable),
      head: this.head ? { rev: this.head.rev, commitCid: this.head.commitCid.toString() } : null,
      recordCount: records.length,
      records: records.map((r) => ({ collection: r.collection, rkey: r.rkey }))
    }
  }

  // Read-only membership diagnostic (NON-BLOCKING — getNow + flags only, no listRecords/base.update).
  // Answers WHY writer admission fails: whether __members__/__devices__ are actually in the linearized
  // view, plus the creator's projection state (_membersProjected / _roster / writable / base lengths).
  async membersDiag () {
    const sb = this.sb
    let members = null; let devices = null
    try { members = await sb.getNow('__members__') } catch {}
    try { devices = await sb.getNow('__devices__') } catch {}
    const roster = Array.isArray(sb._roster)
      ? sb._roster.map((r) => ({ key: String((r && (r.key || r.devicePubkey || r.identity || r.memberId)) || '').slice(0, 12), role: r && r.role }))
      : (sb._roster || null)
    return {
      did: this.did,
      writable: !!(sb.base && sb.base.writable),
      // `_isCreator` (atproto-room 0.2.16), NOT `_amCreator`. The latter is a prototype METHOD, so
      // `!!sb._amCreator` was `!!<function>` — this field reported `true` for every node, creator or not,
      // and could never express the negative case. It was cited as evidence of a role flip in a live
      // incident. `_isCreator` is the decision `_open` actually made.
      amCreator: sb._isCreator === undefined ? null : !!sb._isCreator,
      forcedRole: sb._forceCreator ? 'forced-creator' : (sb._forceNonCreator ? 'forced-non-creator' : null),
      baseLength: sb.base ? sb.base.length : null,
      indexedLength: sb.base ? sb.base.indexedLength : null,
      // PER-WRITER BREAKDOWN. baseLength/indexedLength are AGGREGATES, and an aggregate that looks wrong
      // cannot say WHO made it wrong. Re-joining loser-club left stortron frozen at indexed 34681 /
      // base 34727 — a 46-block gap that was unanswerable from outside the process, because no surface
      // said which writer those blocks came from; it could not be told apart from ordinary replication
      // lag. The same shape at 3728 blocks turned out to be fork residue from an earlier attempt.
      //
      // `seen` is how much of a writer's core the linearized view has CONSUMED; `authored` is how much
      // that writer has actually written. pending = authored-but-not-in-the-view, which is the number
      // that explains a gap. A removed writer still carrying pending blocks, or a writer present on one
      // node and absent on its peer, is the signature worth looking for.
      writers: (sb.base && sb.base.activeWriters)
        ? [...sb.base.activeWriters].map((w) => {
            const key = (w.core && w.core.key) ? b4a.toString(w.core.key, 'hex') : null
            const localKey = (sb.base.local && sb.base.local.key) ? b4a.toString(sb.base.local.key, 'hex') : null
            return {
              key: key ? key.slice(0, 12) : null,
              authored: w.core ? w.core.length : null,
              seen: w.length,
              pending: w.core ? Math.max(0, w.core.length - w.length) : null,
              indexer: !!w.isActiveIndexer,
              removed: !!w.isRemoved,
              local: !!(key && localKey && key === localKey)
            }
          })
        : null,
      membersProjected: !!sb._membersProjected,
      rosterLen: Array.isArray(sb._roster) ? sb._roster.length : (sb._roster ? -1 : 0),
      roster,
      membersInView: members || null,
      devicesInView: devices || null
    }
  }

  // Force a re-projection of __members__/__devices__ (idempotent, re-appends the retained roster). Clears
  // the _membersProjected latch so the creator re-projects into the view even if a prior projection was
  // re-linearized away (the false-positive that leaves admission stuck at "no __members__ in view"). A
  // no-op off the writable creator (projectMembers returns false when not writable).
  async reprojectMembers () {
    const sb = this.sb
    sb._membersProjected = false
    let detail
    try { detail = await sb.projectMembers(sb._roster) } catch (e) { detail = { error: e.message } }
    let members = null
    try { members = await sb.getNow('__members__') } catch {}
    return { reprojected: detail === true, detail, writable: !!(sb.base && sb.base.writable), membersInView: members || null }
  }

  // ── private preferences (bsky-login onboarding: birthdate etc.) ──
  // Stored in the shared statebase under a reserved key — NEVER leaks to the public repo/firehose
  // (RepoBase skips "__"-prefixed keys). Any writable device writes; the autobase linearizes it. The
  // atproto getPreferences/putPreferences shape is { preferences: [...] }.
  async getPreferences () { const p = await this.sb.get(PREFS_KEY); return { preferences: (p && p.preferences) || [] } }
  async putPreferences ({ preferences } = {}) { await this.sb.set(PREFS_KEY, { preferences: preferences || [] }); return {} }

  // ── device registry (Option 3) — delegated browser sub-keys as reserved StateBase entries.
  // Reserved (__-prefixed) → NEVER in the public repo/firehose (RepoBase skips them). Replicated to
  // every DID device, so the linearized view is authoritative + revocation propagates. This is the
  // atproto-keyless analog of hyper-identity's IdentityRegistry device records + `revoked:` tombstone,
  // but it rides the StateBase we already run (no second autobase). Enforced by the verifier via the
  // membrane RPCs (serve-device: list-devices / revoke-device / is-device-revoked).
  async addDevice (subKey, { label = null } = {}) {
    const sk = String(subKey).toLowerCase()
    if (!/^[0-9a-f]{66}$/.test(sk)) throw new Error('addDevice: subKey (33-byte compressed secp256k1 hex) required')
    const existing = await this.sb.get(DEVICE_PREFIX + sk).catch(() => null) // preserve addedAt on re-delegate
    await this.sb.set(DEVICE_PREFIX + sk, { subKey: sk, label: label || (existing && existing.label) || null, addedAt: (existing && existing.addedAt) || Date.now() })
    return { subKey: sk }
  }

  async revokeDevice (subKey, { reason = null } = {}) {
    const sk = String(subKey).toLowerCase()
    if (!/^[0-9a-f]{66}$/.test(sk)) throw new Error('revokeDevice: subKey (33-byte compressed secp256k1 hex) required')
    await this.sb.set(DEVICE_REVOKED_PREFIX + sk, { subKey: sk, revokedAt: Date.now(), reason }) // tombstone (soft, reversible)
    return { subKey: sk, revoked: true }
  }

  async restoreDevice (subKey) {
    const sk = String(subKey).toLowerCase()
    await this.sb.del(DEVICE_REVOKED_PREFIX + sk) // remove the tombstone
    return { subKey: sk, revoked: false }
  }

  async isDeviceRevoked (subKey) {
    const sk = String(subKey).toLowerCase()
    // NON-BLOCKING read (getNow) — a revocation check MUST NOT hang the login flow if base.update() is
    // stalled on an un-converged replica. Reads the current materialized view (autoUpdate HyperDB).
    return !!(await this.sb.getNow(DEVICE_REVOKED_PREFIX + sk).catch(() => null))
  }

  async listDevices () {
    const devs = await this.sb.listNow(DEVICE_PREFIX).catch(() => ({}))
    const revoked = await this.sb.listNow(DEVICE_REVOKED_PREFIX).catch(() => ({}))
    const revById = {}
    for (const r of Object.values(revoked)) if (r && r.subKey) revById[r.subKey] = r
    return Object.values(devs).map((d) => ({
      subKey: d.subKey,
      label: d.label || null,
      addedAt: d.addedAt || null,
      revoked: !!revById[d.subKey],
      revokedAt: revById[d.subKey] ? revById[d.subKey].revokedAt : null
    }))
  }
}
// Persistent Hyperswarm keypair for the peer.
//
// A hyper-proto-peer is a SERVER: the bridge (and any replica) finds it by DID topic and then
// reconnects to it by its Noise/DHT public key. If the peer booted with a RANDOM keypair each
// time (`new Hyperswarm()`), every restart is a brand-new DHT identity — Hyperswarm can't retry
// the peer it knew, so a restarted peer is only rediscovered via the slow topic re-query and its
// fronts go stale in the meantime. A STABLE keypair (persisted across restarts) makes the peer's
// serverKey durable, so reconnection is prompt. (Same pattern + rationale as pear-git's
// TopicConnector; the mesh analogue of the hyper-tps ephemeral-DHT-key bug.)
//
// The swarm identity is deliberately SEPARATE from the atproto signing key (in peer-identity.json)
// — it is only a transport/DHT identity, never signs anything.

import { readFileSync, writeFileSync, mkdirSync } from 'bare-fs'
import { join } from 'bare-path'
import b4a from 'b4a'
import crypto from 'hypercore-crypto'

const KEYPAIR_FILE = 'swarm-keypair.json'

// Load the peer's persistent swarm keypair from <storage>/swarm-keypair.json, or create + persist
// one on first boot. Returns a hypercore-crypto keypair ({ publicKey, secretKey } as Buffers).
// `name` selects WHICH stable identity: the daemon's (default) or a separate one for a client that must
// be allowlistable without impersonating the daemon — running two Hyperswarms on one keypair would put two
// DHT identities behind the same key, so `diag --remote` gets its own file rather than borrowing this one.
export function loadOrCreateSwarmKeyPair (storage, { name = KEYPAIR_FILE } = {}) {
  if (typeof storage !== 'string') throw new Error('loadOrCreateSwarmKeyPair: storage must be a directory path')
  const file = join(storage, name)
  try {
    const saved = JSON.parse(readFileSync(file, 'utf8'))
    return { publicKey: b4a.from(saved.publicKey, 'hex'), secretKey: b4a.from(saved.secretKey, 'hex') }
  } catch {
    const keyPair = crypto.keyPair()
    try { mkdirSync(storage, { recursive: true }) } catch {}
    writeFileSync(file, JSON.stringify({
      publicKey: b4a.toString(keyPair.publicKey, 'hex'),
      secretKey: b4a.toString(keyPair.secretKey, 'hex'),
      createdAt: Date.now()
    }, null, 2), { mode: 0o600 })
    return keyPair
  }
}
const { Pull, Push, HEADERBYTES, KEYBYTES, ABYTES } = require('sodium-secretstream')
const sodium = require('sodium-universal')
const crypto = require('hypercore-crypto')
const { Duplex, Writable, getStreamError } = require('streamx')
const b4a = require('b4a')
const Timeout = require('timeout-refresh')
const unslab = require('unslab')
const Bridge = require('./lib/bridge')
const Handshake = require('./lib/handshake')

const IDHEADERBYTES = HEADERBYTES + 32
const [NS_INITIATOR, NS_RESPONDER, NS_SEND] = crypto.namespace('hyperswarm/secret-stream', 3)
const MAX_ATOMIC_WRITE = 256 * 256 * 256 - 1

module.exports = class NoiseSecretStream extends Duplex {
  constructor(isInitiator, rawStream, opts = {}) {
    super({ mapWritable: toBuffer })

    if (typeof isInitiator !== 'boolean') {
      throw new Error('isInitiator should be a boolean')
    }

    this.noiseStream = this
    this.isInitiator = isInitiator
    this.rawStream = null

    this.publicKey = opts.publicKey || null
    this.remotePublicKey = opts.remotePublicKey || null
    this.handshakeHash = null
    this.connected = false
    this.keepAlive = opts.keepAlive || 0
    this.timeout = 0
    this.enableSend = opts.enableSend !== false

    // pointer for upstream to set data here if they want
    this.userData = null

    let openedDone = null
    this.opened = new Promise((resolve) => {
      openedDone = resolve
    })

    this.rawBytesWritten = 0
    this.rawBytesRead = 0

    // metadata used by 'hyperdht'
    this.relay = null
    this.puncher = null

    // unwrapped raw stream
    this._rawStream = null

    // handshake state
    this._handshake = null
    this._handshakePattern = opts.pattern || null
    this._handshakeDone = null

    // message parsing state
    this._state = 0
    this._len = 0
    this._tmp = 1
    this._message = null

    this._openedDone = openedDone
    this._startDone = null
    this._drainDone = null
    this._outgoingPlain = null
    this._outgoingWrapped = null
    this._utp = null
    this._setup = true
    this._ended = 2
    this._encrypt = null
    this._decrypt = null
    this._timeoutTimer = null
    this._keepAliveTimer = null
    this._sendState = null

    if (opts.autoStart !== false) this.start(rawStream, opts)

    // wiggle it to trigger open immediately (TODO add streamx option for this)
    this.resume()
    this.pause()
  }

  static keyPair(seed) {
    return Handshake.keyPair(seed)
  }

  static id(handshakeHash, isInitiator, id) {
    return streamId(handshakeHash, isInitiator, id)
  }

  setTimeout(ms) {
    if (!ms) ms = 0

    this._clearTimeout()
    this.timeout = ms

    if (!ms || this.rawStream === null) return

    this._timeoutTimer = Timeout.once(ms, destroyTimeout, this)
    this._timeoutTimer.unref()
  }

  setKeepAlive(ms) {
    if (!ms) ms = 0

    this._clearKeepAlive()

    this.keepAlive = ms

    if (!ms || this.rawStream === null) return

    this._keepAliveTimer = Timeout.on(ms, sendKeepAlive, this)
    this._keepAliveTimer.unref()
  }

  sendKeepAlive() {
    const empty = this.alloc(0)
    this.write(empty)
  }

  start(rawStream, opts = {}) {
    if (rawStream) {
      this.rawStream = rawStream
      this._rawStream = rawStream
      if (typeof this.rawStream.setContentSize === 'function') {
        this._utp = rawStream
      }
    } else {
      this.rawStream = new Bridge(this)
      this._rawStream = this.rawStream.reverse
    }

    this.rawStream.on('error', this._onrawerror.bind(this))
    this.rawStream.on('close', this._onrawclose.bind(this))

    this._startHandshake(opts.handshake, opts.keyPair || null)
    this._continueOpen(null)

    if (this.destroying) return

    if (opts.data) this._onrawdata(opts.data)
    if (opts.ended) this._onrawend()

    if (this.keepAlive > 0 && this._keepAliveTimer === null) {
      this.setKeepAlive(this.keepAlive)
    }

    if (this.timeout > 0 && this._timeoutTimer === null) {
      this.setTimeout(this.timeout)
    }
  }

  async flush() {
    if ((await this.opened) === false) return false
    if ((await Writable.drained(this)) === false) return false
    if (this.destroying) return false

    if (this.rawStream !== null && this.rawStream.flush) {
      return await this.rawStream.flush()
    }

    return true
  }

  _continueOpen(err) {
    if (err) this.destroy(err)
    if (this._startDone === null) return
    const done = this._startDone
    this._startDone = null
    this._open(done)
  }

  _onkeypairpromise(p) {
    const self = this
    const cont = this._continueOpen.bind(this)

    p.then(onkeypair, cont)

    function onkeypair(kp) {
      self._onkeypair(kp)
      cont(null)
    }
  }

  _onkeypair(keyPair) {
    const pattern = this._handshakePattern || 'XX'
    const remotePublicKey = this.remotePublicKey

    this._handshake = new Handshake(this.isInitiator, keyPair, remotePublicKey, pattern)
    this.publicKey = this._handshake.keyPair.publicKey
  }

  _startHandshake(handshake, keyPair) {
    if (handshake) {
      const { tx, rx, hash, publicKey, remotePublicKey } = handshake
      this._setupSecretStream(tx, rx, hash, publicKey, remotePublicKey)
      return
    }

    if (!keyPair) keyPair = Handshake.keyPair()

    if (typeof keyPair.then === 'function') {
      this._onkeypairpromise(keyPair)
    } else {
      this._onkeypair(keyPair)
    }
  }

  _onrawerror(err) {
    this.destroy(err)
  }

  _onrawclose() {
    if (this._ended !== 0) this.destroy()
  }

  _onrawdata(data) {
    let offset = 0

    if (this._timeoutTimer !== null) {
      this._timeoutTimer.refresh()
    }

    do {
      switch (this._state) {
        case 0: {
          while (this._tmp !== 0x1000000 && offset < data.byteLength) {
            const v = data[offset++]
            this._len += this._tmp * v
            this._tmp *= 256
          }

          if (this._tmp === 0x1000000) {
            this._tmp = 0
            this._state = 1
            const unprocessed = data.byteLength - offset
            if (unprocessed < this._len && this._utp !== null)
              this._utp.setContentSize(this._len - unprocessed)
          }

          break
        }

        case 1: {
          const missing = this._len - this._tmp
          const end = missing + offset

          if (this._message === null && end <= data.byteLength) {
            this._message = data.subarray(offset, end)
            offset += missing
            this._incoming()
            break
          }

          const unprocessed = data.byteLength - offset

          if (this._message === null) {
            this._message = b4a.allocUnsafe(this._len)
          }

          b4a.copy(data, this._message, this._tmp, offset)
          this._tmp += unprocessed

          if (end <= data.byteLength) {
            offset += missing
            this._incoming()
          } else {
            offset += unprocessed
          }

          break
        }
      }
    } while (offset < data.byteLength && !this.destroying)
  }

  _onrawend() {
    this._ended--
    this.push(null)
  }

  _onrawdrain() {
    const drain = this._drainDone
    if (drain === null) return
    this._drainDone = null
    drain()
  }

  _read(cb) {
    this.rawStream.resume()
    cb(null)
  }

  _incoming() {
    const message = this._message

    this._state = 0
    this._len = 0
    this._tmp = 1
    this._message = null

    if (this._setup === true) {
      if (this._handshake) {
        this._onhandshakert(this._handshake.recv(message))
      } else {
        if (message.byteLength !== IDHEADERBYTES) {
          this.destroy(new Error('Invalid header message received'))
          return
        }

        const remoteId = message.subarray(0, 32)
        const expectedId = streamId(this.handshakeHash, !this.isInitiator)
        const header = message.subarray(32)

        if (!b4a.equals(expectedId, remoteId)) {
          this.destroy(new Error('Invalid header received'))
          return
        }

        this._decrypt.init(header)
        this._setup = false // setup is now done
      }
      return
    }

    if (message.byteLength < ABYTES) {
      this.destroy(new Error('Invalid message received'))
      return
    }

    this.rawBytesRead += message.byteLength

    const plain = message.subarray(1, message.byteLength - ABYTES + 1)

    try {
      this._decrypt.next(message, plain)
    } catch (err) {
      this.destroy(err)
      return
    }

    // If keep alive is selective, eat the empty buffers (ie assume the other side has it enabled also)
    if (plain.byteLength === 0 && this.keepAlive !== 0) return

    if (this.push(plain) === false) {
      this.rawStream.pause()
    }
  }

  _onhandshakert(h) {
    if (this._handshakeDone === null) return

    if (h !== null) {
      if (h.data) this._rawStream.write(h.data)
      if (!h.tx) return
    }

    const done = this._handshakeDone
    const publicKey = this._handshake.keyPair.publicKey

    this._handshakeDone = null
    this._handshake = null

    if (h === null) return done(new Error('Noise handshake failed'))

    this._setupSecretStream(h.tx, h.rx, h.hash, publicKey, h.remotePublicKey)
    this._resolveOpened(true)
    done(null)
  }

  _setupSecretStream(tx, rx, handshakeHash, publicKey, remotePublicKey) {
    const buf = b4a.allocUnsafeSlow(3 + IDHEADERBYTES)
    writeUint24le(IDHEADERBYTES, buf)

    this._encrypt = new Push(unslab(tx.subarray(0, KEYBYTES)), undefined, buf.subarray(3 + 32))
    this._decrypt = new Pull(unslab(rx.subarray(0, KEYBYTES)))

    this.publicKey = publicKey
    this.remotePublicKey = remotePublicKey
    this.handshakeHash = handshakeHash

    const id = buf.subarray(3, 3 + 32)
    streamId(handshakeHash, this.isInitiator, id)

    // initialize secretbox state for unordered messages
    this._setupSecretSend(handshakeHash)

    this.emit('handshake')
    // if rawStream is a bridge, also emit it there
    if (this.rawStream !== this._rawStream) this.rawStream.emit('handshake')

    if (this.destroying) return

    this._rawStream.write(buf)
  }

  _setupSecretSend(handshakeHash) {
    this._sendState = b4a.allocUnsafeSlow(32 + 32 + 8 + 8)
    const encrypt = this._sendState.subarray(0, 32) // secrets
    const decrypt = this._sendState.subarray(32, 64)
    const counter = this._sendState.subarray(64, 72) // nonce
    const initial = this._sendState.subarray(72)

    const inputs = this.isInitiator
      ? [
          [NS_INITIATOR, NS_SEND],
          [NS_RESPONDER, NS_SEND]
        ]
      : [
          [NS_RESPONDER, NS_SEND],
          [NS_INITIATOR, NS_SEND]
        ]

    sodium.crypto_generichash_batch(encrypt, inputs[0], handshakeHash)
    sodium.crypto_generichash_batch(decrypt, inputs[1], handshakeHash)

    sodium.randombytes_buf(initial)
    counter.set(initial)
  }

  _open(cb) {
    // no autostart or no handshake yet
    if (this._rawStream === null || (this._handshake === null && this._encrypt === null)) {
      this._startDone = cb
      return
    }

    this._rawStream.on('data', this._onrawdata.bind(this))
    this._rawStream.on('end', this._onrawend.bind(this))
    this._rawStream.on('drain', this._onrawdrain.bind(this))

    if (this.enableSend) this._rawStream.on('message', this._onmessage.bind(this))

    if (this._encrypt !== null) {
      this._resolveOpened(true)
      return cb(null)
    }

    this._handshakeDone = cb

    if (this.isInitiator) this._onhandshakert(this._handshake.send())
  }

  _predestroy() {
    if (this.rawStream) {
      const error = getStreamError(this)
      this.rawStream.destroy(error)
    }

    if (this._startDone !== null) {
      const done = this._startDone
      this._startDone = null
      done(new Error('Stream destroyed'))
    }

    if (this._handshakeDone !== null) {
      const done = this._handshakeDone
      this._handshakeDone = null
      done(new Error('Stream destroyed'))
    }

    if (this._drainDone !== null) {
      const done = this._drainDone
      this._drainDone = null
      done(new Error('Stream destroyed'))
    }
  }

  _write(data, cb) {
    let wrapped = this._outgoingWrapped

    if (data !== this._outgoingPlain) {
      wrapped = b4a.allocUnsafe(data.byteLength + 3 + ABYTES)
      wrapped.set(data, 4)
    } else {
      this._outgoingWrapped = this._outgoingPlain = null
    }

    if (wrapped.byteLength - 3 > MAX_ATOMIC_WRITE) {
      return cb(
        new Error(
          'Message is too large for an atomic write. Max size is ' + MAX_ATOMIC_WRITE + ' bytes.'
        )
      )
    }
    this.rawBytesWritten += wrapped.byteLength

    writeUint24le(wrapped.byteLength - 3, wrapped)
    // offset 4 so we can do it in-place
    this._encrypt.next(wrapped.subarray(4, 4 + data.byteLength), wrapped.subarray(3))

    if (this._keepAliveTimer !== null) this._keepAliveTimer.refresh()

    if (this._rawStream.write(wrapped) === false) {
      this._drainDone = cb
    } else {
      cb(null)
    }
  }

  _final(cb) {
    this._clearKeepAlive()
    this._ended--
    this._rawStream.end()
    cb(null)
  }

  _resolveOpened(val) {
    if (this._openedDone === null) return
    const opened = this._openedDone
    this._openedDone = null
    opened(val)
    if (!val) return
    this.connected = true
    this.emit('connect')
  }

  _clearTimeout() {
    if (this._timeoutTimer === null) return
    this._timeoutTimer.destroy()
    this._timeoutTimer = null
    this.timeout = 0
  }

  _clearKeepAlive() {
    if (this._keepAliveTimer === null) return
    this._keepAliveTimer.destroy()
    this._keepAliveTimer = null
    this.keepAlive = 0
  }

  _destroy(cb) {
    this._clearKeepAlive()
    this._clearTimeout()
    this._resolveOpened(false)
    cb(null)
  }

  _boxMessage(buffer) {
    const MB = sodium.crypto_secretbox_MACBYTES // 16
    const NB = sodium.crypto_secretbox_NONCEBYTES // 24

    const counter = this._sendState.subarray(64, 72)
    sodium.sodium_increment(counter)
    if (b4a.equals(counter, this._sendState.subarray(72))) {
      this.destroy(new Error('udp send nonce exchausted'))
      return
    }

    const secret = this._sendState.subarray(0, 32)
    const envelope = b4a.allocUnsafe(8 + MB + buffer.byteLength)
    const nonce = envelope.subarray(0, NB)
    const ciphertext = envelope.subarray(8)

    b4a.fill(nonce, 0) // pad suffix
    nonce.set(counter)

    sodium.crypto_secretbox_easy(ciphertext, buffer, nonce, secret)
    return envelope
  }

  send(buffer) {
    if (!this._sendState) return
    if (!this.rawStream?.send) return // udx-stream expected

    const message = this._boxMessage(buffer)
    return this.rawStream.send(message)
  }

  trySend(buffer) {
    if (!this._sendState) return
    if (!this.rawStream?.trySend) return // udx-stream expected

    const message = this._boxMessage(buffer)
    this.rawStream.trySend(message)
  }

  _onmessage(buffer) {
    if (!this._sendState) return // messages before handshake are dropped

    const MB = sodium.crypto_secretbox_MACBYTES // 16
    const NB = sodium.crypto_secretbox_NONCEBYTES // 24

    if (buffer.byteLength < NB) return // Invalid message

    const nonce = b4a.allocUnsafe(NB)
    b4a.fill(nonce, 0)
    nonce.set(buffer.subarray(0, 8))

    const secret = this._sendState.subarray(32, 64)
    const ciphertext = buffer.subarray(8)
    const plain = buffer.subarray(8, buffer.byteLength - MB)

    if (ciphertext.byteLength < MB) return // invalid message

    const success = sodium.crypto_secretbox_open_easy(plain, ciphertext, nonce, secret)

    if (success) this.emit('message', plain)
  }

  alloc(len) {
    const buf = b4a.allocUnsafe(len + 3 + ABYTES)
    this._outgoingWrapped = buf
    this._outgoingPlain = buf.subarray(4, buf.byteLength - ABYTES + 1)
    return this._outgoingPlain
  }

  toJSON() {
    return {
      isInitiator: this.isInitiator,
      publicKey: this.publicKey && b4a.toString(this.publicKey, 'hex'),
      remotePublicKey: this.remotePublicKey && b4a.toString(this.remotePublicKey, 'hex'),
      connected: this.connected,
      destroying: this.destroying,
      destroyed: this.destroyed,
      rawStream: this.rawStream && this.rawStream.toJSON ? this.rawStream.toJSON() : null
    }
  }
}

function writeUint24le(n, buf) {
  buf[0] = n & 255
  buf[1] = (n >>> 8) & 255
  buf[2] = (n >>> 16) & 255
}

function streamId(handshakeHash, isInitiator, out = b4a.allocUnsafe(32)) {
  sodium.crypto_generichash(out, isInitiator ? NS_INITIATOR : NS_RESPONDER, handshakeHash)
  return out
}

function toBuffer(data) {
  return typeof data === 'string' ? b4a.from(data) : data
}

function destroyTimeout() {
  this.destroy(new Error('Stream timed out'))
}

function sendKeepAlive() {
  const empty = this.alloc(0)
  this.write(empty)
}
const { Duplex, Writable } = require('streamx')

class ReversePassThrough extends Duplex {
  constructor(s) {
    super()
    this._stream = s
    this._ondrain = null
  }

  _write(data, cb) {
    if (this._stream.push(data) === false) {
      this._stream._ondrain = cb
    } else {
      cb(null)
    }
  }

  _final(cb) {
    this._stream.push(null)
    cb(null)
  }

  _read(cb) {
    const ondrain = this._ondrain
    this._ondrain = null
    if (ondrain) ondrain()
    cb(null)
  }
}

module.exports = class Bridge extends Duplex {
  constructor(noiseStream) {
    super()

    this.noiseStream = noiseStream

    this._ondrain = null
    this.reverse = new ReversePassThrough(this)
  }

  get publicKey() {
    return this.noiseStream.publicKey
  }

  get remotePublicKey() {
    return this.noiseStream.remotePublicKey
  }

  get handshakeHash() {
    return this.noiseStream.handshakeHash
  }

  flush() {
    return Writable.drained(this)
  }

  _read(cb) {
    const ondrain = this._ondrain
    this._ondrain = null
    if (ondrain) ondrain()
    cb(null)
  }

  _write(data, cb) {
    if (this.reverse.push(data) === false) {
      this.reverse._ondrain = cb
    } else {
      cb(null)
    }
  }

  _final(cb) {
    this.reverse.push(null)
    cb(null)
  }
}
const sodium = require('sodium-universal')
const curve = require('noise-curve-ed')
const Noise = require('noise-handshake')
const b4a = require('b4a')

const EMPTY = b4a.alloc(0)

module.exports = class Handshake {
  constructor(isInitiator, keyPair, remotePublicKey, pattern) {
    this.isInitiator = isInitiator
    this.keyPair = keyPair
    this.noise = new Noise(pattern, isInitiator, keyPair, { curve })
    this.noise.initialise(EMPTY, remotePublicKey)
    this.destroyed = false
  }

  static keyPair(seed) {
    const publicKey = b4a.alloc(32)
    const secretKey = b4a.alloc(64)
    if (seed) sodium.crypto_sign_seed_keypair(publicKey, secretKey, seed)
    else sodium.crypto_sign_keypair(publicKey, secretKey)
    return { publicKey, secretKey }
  }

  recv(data) {
    try {
      this.noise.recv(data)
      if (this.noise.complete) return this._return(null)
      return this.send()
    } catch {
      this.destroy()
      return null
    }
  }

  // note that the data returned here is framed so we don't have to do an extra copy
  // when sending it...
  send() {
    try {
      const data = this.noise.send()
      const wrap = b4a.allocUnsafe(data.byteLength + 3)

      writeUint24le(data.byteLength, wrap)
      wrap.set(data, 3)

      return this._return(wrap)
    } catch {
      this.destroy()
      return null
    }
  }

  destroy() {
    if (this.destroyed) return
    this.destroyed = true
  }

  _return(data) {
    const tx = this.noise.complete ? b4a.toBuffer(this.noise.tx) : null
    const rx = this.noise.complete ? b4a.toBuffer(this.noise.rx) : null
    const hash = this.noise.complete ? b4a.toBuffer(this.noise.hash) : null
    const remotePublicKey = this.noise.complete ? b4a.toBuffer(this.noise.rs) : null

    return {
      data,
      remotePublicKey,
      hash,
      tx,
      rx
    }
  }
}

function writeUint24le(n, buf) {
  buf[0] = n & 255
  buf[1] = (n >>> 8) & 255
  buf[2] = (n >>> 16) & 255
}
{
  "name": "@hyperswarm/secret-stream",
  "version": "6.9.1",
  "description": "Secret stream backed by Noise and libsodium's secretstream",
  "main": "index.js",
  "files": [
    "index.js",
    "lib/**.js"
  ],
  "dependencies": {
    "b4a": "^1.1.0",
    "hypercore-crypto": "^3.3.1",
    "noise-curve-ed": "^2.0.1",
    "noise-handshake": "^4.0.0",
    "sodium-secretstream": "^1.1.0",
    "sodium-universal": "^5.0.0",
    "streamx": "^2.14.0",
    "timeout-refresh": "^2.0.0",
    "unslab": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "udx-native": "^1.13.2"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check .",
    "test": "brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/hyperswarm-secret-stream.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/hyperswarm-secret-stream/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperswarm-secret-stream"
}
{
  "name": "@ipld/dag-cbor",
  "version": "9.2.7",
  "description": "JS implementation of DAG-CBOR",
  "author": "Rod <rod@vagg.org> (http://r.va.gg/)",
  "license": "Apache-2.0 OR MIT",
  "homepage": "https://github.com/ipld/js-dag-cbor#readme",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/ipld/js-dag-cbor.git"
  },
  "bugs": {
    "url": "https://github.com/ipld/js-dag-cbor/issues"
  },
  "publishConfig": {
    "access": "public",
    "provenance": true
  },
  "keywords": [
    "ipfs",
    "ipld",
    "multiformats"
  ],
  "type": "module",
  "types": "./dist/src/index.d.ts",
  "typesVersions": {
    "*": {
      "*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ],
      "src/*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ]
    }
  },
  "files": [
    "src",
    "dist",
    "!dist/test",
    "!**/*.tsbuildinfo"
  ],
  "exports": {
    ".": {
      "types": "./dist/src/index.d.ts",
      "import": "./src/index.js",
      "module-sync": "./src/index.js"
    }
  },
  "release": {
    "branches": [
      "master"
    ],
    "plugins": [
      [
        "@semantic-release/commit-analyzer",
        {
          "preset": "conventionalcommits",
          "releaseRules": [
            {
              "breaking": true,
              "release": "major"
            },
            {
              "revert": true,
              "release": "patch"
            },
            {
              "type": "feat",
              "release": "minor"
            },
            {
              "type": "fix",
              "release": "patch"
            },
            {
              "type": "docs",
              "release": "patch"
            },
            {
              "type": "test",
              "release": "patch"
            },
            {
              "type": "deps",
              "release": "patch"
            },
            {
              "scope": "no-release",
              "release": false
            }
          ]
        }
      ],
      [
        "@semantic-release/release-notes-generator",
        {
          "preset": "conventionalcommits",
          "presetConfig": {
            "types": [
              {
                "type": "feat",
                "section": "Features"
              },
              {
                "type": "fix",
                "section": "Bug Fixes"
              },
              {
                "type": "chore",
                "section": "Trivial Changes"
              },
              {
                "type": "docs",
                "section": "Documentation"
              },
              {
                "type": "deps",
                "section": "Dependencies"
              },
              {
                "type": "test",
                "section": "Tests"
              }
            ]
          }
        }
      ],
      "@semantic-release/changelog",
      "@semantic-release/npm",
      "@semantic-release/github",
      [
        "@semantic-release/git",
        {
          "assets": [
            "CHANGELOG.md",
            "package.json"
          ]
        }
      ]
    ]
  },
  "scripts": {
    "clean": "aegir clean",
    "lint": "aegir lint",
    "build": "aegir build",
    "release": "aegir release",
    "test": "npm run lint && aegir test",
    "test:ts": "npm run test --prefix test/ts-use",
    "test:node": "aegir test -t node --cov",
    "test:chrome": "aegir test -t browser --cov",
    "test:chrome-webworker": "aegir test -t webworker",
    "test:firefox": "aegir test -t browser -- --browser firefox",
    "test:firefox-webworker": "aegir test -t webworker -- --browser firefox",
    "test:electron-main": "aegir test -t electron-main",
    "dep-check": "aegir dep-check"
  },
  "dependencies": {
    "cborg": "^5.0.1",
    "multiformats": "^13.1.0"
  },
  "devDependencies": {
    "@ipld/garbage": "^6.0.0",
    "aegir": "^48.0.1"
  }
}
import * as cborg from 'cborg'
import { CID } from 'multiformats/cid'

// https://github.com/ipfs/go-ipfs/issues/3570#issuecomment-273931692
const CID_CBOR_TAG = 42

/**
 * @template T
 * @typedef {import('multiformats/codecs/interface').ByteView<T>} ByteView
 */

/**
 * @template T
 * @typedef {import('multiformats/codecs/interface').ArrayBufferView<T>} ArrayBufferView
 */

/**
 * @template T
 * @param {ByteView<T> | ArrayBufferView<T>} buf
 * @returns {ByteView<T>}
 */
export function toByteView (buf) {
  if (buf instanceof ArrayBuffer) {
    return new Uint8Array(buf, 0, buf.byteLength)
  }

  return buf
}

/**
 * cidEncoder will receive all Objects during encode, it needs to filter out
 * anything that's not a CID and return `null` for that so it's encoded as
 * normal.
 *
 * @param {any} obj
 * @returns {cborg.Token[]|null}
 */
function cidEncoder (obj) {
  if (obj.asCID !== obj && obj['/'] !== obj.bytes) {
    return null // any other kind of object
  }
  const cid = CID.asCID(obj)
  /* c8 ignore next 4 */
  // very unlikely case, and it'll probably throw a recursion error in cborg
  if (!cid) {
    return null
  }
  const bytes = new Uint8Array(cid.bytes.byteLength + 1)
  bytes.set(cid.bytes, 1) // prefix is 0x00, for historical reasons
  return [
    new cborg.Token(cborg.Type.tag, CID_CBOR_TAG),
    new cborg.Token(cborg.Type.bytes, bytes)
  ]
}

// eslint-disable-next-line jsdoc/require-returns-check
/**
 * Intercept all `undefined` values from an object walk and reject the entire
 * object if we find one.
 *
 * @returns {null}
 */
function undefinedEncoder () {
  throw new Error('`undefined` is not supported by the IPLD Data Model and cannot be encoded')
}

/**
 * Intercept all `number` values from an object walk and reject the entire
 * object if we find something that doesn't fit the IPLD data model (NaN &
 * Infinity).
 *
 * @param {number} num
 * @returns {null}
 */
function numberEncoder (num) {
  if (Number.isNaN(num)) {
    throw new Error('`NaN` is not supported by the IPLD Data Model and cannot be encoded')
  }
  if (num === Infinity || num === -Infinity) {
    throw new Error('`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded')
  }
  return null
}

/**
 * @param {Map<any, any>} map
 * @returns {null}
 */
function mapEncoder (map) {
  for (const key of map.keys()) {
    if (typeof key !== 'string' || key.length === 0) {
      throw new Error('Non-string Map keys are not supported by the IPLD Data Model and cannot be encoded')
    }
  }
  return null
}

const _encodeOptions = {
  float64: true,
  typeEncoders: {
    Map: mapEncoder,
    Object: cidEncoder,
    undefined: undefinedEncoder,
    number: numberEncoder
  }
}

export const encodeOptions = {
  ..._encodeOptions,
  typeEncoders: {
    ..._encodeOptions.typeEncoders
  }
}

/**
 * @param {import('cborg').TagDecodeControl} decode
 * @returns {CID}
 */
function cidDecoder (decode) {
  const bytes = /** @type {Uint8Array} */ (decode())
  if (bytes[0] !== 0) {
    throw new Error('Invalid CID for CBOR tag 42; expected leading 0x00')
  }
  return CID.decode(bytes.subarray(1)) // ignore leading 0x00
}

const _decodeOptions = {
  allowIndefinite: false,
  coerceUndefinedToNull: true,
  allowNaN: false,
  allowInfinity: false,
  allowBigInt: true, // this will lead to BigInt for ints outside of
  // safe-integer range, which may surprise users
  strict: true,
  useMaps: false,
  rejectDuplicateMapKeys: true,
  /** @type {{ [tagNumber: number]: import('cborg').TagDecoder }} */
  tags: { [CID_CBOR_TAG]: cidDecoder }
}

export const decodeOptions = {
  ..._decodeOptions,
  tags: { ..._decodeOptions.tags }
}

export const name = 'dag-cbor'
export const code = 0x71

/**
 * @template T
 * @param {T} node
 * @returns {ByteView<T>}
 */
export const encode = (node) => cborg.encode(node, _encodeOptions)

/**
 * @template T
 * @param {ByteView<T> | ArrayBufferView<T>} data
 * @returns {T}
 */
export const decode = (data) => cborg.decode(toByteView(data), _decodeOptions)
const Cache = require('xache')

module.exports = class AdaptiveTimeout {
  constructor(opts = {}) {
    this._cache = new Cache({
      maxSize: opts.maxSize || 65536,
      maxAge: opts.maxAge || 10 * 60 * 1000 // 10 minutes
    })
    this._fallback = opts.fallback || AdaptiveTimeout.TimeoutExponential
    this._min = opts.min ?? 300
    this._max = opts.max || 4000
    this._jitter = opts.jitter ?? 256
  }

  // Default - aggressive ramp
  static TimeoutAggressive = [500, 750, 1000, 1500, 2000]

  // Linear - steady increase
  static TimeoutLinear = [500, 1000, 1500, 2000, 2500]

  // Exponential - slow start, rapid backoff
  static TimeoutExponential = [250, 500, 1000, 2000, 4000]

  // Gentle - conservative, patient
  static TimeoutGentle = [1000, 1250, 1500, 1750, 2000]

  // Fast - rapid fire retries
  static TimeoutFast = [200, 400, 600, 800, 1000]

  // U-shape - long, short, long
  static TimeoutUShape = [1500, 750, 500, 750, 1500]

  // Inverse U - short, long, short
  static TimeoutInverseU = [500, 1000, 1500, 1000, 500]

  // Sawtooth - alternating fast/slow
  static TimeoutSawtooth = [500, 1500, 500, 1500, 500]

  // Plateau - quick ramp then steady
  static TimeoutPlateau = [500, 1000, 2000, 2000, 2000]

  // Logarithmic - diminishing increases
  static TimeoutLogarithmic = [500, 1000, 1300, 1500, 1600]

  getValue(key) {
    return this._cache.get(key)
  }

  put(key, value) {
    let p = this._cache.get(key)

    if (!p) {
      p = { avg: value, variance: value >> 1 }
    } else {
      // blend 75% old + 25% new deviation
      p.variance += (Math.abs(p.avg - value) - p.variance) >> 2
      // blend 87.5% old + 12.5% new sample
      p.avg += (value - p.avg) >> 3
    }

    this._cache.set(key, p)

    return p
  }

  get(key, attempt = 1) {
    const p = this._cache.get(key)
    const jitter = (Math.random() * this._jitter) | 0

    if (p) {
      // known - use adaptive with linear backoff
      const base = p.avg + (p.variance << 1)
      const backoff = base * attempt
      return Math.min(Math.max(backoff + jitter, this._min), this._max)
    } else {
      // unknown - use aggressive fallback
      const base = this._fallback[Math.min(attempt - 1, this._fallback.length - 1)]
      return base + jitter
    }
  }

  has(key) {
    return this._cache.has(key)
  }

  delete(key) {
    return this._cache.delete(key)
  }

  clear() {
    this._cache.clear()
  }
}
{
  "name": "adaptive-timeout",
  "version": "1.0.1",
  "description": "adaptive-timeout",
  "main": "index.js",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    }
  },
  "files": [
    "package.json",
    "index.js",
    "index.d.ts"
  ],
  "devDependencies": {
    "brittle": "^3.19.0",
    "lunte": "^1.2.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && lunte && brittle-bare test/index.js",
    "lint": "lunte"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/adaptive-timeout.git"
  },
  "author": "Holepunch Inc",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/adaptive-timeout/issues"
  },
  "homepage": "https://github.com/holepunchto/adaptive-timeout",
  "dependencies": {
    "xache": "^1.2.1"
  }
}
// Seed-anchored atproto identity — the secp256k1 / did:plc half.
//
// One BIP39 mnemonic anchors both worlds:
//   mnemonic -> Ed25519  (keet-identity-key)  -> Hypercore log signing   [NEXT increment]
//   mnemonic -> secp256k1 (this module)        -> did:plc + atproto commits
//
// This module owns the atproto side: deterministic secp256k1 derivation, did:key
// encoding, and building/signing a did:plc genesis operation — entirely offline.
// It never submits to the PLC directory (the op-log is permanent; don't churn).

import { mnemonicToSeedSync } from '@scure/bip39'
import { HDKey } from '@scure/bip32'
import { secp256k1 } from '@noble/curves/secp256k1'
import { sha256 } from '@noble/hashes/sha2'
import { base64url } from 'multiformats/bases/base64'
import { encodeDidKey, CURVE_SECP256K1 } from './did-key.js'
import { encodeOp, unsignedOp, didForCreateOp, opCid } from './did-plc.js'

// Our fixed derivation path. No BIP44 coin type is registered for atproto, so this
// is a project convention — the *mnemonic* is the recovery anchor; the path is fixed
// by this constant so the same phrase always yields the same atproto key.
export const ATPROTO_SIGNING_PATH = "m/44'/0'/0'/0/0"
// A SEPARATE derivation for the swarm's ROOT recovery/rotation key — held only by the root, NEVER
// distributed to devices. Distinct account index ('1') so a device that holds the signing key
// cannot derive this. See atproto-base-REVOCATION.md §4-5.
export const ATPROTO_RECOVERY_PATH = "m/44'/0'/1'/0/0"

// raw base64url (no multibase prefix, no padding) — atproto's sig encoding.
function sigToBase64url (bytes) {
  return base64url.encode(bytes).slice(1) // drop multibase 'u'
}
export function base64urlToBytes (str) {
  return base64url.decode('u' + str)
}

// mnemonic -> deterministic secp256k1 keypair for atproto signing.
export function deriveAtprotoKey (mnemonic, path = ATPROTO_SIGNING_PATH) {
  const seed = mnemonicToSeedSync(mnemonic)
  const node = HDKey.fromMasterSeed(seed).derive(path)
  if (!node.privateKey) throw new Error('derivation produced no private key')
  return keyFromPrivate(node.privateKey)
}

// raw 32-byte secp256k1 private key -> { privateKey, publicKey, didKey }.
export function keyFromPrivate (privateKey) {
  const publicKey = secp256k1.getPublicKey(privateKey, true) // 33-byte compressed
  return { privateKey, publicKey, didKey: encodeDidKey(CURVE_SECP256K1, publicKey) }
}

// A fresh random atproto signing keypair (server-minted accounts with no seed anchor).
export function generateAtprotoKey () {
  return keyFromPrivate(secp256k1.utils.randomPrivateKey())
}

// ECDSA sign the sha256 of DAG-CBOR(unsignedOp), low-S, compact -> base64url.
export function signOp (unsigned, privateKey) {
  const hash = sha256(encodeOp(unsigned))
  const sig = secp256k1.sign(hash, privateKey, { lowS: true })
  return sigToBase64url(sig.toCompactRawBytes())
}

// verify a signature string against an unsigned op + did:key-encoded pubkey bytes.
export function verifyOp (unsigned, sigB64url, publicKey) {
  const hash = sha256(encodeOp(unsigned))
  return secp256k1.verify(base64urlToBytes(sigB64url), hash, publicKey, { lowS: true })
}

// Build an UNSIGNED did:plc genesis op. rotationKey defaults to the signing key
// (single-key setup); pass a distinct rotation didKey for key-separation.
// A HANDLE AND A PDS ARE OPTIONAL, and omitting both is the P2P-only genesis (hyper-social #54 §8):
// an identity that names nobody's infrastructure. Creating a did:plc and joining someone's service are
// different decisions, and requiring both at once is what made minting undecidable — you could not have
// an identity without first answering "whose server are you on?". Accepting an invite from
// atproto-bridge or ap-bridge is a LATER PLC UPDATE op that adds the domain handle and the endpoint, so
// creation stays free and joining stays reversible.
//
// ⛔ THEY USED TO BE UNCONDITIONAL, and the two failure modes were not equally survivable. A missing
// pdsUrl put the VALUE `undefined` in the op and dag-cbor refused to encode it — loud, and safe. A
// missing handle produced the STRING 'at://undefined', which encodes perfectly and would have been
// appended to a global, permanent, public log. The silent one is the one this guards.
//
// The directory requires neither: checkGenesisOp (lib/plc-directory.js) asks only for a plc_operation
// with prev:null, rotationKeys, a verificationMethods.atproto and a self-signature.
export function buildGenesisOp ({ signingDidKey, rotationDidKeys, handle = null, pdsUrl = null, labelDidKey = null, feedGenEndpoint = null, labelerEndpoint = null }) {
  const verificationMethods = { atproto: signingDidKey }
  const services = {}
  if (pdsUrl) services.atproto_pds = { type: 'AtprotoPersonalDataServer', endpoint: pdsUrl }
  // Lens-export service entries (a self-custody feed-generator + labeler — e.g. a favela community DID).
  // The PLC op's `services`/`verificationMethods` KEYS become DID-doc fragments: services.bsky_fg → the
  // #bsky_fg service, verificationMethods.atproto_label → the #atproto_label VM. Endpoints point at where
  // the getFeedSkeleton / queryLabels+subscribeLabels XRPC is served (the membrane). #atproto_label
  // defaults to the #atproto signing key (labels co-signed by the shared key) unless a distinct key is given.
  if (feedGenEndpoint) services.bsky_fg = { type: 'BskyFeedGenerator', endpoint: feedGenEndpoint }
  if (labelerEndpoint) {
    services.atproto_labeler = { type: 'AtprotoLabeler', endpoint: labelerEndpoint }
    verificationMethods.atproto_label = labelDidKey || signingDidKey
  } else if (labelDidKey) {
    verificationMethods.atproto_label = labelDidKey
  }
  return {
    type: 'plc_operation',
    rotationKeys: rotationDidKeys && rotationDidKeys.length ? rotationDidKeys : [signingDidKey],
    verificationMethods,
    // Empty, not absent: an identity with no handle claims no alias. The domain handle arrives with the
    // invite, as an update op — it is not a thing you are born with.
    alsoKnownAs: handle ? [`at://${handle}`] : [],
    services,
    prev: null
  }
}

// key { privateKey, publicKey, didKey } -> signed genesis op + did:plc.
export function identityFromKey (key, { handle, pdsUrl }) {
  const unsigned = buildGenesisOp({ signingDidKey: key.didKey, handle, pdsUrl })
  const sig = signOp(unsigned, key.privateKey)
  const signedOp = { ...unsigned, sig }
  const did = didForCreateOp(signedOp)
  return { did, didKey: key.didKey, publicKey: key.publicKey, privateKey: key.privateKey, signedOp }
}

// Full offline flow: mnemonic -> signed genesis op + did:plc.
export function createAtprotoIdentity (mnemonic, { handle, pdsUrl, path = ATPROTO_SIGNING_PATH }) {
  return identityFromKey(deriveAtprotoKey(mnemonic, path), { handle, pdsUrl })
}

// Same, but from a raw private key (server-minted / bring-your-own accounts).
export function createAtprotoIdentityFromKey (privateKey, { handle, pdsUrl }) {
  return identityFromKey(keyFromPrivate(privateKey), { handle, pdsUrl })
}

// The atproto-base SWARM identity: ONE did:plc whose #atproto signing key is SHARED among N
// attested devices, but whose ROTATION authority is a SEPARATE root recovery key that is NEVER
// distributed to devices. Devices sign commits (verificationMethods.atproto = shared signing key)
// but have ZERO PLC authority — only the root (recovery key) can rotate/revoke. Revocation = the
// root rotates the shared signing key via a PLC update; a device holds only the old signing key,
// not the root, so it cannot self-recover. Contrast createAtprotoIdentity (rotationKeys =
// [signingKey], no separation — a device could rotate the DID). The genesis is signed by the
// recovery key (a genesis must be signed by one of its own rotationKeys). See
// atproto-base-REVOCATION.md §5. Returns { did, signedOp, signingKey, recoveryKey } — `signingKey`
// is distributed to attested devices; `recoveryKey` STAYS WITH THE ROOT.
export function createSwarmIdentity (mnemonic, { handle, pdsUrl, feedGenEndpoint = null, labelerEndpoint = null, labelDidKey = null } = {}) {
  const signingKey = deriveAtprotoKey(mnemonic, ATPROTO_SIGNING_PATH)
  const recoveryKey = deriveAtprotoKey(mnemonic, ATPROTO_RECOVERY_PATH)
  const unsigned = buildGenesisOp({ signingDidKey: signingKey.didKey, rotationDidKeys: [recoveryKey.didKey], handle, pdsUrl, feedGenEndpoint, labelerEndpoint, labelDidKey })
  const sig = signOp(unsigned, recoveryKey.privateKey)
  const signedOp = { ...unsigned, sig }
  const did = didForCreateOp(signedOp)
  return { did, signedOp, signingKey, recoveryKey, didKey: signingKey.didKey }
}

// ── Post-genesis PLC operations (device attestation = rotation, NOT genesis) ──
//
// A did:plc is fixed at genesis; you evolve it with UPDATE operations that chain via
// `prev` (the CID of the previous signed op) and are signed by one of the CURRENT
// rotationKeys. This is how a device signing key is attested AFTER genesis without
// changing the DID — the atproto-correct model (see DESIGN.md §4a). The genesis stays
// deterministic (root-derived signing key → reproducible DID); the device key arrives
// as a rotation of verificationMethods.atproto.

// Build an UNSIGNED update op. `prevSignedOp` is the previous op in the log (its CID
// becomes `prev`). The remaining fields are the FULL new operation state — carry
// forward what you're not changing (a PLC op replaces the whole doc state, it is not a
// patch). This module never submits to the PLC directory; it only builds/signs offline.
export function buildUpdateOp ({ prevSignedOp, rotationDidKeys, verificationMethods, alsoKnownAs, services }) {
  if (!prevSignedOp) throw new Error('buildUpdateOp: prevSignedOp required')
  return {
    type: 'plc_operation',
    rotationKeys: rotationDidKeys,
    verificationMethods,
    alsoKnownAs,
    services,
    prev: opCid(prevSignedOp)
  }
}

// Attest a device by ROTATING verificationMethods.atproto to the device's did:key,
// carrying every other field forward from `prevSignedOp`, signed by a rotation key
// (the root — `signerPrivateKey` must correspond to one of prevSignedOp.rotationKeys).
// The DID is UNCHANGED. Returns the signed update op ready to submit to the PLC log.
export function rotateVerificationMethod ({ prevSignedOp, newAtprotoDidKey, signerPrivateKey }) {
  const unsigned = buildUpdateOp({
    prevSignedOp,
    rotationDidKeys: prevSignedOp.rotationKeys,
    verificationMethods: { ...prevSignedOp.verificationMethods, atproto: newAtprotoDidKey },
    alsoKnownAs: prevSignedOp.alsoKnownAs,
    services: prevSignedOp.services
  })
  const sig = signOp(unsigned, signerPrivateKey)
  return { ...unsigned, sig }
}

// Full self-custody onboarding — the atproto-correct device-attested model. A DETERMINISTIC,
// root-derived genesis pins the DID (reproducible from rootMnemonic+handle+pdsUrl), then a
// POST-genesis rotation attests a per-device signing key. The DID is f(root,handle,pds) — NOT
// f(device key) — so it reproduces across runs and can span multiple devices. The root key
// signs the genesis + the rotation and is then discarded (the user keeps it via hyperident);
// the peer holds ONLY the device key. This supersedes buildAttestedIdentity, which baked the
// device key INTO the genesis (making did:plc = f(device key) — non-reproducible, single-device).
// Pass a device secp256k1 privateKey to pin it; otherwise a fresh device key is minted.
export function selfCustodyIdentity ({ rootMnemonic, rootKey, handle, pdsUrl, deviceKey, path = ATPROTO_SIGNING_PATH }) {
  const genesis = rootKey
    ? createAtprotoIdentityFromKey(rootKey, { handle, pdsUrl })
    : createAtprotoIdentity(rootMnemonic, { handle, pdsUrl, path })
  const device = deviceKey ? keyFromPrivate(deviceKey) : generateAtprotoKey()
  const rotationOp = rotateVerificationMethod({
    prevSignedOp: genesis.signedOp,
    newAtprotoDidKey: device.didKey,
    signerPrivateKey: genesis.privateKey // the root — a rotationKey of the genesis
  })
  return {
    did: genesis.did, // = f(root, handle, pds) — reproducible, device-independent
    genesisOp: genesis.signedOp, // vm = root-derived key, signed by root, prev:null
    rotationOp, // vm → device key, signed by root, prev = cid(genesis)
    deviceKey: device, // { privateKey, publicKey, didKey } — the peer holds THIS
    rootDidKey: genesis.didKey, // the root (rotation / recovery) key's did:key
    rootPublicKey: genesis.publicKey,
    rotationKeys: genesis.signedOp.rotationKeys
  }
}

export { unsignedOp, didForCreateOp, opCid }
// PDS auth primitives — password hashing + HS256 session tokens. Pure and bare-safe:
// scrypt/hmac/sha256 are @noble/hashes (pure JS, no crypto global), randomness comes from
// hypercore-crypto (bare-native via sodium). No I/O — the caller owns storage + clock.
//
// This is the ONLY auth the bsky-facing HTTP membrane needs: a client calls createSession
// with {identifier,password}, gets an opaque accessJwt, and presents it as `Authorization:
// Bearer` on writes. The PDS verifies the HMAC + expiry and reads `sub` (the repo DID).
// Standard atproto shape, so any @atproto/api client works unchanged.

import { scrypt } from '@noble/hashes/scrypt'
import { hmac } from '@noble/hashes/hmac'
import { sha256 } from '@noble/hashes/sha2'
import { secp256k1 } from '@noble/curves/secp256k1'
import { randomBytes } from 'hypercore-crypto'

const enc = new TextEncoder()
const dec = new TextDecoder()

// scrypt work factor — ~16 MiB, interactive-login appropriate. Embedded in the stored
// string so the params can evolve without breaking existing hashes.
const SCRYPT = { N: 16384, r: 8, p: 1, dkLen: 32 }

// ---- base64url (JWT segments) — base64 is universally supported (node + bare-buffer);
// the +/ -> -_ transform makes it url-safe without needing 'base64url' encoder support. ----
export function b64url (bytes) {
  return Buffer.from(bytes).toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
}
export function b64urlToBytes (str) {
  let s = str.replace(/-/g, '+').replace(/_/g, '/')
  while (s.length % 4) s += '='
  return new Uint8Array(Buffer.from(s, 'base64'))
}

function hex (bytes) { return Buffer.from(bytes).toString('hex') }
function fromHex (str) { return new Uint8Array(Buffer.from(str, 'hex')) }

// Constant-time equality — never leak match progress via early return.
export function timingSafeEqual (a, b) {
  if (a.length !== b.length) return false
  let d = 0
  for (let i = 0; i < a.length; i++) d |= a[i] ^ b[i]
  return d === 0
}

// ---- passwords ----
// Stored form: `scrypt$<N>$<r>$<p>$<saltHex>$<hashHex>`.
export function hashPassword (password, { salt } = {}) {
  const s = salt || randomBytes(16)
  const h = scrypt(enc.encode(password), s, SCRYPT)
  return `scrypt$${SCRYPT.N}$${SCRYPT.r}$${SCRYPT.p}$${hex(s)}$${hex(h)}`
}

export function verifyPassword (password, stored) {
  if (typeof stored !== 'string' || !stored.startsWith('scrypt$')) return false
  const parts = stored.split('$')
  if (parts.length !== 6) return false
  const N = parseInt(parts[1], 10)
  const r = parseInt(parts[2], 10)
  const p = parseInt(parts[3], 10)
  const salt = fromHex(parts[4])
  const expect = fromHex(parts[5])
  const got = scrypt(enc.encode(password), salt, { N, r, p, dkLen: expect.length })
  return timingSafeEqual(got, expect)
}

// ---- HS256 JWTs ----
function segment (obj) { return b64url(enc.encode(JSON.stringify(obj))) }

export function signJwt (payload, secret) {
  const head = segment({ alg: 'HS256', typ: 'JWT' })
  const body = segment(payload)
  const signingInput = `${head}.${body}`
  const sig = hmac(sha256, secret, enc.encode(signingInput))
  return `${signingInput}.${b64url(sig)}`
}

// Verify signature + expiry (nowSec = current time in epoch seconds). Throws a typed
// Error ({ status, error }) on any failure so the membrane can map it to an XRPC error.
export function verifyJwt (token, secret, { nowSec } = {}) {
  const parts = typeof token === 'string' ? token.split('.') : []
  if (parts.length !== 3) throw authError(401, 'AuthMissing', 'malformed token')
  const signingInput = `${parts[0]}.${parts[1]}`
  const expected = hmac(sha256, secret, enc.encode(signingInput))
  const got = b64urlToBytes(parts[2])
  if (!timingSafeEqual(got, expected)) throw authError(401, 'InvalidToken', 'bad signature')
  let payload
  try { payload = JSON.parse(dec.decode(b64urlToBytes(parts[1]))) } catch { throw authError(401, 'InvalidToken', 'bad payload') }
  const now = nowSec != null ? nowSec : Math.floor(Date.now() / 1000)
  if (payload.exp != null && now >= payload.exp) throw authError(401, 'ExpiredToken', 'token expired')
  return payload
}

// ---- ES256K signed assertions — the key-native login (also atproto's service-auth
// shape). A caller proves control of an account's atproto signing key by signing a
// short-lived assertion; the PDS verifies against the key already published in the DID,
// so NO secret is stored. This is the P2P trust root (key possession) brought to the
// HTTP edge — the same key that signs the repo's commits. ----
export function signAssertion (payload, privKey) {
  const head = segment({ alg: 'ES256K', typ: 'JWT' })
  const body = segment(payload)
  const signingInput = `${head}.${body}`
  const sig = secp256k1.sign(sha256(enc.encode(signingInput)), privKey, { lowS: true }).toCompactRawBytes()
  return `${signingInput}.${b64url(sig)}`
}

// Verify signature + expiry against a compressed secp256k1 public key. Throws typed.
export function verifyAssertion (token, pubKeyCompressed, { nowSec } = {}) {
  const parts = typeof token === 'string' ? token.split('.') : []
  if (parts.length !== 3) throw authError(401, 'AuthMissing', 'malformed assertion')
  const signingInput = `${parts[0]}.${parts[1]}`
  let okSig = false
  try { okSig = secp256k1.verify(b64urlToBytes(parts[2]), sha256(enc.encode(signingInput)), pubKeyCompressed, { lowS: true }) } catch { okSig = false }
  if (!okSig) throw authError(401, 'InvalidToken', 'bad assertion signature')
  let payload
  try { payload = JSON.parse(dec.decode(b64urlToBytes(parts[1]))) } catch { throw authError(401, 'InvalidToken', 'bad assertion payload') }
  const now = nowSec != null ? nowSec : Math.floor(Date.now() / 1000)
  if (payload.exp != null && now >= payload.exp) throw authError(401, 'ExpiredToken', 'assertion expired')
  return payload
}

// Decode a JWT/assertion segment (header or claims) WITHOUT verifying — used to read the
// issuer before we know which key to verify against. null on malformed input.
export function decodeSegment (seg) {
  try { return JSON.parse(dec.decode(b64urlToBytes(seg))) } catch { return null }
}

export function parseBearer (authHeader) {
  if (typeof authHeader !== 'string') return null
  const m = authHeader.match(/^Bearer\s+(.+)$/i)
  return m ? m[1].trim() : null
}

export function authError (status, error, message) {
  const e = new Error(message || error)
  e.status = status
  e.error = error
  return e
}

export const ACCESS_SCOPE = 'com.atproto.access'
export const REFRESH_SCOPE = 'com.atproto.refresh'
// keet-identity-key device chain — the P2P-verifiable half of device attestation.
//
// Runs in PARALLEL to the atproto PLC authority (device-attestation.js). atproto's
// rotationKeys/PLC-op-log carry the FEDERATION-visible authority (secp256k1); this keet
// chain carries the authority OUR P2P world verifies (Ed25519). Both anchor on the same
// root identity and vouch for the same device.
//
// Shape (from keet-identity-key): a proof is `{ identity, epoch, chain: [{publicKey,
// signature}], data? }`. `bootstrap` attests a device pubkey under the root identity;
// `attestData` lets the (leaf) device sign arbitrary data — here, the atproto DID — so a
// verifier learns "root → device → this device vouches for did:plc:…". `verify` walks the
// chain back to the identity and checks the data signature.

import IdentityKey from 'keet-identity-key'
import b4a from 'b4a'

// The device's keet-world Ed25519 keypair (derived from the device seed) — distinct from
// its secp256k1 atproto signing key. This is the device's identity in the keet chain.
export async function deviceKeetKeyPair (mnemonic, seed) {
  const idk = await IdentityKey.from({ mnemonic, seed })
  return idk.identityKeyPair // { publicKey, secretKey }
}

// The root identity's Ed25519 public key — the anchor every chain must resolve to.
export async function rootIdentityPublicKey (mnemonic, seed) {
  const idk = await IdentityKey.from({ mnemonic, seed })
  return b4a.from(idk.identityPublicKey)
}

// Root identity attests a device's Ed25519 public key → an encoded proof chain.
export async function attestDeviceChain ({ rootMnemonic, rootSeed, devicePublicKey }) {
  return IdentityKey.bootstrap({ mnemonic: rootMnemonic, seed: rootSeed }, devicePublicKey)
}

// An ALREADY-ATTESTED device attests ANOTHER device, extending the chain: root → parent → child.
// keet's attestDevice signs { epoch, identity, device } with the PARENT's keypair and pushes
// { publicKey, signature } onto the parent's chain, so the result still resolves to the same root
// identity and the same epoch — a chained device passes the identical admission gate and the identical
// minimum-epoch receipt check as a root-attested one.
//
// WHY THIS MATTERS OPERATIONALLY: admitting a new device to a room needs a proof anchored at the room's
// root identity, and attestDeviceChain above needs the ROOT MNEMONIC — which is deliberately not stored
// on any node (config.js: a device "must never hold" it). Read alone, that makes adding a co-owner
// impossible without recovering a secret nobody kept. It is not: an existing attested device already has
// everything required to vouch for the next one. Only the root's PUBLIC key is needed to verify.
//
// parentKeyPair: the attesting device's Ed25519 identity keypair (deviceKeetKeyPair of its mnemonic).
// parentProof: that device's own proof (root-attested, or itself chained — chains nest).
export function attestDeviceViaDevice ({ parentKeyPair, parentProof, devicePublicKey }) {
  if (!parentKeyPair || !parentProof || !devicePublicKey) throw new Error('attestDeviceViaDevice: parentKeyPair, parentProof, devicePublicKey required')
  // Pass the proof as BYTES: keet decodes a fresh copy, so the caller's proof is never mutated by the
  // chain.push inside attestDevice (it would otherwise grow the parent's own proof on every call).
  const proof = b4a.isBuffer(parentProof) ? parentProof : b4a.from(parentProof)
  return IdentityKey.attestDevice(b4a.from(devicePublicKey), parentKeyPair, proof)
}

// The attested (leaf) device vouches for the atproto DID by signing it as attested data,
// extending the proof with `proof.data`. Result: root → device → vouches-for(did).
export function attestAtprotoBinding ({ deviceKeyPair, did, proof }) {
  return IdentityKey.attestData(b4a.from(did), deviceKeyPair, proof)
}

// Verify the full binding: the chain resolves to the root identity AND the device vouched
// for exactly this DID. Returns { receipt, identityPublicKey, devicePublicKey } or null.
export function verifyAtprotoBinding ({ proof, did, expectedIdentity, expectedDevice }) {
  return IdentityKey.verify(proof, b4a.from(did), { expectedIdentity, expectedDevice })
}
// did:key encoding/decoding for the two curves atproto accepts.
//
//   did:key:z<base58btc( <multicodec-varint> ++ <compressed-pubkey> )>
//
// Multicodec key-type prefixes (unsigned-varint):
//   secp256k1-pub = 0xe7   -> varint [0xe7, 0x01]   -> did:key:zQ3s...
//   p256-pub      = 0x1200 -> varint [0x80, 0x24]   -> did:key:zDna...
//
// The pubkey is the 33-byte SEC1 compressed point (0x02/0x03 ++ x). This matches
// @atproto/crypto's formatDidKey. Validated by the P-256 golden round-trip test.

import { base58btc } from 'multiformats/bases/base58'

export const CURVE_SECP256K1 = 'secp256k1'
export const CURVE_P256 = 'p256'

const MULTICODEC = {
  [CURVE_SECP256K1]: 0xe7,
  [CURVE_P256]: 0x1200
}
const BY_CODE = { 0xe7: CURVE_SECP256K1, 0x1200: CURVE_P256 }

function varintEncode (n) {
  const out = []
  while (n >= 0x80) { out.push((n & 0x7f) | 0x80); n >>>= 7 }
  out.push(n)
  return Uint8Array.from(out)
}

function varintDecode (bytes) {
  let n = 0, shift = 0, i = 0
  for (;;) {
    const b = bytes[i++]
    n |= (b & 0x7f) << shift
    if ((b & 0x80) === 0) break
    shift += 7
  }
  return { code: n >>> 0, length: i }
}

// compressed pubkey bytes (33) -> did:key string
export function encodeDidKey (curve, compressedPubkey) {
  const code = MULTICODEC[curve]
  if (code === undefined) throw new Error(`unsupported curve: ${curve}`)
  const prefix = varintEncode(code)
  const bytes = new Uint8Array(prefix.length + compressedPubkey.length)
  bytes.set(prefix, 0)
  bytes.set(compressedPubkey, prefix.length)
  return `did:key:${base58btc.encode(bytes)}` // base58btc.encode already prepends 'z'
}

// did:key string -> { curve, pubkey (compressed bytes) }
export function decodeDidKey (didKey) {
  if (!didKey.startsWith('did:key:')) throw new Error('not a did:key')
  const mb = didKey.slice('did:key:'.length)
  const bytes = base58btc.decode(mb) // expects leading 'z'
  const { code, length } = varintDecode(bytes)
  const curve = BY_CODE[code]
  if (!curve) throw new Error(`unknown multicodec 0x${code.toString(16)}`)
  return { curve, pubkey: bytes.slice(length) }
}
// did:plc computation — byte-exact.
//
// A did:plc is derived from its *genesis* operation:
//   did = "did:plc:" + base32( sha256( dag-cbor(signedGenesisOp) ) ).slice(0, 24)
//
// The hash is over the SIGNED op (the `sig` field is included). DAG-CBOR gives a
// canonical byte layout (sorted map keys, definite lengths), so the DID is a pure
// function of the op. base32 here is RFC-4648 lowercase, NO padding, and NO
// multibase prefix (did-method-plc uses raw base32, not multiformats' 'b'-prefixed
// multibase form) — see the golden-vector test.
//
// Reference: https://github.com/did-method-plc/did-method-plc (didForCreateOp)

import * as dagCbor from '@ipld/dag-cbor'
import { sha256 } from '@noble/hashes/sha2'
import { base32 } from 'multiformats/bases/base32'
import { CID } from 'multiformats/cid'
import * as Digest from 'multiformats/hashes/digest'

// multiformats' base32.encode returns a multibase string prefixed with 'b'.
// did:plc uses the raw base32 alphabet output, so strip the leading multibase char.
function rawBase32 (bytes) {
  const multibase = base32.encode(bytes) // 'b' + <rfc4648-lower-nopad>
  return multibase.slice(1)
}

// Canonical DAG-CBOR bytes for an operation object.
export function encodeOp (op) {
  return dagCbor.encode(op)
}

// Compute the did:plc for a signed genesis operation.
export function didForCreateOp (signedOp, truncate = 24) {
  const bytes = encodeOp(signedOp)
  const hash = sha256(bytes)
  const b32 = rawBase32(hash)
  return `did:plc:${b32.slice(0, truncate)}`
}

// The unsigned operation is everything except `sig`. did:plc signs the DAG-CBOR of
// the unsigned op; the signature is then attached and the DID hashes the signed form.
export function unsignedOp (op) {
  const { sig, ...rest } = op // eslint-disable-line no-unused-vars
  return rest
}

// The CID of a SIGNED operation — CIDv1, dag-cbor codec (0x71), sha2-256 multihash
// (0x12), rendered as a base32 string. This is the value the NEXT operation carries in
// its `prev` field to chain the PLC op-log (genesis has `prev: null`). Same encoding as
// atproto-repo/lib/cid.js cidForBytesSync, over DAG-CBOR(signedOp). Reference: the
// did-method-plc CID = CID.create(1, 0x71, sha256(cborEncode(op))).
export function opCid (signedOp) {
  const bytes = encodeOp(signedOp)
  const digest = Digest.create(0x12, sha256(bytes))
  return CID.createV1(dagCbor.code, digest).toString()
}
// DID-derived P2P discovery (the "sneaky P2P" binding, Option 2).
//
// The rendezvous topic for a DID is DERIVED, not written anywhere: the DID document stays
// 100% vanilla atproto (only atproto_pds -> the bridge), so bsky/HTTP never sees a P2P side.
// A self-custody peer announces on discoveryTopic(did); a bridge, given the DID, derives the
// SAME topic, connects, and AUTHENTICATES the peer on connect (the peer's served repo must
// sign against the DID's key — a squatter on the public topic can't forge that). So the lookup
// is deterministic + unauthenticated; trust is established at the connection, not the address.

import crypto from 'hypercore-crypto'

const NS = 'hyper-proto-peer/discovery/v1:'

// did (string) -> 32-byte Hyperswarm topic. Deterministic; anyone with the DID can compute it.
export function discoveryTopic (did) {
  if (!did || typeof did !== 'string') throw new Error('discoveryTopic: did (string) required')
  return crypto.data(new TextEncoder().encode(NS + did))
}
// Attaching an identity to hosting, and detaching it again — the holder's half of the invite ceremony.
//
// ── WHY THIS IS A SEPARATE ACT FROM CREATING AN IDENTITY ─────────────────────────────────────────
// buildGenesisOp makes handle and pdsUrl optional, so an identity can be minted P2P-only: it names
// nobody's infrastructure and needs nobody's permission to exist (hyper-social #54 §8). What is scarce
// is not identity, it is somebody's servers. So being fronted by a membrane (pds.7rnx.net) or a
// fediverse bridge (ap.7rnx.net) is gated by an invite, and accepting one is THIS: a later PLC update
// adding a domain handle and a service endpoint.
//
// The ordering is forced rather than chosen. An update op must chain onto a genesis already in the log
// (checkUpdateOp wants prev == the head CID), so genesis is submitted at creation and the invite extends
// it. That is what keeps creation genuinely free and joining genuinely reversible.
//
// ── ⛔ THE OPERATOR CANNOT DO THIS FOR YOU ───────────────────────────────────────────────────────
// A PLC update must be signed by a CURRENT rotation key, and createSwarmIdentity puts exactly one there:
// the root recovery key, which never leaves its owner (device-node.js: a device receives the signing key
// and NEVER the root, "so it can't derive the recovery key or self-recover"). An operator can grant
// infrastructure and can add a DID to the bridge's fronted set, but cannot alter someone's identity
// document. The ceremony is two-sided by construction, not by policy — which is the property that makes
// "our infrastructure" a service rather than custody.
//
// ── SHAPE, FOR THE UI THAT WILL DRIVE IT ─────────────────────────────────────────────────────────
// These are OFFLINE and PURE: they take the current head op and return a signed op. Nothing here
// resolves, submits, or talks to a network — PlcDirectory.submitUpdate does that, and it is deliberately
// somebody else's call, because it is the irreversible half.
//
// So an atproto-bridge web UI splits cleanly: the UI issues the invite and knows the handle + endpoint;
// the HOLDER (a phone unlocking its vault, or an operator with the mnemonic) calls these and submits.
// Neither side can complete the ceremony alone.
//
// A PLC op REPLACES the whole document state — it is not a patch — so every field not being changed must
// be carried forward explicitly. Dropping one silently removes a key or a service.

import { buildUpdateOp, signOp, keyFromPrivate } from './atproto-identity.js'

const PDS_SERVICE = 'atproto_pds'
const PDS_TYPE = 'AtprotoPersonalDataServer'

const aka = (handle) => 'at://' + String(handle).replace(/^at:\/\//, '')

/**
 * Refuse locally what the directory would refuse remotely.
 *
 * Signing with a key that is not a current rotation key produces an op the directory rejects, and
 * finding that out by submitting is a wasted round trip against a permanent public log — and a
 * confusing one, because the rejection names a CID, not the mistake. The likely wrong key is the
 * #atproto signing key, which a device legitimately holds and which has zero PLC authority.
 */
function assertRotationSigner (prevSignedOp, signerPrivateKey) {
  const rot = (prevSignedOp && prevSignedOp.rotationKeys) || []
  let didKey = null
  try { didKey = keyFromPrivate(signerPrivateKey).didKey } catch { didKey = null }
  if (!didKey || !rot.includes(didKey)) {
    throw new Error(
      'hosting: signer is not a current rotation key of this identity — a PLC update must be signed by ' +
      'the recovery key, not the #atproto signing key'
    )
  }
}

/** Sign an unsigned op, after checking the signer may. */
function finish (prevSignedOp, unsigned, signerPrivateKey) {
  assertRotationSigner(prevSignedOp, signerPrivateKey)
  return { ...unsigned, sig: signOp(unsigned, signerPrivateKey) }
}

/**
 * Accept hosting: claim `handle` and name `pdsUrl` as this identity's PDS.
 *
 * Also the MOVE operation — pointing at a different host is one op, not a detach plus an attach, because
 * two ops would leave the identity briefly homeless in a log that never forgets.
 *
 * @param {object}  opts
 * @param {object}  opts.prevSignedOp      the current head op (genesis, or the last update)
 * @param {string}  opts.handle            e.g. 'flaky.7rnx.net'
 * @param {string}  opts.pdsUrl            e.g. 'https://pds.7rnx.net'
 * @param {Uint8Array} opts.signerPrivateKey  a CURRENT rotation key — the root recovery key
 * @returns {object} a signed plc_operation, ready for PlcDirectory.submitUpdate
 */
export function attachHosting ({ prevSignedOp, handle, pdsUrl, signerPrivateKey } = {}) {
  if (!prevSignedOp) throw new Error('attachHosting: prevSignedOp required')
  if (!handle) throw new Error('attachHosting: handle required')
  if (!pdsUrl) throw new Error('attachHosting: pdsUrl required')

  const prevServices = prevSignedOp.services || {}
  const prevAka = prevSignedOp.alsoKnownAs || []
  const wantAka = [aka(handle)]

  // ⛔ REFUSE A NO-OP. Every accepted op is a permanent, public append to a global log. Re-running an
  // invite that already succeeded must not add a second identical entry to someone's history — and a
  // web UI WILL re-run it, because a user who does not see a change presses the button again.
  const already = prevServices[PDS_SERVICE] &&
    prevServices[PDS_SERVICE].endpoint === pdsUrl &&
    prevAka.length === 1 && prevAka[0] === wantAka[0]
  if (already) {
    throw new Error('attachHosting: this identity is already hosted at ' + pdsUrl + ' as ' + handle + ' — nothing to append')
  }

  // The handle REPLACES rather than accumulates: atproto treats the first alias as the identity's handle,
  // and an identity that silently kept every host it ever tried would advertise handles that no longer
  // resolve. Other services are carried forward — a community DID's feed generator and labeler are not
  // this operation's business.
  const unsigned = buildUpdateOp({
    prevSignedOp,
    rotationDidKeys: prevSignedOp.rotationKeys,
    verificationMethods: prevSignedOp.verificationMethods,
    alsoKnownAs: wantAka,
    services: { ...prevServices, [PDS_SERVICE]: { type: PDS_TYPE, endpoint: pdsUrl } }
  })
  return finish(prevSignedOp, unsigned, signerPrivateKey)
}

/**
 * Leave hosting: release the handle and stop naming a PDS, returning the identity to P2P-only.
 *
 * This is what makes accepting an invite reversible, and it is why the invite gates INFRASTRUCTURE
 * rather than existence: leaving costs the identity nothing it was born with. The DID, its keys and its
 * repo are untouched — only the document's claims about where to reach it change.
 *
 * ⚠ Reversible is not retroactive. Content already replicated to a membrane or a relay has been read,
 * and detaching does not unsay it. This changes where the network is TOLD to look, nothing more.
 */
export function detachHosting ({ prevSignedOp, signerPrivateKey } = {}) {
  if (!prevSignedOp) throw new Error('detachHosting: prevSignedOp required')

  const services = { ...(prevSignedOp.services || {}) }
  const hadPds = !!services[PDS_SERVICE]
  delete services[PDS_SERVICE]
  const hadAka = (prevSignedOp.alsoKnownAs || []).length > 0
  if (!hadPds && !hadAka) {
    throw new Error('detachHosting: this identity is already P2P-only — nothing to append')
  }

  const unsigned = buildUpdateOp({
    prevSignedOp,
    rotationDidKeys: prevSignedOp.rotationKeys,
    verificationMethods: prevSignedOp.verificationMethods,
    alsoKnownAs: [],
    services
  })
  return finish(prevSignedOp, unsigned, signerPrivateKey)
}
// PLC Directory submit ceremony — the SUBMIT half of did:plc (the offline half lives in
// did-plc.js / atproto-identity.js and is byte-exact-proven). See the did-plc skill +
// atproto-base/docs/did-plc-contract-reference.md.
//
// ⚠️ POST /:did is a PERMANENT, irreversible append to the global PLC op-log (nullifiable only
// by a higher-authority fork within a 72h window). So this module is OFFLINE-FIRST: the op
// construction (elsewhere), the §6 validation MIRROR (checkGenesisOp / checkUpdateOp), and the
// ceremony orchestration are all pure/injectable and fully tested WITHOUT the network. The only
// I/O is the injectable `fetchImpl`; nothing here touches the live directory at import.
//
// The self-custody sequence (did-plc skill §5):
//   GET /:did/log/last → live head → opCid(head) == our prev → build full-state op → sign with a
//   CURRENT rotation key → LOCALLY re-validate (§6) → POST /:did → confirm via GET /:did/data.

import { sha256 } from '@noble/hashes/sha2'
import { secp256k1 } from '@noble/curves/secp256k1'
import { p256 } from '@noble/curves/p256'
import { encodeOp, unsignedOp, didForCreateOp, opCid } from './did-plc.js'
import { base64urlToBytes, rotateVerificationMethod } from './atproto-identity.js'
import { decodeDidKey, CURVE_P256 } from './did-key.js'

const DEFAULT_PLC = 'https://plc.directory'

function err (message) { return { ok: false, error: message } }

// ── §6 local validation mirror (pure — run BEFORE the irreversible write) ──

// Verify an atproto ECDSA signature: sig over sha256(messageBytes) against a did:key, honoring
// its curve (secp256k1 or P-256), low-S enforced (§2 — high-S and DER-encoded sigs are rejected).
// The atproto signing primitive. Returns false on any decode/verify error (never throws).
export function verifySig (messageBytes, sigBytes, didKey) {
  let dk
  try { dk = decodeDidKey(didKey) } catch { return false }
  // atproto requires the raw 64-byte (r‖s) compact form — DER-encoded sigs (longer) are INVALID
  // even if cryptographically sound (conformance rule §2). noble would otherwise parse DER.
  if (!sigBytes || sigBytes.length !== 64) return false
  const hash = sha256(messageBytes)
  const curve = dk.curve === CURVE_P256 ? p256 : secp256k1
  try { return curve.verify(sigBytes, hash, dk.pubkey, { lowS: true }) } catch { return false }
}

// Verify a PLC op's signature (over dag-cbor of the unsigned op) against a did:key.
export function verifyOpSig (signedOp, didKey) {
  let sig
  try { sig = base64urlToBytes(signedOp.sig) } catch { return false }
  return verifySig(encodeOp(unsignedOp(signedOp)), sig, didKey)
}

// True iff the op is signed by AT LEAST ONE of the given rotation did:keys (the directory
// accepts if any current rotation key matches — did-plc skill §2).
export function verifyOpSignedByAny (signedOp, rotationDidKeys) {
  return Array.isArray(rotationDidKeys) && rotationDidKeys.some((rk) => verifyOpSig(signedOp, rk))
}

// Local mirror of the directory's genesis validation (§6.2): plc_operation shape, prev:null,
// DID hashes from the op, sig by one of its OWN rotationKeys.
export function checkGenesisOp (signedOp, did) {
  if (!signedOp || signedOp.type !== 'plc_operation') return err('not a plc_operation')
  if (signedOp.prev !== null) return err('genesis prev must be null')
  if (!Array.isArray(signedOp.rotationKeys) || signedOp.rotationKeys.length === 0) return err('no rotationKeys')
  if (!signedOp.verificationMethods || !signedOp.verificationMethods.atproto) return err('no atproto verificationMethod')
  if (!signedOp.sig) return err('op is unsigned')
  let computed
  try { computed = didForCreateOp(signedOp) } catch (e) { return err('DID computation failed: ' + e.message) }
  if (did && computed !== did) return err('DID mismatch: op hashes to ' + computed + ', not ' + did)
  if (!verifyOpSignedByAny(signedOp, signedOp.rotationKeys)) return err('sig not by any of its own rotationKeys')
  return { ok: true, error: null, did: computed }
}

// Local mirror of the directory's forward-extension validation (§6.3-4): the op chains onto
// `prevSignedOp` (prev == its CID) and is signed by one of the HEAD op's rotationKeys.
export function checkUpdateOp (signedOp, prevSignedOp) {
  if (!signedOp || (signedOp.type !== 'plc_operation' && signedOp.type !== 'plc_tombstone')) return err('not a plc op')
  if (typeof signedOp.prev !== 'string' || signedOp.prev.length === 0) return err('update prev must be the head op CID')
  if (!signedOp.sig) return err('op is unsigned')
  if (!prevSignedOp) return err('no prev (head) op to validate against')
  let prevCid
  try { prevCid = opCid(prevSignedOp) } catch (e) { return err('prev CID computation failed: ' + e.message) }
  if (signedOp.prev !== prevCid) return err('prev != head CID (' + signedOp.prev + ' != ' + prevCid + ')')
  if (!verifyOpSignedByAny(signedOp, prevSignedOp.rotationKeys)) return err('sig not by a current (head) rotationKey')
  return { ok: true, error: null }
}

// Normalize a fetched op to EXACTLY the signed-op fields, so opCid() hashes the canonical bytes
// regardless of whether the endpoint wrapped it (`.operation`) or added audit fields (cid/…).
function opFieldsOnly (o) {
  const op = o && o.operation ? o.operation : o
  if (!op || typeof op !== 'object') return op
  if (op.type === 'plc_tombstone') return { type: op.type, prev: op.prev, sig: op.sig }
  return {
    type: op.type,
    rotationKeys: op.rotationKeys,
    verificationMethods: op.verificationMethods,
    alsoKnownAs: op.alsoKnownAs,
    services: op.services,
    prev: op.prev,
    sig: op.sig
  }
}

async function plcError (res, ctx) {
  let body = null
  try { body = await res.json() } catch { try { body = await res.text() } catch { /* ignore */ } }
  const msg = (body && body.message) || (body && body.error) || (typeof body === 'string' && body) || res.statusText || 'error'
  const e = new Error('PLC ' + ctx + ' failed (' + res.status + '): ' + msg)
  e.status = res.status
  e.plc = body
  return e
}

// ── the directory client + ceremony (injectable fetch — offline-testable) ──

export class PlcDirectory {
  constructor ({ baseUrl = DEFAULT_PLC, fetchImpl } = {}) {
    const f = fetchImpl || (typeof globalThis.fetch === 'function' ? globalThis.fetch.bind(globalThis) : null)
    if (typeof f !== 'function') throw new Error('PlcDirectory: no fetch available — pass { fetchImpl }')
    this.baseUrl = String(baseUrl).replace(/\/+$/, '')
    this._fetch = f
  }

  async _get (path) {
    const res = await this._fetch(this.baseUrl + path, { method: 'GET' })
    if (!res.ok) throw await plcError(res, 'GET ' + path)
    return res.json()
  }

  // GET /:did/log/last → the head op (normalized to canonical op fields for opCid).
  async getHead (did) { return opFieldsOnly(await this._get('/' + did + '/log/last')) }
  // GET /:did/data → current PLC state { did, verificationMethods, rotationKeys, alsoKnownAs, services }.
  getData (did) { return this._get('/' + did + '/data') }
  // GET /:did → the DID document.
  resolve (did) { return this._get('/' + did) }
  // GET /:did/log/audit → the audit log (incl. nullified ops).
  getAuditLog (did) { return this._get('/' + did + '/log/audit') }

  // POST /:did — the raw irreversible append (body = the signed op, unwrapped). No local check;
  // callers should use submitGenesis / submitUpdate which validate first.
  async submitRaw (did, signedOp) {
    const res = await this._fetch(this.baseUrl + '/' + did, {
      method: 'POST',
      headers: { 'content-type': 'application/json' },
      body: JSON.stringify(signedOp)
    })
    if (!res.ok) throw await plcError(res, 'POST /' + did)
    return true
  }

  // Submit a genesis op: local §6.2 validation → POST → confirm via getData.
  async submitGenesis ({ did, signedOp, confirm = true }) {
    const chk = checkGenesisOp(signedOp, did)
    if (!chk.ok) throw new Error('refusing to submit invalid genesis: ' + chk.error)
    await this.submitRaw(did, signedOp)
    return confirm ? this.getData(did) : true
  }

  // Submit an update op: fetch the LIVE head, require our op chains onto it (prev == opCid(head))
  // AND passes §6 validation, then POST → confirm. Re-fetching the head at submit time closes the
  // build-vs-submit TOCTOU (a MisorderedOperation reject on the live directory otherwise).
  async submitUpdate ({ did, signedOp, confirm = true }) {
    const head = await this.getHead(did)
    if (signedOp.prev !== opCid(head)) throw new Error('refusing to submit: op.prev != live head CID — refetch the head and rebuild')
    const chk = checkUpdateOp(signedOp, head)
    if (!chk.ok) throw new Error('refusing to submit invalid update: ' + chk.error)
    await this.submitRaw(did, signedOp)
    return confirm ? this.getData(did) : true
  }

  // The device-attestation migration primitive: rotate verificationMethods.atproto to a device
  // key on-chain. Fetches the live head, builds a root-signed rotation off it, validates, submits.
  // signerPrivateKey must correspond to a CURRENT rotation key (the root).
  async rotateVerificationMethodOnChain ({ did, newAtprotoDidKey, signerPrivateKey, confirm = true }) {
    const head = await this.getHead(did)
    const op = rotateVerificationMethod({ prevSignedOp: head, newAtprotoDidKey, signerPrivateKey })
    return this.submitUpdate({ did, signedOp: op, confirm })
  }
}
// vault.js — the recovery secret, encrypted so it can be replicated.
//
// WHAT THIS IS FOR. Creating an identity phone-first means minting a did:plc, and whoever holds its
// recovery material can rotate its keys for ever. That secret has to reach the owner's other devices
// somehow, and every obvious channel is worse than this one: retyping 24 words on a handset invites
// transcription errors, a screenshot lands in a cloud photo library, and shipping it in plaintext to
// "attested devices" makes device attestation exactly as strong as the root key it is meant to protect.
//
// ⛔ THE PASSPHRASE IS NEVER STORED, ANYWHERE. That is the whole security argument: the sealed blob is
// designed to be replicated over the same P2P substrate as everything else, so it WILL end up on disks
// we do not control and in the hands of anyone who later joins the identity. It is safe there only
// because it is useless without something that lives in a person's head. If a future change writes the
// passphrase to disk to "make unlock smoother", this file stops being a vault and becomes a very
// elaborate copy of the mnemonic.
//
// ⛔ SEALING IS NOT REVOCATION. A device that once unlocked this vault knows the secret and will keep
// knowing it after you remove the device — see app/Pair.jsx in favela-android, which says the same thing
// about the signing key: removing a device stops it being ADMITTED, it cannot make it forget. The only
// thing that devalues a leaked recovery secret is ROTATING the identity's keys on the PLC log (see
// plc-directory.js rotateVerificationMethodOnChain). This module is how a NEW secret reaches the
// remaining devices; it is not what makes an old one harmless.
//
// ⛔ BOUND TO THE DID. The DID goes in as AEAD additional data, so a blob sealed for one identity cannot
// be silently served in place of another's. A vault that opens under the wrong identity is a vault that
// can be swapped.
//
// Argon2id via sodium-native, XChaCha20-Poly1305 for the seal. Both parameters and salt travel INSIDE
// the envelope: a phone and a workstation have very different tolerances for a KDF, and cost is a thing
// we will want to raise later without stranding blobs sealed today.
import sodium from 'sodium-native'
import b4a from 'b4a'

export const VAULT_VERSION = 1

// Interactive memory (64 MiB) with moderate ops. A handset is the constrained case and this has to run
// there without the OS killing the app; the ops cost carries the weight instead. Recorded per-envelope,
// so raising either later leaves old blobs openable.
const DEFAULT_OPSLIMIT = sodium.crypto_pwhash_OPSLIMIT_MODERATE
const DEFAULT_MEMLIMIT = sodium.crypto_pwhash_MEMLIMIT_INTERACTIVE

const b64 = (buf) => b4a.toString(buf, 'base64')
const unb64 = (s) => b4a.from(s, 'base64')

function deriveKey (passphrase, salt, opslimit, memlimit) {
  const key = b4a.alloc(sodium.crypto_aead_xchacha20poly1305_ietf_KEYBYTES)
  // ⛔ NOT a plain hash. A passphrase people can remember is low-entropy by definition, so the only
  // thing standing between a replicated blob and an offline guessing attack is the KDF's cost. Argon2id
  // is memory-hard, which is what makes that cost real on a GPU too.
  sodium.crypto_pwhash(
    key,
    b4a.from(String(passphrase), 'utf8'),
    salt,
    opslimit,
    memlimit,
    sodium.crypto_pwhash_ALG_ARGON2ID13
  )
  return key
}

/**
 * Seal a recovery secret for one identity.
 *
 * @param {{secret: string, passphrase: string, did: string, opslimit?: number, memlimit?: number}} opts
 * @returns {object} a JSON-safe envelope, safe to replicate
 */
export function sealVault ({ secret, passphrase, did, opslimit = DEFAULT_OPSLIMIT, memlimit = DEFAULT_MEMLIMIT } = {}) {
  if (typeof secret !== 'string' || !secret) throw new Error('secret required')
  // A vault with no passphrase is a file with extra steps, and would be worse than none: it would LOOK
  // encrypted to everyone downstream, including to whoever decides where to replicate it.
  if (typeof passphrase !== 'string' || !passphrase) throw new Error('passphrase required')
  if (typeof did !== 'string' || !did.startsWith('did:')) throw new Error('did required')

  const salt = b4a.alloc(sodium.crypto_pwhash_SALTBYTES)
  sodium.randombytes_buf(salt)
  const nonce = b4a.alloc(sodium.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES)
  sodium.randombytes_buf(nonce)

  const key = deriveKey(passphrase, salt, opslimit, memlimit)
  const message = b4a.from(secret, 'utf8')
  const ct = b4a.alloc(message.length + sodium.crypto_aead_xchacha20poly1305_ietf_ABYTES)
  sodium.crypto_aead_xchacha20poly1305_ietf_encrypt(ct, message, b4a.from(did, 'utf8'), null, nonce, key)
  sodium.sodium_memzero(key)
  sodium.sodium_memzero(message)

  return {
    v: VAULT_VERSION,
    did,
    kdf: { alg: 'argon2id13', opslimit, memlimit, salt: b64(salt) },
    aead: 'xchacha20poly1305-ietf',
    nonce: b64(nonce),
    ct: b64(ct)
  }
}

/**
 * Open a sealed vault. Throws on a wrong passphrase, a tampered blob, or the wrong identity — all three
 * are the same AEAD failure and are deliberately NOT distinguished in the message: telling a caller
 * which one failed tells an attacker which half they got right.
 */
export function openVault ({ envelope, passphrase, did } = {}) {
  const e = envelope
  if (!e || typeof e !== 'object') throw new Error('envelope required')
  if (e.v !== VAULT_VERSION) throw new Error('unsupported vault version: ' + e.v)
  if (e.aead !== 'xchacha20poly1305-ietf') throw new Error('unsupported aead: ' + e.aead)
  if (!e.kdf || e.kdf.alg !== 'argon2id13') throw new Error('unsupported kdf: ' + (e.kdf && e.kdf.alg))
  if (typeof passphrase !== 'string' || !passphrase) throw new Error('passphrase required')

  // The caller says which identity it BELIEVES this vault is for, and the AEAD refuses if it disagrees.
  // Defaulting to the envelope's own `did` would let a swapped blob authenticate itself.
  const forDid = typeof did === 'string' && did ? did : e.did
  if (typeof forDid !== 'string' || !forDid.startsWith('did:')) throw new Error('did required')

  const salt = unb64(e.kdf.salt)
  const nonce = unb64(e.nonce)
  const ct = unb64(e.ct)
  if (salt.length !== sodium.crypto_pwhash_SALTBYTES) throw new Error('malformed vault: salt')
  if (nonce.length !== sodium.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES) throw new Error('malformed vault: nonce')
  if (ct.length < sodium.crypto_aead_xchacha20poly1305_ietf_ABYTES) throw new Error('malformed vault: ciphertext')

  const key = deriveKey(passphrase, salt, e.kdf.opslimit, e.kdf.memlimit)
  const out = b4a.alloc(ct.length - sodium.crypto_aead_xchacha20poly1305_ietf_ABYTES)
  try {
    sodium.crypto_aead_xchacha20poly1305_ietf_decrypt(out, null, ct, b4a.from(forDid, 'utf8'), nonce, key)
  } catch {
    throw new Error('could not open the vault')
  } finally {
    sodium.sodium_memzero(key)
  }
  const secret = b4a.toString(out, 'utf8')
  sodium.sodium_memzero(out)
  return secret
}

/**
 * Re-seal an already-open secret under a new passphrase.
 *
 * Separate from sealVault so the caller cannot accidentally change WHICH identity a vault is for while
 * changing its passphrase — the did is carried over, not re-supplied.
 */
export function rekeyVault ({ envelope, passphrase, newPassphrase, did, ...rest } = {}) {
  const secret = openVault({ envelope, passphrase, did })
  return sealVault({ secret, passphrase: newPassphrase, did: (typeof did === 'string' && did) ? did : envelope.did, ...rest })
}
{
  "name": "@ipld/dag-cbor",
  "version": "9.2.7",
  "description": "JS implementation of DAG-CBOR",
  "author": "Rod <rod@vagg.org> (http://r.va.gg/)",
  "license": "Apache-2.0 OR MIT",
  "homepage": "https://github.com/ipld/js-dag-cbor#readme",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/ipld/js-dag-cbor.git"
  },
  "bugs": {
    "url": "https://github.com/ipld/js-dag-cbor/issues"
  },
  "publishConfig": {
    "access": "public",
    "provenance": true
  },
  "keywords": [
    "ipfs",
    "ipld",
    "multiformats"
  ],
  "type": "module",
  "types": "./dist/src/index.d.ts",
  "typesVersions": {
    "*": {
      "*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ],
      "src/*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ]
    }
  },
  "files": [
    "src",
    "dist",
    "!dist/test",
    "!**/*.tsbuildinfo"
  ],
  "exports": {
    ".": {
      "types": "./dist/src/index.d.ts",
      "import": "./src/index.js",
      "module-sync": "./src/index.js"
    }
  },
  "release": {
    "branches": [
      "master"
    ],
    "plugins": [
      [
        "@semantic-release/commit-analyzer",
        {
          "preset": "conventionalcommits",
          "releaseRules": [
            {
              "breaking": true,
              "release": "major"
            },
            {
              "revert": true,
              "release": "patch"
            },
            {
              "type": "feat",
              "release": "minor"
            },
            {
              "type": "fix",
              "release": "patch"
            },
            {
              "type": "docs",
              "release": "patch"
            },
            {
              "type": "test",
              "release": "patch"
            },
            {
              "type": "deps",
              "release": "patch"
            },
            {
              "scope": "no-release",
              "release": false
            }
          ]
        }
      ],
      [
        "@semantic-release/release-notes-generator",
        {
          "preset": "conventionalcommits",
          "presetConfig": {
            "types": [
              {
                "type": "feat",
                "section": "Features"
              },
              {
                "type": "fix",
                "section": "Bug Fixes"
              },
              {
                "type": "chore",
                "section": "Trivial Changes"
              },
              {
                "type": "docs",
                "section": "Documentation"
              },
              {
                "type": "deps",
                "section": "Dependencies"
              },
              {
                "type": "test",
                "section": "Tests"
              }
            ]
          }
        }
      ],
      "@semantic-release/changelog",
      "@semantic-release/npm",
      "@semantic-release/github",
      [
        "@semantic-release/git",
        {
          "assets": [
            "CHANGELOG.md",
            "package.json"
          ]
        }
      ]
    ]
  },
  "scripts": {
    "clean": "aegir clean",
    "lint": "aegir lint",
    "build": "aegir build",
    "release": "aegir release",
    "test": "npm run lint && aegir test",
    "test:ts": "npm run test --prefix test/ts-use",
    "test:node": "aegir test -t node --cov",
    "test:chrome": "aegir test -t browser --cov",
    "test:chrome-webworker": "aegir test -t webworker",
    "test:firefox": "aegir test -t browser -- --browser firefox",
    "test:firefox-webworker": "aegir test -t webworker -- --browser firefox",
    "test:electron-main": "aegir test -t electron-main",
    "dep-check": "aegir dep-check"
  },
  "dependencies": {
    "cborg": "^5.0.1",
    "multiformats": "^13.1.0"
  },
  "devDependencies": {
    "@ipld/garbage": "^6.0.0",
    "aegir": "^48.0.1"
  }
}
import * as cborg from 'cborg'
import { CID } from 'multiformats/cid'

// https://github.com/ipfs/go-ipfs/issues/3570#issuecomment-273931692
const CID_CBOR_TAG = 42

/**
 * @template T
 * @typedef {import('multiformats/codecs/interface').ByteView<T>} ByteView
 */

/**
 * @template T
 * @typedef {import('multiformats/codecs/interface').ArrayBufferView<T>} ArrayBufferView
 */

/**
 * @template T
 * @param {ByteView<T> | ArrayBufferView<T>} buf
 * @returns {ByteView<T>}
 */
export function toByteView (buf) {
  if (buf instanceof ArrayBuffer) {
    return new Uint8Array(buf, 0, buf.byteLength)
  }

  return buf
}

/**
 * cidEncoder will receive all Objects during encode, it needs to filter out
 * anything that's not a CID and return `null` for that so it's encoded as
 * normal.
 *
 * @param {any} obj
 * @returns {cborg.Token[]|null}
 */
function cidEncoder (obj) {
  if (obj.asCID !== obj && obj['/'] !== obj.bytes) {
    return null // any other kind of object
  }
  const cid = CID.asCID(obj)
  /* c8 ignore next 4 */
  // very unlikely case, and it'll probably throw a recursion error in cborg
  if (!cid) {
    return null
  }
  const bytes = new Uint8Array(cid.bytes.byteLength + 1)
  bytes.set(cid.bytes, 1) // prefix is 0x00, for historical reasons
  return [
    new cborg.Token(cborg.Type.tag, CID_CBOR_TAG),
    new cborg.Token(cborg.Type.bytes, bytes)
  ]
}

// eslint-disable-next-line jsdoc/require-returns-check
/**
 * Intercept all `undefined` values from an object walk and reject the entire
 * object if we find one.
 *
 * @returns {null}
 */
function undefinedEncoder () {
  throw new Error('`undefined` is not supported by the IPLD Data Model and cannot be encoded')
}

/**
 * Intercept all `number` values from an object walk and reject the entire
 * object if we find something that doesn't fit the IPLD data model (NaN &
 * Infinity).
 *
 * @param {number} num
 * @returns {null}
 */
function numberEncoder (num) {
  if (Number.isNaN(num)) {
    throw new Error('`NaN` is not supported by the IPLD Data Model and cannot be encoded')
  }
  if (num === Infinity || num === -Infinity) {
    throw new Error('`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded')
  }
  return null
}

/**
 * @param {Map<any, any>} map
 * @returns {null}
 */
function mapEncoder (map) {
  for (const key of map.keys()) {
    if (typeof key !== 'string' || key.length === 0) {
      throw new Error('Non-string Map keys are not supported by the IPLD Data Model and cannot be encoded')
    }
  }
  return null
}

const _encodeOptions = {
  float64: true,
  typeEncoders: {
    Map: mapEncoder,
    Object: cidEncoder,
    undefined: undefinedEncoder,
    number: numberEncoder
  }
}

export const encodeOptions = {
  ..._encodeOptions,
  typeEncoders: {
    ..._encodeOptions.typeEncoders
  }
}

/**
 * @param {import('cborg').TagDecodeControl} decode
 * @returns {CID}
 */
function cidDecoder (decode) {
  const bytes = /** @type {Uint8Array} */ (decode())
  if (bytes[0] !== 0) {
    throw new Error('Invalid CID for CBOR tag 42; expected leading 0x00')
  }
  return CID.decode(bytes.subarray(1)) // ignore leading 0x00
}

const _decodeOptions = {
  allowIndefinite: false,
  coerceUndefinedToNull: true,
  allowNaN: false,
  allowInfinity: false,
  allowBigInt: true, // this will lead to BigInt for ints outside of
  // safe-integer range, which may surprise users
  strict: true,
  useMaps: false,
  rejectDuplicateMapKeys: true,
  /** @type {{ [tagNumber: number]: import('cborg').TagDecoder }} */
  tags: { [CID_CBOR_TAG]: cidDecoder }
}

export const decodeOptions = {
  ..._decodeOptions,
  tags: { ..._decodeOptions.tags }
}

export const name = 'dag-cbor'
export const code = 0x71

/**
 * @template T
 * @param {T} node
 * @returns {ByteView<T>}
 */
export const encode = (node) => cborg.encode(node, _encodeOptions)

/**
 * @template T
 * @param {ByteView<T> | ArrayBufferView<T>} data
 * @returns {T}
 */
export const decode = (data) => cborg.decode(toByteView(data), _decodeOptions)
/**
 * Utilities for short weierstrass curves, combined with noble-hashes.
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { weierstrass } from "./abstract/weierstrass.js";
/** connects noble-curves to noble-hashes */
export function getHash(hash) {
    return { hash };
}
/** @deprecated use new `weierstrass()` and `ecdsa()` methods */
export function createCurve(curveDef, defHash) {
    const create = (hash) => weierstrass({ ...curveDef, hash: hash });
    return { ...create(defHash), create };
}
//# sourceMappingURL=_shortw_utils.js.map/**
 * Methods for elliptic curve multiplication by scalars.
 * Contains wNAF, pippenger.
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { bitLen, bitMask, validateObject } from "../utils.js";
import { Field, FpInvertBatch, nLength, validateField } from "./modular.js";
const _0n = BigInt(0);
const _1n = BigInt(1);
export function negateCt(condition, item) {
    const neg = item.negate();
    return condition ? neg : item;
}
/**
 * Takes a bunch of Projective Points but executes only one
 * inversion on all of them. Inversion is very slow operation,
 * so this improves performance massively.
 * Optimization: converts a list of projective points to a list of identical points with Z=1.
 */
export function normalizeZ(c, points) {
    const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
    return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
}
function validateW(W, bits) {
    if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
        throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);
}
function calcWOpts(W, scalarBits) {
    validateW(W, scalarBits);
    const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero
    const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero
    const maxNumber = 2 ** W; // W=8 256
    const mask = bitMask(W); // W=8 255 == mask 0b11111111
    const shiftBy = BigInt(W); // W=8 8
    return { windows, windowSize, mask, maxNumber, shiftBy };
}
function calcOffsets(n, window, wOpts) {
    const { windowSize, mask, maxNumber, shiftBy } = wOpts;
    let wbits = Number(n & mask); // extract W bits.
    let nextN = n >> shiftBy; // shift number by W bits.
    // What actually happens here:
    // const highestBit = Number(mask ^ (mask >> 1n));
    // let wbits2 = wbits - 1; // skip zero
    // if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);
    // split if bits > max: +224 => 256-32
    if (wbits > windowSize) {
        // we skip zero, which means instead of `>= size-1`, we do `> size`
        wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.
        nextN += _1n; // +256 (carry)
    }
    const offsetStart = window * windowSize;
    const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero
    const isZero = wbits === 0; // is current window slice a 0?
    const isNeg = wbits < 0; // is current window slice negative?
    const isNegF = window % 2 !== 0; // fake random statement for noise
    const offsetF = offsetStart; // fake offset for noise
    return { nextN, offset, isZero, isNeg, isNegF, offsetF };
}
function validateMSMPoints(points, c) {
    if (!Array.isArray(points))
        throw new Error('array expected');
    points.forEach((p, i) => {
        if (!(p instanceof c))
            throw new Error('invalid point at index ' + i);
    });
}
function validateMSMScalars(scalars, field) {
    if (!Array.isArray(scalars))
        throw new Error('array of scalars expected');
    scalars.forEach((s, i) => {
        if (!field.isValid(s))
            throw new Error('invalid scalar at index ' + i);
    });
}
// Since points in different groups cannot be equal (different object constructor),
// we can have single place to store precomputes.
// Allows to make points frozen / immutable.
const pointPrecomputes = new WeakMap();
const pointWindowSizes = new WeakMap();
function getW(P) {
    // To disable precomputes:
    // return 1;
    return pointWindowSizes.get(P) || 1;
}
function assert0(n) {
    if (n !== _0n)
        throw new Error('invalid wNAF');
}
/**
 * Elliptic curve multiplication of Point by scalar. Fragile.
 * Table generation takes **30MB of ram and 10ms on high-end CPU**,
 * but may take much longer on slow devices. Actual generation will happen on
 * first call of `multiply()`. By default, `BASE` point is precomputed.
 *
 * Scalars should always be less than curve order: this should be checked inside of a curve itself.
 * Creates precomputation tables for fast multiplication:
 * - private scalar is split by fixed size windows of W bits
 * - every window point is collected from window's table & added to accumulator
 * - since windows are different, same point inside tables won't be accessed more than once per calc
 * - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)
 * - +1 window is neccessary for wNAF
 * - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication
 *
 * @todo Research returning 2d JS array of windows, instead of a single window.
 * This would allow windows to be in different memory locations
 */
export class wNAF {
    // Parametrized with a given Point class (not individual point)
    constructor(Point, bits) {
        this.BASE = Point.BASE;
        this.ZERO = Point.ZERO;
        this.Fn = Point.Fn;
        this.bits = bits;
    }
    // non-const time multiplication ladder
    _unsafeLadder(elm, n, p = this.ZERO) {
        let d = elm;
        while (n > _0n) {
            if (n & _1n)
                p = p.add(d);
            d = d.double();
            n >>= _1n;
        }
        return p;
    }
    /**
     * Creates a wNAF precomputation window. Used for caching.
     * Default window size is set by `utils.precompute()` and is equal to 8.
     * Number of precomputed points depends on the curve size:
     * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
     * - 𝑊 is the window size
     * - 𝑛 is the bitlength of the curve order.
     * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
     * @param point Point instance
     * @param W window size
     * @returns precomputed point tables flattened to a single array
     */
    precomputeWindow(point, W) {
        const { windows, windowSize } = calcWOpts(W, this.bits);
        const points = [];
        let p = point;
        let base = p;
        for (let window = 0; window < windows; window++) {
            base = p;
            points.push(base);
            // i=1, bc we skip 0
            for (let i = 1; i < windowSize; i++) {
                base = base.add(p);
                points.push(base);
            }
            p = base.double();
        }
        return points;
    }
    /**
     * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
     * More compact implementation:
     * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
     * @returns real and fake (for const-time) points
     */
    wNAF(W, precomputes, n) {
        // Scalar should be smaller than field order
        if (!this.Fn.isValid(n))
            throw new Error('invalid scalar');
        // Accumulators
        let p = this.ZERO;
        let f = this.BASE;
        // This code was first written with assumption that 'f' and 'p' will never be infinity point:
        // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,
        // there is negate now: it is possible that negated element from low value
        // would be the same as high element, which will create carry into next window.
        // It's not obvious how this can fail, but still worth investigating later.
        const wo = calcWOpts(W, this.bits);
        for (let window = 0; window < wo.windows; window++) {
            // (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise
            const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
            n = nextN;
            if (isZero) {
                // bits are 0: add garbage to fake point
                // Important part for const-time getPublicKey: add random "noise" point to f.
                f = f.add(negateCt(isNegF, precomputes[offsetF]));
            }
            else {
                // bits are 1: add to result point
                p = p.add(negateCt(isNeg, precomputes[offset]));
            }
        }
        assert0(n);
        // Return both real and fake points: JIT won't eliminate f.
        // At this point there is a way to F be infinity-point even if p is not,
        // which makes it less const-time: around 1 bigint multiply.
        return { p, f };
    }
    /**
     * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
     * @param acc accumulator point to add result of multiplication
     * @returns point
     */
    wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
        const wo = calcWOpts(W, this.bits);
        for (let window = 0; window < wo.windows; window++) {
            if (n === _0n)
                break; // Early-exit, skip 0 value
            const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
            n = nextN;
            if (isZero) {
                // Window bits are 0: skip processing.
                // Move to next window.
                continue;
            }
            else {
                const item = precomputes[offset];
                acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM
            }
        }
        assert0(n);
        return acc;
    }
    getPrecomputes(W, point, transform) {
        // Calculate precomputes on a first run, reuse them after
        let comp = pointPrecomputes.get(point);
        if (!comp) {
            comp = this.precomputeWindow(point, W);
            if (W !== 1) {
                // Doing transform outside of if brings 15% perf hit
                if (typeof transform === 'function')
                    comp = transform(comp);
                pointPrecomputes.set(point, comp);
            }
        }
        return comp;
    }
    cached(point, scalar, transform) {
        const W = getW(point);
        return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
    }
    unsafe(point, scalar, transform, prev) {
        const W = getW(point);
        if (W === 1)
            return this._unsafeLadder(point, scalar, prev); // For W=1 ladder is ~x2 faster
        return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
    }
    // We calculate precomputes for elliptic curve point multiplication
    // using windowed method. This specifies window size and
    // stores precomputed values. Usually only base point would be precomputed.
    createCache(P, W) {
        validateW(W, this.bits);
        pointWindowSizes.set(P, W);
        pointPrecomputes.delete(P);
    }
    hasCache(elm) {
        return getW(elm) !== 1;
    }
}
/**
 * Endomorphism-specific multiplication for Koblitz curves.
 * Cost: 128 dbl, 0-256 adds.
 */
export function mulEndoUnsafe(Point, point, k1, k2) {
    let acc = point;
    let p1 = Point.ZERO;
    let p2 = Point.ZERO;
    while (k1 > _0n || k2 > _0n) {
        if (k1 & _1n)
            p1 = p1.add(acc);
        if (k2 & _1n)
            p2 = p2.add(acc);
        acc = acc.double();
        k1 >>= _1n;
        k2 >>= _1n;
    }
    return { p1, p2 };
}
/**
 * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).
 * 30x faster vs naive addition on L=4096, 10x faster than precomputes.
 * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.
 * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.
 * @param c Curve Point constructor
 * @param fieldN field over CURVE.N - important that it's not over CURVE.P
 * @param points array of L curve points
 * @param scalars array of L scalars (aka secret keys / bigints)
 */
export function pippenger(c, fieldN, points, scalars) {
    // If we split scalars by some window (let's say 8 bits), every chunk will only
    // take 256 buckets even if there are 4096 scalars, also re-uses double.
    // TODO:
    // - https://eprint.iacr.org/2024/750.pdf
    // - https://tches.iacr.org/index.php/TCHES/article/view/10287
    // 0 is accepted in scalars
    validateMSMPoints(points, c);
    validateMSMScalars(scalars, fieldN);
    const plength = points.length;
    const slength = scalars.length;
    if (plength !== slength)
        throw new Error('arrays of points and scalars must have equal length');
    // if (plength === 0) throw new Error('array must be of length >= 2');
    const zero = c.ZERO;
    const wbits = bitLen(BigInt(plength));
    let windowSize = 1; // bits
    if (wbits > 12)
        windowSize = wbits - 3;
    else if (wbits > 4)
        windowSize = wbits - 2;
    else if (wbits > 0)
        windowSize = 2;
    const MASK = bitMask(windowSize);
    const buckets = new Array(Number(MASK) + 1).fill(zero); // +1 for zero array
    const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;
    let sum = zero;
    for (let i = lastBits; i >= 0; i -= windowSize) {
        buckets.fill(zero);
        for (let j = 0; j < slength; j++) {
            const scalar = scalars[j];
            const wbits = Number((scalar >> BigInt(i)) & MASK);
            buckets[wbits] = buckets[wbits].add(points[j]);
        }
        let resI = zero; // not using this will do small speed-up, but will lose ct
        // Skip first bucket, because it is zero
        for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {
            sumI = sumI.add(buckets[j]);
            resI = resI.add(sumI);
        }
        sum = sum.add(resI);
        if (i !== 0)
            for (let j = 0; j < windowSize; j++)
                sum = sum.double();
    }
    return sum;
}
/**
 * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).
 * @param c Curve Point constructor
 * @param fieldN field over CURVE.N - important that it's not over CURVE.P
 * @param points array of L curve points
 * @returns function which multiplies points with scaars
 */
export function precomputeMSMUnsafe(c, fieldN, points, windowSize) {
    /**
     * Performance Analysis of Window-based Precomputation
     *
     * Base Case (256-bit scalar, 8-bit window):
     * - Standard precomputation requires:
     *   - 31 additions per scalar × 256 scalars = 7,936 ops
     *   - Plus 255 summary additions = 8,191 total ops
     *   Note: Summary additions can be optimized via accumulator
     *
     * Chunked Precomputation Analysis:
     * - Using 32 chunks requires:
     *   - 255 additions per chunk
     *   - 256 doublings
     *   - Total: (255 × 32) + 256 = 8,416 ops
     *
     * Memory Usage Comparison:
     * Window Size | Standard Points | Chunked Points
     * ------------|-----------------|---------------
     *     4-bit   |     520         |      15
     *     8-bit   |    4,224        |     255
     *    10-bit   |   13,824        |   1,023
     *    16-bit   |  557,056        |  65,535
     *
     * Key Advantages:
     * 1. Enables larger window sizes due to reduced memory overhead
     * 2. More efficient for smaller scalar counts:
     *    - 16 chunks: (16 × 255) + 256 = 4,336 ops
     *    - ~2x faster than standard 8,191 ops
     *
     * Limitations:
     * - Not suitable for plain precomputes (requires 256 constant doublings)
     * - Performance degrades with larger scalar counts:
     *   - Optimal for ~256 scalars
     *   - Less efficient for 4096+ scalars (Pippenger preferred)
     */
    validateW(windowSize, fieldN.BITS);
    validateMSMPoints(points, c);
    const zero = c.ZERO;
    const tableSize = 2 ** windowSize - 1; // table size (without zero)
    const chunks = Math.ceil(fieldN.BITS / windowSize); // chunks of item
    const MASK = bitMask(windowSize);
    const tables = points.map((p) => {
        const res = [];
        for (let i = 0, acc = p; i < tableSize; i++) {
            res.push(acc);
            acc = acc.add(p);
        }
        return res;
    });
    return (scalars) => {
        validateMSMScalars(scalars, fieldN);
        if (scalars.length > points.length)
            throw new Error('array of scalars must be smaller than array of points');
        let res = zero;
        for (let i = 0; i < chunks; i++) {
            // No need to double if accumulator is still zero.
            if (res !== zero)
                for (let j = 0; j < windowSize; j++)
                    res = res.double();
            const shiftBy = BigInt(chunks * windowSize - (i + 1) * windowSize);
            for (let j = 0; j < scalars.length; j++) {
                const n = scalars[j];
                const curr = Number((n >> shiftBy) & MASK);
                if (!curr)
                    continue; // skip zero scalars chunks
                res = res.add(tables[j][curr - 1]);
            }
        }
        return res;
    };
}
// TODO: remove
/** @deprecated */
export function validateBasic(curve) {
    validateField(curve.Fp);
    validateObject(curve, {
        n: 'bigint',
        h: 'bigint',
        Gx: 'field',
        Gy: 'field',
    }, {
        nBitLength: 'isSafeInteger',
        nByteLength: 'isSafeInteger',
    });
    // Set defaults
    return Object.freeze({
        ...nLength(curve.n, curve.nBitLength),
        ...curve,
        ...{ p: curve.Fp.ORDER },
    });
}
function createField(order, field, isLE) {
    if (field) {
        if (field.ORDER !== order)
            throw new Error('Field.ORDER must match order: Fp == p, Fn == n');
        validateField(field);
        return field;
    }
    else {
        return Field(order, { isLE });
    }
}
/** Validates CURVE opts and creates fields */
export function _createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
    if (FpFnLE === undefined)
        FpFnLE = type === 'edwards';
    if (!CURVE || typeof CURVE !== 'object')
        throw new Error(`expected valid ${type} CURVE object`);
    for (const p of ['p', 'n', 'h']) {
        const val = CURVE[p];
        if (!(typeof val === 'bigint' && val > _0n))
            throw new Error(`CURVE.${p} must be positive bigint`);
    }
    const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);
    const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
    const _b = type === 'weierstrass' ? 'b' : 'd';
    const params = ['Gx', 'Gy', 'a', _b];
    for (const p of params) {
        // @ts-ignore
        if (!Fp.isValid(CURVE[p]))
            throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
    }
    CURVE = Object.freeze(Object.assign({}, CURVE));
    return { CURVE, Fp, Fn };
}
//# sourceMappingURL=curve.js.mapimport { _validateObject, abytes, bytesToNumberBE, concatBytes, isBytes, isHash, utf8ToBytes, } from "../utils.js";
import { FpInvertBatch, mod } from "./modular.js";
// Octet Stream to Integer. "spec" implementation of os2ip is 2.5x slower vs bytesToNumberBE.
const os2ip = bytesToNumberBE;
// Integer to Octet Stream (numberToBytesBE)
function i2osp(value, length) {
    anum(value);
    anum(length);
    if (value < 0 || value >= 1 << (8 * length))
        throw new Error('invalid I2OSP input: ' + value);
    const res = Array.from({ length }).fill(0);
    for (let i = length - 1; i >= 0; i--) {
        res[i] = value & 0xff;
        value >>>= 8;
    }
    return new Uint8Array(res);
}
function strxor(a, b) {
    const arr = new Uint8Array(a.length);
    for (let i = 0; i < a.length; i++) {
        arr[i] = a[i] ^ b[i];
    }
    return arr;
}
function anum(item) {
    if (!Number.isSafeInteger(item))
        throw new Error('number expected');
}
function normDST(DST) {
    if (!isBytes(DST) && typeof DST !== 'string')
        throw new Error('DST must be Uint8Array or string');
    return typeof DST === 'string' ? utf8ToBytes(DST) : DST;
}
/**
 * Produces a uniformly random byte string using a cryptographic hash function H that outputs b bits.
 * [RFC 9380 5.3.1](https://www.rfc-editor.org/rfc/rfc9380#section-5.3.1).
 */
export function expand_message_xmd(msg, DST, lenInBytes, H) {
    abytes(msg);
    anum(lenInBytes);
    DST = normDST(DST);
    // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3
    if (DST.length > 255)
        DST = H(concatBytes(utf8ToBytes('H2C-OVERSIZE-DST-'), DST));
    const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H;
    const ell = Math.ceil(lenInBytes / b_in_bytes);
    if (lenInBytes > 65535 || ell > 255)
        throw new Error('expand_message_xmd: invalid lenInBytes');
    const DST_prime = concatBytes(DST, i2osp(DST.length, 1));
    const Z_pad = i2osp(0, r_in_bytes);
    const l_i_b_str = i2osp(lenInBytes, 2); // len_in_bytes_str
    const b = new Array(ell);
    const b_0 = H(concatBytes(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));
    b[0] = H(concatBytes(b_0, i2osp(1, 1), DST_prime));
    for (let i = 1; i <= ell; i++) {
        const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime];
        b[i] = H(concatBytes(...args));
    }
    const pseudo_random_bytes = concatBytes(...b);
    return pseudo_random_bytes.slice(0, lenInBytes);
}
/**
 * Produces a uniformly random byte string using an extendable-output function (XOF) H.
 * 1. The collision resistance of H MUST be at least k bits.
 * 2. H MUST be an XOF that has been proved indifferentiable from
 *    a random oracle under a reasonable cryptographic assumption.
 * [RFC 9380 5.3.2](https://www.rfc-editor.org/rfc/rfc9380#section-5.3.2).
 */
export function expand_message_xof(msg, DST, lenInBytes, k, H) {
    abytes(msg);
    anum(lenInBytes);
    DST = normDST(DST);
    // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3
    // DST = H('H2C-OVERSIZE-DST-' || a_very_long_DST, Math.ceil((lenInBytes * k) / 8));
    if (DST.length > 255) {
        const dkLen = Math.ceil((2 * k) / 8);
        DST = H.create({ dkLen }).update(utf8ToBytes('H2C-OVERSIZE-DST-')).update(DST).digest();
    }
    if (lenInBytes > 65535 || DST.length > 255)
        throw new Error('expand_message_xof: invalid lenInBytes');
    return (H.create({ dkLen: lenInBytes })
        .update(msg)
        .update(i2osp(lenInBytes, 2))
        // 2. DST_prime = DST || I2OSP(len(DST), 1)
        .update(DST)
        .update(i2osp(DST.length, 1))
        .digest());
}
/**
 * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F.
 * [RFC 9380 5.2](https://www.rfc-editor.org/rfc/rfc9380#section-5.2).
 * @param msg a byte string containing the message to hash
 * @param count the number of elements of F to output
 * @param options `{DST: string, p: bigint, m: number, k: number, expand: 'xmd' | 'xof', hash: H}`, see above
 * @returns [u_0, ..., u_(count - 1)], a list of field elements.
 */
export function hash_to_field(msg, count, options) {
    _validateObject(options, {
        p: 'bigint',
        m: 'number',
        k: 'number',
        hash: 'function',
    });
    const { p, k, m, hash, expand, DST } = options;
    if (!isHash(options.hash))
        throw new Error('expected valid hash');
    abytes(msg);
    anum(count);
    const log2p = p.toString(2).length;
    const L = Math.ceil((log2p + k) / 8); // section 5.1 of ietf draft link above
    const len_in_bytes = count * m * L;
    let prb; // pseudo_random_bytes
    if (expand === 'xmd') {
        prb = expand_message_xmd(msg, DST, len_in_bytes, hash);
    }
    else if (expand === 'xof') {
        prb = expand_message_xof(msg, DST, len_in_bytes, k, hash);
    }
    else if (expand === '_internal_pass') {
        // for internal tests only
        prb = msg;
    }
    else {
        throw new Error('expand must be "xmd" or "xof"');
    }
    const u = new Array(count);
    for (let i = 0; i < count; i++) {
        const e = new Array(m);
        for (let j = 0; j < m; j++) {
            const elm_offset = L * (j + i * m);
            const tv = prb.subarray(elm_offset, elm_offset + L);
            e[j] = mod(os2ip(tv), p);
        }
        u[i] = e;
    }
    return u;
}
export function isogenyMap(field, map) {
    // Make same order as in spec
    const coeff = map.map((i) => Array.from(i).reverse());
    return (x, y) => {
        const [xn, xd, yn, yd] = coeff.map((val) => val.reduce((acc, i) => field.add(field.mul(acc, x), i)));
        // 6.6.3
        // Exceptional cases of iso_map are inputs that cause the denominator of
        // either rational function to evaluate to zero; such cases MUST return
        // the identity point on E.
        const [xd_inv, yd_inv] = FpInvertBatch(field, [xd, yd], true);
        x = field.mul(xn, xd_inv); // xNum / xDen
        y = field.mul(y, field.mul(yn, yd_inv)); // y * (yNum / yDev)
        return { x, y };
    };
}
export const _DST_scalar = utf8ToBytes('HashToScalar-');
/** Creates hash-to-curve methods from EC Point and mapToCurve function. See {@link H2CHasher}. */
export function createHasher(Point, mapToCurve, defaults) {
    if (typeof mapToCurve !== 'function')
        throw new Error('mapToCurve() must be defined');
    function map(num) {
        return Point.fromAffine(mapToCurve(num));
    }
    function clear(initial) {
        const P = initial.clearCofactor();
        if (P.equals(Point.ZERO))
            return Point.ZERO; // zero will throw in assert
        P.assertValidity();
        return P;
    }
    return {
        defaults,
        hashToCurve(msg, options) {
            const opts = Object.assign({}, defaults, options);
            const u = hash_to_field(msg, 2, opts);
            const u0 = map(u[0]);
            const u1 = map(u[1]);
            return clear(u0.add(u1));
        },
        encodeToCurve(msg, options) {
            const optsDst = defaults.encodeDST ? { DST: defaults.encodeDST } : {};
            const opts = Object.assign({}, defaults, optsDst, options);
            const u = hash_to_field(msg, 1, opts);
            const u0 = map(u[0]);
            return clear(u0);
        },
        /** See {@link H2CHasher} */
        mapToCurve(scalars) {
            if (!Array.isArray(scalars))
                throw new Error('expected array of bigints');
            for (const i of scalars)
                if (typeof i !== 'bigint')
                    throw new Error('expected array of bigints');
            return clear(map(scalars));
        },
        // hash_to_scalar can produce 0: https://www.rfc-editor.org/errata/eid8393
        // RFC 9380, draft-irtf-cfrg-bbs-signatures-08
        hashToScalar(msg, options) {
            // @ts-ignore
            const N = Point.Fn.ORDER;
            const opts = Object.assign({}, defaults, { p: N, m: 1, DST: _DST_scalar }, options);
            return hash_to_field(msg, 1, opts)[0][0];
        },
    };
}
//# sourceMappingURL=hash-to-curve.js.map/**
 * Utils for modular division and fields.
 * Field over 11 is a finite (Galois) field is integer number operations `mod 11`.
 * There is no division: it is replaced by modular multiplicative inverse.
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { _validateObject, anumber, bitMask, bytesToNumberBE, bytesToNumberLE, ensureBytes, numberToBytesBE, numberToBytesLE, } from "../utils.js";
// prettier-ignore
const _0n = BigInt(0), _1n = BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3);
// prettier-ignore
const _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5), _7n = /* @__PURE__ */ BigInt(7);
// prettier-ignore
const _8n = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9), _16n = /* @__PURE__ */ BigInt(16);
// Calculates a modulo b
export function mod(a, b) {
    const result = a % b;
    return result >= _0n ? result : b + result;
}
/**
 * Efficiently raise num to power and do modular division.
 * Unsafe in some contexts: uses ladder, so can expose bigint bits.
 * @example
 * pow(2n, 6n, 11n) // 64n % 11n == 9n
 */
export function pow(num, power, modulo) {
    return FpPow(Field(modulo), num, power);
}
/** Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)` */
export function pow2(x, power, modulo) {
    let res = x;
    while (power-- > _0n) {
        res *= res;
        res %= modulo;
    }
    return res;
}
/**
 * Inverses number over modulo.
 * Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).
 */
export function invert(number, modulo) {
    if (number === _0n)
        throw new Error('invert: expected non-zero number');
    if (modulo <= _0n)
        throw new Error('invert: expected positive modulus, got ' + modulo);
    // Fermat's little theorem "CT-like" version inv(n) = n^(m-2) mod m is 30x slower.
    let a = mod(number, modulo);
    let b = modulo;
    // prettier-ignore
    let x = _0n, y = _1n, u = _1n, v = _0n;
    while (a !== _0n) {
        // JIT applies optimization if those two lines follow each other
        const q = b / a;
        const r = b % a;
        const m = x - u * q;
        const n = y - v * q;
        // prettier-ignore
        b = a, a = r, x = u, y = v, u = m, v = n;
    }
    const gcd = b;
    if (gcd !== _1n)
        throw new Error('invert: does not exist');
    return mod(x, modulo);
}
function assertIsSquare(Fp, root, n) {
    if (!Fp.eql(Fp.sqr(root), n))
        throw new Error('Cannot find square root');
}
// Not all roots are possible! Example which will throw:
// const NUM =
// n = 72057594037927816n;
// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));
function sqrt3mod4(Fp, n) {
    const p1div4 = (Fp.ORDER + _1n) / _4n;
    const root = Fp.pow(n, p1div4);
    assertIsSquare(Fp, root, n);
    return root;
}
function sqrt5mod8(Fp, n) {
    const p5div8 = (Fp.ORDER - _5n) / _8n;
    const n2 = Fp.mul(n, _2n);
    const v = Fp.pow(n2, p5div8);
    const nv = Fp.mul(n, v);
    const i = Fp.mul(Fp.mul(nv, _2n), v);
    const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
    assertIsSquare(Fp, root, n);
    return root;
}
// Based on RFC9380, Kong algorithm
// prettier-ignore
function sqrt9mod16(P) {
    const Fp_ = Field(P);
    const tn = tonelliShanks(P);
    const c1 = tn(Fp_, Fp_.neg(Fp_.ONE)); //  1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F
    const c2 = tn(Fp_, c1); //  2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F
    const c3 = tn(Fp_, Fp_.neg(c1)); //  3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F
    const c4 = (P + _7n) / _16n; //  4. c4 = (q + 7) / 16        # Integer arithmetic
    return (Fp, n) => {
        let tv1 = Fp.pow(n, c4); //  1. tv1 = x^c4
        let tv2 = Fp.mul(tv1, c1); //  2. tv2 = c1 * tv1
        const tv3 = Fp.mul(tv1, c2); //  3. tv3 = c2 * tv1
        const tv4 = Fp.mul(tv1, c3); //  4. tv4 = c3 * tv1
        const e1 = Fp.eql(Fp.sqr(tv2), n); //  5.  e1 = (tv2^2) == x
        const e2 = Fp.eql(Fp.sqr(tv3), n); //  6.  e2 = (tv3^2) == x
        tv1 = Fp.cmov(tv1, tv2, e1); //  7. tv1 = CMOV(tv1, tv2, e1)  # Select tv2 if (tv2^2) == x
        tv2 = Fp.cmov(tv4, tv3, e2); //  8. tv2 = CMOV(tv4, tv3, e2)  # Select tv3 if (tv3^2) == x
        const e3 = Fp.eql(Fp.sqr(tv2), n); //  9.  e3 = (tv2^2) == x
        const root = Fp.cmov(tv1, tv2, e3); // 10.  z = CMOV(tv1, tv2, e3)   # Select sqrt from tv1 & tv2
        assertIsSquare(Fp, root, n);
        return root;
    };
}
/**
 * Tonelli-Shanks square root search algorithm.
 * 1. https://eprint.iacr.org/2012/685.pdf (page 12)
 * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks
 * @param P field order
 * @returns function that takes field Fp (created from P) and number n
 */
export function tonelliShanks(P) {
    // Initialization (precomputation).
    // Caching initialization could boost perf by 7%.
    if (P < _3n)
        throw new Error('sqrt is not defined for small field');
    // Factor P - 1 = Q * 2^S, where Q is odd
    let Q = P - _1n;
    let S = 0;
    while (Q % _2n === _0n) {
        Q /= _2n;
        S++;
    }
    // Find the first quadratic non-residue Z >= 2
    let Z = _2n;
    const _Fp = Field(P);
    while (FpLegendre(_Fp, Z) === 1) {
        // Basic primality test for P. After x iterations, chance of
        // not finding quadratic non-residue is 2^x, so 2^1000.
        if (Z++ > 1000)
            throw new Error('Cannot find square root: probably non-prime P');
    }
    // Fast-path; usually done before Z, but we do "primality test".
    if (S === 1)
        return sqrt3mod4;
    // Slow-path
    // TODO: test on Fp2 and others
    let cc = _Fp.pow(Z, Q); // c = z^Q
    const Q1div2 = (Q + _1n) / _2n;
    return function tonelliSlow(Fp, n) {
        if (Fp.is0(n))
            return n;
        // Check if n is a quadratic residue using Legendre symbol
        if (FpLegendre(Fp, n) !== 1)
            throw new Error('Cannot find square root');
        // Initialize variables for the main loop
        let M = S;
        let c = Fp.mul(Fp.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp
        let t = Fp.pow(n, Q); // t = n^Q, first guess at the fudge factor
        let R = Fp.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root
        // Main loop
        // while t != 1
        while (!Fp.eql(t, Fp.ONE)) {
            if (Fp.is0(t))
                return Fp.ZERO; // if t=0 return R=0
            let i = 1;
            // Find the smallest i >= 1 such that t^(2^i) ≡ 1 (mod P)
            let t_tmp = Fp.sqr(t); // t^(2^1)
            while (!Fp.eql(t_tmp, Fp.ONE)) {
                i++;
                t_tmp = Fp.sqr(t_tmp); // t^(2^2)...
                if (i === M)
                    throw new Error('Cannot find square root');
            }
            // Calculate the exponent for b: 2^(M - i - 1)
            const exponent = _1n << BigInt(M - i - 1); // bigint is important
            const b = Fp.pow(c, exponent); // b = 2^(M - i - 1)
            // Update variables
            M = i;
            c = Fp.sqr(b); // c = b^2
            t = Fp.mul(t, c); // t = (t * b^2)
            R = Fp.mul(R, b); // R = R*b
        }
        return R;
    };
}
/**
 * Square root for a finite field. Will try optimized versions first:
 *
 * 1. P ≡ 3 (mod 4)
 * 2. P ≡ 5 (mod 8)
 * 3. P ≡ 9 (mod 16)
 * 4. Tonelli-Shanks algorithm
 *
 * Different algorithms can give different roots, it is up to user to decide which one they want.
 * For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).
 */
export function FpSqrt(P) {
    // P ≡ 3 (mod 4) => √n = n^((P+1)/4)
    if (P % _4n === _3n)
        return sqrt3mod4;
    // P ≡ 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf
    if (P % _8n === _5n)
        return sqrt5mod8;
    // P ≡ 9 (mod 16) => Kong algorithm, page 11 of https://eprint.iacr.org/2012/685.pdf (algorithm 4)
    if (P % _16n === _9n)
        return sqrt9mod16(P);
    // Tonelli-Shanks algorithm
    return tonelliShanks(P);
}
// Little-endian check for first LE bit (last BE bit);
export const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n;
// prettier-ignore
const FIELD_FIELDS = [
    'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',
    'eql', 'add', 'sub', 'mul', 'pow', 'div',
    'addN', 'subN', 'mulN', 'sqrN'
];
export function validateField(field) {
    const initial = {
        ORDER: 'bigint',
        MASK: 'bigint',
        BYTES: 'number',
        BITS: 'number',
    };
    const opts = FIELD_FIELDS.reduce((map, val) => {
        map[val] = 'function';
        return map;
    }, initial);
    _validateObject(field, opts);
    // const max = 16384;
    // if (field.BYTES < 1 || field.BYTES > max) throw new Error('invalid field');
    // if (field.BITS < 1 || field.BITS > 8 * max) throw new Error('invalid field');
    return field;
}
// Generic field functions
/**
 * Same as `pow` but for Fp: non-constant-time.
 * Unsafe in some contexts: uses ladder, so can expose bigint bits.
 */
export function FpPow(Fp, num, power) {
    if (power < _0n)
        throw new Error('invalid exponent, negatives unsupported');
    if (power === _0n)
        return Fp.ONE;
    if (power === _1n)
        return num;
    let p = Fp.ONE;
    let d = num;
    while (power > _0n) {
        if (power & _1n)
            p = Fp.mul(p, d);
        d = Fp.sqr(d);
        power >>= _1n;
    }
    return p;
}
/**
 * Efficiently invert an array of Field elements.
 * Exception-free. Will return `undefined` for 0 elements.
 * @param passZero map 0 to 0 (instead of undefined)
 */
export function FpInvertBatch(Fp, nums, passZero = false) {
    const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : undefined);
    // Walk from first to last, multiply them by each other MOD p
    const multipliedAcc = nums.reduce((acc, num, i) => {
        if (Fp.is0(num))
            return acc;
        inverted[i] = acc;
        return Fp.mul(acc, num);
    }, Fp.ONE);
    // Invert last element
    const invertedAcc = Fp.inv(multipliedAcc);
    // Walk from last to first, multiply them by inverted each other MOD p
    nums.reduceRight((acc, num, i) => {
        if (Fp.is0(num))
            return acc;
        inverted[i] = Fp.mul(acc, inverted[i]);
        return Fp.mul(acc, num);
    }, invertedAcc);
    return inverted;
}
// TODO: remove
export function FpDiv(Fp, lhs, rhs) {
    return Fp.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, Fp.ORDER) : Fp.inv(rhs));
}
/**
 * Legendre symbol.
 * Legendre constant is used to calculate Legendre symbol (a | p)
 * which denotes the value of a^((p-1)/2) (mod p).
 *
 * * (a | p) ≡ 1    if a is a square (mod p), quadratic residue
 * * (a | p) ≡ -1   if a is not a square (mod p), quadratic non residue
 * * (a | p) ≡ 0    if a ≡ 0 (mod p)
 */
export function FpLegendre(Fp, n) {
    // We can use 3rd argument as optional cache of this value
    // but seems unneeded for now. The operation is very fast.
    const p1mod2 = (Fp.ORDER - _1n) / _2n;
    const powered = Fp.pow(n, p1mod2);
    const yes = Fp.eql(powered, Fp.ONE);
    const zero = Fp.eql(powered, Fp.ZERO);
    const no = Fp.eql(powered, Fp.neg(Fp.ONE));
    if (!yes && !zero && !no)
        throw new Error('invalid Legendre symbol result');
    return yes ? 1 : zero ? 0 : -1;
}
// This function returns True whenever the value x is a square in the field F.
export function FpIsSquare(Fp, n) {
    const l = FpLegendre(Fp, n);
    return l === 1;
}
// CURVE.n lengths
export function nLength(n, nBitLength) {
    // Bit size, byte size of CURVE.n
    if (nBitLength !== undefined)
        anumber(nBitLength);
    const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;
    const nByteLength = Math.ceil(_nBitLength / 8);
    return { nBitLength: _nBitLength, nByteLength };
}
/**
 * Creates a finite field. Major performance optimizations:
 * * 1. Denormalized operations like mulN instead of mul.
 * * 2. Identical object shape: never add or remove keys.
 * * 3. `Object.freeze`.
 * Fragile: always run a benchmark on a change.
 * Security note: operations don't check 'isValid' for all elements for performance reasons,
 * it is caller responsibility to check this.
 * This is low-level code, please make sure you know what you're doing.
 *
 * Note about field properties:
 * * CHARACTERISTIC p = prime number, number of elements in main subgroup.
 * * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.
 *
 * @param ORDER field order, probably prime, or could be composite
 * @param bitLen how many bits the field consumes
 * @param isLE (default: false) if encoding / decoding should be in little-endian
 * @param redef optional faster redefinitions of sqrt and other methods
 */
export function Field(ORDER, bitLenOrOpts, // TODO: use opts only in v2?
isLE = false, opts = {}) {
    if (ORDER <= _0n)
        throw new Error('invalid field: expected ORDER > 0, got ' + ORDER);
    let _nbitLength = undefined;
    let _sqrt = undefined;
    let modFromBytes = false;
    let allowedLengths = undefined;
    if (typeof bitLenOrOpts === 'object' && bitLenOrOpts != null) {
        if (opts.sqrt || isLE)
            throw new Error('cannot specify opts in two arguments');
        const _opts = bitLenOrOpts;
        if (_opts.BITS)
            _nbitLength = _opts.BITS;
        if (_opts.sqrt)
            _sqrt = _opts.sqrt;
        if (typeof _opts.isLE === 'boolean')
            isLE = _opts.isLE;
        if (typeof _opts.modFromBytes === 'boolean')
            modFromBytes = _opts.modFromBytes;
        allowedLengths = _opts.allowedLengths;
    }
    else {
        if (typeof bitLenOrOpts === 'number')
            _nbitLength = bitLenOrOpts;
        if (opts.sqrt)
            _sqrt = opts.sqrt;
    }
    const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, _nbitLength);
    if (BYTES > 2048)
        throw new Error('invalid field: expected ORDER of <= 2048 bytes');
    let sqrtP; // cached sqrtP
    const f = Object.freeze({
        ORDER,
        isLE,
        BITS,
        BYTES,
        MASK: bitMask(BITS),
        ZERO: _0n,
        ONE: _1n,
        allowedLengths: allowedLengths,
        create: (num) => mod(num, ORDER),
        isValid: (num) => {
            if (typeof num !== 'bigint')
                throw new Error('invalid field element: expected bigint, got ' + typeof num);
            return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible
        },
        is0: (num) => num === _0n,
        // is valid and invertible
        isValidNot0: (num) => !f.is0(num) && f.isValid(num),
        isOdd: (num) => (num & _1n) === _1n,
        neg: (num) => mod(-num, ORDER),
        eql: (lhs, rhs) => lhs === rhs,
        sqr: (num) => mod(num * num, ORDER),
        add: (lhs, rhs) => mod(lhs + rhs, ORDER),
        sub: (lhs, rhs) => mod(lhs - rhs, ORDER),
        mul: (lhs, rhs) => mod(lhs * rhs, ORDER),
        pow: (num, power) => FpPow(f, num, power),
        div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),
        // Same as above, but doesn't normalize
        sqrN: (num) => num * num,
        addN: (lhs, rhs) => lhs + rhs,
        subN: (lhs, rhs) => lhs - rhs,
        mulN: (lhs, rhs) => lhs * rhs,
        inv: (num) => invert(num, ORDER),
        sqrt: _sqrt ||
            ((n) => {
                if (!sqrtP)
                    sqrtP = FpSqrt(ORDER);
                return sqrtP(f, n);
            }),
        toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),
        fromBytes: (bytes, skipValidation = true) => {
            if (allowedLengths) {
                if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
                    throw new Error('Field.fromBytes: expected ' + allowedLengths + ' bytes, got ' + bytes.length);
                }
                const padded = new Uint8Array(BYTES);
                // isLE add 0 to right, !isLE to the left.
                padded.set(bytes, isLE ? 0 : padded.length - bytes.length);
                bytes = padded;
            }
            if (bytes.length !== BYTES)
                throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);
            let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
            if (modFromBytes)
                scalar = mod(scalar, ORDER);
            if (!skipValidation)
                if (!f.isValid(scalar))
                    throw new Error('invalid field element: outside of range 0..ORDER');
            // NOTE: we don't validate scalar here, please use isValid. This done such way because some
            // protocol may allow non-reduced scalar that reduced later or changed some other way.
            return scalar;
        },
        // TODO: we don't need it here, move out to separate fn
        invertBatch: (lst) => FpInvertBatch(f, lst),
        // We can't move this out because Fp6, Fp12 implement it
        // and it's unclear what to return in there.
        cmov: (a, b, c) => (c ? b : a),
    });
    return Object.freeze(f);
}
// Generic random scalar, we can do same for other fields if via Fp2.mul(Fp2.ONE, Fp2.random)?
// This allows unsafe methods like ignore bias or zero. These unsafe, but often used in different protocols (if deterministic RNG).
// which mean we cannot force this via opts.
// Not sure what to do with randomBytes, we can accept it inside opts if wanted.
// Probably need to export getMinHashLength somewhere?
// random(bytes?: Uint8Array, unsafeAllowZero = false, unsafeAllowBias = false) {
//   const LEN = !unsafeAllowBias ? getMinHashLength(ORDER) : BYTES;
//   if (bytes === undefined) bytes = randomBytes(LEN); // _opts.randomBytes?
//   const num = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
//   // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0
//   const reduced = unsafeAllowZero ? mod(num, ORDER) : mod(num, ORDER - _1n) + _1n;
//   return reduced;
// },
export function FpSqrtOdd(Fp, elm) {
    if (!Fp.isOdd)
        throw new Error("Field doesn't have isOdd");
    const root = Fp.sqrt(elm);
    return Fp.isOdd(root) ? root : Fp.neg(root);
}
export function FpSqrtEven(Fp, elm) {
    if (!Fp.isOdd)
        throw new Error("Field doesn't have isOdd");
    const root = Fp.sqrt(elm);
    return Fp.isOdd(root) ? Fp.neg(root) : root;
}
/**
 * "Constant-time" private key generation utility.
 * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field).
 * Which makes it slightly more biased, less secure.
 * @deprecated use `mapKeyToField` instead
 */
export function hashToPrivateScalar(hash, groupOrder, isLE = false) {
    hash = ensureBytes('privateHash', hash);
    const hashLen = hash.length;
    const minLen = nLength(groupOrder).nByteLength + 8;
    if (minLen < 24 || hashLen < minLen || hashLen > 1024)
        throw new Error('hashToPrivateScalar: expected ' + minLen + '-1024 bytes of input, got ' + hashLen);
    const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash);
    return mod(num, groupOrder - _1n) + _1n;
}
/**
 * Returns total number of bytes consumed by the field element.
 * For example, 32 bytes for usual 256-bit weierstrass curve.
 * @param fieldOrder number of field elements, usually CURVE.n
 * @returns byte length of field
 */
export function getFieldBytesLength(fieldOrder) {
    if (typeof fieldOrder !== 'bigint')
        throw new Error('field order must be bigint');
    const bitLength = fieldOrder.toString(2).length;
    return Math.ceil(bitLength / 8);
}
/**
 * Returns minimal amount of bytes that can be safely reduced
 * by field order.
 * Should be 2^-128 for 128-bit curve such as P256.
 * @param fieldOrder number of field elements, usually CURVE.n
 * @returns byte length of target hash
 */
export function getMinHashLength(fieldOrder) {
    const length = getFieldBytesLength(fieldOrder);
    return length + Math.ceil(length / 2);
}
/**
 * "Constant-time" private key generation utility.
 * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF
 * and convert them into private scalar, with the modulo bias being negligible.
 * Needs at least 48 bytes of input for 32-byte private key.
 * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/
 * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final
 * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5
 * @param hash hash output from SHA3 or a similar function
 * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)
 * @param isLE interpret hash bytes as LE num
 * @returns valid private scalar
 */
export function mapHashToField(key, fieldOrder, isLE = false) {
    const len = key.length;
    const fieldLen = getFieldBytesLength(fieldOrder);
    const minLen = getMinHashLength(fieldOrder);
    // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.
    if (len < 16 || len < minLen || len > 1024)
        throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);
    const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);
    // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0
    const reduced = mod(num, fieldOrder - _1n) + _1n;
    return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
}
//# sourceMappingURL=modular.js.map/**
 * Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.
 *
 * ### Design rationale for types
 *
 * * Interaction between classes from different curves should fail:
 *   `k256.Point.BASE.add(p256.Point.BASE)`
 * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime
 * * Different calls of `curve()` would return different classes -
 *   `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,
 *   it won't affect others
 *
 * TypeScript can't infer types for classes created inside a function. Classes is one instance
 * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create
 * unique type for every function call.
 *
 * We can use generic types via some param, like curve opts, but that would:
 *     1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)
 *     which is hard to debug.
 *     2. Params can be generic and we can't enforce them to be constant value:
 *     if somebody creates curve from non-constant params,
 *     it would be allowed to interact with other curves with non-constant params
 *
 * @todo https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { hmac as nobleHmac } from '@noble/hashes/hmac.js';
import { ahash } from '@noble/hashes/utils';
import { _validateObject, _abool2 as abool, _abytes2 as abytes, aInRange, bitLen, bitMask, bytesToHex, bytesToNumberBE, concatBytes, createHmacDrbg, ensureBytes, hexToBytes, inRange, isBytes, memoized, numberToHexUnpadded, randomBytes as randomBytesWeb, } from "../utils.js";
import { _createCurveFields, mulEndoUnsafe, negateCt, normalizeZ, pippenger, wNAF, } from "./curve.js";
import { Field, FpInvertBatch, getMinHashLength, mapHashToField, nLength, validateField, } from "./modular.js";
// We construct basis in such way that den is always positive and equals n, but num sign depends on basis (not on secret value)
const divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n) / den;
/**
 * Splits scalar for GLV endomorphism.
 */
export function _splitEndoScalar(k, basis, n) {
    // Split scalar into two such that part is ~half bits: `abs(part) < sqrt(N)`
    // Since part can be negative, we need to do this on point.
    // TODO: verifyScalar function which consumes lambda
    const [[a1, b1], [a2, b2]] = basis;
    const c1 = divNearest(b2 * k, n);
    const c2 = divNearest(-b1 * k, n);
    // |k1|/|k2| is < sqrt(N), but can be negative.
    // If we do `k1 mod N`, we'll get big scalar (`> sqrt(N)`): so, we do cheaper negation instead.
    let k1 = k - c1 * a1 - c2 * a2;
    let k2 = -c1 * b1 - c2 * b2;
    const k1neg = k1 < _0n;
    const k2neg = k2 < _0n;
    if (k1neg)
        k1 = -k1;
    if (k2neg)
        k2 = -k2;
    // Double check that resulting scalar less than half bits of N: otherwise wNAF will fail.
    // This should only happen on wrong basises. Also, math inside is too complex and I don't trust it.
    const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n; // Half bits of N
    if (k1 < _0n || k1 >= MAX_NUM || k2 < _0n || k2 >= MAX_NUM) {
        throw new Error('splitScalar (endomorphism): failed, k=' + k);
    }
    return { k1neg, k1, k2neg, k2 };
}
function validateSigFormat(format) {
    if (!['compact', 'recovered', 'der'].includes(format))
        throw new Error('Signature format must be "compact", "recovered", or "der"');
    return format;
}
function validateSigOpts(opts, def) {
    const optsn = {};
    for (let optName of Object.keys(def)) {
        // @ts-ignore
        optsn[optName] = opts[optName] === undefined ? def[optName] : opts[optName];
    }
    abool(optsn.lowS, 'lowS');
    abool(optsn.prehash, 'prehash');
    if (optsn.format !== undefined)
        validateSigFormat(optsn.format);
    return optsn;
}
export class DERErr extends Error {
    constructor(m = '') {
        super(m);
    }
}
/**
 * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:
 *
 *     [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]
 *
 * Docs: https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/, https://luca.ntop.org/Teaching/Appunti/asn1.html
 */
export const DER = {
    // asn.1 DER encoding utils
    Err: DERErr,
    // Basic building block is TLV (Tag-Length-Value)
    _tlv: {
        encode: (tag, data) => {
            const { Err: E } = DER;
            if (tag < 0 || tag > 256)
                throw new E('tlv.encode: wrong tag');
            if (data.length & 1)
                throw new E('tlv.encode: unpadded data');
            const dataLen = data.length / 2;
            const len = numberToHexUnpadded(dataLen);
            if ((len.length / 2) & 128)
                throw new E('tlv.encode: long form length too big');
            // length of length with long form flag
            const lenLen = dataLen > 127 ? numberToHexUnpadded((len.length / 2) | 128) : '';
            const t = numberToHexUnpadded(tag);
            return t + lenLen + len + data;
        },
        // v - value, l - left bytes (unparsed)
        decode(tag, data) {
            const { Err: E } = DER;
            let pos = 0;
            if (tag < 0 || tag > 256)
                throw new E('tlv.encode: wrong tag');
            if (data.length < 2 || data[pos++] !== tag)
                throw new E('tlv.decode: wrong tlv');
            const first = data[pos++];
            const isLong = !!(first & 128); // First bit of first length byte is flag for short/long form
            let length = 0;
            if (!isLong)
                length = first;
            else {
                // Long form: [longFlag(1bit), lengthLength(7bit), length (BE)]
                const lenLen = first & 127;
                if (!lenLen)
                    throw new E('tlv.decode(long): indefinite length not supported');
                if (lenLen > 4)
                    throw new E('tlv.decode(long): byte length is too big'); // this will overflow u32 in js
                const lengthBytes = data.subarray(pos, pos + lenLen);
                if (lengthBytes.length !== lenLen)
                    throw new E('tlv.decode: length bytes not complete');
                if (lengthBytes[0] === 0)
                    throw new E('tlv.decode(long): zero leftmost byte');
                for (const b of lengthBytes)
                    length = (length << 8) | b;
                pos += lenLen;
                if (length < 128)
                    throw new E('tlv.decode(long): not minimal encoding');
            }
            const v = data.subarray(pos, pos + length);
            if (v.length !== length)
                throw new E('tlv.decode: wrong value length');
            return { v, l: data.subarray(pos + length) };
        },
    },
    // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
    // since we always use positive integers here. It must always be empty:
    // - add zero byte if exists
    // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
    _int: {
        encode(num) {
            const { Err: E } = DER;
            if (num < _0n)
                throw new E('integer: negative integers are not allowed');
            let hex = numberToHexUnpadded(num);
            // Pad with zero byte if negative flag is present
            if (Number.parseInt(hex[0], 16) & 0b1000)
                hex = '00' + hex;
            if (hex.length & 1)
                throw new E('unexpected DER parsing assertion: unpadded hex');
            return hex;
        },
        decode(data) {
            const { Err: E } = DER;
            if (data[0] & 128)
                throw new E('invalid signature integer: negative');
            if (data[0] === 0x00 && !(data[1] & 128))
                throw new E('invalid signature integer: unnecessary leading zero');
            return bytesToNumberBE(data);
        },
    },
    toSig(hex) {
        // parse DER signature
        const { Err: E, _int: int, _tlv: tlv } = DER;
        const data = ensureBytes('signature', hex);
        const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);
        if (seqLeftBytes.length)
            throw new E('invalid signature: left bytes after parsing');
        const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);
        const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);
        if (sLeftBytes.length)
            throw new E('invalid signature: left bytes after parsing');
        return { r: int.decode(rBytes), s: int.decode(sBytes) };
    },
    hexFromSig(sig) {
        const { _tlv: tlv, _int: int } = DER;
        const rs = tlv.encode(0x02, int.encode(sig.r));
        const ss = tlv.encode(0x02, int.encode(sig.s));
        const seq = rs + ss;
        return tlv.encode(0x30, seq);
    },
};
// Be friendly to bad ECMAScript parsers by not using bigint literals
// prettier-ignore
const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4);
export function _normFnElement(Fn, key) {
    const { BYTES: expected } = Fn;
    let num;
    if (typeof key === 'bigint') {
        num = key;
    }
    else {
        let bytes = ensureBytes('private key', key);
        try {
            num = Fn.fromBytes(bytes);
        }
        catch (error) {
            throw new Error(`invalid private key: expected ui8a of size ${expected}, got ${typeof key}`);
        }
    }
    if (!Fn.isValidNot0(num))
        throw new Error('invalid private key: out of range [1..N-1]');
    return num;
}
/**
 * Creates weierstrass Point constructor, based on specified curve options.
 *
 * @example
```js
const opts = {
  p: BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff'),
  n: BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551'),
  h: BigInt(1),
  a: BigInt('0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc'),
  b: BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b'),
  Gx: BigInt('0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296'),
  Gy: BigInt('0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5'),
};
const p256_Point = weierstrass(opts);
```
 */
export function weierstrassN(params, extraOpts = {}) {
    const validated = _createCurveFields('weierstrass', params, extraOpts);
    const { Fp, Fn } = validated;
    let CURVE = validated.CURVE;
    const { h: cofactor, n: CURVE_ORDER } = CURVE;
    _validateObject(extraOpts, {}, {
        allowInfinityPoint: 'boolean',
        clearCofactor: 'function',
        isTorsionFree: 'function',
        fromBytes: 'function',
        toBytes: 'function',
        endo: 'object',
        wrapPrivateKey: 'boolean',
    });
    const { endo } = extraOpts;
    if (endo) {
        // validateObject(endo, { beta: 'bigint', splitScalar: 'function' });
        if (!Fp.is0(CURVE.a) || typeof endo.beta !== 'bigint' || !Array.isArray(endo.basises)) {
            throw new Error('invalid endo: expected "beta": bigint and "basises": array');
        }
    }
    const lengths = getWLengths(Fp, Fn);
    function assertCompressionIsSupported() {
        if (!Fp.isOdd)
            throw new Error('compression is not supported: Field does not have .isOdd()');
    }
    // Implements IEEE P1363 point encoding
    function pointToBytes(_c, point, isCompressed) {
        const { x, y } = point.toAffine();
        const bx = Fp.toBytes(x);
        abool(isCompressed, 'isCompressed');
        if (isCompressed) {
            assertCompressionIsSupported();
            const hasEvenY = !Fp.isOdd(y);
            return concatBytes(pprefix(hasEvenY), bx);
        }
        else {
            return concatBytes(Uint8Array.of(0x04), bx, Fp.toBytes(y));
        }
    }
    function pointFromBytes(bytes) {
        abytes(bytes, undefined, 'Point');
        const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths; // e.g. for 32-byte: 33, 65
        const length = bytes.length;
        const head = bytes[0];
        const tail = bytes.subarray(1);
        // No actual validation is done here: use .assertValidity()
        if (length === comp && (head === 0x02 || head === 0x03)) {
            const x = Fp.fromBytes(tail);
            if (!Fp.isValid(x))
                throw new Error('bad point: is not on curve, wrong x');
            const y2 = weierstrassEquation(x); // y² = x³ + ax + b
            let y;
            try {
                y = Fp.sqrt(y2); // y = y² ^ (p+1)/4
            }
            catch (sqrtError) {
                const err = sqrtError instanceof Error ? ': ' + sqrtError.message : '';
                throw new Error('bad point: is not on curve, sqrt error' + err);
            }
            assertCompressionIsSupported();
            const isYOdd = Fp.isOdd(y); // (y & _1n) === _1n;
            const isHeadOdd = (head & 1) === 1; // ECDSA-specific
            if (isHeadOdd !== isYOdd)
                y = Fp.neg(y);
            return { x, y };
        }
        else if (length === uncomp && head === 0x04) {
            // TODO: more checks
            const L = Fp.BYTES;
            const x = Fp.fromBytes(tail.subarray(0, L));
            const y = Fp.fromBytes(tail.subarray(L, L * 2));
            if (!isValidXY(x, y))
                throw new Error('bad point: is not on curve');
            return { x, y };
        }
        else {
            throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);
        }
    }
    const encodePoint = extraOpts.toBytes || pointToBytes;
    const decodePoint = extraOpts.fromBytes || pointFromBytes;
    function weierstrassEquation(x) {
        const x2 = Fp.sqr(x); // x * x
        const x3 = Fp.mul(x2, x); // x² * x
        return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b); // x³ + a * x + b
    }
    // TODO: move top-level
    /** Checks whether equation holds for given x, y: y² == x³ + ax + b */
    function isValidXY(x, y) {
        const left = Fp.sqr(y); // y²
        const right = weierstrassEquation(x); // x³ + ax + b
        return Fp.eql(left, right);
    }
    // Validate whether the passed curve params are valid.
    // Test 1: equation y² = x³ + ax + b should work for generator point.
    if (!isValidXY(CURVE.Gx, CURVE.Gy))
        throw new Error('bad curve params: generator point');
    // Test 2: discriminant Δ part should be non-zero: 4a³ + 27b² != 0.
    // Guarantees curve is genus-1, smooth (non-singular).
    const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n), _4n);
    const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));
    if (Fp.is0(Fp.add(_4a3, _27b2)))
        throw new Error('bad curve params: a or b');
    /** Asserts coordinate is valid: 0 <= n < Fp.ORDER. */
    function acoord(title, n, banZero = false) {
        if (!Fp.isValid(n) || (banZero && Fp.is0(n)))
            throw new Error(`bad point coordinate ${title}`);
        return n;
    }
    function aprjpoint(other) {
        if (!(other instanceof Point))
            throw new Error('ProjectivePoint expected');
    }
    function splitEndoScalarN(k) {
        if (!endo || !endo.basises)
            throw new Error('no endo');
        return _splitEndoScalar(k, endo.basises, Fn.ORDER);
    }
    // Memoized toAffine / validity check. They are heavy. Points are immutable.
    // Converts Projective point to affine (x, y) coordinates.
    // Can accept precomputed Z^-1 - for example, from invertBatch.
    // (X, Y, Z) ∋ (x=X/Z, y=Y/Z)
    const toAffineMemo = memoized((p, iz) => {
        const { X, Y, Z } = p;
        // Fast-path for normalized points
        if (Fp.eql(Z, Fp.ONE))
            return { x: X, y: Y };
        const is0 = p.is0();
        // If invZ was 0, we return zero point. However we still want to execute
        // all operations, so we replace invZ with a random number, 1.
        if (iz == null)
            iz = is0 ? Fp.ONE : Fp.inv(Z);
        const x = Fp.mul(X, iz);
        const y = Fp.mul(Y, iz);
        const zz = Fp.mul(Z, iz);
        if (is0)
            return { x: Fp.ZERO, y: Fp.ZERO };
        if (!Fp.eql(zz, Fp.ONE))
            throw new Error('invZ was invalid');
        return { x, y };
    });
    // NOTE: on exception this will crash 'cached' and no value will be set.
    // Otherwise true will be return
    const assertValidMemo = memoized((p) => {
        if (p.is0()) {
            // (0, 1, 0) aka ZERO is invalid in most contexts.
            // In BLS, ZERO can be serialized, so we allow it.
            // (0, 0, 0) is invalid representation of ZERO.
            if (extraOpts.allowInfinityPoint && !Fp.is0(p.Y))
                return;
            throw new Error('bad point: ZERO');
        }
        // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`
        const { x, y } = p.toAffine();
        if (!Fp.isValid(x) || !Fp.isValid(y))
            throw new Error('bad point: x or y not field elements');
        if (!isValidXY(x, y))
            throw new Error('bad point: equation left != right');
        if (!p.isTorsionFree())
            throw new Error('bad point: not in prime-order subgroup');
        return true;
    });
    function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) {
        k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);
        k1p = negateCt(k1neg, k1p);
        k2p = negateCt(k2neg, k2p);
        return k1p.add(k2p);
    }
    /**
     * Projective Point works in 3d / projective (homogeneous) coordinates:(X, Y, Z) ∋ (x=X/Z, y=Y/Z).
     * Default Point works in 2d / affine coordinates: (x, y).
     * We're doing calculations in projective, because its operations don't require costly inversion.
     */
    class Point {
        /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
        constructor(X, Y, Z) {
            this.X = acoord('x', X);
            this.Y = acoord('y', Y, true);
            this.Z = acoord('z', Z);
            Object.freeze(this);
        }
        static CURVE() {
            return CURVE;
        }
        /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
        static fromAffine(p) {
            const { x, y } = p || {};
            if (!p || !Fp.isValid(x) || !Fp.isValid(y))
                throw new Error('invalid affine point');
            if (p instanceof Point)
                throw new Error('projective point not allowed');
            // (0, 0) would've produced (0, 0, 1) - instead, we need (0, 1, 0)
            if (Fp.is0(x) && Fp.is0(y))
                return Point.ZERO;
            return new Point(x, y, Fp.ONE);
        }
        static fromBytes(bytes) {
            const P = Point.fromAffine(decodePoint(abytes(bytes, undefined, 'point')));
            P.assertValidity();
            return P;
        }
        static fromHex(hex) {
            return Point.fromBytes(ensureBytes('pointHex', hex));
        }
        get x() {
            return this.toAffine().x;
        }
        get y() {
            return this.toAffine().y;
        }
        /**
         *
         * @param windowSize
         * @param isLazy true will defer table computation until the first multiplication
         * @returns
         */
        precompute(windowSize = 8, isLazy = true) {
            wnaf.createCache(this, windowSize);
            if (!isLazy)
                this.multiply(_3n); // random number
            return this;
        }
        // TODO: return `this`
        /** A point on curve is valid if it conforms to equation. */
        assertValidity() {
            assertValidMemo(this);
        }
        hasEvenY() {
            const { y } = this.toAffine();
            if (!Fp.isOdd)
                throw new Error("Field doesn't support isOdd");
            return !Fp.isOdd(y);
        }
        /** Compare one point to another. */
        equals(other) {
            aprjpoint(other);
            const { X: X1, Y: Y1, Z: Z1 } = this;
            const { X: X2, Y: Y2, Z: Z2 } = other;
            const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
            const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
            return U1 && U2;
        }
        /** Flips point to one corresponding to (x, -y) in Affine coordinates. */
        negate() {
            return new Point(this.X, Fp.neg(this.Y), this.Z);
        }
        // Renes-Costello-Batina exception-free doubling formula.
        // There is 30% faster Jacobian formula, but it is not complete.
        // https://eprint.iacr.org/2015/1060, algorithm 3
        // Cost: 8M + 3S + 3*a + 2*b3 + 15add.
        double() {
            const { a, b } = CURVE;
            const b3 = Fp.mul(b, _3n);
            const { X: X1, Y: Y1, Z: Z1 } = this;
            let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore
            let t0 = Fp.mul(X1, X1); // step 1
            let t1 = Fp.mul(Y1, Y1);
            let t2 = Fp.mul(Z1, Z1);
            let t3 = Fp.mul(X1, Y1);
            t3 = Fp.add(t3, t3); // step 5
            Z3 = Fp.mul(X1, Z1);
            Z3 = Fp.add(Z3, Z3);
            X3 = Fp.mul(a, Z3);
            Y3 = Fp.mul(b3, t2);
            Y3 = Fp.add(X3, Y3); // step 10
            X3 = Fp.sub(t1, Y3);
            Y3 = Fp.add(t1, Y3);
            Y3 = Fp.mul(X3, Y3);
            X3 = Fp.mul(t3, X3);
            Z3 = Fp.mul(b3, Z3); // step 15
            t2 = Fp.mul(a, t2);
            t3 = Fp.sub(t0, t2);
            t3 = Fp.mul(a, t3);
            t3 = Fp.add(t3, Z3);
            Z3 = Fp.add(t0, t0); // step 20
            t0 = Fp.add(Z3, t0);
            t0 = Fp.add(t0, t2);
            t0 = Fp.mul(t0, t3);
            Y3 = Fp.add(Y3, t0);
            t2 = Fp.mul(Y1, Z1); // step 25
            t2 = Fp.add(t2, t2);
            t0 = Fp.mul(t2, t3);
            X3 = Fp.sub(X3, t0);
            Z3 = Fp.mul(t2, t1);
            Z3 = Fp.add(Z3, Z3); // step 30
            Z3 = Fp.add(Z3, Z3);
            return new Point(X3, Y3, Z3);
        }
        // Renes-Costello-Batina exception-free addition formula.
        // There is 30% faster Jacobian formula, but it is not complete.
        // https://eprint.iacr.org/2015/1060, algorithm 1
        // Cost: 12M + 0S + 3*a + 3*b3 + 23add.
        add(other) {
            aprjpoint(other);
            const { X: X1, Y: Y1, Z: Z1 } = this;
            const { X: X2, Y: Y2, Z: Z2 } = other;
            let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore
            const a = CURVE.a;
            const b3 = Fp.mul(CURVE.b, _3n);
            let t0 = Fp.mul(X1, X2); // step 1
            let t1 = Fp.mul(Y1, Y2);
            let t2 = Fp.mul(Z1, Z2);
            let t3 = Fp.add(X1, Y1);
            let t4 = Fp.add(X2, Y2); // step 5
            t3 = Fp.mul(t3, t4);
            t4 = Fp.add(t0, t1);
            t3 = Fp.sub(t3, t4);
            t4 = Fp.add(X1, Z1);
            let t5 = Fp.add(X2, Z2); // step 10
            t4 = Fp.mul(t4, t5);
            t5 = Fp.add(t0, t2);
            t4 = Fp.sub(t4, t5);
            t5 = Fp.add(Y1, Z1);
            X3 = Fp.add(Y2, Z2); // step 15
            t5 = Fp.mul(t5, X3);
            X3 = Fp.add(t1, t2);
            t5 = Fp.sub(t5, X3);
            Z3 = Fp.mul(a, t4);
            X3 = Fp.mul(b3, t2); // step 20
            Z3 = Fp.add(X3, Z3);
            X3 = Fp.sub(t1, Z3);
            Z3 = Fp.add(t1, Z3);
            Y3 = Fp.mul(X3, Z3);
            t1 = Fp.add(t0, t0); // step 25
            t1 = Fp.add(t1, t0);
            t2 = Fp.mul(a, t2);
            t4 = Fp.mul(b3, t4);
            t1 = Fp.add(t1, t2);
            t2 = Fp.sub(t0, t2); // step 30
            t2 = Fp.mul(a, t2);
            t4 = Fp.add(t4, t2);
            t0 = Fp.mul(t1, t4);
            Y3 = Fp.add(Y3, t0);
            t0 = Fp.mul(t5, t4); // step 35
            X3 = Fp.mul(t3, X3);
            X3 = Fp.sub(X3, t0);
            t0 = Fp.mul(t3, t1);
            Z3 = Fp.mul(t5, Z3);
            Z3 = Fp.add(Z3, t0); // step 40
            return new Point(X3, Y3, Z3);
        }
        subtract(other) {
            return this.add(other.negate());
        }
        is0() {
            return this.equals(Point.ZERO);
        }
        /**
         * Constant time multiplication.
         * Uses wNAF method. Windowed method may be 10% faster,
         * but takes 2x longer to generate and consumes 2x memory.
         * Uses precomputes when available.
         * Uses endomorphism for Koblitz curves.
         * @param scalar by which the point would be multiplied
         * @returns New point
         */
        multiply(scalar) {
            const { endo } = extraOpts;
            if (!Fn.isValidNot0(scalar))
                throw new Error('invalid scalar: out of range'); // 0 is invalid
            let point, fake; // Fake point is used to const-time mult
            const mul = (n) => wnaf.cached(this, n, (p) => normalizeZ(Point, p));
            /** See docs for {@link EndomorphismOpts} */
            if (endo) {
                const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);
                const { p: k1p, f: k1f } = mul(k1);
                const { p: k2p, f: k2f } = mul(k2);
                fake = k1f.add(k2f);
                point = finishEndo(endo.beta, k1p, k2p, k1neg, k2neg);
            }
            else {
                const { p, f } = mul(scalar);
                point = p;
                fake = f;
            }
            // Normalize `z` for both points, but return only real one
            return normalizeZ(Point, [point, fake])[0];
        }
        /**
         * Non-constant-time multiplication. Uses double-and-add algorithm.
         * It's faster, but should only be used when you don't care about
         * an exposed secret key e.g. sig verification, which works over *public* keys.
         */
        multiplyUnsafe(sc) {
            const { endo } = extraOpts;
            const p = this;
            if (!Fn.isValid(sc))
                throw new Error('invalid scalar: out of range'); // 0 is valid
            if (sc === _0n || p.is0())
                return Point.ZERO;
            if (sc === _1n)
                return p; // fast-path
            if (wnaf.hasCache(this))
                return this.multiply(sc);
            if (endo) {
                const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);
                const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2); // 30% faster vs wnaf.unsafe
                return finishEndo(endo.beta, p1, p2, k1neg, k2neg);
            }
            else {
                return wnaf.unsafe(p, sc);
            }
        }
        multiplyAndAddUnsafe(Q, a, b) {
            const sum = this.multiplyUnsafe(a).add(Q.multiplyUnsafe(b));
            return sum.is0() ? undefined : sum;
        }
        /**
         * Converts Projective point to affine (x, y) coordinates.
         * @param invertedZ Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch
         */
        toAffine(invertedZ) {
            return toAffineMemo(this, invertedZ);
        }
        /**
         * Checks whether Point is free of torsion elements (is in prime subgroup).
         * Always torsion-free for cofactor=1 curves.
         */
        isTorsionFree() {
            const { isTorsionFree } = extraOpts;
            if (cofactor === _1n)
                return true;
            if (isTorsionFree)
                return isTorsionFree(Point, this);
            return wnaf.unsafe(this, CURVE_ORDER).is0();
        }
        clearCofactor() {
            const { clearCofactor } = extraOpts;
            if (cofactor === _1n)
                return this; // Fast-path
            if (clearCofactor)
                return clearCofactor(Point, this);
            return this.multiplyUnsafe(cofactor);
        }
        isSmallOrder() {
            // can we use this.clearCofactor()?
            return this.multiplyUnsafe(cofactor).is0();
        }
        toBytes(isCompressed = true) {
            abool(isCompressed, 'isCompressed');
            this.assertValidity();
            return encodePoint(Point, this, isCompressed);
        }
        toHex(isCompressed = true) {
            return bytesToHex(this.toBytes(isCompressed));
        }
        toString() {
            return `<Point ${this.is0() ? 'ZERO' : this.toHex()}>`;
        }
        // TODO: remove
        get px() {
            return this.X;
        }
        get py() {
            return this.X;
        }
        get pz() {
            return this.Z;
        }
        toRawBytes(isCompressed = true) {
            return this.toBytes(isCompressed);
        }
        _setWindowSize(windowSize) {
            this.precompute(windowSize);
        }
        static normalizeZ(points) {
            return normalizeZ(Point, points);
        }
        static msm(points, scalars) {
            return pippenger(Point, Fn, points, scalars);
        }
        static fromPrivateKey(privateKey) {
            return Point.BASE.multiply(_normFnElement(Fn, privateKey));
        }
    }
    // base / generator point
    Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
    // zero / infinity / identity point
    Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); // 0, 1, 0
    // math field
    Point.Fp = Fp;
    // scalar field
    Point.Fn = Fn;
    const bits = Fn.BITS;
    const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);
    Point.BASE.precompute(8); // Enable precomputes. Slows down first publicKey computation by 20ms.
    return Point;
}
// Points start with byte 0x02 when y is even; otherwise 0x03
function pprefix(hasEvenY) {
    return Uint8Array.of(hasEvenY ? 0x02 : 0x03);
}
/**
 * Implementation of the Shallue and van de Woestijne method for any weierstrass curve.
 * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular.
 * b = True and y = sqrt(u / v) if (u / v) is square in F, and
 * b = False and y = sqrt(Z * (u / v)) otherwise.
 * @param Fp
 * @param Z
 * @returns
 */
export function SWUFpSqrtRatio(Fp, Z) {
    // Generic implementation
    const q = Fp.ORDER;
    let l = _0n;
    for (let o = q - _1n; o % _2n === _0n; o /= _2n)
        l += _1n;
    const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1.
    // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<.
    // 2n ** c1 == 2n << (c1-1)
    const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n);
    const _2n_pow_c1 = _2n_pow_c1_1 * _2n;
    const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1)  # Integer arithmetic
    const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2            # Integer arithmetic
    const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1                # Integer arithmetic
    const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1)                  # Integer arithmetic
    const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2
    const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2)
    let sqrtRatio = (u, v) => {
        let tv1 = c6; // 1. tv1 = c6
        let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4
        let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2
        tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v
        let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3
        tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3
        tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2
        tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v
        tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u
        let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2
        tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5
        let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1
        tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7
        tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1
        tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR)
        tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR)
        // 17. for i in (c1, c1 - 1, ..., 2):
        for (let i = c1; i > _1n; i--) {
            let tv5 = i - _2n; // 18.    tv5 = i - 2
            tv5 = _2n << (tv5 - _1n); // 19.    tv5 = 2^tv5
            let tvv5 = Fp.pow(tv4, tv5); // 20.    tv5 = tv4^tv5
            const e1 = Fp.eql(tvv5, Fp.ONE); // 21.    e1 = tv5 == 1
            tv2 = Fp.mul(tv3, tv1); // 22.    tv2 = tv3 * tv1
            tv1 = Fp.mul(tv1, tv1); // 23.    tv1 = tv1 * tv1
            tvv5 = Fp.mul(tv4, tv1); // 24.    tv5 = tv4 * tv1
            tv3 = Fp.cmov(tv2, tv3, e1); // 25.    tv3 = CMOV(tv2, tv3, e1)
            tv4 = Fp.cmov(tvv5, tv4, e1); // 26.    tv4 = CMOV(tv5, tv4, e1)
        }
        return { isValid: isQR, value: tv3 };
    };
    if (Fp.ORDER % _4n === _3n) {
        // sqrt_ratio_3mod4(u, v)
        const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4     # Integer arithmetic
        const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z)
        sqrtRatio = (u, v) => {
            let tv1 = Fp.sqr(v); // 1. tv1 = v^2
            const tv2 = Fp.mul(u, v); // 2. tv2 = u * v
            tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2
            let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1
            y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2
            const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2
            const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v
            const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u
            let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR)
            return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2
        };
    }
    // No curves uses that
    // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8
    return sqrtRatio;
}
/**
 * Simplified Shallue-van de Woestijne-Ulas Method
 * https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2
 */
export function mapToCurveSimpleSWU(Fp, opts) {
    validateField(Fp);
    const { A, B, Z } = opts;
    if (!Fp.isValid(A) || !Fp.isValid(B) || !Fp.isValid(Z))
        throw new Error('mapToCurveSimpleSWU: invalid opts');
    const sqrtRatio = SWUFpSqrtRatio(Fp, Z);
    if (!Fp.isOdd)
        throw new Error('Field does not have .isOdd()');
    // Input: u, an element of F.
    // Output: (x, y), a point on E.
    return (u) => {
        // prettier-ignore
        let tv1, tv2, tv3, tv4, tv5, tv6, x, y;
        tv1 = Fp.sqr(u); // 1.  tv1 = u^2
        tv1 = Fp.mul(tv1, Z); // 2.  tv1 = Z * tv1
        tv2 = Fp.sqr(tv1); // 3.  tv2 = tv1^2
        tv2 = Fp.add(tv2, tv1); // 4.  tv2 = tv2 + tv1
        tv3 = Fp.add(tv2, Fp.ONE); // 5.  tv3 = tv2 + 1
        tv3 = Fp.mul(tv3, B); // 6.  tv3 = B * tv3
        tv4 = Fp.cmov(Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7.  tv4 = CMOV(Z, -tv2, tv2 != 0)
        tv4 = Fp.mul(tv4, A); // 8.  tv4 = A * tv4
        tv2 = Fp.sqr(tv3); // 9.  tv2 = tv3^2
        tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2
        tv5 = Fp.mul(tv6, A); // 11. tv5 = A * tv6
        tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5
        tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3
        tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4
        tv5 = Fp.mul(tv6, B); // 15. tv5 = B * tv6
        tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5
        x = Fp.mul(tv1, tv3); // 17.   x = tv1 * tv3
        const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6)
        y = Fp.mul(tv1, u); // 19.   y = tv1 * u  -> Z * u^3 * y1
        y = Fp.mul(y, value); // 20.   y = y * y1
        x = Fp.cmov(x, tv3, isValid); // 21.   x = CMOV(x, tv3, is_gx1_square)
        y = Fp.cmov(y, value, isValid); // 22.   y = CMOV(y, y1, is_gx1_square)
        const e1 = Fp.isOdd(u) === Fp.isOdd(y); // 23.  e1 = sgn0(u) == sgn0(y)
        y = Fp.cmov(Fp.neg(y), y, e1); // 24.   y = CMOV(-y, y, e1)
        const tv4_inv = FpInvertBatch(Fp, [tv4], true)[0];
        x = Fp.mul(x, tv4_inv); // 25.   x = x / tv4
        return { x, y };
    };
}
function getWLengths(Fp, Fn) {
    return {
        secretKey: Fn.BYTES,
        publicKey: 1 + Fp.BYTES,
        publicKeyUncompressed: 1 + 2 * Fp.BYTES,
        publicKeyHasPrefix: true,
        signature: 2 * Fn.BYTES,
    };
}
/**
 * Sometimes users only need getPublicKey, getSharedSecret, and secret key handling.
 * This helper ensures no signature functionality is present. Less code, smaller bundle size.
 */
export function ecdh(Point, ecdhOpts = {}) {
    const { Fn } = Point;
    const randomBytes_ = ecdhOpts.randomBytes || randomBytesWeb;
    const lengths = Object.assign(getWLengths(Point.Fp, Fn), { seed: getMinHashLength(Fn.ORDER) });
    function isValidSecretKey(secretKey) {
        try {
            return !!_normFnElement(Fn, secretKey);
        }
        catch (error) {
            return false;
        }
    }
    function isValidPublicKey(publicKey, isCompressed) {
        const { publicKey: comp, publicKeyUncompressed } = lengths;
        try {
            const l = publicKey.length;
            if (isCompressed === true && l !== comp)
                return false;
            if (isCompressed === false && l !== publicKeyUncompressed)
                return false;
            return !!Point.fromBytes(publicKey);
        }
        catch (error) {
            return false;
        }
    }
    /**
     * Produces cryptographically secure secret key from random of size
     * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.
     */
    function randomSecretKey(seed = randomBytes_(lengths.seed)) {
        return mapHashToField(abytes(seed, lengths.seed, 'seed'), Fn.ORDER);
    }
    /**
     * Computes public key for a secret key. Checks for validity of the secret key.
     * @param isCompressed whether to return compact (default), or full key
     * @returns Public key, full when isCompressed=false; short when isCompressed=true
     */
    function getPublicKey(secretKey, isCompressed = true) {
        return Point.BASE.multiply(_normFnElement(Fn, secretKey)).toBytes(isCompressed);
    }
    function keygen(seed) {
        const secretKey = randomSecretKey(seed);
        return { secretKey, publicKey: getPublicKey(secretKey) };
    }
    /**
     * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.
     */
    function isProbPub(item) {
        if (typeof item === 'bigint')
            return false;
        if (item instanceof Point)
            return true;
        const { secretKey, publicKey, publicKeyUncompressed } = lengths;
        if (Fn.allowedLengths || secretKey === publicKey)
            return undefined;
        const l = ensureBytes('key', item).length;
        return l === publicKey || l === publicKeyUncompressed;
    }
    /**
     * ECDH (Elliptic Curve Diffie Hellman).
     * Computes shared public key from secret key A and public key B.
     * Checks: 1) secret key validity 2) shared key is on-curve.
     * Does NOT hash the result.
     * @param isCompressed whether to return compact (default), or full key
     * @returns shared public key
     */
    function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {
        if (isProbPub(secretKeyA) === true)
            throw new Error('first arg must be private key');
        if (isProbPub(publicKeyB) === false)
            throw new Error('second arg must be public key');
        const s = _normFnElement(Fn, secretKeyA);
        const b = Point.fromHex(publicKeyB); // checks for being on-curve
        return b.multiply(s).toBytes(isCompressed);
    }
    const utils = {
        isValidSecretKey,
        isValidPublicKey,
        randomSecretKey,
        // TODO: remove
        isValidPrivateKey: isValidSecretKey,
        randomPrivateKey: randomSecretKey,
        normPrivateKeyToScalar: (key) => _normFnElement(Fn, key),
        precompute(windowSize = 8, point = Point.BASE) {
            return point.precompute(windowSize, false);
        },
    };
    return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point, utils, lengths });
}
/**
 * Creates ECDSA signing interface for given elliptic curve `Point` and `hash` function.
 * We need `hash` for 2 features:
 * 1. Message prehash-ing. NOT used if `sign` / `verify` are called with `prehash: false`
 * 2. k generation in `sign`, using HMAC-drbg(hash)
 *
 * ECDSAOpts are only rarely needed.
 *
 * @example
 * ```js
 * const p256_Point = weierstrass(...);
 * const p256_sha256 = ecdsa(p256_Point, sha256);
 * const p256_sha224 = ecdsa(p256_Point, sha224);
 * const p256_sha224_r = ecdsa(p256_Point, sha224, { randomBytes: (length) => { ... } });
 * ```
 */
export function ecdsa(Point, hash, ecdsaOpts = {}) {
    ahash(hash);
    _validateObject(ecdsaOpts, {}, {
        hmac: 'function',
        lowS: 'boolean',
        randomBytes: 'function',
        bits2int: 'function',
        bits2int_modN: 'function',
    });
    const randomBytes = ecdsaOpts.randomBytes || randomBytesWeb;
    const hmac = ecdsaOpts.hmac ||
        ((key, ...msgs) => nobleHmac(hash, key, concatBytes(...msgs)));
    const { Fp, Fn } = Point;
    const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;
    const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);
    const defaultSigOpts = {
        prehash: false,
        lowS: typeof ecdsaOpts.lowS === 'boolean' ? ecdsaOpts.lowS : false,
        format: undefined, //'compact' as ECDSASigFormat,
        extraEntropy: false,
    };
    const defaultSigOpts_format = 'compact';
    function isBiggerThanHalfOrder(number) {
        const HALF = CURVE_ORDER >> _1n;
        return number > HALF;
    }
    function validateRS(title, num) {
        if (!Fn.isValidNot0(num))
            throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);
        return num;
    }
    function validateSigLength(bytes, format) {
        validateSigFormat(format);
        const size = lengths.signature;
        const sizer = format === 'compact' ? size : format === 'recovered' ? size + 1 : undefined;
        return abytes(bytes, sizer, `${format} signature`);
    }
    /**
     * ECDSA signature with its (r, s) properties. Supports compact, recovered & DER representations.
     */
    class Signature {
        constructor(r, s, recovery) {
            this.r = validateRS('r', r); // r in [1..N-1];
            this.s = validateRS('s', s); // s in [1..N-1];
            if (recovery != null)
                this.recovery = recovery;
            Object.freeze(this);
        }
        static fromBytes(bytes, format = defaultSigOpts_format) {
            validateSigLength(bytes, format);
            let recid;
            if (format === 'der') {
                const { r, s } = DER.toSig(abytes(bytes));
                return new Signature(r, s);
            }
            if (format === 'recovered') {
                recid = bytes[0];
                format = 'compact';
                bytes = bytes.subarray(1);
            }
            const L = Fn.BYTES;
            const r = bytes.subarray(0, L);
            const s = bytes.subarray(L, L * 2);
            return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);
        }
        static fromHex(hex, format) {
            return this.fromBytes(hexToBytes(hex), format);
        }
        addRecoveryBit(recovery) {
            return new Signature(this.r, this.s, recovery);
        }
        recoverPublicKey(messageHash) {
            const FIELD_ORDER = Fp.ORDER;
            const { r, s, recovery: rec } = this;
            if (rec == null || ![0, 1, 2, 3].includes(rec))
                throw new Error('recovery id invalid');
            // ECDSA recovery is hard for cofactor > 1 curves.
            // In sign, `r = q.x mod n`, and here we recover q.x from r.
            // While recovering q.x >= n, we need to add r+n for cofactor=1 curves.
            // However, for cofactor>1, r+n may not get q.x:
            // r+n*i would need to be done instead where i is unknown.
            // To easily get i, we either need to:
            // a. increase amount of valid recid values (4, 5...); OR
            // b. prohibit non-prime-order signatures (recid > 1).
            const hasCofactor = CURVE_ORDER * _2n < FIELD_ORDER;
            if (hasCofactor && rec > 1)
                throw new Error('recovery id is ambiguous for h>1 curve');
            const radj = rec === 2 || rec === 3 ? r + CURVE_ORDER : r;
            if (!Fp.isValid(radj))
                throw new Error('recovery id 2 or 3 invalid');
            const x = Fp.toBytes(radj);
            const R = Point.fromBytes(concatBytes(pprefix((rec & 1) === 0), x));
            const ir = Fn.inv(radj); // r^-1
            const h = bits2int_modN(ensureBytes('msgHash', messageHash)); // Truncate hash
            const u1 = Fn.create(-h * ir); // -hr^-1
            const u2 = Fn.create(s * ir); // sr^-1
            // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1). unsafe is fine: there is no private data.
            const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));
            if (Q.is0())
                throw new Error('point at infinify');
            Q.assertValidity();
            return Q;
        }
        // Signatures should be low-s, to prevent malleability.
        hasHighS() {
            return isBiggerThanHalfOrder(this.s);
        }
        toBytes(format = defaultSigOpts_format) {
            validateSigFormat(format);
            if (format === 'der')
                return hexToBytes(DER.hexFromSig(this));
            const r = Fn.toBytes(this.r);
            const s = Fn.toBytes(this.s);
            if (format === 'recovered') {
                if (this.recovery == null)
                    throw new Error('recovery bit must be present');
                return concatBytes(Uint8Array.of(this.recovery), r, s);
            }
            return concatBytes(r, s);
        }
        toHex(format) {
            return bytesToHex(this.toBytes(format));
        }
        // TODO: remove
        assertValidity() { }
        static fromCompact(hex) {
            return Signature.fromBytes(ensureBytes('sig', hex), 'compact');
        }
        static fromDER(hex) {
            return Signature.fromBytes(ensureBytes('sig', hex), 'der');
        }
        normalizeS() {
            return this.hasHighS() ? new Signature(this.r, Fn.neg(this.s), this.recovery) : this;
        }
        toDERRawBytes() {
            return this.toBytes('der');
        }
        toDERHex() {
            return bytesToHex(this.toBytes('der'));
        }
        toCompactRawBytes() {
            return this.toBytes('compact');
        }
        toCompactHex() {
            return bytesToHex(this.toBytes('compact'));
        }
    }
    // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.
    // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.
    // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.
    // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors
    const bits2int = ecdsaOpts.bits2int ||
        function bits2int_def(bytes) {
            // Our custom check "just in case", for protection against DoS
            if (bytes.length > 8192)
                throw new Error('input is too large');
            // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)
            // for some cases, since bytes.length * 8 is not actual bitLength.
            const num = bytesToNumberBE(bytes); // check for == u8 done here
            const delta = bytes.length * 8 - fnBits; // truncate to nBitLength leftmost bits
            return delta > 0 ? num >> BigInt(delta) : num;
        };
    const bits2int_modN = ecdsaOpts.bits2int_modN ||
        function bits2int_modN_def(bytes) {
            return Fn.create(bits2int(bytes)); // can't use bytesToNumberBE here
        };
    // Pads output with zero as per spec
    const ORDER_MASK = bitMask(fnBits);
    /** Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. */
    function int2octets(num) {
        // IMPORTANT: the check ensures working for case `Fn.BYTES != Fn.BITS * 8`
        aInRange('num < 2^' + fnBits, num, _0n, ORDER_MASK);
        return Fn.toBytes(num);
    }
    function validateMsgAndHash(message, prehash) {
        abytes(message, undefined, 'message');
        return prehash ? abytes(hash(message), undefined, 'prehashed message') : message;
    }
    /**
     * Steps A, D of RFC6979 3.2.
     * Creates RFC6979 seed; converts msg/privKey to numbers.
     * Used only in sign, not in verify.
     *
     * Warning: we cannot assume here that message has same amount of bytes as curve order,
     * this will be invalid at least for P521. Also it can be bigger for P224 + SHA256.
     */
    function prepSig(message, privateKey, opts) {
        if (['recovered', 'canonical'].some((k) => k in opts))
            throw new Error('sign() legacy options not supported');
        const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);
        message = validateMsgAndHash(message, prehash); // RFC6979 3.2 A: h1 = H(m)
        // We can't later call bits2octets, since nested bits2int is broken for curves
        // with fnBits % 8 !== 0. Because of that, we unwrap it here as int2octets call.
        // const bits2octets = (bits) => int2octets(bits2int_modN(bits))
        const h1int = bits2int_modN(message);
        const d = _normFnElement(Fn, privateKey); // validate secret key, convert to bigint
        const seedArgs = [int2octets(d), int2octets(h1int)];
        // extraEntropy. RFC6979 3.6: additional k' (optional).
        if (extraEntropy != null && extraEntropy !== false) {
            // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')
            // gen random bytes OR pass as-is
            const e = extraEntropy === true ? randomBytes(lengths.secretKey) : extraEntropy;
            seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes
        }
        const seed = concatBytes(...seedArgs); // Step D of RFC6979 3.2
        const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash!
        // Converts signature params into point w r/s, checks result for validity.
        // To transform k => Signature:
        // q = k⋅G
        // r = q.x mod n
        // s = k^-1(m + rd) mod n
        // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to
        // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:
        // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT
        function k2sig(kBytes) {
            // RFC 6979 Section 3.2, step 3: k = bits2int(T)
            // Important: all mod() calls here must be done over N
            const k = bits2int(kBytes); // mod n, not mod p
            if (!Fn.isValidNot0(k))
                return; // Valid scalars (including k) must be in 1..N-1
            const ik = Fn.inv(k); // k^-1 mod n
            const q = Point.BASE.multiply(k).toAffine(); // q = k⋅G
            const r = Fn.create(q.x); // r = q.x mod n
            if (r === _0n)
                return;
            const s = Fn.create(ik * Fn.create(m + r * d)); // Not using blinding here, see comment above
            if (s === _0n)
                return;
            let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n)
            let normS = s;
            if (lowS && isBiggerThanHalfOrder(s)) {
                normS = Fn.neg(s); // if lowS was passed, ensure s is always
                recovery ^= 1; // // in the bottom half of N
            }
            return new Signature(r, normS, recovery); // use normS, not s
        }
        return { seed, k2sig };
    }
    /**
     * Signs message hash with a secret key.
     *
     * ```
     * sign(m, d) where
     *   k = rfc6979_hmac_drbg(m, d)
     *   (x, y) = G × k
     *   r = x mod n
     *   s = (m + dr) / k mod n
     * ```
     */
    function sign(message, secretKey, opts = {}) {
        message = ensureBytes('message', message);
        const { seed, k2sig } = prepSig(message, secretKey, opts); // Steps A, D of RFC6979 3.2.
        const drbg = createHmacDrbg(hash.outputLen, Fn.BYTES, hmac);
        const sig = drbg(seed, k2sig); // Steps B, C, D, E, F, G
        return sig;
    }
    function tryParsingSig(sg) {
        // Try to deduce format
        let sig = undefined;
        const isHex = typeof sg === 'string' || isBytes(sg);
        const isObj = !isHex &&
            sg !== null &&
            typeof sg === 'object' &&
            typeof sg.r === 'bigint' &&
            typeof sg.s === 'bigint';
        if (!isHex && !isObj)
            throw new Error('invalid signature, expected Uint8Array, hex string or Signature instance');
        if (isObj) {
            sig = new Signature(sg.r, sg.s);
        }
        else if (isHex) {
            try {
                sig = Signature.fromBytes(ensureBytes('sig', sg), 'der');
            }
            catch (derError) {
                if (!(derError instanceof DER.Err))
                    throw derError;
            }
            if (!sig) {
                try {
                    sig = Signature.fromBytes(ensureBytes('sig', sg), 'compact');
                }
                catch (error) {
                    return false;
                }
            }
        }
        if (!sig)
            return false;
        return sig;
    }
    /**
     * Verifies a signature against message and public key.
     * Rejects lowS signatures by default: see {@link ECDSAVerifyOpts}.
     * Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:
     *
     * ```
     * verify(r, s, h, P) where
     *   u1 = hs^-1 mod n
     *   u2 = rs^-1 mod n
     *   R = u1⋅G + u2⋅P
     *   mod(R.x, n) == r
     * ```
     */
    function verify(signature, message, publicKey, opts = {}) {
        const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);
        publicKey = ensureBytes('publicKey', publicKey);
        message = validateMsgAndHash(ensureBytes('message', message), prehash);
        if ('strict' in opts)
            throw new Error('options.strict was renamed to lowS');
        const sig = format === undefined
            ? tryParsingSig(signature)
            : Signature.fromBytes(ensureBytes('sig', signature), format);
        if (sig === false)
            return false;
        try {
            const P = Point.fromBytes(publicKey);
            if (lowS && sig.hasHighS())
                return false;
            const { r, s } = sig;
            const h = bits2int_modN(message); // mod n, not mod p
            const is = Fn.inv(s); // s^-1 mod n
            const u1 = Fn.create(h * is); // u1 = hs^-1 mod n
            const u2 = Fn.create(r * is); // u2 = rs^-1 mod n
            const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2)); // u1⋅G + u2⋅P
            if (R.is0())
                return false;
            const v = Fn.create(R.x); // v = r.x mod n
            return v === r;
        }
        catch (e) {
            return false;
        }
    }
    function recoverPublicKey(signature, message, opts = {}) {
        const { prehash } = validateSigOpts(opts, defaultSigOpts);
        message = validateMsgAndHash(message, prehash);
        return Signature.fromBytes(signature, 'recovered').recoverPublicKey(message).toBytes();
    }
    return Object.freeze({
        keygen,
        getPublicKey,
        getSharedSecret,
        utils,
        lengths,
        Point,
        sign,
        verify,
        recoverPublicKey,
        Signature,
        hash,
    });
}
/** @deprecated use `weierstrass` in newer releases */
export function weierstrassPoints(c) {
    const { CURVE, curveOpts } = _weierstrass_legacy_opts_to_new(c);
    const Point = weierstrassN(CURVE, curveOpts);
    return _weierstrass_new_output_to_legacy(c, Point);
}
function _weierstrass_legacy_opts_to_new(c) {
    const CURVE = {
        a: c.a,
        b: c.b,
        p: c.Fp.ORDER,
        n: c.n,
        h: c.h,
        Gx: c.Gx,
        Gy: c.Gy,
    };
    const Fp = c.Fp;
    let allowedLengths = c.allowedPrivateKeyLengths
        ? Array.from(new Set(c.allowedPrivateKeyLengths.map((l) => Math.ceil(l / 2))))
        : undefined;
    const Fn = Field(CURVE.n, {
        BITS: c.nBitLength,
        allowedLengths: allowedLengths,
        modFromBytes: c.wrapPrivateKey,
    });
    const curveOpts = {
        Fp,
        Fn,
        allowInfinityPoint: c.allowInfinityPoint,
        endo: c.endo,
        isTorsionFree: c.isTorsionFree,
        clearCofactor: c.clearCofactor,
        fromBytes: c.fromBytes,
        toBytes: c.toBytes,
    };
    return { CURVE, curveOpts };
}
function _ecdsa_legacy_opts_to_new(c) {
    const { CURVE, curveOpts } = _weierstrass_legacy_opts_to_new(c);
    const ecdsaOpts = {
        hmac: c.hmac,
        randomBytes: c.randomBytes,
        lowS: c.lowS,
        bits2int: c.bits2int,
        bits2int_modN: c.bits2int_modN,
    };
    return { CURVE, curveOpts, hash: c.hash, ecdsaOpts };
}
export function _legacyHelperEquat(Fp, a, b) {
    /**
     * y² = x³ + ax + b: Short weierstrass curve formula. Takes x, returns y².
     * @returns y²
     */
    function weierstrassEquation(x) {
        const x2 = Fp.sqr(x); // x * x
        const x3 = Fp.mul(x2, x); // x² * x
        return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x³ + a * x + b
    }
    return weierstrassEquation;
}
function _weierstrass_new_output_to_legacy(c, Point) {
    const { Fp, Fn } = Point;
    function isWithinCurveOrder(num) {
        return inRange(num, _1n, Fn.ORDER);
    }
    const weierstrassEquation = _legacyHelperEquat(Fp, c.a, c.b);
    return Object.assign({}, {
        CURVE: c,
        Point: Point,
        ProjectivePoint: Point,
        normPrivateKeyToScalar: (key) => _normFnElement(Fn, key),
        weierstrassEquation,
        isWithinCurveOrder,
    });
}
function _ecdsa_new_output_to_legacy(c, _ecdsa) {
    const Point = _ecdsa.Point;
    return Object.assign({}, _ecdsa, {
        ProjectivePoint: Point,
        CURVE: Object.assign({}, c, nLength(Point.Fn.ORDER, Point.Fn.BITS)),
    });
}
// _ecdsa_legacy
export function weierstrass(c) {
    const { CURVE, curveOpts, hash, ecdsaOpts } = _ecdsa_legacy_opts_to_new(c);
    const Point = weierstrassN(CURVE, curveOpts);
    const signs = ecdsa(Point, hash, ecdsaOpts);
    return _ecdsa_new_output_to_legacy(c, signs);
}
//# sourceMappingURL=weierstrass.js.map/**
 * Internal module for NIST P256, P384, P521 curves.
 * Do not use for now.
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { sha256, sha384, sha512 } from '@noble/hashes/sha2.js';
import { createCurve } from "./_shortw_utils.js";
import { createHasher } from "./abstract/hash-to-curve.js";
import { Field } from "./abstract/modular.js";
import { mapToCurveSimpleSWU, } from "./abstract/weierstrass.js";
// p = 2n**224n * (2n**32n-1n) + 2n**192n + 2n**96n - 1n
// a = Fp256.create(BigInt('-3'));
const p256_CURVE = {
    p: BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff'),
    n: BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551'),
    h: BigInt(1),
    a: BigInt('0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc'),
    b: BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b'),
    Gx: BigInt('0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296'),
    Gy: BigInt('0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5'),
};
// p = 2n**384n - 2n**128n - 2n**96n + 2n**32n - 1n
const p384_CURVE = {
    p: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff'),
    n: BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973'),
    h: BigInt(1),
    a: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc'),
    b: BigInt('0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef'),
    Gx: BigInt('0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7'),
    Gy: BigInt('0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f'),
};
// p = 2n**521n - 1n
const p521_CURVE = {
    p: BigInt('0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'),
    n: BigInt('0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409'),
    h: BigInt(1),
    a: BigInt('0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc'),
    b: BigInt('0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00'),
    Gx: BigInt('0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66'),
    Gy: BigInt('0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650'),
};
const Fp256 = Field(p256_CURVE.p);
const Fp384 = Field(p384_CURVE.p);
const Fp521 = Field(p521_CURVE.p);
function createSWU(Point, opts) {
    const map = mapToCurveSimpleSWU(Point.Fp, opts);
    return (scalars) => map(scalars[0]);
}
/** NIST P256 (aka secp256r1, prime256v1) curve, ECDSA and ECDH methods. */
export const p256 = createCurve({ ...p256_CURVE, Fp: Fp256, lowS: false }, sha256);
/** Hashing / encoding to p256 points / field. RFC 9380 methods. */
export const p256_hasher = /* @__PURE__ */ (() => {
    return createHasher(p256.Point, createSWU(p256.Point, {
        A: p256_CURVE.a,
        B: p256_CURVE.b,
        Z: p256.Point.Fp.create(BigInt('-10')),
    }), {
        DST: 'P256_XMD:SHA-256_SSWU_RO_',
        encodeDST: 'P256_XMD:SHA-256_SSWU_NU_',
        p: p256_CURVE.p,
        m: 1,
        k: 128,
        expand: 'xmd',
        hash: sha256,
    });
})();
// export const p256_oprf: OPRF = createORPF({
//   name: 'P256-SHA256',
//   Point: p256.Point,
//   hash: sha256,
//   hashToGroup: p256_hasher.hashToCurve,
//   hashToScalar: p256_hasher.hashToScalar,
// });
/** NIST P384 (aka secp384r1) curve, ECDSA and ECDH methods. */
export const p384 = createCurve({ ...p384_CURVE, Fp: Fp384, lowS: false }, sha384);
/** Hashing / encoding to p384 points / field. RFC 9380 methods. */
export const p384_hasher = /* @__PURE__ */ (() => {
    return createHasher(p384.Point, createSWU(p384.Point, {
        A: p384_CURVE.a,
        B: p384_CURVE.b,
        Z: p384.Point.Fp.create(BigInt('-12')),
    }), {
        DST: 'P384_XMD:SHA-384_SSWU_RO_',
        encodeDST: 'P384_XMD:SHA-384_SSWU_NU_',
        p: p384_CURVE.p,
        m: 1,
        k: 192,
        expand: 'xmd',
        hash: sha384,
    });
})();
// export const p384_oprf: OPRF = createORPF({
//   name: 'P384-SHA384',
//   Point: p384.Point,
//   hash: sha384,
//   hashToGroup: p384_hasher.hashToCurve,
//   hashToScalar: p384_hasher.hashToScalar,
// });
// const Fn521 = Field(p521_CURVE.n, { allowedScalarLengths: [65, 66] });
/** NIST P521 (aka secp521r1) curve, ECDSA and ECDH methods. */
export const p521 = createCurve({ ...p521_CURVE, Fp: Fp521, lowS: false, allowedPrivateKeyLengths: [130, 131, 132] }, sha512);
/** @deprecated use `p256` for consistency with `p256_hasher` */
export const secp256r1 = p256;
/** @deprecated use `p384` for consistency with `p384_hasher` */
export const secp384r1 = p384;
/** @deprecated use `p521` for consistency with `p521_hasher` */
export const secp521r1 = p521;
/** Hashing / encoding to p521 points / field. RFC 9380 methods. */
export const p521_hasher = /* @__PURE__ */ (() => {
    return createHasher(p521.Point, createSWU(p521.Point, {
        A: p521_CURVE.a,
        B: p521_CURVE.b,
        Z: p521.Point.Fp.create(BigInt('-4')),
    }), {
        DST: 'P521_XMD:SHA-512_SSWU_RO_',
        encodeDST: 'P521_XMD:SHA-512_SSWU_NU_',
        p: p521_CURVE.p,
        m: 1,
        k: 256,
        expand: 'xmd',
        hash: sha512,
    });
})();
// export const p521_oprf: OPRF = createORPF({
//   name: 'P521-SHA512',
//   Point: p521.Point,
//   hash: sha512,
//   hashToGroup: p521_hasher.hashToCurve,
//   hashToScalar: p521_hasher.hashToScalar, // produces L=98 just like in RFC
// });
//# sourceMappingURL=nist.js.map/**
 * NIST secp256r1 aka p256.
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import {} from "./abstract/hash-to-curve.js";
import { p256_hasher, p256 as p256n } from "./nist.js";
/** @deprecated use `import { p256 } from '@noble/curves/nist.js';` */
export const p256 = p256n;
/** @deprecated use `import { p256 } from '@noble/curves/nist.js';` */
export const secp256r1 = p256n;
/** @deprecated use `import { p256_hasher } from '@noble/curves/nist.js';` */
export const hashToCurve = /* @__PURE__ */ (() => p256_hasher.hashToCurve)();
/** @deprecated use `import { p256_hasher } from '@noble/curves/nist.js';` */
export const encodeToCurve = /* @__PURE__ */ (() => p256_hasher.encodeToCurve)();
//# sourceMappingURL=p256.js.map{
  "type": "module",
  "sideEffects": false
}
/**
 * SECG secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).
 *
 * Belongs to Koblitz curves: it has efficiently-computable GLV endomorphism ψ,
 * check out {@link EndomorphismOpts}. Seems to be rigid (not backdoored).
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { sha256 } from '@noble/hashes/sha2.js';
import { randomBytes } from '@noble/hashes/utils.js';
import { createCurve } from "./_shortw_utils.js";
import { createHasher, isogenyMap, } from "./abstract/hash-to-curve.js";
import { Field, mapHashToField, mod, pow2 } from "./abstract/modular.js";
import { _normFnElement, mapToCurveSimpleSWU, } from "./abstract/weierstrass.js";
import { bytesToNumberBE, concatBytes, ensureBytes, inRange, numberToBytesBE, utf8ToBytes, } from "./utils.js";
// Seems like generator was produced from some seed:
// `Point.BASE.multiply(Point.Fn.inv(2n, N)).toAffine().x`
// // gives short x 0x3b78ce563f89a0ed9414f5aa28ad0d96d6795f9c63n
const secp256k1_CURVE = {
    p: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'),
    n: BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'),
    h: BigInt(1),
    a: BigInt(0),
    b: BigInt(7),
    Gx: BigInt('0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'),
    Gy: BigInt('0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8'),
};
const secp256k1_ENDO = {
    beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),
    basises: [
        [BigInt('0x3086d221a7d46bcde86c90e49284eb15'), -BigInt('0xe4437ed6010e88286f547fa90abfe4c3')],
        [BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'), BigInt('0x3086d221a7d46bcde86c90e49284eb15')],
    ],
};
const _0n = /* @__PURE__ */ BigInt(0);
const _1n = /* @__PURE__ */ BigInt(1);
const _2n = /* @__PURE__ */ BigInt(2);
/**
 * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.
 * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]
 */
function sqrtMod(y) {
    const P = secp256k1_CURVE.p;
    // prettier-ignore
    const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
    // prettier-ignore
    const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
    const b2 = (y * y * y) % P; // x^3, 11
    const b3 = (b2 * b2 * y) % P; // x^7
    const b6 = (pow2(b3, _3n, P) * b3) % P;
    const b9 = (pow2(b6, _3n, P) * b3) % P;
    const b11 = (pow2(b9, _2n, P) * b2) % P;
    const b22 = (pow2(b11, _11n, P) * b11) % P;
    const b44 = (pow2(b22, _22n, P) * b22) % P;
    const b88 = (pow2(b44, _44n, P) * b44) % P;
    const b176 = (pow2(b88, _88n, P) * b88) % P;
    const b220 = (pow2(b176, _44n, P) * b44) % P;
    const b223 = (pow2(b220, _3n, P) * b3) % P;
    const t1 = (pow2(b223, _23n, P) * b22) % P;
    const t2 = (pow2(t1, _6n, P) * b2) % P;
    const root = pow2(t2, _2n, P);
    if (!Fpk1.eql(Fpk1.sqr(root), y))
        throw new Error('Cannot find square root');
    return root;
}
const Fpk1 = Field(secp256k1_CURVE.p, { sqrt: sqrtMod });
/**
 * secp256k1 curve, ECDSA and ECDH methods.
 *
 * Field: `2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n`
 *
 * @example
 * ```js
 * import { secp256k1 } from '@noble/curves/secp256k1';
 * const { secretKey, publicKey } = secp256k1.keygen();
 * const msg = new TextEncoder().encode('hello');
 * const sig = secp256k1.sign(msg, secretKey);
 * const isValid = secp256k1.verify(sig, msg, publicKey) === true;
 * ```
 */
export const secp256k1 = createCurve({ ...secp256k1_CURVE, Fp: Fpk1, lowS: true, endo: secp256k1_ENDO }, sha256);
// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.
// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki
/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */
const TAGGED_HASH_PREFIXES = {};
function taggedHash(tag, ...messages) {
    let tagP = TAGGED_HASH_PREFIXES[tag];
    if (tagP === undefined) {
        const tagH = sha256(utf8ToBytes(tag));
        tagP = concatBytes(tagH, tagH);
        TAGGED_HASH_PREFIXES[tag] = tagP;
    }
    return sha256(concatBytes(tagP, ...messages));
}
// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03
const pointToBytes = (point) => point.toBytes(true).slice(1);
const Pointk1 = /* @__PURE__ */ (() => secp256k1.Point)();
const hasEven = (y) => y % _2n === _0n;
// Calculate point, scalar and bytes
function schnorrGetExtPubKey(priv) {
    const { Fn, BASE } = Pointk1;
    const d_ = _normFnElement(Fn, priv);
    const p = BASE.multiply(d_); // P = d'⋅G; 0 < d' < n check is done inside
    const scalar = hasEven(p.y) ? d_ : Fn.neg(d_);
    return { scalar, bytes: pointToBytes(p) };
}
/**
 * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.
 * @returns valid point checked for being on-curve
 */
function lift_x(x) {
    const Fp = Fpk1;
    if (!Fp.isValidNot0(x))
        throw new Error('invalid x: Fail if x ≥ p');
    const xx = Fp.create(x * x);
    const c = Fp.create(xx * x + BigInt(7)); // Let c = x³ + 7 mod p.
    let y = Fp.sqrt(c); // Let y = c^(p+1)/4 mod p. Same as sqrt().
    // Return the unique point P such that x(P) = x and
    // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.
    if (!hasEven(y))
        y = Fp.neg(y);
    const p = Pointk1.fromAffine({ x, y });
    p.assertValidity();
    return p;
}
const num = bytesToNumberBE;
/**
 * Create tagged hash, convert it to bigint, reduce modulo-n.
 */
function challenge(...args) {
    return Pointk1.Fn.create(num(taggedHash('BIP0340/challenge', ...args)));
}
/**
 * Schnorr public key is just `x` coordinate of Point as per BIP340.
 */
function schnorrGetPublicKey(secretKey) {
    return schnorrGetExtPubKey(secretKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G)
}
/**
 * Creates Schnorr signature as per BIP340. Verifies itself before returning anything.
 * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous.
 */
function schnorrSign(message, secretKey, auxRand = randomBytes(32)) {
    const { Fn } = Pointk1;
    const m = ensureBytes('message', message);
    const { bytes: px, scalar: d } = schnorrGetExtPubKey(secretKey); // checks for isWithinCurveOrder
    const a = ensureBytes('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array
    const t = Fn.toBytes(d ^ num(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a)
    const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m)
    // Let k' = int(rand) mod n. Fail if k' = 0. Let R = k'⋅G
    const { bytes: rx, scalar: k } = schnorrGetExtPubKey(rand);
    const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.
    const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n).
    sig.set(rx, 0);
    sig.set(Fn.toBytes(Fn.create(k + e * d)), 32);
    // If Verify(bytes(P), m, sig) (see below) returns failure, abort
    if (!schnorrVerify(sig, m, px))
        throw new Error('sign: Invalid signature produced');
    return sig;
}
/**
 * Verifies Schnorr signature.
 * Will swallow errors & return false except for initial type validation of arguments.
 */
function schnorrVerify(signature, message, publicKey) {
    const { Fn, BASE } = Pointk1;
    const sig = ensureBytes('signature', signature, 64);
    const m = ensureBytes('message', message);
    const pub = ensureBytes('publicKey', publicKey, 32);
    try {
        const P = lift_x(num(pub)); // P = lift_x(int(pk)); fail if that fails
        const r = num(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r ≥ p.
        if (!inRange(r, _1n, secp256k1_CURVE.p))
            return false;
        const s = num(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n.
        if (!inRange(s, _1n, secp256k1_CURVE.n))
            return false;
        // int(challenge(bytes(r)||bytes(P)||m))%n
        const e = challenge(Fn.toBytes(r), pointToBytes(P), m);
        // R = s⋅G - e⋅P, where -eP == (n-e)P
        const R = BASE.multiplyUnsafe(s).add(P.multiplyUnsafe(Fn.neg(e)));
        const { x, y } = R.toAffine();
        // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r.
        if (R.is0() || !hasEven(y) || x !== r)
            return false;
        return true;
    }
    catch (error) {
        return false;
    }
}
/**
 * Schnorr signatures over secp256k1.
 * https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki
 * @example
 * ```js
 * import { schnorr } from '@noble/curves/secp256k1';
 * const { secretKey, publicKey } = schnorr.keygen();
 * // const publicKey = schnorr.getPublicKey(secretKey);
 * const msg = new TextEncoder().encode('hello');
 * const sig = schnorr.sign(msg, secretKey);
 * const isValid = schnorr.verify(sig, msg, publicKey);
 * ```
 */
export const schnorr = /* @__PURE__ */ (() => {
    const size = 32;
    const seedLength = 48;
    const randomSecretKey = (seed = randomBytes(seedLength)) => {
        return mapHashToField(seed, secp256k1_CURVE.n);
    };
    // TODO: remove
    secp256k1.utils.randomSecretKey;
    function keygen(seed) {
        const secretKey = randomSecretKey(seed);
        return { secretKey, publicKey: schnorrGetPublicKey(secretKey) };
    }
    return {
        keygen,
        getPublicKey: schnorrGetPublicKey,
        sign: schnorrSign,
        verify: schnorrVerify,
        Point: Pointk1,
        utils: {
            randomSecretKey: randomSecretKey,
            randomPrivateKey: randomSecretKey,
            taggedHash,
            // TODO: remove
            lift_x,
            pointToBytes,
            numberToBytesBE,
            bytesToNumberBE,
            mod,
        },
        lengths: {
            secretKey: size,
            publicKey: size,
            publicKeyHasPrefix: false,
            signature: size * 2,
            seed: seedLength,
        },
    };
})();
const isoMap = /* @__PURE__ */ (() => isogenyMap(Fpk1, [
    // xNum
    [
        '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7',
        '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581',
        '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262',
        '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c',
    ],
    // xDen
    [
        '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b',
        '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14',
        '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1
    ],
    // yNum
    [
        '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c',
        '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3',
        '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931',
        '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84',
    ],
    // yDen
    [
        '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b',
        '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573',
        '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f',
        '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1
    ],
].map((i) => i.map((j) => BigInt(j)))))();
const mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fpk1, {
    A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),
    B: BigInt('1771'),
    Z: Fpk1.create(BigInt('-11')),
}))();
/** Hashing / encoding to secp256k1 points / field. RFC 9380 methods. */
export const secp256k1_hasher = /* @__PURE__ */ (() => createHasher(secp256k1.Point, (scalars) => {
    const { x, y } = mapSWU(Fpk1.create(scalars[0]));
    return isoMap(x, y);
}, {
    DST: 'secp256k1_XMD:SHA-256_SSWU_RO_',
    encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_',
    p: Fpk1.ORDER,
    m: 1,
    k: 128,
    expand: 'xmd',
    hash: sha256,
}))();
/** @deprecated use `import { secp256k1_hasher } from '@noble/curves/secp256k1.js';` */
export const hashToCurve = /* @__PURE__ */ (() => secp256k1_hasher.hashToCurve)();
/** @deprecated use `import { secp256k1_hasher } from '@noble/curves/secp256k1.js';` */
export const encodeToCurve = /* @__PURE__ */ (() => secp256k1_hasher.encodeToCurve)();
//# sourceMappingURL=secp256k1.js.map/**
 * Hex, bytes and number utilities.
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { abytes as abytes_, bytesToHex as bytesToHex_, concatBytes as concatBytes_, hexToBytes as hexToBytes_, isBytes as isBytes_, } from '@noble/hashes/utils.js';
export { abytes, anumber, bytesToHex, bytesToUtf8, concatBytes, hexToBytes, isBytes, randomBytes, utf8ToBytes, } from '@noble/hashes/utils.js';
const _0n = /* @__PURE__ */ BigInt(0);
const _1n = /* @__PURE__ */ BigInt(1);
export function abool(title, value) {
    if (typeof value !== 'boolean')
        throw new Error(title + ' boolean expected, got ' + value);
}
// tmp name until v2
export function _abool2(value, title = '') {
    if (typeof value !== 'boolean') {
        const prefix = title && `"${title}"`;
        throw new Error(prefix + 'expected boolean, got type=' + typeof value);
    }
    return value;
}
// tmp name until v2
/** Asserts something is Uint8Array. */
export function _abytes2(value, length, title = '') {
    const bytes = isBytes_(value);
    const len = value?.length;
    const needsLen = length !== undefined;
    if (!bytes || (needsLen && len !== length)) {
        const prefix = title && `"${title}" `;
        const ofLen = needsLen ? ` of length ${length}` : '';
        const got = bytes ? `length=${len}` : `type=${typeof value}`;
        throw new Error(prefix + 'expected Uint8Array' + ofLen + ', got ' + got);
    }
    return value;
}
// Used in weierstrass, der
export function numberToHexUnpadded(num) {
    const hex = num.toString(16);
    return hex.length & 1 ? '0' + hex : hex;
}
export function hexToNumber(hex) {
    if (typeof hex !== 'string')
        throw new Error('hex string expected, got ' + typeof hex);
    return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian
}
// BE: Big Endian, LE: Little Endian
export function bytesToNumberBE(bytes) {
    return hexToNumber(bytesToHex_(bytes));
}
export function bytesToNumberLE(bytes) {
    abytes_(bytes);
    return hexToNumber(bytesToHex_(Uint8Array.from(bytes).reverse()));
}
export function numberToBytesBE(n, len) {
    return hexToBytes_(n.toString(16).padStart(len * 2, '0'));
}
export function numberToBytesLE(n, len) {
    return numberToBytesBE(n, len).reverse();
}
// Unpadded, rarely used
export function numberToVarBytesBE(n) {
    return hexToBytes_(numberToHexUnpadded(n));
}
/**
 * Takes hex string or Uint8Array, converts to Uint8Array.
 * Validates output length.
 * Will throw error for other types.
 * @param title descriptive title for an error e.g. 'secret key'
 * @param hex hex string or Uint8Array
 * @param expectedLength optional, will compare to result array's length
 * @returns
 */
export function ensureBytes(title, hex, expectedLength) {
    let res;
    if (typeof hex === 'string') {
        try {
            res = hexToBytes_(hex);
        }
        catch (e) {
            throw new Error(title + ' must be hex string or Uint8Array, cause: ' + e);
        }
    }
    else if (isBytes_(hex)) {
        // Uint8Array.from() instead of hash.slice() because node.js Buffer
        // is instance of Uint8Array, and its slice() creates **mutable** copy
        res = Uint8Array.from(hex);
    }
    else {
        throw new Error(title + ' must be hex string or Uint8Array');
    }
    const len = res.length;
    if (typeof expectedLength === 'number' && len !== expectedLength)
        throw new Error(title + ' of length ' + expectedLength + ' expected, got ' + len);
    return res;
}
// Compares 2 u8a-s in kinda constant time
export function equalBytes(a, b) {
    if (a.length !== b.length)
        return false;
    let diff = 0;
    for (let i = 0; i < a.length; i++)
        diff |= a[i] ^ b[i];
    return diff === 0;
}
/**
 * Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,
 * and Buffer#slice creates mutable copy. Never use Buffers!
 */
export function copyBytes(bytes) {
    return Uint8Array.from(bytes);
}
/**
 * Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols
 * Should be safe to use for things expected to be ASCII.
 * Returns exact same result as utf8ToBytes for ASCII or throws.
 */
export function asciiToBytes(ascii) {
    return Uint8Array.from(ascii, (c, i) => {
        const charCode = c.charCodeAt(0);
        if (c.length !== 1 || charCode > 127) {
            throw new Error(`string contains non-ASCII character "${ascii[i]}" with code ${charCode} at position ${i}`);
        }
        return charCode;
    });
}
/**
 * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
 */
// export const utf8ToBytes: typeof utf8ToBytes_ = utf8ToBytes_;
/**
 * Converts bytes to string using UTF8 encoding.
 * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'
 */
// export const bytesToUtf8: typeof bytesToUtf8_ = bytesToUtf8_;
// Is positive bigint
const isPosBig = (n) => typeof n === 'bigint' && _0n <= n;
export function inRange(n, min, max) {
    return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
}
/**
 * Asserts min <= n < max. NOTE: It's < max and not <= max.
 * @example
 * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)
 */
export function aInRange(title, n, min, max) {
    // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?
    // consider P=256n, min=0n, max=P
    // - a for min=0 would require -1:          `inRange('x', x, -1n, P)`
    // - b would commonly require subtraction:  `inRange('x', x, 0n, P - 1n)`
    // - our way is the cleanest:               `inRange('x', x, 0n, P)
    if (!inRange(n, min, max))
        throw new Error('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);
}
// Bit operations
/**
 * Calculates amount of bits in a bigint.
 * Same as `n.toString(2).length`
 * TODO: merge with nLength in modular
 */
export function bitLen(n) {
    let len;
    for (len = 0; n > _0n; n >>= _1n, len += 1)
        ;
    return len;
}
/**
 * Gets single bit at position.
 * NOTE: first bit position is 0 (same as arrays)
 * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`
 */
export function bitGet(n, pos) {
    return (n >> BigInt(pos)) & _1n;
}
/**
 * Sets single bit at position.
 */
export function bitSet(n, pos, value) {
    return n | ((value ? _1n : _0n) << BigInt(pos));
}
/**
 * Calculate mask for N bits. Not using ** operator with bigints because of old engines.
 * Same as BigInt(`0b${Array(i).fill('1').join('')}`)
 */
export const bitMask = (n) => (_1n << BigInt(n)) - _1n;
/**
 * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
 * @returns function that will call DRBG until 2nd arg returns something meaningful
 * @example
 *   const drbg = createHmacDRBG<Key>(32, 32, hmac);
 *   drbg(seed, bytesToKey); // bytesToKey must return Key or undefined
 */
export function createHmacDrbg(hashLen, qByteLen, hmacFn) {
    if (typeof hashLen !== 'number' || hashLen < 2)
        throw new Error('hashLen must be a number');
    if (typeof qByteLen !== 'number' || qByteLen < 2)
        throw new Error('qByteLen must be a number');
    if (typeof hmacFn !== 'function')
        throw new Error('hmacFn must be a function');
    // Step B, Step C: set hashLen to 8*ceil(hlen/8)
    const u8n = (len) => new Uint8Array(len); // creates Uint8Array
    const u8of = (byte) => Uint8Array.of(byte); // another shortcut
    let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
    let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same
    let i = 0; // Iterations counter, will throw when over 1000
    const reset = () => {
        v.fill(1);
        k.fill(0);
        i = 0;
    };
    const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)
    const reseed = (seed = u8n(0)) => {
        // HMAC-DRBG reseed() function. Steps D-G
        k = h(u8of(0x00), seed); // k = hmac(k || v || 0x00 || seed)
        v = h(); // v = hmac(k || v)
        if (seed.length === 0)
            return;
        k = h(u8of(0x01), seed); // k = hmac(k || v || 0x01 || seed)
        v = h(); // v = hmac(k || v)
    };
    const gen = () => {
        // HMAC-DRBG generate() function
        if (i++ >= 1000)
            throw new Error('drbg: tried 1000 values');
        let len = 0;
        const out = [];
        while (len < qByteLen) {
            v = h();
            const sl = v.slice();
            out.push(sl);
            len += v.length;
        }
        return concatBytes_(...out);
    };
    const genUntil = (seed, pred) => {
        reset();
        reseed(seed); // Steps D-G
        let res = undefined; // Step H: grind until k is in [1..n-1]
        while (!(res = pred(gen())))
            reseed();
        reset();
        return res;
    };
    return genUntil;
}
// Validating curves and fields
const validatorFns = {
    bigint: (val) => typeof val === 'bigint',
    function: (val) => typeof val === 'function',
    boolean: (val) => typeof val === 'boolean',
    string: (val) => typeof val === 'string',
    stringOrUint8Array: (val) => typeof val === 'string' || isBytes_(val),
    isSafeInteger: (val) => Number.isSafeInteger(val),
    array: (val) => Array.isArray(val),
    field: (val, object) => object.Fp.isValid(val),
    hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),
};
// type Record<K extends string | number | symbol, T> = { [P in K]: T; }
export function validateObject(object, validators, optValidators = {}) {
    const checkField = (fieldName, type, isOptional) => {
        const checkVal = validatorFns[type];
        if (typeof checkVal !== 'function')
            throw new Error('invalid validator function');
        const val = object[fieldName];
        if (isOptional && val === undefined)
            return;
        if (!checkVal(val, object)) {
            throw new Error('param ' + String(fieldName) + ' is invalid. Expected ' + type + ', got ' + val);
        }
    };
    for (const [fieldName, type] of Object.entries(validators))
        checkField(fieldName, type, false);
    for (const [fieldName, type] of Object.entries(optValidators))
        checkField(fieldName, type, true);
    return object;
}
// validate type tests
// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };
// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!
// // Should fail type-check
// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });
// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });
// const z3 = validateObject(o, { test: 'boolean', z: 'bug' });
// const z4 = validateObject(o, { a: 'boolean', z: 'bug' });
export function isHash(val) {
    return typeof val === 'function' && Number.isSafeInteger(val.outputLen);
}
export function _validateObject(object, fields, optFields = {}) {
    if (!object || typeof object !== 'object')
        throw new Error('expected valid options object');
    function checkField(fieldName, expectedType, isOpt) {
        const val = object[fieldName];
        if (isOpt && val === undefined)
            return;
        const current = typeof val;
        if (current !== expectedType || val === null)
            throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
    }
    Object.entries(fields).forEach(([k, v]) => checkField(k, v, false));
    Object.entries(optFields).forEach(([k, v]) => checkField(k, v, true));
}
/**
 * throws not implemented error
 */
export const notImplemented = () => {
    throw new Error('not implemented');
};
/**
 * Memoizes (caches) computation result.
 * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.
 */
export function memoized(fn) {
    const map = new WeakMap();
    return (arg, ...args) => {
        const val = map.get(arg);
        if (val !== undefined)
            return val;
        const computed = fn(arg, ...args);
        map.set(arg, computed);
        return computed;
    };
}
//# sourceMappingURL=utils.js.map/**
 * Internal Merkle-Damgard hash utils.
 * @module
 */
import { Hash, abytes, aexists, aoutput, clean, createView, toBytes } from "./utils.js";
/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */
export function setBigUint64(view, byteOffset, value, isLE) {
    if (typeof view.setBigUint64 === 'function')
        return view.setBigUint64(byteOffset, value, isLE);
    const _32n = BigInt(32);
    const _u32_max = BigInt(0xffffffff);
    const wh = Number((value >> _32n) & _u32_max);
    const wl = Number(value & _u32_max);
    const h = isLE ? 4 : 0;
    const l = isLE ? 0 : 4;
    view.setUint32(byteOffset + h, wh, isLE);
    view.setUint32(byteOffset + l, wl, isLE);
}
/** Choice: a ? b : c */
export function Chi(a, b, c) {
    return (a & b) ^ (~a & c);
}
/** Majority function, true if any two inputs is true. */
export function Maj(a, b, c) {
    return (a & b) ^ (a & c) ^ (b & c);
}
/**
 * Merkle-Damgard hash construction base class.
 * Could be used to create MD5, RIPEMD, SHA1, SHA2.
 */
export class HashMD extends Hash {
    constructor(blockLen, outputLen, padOffset, isLE) {
        super();
        this.finished = false;
        this.length = 0;
        this.pos = 0;
        this.destroyed = false;
        this.blockLen = blockLen;
        this.outputLen = outputLen;
        this.padOffset = padOffset;
        this.isLE = isLE;
        this.buffer = new Uint8Array(blockLen);
        this.view = createView(this.buffer);
    }
    update(data) {
        aexists(this);
        data = toBytes(data);
        abytes(data);
        const { view, buffer, blockLen } = this;
        const len = data.length;
        for (let pos = 0; pos < len;) {
            const take = Math.min(blockLen - this.pos, len - pos);
            // Fast path: we have at least one block in input, cast it to view and process
            if (take === blockLen) {
                const dataView = createView(data);
                for (; blockLen <= len - pos; pos += blockLen)
                    this.process(dataView, pos);
                continue;
            }
            buffer.set(data.subarray(pos, pos + take), this.pos);
            this.pos += take;
            pos += take;
            if (this.pos === blockLen) {
                this.process(view, 0);
                this.pos = 0;
            }
        }
        this.length += data.length;
        this.roundClean();
        return this;
    }
    digestInto(out) {
        aexists(this);
        aoutput(out, this);
        this.finished = true;
        // Padding
        // We can avoid allocation of buffer for padding completely if it
        // was previously not allocated here. But it won't change performance.
        const { buffer, view, blockLen, isLE } = this;
        let { pos } = this;
        // append the bit '1' to the message
        buffer[pos++] = 0b10000000;
        clean(this.buffer.subarray(pos));
        // we have less than padOffset left in buffer, so we cannot put length in
        // current block, need process it and pad again
        if (this.padOffset > blockLen - pos) {
            this.process(view, 0);
            pos = 0;
        }
        // Pad until full block byte with zeros
        for (let i = pos; i < blockLen; i++)
            buffer[i] = 0;
        // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that
        // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.
        // So we just write lowest 64 bits of that value.
        setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
        this.process(view, 0);
        const oview = createView(out);
        const len = this.outputLen;
        // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT
        if (len % 4)
            throw new Error('_sha2: outputLen should be aligned to 32bit');
        const outLen = len / 4;
        const state = this.get();
        if (outLen > state.length)
            throw new Error('_sha2: outputLen bigger than state');
        for (let i = 0; i < outLen; i++)
            oview.setUint32(4 * i, state[i], isLE);
    }
    digest() {
        const { buffer, outputLen } = this;
        this.digestInto(buffer);
        const res = buffer.slice(0, outputLen);
        this.destroy();
        return res;
    }
    _cloneInto(to) {
        to || (to = new this.constructor());
        to.set(...this.get());
        const { blockLen, buffer, length, finished, destroyed, pos } = this;
        to.destroyed = destroyed;
        to.finished = finished;
        to.length = length;
        to.pos = pos;
        if (length % blockLen)
            to.buffer.set(buffer);
        return to;
    }
    clone() {
        return this._cloneInto();
    }
}
/**
 * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.
 * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.
 */
/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */
export const SHA256_IV = /* @__PURE__ */ Uint32Array.from([
    0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
]);
/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */
export const SHA224_IV = /* @__PURE__ */ Uint32Array.from([
    0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,
]);
/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */
export const SHA384_IV = /* @__PURE__ */ Uint32Array.from([
    0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,
    0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,
]);
/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */
export const SHA512_IV = /* @__PURE__ */ Uint32Array.from([
    0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,
    0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,
]);
//# sourceMappingURL=_md.js.map/**
 * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.
 * @todo re-check https://issues.chromium.org/issues/42212588
 * @module
 */
const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
const _32n = /* @__PURE__ */ BigInt(32);
function fromBig(n, le = false) {
    if (le)
        return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };
    return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
}
function split(lst, le = false) {
    const len = lst.length;
    let Ah = new Uint32Array(len);
    let Al = new Uint32Array(len);
    for (let i = 0; i < len; i++) {
        const { h, l } = fromBig(lst[i], le);
        [Ah[i], Al[i]] = [h, l];
    }
    return [Ah, Al];
}
const toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);
// for Shift in [0, 32)
const shrSH = (h, _l, s) => h >>> s;
const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
// Right rotate for Shift in [1, 32)
const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));
const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
// Right rotate for Shift in (32, 64), NOTE: 32 is special case.
const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));
const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));
// Right rotate for shift===32 (just swaps l&h)
const rotr32H = (_h, l) => l;
const rotr32L = (h, _l) => h;
// Left rotate for Shift in [1, 32)
const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));
const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));
// Left rotate for Shift in (32, 64), NOTE: 32 is special case.
const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));
const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));
// JS uses 32-bit signed integers for bitwise operations which means we cannot
// simple take carry out of low bit sum by shift, we need to use division.
function add(Ah, Al, Bh, Bl) {
    const l = (Al >>> 0) + (Bl >>> 0);
    return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };
}
// Addition with more than 2 elements
const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;
const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;
const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;
// prettier-ignore
export { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig };
// prettier-ignore
const u64 = {
    fromBig, split, toBig,
    shrSH, shrSL,
    rotrSH, rotrSL, rotrBH, rotrBL,
    rotr32H, rotr32L,
    rotlSH, rotlSL, rotlBH, rotlBL,
    add, add3L, add3H, add4L, add4H, add5H, add5L,
};
export default u64;
//# sourceMappingURL=_u64.js.mapexport const crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;
//# sourceMappingURL=crypto.js.map/**
 * HMAC: RFC2104 message authentication code.
 * @module
 */
import { abytes, aexists, ahash, clean, Hash, toBytes } from "./utils.js";
export class HMAC extends Hash {
    constructor(hash, _key) {
        super();
        this.finished = false;
        this.destroyed = false;
        ahash(hash);
        const key = toBytes(_key);
        this.iHash = hash.create();
        if (typeof this.iHash.update !== 'function')
            throw new Error('Expected instance of class which extends utils.Hash');
        this.blockLen = this.iHash.blockLen;
        this.outputLen = this.iHash.outputLen;
        const blockLen = this.blockLen;
        const pad = new Uint8Array(blockLen);
        // blockLen can be bigger than outputLen
        pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
        for (let i = 0; i < pad.length; i++)
            pad[i] ^= 0x36;
        this.iHash.update(pad);
        // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone
        this.oHash = hash.create();
        // Undo internal XOR && apply outer XOR
        for (let i = 0; i < pad.length; i++)
            pad[i] ^= 0x36 ^ 0x5c;
        this.oHash.update(pad);
        clean(pad);
    }
    update(buf) {
        aexists(this);
        this.iHash.update(buf);
        return this;
    }
    digestInto(out) {
        aexists(this);
        abytes(out, this.outputLen);
        this.finished = true;
        this.iHash.digestInto(out);
        this.oHash.update(out);
        this.oHash.digestInto(out);
        this.destroy();
    }
    digest() {
        const out = new Uint8Array(this.oHash.outputLen);
        this.digestInto(out);
        return out;
    }
    _cloneInto(to) {
        // Create new instance without calling constructor since key already in state and we don't know it.
        to || (to = Object.create(Object.getPrototypeOf(this), {}));
        const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
        to = to;
        to.finished = finished;
        to.destroyed = destroyed;
        to.blockLen = blockLen;
        to.outputLen = outputLen;
        to.oHash = oHash._cloneInto(to.oHash);
        to.iHash = iHash._cloneInto(to.iHash);
        return to;
    }
    clone() {
        return this._cloneInto();
    }
    destroy() {
        this.destroyed = true;
        this.oHash.destroy();
        this.iHash.destroy();
    }
}
/**
 * HMAC: RFC2104 message authentication code.
 * @param hash - function that would be used e.g. sha256
 * @param key - message key
 * @param message - message data
 * @example
 * import { hmac } from '@noble/hashes/hmac';
 * import { sha256 } from '@noble/hashes/sha2';
 * const mac1 = hmac(sha256, 'key', 'message');
 */
export const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
hmac.create = (hash, key) => new HMAC(hash, key);
//# sourceMappingURL=hmac.js.map/**

SHA1 (RFC 3174), MD5 (RFC 1321) and RIPEMD160 (RFC 2286) legacy, weak hash functions.
Don't use them in a new protocol. What "weak" means:

- Collisions can be made with 2^18 effort in MD5, 2^60 in SHA1, 2^80 in RIPEMD160.
- No practical pre-image attacks (only theoretical, 2^123.4)
- HMAC seems kinda ok: https://datatracker.ietf.org/doc/html/rfc6151
 * @module
 */
import { Chi, HashMD, Maj } from "./_md.js";
import { clean, createHasher, rotl } from "./utils.js";
/** Initial SHA1 state */
const SHA1_IV = /* @__PURE__ */ Uint32Array.from([
    0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0,
]);
// Reusable temporary buffer
const SHA1_W = /* @__PURE__ */ new Uint32Array(80);
/** SHA1 legacy hash class. */
export class SHA1 extends HashMD {
    constructor() {
        super(64, 20, 8, false);
        this.A = SHA1_IV[0] | 0;
        this.B = SHA1_IV[1] | 0;
        this.C = SHA1_IV[2] | 0;
        this.D = SHA1_IV[3] | 0;
        this.E = SHA1_IV[4] | 0;
    }
    get() {
        const { A, B, C, D, E } = this;
        return [A, B, C, D, E];
    }
    set(A, B, C, D, E) {
        this.A = A | 0;
        this.B = B | 0;
        this.C = C | 0;
        this.D = D | 0;
        this.E = E | 0;
    }
    process(view, offset) {
        for (let i = 0; i < 16; i++, offset += 4)
            SHA1_W[i] = view.getUint32(offset, false);
        for (let i = 16; i < 80; i++)
            SHA1_W[i] = rotl(SHA1_W[i - 3] ^ SHA1_W[i - 8] ^ SHA1_W[i - 14] ^ SHA1_W[i - 16], 1);
        // Compression function main loop, 80 rounds
        let { A, B, C, D, E } = this;
        for (let i = 0; i < 80; i++) {
            let F, K;
            if (i < 20) {
                F = Chi(B, C, D);
                K = 0x5a827999;
            }
            else if (i < 40) {
                F = B ^ C ^ D;
                K = 0x6ed9eba1;
            }
            else if (i < 60) {
                F = Maj(B, C, D);
                K = 0x8f1bbcdc;
            }
            else {
                F = B ^ C ^ D;
                K = 0xca62c1d6;
            }
            const T = (rotl(A, 5) + F + E + K + SHA1_W[i]) | 0;
            E = D;
            D = C;
            C = rotl(B, 30);
            B = A;
            A = T;
        }
        // Add the compressed chunk to the current hash value
        A = (A + this.A) | 0;
        B = (B + this.B) | 0;
        C = (C + this.C) | 0;
        D = (D + this.D) | 0;
        E = (E + this.E) | 0;
        this.set(A, B, C, D, E);
    }
    roundClean() {
        clean(SHA1_W);
    }
    destroy() {
        this.set(0, 0, 0, 0, 0);
        clean(this.buffer);
    }
}
/** SHA1 (RFC 3174) legacy hash function. It was cryptographically broken. */
export const sha1 = /* @__PURE__ */ createHasher(() => new SHA1());
/** Per-round constants */
const p32 = /* @__PURE__ */ Math.pow(2, 32);
const K = /* @__PURE__ */ Array.from({ length: 64 }, (_, i) => Math.floor(p32 * Math.abs(Math.sin(i + 1))));
/** md5 initial state: same as sha1, but 4 u32 instead of 5. */
const MD5_IV = /* @__PURE__ */ SHA1_IV.slice(0, 4);
// Reusable temporary buffer
const MD5_W = /* @__PURE__ */ new Uint32Array(16);
/** MD5 legacy hash class. */
export class MD5 extends HashMD {
    constructor() {
        super(64, 16, 8, true);
        this.A = MD5_IV[0] | 0;
        this.B = MD5_IV[1] | 0;
        this.C = MD5_IV[2] | 0;
        this.D = MD5_IV[3] | 0;
    }
    get() {
        const { A, B, C, D } = this;
        return [A, B, C, D];
    }
    set(A, B, C, D) {
        this.A = A | 0;
        this.B = B | 0;
        this.C = C | 0;
        this.D = D | 0;
    }
    process(view, offset) {
        for (let i = 0; i < 16; i++, offset += 4)
            MD5_W[i] = view.getUint32(offset, true);
        // Compression function main loop, 64 rounds
        let { A, B, C, D } = this;
        for (let i = 0; i < 64; i++) {
            let F, g, s;
            if (i < 16) {
                F = Chi(B, C, D);
                g = i;
                s = [7, 12, 17, 22];
            }
            else if (i < 32) {
                F = Chi(D, B, C);
                g = (5 * i + 1) % 16;
                s = [5, 9, 14, 20];
            }
            else if (i < 48) {
                F = B ^ C ^ D;
                g = (3 * i + 5) % 16;
                s = [4, 11, 16, 23];
            }
            else {
                F = C ^ (B | ~D);
                g = (7 * i) % 16;
                s = [6, 10, 15, 21];
            }
            F = F + A + K[i] + MD5_W[g];
            A = D;
            D = C;
            C = B;
            B = B + rotl(F, s[i % 4]);
        }
        // Add the compressed chunk to the current hash value
        A = (A + this.A) | 0;
        B = (B + this.B) | 0;
        C = (C + this.C) | 0;
        D = (D + this.D) | 0;
        this.set(A, B, C, D);
    }
    roundClean() {
        clean(MD5_W);
    }
    destroy() {
        this.set(0, 0, 0, 0);
        clean(this.buffer);
    }
}
/**
 * MD5 (RFC 1321) legacy hash function. It was cryptographically broken.
 * MD5 architecture is similar to SHA1, with some differences:
 * - Reduced output length: 16 bytes (128 bit) instead of 20
 * - 64 rounds, instead of 80
 * - Little-endian: could be faster, but will require more code
 * - Non-linear index selection: huge speed-up for unroll
 * - Per round constants: more memory accesses, additional speed-up for unroll
 */
export const md5 = /* @__PURE__ */ createHasher(() => new MD5());
// RIPEMD-160
const Rho160 = /* @__PURE__ */ Uint8Array.from([
    7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
]);
const Id160 = /* @__PURE__ */ (() => Uint8Array.from(new Array(16).fill(0).map((_, i) => i)))();
const Pi160 = /* @__PURE__ */ (() => Id160.map((i) => (9 * i + 5) % 16))();
const idxLR = /* @__PURE__ */ (() => {
    const L = [Id160];
    const R = [Pi160];
    const res = [L, R];
    for (let i = 0; i < 4; i++)
        for (let j of res)
            j.push(j[i].map((k) => Rho160[k]));
    return res;
})();
const idxL = /* @__PURE__ */ (() => idxLR[0])();
const idxR = /* @__PURE__ */ (() => idxLR[1])();
// const [idxL, idxR] = idxLR;
const shifts160 = /* @__PURE__ */ [
    [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8],
    [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7],
    [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9],
    [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6],
    [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5],
].map((i) => Uint8Array.from(i));
const shiftsL160 = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts160[i][j]));
const shiftsR160 = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts160[i][j]));
const Kl160 = /* @__PURE__ */ Uint32Array.from([
    0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e,
]);
const Kr160 = /* @__PURE__ */ Uint32Array.from([
    0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000,
]);
// It's called f() in spec.
function ripemd_f(group, x, y, z) {
    if (group === 0)
        return x ^ y ^ z;
    if (group === 1)
        return (x & y) | (~x & z);
    if (group === 2)
        return (x | ~y) ^ z;
    if (group === 3)
        return (x & z) | (y & ~z);
    return x ^ (y | ~z);
}
// Reusable temporary buffer
const BUF_160 = /* @__PURE__ */ new Uint32Array(16);
export class RIPEMD160 extends HashMD {
    constructor() {
        super(64, 20, 8, true);
        this.h0 = 0x67452301 | 0;
        this.h1 = 0xefcdab89 | 0;
        this.h2 = 0x98badcfe | 0;
        this.h3 = 0x10325476 | 0;
        this.h4 = 0xc3d2e1f0 | 0;
    }
    get() {
        const { h0, h1, h2, h3, h4 } = this;
        return [h0, h1, h2, h3, h4];
    }
    set(h0, h1, h2, h3, h4) {
        this.h0 = h0 | 0;
        this.h1 = h1 | 0;
        this.h2 = h2 | 0;
        this.h3 = h3 | 0;
        this.h4 = h4 | 0;
    }
    process(view, offset) {
        for (let i = 0; i < 16; i++, offset += 4)
            BUF_160[i] = view.getUint32(offset, true);
        // prettier-ignore
        let al = this.h0 | 0, ar = al, bl = this.h1 | 0, br = bl, cl = this.h2 | 0, cr = cl, dl = this.h3 | 0, dr = dl, el = this.h4 | 0, er = el;
        // Instead of iterating 0 to 80, we split it into 5 groups
        // And use the groups in constants, functions, etc. Much simpler
        for (let group = 0; group < 5; group++) {
            const rGroup = 4 - group;
            const hbl = Kl160[group], hbr = Kr160[group]; // prettier-ignore
            const rl = idxL[group], rr = idxR[group]; // prettier-ignore
            const sl = shiftsL160[group], sr = shiftsR160[group]; // prettier-ignore
            for (let i = 0; i < 16; i++) {
                const tl = (rotl(al + ripemd_f(group, bl, cl, dl) + BUF_160[rl[i]] + hbl, sl[i]) + el) | 0;
                al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore
            }
            // 2 loops are 10% faster
            for (let i = 0; i < 16; i++) {
                const tr = (rotl(ar + ripemd_f(rGroup, br, cr, dr) + BUF_160[rr[i]] + hbr, sr[i]) + er) | 0;
                ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr; // prettier-ignore
            }
        }
        // Add the compressed chunk to the current hash value
        this.set((this.h1 + cl + dr) | 0, (this.h2 + dl + er) | 0, (this.h3 + el + ar) | 0, (this.h4 + al + br) | 0, (this.h0 + bl + cr) | 0);
    }
    roundClean() {
        clean(BUF_160);
    }
    destroy() {
        this.destroyed = true;
        clean(this.buffer);
        this.set(0, 0, 0, 0, 0);
    }
}
/**
 * RIPEMD-160 - a legacy hash function from 1990s.
 * * https://homes.esat.kuleuven.be/~bosselae/ripemd160.html
 * * https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf
 */
export const ripemd160 = /* @__PURE__ */ createHasher(() => new RIPEMD160());
//# sourceMappingURL=legacy.js.map{
  "type": "module",
  "sideEffects": false,
  "browser": {
    "node:crypto": false
  },
  "node": {
    "./crypto": "./esm/cryptoNode.js"
  }
}
/**
 * PBKDF (RFC 2898). Can be used to create a key from password and salt.
 * @module
 */
import { hmac } from "./hmac.js";
// prettier-ignore
import { ahash, anumber, asyncLoop, checkOpts, clean, createView, Hash, kdfInputToBytes } from "./utils.js";
// Common prologue and epilogue for sync/async functions
function pbkdf2Init(hash, _password, _salt, _opts) {
    ahash(hash);
    const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts);
    const { c, dkLen, asyncTick } = opts;
    anumber(c);
    anumber(dkLen);
    anumber(asyncTick);
    if (c < 1)
        throw new Error('iterations (c) should be >= 1');
    const password = kdfInputToBytes(_password);
    const salt = kdfInputToBytes(_salt);
    // DK = PBKDF2(PRF, Password, Salt, c, dkLen);
    const DK = new Uint8Array(dkLen);
    // U1 = PRF(Password, Salt + INT_32_BE(i))
    const PRF = hmac.create(hash, password);
    const PRFSalt = PRF._cloneInto().update(salt);
    return { c, dkLen, asyncTick, DK, PRF, PRFSalt };
}
function pbkdf2Output(PRF, PRFSalt, DK, prfW, u) {
    PRF.destroy();
    PRFSalt.destroy();
    if (prfW)
        prfW.destroy();
    clean(u);
    return DK;
}
/**
 * PBKDF2-HMAC: RFC 2898 key derivation function
 * @param hash - hash function that would be used e.g. sha256
 * @param password - password from which a derived key is generated
 * @param salt - cryptographic salt
 * @param opts - {c, dkLen} where c is work factor and dkLen is output message size
 * @example
 * const key = pbkdf2(sha256, 'password', 'salt', { dkLen: 32, c: Math.pow(2, 18) });
 */
export function pbkdf2(hash, password, salt, opts) {
    const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);
    let prfW; // Working copy
    const arr = new Uint8Array(4);
    const view = createView(arr);
    const u = new Uint8Array(PRF.outputLen);
    // DK = T1 + T2 + ⋯ + Tdklen/hlen
    for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {
        // Ti = F(Password, Salt, c, i)
        const Ti = DK.subarray(pos, pos + PRF.outputLen);
        view.setInt32(0, ti, false);
        // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc
        // U1 = PRF(Password, Salt + INT_32_BE(i))
        (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);
        Ti.set(u.subarray(0, Ti.length));
        for (let ui = 1; ui < c; ui++) {
            // Uc = PRF(Password, Uc−1)
            PRF._cloneInto(prfW).update(u).digestInto(u);
            for (let i = 0; i < Ti.length; i++)
                Ti[i] ^= u[i];
        }
    }
    return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);
}
/**
 * PBKDF2-HMAC: RFC 2898 key derivation function. Async version.
 * @example
 * await pbkdf2Async(sha256, 'password', 'salt', { dkLen: 32, c: 500_000 });
 */
export async function pbkdf2Async(hash, password, salt, opts) {
    const { c, dkLen, asyncTick, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);
    let prfW; // Working copy
    const arr = new Uint8Array(4);
    const view = createView(arr);
    const u = new Uint8Array(PRF.outputLen);
    // DK = T1 + T2 + ⋯ + Tdklen/hlen
    for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {
        // Ti = F(Password, Salt, c, i)
        const Ti = DK.subarray(pos, pos + PRF.outputLen);
        view.setInt32(0, ti, false);
        // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc
        // U1 = PRF(Password, Salt + INT_32_BE(i))
        (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);
        Ti.set(u.subarray(0, Ti.length));
        await asyncLoop(c - 1, asyncTick, () => {
            // Uc = PRF(Password, Uc−1)
            PRF._cloneInto(prfW).update(u).digestInto(u);
            for (let i = 0; i < Ti.length; i++)
                Ti[i] ^= u[i];
        });
    }
    return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);
}
//# sourceMappingURL=pbkdf2.js.map/**
 * RFC 7914 Scrypt KDF. Can be used to create a key from password and salt.
 * @module
 */
import { pbkdf2 } from "./pbkdf2.js";
import { sha256 } from "./sha2.js";
// prettier-ignore
import { anumber, asyncLoop, checkOpts, clean, rotl, swap32IfBE, u32 } from "./utils.js";
// The main Scrypt loop: uses Salsa extensively.
// Six versions of the function were tried, this is the fastest one.
// prettier-ignore
function XorAndSalsa(prev, pi, input, ii, out, oi) {
    // Based on https://cr.yp.to/salsa20.html
    // Xor blocks
    let y00 = prev[pi++] ^ input[ii++], y01 = prev[pi++] ^ input[ii++];
    let y02 = prev[pi++] ^ input[ii++], y03 = prev[pi++] ^ input[ii++];
    let y04 = prev[pi++] ^ input[ii++], y05 = prev[pi++] ^ input[ii++];
    let y06 = prev[pi++] ^ input[ii++], y07 = prev[pi++] ^ input[ii++];
    let y08 = prev[pi++] ^ input[ii++], y09 = prev[pi++] ^ input[ii++];
    let y10 = prev[pi++] ^ input[ii++], y11 = prev[pi++] ^ input[ii++];
    let y12 = prev[pi++] ^ input[ii++], y13 = prev[pi++] ^ input[ii++];
    let y14 = prev[pi++] ^ input[ii++], y15 = prev[pi++] ^ input[ii++];
    // Save state to temporary variables (salsa)
    let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15;
    // Main loop (salsa)
    for (let i = 0; i < 8; i += 2) {
        x04 ^= rotl(x00 + x12 | 0, 7);
        x08 ^= rotl(x04 + x00 | 0, 9);
        x12 ^= rotl(x08 + x04 | 0, 13);
        x00 ^= rotl(x12 + x08 | 0, 18);
        x09 ^= rotl(x05 + x01 | 0, 7);
        x13 ^= rotl(x09 + x05 | 0, 9);
        x01 ^= rotl(x13 + x09 | 0, 13);
        x05 ^= rotl(x01 + x13 | 0, 18);
        x14 ^= rotl(x10 + x06 | 0, 7);
        x02 ^= rotl(x14 + x10 | 0, 9);
        x06 ^= rotl(x02 + x14 | 0, 13);
        x10 ^= rotl(x06 + x02 | 0, 18);
        x03 ^= rotl(x15 + x11 | 0, 7);
        x07 ^= rotl(x03 + x15 | 0, 9);
        x11 ^= rotl(x07 + x03 | 0, 13);
        x15 ^= rotl(x11 + x07 | 0, 18);
        x01 ^= rotl(x00 + x03 | 0, 7);
        x02 ^= rotl(x01 + x00 | 0, 9);
        x03 ^= rotl(x02 + x01 | 0, 13);
        x00 ^= rotl(x03 + x02 | 0, 18);
        x06 ^= rotl(x05 + x04 | 0, 7);
        x07 ^= rotl(x06 + x05 | 0, 9);
        x04 ^= rotl(x07 + x06 | 0, 13);
        x05 ^= rotl(x04 + x07 | 0, 18);
        x11 ^= rotl(x10 + x09 | 0, 7);
        x08 ^= rotl(x11 + x10 | 0, 9);
        x09 ^= rotl(x08 + x11 | 0, 13);
        x10 ^= rotl(x09 + x08 | 0, 18);
        x12 ^= rotl(x15 + x14 | 0, 7);
        x13 ^= rotl(x12 + x15 | 0, 9);
        x14 ^= rotl(x13 + x12 | 0, 13);
        x15 ^= rotl(x14 + x13 | 0, 18);
    }
    // Write output (salsa)
    out[oi++] = (y00 + x00) | 0;
    out[oi++] = (y01 + x01) | 0;
    out[oi++] = (y02 + x02) | 0;
    out[oi++] = (y03 + x03) | 0;
    out[oi++] = (y04 + x04) | 0;
    out[oi++] = (y05 + x05) | 0;
    out[oi++] = (y06 + x06) | 0;
    out[oi++] = (y07 + x07) | 0;
    out[oi++] = (y08 + x08) | 0;
    out[oi++] = (y09 + x09) | 0;
    out[oi++] = (y10 + x10) | 0;
    out[oi++] = (y11 + x11) | 0;
    out[oi++] = (y12 + x12) | 0;
    out[oi++] = (y13 + x13) | 0;
    out[oi++] = (y14 + x14) | 0;
    out[oi++] = (y15 + x15) | 0;
}
function BlockMix(input, ii, out, oi, r) {
    // The block B is r 128-byte chunks (which is equivalent of 2r 64-byte chunks)
    let head = oi + 0;
    let tail = oi + 16 * r;
    for (let i = 0; i < 16; i++)
        out[tail + i] = input[ii + (2 * r - 1) * 16 + i]; // X ← B[2r−1]
    for (let i = 0; i < r; i++, head += 16, ii += 16) {
        // We write odd & even Yi at same time. Even: 0bXXXXX0 Odd:  0bXXXXX1
        XorAndSalsa(out, tail, input, ii, out, head); // head[i] = Salsa(blockIn[2*i] ^ tail[i-1])
        if (i > 0)
            tail += 16; // First iteration overwrites tmp value in tail
        XorAndSalsa(out, head, input, (ii += 16), out, tail); // tail[i] = Salsa(blockIn[2*i+1] ^ head[i])
    }
}
// Common prologue and epilogue for sync/async functions
function scryptInit(password, salt, _opts) {
    // Maxmem - 1GB+1KB by default
    const opts = checkOpts({
        dkLen: 32,
        asyncTick: 10,
        maxmem: 1024 ** 3 + 1024,
    }, _opts);
    const { N, r, p, dkLen, asyncTick, maxmem, onProgress } = opts;
    anumber(N);
    anumber(r);
    anumber(p);
    anumber(dkLen);
    anumber(asyncTick);
    anumber(maxmem);
    if (onProgress !== undefined && typeof onProgress !== 'function')
        throw new Error('progressCb should be function');
    const blockSize = 128 * r;
    const blockSize32 = blockSize / 4;
    // Max N is 2^32 (Integrify is 32-bit). Real limit is 2^22: JS engines Uint8Array limit is 4GB in 2024.
    // Spec check `N >= 2^(blockSize / 8)` is not done for compat with popular libs,
    // which used incorrect r: 1, p: 8. Also, the check seems to be a spec error:
    // https://www.rfc-editor.org/errata_search.php?rfc=7914
    const pow32 = Math.pow(2, 32);
    if (N <= 1 || (N & (N - 1)) !== 0 || N > pow32) {
        throw new Error('Scrypt: N must be larger than 1, a power of 2, and less than 2^32');
    }
    if (p < 0 || p > ((pow32 - 1) * 32) / blockSize) {
        throw new Error('Scrypt: p must be a positive integer less than or equal to ((2^32 - 1) * 32) / (128 * r)');
    }
    if (dkLen < 0 || dkLen > (pow32 - 1) * 32) {
        throw new Error('Scrypt: dkLen should be positive integer less than or equal to (2^32 - 1) * 32');
    }
    const memUsed = blockSize * (N + p);
    if (memUsed > maxmem) {
        throw new Error('Scrypt: memused is bigger than maxMem. Expected 128 * r * (N + p) > maxmem of ' + maxmem);
    }
    // [B0...Bp−1] ← PBKDF2HMAC-SHA256(Passphrase, Salt, 1, blockSize*ParallelizationFactor)
    // Since it has only one iteration there is no reason to use async variant
    const B = pbkdf2(sha256, password, salt, { c: 1, dkLen: blockSize * p });
    const B32 = u32(B);
    // Re-used between parallel iterations. Array(iterations) of B
    const V = u32(new Uint8Array(blockSize * N));
    const tmp = u32(new Uint8Array(blockSize));
    let blockMixCb = () => { };
    if (onProgress) {
        const totalBlockMix = 2 * N * p;
        // Invoke callback if progress changes from 10.01 to 10.02
        // Allows to draw smooth progress bar on up to 8K screen
        const callbackPer = Math.max(Math.floor(totalBlockMix / 10000), 1);
        let blockMixCnt = 0;
        blockMixCb = () => {
            blockMixCnt++;
            if (onProgress && (!(blockMixCnt % callbackPer) || blockMixCnt === totalBlockMix))
                onProgress(blockMixCnt / totalBlockMix);
        };
    }
    return { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick };
}
function scryptOutput(password, dkLen, B, V, tmp) {
    const res = pbkdf2(sha256, password, B, { c: 1, dkLen });
    clean(B, V, tmp);
    return res;
}
/**
 * Scrypt KDF from RFC 7914.
 * @param password - pass
 * @param salt - salt
 * @param opts - parameters
 * - `N` is cpu/mem work factor (power of 2 e.g. 2**18)
 * - `r` is block size (8 is common), fine-tunes sequential memory read size and performance
 * - `p` is parallelization factor (1 is common)
 * - `dkLen` is output key length in bytes e.g. 32.
 * - `asyncTick` - (default: 10) max time in ms for which async function can block execution
 * - `maxmem` - (default: `1024 ** 3 + 1024` aka 1GB+1KB). A limit that the app could use for scrypt
 * - `onProgress` - callback function that would be executed for progress report
 * @returns Derived key
 * @example
 * scrypt('password', 'salt', { N: 2**18, r: 8, p: 1, dkLen: 32 });
 */
export function scrypt(password, salt, opts) {
    const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb } = scryptInit(password, salt, opts);
    swap32IfBE(B32);
    for (let pi = 0; pi < p; pi++) {
        const Pi = blockSize32 * pi;
        for (let i = 0; i < blockSize32; i++)
            V[i] = B32[Pi + i]; // V[0] = B[i]
        for (let i = 0, pos = 0; i < N - 1; i++) {
            BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]);
            blockMixCb();
        }
        BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element
        blockMixCb();
        for (let i = 0; i < N; i++) {
            // First u32 of the last 64-byte block (u32 is LE)
            const j = B32[Pi + blockSize32 - 16] % N; // j = Integrify(X) % iterations
            for (let k = 0; k < blockSize32; k++)
                tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; // tmp = B ^ V[j]
            BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j])
            blockMixCb();
        }
    }
    swap32IfBE(B32);
    return scryptOutput(password, dkLen, B, V, tmp);
}
/**
 * Scrypt KDF from RFC 7914. Async version.
 * @example
 * await scryptAsync('password', 'salt', { N: 2**18, r: 8, p: 1, dkLen: 32 });
 */
export async function scryptAsync(password, salt, opts) {
    const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick } = scryptInit(password, salt, opts);
    swap32IfBE(B32);
    for (let pi = 0; pi < p; pi++) {
        const Pi = blockSize32 * pi;
        for (let i = 0; i < blockSize32; i++)
            V[i] = B32[Pi + i]; // V[0] = B[i]
        let pos = 0;
        await asyncLoop(N - 1, asyncTick, () => {
            BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]);
            blockMixCb();
        });
        BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element
        blockMixCb();
        await asyncLoop(N, asyncTick, () => {
            // First u32 of the last 64-byte block (u32 is LE)
            const j = B32[Pi + blockSize32 - 16] % N; // j = Integrify(X) % iterations
            for (let k = 0; k < blockSize32; k++)
                tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; // tmp = B ^ V[j]
            BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j])
            blockMixCb();
        });
    }
    swap32IfBE(B32);
    return scryptOutput(password, dkLen, B, V, tmp);
}
//# sourceMappingURL=scrypt.js.map/**
 * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.
 * SHA256 is the fastest hash implementable in JS, even faster than Blake3.
 * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and
 * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).
 * @module
 */
import { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from "./_md.js";
import * as u64 from "./_u64.js";
import { clean, createHasher, rotr } from "./utils.js";
/**
 * Round constants:
 * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)
 */
// prettier-ignore
const SHA256_K = /* @__PURE__ */ Uint32Array.from([
    0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
    0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
    0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
    0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
    0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
    0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
    0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
    0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
]);
/** Reusable temporary buffer. "W" comes straight from spec. */
const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
export class SHA256 extends HashMD {
    constructor(outputLen = 32) {
        super(64, outputLen, 8, false);
        // We cannot use array here since array allows indexing by variable
        // which means optimizer/compiler cannot use registers.
        this.A = SHA256_IV[0] | 0;
        this.B = SHA256_IV[1] | 0;
        this.C = SHA256_IV[2] | 0;
        this.D = SHA256_IV[3] | 0;
        this.E = SHA256_IV[4] | 0;
        this.F = SHA256_IV[5] | 0;
        this.G = SHA256_IV[6] | 0;
        this.H = SHA256_IV[7] | 0;
    }
    get() {
        const { A, B, C, D, E, F, G, H } = this;
        return [A, B, C, D, E, F, G, H];
    }
    // prettier-ignore
    set(A, B, C, D, E, F, G, H) {
        this.A = A | 0;
        this.B = B | 0;
        this.C = C | 0;
        this.D = D | 0;
        this.E = E | 0;
        this.F = F | 0;
        this.G = G | 0;
        this.H = H | 0;
    }
    process(view, offset) {
        // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array
        for (let i = 0; i < 16; i++, offset += 4)
            SHA256_W[i] = view.getUint32(offset, false);
        for (let i = 16; i < 64; i++) {
            const W15 = SHA256_W[i - 15];
            const W2 = SHA256_W[i - 2];
            const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);
            const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);
            SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;
        }
        // Compression function main loop, 64 rounds
        let { A, B, C, D, E, F, G, H } = this;
        for (let i = 0; i < 64; i++) {
            const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
            const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
            const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
            const T2 = (sigma0 + Maj(A, B, C)) | 0;
            H = G;
            G = F;
            F = E;
            E = (D + T1) | 0;
            D = C;
            C = B;
            B = A;
            A = (T1 + T2) | 0;
        }
        // Add the compressed chunk to the current hash value
        A = (A + this.A) | 0;
        B = (B + this.B) | 0;
        C = (C + this.C) | 0;
        D = (D + this.D) | 0;
        E = (E + this.E) | 0;
        F = (F + this.F) | 0;
        G = (G + this.G) | 0;
        H = (H + this.H) | 0;
        this.set(A, B, C, D, E, F, G, H);
    }
    roundClean() {
        clean(SHA256_W);
    }
    destroy() {
        this.set(0, 0, 0, 0, 0, 0, 0, 0);
        clean(this.buffer);
    }
}
export class SHA224 extends SHA256 {
    constructor() {
        super(28);
        this.A = SHA224_IV[0] | 0;
        this.B = SHA224_IV[1] | 0;
        this.C = SHA224_IV[2] | 0;
        this.D = SHA224_IV[3] | 0;
        this.E = SHA224_IV[4] | 0;
        this.F = SHA224_IV[5] | 0;
        this.G = SHA224_IV[6] | 0;
        this.H = SHA224_IV[7] | 0;
    }
}
// SHA2-512 is slower than sha256 in js because u64 operations are slow.
// Round contants
// First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409
// prettier-ignore
const K512 = /* @__PURE__ */ (() => u64.split([
    '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',
    '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',
    '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',
    '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',
    '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',
    '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',
    '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',
    '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',
    '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',
    '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',
    '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',
    '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',
    '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',
    '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',
    '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',
    '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',
    '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',
    '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',
    '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',
    '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'
].map(n => BigInt(n))))();
const SHA512_Kh = /* @__PURE__ */ (() => K512[0])();
const SHA512_Kl = /* @__PURE__ */ (() => K512[1])();
// Reusable temporary buffers
const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
export class SHA512 extends HashMD {
    constructor(outputLen = 64) {
        super(128, outputLen, 16, false);
        // We cannot use array here since array allows indexing by variable
        // which means optimizer/compiler cannot use registers.
        // h -- high 32 bits, l -- low 32 bits
        this.Ah = SHA512_IV[0] | 0;
        this.Al = SHA512_IV[1] | 0;
        this.Bh = SHA512_IV[2] | 0;
        this.Bl = SHA512_IV[3] | 0;
        this.Ch = SHA512_IV[4] | 0;
        this.Cl = SHA512_IV[5] | 0;
        this.Dh = SHA512_IV[6] | 0;
        this.Dl = SHA512_IV[7] | 0;
        this.Eh = SHA512_IV[8] | 0;
        this.El = SHA512_IV[9] | 0;
        this.Fh = SHA512_IV[10] | 0;
        this.Fl = SHA512_IV[11] | 0;
        this.Gh = SHA512_IV[12] | 0;
        this.Gl = SHA512_IV[13] | 0;
        this.Hh = SHA512_IV[14] | 0;
        this.Hl = SHA512_IV[15] | 0;
    }
    // prettier-ignore
    get() {
        const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
        return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
    }
    // prettier-ignore
    set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
        this.Ah = Ah | 0;
        this.Al = Al | 0;
        this.Bh = Bh | 0;
        this.Bl = Bl | 0;
        this.Ch = Ch | 0;
        this.Cl = Cl | 0;
        this.Dh = Dh | 0;
        this.Dl = Dl | 0;
        this.Eh = Eh | 0;
        this.El = El | 0;
        this.Fh = Fh | 0;
        this.Fl = Fl | 0;
        this.Gh = Gh | 0;
        this.Gl = Gl | 0;
        this.Hh = Hh | 0;
        this.Hl = Hl | 0;
    }
    process(view, offset) {
        // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array
        for (let i = 0; i < 16; i++, offset += 4) {
            SHA512_W_H[i] = view.getUint32(offset);
            SHA512_W_L[i] = view.getUint32((offset += 4));
        }
        for (let i = 16; i < 80; i++) {
            // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)
            const W15h = SHA512_W_H[i - 15] | 0;
            const W15l = SHA512_W_L[i - 15] | 0;
            const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);
            const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);
            // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)
            const W2h = SHA512_W_H[i - 2] | 0;
            const W2l = SHA512_W_L[i - 2] | 0;
            const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);
            const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);
            // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];
            const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
            const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
            SHA512_W_H[i] = SUMh | 0;
            SHA512_W_L[i] = SUMl | 0;
        }
        let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
        // Compression function main loop, 80 rounds
        for (let i = 0; i < 80; i++) {
            // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)
            const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);
            const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);
            //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
            const CHIh = (Eh & Fh) ^ (~Eh & Gh);
            const CHIl = (El & Fl) ^ (~El & Gl);
            // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]
            // prettier-ignore
            const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
            const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
            const T1l = T1ll | 0;
            // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)
            const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);
            const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);
            const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);
            const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);
            Hh = Gh | 0;
            Hl = Gl | 0;
            Gh = Fh | 0;
            Gl = Fl | 0;
            Fh = Eh | 0;
            Fl = El | 0;
            ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
            Dh = Ch | 0;
            Dl = Cl | 0;
            Ch = Bh | 0;
            Cl = Bl | 0;
            Bh = Ah | 0;
            Bl = Al | 0;
            const All = u64.add3L(T1l, sigma0l, MAJl);
            Ah = u64.add3H(All, T1h, sigma0h, MAJh);
            Al = All | 0;
        }
        // Add the compressed chunk to the current hash value
        ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
        ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
        ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
        ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
        ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
        ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
        ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
        ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
        this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
    }
    roundClean() {
        clean(SHA512_W_H, SHA512_W_L);
    }
    destroy() {
        clean(this.buffer);
        this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
    }
}
export class SHA384 extends SHA512 {
    constructor() {
        super(48);
        this.Ah = SHA384_IV[0] | 0;
        this.Al = SHA384_IV[1] | 0;
        this.Bh = SHA384_IV[2] | 0;
        this.Bl = SHA384_IV[3] | 0;
        this.Ch = SHA384_IV[4] | 0;
        this.Cl = SHA384_IV[5] | 0;
        this.Dh = SHA384_IV[6] | 0;
        this.Dl = SHA384_IV[7] | 0;
        this.Eh = SHA384_IV[8] | 0;
        this.El = SHA384_IV[9] | 0;
        this.Fh = SHA384_IV[10] | 0;
        this.Fl = SHA384_IV[11] | 0;
        this.Gh = SHA384_IV[12] | 0;
        this.Gl = SHA384_IV[13] | 0;
        this.Hh = SHA384_IV[14] | 0;
        this.Hl = SHA384_IV[15] | 0;
    }
}
/**
 * Truncated SHA512/256 and SHA512/224.
 * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as "intermediary" IV of SHA512/t.
 * Then t hashes string to produce result IV.
 * See `test/misc/sha2-gen-iv.js`.
 */
/** SHA512/224 IV */
const T224_IV = /* @__PURE__ */ Uint32Array.from([
    0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,
    0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,
]);
/** SHA512/256 IV */
const T256_IV = /* @__PURE__ */ Uint32Array.from([
    0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,
    0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,
]);
export class SHA512_224 extends SHA512 {
    constructor() {
        super(28);
        this.Ah = T224_IV[0] | 0;
        this.Al = T224_IV[1] | 0;
        this.Bh = T224_IV[2] | 0;
        this.Bl = T224_IV[3] | 0;
        this.Ch = T224_IV[4] | 0;
        this.Cl = T224_IV[5] | 0;
        this.Dh = T224_IV[6] | 0;
        this.Dl = T224_IV[7] | 0;
        this.Eh = T224_IV[8] | 0;
        this.El = T224_IV[9] | 0;
        this.Fh = T224_IV[10] | 0;
        this.Fl = T224_IV[11] | 0;
        this.Gh = T224_IV[12] | 0;
        this.Gl = T224_IV[13] | 0;
        this.Hh = T224_IV[14] | 0;
        this.Hl = T224_IV[15] | 0;
    }
}
export class SHA512_256 extends SHA512 {
    constructor() {
        super(32);
        this.Ah = T256_IV[0] | 0;
        this.Al = T256_IV[1] | 0;
        this.Bh = T256_IV[2] | 0;
        this.Bl = T256_IV[3] | 0;
        this.Ch = T256_IV[4] | 0;
        this.Cl = T256_IV[5] | 0;
        this.Dh = T256_IV[6] | 0;
        this.Dl = T256_IV[7] | 0;
        this.Eh = T256_IV[8] | 0;
        this.El = T256_IV[9] | 0;
        this.Fh = T256_IV[10] | 0;
        this.Fl = T256_IV[11] | 0;
        this.Gh = T256_IV[12] | 0;
        this.Gl = T256_IV[13] | 0;
        this.Hh = T256_IV[14] | 0;
        this.Hl = T256_IV[15] | 0;
    }
}
/**
 * SHA2-256 hash function from RFC 4634.
 *
 * It is the fastest JS hash, even faster than Blake3.
 * To break sha256 using birthday attack, attackers need to try 2^128 hashes.
 * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
 */
export const sha256 = /* @__PURE__ */ createHasher(() => new SHA256());
/** SHA2-224 hash function from RFC 4634 */
export const sha224 = /* @__PURE__ */ createHasher(() => new SHA224());
/** SHA2-512 hash function from RFC 4634. */
export const sha512 = /* @__PURE__ */ createHasher(() => new SHA512());
/** SHA2-384 hash function from RFC 4634. */
export const sha384 = /* @__PURE__ */ createHasher(() => new SHA384());
/**
 * SHA2-512/256 "truncated" hash function, with improved resistance to length extension attacks.
 * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).
 */
export const sha512_256 = /* @__PURE__ */ createHasher(() => new SHA512_256());
/**
 * SHA2-512/224 "truncated" hash function, with improved resistance to length extension attacks.
 * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).
 */
export const sha512_224 = /* @__PURE__ */ createHasher(() => new SHA512_224());
//# sourceMappingURL=sha2.js.map/**
 * Utilities for hex, bytes, CSPRNG.
 * @module
 */
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
// node.js versions earlier than v19 don't declare it in global scope.
// For node.js, package.json#exports field mapping rewrites import
// from `crypto` to `cryptoNode`, which imports native module.
// Makes the utils un-importable in browsers without a bundler.
// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.
import { crypto } from '@noble/hashes/crypto';
/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */
export function isBytes(a) {
    return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
}
/** Asserts something is positive integer. */
export function anumber(n) {
    if (!Number.isSafeInteger(n) || n < 0)
        throw new Error('positive integer expected, got ' + n);
}
/** Asserts something is Uint8Array. */
export function abytes(b, ...lengths) {
    if (!isBytes(b))
        throw new Error('Uint8Array expected');
    if (lengths.length > 0 && !lengths.includes(b.length))
        throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);
}
/** Asserts something is hash */
export function ahash(h) {
    if (typeof h !== 'function' || typeof h.create !== 'function')
        throw new Error('Hash should be wrapped by utils.createHasher');
    anumber(h.outputLen);
    anumber(h.blockLen);
}
/** Asserts a hash instance has not been destroyed / finished */
export function aexists(instance, checkFinished = true) {
    if (instance.destroyed)
        throw new Error('Hash instance has been destroyed');
    if (checkFinished && instance.finished)
        throw new Error('Hash#digest() has already been called');
}
/** Asserts output is properly-sized byte array */
export function aoutput(out, instance) {
    abytes(out);
    const min = instance.outputLen;
    if (out.length < min) {
        throw new Error('digestInto() expects output buffer of length at least ' + min);
    }
}
/** Cast u8 / u16 / u32 to u8. */
export function u8(arr) {
    return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
}
/** Cast u8 / u16 / u32 to u32. */
export function u32(arr) {
    return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
}
/** Zeroize a byte array. Warning: JS provides no guarantees. */
export function clean(...arrays) {
    for (let i = 0; i < arrays.length; i++) {
        arrays[i].fill(0);
    }
}
/** Create DataView of an array for easy byte-level manipulation. */
export function createView(arr) {
    return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
}
/** The rotate right (circular right shift) operation for uint32 */
export function rotr(word, shift) {
    return (word << (32 - shift)) | (word >>> shift);
}
/** The rotate left (circular left shift) operation for uint32 */
export function rotl(word, shift) {
    return (word << shift) | ((word >>> (32 - shift)) >>> 0);
}
/** Is current platform little-endian? Most are. Big-Endian platform: IBM */
export const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();
/** The byte swap operation for uint32 */
export function byteSwap(word) {
    return (((word << 24) & 0xff000000) |
        ((word << 8) & 0xff0000) |
        ((word >>> 8) & 0xff00) |
        ((word >>> 24) & 0xff));
}
/** Conditionally byte swap if on a big-endian platform */
export const swap8IfBE = isLE
    ? (n) => n
    : (n) => byteSwap(n);
/** @deprecated */
export const byteSwapIfBE = swap8IfBE;
/** In place byte swap for Uint32Array */
export function byteSwap32(arr) {
    for (let i = 0; i < arr.length; i++) {
        arr[i] = byteSwap(arr[i]);
    }
    return arr;
}
export const swap32IfBE = isLE
    ? (u) => u
    : byteSwap32;
// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex
const hasHexBuiltin = /* @__PURE__ */ (() => 
// @ts-ignore
typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();
// Array where index 0xf0 (240) is mapped to string 'f0'
const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
/**
 * Convert byte array to hex string. Uses built-in function, when available.
 * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
 */
export function bytesToHex(bytes) {
    abytes(bytes);
    // @ts-ignore
    if (hasHexBuiltin)
        return bytes.toHex();
    // pre-caching improves the speed 6x
    let hex = '';
    for (let i = 0; i < bytes.length; i++) {
        hex += hexes[bytes[i]];
    }
    return hex;
}
// We use optimized technique to convert hex string to byte array
const asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
function asciiToBase16(ch) {
    if (ch >= asciis._0 && ch <= asciis._9)
        return ch - asciis._0; // '2' => 50-48
    if (ch >= asciis.A && ch <= asciis.F)
        return ch - (asciis.A - 10); // 'B' => 66-(65-10)
    if (ch >= asciis.a && ch <= asciis.f)
        return ch - (asciis.a - 10); // 'b' => 98-(97-10)
    return;
}
/**
 * Convert hex string to byte array. Uses built-in function, when available.
 * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
 */
export function hexToBytes(hex) {
    if (typeof hex !== 'string')
        throw new Error('hex string expected, got ' + typeof hex);
    // @ts-ignore
    if (hasHexBuiltin)
        return Uint8Array.fromHex(hex);
    const hl = hex.length;
    const al = hl / 2;
    if (hl % 2)
        throw new Error('hex string expected, got unpadded hex of length ' + hl);
    const array = new Uint8Array(al);
    for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
        const n1 = asciiToBase16(hex.charCodeAt(hi));
        const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
        if (n1 === undefined || n2 === undefined) {
            const char = hex[hi] + hex[hi + 1];
            throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
        }
        array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163
    }
    return array;
}
/**
 * There is no setImmediate in browser and setTimeout is slow.
 * Call of async fn will return Promise, which will be fullfiled only on
 * next scheduler queue processing step and this is exactly what we need.
 */
export const nextTick = async () => { };
/** Returns control to thread each 'tick' ms to avoid blocking. */
export async function asyncLoop(iters, tick, cb) {
    let ts = Date.now();
    for (let i = 0; i < iters; i++) {
        cb(i);
        // Date.now() is not monotonic, so in case if clock goes backwards we return return control too
        const diff = Date.now() - ts;
        if (diff >= 0 && diff < tick)
            continue;
        await nextTick();
        ts += diff;
    }
}
/**
 * Converts string to bytes using UTF8 encoding.
 * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])
 */
export function utf8ToBytes(str) {
    if (typeof str !== 'string')
        throw new Error('string expected');
    return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
}
/**
 * Converts bytes to string using UTF8 encoding.
 * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'
 */
export function bytesToUtf8(bytes) {
    return new TextDecoder().decode(bytes);
}
/**
 * Normalizes (non-hex) string or Uint8Array to Uint8Array.
 * Warning: when Uint8Array is passed, it would NOT get copied.
 * Keep in mind for future mutable operations.
 */
export function toBytes(data) {
    if (typeof data === 'string')
        data = utf8ToBytes(data);
    abytes(data);
    return data;
}
/**
 * Helper for KDFs: consumes uint8array or string.
 * When string is passed, does utf8 decoding, using TextDecoder.
 */
export function kdfInputToBytes(data) {
    if (typeof data === 'string')
        data = utf8ToBytes(data);
    abytes(data);
    return data;
}
/** Copies several Uint8Arrays into one. */
export function concatBytes(...arrays) {
    let sum = 0;
    for (let i = 0; i < arrays.length; i++) {
        const a = arrays[i];
        abytes(a);
        sum += a.length;
    }
    const res = new Uint8Array(sum);
    for (let i = 0, pad = 0; i < arrays.length; i++) {
        const a = arrays[i];
        res.set(a, pad);
        pad += a.length;
    }
    return res;
}
export function checkOpts(defaults, opts) {
    if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')
        throw new Error('options should be object or undefined');
    const merged = Object.assign(defaults, opts);
    return merged;
}
/** For runtime check if class implements interface */
export class Hash {
}
/** Wraps hash function, creating an interface on top of it */
export function createHasher(hashCons) {
    const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
    const tmp = hashCons();
    hashC.outputLen = tmp.outputLen;
    hashC.blockLen = tmp.blockLen;
    hashC.create = () => hashCons();
    return hashC;
}
export function createOptHasher(hashCons) {
    const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();
    const tmp = hashCons({});
    hashC.outputLen = tmp.outputLen;
    hashC.blockLen = tmp.blockLen;
    hashC.create = (opts) => hashCons(opts);
    return hashC;
}
export function createXOFer(hashCons) {
    const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();
    const tmp = hashCons({});
    hashC.outputLen = tmp.outputLen;
    hashC.blockLen = tmp.blockLen;
    hashC.create = (opts) => hashCons(opts);
    return hashC;
}
export const wrapConstructor = createHasher;
export const wrapConstructorWithOpts = createOptHasher;
export const wrapXOFConstructorWithOpts = createXOFer;
/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */
export function randomBytes(bytesLength = 32) {
    if (crypto && typeof crypto.getRandomValues === 'function') {
        return crypto.getRandomValues(new Uint8Array(bytesLength));
    }
    // Legacy Node.js compatibility
    if (crypto && typeof crypto.randomBytes === 'function') {
        return Uint8Array.from(crypto.randomBytes(bytesLength));
    }
    throw new Error('crypto.getRandomValues must be defined');
}
//# sourceMappingURL=utils.js.map/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */
function isBytes(a) {
    return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
}
/** Asserts something is Uint8Array. */
function abytes(b, ...lengths) {
    if (!isBytes(b))
        throw new Error('Uint8Array expected');
    if (lengths.length > 0 && !lengths.includes(b.length))
        throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);
}
function isArrayOf(isString, arr) {
    if (!Array.isArray(arr))
        return false;
    if (arr.length === 0)
        return true;
    if (isString) {
        return arr.every((item) => typeof item === 'string');
    }
    else {
        return arr.every((item) => Number.isSafeInteger(item));
    }
}
// no abytes: seems to have 10% slowdown. Why?!
function afn(input) {
    if (typeof input !== 'function')
        throw new Error('function expected');
    return true;
}
function astr(label, input) {
    if (typeof input !== 'string')
        throw new Error(`${label}: string expected`);
    return true;
}
function anumber(n) {
    if (!Number.isSafeInteger(n))
        throw new Error(`invalid integer: ${n}`);
}
function aArr(input) {
    if (!Array.isArray(input))
        throw new Error('array expected');
}
function astrArr(label, input) {
    if (!isArrayOf(true, input))
        throw new Error(`${label}: array of strings expected`);
}
function anumArr(label, input) {
    if (!isArrayOf(false, input))
        throw new Error(`${label}: array of numbers expected`);
}
/**
 * @__NO_SIDE_EFFECTS__
 */
function chain(...args) {
    const id = (a) => a;
    // Wrap call in closure so JIT can inline calls
    const wrap = (a, b) => (c) => a(b(c));
    // Construct chain of args[-1].encode(args[-2].encode([...]))
    const encode = args.map((x) => x.encode).reduceRight(wrap, id);
    // Construct chain of args[0].decode(args[1].decode(...))
    const decode = args.map((x) => x.decode).reduce(wrap, id);
    return { encode, decode };
}
/**
 * Encodes integer radix representation to array of strings using alphabet and back.
 * Could also be array of strings.
 * @__NO_SIDE_EFFECTS__
 */
function alphabet(letters) {
    // mapping 1 to "b"
    const lettersA = typeof letters === 'string' ? letters.split('') : letters;
    const len = lettersA.length;
    astrArr('alphabet', lettersA);
    // mapping "b" to 1
    const indexes = new Map(lettersA.map((l, i) => [l, i]));
    return {
        encode: (digits) => {
            aArr(digits);
            return digits.map((i) => {
                if (!Number.isSafeInteger(i) || i < 0 || i >= len)
                    throw new Error(`alphabet.encode: digit index outside alphabet "${i}". Allowed: ${letters}`);
                return lettersA[i];
            });
        },
        decode: (input) => {
            aArr(input);
            return input.map((letter) => {
                astr('alphabet.decode', letter);
                const i = indexes.get(letter);
                if (i === undefined)
                    throw new Error(`Unknown letter: "${letter}". Allowed: ${letters}`);
                return i;
            });
        },
    };
}
/**
 * @__NO_SIDE_EFFECTS__
 */
function join(separator = '') {
    astr('join', separator);
    return {
        encode: (from) => {
            astrArr('join.decode', from);
            return from.join(separator);
        },
        decode: (to) => {
            astr('join.decode', to);
            return to.split(separator);
        },
    };
}
/**
 * Pad strings array so it has integer number of bits
 * @__NO_SIDE_EFFECTS__
 */
function padding(bits, chr = '=') {
    anumber(bits);
    astr('padding', chr);
    return {
        encode(data) {
            astrArr('padding.encode', data);
            while ((data.length * bits) % 8)
                data.push(chr);
            return data;
        },
        decode(input) {
            astrArr('padding.decode', input);
            let end = input.length;
            if ((end * bits) % 8)
                throw new Error('padding: invalid, string should have whole number of bytes');
            for (; end > 0 && input[end - 1] === chr; end--) {
                const last = end - 1;
                const byte = last * bits;
                if (byte % 8 === 0)
                    throw new Error('padding: invalid, string has too much padding');
            }
            return input.slice(0, end);
        },
    };
}
/**
 * @__NO_SIDE_EFFECTS__
 */
function normalize(fn) {
    afn(fn);
    return { encode: (from) => from, decode: (to) => fn(to) };
}
/**
 * Slow: O(n^2) time complexity
 */
function convertRadix(data, from, to) {
    // base 1 is impossible
    if (from < 2)
        throw new Error(`convertRadix: invalid from=${from}, base cannot be less than 2`);
    if (to < 2)
        throw new Error(`convertRadix: invalid to=${to}, base cannot be less than 2`);
    aArr(data);
    if (!data.length)
        return [];
    let pos = 0;
    const res = [];
    const digits = Array.from(data, (d) => {
        anumber(d);
        if (d < 0 || d >= from)
            throw new Error(`invalid integer: ${d}`);
        return d;
    });
    const dlen = digits.length;
    while (true) {
        let carry = 0;
        let done = true;
        for (let i = pos; i < dlen; i++) {
            const digit = digits[i];
            const fromCarry = from * carry;
            const digitBase = fromCarry + digit;
            if (!Number.isSafeInteger(digitBase) ||
                fromCarry / from !== carry ||
                digitBase - digit !== fromCarry) {
                throw new Error('convertRadix: carry overflow');
            }
            const div = digitBase / to;
            carry = digitBase % to;
            const rounded = Math.floor(div);
            digits[i] = rounded;
            if (!Number.isSafeInteger(rounded) || rounded * to + carry !== digitBase)
                throw new Error('convertRadix: carry overflow');
            if (!done)
                continue;
            else if (!rounded)
                pos = i;
            else
                done = false;
        }
        res.push(carry);
        if (done)
            break;
    }
    for (let i = 0; i < data.length - 1 && data[i] === 0; i++)
        res.push(0);
    return res.reverse();
}
const gcd = (a, b) => (b === 0 ? a : gcd(b, a % b));
const radix2carry = /* @__NO_SIDE_EFFECTS__ */ (from, to) => from + (to - gcd(from, to));
const powers = /* @__PURE__ */ (() => {
    let res = [];
    for (let i = 0; i < 40; i++)
        res.push(2 ** i);
    return res;
})();
/**
 * Implemented with numbers, because BigInt is 5x slower
 */
function convertRadix2(data, from, to, padding) {
    aArr(data);
    if (from <= 0 || from > 32)
        throw new Error(`convertRadix2: wrong from=${from}`);
    if (to <= 0 || to > 32)
        throw new Error(`convertRadix2: wrong to=${to}`);
    if (radix2carry(from, to) > 32) {
        throw new Error(`convertRadix2: carry overflow from=${from} to=${to} carryBits=${radix2carry(from, to)}`);
    }
    let carry = 0;
    let pos = 0; // bitwise position in current element
    const max = powers[from];
    const mask = powers[to] - 1;
    const res = [];
    for (const n of data) {
        anumber(n);
        if (n >= max)
            throw new Error(`convertRadix2: invalid data word=${n} from=${from}`);
        carry = (carry << from) | n;
        if (pos + from > 32)
            throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from}`);
        pos += from;
        for (; pos >= to; pos -= to)
            res.push(((carry >> (pos - to)) & mask) >>> 0);
        const pow = powers[pos];
        if (pow === undefined)
            throw new Error('invalid carry');
        carry &= pow - 1; // clean carry, otherwise it will cause overflow
    }
    carry = (carry << (to - pos)) & mask;
    if (!padding && pos >= from)
        throw new Error('Excess padding');
    if (!padding && carry > 0)
        throw new Error(`Non-zero padding: ${carry}`);
    if (padding && pos > 0)
        res.push(carry >>> 0);
    return res;
}
/**
 * @__NO_SIDE_EFFECTS__
 */
function radix(num) {
    anumber(num);
    const _256 = 2 ** 8;
    return {
        encode: (bytes) => {
            if (!isBytes(bytes))
                throw new Error('radix.encode input should be Uint8Array');
            return convertRadix(Array.from(bytes), _256, num);
        },
        decode: (digits) => {
            anumArr('radix.decode', digits);
            return Uint8Array.from(convertRadix(digits, num, _256));
        },
    };
}
/**
 * If both bases are power of same number (like `2**8 <-> 2**64`),
 * there is a linear algorithm. For now we have implementation for power-of-two bases only.
 * @__NO_SIDE_EFFECTS__
 */
function radix2(bits, revPadding = false) {
    anumber(bits);
    if (bits <= 0 || bits > 32)
        throw new Error('radix2: bits should be in (0..32]');
    if (radix2carry(8, bits) > 32 || radix2carry(bits, 8) > 32)
        throw new Error('radix2: carry overflow');
    return {
        encode: (bytes) => {
            if (!isBytes(bytes))
                throw new Error('radix2.encode input should be Uint8Array');
            return convertRadix2(Array.from(bytes), 8, bits, !revPadding);
        },
        decode: (digits) => {
            anumArr('radix2.decode', digits);
            return Uint8Array.from(convertRadix2(digits, bits, 8, revPadding));
        },
    };
}
function unsafeWrapper(fn) {
    afn(fn);
    return function (...args) {
        try {
            return fn.apply(null, args);
        }
        catch (e) { }
    };
}
function checksum(len, fn) {
    anumber(len);
    afn(fn);
    return {
        encode(data) {
            if (!isBytes(data))
                throw new Error('checksum.encode: input should be Uint8Array');
            const sum = fn(data).slice(0, len);
            const res = new Uint8Array(data.length + len);
            res.set(data);
            res.set(sum, data.length);
            return res;
        },
        decode(data) {
            if (!isBytes(data))
                throw new Error('checksum.decode: input should be Uint8Array');
            const payload = data.slice(0, -len);
            const oldChecksum = data.slice(-len);
            const newChecksum = fn(payload).slice(0, len);
            for (let i = 0; i < len; i++)
                if (newChecksum[i] !== oldChecksum[i])
                    throw new Error('Invalid checksum');
            return payload;
        },
    };
}
// prettier-ignore
export const utils = {
    alphabet, chain, checksum, convertRadix, convertRadix2, radix, radix2, join, padding,
};
// RFC 4648 aka RFC 3548
// ---------------------
/**
 * base16 encoding from RFC 4648.
 * @example
 * ```js
 * base16.encode(Uint8Array.from([0x12, 0xab]));
 * // => '12AB'
 * ```
 */
export const base16 = chain(radix2(4), alphabet('0123456789ABCDEF'), join(''));
/**
 * base32 encoding from RFC 4648. Has padding.
 * Use `base32nopad` for unpadded version.
 * Also check out `base32hex`, `base32hexnopad`, `base32crockford`.
 * @example
 * ```js
 * base32.encode(Uint8Array.from([0x12, 0xab]));
 * // => 'CKVQ===='
 * base32.decode('CKVQ====');
 * // => Uint8Array.from([0x12, 0xab])
 * ```
 */
export const base32 = chain(radix2(5), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'), padding(5), join(''));
/**
 * base32 encoding from RFC 4648. No padding.
 * Use `base32` for padded version.
 * Also check out `base32hex`, `base32hexnopad`, `base32crockford`.
 * @example
 * ```js
 * base32nopad.encode(Uint8Array.from([0x12, 0xab]));
 * // => 'CKVQ'
 * base32nopad.decode('CKVQ');
 * // => Uint8Array.from([0x12, 0xab])
 * ```
 */
export const base32nopad = chain(radix2(5), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'), join(''));
/**
 * base32 encoding from RFC 4648. Padded. Compared to ordinary `base32`, slightly different alphabet.
 * Use `base32hexnopad` for unpadded version.
 * @example
 * ```js
 * base32hex.encode(Uint8Array.from([0x12, 0xab]));
 * // => '2ALG===='
 * base32hex.decode('2ALG====');
 * // => Uint8Array.from([0x12, 0xab])
 * ```
 */
export const base32hex = chain(radix2(5), alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'), padding(5), join(''));
/**
 * base32 encoding from RFC 4648. No padding. Compared to ordinary `base32`, slightly different alphabet.
 * Use `base32hex` for padded version.
 * @example
 * ```js
 * base32hexnopad.encode(Uint8Array.from([0x12, 0xab]));
 * // => '2ALG'
 * base32hexnopad.decode('2ALG');
 * // => Uint8Array.from([0x12, 0xab])
 * ```
 */
export const base32hexnopad = chain(radix2(5), alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'), join(''));
/**
 * base32 encoding from RFC 4648. Doug Crockford's version.
 * https://www.crockford.com/base32.html
 * @example
 * ```js
 * base32crockford.encode(Uint8Array.from([0x12, 0xab]));
 * // => '2ANG'
 * base32crockford.decode('2ANG');
 * // => Uint8Array.from([0x12, 0xab])
 * ```
 */
export const base32crockford = chain(radix2(5), alphabet('0123456789ABCDEFGHJKMNPQRSTVWXYZ'), join(''), normalize((s) => s.toUpperCase().replace(/O/g, '0').replace(/[IL]/g, '1')));
// Built-in base64 conversion https://caniuse.com/mdn-javascript_builtins_uint8array_frombase64
// prettier-ignore
const hasBase64Builtin = /* @__PURE__ */ (() => typeof Uint8Array.from([]).toBase64 === 'function' &&
    typeof Uint8Array.fromBase64 === 'function')();
const decodeBase64Builtin = (s, isUrl) => {
    astr('base64', s);
    const re = isUrl ? /^[A-Za-z0-9=_-]+$/ : /^[A-Za-z0-9=+/]+$/;
    const alphabet = isUrl ? 'base64url' : 'base64';
    if (s.length > 0 && !re.test(s))
        throw new Error('invalid base64');
    return Uint8Array.fromBase64(s, { alphabet, lastChunkHandling: 'strict' });
};
/**
 * base64 from RFC 4648. Padded.
 * Use `base64nopad` for unpadded version.
 * Also check out `base64url`, `base64urlnopad`.
 * Falls back to built-in function, when available.
 * @example
 * ```js
 * base64.encode(Uint8Array.from([0x12, 0xab]));
 * // => 'Eqs='
 * base64.decode('Eqs=');
 * // => Uint8Array.from([0x12, 0xab])
 * ```
 */
// prettier-ignore
export const base64 = hasBase64Builtin ? {
    encode(b) { abytes(b); return b.toBase64(); },
    decode(s) { return decodeBase64Builtin(s, false); },
} : chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'), padding(6), join(''));
/**
 * base64 from RFC 4648. No padding.
 * Use `base64` for padded version.
 * @example
 * ```js
 * base64nopad.encode(Uint8Array.from([0x12, 0xab]));
 * // => 'Eqs'
 * base64nopad.decode('Eqs');
 * // => Uint8Array.from([0x12, 0xab])
 * ```
 */
export const base64nopad = chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'), join(''));
/**
 * base64 from RFC 4648, using URL-safe alphabet. Padded.
 * Use `base64urlnopad` for unpadded version.
 * Falls back to built-in function, when available.
 * @example
 * ```js
 * base64url.encode(Uint8Array.from([0x12, 0xab]));
 * // => 'Eqs='
 * base64url.decode('Eqs=');
 * // => Uint8Array.from([0x12, 0xab])
 * ```
 */
// prettier-ignore
export const base64url = hasBase64Builtin ? {
    encode(b) { abytes(b); return b.toBase64({ alphabet: 'base64url' }); },
    decode(s) { return decodeBase64Builtin(s, true); },
} : chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'), padding(6), join(''));
/**
 * base64 from RFC 4648, using URL-safe alphabet. No padding.
 * Use `base64url` for padded version.
 * @example
 * ```js
 * base64urlnopad.encode(Uint8Array.from([0x12, 0xab]));
 * // => 'Eqs'
 * base64urlnopad.decode('Eqs');
 * // => Uint8Array.from([0x12, 0xab])
 * ```
 */
export const base64urlnopad = chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'), join(''));
// base58 code
// -----------
const genBase58 = /* @__NO_SIDE_EFFECTS__ */ (abc) => chain(radix(58), alphabet(abc), join(''));
/**
 * base58: base64 without ambigous characters +, /, 0, O, I, l.
 * Quadratic (O(n^2)) - so, can't be used on large inputs.
 * @example
 * ```js
 * base58.decode('01abcdef');
 * // => '3UhJW'
 * ```
 */
export const base58 = genBase58('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz');
/**
 * base58: flickr version. Check out `base58`.
 */
export const base58flickr = genBase58('123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ');
/**
 * base58: XRP version. Check out `base58`.
 */
export const base58xrp = genBase58('rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz');
// Data len (index) -> encoded block len
const XMR_BLOCK_LEN = [0, 2, 3, 5, 6, 7, 9, 10, 11];
/**
 * base58: XMR version. Check out `base58`.
 * Done in 8-byte blocks (which equals 11 chars in decoding). Last (non-full) block padded with '1' to size in XMR_BLOCK_LEN.
 * Block encoding significantly reduces quadratic complexity of base58.
 */
export const base58xmr = {
    encode(data) {
        let res = '';
        for (let i = 0; i < data.length; i += 8) {
            const block = data.subarray(i, i + 8);
            res += base58.encode(block).padStart(XMR_BLOCK_LEN[block.length], '1');
        }
        return res;
    },
    decode(str) {
        let res = [];
        for (let i = 0; i < str.length; i += 11) {
            const slice = str.slice(i, i + 11);
            const blockLen = XMR_BLOCK_LEN.indexOf(slice.length);
            const block = base58.decode(slice);
            for (let j = 0; j < block.length - blockLen; j++) {
                if (block[j] !== 0)
                    throw new Error('base58xmr: wrong padding');
            }
            res = res.concat(Array.from(block.slice(block.length - blockLen)));
        }
        return Uint8Array.from(res);
    },
};
/**
 * Method, which creates base58check encoder.
 * Requires function, calculating sha256.
 */
export const createBase58check = (sha256) => chain(checksum(4, (data) => sha256(sha256(data))), base58);
/**
 * Use `createBase58check` instead.
 * @deprecated
 */
export const base58check = createBase58check;
const BECH_ALPHABET = chain(alphabet('qpzry9x8gf2tvdw0s3jn54khce6mua7l'), join(''));
const POLYMOD_GENERATORS = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];
function bech32Polymod(pre) {
    const b = pre >> 25;
    let chk = (pre & 0x1ffffff) << 5;
    for (let i = 0; i < POLYMOD_GENERATORS.length; i++) {
        if (((b >> i) & 1) === 1)
            chk ^= POLYMOD_GENERATORS[i];
    }
    return chk;
}
function bechChecksum(prefix, words, encodingConst = 1) {
    const len = prefix.length;
    let chk = 1;
    for (let i = 0; i < len; i++) {
        const c = prefix.charCodeAt(i);
        if (c < 33 || c > 126)
            throw new Error(`Invalid prefix (${prefix})`);
        chk = bech32Polymod(chk) ^ (c >> 5);
    }
    chk = bech32Polymod(chk);
    for (let i = 0; i < len; i++)
        chk = bech32Polymod(chk) ^ (prefix.charCodeAt(i) & 0x1f);
    for (let v of words)
        chk = bech32Polymod(chk) ^ v;
    for (let i = 0; i < 6; i++)
        chk = bech32Polymod(chk);
    chk ^= encodingConst;
    return BECH_ALPHABET.encode(convertRadix2([chk % powers[30]], 30, 5, false));
}
/**
 * @__NO_SIDE_EFFECTS__
 */
function genBech32(encoding) {
    const ENCODING_CONST = encoding === 'bech32' ? 1 : 0x2bc830a3;
    const _words = radix2(5);
    const fromWords = _words.decode;
    const toWords = _words.encode;
    const fromWordsUnsafe = unsafeWrapper(fromWords);
    function encode(prefix, words, limit = 90) {
        astr('bech32.encode prefix', prefix);
        if (isBytes(words))
            words = Array.from(words);
        anumArr('bech32.encode', words);
        const plen = prefix.length;
        if (plen === 0)
            throw new TypeError(`Invalid prefix length ${plen}`);
        const actualLength = plen + 7 + words.length;
        if (limit !== false && actualLength > limit)
            throw new TypeError(`Length ${actualLength} exceeds limit ${limit}`);
        const lowered = prefix.toLowerCase();
        const sum = bechChecksum(lowered, words, ENCODING_CONST);
        return `${lowered}1${BECH_ALPHABET.encode(words)}${sum}`;
    }
    function decode(str, limit = 90) {
        astr('bech32.decode input', str);
        const slen = str.length;
        if (slen < 8 || (limit !== false && slen > limit))
            throw new TypeError(`invalid string length: ${slen} (${str}). Expected (8..${limit})`);
        // don't allow mixed case
        const lowered = str.toLowerCase();
        if (str !== lowered && str !== str.toUpperCase())
            throw new Error(`String must be lowercase or uppercase`);
        const sepIndex = lowered.lastIndexOf('1');
        if (sepIndex === 0 || sepIndex === -1)
            throw new Error(`Letter "1" must be present between prefix and data only`);
        const prefix = lowered.slice(0, sepIndex);
        const data = lowered.slice(sepIndex + 1);
        if (data.length < 6)
            throw new Error('Data must be at least 6 characters long');
        const words = BECH_ALPHABET.decode(data).slice(0, -6);
        const sum = bechChecksum(prefix, words, ENCODING_CONST);
        if (!data.endsWith(sum))
            throw new Error(`Invalid checksum in ${str}: expected "${sum}"`);
        return { prefix, words };
    }
    const decodeUnsafe = unsafeWrapper(decode);
    function decodeToBytes(str) {
        const { prefix, words } = decode(str, false);
        return { prefix, words, bytes: fromWords(words) };
    }
    function encodeFromBytes(prefix, bytes) {
        return encode(prefix, toWords(bytes));
    }
    return {
        encode,
        decode,
        encodeFromBytes,
        decodeToBytes,
        decodeUnsafe,
        fromWords,
        fromWordsUnsafe,
        toWords,
    };
}
/**
 * bech32 from BIP 173. Operates on words.
 * For high-level, check out scure-btc-signer:
 * https://github.com/paulmillr/scure-btc-signer.
 */
export const bech32 = genBech32('bech32');
/**
 * bech32m from BIP 350. Operates on words.
 * It was to mitigate `bech32` weaknesses.
 * For high-level, check out scure-btc-signer:
 * https://github.com/paulmillr/scure-btc-signer.
 */
export const bech32m = genBech32('bech32m');
/**
 * UTF-8-to-byte decoder. Uses built-in TextDecoder / TextEncoder.
 * @example
 * ```js
 * const b = utf8.decode("hey"); // => new Uint8Array([ 104, 101, 121 ])
 * const str = utf8.encode(b); // "hey"
 * ```
 */
export const utf8 = {
    encode: (data) => new TextDecoder().decode(data),
    decode: (str) => new TextEncoder().encode(str),
};
// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex
// prettier-ignore
const hasHexBuiltin = /* @__PURE__ */ (() => typeof Uint8Array.from([]).toHex === 'function' &&
    typeof Uint8Array.fromHex === 'function')();
// prettier-ignore
const hexBuiltin = {
    encode(data) { abytes(data); return data.toHex(); },
    decode(s) { astr('hex', s); return Uint8Array.fromHex(s); },
};
/**
 * hex string decoder. Uses built-in function, when available.
 * @example
 * ```js
 * const b = hex.decode("0102ff"); // => new Uint8Array([ 1, 2, 255 ])
 * const str = hex.encode(b); // "0102ff"
 * ```
 */
export const hex = hasHexBuiltin
    ? hexBuiltin
    : chain(radix2(4), alphabet('0123456789abcdef'), join(''), normalize((s) => {
        if (typeof s !== 'string' || s.length % 2 !== 0)
            throw new TypeError(`hex.decode: expected string, got ${typeof s} with length ${s.length}`);
        return s.toLowerCase();
    }));
// prettier-ignore
const CODERS = {
    utf8, hex, base16, base32, base64, base64url, base58, base58xmr
};
const coderTypeError = 'Invalid encoding type. Available types: utf8, hex, base16, base32, base64, base64url, base58, base58xmr';
/** @deprecated */
export const bytesToString = (type, bytes) => {
    if (typeof type !== 'string' || !CODERS.hasOwnProperty(type))
        throw new TypeError(coderTypeError);
    if (!isBytes(bytes))
        throw new TypeError('bytesToString() expects Uint8Array');
    return CODERS[type].encode(bytes);
};
/** @deprecated */
export const str = bytesToString; // as in python, but for bytes only
/** @deprecated */
export const stringToBytes = (type, str) => {
    if (!CODERS.hasOwnProperty(type))
        throw new TypeError(coderTypeError);
    if (typeof str !== 'string')
        throw new TypeError('stringToBytes() expects string');
    return CODERS[type].decode(str);
};
/** @deprecated */
export const bytes = stringToBytes;
//# sourceMappingURL=index.js.map{ "type": "module", "sideEffects": false }
/**
 * @module BIP32 hierarchical deterministic (HD) wallets over secp256k1.
 * @example
 * ```js
 * import { HDKey } from "@scure/bip32";
 * const hdkey1 = HDKey.fromMasterSeed(seed);
 * const hdkey2 = HDKey.fromExtendedKey(base58key);
 * const hdkey3 = HDKey.fromJSON({ xpriv: string });
 *
 * // props
 * [hdkey1.depth, hdkey1.index, hdkey1.chainCode];
 * console.log(hdkey2.privateKey, hdkey2.publicKey);
 * console.log(hdkey3.derive("m/0/2147483647'/1"));
 * const sig = hdkey3.sign(hash);
 * hdkey3.verify(hash, sig);
 * ```
 */
/*! scure-bip32 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) */
import { mod } from '@noble/curves/abstract/modular';
import { secp256k1 as secp } from '@noble/curves/secp256k1';
import { hmac } from '@noble/hashes/hmac';
import { ripemd160 } from '@noble/hashes/legacy';
import { sha256, sha512 } from '@noble/hashes/sha2';
import { abytes, bytesToHex, concatBytes, createView, hexToBytes, utf8ToBytes, } from '@noble/hashes/utils';
import { createBase58check } from '@scure/base';
const Point = secp.ProjectivePoint;
const base58check = createBase58check(sha256);
function bytesToNumber(bytes) {
    abytes(bytes);
    const h = bytes.length === 0 ? '0' : bytesToHex(bytes);
    return BigInt('0x' + h);
}
function numberToBytes(num) {
    if (typeof num !== 'bigint')
        throw new Error('bigint expected');
    return hexToBytes(num.toString(16).padStart(64, '0'));
}
const MASTER_SECRET = utf8ToBytes('Bitcoin seed');
// Bitcoin hardcoded by default
const BITCOIN_VERSIONS = { private: 0x0488ade4, public: 0x0488b21e };
export const HARDENED_OFFSET = 0x80000000;
const hash160 = (data) => ripemd160(sha256(data));
const fromU32 = (data) => createView(data).getUint32(0, false);
const toU32 = (n) => {
    if (!Number.isSafeInteger(n) || n < 0 || n > 2 ** 32 - 1) {
        throw new Error('invalid number, should be from 0 to 2**32-1, got ' + n);
    }
    const buf = new Uint8Array(4);
    createView(buf).setUint32(0, n, false);
    return buf;
};
export class HDKey {
    get fingerprint() {
        if (!this.pubHash) {
            throw new Error('No publicKey set!');
        }
        return fromU32(this.pubHash);
    }
    get identifier() {
        return this.pubHash;
    }
    get pubKeyHash() {
        return this.pubHash;
    }
    get privateKey() {
        return this.privKeyBytes || null;
    }
    get publicKey() {
        return this.pubKey || null;
    }
    get privateExtendedKey() {
        const priv = this.privateKey;
        if (!priv) {
            throw new Error('No private key');
        }
        return base58check.encode(this.serialize(this.versions.private, concatBytes(new Uint8Array([0]), priv)));
    }
    get publicExtendedKey() {
        if (!this.pubKey) {
            throw new Error('No public key');
        }
        return base58check.encode(this.serialize(this.versions.public, this.pubKey));
    }
    static fromMasterSeed(seed, versions = BITCOIN_VERSIONS) {
        abytes(seed);
        if (8 * seed.length < 128 || 8 * seed.length > 512) {
            throw new Error('HDKey: seed length must be between 128 and 512 bits; 256 bits is advised, got ' +
                seed.length);
        }
        const I = hmac(sha512, MASTER_SECRET, seed);
        return new HDKey({
            versions,
            chainCode: I.slice(32),
            privateKey: I.slice(0, 32),
        });
    }
    static fromExtendedKey(base58key, versions = BITCOIN_VERSIONS) {
        // => version(4) || depth(1) || fingerprint(4) || index(4) || chain(32) || key(33)
        const keyBuffer = base58check.decode(base58key);
        const keyView = createView(keyBuffer);
        const version = keyView.getUint32(0, false);
        const opt = {
            versions,
            depth: keyBuffer[4],
            parentFingerprint: keyView.getUint32(5, false),
            index: keyView.getUint32(9, false),
            chainCode: keyBuffer.slice(13, 45),
        };
        const key = keyBuffer.slice(45);
        const isPriv = key[0] === 0;
        if (version !== versions[isPriv ? 'private' : 'public']) {
            throw new Error('Version mismatch');
        }
        if (isPriv) {
            return new HDKey({ ...opt, privateKey: key.slice(1) });
        }
        else {
            return new HDKey({ ...opt, publicKey: key });
        }
    }
    static fromJSON(json) {
        return HDKey.fromExtendedKey(json.xpriv);
    }
    constructor(opt) {
        this.depth = 0;
        this.index = 0;
        this.chainCode = null;
        this.parentFingerprint = 0;
        if (!opt || typeof opt !== 'object') {
            throw new Error('HDKey.constructor must not be called directly');
        }
        this.versions = opt.versions || BITCOIN_VERSIONS;
        this.depth = opt.depth || 0;
        this.chainCode = opt.chainCode || null;
        this.index = opt.index || 0;
        this.parentFingerprint = opt.parentFingerprint || 0;
        if (!this.depth) {
            if (this.parentFingerprint || this.index) {
                throw new Error('HDKey: zero depth with non-zero index/parent fingerprint');
            }
        }
        if (opt.publicKey && opt.privateKey) {
            throw new Error('HDKey: publicKey and privateKey at same time.');
        }
        if (opt.privateKey) {
            if (!secp.utils.isValidPrivateKey(opt.privateKey)) {
                throw new Error('Invalid private key');
            }
            this.privKey =
                typeof opt.privateKey === 'bigint' ? opt.privateKey : bytesToNumber(opt.privateKey);
            this.privKeyBytes = numberToBytes(this.privKey);
            this.pubKey = secp.getPublicKey(opt.privateKey, true);
        }
        else if (opt.publicKey) {
            this.pubKey = Point.fromHex(opt.publicKey).toRawBytes(true); // force compressed point
        }
        else {
            throw new Error('HDKey: no public or private key provided');
        }
        this.pubHash = hash160(this.pubKey);
    }
    derive(path) {
        if (!/^[mM]'?/.test(path)) {
            throw new Error('Path must start with "m" or "M"');
        }
        if (/^[mM]'?$/.test(path)) {
            return this;
        }
        const parts = path.replace(/^[mM]'?\//, '').split('/');
        // tslint:disable-next-line
        let child = this;
        for (const c of parts) {
            const m = /^(\d+)('?)$/.exec(c);
            const m1 = m && m[1];
            if (!m || m.length !== 3 || typeof m1 !== 'string')
                throw new Error('invalid child index: ' + c);
            let idx = +m1;
            if (!Number.isSafeInteger(idx) || idx >= HARDENED_OFFSET) {
                throw new Error('Invalid index');
            }
            // hardened key
            if (m[2] === "'") {
                idx += HARDENED_OFFSET;
            }
            child = child.deriveChild(idx);
        }
        return child;
    }
    deriveChild(index) {
        if (!this.pubKey || !this.chainCode) {
            throw new Error('No publicKey or chainCode set');
        }
        let data = toU32(index);
        if (index >= HARDENED_OFFSET) {
            // Hardened
            const priv = this.privateKey;
            if (!priv) {
                throw new Error('Could not derive hardened child key');
            }
            // Hardened child: 0x00 || ser256(kpar) || ser32(index)
            data = concatBytes(new Uint8Array([0]), priv, data);
        }
        else {
            // Normal child: serP(point(kpar)) || ser32(index)
            data = concatBytes(this.pubKey, data);
        }
        const I = hmac(sha512, this.chainCode, data);
        const childTweak = bytesToNumber(I.slice(0, 32));
        const chainCode = I.slice(32);
        if (!secp.utils.isValidPrivateKey(childTweak)) {
            throw new Error('Tweak bigger than curve order');
        }
        const opt = {
            versions: this.versions,
            chainCode,
            depth: this.depth + 1,
            parentFingerprint: this.fingerprint,
            index,
        };
        try {
            // Private parent key -> private child key
            if (this.privateKey) {
                const added = mod(this.privKey + childTweak, secp.CURVE.n);
                if (!secp.utils.isValidPrivateKey(added)) {
                    throw new Error('The tweak was out of range or the resulted private key is invalid');
                }
                opt.privateKey = added;
            }
            else {
                const added = Point.fromHex(this.pubKey).add(Point.fromPrivateKey(childTweak));
                // Cryptographically impossible: hmac-sha512 preimage would need to be found
                if (added.equals(Point.ZERO)) {
                    throw new Error('The tweak was equal to negative P, which made the result key invalid');
                }
                opt.publicKey = added.toRawBytes(true);
            }
            return new HDKey(opt);
        }
        catch (err) {
            return this.deriveChild(index + 1);
        }
    }
    sign(hash) {
        if (!this.privateKey) {
            throw new Error('No privateKey set!');
        }
        abytes(hash, 32);
        return secp.sign(hash, this.privKey).toCompactRawBytes();
    }
    verify(hash, signature) {
        abytes(hash, 32);
        abytes(signature, 64);
        if (!this.publicKey) {
            throw new Error('No publicKey set!');
        }
        let sig;
        try {
            sig = secp.Signature.fromCompact(signature);
        }
        catch (error) {
            return false;
        }
        return secp.verify(sig, hash, this.publicKey);
    }
    wipePrivateData() {
        this.privKey = undefined;
        if (this.privKeyBytes) {
            this.privKeyBytes.fill(0);
            this.privKeyBytes = undefined;
        }
        return this;
    }
    toJSON() {
        return {
            xpriv: this.privateExtendedKey,
            xpub: this.publicExtendedKey,
        };
    }
    serialize(version, key) {
        if (!this.chainCode) {
            throw new Error('No chainCode set');
        }
        abytes(key, 33);
        // version(4) || depth(1) || fingerprint(4) || index(4) || chain(32) || key(33)
        return concatBytes(toU32(version), new Uint8Array([this.depth]), toU32(this.parentFingerprint), toU32(this.index), this.chainCode, key);
    }
}
//# sourceMappingURL=index.js.map{
  "type": "module",
  "sideEffects": false
}/**
 * Audited & minimal JS implementation of
 * [BIP39 mnemonic phrases](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki).
 * @module
 * @example
```js
import * as bip39 from '@scure/bip39';
import { wordlist } from '@scure/bip39/wordlists/english';
const mn = bip39.generateMnemonic(wordlist);
console.log(mn);
const ent = bip39.mnemonicToEntropy(mn, wordlist)
bip39.entropyToMnemonic(ent, wordlist);
bip39.validateMnemonic(mn, wordlist);
await bip39.mnemonicToSeed(mn, 'password');
bip39.mnemonicToSeedSync(mn, 'password');

// Wordlists
import { wordlist as czech } from '@scure/bip39/wordlists/czech';
import { wordlist as english } from '@scure/bip39/wordlists/english';
import { wordlist as french } from '@scure/bip39/wordlists/french';
import { wordlist as italian } from '@scure/bip39/wordlists/italian';
import { wordlist as japanese } from '@scure/bip39/wordlists/japanese';
import { wordlist as korean } from '@scure/bip39/wordlists/korean';
import { wordlist as portuguese } from '@scure/bip39/wordlists/portuguese';
import { wordlist as simplifiedChinese } from '@scure/bip39/wordlists/simplified-chinese';
import { wordlist as spanish } from '@scure/bip39/wordlists/spanish';
import { wordlist as traditionalChinese } from '@scure/bip39/wordlists/traditional-chinese';
```
 */
/*! scure-bip39 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) */
import { pbkdf2, pbkdf2Async } from '@noble/hashes/pbkdf2';
import { sha256, sha512 } from '@noble/hashes/sha2';
import { abytes, anumber, randomBytes } from '@noble/hashes/utils';
import { utils as baseUtils } from '@scure/base';
// Japanese wordlist
const isJapanese = (wordlist) => wordlist[0] === '\u3042\u3044\u3053\u304f\u3057\u3093';
// Normalization replaces equivalent sequences of characters
// so that any two texts that are equivalent will be reduced
// to the same sequence of code points, called the normal form of the original text.
// https://tonsky.me/blog/unicode/#why-is-a----
function nfkd(str) {
    if (typeof str !== 'string')
        throw new TypeError('invalid mnemonic type: ' + typeof str);
    return str.normalize('NFKD');
}
function normalize(str) {
    const norm = nfkd(str);
    const words = norm.split(' ');
    if (![12, 15, 18, 21, 24].includes(words.length))
        throw new Error('Invalid mnemonic');
    return { nfkd: norm, words };
}
function aentropy(ent) {
    abytes(ent, 16, 20, 24, 28, 32);
}
/**
 * Generate x random words. Uses Cryptographically-Secure Random Number Generator.
 * @param wordlist imported wordlist for specific language
 * @param strength mnemonic strength 128-256 bits
 * @example
 * generateMnemonic(wordlist, 128)
 * // 'legal winner thank year wave sausage worth useful legal winner thank yellow'
 */
export function generateMnemonic(wordlist, strength = 128) {
    anumber(strength);
    if (strength % 32 !== 0 || strength > 256)
        throw new TypeError('Invalid entropy');
    return entropyToMnemonic(randomBytes(strength / 8), wordlist);
}
const calcChecksum = (entropy) => {
    // Checksum is ent.length/4 bits long
    const bitsLeft = 8 - entropy.length / 4;
    // Zero rightmost "bitsLeft" bits in byte
    // For example: bitsLeft=4 val=10111101 -> 10110000
    return new Uint8Array([(sha256(entropy)[0] >> bitsLeft) << bitsLeft]);
};
function getCoder(wordlist) {
    if (!Array.isArray(wordlist) || wordlist.length !== 2048 || typeof wordlist[0] !== 'string')
        throw new Error('Wordlist: expected array of 2048 strings');
    wordlist.forEach((i) => {
        if (typeof i !== 'string')
            throw new Error('wordlist: non-string element: ' + i);
    });
    return baseUtils.chain(baseUtils.checksum(1, calcChecksum), baseUtils.radix2(11, true), baseUtils.alphabet(wordlist));
}
/**
 * Reversible: Converts mnemonic string to raw entropy in form of byte array.
 * @param mnemonic 12-24 words
 * @param wordlist imported wordlist for specific language
 * @example
 * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';
 * mnemonicToEntropy(mnem, wordlist)
 * // Produces
 * new Uint8Array([
 *   0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f,
 *   0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f
 * ])
 */
export function mnemonicToEntropy(mnemonic, wordlist) {
    const { words } = normalize(mnemonic);
    const entropy = getCoder(wordlist).decode(words);
    aentropy(entropy);
    return entropy;
}
/**
 * Reversible: Converts raw entropy in form of byte array to mnemonic string.
 * @param entropy byte array
 * @param wordlist imported wordlist for specific language
 * @returns 12-24 words
 * @example
 * const ent = new Uint8Array([
 *   0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f,
 *   0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f
 * ]);
 * entropyToMnemonic(ent, wordlist);
 * // 'legal winner thank year wave sausage worth useful legal winner thank yellow'
 */
export function entropyToMnemonic(entropy, wordlist) {
    aentropy(entropy);
    const words = getCoder(wordlist).encode(entropy);
    return words.join(isJapanese(wordlist) ? '\u3000' : ' ');
}
/**
 * Validates mnemonic for being 12-24 words contained in `wordlist`.
 */
export function validateMnemonic(mnemonic, wordlist) {
    try {
        mnemonicToEntropy(mnemonic, wordlist);
    }
    catch (e) {
        return false;
    }
    return true;
}
const psalt = (passphrase) => nfkd('mnemonic' + passphrase);
/**
 * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password.
 * @param mnemonic 12-24 words
 * @param passphrase string that will additionally protect the key
 * @returns 64 bytes of key data
 * @example
 * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';
 * await mnemonicToSeed(mnem, 'password');
 * // new Uint8Array([...64 bytes])
 */
export function mnemonicToSeed(mnemonic, passphrase = '') {
    return pbkdf2Async(sha512, normalize(mnemonic).nfkd, psalt(passphrase), { c: 2048, dkLen: 64 });
}
/**
 * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password.
 * @param mnemonic 12-24 words
 * @param passphrase string that will additionally protect the key
 * @returns 64 bytes of key data
 * @example
 * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';
 * mnemonicToSeedSync(mnem, 'password');
 * // new Uint8Array([...64 bytes])
 */
export function mnemonicToSeedSync(mnemonic, passphrase = '') {
    return pbkdf2(sha512, normalize(mnemonic).nfkd, psalt(passphrase), { c: 2048, dkLen: 64 });
}
{
  "type": "module"
}function isBuffer(value) {
  return Buffer.isBuffer(value) || value instanceof Uint8Array
}

function isEncoding(encoding) {
  return Buffer.isEncoding(encoding)
}

function alloc(size, fill, encoding) {
  return Buffer.alloc(size, fill, encoding)
}

function allocUnsafe(size) {
  return Buffer.allocUnsafe(size)
}

function allocUnsafeSlow(size) {
  return Buffer.allocUnsafeSlow(size)
}

function byteLength(string, encoding) {
  return Buffer.byteLength(string, encoding)
}

function compare(a, b) {
  return Buffer.compare(a, b)
}

function concat(buffers, totalLength) {
  return Buffer.concat(buffers, totalLength)
}

function copy(source, target, targetStart, start, end) {
  return toBuffer(source).copy(target, targetStart, start, end)
}

function equals(a, b) {
  return toBuffer(a).equals(b)
}

function fill(buffer, value, offset, end, encoding) {
  return toBuffer(buffer).fill(value, offset, end, encoding)
}

function from(value, encodingOrOffset, length) {
  return Buffer.from(value, encodingOrOffset, length)
}

function includes(buffer, value, byteOffset, encoding) {
  return toBuffer(buffer).includes(value, byteOffset, encoding)
}

function indexOf(buffer, value, byfeOffset, encoding) {
  return toBuffer(buffer).indexOf(value, byfeOffset, encoding)
}

function lastIndexOf(buffer, value, byteOffset, encoding) {
  return toBuffer(buffer).lastIndexOf(value, byteOffset, encoding)
}

function swap16(buffer) {
  return toBuffer(buffer).swap16()
}

function swap32(buffer) {
  return toBuffer(buffer).swap32()
}

function swap64(buffer) {
  return toBuffer(buffer).swap64()
}

function toBuffer(buffer) {
  if (Buffer.isBuffer(buffer)) return buffer
  return Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

function toString(buffer, encoding, start, end) {
  return toBuffer(buffer).toString(encoding, start, end)
}

function write(buffer, string, offset, length, encoding) {
  return toBuffer(buffer).write(string, offset, length, encoding)
}

function readDoubleBE(buffer, offset) {
  return toBuffer(buffer).readDoubleBE(offset)
}

function readDoubleLE(buffer, offset) {
  return toBuffer(buffer).readDoubleLE(offset)
}

function readFloatBE(buffer, offset) {
  return toBuffer(buffer).readFloatBE(offset)
}

function readFloatLE(buffer, offset) {
  return toBuffer(buffer).readFloatLE(offset)
}

function readInt32BE(buffer, offset) {
  return toBuffer(buffer).readInt32BE(offset)
}

function readInt32LE(buffer, offset) {
  return toBuffer(buffer).readInt32LE(offset)
}

function readUInt32BE(buffer, offset) {
  return toBuffer(buffer).readUInt32BE(offset)
}

function readUInt32LE(buffer, offset) {
  return toBuffer(buffer).readUInt32LE(offset)
}

function writeDoubleBE(buffer, value, offset) {
  return toBuffer(buffer).writeDoubleBE(value, offset)
}

function writeDoubleLE(buffer, value, offset) {
  return toBuffer(buffer).writeDoubleLE(value, offset)
}

function writeFloatBE(buffer, value, offset) {
  return toBuffer(buffer).writeFloatBE(value, offset)
}

function writeFloatLE(buffer, value, offset) {
  return toBuffer(buffer).writeFloatLE(value, offset)
}

function writeInt32BE(buffer, value, offset) {
  return toBuffer(buffer).writeInt32BE(value, offset)
}

function writeInt32LE(buffer, value, offset) {
  return toBuffer(buffer).writeInt32LE(value, offset)
}

function writeUInt32BE(buffer, value, offset) {
  return toBuffer(buffer).writeUInt32BE(value, offset)
}

function writeUInt32LE(buffer, value, offset) {
  return toBuffer(buffer).writeUInt32LE(value, offset)
}

module.exports = {
  isBuffer,
  isEncoding,
  alloc,
  allocUnsafe,
  allocUnsafeSlow,
  byteLength,
  compare,
  concat,
  copy,
  equals,
  fill,
  from,
  includes,
  indexOf,
  lastIndexOf,
  swap16,
  swap32,
  swap64,
  toBuffer,
  toString,
  write,
  readDoubleBE,
  readDoubleLE,
  readFloatBE,
  readFloatLE,
  readInt32BE,
  readInt32LE,
  readUInt32BE,
  readUInt32LE,
  writeDoubleBE,
  writeDoubleLE,
  writeFloatBE,
  writeFloatLE,
  writeInt32BE,
  writeInt32LE,
  writeUInt32BE,
  writeUInt32LE
}
{
  "name": "b4a",
  "version": "1.8.1",
  "description": "Bridging the gap between buffers and typed arrays",
  "exports": {
    "./package": "./package.json",
    ".": {
      "react-native": "./react-native.js",
      "browser": "./browser.js",
      "default": "./index.js"
    }
  },
  "files": [
    "browser.js",
    "index.js",
    "react-native.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:bare && npm run test:node",
    "test:bare": "brittle-bare --coverage test.mjs",
    "test:node": "brittle-node --coverage test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/b4a.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/b4a/issues"
  },
  "homepage": "https://github.com/holepunchto/b4a#readme",
  "devDependencies": {
    "brittle": "^3.5.2",
    "lunte": "^1.7.0",
    "nanobench": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "react-native-b4a": "*"
  },
  "peerDependenciesMeta": {
    "react-native-b4a": {
      "optional": true
    }
  }
}
const ESC = '\x1b'
const CSI = ESC + '['
const SGR = (n) => CSI + n + 'm'

exports.constants = {
  ESC,
  CSI,
  SGR
}

// https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_(Control_Sequence_Introducer)_sequences

exports.cursorHide = CSI + '?25l'
exports.cursorShow = CSI + '?25h'

exports.cursorUp = function cursorUp(n = 1) {
  return CSI + n + 'A'
}

exports.cursorDown = function cursorDown(n = 1) {
  return CSI + n + 'B'
}

exports.cursorForward = function cursorForward(n = 1) {
  return CSI + n + 'C'
}

exports.cursorBack = function cursorBack(n = 1) {
  return CSI + n + 'D'
}

exports.cursorNextLine = function cursorNextLine(n = 1) {
  return CSI + n + 'E'
}

exports.cursorPreviousLine = function cursorPreviousLine(n = 1) {
  return CSI + n + 'F'
}

exports.cursorPosition = function cursorPosition(column, row = 0) {
  if (row === 0) return CSI + (column + 1) + 'G'

  return CSI + (row + 1) + ';' + (column + 1) + 'H'
}

exports.eraseDisplayEnd = CSI + 'J'
exports.eraseDisplayStart = CSI + '1J'
exports.eraseDisplay = CSI + '2J'
exports.eraseLineEnd = CSI + 'K'
exports.eraseLineStart = CSI + '1K'
exports.eraseLine = CSI + '2K'

exports.scrollUp = function scrollUp(n = 1) {
  return CSI + n + 'S'
}

exports.scrollDown = function scrollDown(n = 1) {
  return CSI + n + 'T'
}

// https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_(Select_Graphic_Rendition)_parameters

exports.modifierReset = SGR(0)
exports.modifierBold = SGR(1)
exports.modifierDim = SGR(2)
exports.modifierItalic = SGR(3)
exports.modifierUnderline = SGR(4)
exports.modifierNormal = SGR(22)
exports.modifierNotItalic = SGR(23)
exports.modifierNotUnderline = SGR(24)

// https://en.wikipedia.org/wiki/ANSI_escape_code#Colors

exports.colorBlack = SGR(30)
exports.colorRed = SGR(31)
exports.colorGreen = SGR(32)
exports.colorYellow = SGR(33)
exports.colorBlue = SGR(34)
exports.colorMagenta = SGR(35)
exports.colorCyan = SGR(36)
exports.colorWhite = SGR(37)
exports.colorDefault = SGR(39)
exports.colorBrightBlack = SGR(90)
exports.colorBrightRed = SGR(91)
exports.colorBrightGreen = SGR(92)
exports.colorBrightYellow = SGR(93)
exports.colorBrightBlue = SGR(94)
exports.colorBrightMagenta = SGR(95)
exports.colorBrightCyan = SGR(96)
exports.colorBrightWhite = SGR(97)
{
  "name": "bare-ansi-escapes",
  "version": "2.2.3",
  "description": "Parse and produce ANSI escape sequences",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./key-decoder": {
      "types": "./key-decoder.d.ts",
      "default": "./key-decoder.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "key-decoder.js",
    "key-decoder.d.ts"
  ],
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-ansi-escapes.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-ansi-escapes/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-ansi-escapes#readme",
  "dependencies": {
    "bare-stream": "^2.6.5"
  },
  "devDependencies": {
    "bare-buffer": "^3.0.2",
    "brittle": "^3.3.2",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  },
  "peerDependencies": {
    "bare-buffer": "*"
  },
  "peerDependenciesMeta": {
    "bare-buffer": {
      "optional": true
    }
  }
}
const inspect = require('bare-inspect')

class AssertionError extends Error {
  constructor(opts = {}) {
    let { message = null, actual, expected, operator } = opts

    if (message === null) {
      message = `${inspect(actual)} ${operator} ${inspect(expected)}`
    }

    super(message)

    this.actual = actual
    this.expected = expected
    this.operator = operator
  }

  get name() {
    return 'AssertionError'
  }

  get code() {
    'ASSERTION'
  }
}

function assertFail(opts, fn) {
  if (opts.message instanceof Error) throw opts.message

  const err = new AssertionError(opts)

  if (Error.captureStackTrace) Error.captureStackTrace(err, fn)

  throw err
}

module.exports = exports = function assert(actual, message) {
  if (actual) return

  assertFail({ message, actual, expected: true, operator: '==' }, assert)
}

exports.AssertionError = AssertionError

exports.fail = function fail(message) {
  if (message === undefined) message = 'Failed'

  assertFail({ message, operator: 'fail' }, fail)
}

exports.ok = function ok(actual, message) {
  if (actual) return

  assertFail({ message, actual, expected: true, operator: '==' }, ok)
}

exports.notOk = function ok(actual, message) {
  if (!actual) return

  assertFail({ message, actual, expected: false, operator: '==' }, ok)
}

exports.equal = function equal(actual, expected, message) {
  if (actual == expected || (actual !== actual && expected !== expected)) {
    return
  }

  assertFail({ message, actual, expected, operator: '==' }, equal)
}

exports.notEqual = function notEqual(actual, expected, message) {
  if (actual != expected && (actual === actual || expected === expected)) {
    return
  }

  assertFail({ message, actual, expected, operator: '!=' }, notEqual)
}

exports.strictEqual = function strictEqual(actual, expected, message) {
  if (Object.is(actual, expected)) return

  assertFail(
    { message, actual, expected, operator: 'strictEqual' },
    strictEqual
  )
}

exports.notStrictEqual = function notStrictEqual(actual, expected, message) {
  if (!Object.is(actual, expected)) return

  assertFail(
    { message, actual, expected, operator: 'notStrictEqual' },
    notStrictEqual
  )
}
{
  "name": "bare-assert",
  "version": "1.2.0",
  "description": "Assertion library for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts"
  ],
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-assert.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-assert/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-assert#readme",
  "dependencies": {
    "bare-inspect": "^3.1.2"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  }
}
module.exports = require.addon()
const ansiEscapes = require('bare-ansi-escapes')
const getType = require('bare-type')
const binding = require('./binding')

const PLAIN_KEY = /^[a-zA-Z_][a-zA-Z_0-9]*$/

const defaultDepth = 2
const defaultBreakLength = 80
const defaultMaxArrayLength = 40

module.exports = exports = function inspect(value, opts = {}) {
  const {
    colors = false,
    depth = defaultDepth,
    breakLength = defaultBreakLength,
    stylize = defaultStylize(colors)
  } = opts

  const references = new InspectRefMap()

  const tree = inspectValue(value, 0, {
    colors,
    depth,
    breakLength,
    stylize,
    references
  })

  return tree.toString()
}

exports.styles = {
  bigint: ansiEscapes.colorYellow,
  boolean: ansiEscapes.colorYellow,
  date: ansiEscapes.colorMagenta,
  module: ansiEscapes.modifierUnderline,
  name: ansiEscapes.modifierReset,
  null: ansiEscapes.modifierBold,
  number: ansiEscapes.colorYellow,
  regexp: ansiEscapes.colorRed,
  special: ansiEscapes.colorCyan,
  string: ansiEscapes.colorGreen,
  symbol: ansiEscapes.colorGreen,
  undefined: ansiEscapes.colorBrightBlack
}

const styles = exports.styles

function defaultStylize(colors) {
  return function stylize(value, style) {
    const color = colors && styles[style]

    if (color) return color + value + ansiEscapes.modifierReset

    return value
  }
}

class InspectRefMap {
  constructor() {
    this.refs = new WeakMap()
    this.ids = new WeakMap()
    this.nextId = 1
  }

  has(object) {
    return this.refs.has(object)
  }

  get(object) {
    return this.refs.get(object) || null
  }

  set(object, ref) {
    this.refs.set(object, ref)
  }

  id(object) {
    let id = this.ids.get(object)
    if (id) return id

    id = this.nextId++
    this.ids.set(object, id)

    return id
  }
}

class InspectNode {
  constructor(depth, length, opts) {
    const { breakLength = defaultBreakLength, breakAlways = false } = opts

    this.depth = depth
    this.length = length
    this.breakLength = breakLength
    this.breakAlways = breakAlways
  }

  pad(n, string) {
    return string.padStart(n, ' ')
  }

  indent(n, string) {
    return '  '.repeat(n) + string
  }
}

class InspectRef extends InspectNode {
  constructor(depth, opts) {
    super(depth, '[circular *]'.length, opts)

    this.refs = opts.references
    this.count = 0
    this.circular = false
    this.color = opts.colors && styles.special
  }

  get id() {
    return this.refs.id(this)
  }

  increment() {
    return ++this.count
  }

  decrement() {
    return --this.count
  }

  toString(opts = {}) {
    const { offset = 0, pad = 0, indent = 0 } = opts

    let value = this.pad(pad, '[circular *' + this.id + ']')

    if (this.color) value = this.color + value + ansiEscapes.modifierReset

    return offset ? value : this.indent(indent, value)
  }
}

class InspectLeaf extends InspectNode {
  constructor(value, color, depth, opts) {
    const length = value.length

    if (value.includes('\n')) {
      value = value.replaceAll('\n', '\n' + '  '.repeat(depth))

      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.value = value
    this.color = opts.colors && color
  }

  toString(opts = {}) {
    const { offset = 0, pad = 0, indent = 0 } = opts

    let value = this.pad(pad, this.value)

    if (this.color) value = this.color + value + ansiEscapes.modifierReset

    return offset ? value : this.indent(indent, value)
  }
}

class InspectPair extends InspectNode {
  constructor(delim, left, right, depth, opts) {
    const length = left.length + delim.length + right.length

    if (left.breakAlways || right.breakAlways) {
      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.delim = delim
    this.left = left
    this.right = right
  }

  toString(opts = {}) {
    const { indent = 0 } = opts

    return this.indent(
      indent,
      this.left +
        this.delim +
        this.right.toString({
          indent,
          offset: this.left.length + this.delim.length
        })
    )
  }
}

class InspectSuspension extends InspectNode {
  constructor(overflow, depth, opts) {
    const label = `... ${overflow} more`

    super(depth, label.length, opts)

    this.label = label
  }

  toString(opts = {}) {
    const { indent = 0 } = opts

    return this.indent(indent, this.label)
  }
}

class InspectSequence extends InspectNode {
  constructor(header, footer, delim, values, ref, depth, opts) {
    const { tabulate = false } = opts

    const length =
      (ref.circular ? '<ref *>'.length + 1 : 0) +
      header.length +
      values.reduce(
        (length, value, i) =>
          length + value.length + (i === 0 ? 0 : delim.length),
        0
      ) +
      footer.length

    if (values.some((value) => value.breakAlways)) {
      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.header = header
    this.footer = footer
    this.delim = delim
    this.values = values
    this.ref = ref
    this.tabulate = tabulate
  }

  toString(opts = {}) {
    const { offset = 0, indent = 0 } = opts

    const split =
      this.breakAlways ||
      (this.values.length &&
        (offset + this.length > this.breakLength ||
          indent * 2 + this.length > this.breakLength))

    let header = this.header

    if (this.ref.circular) {
      header = '<ref *' + this.ref.id + '> ' + header
    }

    if (this.values.length === 0) {
      header = header.trimEnd()
    }

    if (offset === 0) {
      header = this.indent(indent, header)
    }

    if (split) {
      header = header.trimEnd() + '\n'
    }

    let string = header

    let columns = 1
    let pad = 0

    if (this.tabulate) {
      const widest = this.values.reduce(
        (length, value) =>
          value.breakAlways ? length : Math.max(length, value.length),
        0
      )

      if (widest) {
        columns = Math.max(
          columns,
          Math.floor(
            (this.breakLength - indent * 2) / (widest + this.delim.length)
          )
        )

        if (columns > 1) pad = widest
      }
    }

    for (let i = 0, n = this.values.length, offset = 0; i < n; i++) {
      const value = this.values[i]

      if (split) {
        let part

        if (i % columns === 0 || value.breakAlways) {
          part = value.toString({ indent: indent + 1, pad })
        } else {
          part = value.toString({ pad })
        }

        string += part

        if (i < n - 1) {
          if (i % columns === columns - 1 || this.values[i + 1].breakAlways) {
            string += this.delim.trimEnd() + '\n'
          } else {
            string += this.delim
          }
        }
      } else {
        if (i > 0) string += this.delim

        string += value.toString({ offset })

        offset += value.length
      }
    }

    let footer = this.footer

    if (this.values.length === 0) {
      footer = footer.trimStart()
    }

    if (split) {
      string += '\n' + this.indent(indent, footer.trimStart())
    } else {
      string += footer
    }

    return string
  }
}

function inspectValue(value, depth, opts) {
  const type = getType(value)

  if (type.isUndefined()) return inspectUndefined(depth, opts)
  if (type.isNull()) return inspectNull(depth, opts)
  if (type.isBoolean()) return inspectBoolean(value, depth, opts)
  if (type.isNumber()) return inspectNumber(value, depth, opts)
  if (type.isBigInt()) return inspectBigInt(value, depth, opts)
  if (type.isString()) return inspectString(value, depth, opts)
  if (type.isSymbol()) return inspectSymbol(value, depth, opts)
  if (type.isObject()) return inspectObject(type, value, depth, opts)
  if (type.isFunction()) return inspectFunction(type, value, depth, opts)
  if (type.isExternal()) return inspectExternal(value, opts, opts)
}

function inspectUndefined(depth, opts) {
  return new InspectLeaf('undefined', styles.undefined, depth, opts)
}

function inspectNull(depth, opts) {
  return new InspectLeaf('null', styles.null, depth, opts)
}

function inspectBoolean(value, depth, opts) {
  return new InspectLeaf(value.toString(), styles.boolean, depth, opts)
}

function inspectNumber(value, depth, opts) {
  let string

  if (Object.is(value, -0)) {
    string = '-0'
  } else {
    string = value.toString(10)
  }

  return new InspectLeaf(string, styles.number, depth, opts)
}

function inspectBigInt(value, depth, opts) {
  return new InspectLeaf(value.toString(10) + 'n', styles.bigint, depth, opts)
}

const STRING_ESCAPES =
  /[\ud800-\udbff][\udc00-\udfff]|[\u0000-\u001f'\\\ud800-\udfff]/g

function inspectString(value, depth, opts) {
  // https://tc39.es/ecma262/multipage/structured-data.html#sec-quotejsonstring
  const string = value.replace(STRING_ESCAPES, (match) => {
    if (match.length === 2) return match

    switch (match) {
      case "'":
        return "\\'"
      case '\\':
        return '\\\\'
      case '\b':
        return '\\b'
      case '\t':
        return '\\t'
      case '\n':
        return '\\n'
      case '\f':
        return '\\f'
      case '\r':
        return '\\r'
      default:
        return '\\u' + match.charCodeAt(0).toString(16).padStart(4, '0')
    }
  })

  return new InspectLeaf("'" + string + "'", styles.string, depth, opts)
}

function inspectSymbol(value, depth, opts) {
  return new InspectLeaf(value.toString(), styles.symbol, depth, opts)
}

function inspectKey(value, depth, opts) {
  if (PLAIN_KEY.test(value)) {
    return new InspectLeaf(value, null, depth, opts)
  } else {
    return inspectValue(value, depth, opts)
  }
}

function inspectObject(type, object, depth, opts) {
  const refs = opts.references

  let ref = refs.get(object)
  if (ref === null) {
    ref = new InspectRef(depth, opts)
    refs.set(object, ref)
  } else if (ref.count) {
    ref.circular = true
    return ref
  }

  const maxDepth = typeof opts.depth === 'number' ? opts.depth : Infinity

  if (maxDepth < depth) {
    const constructor = object.constructor

    return new InspectLeaf(
      '[' +
        (constructor && constructor.name ? constructor.name : 'Object') +
        ']',
      styles.special,
      depth,
      opts
    )
  }

  const inspect =
    object[Symbol.for('bare.inspect')] ||
    object[Symbol.for('nodejs.util.inspect.custom')]

  if (typeof inspect === 'function') {
    const value = inspect.call(
      object,
      typeof opts.depth === 'number' ? opts.depth - depth : null,
      {
        colors: opts.colors,
        breakLength: opts.breakLength,
        stylize: opts.stylize
      },
      exports
    )

    if (typeof value === 'object' && value !== null) {
      refs.set(value, ref)
    }

    if (typeof value !== 'string') {
      return inspectValue(value, depth, opts)
    }

    return new InspectLeaf(value, null, depth, opts)
  }

  if (type.isArray()) return inspectArray(object, ref, depth, opts)
  if (type.isDate()) return inspectDate(object, ref, depth, opts)
  if (type.isRegExp()) return inspectRegExp(object, ref, depth, opts)
  if (type.isError()) return inspectError(object, ref, depth, opts)
  if (type.isPromise()) return inspectPromise(object, ref, depth, opts)
  if (type.isMap()) return inspectMap(object, ref, depth, opts)
  if (type.isSet()) return inspectSet(object, ref, depth, opts)
  if (type.isWeakMap()) return inspectWeakMap(object, ref, depth, opts)
  if (type.isWeakSet()) return inspectWeakSet(object, ref, depth, opts)
  if (type.isWeakRef()) return inspectWeakRef(object, ref, depth, opts)
  if (type.isArrayBuffer()) return inspectArrayBuffer(object, ref, depth, opts)
  if (type.isSharedArrayBuffer())
    return inspectSharedArrayBuffer(object, ref, depth, opts)
  if (type.isTypedArray()) return inspectTypedArray(object, ref, depth, opts)
  if (type.isDataView()) return inspectDataView(object, ref, depth, opts)

  ref.increment()

  const values = []

  for (const key in object) {
    if (key === 'constructor') continue

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(object[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  let header = '{ '

  const tag = object[Symbol.toStringTag]

  if (tag) header = '[' + tag + '] ' + header

  if (object.constructor) {
    const name = object.constructor.name

    if (name && name !== 'Object') {
      header = object.constructor.name + ' ' + header
    }
  }

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectArray(array, ref, depth, opts) {
  const { maxArrayLength = defaultMaxArrayLength } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxArrayLength, 0)

  for (let i = 0, n = array.length; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(array.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(inspectValue(array[i], depth + 1, opts))
  }

  for (const key of binding.getOwnNonIndexPropertyNames(array)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(array[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  let header = '[ '

  if (array.constructor.name !== 'Array') {
    header = array.constructor.name + '(' + array.length + ') ' + header
  }

  return new InspectSequence(header, ' ]', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectDate(date, ref, depth, opts) {
  return new InspectLeaf(date.toISOString(), styles.date, depth, opts)
}

function inspectRegExp(regExp, ref, depth, opts) {
  return new InspectLeaf(regExp.toString(), styles.regexp, depth, opts)
}

function inspectError(error, ref, depth, opts) {
  let header

  if ('stack' in error) {
    header = error.stack

    if (depth > 0) {
      header = header.replaceAll('\n', '\n' + '  '.repeat(depth))
    }
  } else {
    header = error.toString()
  }

  const builtins = ['cause']

  if (error.name === 'AggregateError') {
    builtins.push('errors')
  } else if (error.name === 'SuppressedError') {
    builtins.push('error', 'suppressed')
  }

  const values = []

  for (const key of builtins) {
    if (key in error === false) continue

    values.push(
      new InspectPair(
        ': ',
        new InspectLeaf('[' + key + ']', null, depth + 1, opts),
        inspectValue(error[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key in error) {
    if (key === 'constructor' || builtins.includes(key)) continue

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(error[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  if (values.length === 0) return new InspectLeaf(header, null, depth, opts)

  return new InspectSequence(
    header + ' {',
    ' }',
    ', ',
    values,
    ref,
    depth,
    opts
  )
}

function inspectPromise(promise, ref, depth, opts) {
  ref.increment()

  const state = binding.getPromiseState(promise)

  const values = []

  switch (state) {
    case 0: // Pending
      values.push(new InspectLeaf('<pending>', styles.special, depth, opts))
      break

    case 1: // Fulfilled
      values.push(inspectValue(binding.getPromiseResult(promise), depth, opts))
      break

    case 2: // Rejected
      values.push(
        new InspectLeaf('<rejected>', styles.special, depth, opts),
        inspectValue(binding.getPromiseResult(promise), depth, opts)
      )
  }

  ref.decrement()

  const header = promise.constructor.name + ' { '

  return new InspectSequence(header, ' }', ' ', values, ref, depth, opts)
}

function inspectMap(map, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxMapLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = maxMapLength

  for (const entry of map) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(map.size - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )
      break
    }

    values.push(
      new InspectPair(
        ' => ',
        inspectValue(entry[0], depth + 1, opts),
        inspectValue(entry[1], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key in map) {
    if (key === 'constructor') continue

    const value = inspectValue(map[key], depth + 1, opts)

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        value,
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = map.constructor.name + '(' + map.size + ') { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectSet(set, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxSetLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = maxSetLength

  for (const entry of set) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(set.size - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )
      break
    }

    values.push(inspectValue(entry, depth + 1, opts))
  }

  for (const key in set) {
    if (key === 'constructor') continue

    const value = inspectValue(set[key], depth + 1, opts)

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        value,
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = set.constructor.name + '(' + set.size + ') { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectWeakMap(weakMap, ref, depth, opts) {
  const header = weakMap.constructor.name + ' { '

  return new InspectSequence(
    header,
    ' }',
    ' ',
    [new InspectLeaf('<items unknown>', styles.special, depth + 1, opts)],
    ref,
    depth,
    opts
  )
}

function inspectWeakSet(weakSet, ref, depth, opts) {
  const header = weakSet.constructor.name + ' { '

  return new InspectSequence(
    header,
    ' }',
    ' ',
    [new InspectLeaf('<items unknown>', styles.special, depth + 1, opts)],
    ref,
    depth,
    opts
  )
}

function inspectWeakRef(weakRef, ref, depth, opts) {
  const target = weakRef.deref()

  let value

  if (target === undefined) {
    value = new InspectLeaf('<cleared>', styles.special, depth + 1, opts)
  } else {
    value = inspectValue(target, depth + 1, opts)
  }

  const header = weakRef.constructor.name + ' { '

  return new InspectSequence(header, ' }', ' ', [value], ref, depth, opts)
}

function inspectArrayBuffer(arrayBuffer, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(arrayBuffer[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = arrayBuffer.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectSharedArrayBuffer(sharedArrayBuffer, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(sharedArrayBuffer[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = sharedArrayBuffer.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectTypedArray(typedArray, ref, depth, opts) {
  if (Buffer.isBuffer(typedArray)) {
    return inspectBuffer(typedArray, ref, depth, opts)
  }

  const {
    maxArrayLength = defaultMaxArrayLength,
    maxTypedArrayLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxTypedArrayLength, 0)

  for (let i = 0, n = typedArray.length; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(typedArray.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(inspectValue(typedArray[i], depth + 1, opts))
  }

  for (const key of binding.getOwnNonIndexPropertyNames(typedArray)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(typedArray[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = typedArray.constructor.name + '(' + typedArray.length + ') [ '

  return new InspectSequence(header, ' ]', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectBuffer(buffer, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxBufferLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxBufferLength, 0)

  for (let i = 0, n = buffer.byteLength; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(buffer.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(
      new InspectLeaf(
        buffer[i].toString(16).padStart(2, '0'),
        null,
        depth + 1,
        opts
      )
    )
  }

  for (const key of binding.getOwnNonIndexPropertyNames(buffer)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(buffer[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  return new InspectSequence('<Buffer ', '>', ' ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectDataView(dataView, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength', 'byteOffset', 'buffer']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(dataView[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key of binding.getOwnNonIndexPropertyNames(dataView)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(dataView[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = dataView.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectFunction(type, fn, depth, opts) {
  if (fn.toString().startsWith('class')) return inspectClass(fn, depth, opts)

  let tag = 'function'

  if (type.isGeneratorFunction()) tag = 'generator ' + tag
  if (type.isAsyncFunction()) tag = 'async ' + tag

  return new InspectLeaf(
    '[' + tag + ' ' + (fn.name ? fn.name : '(anonymous)') + ']',
    styles.special,
    depth,
    opts
  )
}

function inspectClass(ctor, depth, opts) {
  return new InspectLeaf(
    '[class ' + (ctor.name ? ctor.name : '(anonymous)') + ']',
    styles.special,
    depth,
    opts
  )
}

function inspectExternal(external, depth, opts) {
  return new InspectLeaf(
    '[external 0x' + binding.getExternal(external).toString(16) + ']',
    styles.special,
    depth,
    opts
  )
}
{
  "name": "bare-inspect",
  "version": "3.1.4",
  "description": "Inspect objects as strings for debugging",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-inspect.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-inspect/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-inspect#readme",
  "engines": {
    "bare": ">=1.18.0"
  },
  "dependencies": {
    "bare-ansi-escapes": "^2.1.0",
    "bare-type": "^1.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
module.exports = require.addon()
const binding = require('./binding')

const t = binding.constants

class Type {
  constructor(type) {
    this._type = type
  }

  isUndefined() {
    return this._type === t.UNDEFINED
  }

  isNull() {
    return this._type === t.NULL
  }

  isBoolean() {
    return this._type === t.BOOLEAN
  }

  isNumber() {
    return (this._type & 0xff) === t.NUMBER
  }

  isInt32() {
    return (this._type & (0xff | t.INT32)) === (t.NUMBER | t.INT32)
  }

  isUint32() {
    return (this._type & (0xff | t.UINT32)) === (t.NUMBER | t.UINT32)
  }

  isString() {
    return this._type === t.STRING
  }

  isSymbol() {
    return this._type === t.SYMBOL
  }

  isObject() {
    return (this._type & 0xff) === t.OBJECT
  }

  isArray() {
    return this._type === (t.OBJECT | t.ARRAY)
  }

  isArguments() {
    return this._type === (t.OBJECT | t.ARGUMENTS)
  }

  isDate() {
    return this._type === (t.OBJECT | t.DATE)
  }

  isRegExp() {
    return this._type === (t.OBJECT | t.REGEXP)
  }

  isError() {
    return this._type === (t.OBJECT | t.ERROR)
  }

  isPromise() {
    return this._type === (t.OBJECT | t.PROMISE)
  }

  isProxy() {
    return this._type === (t.OBJECT | t.PROXY)
  }

  isGenerator() {
    return this._type === (t.OBJECT | t.GENERATOR)
  }

  isMap() {
    return this._type === (t.OBJECT | t.MAP)
  }

  isSet() {
    return this._type === (t.OBJECT | t.SET)
  }

  isWeakMap() {
    return this._type === (t.OBJECT | t.WEAK_MAP)
  }

  isWeakSet() {
    return this._type === (t.OBJECT | t.WEAK_SET)
  }

  isWeakRef() {
    return this._type === (t.OBJECT | t.WEAK_REF)
  }

  isArrayBuffer() {
    return this._type === (t.OBJECT | t.ARRAYBUFFER)
  }

  isSharedArrayBuffer() {
    return this._type === (t.OBJECT | t.SHAREDARRAYBUFFER)
  }

  isTypedArray() {
    return (this._type & 0xffff) === (t.OBJECT | t.TYPEDARRAY)
  }

  isInt8Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT8ARRAY)
  }

  isUint8Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT8ARRAY)
  }

  isUint8ClampedArray() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT8CLAMPEDARRAY)
  }

  isInt16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT16ARRAY)
  }

  isUint16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT16ARRAY)
  }

  isInt32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT32ARRAY)
  }

  isUint32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT32ARRAY)
  }

  isFloat16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT16ARRAY)
  }

  isFloat32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT32ARRAY)
  }

  isFloat64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT64ARRAY)
  }

  isBigInt64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.BIGINT64ARRAY)
  }

  isBigUint64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.BIGUINT64ARRAY)
  }

  isDataView() {
    return this._type === (t.OBJECT | t.DATAVIEW)
  }

  isModuleNamespace() {
    return this._type === (t.OBJECT | t.MODULE_NAMESPACE)
  }

  isFunction() {
    return (this._type & 0xff) === t.FUNCTION
  }

  isAsyncFunction() {
    return (
      (this._type & (0xff | t.ASYNC_FUNCTION)) ===
      (t.FUNCTION | t.ASYNC_FUNCTION)
    )
  }

  isGeneratorFunction() {
    return (
      (this._type & (0xff | t.GENERATOR_FUNCTION)) ===
      (t.FUNCTION | t.GENERATOR_FUNCTION)
    )
  }

  isExternal() {
    return this._type === t.EXTERNAL
  }

  isBigInt() {
    return this._type === t.BIGINT
  }
}

module.exports = exports = function type(value) {
  switch (typeof value) {
    case 'undefined':
      return new Type(t.UNDEFINED)
    case 'boolean':
      return new Type(t.BOOLEAN)
    case 'number':
      return new Type(
        Number.isSafeInteger(value) ? binding.type(value) : t.NUMBER
      )
    case 'string':
      return new Type(t.STRING)
    case 'symbol':
      return new Type(t.SYMBOL)
    case 'object':
      return new Type(value === null ? t.NULL : binding.type(value))
    case 'function':
      return new Type(binding.type(value))
    case 'bigint':
      return new Type(t.BIGINT)
  }
}

exports.createTag = function createTag(...components) {
  const tag = new Uint32Array(4)
  for (let i = 0; i < 4; i++) tag[i] = components[i] || 0
  return tag
}

exports.addTag = function addTag(object, tag) {
  binding.addTag(object, tag)
}

exports.checkTag = function checkTag(object, tag) {
  return binding.checkTag(object, tag)
}
{
  "name": "bare-type",
  "version": "1.1.0",
  "description": "Cross-realm type predicates for Bare",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-type.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-type/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-type#readme",
  "engines": {
    "bare": ">=1.2.0"
  },
  "devDependencies": {
    "brittle": "^3.4.0",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
const sodium = require('sodium-universal')
const b4a = require('b4a')
const assert = require('nanoassert')
const { detectLanguage, loadWordlist } = require('./wordlist')

module.exports = {
  generateEntropy,
  generateMnemonic,
  normalizeMnemonic,
  validateMnemonic,
  mnemonicToEntropy,
  mnemonicToSeed,
  entropyToMnemonic
}

function generateMnemonic ({ entropy = generateEntropy(), language = 'english' } = {}) {
  const wordlist = loadWordlist(language)
  const extended = computeCheckSum(entropy)

  const words = []

  for (const index of uint11Reader(extended)) {
    words.push(wordlist[index])
  }

  const delimiter = language === 'japanese' ? '\u3000' : ' '

  return words.join(delimiter).trim()
}

function entropyToMnemonic (entropy, { language = 'english' } = {}) {
  return generateMnemonic({ entropy, language })
}

function mnemonicToEntropy (mnemonic) {
  const words = mnemonic.replace(/\u3000/g, ' ').trim().split(' ')
  const language = detectLanguage(words)

  if (!language) {
    throw new Error('Language not recognised')
  }

  if (words.length % 3 !== 0) {
    throw new Error('Invalid length')
  }

  const wordlist = loadWordlist(language)

  const indexes = []
  for (const word of words) {
    const index = wordlist.indexOf(word)
    if (index === -1) {
      throw new Error('Bad word')
    }

    indexes.push(index)
  }

  const bits = words.length * 11
  const len = (bits * 32 / 33) >> 3

  const extended = b4a.alloc(Math.ceil(bits / 8))
  const entropy = extended.subarray(0, len)

  uint11Writer(extended, indexes)

  if (!b4a.equals(extended, computeCheckSum(entropy))) {
    throw new Error('Invalid checksum')
  }

  return entropy
}

function normalizeMnemonic (mnemonic) {
  return mnemonic.trim().replace(/\u3000/, ' ').split(/\s+/).map(c => c.toLowerCase()).join(' ')
}

async function mnemonicToSeed (mnemonic, passphrase = '') {
  mnemonic = normalizeMnemonic(mnemonic)

  if (!validateMnemonic(mnemonic)) {
    throw new Error('Invalid mnemonic')
  }

  const input = b4a.from(mnemonic)
  const salt = b4a.from('mnemonic' + passphrase)

  const output = b4a.alloc(64)

  await sodium.extension_pbkdf2_sha512_async(
    output,
    input,
    salt,
    2048,
    64
  )

  return output
}

function validateMnemonic (mnemonic) {
  try {
    mnemonicToEntropy(mnemonic)
  } catch (e) {
    return false
  }
  return true
}

function sha256 (data, output = b4a.alloc(32)) {
  sodium.crypto_hash_sha256(output, data)
  return output
}

function computeCheckSum (seed) {
  assert((seed.byteLength & 4) === 0, 'seed must be a multiple of 4 bytes')

  const len = seed.byteLength
  const cklen = len >> 2 // cksum bits
  const total = len + Math.ceil(cklen / 8)

  const output = b4a.alloc(len + 32)
  output.set(seed)

  const entropy = output.subarray(0, len)
  const cksum = output.subarray(len)

  sha256(entropy, cksum)

  // only append cklen bits
  output[total - 1] &= (0xff ^ (0xff >> cklen))

  return output.subarray(0, total)
}

function generateEntropy (length = 32) {
  const seed = b4a.alloc(length)
  sodium.randombytes_buf(seed)

  return seed
}

function * uint11Reader (state) {
  yield * uintReader(state, 11)
}

function uint11Writer (buf, uints) {
  return uintWriter(buf, uints, 11)
}

function * uintReader (buffer, width) {
  const MASK = (2 << (width - 1)) - 1

  let pos = 0
  let value = 0

  while (true) {
    const offset = pos >> 3 // byte offset

    if (offset >= buffer.byteLength) {
      return value & MASK
    }

    const height = width - (pos % width)
    const leftover = (offset + 1) * 8 - pos

    value += shift(buffer[offset], height - leftover)

    pos += Math.min(height, leftover)
    if (pos % width) continue

    yield value & MASK

    value = 0
  }
}

function uintWriter (buffer, uints, width) {
  let pos = 0

  while (true) {
    const offset = pos >> 3 // byte offset

    const i = Math.floor(pos / width)
    if (i >= uints.length) break

    if (offset >= buffer.length) {
      throw new Error('Failed to encode uints')
    }

    const rem = 8 - pos % 8
    const height = (i + 1) * width - pos

    const value = shift(uints[i], rem - height)

    buffer[offset] += mask(value, rem)

    pos += Math.min(rem, height)
  }

  return buffer
}

// when n is positive, shift left n bits
// when n is negative, shift right -n bits
function shift (val, n) {
  if (n === 0) return val
  if (n > 0) return val << n

  return val >> (-1 * n)
}

function mask (val, bits) {
  if (bits < 32) return val & ((1 << bits) - 1)
  return val % (2 ** bits)
}
{
  "name": "bip39-mnemonic",
  "version": "2.5.0",
  "description": "BIP39 mnemonic for key derivation schemes",
  "main": "index.js",
  "scripts": {
    "generate-wordlist": "node scripts/generate-wordlist.js",
    "test": "standard && brittle test/*.js"
  },
  "author": "Holepunch Inc",
  "license": "Apache-2.0",
  "devDependencies": {
    "brittle": "^3.4.0",
    "standard": "^17.1.0"
  },
  "dependencies": {
    "b4a": "^1.6.6",
    "nanoassert": "^2.0.0",
    "sodium-universal": "^5.0.1"
  },
  "files": [
    "index.js",
    "wordlist"
  ],
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bip39.git"
  },
  "bugs": {
    "url": "https://github.com/holepunchto/bip39/issues"
  },
  "homepage": "https://github.com/holepunchto/bip39#readme"
}
["的","一","是","在","不","了","有","和","人","这","中","大","为","上","个","国","我","以","要","他","时","来","用","们","生","到","作","地","于","出","就","分","对","成","会","可","主","发","年","动","同","工","也","能","下","过","子","说","产","种","面","而","方","后","多","定","行","学","法","所","民","得","经","十","三","之","进","着","等","部","度","家","电","力","里","如","水","化","高","自","二","理","起","小","物","现","实","加","量","都","两","体","制","机","当","使","点","从","业","本","去","把","性","好","应","开","它","合","还","因","由","其","些","然","前","外","天","政","四","日","那","社","义","事","平","形","相","全","表","间","样","与","关","各","重","新","线","内","数","正","心","反","你","明","看","原","又","么","利","比","或","但","质","气","第","向","道","命","此","变","条","只","没","结","解","问","意","建","月","公","无","系","军","很","情","者","最","立","代","想","已","通","并","提","直","题","党","程","展","五","果","料","象","员","革","位","入","常","文","总","次","品","式","活","设","及","管","特","件","长","求","老","头","基","资","边","流","路","级","少","图","山","统","接","知","较","将","组","见","计","别","她","手","角","期","根","论","运","农","指","几","九","区","强","放","决","西","被","干","做","必","战","先","回","则","任","取","据","处","队","南","给","色","光","门","即","保","治","北","造","百","规","热","领","七","海","口","东","导","器","压","志","世","金","增","争","济","阶","油","思","术","极","交","受","联","什","认","六","共","权","收","证","改","清","美","再","采","转","更","单","风","切","打","白","教","速","花","带","安","场","身","车","例","真","务","具","万","每","目","至","达","走","积","示","议","声","报","斗","完","类","八","离","华","名","确","才","科","张","信","马","节","话","米","整","空","元","况","今","集","温","传","土","许","步","群","广","石","记","需","段","研","界","拉","林","律","叫","且","究","观","越","织","装","影","算","低","持","音","众","书","布","复","容","儿","须","际","商","非","验","连","断","深","难","近","矿","千","周","委","素","技","备","半","办","青","省","列","习","响","约","支","般","史","感","劳","便","团","往","酸","历","市","克","何","除","消","构","府","称","太","准","精","值","号","率","族","维","划","选","标","写","存","候","毛","亲","快","效","斯","院","查","江","型","眼","王","按","格","养","易","置","派","层","片","始","却","专","状","育","厂","京","识","适","属","圆","包","火","住","调","满","县","局","照","参","红","细","引","听","该","铁","价","严","首","底","液","官","德","随","病","苏","失","尔","死","讲","配","女","黄","推","显","谈","罪","神","艺","呢","席","含","企","望","密","批","营","项","防","举","球","英","氧","势","告","李","台","落","木","帮","轮","破","亚","师","围","注","远","字","材","排","供","河","态","封","另","施","减","树","溶","怎","止","案","言","士","均","武","固","叶","鱼","波","视","仅","费","紧","爱","左","章","早","朝","害","续","轻","服","试","食","充","兵","源","判","护","司","足","某","练","差","致","板","田","降","黑","犯","负","击","范","继","兴","似","余","坚","曲","输","修","故","城","夫","够","送","笔","船","占","右","财","吃","富","春","职","觉","汉","画","功","巴","跟","虽","杂","飞","检","吸","助","升","阳","互","初","创","抗","考","投","坏","策","古","径","换","未","跑","留","钢","曾","端","责","站","简","述","钱","副","尽","帝","射","草","冲","承","独","令","限","阿","宣","环","双","请","超","微","让","控","州","良","轴","找","否","纪","益","依","优","顶","础","载","倒","房","突","坐","粉","敌","略","客","袁","冷","胜","绝","析","块","剂","测","丝","协","诉","念","陈","仍","罗","盐","友","洋","错","苦","夜","刑","移","频","逐","靠","混","母","短","皮","终","聚","汽","村","云","哪","既","距","卫","停","烈","央","察","烧","迅","境","若","印","洲","刻","括","激","孔","搞","甚","室","待","核","校","散","侵","吧","甲","游","久","菜","味","旧","模","湖","货","损","预","阻","毫","普","稳","乙","妈","植","息","扩","银","语","挥","酒","守","拿","序","纸","医","缺","雨","吗","针","刘","啊","急","唱","误","训","愿","审","附","获","茶","鲜","粮","斤","孩","脱","硫","肥","善","龙","演","父","渐","血","欢","械","掌","歌","沙","刚","攻","谓","盾","讨","晚","粒","乱","燃","矛","乎","杀","药","宁","鲁","贵","钟","煤","读","班","伯","香","介","迫","句","丰","培","握","兰","担","弦","蛋","沉","假","穿","执","答","乐","谁","顺","烟","缩","征","脸","喜","松","脚","困","异","免","背","星","福","买","染","井","概","慢","怕","磁","倍","祖","皇","促","静","补","评","翻","肉","践","尼","衣","宽","扬","棉","希","伤","操","垂","秋","宜","氢","套","督","振","架","亮","末","宪","庆","编","牛","触","映","雷","销","诗","座","居","抓","裂","胞","呼","娘","景","威","绿","晶","厚","盟","衡","鸡","孙","延","危","胶","屋","乡","临","陆","顾","掉","呀","灯","岁","措","束","耐","剧","玉","赵","跳","哥","季","课","凯","胡","额","款","绍","卷","齐","伟","蒸","殖","永","宗","苗","川","炉","岩","弱","零","杨","奏","沿","露","杆","探","滑","镇","饭","浓","航","怀","赶","库","夺","伊","灵","税","途","灭","赛","归","召","鼓","播","盘","裁","险","康","唯","录","菌","纯","借","糖","盖","横","符","私","努","堂","域","枪","润","幅","哈","竟","熟","虫","泽","脑","壤","碳","欧","遍","侧","寨","敢","彻","虑","斜","薄","庭","纳","弹","饲","伸","折","麦","湿","暗","荷","瓦","塞","床","筑","恶","户","访","塔","奇","透","梁","刀","旋","迹","卡","氯","遇","份","毒","泥","退","洗","摆","灰","彩","卖","耗","夏","择","忙","铜","献","硬","予","繁","圈","雪","函","亦","抽","篇","阵","阴","丁","尺","追","堆","雄","迎","泛","爸","楼","避","谋","吨","野","猪","旗","累","偏","典","馆","索","秦","脂","潮","爷","豆","忽","托","惊","塑","遗","愈","朱","替","纤","粗","倾","尚","痛","楚","谢","奋","购","磨","君","池","旁","碎","骨","监","捕","弟","暴","割","贯","殊","释","词","亡","壁","顿","宝","午","尘","闻","揭","炮","残","冬","桥","妇","警","综","招","吴","付","浮","遭","徐","您","摇","谷","赞","箱","隔","订","男","吹","园","纷","唐","败","宋","玻","巨","耕","坦","荣","闭","湾","键","凡","驻","锅","救","恩","剥","凝","碱","齿","截","炼","麻","纺","禁","废","盛","版","缓","净","睛","昌","婚","涉","筒","嘴","插","岸","朗","庄","街","藏","姑","贸","腐","奴","啦","惯","乘","伙","恢","匀","纱","扎","辩","耳","彪","臣","亿","璃","抵","脉","秀","萨","俄","网","舞","店","喷","纵","寸","汗","挂","洪","贺","闪","柬","爆","烯","津","稻","墙","软","勇","像","滚","厘","蒙","芳","肯","坡","柱","荡","腿","仪","旅","尾","轧","冰","贡","登","黎","削","钻","勒","逃","障","氨","郭","峰","币","港","伏","轨","亩","毕","擦","莫","刺","浪","秘","援","株","健","售","股","岛","甘","泡","睡","童","铸","汤","阀","休","汇","舍","牧","绕","炸","哲","磷","绩","朋","淡","尖","启","陷","柴","呈","徒","颜","泪","稍","忘","泵","蓝","拖","洞","授","镜","辛","壮","锋","贫","虚","弯","摩","泰","幼","廷","尊","窗","纲","弄","隶","疑","氏","宫","姐","震","瑞","怪","尤","琴","循","描","膜","违","夹","腰","缘","珠","穷","森","枝","竹","沟","催","绳","忆","邦","剩","幸","浆","栏","拥","牙","贮","礼","滤","钠","纹","罢","拍","咱","喊","袖","埃","勤","罚","焦","潜","伍","墨","欲","缝","姓","刊","饱","仿","奖","铝","鬼","丽","跨","默","挖","链","扫","喝","袋","炭","污","幕","诸","弧","励","梅","奶","洁","灾","舟","鉴","苯","讼","抱","毁","懂","寒","智","埔","寄","届","跃","渡","挑","丹","艰","贝","碰","拔","爹","戴","码","梦","芽","熔","赤","渔","哭","敬","颗","奔","铅","仲","虎","稀","妹","乏","珍","申","桌","遵","允","隆","螺","仓","魏","锐","晓","氮","兼","隐","碍","赫","拨","忠","肃","缸","牵","抢","博","巧","壳","兄","杜","讯","诚","碧","祥","柯","页","巡","矩","悲","灌","龄","伦","票","寻","桂","铺","圣","恐","恰","郑","趣","抬","荒","腾","贴","柔","滴","猛","阔","辆","妻","填","撤","储","签","闹","扰","紫","砂","递","戏","吊","陶","伐","喂","疗","瓶","婆","抚","臂","摸","忍","虾","蜡","邻","胸","巩","挤","偶","弃","槽","劲","乳","邓","吉","仁","烂","砖","租","乌","舰","伴","瓜","浅","丙","暂","燥","橡","柳","迷","暖","牌","秧","胆","详","簧","踏","瓷","谱","呆","宾","糊","洛","辉","愤","竞","隙","怒","粘","乃","绪","肩","籍","敏","涂","熙","皆","侦","悬","掘","享","纠","醒","狂","锁","淀","恨","牲","霸","爬","赏","逆","玩","陵","祝","秒","浙","貌","役","彼","悉","鸭","趋","凤","晨","畜","辈","秩","卵","署","梯","炎","滩","棋","驱","筛","峡","冒","啥","寿","译","浸","泉","帽","迟","硅","疆","贷","漏","稿","冠","嫩","胁","芯","牢","叛","蚀","奥","鸣","岭","羊","凭","串","塘","绘","酵","融","盆","锡","庙","筹","冻","辅","摄","袭","筋","拒","僚","旱","钾","鸟","漆","沈","眉","疏","添","棒","穗","硝","韩","逼","扭","侨","凉","挺","碗","栽","炒","杯","患","馏","劝","豪","辽","勃","鸿","旦","吏","拜","狗","埋","辊","掩","饮","搬","骂","辞","勾","扣","估","蒋","绒","雾","丈","朵","姆","拟","宇","辑","陕","雕","偿","蓄","崇","剪","倡","厅","咬","驶","薯","刷","斥","番","赋","奉","佛","浇","漫","曼","扇","钙","桃","扶","仔","返","俗","亏","腔","鞋","棱","覆","框","悄","叔","撞","骗","勘","旺","沸","孤","吐","孟","渠","屈","疾","妙","惜","仰","狠","胀","谐","抛","霉","桑","岗","嘛","衰","盗","渗","脏","赖","涌","甜","曹","阅","肌","哩","厉","烃","纬","毅","昨","伪","症","煮","叹","钉","搭","茎","笼","酷","偷","弓","锥","恒","杰","坑","鼻","翼","纶","叙","狱","逮","罐","络","棚","抑","膨","蔬","寺","骤","穆","冶","枯","册","尸","凸","绅","坯","牺","焰","轰","欣","晋","瘦","御","锭","锦","丧","旬","锻","垄","搜","扑","邀","亭","酯","迈","舒","脆","酶","闲","忧","酚","顽","羽","涨","卸","仗","陪","辟","惩","杭","姚","肚","捉","飘","漂","昆","欺","吾","郎","烷","汁","呵","饰","萧","雅","邮","迁","燕","撒","姻","赴","宴","烦","债","帐","斑","铃","旨","醇","董","饼","雏","姿","拌","傅","腹","妥","揉","贤","拆","歪","葡","胺","丢","浩","徽","昂","垫","挡","览","贪","慰","缴","汪","慌","冯","诺","姜","谊","凶","劣","诬","耀","昏","躺","盈","骑","乔","溪","丛","卢","抹","闷","咨","刮","驾","缆","悟","摘","铒","掷","颇","幻","柄","惠","惨","佳","仇","腊","窝","涤","剑","瞧","堡","泼","葱","罩","霍","捞","胎","苍","滨","俩","捅","湘","砍","霞","邵","萄","疯","淮","遂","熊","粪","烘","宿","档","戈","驳","嫂","裕","徙","箭","捐","肠","撑","晒","辨","殿","莲","摊","搅","酱","屏","疫","哀","蔡","堵","沫","皱","畅","叠","阁","莱","敲","辖","钩","痕","坝","巷","饿","祸","丘","玄","溜","曰","逻","彭","尝","卿","妨","艇","吞","韦","怨","矮","歇"]["的","一","是","在","不","了","有","和","人","這","中","大","為","上","個","國","我","以","要","他","時","來","用","們","生","到","作","地","於","出","就","分","對","成","會","可","主","發","年","動","同","工","也","能","下","過","子","說","產","種","面","而","方","後","多","定","行","學","法","所","民","得","經","十","三","之","進","著","等","部","度","家","電","力","裡","如","水","化","高","自","二","理","起","小","物","現","實","加","量","都","兩","體","制","機","當","使","點","從","業","本","去","把","性","好","應","開","它","合","還","因","由","其","些","然","前","外","天","政","四","日","那","社","義","事","平","形","相","全","表","間","樣","與","關","各","重","新","線","內","數","正","心","反","你","明","看","原","又","麼","利","比","或","但","質","氣","第","向","道","命","此","變","條","只","沒","結","解","問","意","建","月","公","無","系","軍","很","情","者","最","立","代","想","已","通","並","提","直","題","黨","程","展","五","果","料","象","員","革","位","入","常","文","總","次","品","式","活","設","及","管","特","件","長","求","老","頭","基","資","邊","流","路","級","少","圖","山","統","接","知","較","將","組","見","計","別","她","手","角","期","根","論","運","農","指","幾","九","區","強","放","決","西","被","幹","做","必","戰","先","回","則","任","取","據","處","隊","南","給","色","光","門","即","保","治","北","造","百","規","熱","領","七","海","口","東","導","器","壓","志","世","金","增","爭","濟","階","油","思","術","極","交","受","聯","什","認","六","共","權","收","證","改","清","美","再","採","轉","更","單","風","切","打","白","教","速","花","帶","安","場","身","車","例","真","務","具","萬","每","目","至","達","走","積","示","議","聲","報","鬥","完","類","八","離","華","名","確","才","科","張","信","馬","節","話","米","整","空","元","況","今","集","溫","傳","土","許","步","群","廣","石","記","需","段","研","界","拉","林","律","叫","且","究","觀","越","織","裝","影","算","低","持","音","眾","書","布","复","容","兒","須","際","商","非","驗","連","斷","深","難","近","礦","千","週","委","素","技","備","半","辦","青","省","列","習","響","約","支","般","史","感","勞","便","團","往","酸","歷","市","克","何","除","消","構","府","稱","太","準","精","值","號","率","族","維","劃","選","標","寫","存","候","毛","親","快","效","斯","院","查","江","型","眼","王","按","格","養","易","置","派","層","片","始","卻","專","狀","育","廠","京","識","適","屬","圓","包","火","住","調","滿","縣","局","照","參","紅","細","引","聽","該","鐵","價","嚴","首","底","液","官","德","隨","病","蘇","失","爾","死","講","配","女","黃","推","顯","談","罪","神","藝","呢","席","含","企","望","密","批","營","項","防","舉","球","英","氧","勢","告","李","台","落","木","幫","輪","破","亞","師","圍","注","遠","字","材","排","供","河","態","封","另","施","減","樹","溶","怎","止","案","言","士","均","武","固","葉","魚","波","視","僅","費","緊","愛","左","章","早","朝","害","續","輕","服","試","食","充","兵","源","判","護","司","足","某","練","差","致","板","田","降","黑","犯","負","擊","范","繼","興","似","餘","堅","曲","輸","修","故","城","夫","夠","送","筆","船","佔","右","財","吃","富","春","職","覺","漢","畫","功","巴","跟","雖","雜","飛","檢","吸","助","昇","陽","互","初","創","抗","考","投","壞","策","古","徑","換","未","跑","留","鋼","曾","端","責","站","簡","述","錢","副","盡","帝","射","草","衝","承","獨","令","限","阿","宣","環","雙","請","超","微","讓","控","州","良","軸","找","否","紀","益","依","優","頂","礎","載","倒","房","突","坐","粉","敵","略","客","袁","冷","勝","絕","析","塊","劑","測","絲","協","訴","念","陳","仍","羅","鹽","友","洋","錯","苦","夜","刑","移","頻","逐","靠","混","母","短","皮","終","聚","汽","村","雲","哪","既","距","衛","停","烈","央","察","燒","迅","境","若","印","洲","刻","括","激","孔","搞","甚","室","待","核","校","散","侵","吧","甲","遊","久","菜","味","舊","模","湖","貨","損","預","阻","毫","普","穩","乙","媽","植","息","擴","銀","語","揮","酒","守","拿","序","紙","醫","缺","雨","嗎","針","劉","啊","急","唱","誤","訓","願","審","附","獲","茶","鮮","糧","斤","孩","脫","硫","肥","善","龍","演","父","漸","血","歡","械","掌","歌","沙","剛","攻","謂","盾","討","晚","粒","亂","燃","矛","乎","殺","藥","寧","魯","貴","鐘","煤","讀","班","伯","香","介","迫","句","豐","培","握","蘭","擔","弦","蛋","沉","假","穿","執","答","樂","誰","順","煙","縮","徵","臉","喜","松","腳","困","異","免","背","星","福","買","染","井","概","慢","怕","磁","倍","祖","皇","促","靜","補","評","翻","肉","踐","尼","衣","寬","揚","棉","希","傷","操","垂","秋","宜","氫","套","督","振","架","亮","末","憲","慶","編","牛","觸","映","雷","銷","詩","座","居","抓","裂","胞","呼","娘","景","威","綠","晶","厚","盟","衡","雞","孫","延","危","膠","屋","鄉","臨","陸","顧","掉","呀","燈","歲","措","束","耐","劇","玉","趙","跳","哥","季","課","凱","胡","額","款","紹","卷","齊","偉","蒸","殖","永","宗","苗","川","爐","岩","弱","零","楊","奏","沿","露","桿","探","滑","鎮","飯","濃","航","懷","趕","庫","奪","伊","靈","稅","途","滅","賽","歸","召","鼓","播","盤","裁","險","康","唯","錄","菌","純","借","糖","蓋","橫","符","私","努","堂","域","槍","潤","幅","哈","竟","熟","蟲","澤","腦","壤","碳","歐","遍","側","寨","敢","徹","慮","斜","薄","庭","納","彈","飼","伸","折","麥","濕","暗","荷","瓦","塞","床","築","惡","戶","訪","塔","奇","透","梁","刀","旋","跡","卡","氯","遇","份","毒","泥","退","洗","擺","灰","彩","賣","耗","夏","擇","忙","銅","獻","硬","予","繁","圈","雪","函","亦","抽","篇","陣","陰","丁","尺","追","堆","雄","迎","泛","爸","樓","避","謀","噸","野","豬","旗","累","偏","典","館","索","秦","脂","潮","爺","豆","忽","托","驚","塑","遺","愈","朱","替","纖","粗","傾","尚","痛","楚","謝","奮","購","磨","君","池","旁","碎","骨","監","捕","弟","暴","割","貫","殊","釋","詞","亡","壁","頓","寶","午","塵","聞","揭","炮","殘","冬","橋","婦","警","綜","招","吳","付","浮","遭","徐","您","搖","谷","贊","箱","隔","訂","男","吹","園","紛","唐","敗","宋","玻","巨","耕","坦","榮","閉","灣","鍵","凡","駐","鍋","救","恩","剝","凝","鹼","齒","截","煉","麻","紡","禁","廢","盛","版","緩","淨","睛","昌","婚","涉","筒","嘴","插","岸","朗","莊","街","藏","姑","貿","腐","奴","啦","慣","乘","夥","恢","勻","紗","扎","辯","耳","彪","臣","億","璃","抵","脈","秀","薩","俄","網","舞","店","噴","縱","寸","汗","掛","洪","賀","閃","柬","爆","烯","津","稻","牆","軟","勇","像","滾","厘","蒙","芳","肯","坡","柱","盪","腿","儀","旅","尾","軋","冰","貢","登","黎","削","鑽","勒","逃","障","氨","郭","峰","幣","港","伏","軌","畝","畢","擦","莫","刺","浪","秘","援","株","健","售","股","島","甘","泡","睡","童","鑄","湯","閥","休","匯","舍","牧","繞","炸","哲","磷","績","朋","淡","尖","啟","陷","柴","呈","徒","顏","淚","稍","忘","泵","藍","拖","洞","授","鏡","辛","壯","鋒","貧","虛","彎","摩","泰","幼","廷","尊","窗","綱","弄","隸","疑","氏","宮","姐","震","瑞","怪","尤","琴","循","描","膜","違","夾","腰","緣","珠","窮","森","枝","竹","溝","催","繩","憶","邦","剩","幸","漿","欄","擁","牙","貯","禮","濾","鈉","紋","罷","拍","咱","喊","袖","埃","勤","罰","焦","潛","伍","墨","欲","縫","姓","刊","飽","仿","獎","鋁","鬼","麗","跨","默","挖","鏈","掃","喝","袋","炭","污","幕","諸","弧","勵","梅","奶","潔","災","舟","鑑","苯","訟","抱","毀","懂","寒","智","埔","寄","屆","躍","渡","挑","丹","艱","貝","碰","拔","爹","戴","碼","夢","芽","熔","赤","漁","哭","敬","顆","奔","鉛","仲","虎","稀","妹","乏","珍","申","桌","遵","允","隆","螺","倉","魏","銳","曉","氮","兼","隱","礙","赫","撥","忠","肅","缸","牽","搶","博","巧","殼","兄","杜","訊","誠","碧","祥","柯","頁","巡","矩","悲","灌","齡","倫","票","尋","桂","鋪","聖","恐","恰","鄭","趣","抬","荒","騰","貼","柔","滴","猛","闊","輛","妻","填","撤","儲","簽","鬧","擾","紫","砂","遞","戲","吊","陶","伐","餵","療","瓶","婆","撫","臂","摸","忍","蝦","蠟","鄰","胸","鞏","擠","偶","棄","槽","勁","乳","鄧","吉","仁","爛","磚","租","烏","艦","伴","瓜","淺","丙","暫","燥","橡","柳","迷","暖","牌","秧","膽","詳","簧","踏","瓷","譜","呆","賓","糊","洛","輝","憤","競","隙","怒","粘","乃","緒","肩","籍","敏","塗","熙","皆","偵","懸","掘","享","糾","醒","狂","鎖","淀","恨","牲","霸","爬","賞","逆","玩","陵","祝","秒","浙","貌","役","彼","悉","鴨","趨","鳳","晨","畜","輩","秩","卵","署","梯","炎","灘","棋","驅","篩","峽","冒","啥","壽","譯","浸","泉","帽","遲","矽","疆","貸","漏","稿","冠","嫩","脅","芯","牢","叛","蝕","奧","鳴","嶺","羊","憑","串","塘","繪","酵","融","盆","錫","廟","籌","凍","輔","攝","襲","筋","拒","僚","旱","鉀","鳥","漆","沈","眉","疏","添","棒","穗","硝","韓","逼","扭","僑","涼","挺","碗","栽","炒","杯","患","餾","勸","豪","遼","勃","鴻","旦","吏","拜","狗","埋","輥","掩","飲","搬","罵","辭","勾","扣","估","蔣","絨","霧","丈","朵","姆","擬","宇","輯","陝","雕","償","蓄","崇","剪","倡","廳","咬","駛","薯","刷","斥","番","賦","奉","佛","澆","漫","曼","扇","鈣","桃","扶","仔","返","俗","虧","腔","鞋","棱","覆","框","悄","叔","撞","騙","勘","旺","沸","孤","吐","孟","渠","屈","疾","妙","惜","仰","狠","脹","諧","拋","黴","桑","崗","嘛","衰","盜","滲","臟","賴","湧","甜","曹","閱","肌","哩","厲","烴","緯","毅","昨","偽","症","煮","嘆","釘","搭","莖","籠","酷","偷","弓","錐","恆","傑","坑","鼻","翼","綸","敘","獄","逮","罐","絡","棚","抑","膨","蔬","寺","驟","穆","冶","枯","冊","屍","凸","紳","坯","犧","焰","轟","欣","晉","瘦","禦","錠","錦","喪","旬","鍛","壟","搜","撲","邀","亭","酯","邁","舒","脆","酶","閒","憂","酚","頑","羽","漲","卸","仗","陪","闢","懲","杭","姚","肚","捉","飄","漂","昆","欺","吾","郎","烷","汁","呵","飾","蕭","雅","郵","遷","燕","撒","姻","赴","宴","煩","債","帳","斑","鈴","旨","醇","董","餅","雛","姿","拌","傅","腹","妥","揉","賢","拆","歪","葡","胺","丟","浩","徽","昂","墊","擋","覽","貪","慰","繳","汪","慌","馮","諾","姜","誼","兇","劣","誣","耀","昏","躺","盈","騎","喬","溪","叢","盧","抹","悶","諮","刮","駕","纜","悟","摘","鉺","擲","頗","幻","柄","惠","慘","佳","仇","臘","窩","滌","劍","瞧","堡","潑","蔥","罩","霍","撈","胎","蒼","濱","倆","捅","湘","砍","霞","邵","萄","瘋","淮","遂","熊","糞","烘","宿","檔","戈","駁","嫂","裕","徙","箭","捐","腸","撐","曬","辨","殿","蓮","攤","攪","醬","屏","疫","哀","蔡","堵","沫","皺","暢","疊","閣","萊","敲","轄","鉤","痕","壩","巷","餓","禍","丘","玄","溜","曰","邏","彭","嘗","卿","妨","艇","吞","韋","怨","矮","歇"]["abdikace","abeceda","adresa","agrese","akce","aktovka","alej","alkohol","amputace","ananas","andulka","anekdota","anketa","antika","anulovat","archa","arogance","asfalt","asistent","aspirace","astma","astronom","atlas","atletika","atol","autobus","azyl","babka","bachor","bacil","baculka","badatel","bageta","bagr","bahno","bakterie","balada","baletka","balkon","balonek","balvan","balza","bambus","bankomat","barbar","baret","barman","baroko","barva","baterka","batoh","bavlna","bazalka","bazilika","bazuka","bedna","beran","beseda","bestie","beton","bezinka","bezmoc","beztak","bicykl","bidlo","biftek","bikiny","bilance","biograf","biolog","bitva","bizon","blahobyt","blatouch","blecha","bledule","blesk","blikat","blizna","blokovat","bloudit","blud","bobek","bobr","bodlina","bodnout","bohatost","bojkot","bojovat","bokorys","bolest","borec","borovice","bota","boubel","bouchat","bouda","boule","bourat","boxer","bradavka","brambora","branka","bratr","brepta","briketa","brko","brloh","bronz","broskev","brunetka","brusinka","brzda","brzy","bublina","bubnovat","buchta","buditel","budka","budova","bufet","bujarost","bukvice","buldok","bulva","bunda","bunkr","burza","butik","buvol","buzola","bydlet","bylina","bytovka","bzukot","capart","carevna","cedr","cedule","cejch","cejn","cela","celer","celkem","celnice","cenina","cennost","cenovka","centrum","cenzor","cestopis","cetka","chalupa","chapadlo","charita","chata","chechtat","chemie","chichot","chirurg","chlad","chleba","chlubit","chmel","chmura","chobot","chochol","chodba","cholera","chomout","chopit","choroba","chov","chrapot","chrlit","chrt","chrup","chtivost","chudina","chutnat","chvat","chvilka","chvost","chyba","chystat","chytit","cibule","cigareta","cihelna","cihla","cinkot","cirkus","cisterna","citace","citrus","cizinec","cizost","clona","cokoliv","couvat","ctitel","ctnost","cudnost","cuketa","cukr","cupot","cvaknout","cval","cvik","cvrkot","cyklista","daleko","dareba","datel","datum","dcera","debata","dechovka","decibel","deficit","deflace","dekl","dekret","demokrat","deprese","derby","deska","detektiv","dikobraz","diktovat","dioda","diplom","disk","displej","divadlo","divoch","dlaha","dlouho","dluhopis","dnes","dobro","dobytek","docent","dochutit","dodnes","dohled","dohoda","dohra","dojem","dojnice","doklad","dokola","doktor","dokument","dolar","doleva","dolina","doma","dominant","domluvit","domov","donutit","dopad","dopis","doplnit","doposud","doprovod","dopustit","dorazit","dorost","dort","dosah","doslov","dostatek","dosud","dosyta","dotaz","dotek","dotknout","doufat","doutnat","dovozce","dozadu","doznat","dozorce","drahota","drak","dramatik","dravec","draze","drdol","drobnost","drogerie","drozd","drsnost","drtit","drzost","duben","duchovno","dudek","duha","duhovka","dusit","dusno","dutost","dvojice","dvorec","dynamit","ekolog","ekonomie","elektron","elipsa","email","emise","emoce","empatie","epizoda","epocha","epopej","epos","esej","esence","eskorta","eskymo","etiketa","euforie","evoluce","exekuce","exkurze","expedice","exploze","export","extrakt","facka","fajfka","fakulta","fanatik","fantazie","farmacie","favorit","fazole","federace","fejeton","fenka","fialka","figurant","filozof","filtr","finance","finta","fixace","fjord","flanel","flirt","flotila","fond","fosfor","fotbal","fotka","foton","frakce","freska","fronta","fukar","funkce","fyzika","galeje","garant","genetika","geolog","gilotina","glazura","glejt","golem","golfista","gotika","graf","gramofon","granule","grep","gril","grog","groteska","guma","hadice","hadr","hala","halenka","hanba","hanopis","harfa","harpuna","havran","hebkost","hejkal","hejno","hejtman","hektar","helma","hematom","herec","herna","heslo","hezky","historik","hladovka","hlasivky","hlava","hledat","hlen","hlodavec","hloh","hloupost","hltat","hlubina","hluchota","hmat","hmota","hmyz","hnis","hnojivo","hnout","hoblina","hoboj","hoch","hodiny","hodlat","hodnota","hodovat","hojnost","hokej","holinka","holka","holub","homole","honitba","honorace","horal","horda","horizont","horko","horlivec","hormon","hornina","horoskop","horstvo","hospoda","hostina","hotovost","houba","houf","houpat","houska","hovor","hradba","hranice","hravost","hrazda","hrbolek","hrdina","hrdlo","hrdost","hrnek","hrobka","hromada","hrot","hrouda","hrozen","hrstka","hrubost","hryzat","hubenost","hubnout","hudba","hukot","humr","husita","hustota","hvozd","hybnost","hydrant","hygiena","hymna","hysterik","idylka","ihned","ikona","iluze","imunita","infekce","inflace","inkaso","inovace","inspekce","internet","invalida","investor","inzerce","ironie","jablko","jachta","jahoda","jakmile","jakost","jalovec","jantar","jarmark","jaro","jasan","jasno","jatka","javor","jazyk","jedinec","jedle","jednatel","jehlan","jekot","jelen","jelito","jemnost","jenom","jepice","jeseter","jevit","jezdec","jezero","jinak","jindy","jinoch","jiskra","jistota","jitrnice","jizva","jmenovat","jogurt","jurta","kabaret","kabel","kabinet","kachna","kadet","kadidlo","kahan","kajak","kajuta","kakao","kaktus","kalamita","kalhoty","kalibr","kalnost","kamera","kamkoliv","kamna","kanibal","kanoe","kantor","kapalina","kapela","kapitola","kapka","kaple","kapota","kapr","kapusta","kapybara","karamel","karotka","karton","kasa","katalog","katedra","kauce","kauza","kavalec","kazajka","kazeta","kazivost","kdekoliv","kdesi","kedluben","kemp","keramika","kino","klacek","kladivo","klam","klapot","klasika","klaun","klec","klenba","klepat","klesnout","klid","klima","klisna","klobouk","klokan","klopa","kloub","klubovna","klusat","kluzkost","kmen","kmitat","kmotr","kniha","knot","koalice","koberec","kobka","kobliha","kobyla","kocour","kohout","kojenec","kokos","koktejl","kolaps","koleda","kolize","kolo","komando","kometa","komik","komnata","komora","kompas","komunita","konat","koncept","kondice","konec","konfese","kongres","konina","konkurs","kontakt","konzerva","kopanec","kopie","kopnout","koprovka","korbel","korektor","kormidlo","koroptev","korpus","koruna","koryto","korzet","kosatec","kostka","kotel","kotleta","kotoul","koukat","koupelna","kousek","kouzlo","kovboj","koza","kozoroh","krabice","krach","krajina","kralovat","krasopis","kravata","kredit","krejcar","kresba","kreveta","kriket","kritik","krize","krkavec","krmelec","krmivo","krocan","krok","kronika","kropit","kroupa","krovka","krtek","kruhadlo","krupice","krutost","krvinka","krychle","krypta","krystal","kryt","kudlanka","kufr","kujnost","kukla","kulajda","kulich","kulka","kulomet","kultura","kuna","kupodivu","kurt","kurzor","kutil","kvalita","kvasinka","kvestor","kynolog","kyselina","kytara","kytice","kytka","kytovec","kyvadlo","labrador","lachtan","ladnost","laik","lakomec","lamela","lampa","lanovka","lasice","laso","lastura","latinka","lavina","lebka","leckdy","leden","lednice","ledovka","ledvina","legenda","legie","legrace","lehce","lehkost","lehnout","lektvar","lenochod","lentilka","lepenka","lepidlo","letadlo","letec","letmo","letokruh","levhart","levitace","levobok","libra","lichotka","lidojed","lidskost","lihovina","lijavec","lilek","limetka","linie","linka","linoleum","listopad","litina","litovat","lobista","lodivod","logika","logoped","lokalita","loket","lomcovat","lopata","lopuch","lord","losos","lotr","loudal","louh","louka","louskat","lovec","lstivost","lucerna","lucifer","lump","lusk","lustrace","lvice","lyra","lyrika","lysina","madam","madlo","magistr","mahagon","majetek","majitel","majorita","makak","makovice","makrela","malba","malina","malovat","malvice","maminka","mandle","manko","marnost","masakr","maskot","masopust","matice","matrika","maturita","mazanec","mazivo","mazlit","mazurka","mdloba","mechanik","meditace","medovina","melasa","meloun","mentolka","metla","metoda","metr","mezera","migrace","mihnout","mihule","mikina","mikrofon","milenec","milimetr","milost","mimika","mincovna","minibar","minomet","minulost","miska","mistr","mixovat","mladost","mlha","mlhovina","mlok","mlsat","mluvit","mnich","mnohem","mobil","mocnost","modelka","modlitba","mohyla","mokro","molekula","momentka","monarcha","monokl","monstrum","montovat","monzun","mosaz","moskyt","most","motivace","motorka","motyka","moucha","moudrost","mozaika","mozek","mozol","mramor","mravenec","mrkev","mrtvola","mrzet","mrzutost","mstitel","mudrc","muflon","mulat","mumie","munice","muset","mutace","muzeum","muzikant","myslivec","mzda","nabourat","nachytat","nadace","nadbytek","nadhoz","nadobro","nadpis","nahlas","nahnat","nahodile","nahradit","naivita","najednou","najisto","najmout","naklonit","nakonec","nakrmit","nalevo","namazat","namluvit","nanometr","naoko","naopak","naostro","napadat","napevno","naplnit","napnout","naposled","naprosto","narodit","naruby","narychlo","nasadit","nasekat","naslepo","nastat","natolik","navenek","navrch","navzdory","nazvat","nebe","nechat","necky","nedaleko","nedbat","neduh","negace","nehet","nehoda","nejen","nejprve","neklid","nelibost","nemilost","nemoc","neochota","neonka","nepokoj","nerost","nerv","nesmysl","nesoulad","netvor","neuron","nevina","nezvykle","nicota","nijak","nikam","nikdy","nikl","nikterak","nitro","nocleh","nohavice","nominace","nora","norek","nositel","nosnost","nouze","noviny","novota","nozdra","nuda","nudle","nuget","nutit","nutnost","nutrie","nymfa","obal","obarvit","obava","obdiv","obec","obehnat","obejmout","obezita","obhajoba","obilnice","objasnit","objekt","obklopit","oblast","oblek","obliba","obloha","obluda","obnos","obohatit","obojek","obout","obrazec","obrna","obruba","obrys","obsah","obsluha","obstarat","obuv","obvaz","obvinit","obvod","obvykle","obyvatel","obzor","ocas","ocel","ocenit","ochladit","ochota","ochrana","ocitnout","odboj","odbyt","odchod","odcizit","odebrat","odeslat","odevzdat","odezva","odhadce","odhodit","odjet","odjinud","odkaz","odkoupit","odliv","odluka","odmlka","odolnost","odpad","odpis","odplout","odpor","odpustit","odpykat","odrazka","odsoudit","odstup","odsun","odtok","odtud","odvaha","odveta","odvolat","odvracet","odznak","ofina","ofsajd","ohlas","ohnisko","ohrada","ohrozit","ohryzek","okap","okenice","oklika","okno","okouzlit","okovy","okrasa","okres","okrsek","okruh","okupant","okurka","okusit","olejnina","olizovat","omak","omeleta","omezit","omladina","omlouvat","omluva","omyl","onehdy","opakovat","opasek","operace","opice","opilost","opisovat","opora","opozice","opravdu","oproti","orbital","orchestr","orgie","orlice","orloj","ortel","osada","oschnout","osika","osivo","oslava","oslepit","oslnit","oslovit","osnova","osoba","osolit","ospalec","osten","ostraha","ostuda","ostych","osvojit","oteplit","otisk","otop","otrhat","otrlost","otrok","otruby","otvor","ovanout","ovar","oves","ovlivnit","ovoce","oxid","ozdoba","pachatel","pacient","padouch","pahorek","pakt","palanda","palec","palivo","paluba","pamflet","pamlsek","panenka","panika","panna","panovat","panstvo","pantofle","paprika","parketa","parodie","parta","paruka","paryba","paseka","pasivita","pastelka","patent","patrona","pavouk","pazneht","pazourek","pecka","pedagog","pejsek","peklo","peloton","penalta","pendrek","penze","periskop","pero","pestrost","petarda","petice","petrolej","pevnina","pexeso","pianista","piha","pijavice","pikle","piknik","pilina","pilnost","pilulka","pinzeta","pipeta","pisatel","pistole","pitevna","pivnice","pivovar","placenta","plakat","plamen","planeta","plastika","platit","plavidlo","plaz","plech","plemeno","plenta","ples","pletivo","plevel","plivat","plnit","plno","plocha","plodina","plomba","plout","pluk","plyn","pobavit","pobyt","pochod","pocit","poctivec","podat","podcenit","podepsat","podhled","podivit","podklad","podmanit","podnik","podoba","podpora","podraz","podstata","podvod","podzim","poezie","pohanka","pohnutka","pohovor","pohroma","pohyb","pointa","pojistka","pojmout","pokazit","pokles","pokoj","pokrok","pokuta","pokyn","poledne","polibek","polknout","poloha","polynom","pomalu","pominout","pomlka","pomoc","pomsta","pomyslet","ponechat","ponorka","ponurost","popadat","popel","popisek","poplach","poprosit","popsat","popud","poradce","porce","porod","porucha","poryv","posadit","posed","posila","poskok","poslanec","posoudit","pospolu","postava","posudek","posyp","potah","potkan","potlesk","potomek","potrava","potupa","potvora","poukaz","pouto","pouzdro","povaha","povidla","povlak","povoz","povrch","povstat","povyk","povzdech","pozdrav","pozemek","poznatek","pozor","pozvat","pracovat","prahory","praktika","prales","praotec","praporek","prase","pravda","princip","prkno","probudit","procento","prodej","profese","prohra","projekt","prolomit","promile","pronikat","propad","prorok","prosba","proton","proutek","provaz","prskavka","prsten","prudkost","prut","prvek","prvohory","psanec","psovod","pstruh","ptactvo","puberta","puch","pudl","pukavec","puklina","pukrle","pult","pumpa","punc","pupen","pusa","pusinka","pustina","putovat","putyka","pyramida","pysk","pytel","racek","rachot","radiace","radnice","radon","raft","ragby","raketa","rakovina","rameno","rampouch","rande","rarach","rarita","rasovna","rastr","ratolest","razance","razidlo","reagovat","reakce","recept","redaktor","referent","reflex","rejnok","reklama","rekord","rekrut","rektor","reputace","revize","revma","revolver","rezerva","riskovat","riziko","robotika","rodokmen","rohovka","rokle","rokoko","romaneto","ropovod","ropucha","rorejs","rosol","rostlina","rotmistr","rotoped","rotunda","roubenka","roucho","roup","roura","rovina","rovnice","rozbor","rozchod","rozdat","rozeznat","rozhodce","rozinka","rozjezd","rozkaz","rozloha","rozmar","rozpad","rozruch","rozsah","roztok","rozum","rozvod","rubrika","ruchadlo","rukavice","rukopis","ryba","rybolov","rychlost","rydlo","rypadlo","rytina","ryzost","sadista","sahat","sako","samec","samizdat","samota","sanitka","sardinka","sasanka","satelit","sazba","sazenice","sbor","schovat","sebranka","secese","sedadlo","sediment","sedlo","sehnat","sejmout","sekera","sekta","sekunda","sekvoje","semeno","seno","servis","sesadit","seshora","seskok","seslat","sestra","sesuv","sesypat","setba","setina","setkat","setnout","setrvat","sever","seznam","shoda","shrnout","sifon","silnice","sirka","sirotek","sirup","situace","skafandr","skalisko","skanzen","skaut","skeptik","skica","skladba","sklenice","sklo","skluz","skoba","skokan","skoro","skripta","skrz","skupina","skvost","skvrna","slabika","sladidlo","slanina","slast","slavnost","sledovat","slepec","sleva","slezina","slib","slina","sliznice","slon","sloupek","slovo","sluch","sluha","slunce","slupka","slza","smaragd","smetana","smilstvo","smlouva","smog","smrad","smrk","smrtka","smutek","smysl","snad","snaha","snob","sobota","socha","sodovka","sokol","sopka","sotva","souboj","soucit","soudce","souhlas","soulad","soumrak","souprava","soused","soutok","souviset","spalovna","spasitel","spis","splav","spodek","spojenec","spolu","sponzor","spornost","spousta","sprcha","spustit","sranda","sraz","srdce","srna","srnec","srovnat","srpen","srst","srub","stanice","starosta","statika","stavba","stehno","stezka","stodola","stolek","stopa","storno","stoupat","strach","stres","strhnout","strom","struna","studna","stupnice","stvol","styk","subjekt","subtropy","suchar","sudost","sukno","sundat","sunout","surikata","surovina","svah","svalstvo","svetr","svatba","svazek","svisle","svitek","svoboda","svodidlo","svorka","svrab","sykavka","sykot","synek","synovec","sypat","sypkost","syrovost","sysel","sytost","tabletka","tabule","tahoun","tajemno","tajfun","tajga","tajit","tajnost","taktika","tamhle","tampon","tancovat","tanec","tanker","tapeta","tavenina","tazatel","technika","tehdy","tekutina","telefon","temnota","tendence","tenista","tenor","teplota","tepna","teprve","terapie","termoska","textil","ticho","tiskopis","titulek","tkadlec","tkanina","tlapka","tleskat","tlukot","tlupa","tmel","toaleta","topinka","topol","torzo","touha","toulec","tradice","traktor","tramp","trasa","traverza","trefit","trest","trezor","trhavina","trhlina","trochu","trojice","troska","trouba","trpce","trpitel","trpkost","trubec","truchlit","truhlice","trus","trvat","tudy","tuhnout","tuhost","tundra","turista","turnaj","tuzemsko","tvaroh","tvorba","tvrdost","tvrz","tygr","tykev","ubohost","uboze","ubrat","ubrousek","ubrus","ubytovna","ucho","uctivost","udivit","uhradit","ujednat","ujistit","ujmout","ukazatel","uklidnit","uklonit","ukotvit","ukrojit","ulice","ulita","ulovit","umyvadlo","unavit","uniforma","uniknout","upadnout","uplatnit","uplynout","upoutat","upravit","uran","urazit","usednout","usilovat","usmrtit","usnadnit","usnout","usoudit","ustlat","ustrnout","utahovat","utkat","utlumit","utonout","utopenec","utrousit","uvalit","uvolnit","uvozovka","uzdravit","uzel","uzenina","uzlina","uznat","vagon","valcha","valoun","vana","vandal","vanilka","varan","varhany","varovat","vcelku","vchod","vdova","vedro","vegetace","vejce","velbloud","veletrh","velitel","velmoc","velryba","venkov","veranda","verze","veselka","veskrze","vesnice","vespodu","vesta","veterina","veverka","vibrace","vichr","videohra","vidina","vidle","vila","vinice","viset","vitalita","vize","vizitka","vjezd","vklad","vkus","vlajka","vlak","vlasec","vlevo","vlhkost","vliv","vlnovka","vloupat","vnucovat","vnuk","voda","vodivost","vodoznak","vodstvo","vojensky","vojna","vojsko","volant","volba","volit","volno","voskovka","vozidlo","vozovna","vpravo","vrabec","vracet","vrah","vrata","vrba","vrcholek","vrhat","vrstva","vrtule","vsadit","vstoupit","vstup","vtip","vybavit","vybrat","vychovat","vydat","vydra","vyfotit","vyhledat","vyhnout","vyhodit","vyhradit","vyhubit","vyjasnit","vyjet","vyjmout","vyklopit","vykonat","vylekat","vymazat","vymezit","vymizet","vymyslet","vynechat","vynikat","vynutit","vypadat","vyplatit","vypravit","vypustit","vyrazit","vyrovnat","vyrvat","vyslovit","vysoko","vystavit","vysunout","vysypat","vytasit","vytesat","vytratit","vyvinout","vyvolat","vyvrhel","vyzdobit","vyznat","vzadu","vzbudit","vzchopit","vzdor","vzduch","vzdychat","vzestup","vzhledem","vzkaz","vzlykat","vznik","vzorek","vzpoura","vztah","vztek","xylofon","zabrat","zabydlet","zachovat","zadarmo","zadusit","zafoukat","zahltit","zahodit","zahrada","zahynout","zajatec","zajet","zajistit","zaklepat","zakoupit","zalepit","zamezit","zamotat","zamyslet","zanechat","zanikat","zaplatit","zapojit","zapsat","zarazit","zastavit","zasunout","zatajit","zatemnit","zatknout","zaujmout","zavalit","zavelet","zavinit","zavolat","zavrtat","zazvonit","zbavit","zbrusu","zbudovat","zbytek","zdaleka","zdarma","zdatnost","zdivo","zdobit","zdroj","zdvih","zdymadlo","zelenina","zeman","zemina","zeptat","zezadu","zezdola","zhatit","zhltnout","zhluboka","zhotovit","zhruba","zima","zimnice","zjemnit","zklamat","zkoumat","zkratka","zkumavka","zlato","zlehka","zloba","zlom","zlost","zlozvyk","zmapovat","zmar","zmatek","zmije","zmizet","zmocnit","zmodrat","zmrzlina","zmutovat","znak","znalost","znamenat","znovu","zobrazit","zotavit","zoubek","zoufale","zplodit","zpomalit","zprava","zprostit","zprudka","zprvu","zrada","zranit","zrcadlo","zrnitost","zrno","zrovna","zrychlit","zrzavost","zticha","ztratit","zubovina","zubr","zvednout","zvenku","zvesela","zvon","zvrat","zvukovod","zvyk"]["abandon","ability","able","about","above","absent","absorb","abstract","absurd","abuse","access","accident","account","accuse","achieve","acid","acoustic","acquire","across","act","action","actor","actress","actual","adapt","add","addict","address","adjust","admit","adult","advance","advice","aerobic","affair","afford","afraid","again","age","agent","agree","ahead","aim","air","airport","aisle","alarm","album","alcohol","alert","alien","all","alley","allow","almost","alone","alpha","already","also","alter","always","amateur","amazing","among","amount","amused","analyst","anchor","ancient","anger","angle","angry","animal","ankle","announce","annual","another","answer","antenna","antique","anxiety","any","apart","apology","appear","apple","approve","april","arch","arctic","area","arena","argue","arm","armed","armor","army","around","arrange","arrest","arrive","arrow","art","artefact","artist","artwork","ask","aspect","assault","asset","assist","assume","asthma","athlete","atom","attack","attend","attitude","attract","auction","audit","august","aunt","author","auto","autumn","average","avocado","avoid","awake","aware","away","awesome","awful","awkward","axis","baby","bachelor","bacon","badge","bag","balance","balcony","ball","bamboo","banana","banner","bar","barely","bargain","barrel","base","basic","basket","battle","beach","bean","beauty","because","become","beef","before","begin","behave","behind","believe","below","belt","bench","benefit","best","betray","better","between","beyond","bicycle","bid","bike","bind","biology","bird","birth","bitter","black","blade","blame","blanket","blast","bleak","bless","blind","blood","blossom","blouse","blue","blur","blush","board","boat","body","boil","bomb","bone","bonus","book","boost","border","boring","borrow","boss","bottom","bounce","box","boy","bracket","brain","brand","brass","brave","bread","breeze","brick","bridge","brief","bright","bring","brisk","broccoli","broken","bronze","broom","brother","brown","brush","bubble","buddy","budget","buffalo","build","bulb","bulk","bullet","bundle","bunker","burden","burger","burst","bus","business","busy","butter","buyer","buzz","cabbage","cabin","cable","cactus","cage","cake","call","calm","camera","camp","can","canal","cancel","candy","cannon","canoe","canvas","canyon","capable","capital","captain","car","carbon","card","cargo","carpet","carry","cart","case","cash","casino","castle","casual","cat","catalog","catch","category","cattle","caught","cause","caution","cave","ceiling","celery","cement","census","century","cereal","certain","chair","chalk","champion","change","chaos","chapter","charge","chase","chat","cheap","check","cheese","chef","cherry","chest","chicken","chief","child","chimney","choice","choose","chronic","chuckle","chunk","churn","cigar","cinnamon","circle","citizen","city","civil","claim","clap","clarify","claw","clay","clean","clerk","clever","click","client","cliff","climb","clinic","clip","clock","clog","close","cloth","cloud","clown","club","clump","cluster","clutch","coach","coast","coconut","code","coffee","coil","coin","collect","color","column","combine","come","comfort","comic","common","company","concert","conduct","confirm","congress","connect","consider","control","convince","cook","cool","copper","copy","coral","core","corn","correct","cost","cotton","couch","country","couple","course","cousin","cover","coyote","crack","cradle","craft","cram","crane","crash","crater","crawl","crazy","cream","credit","creek","crew","cricket","crime","crisp","critic","crop","cross","crouch","crowd","crucial","cruel","cruise","crumble","crunch","crush","cry","crystal","cube","culture","cup","cupboard","curious","current","curtain","curve","cushion","custom","cute","cycle","dad","damage","damp","dance","danger","daring","dash","daughter","dawn","day","deal","debate","debris","decade","december","decide","decline","decorate","decrease","deer","defense","define","defy","degree","delay","deliver","demand","demise","denial","dentist","deny","depart","depend","deposit","depth","deputy","derive","describe","desert","design","desk","despair","destroy","detail","detect","develop","device","devote","diagram","dial","diamond","diary","dice","diesel","diet","differ","digital","dignity","dilemma","dinner","dinosaur","direct","dirt","disagree","discover","disease","dish","dismiss","disorder","display","distance","divert","divide","divorce","dizzy","doctor","document","dog","doll","dolphin","domain","donate","donkey","donor","door","dose","double","dove","draft","dragon","drama","drastic","draw","dream","dress","drift","drill","drink","drip","drive","drop","drum","dry","duck","dumb","dune","during","dust","dutch","duty","dwarf","dynamic","eager","eagle","early","earn","earth","easily","east","easy","echo","ecology","economy","edge","edit","educate","effort","egg","eight","either","elbow","elder","electric","elegant","element","elephant","elevator","elite","else","embark","embody","embrace","emerge","emotion","employ","empower","empty","enable","enact","end","endless","endorse","enemy","energy","enforce","engage","engine","enhance","enjoy","enlist","enough","enrich","enroll","ensure","enter","entire","entry","envelope","episode","equal","equip","era","erase","erode","erosion","error","erupt","escape","essay","essence","estate","eternal","ethics","evidence","evil","evoke","evolve","exact","example","excess","exchange","excite","exclude","excuse","execute","exercise","exhaust","exhibit","exile","exist","exit","exotic","expand","expect","expire","explain","expose","express","extend","extra","eye","eyebrow","fabric","face","faculty","fade","faint","faith","fall","false","fame","family","famous","fan","fancy","fantasy","farm","fashion","fat","fatal","father","fatigue","fault","favorite","feature","february","federal","fee","feed","feel","female","fence","festival","fetch","fever","few","fiber","fiction","field","figure","file","film","filter","final","find","fine","finger","finish","fire","firm","first","fiscal","fish","fit","fitness","fix","flag","flame","flash","flat","flavor","flee","flight","flip","float","flock","floor","flower","fluid","flush","fly","foam","focus","fog","foil","fold","follow","food","foot","force","forest","forget","fork","fortune","forum","forward","fossil","foster","found","fox","fragile","frame","frequent","fresh","friend","fringe","frog","front","frost","frown","frozen","fruit","fuel","fun","funny","furnace","fury","future","gadget","gain","galaxy","gallery","game","gap","garage","garbage","garden","garlic","garment","gas","gasp","gate","gather","gauge","gaze","general","genius","genre","gentle","genuine","gesture","ghost","giant","gift","giggle","ginger","giraffe","girl","give","glad","glance","glare","glass","glide","glimpse","globe","gloom","glory","glove","glow","glue","goat","goddess","gold","good","goose","gorilla","gospel","gossip","govern","gown","grab","grace","grain","grant","grape","grass","gravity","great","green","grid","grief","grit","grocery","group","grow","grunt","guard","guess","guide","guilt","guitar","gun","gym","habit","hair","half","hammer","hamster","hand","happy","harbor","hard","harsh","harvest","hat","have","hawk","hazard","head","health","heart","heavy","hedgehog","height","hello","helmet","help","hen","hero","hidden","high","hill","hint","hip","hire","history","hobby","hockey","hold","hole","holiday","hollow","home","honey","hood","hope","horn","horror","horse","hospital","host","hotel","hour","hover","hub","huge","human","humble","humor","hundred","hungry","hunt","hurdle","hurry","hurt","husband","hybrid","ice","icon","idea","identify","idle","ignore","ill","illegal","illness","image","imitate","immense","immune","impact","impose","improve","impulse","inch","include","income","increase","index","indicate","indoor","industry","infant","inflict","inform","inhale","inherit","initial","inject","injury","inmate","inner","innocent","input","inquiry","insane","insect","inside","inspire","install","intact","interest","into","invest","invite","involve","iron","island","isolate","issue","item","ivory","jacket","jaguar","jar","jazz","jealous","jeans","jelly","jewel","job","join","joke","journey","joy","judge","juice","jump","jungle","junior","junk","just","kangaroo","keen","keep","ketchup","key","kick","kid","kidney","kind","kingdom","kiss","kit","kitchen","kite","kitten","kiwi","knee","knife","knock","know","lab","label","labor","ladder","lady","lake","lamp","language","laptop","large","later","latin","laugh","laundry","lava","law","lawn","lawsuit","layer","lazy","leader","leaf","learn","leave","lecture","left","leg","legal","legend","leisure","lemon","lend","length","lens","leopard","lesson","letter","level","liar","liberty","library","license","life","lift","light","like","limb","limit","link","lion","liquid","list","little","live","lizard","load","loan","lobster","local","lock","logic","lonely","long","loop","lottery","loud","lounge","love","loyal","lucky","luggage","lumber","lunar","lunch","luxury","lyrics","machine","mad","magic","magnet","maid","mail","main","major","make","mammal","man","manage","mandate","mango","mansion","manual","maple","marble","march","margin","marine","market","marriage","mask","mass","master","match","material","math","matrix","matter","maximum","maze","meadow","mean","measure","meat","mechanic","medal","media","melody","melt","member","memory","mention","menu","mercy","merge","merit","merry","mesh","message","metal","method","middle","midnight","milk","million","mimic","mind","minimum","minor","minute","miracle","mirror","misery","miss","mistake","mix","mixed","mixture","mobile","model","modify","mom","moment","monitor","monkey","monster","month","moon","moral","more","morning","mosquito","mother","motion","motor","mountain","mouse","move","movie","much","muffin","mule","multiply","muscle","museum","mushroom","music","must","mutual","myself","mystery","myth","naive","name","napkin","narrow","nasty","nation","nature","near","neck","need","negative","neglect","neither","nephew","nerve","nest","net","network","neutral","never","news","next","nice","night","noble","noise","nominee","noodle","normal","north","nose","notable","note","nothing","notice","novel","now","nuclear","number","nurse","nut","oak","obey","object","oblige","obscure","observe","obtain","obvious","occur","ocean","october","odor","off","offer","office","often","oil","okay","old","olive","olympic","omit","once","one","onion","online","only","open","opera","opinion","oppose","option","orange","orbit","orchard","order","ordinary","organ","orient","original","orphan","ostrich","other","outdoor","outer","output","outside","oval","oven","over","own","owner","oxygen","oyster","ozone","pact","paddle","page","pair","palace","palm","panda","panel","panic","panther","paper","parade","parent","park","parrot","party","pass","patch","path","patient","patrol","pattern","pause","pave","payment","peace","peanut","pear","peasant","pelican","pen","penalty","pencil","people","pepper","perfect","permit","person","pet","phone","photo","phrase","physical","piano","picnic","picture","piece","pig","pigeon","pill","pilot","pink","pioneer","pipe","pistol","pitch","pizza","place","planet","plastic","plate","play","please","pledge","pluck","plug","plunge","poem","poet","point","polar","pole","police","pond","pony","pool","popular","portion","position","possible","post","potato","pottery","poverty","powder","power","practice","praise","predict","prefer","prepare","present","pretty","prevent","price","pride","primary","print","priority","prison","private","prize","problem","process","produce","profit","program","project","promote","proof","property","prosper","protect","proud","provide","public","pudding","pull","pulp","pulse","pumpkin","punch","pupil","puppy","purchase","purity","purpose","purse","push","put","puzzle","pyramid","quality","quantum","quarter","question","quick","quit","quiz","quote","rabbit","raccoon","race","rack","radar","radio","rail","rain","raise","rally","ramp","ranch","random","range","rapid","rare","rate","rather","raven","raw","razor","ready","real","reason","rebel","rebuild","recall","receive","recipe","record","recycle","reduce","reflect","reform","refuse","region","regret","regular","reject","relax","release","relief","rely","remain","remember","remind","remove","render","renew","rent","reopen","repair","repeat","replace","report","require","rescue","resemble","resist","resource","response","result","retire","retreat","return","reunion","reveal","review","reward","rhythm","rib","ribbon","rice","rich","ride","ridge","rifle","right","rigid","ring","riot","ripple","risk","ritual","rival","river","road","roast","robot","robust","rocket","romance","roof","rookie","room","rose","rotate","rough","round","route","royal","rubber","rude","rug","rule","run","runway","rural","sad","saddle","sadness","safe","sail","salad","salmon","salon","salt","salute","same","sample","sand","satisfy","satoshi","sauce","sausage","save","say","scale","scan","scare","scatter","scene","scheme","school","science","scissors","scorpion","scout","scrap","screen","script","scrub","sea","search","season","seat","second","secret","section","security","seed","seek","segment","select","sell","seminar","senior","sense","sentence","series","service","session","settle","setup","seven","shadow","shaft","shallow","share","shed","shell","sheriff","shield","shift","shine","ship","shiver","shock","shoe","shoot","shop","short","shoulder","shove","shrimp","shrug","shuffle","shy","sibling","sick","side","siege","sight","sign","silent","silk","silly","silver","similar","simple","since","sing","siren","sister","situate","six","size","skate","sketch","ski","skill","skin","skirt","skull","slab","slam","sleep","slender","slice","slide","slight","slim","slogan","slot","slow","slush","small","smart","smile","smoke","smooth","snack","snake","snap","sniff","snow","soap","soccer","social","sock","soda","soft","solar","soldier","solid","solution","solve","someone","song","soon","sorry","sort","soul","sound","soup","source","south","space","spare","spatial","spawn","speak","special","speed","spell","spend","sphere","spice","spider","spike","spin","spirit","split","spoil","sponsor","spoon","sport","spot","spray","spread","spring","spy","square","squeeze","squirrel","stable","stadium","staff","stage","stairs","stamp","stand","start","state","stay","steak","steel","stem","step","stereo","stick","still","sting","stock","stomach","stone","stool","story","stove","strategy","street","strike","strong","struggle","student","stuff","stumble","style","subject","submit","subway","success","such","sudden","suffer","sugar","suggest","suit","summer","sun","sunny","sunset","super","supply","supreme","sure","surface","surge","surprise","surround","survey","suspect","sustain","swallow","swamp","swap","swarm","swear","sweet","swift","swim","swing","switch","sword","symbol","symptom","syrup","system","table","tackle","tag","tail","talent","talk","tank","tape","target","task","taste","tattoo","taxi","teach","team","tell","ten","tenant","tennis","tent","term","test","text","thank","that","theme","then","theory","there","they","thing","this","thought","three","thrive","throw","thumb","thunder","ticket","tide","tiger","tilt","timber","time","tiny","tip","tired","tissue","title","toast","tobacco","today","toddler","toe","together","toilet","token","tomato","tomorrow","tone","tongue","tonight","tool","tooth","top","topic","topple","torch","tornado","tortoise","toss","total","tourist","toward","tower","town","toy","track","trade","traffic","tragic","train","transfer","trap","trash","travel","tray","treat","tree","trend","trial","tribe","trick","trigger","trim","trip","trophy","trouble","truck","true","truly","trumpet","trust","truth","try","tube","tuition","tumble","tuna","tunnel","turkey","turn","turtle","twelve","twenty","twice","twin","twist","two","type","typical","ugly","umbrella","unable","unaware","uncle","uncover","under","undo","unfair","unfold","unhappy","uniform","unique","unit","universe","unknown","unlock","until","unusual","unveil","update","upgrade","uphold","upon","upper","upset","urban","urge","usage","use","used","useful","useless","usual","utility","vacant","vacuum","vague","valid","valley","valve","van","vanish","vapor","various","vast","vault","vehicle","velvet","vendor","venture","venue","verb","verify","version","very","vessel","veteran","viable","vibrant","vicious","victory","video","view","village","vintage","violin","virtual","virus","visa","visit","visual","vital","vivid","vocal","voice","void","volcano","volume","vote","voyage","wage","wagon","wait","walk","wall","walnut","want","warfare","warm","warrior","wash","wasp","waste","water","wave","way","wealth","weapon","wear","weasel","weather","web","wedding","weekend","weird","welcome","west","wet","whale","what","wheat","wheel","when","where","whip","whisper","wide","width","wife","wild","will","win","window","wine","wing","wink","winner","winter","wire","wisdom","wise","wish","witness","wolf","woman","wonder","wood","wool","word","work","world","worry","worth","wrap","wreck","wrestle","wrist","write","wrong","yard","year","yellow","you","young","youth","zebra","zero","zone","zoo"]["abaisser","abandon","abdiquer","abeille","abolir","aborder","aboutir","aboyer","abrasif","abreuver","abriter","abroger","abrupt","absence","absolu","absurde","abusif","abyssal","académie","acajou","acarien","accabler","accepter","acclamer","accolade","accroche","accuser","acerbe","achat","acheter","aciduler","acier","acompte","acquérir","acronyme","acteur","actif","actuel","adepte","adéquat","adhésif","adjectif","adjuger","admettre","admirer","adopter","adorer","adoucir","adresse","adroit","adulte","adverbe","aérer","aéronef","affaire","affecter","affiche","affreux","affubler","agacer","agencer","agile","agiter","agrafer","agréable","agrume","aider","aiguille","ailier","aimable","aisance","ajouter","ajuster","alarmer","alchimie","alerte","algèbre","algue","aliéner","aliment","alléger","alliage","allouer","allumer","alourdir","alpaga","altesse","alvéole","amateur","ambigu","ambre","aménager","amertume","amidon","amiral","amorcer","amour","amovible","amphibie","ampleur","amusant","analyse","anaphore","anarchie","anatomie","ancien","anéantir","angle","angoisse","anguleux","animal","annexer","annonce","annuel","anodin","anomalie","anonyme","anormal","antenne","antidote","anxieux","apaiser","apéritif","aplanir","apologie","appareil","appeler","apporter","appuyer","aquarium","aqueduc","arbitre","arbuste","ardeur","ardoise","argent","arlequin","armature","armement","armoire","armure","arpenter","arracher","arriver","arroser","arsenic","artériel","article","aspect","asphalte","aspirer","assaut","asservir","assiette","associer","assurer","asticot","astre","astuce","atelier","atome","atrium","atroce","attaque","attentif","attirer","attraper","aubaine","auberge","audace","audible","augurer","aurore","automne","autruche","avaler","avancer","avarice","avenir","averse","aveugle","aviateur","avide","avion","aviser","avoine","avouer","avril","axial","axiome","badge","bafouer","bagage","baguette","baignade","balancer","balcon","baleine","balisage","bambin","bancaire","bandage","banlieue","bannière","banquier","barbier","baril","baron","barque","barrage","bassin","bastion","bataille","bateau","batterie","baudrier","bavarder","belette","bélier","belote","bénéfice","berceau","berger","berline","bermuda","besace","besogne","bétail","beurre","biberon","bicycle","bidule","bijou","bilan","bilingue","billard","binaire","biologie","biopsie","biotype","biscuit","bison","bistouri","bitume","bizarre","blafard","blague","blanchir","blessant","blinder","blond","bloquer","blouson","bobard","bobine","boire","boiser","bolide","bonbon","bondir","bonheur","bonifier","bonus","bordure","borne","botte","boucle","boueux","bougie","boulon","bouquin","bourse","boussole","boutique","boxeur","branche","brasier","brave","brebis","brèche","breuvage","bricoler","brigade","brillant","brioche","brique","brochure","broder","bronzer","brousse","broyeur","brume","brusque","brutal","bruyant","buffle","buisson","bulletin","bureau","burin","bustier","butiner","butoir","buvable","buvette","cabanon","cabine","cachette","cadeau","cadre","caféine","caillou","caisson","calculer","calepin","calibre","calmer","calomnie","calvaire","camarade","caméra","camion","campagne","canal","caneton","canon","cantine","canular","capable","caporal","caprice","capsule","capter","capuche","carabine","carbone","caresser","caribou","carnage","carotte","carreau","carton","cascade","casier","casque","cassure","causer","caution","cavalier","caverne","caviar","cédille","ceinture","céleste","cellule","cendrier","censurer","central","cercle","cérébral","cerise","cerner","cerveau","cesser","chagrin","chaise","chaleur","chambre","chance","chapitre","charbon","chasseur","chaton","chausson","chavirer","chemise","chenille","chéquier","chercher","cheval","chien","chiffre","chignon","chimère","chiot","chlorure","chocolat","choisir","chose","chouette","chrome","chute","cigare","cigogne","cimenter","cinéma","cintrer","circuler","cirer","cirque","citerne","citoyen","citron","civil","clairon","clameur","claquer","classe","clavier","client","cligner","climat","clivage","cloche","clonage","cloporte","cobalt","cobra","cocasse","cocotier","coder","codifier","coffre","cogner","cohésion","coiffer","coincer","colère","colibri","colline","colmater","colonel","combat","comédie","commande","compact","concert","conduire","confier","congeler","connoter","consonne","contact","convexe","copain","copie","corail","corbeau","cordage","corniche","corpus","correct","cortège","cosmique","costume","coton","coude","coupure","courage","couteau","couvrir","coyote","crabe","crainte","cravate","crayon","créature","créditer","crémeux","creuser","crevette","cribler","crier","cristal","critère","croire","croquer","crotale","crucial","cruel","crypter","cubique","cueillir","cuillère","cuisine","cuivre","culminer","cultiver","cumuler","cupide","curatif","curseur","cyanure","cycle","cylindre","cynique","daigner","damier","danger","danseur","dauphin","débattre","débiter","déborder","débrider","débutant","décaler","décembre","déchirer","décider","déclarer","décorer","décrire","décupler","dédale","déductif","déesse","défensif","défiler","défrayer","dégager","dégivrer","déglutir","dégrafer","déjeuner","délice","déloger","demander","demeurer","démolir","dénicher","dénouer","dentelle","dénuder","départ","dépenser","déphaser","déplacer","déposer","déranger","dérober","désastre","descente","désert","désigner","désobéir","dessiner","destrier","détacher","détester","détourer","détresse","devancer","devenir","deviner","devoir","diable","dialogue","diamant","dicter","différer","digérer","digital","digne","diluer","dimanche","diminuer","dioxyde","directif","diriger","discuter","disposer","dissiper","distance","divertir","diviser","docile","docteur","dogme","doigt","domaine","domicile","dompter","donateur","donjon","donner","dopamine","dortoir","dorure","dosage","doseur","dossier","dotation","douanier","double","douceur","douter","doyen","dragon","draper","dresser","dribbler","droiture","duperie","duplexe","durable","durcir","dynastie","éblouir","écarter","écharpe","échelle","éclairer","éclipse","éclore","écluse","école","économie","écorce","écouter","écraser","écrémer","écrivain","écrou","écume","écureuil","édifier","éduquer","effacer","effectif","effigie","effort","effrayer","effusion","égaliser","égarer","éjecter","élaborer","élargir","électron","élégant","éléphant","élève","éligible","élitisme","éloge","élucider","éluder","emballer","embellir","embryon","émeraude","émission","emmener","émotion","émouvoir","empereur","employer","emporter","emprise","émulsion","encadrer","enchère","enclave","encoche","endiguer","endosser","endroit","enduire","énergie","enfance","enfermer","enfouir","engager","engin","englober","énigme","enjamber","enjeu","enlever","ennemi","ennuyeux","enrichir","enrobage","enseigne","entasser","entendre","entier","entourer","entraver","énumérer","envahir","enviable","envoyer","enzyme","éolien","épaissir","épargne","épatant","épaule","épicerie","épidémie","épier","épilogue","épine","épisode","épitaphe","époque","épreuve","éprouver","épuisant","équerre","équipe","ériger","érosion","erreur","éruption","escalier","espadon","espèce","espiègle","espoir","esprit","esquiver","essayer","essence","essieu","essorer","estime","estomac","estrade","étagère","étaler","étanche","étatique","éteindre","étendoir","éternel","éthanol","éthique","ethnie","étirer","étoffer","étoile","étonnant","étourdir","étrange","étroit","étude","euphorie","évaluer","évasion","éventail","évidence","éviter","évolutif","évoquer","exact","exagérer","exaucer","exceller","excitant","exclusif","excuse","exécuter","exemple","exercer","exhaler","exhorter","exigence","exiler","exister","exotique","expédier","explorer","exposer","exprimer","exquis","extensif","extraire","exulter","fable","fabuleux","facette","facile","facture","faiblir","falaise","fameux","famille","farceur","farfelu","farine","farouche","fasciner","fatal","fatigue","faucon","fautif","faveur","favori","fébrile","féconder","fédérer","félin","femme","fémur","fendoir","féodal","fermer","féroce","ferveur","festival","feuille","feutre","février","fiasco","ficeler","fictif","fidèle","figure","filature","filetage","filière","filleul","filmer","filou","filtrer","financer","finir","fiole","firme","fissure","fixer","flairer","flamme","flasque","flatteur","fléau","flèche","fleur","flexion","flocon","flore","fluctuer","fluide","fluvial","folie","fonderie","fongible","fontaine","forcer","forgeron","formuler","fortune","fossile","foudre","fougère","fouiller","foulure","fourmi","fragile","fraise","franchir","frapper","frayeur","frégate","freiner","frelon","frémir","frénésie","frère","friable","friction","frisson","frivole","froid","fromage","frontal","frotter","fruit","fugitif","fuite","fureur","furieux","furtif","fusion","futur","gagner","galaxie","galerie","gambader","garantir","gardien","garnir","garrigue","gazelle","gazon","géant","gélatine","gélule","gendarme","général","génie","genou","gentil","géologie","géomètre","géranium","germe","gestuel","geyser","gibier","gicler","girafe","givre","glace","glaive","glisser","globe","gloire","glorieux","golfeur","gomme","gonfler","gorge","gorille","goudron","gouffre","goulot","goupille","gourmand","goutte","graduel","graffiti","graine","grand","grappin","gratuit","gravir","grenat","griffure","griller","grimper","grogner","gronder","grotte","groupe","gruger","grutier","gruyère","guépard","guerrier","guide","guimauve","guitare","gustatif","gymnaste","gyrostat","habitude","hachoir","halte","hameau","hangar","hanneton","haricot","harmonie","harpon","hasard","hélium","hématome","herbe","hérisson","hermine","héron","hésiter","heureux","hiberner","hibou","hilarant","histoire","hiver","homard","hommage","homogène","honneur","honorer","honteux","horde","horizon","horloge","hormone","horrible","houleux","housse","hublot","huileux","humain","humble","humide","humour","hurler","hydromel","hygiène","hymne","hypnose","idylle","ignorer","iguane","illicite","illusion","image","imbiber","imiter","immense","immobile","immuable","impact","impérial","implorer","imposer","imprimer","imputer","incarner","incendie","incident","incliner","incolore","indexer","indice","inductif","inédit","ineptie","inexact","infini","infliger","informer","infusion","ingérer","inhaler","inhiber","injecter","injure","innocent","inoculer","inonder","inscrire","insecte","insigne","insolite","inspirer","instinct","insulter","intact","intense","intime","intrigue","intuitif","inutile","invasion","inventer","inviter","invoquer","ironique","irradier","irréel","irriter","isoler","ivoire","ivresse","jaguar","jaillir","jambe","janvier","jardin","jauger","jaune","javelot","jetable","jeton","jeudi","jeunesse","joindre","joncher","jongler","joueur","jouissif","journal","jovial","joyau","joyeux","jubiler","jugement","junior","jupon","juriste","justice","juteux","juvénile","kayak","kimono","kiosque","label","labial","labourer","lacérer","lactose","lagune","laine","laisser","laitier","lambeau","lamelle","lampe","lanceur","langage","lanterne","lapin","largeur","larme","laurier","lavabo","lavoir","lecture","légal","léger","légume","lessive","lettre","levier","lexique","lézard","liasse","libérer","libre","licence","licorne","liège","lièvre","ligature","ligoter","ligue","limer","limite","limonade","limpide","linéaire","lingot","lionceau","liquide","lisière","lister","lithium","litige","littoral","livreur","logique","lointain","loisir","lombric","loterie","louer","lourd","loutre","louve","loyal","lubie","lucide","lucratif","lueur","lugubre","luisant","lumière","lunaire","lundi","luron","lutter","luxueux","machine","magasin","magenta","magique","maigre","maillon","maintien","mairie","maison","majorer","malaxer","maléfice","malheur","malice","mallette","mammouth","mandater","maniable","manquant","manteau","manuel","marathon","marbre","marchand","mardi","maritime","marqueur","marron","marteler","mascotte","massif","matériel","matière","matraque","maudire","maussade","mauve","maximal","méchant","méconnu","médaille","médecin","méditer","méduse","meilleur","mélange","mélodie","membre","mémoire","menacer","mener","menhir","mensonge","mentor","mercredi","mérite","merle","messager","mesure","métal","météore","méthode","métier","meuble","miauler","microbe","miette","mignon","migrer","milieu","million","mimique","mince","minéral","minimal","minorer","minute","miracle","miroiter","missile","mixte","mobile","moderne","moelleux","mondial","moniteur","monnaie","monotone","monstre","montagne","monument","moqueur","morceau","morsure","mortier","moteur","motif","mouche","moufle","moulin","mousson","mouton","mouvant","multiple","munition","muraille","murène","murmure","muscle","muséum","musicien","mutation","muter","mutuel","myriade","myrtille","mystère","mythique","nageur","nappe","narquois","narrer","natation","nation","nature","naufrage","nautique","navire","nébuleux","nectar","néfaste","négation","négliger","négocier","neige","nerveux","nettoyer","neurone","neutron","neveu","niche","nickel","nitrate","niveau","noble","nocif","nocturne","noirceur","noisette","nomade","nombreux","nommer","normatif","notable","notifier","notoire","nourrir","nouveau","novateur","novembre","novice","nuage","nuancer","nuire","nuisible","numéro","nuptial","nuque","nutritif","obéir","objectif","obliger","obscur","observer","obstacle","obtenir","obturer","occasion","occuper","océan","octobre","octroyer","octupler","oculaire","odeur","odorant","offenser","officier","offrir","ogive","oiseau","oisillon","olfactif","olivier","ombrage","omettre","onctueux","onduler","onéreux","onirique","opale","opaque","opérer","opinion","opportun","opprimer","opter","optique","orageux","orange","orbite","ordonner","oreille","organe","orgueil","orifice","ornement","orque","ortie","osciller","osmose","ossature","otarie","ouragan","ourson","outil","outrager","ouvrage","ovation","oxyde","oxygène","ozone","paisible","palace","palmarès","palourde","palper","panache","panda","pangolin","paniquer","panneau","panorama","pantalon","papaye","papier","papoter","papyrus","paradoxe","parcelle","paresse","parfumer","parler","parole","parrain","parsemer","partager","parure","parvenir","passion","pastèque","paternel","patience","patron","pavillon","pavoiser","payer","paysage","peigne","peintre","pelage","pélican","pelle","pelouse","peluche","pendule","pénétrer","pénible","pensif","pénurie","pépite","péplum","perdrix","perforer","période","permuter","perplexe","persil","perte","peser","pétale","petit","pétrir","peuple","pharaon","phobie","phoque","photon","phrase","physique","piano","pictural","pièce","pierre","pieuvre","pilote","pinceau","pipette","piquer","pirogue","piscine","piston","pivoter","pixel","pizza","placard","plafond","plaisir","planer","plaque","plastron","plateau","pleurer","plexus","pliage","plomb","plonger","pluie","plumage","pochette","poésie","poète","pointe","poirier","poisson","poivre","polaire","policier","pollen","polygone","pommade","pompier","ponctuel","pondérer","poney","portique","position","posséder","posture","potager","poteau","potion","pouce","poulain","poumon","pourpre","poussin","pouvoir","prairie","pratique","précieux","prédire","préfixe","prélude","prénom","présence","prétexte","prévoir","primitif","prince","prison","priver","problème","procéder","prodige","profond","progrès","proie","projeter","prologue","promener","propre","prospère","protéger","prouesse","proverbe","prudence","pruneau","psychose","public","puceron","puiser","pulpe","pulsar","punaise","punitif","pupitre","purifier","puzzle","pyramide","quasar","querelle","question","quiétude","quitter","quotient","racine","raconter","radieux","ragondin","raideur","raisin","ralentir","rallonge","ramasser","rapide","rasage","ratisser","ravager","ravin","rayonner","réactif","réagir","réaliser","réanimer","recevoir","réciter","réclamer","récolter","recruter","reculer","recycler","rédiger","redouter","refaire","réflexe","réformer","refrain","refuge","régalien","région","réglage","régulier","réitérer","rejeter","rejouer","relatif","relever","relief","remarque","remède","remise","remonter","remplir","remuer","renard","renfort","renifler","renoncer","rentrer","renvoi","replier","reporter","reprise","reptile","requin","réserve","résineux","résoudre","respect","rester","résultat","rétablir","retenir","réticule","retomber","retracer","réunion","réussir","revanche","revivre","révolte","révulsif","richesse","rideau","rieur","rigide","rigoler","rincer","riposter","risible","risque","rituel","rival","rivière","rocheux","romance","rompre","ronce","rondin","roseau","rosier","rotatif","rotor","rotule","rouge","rouille","rouleau","routine","royaume","ruban","rubis","ruche","ruelle","rugueux","ruiner","ruisseau","ruser","rustique","rythme","sabler","saboter","sabre","sacoche","safari","sagesse","saisir","salade","salive","salon","saluer","samedi","sanction","sanglier","sarcasme","sardine","saturer","saugrenu","saumon","sauter","sauvage","savant","savonner","scalpel","scandale","scélérat","scénario","sceptre","schéma","science","scinder","score","scrutin","sculpter","séance","sécable","sécher","secouer","sécréter","sédatif","séduire","seigneur","séjour","sélectif","semaine","sembler","semence","séminal","sénateur","sensible","sentence","séparer","séquence","serein","sergent","sérieux","serrure","sérum","service","sésame","sévir","sevrage","sextuple","sidéral","siècle","siéger","siffler","sigle","signal","silence","silicium","simple","sincère","sinistre","siphon","sirop","sismique","situer","skier","social","socle","sodium","soigneux","soldat","soleil","solitude","soluble","sombre","sommeil","somnoler","sonde","songeur","sonnette","sonore","sorcier","sortir","sosie","sottise","soucieux","soudure","souffle","soulever","soupape","source","soutirer","souvenir","spacieux","spatial","spécial","sphère","spiral","stable","station","sternum","stimulus","stipuler","strict","studieux","stupeur","styliste","sublime","substrat","subtil","subvenir","succès","sucre","suffixe","suggérer","suiveur","sulfate","superbe","supplier","surface","suricate","surmener","surprise","sursaut","survie","suspect","syllabe","symbole","symétrie","synapse","syntaxe","système","tabac","tablier","tactile","tailler","talent","talisman","talonner","tambour","tamiser","tangible","tapis","taquiner","tarder","tarif","tartine","tasse","tatami","tatouage","taupe","taureau","taxer","témoin","temporel","tenaille","tendre","teneur","tenir","tension","terminer","terne","terrible","tétine","texte","thème","théorie","thérapie","thorax","tibia","tiède","timide","tirelire","tiroir","tissu","titane","titre","tituber","toboggan","tolérant","tomate","tonique","tonneau","toponyme","torche","tordre","tornade","torpille","torrent","torse","tortue","totem","toucher","tournage","tousser","toxine","traction","trafic","tragique","trahir","train","trancher","travail","trèfle","tremper","trésor","treuil","triage","tribunal","tricoter","trilogie","triomphe","tripler","triturer","trivial","trombone","tronc","tropical","troupeau","tuile","tulipe","tumulte","tunnel","turbine","tuteur","tutoyer","tuyau","tympan","typhon","typique","tyran","ubuesque","ultime","ultrason","unanime","unifier","union","unique","unitaire","univers","uranium","urbain","urticant","usage","usine","usuel","usure","utile","utopie","vacarme","vaccin","vagabond","vague","vaillant","vaincre","vaisseau","valable","valise","vallon","valve","vampire","vanille","vapeur","varier","vaseux","vassal","vaste","vecteur","vedette","végétal","véhicule","veinard","véloce","vendredi","vénérer","venger","venimeux","ventouse","verdure","vérin","vernir","verrou","verser","vertu","veston","vétéran","vétuste","vexant","vexer","viaduc","viande","victoire","vidange","vidéo","vignette","vigueur","vilain","village","vinaigre","violon","vipère","virement","virtuose","virus","visage","viseur","vision","visqueux","visuel","vital","vitesse","viticole","vitrine","vivace","vivipare","vocation","voguer","voile","voisin","voiture","volaille","volcan","voltiger","volume","vorace","vortex","voter","vouloir","voyage","voyelle","wagon","xénon","yacht","zèbre","zénith","zeste","zoologie"]// note all JSON files in this folder are generated with npm run generate-wordlist
const lookup = require('./lookup.json')

module.exports = {
  loadWordlist,
  detectLanguage
}

function loadWordlist (language) {
  switch (language) {
    case 'chinese_simplified': return require('./chinese_simplified.json')
    case 'chinese_traditional': return require('./chinese_traditional.json')
    case 'czech': return require('./czech.json')
    case 'english': return require('./english.json')
    case 'french': return require('./french.json')
    case 'italian': return require('./italian.json')
    case 'japanese': return require('./japanese.json')
    case 'korean': return require('./korean.json')
    case 'portuguese': return require('./portuguese.json')
    case 'russian': return require('./russian.json')
    case 'spanish': return require('./spanish.json')
    case 'turkish': return require('./turkish.json')
  }

  throw new Error('Unknown language: ' + language)
}

function detectLanguage (words) {
  let candidate = null

  for (const word of words) {
    const languages = lookup[word]
    if (!languages) return null

    if (languages.length === 1) return languages[0]

    if (!candidate) {
      candidate = languages
      continue
    }

    const intersect = candidate.filter(l => languages.includes(l))
    if (intersect.length === 1) return intersect[0]
  }

  return candidate[0]
}
["abaco","abbaglio","abbinato","abete","abisso","abolire","abrasivo","abrogato","accadere","accenno","accusato","acetone","achille","acido","acqua","acre","acrilico","acrobata","acuto","adagio","addebito","addome","adeguato","aderire","adipe","adottare","adulare","affabile","affetto","affisso","affranto","aforisma","afoso","africano","agave","agente","agevole","aggancio","agire","agitare","agonismo","agricolo","agrumeto","aguzzo","alabarda","alato","albatro","alberato","albo","albume","alce","alcolico","alettone","alfa","algebra","aliante","alibi","alimento","allagato","allegro","allievo","allodola","allusivo","almeno","alogeno","alpaca","alpestre","altalena","alterno","alticcio","altrove","alunno","alveolo","alzare","amalgama","amanita","amarena","ambito","ambrato","ameba","america","ametista","amico","ammasso","ammenda","ammirare","ammonito","amore","ampio","ampliare","amuleto","anacardo","anagrafe","analista","anarchia","anatra","anca","ancella","ancora","andare","andrea","anello","angelo","angolare","angusto","anima","annegare","annidato","anno","annuncio","anonimo","anticipo","anzi","apatico","apertura","apode","apparire","appetito","appoggio","approdo","appunto","aprile","arabica","arachide","aragosta","araldica","arancio","aratura","arazzo","arbitro","archivio","ardito","arenile","argento","argine","arguto","aria","armonia","arnese","arredato","arringa","arrosto","arsenico","arso","artefice","arzillo","asciutto","ascolto","asepsi","asettico","asfalto","asino","asola","aspirato","aspro","assaggio","asse","assoluto","assurdo","asta","astenuto","astice","astratto","atavico","ateismo","atomico","atono","attesa","attivare","attorno","attrito","attuale","ausilio","austria","autista","autonomo","autunno","avanzato","avere","avvenire","avviso","avvolgere","azione","azoto","azzimo","azzurro","babele","baccano","bacino","baco","badessa","badilata","bagnato","baita","balcone","baldo","balena","ballata","balzano","bambino","bandire","baraonda","barbaro","barca","baritono","barlume","barocco","basilico","basso","batosta","battuto","baule","bava","bavosa","becco","beffa","belgio","belva","benda","benevole","benigno","benzina","bere","berlina","beta","bibita","bici","bidone","bifido","biga","bilancia","bimbo","binocolo","biologo","bipede","bipolare","birbante","birra","biscotto","bisesto","bisnonno","bisonte","bisturi","bizzarro","blando","blatta","bollito","bonifico","bordo","bosco","botanico","bottino","bozzolo","braccio","bradipo","brama","branca","bravura","bretella","brevetto","brezza","briglia","brillante","brindare","broccolo","brodo","bronzina","brullo","bruno","bubbone","buca","budino","buffone","buio","bulbo","buono","burlone","burrasca","bussola","busta","cadetto","caduco","calamaro","calcolo","calesse","calibro","calmo","caloria","cambusa","camerata","camicia","cammino","camola","campale","canapa","candela","cane","canino","canotto","cantina","capace","capello","capitolo","capogiro","cappero","capra","capsula","carapace","carcassa","cardo","carisma","carovana","carretto","cartolina","casaccio","cascata","caserma","caso","cassone","castello","casuale","catasta","catena","catrame","cauto","cavillo","cedibile","cedrata","cefalo","celebre","cellulare","cena","cenone","centesimo","ceramica","cercare","certo","cerume","cervello","cesoia","cespo","ceto","chela","chiaro","chicca","chiedere","chimera","china","chirurgo","chitarra","ciao","ciclismo","cifrare","cigno","cilindro","ciottolo","circa","cirrosi","citrico","cittadino","ciuffo","civetta","civile","classico","clinica","cloro","cocco","codardo","codice","coerente","cognome","collare","colmato","colore","colposo","coltivato","colza","coma","cometa","commando","comodo","computer","comune","conciso","condurre","conferma","congelare","coniuge","connesso","conoscere","consumo","continuo","convegno","coperto","copione","coppia","copricapo","corazza","cordata","coricato","cornice","corolla","corpo","corredo","corsia","cortese","cosmico","costante","cottura","covato","cratere","cravatta","creato","credere","cremoso","crescita","creta","criceto","crinale","crisi","critico","croce","cronaca","crostata","cruciale","crusca","cucire","cuculo","cugino","cullato","cupola","curatore","cursore","curvo","cuscino","custode","dado","daino","dalmata","damerino","daniela","dannoso","danzare","datato","davanti","davvero","debutto","decennio","deciso","declino","decollo","decreto","dedicato","definito","deforme","degno","delegare","delfino","delirio","delta","demenza","denotato","dentro","deposito","derapata","derivare","deroga","descritto","deserto","desiderio","desumere","detersivo","devoto","diametro","dicembre","diedro","difeso","diffuso","digerire","digitale","diluvio","dinamico","dinnanzi","dipinto","diploma","dipolo","diradare","dire","dirotto","dirupo","disagio","discreto","disfare","disgelo","disposto","distanza","disumano","dito","divano","divelto","dividere","divorato","doblone","docente","doganale","dogma","dolce","domato","domenica","dominare","dondolo","dono","dormire","dote","dottore","dovuto","dozzina","drago","druido","dubbio","dubitare","ducale","duna","duomo","duplice","duraturo","ebano","eccesso","ecco","eclissi","economia","edera","edicola","edile","editoria","educare","egemonia","egli","egoismo","egregio","elaborato","elargire","elegante","elencato","eletto","elevare","elfico","elica","elmo","elsa","eluso","emanato","emblema","emesso","emiro","emotivo","emozione","empirico","emulo","endemico","enduro","energia","enfasi","enoteca","entrare","enzima","epatite","epilogo","episodio","epocale","eppure","equatore","erario","erba","erboso","erede","eremita","erigere","ermetico","eroe","erosivo","errante","esagono","esame","esanime","esaudire","esca","esempio","esercito","esibito","esigente","esistere","esito","esofago","esortato","esoso","espanso","espresso","essenza","esso","esteso","estimare","estonia","estroso","esultare","etilico","etnico","etrusco","etto","euclideo","europa","evaso","evidenza","evitato","evoluto","evviva","fabbrica","faccenda","fachiro","falco","famiglia","fanale","fanfara","fango","fantasma","fare","farfalla","farinoso","farmaco","fascia","fastoso","fasullo","faticare","fato","favoloso","febbre","fecola","fede","fegato","felpa","feltro","femmina","fendere","fenomeno","fermento","ferro","fertile","fessura","festivo","fetta","feudo","fiaba","fiducia","fifa","figurato","filo","finanza","finestra","finire","fiore","fiscale","fisico","fiume","flacone","flamenco","flebo","flemma","florido","fluente","fluoro","fobico","focaccia","focoso","foderato","foglio","folata","folclore","folgore","fondente","fonetico","fonia","fontana","forbito","forchetta","foresta","formica","fornaio","foro","fortezza","forzare","fosfato","fosso","fracasso","frana","frassino","fratello","freccetta","frenata","fresco","frigo","frollino","fronde","frugale","frutta","fucilata","fucsia","fuggente","fulmine","fulvo","fumante","fumetto","fumoso","fune","funzione","fuoco","furbo","furgone","furore","fuso","futile","gabbiano","gaffe","galateo","gallina","galoppo","gambero","gamma","garanzia","garbo","garofano","garzone","gasdotto","gasolio","gastrico","gatto","gaudio","gazebo","gazzella","geco","gelatina","gelso","gemello","gemmato","gene","genitore","gennaio","genotipo","gergo","ghepardo","ghiaccio","ghisa","giallo","gilda","ginepro","giocare","gioiello","giorno","giove","girato","girone","gittata","giudizio","giurato","giusto","globulo","glutine","gnomo","gobba","golf","gomito","gommone","gonfio","gonna","governo","gracile","grado","grafico","grammo","grande","grattare","gravoso","grazia","greca","gregge","grifone","grigio","grinza","grotta","gruppo","guadagno","guaio","guanto","guardare","gufo","guidare","ibernato","icona","identico","idillio","idolo","idra","idrico","idrogeno","igiene","ignaro","ignorato","ilare","illeso","illogico","illudere","imballo","imbevuto","imbocco","imbuto","immane","immerso","immolato","impacco","impeto","impiego","importo","impronta","inalare","inarcare","inattivo","incanto","incendio","inchino","incisivo","incluso","incontro","incrocio","incubo","indagine","india","indole","inedito","infatti","infilare","inflitto","ingaggio","ingegno","inglese","ingordo","ingrosso","innesco","inodore","inoltrare","inondato","insano","insetto","insieme","insonnia","insulina","intasato","intero","intonaco","intuito","inumidire","invalido","invece","invito","iperbole","ipnotico","ipotesi","ippica","iride","irlanda","ironico","irrigato","irrorare","isolato","isotopo","isterico","istituto","istrice","italia","iterare","labbro","labirinto","lacca","lacerato","lacrima","lacuna","laddove","lago","lampo","lancetta","lanterna","lardoso","larga","laringe","lastra","latenza","latino","lattuga","lavagna","lavoro","legale","leggero","lembo","lentezza","lenza","leone","lepre","lesivo","lessato","lesto","letterale","leva","levigato","libero","lido","lievito","lilla","limatura","limitare","limpido","lineare","lingua","liquido","lira","lirica","lisca","lite","litigio","livrea","locanda","lode","logica","lombare","londra","longevo","loquace","lorenzo","loto","lotteria","luce","lucidato","lumaca","luminoso","lungo","lupo","luppolo","lusinga","lusso","lutto","macabro","macchina","macero","macinato","madama","magico","maglia","magnete","magro","maiolica","malafede","malgrado","malinteso","malsano","malto","malumore","mana","mancia","mandorla","mangiare","manifesto","mannaro","manovra","mansarda","mantide","manubrio","mappa","maratona","marcire","maretta","marmo","marsupio","maschera","massaia","mastino","materasso","matricola","mattone","maturo","mazurca","meandro","meccanico","mecenate","medesimo","meditare","mega","melassa","melis","melodia","meninge","meno","mensola","mercurio","merenda","merlo","meschino","mese","messere","mestolo","metallo","metodo","mettere","miagolare","mica","micelio","michele","microbo","midollo","miele","migliore","milano","milite","mimosa","minerale","mini","minore","mirino","mirtillo","miscela","missiva","misto","misurare","mitezza","mitigare","mitra","mittente","mnemonico","modello","modifica","modulo","mogano","mogio","mole","molosso","monastero","monco","mondina","monetario","monile","monotono","monsone","montato","monviso","mora","mordere","morsicato","mostro","motivato","motosega","motto","movenza","movimento","mozzo","mucca","mucosa","muffa","mughetto","mugnaio","mulatto","mulinello","multiplo","mummia","munto","muovere","murale","musa","muscolo","musica","mutevole","muto","nababbo","nafta","nanometro","narciso","narice","narrato","nascere","nastrare","naturale","nautica","naviglio","nebulosa","necrosi","negativo","negozio","nemmeno","neofita","neretto","nervo","nessuno","nettuno","neutrale","neve","nevrotico","nicchia","ninfa","nitido","nobile","nocivo","nodo","nome","nomina","nordico","normale","norvegese","nostrano","notare","notizia","notturno","novella","nucleo","nulla","numero","nuovo","nutrire","nuvola","nuziale","oasi","obbedire","obbligo","obelisco","oblio","obolo","obsoleto","occasione","occhio","occidente","occorrere","occultare","ocra","oculato","odierno","odorare","offerta","offrire","offuscato","oggetto","oggi","ognuno","olandese","olfatto","oliato","oliva","ologramma","oltre","omaggio","ombelico","ombra","omega","omissione","ondoso","onere","onice","onnivoro","onorevole","onta","operato","opinione","opposto","oracolo","orafo","ordine","orecchino","orefice","orfano","organico","origine","orizzonte","orma","ormeggio","ornativo","orologio","orrendo","orribile","ortensia","ortica","orzata","orzo","osare","oscurare","osmosi","ospedale","ospite","ossa","ossidare","ostacolo","oste","otite","otre","ottagono","ottimo","ottobre","ovale","ovest","ovino","oviparo","ovocito","ovunque","ovviare","ozio","pacchetto","pace","pacifico","padella","padrone","paese","paga","pagina","palazzina","palesare","pallido","palo","palude","pandoro","pannello","paolo","paonazzo","paprica","parabola","parcella","parere","pargolo","pari","parlato","parola","partire","parvenza","parziale","passivo","pasticca","patacca","patologia","pattume","pavone","peccato","pedalare","pedonale","peggio","peloso","penare","pendice","penisola","pennuto","penombra","pensare","pentola","pepe","pepita","perbene","percorso","perdonato","perforare","pergamena","periodo","permesso","perno","perplesso","persuaso","pertugio","pervaso","pesatore","pesista","peso","pestifero","petalo","pettine","petulante","pezzo","piacere","pianta","piattino","piccino","picozza","piega","pietra","piffero","pigiama","pigolio","pigro","pila","pilifero","pillola","pilota","pimpante","pineta","pinna","pinolo","pioggia","piombo","piramide","piretico","pirite","pirolisi","pitone","pizzico","placebo","planare","plasma","platano","plenario","pochezza","poderoso","podismo","poesia","poggiare","polenta","poligono","pollice","polmonite","polpetta","polso","poltrona","polvere","pomice","pomodoro","ponte","popoloso","porfido","poroso","porpora","porre","portata","posa","positivo","possesso","postulato","potassio","potere","pranzo","prassi","pratica","precluso","predica","prefisso","pregiato","prelievo","premere","prenotare","preparato","presenza","pretesto","prevalso","prima","principe","privato","problema","procura","produrre","profumo","progetto","prolunga","promessa","pronome","proposta","proroga","proteso","prova","prudente","prugna","prurito","psiche","pubblico","pudica","pugilato","pugno","pulce","pulito","pulsante","puntare","pupazzo","pupilla","puro","quadro","qualcosa","quasi","querela","quota","raccolto","raddoppio","radicale","radunato","raffica","ragazzo","ragione","ragno","ramarro","ramingo","ramo","randagio","rantolare","rapato","rapina","rappreso","rasatura","raschiato","rasente","rassegna","rastrello","rata","ravveduto","reale","recepire","recinto","recluta","recondito","recupero","reddito","redimere","regalato","registro","regola","regresso","relazione","remare","remoto","renna","replica","reprimere","reputare","resa","residente","responso","restauro","rete","retina","retorica","rettifica","revocato","riassunto","ribadire","ribelle","ribrezzo","ricarica","ricco","ricevere","riciclato","ricordo","ricreduto","ridicolo","ridurre","rifasare","riflesso","riforma","rifugio","rigare","rigettato","righello","rilassato","rilevato","rimanere","rimbalzo","rimedio","rimorchio","rinascita","rincaro","rinforzo","rinnovo","rinomato","rinsavito","rintocco","rinuncia","rinvenire","riparato","ripetuto","ripieno","riportare","ripresa","ripulire","risata","rischio","riserva","risibile","riso","rispetto","ristoro","risultato","risvolto","ritardo","ritegno","ritmico","ritrovo","riunione","riva","riverso","rivincita","rivolto","rizoma","roba","robotico","robusto","roccia","roco","rodaggio","rodere","roditore","rogito","rollio","romantico","rompere","ronzio","rosolare","rospo","rotante","rotondo","rotula","rovescio","rubizzo","rubrica","ruga","rullino","rumine","rumoroso","ruolo","rupe","russare","rustico","sabato","sabbiare","sabotato","sagoma","salasso","saldatura","salgemma","salivare","salmone","salone","saltare","saluto","salvo","sapere","sapido","saporito","saraceno","sarcasmo","sarto","sassoso","satellite","satira","satollo","saturno","savana","savio","saziato","sbadiglio","sbalzo","sbancato","sbarra","sbattere","sbavare","sbendare","sbirciare","sbloccato","sbocciato","sbrinare","sbruffone","sbuffare","scabroso","scadenza","scala","scambiare","scandalo","scapola","scarso","scatenare","scavato","scelto","scenico","scettro","scheda","schiena","sciarpa","scienza","scindere","scippo","sciroppo","scivolo","sclerare","scodella","scolpito","scomparto","sconforto","scoprire","scorta","scossone","scozzese","scriba","scrollare","scrutinio","scuderia","scultore","scuola","scuro","scusare","sdebitare","sdoganare","seccatura","secondo","sedano","seggiola","segnalato","segregato","seguito","selciato","selettivo","sella","selvaggio","semaforo","sembrare","seme","seminato","sempre","senso","sentire","sepolto","sequenza","serata","serbato","sereno","serio","serpente","serraglio","servire","sestina","setola","settimana","sfacelo","sfaldare","sfamato","sfarzoso","sfaticato","sfera","sfida","sfilato","sfinge","sfocato","sfoderare","sfogo","sfoltire","sforzato","sfratto","sfruttato","sfuggito","sfumare","sfuso","sgabello","sgarbato","sgonfiare","sgorbio","sgrassato","sguardo","sibilo","siccome","sierra","sigla","signore","silenzio","sillaba","simbolo","simpatico","simulato","sinfonia","singolo","sinistro","sino","sintesi","sinusoide","sipario","sisma","sistole","situato","slitta","slogatura","sloveno","smarrito","smemorato","smentito","smeraldo","smilzo","smontare","smottato","smussato","snellire","snervato","snodo","sobbalzo","sobrio","soccorso","sociale","sodale","soffitto","sogno","soldato","solenne","solido","sollazzo","solo","solubile","solvente","somatico","somma","sonda","sonetto","sonnifero","sopire","soppeso","sopra","sorgere","sorpasso","sorriso","sorso","sorteggio","sorvolato","sospiro","sosta","sottile","spada","spalla","spargere","spatola","spavento","spazzola","specie","spedire","spegnere","spelatura","speranza","spessore","spettrale","spezzato","spia","spigoloso","spillato","spinoso","spirale","splendido","sportivo","sposo","spranga","sprecare","spronato","spruzzo","spuntino","squillo","sradicare","srotolato","stabile","stacco","staffa","stagnare","stampato","stantio","starnuto","stasera","statuto","stelo","steppa","sterzo","stiletto","stima","stirpe","stivale","stizzoso","stonato","storico","strappo","stregato","stridulo","strozzare","strutto","stuccare","stufo","stupendo","subentro","succoso","sudore","suggerito","sugo","sultano","suonare","superbo","supporto","surgelato","surrogato","sussurro","sutura","svagare","svedese","sveglio","svelare","svenuto","svezia","sviluppo","svista","svizzera","svolta","svuotare","tabacco","tabulato","tacciare","taciturno","tale","talismano","tampone","tannino","tara","tardivo","targato","tariffa","tarpare","tartaruga","tasto","tattico","taverna","tavolata","tazza","teca","tecnico","telefono","temerario","tempo","temuto","tendone","tenero","tensione","tentacolo","teorema","terme","terrazzo","terzetto","tesi","tesserato","testato","tetro","tettoia","tifare","tigella","timbro","tinto","tipico","tipografo","tiraggio","tiro","titanio","titolo","titubante","tizio","tizzone","toccare","tollerare","tolto","tombola","tomo","tonfo","tonsilla","topazio","topologia","toppa","torba","tornare","torrone","tortora","toscano","tossire","tostatura","totano","trabocco","trachea","trafila","tragedia","tralcio","tramonto","transito","trapano","trarre","trasloco","trattato","trave","treccia","tremolio","trespolo","tributo","tricheco","trifoglio","trillo","trincea","trio","tristezza","triturato","trivella","tromba","trono","troppo","trottola","trovare","truccato","tubatura","tuffato","tulipano","tumulto","tunisia","turbare","turchino","tuta","tutela","ubicato","uccello","uccisore","udire","uditivo","uffa","ufficio","uguale","ulisse","ultimato","umano","umile","umorismo","uncinetto","ungere","ungherese","unicorno","unificato","unisono","unitario","unte","uovo","upupa","uragano","urgenza","urlo","usanza","usato","uscito","usignolo","usuraio","utensile","utilizzo","utopia","vacante","vaccinato","vagabondo","vagliato","valanga","valgo","valico","valletta","valoroso","valutare","valvola","vampata","vangare","vanitoso","vano","vantaggio","vanvera","vapore","varano","varcato","variante","vasca","vedetta","vedova","veduto","vegetale","veicolo","velcro","velina","velluto","veloce","venato","vendemmia","vento","verace","verbale","vergogna","verifica","vero","verruca","verticale","vescica","vessillo","vestale","veterano","vetrina","vetusto","viandante","vibrante","vicenda","vichingo","vicinanza","vidimare","vigilia","vigneto","vigore","vile","villano","vimini","vincitore","viola","vipera","virgola","virologo","virulento","viscoso","visione","vispo","vissuto","visura","vita","vitello","vittima","vivanda","vivido","viziare","voce","voga","volatile","volere","volpe","voragine","vulcano","zampogna","zanna","zappato","zattera","zavorra","zefiro","zelante","zelo","zenzero","zerbino","zibetto","zinco","zircone","zitto","zolla","zotico","zucchero","zufolo","zulu","zuppa"]["あいこくしん","あいさつ","あいだ","あおぞら","あかちゃん","あきる","あけがた","あける","あこがれる","あさい","あさひ","あしあと","あじわう","あずかる","あずき","あそぶ","あたえる","あたためる","あたりまえ","あたる","あつい","あつかう","あっしゅく","あつまり","あつめる","あてな","あてはまる","あひる","あぶら","あぶる","あふれる","あまい","あまど","あまやかす","あまり","あみもの","あめりか","あやまる","あゆむ","あらいぐま","あらし","あらすじ","あらためる","あらゆる","あらわす","ありがとう","あわせる","あわてる","あんい","あんがい","あんこ","あんぜん","あんてい","あんない","あんまり","いいだす","いおん","いがい","いがく","いきおい","いきなり","いきもの","いきる","いくじ","いくぶん","いけばな","いけん","いこう","いこく","いこつ","いさましい","いさん","いしき","いじゅう","いじょう","いじわる","いずみ","いずれ","いせい","いせえび","いせかい","いせき","いぜん","いそうろう","いそがしい","いだい","いだく","いたずら","いたみ","いたりあ","いちおう","いちじ","いちど","いちば","いちぶ","いちりゅう","いつか","いっしゅん","いっせい","いっそう","いったん","いっち","いってい","いっぽう","いてざ","いてん","いどう","いとこ","いない","いなか","いねむり","いのち","いのる","いはつ","いばる","いはん","いびき","いひん","いふく","いへん","いほう","いみん","いもうと","いもたれ","いもり","いやがる","いやす","いよかん","いよく","いらい","いらすと","いりぐち","いりょう","いれい","いれもの","いれる","いろえんぴつ","いわい","いわう","いわかん","いわば","いわゆる","いんげんまめ","いんさつ","いんしょう","いんよう","うえき","うえる","うおざ","うがい","うかぶ","うかべる","うきわ","うくらいな","うくれれ","うけたまわる","うけつけ","うけとる","うけもつ","うける","うごかす","うごく","うこん","うさぎ","うしなう","うしろがみ","うすい","うすぎ","うすぐらい","うすめる","うせつ","うちあわせ","うちがわ","うちき","うちゅう","うっかり","うつくしい","うったえる","うつる","うどん","うなぎ","うなじ","うなずく","うなる","うねる","うのう","うぶげ","うぶごえ","うまれる","うめる","うもう","うやまう","うよく","うらがえす","うらぐち","うらない","うりあげ","うりきれ","うるさい","うれしい","うれゆき","うれる","うろこ","うわき","うわさ","うんこう","うんちん","うんてん","うんどう","えいえん","えいが","えいきょう","えいご","えいせい","えいぶん","えいよう","えいわ","えおり","えがお","えがく","えきたい","えくせる","えしゃく","えすて","えつらん","えのぐ","えほうまき","えほん","えまき","えもじ","えもの","えらい","えらぶ","えりあ","えんえん","えんかい","えんぎ","えんげき","えんしゅう","えんぜつ","えんそく","えんちょう","えんとつ","おいかける","おいこす","おいしい","おいつく","おうえん","おうさま","おうじ","おうせつ","おうたい","おうふく","おうべい","おうよう","おえる","おおい","おおう","おおどおり","おおや","おおよそ","おかえり","おかず","おがむ","おかわり","おぎなう","おきる","おくさま","おくじょう","おくりがな","おくる","おくれる","おこす","おこなう","おこる","おさえる","おさない","おさめる","おしいれ","おしえる","おじぎ","おじさん","おしゃれ","おそらく","おそわる","おたがい","おたく","おだやか","おちつく","おっと","おつり","おでかけ","おとしもの","おとなしい","おどり","おどろかす","おばさん","おまいり","おめでとう","おもいで","おもう","おもたい","おもちゃ","おやつ","おやゆび","およぼす","おらんだ","おろす","おんがく","おんけい","おんしゃ","おんせん","おんだん","おんちゅう","おんどけい","かあつ","かいが","がいき","がいけん","がいこう","かいさつ","かいしゃ","かいすいよく","かいぜん","かいぞうど","かいつう","かいてん","かいとう","かいふく","がいへき","かいほう","かいよう","がいらい","かいわ","かえる","かおり","かかえる","かがく","かがし","かがみ","かくご","かくとく","かざる","がぞう","かたい","かたち","がちょう","がっきゅう","がっこう","がっさん","がっしょう","かなざわし","かのう","がはく","かぶか","かほう","かほご","かまう","かまぼこ","かめれおん","かゆい","かようび","からい","かるい","かろう","かわく","かわら","がんか","かんけい","かんこう","かんしゃ","かんそう","かんたん","かんち","がんばる","きあい","きあつ","きいろ","ぎいん","きうい","きうん","きえる","きおう","きおく","きおち","きおん","きかい","きかく","きかんしゃ","ききて","きくばり","きくらげ","きけんせい","きこう","きこえる","きこく","きさい","きさく","きさま","きさらぎ","ぎじかがく","ぎしき","ぎじたいけん","ぎじにってい","ぎじゅつしゃ","きすう","きせい","きせき","きせつ","きそう","きぞく","きぞん","きたえる","きちょう","きつえん","ぎっちり","きつつき","きつね","きてい","きどう","きどく","きない","きなが","きなこ","きぬごし","きねん","きのう","きのした","きはく","きびしい","きひん","きふく","きぶん","きぼう","きほん","きまる","きみつ","きむずかしい","きめる","きもだめし","きもち","きもの","きゃく","きやく","ぎゅうにく","きよう","きょうりゅう","きらい","きらく","きりん","きれい","きれつ","きろく","ぎろん","きわめる","ぎんいろ","きんかくじ","きんじょ","きんようび","ぐあい","くいず","くうかん","くうき","くうぐん","くうこう","ぐうせい","くうそう","ぐうたら","くうふく","くうぼ","くかん","くきょう","くげん","ぐこう","くさい","くさき","くさばな","くさる","くしゃみ","くしょう","くすのき","くすりゆび","くせげ","くせん","ぐたいてき","くださる","くたびれる","くちこみ","くちさき","くつした","ぐっすり","くつろぐ","くとうてん","くどく","くなん","くねくね","くのう","くふう","くみあわせ","くみたてる","くめる","くやくしょ","くらす","くらべる","くるま","くれる","くろう","くわしい","ぐんかん","ぐんしょく","ぐんたい","ぐんて","けあな","けいかく","けいけん","けいこ","けいさつ","げいじゅつ","けいたい","げいのうじん","けいれき","けいろ","けおとす","けおりもの","げきか","げきげん","げきだん","げきちん","げきとつ","げきは","げきやく","げこう","げこくじょう","げざい","けさき","げざん","けしき","けしごむ","けしょう","げすと","けたば","けちゃっぷ","けちらす","けつあつ","けつい","けつえき","けっこん","けつじょ","けっせき","けってい","けつまつ","げつようび","げつれい","けつろん","げどく","けとばす","けとる","けなげ","けなす","けなみ","けぬき","げねつ","けねん","けはい","げひん","けぶかい","げぼく","けまり","けみかる","けむし","けむり","けもの","けらい","けろけろ","けわしい","けんい","けんえつ","けんお","けんか","げんき","けんげん","けんこう","けんさく","けんしゅう","けんすう","げんそう","けんちく","けんてい","けんとう","けんない","けんにん","げんぶつ","けんま","けんみん","けんめい","けんらん","けんり","こあくま","こいぬ","こいびと","ごうい","こうえん","こうおん","こうかん","ごうきゅう","ごうけい","こうこう","こうさい","こうじ","こうすい","ごうせい","こうそく","こうたい","こうちゃ","こうつう","こうてい","こうどう","こうない","こうはい","ごうほう","ごうまん","こうもく","こうりつ","こえる","こおり","ごかい","ごがつ","ごかん","こくご","こくさい","こくとう","こくない","こくはく","こぐま","こけい","こける","ここのか","こころ","こさめ","こしつ","こすう","こせい","こせき","こぜん","こそだて","こたい","こたえる","こたつ","こちょう","こっか","こつこつ","こつばん","こつぶ","こてい","こてん","ことがら","ことし","ことば","ことり","こなごな","こねこね","このまま","このみ","このよ","ごはん","こひつじ","こふう","こふん","こぼれる","ごまあぶら","こまかい","ごますり","こまつな","こまる","こむぎこ","こもじ","こもち","こもの","こもん","こやく","こやま","こゆう","こゆび","こよい","こよう","こりる","これくしょん","ころっけ","こわもて","こわれる","こんいん","こんかい","こんき","こんしゅう","こんすい","こんだて","こんとん","こんなん","こんびに","こんぽん","こんまけ","こんや","こんれい","こんわく","ざいえき","さいかい","さいきん","ざいげん","ざいこ","さいしょ","さいせい","ざいたく","ざいちゅう","さいてき","ざいりょう","さうな","さかいし","さがす","さかな","さかみち","さがる","さぎょう","さくし","さくひん","さくら","さこく","さこつ","さずかる","ざせき","さたん","さつえい","ざつおん","ざっか","ざつがく","さっきょく","ざっし","さつじん","ざっそう","さつたば","さつまいも","さてい","さといも","さとう","さとおや","さとし","さとる","さのう","さばく","さびしい","さべつ","さほう","さほど","さます","さみしい","さみだれ","さむけ","さめる","さやえんどう","さゆう","さよう","さよく","さらだ","ざるそば","さわやか","さわる","さんいん","さんか","さんきゃく","さんこう","さんさい","ざんしょ","さんすう","さんせい","さんそ","さんち","さんま","さんみ","さんらん","しあい","しあげ","しあさって","しあわせ","しいく","しいん","しうち","しえい","しおけ","しかい","しかく","じかん","しごと","しすう","じだい","したうけ","したぎ","したて","したみ","しちょう","しちりん","しっかり","しつじ","しつもん","してい","してき","してつ","じてん","じどう","しなぎれ","しなもの","しなん","しねま","しねん","しのぐ","しのぶ","しはい","しばかり","しはつ","しはらい","しはん","しひょう","しふく","じぶん","しへい","しほう","しほん","しまう","しまる","しみん","しむける","じむしょ","しめい","しめる","しもん","しゃいん","しゃうん","しゃおん","じゃがいも","しやくしょ","しゃくほう","しゃけん","しゃこ","しゃざい","しゃしん","しゃせん","しゃそう","しゃたい","しゃちょう","しゃっきん","じゃま","しゃりん","しゃれい","じゆう","じゅうしょ","しゅくはく","じゅしん","しゅっせき","しゅみ","しゅらば","じゅんばん","しょうかい","しょくたく","しょっけん","しょどう","しょもつ","しらせる","しらべる","しんか","しんこう","じんじゃ","しんせいじ","しんちく","しんりん","すあげ","すあし","すあな","ずあん","すいえい","すいか","すいとう","ずいぶん","すいようび","すうがく","すうじつ","すうせん","すおどり","すきま","すくう","すくない","すける","すごい","すこし","ずさん","すずしい","すすむ","すすめる","すっかり","ずっしり","ずっと","すてき","すてる","すねる","すのこ","すはだ","すばらしい","ずひょう","ずぶぬれ","すぶり","すふれ","すべて","すべる","ずほう","すぼん","すまい","すめし","すもう","すやき","すらすら","するめ","すれちがう","すろっと","すわる","すんぜん","すんぽう","せあぶら","せいかつ","せいげん","せいじ","せいよう","せおう","せかいかん","せきにん","せきむ","せきゆ","せきらんうん","せけん","せこう","せすじ","せたい","せたけ","せっかく","せっきゃく","ぜっく","せっけん","せっこつ","せっさたくま","せつぞく","せつだん","せつでん","せっぱん","せつび","せつぶん","せつめい","せつりつ","せなか","せのび","せはば","せびろ","せぼね","せまい","せまる","せめる","せもたれ","せりふ","ぜんあく","せんい","せんえい","せんか","せんきょ","せんく","せんげん","ぜんご","せんさい","せんしゅ","せんすい","せんせい","せんぞ","せんたく","せんちょう","せんてい","せんとう","せんぬき","せんねん","せんぱい","ぜんぶ","ぜんぽう","せんむ","せんめんじょ","せんもん","せんやく","せんゆう","せんよう","ぜんら","ぜんりゃく","せんれい","せんろ","そあく","そいとげる","そいね","そうがんきょう","そうき","そうご","そうしん","そうだん","そうなん","そうび","そうめん","そうり","そえもの","そえん","そがい","そげき","そこう","そこそこ","そざい","そしな","そせい","そせん","そそぐ","そだてる","そつう","そつえん","そっかん","そつぎょう","そっけつ","そっこう","そっせん","そっと","そとがわ","そとづら","そなえる","そなた","そふぼ","そぼく","そぼろ","そまつ","そまる","そむく","そむりえ","そめる","そもそも","そよかぜ","そらまめ","そろう","そんかい","そんけい","そんざい","そんしつ","そんぞく","そんちょう","ぞんび","ぞんぶん","そんみん","たあい","たいいん","たいうん","たいえき","たいおう","だいがく","たいき","たいぐう","たいけん","たいこ","たいざい","だいじょうぶ","だいすき","たいせつ","たいそう","だいたい","たいちょう","たいてい","だいどころ","たいない","たいねつ","たいのう","たいはん","だいひょう","たいふう","たいへん","たいほ","たいまつばな","たいみんぐ","たいむ","たいめん","たいやき","たいよう","たいら","たいりょく","たいる","たいわん","たうえ","たえる","たおす","たおる","たおれる","たかい","たかね","たきび","たくさん","たこく","たこやき","たさい","たしざん","だじゃれ","たすける","たずさわる","たそがれ","たたかう","たたく","ただしい","たたみ","たちばな","だっかい","だっきゃく","だっこ","だっしゅつ","だったい","たてる","たとえる","たなばた","たにん","たぬき","たのしみ","たはつ","たぶん","たべる","たぼう","たまご","たまる","だむる","ためいき","ためす","ためる","たもつ","たやすい","たよる","たらす","たりきほんがん","たりょう","たりる","たると","たれる","たれんと","たろっと","たわむれる","だんあつ","たんい","たんおん","たんか","たんき","たんけん","たんご","たんさん","たんじょうび","だんせい","たんそく","たんたい","だんち","たんてい","たんとう","だんな","たんにん","だんねつ","たんのう","たんぴん","だんぼう","たんまつ","たんめい","だんれつ","だんろ","だんわ","ちあい","ちあん","ちいき","ちいさい","ちえん","ちかい","ちから","ちきゅう","ちきん","ちけいず","ちけん","ちこく","ちさい","ちしき","ちしりょう","ちせい","ちそう","ちたい","ちたん","ちちおや","ちつじょ","ちてき","ちてん","ちぬき","ちぬり","ちのう","ちひょう","ちへいせん","ちほう","ちまた","ちみつ","ちみどろ","ちめいど","ちゃんこなべ","ちゅうい","ちゆりょく","ちょうし","ちょさくけん","ちらし","ちらみ","ちりがみ","ちりょう","ちるど","ちわわ","ちんたい","ちんもく","ついか","ついたち","つうか","つうじょう","つうはん","つうわ","つかう","つかれる","つくね","つくる","つけね","つける","つごう","つたえる","つづく","つつじ","つつむ","つとめる","つながる","つなみ","つねづね","つのる","つぶす","つまらない","つまる","つみき","つめたい","つもり","つもる","つよい","つるぼ","つるみく","つわもの","つわり","てあし","てあて","てあみ","ていおん","ていか","ていき","ていけい","ていこく","ていさつ","ていし","ていせい","ていたい","ていど","ていねい","ていひょう","ていへん","ていぼう","てうち","ておくれ","てきとう","てくび","でこぼこ","てさぎょう","てさげ","てすり","てそう","てちがい","てちょう","てつがく","てつづき","でっぱ","てつぼう","てつや","でぬかえ","てぬき","てぬぐい","てのひら","てはい","てぶくろ","てふだ","てほどき","てほん","てまえ","てまきずし","てみじか","てみやげ","てらす","てれび","てわけ","てわたし","でんあつ","てんいん","てんかい","てんき","てんぐ","てんけん","てんごく","てんさい","てんし","てんすう","でんち","てんてき","てんとう","てんない","てんぷら","てんぼうだい","てんめつ","てんらんかい","でんりょく","でんわ","どあい","といれ","どうかん","とうきゅう","どうぐ","とうし","とうむぎ","とおい","とおか","とおく","とおす","とおる","とかい","とかす","ときおり","ときどき","とくい","とくしゅう","とくてん","とくに","とくべつ","とけい","とける","とこや","とさか","としょかん","とそう","とたん","とちゅう","とっきゅう","とっくん","とつぜん","とつにゅう","とどける","ととのえる","とない","となえる","となり","とのさま","とばす","どぶがわ","とほう","とまる","とめる","ともだち","ともる","どようび","とらえる","とんかつ","どんぶり","ないかく","ないこう","ないしょ","ないす","ないせん","ないそう","なおす","ながい","なくす","なげる","なこうど","なさけ","なたでここ","なっとう","なつやすみ","ななおし","なにごと","なにもの","なにわ","なのか","なふだ","なまいき","なまえ","なまみ","なみだ","なめらか","なめる","なやむ","ならう","ならび","ならぶ","なれる","なわとび","なわばり","にあう","にいがた","にうけ","におい","にかい","にがて","にきび","にくしみ","にくまん","にげる","にさんかたんそ","にしき","にせもの","にちじょう","にちようび","にっか","にっき","にっけい","にっこう","にっさん","にっしょく","にっすう","にっせき","にってい","になう","にほん","にまめ","にもつ","にやり","にゅういん","にりんしゃ","にわとり","にんい","にんか","にんき","にんげん","にんしき","にんずう","にんそう","にんたい","にんち","にんてい","にんにく","にんぷ","にんまり","にんむ","にんめい","にんよう","ぬいくぎ","ぬかす","ぬぐいとる","ぬぐう","ぬくもり","ぬすむ","ぬまえび","ぬめり","ぬらす","ぬんちゃく","ねあげ","ねいき","ねいる","ねいろ","ねぐせ","ねくたい","ねくら","ねこぜ","ねこむ","ねさげ","ねすごす","ねそべる","ねだん","ねつい","ねっしん","ねつぞう","ねったいぎょ","ねぶそく","ねふだ","ねぼう","ねほりはほり","ねまき","ねまわし","ねみみ","ねむい","ねむたい","ねもと","ねらう","ねわざ","ねんいり","ねんおし","ねんかん","ねんきん","ねんぐ","ねんざ","ねんし","ねんちゃく","ねんど","ねんぴ","ねんぶつ","ねんまつ","ねんりょう","ねんれい","のいず","のおづま","のがす","のきなみ","のこぎり","のこす","のこる","のせる","のぞく","のぞむ","のたまう","のちほど","のっく","のばす","のはら","のべる","のぼる","のみもの","のやま","のらいぬ","のらねこ","のりもの","のりゆき","のれん","のんき","ばあい","はあく","ばあさん","ばいか","ばいく","はいけん","はいご","はいしん","はいすい","はいせん","はいそう","はいち","ばいばい","はいれつ","はえる","はおる","はかい","ばかり","はかる","はくしゅ","はけん","はこぶ","はさみ","はさん","はしご","ばしょ","はしる","はせる","ぱそこん","はそん","はたん","はちみつ","はつおん","はっかく","はづき","はっきり","はっくつ","はっけん","はっこう","はっさん","はっしん","はったつ","はっちゅう","はってん","はっぴょう","はっぽう","はなす","はなび","はにかむ","はぶらし","はみがき","はむかう","はめつ","はやい","はやし","はらう","はろうぃん","はわい","はんい","はんえい","はんおん","はんかく","はんきょう","ばんぐみ","はんこ","はんしゃ","はんすう","はんだん","ぱんち","ぱんつ","はんてい","はんとし","はんのう","はんぱ","はんぶん","はんぺん","はんぼうき","はんめい","はんらん","はんろん","ひいき","ひうん","ひえる","ひかく","ひかり","ひかる","ひかん","ひくい","ひけつ","ひこうき","ひこく","ひさい","ひさしぶり","ひさん","びじゅつかん","ひしょ","ひそか","ひそむ","ひたむき","ひだり","ひたる","ひつぎ","ひっこし","ひっし","ひつじゅひん","ひっす","ひつぜん","ぴったり","ぴっちり","ひつよう","ひてい","ひとごみ","ひなまつり","ひなん","ひねる","ひはん","ひびく","ひひょう","ひほう","ひまわり","ひまん","ひみつ","ひめい","ひめじし","ひやけ","ひやす","ひよう","びょうき","ひらがな","ひらく","ひりつ","ひりょう","ひるま","ひるやすみ","ひれい","ひろい","ひろう","ひろき","ひろゆき","ひんかく","ひんけつ","ひんこん","ひんしゅ","ひんそう","ぴんち","ひんぱん","びんぼう","ふあん","ふいうち","ふうけい","ふうせん","ぷうたろう","ふうとう","ふうふ","ふえる","ふおん","ふかい","ふきん","ふくざつ","ふくぶくろ","ふこう","ふさい","ふしぎ","ふじみ","ふすま","ふせい","ふせぐ","ふそく","ぶたにく","ふたん","ふちょう","ふつう","ふつか","ふっかつ","ふっき","ふっこく","ぶどう","ふとる","ふとん","ふのう","ふはい","ふひょう","ふへん","ふまん","ふみん","ふめつ","ふめん","ふよう","ふりこ","ふりる","ふるい","ふんいき","ぶんがく","ぶんぐ","ふんしつ","ぶんせき","ふんそう","ぶんぽう","へいあん","へいおん","へいがい","へいき","へいげん","へいこう","へいさ","へいしゃ","へいせつ","へいそ","へいたく","へいてん","へいねつ","へいわ","へきが","へこむ","べにいろ","べにしょうが","へらす","へんかん","べんきょう","べんごし","へんさい","へんたい","べんり","ほあん","ほいく","ぼうぎょ","ほうこく","ほうそう","ほうほう","ほうもん","ほうりつ","ほえる","ほおん","ほかん","ほきょう","ぼきん","ほくろ","ほけつ","ほけん","ほこう","ほこる","ほしい","ほしつ","ほしゅ","ほしょう","ほせい","ほそい","ほそく","ほたて","ほたる","ぽちぶくろ","ほっきょく","ほっさ","ほったん","ほとんど","ほめる","ほんい","ほんき","ほんけ","ほんしつ","ほんやく","まいにち","まかい","まかせる","まがる","まける","まこと","まさつ","まじめ","ますく","まぜる","まつり","まとめ","まなぶ","まぬけ","まねく","まほう","まもる","まゆげ","まよう","まろやか","まわす","まわり","まわる","まんが","まんきつ","まんぞく","まんなか","みいら","みうち","みえる","みがく","みかた","みかん","みけん","みこん","みじかい","みすい","みすえる","みせる","みっか","みつかる","みつける","みてい","みとめる","みなと","みなみかさい","みねらる","みのう","みのがす","みほん","みもと","みやげ","みらい","みりょく","みわく","みんか","みんぞく","むいか","むえき","むえん","むかい","むかう","むかえ","むかし","むぎちゃ","むける","むげん","むさぼる","むしあつい","むしば","むじゅん","むしろ","むすう","むすこ","むすぶ","むすめ","むせる","むせん","むちゅう","むなしい","むのう","むやみ","むよう","むらさき","むりょう","むろん","めいあん","めいうん","めいえん","めいかく","めいきょく","めいさい","めいし","めいそう","めいぶつ","めいれい","めいわく","めぐまれる","めざす","めした","めずらしい","めだつ","めまい","めやす","めんきょ","めんせき","めんどう","もうしあげる","もうどうけん","もえる","もくし","もくてき","もくようび","もちろん","もどる","もらう","もんく","もんだい","やおや","やける","やさい","やさしい","やすい","やすたろう","やすみ","やせる","やそう","やたい","やちん","やっと","やっぱり","やぶる","やめる","ややこしい","やよい","やわらかい","ゆうき","ゆうびんきょく","ゆうべ","ゆうめい","ゆけつ","ゆしゅつ","ゆせん","ゆそう","ゆたか","ゆちゃく","ゆでる","ゆにゅう","ゆびわ","ゆらい","ゆれる","ようい","ようか","ようきゅう","ようじ","ようす","ようちえん","よかぜ","よかん","よきん","よくせい","よくぼう","よけい","よごれる","よさん","よしゅう","よそう","よそく","よっか","よてい","よどがわく","よねつ","よやく","よゆう","よろこぶ","よろしい","らいう","らくがき","らくご","らくさつ","らくだ","らしんばん","らせん","らぞく","らたい","らっか","られつ","りえき","りかい","りきさく","りきせつ","りくぐん","りくつ","りけん","りこう","りせい","りそう","りそく","りてん","りねん","りゆう","りゅうがく","りよう","りょうり","りょかん","りょくちゃ","りょこう","りりく","りれき","りろん","りんご","るいけい","るいさい","るいじ","るいせき","るすばん","るりがわら","れいかん","れいぎ","れいせい","れいぞうこ","れいとう","れいぼう","れきし","れきだい","れんあい","れんけい","れんこん","れんさい","れんしゅう","れんぞく","れんらく","ろうか","ろうご","ろうじん","ろうそく","ろくが","ろこつ","ろじうら","ろしゅつ","ろせん","ろてん","ろめん","ろれつ","ろんぎ","ろんぱ","ろんぶん","ろんり","わかす","わかめ","わかやま","わかれる","わしつ","わじまし","わすれもの","わらう","われる"]["가격","가끔","가난","가능","가득","가르침","가뭄","가방","가상","가슴","가운데","가을","가이드","가입","가장","가정","가족","가죽","각오","각자","간격","간부","간섭","간장","간접","간판","갈등","갈비","갈색","갈증","감각","감기","감소","감수성","감자","감정","갑자기","강남","강당","강도","강력히","강변","강북","강사","강수량","강아지","강원도","강의","강제","강조","같이","개구리","개나리","개방","개별","개선","개성","개인","객관적","거실","거액","거울","거짓","거품","걱정","건강","건물","건설","건조","건축","걸음","검사","검토","게시판","게임","겨울","견해","결과","결국","결론","결석","결승","결심","결정","결혼","경계","경고","경기","경력","경복궁","경비","경상도","경영","경우","경쟁","경제","경주","경찰","경치","경향","경험","계곡","계단","계란","계산","계속","계약","계절","계층","계획","고객","고구려","고궁","고급","고등학생","고무신","고민","고양이","고장","고전","고집","고춧가루","고통","고향","곡식","골목","골짜기","골프","공간","공개","공격","공군","공급","공기","공동","공무원","공부","공사","공식","공업","공연","공원","공장","공짜","공책","공통","공포","공항","공휴일","과목","과일","과장","과정","과학","관객","관계","관광","관념","관람","관련","관리","관습","관심","관점","관찰","광경","광고","광장","광주","괴로움","굉장히","교과서","교문","교복","교실","교양","교육","교장","교직","교통","교환","교훈","구경","구름","구멍","구별","구분","구석","구성","구속","구역","구입","구청","구체적","국가","국기","국내","국립","국물","국민","국수","국어","국왕","국적","국제","국회","군대","군사","군인","궁극적","권리","권위","권투","귀국","귀신","규정","규칙","균형","그날","그냥","그늘","그러나","그룹","그릇","그림","그제서야","그토록","극복","극히","근거","근교","근래","근로","근무","근본","근원","근육","근처","글씨","글자","금강산","금고","금년","금메달","금액","금연","금요일","금지","긍정적","기간","기관","기념","기능","기독교","기둥","기록","기름","기법","기본","기분","기쁨","기숙사","기술","기억","기업","기온","기운","기원","기적","기준","기침","기혼","기획","긴급","긴장","길이","김밥","김치","김포공항","깍두기","깜빡","깨달음","깨소금","껍질","꼭대기","꽃잎","나들이","나란히","나머지","나물","나침반","나흘","낙엽","난방","날개","날씨","날짜","남녀","남대문","남매","남산","남자","남편","남학생","낭비","낱말","내년","내용","내일","냄비","냄새","냇물","냉동","냉면","냉방","냉장고","넥타이","넷째","노동","노란색","노력","노인","녹음","녹차","녹화","논리","논문","논쟁","놀이","농구","농담","농민","농부","농업","농장","농촌","높이","눈동자","눈물","눈썹","뉴욕","느낌","늑대","능동적","능력","다방","다양성","다음","다이어트","다행","단계","단골","단독","단맛","단순","단어","단위","단점","단체","단추","단편","단풍","달걀","달러","달력","달리","닭고기","담당","담배","담요","담임","답변","답장","당근","당분간","당연히","당장","대규모","대낮","대단히","대답","대도시","대략","대량","대륙","대문","대부분","대신","대응","대장","대전","대접","대중","대책","대출","대충","대통령","대학","대한민국","대합실","대형","덩어리","데이트","도대체","도덕","도둑","도망","도서관","도심","도움","도입","도자기","도저히","도전","도중","도착","독감","독립","독서","독일","독창적","동화책","뒷모습","뒷산","딸아이","마누라","마늘","마당","마라톤","마련","마무리","마사지","마약","마요네즈","마을","마음","마이크","마중","마지막","마찬가지","마찰","마흔","막걸리","막내","막상","만남","만두","만세","만약","만일","만점","만족","만화","많이","말기","말씀","말투","맘대로","망원경","매년","매달","매력","매번","매스컴","매일","매장","맥주","먹이","먼저","먼지","멀리","메일","며느리","며칠","면담","멸치","명단","명령","명예","명의","명절","명칭","명함","모금","모니터","모델","모든","모범","모습","모양","모임","모조리","모집","모퉁이","목걸이","목록","목사","목소리","목숨","목적","목표","몰래","몸매","몸무게","몸살","몸속","몸짓","몸통","몹시","무관심","무궁화","무더위","무덤","무릎","무슨","무엇","무역","무용","무조건","무지개","무척","문구","문득","문법","문서","문제","문학","문화","물가","물건","물결","물고기","물론","물리학","물음","물질","물체","미국","미디어","미사일","미술","미역","미용실","미움","미인","미팅","미혼","민간","민족","민주","믿음","밀가루","밀리미터","밑바닥","바가지","바구니","바나나","바늘","바닥","바닷가","바람","바이러스","바탕","박물관","박사","박수","반대","반드시","반말","반발","반성","반응","반장","반죽","반지","반찬","받침","발가락","발걸음","발견","발달","발레","발목","발바닥","발생","발음","발자국","발전","발톱","발표","밤하늘","밥그릇","밥맛","밥상","밥솥","방금","방면","방문","방바닥","방법","방송","방식","방안","방울","방지","방학","방해","방향","배경","배꼽","배달","배드민턴","백두산","백색","백성","백인","백제","백화점","버릇","버섯","버튼","번개","번역","번지","번호","벌금","벌레","벌써","범위","범인","범죄","법률","법원","법적","법칙","베이징","벨트","변경","변동","변명","변신","변호사","변화","별도","별명","별일","병실","병아리","병원","보관","보너스","보라색","보람","보름","보상","보안","보자기","보장","보전","보존","보통","보편적","보험","복도","복사","복숭아","복습","볶음","본격적","본래","본부","본사","본성","본인","본질","볼펜","봉사","봉지","봉투","부근","부끄러움","부담","부동산","부문","부분","부산","부상","부엌","부인","부작용","부장","부정","부족","부지런히","부친","부탁","부품","부회장","북부","북한","분노","분량","분리","분명","분석","분야","분위기","분필","분홍색","불고기","불과","불교","불꽃","불만","불법","불빛","불안","불이익","불행","브랜드","비극","비난","비닐","비둘기","비디오","비로소","비만","비명","비밀","비바람","비빔밥","비상","비용","비율","비중","비타민","비판","빌딩","빗물","빗방울","빗줄기","빛깔","빨간색","빨래","빨리","사건","사계절","사나이","사냥","사람","사랑","사립","사모님","사물","사방","사상","사생활","사설","사슴","사실","사업","사용","사월","사장","사전","사진","사촌","사춘기","사탕","사투리","사흘","산길","산부인과","산업","산책","살림","살인","살짝","삼계탕","삼국","삼십","삼월","삼촌","상관","상금","상대","상류","상반기","상상","상식","상업","상인","상자","상점","상처","상추","상태","상표","상품","상황","새벽","색깔","색연필","생각","생명","생물","생방송","생산","생선","생신","생일","생활","서랍","서른","서명","서민","서비스","서양","서울","서적","서점","서쪽","서클","석사","석유","선거","선물","선배","선생","선수","선원","선장","선전","선택","선풍기","설거지","설날","설렁탕","설명","설문","설사","설악산","설치","설탕","섭씨","성공","성당","성명","성별","성인","성장","성적","성질","성함","세금","세미나","세상","세월","세종대왕","세탁","센터","센티미터","셋째","소규모","소극적","소금","소나기","소년","소득","소망","소문","소설","소속","소아과","소용","소원","소음","소중히","소지품","소질","소풍","소형","속담","속도","속옷","손가락","손길","손녀","손님","손등","손목","손뼉","손실","손질","손톱","손해","솔직히","솜씨","송아지","송이","송편","쇠고기","쇼핑","수건","수년","수단","수돗물","수동적","수면","수명","수박","수상","수석","수술","수시로","수업","수염","수영","수입","수준","수집","수출","수컷","수필","수학","수험생","수화기","숙녀","숙소","숙제","순간","순서","순수","순식간","순위","숟가락","술병","술집","숫자","스님","스물","스스로","스승","스웨터","스위치","스케이트","스튜디오","스트레스","스포츠","슬쩍","슬픔","습관","습기","승객","승리","승부","승용차","승진","시각","시간","시골","시금치","시나리오","시댁","시리즈","시멘트","시민","시부모","시선","시설","시스템","시아버지","시어머니","시월","시인","시일","시작","시장","시절","시점","시중","시즌","시집","시청","시합","시험","식구","식기","식당","식량","식료품","식물","식빵","식사","식생활","식초","식탁","식품","신고","신규","신념","신문","신발","신비","신사","신세","신용","신제품","신청","신체","신화","실감","실내","실력","실례","실망","실수","실습","실시","실장","실정","실질적","실천","실체","실컷","실태","실패","실험","실현","심리","심부름","심사","심장","심정","심판","쌍둥이","씨름","씨앗","아가씨","아나운서","아드님","아들","아쉬움","아스팔트","아시아","아울러","아저씨","아줌마","아직","아침","아파트","아프리카","아픔","아홉","아흔","악기","악몽","악수","안개","안경","안과","안내","안녕","안동","안방","안부","안주","알루미늄","알코올","암시","암컷","압력","앞날","앞문","애인","애정","액수","앨범","야간","야단","야옹","약간","약국","약속","약수","약점","약품","약혼녀","양념","양력","양말","양배추","양주","양파","어둠","어려움","어른","어젯밤","어쨌든","어쩌다가","어쩐지","언니","언덕","언론","언어","얼굴","얼른","얼음","얼핏","엄마","업무","업종","업체","엉덩이","엉망","엉터리","엊그제","에너지","에어컨","엔진","여건","여고생","여관","여군","여권","여대생","여덟","여동생","여든","여론","여름","여섯","여성","여왕","여인","여전히","여직원","여학생","여행","역사","역시","역할","연결","연구","연극","연기","연락","연설","연세","연속","연습","연애","연예인","연인","연장","연주","연출","연필","연합","연휴","열기","열매","열쇠","열심히","열정","열차","열흘","염려","엽서","영국","영남","영상","영양","영역","영웅","영원히","영하","영향","영혼","영화","옆구리","옆방","옆집","예감","예금","예방","예산","예상","예선","예술","예습","예식장","예약","예전","예절","예정","예컨대","옛날","오늘","오락","오랫동안","오렌지","오로지","오른발","오븐","오십","오염","오월","오전","오직","오징어","오페라","오피스텔","오히려","옥상","옥수수","온갖","온라인","온몸","온종일","온통","올가을","올림픽","올해","옷차림","와이셔츠","와인","완성","완전","왕비","왕자","왜냐하면","왠지","외갓집","외국","외로움","외삼촌","외출","외침","외할머니","왼발","왼손","왼쪽","요금","요일","요즘","요청","용기","용서","용어","우산","우선","우승","우연히","우정","우체국","우편","운동","운명","운반","운전","운행","울산","울음","움직임","웃어른","웃음","워낙","원고","원래","원서","원숭이","원인","원장","원피스","월급","월드컵","월세","월요일","웨이터","위반","위법","위성","위원","위험","위협","윗사람","유난히","유럽","유명","유물","유산","유적","유치원","유학","유행","유형","육군","육상","육십","육체","은행","음력","음료","음반","음성","음식","음악","음주","의견","의논","의문","의복","의식","의심","의외로","의욕","의원","의학","이것","이곳","이념","이놈","이달","이대로","이동","이렇게","이력서","이론적","이름","이민","이발소","이별","이불","이빨","이상","이성","이슬","이야기","이용","이웃","이월","이윽고","이익","이전","이중","이튿날","이틀","이혼","인간","인격","인공","인구","인근","인기","인도","인류","인물","인생","인쇄","인연","인원","인재","인종","인천","인체","인터넷","인하","인형","일곱","일기","일단","일대","일등","일반","일본","일부","일상","일생","일손","일요일","일월","일정","일종","일주일","일찍","일체","일치","일행","일회용","임금","임무","입대","입력","입맛","입사","입술","입시","입원","입장","입학","자가용","자격","자극","자동","자랑","자부심","자식","자신","자연","자원","자율","자전거","자정","자존심","자판","작가","작년","작성","작업","작용","작은딸","작품","잔디","잔뜩","잔치","잘못","잠깐","잠수함","잠시","잠옷","잠자리","잡지","장관","장군","장기간","장래","장례","장르","장마","장면","장모","장미","장비","장사","장소","장식","장애인","장인","장점","장차","장학금","재능","재빨리","재산","재생","재작년","재정","재채기","재판","재학","재활용","저것","저고리","저곳","저녁","저런","저렇게","저번","저울","저절로","저축","적극","적당히","적성","적용","적응","전개","전공","전기","전달","전라도","전망","전문","전반","전부","전세","전시","전용","전자","전쟁","전주","전철","전체","전통","전혀","전후","절대","절망","절반","절약","절차","점검","점수","점심","점원","점점","점차","접근","접시","접촉","젓가락","정거장","정도","정류장","정리","정말","정면","정문","정반대","정보","정부","정비","정상","정성","정오","정원","정장","정지","정치","정확히","제공","제과점","제대로","제목","제발","제법","제삿날","제안","제일","제작","제주도","제출","제품","제한","조각","조건","조금","조깅","조명","조미료","조상","조선","조용히","조절","조정","조직","존댓말","존재","졸업","졸음","종교","종로","종류","종소리","종업원","종종","종합","좌석","죄인","주관적","주름","주말","주머니","주먹","주문","주민","주방","주변","주식","주인","주일","주장","주전자","주택","준비","줄거리","줄기","줄무늬","중간","중계방송","중국","중년","중단","중독","중반","중부","중세","중소기업","중순","중앙","중요","중학교","즉석","즉시","즐거움","증가","증거","증권","증상","증세","지각","지갑","지경","지극히","지금","지급","지능","지름길","지리산","지방","지붕","지식","지역","지우개","지원","지적","지점","지진","지출","직선","직업","직원","직장","진급","진동","진로","진료","진리","진짜","진찰","진출","진통","진행","질문","질병","질서","짐작","집단","집안","집중","짜증","찌꺼기","차남","차라리","차량","차림","차별","차선","차츰","착각","찬물","찬성","참가","참기름","참새","참석","참여","참외","참조","찻잔","창가","창고","창구","창문","창밖","창작","창조","채널","채점","책가방","책방","책상","책임","챔피언","처벌","처음","천국","천둥","천장","천재","천천히","철도","철저히","철학","첫날","첫째","청년","청바지","청소","청춘","체계","체력","체온","체육","체중","체험","초등학생","초반","초밥","초상화","초순","초여름","초원","초저녁","초점","초청","초콜릿","촛불","총각","총리","총장","촬영","최근","최상","최선","최신","최악","최종","추석","추억","추진","추천","추측","축구","축소","축제","축하","출근","출발","출산","출신","출연","출입","출장","출판","충격","충고","충돌","충분히","충청도","취업","취직","취향","치약","친구","친척","칠십","칠월","칠판","침대","침묵","침실","칫솔","칭찬","카메라","카운터","칼국수","캐릭터","캠퍼스","캠페인","커튼","컨디션","컬러","컴퓨터","코끼리","코미디","콘서트","콜라","콤플렉스","콩나물","쾌감","쿠데타","크림","큰길","큰딸","큰소리","큰아들","큰어머니","큰일","큰절","클래식","클럽","킬로","타입","타자기","탁구","탁자","탄생","태권도","태양","태풍","택시","탤런트","터널","터미널","테니스","테스트","테이블","텔레비전","토론","토마토","토요일","통계","통과","통로","통신","통역","통일","통장","통제","통증","통합","통화","퇴근","퇴원","퇴직금","튀김","트럭","특급","특별","특성","특수","특징","특히","튼튼히","티셔츠","파란색","파일","파출소","판결","판단","판매","판사","팔십","팔월","팝송","패션","팩스","팩시밀리","팬티","퍼센트","페인트","편견","편의","편지","편히","평가","평균","평생","평소","평양","평일","평화","포스터","포인트","포장","포함","표면","표정","표준","표현","품목","품질","풍경","풍속","풍습","프랑스","프린터","플라스틱","피곤","피망","피아노","필름","필수","필요","필자","필통","핑계","하느님","하늘","하드웨어","하룻밤","하반기","하숙집","하순","하여튼","하지만","하천","하품","하필","학과","학교","학급","학기","학년","학력","학번","학부모","학비","학생","학술","학습","학용품","학원","학위","학자","학점","한계","한글","한꺼번에","한낮","한눈","한동안","한때","한라산","한마디","한문","한번","한복","한식","한여름","한쪽","할머니","할아버지","할인","함께","함부로","합격","합리적","항공","항구","항상","항의","해결","해군","해답","해당","해물","해석","해설","해수욕장","해안","핵심","핸드백","햄버거","햇볕","햇살","행동","행복","행사","행운","행위","향기","향상","향수","허락","허용","헬기","현관","현금","현대","현상","현실","현장","현재","현지","혈액","협력","형부","형사","형수","형식","형제","형태","형편","혜택","호기심","호남","호랑이","호박","호텔","호흡","혹시","홀로","홈페이지","홍보","홍수","홍차","화면","화분","화살","화요일","화장","화학","확보","확인","확장","확정","환갑","환경","환영","환율","환자","활기","활동","활발히","활용","활짝","회견","회관","회복","회색","회원","회장","회전","횟수","횡단보도","효율적","후반","후춧가루","훈련","훨씬","휴식","휴일","흉내","흐름","흑백","흑인","흔적","흔히","흥미","흥분","희곡","희망","희생","흰색","힘껏"]{"的":["chinese_simplified","chinese_traditional"],"一":["chinese_simplified","chinese_traditional"],"是":["chinese_simplified","chinese_traditional"],"在":["chinese_simplified","chinese_traditional"],"不":["chinese_simplified","chinese_traditional"],"了":["chinese_simplified","chinese_traditional"],"有":["chinese_simplified","chinese_traditional"],"和":["chinese_simplified","chinese_traditional"],"人":["chinese_simplified","chinese_traditional"],"这":["chinese_simplified"],"中":["chinese_simplified","chinese_traditional"],"大":["chinese_simplified","chinese_traditional"],"为":["chinese_simplified"],"上":["chinese_simplified","chinese_traditional"],"个":["chinese_simplified"],"国":["chinese_simplified"],"我":["chinese_simplified","chinese_traditional"],"以":["chinese_simplified","chinese_traditional"],"要":["chinese_simplified","chinese_traditional"],"他":["chinese_simplified","chinese_traditional"],"时":["chinese_simplified"],"来":["chinese_simplified"],"用":["chinese_simplified","chinese_traditional"],"们":["chinese_simplified"],"生":["chinese_simplified","chinese_traditional"],"到":["chinese_simplified","chinese_traditional"],"作":["chinese_simplified","chinese_traditional"],"地":["chinese_simplified","chinese_traditional"],"于":["chinese_simplified"],"出":["chinese_simplified","chinese_traditional"],"就":["chinese_simplified","chinese_traditional"],"分":["chinese_simplified","chinese_traditional"],"对":["chinese_simplified"],"成":["chinese_simplified","chinese_traditional"],"会":["chinese_simplified"],"可":["chinese_simplified","chinese_traditional"],"主":["chinese_simplified","chinese_traditional"],"发":["chinese_simplified"],"年":["chinese_simplified","chinese_traditional"],"动":["chinese_simplified"],"同":["chinese_simplified","chinese_traditional"],"工":["chinese_simplified","chinese_traditional"],"也":["chinese_simplified","chinese_traditional"],"能":["chinese_simplified","chinese_traditional"],"下":["chinese_simplified","chinese_traditional"],"过":["chinese_simplified"],"子":["chinese_simplified","chinese_traditional"],"说":["chinese_simplified"],"产":["chinese_simplified"],"种":["chinese_simplified"],"面":["chinese_simplified","chinese_traditional"],"而":["chinese_simplified","chinese_traditional"],"方":["chinese_simplified","chinese_traditional"],"后":["chinese_simplified"],"多":["chinese_simplified","chinese_traditional"],"定":["chinese_simplified","chinese_traditional"],"行":["chinese_simplified","chinese_traditional"],"学":["chinese_simplified"],"法":["chinese_simplified","chinese_traditional"],"所":["chinese_simplified","chinese_traditional"],"民":["chinese_simplified","chinese_traditional"],"得":["chinese_simplified","chinese_traditional"],"经":["chinese_simplified"],"十":["chinese_simplified","chinese_traditional"],"三":["chinese_simplified","chinese_traditional"],"之":["chinese_simplified","chinese_traditional"],"进":["chinese_simplified"],"着":["chinese_simplified"],"等":["chinese_simplified","chinese_traditional"],"部":["chinese_simplified","chinese_traditional"],"度":["chinese_simplified","chinese_traditional"],"家":["chinese_simplified","chinese_traditional"],"电":["chinese_simplified"],"力":["chinese_simplified","chinese_traditional"],"里":["chinese_simplified"],"如":["chinese_simplified","chinese_traditional"],"水":["chinese_simplified","chinese_traditional"],"化":["chinese_simplified","chinese_traditional"],"高":["chinese_simplified","chinese_traditional"],"自":["chinese_simplified","chinese_traditional"],"二":["chinese_simplified","chinese_traditional"],"理":["chinese_simplified","chinese_traditional"],"起":["chinese_simplified","chinese_traditional"],"小":["chinese_simplified","chinese_traditional"],"物":["chinese_simplified","chinese_traditional"],"现":["chinese_simplified"],"实":["chinese_simplified"],"加":["chinese_simplified","chinese_traditional"],"量":["chinese_simplified","chinese_traditional"],"都":["chinese_simplified","chinese_traditional"],"两":["chinese_simplified"],"体":["chinese_simplified"],"制":["chinese_simplified","chinese_traditional"],"机":["chinese_simplified"],"当":["chinese_simplified"],"使":["chinese_simplified","chinese_traditional"],"点":["chinese_simplified"],"从":["chinese_simplified"],"业":["chinese_simplified"],"本":["chinese_simplified","chinese_traditional"],"去":["chinese_simplified","chinese_traditional"],"把":["chinese_simplified","chinese_traditional"],"性":["chinese_simplified","chinese_traditional"],"好":["chinese_simplified","chinese_traditional"],"应":["chinese_simplified"],"开":["chinese_simplified"],"它":["chinese_simplified","chinese_traditional"],"合":["chinese_simplified","chinese_traditional"],"还":["chinese_simplified"],"因":["chinese_simplified","chinese_traditional"],"由":["chinese_simplified","chinese_traditional"],"其":["chinese_simplified","chinese_traditional"],"些":["chinese_simplified","chinese_traditional"],"然":["chinese_simplified","chinese_traditional"],"前":["chinese_simplified","chinese_traditional"],"外":["chinese_simplified","chinese_traditional"],"天":["chinese_simplified","chinese_traditional"],"政":["chinese_simplified","chinese_traditional"],"四":["chinese_simplified","chinese_traditional"],"日":["chinese_simplified","chinese_traditional"],"那":["chinese_simplified","chinese_traditional"],"社":["chinese_simplified","chinese_traditional"],"义":["chinese_simplified"],"事":["chinese_simplified","chinese_traditional"],"平":["chinese_simplified","chinese_traditional"],"形":["chinese_simplified","chinese_traditional"],"相":["chinese_simplified","chinese_traditional"],"全":["chinese_simplified","chinese_traditional"],"表":["chinese_simplified","chinese_traditional"],"间":["chinese_simplified"],"样":["chinese_simplified"],"与":["chinese_simplified"],"关":["chinese_simplified"],"各":["chinese_simplified","chinese_traditional"],"重":["chinese_simplified","chinese_traditional"],"新":["chinese_simplified","chinese_traditional"],"线":["chinese_simplified"],"内":["chinese_simplified"],"数":["chinese_simplified"],"正":["chinese_simplified","chinese_traditional"],"心":["chinese_simplified","chinese_traditional"],"反":["chinese_simplified","chinese_traditional"],"你":["chinese_simplified","chinese_traditional"],"明":["chinese_simplified","chinese_traditional"],"看":["chinese_simplified","chinese_traditional"],"原":["chinese_simplified","chinese_traditional"],"又":["chinese_simplified","chinese_traditional"],"么":["chinese_simplified"],"利":["chinese_simplified","chinese_traditional"],"比":["chinese_simplified","chinese_traditional"],"或":["chinese_simplified","chinese_traditional"],"但":["chinese_simplified","chinese_traditional"],"质":["chinese_simplified"],"气":["chinese_simplified"],"第":["chinese_simplified","chinese_traditional"],"向":["chinese_simplified","chinese_traditional"],"道":["chinese_simplified","chinese_traditional"],"命":["chinese_simplified","chinese_traditional"],"此":["chinese_simplified","chinese_traditional"],"变":["chinese_simplified"],"条":["chinese_simplified"],"只":["chinese_simplified","chinese_traditional"],"没":["chinese_simplified"],"结":["chinese_simplified"],"解":["chinese_simplified","chinese_traditional"],"问":["chinese_simplified"],"意":["chinese_simplified","chinese_traditional"],"建":["chinese_simplified","chinese_traditional"],"月":["chinese_simplified","chinese_traditional"],"公":["chinese_simplified","chinese_traditional"],"无":["chinese_simplified"],"系":["chinese_simplified","chinese_traditional"],"军":["chinese_simplified"],"很":["chinese_simplified","chinese_traditional"],"情":["chinese_simplified","chinese_traditional"],"者":["chinese_simplified","chinese_traditional"],"最":["chinese_simplified","chinese_traditional"],"立":["chinese_simplified","chinese_traditional"],"代":["chinese_simplified","chinese_traditional"],"想":["chinese_simplified","chinese_traditional"],"已":["chinese_simplified","chinese_traditional"],"通":["chinese_simplified","chinese_traditional"],"并":["chinese_simplified"],"提":["chinese_simplified","chinese_traditional"],"直":["chinese_simplified","chinese_traditional"],"题":["chinese_simplified"],"党":["chinese_simplified"],"程":["chinese_simplified","chinese_traditional"],"展":["chinese_simplified","chinese_traditional"],"五":["chinese_simplified","chinese_traditional"],"果":["chinese_simplified","chinese_traditional"],"料":["chinese_simplified","chinese_traditional"],"象":["chinese_simplified","chinese_traditional"],"员":["chinese_simplified"],"革":["chinese_simplified","chinese_traditional"],"位":["chinese_simplified","chinese_traditional"],"入":["chinese_simplified","chinese_traditional"],"常":["chinese_simplified","chinese_traditional"],"文":["chinese_simplified","chinese_traditional"],"总":["chinese_simplified"],"次":["chinese_simplified","chinese_traditional"],"品":["chinese_simplified","chinese_traditional"],"式":["chinese_simplified","chinese_traditional"],"活":["chinese_simplified","chinese_traditional"],"设":["chinese_simplified"],"及":["chinese_simplified","chinese_traditional"],"管":["chinese_simplified","chinese_traditional"],"特":["chinese_simplified","chinese_traditional"],"件":["chinese_simplified","chinese_traditional"],"长":["chinese_simplified"],"求":["chinese_simplified","chinese_traditional"],"老":["chinese_simplified","chinese_traditional"],"头":["chinese_simplified"],"基":["chinese_simplified","chinese_traditional"],"资":["chinese_simplified"],"边":["chinese_simplified"],"流":["chinese_simplified","chinese_traditional"],"路":["chinese_simplified","chinese_traditional"],"级":["chinese_simplified"],"少":["chinese_simplified","chinese_traditional"],"图":["chinese_simplified"],"山":["chinese_simplified","chinese_traditional"],"统":["chinese_simplified"],"接":["chinese_simplified","chinese_traditional"],"知":["chinese_simplified","chinese_traditional"],"较":["chinese_simplified"],"将":["chinese_simplified"],"组":["chinese_simplified"],"见":["chinese_simplified"],"计":["chinese_simplified"],"别":["chinese_simplified"],"她":["chinese_simplified","chinese_traditional"],"手":["chinese_simplified","chinese_traditional"],"角":["chinese_simplified","chinese_traditional"],"期":["chinese_simplified","chinese_traditional"],"根":["chinese_simplified","chinese_traditional"],"论":["chinese_simplified"],"运":["chinese_simplified"],"农":["chinese_simplified"],"指":["chinese_simplified","chinese_traditional"],"几":["chinese_simplified"],"九":["chinese_simplified","chinese_traditional"],"区":["chinese_simplified"],"强":["chinese_simplified"],"放":["chinese_simplified","chinese_traditional"],"决":["chinese_simplified"],"西":["chinese_simplified","chinese_traditional"],"被":["chinese_simplified","chinese_traditional"],"干":["chinese_simplified"],"做":["chinese_simplified","chinese_traditional"],"必":["chinese_simplified","chinese_traditional"],"战":["chinese_simplified"],"先":["chinese_simplified","chinese_traditional"],"回":["chinese_simplified","chinese_traditional"],"则":["chinese_simplified"],"任":["chinese_simplified","chinese_traditional"],"取":["chinese_simplified","chinese_traditional"],"据":["chinese_simplified"],"处":["chinese_simplified"],"队":["chinese_simplified"],"南":["chinese_simplified","chinese_traditional"],"给":["chinese_simplified"],"色":["chinese_simplified","chinese_traditional"],"光":["chinese_simplified","chinese_traditional"],"门":["chinese_simplified"],"即":["chinese_simplified","chinese_traditional"],"保":["chinese_simplified","chinese_traditional"],"治":["chinese_simplified","chinese_traditional"],"北":["chinese_simplified","chinese_traditional"],"造":["chinese_simplified","chinese_traditional"],"百":["chinese_simplified","chinese_traditional"],"规":["chinese_simplified"],"热":["chinese_simplified"],"领":["chinese_simplified"],"七":["chinese_simplified","chinese_traditional"],"海":["chinese_simplified","chinese_traditional"],"口":["chinese_simplified","chinese_traditional"],"东":["chinese_simplified"],"导":["chinese_simplified"],"器":["chinese_simplified","chinese_traditional"],"压":["chinese_simplified"],"志":["chinese_simplified","chinese_traditional"],"世":["chinese_simplified","chinese_traditional"],"金":["chinese_simplified","chinese_traditional"],"增":["chinese_simplified","chinese_traditional"],"争":["chinese_simplified"],"济":["chinese_simplified"],"阶":["chinese_simplified"],"油":["chinese_simplified","chinese_traditional"],"思":["chinese_simplified","chinese_traditional"],"术":["chinese_simplified"],"极":["chinese_simplified"],"交":["chinese_simplified","chinese_traditional"],"受":["chinese_simplified","chinese_traditional"],"联":["chinese_simplified"],"什":["chinese_simplified","chinese_traditional"],"认":["chinese_simplified"],"六":["chinese_simplified","chinese_traditional"],"共":["chinese_simplified","chinese_traditional"],"权":["chinese_simplified"],"收":["chinese_simplified","chinese_traditional"],"证":["chinese_simplified"],"改":["chinese_simplified","chinese_traditional"],"清":["chinese_simplified","chinese_traditional"],"美":["chinese_simplified","chinese_traditional"],"再":["chinese_simplified","chinese_traditional"],"采":["chinese_simplified"],"转":["chinese_simplified"],"更":["chinese_simplified","chinese_traditional"],"单":["chinese_simplified"],"风":["chinese_simplified"],"切":["chinese_simplified","chinese_traditional"],"打":["chinese_simplified","chinese_traditional"],"白":["chinese_simplified","chinese_traditional"],"教":["chinese_simplified","chinese_traditional"],"速":["chinese_simplified","chinese_traditional"],"花":["chinese_simplified","chinese_traditional"],"带":["chinese_simplified"],"安":["chinese_simplified","chinese_traditional"],"场":["chinese_simplified"],"身":["chinese_simplified","chinese_traditional"],"车":["chinese_simplified"],"例":["chinese_simplified","chinese_traditional"],"真":["chinese_simplified","chinese_traditional"],"务":["chinese_simplified"],"具":["chinese_simplified","chinese_traditional"],"万":["chinese_simplified"],"每":["chinese_simplified","chinese_traditional"],"目":["chinese_simplified","chinese_traditional"],"至":["chinese_simplified","chinese_traditional"],"达":["chinese_simplified"],"走":["chinese_simplified","chinese_traditional"],"积":["chinese_simplified"],"示":["chinese_simplified","chinese_traditional"],"议":["chinese_simplified"],"声":["chinese_simplified"],"报":["chinese_simplified"],"斗":["chinese_simplified"],"完":["chinese_simplified","chinese_traditional"],"类":["chinese_simplified"],"八":["chinese_simplified","chinese_traditional"],"离":["chinese_simplified"],"华":["chinese_simplified"],"名":["chinese_simplified","chinese_traditional"],"确":["chinese_simplified"],"才":["chinese_simplified","chinese_traditional"],"科":["chinese_simplified","chinese_traditional"],"张":["chinese_simplified"],"信":["chinese_simplified","chinese_traditional"],"马":["chinese_simplified"],"节":["chinese_simplified"],"话":["chinese_simplified"],"米":["chinese_simplified","chinese_traditional"],"整":["chinese_simplified","chinese_traditional"],"空":["chinese_simplified","chinese_traditional"],"元":["chinese_simplified","chinese_traditional"],"况":["chinese_simplified"],"今":["chinese_simplified","chinese_traditional"],"集":["chinese_simplified","chinese_traditional"],"温":["chinese_simplified"],"传":["chinese_simplified"],"土":["chinese_simplified","chinese_traditional"],"许":["chinese_simplified"],"步":["chinese_simplified","chinese_traditional"],"群":["chinese_simplified","chinese_traditional"],"广":["chinese_simplified"],"石":["chinese_simplified","chinese_traditional"],"记":["chinese_simplified"],"需":["chinese_simplified","chinese_traditional"],"段":["chinese_simplified","chinese_traditional"],"研":["chinese_simplified","chinese_traditional"],"界":["chinese_simplified","chinese_traditional"],"拉":["chinese_simplified","chinese_traditional"],"林":["chinese_simplified","chinese_traditional"],"律":["chinese_simplified","chinese_traditional"],"叫":["chinese_simplified","chinese_traditional"],"且":["chinese_simplified","chinese_traditional"],"究":["chinese_simplified","chinese_traditional"],"观":["chinese_simplified"],"越":["chinese_simplified","chinese_traditional"],"织":["chinese_simplified"],"装":["chinese_simplified"],"影":["chinese_simplified","chinese_traditional"],"算":["chinese_simplified","chinese_traditional"],"低":["chinese_simplified","chinese_traditional"],"持":["chinese_simplified","chinese_traditional"],"音":["chinese_simplified","chinese_traditional"],"众":["chinese_simplified"],"书":["chinese_simplified"],"布":["chinese_simplified","chinese_traditional"],"复":["chinese_simplified","chinese_traditional"],"容":["chinese_simplified","chinese_traditional"],"儿":["chinese_simplified"],"须":["chinese_simplified"],"际":["chinese_simplified"],"商":["chinese_simplified","chinese_traditional"],"非":["chinese_simplified","chinese_traditional"],"验":["chinese_simplified"],"连":["chinese_simplified"],"断":["chinese_simplified"],"深":["chinese_simplified","chinese_traditional"],"难":["chinese_simplified"],"近":["chinese_simplified","chinese_traditional"],"矿":["chinese_simplified"],"千":["chinese_simplified","chinese_traditional"],"周":["chinese_simplified"],"委":["chinese_simplified","chinese_traditional"],"素":["chinese_simplified","chinese_traditional"],"技":["chinese_simplified","chinese_traditional"],"备":["chinese_simplified"],"半":["chinese_simplified","chinese_traditional"],"办":["chinese_simplified"],"青":["chinese_simplified","chinese_traditional"],"省":["chinese_simplified","chinese_traditional"],"列":["chinese_simplified","chinese_traditional"],"习":["chinese_simplified"],"响":["chinese_simplified"],"约":["chinese_simplified"],"支":["chinese_simplified","chinese_traditional"],"般":["chinese_simplified","chinese_traditional"],"史":["chinese_simplified","chinese_traditional"],"感":["chinese_simplified","chinese_traditional"],"劳":["chinese_simplified"],"便":["chinese_simplified","chinese_traditional"],"团":["chinese_simplified"],"往":["chinese_simplified","chinese_traditional"],"酸":["chinese_simplified","chinese_traditional"],"历":["chinese_simplified"],"市":["chinese_simplified","chinese_traditional"],"克":["chinese_simplified","chinese_traditional"],"何":["chinese_simplified","chinese_traditional"],"除":["chinese_simplified","chinese_traditional"],"消":["chinese_simplified","chinese_traditional"],"构":["chinese_simplified"],"府":["chinese_simplified","chinese_traditional"],"称":["chinese_simplified"],"太":["chinese_simplified","chinese_traditional"],"准":["chinese_simplified"],"精":["chinese_simplified","chinese_traditional"],"值":["chinese_simplified","chinese_traditional"],"号":["chinese_simplified"],"率":["chinese_simplified","chinese_traditional"],"族":["chinese_simplified","chinese_traditional"],"维":["chinese_simplified"],"划":["chinese_simplified"],"选":["chinese_simplified"],"标":["chinese_simplified"],"写":["chinese_simplified"],"存":["chinese_simplified","chinese_traditional"],"候":["chinese_simplified","chinese_traditional"],"毛":["chinese_simplified","chinese_traditional"],"亲":["chinese_simplified"],"快":["chinese_simplified","chinese_traditional"],"效":["chinese_simplified","chinese_traditional"],"斯":["chinese_simplified","chinese_traditional"],"院":["chinese_simplified","chinese_traditional"],"查":["chinese_simplified","chinese_traditional"],"江":["chinese_simplified","chinese_traditional"],"型":["chinese_simplified","chinese_traditional"],"眼":["chinese_simplified","chinese_traditional"],"王":["chinese_simplified","chinese_traditional"],"按":["chinese_simplified","chinese_traditional"],"格":["chinese_simplified","chinese_traditional"],"养":["chinese_simplified"],"易":["chinese_simplified","chinese_traditional"],"置":["chinese_simplified","chinese_traditional"],"派":["chinese_simplified","chinese_traditional"],"层":["chinese_simplified"],"片":["chinese_simplified","chinese_traditional"],"始":["chinese_simplified","chinese_traditional"],"却":["chinese_simplified"],"专":["chinese_simplified"],"状":["chinese_simplified"],"育":["chinese_simplified","chinese_traditional"],"厂":["chinese_simplified"],"京":["chinese_simplified","chinese_traditional"],"识":["chinese_simplified"],"适":["chinese_simplified"],"属":["chinese_simplified"],"圆":["chinese_simplified"],"包":["chinese_simplified","chinese_traditional"],"火":["chinese_simplified","chinese_traditional"],"住":["chinese_simplified","chinese_traditional"],"调":["chinese_simplified"],"满":["chinese_simplified"],"县":["chinese_simplified"],"局":["chinese_simplified","chinese_traditional"],"照":["chinese_simplified","chinese_traditional"],"参":["chinese_simplified"],"红":["chinese_simplified"],"细":["chinese_simplified"],"引":["chinese_simplified","chinese_traditional"],"听":["chinese_simplified"],"该":["chinese_simplified"],"铁":["chinese_simplified"],"价":["chinese_simplified"],"严":["chinese_simplified"],"首":["chinese_simplified","chinese_traditional"],"底":["chinese_simplified","chinese_traditional"],"液":["chinese_simplified","chinese_traditional"],"官":["chinese_simplified","chinese_traditional"],"德":["chinese_simplified","chinese_traditional"],"随":["chinese_simplified"],"病":["chinese_simplified","chinese_traditional"],"苏":["chinese_simplified"],"失":["chinese_simplified","chinese_traditional"],"尔":["chinese_simplified"],"死":["chinese_simplified","chinese_traditional"],"讲":["chinese_simplified"],"配":["chinese_simplified","chinese_traditional"],"女":["chinese_simplified","chinese_traditional"],"黄":["chinese_simplified"],"推":["chinese_simplified","chinese_traditional"],"显":["chinese_simplified"],"谈":["chinese_simplified"],"罪":["chinese_simplified","chinese_traditional"],"神":["chinese_simplified","chinese_traditional"],"艺":["chinese_simplified"],"呢":["chinese_simplified","chinese_traditional"],"席":["chinese_simplified","chinese_traditional"],"含":["chinese_simplified","chinese_traditional"],"企":["chinese_simplified","chinese_traditional"],"望":["chinese_simplified","chinese_traditional"],"密":["chinese_simplified","chinese_traditional"],"批":["chinese_simplified","chinese_traditional"],"营":["chinese_simplified"],"项":["chinese_simplified"],"防":["chinese_simplified","chinese_traditional"],"举":["chinese_simplified"],"球":["chinese_simplified","chinese_traditional"],"英":["chinese_simplified","chinese_traditional"],"氧":["chinese_simplified","chinese_traditional"],"势":["chinese_simplified"],"告":["chinese_simplified","chinese_traditional"],"李":["chinese_simplified","chinese_traditional"],"台":["chinese_simplified","chinese_traditional"],"落":["chinese_simplified","chinese_traditional"],"木":["chinese_simplified","chinese_traditional"],"帮":["chinese_simplified"],"轮":["chinese_simplified"],"破":["chinese_simplified","chinese_traditional"],"亚":["chinese_simplified"],"师":["chinese_simplified"],"围":["chinese_simplified"],"注":["chinese_simplified","chinese_traditional"],"远":["chinese_simplified"],"字":["chinese_simplified","chinese_traditional"],"材":["chinese_simplified","chinese_traditional"],"排":["chinese_simplified","chinese_traditional"],"供":["chinese_simplified","chinese_traditional"],"河":["chinese_simplified","chinese_traditional"],"态":["chinese_simplified"],"封":["chinese_simplified","chinese_traditional"],"另":["chinese_simplified","chinese_traditional"],"施":["chinese_simplified","chinese_traditional"],"减":["chinese_simplified"],"树":["chinese_simplified"],"溶":["chinese_simplified","chinese_traditional"],"怎":["chinese_simplified","chinese_traditional"],"止":["chinese_simplified","chinese_traditional"],"案":["chinese_simplified","chinese_traditional"],"言":["chinese_simplified","chinese_traditional"],"士":["chinese_simplified","chinese_traditional"],"均":["chinese_simplified","chinese_traditional"],"武":["chinese_simplified","chinese_traditional"],"固":["chinese_simplified","chinese_traditional"],"叶":["chinese_simplified"],"鱼":["chinese_simplified"],"波":["chinese_simplified","chinese_traditional"],"视":["chinese_simplified"],"仅":["chinese_simplified"],"费":["chinese_simplified"],"紧":["chinese_simplified"],"爱":["chinese_simplified"],"左":["chinese_simplified","chinese_traditional"],"章":["chinese_simplified","chinese_traditional"],"早":["chinese_simplified","chinese_traditional"],"朝":["chinese_simplified","chinese_traditional"],"害":["chinese_simplified","chinese_traditional"],"续":["chinese_simplified"],"轻":["chinese_simplified"],"服":["chinese_simplified","chinese_traditional"],"试":["chinese_simplified"],"食":["chinese_simplified","chinese_traditional"],"充":["chinese_simplified","chinese_traditional"],"兵":["chinese_simplified","chinese_traditional"],"源":["chinese_simplified","chinese_traditional"],"判":["chinese_simplified","chinese_traditional"],"护":["chinese_simplified"],"司":["chinese_simplified","chinese_traditional"],"足":["chinese_simplified","chinese_traditional"],"某":["chinese_simplified","chinese_traditional"],"练":["chinese_simplified"],"差":["chinese_simplified","chinese_traditional"],"致":["chinese_simplified","chinese_traditional"],"板":["chinese_simplified","chinese_traditional"],"田":["chinese_simplified","chinese_traditional"],"降":["chinese_simplified","chinese_traditional"],"黑":["chinese_simplified","chinese_traditional"],"犯":["chinese_simplified","chinese_traditional"],"负":["chinese_simplified"],"击":["chinese_simplified"],"范":["chinese_simplified","chinese_traditional"],"继":["chinese_simplified"],"兴":["chinese_simplified"],"似":["chinese_simplified","chinese_traditional"],"余":["chinese_simplified"],"坚":["chinese_simplified"],"曲":["chinese_simplified","chinese_traditional"],"输":["chinese_simplified"],"修":["chinese_simplified","chinese_traditional"],"故":["chinese_simplified","chinese_traditional"],"城":["chinese_simplified","chinese_traditional"],"夫":["chinese_simplified","chinese_traditional"],"够":["chinese_simplified"],"送":["chinese_simplified","chinese_traditional"],"笔":["chinese_simplified"],"船":["chinese_simplified","chinese_traditional"],"占":["chinese_simplified"],"右":["chinese_simplified","chinese_traditional"],"财":["chinese_simplified"],"吃":["chinese_simplified","chinese_traditional"],"富":["chinese_simplified","chinese_traditional"],"春":["chinese_simplified","chinese_traditional"],"职":["chinese_simplified"],"觉":["chinese_simplified"],"汉":["chinese_simplified"],"画":["chinese_simplified"],"功":["chinese_simplified","chinese_traditional"],"巴":["chinese_simplified","chinese_traditional"],"跟":["chinese_simplified","chinese_traditional"],"虽":["chinese_simplified"],"杂":["chinese_simplified"],"飞":["chinese_simplified"],"检":["chinese_simplified"],"吸":["chinese_simplified","chinese_traditional"],"助":["chinese_simplified","chinese_traditional"],"升":["chinese_simplified"],"阳":["chinese_simplified"],"互":["chinese_simplified","chinese_traditional"],"初":["chinese_simplified","chinese_traditional"],"创":["chinese_simplified"],"抗":["chinese_simplified","chinese_traditional"],"考":["chinese_simplified","chinese_traditional"],"投":["chinese_simplified","chinese_traditional"],"坏":["chinese_simplified"],"策":["chinese_simplified","chinese_traditional"],"古":["chinese_simplified","chinese_traditional"],"径":["chinese_simplified"],"换":["chinese_simplified"],"未":["chinese_simplified","chinese_traditional"],"跑":["chinese_simplified","chinese_traditional"],"留":["chinese_simplified","chinese_traditional"],"钢":["chinese_simplified"],"曾":["chinese_simplified","chinese_traditional"],"端":["chinese_simplified","chinese_traditional"],"责":["chinese_simplified"],"站":["chinese_simplified","chinese_traditional"],"简":["chinese_simplified"],"述":["chinese_simplified","chinese_traditional"],"钱":["chinese_simplified"],"副":["chinese_simplified","chinese_traditional"],"尽":["chinese_simplified"],"帝":["chinese_simplified","chinese_traditional"],"射":["chinese_simplified","chinese_traditional"],"草":["chinese_simplified","chinese_traditional"],"冲":["chinese_simplified"],"承":["chinese_simplified","chinese_traditional"],"独":["chinese_simplified"],"令":["chinese_simplified","chinese_traditional"],"限":["chinese_simplified","chinese_traditional"],"阿":["chinese_simplified","chinese_traditional"],"宣":["chinese_simplified","chinese_traditional"],"环":["chinese_simplified"],"双":["chinese_simplified"],"请":["chinese_simplified"],"超":["chinese_simplified","chinese_traditional"],"微":["chinese_simplified","chinese_traditional"],"让":["chinese_simplified"],"控":["chinese_simplified","chinese_traditional"],"州":["chinese_simplified","chinese_traditional"],"良":["chinese_simplified","chinese_traditional"],"轴":["chinese_simplified"],"找":["chinese_simplified","chinese_traditional"],"否":["chinese_simplified","chinese_traditional"],"纪":["chinese_simplified"],"益":["chinese_simplified","chinese_traditional"],"依":["chinese_simplified","chinese_traditional"],"优":["chinese_simplified"],"顶":["chinese_simplified"],"础":["chinese_simplified"],"载":["chinese_simplified"],"倒":["chinese_simplified","chinese_traditional"],"房":["chinese_simplified","chinese_traditional"],"突":["chinese_simplified","chinese_traditional"],"坐":["chinese_simplified","chinese_traditional"],"粉":["chinese_simplified","chinese_traditional"],"敌":["chinese_simplified"],"略":["chinese_simplified","chinese_traditional"],"客":["chinese_simplified","chinese_traditional"],"袁":["chinese_simplified","chinese_traditional"],"冷":["chinese_simplified","chinese_traditional"],"胜":["chinese_simplified"],"绝":["chinese_simplified"],"析":["chinese_simplified","chinese_traditional"],"块":["chinese_simplified"],"剂":["chinese_simplified"],"测":["chinese_simplified"],"丝":["chinese_simplified"],"协":["chinese_simplified"],"诉":["chinese_simplified"],"念":["chinese_simplified","chinese_traditional"],"陈":["chinese_simplified"],"仍":["chinese_simplified","chinese_traditional"],"罗":["chinese_simplified"],"盐":["chinese_simplified"],"友":["chinese_simplified","chinese_traditional"],"洋":["chinese_simplified","chinese_traditional"],"错":["chinese_simplified"],"苦":["chinese_simplified","chinese_traditional"],"夜":["chinese_simplified","chinese_traditional"],"刑":["chinese_simplified","chinese_traditional"],"移":["chinese_simplified","chinese_traditional"],"频":["chinese_simplified"],"逐":["chinese_simplified","chinese_traditional"],"靠":["chinese_simplified","chinese_traditional"],"混":["chinese_simplified","chinese_traditional"],"母":["chinese_simplified","chinese_traditional"],"短":["chinese_simplified","chinese_traditional"],"皮":["chinese_simplified","chinese_traditional"],"终":["chinese_simplified"],"聚":["chinese_simplified","chinese_traditional"],"汽":["chinese_simplified","chinese_traditional"],"村":["chinese_simplified","chinese_traditional"],"云":["chinese_simplified"],"哪":["chinese_simplified","chinese_traditional"],"既":["chinese_simplified","chinese_traditional"],"距":["chinese_simplified","chinese_traditional"],"卫":["chinese_simplified"],"停":["chinese_simplified","chinese_traditional"],"烈":["chinese_simplified","chinese_traditional"],"央":["chinese_simplified","chinese_traditional"],"察":["chinese_simplified","chinese_traditional"],"烧":["chinese_simplified"],"迅":["chinese_simplified","chinese_traditional"],"境":["chinese_simplified","chinese_traditional"],"若":["chinese_simplified","chinese_traditional"],"印":["chinese_simplified","chinese_traditional"],"洲":["chinese_simplified","chinese_traditional"],"刻":["chinese_simplified","chinese_traditional"],"括":["chinese_simplified","chinese_traditional"],"激":["chinese_simplified","chinese_traditional"],"孔":["chinese_simplified","chinese_traditional"],"搞":["chinese_simplified","chinese_traditional"],"甚":["chinese_simplified","chinese_traditional"],"室":["chinese_simplified","chinese_traditional"],"待":["chinese_simplified","chinese_traditional"],"核":["chinese_simplified","chinese_traditional"],"校":["chinese_simplified","chinese_traditional"],"散":["chinese_simplified","chinese_traditional"],"侵":["chinese_simplified","chinese_traditional"],"吧":["chinese_simplified","chinese_traditional"],"甲":["chinese_simplified","chinese_traditional"],"游":["chinese_simplified"],"久":["chinese_simplified","chinese_traditional"],"菜":["chinese_simplified","chinese_traditional"],"味":["chinese_simplified","chinese_traditional"],"旧":["chinese_simplified"],"模":["chinese_simplified","chinese_traditional"],"湖":["chinese_simplified","chinese_traditional"],"货":["chinese_simplified"],"损":["chinese_simplified"],"预":["chinese_simplified"],"阻":["chinese_simplified","chinese_traditional"],"毫":["chinese_simplified","chinese_traditional"],"普":["chinese_simplified","chinese_traditional"],"稳":["chinese_simplified"],"乙":["chinese_simplified","chinese_traditional"],"妈":["chinese_simplified"],"植":["chinese_simplified","chinese_traditional"],"息":["chinese_simplified","chinese_traditional"],"扩":["chinese_simplified"],"银":["chinese_simplified"],"语":["chinese_simplified"],"挥":["chinese_simplified"],"酒":["chinese_simplified","chinese_traditional"],"守":["chinese_simplified","chinese_traditional"],"拿":["chinese_simplified","chinese_traditional"],"序":["chinese_simplified","chinese_traditional"],"纸":["chinese_simplified"],"医":["chinese_simplified"],"缺":["chinese_simplified","chinese_traditional"],"雨":["chinese_simplified","chinese_traditional"],"吗":["chinese_simplified"],"针":["chinese_simplified"],"刘":["chinese_simplified"],"啊":["chinese_simplified","chinese_traditional"],"急":["chinese_simplified","chinese_traditional"],"唱":["chinese_simplified","chinese_traditional"],"误":["chinese_simplified"],"训":["chinese_simplified"],"愿":["chinese_simplified"],"审":["chinese_simplified"],"附":["chinese_simplified","chinese_traditional"],"获":["chinese_simplified"],"茶":["chinese_simplified","chinese_traditional"],"鲜":["chinese_simplified"],"粮":["chinese_simplified"],"斤":["chinese_simplified","chinese_traditional"],"孩":["chinese_simplified","chinese_traditional"],"脱":["chinese_simplified"],"硫":["chinese_simplified","chinese_traditional"],"肥":["chinese_simplified","chinese_traditional"],"善":["chinese_simplified","chinese_traditional"],"龙":["chinese_simplified"],"演":["chinese_simplified","chinese_traditional"],"父":["chinese_simplified","chinese_traditional"],"渐":["chinese_simplified"],"血":["chinese_simplified","chinese_traditional"],"欢":["chinese_simplified"],"械":["chinese_simplified","chinese_traditional"],"掌":["chinese_simplified","chinese_traditional"],"歌":["chinese_simplified","chinese_traditional"],"沙":["chinese_simplified","chinese_traditional"],"刚":["chinese_simplified"],"攻":["chinese_simplified","chinese_traditional"],"谓":["chinese_simplified"],"盾":["chinese_simplified","chinese_traditional"],"讨":["chinese_simplified"],"晚":["chinese_simplified","chinese_traditional"],"粒":["chinese_simplified","chinese_traditional"],"乱":["chinese_simplified"],"燃":["chinese_simplified","chinese_traditional"],"矛":["chinese_simplified","chinese_traditional"],"乎":["chinese_simplified","chinese_traditional"],"杀":["chinese_simplified"],"药":["chinese_simplified"],"宁":["chinese_simplified"],"鲁":["chinese_simplified"],"贵":["chinese_simplified"],"钟":["chinese_simplified"],"煤":["chinese_simplified","chinese_traditional"],"读":["chinese_simplified"],"班":["chinese_simplified","chinese_traditional"],"伯":["chinese_simplified","chinese_traditional"],"香":["chinese_simplified","chinese_traditional"],"介":["chinese_simplified","chinese_traditional"],"迫":["chinese_simplified","chinese_traditional"],"句":["chinese_simplified","chinese_traditional"],"丰":["chinese_simplified"],"培":["chinese_simplified","chinese_traditional"],"握":["chinese_simplified","chinese_traditional"],"兰":["chinese_simplified"],"担":["chinese_simplified"],"弦":["chinese_simplified","chinese_traditional"],"蛋":["chinese_simplified","chinese_traditional"],"沉":["chinese_simplified","chinese_traditional"],"假":["chinese_simplified","chinese_traditional"],"穿":["chinese_simplified","chinese_traditional"],"执":["chinese_simplified"],"答":["chinese_simplified","chinese_traditional"],"乐":["chinese_simplified"],"谁":["chinese_simplified"],"顺":["chinese_simplified"],"烟":["chinese_simplified"],"缩":["chinese_simplified"],"征":["chinese_simplified"],"脸":["chinese_simplified"],"喜":["chinese_simplified","chinese_traditional"],"松":["chinese_simplified","chinese_traditional"],"脚":["chinese_simplified"],"困":["chinese_simplified","chinese_traditional"],"异":["chinese_simplified"],"免":["chinese_simplified","chinese_traditional"],"背":["chinese_simplified","chinese_traditional"],"星":["chinese_simplified","chinese_traditional"],"福":["chinese_simplified","chinese_traditional"],"买":["chinese_simplified"],"染":["chinese_simplified","chinese_traditional"],"井":["chinese_simplified","chinese_traditional"],"概":["chinese_simplified","chinese_traditional"],"慢":["chinese_simplified","chinese_traditional"],"怕":["chinese_simplified","chinese_traditional"],"磁":["chinese_simplified","chinese_traditional"],"倍":["chinese_simplified","chinese_traditional"],"祖":["chinese_simplified","chinese_traditional"],"皇":["chinese_simplified","chinese_traditional"],"促":["chinese_simplified","chinese_traditional"],"静":["chinese_simplified"],"补":["chinese_simplified"],"评":["chinese_simplified"],"翻":["chinese_simplified","chinese_traditional"],"肉":["chinese_simplified","chinese_traditional"],"践":["chinese_simplified"],"尼":["chinese_simplified","chinese_traditional"],"衣":["chinese_simplified","chinese_traditional"],"宽":["chinese_simplified"],"扬":["chinese_simplified"],"棉":["chinese_simplified","chinese_traditional"],"希":["chinese_simplified","chinese_traditional"],"伤":["chinese_simplified"],"操":["chinese_simplified","chinese_traditional"],"垂":["chinese_simplified","chinese_traditional"],"秋":["chinese_simplified","chinese_traditional"],"宜":["chinese_simplified","chinese_traditional"],"氢":["chinese_simplified"],"套":["chinese_simplified","chinese_traditional"],"督":["chinese_simplified","chinese_traditional"],"振":["chinese_simplified","chinese_traditional"],"架":["chinese_simplified","chinese_traditional"],"亮":["chinese_simplified","chinese_traditional"],"末":["chinese_simplified","chinese_traditional"],"宪":["chinese_simplified"],"庆":["chinese_simplified"],"编":["chinese_simplified"],"牛":["chinese_simplified","chinese_traditional"],"触":["chinese_simplified"],"映":["chinese_simplified","chinese_traditional"],"雷":["chinese_simplified","chinese_traditional"],"销":["chinese_simplified"],"诗":["chinese_simplified"],"座":["chinese_simplified","chinese_traditional"],"居":["chinese_simplified","chinese_traditional"],"抓":["chinese_simplified","chinese_traditional"],"裂":["chinese_simplified","chinese_traditional"],"胞":["chinese_simplified","chinese_traditional"],"呼":["chinese_simplified","chinese_traditional"],"娘":["chinese_simplified","chinese_traditional"],"景":["chinese_simplified","chinese_traditional"],"威":["chinese_simplified","chinese_traditional"],"绿":["chinese_simplified"],"晶":["chinese_simplified","chinese_traditional"],"厚":["chinese_simplified","chinese_traditional"],"盟":["chinese_simplified","chinese_traditional"],"衡":["chinese_simplified","chinese_traditional"],"鸡":["chinese_simplified"],"孙":["chinese_simplified"],"延":["chinese_simplified","chinese_traditional"],"危":["chinese_simplified","chinese_traditional"],"胶":["chinese_simplified"],"屋":["chinese_simplified","chinese_traditional"],"乡":["chinese_simplified"],"临":["chinese_simplified"],"陆":["chinese_simplified"],"顾":["chinese_simplified"],"掉":["chinese_simplified","chinese_traditional"],"呀":["chinese_simplified","chinese_traditional"],"灯":["chinese_simplified"],"岁":["chinese_simplified"],"措":["chinese_simplified","chinese_traditional"],"束":["chinese_simplified","chinese_traditional"],"耐":["chinese_simplified","chinese_traditional"],"剧":["chinese_simplified"],"玉":["chinese_simplified","chinese_traditional"],"赵":["chinese_simplified"],"跳":["chinese_simplified","chinese_traditional"],"哥":["chinese_simplified","chinese_traditional"],"季":["chinese_simplified","chinese_traditional"],"课":["chinese_simplified"],"凯":["chinese_simplified"],"胡":["chinese_simplified","chinese_traditional"],"额":["chinese_simplified"],"款":["chinese_simplified","chinese_traditional"],"绍":["chinese_simplified"],"卷":["chinese_simplified","chinese_traditional"],"齐":["chinese_simplified"],"伟":["chinese_simplified"],"蒸":["chinese_simplified","chinese_traditional"],"殖":["chinese_simplified","chinese_traditional"],"永":["chinese_simplified","chinese_traditional"],"宗":["chinese_simplified","chinese_traditional"],"苗":["chinese_simplified","chinese_traditional"],"川":["chinese_simplified","chinese_traditional"],"炉":["chinese_simplified"],"岩":["chinese_simplified","chinese_traditional"],"弱":["chinese_simplified","chinese_traditional"],"零":["chinese_simplified","chinese_traditional"],"杨":["chinese_simplified"],"奏":["chinese_simplified","chinese_traditional"],"沿":["chinese_simplified","chinese_traditional"],"露":["chinese_simplified","chinese_traditional"],"杆":["chinese_simplified"],"探":["chinese_simplified","chinese_traditional"],"滑":["chinese_simplified","chinese_traditional"],"镇":["chinese_simplified"],"饭":["chinese_simplified"],"浓":["chinese_simplified"],"航":["chinese_simplified","chinese_traditional"],"怀":["chinese_simplified"],"赶":["chinese_simplified"],"库":["chinese_simplified"],"夺":["chinese_simplified"],"伊":["chinese_simplified","chinese_traditional"],"灵":["chinese_simplified"],"税":["chinese_simplified"],"途":["chinese_simplified","chinese_traditional"],"灭":["chinese_simplified"],"赛":["chinese_simplified"],"归":["chinese_simplified"],"召":["chinese_simplified","chinese_traditional"],"鼓":["chinese_simplified","chinese_traditional"],"播":["chinese_simplified","chinese_traditional"],"盘":["chinese_simplified"],"裁":["chinese_simplified","chinese_traditional"],"险":["chinese_simplified"],"康":["chinese_simplified","chinese_traditional"],"唯":["chinese_simplified","chinese_traditional"],"录":["chinese_simplified"],"菌":["chinese_simplified","chinese_traditional"],"纯":["chinese_simplified"],"借":["chinese_simplified","chinese_traditional"],"糖":["chinese_simplified","chinese_traditional"],"盖":["chinese_simplified"],"横":["chinese_simplified"],"符":["chinese_simplified","chinese_traditional"],"私":["chinese_simplified","chinese_traditional"],"努":["chinese_simplified","chinese_traditional"],"堂":["chinese_simplified","chinese_traditional"],"域":["chinese_simplified","chinese_traditional"],"枪":["chinese_simplified"],"润":["chinese_simplified"],"幅":["chinese_simplified","chinese_traditional"],"哈":["chinese_simplified","chinese_traditional"],"竟":["chinese_simplified","chinese_traditional"],"熟":["chinese_simplified","chinese_traditional"],"虫":["chinese_simplified"],"泽":["chinese_simplified"],"脑":["chinese_simplified"],"壤":["chinese_simplified","chinese_traditional"],"碳":["chinese_simplified","chinese_traditional"],"欧":["chinese_simplified"],"遍":["chinese_simplified","chinese_traditional"],"侧":["chinese_simplified"],"寨":["chinese_simplified","chinese_traditional"],"敢":["chinese_simplified","chinese_traditional"],"彻":["chinese_simplified"],"虑":["chinese_simplified"],"斜":["chinese_simplified","chinese_traditional"],"薄":["chinese_simplified","chinese_traditional"],"庭":["chinese_simplified","chinese_traditional"],"纳":["chinese_simplified"],"弹":["chinese_simplified"],"饲":["chinese_simplified"],"伸":["chinese_simplified","chinese_traditional"],"折":["chinese_simplified","chinese_traditional"],"麦":["chinese_simplified"],"湿":["chinese_simplified"],"暗":["chinese_simplified","chinese_traditional"],"荷":["chinese_simplified","chinese_traditional"],"瓦":["chinese_simplified","chinese_traditional"],"塞":["chinese_simplified","chinese_traditional"],"床":["chinese_simplified","chinese_traditional"],"筑":["chinese_simplified"],"恶":["chinese_simplified"],"户":["chinese_simplified"],"访":["chinese_simplified"],"塔":["chinese_simplified","chinese_traditional"],"奇":["chinese_simplified","chinese_traditional"],"透":["chinese_simplified","chinese_traditional"],"梁":["chinese_simplified","chinese_traditional"],"刀":["chinese_simplified","chinese_traditional"],"旋":["chinese_simplified","chinese_traditional"],"迹":["chinese_simplified"],"卡":["chinese_simplified","chinese_traditional"],"氯":["chinese_simplified","chinese_traditional"],"遇":["chinese_simplified","chinese_traditional"],"份":["chinese_simplified","chinese_traditional"],"毒":["chinese_simplified","chinese_traditional"],"泥":["chinese_simplified","chinese_traditional"],"退":["chinese_simplified","chinese_traditional"],"洗":["chinese_simplified","chinese_traditional"],"摆":["chinese_simplified"],"灰":["chinese_simplified","chinese_traditional"],"彩":["chinese_simplified","chinese_traditional"],"卖":["chinese_simplified"],"耗":["chinese_simplified","chinese_traditional"],"夏":["chinese_simplified","chinese_traditional"],"择":["chinese_simplified"],"忙":["chinese_simplified","chinese_traditional"],"铜":["chinese_simplified"],"献":["chinese_simplified"],"硬":["chinese_simplified","chinese_traditional"],"予":["chinese_simplified","chinese_traditional"],"繁":["chinese_simplified","chinese_traditional"],"圈":["chinese_simplified","chinese_traditional"],"雪":["chinese_simplified","chinese_traditional"],"函":["chinese_simplified","chinese_traditional"],"亦":["chinese_simplified","chinese_traditional"],"抽":["chinese_simplified","chinese_traditional"],"篇":["chinese_simplified","chinese_traditional"],"阵":["chinese_simplified"],"阴":["chinese_simplified"],"丁":["chinese_simplified","chinese_traditional"],"尺":["chinese_simplified","chinese_traditional"],"追":["chinese_simplified","chinese_traditional"],"堆":["chinese_simplified","chinese_traditional"],"雄":["chinese_simplified","chinese_traditional"],"迎":["chinese_simplified","chinese_traditional"],"泛":["chinese_simplified","chinese_traditional"],"爸":["chinese_simplified","chinese_traditional"],"楼":["chinese_simplified"],"避":["chinese_simplified","chinese_traditional"],"谋":["chinese_simplified"],"吨":["chinese_simplified"],"野":["chinese_simplified","chinese_traditional"],"猪":["chinese_simplified"],"旗":["chinese_simplified","chinese_traditional"],"累":["chinese_simplified","chinese_traditional"],"偏":["chinese_simplified","chinese_traditional"],"典":["chinese_simplified","chinese_traditional"],"馆":["chinese_simplified"],"索":["chinese_simplified","chinese_traditional"],"秦":["chinese_simplified","chinese_traditional"],"脂":["chinese_simplified","chinese_traditional"],"潮":["chinese_simplified","chinese_traditional"],"爷":["chinese_simplified"],"豆":["chinese_simplified","chinese_traditional"],"忽":["chinese_simplified","chinese_traditional"],"托":["chinese_simplified","chinese_traditional"],"惊":["chinese_simplified"],"塑":["chinese_simplified","chinese_traditional"],"遗":["chinese_simplified"],"愈":["chinese_simplified","chinese_traditional"],"朱":["chinese_simplified","chinese_traditional"],"替":["chinese_simplified","chinese_traditional"],"纤":["chinese_simplified"],"粗":["chinese_simplified","chinese_traditional"],"倾":["chinese_simplified"],"尚":["chinese_simplified","chinese_traditional"],"痛":["chinese_simplified","chinese_traditional"],"楚":["chinese_simplified","chinese_traditional"],"谢":["chinese_simplified"],"奋":["chinese_simplified"],"购":["chinese_simplified"],"磨":["chinese_simplified","chinese_traditional"],"君":["chinese_simplified","chinese_traditional"],"池":["chinese_simplified","chinese_traditional"],"旁":["chinese_simplified","chinese_traditional"],"碎":["chinese_simplified","chinese_traditional"],"骨":["chinese_simplified","chinese_traditional"],"监":["chinese_simplified"],"捕":["chinese_simplified","chinese_traditional"],"弟":["chinese_simplified","chinese_traditional"],"暴":["chinese_simplified","chinese_traditional"],"割":["chinese_simplified","chinese_traditional"],"贯":["chinese_simplified"],"殊":["chinese_simplified","chinese_traditional"],"释":["chinese_simplified"],"词":["chinese_simplified"],"亡":["chinese_simplified","chinese_traditional"],"壁":["chinese_simplified","chinese_traditional"],"顿":["chinese_simplified"],"宝":["chinese_simplified"],"午":["chinese_simplified","chinese_traditional"],"尘":["chinese_simplified"],"闻":["chinese_simplified"],"揭":["chinese_simplified","chinese_traditional"],"炮":["chinese_simplified","chinese_traditional"],"残":["chinese_simplified"],"冬":["chinese_simplified","chinese_traditional"],"桥":["chinese_simplified"],"妇":["chinese_simplified"],"警":["chinese_simplified","chinese_traditional"],"综":["chinese_simplified"],"招":["chinese_simplified","chinese_traditional"],"吴":["chinese_simplified"],"付":["chinese_simplified","chinese_traditional"],"浮":["chinese_simplified","chinese_traditional"],"遭":["chinese_simplified","chinese_traditional"],"徐":["chinese_simplified","chinese_traditional"],"您":["chinese_simplified","chinese_traditional"],"摇":["chinese_simplified"],"谷":["chinese_simplified","chinese_traditional"],"赞":["chinese_simplified"],"箱":["chinese_simplified","chinese_traditional"],"隔":["chinese_simplified","chinese_traditional"],"订":["chinese_simplified"],"男":["chinese_simplified","chinese_traditional"],"吹":["chinese_simplified","chinese_traditional"],"园":["chinese_simplified"],"纷":["chinese_simplified"],"唐":["chinese_simplified","chinese_traditional"],"败":["chinese_simplified"],"宋":["chinese_simplified","chinese_traditional"],"玻":["chinese_simplified","chinese_traditional"],"巨":["chinese_simplified","chinese_traditional"],"耕":["chinese_simplified","chinese_traditional"],"坦":["chinese_simplified","chinese_traditional"],"荣":["chinese_simplified"],"闭":["chinese_simplified"],"湾":["chinese_simplified"],"键":["chinese_simplified"],"凡":["chinese_simplified","chinese_traditional"],"驻":["chinese_simplified"],"锅":["chinese_simplified"],"救":["chinese_simplified","chinese_traditional"],"恩":["chinese_simplified","chinese_traditional"],"剥":["chinese_simplified"],"凝":["chinese_simplified","chinese_traditional"],"碱":["chinese_simplified"],"齿":["chinese_simplified"],"截":["chinese_simplified","chinese_traditional"],"炼":["chinese_simplified"],"麻":["chinese_simplified","chinese_traditional"],"纺":["chinese_simplified"],"禁":["chinese_simplified","chinese_traditional"],"废":["chinese_simplified"],"盛":["chinese_simplified","chinese_traditional"],"版":["chinese_simplified","chinese_traditional"],"缓":["chinese_simplified"],"净":["chinese_simplified"],"睛":["chinese_simplified","chinese_traditional"],"昌":["chinese_simplified","chinese_traditional"],"婚":["chinese_simplified","chinese_traditional"],"涉":["chinese_simplified","chinese_traditional"],"筒":["chinese_simplified","chinese_traditional"],"嘴":["chinese_simplified","chinese_traditional"],"插":["chinese_simplified","chinese_traditional"],"岸":["chinese_simplified","chinese_traditional"],"朗":["chinese_simplified","chinese_traditional"],"庄":["chinese_simplified"],"街":["chinese_simplified","chinese_traditional"],"藏":["chinese_simplified","chinese_traditional"],"姑":["chinese_simplified","chinese_traditional"],"贸":["chinese_simplified"],"腐":["chinese_simplified","chinese_traditional"],"奴":["chinese_simplified","chinese_traditional"],"啦":["chinese_simplified","chinese_traditional"],"惯":["chinese_simplified"],"乘":["chinese_simplified","chinese_traditional"],"伙":["chinese_simplified"],"恢":["chinese_simplified","chinese_traditional"],"匀":["chinese_simplified"],"纱":["chinese_simplified"],"扎":["chinese_simplified","chinese_traditional"],"辩":["chinese_simplified"],"耳":["chinese_simplified","chinese_traditional"],"彪":["chinese_simplified","chinese_traditional"],"臣":["chinese_simplified","chinese_traditional"],"亿":["chinese_simplified"],"璃":["chinese_simplified","chinese_traditional"],"抵":["chinese_simplified","chinese_traditional"],"脉":["chinese_simplified"],"秀":["chinese_simplified","chinese_traditional"],"萨":["chinese_simplified"],"俄":["chinese_simplified","chinese_traditional"],"网":["chinese_simplified"],"舞":["chinese_simplified","chinese_traditional"],"店":["chinese_simplified","chinese_traditional"],"喷":["chinese_simplified"],"纵":["chinese_simplified"],"寸":["chinese_simplified","chinese_traditional"],"汗":["chinese_simplified","chinese_traditional"],"挂":["chinese_simplified"],"洪":["chinese_simplified","chinese_traditional"],"贺":["chinese_simplified"],"闪":["chinese_simplified"],"柬":["chinese_simplified","chinese_traditional"],"爆":["chinese_simplified","chinese_traditional"],"烯":["chinese_simplified","chinese_traditional"],"津":["chinese_simplified","chinese_traditional"],"稻":["chinese_simplified","chinese_traditional"],"墙":["chinese_simplified"],"软":["chinese_simplified"],"勇":["chinese_simplified","chinese_traditional"],"像":["chinese_simplified","chinese_traditional"],"滚":["chinese_simplified"],"厘":["chinese_simplified","chinese_traditional"],"蒙":["chinese_simplified","chinese_traditional"],"芳":["chinese_simplified","chinese_traditional"],"肯":["chinese_simplified","chinese_traditional"],"坡":["chinese_simplified","chinese_traditional"],"柱":["chinese_simplified","chinese_traditional"],"荡":["chinese_simplified"],"腿":["chinese_simplified","chinese_traditional"],"仪":["chinese_simplified"],"旅":["chinese_simplified","chinese_traditional"],"尾":["chinese_simplified","chinese_traditional"],"轧":["chinese_simplified"],"冰":["chinese_simplified","chinese_traditional"],"贡":["chinese_simplified"],"登":["chinese_simplified","chinese_traditional"],"黎":["chinese_simplified","chinese_traditional"],"削":["chinese_simplified","chinese_traditional"],"钻":["chinese_simplified"],"勒":["chinese_simplified","chinese_traditional"],"逃":["chinese_simplified","chinese_traditional"],"障":["chinese_simplified","chinese_traditional"],"氨":["chinese_simplified","chinese_traditional"],"郭":["chinese_simplified","chinese_traditional"],"峰":["chinese_simplified","chinese_traditional"],"币":["chinese_simplified"],"港":["chinese_simplified","chinese_traditional"],"伏":["chinese_simplified","chinese_traditional"],"轨":["chinese_simplified"],"亩":["chinese_simplified"],"毕":["chinese_simplified"],"擦":["chinese_simplified","chinese_traditional"],"莫":["chinese_simplified","chinese_traditional"],"刺":["chinese_simplified","chinese_traditional"],"浪":["chinese_simplified","chinese_traditional"],"秘":["chinese_simplified","chinese_traditional"],"援":["chinese_simplified","chinese_traditional"],"株":["chinese_simplified","chinese_traditional"],"健":["chinese_simplified","chinese_traditional"],"售":["chinese_simplified","chinese_traditional"],"股":["chinese_simplified","chinese_traditional"],"岛":["chinese_simplified"],"甘":["chinese_simplified","chinese_traditional"],"泡":["chinese_simplified","chinese_traditional"],"睡":["chinese_simplified","chinese_traditional"],"童":["chinese_simplified","chinese_traditional"],"铸":["chinese_simplified"],"汤":["chinese_simplified"],"阀":["chinese_simplified"],"休":["chinese_simplified","chinese_traditional"],"汇":["chinese_simplified"],"舍":["chinese_simplified","chinese_traditional"],"牧":["chinese_simplified","chinese_traditional"],"绕":["chinese_simplified"],"炸":["chinese_simplified","chinese_traditional"],"哲":["chinese_simplified","chinese_traditional"],"磷":["chinese_simplified","chinese_traditional"],"绩":["chinese_simplified"],"朋":["chinese_simplified","chinese_traditional"],"淡":["chinese_simplified","chinese_traditional"],"尖":["chinese_simplified","chinese_traditional"],"启":["chinese_simplified"],"陷":["chinese_simplified","chinese_traditional"],"柴":["chinese_simplified","chinese_traditional"],"呈":["chinese_simplified","chinese_traditional"],"徒":["chinese_simplified","chinese_traditional"],"颜":["chinese_simplified"],"泪":["chinese_simplified"],"稍":["chinese_simplified","chinese_traditional"],"忘":["chinese_simplified","chinese_traditional"],"泵":["chinese_simplified","chinese_traditional"],"蓝":["chinese_simplified"],"拖":["chinese_simplified","chinese_traditional"],"洞":["chinese_simplified","chinese_traditional"],"授":["chinese_simplified","chinese_traditional"],"镜":["chinese_simplified"],"辛":["chinese_simplified","chinese_traditional"],"壮":["chinese_simplified"],"锋":["chinese_simplified"],"贫":["chinese_simplified"],"虚":["chinese_simplified"],"弯":["chinese_simplified"],"摩":["chinese_simplified","chinese_traditional"],"泰":["chinese_simplified","chinese_traditional"],"幼":["chinese_simplified","chinese_traditional"],"廷":["chinese_simplified","chinese_traditional"],"尊":["chinese_simplified","chinese_traditional"],"窗":["chinese_simplified","chinese_traditional"],"纲":["chinese_simplified"],"弄":["chinese_simplified","chinese_traditional"],"隶":["chinese_simplified"],"疑":["chinese_simplified","chinese_traditional"],"氏":["chinese_simplified","chinese_traditional"],"宫":["chinese_simplified"],"姐":["chinese_simplified","chinese_traditional"],"震":["chinese_simplified","chinese_traditional"],"瑞":["chinese_simplified","chinese_traditional"],"怪":["chinese_simplified","chinese_traditional"],"尤":["chinese_simplified","chinese_traditional"],"琴":["chinese_simplified","chinese_traditional"],"循":["chinese_simplified","chinese_traditional"],"描":["chinese_simplified","chinese_traditional"],"膜":["chinese_simplified","chinese_traditional"],"违":["chinese_simplified"],"夹":["chinese_simplified"],"腰":["chinese_simplified","chinese_traditional"],"缘":["chinese_simplified"],"珠":["chinese_simplified","chinese_traditional"],"穷":["chinese_simplified"],"森":["chinese_simplified","chinese_traditional"],"枝":["chinese_simplified","chinese_traditional"],"竹":["chinese_simplified","chinese_traditional"],"沟":["chinese_simplified"],"催":["chinese_simplified","chinese_traditional"],"绳":["chinese_simplified"],"忆":["chinese_simplified"],"邦":["chinese_simplified","chinese_traditional"],"剩":["chinese_simplified","chinese_traditional"],"幸":["chinese_simplified","chinese_traditional"],"浆":["chinese_simplified"],"栏":["chinese_simplified"],"拥":["chinese_simplified"],"牙":["chinese_simplified","chinese_traditional"],"贮":["chinese_simplified"],"礼":["chinese_simplified"],"滤":["chinese_simplified"],"钠":["chinese_simplified"],"纹":["chinese_simplified"],"罢":["chinese_simplified"],"拍":["chinese_simplified","chinese_traditional"],"咱":["chinese_simplified","chinese_traditional"],"喊":["chinese_simplified","chinese_traditional"],"袖":["chinese_simplified","chinese_traditional"],"埃":["chinese_simplified","chinese_traditional"],"勤":["chinese_simplified","chinese_traditional"],"罚":["chinese_simplified"],"焦":["chinese_simplified","chinese_traditional"],"潜":["chinese_simplified"],"伍":["chinese_simplified","chinese_traditional"],"墨":["chinese_simplified","chinese_traditional"],"欲":["chinese_simplified","chinese_traditional"],"缝":["chinese_simplified"],"姓":["chinese_simplified","chinese_traditional"],"刊":["chinese_simplified","chinese_traditional"],"饱":["chinese_simplified"],"仿":["chinese_simplified","chinese_traditional"],"奖":["chinese_simplified"],"铝":["chinese_simplified"],"鬼":["chinese_simplified","chinese_traditional"],"丽":["chinese_simplified"],"跨":["chinese_simplified","chinese_traditional"],"默":["chinese_simplified","chinese_traditional"],"挖":["chinese_simplified","chinese_traditional"],"链":["chinese_simplified"],"扫":["chinese_simplified"],"喝":["chinese_simplified","chinese_traditional"],"袋":["chinese_simplified","chinese_traditional"],"炭":["chinese_simplified","chinese_traditional"],"污":["chinese_simplified","chinese_traditional"],"幕":["chinese_simplified","chinese_traditional"],"诸":["chinese_simplified"],"弧":["chinese_simplified","chinese_traditional"],"励":["chinese_simplified"],"梅":["chinese_simplified","chinese_traditional"],"奶":["chinese_simplified","chinese_traditional"],"洁":["chinese_simplified"],"灾":["chinese_simplified"],"舟":["chinese_simplified","chinese_traditional"],"鉴":["chinese_simplified"],"苯":["chinese_simplified","chinese_traditional"],"讼":["chinese_simplified"],"抱":["chinese_simplified","chinese_traditional"],"毁":["chinese_simplified"],"懂":["chinese_simplified","chinese_traditional"],"寒":["chinese_simplified","chinese_traditional"],"智":["chinese_simplified","chinese_traditional"],"埔":["chinese_simplified","chinese_traditional"],"寄":["chinese_simplified","chinese_traditional"],"届":["chinese_simplified"],"跃":["chinese_simplified"],"渡":["chinese_simplified","chinese_traditional"],"挑":["chinese_simplified","chinese_traditional"],"丹":["chinese_simplified","chinese_traditional"],"艰":["chinese_simplified"],"贝":["chinese_simplified"],"碰":["chinese_simplified","chinese_traditional"],"拔":["chinese_simplified","chinese_traditional"],"爹":["chinese_simplified","chinese_traditional"],"戴":["chinese_simplified","chinese_traditional"],"码":["chinese_simplified"],"梦":["chinese_simplified"],"芽":["chinese_simplified","chinese_traditional"],"熔":["chinese_simplified","chinese_traditional"],"赤":["chinese_simplified","chinese_traditional"],"渔":["chinese_simplified"],"哭":["chinese_simplified","chinese_traditional"],"敬":["chinese_simplified","chinese_traditional"],"颗":["chinese_simplified"],"奔":["chinese_simplified","chinese_traditional"],"铅":["chinese_simplified"],"仲":["chinese_simplified","chinese_traditional"],"虎":["chinese_simplified","chinese_traditional"],"稀":["chinese_simplified","chinese_traditional"],"妹":["chinese_simplified","chinese_traditional"],"乏":["chinese_simplified","chinese_traditional"],"珍":["chinese_simplified","chinese_traditional"],"申":["chinese_simplified","chinese_traditional"],"桌":["chinese_simplified","chinese_traditional"],"遵":["chinese_simplified","chinese_traditional"],"允":["chinese_simplified","chinese_traditional"],"隆":["chinese_simplified","chinese_traditional"],"螺":["chinese_simplified","chinese_traditional"],"仓":["chinese_simplified"],"魏":["chinese_simplified","chinese_traditional"],"锐":["chinese_simplified"],"晓":["chinese_simplified"],"氮":["chinese_simplified","chinese_traditional"],"兼":["chinese_simplified","chinese_traditional"],"隐":["chinese_simplified"],"碍":["chinese_simplified"],"赫":["chinese_simplified","chinese_traditional"],"拨":["chinese_simplified"],"忠":["chinese_simplified","chinese_traditional"],"肃":["chinese_simplified"],"缸":["chinese_simplified","chinese_traditional"],"牵":["chinese_simplified"],"抢":["chinese_simplified"],"博":["chinese_simplified","chinese_traditional"],"巧":["chinese_simplified","chinese_traditional"],"壳":["chinese_simplified"],"兄":["chinese_simplified","chinese_traditional"],"杜":["chinese_simplified","chinese_traditional"],"讯":["chinese_simplified"],"诚":["chinese_simplified"],"碧":["chinese_simplified","chinese_traditional"],"祥":["chinese_simplified","chinese_traditional"],"柯":["chinese_simplified","chinese_traditional"],"页":["chinese_simplified"],"巡":["chinese_simplified","chinese_traditional"],"矩":["chinese_simplified","chinese_traditional"],"悲":["chinese_simplified","chinese_traditional"],"灌":["chinese_simplified","chinese_traditional"],"龄":["chinese_simplified"],"伦":["chinese_simplified"],"票":["chinese_simplified","chinese_traditional"],"寻":["chinese_simplified"],"桂":["chinese_simplified","chinese_traditional"],"铺":["chinese_simplified"],"圣":["chinese_simplified"],"恐":["chinese_simplified","chinese_traditional"],"恰":["chinese_simplified","chinese_traditional"],"郑":["chinese_simplified"],"趣":["chinese_simplified","chinese_traditional"],"抬":["chinese_simplified","chinese_traditional"],"荒":["chinese_simplified","chinese_traditional"],"腾":["chinese_simplified"],"贴":["chinese_simplified"],"柔":["chinese_simplified","chinese_traditional"],"滴":["chinese_simplified","chinese_traditional"],"猛":["chinese_simplified","chinese_traditional"],"阔":["chinese_simplified"],"辆":["chinese_simplified"],"妻":["chinese_simplified","chinese_traditional"],"填":["chinese_simplified","chinese_traditional"],"撤":["chinese_simplified","chinese_traditional"],"储":["chinese_simplified"],"签":["chinese_simplified"],"闹":["chinese_simplified"],"扰":["chinese_simplified"],"紫":["chinese_simplified","chinese_traditional"],"砂":["chinese_simplified","chinese_traditional"],"递":["chinese_simplified"],"戏":["chinese_simplified"],"吊":["chinese_simplified","chinese_traditional"],"陶":["chinese_simplified","chinese_traditional"],"伐":["chinese_simplified","chinese_traditional"],"喂":["chinese_simplified"],"疗":["chinese_simplified"],"瓶":["chinese_simplified","chinese_traditional"],"婆":["chinese_simplified","chinese_traditional"],"抚":["chinese_simplified"],"臂":["chinese_simplified","chinese_traditional"],"摸":["chinese_simplified","chinese_traditional"],"忍":["chinese_simplified","chinese_traditional"],"虾":["chinese_simplified"],"蜡":["chinese_simplified"],"邻":["chinese_simplified"],"胸":["chinese_simplified","chinese_traditional"],"巩":["chinese_simplified"],"挤":["chinese_simplified"],"偶":["chinese_simplified","chinese_traditional"],"弃":["chinese_simplified"],"槽":["chinese_simplified","chinese_traditional"],"劲":["chinese_simplified"],"乳":["chinese_simplified","chinese_traditional"],"邓":["chinese_simplified"],"吉":["chinese_simplified","chinese_traditional"],"仁":["chinese_simplified","chinese_traditional"],"烂":["chinese_simplified"],"砖":["chinese_simplified"],"租":["chinese_simplified","chinese_traditional"],"乌":["chinese_simplified"],"舰":["chinese_simplified"],"伴":["chinese_simplified","chinese_traditional"],"瓜":["chinese_simplified","chinese_traditional"],"浅":["chinese_simplified"],"丙":["chinese_simplified","chinese_traditional"],"暂":["chinese_simplified"],"燥":["chinese_simplified","chinese_traditional"],"橡":["chinese_simplified","chinese_traditional"],"柳":["chinese_simplified","chinese_traditional"],"迷":["chinese_simplified","chinese_traditional"],"暖":["chinese_simplified","chinese_traditional"],"牌":["chinese_simplified","chinese_traditional"],"秧":["chinese_simplified","chinese_traditional"],"胆":["chinese_simplified"],"详":["chinese_simplified"],"簧":["chinese_simplified","chinese_traditional"],"踏":["chinese_simplified","chinese_traditional"],"瓷":["chinese_simplified","chinese_traditional"],"谱":["chinese_simplified"],"呆":["chinese_simplified","chinese_traditional"],"宾":["chinese_simplified"],"糊":["chinese_simplified","chinese_traditional"],"洛":["chinese_simplified","chinese_traditional"],"辉":["chinese_simplified"],"愤":["chinese_simplified"],"竞":["chinese_simplified"],"隙":["chinese_simplified","chinese_traditional"],"怒":["chinese_simplified","chinese_traditional"],"粘":["chinese_simplified","chinese_traditional"],"乃":["chinese_simplified","chinese_traditional"],"绪":["chinese_simplified"],"肩":["chinese_simplified","chinese_traditional"],"籍":["chinese_simplified","chinese_traditional"],"敏":["chinese_simplified","chinese_traditional"],"涂":["chinese_simplified"],"熙":["chinese_simplified","chinese_traditional"],"皆":["chinese_simplified","chinese_traditional"],"侦":["chinese_simplified"],"悬":["chinese_simplified"],"掘":["chinese_simplified","chinese_traditional"],"享":["chinese_simplified","chinese_traditional"],"纠":["chinese_simplified"],"醒":["chinese_simplified","chinese_traditional"],"狂":["chinese_simplified","chinese_traditional"],"锁":["chinese_simplified"],"淀":["chinese_simplified","chinese_traditional"],"恨":["chinese_simplified","chinese_traditional"],"牲":["chinese_simplified","chinese_traditional"],"霸":["chinese_simplified","chinese_traditional"],"爬":["chinese_simplified","chinese_traditional"],"赏":["chinese_simplified"],"逆":["chinese_simplified","chinese_traditional"],"玩":["chinese_simplified","chinese_traditional"],"陵":["chinese_simplified","chinese_traditional"],"祝":["chinese_simplified","chinese_traditional"],"秒":["chinese_simplified","chinese_traditional"],"浙":["chinese_simplified","chinese_traditional"],"貌":["chinese_simplified","chinese_traditional"],"役":["chinese_simplified","chinese_traditional"],"彼":["chinese_simplified","chinese_traditional"],"悉":["chinese_simplified","chinese_traditional"],"鸭":["chinese_simplified"],"趋":["chinese_simplified"],"凤":["chinese_simplified"],"晨":["chinese_simplified","chinese_traditional"],"畜":["chinese_simplified","chinese_traditional"],"辈":["chinese_simplified"],"秩":["chinese_simplified","chinese_traditional"],"卵":["chinese_simplified","chinese_traditional"],"署":["chinese_simplified","chinese_traditional"],"梯":["chinese_simplified","chinese_traditional"],"炎":["chinese_simplified","chinese_traditional"],"滩":["chinese_simplified"],"棋":["chinese_simplified","chinese_traditional"],"驱":["chinese_simplified"],"筛":["chinese_simplified"],"峡":["chinese_simplified"],"冒":["chinese_simplified","chinese_traditional"],"啥":["chinese_simplified","chinese_traditional"],"寿":["chinese_simplified"],"译":["chinese_simplified"],"浸":["chinese_simplified","chinese_traditional"],"泉":["chinese_simplified","chinese_traditional"],"帽":["chinese_simplified","chinese_traditional"],"迟":["chinese_simplified"],"硅":["chinese_simplified"],"疆":["chinese_simplified","chinese_traditional"],"贷":["chinese_simplified"],"漏":["chinese_simplified","chinese_traditional"],"稿":["chinese_simplified","chinese_traditional"],"冠":["chinese_simplified","chinese_traditional"],"嫩":["chinese_simplified","chinese_traditional"],"胁":["chinese_simplified"],"芯":["chinese_simplified","chinese_traditional"],"牢":["chinese_simplified","chinese_traditional"],"叛":["chinese_simplified","chinese_traditional"],"蚀":["chinese_simplified"],"奥":["chinese_simplified"],"鸣":["chinese_simplified"],"岭":["chinese_simplified"],"羊":["chinese_simplified","chinese_traditional"],"凭":["chinese_simplified"],"串":["chinese_simplified","chinese_traditional"],"塘":["chinese_simplified","chinese_traditional"],"绘":["chinese_simplified"],"酵":["chinese_simplified","chinese_traditional"],"融":["chinese_simplified","chinese_traditional"],"盆":["chinese_simplified","chinese_traditional"],"锡":["chinese_simplified"],"庙":["chinese_simplified"],"筹":["chinese_simplified"],"冻":["chinese_simplified"],"辅":["chinese_simplified"],"摄":["chinese_simplified"],"袭":["chinese_simplified"],"筋":["chinese_simplified","chinese_traditional"],"拒":["chinese_simplified","chinese_traditional"],"僚":["chinese_simplified","chinese_traditional"],"旱":["chinese_simplified","chinese_traditional"],"钾":["chinese_simplified"],"鸟":["chinese_simplified"],"漆":["chinese_simplified","chinese_traditional"],"沈":["chinese_simplified","chinese_traditional"],"眉":["chinese_simplified","chinese_traditional"],"疏":["chinese_simplified","chinese_traditional"],"添":["chinese_simplified","chinese_traditional"],"棒":["chinese_simplified","chinese_traditional"],"穗":["chinese_simplified","chinese_traditional"],"硝":["chinese_simplified","chinese_traditional"],"韩":["chinese_simplified"],"逼":["chinese_simplified","chinese_traditional"],"扭":["chinese_simplified","chinese_traditional"],"侨":["chinese_simplified"],"凉":["chinese_simplified"],"挺":["chinese_simplified","chinese_traditional"],"碗":["chinese_simplified","chinese_traditional"],"栽":["chinese_simplified","chinese_traditional"],"炒":["chinese_simplified","chinese_traditional"],"杯":["chinese_simplified","chinese_traditional"],"患":["chinese_simplified","chinese_traditional"],"馏":["chinese_simplified"],"劝":["chinese_simplified"],"豪":["chinese_simplified","chinese_traditional"],"辽":["chinese_simplified"],"勃":["chinese_simplified","chinese_traditional"],"鸿":["chinese_simplified"],"旦":["chinese_simplified","chinese_traditional"],"吏":["chinese_simplified","chinese_traditional"],"拜":["chinese_simplified","chinese_traditional"],"狗":["chinese_simplified","chinese_traditional"],"埋":["chinese_simplified","chinese_traditional"],"辊":["chinese_simplified"],"掩":["chinese_simplified","chinese_traditional"],"饮":["chinese_simplified"],"搬":["chinese_simplified","chinese_traditional"],"骂":["chinese_simplified"],"辞":["chinese_simplified"],"勾":["chinese_simplified","chinese_traditional"],"扣":["chinese_simplified","chinese_traditional"],"估":["chinese_simplified","chinese_traditional"],"蒋":["chinese_simplified"],"绒":["chinese_simplified"],"雾":["chinese_simplified"],"丈":["chinese_simplified","chinese_traditional"],"朵":["chinese_simplified","chinese_traditional"],"姆":["chinese_simplified","chinese_traditional"],"拟":["chinese_simplified"],"宇":["chinese_simplified","chinese_traditional"],"辑":["chinese_simplified"],"陕":["chinese_simplified"],"雕":["chinese_simplified","chinese_traditional"],"偿":["chinese_simplified"],"蓄":["chinese_simplified","chinese_traditional"],"崇":["chinese_simplified","chinese_traditional"],"剪":["chinese_simplified","chinese_traditional"],"倡":["chinese_simplified","chinese_traditional"],"厅":["chinese_simplified"],"咬":["chinese_simplified","chinese_traditional"],"驶":["chinese_simplified"],"薯":["chinese_simplified","chinese_traditional"],"刷":["chinese_simplified","chinese_traditional"],"斥":["chinese_simplified","chinese_traditional"],"番":["chinese_simplified","chinese_traditional"],"赋":["chinese_simplified"],"奉":["chinese_simplified","chinese_traditional"],"佛":["chinese_simplified","chinese_traditional"],"浇":["chinese_simplified"],"漫":["chinese_simplified","chinese_traditional"],"曼":["chinese_simplified","chinese_traditional"],"扇":["chinese_simplified","chinese_traditional"],"钙":["chinese_simplified"],"桃":["chinese_simplified","chinese_traditional"],"扶":["chinese_simplified","chinese_traditional"],"仔":["chinese_simplified","chinese_traditional"],"返":["chinese_simplified","chinese_traditional"],"俗":["chinese_simplified","chinese_traditional"],"亏":["chinese_simplified"],"腔":["chinese_simplified","chinese_traditional"],"鞋":["chinese_simplified","chinese_traditional"],"棱":["chinese_simplified","chinese_traditional"],"覆":["chinese_simplified","chinese_traditional"],"框":["chinese_simplified","chinese_traditional"],"悄":["chinese_simplified","chinese_traditional"],"叔":["chinese_simplified","chinese_traditional"],"撞":["chinese_simplified","chinese_traditional"],"骗":["chinese_simplified"],"勘":["chinese_simplified","chinese_traditional"],"旺":["chinese_simplified","chinese_traditional"],"沸":["chinese_simplified","chinese_traditional"],"孤":["chinese_simplified","chinese_traditional"],"吐":["chinese_simplified","chinese_traditional"],"孟":["chinese_simplified","chinese_traditional"],"渠":["chinese_simplified","chinese_traditional"],"屈":["chinese_simplified","chinese_traditional"],"疾":["chinese_simplified","chinese_traditional"],"妙":["chinese_simplified","chinese_traditional"],"惜":["chinese_simplified","chinese_traditional"],"仰":["chinese_simplified","chinese_traditional"],"狠":["chinese_simplified","chinese_traditional"],"胀":["chinese_simplified"],"谐":["chinese_simplified"],"抛":["chinese_simplified"],"霉":["chinese_simplified"],"桑":["chinese_simplified","chinese_traditional"],"岗":["chinese_simplified"],"嘛":["chinese_simplified","chinese_traditional"],"衰":["chinese_simplified","chinese_traditional"],"盗":["chinese_simplified"],"渗":["chinese_simplified"],"脏":["chinese_simplified"],"赖":["chinese_simplified"],"涌":["chinese_simplified"],"甜":["chinese_simplified","chinese_traditional"],"曹":["chinese_simplified","chinese_traditional"],"阅":["chinese_simplified"],"肌":["chinese_simplified","chinese_traditional"],"哩":["chinese_simplified","chinese_traditional"],"厉":["chinese_simplified"],"烃":["chinese_simplified"],"纬":["chinese_simplified"],"毅":["chinese_simplified","chinese_traditional"],"昨":["chinese_simplified","chinese_traditional"],"伪":["chinese_simplified"],"症":["chinese_simplified","chinese_traditional"],"煮":["chinese_simplified","chinese_traditional"],"叹":["chinese_simplified"],"钉":["chinese_simplified"],"搭":["chinese_simplified","chinese_traditional"],"茎":["chinese_simplified"],"笼":["chinese_simplified"],"酷":["chinese_simplified","chinese_traditional"],"偷":["chinese_simplified","chinese_traditional"],"弓":["chinese_simplified","chinese_traditional"],"锥":["chinese_simplified"],"恒":["chinese_simplified"],"杰":["chinese_simplified"],"坑":["chinese_simplified","chinese_traditional"],"鼻":["chinese_simplified","chinese_traditional"],"翼":["chinese_simplified","chinese_traditional"],"纶":["chinese_simplified"],"叙":["chinese_simplified"],"狱":["chinese_simplified"],"逮":["chinese_simplified","chinese_traditional"],"罐":["chinese_simplified","chinese_traditional"],"络":["chinese_simplified"],"棚":["chinese_simplified","chinese_traditional"],"抑":["chinese_simplified","chinese_traditional"],"膨":["chinese_simplified","chinese_traditional"],"蔬":["chinese_simplified","chinese_traditional"],"寺":["chinese_simplified","chinese_traditional"],"骤":["chinese_simplified"],"穆":["chinese_simplified","chinese_traditional"],"冶":["chinese_simplified","chinese_traditional"],"枯":["chinese_simplified","chinese_traditional"],"册":["chinese_simplified"],"尸":["chinese_simplified"],"凸":["chinese_simplified","chinese_traditional"],"绅":["chinese_simplified"],"坯":["chinese_simplified","chinese_traditional"],"牺":["chinese_simplified"],"焰":["chinese_simplified","chinese_traditional"],"轰":["chinese_simplified"],"欣":["chinese_simplified","chinese_traditional"],"晋":["chinese_simplified"],"瘦":["chinese_simplified","chinese_traditional"],"御":["chinese_simplified"],"锭":["chinese_simplified"],"锦":["chinese_simplified"],"丧":["chinese_simplified"],"旬":["chinese_simplified","chinese_traditional"],"锻":["chinese_simplified"],"垄":["chinese_simplified"],"搜":["chinese_simplified","chinese_traditional"],"扑":["chinese_simplified"],"邀":["chinese_simplified","chinese_traditional"],"亭":["chinese_simplified","chinese_traditional"],"酯":["chinese_simplified","chinese_traditional"],"迈":["chinese_simplified"],"舒":["chinese_simplified","chinese_traditional"],"脆":["chinese_simplified","chinese_traditional"],"酶":["chinese_simplified","chinese_traditional"],"闲":["chinese_simplified"],"忧":["chinese_simplified"],"酚":["chinese_simplified","chinese_traditional"],"顽":["chinese_simplified"],"羽":["chinese_simplified","chinese_traditional"],"涨":["chinese_simplified"],"卸":["chinese_simplified","chinese_traditional"],"仗":["chinese_simplified","chinese_traditional"],"陪":["chinese_simplified","chinese_traditional"],"辟":["chinese_simplified"],"惩":["chinese_simplified"],"杭":["chinese_simplified","chinese_traditional"],"姚":["chinese_simplified","chinese_traditional"],"肚":["chinese_simplified","chinese_traditional"],"捉":["chinese_simplified","chinese_traditional"],"飘":["chinese_simplified"],"漂":["chinese_simplified","chinese_traditional"],"昆":["chinese_simplified","chinese_traditional"],"欺":["chinese_simplified","chinese_traditional"],"吾":["chinese_simplified","chinese_traditional"],"郎":["chinese_simplified","chinese_traditional"],"烷":["chinese_simplified","chinese_traditional"],"汁":["chinese_simplified","chinese_traditional"],"呵":["chinese_simplified","chinese_traditional"],"饰":["chinese_simplified"],"萧":["chinese_simplified"],"雅":["chinese_simplified","chinese_traditional"],"邮":["chinese_simplified"],"迁":["chinese_simplified"],"燕":["chinese_simplified","chinese_traditional"],"撒":["chinese_simplified","chinese_traditional"],"姻":["chinese_simplified","chinese_traditional"],"赴":["chinese_simplified","chinese_traditional"],"宴":["chinese_simplified","chinese_traditional"],"烦":["chinese_simplified"],"债":["chinese_simplified"],"帐":["chinese_simplified"],"斑":["chinese_simplified","chinese_traditional"],"铃":["chinese_simplified"],"旨":["chinese_simplified","chinese_traditional"],"醇":["chinese_simplified","chinese_traditional"],"董":["chinese_simplified","chinese_traditional"],"饼":["chinese_simplified"],"雏":["chinese_simplified"],"姿":["chinese_simplified","chinese_traditional"],"拌":["chinese_simplified","chinese_traditional"],"傅":["chinese_simplified","chinese_traditional"],"腹":["chinese_simplified","chinese_traditional"],"妥":["chinese_simplified","chinese_traditional"],"揉":["chinese_simplified","chinese_traditional"],"贤":["chinese_simplified"],"拆":["chinese_simplified","chinese_traditional"],"歪":["chinese_simplified","chinese_traditional"],"葡":["chinese_simplified","chinese_traditional"],"胺":["chinese_simplified","chinese_traditional"],"丢":["chinese_simplified"],"浩":["chinese_simplified","chinese_traditional"],"徽":["chinese_simplified","chinese_traditional"],"昂":["chinese_simplified","chinese_traditional"],"垫":["chinese_simplified"],"挡":["chinese_simplified"],"览":["chinese_simplified"],"贪":["chinese_simplified"],"慰":["chinese_simplified","chinese_traditional"],"缴":["chinese_simplified"],"汪":["chinese_simplified","chinese_traditional"],"慌":["chinese_simplified","chinese_traditional"],"冯":["chinese_simplified"],"诺":["chinese_simplified"],"姜":["chinese_simplified","chinese_traditional"],"谊":["chinese_simplified"],"凶":["chinese_simplified"],"劣":["chinese_simplified","chinese_traditional"],"诬":["chinese_simplified"],"耀":["chinese_simplified","chinese_traditional"],"昏":["chinese_simplified","chinese_traditional"],"躺":["chinese_simplified","chinese_traditional"],"盈":["chinese_simplified","chinese_traditional"],"骑":["chinese_simplified"],"乔":["chinese_simplified"],"溪":["chinese_simplified","chinese_traditional"],"丛":["chinese_simplified"],"卢":["chinese_simplified"],"抹":["chinese_simplified","chinese_traditional"],"闷":["chinese_simplified"],"咨":["chinese_simplified"],"刮":["chinese_simplified","chinese_traditional"],"驾":["chinese_simplified"],"缆":["chinese_simplified"],"悟":["chinese_simplified","chinese_traditional"],"摘":["chinese_simplified","chinese_traditional"],"铒":["chinese_simplified"],"掷":["chinese_simplified"],"颇":["chinese_simplified"],"幻":["chinese_simplified","chinese_traditional"],"柄":["chinese_simplified","chinese_traditional"],"惠":["chinese_simplified","chinese_traditional"],"惨":["chinese_simplified"],"佳":["chinese_simplified","chinese_traditional"],"仇":["chinese_simplified","chinese_traditional"],"腊":["chinese_simplified"],"窝":["chinese_simplified"],"涤":["chinese_simplified"],"剑":["chinese_simplified"],"瞧":["chinese_simplified","chinese_traditional"],"堡":["chinese_simplified","chinese_traditional"],"泼":["chinese_simplified"],"葱":["chinese_simplified"],"罩":["chinese_simplified","chinese_traditional"],"霍":["chinese_simplified","chinese_traditional"],"捞":["chinese_simplified"],"胎":["chinese_simplified","chinese_traditional"],"苍":["chinese_simplified"],"滨":["chinese_simplified"],"俩":["chinese_simplified"],"捅":["chinese_simplified","chinese_traditional"],"湘":["chinese_simplified","chinese_traditional"],"砍":["chinese_simplified","chinese_traditional"],"霞":["chinese_simplified","chinese_traditional"],"邵":["chinese_simplified","chinese_traditional"],"萄":["chinese_simplified","chinese_traditional"],"疯":["chinese_simplified"],"淮":["chinese_simplified","chinese_traditional"],"遂":["chinese_simplified","chinese_traditional"],"熊":["chinese_simplified","chinese_traditional"],"粪":["chinese_simplified"],"烘":["chinese_simplified","chinese_traditional"],"宿":["chinese_simplified","chinese_traditional"],"档":["chinese_simplified"],"戈":["chinese_simplified","chinese_traditional"],"驳":["chinese_simplified"],"嫂":["chinese_simplified","chinese_traditional"],"裕":["chinese_simplified","chinese_traditional"],"徙":["chinese_simplified","chinese_traditional"],"箭":["chinese_simplified","chinese_traditional"],"捐":["chinese_simplified","chinese_traditional"],"肠":["chinese_simplified"],"撑":["chinese_simplified"],"晒":["chinese_simplified"],"辨":["chinese_simplified","chinese_traditional"],"殿":["chinese_simplified","chinese_traditional"],"莲":["chinese_simplified"],"摊":["chinese_simplified"],"搅":["chinese_simplified"],"酱":["chinese_simplified"],"屏":["chinese_simplified","chinese_traditional"],"疫":["chinese_simplified","chinese_traditional"],"哀":["chinese_simplified","chinese_traditional"],"蔡":["chinese_simplified","chinese_traditional"],"堵":["chinese_simplified","chinese_traditional"],"沫":["chinese_simplified","chinese_traditional"],"皱":["chinese_simplified"],"畅":["chinese_simplified"],"叠":["chinese_simplified"],"阁":["chinese_simplified"],"莱":["chinese_simplified"],"敲":["chinese_simplified","chinese_traditional"],"辖":["chinese_simplified"],"钩":["chinese_simplified"],"痕":["chinese_simplified","chinese_traditional"],"坝":["chinese_simplified"],"巷":["chinese_simplified","chinese_traditional"],"饿":["chinese_simplified"],"祸":["chinese_simplified"],"丘":["chinese_simplified","chinese_traditional"],"玄":["chinese_simplified","chinese_traditional"],"溜":["chinese_simplified","chinese_traditional"],"曰":["chinese_simplified","chinese_traditional"],"逻":["chinese_simplified"],"彭":["chinese_simplified","chinese_traditional"],"尝":["chinese_simplified"],"卿":["chinese_simplified","chinese_traditional"],"妨":["chinese_simplified","chinese_traditional"],"艇":["chinese_simplified","chinese_traditional"],"吞":["chinese_simplified","chinese_traditional"],"韦":["chinese_simplified"],"怨":["chinese_simplified","chinese_traditional"],"矮":["chinese_simplified","chinese_traditional"],"歇":["chinese_simplified","chinese_traditional"],"這":["chinese_traditional"],"為":["chinese_traditional"],"個":["chinese_traditional"],"國":["chinese_traditional"],"時":["chinese_traditional"],"來":["chinese_traditional"],"們":["chinese_traditional"],"於":["chinese_traditional"],"對":["chinese_traditional"],"會":["chinese_traditional"],"發":["chinese_traditional"],"動":["chinese_traditional"],"過":["chinese_traditional"],"說":["chinese_traditional"],"產":["chinese_traditional"],"種":["chinese_traditional"],"後":["chinese_traditional"],"學":["chinese_traditional"],"經":["chinese_traditional"],"進":["chinese_traditional"],"著":["chinese_traditional"],"電":["chinese_traditional"],"裡":["chinese_traditional"],"現":["chinese_traditional"],"實":["chinese_traditional"],"兩":["chinese_traditional"],"體":["chinese_traditional"],"機":["chinese_traditional"],"當":["chinese_traditional"],"點":["chinese_traditional"],"從":["chinese_traditional"],"業":["chinese_traditional"],"應":["chinese_traditional"],"開":["chinese_traditional"],"還":["chinese_traditional"],"義":["chinese_traditional"],"間":["chinese_traditional"],"樣":["chinese_traditional"],"與":["chinese_traditional"],"關":["chinese_traditional"],"線":["chinese_traditional"],"內":["chinese_traditional"],"數":["chinese_traditional"],"麼":["chinese_traditional"],"質":["chinese_traditional"],"氣":["chinese_traditional"],"變":["chinese_traditional"],"條":["chinese_traditional"],"沒":["chinese_traditional"],"結":["chinese_traditional"],"問":["chinese_traditional"],"無":["chinese_traditional"],"軍":["chinese_traditional"],"並":["chinese_traditional"],"題":["chinese_traditional"],"黨":["chinese_traditional"],"員":["chinese_traditional"],"總":["chinese_traditional"],"設":["chinese_traditional"],"長":["chinese_traditional"],"頭":["chinese_traditional"],"資":["chinese_traditional"],"邊":["chinese_traditional"],"級":["chinese_traditional"],"圖":["chinese_traditional"],"統":["chinese_traditional"],"較":["chinese_traditional"],"將":["chinese_traditional"],"組":["chinese_traditional"],"見":["chinese_traditional"],"計":["chinese_traditional"],"別":["chinese_traditional"],"論":["chinese_traditional"],"運":["chinese_traditional"],"農":["chinese_traditional"],"幾":["chinese_traditional"],"區":["chinese_traditional"],"強":["chinese_traditional"],"決":["chinese_traditional"],"幹":["chinese_traditional"],"戰":["chinese_traditional"],"則":["chinese_traditional"],"據":["chinese_traditional"],"處":["chinese_traditional"],"隊":["chinese_traditional"],"給":["chinese_traditional"],"門":["chinese_traditional"],"規":["chinese_traditional"],"熱":["chinese_traditional"],"領":["chinese_traditional"],"東":["chinese_traditional"],"導":["chinese_traditional"],"壓":["chinese_traditional"],"爭":["chinese_traditional"],"濟":["chinese_traditional"],"階":["chinese_traditional"],"術":["chinese_traditional"],"極":["chinese_traditional"],"聯":["chinese_traditional"],"認":["chinese_traditional"],"權":["chinese_traditional"],"證":["chinese_traditional"],"採":["chinese_traditional"],"轉":["chinese_traditional"],"單":["chinese_traditional"],"風":["chinese_traditional"],"帶":["chinese_traditional"],"場":["chinese_traditional"],"車":["chinese_traditional"],"務":["chinese_traditional"],"萬":["chinese_traditional"],"達":["chinese_traditional"],"積":["chinese_traditional"],"議":["chinese_traditional"],"聲":["chinese_traditional"],"報":["chinese_traditional"],"鬥":["chinese_traditional"],"類":["chinese_traditional"],"離":["chinese_traditional"],"華":["chinese_traditional"],"確":["chinese_traditional"],"張":["chinese_traditional"],"馬":["chinese_traditional"],"節":["chinese_traditional"],"話":["chinese_traditional"],"況":["chinese_traditional"],"溫":["chinese_traditional"],"傳":["chinese_traditional"],"許":["chinese_traditional"],"廣":["chinese_traditional"],"記":["chinese_traditional"],"觀":["chinese_traditional"],"織":["chinese_traditional"],"裝":["chinese_traditional"],"眾":["chinese_traditional"],"書":["chinese_traditional"],"兒":["chinese_traditional"],"須":["chinese_traditional"],"際":["chinese_traditional"],"驗":["chinese_traditional"],"連":["chinese_traditional"],"斷":["chinese_traditional"],"難":["chinese_traditional"],"礦":["chinese_traditional"],"週":["chinese_traditional"],"備":["chinese_traditional"],"辦":["chinese_traditional"],"習":["chinese_traditional"],"響":["chinese_traditional"],"約":["chinese_traditional"],"勞":["chinese_traditional"],"團":["chinese_traditional"],"歷":["chinese_traditional"],"構":["chinese_traditional"],"稱":["chinese_traditional"],"準":["chinese_traditional"],"號":["chinese_traditional"],"維":["chinese_traditional"],"劃":["chinese_traditional"],"選":["chinese_traditional"],"標":["chinese_traditional"],"寫":["chinese_traditional"],"親":["chinese_traditional"],"養":["chinese_traditional"],"層":["chinese_traditional"],"卻":["chinese_traditional"],"專":["chinese_traditional"],"狀":["chinese_traditional"],"廠":["chinese_traditional"],"識":["chinese_traditional"],"適":["chinese_traditional"],"屬":["chinese_traditional"],"圓":["chinese_traditional"],"調":["chinese_traditional"],"滿":["chinese_traditional"],"縣":["chinese_traditional"],"參":["chinese_traditional"],"紅":["chinese_traditional"],"細":["chinese_traditional"],"聽":["chinese_traditional"],"該":["chinese_traditional"],"鐵":["chinese_traditional"],"價":["chinese_traditional"],"嚴":["chinese_traditional"],"隨":["chinese_traditional"],"蘇":["chinese_traditional"],"爾":["chinese_traditional"],"講":["chinese_traditional"],"黃":["chinese_traditional"],"顯":["chinese_traditional"],"談":["chinese_traditional"],"藝":["chinese_traditional"],"營":["chinese_traditional"],"項":["chinese_traditional"],"舉":["chinese_traditional"],"勢":["chinese_traditional"],"幫":["chinese_traditional"],"輪":["chinese_traditional"],"亞":["chinese_traditional"],"師":["chinese_traditional"],"圍":["chinese_traditional"],"遠":["chinese_traditional"],"態":["chinese_traditional"],"減":["chinese_traditional"],"樹":["chinese_traditional"],"葉":["chinese_traditional"],"魚":["chinese_traditional"],"視":["chinese_traditional"],"僅":["chinese_traditional"],"費":["chinese_traditional"],"緊":["chinese_traditional"],"愛":["chinese_traditional"],"續":["chinese_traditional"],"輕":["chinese_traditional"],"試":["chinese_traditional"],"護":["chinese_traditional"],"練":["chinese_traditional"],"負":["chinese_traditional"],"擊":["chinese_traditional"],"繼":["chinese_traditional"],"興":["chinese_traditional"],"餘":["chinese_traditional"],"堅":["chinese_traditional"],"輸":["chinese_traditional"],"夠":["chinese_traditional"],"筆":["chinese_traditional"],"佔":["chinese_traditional"],"財":["chinese_traditional"],"職":["chinese_traditional"],"覺":["chinese_traditional"],"漢":["chinese_traditional"],"畫":["chinese_traditional"],"雖":["chinese_traditional"],"雜":["chinese_traditional"],"飛":["chinese_traditional"],"檢":["chinese_traditional"],"昇":["chinese_traditional"],"陽":["chinese_traditional"],"創":["chinese_traditional"],"壞":["chinese_traditional"],"徑":["chinese_traditional"],"換":["chinese_traditional"],"鋼":["chinese_traditional"],"責":["chinese_traditional"],"簡":["chinese_traditional"],"錢":["chinese_traditional"],"盡":["chinese_traditional"],"衝":["chinese_traditional"],"獨":["chinese_traditional"],"環":["chinese_traditional"],"雙":["chinese_traditional"],"請":["chinese_traditional"],"讓":["chinese_traditional"],"軸":["chinese_traditional"],"紀":["chinese_traditional"],"優":["chinese_traditional"],"頂":["chinese_traditional"],"礎":["chinese_traditional"],"載":["chinese_traditional"],"敵":["chinese_traditional"],"勝":["chinese_traditional"],"絕":["chinese_traditional"],"塊":["chinese_traditional"],"劑":["chinese_traditional"],"測":["chinese_traditional"],"絲":["chinese_traditional"],"協":["chinese_traditional"],"訴":["chinese_traditional"],"陳":["chinese_traditional"],"羅":["chinese_traditional"],"鹽":["chinese_traditional"],"錯":["chinese_traditional"],"頻":["chinese_traditional"],"終":["chinese_traditional"],"雲":["chinese_traditional"],"衛":["chinese_traditional"],"燒":["chinese_traditional"],"遊":["chinese_traditional"],"舊":["chinese_traditional"],"貨":["chinese_traditional"],"損":["chinese_traditional"],"預":["chinese_traditional"],"穩":["chinese_traditional"],"媽":["chinese_traditional"],"擴":["chinese_traditional"],"銀":["chinese_traditional"],"語":["chinese_traditional"],"揮":["chinese_traditional"],"紙":["chinese_traditional"],"醫":["chinese_traditional"],"嗎":["chinese_traditional"],"針":["chinese_traditional"],"劉":["chinese_traditional"],"誤":["chinese_traditional"],"訓":["chinese_traditional"],"願":["chinese_traditional"],"審":["chinese_traditional"],"獲":["chinese_traditional"],"鮮":["chinese_traditional"],"糧":["chinese_traditional"],"脫":["chinese_traditional"],"龍":["chinese_traditional"],"漸":["chinese_traditional"],"歡":["chinese_traditional"],"剛":["chinese_traditional"],"謂":["chinese_traditional"],"討":["chinese_traditional"],"亂":["chinese_traditional"],"殺":["chinese_traditional"],"藥":["chinese_traditional"],"寧":["chinese_traditional"],"魯":["chinese_traditional"],"貴":["chinese_traditional"],"鐘":["chinese_traditional"],"讀":["chinese_traditional"],"豐":["chinese_traditional"],"蘭":["chinese_traditional"],"擔":["chinese_traditional"],"執":["chinese_traditional"],"樂":["chinese_traditional"],"誰":["chinese_traditional"],"順":["chinese_traditional"],"煙":["chinese_traditional"],"縮":["chinese_traditional"],"徵":["chinese_traditional"],"臉":["chinese_traditional"],"腳":["chinese_traditional"],"異":["chinese_traditional"],"買":["chinese_traditional"],"靜":["chinese_traditional"],"補":["chinese_traditional"],"評":["chinese_traditional"],"踐":["chinese_traditional"],"寬":["chinese_traditional"],"揚":["chinese_traditional"],"傷":["chinese_traditional"],"氫":["chinese_traditional"],"憲":["chinese_traditional"],"慶":["chinese_traditional"],"編":["chinese_traditional"],"觸":["chinese_traditional"],"銷":["chinese_traditional"],"詩":["chinese_traditional"],"綠":["chinese_traditional"],"雞":["chinese_traditional"],"孫":["chinese_traditional"],"膠":["chinese_traditional"],"鄉":["chinese_traditional"],"臨":["chinese_traditional"],"陸":["chinese_traditional"],"顧":["chinese_traditional"],"燈":["chinese_traditional"],"歲":["chinese_traditional"],"劇":["chinese_traditional"],"趙":["chinese_traditional"],"課":["chinese_traditional"],"凱":["chinese_traditional"],"額":["chinese_traditional"],"紹":["chinese_traditional"],"齊":["chinese_traditional"],"偉":["chinese_traditional"],"爐":["chinese_traditional"],"楊":["chinese_traditional"],"桿":["chinese_traditional"],"鎮":["chinese_traditional"],"飯":["chinese_traditional"],"濃":["chinese_traditional"],"懷":["chinese_traditional"],"趕":["chinese_traditional"],"庫":["chinese_traditional"],"奪":["chinese_traditional"],"靈":["chinese_traditional"],"稅":["chinese_traditional"],"滅":["chinese_traditional"],"賽":["chinese_traditional"],"歸":["chinese_traditional"],"盤":["chinese_traditional"],"險":["chinese_traditional"],"錄":["chinese_traditional"],"純":["chinese_traditional"],"蓋":["chinese_traditional"],"橫":["chinese_traditional"],"槍":["chinese_traditional"],"潤":["chinese_traditional"],"蟲":["chinese_traditional"],"澤":["chinese_traditional"],"腦":["chinese_traditional"],"歐":["chinese_traditional"],"側":["chinese_traditional"],"徹":["chinese_traditional"],"慮":["chinese_traditional"],"納":["chinese_traditional"],"彈":["chinese_traditional"],"飼":["chinese_traditional"],"麥":["chinese_traditional"],"濕":["chinese_traditional"],"築":["chinese_traditional"],"惡":["chinese_traditional"],"戶":["chinese_traditional"],"訪":["chinese_traditional"],"跡":["chinese_traditional"],"擺":["chinese_traditional"],"賣":["chinese_traditional"],"擇":["chinese_traditional"],"銅":["chinese_traditional"],"獻":["chinese_traditional"],"陣":["chinese_traditional"],"陰":["chinese_traditional"],"樓":["chinese_traditional"],"謀":["chinese_traditional"],"噸":["chinese_traditional"],"豬":["chinese_traditional"],"館":["chinese_traditional"],"爺":["chinese_traditional"],"驚":["chinese_traditional"],"遺":["chinese_traditional"],"纖":["chinese_traditional"],"傾":["chinese_traditional"],"謝":["chinese_traditional"],"奮":["chinese_traditional"],"購":["chinese_traditional"],"監":["chinese_traditional"],"貫":["chinese_traditional"],"釋":["chinese_traditional"],"詞":["chinese_traditional"],"頓":["chinese_traditional"],"寶":["chinese_traditional"],"塵":["chinese_traditional"],"聞":["chinese_traditional"],"殘":["chinese_traditional"],"橋":["chinese_traditional"],"婦":["chinese_traditional"],"綜":["chinese_traditional"],"吳":["chinese_traditional"],"搖":["chinese_traditional"],"贊":["chinese_traditional"],"訂":["chinese_traditional"],"園":["chinese_traditional"],"紛":["chinese_traditional"],"敗":["chinese_traditional"],"榮":["chinese_traditional"],"閉":["chinese_traditional"],"灣":["chinese_traditional"],"鍵":["chinese_traditional"],"駐":["chinese_traditional"],"鍋":["chinese_traditional"],"剝":["chinese_traditional"],"鹼":["chinese_traditional"],"齒":["chinese_traditional"],"煉":["chinese_traditional"],"紡":["chinese_traditional"],"廢":["chinese_traditional"],"緩":["chinese_traditional"],"淨":["chinese_traditional"],"莊":["chinese_traditional"],"貿":["chinese_traditional"],"慣":["chinese_traditional"],"夥":["chinese_traditional"],"勻":["chinese_traditional"],"紗":["chinese_traditional"],"辯":["chinese_traditional"],"億":["chinese_traditional"],"脈":["chinese_traditional"],"薩":["chinese_traditional"],"網":["chinese_traditional"],"噴":["chinese_traditional"],"縱":["chinese_traditional"],"掛":["chinese_traditional"],"賀":["chinese_traditional"],"閃":["chinese_traditional"],"牆":["chinese_traditional"],"軟":["chinese_traditional"],"滾":["chinese_traditional"],"盪":["chinese_traditional"],"儀":["chinese_traditional"],"軋":["chinese_traditional"],"貢":["chinese_traditional"],"鑽":["chinese_traditional"],"幣":["chinese_traditional"],"軌":["chinese_traditional"],"畝":["chinese_traditional"],"畢":["chinese_traditional"],"島":["chinese_traditional"],"鑄":["chinese_traditional"],"湯":["chinese_traditional"],"閥":["chinese_traditional"],"匯":["chinese_traditional"],"繞":["chinese_traditional"],"績":["chinese_traditional"],"啟":["chinese_traditional"],"顏":["chinese_traditional"],"淚":["chinese_traditional"],"藍":["chinese_traditional"],"鏡":["chinese_traditional"],"壯":["chinese_traditional"],"鋒":["chinese_traditional"],"貧":["chinese_traditional"],"虛":["chinese_traditional"],"彎":["chinese_traditional"],"綱":["chinese_traditional"],"隸":["chinese_traditional"],"宮":["chinese_traditional"],"違":["chinese_traditional"],"夾":["chinese_traditional"],"緣":["chinese_traditional"],"窮":["chinese_traditional"],"溝":["chinese_traditional"],"繩":["chinese_traditional"],"憶":["chinese_traditional"],"漿":["chinese_traditional"],"欄":["chinese_traditional"],"擁":["chinese_traditional"],"貯":["chinese_traditional"],"禮":["chinese_traditional"],"濾":["chinese_traditional"],"鈉":["chinese_traditional"],"紋":["chinese_traditional"],"罷":["chinese_traditional"],"罰":["chinese_traditional"],"潛":["chinese_traditional"],"縫":["chinese_traditional"],"飽":["chinese_traditional"],"獎":["chinese_traditional"],"鋁":["chinese_traditional"],"麗":["chinese_traditional"],"鏈":["chinese_traditional"],"掃":["chinese_traditional"],"諸":["chinese_traditional"],"勵":["chinese_traditional"],"潔":["chinese_traditional"],"災":["chinese_traditional"],"鑑":["chinese_traditional"],"訟":["chinese_traditional"],"毀":["chinese_traditional"],"屆":["chinese_traditional"],"躍":["chinese_traditional"],"艱":["chinese_traditional"],"貝":["chinese_traditional"],"碼":["chinese_traditional"],"夢":["chinese_traditional"],"漁":["chinese_traditional"],"顆":["chinese_traditional"],"鉛":["chinese_traditional"],"倉":["chinese_traditional"],"銳":["chinese_traditional"],"曉":["chinese_traditional"],"隱":["chinese_traditional"],"礙":["chinese_traditional"],"撥":["chinese_traditional"],"肅":["chinese_traditional"],"牽":["chinese_traditional"],"搶":["chinese_traditional"],"殼":["chinese_traditional"],"訊":["chinese_traditional"],"誠":["chinese_traditional"],"頁":["chinese_traditional"],"齡":["chinese_traditional"],"倫":["chinese_traditional"],"尋":["chinese_traditional"],"鋪":["chinese_traditional"],"聖":["chinese_traditional"],"鄭":["chinese_traditional"],"騰":["chinese_traditional"],"貼":["chinese_traditional"],"闊":["chinese_traditional"],"輛":["chinese_traditional"],"儲":["chinese_traditional"],"簽":["chinese_traditional"],"鬧":["chinese_traditional"],"擾":["chinese_traditional"],"遞":["chinese_traditional"],"戲":["chinese_traditional"],"餵":["chinese_traditional"],"療":["chinese_traditional"],"撫":["chinese_traditional"],"蝦":["chinese_traditional"],"蠟":["chinese_traditional"],"鄰":["chinese_traditional"],"鞏":["chinese_traditional"],"擠":["chinese_traditional"],"棄":["chinese_traditional"],"勁":["chinese_traditional"],"鄧":["chinese_traditional"],"爛":["chinese_traditional"],"磚":["chinese_traditional"],"烏":["chinese_traditional"],"艦":["chinese_traditional"],"淺":["chinese_traditional"],"暫":["chinese_traditional"],"膽":["chinese_traditional"],"詳":["chinese_traditional"],"譜":["chinese_traditional"],"賓":["chinese_traditional"],"輝":["chinese_traditional"],"憤":["chinese_traditional"],"競":["chinese_traditional"],"緒":["chinese_traditional"],"塗":["chinese_traditional"],"偵":["chinese_traditional"],"懸":["chinese_traditional"],"糾":["chinese_traditional"],"鎖":["chinese_traditional"],"賞":["chinese_traditional"],"鴨":["chinese_traditional"],"趨":["chinese_traditional"],"鳳":["chinese_traditional"],"輩":["chinese_traditional"],"灘":["chinese_traditional"],"驅":["chinese_traditional"],"篩":["chinese_traditional"],"峽":["chinese_traditional"],"壽":["chinese_traditional"],"譯":["chinese_traditional"],"遲":["chinese_traditional"],"矽":["chinese_traditional"],"貸":["chinese_traditional"],"脅":["chinese_traditional"],"蝕":["chinese_traditional"],"奧":["chinese_traditional"],"鳴":["chinese_traditional"],"嶺":["chinese_traditional"],"憑":["chinese_traditional"],"繪":["chinese_traditional"],"錫":["chinese_traditional"],"廟":["chinese_traditional"],"籌":["chinese_traditional"],"凍":["chinese_traditional"],"輔":["chinese_traditional"],"攝":["chinese_traditional"],"襲":["chinese_traditional"],"鉀":["chinese_traditional"],"鳥":["chinese_traditional"],"韓":["chinese_traditional"],"僑":["chinese_traditional"],"涼":["chinese_traditional"],"餾":["chinese_traditional"],"勸":["chinese_traditional"],"遼":["chinese_traditional"],"鴻":["chinese_traditional"],"輥":["chinese_traditional"],"飲":["chinese_traditional"],"罵":["chinese_traditional"],"辭":["chinese_traditional"],"蔣":["chinese_traditional"],"絨":["chinese_traditional"],"霧":["chinese_traditional"],"擬":["chinese_traditional"],"輯":["chinese_traditional"],"陝":["chinese_traditional"],"償":["chinese_traditional"],"廳":["chinese_traditional"],"駛":["chinese_traditional"],"賦":["chinese_traditional"],"澆":["chinese_traditional"],"鈣":["chinese_traditional"],"虧":["chinese_traditional"],"騙":["chinese_traditional"],"脹":["chinese_traditional"],"諧":["chinese_traditional"],"拋":["chinese_traditional"],"黴":["chinese_traditional"],"崗":["chinese_traditional"],"盜":["chinese_traditional"],"滲":["chinese_traditional"],"臟":["chinese_traditional"],"賴":["chinese_traditional"],"湧":["chinese_traditional"],"閱":["chinese_traditional"],"厲":["chinese_traditional"],"烴":["chinese_traditional"],"緯":["chinese_traditional"],"偽":["chinese_traditional"],"嘆":["chinese_traditional"],"釘":["chinese_traditional"],"莖":["chinese_traditional"],"籠":["chinese_traditional"],"錐":["chinese_traditional"],"恆":["chinese_traditional"],"傑":["chinese_traditional"],"綸":["chinese_traditional"],"敘":["chinese_traditional"],"獄":["chinese_traditional"],"絡":["chinese_traditional"],"驟":["chinese_traditional"],"冊":["chinese_traditional"],"屍":["chinese_traditional"],"紳":["chinese_traditional"],"犧":["chinese_traditional"],"轟":["chinese_traditional"],"晉":["chinese_traditional"],"禦":["chinese_traditional"],"錠":["chinese_traditional"],"錦":["chinese_traditional"],"喪":["chinese_traditional"],"鍛":["chinese_traditional"],"壟":["chinese_traditional"],"撲":["chinese_traditional"],"邁":["chinese_traditional"],"閒":["chinese_traditional"],"憂":["chinese_traditional"],"頑":["chinese_traditional"],"漲":["chinese_traditional"],"闢":["chinese_traditional"],"懲":["chinese_traditional"],"飄":["chinese_traditional"],"飾":["chinese_traditional"],"蕭":["chinese_traditional"],"郵":["chinese_traditional"],"遷":["chinese_traditional"],"煩":["chinese_traditional"],"債":["chinese_traditional"],"帳":["chinese_traditional"],"鈴":["chinese_traditional"],"餅":["chinese_traditional"],"雛":["chinese_traditional"],"賢":["chinese_traditional"],"丟":["chinese_traditional"],"墊":["chinese_traditional"],"擋":["chinese_traditional"],"覽":["chinese_traditional"],"貪":["chinese_traditional"],"繳":["chinese_traditional"],"馮":["chinese_traditional"],"諾":["chinese_traditional"],"誼":["chinese_traditional"],"兇":["chinese_traditional"],"誣":["chinese_traditional"],"騎":["chinese_traditional"],"喬":["chinese_traditional"],"叢":["chinese_traditional"],"盧":["chinese_traditional"],"悶":["chinese_traditional"],"諮":["chinese_traditional"],"駕":["chinese_traditional"],"纜":["chinese_traditional"],"鉺":["chinese_traditional"],"擲":["chinese_traditional"],"頗":["chinese_traditional"],"慘":["chinese_traditional"],"臘":["chinese_traditional"],"窩":["chinese_traditional"],"滌":["chinese_traditional"],"劍":["chinese_traditional"],"潑":["chinese_traditional"],"蔥":["chinese_traditional"],"撈":["chinese_traditional"],"蒼":["chinese_traditional"],"濱":["chinese_traditional"],"倆":["chinese_traditional"],"瘋":["chinese_traditional"],"糞":["chinese_traditional"],"檔":["chinese_traditional"],"駁":["chinese_traditional"],"腸":["chinese_traditional"],"撐":["chinese_traditional"],"曬":["chinese_traditional"],"蓮":["chinese_traditional"],"攤":["chinese_traditional"],"攪":["chinese_traditional"],"醬":["chinese_traditional"],"皺":["chinese_traditional"],"暢":["chinese_traditional"],"疊":["chinese_traditional"],"閣":["chinese_traditional"],"萊":["chinese_traditional"],"轄":["chinese_traditional"],"鉤":["chinese_traditional"],"壩":["chinese_traditional"],"餓":["chinese_traditional"],"禍":["chinese_traditional"],"邏":["chinese_traditional"],"嘗":["chinese_traditional"],"韋":["chinese_traditional"],"abdikace":["czech"],"abeceda":["czech"],"adresa":["czech"],"agrese":["czech"],"akce":["czech"],"aktovka":["czech"],"alej":["czech"],"alkohol":["czech"],"amputace":["czech"],"ananas":["czech"],"andulka":["czech"],"anekdota":["czech"],"anketa":["czech"],"antika":["czech"],"anulovat":["czech"],"archa":["czech"],"arogance":["czech"],"asfalt":["czech","turkish"],"asistent":["czech"],"aspirace":["czech"],"astma":["czech"],"astronom":["czech"],"atlas":["czech"],"atletika":["czech"],"atol":["czech"],"autobus":["czech"],"azyl":["czech"],"babka":["czech"],"bachor":["czech"],"bacil":["czech"],"baculka":["czech"],"badatel":["czech"],"bageta":["czech"],"bagr":["czech"],"bahno":["czech"],"bakterie":["czech"],"balada":["czech"],"baletka":["czech"],"balkon":["czech"],"balonek":["czech"],"balvan":["czech"],"balza":["czech"],"bambus":["czech"],"bankomat":["czech"],"barbar":["czech"],"baret":["czech"],"barman":["czech"],"baroko":["czech"],"barva":["czech"],"baterka":["czech"],"batoh":["czech"],"bavlna":["czech"],"bazalka":["czech"],"bazilika":["czech"],"bazuka":["czech"],"bedna":["czech"],"beran":["czech"],"beseda":["czech"],"bestie":["czech"],"beton":["czech","turkish"],"bezinka":["czech"],"bezmoc":["czech"],"beztak":["czech"],"bicykl":["czech"],"bidlo":["czech"],"biftek":["czech","turkish"],"bikiny":["czech"],"bilance":["czech"],"biograf":["czech"],"biolog":["czech"],"bitva":["czech"],"bizon":["czech"],"blahobyt":["czech"],"blatouch":["czech"],"blecha":["czech"],"bledule":["czech"],"blesk":["czech"],"blikat":["czech"],"blizna":["czech"],"blokovat":["czech"],"bloudit":["czech"],"blud":["czech"],"bobek":["czech"],"bobr":["czech"],"bodlina":["czech"],"bodnout":["czech"],"bohatost":["czech"],"bojkot":["czech"],"bojovat":["czech"],"bokorys":["czech"],"bolest":["czech"],"borec":["czech"],"borovice":["czech"],"bota":["czech"],"boubel":["czech"],"bouchat":["czech"],"bouda":["czech"],"boule":["czech"],"bourat":["czech"],"boxer":["czech"],"bradavka":["czech"],"brambora":["czech"],"branka":["czech"],"bratr":["czech"],"brepta":["czech"],"briketa":["czech"],"brko":["czech"],"brloh":["czech"],"bronz":["czech"],"broskev":["czech"],"brunetka":["czech"],"brusinka":["czech"],"brzda":["czech"],"brzy":["czech"],"bublina":["czech"],"bubnovat":["czech"],"buchta":["czech"],"buditel":["czech"],"budka":["czech"],"budova":["czech"],"bufet":["czech"],"bujarost":["czech"],"bukvice":["czech"],"buldok":["czech"],"bulva":["czech"],"bunda":["czech"],"bunkr":["czech"],"burza":["czech"],"butik":["czech","turkish"],"buvol":["czech"],"buzola":["czech"],"bydlet":["czech"],"bylina":["czech"],"bytovka":["czech"],"bzukot":["czech"],"capart":["czech"],"carevna":["czech"],"cedr":["czech"],"cedule":["czech"],"cejch":["czech"],"cejn":["czech"],"cela":["czech"],"celer":["czech"],"celkem":["czech"],"celnice":["czech"],"cenina":["czech"],"cennost":["czech"],"cenovka":["czech"],"centrum":["czech"],"cenzor":["czech"],"cestopis":["czech"],"cetka":["czech"],"chalupa":["czech"],"chapadlo":["czech"],"charita":["czech"],"chata":["czech"],"chechtat":["czech"],"chemie":["czech"],"chichot":["czech"],"chirurg":["czech"],"chlad":["czech"],"chleba":["czech"],"chlubit":["czech"],"chmel":["czech"],"chmura":["czech"],"chobot":["czech"],"chochol":["czech"],"chodba":["czech"],"cholera":["czech"],"chomout":["czech"],"chopit":["czech"],"choroba":["czech"],"chov":["czech"],"chrapot":["czech"],"chrlit":["czech"],"chrt":["czech"],"chrup":["czech"],"chtivost":["czech"],"chudina":["czech"],"chutnat":["czech"],"chvat":["czech"],"chvilka":["czech"],"chvost":["czech"],"chyba":["czech"],"chystat":["czech"],"chytit":["czech"],"cibule":["czech"],"cigareta":["czech"],"cihelna":["czech"],"cihla":["czech"],"cinkot":["czech"],"cirkus":["czech"],"cisterna":["czech"],"citace":["czech"],"citrus":["czech"],"cizinec":["czech"],"cizost":["czech"],"clona":["czech"],"cokoliv":["czech"],"couvat":["czech"],"ctitel":["czech"],"ctnost":["czech"],"cudnost":["czech"],"cuketa":["czech"],"cukr":["czech"],"cupot":["czech"],"cvaknout":["czech"],"cval":["czech"],"cvik":["czech"],"cvrkot":["czech"],"cyklista":["czech"],"daleko":["czech"],"dareba":["czech"],"datel":["czech"],"datum":["czech"],"dcera":["czech"],"debata":["czech"],"dechovka":["czech"],"decibel":["czech"],"deficit":["czech"],"deflace":["czech"],"dekl":["czech"],"dekret":["czech"],"demokrat":["czech"],"deprese":["czech"],"derby":["czech"],"deska":["czech"],"detektiv":["czech"],"dikobraz":["czech"],"diktovat":["czech"],"dioda":["czech"],"diplom":["czech"],"disk":["czech","turkish"],"displej":["czech"],"divadlo":["czech"],"divoch":["czech"],"dlaha":["czech"],"dlouho":["czech"],"dluhopis":["czech"],"dnes":["czech"],"dobro":["czech"],"dobytek":["czech"],"docent":["czech"],"dochutit":["czech"],"dodnes":["czech"],"dohled":["czech"],"dohoda":["czech"],"dohra":["czech"],"dojem":["czech"],"dojnice":["czech"],"doklad":["czech"],"dokola":["czech"],"doktor":["czech","turkish"],"dokument":["czech"],"dolar":["czech"],"doleva":["czech"],"dolina":["czech"],"doma":["czech"],"dominant":["czech"],"domluvit":["czech"],"domov":["czech"],"donutit":["czech"],"dopad":["czech"],"dopis":["czech"],"doplnit":["czech"],"doposud":["czech"],"doprovod":["czech"],"dopustit":["czech"],"dorazit":["czech"],"dorost":["czech"],"dort":["czech"],"dosah":["czech"],"doslov":["czech"],"dostatek":["czech"],"dosud":["czech"],"dosyta":["czech"],"dotaz":["czech"],"dotek":["czech"],"dotknout":["czech"],"doufat":["czech"],"doutnat":["czech"],"dovozce":["czech"],"dozadu":["czech"],"doznat":["czech"],"dozorce":["czech"],"drahota":["czech"],"drak":["czech"],"dramatik":["czech"],"dravec":["czech"],"draze":["czech"],"drdol":["czech"],"drobnost":["czech"],"drogerie":["czech"],"drozd":["czech"],"drsnost":["czech"],"drtit":["czech"],"drzost":["czech"],"duben":["czech"],"duchovno":["czech"],"dudek":["czech"],"duha":["czech"],"duhovka":["czech"],"dusit":["czech"],"dusno":["czech"],"dutost":["czech"],"dvojice":["czech"],"dvorec":["czech"],"dynamit":["czech"],"ekolog":["czech"],"ekonomie":["czech"],"elektron":["czech"],"elipsa":["czech"],"email":["czech"],"emise":["czech"],"emoce":["czech"],"empatie":["czech"],"epizoda":["czech"],"epocha":["czech"],"epopej":["czech"],"epos":["czech"],"esej":["czech"],"esence":["czech"],"eskorta":["czech"],"eskymo":["czech"],"etiketa":["czech"],"euforie":["czech"],"evoluce":["czech"],"exekuce":["czech"],"exkurze":["czech"],"expedice":["czech"],"exploze":["czech"],"export":["czech"],"extrakt":["czech"],"facka":["czech"],"fajfka":["czech"],"fakulta":["czech"],"fanatik":["czech","turkish"],"fantazie":["czech"],"farmacie":["czech"],"favorit":["czech"],"fazole":["czech"],"federace":["czech"],"fejeton":["czech"],"fenka":["czech"],"fialka":["czech"],"figurant":["czech"],"filozof":["czech"],"filtr":["czech"],"finance":["czech"],"finta":["czech"],"fixace":["czech"],"fjord":["czech"],"flanel":["czech"],"flirt":["czech"],"flotila":["czech"],"fond":["czech"],"fosfor":["czech"],"fotbal":["czech"],"fotka":["czech"],"foton":["czech"],"frakce":["czech"],"freska":["czech"],"fronta":["czech"],"fukar":["czech"],"funkce":["czech"],"fyzika":["czech"],"galeje":["czech"],"garant":["czech"],"genetika":["czech"],"geolog":["czech"],"gilotina":["czech"],"glazura":["czech"],"glejt":["czech"],"golem":["czech"],"golfista":["czech"],"gotika":["czech"],"graf":["czech"],"gramofon":["czech"],"granule":["czech"],"grep":["czech"],"gril":["czech"],"grog":["czech"],"groteska":["czech"],"guma":["czech"],"hadice":["czech"],"hadr":["czech"],"hala":["czech"],"halenka":["czech"],"hanba":["czech"],"hanopis":["czech"],"harfa":["czech"],"harpuna":["czech"],"havran":["czech"],"hebkost":["czech"],"hejkal":["czech"],"hejno":["czech"],"hejtman":["czech"],"hektar":["czech","turkish"],"helma":["czech"],"hematom":["czech"],"herec":["czech"],"herna":["czech"],"heslo":["czech"],"hezky":["czech"],"historik":["czech"],"hladovka":["czech"],"hlasivky":["czech"],"hlava":["czech"],"hledat":["czech"],"hlen":["czech"],"hlodavec":["czech"],"hloh":["czech"],"hloupost":["czech"],"hltat":["czech"],"hlubina":["czech"],"hluchota":["czech"],"hmat":["czech"],"hmota":["czech"],"hmyz":["czech"],"hnis":["czech"],"hnojivo":["czech"],"hnout":["czech"],"hoblina":["czech"],"hoboj":["czech"],"hoch":["czech"],"hodiny":["czech"],"hodlat":["czech"],"hodnota":["czech"],"hodovat":["czech"],"hojnost":["czech"],"hokej":["czech"],"holinka":["czech"],"holka":["czech"],"holub":["czech"],"homole":["czech"],"honitba":["czech"],"honorace":["czech"],"horal":["czech"],"horda":["czech"],"horizont":["czech"],"horko":["czech"],"horlivec":["czech"],"hormon":["czech","turkish"],"hornina":["czech"],"horoskop":["czech"],"horstvo":["czech"],"hospoda":["czech"],"hostina":["czech"],"hotovost":["czech"],"houba":["czech"],"houf":["czech"],"houpat":["czech"],"houska":["czech"],"hovor":["czech"],"hradba":["czech"],"hranice":["czech"],"hravost":["czech"],"hrazda":["czech"],"hrbolek":["czech"],"hrdina":["czech"],"hrdlo":["czech"],"hrdost":["czech"],"hrnek":["czech"],"hrobka":["czech"],"hromada":["czech"],"hrot":["czech"],"hrouda":["czech"],"hrozen":["czech"],"hrstka":["czech"],"hrubost":["czech"],"hryzat":["czech"],"hubenost":["czech"],"hubnout":["czech"],"hudba":["czech"],"hukot":["czech"],"humr":["czech"],"husita":["czech"],"hustota":["czech"],"hvozd":["czech"],"hybnost":["czech"],"hydrant":["czech"],"hygiena":["czech"],"hymna":["czech"],"hysterik":["czech"],"idylka":["czech"],"ihned":["czech"],"ikona":["czech"],"iluze":["czech"],"imunita":["czech"],"infekce":["czech"],"inflace":["czech"],"inkaso":["czech"],"inovace":["czech"],"inspekce":["czech"],"internet":["czech"],"invalida":["czech"],"investor":["czech"],"inzerce":["czech"],"ironie":["czech"],"jablko":["czech"],"jachta":["czech"],"jahoda":["czech"],"jakmile":["czech"],"jakost":["czech"],"jalovec":["czech"],"jantar":["czech"],"jarmark":["czech"],"jaro":["czech"],"jasan":["czech"],"jasno":["czech"],"jatka":["czech"],"javor":["czech"],"jazyk":["czech"],"jedinec":["czech"],"jedle":["czech"],"jednatel":["czech"],"jehlan":["czech"],"jekot":["czech"],"jelen":["czech"],"jelito":["czech"],"jemnost":["czech"],"jenom":["czech"],"jepice":["czech"],"jeseter":["czech"],"jevit":["czech"],"jezdec":["czech"],"jezero":["czech"],"jinak":["czech"],"jindy":["czech"],"jinoch":["czech"],"jiskra":["czech"],"jistota":["czech"],"jitrnice":["czech"],"jizva":["czech"],"jmenovat":["czech"],"jogurt":["czech"],"jurta":["czech"],"kabaret":["czech"],"kabel":["czech"],"kabinet":["czech"],"kachna":["czech"],"kadet":["czech"],"kadidlo":["czech"],"kahan":["czech"],"kajak":["czech"],"kajuta":["czech"],"kakao":["czech"],"kaktus":["czech"],"kalamita":["czech"],"kalhoty":["czech"],"kalibr":["czech"],"kalnost":["czech"],"kamera":["czech"],"kamkoliv":["czech"],"kamna":["czech"],"kanibal":["czech"],"kanoe":["czech"],"kantor":["czech"],"kapalina":["czech"],"kapela":["czech"],"kapitola":["czech"],"kapka":["czech"],"kaple":["czech"],"kapota":["czech"],"kapr":["czech"],"kapusta":["czech"],"kapybara":["czech"],"karamel":["czech"],"karotka":["czech"],"karton":["czech"],"kasa":["czech"],"katalog":["czech"],"katedra":["czech"],"kauce":["czech"],"kauza":["czech"],"kavalec":["czech"],"kazajka":["czech"],"kazeta":["czech"],"kazivost":["czech"],"kdekoliv":["czech"],"kdesi":["czech"],"kedluben":["czech"],"kemp":["czech"],"keramika":["czech"],"kino":["czech"],"klacek":["czech"],"kladivo":["czech"],"klam":["czech"],"klapot":["czech"],"klasika":["czech"],"klaun":["czech"],"klec":["czech"],"klenba":["czech"],"klepat":["czech"],"klesnout":["czech"],"klid":["czech"],"klima":["czech"],"klisna":["czech"],"klobouk":["czech"],"klokan":["czech"],"klopa":["czech"],"kloub":["czech"],"klubovna":["czech"],"klusat":["czech"],"kluzkost":["czech"],"kmen":["czech"],"kmitat":["czech"],"kmotr":["czech"],"kniha":["czech"],"knot":["czech"],"koalice":["czech"],"koberec":["czech"],"kobka":["czech"],"kobliha":["czech"],"kobyla":["czech"],"kocour":["czech"],"kohout":["czech"],"kojenec":["czech"],"kokos":["czech"],"koktejl":["czech"],"kolaps":["czech"],"koleda":["czech"],"kolize":["czech"],"kolo":["czech"],"komando":["czech"],"kometa":["czech"],"komik":["czech"],"komnata":["czech"],"komora":["czech"],"kompas":["czech"],"komunita":["czech"],"konat":["czech"],"koncept":["czech"],"kondice":["czech"],"konec":["czech"],"konfese":["czech"],"kongres":["czech"],"konina":["czech"],"konkurs":["czech"],"kontakt":["czech"],"konzerva":["czech"],"kopanec":["czech"],"kopie":["czech"],"kopnout":["czech"],"koprovka":["czech"],"korbel":["czech"],"korektor":["czech"],"kormidlo":["czech"],"koroptev":["czech"],"korpus":["czech"],"koruna":["czech"],"koryto":["czech"],"korzet":["czech"],"kosatec":["czech"],"kostka":["czech"],"kotel":["czech"],"kotleta":["czech"],"kotoul":["czech"],"koukat":["czech"],"koupelna":["czech"],"kousek":["czech"],"kouzlo":["czech"],"kovboj":["czech"],"koza":["czech"],"kozoroh":["czech"],"krabice":["czech"],"krach":["czech"],"krajina":["czech"],"kralovat":["czech"],"krasopis":["czech"],"kravata":["czech"],"kredit":["czech"],"krejcar":["czech"],"kresba":["czech"],"kreveta":["czech"],"kriket":["czech"],"kritik":["czech"],"krize":["czech"],"krkavec":["czech"],"krmelec":["czech"],"krmivo":["czech"],"krocan":["czech"],"krok":["czech"],"kronika":["czech"],"kropit":["czech"],"kroupa":["czech"],"krovka":["czech"],"krtek":["czech"],"kruhadlo":["czech"],"krupice":["czech"],"krutost":["czech"],"krvinka":["czech"],"krychle":["czech"],"krypta":["czech"],"krystal":["czech"],"kryt":["czech"],"kudlanka":["czech"],"kufr":["czech"],"kujnost":["czech"],"kukla":["czech"],"kulajda":["czech"],"kulich":["czech"],"kulka":["czech"],"kulomet":["czech"],"kultura":["czech"],"kuna":["czech"],"kupodivu":["czech"],"kurt":["czech"],"kurzor":["czech"],"kutil":["czech"],"kvalita":["czech"],"kvasinka":["czech"],"kvestor":["czech"],"kynolog":["czech"],"kyselina":["czech"],"kytara":["czech"],"kytice":["czech"],"kytka":["czech"],"kytovec":["czech"],"kyvadlo":["czech"],"labrador":["czech"],"lachtan":["czech"],"ladnost":["czech"],"laik":["czech"],"lakomec":["czech"],"lamela":["czech"],"lampa":["czech"],"lanovka":["czech"],"lasice":["czech"],"laso":["czech"],"lastura":["czech"],"latinka":["czech"],"lavina":["czech"],"lebka":["czech"],"leckdy":["czech"],"leden":["czech"],"lednice":["czech"],"ledovka":["czech"],"ledvina":["czech"],"legenda":["czech"],"legie":["czech"],"legrace":["czech"],"lehce":["czech"],"lehkost":["czech"],"lehnout":["czech"],"lektvar":["czech"],"lenochod":["czech"],"lentilka":["czech"],"lepenka":["czech"],"lepidlo":["czech"],"letadlo":["czech"],"letec":["czech"],"letmo":["czech"],"letokruh":["czech"],"levhart":["czech"],"levitace":["czech"],"levobok":["czech"],"libra":["czech"],"lichotka":["czech"],"lidojed":["czech"],"lidskost":["czech"],"lihovina":["czech"],"lijavec":["czech"],"lilek":["czech"],"limetka":["czech"],"linie":["czech"],"linka":["czech"],"linoleum":["czech"],"listopad":["czech"],"litina":["czech"],"litovat":["czech"],"lobista":["czech"],"lodivod":["czech"],"logika":["czech"],"logoped":["czech"],"lokalita":["czech"],"loket":["czech"],"lomcovat":["czech"],"lopata":["czech"],"lopuch":["czech"],"lord":["czech"],"losos":["czech"],"lotr":["czech"],"loudal":["czech"],"louh":["czech"],"louka":["czech"],"louskat":["czech"],"lovec":["czech"],"lstivost":["czech"],"lucerna":["czech"],"lucifer":["czech"],"lump":["czech"],"lusk":["czech"],"lustrace":["czech"],"lvice":["czech"],"lyra":["czech"],"lyrika":["czech"],"lysina":["czech"],"madam":["czech"],"madlo":["czech"],"magistr":["czech"],"mahagon":["czech"],"majetek":["czech"],"majitel":["czech"],"majorita":["czech"],"makak":["czech"],"makovice":["czech"],"makrela":["czech"],"malba":["czech"],"malina":["czech"],"malovat":["czech"],"malvice":["czech"],"maminka":["czech"],"mandle":["czech"],"manko":["czech"],"marnost":["czech"],"masakr":["czech"],"maskot":["czech"],"masopust":["czech"],"matice":["czech"],"matrika":["czech"],"maturita":["czech"],"mazanec":["czech"],"mazivo":["czech"],"mazlit":["czech"],"mazurka":["czech"],"mdloba":["czech"],"mechanik":["czech"],"meditace":["czech"],"medovina":["czech"],"melasa":["czech"],"meloun":["czech"],"mentolka":["czech"],"metla":["czech"],"metoda":["czech"],"metr":["czech"],"mezera":["czech"],"migrace":["czech"],"mihnout":["czech"],"mihule":["czech"],"mikina":["czech"],"mikrofon":["czech","turkish"],"milenec":["czech"],"milimetr":["czech"],"milost":["czech"],"mimika":["czech"],"mincovna":["czech"],"minibar":["czech"],"minomet":["czech"],"minulost":["czech"],"miska":["czech"],"mistr":["czech"],"mixovat":["czech"],"mladost":["czech"],"mlha":["czech"],"mlhovina":["czech"],"mlok":["czech"],"mlsat":["czech"],"mluvit":["czech"],"mnich":["czech"],"mnohem":["czech"],"mobil":["czech"],"mocnost":["czech"],"modelka":["czech"],"modlitba":["czech"],"mohyla":["czech"],"mokro":["czech"],"molekula":["czech"],"momentka":["czech"],"monarcha":["czech"],"monokl":["czech"],"monstrum":["czech"],"montovat":["czech"],"monzun":["czech"],"mosaz":["czech"],"moskyt":["czech"],"most":["czech"],"motivace":["czech"],"motorka":["czech"],"motyka":["czech"],"moucha":["czech"],"moudrost":["czech"],"mozaika":["czech"],"mozek":["czech"],"mozol":["czech"],"mramor":["czech"],"mravenec":["czech"],"mrkev":["czech"],"mrtvola":["czech"],"mrzet":["czech"],"mrzutost":["czech"],"mstitel":["czech"],"mudrc":["czech"],"muflon":["czech"],"mulat":["czech"],"mumie":["czech"],"munice":["czech"],"muset":["czech"],"mutace":["czech"],"muzeum":["czech"],"muzikant":["czech"],"myslivec":["czech"],"mzda":["czech"],"nabourat":["czech"],"nachytat":["czech"],"nadace":["czech"],"nadbytek":["czech"],"nadhoz":["czech"],"nadobro":["czech"],"nadpis":["czech"],"nahlas":["czech"],"nahnat":["czech"],"nahodile":["czech"],"nahradit":["czech"],"naivita":["czech"],"najednou":["czech"],"najisto":["czech"],"najmout":["czech"],"naklonit":["czech"],"nakonec":["czech"],"nakrmit":["czech"],"nalevo":["czech"],"namazat":["czech"],"namluvit":["czech"],"nanometr":["czech"],"naoko":["czech"],"naopak":["czech"],"naostro":["czech"],"napadat":["czech"],"napevno":["czech"],"naplnit":["czech"],"napnout":["czech"],"naposled":["czech"],"naprosto":["czech"],"narodit":["czech"],"naruby":["czech"],"narychlo":["czech"],"nasadit":["czech"],"nasekat":["czech"],"naslepo":["czech"],"nastat":["czech"],"natolik":["czech"],"navenek":["czech"],"navrch":["czech"],"navzdory":["czech"],"nazvat":["czech"],"nebe":["czech"],"nechat":["czech"],"necky":["czech"],"nedaleko":["czech"],"nedbat":["czech"],"neduh":["czech"],"negace":["czech"],"nehet":["czech"],"nehoda":["czech"],"nejen":["czech"],"nejprve":["czech"],"neklid":["czech"],"nelibost":["czech"],"nemilost":["czech"],"nemoc":["czech"],"neochota":["czech"],"neonka":["czech"],"nepokoj":["czech"],"nerost":["czech"],"nerv":["czech"],"nesmysl":["czech"],"nesoulad":["czech"],"netvor":["czech"],"neuron":["czech"],"nevina":["czech"],"nezvykle":["czech"],"nicota":["czech"],"nijak":["czech"],"nikam":["czech"],"nikdy":["czech"],"nikl":["czech"],"nikterak":["czech"],"nitro":["czech"],"nocleh":["czech"],"nohavice":["czech"],"nominace":["czech"],"nora":["czech"],"norek":["czech"],"nositel":["czech"],"nosnost":["czech"],"nouze":["czech"],"noviny":["czech"],"novota":["czech"],"nozdra":["czech"],"nuda":["czech"],"nudle":["czech"],"nuget":["czech"],"nutit":["czech"],"nutnost":["czech"],"nutrie":["czech"],"nymfa":["czech"],"obal":["czech"],"obarvit":["czech"],"obava":["czech"],"obdiv":["czech"],"obec":["czech"],"obehnat":["czech"],"obejmout":["czech"],"obezita":["czech"],"obhajoba":["czech"],"obilnice":["czech"],"objasnit":["czech"],"objekt":["czech"],"obklopit":["czech"],"oblast":["czech"],"oblek":["czech"],"obliba":["czech"],"obloha":["czech"],"obluda":["czech"],"obnos":["czech"],"obohatit":["czech"],"obojek":["czech"],"obout":["czech"],"obrazec":["czech"],"obrna":["czech"],"obruba":["czech"],"obrys":["czech"],"obsah":["czech"],"obsluha":["czech"],"obstarat":["czech"],"obuv":["czech"],"obvaz":["czech"],"obvinit":["czech"],"obvod":["czech"],"obvykle":["czech"],"obyvatel":["czech"],"obzor":["czech"],"ocas":["czech"],"ocel":["czech"],"ocenit":["czech"],"ochladit":["czech"],"ochota":["czech"],"ochrana":["czech"],"ocitnout":["czech"],"odboj":["czech"],"odbyt":["czech"],"odchod":["czech"],"odcizit":["czech"],"odebrat":["czech"],"odeslat":["czech"],"odevzdat":["czech"],"odezva":["czech"],"odhadce":["czech"],"odhodit":["czech"],"odjet":["czech"],"odjinud":["czech"],"odkaz":["czech"],"odkoupit":["czech"],"odliv":["czech"],"odluka":["czech"],"odmlka":["czech"],"odolnost":["czech"],"odpad":["czech"],"odpis":["czech"],"odplout":["czech"],"odpor":["czech"],"odpustit":["czech"],"odpykat":["czech"],"odrazka":["czech"],"odsoudit":["czech"],"odstup":["czech"],"odsun":["czech"],"odtok":["czech"],"odtud":["czech"],"odvaha":["czech"],"odveta":["czech"],"odvolat":["czech"],"odvracet":["czech"],"odznak":["czech"],"ofina":["czech"],"ofsajd":["czech"],"ohlas":["czech"],"ohnisko":["czech"],"ohrada":["czech"],"ohrozit":["czech"],"ohryzek":["czech"],"okap":["czech"],"okenice":["czech"],"oklika":["czech"],"okno":["czech"],"okouzlit":["czech"],"okovy":["czech"],"okrasa":["czech"],"okres":["czech"],"okrsek":["czech"],"okruh":["czech"],"okupant":["czech"],"okurka":["czech"],"okusit":["czech"],"olejnina":["czech"],"olizovat":["czech"],"omak":["czech"],"omeleta":["czech"],"omezit":["czech"],"omladina":["czech"],"omlouvat":["czech"],"omluva":["czech"],"omyl":["czech"],"onehdy":["czech"],"opakovat":["czech"],"opasek":["czech"],"operace":["czech"],"opice":["czech"],"opilost":["czech"],"opisovat":["czech"],"opora":["czech"],"opozice":["czech"],"opravdu":["czech"],"oproti":["czech"],"orbital":["czech"],"orchestr":["czech"],"orgie":["czech"],"orlice":["czech"],"orloj":["czech"],"ortel":["czech"],"osada":["czech"],"oschnout":["czech"],"osika":["czech"],"osivo":["czech"],"oslava":["czech"],"oslepit":["czech"],"oslnit":["czech"],"oslovit":["czech"],"osnova":["czech"],"osoba":["czech"],"osolit":["czech"],"ospalec":["czech"],"osten":["czech"],"ostraha":["czech"],"ostuda":["czech"],"ostych":["czech"],"osvojit":["czech"],"oteplit":["czech"],"otisk":["czech"],"otop":["czech"],"otrhat":["czech"],"otrlost":["czech"],"otrok":["czech"],"otruby":["czech"],"otvor":["czech"],"ovanout":["czech"],"ovar":["czech"],"oves":["czech"],"ovlivnit":["czech"],"ovoce":["czech"],"oxid":["czech"],"ozdoba":["czech"],"pachatel":["czech"],"pacient":["czech"],"padouch":["czech"],"pahorek":["czech"],"pakt":["czech"],"palanda":["czech"],"palec":["czech"],"palivo":["czech"],"paluba":["czech"],"pamflet":["czech"],"pamlsek":["czech"],"panenka":["czech"],"panika":["czech"],"panna":["czech"],"panovat":["czech"],"panstvo":["czech"],"pantofle":["czech"],"paprika":["czech"],"parketa":["czech"],"parodie":["czech"],"parta":["czech"],"paruka":["czech"],"paryba":["czech"],"paseka":["czech"],"pasivita":["czech"],"pastelka":["czech"],"patent":["czech"],"patrona":["czech"],"pavouk":["czech"],"pazneht":["czech"],"pazourek":["czech"],"pecka":["czech"],"pedagog":["czech"],"pejsek":["czech"],"peklo":["czech"],"peloton":["czech"],"penalta":["czech"],"pendrek":["czech"],"penze":["czech"],"periskop":["czech"],"pero":["czech"],"pestrost":["czech"],"petarda":["czech"],"petice":["czech"],"petrolej":["czech"],"pevnina":["czech"],"pexeso":["czech"],"pianista":["czech"],"piha":["czech"],"pijavice":["czech"],"pikle":["czech"],"piknik":["czech","turkish"],"pilina":["czech"],"pilnost":["czech"],"pilulka":["czech"],"pinzeta":["czech"],"pipeta":["czech"],"pisatel":["czech"],"pistole":["czech"],"pitevna":["czech"],"pivnice":["czech"],"pivovar":["czech"],"placenta":["czech"],"plakat":["czech"],"plamen":["czech"],"planeta":["czech"],"plastika":["czech"],"platit":["czech"],"plavidlo":["czech"],"plaz":["czech"],"plech":["czech"],"plemeno":["czech"],"plenta":["czech"],"ples":["czech"],"pletivo":["czech"],"plevel":["czech"],"plivat":["czech"],"plnit":["czech"],"plno":["czech"],"plocha":["czech"],"plodina":["czech"],"plomba":["czech"],"plout":["czech"],"pluk":["czech"],"plyn":["czech"],"pobavit":["czech"],"pobyt":["czech"],"pochod":["czech"],"pocit":["czech"],"poctivec":["czech"],"podat":["czech"],"podcenit":["czech"],"podepsat":["czech"],"podhled":["czech"],"podivit":["czech"],"podklad":["czech"],"podmanit":["czech"],"podnik":["czech"],"podoba":["czech"],"podpora":["czech"],"podraz":["czech"],"podstata":["czech"],"podvod":["czech"],"podzim":["czech"],"poezie":["czech"],"pohanka":["czech"],"pohnutka":["czech"],"pohovor":["czech"],"pohroma":["czech"],"pohyb":["czech"],"pointa":["czech"],"pojistka":["czech"],"pojmout":["czech"],"pokazit":["czech"],"pokles":["czech"],"pokoj":["czech"],"pokrok":["czech"],"pokuta":["czech"],"pokyn":["czech"],"poledne":["czech"],"polibek":["czech"],"polknout":["czech"],"poloha":["czech"],"polynom":["czech"],"pomalu":["czech"],"pominout":["czech"],"pomlka":["czech"],"pomoc":["czech"],"pomsta":["czech"],"pomyslet":["czech"],"ponechat":["czech"],"ponorka":["czech"],"ponurost":["czech"],"popadat":["czech"],"popel":["czech"],"popisek":["czech"],"poplach":["czech"],"poprosit":["czech"],"popsat":["czech"],"popud":["czech"],"poradce":["czech"],"porce":["czech"],"porod":["czech"],"porucha":["czech"],"poryv":["czech"],"posadit":["czech"],"posed":["czech"],"posila":["czech"],"poskok":["czech"],"poslanec":["czech"],"posoudit":["czech"],"pospolu":["czech"],"postava":["czech"],"posudek":["czech"],"posyp":["czech"],"potah":["czech"],"potkan":["czech"],"potlesk":["czech"],"potomek":["czech"],"potrava":["czech"],"potupa":["czech"],"potvora":["czech"],"poukaz":["czech"],"pouto":["czech"],"pouzdro":["czech"],"povaha":["czech"],"povidla":["czech"],"povlak":["czech"],"povoz":["czech"],"povrch":["czech"],"povstat":["czech"],"povyk":["czech"],"povzdech":["czech"],"pozdrav":["czech"],"pozemek":["czech"],"poznatek":["czech"],"pozor":["czech"],"pozvat":["czech"],"pracovat":["czech"],"prahory":["czech"],"praktika":["czech"],"prales":["czech"],"praotec":["czech"],"praporek":["czech"],"prase":["czech"],"pravda":["czech"],"princip":["czech"],"prkno":["czech"],"probudit":["czech"],"procento":["czech"],"prodej":["czech"],"profese":["czech"],"prohra":["czech"],"projekt":["czech"],"prolomit":["czech"],"promile":["czech"],"pronikat":["czech"],"propad":["czech"],"prorok":["czech"],"prosba":["czech"],"proton":["czech"],"proutek":["czech"],"provaz":["czech"],"prskavka":["czech"],"prsten":["czech"],"prudkost":["czech"],"prut":["czech"],"prvek":["czech"],"prvohory":["czech"],"psanec":["czech"],"psovod":["czech"],"pstruh":["czech"],"ptactvo":["czech"],"puberta":["czech"],"puch":["czech"],"pudl":["czech"],"pukavec":["czech"],"puklina":["czech"],"pukrle":["czech"],"pult":["czech"],"pumpa":["czech"],"punc":["czech"],"pupen":["czech"],"pusa":["czech"],"pusinka":["czech"],"pustina":["czech"],"putovat":["czech"],"putyka":["czech"],"pyramida":["czech"],"pysk":["czech"],"pytel":["czech"],"racek":["czech"],"rachot":["czech"],"radiace":["czech"],"radnice":["czech"],"radon":["czech"],"raft":["czech"],"ragby":["czech"],"raketa":["czech"],"rakovina":["czech"],"rameno":["czech"],"rampouch":["czech"],"rande":["czech"],"rarach":["czech"],"rarita":["czech"],"rasovna":["czech"],"rastr":["czech"],"ratolest":["czech"],"razance":["czech"],"razidlo":["czech"],"reagovat":["czech"],"reakce":["czech"],"recept":["czech"],"redaktor":["czech"],"referent":["czech"],"reflex":["czech"],"rejnok":["czech"],"reklama":["czech"],"rekord":["czech"],"rekrut":["czech"],"rektor":["czech"],"reputace":["czech"],"revize":["czech","turkish"],"revma":["czech"],"revolver":["czech"],"rezerva":["czech"],"riskovat":["czech"],"riziko":["czech"],"robotika":["czech"],"rodokmen":["czech"],"rohovka":["czech"],"rokle":["czech"],"rokoko":["czech"],"romaneto":["czech"],"ropovod":["czech"],"ropucha":["czech"],"rorejs":["czech"],"rosol":["czech"],"rostlina":["czech"],"rotmistr":["czech"],"rotoped":["czech"],"rotunda":["czech"],"roubenka":["czech"],"roucho":["czech"],"roup":["czech"],"roura":["czech"],"rovina":["czech"],"rovnice":["czech"],"rozbor":["czech"],"rozchod":["czech"],"rozdat":["czech"],"rozeznat":["czech"],"rozhodce":["czech"],"rozinka":["czech"],"rozjezd":["czech"],"rozkaz":["czech"],"rozloha":["czech"],"rozmar":["czech"],"rozpad":["czech"],"rozruch":["czech"],"rozsah":["czech"],"roztok":["czech"],"rozum":["czech"],"rozvod":["czech"],"rubrika":["czech"],"ruchadlo":["czech"],"rukavice":["czech"],"rukopis":["czech"],"ryba":["czech"],"rybolov":["czech"],"rychlost":["czech"],"rydlo":["czech"],"rypadlo":["czech"],"rytina":["czech"],"ryzost":["czech"],"sadista":["czech"],"sahat":["czech"],"sako":["czech"],"samec":["czech"],"samizdat":["czech"],"samota":["czech"],"sanitka":["czech"],"sardinka":["czech"],"sasanka":["czech"],"satelit":["czech"],"sazba":["czech"],"sazenice":["czech"],"sbor":["czech"],"schovat":["czech"],"sebranka":["czech"],"secese":["czech"],"sedadlo":["czech"],"sediment":["czech"],"sedlo":["czech"],"sehnat":["czech"],"sejmout":["czech"],"sekera":["czech"],"sekta":["czech"],"sekunda":["czech"],"sekvoje":["czech"],"semeno":["czech"],"seno":["czech"],"servis":["czech","turkish"],"sesadit":["czech"],"seshora":["czech"],"seskok":["czech"],"seslat":["czech"],"sestra":["czech"],"sesuv":["czech"],"sesypat":["czech"],"setba":["czech"],"setina":["czech"],"setkat":["czech"],"setnout":["czech"],"setrvat":["czech"],"sever":["czech"],"seznam":["czech"],"shoda":["czech"],"shrnout":["czech"],"sifon":["czech"],"silnice":["czech"],"sirka":["czech"],"sirotek":["czech"],"sirup":["czech"],"situace":["czech"],"skafandr":["czech"],"skalisko":["czech"],"skanzen":["czech"],"skaut":["czech"],"skeptik":["czech"],"skica":["czech"],"skladba":["czech"],"sklenice":["czech"],"sklo":["czech"],"skluz":["czech"],"skoba":["czech"],"skokan":["czech"],"skoro":["czech"],"skripta":["czech"],"skrz":["czech"],"skupina":["czech"],"skvost":["czech"],"skvrna":["czech"],"slabika":["czech"],"sladidlo":["czech"],"slanina":["czech"],"slast":["czech"],"slavnost":["czech"],"sledovat":["czech"],"slepec":["czech"],"sleva":["czech"],"slezina":["czech"],"slib":["czech"],"slina":["czech"],"sliznice":["czech"],"slon":["czech"],"sloupek":["czech"],"slovo":["czech"],"sluch":["czech"],"sluha":["czech"],"slunce":["czech"],"slupka":["czech"],"slza":["czech"],"smaragd":["czech"],"smetana":["czech"],"smilstvo":["czech"],"smlouva":["czech"],"smog":["czech"],"smrad":["czech"],"smrk":["czech"],"smrtka":["czech"],"smutek":["czech"],"smysl":["czech"],"snad":["czech"],"snaha":["czech"],"snob":["czech"],"sobota":["czech"],"socha":["czech"],"sodovka":["czech"],"sokol":["czech"],"sopka":["czech"],"sotva":["czech"],"souboj":["czech"],"soucit":["czech"],"soudce":["czech"],"souhlas":["czech"],"soulad":["czech"],"soumrak":["czech"],"souprava":["czech"],"soused":["czech"],"soutok":["czech"],"souviset":["czech"],"spalovna":["czech"],"spasitel":["czech"],"spis":["czech"],"splav":["czech"],"spodek":["czech"],"spojenec":["czech"],"spolu":["czech"],"sponzor":["czech"],"spornost":["czech"],"spousta":["czech"],"sprcha":["czech"],"spustit":["czech"],"sranda":["czech"],"sraz":["czech"],"srdce":["czech"],"srna":["czech"],"srnec":["czech"],"srovnat":["czech"],"srpen":["czech"],"srst":["czech"],"srub":["czech"],"stanice":["czech"],"starosta":["czech"],"statika":["czech"],"stavba":["czech"],"stehno":["czech"],"stezka":["czech"],"stodola":["czech"],"stolek":["czech"],"stopa":["czech"],"storno":["czech"],"stoupat":["czech"],"strach":["czech"],"stres":["czech"],"strhnout":["czech"],"strom":["czech"],"struna":["czech"],"studna":["czech"],"stupnice":["czech"],"stvol":["czech"],"styk":["czech"],"subjekt":["czech"],"subtropy":["czech"],"suchar":["czech"],"sudost":["czech"],"sukno":["czech"],"sundat":["czech"],"sunout":["czech"],"surikata":["czech"],"surovina":["czech"],"svah":["czech"],"svalstvo":["czech"],"svetr":["czech"],"svatba":["czech"],"svazek":["czech"],"svisle":["czech"],"svitek":["czech"],"svoboda":["czech"],"svodidlo":["czech"],"svorka":["czech"],"svrab":["czech"],"sykavka":["czech"],"sykot":["czech"],"synek":["czech"],"synovec":["czech"],"sypat":["czech"],"sypkost":["czech"],"syrovost":["czech"],"sysel":["czech"],"sytost":["czech"],"tabletka":["czech"],"tabule":["czech"],"tahoun":["czech"],"tajemno":["czech"],"tajfun":["czech"],"tajga":["czech"],"tajit":["czech"],"tajnost":["czech"],"taktika":["czech"],"tamhle":["czech"],"tampon":["czech","turkish"],"tancovat":["czech"],"tanec":["czech"],"tanker":["czech"],"tapeta":["czech"],"tavenina":["czech"],"tazatel":["czech"],"technika":["czech"],"tehdy":["czech"],"tekutina":["czech"],"telefon":["czech"],"temnota":["czech"],"tendence":["czech"],"tenista":["czech"],"tenor":["czech"],"teplota":["czech"],"tepna":["czech"],"teprve":["czech"],"terapie":["czech"],"termoska":["czech"],"textil":["czech"],"ticho":["czech"],"tiskopis":["czech"],"titulek":["czech"],"tkadlec":["czech"],"tkanina":["czech"],"tlapka":["czech"],"tleskat":["czech"],"tlukot":["czech"],"tlupa":["czech"],"tmel":["czech"],"toaleta":["czech"],"topinka":["czech"],"topol":["czech"],"torzo":["czech"],"touha":["czech"],"toulec":["czech"],"tradice":["czech"],"traktor":["czech"],"tramp":["czech"],"trasa":["czech"],"traverza":["czech"],"trefit":["czech"],"trest":["czech"],"trezor":["czech"],"trhavina":["czech"],"trhlina":["czech"],"trochu":["czech"],"trojice":["czech"],"troska":["czech"],"trouba":["czech"],"trpce":["czech"],"trpitel":["czech"],"trpkost":["czech"],"trubec":["czech"],"truchlit":["czech"],"truhlice":["czech"],"trus":["czech"],"trvat":["czech"],"tudy":["czech"],"tuhnout":["czech"],"tuhost":["czech"],"tundra":["czech"],"turista":["czech"],"turnaj":["czech"],"tuzemsko":["czech"],"tvaroh":["czech"],"tvorba":["czech"],"tvrdost":["czech"],"tvrz":["czech"],"tygr":["czech"],"tykev":["czech"],"ubohost":["czech"],"uboze":["czech"],"ubrat":["czech"],"ubrousek":["czech"],"ubrus":["czech"],"ubytovna":["czech"],"ucho":["czech"],"uctivost":["czech"],"udivit":["czech"],"uhradit":["czech"],"ujednat":["czech"],"ujistit":["czech"],"ujmout":["czech"],"ukazatel":["czech"],"uklidnit":["czech"],"uklonit":["czech"],"ukotvit":["czech"],"ukrojit":["czech"],"ulice":["czech"],"ulita":["czech"],"ulovit":["czech"],"umyvadlo":["czech"],"unavit":["czech"],"uniforma":["czech"],"uniknout":["czech"],"upadnout":["czech"],"uplatnit":["czech"],"uplynout":["czech"],"upoutat":["czech"],"upravit":["czech"],"uran":["czech"],"urazit":["czech"],"usednout":["czech"],"usilovat":["czech"],"usmrtit":["czech"],"usnadnit":["czech"],"usnout":["czech"],"usoudit":["czech"],"ustlat":["czech"],"ustrnout":["czech"],"utahovat":["czech"],"utkat":["czech"],"utlumit":["czech"],"utonout":["czech"],"utopenec":["czech"],"utrousit":["czech"],"uvalit":["czech"],"uvolnit":["czech"],"uvozovka":["czech"],"uzdravit":["czech"],"uzel":["czech"],"uzenina":["czech"],"uzlina":["czech"],"uznat":["czech"],"vagon":["czech","turkish"],"valcha":["czech"],"valoun":["czech"],"vana":["czech"],"vandal":["czech"],"vanilka":["czech"],"varan":["czech"],"varhany":["czech"],"varovat":["czech"],"vcelku":["czech"],"vchod":["czech"],"vdova":["czech"],"vedro":["czech"],"vegetace":["czech"],"vejce":["czech"],"velbloud":["czech"],"veletrh":["czech"],"velitel":["czech"],"velmoc":["czech"],"velryba":["czech"],"venkov":["czech"],"veranda":["czech"],"verze":["czech"],"veselka":["czech"],"veskrze":["czech"],"vesnice":["czech"],"vespodu":["czech"],"vesta":["czech"],"veterina":["czech"],"veverka":["czech"],"vibrace":["czech"],"vichr":["czech"],"videohra":["czech"],"vidina":["czech"],"vidle":["czech"],"vila":["czech"],"vinice":["czech"],"viset":["czech"],"vitalita":["czech"],"vize":["czech"],"vizitka":["czech"],"vjezd":["czech"],"vklad":["czech"],"vkus":["czech"],"vlajka":["czech"],"vlak":["czech"],"vlasec":["czech"],"vlevo":["czech"],"vlhkost":["czech"],"vliv":["czech"],"vlnovka":["czech"],"vloupat":["czech"],"vnucovat":["czech"],"vnuk":["czech"],"voda":["czech"],"vodivost":["czech"],"vodoznak":["czech"],"vodstvo":["czech"],"vojensky":["czech"],"vojna":["czech"],"vojsko":["czech"],"volant":["czech"],"volba":["czech"],"volit":["czech"],"volno":["czech"],"voskovka":["czech"],"vozidlo":["czech"],"vozovna":["czech"],"vpravo":["czech"],"vrabec":["czech"],"vracet":["czech"],"vrah":["czech"],"vrata":["czech"],"vrba":["czech"],"vrcholek":["czech"],"vrhat":["czech"],"vrstva":["czech"],"vrtule":["czech"],"vsadit":["czech"],"vstoupit":["czech"],"vstup":["czech"],"vtip":["czech"],"vybavit":["czech"],"vybrat":["czech"],"vychovat":["czech"],"vydat":["czech"],"vydra":["czech"],"vyfotit":["czech"],"vyhledat":["czech"],"vyhnout":["czech"],"vyhodit":["czech"],"vyhradit":["czech"],"vyhubit":["czech"],"vyjasnit":["czech"],"vyjet":["czech"],"vyjmout":["czech"],"vyklopit":["czech"],"vykonat":["czech"],"vylekat":["czech"],"vymazat":["czech"],"vymezit":["czech"],"vymizet":["czech"],"vymyslet":["czech"],"vynechat":["czech"],"vynikat":["czech"],"vynutit":["czech"],"vypadat":["czech"],"vyplatit":["czech"],"vypravit":["czech"],"vypustit":["czech"],"vyrazit":["czech"],"vyrovnat":["czech"],"vyrvat":["czech"],"vyslovit":["czech"],"vysoko":["czech"],"vystavit":["czech"],"vysunout":["czech"],"vysypat":["czech"],"vytasit":["czech"],"vytesat":["czech"],"vytratit":["czech"],"vyvinout":["czech"],"vyvolat":["czech"],"vyvrhel":["czech"],"vyzdobit":["czech"],"vyznat":["czech"],"vzadu":["czech"],"vzbudit":["czech"],"vzchopit":["czech"],"vzdor":["czech"],"vzduch":["czech"],"vzdychat":["czech"],"vzestup":["czech"],"vzhledem":["czech"],"vzkaz":["czech"],"vzlykat":["czech"],"vznik":["czech"],"vzorek":["czech"],"vzpoura":["czech"],"vztah":["czech"],"vztek":["czech"],"xylofon":["czech"],"zabrat":["czech"],"zabydlet":["czech"],"zachovat":["czech"],"zadarmo":["czech"],"zadusit":["czech"],"zafoukat":["czech"],"zahltit":["czech"],"zahodit":["czech"],"zahrada":["czech"],"zahynout":["czech"],"zajatec":["czech"],"zajet":["czech"],"zajistit":["czech"],"zaklepat":["czech"],"zakoupit":["czech"],"zalepit":["czech"],"zamezit":["czech"],"zamotat":["czech"],"zamyslet":["czech"],"zanechat":["czech"],"zanikat":["czech"],"zaplatit":["czech"],"zapojit":["czech"],"zapsat":["czech"],"zarazit":["czech"],"zastavit":["czech"],"zasunout":["czech"],"zatajit":["czech"],"zatemnit":["czech"],"zatknout":["czech"],"zaujmout":["czech"],"zavalit":["czech"],"zavelet":["czech"],"zavinit":["czech"],"zavolat":["czech"],"zavrtat":["czech"],"zazvonit":["czech"],"zbavit":["czech"],"zbrusu":["czech"],"zbudovat":["czech"],"zbytek":["czech"],"zdaleka":["czech"],"zdarma":["czech"],"zdatnost":["czech"],"zdivo":["czech"],"zdobit":["czech"],"zdroj":["czech"],"zdvih":["czech"],"zdymadlo":["czech"],"zelenina":["czech"],"zeman":["czech"],"zemina":["czech"],"zeptat":["czech"],"zezadu":["czech"],"zezdola":["czech"],"zhatit":["czech"],"zhltnout":["czech"],"zhluboka":["czech"],"zhotovit":["czech"],"zhruba":["czech"],"zima":["czech"],"zimnice":["czech"],"zjemnit":["czech"],"zklamat":["czech"],"zkoumat":["czech"],"zkratka":["czech"],"zkumavka":["czech"],"zlato":["czech"],"zlehka":["czech"],"zloba":["czech"],"zlom":["czech"],"zlost":["czech"],"zlozvyk":["czech"],"zmapovat":["czech"],"zmar":["czech"],"zmatek":["czech"],"zmije":["czech"],"zmizet":["czech"],"zmocnit":["czech"],"zmodrat":["czech"],"zmrzlina":["czech"],"zmutovat":["czech"],"znak":["czech"],"znalost":["czech"],"znamenat":["czech"],"znovu":["czech"],"zobrazit":["czech"],"zotavit":["czech"],"zoubek":["czech"],"zoufale":["czech"],"zplodit":["czech"],"zpomalit":["czech"],"zprava":["czech"],"zprostit":["czech"],"zprudka":["czech"],"zprvu":["czech"],"zrada":["czech"],"zranit":["czech"],"zrcadlo":["czech"],"zrnitost":["czech"],"zrno":["czech"],"zrovna":["czech"],"zrychlit":["czech"],"zrzavost":["czech"],"zticha":["czech"],"ztratit":["czech"],"zubovina":["czech"],"zubr":["czech"],"zvednout":["czech"],"zvenku":["czech"],"zvesela":["czech"],"zvon":["czech"],"zvrat":["czech"],"zvukovod":["czech"],"zvyk":["czech"],"abandon":["english","french"],"ability":["english"],"able":["english"],"about":["english"],"above":["english"],"absent":["english"],"absorb":["english"],"abstract":["english"],"absurd":["english"],"abuse":["english"],"access":["english"],"accident":["english"],"account":["english"],"accuse":["english"],"achieve":["english"],"acid":["english"],"acoustic":["english"],"acquire":["english"],"across":["english"],"act":["english"],"action":["english"],"actor":["english"],"actress":["english"],"actual":["english"],"adapt":["english"],"add":["english"],"addict":["english"],"address":["english"],"adjust":["english"],"admit":["english"],"adult":["english"],"advance":["english"],"advice":["english"],"aerobic":["english"],"affair":["english"],"afford":["english"],"afraid":["english"],"again":["english"],"age":["english"],"agent":["english"],"agree":["english"],"ahead":["english"],"aim":["english"],"air":["english"],"airport":["english"],"aisle":["english"],"alarm":["english"],"album":["english"],"alcohol":["english"],"alert":["english"],"alien":["english"],"all":["english"],"alley":["english"],"allow":["english"],"almost":["english"],"alone":["english"],"alpha":["english"],"already":["english"],"also":["english"],"alter":["english"],"always":["english"],"amateur":["english","french"],"amazing":["english"],"among":["english"],"amount":["english"],"amused":["english"],"analyst":["english"],"anchor":["english"],"ancient":["english"],"anger":["english"],"angle":["english","french"],"angry":["english"],"animal":["english","french"],"ankle":["english"],"announce":["english"],"annual":["english"],"another":["english"],"answer":["english"],"antenna":["english"],"antique":["english"],"anxiety":["english"],"any":["english"],"apart":["english"],"apology":["english"],"appear":["english"],"apple":["english"],"approve":["english"],"april":["english"],"arch":["english"],"arctic":["english"],"area":["english"],"arena":["english","turkish"],"argue":["english"],"arm":["english"],"armed":["english"],"armor":["english"],"army":["english"],"around":["english"],"arrange":["english"],"arrest":["english"],"arrive":["english"],"arrow":["english"],"art":["english"],"artefact":["english"],"artist":["english","turkish"],"artwork":["english"],"ask":["english"],"aspect":["english","french"],"assault":["english"],"asset":["english"],"assist":["english"],"assume":["english"],"asthma":["english"],"athlete":["english"],"atom":["english","turkish"],"attack":["english"],"attend":["english"],"attitude":["english"],"attract":["english"],"auction":["english"],"audit":["english"],"august":["english"],"aunt":["english"],"author":["english"],"auto":["english"],"autumn":["english"],"average":["english"],"avocado":["english"],"avoid":["english"],"awake":["english"],"aware":["english"],"away":["english"],"awesome":["english"],"awful":["english"],"awkward":["english"],"axis":["english"],"baby":["english"],"bachelor":["english"],"bacon":["english"],"badge":["english","french"],"bag":["english"],"balance":["english"],"balcony":["english"],"ball":["english"],"bamboo":["english"],"banana":["english"],"banner":["english"],"bar":["english"],"barely":["english"],"bargain":["english"],"barrel":["english"],"base":["english"],"basic":["english"],"basket":["english"],"battle":["english"],"beach":["english"],"bean":["english"],"beauty":["english"],"because":["english"],"become":["english"],"beef":["english"],"before":["english"],"begin":["english"],"behave":["english"],"behind":["english"],"believe":["english"],"below":["english"],"belt":["english"],"bench":["english"],"benefit":["english"],"best":["english"],"betray":["english"],"better":["english"],"between":["english"],"beyond":["english"],"bicycle":["english","french"],"bid":["english"],"bike":["english"],"bind":["english"],"biology":["english"],"bird":["english"],"birth":["english"],"bitter":["english"],"black":["english"],"blade":["english"],"blame":["english"],"blanket":["english"],"blast":["english"],"bleak":["english"],"bless":["english"],"blind":["english"],"blood":["english"],"blossom":["english"],"blouse":["english"],"blue":["english"],"blur":["english"],"blush":["english"],"board":["english"],"boat":["english"],"body":["english"],"boil":["english"],"bomb":["english"],"bone":["english"],"bonus":["english","french"],"book":["english"],"boost":["english"],"border":["english"],"boring":["english"],"borrow":["english"],"boss":["english"],"bottom":["english"],"bounce":["english"],"box":["english"],"boy":["english"],"bracket":["english"],"brain":["english"],"brand":["english"],"brass":["english"],"brave":["english","french"],"bread":["english"],"breeze":["english"],"brick":["english"],"bridge":["english"],"brief":["english"],"bright":["english"],"bring":["english"],"brisk":["english"],"broccoli":["english"],"broken":["english"],"bronze":["english"],"broom":["english"],"brother":["english"],"brown":["english"],"brush":["english"],"bubble":["english"],"buddy":["english"],"budget":["english"],"buffalo":["english"],"build":["english"],"bulb":["english"],"bulk":["english"],"bullet":["english"],"bundle":["english"],"bunker":["english"],"burden":["english"],"burger":["english"],"burst":["english"],"bus":["english"],"business":["english"],"busy":["english"],"butter":["english"],"buyer":["english"],"buzz":["english"],"cabbage":["english"],"cabin":["english"],"cable":["english"],"cactus":["english"],"cage":["english"],"cake":["english"],"call":["english"],"calm":["english"],"camera":["english"],"camp":["english"],"can":["english"],"canal":["english","french"],"cancel":["english"],"candy":["english"],"cannon":["english"],"canoe":["english"],"canvas":["english"],"canyon":["english"],"capable":["english","french"],"capital":["english"],"captain":["english"],"car":["english"],"carbon":["english"],"card":["english"],"cargo":["english"],"carpet":["english"],"carry":["english"],"cart":["english"],"case":["english"],"cash":["english"],"casino":["english"],"castle":["english"],"casual":["english"],"cat":["english"],"catalog":["english"],"catch":["english"],"category":["english"],"cattle":["english"],"caught":["english"],"cause":["english"],"caution":["english","french"],"cave":["english"],"ceiling":["english"],"celery":["english"],"cement":["english"],"census":["english"],"century":["english"],"cereal":["english"],"certain":["english"],"chair":["english"],"chalk":["english"],"champion":["english"],"change":["english"],"chaos":["english"],"chapter":["english"],"charge":["english"],"chase":["english"],"chat":["english"],"cheap":["english"],"check":["english"],"cheese":["english"],"chef":["english"],"cherry":["english"],"chest":["english"],"chicken":["english"],"chief":["english"],"child":["english"],"chimney":["english"],"choice":["english"],"choose":["english"],"chronic":["english"],"chuckle":["english"],"chunk":["english"],"churn":["english"],"cigar":["english"],"cinnamon":["english"],"circle":["english"],"citizen":["english"],"city":["english"],"civil":["english","french"],"claim":["english"],"clap":["english"],"clarify":["english"],"claw":["english"],"clay":["english"],"clean":["english"],"clerk":["english"],"clever":["english"],"click":["english"],"client":["english","french"],"cliff":["english"],"climb":["english"],"clinic":["english"],"clip":["english"],"clock":["english"],"clog":["english"],"close":["english"],"cloth":["english"],"cloud":["english"],"clown":["english"],"club":["english"],"clump":["english"],"cluster":["english"],"clutch":["english"],"coach":["english"],"coast":["english"],"coconut":["english"],"code":["english"],"coffee":["english"],"coil":["english"],"coin":["english"],"collect":["english"],"color":["english"],"column":["english"],"combine":["english"],"come":["english"],"comfort":["english"],"comic":["english"],"common":["english"],"company":["english"],"concert":["english","french"],"conduct":["english"],"confirm":["english"],"congress":["english"],"connect":["english"],"consider":["english"],"control":["english"],"convince":["english"],"cook":["english"],"cool":["english"],"copper":["english"],"copy":["english"],"coral":["english"],"core":["english"],"corn":["english"],"correct":["english","french"],"cost":["english"],"cotton":["english"],"couch":["english"],"country":["english"],"couple":["english"],"course":["english"],"cousin":["english"],"cover":["english"],"coyote":["english","french"],"crack":["english"],"cradle":["english"],"craft":["english"],"cram":["english"],"crane":["english"],"crash":["english"],"crater":["english"],"crawl":["english"],"crazy":["english"],"cream":["english"],"credit":["english"],"creek":["english"],"crew":["english"],"cricket":["english"],"crime":["english"],"crisp":["english"],"critic":["english"],"crop":["english"],"cross":["english"],"crouch":["english"],"crowd":["english"],"crucial":["english","french"],"cruel":["english","french"],"cruise":["english"],"crumble":["english"],"crunch":["english"],"crush":["english"],"cry":["english"],"crystal":["english"],"cube":["english"],"culture":["english"],"cup":["english"],"cupboard":["english"],"curious":["english"],"current":["english"],"curtain":["english"],"curve":["english"],"cushion":["english"],"custom":["english"],"cute":["english"],"cycle":["english","french"],"dad":["english"],"damage":["english"],"damp":["english"],"dance":["english"],"danger":["english","french"],"daring":["english"],"dash":["english"],"daughter":["english"],"dawn":["english"],"day":["english"],"deal":["english"],"debate":["english"],"debris":["english"],"decade":["english"],"december":["english"],"decide":["english"],"decline":["english"],"decorate":["english"],"decrease":["english"],"deer":["english"],"defense":["english"],"define":["english"],"defy":["english"],"degree":["english"],"delay":["english"],"deliver":["english"],"demand":["english"],"demise":["english"],"denial":["english"],"dentist":["english"],"deny":["english"],"depart":["english"],"depend":["english"],"deposit":["english"],"depth":["english"],"deputy":["english"],"derive":["english"],"describe":["english"],"desert":["english"],"design":["english"],"desk":["english"],"despair":["english"],"destroy":["english"],"detail":["english"],"detect":["english"],"develop":["english"],"device":["english"],"devote":["english"],"diagram":["english"],"dial":["english"],"diamond":["english"],"diary":["english"],"dice":["english"],"diesel":["english"],"diet":["english"],"differ":["english"],"digital":["english","french"],"dignity":["english"],"dilemma":["english"],"dinner":["english"],"dinosaur":["english"],"direct":["english"],"dirt":["english"],"disagree":["english"],"discover":["english"],"disease":["english"],"dish":["english"],"dismiss":["english"],"disorder":["english"],"display":["english"],"distance":["english","french"],"divert":["english"],"divide":["english"],"divorce":["english"],"dizzy":["english"],"doctor":["english"],"document":["english"],"dog":["english"],"doll":["english"],"dolphin":["english"],"domain":["english"],"donate":["english"],"donkey":["english"],"donor":["english"],"door":["english"],"dose":["english"],"double":["english","french"],"dove":["english"],"draft":["english"],"dragon":["english","french"],"drama":["english"],"drastic":["english"],"draw":["english"],"dream":["english"],"dress":["english"],"drift":["english"],"drill":["english"],"drink":["english"],"drip":["english"],"drive":["english"],"drop":["english"],"drum":["english"],"dry":["english"],"duck":["english"],"dumb":["english"],"dune":["english"],"during":["english"],"dust":["english"],"dutch":["english"],"duty":["english"],"dwarf":["english"],"dynamic":["english"],"eager":["english"],"eagle":["english"],"early":["english"],"earn":["english"],"earth":["english"],"easily":["english"],"east":["english"],"easy":["english"],"echo":["english"],"ecology":["english"],"economy":["english"],"edge":["english"],"edit":["english"],"educate":["english"],"effort":["english","french"],"egg":["english"],"eight":["english"],"either":["english"],"elbow":["english"],"elder":["english"],"electric":["english"],"elegant":["english"],"element":["english"],"elephant":["english"],"elevator":["english"],"elite":["english"],"else":["english"],"embark":["english"],"embody":["english"],"embrace":["english"],"emerge":["english"],"emotion":["english"],"employ":["english"],"empower":["english"],"empty":["english"],"enable":["english"],"enact":["english"],"end":["english"],"endless":["english"],"endorse":["english"],"enemy":["english"],"energy":["english"],"enforce":["english"],"engage":["english"],"engine":["english"],"enhance":["english"],"enjoy":["english"],"enlist":["english"],"enough":["english"],"enrich":["english"],"enroll":["english"],"ensure":["english"],"enter":["english"],"entire":["english"],"entry":["english"],"envelope":["english"],"episode":["english"],"equal":["english"],"equip":["english"],"era":["english"],"erase":["english"],"erode":["english"],"erosion":["english"],"error":["english"],"erupt":["english"],"escape":["english"],"essay":["english"],"essence":["english","french"],"estate":["english"],"eternal":["english"],"ethics":["english"],"evidence":["english"],"evil":["english"],"evoke":["english"],"evolve":["english"],"exact":["english","french"],"example":["english"],"excess":["english"],"exchange":["english"],"excite":["english"],"exclude":["english"],"excuse":["english","french"],"execute":["english"],"exercise":["english"],"exhaust":["english"],"exhibit":["english"],"exile":["english"],"exist":["english"],"exit":["english"],"exotic":["english"],"expand":["english"],"expect":["english"],"expire":["english"],"explain":["english"],"expose":["english"],"express":["english"],"extend":["english"],"extra":["english"],"eye":["english"],"eyebrow":["english"],"fabric":["english"],"face":["english"],"faculty":["english"],"fade":["english"],"faint":["english"],"faith":["english"],"fall":["english"],"false":["english"],"fame":["english"],"family":["english"],"famous":["english"],"fan":["english"],"fancy":["english"],"fantasy":["english"],"farm":["english"],"fashion":["english"],"fat":["english"],"fatal":["english","french"],"father":["english"],"fatigue":["english","french"],"fault":["english"],"favorite":["english"],"feature":["english"],"february":["english"],"federal":["english","turkish"],"fee":["english"],"feed":["english"],"feel":["english"],"female":["english"],"fence":["english"],"festival":["english","french","turkish"],"fetch":["english"],"fever":["english"],"few":["english"],"fiber":["english"],"fiction":["english"],"field":["english"],"figure":["english","french"],"file":["english"],"film":["english"],"filter":["english"],"final":["english"],"find":["english"],"fine":["english"],"finger":["english"],"finish":["english"],"fire":["english"],"firm":["english"],"first":["english"],"fiscal":["english"],"fish":["english"],"fit":["english"],"fitness":["english"],"fix":["english"],"flag":["english"],"flame":["english"],"flash":["english"],"flat":["english"],"flavor":["english"],"flee":["english"],"flight":["english"],"flip":["english"],"float":["english"],"flock":["english"],"floor":["english"],"flower":["english"],"fluid":["english"],"flush":["english"],"fly":["english"],"foam":["english"],"focus":["english"],"fog":["english"],"foil":["english"],"fold":["english"],"follow":["english"],"food":["english"],"foot":["english"],"force":["english"],"forest":["english"],"forget":["english"],"fork":["english"],"fortune":["english","french"],"forum":["english"],"forward":["english"],"fossil":["english"],"foster":["english"],"found":["english"],"fox":["english"],"fragile":["english","french"],"frame":["english"],"frequent":["english"],"fresh":["english"],"friend":["english"],"fringe":["english"],"frog":["english"],"front":["english"],"frost":["english"],"frown":["english"],"frozen":["english"],"fruit":["english","french"],"fuel":["english"],"fun":["english"],"funny":["english"],"furnace":["english"],"fury":["english"],"future":["english"],"gadget":["english"],"gain":["english"],"galaxy":["english"],"gallery":["english"],"game":["english"],"gap":["english"],"garage":["english"],"garbage":["english"],"garden":["english"],"garlic":["english"],"garment":["english"],"gas":["english"],"gasp":["english"],"gate":["english"],"gather":["english"],"gauge":["english"],"gaze":["english"],"general":["english"],"genius":["english"],"genre":["english"],"gentle":["english"],"genuine":["english"],"gesture":["english"],"ghost":["english"],"giant":["english"],"gift":["english"],"giggle":["english"],"ginger":["english"],"giraffe":["english"],"girl":["english"],"give":["english"],"glad":["english"],"glance":["english"],"glare":["english"],"glass":["english"],"glide":["english"],"glimpse":["english"],"globe":["english","french"],"gloom":["english"],"glory":["english"],"glove":["english"],"glow":["english"],"glue":["english"],"goat":["english"],"goddess":["english"],"gold":["english"],"good":["english"],"goose":["english"],"gorilla":["english"],"gospel":["english"],"gossip":["english"],"govern":["english"],"gown":["english"],"grab":["english"],"grace":["english"],"grain":["english"],"grant":["english"],"grape":["english"],"grass":["english"],"gravity":["english"],"great":["english"],"green":["english"],"grid":["english"],"grief":["english"],"grit":["english"],"grocery":["english"],"group":["english"],"grow":["english"],"grunt":["english"],"guard":["english"],"guess":["english"],"guide":["english","french"],"guilt":["english"],"guitar":["english"],"gun":["english"],"gym":["english"],"habit":["english"],"hair":["english"],"half":["english"],"hammer":["english"],"hamster":["english"],"hand":["english"],"happy":["english"],"harbor":["english"],"hard":["english"],"harsh":["english"],"harvest":["english"],"hat":["english"],"have":["english"],"hawk":["english"],"hazard":["english"],"head":["english"],"health":["english"],"heart":["english"],"heavy":["english"],"hedgehog":["english"],"height":["english"],"hello":["english"],"helmet":["english"],"help":["english"],"hen":["english"],"hero":["english"],"hidden":["english"],"high":["english"],"hill":["english"],"hint":["english"],"hip":["english"],"hire":["english"],"history":["english"],"hobby":["english"],"hockey":["english"],"hold":["english"],"hole":["english"],"holiday":["english"],"hollow":["english"],"home":["english"],"honey":["english"],"hood":["english"],"hope":["english"],"horn":["english"],"horror":["english"],"horse":["english"],"hospital":["english"],"host":["english"],"hotel":["english"],"hour":["english"],"hover":["english"],"hub":["english"],"huge":["english"],"human":["english"],"humble":["english","french"],"humor":["english"],"hundred":["english"],"hungry":["english"],"hunt":["english"],"hurdle":["english"],"hurry":["english"],"hurt":["english"],"husband":["english"],"hybrid":["english"],"ice":["english"],"icon":["english"],"idea":["english"],"identify":["english"],"idle":["english"],"ignore":["english"],"ill":["english"],"illegal":["english"],"illness":["english"],"image":["english","french"],"imitate":["english"],"immense":["english","french"],"immune":["english"],"impact":["english","french"],"impose":["english"],"improve":["english"],"impulse":["english"],"inch":["english"],"include":["english"],"income":["english"],"increase":["english"],"index":["english"],"indicate":["english"],"indoor":["english"],"industry":["english"],"infant":["english"],"inflict":["english"],"inform":["english"],"inhale":["english"],"inherit":["english"],"initial":["english"],"inject":["english"],"injury":["english"],"inmate":["english"],"inner":["english"],"innocent":["english","french"],"input":["english"],"inquiry":["english"],"insane":["english"],"insect":["english"],"inside":["english"],"inspire":["english"],"install":["english"],"intact":["english","french"],"interest":["english"],"into":["english"],"invest":["english"],"invite":["english"],"involve":["english"],"iron":["english"],"island":["english"],"isolate":["english"],"issue":["english"],"item":["english"],"ivory":["english"],"jacket":["english"],"jaguar":["english","french"],"jar":["english"],"jazz":["english"],"jealous":["english"],"jeans":["english"],"jelly":["english"],"jewel":["english"],"job":["english"],"join":["english"],"joke":["english"],"journey":["english"],"joy":["english"],"judge":["english"],"juice":["english"],"jump":["english"],"jungle":["english"],"junior":["english","french"],"junk":["english"],"just":["english"],"kangaroo":["english"],"keen":["english"],"keep":["english"],"ketchup":["english"],"key":["english"],"kick":["english"],"kid":["english"],"kidney":["english"],"kind":["english"],"kingdom":["english"],"kiss":["english"],"kit":["english"],"kitchen":["english"],"kite":["english"],"kitten":["english"],"kiwi":["english"],"knee":["english"],"knife":["english"],"knock":["english"],"know":["english"],"lab":["english"],"label":["english","french"],"labor":["english"],"ladder":["english"],"lady":["english"],"lake":["english"],"lamp":["english"],"language":["english"],"laptop":["english"],"large":["english"],"later":["english"],"latin":["english"],"laugh":["english"],"laundry":["english"],"lava":["english"],"law":["english"],"lawn":["english"],"lawsuit":["english"],"layer":["english"],"lazy":["english"],"leader":["english"],"leaf":["english"],"learn":["english"],"leave":["english"],"lecture":["english","french"],"left":["english"],"leg":["english"],"legal":["english"],"legend":["english"],"leisure":["english"],"lemon":["english"],"lend":["english"],"length":["english"],"lens":["english"],"leopard":["english"],"lesson":["english"],"letter":["english"],"level":["english"],"liar":["english"],"liberty":["english"],"library":["english"],"license":["english"],"life":["english"],"lift":["english"],"light":["english"],"like":["english"],"limb":["english"],"limit":["english"],"link":["english"],"lion":["english"],"liquid":["english"],"list":["english"],"little":["english"],"live":["english"],"lizard":["english"],"load":["english"],"loan":["english"],"lobster":["english"],"local":["english"],"lock":["english"],"logic":["english"],"lonely":["english"],"long":["english"],"loop":["english"],"lottery":["english"],"loud":["english"],"lounge":["english"],"love":["english"],"loyal":["english","french"],"lucky":["english"],"luggage":["english"],"lumber":["english"],"lunar":["english"],"lunch":["english"],"luxury":["english"],"lyrics":["english"],"machine":["english","french"],"mad":["english"],"magic":["english"],"magnet":["english"],"maid":["english"],"mail":["english"],"main":["english"],"major":["english"],"make":["english"],"mammal":["english"],"man":["english"],"manage":["english"],"mandate":["english"],"mango":["english"],"mansion":["english"],"manual":["english"],"maple":["english"],"marble":["english"],"march":["english"],"margin":["english"],"marine":["english"],"market":["english","turkish"],"marriage":["english"],"mask":["english"],"mass":["english"],"master":["english"],"match":["english"],"material":["english"],"math":["english"],"matrix":["english"],"matter":["english"],"maximum":["english"],"maze":["english"],"meadow":["english"],"mean":["english"],"measure":["english"],"meat":["english"],"mechanic":["english"],"medal":["english"],"media":["english"],"melody":["english"],"melt":["english"],"member":["english"],"memory":["english"],"mention":["english"],"menu":["english"],"mercy":["english"],"merge":["english"],"merit":["english"],"merry":["english"],"mesh":["english"],"message":["english"],"metal":["english"],"method":["english"],"middle":["english"],"midnight":["english"],"milk":["english"],"million":["english","french"],"mimic":["english"],"mind":["english"],"minimum":["english"],"minor":["english"],"minute":["english","french"],"miracle":["english","french"],"mirror":["english"],"misery":["english"],"miss":["english"],"mistake":["english"],"mix":["english"],"mixed":["english"],"mixture":["english"],"mobile":["english","french"],"model":["english","turkish"],"modify":["english"],"mom":["english"],"moment":["english"],"monitor":["english"],"monkey":["english"],"monster":["english"],"month":["english"],"moon":["english"],"moral":["english"],"more":["english"],"morning":["english"],"mosquito":["english"],"mother":["english"],"motion":["english"],"motor":["english","turkish"],"mountain":["english"],"mouse":["english"],"move":["english"],"movie":["english"],"much":["english"],"muffin":["english"],"mule":["english"],"multiply":["english"],"muscle":["english","french"],"museum":["english"],"mushroom":["english"],"music":["english"],"must":["english"],"mutual":["english"],"myself":["english"],"mystery":["english"],"myth":["english"],"naive":["english"],"name":["english"],"napkin":["english"],"narrow":["english"],"nasty":["english"],"nation":["english","french"],"nature":["english","french"],"near":["english"],"neck":["english"],"need":["english"],"negative":["english"],"neglect":["english"],"neither":["english"],"nephew":["english"],"nerve":["english"],"nest":["english"],"net":["english"],"network":["english"],"neutral":["english"],"never":["english"],"news":["english"],"next":["english"],"nice":["english"],"night":["english"],"noble":["english","french"],"noise":["english"],"nominee":["english"],"noodle":["english"],"normal":["english","turkish"],"north":["english"],"nose":["english"],"notable":["english","french"],"note":["english"],"nothing":["english"],"notice":["english"],"novel":["english"],"now":["english"],"nuclear":["english"],"number":["english"],"nurse":["english"],"nut":["english"],"oak":["english"],"obey":["english"],"object":["english"],"oblige":["english"],"obscure":["english"],"observe":["english"],"obtain":["english"],"obvious":["english"],"occur":["english"],"ocean":["english"],"october":["english"],"odor":["english"],"off":["english"],"offer":["english"],"office":["english"],"often":["english"],"oil":["english"],"okay":["english"],"old":["english"],"olive":["english"],"olympic":["english"],"omit":["english"],"once":["english"],"one":["english"],"onion":["english"],"online":["english"],"only":["english"],"open":["english"],"opera":["english","turkish"],"opinion":["english","french"],"oppose":["english"],"option":["english"],"orange":["english","french"],"orbit":["english"],"orchard":["english"],"order":["english"],"ordinary":["english"],"organ":["english"],"orient":["english"],"original":["english"],"orphan":["english"],"ostrich":["english"],"other":["english"],"outdoor":["english"],"outer":["english"],"output":["english"],"outside":["english"],"oval":["english"],"oven":["english"],"over":["english"],"own":["english"],"owner":["english"],"oxygen":["english"],"oyster":["english"],"ozone":["english","french"],"pact":["english"],"paddle":["english"],"page":["english"],"pair":["english"],"palace":["english","french"],"palm":["english"],"panda":["english","french","turkish"],"panel":["english","turkish"],"panic":["english"],"panther":["english"],"paper":["english"],"parade":["english"],"parent":["english"],"park":["english"],"parrot":["english"],"party":["english"],"pass":["english"],"patch":["english"],"path":["english"],"patient":["english"],"patrol":["english"],"pattern":["english"],"pause":["english"],"pave":["english"],"payment":["english"],"peace":["english"],"peanut":["english"],"pear":["english"],"peasant":["english"],"pelican":["english"],"pen":["english"],"penalty":["english"],"pencil":["english"],"people":["english"],"pepper":["english"],"perfect":["english"],"permit":["english"],"person":["english"],"pet":["english"],"phone":["english"],"photo":["english"],"phrase":["english","french"],"physical":["english"],"piano":["english","french"],"picnic":["english"],"picture":["english"],"piece":["english"],"pig":["english"],"pigeon":["english"],"pill":["english"],"pilot":["english","turkish"],"pink":["english"],"pioneer":["english"],"pipe":["english"],"pistol":["english"],"pitch":["english"],"pizza":["english","french"],"place":["english"],"planet":["english"],"plastic":["english"],"plate":["english"],"play":["english"],"please":["english"],"pledge":["english"],"pluck":["english"],"plug":["english"],"plunge":["english"],"poem":["english"],"poet":["english"],"point":["english"],"polar":["english"],"pole":["english"],"police":["english"],"pond":["english"],"pony":["english"],"pool":["english"],"popular":["english"],"portion":["english"],"position":["english","french"],"possible":["english"],"post":["english"],"potato":["english"],"pottery":["english"],"poverty":["english"],"powder":["english"],"power":["english"],"practice":["english"],"praise":["english"],"predict":["english"],"prefer":["english"],"prepare":["english"],"present":["english"],"pretty":["english"],"prevent":["english"],"price":["english"],"pride":["english"],"primary":["english"],"print":["english"],"priority":["english"],"prison":["english","french"],"private":["english"],"prize":["english"],"problem":["english","turkish"],"process":["english"],"produce":["english"],"profit":["english"],"program":["english","turkish"],"project":["english"],"promote":["english"],"proof":["english"],"property":["english"],"prosper":["english"],"protect":["english"],"proud":["english"],"provide":["english"],"public":["english","french"],"pudding":["english"],"pull":["english"],"pulp":["english"],"pulse":["english"],"pumpkin":["english"],"punch":["english"],"pupil":["english"],"puppy":["english"],"purchase":["english"],"purity":["english"],"purpose":["english"],"purse":["english"],"push":["english"],"put":["english"],"puzzle":["english","french"],"pyramid":["english"],"quality":["english"],"quantum":["english"],"quarter":["english"],"question":["english","french"],"quick":["english"],"quit":["english"],"quiz":["english"],"quote":["english"],"rabbit":["english"],"raccoon":["english"],"race":["english"],"rack":["english"],"radar":["english","turkish"],"radio":["english"],"rail":["english"],"rain":["english"],"raise":["english"],"rally":["english"],"ramp":["english"],"ranch":["english"],"random":["english"],"range":["english"],"rapid":["english"],"rare":["english"],"rate":["english"],"rather":["english"],"raven":["english"],"raw":["english"],"razor":["english"],"ready":["english"],"real":["english"],"reason":["english"],"rebel":["english"],"rebuild":["english"],"recall":["english"],"receive":["english"],"recipe":["english"],"record":["english"],"recycle":["english"],"reduce":["english"],"reflect":["english"],"reform":["english","turkish"],"refuse":["english"],"region":["english"],"regret":["english"],"regular":["english"],"reject":["english"],"relax":["english"],"release":["english"],"relief":["english","french"],"rely":["english"],"remain":["english"],"remember":["english"],"remind":["english"],"remove":["english"],"render":["english"],"renew":["english"],"rent":["english"],"reopen":["english"],"repair":["english"],"repeat":["english"],"replace":["english"],"report":["english"],"require":["english"],"rescue":["english"],"resemble":["english"],"resist":["english"],"resource":["english"],"response":["english"],"result":["english"],"retire":["english"],"retreat":["english"],"return":["english"],"reunion":["english"],"reveal":["english"],"review":["english"],"reward":["english"],"rhythm":["english"],"rib":["english"],"ribbon":["english"],"rice":["english"],"rich":["english"],"ride":["english"],"ridge":["english"],"rifle":["english"],"right":["english"],"rigid":["english"],"ring":["english"],"riot":["english"],"ripple":["english"],"risk":["english"],"ritual":["english"],"rival":["english","french"],"river":["english"],"road":["english"],"roast":["english"],"robot":["english","turkish"],"robust":["english"],"rocket":["english"],"romance":["english","french"],"roof":["english"],"rookie":["english"],"room":["english"],"rose":["english"],"rotate":["english"],"rough":["english"],"round":["english"],"route":["english"],"royal":["english"],"rubber":["english"],"rude":["english"],"rug":["english"],"rule":["english"],"run":["english"],"runway":["english"],"rural":["english"],"sad":["english"],"saddle":["english"],"sadness":["english"],"safe":["english"],"sail":["english"],"salad":["english"],"salmon":["english"],"salon":["english","french","turkish"],"salt":["english"],"salute":["english"],"same":["english"],"sample":["english"],"sand":["english"],"satisfy":["english"],"satoshi":["english"],"sauce":["english"],"sausage":["english"],"save":["english"],"say":["english"],"scale":["english"],"scan":["english"],"scare":["english"],"scatter":["english"],"scene":["english"],"scheme":["english"],"school":["english"],"science":["english","french"],"scissors":["english"],"scorpion":["english"],"scout":["english"],"scrap":["english"],"screen":["english"],"script":["english"],"scrub":["english"],"sea":["english"],"search":["english"],"season":["english"],"seat":["english"],"second":["english"],"secret":["english"],"section":["english"],"security":["english"],"seed":["english"],"seek":["english"],"segment":["english"],"select":["english"],"sell":["english"],"seminar":["english"],"senior":["english"],"sense":["english"],"sentence":["english","french"],"series":["english"],"service":["english","french"],"session":["english"],"settle":["english"],"setup":["english"],"seven":["english"],"shadow":["english"],"shaft":["english"],"shallow":["english"],"share":["english"],"shed":["english"],"shell":["english"],"sheriff":["english"],"shield":["english"],"shift":["english"],"shine":["english"],"ship":["english"],"shiver":["english"],"shock":["english"],"shoe":["english"],"shoot":["english"],"shop":["english"],"short":["english"],"shoulder":["english"],"shove":["english"],"shrimp":["english"],"shrug":["english"],"shuffle":["english"],"shy":["english"],"sibling":["english"],"sick":["english"],"side":["english"],"siege":["english"],"sight":["english"],"sign":["english"],"silent":["english"],"silk":["english"],"silly":["english"],"silver":["english"],"similar":["english"],"simple":["english","french"],"since":["english"],"sing":["english"],"siren":["english"],"sister":["english"],"situate":["english"],"six":["english"],"size":["english"],"skate":["english"],"sketch":["english"],"ski":["english"],"skill":["english"],"skin":["english"],"skirt":["english"],"skull":["english"],"slab":["english"],"slam":["english"],"sleep":["english"],"slender":["english"],"slice":["english"],"slide":["english"],"slight":["english"],"slim":["english"],"slogan":["english","turkish"],"slot":["english"],"slow":["english"],"slush":["english"],"small":["english"],"smart":["english"],"smile":["english"],"smoke":["english"],"smooth":["english"],"snack":["english"],"snake":["english"],"snap":["english"],"sniff":["english"],"snow":["english"],"soap":["english"],"soccer":["english"],"social":["english","french"],"sock":["english"],"soda":["english"],"soft":["english"],"solar":["english"],"soldier":["english"],"solid":["english"],"solution":["english"],"solve":["english"],"someone":["english"],"song":["english"],"soon":["english"],"sorry":["english"],"sort":["english"],"soul":["english"],"sound":["english"],"soup":["english"],"source":["english","french"],"south":["english"],"space":["english"],"spare":["english"],"spatial":["english","french"],"spawn":["english"],"speak":["english"],"special":["english"],"speed":["english"],"spell":["english"],"spend":["english"],"sphere":["english"],"spice":["english"],"spider":["english"],"spike":["english"],"spin":["english"],"spirit":["english"],"split":["english"],"spoil":["english"],"sponsor":["english","turkish"],"spoon":["english"],"sport":["english"],"spot":["english"],"spray":["english"],"spread":["english"],"spring":["english"],"spy":["english"],"square":["english"],"squeeze":["english"],"squirrel":["english"],"stable":["english","french"],"stadium":["english"],"staff":["english"],"stage":["english"],"stairs":["english"],"stamp":["english"],"stand":["english"],"start":["english"],"state":["english"],"stay":["english"],"steak":["english"],"steel":["english"],"stem":["english"],"step":["english"],"stereo":["english"],"stick":["english"],"still":["english"],"sting":["english"],"stock":["english"],"stomach":["english"],"stone":["english"],"stool":["english"],"story":["english"],"stove":["english"],"strategy":["english"],"street":["english"],"strike":["english"],"strong":["english"],"struggle":["english"],"student":["english"],"stuff":["english"],"stumble":["english"],"style":["english"],"subject":["english"],"submit":["english"],"subway":["english"],"success":["english"],"such":["english"],"sudden":["english"],"suffer":["english"],"sugar":["english"],"suggest":["english"],"suit":["english"],"summer":["english"],"sun":["english"],"sunny":["english"],"sunset":["english"],"super":["english"],"supply":["english"],"supreme":["english"],"sure":["english"],"surface":["english","french"],"surge":["english"],"surprise":["english","french"],"surround":["english"],"survey":["english"],"suspect":["english","french"],"sustain":["english"],"swallow":["english"],"swamp":["english"],"swap":["english"],"swarm":["english"],"swear":["english"],"sweet":["english"],"swift":["english"],"swim":["english"],"swing":["english"],"switch":["english"],"sword":["english"],"symbol":["english"],"symptom":["english"],"syrup":["english"],"system":["english"],"table":["english"],"tackle":["english"],"tag":["english"],"tail":["english"],"talent":["english","french"],"talk":["english"],"tank":["english"],"tape":["english"],"target":["english"],"task":["english"],"taste":["english"],"tattoo":["english"],"taxi":["english"],"teach":["english"],"team":["english"],"tell":["english"],"ten":["english"],"tenant":["english"],"tennis":["english"],"tent":["english"],"term":["english"],"test":["english"],"text":["english"],"thank":["english"],"that":["english"],"theme":["english"],"then":["english"],"theory":["english"],"there":["english"],"they":["english"],"thing":["english"],"this":["english"],"thought":["english"],"three":["english"],"thrive":["english"],"throw":["english"],"thumb":["english"],"thunder":["english"],"ticket":["english"],"tide":["english"],"tiger":["english"],"tilt":["english"],"timber":["english"],"time":["english"],"tiny":["english"],"tip":["english"],"tired":["english"],"tissue":["english"],"title":["english"],"toast":["english"],"tobacco":["english"],"today":["english"],"toddler":["english"],"toe":["english"],"together":["english"],"toilet":["english"],"token":["english"],"tomato":["english"],"tomorrow":["english"],"tone":["english"],"tongue":["english"],"tonight":["english"],"tool":["english"],"tooth":["english"],"top":["english"],"topic":["english"],"topple":["english"],"torch":["english"],"tornado":["english"],"tortoise":["english"],"toss":["english"],"total":["english"],"tourist":["english"],"toward":["english"],"tower":["english"],"town":["english"],"toy":["english"],"track":["english"],"trade":["english"],"traffic":["english"],"tragic":["english"],"train":["english","french"],"transfer":["english","turkish"],"trap":["english"],"trash":["english"],"travel":["english"],"tray":["english"],"treat":["english"],"tree":["english"],"trend":["english"],"trial":["english"],"tribe":["english"],"trick":["english"],"trigger":["english"],"trim":["english"],"trip":["english"],"trophy":["english"],"trouble":["english"],"truck":["english"],"true":["english"],"truly":["english"],"trumpet":["english"],"trust":["english"],"truth":["english"],"try":["english"],"tube":["english"],"tuition":["english"],"tumble":["english"],"tuna":["english"],"tunnel":["english","french"],"turkey":["english"],"turn":["english"],"turtle":["english"],"twelve":["english"],"twenty":["english"],"twice":["english"],"twin":["english"],"twist":["english"],"two":["english"],"type":["english"],"typical":["english"],"ugly":["english"],"umbrella":["english"],"unable":["english"],"unaware":["english"],"uncle":["english"],"uncover":["english"],"under":["english"],"undo":["english"],"unfair":["english"],"unfold":["english"],"unhappy":["english"],"uniform":["english"],"unique":["english","french"],"unit":["english"],"universe":["english"],"unknown":["english"],"unlock":["english"],"until":["english"],"unusual":["english"],"unveil":["english"],"update":["english"],"upgrade":["english"],"uphold":["english"],"upon":["english"],"upper":["english"],"upset":["english"],"urban":["english"],"urge":["english"],"usage":["english","french"],"use":["english"],"used":["english"],"useful":["english"],"useless":["english"],"usual":["english"],"utility":["english"],"vacant":["english"],"vacuum":["english"],"vague":["english","french"],"valid":["english"],"valley":["english"],"valve":["english","french"],"van":["english"],"vanish":["english"],"vapor":["english"],"various":["english"],"vast":["english"],"vault":["english"],"vehicle":["english"],"velvet":["english"],"vendor":["english"],"venture":["english"],"venue":["english"],"verb":["english"],"verify":["english"],"version":["english"],"very":["english"],"vessel":["english"],"veteran":["english"],"viable":["english"],"vibrant":["english"],"vicious":["english"],"victory":["english"],"video":["english"],"view":["english"],"village":["english","french"],"vintage":["english"],"violin":["english"],"virtual":["english"],"virus":["english","french"],"visa":["english"],"visit":["english"],"visual":["english"],"vital":["english","french"],"vivid":["english"],"vocal":["english"],"voice":["english"],"void":["english"],"volcano":["english"],"volume":["english","french"],"vote":["english"],"voyage":["english","french"],"wage":["english"],"wagon":["english","french"],"wait":["english"],"walk":["english"],"wall":["english"],"walnut":["english"],"want":["english"],"warfare":["english"],"warm":["english"],"warrior":["english"],"wash":["english"],"wasp":["english"],"waste":["english"],"water":["english"],"wave":["english"],"way":["english"],"wealth":["english"],"weapon":["english"],"wear":["english"],"weasel":["english"],"weather":["english"],"web":["english"],"wedding":["english"],"weekend":["english"],"weird":["english"],"welcome":["english"],"west":["english"],"wet":["english"],"whale":["english"],"what":["english"],"wheat":["english"],"wheel":["english"],"when":["english"],"where":["english"],"whip":["english"],"whisper":["english"],"wide":["english"],"width":["english"],"wife":["english"],"wild":["english"],"will":["english"],"win":["english"],"window":["english"],"wine":["english"],"wing":["english"],"wink":["english"],"winner":["english"],"winter":["english"],"wire":["english"],"wisdom":["english"],"wise":["english"],"wish":["english"],"witness":["english"],"wolf":["english"],"woman":["english"],"wonder":["english"],"wood":["english"],"wool":["english"],"word":["english"],"work":["english"],"world":["english"],"worry":["english"],"worth":["english"],"wrap":["english"],"wreck":["english"],"wrestle":["english"],"wrist":["english"],"write":["english"],"wrong":["english"],"yard":["english"],"year":["english"],"yellow":["english"],"you":["english"],"young":["english"],"youth":["english"],"zebra":["english"],"zero":["english"],"zone":["english"],"zoo":["english"],"abaisser":["french"],"abdiquer":["french"],"abeille":["french"],"abolir":["french"],"aborder":["french"],"aboutir":["french"],"aboyer":["french"],"abrasif":["french"],"abreuver":["french"],"abriter":["french"],"abroger":["french"],"abrupt":["french"],"absence":["french"],"absolu":["french"],"absurde":["french"],"abusif":["french"],"abyssal":["french"],"académie":["french"],"acajou":["french"],"acarien":["french"],"accabler":["french"],"accepter":["french"],"acclamer":["french"],"accolade":["french"],"accroche":["french"],"accuser":["french"],"acerbe":["french"],"achat":["french"],"acheter":["french"],"aciduler":["french"],"acier":["french"],"acompte":["french"],"acquérir":["french"],"acronyme":["french"],"acteur":["french"],"actif":["french"],"actuel":["french"],"adepte":["french"],"adéquat":["french"],"adhésif":["french"],"adjectif":["french"],"adjuger":["french"],"admettre":["french"],"admirer":["french"],"adopter":["french"],"adorer":["french"],"adoucir":["french"],"adresse":["french"],"adroit":["french"],"adulte":["french"],"adverbe":["french"],"aérer":["french"],"aéronef":["french"],"affaire":["french"],"affecter":["french"],"affiche":["french"],"affreux":["french"],"affubler":["french"],"agacer":["french"],"agencer":["french"],"agile":["french"],"agiter":["french"],"agrafer":["french"],"agréable":["french"],"agrume":["french"],"aider":["french"],"aiguille":["french"],"ailier":["french"],"aimable":["french"],"aisance":["french"],"ajouter":["french"],"ajuster":["french"],"alarmer":["french"],"alchimie":["french"],"alerte":["french"],"algèbre":["french"],"algue":["french"],"aliéner":["french"],"aliment":["french"],"alléger":["french"],"alliage":["french"],"allouer":["french"],"allumer":["french"],"alourdir":["french"],"alpaga":["french"],"altesse":["french"],"alvéole":["french"],"ambigu":["french"],"ambre":["french"],"aménager":["french"],"amertume":["french"],"amidon":["french"],"amiral":["french"],"amorcer":["french"],"amour":["french"],"amovible":["french"],"amphibie":["french"],"ampleur":["french"],"amusant":["french"],"analyse":["french"],"anaphore":["french"],"anarchie":["french"],"anatomie":["french"],"ancien":["french"],"anéantir":["french"],"angoisse":["french"],"anguleux":["french"],"annexer":["french"],"annonce":["french"],"annuel":["french"],"anodin":["french"],"anomalie":["french"],"anonyme":["french"],"anormal":["french"],"antenne":["french"],"antidote":["french"],"anxieux":["french"],"apaiser":["french"],"apéritif":["french"],"aplanir":["french"],"apologie":["french"],"appareil":["french"],"appeler":["french"],"apporter":["french"],"appuyer":["french"],"aquarium":["french"],"aqueduc":["french"],"arbitre":["french"],"arbuste":["french"],"ardeur":["french"],"ardoise":["french"],"argent":["french"],"arlequin":["french"],"armature":["french"],"armement":["french"],"armoire":["french"],"armure":["french"],"arpenter":["french"],"arracher":["french"],"arriver":["french"],"arroser":["french"],"arsenic":["french"],"artériel":["french"],"article":["french"],"asphalte":["french"],"aspirer":["french"],"assaut":["french"],"asservir":["french"],"assiette":["french"],"associer":["french"],"assurer":["french"],"asticot":["french"],"astre":["french"],"astuce":["french"],"atelier":["french"],"atome":["french"],"atrium":["french"],"atroce":["french"],"attaque":["french"],"attentif":["french"],"attirer":["french"],"attraper":["french"],"aubaine":["french"],"auberge":["french"],"audace":["french"],"audible":["french"],"augurer":["french"],"aurore":["french"],"automne":["french"],"autruche":["french"],"avaler":["french"],"avancer":["french"],"avarice":["french"],"avenir":["french"],"averse":["french"],"aveugle":["french"],"aviateur":["french"],"avide":["french"],"avion":["french"],"aviser":["french"],"avoine":["french"],"avouer":["french"],"avril":["french"],"axial":["french"],"axiome":["french"],"bafouer":["french"],"bagage":["french"],"baguette":["french"],"baignade":["french"],"balancer":["french"],"balcon":["french"],"baleine":["french"],"balisage":["french"],"bambin":["french"],"bancaire":["french"],"bandage":["french"],"banlieue":["french"],"bannière":["french"],"banquier":["french"],"barbier":["french"],"baril":["french"],"baron":["french"],"barque":["french"],"barrage":["french"],"bassin":["french"],"bastion":["french"],"bataille":["french"],"bateau":["french"],"batterie":["french"],"baudrier":["french"],"bavarder":["french"],"belette":["french"],"bélier":["french"],"belote":["french"],"bénéfice":["french"],"berceau":["french"],"berger":["french"],"berline":["french"],"bermuda":["french","turkish"],"besace":["french"],"besogne":["french"],"bétail":["french"],"beurre":["french"],"biberon":["french"],"bidule":["french"],"bijou":["french"],"bilan":["french"],"bilingue":["french"],"billard":["french"],"binaire":["french"],"biologie":["french"],"biopsie":["french"],"biotype":["french"],"biscuit":["french"],"bison":["french"],"bistouri":["french"],"bitume":["french"],"bizarre":["french"],"blafard":["french"],"blague":["french"],"blanchir":["french"],"blessant":["french"],"blinder":["french"],"blond":["french"],"bloquer":["french"],"blouson":["french"],"bobard":["french"],"bobine":["french"],"boire":["french"],"boiser":["french"],"bolide":["french"],"bonbon":["french"],"bondir":["french"],"bonheur":["french"],"bonifier":["french"],"bordure":["french"],"borne":["french"],"botte":["french"],"boucle":["french"],"boueux":["french"],"bougie":["french"],"boulon":["french"],"bouquin":["french"],"bourse":["french"],"boussole":["french"],"boutique":["french"],"boxeur":["french"],"branche":["french"],"brasier":["french"],"brebis":["french"],"brèche":["french"],"breuvage":["french"],"bricoler":["french"],"brigade":["french"],"brillant":["french"],"brioche":["french"],"brique":["french"],"brochure":["french"],"broder":["french"],"bronzer":["french"],"brousse":["french"],"broyeur":["french"],"brume":["french"],"brusque":["french"],"brutal":["french"],"bruyant":["french"],"buffle":["french"],"buisson":["french"],"bulletin":["french"],"bureau":["french"],"burin":["french"],"bustier":["french"],"butiner":["french"],"butoir":["french"],"buvable":["french"],"buvette":["french"],"cabanon":["french"],"cabine":["french"],"cachette":["french"],"cadeau":["french"],"cadre":["french"],"caféine":["french"],"caillou":["french"],"caisson":["french"],"calculer":["french"],"calepin":["french"],"calibre":["french"],"calmer":["french"],"calomnie":["french"],"calvaire":["french"],"camarade":["french"],"caméra":["french"],"camion":["french"],"campagne":["french"],"caneton":["french"],"canon":["french"],"cantine":["french"],"canular":["french"],"caporal":["french"],"caprice":["french"],"capsule":["french"],"capter":["french"],"capuche":["french"],"carabine":["french"],"carbone":["french"],"caresser":["french"],"caribou":["french"],"carnage":["french"],"carotte":["french"],"carreau":["french"],"carton":["french"],"cascade":["french"],"casier":["french"],"casque":["french"],"cassure":["french"],"causer":["french"],"cavalier":["french"],"caverne":["french"],"caviar":["french"],"cédille":["french"],"ceinture":["french"],"céleste":["french"],"cellule":["french"],"cendrier":["french"],"censurer":["french"],"central":["french"],"cercle":["french"],"cérébral":["french"],"cerise":["french"],"cerner":["french"],"cerveau":["french"],"cesser":["french"],"chagrin":["french"],"chaise":["french"],"chaleur":["french"],"chambre":["french"],"chance":["french"],"chapitre":["french"],"charbon":["french"],"chasseur":["french"],"chaton":["french"],"chausson":["french"],"chavirer":["french"],"chemise":["french"],"chenille":["french"],"chéquier":["french"],"chercher":["french"],"cheval":["french"],"chien":["french"],"chiffre":["french"],"chignon":["french"],"chimère":["french"],"chiot":["french"],"chlorure":["french"],"chocolat":["french"],"choisir":["french"],"chose":["french"],"chouette":["french"],"chrome":["french"],"chute":["french"],"cigare":["french"],"cigogne":["french"],"cimenter":["french"],"cinéma":["french"],"cintrer":["french"],"circuler":["french"],"cirer":["french"],"cirque":["french"],"citerne":["french"],"citoyen":["french"],"citron":["french"],"clairon":["french"],"clameur":["french"],"claquer":["french"],"classe":["french"],"clavier":["french"],"cligner":["french"],"climat":["french"],"clivage":["french"],"cloche":["french"],"clonage":["french"],"cloporte":["french"],"cobalt":["french"],"cobra":["french"],"cocasse":["french"],"cocotier":["french"],"coder":["french"],"codifier":["french"],"coffre":["french"],"cogner":["french"],"cohésion":["french"],"coiffer":["french"],"coincer":["french"],"colère":["french"],"colibri":["french"],"colline":["french"],"colmater":["french"],"colonel":["french"],"combat":["french"],"comédie":["french"],"commande":["french"],"compact":["french"],"conduire":["french"],"confier":["french"],"congeler":["french"],"connoter":["french"],"consonne":["french"],"contact":["french"],"convexe":["french"],"copain":["french"],"copie":["french"],"corail":["french"],"corbeau":["french"],"cordage":["french"],"corniche":["french"],"corpus":["french"],"cortège":["french"],"cosmique":["french"],"costume":["french"],"coton":["french"],"coude":["french"],"coupure":["french"],"courage":["french"],"couteau":["french"],"couvrir":["french"],"crabe":["french"],"crainte":["french"],"cravate":["french"],"crayon":["french"],"créature":["french"],"créditer":["french"],"crémeux":["french"],"creuser":["french"],"crevette":["french"],"cribler":["french"],"crier":["french"],"cristal":["french"],"critère":["french"],"croire":["french"],"croquer":["french"],"crotale":["french"],"crypter":["french"],"cubique":["french"],"cueillir":["french"],"cuillère":["french"],"cuisine":["french"],"cuivre":["french"],"culminer":["french"],"cultiver":["french"],"cumuler":["french"],"cupide":["french"],"curatif":["french"],"curseur":["french"],"cyanure":["french"],"cylindre":["french"],"cynique":["french"],"daigner":["french"],"damier":["french"],"danseur":["french"],"dauphin":["french"],"débattre":["french"],"débiter":["french"],"déborder":["french"],"débrider":["french"],"débutant":["french"],"décaler":["french"],"décembre":["french"],"déchirer":["french"],"décider":["french"],"déclarer":["french"],"décorer":["french"],"décrire":["french"],"décupler":["french"],"dédale":["french"],"déductif":["french"],"déesse":["french"],"défensif":["french"],"défiler":["french"],"défrayer":["french"],"dégager":["french"],"dégivrer":["french"],"déglutir":["french"],"dégrafer":["french"],"déjeuner":["french"],"délice":["french"],"déloger":["french"],"demander":["french"],"demeurer":["french"],"démolir":["french"],"dénicher":["french"],"dénouer":["french"],"dentelle":["french"],"dénuder":["french"],"départ":["french"],"dépenser":["french"],"déphaser":["french"],"déplacer":["french"],"déposer":["french"],"déranger":["french"],"dérober":["french"],"désastre":["french"],"descente":["french"],"désert":["french"],"désigner":["french"],"désobéir":["french"],"dessiner":["french"],"destrier":["french"],"détacher":["french"],"détester":["french"],"détourer":["french"],"détresse":["french"],"devancer":["french"],"devenir":["french"],"deviner":["french"],"devoir":["french"],"diable":["french"],"dialogue":["french"],"diamant":["french"],"dicter":["french"],"différer":["french"],"digérer":["french"],"digne":["french"],"diluer":["french"],"dimanche":["french"],"diminuer":["french"],"dioxyde":["french"],"directif":["french"],"diriger":["french"],"discuter":["french"],"disposer":["french"],"dissiper":["french"],"divertir":["french"],"diviser":["french"],"docile":["french"],"docteur":["french"],"dogme":["french"],"doigt":["french"],"domaine":["french"],"domicile":["french"],"dompter":["french"],"donateur":["french"],"donjon":["french"],"donner":["french"],"dopamine":["french"],"dortoir":["french"],"dorure":["french"],"dosage":["french"],"doseur":["french"],"dossier":["french"],"dotation":["french"],"douanier":["french"],"douceur":["french"],"douter":["french"],"doyen":["french"],"draper":["french"],"dresser":["french"],"dribbler":["french"],"droiture":["french"],"duperie":["french"],"duplexe":["french"],"durable":["french"],"durcir":["french"],"dynastie":["french"],"éblouir":["french"],"écarter":["french"],"écharpe":["french"],"échelle":["french"],"éclairer":["french"],"éclipse":["french"],"éclore":["french"],"écluse":["french"],"école":["french"],"économie":["french"],"écorce":["french"],"écouter":["french"],"écraser":["french"],"écrémer":["french"],"écrivain":["french"],"écrou":["french"],"écume":["french"],"écureuil":["french"],"édifier":["french"],"éduquer":["french"],"effacer":["french"],"effectif":["french"],"effigie":["french"],"effrayer":["french"],"effusion":["french"],"égaliser":["french"],"égarer":["french"],"éjecter":["french"],"élaborer":["french"],"élargir":["french"],"électron":["french"],"élégant":["french"],"éléphant":["french"],"élève":["french"],"éligible":["french"],"élitisme":["french"],"éloge":["french"],"élucider":["french"],"éluder":["french"],"emballer":["french"],"embellir":["french"],"embryon":["french"],"émeraude":["french"],"émission":["french"],"emmener":["french"],"émotion":["french"],"émouvoir":["french"],"empereur":["french"],"employer":["french"],"emporter":["french"],"emprise":["french"],"émulsion":["french"],"encadrer":["french"],"enchère":["french"],"enclave":["french"],"encoche":["french"],"endiguer":["french"],"endosser":["french"],"endroit":["french"],"enduire":["french"],"énergie":["french"],"enfance":["french"],"enfermer":["french"],"enfouir":["french"],"engager":["french"],"engin":["french","turkish"],"englober":["french"],"énigme":["french"],"enjamber":["french"],"enjeu":["french"],"enlever":["french"],"ennemi":["french"],"ennuyeux":["french"],"enrichir":["french"],"enrobage":["french"],"enseigne":["french"],"entasser":["french"],"entendre":["french"],"entier":["french"],"entourer":["french"],"entraver":["french"],"énumérer":["french"],"envahir":["french"],"enviable":["french"],"envoyer":["french"],"enzyme":["french"],"éolien":["french"],"épaissir":["french"],"épargne":["french"],"épatant":["french"],"épaule":["french"],"épicerie":["french"],"épidémie":["french"],"épier":["french"],"épilogue":["french"],"épine":["french"],"épisode":["french"],"épitaphe":["french"],"époque":["french"],"épreuve":["french"],"éprouver":["french"],"épuisant":["french"],"équerre":["french"],"équipe":["french"],"ériger":["french"],"érosion":["french"],"erreur":["french"],"éruption":["french"],"escalier":["french"],"espadon":["french"],"espèce":["french"],"espiègle":["french"],"espoir":["french"],"esprit":["french"],"esquiver":["french"],"essayer":["french"],"essieu":["french"],"essorer":["french"],"estime":["french"],"estomac":["french"],"estrade":["french"],"étagère":["french"],"étaler":["french"],"étanche":["french"],"étatique":["french"],"éteindre":["french"],"étendoir":["french"],"éternel":["french"],"éthanol":["french"],"éthique":["french"],"ethnie":["french"],"étirer":["french"],"étoffer":["french"],"étoile":["french"],"étonnant":["french"],"étourdir":["french"],"étrange":["french"],"étroit":["french"],"étude":["french"],"euphorie":["french"],"évaluer":["french"],"évasion":["french"],"éventail":["french"],"évidence":["french"],"éviter":["french"],"évolutif":["french"],"évoquer":["french"],"exagérer":["french"],"exaucer":["french"],"exceller":["french"],"excitant":["french"],"exclusif":["french"],"exécuter":["french"],"exemple":["french"],"exercer":["french"],"exhaler":["french"],"exhorter":["french"],"exigence":["french"],"exiler":["french"],"exister":["french"],"exotique":["french"],"expédier":["french"],"explorer":["french"],"exposer":["french"],"exprimer":["french"],"exquis":["french"],"extensif":["french"],"extraire":["french"],"exulter":["french"],"fable":["french"],"fabuleux":["french"],"facette":["french"],"facile":["french"],"facture":["french"],"faiblir":["french"],"falaise":["french"],"fameux":["french"],"famille":["french"],"farceur":["french"],"farfelu":["french"],"farine":["french"],"farouche":["french"],"fasciner":["french"],"faucon":["french"],"fautif":["french"],"faveur":["french"],"favori":["french","turkish"],"fébrile":["french"],"féconder":["french"],"fédérer":["french"],"félin":["french"],"femme":["french"],"fémur":["french"],"fendoir":["french"],"féodal":["french"],"fermer":["french"],"féroce":["french"],"ferveur":["french"],"feuille":["french"],"feutre":["french"],"février":["french"],"fiasco":["french"],"ficeler":["french"],"fictif":["french"],"fidèle":["french"],"filature":["french"],"filetage":["french"],"filière":["french"],"filleul":["french"],"filmer":["french"],"filou":["french"],"filtrer":["french"],"financer":["french"],"finir":["french"],"fiole":["french"],"firme":["french"],"fissure":["french"],"fixer":["french"],"flairer":["french"],"flamme":["french"],"flasque":["french"],"flatteur":["french"],"fléau":["french"],"flèche":["french"],"fleur":["french"],"flexion":["french"],"flocon":["french"],"flore":["french"],"fluctuer":["french"],"fluide":["french"],"fluvial":["french"],"folie":["french"],"fonderie":["french"],"fongible":["french"],"fontaine":["french"],"forcer":["french"],"forgeron":["french"],"formuler":["french"],"fossile":["french"],"foudre":["french"],"fougère":["french"],"fouiller":["french"],"foulure":["french"],"fourmi":["french"],"fraise":["french"],"franchir":["french"],"frapper":["french"],"frayeur":["french"],"frégate":["french"],"freiner":["french"],"frelon":["french"],"frémir":["french"],"frénésie":["french"],"frère":["french"],"friable":["french"],"friction":["french"],"frisson":["french"],"frivole":["french"],"froid":["french"],"fromage":["french"],"frontal":["french"],"frotter":["french"],"fugitif":["french"],"fuite":["french"],"fureur":["french"],"furieux":["french"],"furtif":["french"],"fusion":["french"],"futur":["french"],"gagner":["french"],"galaxie":["french"],"galerie":["french"],"gambader":["french"],"garantir":["french"],"gardien":["french"],"garnir":["french"],"garrigue":["french"],"gazelle":["french"],"gazon":["french"],"géant":["french"],"gélatine":["french"],"gélule":["french"],"gendarme":["french"],"général":["french"],"génie":["french"],"genou":["french"],"gentil":["french"],"géologie":["french"],"géomètre":["french"],"géranium":["french"],"germe":["french"],"gestuel":["french"],"geyser":["french"],"gibier":["french"],"gicler":["french"],"girafe":["french"],"givre":["french"],"glace":["french"],"glaive":["french"],"glisser":["french"],"gloire":["french"],"glorieux":["french"],"golfeur":["french"],"gomme":["french"],"gonfler":["french"],"gorge":["french"],"gorille":["french"],"goudron":["french"],"gouffre":["french"],"goulot":["french"],"goupille":["french"],"gourmand":["french"],"goutte":["french"],"graduel":["french"],"graffiti":["french"],"graine":["french"],"grand":["french"],"grappin":["french"],"gratuit":["french"],"gravir":["french"],"grenat":["french"],"griffure":["french"],"griller":["french"],"grimper":["french"],"grogner":["french"],"gronder":["french"],"grotte":["french"],"groupe":["french"],"gruger":["french"],"grutier":["french"],"gruyère":["french"],"guépard":["french"],"guerrier":["french"],"guimauve":["french"],"guitare":["french"],"gustatif":["french"],"gymnaste":["french"],"gyrostat":["french"],"habitude":["french"],"hachoir":["french"],"halte":["french"],"hameau":["french"],"hangar":["french","turkish"],"hanneton":["french"],"haricot":["french"],"harmonie":["french"],"harpon":["french"],"hasard":["french"],"hélium":["french"],"hématome":["french"],"herbe":["french"],"hérisson":["french"],"hermine":["french"],"héron":["french"],"hésiter":["french"],"heureux":["french"],"hiberner":["french"],"hibou":["french"],"hilarant":["french"],"histoire":["french"],"hiver":["french"],"homard":["french"],"hommage":["french"],"homogène":["french"],"honneur":["french"],"honorer":["french"],"honteux":["french"],"horde":["french"],"horizon":["french"],"horloge":["french"],"hormone":["french"],"horrible":["french"],"houleux":["french"],"housse":["french"],"hublot":["french"],"huileux":["french"],"humain":["french"],"humide":["french"],"humour":["french"],"hurler":["french"],"hydromel":["french"],"hygiène":["french"],"hymne":["french"],"hypnose":["french"],"idylle":["french"],"ignorer":["french"],"iguane":["french"],"illicite":["french"],"illusion":["french"],"imbiber":["french"],"imiter":["french"],"immobile":["french"],"immuable":["french"],"impérial":["french"],"implorer":["french"],"imposer":["french"],"imprimer":["french"],"imputer":["french"],"incarner":["french"],"incendie":["french"],"incident":["french"],"incliner":["french"],"incolore":["french"],"indexer":["french"],"indice":["french"],"inductif":["french"],"inédit":["french"],"ineptie":["french"],"inexact":["french"],"infini":["french"],"infliger":["french"],"informer":["french"],"infusion":["french"],"ingérer":["french"],"inhaler":["french"],"inhiber":["french"],"injecter":["french"],"injure":["french"],"inoculer":["french"],"inonder":["french"],"inscrire":["french"],"insecte":["french"],"insigne":["french"],"insolite":["french"],"inspirer":["french"],"instinct":["french"],"insulter":["french"],"intense":["french"],"intime":["french"],"intrigue":["french"],"intuitif":["french"],"inutile":["french"],"invasion":["french"],"inventer":["french"],"inviter":["french"],"invoquer":["french"],"ironique":["french"],"irradier":["french"],"irréel":["french"],"irriter":["french"],"isoler":["french"],"ivoire":["french"],"ivresse":["french"],"jaillir":["french"],"jambe":["french"],"janvier":["french"],"jardin":["french"],"jauger":["french"],"jaune":["french"],"javelot":["french"],"jetable":["french"],"jeton":["french"],"jeudi":["french"],"jeunesse":["french"],"joindre":["french"],"joncher":["french"],"jongler":["french"],"joueur":["french"],"jouissif":["french"],"journal":["french"],"jovial":["french"],"joyau":["french"],"joyeux":["french"],"jubiler":["french"],"jugement":["french"],"jupon":["french"],"juriste":["french"],"justice":["french"],"juteux":["french"],"juvénile":["french"],"kayak":["french"],"kimono":["french"],"kiosque":["french"],"labial":["french"],"labourer":["french"],"lacérer":["french"],"lactose":["french"],"lagune":["french"],"laine":["french"],"laisser":["french"],"laitier":["french"],"lambeau":["french"],"lamelle":["french"],"lampe":["french"],"lanceur":["french"],"langage":["french"],"lanterne":["french"],"lapin":["french"],"largeur":["french"],"larme":["french"],"laurier":["french"],"lavabo":["french"],"lavoir":["french"],"légal":["french"],"léger":["french"],"légume":["french"],"lessive":["french"],"lettre":["french"],"levier":["french"],"lexique":["french"],"lézard":["french"],"liasse":["french"],"libérer":["french"],"libre":["french"],"licence":["french"],"licorne":["french"],"liège":["french"],"lièvre":["french"],"ligature":["french"],"ligoter":["french"],"ligue":["french"],"limer":["french"],"limite":["french"],"limonade":["french"],"limpide":["french"],"linéaire":["french"],"lingot":["french"],"lionceau":["french"],"liquide":["french"],"lisière":["french"],"lister":["french"],"lithium":["french"],"litige":["french"],"littoral":["french"],"livreur":["french"],"logique":["french"],"lointain":["french"],"loisir":["french"],"lombric":["french"],"loterie":["french"],"louer":["french"],"lourd":["french"],"loutre":["french"],"louve":["french"],"lubie":["french"],"lucide":["french"],"lucratif":["french"],"lueur":["french"],"lugubre":["french"],"luisant":["french"],"lumière":["french"],"lunaire":["french"],"lundi":["french"],"luron":["french"],"lutter":["french"],"luxueux":["french"],"magasin":["french"],"magenta":["french"],"magique":["french"],"maigre":["french"],"maillon":["french"],"maintien":["french"],"mairie":["french"],"maison":["french"],"majorer":["french"],"malaxer":["french"],"maléfice":["french"],"malheur":["french"],"malice":["french"],"mallette":["french"],"mammouth":["french"],"mandater":["french"],"maniable":["french"],"manquant":["french"],"manteau":["french"],"manuel":["french"],"marathon":["french"],"marbre":["french"],"marchand":["french"],"mardi":["french"],"maritime":["french"],"marqueur":["french"],"marron":["french"],"marteler":["french"],"mascotte":["french"],"massif":["french"],"matériel":["french"],"matière":["french"],"matraque":["french"],"maudire":["french"],"maussade":["french"],"mauve":["french"],"maximal":["french"],"méchant":["french"],"méconnu":["french"],"médaille":["french"],"médecin":["french"],"méditer":["french"],"méduse":["french"],"meilleur":["french"],"mélange":["french"],"mélodie":["french"],"membre":["french"],"mémoire":["french"],"menacer":["french"],"mener":["french"],"menhir":["french"],"mensonge":["french"],"mentor":["french"],"mercredi":["french"],"mérite":["french"],"merle":["french"],"messager":["french"],"mesure":["french"],"métal":["french"],"météore":["french"],"méthode":["french"],"métier":["french"],"meuble":["french"],"miauler":["french"],"microbe":["french"],"miette":["french"],"mignon":["french"],"migrer":["french"],"milieu":["french"],"mimique":["french"],"mince":["french"],"minéral":["french"],"minimal":["french"],"minorer":["french"],"miroiter":["french"],"missile":["french"],"mixte":["french"],"moderne":["french"],"moelleux":["french"],"mondial":["french"],"moniteur":["french"],"monnaie":["french"],"monotone":["french"],"monstre":["french"],"montagne":["french"],"monument":["french"],"moqueur":["french"],"morceau":["french"],"morsure":["french"],"mortier":["french"],"moteur":["french"],"motif":["french"],"mouche":["french"],"moufle":["french"],"moulin":["french"],"mousson":["french"],"mouton":["french"],"mouvant":["french"],"multiple":["french"],"munition":["french"],"muraille":["french"],"murène":["french"],"murmure":["french"],"muséum":["french"],"musicien":["french"],"mutation":["french"],"muter":["french"],"mutuel":["french"],"myriade":["french"],"myrtille":["french"],"mystère":["french"],"mythique":["french"],"nageur":["french"],"nappe":["french"],"narquois":["french"],"narrer":["french"],"natation":["french"],"naufrage":["french"],"nautique":["french"],"navire":["french"],"nébuleux":["french"],"nectar":["french"],"néfaste":["french"],"négation":["french"],"négliger":["french"],"négocier":["french"],"neige":["french"],"nerveux":["french"],"nettoyer":["french"],"neurone":["french"],"neutron":["french"],"neveu":["french"],"niche":["french"],"nickel":["french"],"nitrate":["french"],"niveau":["french"],"nocif":["french"],"nocturne":["french"],"noirceur":["french"],"noisette":["french"],"nomade":["french"],"nombreux":["french"],"nommer":["french"],"normatif":["french"],"notifier":["french"],"notoire":["french"],"nourrir":["french"],"nouveau":["french"],"novateur":["french"],"novembre":["french"],"novice":["french"],"nuage":["french"],"nuancer":["french"],"nuire":["french"],"nuisible":["french"],"numéro":["french"],"nuptial":["french"],"nuque":["french"],"nutritif":["french"],"obéir":["french"],"objectif":["french"],"obliger":["french"],"obscur":["french"],"observer":["french"],"obstacle":["french"],"obtenir":["french"],"obturer":["french"],"occasion":["french"],"occuper":["french"],"océan":["french"],"octobre":["french"],"octroyer":["french"],"octupler":["french"],"oculaire":["french"],"odeur":["french"],"odorant":["french"],"offenser":["french"],"officier":["french"],"offrir":["french"],"ogive":["french"],"oiseau":["french"],"oisillon":["french"],"olfactif":["french"],"olivier":["french"],"ombrage":["french"],"omettre":["french"],"onctueux":["french"],"onduler":["french"],"onéreux":["french"],"onirique":["french"],"opale":["french"],"opaque":["french"],"opérer":["french"],"opportun":["french"],"opprimer":["french"],"opter":["french"],"optique":["french"],"orageux":["french"],"orbite":["french"],"ordonner":["french"],"oreille":["french"],"organe":["french"],"orgueil":["french"],"orifice":["french"],"ornement":["french"],"orque":["french"],"ortie":["french"],"osciller":["french"],"osmose":["french"],"ossature":["french"],"otarie":["french"],"ouragan":["french"],"ourson":["french"],"outil":["french"],"outrager":["french"],"ouvrage":["french"],"ovation":["french"],"oxyde":["french"],"oxygène":["french"],"paisible":["french"],"palmarès":["french"],"palourde":["french"],"palper":["french"],"panache":["french"],"pangolin":["french"],"paniquer":["french"],"panneau":["french"],"panorama":["french"],"pantalon":["french"],"papaye":["french"],"papier":["french"],"papoter":["french"],"papyrus":["french"],"paradoxe":["french"],"parcelle":["french"],"paresse":["french"],"parfumer":["french"],"parler":["french"],"parole":["french"],"parrain":["french"],"parsemer":["french"],"partager":["french"],"parure":["french"],"parvenir":["french"],"passion":["french"],"pastèque":["french"],"paternel":["french"],"patience":["french"],"patron":["french","turkish"],"pavillon":["french"],"pavoiser":["french"],"payer":["french"],"paysage":["french"],"peigne":["french"],"peintre":["french"],"pelage":["french"],"pélican":["french"],"pelle":["french"],"pelouse":["french"],"peluche":["french"],"pendule":["french"],"pénétrer":["french"],"pénible":["french"],"pensif":["french"],"pénurie":["french"],"pépite":["french"],"péplum":["french"],"perdrix":["french"],"perforer":["french"],"période":["french"],"permuter":["french"],"perplexe":["french"],"persil":["french"],"perte":["french"],"peser":["french"],"pétale":["french"],"petit":["french"],"pétrir":["french"],"peuple":["french"],"pharaon":["french"],"phobie":["french"],"phoque":["french"],"photon":["french"],"physique":["french"],"pictural":["french"],"pièce":["french"],"pierre":["french"],"pieuvre":["french"],"pilote":["french"],"pinceau":["french"],"pipette":["french"],"piquer":["french"],"pirogue":["french"],"piscine":["french"],"piston":["french"],"pivoter":["french"],"pixel":["french"],"placard":["french"],"plafond":["french"],"plaisir":["french"],"planer":["french"],"plaque":["french"],"plastron":["french"],"plateau":["french"],"pleurer":["french"],"plexus":["french"],"pliage":["french"],"plomb":["french"],"plonger":["french"],"pluie":["french"],"plumage":["french"],"pochette":["french"],"poésie":["french"],"poète":["french"],"pointe":["french"],"poirier":["french"],"poisson":["french"],"poivre":["french"],"polaire":["french"],"policier":["french"],"pollen":["french"],"polygone":["french"],"pommade":["french"],"pompier":["french"],"ponctuel":["french"],"pondérer":["french"],"poney":["french"],"portique":["french"],"posséder":["french"],"posture":["french"],"potager":["french"],"poteau":["french"],"potion":["french"],"pouce":["french"],"poulain":["french"],"poumon":["french"],"pourpre":["french"],"poussin":["french"],"pouvoir":["french"],"prairie":["french"],"pratique":["french"],"précieux":["french"],"prédire":["french"],"préfixe":["french"],"prélude":["french"],"prénom":["french"],"présence":["french"],"prétexte":["french"],"prévoir":["french"],"primitif":["french"],"prince":["french"],"priver":["french"],"problème":["french"],"procéder":["french"],"prodige":["french"],"profond":["french"],"progrès":["french"],"proie":["french"],"projeter":["french"],"prologue":["french"],"promener":["french"],"propre":["french"],"prospère":["french"],"protéger":["french"],"prouesse":["french"],"proverbe":["french"],"prudence":["french"],"pruneau":["french"],"psychose":["french"],"puceron":["french"],"puiser":["french"],"pulpe":["french"],"pulsar":["french"],"punaise":["french"],"punitif":["french"],"pupitre":["french"],"purifier":["french"],"pyramide":["french"],"quasar":["french"],"querelle":["french"],"quiétude":["french"],"quitter":["french"],"quotient":["french"],"racine":["french"],"raconter":["french"],"radieux":["french"],"ragondin":["french"],"raideur":["french"],"raisin":["french"],"ralentir":["french"],"rallonge":["french"],"ramasser":["french"],"rapide":["french"],"rasage":["french"],"ratisser":["french"],"ravager":["french"],"ravin":["french"],"rayonner":["french"],"réactif":["french"],"réagir":["french"],"réaliser":["french"],"réanimer":["french"],"recevoir":["french"],"réciter":["french"],"réclamer":["french"],"récolter":["french"],"recruter":["french"],"reculer":["french"],"recycler":["french"],"rédiger":["french"],"redouter":["french"],"refaire":["french"],"réflexe":["french"],"réformer":["french"],"refrain":["french"],"refuge":["french"],"régalien":["french"],"région":["french"],"réglage":["french"],"régulier":["french"],"réitérer":["french"],"rejeter":["french"],"rejouer":["french"],"relatif":["french"],"relever":["french"],"remarque":["french"],"remède":["french"],"remise":["french"],"remonter":["french"],"remplir":["french"],"remuer":["french"],"renard":["french"],"renfort":["french"],"renifler":["french"],"renoncer":["french"],"rentrer":["french"],"renvoi":["french"],"replier":["french"],"reporter":["french"],"reprise":["french"],"reptile":["french"],"requin":["french"],"réserve":["french"],"résineux":["french"],"résoudre":["french"],"respect":["french"],"rester":["french"],"résultat":["french"],"rétablir":["french"],"retenir":["french"],"réticule":["french"],"retomber":["french"],"retracer":["french"],"réunion":["french"],"réussir":["french"],"revanche":["french"],"revivre":["french"],"révolte":["french"],"révulsif":["french"],"richesse":["french"],"rideau":["french"],"rieur":["french"],"rigide":["french"],"rigoler":["french"],"rincer":["french"],"riposter":["french"],"risible":["french"],"risque":["french"],"rituel":["french"],"rivière":["french"],"rocheux":["french"],"rompre":["french"],"ronce":["french"],"rondin":["french"],"roseau":["french"],"rosier":["french"],"rotatif":["french"],"rotor":["french"],"rotule":["french"],"rouge":["french"],"rouille":["french"],"rouleau":["french"],"routine":["french"],"royaume":["french"],"ruban":["french"],"rubis":["french"],"ruche":["french"],"ruelle":["french"],"rugueux":["french"],"ruiner":["french"],"ruisseau":["french"],"ruser":["french"],"rustique":["french"],"rythme":["french"],"sabler":["french"],"saboter":["french"],"sabre":["french"],"sacoche":["french"],"safari":["french"],"sagesse":["french"],"saisir":["french"],"salade":["french"],"salive":["french"],"saluer":["french"],"samedi":["french"],"sanction":["french"],"sanglier":["french"],"sarcasme":["french"],"sardine":["french"],"saturer":["french"],"saugrenu":["french"],"saumon":["french"],"sauter":["french"],"sauvage":["french"],"savant":["french"],"savonner":["french"],"scalpel":["french"],"scandale":["french"],"scélérat":["french"],"scénario":["french"],"sceptre":["french"],"schéma":["french"],"scinder":["french"],"score":["french"],"scrutin":["french"],"sculpter":["french"],"séance":["french"],"sécable":["french"],"sécher":["french"],"secouer":["french"],"sécréter":["french"],"sédatif":["french"],"séduire":["french"],"seigneur":["french"],"séjour":["french"],"sélectif":["french"],"semaine":["french"],"sembler":["french"],"semence":["french"],"séminal":["french"],"sénateur":["french"],"sensible":["french"],"séparer":["french"],"séquence":["french"],"serein":["french"],"sergent":["french"],"sérieux":["french"],"serrure":["french"],"sérum":["french"],"sésame":["french"],"sévir":["french"],"sevrage":["french"],"sextuple":["french"],"sidéral":["french"],"siècle":["french"],"siéger":["french"],"siffler":["french"],"sigle":["french"],"signal":["french"],"silence":["french"],"silicium":["french"],"sincère":["french"],"sinistre":["french"],"siphon":["french"],"sirop":["french"],"sismique":["french"],"situer":["french"],"skier":["french"],"socle":["french"],"sodium":["french"],"soigneux":["french"],"soldat":["french"],"soleil":["french"],"solitude":["french"],"soluble":["french"],"sombre":["french"],"sommeil":["french"],"somnoler":["french"],"sonde":["french"],"songeur":["french"],"sonnette":["french"],"sonore":["french"],"sorcier":["french"],"sortir":["french"],"sosie":["french"],"sottise":["french"],"soucieux":["french"],"soudure":["french"],"souffle":["french"],"soulever":["french"],"soupape":["french"],"soutirer":["french"],"souvenir":["french"],"spacieux":["french"],"spécial":["french"],"sphère":["french"],"spiral":["french","turkish"],"station":["french"],"sternum":["french"],"stimulus":["french"],"stipuler":["french"],"strict":["french"],"studieux":["french"],"stupeur":["french"],"styliste":["french"],"sublime":["french"],"substrat":["french"],"subtil":["french"],"subvenir":["french"],"succès":["french"],"sucre":["french"],"suffixe":["french"],"suggérer":["french"],"suiveur":["french"],"sulfate":["french"],"superbe":["french"],"supplier":["french"],"suricate":["french"],"surmener":["french"],"sursaut":["french"],"survie":["french"],"syllabe":["french"],"symbole":["french"],"symétrie":["french"],"synapse":["french"],"syntaxe":["french"],"système":["french"],"tabac":["french"],"tablier":["french"],"tactile":["french"],"tailler":["french"],"talisman":["french"],"talonner":["french"],"tambour":["french"],"tamiser":["french"],"tangible":["french"],"tapis":["french"],"taquiner":["french"],"tarder":["french"],"tarif":["french"],"tartine":["french"],"tasse":["french"],"tatami":["french"],"tatouage":["french"],"taupe":["french"],"taureau":["french"],"taxer":["french"],"témoin":["french"],"temporel":["french"],"tenaille":["french"],"tendre":["french"],"teneur":["french"],"tenir":["french"],"tension":["french"],"terminer":["french"],"terne":["french"],"terrible":["french"],"tétine":["french"],"texte":["french"],"thème":["french"],"théorie":["french"],"thérapie":["french"],"thorax":["french"],"tibia":["french"],"tiède":["french"],"timide":["french"],"tirelire":["french"],"tiroir":["french"],"tissu":["french"],"titane":["french"],"titre":["french"],"tituber":["french"],"toboggan":["french"],"tolérant":["french"],"tomate":["french"],"tonique":["french"],"tonneau":["french"],"toponyme":["french"],"torche":["french"],"tordre":["french"],"tornade":["french"],"torpille":["french"],"torrent":["french"],"torse":["french"],"tortue":["french"],"totem":["french"],"toucher":["french"],"tournage":["french"],"tousser":["french"],"toxine":["french"],"traction":["french"],"trafic":["french"],"tragique":["french"],"trahir":["french"],"trancher":["french"],"travail":["french"],"trèfle":["french"],"tremper":["french"],"trésor":["french"],"treuil":["french"],"triage":["french"],"tribunal":["french"],"tricoter":["french"],"trilogie":["french"],"triomphe":["french"],"tripler":["french"],"triturer":["french"],"trivial":["french"],"trombone":["french"],"tronc":["french"],"tropical":["french"],"troupeau":["french"],"tuile":["french"],"tulipe":["french"],"tumulte":["french"],"turbine":["french"],"tuteur":["french"],"tutoyer":["french"],"tuyau":["french"],"tympan":["french"],"typhon":["french"],"typique":["french"],"tyran":["french"],"ubuesque":["french"],"ultime":["french"],"ultrason":["french"],"unanime":["french"],"unifier":["french"],"union":["french"],"unitaire":["french"],"univers":["french"],"uranium":["french"],"urbain":["french"],"urticant":["french"],"usine":["french"],"usuel":["french"],"usure":["french"],"utile":["french"],"utopie":["french"],"vacarme":["french"],"vaccin":["french"],"vagabond":["french"],"vaillant":["french"],"vaincre":["french"],"vaisseau":["french"],"valable":["french"],"valise":["french"],"vallon":["french"],"vampire":["french"],"vanille":["french"],"vapeur":["french"],"varier":["french"],"vaseux":["french"],"vassal":["french"],"vaste":["french"],"vecteur":["french"],"vedette":["french"],"végétal":["french"],"véhicule":["french"],"veinard":["french"],"véloce":["french"],"vendredi":["french"],"vénérer":["french"],"venger":["french"],"venimeux":["french"],"ventouse":["french"],"verdure":["french"],"vérin":["french"],"vernir":["french"],"verrou":["french"],"verser":["french"],"vertu":["french"],"veston":["french"],"vétéran":["french"],"vétuste":["french"],"vexant":["french"],"vexer":["french"],"viaduc":["french"],"viande":["french"],"victoire":["french"],"vidange":["french"],"vidéo":["french"],"vignette":["french"],"vigueur":["french"],"vilain":["french"],"vinaigre":["french"],"violon":["french"],"vipère":["french"],"virement":["french"],"virtuose":["french"],"visage":["french"],"viseur":["french"],"vision":["french"],"visqueux":["french"],"visuel":["french"],"vitesse":["french"],"viticole":["french"],"vitrine":["french"],"vivace":["french"],"vivipare":["french"],"vocation":["french"],"voguer":["french"],"voile":["french"],"voisin":["french"],"voiture":["french"],"volaille":["french"],"volcan":["french"],"voltiger":["french"],"vorace":["french"],"vortex":["french"],"voter":["french"],"vouloir":["french"],"voyelle":["french"],"xénon":["french"],"yacht":["french"],"zèbre":["french"],"zénith":["french"],"zeste":["french"],"zoologie":["french"],"abaco":["italian"],"abbaglio":["italian"],"abbinato":["italian"],"abete":["italian"],"abisso":["italian"],"abolire":["italian"],"abrasivo":["italian"],"abrogato":["italian"],"accadere":["italian"],"accenno":["italian"],"accusato":["italian"],"acetone":["italian"],"achille":["italian"],"acido":["italian"],"acqua":["italian"],"acre":["italian"],"acrilico":["italian"],"acrobata":["italian"],"acuto":["italian"],"adagio":["italian"],"addebito":["italian"],"addome":["italian"],"adeguato":["italian"],"aderire":["italian"],"adipe":["italian"],"adottare":["italian"],"adulare":["italian"],"affabile":["italian"],"affetto":["italian"],"affisso":["italian"],"affranto":["italian"],"aforisma":["italian"],"afoso":["italian"],"africano":["italian"],"agave":["italian"],"agente":["italian"],"agevole":["italian"],"aggancio":["italian"],"agire":["italian"],"agitare":["italian"],"agonismo":["italian"],"agricolo":["italian"],"agrumeto":["italian"],"aguzzo":["italian"],"alabarda":["italian"],"alato":["italian"],"albatro":["italian"],"alberato":["italian"],"albo":["italian"],"albume":["italian"],"alce":["italian"],"alcolico":["italian"],"alettone":["italian"],"alfa":["italian"],"algebra":["italian"],"aliante":["italian"],"alibi":["italian"],"alimento":["italian"],"allagato":["italian"],"allegro":["italian"],"allievo":["italian"],"allodola":["italian"],"allusivo":["italian"],"almeno":["italian"],"alogeno":["italian"],"alpaca":["italian"],"alpestre":["italian"],"altalena":["italian"],"alterno":["italian"],"alticcio":["italian"],"altrove":["italian"],"alunno":["italian"],"alveolo":["italian"],"alzare":["italian"],"amalgama":["italian"],"amanita":["italian"],"amarena":["italian"],"ambito":["italian"],"ambrato":["italian"],"ameba":["italian"],"america":["italian"],"ametista":["italian"],"amico":["italian"],"ammasso":["italian"],"ammenda":["italian"],"ammirare":["italian"],"ammonito":["italian"],"amore":["italian"],"ampio":["italian"],"ampliare":["italian"],"amuleto":["italian"],"anacardo":["italian"],"anagrafe":["italian"],"analista":["italian"],"anarchia":["italian"],"anatra":["italian"],"anca":["italian"],"ancella":["italian"],"ancora":["italian"],"andare":["italian"],"andrea":["italian"],"anello":["italian"],"angelo":["italian"],"angolare":["italian"],"angusto":["italian"],"anima":["italian"],"annegare":["italian"],"annidato":["italian"],"anno":["italian"],"annuncio":["italian"],"anonimo":["italian"],"anticipo":["italian"],"anzi":["italian"],"apatico":["italian"],"apertura":["italian"],"apode":["italian"],"apparire":["italian"],"appetito":["italian"],"appoggio":["italian"],"approdo":["italian"],"appunto":["italian"],"aprile":["italian"],"arabica":["italian"],"arachide":["italian"],"aragosta":["italian"],"araldica":["italian"],"arancio":["italian"],"aratura":["italian"],"arazzo":["italian"],"arbitro":["italian"],"archivio":["italian"],"ardito":["italian"],"arenile":["italian"],"argento":["italian"],"argine":["italian"],"arguto":["italian"],"aria":["italian"],"armonia":["italian"],"arnese":["italian"],"arredato":["italian"],"arringa":["italian"],"arrosto":["italian"],"arsenico":["italian"],"arso":["italian"],"artefice":["italian"],"arzillo":["italian"],"asciutto":["italian"],"ascolto":["italian"],"asepsi":["italian"],"asettico":["italian"],"asfalto":["italian"],"asino":["italian"],"asola":["italian"],"aspirato":["italian"],"aspro":["italian"],"assaggio":["italian"],"asse":["italian"],"assoluto":["italian"],"assurdo":["italian"],"asta":["italian"],"astenuto":["italian"],"astice":["italian"],"astratto":["italian"],"atavico":["italian"],"ateismo":["italian"],"atomico":["italian"],"atono":["italian"],"attesa":["italian"],"attivare":["italian"],"attorno":["italian"],"attrito":["italian"],"attuale":["italian"],"ausilio":["italian"],"austria":["italian"],"autista":["italian"],"autonomo":["italian"],"autunno":["italian"],"avanzato":["italian"],"avere":["italian"],"avvenire":["italian"],"avviso":["italian"],"avvolgere":["italian"],"azione":["italian"],"azoto":["italian"],"azzimo":["italian"],"azzurro":["italian"],"babele":["italian"],"baccano":["italian"],"bacino":["italian"],"baco":["italian"],"badessa":["italian"],"badilata":["italian"],"bagnato":["italian"],"baita":["italian"],"balcone":["italian"],"baldo":["italian"],"balena":["italian"],"ballata":["italian"],"balzano":["italian"],"bambino":["italian"],"bandire":["italian"],"baraonda":["italian"],"barbaro":["italian"],"barca":["italian"],"baritono":["italian"],"barlume":["italian"],"barocco":["italian"],"basilico":["italian"],"basso":["italian"],"batosta":["italian"],"battuto":["italian"],"baule":["italian"],"bava":["italian"],"bavosa":["italian"],"becco":["italian"],"beffa":["italian"],"belgio":["italian"],"belva":["italian"],"benda":["italian"],"benevole":["italian"],"benigno":["italian"],"benzina":["italian"],"bere":["italian"],"berlina":["italian"],"beta":["italian"],"bibita":["italian"],"bici":["italian"],"bidone":["italian"],"bifido":["italian"],"biga":["italian"],"bilancia":["italian"],"bimbo":["italian"],"binocolo":["italian"],"biologo":["italian"],"bipede":["italian"],"bipolare":["italian"],"birbante":["italian"],"birra":["italian"],"biscotto":["italian"],"bisesto":["italian"],"bisnonno":["italian"],"bisonte":["italian"],"bisturi":["italian"],"bizzarro":["italian"],"blando":["italian"],"blatta":["italian"],"bollito":["italian"],"bonifico":["italian"],"bordo":["italian"],"bosco":["italian"],"botanico":["italian"],"bottino":["italian"],"bozzolo":["italian"],"braccio":["italian"],"bradipo":["italian"],"brama":["italian"],"branca":["italian"],"bravura":["italian"],"bretella":["italian"],"brevetto":["italian"],"brezza":["italian"],"briglia":["italian"],"brillante":["italian"],"brindare":["italian"],"broccolo":["italian"],"brodo":["italian"],"bronzina":["italian"],"brullo":["italian"],"bruno":["italian"],"bubbone":["italian"],"buca":["italian"],"budino":["italian"],"buffone":["italian"],"buio":["italian"],"bulbo":["italian"],"buono":["italian"],"burlone":["italian"],"burrasca":["italian"],"bussola":["italian"],"busta":["italian"],"cadetto":["italian"],"caduco":["italian"],"calamaro":["italian"],"calcolo":["italian"],"calesse":["italian"],"calibro":["italian"],"calmo":["italian"],"caloria":["italian"],"cambusa":["italian"],"camerata":["italian"],"camicia":["italian"],"cammino":["italian"],"camola":["italian"],"campale":["italian"],"canapa":["italian"],"candela":["italian"],"cane":["italian"],"canino":["italian"],"canotto":["italian"],"cantina":["italian"],"capace":["italian"],"capello":["italian"],"capitolo":["italian"],"capogiro":["italian"],"cappero":["italian"],"capra":["italian"],"capsula":["italian"],"carapace":["italian"],"carcassa":["italian"],"cardo":["italian"],"carisma":["italian"],"carovana":["italian"],"carretto":["italian"],"cartolina":["italian"],"casaccio":["italian"],"cascata":["italian"],"caserma":["italian"],"caso":["italian"],"cassone":["italian"],"castello":["italian"],"casuale":["italian"],"catasta":["italian"],"catena":["italian"],"catrame":["italian"],"cauto":["italian"],"cavillo":["italian"],"cedibile":["italian"],"cedrata":["italian"],"cefalo":["italian"],"celebre":["italian"],"cellulare":["italian"],"cena":["italian"],"cenone":["italian"],"centesimo":["italian"],"ceramica":["italian"],"cercare":["italian"],"certo":["italian"],"cerume":["italian"],"cervello":["italian"],"cesoia":["italian"],"cespo":["italian"],"ceto":["italian"],"chela":["italian"],"chiaro":["italian"],"chicca":["italian"],"chiedere":["italian"],"chimera":["italian"],"china":["italian"],"chirurgo":["italian"],"chitarra":["italian"],"ciao":["italian"],"ciclismo":["italian"],"cifrare":["italian"],"cigno":["italian"],"cilindro":["italian"],"ciottolo":["italian"],"circa":["italian"],"cirrosi":["italian"],"citrico":["italian"],"cittadino":["italian"],"ciuffo":["italian"],"civetta":["italian"],"civile":["italian"],"classico":["italian"],"clinica":["italian"],"cloro":["italian"],"cocco":["italian"],"codardo":["italian"],"codice":["italian"],"coerente":["italian"],"cognome":["italian"],"collare":["italian"],"colmato":["italian"],"colore":["italian"],"colposo":["italian"],"coltivato":["italian"],"colza":["italian"],"coma":["italian"],"cometa":["italian"],"commando":["italian"],"comodo":["italian"],"computer":["italian"],"comune":["italian"],"conciso":["italian"],"condurre":["italian"],"conferma":["italian"],"congelare":["italian"],"coniuge":["italian"],"connesso":["italian"],"conoscere":["italian"],"consumo":["italian"],"continuo":["italian"],"convegno":["italian"],"coperto":["italian"],"copione":["italian"],"coppia":["italian"],"copricapo":["italian"],"corazza":["italian"],"cordata":["italian"],"coricato":["italian"],"cornice":["italian"],"corolla":["italian"],"corpo":["italian"],"corredo":["italian"],"corsia":["italian"],"cortese":["italian"],"cosmico":["italian"],"costante":["italian"],"cottura":["italian"],"covato":["italian"],"cratere":["italian"],"cravatta":["italian"],"creato":["italian"],"credere":["italian"],"cremoso":["italian"],"crescita":["italian"],"creta":["italian"],"criceto":["italian"],"crinale":["italian"],"crisi":["italian"],"critico":["italian"],"croce":["italian"],"cronaca":["italian"],"crostata":["italian"],"cruciale":["italian"],"crusca":["italian"],"cucire":["italian"],"cuculo":["italian"],"cugino":["italian"],"cullato":["italian"],"cupola":["italian"],"curatore":["italian"],"cursore":["italian"],"curvo":["italian"],"cuscino":["italian"],"custode":["italian"],"dado":["italian"],"daino":["italian"],"dalmata":["italian"],"damerino":["italian"],"daniela":["italian"],"dannoso":["italian"],"danzare":["italian"],"datato":["italian"],"davanti":["italian"],"davvero":["italian"],"debutto":["italian"],"decennio":["italian"],"deciso":["italian"],"declino":["italian"],"decollo":["italian"],"decreto":["italian"],"dedicato":["italian"],"definito":["italian"],"deforme":["italian"],"degno":["italian"],"delegare":["italian"],"delfino":["italian"],"delirio":["italian"],"delta":["italian"],"demenza":["italian"],"denotato":["italian"],"dentro":["italian"],"deposito":["italian"],"derapata":["italian"],"derivare":["italian"],"deroga":["italian"],"descritto":["italian"],"deserto":["italian"],"desiderio":["italian"],"desumere":["italian"],"detersivo":["italian"],"devoto":["italian"],"diametro":["italian"],"dicembre":["italian"],"diedro":["italian"],"difeso":["italian"],"diffuso":["italian"],"digerire":["italian"],"digitale":["italian"],"diluvio":["italian"],"dinamico":["italian"],"dinnanzi":["italian"],"dipinto":["italian"],"diploma":["italian"],"dipolo":["italian"],"diradare":["italian"],"dire":["italian"],"dirotto":["italian"],"dirupo":["italian"],"disagio":["italian"],"discreto":["italian"],"disfare":["italian"],"disgelo":["italian"],"disposto":["italian"],"distanza":["italian"],"disumano":["italian"],"dito":["italian"],"divano":["italian"],"divelto":["italian"],"dividere":["italian"],"divorato":["italian"],"doblone":["italian"],"docente":["italian"],"doganale":["italian"],"dogma":["italian"],"dolce":["italian"],"domato":["italian"],"domenica":["italian"],"dominare":["italian"],"dondolo":["italian"],"dono":["italian"],"dormire":["italian"],"dote":["italian"],"dottore":["italian"],"dovuto":["italian"],"dozzina":["italian"],"drago":["italian"],"druido":["italian"],"dubbio":["italian"],"dubitare":["italian"],"ducale":["italian"],"duna":["italian"],"duomo":["italian"],"duplice":["italian"],"duraturo":["italian"],"ebano":["italian"],"eccesso":["italian"],"ecco":["italian"],"eclissi":["italian"],"economia":["italian"],"edera":["italian"],"edicola":["italian"],"edile":["italian"],"editoria":["italian"],"educare":["italian"],"egemonia":["italian"],"egli":["italian"],"egoismo":["italian"],"egregio":["italian"],"elaborato":["italian"],"elargire":["italian"],"elegante":["italian"],"elencato":["italian"],"eletto":["italian"],"elevare":["italian"],"elfico":["italian"],"elica":["italian"],"elmo":["italian"],"elsa":["italian"],"eluso":["italian"],"emanato":["italian"],"emblema":["italian"],"emesso":["italian"],"emiro":["italian"],"emotivo":["italian"],"emozione":["italian"],"empirico":["italian"],"emulo":["italian"],"endemico":["italian"],"enduro":["italian"],"energia":["italian"],"enfasi":["italian"],"enoteca":["italian"],"entrare":["italian"],"enzima":["italian"],"epatite":["italian"],"epilogo":["italian"],"episodio":["italian"],"epocale":["italian"],"eppure":["italian"],"equatore":["italian"],"erario":["italian"],"erba":["italian"],"erboso":["italian"],"erede":["italian"],"eremita":["italian"],"erigere":["italian"],"ermetico":["italian"],"eroe":["italian"],"erosivo":["italian"],"errante":["italian"],"esagono":["italian"],"esame":["italian"],"esanime":["italian"],"esaudire":["italian"],"esca":["italian"],"esempio":["italian"],"esercito":["italian"],"esibito":["italian"],"esigente":["italian"],"esistere":["italian"],"esito":["italian"],"esofago":["italian"],"esortato":["italian"],"esoso":["italian"],"espanso":["italian"],"espresso":["italian"],"essenza":["italian"],"esso":["italian"],"esteso":["italian"],"estimare":["italian"],"estonia":["italian"],"estroso":["italian"],"esultare":["italian"],"etilico":["italian"],"etnico":["italian"],"etrusco":["italian"],"etto":["italian"],"euclideo":["italian"],"europa":["italian"],"evaso":["italian"],"evidenza":["italian"],"evitato":["italian"],"evoluto":["italian"],"evviva":["italian"],"fabbrica":["italian"],"faccenda":["italian"],"fachiro":["italian"],"falco":["italian"],"famiglia":["italian"],"fanale":["italian"],"fanfara":["italian"],"fango":["italian"],"fantasma":["italian"],"fare":["italian"],"farfalla":["italian"],"farinoso":["italian"],"farmaco":["italian"],"fascia":["italian"],"fastoso":["italian"],"fasullo":["italian"],"faticare":["italian"],"fato":["italian"],"favoloso":["italian"],"febbre":["italian"],"fecola":["italian"],"fede":["italian"],"fegato":["italian"],"felpa":["italian"],"feltro":["italian"],"femmina":["italian"],"fendere":["italian"],"fenomeno":["italian"],"fermento":["italian"],"ferro":["italian"],"fertile":["italian"],"fessura":["italian"],"festivo":["italian"],"fetta":["italian"],"feudo":["italian"],"fiaba":["italian"],"fiducia":["italian"],"fifa":["italian"],"figurato":["italian"],"filo":["italian","turkish"],"finanza":["italian"],"finestra":["italian"],"finire":["italian"],"fiore":["italian"],"fiscale":["italian"],"fisico":["italian"],"fiume":["italian"],"flacone":["italian"],"flamenco":["italian"],"flebo":["italian"],"flemma":["italian"],"florido":["italian"],"fluente":["italian"],"fluoro":["italian"],"fobico":["italian"],"focaccia":["italian"],"focoso":["italian"],"foderato":["italian"],"foglio":["italian"],"folata":["italian"],"folclore":["italian"],"folgore":["italian"],"fondente":["italian"],"fonetico":["italian"],"fonia":["italian"],"fontana":["italian"],"forbito":["italian"],"forchetta":["italian"],"foresta":["italian"],"formica":["italian"],"fornaio":["italian"],"foro":["italian"],"fortezza":["italian"],"forzare":["italian"],"fosfato":["italian"],"fosso":["italian"],"fracasso":["italian"],"frana":["italian"],"frassino":["italian"],"fratello":["italian"],"freccetta":["italian"],"frenata":["italian"],"fresco":["italian"],"frigo":["italian"],"frollino":["italian"],"fronde":["italian"],"frugale":["italian"],"frutta":["italian"],"fucilata":["italian"],"fucsia":["italian"],"fuggente":["italian"],"fulmine":["italian"],"fulvo":["italian"],"fumante":["italian"],"fumetto":["italian"],"fumoso":["italian"],"fune":["italian"],"funzione":["italian"],"fuoco":["italian"],"furbo":["italian"],"furgone":["italian"],"furore":["italian"],"fuso":["italian"],"futile":["italian"],"gabbiano":["italian"],"gaffe":["italian"],"galateo":["italian"],"gallina":["italian"],"galoppo":["italian"],"gambero":["italian"],"gamma":["italian"],"garanzia":["italian"],"garbo":["italian"],"garofano":["italian"],"garzone":["italian"],"gasdotto":["italian"],"gasolio":["italian"],"gastrico":["italian"],"gatto":["italian"],"gaudio":["italian"],"gazebo":["italian"],"gazzella":["italian"],"geco":["italian"],"gelatina":["italian"],"gelso":["italian"],"gemello":["italian"],"gemmato":["italian"],"gene":["italian"],"genitore":["italian"],"gennaio":["italian"],"genotipo":["italian"],"gergo":["italian"],"ghepardo":["italian"],"ghiaccio":["italian"],"ghisa":["italian"],"giallo":["italian"],"gilda":["italian"],"ginepro":["italian"],"giocare":["italian"],"gioiello":["italian"],"giorno":["italian"],"giove":["italian"],"girato":["italian"],"girone":["italian"],"gittata":["italian"],"giudizio":["italian"],"giurato":["italian"],"giusto":["italian"],"globulo":["italian"],"glutine":["italian"],"gnomo":["italian"],"gobba":["italian"],"golf":["italian"],"gomito":["italian"],"gommone":["italian"],"gonfio":["italian"],"gonna":["italian"],"governo":["italian"],"gracile":["italian"],"grado":["italian"],"grafico":["italian"],"grammo":["italian"],"grande":["italian"],"grattare":["italian"],"gravoso":["italian"],"grazia":["italian"],"greca":["italian"],"gregge":["italian"],"grifone":["italian"],"grigio":["italian"],"grinza":["italian"],"grotta":["italian"],"gruppo":["italian"],"guadagno":["italian"],"guaio":["italian"],"guanto":["italian"],"guardare":["italian"],"gufo":["italian"],"guidare":["italian"],"ibernato":["italian"],"icona":["italian"],"identico":["italian"],"idillio":["italian"],"idolo":["italian"],"idra":["italian"],"idrico":["italian"],"idrogeno":["italian"],"igiene":["italian"],"ignaro":["italian"],"ignorato":["italian"],"ilare":["italian"],"illeso":["italian"],"illogico":["italian"],"illudere":["italian"],"imballo":["italian"],"imbevuto":["italian"],"imbocco":["italian"],"imbuto":["italian"],"immane":["italian"],"immerso":["italian"],"immolato":["italian"],"impacco":["italian"],"impeto":["italian"],"impiego":["italian"],"importo":["italian"],"impronta":["italian"],"inalare":["italian"],"inarcare":["italian"],"inattivo":["italian"],"incanto":["italian"],"incendio":["italian"],"inchino":["italian"],"incisivo":["italian"],"incluso":["italian"],"incontro":["italian"],"incrocio":["italian"],"incubo":["italian"],"indagine":["italian"],"india":["italian"],"indole":["italian"],"inedito":["italian"],"infatti":["italian"],"infilare":["italian"],"inflitto":["italian"],"ingaggio":["italian"],"ingegno":["italian"],"inglese":["italian"],"ingordo":["italian"],"ingrosso":["italian"],"innesco":["italian"],"inodore":["italian"],"inoltrare":["italian"],"inondato":["italian"],"insano":["italian"],"insetto":["italian"],"insieme":["italian"],"insonnia":["italian"],"insulina":["italian"],"intasato":["italian"],"intero":["italian"],"intonaco":["italian"],"intuito":["italian"],"inumidire":["italian"],"invalido":["italian"],"invece":["italian"],"invito":["italian"],"iperbole":["italian"],"ipnotico":["italian"],"ipotesi":["italian"],"ippica":["italian"],"iride":["italian"],"irlanda":["italian"],"ironico":["italian"],"irrigato":["italian"],"irrorare":["italian"],"isolato":["italian"],"isotopo":["italian"],"isterico":["italian"],"istituto":["italian"],"istrice":["italian"],"italia":["italian"],"iterare":["italian"],"labbro":["italian"],"labirinto":["italian"],"lacca":["italian"],"lacerato":["italian"],"lacrima":["italian"],"lacuna":["italian"],"laddove":["italian"],"lago":["italian"],"lampo":["italian"],"lancetta":["italian"],"lanterna":["italian"],"lardoso":["italian"],"larga":["italian"],"laringe":["italian"],"lastra":["italian"],"latenza":["italian"],"latino":["italian"],"lattuga":["italian"],"lavagna":["italian"],"lavoro":["italian"],"legale":["italian"],"leggero":["italian"],"lembo":["italian"],"lentezza":["italian"],"lenza":["italian"],"leone":["italian"],"lepre":["italian"],"lesivo":["italian"],"lessato":["italian"],"lesto":["italian"],"letterale":["italian"],"leva":["italian"],"levigato":["italian"],"libero":["italian"],"lido":["italian"],"lievito":["italian"],"lilla":["italian"],"limatura":["italian"],"limitare":["italian"],"limpido":["italian"],"lineare":["italian"],"lingua":["italian"],"liquido":["italian"],"lira":["italian"],"lirica":["italian"],"lisca":["italian"],"lite":["italian"],"litigio":["italian"],"livrea":["italian"],"locanda":["italian"],"lode":["italian"],"logica":["italian"],"lombare":["italian"],"londra":["italian"],"longevo":["italian"],"loquace":["italian"],"lorenzo":["italian"],"loto":["italian"],"lotteria":["italian"],"luce":["italian"],"lucidato":["italian"],"lumaca":["italian"],"luminoso":["italian"],"lungo":["italian"],"lupo":["italian"],"luppolo":["italian"],"lusinga":["italian"],"lusso":["italian"],"lutto":["italian"],"macabro":["italian"],"macchina":["italian"],"macero":["italian"],"macinato":["italian"],"madama":["italian"],"magico":["italian"],"maglia":["italian"],"magnete":["italian"],"magro":["italian"],"maiolica":["italian"],"malafede":["italian"],"malgrado":["italian"],"malinteso":["italian"],"malsano":["italian"],"malto":["italian"],"malumore":["italian"],"mana":["italian"],"mancia":["italian"],"mandorla":["italian"],"mangiare":["italian"],"manifesto":["italian"],"mannaro":["italian"],"manovra":["italian"],"mansarda":["italian"],"mantide":["italian"],"manubrio":["italian"],"mappa":["italian"],"maratona":["italian"],"marcire":["italian"],"maretta":["italian"],"marmo":["italian"],"marsupio":["italian"],"maschera":["italian"],"massaia":["italian"],"mastino":["italian"],"materasso":["italian"],"matricola":["italian"],"mattone":["italian"],"maturo":["italian"],"mazurca":["italian"],"meandro":["italian"],"meccanico":["italian"],"mecenate":["italian"],"medesimo":["italian"],"meditare":["italian"],"mega":["italian"],"melassa":["italian"],"melis":["italian"],"melodia":["italian"],"meninge":["italian"],"meno":["italian"],"mensola":["italian"],"mercurio":["italian"],"merenda":["italian"],"merlo":["italian"],"meschino":["italian"],"mese":["italian"],"messere":["italian"],"mestolo":["italian"],"metallo":["italian"],"metodo":["italian"],"mettere":["italian"],"miagolare":["italian"],"mica":["italian"],"micelio":["italian"],"michele":["italian"],"microbo":["italian"],"midollo":["italian"],"miele":["italian"],"migliore":["italian"],"milano":["italian"],"milite":["italian"],"mimosa":["italian"],"minerale":["italian"],"mini":["italian"],"minore":["italian"],"mirino":["italian"],"mirtillo":["italian"],"miscela":["italian"],"missiva":["italian"],"misto":["italian"],"misurare":["italian"],"mitezza":["italian"],"mitigare":["italian"],"mitra":["italian"],"mittente":["italian"],"mnemonico":["italian"],"modello":["italian"],"modifica":["italian"],"modulo":["italian"],"mogano":["italian"],"mogio":["italian"],"mole":["italian"],"molosso":["italian"],"monastero":["italian"],"monco":["italian"],"mondina":["italian"],"monetario":["italian"],"monile":["italian"],"monotono":["italian"],"monsone":["italian"],"montato":["italian"],"monviso":["italian"],"mora":["italian"],"mordere":["italian"],"morsicato":["italian"],"mostro":["italian"],"motivato":["italian"],"motosega":["italian"],"motto":["italian"],"movenza":["italian"],"movimento":["italian"],"mozzo":["italian"],"mucca":["italian"],"mucosa":["italian"],"muffa":["italian"],"mughetto":["italian"],"mugnaio":["italian"],"mulatto":["italian"],"mulinello":["italian"],"multiplo":["italian"],"mummia":["italian"],"munto":["italian"],"muovere":["italian"],"murale":["italian"],"musa":["italian"],"muscolo":["italian"],"musica":["italian"],"mutevole":["italian"],"muto":["italian"],"nababbo":["italian"],"nafta":["italian"],"nanometro":["italian"],"narciso":["italian"],"narice":["italian"],"narrato":["italian"],"nascere":["italian"],"nastrare":["italian"],"naturale":["italian"],"nautica":["italian"],"naviglio":["italian"],"nebulosa":["italian"],"necrosi":["italian"],"negativo":["italian"],"negozio":["italian"],"nemmeno":["italian"],"neofita":["italian"],"neretto":["italian"],"nervo":["italian"],"nessuno":["italian"],"nettuno":["italian"],"neutrale":["italian"],"neve":["italian"],"nevrotico":["italian"],"nicchia":["italian"],"ninfa":["italian"],"nitido":["italian"],"nobile":["italian"],"nocivo":["italian"],"nodo":["italian"],"nome":["italian"],"nomina":["italian"],"nordico":["italian"],"normale":["italian"],"norvegese":["italian"],"nostrano":["italian"],"notare":["italian"],"notizia":["italian"],"notturno":["italian"],"novella":["italian"],"nucleo":["italian"],"nulla":["italian"],"numero":["italian"],"nuovo":["italian"],"nutrire":["italian"],"nuvola":["italian"],"nuziale":["italian"],"oasi":["italian"],"obbedire":["italian"],"obbligo":["italian"],"obelisco":["italian"],"oblio":["italian"],"obolo":["italian"],"obsoleto":["italian"],"occasione":["italian"],"occhio":["italian"],"occidente":["italian"],"occorrere":["italian"],"occultare":["italian"],"ocra":["italian"],"oculato":["italian"],"odierno":["italian"],"odorare":["italian"],"offerta":["italian"],"offrire":["italian"],"offuscato":["italian"],"oggetto":["italian"],"oggi":["italian"],"ognuno":["italian"],"olandese":["italian"],"olfatto":["italian"],"oliato":["italian"],"oliva":["italian"],"ologramma":["italian"],"oltre":["italian"],"omaggio":["italian"],"ombelico":["italian"],"ombra":["italian"],"omega":["italian"],"omissione":["italian"],"ondoso":["italian"],"onere":["italian"],"onice":["italian"],"onnivoro":["italian"],"onorevole":["italian"],"onta":["italian"],"operato":["italian"],"opinione":["italian"],"opposto":["italian"],"oracolo":["italian"],"orafo":["italian"],"ordine":["italian"],"orecchino":["italian"],"orefice":["italian"],"orfano":["italian"],"organico":["italian"],"origine":["italian"],"orizzonte":["italian"],"orma":["italian"],"ormeggio":["italian"],"ornativo":["italian"],"orologio":["italian"],"orrendo":["italian"],"orribile":["italian"],"ortensia":["italian"],"ortica":["italian"],"orzata":["italian"],"orzo":["italian"],"osare":["italian"],"oscurare":["italian"],"osmosi":["italian"],"ospedale":["italian"],"ospite":["italian"],"ossa":["italian"],"ossidare":["italian"],"ostacolo":["italian"],"oste":["italian"],"otite":["italian"],"otre":["italian"],"ottagono":["italian"],"ottimo":["italian"],"ottobre":["italian"],"ovale":["italian"],"ovest":["italian"],"ovino":["italian"],"oviparo":["italian"],"ovocito":["italian"],"ovunque":["italian"],"ovviare":["italian"],"ozio":["italian"],"pacchetto":["italian"],"pace":["italian"],"pacifico":["italian"],"padella":["italian"],"padrone":["italian"],"paese":["italian"],"paga":["italian"],"pagina":["italian"],"palazzina":["italian"],"palesare":["italian"],"pallido":["italian"],"palo":["italian"],"palude":["italian"],"pandoro":["italian"],"pannello":["italian"],"paolo":["italian"],"paonazzo":["italian"],"paprica":["italian"],"parabola":["italian"],"parcella":["italian"],"parere":["italian"],"pargolo":["italian"],"pari":["italian"],"parlato":["italian"],"parola":["italian"],"partire":["italian"],"parvenza":["italian"],"parziale":["italian"],"passivo":["italian"],"pasticca":["italian"],"patacca":["italian"],"patologia":["italian"],"pattume":["italian"],"pavone":["italian"],"peccato":["italian"],"pedalare":["italian"],"pedonale":["italian"],"peggio":["italian"],"peloso":["italian"],"penare":["italian"],"pendice":["italian"],"penisola":["italian"],"pennuto":["italian"],"penombra":["italian"],"pensare":["italian"],"pentola":["italian"],"pepe":["italian"],"pepita":["italian"],"perbene":["italian"],"percorso":["italian"],"perdonato":["italian"],"perforare":["italian"],"pergamena":["italian"],"periodo":["italian"],"permesso":["italian"],"perno":["italian"],"perplesso":["italian"],"persuaso":["italian"],"pertugio":["italian"],"pervaso":["italian"],"pesatore":["italian"],"pesista":["italian"],"peso":["italian"],"pestifero":["italian"],"petalo":["italian"],"pettine":["italian"],"petulante":["italian"],"pezzo":["italian"],"piacere":["italian"],"pianta":["italian"],"piattino":["italian"],"piccino":["italian"],"picozza":["italian"],"piega":["italian"],"pietra":["italian"],"piffero":["italian"],"pigiama":["italian"],"pigolio":["italian"],"pigro":["italian"],"pila":["italian"],"pilifero":["italian"],"pillola":["italian"],"pilota":["italian"],"pimpante":["italian"],"pineta":["italian"],"pinna":["italian"],"pinolo":["italian"],"pioggia":["italian"],"piombo":["italian"],"piramide":["italian"],"piretico":["italian"],"pirite":["italian"],"pirolisi":["italian"],"pitone":["italian"],"pizzico":["italian"],"placebo":["italian"],"planare":["italian"],"plasma":["italian"],"platano":["italian"],"plenario":["italian"],"pochezza":["italian"],"poderoso":["italian"],"podismo":["italian"],"poesia":["italian"],"poggiare":["italian"],"polenta":["italian"],"poligono":["italian"],"pollice":["italian"],"polmonite":["italian"],"polpetta":["italian"],"polso":["italian"],"poltrona":["italian"],"polvere":["italian"],"pomice":["italian"],"pomodoro":["italian"],"ponte":["italian"],"popoloso":["italian"],"porfido":["italian"],"poroso":["italian"],"porpora":["italian"],"porre":["italian"],"portata":["italian"],"posa":["italian","turkish"],"positivo":["italian"],"possesso":["italian"],"postulato":["italian"],"potassio":["italian"],"potere":["italian"],"pranzo":["italian"],"prassi":["italian"],"pratica":["italian"],"precluso":["italian"],"predica":["italian"],"prefisso":["italian"],"pregiato":["italian"],"prelievo":["italian"],"premere":["italian"],"prenotare":["italian"],"preparato":["italian"],"presenza":["italian"],"pretesto":["italian"],"prevalso":["italian"],"prima":["italian"],"principe":["italian"],"privato":["italian"],"problema":["italian"],"procura":["italian"],"produrre":["italian"],"profumo":["italian"],"progetto":["italian"],"prolunga":["italian"],"promessa":["italian"],"pronome":["italian"],"proposta":["italian"],"proroga":["italian"],"proteso":["italian"],"prova":["italian","turkish"],"prudente":["italian"],"prugna":["italian"],"prurito":["italian"],"psiche":["italian"],"pubblico":["italian"],"pudica":["italian"],"pugilato":["italian"],"pugno":["italian"],"pulce":["italian"],"pulito":["italian"],"pulsante":["italian"],"puntare":["italian"],"pupazzo":["italian"],"pupilla":["italian"],"puro":["italian"],"quadro":["italian"],"qualcosa":["italian"],"quasi":["italian"],"querela":["italian"],"quota":["italian"],"raccolto":["italian"],"raddoppio":["italian"],"radicale":["italian"],"radunato":["italian"],"raffica":["italian"],"ragazzo":["italian"],"ragione":["italian"],"ragno":["italian"],"ramarro":["italian"],"ramingo":["italian"],"ramo":["italian"],"randagio":["italian"],"rantolare":["italian"],"rapato":["italian"],"rapina":["italian"],"rappreso":["italian"],"rasatura":["italian"],"raschiato":["italian"],"rasente":["italian"],"rassegna":["italian"],"rastrello":["italian"],"rata":["italian"],"ravveduto":["italian"],"reale":["italian"],"recepire":["italian"],"recinto":["italian"],"recluta":["italian"],"recondito":["italian"],"recupero":["italian"],"reddito":["italian"],"redimere":["italian"],"regalato":["italian"],"registro":["italian"],"regola":["italian"],"regresso":["italian"],"relazione":["italian"],"remare":["italian"],"remoto":["italian"],"renna":["italian"],"replica":["italian"],"reprimere":["italian"],"reputare":["italian"],"resa":["italian"],"residente":["italian"],"responso":["italian"],"restauro":["italian"],"rete":["italian"],"retina":["italian"],"retorica":["italian"],"rettifica":["italian"],"revocato":["italian"],"riassunto":["italian"],"ribadire":["italian"],"ribelle":["italian"],"ribrezzo":["italian"],"ricarica":["italian"],"ricco":["italian"],"ricevere":["italian"],"riciclato":["italian"],"ricordo":["italian"],"ricreduto":["italian"],"ridicolo":["italian"],"ridurre":["italian"],"rifasare":["italian"],"riflesso":["italian"],"riforma":["italian"],"rifugio":["italian"],"rigare":["italian"],"rigettato":["italian"],"righello":["italian"],"rilassato":["italian"],"rilevato":["italian"],"rimanere":["italian"],"rimbalzo":["italian"],"rimedio":["italian"],"rimorchio":["italian"],"rinascita":["italian"],"rincaro":["italian"],"rinforzo":["italian"],"rinnovo":["italian"],"rinomato":["italian"],"rinsavito":["italian"],"rintocco":["italian"],"rinuncia":["italian"],"rinvenire":["italian"],"riparato":["italian"],"ripetuto":["italian"],"ripieno":["italian"],"riportare":["italian"],"ripresa":["italian"],"ripulire":["italian"],"risata":["italian"],"rischio":["italian"],"riserva":["italian"],"risibile":["italian"],"riso":["italian"],"rispetto":["italian"],"ristoro":["italian"],"risultato":["italian"],"risvolto":["italian"],"ritardo":["italian"],"ritegno":["italian"],"ritmico":["italian"],"ritrovo":["italian"],"riunione":["italian"],"riva":["italian"],"riverso":["italian"],"rivincita":["italian"],"rivolto":["italian"],"rizoma":["italian"],"roba":["italian"],"robotico":["italian"],"robusto":["italian"],"roccia":["italian"],"roco":["italian"],"rodaggio":["italian"],"rodere":["italian"],"roditore":["italian"],"rogito":["italian"],"rollio":["italian"],"romantico":["italian"],"rompere":["italian"],"ronzio":["italian"],"rosolare":["italian"],"rospo":["italian"],"rotante":["italian"],"rotondo":["italian"],"rotula":["italian"],"rovescio":["italian"],"rubizzo":["italian"],"rubrica":["italian"],"ruga":["italian"],"rullino":["italian"],"rumine":["italian"],"rumoroso":["italian"],"ruolo":["italian"],"rupe":["italian"],"russare":["italian"],"rustico":["italian"],"sabato":["italian"],"sabbiare":["italian"],"sabotato":["italian"],"sagoma":["italian"],"salasso":["italian"],"saldatura":["italian"],"salgemma":["italian"],"salivare":["italian"],"salmone":["italian"],"salone":["italian"],"saltare":["italian"],"saluto":["italian"],"salvo":["italian"],"sapere":["italian"],"sapido":["italian"],"saporito":["italian"],"saraceno":["italian"],"sarcasmo":["italian"],"sarto":["italian"],"sassoso":["italian"],"satellite":["italian"],"satira":["italian"],"satollo":["italian"],"saturno":["italian"],"savana":["italian"],"savio":["italian"],"saziato":["italian"],"sbadiglio":["italian"],"sbalzo":["italian"],"sbancato":["italian"],"sbarra":["italian"],"sbattere":["italian"],"sbavare":["italian"],"sbendare":["italian"],"sbirciare":["italian"],"sbloccato":["italian"],"sbocciato":["italian"],"sbrinare":["italian"],"sbruffone":["italian"],"sbuffare":["italian"],"scabroso":["italian"],"scadenza":["italian"],"scala":["italian"],"scambiare":["italian"],"scandalo":["italian"],"scapola":["italian"],"scarso":["italian"],"scatenare":["italian"],"scavato":["italian"],"scelto":["italian"],"scenico":["italian"],"scettro":["italian"],"scheda":["italian"],"schiena":["italian"],"sciarpa":["italian"],"scienza":["italian"],"scindere":["italian"],"scippo":["italian"],"sciroppo":["italian"],"scivolo":["italian"],"sclerare":["italian"],"scodella":["italian"],"scolpito":["italian"],"scomparto":["italian"],"sconforto":["italian"],"scoprire":["italian"],"scorta":["italian"],"scossone":["italian"],"scozzese":["italian"],"scriba":["italian"],"scrollare":["italian"],"scrutinio":["italian"],"scuderia":["italian"],"scultore":["italian"],"scuola":["italian"],"scuro":["italian"],"scusare":["italian"],"sdebitare":["italian"],"sdoganare":["italian"],"seccatura":["italian"],"secondo":["italian"],"sedano":["italian"],"seggiola":["italian"],"segnalato":["italian"],"segregato":["italian"],"seguito":["italian"],"selciato":["italian"],"selettivo":["italian"],"sella":["italian"],"selvaggio":["italian"],"semaforo":["italian"],"sembrare":["italian"],"seme":["italian"],"seminato":["italian"],"sempre":["italian"],"senso":["italian"],"sentire":["italian"],"sepolto":["italian"],"sequenza":["italian"],"serata":["italian"],"serbato":["italian"],"sereno":["italian"],"serio":["italian"],"serpente":["italian"],"serraglio":["italian"],"servire":["italian"],"sestina":["italian"],"setola":["italian"],"settimana":["italian"],"sfacelo":["italian"],"sfaldare":["italian"],"sfamato":["italian"],"sfarzoso":["italian"],"sfaticato":["italian"],"sfera":["italian"],"sfida":["italian"],"sfilato":["italian"],"sfinge":["italian"],"sfocato":["italian"],"sfoderare":["italian"],"sfogo":["italian"],"sfoltire":["italian"],"sforzato":["italian"],"sfratto":["italian"],"sfruttato":["italian"],"sfuggito":["italian"],"sfumare":["italian"],"sfuso":["italian"],"sgabello":["italian"],"sgarbato":["italian"],"sgonfiare":["italian"],"sgorbio":["italian"],"sgrassato":["italian"],"sguardo":["italian"],"sibilo":["italian"],"siccome":["italian"],"sierra":["italian"],"sigla":["italian"],"signore":["italian"],"silenzio":["italian"],"sillaba":["italian"],"simbolo":["italian"],"simpatico":["italian"],"simulato":["italian"],"sinfonia":["italian"],"singolo":["italian"],"sinistro":["italian"],"sino":["italian"],"sintesi":["italian"],"sinusoide":["italian"],"sipario":["italian"],"sisma":["italian"],"sistole":["italian"],"situato":["italian"],"slitta":["italian"],"slogatura":["italian"],"sloveno":["italian"],"smarrito":["italian"],"smemorato":["italian"],"smentito":["italian"],"smeraldo":["italian"],"smilzo":["italian"],"smontare":["italian"],"smottato":["italian"],"smussato":["italian"],"snellire":["italian"],"snervato":["italian"],"snodo":["italian"],"sobbalzo":["italian"],"sobrio":["italian"],"soccorso":["italian"],"sociale":["italian"],"sodale":["italian"],"soffitto":["italian"],"sogno":["italian"],"soldato":["italian"],"solenne":["italian"],"solido":["italian"],"sollazzo":["italian"],"solo":["italian"],"solubile":["italian"],"solvente":["italian"],"somatico":["italian"],"somma":["italian"],"sonda":["italian"],"sonetto":["italian"],"sonnifero":["italian"],"sopire":["italian"],"soppeso":["italian"],"sopra":["italian"],"sorgere":["italian"],"sorpasso":["italian"],"sorriso":["italian"],"sorso":["italian"],"sorteggio":["italian"],"sorvolato":["italian"],"sospiro":["italian"],"sosta":["italian"],"sottile":["italian"],"spada":["italian"],"spalla":["italian"],"spargere":["italian"],"spatola":["italian"],"spavento":["italian"],"spazzola":["italian"],"specie":["italian"],"spedire":["italian"],"spegnere":["italian"],"spelatura":["italian"],"speranza":["italian"],"spessore":["italian"],"spettrale":["italian"],"spezzato":["italian"],"spia":["italian"],"spigoloso":["italian"],"spillato":["italian"],"spinoso":["italian"],"spirale":["italian"],"splendido":["italian"],"sportivo":["italian"],"sposo":["italian"],"spranga":["italian"],"sprecare":["italian"],"spronato":["italian"],"spruzzo":["italian"],"spuntino":["italian"],"squillo":["italian"],"sradicare":["italian"],"srotolato":["italian"],"stabile":["italian"],"stacco":["italian"],"staffa":["italian"],"stagnare":["italian"],"stampato":["italian"],"stantio":["italian"],"starnuto":["italian"],"stasera":["italian"],"statuto":["italian"],"stelo":["italian"],"steppa":["italian"],"sterzo":["italian"],"stiletto":["italian"],"stima":["italian"],"stirpe":["italian"],"stivale":["italian"],"stizzoso":["italian"],"stonato":["italian"],"storico":["italian"],"strappo":["italian"],"stregato":["italian"],"stridulo":["italian"],"strozzare":["italian"],"strutto":["italian"],"stuccare":["italian"],"stufo":["italian"],"stupendo":["italian"],"subentro":["italian"],"succoso":["italian"],"sudore":["italian"],"suggerito":["italian"],"sugo":["italian"],"sultano":["italian"],"suonare":["italian"],"superbo":["italian"],"supporto":["italian"],"surgelato":["italian"],"surrogato":["italian"],"sussurro":["italian"],"sutura":["italian"],"svagare":["italian"],"svedese":["italian"],"sveglio":["italian"],"svelare":["italian"],"svenuto":["italian"],"svezia":["italian"],"sviluppo":["italian"],"svista":["italian"],"svizzera":["italian"],"svolta":["italian"],"svuotare":["italian"],"tabacco":["italian"],"tabulato":["italian"],"tacciare":["italian"],"taciturno":["italian"],"tale":["italian"],"talismano":["italian"],"tampone":["italian"],"tannino":["italian"],"tara":["italian"],"tardivo":["italian"],"targato":["italian"],"tariffa":["italian"],"tarpare":["italian"],"tartaruga":["italian"],"tasto":["italian"],"tattico":["italian"],"taverna":["italian"],"tavolata":["italian"],"tazza":["italian"],"teca":["italian"],"tecnico":["italian"],"telefono":["italian"],"temerario":["italian"],"tempo":["italian","turkish"],"temuto":["italian"],"tendone":["italian"],"tenero":["italian"],"tensione":["italian"],"tentacolo":["italian"],"teorema":["italian"],"terme":["italian"],"terrazzo":["italian"],"terzetto":["italian"],"tesi":["italian"],"tesserato":["italian"],"testato":["italian"],"tetro":["italian"],"tettoia":["italian"],"tifare":["italian"],"tigella":["italian"],"timbro":["italian"],"tinto":["italian"],"tipico":["italian"],"tipografo":["italian"],"tiraggio":["italian"],"tiro":["italian"],"titanio":["italian"],"titolo":["italian"],"titubante":["italian"],"tizio":["italian"],"tizzone":["italian"],"toccare":["italian"],"tollerare":["italian"],"tolto":["italian"],"tombola":["italian"],"tomo":["italian"],"tonfo":["italian"],"tonsilla":["italian"],"topazio":["italian"],"topologia":["italian"],"toppa":["italian"],"torba":["italian"],"tornare":["italian"],"torrone":["italian"],"tortora":["italian"],"toscano":["italian"],"tossire":["italian"],"tostatura":["italian"],"totano":["italian"],"trabocco":["italian"],"trachea":["italian"],"trafila":["italian"],"tragedia":["italian"],"tralcio":["italian"],"tramonto":["italian"],"transito":["italian"],"trapano":["italian"],"trarre":["italian"],"trasloco":["italian"],"trattato":["italian"],"trave":["italian"],"treccia":["italian"],"tremolio":["italian"],"trespolo":["italian"],"tributo":["italian"],"tricheco":["italian"],"trifoglio":["italian"],"trillo":["italian"],"trincea":["italian"],"trio":["italian"],"tristezza":["italian"],"triturato":["italian"],"trivella":["italian"],"tromba":["italian"],"trono":["italian"],"troppo":["italian"],"trottola":["italian"],"trovare":["italian"],"truccato":["italian"],"tubatura":["italian"],"tuffato":["italian"],"tulipano":["italian"],"tumulto":["italian"],"tunisia":["italian"],"turbare":["italian"],"turchino":["italian"],"tuta":["italian"],"tutela":["italian"],"ubicato":["italian"],"uccello":["italian"],"uccisore":["italian"],"udire":["italian"],"uditivo":["italian"],"uffa":["italian"],"ufficio":["italian"],"uguale":["italian"],"ulisse":["italian"],"ultimato":["italian"],"umano":["italian"],"umile":["italian"],"umorismo":["italian"],"uncinetto":["italian"],"ungere":["italian"],"ungherese":["italian"],"unicorno":["italian"],"unificato":["italian"],"unisono":["italian"],"unitario":["italian"],"unte":["italian"],"uovo":["italian"],"upupa":["italian"],"uragano":["italian"],"urgenza":["italian"],"urlo":["italian"],"usanza":["italian"],"usato":["italian"],"uscito":["italian"],"usignolo":["italian"],"usuraio":["italian"],"utensile":["italian"],"utilizzo":["italian"],"utopia":["italian"],"vacante":["italian"],"vaccinato":["italian"],"vagabondo":["italian"],"vagliato":["italian"],"valanga":["italian"],"valgo":["italian"],"valico":["italian"],"valletta":["italian"],"valoroso":["italian"],"valutare":["italian"],"valvola":["italian"],"vampata":["italian"],"vangare":["italian"],"vanitoso":["italian"],"vano":["italian"],"vantaggio":["italian"],"vanvera":["italian"],"vapore":["italian"],"varano":["italian"],"varcato":["italian"],"variante":["italian"],"vasca":["italian"],"vedetta":["italian"],"vedova":["italian"],"veduto":["italian"],"vegetale":["italian"],"veicolo":["italian"],"velcro":["italian"],"velina":["italian"],"velluto":["italian"],"veloce":["italian"],"venato":["italian"],"vendemmia":["italian"],"vento":["italian"],"verace":["italian"],"verbale":["italian"],"vergogna":["italian"],"verifica":["italian"],"vero":["italian"],"verruca":["italian"],"verticale":["italian"],"vescica":["italian"],"vessillo":["italian"],"vestale":["italian"],"veterano":["italian"],"vetrina":["italian"],"vetusto":["italian"],"viandante":["italian"],"vibrante":["italian"],"vicenda":["italian"],"vichingo":["italian"],"vicinanza":["italian"],"vidimare":["italian"],"vigilia":["italian"],"vigneto":["italian"],"vigore":["italian"],"vile":["italian"],"villano":["italian"],"vimini":["italian"],"vincitore":["italian"],"viola":["italian"],"vipera":["italian"],"virgola":["italian"],"virologo":["italian"],"virulento":["italian"],"viscoso":["italian"],"visione":["italian"],"vispo":["italian"],"vissuto":["italian"],"visura":["italian"],"vita":["italian"],"vitello":["italian"],"vittima":["italian"],"vivanda":["italian"],"vivido":["italian"],"viziare":["italian"],"voce":["italian"],"voga":["italian"],"volatile":["italian"],"volere":["italian"],"volpe":["italian"],"voragine":["italian"],"vulcano":["italian"],"zampogna":["italian"],"zanna":["italian"],"zappato":["italian"],"zattera":["italian"],"zavorra":["italian"],"zefiro":["italian"],"zelante":["italian"],"zelo":["italian"],"zenzero":["italian"],"zerbino":["italian"],"zibetto":["italian"],"zinco":["italian"],"zircone":["italian"],"zitto":["italian"],"zolla":["italian"],"zotico":["italian"],"zucchero":["italian"],"zufolo":["italian"],"zulu":["italian"],"zuppa":["italian"],"あいこくしん":["japanese"],"あいさつ":["japanese"],"あいだ":["japanese"],"あおぞら":["japanese"],"あかちゃん":["japanese"],"あきる":["japanese"],"あけがた":["japanese"],"あける":["japanese"],"あこがれる":["japanese"],"あさい":["japanese"],"あさひ":["japanese"],"あしあと":["japanese"],"あじわう":["japanese"],"あずかる":["japanese"],"あずき":["japanese"],"あそぶ":["japanese"],"あたえる":["japanese"],"あたためる":["japanese"],"あたりまえ":["japanese"],"あたる":["japanese"],"あつい":["japanese"],"あつかう":["japanese"],"あっしゅく":["japanese"],"あつまり":["japanese"],"あつめる":["japanese"],"あてな":["japanese"],"あてはまる":["japanese"],"あひる":["japanese"],"あぶら":["japanese"],"あぶる":["japanese"],"あふれる":["japanese"],"あまい":["japanese"],"あまど":["japanese"],"あまやかす":["japanese"],"あまり":["japanese"],"あみもの":["japanese"],"あめりか":["japanese"],"あやまる":["japanese"],"あゆむ":["japanese"],"あらいぐま":["japanese"],"あらし":["japanese"],"あらすじ":["japanese"],"あらためる":["japanese"],"あらゆる":["japanese"],"あらわす":["japanese"],"ありがとう":["japanese"],"あわせる":["japanese"],"あわてる":["japanese"],"あんい":["japanese"],"あんがい":["japanese"],"あんこ":["japanese"],"あんぜん":["japanese"],"あんてい":["japanese"],"あんない":["japanese"],"あんまり":["japanese"],"いいだす":["japanese"],"いおん":["japanese"],"いがい":["japanese"],"いがく":["japanese"],"いきおい":["japanese"],"いきなり":["japanese"],"いきもの":["japanese"],"いきる":["japanese"],"いくじ":["japanese"],"いくぶん":["japanese"],"いけばな":["japanese"],"いけん":["japanese"],"いこう":["japanese"],"いこく":["japanese"],"いこつ":["japanese"],"いさましい":["japanese"],"いさん":["japanese"],"いしき":["japanese"],"いじゅう":["japanese"],"いじょう":["japanese"],"いじわる":["japanese"],"いずみ":["japanese"],"いずれ":["japanese"],"いせい":["japanese"],"いせえび":["japanese"],"いせかい":["japanese"],"いせき":["japanese"],"いぜん":["japanese"],"いそうろう":["japanese"],"いそがしい":["japanese"],"いだい":["japanese"],"いだく":["japanese"],"いたずら":["japanese"],"いたみ":["japanese"],"いたりあ":["japanese"],"いちおう":["japanese"],"いちじ":["japanese"],"いちど":["japanese"],"いちば":["japanese"],"いちぶ":["japanese"],"いちりゅう":["japanese"],"いつか":["japanese"],"いっしゅん":["japanese"],"いっせい":["japanese"],"いっそう":["japanese"],"いったん":["japanese"],"いっち":["japanese"],"いってい":["japanese"],"いっぽう":["japanese"],"いてざ":["japanese"],"いてん":["japanese"],"いどう":["japanese"],"いとこ":["japanese"],"いない":["japanese"],"いなか":["japanese"],"いねむり":["japanese"],"いのち":["japanese"],"いのる":["japanese"],"いはつ":["japanese"],"いばる":["japanese"],"いはん":["japanese"],"いびき":["japanese"],"いひん":["japanese"],"いふく":["japanese"],"いへん":["japanese"],"いほう":["japanese"],"いみん":["japanese"],"いもうと":["japanese"],"いもたれ":["japanese"],"いもり":["japanese"],"いやがる":["japanese"],"いやす":["japanese"],"いよかん":["japanese"],"いよく":["japanese"],"いらい":["japanese"],"いらすと":["japanese"],"いりぐち":["japanese"],"いりょう":["japanese"],"いれい":["japanese"],"いれもの":["japanese"],"いれる":["japanese"],"いろえんぴつ":["japanese"],"いわい":["japanese"],"いわう":["japanese"],"いわかん":["japanese"],"いわば":["japanese"],"いわゆる":["japanese"],"いんげんまめ":["japanese"],"いんさつ":["japanese"],"いんしょう":["japanese"],"いんよう":["japanese"],"うえき":["japanese"],"うえる":["japanese"],"うおざ":["japanese"],"うがい":["japanese"],"うかぶ":["japanese"],"うかべる":["japanese"],"うきわ":["japanese"],"うくらいな":["japanese"],"うくれれ":["japanese"],"うけたまわる":["japanese"],"うけつけ":["japanese"],"うけとる":["japanese"],"うけもつ":["japanese"],"うける":["japanese"],"うごかす":["japanese"],"うごく":["japanese"],"うこん":["japanese"],"うさぎ":["japanese"],"うしなう":["japanese"],"うしろがみ":["japanese"],"うすい":["japanese"],"うすぎ":["japanese"],"うすぐらい":["japanese"],"うすめる":["japanese"],"うせつ":["japanese"],"うちあわせ":["japanese"],"うちがわ":["japanese"],"うちき":["japanese"],"うちゅう":["japanese"],"うっかり":["japanese"],"うつくしい":["japanese"],"うったえる":["japanese"],"うつる":["japanese"],"うどん":["japanese"],"うなぎ":["japanese"],"うなじ":["japanese"],"うなずく":["japanese"],"うなる":["japanese"],"うねる":["japanese"],"うのう":["japanese"],"うぶげ":["japanese"],"うぶごえ":["japanese"],"うまれる":["japanese"],"うめる":["japanese"],"うもう":["japanese"],"うやまう":["japanese"],"うよく":["japanese"],"うらがえす":["japanese"],"うらぐち":["japanese"],"うらない":["japanese"],"うりあげ":["japanese"],"うりきれ":["japanese"],"うるさい":["japanese"],"うれしい":["japanese"],"うれゆき":["japanese"],"うれる":["japanese"],"うろこ":["japanese"],"うわき":["japanese"],"うわさ":["japanese"],"うんこう":["japanese"],"うんちん":["japanese"],"うんてん":["japanese"],"うんどう":["japanese"],"えいえん":["japanese"],"えいが":["japanese"],"えいきょう":["japanese"],"えいご":["japanese"],"えいせい":["japanese"],"えいぶん":["japanese"],"えいよう":["japanese"],"えいわ":["japanese"],"えおり":["japanese"],"えがお":["japanese"],"えがく":["japanese"],"えきたい":["japanese"],"えくせる":["japanese"],"えしゃく":["japanese"],"えすて":["japanese"],"えつらん":["japanese"],"えのぐ":["japanese"],"えほうまき":["japanese"],"えほん":["japanese"],"えまき":["japanese"],"えもじ":["japanese"],"えもの":["japanese"],"えらい":["japanese"],"えらぶ":["japanese"],"えりあ":["japanese"],"えんえん":["japanese"],"えんかい":["japanese"],"えんぎ":["japanese"],"えんげき":["japanese"],"えんしゅう":["japanese"],"えんぜつ":["japanese"],"えんそく":["japanese"],"えんちょう":["japanese"],"えんとつ":["japanese"],"おいかける":["japanese"],"おいこす":["japanese"],"おいしい":["japanese"],"おいつく":["japanese"],"おうえん":["japanese"],"おうさま":["japanese"],"おうじ":["japanese"],"おうせつ":["japanese"],"おうたい":["japanese"],"おうふく":["japanese"],"おうべい":["japanese"],"おうよう":["japanese"],"おえる":["japanese"],"おおい":["japanese"],"おおう":["japanese"],"おおどおり":["japanese"],"おおや":["japanese"],"おおよそ":["japanese"],"おかえり":["japanese"],"おかず":["japanese"],"おがむ":["japanese"],"おかわり":["japanese"],"おぎなう":["japanese"],"おきる":["japanese"],"おくさま":["japanese"],"おくじょう":["japanese"],"おくりがな":["japanese"],"おくる":["japanese"],"おくれる":["japanese"],"おこす":["japanese"],"おこなう":["japanese"],"おこる":["japanese"],"おさえる":["japanese"],"おさない":["japanese"],"おさめる":["japanese"],"おしいれ":["japanese"],"おしえる":["japanese"],"おじぎ":["japanese"],"おじさん":["japanese"],"おしゃれ":["japanese"],"おそらく":["japanese"],"おそわる":["japanese"],"おたがい":["japanese"],"おたく":["japanese"],"おだやか":["japanese"],"おちつく":["japanese"],"おっと":["japanese"],"おつり":["japanese"],"おでかけ":["japanese"],"おとしもの":["japanese"],"おとなしい":["japanese"],"おどり":["japanese"],"おどろかす":["japanese"],"おばさん":["japanese"],"おまいり":["japanese"],"おめでとう":["japanese"],"おもいで":["japanese"],"おもう":["japanese"],"おもたい":["japanese"],"おもちゃ":["japanese"],"おやつ":["japanese"],"おやゆび":["japanese"],"およぼす":["japanese"],"おらんだ":["japanese"],"おろす":["japanese"],"おんがく":["japanese"],"おんけい":["japanese"],"おんしゃ":["japanese"],"おんせん":["japanese"],"おんだん":["japanese"],"おんちゅう":["japanese"],"おんどけい":["japanese"],"かあつ":["japanese"],"かいが":["japanese"],"がいき":["japanese"],"がいけん":["japanese"],"がいこう":["japanese"],"かいさつ":["japanese"],"かいしゃ":["japanese"],"かいすいよく":["japanese"],"かいぜん":["japanese"],"かいぞうど":["japanese"],"かいつう":["japanese"],"かいてん":["japanese"],"かいとう":["japanese"],"かいふく":["japanese"],"がいへき":["japanese"],"かいほう":["japanese"],"かいよう":["japanese"],"がいらい":["japanese"],"かいわ":["japanese"],"かえる":["japanese"],"かおり":["japanese"],"かかえる":["japanese"],"かがく":["japanese"],"かがし":["japanese"],"かがみ":["japanese"],"かくご":["japanese"],"かくとく":["japanese"],"かざる":["japanese"],"がぞう":["japanese"],"かたい":["japanese"],"かたち":["japanese"],"がちょう":["japanese"],"がっきゅう":["japanese"],"がっこう":["japanese"],"がっさん":["japanese"],"がっしょう":["japanese"],"かなざわし":["japanese"],"かのう":["japanese"],"がはく":["japanese"],"かぶか":["japanese"],"かほう":["japanese"],"かほご":["japanese"],"かまう":["japanese"],"かまぼこ":["japanese"],"かめれおん":["japanese"],"かゆい":["japanese"],"かようび":["japanese"],"からい":["japanese"],"かるい":["japanese"],"かろう":["japanese"],"かわく":["japanese"],"かわら":["japanese"],"がんか":["japanese"],"かんけい":["japanese"],"かんこう":["japanese"],"かんしゃ":["japanese"],"かんそう":["japanese"],"かんたん":["japanese"],"かんち":["japanese"],"がんばる":["japanese"],"きあい":["japanese"],"きあつ":["japanese"],"きいろ":["japanese"],"ぎいん":["japanese"],"きうい":["japanese"],"きうん":["japanese"],"きえる":["japanese"],"きおう":["japanese"],"きおく":["japanese"],"きおち":["japanese"],"きおん":["japanese"],"きかい":["japanese"],"きかく":["japanese"],"きかんしゃ":["japanese"],"ききて":["japanese"],"きくばり":["japanese"],"きくらげ":["japanese"],"きけんせい":["japanese"],"きこう":["japanese"],"きこえる":["japanese"],"きこく":["japanese"],"きさい":["japanese"],"きさく":["japanese"],"きさま":["japanese"],"きさらぎ":["japanese"],"ぎじかがく":["japanese"],"ぎしき":["japanese"],"ぎじたいけん":["japanese"],"ぎじにってい":["japanese"],"ぎじゅつしゃ":["japanese"],"きすう":["japanese"],"きせい":["japanese"],"きせき":["japanese"],"きせつ":["japanese"],"きそう":["japanese"],"きぞく":["japanese"],"きぞん":["japanese"],"きたえる":["japanese"],"きちょう":["japanese"],"きつえん":["japanese"],"ぎっちり":["japanese"],"きつつき":["japanese"],"きつね":["japanese"],"きてい":["japanese"],"きどう":["japanese"],"きどく":["japanese"],"きない":["japanese"],"きなが":["japanese"],"きなこ":["japanese"],"きぬごし":["japanese"],"きねん":["japanese"],"きのう":["japanese"],"きのした":["japanese"],"きはく":["japanese"],"きびしい":["japanese"],"きひん":["japanese"],"きふく":["japanese"],"きぶん":["japanese"],"きぼう":["japanese"],"きほん":["japanese"],"きまる":["japanese"],"きみつ":["japanese"],"きむずかしい":["japanese"],"きめる":["japanese"],"きもだめし":["japanese"],"きもち":["japanese"],"きもの":["japanese"],"きゃく":["japanese"],"きやく":["japanese"],"ぎゅうにく":["japanese"],"きよう":["japanese"],"きょうりゅう":["japanese"],"きらい":["japanese"],"きらく":["japanese"],"きりん":["japanese"],"きれい":["japanese"],"きれつ":["japanese"],"きろく":["japanese"],"ぎろん":["japanese"],"きわめる":["japanese"],"ぎんいろ":["japanese"],"きんかくじ":["japanese"],"きんじょ":["japanese"],"きんようび":["japanese"],"ぐあい":["japanese"],"くいず":["japanese"],"くうかん":["japanese"],"くうき":["japanese"],"くうぐん":["japanese"],"くうこう":["japanese"],"ぐうせい":["japanese"],"くうそう":["japanese"],"ぐうたら":["japanese"],"くうふく":["japanese"],"くうぼ":["japanese"],"くかん":["japanese"],"くきょう":["japanese"],"くげん":["japanese"],"ぐこう":["japanese"],"くさい":["japanese"],"くさき":["japanese"],"くさばな":["japanese"],"くさる":["japanese"],"くしゃみ":["japanese"],"くしょう":["japanese"],"くすのき":["japanese"],"くすりゆび":["japanese"],"くせげ":["japanese"],"くせん":["japanese"],"ぐたいてき":["japanese"],"くださる":["japanese"],"くたびれる":["japanese"],"くちこみ":["japanese"],"くちさき":["japanese"],"くつした":["japanese"],"ぐっすり":["japanese"],"くつろぐ":["japanese"],"くとうてん":["japanese"],"くどく":["japanese"],"くなん":["japanese"],"くねくね":["japanese"],"くのう":["japanese"],"くふう":["japanese"],"くみあわせ":["japanese"],"くみたてる":["japanese"],"くめる":["japanese"],"くやくしょ":["japanese"],"くらす":["japanese"],"くらべる":["japanese"],"くるま":["japanese"],"くれる":["japanese"],"くろう":["japanese"],"くわしい":["japanese"],"ぐんかん":["japanese"],"ぐんしょく":["japanese"],"ぐんたい":["japanese"],"ぐんて":["japanese"],"けあな":["japanese"],"けいかく":["japanese"],"けいけん":["japanese"],"けいこ":["japanese"],"けいさつ":["japanese"],"げいじゅつ":["japanese"],"けいたい":["japanese"],"げいのうじん":["japanese"],"けいれき":["japanese"],"けいろ":["japanese"],"けおとす":["japanese"],"けおりもの":["japanese"],"げきか":["japanese"],"げきげん":["japanese"],"げきだん":["japanese"],"げきちん":["japanese"],"げきとつ":["japanese"],"げきは":["japanese"],"げきやく":["japanese"],"げこう":["japanese"],"げこくじょう":["japanese"],"げざい":["japanese"],"けさき":["japanese"],"げざん":["japanese"],"けしき":["japanese"],"けしごむ":["japanese"],"けしょう":["japanese"],"げすと":["japanese"],"けたば":["japanese"],"けちゃっぷ":["japanese"],"けちらす":["japanese"],"けつあつ":["japanese"],"けつい":["japanese"],"けつえき":["japanese"],"けっこん":["japanese"],"けつじょ":["japanese"],"けっせき":["japanese"],"けってい":["japanese"],"けつまつ":["japanese"],"げつようび":["japanese"],"げつれい":["japanese"],"けつろん":["japanese"],"げどく":["japanese"],"けとばす":["japanese"],"けとる":["japanese"],"けなげ":["japanese"],"けなす":["japanese"],"けなみ":["japanese"],"けぬき":["japanese"],"げねつ":["japanese"],"けねん":["japanese"],"けはい":["japanese"],"げひん":["japanese"],"けぶかい":["japanese"],"げぼく":["japanese"],"けまり":["japanese"],"けみかる":["japanese"],"けむし":["japanese"],"けむり":["japanese"],"けもの":["japanese"],"けらい":["japanese"],"けろけろ":["japanese"],"けわしい":["japanese"],"けんい":["japanese"],"けんえつ":["japanese"],"けんお":["japanese"],"けんか":["japanese"],"げんき":["japanese"],"けんげん":["japanese"],"けんこう":["japanese"],"けんさく":["japanese"],"けんしゅう":["japanese"],"けんすう":["japanese"],"げんそう":["japanese"],"けんちく":["japanese"],"けんてい":["japanese"],"けんとう":["japanese"],"けんない":["japanese"],"けんにん":["japanese"],"げんぶつ":["japanese"],"けんま":["japanese"],"けんみん":["japanese"],"けんめい":["japanese"],"けんらん":["japanese"],"けんり":["japanese"],"こあくま":["japanese"],"こいぬ":["japanese"],"こいびと":["japanese"],"ごうい":["japanese"],"こうえん":["japanese"],"こうおん":["japanese"],"こうかん":["japanese"],"ごうきゅう":["japanese"],"ごうけい":["japanese"],"こうこう":["japanese"],"こうさい":["japanese"],"こうじ":["japanese"],"こうすい":["japanese"],"ごうせい":["japanese"],"こうそく":["japanese"],"こうたい":["japanese"],"こうちゃ":["japanese"],"こうつう":["japanese"],"こうてい":["japanese"],"こうどう":["japanese"],"こうない":["japanese"],"こうはい":["japanese"],"ごうほう":["japanese"],"ごうまん":["japanese"],"こうもく":["japanese"],"こうりつ":["japanese"],"こえる":["japanese"],"こおり":["japanese"],"ごかい":["japanese"],"ごがつ":["japanese"],"ごかん":["japanese"],"こくご":["japanese"],"こくさい":["japanese"],"こくとう":["japanese"],"こくない":["japanese"],"こくはく":["japanese"],"こぐま":["japanese"],"こけい":["japanese"],"こける":["japanese"],"ここのか":["japanese"],"こころ":["japanese"],"こさめ":["japanese"],"こしつ":["japanese"],"こすう":["japanese"],"こせい":["japanese"],"こせき":["japanese"],"こぜん":["japanese"],"こそだて":["japanese"],"こたい":["japanese"],"こたえる":["japanese"],"こたつ":["japanese"],"こちょう":["japanese"],"こっか":["japanese"],"こつこつ":["japanese"],"こつばん":["japanese"],"こつぶ":["japanese"],"こてい":["japanese"],"こてん":["japanese"],"ことがら":["japanese"],"ことし":["japanese"],"ことば":["japanese"],"ことり":["japanese"],"こなごな":["japanese"],"こねこね":["japanese"],"このまま":["japanese"],"このみ":["japanese"],"このよ":["japanese"],"ごはん":["japanese"],"こひつじ":["japanese"],"こふう":["japanese"],"こふん":["japanese"],"こぼれる":["japanese"],"ごまあぶら":["japanese"],"こまかい":["japanese"],"ごますり":["japanese"],"こまつな":["japanese"],"こまる":["japanese"],"こむぎこ":["japanese"],"こもじ":["japanese"],"こもち":["japanese"],"こもの":["japanese"],"こもん":["japanese"],"こやく":["japanese"],"こやま":["japanese"],"こゆう":["japanese"],"こゆび":["japanese"],"こよい":["japanese"],"こよう":["japanese"],"こりる":["japanese"],"これくしょん":["japanese"],"ころっけ":["japanese"],"こわもて":["japanese"],"こわれる":["japanese"],"こんいん":["japanese"],"こんかい":["japanese"],"こんき":["japanese"],"こんしゅう":["japanese"],"こんすい":["japanese"],"こんだて":["japanese"],"こんとん":["japanese"],"こんなん":["japanese"],"こんびに":["japanese"],"こんぽん":["japanese"],"こんまけ":["japanese"],"こんや":["japanese"],"こんれい":["japanese"],"こんわく":["japanese"],"ざいえき":["japanese"],"さいかい":["japanese"],"さいきん":["japanese"],"ざいげん":["japanese"],"ざいこ":["japanese"],"さいしょ":["japanese"],"さいせい":["japanese"],"ざいたく":["japanese"],"ざいちゅう":["japanese"],"さいてき":["japanese"],"ざいりょう":["japanese"],"さうな":["japanese"],"さかいし":["japanese"],"さがす":["japanese"],"さかな":["japanese"],"さかみち":["japanese"],"さがる":["japanese"],"さぎょう":["japanese"],"さくし":["japanese"],"さくひん":["japanese"],"さくら":["japanese"],"さこく":["japanese"],"さこつ":["japanese"],"さずかる":["japanese"],"ざせき":["japanese"],"さたん":["japanese"],"さつえい":["japanese"],"ざつおん":["japanese"],"ざっか":["japanese"],"ざつがく":["japanese"],"さっきょく":["japanese"],"ざっし":["japanese"],"さつじん":["japanese"],"ざっそう":["japanese"],"さつたば":["japanese"],"さつまいも":["japanese"],"さてい":["japanese"],"さといも":["japanese"],"さとう":["japanese"],"さとおや":["japanese"],"さとし":["japanese"],"さとる":["japanese"],"さのう":["japanese"],"さばく":["japanese"],"さびしい":["japanese"],"さべつ":["japanese"],"さほう":["japanese"],"さほど":["japanese"],"さます":["japanese"],"さみしい":["japanese"],"さみだれ":["japanese"],"さむけ":["japanese"],"さめる":["japanese"],"さやえんどう":["japanese"],"さゆう":["japanese"],"さよう":["japanese"],"さよく":["japanese"],"さらだ":["japanese"],"ざるそば":["japanese"],"さわやか":["japanese"],"さわる":["japanese"],"さんいん":["japanese"],"さんか":["japanese"],"さんきゃく":["japanese"],"さんこう":["japanese"],"さんさい":["japanese"],"ざんしょ":["japanese"],"さんすう":["japanese"],"さんせい":["japanese"],"さんそ":["japanese"],"さんち":["japanese"],"さんま":["japanese"],"さんみ":["japanese"],"さんらん":["japanese"],"しあい":["japanese"],"しあげ":["japanese"],"しあさって":["japanese"],"しあわせ":["japanese"],"しいく":["japanese"],"しいん":["japanese"],"しうち":["japanese"],"しえい":["japanese"],"しおけ":["japanese"],"しかい":["japanese"],"しかく":["japanese"],"じかん":["japanese"],"しごと":["japanese"],"しすう":["japanese"],"じだい":["japanese"],"したうけ":["japanese"],"したぎ":["japanese"],"したて":["japanese"],"したみ":["japanese"],"しちょう":["japanese"],"しちりん":["japanese"],"しっかり":["japanese"],"しつじ":["japanese"],"しつもん":["japanese"],"してい":["japanese"],"してき":["japanese"],"してつ":["japanese"],"じてん":["japanese"],"じどう":["japanese"],"しなぎれ":["japanese"],"しなもの":["japanese"],"しなん":["japanese"],"しねま":["japanese"],"しねん":["japanese"],"しのぐ":["japanese"],"しのぶ":["japanese"],"しはい":["japanese"],"しばかり":["japanese"],"しはつ":["japanese"],"しはらい":["japanese"],"しはん":["japanese"],"しひょう":["japanese"],"しふく":["japanese"],"じぶん":["japanese"],"しへい":["japanese"],"しほう":["japanese"],"しほん":["japanese"],"しまう":["japanese"],"しまる":["japanese"],"しみん":["japanese"],"しむける":["japanese"],"じむしょ":["japanese"],"しめい":["japanese"],"しめる":["japanese"],"しもん":["japanese"],"しゃいん":["japanese"],"しゃうん":["japanese"],"しゃおん":["japanese"],"じゃがいも":["japanese"],"しやくしょ":["japanese"],"しゃくほう":["japanese"],"しゃけん":["japanese"],"しゃこ":["japanese"],"しゃざい":["japanese"],"しゃしん":["japanese"],"しゃせん":["japanese"],"しゃそう":["japanese"],"しゃたい":["japanese"],"しゃちょう":["japanese"],"しゃっきん":["japanese"],"じゃま":["japanese"],"しゃりん":["japanese"],"しゃれい":["japanese"],"じゆう":["japanese"],"じゅうしょ":["japanese"],"しゅくはく":["japanese"],"じゅしん":["japanese"],"しゅっせき":["japanese"],"しゅみ":["japanese"],"しゅらば":["japanese"],"じゅんばん":["japanese"],"しょうかい":["japanese"],"しょくたく":["japanese"],"しょっけん":["japanese"],"しょどう":["japanese"],"しょもつ":["japanese"],"しらせる":["japanese"],"しらべる":["japanese"],"しんか":["japanese"],"しんこう":["japanese"],"じんじゃ":["japanese"],"しんせいじ":["japanese"],"しんちく":["japanese"],"しんりん":["japanese"],"すあげ":["japanese"],"すあし":["japanese"],"すあな":["japanese"],"ずあん":["japanese"],"すいえい":["japanese"],"すいか":["japanese"],"すいとう":["japanese"],"ずいぶん":["japanese"],"すいようび":["japanese"],"すうがく":["japanese"],"すうじつ":["japanese"],"すうせん":["japanese"],"すおどり":["japanese"],"すきま":["japanese"],"すくう":["japanese"],"すくない":["japanese"],"すける":["japanese"],"すごい":["japanese"],"すこし":["japanese"],"ずさん":["japanese"],"すずしい":["japanese"],"すすむ":["japanese"],"すすめる":["japanese"],"すっかり":["japanese"],"ずっしり":["japanese"],"ずっと":["japanese"],"すてき":["japanese"],"すてる":["japanese"],"すねる":["japanese"],"すのこ":["japanese"],"すはだ":["japanese"],"すばらしい":["japanese"],"ずひょう":["japanese"],"ずぶぬれ":["japanese"],"すぶり":["japanese"],"すふれ":["japanese"],"すべて":["japanese"],"すべる":["japanese"],"ずほう":["japanese"],"すぼん":["japanese"],"すまい":["japanese"],"すめし":["japanese"],"すもう":["japanese"],"すやき":["japanese"],"すらすら":["japanese"],"するめ":["japanese"],"すれちがう":["japanese"],"すろっと":["japanese"],"すわる":["japanese"],"すんぜん":["japanese"],"すんぽう":["japanese"],"せあぶら":["japanese"],"せいかつ":["japanese"],"せいげん":["japanese"],"せいじ":["japanese"],"せいよう":["japanese"],"せおう":["japanese"],"せかいかん":["japanese"],"せきにん":["japanese"],"せきむ":["japanese"],"せきゆ":["japanese"],"せきらんうん":["japanese"],"せけん":["japanese"],"せこう":["japanese"],"せすじ":["japanese"],"せたい":["japanese"],"せたけ":["japanese"],"せっかく":["japanese"],"せっきゃく":["japanese"],"ぜっく":["japanese"],"せっけん":["japanese"],"せっこつ":["japanese"],"せっさたくま":["japanese"],"せつぞく":["japanese"],"せつだん":["japanese"],"せつでん":["japanese"],"せっぱん":["japanese"],"せつび":["japanese"],"せつぶん":["japanese"],"せつめい":["japanese"],"せつりつ":["japanese"],"せなか":["japanese"],"せのび":["japanese"],"せはば":["japanese"],"せびろ":["japanese"],"せぼね":["japanese"],"せまい":["japanese"],"せまる":["japanese"],"せめる":["japanese"],"せもたれ":["japanese"],"せりふ":["japanese"],"ぜんあく":["japanese"],"せんい":["japanese"],"せんえい":["japanese"],"せんか":["japanese"],"せんきょ":["japanese"],"せんく":["japanese"],"せんげん":["japanese"],"ぜんご":["japanese"],"せんさい":["japanese"],"せんしゅ":["japanese"],"せんすい":["japanese"],"せんせい":["japanese"],"せんぞ":["japanese"],"せんたく":["japanese"],"せんちょう":["japanese"],"せんてい":["japanese"],"せんとう":["japanese"],"せんぬき":["japanese"],"せんねん":["japanese"],"せんぱい":["japanese"],"ぜんぶ":["japanese"],"ぜんぽう":["japanese"],"せんむ":["japanese"],"せんめんじょ":["japanese"],"せんもん":["japanese"],"せんやく":["japanese"],"せんゆう":["japanese"],"せんよう":["japanese"],"ぜんら":["japanese"],"ぜんりゃく":["japanese"],"せんれい":["japanese"],"せんろ":["japanese"],"そあく":["japanese"],"そいとげる":["japanese"],"そいね":["japanese"],"そうがんきょう":["japanese"],"そうき":["japanese"],"そうご":["japanese"],"そうしん":["japanese"],"そうだん":["japanese"],"そうなん":["japanese"],"そうび":["japanese"],"そうめん":["japanese"],"そうり":["japanese"],"そえもの":["japanese"],"そえん":["japanese"],"そがい":["japanese"],"そげき":["japanese"],"そこう":["japanese"],"そこそこ":["japanese"],"そざい":["japanese"],"そしな":["japanese"],"そせい":["japanese"],"そせん":["japanese"],"そそぐ":["japanese"],"そだてる":["japanese"],"そつう":["japanese"],"そつえん":["japanese"],"そっかん":["japanese"],"そつぎょう":["japanese"],"そっけつ":["japanese"],"そっこう":["japanese"],"そっせん":["japanese"],"そっと":["japanese"],"そとがわ":["japanese"],"そとづら":["japanese"],"そなえる":["japanese"],"そなた":["japanese"],"そふぼ":["japanese"],"そぼく":["japanese"],"そぼろ":["japanese"],"そまつ":["japanese"],"そまる":["japanese"],"そむく":["japanese"],"そむりえ":["japanese"],"そめる":["japanese"],"そもそも":["japanese"],"そよかぜ":["japanese"],"そらまめ":["japanese"],"そろう":["japanese"],"そんかい":["japanese"],"そんけい":["japanese"],"そんざい":["japanese"],"そんしつ":["japanese"],"そんぞく":["japanese"],"そんちょう":["japanese"],"ぞんび":["japanese"],"ぞんぶん":["japanese"],"そんみん":["japanese"],"たあい":["japanese"],"たいいん":["japanese"],"たいうん":["japanese"],"たいえき":["japanese"],"たいおう":["japanese"],"だいがく":["japanese"],"たいき":["japanese"],"たいぐう":["japanese"],"たいけん":["japanese"],"たいこ":["japanese"],"たいざい":["japanese"],"だいじょうぶ":["japanese"],"だいすき":["japanese"],"たいせつ":["japanese"],"たいそう":["japanese"],"だいたい":["japanese"],"たいちょう":["japanese"],"たいてい":["japanese"],"だいどころ":["japanese"],"たいない":["japanese"],"たいねつ":["japanese"],"たいのう":["japanese"],"たいはん":["japanese"],"だいひょう":["japanese"],"たいふう":["japanese"],"たいへん":["japanese"],"たいほ":["japanese"],"たいまつばな":["japanese"],"たいみんぐ":["japanese"],"たいむ":["japanese"],"たいめん":["japanese"],"たいやき":["japanese"],"たいよう":["japanese"],"たいら":["japanese"],"たいりょく":["japanese"],"たいる":["japanese"],"たいわん":["japanese"],"たうえ":["japanese"],"たえる":["japanese"],"たおす":["japanese"],"たおる":["japanese"],"たおれる":["japanese"],"たかい":["japanese"],"たかね":["japanese"],"たきび":["japanese"],"たくさん":["japanese"],"たこく":["japanese"],"たこやき":["japanese"],"たさい":["japanese"],"たしざん":["japanese"],"だじゃれ":["japanese"],"たすける":["japanese"],"たずさわる":["japanese"],"たそがれ":["japanese"],"たたかう":["japanese"],"たたく":["japanese"],"ただしい":["japanese"],"たたみ":["japanese"],"たちばな":["japanese"],"だっかい":["japanese"],"だっきゃく":["japanese"],"だっこ":["japanese"],"だっしゅつ":["japanese"],"だったい":["japanese"],"たてる":["japanese"],"たとえる":["japanese"],"たなばた":["japanese"],"たにん":["japanese"],"たぬき":["japanese"],"たのしみ":["japanese"],"たはつ":["japanese"],"たぶん":["japanese"],"たべる":["japanese"],"たぼう":["japanese"],"たまご":["japanese"],"たまる":["japanese"],"だむる":["japanese"],"ためいき":["japanese"],"ためす":["japanese"],"ためる":["japanese"],"たもつ":["japanese"],"たやすい":["japanese"],"たよる":["japanese"],"たらす":["japanese"],"たりきほんがん":["japanese"],"たりょう":["japanese"],"たりる":["japanese"],"たると":["japanese"],"たれる":["japanese"],"たれんと":["japanese"],"たろっと":["japanese"],"たわむれる":["japanese"],"だんあつ":["japanese"],"たんい":["japanese"],"たんおん":["japanese"],"たんか":["japanese"],"たんき":["japanese"],"たんけん":["japanese"],"たんご":["japanese"],"たんさん":["japanese"],"たんじょうび":["japanese"],"だんせい":["japanese"],"たんそく":["japanese"],"たんたい":["japanese"],"だんち":["japanese"],"たんてい":["japanese"],"たんとう":["japanese"],"だんな":["japanese"],"たんにん":["japanese"],"だんねつ":["japanese"],"たんのう":["japanese"],"たんぴん":["japanese"],"だんぼう":["japanese"],"たんまつ":["japanese"],"たんめい":["japanese"],"だんれつ":["japanese"],"だんろ":["japanese"],"だんわ":["japanese"],"ちあい":["japanese"],"ちあん":["japanese"],"ちいき":["japanese"],"ちいさい":["japanese"],"ちえん":["japanese"],"ちかい":["japanese"],"ちから":["japanese"],"ちきゅう":["japanese"],"ちきん":["japanese"],"ちけいず":["japanese"],"ちけん":["japanese"],"ちこく":["japanese"],"ちさい":["japanese"],"ちしき":["japanese"],"ちしりょう":["japanese"],"ちせい":["japanese"],"ちそう":["japanese"],"ちたい":["japanese"],"ちたん":["japanese"],"ちちおや":["japanese"],"ちつじょ":["japanese"],"ちてき":["japanese"],"ちてん":["japanese"],"ちぬき":["japanese"],"ちぬり":["japanese"],"ちのう":["japanese"],"ちひょう":["japanese"],"ちへいせん":["japanese"],"ちほう":["japanese"],"ちまた":["japanese"],"ちみつ":["japanese"],"ちみどろ":["japanese"],"ちめいど":["japanese"],"ちゃんこなべ":["japanese"],"ちゅうい":["japanese"],"ちゆりょく":["japanese"],"ちょうし":["japanese"],"ちょさくけん":["japanese"],"ちらし":["japanese"],"ちらみ":["japanese"],"ちりがみ":["japanese"],"ちりょう":["japanese"],"ちるど":["japanese"],"ちわわ":["japanese"],"ちんたい":["japanese"],"ちんもく":["japanese"],"ついか":["japanese"],"ついたち":["japanese"],"つうか":["japanese"],"つうじょう":["japanese"],"つうはん":["japanese"],"つうわ":["japanese"],"つかう":["japanese"],"つかれる":["japanese"],"つくね":["japanese"],"つくる":["japanese"],"つけね":["japanese"],"つける":["japanese"],"つごう":["japanese"],"つたえる":["japanese"],"つづく":["japanese"],"つつじ":["japanese"],"つつむ":["japanese"],"つとめる":["japanese"],"つながる":["japanese"],"つなみ":["japanese"],"つねづね":["japanese"],"つのる":["japanese"],"つぶす":["japanese"],"つまらない":["japanese"],"つまる":["japanese"],"つみき":["japanese"],"つめたい":["japanese"],"つもり":["japanese"],"つもる":["japanese"],"つよい":["japanese"],"つるぼ":["japanese"],"つるみく":["japanese"],"つわもの":["japanese"],"つわり":["japanese"],"てあし":["japanese"],"てあて":["japanese"],"てあみ":["japanese"],"ていおん":["japanese"],"ていか":["japanese"],"ていき":["japanese"],"ていけい":["japanese"],"ていこく":["japanese"],"ていさつ":["japanese"],"ていし":["japanese"],"ていせい":["japanese"],"ていたい":["japanese"],"ていど":["japanese"],"ていねい":["japanese"],"ていひょう":["japanese"],"ていへん":["japanese"],"ていぼう":["japanese"],"てうち":["japanese"],"ておくれ":["japanese"],"てきとう":["japanese"],"てくび":["japanese"],"でこぼこ":["japanese"],"てさぎょう":["japanese"],"てさげ":["japanese"],"てすり":["japanese"],"てそう":["japanese"],"てちがい":["japanese"],"てちょう":["japanese"],"てつがく":["japanese"],"てつづき":["japanese"],"でっぱ":["japanese"],"てつぼう":["japanese"],"てつや":["japanese"],"でぬかえ":["japanese"],"てぬき":["japanese"],"てぬぐい":["japanese"],"てのひら":["japanese"],"てはい":["japanese"],"てぶくろ":["japanese"],"てふだ":["japanese"],"てほどき":["japanese"],"てほん":["japanese"],"てまえ":["japanese"],"てまきずし":["japanese"],"てみじか":["japanese"],"てみやげ":["japanese"],"てらす":["japanese"],"てれび":["japanese"],"てわけ":["japanese"],"てわたし":["japanese"],"でんあつ":["japanese"],"てんいん":["japanese"],"てんかい":["japanese"],"てんき":["japanese"],"てんぐ":["japanese"],"てんけん":["japanese"],"てんごく":["japanese"],"てんさい":["japanese"],"てんし":["japanese"],"てんすう":["japanese"],"でんち":["japanese"],"てんてき":["japanese"],"てんとう":["japanese"],"てんない":["japanese"],"てんぷら":["japanese"],"てんぼうだい":["japanese"],"てんめつ":["japanese"],"てんらんかい":["japanese"],"でんりょく":["japanese"],"でんわ":["japanese"],"どあい":["japanese"],"といれ":["japanese"],"どうかん":["japanese"],"とうきゅう":["japanese"],"どうぐ":["japanese"],"とうし":["japanese"],"とうむぎ":["japanese"],"とおい":["japanese"],"とおか":["japanese"],"とおく":["japanese"],"とおす":["japanese"],"とおる":["japanese"],"とかい":["japanese"],"とかす":["japanese"],"ときおり":["japanese"],"ときどき":["japanese"],"とくい":["japanese"],"とくしゅう":["japanese"],"とくてん":["japanese"],"とくに":["japanese"],"とくべつ":["japanese"],"とけい":["japanese"],"とける":["japanese"],"とこや":["japanese"],"とさか":["japanese"],"としょかん":["japanese"],"とそう":["japanese"],"とたん":["japanese"],"とちゅう":["japanese"],"とっきゅう":["japanese"],"とっくん":["japanese"],"とつぜん":["japanese"],"とつにゅう":["japanese"],"とどける":["japanese"],"ととのえる":["japanese"],"とない":["japanese"],"となえる":["japanese"],"となり":["japanese"],"とのさま":["japanese"],"とばす":["japanese"],"どぶがわ":["japanese"],"とほう":["japanese"],"とまる":["japanese"],"とめる":["japanese"],"ともだち":["japanese"],"ともる":["japanese"],"どようび":["japanese"],"とらえる":["japanese"],"とんかつ":["japanese"],"どんぶり":["japanese"],"ないかく":["japanese"],"ないこう":["japanese"],"ないしょ":["japanese"],"ないす":["japanese"],"ないせん":["japanese"],"ないそう":["japanese"],"なおす":["japanese"],"ながい":["japanese"],"なくす":["japanese"],"なげる":["japanese"],"なこうど":["japanese"],"なさけ":["japanese"],"なたでここ":["japanese"],"なっとう":["japanese"],"なつやすみ":["japanese"],"ななおし":["japanese"],"なにごと":["japanese"],"なにもの":["japanese"],"なにわ":["japanese"],"なのか":["japanese"],"なふだ":["japanese"],"なまいき":["japanese"],"なまえ":["japanese"],"なまみ":["japanese"],"なみだ":["japanese"],"なめらか":["japanese"],"なめる":["japanese"],"なやむ":["japanese"],"ならう":["japanese"],"ならび":["japanese"],"ならぶ":["japanese"],"なれる":["japanese"],"なわとび":["japanese"],"なわばり":["japanese"],"にあう":["japanese"],"にいがた":["japanese"],"にうけ":["japanese"],"におい":["japanese"],"にかい":["japanese"],"にがて":["japanese"],"にきび":["japanese"],"にくしみ":["japanese"],"にくまん":["japanese"],"にげる":["japanese"],"にさんかたんそ":["japanese"],"にしき":["japanese"],"にせもの":["japanese"],"にちじょう":["japanese"],"にちようび":["japanese"],"にっか":["japanese"],"にっき":["japanese"],"にっけい":["japanese"],"にっこう":["japanese"],"にっさん":["japanese"],"にっしょく":["japanese"],"にっすう":["japanese"],"にっせき":["japanese"],"にってい":["japanese"],"になう":["japanese"],"にほん":["japanese"],"にまめ":["japanese"],"にもつ":["japanese"],"にやり":["japanese"],"にゅういん":["japanese"],"にりんしゃ":["japanese"],"にわとり":["japanese"],"にんい":["japanese"],"にんか":["japanese"],"にんき":["japanese"],"にんげん":["japanese"],"にんしき":["japanese"],"にんずう":["japanese"],"にんそう":["japanese"],"にんたい":["japanese"],"にんち":["japanese"],"にんてい":["japanese"],"にんにく":["japanese"],"にんぷ":["japanese"],"にんまり":["japanese"],"にんむ":["japanese"],"にんめい":["japanese"],"にんよう":["japanese"],"ぬいくぎ":["japanese"],"ぬかす":["japanese"],"ぬぐいとる":["japanese"],"ぬぐう":["japanese"],"ぬくもり":["japanese"],"ぬすむ":["japanese"],"ぬまえび":["japanese"],"ぬめり":["japanese"],"ぬらす":["japanese"],"ぬんちゃく":["japanese"],"ねあげ":["japanese"],"ねいき":["japanese"],"ねいる":["japanese"],"ねいろ":["japanese"],"ねぐせ":["japanese"],"ねくたい":["japanese"],"ねくら":["japanese"],"ねこぜ":["japanese"],"ねこむ":["japanese"],"ねさげ":["japanese"],"ねすごす":["japanese"],"ねそべる":["japanese"],"ねだん":["japanese"],"ねつい":["japanese"],"ねっしん":["japanese"],"ねつぞう":["japanese"],"ねったいぎょ":["japanese"],"ねぶそく":["japanese"],"ねふだ":["japanese"],"ねぼう":["japanese"],"ねほりはほり":["japanese"],"ねまき":["japanese"],"ねまわし":["japanese"],"ねみみ":["japanese"],"ねむい":["japanese"],"ねむたい":["japanese"],"ねもと":["japanese"],"ねらう":["japanese"],"ねわざ":["japanese"],"ねんいり":["japanese"],"ねんおし":["japanese"],"ねんかん":["japanese"],"ねんきん":["japanese"],"ねんぐ":["japanese"],"ねんざ":["japanese"],"ねんし":["japanese"],"ねんちゃく":["japanese"],"ねんど":["japanese"],"ねんぴ":["japanese"],"ねんぶつ":["japanese"],"ねんまつ":["japanese"],"ねんりょう":["japanese"],"ねんれい":["japanese"],"のいず":["japanese"],"のおづま":["japanese"],"のがす":["japanese"],"のきなみ":["japanese"],"のこぎり":["japanese"],"のこす":["japanese"],"のこる":["japanese"],"のせる":["japanese"],"のぞく":["japanese"],"のぞむ":["japanese"],"のたまう":["japanese"],"のちほど":["japanese"],"のっく":["japanese"],"のばす":["japanese"],"のはら":["japanese"],"のべる":["japanese"],"のぼる":["japanese"],"のみもの":["japanese"],"のやま":["japanese"],"のらいぬ":["japanese"],"のらねこ":["japanese"],"のりもの":["japanese"],"のりゆき":["japanese"],"のれん":["japanese"],"のんき":["japanese"],"ばあい":["japanese"],"はあく":["japanese"],"ばあさん":["japanese"],"ばいか":["japanese"],"ばいく":["japanese"],"はいけん":["japanese"],"はいご":["japanese"],"はいしん":["japanese"],"はいすい":["japanese"],"はいせん":["japanese"],"はいそう":["japanese"],"はいち":["japanese"],"ばいばい":["japanese"],"はいれつ":["japanese"],"はえる":["japanese"],"はおる":["japanese"],"はかい":["japanese"],"ばかり":["japanese"],"はかる":["japanese"],"はくしゅ":["japanese"],"はけん":["japanese"],"はこぶ":["japanese"],"はさみ":["japanese"],"はさん":["japanese"],"はしご":["japanese"],"ばしょ":["japanese"],"はしる":["japanese"],"はせる":["japanese"],"ぱそこん":["japanese"],"はそん":["japanese"],"はたん":["japanese"],"はちみつ":["japanese"],"はつおん":["japanese"],"はっかく":["japanese"],"はづき":["japanese"],"はっきり":["japanese"],"はっくつ":["japanese"],"はっけん":["japanese"],"はっこう":["japanese"],"はっさん":["japanese"],"はっしん":["japanese"],"はったつ":["japanese"],"はっちゅう":["japanese"],"はってん":["japanese"],"はっぴょう":["japanese"],"はっぽう":["japanese"],"はなす":["japanese"],"はなび":["japanese"],"はにかむ":["japanese"],"はぶらし":["japanese"],"はみがき":["japanese"],"はむかう":["japanese"],"はめつ":["japanese"],"はやい":["japanese"],"はやし":["japanese"],"はらう":["japanese"],"はろうぃん":["japanese"],"はわい":["japanese"],"はんい":["japanese"],"はんえい":["japanese"],"はんおん":["japanese"],"はんかく":["japanese"],"はんきょう":["japanese"],"ばんぐみ":["japanese"],"はんこ":["japanese"],"はんしゃ":["japanese"],"はんすう":["japanese"],"はんだん":["japanese"],"ぱんち":["japanese"],"ぱんつ":["japanese"],"はんてい":["japanese"],"はんとし":["japanese"],"はんのう":["japanese"],"はんぱ":["japanese"],"はんぶん":["japanese"],"はんぺん":["japanese"],"はんぼうき":["japanese"],"はんめい":["japanese"],"はんらん":["japanese"],"はんろん":["japanese"],"ひいき":["japanese"],"ひうん":["japanese"],"ひえる":["japanese"],"ひかく":["japanese"],"ひかり":["japanese"],"ひかる":["japanese"],"ひかん":["japanese"],"ひくい":["japanese"],"ひけつ":["japanese"],"ひこうき":["japanese"],"ひこく":["japanese"],"ひさい":["japanese"],"ひさしぶり":["japanese"],"ひさん":["japanese"],"びじゅつかん":["japanese"],"ひしょ":["japanese"],"ひそか":["japanese"],"ひそむ":["japanese"],"ひたむき":["japanese"],"ひだり":["japanese"],"ひたる":["japanese"],"ひつぎ":["japanese"],"ひっこし":["japanese"],"ひっし":["japanese"],"ひつじゅひん":["japanese"],"ひっす":["japanese"],"ひつぜん":["japanese"],"ぴったり":["japanese"],"ぴっちり":["japanese"],"ひつよう":["japanese"],"ひてい":["japanese"],"ひとごみ":["japanese"],"ひなまつり":["japanese"],"ひなん":["japanese"],"ひねる":["japanese"],"ひはん":["japanese"],"ひびく":["japanese"],"ひひょう":["japanese"],"ひほう":["japanese"],"ひまわり":["japanese"],"ひまん":["japanese"],"ひみつ":["japanese"],"ひめい":["japanese"],"ひめじし":["japanese"],"ひやけ":["japanese"],"ひやす":["japanese"],"ひよう":["japanese"],"びょうき":["japanese"],"ひらがな":["japanese"],"ひらく":["japanese"],"ひりつ":["japanese"],"ひりょう":["japanese"],"ひるま":["japanese"],"ひるやすみ":["japanese"],"ひれい":["japanese"],"ひろい":["japanese"],"ひろう":["japanese"],"ひろき":["japanese"],"ひろゆき":["japanese"],"ひんかく":["japanese"],"ひんけつ":["japanese"],"ひんこん":["japanese"],"ひんしゅ":["japanese"],"ひんそう":["japanese"],"ぴんち":["japanese"],"ひんぱん":["japanese"],"びんぼう":["japanese"],"ふあん":["japanese"],"ふいうち":["japanese"],"ふうけい":["japanese"],"ふうせん":["japanese"],"ぷうたろう":["japanese"],"ふうとう":["japanese"],"ふうふ":["japanese"],"ふえる":["japanese"],"ふおん":["japanese"],"ふかい":["japanese"],"ふきん":["japanese"],"ふくざつ":["japanese"],"ふくぶくろ":["japanese"],"ふこう":["japanese"],"ふさい":["japanese"],"ふしぎ":["japanese"],"ふじみ":["japanese"],"ふすま":["japanese"],"ふせい":["japanese"],"ふせぐ":["japanese"],"ふそく":["japanese"],"ぶたにく":["japanese"],"ふたん":["japanese"],"ふちょう":["japanese"],"ふつう":["japanese"],"ふつか":["japanese"],"ふっかつ":["japanese"],"ふっき":["japanese"],"ふっこく":["japanese"],"ぶどう":["japanese"],"ふとる":["japanese"],"ふとん":["japanese"],"ふのう":["japanese"],"ふはい":["japanese"],"ふひょう":["japanese"],"ふへん":["japanese"],"ふまん":["japanese"],"ふみん":["japanese"],"ふめつ":["japanese"],"ふめん":["japanese"],"ふよう":["japanese"],"ふりこ":["japanese"],"ふりる":["japanese"],"ふるい":["japanese"],"ふんいき":["japanese"],"ぶんがく":["japanese"],"ぶんぐ":["japanese"],"ふんしつ":["japanese"],"ぶんせき":["japanese"],"ふんそう":["japanese"],"ぶんぽう":["japanese"],"へいあん":["japanese"],"へいおん":["japanese"],"へいがい":["japanese"],"へいき":["japanese"],"へいげん":["japanese"],"へいこう":["japanese"],"へいさ":["japanese"],"へいしゃ":["japanese"],"へいせつ":["japanese"],"へいそ":["japanese"],"へいたく":["japanese"],"へいてん":["japanese"],"へいねつ":["japanese"],"へいわ":["japanese"],"へきが":["japanese"],"へこむ":["japanese"],"べにいろ":["japanese"],"べにしょうが":["japanese"],"へらす":["japanese"],"へんかん":["japanese"],"べんきょう":["japanese"],"べんごし":["japanese"],"へんさい":["japanese"],"へんたい":["japanese"],"べんり":["japanese"],"ほあん":["japanese"],"ほいく":["japanese"],"ぼうぎょ":["japanese"],"ほうこく":["japanese"],"ほうそう":["japanese"],"ほうほう":["japanese"],"ほうもん":["japanese"],"ほうりつ":["japanese"],"ほえる":["japanese"],"ほおん":["japanese"],"ほかん":["japanese"],"ほきょう":["japanese"],"ぼきん":["japanese"],"ほくろ":["japanese"],"ほけつ":["japanese"],"ほけん":["japanese"],"ほこう":["japanese"],"ほこる":["japanese"],"ほしい":["japanese"],"ほしつ":["japanese"],"ほしゅ":["japanese"],"ほしょう":["japanese"],"ほせい":["japanese"],"ほそい":["japanese"],"ほそく":["japanese"],"ほたて":["japanese"],"ほたる":["japanese"],"ぽちぶくろ":["japanese"],"ほっきょく":["japanese"],"ほっさ":["japanese"],"ほったん":["japanese"],"ほとんど":["japanese"],"ほめる":["japanese"],"ほんい":["japanese"],"ほんき":["japanese"],"ほんけ":["japanese"],"ほんしつ":["japanese"],"ほんやく":["japanese"],"まいにち":["japanese"],"まかい":["japanese"],"まかせる":["japanese"],"まがる":["japanese"],"まける":["japanese"],"まこと":["japanese"],"まさつ":["japanese"],"まじめ":["japanese"],"ますく":["japanese"],"まぜる":["japanese"],"まつり":["japanese"],"まとめ":["japanese"],"まなぶ":["japanese"],"まぬけ":["japanese"],"まねく":["japanese"],"まほう":["japanese"],"まもる":["japanese"],"まゆげ":["japanese"],"まよう":["japanese"],"まろやか":["japanese"],"まわす":["japanese"],"まわり":["japanese"],"まわる":["japanese"],"まんが":["japanese"],"まんきつ":["japanese"],"まんぞく":["japanese"],"まんなか":["japanese"],"みいら":["japanese"],"みうち":["japanese"],"みえる":["japanese"],"みがく":["japanese"],"みかた":["japanese"],"みかん":["japanese"],"みけん":["japanese"],"みこん":["japanese"],"みじかい":["japanese"],"みすい":["japanese"],"みすえる":["japanese"],"みせる":["japanese"],"みっか":["japanese"],"みつかる":["japanese"],"みつける":["japanese"],"みてい":["japanese"],"みとめる":["japanese"],"みなと":["japanese"],"みなみかさい":["japanese"],"みねらる":["japanese"],"みのう":["japanese"],"みのがす":["japanese"],"みほん":["japanese"],"みもと":["japanese"],"みやげ":["japanese"],"みらい":["japanese"],"みりょく":["japanese"],"みわく":["japanese"],"みんか":["japanese"],"みんぞく":["japanese"],"むいか":["japanese"],"むえき":["japanese"],"むえん":["japanese"],"むかい":["japanese"],"むかう":["japanese"],"むかえ":["japanese"],"むかし":["japanese"],"むぎちゃ":["japanese"],"むける":["japanese"],"むげん":["japanese"],"むさぼる":["japanese"],"むしあつい":["japanese"],"むしば":["japanese"],"むじゅん":["japanese"],"むしろ":["japanese"],"むすう":["japanese"],"むすこ":["japanese"],"むすぶ":["japanese"],"むすめ":["japanese"],"むせる":["japanese"],"むせん":["japanese"],"むちゅう":["japanese"],"むなしい":["japanese"],"むのう":["japanese"],"むやみ":["japanese"],"むよう":["japanese"],"むらさき":["japanese"],"むりょう":["japanese"],"むろん":["japanese"],"めいあん":["japanese"],"めいうん":["japanese"],"めいえん":["japanese"],"めいかく":["japanese"],"めいきょく":["japanese"],"めいさい":["japanese"],"めいし":["japanese"],"めいそう":["japanese"],"めいぶつ":["japanese"],"めいれい":["japanese"],"めいわく":["japanese"],"めぐまれる":["japanese"],"めざす":["japanese"],"めした":["japanese"],"めずらしい":["japanese"],"めだつ":["japanese"],"めまい":["japanese"],"めやす":["japanese"],"めんきょ":["japanese"],"めんせき":["japanese"],"めんどう":["japanese"],"もうしあげる":["japanese"],"もうどうけん":["japanese"],"もえる":["japanese"],"もくし":["japanese"],"もくてき":["japanese"],"もくようび":["japanese"],"もちろん":["japanese"],"もどる":["japanese"],"もらう":["japanese"],"もんく":["japanese"],"もんだい":["japanese"],"やおや":["japanese"],"やける":["japanese"],"やさい":["japanese"],"やさしい":["japanese"],"やすい":["japanese"],"やすたろう":["japanese"],"やすみ":["japanese"],"やせる":["japanese"],"やそう":["japanese"],"やたい":["japanese"],"やちん":["japanese"],"やっと":["japanese"],"やっぱり":["japanese"],"やぶる":["japanese"],"やめる":["japanese"],"ややこしい":["japanese"],"やよい":["japanese"],"やわらかい":["japanese"],"ゆうき":["japanese"],"ゆうびんきょく":["japanese"],"ゆうべ":["japanese"],"ゆうめい":["japanese"],"ゆけつ":["japanese"],"ゆしゅつ":["japanese"],"ゆせん":["japanese"],"ゆそう":["japanese"],"ゆたか":["japanese"],"ゆちゃく":["japanese"],"ゆでる":["japanese"],"ゆにゅう":["japanese"],"ゆびわ":["japanese"],"ゆらい":["japanese"],"ゆれる":["japanese"],"ようい":["japanese"],"ようか":["japanese"],"ようきゅう":["japanese"],"ようじ":["japanese"],"ようす":["japanese"],"ようちえん":["japanese"],"よかぜ":["japanese"],"よかん":["japanese"],"よきん":["japanese"],"よくせい":["japanese"],"よくぼう":["japanese"],"よけい":["japanese"],"よごれる":["japanese"],"よさん":["japanese"],"よしゅう":["japanese"],"よそう":["japanese"],"よそく":["japanese"],"よっか":["japanese"],"よてい":["japanese"],"よどがわく":["japanese"],"よねつ":["japanese"],"よやく":["japanese"],"よゆう":["japanese"],"よろこぶ":["japanese"],"よろしい":["japanese"],"らいう":["japanese"],"らくがき":["japanese"],"らくご":["japanese"],"らくさつ":["japanese"],"らくだ":["japanese"],"らしんばん":["japanese"],"らせん":["japanese"],"らぞく":["japanese"],"らたい":["japanese"],"らっか":["japanese"],"られつ":["japanese"],"りえき":["japanese"],"りかい":["japanese"],"りきさく":["japanese"],"りきせつ":["japanese"],"りくぐん":["japanese"],"りくつ":["japanese"],"りけん":["japanese"],"りこう":["japanese"],"りせい":["japanese"],"りそう":["japanese"],"りそく":["japanese"],"りてん":["japanese"],"りねん":["japanese"],"りゆう":["japanese"],"りゅうがく":["japanese"],"りよう":["japanese"],"りょうり":["japanese"],"りょかん":["japanese"],"りょくちゃ":["japanese"],"りょこう":["japanese"],"りりく":["japanese"],"りれき":["japanese"],"りろん":["japanese"],"りんご":["japanese"],"るいけい":["japanese"],"るいさい":["japanese"],"るいじ":["japanese"],"るいせき":["japanese"],"るすばん":["japanese"],"るりがわら":["japanese"],"れいかん":["japanese"],"れいぎ":["japanese"],"れいせい":["japanese"],"れいぞうこ":["japanese"],"れいとう":["japanese"],"れいぼう":["japanese"],"れきし":["japanese"],"れきだい":["japanese"],"れんあい":["japanese"],"れんけい":["japanese"],"れんこん":["japanese"],"れんさい":["japanese"],"れんしゅう":["japanese"],"れんぞく":["japanese"],"れんらく":["japanese"],"ろうか":["japanese"],"ろうご":["japanese"],"ろうじん":["japanese"],"ろうそく":["japanese"],"ろくが":["japanese"],"ろこつ":["japanese"],"ろじうら":["japanese"],"ろしゅつ":["japanese"],"ろせん":["japanese"],"ろてん":["japanese"],"ろめん":["japanese"],"ろれつ":["japanese"],"ろんぎ":["japanese"],"ろんぱ":["japanese"],"ろんぶん":["japanese"],"ろんり":["japanese"],"わかす":["japanese"],"わかめ":["japanese"],"わかやま":["japanese"],"わかれる":["japanese"],"わしつ":["japanese"],"わじまし":["japanese"],"わすれもの":["japanese"],"わらう":["japanese"],"われる":["japanese"],"가격":["korean"],"가끔":["korean"],"가난":["korean"],"가능":["korean"],"가득":["korean"],"가르침":["korean"],"가뭄":["korean"],"가방":["korean"],"가상":["korean"],"가슴":["korean"],"가운데":["korean"],"가을":["korean"],"가이드":["korean"],"가입":["korean"],"가장":["korean"],"가정":["korean"],"가족":["korean"],"가죽":["korean"],"각오":["korean"],"각자":["korean"],"간격":["korean"],"간부":["korean"],"간섭":["korean"],"간장":["korean"],"간접":["korean"],"간판":["korean"],"갈등":["korean"],"갈비":["korean"],"갈색":["korean"],"갈증":["korean"],"감각":["korean"],"감기":["korean"],"감소":["korean"],"감수성":["korean"],"감자":["korean"],"감정":["korean"],"갑자기":["korean"],"강남":["korean"],"강당":["korean"],"강도":["korean"],"강력히":["korean"],"강변":["korean"],"강북":["korean"],"강사":["korean"],"강수량":["korean"],"강아지":["korean"],"강원도":["korean"],"강의":["korean"],"강제":["korean"],"강조":["korean"],"같이":["korean"],"개구리":["korean"],"개나리":["korean"],"개방":["korean"],"개별":["korean"],"개선":["korean"],"개성":["korean"],"개인":["korean"],"객관적":["korean"],"거실":["korean"],"거액":["korean"],"거울":["korean"],"거짓":["korean"],"거품":["korean"],"걱정":["korean"],"건강":["korean"],"건물":["korean"],"건설":["korean"],"건조":["korean"],"건축":["korean"],"걸음":["korean"],"검사":["korean"],"검토":["korean"],"게시판":["korean"],"게임":["korean"],"겨울":["korean"],"견해":["korean"],"결과":["korean"],"결국":["korean"],"결론":["korean"],"결석":["korean"],"결승":["korean"],"결심":["korean"],"결정":["korean"],"결혼":["korean"],"경계":["korean"],"경고":["korean"],"경기":["korean"],"경력":["korean"],"경복궁":["korean"],"경비":["korean"],"경상도":["korean"],"경영":["korean"],"경우":["korean"],"경쟁":["korean"],"경제":["korean"],"경주":["korean"],"경찰":["korean"],"경치":["korean"],"경향":["korean"],"경험":["korean"],"계곡":["korean"],"계단":["korean"],"계란":["korean"],"계산":["korean"],"계속":["korean"],"계약":["korean"],"계절":["korean"],"계층":["korean"],"계획":["korean"],"고객":["korean"],"고구려":["korean"],"고궁":["korean"],"고급":["korean"],"고등학생":["korean"],"고무신":["korean"],"고민":["korean"],"고양이":["korean"],"고장":["korean"],"고전":["korean"],"고집":["korean"],"고춧가루":["korean"],"고통":["korean"],"고향":["korean"],"곡식":["korean"],"골목":["korean"],"골짜기":["korean"],"골프":["korean"],"공간":["korean"],"공개":["korean"],"공격":["korean"],"공군":["korean"],"공급":["korean"],"공기":["korean"],"공동":["korean"],"공무원":["korean"],"공부":["korean"],"공사":["korean"],"공식":["korean"],"공업":["korean"],"공연":["korean"],"공원":["korean"],"공장":["korean"],"공짜":["korean"],"공책":["korean"],"공통":["korean"],"공포":["korean"],"공항":["korean"],"공휴일":["korean"],"과목":["korean"],"과일":["korean"],"과장":["korean"],"과정":["korean"],"과학":["korean"],"관객":["korean"],"관계":["korean"],"관광":["korean"],"관념":["korean"],"관람":["korean"],"관련":["korean"],"관리":["korean"],"관습":["korean"],"관심":["korean"],"관점":["korean"],"관찰":["korean"],"광경":["korean"],"광고":["korean"],"광장":["korean"],"광주":["korean"],"괴로움":["korean"],"굉장히":["korean"],"교과서":["korean"],"교문":["korean"],"교복":["korean"],"교실":["korean"],"교양":["korean"],"교육":["korean"],"교장":["korean"],"교직":["korean"],"교통":["korean"],"교환":["korean"],"교훈":["korean"],"구경":["korean"],"구름":["korean"],"구멍":["korean"],"구별":["korean"],"구분":["korean"],"구석":["korean"],"구성":["korean"],"구속":["korean"],"구역":["korean"],"구입":["korean"],"구청":["korean"],"구체적":["korean"],"국가":["korean"],"국기":["korean"],"국내":["korean"],"국립":["korean"],"국물":["korean"],"국민":["korean"],"국수":["korean"],"국어":["korean"],"국왕":["korean"],"국적":["korean"],"국제":["korean"],"국회":["korean"],"군대":["korean"],"군사":["korean"],"군인":["korean"],"궁극적":["korean"],"권리":["korean"],"권위":["korean"],"권투":["korean"],"귀국":["korean"],"귀신":["korean"],"규정":["korean"],"규칙":["korean"],"균형":["korean"],"그날":["korean"],"그냥":["korean"],"그늘":["korean"],"그러나":["korean"],"그룹":["korean"],"그릇":["korean"],"그림":["korean"],"그제서야":["korean"],"그토록":["korean"],"극복":["korean"],"극히":["korean"],"근거":["korean"],"근교":["korean"],"근래":["korean"],"근로":["korean"],"근무":["korean"],"근본":["korean"],"근원":["korean"],"근육":["korean"],"근처":["korean"],"글씨":["korean"],"글자":["korean"],"금강산":["korean"],"금고":["korean"],"금년":["korean"],"금메달":["korean"],"금액":["korean"],"금연":["korean"],"금요일":["korean"],"금지":["korean"],"긍정적":["korean"],"기간":["korean"],"기관":["korean"],"기념":["korean"],"기능":["korean"],"기독교":["korean"],"기둥":["korean"],"기록":["korean"],"기름":["korean"],"기법":["korean"],"기본":["korean"],"기분":["korean"],"기쁨":["korean"],"기숙사":["korean"],"기술":["korean"],"기억":["korean"],"기업":["korean"],"기온":["korean"],"기운":["korean"],"기원":["korean"],"기적":["korean"],"기준":["korean"],"기침":["korean"],"기혼":["korean"],"기획":["korean"],"긴급":["korean"],"긴장":["korean"],"길이":["korean"],"김밥":["korean"],"김치":["korean"],"김포공항":["korean"],"깍두기":["korean"],"깜빡":["korean"],"깨달음":["korean"],"깨소금":["korean"],"껍질":["korean"],"꼭대기":["korean"],"꽃잎":["korean"],"나들이":["korean"],"나란히":["korean"],"나머지":["korean"],"나물":["korean"],"나침반":["korean"],"나흘":["korean"],"낙엽":["korean"],"난방":["korean"],"날개":["korean"],"날씨":["korean"],"날짜":["korean"],"남녀":["korean"],"남대문":["korean"],"남매":["korean"],"남산":["korean"],"남자":["korean"],"남편":["korean"],"남학생":["korean"],"낭비":["korean"],"낱말":["korean"],"내년":["korean"],"내용":["korean"],"내일":["korean"],"냄비":["korean"],"냄새":["korean"],"냇물":["korean"],"냉동":["korean"],"냉면":["korean"],"냉방":["korean"],"냉장고":["korean"],"넥타이":["korean"],"넷째":["korean"],"노동":["korean"],"노란색":["korean"],"노력":["korean"],"노인":["korean"],"녹음":["korean"],"녹차":["korean"],"녹화":["korean"],"논리":["korean"],"논문":["korean"],"논쟁":["korean"],"놀이":["korean"],"농구":["korean"],"농담":["korean"],"농민":["korean"],"농부":["korean"],"농업":["korean"],"농장":["korean"],"농촌":["korean"],"높이":["korean"],"눈동자":["korean"],"눈물":["korean"],"눈썹":["korean"],"뉴욕":["korean"],"느낌":["korean"],"늑대":["korean"],"능동적":["korean"],"능력":["korean"],"다방":["korean"],"다양성":["korean"],"다음":["korean"],"다이어트":["korean"],"다행":["korean"],"단계":["korean"],"단골":["korean"],"단독":["korean"],"단맛":["korean"],"단순":["korean"],"단어":["korean"],"단위":["korean"],"단점":["korean"],"단체":["korean"],"단추":["korean"],"단편":["korean"],"단풍":["korean"],"달걀":["korean"],"달러":["korean"],"달력":["korean"],"달리":["korean"],"닭고기":["korean"],"담당":["korean"],"담배":["korean"],"담요":["korean"],"담임":["korean"],"답변":["korean"],"답장":["korean"],"당근":["korean"],"당분간":["korean"],"당연히":["korean"],"당장":["korean"],"대규모":["korean"],"대낮":["korean"],"대단히":["korean"],"대답":["korean"],"대도시":["korean"],"대략":["korean"],"대량":["korean"],"대륙":["korean"],"대문":["korean"],"대부분":["korean"],"대신":["korean"],"대응":["korean"],"대장":["korean"],"대전":["korean"],"대접":["korean"],"대중":["korean"],"대책":["korean"],"대출":["korean"],"대충":["korean"],"대통령":["korean"],"대학":["korean"],"대한민국":["korean"],"대합실":["korean"],"대형":["korean"],"덩어리":["korean"],"데이트":["korean"],"도대체":["korean"],"도덕":["korean"],"도둑":["korean"],"도망":["korean"],"도서관":["korean"],"도심":["korean"],"도움":["korean"],"도입":["korean"],"도자기":["korean"],"도저히":["korean"],"도전":["korean"],"도중":["korean"],"도착":["korean"],"독감":["korean"],"독립":["korean"],"독서":["korean"],"독일":["korean"],"독창적":["korean"],"동화책":["korean"],"뒷모습":["korean"],"뒷산":["korean"],"딸아이":["korean"],"마누라":["korean"],"마늘":["korean"],"마당":["korean"],"마라톤":["korean"],"마련":["korean"],"마무리":["korean"],"마사지":["korean"],"마약":["korean"],"마요네즈":["korean"],"마을":["korean"],"마음":["korean"],"마이크":["korean"],"마중":["korean"],"마지막":["korean"],"마찬가지":["korean"],"마찰":["korean"],"마흔":["korean"],"막걸리":["korean"],"막내":["korean"],"막상":["korean"],"만남":["korean"],"만두":["korean"],"만세":["korean"],"만약":["korean"],"만일":["korean"],"만점":["korean"],"만족":["korean"],"만화":["korean"],"많이":["korean"],"말기":["korean"],"말씀":["korean"],"말투":["korean"],"맘대로":["korean"],"망원경":["korean"],"매년":["korean"],"매달":["korean"],"매력":["korean"],"매번":["korean"],"매스컴":["korean"],"매일":["korean"],"매장":["korean"],"맥주":["korean"],"먹이":["korean"],"먼저":["korean"],"먼지":["korean"],"멀리":["korean"],"메일":["korean"],"며느리":["korean"],"며칠":["korean"],"면담":["korean"],"멸치":["korean"],"명단":["korean"],"명령":["korean"],"명예":["korean"],"명의":["korean"],"명절":["korean"],"명칭":["korean"],"명함":["korean"],"모금":["korean"],"모니터":["korean"],"모델":["korean"],"모든":["korean"],"모범":["korean"],"모습":["korean"],"모양":["korean"],"모임":["korean"],"모조리":["korean"],"모집":["korean"],"모퉁이":["korean"],"목걸이":["korean"],"목록":["korean"],"목사":["korean"],"목소리":["korean"],"목숨":["korean"],"목적":["korean"],"목표":["korean"],"몰래":["korean"],"몸매":["korean"],"몸무게":["korean"],"몸살":["korean"],"몸속":["korean"],"몸짓":["korean"],"몸통":["korean"],"몹시":["korean"],"무관심":["korean"],"무궁화":["korean"],"무더위":["korean"],"무덤":["korean"],"무릎":["korean"],"무슨":["korean"],"무엇":["korean"],"무역":["korean"],"무용":["korean"],"무조건":["korean"],"무지개":["korean"],"무척":["korean"],"문구":["korean"],"문득":["korean"],"문법":["korean"],"문서":["korean"],"문제":["korean"],"문학":["korean"],"문화":["korean"],"물가":["korean"],"물건":["korean"],"물결":["korean"],"물고기":["korean"],"물론":["korean"],"물리학":["korean"],"물음":["korean"],"물질":["korean"],"물체":["korean"],"미국":["korean"],"미디어":["korean"],"미사일":["korean"],"미술":["korean"],"미역":["korean"],"미용실":["korean"],"미움":["korean"],"미인":["korean"],"미팅":["korean"],"미혼":["korean"],"민간":["korean"],"민족":["korean"],"민주":["korean"],"믿음":["korean"],"밀가루":["korean"],"밀리미터":["korean"],"밑바닥":["korean"],"바가지":["korean"],"바구니":["korean"],"바나나":["korean"],"바늘":["korean"],"바닥":["korean"],"바닷가":["korean"],"바람":["korean"],"바이러스":["korean"],"바탕":["korean"],"박물관":["korean"],"박사":["korean"],"박수":["korean"],"반대":["korean"],"반드시":["korean"],"반말":["korean"],"반발":["korean"],"반성":["korean"],"반응":["korean"],"반장":["korean"],"반죽":["korean"],"반지":["korean"],"반찬":["korean"],"받침":["korean"],"발가락":["korean"],"발걸음":["korean"],"발견":["korean"],"발달":["korean"],"발레":["korean"],"발목":["korean"],"발바닥":["korean"],"발생":["korean"],"발음":["korean"],"발자국":["korean"],"발전":["korean"],"발톱":["korean"],"발표":["korean"],"밤하늘":["korean"],"밥그릇":["korean"],"밥맛":["korean"],"밥상":["korean"],"밥솥":["korean"],"방금":["korean"],"방면":["korean"],"방문":["korean"],"방바닥":["korean"],"방법":["korean"],"방송":["korean"],"방식":["korean"],"방안":["korean"],"방울":["korean"],"방지":["korean"],"방학":["korean"],"방해":["korean"],"방향":["korean"],"배경":["korean"],"배꼽":["korean"],"배달":["korean"],"배드민턴":["korean"],"백두산":["korean"],"백색":["korean"],"백성":["korean"],"백인":["korean"],"백제":["korean"],"백화점":["korean"],"버릇":["korean"],"버섯":["korean"],"버튼":["korean"],"번개":["korean"],"번역":["korean"],"번지":["korean"],"번호":["korean"],"벌금":["korean"],"벌레":["korean"],"벌써":["korean"],"범위":["korean"],"범인":["korean"],"범죄":["korean"],"법률":["korean"],"법원":["korean"],"법적":["korean"],"법칙":["korean"],"베이징":["korean"],"벨트":["korean"],"변경":["korean"],"변동":["korean"],"변명":["korean"],"변신":["korean"],"변호사":["korean"],"변화":["korean"],"별도":["korean"],"별명":["korean"],"별일":["korean"],"병실":["korean"],"병아리":["korean"],"병원":["korean"],"보관":["korean"],"보너스":["korean"],"보라색":["korean"],"보람":["korean"],"보름":["korean"],"보상":["korean"],"보안":["korean"],"보자기":["korean"],"보장":["korean"],"보전":["korean"],"보존":["korean"],"보통":["korean"],"보편적":["korean"],"보험":["korean"],"복도":["korean"],"복사":["korean"],"복숭아":["korean"],"복습":["korean"],"볶음":["korean"],"본격적":["korean"],"본래":["korean"],"본부":["korean"],"본사":["korean"],"본성":["korean"],"본인":["korean"],"본질":["korean"],"볼펜":["korean"],"봉사":["korean"],"봉지":["korean"],"봉투":["korean"],"부근":["korean"],"부끄러움":["korean"],"부담":["korean"],"부동산":["korean"],"부문":["korean"],"부분":["korean"],"부산":["korean"],"부상":["korean"],"부엌":["korean"],"부인":["korean"],"부작용":["korean"],"부장":["korean"],"부정":["korean"],"부족":["korean"],"부지런히":["korean"],"부친":["korean"],"부탁":["korean"],"부품":["korean"],"부회장":["korean"],"북부":["korean"],"북한":["korean"],"분노":["korean"],"분량":["korean"],"분리":["korean"],"분명":["korean"],"분석":["korean"],"분야":["korean"],"분위기":["korean"],"분필":["korean"],"분홍색":["korean"],"불고기":["korean"],"불과":["korean"],"불교":["korean"],"불꽃":["korean"],"불만":["korean"],"불법":["korean"],"불빛":["korean"],"불안":["korean"],"불이익":["korean"],"불행":["korean"],"브랜드":["korean"],"비극":["korean"],"비난":["korean"],"비닐":["korean"],"비둘기":["korean"],"비디오":["korean"],"비로소":["korean"],"비만":["korean"],"비명":["korean"],"비밀":["korean"],"비바람":["korean"],"비빔밥":["korean"],"비상":["korean"],"비용":["korean"],"비율":["korean"],"비중":["korean"],"비타민":["korean"],"비판":["korean"],"빌딩":["korean"],"빗물":["korean"],"빗방울":["korean"],"빗줄기":["korean"],"빛깔":["korean"],"빨간색":["korean"],"빨래":["korean"],"빨리":["korean"],"사건":["korean"],"사계절":["korean"],"사나이":["korean"],"사냥":["korean"],"사람":["korean"],"사랑":["korean"],"사립":["korean"],"사모님":["korean"],"사물":["korean"],"사방":["korean"],"사상":["korean"],"사생활":["korean"],"사설":["korean"],"사슴":["korean"],"사실":["korean"],"사업":["korean"],"사용":["korean"],"사월":["korean"],"사장":["korean"],"사전":["korean"],"사진":["korean"],"사촌":["korean"],"사춘기":["korean"],"사탕":["korean"],"사투리":["korean"],"사흘":["korean"],"산길":["korean"],"산부인과":["korean"],"산업":["korean"],"산책":["korean"],"살림":["korean"],"살인":["korean"],"살짝":["korean"],"삼계탕":["korean"],"삼국":["korean"],"삼십":["korean"],"삼월":["korean"],"삼촌":["korean"],"상관":["korean"],"상금":["korean"],"상대":["korean"],"상류":["korean"],"상반기":["korean"],"상상":["korean"],"상식":["korean"],"상업":["korean"],"상인":["korean"],"상자":["korean"],"상점":["korean"],"상처":["korean"],"상추":["korean"],"상태":["korean"],"상표":["korean"],"상품":["korean"],"상황":["korean"],"새벽":["korean"],"색깔":["korean"],"색연필":["korean"],"생각":["korean"],"생명":["korean"],"생물":["korean"],"생방송":["korean"],"생산":["korean"],"생선":["korean"],"생신":["korean"],"생일":["korean"],"생활":["korean"],"서랍":["korean"],"서른":["korean"],"서명":["korean"],"서민":["korean"],"서비스":["korean"],"서양":["korean"],"서울":["korean"],"서적":["korean"],"서점":["korean"],"서쪽":["korean"],"서클":["korean"],"석사":["korean"],"석유":["korean"],"선거":["korean"],"선물":["korean"],"선배":["korean"],"선생":["korean"],"선수":["korean"],"선원":["korean"],"선장":["korean"],"선전":["korean"],"선택":["korean"],"선풍기":["korean"],"설거지":["korean"],"설날":["korean"],"설렁탕":["korean"],"설명":["korean"],"설문":["korean"],"설사":["korean"],"설악산":["korean"],"설치":["korean"],"설탕":["korean"],"섭씨":["korean"],"성공":["korean"],"성당":["korean"],"성명":["korean"],"성별":["korean"],"성인":["korean"],"성장":["korean"],"성적":["korean"],"성질":["korean"],"성함":["korean"],"세금":["korean"],"세미나":["korean"],"세상":["korean"],"세월":["korean"],"세종대왕":["korean"],"세탁":["korean"],"센터":["korean"],"센티미터":["korean"],"셋째":["korean"],"소규모":["korean"],"소극적":["korean"],"소금":["korean"],"소나기":["korean"],"소년":["korean"],"소득":["korean"],"소망":["korean"],"소문":["korean"],"소설":["korean"],"소속":["korean"],"소아과":["korean"],"소용":["korean"],"소원":["korean"],"소음":["korean"],"소중히":["korean"],"소지품":["korean"],"소질":["korean"],"소풍":["korean"],"소형":["korean"],"속담":["korean"],"속도":["korean"],"속옷":["korean"],"손가락":["korean"],"손길":["korean"],"손녀":["korean"],"손님":["korean"],"손등":["korean"],"손목":["korean"],"손뼉":["korean"],"손실":["korean"],"손질":["korean"],"손톱":["korean"],"손해":["korean"],"솔직히":["korean"],"솜씨":["korean"],"송아지":["korean"],"송이":["korean"],"송편":["korean"],"쇠고기":["korean"],"쇼핑":["korean"],"수건":["korean"],"수년":["korean"],"수단":["korean"],"수돗물":["korean"],"수동적":["korean"],"수면":["korean"],"수명":["korean"],"수박":["korean"],"수상":["korean"],"수석":["korean"],"수술":["korean"],"수시로":["korean"],"수업":["korean"],"수염":["korean"],"수영":["korean"],"수입":["korean"],"수준":["korean"],"수집":["korean"],"수출":["korean"],"수컷":["korean"],"수필":["korean"],"수학":["korean"],"수험생":["korean"],"수화기":["korean"],"숙녀":["korean"],"숙소":["korean"],"숙제":["korean"],"순간":["korean"],"순서":["korean"],"순수":["korean"],"순식간":["korean"],"순위":["korean"],"숟가락":["korean"],"술병":["korean"],"술집":["korean"],"숫자":["korean"],"스님":["korean"],"스물":["korean"],"스스로":["korean"],"스승":["korean"],"스웨터":["korean"],"스위치":["korean"],"스케이트":["korean"],"스튜디오":["korean"],"스트레스":["korean"],"스포츠":["korean"],"슬쩍":["korean"],"슬픔":["korean"],"습관":["korean"],"습기":["korean"],"승객":["korean"],"승리":["korean"],"승부":["korean"],"승용차":["korean"],"승진":["korean"],"시각":["korean"],"시간":["korean"],"시골":["korean"],"시금치":["korean"],"시나리오":["korean"],"시댁":["korean"],"시리즈":["korean"],"시멘트":["korean"],"시민":["korean"],"시부모":["korean"],"시선":["korean"],"시설":["korean"],"시스템":["korean"],"시아버지":["korean"],"시어머니":["korean"],"시월":["korean"],"시인":["korean"],"시일":["korean"],"시작":["korean"],"시장":["korean"],"시절":["korean"],"시점":["korean"],"시중":["korean"],"시즌":["korean"],"시집":["korean"],"시청":["korean"],"시합":["korean"],"시험":["korean"],"식구":["korean"],"식기":["korean"],"식당":["korean"],"식량":["korean"],"식료품":["korean"],"식물":["korean"],"식빵":["korean"],"식사":["korean"],"식생활":["korean"],"식초":["korean"],"식탁":["korean"],"식품":["korean"],"신고":["korean"],"신규":["korean"],"신념":["korean"],"신문":["korean"],"신발":["korean"],"신비":["korean"],"신사":["korean"],"신세":["korean"],"신용":["korean"],"신제품":["korean"],"신청":["korean"],"신체":["korean"],"신화":["korean"],"실감":["korean"],"실내":["korean"],"실력":["korean"],"실례":["korean"],"실망":["korean"],"실수":["korean"],"실습":["korean"],"실시":["korean"],"실장":["korean"],"실정":["korean"],"실질적":["korean"],"실천":["korean"],"실체":["korean"],"실컷":["korean"],"실태":["korean"],"실패":["korean"],"실험":["korean"],"실현":["korean"],"심리":["korean"],"심부름":["korean"],"심사":["korean"],"심장":["korean"],"심정":["korean"],"심판":["korean"],"쌍둥이":["korean"],"씨름":["korean"],"씨앗":["korean"],"아가씨":["korean"],"아나운서":["korean"],"아드님":["korean"],"아들":["korean"],"아쉬움":["korean"],"아스팔트":["korean"],"아시아":["korean"],"아울러":["korean"],"아저씨":["korean"],"아줌마":["korean"],"아직":["korean"],"아침":["korean"],"아파트":["korean"],"아프리카":["korean"],"아픔":["korean"],"아홉":["korean"],"아흔":["korean"],"악기":["korean"],"악몽":["korean"],"악수":["korean"],"안개":["korean"],"안경":["korean"],"안과":["korean"],"안내":["korean"],"안녕":["korean"],"안동":["korean"],"안방":["korean"],"안부":["korean"],"안주":["korean"],"알루미늄":["korean"],"알코올":["korean"],"암시":["korean"],"암컷":["korean"],"압력":["korean"],"앞날":["korean"],"앞문":["korean"],"애인":["korean"],"애정":["korean"],"액수":["korean"],"앨범":["korean"],"야간":["korean"],"야단":["korean"],"야옹":["korean"],"약간":["korean"],"약국":["korean"],"약속":["korean"],"약수":["korean"],"약점":["korean"],"약품":["korean"],"약혼녀":["korean"],"양념":["korean"],"양력":["korean"],"양말":["korean"],"양배추":["korean"],"양주":["korean"],"양파":["korean"],"어둠":["korean"],"어려움":["korean"],"어른":["korean"],"어젯밤":["korean"],"어쨌든":["korean"],"어쩌다가":["korean"],"어쩐지":["korean"],"언니":["korean"],"언덕":["korean"],"언론":["korean"],"언어":["korean"],"얼굴":["korean"],"얼른":["korean"],"얼음":["korean"],"얼핏":["korean"],"엄마":["korean"],"업무":["korean"],"업종":["korean"],"업체":["korean"],"엉덩이":["korean"],"엉망":["korean"],"엉터리":["korean"],"엊그제":["korean"],"에너지":["korean"],"에어컨":["korean"],"엔진":["korean"],"여건":["korean"],"여고생":["korean"],"여관":["korean"],"여군":["korean"],"여권":["korean"],"여대생":["korean"],"여덟":["korean"],"여동생":["korean"],"여든":["korean"],"여론":["korean"],"여름":["korean"],"여섯":["korean"],"여성":["korean"],"여왕":["korean"],"여인":["korean"],"여전히":["korean"],"여직원":["korean"],"여학생":["korean"],"여행":["korean"],"역사":["korean"],"역시":["korean"],"역할":["korean"],"연결":["korean"],"연구":["korean"],"연극":["korean"],"연기":["korean"],"연락":["korean"],"연설":["korean"],"연세":["korean"],"연속":["korean"],"연습":["korean"],"연애":["korean"],"연예인":["korean"],"연인":["korean"],"연장":["korean"],"연주":["korean"],"연출":["korean"],"연필":["korean"],"연합":["korean"],"연휴":["korean"],"열기":["korean"],"열매":["korean"],"열쇠":["korean"],"열심히":["korean"],"열정":["korean"],"열차":["korean"],"열흘":["korean"],"염려":["korean"],"엽서":["korean"],"영국":["korean"],"영남":["korean"],"영상":["korean"],"영양":["korean"],"영역":["korean"],"영웅":["korean"],"영원히":["korean"],"영하":["korean"],"영향":["korean"],"영혼":["korean"],"영화":["korean"],"옆구리":["korean"],"옆방":["korean"],"옆집":["korean"],"예감":["korean"],"예금":["korean"],"예방":["korean"],"예산":["korean"],"예상":["korean"],"예선":["korean"],"예술":["korean"],"예습":["korean"],"예식장":["korean"],"예약":["korean"],"예전":["korean"],"예절":["korean"],"예정":["korean"],"예컨대":["korean"],"옛날":["korean"],"오늘":["korean"],"오락":["korean"],"오랫동안":["korean"],"오렌지":["korean"],"오로지":["korean"],"오른발":["korean"],"오븐":["korean"],"오십":["korean"],"오염":["korean"],"오월":["korean"],"오전":["korean"],"오직":["korean"],"오징어":["korean"],"오페라":["korean"],"오피스텔":["korean"],"오히려":["korean"],"옥상":["korean"],"옥수수":["korean"],"온갖":["korean"],"온라인":["korean"],"온몸":["korean"],"온종일":["korean"],"온통":["korean"],"올가을":["korean"],"올림픽":["korean"],"올해":["korean"],"옷차림":["korean"],"와이셔츠":["korean"],"와인":["korean"],"완성":["korean"],"완전":["korean"],"왕비":["korean"],"왕자":["korean"],"왜냐하면":["korean"],"왠지":["korean"],"외갓집":["korean"],"외국":["korean"],"외로움":["korean"],"외삼촌":["korean"],"외출":["korean"],"외침":["korean"],"외할머니":["korean"],"왼발":["korean"],"왼손":["korean"],"왼쪽":["korean"],"요금":["korean"],"요일":["korean"],"요즘":["korean"],"요청":["korean"],"용기":["korean"],"용서":["korean"],"용어":["korean"],"우산":["korean"],"우선":["korean"],"우승":["korean"],"우연히":["korean"],"우정":["korean"],"우체국":["korean"],"우편":["korean"],"운동":["korean"],"운명":["korean"],"운반":["korean"],"운전":["korean"],"운행":["korean"],"울산":["korean"],"울음":["korean"],"움직임":["korean"],"웃어른":["korean"],"웃음":["korean"],"워낙":["korean"],"원고":["korean"],"원래":["korean"],"원서":["korean"],"원숭이":["korean"],"원인":["korean"],"원장":["korean"],"원피스":["korean"],"월급":["korean"],"월드컵":["korean"],"월세":["korean"],"월요일":["korean"],"웨이터":["korean"],"위반":["korean"],"위법":["korean"],"위성":["korean"],"위원":["korean"],"위험":["korean"],"위협":["korean"],"윗사람":["korean"],"유난히":["korean"],"유럽":["korean"],"유명":["korean"],"유물":["korean"],"유산":["korean"],"유적":["korean"],"유치원":["korean"],"유학":["korean"],"유행":["korean"],"유형":["korean"],"육군":["korean"],"육상":["korean"],"육십":["korean"],"육체":["korean"],"은행":["korean"],"음력":["korean"],"음료":["korean"],"음반":["korean"],"음성":["korean"],"음식":["korean"],"음악":["korean"],"음주":["korean"],"의견":["korean"],"의논":["korean"],"의문":["korean"],"의복":["korean"],"의식":["korean"],"의심":["korean"],"의외로":["korean"],"의욕":["korean"],"의원":["korean"],"의학":["korean"],"이것":["korean"],"이곳":["korean"],"이념":["korean"],"이놈":["korean"],"이달":["korean"],"이대로":["korean"],"이동":["korean"],"이렇게":["korean"],"이력서":["korean"],"이론적":["korean"],"이름":["korean"],"이민":["korean"],"이발소":["korean"],"이별":["korean"],"이불":["korean"],"이빨":["korean"],"이상":["korean"],"이성":["korean"],"이슬":["korean"],"이야기":["korean"],"이용":["korean"],"이웃":["korean"],"이월":["korean"],"이윽고":["korean"],"이익":["korean"],"이전":["korean"],"이중":["korean"],"이튿날":["korean"],"이틀":["korean"],"이혼":["korean"],"인간":["korean"],"인격":["korean"],"인공":["korean"],"인구":["korean"],"인근":["korean"],"인기":["korean"],"인도":["korean"],"인류":["korean"],"인물":["korean"],"인생":["korean"],"인쇄":["korean"],"인연":["korean"],"인원":["korean"],"인재":["korean"],"인종":["korean"],"인천":["korean"],"인체":["korean"],"인터넷":["korean"],"인하":["korean"],"인형":["korean"],"일곱":["korean"],"일기":["korean"],"일단":["korean"],"일대":["korean"],"일등":["korean"],"일반":["korean"],"일본":["korean"],"일부":["korean"],"일상":["korean"],"일생":["korean"],"일손":["korean"],"일요일":["korean"],"일월":["korean"],"일정":["korean"],"일종":["korean"],"일주일":["korean"],"일찍":["korean"],"일체":["korean"],"일치":["korean"],"일행":["korean"],"일회용":["korean"],"임금":["korean"],"임무":["korean"],"입대":["korean"],"입력":["korean"],"입맛":["korean"],"입사":["korean"],"입술":["korean"],"입시":["korean"],"입원":["korean"],"입장":["korean"],"입학":["korean"],"자가용":["korean"],"자격":["korean"],"자극":["korean"],"자동":["korean"],"자랑":["korean"],"자부심":["korean"],"자식":["korean"],"자신":["korean"],"자연":["korean"],"자원":["korean"],"자율":["korean"],"자전거":["korean"],"자정":["korean"],"자존심":["korean"],"자판":["korean"],"작가":["korean"],"작년":["korean"],"작성":["korean"],"작업":["korean"],"작용":["korean"],"작은딸":["korean"],"작품":["korean"],"잔디":["korean"],"잔뜩":["korean"],"잔치":["korean"],"잘못":["korean"],"잠깐":["korean"],"잠수함":["korean"],"잠시":["korean"],"잠옷":["korean"],"잠자리":["korean"],"잡지":["korean"],"장관":["korean"],"장군":["korean"],"장기간":["korean"],"장래":["korean"],"장례":["korean"],"장르":["korean"],"장마":["korean"],"장면":["korean"],"장모":["korean"],"장미":["korean"],"장비":["korean"],"장사":["korean"],"장소":["korean"],"장식":["korean"],"장애인":["korean"],"장인":["korean"],"장점":["korean"],"장차":["korean"],"장학금":["korean"],"재능":["korean"],"재빨리":["korean"],"재산":["korean"],"재생":["korean"],"재작년":["korean"],"재정":["korean"],"재채기":["korean"],"재판":["korean"],"재학":["korean"],"재활용":["korean"],"저것":["korean"],"저고리":["korean"],"저곳":["korean"],"저녁":["korean"],"저런":["korean"],"저렇게":["korean"],"저번":["korean"],"저울":["korean"],"저절로":["korean"],"저축":["korean"],"적극":["korean"],"적당히":["korean"],"적성":["korean"],"적용":["korean"],"적응":["korean"],"전개":["korean"],"전공":["korean"],"전기":["korean"],"전달":["korean"],"전라도":["korean"],"전망":["korean"],"전문":["korean"],"전반":["korean"],"전부":["korean"],"전세":["korean"],"전시":["korean"],"전용":["korean"],"전자":["korean"],"전쟁":["korean"],"전주":["korean"],"전철":["korean"],"전체":["korean"],"전통":["korean"],"전혀":["korean"],"전후":["korean"],"절대":["korean"],"절망":["korean"],"절반":["korean"],"절약":["korean"],"절차":["korean"],"점검":["korean"],"점수":["korean"],"점심":["korean"],"점원":["korean"],"점점":["korean"],"점차":["korean"],"접근":["korean"],"접시":["korean"],"접촉":["korean"],"젓가락":["korean"],"정거장":["korean"],"정도":["korean"],"정류장":["korean"],"정리":["korean"],"정말":["korean"],"정면":["korean"],"정문":["korean"],"정반대":["korean"],"정보":["korean"],"정부":["korean"],"정비":["korean"],"정상":["korean"],"정성":["korean"],"정오":["korean"],"정원":["korean"],"정장":["korean"],"정지":["korean"],"정치":["korean"],"정확히":["korean"],"제공":["korean"],"제과점":["korean"],"제대로":["korean"],"제목":["korean"],"제발":["korean"],"제법":["korean"],"제삿날":["korean"],"제안":["korean"],"제일":["korean"],"제작":["korean"],"제주도":["korean"],"제출":["korean"],"제품":["korean"],"제한":["korean"],"조각":["korean"],"조건":["korean"],"조금":["korean"],"조깅":["korean"],"조명":["korean"],"조미료":["korean"],"조상":["korean"],"조선":["korean"],"조용히":["korean"],"조절":["korean"],"조정":["korean"],"조직":["korean"],"존댓말":["korean"],"존재":["korean"],"졸업":["korean"],"졸음":["korean"],"종교":["korean"],"종로":["korean"],"종류":["korean"],"종소리":["korean"],"종업원":["korean"],"종종":["korean"],"종합":["korean"],"좌석":["korean"],"죄인":["korean"],"주관적":["korean"],"주름":["korean"],"주말":["korean"],"주머니":["korean"],"주먹":["korean"],"주문":["korean"],"주민":["korean"],"주방":["korean"],"주변":["korean"],"주식":["korean"],"주인":["korean"],"주일":["korean"],"주장":["korean"],"주전자":["korean"],"주택":["korean"],"준비":["korean"],"줄거리":["korean"],"줄기":["korean"],"줄무늬":["korean"],"중간":["korean"],"중계방송":["korean"],"중국":["korean"],"중년":["korean"],"중단":["korean"],"중독":["korean"],"중반":["korean"],"중부":["korean"],"중세":["korean"],"중소기업":["korean"],"중순":["korean"],"중앙":["korean"],"중요":["korean"],"중학교":["korean"],"즉석":["korean"],"즉시":["korean"],"즐거움":["korean"],"증가":["korean"],"증거":["korean"],"증권":["korean"],"증상":["korean"],"증세":["korean"],"지각":["korean"],"지갑":["korean"],"지경":["korean"],"지극히":["korean"],"지금":["korean"],"지급":["korean"],"지능":["korean"],"지름길":["korean"],"지리산":["korean"],"지방":["korean"],"지붕":["korean"],"지식":["korean"],"지역":["korean"],"지우개":["korean"],"지원":["korean"],"지적":["korean"],"지점":["korean"],"지진":["korean"],"지출":["korean"],"직선":["korean"],"직업":["korean"],"직원":["korean"],"직장":["korean"],"진급":["korean"],"진동":["korean"],"진로":["korean"],"진료":["korean"],"진리":["korean"],"진짜":["korean"],"진찰":["korean"],"진출":["korean"],"진통":["korean"],"진행":["korean"],"질문":["korean"],"질병":["korean"],"질서":["korean"],"짐작":["korean"],"집단":["korean"],"집안":["korean"],"집중":["korean"],"짜증":["korean"],"찌꺼기":["korean"],"차남":["korean"],"차라리":["korean"],"차량":["korean"],"차림":["korean"],"차별":["korean"],"차선":["korean"],"차츰":["korean"],"착각":["korean"],"찬물":["korean"],"찬성":["korean"],"참가":["korean"],"참기름":["korean"],"참새":["korean"],"참석":["korean"],"참여":["korean"],"참외":["korean"],"참조":["korean"],"찻잔":["korean"],"창가":["korean"],"창고":["korean"],"창구":["korean"],"창문":["korean"],"창밖":["korean"],"창작":["korean"],"창조":["korean"],"채널":["korean"],"채점":["korean"],"책가방":["korean"],"책방":["korean"],"책상":["korean"],"책임":["korean"],"챔피언":["korean"],"처벌":["korean"],"처음":["korean"],"천국":["korean"],"천둥":["korean"],"천장":["korean"],"천재":["korean"],"천천히":["korean"],"철도":["korean"],"철저히":["korean"],"철학":["korean"],"첫날":["korean"],"첫째":["korean"],"청년":["korean"],"청바지":["korean"],"청소":["korean"],"청춘":["korean"],"체계":["korean"],"체력":["korean"],"체온":["korean"],"체육":["korean"],"체중":["korean"],"체험":["korean"],"초등학생":["korean"],"초반":["korean"],"초밥":["korean"],"초상화":["korean"],"초순":["korean"],"초여름":["korean"],"초원":["korean"],"초저녁":["korean"],"초점":["korean"],"초청":["korean"],"초콜릿":["korean"],"촛불":["korean"],"총각":["korean"],"총리":["korean"],"총장":["korean"],"촬영":["korean"],"최근":["korean"],"최상":["korean"],"최선":["korean"],"최신":["korean"],"최악":["korean"],"최종":["korean"],"추석":["korean"],"추억":["korean"],"추진":["korean"],"추천":["korean"],"추측":["korean"],"축구":["korean"],"축소":["korean"],"축제":["korean"],"축하":["korean"],"출근":["korean"],"출발":["korean"],"출산":["korean"],"출신":["korean"],"출연":["korean"],"출입":["korean"],"출장":["korean"],"출판":["korean"],"충격":["korean"],"충고":["korean"],"충돌":["korean"],"충분히":["korean"],"충청도":["korean"],"취업":["korean"],"취직":["korean"],"취향":["korean"],"치약":["korean"],"친구":["korean"],"친척":["korean"],"칠십":["korean"],"칠월":["korean"],"칠판":["korean"],"침대":["korean"],"침묵":["korean"],"침실":["korean"],"칫솔":["korean"],"칭찬":["korean"],"카메라":["korean"],"카운터":["korean"],"칼국수":["korean"],"캐릭터":["korean"],"캠퍼스":["korean"],"캠페인":["korean"],"커튼":["korean"],"컨디션":["korean"],"컬러":["korean"],"컴퓨터":["korean"],"코끼리":["korean"],"코미디":["korean"],"콘서트":["korean"],"콜라":["korean"],"콤플렉스":["korean"],"콩나물":["korean"],"쾌감":["korean"],"쿠데타":["korean"],"크림":["korean"],"큰길":["korean"],"큰딸":["korean"],"큰소리":["korean"],"큰아들":["korean"],"큰어머니":["korean"],"큰일":["korean"],"큰절":["korean"],"클래식":["korean"],"클럽":["korean"],"킬로":["korean"],"타입":["korean"],"타자기":["korean"],"탁구":["korean"],"탁자":["korean"],"탄생":["korean"],"태권도":["korean"],"태양":["korean"],"태풍":["korean"],"택시":["korean"],"탤런트":["korean"],"터널":["korean"],"터미널":["korean"],"테니스":["korean"],"테스트":["korean"],"테이블":["korean"],"텔레비전":["korean"],"토론":["korean"],"토마토":["korean"],"토요일":["korean"],"통계":["korean"],"통과":["korean"],"통로":["korean"],"통신":["korean"],"통역":["korean"],"통일":["korean"],"통장":["korean"],"통제":["korean"],"통증":["korean"],"통합":["korean"],"통화":["korean"],"퇴근":["korean"],"퇴원":["korean"],"퇴직금":["korean"],"튀김":["korean"],"트럭":["korean"],"특급":["korean"],"특별":["korean"],"특성":["korean"],"특수":["korean"],"특징":["korean"],"특히":["korean"],"튼튼히":["korean"],"티셔츠":["korean"],"파란색":["korean"],"파일":["korean"],"파출소":["korean"],"판결":["korean"],"판단":["korean"],"판매":["korean"],"판사":["korean"],"팔십":["korean"],"팔월":["korean"],"팝송":["korean"],"패션":["korean"],"팩스":["korean"],"팩시밀리":["korean"],"팬티":["korean"],"퍼센트":["korean"],"페인트":["korean"],"편견":["korean"],"편의":["korean"],"편지":["korean"],"편히":["korean"],"평가":["korean"],"평균":["korean"],"평생":["korean"],"평소":["korean"],"평양":["korean"],"평일":["korean"],"평화":["korean"],"포스터":["korean"],"포인트":["korean"],"포장":["korean"],"포함":["korean"],"표면":["korean"],"표정":["korean"],"표준":["korean"],"표현":["korean"],"품목":["korean"],"품질":["korean"],"풍경":["korean"],"풍속":["korean"],"풍습":["korean"],"프랑스":["korean"],"프린터":["korean"],"플라스틱":["korean"],"피곤":["korean"],"피망":["korean"],"피아노":["korean"],"필름":["korean"],"필수":["korean"],"필요":["korean"],"필자":["korean"],"필통":["korean"],"핑계":["korean"],"하느님":["korean"],"하늘":["korean"],"하드웨어":["korean"],"하룻밤":["korean"],"하반기":["korean"],"하숙집":["korean"],"하순":["korean"],"하여튼":["korean"],"하지만":["korean"],"하천":["korean"],"하품":["korean"],"하필":["korean"],"학과":["korean"],"학교":["korean"],"학급":["korean"],"학기":["korean"],"학년":["korean"],"학력":["korean"],"학번":["korean"],"학부모":["korean"],"학비":["korean"],"학생":["korean"],"학술":["korean"],"학습":["korean"],"학용품":["korean"],"학원":["korean"],"학위":["korean"],"학자":["korean"],"학점":["korean"],"한계":["korean"],"한글":["korean"],"한꺼번에":["korean"],"한낮":["korean"],"한눈":["korean"],"한동안":["korean"],"한때":["korean"],"한라산":["korean"],"한마디":["korean"],"한문":["korean"],"한번":["korean"],"한복":["korean"],"한식":["korean"],"한여름":["korean"],"한쪽":["korean"],"할머니":["korean"],"할아버지":["korean"],"할인":["korean"],"함께":["korean"],"함부로":["korean"],"합격":["korean"],"합리적":["korean"],"항공":["korean"],"항구":["korean"],"항상":["korean"],"항의":["korean"],"해결":["korean"],"해군":["korean"],"해답":["korean"],"해당":["korean"],"해물":["korean"],"해석":["korean"],"해설":["korean"],"해수욕장":["korean"],"해안":["korean"],"핵심":["korean"],"핸드백":["korean"],"햄버거":["korean"],"햇볕":["korean"],"햇살":["korean"],"행동":["korean"],"행복":["korean"],"행사":["korean"],"행운":["korean"],"행위":["korean"],"향기":["korean"],"향상":["korean"],"향수":["korean"],"허락":["korean"],"허용":["korean"],"헬기":["korean"],"현관":["korean"],"현금":["korean"],"현대":["korean"],"현상":["korean"],"현실":["korean"],"현장":["korean"],"현재":["korean"],"현지":["korean"],"혈액":["korean"],"협력":["korean"],"형부":["korean"],"형사":["korean"],"형수":["korean"],"형식":["korean"],"형제":["korean"],"형태":["korean"],"형편":["korean"],"혜택":["korean"],"호기심":["korean"],"호남":["korean"],"호랑이":["korean"],"호박":["korean"],"호텔":["korean"],"호흡":["korean"],"혹시":["korean"],"홀로":["korean"],"홈페이지":["korean"],"홍보":["korean"],"홍수":["korean"],"홍차":["korean"],"화면":["korean"],"화분":["korean"],"화살":["korean"],"화요일":["korean"],"화장":["korean"],"화학":["korean"],"확보":["korean"],"확인":["korean"],"확장":["korean"],"확정":["korean"],"환갑":["korean"],"환경":["korean"],"환영":["korean"],"환율":["korean"],"환자":["korean"],"활기":["korean"],"활동":["korean"],"활발히":["korean"],"활용":["korean"],"활짝":["korean"],"회견":["korean"],"회관":["korean"],"회복":["korean"],"회색":["korean"],"회원":["korean"],"회장":["korean"],"회전":["korean"],"횟수":["korean"],"횡단보도":["korean"],"효율적":["korean"],"후반":["korean"],"후춧가루":["korean"],"훈련":["korean"],"훨씬":["korean"],"휴식":["korean"],"휴일":["korean"],"흉내":["korean"],"흐름":["korean"],"흑백":["korean"],"흑인":["korean"],"흔적":["korean"],"흔히":["korean"],"흥미":["korean"],"흥분":["korean"],"희곡":["korean"],"희망":["korean"],"희생":["korean"],"흰색":["korean"],"힘껏":["korean"],"abacate":["portuguese"],"abaixo":["portuguese"],"abalar":["portuguese"],"abater":["portuguese"],"abduzir":["portuguese"],"abelha":["portuguese"],"aberto":["portuguese"],"abismo":["portuguese"],"abotoar":["portuguese"],"abranger":["portuguese"],"abreviar":["portuguese"],"abrigar":["portuguese"],"abrupto":["portuguese"],"absinto":["portuguese"],"absoluto":["portuguese"],"absurdo":["portuguese"],"abutre":["portuguese"],"acabado":["portuguese"],"acalmar":["portuguese"],"acampar":["portuguese"],"acanhar":["portuguese"],"acaso":["portuguese"],"aceitar":["portuguese"],"acelerar":["portuguese"],"acenar":["portuguese"],"acervo":["portuguese"],"acessar":["portuguese"],"acetona":["portuguese"],"achatar":["portuguese"],"acidez":["portuguese"],"acima":["portuguese"],"acionado":["portuguese"],"acirrar":["portuguese"],"aclamar":["portuguese"],"aclive":["portuguese"],"acolhida":["portuguese"],"acomodar":["portuguese"],"acoplar":["portuguese"],"acordar":["portuguese"],"acumular":["portuguese"],"acusador":["portuguese"],"adaptar":["portuguese"],"adega":["portuguese"],"adentro":["portuguese"],"adepto":["portuguese"],"adequar":["portuguese"],"aderente":["portuguese"],"adesivo":["portuguese"],"adeus":["portuguese"],"adiante":["portuguese"],"aditivo":["portuguese"],"adjetivo":["portuguese"],"adjunto":["portuguese"],"admirar":["portuguese"],"adorar":["portuguese"],"adquirir":["portuguese"],"adubo":["portuguese"],"adverso":["portuguese"],"advogado":["portuguese"],"aeronave":["portuguese"],"afastar":["portuguese"],"aferir":["portuguese"],"afetivo":["portuguese"],"afinador":["portuguese"],"afivelar":["portuguese"],"aflito":["portuguese"],"afluente":["portuguese"],"afrontar":["portuguese"],"agachar":["portuguese"],"agarrar":["portuguese"],"agasalho":["portuguese"],"agenciar":["portuguese"],"agilizar":["portuguese"],"agiota":["portuguese"],"agitado":["portuguese"],"agora":["portuguese"],"agradar":["portuguese"],"agreste":["portuguese"],"agrupar":["portuguese"],"aguardar":["portuguese"],"agulha":["portuguese"],"ajoelhar":["portuguese"],"ajudar":["portuguese"],"ajustar":["portuguese"],"alameda":["portuguese"],"alarme":["portuguese"],"alastrar":["portuguese"],"alavanca":["portuguese"],"albergue":["portuguese"],"albino":["portuguese"],"alcatra":["portuguese"],"aldeia":["portuguese"],"alecrim":["portuguese"],"alegria":["portuguese"],"alertar":["portuguese"],"alface":["portuguese"],"alfinete":["portuguese"],"algum":["portuguese"],"alheio":["portuguese"],"aliar":["portuguese"],"alicate":["portuguese"],"alienar":["portuguese"],"alinhar":["portuguese"],"aliviar":["portuguese"],"almofada":["portuguese"],"alocar":["portuguese"],"alpiste":["portuguese"],"alterar":["portuguese"],"altitude":["portuguese"],"alucinar":["portuguese"],"alugar":["portuguese"],"aluno":["portuguese"],"alusivo":["portuguese"],"alvo":["portuguese"],"amaciar":["portuguese"],"amador":["portuguese"],"amarelo":["portuguese"],"amassar":["portuguese"],"ambas":["portuguese"],"ambiente":["portuguese"],"ameixa":["portuguese"],"amenizar":["portuguese"],"amido":["portuguese"],"amistoso":["portuguese"],"amizade":["portuguese"],"amolador":["portuguese"],"amontoar":["portuguese"],"amoroso":["portuguese"],"amostra":["portuguese"],"amparar":["portuguese"],"ampliar":["portuguese"],"ampola":["portuguese"],"anagrama":["portuguese"],"analisar":["portuguese"],"anarquia":["portuguese"],"anatomia":["portuguese"],"andaime":["portuguese"],"anel":["portuguese"],"anexo":["portuguese"],"angular":["portuguese"],"animar":["portuguese"],"anjo":["portuguese"],"anomalia":["portuguese"],"anotado":["portuguese"],"ansioso":["portuguese"],"anterior":["portuguese"],"anuidade":["portuguese"],"anunciar":["portuguese"],"anzol":["portuguese"],"apagador":["portuguese"],"apalpar":["portuguese"],"apanhado":["portuguese"],"apego":["portuguese"],"apelido":["portuguese"],"apertada":["portuguese"],"apesar":["portuguese"],"apetite":["portuguese"],"apito":["portuguese"],"aplauso":["portuguese"],"aplicada":["portuguese"],"apoio":["portuguese"],"apontar":["portuguese"],"aposta":["portuguese"],"aprendiz":["portuguese"],"aprovar":["portuguese"],"aquecer":["portuguese"],"arame":["portuguese"],"aranha":["portuguese"],"arara":["portuguese"],"arcada":["portuguese"],"ardente":["portuguese"],"areia":["portuguese"],"arejar":["portuguese"],"arenito":["portuguese"],"aresta":["portuguese"],"argiloso":["portuguese"],"argola":["portuguese"],"arma":["portuguese"],"arquivo":["portuguese"],"arraial":["portuguese"],"arrebate":["portuguese"],"arriscar":["portuguese"],"arroba":["portuguese"],"arrumar":["portuguese"],"arsenal":["portuguese"],"arterial":["portuguese"],"artigo":["portuguese"],"arvoredo":["portuguese"],"asfaltar":["portuguese"],"asilado":["portuguese"],"aspirar":["portuguese"],"assador":["portuguese"],"assinar":["portuguese"],"assoalho":["portuguese"],"assunto":["portuguese"],"astral":["portuguese"],"atacado":["portuguese"],"atadura":["portuguese"],"atalho":["portuguese"],"atarefar":["portuguese"],"atear":["portuguese"],"atender":["portuguese"],"aterro":["portuguese"],"ateu":["portuguese"],"atingir":["portuguese"],"atirador":["portuguese"],"ativo":["portuguese"],"atoleiro":["portuguese"],"atracar":["portuguese"],"atrevido":["portuguese"],"atriz":["portuguese"],"atual":["portuguese"],"atum":["portuguese"],"auditor":["portuguese"],"aumentar":["portuguese"],"aura":["portuguese"],"aurora":["portuguese"],"autismo":["portuguese"],"autoria":["portuguese"],"autuar":["portuguese"],"avaliar":["portuguese"],"avante":["portuguese"],"avaria":["portuguese"],"avental":["portuguese"],"avesso":["portuguese"],"aviador":["portuguese"],"avisar":["portuguese"],"avulso":["portuguese"],"axila":["portuguese"],"azarar":["portuguese"],"azedo":["portuguese"],"azeite":["portuguese"],"azulejo":["portuguese"],"babar":["portuguese"],"babosa":["portuguese"],"bacalhau":["portuguese"],"bacharel":["portuguese"],"bacia":["portuguese"],"bagagem":["portuguese"],"baiano":["portuguese"],"bailar":["portuguese"],"baioneta":["portuguese"],"bairro":["portuguese"],"baixista":["portuguese"],"bajular":["portuguese"],"baleia":["portuguese"],"baliza":["portuguese"],"balsa":["portuguese"],"banal":["portuguese"],"bandeira":["portuguese"],"banho":["portuguese"],"banir":["portuguese"],"banquete":["portuguese"],"barato":["portuguese"],"barbado":["portuguese"],"baronesa":["portuguese"],"barraca":["portuguese"],"barulho":["portuguese"],"baseado":["portuguese"],"bastante":["portuguese"],"batata":["portuguese"],"batedor":["portuguese"],"batida":["portuguese"],"batom":["portuguese"],"batucar":["portuguese"],"baunilha":["portuguese"],"beber":["portuguese"],"beijo":["portuguese"],"beirada":["portuguese"],"beisebol":["portuguese"],"beldade":["portuguese"],"beleza":["portuguese"],"belga":["portuguese"],"beliscar":["portuguese"],"bendito":["portuguese"],"bengala":["portuguese"],"benzer":["portuguese","turkish"],"berimbau":["portuguese"],"berlinda":["portuguese"],"berro":["portuguese"],"besouro":["portuguese"],"bexiga":["portuguese"],"bezerro":["portuguese"],"bico":["portuguese"],"bicudo":["portuguese"],"bienal":["portuguese"],"bifocal":["portuguese"],"bifurcar":["portuguese"],"bigorna":["portuguese"],"bilhete":["portuguese"],"bimestre":["portuguese"],"bimotor":["portuguese"],"biologia":["portuguese"],"biombo":["portuguese"],"biosfera":["portuguese"],"bipolar":["portuguese"],"birrento":["portuguese"],"biscoito":["portuguese"],"bisneto":["portuguese"],"bispo":["portuguese"],"bissexto":["portuguese"],"bitola":["portuguese"],"bizarro":["portuguese"],"blindado":["portuguese"],"bloco":["portuguese"],"bloquear":["portuguese"],"boato":["portuguese"],"bobagem":["portuguese"],"bocado":["portuguese"],"bocejo":["portuguese"],"bochecha":["portuguese"],"boicotar":["portuguese"],"bolada":["portuguese"],"boletim":["portuguese"],"bolha":["portuguese"],"bolo":["portuguese"],"bombeiro":["portuguese"],"bonde":["portuguese"],"boneco":["portuguese"],"bonita":["portuguese"],"borbulha":["portuguese"],"borda":["portuguese"],"boreal":["portuguese"],"borracha":["portuguese"],"bovino":["portuguese"],"boxeador":["portuguese"],"branco":["portuguese"],"brasa":["portuguese"],"braveza":["portuguese"],"breu":["portuguese"],"briga":["portuguese"],"brilho":["portuguese"],"brincar":["portuguese"],"broa":["portuguese"],"brochura":["portuguese"],"bronzear":["portuguese"],"broto":["portuguese"],"bruxo":["portuguese"],"bucha":["portuguese"],"budismo":["portuguese"],"bufar":["portuguese"],"bule":["portuguese"],"buraco":["portuguese"],"busca":["portuguese"],"busto":["portuguese"],"buzina":["portuguese"],"cabana":["portuguese"],"cabelo":["portuguese"],"cabide":["portuguese"],"cabo":["portuguese"],"cabrito":["portuguese"],"cacau":["portuguese"],"cacetada":["portuguese"],"cachorro":["portuguese"],"cacique":["portuguese"],"cadastro":["portuguese"],"cadeado":["portuguese"],"cafezal":["portuguese"],"caiaque":["portuguese"],"caipira":["portuguese"],"caixote":["portuguese"],"cajado":["portuguese"],"caju":["portuguese"],"calafrio":["portuguese"],"calcular":["portuguese"],"caldeira":["portuguese"],"calibrar":["portuguese"],"calmante":["portuguese"],"calota":["portuguese"],"camada":["portuguese"],"cambista":["portuguese"],"camisa":["portuguese"],"camomila":["portuguese"],"campanha":["portuguese"],"camuflar":["portuguese"],"canavial":["portuguese"],"cancelar":["portuguese"],"caneta":["portuguese"],"canguru":["portuguese"],"canhoto":["portuguese"],"canivete":["portuguese"],"canoa":["portuguese"],"cansado":["portuguese"],"cantar":["portuguese"],"canudo":["portuguese"],"capacho":["portuguese"],"capela":["portuguese"],"capinar":["portuguese"],"capotar":["portuguese"],"capricho":["portuguese"],"captador":["portuguese"],"capuz":["portuguese"],"caracol":["portuguese"],"carbono":["portuguese"],"cardeal":["portuguese"],"careca":["portuguese"],"carimbar":["portuguese"],"carneiro":["portuguese"],"carpete":["portuguese"],"carreira":["portuguese"],"cartaz":["portuguese"],"carvalho":["portuguese"],"casaco":["portuguese"],"casca":["portuguese"],"casebre":["portuguese"],"castelo":["portuguese"],"casulo":["portuguese"],"catarata":["portuguese"],"cativar":["portuguese"],"caule":["portuguese"],"causador":["portuguese"],"cautelar":["portuguese"],"cavalo":["portuguese"],"caverna":["portuguese"],"cebola":["portuguese"],"cedilha":["portuguese"],"cegonha":["portuguese"],"celebrar":["portuguese"],"celular":["portuguese"],"cenoura":["portuguese"],"censo":["portuguese"],"centeio":["portuguese"],"cercar":["portuguese"],"cerrado":["portuguese"],"certeiro":["portuguese"],"cerveja":["portuguese"],"cetim":["portuguese"],"cevada":["portuguese"],"chacota":["portuguese"],"chaleira":["portuguese"],"chamado":["portuguese"],"chapada":["portuguese"],"charme":["portuguese"],"chatice":["portuguese"],"chave":["portuguese"],"chefe":["portuguese"],"chegada":["portuguese"],"cheiro":["portuguese"],"cheque":["portuguese"],"chicote":["portuguese"],"chifre":["portuguese"],"chinelo":["portuguese"],"chocalho":["portuguese"],"chover":["portuguese"],"chumbo":["portuguese"],"chutar":["portuguese"],"chuva":["portuguese"],"cicatriz":["portuguese"],"ciclone":["portuguese"],"cidade":["portuguese"],"cidreira":["portuguese"],"ciente":["portuguese"],"cigana":["portuguese"],"cimento":["portuguese"],"cinto":["portuguese"],"cinza":["portuguese"],"ciranda":["portuguese"],"circuito":["portuguese"],"cirurgia":["portuguese"],"citar":["portuguese"],"clareza":["portuguese"],"clero":["portuguese"],"clicar":["portuguese"],"clone":["portuguese"],"clube":["portuguese"],"coado":["portuguese"],"coagir":["portuguese"],"cobaia":["portuguese"],"cobertor":["portuguese"],"cobrar":["portuguese"],"cocada":["portuguese"],"coelho":["portuguese"],"coentro":["portuguese"],"coeso":["portuguese"],"cogumelo":["portuguese"],"coibir":["portuguese"],"coifa":["portuguese"],"coiote":["portuguese"],"colar":["portuguese"],"coleira":["portuguese"],"colher":["portuguese"],"colidir":["portuguese"],"colmeia":["portuguese"],"colono":["portuguese"],"coluna":["portuguese"],"comando":["portuguese"],"combinar":["portuguese"],"comentar":["portuguese"],"comitiva":["portuguese"],"comover":["portuguese"],"complexo":["portuguese"],"comum":["portuguese"],"concha":["portuguese"],"condor":["portuguese"],"conectar":["portuguese"],"confuso":["portuguese"],"congelar":["portuguese"],"conhecer":["portuguese"],"conjugar":["portuguese"],"consumir":["portuguese"],"contrato":["portuguese"],"convite":["portuguese"],"cooperar":["portuguese"],"copeiro":["portuguese"],"copiador":["portuguese"],"copo":["portuguese"],"coquetel":["portuguese"],"coragem":["portuguese"],"cordial":["portuguese"],"corneta":["portuguese"],"coronha":["portuguese"],"corporal":["portuguese"],"correio":["portuguese"],"cortejo":["portuguese"],"coruja":["portuguese"],"corvo":["portuguese"],"cosseno":["portuguese"],"costela":["portuguese"],"cotonete":["portuguese"],"couro":["portuguese"],"couve":["portuguese"],"covil":["portuguese"],"cozinha":["portuguese"],"cratera":["portuguese"],"cravo":["portuguese"],"creche":["portuguese"],"credor":["portuguese"],"creme":["portuguese"],"crer":["portuguese"],"crespo":["portuguese"],"criada":["portuguese"],"criminal":["portuguese"],"crioulo":["portuguese"],"crise":["portuguese"],"criticar":["portuguese"],"crosta":["portuguese"],"crua":["portuguese"],"cruzeiro":["portuguese"],"cubano":["portuguese"],"cueca":["portuguese"],"cuidado":["portuguese"],"cujo":["portuguese"],"culatra":["portuguese"],"culminar":["portuguese"],"culpar":["portuguese"],"cultura":["portuguese"],"cumprir":["portuguese"],"cunhado":["portuguese"],"cupido":["portuguese"],"curativo":["portuguese"],"curral":["portuguese"],"cursar":["portuguese"],"curto":["portuguese"],"cuspir":["portuguese"],"custear":["portuguese"],"cutelo":["portuguese"],"damasco":["portuguese"],"datar":["portuguese"],"debater":["portuguese"],"debitar":["portuguese"],"deboche":["portuguese"],"debulhar":["portuguese"],"decalque":["portuguese"],"decimal":["portuguese"],"declive":["portuguese"],"decote":["portuguese"],"decretar":["portuguese"],"dedal":["portuguese"],"dedicado":["portuguese"],"deduzir":["portuguese"],"defesa":["portuguese"],"defumar":["portuguese"],"degelo":["portuguese"],"degrau":["portuguese"],"degustar":["portuguese"],"deitado":["portuguese"],"deixar":["portuguese"],"delator":["portuguese"],"delegado":["portuguese"],"delinear":["portuguese"],"delonga":["portuguese"],"demanda":["portuguese"],"demitir":["portuguese"],"demolido":["portuguese"],"dentista":["portuguese"],"depenado":["portuguese"],"depilar":["portuguese"],"depois":["portuguese"],"depressa":["portuguese"],"depurar":["portuguese"],"deriva":["portuguese"],"derramar":["portuguese"],"desafio":["portuguese"],"desbotar":["portuguese"],"descanso":["portuguese"],"desenho":["portuguese"],"desfiado":["portuguese"],"desgaste":["portuguese"],"desigual":["portuguese"],"deslize":["portuguese"],"desmamar":["portuguese"],"desova":["portuguese"],"despesa":["portuguese"],"destaque":["portuguese"],"desviar":["portuguese"],"detalhar":["portuguese"],"detentor":["portuguese"],"detonar":["portuguese"],"detrito":["portuguese"],"deusa":["portuguese"],"dever":["portuguese"],"devido":["portuguese"],"devotado":["portuguese"],"dezena":["portuguese"],"diagrama":["portuguese"],"dialeto":["portuguese"],"didata":["portuguese"],"difuso":["portuguese"],"digitar":["portuguese"],"dilatado":["portuguese"],"diluente":["portuguese"],"diminuir":["portuguese"],"dinastia":["portuguese"],"dinheiro":["portuguese"],"diocese":["portuguese"],"direto":["portuguese"],"discreta":["portuguese"],"disfarce":["portuguese"],"disparo":["portuguese"],"disquete":["portuguese"],"dissipar":["portuguese"],"distante":["portuguese"],"ditador":["portuguese"],"diurno":["portuguese"],"diverso":["portuguese"],"divisor":["portuguese"],"divulgar":["portuguese"],"dizer":["portuguese"],"dobrador":["portuguese"],"dolorido":["portuguese"],"domador":["portuguese"],"dominado":["portuguese"],"donativo":["portuguese"],"donzela":["portuguese"],"dormente":["portuguese"],"dorsal":["portuguese"],"dosagem":["portuguese"],"dourado":["portuguese"],"doutor":["portuguese"],"drenagem":["portuguese"],"drible":["portuguese"],"drogaria":["portuguese"],"duelar":["portuguese"],"duende":["portuguese"],"dueto":["portuguese"],"duplo":["portuguese"],"duquesa":["portuguese"],"durante":["portuguese"],"duvidoso":["portuguese"],"eclodir":["portuguese"],"ecoar":["portuguese"],"ecologia":["portuguese"],"edificar":["portuguese"],"edital":["portuguese"],"educado":["portuguese"],"efeito":["portuguese"],"efetivar":["portuguese"],"ejetar":["portuguese"],"elaborar":["portuguese"],"eleger":["portuguese"],"eleitor":["portuguese"],"elenco":["portuguese"],"elevador":["portuguese"],"eliminar":["portuguese"],"elogiar":["portuguese"],"embargo":["portuguese"],"embolado":["portuguese"],"embrulho":["portuguese"],"embutido":["portuguese"],"emenda":["portuguese"],"emergir":["portuguese"],"emissor":["portuguese"],"empatia":["portuguese"],"empenho":["portuguese"],"empinado":["portuguese"],"empolgar":["portuguese"],"emprego":["portuguese"],"empurrar":["portuguese"],"emulador":["portuguese"],"encaixe":["portuguese"],"encenado":["portuguese"],"enchente":["portuguese"],"encontro":["portuguese"],"endeusar":["portuguese"],"endossar":["portuguese"],"enfaixar":["portuguese"],"enfeite":["portuguese"],"enfim":["portuguese"],"engajado":["portuguese"],"engenho":["portuguese"],"englobar":["portuguese"],"engomado":["portuguese"],"engraxar":["portuguese"],"enguia":["portuguese"],"enjoar":["portuguese"],"enlatar":["portuguese"],"enquanto":["portuguese"],"enraizar":["portuguese"],"enrolado":["portuguese"],"enrugar":["portuguese"],"ensaio":["portuguese"],"enseada":["portuguese"],"ensino":["portuguese"],"ensopado":["portuguese"],"entanto":["portuguese"],"enteado":["portuguese"],"entidade":["portuguese"],"entortar":["portuguese"],"entrada":["portuguese"],"entulho":["portuguese"],"envergar":["portuguese"],"enviado":["portuguese"],"envolver":["portuguese"],"enxame":["portuguese"],"enxerto":["portuguese"],"enxofre":["portuguese"],"enxuto":["portuguese"],"epiderme":["portuguese"],"equipar":["portuguese"],"ereto":["portuguese"],"erguido":["portuguese"],"errata":["portuguese"],"erva":["portuguese"],"ervilha":["portuguese"],"esbanjar":["portuguese"],"esbelto":["portuguese"],"escama":["portuguese"],"escola":["portuguese"],"escrita":["portuguese"],"escuta":["portuguese"],"esfinge":["portuguese"],"esfolar":["portuguese"],"esfregar":["portuguese"],"esfumado":["portuguese"],"esgrima":["portuguese"],"esmalte":["portuguese"],"espanto":["portuguese"],"espelho":["portuguese"],"espiga":["portuguese"],"esponja":["portuguese"],"espreita":["portuguese"],"espumar":["portuguese"],"esquerda":["portuguese"],"estaca":["portuguese"],"esteira":["portuguese"],"esticar":["portuguese"],"estofado":["portuguese"],"estrela":["portuguese"],"estudo":["portuguese"],"esvaziar":["portuguese"],"etanol":["portuguese"],"etiqueta":["portuguese"],"euforia":["portuguese"],"europeu":["portuguese"],"evacuar":["portuguese"],"evaporar":["portuguese"],"evasivo":["portuguese"],"eventual":["portuguese"],"evidente":["portuguese"],"evoluir":["portuguese"],"exagero":["portuguese"],"exalar":["portuguese"],"examinar":["portuguese"],"exato":["portuguese"],"exausto":["portuguese"],"excesso":["portuguese"],"excitar":["portuguese"],"exclamar":["portuguese"],"executar":["portuguese"],"exemplo":["portuguese"],"exibir":["portuguese"],"exigente":["portuguese"],"exonerar":["portuguese"],"expandir":["portuguese"],"expelir":["portuguese"],"expirar":["portuguese"],"explanar":["portuguese"],"exposto":["portuguese"],"expresso":["portuguese"],"expulsar":["portuguese"],"externo":["portuguese"],"extinto":["portuguese"],"extrato":["portuguese"],"fabricar":["portuguese"],"fabuloso":["portuguese"],"faceta":["portuguese"],"facial":["portuguese"],"fada":["portuguese"],"fadiga":["portuguese"],"faixa":["portuguese"],"falar":["portuguese"],"falta":["portuguese"],"familiar":["portuguese"],"fandango":["portuguese"],"fanfarra":["portuguese"],"fantoche":["portuguese"],"fardado":["portuguese"],"farelo":["portuguese"],"farinha":["portuguese"],"farofa":["portuguese"],"farpa":["portuguese"],"fartura":["portuguese"],"fatia":["portuguese"],"fator":["portuguese"],"favorita":["portuguese"],"faxina":["portuguese"],"fazenda":["portuguese"],"fechado":["portuguese"],"feijoada":["portuguese"],"feirante":["portuguese"],"felino":["portuguese"],"feminino":["portuguese"],"fenda":["portuguese"],"feno":["portuguese"],"fera":["portuguese"],"feriado":["portuguese"],"ferrugem":["portuguese"],"ferver":["portuguese"],"festejar":["portuguese"],"fetal":["portuguese"],"feudal":["portuguese"],"fiapo":["portuguese"],"fibrose":["portuguese"],"ficar":["portuguese"],"ficheiro":["portuguese"],"figurado":["portuguese"],"fileira":["portuguese"],"filho":["portuguese"],"filme":["portuguese"],"filtrar":["portuguese"],"firmeza":["portuguese"],"fisgada":["portuguese"],"fissura":["portuguese"],"fita":["portuguese"],"fivela":["portuguese"],"fixador":["portuguese"],"fixo":["portuguese"],"flacidez":["portuguese"],"flamingo":["portuguese"],"flanela":["portuguese"],"flechada":["portuguese"],"flora":["portuguese"],"flutuar":["portuguese"],"fluxo":["portuguese"],"focal":["portuguese"],"focinho":["portuguese"],"fofocar":["portuguese"],"fogo":["portuguese"],"foguete":["portuguese"],"foice":["portuguese"],"folgado":["portuguese"],"folheto":["portuguese"],"forjar":["portuguese"],"formiga":["portuguese"],"forno":["portuguese"],"forte":["portuguese"],"fosco":["portuguese"],"fossa":["portuguese"],"fragata":["portuguese"],"fralda":["portuguese"],"frango":["portuguese"],"frasco":["portuguese"],"fraterno":["portuguese"],"freira":["portuguese"],"frente":["portuguese"],"fretar":["portuguese"],"frieza":["portuguese"],"friso":["portuguese"],"fritura":["portuguese"],"fronha":["portuguese"],"frustrar":["portuguese"],"fruteira":["portuguese"],"fugir":["portuguese"],"fulano":["portuguese"],"fuligem":["portuguese"],"fundar":["portuguese"],"fungo":["portuguese"],"funil":["portuguese"],"furador":["portuguese"],"furioso":["portuguese"],"futebol":["portuguese"],"gabarito":["portuguese"],"gabinete":["portuguese"],"gado":["portuguese"],"gaiato":["portuguese"],"gaiola":["portuguese"],"gaivota":["portuguese"],"galega":["portuguese"],"galho":["portuguese"],"galinha":["portuguese"],"galocha":["portuguese"],"ganhar":["portuguese"],"garagem":["portuguese"],"garfo":["portuguese"],"gargalo":["portuguese"],"garimpo":["portuguese"],"garoupa":["portuguese"],"garrafa":["portuguese"],"gasoduto":["portuguese"],"gasto":["portuguese"],"gata":["portuguese"],"gatilho":["portuguese"],"gaveta":["portuguese"],"gazela":["portuguese"],"gelado":["portuguese"],"geleia":["portuguese"],"gelo":["portuguese"],"gemada":["portuguese"],"gemer":["portuguese"],"gemido":["portuguese"],"generoso":["portuguese"],"gengiva":["portuguese"],"genial":["portuguese"],"genoma":["portuguese"],"genro":["portuguese"],"geologia":["portuguese"],"gerador":["portuguese"],"germinar":["portuguese"],"gesso":["portuguese"],"gestor":["portuguese"],"ginasta":["portuguese"],"gincana":["portuguese"],"gingado":["portuguese"],"girafa":["portuguese"],"girino":["portuguese"],"glacial":["portuguese"],"glicose":["portuguese"],"global":["portuguese"],"glorioso":["portuguese"],"goela":["portuguese"],"goiaba":["portuguese"],"golfe":["portuguese"],"golpear":["portuguese"],"gordura":["portuguese"],"gorjeta":["portuguese"],"gorro":["portuguese"],"gostoso":["portuguese"],"goteira":["portuguese"],"governar":["portuguese"],"gracejo":["portuguese"],"gradual":["portuguese"],"grafite":["portuguese"],"gralha":["portuguese"],"grampo":["portuguese"],"granada":["portuguese"],"gratuito":["portuguese"],"graveto":["portuguese"],"graxa":["portuguese"],"grego":["portuguese"],"grelhar":["portuguese"],"greve":["portuguese"],"grilo":["portuguese"],"grisalho":["portuguese"],"gritaria":["portuguese"],"grosso":["portuguese"],"grotesco":["portuguese"],"grudado":["portuguese"],"grunhido":["portuguese"],"gruta":["portuguese"],"guache":["portuguese"],"guarani":["portuguese"],"guaxinim":["portuguese"],"guerrear":["portuguese"],"guiar":["portuguese"],"guincho":["portuguese"],"guisado":["portuguese"],"gula":["portuguese"],"guloso":["portuguese"],"guru":["portuguese"],"habitar":["portuguese"],"harmonia":["portuguese"],"haste":["portuguese"],"haver":["portuguese"],"hectare":["portuguese"],"herdar":["portuguese"],"heresia":["portuguese"],"hesitar":["portuguese"],"hiato":["portuguese"],"hibernar":["portuguese"],"hidratar":["portuguese"],"hiena":["portuguese"],"hino":["portuguese"],"hipismo":["portuguese"],"hipnose":["portuguese"],"hipoteca":["portuguese"],"hoje":["portuguese"],"holofote":["portuguese"],"homem":["portuguese"],"honesto":["portuguese"],"honrado":["portuguese"],"hormonal":["portuguese"],"hospedar":["portuguese"],"humorado":["portuguese"],"iate":["portuguese"],"ideia":["portuguese"],"idoso":["portuguese"],"ignorado":["portuguese"],"igreja":["portuguese"],"iguana":["portuguese"],"ileso":["portuguese"],"ilha":["portuguese"],"iludido":["portuguese"],"iluminar":["portuguese"],"ilustrar":["portuguese"],"imagem":["portuguese"],"imediato":["portuguese"],"imenso":["portuguese"],"imersivo":["portuguese"],"iminente":["portuguese"],"imitador":["portuguese"],"imortal":["portuguese"],"impacto":["portuguese"],"impedir":["portuguese"],"implante":["portuguese"],"impor":["portuguese"],"imprensa":["portuguese"],"impune":["portuguese"],"imunizar":["portuguese"],"inalador":["portuguese"],"inapto":["portuguese"],"inativo":["portuguese"],"incenso":["portuguese"],"inchar":["portuguese"],"incidir":["portuguese"],"incluir":["portuguese"],"incolor":["portuguese"],"indeciso":["portuguese"],"indireto":["portuguese"],"indutor":["portuguese"],"ineficaz":["portuguese"],"inerente":["portuguese"],"infantil":["portuguese"],"infestar":["portuguese"],"infinito":["portuguese"],"inflamar":["portuguese"],"informal":["portuguese"],"infrator":["portuguese"],"ingerir":["portuguese"],"inibido":["portuguese"],"inicial":["portuguese"],"inimigo":["portuguese"],"injetar":["portuguese"],"inocente":["portuguese"],"inodoro":["portuguese"],"inovador":["portuguese"],"inox":["portuguese"],"inquieto":["portuguese"],"inscrito":["portuguese"],"inseto":["portuguese"],"insistir":["portuguese"],"inspetor":["portuguese"],"instalar":["portuguese"],"insulto":["portuguese"],"intacto":["portuguese"],"integral":["portuguese"],"intimar":["portuguese"],"intocado":["portuguese"],"intriga":["portuguese"],"invasor":["portuguese"],"inverno":["portuguese"],"invicto":["portuguese"],"invocar":["portuguese"],"iogurte":["portuguese"],"iraniano":["portuguese"],"ironizar":["portuguese"],"irreal":["portuguese"],"irritado":["portuguese"],"isca":["portuguese"],"isento":["portuguese"],"isolado":["portuguese"],"isqueiro":["portuguese"],"italiano":["portuguese"],"janeiro":["portuguese"],"jangada":["portuguese"],"janta":["portuguese"],"jararaca":["portuguese"],"jardim":["portuguese"],"jarro":["portuguese"],"jasmim":["portuguese"],"jato":["portuguese"],"javali":["portuguese"],"jazida":["portuguese"],"jejum":["portuguese"],"joaninha":["portuguese"],"joelhada":["portuguese"],"jogador":["portuguese"],"joia":["portuguese"],"jornal":["portuguese"],"jorrar":["portuguese"],"jovem":["portuguese"],"juba":["portuguese"],"judeu":["portuguese"],"judoca":["portuguese"],"juiz":["portuguese"],"julgador":["portuguese"],"julho":["portuguese"],"jurado":["portuguese"],"jurista":["portuguese"],"juro":["portuguese"],"justa":["portuguese"],"labareda":["portuguese"],"laboral":["portuguese"],"lacre":["portuguese"],"lactante":["portuguese"],"ladrilho":["portuguese"],"lagarta":["portuguese"],"lagoa":["portuguese"],"laje":["portuguese"],"lamber":["portuguese"],"lamentar":["portuguese"],"laminar":["portuguese"],"lampejo":["portuguese"],"lanche":["portuguese"],"lapidar":["portuguese"],"lapso":["portuguese"],"laranja":["portuguese"],"lareira":["portuguese"],"largura":["portuguese"],"lasanha":["portuguese"],"lastro":["portuguese"],"lateral":["portuguese"],"latido":["portuguese"],"lavanda":["portuguese"],"lavoura":["portuguese"],"lavrador":["portuguese"],"laxante":["portuguese"],"lazer":["portuguese"],"lealdade":["portuguese"],"lebre":["portuguese"],"legado":["portuguese"],"legendar":["portuguese"],"legista":["portuguese"],"leigo":["portuguese"],"leiloar":["portuguese"],"leitura":["portuguese"],"lembrete":["portuguese"],"leme":["portuguese"],"lenhador":["portuguese"],"lentilha":["portuguese"],"leoa":["portuguese"],"lesma":["portuguese"],"leste":["portuguese"],"letivo":["portuguese"],"letreiro":["portuguese"],"levar":["portuguese"],"leveza":["portuguese"],"levitar":["portuguese"],"liberal":["portuguese"],"libido":["portuguese"],"liderar":["portuguese"],"ligar":["portuguese"],"ligeiro":["portuguese"],"limitar":["portuguese"],"limoeiro":["portuguese"],"limpador":["portuguese"],"linda":["portuguese"],"linear":["portuguese"],"linhagem":["portuguese"],"liquidez":["portuguese"],"listagem":["portuguese"],"lisura":["portuguese"],"litoral":["portuguese"],"livro":["portuguese"],"lixa":["portuguese"],"lixeira":["portuguese"],"locador":["portuguese"],"locutor":["portuguese"],"lojista":["portuguese"],"lombo":["portuguese"],"lona":["portuguese"],"longe":["portuguese"],"lontra":["portuguese"],"lorde":["portuguese"],"lotado":["portuguese"],"loteria":["portuguese"],"loucura":["portuguese"],"lousa":["portuguese"],"louvar":["portuguese"],"luar":["portuguese"],"lucidez":["portuguese"],"lucro":["portuguese"],"luneta":["portuguese"],"lustre":["portuguese"],"lutador":["portuguese"],"luva":["portuguese"],"macaco":["portuguese"],"macete":["portuguese"],"machado":["portuguese"],"macio":["portuguese"],"madeira":["portuguese"],"madrinha":["portuguese"],"magnata":["portuguese"],"magreza":["portuguese"],"maior":["portuguese"],"mais":["portuguese"],"malandro":["portuguese"],"malha":["portuguese"],"malote":["portuguese"],"maluco":["portuguese"],"mamilo":["portuguese"],"mamoeiro":["portuguese"],"mamute":["portuguese"],"manada":["portuguese"],"mancha":["portuguese"],"mandato":["portuguese"],"manequim":["portuguese"],"manhoso":["portuguese"],"manivela":["portuguese"],"manobrar":["portuguese"],"mansa":["portuguese"],"manter":["portuguese"],"manusear":["portuguese"],"mapeado":["portuguese"],"maquinar":["portuguese"],"marcador":["portuguese"],"maresia":["portuguese"],"marfim":["portuguese"],"margem":["portuguese"],"marinho":["portuguese"],"marmita":["portuguese"],"maroto":["portuguese"],"marquise":["portuguese"],"marreco":["portuguese"],"martelo":["portuguese"],"marujo":["portuguese"],"mascote":["portuguese"],"masmorra":["portuguese"],"massagem":["portuguese"],"mastigar":["portuguese"],"matagal":["portuguese"],"materno":["portuguese"],"matinal":["portuguese"],"matutar":["portuguese"],"maxilar":["portuguese"],"medalha":["portuguese"],"medida":["portuguese"],"medusa":["portuguese"],"megafone":["portuguese"],"meiga":["portuguese"],"melancia":["portuguese"],"melhor":["portuguese"],"membro":["portuguese"],"memorial":["portuguese"],"menino":["portuguese"],"menos":["portuguese"],"mensagem":["portuguese"],"mental":["portuguese"],"merecer":["portuguese"],"mergulho":["portuguese"],"mesada":["portuguese"],"mesclar":["portuguese"],"mesmo":["portuguese"],"mesquita":["portuguese"],"mestre":["portuguese"],"metade":["portuguese"],"meteoro":["portuguese"],"metragem":["portuguese"],"mexer":["portuguese"],"mexicano":["portuguese"],"micro":["portuguese"],"migalha":["portuguese"],"migrar":["portuguese"],"milagre":["portuguese"],"milenar":["portuguese"],"milhar":["portuguese"],"mimado":["portuguese"],"minerar":["portuguese"],"minhoca":["portuguese"],"ministro":["portuguese"],"minoria":["portuguese"],"miolo":["portuguese"],"mirante":["portuguese"],"mirtilo":["portuguese"],"misturar":["portuguese"],"mocidade":["portuguese"],"moderno":["portuguese"],"modular":["portuguese"],"moeda":["portuguese"],"moer":["portuguese"],"moinho":["portuguese"],"moita":["portuguese"],"moldura":["portuguese"],"moleza":["portuguese"],"molho":["portuguese"],"molinete":["portuguese"],"molusco":["portuguese"],"montanha":["portuguese"],"moqueca":["portuguese"],"morango":["portuguese"],"morcego":["portuguese"],"mordomo":["portuguese"],"morena":["portuguese"],"mosaico":["portuguese"],"mosquete":["portuguese"],"mostarda":["portuguese"],"motel":["portuguese"],"motim":["portuguese"],"moto":["portuguese"],"motriz":["portuguese"],"muda":["portuguese"],"muito":["portuguese"],"mulata":["portuguese"],"mulher":["portuguese"],"multar":["portuguese"],"mundial":["portuguese"],"munido":["portuguese"],"muralha":["portuguese"],"murcho":["portuguese"],"muscular":["portuguese"],"museu":["portuguese"],"musical":["portuguese"],"nacional":["portuguese"],"nadador":["portuguese"],"naja":["portuguese"],"namoro":["portuguese"],"narina":["portuguese"],"narrado":["portuguese"],"nascer":["portuguese"],"nativa":["portuguese"],"natureza":["portuguese"],"navalha":["portuguese"],"navegar":["portuguese"],"navio":["portuguese"],"neblina":["portuguese"],"nebuloso":["portuguese"],"negativa":["portuguese"],"negociar":["portuguese"],"negrito":["portuguese"],"nervoso":["portuguese"],"neta":["portuguese"],"neural":["portuguese"],"nevasca":["portuguese"],"nevoeiro":["portuguese"],"ninar":["portuguese"],"ninho":["portuguese"],"nitidez":["portuguese"],"nivelar":["portuguese"],"nobreza":["portuguese"],"noite":["portuguese"],"noiva":["portuguese"],"nomear":["portuguese"],"nominal":["portuguese"],"nordeste":["portuguese"],"nortear":["portuguese"],"notar":["portuguese"],"noticiar":["portuguese"],"noturno":["portuguese"],"novelo":["portuguese"],"novilho":["portuguese"],"novo":["portuguese"],"nublado":["portuguese"],"nudez":["portuguese"],"numeral":["portuguese"],"nupcial":["portuguese"],"nutrir":["portuguese"],"nuvem":["portuguese"],"obcecado":["portuguese"],"obedecer":["portuguese"],"objetivo":["portuguese"],"obrigado":["portuguese"],"obscuro":["portuguese"],"obstetra":["portuguese"],"obter":["portuguese"],"obturar":["portuguese"],"ocidente":["portuguese"],"ocioso":["portuguese"],"ocorrer":["portuguese"],"oculista":["portuguese"],"ocupado":["portuguese"],"ofegante":["portuguese"],"ofensiva":["portuguese"],"oferenda":["portuguese"],"oficina":["portuguese"],"ofuscado":["portuguese"],"ogiva":["portuguese"],"olaria":["portuguese"],"oleoso":["portuguese"],"olhar":["portuguese"],"oliveira":["portuguese"],"ombro":["portuguese"],"omelete":["portuguese"],"omisso":["portuguese"],"omitir":["portuguese"],"ondulado":["portuguese"],"oneroso":["portuguese"],"ontem":["portuguese"],"opcional":["portuguese"],"operador":["portuguese"],"oponente":["portuguese"],"oportuno":["portuguese"],"oposto":["portuguese"],"orar":["portuguese"],"orbitar":["portuguese"],"ordem":["portuguese"],"ordinal":["portuguese"],"orfanato":["portuguese"],"orgasmo":["portuguese"],"orgulho":["portuguese"],"oriental":["portuguese"],"origem":["portuguese"],"oriundo":["portuguese"],"orla":["portuguese"],"ortodoxo":["portuguese"],"orvalho":["portuguese"],"oscilar":["portuguese"],"ossada":["portuguese"],"osso":["portuguese"],"ostentar":["portuguese"],"otimismo":["portuguese"],"ousadia":["portuguese"],"outono":["portuguese"],"outubro":["portuguese"],"ouvido":["portuguese"],"ovelha":["portuguese"],"ovular":["portuguese"],"oxidar":["portuguese"],"oxigenar":["portuguese"],"pacato":["portuguese"],"paciente":["portuguese"],"pacote":["portuguese"],"pactuar":["portuguese"],"padaria":["portuguese"],"padrinho":["portuguese"],"pagar":["portuguese"],"pagode":["portuguese"],"painel":["portuguese"],"pairar":["portuguese"],"paisagem":["portuguese"],"palavra":["portuguese"],"palestra":["portuguese"],"palheta":["portuguese"],"palito":["portuguese"],"palmada":["portuguese"],"palpitar":["portuguese"],"pancada":["portuguese"],"panela":["portuguese"],"panfleto":["portuguese"],"panqueca":["portuguese"],"pantanal":["portuguese"],"papagaio":["portuguese"],"papelada":["portuguese"],"papiro":["portuguese"],"parafina":["portuguese"],"parcial":["portuguese"],"pardal":["portuguese"],"parede":["portuguese"],"partida":["portuguese"],"pasmo":["portuguese"],"passado":["portuguese"],"pastel":["portuguese"],"patamar":["portuguese"],"patente":["portuguese"],"patinar":["portuguese"],"patrono":["portuguese"],"paulada":["portuguese"],"pausar":["portuguese"],"peculiar":["portuguese"],"pedalar":["portuguese"],"pedestre":["portuguese"],"pediatra":["portuguese"],"pedra":["portuguese"],"pegada":["portuguese"],"peitoral":["portuguese"],"peixe":["portuguese"],"pele":["portuguese"],"pelicano":["portuguese"],"penca":["portuguese"],"pendurar":["portuguese"],"peneira":["portuguese"],"penhasco":["portuguese"],"pensador":["portuguese"],"pente":["portuguese"],"perceber":["portuguese"],"perfeito":["portuguese"],"pergunta":["portuguese"],"perito":["portuguese"],"permitir":["portuguese"],"perna":["portuguese"],"perplexo":["portuguese"],"persiana":["portuguese"],"pertence":["portuguese"],"peruca":["portuguese"],"pescado":["portuguese"],"pesquisa":["portuguese"],"pessoa":["portuguese"],"petiscar":["portuguese"],"piada":["portuguese"],"picado":["portuguese"],"piedade":["portuguese"],"pigmento":["portuguese"],"pilastra":["portuguese"],"pilhado":["portuguese"],"pilotar":["portuguese"],"pimenta":["portuguese"],"pincel":["portuguese"],"pinguim":["portuguese"],"pinha":["portuguese"],"pinote":["portuguese"],"pintar":["portuguese"],"pioneiro":["portuguese"],"pipoca":["portuguese"],"piquete":["portuguese"],"piranha":["portuguese"],"pires":["portuguese"],"pirueta":["portuguese"],"piscar":["portuguese"],"pistola":["portuguese"],"pitanga":["portuguese"],"pivete":["portuguese"],"planta":["portuguese"],"plaqueta":["portuguese"],"platina":["portuguese"],"plebeu":["portuguese"],"plumagem":["portuguese"],"pluvial":["portuguese"],"pneu":["portuguese"],"poda":["portuguese"],"poeira":["portuguese"],"poetisa":["portuguese"],"polegada":["portuguese"],"policiar":["portuguese"],"poluente":["portuguese"],"polvilho":["portuguese"],"pomar":["portuguese"],"pomba":["portuguese"],"ponderar":["portuguese"],"pontaria":["portuguese"],"populoso":["portuguese"],"porta":["portuguese"],"possuir":["portuguese"],"postal":["portuguese"],"pote":["portuguese"],"poupar":["portuguese"],"pouso":["portuguese"],"povoar":["portuguese"],"praia":["portuguese"],"prancha":["portuguese"],"prato":["portuguese"],"praxe":["portuguese"],"prece":["portuguese"],"predador":["portuguese"],"prefeito":["portuguese"],"premiar":["portuguese"],"prensar":["portuguese"],"preparar":["portuguese"],"presilha":["portuguese"],"pretexto":["portuguese"],"prevenir":["portuguese"],"prezar":["portuguese"],"primata":["portuguese"],"princesa":["portuguese"],"prisma":["portuguese"],"privado":["portuguese"],"processo":["portuguese"],"produto":["portuguese"],"profeta":["portuguese"],"proibido":["portuguese"],"projeto":["portuguese"],"prometer":["portuguese"],"propagar":["portuguese"],"prosa":["portuguese"],"protetor":["portuguese"],"provador":["portuguese"],"publicar":["portuguese"],"pudim":["portuguese"],"pular":["portuguese"],"pulmonar":["portuguese"],"pulseira":["portuguese"],"punhal":["portuguese"],"punir":["portuguese"],"pupilo":["portuguese"],"pureza":["portuguese"],"puxador":["portuguese"],"quadra":["portuguese"],"quantia":["portuguese"],"quarto":["portuguese"],"quase":["portuguese"],"quebrar":["portuguese"],"queda":["portuguese"],"queijo":["portuguese"],"quente":["portuguese"],"querido":["portuguese"],"quimono":["portuguese"],"quina":["portuguese"],"quiosque":["portuguese"],"rabanada":["portuguese"],"rabisco":["portuguese"],"rachar":["portuguese"],"racionar":["portuguese"],"radial":["portuguese"],"raiar":["portuguese"],"rainha":["portuguese"],"raio":["portuguese"],"raiva":["portuguese"],"rajada":["portuguese"],"ralado":["portuguese"],"ramal":["portuguese"],"ranger":["portuguese"],"ranhura":["portuguese"],"rapadura":["portuguese"],"rapel":["portuguese"],"rapidez":["portuguese"],"raposa":["portuguese"],"raquete":["portuguese"],"raridade":["portuguese"],"rasante":["portuguese"],"rascunho":["portuguese"],"rasgar":["portuguese"],"raspador":["portuguese"],"rasteira":["portuguese"],"rasurar":["portuguese"],"ratazana":["portuguese"],"ratoeira":["portuguese"],"realeza":["portuguese"],"reanimar":["portuguese"],"reaver":["portuguese"],"rebaixar":["portuguese"],"rebelde":["portuguese"],"rebolar":["portuguese"],"recado":["portuguese"],"recente":["portuguese"],"recheio":["portuguese"],"recibo":["portuguese"],"recordar":["portuguese"],"recrutar":["portuguese"],"recuar":["portuguese"],"rede":["portuguese"],"redimir":["portuguese"],"redonda":["portuguese"],"reduzida":["portuguese"],"reenvio":["portuguese"],"refinar":["portuguese"],"refletir":["portuguese"],"refogar":["portuguese"],"refresco":["portuguese"],"refugiar":["portuguese"],"regalia":["portuguese"],"regime":["portuguese"],"regra":["portuguese"],"reinado":["portuguese"],"reitor":["portuguese"],"rejeitar":["portuguese"],"relativo":["portuguese"],"remador":["portuguese"],"remendo":["portuguese"],"remorso":["portuguese"],"renovado":["portuguese"],"reparo":["portuguese"],"repelir":["portuguese"],"repleto":["portuguese"],"repolho":["portuguese"],"represa":["portuguese"],"repudiar":["portuguese"],"requerer":["portuguese"],"resenha":["portuguese"],"resfriar":["portuguese"],"resgatar":["portuguese"],"residir":["portuguese"],"resolver":["portuguese"],"respeito":["portuguese"],"ressaca":["portuguese"],"restante":["portuguese"],"resumir":["portuguese"],"retalho":["portuguese"],"reter":["portuguese"],"retirar":["portuguese"],"retomada":["portuguese"],"retratar":["portuguese"],"revelar":["portuguese"],"revisor":["portuguese"],"revolta":["portuguese"],"riacho":["portuguese"],"rica":["portuguese"],"rigidez":["portuguese"],"rigoroso":["portuguese"],"rimar":["portuguese"],"ringue":["portuguese"],"risada":["portuguese"],"risco":["portuguese"],"risonho":["portuguese"],"robalo":["portuguese"],"rochedo":["portuguese"],"rodada":["portuguese"],"rodeio":["portuguese"],"rodovia":["portuguese"],"roedor":["portuguese"],"roleta":["portuguese"],"romano":["portuguese"],"roncar":["portuguese"],"rosado":["portuguese"],"roseira":["portuguese"],"rosto":["portuguese"],"rota":["portuguese","turkish"],"roteiro":["portuguese"],"rotina":["portuguese"],"rotular":["portuguese"],"rouco":["portuguese"],"roupa":["portuguese"],"roxo":["portuguese"],"rubro":["portuguese"],"rugido":["portuguese"],"rugoso":["portuguese"],"ruivo":["portuguese"],"rumo":["portuguese"],"rupestre":["portuguese"],"russo":["portuguese"],"sabor":["portuguese"],"saciar":["portuguese"],"sacola":["portuguese"],"sacudir":["portuguese"],"sadio":["portuguese"],"safira":["portuguese"],"saga":["portuguese"],"sagrada":["portuguese"],"saibro":["portuguese"],"salada":["portuguese"],"saleiro":["portuguese"],"salgado":["portuguese"],"saliva":["portuguese"],"salpicar":["portuguese"],"salsicha":["portuguese"],"saltar":["portuguese"],"salvador":["portuguese"],"sambar":["portuguese"],"samurai":["portuguese"],"sanar":["portuguese"],"sanfona":["portuguese"],"sangue":["portuguese"],"sanidade":["portuguese"],"sapato":["portuguese"],"sarda":["portuguese"],"sargento":["portuguese"],"sarjeta":["portuguese"],"saturar":["portuguese"],"saudade":["portuguese"],"saxofone":["portuguese"],"sazonal":["portuguese"],"secar":["portuguese"],"secular":["portuguese"],"seda":["portuguese","turkish"],"sedento":["portuguese"],"sediado":["portuguese"],"sedoso":["portuguese"],"sedutor":["portuguese"],"segmento":["portuguese"],"segredo":["portuguese"],"segundo":["portuguese"],"seiva":["portuguese"],"seleto":["portuguese"],"selvagem":["portuguese"],"semanal":["portuguese"],"semente":["portuguese"],"senador":["portuguese"],"senhor":["portuguese"],"sensual":["portuguese"],"sentado":["portuguese"],"separado":["portuguese"],"sereia":["portuguese"],"seringa":["portuguese"],"serra":["portuguese"],"servo":["portuguese"],"setembro":["portuguese"],"setor":["portuguese"],"sigilo":["portuguese"],"silhueta":["portuguese"],"silicone":["portuguese"],"simetria":["portuguese"],"simpatia":["portuguese"],"simular":["portuguese"],"sinal":["portuguese"],"sincero":["portuguese"],"singular":["portuguese"],"sinopse":["portuguese"],"sintonia":["portuguese"],"sirene":["portuguese"],"siri":["portuguese"],"situado":["portuguese"],"soberano":["portuguese"],"sobra":["portuguese"],"socorro":["portuguese"],"sogro":["portuguese"],"soja":["portuguese"],"solda":["portuguese"],"soletrar":["portuguese"],"solteiro":["portuguese"],"sombrio":["portuguese"],"sonata":["portuguese"],"sondar":["portuguese"],"sonegar":["portuguese"],"sonhador":["portuguese"],"sono":["portuguese"],"soprano":["portuguese"],"soquete":["portuguese"],"sorrir":["portuguese"],"sorteio":["portuguese"],"sossego":["portuguese"],"sotaque":["portuguese"],"soterrar":["portuguese"],"sovado":["portuguese"],"sozinho":["portuguese"],"suavizar":["portuguese"],"subida":["portuguese"],"submerso":["portuguese"],"subsolo":["portuguese"],"subtrair":["portuguese"],"sucata":["portuguese"],"sucesso":["portuguese"],"suco":["portuguese"],"sudeste":["portuguese"],"sufixo":["portuguese"],"sugador":["portuguese"],"sugerir":["portuguese"],"sujeito":["portuguese"],"sulfato":["portuguese"],"sumir":["portuguese"],"suor":["portuguese"],"superior":["portuguese"],"suplicar":["portuguese"],"suposto":["portuguese"],"suprimir":["portuguese"],"surdina":["portuguese"],"surfista":["portuguese"],"surpresa":["portuguese"],"surreal":["portuguese"],"surtir":["portuguese"],"suspiro":["portuguese"],"sustento":["portuguese"],"tabela":["portuguese","turkish"],"tablete":["portuguese"],"tabuada":["portuguese"],"tacho":["portuguese"],"tagarela":["portuguese"],"talher":["portuguese"],"talo":["portuguese"],"talvez":["portuguese"],"tamanho":["portuguese"],"tamborim":["portuguese"],"tampa":["portuguese"],"tangente":["portuguese"],"tanto":["portuguese"],"tapar":["portuguese"],"tapioca":["portuguese"],"tardio":["portuguese"],"tarefa":["portuguese"],"tarja":["portuguese"],"tarraxa":["portuguese"],"tatuagem":["portuguese"],"taurino":["portuguese"],"taxativo":["portuguese"],"taxista":["portuguese"],"teatral":["portuguese"],"tecer":["portuguese"],"tecido":["portuguese"],"teclado":["portuguese"],"tedioso":["portuguese"],"teia":["portuguese"],"teimar":["portuguese"],"telefone":["portuguese"],"telhado":["portuguese"],"tempero":["portuguese"],"tenente":["portuguese"],"tensor":["portuguese"],"tentar":["portuguese"],"termal":["portuguese"],"terno":["portuguese"],"terreno":["portuguese"],"tese":["portuguese"],"tesoura":["portuguese"],"testado":["portuguese"],"teto":["portuguese"],"textura":["portuguese"],"texugo":["portuguese"],"tiara":["portuguese"],"tigela":["portuguese"],"tijolo":["portuguese"],"timbrar":["portuguese"],"timidez":["portuguese"],"tingido":["portuguese"],"tinteiro":["portuguese"],"tiragem":["portuguese"],"titular":["portuguese"],"toalha":["portuguese"],"tocha":["portuguese"],"tolerar":["portuguese"],"tolice":["portuguese"],"tomada":["portuguese"],"tomilho":["portuguese"],"tonel":["portuguese"],"tontura":["portuguese"],"topete":["portuguese"],"tora":["portuguese"],"torcido":["portuguese"],"torneio":["portuguese"],"torque":["portuguese"],"torrada":["portuguese"],"torto":["portuguese"],"tostar":["portuguese"],"touca":["portuguese"],"toupeira":["portuguese"],"toxina":["portuguese"],"trabalho":["portuguese"],"tracejar":["portuguese"],"tradutor":["portuguese"],"trafegar":["portuguese"],"trajeto":["portuguese"],"trama":["portuguese"],"trancar":["portuguese"],"trapo":["portuguese"],"traseiro":["portuguese"],"tratador":["portuguese"],"travar":["portuguese"],"treino":["portuguese"],"tremer":["portuguese"],"trepidar":["portuguese"],"trevo":["portuguese"],"triagem":["portuguese"],"tribo":["portuguese"],"triciclo":["portuguese"],"tridente":["portuguese"],"trilogia":["portuguese"],"trindade":["portuguese"],"triplo":["portuguese"],"triturar":["portuguese"],"triunfal":["portuguese"],"trocar":["portuguese"],"trombeta":["portuguese"],"trova":["portuguese"],"trunfo":["portuguese"],"truque":["portuguese"],"tubular":["portuguese"],"tucano":["portuguese"],"tudo":["portuguese"],"tulipa":["portuguese"],"tupi":["portuguese"],"turbo":["portuguese"],"turma":["portuguese"],"turquesa":["portuguese"],"tutelar":["portuguese"],"tutorial":["portuguese"],"uivar":["portuguese"],"umbigo":["portuguese"],"unha":["portuguese"],"unidade":["portuguese"],"uniforme":["portuguese"],"urologia":["portuguese"],"urso":["portuguese"],"urtiga":["portuguese"],"urubu":["portuguese"],"usado":["portuguese"],"usina":["portuguese"],"usufruir":["portuguese"],"vacina":["portuguese"],"vadiar":["portuguese"],"vagaroso":["portuguese"],"vaidoso":["portuguese"],"vala":["portuguese"],"valente":["portuguese"],"validade":["portuguese"],"valores":["portuguese"],"vantagem":["portuguese"],"vaqueiro":["portuguese"],"varanda":["portuguese"],"vareta":["portuguese"],"varrer":["portuguese"],"vascular":["portuguese"],"vasilha":["portuguese"],"vassoura":["portuguese"],"vazar":["portuguese"],"vazio":["portuguese"],"veado":["portuguese"],"vedar":["portuguese"],"vegetar":["portuguese"],"veicular":["portuguese"],"veleiro":["portuguese"],"velhice":["portuguese"],"veludo":["portuguese"],"vencedor":["portuguese"],"vendaval":["portuguese"],"venerar":["portuguese"],"ventre":["portuguese"],"verbal":["portuguese"],"verdade":["portuguese"],"vereador":["portuguese"],"vergonha":["portuguese"],"vermelho":["portuguese"],"verniz":["portuguese"],"versar":["portuguese"],"vertente":["portuguese"],"vespa":["portuguese"],"vestido":["portuguese"],"vetorial":["portuguese"],"viaduto":["portuguese"],"viagem":["portuguese"],"viajar":["portuguese"],"viatura":["portuguese"],"vibrador":["portuguese"],"videira":["portuguese"],"vidraria":["portuguese"],"viela":["portuguese"],"viga":["portuguese"],"vigente":["portuguese"],"vigiar":["portuguese"],"vigorar":["portuguese"],"vilarejo":["portuguese"],"vinco":["portuguese"],"vinheta":["portuguese"],"vinil":["portuguese"],"violeta":["portuguese"],"virada":["portuguese"],"virtude":["portuguese"],"visitar":["portuguese"],"visto":["portuguese"],"vitral":["portuguese"],"viveiro":["portuguese"],"vizinho":["portuguese"],"voador":["portuguese"],"voar":["portuguese"],"vogal":["portuguese"],"volante":["portuguese"],"voleibol":["portuguese"],"voltagem":["portuguese"],"volumoso":["portuguese"],"vontade":["portuguese"],"vulto":["portuguese"],"vuvuzela":["portuguese"],"xadrez":["portuguese"],"xarope":["portuguese"],"xeque":["portuguese"],"xeretar":["portuguese"],"xerife":["portuguese"],"xingar":["portuguese"],"zangado":["portuguese"],"zarpar":["portuguese"],"zebu":["portuguese"],"zelador":["portuguese"],"zombar":["portuguese"],"zoologia":["portuguese"],"zumbido":["portuguese"],"абзац":["russian"],"абонент":["russian"],"абсурд":["russian"],"авангард":["russian"],"авария":["russian"],"август":["russian"],"авиация":["russian"],"автор":["russian"],"агент":["russian"],"агитация":["russian"],"агрегат":["russian"],"адвокат":["russian"],"адмирал":["russian"],"адрес":["russian"],"азарт":["russian"],"азот":["russian"],"академия":["russian"],"аквариум":["russian"],"аксиома":["russian"],"акула":["russian"],"акцент":["russian"],"акция":["russian"],"аллея":["russian"],"алмаз":["russian"],"алтарь":["russian"],"альбом":["russian"],"альянс":["russian"],"амбиция":["russian"],"анализ":["russian"],"анекдот":["russian"],"анкета":["russian"],"ансамбль":["russian"],"антенна":["russian"],"апельсин":["russian"],"аппарат":["russian"],"аппетит":["russian"],"апрель":["russian"],"аптека":["russian"],"арбуз":["russian"],"аргумент":["russian"],"аренда":["russian"],"арест":["russian"],"армия":["russian"],"аромат":["russian"],"арсенал":["russian"],"артерия":["russian"],"артист":["russian"],"архив":["russian"],"аспирант":["russian"],"асфальт":["russian"],"атака":["russian"],"атомный":["russian"],"атрибут":["russian"],"аукцион":["russian"],"афиша":["russian"],"аэропорт":["russian"],"бабочка":["russian"],"бабушка":["russian"],"багаж":["russian"],"база":["russian"],"бактерия":["russian"],"баланс":["russian"],"балерина":["russian"],"балкон":["russian"],"бандит":["russian"],"банк":["russian"],"барабан":["russian"],"барон":["russian"],"барышня":["russian"],"барьер":["russian"],"бассейн":["russian"],"батарея":["russian"],"башмак":["russian"],"башня":["russian"],"бедный":["russian"],"беженец":["russian"],"бездна":["russian"],"белка":["russian"],"белый":["russian"],"бензин":["russian"],"берег":["russian"],"беседа":["russian"],"бешеный":["russian"],"билет":["russian"],"бинокль":["russian"],"биржа":["russian"],"битва":["russian"],"благо":["russian"],"блеск":["russian"],"близкий":["russian"],"блин":["russian"],"блок":["russian"],"блюдо":["russian"],"богатый":["russian"],"бодрый":["russian"],"боец":["russian"],"бокал":["russian"],"боковой":["russian"],"бокс":["russian"],"более":["russian"],"болото":["russian"],"болтать":["russian"],"большой":["russian"],"бомба":["russian"],"борт":["russian"],"борьба":["russian"],"босой":["russian"],"ботинок":["russian"],"бояться":["russian"],"брак":["russian"],"брать":["russian"],"бревно":["russian"],"бред":["russian"],"бригада":["russian"],"бродяга":["russian"],"броня":["russian"],"бросить":["russian"],"брызги":["russian"],"брюки":["russian"],"брюхо":["russian"],"бугор":["russian"],"будка":["russian"],"будни":["russian"],"будущее":["russian"],"буква":["russian"],"букет":["russian"],"бульвар":["russian"],"бумага":["russian"],"бунт":["russian"],"бурный":["russian"],"буря":["russian"],"бутылка":["russian"],"бухта":["russian"],"бывший":["russian"],"быстро":["russian"],"бытовой":["russian"],"быть":["russian"],"бюджет":["russian"],"бюро":["russian"],"бюст":["russian"],"вагон":["russian"],"важный":["russian"],"вакцина":["russian"],"валенок":["russian"],"вальс":["russian"],"валюта":["russian"],"ванная":["russian"],"варенье":["russian"],"вариант":["russian"],"вблизи":["russian"],"вверх":["russian"],"вводить":["russian"],"вдали":["russian"],"вдвое":["russian"],"вдова":["russian"],"вдоль":["russian"],"вдруг":["russian"],"ведро":["russian"],"ведущий":["russian"],"ведьма":["russian"],"вежливо":["russian"],"везде":["russian"],"веко":["russian"],"вексель":["russian"],"велеть":["russian"],"великий":["russian"],"венец":["russian"],"веник":["russian"],"веранда":["russian"],"верблюд":["russian"],"верить":["russian"],"верный":["russian"],"версия":["russian"],"вертеть":["russian"],"верхний":["russian"],"вершина":["russian"],"весело":["russian"],"весна":["russian"],"весомый":["russian"],"вести":["russian"],"весь":["russian"],"ветеран":["russian"],"ветхий":["russian"],"вечер":["russian"],"вечно":["russian"],"вешалка":["russian"],"вещество":["russian"],"взамен":["russian"],"взгляд":["russian"],"вздох":["russian"],"взнос":["russian"],"взойти":["russian"],"взор":["russian"],"взрыв":["russian"],"взять":["russian"],"видеть":["russian"],"видимо":["russian"],"визг":["russian"],"визит":["russian"],"вилка":["russian"],"вина":["russian"],"вирус":["russian"],"висок":["russian"],"витамин":["russian"],"витрина":["russian"],"вихрь":["russian"],"вишня":["russian"],"вкус":["russian"],"влага":["russian"],"владелец":["russian"],"власть":["russian"],"влево":["russian"],"влияние":["russian"],"вложить":["russian"],"вместе":["russian"],"внешний":["russian"],"вникать":["russian"],"внимание":["russian"],"вновь":["russian"],"внук":["russian"],"внутри":["russian"],"внучка":["russian"],"внушать":["russian"],"вовлечь":["russian"],"вовремя":["russian"],"вовсю":["russian"],"вода":["russian"],"водород":["russian"],"водяной":["russian"],"воевать":["russian"],"возврат":["russian"],"возглас":["russian"],"воздух":["russian"],"возить":["russian"],"возле":["russian"],"возня":["russian"],"возраст":["russian"],"война":["russian"],"войско":["russian"],"вокзал":["russian"],"волос":["russian"],"волчий":["russian"],"вольный":["russian"],"воля":["russian"],"вообще":["russian"],"вопль":["russian"],"вопрос":["russian"],"ворота":["russian"],"восемь":["russian"],"восток":["russian"],"вплоть":["russian"],"вполне":["russian"],"вправе":["russian"],"впредь":["russian"],"впрочем":["russian"],"врач":["russian"],"вредный":["russian"],"время":["russian"],"вручить":["russian"],"всадник":["russian"],"всегда":["russian"],"вскоре":["russian"],"вскрыть":["russian"],"всплеск":["russian"],"вспышка":["russian"],"встреча":["russian"],"всюду":["russian"],"всякий":["russian"],"второй":["russian"],"вход":["russian"],"вчера":["russian"],"выбор":["russian"],"вывод":["russian"],"выгнать":["russian"],"выдать":["russian"],"выехать":["russian"],"вызов":["russian"],"выйти":["russian"],"выкуп":["russian"],"вылезти":["russian"],"вымыть":["russian"],"выпасть":["russian"],"выпить":["russian"],"выплата":["russian"],"выпуск":["russian"],"вырасти":["russian"],"выручка":["russian"],"выслать":["russian"],"высокий":["russian"],"выставка":["russian"],"вышка":["russian"],"вязать":["russian"],"вялый":["russian"],"газета":["russian"],"газовый":["russian"],"галерея":["russian"],"галстук":["russian"],"гамма":["russian"],"гарантия":["russian"],"гармония":["russian"],"гарнизон":["russian"],"гастроли":["russian"],"гвардия":["russian"],"гвоздь":["russian"],"гектар":["russian"],"генерал":["russian"],"гений":["russian"],"геном":["russian"],"геолог":["russian"],"герб":["russian"],"герой":["russian"],"гибкий":["russian"],"гигант":["russian"],"гимн":["russian"],"гипотеза":["russian"],"гитара":["russian"],"главный":["russian"],"глагол":["russian"],"гладить":["russian"],"глаз":["russian"],"глина":["russian"],"глоток":["russian"],"глубокий":["russian"],"глупый":["russian"],"глухой":["russian"],"глыба":["russian"],"глядеть":["russian"],"гнев":["russian"],"гнездо":["russian"],"гнилой":["russian"],"годовой":["russian"],"голова":["russian"],"голубой":["russian"],"голый":["russian"],"гонорар":["russian"],"гордость":["russian"],"горизонт":["russian"],"горло":["russian"],"горный":["russian"],"город":["russian"],"горшок":["russian"],"горький":["russian"],"горючее":["russian"],"горячий":["russian"],"готовый":["russian"],"градус":["russian"],"грамм":["russian"],"граница":["russian"],"граф":["russian"],"гребень":["russian"],"гриб":["russian"],"гримаса":["russian"],"грозить":["russian"],"грохот":["russian"],"грош":["russian"],"грубый":["russian"],"грудь":["russian"],"груз":["russian"],"грунт":["russian"],"группа":["russian"],"груша":["russian"],"грязный":["russian"],"губа":["russian"],"гудок":["russian"],"гулкий":["russian"],"гулять":["russian"],"гусеница":["russian"],"густо":["russian"],"гусь":["russian"],"давление":["russian"],"давно":["russian"],"даже":["russian"],"дальний":["russian"],"данный":["russian"],"дарить":["russian"],"датчик":["russian"],"дать":["russian"],"дача":["russian"],"двадцать":["russian"],"дважды":["russian"],"дверь":["russian"],"двигать":["russian"],"движение":["russian"],"двойной":["russian"],"двор":["russian"],"дебют":["russian"],"девятый":["russian"],"дежурный":["russian"],"действие":["russian"],"декабрь":["russian"],"деление":["russian"],"дело":["russian"],"дельфин":["russian"],"день":["russian"],"дерево":["russian"],"держать":["russian"],"дерзкий":["russian"],"десять":["russian"],"деталь":["russian"],"детский":["russian"],"дефект":["russian"],"дефицит":["russian"],"деятель":["russian"],"джаз":["russian"],"джинсы":["russian"],"джунгли":["russian"],"диагноз":["russian"],"диалог":["russian"],"диапазон":["russian"],"диван":["russian"],"дивизия":["russian"],"дивный":["russian"],"диета":["russian"],"дизайн":["russian"],"дикарь":["russian"],"дилер":["russian"],"динамика":["russian"],"диплом":["russian"],"директор":["russian"],"дитя":["russian"],"длинный":["russian"],"дневник":["russian"],"добрый":["russian"],"добыча":["russian"],"доверие":["russian"],"догадка":["russian"],"догнать":["russian"],"дождь":["russian"],"доклад":["russian"],"доктор":["russian"],"документ":["russian"],"долго":["russian"],"должен":["russian"],"долина":["russian"],"донос":["russian"],"дорога":["russian"],"досада":["russian"],"доска":["russian"],"достать":["russian"],"досуг":["russian"],"доход":["russian"],"доцент":["russian"],"дощатый":["russian"],"драка":["russian"],"древний":["russian"],"дремать":["russian"],"дробный":["russian"],"дрова":["russian"],"дрожать":["russian"],"другой":["russian"],"дружба":["russian"],"дубовый":["russian"],"дуга":["russian"],"думать":["russian"],"дурной":["russian"],"духи":["russian"],"душный":["russian"],"дуэль":["russian"],"дуэт":["russian"],"дыра":["russian"],"дыхание":["russian"],"дюжина":["russian"],"дядя":["russian"],"едва":["russian"],"единый":["russian"],"ерунда":["russian"],"если":["russian"],"ехать":["russian"],"жадный":["russian"],"жажда":["russian"],"жалеть":["russian"],"жалоба":["russian"],"жанр":["russian"],"жареный":["russian"],"жаркий":["russian"],"жгучий":["russian"],"жевать":["russian"],"желание":["russian"],"желудок":["russian"],"жена":["russian"],"женщина":["russian"],"жертва":["russian"],"жест":["russian"],"жидкость":["russian"],"житель":["russian"],"жить":["russian"],"жрец":["russian"],"жулик":["russian"],"журнал":["russian"],"жуткий":["russian"],"забрать":["russian"],"забыть":["russian"],"завести":["russian"],"завод":["russian"],"завтра":["russian"],"загадка":["russian"],"загнать":["russian"],"заговор":["russian"],"задача":["russian"],"задеть":["russian"],"задний":["russian"],"задолго":["russian"],"заехать":["russian"],"заказ":["russian"],"закон":["russian"],"закрыть":["russian"],"закуска":["russian"],"залезть":["russian"],"залить":["russian"],"залп":["russian"],"замок":["russian"],"замуж":["russian"],"замысел":["russian"],"занавес":["russian"],"заново":["russian"],"занять":["russian"],"заодно":["russian"],"запись":["russian"],"запрос":["russian"],"запуск":["russian"],"запястье":["russian"],"заранее":["russian"],"заросль":["russian"],"зарплата":["russian"],"заря":["russian"],"засада":["russian"],"заслуга":["russian"],"заснуть":["russian"],"застать":["russian"],"затвор":["russian"],"затеять":["russian"],"затрата":["russian"],"затылок":["russian"],"захват":["russian"],"зачем":["russian"],"защита":["russian"],"заявить":["russian"],"заяц":["russian"],"звезда":["russian"],"звено":["russian"],"звонить":["russian"],"здесь":["russian"],"зелень":["russian"],"земля":["russian"],"зеркало":["russian"],"зерно":["russian"],"зима":["russian"],"злой":["russian"],"змея":["russian"],"знамя":["russian"],"знание":["russian"],"значит":["russian"],"золотой":["russian"],"зона":["russian"],"зонтик":["russian"],"зоопарк":["russian"],"зрачок":["russian"],"зрение":["russian"],"зритель":["russian"],"зубной":["russian"],"зубр":["russian"],"игла":["russian"],"идеал":["russian"],"идеолог":["russian"],"идея":["russian"],"идол":["russian"],"идти":["russian"],"изба":["russian"],"избить":["russian"],"избрать":["russian"],"избыток":["russian"],"извлечь":["russian"],"извне":["russian"],"изгиб":["russian"],"изгнать":["russian"],"издание":["russian"],"изделие":["russian"],"изнутри":["russian"],"изобилие":["russian"],"изоляция":["russian"],"изредка":["russian"],"изрядно":["russian"],"изучение":["russian"],"изъять":["russian"],"изящный":["russian"],"икона":["russian"],"икра":["russian"],"иллюзия":["russian"],"именно":["russian"],"иметь":["russian"],"имидж":["russian"],"империя":["russian"],"импульс":["russian"],"иначе":["russian"],"инвалид":["russian"],"индекс":["russian"],"индивид":["russian"],"инерция":["russian"],"инженер":["russian"],"иногда":["russian"],"иной":["russian"],"институт":["russian"],"интерес":["russian"],"интрига":["russian"],"интуиция":["russian"],"инфаркт":["russian"],"инцидент":["russian"],"ирония":["russian"],"искать":["russian"],"испуг":["russian"],"история":["russian"],"итог":["russian"],"июнь":["russian"],"кабель":["russian"],"кабинет":["russian"],"каблук":["russian"],"кавалер":["russian"],"кадр":["russian"],"каждый":["russian"],"кажется":["russian"],"казино":["russian"],"калитка":["russian"],"камень":["russian"],"камин":["russian"],"канал":["russian"],"кандидат":["russian"],"каникулы":["russian"],"канон":["russian"],"капитан":["russian"],"капля":["russian"],"капот":["russian"],"капуста":["russian"],"карандаш":["russian"],"карета":["russian"],"каркас":["russian"],"карман":["russian"],"картина":["russian"],"карьера":["russian"],"каска":["russian"],"кассета":["russian"],"кастрюля":["russian"],"каталог":["russian"],"катер":["russian"],"каток":["russian"],"катушка":["russian"],"кафедра":["russian"],"качество":["russian"],"каша":["russian"],"кашлять":["russian"],"каюта":["russian"],"квадрат":["russian"],"квартира":["russian"],"квота":["russian"],"кепка":["russian"],"кивнуть":["russian"],"километр":["russian"],"кино":["russian"],"киоск":["russian"],"кипяток":["russian"],"кирпич":["russian"],"кислота":["russian"],"кисть":["russian"],"клавиша":["russian"],"клапан":["russian"],"класс":["russian"],"клей":["russian"],"клетка":["russian"],"клиент":["russian"],"климат":["russian"],"клиника":["russian"],"кличка":["russian"],"клоун":["russian"],"клочок":["russian"],"клуб":["russian"],"клумба":["russian"],"ключ":["russian"],"книга":["russian"],"кнопка":["russian"],"кнут":["russian"],"княгиня":["russian"],"князь":["russian"],"кобура":["russian"],"когда":["russian"],"кодекс":["russian"],"кожа":["russian"],"коктейль":["russian"],"колено":["russian"],"коллега":["russian"],"колонна":["russian"],"колпак":["russian"],"кольцо":["russian"],"колючий":["russian"],"коляска":["russian"],"команда":["russian"],"комедия":["russian"],"комиссия":["russian"],"коммуна":["russian"],"комната":["russian"],"комок":["russian"],"компания":["russian"],"комфорт":["russian"],"конвейер":["russian"],"конгресс":["russian"],"конечно":["russian"],"конкурс":["russian"],"контроль":["russian"],"концерт":["russian"],"конь":["russian"],"конюшня":["russian"],"копать":["russian"],"копейка":["russian"],"копыто":["russian"],"корабль":["russian"],"корень":["russian"],"корзина":["russian"],"коридор":["russian"],"кормить":["russian"],"корпус":["russian"],"космос":["russian"],"костюм":["russian"],"косяк":["russian"],"котел":["russian"],"котлета":["russian"],"который":["russian"],"коттедж":["russian"],"кофе":["russian"],"кофта":["russian"],"кошка":["russian"],"кража":["russian"],"край":["russian"],"красный":["russian"],"краткий":["russian"],"кредит":["russian"],"крем":["russian"],"крепкий":["russian"],"кресло":["russian"],"кривой":["russian"],"кризис":["russian"],"кристалл":["russian"],"критерий":["russian"],"кричать":["russian"],"кровь":["russian"],"крокодил":["russian"],"кролик":["russian"],"кроме":["russian"],"крона":["russian"],"круг":["russian"],"кружка":["russian"],"крупный":["russian"],"крутой":["russian"],"крушение":["russian"],"крыло":["russian"],"крыша":["russian"],"крючок":["russian"],"кстати":["russian"],"кубик":["russian"],"куда":["russian"],"кузов":["russian"],"кукла":["russian"],"кулак":["russian"],"кулиса":["russian"],"культура":["russian"],"кумир":["russian"],"купе":["russian"],"купить":["russian"],"купол":["russian"],"купюра":["russian"],"курица":["russian"],"курорт":["russian"],"курс":["russian"],"куртка":["russian"],"кусок":["russian"],"куст":["russian"],"кухня":["russian"],"кушать":["russian"],"лабиринт":["russian"],"лавка":["russian"],"лагерь":["russian"],"ладно":["russian"],"ладонь":["russian"],"лапа":["russian"],"лауреат":["russian"],"лгать":["russian"],"лебедь":["russian"],"левый":["russian"],"легенда":["russian"],"легкий":["russian"],"ледяной":["russian"],"лежать":["russian"],"лезвие":["russian"],"лезть":["russian"],"лекция":["russian"],"ленивый":["russian"],"лента":["russian"],"лепесток":["russian"],"лесной":["russian"],"лестница":["russian"],"лететь":["russian"],"лето":["russian"],"лечить":["russian"],"лига":["russian"],"лидер":["russian"],"лиловый":["russian"],"лимон":["russian"],"линия":["russian"],"липкий":["russian"],"лист":["russian"],"литр":["russian"],"лихой":["russian"],"лицо":["russian"],"лишить":["russian"],"лишний":["russian"],"ловить":["russian"],"логика":["russian"],"лодка":["russian"],"ложь":["russian"],"лозунг":["russian"],"локоть":["russian"],"лопата":["russian"],"лошадь":["russian"],"лукавый":["russian"],"луна":["russian"],"лучший":["russian"],"лысый":["russian"],"льгота":["russian"],"любить":["russian"],"любой":["russian"],"людской":["russian"],"люстра":["russian"],"лютый":["russian"],"лягушка":["russian"],"магазин":["russian"],"магия":["russian"],"майор":["russian"],"майский":["russian"],"максимум":["russian"],"макушка":["russian"],"мало":["russian"],"мальчик":["russian"],"мама":["russian"],"манера":["russian"],"марка":["russian"],"март":["russian"],"маршрут":["russian"],"масса":["russian"],"мастер":["russian"],"масштаб":["russian"],"материал":["russian"],"матч":["russian"],"махать":["russian"],"машина":["russian"],"маяк":["russian"],"мебель":["russian"],"медаль":["russian"],"медведь":["russian"],"медицина":["russian"],"медь":["russian"],"между":["russian"],"мелкий":["russian"],"мелочь":["russian"],"мемуары":["russian"],"меньше":["russian"],"меню":["russian"],"менять":["russian"],"мера":["russian"],"мерцать":["russian"],"место":["russian"],"месяц":["russian"],"металл":["russian"],"метод":["russian"],"метр":["russian"],"механизм":["russian"],"меховой":["russian"],"мечтать":["russian"],"мешать":["russian"],"мешок":["russian"],"миграция":["russian"],"микрофон":["russian"],"милиция":["russian"],"миллион":["russian"],"милость":["russian"],"миля":["russian"],"мимо":["russian"],"минерал":["russian"],"министр":["russian"],"минута":["russian"],"мирный":["russian"],"миска":["russian"],"миссия":["russian"],"митинг":["russian"],"мишень":["russian"],"младший":["russian"],"мнение":["russian"],"мнимый":["russian"],"много":["russian"],"могучий":["russian"],"модель":["russian"],"может":["russian"],"мозг":["russian"],"мокрый":["russian"],"молекула":["russian"],"молния":["russian"],"молодой":["russian"],"молчать":["russian"],"момент":["russian"],"монета":["russian"],"монитор":["russian"],"монолог":["russian"],"монстр":["russian"],"монтаж":["russian"],"мораль":["russian"],"море":["russian"],"морковь":["russian"],"мороз":["russian"],"морщина":["russian"],"мостовая":["russian"],"мотать":["russian"],"мотив":["russian"],"мотор":["russian"],"мохнатый":["russian"],"мрамор":["russian"],"мрачный":["russian"],"мстить":["russian"],"мудрый":["russian"],"мужество":["russian"],"мужчина":["russian"],"музей":["russian"],"музыка":["russian"],"мундир":["russian"],"муравей":["russian"],"мусор":["russian"],"муха":["russian"],"мчаться":["russian"],"мысль":["russian"],"мыться":["russian"],"мышца":["russian"],"мышь":["russian"],"мюзикл":["russian"],"мягкий":["russian"],"мясо":["russian"],"набор":["russian"],"навык":["russian"],"наглый":["russian"],"нагрузка":["russian"],"надежда":["russian"],"надзор":["russian"],"надо":["russian"],"наедине":["russian"],"назад":["russian"],"название":["russian"],"назло":["russian"],"наивный":["russian"],"найти":["russian"],"наконец":["russian"],"налево":["russian"],"наличие":["russian"],"налог":["russian"],"намерен":["russian"],"нанести":["russian"],"напасть":["russian"],"например":["russian"],"народ":["russian"],"наследие":["russian"],"натура":["russian"],"наука":["russian"],"наутро":["russian"],"начать":["russian"],"небо":["russian"],"неважно":["russian"],"невеста":["russian"],"негодяй":["russian"],"недавно":["russian"],"неделя":["russian"],"недолго":["russian"],"недра":["russian"],"недуг":["russian"],"нежный":["russian"],"незачем":["russian"],"некто":["russian"],"нелепый":["russian"],"неловко":["russian"],"нельзя":["russian"],"немало":["russian"],"немой":["russian"],"неплохо":["russian"],"нервный":["russian"],"нередко":["russian"],"нестись":["russian"],"неудача":["russian"],"неужели":["russian"],"нефть":["russian"],"неясный":["russian"],"нигде":["russian"],"низкий":["russian"],"никакой":["russian"],"никогда":["russian"],"никуда":["russian"],"ничто":["russian"],"ничуть":["russian"],"ниша":["russian"],"нищий":["russian"],"новость":["russian"],"новый":["russian"],"нога":["russian"],"ноготь":["russian"],"ножницы":["russian"],"ноздря":["russian"],"номер":["russian"],"носить":["russian"],"носок":["russian"],"ночь":["russian"],"ноябрь":["russian"],"нрав":["russian"],"нуль":["russian"],"нынче":["russian"],"нырять":["russian"],"нюанс":["russian"],"няня":["russian"],"обаяние":["russian"],"обед":["russian"],"обезьяна":["russian"],"обещать":["russian"],"обжечь":["russian"],"обзор":["russian"],"обилие":["russian"],"обитать":["russian"],"область":["russian"],"облик":["russian"],"обложка":["russian"],"обмен":["russian"],"обморок":["russian"],"обожать":["russian"],"обои":["russian"],"оболочка":["russian"],"оборона":["russian"],"обочина":["russian"],"образ":["russian"],"обрести":["russian"],"обрыв":["russian"],"обувь":["russian"],"обучение":["russian"],"обход":["russian"],"общество":["russian"],"общий":["russian"],"объект":["russian"],"обыск":["russian"],"обычно":["russian"],"обязать":["russian"],"овощи":["russian"],"овраг":["russian"],"овца":["russian"],"оговорка":["russian"],"ограда":["russian"],"огурец":["russian"],"одежда":["russian"],"одеяло":["russian"],"один":["russian"],"однако":["russian"],"одолеть":["russian"],"ожидать":["russian"],"озеро":["russian"],"океан":["russian"],"окно":["russian"],"около":["russian"],"окоп":["russian"],"окраина":["russian"],"октябрь":["russian"],"опасный":["russian"],"опека":["russian"],"операция":["russian"],"описание":["russian"],"оплата":["russian"],"опора":["russian"],"оппонент":["russian"],"оптимизм":["russian"],"оптовый":["russian"],"опухоль":["russian"],"опыт":["russian"],"оратор":["russian"],"орбита":["russian"],"орган":["russian"],"орден":["russian"],"орел":["russian"],"оригинал":["russian"],"ориентир":["russian"],"оркестр":["russian"],"оружие":["russian"],"осенний":["russian"],"осколок":["russian"],"осмотр":["russian"],"остров":["russian"],"отбор":["russian"],"отбыть":["russian"],"отвлечь":["russian"],"отдать":["russian"],"отдел":["russian"],"отдых":["russian"],"отель":["russian"],"отец":["russian"],"отзыв":["russian"],"отказ":["russian"],"отклик":["russian"],"открыть":["russian"],"откуда":["russian"],"отличие":["russian"],"отныне":["russian"],"отойти":["russian"],"отпуск":["russian"],"отрасль":["russian"],"отросток":["russian"],"отрывок":["russian"],"отряд":["russian"],"отсек":["russian"],"отставка":["russian"],"отсюда":["russian"],"оттенок":["russian"],"оттого":["russian"],"отчего":["russian"],"отъезд":["russian"],"офис":["russian"],"офицер":["russian"],"охота":["russian"],"охрана":["russian"],"оценка":["russian"],"очаг":["russian"],"очень":["russian"],"очередь":["russian"],"очищать":["russian"],"ошибка":["russian"],"ощущение":["russian"],"павильон":["russian"],"падать":["russian"],"пазуха":["russian"],"пакет":["russian"],"палата":["russian"],"палец":["russian"],"палуба":["russian"],"пальто":["russian"],"память":["russian"],"панель":["russian"],"паника":["russian"],"пара":["russian"],"парень":["russian"],"пароход":["russian"],"партия":["russian"],"парус":["russian"],"паспорт":["russian"],"пассажир":["russian"],"пастух":["russian"],"патент":["russian"],"патрон":["russian"],"пауза":["russian"],"паук":["russian"],"паутина":["russian"],"пафос":["russian"],"пахнуть":["russian"],"пациент":["russian"],"пачка":["russian"],"певец":["russian"],"педагог":["russian"],"пейзаж":["russian"],"пенсия":["russian"],"пепел":["russian"],"первый":["russian"],"перед":["russian"],"период":["russian"],"перо":["russian"],"перрон":["russian"],"персонаж":["russian"],"перчатка":["russian"],"песня":["russian"],"песок":["russian"],"петля":["russian"],"петрушка":["russian"],"петух":["russian"],"пехота":["russian"],"печать":["russian"],"печень":["russian"],"пешком":["russian"],"пещера":["russian"],"пианист":["russian"],"пиджак":["russian"],"пилот":["russian"],"пионер":["russian"],"пирамида":["russian"],"пирожок":["russian"],"письмо":["russian"],"пища":["russian"],"плавание":["russian"],"плакать":["russian"],"пламя":["russian"],"план":["russian"],"пласт":["russian"],"платить":["russian"],"пленный":["russian"],"плечо":["russian"],"плита":["russian"],"плод":["russian"],"плоский":["russian"],"плотный":["russian"],"плохой":["russian"],"площадь":["russian"],"плыть":["russian"],"плюс":["russian"],"пляж":["russian"],"плясать":["russian"],"победа":["russian"],"повар":["russian"],"повод":["russian"],"повсюду":["russian"],"повязка":["russian"],"погода":["russian"],"погреб":["russian"],"подбор":["russian"],"подвиг":["russian"],"подделка":["russian"],"поджать":["russian"],"поднос":["russian"],"подпись":["russian"],"подруга":["russian"],"подход":["russian"],"подчас":["russian"],"подъезд":["russian"],"поединок":["russian"],"поезд":["russian"],"поесть":["russian"],"поехать":["russian"],"пожалуй":["russian"],"пожилой":["russian"],"позади":["russian"],"позвать":["russian"],"поздний":["russian"],"позиция":["russian"],"позор":["russian"],"поиск":["russian"],"поймать":["russian"],"пойти":["russian"],"поклон":["russian"],"покой":["russian"],"покрыть":["russian"],"полдень":["russian"],"полезный":["russian"],"ползти":["russian"],"полк":["russian"],"полный":["russian"],"половина":["russian"],"полтора":["russian"],"польза":["russian"],"поляна":["russian"],"помидор":["russian"],"помнить":["russian"],"помощь":["russian"],"попасть":["russian"],"поперек":["russian"],"поплыть":["russian"],"пополам":["russian"],"поправка":["russian"],"попугай":["russian"],"попытка":["russian"],"порог":["russian"],"портрет":["russian"],"порция":["russian"],"порыв":["russian"],"порядок":["russian"],"после":["russian"],"посол":["russian"],"посреди":["russian"],"постель":["russian"],"посуда":["russian"],"потом":["russian"],"похвала":["russian"],"похожий":["russian"],"поцелуй":["russian"],"почва":["russian"],"почему":["russian"],"пошлина":["russian"],"поэма":["russian"],"поэтому":["russian"],"право":["russian"],"праздник":["russian"],"практика":["russian"],"прах":["russian"],"преграда":["russian"],"предмет":["russian"],"прежде":["russian"],"прелесть":["russian"],"премия":["russian"],"препарат":["russian"],"пресса":["russian"],"прибыть":["russian"],"прижать":["russian"],"прийти":["russian"],"приказ":["russian"],"прилавок":["russian"],"пример":["russian"],"принять":["russian"],"природа":["russian"],"притом":["russian"],"прихожая":["russian"],"прицел":["russian"],"причина":["russian"],"приют":["russian"],"прогноз":["russian"],"продукт":["russian"],"проект":["russian"],"прожить":["russian"],"прокат":["russian"],"промысел":["russian"],"пропуск":["russian"],"просто":["russian"],"против":["russian"],"профиль":["russian"],"процесс":["russian"],"прочий":["russian"],"прошлый":["russian"],"прощать":["russian"],"пружина":["russian"],"прут":["russian"],"прыжок":["russian"],"прямой":["russian"],"птица":["russian"],"публика":["russian"],"пугать":["russian"],"пуговица":["russian"],"пузырь":["russian"],"пульт":["russian"],"пуля":["russian"],"пункт":["russian"],"пускать":["russian"],"пустой":["russian"],"путь":["russian"],"пухлый":["russian"],"пучок":["russian"],"пушистый":["russian"],"пушка":["russian"],"пчела":["russian"],"пшеница":["russian"],"пылать":["russian"],"пыль":["russian"],"пышный":["russian"],"пьеса":["russian"],"пятка":["russian"],"пятно":["russian"],"пятый":["russian"],"пятьсот":["russian"],"работа":["russian"],"равнина":["russian"],"ради":["russian"],"радость":["russian"],"радуга":["russian"],"разбить":["russian"],"развитие":["russian"],"разговор":["russian"],"раздел":["russian"],"различие":["russian"],"размер":["russian"],"разный":["russian"],"разрыв":["russian"],"разум":["russian"],"район":["russian"],"ракета":["russian"],"раковина":["russian"],"рамка":["russian"],"рано":["russian"],"рапорт":["russian"],"распад":["russian"],"рассказ":["russian"],"расти":["russian"],"расход":["russian"],"расцвет":["russian"],"рация":["russian"],"рвануть":["russian"],"рваться":["russian"],"реакция":["russian"],"ребро":["russian"],"реветь":["russian"],"редактор":["russian"],"редкий":["russian"],"реестр":["russian"],"режим":["russian"],"резать":["russian"],"резерв":["russian"],"резина":["russian"],"резко":["russian"],"резной":["russian"],"рейс":["russian"],"реклама":["russian"],"рекорд":["russian"],"религия":["russian"],"рельс":["russian"],"ремень":["russian"],"ремонт":["russian"],"реплика":["russian"],"репортаж":["russian"],"ресница":["russian"],"ресторан":["russian"],"реформа":["russian"],"рецепт":["russian"],"речь":["russian"],"решение":["russian"],"ржавый":["russian"],"риск":["russian"],"рисунок":["russian"],"ритуал":["russian"],"рифма":["russian"],"робко":["russian"],"робот":["russian"],"ровесник":["russian"],"ровно":["russian"],"родной":["russian"],"рождение":["russian"],"роза":["russian"],"розовый":["russian"],"розыск":["russian"],"роль":["russian"],"роман":["russian"],"роскошь":["russian"],"роспись":["russian"],"рост":["russian"],"рубашка":["russian"],"рубеж":["russian"],"рубить":["russian"],"рубрика":["russian"],"рудник":["russian"],"рука":["russian"],"рукопись":["russian"],"румяный":["russian"],"русло":["russian"],"рухнуть":["russian"],"ручей":["russian"],"ручной":["russian"],"рыба":["russian"],"рыжий":["russian"],"рынок":["russian"],"рыхлый":["russian"],"рыцарь":["russian"],"рычаг":["russian"],"рюкзак":["russian"],"рядом":["russian"],"садовый":["russian"],"сажать":["russian"],"салон":["russian"],"салфетка":["russian"],"салют":["russian"],"самец":["russian"],"самовар":["russian"],"самый":["russian"],"сани":["russian"],"санкция":["russian"],"сапог":["russian"],"сарай":["russian"],"сатира":["russian"],"сахар":["russian"],"сбить":["russian"],"сбоку":["russian"],"сборная":["russian"],"сбыт":["russian"],"свадьба":["russian"],"свалка":["russian"],"сварить":["russian"],"свежий":["russian"],"сверху":["russian"],"свет":["russian"],"свеча":["russian"],"свинья":["russian"],"свист":["russian"],"свитер":["russian"],"свобода":["russian"],"сводка":["russian"],"свой":["russian"],"свыше":["russian"],"связь":["russian"],"сдаться":["russian"],"сделать":["russian"],"сегмент":["russian"],"сегодня":["russian"],"седло":["russian"],"седой":["russian"],"седьмой":["russian"],"сезон":["russian"],"сейф":["russian"],"сейчас":["russian"],"секрет":["russian"],"сектор":["russian"],"секунда":["russian"],"семинар":["russian"],"семья":["russian"],"сенатор":["russian"],"сено":["russian"],"сенсация":["russian"],"сентябрь":["russian"],"сервис":["russian"],"сердце":["russian"],"середина":["russian"],"сержант":["russian"],"серия":["russian"],"серый":["russian"],"сессия":["russian"],"сесть":["russian"],"сетевой":["russian"],"сжатый":["russian"],"сжечь":["russian"],"сзади":["russian"],"сигнал":["russian"],"сиденье":["russian"],"сила":["russian"],"силуэт":["russian"],"сильный":["russian"],"символ":["russian"],"симпатия":["russian"],"симфония":["russian"],"синий":["russian"],"синтез":["russian"],"синяк":["russian"],"сирень":["russian"],"система":["russian"],"ситуация":["russian"],"сияние":["russian"],"сказать":["russian"],"скала":["russian"],"скамейка":["russian"],"скандал":["russian"],"скатерть":["russian"],"скачок":["russian"],"скважина":["russian"],"сквер":["russian"],"сквозь":["russian"],"скелет":["russian"],"скидка":["russian"],"склад":["russian"],"сколько":["russian"],"скорый":["russian"],"скосить":["russian"],"скот":["russian"],"скрипка":["russian"],"скудный":["russian"],"скука":["russian"],"слабый":["russian"],"слава":["russian"],"сладкий":["russian"],"слегка":["russian"],"след":["russian"],"слеза":["russian"],"слепой":["russian"],"слесарь":["russian"],"слишком":["russian"],"слово":["russian"],"слог":["russian"],"сложный":["russian"],"сломать":["russian"],"служба":["russian"],"слух":["russian"],"случай":["russian"],"слышать":["russian"],"слюна":["russian"],"смежный":["russian"],"смелый":["russian"],"сменить":["russian"],"смесь":["russian"],"сметана":["russian"],"смех":["russian"],"смола":["russian"],"смуглый":["russian"],"смутный":["russian"],"смущать":["russian"],"смысл":["russian"],"снайпер":["russian"],"снаряд":["russian"],"сначала":["russian"],"снег":["russian"],"снизу":["russian"],"сниться":["russian"],"сно��а":["russian"],"снять":["russian"],"собака":["russian"],"соблазн":["russian"],"собрание":["russian"],"событие":["russian"],"совесть":["russian"],"совсем":["russian"],"согласие":["russian"],"создать":["russian"],"сознание":["russian"],"созреть":["russian"],"сойтись":["russian"],"сокол":["russian"],"солдат":["russian"],"соленый":["russian"],"солнце":["russian"],"солома":["russian"],"сомнение":["russian"],"сонный":["russian"],"соперник":["russian"],"соратник":["russian"],"сорвать":["russian"],"сосед":["russian"],"сосиска":["russian"],"состав":["russian"],"сотня":["russian"],"соус":["russian"],"союз":["russian"],"спад":["russian"],"спальня":["russian"],"спасти":["russian"],"спектр":["russian"],"сперва":["russian"],"спешить":["russian"],"спина":["russian"],"спирт":["russian"],"список":["russian"],"спичка":["russian"],"сплав":["russian"],"спонсор":["russian"],"спор":["russian"],"способ":["russian"],"справка":["russian"],"спустя":["russian"],"спутник":["russian"],"сразу":["russian"],"средство":["russian"],"срок":["russian"],"срыв":["russian"],"ссора":["russian"],"ссылка":["russian"],"ставить":["russian"],"стадия":["russian"],"стакан":["russian"],"станция":["russian"],"старый":["russian"],"стая":["russian"],"стебель":["russian"],"стекло":["russian"],"стена":["russian"],"степень":["russian"],"стереть":["russian"],"стиль":["russian"],"стимул":["russian"],"стирать":["russian"],"стихи":["russian"],"стоить":["russian"],"стойка":["russian"],"стол":["russian"],"стонать":["russian"],"стопа":["russian"],"сторона":["russian"],"стоянка":["russian"],"страна":["russian"],"стричь":["russian"],"строгий":["russian"],"струя":["russian"],"студент":["russian"],"стук":["russian"],"ступня":["russian"],"стыдно":["russian"],"суббота":["russian"],"субъект":["russian"],"сувенир":["russian"],"сугроб":["russian"],"сугубо":["russian"],"судить":["russian"],"судно":["russian"],"судьба":["russian"],"суета":["russian"],"суметь":["russian"],"сумма":["russian"],"сумрак":["russian"],"сундук":["russian"],"супруг":["russian"],"суровый":["russian"],"сутки":["russian"],"сухой":["russian"],"суша":["russian"],"существо":["russian"],"сфера":["russian"],"схема":["russian"],"схожий":["russian"],"сценарий":["russian"],"счастье":["russian"],"считать":["russian"],"съезд":["russian"],"сыграть":["russian"],"сырой":["russian"],"сытый":["russian"],"сыщик":["russian"],"сюда":["russian"],"сюжет":["russian"],"сюрприз":["russian"],"тайна":["russian"],"также":["russian"],"такой":["russian"],"такси":["russian"],"тактика":["russian"],"талия":["russian"],"таможня":["russian"],"танец":["russian"],"таракан":["russian"],"тарелка":["russian"],"тариф":["russian"],"тащить":["russian"],"таять":["russian"],"тварь":["russian"],"театр":["russian"],"тезис":["russian"],"текст":["russian"],"текущий":["russian"],"телефон":["russian"],"тема":["russian"],"темнота":["russian"],"теневой":["russian"],"теннис":["russian"],"теория":["russian"],"теперь":["russian"],"тепло":["russian"],"терапия":["russian"],"терзать":["russian"],"термин":["russian"],"терпеть":["russian"],"терраса":["russian"],"терять":["russian"],"тесный":["russian"],"тетрадь":["russian"],"техника":["russian"],"течение":["russian"],"тигр":["russian"],"типовой":["russian"],"тираж":["russian"],"титул":["russian"],"тихий":["russian"],"ткань":["russian"],"товарищ":["russian"],"тоже":["russian"],"толпа":["russian"],"толстый":["russian"],"толчок":["russian"],"толщина":["russian"],"только":["russian"],"тонкий":["russian"],"тонна":["russian"],"топить":["russian"],"топор":["russian"],"торговля":["russian"],"тормоз":["russian"],"торчать":["russian"],"тотчас":["russian"],"точка":["russian"],"точно":["russian"],"тощий":["russian"],"трава":["russian"],"традиция":["russian"],"трактор":["russian"],"трамвай":["russian"],"траншея":["russian"],"трасса":["russian"],"тревога":["russian"],"трезвый":["russian"],"тренер":["russian"],"трепет":["russian"],"треск":["russian"],"третий":["russian"],"трещина":["russian"],"трибуна":["russian"],"тридцать":["russian"],"триста":["russian"],"триумф":["russian"],"трогать":["russian"],"тройка":["russian"],"тронуть":["russian"],"тропа":["russian"],"тротуар":["russian"],"трубка":["russian"],"труд":["russian"],"трюк":["russian"],"тряпка":["russian"],"туго":["russian"],"туловище":["russian"],"туман":["russian"],"тумбочка":["russian"],"тундра":["russian"],"тупик":["russian"],"турист":["russian"],"турнир":["russian"],"тусклый":["russian"],"туфля":["russian"],"туча":["russian"],"тысяча":["russian"],"тяга":["russian"],"тяжело":["russian"],"убежать":["russian"],"убогий":["russian"],"уборка":["russian"],"уважение":["russian"],"увезти":["russian"],"уволить":["russian"],"угадать":["russian"],"угол":["russian"],"угощать":["russian"],"угроза":["russian"],"угрюмый":["russian"],"удар":["russian"],"удачный":["russian"],"уделять":["russian"],"удивить":["russian"],"удобный":["russian"],"удочка":["russian"],"уезжать":["russian"],"ужин":["russian"],"узел":["russian"],"узкий":["russian"],"уйти":["russian"],"указание":["russian"],"уклон":["russian"],"украсть":["russian"],"укусить":["russian"],"улетать":["russian"],"улица":["russian"],"улыбка":["russian"],"умело":["russian"],"умение":["russian"],"умный":["russian"],"умолять":["russian"],"унести":["russian"],"унижать":["russian"],"унылый":["russian"],"упаковка":["russian"],"упасть":["russian"],"упорно":["russian"],"упрек":["russian"],"урна":["russian"],"уровень":["russian"],"урожай":["russian"],"уронить":["russian"],"усадьба":["russian"],"усатый":["russian"],"усвоить":["russian"],"усилие":["russian"],"условие":["russian"],"услуга":["russian"],"усмешка":["russian"],"успеть":["russian"],"устав":["russian"],"устоять":["russian"],"утечка":["russian"],"утешать":["russian"],"утро":["russian"],"уцелеть":["russian"],"участие":["russian"],"ученик":["russian"],"учесть":["russian"],"ущелье":["russian"],"ущерб":["russian"],"уютный":["russian"],"фабрика":["russian"],"фаворит":["russian"],"факел":["russian"],"факт":["russian"],"фамилия":["russian"],"фантазия":["russian"],"фасад":["russian"],"февраль":["russian"],"феномен":["russian"],"фермер":["russian"],"фигура":["russian"],"физика":["russian"],"филиал":["russian"],"философ":["russian"],"фильм":["russian"],"финал":["russian"],"флаг":["russian"],"флот":["russian"],"фойе":["russian"],"фокус":["russian"],"фонарь":["russian"],"фонд":["russian"],"фонтан":["russian"],"форма":["russian"],"форум":["russian"],"фото":["russian"],"фрагмент":["russian"],"фраза":["russian"],"фракция":["russian"],"фронт":["russian"],"фрукт":["russian"],"функция":["russian"],"фуражка":["russian"],"футбол":["russian"],"футляр":["russian"],"халат":["russian"],"хаос":["russian"],"характер":["russian"],"хата":["russian"],"хвалить":["russian"],"хватать":["russian"],"хвойный":["russian"],"хвост":["russian"],"химия":["russian"],"хирург":["russian"],"хитрый":["russian"],"хищник":["russian"],"хлеб":["russian"],"хлынуть":["russian"],"хмурый":["russian"],"ходить":["russian"],"хозяин":["russian"],"хоккей":["russian"],"холм":["russian"],"холст":["russian"],"хорошо":["russian"],"хотеть":["russian"],"храбрый":["russian"],"храм":["russian"],"хранить":["russian"],"хребет":["russian"],"хрен":["russian"],"хрипло":["russian"],"хроника":["russian"],"хрупкий":["russian"],"художник":["russian"],"худший":["russian"],"хулиган":["russian"],"хутор":["russian"],"царь":["russian"],"цветок":["russian"],"целевой":["russian"],"целиком":["russian"],"целое":["russian"],"цель":["russian"],"цензура":["russian"],"ценить":["russian"],"центр":["russian"],"цепной":["russian"],"цикл":["russian"],"цилиндр":["russian"],"цирк":["russian"],"цитата":["russian"],"цифра":["russian"],"чайник":["russian"],"часы":["russian"],"чашка":["russian"],"человек":["russian"],"челюсть":["russian"],"чемодан":["russian"],"чемпион":["russian"],"чепуха":["russian"],"червь":["russian"],"чердак":["russian"],"через":["russian"],"чернила":["russian"],"черта":["russian"],"чеснок":["russian"],"честно":["russian"],"четверть":["russian"],"четыре":["russian"],"число":["russian"],"чистый":["russian"],"читатель":["russian"],"чтение":["russian"],"чтобы":["russian"],"чувство":["russian"],"чудак":["russian"],"чудный":["russian"],"чудо":["russian"],"чужой":["russian"],"чулок":["russian"],"чума":["russian"],"чушь":["russian"],"чуять":["russian"],"шагать":["russian"],"шанс":["russian"],"шапка":["russian"],"шарик":["russian"],"шарф":["russian"],"шахматы":["russian"],"шашлык":["russian"],"шедевр":["russian"],"шептать":["russian"],"шерсть":["russian"],"шестой":["russian"],"шинель":["russian"],"ширина":["russian"],"шишка":["russian"],"шкаф":["russian"],"школа":["russian"],"шкура":["russian"],"шланг":["russian"],"шлем":["russian"],"шнур":["russian"],"шоколад":["russian"],"шорох":["russian"],"шоссе":["russian"],"шпион":["russian"],"шприц":["russian"],"штаб":["russian"],"штамм":["russian"],"штаны":["russian"],"штатный":["russian"],"штора":["russian"],"штраф":["russian"],"штурм":["russian"],"штык":["russian"],"шумно":["russian"],"шуршать":["russian"],"шутить":["russian"],"шутка":["russian"],"щедрый":["russian"],"щека":["russian"],"щенок":["russian"],"экзамен":["russian"],"экипаж":["russian"],"экономия":["russian"],"экран":["russian"],"эксперт":["russian"],"элемент":["russian"],"элитный":["russian"],"эмоция":["russian"],"энергия":["russian"],"эпизод":["russian"],"эпоха":["russian"],"эскиз":["russian"],"эстрада":["russian"],"этап":["russian"],"этика":["russian"],"этот":["russian"],"эфир":["russian"],"эффект":["russian"],"эшелон":["russian"],"юбилей":["russian"],"юбка":["russian"],"южный":["russian"],"юмор":["russian"],"юность":["russian"],"юрист":["russian"],"юстиция":["russian"],"яблоко":["russian"],"явление":["russian"],"ягода":["russian"],"ядро":["russian"],"язык":["russian"],"яйцо":["russian"],"якобы":["russian"],"якорь":["russian"],"январь":["russian"],"яркий":["russian"],"ярмарка":["russian"],"ярость":["russian"],"ясный":["russian"],"яхта":["russian"],"ячейка":["russian"],"ящик":["russian"],"ábaco":["spanish"],"abdomen":["spanish"],"abeja":["spanish"],"abierto":["spanish"],"abogado":["spanish"],"abono":["spanish"],"aborto":["spanish"],"abrazo":["spanish"],"abrir":["spanish"],"abuelo":["spanish"],"abuso":["spanish"],"acabar":["spanish"],"academia":["spanish"],"acceso":["spanish"],"acción":["spanish"],"aceite":["spanish"],"acelga":["spanish"],"acento":["spanish"],"aceptar":["spanish"],"ácido":["spanish"],"aclarar":["spanish"],"acné":["spanish"],"acoger":["spanish"],"acoso":["spanish"],"activo":["spanish"],"acto":["spanish"],"actriz":["spanish"],"actuar":["spanish"],"acudir":["spanish"],"acuerdo":["spanish"],"acusar":["spanish"],"adicto":["spanish"],"admitir":["spanish"],"adoptar":["spanish"],"adorno":["spanish"],"aduana":["spanish"],"adulto":["spanish"],"aéreo":["spanish"],"afectar":["spanish"],"afición":["spanish"],"afinar":["spanish"],"afirmar":["spanish"],"ágil":["spanish"],"agitar":["spanish"],"agonía":["spanish"],"agosto":["spanish"],"agotar":["spanish"],"agregar":["spanish"],"agrio":["spanish"],"agua":["spanish"],"agudo":["spanish"],"águila":["spanish"],"aguja":["spanish"],"ahogo":["spanish"],"ahorro":["spanish"],"aire":["spanish"],"aislar":["spanish"],"ajedrez":["spanish"],"ajeno":["spanish"],"ajuste":["spanish"],"alacrán":["spanish"],"alambre":["spanish"],"alarma":["spanish"],"alba":["spanish"],"álbum":["spanish"],"alcalde":["spanish"],"aldea":["spanish"],"alegre":["spanish"],"alejar":["spanish"],"alerta":["spanish"],"aleta":["spanish"],"alfiler":["spanish"],"alga":["spanish"],"algodón":["spanish"],"aliado":["spanish"],"aliento":["spanish"],"alivio":["spanish"],"alma":["spanish"],"almeja":["spanish"],"almíbar":["spanish"],"altar":["spanish"],"alteza":["spanish"],"altivo":["spanish"],"alto":["spanish"],"altura":["spanish"],"alumno":["spanish"],"alzar":["spanish"],"amable":["spanish"],"amante":["spanish"],"amapola":["spanish"],"amargo":["spanish"],"amasar":["spanish"],"ámbar":["spanish"],"ámbito":["spanish"],"ameno":["spanish"],"amigo":["spanish","turkish"],"amistad":["spanish"],"amor":["spanish"],"amparo":["spanish"],"amplio":["spanish"],"ancho":["spanish"],"anciano":["spanish"],"ancla":["spanish"],"andar":["spanish"],"andén":["spanish"],"anemia":["spanish"],"ángulo":["spanish"],"anillo":["spanish"],"ánimo":["spanish"],"anís":["spanish"],"anotar":["spanish"],"antena":["spanish"],"antiguo":["spanish"],"antojo":["spanish"],"anual":["spanish"],"anular":["spanish"],"anuncio":["spanish"],"añadir":["spanish"],"añejo":["spanish"],"año":["spanish"],"apagar":["spanish"],"aparato":["spanish"],"apetito":["spanish"],"apio":["spanish"],"aplicar":["spanish"],"apodo":["spanish"],"aporte":["spanish"],"apoyo":["spanish"],"aprender":["spanish"],"aprobar":["spanish"],"apuesta":["spanish"],"apuro":["spanish"],"arado":["spanish"],"araña":["spanish"],"arar":["spanish"],"árbitro":["spanish"],"árbol":["spanish"],"arbusto":["spanish"],"archivo":["spanish"],"arco":["spanish"],"arder":["spanish"],"ardilla":["spanish"],"arduo":["spanish"],"área":["spanish"],"árido":["spanish"],"aries":["spanish"],"armonía":["spanish"],"arnés":["spanish"],"aroma":["spanish","turkish"],"arpa":["spanish"],"arpón":["spanish"],"arreglo":["spanish"],"arroz":["spanish"],"arruga":["spanish"],"arte":["spanish"],"artista":["spanish"],"asa":["spanish"],"asado":["spanish"],"asalto":["spanish"],"ascenso":["spanish"],"asegurar":["spanish"],"aseo":["spanish"],"asesor":["spanish"],"asiento":["spanish"],"asilo":["spanish"],"asistir":["spanish"],"asno":["spanish"],"asombro":["spanish"],"áspero":["spanish"],"astilla":["spanish"],"astro":["spanish"],"astuto":["spanish"],"asumir":["spanish"],"asunto":["spanish"],"atajo":["spanish"],"ataque":["spanish"],"atar":["spanish"],"atento":["spanish"],"ateo":["spanish"],"ático":["spanish"],"atleta":["spanish"],"átomo":["spanish"],"atraer":["spanish"],"atroz":["spanish"],"atún":["spanish"],"audaz":["spanish"],"audio":["spanish"],"auge":["spanish"],"aula":["spanish"],"aumento":["spanish"],"ausente":["spanish"],"autor":["spanish"],"aval":["spanish"],"avance":["spanish"],"avaro":["spanish"],"ave":["spanish"],"avellana":["spanish"],"avena":["spanish"],"avestruz":["spanish"],"avión":["spanish"],"aviso":["spanish"],"ayer":["spanish"],"ayuda":["spanish"],"ayuno":["spanish"],"azafrán":["spanish"],"azar":["spanish"],"azote":["spanish"],"azúcar":["spanish"],"azufre":["spanish"],"azul":["spanish"],"baba":["spanish"],"babor":["spanish"],"bache":["spanish"],"bahía":["spanish"],"baile":["spanish"],"bajar":["spanish"],"balanza":["spanish"],"balcón":["spanish"],"balde":["spanish"],"bambú":["spanish"],"banco":["spanish"],"banda":["spanish"],"baño":["spanish"],"barba":["spanish"],"barco":["spanish"],"barniz":["spanish"],"barro":["spanish"],"báscula":["spanish"],"bastón":["spanish"],"basura":["spanish"],"batalla":["spanish"],"batería":["spanish"],"batir":["spanish"],"batuta":["spanish"],"baúl":["spanish"],"bazar":["spanish"],"bebé":["spanish"],"bebida":["spanish"],"bello":["spanish"],"besar":["spanish"],"beso":["spanish"],"bestia":["spanish"],"bicho":["spanish"],"bien":["spanish"],"bingo":["spanish"],"blanco":["spanish"],"bloque":["spanish"],"blusa":["spanish"],"boa":["spanish"],"bobina":["spanish"],"bobo":["spanish"],"boca":["spanish"],"bocina":["spanish"],"boda":["spanish"],"bodega":["spanish"],"boina":["spanish"],"bola":["spanish"],"bolero":["spanish","turkish"],"bolsa":["spanish"],"bomba":["spanish"],"bondad":["spanish"],"bonito":["spanish"],"bono":["spanish"],"bonsái":["spanish"],"borde":["spanish"],"borrar":["spanish"],"bosque":["spanish"],"bote":["spanish"],"botín":["spanish"],"bóveda":["spanish"],"bozal":["spanish"],"bravo":["spanish"],"brazo":["spanish"],"brecha":["spanish"],"breve":["spanish"],"brillo":["spanish"],"brinco":["spanish"],"brisa":["spanish"],"broca":["spanish"],"broma":["spanish"],"bronce":["spanish"],"brote":["spanish"],"bruja":["spanish"],"brusco":["spanish"],"bruto":["spanish"],"buceo":["spanish"],"bucle":["spanish"],"bueno":["spanish"],"buey":["spanish"],"bufanda":["spanish"],"bufón":["spanish"],"búho":["spanish"],"buitre":["spanish"],"bulto":["spanish"],"burbuja":["spanish"],"burla":["spanish"],"burro":["spanish"],"buscar":["spanish"],"butaca":["spanish"],"buzón":["spanish"],"caballo":["spanish"],"cabeza":["spanish"],"cabina":["spanish"],"cabra":["spanish"],"cacao":["spanish"],"cadáver":["spanish"],"cadena":["spanish"],"caer":["spanish"],"café":["spanish"],"caída":["spanish"],"caimán":["spanish"],"caja":["spanish"],"cajón":["spanish"],"cal":["spanish"],"calamar":["spanish"],"calcio":["spanish"],"caldo":["spanish"],"calidad":["spanish"],"calle":["spanish"],"calma":["spanish"],"calor":["spanish"],"calvo":["spanish"],"cama":["spanish"],"cambio":["spanish"],"camello":["spanish"],"camino":["spanish"],"campo":["spanish"],"cáncer":["spanish"],"candil":["spanish"],"canela":["spanish"],"canguro":["spanish"],"canica":["spanish"],"canto":["spanish"],"caña":["spanish"],"cañón":["spanish"],"caoba":["spanish"],"caos":["spanish"],"capaz":["spanish"],"capitán":["spanish"],"capote":["spanish"],"captar":["spanish"],"capucha":["spanish"],"cara":["spanish"],"carbón":["spanish"],"cárcel":["spanish"],"careta":["spanish"],"carga":["spanish"],"cariño":["spanish"],"carne":["spanish"],"carpeta":["spanish"],"carro":["spanish"],"carta":["spanish"],"casa":["spanish"],"casco":["spanish"],"casero":["spanish"],"caspa":["spanish"],"castor":["spanish"],"catorce":["spanish"],"catre":["spanish"],"caudal":["spanish"],"causa":["spanish"],"cazo":["spanish"],"cebolla":["spanish"],"ceder":["spanish"],"cedro":["spanish"],"celda":["spanish"],"célebre":["spanish"],"celoso":["spanish"],"célula":["spanish"],"cemento":["spanish"],"ceniza":["spanish"],"centro":["spanish"],"cerca":["spanish"],"cerdo":["spanish"],"cereza":["spanish"],"cero":["spanish"],"cerrar":["spanish"],"certeza":["spanish"],"césped":["spanish"],"cetro":["spanish"],"chacal":["spanish"],"chaleco":["spanish"],"champú":["spanish"],"chancla":["spanish"],"chapa":["spanish"],"charla":["spanish"],"chico":["spanish"],"chiste":["spanish"],"chivo":["spanish"],"choque":["spanish"],"choza":["spanish"],"chuleta":["spanish"],"chupar":["spanish"],"ciclón":["spanish"],"ciego":["spanish"],"cielo":["spanish"],"cien":["spanish"],"cierto":["spanish"],"cifra":["spanish"],"cigarro":["spanish"],"cima":["spanish"],"cinco":["spanish"],"cine":["spanish"],"cinta":["spanish"],"ciprés":["spanish"],"circo":["spanish"],"ciruela":["spanish"],"cisne":["spanish"],"cita":["spanish"],"ciudad":["spanish"],"clamor":["spanish"],"clan":["spanish"],"claro":["spanish"],"clase":["spanish"],"clave":["spanish"],"cliente":["spanish"],"clima":["spanish"],"clínica":["spanish"],"cobre":["spanish"],"cocción":["spanish"],"cochino":["spanish"],"cocina":["spanish"],"coco":["spanish"],"código":["spanish"],"codo":["spanish"],"cofre":["spanish"],"coger":["spanish"],"cohete":["spanish"],"cojín":["spanish"],"cojo":["spanish"],"cola":["spanish"],"colcha":["spanish"],"colegio":["spanish"],"colgar":["spanish"],"colina":["spanish"],"collar":["spanish"],"colmo":["spanish"],"columna":["spanish"],"combate":["spanish"],"comer":["spanish"],"comida":["spanish"],"cómodo":["spanish"],"compra":["spanish"],"conde":["spanish"],"conejo":["spanish"],"conga":["spanish"],"conocer":["spanish"],"consejo":["spanish"],"contar":["spanish"],"copa":["spanish"],"copia":["spanish"],"corazón":["spanish"],"corbata":["spanish"],"corcho":["spanish"],"cordón":["spanish"],"corona":["spanish"],"correr":["spanish"],"coser":["spanish"],"cosmos":["spanish"],"costa":["spanish"],"cráneo":["spanish"],"cráter":["spanish"],"crear":["spanish"],"crecer":["spanish"],"creído":["spanish"],"crema":["spanish"],"cría":["spanish"],"crimen":["spanish"],"cripta":["spanish"],"crisis":["spanish"],"cromo":["spanish"],"crónica":["spanish"],"croqueta":["spanish"],"crudo":["spanish"],"cruz":["spanish"],"cuadro":["spanish"],"cuarto":["spanish"],"cuatro":["spanish"],"cubo":["spanish"],"cubrir":["spanish"],"cuchara":["spanish"],"cuello":["spanish"],"cuento":["spanish"],"cuerda":["spanish"],"cuesta":["spanish"],"cueva":["spanish"],"cuidar":["spanish"],"culebra":["spanish"],"culpa":["spanish"],"culto":["spanish"],"cumbre":["spanish"],"cumplir":["spanish"],"cuna":["spanish"],"cuneta":["spanish"],"cuota":["spanish"],"cupón":["spanish"],"cúpula":["spanish"],"curar":["spanish"],"curioso":["spanish"],"curso":["spanish"],"curva":["spanish"],"cutis":["spanish"],"dama":["spanish"],"danza":["spanish"],"dar":["spanish"],"dardo":["spanish"],"dátil":["spanish"],"deber":["spanish"],"débil":["spanish"],"década":["spanish"],"decir":["spanish"],"dedo":["spanish"],"defensa":["spanish"],"definir":["spanish"],"dejar":["spanish"],"delfín":["spanish"],"delgado":["spanish"],"delito":["spanish"],"demora":["spanish"],"denso":["spanish"],"dental":["spanish"],"deporte":["spanish"],"derecho":["spanish"],"derrota":["spanish"],"desayuno":["spanish"],"deseo":["spanish"],"desfile":["spanish"],"desnudo":["spanish"],"destino":["spanish"],"desvío":["spanish"],"detalle":["spanish"],"detener":["spanish"],"deuda":["spanish"],"día":["spanish"],"diablo":["spanish"],"diadema":["spanish"],"diamante":["spanish"],"diana":["spanish"],"diario":["spanish"],"dibujo":["spanish"],"dictar":["spanish"],"diente":["spanish"],"dieta":["spanish"],"diez":["spanish"],"difícil":["spanish"],"digno":["spanish"],"dilema":["spanish"],"diluir":["spanish"],"dinero":["spanish"],"directo":["spanish"],"dirigir":["spanish"],"disco":["spanish"],"diseño":["spanish"],"disfraz":["spanish"],"diva":["spanish"],"divino":["spanish"],"doble":["spanish"],"doce":["spanish"],"dolor":["spanish"],"domingo":["spanish"],"don":["spanish"],"donar":["spanish"],"dorado":["spanish"],"dormir":["spanish"],"dorso":["spanish"],"dos":["spanish"],"dosis":["spanish"],"dragón":["spanish"],"droga":["spanish"],"ducha":["spanish"],"duda":["spanish"],"duelo":["spanish"],"dueño":["spanish"],"dulce":["spanish"],"dúo":["spanish"],"duque":["spanish"],"durar":["spanish"],"dureza":["spanish"],"duro":["spanish"],"ébano":["spanish"],"ebrio":["spanish"],"echar":["spanish"],"eco":["spanish"],"ecuador":["spanish"],"edad":["spanish"],"edición":["spanish"],"edificio":["spanish"],"editor":["spanish"],"educar":["spanish"],"efecto":["spanish"],"eficaz":["spanish"],"eje":["spanish"],"ejemplo":["spanish"],"elefante":["spanish"],"elegir":["spanish"],"elemento":["spanish"],"elevar":["spanish"],"elipse":["spanish"],"élite":["spanish"],"elixir":["spanish"],"elogio":["spanish"],"eludir":["spanish"],"embudo":["spanish"],"emitir":["spanish"],"emoción":["spanish"],"empate":["spanish"],"empeño":["spanish"],"empleo":["spanish"],"empresa":["spanish"],"enano":["spanish"],"encargo":["spanish"],"enchufe":["spanish"],"encía":["spanish"],"enemigo":["spanish"],"enero":["spanish"],"enfado":["spanish"],"enfermo":["spanish"],"engaño":["spanish"],"enigma":["spanish"],"enlace":["spanish"],"enorme":["spanish"],"enredo":["spanish"],"ensayo":["spanish"],"enseñar":["spanish"],"entero":["spanish"],"entrar":["spanish"],"envase":["spanish"],"envío":["spanish"],"época":["spanish"],"equipo":["spanish"],"erizo":["spanish"],"escala":["spanish"],"escena":["spanish"],"escolar":["spanish"],"escribir":["spanish"],"escudo":["spanish"],"esencia":["spanish"],"esfera":["spanish"],"esfuerzo":["spanish"],"espada":["spanish"],"espejo":["spanish"],"espía":["spanish"],"esposa":["spanish"],"espuma":["spanish"],"esquí":["spanish"],"estar":["spanish"],"este":["spanish"],"estilo":["spanish"],"estufa":["spanish"],"etapa":["spanish"],"eterno":["spanish"],"ética":["spanish"],"etnia":["spanish"],"evadir":["spanish"],"evaluar":["spanish"],"evento":["spanish"],"evitar":["spanish"],"exacto":["spanish"],"examen":["spanish"],"exceso":["spanish"],"excusa":["spanish"],"exento":["spanish"],"exigir":["spanish"],"exilio":["spanish"],"existir":["spanish"],"éxito":["spanish"],"experto":["spanish"],"explicar":["spanish"],"exponer":["spanish"],"extremo":["spanish"],"fábrica":["spanish"],"fábula":["spanish"],"fachada":["spanish"],"fácil":["spanish"],"factor":["spanish"],"faena":["spanish"],"faja":["spanish"],"falda":["spanish"],"fallo":["spanish"],"falso":["spanish"],"faltar":["spanish"],"fama":["spanish"],"familia":["spanish"],"famoso":["spanish"],"faraón":["spanish"],"farmacia":["spanish"],"farol":["spanish"],"farsa":["spanish"],"fase":["spanish"],"fatiga":["spanish"],"fauna":["spanish","turkish"],"favor":["spanish"],"fax":["spanish"],"febrero":["spanish"],"fecha":["spanish"],"feliz":["spanish"],"feo":["spanish"],"feria":["spanish"],"feroz":["spanish"],"fértil":["spanish"],"fervor":["spanish"],"festín":["spanish"],"fiable":["spanish"],"fianza":["spanish"],"fiar":["spanish"],"fibra":["spanish"],"ficción":["spanish"],"ficha":["spanish"],"fideo":["spanish"],"fiebre":["spanish"],"fiel":["spanish"],"fiera":["spanish"],"fiesta":["spanish"],"figura":["spanish"],"fijar":["spanish"],"fijo":["spanish"],"fila":["spanish"],"filete":["spanish"],"filial":["spanish"],"filtro":["spanish"],"fin":["spanish"],"finca":["spanish"],"fingir":["spanish"],"finito":["spanish"],"firma":["spanish"],"flaco":["spanish"],"flauta":["spanish"],"flecha":["spanish"],"flor":["spanish"],"flota":["spanish"],"fluir":["spanish"],"flujo":["spanish"],"flúor":["spanish"],"fobia":["spanish"],"foca":["spanish"],"fogata":["spanish"],"fogón":["spanish"],"folio":["spanish"],"folleto":["spanish"],"fondo":["spanish"],"forma":["spanish"],"forro":["spanish"],"fortuna":["spanish"],"forzar":["spanish"],"fosa":["spanish"],"foto":["spanish"],"fracaso":["spanish"],"frágil":["spanish"],"franja":["spanish"],"frase":["spanish"],"fraude":["spanish"],"freír":["spanish"],"freno":["spanish"],"fresa":["spanish"],"frío":["spanish"],"frito":["spanish"],"fruta":["spanish"],"fuego":["spanish"],"fuente":["spanish"],"fuerza":["spanish"],"fuga":["spanish"],"fumar":["spanish"],"función":["spanish"],"funda":["spanish"],"furgón":["spanish"],"furia":["spanish"],"fusil":["spanish"],"fútbol":["spanish"],"futuro":["spanish"],"gacela":["spanish"],"gafas":["spanish"],"gaita":["spanish"],"gajo":["spanish"],"gala":["spanish"],"galería":["spanish"],"gallo":["spanish"],"gamba":["spanish"],"ganar":["spanish"],"gancho":["spanish"],"ganga":["spanish"],"ganso":["spanish"],"garaje":["spanish"],"garza":["spanish"],"gasolina":["spanish"],"gastar":["spanish"],"gato":["spanish"],"gavilán":["spanish"],"gemelo":["spanish"],"gemir":["spanish"],"gen":["spanish"],"género":["spanish"],"genio":["spanish"],"gente":["spanish"],"geranio":["spanish"],"gerente":["spanish"],"germen":["spanish"],"gesto":["spanish"],"gigante":["spanish"],"gimnasio":["spanish"],"girar":["spanish"],"giro":["spanish"],"glaciar":["spanish"],"globo":["spanish"],"gloria":["spanish"],"gol":["spanish"],"golfo":["spanish"],"goloso":["spanish"],"golpe":["spanish"],"goma":["spanish"],"gordo":["spanish"],"gorila":["spanish"],"gorra":["spanish"],"gota":["spanish"],"goteo":["spanish"],"gozar":["spanish"],"grada":["spanish"],"gráfico":["spanish"],"grano":["spanish"],"grasa":["spanish"],"gratis":["spanish"],"grave":["spanish"],"grieta":["spanish"],"grillo":["spanish"],"gripe":["spanish"],"gris":["spanish"],"grito":["spanish"],"grosor":["spanish"],"grúa":["spanish"],"grueso":["spanish"],"grumo":["spanish"],"grupo":["spanish"],"guante":["spanish"],"guapo":["spanish"],"guardia":["spanish"],"guerra":["spanish"],"guía":["spanish"],"guiño":["spanish"],"guion":["spanish"],"guiso":["spanish"],"guitarra":["spanish"],"gusano":["spanish"],"gustar":["spanish"],"haber":["spanish","turkish"],"hábil":["spanish"],"hablar":["spanish"],"hacer":["spanish"],"hacha":["spanish"],"hada":["spanish"],"hallar":["spanish"],"hamaca":["spanish"],"harina":["spanish"],"haz":["spanish"],"hazaña":["spanish"],"hebilla":["spanish"],"hebra":["spanish"],"hecho":["spanish"],"helado":["spanish"],"helio":["spanish"],"hembra":["spanish"],"herir":["spanish"],"hermano":["spanish"],"héroe":["spanish"],"hervir":["spanish"],"hielo":["spanish"],"hierro":["spanish"],"hígado":["spanish"],"higiene":["spanish"],"hijo":["spanish"],"himno":["spanish"],"historia":["spanish"],"hocico":["spanish"],"hogar":["spanish"],"hoguera":["spanish"],"hoja":["spanish"],"hombre":["spanish"],"hongo":["spanish"],"honor":["spanish"],"honra":["spanish"],"hora":["spanish"],"hormiga":["spanish"],"horno":["spanish"],"hostil":["spanish"],"hoyo":["spanish"],"hueco":["spanish"],"huelga":["spanish"],"huerta":["spanish"],"hueso":["spanish"],"huevo":["spanish"],"huida":["spanish"],"huir":["spanish"],"humano":["spanish"],"húmedo":["spanish"],"humilde":["spanish"],"humo":["spanish"],"hundir":["spanish"],"huracán":["spanish"],"hurto":["spanish"],"icono":["spanish"],"ideal":["spanish"],"idioma":["spanish"],"ídolo":["spanish"],"iglesia":["spanish"],"iglú":["spanish"],"igual":["spanish"],"ilegal":["spanish"],"ilusión":["spanish"],"imagen":["spanish"],"imán":["spanish"],"imitar":["spanish"],"impar":["spanish"],"imperio":["spanish"],"imponer":["spanish"],"impulso":["spanish"],"incapaz":["spanish"],"índice":["spanish"],"inerte":["spanish"],"infiel":["spanish"],"informe":["spanish"],"ingenio":["spanish"],"inicio":["spanish"],"inmenso":["spanish"],"inmune":["spanish"],"innato":["spanish"],"insecto":["spanish"],"instante":["spanish"],"interés":["spanish"],"íntimo":["spanish"],"intuir":["spanish"],"inútil":["spanish"],"invierno":["spanish"],"ira":["spanish"],"iris":["spanish"],"ironía":["spanish"],"isla":["spanish"],"islote":["spanish"],"jabalí":["spanish"],"jabón":["spanish"],"jamón":["spanish"],"jarabe":["spanish"],"jardín":["spanish"],"jarra":["spanish"],"jaula":["spanish"],"jazmín":["spanish"],"jefe":["spanish"],"jeringa":["spanish"],"jinete":["spanish"],"jornada":["spanish"],"joroba":["spanish"],"joven":["spanish"],"joya":["spanish"],"juerga":["spanish"],"jueves":["spanish"],"juez":["spanish"],"jugador":["spanish"],"jugo":["spanish"],"juguete":["spanish"],"juicio":["spanish"],"junco":["spanish"],"jungla":["spanish"],"junio":["spanish"],"juntar":["spanish"],"júpiter":["spanish"],"jurar":["spanish"],"justo":["spanish"],"juvenil":["spanish"],"juzgar":["spanish"],"kilo":["spanish"],"koala":["spanish"],"labio":["spanish"],"lacio":["spanish"],"lacra":["spanish"],"lado":["spanish"],"ladrón":["spanish"],"lagarto":["spanish"],"lágrima":["spanish"],"laguna":["spanish"],"laico":["spanish"],"lamer":["spanish"],"lámina":["spanish"],"lámpara":["spanish"],"lana":["spanish"],"lancha":["spanish"],"langosta":["spanish"],"lanza":["spanish"],"lápiz":["spanish"],"largo":["spanish"],"larva":["spanish"],"lástima":["spanish"],"lata":["spanish"],"látex":["spanish"],"latir":["spanish"],"laurel":["spanish"],"lavar":["spanish"],"lazo":["spanish"],"leal":["spanish"],"lección":["spanish"],"leche":["spanish"],"lector":["spanish"],"leer":["spanish"],"legión":["spanish"],"legumbre":["spanish"],"lejano":["spanish"],"lengua":["spanish"],"lento":["spanish"],"leña":["spanish"],"león":["spanish"],"leopardo":["spanish"],"lesión":["spanish"],"letal":["spanish"],"letra":["spanish"],"leve":["spanish"],"leyenda":["spanish"],"libertad":["spanish"],"libro":["spanish"],"licor":["spanish"],"líder":["spanish"],"lidiar":["spanish"],"lienzo":["spanish"],"liga":["spanish"],"ligero":["spanish"],"lima":["spanish"],"límite":["spanish"],"limón":["spanish"],"limpio":["spanish"],"lince":["spanish"],"lindo":["spanish"],"línea":["spanish"],"lingote":["spanish"],"lino":["spanish"],"linterna":["spanish"],"líquido":["spanish"],"liso":["spanish"],"lista":["spanish"],"litera":["spanish"],"litio":["spanish"],"litro":["spanish"],"llaga":["spanish"],"llama":["spanish"],"llanto":["spanish"],"llave":["spanish"],"llegar":["spanish"],"llenar":["spanish"],"llevar":["spanish"],"llorar":["spanish"],"llover":["spanish"],"lluvia":["spanish"],"lobo":["spanish"],"loción":["spanish"],"loco":["spanish"],"locura":["spanish"],"lógica":["spanish"],"logro":["spanish"],"lombriz":["spanish"],"lomo":["spanish"],"lonja":["spanish"],"lote":["spanish"],"lucha":["spanish"],"lucir":["spanish"],"lugar":["spanish"],"lujo":["spanish"],"luna":["spanish"],"lunes":["spanish"],"lupa":["spanish"],"lustro":["spanish"],"luto":["spanish"],"luz":["spanish"],"maceta":["spanish"],"macho":["spanish"],"madera":["spanish"],"madre":["spanish"],"maduro":["spanish"],"maestro":["spanish"],"mafia":["spanish"],"magia":["spanish"],"mago":["spanish"],"maíz":["spanish"],"maldad":["spanish"],"maleta":["spanish"],"malla":["spanish"],"malo":["spanish"],"mamá":["spanish"],"mambo":["spanish"],"mamut":["spanish"],"manco":["spanish"],"mando":["spanish"],"manejar":["spanish"],"manga":["spanish"],"maniquí":["spanish"],"manjar":["spanish"],"mano":["spanish"],"manso":["spanish"],"manta":["spanish"],"mañana":["spanish"],"mapa":["spanish"],"máquina":["spanish"],"mar":["spanish"],"marco":["spanish"],"marea":["spanish"],"marfil":["spanish"],"margen":["spanish"],"marido":["spanish"],"mármol":["spanish"],"marrón":["spanish"],"martes":["spanish"],"marzo":["spanish"],"masa":["spanish"],"máscara":["spanish"],"masivo":["spanish"],"matar":["spanish"],"materia":["spanish"],"matiz":["spanish"],"matriz":["spanish"],"máximo":["spanish"],"mayor":["spanish"],"mazorca":["spanish"],"mecha":["spanish"],"medalla":["spanish"],"medio":["spanish"],"médula":["spanish"],"mejilla":["spanish"],"mejor":["spanish"],"melena":["spanish"],"melón":["spanish"],"memoria":["spanish"],"menor":["spanish"],"mensaje":["spanish"],"mente":["spanish"],"menú":["spanish"],"mercado":["spanish"],"merengue":["spanish"],"mérito":["spanish"],"mes":["spanish"],"mesón":["spanish"],"meta":["spanish"],"meter":["spanish"],"método":["spanish"],"metro":["spanish"],"mezcla":["spanish"],"miedo":["spanish"],"miel":["spanish"],"miembro":["spanish"],"miga":["spanish"],"mil":["spanish"],"milagro":["spanish"],"militar":["spanish"],"millón":["spanish"],"mimo":["spanish"],"mina":["spanish"],"minero":["spanish"],"mínimo":["spanish"],"minuto":["spanish"],"miope":["spanish"],"mirar":["spanish"],"misa":["spanish"],"miseria":["spanish"],"misil":["spanish"],"mismo":["spanish"],"mitad":["spanish"],"mito":["spanish"],"mochila":["spanish"],"moción":["spanish"],"moda":["spanish"],"modelo":["spanish"],"moho":["spanish"],"mojar":["spanish"],"molde":["spanish"],"moler":["spanish"],"molino":["spanish"],"momento":["spanish"],"momia":["spanish"],"monarca":["spanish"],"moneda":["spanish"],"monja":["spanish"],"monto":["spanish"],"moño":["spanish"],"morada":["spanish"],"morder":["spanish"],"moreno":["spanish"],"morir":["spanish"],"morro":["spanish"],"morsa":["spanish"],"mortal":["spanish"],"mosca":["spanish"],"mostrar":["spanish"],"motivo":["spanish"],"mover":["spanish"],"móvil":["spanish"],"mozo":["spanish"],"mucho":["spanish"],"mudar":["spanish"],"mueble":["spanish"],"muela":["spanish"],"muerte":["spanish"],"muestra":["spanish"],"mugre":["spanish"],"mujer":["spanish"],"mula":["spanish"],"muleta":["spanish"],"multa":["spanish"],"mundo":["spanish"],"muñeca":["spanish"],"mural":["spanish"],"muro":["spanish"],"músculo":["spanish"],"museo":["spanish"],"musgo":["spanish"],"música":["spanish"],"muslo":["spanish"],"nácar":["spanish"],"nación":["spanish"],"nadar":["spanish"],"naipe":["spanish"],"naranja":["spanish"],"nariz":["spanish"],"narrar":["spanish"],"nasal":["spanish"],"natal":["spanish"],"nativo":["spanish"],"natural":["spanish"],"náusea":["spanish"],"naval":["spanish"],"nave":["spanish"],"navidad":["spanish"],"necio":["spanish"],"néctar":["spanish"],"negar":["spanish"],"negocio":["spanish"],"negro":["spanish"],"neón":["spanish"],"nervio":["spanish"],"neto":["spanish"],"neutro":["spanish"],"nevar":["spanish"],"nevera":["spanish"],"nicho":["spanish"],"nido":["spanish"],"niebla":["spanish"],"nieto":["spanish"],"niñez":["spanish"],"niño":["spanish"],"nítido":["spanish"],"nivel":["spanish"],"nobleza":["spanish"],"noche":["spanish"],"nómina":["spanish"],"noria":["spanish"],"norma":["spanish"],"norte":["spanish"],"nota":["spanish"],"noticia":["spanish"],"novato":["spanish"],"novela":["spanish"],"novio":["spanish"],"nube":["spanish"],"nuca":["spanish"],"núcleo":["spanish"],"nudillo":["spanish"],"nudo":["spanish"],"nuera":["spanish"],"nueve":["spanish"],"nuez":["spanish"],"nulo":["spanish"],"número":["spanish"],"nutria":["spanish"],"oasis":["spanish"],"obeso":["spanish"],"obispo":["spanish"],"objeto":["spanish"],"obra":["spanish"],"obrero":["spanish"],"observar":["spanish"],"obtener":["spanish"],"obvio":["spanish"],"oca":["spanish"],"ocaso":["spanish"],"océano":["spanish"],"ochenta":["spanish"],"ocho":["spanish"],"ocio":["spanish"],"ocre":["spanish"],"octavo":["spanish"],"octubre":["spanish"],"oculto":["spanish"],"ocupar":["spanish"],"ocurrir":["spanish"],"odiar":["spanish"],"odio":["spanish"],"odisea":["spanish"],"oeste":["spanish"],"ofensa":["spanish"],"oferta":["spanish"],"oficio":["spanish"],"ofrecer":["spanish"],"ogro":["spanish"],"oído":["spanish"],"oír":["spanish"],"ojo":["spanish"],"ola":["spanish"],"oleada":["spanish"],"olfato":["spanish"],"olivo":["spanish"],"olla":["spanish"],"olmo":["spanish"],"olor":["spanish"],"olvido":["spanish"],"ombligo":["spanish"],"onda":["spanish"],"onza":["spanish"],"opaco":["spanish"],"opción":["spanish"],"ópera":["spanish"],"opinar":["spanish"],"oponer":["spanish"],"optar":["spanish"],"óptica":["spanish"],"opuesto":["spanish"],"oración":["spanish"],"orador":["spanish"],"oral":["spanish","turkish"],"órbita":["spanish"],"orca":["spanish"],"orden":["spanish"],"oreja":["spanish"],"órgano":["spanish"],"orgía":["spanish"],"orgullo":["spanish"],"oriente":["spanish"],"origen":["spanish"],"orilla":["spanish"],"oro":["spanish"],"orquesta":["spanish"],"oruga":["spanish"],"osadía":["spanish"],"oscuro":["spanish"],"osezno":["spanish"],"oso":["spanish"],"ostra":["spanish"],"otoño":["spanish"],"otro":["spanish"],"oveja":["spanish"],"óvulo":["spanish"],"óxido":["spanish"],"oxígeno":["spanish"],"oyente":["spanish"],"ozono":["spanish"],"pacto":["spanish"],"padre":["spanish"],"paella":["spanish"],"página":["spanish"],"pago":["spanish"],"país":["spanish"],"pájaro":["spanish"],"palabra":["spanish"],"palco":["spanish"],"paleta":["spanish"],"pálido":["spanish"],"palma":["spanish"],"paloma":["spanish"],"palpar":["spanish"],"pan":["spanish"],"panal":["spanish"],"pánico":["spanish"],"pantera":["spanish"],"pañuelo":["spanish"],"papá":["spanish"],"papel":["spanish"],"papilla":["spanish"],"paquete":["spanish"],"parar":["spanish"],"parcela":["spanish"],"pared":["spanish"],"parir":["spanish"],"paro":["spanish"],"párpado":["spanish"],"parque":["spanish"],"párrafo":["spanish"],"parte":["spanish"],"pasar":["spanish"],"paseo":["spanish"],"pasión":["spanish"],"paso":["spanish"],"pasta":["spanish"],"pata":["spanish"],"patio":["spanish"],"patria":["spanish"],"pausa":["spanish"],"pauta":["spanish"],"pavo":["spanish"],"payaso":["spanish"],"peatón":["spanish"],"pecado":["spanish"],"pecera":["spanish"],"pecho":["spanish"],"pedal":["spanish","turkish"],"pedir":["spanish"],"pegar":["spanish"],"peine":["spanish"],"pelar":["spanish"],"peldaño":["spanish"],"pelea":["spanish"],"peligro":["spanish"],"pellejo":["spanish"],"pelo":["spanish"],"peluca":["spanish"],"pena":["spanish","turkish"],"pensar":["spanish"],"peñón":["spanish"],"peón":["spanish"],"peor":["spanish"],"pepino":["spanish"],"pequeño":["spanish"],"pera":["spanish"],"percha":["spanish"],"perder":["spanish"],"pereza":["spanish"],"perfil":["spanish"],"perico":["spanish"],"perla":["spanish"],"permiso":["spanish"],"perro":["spanish"],"persona":["spanish"],"pesa":["spanish"],"pesca":["spanish"],"pésimo":["spanish"],"pestaña":["spanish"],"pétalo":["spanish"],"petróleo":["spanish"],"pez":["spanish"],"pezuña":["spanish"],"picar":["spanish"],"pichón":["spanish"],"pie":["spanish"],"piedra":["spanish"],"pierna":["spanish"],"pieza":["spanish"],"pijama":["spanish"],"pilar":["spanish"],"piloto":["spanish"],"pimienta":["spanish"],"pino":["spanish"],"pintor":["spanish"],"pinza":["spanish"],"piña":["spanish"],"piojo":["spanish"],"pipa":["spanish"],"pirata":["spanish"],"pisar":["spanish"],"piscina":["spanish"],"piso":["spanish"],"pista":["spanish"],"pitón":["spanish"],"pizca":["spanish"],"placa":["spanish"],"plan":["spanish"],"plata":["spanish"],"playa":["spanish"],"plaza":["spanish"],"pleito":["spanish"],"pleno":["spanish"],"plomo":["spanish"],"pluma":["spanish"],"plural":["spanish"],"pobre":["spanish"],"poco":["spanish"],"poder":["spanish"],"podio":["spanish"],"poema":["spanish"],"poesía":["spanish"],"poeta":["spanish"],"polen":["spanish","turkish"],"policía":["spanish"],"pollo":["spanish"],"polvo":["spanish"],"pomada":["spanish"],"pomelo":["spanish"],"pomo":["spanish"],"pompa":["spanish","turkish"],"poner":["spanish"],"porción":["spanish"],"portal":["spanish"],"posada":["spanish"],"poseer":["spanish"],"posible":["spanish"],"poste":["spanish"],"potencia":["spanish"],"potro":["spanish"],"pozo":["spanish"],"prado":["spanish"],"precoz":["spanish"],"pregunta":["spanish"],"premio":["spanish"],"prensa":["spanish"],"preso":["spanish"],"previo":["spanish"],"primo":["spanish"],"príncipe":["spanish"],"prisión":["spanish"],"privar":["spanish"],"proa":["spanish"],"probar":["spanish"],"proceso":["spanish"],"producto":["spanish"],"proeza":["spanish"],"profesor":["spanish"],"programa":["spanish"],"prole":["spanish"],"promesa":["spanish"],"pronto":["spanish"],"propio":["spanish"],"próximo":["spanish"],"prueba":["spanish"],"público":["spanish"],"puchero":["spanish"],"pudor":["spanish"],"pueblo":["spanish"],"puerta":["spanish"],"puesto":["spanish"],"pulga":["spanish"],"pulir":["spanish"],"pulmón":["spanish"],"pulpo":["spanish"],"pulso":["spanish"],"puma":["spanish"],"punto":["spanish"],"puñal":["spanish"],"puño":["spanish"],"pupa":["spanish"],"pupila":["spanish"],"puré":["spanish"],"quedar":["spanish"],"queja":["spanish"],"quemar":["spanish"],"querer":["spanish"],"queso":["spanish"],"quieto":["spanish"],"química":["spanish"],"quince":["spanish"],"quitar":["spanish"],"rábano":["spanish"],"rabia":["spanish"],"rabo":["spanish"],"ración":["spanish"],"radical":["spanish"],"raíz":["spanish"],"rama":["spanish"],"rampa":["spanish","turkish"],"rancho":["spanish"],"rango":["spanish"],"rapaz":["spanish"],"rápido":["spanish"],"rapto":["spanish"],"rasgo":["spanish"],"raspa":["spanish"],"rato":["spanish"],"rayo":["spanish"],"raza":["spanish"],"razón":["spanish"],"reacción":["spanish"],"realidad":["spanish"],"rebaño":["spanish"],"rebote":["spanish"],"recaer":["spanish"],"receta":["spanish"],"rechazo":["spanish"],"recoger":["spanish"],"recreo":["spanish"],"recto":["spanish"],"recurso":["spanish"],"red":["spanish"],"redondo":["spanish"],"reducir":["spanish"],"reflejo":["spanish"],"reforma":["spanish"],"refrán":["spanish"],"refugio":["spanish"],"regalo":["spanish"],"regir":["spanish"],"regla":["spanish"],"regreso":["spanish"],"rehén":["spanish"],"reino":["spanish"],"reír":["spanish"],"reja":["spanish"],"relato":["spanish"],"relevo":["spanish"],"relieve":["spanish"],"relleno":["spanish"],"reloj":["spanish"],"remar":["spanish"],"remedio":["spanish"],"remo":["spanish"],"rencor":["spanish"],"rendir":["spanish"],"renta":["spanish"],"reparto":["spanish"],"repetir":["spanish"],"reposo":["spanish"],"reptil":["spanish"],"res":["spanish"],"rescate":["spanish"],"resina":["spanish"],"respeto":["spanish"],"resto":["spanish"],"resumen":["spanish"],"retiro":["spanish"],"retorno":["spanish"],"retrato":["spanish"],"reunir":["spanish"],"revés":["spanish"],"revista":["spanish"],"rey":["spanish"],"rezar":["spanish"],"rico":["spanish"],"riego":["spanish"],"rienda":["spanish"],"riesgo":["spanish"],"rifa":["spanish"],"rígido":["spanish"],"rigor":["spanish"],"rincón":["spanish"],"riñón":["spanish"],"río":["spanish"],"riqueza":["spanish"],"risa":["spanish"],"ritmo":["spanish"],"rito":["spanish"],"rizo":["spanish"],"roble":["spanish"],"roce":["spanish"],"rociar":["spanish"],"rodar":["spanish"],"rodeo":["spanish"],"rodilla":["spanish"],"roer":["spanish"],"rojizo":["spanish"],"rojo":["spanish"],"romero":["spanish"],"romper":["spanish"],"ron":["spanish"],"ronco":["spanish"],"ronda":["spanish"],"ropa":["spanish"],"ropero":["spanish"],"rosa":["spanish"],"rosca":["spanish"],"rostro":["spanish"],"rotar":["spanish"],"rubí":["spanish"],"rubor":["spanish"],"rudo":["spanish"],"rueda":["spanish"],"rugir":["spanish"],"ruido":["spanish"],"ruina":["spanish"],"ruleta":["spanish"],"rulo":["spanish","turkish"],"rumbo":["spanish"],"rumor":["spanish"],"ruptura":["spanish"],"ruta":["spanish"],"rutina":["spanish"],"sábado":["spanish"],"saber":["spanish"],"sabio":["spanish"],"sable":["spanish"],"sacar":["spanish"],"sagaz":["spanish"],"sagrado":["spanish"],"sala":["spanish"],"saldo":["spanish"],"salero":["spanish"],"salir":["spanish"],"salmón":["spanish"],"salón":["spanish"],"salsa":["spanish"],"salto":["spanish"],"salud":["spanish"],"salvar":["spanish"],"samba":["spanish"],"sanción":["spanish"],"sandía":["spanish"],"sanear":["spanish"],"sangre":["spanish"],"sanidad":["spanish"],"sano":["spanish"],"santo":["spanish"],"sapo":["spanish"],"saque":["spanish"],"sardina":["spanish"],"sartén":["spanish"],"sastre":["spanish"],"satán":["spanish"],"sauna":["spanish"],"saxofón":["spanish"],"sección":["spanish"],"seco":["spanish"],"secreto":["spanish"],"secta":["spanish"],"sed":["spanish"],"seguir":["spanish"],"seis":["spanish"],"sello":["spanish"],"selva":["spanish"],"semana":["spanish"],"semilla":["spanish"],"senda":["spanish"],"sensor":["spanish"],"señal":["spanish"],"señor":["spanish"],"separar":["spanish"],"sepia":["spanish"],"sequía":["spanish"],"ser":["spanish"],"serie":["spanish"],"sermón":["spanish"],"servir":["spanish"],"sesenta":["spanish"],"sesión":["spanish"],"seta":["spanish"],"setenta":["spanish"],"severo":["spanish"],"sexo":["spanish"],"sexto":["spanish"],"sidra":["spanish"],"siesta":["spanish"],"siete":["spanish"],"siglo":["spanish"],"signo":["spanish"],"sílaba":["spanish"],"silbar":["spanish"],"silencio":["spanish"],"silla":["spanish"],"símbolo":["spanish"],"simio":["spanish"],"sirena":["spanish"],"sistema":["spanish"],"sitio":["spanish"],"situar":["spanish"],"sobre":["spanish"],"socio":["spanish"],"sodio":["spanish"],"sol":["spanish"],"solapa":["spanish"],"soldado":["spanish"],"soledad":["spanish"],"sólido":["spanish"],"soltar":["spanish"],"solución":["spanish"],"sombra":["spanish"],"sondeo":["spanish"],"sonido":["spanish"],"sonoro":["spanish"],"sonrisa":["spanish"],"sopa":["spanish"],"soplar":["spanish"],"soporte":["spanish"],"sordo":["spanish"],"sorpresa":["spanish"],"sorteo":["spanish"],"sostén":["spanish"],"sótano":["spanish"],"suave":["spanish"],"subir":["spanish"],"suceso":["spanish"],"sudor":["spanish"],"suegra":["spanish"],"suelo":["spanish"],"sueño":["spanish"],"suerte":["spanish"],"sufrir":["spanish"],"sujeto":["spanish"],"sultán":["spanish"],"sumar":["spanish"],"superar":["spanish"],"suplir":["spanish"],"suponer":["spanish"],"supremo":["spanish"],"sur":["spanish"],"surco":["spanish"],"sureño":["spanish"],"surgir":["spanish"],"susto":["spanish"],"sutil":["spanish"],"tabaco":["spanish"],"tabique":["spanish"],"tabla":["spanish"],"tabú":["spanish"],"taco":["spanish"],"tacto":["spanish"],"tajo":["spanish"],"talar":["spanish"],"talco":["spanish"],"talento":["spanish"],"talla":["spanish"],"talón":["spanish"],"tamaño":["spanish"],"tambor":["spanish"],"tango":["spanish"],"tanque":["spanish"],"tapa":["spanish"],"tapete":["spanish"],"tapia":["spanish"],"tapón":["spanish"],"taquilla":["spanish"],"tarde":["spanish"],"tarea":["spanish"],"tarifa":["spanish"],"tarjeta":["spanish"],"tarot":["spanish"],"tarro":["spanish"],"tarta":["spanish"],"tatuaje":["spanish"],"tauro":["spanish"],"taza":["spanish"],"tazón":["spanish"],"teatro":["spanish"],"techo":["spanish"],"tecla":["spanish"],"técnica":["spanish"],"tejado":["spanish"],"tejer":["spanish"],"tejido":["spanish"],"tela":["spanish"],"teléfono":["spanish"],"tema":["spanish"],"temor":["spanish"],"templo":["spanish"],"tenaz":["spanish"],"tender":["spanish"],"tener":["spanish"],"tenis":["spanish"],"tenso":["spanish"],"teoría":["spanish"],"terapia":["spanish"],"terco":["spanish"],"término":["spanish"],"ternura":["spanish"],"terror":["spanish"],"tesis":["spanish"],"tesoro":["spanish"],"testigo":["spanish"],"tetera":["spanish"],"texto":["spanish"],"tez":["spanish"],"tibio":["spanish"],"tiburón":["spanish"],"tiempo":["spanish"],"tienda":["spanish"],"tierra":["spanish"],"tieso":["spanish"],"tigre":["spanish"],"tijera":["spanish"],"tilde":["spanish"],"timbre":["spanish"],"tímido":["spanish"],"timo":["spanish"],"tinta":["spanish"],"tío":["spanish"],"típico":["spanish"],"tipo":["spanish"],"tira":["spanish"],"tirón":["spanish"],"titán":["spanish"],"títere":["spanish"],"título":["spanish"],"tiza":["spanish"],"toalla":["spanish"],"tobillo":["spanish"],"tocar":["spanish"],"tocino":["spanish"],"todo":["spanish"],"toga":["spanish"],"toldo":["spanish"],"tomar":["spanish","turkish"],"tono":["spanish"],"tonto":["spanish"],"topar":["spanish"],"tope":["spanish"],"toque":["spanish"],"tórax":["spanish"],"torero":["spanish"],"tormenta":["spanish"],"torneo":["spanish"],"toro":["spanish"],"torpedo":["spanish"],"torre":["spanish"],"torso":["spanish"],"tortuga":["spanish"],"tos":["spanish"],"tosco":["spanish"],"toser":["spanish"],"tóxico":["spanish"],"trabajo":["spanish"],"tractor":["spanish"],"traer":["spanish"],"tráfico":["spanish"],"trago":["spanish"],"traje":["spanish"],"tramo":["spanish"],"trance":["spanish"],"trato":["spanish"],"trauma":["spanish"],"trazar":["spanish"],"trébol":["spanish"],"tregua":["spanish"],"treinta":["spanish"],"tren":["spanish"],"trepar":["spanish"],"tres":["spanish"],"tribu":["spanish"],"trigo":["spanish"],"tripa":["spanish"],"triste":["spanish"],"triunfo":["spanish"],"trofeo":["spanish"],"trompa":["spanish"],"tronco":["spanish"],"tropa":["spanish"],"trote":["spanish"],"trozo":["spanish"],"truco":["spanish"],"trueno":["spanish"],"trufa":["spanish"],"tubería":["spanish"],"tubo":["spanish"],"tuerto":["spanish"],"tumba":["spanish"],"tumor":["spanish"],"túnel":["spanish"],"túnica":["spanish"],"turbina":["spanish"],"turismo":["spanish"],"turno":["spanish"],"tutor":["spanish"],"ubicar":["spanish"],"úlcera":["spanish"],"umbral":["spanish"],"unidad":["spanish"],"unir":["spanish"],"universo":["spanish"],"uno":["spanish"],"untar":["spanish"],"uña":["spanish"],"urbano":["spanish"],"urbe":["spanish"],"urgente":["spanish"],"urna":["spanish"],"usar":["spanish"],"usuario":["spanish"],"útil":["spanish"],"utopía":["spanish"],"uva":["spanish"],"vaca":["spanish"],"vacío":["spanish"],"vacuna":["spanish"],"vagar":["spanish"],"vago":["spanish"],"vaina":["spanish"],"vajilla":["spanish"],"vale":["spanish"],"válido":["spanish"],"valle":["spanish"],"valor":["spanish"],"válvula":["spanish"],"vampiro":["spanish"],"vara":["spanish"],"variar":["spanish"],"varón":["spanish"],"vaso":["spanish"],"vecino":["spanish"],"vector":["spanish"],"vehículo":["spanish"],"veinte":["spanish"],"vejez":["spanish"],"vela":["spanish"],"velero":["spanish"],"veloz":["spanish"],"vena":["spanish"],"vencer":["spanish"],"venda":["spanish"],"veneno":["spanish"],"vengar":["spanish"],"venir":["spanish"],"venta":["spanish"],"venus":["spanish"],"ver":["spanish"],"verano":["spanish"],"verbo":["spanish"],"verde":["spanish"],"vereda":["spanish"],"verja":["spanish"],"verso":["spanish"],"verter":["spanish"],"vía":["spanish"],"viaje":["spanish"],"vibrar":["spanish"],"vicio":["spanish"],"víctima":["spanish"],"vida":["spanish"],"vídeo":["spanish"],"vidrio":["spanish"],"viejo":["spanish"],"viernes":["spanish"],"vigor":["spanish"],"vil":["spanish"],"villa":["spanish"],"vinagre":["spanish"],"vino":["spanish"],"viñedo":["spanish"],"violín":["spanish"],"viral":["spanish"],"virgo":["spanish"],"virtud":["spanish"],"visor":["spanish"],"víspera":["spanish"],"vista":["spanish"],"vitamina":["spanish"],"viudo":["spanish"],"vivaz":["spanish"],"vivero":["spanish"],"vivir":["spanish"],"vivo":["spanish"],"volcán":["spanish"],"volumen":["spanish"],"volver":["spanish"],"voraz":["spanish"],"votar":["spanish"],"voto":["spanish"],"voz":["spanish"],"vuelo":["spanish"],"vulgar":["spanish"],"yacer":["spanish"],"yate":["spanish"],"yegua":["spanish"],"yema":["spanish"],"yerno":["spanish"],"yeso":["spanish"],"yodo":["spanish"],"yoga":["spanish"],"yogur":["spanish"],"zafiro":["spanish"],"zanja":["spanish"],"zapato":["spanish"],"zarza":["spanish"],"zona":["spanish"],"zorro":["spanish"],"zumo":["spanish"],"zurdo":["spanish"],"abajur":["turkish"],"abaküs":["turkish"],"abartı":["turkish"],"abdal":["turkish"],"abdest":["turkish"],"abiye":["turkish"],"abluka":["turkish"],"abone":["turkish"],"absorbe":["turkish"],"absürt":["turkish"],"acayip":["turkish"],"acele":["turkish"],"acemi":["turkish"],"açıkgöz":["turkish"],"adalet":["turkish"],"adam":["turkish"],"adezyon":["turkish"],"adisyon":["turkish"],"adliye":["turkish"],"adres":["turkish"],"afacan":["turkish"],"afili":["turkish"],"afiş":["turkish"],"afiyet":["turkish"],"aforizm":["turkish"],"afra":["turkish"],"ağaç":["turkish"],"ağır":["turkish"],"ahbap":["turkish"],"ahkam":["turkish"],"ahlak":["turkish"],"ahtapot":["turkish"],"aidat":["turkish"],"aile":["turkish"],"ajan":["turkish"],"akademi":["turkish"],"akarsu":["turkish"],"akbaş":["turkish"],"akciğer":["turkish"],"akdeniz":["turkish"],"akıbet":["turkish"],"akıl":["turkish"],"akıntı":["turkish"],"akide":["turkish"],"akrep":["turkish"],"akrobasi":["turkish"],"aksiyon":["turkish"],"akşam":["turkish"],"aktif":["turkish"],"aktör":["turkish"],"aktris":["turkish"],"akustik":["turkish"],"alaca":["turkish"],"albüm":["turkish"],"alçak":["turkish"],"aldanma":["turkish"],"aleni":["turkish"],"alet":["turkish"],"alfabe":["turkish"],"algılama":["turkish"],"alıngan":["turkish"],"alkış":["turkish"],"alkol":["turkish"],"alpay":["turkish"],"alperen":["turkish"],"altın":["turkish"],"altüst":["turkish"],"altyapı":["turkish"],"alyuvar":["turkish"],"amade":["turkish"],"amatör":["turkish"],"amazon":["turkish"],"ambalaj":["turkish"],"amblem":["turkish"],"ambulans":["turkish"],"amca":["turkish"],"amel":["turkish"],"amir":["turkish"],"amiyane":["turkish"],"amorti":["turkish"],"ampul":["turkish"],"anadolu":["turkish"],"anahtar":["turkish"],"anakonda":["turkish"],"anaokul":["turkish"],"anapara":["turkish"],"anarşi":["turkish"],"anatomi":["turkish"],"anayasa":["turkish"],"anekdot":["turkish"],"anestezi":["turkish"],"angaje":["turkish"],"anka":["turkish"],"anket":["turkish"],"anlamlı":["turkish"],"anne":["turkish"],"anomali":["turkish"],"anonim":["turkish"],"anten":["turkish"],"antlaşma":["turkish"],"apse":["turkish"],"araba":["turkish"],"aracı":["turkish"],"araf":["turkish"],"arbede":["turkish"],"arda":["turkish"],"arefe":["turkish"],"argo":["turkish"],"argüman":["turkish"],"arkadaş":["turkish"],"armoni":["turkish"],"arsa":["turkish"],"arsız":["turkish"],"artı":["turkish"],"aruz":["turkish"],"asansör":["turkish"],"asayiş":["turkish"],"asgari":["turkish"],"asil":["turkish"],"asker":["turkish"],"askı":["turkish"],"aslan":["turkish"],"asosyal":["turkish"],"astsubay":["turkish"],"asya":["turkish"],"aşçı":["turkish"],"aşırı":["turkish"],"aşure":["turkish"],"atabey":["turkish"],"ataman":["turkish"],"ateş":["turkish"],"atmaca":["turkish"],"atmosfer":["turkish"],"atölye":["turkish"],"avcı":["turkish"],"avdet":["turkish"],"avize":["turkish"],"avlu":["turkish"],"avokado":["turkish"],"avrupa":["turkish"],"avukat":["turkish"],"ayaz":["turkish"],"ayçiçeği":["turkish"],"aydın":["turkish"],"aygıt":["turkish"],"ayna":["turkish"],"ayran":["turkish"],"ayrıntı":["turkish"],"azim":["turkish"],"baca":["turkish"],"bagaj":["turkish"],"bağlantı":["turkish"],"bahadır":["turkish"],"bahçe":["turkish"],"baki":["turkish"],"bakkal":["turkish"],"baklava":["turkish"],"bakteri":["turkish"],"balçık":["turkish"],"balina":["turkish"],"balo":["turkish"],"balta":["turkish"],"bant":["turkish"],"banyo":["turkish"],"bardak":["turkish"],"barış":["turkish"],"başbuğ":["turkish"],"başıboş":["turkish"],"başkan":["turkish"],"başlık":["turkish"],"bavul":["turkish"],"bayındır":["turkish"],"baykuş":["turkish"],"bazlama":["turkish"],"bedel":["turkish"],"begüm":["turkish"],"bekçi":["turkish"],"bekle":["turkish"],"belge":["turkish"],"belki":["turkish"],"bencil":["turkish"],"benek":["turkish"],"bengi":["turkish"],"berjer":["turkish"],"berk":["turkish"],"berrak":["turkish"],"beşik":["turkish"],"beyin":["turkish"],"beyoğlu":["turkish"],"bıçak":["turkish"],"biberiye":["turkish"],"bidon":["turkish"],"bihaber":["turkish"],"bikini":["turkish"],"bilezik":["turkish"],"bilinç":["turkish"],"bilye":["turkish"],"bina":["turkish"],"binbaşı":["turkish"],"binyıl":["turkish"],"bisiklet":["turkish"],"bisküvi":["turkish"],"bitki":["turkish"],"bizzat":["turkish"],"bodrum":["turkish"],"boğaz":["turkish"],"bohça":["turkish"],"boncuk":["turkish"],"bonfile":["turkish"],"borsa":["turkish"],"boru":["turkish"],"bostan":["turkish"],"boşboğaz":["turkish"],"botanik":["turkish"],"boya":["turkish"],"boykot":["turkish"],"boynuz":["turkish"],"bozgun":["turkish"],"bozkır":["turkish"],"bölüm":["turkish"],"börek":["turkish"],"buçuk":["turkish"],"bugün":["turkish"],"buğday":["turkish"],"buhar":["turkish"],"buhran":["turkish"],"bulvar":["turkish"],"buram":["turkish"],"burçak":["turkish"],"burs":["turkish"],"burun":["turkish"],"buzdağı":["turkish"],"buzkıran":["turkish"],"bücür":["turkish"],"büfe":["turkish"],"bülten":["turkish"],"bütçe":["turkish"],"bütün":["turkish"],"büyük":["turkish"],"cacık":["turkish"],"cadı":["turkish"],"cahil":["turkish"],"cambaz":["turkish"],"canhıraş":["turkish"],"casus":["turkish"],"cazibe":["turkish"],"cehalet":["turkish"],"cehennem":["turkish"],"ceket":["turkish"],"cemre":["turkish"],"cenin":["turkish"],"cennet":["turkish"],"cepken":["turkish"],"cerrah":["turkish"],"cesur":["turkish"],"cetvel":["turkish"],"cevher":["turkish"],"ceylan":["turkish"],"cılız":["turkish"],"cıva":["turkish"],"cilt":["turkish"],"cisim":["turkish"],"ciyak":["turkish"],"coğrafya":["turkish"],"cömert":["turkish"],"cumba":["turkish"],"cüzdan":["turkish"],"çabucak":["turkish"],"çadır":["turkish"],"çağdaş":["turkish"],"çağlayan":["turkish"],"çağrı":["turkish"],"çakmak":["turkish"],"çalışkan":["turkish"],"çamaşır":["turkish"],"çapa":["turkish"],"çaput":["turkish"],"çarık":["turkish"],"çarpan":["turkish"],"çarşaf":["turkish"],"çayhane":["turkish"],"çekirdek":["turkish"],"çelebi":["turkish"],"çember":["turkish"],"çenet":["turkish"],"çengel":["turkish"],"çerçeve":["turkish"],"çerez":["turkish"],"çeşit":["turkish"],"çeşme":["turkish"],"çete":["turkish"],"çevre":["turkish"],"çeyiz":["turkish"],"çeyrek":["turkish"],"çığır":["turkish"],"çılgın":["turkish"],"çıngırak":["turkish"],"çift":["turkish"],"çiğdem":["turkish"],"çikolata":["turkish"],"çilek":["turkish"],"çimen":["turkish"],"çivi":["turkish"],"çoban":["turkish"],"çocuk":["turkish"],"çokgen":["turkish"],"çomak":["turkish"],"çorba":["turkish"],"çözelti":["turkish"],"çubuk":["turkish"],"çukur":["turkish"],"çuval":["turkish"],"çürük":["turkish"],"dağbaşı":["turkish"],"dağılım":["turkish"],"daktilo":["turkish"],"daldırış":["turkish"],"dalga":["turkish"],"dalkavuk":["turkish"],"damak":["turkish"],"damıtma":["turkish"],"damla":["turkish"],"dana":["turkish"],"dandik":["turkish"],"danışman":["turkish"],"daniska":["turkish"],"dantel":["turkish"],"dargeçit":["turkish"],"darphane":["turkish"],"davet":["turkish"],"dayı":["turkish"],"defter":["turkish"],"değer":["turkish"],"değirmen":["turkish"],"dehşet":["turkish"],"delgeç":["turkish"],"demir":["turkish"],"deneyim":["turkish"],"denge":["turkish"],"depo":["turkish"],"deprem":["turkish"],"derdest":["turkish"],"dere":["turkish"],"derhal":["turkish"],"derman":["turkish"],"dernek":["turkish"],"derviş":["turkish"],"desen":["turkish"],"destan":["turkish"],"dışarı":["turkish"],"dışbükey":["turkish"],"dijital":["turkish"],"dikbaşlı":["turkish"],"dilekçe":["turkish"],"dimağ":["turkish"],"dinamik":["turkish"],"dindar":["turkish"],"dinleme":["turkish"],"dinozor":["turkish"],"dipçik":["turkish"],"dipnot":["turkish"],"direniş":["turkish"],"dirsek":["turkish"],"disiplin":["turkish"],"divriği":["turkish"],"dizüstü":["turkish"],"dobra":["turkish"],"dodurga":["turkish"],"doğalgaz":["turkish"],"doküman":["turkish"],"dolap":["turkish"],"donanım":["turkish"],"dondurma":["turkish"],"donör":["turkish"],"doruk":["turkish"],"dosdoğru":["turkish"],"dost":["turkish"],"dosya":["turkish"],"dozer":["turkish"],"döküm":["turkish"],"dönence":["turkish"],"dörtyol":["turkish"],"dövme":["turkish"],"dram":["turkish"],"dublaj":["turkish"],"durum":["turkish"],"duvak":["turkish"],"duyarga":["turkish"],"duyma":["turkish"],"duyuru":["turkish"],"düğme":["turkish"],"düğüm":["turkish"],"dükkan":["turkish"],"dünür":["turkish"],"düpedüz":["turkish"],"dürbün":["turkish"],"düşünür":["turkish"],"düzayak":["turkish"],"düzeltme":["turkish"],"ebeveyn":["turkish"],"ebru":["turkish"],"ecel":["turkish"],"ecnebi":["turkish"],"ecza":["turkish"],"edat":["turkish"],"edilgen":["turkish"],"efendi":["turkish"],"efor":["turkish"],"efsane":["turkish"],"egemen":["turkish"],"egzersiz":["turkish"],"eğrelti":["turkish"],"ekarte":["turkish"],"ekip":["turkish"],"eklem":["turkish"],"ekmek":["turkish"],"ekol":["turkish"],"ekonomi":["turkish"],"ekose":["turkish"],"ekran":["turkish"],"ekvator":["turkish"],"elaman":["turkish"],"elastik":["turkish"],"elbet":["turkish"],"elbise":["turkish"],"elçi":["turkish"],"eldiven":["turkish"],"elebaşı":["turkish"],"eleştiri":["turkish"],"elma":["turkish"],"eloğlu":["turkish"],"elveda":["turkish"],"emare":["turkish"],"emekçi":["turkish"],"emisyon":["turkish"],"emniyet":["turkish"],"empati":["turkish"],"emsal":["turkish"],"emzik":["turkish"],"endüstri":["turkish"],"enerji":["turkish"],"engebe":["turkish"],"enişte":["turkish"],"enkaz":["turkish"],"entari":["turkish"],"entegre":["turkish"],"entrika":["turkish"],"enzim":["turkish"],"erdem":["turkish"],"ergen":["turkish"],"erguvan":["turkish"],"erkek":["turkish"],"erozyon":["turkish"],"ertesi":["turkish"],"erzak":["turkish"],"esaret":["turkish"],"esenlik":["turkish"],"eser":["turkish"],"eski":["turkish"],"esnek":["turkish"],"eşarp":["turkish"],"eşofman":["turkish"],"eşraf":["turkish"],"eşya":["turkish"],"eşzaman":["turkish"],"etik":["turkish"],"etken":["turkish"],"etkinlik":["turkish"],"etüt":["turkish"],"evet":["turkish"],"evire":["turkish"],"evrak":["turkish"],"evrim":["turkish"],"eyalet":["turkish"],"eyvah":["turkish"],"ezber":["turkish"],"fabrika":["turkish"],"fanus":["turkish"],"fason":["turkish"],"fasulye":["turkish"],"fatih":["turkish"],"fatura":["turkish"],"fayans":["turkish"],"fayton":["turkish"],"fazıl":["turkish"],"fazilet":["turkish"],"felsefe":["turkish"],"fener":["turkish"],"feribot":["turkish"],"fersah":["turkish"],"fesih":["turkish"],"feveran":["turkish"],"feza":["turkish"],"fıçı":["turkish"],"fıldır":["turkish"],"fındık":["turkish"],"fırça":["turkish"],"fırsat":["turkish"],"fırtına":["turkish"],"fıtık":["turkish"],"fidan":["turkish"],"fidye":["turkish"],"figür":["turkish"],"fihrist":["turkish"],"fikir":["turkish"],"fildişi":["turkish"],"filtre":["turkish"],"fincan":["turkish"],"firuze":["turkish"],"fitil":["turkish"],"fiyaka":["turkish"],"fizik":["turkish"],"flaş":["turkish"],"flüt":["turkish"],"fosil":["turkish"],"fren":["turkish"],"fukara":["turkish"],"futbol":["turkish"],"garabet":["turkish"],"gariban":["turkish"],"garnitür":["turkish"],"gazi":["turkish"],"gece":["turkish"],"gedik":["turkish"],"gelenek":["turkish"],"gelin":["turkish"],"gemi":["turkish"],"genç":["turkish"],"geniş":["turkish"],"geometri":["turkish"],"gerçek":["turkish"],"gevrek":["turkish"],"gezegen":["turkish"],"gezgin":["turkish"],"geziyolu":["turkish"],"gıcık":["turkish"],"gıda":["turkish"],"gıybet":["turkish"],"girdap":["turkish"],"girişim":["turkish"],"gitar":["turkish"],"giyecek":["turkish"],"giysi":["turkish"],"gizem":["turkish"],"gofret":["turkish"],"goril":["turkish"],"göbek":["turkish"],"göçebe":["turkish"],"göğüs":["turkish"],"gökdelen":["turkish"],"gökmen":["turkish"],"gökyüzü":["turkish"],"gölge":["turkish"],"gömlek":["turkish"],"gönül":["turkish"],"görenek":["turkish"],"görkemli":["turkish"],"görsel":["turkish"],"gösteri":["turkish"],"gövde":["turkish"],"gözaltı":["turkish"],"gözcü":["turkish"],"gözdağı":["turkish"],"gözleme":["turkish"],"gözyaşı":["turkish"],"grup":["turkish"],"gurbet":["turkish"],"gusül":["turkish"],"gübre":["turkish"],"güfte":["turkish"],"gümüş":["turkish"],"günaydın":["turkish"],"güncel":["turkish"],"gündüz":["turkish"],"güneş":["turkish"],"günyüzü":["turkish"],"gürbüz":["turkish"],"güvercin":["turkish"],"güzel":["turkish"],"hacamat":["turkish"],"hacim":["turkish"],"hademe":["turkish"],"hafız":["turkish"],"hafriyat":["turkish"],"hafta":["turkish"],"hakan":["turkish"],"hakem":["turkish"],"hakikat":["turkish"],"haksever":["turkish"],"halı":["turkish"],"hançer":["turkish"],"hane":["turkish"],"hapis":["turkish"],"hapşırık":["turkish"],"harf":["turkish"],"haseki":["turkish"],"hasret":["turkish"],"hatun":["turkish"],"havuç":["turkish"],"haylaz":["turkish"],"haysiyet":["turkish"],"hayvan":["turkish"],"hedef":["turkish"],"hemen":["turkish"],"hemfikir":["turkish"],"hendek":["turkish"],"hepsi":["turkish"],"hergele":["turkish"],"herhangi":["turkish"],"hesap":["turkish"],"heyecan":["turkish"],"heykel":["turkish"],"hezimet":["turkish"],"hıçkırık":["turkish"],"hızölçer":["turkish"],"hicviye":["turkish"],"hikaye":["turkish"],"hikmet":["turkish"],"hile":["turkish"],"hisse":["turkish"],"hobi":["turkish"],"hoca":["turkish"],"horlama":["turkish"],"hoşbeş":["turkish"],"hoşgörü":["turkish"],"hoyrat":["turkish"],"hörgüç":["turkish"],"höyük":["turkish"],"hudut":["turkish"],"hukuk":["turkish"],"hunhar":["turkish"],"hurda":["turkish"],"huysuz":["turkish"],"huzur":["turkish"],"hücum":["turkish"],"hükümet":["turkish"],"hünkar":["turkish"],"hüviyet":["turkish"],"ırmak":["turkish"],"ısıölçer":["turkish"],"ısıtıcı":["turkish"],"ıspanak":["turkish"],"ısrar":["turkish"],"ışıldak":["turkish"],"ızdırap":["turkish"],"ızgara":["turkish"],"ibadet":["turkish"],"icat":["turkish"],"içbükey":["turkish"],"içecek":["turkish"],"içgüdü":["turkish"],"içsel":["turkish"],"idman":["turkish"],"iftihar":["turkish"],"iğne":["turkish"],"ihanet":["turkish"],"ihbar":["turkish"],"ihdas":["turkish"],"ihmal":["turkish"],"ihracat":["turkish"],"ihsan":["turkish"],"ikilem":["turkish"],"ikindi":["turkish"],"ikircik":["turkish"],"iklim":["turkish"],"iksir":["turkish"],"iktibas":["turkish"],"ilaç":["turkish"],"ilçe":["turkish"],"ileri":["turkish"],"iletişim":["turkish"],"ilgi":["turkish"],"ilhak":["turkish"],"ilkbahar":["turkish"],"ilkokul":["turkish"],"ilmek":["turkish"],"imkan":["turkish"],"imleç":["turkish"],"imsak":["turkish"],"imtihan":["turkish"],"imza":["turkish"],"ince":["turkish"],"inkar":["turkish"],"inşa":["turkish"],"ipek":["turkish"],"ipucu":["turkish"],"irade":["turkish"],"irfan":["turkish"],"irmik":["turkish"],"isabet":["turkish"],"iskele":["turkish"],"israf":["turkish"],"isyan":["turkish"],"işçi":["turkish"],"işgal":["turkish"],"işgüzar":["turkish"],"işlem":["turkish"],"itibar":["turkish"],"itiraf":["turkish"],"ivedi":["turkish"],"ivme":["turkish"],"iyileşme":["turkish"],"iyimser":["turkish"],"izbandut":["turkish"],"izci":["turkish"],"izdiham":["turkish"],"izin":["turkish"],"jakoben":["turkish"],"jandarma":["turkish"],"jargon":["turkish"],"kabadayı":["turkish"],"kablo":["turkish"],"kabus":["turkish"],"kaçamak":["turkish"],"kadeh":["turkish"],"kadın":["turkish"],"kadraj":["turkish"],"kafa":["turkish"],"kafkas":["turkish"],"kağıt":["turkish"],"kağnı":["turkish"],"kahkaha":["turkish"],"kahraman":["turkish"],"kahvaltı":["turkish"],"kakül":["turkish"],"kaldırım":["turkish"],"kale":["turkish"],"kalibre":["turkish"],"kalkan":["turkish"],"kalpak":["turkish"],"kamış":["turkish"],"kamyon":["turkish"],"kanat":["turkish"],"kandaş":["turkish"],"kanepe":["turkish"],"kanser":["turkish"],"kanun":["turkish"],"kaos":["turkish"],"kapı":["turkish"],"kaplıca":["turkish"],"kaptan":["turkish"],"karanlık":["turkish"],"kardeş":["turkish"],"karga":["turkish"],"karınca":["turkish"],"karmaşa":["turkish"],"karşıt":["turkish"],"kasırga":["turkish"],"kask":["turkish"],"kasvet":["turkish"],"katkı":["turkish"],"katman":["turkish"],"kavram":["turkish"],"kaygan":["turkish"],"kaynakça":["turkish"],"kayyum":["turkish"],"kedi":["turkish"],"kehanet":["turkish"],"kekik":["turkish"],"kelebek":["turkish"],"kenar":["turkish"],"kerkenez":["turkish"],"kerpiç":["turkish"],"kesirli":["turkish"],"kesmece":["turkish"],"kestane":["turkish"],"keşkek":["turkish"],"ketçap":["turkish"],"keyfiyet":["turkish"],"kıble":["turkish"],"kıdemli":["turkish"],"kılavuz":["turkish"],"kılçık":["turkish"],"kılıf":["turkish"],"kıraç":["turkish"],"kırmızı":["turkish"],"kırsal":["turkish"],"kısayol":["turkish"],"kısım":["turkish"],"kıskanç":["turkish"],"kısmet":["turkish"],"kışla":["turkish"],"kıvanç":["turkish"],"kıvılcım":["turkish"],"kıvrık":["turkish"],"kıyafet":["turkish"],"kıymetli":["turkish"],"kızak":["turkish"],"kızılcık":["turkish"],"kibar":["turkish"],"kinaye":["turkish"],"kira":["turkish"],"kiremit":["turkish"],"kirli":["turkish"],"kirpik":["turkish"],"kişisel":["turkish"],"kitap":["turkish"],"koçbaşı":["turkish"],"kodaman":["turkish"],"koğuş":["turkish"],"kokteyl":["turkish"],"kolaycı":["turkish"],"kolbastı":["turkish"],"kolonya":["turkish"],"koltuk":["turkish"],"kolye":["turkish"],"kombine":["turkish"],"komedyen":["turkish"],"komiser":["turkish"],"komposto":["turkish"],"komşu":["turkish"],"komuta":["turkish"],"konak":["turkish"],"konfor":["turkish"],"koni":["turkish"],"konsül":["turkish"],"kopya":["turkish"],"korkusuz":["turkish"],"korna":["turkish"],"korse":["turkish"],"korunak":["turkish"],"korvet":["turkish"],"kostüm":["turkish"],"koşul":["turkish"],"koyu":["turkish"],"kozmik":["turkish"],"köfte":["turkish"],"kökensel":["turkish"],"köprücük":["turkish"],"köpük":["turkish"],"kördüğüm":["turkish"],"körfez":["turkish"],"köstebek":["turkish"],"köşegen":["turkish"],"kötü":["turkish"],"kravat":["turkish"],"kriter":["turkish"],"kuantum":["turkish"],"kudurma":["turkish"],"kuluçka":["turkish"],"kulübe":["turkish"],"kumanya":["turkish"],"kumbara":["turkish"],"kumlu":["turkish"],"kumpir":["turkish"],"kumral":["turkish"],"kundura":["turkish"],"kupa":["turkish"],"kupkuru":["turkish"],"kuramsal":["turkish"],"kurbağa":["turkish"],"kurdele":["turkish"],"kurgu":["turkish"],"kurmay":["turkish"],"kurşun":["turkish"],"kurtuluş":["turkish"],"kurultay":["turkish"],"kurye":["turkish"],"kusursuz":["turkish"],"kuşak":["turkish"],"kuşbaşı":["turkish"],"kuşkulu":["turkish"],"kutlama":["turkish"],"kutsal":["turkish"],"kutup":["turkish"],"kuver":["turkish"],"kuyruk":["turkish"],"kuzey":["turkish"],"kuzgun":["turkish"],"küçük":["turkish"],"külçe":["turkish"],"külfet":["turkish"],"külliye":["turkish"],"kültürel":["turkish"],"kümes":["turkish"],"künefe":["turkish"],"küresel":["turkish"],"kütle":["turkish"],"lahana":["turkish"],"lahmacun":["turkish"],"lamba":["turkish"],"lansman":["turkish"],"lavaş":["turkish"],"layık":["turkish"],"leğen":["turkish"],"levent":["turkish"],"leziz":["turkish"],"lezzet":["turkish"],"lider":["turkish"],"likide":["turkish"],"liman":["turkish"],"liste":["turkish"],"litre":["turkish"],"liyakat":["turkish"],"lodos":["turkish"],"lokanta":["turkish"],"lokman":["turkish"],"lokum":["turkish"],"lunapark":["turkish"],"lütfen":["turkish"],"lüzum":["turkish"],"nokta":["turkish"],"mabet":["turkish"],"macera":["turkish"],"macun":["turkish"],"madalya":["turkish"],"madde":["turkish"],"madem":["turkish"],"mağara":["turkish"],"mağdur":["turkish"],"mağfiret":["turkish"],"mağlup":["turkish"],"mahalle":["turkish"],"mahcup":["turkish"],"mahir":["turkish"],"mahkeme":["turkish"],"mahlas":["turkish"],"mahrum":["turkish"],"mahsul":["turkish"],"makas":["turkish"],"makbuz":["turkish"],"makine":["turkish"],"makro":["turkish"],"maksat":["turkish"],"makul":["turkish"],"maliye":["turkish"],"manav":["turkish"],"mangal":["turkish"],"manidar":["turkish"],"manken":["turkish"],"mantık":["turkish"],"manzara":["turkish"],"mareşal":["turkish"],"margarin":["turkish"],"marifet":["turkish"],"marmelat":["turkish"],"masaüstü":["turkish"],"masmavi":["turkish"],"masraf":["turkish"],"masum":["turkish"],"matah":["turkish"],"materyal":["turkish"],"matrak":["turkish"],"maval":["turkish"],"mavra":["turkish"],"maydanoz":["turkish"],"mayhoş":["turkish"],"maytap":["turkish"],"mazbata":["turkish"],"mazeret":["turkish"],"mazlum":["turkish"],"mazot":["turkish"],"mazur":["turkish"],"meblağ":["turkish"],"mebus":["turkish"],"mecaz":["turkish"],"mecbur":["turkish"],"meclis":["turkish"],"mecmua":["turkish"],"mecnun":["turkish"],"meçhul":["turkish"],"medeni":["turkish"],"mehtap":["turkish"],"mekanik":["turkish"],"melodi":["turkish"],"meltem":["turkish"],"memur":["turkish"],"mendil":["turkish"],"menekşe":["turkish"],"menteşe":["turkish"],"meraklı":["turkish"],"mercek":["turkish"],"merdiven":["turkish"],"merhaba":["turkish"],"merinos":["turkish"],"merkez":["turkish"],"mermi":["turkish"],"mert":["turkish"],"mesafe":["turkish"],"mesele":["turkish"],"mesken":["turkish"],"meslek":["turkish"],"meşale":["turkish"],"meşgul":["turkish"],"meşhur":["turkish"],"metafor":["turkish"],"metin":["turkish"],"metre":["turkish"],"mevcut":["turkish"],"mevkidaş":["turkish"],"meydan":["turkish"],"meyil":["turkish"],"meyve":["turkish"],"meziyet":["turkish"],"mezun":["turkish"],"mıknatıs":["turkish"],"mısra":["turkish"],"mızıka":["turkish"],"miğfer":["turkish"],"mihrak":["turkish"],"miktar":["turkish"],"milat":["turkish"],"milli":["turkish"],"mimar":["turkish"],"minare":["turkish"],"mineral":["turkish"],"minik":["turkish"],"minyon":["turkish"],"mirliva":["turkish"],"misafir":["turkish"],"miskin":["turkish"],"miting":["turkish"],"miyop":["turkish"],"mizah":["turkish"],"mobilya":["turkish"],"monitör":["turkish"],"morötesi":["turkish"],"motive":["turkish"],"mozaik":["turkish"],"muavin":["turkish"],"mucize":["turkish"],"muhafız":["turkish"],"muhteşem":["turkish"],"mukayese":["turkish"],"mumya":["turkish"],"musluk":["turkish"],"muşamba":["turkish"],"mutabık":["turkish"],"mutfak":["turkish"],"mutlu":["turkish"],"muzaffer":["turkish"],"muzdarip":["turkish"],"mübarek":["turkish"],"mücadele":["turkish"],"müdür":["turkish"],"müfredat":["turkish"],"müftü":["turkish"],"mühendis":["turkish"],"mühim":["turkish"],"mühlet":["turkish"],"mükemmel":["turkish"],"mülk":["turkish"],"mümkün":["turkish"],"mümtaz":["turkish"],"müsrif":["turkish"],"müstesna":["turkish"],"müşahit":["turkish"],"müşteri":["turkish"],"mütercim":["turkish"],"müthiş":["turkish"],"müze":["turkish"],"müzik":["turkish"],"nabız":["turkish"],"nadas":["turkish"],"nadir":["turkish"],"nahoş":["turkish"],"nakarat":["turkish"],"nakış":["turkish"],"nalbur":["turkish"],"namlu":["turkish"],"namus":["turkish"],"nankör":["turkish"],"nargile":["turkish"],"narkoz":["turkish"],"nasıl":["turkish"],"nasip":["turkish"],"naylon":["turkish"],"nazar":["turkish"],"nazım":["turkish"],"nazik":["turkish"],"neden":["turkish"],"nefes":["turkish"],"negatif":["turkish"],"neon":["turkish"],"neptün":["turkish"],"nerede":["turkish"],"nesil":["turkish"],"nesnel":["turkish"],"neşeli":["turkish"],"netice":["turkish"],"nevresim":["turkish"],"neyse":["turkish"],"neyzen":["turkish"],"nezaket":["turkish"],"nezih":["turkish"],"nezle":["turkish"],"nicel":["turkish"],"nilüfer":["turkish"],"nimet":["turkish"],"nisan":["turkish"],"nispet":["turkish"],"nitekim":["turkish"],"nizam":["turkish"],"nohut":["turkish"],"noksan":["turkish"],"nostalji":["turkish"],"noter":["turkish"],"nöbet":["turkish"],"numara":["turkish"],"numune":["turkish"],"nutuk":["turkish"],"nüfus":["turkish"],"obabaşı":["turkish"],"obez":["turkish"],"obje":["turkish"],"ocak":["turkish"],"odun":["turkish"],"ofansif":["turkish"],"ofis":["turkish"],"oğlak":["turkish"],"oğuz":["turkish"],"okçu":["turkish"],"oklava":["turkish"],"oksijen":["turkish"],"okul":["turkish"],"okumuş":["turkish"],"okutman":["turkish"],"okuyucu":["turkish"],"okyanus":["turkish"],"olağan":["turkish"],"olanak":["turkish"],"olası":["turkish"],"olay":["turkish"],"olgun":["turkish"],"olimpik":["turkish"],"olumlu":["turkish"],"omlet":["turkish"],"omurga":["turkish"],"onarım":["turkish"],"onursal":["turkish"],"optik":["turkish"],"orantı":["turkish"],"ordu":["turkish"],"organik":["turkish"],"orijin":["turkish"],"orkide":["turkish"],"orman":["turkish"],"orta":["turkish"],"oruç":["turkish"],"otağ":["turkish"],"otantik":["turkish"],"otel":["turkish"],"otoban":["turkish"],"otogar":["turkish"],"otomobil":["turkish"],"otonom":["turkish"],"otopark":["turkish"],"otorite":["turkish"],"otoyol":["turkish"],"oturum":["turkish"],"oyuk":["turkish"],"oyuncak":["turkish"],"ozan":["turkish"],"ödeme":["turkish"],"ödenek":["turkish"],"ödev":["turkish"],"ödül":["turkish"],"ödünç":["turkish"],"öfke":["turkish"],"öğlen":["turkish"],"öğrenci":["turkish"],"öğün":["turkish"],"öğütücü":["turkish"],"öksürük":["turkish"],"ölçme":["turkish"],"ölçü":["turkish"],"ölümsüz":["turkish"],"ömür":["turkish"],"önayak":["turkish"],"öncü":["turkish"],"önder":["turkish"],"önem":["turkish"],"önerge":["turkish"],"öngörü":["turkish"],"önlük":["turkish"],"önsezi":["turkish"],"öpücük":["turkish"],"ördek":["turkish"],"örgü":["turkish"],"örtbas":["turkish"],"örtme":["turkish"],"örtü":["turkish"],"örümcek":["turkish"],"örüntü":["turkish"],"öteberi":["turkish"],"öteki":["turkish"],"övünç":["turkish"],"öykü":["turkish"],"öyleyse":["turkish"],"özçekim":["turkish"],"özdeyiş":["turkish"],"özel":["turkish"],"özenti":["turkish"],"özerk":["turkish"],"özgürlük":["turkish"],"özlem":["turkish"],"özlü":["turkish"],"özne":["turkish"],"özsever":["turkish"],"özümseme":["turkish"],"özür":["turkish"],"özveri":["turkish"],"pabuç":["turkish"],"padişah":["turkish"],"palamut":["turkish"],"palmiye":["turkish"],"palto":["turkish"],"palyaço":["turkish"],"pamuk":["turkish"],"panayır":["turkish"],"pancar":["turkish"],"panik":["turkish"],"panjur":["turkish"],"pankart":["turkish"],"pano":["turkish"],"pansuman":["turkish"],"pantolon":["turkish"],"panzehir":["turkish"],"papatya":["turkish"],"papyon":["turkish"],"paraşüt":["turkish"],"parça":["turkish"],"pardösü":["turkish"],"parfüm":["turkish"],"parıltı":["turkish"],"parkur":["turkish"],"parmak":["turkish"],"parodi":["turkish"],"parsel":["turkish"],"partner":["turkish"],"pasaport":["turkish"],"pasif":["turkish"],"paskalya":["turkish"],"pastırma":["turkish"],"paşa":["turkish"],"patates":["turkish"],"paten":["turkish"],"patika":["turkish"],"patlıcan":["turkish"],"patolog":["turkish"],"payanda":["turkish"],"paydaş":["turkish"],"payidar":["turkish"],"paylaşma":["turkish"],"paytak":["turkish"],"peçete":["turkish"],"peder":["turkish"],"pehlivan":["turkish"],"pekala":["turkish"],"pekmez":["turkish"],"pelerin":["turkish"],"pelikan":["turkish"],"pelüş":["turkish"],"pembe":["turkish"],"pencere":["turkish"],"pense":["turkish"],"perçin":["turkish"],"perde":["turkish"],"pergel":["turkish"],"perişan":["turkish"],"peron":["turkish"],"personel":["turkish"],"perşembe":["turkish"],"peruk":["turkish"],"pervane":["turkish"],"pespaye":["turkish"],"pestil":["turkish"],"peşin":["turkish"],"petek":["turkish"],"petrol":["turkish"],"petunya":["turkish"],"peynir":["turkish"],"peyzaj":["turkish"],"pınar":["turkish"],"pırasa":["turkish"],"pırlanta":["turkish"],"pide":["turkish"],"pikap":["turkish"],"pilav":["turkish"],"piliç":["turkish"],"pipet":["turkish"],"pipo":["turkish"],"piramit":["turkish"],"pirinç":["turkish"],"pirzola":["turkish"],"pist":["turkish"],"pişik":["turkish"],"pişman":["turkish"],"piyasa":["turkish"],"piyes":["turkish"],"plaj":["turkish"],"plaket":["turkish"],"planlama":["turkish"],"platform":["turkish"],"plazma":["turkish"],"podyum":["turkish"],"poğaça":["turkish"],"polat":["turkish"],"politika":["turkish"],"popüler":["turkish"],"porselen":["turkish"],"portakal":["turkish"],"poster":["turkish"],"poşet":["turkish"],"poyraz":["turkish"],"pozitif":["turkish"],"pranga":["turkish"],"pratik":["turkish"],"prenses":["turkish"],"prim":["turkish"],"profil":["turkish"],"proje":["turkish"],"protokol":["turkish"],"puan":["turkish"],"pudra":["turkish"],"pusula":["turkish"],"püre":["turkish"],"pürüz":["turkish"],"püstül":["turkish"],"püsür":["turkish"],"racon":["turkish"],"radikal":["turkish"],"radyo":["turkish"],"rafadan":["turkish"],"rafine":["turkish"],"rağbet":["turkish"],"rahat":["turkish"],"rahle":["turkish"],"rakam":["turkish"],"raket":["turkish"],"rakip":["turkish"],"rakun":["turkish"],"ralli":["turkish"],"randevu":["turkish"],"ranza":["turkish"],"rapor":["turkish"],"rastgele":["turkish"],"rasyonel":["turkish"],"razı":["turkish"],"realite":["turkish"],"reçine":["turkish"],"refah":["turkish"],"referans":["turkish"],"refik":["turkish"],"rehber":["turkish"],"rehin":["turkish"],"reis":["turkish"],"rekabet":["turkish"],"reklam":["turkish"],"rekor":["turkish"],"rektör":["turkish"],"renk":["turkish"],"resim":["turkish"],"resmen":["turkish"],"restoran":["turkish"],"retorik":["turkish"],"revaç":["turkish"],"reyon":["turkish"],"rezalet":["turkish"],"rezerv":["turkish"],"rezil":["turkish"],"rıhtım":["turkish"],"rıza":["turkish"],"ritim":["turkish"],"ritüel":["turkish"],"rivayet":["turkish"],"roman":["turkish"],"rozet":["turkish"],"röportaj":["turkish"],"rötar":["turkish"],"ruble":["turkish"],"ruhban":["turkish"],"ruhsat":["turkish"],"rulet":["turkish"],"runik":["turkish"],"rutin":["turkish"],"rutubet":["turkish"],"rüşvet":["turkish"],"rütbe":["turkish"],"rüya":["turkish"],"rüzgar":["turkish"],"sabah":["turkish"],"sabıka":["turkish"],"sabit":["turkish"],"sabun":["turkish"],"saçma":["turkish"],"sade":["turkish"],"sadık":["turkish"],"safahat":["turkish"],"safdil":["turkish"],"safkan":["turkish"],"sağanak":["turkish"],"sağduyu":["turkish"],"sağlam":["turkish"],"saha":["turkish"],"sahiden":["turkish"],"sahne":["turkish"],"sakal":["turkish"],"sakız":["turkish"],"sakin":["turkish"],"saklama":["turkish"],"saksağan":["turkish"],"salamura":["turkish"],"salça":["turkish"],"salgı":["turkish"],"salınım":["turkish"],"salkım":["turkish"],"saltanat":["turkish"],"sanatçı":["turkish"],"sancak":["turkish"],"sandalye":["turkish"],"saniye":["turkish"],"saplantı":["turkish"],"sapsız":["turkish"],"saray":["turkish"],"sarışın":["turkish"],"sarkık":["turkish"],"sarmaşık":["turkish"],"satır":["turkish"],"savaşım":["turkish"],"savunma":["turkish"],"saydam":["turkish"],"sayfa":["turkish"],"saygın":["turkish"],"sayısal":["turkish"],"sebep":["turkish"],"seçenek":["turkish"],"seçim":["turkish"],"seçkin":["turkish"],"seçmen":["turkish"],"sedir":["turkish"],"sedye":["turkish"],"sefer":["turkish"],"sehpa":["turkish"],"sekizgen":["turkish"],"selektör":["turkish"],"selvi":["turkish"],"semavi":["turkish"],"sembol":["turkish"],"seminer":["turkish"],"senaryo":["turkish"],"sendika":["turkish"],"senkron":["turkish"],"sensör":["turkish"],"sentez":["turkish"],"sepet":["turkish"],"seramik":["turkish"],"serbest":["turkish"],"serdar":["turkish"],"seremoni":["turkish"],"sergi":["turkish"],"serhat":["turkish"],"serin":["turkish"],"sermaye":["turkish"],"serpuş":["turkish"],"sersem":["turkish"],"serüven":["turkish"],"sesli":["turkish"],"sesteş":["turkish"],"sevap":["turkish"],"seviye":["turkish"],"seyahat":["turkish"],"seyirci":["turkish"],"sezon":["turkish"],"sıcak":["turkish"],"sıfat":["turkish"],"sıhhi":["turkish"],"sınanma":["turkish"],"sınır":["turkish"],"sıradan":["turkish"],"sırdaş":["turkish"],"sırma":["turkish"],"sırtüstü":["turkish"],"sızgıt":["turkish"],"siftah":["turkish"],"sigorta":["turkish"],"sihirbaz":["turkish"],"silah":["turkish"],"silecek":["turkish"],"silindir":["turkish"],"simetri":["turkish"],"simge":["turkish"],"simit":["turkish"],"sincap":["turkish"],"sindirim":["turkish"],"sinema":["turkish"],"sinirli":["turkish"],"sipariş":["turkish"],"sirke":["turkish"],"siroz":["turkish"],"sistem":["turkish"],"sivilce":["turkish"],"siyasi":["turkish"],"soba":["turkish"],"sofra":["turkish"],"soğuk":["turkish"],"sohbet":["turkish"],"sokak":["turkish"],"solfej":["turkish"],"solunum":["turkish"],"somut":["turkish"],"sonbahar":["turkish"],"sonraki":["turkish"],"sonsuz":["turkish"],"sorunsuz":["turkish"],"sosyete":["turkish"],"soyağacı":["turkish"],"soydaş":["turkish"],"soygun":["turkish"],"soytarı":["turkish"],"söğüş":["turkish"],"sömürge":["turkish"],"sönük":["turkish"],"söylem":["turkish"],"sözcük":["turkish"],"sözde":["turkish"],"spatula":["turkish"],"spektrum":["turkish"],"spiker":["turkish"],"sporcu":["turkish"],"sprey":["turkish"],"stabil":["turkish"],"statü":["turkish"],"stok":["turkish"],"stopaj":["turkish"],"strateji":["turkish"],"subay":["turkish"],"sucuk":["turkish"],"suçüstü":["turkish"],"suhulet":["turkish"],"sulama":["turkish"],"sungur":["turkish"],"sunucu":["turkish"],"surat":["turkish"],"susam":["turkish"],"suskun":["turkish"],"sükse":["turkish"],"sükut":["turkish"],"sülale":["turkish"],"sünger":["turkish"],"süpürge":["turkish"],"sürahi":["turkish"],"süreç":["turkish"],"sürgün":["turkish"],"sürüm":["turkish"],"süsleme":["turkish"],"sütanne":["turkish"],"sütlaç":["turkish"],"sütun":["turkish"],"süvari":["turkish"],"şahane":["turkish"],"şahbaz":["turkish"],"şahit":["turkish"],"şahsiyet":["turkish"],"şakıma":["turkish"],"şaklaban":["turkish"],"şakrak":["turkish"],"şamar":["turkish"],"şampiyon":["turkish"],"şanslı":["turkish"],"şantiye":["turkish"],"şapka":["turkish"],"şarkıcı":["turkish"],"şartname":["turkish"],"şaşırma":["turkish"],"şaşkın":["turkish"],"şatafat":["turkish"],"şayet":["turkish"],"şebeke":["turkish"],"şefkat":["turkish"],"şeftali":["turkish"],"şehir":["turkish"],"şehvet":["turkish"],"şeker":["turkish"],"şekil":["turkish"],"şelale":["turkish"],"şema":["turkish"],"şemsiye":["turkish"],"şerbet":["turkish"],"şeref":["turkish"],"şerit":["turkish"],"şımarık":["turkish"],"şıpıdık":["turkish"],"şifre":["turkish"],"şimdi":["turkish"],"şimşek":["turkish"],"şipşak":["turkish"],"şirin":["turkish"],"şişe":["turkish"],"şişirme":["turkish"],"şofben":["turkish"],"şöhret":["turkish"],"şölen":["turkish"],"şüphe":["turkish"],"tabaka":["turkish"],"tabure":["turkish"],"tadilat":["turkish"],"taharet":["turkish"],"tahıl":["turkish"],"tahkim":["turkish"],"tahlil":["turkish"],"tahmin":["turkish"],"tahrifat":["turkish"],"tahsilat":["turkish"],"tahta":["turkish"],"taklit":["turkish"],"takoz":["turkish"],"taksici":["turkish"],"taktik":["turkish"],"takvim":["turkish"],"talebe":["turkish"],"talip":["turkish"],"tamamen":["turkish"],"tamirci":["turkish"],"tamtakır":["turkish"],"tandır":["turkish"],"tanecik":["turkish"],"tanıtım":["turkish"],"tanrı":["turkish"],"tansiyon":["turkish"],"tapan":["turkish"],"tapınak":["turkish"],"taptaze":["turkish"],"tapu":["turkish"],"tarafgir":["turkish"],"tarhana":["turkish"],"tarım":["turkish"],"tarih":["turkish"],"tarla":["turkish"],"tartak":["turkish"],"tarumar":["turkish"],"tasarım":["turkish"],"tasdik":["turkish"],"taslak":["turkish"],"tastamam":["turkish"],"taşeron":["turkish"],"taşınmaz":["turkish"],"taşra":["turkish"],"tatava":["turkish"],"tatbikat":["turkish"],"tatil":["turkish"],"tatlı":["turkish"],"tavsiye":["turkish"],"tavşan":["turkish"],"tavuk":["turkish"],"taze":["turkish"],"taziye":["turkish"],"tazminat":["turkish"],"tebeşir":["turkish"],"tebrik":["turkish"],"tecrübe":["turkish"],"teçhizat":["turkish"],"tedarik":["turkish"],"tedbir":["turkish"],"teftiş":["turkish"],"teğet":["turkish"],"teğmen":["turkish"],"tehdit":["turkish"],"tehlike":["turkish"],"tekdüze":["turkish"],"tekerlek":["turkish"],"tekme":["turkish"],"teknik":["turkish"],"tekrar":["turkish"],"telef":["turkish"],"telsiz":["turkish"],"telve":["turkish"],"temas":["turkish"],"tembel":["turkish"],"temiz":["turkish"],"temkin":["turkish"],"temsilci":["turkish"],"tendon":["turkish"],"teneke":["turkish"],"tenha":["turkish"],"tenkit":["turkish"],"tepegöz":["turkish"],"tepki":["turkish"],"terazi":["turkish"],"terbiye":["turkish"],"tercih":["turkish"],"tereyağı":["turkish"],"terfi":["turkish"],"terim":["turkish"],"terminal":["turkish"],"tersane":["turkish"],"tertip":["turkish"],"tesadüf":["turkish"],"tescil":["turkish"],"tesir":["turkish"],"teslimat":["turkish"],"tespit":["turkish"],"testere":["turkish"],"teşekkür":["turkish"],"teşhir":["turkish"],"teşrif":["turkish"],"teşvik":["turkish"],"teyze":["turkish"],"tezahür":["turkish"],"tezgah":["turkish"],"tıbbi":["turkish"],"tıkaç":["turkish"],"tıkışık":["turkish"],"tıknaz":["turkish"],"tılsım":["turkish"],"tıpkı":["turkish"],"tıraş":["turkish"],"tırışka":["turkish"],"tırmanış":["turkish"],"tırnak":["turkish"],"tırpan":["turkish"],"tıslama":["turkish"],"ticaret":["turkish"],"tilki":["turkish"],"tiryaki":["turkish"],"titreşim":["turkish"],"tohum":["turkish"],"tokat":["turkish"],"tolere":["turkish"],"tombak":["turkish"],"tomurcuk":["turkish"],"topaç":["turkish"],"toplum":["turkish"],"toprak":["turkish"],"toptan":["turkish"],"toraman":["turkish"],"torpido":["turkish"],"tortu":["turkish"],"tosbağa":["turkish"],"toynak":["turkish"],"tören":["turkish"],"trafik":["turkish"],"trajedi":["turkish"],"tramvay":["turkish"],"tribün":["turkish"],"triko":["turkish"],"tugay":["turkish"],"tuğla":["turkish"],"tuğrul":["turkish"],"tuhaf":["turkish"],"tulumba":["turkish"],"tunç":["turkish"],"turan":["turkish"],"turkuaz":["turkish"],"turnusol":["turkish"],"turşu":["turkish"],"turuncu":["turkish"],"tutanak":["turkish"],"tutkal":["turkish"],"tutsak":["turkish"],"tutum":["turkish"],"tuyuğ":["turkish"],"tuzlu":["turkish"],"tüccar":["turkish"],"tüfek":["turkish"],"tükenmez":["turkish"],"tülbent":["turkish"],"tümleç":["turkish"],"tünel":["turkish"],"türbin":["turkish"],"türev":["turkish"],"türk":["turkish"],"tüzük":["turkish"],"ucube":["turkish"],"ucuz":["turkish"],"uçak":["turkish"],"uçurtma":["turkish"],"ufuk":["turkish"],"uğrak":["turkish"],"uğur":["turkish"],"ukala":["turkish"],"ulaşım":["turkish"],"ulema":["turkish"],"ulus":["turkish"],"ulvi":["turkish"],"umursama":["turkish"],"umut":["turkish"],"unutkan":["turkish"],"uslu":["turkish"],"ustabaşı":["turkish"],"ustura":["turkish"],"usul":["turkish"],"utangaç":["turkish"],"uyanık":["turkish"],"uyarı":["turkish"],"uydu":["turkish"],"uygar":["turkish"],"uygulama":["turkish"],"uykusuz":["turkish"],"uysal":["turkish"],"uyuşma":["turkish"],"uzantı":["turkish"],"uzay":["turkish"],"uzgören":["turkish"],"uzlaşma":["turkish"],"uzman":["turkish"],"uzun":["turkish"],"ücra":["turkish"],"ücret":["turkish"],"üçbudak":["turkish"],"üçgen":["turkish"],"üçkağıt":["turkish"],"üçleme":["turkish"],"üfürük":["turkish"],"ülke":["turkish"],"ümit":["turkish"],"üniforma":["turkish"],"ünite":["turkish"],"ünlem":["turkish"],"üretken":["turkish"],"ürün":["turkish"],"üslup":["turkish"],"üstel":["turkish"],"üstün":["turkish"],"üşengeç":["turkish"],"üşüme":["turkish"],"ütopya":["turkish"],"üvey":["turkish"],"üzengi":["turkish"],"üzgün":["turkish"],"üzüm":["turkish"],"vaka":["turkish"],"vakfiye":["turkish"],"vakıf":["turkish"],"vakit":["turkish"],"vakum":["turkish"],"vapur":["turkish"],"varil":["turkish"],"varlık":["turkish"],"varsayım":["turkish"],"varyemez":["turkish"],"vasıta":["turkish"],"vasiyet":["turkish"],"vatandaş":["turkish"],"vazife":["turkish"],"vazo":["turkish"],"veciz":["turkish"],"vefa":["turkish"],"vehim":["turkish"],"veliaht":["turkish"],"veresiye":["turkish"],"verimli":["turkish"],"verkaç":["turkish"],"vernik":["turkish"],"vertigo":["turkish"],"vesait":["turkish"],"vesika":["turkish"],"vestiyer":["turkish"],"veznedar":["turkish"],"vicdan":["turkish"],"vilayet":["turkish"],"virane":["turkish"],"virgül":["turkish"],"vişne":["turkish"],"vites":["turkish"],"vokal":["turkish"],"volkan":["turkish"],"vurma":["turkish"],"vurucu":["turkish"],"vücut":["turkish"],"yabancı":["turkish"],"yabgu":["turkish"],"yağış":["turkish"],"yağlı":["turkish"],"yağmur":["turkish"],"yakamoz":["turkish"],"yakın":["turkish"],"yaklaşık":["turkish"],"yalçın":["turkish"],"yalıtım":["turkish"],"yaman":["turkish"],"yanardağ":["turkish"],"yangın":["turkish"],"yanıt":["turkish"],"yankı":["turkish"],"yanlış":["turkish"],"yansıma":["turkish"],"yapay":["turkish"],"yapboz":["turkish"],"yapımcı":["turkish"],"yaprak":["turkish"],"yaratık":["turkish"],"yarbay":["turkish"],"yardım":["turkish"],"yargıç":["turkish"],"yarıçap":["turkish"],"yasemin":["turkish"],"yastık":["turkish"],"yaşam":["turkish"],"yatak":["turkish"],"yatırım":["turkish"],"yavru":["turkish"],"yaygara":["turkish"],"yayıncı":["turkish"],"yayla":["turkish"],"yazılım":["turkish"],"yekpare":["turkish"],"yekvücut":["turkish"],"yelkovan":["turkish"],"yelpaze":["turkish"],"yemek":["turkish"],"yemiş":["turkish"],"yengeç":["turkish"],"yeniçeri":["turkish"],"yeraltı":["turkish"],"yerküre":["turkish"],"yerleşke":["turkish"],"yeryüzü":["turkish"],"yeşil":["turkish"],"yetenek":["turkish"],"yetkili":["turkish"],"yığınak":["turkish"],"yıkama":["turkish"],"yılbaşı":["turkish"],"yıldırım":["turkish"],"yılkı":["turkish"],"yılmaz":["turkish"],"yırtıcı":["turkish"],"yiğit":["turkish"],"yoğurt":["turkish"],"yokuş":["turkish"],"yolcu":["turkish"],"yoldaş":["turkish"],"yolgeçen":["turkish"],"yolkesen":["turkish"],"yolüstü":["turkish"],"yordam":["turkish"],"yorgan":["turkish"],"yorumcu":["turkish"],"yosun":["turkish"],"yöndeş":["turkish"],"yönetim":["turkish"],"yönlü":["turkish"],"yöntem":["turkish"],"yöresel":["turkish"],"yörünge":["turkish"],"yufka":["turkish"],"yukarı":["turkish"],"yumruk":["turkish"],"yumurta":["turkish"],"yuvarlak":["turkish"],"yücelme":["turkish"],"yükçeker":["turkish"],"yüklem":["turkish"],"yüksek":["turkish"],"yürek":["turkish"],"yürütme":["turkish"],"yüzde":["turkish"],"yüzeysel":["turkish"],"yüzgeç":["turkish"],"yüzüstü":["turkish"],"yüzyıl":["turkish"],"zabıta":["turkish"],"zafer":["turkish"],"zahmet":["turkish"],"zambak":["turkish"],"zaptiye":["turkish"],"zarafet":["turkish"],"zaruret":["turkish"],"zeka":["turkish"],"zekice":["turkish"],"zemberek":["turkish"],"zemin":["turkish"],"zencefil":["turkish"],"zeplin":["turkish"],"zeytin":["turkish"],"zıbın":["turkish"],"zılgıt":["turkish"],"zımbırtı":["turkish"],"zımpara":["turkish"],"zıpkın":["turkish"],"zigon":["turkish"],"zihinsel":["turkish"],"zihniyet":["turkish"],"zincir":["turkish"],"zindan":["turkish"],"zirzop":["turkish"],"ziyaret":["turkish"],"ziynet":["turkish"],"zoraki":["turkish"],"zorlu":["turkish"],"zorunlu":["turkish"],"züğürt":["turkish"],"zümre":["turkish"]}["abacate","abaixo","abalar","abater","abduzir","abelha","aberto","abismo","abotoar","abranger","abreviar","abrigar","abrupto","absinto","absoluto","absurdo","abutre","acabado","acalmar","acampar","acanhar","acaso","aceitar","acelerar","acenar","acervo","acessar","acetona","achatar","acidez","acima","acionado","acirrar","aclamar","aclive","acolhida","acomodar","acoplar","acordar","acumular","acusador","adaptar","adega","adentro","adepto","adequar","aderente","adesivo","adeus","adiante","aditivo","adjetivo","adjunto","admirar","adorar","adquirir","adubo","adverso","advogado","aeronave","afastar","aferir","afetivo","afinador","afivelar","aflito","afluente","afrontar","agachar","agarrar","agasalho","agenciar","agilizar","agiota","agitado","agora","agradar","agreste","agrupar","aguardar","agulha","ajoelhar","ajudar","ajustar","alameda","alarme","alastrar","alavanca","albergue","albino","alcatra","aldeia","alecrim","alegria","alertar","alface","alfinete","algum","alheio","aliar","alicate","alienar","alinhar","aliviar","almofada","alocar","alpiste","alterar","altitude","alucinar","alugar","aluno","alusivo","alvo","amaciar","amador","amarelo","amassar","ambas","ambiente","ameixa","amenizar","amido","amistoso","amizade","amolador","amontoar","amoroso","amostra","amparar","ampliar","ampola","anagrama","analisar","anarquia","anatomia","andaime","anel","anexo","angular","animar","anjo","anomalia","anotado","ansioso","anterior","anuidade","anunciar","anzol","apagador","apalpar","apanhado","apego","apelido","apertada","apesar","apetite","apito","aplauso","aplicada","apoio","apontar","aposta","aprendiz","aprovar","aquecer","arame","aranha","arara","arcada","ardente","areia","arejar","arenito","aresta","argiloso","argola","arma","arquivo","arraial","arrebate","arriscar","arroba","arrumar","arsenal","arterial","artigo","arvoredo","asfaltar","asilado","aspirar","assador","assinar","assoalho","assunto","astral","atacado","atadura","atalho","atarefar","atear","atender","aterro","ateu","atingir","atirador","ativo","atoleiro","atracar","atrevido","atriz","atual","atum","auditor","aumentar","aura","aurora","autismo","autoria","autuar","avaliar","avante","avaria","avental","avesso","aviador","avisar","avulso","axila","azarar","azedo","azeite","azulejo","babar","babosa","bacalhau","bacharel","bacia","bagagem","baiano","bailar","baioneta","bairro","baixista","bajular","baleia","baliza","balsa","banal","bandeira","banho","banir","banquete","barato","barbado","baronesa","barraca","barulho","baseado","bastante","batata","batedor","batida","batom","batucar","baunilha","beber","beijo","beirada","beisebol","beldade","beleza","belga","beliscar","bendito","bengala","benzer","berimbau","berlinda","berro","besouro","bexiga","bezerro","bico","bicudo","bienal","bifocal","bifurcar","bigorna","bilhete","bimestre","bimotor","biologia","biombo","biosfera","bipolar","birrento","biscoito","bisneto","bispo","bissexto","bitola","bizarro","blindado","bloco","bloquear","boato","bobagem","bocado","bocejo","bochecha","boicotar","bolada","boletim","bolha","bolo","bombeiro","bonde","boneco","bonita","borbulha","borda","boreal","borracha","bovino","boxeador","branco","brasa","braveza","breu","briga","brilho","brincar","broa","brochura","bronzear","broto","bruxo","bucha","budismo","bufar","bule","buraco","busca","busto","buzina","cabana","cabelo","cabide","cabo","cabrito","cacau","cacetada","cachorro","cacique","cadastro","cadeado","cafezal","caiaque","caipira","caixote","cajado","caju","calafrio","calcular","caldeira","calibrar","calmante","calota","camada","cambista","camisa","camomila","campanha","camuflar","canavial","cancelar","caneta","canguru","canhoto","canivete","canoa","cansado","cantar","canudo","capacho","capela","capinar","capotar","capricho","captador","capuz","caracol","carbono","cardeal","careca","carimbar","carneiro","carpete","carreira","cartaz","carvalho","casaco","casca","casebre","castelo","casulo","catarata","cativar","caule","causador","cautelar","cavalo","caverna","cebola","cedilha","cegonha","celebrar","celular","cenoura","censo","centeio","cercar","cerrado","certeiro","cerveja","cetim","cevada","chacota","chaleira","chamado","chapada","charme","chatice","chave","chefe","chegada","cheiro","cheque","chicote","chifre","chinelo","chocalho","chover","chumbo","chutar","chuva","cicatriz","ciclone","cidade","cidreira","ciente","cigana","cimento","cinto","cinza","ciranda","circuito","cirurgia","citar","clareza","clero","clicar","clone","clube","coado","coagir","cobaia","cobertor","cobrar","cocada","coelho","coentro","coeso","cogumelo","coibir","coifa","coiote","colar","coleira","colher","colidir","colmeia","colono","coluna","comando","combinar","comentar","comitiva","comover","complexo","comum","concha","condor","conectar","confuso","congelar","conhecer","conjugar","consumir","contrato","convite","cooperar","copeiro","copiador","copo","coquetel","coragem","cordial","corneta","coronha","corporal","correio","cortejo","coruja","corvo","cosseno","costela","cotonete","couro","couve","covil","cozinha","cratera","cravo","creche","credor","creme","crer","crespo","criada","criminal","crioulo","crise","criticar","crosta","crua","cruzeiro","cubano","cueca","cuidado","cujo","culatra","culminar","culpar","cultura","cumprir","cunhado","cupido","curativo","curral","cursar","curto","cuspir","custear","cutelo","damasco","datar","debater","debitar","deboche","debulhar","decalque","decimal","declive","decote","decretar","dedal","dedicado","deduzir","defesa","defumar","degelo","degrau","degustar","deitado","deixar","delator","delegado","delinear","delonga","demanda","demitir","demolido","dentista","depenado","depilar","depois","depressa","depurar","deriva","derramar","desafio","desbotar","descanso","desenho","desfiado","desgaste","desigual","deslize","desmamar","desova","despesa","destaque","desviar","detalhar","detentor","detonar","detrito","deusa","dever","devido","devotado","dezena","diagrama","dialeto","didata","difuso","digitar","dilatado","diluente","diminuir","dinastia","dinheiro","diocese","direto","discreta","disfarce","disparo","disquete","dissipar","distante","ditador","diurno","diverso","divisor","divulgar","dizer","dobrador","dolorido","domador","dominado","donativo","donzela","dormente","dorsal","dosagem","dourado","doutor","drenagem","drible","drogaria","duelar","duende","dueto","duplo","duquesa","durante","duvidoso","eclodir","ecoar","ecologia","edificar","edital","educado","efeito","efetivar","ejetar","elaborar","eleger","eleitor","elenco","elevador","eliminar","elogiar","embargo","embolado","embrulho","embutido","emenda","emergir","emissor","empatia","empenho","empinado","empolgar","emprego","empurrar","emulador","encaixe","encenado","enchente","encontro","endeusar","endossar","enfaixar","enfeite","enfim","engajado","engenho","englobar","engomado","engraxar","enguia","enjoar","enlatar","enquanto","enraizar","enrolado","enrugar","ensaio","enseada","ensino","ensopado","entanto","enteado","entidade","entortar","entrada","entulho","envergar","enviado","envolver","enxame","enxerto","enxofre","enxuto","epiderme","equipar","ereto","erguido","errata","erva","ervilha","esbanjar","esbelto","escama","escola","escrita","escuta","esfinge","esfolar","esfregar","esfumado","esgrima","esmalte","espanto","espelho","espiga","esponja","espreita","espumar","esquerda","estaca","esteira","esticar","estofado","estrela","estudo","esvaziar","etanol","etiqueta","euforia","europeu","evacuar","evaporar","evasivo","eventual","evidente","evoluir","exagero","exalar","examinar","exato","exausto","excesso","excitar","exclamar","executar","exemplo","exibir","exigente","exonerar","expandir","expelir","expirar","explanar","exposto","expresso","expulsar","externo","extinto","extrato","fabricar","fabuloso","faceta","facial","fada","fadiga","faixa","falar","falta","familiar","fandango","fanfarra","fantoche","fardado","farelo","farinha","farofa","farpa","fartura","fatia","fator","favorita","faxina","fazenda","fechado","feijoada","feirante","felino","feminino","fenda","feno","fera","feriado","ferrugem","ferver","festejar","fetal","feudal","fiapo","fibrose","ficar","ficheiro","figurado","fileira","filho","filme","filtrar","firmeza","fisgada","fissura","fita","fivela","fixador","fixo","flacidez","flamingo","flanela","flechada","flora","flutuar","fluxo","focal","focinho","fofocar","fogo","foguete","foice","folgado","folheto","forjar","formiga","forno","forte","fosco","fossa","fragata","fralda","frango","frasco","fraterno","freira","frente","fretar","frieza","friso","fritura","fronha","frustrar","fruteira","fugir","fulano","fuligem","fundar","fungo","funil","furador","furioso","futebol","gabarito","gabinete","gado","gaiato","gaiola","gaivota","galega","galho","galinha","galocha","ganhar","garagem","garfo","gargalo","garimpo","garoupa","garrafa","gasoduto","gasto","gata","gatilho","gaveta","gazela","gelado","geleia","gelo","gemada","gemer","gemido","generoso","gengiva","genial","genoma","genro","geologia","gerador","germinar","gesso","gestor","ginasta","gincana","gingado","girafa","girino","glacial","glicose","global","glorioso","goela","goiaba","golfe","golpear","gordura","gorjeta","gorro","gostoso","goteira","governar","gracejo","gradual","grafite","gralha","grampo","granada","gratuito","graveto","graxa","grego","grelhar","greve","grilo","grisalho","gritaria","grosso","grotesco","grudado","grunhido","gruta","guache","guarani","guaxinim","guerrear","guiar","guincho","guisado","gula","guloso","guru","habitar","harmonia","haste","haver","hectare","herdar","heresia","hesitar","hiato","hibernar","hidratar","hiena","hino","hipismo","hipnose","hipoteca","hoje","holofote","homem","honesto","honrado","hormonal","hospedar","humorado","iate","ideia","idoso","ignorado","igreja","iguana","ileso","ilha","iludido","iluminar","ilustrar","imagem","imediato","imenso","imersivo","iminente","imitador","imortal","impacto","impedir","implante","impor","imprensa","impune","imunizar","inalador","inapto","inativo","incenso","inchar","incidir","incluir","incolor","indeciso","indireto","indutor","ineficaz","inerente","infantil","infestar","infinito","inflamar","informal","infrator","ingerir","inibido","inicial","inimigo","injetar","inocente","inodoro","inovador","inox","inquieto","inscrito","inseto","insistir","inspetor","instalar","insulto","intacto","integral","intimar","intocado","intriga","invasor","inverno","invicto","invocar","iogurte","iraniano","ironizar","irreal","irritado","isca","isento","isolado","isqueiro","italiano","janeiro","jangada","janta","jararaca","jardim","jarro","jasmim","jato","javali","jazida","jejum","joaninha","joelhada","jogador","joia","jornal","jorrar","jovem","juba","judeu","judoca","juiz","julgador","julho","jurado","jurista","juro","justa","labareda","laboral","lacre","lactante","ladrilho","lagarta","lagoa","laje","lamber","lamentar","laminar","lampejo","lanche","lapidar","lapso","laranja","lareira","largura","lasanha","lastro","lateral","latido","lavanda","lavoura","lavrador","laxante","lazer","lealdade","lebre","legado","legendar","legista","leigo","leiloar","leitura","lembrete","leme","lenhador","lentilha","leoa","lesma","leste","letivo","letreiro","levar","leveza","levitar","liberal","libido","liderar","ligar","ligeiro","limitar","limoeiro","limpador","linda","linear","linhagem","liquidez","listagem","lisura","litoral","livro","lixa","lixeira","locador","locutor","lojista","lombo","lona","longe","lontra","lorde","lotado","loteria","loucura","lousa","louvar","luar","lucidez","lucro","luneta","lustre","lutador","luva","macaco","macete","machado","macio","madeira","madrinha","magnata","magreza","maior","mais","malandro","malha","malote","maluco","mamilo","mamoeiro","mamute","manada","mancha","mandato","manequim","manhoso","manivela","manobrar","mansa","manter","manusear","mapeado","maquinar","marcador","maresia","marfim","margem","marinho","marmita","maroto","marquise","marreco","martelo","marujo","mascote","masmorra","massagem","mastigar","matagal","materno","matinal","matutar","maxilar","medalha","medida","medusa","megafone","meiga","melancia","melhor","membro","memorial","menino","menos","mensagem","mental","merecer","mergulho","mesada","mesclar","mesmo","mesquita","mestre","metade","meteoro","metragem","mexer","mexicano","micro","migalha","migrar","milagre","milenar","milhar","mimado","minerar","minhoca","ministro","minoria","miolo","mirante","mirtilo","misturar","mocidade","moderno","modular","moeda","moer","moinho","moita","moldura","moleza","molho","molinete","molusco","montanha","moqueca","morango","morcego","mordomo","morena","mosaico","mosquete","mostarda","motel","motim","moto","motriz","muda","muito","mulata","mulher","multar","mundial","munido","muralha","murcho","muscular","museu","musical","nacional","nadador","naja","namoro","narina","narrado","nascer","nativa","natureza","navalha","navegar","navio","neblina","nebuloso","negativa","negociar","negrito","nervoso","neta","neural","nevasca","nevoeiro","ninar","ninho","nitidez","nivelar","nobreza","noite","noiva","nomear","nominal","nordeste","nortear","notar","noticiar","noturno","novelo","novilho","novo","nublado","nudez","numeral","nupcial","nutrir","nuvem","obcecado","obedecer","objetivo","obrigado","obscuro","obstetra","obter","obturar","ocidente","ocioso","ocorrer","oculista","ocupado","ofegante","ofensiva","oferenda","oficina","ofuscado","ogiva","olaria","oleoso","olhar","oliveira","ombro","omelete","omisso","omitir","ondulado","oneroso","ontem","opcional","operador","oponente","oportuno","oposto","orar","orbitar","ordem","ordinal","orfanato","orgasmo","orgulho","oriental","origem","oriundo","orla","ortodoxo","orvalho","oscilar","ossada","osso","ostentar","otimismo","ousadia","outono","outubro","ouvido","ovelha","ovular","oxidar","oxigenar","pacato","paciente","pacote","pactuar","padaria","padrinho","pagar","pagode","painel","pairar","paisagem","palavra","palestra","palheta","palito","palmada","palpitar","pancada","panela","panfleto","panqueca","pantanal","papagaio","papelada","papiro","parafina","parcial","pardal","parede","partida","pasmo","passado","pastel","patamar","patente","patinar","patrono","paulada","pausar","peculiar","pedalar","pedestre","pediatra","pedra","pegada","peitoral","peixe","pele","pelicano","penca","pendurar","peneira","penhasco","pensador","pente","perceber","perfeito","pergunta","perito","permitir","perna","perplexo","persiana","pertence","peruca","pescado","pesquisa","pessoa","petiscar","piada","picado","piedade","pigmento","pilastra","pilhado","pilotar","pimenta","pincel","pinguim","pinha","pinote","pintar","pioneiro","pipoca","piquete","piranha","pires","pirueta","piscar","pistola","pitanga","pivete","planta","plaqueta","platina","plebeu","plumagem","pluvial","pneu","poda","poeira","poetisa","polegada","policiar","poluente","polvilho","pomar","pomba","ponderar","pontaria","populoso","porta","possuir","postal","pote","poupar","pouso","povoar","praia","prancha","prato","praxe","prece","predador","prefeito","premiar","prensar","preparar","presilha","pretexto","prevenir","prezar","primata","princesa","prisma","privado","processo","produto","profeta","proibido","projeto","prometer","propagar","prosa","protetor","provador","publicar","pudim","pular","pulmonar","pulseira","punhal","punir","pupilo","pureza","puxador","quadra","quantia","quarto","quase","quebrar","queda","queijo","quente","querido","quimono","quina","quiosque","rabanada","rabisco","rachar","racionar","radial","raiar","rainha","raio","raiva","rajada","ralado","ramal","ranger","ranhura","rapadura","rapel","rapidez","raposa","raquete","raridade","rasante","rascunho","rasgar","raspador","rasteira","rasurar","ratazana","ratoeira","realeza","reanimar","reaver","rebaixar","rebelde","rebolar","recado","recente","recheio","recibo","recordar","recrutar","recuar","rede","redimir","redonda","reduzida","reenvio","refinar","refletir","refogar","refresco","refugiar","regalia","regime","regra","reinado","reitor","rejeitar","relativo","remador","remendo","remorso","renovado","reparo","repelir","repleto","repolho","represa","repudiar","requerer","resenha","resfriar","resgatar","residir","resolver","respeito","ressaca","restante","resumir","retalho","reter","retirar","retomada","retratar","revelar","revisor","revolta","riacho","rica","rigidez","rigoroso","rimar","ringue","risada","risco","risonho","robalo","rochedo","rodada","rodeio","rodovia","roedor","roleta","romano","roncar","rosado","roseira","rosto","rota","roteiro","rotina","rotular","rouco","roupa","roxo","rubro","rugido","rugoso","ruivo","rumo","rupestre","russo","sabor","saciar","sacola","sacudir","sadio","safira","saga","sagrada","saibro","salada","saleiro","salgado","saliva","salpicar","salsicha","saltar","salvador","sambar","samurai","sanar","sanfona","sangue","sanidade","sapato","sarda","sargento","sarjeta","saturar","saudade","saxofone","sazonal","secar","secular","seda","sedento","sediado","sedoso","sedutor","segmento","segredo","segundo","seiva","seleto","selvagem","semanal","semente","senador","senhor","sensual","sentado","separado","sereia","seringa","serra","servo","setembro","setor","sigilo","silhueta","silicone","simetria","simpatia","simular","sinal","sincero","singular","sinopse","sintonia","sirene","siri","situado","soberano","sobra","socorro","sogro","soja","solda","soletrar","solteiro","sombrio","sonata","sondar","sonegar","sonhador","sono","soprano","soquete","sorrir","sorteio","sossego","sotaque","soterrar","sovado","sozinho","suavizar","subida","submerso","subsolo","subtrair","sucata","sucesso","suco","sudeste","sufixo","sugador","sugerir","sujeito","sulfato","sumir","suor","superior","suplicar","suposto","suprimir","surdina","surfista","surpresa","surreal","surtir","suspiro","sustento","tabela","tablete","tabuada","tacho","tagarela","talher","talo","talvez","tamanho","tamborim","tampa","tangente","tanto","tapar","tapioca","tardio","tarefa","tarja","tarraxa","tatuagem","taurino","taxativo","taxista","teatral","tecer","tecido","teclado","tedioso","teia","teimar","telefone","telhado","tempero","tenente","tensor","tentar","termal","terno","terreno","tese","tesoura","testado","teto","textura","texugo","tiara","tigela","tijolo","timbrar","timidez","tingido","tinteiro","tiragem","titular","toalha","tocha","tolerar","tolice","tomada","tomilho","tonel","tontura","topete","tora","torcido","torneio","torque","torrada","torto","tostar","touca","toupeira","toxina","trabalho","tracejar","tradutor","trafegar","trajeto","trama","trancar","trapo","traseiro","tratador","travar","treino","tremer","trepidar","trevo","triagem","tribo","triciclo","tridente","trilogia","trindade","triplo","triturar","triunfal","trocar","trombeta","trova","trunfo","truque","tubular","tucano","tudo","tulipa","tupi","turbo","turma","turquesa","tutelar","tutorial","uivar","umbigo","unha","unidade","uniforme","urologia","urso","urtiga","urubu","usado","usina","usufruir","vacina","vadiar","vagaroso","vaidoso","vala","valente","validade","valores","vantagem","vaqueiro","varanda","vareta","varrer","vascular","vasilha","vassoura","vazar","vazio","veado","vedar","vegetar","veicular","veleiro","velhice","veludo","vencedor","vendaval","venerar","ventre","verbal","verdade","vereador","vergonha","vermelho","verniz","versar","vertente","vespa","vestido","vetorial","viaduto","viagem","viajar","viatura","vibrador","videira","vidraria","viela","viga","vigente","vigiar","vigorar","vilarejo","vinco","vinheta","vinil","violeta","virada","virtude","visitar","visto","vitral","viveiro","vizinho","voador","voar","vogal","volante","voleibol","voltagem","volumoso","vontade","vulto","vuvuzela","xadrez","xarope","xeque","xeretar","xerife","xingar","zangado","zarpar","zebu","zelador","zombar","zoologia","zumbido"]["абзац","абонент","абсурд","авангард","авария","август","авиация","автор","агент","агитация","агрегат","адвокат","адмирал","адрес","азарт","азот","академия","аквариум","аксиома","акула","акцент","акция","аллея","алмаз","алтарь","альбом","альянс","амбиция","анализ","анекдот","анкета","ансамбль","антенна","апельсин","аппарат","аппетит","апрель","аптека","арбуз","аргумент","аренда","арест","армия","аромат","арсенал","артерия","артист","архив","аспирант","асфальт","атака","атомный","атрибут","аукцион","афиша","аэропорт","бабочка","бабушка","багаж","база","бактерия","баланс","балерина","балкон","бандит","банк","барабан","барон","барышня","барьер","бассейн","батарея","башмак","башня","бедный","беженец","бездна","белка","белый","бензин","берег","беседа","бешеный","билет","бинокль","биржа","битва","благо","блеск","близкий","блин","блок","блюдо","богатый","бодрый","боец","бокал","боковой","бокс","более","болото","болтать","большой","бомба","борт","борьба","босой","ботинок","бояться","брак","брать","бревно","бред","бригада","бродяга","броня","бросить","брызги","брюки","брюхо","бугор","будка","будни","будущее","буква","букет","бульвар","бумага","бунт","бурный","буря","бутылка","бухта","бывший","быстро","бытовой","быть","бюджет","бюро","бюст","вагон","важный","вакцина","валенок","вальс","валюта","ванная","варенье","вариант","вблизи","вверх","вводить","вдали","вдвое","вдова","вдоль","вдруг","ведро","ведущий","ведьма","вежливо","везде","веко","вексель","велеть","великий","венец","веник","веранда","верблюд","верить","верный","версия","вертеть","верхний","вершина","весело","весна","весомый","вести","весь","ветеран","ветхий","вечер","вечно","вешалка","вещество","взамен","взгляд","вздох","взнос","взойти","взор","взрыв","взять","видеть","видимо","визг","визит","вилка","вина","вирус","висок","витамин","витрина","вихрь","вишня","вкус","влага","владелец","власть","влево","влияние","вложить","вместе","внешний","вникать","внимание","вновь","внук","внутри","внучка","внушать","вовлечь","вовремя","вовсю","вода","водород","водяной","воевать","возврат","возглас","воздух","возить","возле","возня","возраст","война","войско","вокзал","волос","волчий","вольный","воля","вообще","вопль","вопрос","ворота","восемь","восток","вплоть","вполне","вправе","впредь","впрочем","врач","вредный","время","вручить","всадник","всегда","вскоре","вскрыть","всплеск","вспышка","встреча","всюду","всякий","второй","вход","вчера","выбор","вывод","выгнать","выдать","выехать","вызов","выйти","выкуп","вылезти","вымыть","выпасть","выпить","выплата","выпуск","вырасти","выручка","выслать","высокий","выставка","вышка","вязать","вялый","газета","газовый","галерея","галстук","гамма","гарантия","гармония","гарнизон","гастроли","гвардия","гвоздь","гектар","генерал","гений","геном","геолог","герб","герой","гибкий","гигант","гимн","гипотеза","гитара","главный","глагол","гладить","глаз","глина","глоток","глубокий","глупый","глухой","глыба","глядеть","гнев","гнездо","гнилой","годовой","голова","голубой","голый","гонорар","гордость","горизонт","горло","горный","город","горшок","горький","горючее","горячий","готовый","градус","грамм","граница","граф","гребень","гриб","гримаса","грозить","грохот","грош","грубый","грудь","груз","грунт","группа","груша","грязный","губа","гудок","гулкий","гулять","гусеница","густо","гусь","давление","давно","даже","дальний","данный","дарить","датчик","дать","дача","двадцать","дважды","дверь","двигать","движение","двойной","двор","дебют","девятый","дежурный","действие","декабрь","деление","дело","дельфин","день","дерево","держать","дерзкий","десять","деталь","детский","дефект","дефицит","деятель","джаз","джинсы","джунгли","диагноз","диалог","диапазон","диван","дивизия","дивный","диета","дизайн","дикарь","дилер","динамика","диплом","директор","дитя","длинный","дневник","добрый","добыча","доверие","догадка","догнать","дождь","доклад","доктор","документ","долго","должен","долина","донос","дорога","досада","доска","достать","досуг","доход","доцент","дощатый","драка","древний","дремать","дробный","дрова","дрожать","другой","дружба","дубовый","дуга","думать","дурной","духи","душный","дуэль","дуэт","дыра","дыхание","дюжина","дядя","едва","единый","ерунда","если","ехать","жадный","жажда","жалеть","жалоба","жанр","жареный","жаркий","жгучий","жевать","желание","желудок","жена","женщина","жертва","жест","жидкость","житель","жить","жрец","жулик","журнал","жуткий","забрать","забыть","завести","завод","завтра","загадка","загнать","заговор","задача","задеть","задний","задолго","заехать","заказ","закон","закрыть","закуска","залезть","залить","залп","замок","замуж","замысел","занавес","заново","занять","заодно","запись","запрос","запуск","запястье","заранее","заросль","зарплата","заря","засада","заслуга","заснуть","застать","затвор","затеять","затрата","затылок","захват","зачем","защита","заявить","заяц","звезда","звено","звонить","здесь","зелень","земля","зеркало","зерно","зима","злой","змея","знамя","знание","значит","золотой","зона","зонтик","зоопарк","зрачок","зрение","зритель","зубной","зубр","игла","идеал","идеолог","идея","идол","идти","изба","избить","избрать","избыток","извлечь","извне","изгиб","изгнать","издание","изделие","изнутри","изобилие","изоляция","изредка","изрядно","изучение","изъять","изящный","икона","икра","иллюзия","именно","иметь","имидж","империя","импульс","иначе","инвалид","индекс","индивид","инерция","инженер","иногда","иной","институт","интерес","интрига","интуиция","инфаркт","инцидент","ирония","искать","испуг","история","итог","июнь","кабель","кабинет","каблук","кавалер","кадр","каждый","кажется","казино","калитка","камень","камин","канал","кандидат","каникулы","канон","капитан","капля","капот","капуста","карандаш","карета","каркас","карман","картина","карьера","каска","кассета","кастрюля","каталог","катер","каток","катушка","кафедра","качество","каша","кашлять","каюта","квадрат","квартира","квота","кепка","кивнуть","километр","кино","киоск","кипяток","кирпич","кислота","кисть","клавиша","клапан","класс","клей","клетка","клиент","климат","клиника","кличка","клоун","клочок","клуб","клумба","ключ","книга","кнопка","кнут","княгиня","князь","кобура","когда","кодекс","кожа","коктейль","колено","коллега","колонна","колпак","кольцо","колючий","коляска","команда","комедия","комиссия","коммуна","комната","комок","компания","комфорт","конвейер","конгресс","конечно","конкурс","контроль","концерт","конь","конюшня","копать","копейка","копыто","корабль","корень","корзина","коридор","кормить","корпус","космос","костюм","косяк","котел","котлета","который","коттедж","кофе","кофта","кошка","кража","край","красный","краткий","кредит","крем","крепкий","кресло","кривой","кризис","кристалл","критерий","кричать","кровь","крокодил","кролик","кроме","крона","круг","кружка","крупный","крутой","крушение","крыло","крыша","крючок","кстати","кубик","куда","кузов","кукла","кулак","кулиса","культура","кумир","купе","купить","купол","купюра","курица","курорт","курс","куртка","кусок","куст","кухня","кушать","лабиринт","лавка","лагерь","ладно","ладонь","лапа","лауреат","лгать","лебедь","левый","легенда","легкий","ледяной","лежать","лезвие","лезть","лекция","ленивый","лента","лепесток","лесной","лестница","лететь","лето","лечить","лига","лидер","лиловый","лимон","линия","липкий","лист","литр","лихой","лицо","лишить","лишний","ловить","логика","лодка","ложь","лозунг","локоть","лопата","лошадь","лукавый","луна","лучший","лысый","льгота","любить","любой","людской","люстра","лютый","лягушка","магазин","магия","майор","майский","максимум","макушка","мало","мальчик","мама","манера","марка","март","маршрут","масса","мастер","масштаб","материал","матч","махать","машина","маяк","мебель","медаль","медведь","медицина","медь","между","мелкий","мелочь","мемуары","меньше","меню","менять","мера","мерцать","место","месяц","металл","метод","метр","механизм","меховой","мечтать","мешать","мешок","миграция","микрофон","милиция","миллион","милость","миля","мимо","минерал","министр","минута","мирный","миска","миссия","митинг","мишень","младший","мнение","мнимый","много","могучий","модель","может","мозг","мокрый","молекула","молния","молодой","молчать","момент","монета","монитор","монолог","монстр","монтаж","мораль","море","морковь","мороз","морщина","мостовая","мотать","мотив","мотор","мохнатый","мрамор","мрачный","мстить","мудрый","мужество","мужчина","музей","музыка","мундир","муравей","мусор","муха","мчаться","мысль","мыться","мышца","мышь","мюзикл","мягкий","мясо","набор","навык","наглый","нагрузка","надежда","надзор","надо","наедине","назад","название","назло","наивный","найти","наконец","налево","наличие","налог","намерен","нанести","напасть","например","народ","наследие","натура","наука","наутро","начать","небо","неважно","невеста","негодяй","недавно","неделя","недолго","недра","недуг","нежный","незачем","некто","нелепый","неловко","нельзя","немало","немой","неплохо","нервный","нередко","нестись","неудача","неужели","нефть","неясный","нигде","низкий","никакой","никогда","никуда","ничто","ничуть","ниша","нищий","новость","новый","нога","ноготь","ножницы","ноздря","номер","носить","носок","ночь","ноябрь","нрав","нуль","нынче","нырять","нюанс","няня","обаяние","обед","обезьяна","обещать","обжечь","обзор","обилие","обитать","область","облик","обложка","обмен","обморок","обожать","обои","оболочка","оборона","обочина","образ","обрести","обрыв","обувь","обучение","обход","общество","общий","объект","обыск","обычно","обязать","овощи","овраг","овца","оговорка","ограда","огурец","одежда","одеяло","один","однако","одолеть","ожидать","озеро","океан","окно","около","окоп","окраина","октябрь","опасный","опека","операция","описание","оплата","опора","оппонент","оптимизм","оптовый","опухоль","опыт","оратор","орбита","орган","орден","орел","оригинал","ориентир","оркестр","оружие","осенний","осколок","осмотр","остров","отбор","отбыть","отвлечь","отдать","отдел","отдых","отель","отец","отзыв","отказ","отклик","открыть","откуда","отличие","отныне","отойти","отпуск","отрасль","отросток","отрывок","отряд","отсек","отставка","отсюда","оттенок","оттого","отчего","отъезд","офис","офицер","охота","охрана","оценка","очаг","очень","очередь","очищать","ошибка","ощущение","павильон","падать","пазуха","пакет","палата","палец","палуба","пальто","память","панель","паника","пара","парень","пароход","партия","парус","паспорт","пассажир","пастух","патент","патрон","пауза","паук","паутина","пафос","пахнуть","пациент","пачка","певец","педагог","пейзаж","пенсия","пепел","первый","перед","период","перо","перрон","персонаж","перчатка","песня","песок","петля","петрушка","петух","пехота","печать","печень","пешком","пещера","пианист","пиджак","пилот","пионер","пирамида","пирожок","письмо","пища","плавание","плакать","пламя","план","пласт","платить","пленный","плечо","плита","плод","плоский","плотный","плохой","площадь","плыть","плюс","пляж","плясать","победа","повар","повод","повсюду","повязка","погода","погреб","подбор","подвиг","подделка","поджать","поднос","подпись","подруга","подход","подчас","подъезд","поединок","поезд","поесть","поехать","пожалуй","пожилой","позади","позвать","поздний","позиция","позор","поиск","поймать","пойти","поклон","покой","покрыть","полдень","полезный","ползти","полк","полный","половина","полтора","польза","поляна","помидор","помнить","помощь","попасть","поперек","поплыть","пополам","поправка","попугай","попытка","порог","портрет","порция","порыв","порядок","после","посол","посреди","постель","посуда","потом","похвала","похожий","поцелуй","почва","почему","пошлина","поэма","поэтому","право","праздник","практика","прах","преграда","предмет","прежде","прелесть","премия","препарат","пресса","прибыть","прижать","прийти","приказ","прилавок","пример","принять","природа","притом","прихожая","прицел","причина","приют","прогноз","продукт","проект","прожить","прокат","промысел","пропуск","просто","против","профиль","процесс","прочий","прошлый","прощать","пружина","прут","прыжок","прямой","птица","публика","пугать","пуговица","пузырь","пульт","пуля","пункт","пускать","пустой","путь","пухлый","пучок","пушистый","пушка","пчела","пшеница","пылать","пыль","пышный","пьеса","пятка","пятно","пятый","пятьсот","работа","равнина","ради","радость","радуга","разбить","развитие","разговор","раздел","различие","размер","разный","разрыв","разум","район","ракета","раковина","рамка","рано","рапорт","распад","рассказ","расти","расход","расцвет","рация","рвануть","рваться","реакция","ребро","реветь","редактор","редкий","реестр","режим","резать","резерв","резина","резко","резной","рейс","реклама","рекорд","религия","рельс","ремень","ремонт","реплика","репортаж","ресница","ресторан","реформа","рецепт","речь","решение","ржавый","риск","рисунок","ритуал","рифма","робко","робот","ровесник","ровно","родной","рождение","роза","розовый","розыск","роль","роман","роскошь","роспись","рост","рубашка","рубеж","рубить","рубрика","рудник","рука","рукопись","румяный","русло","рухнуть","ручей","ручной","рыба","рыжий","рынок","рыхлый","рыцарь","рычаг","рюкзак","рядом","садовый","сажать","салон","салфетка","салют","самец","самовар","самый","сани","санкция","сапог","сарай","сатира","сахар","сбить","сбоку","сборная","сбыт","свадьба","свалка","сварить","свежий","сверху","свет","свеча","свинья","свист","свитер","свобода","сводка","свой","свыше","связь","сдаться","сделать","сегмент","сегодня","седло","седой","седьмой","сезон","сейф","сейчас","секрет","сектор","секунда","семинар","семья","сенатор","сено","сенсация","сентябрь","сервис","сердце","середина","сержант","серия","серый","сессия","сесть","сетевой","сжатый","сжечь","сзади","сигнал","сиденье","сила","силуэт","сильный","символ","симпатия","симфония","синий","синтез","синяк","сирень","система","ситуация","сияние","сказать","скала","скамейка","скандал","скатерть","скачок","скважина","сквер","сквозь","скелет","скидка","склад","сколько","скорый","скосить","скот","скрипка","скудный","скука","слабый","слава","сладкий","слегка","след","слеза","слепой","слесарь","слишком","слово","слог","сложный","сломать","служба","слух","случай","слышать","слюна","смежный","смелый","сменить","смесь","сметана","смех","смола","смуглый","смутный","смущать","смысл","снайпер","снаряд","сначала","снег","снизу","сниться","сно��а","снять","собака","соблазн","собрание","событие","совесть","совсем","согласие","создать","сознание","созреть","сойтись","сокол","солдат","соленый","солнце","солома","сомнение","сонный","соперник","соратник","сорвать","сосед","сосиска","состав","сотня","соус","союз","спад","спальня","спасти","спектр","сперва","спешить","спина","спирт","список","спичка","сплав","спонсор","спор","способ","справка","спустя","спутник","сразу","средство","срок","срыв","ссора","ссылка","ставить","стадия","стакан","станция","старый","стая","стебель","стекло","стена","степень","стереть","стиль","стимул","стирать","стихи","стоить","стойка","стол","стонать","стопа","сторона","стоянка","страна","стричь","строгий","струя","студент","стук","ступня","стыдно","суббота","субъект","сувенир","сугроб","сугубо","судить","судно","судьба","суета","суметь","сумма","сумрак","сундук","супруг","суровый","сутки","сухой","суша","существо","сфера","схема","схожий","сценарий","счастье","считать","съезд","сыграть","сырой","сытый","сыщик","сюда","сюжет","сюрприз","тайна","также","такой","такси","тактика","талия","таможня","танец","таракан","тарелка","тариф","тащить","таять","тварь","театр","тезис","текст","текущий","телефон","тема","темнота","теневой","теннис","теория","теперь","тепло","терапия","терзать","термин","терпеть","терраса","терять","тесный","тетрадь","техника","течение","тигр","типовой","тираж","титул","тихий","ткань","товарищ","тоже","толпа","толстый","толчок","толщина","только","тонкий","тонна","топить","топор","торговля","тормоз","торчать","тотчас","точка","точно","тощий","трава","традиция","трактор","трамвай","траншея","трасса","тревога","трезвый","тренер","трепет","треск","третий","трещина","трибуна","тридцать","триста","триумф","трогать","тройка","тронуть","тропа","тротуар","трубка","труд","трюк","тряпка","туго","туловище","туман","тумбочка","тундра","тупик","турист","турнир","тусклый","туфля","туча","тысяча","тяга","тяжело","убежать","убогий","уборка","уважение","увезти","уволить","угадать","угол","угощать","угроза","угрюмый","удар","удачный","уделять","удивить","удобный","удочка","уезжать","ужин","узел","узкий","уйти","указание","уклон","украсть","укусить","улетать","улица","улыбка","умело","умение","умный","умолять","унести","унижать","унылый","упаковка","упасть","упорно","упрек","урна","уровень","урожай","уронить","усадьба","усатый","усвоить","усилие","условие","услуга","усмешка","успеть","устав","устоять","утечка","утешать","утро","уцелеть","участие","ученик","учесть","ущелье","ущерб","уютный","фабрика","фаворит","факел","факт","фамилия","фантазия","фасад","февраль","феномен","фермер","фигура","физика","филиал","философ","фильм","финал","флаг","флот","фойе","фокус","фонарь","фонд","фонтан","форма","форум","фото","фрагмент","фраза","фракция","фронт","фрукт","функция","фуражка","футбол","футляр","халат","хаос","характер","хата","хвалить","хватать","хвойный","хвост","химия","хирург","хитрый","хищник","хлеб","хлынуть","хмурый","ходить","хозяин","хоккей","холм","холст","хорошо","хотеть","храбрый","храм","хранить","хребет","хрен","хрипло","хроника","хрупкий","художник","худший","хулиган","хутор","царь","цветок","целевой","целиком","целое","цель","цензура","ценить","центр","цепной","цикл","цилиндр","цирк","цитата","цифра","чайник","часы","чашка","человек","челюсть","чемодан","чемпион","чепуха","червь","чердак","через","чернила","черта","чеснок","честно","четверть","четыре","число","чистый","читатель","чтение","чтобы","чувство","чудак","чудный","чудо","чужой","чулок","чума","чушь","чуять","шагать","шанс","шапка","шарик","шарф","шахматы","шашлык","шедевр","шептать","шерсть","шестой","шинель","ширина","шишка","шкаф","школа","шкура","шланг","шлем","шнур","шоколад","шорох","шоссе","шпион","шприц","штаб","штамм","штаны","штатный","штора","штраф","штурм","штык","шумно","шуршать","шутить","шутка","щедрый","щека","щенок","экзамен","экипаж","экономия","экран","эксперт","элемент","элитный","эмоция","энергия","эпизод","эпоха","эскиз","эстрада","этап","этика","этот","эфир","эффект","эшелон","юбилей","юбка","южный","юмор","юность","юрист","юстиция","яблоко","явление","ягода","ядро","язык","яйцо","якобы","якорь","январь","яркий","ярмарка","ярость","ясный","яхта","ячейка","ящик"]["ábaco","abdomen","abeja","abierto","abogado","abono","aborto","abrazo","abrir","abuelo","abuso","acabar","academia","acceso","acción","aceite","acelga","acento","aceptar","ácido","aclarar","acné","acoger","acoso","activo","acto","actriz","actuar","acudir","acuerdo","acusar","adicto","admitir","adoptar","adorno","aduana","adulto","aéreo","afectar","afición","afinar","afirmar","ágil","agitar","agonía","agosto","agotar","agregar","agrio","agua","agudo","águila","aguja","ahogo","ahorro","aire","aislar","ajedrez","ajeno","ajuste","alacrán","alambre","alarma","alba","álbum","alcalde","aldea","alegre","alejar","alerta","aleta","alfiler","alga","algodón","aliado","aliento","alivio","alma","almeja","almíbar","altar","alteza","altivo","alto","altura","alumno","alzar","amable","amante","amapola","amargo","amasar","ámbar","ámbito","ameno","amigo","amistad","amor","amparo","amplio","ancho","anciano","ancla","andar","andén","anemia","ángulo","anillo","ánimo","anís","anotar","antena","antiguo","antojo","anual","anular","anuncio","añadir","añejo","año","apagar","aparato","apetito","apio","aplicar","apodo","aporte","apoyo","aprender","aprobar","apuesta","apuro","arado","araña","arar","árbitro","árbol","arbusto","archivo","arco","arder","ardilla","arduo","área","árido","aries","armonía","arnés","aroma","arpa","arpón","arreglo","arroz","arruga","arte","artista","asa","asado","asalto","ascenso","asegurar","aseo","asesor","asiento","asilo","asistir","asno","asombro","áspero","astilla","astro","astuto","asumir","asunto","atajo","ataque","atar","atento","ateo","ático","atleta","átomo","atraer","atroz","atún","audaz","audio","auge","aula","aumento","ausente","autor","aval","avance","avaro","ave","avellana","avena","avestruz","avión","aviso","ayer","ayuda","ayuno","azafrán","azar","azote","azúcar","azufre","azul","baba","babor","bache","bahía","baile","bajar","balanza","balcón","balde","bambú","banco","banda","baño","barba","barco","barniz","barro","báscula","bastón","basura","batalla","batería","batir","batuta","baúl","bazar","bebé","bebida","bello","besar","beso","bestia","bicho","bien","bingo","blanco","bloque","blusa","boa","bobina","bobo","boca","bocina","boda","bodega","boina","bola","bolero","bolsa","bomba","bondad","bonito","bono","bonsái","borde","borrar","bosque","bote","botín","bóveda","bozal","bravo","brazo","brecha","breve","brillo","brinco","brisa","broca","broma","bronce","brote","bruja","brusco","bruto","buceo","bucle","bueno","buey","bufanda","bufón","búho","buitre","bulto","burbuja","burla","burro","buscar","butaca","buzón","caballo","cabeza","cabina","cabra","cacao","cadáver","cadena","caer","café","caída","caimán","caja","cajón","cal","calamar","calcio","caldo","calidad","calle","calma","calor","calvo","cama","cambio","camello","camino","campo","cáncer","candil","canela","canguro","canica","canto","caña","cañón","caoba","caos","capaz","capitán","capote","captar","capucha","cara","carbón","cárcel","careta","carga","cariño","carne","carpeta","carro","carta","casa","casco","casero","caspa","castor","catorce","catre","caudal","causa","cazo","cebolla","ceder","cedro","celda","célebre","celoso","célula","cemento","ceniza","centro","cerca","cerdo","cereza","cero","cerrar","certeza","césped","cetro","chacal","chaleco","champú","chancla","chapa","charla","chico","chiste","chivo","choque","choza","chuleta","chupar","ciclón","ciego","cielo","cien","cierto","cifra","cigarro","cima","cinco","cine","cinta","ciprés","circo","ciruela","cisne","cita","ciudad","clamor","clan","claro","clase","clave","cliente","clima","clínica","cobre","cocción","cochino","cocina","coco","código","codo","cofre","coger","cohete","cojín","cojo","cola","colcha","colegio","colgar","colina","collar","colmo","columna","combate","comer","comida","cómodo","compra","conde","conejo","conga","conocer","consejo","contar","copa","copia","corazón","corbata","corcho","cordón","corona","correr","coser","cosmos","costa","cráneo","cráter","crear","crecer","creído","crema","cría","crimen","cripta","crisis","cromo","crónica","croqueta","crudo","cruz","cuadro","cuarto","cuatro","cubo","cubrir","cuchara","cuello","cuento","cuerda","cuesta","cueva","cuidar","culebra","culpa","culto","cumbre","cumplir","cuna","cuneta","cuota","cupón","cúpula","curar","curioso","curso","curva","cutis","dama","danza","dar","dardo","dátil","deber","débil","década","decir","dedo","defensa","definir","dejar","delfín","delgado","delito","demora","denso","dental","deporte","derecho","derrota","desayuno","deseo","desfile","desnudo","destino","desvío","detalle","detener","deuda","día","diablo","diadema","diamante","diana","diario","dibujo","dictar","diente","dieta","diez","difícil","digno","dilema","diluir","dinero","directo","dirigir","disco","diseño","disfraz","diva","divino","doble","doce","dolor","domingo","don","donar","dorado","dormir","dorso","dos","dosis","dragón","droga","ducha","duda","duelo","dueño","dulce","dúo","duque","durar","dureza","duro","ébano","ebrio","echar","eco","ecuador","edad","edición","edificio","editor","educar","efecto","eficaz","eje","ejemplo","elefante","elegir","elemento","elevar","elipse","élite","elixir","elogio","eludir","embudo","emitir","emoción","empate","empeño","empleo","empresa","enano","encargo","enchufe","encía","enemigo","enero","enfado","enfermo","engaño","enigma","enlace","enorme","enredo","ensayo","enseñar","entero","entrar","envase","envío","época","equipo","erizo","escala","escena","escolar","escribir","escudo","esencia","esfera","esfuerzo","espada","espejo","espía","esposa","espuma","esquí","estar","este","estilo","estufa","etapa","eterno","ética","etnia","evadir","evaluar","evento","evitar","exacto","examen","exceso","excusa","exento","exigir","exilio","existir","éxito","experto","explicar","exponer","extremo","fábrica","fábula","fachada","fácil","factor","faena","faja","falda","fallo","falso","faltar","fama","familia","famoso","faraón","farmacia","farol","farsa","fase","fatiga","fauna","favor","fax","febrero","fecha","feliz","feo","feria","feroz","fértil","fervor","festín","fiable","fianza","fiar","fibra","ficción","ficha","fideo","fiebre","fiel","fiera","fiesta","figura","fijar","fijo","fila","filete","filial","filtro","fin","finca","fingir","finito","firma","flaco","flauta","flecha","flor","flota","fluir","flujo","flúor","fobia","foca","fogata","fogón","folio","folleto","fondo","forma","forro","fortuna","forzar","fosa","foto","fracaso","frágil","franja","frase","fraude","freír","freno","fresa","frío","frito","fruta","fuego","fuente","fuerza","fuga","fumar","función","funda","furgón","furia","fusil","fútbol","futuro","gacela","gafas","gaita","gajo","gala","galería","gallo","gamba","ganar","gancho","ganga","ganso","garaje","garza","gasolina","gastar","gato","gavilán","gemelo","gemir","gen","género","genio","gente","geranio","gerente","germen","gesto","gigante","gimnasio","girar","giro","glaciar","globo","gloria","gol","golfo","goloso","golpe","goma","gordo","gorila","gorra","gota","goteo","gozar","grada","gráfico","grano","grasa","gratis","grave","grieta","grillo","gripe","gris","grito","grosor","grúa","grueso","grumo","grupo","guante","guapo","guardia","guerra","guía","guiño","guion","guiso","guitarra","gusano","gustar","haber","hábil","hablar","hacer","hacha","hada","hallar","hamaca","harina","haz","hazaña","hebilla","hebra","hecho","helado","helio","hembra","herir","hermano","héroe","hervir","hielo","hierro","hígado","higiene","hijo","himno","historia","hocico","hogar","hoguera","hoja","hombre","hongo","honor","honra","hora","hormiga","horno","hostil","hoyo","hueco","huelga","huerta","hueso","huevo","huida","huir","humano","húmedo","humilde","humo","hundir","huracán","hurto","icono","ideal","idioma","ídolo","iglesia","iglú","igual","ilegal","ilusión","imagen","imán","imitar","impar","imperio","imponer","impulso","incapaz","índice","inerte","infiel","informe","ingenio","inicio","inmenso","inmune","innato","insecto","instante","interés","íntimo","intuir","inútil","invierno","ira","iris","ironía","isla","islote","jabalí","jabón","jamón","jarabe","jardín","jarra","jaula","jazmín","jefe","jeringa","jinete","jornada","joroba","joven","joya","juerga","jueves","juez","jugador","jugo","juguete","juicio","junco","jungla","junio","juntar","júpiter","jurar","justo","juvenil","juzgar","kilo","koala","labio","lacio","lacra","lado","ladrón","lagarto","lágrima","laguna","laico","lamer","lámina","lámpara","lana","lancha","langosta","lanza","lápiz","largo","larva","lástima","lata","látex","latir","laurel","lavar","lazo","leal","lección","leche","lector","leer","legión","legumbre","lejano","lengua","lento","leña","león","leopardo","lesión","letal","letra","leve","leyenda","libertad","libro","licor","líder","lidiar","lienzo","liga","ligero","lima","límite","limón","limpio","lince","lindo","línea","lingote","lino","linterna","líquido","liso","lista","litera","litio","litro","llaga","llama","llanto","llave","llegar","llenar","llevar","llorar","llover","lluvia","lobo","loción","loco","locura","lógica","logro","lombriz","lomo","lonja","lote","lucha","lucir","lugar","lujo","luna","lunes","lupa","lustro","luto","luz","maceta","macho","madera","madre","maduro","maestro","mafia","magia","mago","maíz","maldad","maleta","malla","malo","mamá","mambo","mamut","manco","mando","manejar","manga","maniquí","manjar","mano","manso","manta","mañana","mapa","máquina","mar","marco","marea","marfil","margen","marido","mármol","marrón","martes","marzo","masa","máscara","masivo","matar","materia","matiz","matriz","máximo","mayor","mazorca","mecha","medalla","medio","médula","mejilla","mejor","melena","melón","memoria","menor","mensaje","mente","menú","mercado","merengue","mérito","mes","mesón","meta","meter","método","metro","mezcla","miedo","miel","miembro","miga","mil","milagro","militar","millón","mimo","mina","minero","mínimo","minuto","miope","mirar","misa","miseria","misil","mismo","mitad","mito","mochila","moción","moda","modelo","moho","mojar","molde","moler","molino","momento","momia","monarca","moneda","monja","monto","moño","morada","morder","moreno","morir","morro","morsa","mortal","mosca","mostrar","motivo","mover","móvil","mozo","mucho","mudar","mueble","muela","muerte","muestra","mugre","mujer","mula","muleta","multa","mundo","muñeca","mural","muro","músculo","museo","musgo","música","muslo","nácar","nación","nadar","naipe","naranja","nariz","narrar","nasal","natal","nativo","natural","náusea","naval","nave","navidad","necio","néctar","negar","negocio","negro","neón","nervio","neto","neutro","nevar","nevera","nicho","nido","niebla","nieto","niñez","niño","nítido","nivel","nobleza","noche","nómina","noria","norma","norte","nota","noticia","novato","novela","novio","nube","nuca","núcleo","nudillo","nudo","nuera","nueve","nuez","nulo","número","nutria","oasis","obeso","obispo","objeto","obra","obrero","observar","obtener","obvio","oca","ocaso","océano","ochenta","ocho","ocio","ocre","octavo","octubre","oculto","ocupar","ocurrir","odiar","odio","odisea","oeste","ofensa","oferta","oficio","ofrecer","ogro","oído","oír","ojo","ola","oleada","olfato","olivo","olla","olmo","olor","olvido","ombligo","onda","onza","opaco","opción","ópera","opinar","oponer","optar","óptica","opuesto","oración","orador","oral","órbita","orca","orden","oreja","órgano","orgía","orgullo","oriente","origen","orilla","oro","orquesta","oruga","osadía","oscuro","osezno","oso","ostra","otoño","otro","oveja","óvulo","óxido","oxígeno","oyente","ozono","pacto","padre","paella","página","pago","país","pájaro","palabra","palco","paleta","pálido","palma","paloma","palpar","pan","panal","pánico","pantera","pañuelo","papá","papel","papilla","paquete","parar","parcela","pared","parir","paro","párpado","parque","párrafo","parte","pasar","paseo","pasión","paso","pasta","pata","patio","patria","pausa","pauta","pavo","payaso","peatón","pecado","pecera","pecho","pedal","pedir","pegar","peine","pelar","peldaño","pelea","peligro","pellejo","pelo","peluca","pena","pensar","peñón","peón","peor","pepino","pequeño","pera","percha","perder","pereza","perfil","perico","perla","permiso","perro","persona","pesa","pesca","pésimo","pestaña","pétalo","petróleo","pez","pezuña","picar","pichón","pie","piedra","pierna","pieza","pijama","pilar","piloto","pimienta","pino","pintor","pinza","piña","piojo","pipa","pirata","pisar","piscina","piso","pista","pitón","pizca","placa","plan","plata","playa","plaza","pleito","pleno","plomo","pluma","plural","pobre","poco","poder","podio","poema","poesía","poeta","polen","policía","pollo","polvo","pomada","pomelo","pomo","pompa","poner","porción","portal","posada","poseer","posible","poste","potencia","potro","pozo","prado","precoz","pregunta","premio","prensa","preso","previo","primo","príncipe","prisión","privar","proa","probar","proceso","producto","proeza","profesor","programa","prole","promesa","pronto","propio","próximo","prueba","público","puchero","pudor","pueblo","puerta","puesto","pulga","pulir","pulmón","pulpo","pulso","puma","punto","puñal","puño","pupa","pupila","puré","quedar","queja","quemar","querer","queso","quieto","química","quince","quitar","rábano","rabia","rabo","ración","radical","raíz","rama","rampa","rancho","rango","rapaz","rápido","rapto","rasgo","raspa","rato","rayo","raza","razón","reacción","realidad","rebaño","rebote","recaer","receta","rechazo","recoger","recreo","recto","recurso","red","redondo","reducir","reflejo","reforma","refrán","refugio","regalo","regir","regla","regreso","rehén","reino","reír","reja","relato","relevo","relieve","relleno","reloj","remar","remedio","remo","rencor","rendir","renta","reparto","repetir","reposo","reptil","res","rescate","resina","respeto","resto","resumen","retiro","retorno","retrato","reunir","revés","revista","rey","rezar","rico","riego","rienda","riesgo","rifa","rígido","rigor","rincón","riñón","río","riqueza","risa","ritmo","rito","rizo","roble","roce","rociar","rodar","rodeo","rodilla","roer","rojizo","rojo","romero","romper","ron","ronco","ronda","ropa","ropero","rosa","rosca","rostro","rotar","rubí","rubor","rudo","rueda","rugir","ruido","ruina","ruleta","rulo","rumbo","rumor","ruptura","ruta","rutina","sábado","saber","sabio","sable","sacar","sagaz","sagrado","sala","saldo","salero","salir","salmón","salón","salsa","salto","salud","salvar","samba","sanción","sandía","sanear","sangre","sanidad","sano","santo","sapo","saque","sardina","sartén","sastre","satán","sauna","saxofón","sección","seco","secreto","secta","sed","seguir","seis","sello","selva","semana","semilla","senda","sensor","señal","señor","separar","sepia","sequía","ser","serie","sermón","servir","sesenta","sesión","seta","setenta","severo","sexo","sexto","sidra","siesta","siete","siglo","signo","sílaba","silbar","silencio","silla","símbolo","simio","sirena","sistema","sitio","situar","sobre","socio","sodio","sol","solapa","soldado","soledad","sólido","soltar","solución","sombra","sondeo","sonido","sonoro","sonrisa","sopa","soplar","soporte","sordo","sorpresa","sorteo","sostén","sótano","suave","subir","suceso","sudor","suegra","suelo","sueño","suerte","sufrir","sujeto","sultán","sumar","superar","suplir","suponer","supremo","sur","surco","sureño","surgir","susto","sutil","tabaco","tabique","tabla","tabú","taco","tacto","tajo","talar","talco","talento","talla","talón","tamaño","tambor","tango","tanque","tapa","tapete","tapia","tapón","taquilla","tarde","tarea","tarifa","tarjeta","tarot","tarro","tarta","tatuaje","tauro","taza","tazón","teatro","techo","tecla","técnica","tejado","tejer","tejido","tela","teléfono","tema","temor","templo","tenaz","tender","tener","tenis","tenso","teoría","terapia","terco","término","ternura","terror","tesis","tesoro","testigo","tetera","texto","tez","tibio","tiburón","tiempo","tienda","tierra","tieso","tigre","tijera","tilde","timbre","tímido","timo","tinta","tío","típico","tipo","tira","tirón","titán","títere","título","tiza","toalla","tobillo","tocar","tocino","todo","toga","toldo","tomar","tono","tonto","topar","tope","toque","tórax","torero","tormenta","torneo","toro","torpedo","torre","torso","tortuga","tos","tosco","toser","tóxico","trabajo","tractor","traer","tráfico","trago","traje","tramo","trance","trato","trauma","trazar","trébol","tregua","treinta","tren","trepar","tres","tribu","trigo","tripa","triste","triunfo","trofeo","trompa","tronco","tropa","trote","trozo","truco","trueno","trufa","tubería","tubo","tuerto","tumba","tumor","túnel","túnica","turbina","turismo","turno","tutor","ubicar","úlcera","umbral","unidad","unir","universo","uno","untar","uña","urbano","urbe","urgente","urna","usar","usuario","útil","utopía","uva","vaca","vacío","vacuna","vagar","vago","vaina","vajilla","vale","válido","valle","valor","válvula","vampiro","vara","variar","varón","vaso","vecino","vector","vehículo","veinte","vejez","vela","velero","veloz","vena","vencer","venda","veneno","vengar","venir","venta","venus","ver","verano","verbo","verde","vereda","verja","verso","verter","vía","viaje","vibrar","vicio","víctima","vida","vídeo","vidrio","viejo","viernes","vigor","vil","villa","vinagre","vino","viñedo","violín","viral","virgo","virtud","visor","víspera","vista","vitamina","viudo","vivaz","vivero","vivir","vivo","volcán","volumen","volver","voraz","votar","voto","voz","vuelo","vulgar","yacer","yate","yegua","yema","yerno","yeso","yodo","yoga","yogur","zafiro","zanja","zapato","zarza","zona","zorro","zumo","zurdo"]["abajur","abaküs","abartı","abdal","abdest","abiye","abluka","abone","absorbe","absürt","acayip","acele","acemi","açıkgöz","adalet","adam","adezyon","adisyon","adliye","adres","afacan","afili","afiş","afiyet","aforizm","afra","ağaç","ağır","ahbap","ahkam","ahlak","ahtapot","aidat","aile","ajan","akademi","akarsu","akbaş","akciğer","akdeniz","akıbet","akıl","akıntı","akide","akrep","akrobasi","aksiyon","akşam","aktif","aktör","aktris","akustik","alaca","albüm","alçak","aldanma","aleni","alet","alfabe","algılama","alıngan","alkış","alkol","alpay","alperen","altın","altüst","altyapı","alyuvar","amade","amatör","amazon","ambalaj","amblem","ambulans","amca","amel","amigo","amir","amiyane","amorti","ampul","anadolu","anahtar","anakonda","anaokul","anapara","anarşi","anatomi","anayasa","anekdot","anestezi","angaje","anka","anket","anlamlı","anne","anomali","anonim","anten","antlaşma","apse","araba","aracı","araf","arbede","arda","arefe","arena","argo","argüman","arkadaş","armoni","aroma","arsa","arsız","artı","artist","aruz","asansör","asayiş","asfalt","asgari","asil","asker","askı","aslan","asosyal","astsubay","asya","aşçı","aşırı","aşure","atabey","ataman","ateş","atmaca","atmosfer","atom","atölye","avcı","avdet","avize","avlu","avokado","avrupa","avukat","ayaz","ayçiçeği","aydın","aygıt","ayna","ayran","ayrıntı","azim","baca","bagaj","bağlantı","bahadır","bahçe","baki","bakkal","baklava","bakteri","balçık","balina","balo","balta","bant","banyo","bardak","barış","başbuğ","başıboş","başkan","başlık","bavul","bayındır","baykuş","bazlama","bedel","begüm","bekçi","bekle","belge","belki","bencil","benek","bengi","benzer","berjer","berk","bermuda","berrak","beşik","beton","beyin","beyoğlu","bıçak","biberiye","bidon","biftek","bihaber","bikini","bilezik","bilinç","bilye","bina","binbaşı","binyıl","bisiklet","bisküvi","bitki","bizzat","bodrum","boğaz","bohça","bolero","boncuk","bonfile","borsa","boru","bostan","boşboğaz","botanik","boya","boykot","boynuz","bozgun","bozkır","bölüm","börek","buçuk","bugün","buğday","buhar","buhran","bulvar","buram","burçak","burs","burun","butik","buzdağı","buzkıran","bücür","büfe","bülten","bütçe","bütün","büyük","cacık","cadı","cahil","cambaz","canhıraş","casus","cazibe","cehalet","cehennem","ceket","cemre","cenin","cennet","cepken","cerrah","cesur","cetvel","cevher","ceylan","cılız","cıva","cilt","cisim","ciyak","coğrafya","cömert","cumba","cüzdan","çabucak","çadır","çağdaş","çağlayan","çağrı","çakmak","çalışkan","çamaşır","çapa","çaput","çarık","çarpan","çarşaf","çayhane","çekirdek","çelebi","çember","çenet","çengel","çerçeve","çerez","çeşit","çeşme","çete","çevre","çeyiz","çeyrek","çığır","çılgın","çıngırak","çift","çiğdem","çikolata","çilek","çimen","çivi","çoban","çocuk","çokgen","çomak","çorba","çözelti","çubuk","çukur","çuval","çürük","dağbaşı","dağılım","daktilo","daldırış","dalga","dalkavuk","damak","damıtma","damla","dana","dandik","danışman","daniska","dantel","dargeçit","darphane","davet","dayı","defter","değer","değirmen","dehşet","delgeç","demir","deneyim","denge","depo","deprem","derdest","dere","derhal","derman","dernek","derviş","desen","destan","dışarı","dışbükey","dijital","dikbaşlı","dilekçe","dimağ","dinamik","dindar","dinleme","dinozor","dipçik","dipnot","direniş","dirsek","disiplin","disk","divriği","dizüstü","dobra","dodurga","doğalgaz","doktor","doküman","dolap","donanım","dondurma","donör","doruk","dosdoğru","dost","dosya","dozer","döküm","dönence","dörtyol","dövme","dram","dublaj","durum","duvak","duyarga","duyma","duyuru","düğme","düğüm","dükkan","dünür","düpedüz","dürbün","düşünür","düzayak","düzeltme","ebeveyn","ebru","ecel","ecnebi","ecza","edat","edilgen","efendi","efor","efsane","egemen","egzersiz","eğrelti","ekarte","ekip","eklem","ekmek","ekol","ekonomi","ekose","ekran","ekvator","elaman","elastik","elbet","elbise","elçi","eldiven","elebaşı","eleştiri","elma","eloğlu","elveda","emare","emekçi","emisyon","emniyet","empati","emsal","emzik","endüstri","enerji","engebe","engin","enişte","enkaz","entari","entegre","entrika","enzim","erdem","ergen","erguvan","erkek","erozyon","ertesi","erzak","esaret","esenlik","eser","eski","esnek","eşarp","eşofman","eşraf","eşya","eşzaman","etik","etken","etkinlik","etüt","evet","evire","evrak","evrim","eyalet","eyvah","ezber","fabrika","fanatik","fanus","fason","fasulye","fatih","fatura","fauna","favori","fayans","fayton","fazıl","fazilet","federal","felsefe","fener","feribot","fersah","fesih","festival","feveran","feza","fıçı","fıldır","fındık","fırça","fırsat","fırtına","fıtık","fidan","fidye","figür","fihrist","fikir","fildişi","filo","filtre","fincan","firuze","fitil","fiyaka","fizik","flaş","flüt","fosil","fren","fukara","futbol","garabet","gariban","garnitür","gazi","gece","gedik","gelenek","gelin","gemi","genç","geniş","geometri","gerçek","gevrek","gezegen","gezgin","geziyolu","gıcık","gıda","gıybet","girdap","girişim","gitar","giyecek","giysi","gizem","gofret","goril","göbek","göçebe","göğüs","gökdelen","gökmen","gökyüzü","gölge","gömlek","gönül","görenek","görkemli","görsel","gösteri","gövde","gözaltı","gözcü","gözdağı","gözleme","gözyaşı","grup","gurbet","gusül","gübre","güfte","gümüş","günaydın","güncel","gündüz","güneş","günyüzü","gürbüz","güvercin","güzel","haber","hacamat","hacim","hademe","hafız","hafriyat","hafta","hakan","hakem","hakikat","haksever","halı","hançer","hane","hangar","hapis","hapşırık","harf","haseki","hasret","hatun","havuç","haylaz","haysiyet","hayvan","hedef","hektar","hemen","hemfikir","hendek","hepsi","hergele","herhangi","hesap","heyecan","heykel","hezimet","hıçkırık","hızölçer","hicviye","hikaye","hikmet","hile","hisse","hobi","hoca","horlama","hormon","hoşbeş","hoşgörü","hoyrat","hörgüç","höyük","hudut","hukuk","hunhar","hurda","huysuz","huzur","hücum","hükümet","hünkar","hüviyet","ırmak","ısıölçer","ısıtıcı","ıspanak","ısrar","ışıldak","ızdırap","ızgara","ibadet","icat","içbükey","içecek","içgüdü","içsel","idman","iftihar","iğne","ihanet","ihbar","ihdas","ihmal","ihracat","ihsan","ikilem","ikindi","ikircik","iklim","iksir","iktibas","ilaç","ilçe","ileri","iletişim","ilgi","ilhak","ilkbahar","ilkokul","ilmek","imkan","imleç","imsak","imtihan","imza","ince","inkar","inşa","ipek","ipucu","irade","irfan","irmik","isabet","iskele","israf","isyan","işçi","işgal","işgüzar","işlem","itibar","itiraf","ivedi","ivme","iyileşme","iyimser","izbandut","izci","izdiham","izin","jakoben","jandarma","jargon","kabadayı","kablo","kabus","kaçamak","kadeh","kadın","kadraj","kafa","kafkas","kağıt","kağnı","kahkaha","kahraman","kahvaltı","kakül","kaldırım","kale","kalibre","kalkan","kalpak","kamış","kamyon","kanat","kandaş","kanepe","kanser","kanun","kaos","kapı","kaplıca","kaptan","karanlık","kardeş","karga","karınca","karmaşa","karşıt","kasırga","kask","kasvet","katkı","katman","kavram","kaygan","kaynakça","kayyum","kedi","kehanet","kekik","kelebek","kenar","kerkenez","kerpiç","kesirli","kesmece","kestane","keşkek","ketçap","keyfiyet","kıble","kıdemli","kılavuz","kılçık","kılıf","kıraç","kırmızı","kırsal","kısayol","kısım","kıskanç","kısmet","kışla","kıvanç","kıvılcım","kıvrık","kıyafet","kıymetli","kızak","kızılcık","kibar","kinaye","kira","kiremit","kirli","kirpik","kişisel","kitap","koçbaşı","kodaman","koğuş","kokteyl","kolaycı","kolbastı","kolonya","koltuk","kolye","kombine","komedyen","komiser","komposto","komşu","komuta","konak","konfor","koni","konsül","kopya","korkusuz","korna","korse","korunak","korvet","kostüm","koşul","koyu","kozmik","köfte","kökensel","köprücük","köpük","kördüğüm","körfez","köstebek","köşegen","kötü","kravat","kriter","kuantum","kudurma","kuluçka","kulübe","kumanya","kumbara","kumlu","kumpir","kumral","kundura","kupa","kupkuru","kuramsal","kurbağa","kurdele","kurgu","kurmay","kurşun","kurtuluş","kurultay","kurye","kusursuz","kuşak","kuşbaşı","kuşkulu","kutlama","kutsal","kutup","kuver","kuyruk","kuzey","kuzgun","küçük","külçe","külfet","külliye","kültürel","kümes","künefe","küresel","kütle","lahana","lahmacun","lamba","lansman","lavaş","layık","leğen","levent","leziz","lezzet","lider","likide","liman","liste","litre","liyakat","lodos","lokanta","lokman","lokum","lunapark","lütfen","lüzum","nokta","mabet","macera","macun","madalya","madde","madem","mağara","mağdur","mağfiret","mağlup","mahalle","mahcup","mahir","mahkeme","mahlas","mahrum","mahsul","makas","makbuz","makine","makro","maksat","makul","maliye","manav","mangal","manidar","manken","mantık","manzara","mareşal","margarin","marifet","market","marmelat","masaüstü","masmavi","masraf","masum","matah","materyal","matrak","maval","mavra","maydanoz","mayhoş","maytap","mazbata","mazeret","mazlum","mazot","mazur","meblağ","mebus","mecaz","mecbur","meclis","mecmua","mecnun","meçhul","medeni","mehtap","mekanik","melodi","meltem","memur","mendil","menekşe","menteşe","meraklı","mercek","merdiven","merhaba","merinos","merkez","mermi","mert","mesafe","mesele","mesken","meslek","meşale","meşgul","meşhur","metafor","metin","metre","mevcut","mevkidaş","meydan","meyil","meyve","meziyet","mezun","mıknatıs","mısra","mızıka","miğfer","mihrak","mikrofon","miktar","milat","milli","mimar","minare","mineral","minik","minyon","mirliva","misafir","miskin","miting","miyop","mizah","mobilya","model","monitör","morötesi","motive","motor","mozaik","muavin","mucize","muhafız","muhteşem","mukayese","mumya","musluk","muşamba","mutabık","mutfak","mutlu","muzaffer","muzdarip","mübarek","mücadele","müdür","müfredat","müftü","mühendis","mühim","mühlet","mükemmel","mülk","mümkün","mümtaz","müsrif","müstesna","müşahit","müşteri","mütercim","müthiş","müze","müzik","nabız","nadas","nadir","nahoş","nakarat","nakış","nalbur","namlu","namus","nankör","nargile","narkoz","nasıl","nasip","naylon","nazar","nazım","nazik","neden","nefes","negatif","neon","neptün","nerede","nesil","nesnel","neşeli","netice","nevresim","neyse","neyzen","nezaket","nezih","nezle","nicel","nilüfer","nimet","nisan","nispet","nitekim","nizam","nohut","noksan","normal","nostalji","noter","nöbet","numara","numune","nutuk","nüfus","obabaşı","obez","obje","ocak","odun","ofansif","ofis","oğlak","oğuz","okçu","oklava","oksijen","okul","okumuş","okutman","okuyucu","okyanus","olağan","olanak","olası","olay","olgun","olimpik","olumlu","omlet","omurga","onarım","onursal","opera","optik","oral","orantı","ordu","organik","orijin","orkide","orman","orta","oruç","otağ","otantik","otel","otoban","otogar","otomobil","otonom","otopark","otorite","otoyol","oturum","oyuk","oyuncak","ozan","ödeme","ödenek","ödev","ödül","ödünç","öfke","öğlen","öğrenci","öğün","öğütücü","öksürük","ölçme","ölçü","ölümsüz","ömür","önayak","öncü","önder","önem","önerge","öngörü","önlük","önsezi","öpücük","ördek","örgü","örtbas","örtme","örtü","örümcek","örüntü","öteberi","öteki","övünç","öykü","öyleyse","özçekim","özdeyiş","özel","özenti","özerk","özgürlük","özlem","özlü","özne","özsever","özümseme","özür","özveri","pabuç","padişah","palamut","palmiye","palto","palyaço","pamuk","panayır","pancar","panda","panel","panik","panjur","pankart","pano","pansuman","pantolon","panzehir","papatya","papyon","paraşüt","parça","pardösü","parfüm","parıltı","parkur","parmak","parodi","parsel","partner","pasaport","pasif","paskalya","pastırma","paşa","patates","paten","patika","patlıcan","patolog","patron","payanda","paydaş","payidar","paylaşma","paytak","peçete","pedal","peder","pehlivan","pekala","pekmez","pelerin","pelikan","pelüş","pembe","pena","pencere","pense","perçin","perde","pergel","perişan","peron","personel","perşembe","peruk","pervane","pespaye","pestil","peşin","petek","petrol","petunya","peynir","peyzaj","pınar","pırasa","pırlanta","pide","pikap","piknik","pilav","piliç","pilot","pipet","pipo","piramit","pirinç","pirzola","pist","pişik","pişman","piyasa","piyes","plaj","plaket","planlama","platform","plazma","podyum","poğaça","polat","polen","politika","pompa","popüler","porselen","portakal","posa","poster","poşet","poyraz","pozitif","pranga","pratik","prenses","prim","problem","profil","program","proje","protokol","prova","puan","pudra","pusula","püre","pürüz","püstül","püsür","racon","radar","radikal","radyo","rafadan","rafine","rağbet","rahat","rahle","rakam","raket","rakip","rakun","ralli","rampa","randevu","ranza","rapor","rastgele","rasyonel","razı","realite","reçine","refah","referans","refik","reform","rehber","rehin","reis","rekabet","reklam","rekor","rektör","renk","resim","resmen","restoran","retorik","revaç","revize","reyon","rezalet","rezerv","rezil","rıhtım","rıza","ritim","ritüel","rivayet","robot","roman","rota","rozet","röportaj","rötar","ruble","ruhban","ruhsat","rulet","rulo","runik","rutin","rutubet","rüşvet","rütbe","rüya","rüzgar","sabah","sabıka","sabit","sabun","saçma","sade","sadık","safahat","safdil","safkan","sağanak","sağduyu","sağlam","saha","sahiden","sahne","sakal","sakız","sakin","saklama","saksağan","salamura","salça","salgı","salınım","salkım","salon","saltanat","sanatçı","sancak","sandalye","saniye","saplantı","sapsız","saray","sarışın","sarkık","sarmaşık","satır","savaşım","savunma","saydam","sayfa","saygın","sayısal","sebep","seçenek","seçim","seçkin","seçmen","seda","sedir","sedye","sefer","sehpa","sekizgen","selektör","selvi","semavi","sembol","seminer","senaryo","sendika","senkron","sensör","sentez","sepet","seramik","serbest","serdar","seremoni","sergi","serhat","serin","sermaye","serpuş","sersem","serüven","servis","sesli","sesteş","sevap","seviye","seyahat","seyirci","sezon","sıcak","sıfat","sıhhi","sınanma","sınır","sıradan","sırdaş","sırma","sırtüstü","sızgıt","siftah","sigorta","sihirbaz","silah","silecek","silindir","simetri","simge","simit","sincap","sindirim","sinema","sinirli","sipariş","sirke","siroz","sistem","sivilce","siyasi","slogan","soba","sofra","soğuk","sohbet","sokak","solfej","solunum","somut","sonbahar","sonraki","sonsuz","sorunsuz","sosyete","soyağacı","soydaş","soygun","soytarı","söğüş","sömürge","sönük","söylem","sözcük","sözde","spatula","spektrum","spiker","spiral","sponsor","sporcu","sprey","stabil","statü","stok","stopaj","strateji","subay","sucuk","suçüstü","suhulet","sulama","sungur","sunucu","surat","susam","suskun","sükse","sükut","sülale","sünger","süpürge","sürahi","süreç","sürgün","sürüm","süsleme","sütanne","sütlaç","sütun","süvari","şahane","şahbaz","şahit","şahsiyet","şakıma","şaklaban","şakrak","şamar","şampiyon","şanslı","şantiye","şapka","şarkıcı","şartname","şaşırma","şaşkın","şatafat","şayet","şebeke","şefkat","şeftali","şehir","şehvet","şeker","şekil","şelale","şema","şemsiye","şerbet","şeref","şerit","şımarık","şıpıdık","şifre","şimdi","şimşek","şipşak","şirin","şişe","şişirme","şofben","şöhret","şölen","şüphe","tabaka","tabela","tabure","tadilat","taharet","tahıl","tahkim","tahlil","tahmin","tahrifat","tahsilat","tahta","taklit","takoz","taksici","taktik","takvim","talebe","talip","tamamen","tamirci","tampon","tamtakır","tandır","tanecik","tanıtım","tanrı","tansiyon","tapan","tapınak","taptaze","tapu","tarafgir","tarhana","tarım","tarih","tarla","tartak","tarumar","tasarım","tasdik","taslak","tastamam","taşeron","taşınmaz","taşra","tatava","tatbikat","tatil","tatlı","tavsiye","tavşan","tavuk","taze","taziye","tazminat","tebeşir","tebrik","tecrübe","teçhizat","tedarik","tedbir","teftiş","teğet","teğmen","tehdit","tehlike","tekdüze","tekerlek","tekme","teknik","tekrar","telef","telsiz","telve","temas","tembel","temiz","temkin","tempo","temsilci","tendon","teneke","tenha","tenkit","tepegöz","tepki","terazi","terbiye","tercih","tereyağı","terfi","terim","terminal","tersane","tertip","tesadüf","tescil","tesir","teslimat","tespit","testere","teşekkür","teşhir","teşrif","teşvik","teyze","tezahür","tezgah","tıbbi","tıkaç","tıkışık","tıknaz","tılsım","tıpkı","tıraş","tırışka","tırmanış","tırnak","tırpan","tıslama","ticaret","tilki","tiryaki","titreşim","tohum","tokat","tolere","tomar","tombak","tomurcuk","topaç","toplum","toprak","toptan","toraman","torpido","tortu","tosbağa","toynak","tören","trafik","trajedi","tramvay","transfer","tribün","triko","tugay","tuğla","tuğrul","tuhaf","tulumba","tunç","turan","turkuaz","turnusol","turşu","turuncu","tutanak","tutkal","tutsak","tutum","tuyuğ","tuzlu","tüccar","tüfek","tükenmez","tülbent","tümleç","tünel","türbin","türev","türk","tüzük","ucube","ucuz","uçak","uçurtma","ufuk","uğrak","uğur","ukala","ulaşım","ulema","ulus","ulvi","umursama","umut","unutkan","uslu","ustabaşı","ustura","usul","utangaç","uyanık","uyarı","uydu","uygar","uygulama","uykusuz","uysal","uyuşma","uzantı","uzay","uzgören","uzlaşma","uzman","uzun","ücra","ücret","üçbudak","üçgen","üçkağıt","üçleme","üfürük","ülke","ümit","üniforma","ünite","ünlem","üretken","ürün","üslup","üstel","üstün","üşengeç","üşüme","ütopya","üvey","üzengi","üzgün","üzüm","vagon","vaka","vakfiye","vakıf","vakit","vakum","vapur","varil","varlık","varsayım","varyemez","vasıta","vasiyet","vatandaş","vazife","vazo","veciz","vefa","vehim","veliaht","veresiye","verimli","verkaç","vernik","vertigo","vesait","vesika","vestiyer","veznedar","vicdan","vilayet","virane","virgül","vişne","vites","vokal","volkan","vurma","vurucu","vücut","yabancı","yabgu","yağış","yağlı","yağmur","yakamoz","yakın","yaklaşık","yalçın","yalıtım","yaman","yanardağ","yangın","yanıt","yankı","yanlış","yansıma","yapay","yapboz","yapımcı","yaprak","yaratık","yarbay","yardım","yargıç","yarıçap","yasemin","yastık","yaşam","yatak","yatırım","yavru","yaygara","yayıncı","yayla","yazılım","yekpare","yekvücut","yelkovan","yelpaze","yemek","yemiş","yengeç","yeniçeri","yeraltı","yerküre","yerleşke","yeryüzü","yeşil","yetenek","yetkili","yığınak","yıkama","yılbaşı","yıldırım","yılkı","yılmaz","yırtıcı","yiğit","yoğurt","yokuş","yolcu","yoldaş","yolgeçen","yolkesen","yolüstü","yordam","yorgan","yorumcu","yosun","yöndeş","yönetim","yönlü","yöntem","yöresel","yörünge","yufka","yukarı","yumruk","yumurta","yuvarlak","yücelme","yükçeker","yüklem","yüksek","yürek","yürütme","yüzde","yüzeysel","yüzgeç","yüzüstü","yüzyıl","zabıta","zafer","zahmet","zambak","zaptiye","zarafet","zaruret","zeka","zekice","zemberek","zemin","zencefil","zeplin","zeytin","zıbın","zılgıt","zımbırtı","zımpara","zıpkın","zigon","zihinsel","zihniyet","zincir","zindan","zirzop","ziyaret","ziynet","zoraki","zorlu","zorunlu","züğürt","zümre"]import { encode, encodeInto, objectToTokens, rfc8949EncodeOptions } from './lib/encode.js'
import { decode, decodeFirst, Tokeniser, tokensToObject } from './lib/decode.js'
import { Tagged } from './lib/tagged.js'
import { Token, Type } from './lib/token.js'

/**
 * Export the types that were present in the original manual cborg.d.ts
 * @typedef {import('./interface.js').TagDecodeControl} TagDecodeControl
 * @typedef {import('./interface.js').TagDecoder} TagDecoder
 * There was originally just `TypeEncoder` so don't break types by renaming or not exporting
 * @typedef {import('./interface.js').OptionalTypeEncoder} TypeEncoder
 * @typedef {import('./interface.js').DecodeOptions} DecodeOptions
 * @typedef {import('./interface.js').EncodeOptions} EncodeOptions
 */

export {
  decode,
  decodeFirst,
  Tokeniser as Tokenizer,
  tokensToObject,
  encode,
  encodeInto,
  objectToTokens,
  rfc8949EncodeOptions,
  Tagged,
  Token,
  Type
}
/* globals BigInt */

import { Token, Type } from './token.js'
import { decodeErrPrefix, assertEnoughData } from './common.js'

export const uintBoundaries = [24, 256, 65536, 4294967296, BigInt('18446744073709551616')]

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number}
 */
export function readUint8 (data, offset, options) {
  assertEnoughData(data, offset, 1)
  const value = data[offset]
  if (options.strict === true && value < uintBoundaries[0]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  return value
}

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number}
 */
export function readUint16 (data, offset, options) {
  assertEnoughData(data, offset, 2)
  const value = (data[offset] << 8) | data[offset + 1]
  if (options.strict === true && value < uintBoundaries[1]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  return value
}

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number}
 */
export function readUint32 (data, offset, options) {
  assertEnoughData(data, offset, 4)
  const value = (data[offset] * 16777216 /* 2 ** 24 */) + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]
  if (options.strict === true && value < uintBoundaries[2]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  return value
}

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number|bigint}
 */
export function readUint64 (data, offset, options) {
  // assume BigInt, convert back to Number if within safe range
  assertEnoughData(data, offset, 8)
  const hi = (data[offset] * 16777216 /* 2 ** 24 */) + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]
  const lo = (data[offset + 4] * 16777216 /* 2 ** 24 */) + (data[offset + 5] << 16) + (data[offset + 6] << 8) + data[offset + 7]
  const value = (BigInt(hi) << BigInt(32)) + BigInt(lo)
  if (options.strict === true && value < uintBoundaries[3]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  if (value <= Number.MAX_SAFE_INTEGER) {
    return Number(value)
  }
  if (options.allowBigInt === true) {
    return value
  }
  throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`)
}

/* not required thanks to quick[] list
const oneByteTokens = new Array(24).fill(0).map((v, i) => new Token(Type.uint, i, 1))
export function decodeUintCompact (data, pos, minor, options) {
  return oneByteTokens[minor]
}
*/

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint8 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint8(data, pos + 1, options), 2)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint16 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint16(data, pos + 1, options), 3)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint32 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint32(data, pos + 1, options), 5)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint64 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint64(data, pos + 1, options), 9)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeUint (writer, token) {
  return encodeUintValue(writer, 0, token.value)
}

/**
 * @param {ByteWriter} writer
 * @param {number} major
 * @param {number|bigint} uint
 */
export function encodeUintValue (writer, major, uint) {
  if (uint < uintBoundaries[0]) {
    const nuint = Number(uint)
    // pack into one byte, minor=0, additional=value
    writer.push([major | nuint])
  } else if (uint < uintBoundaries[1]) {
    const nuint = Number(uint)
    // pack into two byte, minor=0, additional=24
    writer.push([major | 24, nuint])
  } else if (uint < uintBoundaries[2]) {
    const nuint = Number(uint)
    // pack into three byte, minor=0, additional=25
    writer.push([major | 25, nuint >>> 8, nuint & 0xff])
  } else if (uint < uintBoundaries[3]) {
    const nuint = Number(uint)
    // pack into five byte, minor=0, additional=26
    writer.push([major | 26, (nuint >>> 24) & 0xff, (nuint >>> 16) & 0xff, (nuint >>> 8) & 0xff, nuint & 0xff])
  } else {
    const buint = BigInt(uint)
    if (buint < uintBoundaries[4]) {
      // pack into nine byte, minor=0, additional=27
      const set = [major | 27, 0, 0, 0, 0, 0, 0, 0]
      // simulate bitwise above 32 bits
      let lo = Number(buint & BigInt(0xffffffff))
      let hi = Number(buint >> BigInt(32) & BigInt(0xffffffff))
      set[8] = lo & 0xff
      lo = lo >> 8
      set[7] = lo & 0xff
      lo = lo >> 8
      set[6] = lo & 0xff
      lo = lo >> 8
      set[5] = lo & 0xff
      set[4] = hi & 0xff
      hi = hi >> 8
      set[3] = hi & 0xff
      hi = hi >> 8
      set[2] = hi & 0xff
      hi = hi >> 8
      set[1] = hi & 0xff
      writer.push(set)
    } else {
      throw new Error(`${decodeErrPrefix} encountered BigInt larger than allowable range`)
    }
  }
}

/**
 * @param {Token} token
 * @returns {number}
 */
encodeUint.encodedSize = function encodedSize (token) {
  return encodeUintValue.encodedSize(token.value)
}

/**
 * @param {number} uint
 * @returns {number}
 */
encodeUintValue.encodedSize = function encodedSize (uint) {
  if (uint < uintBoundaries[0]) {
    return 1
  }
  if (uint < uintBoundaries[1]) {
    return 2
  }
  if (uint < uintBoundaries[2]) {
    return 3
  }
  if (uint < uintBoundaries[3]) {
    return 5
  }
  return 9
}

/**
 * @param {Token} tok1
 * @param {Token} tok2
 * @returns {number}
 */
encodeUint.compareTokens = function compareTokens (tok1, tok2) {
  return tok1.value < tok2.value ? -1 : tok1.value > tok2.value ? 1 : 0
}
/* eslint-env es2020 */

import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import { decodeErrPrefix } from './common.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint8 (data, pos, _minor, options) {
  return new Token(Type.negint, -1 - uint.readUint8(data, pos + 1, options), 2)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint16 (data, pos, _minor, options) {
  return new Token(Type.negint, -1 - uint.readUint16(data, pos + 1, options), 3)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint32 (data, pos, _minor, options) {
  return new Token(Type.negint, -1 - uint.readUint32(data, pos + 1, options), 5)
}

const neg1b = BigInt(-1)
const pos1b = BigInt(1)

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint64 (data, pos, _minor, options) {
  const int = uint.readUint64(data, pos + 1, options)
  if (typeof int !== 'bigint') {
    const value = -1 - int
    if (value >= Number.MIN_SAFE_INTEGER) {
      return new Token(Type.negint, value, 9)
    }
  }
  if (options.allowBigInt !== true) {
    throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`)
  }
  return new Token(Type.negint, neg1b - BigInt(int), 9)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeNegint (writer, token) {
  const negint = token.value
  const unsigned = (typeof negint === 'bigint' ? (negint * neg1b - pos1b) : (negint * -1 - 1))
  uint.encodeUintValue(writer, token.type.majorEncoded, unsigned)
}

/**
 * @param {Token} token
 * @returns {number}
 */
encodeNegint.encodedSize = function encodedSize (token) {
  const negint = token.value
  const unsigned = (typeof negint === 'bigint' ? (negint * neg1b - pos1b) : (negint * -1 - 1))
  // handled by quickEncode, we shouldn't get here but it's included for completeness
  if (unsigned < uint.uintBoundaries[0]) {
    return 1
  }
  if (unsigned < uint.uintBoundaries[1]) {
    return 2
  }
  if (unsigned < uint.uintBoundaries[2]) {
    return 3
  }
  if (unsigned < uint.uintBoundaries[3]) {
    return 5
  }
  return 9
}

/**
 * @param {Token} tok1
 * @param {Token} tok2
 * @returns {number}
 */
encodeNegint.compareTokens = function compareTokens (tok1, tok2) {
  // opposite of the uint comparison since we store the uint version in bytes
  return tok1.value < tok2.value ? 1 : tok1.value > tok2.value ? -1 : 0
}
import { Token, Type } from './token.js'
import { assertEnoughData, decodeErrPrefix } from './common.js'
import * as uint from './0uint.js'
import { compare, fromString } from './byte-utils.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} prefix
 * @param {number} length
 * @returns {Token}
 */
function toToken (data, pos, prefix, length) {
  assertEnoughData(data, pos, prefix + length)
  const buf = data.slice(pos + prefix, pos + prefix + length)
  return new Token(Type.bytes, buf, prefix + length)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeBytesCompact (data, pos, minor, _options) {
  return toToken(data, pos, 1, minor)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer bytes lengths not supported`)
  }
  return toToken(data, pos, 9, l)
}

/**
 * `encodedBytes` allows for caching when we do a byte version of a string
 * for key sorting purposes
 * @param {Token} token
 * @returns {Uint8Array}
 */
function tokenBytes (token) {
  if (token.encodedBytes === undefined) {
    token.encodedBytes = Type.equals(token.type, Type.string) ? fromString(token.value) : token.value
  }
  // @ts-ignore c'mon
  return token.encodedBytes
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeBytes (writer, token) {
  const bytes = tokenBytes(token)
  uint.encodeUintValue(writer, token.type.majorEncoded, bytes.length)
  writer.push(bytes)
}

/**
 * @param {Token} token
 * @returns {number}
 */
encodeBytes.encodedSize = function encodedSize (token) {
  const bytes = tokenBytes(token)
  return uint.encodeUintValue.encodedSize(bytes.length) + bytes.length
}

/**
 * @param {Token} tok1
 * @param {Token} tok2
 * @returns {number}
 */
encodeBytes.compareTokens = function compareTokens (tok1, tok2) {
  return compareBytes(tokenBytes(tok1), tokenBytes(tok2))
}

/**
 * @param {Uint8Array} b1
 * @param {Uint8Array} b2
 * @returns {number}
 */
export function compareBytes (b1, b2) {
  return b1.length < b2.length ? -1 : b1.length > b2.length ? 1 : compare(b1, b2)
}
import { Token, Type } from './token.js'
import { assertEnoughData, decodeErrPrefix } from './common.js'
import * as uint from './0uint.js'
import { encodeBytes } from './2bytes.js'

const textDecoder = new TextDecoder()

// Threshold for ASCII fast-path vs TextDecoder. Short ASCII strings (common for
// map keys) are faster to decode with a simple loop than TextDecoder overhead.
const ASCII_THRESHOLD = 32

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * Decode UTF-8 bytes to string. For short ASCII strings (common case for map keys),
 * a simple loop is faster than TextDecoder.
 * @param {Uint8Array} bytes
 * @param {number} start
 * @param {number} end
 * @returns {string}
 */
function toStr (bytes, start, end) {
  const len = end - start
  if (len < ASCII_THRESHOLD) {
    let str = ''
    for (let i = start; i < end; i++) {
      const c = bytes[i]
      if (c & 0x80) { // non-ASCII, fall back to TextDecoder
        return textDecoder.decode(bytes.subarray(start, end))
      }
      str += String.fromCharCode(c)
    }
    return str
  }
  return textDecoder.decode(bytes.subarray(start, end))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} prefix
 * @param {number} length
 * @param {DecodeOptions} options
 * @returns {Token}
 */
function toToken (data, pos, prefix, length, options) {
  const totLength = prefix + length
  assertEnoughData(data, pos, totLength)
  const tok = new Token(Type.string, toStr(data, pos + prefix, pos + totLength), totLength)
  if (options.retainStringBytes === true) {
    tok.byteValue = data.slice(pos + prefix, pos + totLength)
  }
  return tok
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeStringCompact (data, pos, minor, options) {
  return toToken(data, pos, 1, minor, options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options), options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options), options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options), options)
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer string lengths not supported`)
  }
  return toToken(data, pos, 9, l, options)
}

export const encodeString = encodeBytes
import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import { decodeErrPrefix } from './common.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} prefix
 * @param {number} length
 * @returns {Token}
 */
function toToken (_data, _pos, prefix, length) {
  return new Token(Type.array, length, prefix)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeArrayCompact (data, pos, minor, _options) {
  return toToken(data, pos, 1, minor)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer array lengths not supported`)
  }
  return toToken(data, pos, 9, l)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArrayIndefinite (data, pos, _minor, options) {
  if (options.allowIndefinite === false) {
    throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)
  }
  return toToken(data, pos, 1, Infinity)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeArray (writer, token) {
  uint.encodeUintValue(writer, Type.array.majorEncoded, token.value)
}

// using an array as a map key, are you sure about this? we can only sort
// by map length here, it's up to the encoder to decide to look deeper
encodeArray.compareTokens = uint.encodeUint.compareTokens

/**
 * @param {Token} token
 * @returns {number}
 */
encodeArray.encodedSize = function encodedSize (token) {
  return uint.encodeUintValue.encodedSize(token.value)
}
import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import { decodeErrPrefix } from './common.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} prefix
 * @param {number} length
 * @returns {Token}
 */
function toToken (_data, _pos, prefix, length) {
  return new Token(Type.map, length, prefix)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeMapCompact (data, pos, minor, _options) {
  return toToken(data, pos, 1, minor)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer map lengths not supported`)
  }
  return toToken(data, pos, 9, l)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMapIndefinite (data, pos, _minor, options) {
  if (options.allowIndefinite === false) {
    throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)
  }
  return toToken(data, pos, 1, Infinity)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeMap (writer, token) {
  uint.encodeUintValue(writer, Type.map.majorEncoded, token.value)
}

// using a map as a map key, are you sure about this? we can only sort
// by map length here, it's up to the encoder to decide to look deeper
encodeMap.compareTokens = uint.encodeUint.compareTokens

/**
 * @param {Token} token
 * @returns {number}
 */
encodeMap.encodedSize = function encodedSize (token) {
  return uint.encodeUintValue.encodedSize(token.value)
}
import { Token, Type } from './token.js'
import * as uint from './0uint.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeTagCompact (_data, _pos, minor, _options) {
  return new Token(Type.tag, minor, 1)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag8 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint8(data, pos + 1, options), 2)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag16 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint16(data, pos + 1, options), 3)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag32 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint32(data, pos + 1, options), 5)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag64 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint64(data, pos + 1, options), 9)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeTag (writer, token) {
  uint.encodeUintValue(writer, Type.tag.majorEncoded, token.value)
}

encodeTag.compareTokens = uint.encodeUint.compareTokens

/**
 * @param {Token} token
 * @returns {number}
 */
encodeTag.encodedSize = function encodedSize (token) {
  return uint.encodeUintValue.encodedSize(token.value)
}
// TODO: shift some of the bytes logic to bytes-utils so we can use Buffer
// where possible

import { Token, Type } from './token.js'
import { decodeErrPrefix } from './common.js'
import { encodeUint } from './0uint.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 * @typedef {import('../interface.js').EncodeOptions} EncodeOptions
 */

export const MINOR_FALSE = 20
export const MINOR_TRUE = 21
export const MINOR_NULL = 22
export const MINOR_UNDEFINED = 23

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUndefined (_data, _pos, _minor, options) {
  if (options.allowUndefined === false) {
    throw new Error(`${decodeErrPrefix} undefined values are not supported`)
  } else if (options.coerceUndefinedToNull === true) {
    return new Token(Type.null, null, 1)
  }
  return new Token(Type.undefined, undefined, 1)
}

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBreak (_data, _pos, _minor, options) {
  if (options.allowIndefinite === false) {
    throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)
  }
  return new Token(Type.break, undefined, 1)
}

/**
 * @param {number} value
 * @param {number} bytes
 * @param {DecodeOptions} options
 * @returns {Token}
 */
function createToken (value, bytes, options) {
  if (options) {
    if (options.allowNaN === false && Number.isNaN(value)) {
      throw new Error(`${decodeErrPrefix} NaN values are not supported`)
    }
    if (options.allowInfinity === false && (value === Infinity || value === -Infinity)) {
      throw new Error(`${decodeErrPrefix} Infinity values are not supported`)
    }
  }
  return new Token(Type.float, value, bytes)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeFloat16 (data, pos, _minor, options) {
  return createToken(readFloat16(data, pos + 1), 3, options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeFloat32 (data, pos, _minor, options) {
  return createToken(readFloat32(data, pos + 1), 5, options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeFloat64 (data, pos, _minor, options) {
  return createToken(readFloat64(data, pos + 1), 9, options)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 * @param {EncodeOptions} options
 */
export function encodeFloat (writer, token, options) {
  const float = token.value

  if (float === false) {
    writer.push([Type.float.majorEncoded | MINOR_FALSE])
  } else if (float === true) {
    writer.push([Type.float.majorEncoded | MINOR_TRUE])
  } else if (float === null) {
    writer.push([Type.float.majorEncoded | MINOR_NULL])
  } else if (float === undefined) {
    writer.push([Type.float.majorEncoded | MINOR_UNDEFINED])
  } else {
    let decoded
    let success = false
    if (!options || options.float64 !== true) {
      encodeFloat16(float)
      decoded = readFloat16(ui8a, 1)
      if (float === decoded || Number.isNaN(float)) {
        ui8a[0] = 0xf9
        writer.push(ui8a.slice(0, 3))
        success = true
      } else {
        encodeFloat32(float)
        decoded = readFloat32(ui8a, 1)
        if (float === decoded) {
          ui8a[0] = 0xfa
          writer.push(ui8a.slice(0, 5))
          success = true
        }
      }
    }
    if (!success) {
      encodeFloat64(float)
      decoded = readFloat64(ui8a, 1)
      ui8a[0] = 0xfb
      writer.push(ui8a.slice(0, 9))
    }
  }
}

/**
 * @param {Token} token
 * @param {EncodeOptions} options
 * @returns {number}
 */
encodeFloat.encodedSize = function encodedSize (token, options) {
  const float = token.value

  if (float === false || float === true || float === null || float === undefined) {
    return 1
  }

  if (!options || options.float64 !== true) {
    encodeFloat16(float)
    let decoded = readFloat16(ui8a, 1)
    if (float === decoded || Number.isNaN(float)) {
      return 3
    }
    encodeFloat32(float)
    decoded = readFloat32(ui8a, 1)
    if (float === decoded) {
      return 5
    }
  }
  return 9
}

const buffer = new ArrayBuffer(9)
const dataView = new DataView(buffer, 1)
const ui8a = new Uint8Array(buffer, 0)

/**
 * @param {number} inp
 */
function encodeFloat16 (inp) {
  if (inp === Infinity) {
    dataView.setUint16(0, 0x7c00, false)
  } else if (inp === -Infinity) {
    dataView.setUint16(0, 0xfc00, false)
  } else if (Number.isNaN(inp)) {
    dataView.setUint16(0, 0x7e00, false)
  } else {
    dataView.setFloat32(0, inp)
    const valu32 = dataView.getUint32(0)
    const exponent = (valu32 & 0x7f800000) >> 23
    const mantissa = valu32 & 0x7fffff

    if (exponent === 0xff) {
      // too big, Infinity, but this should be hard (impossible?) to trigger
      dataView.setUint16(0, 0x7c00, false)
    } else if (exponent === 0x00) {
      // 0.0, -0.0 and subnormals, shouldn't be possible to get here because 0.0 should be counted as an int
      // Use valu32 for sign bit since bitwise ops on floats lose -0 sign
      dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | (mantissa >> 13), false)
    } else { // standard numbers
      // chunks of logic here borrowed from https://github.com/PJK/libcbor/blob/c78f437182533e3efa8d963ff4b945bb635c2284/src/cbor/encoding.c#L127
      const logicalExponent = exponent - 127
      // Now we know that 2^exponent <= 0 logically
      if (logicalExponent < -24) {
        /* No unambiguous representation exists, this float is not a half float
          and is too small to be represented using a half, round off to zero.
          Consistent with the reference implementation. */
        // should be difficult (impossible?) to get here in JS
        dataView.setUint16(0, 0)
      } else if (logicalExponent < -14) {
        /* Offset the remaining decimal places by shifting the significand, the
          value is lost. This is an implementation decision that works around the
          absence of standard half-float in the language. */
        dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | /* sign bit */ (1 << (24 + logicalExponent)), false)
      } else {
        dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | ((logicalExponent + 15) << 10) | (mantissa >> 13), false)
      }
    }
  }
}

/**
 * @param {Uint8Array} ui8a
 * @param {number} pos
 * @returns {number}
 */
function readFloat16 (ui8a, pos) {
  if (ui8a.length - pos < 2) {
    throw new Error(`${decodeErrPrefix} not enough data for float16`)
  }

  const half = (ui8a[pos] << 8) + ui8a[pos + 1]
  if (half === 0x7c00) {
    return Infinity
  }
  if (half === 0xfc00) {
    return -Infinity
  }
  if (half === 0x7e00) {
    return NaN
  }
  const exp = (half >> 10) & 0x1f
  const mant = half & 0x3ff
  let val
  if (exp === 0) {
    val = mant * (2 ** -24)
  } else if (exp !== 31) {
    val = (mant + 1024) * (2 ** (exp - 25))
  } else {
    // may not be possible to get here
    val = mant === 0 ? Infinity : NaN
  }
  return (half & 0x8000) ? -val : val
}

/**
 * @param {number} inp
 */
function encodeFloat32 (inp) {
  dataView.setFloat32(0, inp, false)
}

/**
 * @param {Uint8Array} ui8a
 * @param {number} pos
 * @returns {number}
 */
function readFloat32 (ui8a, pos) {
  if (ui8a.length - pos < 4) {
    throw new Error(`${decodeErrPrefix} not enough data for float32`)
  }
  const offset = (ui8a.byteOffset || 0) + pos
  return new DataView(ui8a.buffer, offset, 4).getFloat32(0, false)
}

/**
 * @param {number} inp
 */
function encodeFloat64 (inp) {
  dataView.setFloat64(0, inp, false)
}

/**
 * @param {Uint8Array} ui8a
 * @param {number} pos
 * @returns {number}
 */
function readFloat64 (ui8a, pos) {
  if (ui8a.length - pos < 8) {
    throw new Error(`${decodeErrPrefix} not enough data for float64`)
  }
  const offset = (ui8a.byteOffset || 0) + pos
  return new DataView(ui8a.buffer, offset, 8).getFloat64(0, false)
}

/**
 * @param {Token} _tok1
 * @param {Token} _tok2
 * @returns {number}
 */
encodeFloat.compareTokens = encodeUint.compareTokens
/*
encodeFloat.compareTokens = function compareTokens (_tok1, _tok2) {
  return _tok1
  throw new Error(`${encodeErrPrefix} cannot use floats as map keys`)
}
*/
/**
 * Bl is a list of byte chunks, similar to https://github.com/rvagg/bl but for
 * writing rather than reading.
 * A Bl object accepts set() operations for individual bytes and copyTo() for
 * inserting byte arrays. These write operations don't automatically increment
 * the internal cursor so its "length" won't be changed. Instead, increment()
 * must be called to extend its length to cover the inserted data.
 * The toBytes() call will convert all internal memory to a single Uint8Array of
 * the correct length, truncating any data that is stored but hasn't been
 * included by an increment().
 * get() can retrieve a single byte.
 * All operations (except toBytes()) take an "offset" argument that will perform
 * the write at the offset _from the current cursor_. For most operations this
 * will be `0` to write at the current cursor position but it can be ahead of
 * the current cursor. Negative offsets probably work but are untested.
 */

// TODO: ipjs doesn't support this, only for test files: https://github.com/mikeal/ipjs/blob/master/src/package/testFile.js#L39
import { alloc, concat, slice } from './byte-utils.js'

// the ts-ignores in this file are almost all for the `Uint8Array|number[]` duality that exists
// for perf reasons. Consider better approaches to this or removing it entirely, it is quite
// risky because of some assumptions about small chunks === number[] and everything else === Uint8Array.

const defaultChunkSize = 256

export class Bl {
  /**
   * @param {number} [chunkSize]
   */
  constructor (chunkSize = defaultChunkSize) {
    this.chunkSize = chunkSize
    /** @type {number} */
    this.cursor = 0
    /** @type {number} */
    this.maxCursor = -1
    /** @type {(Uint8Array|number[])[]} */
    this.chunks = []
    // keep the first chunk around if we can to save allocations for future encodes
    /** @type {Uint8Array|number[]|null} */
    this._initReuseChunk = null
  }

  reset () {
    this.cursor = 0
    this.maxCursor = -1
    if (this.chunks.length) {
      this.chunks = []
    }
    if (this._initReuseChunk !== null) {
      this.chunks.push(this._initReuseChunk)
      this.maxCursor = this._initReuseChunk.length - 1
    }
  }

  /**
   * @param {Uint8Array|number[]} bytes
   */
  push (bytes) {
    let topChunk = this.chunks[this.chunks.length - 1]
    const newMax = this.cursor + bytes.length
    if (newMax <= this.maxCursor + 1) {
      // we have at least one chunk and we can fit these bytes into that chunk
      const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1
      // @ts-ignore
      topChunk.set(bytes, chunkPos)
    } else {
      // can't fit it in
      if (topChunk) {
        // trip the last chunk to `cursor` if we need to
        const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1
        if (chunkPos < topChunk.length) {
          // @ts-ignore
          this.chunks[this.chunks.length - 1] = topChunk.subarray(0, chunkPos)
          this.maxCursor = this.cursor - 1
        }
      }
      if (bytes.length < 64 && bytes.length < this.chunkSize) {
        // make a new chunk and copy the new one into it
        topChunk = alloc(this.chunkSize)
        this.chunks.push(topChunk)
        this.maxCursor += topChunk.length
        if (this._initReuseChunk === null) {
          this._initReuseChunk = topChunk
        }
        // @ts-ignore
        topChunk.set(bytes, 0)
      } else {
        // push the new bytes in as its own chunk
        this.chunks.push(bytes)
        this.maxCursor += bytes.length
      }
    }
    this.cursor += bytes.length
  }

  /**
   * @param {boolean} [reset]
   * @returns {Uint8Array}
   */
  toBytes (reset = false) {
    let byts
    if (this.chunks.length === 1) {
      const chunk = this.chunks[0]
      if (reset && this.cursor > chunk.length / 2) {
        // @ts-ignore
        byts = this.cursor === chunk.length ? chunk : chunk.subarray(0, this.cursor)
        this._initReuseChunk = null
        this.chunks = []
      } else {
        // @ts-ignore
        byts = slice(chunk, 0, this.cursor)
      }
    } else {
      // @ts-ignore
      byts = concat(this.chunks, this.cursor)
    }
    if (reset) {
      this.reset()
    }
    return byts
  }
}

/**
 * U8Bl is a buffer list that writes directly to a user-provided Uint8Array.
 * It provides the same interface as Bl but writes to a fixed destination.
 */
export class U8Bl {
  /**
   * @param {Uint8Array} dest
   */
  constructor (dest) {
    this.dest = dest
    /** @type {number} */
    this.cursor = 0
    // chunks is for interface compatibility with Bl - encode.js checks chunks.length
    // as a sanity check for pre-calculated sizes. For U8Bl this is always [dest].
    /** @type {Uint8Array[]} */
    this.chunks = [dest]
  }

  reset () {
    this.cursor = 0
  }

  /**
   * @param {Uint8Array|number[]} bytes
   */
  push (bytes) {
    if (this.cursor + bytes.length > this.dest.length) {
      throw new Error('write out of bounds, destination buffer is too small')
    }
    this.dest.set(bytes, this.cursor)
    this.cursor += bytes.length
  }

  /**
   * @param {boolean} [reset]
   * @returns {Uint8Array}
   */
  toBytes (reset = false) {
    const byts = this.dest.subarray(0, this.cursor)
    if (reset) {
      this.reset()
    }
    return byts
  }
}
// Use Uint8Array directly in the browser, use Buffer in Node.js but don't
// speak its name directly to avoid bundlers pulling in the `Buffer` polyfill

// @ts-ignore
export const useBuffer = globalThis.process &&
  // @ts-ignore
  !globalThis.process.browser &&
  // @ts-ignore
  globalThis.Buffer &&
  // @ts-ignore
  typeof globalThis.Buffer.isBuffer === 'function'

const textEncoder = new TextEncoder()

/**
 * @param {Uint8Array} buf
 * @returns {boolean}
 */
function isBuffer (buf) {
  // @ts-ignore
  return useBuffer && globalThis.Buffer.isBuffer(buf)
}

/**
 * @param {Uint8Array|number[]} buf
 * @returns {Uint8Array}
 */
export function asU8A (buf) {
  if (!(buf instanceof Uint8Array)) {
    return Uint8Array.from(buf)
  }
  return isBuffer(buf) ? new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength) : buf
}

// Threshold for manual UTF-8 encoding vs native methods.
// Node.js Buffer.from: crossover ~24 chars
// Browser TextEncoder: crossover ~200 chars
const FROM_STRING_THRESHOLD_BUFFER = 24
const FROM_STRING_THRESHOLD_TEXTENCODER = 200

export const fromString = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {string} string
     */
    (string) => {
      return string.length >= FROM_STRING_THRESHOLD_BUFFER
        ? // eslint-disable-line operator-linebreak
      // @ts-ignore
        globalThis.Buffer.from(string)
        : utf8ToBytes(string)
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {string} string
     */
    (string) => {
      return string.length >= FROM_STRING_THRESHOLD_TEXTENCODER ? textEncoder.encode(string) : utf8ToBytes(string)
    }

/**
 * Buffer variant not fast enough for what we need
 * @param {number[]} arr
 * @returns {Uint8Array}
 */
export const fromArray = (arr) => {
  return Uint8Array.from(arr)
}

export const slice = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} bytes
     * @param {number} start
     * @param {number} end
     */
    // Buffer.slice() returns a view, not a copy, so we need special handling
    (bytes, start, end) => {
      if (isBuffer(bytes)) {
        return new Uint8Array(bytes.subarray(start, end))
      }
      return bytes.slice(start, end)
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} bytes
     * @param {number} start
     * @param {number} end
     */
    (bytes, start, end) => {
      return bytes.slice(start, end)
    }

export const concat = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array[]} chunks
     * @param {number} length
     * @returns {Uint8Array}
     */
    (chunks, length) => {
      // might get a stray plain Array here
      chunks = chunks.map((c) => c instanceof Uint8Array
        ? c
        : // eslint-disable-line operator-linebreak
        // @ts-ignore
        globalThis.Buffer.from(c))
      // @ts-ignore
      return asU8A(globalThis.Buffer.concat(chunks, length))
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array[]} chunks
     * @param {number} length
     * @returns {Uint8Array}
     */
    (chunks, length) => {
      const out = new Uint8Array(length)
      let off = 0
      for (let b of chunks) {
        if (off + b.length > out.length) {
          // final chunk that's bigger than we need
          b = b.subarray(0, out.length - off)
        }
        out.set(b, off)
        off += b.length
      }
      return out
    }

export const alloc = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {number} size
     * @returns {Uint8Array}
     */
    (size) => {
      // we always write over the contents we expose so this should be safe
      // @ts-ignore
      return globalThis.Buffer.allocUnsafe(size)
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {number} size
     * @returns {Uint8Array}
     */
    (size) => {
      return new Uint8Array(size)
    }

export const toHex = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} d
     * @returns {string}
     */
    (d) => {
      if (typeof d === 'string') {
        return d
      }
      // @ts-ignore
      return globalThis.Buffer.from(toBytes(d)).toString('hex')
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} d
     * @returns {string}
     */
    (d) => {
      if (typeof d === 'string') {
        return d
      }
      // @ts-ignore not smart enough to figure this out
      return Array.prototype.reduce.call(toBytes(d), (p, c) => `${p}${c.toString(16).padStart(2, '0')}`, '')
    }

export const fromHex = useBuffer
  ? // eslint-disable-line operator-linebreak
  /**
   * @param {string|Uint8Array} hex
   * @returns {Uint8Array}
   */
    (hex) => {
      if (hex instanceof Uint8Array) {
        return hex
      }
      // @ts-ignore
      return globalThis.Buffer.from(hex, 'hex')
    }
  : // eslint-disable-line operator-linebreak
  /**
   * @param {string|Uint8Array} hex
   * @returns {Uint8Array}
   */
    (hex) => {
      if (hex instanceof Uint8Array) {
        return hex
      }
      if (!hex.length) {
        return new Uint8Array(0)
      }
      return new Uint8Array(hex.split('')
        .map((/** @type {string} */ c, /** @type {number} */ i, /** @type {string[]} */ d) => i % 2 === 0 ? `0x${c}${d[i + 1]}` : '')
        .filter(Boolean)
        .map((/** @type {string} */ e) => parseInt(e, 16)))
    }

/**
 * @param {Uint8Array|ArrayBuffer|ArrayBufferView} obj
 * @returns {Uint8Array}
 */
function toBytes (obj) {
  if (obj instanceof Uint8Array && obj.constructor.name === 'Uint8Array') {
    return obj
  }
  if (obj instanceof ArrayBuffer) {
    return new Uint8Array(obj)
  }
  if (ArrayBuffer.isView(obj)) {
    return new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength)
  }
  throw new Error('Unknown type, must be binary type')
}

/**
 * @param {Uint8Array} b1
 * @param {Uint8Array} b2
 * @returns {number}
 */
export function compare (b1, b2) {
  if (isBuffer(b1) && isBuffer(b2)) {
    // probably not possible to get here in the current API
    // @ts-ignore Buffer
    return b1.compare(b2)
  }
  for (let i = 0; i < b1.length; i++) {
    if (b1[i] === b2[i]) {
      continue
    }
    return b1[i] < b2[i] ? -1 : 1
  }
  return 0
}

// The below code is taken from https://github.com/google/closure-library/blob/8598d87242af59aac233270742c8984e2b2bdbe0/closure/goog/crypt/crypt.js#L117-L143
// Licensed Apache-2.0.

/**
 * @param {string} str
 * @returns {number[]}
 */
function utf8ToBytes (str) {
  const out = []
  let p = 0
  for (let i = 0; i < str.length; i++) {
    let c = str.charCodeAt(i)
    if (c < 128) {
      out[p++] = c
    } else if (c < 2048) {
      out[p++] = (c >> 6) | 192
      out[p++] = (c & 63) | 128
    } else if (
      ((c & 0xFC00) === 0xD800) && (i + 1) < str.length &&
      ((str.charCodeAt(i + 1) & 0xFC00) === 0xDC00)) {
      // Surrogate Pair
      c = 0x10000 + ((c & 0x03FF) << 10) + (str.charCodeAt(++i) & 0x03FF)
      out[p++] = (c >> 18) | 240
      out[p++] = ((c >> 12) & 63) | 128
      out[p++] = ((c >> 6) & 63) | 128
      out[p++] = (c & 63) | 128
    } else {
      if ((c >= 0xD800) && (c <= 0xDFFF)) {
        c = 0xFFFD // Unpaired Surrogate
      }
      out[p++] = (c >> 12) | 224
      out[p++] = ((c >> 6) & 63) | 128
      out[p++] = (c & 63) | 128
    }
  }
  return out
}

// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
const MAX_ARGUMENTS_LENGTH = 0x1000

/**
 * @param {number[]} codePoints
 * @returns {string}
 */
export function decodeCodePointsArray (codePoints) {
  const len = codePoints.length
  if (len <= MAX_ARGUMENTS_LENGTH) {
    return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  }
  // Decode in chunks to avoid "call stack size exceeded".
  let res = ''
  let i = 0
  while (i < len) {
    res += String.fromCharCode.apply(
      String,
      codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
    )
  }
  return res
}
const decodeErrPrefix = 'CBOR decode error:'
const encodeErrPrefix = 'CBOR encode error:'

const uintMinorPrefixBytes = []
uintMinorPrefixBytes[23] = 1
uintMinorPrefixBytes[24] = 2
uintMinorPrefixBytes[25] = 3
uintMinorPrefixBytes[26] = 5
uintMinorPrefixBytes[27] = 9

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} need
 */
function assertEnoughData (data, pos, need) {
  if (data.length - pos < need) {
    throw new Error(`${decodeErrPrefix} not enough data for type`)
  }
}

export {
  decodeErrPrefix,
  encodeErrPrefix,
  uintMinorPrefixBytes,
  assertEnoughData
}
import { decodeErrPrefix } from './common.js'
import { Type } from './token.js'
import { jump, quick } from './jump.js'
import { asU8A } from './byte-utils.js'

/**
 * @typedef {import('./token.js').Token} Token
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 * @typedef {import('../interface.js').DecodeTokenizer} DecodeTokenizer
 * @typedef {import('../interface.js').TagDecodeControl} TagDecodeControl
 */

const defaultDecodeOptions = {
  strict: false,
  allowIndefinite: true,
  allowUndefined: true,
  allowBigInt: true
}

/**
 * @implements {DecodeTokenizer}
 */
class Tokeniser {
  /**
   * @param {Uint8Array} data
   * @param {DecodeOptions} options
   */
  constructor (data, options = {}) {
    this._pos = 0
    this.data = data
    this.options = options
  }

  pos () {
    return this._pos
  }

  done () {
    return this._pos >= this.data.length
  }

  next () {
    const byt = this.data[this._pos]
    let token = quick[byt]
    if (token === undefined) {
      const decoder = jump[byt]
      // if we're here then there's something wrong with our jump or quick lists!
      if (!decoder) {
        throw new Error(`${decodeErrPrefix} no decoder for major type ${byt >>> 5} (byte 0x${byt.toString(16).padStart(2, '0')})`)
      }
      const minor = byt & 31
      token = decoder(this.data, this._pos, minor, this.options)
    }
    // @ts-ignore we get to assume encodedLength is set (crossing fingers slightly)
    this._pos += token.encodedLength
    return token
  }
}

const DONE = Symbol.for('DONE')
const BREAK = Symbol.for('BREAK')

/**
 * @param {Token} token
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {any|BREAK|DONE}
 */
function tokenToArray (token, tokeniser, options) {
  const arr = []
  for (let i = 0; i < token.value; i++) {
    const value = tokensToObject(tokeniser, options)
    if (value === BREAK) {
      if (token.value === Infinity) {
        // normal end to indefinite length array
        break
      }
      throw new Error(`${decodeErrPrefix} got unexpected break to lengthed array`)
    }
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} found array but not enough entries (got ${i}, expected ${token.value})`)
    }
    arr[i] = value
  }
  return arr
}

/**
 * @param {Token} token
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {any|BREAK|DONE}
 */
function tokenToMap (token, tokeniser, options) {
  const useMaps = options.useMaps === true
  const rejectDuplicateMapKeys = options.rejectDuplicateMapKeys === true
  const obj = useMaps ? undefined : {}
  const m = useMaps ? new Map() : undefined
  for (let i = 0; i < token.value; i++) {
    const key = tokensToObject(tokeniser, options)
    if (key === BREAK) {
      if (token.value === Infinity) {
        // normal end to indefinite length map
        break
      }
      throw new Error(`${decodeErrPrefix} got unexpected break to lengthed map`)
    }
    if (key === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no key], expected ${token.value})`)
    }
    if (!useMaps && typeof key !== 'string') {
      throw new Error(`${decodeErrPrefix} non-string keys not supported (got ${typeof key})`)
    }
    if (rejectDuplicateMapKeys) {
      // @ts-ignore
      if ((useMaps && m.has(key)) || (!useMaps && Object.hasOwn(obj, key))) {
        throw new Error(`${decodeErrPrefix} found repeat map key "${key}"`)
      }
    }
    const value = tokensToObject(tokeniser, options)
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no value], expected ${token.value})`)
    }
    if (useMaps) {
      // @ts-ignore TODO reconsider this .. maybe needs to be strict about key types
      m.set(key, value)
    } else {
      // @ts-ignore TODO reconsider this .. maybe needs to be strict about key types
      obj[key] = value
    }
  }
  // @ts-ignore c'mon man
  return useMaps ? m : obj
}

/**
 * Generator that yields [key, value] entries from a CBOR map token.
 * Used by tag decoders that need to preserve key types (e.g., Tag 259 Map).
 * @param {Token} token - The map token
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {Generator<[any, any], void, unknown>}
 */
function * tokenToMapEntries (token, tokeniser, options) {
  for (let i = 0; i < token.value; i++) {
    const key = tokensToObject(tokeniser, options)
    if (key === BREAK) {
      if (token.value === Infinity) {
        // normal end to indefinite length map
        break
      }
      throw new Error(`${decodeErrPrefix} got unexpected break to lengthed map`)
    }
    if (key === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no key], expected ${token.value})`)
    }
    const value = tokensToObject(tokeniser, options)
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no value], expected ${token.value})`)
    }
    yield [key, value]
  }
}

/**
 * Creates a TagDecodeControl object for tag decoders.
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {TagDecodeControl}
 */
function createTagDecodeControl (tokeniser, options) {
  let called = false

  /**
   * @type {TagDecodeControl}
   */
  const decode = function () {
    if (called) {
      throw new Error(`${decodeErrPrefix} tag decode() may only be called once`)
    }
    called = true
    const value = tokensToObject(tokeniser, options)
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} tag content missing`)
    }
    if (value === BREAK) {
      throw new Error(`${decodeErrPrefix} got unexpected break in tag content`)
    }
    return value
  }

  decode.entries = function () {
    if (called) {
      throw new Error(`${decodeErrPrefix} tag decode() may only be called once`)
    }
    called = true

    // Get the next token and ensure it's a map
    const token = tokeniser.next()
    if (!Type.equals(token.type, Type.map)) {
      throw new Error(`${decodeErrPrefix} entries() requires map content, got ${token.type.name}`)
    }

    // Collect all entries into an array (ensures full content consumption)
    const entries = []
    for (const entry of tokenToMapEntries(token, tokeniser, options)) {
      entries.push(entry)
    }
    return entries
  }

  // For internal tracking
  Object.defineProperty(decode, '_called', {
    get () { return called },
    enumerable: false
  })

  return decode
}

/**
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {any|BREAK|DONE}
 */
function tokensToObject (tokeniser, options) {
  // should we support array as an argument?
  // check for tokenIter[Symbol.iterator] and replace tokenIter with what that returns?
  if (tokeniser.done()) {
    return DONE
  }

  const token = tokeniser.next()

  if (Type.equals(token.type, Type.break)) {
    return BREAK
  }

  if (token.type.terminal) {
    return token.value
  }

  if (Type.equals(token.type, Type.array)) {
    return tokenToArray(token, tokeniser, options)
  }

  if (Type.equals(token.type, Type.map)) {
    return tokenToMap(token, tokeniser, options)
  }

  if (Type.equals(token.type, Type.tag)) {
    if (options.tags && typeof options.tags[token.value] === 'function') {
      const decodeControl = createTagDecodeControl(tokeniser, options)
      const result = options.tags[token.value](decodeControl)
      if (!decodeControl._called) {
        throw new Error(`${decodeErrPrefix} tag decoder must call decode() or entries()`)
      }
      return result
    }
    throw new Error(`${decodeErrPrefix} tag not supported (${token.value})`)
  }
  throw new Error('unsupported')
}

/**
 * @param {Uint8Array} data
 * @param {DecodeOptions} [options]
 * @returns {[any, Uint8Array]}
 */
function decodeFirst (data, options) {
  if (!(data instanceof Uint8Array)) {
    throw new Error(`${decodeErrPrefix} data to decode must be a Uint8Array`)
  }
  options = Object.assign({}, defaultDecodeOptions, options)
  // Convert Buffer to plain Uint8Array for faster slicing in decode path
  const u8aData = asU8A(data)
  const tokeniser = options.tokenizer || new Tokeniser(u8aData, options)
  const decoded = tokensToObject(tokeniser, options)
  if (decoded === DONE) {
    throw new Error(`${decodeErrPrefix} did not find any content to decode`)
  }
  if (decoded === BREAK) {
    throw new Error(`${decodeErrPrefix} got unexpected break`)
  }
  return [decoded, data.subarray(tokeniser.pos())]
}

/**
 * @param {Uint8Array} data
 * @param {DecodeOptions} [options]
 * @returns {any}
 */
function decode (data, options) {
  const [decoded, remainder] = decodeFirst(data, options)
  if (remainder.length > 0) {
    throw new Error(`${decodeErrPrefix} too many terminals, data makes no sense`)
  }
  return decoded
}

export { Tokeniser, tokensToObject, decode, decodeFirst }
import { is } from './is.js'
import { Token, Type } from './token.js'
import { Bl, U8Bl } from './bl.js'
import { encodeErrPrefix } from './common.js'
import { quickEncodeToken } from './jump.js'
import { asU8A, compare, fromString } from './byte-utils.js'

import { encodeUint, encodeUintValue } from './0uint.js'
import { encodeNegint } from './1negint.js'
import { encodeBytes } from './2bytes.js'
import { encodeString } from './3string.js'
import { encodeArray } from './4array.js'
import { encodeMap } from './5map.js'
import { encodeTag } from './6tag.js'
import { encodeFloat, MINOR_FALSE, MINOR_TRUE, MINOR_NULL, MINOR_UNDEFINED } from './7float.js'

/**
 * @typedef {import('../interface.js').EncodeOptions} EncodeOptions
 * @typedef {import('../interface.js').OptionalTypeEncoder} OptionalTypeEncoder
 * @typedef {import('../interface.js').Reference} Reference
 * @typedef {import('../interface.js').StrictTypeEncoder} StrictTypeEncoder
 * @typedef {import('../interface.js').TokenTypeEncoder} TokenTypeEncoder
 * @typedef {import('../interface.js').TokenOrNestedTokens} TokenOrNestedTokens
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 */

/** @type {EncodeOptions} */
const defaultEncodeOptions = {
  float64: false,
  mapSorter,
  quickEncodeToken
}

/** @type {EncodeOptions} */
export const rfc8949EncodeOptions = Object.freeze({
  mapSorter: rfc8949MapSorter,
  quickEncodeToken
})

/** @returns {TokenTypeEncoder[]} */
export function makeCborEncoders () {
  const encoders = []
  encoders[Type.uint.major] = encodeUint
  encoders[Type.negint.major] = encodeNegint
  encoders[Type.bytes.major] = encodeBytes
  encoders[Type.string.major] = encodeString
  encoders[Type.array.major] = encodeArray
  encoders[Type.map.major] = encodeMap
  encoders[Type.tag.major] = encodeTag
  encoders[Type.float.major] = encodeFloat
  return encoders
}

const cborEncoders = makeCborEncoders()

const defaultWriter = new Bl()

/** @implements {Reference} */
class Ref {
  /**
   * @param {object|any[]} obj
   * @param {Reference|undefined} parent
   */
  constructor (obj, parent) {
    this.obj = obj
    this.parent = parent
  }

  /**
   * @param {object|any[]} obj
   * @returns {boolean}
   */
  includes (obj) {
    /** @type {Reference|undefined} */
    let p = this
    do {
      if (p.obj === obj) {
        return true
      }
    } while (p = p.parent) // eslint-disable-line
    return false
  }

  /**
   * @param {Reference|undefined} stack
   * @param {object|any[]} obj
   * @returns {Reference}
   */
  static createCheck (stack, obj) {
    if (stack && stack.includes(obj)) {
      throw new Error(`${encodeErrPrefix} object contains circular references`)
    }
    return new Ref(obj, stack)
  }
}

const simpleTokens = {
  null: new Token(Type.null, null),
  undefined: new Token(Type.undefined, undefined),
  true: new Token(Type.true, true),
  false: new Token(Type.false, false),
  emptyArray: new Token(Type.array, 0),
  emptyMap: new Token(Type.map, 0)
}

/** @type {{[typeName: string]: StrictTypeEncoder}} */
const typeEncoders = {
  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  number (obj, _typ, _options, _refStack) {
    if (!Number.isInteger(obj) || !Number.isSafeInteger(obj)) {
      return new Token(Type.float, obj)
    } else if (obj >= 0) {
      return new Token(Type.uint, obj)
    } else {
      return new Token(Type.negint, obj)
    }
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  bigint (obj, _typ, _options, _refStack) {
    if (obj >= BigInt(0)) {
      return new Token(Type.uint, obj)
    } else {
      return new Token(Type.negint, obj)
    }
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  Uint8Array (obj, _typ, _options, _refStack) {
    return new Token(Type.bytes, obj)
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  string (obj, _typ, _options, _refStack) {
    return new Token(Type.string, obj)
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  boolean (obj, _typ, _options, _refStack) {
    return obj ? simpleTokens.true : simpleTokens.false
  },

  /**
   * @param {any} _obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  null (_obj, _typ, _options, _refStack) {
    return simpleTokens.null
  },

  /**
   * @param {any} _obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  undefined (_obj, _typ, _options, _refStack) {
    return simpleTokens.undefined
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  ArrayBuffer (obj, _typ, _options, _refStack) {
    return new Token(Type.bytes, new Uint8Array(obj))
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  DataView (obj, _typ, _options, _refStack) {
    return new Token(Type.bytes, new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength))
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} options
   * @param {Reference} [refStack]
   * @returns {TokenOrNestedTokens}
   */
  Array (obj, _typ, options, refStack) {
    if (!obj.length) {
      if (options.addBreakTokens === true) {
        return [simpleTokens.emptyArray, new Token(Type.break)]
      }
      return simpleTokens.emptyArray
    }
    refStack = Ref.createCheck(refStack, obj)
    const entries = []
    let i = 0
    for (const e of obj) {
      entries[i++] = objectToTokens(e, options, refStack)
    }
    if (options.addBreakTokens) {
      return [new Token(Type.array, obj.length), entries, new Token(Type.break)]
    }
    return [new Token(Type.array, obj.length), entries]
  },

  /**
   * @param {any} obj
   * @param {string} typ
   * @param {EncodeOptions} options
   * @param {Reference} [refStack]
   * @returns {TokenOrNestedTokens}
   */
  Object (obj, typ, options, refStack) {
    // could be an Object or a Map
    const isMap = typ !== 'Object'
    // it's slightly quicker to use Object.keys() than Object.entries()
    const keys = isMap ? obj.keys() : Object.keys(obj)
    const maxLength = isMap ? obj.size : keys.length

    /** @type {undefined | [TokenOrNestedTokens, TokenOrNestedTokens][]} */
    let entries

    if (maxLength) {
      // Pre-allocate the array with the expected size
      entries = new Array(maxLength)
      refStack = Ref.createCheck(refStack, obj)
      const skipUndefined = !isMap && options.ignoreUndefinedProperties

      let i = 0
      for (const key of keys) {
        const value = isMap ? obj.get(key) : obj[key]
        if (skipUndefined && value === undefined) {
          continue
        }
        entries[i++] = [
          objectToTokens(key, options, refStack),
          objectToTokens(value, options, refStack)
        ]
      }

      // Truncate only if properties were skipped
      if (i < maxLength) {
        entries.length = i
      }
    }

    if (!entries?.length) {
      if (options.addBreakTokens === true) {
        return [simpleTokens.emptyMap, new Token(Type.break)]
      }
      return simpleTokens.emptyMap
    }

    sortMapEntries(entries, options)
    if (options.addBreakTokens) {
      return [new Token(Type.map, entries.length), entries, new Token(Type.break)]
    }
    return [new Token(Type.map, entries.length), entries]
  },

  /**
   * Encode a `Tagged` wrapper as a CBOR tag header followed by the encoded
   * form of the wrapped value. The value is recursively tokenised through
   * `objectToTokens()` so any registered `typeEncoders` apply to it.
   *
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} options
   * @param {Reference} [refStack]
   * @returns {TokenOrNestedTokens}
   */
  Tagged (obj, _typ, options, refStack) {
    return [
      new Token(Type.tag, obj.tag),
      objectToTokens(obj.value, options, refStack)
    ]
  }
}

typeEncoders.Map = typeEncoders.Object
typeEncoders.Buffer = typeEncoders.Uint8Array
for (const typ of 'Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64'.split(' ')) {
  typeEncoders[`${typ}Array`] = typeEncoders.DataView
}

/**
 * @param {any} obj
 * @param {EncodeOptions} [options]
 * @param {Reference} [refStack]
 * @returns {TokenOrNestedTokens}
 */
function objectToTokens (obj, options = {}, refStack) {
  const typ = is(obj)
  const customTypeEncoder = (options && options.typeEncoders && /** @type {OptionalTypeEncoder} */ options.typeEncoders[typ]) || typeEncoders[typ]
  if (typeof customTypeEncoder === 'function') {
    const tokens = customTypeEncoder(obj, typ, options, refStack)
    if (tokens != null) {
      return tokens
    }
  }
  const typeEncoder = typeEncoders[typ]
  if (!typeEncoder) {
    throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`)
  }
  return typeEncoder(obj, typ, options, refStack)
}

/*
CBOR key sorting is a mess.

The canonicalisation recommendation from https://tools.ietf.org/html/rfc7049#section-3.9
includes the wording:

> The keys in every map must be sorted lowest value to highest.
> Sorting is performed on the bytes of the representation of the key
> data items without paying attention to the 3/5 bit splitting for
> major types.
> ...
>  *  If two keys have different lengths, the shorter one sorts
      earlier;
>  *  If two keys have the same length, the one with the lower value
      in (byte-wise) lexical order sorts earlier.

1. It is not clear what "bytes of the representation of the key" means: is it
   the CBOR representation, or the binary representation of the object itself?
   Consider the int and uint difference here.
2. It is not clear what "without paying attention to" means: do we include it
   and compare on that? Or do we omit the special prefix byte, (mostly) treating
   the key in its plain binary representation form.

The FIDO 2.0: Client To Authenticator Protocol spec takes the original CBOR
wording and clarifies it according to their understanding.
https://fidoalliance.org/specs/fido-v2.0-rd-20170927/fido-client-to-authenticator-protocol-v2.0-rd-20170927.html#message-encoding

> The keys in every map must be sorted lowest value to highest. Sorting is
> performed on the bytes of the representation of the key data items without
> paying attention to the 3/5 bit splitting for major types. The sorting rules
> are:
>  * If the major types are different, the one with the lower value in numerical
>    order sorts earlier.
>  * If two keys have different lengths, the shorter one sorts earlier;
>  * If two keys have the same length, the one with the lower value in
>    (byte-wise) lexical order sorts earlier.

Some other implementations, such as borc, do a full encode then do a
length-first, byte-wise-second comparison:
https://github.com/dignifiedquire/borc/blob/b6bae8b0bcde7c3976b0f0f0957208095c392a36/src/encoder.js#L358
https://github.com/dignifiedquire/borc/blob/b6bae8b0bcde7c3976b0f0f0957208095c392a36/src/utils.js#L143-L151

This has the benefit of being able to easily handle arbitrary keys, including
complex types (maps and arrays).

We'll opt for the FIDO approach, since it affords some efficies since we don't
need a full encode of each key to determine order and can defer to the types
to determine how to most efficiently order their values (i.e. int and uint
ordering can be done on the numbers, no need for byte-wise, for example).

Recommendation: stick to single key types or you'll get into trouble, and prefer
string keys because it's much simpler that way.
*/

/**
 * @param {TokenOrNestedTokens[]} entries
 * @param {EncodeOptions} options
 */
function sortMapEntries (entries, options) {
  if (options.mapSorter) {
    entries.sort(options.mapSorter)
  }
}

/**
 * @param {(Token|Token[])[]} e1
 * @param {(Token|Token[])[]} e2
 * @returns {number}
 */
function mapSorter (e1, e2) {
  // the key position ([0]) could have a single token or an array
  // almost always it'll be a single token but complex key might get involved
  const keyToken1 = Array.isArray(e1[0]) ? e1[0][0] : e1[0]
  const keyToken2 = Array.isArray(e2[0]) ? e2[0][0] : e2[0]

  // different key types
  if (keyToken1.type !== keyToken2.type) {
    return keyToken1.type.compare(keyToken2.type)
  }

  const major = keyToken1.type.major
  // TODO: handle case where cmp === 0 but there are more keyToken e. complex type)
  const tcmp = cborEncoders[major].compareTokens(keyToken1, keyToken2)
  if (tcmp === 0) {
    // duplicate key or complex type where the first token matched,
    // i.e. a map or array and we're only comparing the opening token
    console.warn('WARNING: complex key types used, CBOR key sorting guarantees are gone')
  }
  return tcmp
}

/**
 * @typedef {Token & { _keyBytes?: Uint8Array }} TokenEx
 *
 * @param {(Token|Token[])[]} e1
 * @param {(Token|Token[])[]} e2
 * @returns {number}
 */
function rfc8949MapSorter (e1, e2) {
  if (e1[0] instanceof Token && e2[0] instanceof Token) {
    const t1 = /** @type {TokenEx} */ (e1[0])
    const t2 = /** @type {TokenEx} */ (e2[0])

    if (!t1._keyBytes) {
      t1._keyBytes = encodeRfc8949(t1.value)
    }

    if (!t2._keyBytes) {
      t2._keyBytes = encodeRfc8949(t2.value)
    }

    return compare(t1._keyBytes, t2._keyBytes)
  }

  throw new Error('rfc8949MapSorter: complex key types are not supported yet')
}

/**
 * @param {any} data
 * @returns {Uint8Array}
 */
function encodeRfc8949 (data) {
  return encodeCustom(data, cborEncoders, rfc8949EncodeOptions)
}

/**
 * @param {ByteWriter} writer
 * @param {TokenOrNestedTokens} tokens
 * @param {TokenTypeEncoder[]} encoders
 * @param {EncodeOptions} options
 */
function tokensToEncoded (writer, tokens, encoders, options) {
  if (Array.isArray(tokens)) {
    for (const token of tokens) {
      tokensToEncoded(writer, token, encoders, options)
    }
  } else {
    encoders[tokens.type.major](writer, tokens, options)
  }
}

// CBOR major type prefixes, cached from Type for hot path performance
const MAJOR_UINT = Type.uint.majorEncoded
const MAJOR_NEGINT = Type.negint.majorEncoded
const MAJOR_BYTES = Type.bytes.majorEncoded
const MAJOR_STRING = Type.string.majorEncoded
const MAJOR_ARRAY = Type.array.majorEncoded

// Simple value bytes (CBOR major type 7 + minor value)
const SIMPLE_FALSE = Type.float.majorEncoded | MINOR_FALSE
const SIMPLE_TRUE = Type.float.majorEncoded | MINOR_TRUE
const SIMPLE_NULL = Type.float.majorEncoded | MINOR_NULL
const SIMPLE_UNDEFINED = Type.float.majorEncoded | MINOR_UNDEFINED

const neg1b = BigInt(-1)
const pos1b = BigInt(1)

/**
 * Check if direct encoding can be used for the given options.
 * Direct encoding bypasses token creation for most values.
 * @param {EncodeOptions} options
 * @returns {boolean}
 */
function canDirectEncode (options) {
  // Cannot use direct encode with addBreakTokens (needs special break token handling).
  // Direct encode checks typeEncoders per-value, falling back to tokens as needed.
  // Maps fall back to token-based encoding for efficient key sorting.
  return options.addBreakTokens !== true
}

/**
 * Direct encode a value to the writer, bypassing token creation for most types.
 * Falls back to token-based encoding for custom type encoders.
 * @param {ByteWriter} writer
 * @param {any} data
 * @param {EncodeOptions} options
 * @param {Reference|undefined} refStack
 */
function directEncode (writer, data, options, refStack) {
  const typ = is(data)

  // Check for custom encoder for THIS specific type
  const customEncoder = options.typeEncoders && options.typeEncoders[typ]
  if (customEncoder) {
    const tokens = customEncoder(data, typ, options, refStack)
    if (tokens != null) {
      // Custom encoder returned tokens, serialize immediately
      tokensToEncoded(writer, tokens, cborEncoders, options)
      return
    }
    // Custom encoder returned null, fall through to default handling
  }

  // Direct encode based on type
  switch (typ) {
    case 'null':
      writer.push([SIMPLE_NULL])
      return

    case 'undefined':
      writer.push([SIMPLE_UNDEFINED])
      return

    case 'boolean':
      writer.push([data ? SIMPLE_TRUE : SIMPLE_FALSE])
      return

    case 'number':
      if (!Number.isInteger(data) || !Number.isSafeInteger(data)) {
        // Float, use token encoder for complex float encoding
        encodeFloat(writer, new Token(Type.float, data), options)
      } else if (data >= 0) {
        encodeUintValue(writer, MAJOR_UINT, data)
      } else {
        // Negative integer
        encodeUintValue(writer, MAJOR_NEGINT, data * -1 - 1)
      }
      return

    case 'bigint':
      if (data >= BigInt(0)) {
        encodeUintValue(writer, MAJOR_UINT, data)
      } else {
        encodeUintValue(writer, MAJOR_NEGINT, data * neg1b - pos1b)
      }
      return

    case 'string': {
      const bytes = fromString(data)
      encodeUintValue(writer, MAJOR_STRING, bytes.length)
      writer.push(bytes)
      return
    }

    case 'Uint8Array':
      encodeUintValue(writer, MAJOR_BYTES, data.length)
      writer.push(data)
      return

    case 'Array':
      if (!data.length) {
        writer.push([MAJOR_ARRAY]) // Empty array: 0x80
        return
      }
      refStack = Ref.createCheck(refStack, data)
      encodeUintValue(writer, MAJOR_ARRAY, data.length)
      for (const elem of data) {
        directEncode(writer, elem, options, refStack)
      }
      return

    case 'Object':
    case 'Map':
      // Maps require key sorting, use token-based encoding for efficiency
      // (pre-encoding all keys for sorting is expensive)
      {
        const tokens = typeEncoders.Object(data, typ, options, refStack)
        tokensToEncoded(writer, tokens, cborEncoders, options)
      }
      return

    default:
    // Fall back to token-based encoding for other types (DataView, TypedArrays, etc.)
    {
      const typeEncoder = typeEncoders[typ]
      if (!typeEncoder) {
        throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`)
      }
      const tokens = typeEncoder(data, typ, options, refStack)
      tokensToEncoded(writer, tokens, cborEncoders, options)
    }
  }
}

/**
 * @param {any} data
 * @param {TokenTypeEncoder[]} encoders
 * @param {EncodeOptions} options
 * @param {Uint8Array} [destination]
 * @returns {Uint8Array}
 */
function encodeCustom (data, encoders, options, destination) {
  // arg ordering is different to encodeInto for backward compatibility
  const hasDest = destination instanceof Uint8Array
  let writeTo = hasDest ? new U8Bl(destination) : defaultWriter

  const tokens = objectToTokens(data, options)
  if (!Array.isArray(tokens) && options.quickEncodeToken) {
    const quickBytes = options.quickEncodeToken(tokens)
    if (quickBytes) {
      if (hasDest) {
        // Copy quick bytes into destination buffer
        writeTo.push(quickBytes)
        return writeTo.toBytes()
      }
      return quickBytes
    }
    const encoder = encoders[tokens.type.major]
    if (encoder.encodedSize) {
      const size = encoder.encodedSize(tokens, options)
      if (!hasDest) {
        writeTo = new Bl(size)
      }
      encoder(writeTo, tokens, options)
      // this would be a problem with encodedSize() functions
      if (writeTo.chunks.length !== 1) {
        throw new Error(`Unexpected error: pre-calculated length for ${tokens} was wrong`)
      }
      return hasDest ? writeTo.toBytes() : asU8A(writeTo.chunks[0])
    }
  }
  writeTo.reset()
  tokensToEncoded(writeTo, tokens, encoders, options)
  return writeTo.toBytes(true)
}

/**
 * @param {any} data
 * @param {EncodeOptions} [options]
 * @returns {Uint8Array}
 */
function encode (data, options) {
  options = Object.assign({}, defaultEncodeOptions, options)

  // Use direct encode path when possible
  if (canDirectEncode(options)) {
    defaultWriter.reset()
    directEncode(defaultWriter, data, options, undefined)
    return defaultWriter.toBytes(true)
  }

  return encodeCustom(data, cborEncoders, options)
}

/**
 * @param {any} data
 * @param {Uint8Array} destination
 * @param {EncodeOptions} [options]
 * @returns {{ written: number }}
 */
function encodeInto (data, destination, options) {
  options = Object.assign({}, defaultEncodeOptions, options)

  // Use direct encode path when possible
  if (canDirectEncode(options)) {
    const writer = new U8Bl(destination)
    directEncode(writer, data, options, undefined)
    return { written: writer.toBytes().length }
  }

  const result = encodeCustom(data, cborEncoders, options, destination)
  return { written: result.length }
}

export { objectToTokens, encode, encodeCustom, encodeInto, Ref }
// This is an unfortunate replacement for @sindresorhus/is that we need to
// re-implement for performance purposes. In particular the is.observable()
// check is expensive, and unnecessary for our purposes. The values returned
// are compatible with @sindresorhus/is, however.

// Types that reach getObjectType() - excludes types with fast-paths above:
// primitives (typeof), Array (isArray), Uint8Array (instanceof), plain Object (constructor)
const objectTypeNames = [
  'Object', // for Object.create(null) and other non-plain objects
  'RegExp',
  'Date',
  'Error',
  'Map',
  'Set',
  'WeakMap',
  'WeakSet',
  'ArrayBuffer',
  'SharedArrayBuffer',
  'DataView',
  'Promise',
  'URL',
  'HTMLElement',
  'Int8Array',
  'Uint8ClampedArray',
  'Int16Array',
  'Uint16Array',
  'Int32Array',
  'Uint32Array',
  'Float32Array',
  'Float64Array',
  'BigInt64Array',
  'BigUint64Array',
  'Tagged'
]

/**
 * @param {any} value
 * @returns {string}
 */
export function is (value) {
  if (value === null) {
    return 'null'
  }
  if (value === undefined) {
    return 'undefined'
  }
  if (value === true || value === false) {
    return 'boolean'
  }
  const typeOf = typeof value
  if (typeOf === 'string' || typeOf === 'number' || typeOf === 'bigint' || typeOf === 'symbol') {
    return typeOf
  }
  if (typeOf === 'function') {
    return 'Function'
  }
  if (Array.isArray(value)) {
    return 'Array'
  }
  // Also catches Node.js Buffer which extends Uint8Array
  if (value instanceof Uint8Array) {
    return 'Uint8Array'
  }
  // Fast path for plain objects (most common case after primitives/arrays/bytes)
  if (value.constructor === Object) {
    return 'Object'
  }
  const objectType = getObjectType(value)
  if (objectType) {
    return objectType
  }
  return 'Object'
}

/**
 * @param {any} value
 * @returns {string|undefined}
 */
function getObjectType (value) {
  const objectTypeName = Object.prototype.toString.call(value).slice(8, -1)
  if (objectTypeNames.includes(objectTypeName)) {
    return objectTypeName
  }
  return undefined
}
import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import * as negint from './1negint.js'
import * as bytes from './2bytes.js'
import * as string from './3string.js'
import * as array from './4array.js'
import * as map from './5map.js'
import * as tag from './6tag.js'
import * as float from './7float.js'
import { decodeErrPrefix } from './common.js'
import { fromArray } from './byte-utils.js'

/**
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 */
function invalidMinor (data, pos, minor) {
  throw new Error(`${decodeErrPrefix} encountered invalid minor (${minor}) for major ${data[pos] >>> 5}`)
}

/**
 * @param {string} msg
 * @returns {()=>any}
 */
function errorer (msg) {
  return () => { throw new Error(`${decodeErrPrefix} ${msg}`) }
}

/** @type {((data:Uint8Array, pos:number, minor:number, options?:DecodeOptions) => any)[]} */
export const jump = []

// unsigned integer, 0x00..0x17 (0..23)
for (let i = 0; i <= 0x17; i++) {
  jump[i] = invalidMinor // uint.decodeUintCompact, handled by quick[]
}
jump[0x18] = uint.decodeUint8 // unsigned integer, one-byte uint8_t follows
jump[0x19] = uint.decodeUint16 // unsigned integer, two-byte uint16_t follows
jump[0x1a] = uint.decodeUint32 // unsigned integer, four-byte uint32_t follows
jump[0x1b] = uint.decodeUint64 // unsigned integer, eight-byte uint64_t follows
jump[0x1c] = invalidMinor
jump[0x1d] = invalidMinor
jump[0x1e] = invalidMinor
jump[0x1f] = invalidMinor
// negative integer, -1-0x00..-1-0x17 (-1..-24)
for (let i = 0x20; i <= 0x37; i++) {
  jump[i] = invalidMinor // negintDecode, handled by quick[]
}
jump[0x38] = negint.decodeNegint8 // negative integer, -1-n one-byte uint8_t for n follows
jump[0x39] = negint.decodeNegint16 // negative integer, -1-n two-byte uint16_t for n follows
jump[0x3a] = negint.decodeNegint32 // negative integer, -1-n four-byte uint32_t for follows
jump[0x3b] = negint.decodeNegint64 // negative integer, -1-n eight-byte uint64_t for follows
jump[0x3c] = invalidMinor
jump[0x3d] = invalidMinor
jump[0x3e] = invalidMinor
jump[0x3f] = invalidMinor
// byte string, 0x00..0x17 bytes follow
for (let i = 0x40; i <= 0x57; i++) {
  jump[i] = bytes.decodeBytesCompact
}
jump[0x58] = bytes.decodeBytes8 // byte string, one-byte uint8_t for n, and then n bytes follow
jump[0x59] = bytes.decodeBytes16 // byte string, two-byte uint16_t for n, and then n bytes follow
jump[0x5a] = bytes.decodeBytes32 // byte string, four-byte uint32_t for n, and then n bytes follow
jump[0x5b] = bytes.decodeBytes64 // byte string, eight-byte uint64_t for n, and then n bytes follow
jump[0x5c] = invalidMinor
jump[0x5d] = invalidMinor
jump[0x5e] = invalidMinor
jump[0x5f] = errorer('indefinite length bytes/strings are not supported') // byte string, byte strings follow, terminated by "break"
// UTF-8 string 0x00..0x17 bytes follow
for (let i = 0x60; i <= 0x77; i++) {
  jump[i] = string.decodeStringCompact
}
jump[0x78] = string.decodeString8 // UTF-8 string, one-byte uint8_t for n, and then n bytes follow
jump[0x79] = string.decodeString16 // UTF-8 string, two-byte uint16_t for n, and then n bytes follow
jump[0x7a] = string.decodeString32 // UTF-8 string, four-byte uint32_t for n, and then n bytes follow
jump[0x7b] = string.decodeString64 // UTF-8 string, eight-byte uint64_t for n, and then n bytes follow
jump[0x7c] = invalidMinor
jump[0x7d] = invalidMinor
jump[0x7e] = invalidMinor
jump[0x7f] = errorer('indefinite length bytes/strings are not supported') // UTF-8 strings follow, terminated by "break"
// array, 0x00..0x17 data items follow
for (let i = 0x80; i <= 0x97; i++) {
  jump[i] = array.decodeArrayCompact
}
jump[0x98] = array.decodeArray8 // array, one-byte uint8_t for n, and then n data items follow
jump[0x99] = array.decodeArray16 // array, two-byte uint16_t for n, and then n data items follow
jump[0x9a] = array.decodeArray32 // array, four-byte uint32_t for n, and then n data items follow
jump[0x9b] = array.decodeArray64 // array, eight-byte uint64_t for n, and then n data items follow
jump[0x9c] = invalidMinor
jump[0x9d] = invalidMinor
jump[0x9e] = invalidMinor
jump[0x9f] = array.decodeArrayIndefinite // array, data items follow, terminated by "break"
// map, 0x00..0x17 pairs of data items follow
for (let i = 0xa0; i <= 0xb7; i++) {
  jump[i] = map.decodeMapCompact
}
jump[0xb8] = map.decodeMap8 // map, one-byte uint8_t for n, and then n pairs of data items follow
jump[0xb9] = map.decodeMap16 // map, two-byte uint16_t for n, and then n pairs of data items follow
jump[0xba] = map.decodeMap32 // map, four-byte uint32_t for n, and then n pairs of data items follow
jump[0xbb] = map.decodeMap64 // map, eight-byte uint64_t for n, and then n pairs of data items follow
jump[0xbc] = invalidMinor
jump[0xbd] = invalidMinor
jump[0xbe] = invalidMinor
jump[0xbf] = map.decodeMapIndefinite // map, pairs of data items follow, terminated by "break"
// tags
for (let i = 0xc0; i <= 0xd7; i++) {
  jump[i] = tag.decodeTagCompact
}
jump[0xd8] = tag.decodeTag8
jump[0xd9] = tag.decodeTag16
jump[0xda] = tag.decodeTag32
jump[0xdb] = tag.decodeTag64
jump[0xdc] = invalidMinor
jump[0xdd] = invalidMinor
jump[0xde] = invalidMinor
jump[0xdf] = invalidMinor
// 0xe0..0xf3 simple values, unsupported
for (let i = 0xe0; i <= 0xf3; i++) {
  jump[i] = errorer('simple values are not supported')
}
jump[0xf4] = invalidMinor // false, handled by quick[]
jump[0xf5] = invalidMinor // true, handled by quick[]
jump[0xf6] = invalidMinor // null, handled by quick[]
jump[0xf7] = float.decodeUndefined // undefined
jump[0xf8] = errorer('simple values are not supported') // simple value, one byte follows, unsupported
jump[0xf9] = float.decodeFloat16 // half-precision float (two-byte IEEE 754)
jump[0xfa] = float.decodeFloat32 // single-precision float (four-byte IEEE 754)
jump[0xfb] = float.decodeFloat64 // double-precision float (eight-byte IEEE 754)
jump[0xfc] = invalidMinor
jump[0xfd] = invalidMinor
jump[0xfe] = invalidMinor
jump[0xff] = float.decodeBreak // "break" stop code

/** @type {Token[]} */
export const quick = []
// ints <24
for (let i = 0; i < 24; i++) {
  quick[i] = new Token(Type.uint, i, 1)
}
// negints >= -24
for (let i = -1; i >= -24; i--) {
  quick[31 - i] = new Token(Type.negint, i, 1)
}
// empty bytes
quick[0x40] = new Token(Type.bytes, new Uint8Array(0), 1)
// empty string
quick[0x60] = new Token(Type.string, '', 1)
// empty list
quick[0x80] = new Token(Type.array, 0, 1)
// empty map
quick[0xa0] = new Token(Type.map, 0, 1)
// false
quick[0xf4] = new Token(Type.false, false, 1)
// true
quick[0xf5] = new Token(Type.true, true, 1)
// null
quick[0xf6] = new Token(Type.null, null, 1)

/**
 * @param {Token} token
 * @returns {Uint8Array|undefined}
 */
export function quickEncodeToken (token) {
  switch (token.type) {
    case Type.false:
      return fromArray([0xf4])
    case Type.true:
      return fromArray([0xf5])
    case Type.null:
      return fromArray([0xf6])
    case Type.bytes:
      if (!token.value.length) {
        return fromArray([0x40])
      }
      return
    case Type.string:
      if (token.value === '') {
        return fromArray([0x60])
      }
      return
    case Type.array:
      if (token.value === 0) {
        return fromArray([0x80])
      }
      // shouldn't be possible if this were called when there was only one token
      return
    case Type.map:
      if (token.value === 0) {
        return fromArray([0xa0])
      }
      // shouldn't be possible if this were called when there was only one token
      return
    case Type.uint:
      if (token.value < 24) {
        return fromArray([Number(token.value)])
      }
      return
    case Type.negint:
      if (token.value >= -24) {
        return fromArray([31 - Number(token.value)])
      }
  }
}
/**
 * @typedef {import('../interface.js').TagDecodeControl} TagDecodeControl
 * @typedef {(decode: TagDecodeControl) => Tagged} TaggedTagDecoder
 */

/**
 * A wrapper class for representing a CBOR tag with an arbitrary nested value.
 *
 * `Tagged` is a symmetric primitive: it can be passed to `encode()` to emit
 * a CBOR tag header followed by the encoded form of `value`, and it can be
 * returned from a tag decoder (via `Tagged.decoder(tag)` or `Tagged.preserve()`)
 * to round-trip a tag through decode without losing the tag number.
 *
 * Use `Tagged` for one-off tag handling where defining a dedicated
 * `typeEncoders` entry and tag decoder pair would be heavyweight, e.g. when
 * wrapping a structure in a single application-specific tag (COSE, dCBOR
 * envelopes, etc.).
 *
 * For systematic mapping of a JS type to a tag (e.g. CID -> tag 42), prefer
 * a dedicated `typeEncoders` entry instead.
 */
export class Tagged {
  /**
   * @param {number} tag - CBOR tag number, a non-negative integer
   * @param {any} value - The value to be tagged; encoded recursively
   */
  constructor (tag, value) {
    if (typeof tag !== 'number' || !Number.isInteger(tag) || tag < 0) {
      throw new TypeError('Tagged: tag must be a non-negative integer')
    }
    this.tag = tag
    this.value = value
  }

  /**
   * Build a tag decoder for use in `decode()`'s `tags` option that returns the
   * decoded content wrapped in a `Tagged` instance, preserving the tag number
   * for the caller to inspect.
   *
   * @param {number} tag - The CBOR tag number this decoder will be registered for
   * @returns {TaggedTagDecoder}
   *
   * @example
   * import { decode, Tagged } from 'cborg'
   * const value = decode(bytes, { tags: { 16: Tagged.decoder(16) } })
   * // value instanceof Tagged; value.tag === 16
   */
  static decoder (tag) {
    return (decode) => new Tagged(tag, decode())
  }

  /**
   * Build a `tags` option for `decode()` that wraps each listed tag number in
   * a `Tagged` instance, preserving those tags through decode without
   * registering a dedicated decoder per tag.
   *
   * @param {...number} tagNumbers - One or more CBOR tag numbers to preserve
   * @returns {{[tagNumber: number]: TaggedTagDecoder}}
   *
   * @example
   * import { decode, Tagged } from 'cborg'
   * const value = decode(bytes, { tags: Tagged.preserve(16, 96) })
   */
  static preserve (...tagNumbers) {
    /** @type {{[tagNumber: number]: TaggedTagDecoder}} */
    const tags = {}
    for (const tag of tagNumbers) {
      tags[tag] = Tagged.decoder(tag)
    }
    return tags
  }
}

// Symbol.toStringTag so the internal `is()` type detection returns 'Tagged'
// for instances, allowing the default Tagged typeEncoder to match.
Object.defineProperty(Tagged.prototype, Symbol.toStringTag, {
  value: 'Tagged'
})
class Type {
  /**
   * @param {number} major
   * @param {string} name
   * @param {boolean} terminal
   */
  constructor (major, name, terminal) {
    this.major = major
    this.majorEncoded = major << 5
    this.name = name
    this.terminal = terminal
  }

  toString () {
    return `Type[${this.major}].${this.name}`
  }

  /**
   * @param {Type} typ
   * @returns {number}
   */
  compare (typ) {
    return this.major < typ.major ? -1 : this.major > typ.major ? 1 : 0
  }

  /**
   * Check equality between two Type instances. Safe to use across different
   * copies of the Type class (e.g., when bundlers duplicate the module).
   * (major, name) uniquely identifies a Type; terminal is implied by these.
   * @param {Type} a
   * @param {Type} b
   * @returns {boolean}
   */
  static equals (a, b) {
    return a === b || (a.major === b.major && a.name === b.name)
  }
}

// convert to static fields when better supported
Type.uint = new Type(0, 'uint', true)
Type.negint = new Type(1, 'negint', true)
Type.bytes = new Type(2, 'bytes', true)
Type.string = new Type(3, 'string', true)
Type.array = new Type(4, 'array', false)
Type.map = new Type(5, 'map', false)
Type.tag = new Type(6, 'tag', false) // terminal?
Type.float = new Type(7, 'float', true)
Type.false = new Type(7, 'false', true)
Type.true = new Type(7, 'true', true)
Type.null = new Type(7, 'null', true)
Type.undefined = new Type(7, 'undefined', true)
Type.break = new Type(7, 'break', true)
// Type.indefiniteLength = new Type(0, 'indefiniteLength', true)

class Token {
  /**
   * @param {Type} type
   * @param {any} [value]
   * @param {number} [encodedLength]
   */
  constructor (type, value, encodedLength) {
    this.type = type
    this.value = value
    this.encodedLength = encodedLength
    /** @type {Uint8Array|undefined} */
    this.encodedBytes = undefined
    /** @type {Uint8Array|undefined} */
    this.byteValue = undefined
  }

  toString () {
    return `Token[${this.type}].${this.value}`
  }
}

export { Type, Token }
{
  "name": "cborg",
  "version": "5.1.6",
  "description": "Fast CBOR with a focus on strictness",
  "main": "cborg.js",
  "type": "module",
  "bin": {
    "cborg": "lib/bin.js"
  },
  "scripts": {
    "lint": "standard *.js lib/*.js test/*.js",
    "build": "npm run build:types",
    "build:types": "tsc --build",
    "prepublishOnly": "npm run build",
    "test:node": "mocha test/test-*.js",
    "test:node-bin": "mocha test/node-test-bin.js",
    "test:browser": "polendina --cleanup test/test-*.js",
    "test": "npm run lint && npm run build && npm run test:node && npm run test:node-bin && npm run test:browser",
    "test:ci": "npm run test"
  },
  "repository": {
    "type": "git",
    "url": "git@github.com:rvagg/cborg.git"
  },
  "keywords": [
    "cbor"
  ],
  "author": "Rod <rod@vagg.org> (http://r.va.gg/)",
  "license": "Apache-2.0",
  "devDependencies": {
    "@semantic-release/changelog": "^6.0.3",
    "@semantic-release/commit-analyzer": "^13.0.1",
    "@semantic-release/git": "^10.0.1",
    "@semantic-release/github": "^12.0.6",
    "@semantic-release/npm": "^13.1.5",
    "@semantic-release/release-notes-generator": "^14.1.0",
    "@types/chai": "^5.2.3",
    "@types/mocha": "^10.0.10",
    "@types/node": "^26.0.1",
    "chai": "^6.2.2",
    "conventional-changelog-conventionalcommits": "^10.0.0",
    "ipld-garbage": "^5.0.0",
    "mocha": "^11.7.5",
    "polendina": "^3.2.20",
    "semantic-release": "^25.0.3",
    "standard": "^17.1.2",
    "typescript": "^6.0.2"
  },
  "exports": {
    ".": {
      "import": "./cborg.js",
      "types": "./types/cborg.d.ts"
    },
    "./length": {
      "import": "./lib/length.js",
      "types": "./types/lib/length.d.ts"
    },
    "./taglib": {
      "import": "./lib/taglib.js",
      "types": "./types/lib/taglib.d.ts"
    },
    "./json": {
      "import": "./lib/json/json.js",
      "types": "./types/lib/json/json.d.ts"
    },
    "./extended": {
      "import": "./lib/extended/extended.js",
      "types": "./types/lib/extended/extended.d.ts"
    },
    "./interface": {
      "types": "./types/interface.d.ts"
    }
  },
  "types": "cborg.d.ts",
  "typesVersions": {
    "*": {
      "json": [
        "types/lib/json/json.d.ts"
      ],
      "length": [
        "types/lib/length.d.ts"
      ],
      "*": [
        "types/*"
      ],
      "types/*": [
        "types/*"
      ]
    }
  },
  "release": {
    "branches": [
      "master"
    ],
    "plugins": [
      [
        "@semantic-release/commit-analyzer",
        {
          "preset": "conventionalcommits",
          "releaseRules": [
            {
              "breaking": true,
              "release": "major"
            },
            {
              "revert": true,
              "release": "patch"
            },
            {
              "type": "feat",
              "release": "minor"
            },
            {
              "type": "fix",
              "release": "patch"
            },
            {
              "type": "chore",
              "release": "patch"
            },
            {
              "type": "docs",
              "release": "patch"
            },
            {
              "type": "test",
              "release": "patch"
            },
            {
              "scope": "no-release",
              "release": false
            }
          ]
        }
      ],
      [
        "@semantic-release/release-notes-generator",
        {
          "preset": "conventionalcommits",
          "presetConfig": {
            "types": [
              {
                "type": "feat",
                "section": "Features"
              },
              {
                "type": "fix",
                "section": "Bug Fixes"
              },
              {
                "type": "chore",
                "section": "Trivial Changes"
              },
              {
                "type": "docs",
                "section": "Trivial Changes"
              },
              {
                "type": "test",
                "section": "Tests"
              }
            ]
          }
        }
      ],
      "@semantic-release/changelog",
      "@semantic-release/npm",
      "@semantic-release/github",
      "@semantic-release/git"
    ]
  }
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const b4a = require('b4a')

// https://en.wikipedia.org/wiki/Merkle_tree#Second_preimage_attack
const LEAF_TYPE = b4a.from([0])
const PARENT_TYPE = b4a.from([1])
const ROOT_TYPE = b4a.from([2])

const HYPERCORE = b4a.from('hypercore')

exports.keyPair = function (seed) {
  // key pairs might stay around for a while, so better not to use a default slab to avoid retaining it completely
  const slab = b4a.allocUnsafeSlow(
    sodium.crypto_sign_PUBLICKEYBYTES + sodium.crypto_sign_SECRETKEYBYTES
  )
  const publicKey = slab.subarray(0, sodium.crypto_sign_PUBLICKEYBYTES)
  const secretKey = slab.subarray(sodium.crypto_sign_PUBLICKEYBYTES)

  if (seed) sodium.crypto_sign_seed_keypair(publicKey, secretKey, seed)
  else sodium.crypto_sign_keypair(publicKey, secretKey)

  return {
    publicKey,
    secretKey
  }
}

exports.validateKeyPair = function (keyPair) {
  const pk = b4a.allocUnsafe(sodium.crypto_sign_PUBLICKEYBYTES)
  sodium.crypto_sign_ed25519_sk_to_pk(pk, keyPair.secretKey)
  return b4a.equals(pk, keyPair.publicKey)
}

exports.sign = function (message, secretKey) {
  // Dedicated slab for the signature, to avoid retaining unneeded mem and for security
  const signature = b4a.allocUnsafeSlow(sodium.crypto_sign_BYTES)
  sodium.crypto_sign_detached(signature, message, secretKey)
  return signature
}

exports.verify = function (message, signature, publicKey) {
  if (signature.byteLength !== sodium.crypto_sign_BYTES) return false
  if (publicKey.byteLength !== sodium.crypto_sign_PUBLICKEYBYTES) return false
  return sodium.crypto_sign_verify_detached(signature, message, publicKey)
}

exports.encrypt = function (message, publicKey) {
  const ciphertext = b4a.alloc(message.byteLength + sodium.crypto_box_SEALBYTES)
  sodium.crypto_box_seal(ciphertext, message, publicKey)
  return ciphertext
}

exports.decrypt = function (ciphertext, keyPair) {
  if (ciphertext.byteLength < sodium.crypto_box_SEALBYTES) return null

  const plaintext = b4a.alloc(ciphertext.byteLength - sodium.crypto_box_SEALBYTES)

  if (!sodium.crypto_box_seal_open(plaintext, ciphertext, keyPair.publicKey, keyPair.secretKey)) {
    return null
  }

  return plaintext
}

exports.encryptionKeyPair = function (seed) {
  const publicKey = b4a.alloc(sodium.crypto_box_PUBLICKEYBYTES)
  const secretKey = b4a.alloc(sodium.crypto_box_SECRETKEYBYTES)

  if (seed) {
    sodium.crypto_box_seed_keypair(publicKey, secretKey, seed)
  } else {
    sodium.crypto_box_keypair(publicKey, secretKey)
  }

  return {
    publicKey,
    secretKey
  }
}

exports.data = function (data) {
  const out = b4a.allocUnsafe(32)

  sodium.crypto_generichash_batch(out, [LEAF_TYPE, c.encode(c.uint64, data.byteLength), data])

  return out
}

exports.parent = function (a, b) {
  if (a.index > b.index) {
    const tmp = a
    a = b
    b = tmp
  }

  const out = b4a.allocUnsafe(32)

  sodium.crypto_generichash_batch(out, [
    PARENT_TYPE,
    c.encode(c.uint64, a.size + b.size),
    a.hash,
    b.hash
  ])

  return out
}

exports.tree = function (roots, out) {
  const buffers = new Array(3 * roots.length + 1)
  let j = 0

  buffers[j++] = ROOT_TYPE

  for (let i = 0; i < roots.length; i++) {
    const r = roots[i]
    buffers[j++] = r.hash
    buffers[j++] = c.encode(c.uint64, r.index)
    buffers[j++] = c.encode(c.uint64, r.size)
  }

  if (!out) out = b4a.allocUnsafe(32)
  sodium.crypto_generichash_batch(out, buffers)
  return out
}

exports.hash = function (data, out) {
  if (!out) out = b4a.allocUnsafe(32)
  if (!Array.isArray(data)) data = [data]

  sodium.crypto_generichash_batch(out, data)

  return out
}

exports.randomBytes = function (n) {
  const buf = b4a.allocUnsafe(n)
  sodium.randombytes_buf(buf)
  return buf
}

exports.discoveryKey = function (key) {
  if (!key || key.byteLength !== 32) throw new Error('Must pass a 32 byte buffer')
  // Discovery keys might stay around for a while, so better not to use slab memory (for better gc)
  const digest = b4a.allocUnsafeSlow(32)
  sodium.crypto_generichash(digest, HYPERCORE, key)
  return digest
}

if (sodium.sodium_free) {
  exports.free = function (secureBuf) {
    if (secureBuf.secure) sodium.sodium_free(secureBuf)
  }
} else {
  exports.free = function () {}
}

exports.namespace = function (name, count) {
  const ids = typeof count === 'number' ? range(count) : count

  // Namespaces are long-lived, so better to use a dedicated slab
  const buf = b4a.allocUnsafeSlow(32 * ids.length)

  const list = new Array(ids.length)

  // ns is ephemeral, so default slab
  const ns = b4a.allocUnsafe(33)
  sodium.crypto_generichash(ns.subarray(0, 32), typeof name === 'string' ? b4a.from(name) : name)

  for (let i = 0; i < list.length; i++) {
    list[i] = buf.subarray(32 * i, 32 * i + 32)
    ns[32] = ids[i]
    sodium.crypto_generichash(list[i], ns)
  }

  return list
}

function range(count) {
  const arr = new Array(count)
  for (let i = 0; i < count; i++) arr[i] = i
  return arr
}
{
  "name": "hypercore-crypto",
  "version": "3.7.0",
  "description": "The crypto primitives used in hypercore, extracted into a separate module",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.6.6",
    "compact-encoding": "^3.0.0",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "brittle": "^3.5.0",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/hypercore-crypto.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/hypercore-crypto/issues"
  },
  "homepage": "https://github.com/mafintosh/hypercore-crypto"
}
const c = require('compact-encoding')
const b4a = require('b4a')

const KeyChain = require('./lib/keychain')
const { sign, verify, hash } = require('./lib/crypto')

const {
  ProofEncoding,
  AttestedData,
  AttestedDevice,
  ReceiptEncoding
} = require('./lib/encoding')

const PROOF_VERSION = 1
const KEET_TYPE = 5338

const NS_PROFILE_DISC_ENC = hash(b4a.from('profile discovery'))

module.exports = class IdentityKey {
  constructor (keyChain) {
    this.keyChain = keyChain

    this.identityKeyPair = this.keyChain.get(identityKeyPath(0))
    this.profileDiscoveryKeyPair = this.keyChain.get(discoveryCorePath(0))
  }

  static generateMnemonic () {
    return KeyChain.generateMnemonic()
  }

  static deriveSeed (mnemonic) {
    return KeyChain.deriveSeed(mnemonic)
  }

  get identityPublicKey () {
    return this.identityKeyPair.publicKey
  }

  get profileDiscoveryPublicKey () {
    return this.profileDiscoveryKeyPair.publicKey
  }

  getProfileDiscoveryEncryptionKey () {
    return this.keyChain.getSymmetricKey(encryptionKeyPath(NS_PROFILE_DISC_ENC))
  }

  getEncryptionKey (profileKey) {
    return this.keyChain.getSymmetricKey(encryptionKeyPath(profileKey))
  }

  bootstrap (device) {
    return IdentityKey.bootstrap({ identity: this.identityKeyPair }, device)
  }

  clear () {
    this.keyChain.clear()
    this.identityKeyPair.secretKey.fill(0)
    this.profileDiscoveryKeyPair.secretKey.fill(0)
  }

  static async bootstrap ({ identity, seed, mnemonic }, device) {
    if (!identity) {
      const identityPath = identityKeyPath(0) // accountIndex unused for now
      identity = await KeyChain.from({ seed, mnemonic }, identityPath)
    }

    const proof = {
      version: PROOF_VERSION,
      epoch: Date.now(),
      identity: identity.publicKey,
      chain: []
    }

    return IdentityKey.attestDevice(device, identity, proof)
  }

  static attestDevice (publicKey, parent, proof) {
    if (!proof) return IdentityKey.bootstrap({ identity: parent }, publicKey)

    if (b4a.isBuffer(proof)) {
      proof = c.decode(ProofEncoding, proof)
    }

    if (proof.version === 0) {
      throw new Error('Version 0 proofs are not supported')
    }

    const signable = c.encode(AttestedDevice, {
      epoch: proof.epoch,
      identity: proof.identity,
      device: publicKey
    })

    const signature = sign(signable, parent)

    proof.chain.push({ publicKey, signature })

    return c.encode(ProofEncoding, proof)
  }

  static attestData (attestedData, keyPair, proof) {
    if (attestedData === null) throw new Error('Data is not attestable')

    if (b4a.isBuffer(proof)) {
      proof = c.decode(ProofEncoding, proof)
    }

    if (proof && proof.version === 0) {
      throw new Error('Version 0 proofs are not supported')
    }

    if (!proof) {
      proof = {
        version: PROOF_VERSION,
        epoch: Date.now(),
        identity: keyPair.publicKey,
        chain: []
      }
    }

    const signable = c.encode(AttestedData, {
      epoch: proof.epoch,
      identity: proof.identity,
      data: hash(attestedData)
    })

    proof.data = { signature: sign(signable, keyPair) }

    return c.encode(ProofEncoding, proof)
  }

  static async from ({ seed, mnemonic }) {
    const keyChain = await KeyChain.from({ seed, mnemonic })

    return new IdentityKey(keyChain)
  }

  static verify (proof, attestedData, opts = {}) {
    if (b4a.isBuffer(proof)) {
      proof = c.decode(ProofEncoding, proof)
    }

    if (!validateProof(proof, attestedData, opts)) {
      return null
    }

    const { epoch, identity, chain } = proof

    const candidate = getLastKey(chain) || identity

    if (opts.expectedDevice) {
      if (!b4a.equals(candidate, opts.expectedDevice)) return null
    }

    let parent = identity

    // verify chain
    for (let i = 0; i < chain.length; i++) {
      const { publicKey, signature } = chain[i]

      const signable = c.encode(AttestedDevice, {
        epoch,
        identity,
        device: publicKey
      })

      if (!verify(signable, signature, parent)) {
        return null
      }

      parent = publicKey
    }

    if (proof.data) {
      const signable = c.encode(AttestedData, {
        epoch,
        identity,
        data: hash(attestedData)
      })

      if (!verify(signable, proof.data.signature, parent)) {
        return null
      }
    }

    const receipt = c.encode(ReceiptEncoding, { epoch })

    return {
      receipt,
      identityPublicKey: identity,
      devicePublicKey: candidate
    }
  }
}

function validateProof (proof, attestedData, opts = {}) {
  // version 0 is ignored
  if (proof.version === 0) return false

  // validate version
  if (proof.version > PROOF_VERSION) return false

  // verify epoch
  if (opts.receipt) {
    const { epoch } = c.decode(ReceiptEncoding, opts.receipt)
    if (proof.epoch < epoch) return false
  }

  // verify identity
  if (opts.expectedIdentity) {
    if (!b4a.equals(proof.identity, opts.expectedIdentity)) return false
  }

  return validateAttestedData(proof.data, attestedData)
}

function validateAttestedData (data, attestedData) {
  if (!data && attestedData) return false
  return true
}

function getLastKey (chain) {
  if (!chain.length) return null

  const last = chain[chain.length - 1]
  return last.publicKey
}

// slip48 derivations:
// https://github.com/satoshilabs/slips/blob/master/slip-0048.md

function keyPath (accountIndex, index) {
  // https://github.com/bitcoin/bips/blob/master/bip-0043.mediawiki
  const purpose = 48 // SLIP-48 wallet
  const role = 0 // owner

  return [purpose, KEET_TYPE, role, accountIndex, index]
}

// identityKey -> m/48'/keet'/0'/0'

function identityKeyPath (accountIndex) {
  return keyPath(accountIndex, 0)
}

// identityKey -> m/48'/keet'/0'/1'

function discoveryCorePath (accountIndex) {
  return keyPath(accountIndex, 1)
}

// slip21 derivations
// https://github.com/satoshilabs/slips/blob/master/slip-0021.md

function symmetricPath (...path) {
  const purpose = 'SLIP-0021' // SLIP-21 wallet
  const namespace = 'keet-identity-key' // keet

  return [purpose, namespace, ...path]
}

// encryptionKey  -> m/SLIP-10/keet-identity-key/account/"encryption key"

function encryptionKeyPath (profileKey) {
  return symmetricPath(b4a.toString(profileKey, 'hex'), 'encryption key')
}
const sodium = require('sodium-universal')
const b4a = require('b4a')

module.exports = {
  sign,
  verify,
  hash: blake2b
}

function sign (signable, keyPair) {
  const signature = b4a.alloc(sodium.crypto_sign_BYTES)
  sodium.crypto_sign_detached(signature, signable, keyPair.secretKey)

  return signature
}

function verify (signable, signature, publicKey) {
  return sodium.crypto_sign_verify_detached(signature, signable, publicKey)
}

function blake2b (data, output = b4a.alloc(32)) {
  sodium.crypto_generichash(output, data)
  return output
}
const c = require('compact-encoding')

const ATTESTED_DEVICE = 0
const ATTESTED_DATA = 1

const Epoch = {
  preencode (state, e) {
    c.uint64.preencode(state, Math.floor(e / 1000))
  },
  encode (state, e) {
    c.uint64.encode(state, Math.floor(e / 1000))
  },
  decode (state) {
    return c.uint64.decode(state) * 1000
  }
}

const AttestedDevice = {
  preencode (state, a) {
    c.uint8.preencode(state, ATTESTED_DEVICE)
    Epoch.preencode(state, a.epoch)
    c.fixed32.preencode(state, a.identity)
    c.fixed32.preencode(state, a.device)
  },
  encode (state, a) {
    c.uint8.encode(state, ATTESTED_DEVICE)
    Epoch.encode(state, a.epoch)
    c.fixed32.encode(state, a.identity)
    c.fixed32.encode(state, a.device)
  },
  decode (state) {
    throw new Error('Signed data should only be encoded')
  }
}

const AttestedData = {
  preencode (state, a) {
    c.uint8.preencode(state, ATTESTED_DATA)
    Epoch.preencode(state, a.epoch)
    c.fixed32.preencode(state, a.identity)
    c.fixed32.preencode(state, a.data)
  },
  encode (state, a) {
    c.uint8.encode(state, ATTESTED_DATA)
    Epoch.encode(state, a.epoch)
    c.fixed32.encode(state, a.identity)
    c.fixed32.encode(state, a.data)
  },
  decode (state) {
    throw new Error('Signed data should only be encoded')
  }
}

const DeviceAttestation = {
  preencode (state, a) {
    c.fixed32.preencode(state, a.publicKey)
    c.fixed64.preencode(state, a.signature)
  },
  encode (state, a) {
    c.fixed32.encode(state, a.publicKey)
    c.fixed64.encode(state, a.signature)
  },
  decode (state) {
    return {
      publicKey: c.fixed32.decode(state),
      signature: c.fixed64.decode(state)
    }
  }
}

const DeviceAttestationArray = c.array(DeviceAttestation)

const DataAttestation = {
  preencode (state, a) {
    c.fixed64.preencode(state, a.signature)
  },
  encode (state, a) {
    c.fixed64.encode(state, a.signature)
  },
  decode (state) {
    return {
      signature: c.fixed64.decode(state)
    }
  }
}

const ProofEncoding = {
  preencode (state, proof) {
    c.uint.preencode(state, proof.version)
    Epoch.preencode(state, proof.epoch)
    c.fixed32.preencode(state, proof.identity)
    DeviceAttestationArray.preencode(state, proof.chain)

    let flags = 0
    if (proof.data) flags |= 1
    c.uint.preencode(state, flags)

    if (proof.data) DataAttestation.preencode(state, proof.data)
  },
  encode (state, proof) {
    c.uint.encode(state, proof.version)
    Epoch.encode(state, proof.epoch)
    c.fixed32.encode(state, proof.identity)
    DeviceAttestationArray.encode(state, proof.chain)

    let flags = 0
    if (proof.data) flags |= 1
    c.uint.encode(state, flags)

    if (proof.data) DataAttestation.encode(state, proof.data)
  },
  decode (state) {
    const version = c.uint.decode(state)

    // ignore v0 proofs
    if (version === 0) {
      return {
        version: 0,
        epoch: 0,
        identity: null,
        chain: [],
        data: null
      }
    }

    const epoch = Epoch.decode(state)
    const identity = c.fixed32.decode(state)
    const chain = DeviceAttestationArray.decode(state)

    const flags = c.uint.decode(state)
    const data = flags & 1 ? DataAttestation.decode(state) : null

    return {
      version,
      epoch,
      identity,
      chain,
      data
    }
  }
}

const ReceiptEncoding = {
  preencode (state, receipt) {
    Epoch.preencode(state, receipt.epoch)
  },
  encode (state, receipt) {
    Epoch.encode(state, receipt.epoch)
  },
  decode (state) {
    return {
      epoch: Epoch.decode(state)
    }
  }
}

module.exports = {
  ATTESTED_DEVICE,
  ATTESTED_DATA,
  AttestedDevice,
  AttestedData,
  ProofEncoding,
  ReceiptEncoding
}
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const assert = require('nanoassert')
const b4a = require('b4a')
const { HMAC } = require('sodium-hmac')
const bip39 = require('bip39-mnemonic')

const { sign } = require('./crypto')

const MASTER_CHAIN_CODE = b4a.from('ed25519 seed')
const MASTER_SYMMETRIC_CODE = b4a.from('Symmetric key seed')

const HARDENED_OFFSET = 0x80000000

class KeyChain {
  constructor (seed) {
    this.seed = seed

    this._buffer = b4a.alloc(64)

    this.chainKey = this._buffer.subarray(0, 32)
    this.chainCode = this._buffer.subarray(32)

    this.publicKey = b4a.alloc(sodium.crypto_sign_PUBLICKEYBYTES)
    this.secretKey = b4a.alloc(sodium.crypto_sign_SECRETKEYBYTES)

    this._initialise()
  }

  static generateMnemonic () {
    return bip39.generateMnemonic()
  }

  static deriveSeed (mnemonic) {
    return bip39.mnemonicToSeed(mnemonic)
  }

  static async from ({ mnemonic, seed }, path) {
    assert(mnemonic || seed, 'No mnemonic or seed was passed.')

    if (!seed) seed = await KeyChain.deriveSeed(mnemonic)

    const key = new KeyChain(seed)

    if (!path) return key

    return key.get(path)
  }

  getSymmetricKey (path) {
    const buffer = b4a.alloc(64)

    const chainKey = buffer.subarray(0, 32)
    const key = buffer.subarray(32)

    HMAC.sha512(this.seed, MASTER_SYMMETRIC_CODE, buffer)

    for (const step of path) {
      const label = b4a.alloc(step.length + 1)
      b4a.write(label, step, 1, 'utf8')

      HMAC.sha512(label, chainKey, buffer)
    }

    return key
  }

  get isKeychain () {
    return true
  }

  _initialise () {
    HMAC.sha512(this.seed, MASTER_CHAIN_CODE, this._buffer)
    sodium.crypto_sign_seed_keypair(this.publicKey, this.secretKey, this.chainKey)
  }

  clear () {
    this.secretKey.fill(0)
    this.chainKey.fill(0)
    this.chainCode.fill(0)
  }

  get (path) {
    return this.derive(path)
  }

  sign (signable) {
    return sign(signable, this)
  }

  derive (path) {
    const buffer = b4a.from(this._buffer)

    const chainKey = buffer.subarray(0, 32)
    const chainCode = buffer.subarray(32)

    for (const step of path) {
      const index = ensureHardened(step) // hardened indices are >= 2^31
      HMAC.sha512(encodeDerivationData(chainKey, index), chainCode, buffer)
    }

    return createKeyPair(chainKey)
  }
}

module.exports = KeyChain

function createKeyPair (seed) {
  if (!seed) throw new Error('No seed provided')

  const publicKey = b4a.alloc(sodium.crypto_sign_PUBLICKEYBYTES)
  const secretKey = b4a.alloc(sodium.crypto_sign_SECRETKEYBYTES)

  sodium.crypto_sign_seed_keypair(publicKey, secretKey, seed)

  return {
    publicKey,
    secretKey
  }
}

function encodeDerivationData (key, step) {
  const state = { buffer: b4a.alloc(37), start: 0, end: 37 }

  c.uint8.encode(state, 0)
  c.fixed32.encode(state, key)
  state.buffer.writeUInt32BE(step, state.start)

  state.buffer[33] |= 0x80

  return state.buffer
}

function ensureHardened (n) {
  if (n >= HARDENED_OFFSET) return n
  return n + HARDENED_OFFSET
}
{
  "name": "keet-identity-key",
  "version": "3.2.0",
  "description": "Hierarchical Deterministic Keys for Keet Identities",
  "main": "index.js",
  "scripts": {
    "test": "standard && brittle test/*.js"
  },
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "devDependencies": {
    "brittle": "^3.3.2",
    "hypercore-crypto": "^3.4.0",
    "standard": "^17.1.0"
  },
  "dependencies": {
    "b4a": "^1.6.4",
    "bip39-mnemonic": "^2.2.0",
    "compact-encoding": "^3.0.0",
    "nanoassert": "^2.0.0",
    "sodium-hmac": "^2.0.1",
    "sodium-universal": "^5.0.1"
  },
  "files": [
    "lib/*"
  ],
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/keet-identity-key.git"
  },
  "bugs": {
    "url": "https://github.com/holepunchto/keet-identity-key/issues"
  },
  "homepage": "https://github.com/holepunchto/keet-identity-key#readme"
}
import { coerce } from '../bytes.js';
import basex from '../vendor/base-x.js';
/**
 * Class represents both BaseEncoder and MultibaseEncoder meaning it
 * can be used to encode to multibase or base encode without multibase
 * prefix.
 */
class Encoder {
    name;
    prefix;
    baseEncode;
    constructor(name, prefix, baseEncode) {
        this.name = name;
        this.prefix = prefix;
        this.baseEncode = baseEncode;
    }
    encode(bytes) {
        if (bytes instanceof Uint8Array) {
            return `${this.prefix}${this.baseEncode(bytes)}`;
        }
        else {
            throw Error('Unknown type, must be binary type');
        }
    }
}
/**
 * Class represents both BaseDecoder and MultibaseDecoder so it could be used
 * to decode multibases (with matching prefix) or just base decode strings
 * with corresponding base encoding.
 */
class Decoder {
    name;
    prefix;
    baseDecode;
    prefixCodePoint;
    constructor(name, prefix, baseDecode) {
        this.name = name;
        this.prefix = prefix;
        const prefixCodePoint = prefix.codePointAt(0);
        /* c8 ignore next 3 */
        if (prefixCodePoint === undefined) {
            throw new Error('Invalid prefix character');
        }
        this.prefixCodePoint = prefixCodePoint;
        this.baseDecode = baseDecode;
    }
    decode(text) {
        if (typeof text === 'string') {
            if (text.codePointAt(0) !== this.prefixCodePoint) {
                throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);
            }
            return this.baseDecode(text.slice(this.prefix.length));
        }
        else {
            throw Error('Can only multibase decode strings');
        }
    }
    or(decoder) {
        return or(this, decoder);
    }
}
class ComposedDecoder {
    decoders;
    constructor(decoders) {
        this.decoders = decoders;
    }
    or(decoder) {
        return or(this, decoder);
    }
    decode(input) {
        const prefix = input[0];
        const decoder = this.decoders[prefix];
        if (decoder != null) {
            return decoder.decode(input);
        }
        else {
            throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);
        }
    }
}
export function or(left, right) {
    return new ComposedDecoder({
        ...(left.decoders ?? { [left.prefix]: left }),
        ...(right.decoders ?? { [right.prefix]: right })
    });
}
export class Codec {
    name;
    prefix;
    baseEncode;
    baseDecode;
    encoder;
    decoder;
    constructor(name, prefix, baseEncode, baseDecode) {
        this.name = name;
        this.prefix = prefix;
        this.baseEncode = baseEncode;
        this.baseDecode = baseDecode;
        this.encoder = new Encoder(name, prefix, baseEncode);
        this.decoder = new Decoder(name, prefix, baseDecode);
    }
    encode(input) {
        return this.encoder.encode(input);
    }
    decode(input) {
        return this.decoder.decode(input);
    }
}
export function from({ name, prefix, encode, decode }) {
    return new Codec(name, prefix, encode, decode);
}
export function baseX({ name, prefix, alphabet }) {
    const { encode, decode } = basex(alphabet, name);
    return from({
        prefix,
        name,
        encode,
        decode: (text) => coerce(decode(text))
    });
}
function decode(string, alphabetIdx, bitsPerChar, name) {
    // Count the padding bytes:
    let end = string.length;
    while (string[end - 1] === '=') {
        --end;
    }
    // Allocate the output:
    const out = new Uint8Array((end * bitsPerChar / 8) | 0);
    // Parse the data:
    let bits = 0; // Number of bits currently in the buffer
    let buffer = 0; // Bits waiting to be written out, MSB first
    let written = 0; // Next byte to write
    for (let i = 0; i < end; ++i) {
        // Read one character from the string:
        const value = alphabetIdx[string[i]];
        if (value === undefined) {
            throw new SyntaxError(`Non-${name} character`);
        }
        // Append the bits to the buffer:
        buffer = (buffer << bitsPerChar) | value;
        bits += bitsPerChar;
        // Write out some bits if the buffer has a byte's worth:
        if (bits >= 8) {
            bits -= 8;
            out[written++] = 0xff & (buffer >> bits);
        }
    }
    // Verify that we have received just enough bits:
    if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {
        throw new SyntaxError('Unexpected end of data');
    }
    return out;
}
function encode(data, alphabet, bitsPerChar) {
    const pad = alphabet[alphabet.length - 1] === '=';
    const mask = (1 << bitsPerChar) - 1;
    let out = '';
    let bits = 0; // Number of bits currently in the buffer
    let buffer = 0; // Bits waiting to be written out, MSB first
    for (let i = 0; i < data.length; ++i) {
        // Slurp data into the buffer:
        buffer = (buffer << 8) | data[i];
        bits += 8;
        // Write out as much as we can:
        while (bits > bitsPerChar) {
            bits -= bitsPerChar;
            out += alphabet[mask & (buffer >> bits)];
        }
    }
    // Partial character:
    if (bits !== 0) {
        out += alphabet[mask & (buffer << (bitsPerChar - bits))];
    }
    // Add padding characters until we hit a byte boundary:
    if (pad) {
        while (((out.length * bitsPerChar) & 7) !== 0) {
            out += '=';
        }
    }
    return out;
}
function createAlphabetIdx(alphabet) {
    // Build the character lookup table:
    const alphabetIdx = {};
    for (let i = 0; i < alphabet.length; ++i) {
        alphabetIdx[alphabet[i]] = i;
    }
    return alphabetIdx;
}
/**
 * RFC4648 Factory
 */
export function rfc4648({ name, prefix, bitsPerChar, alphabet }) {
    const alphabetIdx = createAlphabetIdx(alphabet);
    return from({
        prefix,
        name,
        encode(input) {
            return encode(input, alphabet, bitsPerChar);
        },
        decode(input) {
            return decode(input, alphabetIdx, bitsPerChar, name);
        }
    });
}
//# sourceMappingURL=base.js.mapimport { rfc4648 } from './base.js';
export const base32 = rfc4648({
    prefix: 'b',
    name: 'base32',
    alphabet: 'abcdefghijklmnopqrstuvwxyz234567',
    bitsPerChar: 5
});
export const base32upper = rfc4648({
    prefix: 'B',
    name: 'base32upper',
    alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',
    bitsPerChar: 5
});
export const base32pad = rfc4648({
    prefix: 'c',
    name: 'base32pad',
    alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',
    bitsPerChar: 5
});
export const base32padupper = rfc4648({
    prefix: 'C',
    name: 'base32padupper',
    alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',
    bitsPerChar: 5
});
export const base32hex = rfc4648({
    prefix: 'v',
    name: 'base32hex',
    alphabet: '0123456789abcdefghijklmnopqrstuv',
    bitsPerChar: 5
});
export const base32hexupper = rfc4648({
    prefix: 'V',
    name: 'base32hexupper',
    alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',
    bitsPerChar: 5
});
export const base32hexpad = rfc4648({
    prefix: 't',
    name: 'base32hexpad',
    alphabet: '0123456789abcdefghijklmnopqrstuv=',
    bitsPerChar: 5
});
export const base32hexpadupper = rfc4648({
    prefix: 'T',
    name: 'base32hexpadupper',
    alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',
    bitsPerChar: 5
});
export const base32z = rfc4648({
    prefix: 'h',
    name: 'base32z',
    alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',
    bitsPerChar: 5
});
//# sourceMappingURL=base32.js.mapimport { baseX } from './base.js';
export const base36 = baseX({
    prefix: 'k',
    name: 'base36',
    alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'
});
export const base36upper = baseX({
    prefix: 'K',
    name: 'base36upper',
    alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
});
//# sourceMappingURL=base36.js.mapimport { baseX } from './base.js';
export const base58btc = baseX({
    name: 'base58btc',
    prefix: 'z',
    alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
});
export const base58flickr = baseX({
    name: 'base58flickr',
    prefix: 'Z',
    alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'
});
//# sourceMappingURL=base58.js.mapimport { rfc4648 } from './base.js';
export const base64 = rfc4648({
    prefix: 'm',
    name: 'base64',
    alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',
    bitsPerChar: 6
});
export const base64pad = rfc4648({
    prefix: 'M',
    name: 'base64pad',
    alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',
    bitsPerChar: 6
});
export const base64url = rfc4648({
    prefix: 'u',
    name: 'base64url',
    alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',
    bitsPerChar: 6
});
export const base64urlpad = rfc4648({
    prefix: 'U',
    name: 'base64urlpad',
    alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',
    bitsPerChar: 6
});
//# sourceMappingURL=base64.js.mapexport const empty = new Uint8Array(0);
export function toHex(d) {
    return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '');
}
export function fromHex(hex) {
    const hexes = hex.match(/../g);
    return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty;
}
export function equals(aa, bb) {
    if (aa === bb) {
        return true;
    }
    if (aa.byteLength !== bb.byteLength) {
        return false;
    }
    for (let ii = 0; ii < aa.byteLength; ii++) {
        if (aa[ii] !== bb[ii]) {
            return false;
        }
    }
    return true;
}
export function coerce(o) {
    if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') {
        return o;
    }
    if (o instanceof ArrayBuffer) {
        return new Uint8Array(o);
    }
    if (ArrayBuffer.isView(o)) {
        return new Uint8Array(o.buffer, o.byteOffset, o.byteLength);
    }
    throw new Error('Unknown type, must be binary type');
}
export function isBinary(o) {
    return o instanceof ArrayBuffer || ArrayBuffer.isView(o);
}
export function fromString(str) {
    return new TextEncoder().encode(str);
}
export function toString(b) {
    return new TextDecoder().decode(b);
}
//# sourceMappingURL=bytes.js.mapimport { base32 } from './bases/base32.js';
import { base36 } from './bases/base36.js';
import { base58btc } from './bases/base58.js';
import { coerce } from './bytes.js';
import * as Digest from './hashes/digest.js';
import * as varint from './varint.js';
// This way TS will also expose all the types from module
export * from './link/interface.js';
export function format(link, base) {
    const { bytes, version } = link;
    switch (version) {
        case 0:
            return toStringV0(bytes, baseCache(link), base ?? base58btc.encoder);
        default:
            return toStringV1(bytes, baseCache(link), (base ?? base32.encoder));
    }
}
export function toJSON(link) {
    return {
        '/': format(link)
    };
}
export function fromJSON(json) {
    return CID.parse(json['/']);
}
const cache = new WeakMap();
function baseCache(cid) {
    const baseCache = cache.get(cid);
    if (baseCache == null) {
        const baseCache = new Map();
        cache.set(cid, baseCache);
        return baseCache;
    }
    return baseCache;
}
export class CID {
    code;
    version;
    multihash;
    bytes;
    '/';
    /**
     * @param version - Version of the CID
     * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
     * @param multihash - (Multi)hash of the of the content.
     */
    constructor(version, code, multihash, bytes) {
        this.code = code;
        this.version = version;
        this.multihash = multihash;
        this.bytes = bytes;
        // flag to serializers that this is a CID and
        // should be treated specially
        this['/'] = bytes;
    }
    /**
     * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`
     * please either use `CID.asCID(cid)` or switch to new signalling mechanism
     *
     * @deprecated
     */
    get asCID() {
        return this;
    }
    // ArrayBufferView
    get byteOffset() {
        return this.bytes.byteOffset;
    }
    // ArrayBufferView
    get byteLength() {
        return this.bytes.byteLength;
    }
    toV0() {
        switch (this.version) {
            case 0: {
                return this;
            }
            case 1: {
                const { code, multihash } = this;
                if (code !== DAG_PB_CODE) {
                    throw new Error('Cannot convert a non dag-pb CID to CIDv0');
                }
                // sha2-256
                if (multihash.code !== SHA_256_CODE) {
                    throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0');
                }
                return (CID.createV0(multihash));
            }
            default: {
                throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);
            }
        }
    }
    toV1() {
        switch (this.version) {
            case 0: {
                const { code, digest } = this.multihash;
                const multihash = Digest.create(code, digest);
                return (CID.createV1(this.code, multihash));
            }
            case 1: {
                return this;
            }
            default: {
                throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);
            }
        }
    }
    equals(other) {
        return CID.equals(this, other);
    }
    static equals(self, other) {
        const unknown = other;
        return (unknown != null &&
            self.code === unknown.code &&
            self.version === unknown.version &&
            Digest.equals(self.multihash, unknown.multihash));
    }
    toString(base) {
        return format(this, base);
    }
    toJSON() {
        return { '/': format(this) };
    }
    link() {
        return this;
    }
    [Symbol.toStringTag] = 'CID';
    // Legacy
    [Symbol.for('nodejs.util.inspect.custom')]() {
        return `CID(${this.toString()})`;
    }
    /**
     * Takes any input `value` and returns a `CID` instance if it was
     * a `CID` otherwise returns `null`. If `value` is instanceof `CID`
     * it will return value back. If `value` is not instance of this CID
     * class, but is compatible CID it will return new instance of this
     * `CID` class. Otherwise returns null.
     *
     * This allows two different incompatible versions of CID library to
     * co-exist and interop as long as binary interface is compatible.
     */
    static asCID(input) {
        if (input == null) {
            return null;
        }
        const value = input;
        if (value instanceof CID) {
            // If value is instance of CID then we're all set.
            return value;
        }
        else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {
            // If value isn't instance of this CID class but `this.asCID === this` or
            // `value['/'] === value.bytes` is true it is CID instance coming from a
            // different implementation (diff version or duplicate). In that case we
            // rebase it to this `CID` implementation so caller is guaranteed to get
            // instance with expected API.
            const { version, code, multihash, bytes } = value;
            return new CID(version, code, multihash, bytes ?? encodeCID(version, code, multihash.bytes));
        }
        else if (value[cidSymbol] === true) {
            // If value is a CID from older implementation that used to be tagged via
            // symbol we still rebase it to the this `CID` implementation by
            // delegating that to a constructor.
            const { version, multihash, code } = value;
            const digest = Digest.decode(multihash);
            return CID.create(version, code, digest);
        }
        else {
            // Otherwise value is not a CID (or an incompatible version of it) in
            // which case we return `null`.
            return null;
        }
    }
    /**
     * @param version - Version of the CID
     * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
     * @param digest - (Multi)hash of the of the content.
     */
    static create(version, code, digest) {
        if (typeof code !== 'number') {
            throw new Error('String codecs are no longer supported');
        }
        if (!(digest.bytes instanceof Uint8Array)) {
            throw new Error('Invalid digest');
        }
        switch (version) {
            case 0: {
                if (code !== DAG_PB_CODE) {
                    throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);
                }
                else {
                    return new CID(version, code, digest, digest.bytes);
                }
            }
            case 1: {
                const bytes = encodeCID(version, code, digest.bytes);
                return new CID(version, code, digest, bytes);
            }
            default: {
                throw new Error('Invalid version');
            }
        }
    }
    /**
     * Simplified version of `create` for CIDv0.
     */
    static createV0(digest) {
        return CID.create(0, DAG_PB_CODE, digest);
    }
    /**
     * Simplified version of `create` for CIDv1.
     *
     * @param code - Content encoding format code.
     * @param digest - Multihash of the content.
     */
    static createV1(code, digest) {
        return CID.create(1, code, digest);
    }
    /**
     * Decoded a CID from its binary representation. The byte array must contain
     * only the CID with no additional bytes.
     *
     * An error will be thrown if the bytes provided do not contain a valid
     * binary representation of a CID.
     */
    static decode(bytes) {
        const [cid, remainder] = CID.decodeFirst(bytes);
        if (remainder.length !== 0) {
            throw new Error('Incorrect length');
        }
        return cid;
    }
    /**
     * Decoded a CID from its binary representation at the beginning of a byte
     * array.
     *
     * Returns an array with the first element containing the CID and the second
     * element containing the remainder of the original byte array. The remainder
     * will be a zero-length byte array if the provided bytes only contained a
     * binary CID representation.
     */
    static decodeFirst(bytes) {
        const specs = CID.inspectBytes(bytes);
        const prefixSize = specs.size - specs.multihashSize;
        const multihashBytes = coerce(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));
        if (multihashBytes.byteLength !== specs.multihashSize) {
            throw new Error('Incorrect length');
        }
        const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);
        const digest = new Digest.Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);
        const cid = specs.version === 0
            ? CID.createV0(digest)
            : CID.createV1(specs.codec, digest);
        return [cid, bytes.subarray(specs.size)];
    }
    /**
     * Inspect the initial bytes of a CID to determine its properties.
     *
     * Involves decoding up to 4 varints. Typically this will require only 4 to 6
     * bytes but for larger multicodec code values and larger multihash digest
     * lengths these varints can be quite large. It is recommended that at least
     * 10 bytes be made available in the `initialBytes` argument for a complete
     * inspection.
     */
    static inspectBytes(initialBytes) {
        let offset = 0;
        const next = () => {
            const [i, length] = varint.decode(initialBytes.subarray(offset));
            offset += length;
            return i;
        };
        let version = next();
        let codec = DAG_PB_CODE;
        if (version === 18) {
            // CIDv0
            version = 0;
            offset = 0;
        }
        else {
            codec = next();
        }
        if (version !== 0 && version !== 1) {
            throw new RangeError(`Invalid CID version ${version}`);
        }
        const prefixSize = offset;
        const multihashCode = next(); // multihash code
        const digestSize = next(); // multihash length
        const size = offset + digestSize;
        const multihashSize = size - prefixSize;
        return { version, codec, multihashCode, digestSize, multihashSize, size };
    }
    /**
     * Takes cid in a string representation and creates an instance. If `base`
     * decoder is not provided will use a default from the configuration. It will
     * throw an error if encoding of the CID is not compatible with supplied (or
     * a default decoder).
     */
    static parse(source, base) {
        const [prefix, bytes] = parseCIDtoBytes(source, base);
        const cid = CID.decode(bytes);
        if (cid.version === 0 && source[0] !== 'Q') {
            throw Error('Version 0 CID string must not include multibase prefix');
        }
        // Cache string representation to avoid computing it on `this.toString()`
        baseCache(cid).set(prefix, source);
        return cid;
    }
}
function parseCIDtoBytes(source, base) {
    switch (source[0]) {
        // CIDv0 is parsed differently
        case 'Q': {
            const decoder = base ?? base58btc;
            return [
                base58btc.prefix,
                decoder.decode(`${base58btc.prefix}${source}`)
            ];
        }
        case base58btc.prefix: {
            const decoder = base ?? base58btc;
            return [base58btc.prefix, decoder.decode(source)];
        }
        case base32.prefix: {
            const decoder = base ?? base32;
            return [base32.prefix, decoder.decode(source)];
        }
        case base36.prefix: {
            const decoder = base ?? base36;
            return [base36.prefix, decoder.decode(source)];
        }
        default: {
            if (base == null) {
                throw Error('To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided');
            }
            return [source[0], base.decode(source)];
        }
    }
}
function toStringV0(bytes, cache, base) {
    const { prefix } = base;
    if (prefix !== base58btc.prefix) {
        throw Error(`Cannot string encode V0 in ${base.name} encoding`);
    }
    const cid = cache.get(prefix);
    if (cid == null) {
        const cid = base.encode(bytes).slice(1);
        cache.set(prefix, cid);
        return cid;
    }
    else {
        return cid;
    }
}
function toStringV1(bytes, cache, base) {
    const { prefix } = base;
    const cid = cache.get(prefix);
    if (cid == null) {
        const cid = base.encode(bytes);
        cache.set(prefix, cid);
        return cid;
    }
    else {
        return cid;
    }
}
const DAG_PB_CODE = 0x70;
const SHA_256_CODE = 0x12;
function encodeCID(version, code, multihash) {
    const codeOffset = varint.encodingLength(version);
    const hashOffset = codeOffset + varint.encodingLength(code);
    const bytes = new Uint8Array(hashOffset + multihash.byteLength);
    varint.encodeTo(version, bytes, 0);
    varint.encodeTo(code, bytes, codeOffset);
    bytes.set(multihash, hashOffset);
    return bytes;
}
const cidSymbol = Symbol.for('@ipld/js-cid/CID');
//# sourceMappingURL=cid.js.mapimport { coerce, equals as equalBytes } from '../bytes.js';
import * as varint from '../varint.js';
/**
 * Creates a multihash digest.
 */
export function create(code, digest) {
    const size = digest.byteLength;
    const sizeOffset = varint.encodingLength(code);
    const digestOffset = sizeOffset + varint.encodingLength(size);
    const bytes = new Uint8Array(digestOffset + size);
    varint.encodeTo(code, bytes, 0);
    varint.encodeTo(size, bytes, sizeOffset);
    bytes.set(digest, digestOffset);
    return new Digest(code, size, digest, bytes);
}
/**
 * Turns bytes representation of multihash digest into an instance.
 */
export function decode(multihash) {
    const bytes = coerce(multihash);
    const [code, sizeOffset] = varint.decode(bytes);
    const [size, digestOffset] = varint.decode(bytes.subarray(sizeOffset));
    const digest = bytes.subarray(sizeOffset + digestOffset);
    if (digest.byteLength !== size) {
        throw new Error('Incorrect length');
    }
    return new Digest(code, size, digest, bytes);
}
export function equals(a, b) {
    if (a === b) {
        return true;
    }
    else {
        const data = b;
        return (a.code === data.code &&
            a.size === data.size &&
            data.bytes instanceof Uint8Array &&
            equalBytes(a.bytes, data.bytes));
    }
}
/**
 * Represents a multihash digest which carries information about the
 * hashing algorithm and an actual hash digest.
 */
export class Digest {
    code;
    size;
    digest;
    bytes;
    /**
     * Creates a multihash digest.
     */
    constructor(code, size, digest, bytes) {
        this.code = code;
        this.size = size;
        this.digest = digest;
        this.bytes = bytes;
    }
}
/**
 * Used to check that the passed multihash has the passed code
 */
export function hasCode(digest, code) {
    return digest.code === code;
}
//# sourceMappingURL=digest.js.mapexport {};
//# sourceMappingURL=interface.js.mapimport varint from './vendor/varint.js';
export function decode(data, offset = 0) {
    const code = varint.decode(data, offset);
    return [code, varint.decode.bytes];
}
export function encodeTo(int, target, offset = 0) {
    varint.encode(int, target, offset);
    return target;
}
export function encodingLength(int) {
    return varint.encodingLength(int);
}
//# sourceMappingURL=varint.js.map/* eslint-disable */
// base-x encoding / decoding
// Copyright (c) 2018 base-x contributors
// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)
// Distributed under the MIT software license, see the accompanying
// file LICENSE or http://www.opensource.org/licenses/mit-license.php.
/**
 * @param {string} ALPHABET
 * @param {any} name
 */
function base(ALPHABET, name) {
    if (ALPHABET.length >= 255) {
        throw new TypeError('Alphabet too long');
    }
    var BASE_MAP = new Uint8Array(256);
    for (var j = 0; j < BASE_MAP.length; j++) {
        BASE_MAP[j] = 255;
    }
    for (var i = 0; i < ALPHABET.length; i++) {
        var x = ALPHABET.charAt(i);
        var xc = x.charCodeAt(0);
        if (BASE_MAP[xc] !== 255) {
            throw new TypeError(x + ' is ambiguous');
        }
        BASE_MAP[xc] = i;
    }
    var BASE = ALPHABET.length;
    var LEADER = ALPHABET.charAt(0);
    var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up
    var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up
    /**
     * @param {any[] | Iterable<number>} source
     */
    function encode(source) {
        // @ts-ignore
        if (source instanceof Uint8Array)
            ;
        else if (ArrayBuffer.isView(source)) {
            source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
        }
        else if (Array.isArray(source)) {
            source = Uint8Array.from(source);
        }
        if (!(source instanceof Uint8Array)) {
            throw new TypeError('Expected Uint8Array');
        }
        if (source.length === 0) {
            return '';
        }
        // Skip & count leading zeroes.
        var zeroes = 0;
        var length = 0;
        var pbegin = 0;
        var pend = source.length;
        while (pbegin !== pend && source[pbegin] === 0) {
            pbegin++;
            zeroes++;
        }
        // Allocate enough space in big-endian base58 representation.
        var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;
        var b58 = new Uint8Array(size);
        // Process the bytes.
        while (pbegin !== pend) {
            var carry = source[pbegin];
            // Apply "b58 = b58 * 256 + ch".
            var i = 0;
            for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {
                carry += (256 * b58[it1]) >>> 0;
                b58[it1] = (carry % BASE) >>> 0;
                carry = (carry / BASE) >>> 0;
            }
            if (carry !== 0) {
                throw new Error('Non-zero carry');
            }
            length = i;
            pbegin++;
        }
        // Skip leading zeroes in base58 result.
        var it2 = size - length;
        while (it2 !== size && b58[it2] === 0) {
            it2++;
        }
        // Translate the result into a string.
        var str = LEADER.repeat(zeroes);
        for (; it2 < size; ++it2) {
            str += ALPHABET.charAt(b58[it2]);
        }
        return str;
    }
    /**
     * @param {string | string[]} source
     */
    function decodeUnsafe(source) {
        if (typeof source !== 'string') {
            throw new TypeError('Expected String');
        }
        if (source.length === 0) {
            return new Uint8Array();
        }
        var psz = 0;
        // Skip leading spaces.
        if (source[psz] === ' ') {
            return;
        }
        // Skip and count leading '1's.
        var zeroes = 0;
        var length = 0;
        while (source[psz] === LEADER) {
            zeroes++;
            psz++;
        }
        // Allocate enough space in big-endian base256 representation.
        var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.
        var b256 = new Uint8Array(size);
        // Process the characters.
        while (source[psz]) {
            // Decode character
            var carry = BASE_MAP[source.charCodeAt(psz)];
            // Invalid character
            if (carry === 255) {
                return;
            }
            var i = 0;
            for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {
                carry += (BASE * b256[it3]) >>> 0;
                b256[it3] = (carry % 256) >>> 0;
                carry = (carry / 256) >>> 0;
            }
            if (carry !== 0) {
                throw new Error('Non-zero carry');
            }
            length = i;
            psz++;
        }
        // Skip trailing spaces.
        if (source[psz] === ' ') {
            return;
        }
        // Skip leading zeroes in b256.
        var it4 = size - length;
        while (it4 !== size && b256[it4] === 0) {
            it4++;
        }
        var vch = new Uint8Array(zeroes + (size - it4));
        var j = zeroes;
        while (it4 !== size) {
            vch[j++] = b256[it4++];
        }
        return vch;
    }
    /**
     * @param {string | string[]} string
     */
    function decode(string) {
        var buffer = decodeUnsafe(string);
        if (buffer) {
            return buffer;
        }
        throw new Error(`Non-${name} character`);
    }
    return {
        encode: encode,
        decodeUnsafe: decodeUnsafe,
        decode: decode
    };
}
var src = base;
var _brrp__multiformats_scope_baseX = src;
export default _brrp__multiformats_scope_baseX;
//# sourceMappingURL=base-x.js.map/* eslint-disable */
var encode_1 = encode;
var MSB = 0x80, REST = 0x7F, MSBALL = ~REST, INT = Math.pow(2, 31);
/**
 * @param {number} num
 * @param {number[]} out
 * @param {number} offset
 */
function encode(num, out, offset) {
    out = out || [];
    offset = offset || 0;
    var oldOffset = offset;
    while (num >= INT) {
        out[offset++] = (num & 0xFF) | MSB;
        num /= 128;
    }
    while (num & MSBALL) {
        out[offset++] = (num & 0xFF) | MSB;
        num >>>= 7;
    }
    out[offset] = num | 0;
    // @ts-ignore
    encode.bytes = offset - oldOffset + 1;
    return out;
}
var decode = read;
var MSB$1 = 0x80, REST$1 = 0x7F;
/**
 * @param {string | any[]} buf
 * @param {number} offset
 */
function read(buf, offset) {
    var res = 0, offset = offset || 0, shift = 0, counter = offset, b, l = buf.length;
    do {
        if (counter >= l) {
            // @ts-ignore
            read.bytes = 0;
            throw new RangeError('Could not decode varint');
        }
        b = buf[counter++];
        res += shift < 28
            ? (b & REST$1) << shift
            : (b & REST$1) * Math.pow(2, shift);
        shift += 7;
    } while (b >= MSB$1);
    // @ts-ignore
    read.bytes = counter - offset;
    return res;
}
var N1 = Math.pow(2, 7);
var N2 = Math.pow(2, 14);
var N3 = Math.pow(2, 21);
var N4 = Math.pow(2, 28);
var N5 = Math.pow(2, 35);
var N6 = Math.pow(2, 42);
var N7 = Math.pow(2, 49);
var N8 = Math.pow(2, 56);
var N9 = Math.pow(2, 63);
var length = function (/** @type {number} */ value) {
    return (value < N1 ? 1
        : value < N2 ? 2
            : value < N3 ? 3
                : value < N4 ? 4
                    : value < N5 ? 5
                        : value < N6 ? 6
                            : value < N7 ? 7
                                : value < N8 ? 8
                                    : value < N9 ? 9
                                        : 10);
};
var varint = {
    encode: encode_1,
    decode: decode,
    encodingLength: length
};
var _brrp_varint = varint;
export default _brrp_varint;
//# sourceMappingURL=varint.js.map{
  "name": "multiformats",
  "version": "13.4.2",
  "description": "Interface for multihash, multicodec, multibase and CID",
  "author": "Mikeal Rogers <mikeal.rogers@gmail.com> (https://www.mikealrogers.com/)",
  "license": "Apache-2.0 OR MIT",
  "homepage": "https://github.com/multiformats/js-multiformats#readme",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/multiformats/js-multiformats.git"
  },
  "bugs": {
    "url": "https://github.com/multiformats/js-multiformats/issues"
  },
  "publishConfig": {
    "access": "public",
    "provenance": true
  },
  "keywords": [
    "ipfs",
    "ipld",
    "multiformats"
  ],
  "type": "module",
  "types": "./dist/src/index.d.ts",
  "typesVersions": {
    "*": {
      "*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ],
      "src/*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ]
    }
  },
  "files": [
    "src",
    "dist",
    "!dist/test",
    "!**/*.tsbuildinfo"
  ],
  "exports": {
    ".": {
      "types": "./dist/src/index.d.ts",
      "import": "./dist/src/index.js"
    },
    "./bases/base10": {
      "types": "./dist/src/bases/base10.d.ts",
      "import": "./dist/src/bases/base10.js"
    },
    "./bases/base16": {
      "types": "./dist/src/bases/base16.d.ts",
      "import": "./dist/src/bases/base16.js"
    },
    "./bases/base2": {
      "types": "./dist/src/bases/base2.d.ts",
      "import": "./dist/src/bases/base2.js"
    },
    "./bases/base256emoji": {
      "types": "./dist/src/bases/base256emoji.d.ts",
      "import": "./dist/src/bases/base256emoji.js"
    },
    "./bases/base32": {
      "types": "./dist/src/bases/base32.d.ts",
      "import": "./dist/src/bases/base32.js"
    },
    "./bases/base36": {
      "types": "./dist/src/bases/base36.d.ts",
      "import": "./dist/src/bases/base36.js"
    },
    "./bases/base58": {
      "types": "./dist/src/bases/base58.d.ts",
      "import": "./dist/src/bases/base58.js"
    },
    "./bases/base64": {
      "types": "./dist/src/bases/base64.d.ts",
      "import": "./dist/src/bases/base64.js"
    },
    "./bases/base8": {
      "types": "./dist/src/bases/base8.d.ts",
      "import": "./dist/src/bases/base8.js"
    },
    "./bases/identity": {
      "types": "./dist/src/bases/identity.d.ts",
      "import": "./dist/src/bases/identity.js"
    },
    "./bases/interface": {
      "types": "./dist/src/bases/interface.d.ts",
      "import": "./dist/src/bases/interface.js"
    },
    "./basics": {
      "types": "./dist/src/basics.d.ts",
      "import": "./dist/src/basics.js"
    },
    "./block": {
      "types": "./dist/src/block.d.ts",
      "import": "./dist/src/block.js"
    },
    "./block/interface": {
      "types": "./dist/src/block/interface.d.ts",
      "import": "./dist/src/block/interface.js"
    },
    "./bytes": {
      "types": "./dist/src/bytes.d.ts",
      "import": "./dist/src/bytes.js"
    },
    "./cid": {
      "types": "./dist/src/cid.d.ts",
      "import": "./dist/src/cid.js"
    },
    "./codecs/interface": {
      "types": "./dist/src/codecs/interface.d.ts",
      "import": "./dist/src/codecs/interface.js"
    },
    "./codecs/json": {
      "types": "./dist/src/codecs/json.d.ts",
      "import": "./dist/src/codecs/json.js"
    },
    "./codecs/raw": {
      "types": "./dist/src/codecs/raw.d.ts",
      "import": "./dist/src/codecs/raw.js"
    },
    "./hashes/digest": {
      "types": "./dist/src/hashes/digest.d.ts",
      "import": "./dist/src/hashes/digest.js"
    },
    "./hashes/hasher": {
      "types": "./dist/src/hashes/hasher.d.ts",
      "import": "./dist/src/hashes/hasher.js"
    },
    "./hashes/identity": {
      "types": "./dist/src/hashes/identity.d.ts",
      "import": "./dist/src/hashes/identity.js"
    },
    "./hashes/interface": {
      "types": "./dist/src/hashes/interface.d.ts",
      "import": "./dist/src/hashes/interface.js"
    },
    "./hashes/sha1": {
      "types": "./dist/types/src/hashes/sha1.d.ts",
      "browser": "./dist/src/hashes/sha1-browser.js",
      "import": "./dist/src/hashes/sha1.js"
    },
    "./hashes/sha2": {
      "types": "./dist/src/hashes/sha2.d.ts",
      "browser": "./dist/src/hashes/sha2-browser.js",
      "import": "./dist/src/hashes/sha2.js"
    },
    "./interface": {
      "types": "./dist/src/interface.d.ts",
      "import": "./dist/src/interface.js"
    },
    "./link": {
      "types": "./dist/src/link.d.ts",
      "import": "./dist/src/link.js"
    },
    "./link/interface": {
      "types": "./dist/src/link/interface.d.ts",
      "import": "./dist/src/link/interface.js"
    },
    "./traversal": {
      "types": "./dist/src/traversal.d.ts",
      "import": "./dist/src/traversal.js"
    }
  },
  "eslintConfig": {
    "extends": "ipfs",
    "parserOptions": {
      "project": true,
      "sourceType": "module"
    }
  },
  "release": {
    "branches": [
      "master"
    ],
    "plugins": [
      [
        "@semantic-release/commit-analyzer",
        {
          "preset": "conventionalcommits",
          "releaseRules": [
            {
              "breaking": true,
              "release": "major"
            },
            {
              "revert": true,
              "release": "patch"
            },
            {
              "type": "feat",
              "release": "minor"
            },
            {
              "type": "fix",
              "release": "patch"
            },
            {
              "type": "docs",
              "release": "patch"
            },
            {
              "type": "test",
              "release": "patch"
            },
            {
              "type": "deps",
              "release": "patch"
            },
            {
              "scope": "no-release",
              "release": false
            }
          ]
        }
      ],
      [
        "@semantic-release/release-notes-generator",
        {
          "preset": "conventionalcommits",
          "presetConfig": {
            "types": [
              {
                "type": "feat",
                "section": "Features"
              },
              {
                "type": "fix",
                "section": "Bug Fixes"
              },
              {
                "type": "chore",
                "section": "Trivial Changes"
              },
              {
                "type": "docs",
                "section": "Documentation"
              },
              {
                "type": "deps",
                "section": "Dependencies"
              },
              {
                "type": "test",
                "section": "Tests"
              }
            ]
          }
        }
      ],
      "@semantic-release/changelog",
      "@semantic-release/npm",
      "@semantic-release/github",
      [
        "@semantic-release/git",
        {
          "assets": [
            "CHANGELOG.md",
            "package.json"
          ]
        }
      ]
    ]
  },
  "scripts": {
    "clean": "aegir clean",
    "lint": "aegir lint",
    "build": "aegir build",
    "release": "aegir release",
    "docs": "aegir docs",
    "test": "npm run lint && npm run test:node && npm run test:chrome",
    "test:node": "aegir test -t node --cov",
    "test:chrome": "aegir test -t browser --cov",
    "test:chrome-webworker": "aegir test -t webworker",
    "test:firefox": "aegir test -t browser -- --browser firefox",
    "test:firefox-webworker": "aegir test -t webworker -- --browser firefox",
    "test:electron-main": "aegir test -t electron-main"
  },
  "devDependencies": {
    "@stablelib/sha256": "^2.0.0",
    "@stablelib/sha512": "^2.0.0",
    "@types/node": "^25.0.0",
    "aegir": "^47.0.7",
    "buffer": "^6.0.3",
    "cids": "^1.1.9",
    "crypto-hash": "^4.0.0"
  },
  "aegir": {
    "test": {
      "target": [
        "node",
        "browser"
      ]
    }
  },
  "browser": {
    "./hashes/sha1": "./dist/src/hashes/sha1-browser.js",
    "./dist/src/hashes/sha1.js": "./dist/src/hashes/sha1-browser.js",
    "./hashes/sha2": "./dist/src/hashes/sha2-browser.js",
    "./dist/src/hashes/sha2.js": "./dist/src/hashes/sha2-browser.js"
  }
}
module.exports = assert

class AssertionError extends Error {}
AssertionError.prototype.name = 'AssertionError'

/**
 * Minimal assert function
 * @param  {any} t Value to check if falsy
 * @param  {string=} m Optional assertion error message
 * @throws {AssertionError}
 */
function assert (t, m) {
  if (!t) {
    var err = new AssertionError(m)
    if (Error.captureStackTrace) Error.captureStackTrace(err, assert)
    throw err
  }
}
{
  "name": "nanoassert",
  "version": "2.0.0",
  "description": "Nanoscale assertion module",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "tape": "^4.9.1"
  },
  "scripts": {
    "test": "tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/emilbayes/nanoassert.git"
  },
  "keywords": [
    "assert",
    "unassert",
    "power-assert",
    "tiny",
    "nano",
    "pico"
  ],
  "author": "Emil Bay <github@tixz.dk>",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/emilbayes/nanoassert/issues"
  },
  "homepage": "https://github.com/emilbayes/nanoassert#readme"
}
module.exports = require.addon.bind(require)
{
  "name": "require-addon",
  "version": "1.2.0",
  "description": "Import native addons across JavaScript runtimes",
  "exports": {
    "./package": "./package.json",
    ".": {
      "bare": "./lib/bare.js",
      "node": "./lib/node.js",
      "default": "./lib/default.js"
    }
  },
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    },
    "url": {
      "bare": "bare-url",
      "default": "url"
    }
  },
  "files": [
    "lib"
  ],
  "scripts": {
    "test": "npm run lint && npm run test:bare && npm run test:node",
    "test:bare": "bare test.js",
    "test:node": "node test.js",
    "lint": "prettier --check .",
    "format": "prettier --write ."
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/require-addon.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/require-addon/issues"
  },
  "homepage": "https://github.com/holepunchto/require-addon#readme",
  "engines": {
    "bare": ">=1.10.0"
  },
  "dependencies": {
    "bare-addon-resolve": "^1.3.0"
  },
  "devDependencies": {
    "bare-bundle": "^1.8.1",
    "bare-bundle-evaluate": "^1.1.0",
    "bare-fs": "^4.0.0",
    "bare-path": "^3.0.0",
    "bare-url": "^2.1.0",
    "brittle": "^3.7.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
const sodium = require('sodium-universal')

module.exports = {
  init: sodium.crypto_hash_sha256_init,
  update: sodium.crypto_hash_sha256_update,
  final: sodium.crypto_hash_sha256_final,
  BYTES: sodium.crypto_hash_sha256_BYTES,
  STATEBYTES: sodium.crypto_hash_sha256_STATEBYTES
}
const sodium = require('sodium-universal')

module.exports = {
  init: sodium.crypto_hash_sha512_init,
  update: sodium.crypto_hash_sha512_update,
  final: sodium.crypto_hash_sha512_final,
  BYTES: sodium.crypto_hash_sha512_BYTES,
  STATEBYTES: sodium.crypto_hash_sha512_STATEBYTES
}
const b4a = require('b4a')

const sha256 = require('./hash/sha256')
const sha512 = require('./hash/sha512')

class HMAC {
  constructor (hash, key) {
    this.hash = hash
    this.length = hash.BYTES

    this._blocksize = 2 * hash.BYTES

    this._initialised = false

    this.state = b4a.alloc(hash.STATEBYTES)
    this.pad = b4a.alloc(this._blocksize)

    if (key) this.init(key)
  }

  init (key) {
    if (this._initialised) {
      throw new Error('Already initialised, call final first')
    }

    if (key.length > this._blocksize) {
      this.hash.init(this.state)
      this.hash.update(this.state, key)
      this.hash.final(this.state, this.pad.subarray(0, this.length))
    } else {
      this.pad.set(key)
    }

    bufferByteXor(this.pad, 0x36)

    this.hash.init(this.state)
    this.hash.update(this.state, this.pad)

    bufferByteXor(this.pad, 0x5c ^ 0x36)

    this._initialised = true

    return this
  }

  update (data) {
    if (!this._initialised) {
      throw new Error('First initialise with a key')
    }

    this.hash.update(this.state, data)
    return this
  }

  final (output = b4a.alloc(this.length)) {
    if (!this._initialised) {
      throw new Error('First initialise with a key')
    }

    const out = output.byteLength === this.length
      ? output
      : output.subarray(0, this.hash.BYTES)

    this.hash.final(this.state, out)

    this.hash.init(this.state)
    this.hash.update(this.state, this.pad)
    this.hash.update(this.state, out)
    this.hash.final(this.state, out)

    this.pad.fill(0)
    this.state.fill(0)

    this._initialised = false

    return out
  }

  static sha256 (data, key, output) {
    const hmac = new HMAC(sha256, key)
    return hmac.update(data).final(output)
  }

  static sha512 (data, key, output) {
    const hmac = new HMAC(sha512, key)
    return hmac.update(data).final(output)
  }
}

module.exports = {
  HMAC,
  sha256,
  sha512
}

function bufferByteXor (output, byte) {
  for (let i = 0; i < output.byteLength; i++) {
    output[i] ^= byte
  }

  return output
}
{
  "name": "sodium-hmac",
  "version": "2.1.0",
  "description": "HMAC utility",
  "main": "index.js",
  "scripts": {
    "test": "standard && brittle test/*.js"
  },
  "author": "",
  "license": "Apache-2.0",
  "dependencies": {
    "b4a": "^1.6.6",
    "sodium-universal": "^5.0.1"
  },
  "devDependencies": {
    "brittle": "^3.4.0",
    "standard": "^17.1.0"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sodium-hmac.git"
  },
  "files": [
    "index.js",
    "hash/*"
  ],
  "bugs": {
    "url": "https://github.com/holepunchto/sodium-hmac/issues"
  },
  "homepage": "https://github.com/holepunchto/sodium-hmac#readme"
}
require.addon = require('require-addon')
module.exports = require.addon('.', __filename)
const assert = require('assert')
const binding = require('./binding')
const { isNode } = require('which-runtime')

const OPTIONAL = Buffer.from(new ArrayBuffer(0))

module.exports = exports = { ...binding }

// memory

exports.sodium_memzero = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  binding.sodium_memzero(buf)
}

exports.sodium_mlock = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  const res = binding.sodium_mlock(buf)

  if (res !== 0) throw new Error('memory lock failed')
}

exports.sodium_munlock = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  const res = binding.sodium_munlock(buf)

  if (res !== 0) throw new Error('memory unlock failed')
}

exports.sodium_malloc = function (size) {
  assert(size >= 0, 'invalid size')

  const buf = Buffer.from(binding.sodium_malloc(size))
  buf.secure = true
  return buf
}

exports.sodium_free = function (buf) {
  if (!buf || !buf.secure) return

  binding.sodium_free(buf.buffer)
}

exports.sodium_mprotect_noaccess = function (buf) {
  const res = binding.sodium_mprotect_noaccess(buf.buffer)

  if (res !== 0) throw new Error('failed to lock buffer')
}

exports.sodium_mprotect_readonly = function (buf) {
  const res = binding.sodium_mprotect_readonly(buf.buffer)

  if (res !== 0) throw new Error('failed to unlock buffer')
}

exports.sodium_mprotect_readwrite = function (buf) {
  const res = binding.sodium_mprotect_readwrite(buf.buffer)

  if (res !== 0) throw new Error('failed to unlock buffer')
}

// crypto_randombytes

exports.randombytes_buf = function (buffer) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')

  binding.randombytes_buf(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

exports.randombytes_buf_deterministic = function (buffer, seed) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    seed.byteLength === binding.randombytes_SEEDBYTES,
    "seed must be 'randombytes_SEEDBYTES' bytes"
  )

  binding.randombytes_buf_deterministic(
    buffer.buffer,
    buffer.byteOffset,
    buffer.byteLength,

    seed.buffer,
    seed.byteOffset,
    seed.byteLength
  )
}

// sodium_helpers

exports.sodium_memcmp = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  return binding.sodium_memcmp(a, b)
}

exports.sodium_add = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  binding.sodium_add(a, b)
}

exports.sodium_sub = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  binding.sodium_sub(a, b)
}

exports.sodium_compare = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  return binding.sodium_compare(a, b)
}

exports.sodium_is_zero = function (buffer, length) {
  if (length === undefined) length = buffer.byteLength

  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(length >= 0 && length <= buffer.byteLength, 'invalid length')

  return binding.sodium_is_zero(buffer, length)
}

exports.sodium_pad = function (buffer, unpaddedBuflen, blockSize) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(unpaddedBuflen <= buffer.byteLength, 'unpadded length cannot exceed buffer length')
  assert(blockSize <= buffer.byteLength, 'block size cannot exceed buffer length')
  assert(blockSize >= 1, 'block size must be at least 1 byte')
  assert(
    buffer.byteLength >= unpaddedBuflen + (blockSize - (unpaddedBuflen % blockSize)),
    'buf not long enough'
  )

  return binding.sodium_pad(buffer, unpaddedBuflen, blockSize)
}

exports.sodium_unpad = function (buffer, paddedBuflen, blockSize) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(paddedBuflen <= buffer.byteLength, 'unpadded length cannot exceed buffer length')
  assert(blockSize <= buffer.byteLength, 'block size cannot exceed buffer length')
  assert(blockSize >= 1, 'block size must be at least 1 byte')

  return binding.sodium_unpad(buffer, paddedBuflen, blockSize)
}

// crypto_sign

exports.crypto_sign_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )
  assert(
    seed.byteLength === binding.crypto_sign_SEEDBYTES,
    "seed must be 'crypto_sign_SEEDBYTES' bytes"
  )

  const res = binding.crypto_sign_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign = function (sm, m, sk) {
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sm.byteLength === binding.crypto_sign_BYTES + m.byteLength,
    "sm must be 'm.byteLength + crypto_sign_BYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign(sm, m, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_open = function (m, sm, pk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sm.byteLength >= binding.crypto_sign_BYTES,
    "sm must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    m.byteLength === sm.byteLength - binding.crypto_sign_BYTES,
    "m must be 'sm.byteLength - crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_open(m, sm, pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_open = function (m, sm, pk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sm.byteLength >= binding.crypto_sign_BYTES,
    "sm must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    m.byteLength === sm.byteLength - binding.crypto_sign_BYTES,
    "m must be 'sm.byteLength - crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  return binding.crypto_sign_open(m, sm, pk)
}

exports.crypto_sign_detached = function (sig, m, sk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(sig.byteLength === binding.crypto_sign_BYTES, "sig must be 'crypto_sign_BYTES' bytes")
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_detached(sig, m, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_verify_detached = function (sig, m, pk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sig.byteLength >= binding.crypto_sign_BYTES,
    "sig must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  return binding.crypto_sign_verify_detached(
    sig.buffer,
    sig.byteOffset,
    sig.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    pk.buffer,
    pk.byteOffset,
    pk.byteLength
  )
}

exports.crypto_sign_ed25519_sk_to_pk = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_sk_to_pk(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_ed25519_pk_to_curve25519 = function (x25519pk, ed25519pk) {
  assert(ArrayBuffer.isView(x25519pk), 'x25519pk must be a typed array')
  assert(ArrayBuffer.isView(ed25519pk), 'ed25519pk must be a typed array')
  assert(
    x25519pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "x25519pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    ed25519pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "ed25519pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_pk_to_curve25519(x25519pk, ed25519pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_ed25519_sk_to_curve25519 = function (x25519sk, ed25519sk) {
  assert(ArrayBuffer.isView(x25519sk), 'x25519sk must be a typed array')
  assert(ArrayBuffer.isView(ed25519sk), 'ed25519sk must be a typed array')
  assert(
    x25519sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "x25519sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const edLen = ed25519sk.byteLength

  assert(
    edLen === binding.crypto_sign_SECRETKEYBYTES || edLen === binding.crypto_box_SECRETKEYBYTES,
    "ed25519sk must be 'crypto_sign_SECRETKEYBYTES' or 'crypto_sign_SECRETKEYBYTES - crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_sk_to_curve25519(x25519sk, ed25519sk)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_box

exports.crypto_box_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    seed.byteLength === binding.crypto_box_SEEDBYTES,
    "seed must be 'crypto_box_SEEDBYTES' bytes"
  )

  const res = binding.crypto_box_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_easy = function (c, m, n, pk, sk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength === m.byteLength + exports.crypto_box_MACBYTES,
    "c must be 'm.byteLength + crypto_box_MACBYTES' bytes"
  )
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_easy(c, m, n, pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_detached = function (c, mac, m, n, pk, sk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(mac.byteLength === exports.crypto_box_MACBYTES, "mac must be 'crypto_box_MACBYTES' bytes")
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_detached(c, mac, m, n, pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_open_easy = function (m, c, n, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength >= exports.crypto_box_MACBYTES,
    "c must be at least 'crypto_box_MACBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - exports.crypto_box_MACBYTES,
    "m must be 'c.byteLength - crypto_box_MACBYTES' bytes"
  )
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_open_easy(m, c, n, pk, sk)
}

exports.crypto_box_open_detached = function (m, c, mac, n, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(mac.byteLength === exports.crypto_box_MACBYTES, "mac must be 'crypto_box_MACBYTES' bytes")
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_open_detached(m, c, mac, n, pk, sk)
}

exports.crypto_box_seal = function (c, m, pk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    c.byteLength === m.byteLength + exports.crypto_box_SEALBYTES,
    "c must be 'm.byteLength + crypto_box_SEALBYTES' bytes"
  )
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_box_seal(c, m, pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_seal_open = function (m, c, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength >= exports.crypto_box_SEALBYTES,
    "c must be at least 'crypto_box_SEALBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - exports.crypto_box_SEALBYTES,
    "m must be 'c.byteLength - crypto_box_SEALBYTES' bytes"
  )
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_seal_open(
    m.buffer,
    m.byteOffset,
    m.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    pk.buffer,
    pk.byteOffset,
    pk.byteLength,

    sk.buffer,
    sk.byteOffset,
    sk.byteLength
  )
}

// crypto_secretbox

exports.crypto_secretbox_easy = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_secretbox_MACBYTES,
    "c must be 'm.byteLength + crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretbox_easy(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretbox_open_easy = function (m, c, n, k) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    c.byteLength >= binding.crypto_secretbox_MACBYTES,
    "c must be at least 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - binding.crypto_secretbox_MACBYTES,
    "m must be 'c.byteLength - crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  return binding.crypto_secretbox_open_easy(m, c, n, k)
}

exports.crypto_secretbox_detached = function (c, mac, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    mac.byteLength === binding.crypto_secretbox_MACBYTES,
    "mac must be 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretbox_detached(c, mac, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretbox_open_detached = function (m, c, mac, n, k) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(
    mac.byteLength === binding.crypto_secretbox_MACBYTES,
    "mac must be 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  return binding.crypto_secretbox_open_detached(m, c, mac, n, k)
}

// crypto_generichash

exports.crypto_generichash = function (output, input, key) {
  if (!key) key = OPTIONAL

  assert(ArrayBuffer.isView(output), 'output must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    output.byteLength >= binding.crypto_generichash_BYTES_MIN &&
      output.byteLength <= binding.crypto_generichash_BYTES_MAX,
    'output must be between crypto_generichash_BYTES_MIN and crypto_generichash_BYTES_MAX bytes'
  )

  if (key !== OPTIONAL) {
    assert(ArrayBuffer.isView(key), 'key must be a typed array')
    assert(
      key.byteLength >= binding.crypto_generichash_KEYBYTES_MIN &&
        key.byteLength <= binding.crypto_generichash_KEYBYTES_MAX,
      'key must be between crypto_generichash_KEYBYTES_MIN and crypto_generichash_KEYBYTES_MAX bytes'
    )
  }

  const res = binding.crypto_generichash(
    output.buffer,
    output.byteOffset,
    output.byteLength,

    input.buffer,
    input.byteOffset,
    input.byteLength,

    key.buffer,
    key.byteOffset,
    key.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_batch = function (output, batch, key) {
  assert(ArrayBuffer.isView(output), 'output must be a typed array')

  if (isNode || batch.length < 4) {
    const res = binding.crypto_generichash_batch(output, batch, !!key, key || OPTIONAL)
    if (res !== 0) throw new Error('status: ' + res)
  } else {
    const state = Buffer.alloc(binding.crypto_generichash_STATEBYTES)

    exports.crypto_generichash_init(state, key, output.byteLength)

    for (const buf of batch) {
      exports.crypto_generichash_update(state, buf)
    }

    exports.crypto_generichash_final(state, output)
  }
}

exports.crypto_generichash_keygen = function (key) {
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(
    key.byteLength === binding.crypto_generichash_KEYBYTES,
    "key must be 'crypto_generichash_KEYBYTES' bytes"
  )

  const res = binding.crypto_generichash_keygen(key.buffer, key.byteOffset, key.byteLength)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_init = function (state, key, outputLength) {
  if (!key) key = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_init(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    key.buffer,
    key.byteOffset,
    key.byteLength,

    outputLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_update(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    input.buffer,
    input.byteOffset,
    input.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_final = function (state, output) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(output), 'output must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_final(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    output.buffer,
    output.byteOffset,
    output.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

// secretstream

exports.crypto_secretstream_xchacha20poly1305_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  binding.crypto_secretstream_xchacha20poly1305_keygen(k.buffer, k.byteOffset, k.byteLength)
}

exports.crypto_secretstream_xchacha20poly1305_init_push = function (state, header, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(header), 'header must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    header.byteLength === binding.crypto_secretstream_xchacha20poly1305_HEADERBYTES,
    "header must be 'crypto_secretstream_xchacha20poly1305_HEADERBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_init_push(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    header.buffer,
    header.byteOffset,
    header.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretstream_xchacha20poly1305_init_pull = function (state, header, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(header), 'header must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    header.byteLength === binding.crypto_secretstream_xchacha20poly1305_HEADERBYTES,
    "header must be 'crypto_secretstream_xchacha20poly1305_HEADERBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_init_pull(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    header.buffer,
    header.byteOffset,
    header.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretstream_xchacha20poly1305_push = function (state, c, m, ad, tag) {
  if (!ad) ad = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    c.byteLength === m.byteLength + binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "c must be 'm.byteLength + crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_push(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    ad.buffer,
    ad.byteOffset,
    ad.byteLength,

    tag
  )

  if (res < 0) throw new Error('push failed')

  return res
}

exports.crypto_secretstream_xchacha20poly1305_pull = function (state, m, tag, c, ad) {
  if (!ad) ad = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(tag), 'tag must be a typed array')
  assert(tag.byteLength === 1, 'tag must be 1 byte')

  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    c.byteLength >= binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "c must be at least 'crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "m must be 'c.byteLength - crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_pull(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    tag.buffer,
    tag.byteOffset,
    tag.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    ad.buffer,
    ad.byteOffset,
    ad.byteLength
  )

  if (res < 0) throw new Error('pull failed')

  return res
}

exports.crypto_secretstream_xchacha20poly1305_rekey = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )

  binding.crypto_secretstream_xchacha20poly1305_rekey(
    state.buffer,
    state.byteOffset,
    state.byteLength
  )
}

// crypto_stream

exports.crypto_stream = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xor(
    c.buffer,
    c.byteOffset,
    c.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    n.buffer,
    n.byteOffset,
    n.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_auth

exports.crypto_auth = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(out.byteLength === binding.crypto_auth_BYTES, "out must be 'crypto_auth_BYTES' bytes")
  assert(k.byteLength === binding.crypto_auth_KEYBYTES, "k must be 'crypto_auth_KEYBYTES' bytes")

  const res = binding.crypto_auth(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_auth_verify = function (h, input, k) {
  assert(ArrayBuffer.isView(h), 'h must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(h.byteLength === binding.crypto_auth_BYTES, "h must be 'crypto_auth_BYTES' bytes")
  assert(k.byteLength === binding.crypto_auth_KEYBYTES, "k must be 'crypto_auth_KEYBYTES' bytes")

  return binding.crypto_auth_verify(h, input, k)
}

// crypto_onetimeauth

exports.crypto_onetimeauth = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    out.byteLength === binding.crypto_onetimeauth_BYTES,
    "out must be 'crypto_onetimeauth_BYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_init = function (state, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_init(state, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )
  assert(
    out.byteLength === binding.crypto_onetimeauth_BYTES,
    "out must be 'crypto_onetimeauth_BYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_verify = function (h, input, k) {
  assert(ArrayBuffer.isView(h), 'h must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    h.byteLength === binding.crypto_onetimeauth_BYTES,
    "h must be 'crypto_onetimeauth_BYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  return binding.crypto_onetimeauth_verify(h, input, k)
}

// crypto_pwhash

exports.crypto_pwhash = function (out, passwd, salt, opslimit, memlimit, alg) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_BYTES_MIN,
    "out must be at least 'crypto_pwhash_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_BYTES_MAX,
    "out must be at most 'crypto_pwhash_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_SALTBYTES,
    "salt must be 'crypto_pwhash_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )
  assert(alg >= 1 && alg <= 2, 'alg must be either Argon2i 1.3 or Argon2id 1.3')

  const res = binding.crypto_pwhash(out, passwd, salt, opslimit, memlimit, alg)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_async = function (
  out,
  passwd,
  salt,
  opslimit,
  memlimit,
  alg,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_BYTES_MIN,
    "out must be at least 'crypto_pwhash_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_BYTES_MAX,
    "out must be at most 'crypto_pwhash_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_SALTBYTES,
    "salt must be 'crypto_pwhash_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )
  assert(alg >= 1 && alg <= 2, 'alg must be either Argon2i 1.3 or Argon2id 1.3')

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    opslimit,
    memlimit,
    alg,

    done
  )

  return promise
}

exports.crypto_pwhash_str = function (out, passwd, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_STRBYTES,
    "out must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(typeof opslimit === 'number', 'opslimit must be a number')
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(typeof memlimit === 'number', 'memlimit must be a number')
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_str(out, passwd, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_str_async = function (out, passwd, opslimit, memlimit, callback = undefined) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_STRBYTES,
    "out must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(typeof opslimit === 'number', 'opslimit must be a number')
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(typeof memlimit === 'number', 'memlimit must be a number')
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_str_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_str_verify = function (str, passwd) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )

  return binding.crypto_pwhash_str_verify(str, passwd)
}

exports.crypto_pwhash_str_verify_async = function (str, passwd, callback = undefined) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  const [done, promise] = checkStatus(callback, true)

  binding.crypto_pwhash_str_verify_async(
    str.buffer,
    str.byteOffset,
    str.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    done
  )

  return promise
}

exports.crypto_pwhash_str_needs_rehash = function (str, opslimit, memlimit) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  return binding.crypto_pwhash_str_needs_rehash(str, opslimit, memlimit)
}

exports.crypto_pwhash_scryptsalsa208sha256 = function (out, passwd, salt, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MIN,
    "out must be at least 'crypto_pwhash_scryptsalsa208sha256_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MAX,
    "out must be at most 'crypto_pwhash_scryptsalsa208sha256_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_SALTBYTES,
    "salt must be 'crypto_pwhash_scryptsalsa208sha256_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_scryptsalsa208sha256(out, passwd, salt, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_scryptsalsa208sha256_async = function (
  out,
  passwd,
  salt,
  opslimit,
  memlimit,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MIN,
    "out must be at least 'crypto_pwhash_scryptsalsa208sha256_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MAX,
    "out must be at most 'crypto_pwhash_scryptsalsa208sha256_BYTES_MAX' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    salt.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_SALTBYTES,
    "salt must be 'crypto_pwhash_scryptsalsa208sha256_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_scryptsalsa208sha256_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str_async = function (
  out,
  passwd,
  opslimit,
  memlimit,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "out must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_scryptsalsa208sha256_str_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str = function (out, passwd, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "out must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_scryptsalsa208sha256_str(out, passwd, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_scryptsalsa208sha256_str_verify_async = function (
  str,
  passwd,
  callback = undefined
) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  const [done, promise] = checkStatus(callback, true)

  binding.crypto_pwhash_scryptsalsa208sha256_str_verify_async(
    str.buffer,
    str.byteOffset,
    str.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str_verify = function (str, passwd) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  return binding.crypto_pwhash_scryptsalsa208sha256_str_verify(str, passwd)
}

exports.crypto_pwhash_scryptsalsa208sha256_str_needs_rehash = function (str, opslimit, memlimit) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  return binding.crypto_pwhash_scryptsalsa208sha256_str_needs_rehash(str, opslimit, memlimit)
}

// crypto_kx

exports.crypto_kx_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "pk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "sk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    pk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "pk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "sk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    seed.byteLength === binding.crypto_kx_SEEDBYTES,
    "seed must be 'crypto_kx_SEEDBYTES' bytes"
  )

  const res = binding.crypto_kx_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_client_session_keys = function (rx, tx, clientPk, clientSk, serverPk) {
  if (!rx) rx = undefined
  if (!tx) tx = undefined

  assert(rx || tx, 'at least one session key must be specified')

  if (rx) {
    assert(ArrayBuffer.isView(rx), 'rx must be a typed array')
    assert(
      rx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "rx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  if (tx) {
    assert(ArrayBuffer.isView(tx), 'tx must be a typed array')
    assert(
      tx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "tx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  assert(ArrayBuffer.isView(clientPk), 'clientPk must be a typed array')
  assert(ArrayBuffer.isView(clientSk), 'clientSk must be a typed array')
  assert(ArrayBuffer.isView(serverPk), 'serverPk must be a typed array')
  assert(
    clientPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "clientPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    clientSk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "clientSk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    serverPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "serverPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_client_session_keys(rx, tx, clientPk, clientSk, serverPk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_server_session_keys = function (rx, tx, serverPk, serverSk, clientPk) {
  if (!rx) rx = undefined
  if (!tx) tx = undefined

  assert(rx || tx, 'at least one session key must be specified')

  if (rx) {
    assert(ArrayBuffer.isView(rx), 'rx must be a typed array')
    assert(
      rx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "rx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  if (tx) {
    assert(ArrayBuffer.isView(tx), 'tx must be a typed array')
    assert(
      tx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "tx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  assert(ArrayBuffer.isView(serverPk), 'serverPk must be a typed array')
  assert(ArrayBuffer.isView(serverSk), 'serverSk must be a typed array')
  assert(ArrayBuffer.isView(clientPk), 'clientPk must be a typed array')
  assert(
    serverPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "serverPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    serverSk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "serverSk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    clientPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "clientPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_server_session_keys(rx, tx, serverPk, serverSk, clientPk)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_scalarmult

exports.crypto_scalarmult_base = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_BYTES,
    "q must be 'crypto_scalarmult_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_SCALARBYTES,
    "n must be 'crypto_scalarmult_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_base(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_BYTES,
    "q must be 'crypto_scalarmult_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_SCALARBYTES,
    "n must be 'crypto_scalarmult_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_BYTES,
    "p must be 'crypto_scalarmult_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_base = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_base(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519 = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "p must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_is_valid_point = function (p) {
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )

  return binding.crypto_core_ed25519_is_valid_point(p)
}

exports.crypto_core_ed25519_from_uniform = function (p, r) {
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_UNIFORMBYTES,
    "r must be 'crypto_core_ed25519_UNIFORMBYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_from_uniform(p, r)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_base_noclamp = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_base_noclamp(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_noclamp = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "p must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_noclamp(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_core

exports.crypto_core_ed25519_add = function (r, p, q) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_BYTES,
    "r must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_core_ed25519_BYTES,
    "q must be 'crypto_core_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_add(r, p, q)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_sub = function (r, p, q) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_BYTES,
    "r must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_core_ed25519_BYTES,
    "q must be 'crypto_core_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_sub(r, p, q)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_scalar_random = function (r) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "r must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_random(r)
}

exports.crypto_core_ed25519_scalar_reduce = function (r, s) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "r must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_NONREDUCEDSCALARBYTES,
    "s must be 'crypto_core_ed25519_NONREDUCEDSCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_reduce(r, s)
}

exports.crypto_core_ed25519_scalar_invert = function (recip, s) {
  assert(ArrayBuffer.isView(recip), 'recip must be a typed array')
  assert(
    recip.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "recip must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_invert(recip, s)
}

exports.crypto_core_ed25519_scalar_negate = function (neg, s) {
  assert(ArrayBuffer.isView(neg), 'neg must be a typed array')
  assert(
    neg.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "neg must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_negate(neg, s)
}

exports.crypto_core_ed25519_scalar_complement = function (comp, s) {
  assert(ArrayBuffer.isView(comp), 'comp must be a typed array')
  assert(
    comp.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "comp must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_complement(comp, s)
}

exports.crypto_core_ed25519_scalar_add = function (z, x, y) {
  assert(ArrayBuffer.isView(z), 'z must be a typed array')
  assert(
    z.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "z must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(x), 'x must be a typed array')
  assert(
    x.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "x must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(y), 'y must be a typed array')
  assert(
    y.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "y must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_add(z, x, y)
}

exports.crypto_core_ed25519_scalar_sub = function (z, x, y) {
  assert(ArrayBuffer.isView(z), 'z must be a typed array')
  assert(
    z.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "z must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(x), 'x must be a typed array')
  assert(
    x.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "x must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(y), 'y must be a typed array')
  assert(
    y.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "y must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_sub(z, x, y)
}

// crypto_shorthash

exports.crypto_shorthash = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_shorthash_BYTES,
    "out must be 'crypto_shorthash_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_shorthash_KEYBYTES,
    "k must be 'crypto_shorthash_KEYBYTES' bytes"
  )

  const res = binding.crypto_shorthash(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_kdf

exports.crypto_kdf_keygen = function (key) {
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(key.byteLength === binding.crypto_kdf_KEYBYTES, "key must be 'crypto_kdf_KEYBYTES' bytes")

  binding.crypto_kdf_keygen(key)
}

exports.crypto_kdf_derive_from_key = function (subkey, subkeyId, ctx, key) {
  assert(ArrayBuffer.isView(subkey), 'subkey must be a typed array')
  assert(
    subkey.byteLength >= binding.crypto_kdf_BYTES_MIN,
    "subkey must be at least 'crypto_kdf_BYTES_MIN' bytes"
  )
  assert(
    subkey.byteLength <= binding.crypto_kdf_BYTES_MAX,
    "subkey must be at most 'crypto_kdf_BYTES_MAX' bytes"
  )
  assert(ArrayBuffer.isView(ctx), 'ctx must be a typed array')
  assert(
    ctx.byteLength === binding.crypto_kdf_CONTEXTBYTES,
    "ctx must be 'crypto_kdf_CONTEXTBYTES' bytes"
  )
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(key.byteLength === binding.crypto_kdf_KEYBYTES, "key must be 'crypto_kdf_KEYBYTES' bytes")

  const res = binding.crypto_kdf_derive_from_key(subkey, subkeyId, ctx, key)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_hash

exports.crypto_hash = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(out.byteLength === binding.crypto_hash_BYTES, "out must be 'crypto_hash_BYTES' bytes")

  const res = binding.crypto_hash(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256 = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha256_BYTES,
    "out must be 'crypto_hash_sha256_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha256(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_init = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_init(state)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha256_BYTES,
    "out must be 'crypto_hash_sha256_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512 = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha512_BYTES,
    "out must be 'crypto_hash_sha512_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha512(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_init = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_init(state)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha512_BYTES,
    "out must be 'crypto_hash_sha512_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_aead

exports.crypto_aead_xchacha20poly1305_ietf_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  binding.crypto_aead_xchacha20poly1305_ietf_keygen(k)
}

exports.crypto_aead_xchacha20poly1305_ietf_encrypt = function (c, m, ad, nsec, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "c must be 'm.byteLength + crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(c.byteLength <= 0xffffffff, 'c.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_encrypt(c, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_decrypt = function (m, nsec, c, ad, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "m must be 'c.byteLength - crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(m.byteLength <= 0xffffffff, 'm.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_decrypt(m, c, ad, npub, k)

  if (res < 0) throw new Error('could not verify data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_encrypt_detached = function (
  c,
  mac,
  m,
  ad,
  nsec,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_encrypt_detached(c, mac, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_decrypt_detached = function (
  m,
  nsec,
  c,
  mac,
  ad,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_decrypt_detached(m, c, mac, ad, npub, k)

  if (res !== 0) throw new Error('could not verify data')
}

exports.crypto_aead_chacha20poly1305_ietf_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  binding.crypto_aead_chacha20poly1305_ietf_keygen(k)
}

exports.crypto_aead_chacha20poly1305_ietf_encrypt = function (c, m, ad, nsec, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "c must be 'm.byteLength + crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(c.byteLength <= 0xffffffff, 'c.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_encrypt(c, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_decrypt = function (m, nsec, c, ad, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "m must be 'c.byteLength - crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(m.byteLength <= 0xffffffff, 'm.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_decrypt(m, c, ad, npub, k)

  if (res < 0) throw new Error('could not verify data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_encrypt_detached = function (
  c,
  mac,
  m,
  ad,
  nsec,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_encrypt_detached(c, mac, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_decrypt_detached = function (
  m,
  nsec,
  c,
  mac,
  ad,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_decrypt_detached(m, c, mac, ad, npub, k)

  if (res !== 0) throw new Error('could not verify data')
}

// crypto_stream

exports.crypto_stream_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  binding.crypto_stream_xor_wrap_init(state, n, k)
}

exports.crypto_stream_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_xor_wrap_update(state, c, m)
}

exports.crypto_stream_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_xor_wrap_final(state)
}

exports.crypto_stream_chacha20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  binding.crypto_stream_chacha20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_chacha20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_chacha20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_chacha20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_chacha20_xor_wrap_final(state)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  binding.crypto_stream_chacha20_ietf_xor_wrap_init(state, n, k)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_chacha20_ietf_xor_wrap_update(state, c, m)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_chacha20_ietf_xor_wrap_final(state)
}

exports.crypto_stream_xchacha20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  binding.crypto_stream_xchacha20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_xchacha20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_xchacha20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_xchacha20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_xchacha20_xor_wrap_final(state)
}

exports.crypto_stream_salsa20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  binding.crypto_stream_salsa20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_salsa20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_salsa20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_salsa20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_salsa20_xor_wrap_final(state)
}

// experimental

exports.extension_tweak_ed25519_base = function (n, p, ns) {
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.extension_tweak_ed25519_BYTES,
    "p must be 'extension_tweak_ed25519_BYTES' bytes"
  )

  binding.extension_tweak_ed25519_base(n, p, ns)
}

exports.extension_tweak_ed25519_sign_detached = function (sig, m, scalar, pk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(sig.byteLength === binding.crypto_sign_BYTES, "sig must be 'crypto_sign_BYTES' bytes")
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  if (pk) {
    assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
    assert(
      pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
      "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
    )
  }

  const res = binding.extension_tweak_ed25519_sign_detached(sig, m, scalar, pk)

  if (res !== 0) throw new Error('failed to compute signature')
}

exports.extension_tweak_ed25519_sk_to_scalar = function (n, sk) {
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  binding.extension_tweak_ed25519_sk_to_scalar(n, sk)
}

exports.extension_tweak_ed25519_scalar = function (scalarOut, scalar, ns) {
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_scalar(scalarOut, scalar, ns)
}

exports.extension_tweak_ed25519_pk = function (tpk, pk, ns) {
  assert(ArrayBuffer.isView(tpk), 'tpk must be a typed array')
  assert(
    tpk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "tpk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_pk(tpk, pk, ns)

  if (res !== 0) throw new Error('failed to tweak public key')
}

exports.extension_tweak_ed25519_keypair = function (pk, scalarOut, scalarIn, ns) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.extension_tweak_ed25519_BYTES,
    "pk must be 'extension_tweak_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarIn), 'scalarIn must be a typed array')
  assert(
    scalarIn.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarIn must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_keypair(pk, scalarOut, scalarIn, ns)
}

exports.extension_tweak_ed25519_scalar_add = function (scalarOut, scalar, n) {
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_scalar_add(scalarOut, scalar, n)
}

exports.extension_tweak_ed25519_pk_add = function (tpk, pk, p) {
  assert(ArrayBuffer.isView(tpk), 'tpk must be a typed array')
  assert(
    tpk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "tpk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "p must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_pk_add(tpk, pk, p)

  if (res !== 0) throw new Error('failed to add tweak to public key')
}

exports.extension_tweak_ed25519_keypair_add = function (pk, scalarOut, scalarIn, tweak) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.extension_tweak_ed25519_BYTES,
    "pk must be 'extension_tweak_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarIn), 'scalarIn must be a typed array')
  assert(
    scalarIn.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarIn must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(tweak), 'tweak must be a typed array')
  assert(
    tweak.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "tweak must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_keypair_add(pk, scalarOut, scalarIn, tweak)

  if (res !== 0) throw new Error('failed to add tweak to keypair')
}

exports.extension_pbkdf2_sha512_async = function (out, passwd, salt, iter, outlen, callback) {
  assert(
    iter >= binding.extension_pbkdf2_sha512_ITERATIONS_MIN,
    "iter must be at least 'extension_pbkdf2_sha512_ITERATIONS_MIN'"
  )
  assert(
    outlen <= binding.extension_pbkdf2_sha512_BYTES_MAX,
    "outlen must be at most 'extension_pbkdf2_sha512_BYTES_MAX'"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(out.byteLength >= outlen, "out must be at least 'outlen' bytes")
  assert(out.byteLength > 0, 'out must not be empty')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(salt.byteLength > 0, 'salt must not be empty')

  const [done, promise] = checkStatus(callback)

  binding.extension_pbkdf2_sha512_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    iter,
    outlen,

    done
  )

  return promise
}

exports.extension_pbkdf2_sha512 = function (out, passwd, salt, iter, outlen) {
  assert(
    iter >= binding.extension_pbkdf2_sha512_ITERATIONS_MIN,
    "iter must be at least 'extension_pbkdf2_sha512_ITERATIONS_MIN'"
  )
  assert(
    outlen <= binding.extension_pbkdf2_sha512_BYTES_MAX,
    "outlen must be at most 'extension_pbkdf2_sha512_BYTES_MAX'"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(out.byteLength >= outlen, "out must be at least 'outlen' bytes")
  assert(out.byteLength > 0, 'out must not be empty')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(salt.byteLength > 0, 'salt must not be empty')

  const res = binding.extension_pbkdf2_sha512(out, passwd, salt, iter, outlen)

  if (res !== 0) throw new Error('failed to add tweak to public key')
}

function checkStatus(callback, booleanResult = false) {
  let done, promise

  if (typeof callback === 'function') {
    done = function (status) {
      if (booleanResult) callback(null, status === 0)
      else if (status === 0) callback(null)
      else callback(new Error('status: ' + status))
    }
  } else {
    promise = new Promise(function (resolve, reject) {
      done = function (status) {
        if (booleanResult) resolve(status === 0)
        else if (status === 0) resolve()
        else reject(new Error('status: ' + status))
      }
    })
  }

  return [done, promise]
}
{
  "name": "sodium-native",
  "version": "5.1.0",
  "description": "Low level bindings for libsodium",
  "main": "index.js",
  "files": [
    "index.js",
    "binding.cc",
    "binding.js",
    "extensions",
    "prebuilds",
    "CMakeLists.txt"
  ],
  "imports": {
    "assert": {
      "bare": "bare-assert",
      "node": "assert"
    }
  },
  "addon": true,
  "dependencies": {
    "bare-assert": "^1.2.0",
    "require-addon": "^1.1.0",
    "which-runtime": "^1.2.1"
  },
  "devDependencies": {
    "bare-compat-napi": "^1.3.5",
    "brittle": "^3.16.2",
    "cmake-bare": "^1.6.1",
    "cmake-fetch": "^1.4.3",
    "cmake-napi": "^1.2.1",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "test": "prettier . --check && npm run test:node && npm run test:bare",
    "test:node": "node test/all.js",
    "test:bare": "bare test/all.js"
  },
  "standard": {
    "ignore": [
      "/test/fixtures/*.js"
    ]
  },
  "engines": {
    "bare": ">=1.16.0"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sodium-native.git"
  },
  "contributors": [
    "Emil Bay <github@tixz.dk> (http://bayes.dk)",
    "Mathias Buus <mathiasbuus@gmail.com> (https://mafinto.sh)",
    "Christophe Diederichs <chm-diederichs@hyperdivision.dk>"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/sodium-native/issues"
  },
  "homepage": "https://github.com/holepunchto/sodium-native"
}
module.exports = require('sodium-native')
{
  "name": "sodium-universal",
  "version": "5.0.1",
  "description": "Universal wrapper for sodium-javascript and sodium-native working in Node.js and the Browser",
  "main": "index.js",
  "dependencies": {
    "sodium-native": "^5.0.1"
  },
  "peerDependencies": {
    "sodium-javascript": "~0.8.0"
  },
  "peerDependenciesMeta": {
    "sodium-javascript": {
      "optional": true
    }
  },
  "scripts": {
    "prepublish": "./build-scripts/generate.js"
  },
  "browser": {
    "sodium-native": "sodium-javascript"
  },
  "browserify": {
    "transform": [
      "./build-scripts/transform.js"
    ]
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sodium-universal.git"
  },
  "keywords": [
    "libsodium",
    "sodium",
    "sodium-native",
    "sodium-javascript",
    "browserify"
  ],
  "contributors": [
    "Emil Bay <github@tixz.dk> (http://bayes.dk)",
    "Mathias Buus <mathiasbuus@gmail.com> (https://mafinto.sh)",
    "Christophe Diederichs <chm-diederichs@hyperdivision.dk>"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/sodium-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/sodium-universal#readme"
}
const { runtime, platform, arch, version } =
  typeof Bare !== 'undefined'
    ? {
        runtime: 'bare',
        platform: global.Bare.platform,
        arch: global.Bare.arch,
        version: global.Bare.version
      }
    : typeof process !== 'undefined'
      ? {
          runtime: 'node',
          platform: global.process.platform,
          arch: global.process.arch,
          version: global.process.version
        }
      : typeof Window !== 'undefined'
        ? { runtime: 'browser', platform: 'unknown', arch: 'unknown', version: 'unknown' }
        : { runtime: 'unknown', platform: 'unknown', arch: 'unknown', version: 'unknown' }

exports.runtime = runtime
exports.version = version
exports.platform = platform
exports.arch = arch
exports.isBare = runtime === 'bare'
exports.isBareKit = exports.isBare && typeof BareKit !== 'undefined'
exports.isPear = typeof Pear !== 'undefined'
exports.isNode = runtime === 'node'
exports.isBrowser = runtime === 'browser'
exports.isWindows = platform === 'win32'
exports.isLinux = platform === 'linux'
exports.isMac = platform === 'darwin'
exports.isIOS = platform === 'ios' || platform === 'ios-simulator'
exports.isAndroid = platform === 'android'
exports.isElectron = typeof process !== 'undefined' && !!global.process.versions?.electron
exports.isElectronRenderer = exports.isElectron && global.process.type === 'renderer'
exports.isElectronWorker = exports.isElectron && global.process.type === 'worker'
{
  "name": "which-runtime",
  "version": "1.4.0",
  "description": "Detect if you are in Bare or Node and which os etc",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte .",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/which-runtime.git"
  },
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/which-runtime/issues"
  },
  "homepage": "https://github.com/holepunchto/which-runtime",
  "devDependencies": {
    "brittle": "^3.0.0",
    "lunte": "^1.4.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
{
  "name": "atproto-identity",
  "version": "0.0.4",
  "description": "Seed-anchored atproto identity: one BIP39 mnemonic -> Ed25519 (Hypercore) + secp256k1 (did:plc). Offline did:plc genesis + verification.",
  "type": "module",
  "main": "lib/atproto-identity.js",
  "scripts": {
    "test": "brittle-node test/*.test.js && node test/labels.test.mjs",
    "postinstall": "node scripts/bare-deps.mjs"
  },
  "dependencies": {
    "@ipld/dag-cbor": "^9.2.1",
    "@noble/curves": "^1.6.0",
    "@noble/hashes": "^1.5.0",
    "@scure/bip32": "^1.5.0",
    "@scure/bip39": "^1.4.0",
    "b4a": "^1.6.7",
    "hypercore-crypto": "^3.0.0",
    "keet-identity-key": "^3.2.0",
    "multiformats": "^13.3.0",
    "sodium-native": "^5.1.0"
  },
  "devDependencies": {
    "brittle": "^4.0.2"
  }
}
// Minimal CAR v1 codec — bare-safe, dependency-light replacement for @ipld/car.
//
// CAR v1 is a trivial container: varint(headerLen) ++ dag-cbor({version:1, roots:[…]})
// then, per block, varint(len) ++ CIDbytes ++ blockBytes. We only need whole-buffer
// read/write (no streaming, no file I/O), so this is ~40 lines of pure JS over
// multiformats' CID (byte-exact with @ipld/car — verified by the repo tests + the
// @atproto/repo conformance reader). Drops @ipld/car (which imports `fs`/streams and
// won't load under Bare).
//
// ⚠️ LIMITATIONS vs @ipld/car (tracked in memory: bare-car-limitations). Fine for our
// current use (whole-buffer, CARv1, OUR-OWN trusted output); add the feature before the
// gate it guards:
//   - No streaming — whole CAR is buffered in memory. GATE: large repos (getRepo of a
//     big repo could be GBs). Add an async-iterator read/write path.
//   - No untrusted-input hardening — readCar trusts varints/lengths/CIDs. GATE: reading
//     UNTRUSTED CARs (com.atproto.repo.importRepo, ingress bridge). Add bounds/overflow/
//     truncation checks + duplicate-CID handling before then.
//   - CARv1 only (no CARv2/index). atproto is CARv1, so no gate today.
// Fully-featured path: grow this file at each gate, OR extract a standalone bare-native
// `bare-car` package (the holepunch ecosystem lacks one — a real contribution).

import { CID } from 'multiformats/cid'
import * as dagCbor from '@ipld/dag-cbor'

function varintEncode (n) {
  const out = []
  while (n >= 0x80) { out.push((n & 0x7f) | 0x80); n >>>= 7 }
  out.push(n)
  return Uint8Array.from(out)
}

function varintDecode (bytes, offset) {
  let n = 0; let shift = 0; let i = offset
  for (;;) {
    const b = bytes[i++]
    n |= (b & 0x7f) << shift
    if ((b & 0x80) === 0) break
    shift += 7
  }
  return [n >>> 0, i]
}

// Serialise { root, blocks } to CAR bytes. `blocks` is an iterable of { cid, bytes }.
export async function writeCar (rootCid, blocks) {
  const header = dagCbor.encode({ version: 1, roots: [rootCid] })
  const parts = [Buffer.from(varintEncode(header.length)), Buffer.from(header)]
  for (const { cid, bytes } of blocks) {
    const cidBytes = cid.bytes
    const body = new Uint8Array(cidBytes.length + bytes.length)
    body.set(cidBytes, 0)
    body.set(bytes, cidBytes.length)
    parts.push(Buffer.from(varintEncode(body.length)), Buffer.from(body))
  }
  return Buffer.concat(parts)
}

// Read a CAR into { roots, blocks } where blocks maps cid-string -> { cid, bytes }.
export async function readCar (carBytes) {
  const bytes = carBytes instanceof Uint8Array ? carBytes : new Uint8Array(carBytes)
  let [hlen, off] = varintDecode(bytes, 0)
  const header = dagCbor.decode(bytes.subarray(off, off + hlen))
  off += hlen
  const blocks = new Map()
  while (off < bytes.length) {
    const [blen, bodyStart] = varintDecode(bytes, off)
    const end = bodyStart + blen
    const [cid, rest] = CID.decodeFirst(bytes.subarray(bodyStart, end))
    blocks.set(cid.toString(), { cid, bytes: rest })
    off = end
  }
  return { roots: header.roots, blocks }
}
// atproto block CIDs — CIDv1, dag-cbor codec (0x71), sha2-256 multihash (0x12).
// Every block in a repo (commit, MST node, record) is content-addressed this way,
// so computeCid(dag-cbor(block)) IS the block's identity. This is the anchor for
// byte-exact fidelity: if our re-encoded bytes hash to the same CID the reference
// produced, our encoding is byte-identical.

import { CID } from 'multiformats/cid'
import * as Digest from 'multiformats/hashes/digest'
import { sha256 as nobleSha256 } from '@noble/hashes/sha2'
import * as dagCbor from '@ipld/dag-cbor'
import * as raw from 'multiformats/codecs/raw'

// raw block bytes -> CID. Uses noble's pure-JS sha256 (same as the sync path) rather
// than multiformats' `crypto.subtle` path — identical CID, and no WebCrypto dependency
// (so it loads + runs under Bare, which has no crypto.subtle).
export async function cidForBytes (bytes) {
  return cidForBytesSync(bytes)
}

// Synchronous variant — needed by the recursive MST build. Same result as
// cidForBytes (CIDv1 / dag-cbor 0x71 / sha2-256 0x12), just without the async
// WebCrypto digest.
export function cidForBytesSync (bytes) {
  const digest = Digest.create(0x12, nobleSha256(bytes)) // 0x12 = sha2-256 multihash code
  return CID.createV1(dagCbor.code, digest)
}

// BLOB CID — CIDv1, RAW codec (0x55), sha2-256. atproto blobs (images/avatars) are
// content-addressed with the raw codec (opaque bytes), NOT dag-cbor. This is the CID that
// goes in a blob ref ({$type:'blob', ref:{$link:<this>}, mimeType, size}) and the key
// com.atproto.sync.getBlob serves by.
export function cidForBlobSync (bytes) {
  const digest = Digest.create(0x12, nobleSha256(bytes))
  return CID.createV1(raw.code, digest)
}

// a JS value -> its canonical dag-cbor bytes + CID
export async function cidForValue (value) {
  const bytes = dagCbor.encode(value)
  return { bytes, cid: await cidForBytes(bytes) }
}
// atproto repo commit — sign + verify.
//
// A commit is { did, version: 3, data: <MST root CID>, rev, prev, sig }. The
// signature is ECDSA-secp256k1 (low-S) over sha256(dag-cbor(unsignedCommit)), stored
// as a raw 64-byte CBOR byte string (NOT base64url — that's the did:plc genesis).
// The relay validates this sig against the DID doc's verificationMethod.

import * as dagCbor from '@ipld/dag-cbor'
import { sha256 as nobleSha256 } from '@noble/hashes/sha2'
import { secp256k1 } from '@noble/curves/secp256k1'
import { cidForBytesSync } from './cid.js'

export const REPO_VERSION = 3

// The unsigned commit (everything the signature covers).
export function unsignedCommit ({ did, rev, data, prev = null }) {
  return { did, version: REPO_VERSION, data, rev, prev }
}

// Sign an unsigned commit -> signed commit with `sig` (64 raw bytes).
export function signCommit (unsigned, privateKey) {
  const hash = nobleSha256(dagCbor.encode(unsigned))
  const sig = secp256k1.sign(hash, privateKey, { lowS: true }).toCompactRawBytes()
  return { ...unsigned, sig }
}

export function commitCid (signedCommit) {
  return cidForBytesSync(dagCbor.encode(signedCommit))
}

// Verify a signed commit against a compressed secp256k1 pubkey (33 bytes).
export function verifyCommit (signedCommit, publicKey) {
  const { sig, ...unsigned } = signedCommit
  const hash = nobleSha256(dagCbor.encode(unsigned))
  return secp256k1.verify(sig, hash, publicKey, { lowS: true })
}
// atproto MST — WRITE path (slice 2).
//
// A faithful port of millipds's `atmst` (mst/node.py + node_wrangler.py) — the exact
// code that produced our golden CAR. Byte-exactness is verified two ways: rebuilding
// the golden repo's MST, and matching atmst's own root CIDs for a multi-height tree
// (build + delete oracles). See test/mst-write.test.js.
//
// Node shape (interleaved): subtrees[0], (keys[0],vals[0]), subtrees[1], … ,subtrees[n].
// key layer = leading-zero BITS of sha256(key), // 2 (fanout 4).

import * as dagCbor from '@ipld/dag-cbor'
import { sha256 as nobleSha256 } from '@noble/hashes/sha2'
import { cidForBytesSync } from './cid.js'

const cidEq = (a, b) => (a === null || b === null) ? a === b : a.equals(b)
const replaceAt = (arr, i, v) => { const c = arr.slice(); c[i] = v; return c }
const insertAt = (arr, i, v) => arr.slice(0, i).concat([v], arr.slice(i))
const removeAt = (arr, i) => arr.slice(0, i).concat(arr.slice(i + 1))

export function keyHeight (key) {
  const h = nobleSha256(Buffer.from(key, 'utf8')) // 32 bytes
  let zeros = 0
  for (const byte of h) {
    if (byte === 0) { zeros += 8; continue }
    zeros += Math.clz32(byte) - 24 // leading zero bits within this byte
    break
  }
  return zeros >> 1 // // 2
}

export class MSTNode {
  constructor (keys, vals, subtrees) {
    this.keys = keys // [string]
    this.vals = vals // [CID]
    this.subtrees = subtrees // [CID|null], length keys.length + 1
  }

  static empty () { return new MSTNode([], [], [null]) }

  isEmpty () { return this.keys.length === 0 && this.subtrees.length === 1 && this.subtrees[0] === null }

  serialise () {
    const e = []
    let prevKey = Buffer.alloc(0)
    for (let i = 0; i < this.keys.length; i++) {
      const keyBytes = Buffer.from(this.keys[i], 'utf8')
      const max = Math.min(prevKey.length, keyBytes.length)
      let p = 0
      while (p < max && prevKey[p] === keyBytes[p]) p++
      e.push({ k: keyBytes.subarray(p), p, t: this.subtrees[i + 1], v: this.vals[i] })
      prevKey = keyBytes
    }
    return dagCbor.encode({ e, l: this.subtrees[0] }) // dag-cbor canonicalises map key order
  }

  cid () { return cidForBytesSync(this.serialise()) }

  toOptional () { return this.isEmpty() ? null : this.cid() }

  gteIndex (key) { let i = 0; while (i < this.keys.length && key > this.keys[i]) i++; return i }

  height () {
    if (this.keys.length) return keyHeight(this.keys[0])
    if (this.subtrees[0] === null) return 0
    return null // indeterminate (empty intermediate node)
  }

  static deserialise (bytes) {
    const cbor = dagCbor.decode(bytes)
    const subtrees = [cbor.l]
    const keys = []
    const vals = []
    let prevKey = Buffer.alloc(0)
    for (const e of cbor.e) {
      const suffix = Buffer.from(e.k)
      const thisKey = Buffer.concat([prevKey.subarray(0, e.p), suffix])
      keys.push(thisKey.toString('utf8'))
      vals.push(e.v)
      subtrees.push(e.t)
      prevKey = thisKey
    }
    return new MSTNode(keys, vals, subtrees)
  }
}

// In-memory node store — maps CID string -> { cid, bytes }. get(null) returns the
// (stored) empty node, matching atmst NodeStore.get_node(None).
export class NodeStore {
  constructor () { this.blocks = new Map() }

  storedNode (node) {
    const bytes = node.serialise()
    const cid = cidForBytesSync(bytes)
    this.blocks.set(cid.toString(), { cid, bytes })
    return node
  }

  getNode (cid) {
    if (cid === null || cid === undefined) return this.storedNode(MSTNode.empty())
    const b = this.blocks.get(cid.toString())
    if (!b) throw new Error(`missing MST node ${cid}`)
    return MSTNode.deserialise(b.bytes)
  }
}

export class NodeWrangler {
  constructor (ns) { this.ns = ns }

  putRecord (rootCid, key, val) {
    const root = this.ns.getNode(rootCid)
    if (root.isEmpty()) return this._putHere(root, key, val).cid()
    return this._putRecursive(root, key, val, keyHeight(key), root.height()).cid()
  }

  delRecord (rootCid, key) {
    const root = this.ns.getNode(rootCid)
    const afterDel = this._deleteRecursive(root, key, keyHeight(key), root.height())
    return this.ns.getNode(this._squashTop(afterDel)).cid()
  }

  _putHere (node, key, val) {
    const i = node.gteIndex(key)
    if (i < node.keys.length && node.keys[i] === key) {
      if (cidEq(node.vals[i], val)) return node
      return this.ns.storedNode(new MSTNode(node.keys.slice(), replaceAt(node.vals, i, val), node.subtrees.slice()))
    }
    const [lsub, rsub] = this._splitOnKey(node.subtrees[i], key)
    return this.ns.storedNode(new MSTNode(
      insertAt(node.keys, i, key),
      insertAt(node.vals, i, val),
      node.subtrees.slice(0, i).concat([lsub, rsub], node.subtrees.slice(i + 1))
    ))
  }

  _putRecursive (node, key, val, keyH, treeH) {
    if (keyH > treeH) { // grow the tree upward
      return this.ns.storedNode(this._putRecursive(
        this.ns.storedNode(new MSTNode([], [], [node.cid()])),
        key, val, keyH, treeH + 1
      ))
    }
    if (keyH < treeH) { // descend
      const i = node.gteIndex(key)
      return this.ns.storedNode(new MSTNode(
        node.keys.slice(), node.vals.slice(),
        replaceAt(node.subtrees, i, this._putRecursive(this.ns.getNode(node.subtrees[i]), key, val, keyH, treeH - 1).cid())
      ))
    }
    return this._putHere(node, key, val) // keyH === treeH
  }

  _splitOnKey (nodeCid, key) {
    if (nodeCid === null || nodeCid === undefined) return [null, null]
    const node = this.ns.getNode(nodeCid)
    const i = node.gteIndex(key)
    const [lsub, rsub] = this._splitOnKey(node.subtrees[i], key)
    const left = this.ns.storedNode(new MSTNode(node.keys.slice(0, i), node.vals.slice(0, i), node.subtrees.slice(0, i).concat([lsub]))).toOptional()
    const right = this.ns.storedNode(new MSTNode(node.keys.slice(i), node.vals.slice(i), [rsub].concat(node.subtrees.slice(i + 1)))).toOptional()
    return [left, right]
  }

  _squashTop (nodeCid) {
    const node = this.ns.getNode(nodeCid)
    if (node.keys.length) return nodeCid
    if (node.subtrees[0] === null) return nodeCid
    return this._squashTop(node.subtrees[0])
  }

  _deleteRecursive (node, key, keyH, treeH) {
    if (keyH > treeH) return node.toOptional()
    let i = node.gteIndex(key)
    if (keyH < treeH) {
      if (node.subtrees[i] === null) return node.toOptional()
      return this.ns.storedNode(new MSTNode(
        node.keys.slice(), node.vals.slice(),
        replaceAt(node.subtrees, i, this._deleteRecursive(this.ns.getNode(node.subtrees[i]), key, keyH, treeH - 1))
      )).toOptional()
    }
    i = node.gteIndex(key)
    if (i === node.keys.length || node.keys[i] !== key) return node.toOptional()
    return this.ns.storedNode(new MSTNode(
      removeAt(node.keys, i), removeAt(node.vals, i),
      node.subtrees.slice(0, i).concat([this._merge(node.subtrees[i], node.subtrees[i + 1])], node.subtrees.slice(i + 2))
    )).toOptional()
  }

  _merge (leftCid, rightCid) {
    if (leftCid === null) return rightCid
    if (rightCid === null) return leftCid
    const left = this.ns.getNode(leftCid)
    const right = this.ns.getNode(rightCid)
    return this.ns.storedNode(new MSTNode(
      left.keys.concat(right.keys), left.vals.concat(right.vals),
      left.subtrees.slice(0, -1).concat([this._merge(left.subtrees[left.subtrees.length - 1], right.subtrees[0])], right.subtrees.slice(1))
    )).toOptional()
  }
}

// Build an MST from records [{ key, value: CID }] (any order). Returns
// { root: CID, ns: NodeStore }. ns.blocks holds every node created; use
// reachableBlocks(ns, root) for just the live set (CAR output).
export function buildMst (records) {
  const ns = new NodeStore()
  const w = new NodeWrangler(ns)
  let root = ns.storedNode(MSTNode.empty()).cid()
  for (const { key, value } of records) root = w.putRecord(root, key, value)
  return { root, ns, wrangler: w }
}

// BFS the live MST nodes reachable from root (for CAR block sets).
export function reachableBlocks (ns, rootCid) {
  const out = new Map()
  const stack = [rootCid]
  while (stack.length) {
    const cid = stack.pop()
    if (cid === null || cid === undefined) continue
    const key = cid.toString()
    if (out.has(key)) continue
    const b = ns.blocks.get(key)
    if (!b) throw new Error(`missing node ${key}`)
    out.set(key, b)
    const node = MSTNode.deserialise(b.bytes)
    for (const t of node.subtrees) if (t) stack.push(t)
  }
  return out
}

// ---- Firehose MST-inversion proof (slice 3b) ----
//
// A #commit's `blocks` CAR must be a MINIMAL, self-contained proof of the
// old→new transition — not the whole tree (that would trip a relay's `tooBig`).
// This ports millipds `repo_ops.py:apply_writes` step 2b + `atmst` proof.py:
//   blocks = created | deletion_proof_cids | inductive_proof_nodes  (+ new records)
// where `inductive_proof_nodes` = every MST node READ while replaying the ops
// backward from the new root, which must reproduce the old (prevData) root.
// The prior record CIDs travel in each op's `prev` (like millipds), so a cold
// relay can invert with no old-tree state of its own.

// A NodeStore overlay: writes land in an in-memory upper layer (NOT logged);
// reads that fall through to `lower` are recorded in `.gets`. Mirrors millipds's
// OverlayBlockStore(MemoryBlockStore, LoggingBlockStoreWrapper(bs)).
export class OverlayNodeStore {
  constructor (lower) { this.lower = lower; this.upper = new Map(); this.gets = new Set() }

  storedNode (node) {
    const bytes = node.serialise()
    const cid = cidForBytesSync(bytes)
    this.upper.set(cid.toString(), { cid, bytes })
    return node
  }

  getNode (cid) {
    if (cid === null || cid === undefined) return MSTNode.empty()
    const k = cid.toString()
    const u = this.upper.get(k)
    if (u) return MSTNode.deserialise(u.bytes)
    this.gets.add(k) // a read of a pre-existing node — part of the inductive proof
    return this.lower.getNode(cid)
  }
}

// Follow the search path for `key` from `rootCid`, collecting every node visited.
// Returns { value: CID|null, proof: Set<cidStr> }. value===null ⇒ exclusion proof;
// value!==null ⇒ inclusion proof. Port of atmst find_rpath_and_build_proof.
export function findRpathProof (ns, rootCid, key) {
  const proof = new Set()
  let cid = rootCid
  while (cid !== null && cid !== undefined) {
    const node = ns.getNode(cid)
    proof.add(cid.toString())
    const i = node.gteIndex(key)
    if (i < node.keys.length && node.keys[i] === key) return { value: node.vals[i], proof }
    cid = node.subtrees[i] // descend the subtree left of the first key >= target
  }
  return { value: null, proof }
}

// Build a NodeStore holding exactly the given blocks (cid-string -> { cid, bytes }).
export function nodeStoreFromBlocks (blocks) {
  const ns = new NodeStore()
  for (const [k, v] of blocks) ns.blocks.set(k, v)
  return ns
}

// Compute the minimal firehose block set for a single commit's ops.
//   oldRecords / newRecords : [{ key, value: CID }] — the record sets BEFORE/AFTER.
//   ops : [{ action:'create'|'update'|'delete', path, cid: CID|null, prev: CID|null }]
// Returns { blocks: Map<cidStr,{cid,bytes}>, dataCid, oldRoot } — MST nodes only
// (record + commit blocks are added by the caller). Throws if the backward replay
// does not reproduce the old root (i.e. the proof would be invalid).
export function firehoseProofBlocks ({ oldRecords, newRecords, ops }) {
  const oldB = buildMst(oldRecords)
  const newB = buildMst(newRecords)
  const oldRoot = oldB.root
  const newRoot = newB.root

  const oldSet = reachableBlocks(oldB.ns, oldRoot)
  const newSet = reachableBlocks(newB.ns, newRoot)

  // combined store holds every node of BOTH trees (proof reads span both)
  const combined = new NodeStore()
  for (const [k, v] of oldSet) combined.blocks.set(k, v)
  for (const [k, v] of newSet) combined.blocks.set(k, v)

  const proofCids = new Set()

  // created: new-tree nodes not present in the old tree
  for (const k of newSet.keys()) if (!oldSet.has(k)) proofCids.add(k)

  // deletion proofs: for each delete, the exclusion-proof path in the NEW tree
  for (const op of ops) {
    if (op.action !== 'delete') continue
    const { value, proof } = findRpathProof(combined, newRoot, op.path)
    if (value !== null) throw new Error(`delete proof: ${op.path} still present in new tree`)
    for (const c of proof) proofCids.add(c)
  }

  // inductive proof: replay ops backward from newRoot; every node read is required.
  const overlay = new OverlayNodeStore(combined)
  const w = new NodeWrangler(overlay)
  let inv = newRoot
  for (let i = ops.length - 1; i >= 0; i--) {
    const op = ops[i]
    if (op.action === 'create') {
      inv = w.delRecord(inv, op.path)
    } else { // update | delete → restore the prior value
      if (op.prev === null || op.prev === undefined) throw new Error(`inversion: ${op.action} ${op.path} missing prev`)
      inv = w.putRecord(inv, op.path, op.prev)
    }
  }
  if (!inv.equals(oldRoot)) throw new Error('inversion proof failed: backward replay did not reproduce prevData root')
  for (const k of overlay.gets) proofCids.add(k)

  const blocks = new Map()
  for (const k of proofCids) blocks.set(k, combined.blocks.get(k))
  return { blocks, dataCid: newRoot, oldRoot }
}
// atproto repo — READ path (slice 1).
//
// A repo is a CAR whose root is a signed commit; the commit's `data` CID points at
// the root of a Merkle Search Tree (MST) of records. This module reads a CAR, walks
// the MST, and — most importantly — VERIFIES byte-exact fidelity by re-encoding every
// block and checking its CID. Writing/mutating the MST is slice 2.

import * as dagCbor from '@ipld/dag-cbor'
import { cidForBytes, cidForBytesSync } from './cid.js'
import { buildMst, reachableBlocks } from './mst.js'
import { unsignedCommit, signCommit, commitCid } from './commit.js'
import { readCar, writeCar } from './car.js'

// CAR read/write moved to the bare-safe minimal codec in ./car.js (was @ipld/car).
export { readCar, writeCar }

export function getBlock (car, cid) {
  const b = car.blocks.get(cid.toString())
  if (!b) throw new Error(`missing block ${cid}`)
  return b
}

export function decodeBlock (car, cid) {
  return dagCbor.decode(getBlock(car, cid).bytes)
}

// The signed commit at the CAR root.
export function loadCommit (car) {
  if (car.roots.length !== 1) throw new Error(`expected 1 root, got ${car.roots.length}`)
  const commit = decodeBlock(car, car.roots[0])
  if (!commit || !commit.did || commit.data === undefined) throw new Error('root is not a commit')
  return { cid: car.roots[0], value: commit }
}

// Walk the MST in key order, yielding { key, value: recordCid }. MST node shape:
//   { l: CID|null, e: [ { p: int, k: bytes, v: CID, t: CID|null } ] }
// keys are prefix-compressed against the previous key in the SAME node.
export function * walkMst (car, rootCid, _prevKey = '') {
  const node = decodeBlock(car, rootCid)
  if (!node || !Array.isArray(node.e)) throw new Error(`not an MST node: ${rootCid}`)
  if (node.l) yield * walkMst(car, node.l)
  let prev = ''
  for (const e of node.e) {
    const suffix = Buffer.from(e.k).toString('utf8')
    const key = prev.slice(0, e.p) + suffix
    prev = key
    yield { key, value: e.v }
    if (e.t) yield * walkMst(car, e.t)
  }
}

// All records as { key, cid, value } in key order.
export function listRecords (car) {
  const commit = loadCommit(car)
  const out = []
  for (const { key, value } of walkMst(car, commit.value.data)) {
    out.push({ key, cid: value, value: decodeBlock(car, value) })
  }
  return out
}

// Byte-exact fidelity check: re-encode every block and confirm its CID is unchanged.
// Also confirms the commit's data CID and every MST value CID resolve to a present
// block. Returns { blocks, records, ok, mismatches }.
export async function verifyRepo (car) {
  const mismatches = []
  for (const [cidStr, { cid, bytes }] of car.blocks) {
    // re-encode: decode then canonical-encode; must reproduce the exact bytes + CID
    const reencoded = dagCbor.encode(dagCbor.decode(bytes))
    const sameBytes = Buffer.from(reencoded).equals(Buffer.from(bytes))
    const recomputed = await cidForBytes(reencoded)
    if (!sameBytes || !recomputed.equals(cid)) {
      mismatches.push({ cid: cidStr, sameBytes, recomputed: recomputed.toString() })
    }
  }
  const commit = loadCommit(car)
  getBlock(car, commit.value.data) // MST root must be present
  const records = listRecords(car)
  for (const r of records) getBlock(car, r.cid) // each record block present
  return { blocks: car.blocks.size, records: records.length, ok: mismatches.length === 0, mismatches }
}

// ---- WRITE path (slice 3) ----

// Originate a full atproto repo from records. Each record is
// { collection, rkey, record } (or { key, value }). Returns the CAR bytes plus the
// commit/data CIDs. `privateKey` is the atproto secp256k1 signing key.
export async function createRepo ({ records, did, rev, privateKey }) {
  const recordBlocks = new Map()
  const mstRecords = []
  for (const r of records) {
    const key = r.key !== undefined ? r.key : `${r.collection}/${r.rkey}`
    const value = r.record !== undefined ? r.record : r.value
    const bytes = dagCbor.encode(value)
    const cid = cidForBytesSync(bytes)
    recordBlocks.set(cid.toString(), { cid, bytes })
    mstRecords.push({ key, value: cid })
  }
  const { root: dataCid, ns } = buildMst(mstRecords)
  const mstBlocks = reachableBlocks(ns, dataCid)

  const signed = signCommit(unsignedCommit({ did, rev, data: dataCid }), privateKey)
  const cCid = commitCid(signed)
  const commitBytes = dagCbor.encode(signed)

  const blocks = [{ cid: cCid, bytes: commitBytes }, ...mstBlocks.values(), ...recordBlocks.values()]
  const carBytes = await writeCar(cCid, blocks)
  return { carBytes, commitCid: cCid, dataCid, signedCommit: signed }
}
{
  "name": "@ipld/dag-cbor",
  "version": "9.2.7",
  "description": "JS implementation of DAG-CBOR",
  "author": "Rod <rod@vagg.org> (http://r.va.gg/)",
  "license": "Apache-2.0 OR MIT",
  "homepage": "https://github.com/ipld/js-dag-cbor#readme",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/ipld/js-dag-cbor.git"
  },
  "bugs": {
    "url": "https://github.com/ipld/js-dag-cbor/issues"
  },
  "publishConfig": {
    "access": "public",
    "provenance": true
  },
  "keywords": [
    "ipfs",
    "ipld",
    "multiformats"
  ],
  "type": "module",
  "types": "./dist/src/index.d.ts",
  "typesVersions": {
    "*": {
      "*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ],
      "src/*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ]
    }
  },
  "files": [
    "src",
    "dist",
    "!dist/test",
    "!**/*.tsbuildinfo"
  ],
  "exports": {
    ".": {
      "types": "./dist/src/index.d.ts",
      "import": "./src/index.js",
      "module-sync": "./src/index.js"
    }
  },
  "release": {
    "branches": [
      "master"
    ],
    "plugins": [
      [
        "@semantic-release/commit-analyzer",
        {
          "preset": "conventionalcommits",
          "releaseRules": [
            {
              "breaking": true,
              "release": "major"
            },
            {
              "revert": true,
              "release": "patch"
            },
            {
              "type": "feat",
              "release": "minor"
            },
            {
              "type": "fix",
              "release": "patch"
            },
            {
              "type": "docs",
              "release": "patch"
            },
            {
              "type": "test",
              "release": "patch"
            },
            {
              "type": "deps",
              "release": "patch"
            },
            {
              "scope": "no-release",
              "release": false
            }
          ]
        }
      ],
      [
        "@semantic-release/release-notes-generator",
        {
          "preset": "conventionalcommits",
          "presetConfig": {
            "types": [
              {
                "type": "feat",
                "section": "Features"
              },
              {
                "type": "fix",
                "section": "Bug Fixes"
              },
              {
                "type": "chore",
                "section": "Trivial Changes"
              },
              {
                "type": "docs",
                "section": "Documentation"
              },
              {
                "type": "deps",
                "section": "Dependencies"
              },
              {
                "type": "test",
                "section": "Tests"
              }
            ]
          }
        }
      ],
      "@semantic-release/changelog",
      "@semantic-release/npm",
      "@semantic-release/github",
      [
        "@semantic-release/git",
        {
          "assets": [
            "CHANGELOG.md",
            "package.json"
          ]
        }
      ]
    ]
  },
  "scripts": {
    "clean": "aegir clean",
    "lint": "aegir lint",
    "build": "aegir build",
    "release": "aegir release",
    "test": "npm run lint && aegir test",
    "test:ts": "npm run test --prefix test/ts-use",
    "test:node": "aegir test -t node --cov",
    "test:chrome": "aegir test -t browser --cov",
    "test:chrome-webworker": "aegir test -t webworker",
    "test:firefox": "aegir test -t browser -- --browser firefox",
    "test:firefox-webworker": "aegir test -t webworker -- --browser firefox",
    "test:electron-main": "aegir test -t electron-main",
    "dep-check": "aegir dep-check"
  },
  "dependencies": {
    "cborg": "^5.0.1",
    "multiformats": "^13.1.0"
  },
  "devDependencies": {
    "@ipld/garbage": "^6.0.0",
    "aegir": "^48.0.1"
  }
}
import * as cborg from 'cborg'
import { CID } from 'multiformats/cid'

// https://github.com/ipfs/go-ipfs/issues/3570#issuecomment-273931692
const CID_CBOR_TAG = 42

/**
 * @template T
 * @typedef {import('multiformats/codecs/interface').ByteView<T>} ByteView
 */

/**
 * @template T
 * @typedef {import('multiformats/codecs/interface').ArrayBufferView<T>} ArrayBufferView
 */

/**
 * @template T
 * @param {ByteView<T> | ArrayBufferView<T>} buf
 * @returns {ByteView<T>}
 */
export function toByteView (buf) {
  if (buf instanceof ArrayBuffer) {
    return new Uint8Array(buf, 0, buf.byteLength)
  }

  return buf
}

/**
 * cidEncoder will receive all Objects during encode, it needs to filter out
 * anything that's not a CID and return `null` for that so it's encoded as
 * normal.
 *
 * @param {any} obj
 * @returns {cborg.Token[]|null}
 */
function cidEncoder (obj) {
  if (obj.asCID !== obj && obj['/'] !== obj.bytes) {
    return null // any other kind of object
  }
  const cid = CID.asCID(obj)
  /* c8 ignore next 4 */
  // very unlikely case, and it'll probably throw a recursion error in cborg
  if (!cid) {
    return null
  }
  const bytes = new Uint8Array(cid.bytes.byteLength + 1)
  bytes.set(cid.bytes, 1) // prefix is 0x00, for historical reasons
  return [
    new cborg.Token(cborg.Type.tag, CID_CBOR_TAG),
    new cborg.Token(cborg.Type.bytes, bytes)
  ]
}

// eslint-disable-next-line jsdoc/require-returns-check
/**
 * Intercept all `undefined` values from an object walk and reject the entire
 * object if we find one.
 *
 * @returns {null}
 */
function undefinedEncoder () {
  throw new Error('`undefined` is not supported by the IPLD Data Model and cannot be encoded')
}

/**
 * Intercept all `number` values from an object walk and reject the entire
 * object if we find something that doesn't fit the IPLD data model (NaN &
 * Infinity).
 *
 * @param {number} num
 * @returns {null}
 */
function numberEncoder (num) {
  if (Number.isNaN(num)) {
    throw new Error('`NaN` is not supported by the IPLD Data Model and cannot be encoded')
  }
  if (num === Infinity || num === -Infinity) {
    throw new Error('`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded')
  }
  return null
}

/**
 * @param {Map<any, any>} map
 * @returns {null}
 */
function mapEncoder (map) {
  for (const key of map.keys()) {
    if (typeof key !== 'string' || key.length === 0) {
      throw new Error('Non-string Map keys are not supported by the IPLD Data Model and cannot be encoded')
    }
  }
  return null
}

const _encodeOptions = {
  float64: true,
  typeEncoders: {
    Map: mapEncoder,
    Object: cidEncoder,
    undefined: undefinedEncoder,
    number: numberEncoder
  }
}

export const encodeOptions = {
  ..._encodeOptions,
  typeEncoders: {
    ..._encodeOptions.typeEncoders
  }
}

/**
 * @param {import('cborg').TagDecodeControl} decode
 * @returns {CID}
 */
function cidDecoder (decode) {
  const bytes = /** @type {Uint8Array} */ (decode())
  if (bytes[0] !== 0) {
    throw new Error('Invalid CID for CBOR tag 42; expected leading 0x00')
  }
  return CID.decode(bytes.subarray(1)) // ignore leading 0x00
}

const _decodeOptions = {
  allowIndefinite: false,
  coerceUndefinedToNull: true,
  allowNaN: false,
  allowInfinity: false,
  allowBigInt: true, // this will lead to BigInt for ints outside of
  // safe-integer range, which may surprise users
  strict: true,
  useMaps: false,
  rejectDuplicateMapKeys: true,
  /** @type {{ [tagNumber: number]: import('cborg').TagDecoder }} */
  tags: { [CID_CBOR_TAG]: cidDecoder }
}

export const decodeOptions = {
  ..._decodeOptions,
  tags: { ..._decodeOptions.tags }
}

export const name = 'dag-cbor'
export const code = 0x71

/**
 * @template T
 * @param {T} node
 * @returns {ByteView<T>}
 */
export const encode = (node) => cborg.encode(node, _encodeOptions)

/**
 * @template T
 * @param {ByteView<T> | ArrayBufferView<T>} data
 * @returns {T}
 */
export const decode = (data) => cborg.decode(toByteView(data), _decodeOptions)
/**
 * Utilities for short weierstrass curves, combined with noble-hashes.
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { weierstrass } from "./abstract/weierstrass.js";
/** connects noble-curves to noble-hashes */
export function getHash(hash) {
    return { hash };
}
/** @deprecated use new `weierstrass()` and `ecdsa()` methods */
export function createCurve(curveDef, defHash) {
    const create = (hash) => weierstrass({ ...curveDef, hash: hash });
    return { ...create(defHash), create };
}
//# sourceMappingURL=_shortw_utils.js.map/**
 * Methods for elliptic curve multiplication by scalars.
 * Contains wNAF, pippenger.
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { bitLen, bitMask, validateObject } from "../utils.js";
import { Field, FpInvertBatch, nLength, validateField } from "./modular.js";
const _0n = BigInt(0);
const _1n = BigInt(1);
export function negateCt(condition, item) {
    const neg = item.negate();
    return condition ? neg : item;
}
/**
 * Takes a bunch of Projective Points but executes only one
 * inversion on all of them. Inversion is very slow operation,
 * so this improves performance massively.
 * Optimization: converts a list of projective points to a list of identical points with Z=1.
 */
export function normalizeZ(c, points) {
    const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
    return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
}
function validateW(W, bits) {
    if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
        throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);
}
function calcWOpts(W, scalarBits) {
    validateW(W, scalarBits);
    const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero
    const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero
    const maxNumber = 2 ** W; // W=8 256
    const mask = bitMask(W); // W=8 255 == mask 0b11111111
    const shiftBy = BigInt(W); // W=8 8
    return { windows, windowSize, mask, maxNumber, shiftBy };
}
function calcOffsets(n, window, wOpts) {
    const { windowSize, mask, maxNumber, shiftBy } = wOpts;
    let wbits = Number(n & mask); // extract W bits.
    let nextN = n >> shiftBy; // shift number by W bits.
    // What actually happens here:
    // const highestBit = Number(mask ^ (mask >> 1n));
    // let wbits2 = wbits - 1; // skip zero
    // if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);
    // split if bits > max: +224 => 256-32
    if (wbits > windowSize) {
        // we skip zero, which means instead of `>= size-1`, we do `> size`
        wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.
        nextN += _1n; // +256 (carry)
    }
    const offsetStart = window * windowSize;
    const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero
    const isZero = wbits === 0; // is current window slice a 0?
    const isNeg = wbits < 0; // is current window slice negative?
    const isNegF = window % 2 !== 0; // fake random statement for noise
    const offsetF = offsetStart; // fake offset for noise
    return { nextN, offset, isZero, isNeg, isNegF, offsetF };
}
function validateMSMPoints(points, c) {
    if (!Array.isArray(points))
        throw new Error('array expected');
    points.forEach((p, i) => {
        if (!(p instanceof c))
            throw new Error('invalid point at index ' + i);
    });
}
function validateMSMScalars(scalars, field) {
    if (!Array.isArray(scalars))
        throw new Error('array of scalars expected');
    scalars.forEach((s, i) => {
        if (!field.isValid(s))
            throw new Error('invalid scalar at index ' + i);
    });
}
// Since points in different groups cannot be equal (different object constructor),
// we can have single place to store precomputes.
// Allows to make points frozen / immutable.
const pointPrecomputes = new WeakMap();
const pointWindowSizes = new WeakMap();
function getW(P) {
    // To disable precomputes:
    // return 1;
    return pointWindowSizes.get(P) || 1;
}
function assert0(n) {
    if (n !== _0n)
        throw new Error('invalid wNAF');
}
/**
 * Elliptic curve multiplication of Point by scalar. Fragile.
 * Table generation takes **30MB of ram and 10ms on high-end CPU**,
 * but may take much longer on slow devices. Actual generation will happen on
 * first call of `multiply()`. By default, `BASE` point is precomputed.
 *
 * Scalars should always be less than curve order: this should be checked inside of a curve itself.
 * Creates precomputation tables for fast multiplication:
 * - private scalar is split by fixed size windows of W bits
 * - every window point is collected from window's table & added to accumulator
 * - since windows are different, same point inside tables won't be accessed more than once per calc
 * - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)
 * - +1 window is neccessary for wNAF
 * - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication
 *
 * @todo Research returning 2d JS array of windows, instead of a single window.
 * This would allow windows to be in different memory locations
 */
export class wNAF {
    // Parametrized with a given Point class (not individual point)
    constructor(Point, bits) {
        this.BASE = Point.BASE;
        this.ZERO = Point.ZERO;
        this.Fn = Point.Fn;
        this.bits = bits;
    }
    // non-const time multiplication ladder
    _unsafeLadder(elm, n, p = this.ZERO) {
        let d = elm;
        while (n > _0n) {
            if (n & _1n)
                p = p.add(d);
            d = d.double();
            n >>= _1n;
        }
        return p;
    }
    /**
     * Creates a wNAF precomputation window. Used for caching.
     * Default window size is set by `utils.precompute()` and is equal to 8.
     * Number of precomputed points depends on the curve size:
     * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
     * - 𝑊 is the window size
     * - 𝑛 is the bitlength of the curve order.
     * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
     * @param point Point instance
     * @param W window size
     * @returns precomputed point tables flattened to a single array
     */
    precomputeWindow(point, W) {
        const { windows, windowSize } = calcWOpts(W, this.bits);
        const points = [];
        let p = point;
        let base = p;
        for (let window = 0; window < windows; window++) {
            base = p;
            points.push(base);
            // i=1, bc we skip 0
            for (let i = 1; i < windowSize; i++) {
                base = base.add(p);
                points.push(base);
            }
            p = base.double();
        }
        return points;
    }
    /**
     * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
     * More compact implementation:
     * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
     * @returns real and fake (for const-time) points
     */
    wNAF(W, precomputes, n) {
        // Scalar should be smaller than field order
        if (!this.Fn.isValid(n))
            throw new Error('invalid scalar');
        // Accumulators
        let p = this.ZERO;
        let f = this.BASE;
        // This code was first written with assumption that 'f' and 'p' will never be infinity point:
        // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,
        // there is negate now: it is possible that negated element from low value
        // would be the same as high element, which will create carry into next window.
        // It's not obvious how this can fail, but still worth investigating later.
        const wo = calcWOpts(W, this.bits);
        for (let window = 0; window < wo.windows; window++) {
            // (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise
            const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
            n = nextN;
            if (isZero) {
                // bits are 0: add garbage to fake point
                // Important part for const-time getPublicKey: add random "noise" point to f.
                f = f.add(negateCt(isNegF, precomputes[offsetF]));
            }
            else {
                // bits are 1: add to result point
                p = p.add(negateCt(isNeg, precomputes[offset]));
            }
        }
        assert0(n);
        // Return both real and fake points: JIT won't eliminate f.
        // At this point there is a way to F be infinity-point even if p is not,
        // which makes it less const-time: around 1 bigint multiply.
        return { p, f };
    }
    /**
     * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
     * @param acc accumulator point to add result of multiplication
     * @returns point
     */
    wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
        const wo = calcWOpts(W, this.bits);
        for (let window = 0; window < wo.windows; window++) {
            if (n === _0n)
                break; // Early-exit, skip 0 value
            const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
            n = nextN;
            if (isZero) {
                // Window bits are 0: skip processing.
                // Move to next window.
                continue;
            }
            else {
                const item = precomputes[offset];
                acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM
            }
        }
        assert0(n);
        return acc;
    }
    getPrecomputes(W, point, transform) {
        // Calculate precomputes on a first run, reuse them after
        let comp = pointPrecomputes.get(point);
        if (!comp) {
            comp = this.precomputeWindow(point, W);
            if (W !== 1) {
                // Doing transform outside of if brings 15% perf hit
                if (typeof transform === 'function')
                    comp = transform(comp);
                pointPrecomputes.set(point, comp);
            }
        }
        return comp;
    }
    cached(point, scalar, transform) {
        const W = getW(point);
        return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
    }
    unsafe(point, scalar, transform, prev) {
        const W = getW(point);
        if (W === 1)
            return this._unsafeLadder(point, scalar, prev); // For W=1 ladder is ~x2 faster
        return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
    }
    // We calculate precomputes for elliptic curve point multiplication
    // using windowed method. This specifies window size and
    // stores precomputed values. Usually only base point would be precomputed.
    createCache(P, W) {
        validateW(W, this.bits);
        pointWindowSizes.set(P, W);
        pointPrecomputes.delete(P);
    }
    hasCache(elm) {
        return getW(elm) !== 1;
    }
}
/**
 * Endomorphism-specific multiplication for Koblitz curves.
 * Cost: 128 dbl, 0-256 adds.
 */
export function mulEndoUnsafe(Point, point, k1, k2) {
    let acc = point;
    let p1 = Point.ZERO;
    let p2 = Point.ZERO;
    while (k1 > _0n || k2 > _0n) {
        if (k1 & _1n)
            p1 = p1.add(acc);
        if (k2 & _1n)
            p2 = p2.add(acc);
        acc = acc.double();
        k1 >>= _1n;
        k2 >>= _1n;
    }
    return { p1, p2 };
}
/**
 * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).
 * 30x faster vs naive addition on L=4096, 10x faster than precomputes.
 * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.
 * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.
 * @param c Curve Point constructor
 * @param fieldN field over CURVE.N - important that it's not over CURVE.P
 * @param points array of L curve points
 * @param scalars array of L scalars (aka secret keys / bigints)
 */
export function pippenger(c, fieldN, points, scalars) {
    // If we split scalars by some window (let's say 8 bits), every chunk will only
    // take 256 buckets even if there are 4096 scalars, also re-uses double.
    // TODO:
    // - https://eprint.iacr.org/2024/750.pdf
    // - https://tches.iacr.org/index.php/TCHES/article/view/10287
    // 0 is accepted in scalars
    validateMSMPoints(points, c);
    validateMSMScalars(scalars, fieldN);
    const plength = points.length;
    const slength = scalars.length;
    if (plength !== slength)
        throw new Error('arrays of points and scalars must have equal length');
    // if (plength === 0) throw new Error('array must be of length >= 2');
    const zero = c.ZERO;
    const wbits = bitLen(BigInt(plength));
    let windowSize = 1; // bits
    if (wbits > 12)
        windowSize = wbits - 3;
    else if (wbits > 4)
        windowSize = wbits - 2;
    else if (wbits > 0)
        windowSize = 2;
    const MASK = bitMask(windowSize);
    const buckets = new Array(Number(MASK) + 1).fill(zero); // +1 for zero array
    const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;
    let sum = zero;
    for (let i = lastBits; i >= 0; i -= windowSize) {
        buckets.fill(zero);
        for (let j = 0; j < slength; j++) {
            const scalar = scalars[j];
            const wbits = Number((scalar >> BigInt(i)) & MASK);
            buckets[wbits] = buckets[wbits].add(points[j]);
        }
        let resI = zero; // not using this will do small speed-up, but will lose ct
        // Skip first bucket, because it is zero
        for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {
            sumI = sumI.add(buckets[j]);
            resI = resI.add(sumI);
        }
        sum = sum.add(resI);
        if (i !== 0)
            for (let j = 0; j < windowSize; j++)
                sum = sum.double();
    }
    return sum;
}
/**
 * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).
 * @param c Curve Point constructor
 * @param fieldN field over CURVE.N - important that it's not over CURVE.P
 * @param points array of L curve points
 * @returns function which multiplies points with scaars
 */
export function precomputeMSMUnsafe(c, fieldN, points, windowSize) {
    /**
     * Performance Analysis of Window-based Precomputation
     *
     * Base Case (256-bit scalar, 8-bit window):
     * - Standard precomputation requires:
     *   - 31 additions per scalar × 256 scalars = 7,936 ops
     *   - Plus 255 summary additions = 8,191 total ops
     *   Note: Summary additions can be optimized via accumulator
     *
     * Chunked Precomputation Analysis:
     * - Using 32 chunks requires:
     *   - 255 additions per chunk
     *   - 256 doublings
     *   - Total: (255 × 32) + 256 = 8,416 ops
     *
     * Memory Usage Comparison:
     * Window Size | Standard Points | Chunked Points
     * ------------|-----------------|---------------
     *     4-bit   |     520         |      15
     *     8-bit   |    4,224        |     255
     *    10-bit   |   13,824        |   1,023
     *    16-bit   |  557,056        |  65,535
     *
     * Key Advantages:
     * 1. Enables larger window sizes due to reduced memory overhead
     * 2. More efficient for smaller scalar counts:
     *    - 16 chunks: (16 × 255) + 256 = 4,336 ops
     *    - ~2x faster than standard 8,191 ops
     *
     * Limitations:
     * - Not suitable for plain precomputes (requires 256 constant doublings)
     * - Performance degrades with larger scalar counts:
     *   - Optimal for ~256 scalars
     *   - Less efficient for 4096+ scalars (Pippenger preferred)
     */
    validateW(windowSize, fieldN.BITS);
    validateMSMPoints(points, c);
    const zero = c.ZERO;
    const tableSize = 2 ** windowSize - 1; // table size (without zero)
    const chunks = Math.ceil(fieldN.BITS / windowSize); // chunks of item
    const MASK = bitMask(windowSize);
    const tables = points.map((p) => {
        const res = [];
        for (let i = 0, acc = p; i < tableSize; i++) {
            res.push(acc);
            acc = acc.add(p);
        }
        return res;
    });
    return (scalars) => {
        validateMSMScalars(scalars, fieldN);
        if (scalars.length > points.length)
            throw new Error('array of scalars must be smaller than array of points');
        let res = zero;
        for (let i = 0; i < chunks; i++) {
            // No need to double if accumulator is still zero.
            if (res !== zero)
                for (let j = 0; j < windowSize; j++)
                    res = res.double();
            const shiftBy = BigInt(chunks * windowSize - (i + 1) * windowSize);
            for (let j = 0; j < scalars.length; j++) {
                const n = scalars[j];
                const curr = Number((n >> shiftBy) & MASK);
                if (!curr)
                    continue; // skip zero scalars chunks
                res = res.add(tables[j][curr - 1]);
            }
        }
        return res;
    };
}
// TODO: remove
/** @deprecated */
export function validateBasic(curve) {
    validateField(curve.Fp);
    validateObject(curve, {
        n: 'bigint',
        h: 'bigint',
        Gx: 'field',
        Gy: 'field',
    }, {
        nBitLength: 'isSafeInteger',
        nByteLength: 'isSafeInteger',
    });
    // Set defaults
    return Object.freeze({
        ...nLength(curve.n, curve.nBitLength),
        ...curve,
        ...{ p: curve.Fp.ORDER },
    });
}
function createField(order, field, isLE) {
    if (field) {
        if (field.ORDER !== order)
            throw new Error('Field.ORDER must match order: Fp == p, Fn == n');
        validateField(field);
        return field;
    }
    else {
        return Field(order, { isLE });
    }
}
/** Validates CURVE opts and creates fields */
export function _createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
    if (FpFnLE === undefined)
        FpFnLE = type === 'edwards';
    if (!CURVE || typeof CURVE !== 'object')
        throw new Error(`expected valid ${type} CURVE object`);
    for (const p of ['p', 'n', 'h']) {
        const val = CURVE[p];
        if (!(typeof val === 'bigint' && val > _0n))
            throw new Error(`CURVE.${p} must be positive bigint`);
    }
    const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);
    const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
    const _b = type === 'weierstrass' ? 'b' : 'd';
    const params = ['Gx', 'Gy', 'a', _b];
    for (const p of params) {
        // @ts-ignore
        if (!Fp.isValid(CURVE[p]))
            throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
    }
    CURVE = Object.freeze(Object.assign({}, CURVE));
    return { CURVE, Fp, Fn };
}
//# sourceMappingURL=curve.js.mapimport { _validateObject, abytes, bytesToNumberBE, concatBytes, isBytes, isHash, utf8ToBytes, } from "../utils.js";
import { FpInvertBatch, mod } from "./modular.js";
// Octet Stream to Integer. "spec" implementation of os2ip is 2.5x slower vs bytesToNumberBE.
const os2ip = bytesToNumberBE;
// Integer to Octet Stream (numberToBytesBE)
function i2osp(value, length) {
    anum(value);
    anum(length);
    if (value < 0 || value >= 1 << (8 * length))
        throw new Error('invalid I2OSP input: ' + value);
    const res = Array.from({ length }).fill(0);
    for (let i = length - 1; i >= 0; i--) {
        res[i] = value & 0xff;
        value >>>= 8;
    }
    return new Uint8Array(res);
}
function strxor(a, b) {
    const arr = new Uint8Array(a.length);
    for (let i = 0; i < a.length; i++) {
        arr[i] = a[i] ^ b[i];
    }
    return arr;
}
function anum(item) {
    if (!Number.isSafeInteger(item))
        throw new Error('number expected');
}
function normDST(DST) {
    if (!isBytes(DST) && typeof DST !== 'string')
        throw new Error('DST must be Uint8Array or string');
    return typeof DST === 'string' ? utf8ToBytes(DST) : DST;
}
/**
 * Produces a uniformly random byte string using a cryptographic hash function H that outputs b bits.
 * [RFC 9380 5.3.1](https://www.rfc-editor.org/rfc/rfc9380#section-5.3.1).
 */
export function expand_message_xmd(msg, DST, lenInBytes, H) {
    abytes(msg);
    anum(lenInBytes);
    DST = normDST(DST);
    // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3
    if (DST.length > 255)
        DST = H(concatBytes(utf8ToBytes('H2C-OVERSIZE-DST-'), DST));
    const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H;
    const ell = Math.ceil(lenInBytes / b_in_bytes);
    if (lenInBytes > 65535 || ell > 255)
        throw new Error('expand_message_xmd: invalid lenInBytes');
    const DST_prime = concatBytes(DST, i2osp(DST.length, 1));
    const Z_pad = i2osp(0, r_in_bytes);
    const l_i_b_str = i2osp(lenInBytes, 2); // len_in_bytes_str
    const b = new Array(ell);
    const b_0 = H(concatBytes(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));
    b[0] = H(concatBytes(b_0, i2osp(1, 1), DST_prime));
    for (let i = 1; i <= ell; i++) {
        const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime];
        b[i] = H(concatBytes(...args));
    }
    const pseudo_random_bytes = concatBytes(...b);
    return pseudo_random_bytes.slice(0, lenInBytes);
}
/**
 * Produces a uniformly random byte string using an extendable-output function (XOF) H.
 * 1. The collision resistance of H MUST be at least k bits.
 * 2. H MUST be an XOF that has been proved indifferentiable from
 *    a random oracle under a reasonable cryptographic assumption.
 * [RFC 9380 5.3.2](https://www.rfc-editor.org/rfc/rfc9380#section-5.3.2).
 */
export function expand_message_xof(msg, DST, lenInBytes, k, H) {
    abytes(msg);
    anum(lenInBytes);
    DST = normDST(DST);
    // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3
    // DST = H('H2C-OVERSIZE-DST-' || a_very_long_DST, Math.ceil((lenInBytes * k) / 8));
    if (DST.length > 255) {
        const dkLen = Math.ceil((2 * k) / 8);
        DST = H.create({ dkLen }).update(utf8ToBytes('H2C-OVERSIZE-DST-')).update(DST).digest();
    }
    if (lenInBytes > 65535 || DST.length > 255)
        throw new Error('expand_message_xof: invalid lenInBytes');
    return (H.create({ dkLen: lenInBytes })
        .update(msg)
        .update(i2osp(lenInBytes, 2))
        // 2. DST_prime = DST || I2OSP(len(DST), 1)
        .update(DST)
        .update(i2osp(DST.length, 1))
        .digest());
}
/**
 * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F.
 * [RFC 9380 5.2](https://www.rfc-editor.org/rfc/rfc9380#section-5.2).
 * @param msg a byte string containing the message to hash
 * @param count the number of elements of F to output
 * @param options `{DST: string, p: bigint, m: number, k: number, expand: 'xmd' | 'xof', hash: H}`, see above
 * @returns [u_0, ..., u_(count - 1)], a list of field elements.
 */
export function hash_to_field(msg, count, options) {
    _validateObject(options, {
        p: 'bigint',
        m: 'number',
        k: 'number',
        hash: 'function',
    });
    const { p, k, m, hash, expand, DST } = options;
    if (!isHash(options.hash))
        throw new Error('expected valid hash');
    abytes(msg);
    anum(count);
    const log2p = p.toString(2).length;
    const L = Math.ceil((log2p + k) / 8); // section 5.1 of ietf draft link above
    const len_in_bytes = count * m * L;
    let prb; // pseudo_random_bytes
    if (expand === 'xmd') {
        prb = expand_message_xmd(msg, DST, len_in_bytes, hash);
    }
    else if (expand === 'xof') {
        prb = expand_message_xof(msg, DST, len_in_bytes, k, hash);
    }
    else if (expand === '_internal_pass') {
        // for internal tests only
        prb = msg;
    }
    else {
        throw new Error('expand must be "xmd" or "xof"');
    }
    const u = new Array(count);
    for (let i = 0; i < count; i++) {
        const e = new Array(m);
        for (let j = 0; j < m; j++) {
            const elm_offset = L * (j + i * m);
            const tv = prb.subarray(elm_offset, elm_offset + L);
            e[j] = mod(os2ip(tv), p);
        }
        u[i] = e;
    }
    return u;
}
export function isogenyMap(field, map) {
    // Make same order as in spec
    const coeff = map.map((i) => Array.from(i).reverse());
    return (x, y) => {
        const [xn, xd, yn, yd] = coeff.map((val) => val.reduce((acc, i) => field.add(field.mul(acc, x), i)));
        // 6.6.3
        // Exceptional cases of iso_map are inputs that cause the denominator of
        // either rational function to evaluate to zero; such cases MUST return
        // the identity point on E.
        const [xd_inv, yd_inv] = FpInvertBatch(field, [xd, yd], true);
        x = field.mul(xn, xd_inv); // xNum / xDen
        y = field.mul(y, field.mul(yn, yd_inv)); // y * (yNum / yDev)
        return { x, y };
    };
}
export const _DST_scalar = utf8ToBytes('HashToScalar-');
/** Creates hash-to-curve methods from EC Point and mapToCurve function. See {@link H2CHasher}. */
export function createHasher(Point, mapToCurve, defaults) {
    if (typeof mapToCurve !== 'function')
        throw new Error('mapToCurve() must be defined');
    function map(num) {
        return Point.fromAffine(mapToCurve(num));
    }
    function clear(initial) {
        const P = initial.clearCofactor();
        if (P.equals(Point.ZERO))
            return Point.ZERO; // zero will throw in assert
        P.assertValidity();
        return P;
    }
    return {
        defaults,
        hashToCurve(msg, options) {
            const opts = Object.assign({}, defaults, options);
            const u = hash_to_field(msg, 2, opts);
            const u0 = map(u[0]);
            const u1 = map(u[1]);
            return clear(u0.add(u1));
        },
        encodeToCurve(msg, options) {
            const optsDst = defaults.encodeDST ? { DST: defaults.encodeDST } : {};
            const opts = Object.assign({}, defaults, optsDst, options);
            const u = hash_to_field(msg, 1, opts);
            const u0 = map(u[0]);
            return clear(u0);
        },
        /** See {@link H2CHasher} */
        mapToCurve(scalars) {
            if (!Array.isArray(scalars))
                throw new Error('expected array of bigints');
            for (const i of scalars)
                if (typeof i !== 'bigint')
                    throw new Error('expected array of bigints');
            return clear(map(scalars));
        },
        // hash_to_scalar can produce 0: https://www.rfc-editor.org/errata/eid8393
        // RFC 9380, draft-irtf-cfrg-bbs-signatures-08
        hashToScalar(msg, options) {
            // @ts-ignore
            const N = Point.Fn.ORDER;
            const opts = Object.assign({}, defaults, { p: N, m: 1, DST: _DST_scalar }, options);
            return hash_to_field(msg, 1, opts)[0][0];
        },
    };
}
//# sourceMappingURL=hash-to-curve.js.map/**
 * Utils for modular division and fields.
 * Field over 11 is a finite (Galois) field is integer number operations `mod 11`.
 * There is no division: it is replaced by modular multiplicative inverse.
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { _validateObject, anumber, bitMask, bytesToNumberBE, bytesToNumberLE, ensureBytes, numberToBytesBE, numberToBytesLE, } from "../utils.js";
// prettier-ignore
const _0n = BigInt(0), _1n = BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3);
// prettier-ignore
const _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5), _7n = /* @__PURE__ */ BigInt(7);
// prettier-ignore
const _8n = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9), _16n = /* @__PURE__ */ BigInt(16);
// Calculates a modulo b
export function mod(a, b) {
    const result = a % b;
    return result >= _0n ? result : b + result;
}
/**
 * Efficiently raise num to power and do modular division.
 * Unsafe in some contexts: uses ladder, so can expose bigint bits.
 * @example
 * pow(2n, 6n, 11n) // 64n % 11n == 9n
 */
export function pow(num, power, modulo) {
    return FpPow(Field(modulo), num, power);
}
/** Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)` */
export function pow2(x, power, modulo) {
    let res = x;
    while (power-- > _0n) {
        res *= res;
        res %= modulo;
    }
    return res;
}
/**
 * Inverses number over modulo.
 * Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).
 */
export function invert(number, modulo) {
    if (number === _0n)
        throw new Error('invert: expected non-zero number');
    if (modulo <= _0n)
        throw new Error('invert: expected positive modulus, got ' + modulo);
    // Fermat's little theorem "CT-like" version inv(n) = n^(m-2) mod m is 30x slower.
    let a = mod(number, modulo);
    let b = modulo;
    // prettier-ignore
    let x = _0n, y = _1n, u = _1n, v = _0n;
    while (a !== _0n) {
        // JIT applies optimization if those two lines follow each other
        const q = b / a;
        const r = b % a;
        const m = x - u * q;
        const n = y - v * q;
        // prettier-ignore
        b = a, a = r, x = u, y = v, u = m, v = n;
    }
    const gcd = b;
    if (gcd !== _1n)
        throw new Error('invert: does not exist');
    return mod(x, modulo);
}
function assertIsSquare(Fp, root, n) {
    if (!Fp.eql(Fp.sqr(root), n))
        throw new Error('Cannot find square root');
}
// Not all roots are possible! Example which will throw:
// const NUM =
// n = 72057594037927816n;
// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));
function sqrt3mod4(Fp, n) {
    const p1div4 = (Fp.ORDER + _1n) / _4n;
    const root = Fp.pow(n, p1div4);
    assertIsSquare(Fp, root, n);
    return root;
}
function sqrt5mod8(Fp, n) {
    const p5div8 = (Fp.ORDER - _5n) / _8n;
    const n2 = Fp.mul(n, _2n);
    const v = Fp.pow(n2, p5div8);
    const nv = Fp.mul(n, v);
    const i = Fp.mul(Fp.mul(nv, _2n), v);
    const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
    assertIsSquare(Fp, root, n);
    return root;
}
// Based on RFC9380, Kong algorithm
// prettier-ignore
function sqrt9mod16(P) {
    const Fp_ = Field(P);
    const tn = tonelliShanks(P);
    const c1 = tn(Fp_, Fp_.neg(Fp_.ONE)); //  1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F
    const c2 = tn(Fp_, c1); //  2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F
    const c3 = tn(Fp_, Fp_.neg(c1)); //  3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F
    const c4 = (P + _7n) / _16n; //  4. c4 = (q + 7) / 16        # Integer arithmetic
    return (Fp, n) => {
        let tv1 = Fp.pow(n, c4); //  1. tv1 = x^c4
        let tv2 = Fp.mul(tv1, c1); //  2. tv2 = c1 * tv1
        const tv3 = Fp.mul(tv1, c2); //  3. tv3 = c2 * tv1
        const tv4 = Fp.mul(tv1, c3); //  4. tv4 = c3 * tv1
        const e1 = Fp.eql(Fp.sqr(tv2), n); //  5.  e1 = (tv2^2) == x
        const e2 = Fp.eql(Fp.sqr(tv3), n); //  6.  e2 = (tv3^2) == x
        tv1 = Fp.cmov(tv1, tv2, e1); //  7. tv1 = CMOV(tv1, tv2, e1)  # Select tv2 if (tv2^2) == x
        tv2 = Fp.cmov(tv4, tv3, e2); //  8. tv2 = CMOV(tv4, tv3, e2)  # Select tv3 if (tv3^2) == x
        const e3 = Fp.eql(Fp.sqr(tv2), n); //  9.  e3 = (tv2^2) == x
        const root = Fp.cmov(tv1, tv2, e3); // 10.  z = CMOV(tv1, tv2, e3)   # Select sqrt from tv1 & tv2
        assertIsSquare(Fp, root, n);
        return root;
    };
}
/**
 * Tonelli-Shanks square root search algorithm.
 * 1. https://eprint.iacr.org/2012/685.pdf (page 12)
 * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks
 * @param P field order
 * @returns function that takes field Fp (created from P) and number n
 */
export function tonelliShanks(P) {
    // Initialization (precomputation).
    // Caching initialization could boost perf by 7%.
    if (P < _3n)
        throw new Error('sqrt is not defined for small field');
    // Factor P - 1 = Q * 2^S, where Q is odd
    let Q = P - _1n;
    let S = 0;
    while (Q % _2n === _0n) {
        Q /= _2n;
        S++;
    }
    // Find the first quadratic non-residue Z >= 2
    let Z = _2n;
    const _Fp = Field(P);
    while (FpLegendre(_Fp, Z) === 1) {
        // Basic primality test for P. After x iterations, chance of
        // not finding quadratic non-residue is 2^x, so 2^1000.
        if (Z++ > 1000)
            throw new Error('Cannot find square root: probably non-prime P');
    }
    // Fast-path; usually done before Z, but we do "primality test".
    if (S === 1)
        return sqrt3mod4;
    // Slow-path
    // TODO: test on Fp2 and others
    let cc = _Fp.pow(Z, Q); // c = z^Q
    const Q1div2 = (Q + _1n) / _2n;
    return function tonelliSlow(Fp, n) {
        if (Fp.is0(n))
            return n;
        // Check if n is a quadratic residue using Legendre symbol
        if (FpLegendre(Fp, n) !== 1)
            throw new Error('Cannot find square root');
        // Initialize variables for the main loop
        let M = S;
        let c = Fp.mul(Fp.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp
        let t = Fp.pow(n, Q); // t = n^Q, first guess at the fudge factor
        let R = Fp.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root
        // Main loop
        // while t != 1
        while (!Fp.eql(t, Fp.ONE)) {
            if (Fp.is0(t))
                return Fp.ZERO; // if t=0 return R=0
            let i = 1;
            // Find the smallest i >= 1 such that t^(2^i) ≡ 1 (mod P)
            let t_tmp = Fp.sqr(t); // t^(2^1)
            while (!Fp.eql(t_tmp, Fp.ONE)) {
                i++;
                t_tmp = Fp.sqr(t_tmp); // t^(2^2)...
                if (i === M)
                    throw new Error('Cannot find square root');
            }
            // Calculate the exponent for b: 2^(M - i - 1)
            const exponent = _1n << BigInt(M - i - 1); // bigint is important
            const b = Fp.pow(c, exponent); // b = 2^(M - i - 1)
            // Update variables
            M = i;
            c = Fp.sqr(b); // c = b^2
            t = Fp.mul(t, c); // t = (t * b^2)
            R = Fp.mul(R, b); // R = R*b
        }
        return R;
    };
}
/**
 * Square root for a finite field. Will try optimized versions first:
 *
 * 1. P ≡ 3 (mod 4)
 * 2. P ≡ 5 (mod 8)
 * 3. P ≡ 9 (mod 16)
 * 4. Tonelli-Shanks algorithm
 *
 * Different algorithms can give different roots, it is up to user to decide which one they want.
 * For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).
 */
export function FpSqrt(P) {
    // P ≡ 3 (mod 4) => √n = n^((P+1)/4)
    if (P % _4n === _3n)
        return sqrt3mod4;
    // P ≡ 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf
    if (P % _8n === _5n)
        return sqrt5mod8;
    // P ≡ 9 (mod 16) => Kong algorithm, page 11 of https://eprint.iacr.org/2012/685.pdf (algorithm 4)
    if (P % _16n === _9n)
        return sqrt9mod16(P);
    // Tonelli-Shanks algorithm
    return tonelliShanks(P);
}
// Little-endian check for first LE bit (last BE bit);
export const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n;
// prettier-ignore
const FIELD_FIELDS = [
    'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',
    'eql', 'add', 'sub', 'mul', 'pow', 'div',
    'addN', 'subN', 'mulN', 'sqrN'
];
export function validateField(field) {
    const initial = {
        ORDER: 'bigint',
        MASK: 'bigint',
        BYTES: 'number',
        BITS: 'number',
    };
    const opts = FIELD_FIELDS.reduce((map, val) => {
        map[val] = 'function';
        return map;
    }, initial);
    _validateObject(field, opts);
    // const max = 16384;
    // if (field.BYTES < 1 || field.BYTES > max) throw new Error('invalid field');
    // if (field.BITS < 1 || field.BITS > 8 * max) throw new Error('invalid field');
    return field;
}
// Generic field functions
/**
 * Same as `pow` but for Fp: non-constant-time.
 * Unsafe in some contexts: uses ladder, so can expose bigint bits.
 */
export function FpPow(Fp, num, power) {
    if (power < _0n)
        throw new Error('invalid exponent, negatives unsupported');
    if (power === _0n)
        return Fp.ONE;
    if (power === _1n)
        return num;
    let p = Fp.ONE;
    let d = num;
    while (power > _0n) {
        if (power & _1n)
            p = Fp.mul(p, d);
        d = Fp.sqr(d);
        power >>= _1n;
    }
    return p;
}
/**
 * Efficiently invert an array of Field elements.
 * Exception-free. Will return `undefined` for 0 elements.
 * @param passZero map 0 to 0 (instead of undefined)
 */
export function FpInvertBatch(Fp, nums, passZero = false) {
    const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : undefined);
    // Walk from first to last, multiply them by each other MOD p
    const multipliedAcc = nums.reduce((acc, num, i) => {
        if (Fp.is0(num))
            return acc;
        inverted[i] = acc;
        return Fp.mul(acc, num);
    }, Fp.ONE);
    // Invert last element
    const invertedAcc = Fp.inv(multipliedAcc);
    // Walk from last to first, multiply them by inverted each other MOD p
    nums.reduceRight((acc, num, i) => {
        if (Fp.is0(num))
            return acc;
        inverted[i] = Fp.mul(acc, inverted[i]);
        return Fp.mul(acc, num);
    }, invertedAcc);
    return inverted;
}
// TODO: remove
export function FpDiv(Fp, lhs, rhs) {
    return Fp.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, Fp.ORDER) : Fp.inv(rhs));
}
/**
 * Legendre symbol.
 * Legendre constant is used to calculate Legendre symbol (a | p)
 * which denotes the value of a^((p-1)/2) (mod p).
 *
 * * (a | p) ≡ 1    if a is a square (mod p), quadratic residue
 * * (a | p) ≡ -1   if a is not a square (mod p), quadratic non residue
 * * (a | p) ≡ 0    if a ≡ 0 (mod p)
 */
export function FpLegendre(Fp, n) {
    // We can use 3rd argument as optional cache of this value
    // but seems unneeded for now. The operation is very fast.
    const p1mod2 = (Fp.ORDER - _1n) / _2n;
    const powered = Fp.pow(n, p1mod2);
    const yes = Fp.eql(powered, Fp.ONE);
    const zero = Fp.eql(powered, Fp.ZERO);
    const no = Fp.eql(powered, Fp.neg(Fp.ONE));
    if (!yes && !zero && !no)
        throw new Error('invalid Legendre symbol result');
    return yes ? 1 : zero ? 0 : -1;
}
// This function returns True whenever the value x is a square in the field F.
export function FpIsSquare(Fp, n) {
    const l = FpLegendre(Fp, n);
    return l === 1;
}
// CURVE.n lengths
export function nLength(n, nBitLength) {
    // Bit size, byte size of CURVE.n
    if (nBitLength !== undefined)
        anumber(nBitLength);
    const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;
    const nByteLength = Math.ceil(_nBitLength / 8);
    return { nBitLength: _nBitLength, nByteLength };
}
/**
 * Creates a finite field. Major performance optimizations:
 * * 1. Denormalized operations like mulN instead of mul.
 * * 2. Identical object shape: never add or remove keys.
 * * 3. `Object.freeze`.
 * Fragile: always run a benchmark on a change.
 * Security note: operations don't check 'isValid' for all elements for performance reasons,
 * it is caller responsibility to check this.
 * This is low-level code, please make sure you know what you're doing.
 *
 * Note about field properties:
 * * CHARACTERISTIC p = prime number, number of elements in main subgroup.
 * * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.
 *
 * @param ORDER field order, probably prime, or could be composite
 * @param bitLen how many bits the field consumes
 * @param isLE (default: false) if encoding / decoding should be in little-endian
 * @param redef optional faster redefinitions of sqrt and other methods
 */
export function Field(ORDER, bitLenOrOpts, // TODO: use opts only in v2?
isLE = false, opts = {}) {
    if (ORDER <= _0n)
        throw new Error('invalid field: expected ORDER > 0, got ' + ORDER);
    let _nbitLength = undefined;
    let _sqrt = undefined;
    let modFromBytes = false;
    let allowedLengths = undefined;
    if (typeof bitLenOrOpts === 'object' && bitLenOrOpts != null) {
        if (opts.sqrt || isLE)
            throw new Error('cannot specify opts in two arguments');
        const _opts = bitLenOrOpts;
        if (_opts.BITS)
            _nbitLength = _opts.BITS;
        if (_opts.sqrt)
            _sqrt = _opts.sqrt;
        if (typeof _opts.isLE === 'boolean')
            isLE = _opts.isLE;
        if (typeof _opts.modFromBytes === 'boolean')
            modFromBytes = _opts.modFromBytes;
        allowedLengths = _opts.allowedLengths;
    }
    else {
        if (typeof bitLenOrOpts === 'number')
            _nbitLength = bitLenOrOpts;
        if (opts.sqrt)
            _sqrt = opts.sqrt;
    }
    const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, _nbitLength);
    if (BYTES > 2048)
        throw new Error('invalid field: expected ORDER of <= 2048 bytes');
    let sqrtP; // cached sqrtP
    const f = Object.freeze({
        ORDER,
        isLE,
        BITS,
        BYTES,
        MASK: bitMask(BITS),
        ZERO: _0n,
        ONE: _1n,
        allowedLengths: allowedLengths,
        create: (num) => mod(num, ORDER),
        isValid: (num) => {
            if (typeof num !== 'bigint')
                throw new Error('invalid field element: expected bigint, got ' + typeof num);
            return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible
        },
        is0: (num) => num === _0n,
        // is valid and invertible
        isValidNot0: (num) => !f.is0(num) && f.isValid(num),
        isOdd: (num) => (num & _1n) === _1n,
        neg: (num) => mod(-num, ORDER),
        eql: (lhs, rhs) => lhs === rhs,
        sqr: (num) => mod(num * num, ORDER),
        add: (lhs, rhs) => mod(lhs + rhs, ORDER),
        sub: (lhs, rhs) => mod(lhs - rhs, ORDER),
        mul: (lhs, rhs) => mod(lhs * rhs, ORDER),
        pow: (num, power) => FpPow(f, num, power),
        div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),
        // Same as above, but doesn't normalize
        sqrN: (num) => num * num,
        addN: (lhs, rhs) => lhs + rhs,
        subN: (lhs, rhs) => lhs - rhs,
        mulN: (lhs, rhs) => lhs * rhs,
        inv: (num) => invert(num, ORDER),
        sqrt: _sqrt ||
            ((n) => {
                if (!sqrtP)
                    sqrtP = FpSqrt(ORDER);
                return sqrtP(f, n);
            }),
        toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),
        fromBytes: (bytes, skipValidation = true) => {
            if (allowedLengths) {
                if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
                    throw new Error('Field.fromBytes: expected ' + allowedLengths + ' bytes, got ' + bytes.length);
                }
                const padded = new Uint8Array(BYTES);
                // isLE add 0 to right, !isLE to the left.
                padded.set(bytes, isLE ? 0 : padded.length - bytes.length);
                bytes = padded;
            }
            if (bytes.length !== BYTES)
                throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);
            let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
            if (modFromBytes)
                scalar = mod(scalar, ORDER);
            if (!skipValidation)
                if (!f.isValid(scalar))
                    throw new Error('invalid field element: outside of range 0..ORDER');
            // NOTE: we don't validate scalar here, please use isValid. This done such way because some
            // protocol may allow non-reduced scalar that reduced later or changed some other way.
            return scalar;
        },
        // TODO: we don't need it here, move out to separate fn
        invertBatch: (lst) => FpInvertBatch(f, lst),
        // We can't move this out because Fp6, Fp12 implement it
        // and it's unclear what to return in there.
        cmov: (a, b, c) => (c ? b : a),
    });
    return Object.freeze(f);
}
// Generic random scalar, we can do same for other fields if via Fp2.mul(Fp2.ONE, Fp2.random)?
// This allows unsafe methods like ignore bias or zero. These unsafe, but often used in different protocols (if deterministic RNG).
// which mean we cannot force this via opts.
// Not sure what to do with randomBytes, we can accept it inside opts if wanted.
// Probably need to export getMinHashLength somewhere?
// random(bytes?: Uint8Array, unsafeAllowZero = false, unsafeAllowBias = false) {
//   const LEN = !unsafeAllowBias ? getMinHashLength(ORDER) : BYTES;
//   if (bytes === undefined) bytes = randomBytes(LEN); // _opts.randomBytes?
//   const num = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
//   // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0
//   const reduced = unsafeAllowZero ? mod(num, ORDER) : mod(num, ORDER - _1n) + _1n;
//   return reduced;
// },
export function FpSqrtOdd(Fp, elm) {
    if (!Fp.isOdd)
        throw new Error("Field doesn't have isOdd");
    const root = Fp.sqrt(elm);
    return Fp.isOdd(root) ? root : Fp.neg(root);
}
export function FpSqrtEven(Fp, elm) {
    if (!Fp.isOdd)
        throw new Error("Field doesn't have isOdd");
    const root = Fp.sqrt(elm);
    return Fp.isOdd(root) ? Fp.neg(root) : root;
}
/**
 * "Constant-time" private key generation utility.
 * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field).
 * Which makes it slightly more biased, less secure.
 * @deprecated use `mapKeyToField` instead
 */
export function hashToPrivateScalar(hash, groupOrder, isLE = false) {
    hash = ensureBytes('privateHash', hash);
    const hashLen = hash.length;
    const minLen = nLength(groupOrder).nByteLength + 8;
    if (minLen < 24 || hashLen < minLen || hashLen > 1024)
        throw new Error('hashToPrivateScalar: expected ' + minLen + '-1024 bytes of input, got ' + hashLen);
    const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash);
    return mod(num, groupOrder - _1n) + _1n;
}
/**
 * Returns total number of bytes consumed by the field element.
 * For example, 32 bytes for usual 256-bit weierstrass curve.
 * @param fieldOrder number of field elements, usually CURVE.n
 * @returns byte length of field
 */
export function getFieldBytesLength(fieldOrder) {
    if (typeof fieldOrder !== 'bigint')
        throw new Error('field order must be bigint');
    const bitLength = fieldOrder.toString(2).length;
    return Math.ceil(bitLength / 8);
}
/**
 * Returns minimal amount of bytes that can be safely reduced
 * by field order.
 * Should be 2^-128 for 128-bit curve such as P256.
 * @param fieldOrder number of field elements, usually CURVE.n
 * @returns byte length of target hash
 */
export function getMinHashLength(fieldOrder) {
    const length = getFieldBytesLength(fieldOrder);
    return length + Math.ceil(length / 2);
}
/**
 * "Constant-time" private key generation utility.
 * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF
 * and convert them into private scalar, with the modulo bias being negligible.
 * Needs at least 48 bytes of input for 32-byte private key.
 * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/
 * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final
 * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5
 * @param hash hash output from SHA3 or a similar function
 * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)
 * @param isLE interpret hash bytes as LE num
 * @returns valid private scalar
 */
export function mapHashToField(key, fieldOrder, isLE = false) {
    const len = key.length;
    const fieldLen = getFieldBytesLength(fieldOrder);
    const minLen = getMinHashLength(fieldOrder);
    // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.
    if (len < 16 || len < minLen || len > 1024)
        throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);
    const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);
    // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0
    const reduced = mod(num, fieldOrder - _1n) + _1n;
    return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
}
//# sourceMappingURL=modular.js.map/**
 * Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.
 *
 * ### Design rationale for types
 *
 * * Interaction between classes from different curves should fail:
 *   `k256.Point.BASE.add(p256.Point.BASE)`
 * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime
 * * Different calls of `curve()` would return different classes -
 *   `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,
 *   it won't affect others
 *
 * TypeScript can't infer types for classes created inside a function. Classes is one instance
 * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create
 * unique type for every function call.
 *
 * We can use generic types via some param, like curve opts, but that would:
 *     1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)
 *     which is hard to debug.
 *     2. Params can be generic and we can't enforce them to be constant value:
 *     if somebody creates curve from non-constant params,
 *     it would be allowed to interact with other curves with non-constant params
 *
 * @todo https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { hmac as nobleHmac } from '@noble/hashes/hmac.js';
import { ahash } from '@noble/hashes/utils';
import { _validateObject, _abool2 as abool, _abytes2 as abytes, aInRange, bitLen, bitMask, bytesToHex, bytesToNumberBE, concatBytes, createHmacDrbg, ensureBytes, hexToBytes, inRange, isBytes, memoized, numberToHexUnpadded, randomBytes as randomBytesWeb, } from "../utils.js";
import { _createCurveFields, mulEndoUnsafe, negateCt, normalizeZ, pippenger, wNAF, } from "./curve.js";
import { Field, FpInvertBatch, getMinHashLength, mapHashToField, nLength, validateField, } from "./modular.js";
// We construct basis in such way that den is always positive and equals n, but num sign depends on basis (not on secret value)
const divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n) / den;
/**
 * Splits scalar for GLV endomorphism.
 */
export function _splitEndoScalar(k, basis, n) {
    // Split scalar into two such that part is ~half bits: `abs(part) < sqrt(N)`
    // Since part can be negative, we need to do this on point.
    // TODO: verifyScalar function which consumes lambda
    const [[a1, b1], [a2, b2]] = basis;
    const c1 = divNearest(b2 * k, n);
    const c2 = divNearest(-b1 * k, n);
    // |k1|/|k2| is < sqrt(N), but can be negative.
    // If we do `k1 mod N`, we'll get big scalar (`> sqrt(N)`): so, we do cheaper negation instead.
    let k1 = k - c1 * a1 - c2 * a2;
    let k2 = -c1 * b1 - c2 * b2;
    const k1neg = k1 < _0n;
    const k2neg = k2 < _0n;
    if (k1neg)
        k1 = -k1;
    if (k2neg)
        k2 = -k2;
    // Double check that resulting scalar less than half bits of N: otherwise wNAF will fail.
    // This should only happen on wrong basises. Also, math inside is too complex and I don't trust it.
    const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n; // Half bits of N
    if (k1 < _0n || k1 >= MAX_NUM || k2 < _0n || k2 >= MAX_NUM) {
        throw new Error('splitScalar (endomorphism): failed, k=' + k);
    }
    return { k1neg, k1, k2neg, k2 };
}
function validateSigFormat(format) {
    if (!['compact', 'recovered', 'der'].includes(format))
        throw new Error('Signature format must be "compact", "recovered", or "der"');
    return format;
}
function validateSigOpts(opts, def) {
    const optsn = {};
    for (let optName of Object.keys(def)) {
        // @ts-ignore
        optsn[optName] = opts[optName] === undefined ? def[optName] : opts[optName];
    }
    abool(optsn.lowS, 'lowS');
    abool(optsn.prehash, 'prehash');
    if (optsn.format !== undefined)
        validateSigFormat(optsn.format);
    return optsn;
}
export class DERErr extends Error {
    constructor(m = '') {
        super(m);
    }
}
/**
 * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:
 *
 *     [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]
 *
 * Docs: https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/, https://luca.ntop.org/Teaching/Appunti/asn1.html
 */
export const DER = {
    // asn.1 DER encoding utils
    Err: DERErr,
    // Basic building block is TLV (Tag-Length-Value)
    _tlv: {
        encode: (tag, data) => {
            const { Err: E } = DER;
            if (tag < 0 || tag > 256)
                throw new E('tlv.encode: wrong tag');
            if (data.length & 1)
                throw new E('tlv.encode: unpadded data');
            const dataLen = data.length / 2;
            const len = numberToHexUnpadded(dataLen);
            if ((len.length / 2) & 128)
                throw new E('tlv.encode: long form length too big');
            // length of length with long form flag
            const lenLen = dataLen > 127 ? numberToHexUnpadded((len.length / 2) | 128) : '';
            const t = numberToHexUnpadded(tag);
            return t + lenLen + len + data;
        },
        // v - value, l - left bytes (unparsed)
        decode(tag, data) {
            const { Err: E } = DER;
            let pos = 0;
            if (tag < 0 || tag > 256)
                throw new E('tlv.encode: wrong tag');
            if (data.length < 2 || data[pos++] !== tag)
                throw new E('tlv.decode: wrong tlv');
            const first = data[pos++];
            const isLong = !!(first & 128); // First bit of first length byte is flag for short/long form
            let length = 0;
            if (!isLong)
                length = first;
            else {
                // Long form: [longFlag(1bit), lengthLength(7bit), length (BE)]
                const lenLen = first & 127;
                if (!lenLen)
                    throw new E('tlv.decode(long): indefinite length not supported');
                if (lenLen > 4)
                    throw new E('tlv.decode(long): byte length is too big'); // this will overflow u32 in js
                const lengthBytes = data.subarray(pos, pos + lenLen);
                if (lengthBytes.length !== lenLen)
                    throw new E('tlv.decode: length bytes not complete');
                if (lengthBytes[0] === 0)
                    throw new E('tlv.decode(long): zero leftmost byte');
                for (const b of lengthBytes)
                    length = (length << 8) | b;
                pos += lenLen;
                if (length < 128)
                    throw new E('tlv.decode(long): not minimal encoding');
            }
            const v = data.subarray(pos, pos + length);
            if (v.length !== length)
                throw new E('tlv.decode: wrong value length');
            return { v, l: data.subarray(pos + length) };
        },
    },
    // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
    // since we always use positive integers here. It must always be empty:
    // - add zero byte if exists
    // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
    _int: {
        encode(num) {
            const { Err: E } = DER;
            if (num < _0n)
                throw new E('integer: negative integers are not allowed');
            let hex = numberToHexUnpadded(num);
            // Pad with zero byte if negative flag is present
            if (Number.parseInt(hex[0], 16) & 0b1000)
                hex = '00' + hex;
            if (hex.length & 1)
                throw new E('unexpected DER parsing assertion: unpadded hex');
            return hex;
        },
        decode(data) {
            const { Err: E } = DER;
            if (data[0] & 128)
                throw new E('invalid signature integer: negative');
            if (data[0] === 0x00 && !(data[1] & 128))
                throw new E('invalid signature integer: unnecessary leading zero');
            return bytesToNumberBE(data);
        },
    },
    toSig(hex) {
        // parse DER signature
        const { Err: E, _int: int, _tlv: tlv } = DER;
        const data = ensureBytes('signature', hex);
        const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);
        if (seqLeftBytes.length)
            throw new E('invalid signature: left bytes after parsing');
        const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);
        const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);
        if (sLeftBytes.length)
            throw new E('invalid signature: left bytes after parsing');
        return { r: int.decode(rBytes), s: int.decode(sBytes) };
    },
    hexFromSig(sig) {
        const { _tlv: tlv, _int: int } = DER;
        const rs = tlv.encode(0x02, int.encode(sig.r));
        const ss = tlv.encode(0x02, int.encode(sig.s));
        const seq = rs + ss;
        return tlv.encode(0x30, seq);
    },
};
// Be friendly to bad ECMAScript parsers by not using bigint literals
// prettier-ignore
const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4);
export function _normFnElement(Fn, key) {
    const { BYTES: expected } = Fn;
    let num;
    if (typeof key === 'bigint') {
        num = key;
    }
    else {
        let bytes = ensureBytes('private key', key);
        try {
            num = Fn.fromBytes(bytes);
        }
        catch (error) {
            throw new Error(`invalid private key: expected ui8a of size ${expected}, got ${typeof key}`);
        }
    }
    if (!Fn.isValidNot0(num))
        throw new Error('invalid private key: out of range [1..N-1]');
    return num;
}
/**
 * Creates weierstrass Point constructor, based on specified curve options.
 *
 * @example
```js
const opts = {
  p: BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff'),
  n: BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551'),
  h: BigInt(1),
  a: BigInt('0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc'),
  b: BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b'),
  Gx: BigInt('0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296'),
  Gy: BigInt('0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5'),
};
const p256_Point = weierstrass(opts);
```
 */
export function weierstrassN(params, extraOpts = {}) {
    const validated = _createCurveFields('weierstrass', params, extraOpts);
    const { Fp, Fn } = validated;
    let CURVE = validated.CURVE;
    const { h: cofactor, n: CURVE_ORDER } = CURVE;
    _validateObject(extraOpts, {}, {
        allowInfinityPoint: 'boolean',
        clearCofactor: 'function',
        isTorsionFree: 'function',
        fromBytes: 'function',
        toBytes: 'function',
        endo: 'object',
        wrapPrivateKey: 'boolean',
    });
    const { endo } = extraOpts;
    if (endo) {
        // validateObject(endo, { beta: 'bigint', splitScalar: 'function' });
        if (!Fp.is0(CURVE.a) || typeof endo.beta !== 'bigint' || !Array.isArray(endo.basises)) {
            throw new Error('invalid endo: expected "beta": bigint and "basises": array');
        }
    }
    const lengths = getWLengths(Fp, Fn);
    function assertCompressionIsSupported() {
        if (!Fp.isOdd)
            throw new Error('compression is not supported: Field does not have .isOdd()');
    }
    // Implements IEEE P1363 point encoding
    function pointToBytes(_c, point, isCompressed) {
        const { x, y } = point.toAffine();
        const bx = Fp.toBytes(x);
        abool(isCompressed, 'isCompressed');
        if (isCompressed) {
            assertCompressionIsSupported();
            const hasEvenY = !Fp.isOdd(y);
            return concatBytes(pprefix(hasEvenY), bx);
        }
        else {
            return concatBytes(Uint8Array.of(0x04), bx, Fp.toBytes(y));
        }
    }
    function pointFromBytes(bytes) {
        abytes(bytes, undefined, 'Point');
        const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths; // e.g. for 32-byte: 33, 65
        const length = bytes.length;
        const head = bytes[0];
        const tail = bytes.subarray(1);
        // No actual validation is done here: use .assertValidity()
        if (length === comp && (head === 0x02 || head === 0x03)) {
            const x = Fp.fromBytes(tail);
            if (!Fp.isValid(x))
                throw new Error('bad point: is not on curve, wrong x');
            const y2 = weierstrassEquation(x); // y² = x³ + ax + b
            let y;
            try {
                y = Fp.sqrt(y2); // y = y² ^ (p+1)/4
            }
            catch (sqrtError) {
                const err = sqrtError instanceof Error ? ': ' + sqrtError.message : '';
                throw new Error('bad point: is not on curve, sqrt error' + err);
            }
            assertCompressionIsSupported();
            const isYOdd = Fp.isOdd(y); // (y & _1n) === _1n;
            const isHeadOdd = (head & 1) === 1; // ECDSA-specific
            if (isHeadOdd !== isYOdd)
                y = Fp.neg(y);
            return { x, y };
        }
        else if (length === uncomp && head === 0x04) {
            // TODO: more checks
            const L = Fp.BYTES;
            const x = Fp.fromBytes(tail.subarray(0, L));
            const y = Fp.fromBytes(tail.subarray(L, L * 2));
            if (!isValidXY(x, y))
                throw new Error('bad point: is not on curve');
            return { x, y };
        }
        else {
            throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);
        }
    }
    const encodePoint = extraOpts.toBytes || pointToBytes;
    const decodePoint = extraOpts.fromBytes || pointFromBytes;
    function weierstrassEquation(x) {
        const x2 = Fp.sqr(x); // x * x
        const x3 = Fp.mul(x2, x); // x² * x
        return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b); // x³ + a * x + b
    }
    // TODO: move top-level
    /** Checks whether equation holds for given x, y: y² == x³ + ax + b */
    function isValidXY(x, y) {
        const left = Fp.sqr(y); // y²
        const right = weierstrassEquation(x); // x³ + ax + b
        return Fp.eql(left, right);
    }
    // Validate whether the passed curve params are valid.
    // Test 1: equation y² = x³ + ax + b should work for generator point.
    if (!isValidXY(CURVE.Gx, CURVE.Gy))
        throw new Error('bad curve params: generator point');
    // Test 2: discriminant Δ part should be non-zero: 4a³ + 27b² != 0.
    // Guarantees curve is genus-1, smooth (non-singular).
    const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n), _4n);
    const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));
    if (Fp.is0(Fp.add(_4a3, _27b2)))
        throw new Error('bad curve params: a or b');
    /** Asserts coordinate is valid: 0 <= n < Fp.ORDER. */
    function acoord(title, n, banZero = false) {
        if (!Fp.isValid(n) || (banZero && Fp.is0(n)))
            throw new Error(`bad point coordinate ${title}`);
        return n;
    }
    function aprjpoint(other) {
        if (!(other instanceof Point))
            throw new Error('ProjectivePoint expected');
    }
    function splitEndoScalarN(k) {
        if (!endo || !endo.basises)
            throw new Error('no endo');
        return _splitEndoScalar(k, endo.basises, Fn.ORDER);
    }
    // Memoized toAffine / validity check. They are heavy. Points are immutable.
    // Converts Projective point to affine (x, y) coordinates.
    // Can accept precomputed Z^-1 - for example, from invertBatch.
    // (X, Y, Z) ∋ (x=X/Z, y=Y/Z)
    const toAffineMemo = memoized((p, iz) => {
        const { X, Y, Z } = p;
        // Fast-path for normalized points
        if (Fp.eql(Z, Fp.ONE))
            return { x: X, y: Y };
        const is0 = p.is0();
        // If invZ was 0, we return zero point. However we still want to execute
        // all operations, so we replace invZ with a random number, 1.
        if (iz == null)
            iz = is0 ? Fp.ONE : Fp.inv(Z);
        const x = Fp.mul(X, iz);
        const y = Fp.mul(Y, iz);
        const zz = Fp.mul(Z, iz);
        if (is0)
            return { x: Fp.ZERO, y: Fp.ZERO };
        if (!Fp.eql(zz, Fp.ONE))
            throw new Error('invZ was invalid');
        return { x, y };
    });
    // NOTE: on exception this will crash 'cached' and no value will be set.
    // Otherwise true will be return
    const assertValidMemo = memoized((p) => {
        if (p.is0()) {
            // (0, 1, 0) aka ZERO is invalid in most contexts.
            // In BLS, ZERO can be serialized, so we allow it.
            // (0, 0, 0) is invalid representation of ZERO.
            if (extraOpts.allowInfinityPoint && !Fp.is0(p.Y))
                return;
            throw new Error('bad point: ZERO');
        }
        // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`
        const { x, y } = p.toAffine();
        if (!Fp.isValid(x) || !Fp.isValid(y))
            throw new Error('bad point: x or y not field elements');
        if (!isValidXY(x, y))
            throw new Error('bad point: equation left != right');
        if (!p.isTorsionFree())
            throw new Error('bad point: not in prime-order subgroup');
        return true;
    });
    function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) {
        k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);
        k1p = negateCt(k1neg, k1p);
        k2p = negateCt(k2neg, k2p);
        return k1p.add(k2p);
    }
    /**
     * Projective Point works in 3d / projective (homogeneous) coordinates:(X, Y, Z) ∋ (x=X/Z, y=Y/Z).
     * Default Point works in 2d / affine coordinates: (x, y).
     * We're doing calculations in projective, because its operations don't require costly inversion.
     */
    class Point {
        /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
        constructor(X, Y, Z) {
            this.X = acoord('x', X);
            this.Y = acoord('y', Y, true);
            this.Z = acoord('z', Z);
            Object.freeze(this);
        }
        static CURVE() {
            return CURVE;
        }
        /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
        static fromAffine(p) {
            const { x, y } = p || {};
            if (!p || !Fp.isValid(x) || !Fp.isValid(y))
                throw new Error('invalid affine point');
            if (p instanceof Point)
                throw new Error('projective point not allowed');
            // (0, 0) would've produced (0, 0, 1) - instead, we need (0, 1, 0)
            if (Fp.is0(x) && Fp.is0(y))
                return Point.ZERO;
            return new Point(x, y, Fp.ONE);
        }
        static fromBytes(bytes) {
            const P = Point.fromAffine(decodePoint(abytes(bytes, undefined, 'point')));
            P.assertValidity();
            return P;
        }
        static fromHex(hex) {
            return Point.fromBytes(ensureBytes('pointHex', hex));
        }
        get x() {
            return this.toAffine().x;
        }
        get y() {
            return this.toAffine().y;
        }
        /**
         *
         * @param windowSize
         * @param isLazy true will defer table computation until the first multiplication
         * @returns
         */
        precompute(windowSize = 8, isLazy = true) {
            wnaf.createCache(this, windowSize);
            if (!isLazy)
                this.multiply(_3n); // random number
            return this;
        }
        // TODO: return `this`
        /** A point on curve is valid if it conforms to equation. */
        assertValidity() {
            assertValidMemo(this);
        }
        hasEvenY() {
            const { y } = this.toAffine();
            if (!Fp.isOdd)
                throw new Error("Field doesn't support isOdd");
            return !Fp.isOdd(y);
        }
        /** Compare one point to another. */
        equals(other) {
            aprjpoint(other);
            const { X: X1, Y: Y1, Z: Z1 } = this;
            const { X: X2, Y: Y2, Z: Z2 } = other;
            const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
            const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
            return U1 && U2;
        }
        /** Flips point to one corresponding to (x, -y) in Affine coordinates. */
        negate() {
            return new Point(this.X, Fp.neg(this.Y), this.Z);
        }
        // Renes-Costello-Batina exception-free doubling formula.
        // There is 30% faster Jacobian formula, but it is not complete.
        // https://eprint.iacr.org/2015/1060, algorithm 3
        // Cost: 8M + 3S + 3*a + 2*b3 + 15add.
        double() {
            const { a, b } = CURVE;
            const b3 = Fp.mul(b, _3n);
            const { X: X1, Y: Y1, Z: Z1 } = this;
            let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore
            let t0 = Fp.mul(X1, X1); // step 1
            let t1 = Fp.mul(Y1, Y1);
            let t2 = Fp.mul(Z1, Z1);
            let t3 = Fp.mul(X1, Y1);
            t3 = Fp.add(t3, t3); // step 5
            Z3 = Fp.mul(X1, Z1);
            Z3 = Fp.add(Z3, Z3);
            X3 = Fp.mul(a, Z3);
            Y3 = Fp.mul(b3, t2);
            Y3 = Fp.add(X3, Y3); // step 10
            X3 = Fp.sub(t1, Y3);
            Y3 = Fp.add(t1, Y3);
            Y3 = Fp.mul(X3, Y3);
            X3 = Fp.mul(t3, X3);
            Z3 = Fp.mul(b3, Z3); // step 15
            t2 = Fp.mul(a, t2);
            t3 = Fp.sub(t0, t2);
            t3 = Fp.mul(a, t3);
            t3 = Fp.add(t3, Z3);
            Z3 = Fp.add(t0, t0); // step 20
            t0 = Fp.add(Z3, t0);
            t0 = Fp.add(t0, t2);
            t0 = Fp.mul(t0, t3);
            Y3 = Fp.add(Y3, t0);
            t2 = Fp.mul(Y1, Z1); // step 25
            t2 = Fp.add(t2, t2);
            t0 = Fp.mul(t2, t3);
            X3 = Fp.sub(X3, t0);
            Z3 = Fp.mul(t2, t1);
            Z3 = Fp.add(Z3, Z3); // step 30
            Z3 = Fp.add(Z3, Z3);
            return new Point(X3, Y3, Z3);
        }
        // Renes-Costello-Batina exception-free addition formula.
        // There is 30% faster Jacobian formula, but it is not complete.
        // https://eprint.iacr.org/2015/1060, algorithm 1
        // Cost: 12M + 0S + 3*a + 3*b3 + 23add.
        add(other) {
            aprjpoint(other);
            const { X: X1, Y: Y1, Z: Z1 } = this;
            const { X: X2, Y: Y2, Z: Z2 } = other;
            let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore
            const a = CURVE.a;
            const b3 = Fp.mul(CURVE.b, _3n);
            let t0 = Fp.mul(X1, X2); // step 1
            let t1 = Fp.mul(Y1, Y2);
            let t2 = Fp.mul(Z1, Z2);
            let t3 = Fp.add(X1, Y1);
            let t4 = Fp.add(X2, Y2); // step 5
            t3 = Fp.mul(t3, t4);
            t4 = Fp.add(t0, t1);
            t3 = Fp.sub(t3, t4);
            t4 = Fp.add(X1, Z1);
            let t5 = Fp.add(X2, Z2); // step 10
            t4 = Fp.mul(t4, t5);
            t5 = Fp.add(t0, t2);
            t4 = Fp.sub(t4, t5);
            t5 = Fp.add(Y1, Z1);
            X3 = Fp.add(Y2, Z2); // step 15
            t5 = Fp.mul(t5, X3);
            X3 = Fp.add(t1, t2);
            t5 = Fp.sub(t5, X3);
            Z3 = Fp.mul(a, t4);
            X3 = Fp.mul(b3, t2); // step 20
            Z3 = Fp.add(X3, Z3);
            X3 = Fp.sub(t1, Z3);
            Z3 = Fp.add(t1, Z3);
            Y3 = Fp.mul(X3, Z3);
            t1 = Fp.add(t0, t0); // step 25
            t1 = Fp.add(t1, t0);
            t2 = Fp.mul(a, t2);
            t4 = Fp.mul(b3, t4);
            t1 = Fp.add(t1, t2);
            t2 = Fp.sub(t0, t2); // step 30
            t2 = Fp.mul(a, t2);
            t4 = Fp.add(t4, t2);
            t0 = Fp.mul(t1, t4);
            Y3 = Fp.add(Y3, t0);
            t0 = Fp.mul(t5, t4); // step 35
            X3 = Fp.mul(t3, X3);
            X3 = Fp.sub(X3, t0);
            t0 = Fp.mul(t3, t1);
            Z3 = Fp.mul(t5, Z3);
            Z3 = Fp.add(Z3, t0); // step 40
            return new Point(X3, Y3, Z3);
        }
        subtract(other) {
            return this.add(other.negate());
        }
        is0() {
            return this.equals(Point.ZERO);
        }
        /**
         * Constant time multiplication.
         * Uses wNAF method. Windowed method may be 10% faster,
         * but takes 2x longer to generate and consumes 2x memory.
         * Uses precomputes when available.
         * Uses endomorphism for Koblitz curves.
         * @param scalar by which the point would be multiplied
         * @returns New point
         */
        multiply(scalar) {
            const { endo } = extraOpts;
            if (!Fn.isValidNot0(scalar))
                throw new Error('invalid scalar: out of range'); // 0 is invalid
            let point, fake; // Fake point is used to const-time mult
            const mul = (n) => wnaf.cached(this, n, (p) => normalizeZ(Point, p));
            /** See docs for {@link EndomorphismOpts} */
            if (endo) {
                const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);
                const { p: k1p, f: k1f } = mul(k1);
                const { p: k2p, f: k2f } = mul(k2);
                fake = k1f.add(k2f);
                point = finishEndo(endo.beta, k1p, k2p, k1neg, k2neg);
            }
            else {
                const { p, f } = mul(scalar);
                point = p;
                fake = f;
            }
            // Normalize `z` for both points, but return only real one
            return normalizeZ(Point, [point, fake])[0];
        }
        /**
         * Non-constant-time multiplication. Uses double-and-add algorithm.
         * It's faster, but should only be used when you don't care about
         * an exposed secret key e.g. sig verification, which works over *public* keys.
         */
        multiplyUnsafe(sc) {
            const { endo } = extraOpts;
            const p = this;
            if (!Fn.isValid(sc))
                throw new Error('invalid scalar: out of range'); // 0 is valid
            if (sc === _0n || p.is0())
                return Point.ZERO;
            if (sc === _1n)
                return p; // fast-path
            if (wnaf.hasCache(this))
                return this.multiply(sc);
            if (endo) {
                const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);
                const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2); // 30% faster vs wnaf.unsafe
                return finishEndo(endo.beta, p1, p2, k1neg, k2neg);
            }
            else {
                return wnaf.unsafe(p, sc);
            }
        }
        multiplyAndAddUnsafe(Q, a, b) {
            const sum = this.multiplyUnsafe(a).add(Q.multiplyUnsafe(b));
            return sum.is0() ? undefined : sum;
        }
        /**
         * Converts Projective point to affine (x, y) coordinates.
         * @param invertedZ Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch
         */
        toAffine(invertedZ) {
            return toAffineMemo(this, invertedZ);
        }
        /**
         * Checks whether Point is free of torsion elements (is in prime subgroup).
         * Always torsion-free for cofactor=1 curves.
         */
        isTorsionFree() {
            const { isTorsionFree } = extraOpts;
            if (cofactor === _1n)
                return true;
            if (isTorsionFree)
                return isTorsionFree(Point, this);
            return wnaf.unsafe(this, CURVE_ORDER).is0();
        }
        clearCofactor() {
            const { clearCofactor } = extraOpts;
            if (cofactor === _1n)
                return this; // Fast-path
            if (clearCofactor)
                return clearCofactor(Point, this);
            return this.multiplyUnsafe(cofactor);
        }
        isSmallOrder() {
            // can we use this.clearCofactor()?
            return this.multiplyUnsafe(cofactor).is0();
        }
        toBytes(isCompressed = true) {
            abool(isCompressed, 'isCompressed');
            this.assertValidity();
            return encodePoint(Point, this, isCompressed);
        }
        toHex(isCompressed = true) {
            return bytesToHex(this.toBytes(isCompressed));
        }
        toString() {
            return `<Point ${this.is0() ? 'ZERO' : this.toHex()}>`;
        }
        // TODO: remove
        get px() {
            return this.X;
        }
        get py() {
            return this.X;
        }
        get pz() {
            return this.Z;
        }
        toRawBytes(isCompressed = true) {
            return this.toBytes(isCompressed);
        }
        _setWindowSize(windowSize) {
            this.precompute(windowSize);
        }
        static normalizeZ(points) {
            return normalizeZ(Point, points);
        }
        static msm(points, scalars) {
            return pippenger(Point, Fn, points, scalars);
        }
        static fromPrivateKey(privateKey) {
            return Point.BASE.multiply(_normFnElement(Fn, privateKey));
        }
    }
    // base / generator point
    Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
    // zero / infinity / identity point
    Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); // 0, 1, 0
    // math field
    Point.Fp = Fp;
    // scalar field
    Point.Fn = Fn;
    const bits = Fn.BITS;
    const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);
    Point.BASE.precompute(8); // Enable precomputes. Slows down first publicKey computation by 20ms.
    return Point;
}
// Points start with byte 0x02 when y is even; otherwise 0x03
function pprefix(hasEvenY) {
    return Uint8Array.of(hasEvenY ? 0x02 : 0x03);
}
/**
 * Implementation of the Shallue and van de Woestijne method for any weierstrass curve.
 * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular.
 * b = True and y = sqrt(u / v) if (u / v) is square in F, and
 * b = False and y = sqrt(Z * (u / v)) otherwise.
 * @param Fp
 * @param Z
 * @returns
 */
export function SWUFpSqrtRatio(Fp, Z) {
    // Generic implementation
    const q = Fp.ORDER;
    let l = _0n;
    for (let o = q - _1n; o % _2n === _0n; o /= _2n)
        l += _1n;
    const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1.
    // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<.
    // 2n ** c1 == 2n << (c1-1)
    const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n);
    const _2n_pow_c1 = _2n_pow_c1_1 * _2n;
    const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1)  # Integer arithmetic
    const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2            # Integer arithmetic
    const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1                # Integer arithmetic
    const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1)                  # Integer arithmetic
    const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2
    const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2)
    let sqrtRatio = (u, v) => {
        let tv1 = c6; // 1. tv1 = c6
        let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4
        let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2
        tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v
        let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3
        tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3
        tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2
        tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v
        tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u
        let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2
        tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5
        let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1
        tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7
        tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1
        tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR)
        tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR)
        // 17. for i in (c1, c1 - 1, ..., 2):
        for (let i = c1; i > _1n; i--) {
            let tv5 = i - _2n; // 18.    tv5 = i - 2
            tv5 = _2n << (tv5 - _1n); // 19.    tv5 = 2^tv5
            let tvv5 = Fp.pow(tv4, tv5); // 20.    tv5 = tv4^tv5
            const e1 = Fp.eql(tvv5, Fp.ONE); // 21.    e1 = tv5 == 1
            tv2 = Fp.mul(tv3, tv1); // 22.    tv2 = tv3 * tv1
            tv1 = Fp.mul(tv1, tv1); // 23.    tv1 = tv1 * tv1
            tvv5 = Fp.mul(tv4, tv1); // 24.    tv5 = tv4 * tv1
            tv3 = Fp.cmov(tv2, tv3, e1); // 25.    tv3 = CMOV(tv2, tv3, e1)
            tv4 = Fp.cmov(tvv5, tv4, e1); // 26.    tv4 = CMOV(tv5, tv4, e1)
        }
        return { isValid: isQR, value: tv3 };
    };
    if (Fp.ORDER % _4n === _3n) {
        // sqrt_ratio_3mod4(u, v)
        const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4     # Integer arithmetic
        const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z)
        sqrtRatio = (u, v) => {
            let tv1 = Fp.sqr(v); // 1. tv1 = v^2
            const tv2 = Fp.mul(u, v); // 2. tv2 = u * v
            tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2
            let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1
            y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2
            const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2
            const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v
            const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u
            let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR)
            return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2
        };
    }
    // No curves uses that
    // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8
    return sqrtRatio;
}
/**
 * Simplified Shallue-van de Woestijne-Ulas Method
 * https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2
 */
export function mapToCurveSimpleSWU(Fp, opts) {
    validateField(Fp);
    const { A, B, Z } = opts;
    if (!Fp.isValid(A) || !Fp.isValid(B) || !Fp.isValid(Z))
        throw new Error('mapToCurveSimpleSWU: invalid opts');
    const sqrtRatio = SWUFpSqrtRatio(Fp, Z);
    if (!Fp.isOdd)
        throw new Error('Field does not have .isOdd()');
    // Input: u, an element of F.
    // Output: (x, y), a point on E.
    return (u) => {
        // prettier-ignore
        let tv1, tv2, tv3, tv4, tv5, tv6, x, y;
        tv1 = Fp.sqr(u); // 1.  tv1 = u^2
        tv1 = Fp.mul(tv1, Z); // 2.  tv1 = Z * tv1
        tv2 = Fp.sqr(tv1); // 3.  tv2 = tv1^2
        tv2 = Fp.add(tv2, tv1); // 4.  tv2 = tv2 + tv1
        tv3 = Fp.add(tv2, Fp.ONE); // 5.  tv3 = tv2 + 1
        tv3 = Fp.mul(tv3, B); // 6.  tv3 = B * tv3
        tv4 = Fp.cmov(Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7.  tv4 = CMOV(Z, -tv2, tv2 != 0)
        tv4 = Fp.mul(tv4, A); // 8.  tv4 = A * tv4
        tv2 = Fp.sqr(tv3); // 9.  tv2 = tv3^2
        tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2
        tv5 = Fp.mul(tv6, A); // 11. tv5 = A * tv6
        tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5
        tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3
        tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4
        tv5 = Fp.mul(tv6, B); // 15. tv5 = B * tv6
        tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5
        x = Fp.mul(tv1, tv3); // 17.   x = tv1 * tv3
        const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6)
        y = Fp.mul(tv1, u); // 19.   y = tv1 * u  -> Z * u^3 * y1
        y = Fp.mul(y, value); // 20.   y = y * y1
        x = Fp.cmov(x, tv3, isValid); // 21.   x = CMOV(x, tv3, is_gx1_square)
        y = Fp.cmov(y, value, isValid); // 22.   y = CMOV(y, y1, is_gx1_square)
        const e1 = Fp.isOdd(u) === Fp.isOdd(y); // 23.  e1 = sgn0(u) == sgn0(y)
        y = Fp.cmov(Fp.neg(y), y, e1); // 24.   y = CMOV(-y, y, e1)
        const tv4_inv = FpInvertBatch(Fp, [tv4], true)[0];
        x = Fp.mul(x, tv4_inv); // 25.   x = x / tv4
        return { x, y };
    };
}
function getWLengths(Fp, Fn) {
    return {
        secretKey: Fn.BYTES,
        publicKey: 1 + Fp.BYTES,
        publicKeyUncompressed: 1 + 2 * Fp.BYTES,
        publicKeyHasPrefix: true,
        signature: 2 * Fn.BYTES,
    };
}
/**
 * Sometimes users only need getPublicKey, getSharedSecret, and secret key handling.
 * This helper ensures no signature functionality is present. Less code, smaller bundle size.
 */
export function ecdh(Point, ecdhOpts = {}) {
    const { Fn } = Point;
    const randomBytes_ = ecdhOpts.randomBytes || randomBytesWeb;
    const lengths = Object.assign(getWLengths(Point.Fp, Fn), { seed: getMinHashLength(Fn.ORDER) });
    function isValidSecretKey(secretKey) {
        try {
            return !!_normFnElement(Fn, secretKey);
        }
        catch (error) {
            return false;
        }
    }
    function isValidPublicKey(publicKey, isCompressed) {
        const { publicKey: comp, publicKeyUncompressed } = lengths;
        try {
            const l = publicKey.length;
            if (isCompressed === true && l !== comp)
                return false;
            if (isCompressed === false && l !== publicKeyUncompressed)
                return false;
            return !!Point.fromBytes(publicKey);
        }
        catch (error) {
            return false;
        }
    }
    /**
     * Produces cryptographically secure secret key from random of size
     * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.
     */
    function randomSecretKey(seed = randomBytes_(lengths.seed)) {
        return mapHashToField(abytes(seed, lengths.seed, 'seed'), Fn.ORDER);
    }
    /**
     * Computes public key for a secret key. Checks for validity of the secret key.
     * @param isCompressed whether to return compact (default), or full key
     * @returns Public key, full when isCompressed=false; short when isCompressed=true
     */
    function getPublicKey(secretKey, isCompressed = true) {
        return Point.BASE.multiply(_normFnElement(Fn, secretKey)).toBytes(isCompressed);
    }
    function keygen(seed) {
        const secretKey = randomSecretKey(seed);
        return { secretKey, publicKey: getPublicKey(secretKey) };
    }
    /**
     * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.
     */
    function isProbPub(item) {
        if (typeof item === 'bigint')
            return false;
        if (item instanceof Point)
            return true;
        const { secretKey, publicKey, publicKeyUncompressed } = lengths;
        if (Fn.allowedLengths || secretKey === publicKey)
            return undefined;
        const l = ensureBytes('key', item).length;
        return l === publicKey || l === publicKeyUncompressed;
    }
    /**
     * ECDH (Elliptic Curve Diffie Hellman).
     * Computes shared public key from secret key A and public key B.
     * Checks: 1) secret key validity 2) shared key is on-curve.
     * Does NOT hash the result.
     * @param isCompressed whether to return compact (default), or full key
     * @returns shared public key
     */
    function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {
        if (isProbPub(secretKeyA) === true)
            throw new Error('first arg must be private key');
        if (isProbPub(publicKeyB) === false)
            throw new Error('second arg must be public key');
        const s = _normFnElement(Fn, secretKeyA);
        const b = Point.fromHex(publicKeyB); // checks for being on-curve
        return b.multiply(s).toBytes(isCompressed);
    }
    const utils = {
        isValidSecretKey,
        isValidPublicKey,
        randomSecretKey,
        // TODO: remove
        isValidPrivateKey: isValidSecretKey,
        randomPrivateKey: randomSecretKey,
        normPrivateKeyToScalar: (key) => _normFnElement(Fn, key),
        precompute(windowSize = 8, point = Point.BASE) {
            return point.precompute(windowSize, false);
        },
    };
    return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point, utils, lengths });
}
/**
 * Creates ECDSA signing interface for given elliptic curve `Point` and `hash` function.
 * We need `hash` for 2 features:
 * 1. Message prehash-ing. NOT used if `sign` / `verify` are called with `prehash: false`
 * 2. k generation in `sign`, using HMAC-drbg(hash)
 *
 * ECDSAOpts are only rarely needed.
 *
 * @example
 * ```js
 * const p256_Point = weierstrass(...);
 * const p256_sha256 = ecdsa(p256_Point, sha256);
 * const p256_sha224 = ecdsa(p256_Point, sha224);
 * const p256_sha224_r = ecdsa(p256_Point, sha224, { randomBytes: (length) => { ... } });
 * ```
 */
export function ecdsa(Point, hash, ecdsaOpts = {}) {
    ahash(hash);
    _validateObject(ecdsaOpts, {}, {
        hmac: 'function',
        lowS: 'boolean',
        randomBytes: 'function',
        bits2int: 'function',
        bits2int_modN: 'function',
    });
    const randomBytes = ecdsaOpts.randomBytes || randomBytesWeb;
    const hmac = ecdsaOpts.hmac ||
        ((key, ...msgs) => nobleHmac(hash, key, concatBytes(...msgs)));
    const { Fp, Fn } = Point;
    const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;
    const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);
    const defaultSigOpts = {
        prehash: false,
        lowS: typeof ecdsaOpts.lowS === 'boolean' ? ecdsaOpts.lowS : false,
        format: undefined, //'compact' as ECDSASigFormat,
        extraEntropy: false,
    };
    const defaultSigOpts_format = 'compact';
    function isBiggerThanHalfOrder(number) {
        const HALF = CURVE_ORDER >> _1n;
        return number > HALF;
    }
    function validateRS(title, num) {
        if (!Fn.isValidNot0(num))
            throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);
        return num;
    }
    function validateSigLength(bytes, format) {
        validateSigFormat(format);
        const size = lengths.signature;
        const sizer = format === 'compact' ? size : format === 'recovered' ? size + 1 : undefined;
        return abytes(bytes, sizer, `${format} signature`);
    }
    /**
     * ECDSA signature with its (r, s) properties. Supports compact, recovered & DER representations.
     */
    class Signature {
        constructor(r, s, recovery) {
            this.r = validateRS('r', r); // r in [1..N-1];
            this.s = validateRS('s', s); // s in [1..N-1];
            if (recovery != null)
                this.recovery = recovery;
            Object.freeze(this);
        }
        static fromBytes(bytes, format = defaultSigOpts_format) {
            validateSigLength(bytes, format);
            let recid;
            if (format === 'der') {
                const { r, s } = DER.toSig(abytes(bytes));
                return new Signature(r, s);
            }
            if (format === 'recovered') {
                recid = bytes[0];
                format = 'compact';
                bytes = bytes.subarray(1);
            }
            const L = Fn.BYTES;
            const r = bytes.subarray(0, L);
            const s = bytes.subarray(L, L * 2);
            return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);
        }
        static fromHex(hex, format) {
            return this.fromBytes(hexToBytes(hex), format);
        }
        addRecoveryBit(recovery) {
            return new Signature(this.r, this.s, recovery);
        }
        recoverPublicKey(messageHash) {
            const FIELD_ORDER = Fp.ORDER;
            const { r, s, recovery: rec } = this;
            if (rec == null || ![0, 1, 2, 3].includes(rec))
                throw new Error('recovery id invalid');
            // ECDSA recovery is hard for cofactor > 1 curves.
            // In sign, `r = q.x mod n`, and here we recover q.x from r.
            // While recovering q.x >= n, we need to add r+n for cofactor=1 curves.
            // However, for cofactor>1, r+n may not get q.x:
            // r+n*i would need to be done instead where i is unknown.
            // To easily get i, we either need to:
            // a. increase amount of valid recid values (4, 5...); OR
            // b. prohibit non-prime-order signatures (recid > 1).
            const hasCofactor = CURVE_ORDER * _2n < FIELD_ORDER;
            if (hasCofactor && rec > 1)
                throw new Error('recovery id is ambiguous for h>1 curve');
            const radj = rec === 2 || rec === 3 ? r + CURVE_ORDER : r;
            if (!Fp.isValid(radj))
                throw new Error('recovery id 2 or 3 invalid');
            const x = Fp.toBytes(radj);
            const R = Point.fromBytes(concatBytes(pprefix((rec & 1) === 0), x));
            const ir = Fn.inv(radj); // r^-1
            const h = bits2int_modN(ensureBytes('msgHash', messageHash)); // Truncate hash
            const u1 = Fn.create(-h * ir); // -hr^-1
            const u2 = Fn.create(s * ir); // sr^-1
            // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1). unsafe is fine: there is no private data.
            const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));
            if (Q.is0())
                throw new Error('point at infinify');
            Q.assertValidity();
            return Q;
        }
        // Signatures should be low-s, to prevent malleability.
        hasHighS() {
            return isBiggerThanHalfOrder(this.s);
        }
        toBytes(format = defaultSigOpts_format) {
            validateSigFormat(format);
            if (format === 'der')
                return hexToBytes(DER.hexFromSig(this));
            const r = Fn.toBytes(this.r);
            const s = Fn.toBytes(this.s);
            if (format === 'recovered') {
                if (this.recovery == null)
                    throw new Error('recovery bit must be present');
                return concatBytes(Uint8Array.of(this.recovery), r, s);
            }
            return concatBytes(r, s);
        }
        toHex(format) {
            return bytesToHex(this.toBytes(format));
        }
        // TODO: remove
        assertValidity() { }
        static fromCompact(hex) {
            return Signature.fromBytes(ensureBytes('sig', hex), 'compact');
        }
        static fromDER(hex) {
            return Signature.fromBytes(ensureBytes('sig', hex), 'der');
        }
        normalizeS() {
            return this.hasHighS() ? new Signature(this.r, Fn.neg(this.s), this.recovery) : this;
        }
        toDERRawBytes() {
            return this.toBytes('der');
        }
        toDERHex() {
            return bytesToHex(this.toBytes('der'));
        }
        toCompactRawBytes() {
            return this.toBytes('compact');
        }
        toCompactHex() {
            return bytesToHex(this.toBytes('compact'));
        }
    }
    // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.
    // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.
    // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.
    // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors
    const bits2int = ecdsaOpts.bits2int ||
        function bits2int_def(bytes) {
            // Our custom check "just in case", for protection against DoS
            if (bytes.length > 8192)
                throw new Error('input is too large');
            // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)
            // for some cases, since bytes.length * 8 is not actual bitLength.
            const num = bytesToNumberBE(bytes); // check for == u8 done here
            const delta = bytes.length * 8 - fnBits; // truncate to nBitLength leftmost bits
            return delta > 0 ? num >> BigInt(delta) : num;
        };
    const bits2int_modN = ecdsaOpts.bits2int_modN ||
        function bits2int_modN_def(bytes) {
            return Fn.create(bits2int(bytes)); // can't use bytesToNumberBE here
        };
    // Pads output with zero as per spec
    const ORDER_MASK = bitMask(fnBits);
    /** Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. */
    function int2octets(num) {
        // IMPORTANT: the check ensures working for case `Fn.BYTES != Fn.BITS * 8`
        aInRange('num < 2^' + fnBits, num, _0n, ORDER_MASK);
        return Fn.toBytes(num);
    }
    function validateMsgAndHash(message, prehash) {
        abytes(message, undefined, 'message');
        return prehash ? abytes(hash(message), undefined, 'prehashed message') : message;
    }
    /**
     * Steps A, D of RFC6979 3.2.
     * Creates RFC6979 seed; converts msg/privKey to numbers.
     * Used only in sign, not in verify.
     *
     * Warning: we cannot assume here that message has same amount of bytes as curve order,
     * this will be invalid at least for P521. Also it can be bigger for P224 + SHA256.
     */
    function prepSig(message, privateKey, opts) {
        if (['recovered', 'canonical'].some((k) => k in opts))
            throw new Error('sign() legacy options not supported');
        const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);
        message = validateMsgAndHash(message, prehash); // RFC6979 3.2 A: h1 = H(m)
        // We can't later call bits2octets, since nested bits2int is broken for curves
        // with fnBits % 8 !== 0. Because of that, we unwrap it here as int2octets call.
        // const bits2octets = (bits) => int2octets(bits2int_modN(bits))
        const h1int = bits2int_modN(message);
        const d = _normFnElement(Fn, privateKey); // validate secret key, convert to bigint
        const seedArgs = [int2octets(d), int2octets(h1int)];
        // extraEntropy. RFC6979 3.6: additional k' (optional).
        if (extraEntropy != null && extraEntropy !== false) {
            // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')
            // gen random bytes OR pass as-is
            const e = extraEntropy === true ? randomBytes(lengths.secretKey) : extraEntropy;
            seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes
        }
        const seed = concatBytes(...seedArgs); // Step D of RFC6979 3.2
        const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash!
        // Converts signature params into point w r/s, checks result for validity.
        // To transform k => Signature:
        // q = k⋅G
        // r = q.x mod n
        // s = k^-1(m + rd) mod n
        // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to
        // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:
        // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT
        function k2sig(kBytes) {
            // RFC 6979 Section 3.2, step 3: k = bits2int(T)
            // Important: all mod() calls here must be done over N
            const k = bits2int(kBytes); // mod n, not mod p
            if (!Fn.isValidNot0(k))
                return; // Valid scalars (including k) must be in 1..N-1
            const ik = Fn.inv(k); // k^-1 mod n
            const q = Point.BASE.multiply(k).toAffine(); // q = k⋅G
            const r = Fn.create(q.x); // r = q.x mod n
            if (r === _0n)
                return;
            const s = Fn.create(ik * Fn.create(m + r * d)); // Not using blinding here, see comment above
            if (s === _0n)
                return;
            let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n)
            let normS = s;
            if (lowS && isBiggerThanHalfOrder(s)) {
                normS = Fn.neg(s); // if lowS was passed, ensure s is always
                recovery ^= 1; // // in the bottom half of N
            }
            return new Signature(r, normS, recovery); // use normS, not s
        }
        return { seed, k2sig };
    }
    /**
     * Signs message hash with a secret key.
     *
     * ```
     * sign(m, d) where
     *   k = rfc6979_hmac_drbg(m, d)
     *   (x, y) = G × k
     *   r = x mod n
     *   s = (m + dr) / k mod n
     * ```
     */
    function sign(message, secretKey, opts = {}) {
        message = ensureBytes('message', message);
        const { seed, k2sig } = prepSig(message, secretKey, opts); // Steps A, D of RFC6979 3.2.
        const drbg = createHmacDrbg(hash.outputLen, Fn.BYTES, hmac);
        const sig = drbg(seed, k2sig); // Steps B, C, D, E, F, G
        return sig;
    }
    function tryParsingSig(sg) {
        // Try to deduce format
        let sig = undefined;
        const isHex = typeof sg === 'string' || isBytes(sg);
        const isObj = !isHex &&
            sg !== null &&
            typeof sg === 'object' &&
            typeof sg.r === 'bigint' &&
            typeof sg.s === 'bigint';
        if (!isHex && !isObj)
            throw new Error('invalid signature, expected Uint8Array, hex string or Signature instance');
        if (isObj) {
            sig = new Signature(sg.r, sg.s);
        }
        else if (isHex) {
            try {
                sig = Signature.fromBytes(ensureBytes('sig', sg), 'der');
            }
            catch (derError) {
                if (!(derError instanceof DER.Err))
                    throw derError;
            }
            if (!sig) {
                try {
                    sig = Signature.fromBytes(ensureBytes('sig', sg), 'compact');
                }
                catch (error) {
                    return false;
                }
            }
        }
        if (!sig)
            return false;
        return sig;
    }
    /**
     * Verifies a signature against message and public key.
     * Rejects lowS signatures by default: see {@link ECDSAVerifyOpts}.
     * Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:
     *
     * ```
     * verify(r, s, h, P) where
     *   u1 = hs^-1 mod n
     *   u2 = rs^-1 mod n
     *   R = u1⋅G + u2⋅P
     *   mod(R.x, n) == r
     * ```
     */
    function verify(signature, message, publicKey, opts = {}) {
        const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);
        publicKey = ensureBytes('publicKey', publicKey);
        message = validateMsgAndHash(ensureBytes('message', message), prehash);
        if ('strict' in opts)
            throw new Error('options.strict was renamed to lowS');
        const sig = format === undefined
            ? tryParsingSig(signature)
            : Signature.fromBytes(ensureBytes('sig', signature), format);
        if (sig === false)
            return false;
        try {
            const P = Point.fromBytes(publicKey);
            if (lowS && sig.hasHighS())
                return false;
            const { r, s } = sig;
            const h = bits2int_modN(message); // mod n, not mod p
            const is = Fn.inv(s); // s^-1 mod n
            const u1 = Fn.create(h * is); // u1 = hs^-1 mod n
            const u2 = Fn.create(r * is); // u2 = rs^-1 mod n
            const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2)); // u1⋅G + u2⋅P
            if (R.is0())
                return false;
            const v = Fn.create(R.x); // v = r.x mod n
            return v === r;
        }
        catch (e) {
            return false;
        }
    }
    function recoverPublicKey(signature, message, opts = {}) {
        const { prehash } = validateSigOpts(opts, defaultSigOpts);
        message = validateMsgAndHash(message, prehash);
        return Signature.fromBytes(signature, 'recovered').recoverPublicKey(message).toBytes();
    }
    return Object.freeze({
        keygen,
        getPublicKey,
        getSharedSecret,
        utils,
        lengths,
        Point,
        sign,
        verify,
        recoverPublicKey,
        Signature,
        hash,
    });
}
/** @deprecated use `weierstrass` in newer releases */
export function weierstrassPoints(c) {
    const { CURVE, curveOpts } = _weierstrass_legacy_opts_to_new(c);
    const Point = weierstrassN(CURVE, curveOpts);
    return _weierstrass_new_output_to_legacy(c, Point);
}
function _weierstrass_legacy_opts_to_new(c) {
    const CURVE = {
        a: c.a,
        b: c.b,
        p: c.Fp.ORDER,
        n: c.n,
        h: c.h,
        Gx: c.Gx,
        Gy: c.Gy,
    };
    const Fp = c.Fp;
    let allowedLengths = c.allowedPrivateKeyLengths
        ? Array.from(new Set(c.allowedPrivateKeyLengths.map((l) => Math.ceil(l / 2))))
        : undefined;
    const Fn = Field(CURVE.n, {
        BITS: c.nBitLength,
        allowedLengths: allowedLengths,
        modFromBytes: c.wrapPrivateKey,
    });
    const curveOpts = {
        Fp,
        Fn,
        allowInfinityPoint: c.allowInfinityPoint,
        endo: c.endo,
        isTorsionFree: c.isTorsionFree,
        clearCofactor: c.clearCofactor,
        fromBytes: c.fromBytes,
        toBytes: c.toBytes,
    };
    return { CURVE, curveOpts };
}
function _ecdsa_legacy_opts_to_new(c) {
    const { CURVE, curveOpts } = _weierstrass_legacy_opts_to_new(c);
    const ecdsaOpts = {
        hmac: c.hmac,
        randomBytes: c.randomBytes,
        lowS: c.lowS,
        bits2int: c.bits2int,
        bits2int_modN: c.bits2int_modN,
    };
    return { CURVE, curveOpts, hash: c.hash, ecdsaOpts };
}
export function _legacyHelperEquat(Fp, a, b) {
    /**
     * y² = x³ + ax + b: Short weierstrass curve formula. Takes x, returns y².
     * @returns y²
     */
    function weierstrassEquation(x) {
        const x2 = Fp.sqr(x); // x * x
        const x3 = Fp.mul(x2, x); // x² * x
        return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x³ + a * x + b
    }
    return weierstrassEquation;
}
function _weierstrass_new_output_to_legacy(c, Point) {
    const { Fp, Fn } = Point;
    function isWithinCurveOrder(num) {
        return inRange(num, _1n, Fn.ORDER);
    }
    const weierstrassEquation = _legacyHelperEquat(Fp, c.a, c.b);
    return Object.assign({}, {
        CURVE: c,
        Point: Point,
        ProjectivePoint: Point,
        normPrivateKeyToScalar: (key) => _normFnElement(Fn, key),
        weierstrassEquation,
        isWithinCurveOrder,
    });
}
function _ecdsa_new_output_to_legacy(c, _ecdsa) {
    const Point = _ecdsa.Point;
    return Object.assign({}, _ecdsa, {
        ProjectivePoint: Point,
        CURVE: Object.assign({}, c, nLength(Point.Fn.ORDER, Point.Fn.BITS)),
    });
}
// _ecdsa_legacy
export function weierstrass(c) {
    const { CURVE, curveOpts, hash, ecdsaOpts } = _ecdsa_legacy_opts_to_new(c);
    const Point = weierstrassN(CURVE, curveOpts);
    const signs = ecdsa(Point, hash, ecdsaOpts);
    return _ecdsa_new_output_to_legacy(c, signs);
}
//# sourceMappingURL=weierstrass.js.map{
  "type": "module",
  "sideEffects": false
}
/**
 * SECG secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).
 *
 * Belongs to Koblitz curves: it has efficiently-computable GLV endomorphism ψ,
 * check out {@link EndomorphismOpts}. Seems to be rigid (not backdoored).
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { sha256 } from '@noble/hashes/sha2.js';
import { randomBytes } from '@noble/hashes/utils.js';
import { createCurve } from "./_shortw_utils.js";
import { createHasher, isogenyMap, } from "./abstract/hash-to-curve.js";
import { Field, mapHashToField, mod, pow2 } from "./abstract/modular.js";
import { _normFnElement, mapToCurveSimpleSWU, } from "./abstract/weierstrass.js";
import { bytesToNumberBE, concatBytes, ensureBytes, inRange, numberToBytesBE, utf8ToBytes, } from "./utils.js";
// Seems like generator was produced from some seed:
// `Point.BASE.multiply(Point.Fn.inv(2n, N)).toAffine().x`
// // gives short x 0x3b78ce563f89a0ed9414f5aa28ad0d96d6795f9c63n
const secp256k1_CURVE = {
    p: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'),
    n: BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'),
    h: BigInt(1),
    a: BigInt(0),
    b: BigInt(7),
    Gx: BigInt('0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'),
    Gy: BigInt('0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8'),
};
const secp256k1_ENDO = {
    beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),
    basises: [
        [BigInt('0x3086d221a7d46bcde86c90e49284eb15'), -BigInt('0xe4437ed6010e88286f547fa90abfe4c3')],
        [BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'), BigInt('0x3086d221a7d46bcde86c90e49284eb15')],
    ],
};
const _0n = /* @__PURE__ */ BigInt(0);
const _1n = /* @__PURE__ */ BigInt(1);
const _2n = /* @__PURE__ */ BigInt(2);
/**
 * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.
 * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]
 */
function sqrtMod(y) {
    const P = secp256k1_CURVE.p;
    // prettier-ignore
    const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
    // prettier-ignore
    const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
    const b2 = (y * y * y) % P; // x^3, 11
    const b3 = (b2 * b2 * y) % P; // x^7
    const b6 = (pow2(b3, _3n, P) * b3) % P;
    const b9 = (pow2(b6, _3n, P) * b3) % P;
    const b11 = (pow2(b9, _2n, P) * b2) % P;
    const b22 = (pow2(b11, _11n, P) * b11) % P;
    const b44 = (pow2(b22, _22n, P) * b22) % P;
    const b88 = (pow2(b44, _44n, P) * b44) % P;
    const b176 = (pow2(b88, _88n, P) * b88) % P;
    const b220 = (pow2(b176, _44n, P) * b44) % P;
    const b223 = (pow2(b220, _3n, P) * b3) % P;
    const t1 = (pow2(b223, _23n, P) * b22) % P;
    const t2 = (pow2(t1, _6n, P) * b2) % P;
    const root = pow2(t2, _2n, P);
    if (!Fpk1.eql(Fpk1.sqr(root), y))
        throw new Error('Cannot find square root');
    return root;
}
const Fpk1 = Field(secp256k1_CURVE.p, { sqrt: sqrtMod });
/**
 * secp256k1 curve, ECDSA and ECDH methods.
 *
 * Field: `2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n`
 *
 * @example
 * ```js
 * import { secp256k1 } from '@noble/curves/secp256k1';
 * const { secretKey, publicKey } = secp256k1.keygen();
 * const msg = new TextEncoder().encode('hello');
 * const sig = secp256k1.sign(msg, secretKey);
 * const isValid = secp256k1.verify(sig, msg, publicKey) === true;
 * ```
 */
export const secp256k1 = createCurve({ ...secp256k1_CURVE, Fp: Fpk1, lowS: true, endo: secp256k1_ENDO }, sha256);
// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.
// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki
/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */
const TAGGED_HASH_PREFIXES = {};
function taggedHash(tag, ...messages) {
    let tagP = TAGGED_HASH_PREFIXES[tag];
    if (tagP === undefined) {
        const tagH = sha256(utf8ToBytes(tag));
        tagP = concatBytes(tagH, tagH);
        TAGGED_HASH_PREFIXES[tag] = tagP;
    }
    return sha256(concatBytes(tagP, ...messages));
}
// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03
const pointToBytes = (point) => point.toBytes(true).slice(1);
const Pointk1 = /* @__PURE__ */ (() => secp256k1.Point)();
const hasEven = (y) => y % _2n === _0n;
// Calculate point, scalar and bytes
function schnorrGetExtPubKey(priv) {
    const { Fn, BASE } = Pointk1;
    const d_ = _normFnElement(Fn, priv);
    const p = BASE.multiply(d_); // P = d'⋅G; 0 < d' < n check is done inside
    const scalar = hasEven(p.y) ? d_ : Fn.neg(d_);
    return { scalar, bytes: pointToBytes(p) };
}
/**
 * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.
 * @returns valid point checked for being on-curve
 */
function lift_x(x) {
    const Fp = Fpk1;
    if (!Fp.isValidNot0(x))
        throw new Error('invalid x: Fail if x ≥ p');
    const xx = Fp.create(x * x);
    const c = Fp.create(xx * x + BigInt(7)); // Let c = x³ + 7 mod p.
    let y = Fp.sqrt(c); // Let y = c^(p+1)/4 mod p. Same as sqrt().
    // Return the unique point P such that x(P) = x and
    // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.
    if (!hasEven(y))
        y = Fp.neg(y);
    const p = Pointk1.fromAffine({ x, y });
    p.assertValidity();
    return p;
}
const num = bytesToNumberBE;
/**
 * Create tagged hash, convert it to bigint, reduce modulo-n.
 */
function challenge(...args) {
    return Pointk1.Fn.create(num(taggedHash('BIP0340/challenge', ...args)));
}
/**
 * Schnorr public key is just `x` coordinate of Point as per BIP340.
 */
function schnorrGetPublicKey(secretKey) {
    return schnorrGetExtPubKey(secretKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G)
}
/**
 * Creates Schnorr signature as per BIP340. Verifies itself before returning anything.
 * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous.
 */
function schnorrSign(message, secretKey, auxRand = randomBytes(32)) {
    const { Fn } = Pointk1;
    const m = ensureBytes('message', message);
    const { bytes: px, scalar: d } = schnorrGetExtPubKey(secretKey); // checks for isWithinCurveOrder
    const a = ensureBytes('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array
    const t = Fn.toBytes(d ^ num(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a)
    const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m)
    // Let k' = int(rand) mod n. Fail if k' = 0. Let R = k'⋅G
    const { bytes: rx, scalar: k } = schnorrGetExtPubKey(rand);
    const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.
    const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n).
    sig.set(rx, 0);
    sig.set(Fn.toBytes(Fn.create(k + e * d)), 32);
    // If Verify(bytes(P), m, sig) (see below) returns failure, abort
    if (!schnorrVerify(sig, m, px))
        throw new Error('sign: Invalid signature produced');
    return sig;
}
/**
 * Verifies Schnorr signature.
 * Will swallow errors & return false except for initial type validation of arguments.
 */
function schnorrVerify(signature, message, publicKey) {
    const { Fn, BASE } = Pointk1;
    const sig = ensureBytes('signature', signature, 64);
    const m = ensureBytes('message', message);
    const pub = ensureBytes('publicKey', publicKey, 32);
    try {
        const P = lift_x(num(pub)); // P = lift_x(int(pk)); fail if that fails
        const r = num(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r ≥ p.
        if (!inRange(r, _1n, secp256k1_CURVE.p))
            return false;
        const s = num(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n.
        if (!inRange(s, _1n, secp256k1_CURVE.n))
            return false;
        // int(challenge(bytes(r)||bytes(P)||m))%n
        const e = challenge(Fn.toBytes(r), pointToBytes(P), m);
        // R = s⋅G - e⋅P, where -eP == (n-e)P
        const R = BASE.multiplyUnsafe(s).add(P.multiplyUnsafe(Fn.neg(e)));
        const { x, y } = R.toAffine();
        // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r.
        if (R.is0() || !hasEven(y) || x !== r)
            return false;
        return true;
    }
    catch (error) {
        return false;
    }
}
/**
 * Schnorr signatures over secp256k1.
 * https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki
 * @example
 * ```js
 * import { schnorr } from '@noble/curves/secp256k1';
 * const { secretKey, publicKey } = schnorr.keygen();
 * // const publicKey = schnorr.getPublicKey(secretKey);
 * const msg = new TextEncoder().encode('hello');
 * const sig = schnorr.sign(msg, secretKey);
 * const isValid = schnorr.verify(sig, msg, publicKey);
 * ```
 */
export const schnorr = /* @__PURE__ */ (() => {
    const size = 32;
    const seedLength = 48;
    const randomSecretKey = (seed = randomBytes(seedLength)) => {
        return mapHashToField(seed, secp256k1_CURVE.n);
    };
    // TODO: remove
    secp256k1.utils.randomSecretKey;
    function keygen(seed) {
        const secretKey = randomSecretKey(seed);
        return { secretKey, publicKey: schnorrGetPublicKey(secretKey) };
    }
    return {
        keygen,
        getPublicKey: schnorrGetPublicKey,
        sign: schnorrSign,
        verify: schnorrVerify,
        Point: Pointk1,
        utils: {
            randomSecretKey: randomSecretKey,
            randomPrivateKey: randomSecretKey,
            taggedHash,
            // TODO: remove
            lift_x,
            pointToBytes,
            numberToBytesBE,
            bytesToNumberBE,
            mod,
        },
        lengths: {
            secretKey: size,
            publicKey: size,
            publicKeyHasPrefix: false,
            signature: size * 2,
            seed: seedLength,
        },
    };
})();
const isoMap = /* @__PURE__ */ (() => isogenyMap(Fpk1, [
    // xNum
    [
        '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7',
        '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581',
        '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262',
        '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c',
    ],
    // xDen
    [
        '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b',
        '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14',
        '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1
    ],
    // yNum
    [
        '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c',
        '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3',
        '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931',
        '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84',
    ],
    // yDen
    [
        '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b',
        '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573',
        '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f',
        '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1
    ],
].map((i) => i.map((j) => BigInt(j)))))();
const mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fpk1, {
    A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),
    B: BigInt('1771'),
    Z: Fpk1.create(BigInt('-11')),
}))();
/** Hashing / encoding to secp256k1 points / field. RFC 9380 methods. */
export const secp256k1_hasher = /* @__PURE__ */ (() => createHasher(secp256k1.Point, (scalars) => {
    const { x, y } = mapSWU(Fpk1.create(scalars[0]));
    return isoMap(x, y);
}, {
    DST: 'secp256k1_XMD:SHA-256_SSWU_RO_',
    encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_',
    p: Fpk1.ORDER,
    m: 1,
    k: 128,
    expand: 'xmd',
    hash: sha256,
}))();
/** @deprecated use `import { secp256k1_hasher } from '@noble/curves/secp256k1.js';` */
export const hashToCurve = /* @__PURE__ */ (() => secp256k1_hasher.hashToCurve)();
/** @deprecated use `import { secp256k1_hasher } from '@noble/curves/secp256k1.js';` */
export const encodeToCurve = /* @__PURE__ */ (() => secp256k1_hasher.encodeToCurve)();
//# sourceMappingURL=secp256k1.js.map/**
 * Hex, bytes and number utilities.
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { abytes as abytes_, bytesToHex as bytesToHex_, concatBytes as concatBytes_, hexToBytes as hexToBytes_, isBytes as isBytes_, } from '@noble/hashes/utils.js';
export { abytes, anumber, bytesToHex, bytesToUtf8, concatBytes, hexToBytes, isBytes, randomBytes, utf8ToBytes, } from '@noble/hashes/utils.js';
const _0n = /* @__PURE__ */ BigInt(0);
const _1n = /* @__PURE__ */ BigInt(1);
export function abool(title, value) {
    if (typeof value !== 'boolean')
        throw new Error(title + ' boolean expected, got ' + value);
}
// tmp name until v2
export function _abool2(value, title = '') {
    if (typeof value !== 'boolean') {
        const prefix = title && `"${title}"`;
        throw new Error(prefix + 'expected boolean, got type=' + typeof value);
    }
    return value;
}
// tmp name until v2
/** Asserts something is Uint8Array. */
export function _abytes2(value, length, title = '') {
    const bytes = isBytes_(value);
    const len = value?.length;
    const needsLen = length !== undefined;
    if (!bytes || (needsLen && len !== length)) {
        const prefix = title && `"${title}" `;
        const ofLen = needsLen ? ` of length ${length}` : '';
        const got = bytes ? `length=${len}` : `type=${typeof value}`;
        throw new Error(prefix + 'expected Uint8Array' + ofLen + ', got ' + got);
    }
    return value;
}
// Used in weierstrass, der
export function numberToHexUnpadded(num) {
    const hex = num.toString(16);
    return hex.length & 1 ? '0' + hex : hex;
}
export function hexToNumber(hex) {
    if (typeof hex !== 'string')
        throw new Error('hex string expected, got ' + typeof hex);
    return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian
}
// BE: Big Endian, LE: Little Endian
export function bytesToNumberBE(bytes) {
    return hexToNumber(bytesToHex_(bytes));
}
export function bytesToNumberLE(bytes) {
    abytes_(bytes);
    return hexToNumber(bytesToHex_(Uint8Array.from(bytes).reverse()));
}
export function numberToBytesBE(n, len) {
    return hexToBytes_(n.toString(16).padStart(len * 2, '0'));
}
export function numberToBytesLE(n, len) {
    return numberToBytesBE(n, len).reverse();
}
// Unpadded, rarely used
export function numberToVarBytesBE(n) {
    return hexToBytes_(numberToHexUnpadded(n));
}
/**
 * Takes hex string or Uint8Array, converts to Uint8Array.
 * Validates output length.
 * Will throw error for other types.
 * @param title descriptive title for an error e.g. 'secret key'
 * @param hex hex string or Uint8Array
 * @param expectedLength optional, will compare to result array's length
 * @returns
 */
export function ensureBytes(title, hex, expectedLength) {
    let res;
    if (typeof hex === 'string') {
        try {
            res = hexToBytes_(hex);
        }
        catch (e) {
            throw new Error(title + ' must be hex string or Uint8Array, cause: ' + e);
        }
    }
    else if (isBytes_(hex)) {
        // Uint8Array.from() instead of hash.slice() because node.js Buffer
        // is instance of Uint8Array, and its slice() creates **mutable** copy
        res = Uint8Array.from(hex);
    }
    else {
        throw new Error(title + ' must be hex string or Uint8Array');
    }
    const len = res.length;
    if (typeof expectedLength === 'number' && len !== expectedLength)
        throw new Error(title + ' of length ' + expectedLength + ' expected, got ' + len);
    return res;
}
// Compares 2 u8a-s in kinda constant time
export function equalBytes(a, b) {
    if (a.length !== b.length)
        return false;
    let diff = 0;
    for (let i = 0; i < a.length; i++)
        diff |= a[i] ^ b[i];
    return diff === 0;
}
/**
 * Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,
 * and Buffer#slice creates mutable copy. Never use Buffers!
 */
export function copyBytes(bytes) {
    return Uint8Array.from(bytes);
}
/**
 * Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols
 * Should be safe to use for things expected to be ASCII.
 * Returns exact same result as utf8ToBytes for ASCII or throws.
 */
export function asciiToBytes(ascii) {
    return Uint8Array.from(ascii, (c, i) => {
        const charCode = c.charCodeAt(0);
        if (c.length !== 1 || charCode > 127) {
            throw new Error(`string contains non-ASCII character "${ascii[i]}" with code ${charCode} at position ${i}`);
        }
        return charCode;
    });
}
/**
 * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
 */
// export const utf8ToBytes: typeof utf8ToBytes_ = utf8ToBytes_;
/**
 * Converts bytes to string using UTF8 encoding.
 * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'
 */
// export const bytesToUtf8: typeof bytesToUtf8_ = bytesToUtf8_;
// Is positive bigint
const isPosBig = (n) => typeof n === 'bigint' && _0n <= n;
export function inRange(n, min, max) {
    return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
}
/**
 * Asserts min <= n < max. NOTE: It's < max and not <= max.
 * @example
 * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)
 */
export function aInRange(title, n, min, max) {
    // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?
    // consider P=256n, min=0n, max=P
    // - a for min=0 would require -1:          `inRange('x', x, -1n, P)`
    // - b would commonly require subtraction:  `inRange('x', x, 0n, P - 1n)`
    // - our way is the cleanest:               `inRange('x', x, 0n, P)
    if (!inRange(n, min, max))
        throw new Error('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);
}
// Bit operations
/**
 * Calculates amount of bits in a bigint.
 * Same as `n.toString(2).length`
 * TODO: merge with nLength in modular
 */
export function bitLen(n) {
    let len;
    for (len = 0; n > _0n; n >>= _1n, len += 1)
        ;
    return len;
}
/**
 * Gets single bit at position.
 * NOTE: first bit position is 0 (same as arrays)
 * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`
 */
export function bitGet(n, pos) {
    return (n >> BigInt(pos)) & _1n;
}
/**
 * Sets single bit at position.
 */
export function bitSet(n, pos, value) {
    return n | ((value ? _1n : _0n) << BigInt(pos));
}
/**
 * Calculate mask for N bits. Not using ** operator with bigints because of old engines.
 * Same as BigInt(`0b${Array(i).fill('1').join('')}`)
 */
export const bitMask = (n) => (_1n << BigInt(n)) - _1n;
/**
 * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
 * @returns function that will call DRBG until 2nd arg returns something meaningful
 * @example
 *   const drbg = createHmacDRBG<Key>(32, 32, hmac);
 *   drbg(seed, bytesToKey); // bytesToKey must return Key or undefined
 */
export function createHmacDrbg(hashLen, qByteLen, hmacFn) {
    if (typeof hashLen !== 'number' || hashLen < 2)
        throw new Error('hashLen must be a number');
    if (typeof qByteLen !== 'number' || qByteLen < 2)
        throw new Error('qByteLen must be a number');
    if (typeof hmacFn !== 'function')
        throw new Error('hmacFn must be a function');
    // Step B, Step C: set hashLen to 8*ceil(hlen/8)
    const u8n = (len) => new Uint8Array(len); // creates Uint8Array
    const u8of = (byte) => Uint8Array.of(byte); // another shortcut
    let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
    let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same
    let i = 0; // Iterations counter, will throw when over 1000
    const reset = () => {
        v.fill(1);
        k.fill(0);
        i = 0;
    };
    const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)
    const reseed = (seed = u8n(0)) => {
        // HMAC-DRBG reseed() function. Steps D-G
        k = h(u8of(0x00), seed); // k = hmac(k || v || 0x00 || seed)
        v = h(); // v = hmac(k || v)
        if (seed.length === 0)
            return;
        k = h(u8of(0x01), seed); // k = hmac(k || v || 0x01 || seed)
        v = h(); // v = hmac(k || v)
    };
    const gen = () => {
        // HMAC-DRBG generate() function
        if (i++ >= 1000)
            throw new Error('drbg: tried 1000 values');
        let len = 0;
        const out = [];
        while (len < qByteLen) {
            v = h();
            const sl = v.slice();
            out.push(sl);
            len += v.length;
        }
        return concatBytes_(...out);
    };
    const genUntil = (seed, pred) => {
        reset();
        reseed(seed); // Steps D-G
        let res = undefined; // Step H: grind until k is in [1..n-1]
        while (!(res = pred(gen())))
            reseed();
        reset();
        return res;
    };
    return genUntil;
}
// Validating curves and fields
const validatorFns = {
    bigint: (val) => typeof val === 'bigint',
    function: (val) => typeof val === 'function',
    boolean: (val) => typeof val === 'boolean',
    string: (val) => typeof val === 'string',
    stringOrUint8Array: (val) => typeof val === 'string' || isBytes_(val),
    isSafeInteger: (val) => Number.isSafeInteger(val),
    array: (val) => Array.isArray(val),
    field: (val, object) => object.Fp.isValid(val),
    hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),
};
// type Record<K extends string | number | symbol, T> = { [P in K]: T; }
export function validateObject(object, validators, optValidators = {}) {
    const checkField = (fieldName, type, isOptional) => {
        const checkVal = validatorFns[type];
        if (typeof checkVal !== 'function')
            throw new Error('invalid validator function');
        const val = object[fieldName];
        if (isOptional && val === undefined)
            return;
        if (!checkVal(val, object)) {
            throw new Error('param ' + String(fieldName) + ' is invalid. Expected ' + type + ', got ' + val);
        }
    };
    for (const [fieldName, type] of Object.entries(validators))
        checkField(fieldName, type, false);
    for (const [fieldName, type] of Object.entries(optValidators))
        checkField(fieldName, type, true);
    return object;
}
// validate type tests
// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };
// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!
// // Should fail type-check
// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });
// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });
// const z3 = validateObject(o, { test: 'boolean', z: 'bug' });
// const z4 = validateObject(o, { a: 'boolean', z: 'bug' });
export function isHash(val) {
    return typeof val === 'function' && Number.isSafeInteger(val.outputLen);
}
export function _validateObject(object, fields, optFields = {}) {
    if (!object || typeof object !== 'object')
        throw new Error('expected valid options object');
    function checkField(fieldName, expectedType, isOpt) {
        const val = object[fieldName];
        if (isOpt && val === undefined)
            return;
        const current = typeof val;
        if (current !== expectedType || val === null)
            throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
    }
    Object.entries(fields).forEach(([k, v]) => checkField(k, v, false));
    Object.entries(optFields).forEach(([k, v]) => checkField(k, v, true));
}
/**
 * throws not implemented error
 */
export const notImplemented = () => {
    throw new Error('not implemented');
};
/**
 * Memoizes (caches) computation result.
 * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.
 */
export function memoized(fn) {
    const map = new WeakMap();
    return (arg, ...args) => {
        const val = map.get(arg);
        if (val !== undefined)
            return val;
        const computed = fn(arg, ...args);
        map.set(arg, computed);
        return computed;
    };
}
//# sourceMappingURL=utils.js.map/**
 * Internal Merkle-Damgard hash utils.
 * @module
 */
import { Hash, abytes, aexists, aoutput, clean, createView, toBytes } from "./utils.js";
/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */
export function setBigUint64(view, byteOffset, value, isLE) {
    if (typeof view.setBigUint64 === 'function')
        return view.setBigUint64(byteOffset, value, isLE);
    const _32n = BigInt(32);
    const _u32_max = BigInt(0xffffffff);
    const wh = Number((value >> _32n) & _u32_max);
    const wl = Number(value & _u32_max);
    const h = isLE ? 4 : 0;
    const l = isLE ? 0 : 4;
    view.setUint32(byteOffset + h, wh, isLE);
    view.setUint32(byteOffset + l, wl, isLE);
}
/** Choice: a ? b : c */
export function Chi(a, b, c) {
    return (a & b) ^ (~a & c);
}
/** Majority function, true if any two inputs is true. */
export function Maj(a, b, c) {
    return (a & b) ^ (a & c) ^ (b & c);
}
/**
 * Merkle-Damgard hash construction base class.
 * Could be used to create MD5, RIPEMD, SHA1, SHA2.
 */
export class HashMD extends Hash {
    constructor(blockLen, outputLen, padOffset, isLE) {
        super();
        this.finished = false;
        this.length = 0;
        this.pos = 0;
        this.destroyed = false;
        this.blockLen = blockLen;
        this.outputLen = outputLen;
        this.padOffset = padOffset;
        this.isLE = isLE;
        this.buffer = new Uint8Array(blockLen);
        this.view = createView(this.buffer);
    }
    update(data) {
        aexists(this);
        data = toBytes(data);
        abytes(data);
        const { view, buffer, blockLen } = this;
        const len = data.length;
        for (let pos = 0; pos < len;) {
            const take = Math.min(blockLen - this.pos, len - pos);
            // Fast path: we have at least one block in input, cast it to view and process
            if (take === blockLen) {
                const dataView = createView(data);
                for (; blockLen <= len - pos; pos += blockLen)
                    this.process(dataView, pos);
                continue;
            }
            buffer.set(data.subarray(pos, pos + take), this.pos);
            this.pos += take;
            pos += take;
            if (this.pos === blockLen) {
                this.process(view, 0);
                this.pos = 0;
            }
        }
        this.length += data.length;
        this.roundClean();
        return this;
    }
    digestInto(out) {
        aexists(this);
        aoutput(out, this);
        this.finished = true;
        // Padding
        // We can avoid allocation of buffer for padding completely if it
        // was previously not allocated here. But it won't change performance.
        const { buffer, view, blockLen, isLE } = this;
        let { pos } = this;
        // append the bit '1' to the message
        buffer[pos++] = 0b10000000;
        clean(this.buffer.subarray(pos));
        // we have less than padOffset left in buffer, so we cannot put length in
        // current block, need process it and pad again
        if (this.padOffset > blockLen - pos) {
            this.process(view, 0);
            pos = 0;
        }
        // Pad until full block byte with zeros
        for (let i = pos; i < blockLen; i++)
            buffer[i] = 0;
        // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that
        // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.
        // So we just write lowest 64 bits of that value.
        setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
        this.process(view, 0);
        const oview = createView(out);
        const len = this.outputLen;
        // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT
        if (len % 4)
            throw new Error('_sha2: outputLen should be aligned to 32bit');
        const outLen = len / 4;
        const state = this.get();
        if (outLen > state.length)
            throw new Error('_sha2: outputLen bigger than state');
        for (let i = 0; i < outLen; i++)
            oview.setUint32(4 * i, state[i], isLE);
    }
    digest() {
        const { buffer, outputLen } = this;
        this.digestInto(buffer);
        const res = buffer.slice(0, outputLen);
        this.destroy();
        return res;
    }
    _cloneInto(to) {
        to || (to = new this.constructor());
        to.set(...this.get());
        const { blockLen, buffer, length, finished, destroyed, pos } = this;
        to.destroyed = destroyed;
        to.finished = finished;
        to.length = length;
        to.pos = pos;
        if (length % blockLen)
            to.buffer.set(buffer);
        return to;
    }
    clone() {
        return this._cloneInto();
    }
}
/**
 * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.
 * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.
 */
/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */
export const SHA256_IV = /* @__PURE__ */ Uint32Array.from([
    0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
]);
/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */
export const SHA224_IV = /* @__PURE__ */ Uint32Array.from([
    0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,
]);
/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */
export const SHA384_IV = /* @__PURE__ */ Uint32Array.from([
    0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,
    0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,
]);
/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */
export const SHA512_IV = /* @__PURE__ */ Uint32Array.from([
    0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,
    0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,
]);
//# sourceMappingURL=_md.js.map/**
 * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.
 * @todo re-check https://issues.chromium.org/issues/42212588
 * @module
 */
const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
const _32n = /* @__PURE__ */ BigInt(32);
function fromBig(n, le = false) {
    if (le)
        return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };
    return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
}
function split(lst, le = false) {
    const len = lst.length;
    let Ah = new Uint32Array(len);
    let Al = new Uint32Array(len);
    for (let i = 0; i < len; i++) {
        const { h, l } = fromBig(lst[i], le);
        [Ah[i], Al[i]] = [h, l];
    }
    return [Ah, Al];
}
const toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);
// for Shift in [0, 32)
const shrSH = (h, _l, s) => h >>> s;
const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
// Right rotate for Shift in [1, 32)
const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));
const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
// Right rotate for Shift in (32, 64), NOTE: 32 is special case.
const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));
const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));
// Right rotate for shift===32 (just swaps l&h)
const rotr32H = (_h, l) => l;
const rotr32L = (h, _l) => h;
// Left rotate for Shift in [1, 32)
const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));
const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));
// Left rotate for Shift in (32, 64), NOTE: 32 is special case.
const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));
const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));
// JS uses 32-bit signed integers for bitwise operations which means we cannot
// simple take carry out of low bit sum by shift, we need to use division.
function add(Ah, Al, Bh, Bl) {
    const l = (Al >>> 0) + (Bl >>> 0);
    return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };
}
// Addition with more than 2 elements
const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;
const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;
const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;
// prettier-ignore
export { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig };
// prettier-ignore
const u64 = {
    fromBig, split, toBig,
    shrSH, shrSL,
    rotrSH, rotrSL, rotrBH, rotrBL,
    rotr32H, rotr32L,
    rotlSH, rotlSL, rotlBH, rotlBL,
    add, add3L, add3H, add4L, add4H, add5H, add5L,
};
export default u64;
//# sourceMappingURL=_u64.js.mapexport const crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;
//# sourceMappingURL=crypto.js.map/**
 * HMAC: RFC2104 message authentication code.
 * @module
 */
import { abytes, aexists, ahash, clean, Hash, toBytes } from "./utils.js";
export class HMAC extends Hash {
    constructor(hash, _key) {
        super();
        this.finished = false;
        this.destroyed = false;
        ahash(hash);
        const key = toBytes(_key);
        this.iHash = hash.create();
        if (typeof this.iHash.update !== 'function')
            throw new Error('Expected instance of class which extends utils.Hash');
        this.blockLen = this.iHash.blockLen;
        this.outputLen = this.iHash.outputLen;
        const blockLen = this.blockLen;
        const pad = new Uint8Array(blockLen);
        // blockLen can be bigger than outputLen
        pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
        for (let i = 0; i < pad.length; i++)
            pad[i] ^= 0x36;
        this.iHash.update(pad);
        // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone
        this.oHash = hash.create();
        // Undo internal XOR && apply outer XOR
        for (let i = 0; i < pad.length; i++)
            pad[i] ^= 0x36 ^ 0x5c;
        this.oHash.update(pad);
        clean(pad);
    }
    update(buf) {
        aexists(this);
        this.iHash.update(buf);
        return this;
    }
    digestInto(out) {
        aexists(this);
        abytes(out, this.outputLen);
        this.finished = true;
        this.iHash.digestInto(out);
        this.oHash.update(out);
        this.oHash.digestInto(out);
        this.destroy();
    }
    digest() {
        const out = new Uint8Array(this.oHash.outputLen);
        this.digestInto(out);
        return out;
    }
    _cloneInto(to) {
        // Create new instance without calling constructor since key already in state and we don't know it.
        to || (to = Object.create(Object.getPrototypeOf(this), {}));
        const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
        to = to;
        to.finished = finished;
        to.destroyed = destroyed;
        to.blockLen = blockLen;
        to.outputLen = outputLen;
        to.oHash = oHash._cloneInto(to.oHash);
        to.iHash = iHash._cloneInto(to.iHash);
        return to;
    }
    clone() {
        return this._cloneInto();
    }
    destroy() {
        this.destroyed = true;
        this.oHash.destroy();
        this.iHash.destroy();
    }
}
/**
 * HMAC: RFC2104 message authentication code.
 * @param hash - function that would be used e.g. sha256
 * @param key - message key
 * @param message - message data
 * @example
 * import { hmac } from '@noble/hashes/hmac';
 * import { sha256 } from '@noble/hashes/sha2';
 * const mac1 = hmac(sha256, 'key', 'message');
 */
export const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
hmac.create = (hash, key) => new HMAC(hash, key);
//# sourceMappingURL=hmac.js.map{
  "type": "module",
  "sideEffects": false,
  "browser": {
    "node:crypto": false
  },
  "node": {
    "./crypto": "./esm/cryptoNode.js"
  }
}
/**
 * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.
 * SHA256 is the fastest hash implementable in JS, even faster than Blake3.
 * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and
 * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).
 * @module
 */
import { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from "./_md.js";
import * as u64 from "./_u64.js";
import { clean, createHasher, rotr } from "./utils.js";
/**
 * Round constants:
 * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)
 */
// prettier-ignore
const SHA256_K = /* @__PURE__ */ Uint32Array.from([
    0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
    0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
    0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
    0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
    0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
    0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
    0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
    0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
]);
/** Reusable temporary buffer. "W" comes straight from spec. */
const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
export class SHA256 extends HashMD {
    constructor(outputLen = 32) {
        super(64, outputLen, 8, false);
        // We cannot use array here since array allows indexing by variable
        // which means optimizer/compiler cannot use registers.
        this.A = SHA256_IV[0] | 0;
        this.B = SHA256_IV[1] | 0;
        this.C = SHA256_IV[2] | 0;
        this.D = SHA256_IV[3] | 0;
        this.E = SHA256_IV[4] | 0;
        this.F = SHA256_IV[5] | 0;
        this.G = SHA256_IV[6] | 0;
        this.H = SHA256_IV[7] | 0;
    }
    get() {
        const { A, B, C, D, E, F, G, H } = this;
        return [A, B, C, D, E, F, G, H];
    }
    // prettier-ignore
    set(A, B, C, D, E, F, G, H) {
        this.A = A | 0;
        this.B = B | 0;
        this.C = C | 0;
        this.D = D | 0;
        this.E = E | 0;
        this.F = F | 0;
        this.G = G | 0;
        this.H = H | 0;
    }
    process(view, offset) {
        // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array
        for (let i = 0; i < 16; i++, offset += 4)
            SHA256_W[i] = view.getUint32(offset, false);
        for (let i = 16; i < 64; i++) {
            const W15 = SHA256_W[i - 15];
            const W2 = SHA256_W[i - 2];
            const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);
            const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);
            SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;
        }
        // Compression function main loop, 64 rounds
        let { A, B, C, D, E, F, G, H } = this;
        for (let i = 0; i < 64; i++) {
            const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
            const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
            const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
            const T2 = (sigma0 + Maj(A, B, C)) | 0;
            H = G;
            G = F;
            F = E;
            E = (D + T1) | 0;
            D = C;
            C = B;
            B = A;
            A = (T1 + T2) | 0;
        }
        // Add the compressed chunk to the current hash value
        A = (A + this.A) | 0;
        B = (B + this.B) | 0;
        C = (C + this.C) | 0;
        D = (D + this.D) | 0;
        E = (E + this.E) | 0;
        F = (F + this.F) | 0;
        G = (G + this.G) | 0;
        H = (H + this.H) | 0;
        this.set(A, B, C, D, E, F, G, H);
    }
    roundClean() {
        clean(SHA256_W);
    }
    destroy() {
        this.set(0, 0, 0, 0, 0, 0, 0, 0);
        clean(this.buffer);
    }
}
export class SHA224 extends SHA256 {
    constructor() {
        super(28);
        this.A = SHA224_IV[0] | 0;
        this.B = SHA224_IV[1] | 0;
        this.C = SHA224_IV[2] | 0;
        this.D = SHA224_IV[3] | 0;
        this.E = SHA224_IV[4] | 0;
        this.F = SHA224_IV[5] | 0;
        this.G = SHA224_IV[6] | 0;
        this.H = SHA224_IV[7] | 0;
    }
}
// SHA2-512 is slower than sha256 in js because u64 operations are slow.
// Round contants
// First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409
// prettier-ignore
const K512 = /* @__PURE__ */ (() => u64.split([
    '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',
    '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',
    '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',
    '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',
    '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',
    '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',
    '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',
    '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',
    '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',
    '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',
    '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',
    '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',
    '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',
    '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',
    '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',
    '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',
    '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',
    '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',
    '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',
    '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'
].map(n => BigInt(n))))();
const SHA512_Kh = /* @__PURE__ */ (() => K512[0])();
const SHA512_Kl = /* @__PURE__ */ (() => K512[1])();
// Reusable temporary buffers
const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
export class SHA512 extends HashMD {
    constructor(outputLen = 64) {
        super(128, outputLen, 16, false);
        // We cannot use array here since array allows indexing by variable
        // which means optimizer/compiler cannot use registers.
        // h -- high 32 bits, l -- low 32 bits
        this.Ah = SHA512_IV[0] | 0;
        this.Al = SHA512_IV[1] | 0;
        this.Bh = SHA512_IV[2] | 0;
        this.Bl = SHA512_IV[3] | 0;
        this.Ch = SHA512_IV[4] | 0;
        this.Cl = SHA512_IV[5] | 0;
        this.Dh = SHA512_IV[6] | 0;
        this.Dl = SHA512_IV[7] | 0;
        this.Eh = SHA512_IV[8] | 0;
        this.El = SHA512_IV[9] | 0;
        this.Fh = SHA512_IV[10] | 0;
        this.Fl = SHA512_IV[11] | 0;
        this.Gh = SHA512_IV[12] | 0;
        this.Gl = SHA512_IV[13] | 0;
        this.Hh = SHA512_IV[14] | 0;
        this.Hl = SHA512_IV[15] | 0;
    }
    // prettier-ignore
    get() {
        const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
        return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
    }
    // prettier-ignore
    set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
        this.Ah = Ah | 0;
        this.Al = Al | 0;
        this.Bh = Bh | 0;
        this.Bl = Bl | 0;
        this.Ch = Ch | 0;
        this.Cl = Cl | 0;
        this.Dh = Dh | 0;
        this.Dl = Dl | 0;
        this.Eh = Eh | 0;
        this.El = El | 0;
        this.Fh = Fh | 0;
        this.Fl = Fl | 0;
        this.Gh = Gh | 0;
        this.Gl = Gl | 0;
        this.Hh = Hh | 0;
        this.Hl = Hl | 0;
    }
    process(view, offset) {
        // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array
        for (let i = 0; i < 16; i++, offset += 4) {
            SHA512_W_H[i] = view.getUint32(offset);
            SHA512_W_L[i] = view.getUint32((offset += 4));
        }
        for (let i = 16; i < 80; i++) {
            // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)
            const W15h = SHA512_W_H[i - 15] | 0;
            const W15l = SHA512_W_L[i - 15] | 0;
            const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);
            const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);
            // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)
            const W2h = SHA512_W_H[i - 2] | 0;
            const W2l = SHA512_W_L[i - 2] | 0;
            const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);
            const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);
            // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];
            const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
            const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
            SHA512_W_H[i] = SUMh | 0;
            SHA512_W_L[i] = SUMl | 0;
        }
        let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
        // Compression function main loop, 80 rounds
        for (let i = 0; i < 80; i++) {
            // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)
            const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);
            const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);
            //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
            const CHIh = (Eh & Fh) ^ (~Eh & Gh);
            const CHIl = (El & Fl) ^ (~El & Gl);
            // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]
            // prettier-ignore
            const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
            const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
            const T1l = T1ll | 0;
            // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)
            const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);
            const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);
            const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);
            const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);
            Hh = Gh | 0;
            Hl = Gl | 0;
            Gh = Fh | 0;
            Gl = Fl | 0;
            Fh = Eh | 0;
            Fl = El | 0;
            ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
            Dh = Ch | 0;
            Dl = Cl | 0;
            Ch = Bh | 0;
            Cl = Bl | 0;
            Bh = Ah | 0;
            Bl = Al | 0;
            const All = u64.add3L(T1l, sigma0l, MAJl);
            Ah = u64.add3H(All, T1h, sigma0h, MAJh);
            Al = All | 0;
        }
        // Add the compressed chunk to the current hash value
        ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
        ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
        ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
        ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
        ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
        ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
        ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
        ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
        this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
    }
    roundClean() {
        clean(SHA512_W_H, SHA512_W_L);
    }
    destroy() {
        clean(this.buffer);
        this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
    }
}
export class SHA384 extends SHA512 {
    constructor() {
        super(48);
        this.Ah = SHA384_IV[0] | 0;
        this.Al = SHA384_IV[1] | 0;
        this.Bh = SHA384_IV[2] | 0;
        this.Bl = SHA384_IV[3] | 0;
        this.Ch = SHA384_IV[4] | 0;
        this.Cl = SHA384_IV[5] | 0;
        this.Dh = SHA384_IV[6] | 0;
        this.Dl = SHA384_IV[7] | 0;
        this.Eh = SHA384_IV[8] | 0;
        this.El = SHA384_IV[9] | 0;
        this.Fh = SHA384_IV[10] | 0;
        this.Fl = SHA384_IV[11] | 0;
        this.Gh = SHA384_IV[12] | 0;
        this.Gl = SHA384_IV[13] | 0;
        this.Hh = SHA384_IV[14] | 0;
        this.Hl = SHA384_IV[15] | 0;
    }
}
/**
 * Truncated SHA512/256 and SHA512/224.
 * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as "intermediary" IV of SHA512/t.
 * Then t hashes string to produce result IV.
 * See `test/misc/sha2-gen-iv.js`.
 */
/** SHA512/224 IV */
const T224_IV = /* @__PURE__ */ Uint32Array.from([
    0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,
    0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,
]);
/** SHA512/256 IV */
const T256_IV = /* @__PURE__ */ Uint32Array.from([
    0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,
    0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,
]);
export class SHA512_224 extends SHA512 {
    constructor() {
        super(28);
        this.Ah = T224_IV[0] | 0;
        this.Al = T224_IV[1] | 0;
        this.Bh = T224_IV[2] | 0;
        this.Bl = T224_IV[3] | 0;
        this.Ch = T224_IV[4] | 0;
        this.Cl = T224_IV[5] | 0;
        this.Dh = T224_IV[6] | 0;
        this.Dl = T224_IV[7] | 0;
        this.Eh = T224_IV[8] | 0;
        this.El = T224_IV[9] | 0;
        this.Fh = T224_IV[10] | 0;
        this.Fl = T224_IV[11] | 0;
        this.Gh = T224_IV[12] | 0;
        this.Gl = T224_IV[13] | 0;
        this.Hh = T224_IV[14] | 0;
        this.Hl = T224_IV[15] | 0;
    }
}
export class SHA512_256 extends SHA512 {
    constructor() {
        super(32);
        this.Ah = T256_IV[0] | 0;
        this.Al = T256_IV[1] | 0;
        this.Bh = T256_IV[2] | 0;
        this.Bl = T256_IV[3] | 0;
        this.Ch = T256_IV[4] | 0;
        this.Cl = T256_IV[5] | 0;
        this.Dh = T256_IV[6] | 0;
        this.Dl = T256_IV[7] | 0;
        this.Eh = T256_IV[8] | 0;
        this.El = T256_IV[9] | 0;
        this.Fh = T256_IV[10] | 0;
        this.Fl = T256_IV[11] | 0;
        this.Gh = T256_IV[12] | 0;
        this.Gl = T256_IV[13] | 0;
        this.Hh = T256_IV[14] | 0;
        this.Hl = T256_IV[15] | 0;
    }
}
/**
 * SHA2-256 hash function from RFC 4634.
 *
 * It is the fastest JS hash, even faster than Blake3.
 * To break sha256 using birthday attack, attackers need to try 2^128 hashes.
 * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
 */
export const sha256 = /* @__PURE__ */ createHasher(() => new SHA256());
/** SHA2-224 hash function from RFC 4634 */
export const sha224 = /* @__PURE__ */ createHasher(() => new SHA224());
/** SHA2-512 hash function from RFC 4634. */
export const sha512 = /* @__PURE__ */ createHasher(() => new SHA512());
/** SHA2-384 hash function from RFC 4634. */
export const sha384 = /* @__PURE__ */ createHasher(() => new SHA384());
/**
 * SHA2-512/256 "truncated" hash function, with improved resistance to length extension attacks.
 * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).
 */
export const sha512_256 = /* @__PURE__ */ createHasher(() => new SHA512_256());
/**
 * SHA2-512/224 "truncated" hash function, with improved resistance to length extension attacks.
 * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).
 */
export const sha512_224 = /* @__PURE__ */ createHasher(() => new SHA512_224());
//# sourceMappingURL=sha2.js.map/**
 * Utilities for hex, bytes, CSPRNG.
 * @module
 */
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
// node.js versions earlier than v19 don't declare it in global scope.
// For node.js, package.json#exports field mapping rewrites import
// from `crypto` to `cryptoNode`, which imports native module.
// Makes the utils un-importable in browsers without a bundler.
// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.
import { crypto } from '@noble/hashes/crypto';
/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */
export function isBytes(a) {
    return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
}
/** Asserts something is positive integer. */
export function anumber(n) {
    if (!Number.isSafeInteger(n) || n < 0)
        throw new Error('positive integer expected, got ' + n);
}
/** Asserts something is Uint8Array. */
export function abytes(b, ...lengths) {
    if (!isBytes(b))
        throw new Error('Uint8Array expected');
    if (lengths.length > 0 && !lengths.includes(b.length))
        throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);
}
/** Asserts something is hash */
export function ahash(h) {
    if (typeof h !== 'function' || typeof h.create !== 'function')
        throw new Error('Hash should be wrapped by utils.createHasher');
    anumber(h.outputLen);
    anumber(h.blockLen);
}
/** Asserts a hash instance has not been destroyed / finished */
export function aexists(instance, checkFinished = true) {
    if (instance.destroyed)
        throw new Error('Hash instance has been destroyed');
    if (checkFinished && instance.finished)
        throw new Error('Hash#digest() has already been called');
}
/** Asserts output is properly-sized byte array */
export function aoutput(out, instance) {
    abytes(out);
    const min = instance.outputLen;
    if (out.length < min) {
        throw new Error('digestInto() expects output buffer of length at least ' + min);
    }
}
/** Cast u8 / u16 / u32 to u8. */
export function u8(arr) {
    return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
}
/** Cast u8 / u16 / u32 to u32. */
export function u32(arr) {
    return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
}
/** Zeroize a byte array. Warning: JS provides no guarantees. */
export function clean(...arrays) {
    for (let i = 0; i < arrays.length; i++) {
        arrays[i].fill(0);
    }
}
/** Create DataView of an array for easy byte-level manipulation. */
export function createView(arr) {
    return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
}
/** The rotate right (circular right shift) operation for uint32 */
export function rotr(word, shift) {
    return (word << (32 - shift)) | (word >>> shift);
}
/** The rotate left (circular left shift) operation for uint32 */
export function rotl(word, shift) {
    return (word << shift) | ((word >>> (32 - shift)) >>> 0);
}
/** Is current platform little-endian? Most are. Big-Endian platform: IBM */
export const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();
/** The byte swap operation for uint32 */
export function byteSwap(word) {
    return (((word << 24) & 0xff000000) |
        ((word << 8) & 0xff0000) |
        ((word >>> 8) & 0xff00) |
        ((word >>> 24) & 0xff));
}
/** Conditionally byte swap if on a big-endian platform */
export const swap8IfBE = isLE
    ? (n) => n
    : (n) => byteSwap(n);
/** @deprecated */
export const byteSwapIfBE = swap8IfBE;
/** In place byte swap for Uint32Array */
export function byteSwap32(arr) {
    for (let i = 0; i < arr.length; i++) {
        arr[i] = byteSwap(arr[i]);
    }
    return arr;
}
export const swap32IfBE = isLE
    ? (u) => u
    : byteSwap32;
// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex
const hasHexBuiltin = /* @__PURE__ */ (() => 
// @ts-ignore
typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();
// Array where index 0xf0 (240) is mapped to string 'f0'
const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
/**
 * Convert byte array to hex string. Uses built-in function, when available.
 * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
 */
export function bytesToHex(bytes) {
    abytes(bytes);
    // @ts-ignore
    if (hasHexBuiltin)
        return bytes.toHex();
    // pre-caching improves the speed 6x
    let hex = '';
    for (let i = 0; i < bytes.length; i++) {
        hex += hexes[bytes[i]];
    }
    return hex;
}
// We use optimized technique to convert hex string to byte array
const asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
function asciiToBase16(ch) {
    if (ch >= asciis._0 && ch <= asciis._9)
        return ch - asciis._0; // '2' => 50-48
    if (ch >= asciis.A && ch <= asciis.F)
        return ch - (asciis.A - 10); // 'B' => 66-(65-10)
    if (ch >= asciis.a && ch <= asciis.f)
        return ch - (asciis.a - 10); // 'b' => 98-(97-10)
    return;
}
/**
 * Convert hex string to byte array. Uses built-in function, when available.
 * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
 */
export function hexToBytes(hex) {
    if (typeof hex !== 'string')
        throw new Error('hex string expected, got ' + typeof hex);
    // @ts-ignore
    if (hasHexBuiltin)
        return Uint8Array.fromHex(hex);
    const hl = hex.length;
    const al = hl / 2;
    if (hl % 2)
        throw new Error('hex string expected, got unpadded hex of length ' + hl);
    const array = new Uint8Array(al);
    for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
        const n1 = asciiToBase16(hex.charCodeAt(hi));
        const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
        if (n1 === undefined || n2 === undefined) {
            const char = hex[hi] + hex[hi + 1];
            throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
        }
        array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163
    }
    return array;
}
/**
 * There is no setImmediate in browser and setTimeout is slow.
 * Call of async fn will return Promise, which will be fullfiled only on
 * next scheduler queue processing step and this is exactly what we need.
 */
export const nextTick = async () => { };
/** Returns control to thread each 'tick' ms to avoid blocking. */
export async function asyncLoop(iters, tick, cb) {
    let ts = Date.now();
    for (let i = 0; i < iters; i++) {
        cb(i);
        // Date.now() is not monotonic, so in case if clock goes backwards we return return control too
        const diff = Date.now() - ts;
        if (diff >= 0 && diff < tick)
            continue;
        await nextTick();
        ts += diff;
    }
}
/**
 * Converts string to bytes using UTF8 encoding.
 * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])
 */
export function utf8ToBytes(str) {
    if (typeof str !== 'string')
        throw new Error('string expected');
    return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
}
/**
 * Converts bytes to string using UTF8 encoding.
 * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'
 */
export function bytesToUtf8(bytes) {
    return new TextDecoder().decode(bytes);
}
/**
 * Normalizes (non-hex) string or Uint8Array to Uint8Array.
 * Warning: when Uint8Array is passed, it would NOT get copied.
 * Keep in mind for future mutable operations.
 */
export function toBytes(data) {
    if (typeof data === 'string')
        data = utf8ToBytes(data);
    abytes(data);
    return data;
}
/**
 * Helper for KDFs: consumes uint8array or string.
 * When string is passed, does utf8 decoding, using TextDecoder.
 */
export function kdfInputToBytes(data) {
    if (typeof data === 'string')
        data = utf8ToBytes(data);
    abytes(data);
    return data;
}
/** Copies several Uint8Arrays into one. */
export function concatBytes(...arrays) {
    let sum = 0;
    for (let i = 0; i < arrays.length; i++) {
        const a = arrays[i];
        abytes(a);
        sum += a.length;
    }
    const res = new Uint8Array(sum);
    for (let i = 0, pad = 0; i < arrays.length; i++) {
        const a = arrays[i];
        res.set(a, pad);
        pad += a.length;
    }
    return res;
}
export function checkOpts(defaults, opts) {
    if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')
        throw new Error('options should be object or undefined');
    const merged = Object.assign(defaults, opts);
    return merged;
}
/** For runtime check if class implements interface */
export class Hash {
}
/** Wraps hash function, creating an interface on top of it */
export function createHasher(hashCons) {
    const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
    const tmp = hashCons();
    hashC.outputLen = tmp.outputLen;
    hashC.blockLen = tmp.blockLen;
    hashC.create = () => hashCons();
    return hashC;
}
export function createOptHasher(hashCons) {
    const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();
    const tmp = hashCons({});
    hashC.outputLen = tmp.outputLen;
    hashC.blockLen = tmp.blockLen;
    hashC.create = (opts) => hashCons(opts);
    return hashC;
}
export function createXOFer(hashCons) {
    const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();
    const tmp = hashCons({});
    hashC.outputLen = tmp.outputLen;
    hashC.blockLen = tmp.blockLen;
    hashC.create = (opts) => hashCons(opts);
    return hashC;
}
export const wrapConstructor = createHasher;
export const wrapConstructorWithOpts = createOptHasher;
export const wrapXOFConstructorWithOpts = createXOFer;
/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */
export function randomBytes(bytesLength = 32) {
    if (crypto && typeof crypto.getRandomValues === 'function') {
        return crypto.getRandomValues(new Uint8Array(bytesLength));
    }
    // Legacy Node.js compatibility
    if (crypto && typeof crypto.randomBytes === 'function') {
        return Uint8Array.from(crypto.randomBytes(bytesLength));
    }
    throw new Error('crypto.getRandomValues must be defined');
}
//# sourceMappingURL=utils.js.mapimport { encode, encodeInto, objectToTokens, rfc8949EncodeOptions } from './lib/encode.js'
import { decode, decodeFirst, Tokeniser, tokensToObject } from './lib/decode.js'
import { Tagged } from './lib/tagged.js'
import { Token, Type } from './lib/token.js'

/**
 * Export the types that were present in the original manual cborg.d.ts
 * @typedef {import('./interface.js').TagDecodeControl} TagDecodeControl
 * @typedef {import('./interface.js').TagDecoder} TagDecoder
 * There was originally just `TypeEncoder` so don't break types by renaming or not exporting
 * @typedef {import('./interface.js').OptionalTypeEncoder} TypeEncoder
 * @typedef {import('./interface.js').DecodeOptions} DecodeOptions
 * @typedef {import('./interface.js').EncodeOptions} EncodeOptions
 */

export {
  decode,
  decodeFirst,
  Tokeniser as Tokenizer,
  tokensToObject,
  encode,
  encodeInto,
  objectToTokens,
  rfc8949EncodeOptions,
  Tagged,
  Token,
  Type
}
/* globals BigInt */

import { Token, Type } from './token.js'
import { decodeErrPrefix, assertEnoughData } from './common.js'

export const uintBoundaries = [24, 256, 65536, 4294967296, BigInt('18446744073709551616')]

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number}
 */
export function readUint8 (data, offset, options) {
  assertEnoughData(data, offset, 1)
  const value = data[offset]
  if (options.strict === true && value < uintBoundaries[0]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  return value
}

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number}
 */
export function readUint16 (data, offset, options) {
  assertEnoughData(data, offset, 2)
  const value = (data[offset] << 8) | data[offset + 1]
  if (options.strict === true && value < uintBoundaries[1]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  return value
}

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number}
 */
export function readUint32 (data, offset, options) {
  assertEnoughData(data, offset, 4)
  const value = (data[offset] * 16777216 /* 2 ** 24 */) + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]
  if (options.strict === true && value < uintBoundaries[2]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  return value
}

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number|bigint}
 */
export function readUint64 (data, offset, options) {
  // assume BigInt, convert back to Number if within safe range
  assertEnoughData(data, offset, 8)
  const hi = (data[offset] * 16777216 /* 2 ** 24 */) + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]
  const lo = (data[offset + 4] * 16777216 /* 2 ** 24 */) + (data[offset + 5] << 16) + (data[offset + 6] << 8) + data[offset + 7]
  const value = (BigInt(hi) << BigInt(32)) + BigInt(lo)
  if (options.strict === true && value < uintBoundaries[3]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  if (value <= Number.MAX_SAFE_INTEGER) {
    return Number(value)
  }
  if (options.allowBigInt === true) {
    return value
  }
  throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`)
}

/* not required thanks to quick[] list
const oneByteTokens = new Array(24).fill(0).map((v, i) => new Token(Type.uint, i, 1))
export function decodeUintCompact (data, pos, minor, options) {
  return oneByteTokens[minor]
}
*/

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint8 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint8(data, pos + 1, options), 2)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint16 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint16(data, pos + 1, options), 3)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint32 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint32(data, pos + 1, options), 5)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint64 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint64(data, pos + 1, options), 9)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeUint (writer, token) {
  return encodeUintValue(writer, 0, token.value)
}

/**
 * @param {ByteWriter} writer
 * @param {number} major
 * @param {number|bigint} uint
 */
export function encodeUintValue (writer, major, uint) {
  if (uint < uintBoundaries[0]) {
    const nuint = Number(uint)
    // pack into one byte, minor=0, additional=value
    writer.push([major | nuint])
  } else if (uint < uintBoundaries[1]) {
    const nuint = Number(uint)
    // pack into two byte, minor=0, additional=24
    writer.push([major | 24, nuint])
  } else if (uint < uintBoundaries[2]) {
    const nuint = Number(uint)
    // pack into three byte, minor=0, additional=25
    writer.push([major | 25, nuint >>> 8, nuint & 0xff])
  } else if (uint < uintBoundaries[3]) {
    const nuint = Number(uint)
    // pack into five byte, minor=0, additional=26
    writer.push([major | 26, (nuint >>> 24) & 0xff, (nuint >>> 16) & 0xff, (nuint >>> 8) & 0xff, nuint & 0xff])
  } else {
    const buint = BigInt(uint)
    if (buint < uintBoundaries[4]) {
      // pack into nine byte, minor=0, additional=27
      const set = [major | 27, 0, 0, 0, 0, 0, 0, 0]
      // simulate bitwise above 32 bits
      let lo = Number(buint & BigInt(0xffffffff))
      let hi = Number(buint >> BigInt(32) & BigInt(0xffffffff))
      set[8] = lo & 0xff
      lo = lo >> 8
      set[7] = lo & 0xff
      lo = lo >> 8
      set[6] = lo & 0xff
      lo = lo >> 8
      set[5] = lo & 0xff
      set[4] = hi & 0xff
      hi = hi >> 8
      set[3] = hi & 0xff
      hi = hi >> 8
      set[2] = hi & 0xff
      hi = hi >> 8
      set[1] = hi & 0xff
      writer.push(set)
    } else {
      throw new Error(`${decodeErrPrefix} encountered BigInt larger than allowable range`)
    }
  }
}

/**
 * @param {Token} token
 * @returns {number}
 */
encodeUint.encodedSize = function encodedSize (token) {
  return encodeUintValue.encodedSize(token.value)
}

/**
 * @param {number} uint
 * @returns {number}
 */
encodeUintValue.encodedSize = function encodedSize (uint) {
  if (uint < uintBoundaries[0]) {
    return 1
  }
  if (uint < uintBoundaries[1]) {
    return 2
  }
  if (uint < uintBoundaries[2]) {
    return 3
  }
  if (uint < uintBoundaries[3]) {
    return 5
  }
  return 9
}

/**
 * @param {Token} tok1
 * @param {Token} tok2
 * @returns {number}
 */
encodeUint.compareTokens = function compareTokens (tok1, tok2) {
  return tok1.value < tok2.value ? -1 : tok1.value > tok2.value ? 1 : 0
}
/* eslint-env es2020 */

import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import { decodeErrPrefix } from './common.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint8 (data, pos, _minor, options) {
  return new Token(Type.negint, -1 - uint.readUint8(data, pos + 1, options), 2)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint16 (data, pos, _minor, options) {
  return new Token(Type.negint, -1 - uint.readUint16(data, pos + 1, options), 3)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint32 (data, pos, _minor, options) {
  return new Token(Type.negint, -1 - uint.readUint32(data, pos + 1, options), 5)
}

const neg1b = BigInt(-1)
const pos1b = BigInt(1)

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint64 (data, pos, _minor, options) {
  const int = uint.readUint64(data, pos + 1, options)
  if (typeof int !== 'bigint') {
    const value = -1 - int
    if (value >= Number.MIN_SAFE_INTEGER) {
      return new Token(Type.negint, value, 9)
    }
  }
  if (options.allowBigInt !== true) {
    throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`)
  }
  return new Token(Type.negint, neg1b - BigInt(int), 9)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeNegint (writer, token) {
  const negint = token.value
  const unsigned = (typeof negint === 'bigint' ? (negint * neg1b - pos1b) : (negint * -1 - 1))
  uint.encodeUintValue(writer, token.type.majorEncoded, unsigned)
}

/**
 * @param {Token} token
 * @returns {number}
 */
encodeNegint.encodedSize = function encodedSize (token) {
  const negint = token.value
  const unsigned = (typeof negint === 'bigint' ? (negint * neg1b - pos1b) : (negint * -1 - 1))
  // handled by quickEncode, we shouldn't get here but it's included for completeness
  if (unsigned < uint.uintBoundaries[0]) {
    return 1
  }
  if (unsigned < uint.uintBoundaries[1]) {
    return 2
  }
  if (unsigned < uint.uintBoundaries[2]) {
    return 3
  }
  if (unsigned < uint.uintBoundaries[3]) {
    return 5
  }
  return 9
}

/**
 * @param {Token} tok1
 * @param {Token} tok2
 * @returns {number}
 */
encodeNegint.compareTokens = function compareTokens (tok1, tok2) {
  // opposite of the uint comparison since we store the uint version in bytes
  return tok1.value < tok2.value ? 1 : tok1.value > tok2.value ? -1 : 0
}
import { Token, Type } from './token.js'
import { assertEnoughData, decodeErrPrefix } from './common.js'
import * as uint from './0uint.js'
import { compare, fromString } from './byte-utils.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} prefix
 * @param {number} length
 * @returns {Token}
 */
function toToken (data, pos, prefix, length) {
  assertEnoughData(data, pos, prefix + length)
  const buf = data.slice(pos + prefix, pos + prefix + length)
  return new Token(Type.bytes, buf, prefix + length)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeBytesCompact (data, pos, minor, _options) {
  return toToken(data, pos, 1, minor)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer bytes lengths not supported`)
  }
  return toToken(data, pos, 9, l)
}

/**
 * `encodedBytes` allows for caching when we do a byte version of a string
 * for key sorting purposes
 * @param {Token} token
 * @returns {Uint8Array}
 */
function tokenBytes (token) {
  if (token.encodedBytes === undefined) {
    token.encodedBytes = Type.equals(token.type, Type.string) ? fromString(token.value) : token.value
  }
  // @ts-ignore c'mon
  return token.encodedBytes
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeBytes (writer, token) {
  const bytes = tokenBytes(token)
  uint.encodeUintValue(writer, token.type.majorEncoded, bytes.length)
  writer.push(bytes)
}

/**
 * @param {Token} token
 * @returns {number}
 */
encodeBytes.encodedSize = function encodedSize (token) {
  const bytes = tokenBytes(token)
  return uint.encodeUintValue.encodedSize(bytes.length) + bytes.length
}

/**
 * @param {Token} tok1
 * @param {Token} tok2
 * @returns {number}
 */
encodeBytes.compareTokens = function compareTokens (tok1, tok2) {
  return compareBytes(tokenBytes(tok1), tokenBytes(tok2))
}

/**
 * @param {Uint8Array} b1
 * @param {Uint8Array} b2
 * @returns {number}
 */
export function compareBytes (b1, b2) {
  return b1.length < b2.length ? -1 : b1.length > b2.length ? 1 : compare(b1, b2)
}
import { Token, Type } from './token.js'
import { assertEnoughData, decodeErrPrefix } from './common.js'
import * as uint from './0uint.js'
import { encodeBytes } from './2bytes.js'

const textDecoder = new TextDecoder()

// Threshold for ASCII fast-path vs TextDecoder. Short ASCII strings (common for
// map keys) are faster to decode with a simple loop than TextDecoder overhead.
const ASCII_THRESHOLD = 32

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * Decode UTF-8 bytes to string. For short ASCII strings (common case for map keys),
 * a simple loop is faster than TextDecoder.
 * @param {Uint8Array} bytes
 * @param {number} start
 * @param {number} end
 * @returns {string}
 */
function toStr (bytes, start, end) {
  const len = end - start
  if (len < ASCII_THRESHOLD) {
    let str = ''
    for (let i = start; i < end; i++) {
      const c = bytes[i]
      if (c & 0x80) { // non-ASCII, fall back to TextDecoder
        return textDecoder.decode(bytes.subarray(start, end))
      }
      str += String.fromCharCode(c)
    }
    return str
  }
  return textDecoder.decode(bytes.subarray(start, end))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} prefix
 * @param {number} length
 * @param {DecodeOptions} options
 * @returns {Token}
 */
function toToken (data, pos, prefix, length, options) {
  const totLength = prefix + length
  assertEnoughData(data, pos, totLength)
  const tok = new Token(Type.string, toStr(data, pos + prefix, pos + totLength), totLength)
  if (options.retainStringBytes === true) {
    tok.byteValue = data.slice(pos + prefix, pos + totLength)
  }
  return tok
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeStringCompact (data, pos, minor, options) {
  return toToken(data, pos, 1, minor, options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options), options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options), options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options), options)
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer string lengths not supported`)
  }
  return toToken(data, pos, 9, l, options)
}

export const encodeString = encodeBytes
import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import { decodeErrPrefix } from './common.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} prefix
 * @param {number} length
 * @returns {Token}
 */
function toToken (_data, _pos, prefix, length) {
  return new Token(Type.array, length, prefix)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeArrayCompact (data, pos, minor, _options) {
  return toToken(data, pos, 1, minor)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer array lengths not supported`)
  }
  return toToken(data, pos, 9, l)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArrayIndefinite (data, pos, _minor, options) {
  if (options.allowIndefinite === false) {
    throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)
  }
  return toToken(data, pos, 1, Infinity)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeArray (writer, token) {
  uint.encodeUintValue(writer, Type.array.majorEncoded, token.value)
}

// using an array as a map key, are you sure about this? we can only sort
// by map length here, it's up to the encoder to decide to look deeper
encodeArray.compareTokens = uint.encodeUint.compareTokens

/**
 * @param {Token} token
 * @returns {number}
 */
encodeArray.encodedSize = function encodedSize (token) {
  return uint.encodeUintValue.encodedSize(token.value)
}
import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import { decodeErrPrefix } from './common.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} prefix
 * @param {number} length
 * @returns {Token}
 */
function toToken (_data, _pos, prefix, length) {
  return new Token(Type.map, length, prefix)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeMapCompact (data, pos, minor, _options) {
  return toToken(data, pos, 1, minor)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer map lengths not supported`)
  }
  return toToken(data, pos, 9, l)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMapIndefinite (data, pos, _minor, options) {
  if (options.allowIndefinite === false) {
    throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)
  }
  return toToken(data, pos, 1, Infinity)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeMap (writer, token) {
  uint.encodeUintValue(writer, Type.map.majorEncoded, token.value)
}

// using a map as a map key, are you sure about this? we can only sort
// by map length here, it's up to the encoder to decide to look deeper
encodeMap.compareTokens = uint.encodeUint.compareTokens

/**
 * @param {Token} token
 * @returns {number}
 */
encodeMap.encodedSize = function encodedSize (token) {
  return uint.encodeUintValue.encodedSize(token.value)
}
import { Token, Type } from './token.js'
import * as uint from './0uint.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeTagCompact (_data, _pos, minor, _options) {
  return new Token(Type.tag, minor, 1)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag8 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint8(data, pos + 1, options), 2)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag16 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint16(data, pos + 1, options), 3)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag32 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint32(data, pos + 1, options), 5)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag64 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint64(data, pos + 1, options), 9)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeTag (writer, token) {
  uint.encodeUintValue(writer, Type.tag.majorEncoded, token.value)
}

encodeTag.compareTokens = uint.encodeUint.compareTokens

/**
 * @param {Token} token
 * @returns {number}
 */
encodeTag.encodedSize = function encodedSize (token) {
  return uint.encodeUintValue.encodedSize(token.value)
}
// TODO: shift some of the bytes logic to bytes-utils so we can use Buffer
// where possible

import { Token, Type } from './token.js'
import { decodeErrPrefix } from './common.js'
import { encodeUint } from './0uint.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 * @typedef {import('../interface.js').EncodeOptions} EncodeOptions
 */

export const MINOR_FALSE = 20
export const MINOR_TRUE = 21
export const MINOR_NULL = 22
export const MINOR_UNDEFINED = 23

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUndefined (_data, _pos, _minor, options) {
  if (options.allowUndefined === false) {
    throw new Error(`${decodeErrPrefix} undefined values are not supported`)
  } else if (options.coerceUndefinedToNull === true) {
    return new Token(Type.null, null, 1)
  }
  return new Token(Type.undefined, undefined, 1)
}

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBreak (_data, _pos, _minor, options) {
  if (options.allowIndefinite === false) {
    throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)
  }
  return new Token(Type.break, undefined, 1)
}

/**
 * @param {number} value
 * @param {number} bytes
 * @param {DecodeOptions} options
 * @returns {Token}
 */
function createToken (value, bytes, options) {
  if (options) {
    if (options.allowNaN === false && Number.isNaN(value)) {
      throw new Error(`${decodeErrPrefix} NaN values are not supported`)
    }
    if (options.allowInfinity === false && (value === Infinity || value === -Infinity)) {
      throw new Error(`${decodeErrPrefix} Infinity values are not supported`)
    }
  }
  return new Token(Type.float, value, bytes)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeFloat16 (data, pos, _minor, options) {
  return createToken(readFloat16(data, pos + 1), 3, options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeFloat32 (data, pos, _minor, options) {
  return createToken(readFloat32(data, pos + 1), 5, options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeFloat64 (data, pos, _minor, options) {
  return createToken(readFloat64(data, pos + 1), 9, options)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 * @param {EncodeOptions} options
 */
export function encodeFloat (writer, token, options) {
  const float = token.value

  if (float === false) {
    writer.push([Type.float.majorEncoded | MINOR_FALSE])
  } else if (float === true) {
    writer.push([Type.float.majorEncoded | MINOR_TRUE])
  } else if (float === null) {
    writer.push([Type.float.majorEncoded | MINOR_NULL])
  } else if (float === undefined) {
    writer.push([Type.float.majorEncoded | MINOR_UNDEFINED])
  } else {
    let decoded
    let success = false
    if (!options || options.float64 !== true) {
      encodeFloat16(float)
      decoded = readFloat16(ui8a, 1)
      if (float === decoded || Number.isNaN(float)) {
        ui8a[0] = 0xf9
        writer.push(ui8a.slice(0, 3))
        success = true
      } else {
        encodeFloat32(float)
        decoded = readFloat32(ui8a, 1)
        if (float === decoded) {
          ui8a[0] = 0xfa
          writer.push(ui8a.slice(0, 5))
          success = true
        }
      }
    }
    if (!success) {
      encodeFloat64(float)
      decoded = readFloat64(ui8a, 1)
      ui8a[0] = 0xfb
      writer.push(ui8a.slice(0, 9))
    }
  }
}

/**
 * @param {Token} token
 * @param {EncodeOptions} options
 * @returns {number}
 */
encodeFloat.encodedSize = function encodedSize (token, options) {
  const float = token.value

  if (float === false || float === true || float === null || float === undefined) {
    return 1
  }

  if (!options || options.float64 !== true) {
    encodeFloat16(float)
    let decoded = readFloat16(ui8a, 1)
    if (float === decoded || Number.isNaN(float)) {
      return 3
    }
    encodeFloat32(float)
    decoded = readFloat32(ui8a, 1)
    if (float === decoded) {
      return 5
    }
  }
  return 9
}

const buffer = new ArrayBuffer(9)
const dataView = new DataView(buffer, 1)
const ui8a = new Uint8Array(buffer, 0)

/**
 * @param {number} inp
 */
function encodeFloat16 (inp) {
  if (inp === Infinity) {
    dataView.setUint16(0, 0x7c00, false)
  } else if (inp === -Infinity) {
    dataView.setUint16(0, 0xfc00, false)
  } else if (Number.isNaN(inp)) {
    dataView.setUint16(0, 0x7e00, false)
  } else {
    dataView.setFloat32(0, inp)
    const valu32 = dataView.getUint32(0)
    const exponent = (valu32 & 0x7f800000) >> 23
    const mantissa = valu32 & 0x7fffff

    if (exponent === 0xff) {
      // too big, Infinity, but this should be hard (impossible?) to trigger
      dataView.setUint16(0, 0x7c00, false)
    } else if (exponent === 0x00) {
      // 0.0, -0.0 and subnormals, shouldn't be possible to get here because 0.0 should be counted as an int
      // Use valu32 for sign bit since bitwise ops on floats lose -0 sign
      dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | (mantissa >> 13), false)
    } else { // standard numbers
      // chunks of logic here borrowed from https://github.com/PJK/libcbor/blob/c78f437182533e3efa8d963ff4b945bb635c2284/src/cbor/encoding.c#L127
      const logicalExponent = exponent - 127
      // Now we know that 2^exponent <= 0 logically
      if (logicalExponent < -24) {
        /* No unambiguous representation exists, this float is not a half float
          and is too small to be represented using a half, round off to zero.
          Consistent with the reference implementation. */
        // should be difficult (impossible?) to get here in JS
        dataView.setUint16(0, 0)
      } else if (logicalExponent < -14) {
        /* Offset the remaining decimal places by shifting the significand, the
          value is lost. This is an implementation decision that works around the
          absence of standard half-float in the language. */
        dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | /* sign bit */ (1 << (24 + logicalExponent)), false)
      } else {
        dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | ((logicalExponent + 15) << 10) | (mantissa >> 13), false)
      }
    }
  }
}

/**
 * @param {Uint8Array} ui8a
 * @param {number} pos
 * @returns {number}
 */
function readFloat16 (ui8a, pos) {
  if (ui8a.length - pos < 2) {
    throw new Error(`${decodeErrPrefix} not enough data for float16`)
  }

  const half = (ui8a[pos] << 8) + ui8a[pos + 1]
  if (half === 0x7c00) {
    return Infinity
  }
  if (half === 0xfc00) {
    return -Infinity
  }
  if (half === 0x7e00) {
    return NaN
  }
  const exp = (half >> 10) & 0x1f
  const mant = half & 0x3ff
  let val
  if (exp === 0) {
    val = mant * (2 ** -24)
  } else if (exp !== 31) {
    val = (mant + 1024) * (2 ** (exp - 25))
  } else {
    // may not be possible to get here
    val = mant === 0 ? Infinity : NaN
  }
  return (half & 0x8000) ? -val : val
}

/**
 * @param {number} inp
 */
function encodeFloat32 (inp) {
  dataView.setFloat32(0, inp, false)
}

/**
 * @param {Uint8Array} ui8a
 * @param {number} pos
 * @returns {number}
 */
function readFloat32 (ui8a, pos) {
  if (ui8a.length - pos < 4) {
    throw new Error(`${decodeErrPrefix} not enough data for float32`)
  }
  const offset = (ui8a.byteOffset || 0) + pos
  return new DataView(ui8a.buffer, offset, 4).getFloat32(0, false)
}

/**
 * @param {number} inp
 */
function encodeFloat64 (inp) {
  dataView.setFloat64(0, inp, false)
}

/**
 * @param {Uint8Array} ui8a
 * @param {number} pos
 * @returns {number}
 */
function readFloat64 (ui8a, pos) {
  if (ui8a.length - pos < 8) {
    throw new Error(`${decodeErrPrefix} not enough data for float64`)
  }
  const offset = (ui8a.byteOffset || 0) + pos
  return new DataView(ui8a.buffer, offset, 8).getFloat64(0, false)
}

/**
 * @param {Token} _tok1
 * @param {Token} _tok2
 * @returns {number}
 */
encodeFloat.compareTokens = encodeUint.compareTokens
/*
encodeFloat.compareTokens = function compareTokens (_tok1, _tok2) {
  return _tok1
  throw new Error(`${encodeErrPrefix} cannot use floats as map keys`)
}
*/
/**
 * Bl is a list of byte chunks, similar to https://github.com/rvagg/bl but for
 * writing rather than reading.
 * A Bl object accepts set() operations for individual bytes and copyTo() for
 * inserting byte arrays. These write operations don't automatically increment
 * the internal cursor so its "length" won't be changed. Instead, increment()
 * must be called to extend its length to cover the inserted data.
 * The toBytes() call will convert all internal memory to a single Uint8Array of
 * the correct length, truncating any data that is stored but hasn't been
 * included by an increment().
 * get() can retrieve a single byte.
 * All operations (except toBytes()) take an "offset" argument that will perform
 * the write at the offset _from the current cursor_. For most operations this
 * will be `0` to write at the current cursor position but it can be ahead of
 * the current cursor. Negative offsets probably work but are untested.
 */

// TODO: ipjs doesn't support this, only for test files: https://github.com/mikeal/ipjs/blob/master/src/package/testFile.js#L39
import { alloc, concat, slice } from './byte-utils.js'

// the ts-ignores in this file are almost all for the `Uint8Array|number[]` duality that exists
// for perf reasons. Consider better approaches to this or removing it entirely, it is quite
// risky because of some assumptions about small chunks === number[] and everything else === Uint8Array.

const defaultChunkSize = 256

export class Bl {
  /**
   * @param {number} [chunkSize]
   */
  constructor (chunkSize = defaultChunkSize) {
    this.chunkSize = chunkSize
    /** @type {number} */
    this.cursor = 0
    /** @type {number} */
    this.maxCursor = -1
    /** @type {(Uint8Array|number[])[]} */
    this.chunks = []
    // keep the first chunk around if we can to save allocations for future encodes
    /** @type {Uint8Array|number[]|null} */
    this._initReuseChunk = null
  }

  reset () {
    this.cursor = 0
    this.maxCursor = -1
    if (this.chunks.length) {
      this.chunks = []
    }
    if (this._initReuseChunk !== null) {
      this.chunks.push(this._initReuseChunk)
      this.maxCursor = this._initReuseChunk.length - 1
    }
  }

  /**
   * @param {Uint8Array|number[]} bytes
   */
  push (bytes) {
    let topChunk = this.chunks[this.chunks.length - 1]
    const newMax = this.cursor + bytes.length
    if (newMax <= this.maxCursor + 1) {
      // we have at least one chunk and we can fit these bytes into that chunk
      const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1
      // @ts-ignore
      topChunk.set(bytes, chunkPos)
    } else {
      // can't fit it in
      if (topChunk) {
        // trip the last chunk to `cursor` if we need to
        const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1
        if (chunkPos < topChunk.length) {
          // @ts-ignore
          this.chunks[this.chunks.length - 1] = topChunk.subarray(0, chunkPos)
          this.maxCursor = this.cursor - 1
        }
      }
      if (bytes.length < 64 && bytes.length < this.chunkSize) {
        // make a new chunk and copy the new one into it
        topChunk = alloc(this.chunkSize)
        this.chunks.push(topChunk)
        this.maxCursor += topChunk.length
        if (this._initReuseChunk === null) {
          this._initReuseChunk = topChunk
        }
        // @ts-ignore
        topChunk.set(bytes, 0)
      } else {
        // push the new bytes in as its own chunk
        this.chunks.push(bytes)
        this.maxCursor += bytes.length
      }
    }
    this.cursor += bytes.length
  }

  /**
   * @param {boolean} [reset]
   * @returns {Uint8Array}
   */
  toBytes (reset = false) {
    let byts
    if (this.chunks.length === 1) {
      const chunk = this.chunks[0]
      if (reset && this.cursor > chunk.length / 2) {
        // @ts-ignore
        byts = this.cursor === chunk.length ? chunk : chunk.subarray(0, this.cursor)
        this._initReuseChunk = null
        this.chunks = []
      } else {
        // @ts-ignore
        byts = slice(chunk, 0, this.cursor)
      }
    } else {
      // @ts-ignore
      byts = concat(this.chunks, this.cursor)
    }
    if (reset) {
      this.reset()
    }
    return byts
  }
}

/**
 * U8Bl is a buffer list that writes directly to a user-provided Uint8Array.
 * It provides the same interface as Bl but writes to a fixed destination.
 */
export class U8Bl {
  /**
   * @param {Uint8Array} dest
   */
  constructor (dest) {
    this.dest = dest
    /** @type {number} */
    this.cursor = 0
    // chunks is for interface compatibility with Bl - encode.js checks chunks.length
    // as a sanity check for pre-calculated sizes. For U8Bl this is always [dest].
    /** @type {Uint8Array[]} */
    this.chunks = [dest]
  }

  reset () {
    this.cursor = 0
  }

  /**
   * @param {Uint8Array|number[]} bytes
   */
  push (bytes) {
    if (this.cursor + bytes.length > this.dest.length) {
      throw new Error('write out of bounds, destination buffer is too small')
    }
    this.dest.set(bytes, this.cursor)
    this.cursor += bytes.length
  }

  /**
   * @param {boolean} [reset]
   * @returns {Uint8Array}
   */
  toBytes (reset = false) {
    const byts = this.dest.subarray(0, this.cursor)
    if (reset) {
      this.reset()
    }
    return byts
  }
}
// Use Uint8Array directly in the browser, use Buffer in Node.js but don't
// speak its name directly to avoid bundlers pulling in the `Buffer` polyfill

// @ts-ignore
export const useBuffer = globalThis.process &&
  // @ts-ignore
  !globalThis.process.browser &&
  // @ts-ignore
  globalThis.Buffer &&
  // @ts-ignore
  typeof globalThis.Buffer.isBuffer === 'function'

const textEncoder = new TextEncoder()

/**
 * @param {Uint8Array} buf
 * @returns {boolean}
 */
function isBuffer (buf) {
  // @ts-ignore
  return useBuffer && globalThis.Buffer.isBuffer(buf)
}

/**
 * @param {Uint8Array|number[]} buf
 * @returns {Uint8Array}
 */
export function asU8A (buf) {
  if (!(buf instanceof Uint8Array)) {
    return Uint8Array.from(buf)
  }
  return isBuffer(buf) ? new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength) : buf
}

// Threshold for manual UTF-8 encoding vs native methods.
// Node.js Buffer.from: crossover ~24 chars
// Browser TextEncoder: crossover ~200 chars
const FROM_STRING_THRESHOLD_BUFFER = 24
const FROM_STRING_THRESHOLD_TEXTENCODER = 200

export const fromString = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {string} string
     */
    (string) => {
      return string.length >= FROM_STRING_THRESHOLD_BUFFER
        ? // eslint-disable-line operator-linebreak
      // @ts-ignore
        globalThis.Buffer.from(string)
        : utf8ToBytes(string)
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {string} string
     */
    (string) => {
      return string.length >= FROM_STRING_THRESHOLD_TEXTENCODER ? textEncoder.encode(string) : utf8ToBytes(string)
    }

/**
 * Buffer variant not fast enough for what we need
 * @param {number[]} arr
 * @returns {Uint8Array}
 */
export const fromArray = (arr) => {
  return Uint8Array.from(arr)
}

export const slice = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} bytes
     * @param {number} start
     * @param {number} end
     */
    // Buffer.slice() returns a view, not a copy, so we need special handling
    (bytes, start, end) => {
      if (isBuffer(bytes)) {
        return new Uint8Array(bytes.subarray(start, end))
      }
      return bytes.slice(start, end)
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} bytes
     * @param {number} start
     * @param {number} end
     */
    (bytes, start, end) => {
      return bytes.slice(start, end)
    }

export const concat = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array[]} chunks
     * @param {number} length
     * @returns {Uint8Array}
     */
    (chunks, length) => {
      // might get a stray plain Array here
      chunks = chunks.map((c) => c instanceof Uint8Array
        ? c
        : // eslint-disable-line operator-linebreak
        // @ts-ignore
        globalThis.Buffer.from(c))
      // @ts-ignore
      return asU8A(globalThis.Buffer.concat(chunks, length))
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array[]} chunks
     * @param {number} length
     * @returns {Uint8Array}
     */
    (chunks, length) => {
      const out = new Uint8Array(length)
      let off = 0
      for (let b of chunks) {
        if (off + b.length > out.length) {
          // final chunk that's bigger than we need
          b = b.subarray(0, out.length - off)
        }
        out.set(b, off)
        off += b.length
      }
      return out
    }

export const alloc = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {number} size
     * @returns {Uint8Array}
     */
    (size) => {
      // we always write over the contents we expose so this should be safe
      // @ts-ignore
      return globalThis.Buffer.allocUnsafe(size)
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {number} size
     * @returns {Uint8Array}
     */
    (size) => {
      return new Uint8Array(size)
    }

export const toHex = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} d
     * @returns {string}
     */
    (d) => {
      if (typeof d === 'string') {
        return d
      }
      // @ts-ignore
      return globalThis.Buffer.from(toBytes(d)).toString('hex')
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} d
     * @returns {string}
     */
    (d) => {
      if (typeof d === 'string') {
        return d
      }
      // @ts-ignore not smart enough to figure this out
      return Array.prototype.reduce.call(toBytes(d), (p, c) => `${p}${c.toString(16).padStart(2, '0')}`, '')
    }

export const fromHex = useBuffer
  ? // eslint-disable-line operator-linebreak
  /**
   * @param {string|Uint8Array} hex
   * @returns {Uint8Array}
   */
    (hex) => {
      if (hex instanceof Uint8Array) {
        return hex
      }
      // @ts-ignore
      return globalThis.Buffer.from(hex, 'hex')
    }
  : // eslint-disable-line operator-linebreak
  /**
   * @param {string|Uint8Array} hex
   * @returns {Uint8Array}
   */
    (hex) => {
      if (hex instanceof Uint8Array) {
        return hex
      }
      if (!hex.length) {
        return new Uint8Array(0)
      }
      return new Uint8Array(hex.split('')
        .map((/** @type {string} */ c, /** @type {number} */ i, /** @type {string[]} */ d) => i % 2 === 0 ? `0x${c}${d[i + 1]}` : '')
        .filter(Boolean)
        .map((/** @type {string} */ e) => parseInt(e, 16)))
    }

/**
 * @param {Uint8Array|ArrayBuffer|ArrayBufferView} obj
 * @returns {Uint8Array}
 */
function toBytes (obj) {
  if (obj instanceof Uint8Array && obj.constructor.name === 'Uint8Array') {
    return obj
  }
  if (obj instanceof ArrayBuffer) {
    return new Uint8Array(obj)
  }
  if (ArrayBuffer.isView(obj)) {
    return new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength)
  }
  throw new Error('Unknown type, must be binary type')
}

/**
 * @param {Uint8Array} b1
 * @param {Uint8Array} b2
 * @returns {number}
 */
export function compare (b1, b2) {
  if (isBuffer(b1) && isBuffer(b2)) {
    // probably not possible to get here in the current API
    // @ts-ignore Buffer
    return b1.compare(b2)
  }
  for (let i = 0; i < b1.length; i++) {
    if (b1[i] === b2[i]) {
      continue
    }
    return b1[i] < b2[i] ? -1 : 1
  }
  return 0
}

// The below code is taken from https://github.com/google/closure-library/blob/8598d87242af59aac233270742c8984e2b2bdbe0/closure/goog/crypt/crypt.js#L117-L143
// Licensed Apache-2.0.

/**
 * @param {string} str
 * @returns {number[]}
 */
function utf8ToBytes (str) {
  const out = []
  let p = 0
  for (let i = 0; i < str.length; i++) {
    let c = str.charCodeAt(i)
    if (c < 128) {
      out[p++] = c
    } else if (c < 2048) {
      out[p++] = (c >> 6) | 192
      out[p++] = (c & 63) | 128
    } else if (
      ((c & 0xFC00) === 0xD800) && (i + 1) < str.length &&
      ((str.charCodeAt(i + 1) & 0xFC00) === 0xDC00)) {
      // Surrogate Pair
      c = 0x10000 + ((c & 0x03FF) << 10) + (str.charCodeAt(++i) & 0x03FF)
      out[p++] = (c >> 18) | 240
      out[p++] = ((c >> 12) & 63) | 128
      out[p++] = ((c >> 6) & 63) | 128
      out[p++] = (c & 63) | 128
    } else {
      if ((c >= 0xD800) && (c <= 0xDFFF)) {
        c = 0xFFFD // Unpaired Surrogate
      }
      out[p++] = (c >> 12) | 224
      out[p++] = ((c >> 6) & 63) | 128
      out[p++] = (c & 63) | 128
    }
  }
  return out
}

// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
const MAX_ARGUMENTS_LENGTH = 0x1000

/**
 * @param {number[]} codePoints
 * @returns {string}
 */
export function decodeCodePointsArray (codePoints) {
  const len = codePoints.length
  if (len <= MAX_ARGUMENTS_LENGTH) {
    return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  }
  // Decode in chunks to avoid "call stack size exceeded".
  let res = ''
  let i = 0
  while (i < len) {
    res += String.fromCharCode.apply(
      String,
      codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
    )
  }
  return res
}
const decodeErrPrefix = 'CBOR decode error:'
const encodeErrPrefix = 'CBOR encode error:'

const uintMinorPrefixBytes = []
uintMinorPrefixBytes[23] = 1
uintMinorPrefixBytes[24] = 2
uintMinorPrefixBytes[25] = 3
uintMinorPrefixBytes[26] = 5
uintMinorPrefixBytes[27] = 9

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} need
 */
function assertEnoughData (data, pos, need) {
  if (data.length - pos < need) {
    throw new Error(`${decodeErrPrefix} not enough data for type`)
  }
}

export {
  decodeErrPrefix,
  encodeErrPrefix,
  uintMinorPrefixBytes,
  assertEnoughData
}
import { decodeErrPrefix } from './common.js'
import { Type } from './token.js'
import { jump, quick } from './jump.js'
import { asU8A } from './byte-utils.js'

/**
 * @typedef {import('./token.js').Token} Token
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 * @typedef {import('../interface.js').DecodeTokenizer} DecodeTokenizer
 * @typedef {import('../interface.js').TagDecodeControl} TagDecodeControl
 */

const defaultDecodeOptions = {
  strict: false,
  allowIndefinite: true,
  allowUndefined: true,
  allowBigInt: true
}

/**
 * @implements {DecodeTokenizer}
 */
class Tokeniser {
  /**
   * @param {Uint8Array} data
   * @param {DecodeOptions} options
   */
  constructor (data, options = {}) {
    this._pos = 0
    this.data = data
    this.options = options
  }

  pos () {
    return this._pos
  }

  done () {
    return this._pos >= this.data.length
  }

  next () {
    const byt = this.data[this._pos]
    let token = quick[byt]
    if (token === undefined) {
      const decoder = jump[byt]
      // if we're here then there's something wrong with our jump or quick lists!
      if (!decoder) {
        throw new Error(`${decodeErrPrefix} no decoder for major type ${byt >>> 5} (byte 0x${byt.toString(16).padStart(2, '0')})`)
      }
      const minor = byt & 31
      token = decoder(this.data, this._pos, minor, this.options)
    }
    // @ts-ignore we get to assume encodedLength is set (crossing fingers slightly)
    this._pos += token.encodedLength
    return token
  }
}

const DONE = Symbol.for('DONE')
const BREAK = Symbol.for('BREAK')

/**
 * @param {Token} token
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {any|BREAK|DONE}
 */
function tokenToArray (token, tokeniser, options) {
  const arr = []
  for (let i = 0; i < token.value; i++) {
    const value = tokensToObject(tokeniser, options)
    if (value === BREAK) {
      if (token.value === Infinity) {
        // normal end to indefinite length array
        break
      }
      throw new Error(`${decodeErrPrefix} got unexpected break to lengthed array`)
    }
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} found array but not enough entries (got ${i}, expected ${token.value})`)
    }
    arr[i] = value
  }
  return arr
}

/**
 * @param {Token} token
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {any|BREAK|DONE}
 */
function tokenToMap (token, tokeniser, options) {
  const useMaps = options.useMaps === true
  const rejectDuplicateMapKeys = options.rejectDuplicateMapKeys === true
  const obj = useMaps ? undefined : {}
  const m = useMaps ? new Map() : undefined
  for (let i = 0; i < token.value; i++) {
    const key = tokensToObject(tokeniser, options)
    if (key === BREAK) {
      if (token.value === Infinity) {
        // normal end to indefinite length map
        break
      }
      throw new Error(`${decodeErrPrefix} got unexpected break to lengthed map`)
    }
    if (key === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no key], expected ${token.value})`)
    }
    if (!useMaps && typeof key !== 'string') {
      throw new Error(`${decodeErrPrefix} non-string keys not supported (got ${typeof key})`)
    }
    if (rejectDuplicateMapKeys) {
      // @ts-ignore
      if ((useMaps && m.has(key)) || (!useMaps && Object.hasOwn(obj, key))) {
        throw new Error(`${decodeErrPrefix} found repeat map key "${key}"`)
      }
    }
    const value = tokensToObject(tokeniser, options)
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no value], expected ${token.value})`)
    }
    if (useMaps) {
      // @ts-ignore TODO reconsider this .. maybe needs to be strict about key types
      m.set(key, value)
    } else {
      // @ts-ignore TODO reconsider this .. maybe needs to be strict about key types
      obj[key] = value
    }
  }
  // @ts-ignore c'mon man
  return useMaps ? m : obj
}

/**
 * Generator that yields [key, value] entries from a CBOR map token.
 * Used by tag decoders that need to preserve key types (e.g., Tag 259 Map).
 * @param {Token} token - The map token
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {Generator<[any, any], void, unknown>}
 */
function * tokenToMapEntries (token, tokeniser, options) {
  for (let i = 0; i < token.value; i++) {
    const key = tokensToObject(tokeniser, options)
    if (key === BREAK) {
      if (token.value === Infinity) {
        // normal end to indefinite length map
        break
      }
      throw new Error(`${decodeErrPrefix} got unexpected break to lengthed map`)
    }
    if (key === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no key], expected ${token.value})`)
    }
    const value = tokensToObject(tokeniser, options)
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no value], expected ${token.value})`)
    }
    yield [key, value]
  }
}

/**
 * Creates a TagDecodeControl object for tag decoders.
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {TagDecodeControl}
 */
function createTagDecodeControl (tokeniser, options) {
  let called = false

  /**
   * @type {TagDecodeControl}
   */
  const decode = function () {
    if (called) {
      throw new Error(`${decodeErrPrefix} tag decode() may only be called once`)
    }
    called = true
    const value = tokensToObject(tokeniser, options)
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} tag content missing`)
    }
    if (value === BREAK) {
      throw new Error(`${decodeErrPrefix} got unexpected break in tag content`)
    }
    return value
  }

  decode.entries = function () {
    if (called) {
      throw new Error(`${decodeErrPrefix} tag decode() may only be called once`)
    }
    called = true

    // Get the next token and ensure it's a map
    const token = tokeniser.next()
    if (!Type.equals(token.type, Type.map)) {
      throw new Error(`${decodeErrPrefix} entries() requires map content, got ${token.type.name}`)
    }

    // Collect all entries into an array (ensures full content consumption)
    const entries = []
    for (const entry of tokenToMapEntries(token, tokeniser, options)) {
      entries.push(entry)
    }
    return entries
  }

  // For internal tracking
  Object.defineProperty(decode, '_called', {
    get () { return called },
    enumerable: false
  })

  return decode
}

/**
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {any|BREAK|DONE}
 */
function tokensToObject (tokeniser, options) {
  // should we support array as an argument?
  // check for tokenIter[Symbol.iterator] and replace tokenIter with what that returns?
  if (tokeniser.done()) {
    return DONE
  }

  const token = tokeniser.next()

  if (Type.equals(token.type, Type.break)) {
    return BREAK
  }

  if (token.type.terminal) {
    return token.value
  }

  if (Type.equals(token.type, Type.array)) {
    return tokenToArray(token, tokeniser, options)
  }

  if (Type.equals(token.type, Type.map)) {
    return tokenToMap(token, tokeniser, options)
  }

  if (Type.equals(token.type, Type.tag)) {
    if (options.tags && typeof options.tags[token.value] === 'function') {
      const decodeControl = createTagDecodeControl(tokeniser, options)
      const result = options.tags[token.value](decodeControl)
      if (!decodeControl._called) {
        throw new Error(`${decodeErrPrefix} tag decoder must call decode() or entries()`)
      }
      return result
    }
    throw new Error(`${decodeErrPrefix} tag not supported (${token.value})`)
  }
  throw new Error('unsupported')
}

/**
 * @param {Uint8Array} data
 * @param {DecodeOptions} [options]
 * @returns {[any, Uint8Array]}
 */
function decodeFirst (data, options) {
  if (!(data instanceof Uint8Array)) {
    throw new Error(`${decodeErrPrefix} data to decode must be a Uint8Array`)
  }
  options = Object.assign({}, defaultDecodeOptions, options)
  // Convert Buffer to plain Uint8Array for faster slicing in decode path
  const u8aData = asU8A(data)
  const tokeniser = options.tokenizer || new Tokeniser(u8aData, options)
  const decoded = tokensToObject(tokeniser, options)
  if (decoded === DONE) {
    throw new Error(`${decodeErrPrefix} did not find any content to decode`)
  }
  if (decoded === BREAK) {
    throw new Error(`${decodeErrPrefix} got unexpected break`)
  }
  return [decoded, data.subarray(tokeniser.pos())]
}

/**
 * @param {Uint8Array} data
 * @param {DecodeOptions} [options]
 * @returns {any}
 */
function decode (data, options) {
  const [decoded, remainder] = decodeFirst(data, options)
  if (remainder.length > 0) {
    throw new Error(`${decodeErrPrefix} too many terminals, data makes no sense`)
  }
  return decoded
}

export { Tokeniser, tokensToObject, decode, decodeFirst }
import { is } from './is.js'
import { Token, Type } from './token.js'
import { Bl, U8Bl } from './bl.js'
import { encodeErrPrefix } from './common.js'
import { quickEncodeToken } from './jump.js'
import { asU8A, compare, fromString } from './byte-utils.js'

import { encodeUint, encodeUintValue } from './0uint.js'
import { encodeNegint } from './1negint.js'
import { encodeBytes } from './2bytes.js'
import { encodeString } from './3string.js'
import { encodeArray } from './4array.js'
import { encodeMap } from './5map.js'
import { encodeTag } from './6tag.js'
import { encodeFloat, MINOR_FALSE, MINOR_TRUE, MINOR_NULL, MINOR_UNDEFINED } from './7float.js'

/**
 * @typedef {import('../interface.js').EncodeOptions} EncodeOptions
 * @typedef {import('../interface.js').OptionalTypeEncoder} OptionalTypeEncoder
 * @typedef {import('../interface.js').Reference} Reference
 * @typedef {import('../interface.js').StrictTypeEncoder} StrictTypeEncoder
 * @typedef {import('../interface.js').TokenTypeEncoder} TokenTypeEncoder
 * @typedef {import('../interface.js').TokenOrNestedTokens} TokenOrNestedTokens
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 */

/** @type {EncodeOptions} */
const defaultEncodeOptions = {
  float64: false,
  mapSorter,
  quickEncodeToken
}

/** @type {EncodeOptions} */
export const rfc8949EncodeOptions = Object.freeze({
  mapSorter: rfc8949MapSorter,
  quickEncodeToken
})

/** @returns {TokenTypeEncoder[]} */
export function makeCborEncoders () {
  const encoders = []
  encoders[Type.uint.major] = encodeUint
  encoders[Type.negint.major] = encodeNegint
  encoders[Type.bytes.major] = encodeBytes
  encoders[Type.string.major] = encodeString
  encoders[Type.array.major] = encodeArray
  encoders[Type.map.major] = encodeMap
  encoders[Type.tag.major] = encodeTag
  encoders[Type.float.major] = encodeFloat
  return encoders
}

const cborEncoders = makeCborEncoders()

const defaultWriter = new Bl()

/** @implements {Reference} */
class Ref {
  /**
   * @param {object|any[]} obj
   * @param {Reference|undefined} parent
   */
  constructor (obj, parent) {
    this.obj = obj
    this.parent = parent
  }

  /**
   * @param {object|any[]} obj
   * @returns {boolean}
   */
  includes (obj) {
    /** @type {Reference|undefined} */
    let p = this
    do {
      if (p.obj === obj) {
        return true
      }
    } while (p = p.parent) // eslint-disable-line
    return false
  }

  /**
   * @param {Reference|undefined} stack
   * @param {object|any[]} obj
   * @returns {Reference}
   */
  static createCheck (stack, obj) {
    if (stack && stack.includes(obj)) {
      throw new Error(`${encodeErrPrefix} object contains circular references`)
    }
    return new Ref(obj, stack)
  }
}

const simpleTokens = {
  null: new Token(Type.null, null),
  undefined: new Token(Type.undefined, undefined),
  true: new Token(Type.true, true),
  false: new Token(Type.false, false),
  emptyArray: new Token(Type.array, 0),
  emptyMap: new Token(Type.map, 0)
}

/** @type {{[typeName: string]: StrictTypeEncoder}} */
const typeEncoders = {
  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  number (obj, _typ, _options, _refStack) {
    if (!Number.isInteger(obj) || !Number.isSafeInteger(obj)) {
      return new Token(Type.float, obj)
    } else if (obj >= 0) {
      return new Token(Type.uint, obj)
    } else {
      return new Token(Type.negint, obj)
    }
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  bigint (obj, _typ, _options, _refStack) {
    if (obj >= BigInt(0)) {
      return new Token(Type.uint, obj)
    } else {
      return new Token(Type.negint, obj)
    }
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  Uint8Array (obj, _typ, _options, _refStack) {
    return new Token(Type.bytes, obj)
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  string (obj, _typ, _options, _refStack) {
    return new Token(Type.string, obj)
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  boolean (obj, _typ, _options, _refStack) {
    return obj ? simpleTokens.true : simpleTokens.false
  },

  /**
   * @param {any} _obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  null (_obj, _typ, _options, _refStack) {
    return simpleTokens.null
  },

  /**
   * @param {any} _obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  undefined (_obj, _typ, _options, _refStack) {
    return simpleTokens.undefined
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  ArrayBuffer (obj, _typ, _options, _refStack) {
    return new Token(Type.bytes, new Uint8Array(obj))
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  DataView (obj, _typ, _options, _refStack) {
    return new Token(Type.bytes, new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength))
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} options
   * @param {Reference} [refStack]
   * @returns {TokenOrNestedTokens}
   */
  Array (obj, _typ, options, refStack) {
    if (!obj.length) {
      if (options.addBreakTokens === true) {
        return [simpleTokens.emptyArray, new Token(Type.break)]
      }
      return simpleTokens.emptyArray
    }
    refStack = Ref.createCheck(refStack, obj)
    const entries = []
    let i = 0
    for (const e of obj) {
      entries[i++] = objectToTokens(e, options, refStack)
    }
    if (options.addBreakTokens) {
      return [new Token(Type.array, obj.length), entries, new Token(Type.break)]
    }
    return [new Token(Type.array, obj.length), entries]
  },

  /**
   * @param {any} obj
   * @param {string} typ
   * @param {EncodeOptions} options
   * @param {Reference} [refStack]
   * @returns {TokenOrNestedTokens}
   */
  Object (obj, typ, options, refStack) {
    // could be an Object or a Map
    const isMap = typ !== 'Object'
    // it's slightly quicker to use Object.keys() than Object.entries()
    const keys = isMap ? obj.keys() : Object.keys(obj)
    const maxLength = isMap ? obj.size : keys.length

    /** @type {undefined | [TokenOrNestedTokens, TokenOrNestedTokens][]} */
    let entries

    if (maxLength) {
      // Pre-allocate the array with the expected size
      entries = new Array(maxLength)
      refStack = Ref.createCheck(refStack, obj)
      const skipUndefined = !isMap && options.ignoreUndefinedProperties

      let i = 0
      for (const key of keys) {
        const value = isMap ? obj.get(key) : obj[key]
        if (skipUndefined && value === undefined) {
          continue
        }
        entries[i++] = [
          objectToTokens(key, options, refStack),
          objectToTokens(value, options, refStack)
        ]
      }

      // Truncate only if properties were skipped
      if (i < maxLength) {
        entries.length = i
      }
    }

    if (!entries?.length) {
      if (options.addBreakTokens === true) {
        return [simpleTokens.emptyMap, new Token(Type.break)]
      }
      return simpleTokens.emptyMap
    }

    sortMapEntries(entries, options)
    if (options.addBreakTokens) {
      return [new Token(Type.map, entries.length), entries, new Token(Type.break)]
    }
    return [new Token(Type.map, entries.length), entries]
  },

  /**
   * Encode a `Tagged` wrapper as a CBOR tag header followed by the encoded
   * form of the wrapped value. The value is recursively tokenised through
   * `objectToTokens()` so any registered `typeEncoders` apply to it.
   *
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} options
   * @param {Reference} [refStack]
   * @returns {TokenOrNestedTokens}
   */
  Tagged (obj, _typ, options, refStack) {
    return [
      new Token(Type.tag, obj.tag),
      objectToTokens(obj.value, options, refStack)
    ]
  }
}

typeEncoders.Map = typeEncoders.Object
typeEncoders.Buffer = typeEncoders.Uint8Array
for (const typ of 'Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64'.split(' ')) {
  typeEncoders[`${typ}Array`] = typeEncoders.DataView
}

/**
 * @param {any} obj
 * @param {EncodeOptions} [options]
 * @param {Reference} [refStack]
 * @returns {TokenOrNestedTokens}
 */
function objectToTokens (obj, options = {}, refStack) {
  const typ = is(obj)
  const customTypeEncoder = (options && options.typeEncoders && /** @type {OptionalTypeEncoder} */ options.typeEncoders[typ]) || typeEncoders[typ]
  if (typeof customTypeEncoder === 'function') {
    const tokens = customTypeEncoder(obj, typ, options, refStack)
    if (tokens != null) {
      return tokens
    }
  }
  const typeEncoder = typeEncoders[typ]
  if (!typeEncoder) {
    throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`)
  }
  return typeEncoder(obj, typ, options, refStack)
}

/*
CBOR key sorting is a mess.

The canonicalisation recommendation from https://tools.ietf.org/html/rfc7049#section-3.9
includes the wording:

> The keys in every map must be sorted lowest value to highest.
> Sorting is performed on the bytes of the representation of the key
> data items without paying attention to the 3/5 bit splitting for
> major types.
> ...
>  *  If two keys have different lengths, the shorter one sorts
      earlier;
>  *  If two keys have the same length, the one with the lower value
      in (byte-wise) lexical order sorts earlier.

1. It is not clear what "bytes of the representation of the key" means: is it
   the CBOR representation, or the binary representation of the object itself?
   Consider the int and uint difference here.
2. It is not clear what "without paying attention to" means: do we include it
   and compare on that? Or do we omit the special prefix byte, (mostly) treating
   the key in its plain binary representation form.

The FIDO 2.0: Client To Authenticator Protocol spec takes the original CBOR
wording and clarifies it according to their understanding.
https://fidoalliance.org/specs/fido-v2.0-rd-20170927/fido-client-to-authenticator-protocol-v2.0-rd-20170927.html#message-encoding

> The keys in every map must be sorted lowest value to highest. Sorting is
> performed on the bytes of the representation of the key data items without
> paying attention to the 3/5 bit splitting for major types. The sorting rules
> are:
>  * If the major types are different, the one with the lower value in numerical
>    order sorts earlier.
>  * If two keys have different lengths, the shorter one sorts earlier;
>  * If two keys have the same length, the one with the lower value in
>    (byte-wise) lexical order sorts earlier.

Some other implementations, such as borc, do a full encode then do a
length-first, byte-wise-second comparison:
https://github.com/dignifiedquire/borc/blob/b6bae8b0bcde7c3976b0f0f0957208095c392a36/src/encoder.js#L358
https://github.com/dignifiedquire/borc/blob/b6bae8b0bcde7c3976b0f0f0957208095c392a36/src/utils.js#L143-L151

This has the benefit of being able to easily handle arbitrary keys, including
complex types (maps and arrays).

We'll opt for the FIDO approach, since it affords some efficies since we don't
need a full encode of each key to determine order and can defer to the types
to determine how to most efficiently order their values (i.e. int and uint
ordering can be done on the numbers, no need for byte-wise, for example).

Recommendation: stick to single key types or you'll get into trouble, and prefer
string keys because it's much simpler that way.
*/

/**
 * @param {TokenOrNestedTokens[]} entries
 * @param {EncodeOptions} options
 */
function sortMapEntries (entries, options) {
  if (options.mapSorter) {
    entries.sort(options.mapSorter)
  }
}

/**
 * @param {(Token|Token[])[]} e1
 * @param {(Token|Token[])[]} e2
 * @returns {number}
 */
function mapSorter (e1, e2) {
  // the key position ([0]) could have a single token or an array
  // almost always it'll be a single token but complex key might get involved
  const keyToken1 = Array.isArray(e1[0]) ? e1[0][0] : e1[0]
  const keyToken2 = Array.isArray(e2[0]) ? e2[0][0] : e2[0]

  // different key types
  if (keyToken1.type !== keyToken2.type) {
    return keyToken1.type.compare(keyToken2.type)
  }

  const major = keyToken1.type.major
  // TODO: handle case where cmp === 0 but there are more keyToken e. complex type)
  const tcmp = cborEncoders[major].compareTokens(keyToken1, keyToken2)
  if (tcmp === 0) {
    // duplicate key or complex type where the first token matched,
    // i.e. a map or array and we're only comparing the opening token
    console.warn('WARNING: complex key types used, CBOR key sorting guarantees are gone')
  }
  return tcmp
}

/**
 * @typedef {Token & { _keyBytes?: Uint8Array }} TokenEx
 *
 * @param {(Token|Token[])[]} e1
 * @param {(Token|Token[])[]} e2
 * @returns {number}
 */
function rfc8949MapSorter (e1, e2) {
  if (e1[0] instanceof Token && e2[0] instanceof Token) {
    const t1 = /** @type {TokenEx} */ (e1[0])
    const t2 = /** @type {TokenEx} */ (e2[0])

    if (!t1._keyBytes) {
      t1._keyBytes = encodeRfc8949(t1.value)
    }

    if (!t2._keyBytes) {
      t2._keyBytes = encodeRfc8949(t2.value)
    }

    return compare(t1._keyBytes, t2._keyBytes)
  }

  throw new Error('rfc8949MapSorter: complex key types are not supported yet')
}

/**
 * @param {any} data
 * @returns {Uint8Array}
 */
function encodeRfc8949 (data) {
  return encodeCustom(data, cborEncoders, rfc8949EncodeOptions)
}

/**
 * @param {ByteWriter} writer
 * @param {TokenOrNestedTokens} tokens
 * @param {TokenTypeEncoder[]} encoders
 * @param {EncodeOptions} options
 */
function tokensToEncoded (writer, tokens, encoders, options) {
  if (Array.isArray(tokens)) {
    for (const token of tokens) {
      tokensToEncoded(writer, token, encoders, options)
    }
  } else {
    encoders[tokens.type.major](writer, tokens, options)
  }
}

// CBOR major type prefixes, cached from Type for hot path performance
const MAJOR_UINT = Type.uint.majorEncoded
const MAJOR_NEGINT = Type.negint.majorEncoded
const MAJOR_BYTES = Type.bytes.majorEncoded
const MAJOR_STRING = Type.string.majorEncoded
const MAJOR_ARRAY = Type.array.majorEncoded

// Simple value bytes (CBOR major type 7 + minor value)
const SIMPLE_FALSE = Type.float.majorEncoded | MINOR_FALSE
const SIMPLE_TRUE = Type.float.majorEncoded | MINOR_TRUE
const SIMPLE_NULL = Type.float.majorEncoded | MINOR_NULL
const SIMPLE_UNDEFINED = Type.float.majorEncoded | MINOR_UNDEFINED

const neg1b = BigInt(-1)
const pos1b = BigInt(1)

/**
 * Check if direct encoding can be used for the given options.
 * Direct encoding bypasses token creation for most values.
 * @param {EncodeOptions} options
 * @returns {boolean}
 */
function canDirectEncode (options) {
  // Cannot use direct encode with addBreakTokens (needs special break token handling).
  // Direct encode checks typeEncoders per-value, falling back to tokens as needed.
  // Maps fall back to token-based encoding for efficient key sorting.
  return options.addBreakTokens !== true
}

/**
 * Direct encode a value to the writer, bypassing token creation for most types.
 * Falls back to token-based encoding for custom type encoders.
 * @param {ByteWriter} writer
 * @param {any} data
 * @param {EncodeOptions} options
 * @param {Reference|undefined} refStack
 */
function directEncode (writer, data, options, refStack) {
  const typ = is(data)

  // Check for custom encoder for THIS specific type
  const customEncoder = options.typeEncoders && options.typeEncoders[typ]
  if (customEncoder) {
    const tokens = customEncoder(data, typ, options, refStack)
    if (tokens != null) {
      // Custom encoder returned tokens, serialize immediately
      tokensToEncoded(writer, tokens, cborEncoders, options)
      return
    }
    // Custom encoder returned null, fall through to default handling
  }

  // Direct encode based on type
  switch (typ) {
    case 'null':
      writer.push([SIMPLE_NULL])
      return

    case 'undefined':
      writer.push([SIMPLE_UNDEFINED])
      return

    case 'boolean':
      writer.push([data ? SIMPLE_TRUE : SIMPLE_FALSE])
      return

    case 'number':
      if (!Number.isInteger(data) || !Number.isSafeInteger(data)) {
        // Float, use token encoder for complex float encoding
        encodeFloat(writer, new Token(Type.float, data), options)
      } else if (data >= 0) {
        encodeUintValue(writer, MAJOR_UINT, data)
      } else {
        // Negative integer
        encodeUintValue(writer, MAJOR_NEGINT, data * -1 - 1)
      }
      return

    case 'bigint':
      if (data >= BigInt(0)) {
        encodeUintValue(writer, MAJOR_UINT, data)
      } else {
        encodeUintValue(writer, MAJOR_NEGINT, data * neg1b - pos1b)
      }
      return

    case 'string': {
      const bytes = fromString(data)
      encodeUintValue(writer, MAJOR_STRING, bytes.length)
      writer.push(bytes)
      return
    }

    case 'Uint8Array':
      encodeUintValue(writer, MAJOR_BYTES, data.length)
      writer.push(data)
      return

    case 'Array':
      if (!data.length) {
        writer.push([MAJOR_ARRAY]) // Empty array: 0x80
        return
      }
      refStack = Ref.createCheck(refStack, data)
      encodeUintValue(writer, MAJOR_ARRAY, data.length)
      for (const elem of data) {
        directEncode(writer, elem, options, refStack)
      }
      return

    case 'Object':
    case 'Map':
      // Maps require key sorting, use token-based encoding for efficiency
      // (pre-encoding all keys for sorting is expensive)
      {
        const tokens = typeEncoders.Object(data, typ, options, refStack)
        tokensToEncoded(writer, tokens, cborEncoders, options)
      }
      return

    default:
    // Fall back to token-based encoding for other types (DataView, TypedArrays, etc.)
    {
      const typeEncoder = typeEncoders[typ]
      if (!typeEncoder) {
        throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`)
      }
      const tokens = typeEncoder(data, typ, options, refStack)
      tokensToEncoded(writer, tokens, cborEncoders, options)
    }
  }
}

/**
 * @param {any} data
 * @param {TokenTypeEncoder[]} encoders
 * @param {EncodeOptions} options
 * @param {Uint8Array} [destination]
 * @returns {Uint8Array}
 */
function encodeCustom (data, encoders, options, destination) {
  // arg ordering is different to encodeInto for backward compatibility
  const hasDest = destination instanceof Uint8Array
  let writeTo = hasDest ? new U8Bl(destination) : defaultWriter

  const tokens = objectToTokens(data, options)
  if (!Array.isArray(tokens) && options.quickEncodeToken) {
    const quickBytes = options.quickEncodeToken(tokens)
    if (quickBytes) {
      if (hasDest) {
        // Copy quick bytes into destination buffer
        writeTo.push(quickBytes)
        return writeTo.toBytes()
      }
      return quickBytes
    }
    const encoder = encoders[tokens.type.major]
    if (encoder.encodedSize) {
      const size = encoder.encodedSize(tokens, options)
      if (!hasDest) {
        writeTo = new Bl(size)
      }
      encoder(writeTo, tokens, options)
      // this would be a problem with encodedSize() functions
      if (writeTo.chunks.length !== 1) {
        throw new Error(`Unexpected error: pre-calculated length for ${tokens} was wrong`)
      }
      return hasDest ? writeTo.toBytes() : asU8A(writeTo.chunks[0])
    }
  }
  writeTo.reset()
  tokensToEncoded(writeTo, tokens, encoders, options)
  return writeTo.toBytes(true)
}

/**
 * @param {any} data
 * @param {EncodeOptions} [options]
 * @returns {Uint8Array}
 */
function encode (data, options) {
  options = Object.assign({}, defaultEncodeOptions, options)

  // Use direct encode path when possible
  if (canDirectEncode(options)) {
    defaultWriter.reset()
    directEncode(defaultWriter, data, options, undefined)
    return defaultWriter.toBytes(true)
  }

  return encodeCustom(data, cborEncoders, options)
}

/**
 * @param {any} data
 * @param {Uint8Array} destination
 * @param {EncodeOptions} [options]
 * @returns {{ written: number }}
 */
function encodeInto (data, destination, options) {
  options = Object.assign({}, defaultEncodeOptions, options)

  // Use direct encode path when possible
  if (canDirectEncode(options)) {
    const writer = new U8Bl(destination)
    directEncode(writer, data, options, undefined)
    return { written: writer.toBytes().length }
  }

  const result = encodeCustom(data, cborEncoders, options, destination)
  return { written: result.length }
}

export { objectToTokens, encode, encodeCustom, encodeInto, Ref }
// This is an unfortunate replacement for @sindresorhus/is that we need to
// re-implement for performance purposes. In particular the is.observable()
// check is expensive, and unnecessary for our purposes. The values returned
// are compatible with @sindresorhus/is, however.

// Types that reach getObjectType() - excludes types with fast-paths above:
// primitives (typeof), Array (isArray), Uint8Array (instanceof), plain Object (constructor)
const objectTypeNames = [
  'Object', // for Object.create(null) and other non-plain objects
  'RegExp',
  'Date',
  'Error',
  'Map',
  'Set',
  'WeakMap',
  'WeakSet',
  'ArrayBuffer',
  'SharedArrayBuffer',
  'DataView',
  'Promise',
  'URL',
  'HTMLElement',
  'Int8Array',
  'Uint8ClampedArray',
  'Int16Array',
  'Uint16Array',
  'Int32Array',
  'Uint32Array',
  'Float32Array',
  'Float64Array',
  'BigInt64Array',
  'BigUint64Array',
  'Tagged'
]

/**
 * @param {any} value
 * @returns {string}
 */
export function is (value) {
  if (value === null) {
    return 'null'
  }
  if (value === undefined) {
    return 'undefined'
  }
  if (value === true || value === false) {
    return 'boolean'
  }
  const typeOf = typeof value
  if (typeOf === 'string' || typeOf === 'number' || typeOf === 'bigint' || typeOf === 'symbol') {
    return typeOf
  }
  if (typeOf === 'function') {
    return 'Function'
  }
  if (Array.isArray(value)) {
    return 'Array'
  }
  // Also catches Node.js Buffer which extends Uint8Array
  if (value instanceof Uint8Array) {
    return 'Uint8Array'
  }
  // Fast path for plain objects (most common case after primitives/arrays/bytes)
  if (value.constructor === Object) {
    return 'Object'
  }
  const objectType = getObjectType(value)
  if (objectType) {
    return objectType
  }
  return 'Object'
}

/**
 * @param {any} value
 * @returns {string|undefined}
 */
function getObjectType (value) {
  const objectTypeName = Object.prototype.toString.call(value).slice(8, -1)
  if (objectTypeNames.includes(objectTypeName)) {
    return objectTypeName
  }
  return undefined
}
import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import * as negint from './1negint.js'
import * as bytes from './2bytes.js'
import * as string from './3string.js'
import * as array from './4array.js'
import * as map from './5map.js'
import * as tag from './6tag.js'
import * as float from './7float.js'
import { decodeErrPrefix } from './common.js'
import { fromArray } from './byte-utils.js'

/**
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 */
function invalidMinor (data, pos, minor) {
  throw new Error(`${decodeErrPrefix} encountered invalid minor (${minor}) for major ${data[pos] >>> 5}`)
}

/**
 * @param {string} msg
 * @returns {()=>any}
 */
function errorer (msg) {
  return () => { throw new Error(`${decodeErrPrefix} ${msg}`) }
}

/** @type {((data:Uint8Array, pos:number, minor:number, options?:DecodeOptions) => any)[]} */
export const jump = []

// unsigned integer, 0x00..0x17 (0..23)
for (let i = 0; i <= 0x17; i++) {
  jump[i] = invalidMinor // uint.decodeUintCompact, handled by quick[]
}
jump[0x18] = uint.decodeUint8 // unsigned integer, one-byte uint8_t follows
jump[0x19] = uint.decodeUint16 // unsigned integer, two-byte uint16_t follows
jump[0x1a] = uint.decodeUint32 // unsigned integer, four-byte uint32_t follows
jump[0x1b] = uint.decodeUint64 // unsigned integer, eight-byte uint64_t follows
jump[0x1c] = invalidMinor
jump[0x1d] = invalidMinor
jump[0x1e] = invalidMinor
jump[0x1f] = invalidMinor
// negative integer, -1-0x00..-1-0x17 (-1..-24)
for (let i = 0x20; i <= 0x37; i++) {
  jump[i] = invalidMinor // negintDecode, handled by quick[]
}
jump[0x38] = negint.decodeNegint8 // negative integer, -1-n one-byte uint8_t for n follows
jump[0x39] = negint.decodeNegint16 // negative integer, -1-n two-byte uint16_t for n follows
jump[0x3a] = negint.decodeNegint32 // negative integer, -1-n four-byte uint32_t for follows
jump[0x3b] = negint.decodeNegint64 // negative integer, -1-n eight-byte uint64_t for follows
jump[0x3c] = invalidMinor
jump[0x3d] = invalidMinor
jump[0x3e] = invalidMinor
jump[0x3f] = invalidMinor
// byte string, 0x00..0x17 bytes follow
for (let i = 0x40; i <= 0x57; i++) {
  jump[i] = bytes.decodeBytesCompact
}
jump[0x58] = bytes.decodeBytes8 // byte string, one-byte uint8_t for n, and then n bytes follow
jump[0x59] = bytes.decodeBytes16 // byte string, two-byte uint16_t for n, and then n bytes follow
jump[0x5a] = bytes.decodeBytes32 // byte string, four-byte uint32_t for n, and then n bytes follow
jump[0x5b] = bytes.decodeBytes64 // byte string, eight-byte uint64_t for n, and then n bytes follow
jump[0x5c] = invalidMinor
jump[0x5d] = invalidMinor
jump[0x5e] = invalidMinor
jump[0x5f] = errorer('indefinite length bytes/strings are not supported') // byte string, byte strings follow, terminated by "break"
// UTF-8 string 0x00..0x17 bytes follow
for (let i = 0x60; i <= 0x77; i++) {
  jump[i] = string.decodeStringCompact
}
jump[0x78] = string.decodeString8 // UTF-8 string, one-byte uint8_t for n, and then n bytes follow
jump[0x79] = string.decodeString16 // UTF-8 string, two-byte uint16_t for n, and then n bytes follow
jump[0x7a] = string.decodeString32 // UTF-8 string, four-byte uint32_t for n, and then n bytes follow
jump[0x7b] = string.decodeString64 // UTF-8 string, eight-byte uint64_t for n, and then n bytes follow
jump[0x7c] = invalidMinor
jump[0x7d] = invalidMinor
jump[0x7e] = invalidMinor
jump[0x7f] = errorer('indefinite length bytes/strings are not supported') // UTF-8 strings follow, terminated by "break"
// array, 0x00..0x17 data items follow
for (let i = 0x80; i <= 0x97; i++) {
  jump[i] = array.decodeArrayCompact
}
jump[0x98] = array.decodeArray8 // array, one-byte uint8_t for n, and then n data items follow
jump[0x99] = array.decodeArray16 // array, two-byte uint16_t for n, and then n data items follow
jump[0x9a] = array.decodeArray32 // array, four-byte uint32_t for n, and then n data items follow
jump[0x9b] = array.decodeArray64 // array, eight-byte uint64_t for n, and then n data items follow
jump[0x9c] = invalidMinor
jump[0x9d] = invalidMinor
jump[0x9e] = invalidMinor
jump[0x9f] = array.decodeArrayIndefinite // array, data items follow, terminated by "break"
// map, 0x00..0x17 pairs of data items follow
for (let i = 0xa0; i <= 0xb7; i++) {
  jump[i] = map.decodeMapCompact
}
jump[0xb8] = map.decodeMap8 // map, one-byte uint8_t for n, and then n pairs of data items follow
jump[0xb9] = map.decodeMap16 // map, two-byte uint16_t for n, and then n pairs of data items follow
jump[0xba] = map.decodeMap32 // map, four-byte uint32_t for n, and then n pairs of data items follow
jump[0xbb] = map.decodeMap64 // map, eight-byte uint64_t for n, and then n pairs of data items follow
jump[0xbc] = invalidMinor
jump[0xbd] = invalidMinor
jump[0xbe] = invalidMinor
jump[0xbf] = map.decodeMapIndefinite // map, pairs of data items follow, terminated by "break"
// tags
for (let i = 0xc0; i <= 0xd7; i++) {
  jump[i] = tag.decodeTagCompact
}
jump[0xd8] = tag.decodeTag8
jump[0xd9] = tag.decodeTag16
jump[0xda] = tag.decodeTag32
jump[0xdb] = tag.decodeTag64
jump[0xdc] = invalidMinor
jump[0xdd] = invalidMinor
jump[0xde] = invalidMinor
jump[0xdf] = invalidMinor
// 0xe0..0xf3 simple values, unsupported
for (let i = 0xe0; i <= 0xf3; i++) {
  jump[i] = errorer('simple values are not supported')
}
jump[0xf4] = invalidMinor // false, handled by quick[]
jump[0xf5] = invalidMinor // true, handled by quick[]
jump[0xf6] = invalidMinor // null, handled by quick[]
jump[0xf7] = float.decodeUndefined // undefined
jump[0xf8] = errorer('simple values are not supported') // simple value, one byte follows, unsupported
jump[0xf9] = float.decodeFloat16 // half-precision float (two-byte IEEE 754)
jump[0xfa] = float.decodeFloat32 // single-precision float (four-byte IEEE 754)
jump[0xfb] = float.decodeFloat64 // double-precision float (eight-byte IEEE 754)
jump[0xfc] = invalidMinor
jump[0xfd] = invalidMinor
jump[0xfe] = invalidMinor
jump[0xff] = float.decodeBreak // "break" stop code

/** @type {Token[]} */
export const quick = []
// ints <24
for (let i = 0; i < 24; i++) {
  quick[i] = new Token(Type.uint, i, 1)
}
// negints >= -24
for (let i = -1; i >= -24; i--) {
  quick[31 - i] = new Token(Type.negint, i, 1)
}
// empty bytes
quick[0x40] = new Token(Type.bytes, new Uint8Array(0), 1)
// empty string
quick[0x60] = new Token(Type.string, '', 1)
// empty list
quick[0x80] = new Token(Type.array, 0, 1)
// empty map
quick[0xa0] = new Token(Type.map, 0, 1)
// false
quick[0xf4] = new Token(Type.false, false, 1)
// true
quick[0xf5] = new Token(Type.true, true, 1)
// null
quick[0xf6] = new Token(Type.null, null, 1)

/**
 * @param {Token} token
 * @returns {Uint8Array|undefined}
 */
export function quickEncodeToken (token) {
  switch (token.type) {
    case Type.false:
      return fromArray([0xf4])
    case Type.true:
      return fromArray([0xf5])
    case Type.null:
      return fromArray([0xf6])
    case Type.bytes:
      if (!token.value.length) {
        return fromArray([0x40])
      }
      return
    case Type.string:
      if (token.value === '') {
        return fromArray([0x60])
      }
      return
    case Type.array:
      if (token.value === 0) {
        return fromArray([0x80])
      }
      // shouldn't be possible if this were called when there was only one token
      return
    case Type.map:
      if (token.value === 0) {
        return fromArray([0xa0])
      }
      // shouldn't be possible if this were called when there was only one token
      return
    case Type.uint:
      if (token.value < 24) {
        return fromArray([Number(token.value)])
      }
      return
    case Type.negint:
      if (token.value >= -24) {
        return fromArray([31 - Number(token.value)])
      }
  }
}
/**
 * @typedef {import('../interface.js').TagDecodeControl} TagDecodeControl
 * @typedef {(decode: TagDecodeControl) => Tagged} TaggedTagDecoder
 */

/**
 * A wrapper class for representing a CBOR tag with an arbitrary nested value.
 *
 * `Tagged` is a symmetric primitive: it can be passed to `encode()` to emit
 * a CBOR tag header followed by the encoded form of `value`, and it can be
 * returned from a tag decoder (via `Tagged.decoder(tag)` or `Tagged.preserve()`)
 * to round-trip a tag through decode without losing the tag number.
 *
 * Use `Tagged` for one-off tag handling where defining a dedicated
 * `typeEncoders` entry and tag decoder pair would be heavyweight, e.g. when
 * wrapping a structure in a single application-specific tag (COSE, dCBOR
 * envelopes, etc.).
 *
 * For systematic mapping of a JS type to a tag (e.g. CID -> tag 42), prefer
 * a dedicated `typeEncoders` entry instead.
 */
export class Tagged {
  /**
   * @param {number} tag - CBOR tag number, a non-negative integer
   * @param {any} value - The value to be tagged; encoded recursively
   */
  constructor (tag, value) {
    if (typeof tag !== 'number' || !Number.isInteger(tag) || tag < 0) {
      throw new TypeError('Tagged: tag must be a non-negative integer')
    }
    this.tag = tag
    this.value = value
  }

  /**
   * Build a tag decoder for use in `decode()`'s `tags` option that returns the
   * decoded content wrapped in a `Tagged` instance, preserving the tag number
   * for the caller to inspect.
   *
   * @param {number} tag - The CBOR tag number this decoder will be registered for
   * @returns {TaggedTagDecoder}
   *
   * @example
   * import { decode, Tagged } from 'cborg'
   * const value = decode(bytes, { tags: { 16: Tagged.decoder(16) } })
   * // value instanceof Tagged; value.tag === 16
   */
  static decoder (tag) {
    return (decode) => new Tagged(tag, decode())
  }

  /**
   * Build a `tags` option for `decode()` that wraps each listed tag number in
   * a `Tagged` instance, preserving those tags through decode without
   * registering a dedicated decoder per tag.
   *
   * @param {...number} tagNumbers - One or more CBOR tag numbers to preserve
   * @returns {{[tagNumber: number]: TaggedTagDecoder}}
   *
   * @example
   * import { decode, Tagged } from 'cborg'
   * const value = decode(bytes, { tags: Tagged.preserve(16, 96) })
   */
  static preserve (...tagNumbers) {
    /** @type {{[tagNumber: number]: TaggedTagDecoder}} */
    const tags = {}
    for (const tag of tagNumbers) {
      tags[tag] = Tagged.decoder(tag)
    }
    return tags
  }
}

// Symbol.toStringTag so the internal `is()` type detection returns 'Tagged'
// for instances, allowing the default Tagged typeEncoder to match.
Object.defineProperty(Tagged.prototype, Symbol.toStringTag, {
  value: 'Tagged'
})
class Type {
  /**
   * @param {number} major
   * @param {string} name
   * @param {boolean} terminal
   */
  constructor (major, name, terminal) {
    this.major = major
    this.majorEncoded = major << 5
    this.name = name
    this.terminal = terminal
  }

  toString () {
    return `Type[${this.major}].${this.name}`
  }

  /**
   * @param {Type} typ
   * @returns {number}
   */
  compare (typ) {
    return this.major < typ.major ? -1 : this.major > typ.major ? 1 : 0
  }

  /**
   * Check equality between two Type instances. Safe to use across different
   * copies of the Type class (e.g., when bundlers duplicate the module).
   * (major, name) uniquely identifies a Type; terminal is implied by these.
   * @param {Type} a
   * @param {Type} b
   * @returns {boolean}
   */
  static equals (a, b) {
    return a === b || (a.major === b.major && a.name === b.name)
  }
}

// convert to static fields when better supported
Type.uint = new Type(0, 'uint', true)
Type.negint = new Type(1, 'negint', true)
Type.bytes = new Type(2, 'bytes', true)
Type.string = new Type(3, 'string', true)
Type.array = new Type(4, 'array', false)
Type.map = new Type(5, 'map', false)
Type.tag = new Type(6, 'tag', false) // terminal?
Type.float = new Type(7, 'float', true)
Type.false = new Type(7, 'false', true)
Type.true = new Type(7, 'true', true)
Type.null = new Type(7, 'null', true)
Type.undefined = new Type(7, 'undefined', true)
Type.break = new Type(7, 'break', true)
// Type.indefiniteLength = new Type(0, 'indefiniteLength', true)

class Token {
  /**
   * @param {Type} type
   * @param {any} [value]
   * @param {number} [encodedLength]
   */
  constructor (type, value, encodedLength) {
    this.type = type
    this.value = value
    this.encodedLength = encodedLength
    /** @type {Uint8Array|undefined} */
    this.encodedBytes = undefined
    /** @type {Uint8Array|undefined} */
    this.byteValue = undefined
  }

  toString () {
    return `Token[${this.type}].${this.value}`
  }
}

export { Type, Token }
{
  "name": "cborg",
  "version": "5.1.6",
  "description": "Fast CBOR with a focus on strictness",
  "main": "cborg.js",
  "type": "module",
  "bin": {
    "cborg": "lib/bin.js"
  },
  "scripts": {
    "lint": "standard *.js lib/*.js test/*.js",
    "build": "npm run build:types",
    "build:types": "tsc --build",
    "prepublishOnly": "npm run build",
    "test:node": "mocha test/test-*.js",
    "test:node-bin": "mocha test/node-test-bin.js",
    "test:browser": "polendina --cleanup test/test-*.js",
    "test": "npm run lint && npm run build && npm run test:node && npm run test:node-bin && npm run test:browser",
    "test:ci": "npm run test"
  },
  "repository": {
    "type": "git",
    "url": "git@github.com:rvagg/cborg.git"
  },
  "keywords": [
    "cbor"
  ],
  "author": "Rod <rod@vagg.org> (http://r.va.gg/)",
  "license": "Apache-2.0",
  "devDependencies": {
    "@semantic-release/changelog": "^6.0.3",
    "@semantic-release/commit-analyzer": "^13.0.1",
    "@semantic-release/git": "^10.0.1",
    "@semantic-release/github": "^12.0.6",
    "@semantic-release/npm": "^13.1.5",
    "@semantic-release/release-notes-generator": "^14.1.0",
    "@types/chai": "^5.2.3",
    "@types/mocha": "^10.0.10",
    "@types/node": "^26.0.1",
    "chai": "^6.2.2",
    "conventional-changelog-conventionalcommits": "^10.0.0",
    "ipld-garbage": "^5.0.0",
    "mocha": "^11.7.5",
    "polendina": "^3.2.20",
    "semantic-release": "^25.0.3",
    "standard": "^17.1.2",
    "typescript": "^6.0.2"
  },
  "exports": {
    ".": {
      "import": "./cborg.js",
      "types": "./types/cborg.d.ts"
    },
    "./length": {
      "import": "./lib/length.js",
      "types": "./types/lib/length.d.ts"
    },
    "./taglib": {
      "import": "./lib/taglib.js",
      "types": "./types/lib/taglib.d.ts"
    },
    "./json": {
      "import": "./lib/json/json.js",
      "types": "./types/lib/json/json.d.ts"
    },
    "./extended": {
      "import": "./lib/extended/extended.js",
      "types": "./types/lib/extended/extended.d.ts"
    },
    "./interface": {
      "types": "./types/interface.d.ts"
    }
  },
  "types": "cborg.d.ts",
  "typesVersions": {
    "*": {
      "json": [
        "types/lib/json/json.d.ts"
      ],
      "length": [
        "types/lib/length.d.ts"
      ],
      "*": [
        "types/*"
      ],
      "types/*": [
        "types/*"
      ]
    }
  },
  "release": {
    "branches": [
      "master"
    ],
    "plugins": [
      [
        "@semantic-release/commit-analyzer",
        {
          "preset": "conventionalcommits",
          "releaseRules": [
            {
              "breaking": true,
              "release": "major"
            },
            {
              "revert": true,
              "release": "patch"
            },
            {
              "type": "feat",
              "release": "minor"
            },
            {
              "type": "fix",
              "release": "patch"
            },
            {
              "type": "chore",
              "release": "patch"
            },
            {
              "type": "docs",
              "release": "patch"
            },
            {
              "type": "test",
              "release": "patch"
            },
            {
              "scope": "no-release",
              "release": false
            }
          ]
        }
      ],
      [
        "@semantic-release/release-notes-generator",
        {
          "preset": "conventionalcommits",
          "presetConfig": {
            "types": [
              {
                "type": "feat",
                "section": "Features"
              },
              {
                "type": "fix",
                "section": "Bug Fixes"
              },
              {
                "type": "chore",
                "section": "Trivial Changes"
              },
              {
                "type": "docs",
                "section": "Trivial Changes"
              },
              {
                "type": "test",
                "section": "Tests"
              }
            ]
          }
        }
      ],
      "@semantic-release/changelog",
      "@semantic-release/npm",
      "@semantic-release/github",
      "@semantic-release/git"
    ]
  }
}
import { coerce } from '../bytes.js';
import basex from '../vendor/base-x.js';
/**
 * Class represents both BaseEncoder and MultibaseEncoder meaning it
 * can be used to encode to multibase or base encode without multibase
 * prefix.
 */
class Encoder {
    name;
    prefix;
    baseEncode;
    constructor(name, prefix, baseEncode) {
        this.name = name;
        this.prefix = prefix;
        this.baseEncode = baseEncode;
    }
    encode(bytes) {
        if (bytes instanceof Uint8Array) {
            return `${this.prefix}${this.baseEncode(bytes)}`;
        }
        else {
            throw Error('Unknown type, must be binary type');
        }
    }
}
/**
 * Class represents both BaseDecoder and MultibaseDecoder so it could be used
 * to decode multibases (with matching prefix) or just base decode strings
 * with corresponding base encoding.
 */
class Decoder {
    name;
    prefix;
    baseDecode;
    prefixCodePoint;
    constructor(name, prefix, baseDecode) {
        this.name = name;
        this.prefix = prefix;
        const prefixCodePoint = prefix.codePointAt(0);
        /* c8 ignore next 3 */
        if (prefixCodePoint === undefined) {
            throw new Error('Invalid prefix character');
        }
        this.prefixCodePoint = prefixCodePoint;
        this.baseDecode = baseDecode;
    }
    decode(text) {
        if (typeof text === 'string') {
            if (text.codePointAt(0) !== this.prefixCodePoint) {
                throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);
            }
            return this.baseDecode(text.slice(this.prefix.length));
        }
        else {
            throw Error('Can only multibase decode strings');
        }
    }
    or(decoder) {
        return or(this, decoder);
    }
}
class ComposedDecoder {
    decoders;
    constructor(decoders) {
        this.decoders = decoders;
    }
    or(decoder) {
        return or(this, decoder);
    }
    decode(input) {
        const prefix = input[0];
        const decoder = this.decoders[prefix];
        if (decoder != null) {
            return decoder.decode(input);
        }
        else {
            throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);
        }
    }
}
export function or(left, right) {
    return new ComposedDecoder({
        ...(left.decoders ?? { [left.prefix]: left }),
        ...(right.decoders ?? { [right.prefix]: right })
    });
}
export class Codec {
    name;
    prefix;
    baseEncode;
    baseDecode;
    encoder;
    decoder;
    constructor(name, prefix, baseEncode, baseDecode) {
        this.name = name;
        this.prefix = prefix;
        this.baseEncode = baseEncode;
        this.baseDecode = baseDecode;
        this.encoder = new Encoder(name, prefix, baseEncode);
        this.decoder = new Decoder(name, prefix, baseDecode);
    }
    encode(input) {
        return this.encoder.encode(input);
    }
    decode(input) {
        return this.decoder.decode(input);
    }
}
export function from({ name, prefix, encode, decode }) {
    return new Codec(name, prefix, encode, decode);
}
export function baseX({ name, prefix, alphabet }) {
    const { encode, decode } = basex(alphabet, name);
    return from({
        prefix,
        name,
        encode,
        decode: (text) => coerce(decode(text))
    });
}
function decode(string, alphabetIdx, bitsPerChar, name) {
    // Count the padding bytes:
    let end = string.length;
    while (string[end - 1] === '=') {
        --end;
    }
    // Allocate the output:
    const out = new Uint8Array((end * bitsPerChar / 8) | 0);
    // Parse the data:
    let bits = 0; // Number of bits currently in the buffer
    let buffer = 0; // Bits waiting to be written out, MSB first
    let written = 0; // Next byte to write
    for (let i = 0; i < end; ++i) {
        // Read one character from the string:
        const value = alphabetIdx[string[i]];
        if (value === undefined) {
            throw new SyntaxError(`Non-${name} character`);
        }
        // Append the bits to the buffer:
        buffer = (buffer << bitsPerChar) | value;
        bits += bitsPerChar;
        // Write out some bits if the buffer has a byte's worth:
        if (bits >= 8) {
            bits -= 8;
            out[written++] = 0xff & (buffer >> bits);
        }
    }
    // Verify that we have received just enough bits:
    if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {
        throw new SyntaxError('Unexpected end of data');
    }
    return out;
}
function encode(data, alphabet, bitsPerChar) {
    const pad = alphabet[alphabet.length - 1] === '=';
    const mask = (1 << bitsPerChar) - 1;
    let out = '';
    let bits = 0; // Number of bits currently in the buffer
    let buffer = 0; // Bits waiting to be written out, MSB first
    for (let i = 0; i < data.length; ++i) {
        // Slurp data into the buffer:
        buffer = (buffer << 8) | data[i];
        bits += 8;
        // Write out as much as we can:
        while (bits > bitsPerChar) {
            bits -= bitsPerChar;
            out += alphabet[mask & (buffer >> bits)];
        }
    }
    // Partial character:
    if (bits !== 0) {
        out += alphabet[mask & (buffer << (bitsPerChar - bits))];
    }
    // Add padding characters until we hit a byte boundary:
    if (pad) {
        while (((out.length * bitsPerChar) & 7) !== 0) {
            out += '=';
        }
    }
    return out;
}
function createAlphabetIdx(alphabet) {
    // Build the character lookup table:
    const alphabetIdx = {};
    for (let i = 0; i < alphabet.length; ++i) {
        alphabetIdx[alphabet[i]] = i;
    }
    return alphabetIdx;
}
/**
 * RFC4648 Factory
 */
export function rfc4648({ name, prefix, bitsPerChar, alphabet }) {
    const alphabetIdx = createAlphabetIdx(alphabet);
    return from({
        prefix,
        name,
        encode(input) {
            return encode(input, alphabet, bitsPerChar);
        },
        decode(input) {
            return decode(input, alphabetIdx, bitsPerChar, name);
        }
    });
}
//# sourceMappingURL=base.js.mapimport { rfc4648 } from './base.js';
export const base32 = rfc4648({
    prefix: 'b',
    name: 'base32',
    alphabet: 'abcdefghijklmnopqrstuvwxyz234567',
    bitsPerChar: 5
});
export const base32upper = rfc4648({
    prefix: 'B',
    name: 'base32upper',
    alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',
    bitsPerChar: 5
});
export const base32pad = rfc4648({
    prefix: 'c',
    name: 'base32pad',
    alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',
    bitsPerChar: 5
});
export const base32padupper = rfc4648({
    prefix: 'C',
    name: 'base32padupper',
    alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',
    bitsPerChar: 5
});
export const base32hex = rfc4648({
    prefix: 'v',
    name: 'base32hex',
    alphabet: '0123456789abcdefghijklmnopqrstuv',
    bitsPerChar: 5
});
export const base32hexupper = rfc4648({
    prefix: 'V',
    name: 'base32hexupper',
    alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',
    bitsPerChar: 5
});
export const base32hexpad = rfc4648({
    prefix: 't',
    name: 'base32hexpad',
    alphabet: '0123456789abcdefghijklmnopqrstuv=',
    bitsPerChar: 5
});
export const base32hexpadupper = rfc4648({
    prefix: 'T',
    name: 'base32hexpadupper',
    alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',
    bitsPerChar: 5
});
export const base32z = rfc4648({
    prefix: 'h',
    name: 'base32z',
    alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',
    bitsPerChar: 5
});
//# sourceMappingURL=base32.js.mapimport { baseX } from './base.js';
export const base36 = baseX({
    prefix: 'k',
    name: 'base36',
    alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'
});
export const base36upper = baseX({
    prefix: 'K',
    name: 'base36upper',
    alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
});
//# sourceMappingURL=base36.js.mapimport { baseX } from './base.js';
export const base58btc = baseX({
    name: 'base58btc',
    prefix: 'z',
    alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
});
export const base58flickr = baseX({
    name: 'base58flickr',
    prefix: 'Z',
    alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'
});
//# sourceMappingURL=base58.js.mapexport const empty = new Uint8Array(0);
export function toHex(d) {
    return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '');
}
export function fromHex(hex) {
    const hexes = hex.match(/../g);
    return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty;
}
export function equals(aa, bb) {
    if (aa === bb) {
        return true;
    }
    if (aa.byteLength !== bb.byteLength) {
        return false;
    }
    for (let ii = 0; ii < aa.byteLength; ii++) {
        if (aa[ii] !== bb[ii]) {
            return false;
        }
    }
    return true;
}
export function coerce(o) {
    if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') {
        return o;
    }
    if (o instanceof ArrayBuffer) {
        return new Uint8Array(o);
    }
    if (ArrayBuffer.isView(o)) {
        return new Uint8Array(o.buffer, o.byteOffset, o.byteLength);
    }
    throw new Error('Unknown type, must be binary type');
}
export function isBinary(o) {
    return o instanceof ArrayBuffer || ArrayBuffer.isView(o);
}
export function fromString(str) {
    return new TextEncoder().encode(str);
}
export function toString(b) {
    return new TextDecoder().decode(b);
}
//# sourceMappingURL=bytes.js.mapimport { base32 } from './bases/base32.js';
import { base36 } from './bases/base36.js';
import { base58btc } from './bases/base58.js';
import { coerce } from './bytes.js';
import * as Digest from './hashes/digest.js';
import * as varint from './varint.js';
// This way TS will also expose all the types from module
export * from './link/interface.js';
export function format(link, base) {
    const { bytes, version } = link;
    switch (version) {
        case 0:
            return toStringV0(bytes, baseCache(link), base ?? base58btc.encoder);
        default:
            return toStringV1(bytes, baseCache(link), (base ?? base32.encoder));
    }
}
export function toJSON(link) {
    return {
        '/': format(link)
    };
}
export function fromJSON(json) {
    return CID.parse(json['/']);
}
const cache = new WeakMap();
function baseCache(cid) {
    const baseCache = cache.get(cid);
    if (baseCache == null) {
        const baseCache = new Map();
        cache.set(cid, baseCache);
        return baseCache;
    }
    return baseCache;
}
export class CID {
    code;
    version;
    multihash;
    bytes;
    '/';
    /**
     * @param version - Version of the CID
     * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
     * @param multihash - (Multi)hash of the of the content.
     */
    constructor(version, code, multihash, bytes) {
        this.code = code;
        this.version = version;
        this.multihash = multihash;
        this.bytes = bytes;
        // flag to serializers that this is a CID and
        // should be treated specially
        this['/'] = bytes;
    }
    /**
     * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`
     * please either use `CID.asCID(cid)` or switch to new signalling mechanism
     *
     * @deprecated
     */
    get asCID() {
        return this;
    }
    // ArrayBufferView
    get byteOffset() {
        return this.bytes.byteOffset;
    }
    // ArrayBufferView
    get byteLength() {
        return this.bytes.byteLength;
    }
    toV0() {
        switch (this.version) {
            case 0: {
                return this;
            }
            case 1: {
                const { code, multihash } = this;
                if (code !== DAG_PB_CODE) {
                    throw new Error('Cannot convert a non dag-pb CID to CIDv0');
                }
                // sha2-256
                if (multihash.code !== SHA_256_CODE) {
                    throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0');
                }
                return (CID.createV0(multihash));
            }
            default: {
                throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);
            }
        }
    }
    toV1() {
        switch (this.version) {
            case 0: {
                const { code, digest } = this.multihash;
                const multihash = Digest.create(code, digest);
                return (CID.createV1(this.code, multihash));
            }
            case 1: {
                return this;
            }
            default: {
                throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);
            }
        }
    }
    equals(other) {
        return CID.equals(this, other);
    }
    static equals(self, other) {
        const unknown = other;
        return (unknown != null &&
            self.code === unknown.code &&
            self.version === unknown.version &&
            Digest.equals(self.multihash, unknown.multihash));
    }
    toString(base) {
        return format(this, base);
    }
    toJSON() {
        return { '/': format(this) };
    }
    link() {
        return this;
    }
    [Symbol.toStringTag] = 'CID';
    // Legacy
    [Symbol.for('nodejs.util.inspect.custom')]() {
        return `CID(${this.toString()})`;
    }
    /**
     * Takes any input `value` and returns a `CID` instance if it was
     * a `CID` otherwise returns `null`. If `value` is instanceof `CID`
     * it will return value back. If `value` is not instance of this CID
     * class, but is compatible CID it will return new instance of this
     * `CID` class. Otherwise returns null.
     *
     * This allows two different incompatible versions of CID library to
     * co-exist and interop as long as binary interface is compatible.
     */
    static asCID(input) {
        if (input == null) {
            return null;
        }
        const value = input;
        if (value instanceof CID) {
            // If value is instance of CID then we're all set.
            return value;
        }
        else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {
            // If value isn't instance of this CID class but `this.asCID === this` or
            // `value['/'] === value.bytes` is true it is CID instance coming from a
            // different implementation (diff version or duplicate). In that case we
            // rebase it to this `CID` implementation so caller is guaranteed to get
            // instance with expected API.
            const { version, code, multihash, bytes } = value;
            return new CID(version, code, multihash, bytes ?? encodeCID(version, code, multihash.bytes));
        }
        else if (value[cidSymbol] === true) {
            // If value is a CID from older implementation that used to be tagged via
            // symbol we still rebase it to the this `CID` implementation by
            // delegating that to a constructor.
            const { version, multihash, code } = value;
            const digest = Digest.decode(multihash);
            return CID.create(version, code, digest);
        }
        else {
            // Otherwise value is not a CID (or an incompatible version of it) in
            // which case we return `null`.
            return null;
        }
    }
    /**
     * @param version - Version of the CID
     * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
     * @param digest - (Multi)hash of the of the content.
     */
    static create(version, code, digest) {
        if (typeof code !== 'number') {
            throw new Error('String codecs are no longer supported');
        }
        if (!(digest.bytes instanceof Uint8Array)) {
            throw new Error('Invalid digest');
        }
        switch (version) {
            case 0: {
                if (code !== DAG_PB_CODE) {
                    throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);
                }
                else {
                    return new CID(version, code, digest, digest.bytes);
                }
            }
            case 1: {
                const bytes = encodeCID(version, code, digest.bytes);
                return new CID(version, code, digest, bytes);
            }
            default: {
                throw new Error('Invalid version');
            }
        }
    }
    /**
     * Simplified version of `create` for CIDv0.
     */
    static createV0(digest) {
        return CID.create(0, DAG_PB_CODE, digest);
    }
    /**
     * Simplified version of `create` for CIDv1.
     *
     * @param code - Content encoding format code.
     * @param digest - Multihash of the content.
     */
    static createV1(code, digest) {
        return CID.create(1, code, digest);
    }
    /**
     * Decoded a CID from its binary representation. The byte array must contain
     * only the CID with no additional bytes.
     *
     * An error will be thrown if the bytes provided do not contain a valid
     * binary representation of a CID.
     */
    static decode(bytes) {
        const [cid, remainder] = CID.decodeFirst(bytes);
        if (remainder.length !== 0) {
            throw new Error('Incorrect length');
        }
        return cid;
    }
    /**
     * Decoded a CID from its binary representation at the beginning of a byte
     * array.
     *
     * Returns an array with the first element containing the CID and the second
     * element containing the remainder of the original byte array. The remainder
     * will be a zero-length byte array if the provided bytes only contained a
     * binary CID representation.
     */
    static decodeFirst(bytes) {
        const specs = CID.inspectBytes(bytes);
        const prefixSize = specs.size - specs.multihashSize;
        const multihashBytes = coerce(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));
        if (multihashBytes.byteLength !== specs.multihashSize) {
            throw new Error('Incorrect length');
        }
        const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);
        const digest = new Digest.Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);
        const cid = specs.version === 0
            ? CID.createV0(digest)
            : CID.createV1(specs.codec, digest);
        return [cid, bytes.subarray(specs.size)];
    }
    /**
     * Inspect the initial bytes of a CID to determine its properties.
     *
     * Involves decoding up to 4 varints. Typically this will require only 4 to 6
     * bytes but for larger multicodec code values and larger multihash digest
     * lengths these varints can be quite large. It is recommended that at least
     * 10 bytes be made available in the `initialBytes` argument for a complete
     * inspection.
     */
    static inspectBytes(initialBytes) {
        let offset = 0;
        const next = () => {
            const [i, length] = varint.decode(initialBytes.subarray(offset));
            offset += length;
            return i;
        };
        let version = next();
        let codec = DAG_PB_CODE;
        if (version === 18) {
            // CIDv0
            version = 0;
            offset = 0;
        }
        else {
            codec = next();
        }
        if (version !== 0 && version !== 1) {
            throw new RangeError(`Invalid CID version ${version}`);
        }
        const prefixSize = offset;
        const multihashCode = next(); // multihash code
        const digestSize = next(); // multihash length
        const size = offset + digestSize;
        const multihashSize = size - prefixSize;
        return { version, codec, multihashCode, digestSize, multihashSize, size };
    }
    /**
     * Takes cid in a string representation and creates an instance. If `base`
     * decoder is not provided will use a default from the configuration. It will
     * throw an error if encoding of the CID is not compatible with supplied (or
     * a default decoder).
     */
    static parse(source, base) {
        const [prefix, bytes] = parseCIDtoBytes(source, base);
        const cid = CID.decode(bytes);
        if (cid.version === 0 && source[0] !== 'Q') {
            throw Error('Version 0 CID string must not include multibase prefix');
        }
        // Cache string representation to avoid computing it on `this.toString()`
        baseCache(cid).set(prefix, source);
        return cid;
    }
}
function parseCIDtoBytes(source, base) {
    switch (source[0]) {
        // CIDv0 is parsed differently
        case 'Q': {
            const decoder = base ?? base58btc;
            return [
                base58btc.prefix,
                decoder.decode(`${base58btc.prefix}${source}`)
            ];
        }
        case base58btc.prefix: {
            const decoder = base ?? base58btc;
            return [base58btc.prefix, decoder.decode(source)];
        }
        case base32.prefix: {
            const decoder = base ?? base32;
            return [base32.prefix, decoder.decode(source)];
        }
        case base36.prefix: {
            const decoder = base ?? base36;
            return [base36.prefix, decoder.decode(source)];
        }
        default: {
            if (base == null) {
                throw Error('To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided');
            }
            return [source[0], base.decode(source)];
        }
    }
}
function toStringV0(bytes, cache, base) {
    const { prefix } = base;
    if (prefix !== base58btc.prefix) {
        throw Error(`Cannot string encode V0 in ${base.name} encoding`);
    }
    const cid = cache.get(prefix);
    if (cid == null) {
        const cid = base.encode(bytes).slice(1);
        cache.set(prefix, cid);
        return cid;
    }
    else {
        return cid;
    }
}
function toStringV1(bytes, cache, base) {
    const { prefix } = base;
    const cid = cache.get(prefix);
    if (cid == null) {
        const cid = base.encode(bytes);
        cache.set(prefix, cid);
        return cid;
    }
    else {
        return cid;
    }
}
const DAG_PB_CODE = 0x70;
const SHA_256_CODE = 0x12;
function encodeCID(version, code, multihash) {
    const codeOffset = varint.encodingLength(version);
    const hashOffset = codeOffset + varint.encodingLength(code);
    const bytes = new Uint8Array(hashOffset + multihash.byteLength);
    varint.encodeTo(version, bytes, 0);
    varint.encodeTo(code, bytes, codeOffset);
    bytes.set(multihash, hashOffset);
    return bytes;
}
const cidSymbol = Symbol.for('@ipld/js-cid/CID');
//# sourceMappingURL=cid.js.mapimport { coerce } from '../bytes.js';
export const name = 'raw';
export const code = 0x55;
export function encode(node) {
    return coerce(node);
}
export function decode(data) {
    return coerce(data);
}
//# sourceMappingURL=raw.js.mapimport { coerce, equals as equalBytes } from '../bytes.js';
import * as varint from '../varint.js';
/**
 * Creates a multihash digest.
 */
export function create(code, digest) {
    const size = digest.byteLength;
    const sizeOffset = varint.encodingLength(code);
    const digestOffset = sizeOffset + varint.encodingLength(size);
    const bytes = new Uint8Array(digestOffset + size);
    varint.encodeTo(code, bytes, 0);
    varint.encodeTo(size, bytes, sizeOffset);
    bytes.set(digest, digestOffset);
    return new Digest(code, size, digest, bytes);
}
/**
 * Turns bytes representation of multihash digest into an instance.
 */
export function decode(multihash) {
    const bytes = coerce(multihash);
    const [code, sizeOffset] = varint.decode(bytes);
    const [size, digestOffset] = varint.decode(bytes.subarray(sizeOffset));
    const digest = bytes.subarray(sizeOffset + digestOffset);
    if (digest.byteLength !== size) {
        throw new Error('Incorrect length');
    }
    return new Digest(code, size, digest, bytes);
}
export function equals(a, b) {
    if (a === b) {
        return true;
    }
    else {
        const data = b;
        return (a.code === data.code &&
            a.size === data.size &&
            data.bytes instanceof Uint8Array &&
            equalBytes(a.bytes, data.bytes));
    }
}
/**
 * Represents a multihash digest which carries information about the
 * hashing algorithm and an actual hash digest.
 */
export class Digest {
    code;
    size;
    digest;
    bytes;
    /**
     * Creates a multihash digest.
     */
    constructor(code, size, digest, bytes) {
        this.code = code;
        this.size = size;
        this.digest = digest;
        this.bytes = bytes;
    }
}
/**
 * Used to check that the passed multihash has the passed code
 */
export function hasCode(digest, code) {
    return digest.code === code;
}
//# sourceMappingURL=digest.js.mapexport {};
//# sourceMappingURL=interface.js.mapimport varint from './vendor/varint.js';
export function decode(data, offset = 0) {
    const code = varint.decode(data, offset);
    return [code, varint.decode.bytes];
}
export function encodeTo(int, target, offset = 0) {
    varint.encode(int, target, offset);
    return target;
}
export function encodingLength(int) {
    return varint.encodingLength(int);
}
//# sourceMappingURL=varint.js.map/* eslint-disable */
// base-x encoding / decoding
// Copyright (c) 2018 base-x contributors
// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)
// Distributed under the MIT software license, see the accompanying
// file LICENSE or http://www.opensource.org/licenses/mit-license.php.
/**
 * @param {string} ALPHABET
 * @param {any} name
 */
function base(ALPHABET, name) {
    if (ALPHABET.length >= 255) {
        throw new TypeError('Alphabet too long');
    }
    var BASE_MAP = new Uint8Array(256);
    for (var j = 0; j < BASE_MAP.length; j++) {
        BASE_MAP[j] = 255;
    }
    for (var i = 0; i < ALPHABET.length; i++) {
        var x = ALPHABET.charAt(i);
        var xc = x.charCodeAt(0);
        if (BASE_MAP[xc] !== 255) {
            throw new TypeError(x + ' is ambiguous');
        }
        BASE_MAP[xc] = i;
    }
    var BASE = ALPHABET.length;
    var LEADER = ALPHABET.charAt(0);
    var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up
    var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up
    /**
     * @param {any[] | Iterable<number>} source
     */
    function encode(source) {
        // @ts-ignore
        if (source instanceof Uint8Array)
            ;
        else if (ArrayBuffer.isView(source)) {
            source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
        }
        else if (Array.isArray(source)) {
            source = Uint8Array.from(source);
        }
        if (!(source instanceof Uint8Array)) {
            throw new TypeError('Expected Uint8Array');
        }
        if (source.length === 0) {
            return '';
        }
        // Skip & count leading zeroes.
        var zeroes = 0;
        var length = 0;
        var pbegin = 0;
        var pend = source.length;
        while (pbegin !== pend && source[pbegin] === 0) {
            pbegin++;
            zeroes++;
        }
        // Allocate enough space in big-endian base58 representation.
        var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;
        var b58 = new Uint8Array(size);
        // Process the bytes.
        while (pbegin !== pend) {
            var carry = source[pbegin];
            // Apply "b58 = b58 * 256 + ch".
            var i = 0;
            for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {
                carry += (256 * b58[it1]) >>> 0;
                b58[it1] = (carry % BASE) >>> 0;
                carry = (carry / BASE) >>> 0;
            }
            if (carry !== 0) {
                throw new Error('Non-zero carry');
            }
            length = i;
            pbegin++;
        }
        // Skip leading zeroes in base58 result.
        var it2 = size - length;
        while (it2 !== size && b58[it2] === 0) {
            it2++;
        }
        // Translate the result into a string.
        var str = LEADER.repeat(zeroes);
        for (; it2 < size; ++it2) {
            str += ALPHABET.charAt(b58[it2]);
        }
        return str;
    }
    /**
     * @param {string | string[]} source
     */
    function decodeUnsafe(source) {
        if (typeof source !== 'string') {
            throw new TypeError('Expected String');
        }
        if (source.length === 0) {
            return new Uint8Array();
        }
        var psz = 0;
        // Skip leading spaces.
        if (source[psz] === ' ') {
            return;
        }
        // Skip and count leading '1's.
        var zeroes = 0;
        var length = 0;
        while (source[psz] === LEADER) {
            zeroes++;
            psz++;
        }
        // Allocate enough space in big-endian base256 representation.
        var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.
        var b256 = new Uint8Array(size);
        // Process the characters.
        while (source[psz]) {
            // Decode character
            var carry = BASE_MAP[source.charCodeAt(psz)];
            // Invalid character
            if (carry === 255) {
                return;
            }
            var i = 0;
            for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {
                carry += (BASE * b256[it3]) >>> 0;
                b256[it3] = (carry % 256) >>> 0;
                carry = (carry / 256) >>> 0;
            }
            if (carry !== 0) {
                throw new Error('Non-zero carry');
            }
            length = i;
            psz++;
        }
        // Skip trailing spaces.
        if (source[psz] === ' ') {
            return;
        }
        // Skip leading zeroes in b256.
        var it4 = size - length;
        while (it4 !== size && b256[it4] === 0) {
            it4++;
        }
        var vch = new Uint8Array(zeroes + (size - it4));
        var j = zeroes;
        while (it4 !== size) {
            vch[j++] = b256[it4++];
        }
        return vch;
    }
    /**
     * @param {string | string[]} string
     */
    function decode(string) {
        var buffer = decodeUnsafe(string);
        if (buffer) {
            return buffer;
        }
        throw new Error(`Non-${name} character`);
    }
    return {
        encode: encode,
        decodeUnsafe: decodeUnsafe,
        decode: decode
    };
}
var src = base;
var _brrp__multiformats_scope_baseX = src;
export default _brrp__multiformats_scope_baseX;
//# sourceMappingURL=base-x.js.map/* eslint-disable */
var encode_1 = encode;
var MSB = 0x80, REST = 0x7F, MSBALL = ~REST, INT = Math.pow(2, 31);
/**
 * @param {number} num
 * @param {number[]} out
 * @param {number} offset
 */
function encode(num, out, offset) {
    out = out || [];
    offset = offset || 0;
    var oldOffset = offset;
    while (num >= INT) {
        out[offset++] = (num & 0xFF) | MSB;
        num /= 128;
    }
    while (num & MSBALL) {
        out[offset++] = (num & 0xFF) | MSB;
        num >>>= 7;
    }
    out[offset] = num | 0;
    // @ts-ignore
    encode.bytes = offset - oldOffset + 1;
    return out;
}
var decode = read;
var MSB$1 = 0x80, REST$1 = 0x7F;
/**
 * @param {string | any[]} buf
 * @param {number} offset
 */
function read(buf, offset) {
    var res = 0, offset = offset || 0, shift = 0, counter = offset, b, l = buf.length;
    do {
        if (counter >= l) {
            // @ts-ignore
            read.bytes = 0;
            throw new RangeError('Could not decode varint');
        }
        b = buf[counter++];
        res += shift < 28
            ? (b & REST$1) << shift
            : (b & REST$1) * Math.pow(2, shift);
        shift += 7;
    } while (b >= MSB$1);
    // @ts-ignore
    read.bytes = counter - offset;
    return res;
}
var N1 = Math.pow(2, 7);
var N2 = Math.pow(2, 14);
var N3 = Math.pow(2, 21);
var N4 = Math.pow(2, 28);
var N5 = Math.pow(2, 35);
var N6 = Math.pow(2, 42);
var N7 = Math.pow(2, 49);
var N8 = Math.pow(2, 56);
var N9 = Math.pow(2, 63);
var length = function (/** @type {number} */ value) {
    return (value < N1 ? 1
        : value < N2 ? 2
            : value < N3 ? 3
                : value < N4 ? 4
                    : value < N5 ? 5
                        : value < N6 ? 6
                            : value < N7 ? 7
                                : value < N8 ? 8
                                    : value < N9 ? 9
                                        : 10);
};
var varint = {
    encode: encode_1,
    decode: decode,
    encodingLength: length
};
var _brrp_varint = varint;
export default _brrp_varint;
//# sourceMappingURL=varint.js.map{
  "name": "multiformats",
  "version": "13.4.2",
  "description": "Interface for multihash, multicodec, multibase and CID",
  "author": "Mikeal Rogers <mikeal.rogers@gmail.com> (https://www.mikealrogers.com/)",
  "license": "Apache-2.0 OR MIT",
  "homepage": "https://github.com/multiformats/js-multiformats#readme",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/multiformats/js-multiformats.git"
  },
  "bugs": {
    "url": "https://github.com/multiformats/js-multiformats/issues"
  },
  "publishConfig": {
    "access": "public",
    "provenance": true
  },
  "keywords": [
    "ipfs",
    "ipld",
    "multiformats"
  ],
  "type": "module",
  "types": "./dist/src/index.d.ts",
  "typesVersions": {
    "*": {
      "*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ],
      "src/*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ]
    }
  },
  "files": [
    "src",
    "dist",
    "!dist/test",
    "!**/*.tsbuildinfo"
  ],
  "exports": {
    ".": {
      "types": "./dist/src/index.d.ts",
      "import": "./dist/src/index.js"
    },
    "./bases/base10": {
      "types": "./dist/src/bases/base10.d.ts",
      "import": "./dist/src/bases/base10.js"
    },
    "./bases/base16": {
      "types": "./dist/src/bases/base16.d.ts",
      "import": "./dist/src/bases/base16.js"
    },
    "./bases/base2": {
      "types": "./dist/src/bases/base2.d.ts",
      "import": "./dist/src/bases/base2.js"
    },
    "./bases/base256emoji": {
      "types": "./dist/src/bases/base256emoji.d.ts",
      "import": "./dist/src/bases/base256emoji.js"
    },
    "./bases/base32": {
      "types": "./dist/src/bases/base32.d.ts",
      "import": "./dist/src/bases/base32.js"
    },
    "./bases/base36": {
      "types": "./dist/src/bases/base36.d.ts",
      "import": "./dist/src/bases/base36.js"
    },
    "./bases/base58": {
      "types": "./dist/src/bases/base58.d.ts",
      "import": "./dist/src/bases/base58.js"
    },
    "./bases/base64": {
      "types": "./dist/src/bases/base64.d.ts",
      "import": "./dist/src/bases/base64.js"
    },
    "./bases/base8": {
      "types": "./dist/src/bases/base8.d.ts",
      "import": "./dist/src/bases/base8.js"
    },
    "./bases/identity": {
      "types": "./dist/src/bases/identity.d.ts",
      "import": "./dist/src/bases/identity.js"
    },
    "./bases/interface": {
      "types": "./dist/src/bases/interface.d.ts",
      "import": "./dist/src/bases/interface.js"
    },
    "./basics": {
      "types": "./dist/src/basics.d.ts",
      "import": "./dist/src/basics.js"
    },
    "./block": {
      "types": "./dist/src/block.d.ts",
      "import": "./dist/src/block.js"
    },
    "./block/interface": {
      "types": "./dist/src/block/interface.d.ts",
      "import": "./dist/src/block/interface.js"
    },
    "./bytes": {
      "types": "./dist/src/bytes.d.ts",
      "import": "./dist/src/bytes.js"
    },
    "./cid": {
      "types": "./dist/src/cid.d.ts",
      "import": "./dist/src/cid.js"
    },
    "./codecs/interface": {
      "types": "./dist/src/codecs/interface.d.ts",
      "import": "./dist/src/codecs/interface.js"
    },
    "./codecs/json": {
      "types": "./dist/src/codecs/json.d.ts",
      "import": "./dist/src/codecs/json.js"
    },
    "./codecs/raw": {
      "types": "./dist/src/codecs/raw.d.ts",
      "import": "./dist/src/codecs/raw.js"
    },
    "./hashes/digest": {
      "types": "./dist/src/hashes/digest.d.ts",
      "import": "./dist/src/hashes/digest.js"
    },
    "./hashes/hasher": {
      "types": "./dist/src/hashes/hasher.d.ts",
      "import": "./dist/src/hashes/hasher.js"
    },
    "./hashes/identity": {
      "types": "./dist/src/hashes/identity.d.ts",
      "import": "./dist/src/hashes/identity.js"
    },
    "./hashes/interface": {
      "types": "./dist/src/hashes/interface.d.ts",
      "import": "./dist/src/hashes/interface.js"
    },
    "./hashes/sha1": {
      "types": "./dist/types/src/hashes/sha1.d.ts",
      "browser": "./dist/src/hashes/sha1-browser.js",
      "import": "./dist/src/hashes/sha1.js"
    },
    "./hashes/sha2": {
      "types": "./dist/src/hashes/sha2.d.ts",
      "browser": "./dist/src/hashes/sha2-browser.js",
      "import": "./dist/src/hashes/sha2.js"
    },
    "./interface": {
      "types": "./dist/src/interface.d.ts",
      "import": "./dist/src/interface.js"
    },
    "./link": {
      "types": "./dist/src/link.d.ts",
      "import": "./dist/src/link.js"
    },
    "./link/interface": {
      "types": "./dist/src/link/interface.d.ts",
      "import": "./dist/src/link/interface.js"
    },
    "./traversal": {
      "types": "./dist/src/traversal.d.ts",
      "import": "./dist/src/traversal.js"
    }
  },
  "eslintConfig": {
    "extends": "ipfs",
    "parserOptions": {
      "project": true,
      "sourceType": "module"
    }
  },
  "release": {
    "branches": [
      "master"
    ],
    "plugins": [
      [
        "@semantic-release/commit-analyzer",
        {
          "preset": "conventionalcommits",
          "releaseRules": [
            {
              "breaking": true,
              "release": "major"
            },
            {
              "revert": true,
              "release": "patch"
            },
            {
              "type": "feat",
              "release": "minor"
            },
            {
              "type": "fix",
              "release": "patch"
            },
            {
              "type": "docs",
              "release": "patch"
            },
            {
              "type": "test",
              "release": "patch"
            },
            {
              "type": "deps",
              "release": "patch"
            },
            {
              "scope": "no-release",
              "release": false
            }
          ]
        }
      ],
      [
        "@semantic-release/release-notes-generator",
        {
          "preset": "conventionalcommits",
          "presetConfig": {
            "types": [
              {
                "type": "feat",
                "section": "Features"
              },
              {
                "type": "fix",
                "section": "Bug Fixes"
              },
              {
                "type": "chore",
                "section": "Trivial Changes"
              },
              {
                "type": "docs",
                "section": "Documentation"
              },
              {
                "type": "deps",
                "section": "Dependencies"
              },
              {
                "type": "test",
                "section": "Tests"
              }
            ]
          }
        }
      ],
      "@semantic-release/changelog",
      "@semantic-release/npm",
      "@semantic-release/github",
      [
        "@semantic-release/git",
        {
          "assets": [
            "CHANGELOG.md",
            "package.json"
          ]
        }
      ]
    ]
  },
  "scripts": {
    "clean": "aegir clean",
    "lint": "aegir lint",
    "build": "aegir build",
    "release": "aegir release",
    "docs": "aegir docs",
    "test": "npm run lint && npm run test:node && npm run test:chrome",
    "test:node": "aegir test -t node --cov",
    "test:chrome": "aegir test -t browser --cov",
    "test:chrome-webworker": "aegir test -t webworker",
    "test:firefox": "aegir test -t browser -- --browser firefox",
    "test:firefox-webworker": "aegir test -t webworker -- --browser firefox",
    "test:electron-main": "aegir test -t electron-main"
  },
  "devDependencies": {
    "@stablelib/sha256": "^2.0.0",
    "@stablelib/sha512": "^2.0.0",
    "@types/node": "^25.0.0",
    "aegir": "^47.0.7",
    "buffer": "^6.0.3",
    "cids": "^1.1.9",
    "crypto-hash": "^4.0.0"
  },
  "aegir": {
    "test": {
      "target": [
        "node",
        "browser"
      ]
    }
  },
  "browser": {
    "./hashes/sha1": "./dist/src/hashes/sha1-browser.js",
    "./dist/src/hashes/sha1.js": "./dist/src/hashes/sha1-browser.js",
    "./hashes/sha2": "./dist/src/hashes/sha2-browser.js",
    "./dist/src/hashes/sha2.js": "./dist/src/hashes/sha2-browser.js"
  }
}
{
  "name": "atproto-repo",
  "version": "0.0.1",
  "description": "Byte-exact atproto repo layer — CAR + DAG-CBOR + CID + MST — over Hypercore-friendly primitives. Verified against real relay-accepted repos.",
  "type": "module",
  "main": "lib/repo.js",
  "scripts": {
    "test": "brittle-node test/*.test.js",
    "postinstall": "node scripts/bare-deps.mjs"
  },
  "dependencies": {
    "@ipld/car": "^5.4.0",
    "@ipld/dag-cbor": "^9.2.1",
    "@noble/curves": "^1.9.7",
    "@noble/hashes": "^1.5.0",
    "multiformats": "^13.3.0"
  },
  "devDependencies": {
    "atproto-identity": "file:../atproto-identity",
    "brittle": "^4.0.2"
  }
}
// Lease — single active-signer election over the shared intent log.
//
// The canonical atproto chain is append-only, so exactly ONE device may extend it at a time.
// The lease is a reserved `__lease__` record naming the current holder + a monotonic epoch.
// Devices claim/renew by writing it; the autobase linearizes concurrent claims into ONE
// deterministic winner (highest epoch / last in linear order). Expiry and renewal are decided
// OUT-OF-APPLY against wall-clock (legal there — the signer is an out-of-apply consumer, exactly
// like StateBaseV3's promotion timer); the `apply` only ever stores the record, staying
// deterministic. On holder failure the lease lapses (TTL) and another device claims epoch+1 and
// continues the chain from the last signed head.
//
// `statebase`: the KV intent-log (StateBaseV3 or compatible). `__lease__` has no "/", so RepoBase
// treats it as reserved and never surfaces it as a repo record.

const LEASE_KEY = '__lease__'

export class Lease {
  constructor (statebase, { self, ttlMs = 15000 } = {}) {
    if (!statebase || typeof statebase.set !== 'function') throw new Error('Lease: a statebase is required')
    if (!self) throw new Error('Lease: self (this device id) required')
    this.sb = statebase
    this.self = String(self)
    this.ttlMs = ttlMs
  }

  // The current lease record from the linearized view, or null.
  //
  // NON-BLOCKING read (Phase-2 #6): use the statebase's getNow snapshot when available. current()
  // is the FIRST call the sign loop makes every tick (renewOrClaim → renew/claim → current). If it
  // went through the blocking get()→base.update(), a single stalled drain on an un-converged replica
  // froze the ENTIRE sign loop — so it never reached the re-admission doorbell (the live tabertron
  // hang: get-state over UDS hung here). The lease is wall-clock-TTL + "never steal a live lease",
  // so a few-ms-stale snapshot is safe (the autobase still linearizes concurrent claims to one
  // winner). Falls back to get() for injected substrates without getNow.
  async current () {
    const v = typeof this.sb.getNow === 'function' ? await this.sb.getNow(LEASE_KEY) : await this.sb.get(LEASE_KEY)
    return v && v.holder ? v : null
  }

  // Claim the lease: write self as holder at epoch = (seen epoch)+1 — but NEVER steal a LIVE lease
  // from another holder (that was the split-brain bug: a booting device grabbed the lease before it
  // had replicated the current holder's still-valid lease). Only claim if the lease is FREE
  // (unheld/expired) or already ours. Returns the new epoch, or null if a live other holds it.
  async claim (now = Date.now()) {
    const cur = await this.current()
    if (cur && cur.holder !== this.self && (now - (cur.ts || 0)) < this.ttlMs) return null // live other holder
    const epoch = (cur && Number.isInteger(cur.epoch) ? cur.epoch : 0) + 1
    await this.sb.set(LEASE_KEY, { holder: this.self, epoch, ts: now })
    return epoch
  }

  // The safe per-tick lease op: renew if we hold it, else claim ONLY if free (TTL-lapsed) — never
  // steal a live lease. Returns true iff we hold the lease afterward. This is the whole failover
  // model: the primary renews every tick; a standby takes over ONLY after the primary's lease has
  // lapsed (no primary online to renew it). Read against the linearized view + wall-clock TTL.
  async renewOrClaim (now = Date.now()) {
    if (await this.renew(now)) return true
    return (await this.claim(now)) !== null
  }

  // Renew our hold (bumps ts). No-op (returns false) if we're not the current holder.
  //
  // WRITE-GATED: only actually re-write the lease once it is past HALF its TTL. The sign loop calls this
  // every ~2s, but a fresh 15s lease does not need re-writing 7× before it could lapse. Renewing every tick
  // appended a new `__lease__` op to the append-only intent log EVERY tick forever (ts:now defeats value
  // dedup) — an unbounded at-rest storage leak (the ~25KB/s-at-rest we traced). Gating at ttlMs/2 keeps
  // `now - ts` under ~ttlMs/2 + one tick (≈9.5s ≪ 15s), so no standby ever claims while we are alive, and
  // failover stays within ~1.5×TTL. We still return true (we DO hold the lease) when we skip the write.
  async renew (now = Date.now()) {
    const cur = await this.current()
    if (!cur || cur.holder !== this.self) return false
    if ((now - (cur.ts || 0)) < this.ttlMs / 2) return true // still fresh — hold stands, no write needed
    await this.sb.set(LEASE_KEY, { holder: this.self, epoch: cur.epoch, ts: now })
    return true
  }

  // Do WE currently hold a live (un-expired) lease? Out-of-apply wall-clock TTL check.
  async holds (now = Date.now()) {
    const cur = await this.current()
    return !!cur && cur.holder === this.self && (now - (cur.ts || 0)) < this.ttlMs
  }

  // Is the lease free to (re)claim — unheld or expired?
  async isFree (now = Date.now()) {
    const cur = await this.current()
    return !cur || (now - (cur.ts || 0)) >= this.ttlMs
  }
}

export { LEASE_KEY }
// Membership — binary attestation admission for the swarm.
//
// One member type: the N devices of ONE DID, all equal. A device is admitted iff it can prove it
// is attested to the DID's ROOT identity (a keet-identity-key chain: root → device). No roles.
// These functions plug into StateBaseV3's injectable admission (opts.attest / opts.verifyAttest):
// the device attests the autobase's admission bytes (localKey‖base.key) as itself, and any writer
// re-verifies that the proof resolves to the DID's root identity + the claimed device key.
//
// The device roster (opts.getMembers) is the set of root-attested devices — supplied by the host
// (all role-equal); admission is proof-gated, the roster only says "these device ids are members".

import IdentityKey from 'keet-identity-key'
import keetEncoding from 'keet-identity-key/lib/encoding.js'
import c from 'compact-encoding'
import b4a from 'b4a'
import { attestDeviceChain, attestDeviceViaDevice, deviceKeetKeyPair, rootIdentityPublicKey } from 'atproto-identity/lib/device-chain.js'

const { ReceiptEncoding } = keetEncoding

// Epoch enforcement (atproto-base-REVOCATION §3): a receipt encodes a MINIMUM acceptable attestation
// epoch. Admission passes the current __receipt__ to verify, which rejects any proof whose epoch is
// below it. Bump it (encodeReceipt of a higher epoch, + re-attest survivors) to invalidate ALL stale
// proofs at once — the keet verifyAttestation(…, latestReceipt) mechanism.
export function encodeReceipt (epoch) { return c.encode(ReceiptEncoding, { epoch: Number(epoch) }) }
export function receiptEpoch (receipt) { return c.decode(ReceiptEncoding, b4a.isBuffer(receipt) ? receipt : b4a.from(receipt)).epoch }

// attest fn for StateBaseV3: sign arbitrary bytes as this device, carrying its root→device chain.
// deviceKeetKeyPair = this device's Ed25519 identity keypair; deviceProof = the root's attestation
// of this device (from attestDeviceChain / keet-identity-key bootstrap).
export function makeAttest (deviceKeetKeyPair, deviceProof) {
  return async (signData) => {
    const proof = IdentityKey.attestData(b4a.from(signData), deviceKeetKeyPair, deviceProof)
    return b4a.isBuffer(proof) ? proof : b4a.from(proof) // StateBaseV3 hex-encodes it into the admit
  }
}

// verifyAttest fn for StateBaseV3, bound to the DID's root identity pubkey. Returns bool: the
// proof over signData must resolve to (root identity, claimed device id).
export function makeVerifyAttest (rootIdentityPublicKey) {
  const root = b4a.from(rootIdentityPublicKey)
  // Returns the verify RESULT ({ receipt, identityPublicKey, devicePublicKey }, truthy) on success,
  // or null. `receipt` (optional) is the current MINIMUM-epoch receipt — a proof below it is rejected.
  return async (proof, signData, deviceId, receipt) => {
    try {
      const opts = { expectedIdentity: root, expectedDevice: b4a.from(deviceId) }
      if (receipt) opts.receipt = b4a.isBuffer(receipt) ? receipt : b4a.from(receipt)
      const r = IdentityKey.verify(b4a.from(proof), b4a.from(signData), opts)
      return r || null
    } catch { return null }
  }
}

export { attestDeviceChain, attestDeviceViaDevice, deviceKeetKeyPair, rootIdentityPublicKey }
// pairing.js — hpp-initiated browser pairing over blind-pairing (the "hash URL" that opens a peer tunnel).
//
// Aligns with pgv3's DeviceLinker (blind-pairing). pgv3's browser auth is TOFU (the daemon IS the identity
// authority, so it self-registers a browser key). favela is KEYLESS — the authority is the remote hpp/DID —
// so a browser sub-key must be DELEGATED by the DID. The DID key-holder (hpp) mints a one-time invite; the
// candidate (favela-web, on the browser's behalf) joins → an E2E tunnel opens over the DHT → the browser's
// sub-key PUBKEY goes up → the hpp delegates it → the delegation comes back. Works REMOTELY (any hpp on the
// DHT) and is owner-gated by construction (only the key-holder can mint an invite; favela-web holds no key).
//
// Direction note: DeviceLinker's source PUSHES a bundle to the joiner; here the candidate must send its
// sub-key UP first, so the sub-key rides the candidate's blind-pairing `userData` (the member's hello) and
// the delegation comes back as the confirm's `additional.data`.
import Hyperswarm from 'hyperswarm'
import BlindPairing from 'blind-pairing'
import crypto from 'hypercore-crypto'
import b4a from 'b4a'

const TIMEOUT_MS = 5 * 60 * 1000

// SOURCE (hpp): mint a one-time pairing invite. onSubkey(subKeyHex) => delegation object (device.delegate).
// Returns { inviteHex, waitForPeer, close }. Stays open for ONE pairing session (owner mints per browser).
export async function createPairInvite ({ onSubkey, swarm = null, timeout = TIMEOUT_MS } = {}) {
  if (typeof onSubkey !== 'function') throw new Error('createPairInvite requires onSubkey(subKey) => delegation')
  const pairingKey = crypto.keyPair()
  const { invite, publicKey: invitePublicKey, discoveryKey, seed } = BlindPairing.createInvite(pairingKey.publicKey)
  const inviteKeyPair = crypto.keyPair(seed)
  const sw = swarm || new Hyperswarm()
  const pairing = new BlindPairing(sw)
  const done = new Promise((resolve, reject) => {
    const timer = setTimeout(() => reject(new Error('createPairInvite: timeout waiting for the browser')), timeout)
    pairing.addMember({
      discoveryKey,
      onadd: async (request) => {
        clearTimeout(timer)
        try {
          request.open(invitePublicKey)
          const hello = JSON.parse(b4a.toString(request.userData)) // the candidate's sub-key
          const delegation = await onSubkey(hello.subKey)
          const data = b4a.from(JSON.stringify(delegation))
          request.confirm({ key: pairingKey.publicKey, encryptionKey: null, additional: { data, signature: crypto.sign(data, inviteKeyPair.secretKey) } })
          resolve({ subKey: hello.subKey, delegation })
        } catch (e) {
          // ⛔ TELL THE CANDIDATE. Rejecting only settles OUR promise; the joiner is left holding an open
          // tunnel with nothing coming back, so it waits out its full timeout (5 min) and reports
          // nothing about why. That is exactly how a BROWSER invite pasted into a NODE presents: the
          // node sends a 64-hex keet device key, delegate() demands 66-hex secp256k1 and throws here,
          // and the node just… hangs. A refusal is information the other side needs.
          //
          // Confirm with an { error } payload — the same shape mintAdoptInvite already returns when a
          // human declines — then reject locally. Best-effort: if the channel is already gone there is
          // nothing to say and the timeout remains the backstop.
          try {
            const data = b4a.from(JSON.stringify({ error: (e && e.message) || String(e) }))
            request.confirm({ key: pairingKey.publicKey, encryptionKey: null, additional: { data, signature: crypto.sign(data, inviteKeyPair.secretKey) } })
          } catch { /* channel gone — the candidate falls back to its timeout */ }
          reject(e)
        }
      }
    })
  })
  return {
    inviteHex: b4a.toString(invite, 'hex'),
    waitForPeer: () => done,
    // DRAIN before teardown (mirrors pgv3 DeviceLinker.close). The confirm frame carrying the delegation
    // is enqueued via protomux AFTER onadd returns, but waitForPeer resolves SYNCHRONOUSLY inside onadd —
    // so the CLI's `await waitForPeer(); await close()` would destroy the swarm before the frame hits the
    // wire. The candidate (favela-web) then never receives the delegation and hangs to timeout, while the
    // source falsely reports success. Awaiting conn.flush() drains protomux→noise→UDX before destroy.
    close: async () => {
      try {
        const flushes = []
        for (const conn of sw.connections) { if (typeof conn.flush === 'function') flushes.push(conn.flush()) }
        await Promise.all(flushes).catch(() => {})
      } catch {}
      try { await pairing.close() } catch {}
      if (!swarm) { try { await sw.destroy() } catch {} }
    }
  }
}

// CANDIDATE (favela-web): join with the invite + the browser's sub-key pubkey → receive the delegation.
// swarm optional (an ephemeral one is created + destroyed). Throws on timeout.
export async function joinPairInvite (inviteHex, { subKey, swarm = null, timeout = TIMEOUT_MS } = {}) {
  if (!subKey) throw new Error('joinPairInvite requires subKey')
  const sw = swarm || new Hyperswarm()
  const pairing = new BlindPairing(sw)
  const userData = b4a.from(JSON.stringify({ subKey }))
  try {
    return await new Promise((resolve, reject) => {
      const timer = setTimeout(() => reject(new Error('joinPairInvite: timeout')), timeout)
      pairing.addCandidate({
        invite: b4a.from(inviteHex, 'hex'),
        userData,
        onadd: (result) => {
          clearTimeout(timer)
          try { resolve(JSON.parse(b4a.toString(result.data))) } catch (e) { reject(e) }
        }
      })
    })
  } finally {
    try { await pairing.close() } catch {}
    if (!swarm) { try { await sw.destroy() } catch {} }
  }
}
// RepoBase — the repo-ops intent layer of atproto-base.
//
// atproto-base reskins keet-daemon's StateBaseV3 (the hyper-tps per-room gamestate autobase):
// the members are the N EQUAL attested devices of ONE DID, they write repo-op INTENTS into the
// shared autobase, and the linearized view IS the DID's repo record set. A lease elects the
// single active signer that materializes this view into one canonical signed atproto commit
// chain (see lib/signer.js — later slice). This file owns ONLY the repo-ops convention over the
// generic KV intent-log; membership/admission, the lease, and signing are separate modules.
//
// The substrate is INJECTED (a StateBaseV3 instance, or any KV log exposing the same async
// interface): { set(key,value), del(key), get(key)->value|null, list(prefix)->{key:value} }.
// Injection keeps this layer runtime-agnostic and unit-testable without the (Bare) StateBaseV3.
//
// KV → repo mapping: key = "<collection>/<rkey>", value = the record object. atproto collections
// are NSIDs (dot-separated, no "/") and rkeys forbid "/", so the FIRST "/" cleanly separates them.

const SEP = '/'

// A deleted record's durable marker. Kept in the record namespace (not a reserved "__" key) so it
// replicates and linearizes exactly like the record it replaces, and so a peer can distinguish
// "deleted" from "not yet replicated". See deleteRecord below.
const TOMBSTONE = { $deleted: true }
const isTombstone = (v) => !!(v && typeof v === 'object' && v.$deleted === true)

function assertSegment (name, v) {
  if (typeof v !== 'string' || v.length === 0) throw new Error('RepoBase: ' + name + ' must be a non-empty string')
  if (v.includes(SEP)) throw new Error('RepoBase: ' + name + ' must not contain "' + SEP + '" (got ' + JSON.stringify(v) + ')')
}

function recordKey (collection, rkey) {
  assertSegment('collection', collection)
  assertSegment('rkey', rkey)
  return collection + SEP + rkey
}

// Split a stored key back into { collection, rkey } on the FIRST separator. Reserved keys are
// NEVER repo records: single-segment keys (e.g. __lease__) AND any key whose collection starts
// with "__" (e.g. __commit__/<rev> — the firehose log). atproto collections are NSIDs (reverse-DNS)
// so they never start with "__"; this keeps the shared StateBase's control/firehose data out of
// the signed repo (it must never be materialized into a commit).
function splitKey (key) {
  const i = key.indexOf(SEP)
  if (i < 0) return null
  const collection = key.slice(0, i)
  if (collection.startsWith('__')) return null // reserved namespace (control/firehose), not a record
  return { collection, rkey: key.slice(i + 1) }
}

export class RepoBase {
  // statebase: an async KV intent-log (StateBaseV3 or compatible). did: the repo's did:plc.
  constructor (statebase, { did = null } = {}) {
    if (!statebase || typeof statebase.set !== 'function' || typeof statebase.list !== 'function') {
      throw new Error('RepoBase: a statebase with async set/del/get/list is required')
    }
    this.sb = statebase
    this.did = did
  }

  // ── repo-op intents (create/put/delete a record) ──────────────
  // create + put are the same intent at this layer (last-writer-wins on the key), matching the
  // KV log; the atproto create-vs-update distinction is enforced when the signer materializes.
  async putRecord (collection, rkey, record) {
    if (record == null || typeof record !== 'object') throw new Error('RepoBase.putRecord: record must be an object')
    await this.sb.set(recordKey(collection, rkey), record)
    return { collection, rkey }
  }

  // Deletion writes an explicit TOMBSTONE rather than removing the key. Absence of a pointer is
  // AMBIGUOUS in a replicated log — "deleted" and "never replicated to me" look identical — and the
  // signer's forward-only gate has to tell them apart: reading absence as "deleted" makes a device
  // whose view is merely lagging publish a delete for a record that is actually live (a content
  // regression to the relay; proven offline in the 0d probe). A tombstone makes deletion POSITIVE
  // evidence, so absence can safely mean "I don't know yet" and the gate fails safe.
  // The tombstone is a record-layer convention: reads below treat it as absent, so every consumer
  // (listRecords/snapshot/getRecord) sees a deleted record as gone, exactly as before.
  async deleteRecord (collection, rkey) {
    await this.sb.set(recordKey(collection, rkey), { ...TOMBSTONE })
    return { collection, rkey }
  }

  // ── reads over the linearized view ────────────────────────────
  async getRecord (collection, rkey) {
    const v = await this.sb.get(recordKey(collection, rkey))
    return (v == null || isTombstone(v)) ? null : v // a tombstoned record reads as absent
  }

  // List the repo's records (optionally scoped to one collection) as [{collection, rkey, record}],
  // skipping any reserved/non-record keys the underlying StateBase may hold (e.g. __members__).
  //
  // { now:true } (Phase-2 #6) reads the non-blocking autoUpdate snapshot (sb.listNow) instead of the
  // blocking sb.list()→base.update(), so liveness-critical callers (device.state()/get-state) never
  // hang on an un-converged replica. Falls back to list() if the substrate has no listNow.
  async listRecords (collection = null, { now = false } = {}) {
    const prefix = collection ? (assertSegment('collection', collection), collection + SEP) : ''
    const map = (now && typeof this.sb.listNow === 'function') ? await this.sb.listNow(prefix) : await this.sb.list(prefix)
    const out = []
    for (const key of Object.keys(map)) {
      const split = splitKey(key)
      if (!split) continue
      if (isTombstone(map[key])) continue // deleted — present as a tombstone, absent as a record
      out.push({ collection: split.collection, rkey: split.rkey, record: map[key] })
    }
    return out
  }

  // The record set as a nested {collection: {rkey: record}} — the shape the signer walks to
  // rebuild the MST and materialize the canonical commit.
  async snapshot () {
    const records = await this.listRecords()
    const byCollection = {}
    for (const { collection, rkey, record } of records) {
      ;(byCollection[collection] || (byCollection[collection] = {}))[rkey] = record
    }
    return byCollection
  }
}

export { recordKey, splitKey, TOMBSTONE, isTombstone }
// serveMembrane — Phase D (option A): expose the swarm's repo + firehose so the KEYLESS membrane
// (atproto-bridge PeerFront) fronts it UNCHANGED. Each device projects the shared, replicated
// __commit__ log → a local FirehoseSequencer Hypercore + the records → a RepoStore Hypercore, and
// PUSHES an announce (atproto/did-announce/v1) on connect. Because __commit__ is rev-ordered + deterministic,
// every device projects the SAME firehose (same seq), so the membrane can front any device and
// reconnect to another on hand-off. No shared-writer core, no fork hazard.

import b4a from 'b4a'
import c from 'compact-encoding'
import Protomux from 'protomux'
import ProtomuxRPC from 'protomux-rpc'
import { CID } from 'multiformats/cid'
import * as dagCbor from '@ipld/dag-cbor'
import { cidForBytesSync } from 'atproto-repo/lib/cid.js'
import { buildMst } from 'atproto-repo/lib/mst.js'
import { RepoStore } from 'atproto-store/lib/repo-store.js'
import { FirehoseSequencer } from 'atproto-store/lib/sequencer.js'
import { discoveryTopic } from 'atproto-identity/lib/discovery.js'

const RPC_PROTOCOL = 'hyper-proto-peer/rpc/v1' // MUST match atproto-bridge PeerFront + peer.serve
const ANNOUNCE_PROTOCOL = 'atproto/did-announce/v1' // MUST match atproto-bridge lib/did-peer.js (corrected discovery)

// A serialized __commit__ entry (swarm-device serializeEntry) → the `write` object commitFrame wants.
function deserializeEntry (e) {
  const cid = (s) => (s ? CID.parse(s) : null)
  const bytes = (h) => b4a.from(h, 'hex')
  const commitBlock = { cid: cid(e.commitCid), bytes: bytes(e.commit) }
  const signedCommit = dagCbor.decode(commitBlock.bytes)
  return {
    commitCid: cid(e.commitCid),
    commitBlock,
    signedCommit,
    dataCid: signedCommit.data,
    prevData: cid(e.prevData),
    rev: e.rev,
    since: e.since,
    ops: (e.ops || []).map((o) => ({ action: o.action, path: o.path, cid: cid(o.cid), prev: cid(o.prev) })),
    newBlocks: (e.blocks || []).map((b) => ({ cid: cid(b.cid), bytes: bytes(b.bytes) }))
  }
}

// Project the device's current LIVE record set into a RepoStore (last-writer-wins by key).
//
// ⚠ NOT the membrane projection path — see projectRepoFrames below for why. This reads THIS NODE's
// view, which is a different source from the __commit__ frames the firehose projection consumes, so
// using it to fill the membrane repo core produces a repo/head pair that does not describe one state.
// Kept because it is the "project the live view" baseline the derive-vs-project equivalence proof
// compares exportCar against (hyper-proto-peer/test/derive-vs-project.test.mjs) — a legitimate,
// different job. It also never deletes, so it can only ever be used against a fresh store.
async function projectRepo (device, repo) {
  for (const { collection, rkey, record } of await device.repo.listRecords()) {
    await repo.put(collection, rkey, record)
  }
}

// The MST data root for a record set — byte-for-byte the computation `materialize` (lib/signer.js)
// and read-view's getRepoFromCommit perform, so agreeing with it here means the consumer agrees too.
// byPath: Map<"collection/rkey", record>. Sorted, because the MST is defined over ordered keys.
function dataRoot (byPath) {
  const mstRecords = [...byPath.entries()].map(([key, record]) => ({ key, value: cidForBytesSync(dagCbor.encode(record)) }))
  mstRecords.sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0))
  return buildMst(mstRecords).root
}

// The data root a serialized __commit__ entry's signed commit commits to.
function entryDataCid (e) {
  return dagCbor.decode(b4a.from(e.commit, 'hex')).data
}

// Apply a run of __commit__ frames' ops onto a record set, resolving each create/update to the record
// block the frame ITSELF carries (buildCommitWrite puts them in newBlocks). Race-free: it depends on
// nothing but the frames. Returns the mutated map, or null if a referenced block is absent — a
// partially-replicated log we must NOT pretend to have reconstructed.
//
// ⚠ LOAD-BEARING ASSUMPTION: a #commit frame carries the record bytes for its own create/update ops,
// and __commit__ entries replicate whole (blocks included) as autobase values. That is what lets this
// reconstruct a complete record set with NO byte resolution and no live view — so a co-owner whose
// overlay bytes have not arrived can still serve a complete, self-consistent repo for any head whose
// frames it holds. SwarmDevice.restore/_recordsFromFirehose already depend on the same property.
// hyper-proto-peer's swarm-device.js:78 muses about a future step where "the firehose no longer
// carries them" (record bytes move wholly to the overlay files). Doing that would break BOTH this
// projection and restore(); it would need the projection to resolve bytes through the record store
// first, and would give up the no-byte-resolution property above. Not a plan of record anywhere —
// noted so it is a decision rather than a surprise.
function applyFrames (byPath, frames) {
  for (const e of frames) {
    const blocks = new Map((e.blocks || []).map((b) => [b.cid, b.bytes]))
    for (const op of (e.ops || [])) {
      if (op.action === 'delete') { byPath.delete(op.path); continue }
      const hex = op.cid ? blocks.get(op.cid) : null
      if (!hex) return null
      byPath.set(op.path, dagCbor.decode(b4a.from(hex, 'hex')))
    }
  }
  return byPath
}

// Bring the membrane repo core to EXACTLY the record set the log's head frame commits to.
//
// This is the fix for the projectRepo/projectFirehose DRIFT. The two projections are read by a
// keyless consumer as a PAIR: it takes the head off the firehose and asserts the MST rebuilt from
// the repo core equals that head's data root (read-view getRepoFromCommit). projectRepo sourced the
// repo half from `device.repo.listRecords()` — this NODE's live view — while projectFirehose sourced
// the other half from the SHARED __commit__ log, so the invariant held only by luck. Four ways it
// broke, all seen or provable (test/membrane-projection-drift.test.mjs):
//   - LAGGING view: a co-owner whose bytes/pointers have not caught up projects a SUBSET. A
//     non-signer never adopts the network head and only resolves bytes as a side effect of sign()
//     (which returns at the election gate), so it sits there indefinitely — tabertron's device head
//     stuck at s222 against a log head of s322, every getRepo 500 (hyper-social #14, incident 3).
//   - DELETES: projectRepo only ever put(), never del(), so one signed delete broke the core
//     PERMANENTLY regardless of lag.
//   - Running AHEAD: an unsigned write in the view projects a SUPERSET.
//   - POLLUTION: a core already holding leftovers from the above never self-corrects.
// Deriving BOTH halves from the frames makes the pair correct by construction, for signer and
// non-signer alike, and needs no byte resolution and no live view at all. It is the file's own
// premise ("__commit__ is rev-ordered + deterministic, so every device projects the SAME firehose")
// applied to the repo half.
//
// Incremental first (apply only the not-yet-projected frames onto what the core already holds), then
// VERIFY against the head frame before writing anything. On a mismatch, replay the whole log from
// genesis and re-verify — that heals a core polluted by the old live-view projection, which is the
// state every deployed node is in right now, with no operator step.
//
// Returns { ok: true } when the core now matches the head (the caller may advance the firehose), or
// { ok: false, reason } when it could not be made to match — the caller must then advance NEITHER core
// (an older CONSISTENT pair still serves; an inconsistent one 500s on every read). It never throws:
// a malformed frame is one of the conditions it exists to survive. `reason` distinguishes the faults
// rather than asserting one of them, because a message that names a cause it cannot tell apart from
// another is worse than one that says nothing (hyper-social #14, lesson 2 — "no connected peer served
// this oid" cost two days by calling a transport fault a content fault).
async function projectRepoFrames (repo, log, projected) {
  let rows, curBytes, headData, target
  try {
    rows = await repo.records() // [{ key, bytes, record }], key order
    curBytes = new Map(rows.map((r) => [r.key, r.bytes]))
    headData = entryDataCid(log[log.length - 1])
    target = applyFrames(new Map(rows.map((r) => [r.key, r.record])), log.slice(projected))
    if (!target || !dataRoot(target).equals(headData)) {
      target = applyFrames(new Map(), log) // full replay from genesis — heals a polluted/mis-seeded core
      if (!target) return { ok: false, reason: 'a record block referenced by a #commit op is absent from the log (partial replication)' }
      if (!dataRoot(target).equals(headData)) return { ok: false, reason: 'the replayed ops do not reproduce the head commit\'s data root (discontinuous log)' }
    }
  } catch (e) {
    return { ok: false, reason: 'the log head could not be read as a signed #commit: ' + e.message }
  }

  // Write the DIFF only. Redundant puts are already no-ops (RepoStore opens the bee with
  // alwaysDuplicate:false), but not walking them keeps an idle projection genuinely write-free.
  for (const [key, record] of target) {
    const bytes = dagCbor.encode(record)
    const have = curBytes.get(key)
    if (have && b4a.equals(b4a.from(have), b4a.from(bytes))) continue
    const i = key.indexOf('/')
    await repo.put(key.slice(0, i), key.slice(i + 1), record)
  }
  for (const key of curBytes.keys()) {
    if (target.has(key)) continue
    const i = key.indexOf('/')
    await repo.del(key.slice(0, i), key.slice(i + 1)) // the delete projectRepo never performed
  }
  return { ok: true }
}

// Append any NOT-yet-projected __commit__ frames into the FirehoseSequencer, in seq order. Idempotent
// (only entries with seq > sequencer.length). Deterministic across devices (same __commit__ order).
async function projectFirehose (device, seq, log = null) {
  if (!log) log = await device.firehoseLog() // seq-ordered
  for (let i = seq.length; i < log.length; i++) {
    const write = deserializeEntry(log[i])
    // `time` comes from the frame the SIGNER recorded in the shared __commit__ log, so it is a real
    // wall-clock instant AND identical on every device (all reading one replicated fact). Frames
    // written before that field existed fall back to deriving it from the rev — correct for those,
    // because their revs WERE wall-clock TIDs. Deriving it from a deterministic prev+1µs rev chain
    // would freeze `time` near the first commit and drift ever further into the past, which relays
    // read as staleness. Frame metadata only — never part of the signed commit.
    await seq.sequenceCommit(write, { time: log[i].time || revTime(log[i].rev) })
  }
}

// Deterministic ISO time from a TID rev (13-char base32-sortable, micros since epoch in the high bits).
function revTime (rev) {
  try {
    const A = '234567abcdefghijklmnopqrstuvwxyz'
    let n = 0n
    for (const ch of String(rev)) n = (n << 5n) | BigInt(A.indexOf(ch))
    const micros = n >> 10n // drop the 10-bit clock id
    return new Date(Number(micros / 1000n)).toISOString()
  } catch { return new Date(0).toISOString() }
}

// serveMembrane — project the stores + PUSH the announce + replicate the corestore over `swarm`.
// Mirrors peer.serve: joins the DID discovery topic + the serverKey topic; on connect, replicates
// the corestore and pushes an announce. Call `sync()` after new signs to project the latest state.
// `projectRepoCore` (default true) — when FALSE the membrane-repo Hyperbee is never opened and
// projectRepo never runs, so record bytes exist ONLY as the content-addressed files. Consumers then
// read the repo via the `get-repo-car` RPC above (derived on demand) or, when co-located, straight off
// the shared overlay files. This is SPEC §6.3's "the virtual device holds nothing".
//
// It is an OPTION rather than a deletion because the announce contract still carries `repoKey`, and
// atproto-did-peer's onAnnounce/holds/_announceTo all gate on it — a peer that stops projecting is
// simply not fronted by an unpatched consumer. Flipping this to false is therefore a COORDINATED
// change with the consumer; shipping the flag first lets the derive-on-read surface land with zero
// behavioural change and be verified in place before anything is removed.
export async function serveMembrane (device, { corestore, swarm, did, handle, sessions = null, blobs = null, projectRepoCore = true } = {}) {
  if (!corestore || !swarm || !did) throw new Error('serveMembrane: corestore, swarm, did required')
  // Step markers. This function is `await`ed during a DID's boot, so anything slow here stalls the whole
  // node — and on a phone it stalled with NO output at all, leaving "somewhere inside serveMembrane" as
  // the entire diagnosis. Each step is cheap and local on a workstation; the point is that when one is
  // not, the log says WHICH. Timed, because "slow" and "wedged" look identical from outside.
  const t0 = Date.now()
  const step = (msg) => { try { console.log(JSON.stringify({ msg: 'membrane: ' + msg, did, ms: Date.now() - t0 })) } catch {} }
  const repo = projectRepoCore ? await new RepoStore(corestore, { name: 'membrane-repo:' + did }).ready() : null
  step(projectRepoCore ? 'repo core ready' : 'repo core SKIPPED (virtual device)')
  const seq = await new FirehoseSequencer(corestore.get({ name: 'membrane-firehose:' + did })).ready()
  step('firehose sequencer ready')
  // Project ONLY when the device's __commit__ log has advanced past what the membrane firehose already
  // holds. WITHOUT this gate, the caller's sign loop (every signIntervalMs, ~2s) called sync()
  // UNCONDITIONALLY, and projectRepo re-put ALL records into the APPEND-ONLY Hyperbee repo core on EVERY
  // tick — even with zero new commits — growing it ~one record-set / 2s → 1.3M blocks / GB in hours, a
  // runaway storage+CPU leak (favela then re-replicates the bloated core at ~100 MB/s). projectFirehose
  // was already incremental; projectRepo was not. After a full projection seq.length === log.length, so
  // `log.length <= seq.length` means there is nothing new to project — skip both (read-only, no writes).
  // Freshness is a REV comparison, not a length comparison.
  //
  // The old gate was `if (log.length <= seq.length) return`, which silently assumes the __commit__ log
  // only ever GROWS. After a base rebuild / resync the log RESTARTS SHORTER, so a node carrying an old
  // membrane (say 83 frames) with a fresh log (say 49) satisfies 49 <= 83 and NEVER PROJECTS AGAIN — it
  // advertises a pre-rebuild head forever while its device head is current. Observed live: a wj62
  // co-owner stuck at rev 3mr436gzyts22 for four days, still announcing, so the bridge could pick it as
  // a front and serve a REV REGRESSION to the relay (which parks a forward-only cursor).
  //
  // Deliberately NOT auto-repaired here. The membrane firehose is an append-only core that consumers
  // replicate; appending the new log's frames after the stale ones would put a rev REGRESSION mid-stream
  // — worse than freezing. A correct repair re-bases onto a NEW core (consumers already re-front on a
  // key change) or emits #sync, and that is a deliberate change, not something to do inside a sync tick.
  // What this DOES do is make it loud, once, naming the DID and both revs — the condition was previously
  // invisible from every surface, which is why it survived four days.
  let staleWarned = false
  let driftWarnedAt = null // the head rev we last refused to project — re-report when the head moves
  // The head rev at which this process last VERIFIED the repo core against the firehose head. The
  // anti-balloon guard below used to skip on `log.length === seq.length` alone, which also skipped the
  // only thing that can notice an ALREADY-INCONSISTENT pair — so a core polluted by the old live-view
  // projection (every deployed node, today) would keep 500ing until a new frame happened to arrive, and
  // an idle DID would never heal at all. Verifying once per head instead of once per new frame means the
  // first sync after a deploy repairs it, and steady state stays free (the check is skipped the moment
  // this head is known good). Nothing else writes the core, so a verified head cannot go bad underneath us.
  let verifiedAt = null
  const sync = async () => {
    const log = await device.firehoseLog()
    if (!log.length) return
    const logHeadRev = log[log.length - 1].rev
    if (log.length < seq.length) {
      if (!staleWarned) {
        staleWarned = true
        console.error(JSON.stringify({
          msg: 'membrane STALE — the __commit__ log restarted shorter than the projected firehose (base rebuild/resync). This node advertises a PRE-REBUILD head and must not be fronted; it needs a membrane re-base, not an append.',
          did, logLength: log.length, membraneLength: seq.length, logHeadRev
        }))
      }
      return
    }
    // Fully projected AND already verified at this head — nothing to do (the anti-balloon guard).
    if (log.length === seq.length && verifiedAt === logHeadRev) return
    // The repo core is brought to the head frame's record set FIRST, and the firehose is advanced ONLY
    // if that succeeded — the two cores are a pair a consumer reads together, so they advance together
    // or not at all. Skipped entirely when the repo core is off (the stateless virtual device derives
    // its CAR on demand instead, so there is no pair to keep).
    const projection = repo ? await projectRepoFrames(repo, log, seq.length) : { ok: true }
    if (!projection.ok) {
      if (driftWarnedAt !== logHeadRev) {
        driftWarnedAt = logHeadRev
        console.error(JSON.stringify({
          msg: 'membrane projection REFUSED — the repo core cannot be made to match the record set the log head commits to, so NEITHER core advanced: the previously-served head stays CONSISTENT (degraded) instead of 500ing every read. A co-owner that can reconstruct this head should be fronted instead.',
          did, reason: projection.reason, logLength: log.length, membraneLength: seq.length, logHeadRev
        }))
      }
      return
    }
    verifiedAt = logHeadRev
    // No-op when the firehose is already at the log head (the repo-only reconcile above) — its loop
    // runs from seq.length to log.length.
    await projectFirehose(device, seq, log)
  }
  await sync()

  const serverKey = b4a.toString(swarm.keyPair.publicKey, 'hex')
  const repoKey = repo ? b4a.toString(repo.core.key, 'hex') : null
  const firehoseKey = b4a.toString(seq.core.key, 'hex')
  const onconn = (conn) => {
    corestore.replicate(conn)
    const rpc = new ProtomuxRPC(conn, { protocol: RPC_PROTOCOL, valueEncoding: c.json })
    // ANNOUNCE-PUSH (atproto/did-announce/v1) is the SOLE discovery path — PUSH {repoKey,firehoseKey,
    // lengths} on connect + on each new firehose commit, so a DidPeer consumer learns the cores with NO
    // round-trip, NO serverKey directionality (get-coords was removed after the bridge cut over). The
    // rpc above stays for the write/session/blob relay. Shares this connection's protomux (one mux per
    // conn, keet model). See atproto-bridge lib/did-peer.js + lib/peer-router.js.
    try {
      const achan = Protomux.from(conn).createChannel({ protocol: ANNOUNCE_PROTOCOL })
      if (achan) {
        const amsg = achan.addMessage({ encoding: c.json, onmessage: () => {} })
        achan.open()
        // repoKey/repoLength are null when the repo core is off — a consumer that requires them simply
        // does not front this peer (it keeps using a co-owner that still projects), which is the
        // graceful degradation that makes the flag safe to roll out one node at a time.
        const pushAnnounce = () => { try { amsg.send({ did, handle: handle || null, repoKey, firehoseKey, repoLength: repo ? repo.core.length : null, firehoseLength: seq.core.length }) } catch {} }
        pushAnnounce()
        const onapp = () => pushAnnounce()
        seq.core.on('append', onapp)
        conn.on('close', () => { try { seq.core.off('append', onapp) } catch {} })
      }
    } catch {}
    // get-repo-car (com.atproto.sync.getRepo, DERIVED) — the stateless replacement for the
    // membrane-repo projection core. device.exportCar() rebuilds the MST + CAR from the record FILES on
    // demand and asserts the rebuilt data root equals the signed head's, so it serves nothing that does
    // not match its own signature. Nothing is stored to answer this.
    //
    // WHY: projectRepo copies EVERY record into an append-only Hyperbee (membrane-repo:<did>), which a
    // consumer then replicates again — so record bytes live three times (files, this core, the
    // consumer's replica) for data the files already hold. SPEC-atproto-overlay-storage §6.3: "the
    // virtual device stores nothing of its own — it derives." This is that surface. PUBLIC, like
    // get-blob: a repo CAR is public atproto data and is self-verifying against the DID key.
    rpc.respond('get-repo-car', async () => {
      const r = await device.exportCar()
      return { car: b4a.toString(r.carBytes, 'hex'), commitCid: r.commitCid, dataCid: r.dataCid, rev: r.rev, recordCount: r.recordCount }
    })
    // get-blob (com.atproto.sync.getBlob) — PUBLIC: atproto blobs are public bytes addressed by CID.
    // Blobs live in the PEER's BlobStore; the keyless bridge relays this RPC (peer-front.getBlob) and
    // streams the bytes back. null → the bridge answers 404. bytes are hex in the c.json RPC value.
    if (blobs) {
      // list-blobs (com.atproto.sync.listBlobs) — PUBLIC, same reasoning as get-blob: it returns content
      // addresses this peer already serves by CID, so it grants no access get-blob does not.
      //
      // ⛔ THIS SURFACE IS THE ONE THE BRIDGE TALKS TO. hpp's serve-device.js has a SEPARATE responder
      // list, and adding the method only there produced exactly the confusing symptom you would expect:
      // getBlob worked, listBlobs answered UNKNOWN_METHOD, and the deployed tree demonstrably contained
      // the handler. Two surfaces, one patched. Keep them in step.
      rpc.respond('list-blobs', async ({ limit, cursor } = {}) => {
        if (typeof blobs.list !== 'function') return { cids: [], cursor: null, skipped: 'not-supported' }
        return blobs.list({ limit, cursor })
      })
      rpc.respond('get-blob', async ({ cid } = {}) => {
        if (!cid) return null
        const b = await blobs.get(String(cid))
        return b ? { mimeType: b.mimeType, size: b.size, bytes: b4a.toString(b.bytes, 'hex') } : null
      })
    }
    // bsky-login relay: the bridge relays com.atproto.server.createSession/refreshSession here (it is
    // keyless — the PEER verifies the app-password + mints/verifies tokens). Same channel + protocol
    // the single-tenant peer served on (lib/peer.js _attachRpc). Gated on sessions being configured.
    if (sessions && sessions.canLogin) {
      rpc.respond('create-session', async (params) => sessions.createSession(params))
      rpc.respond('refresh-session', async ({ refreshJwt } = {}) => sessions.refreshSession(refreshJwt))
      // bsky write path: the bridge relays createRecord/putRecord/deleteRecord as apply-write, carrying
      // the caller's access token. The PEER (not the keyless bridge) verifies the token, then appends
      // the intent to the shared log (lease-holder signs later). Returns { uri, cid } for createRecord:
      // the record content CID is computable immediately; the commit rev/seq are not (async sign).
      rpc.respond('apply-write', async (op = {}) => {
        sessions.verifyAccess(op.token) // throws → CHANNEL error → client 401; only a valid access JWT writes
        const { token, action = 'create', collection, rkey, record } = op
        const r = await device.applyWrite({ action, collection, rkey, record })
        const uri = 'at://' + did + '/' + collection + '/' + rkey
        let cid = null
        if (record) cid = cidForBytesSync(dagCbor.encode(record)).toString()
        return { ...r, uri, cid }
      })
      // batch write path (com.atproto.repo.applyWrites) — the bsky composer posts via applyWrites,
      // not always createRecord. The bridge normalizes each write to { action, collection, rkey,
      // record }; we apply them in order + shape the atproto result objects (uri/cid per write).
      rpc.respond('apply-writes', async (op = {}) => {
        sessions.verifyAccess(op.token)
        const results = []
        for (const w of (op.writes || [])) {
          const { action = 'create', collection, rkey, record } = w
          await device.applyWrite({ action, collection, rkey, record })
          if (action === 'delete') { results.push({ $type: 'com.atproto.repo.applyWrites#deleteResult' }); continue }
          const uri = 'at://' + did + '/' + collection + '/' + rkey
          const cid = record ? cidForBytesSync(dagCbor.encode(record)).toString() : null
          results.push({ $type: 'com.atproto.repo.applyWrites#' + (action === 'update' ? 'updateResult' : 'createResult'), uri, cid, validationStatus: 'unknown' })
        }
        return { results }
      })
      // com.atproto.server.getServiceAuth — the peer mints the ES256K token (it holds the key);
      // the keyless bridge attaches it when proxying user-scoped AppView reads. Token-verified.
      rpc.respond('get-service-auth', async (op = {}) => {
        sessions.verifyAccess(op.token)
        return device.getServiceAuth({ aud: op.aud, lxm: op.lxm })
      })
      // private preferences (birthdate etc.) — token-verified; stored on the peer, out of the public repo.
      rpc.respond('get-preferences', async (op = {}) => { sessions.verifyAccess(op.token); return device.getPreferences() })
      rpc.respond('put-preferences', async (op = {}) => { sessions.verifyAccess(op.token); return device.putPreferences(op) })
      // upload-blob (com.atproto.repo.uploadBlob) — token-gated: a logged-in bsky client uploads an
      // avatar/image, the PEER stores it content-addressed + returns the blob ref for the record. bytes
      // are hex in the c.json RPC value (the bridge hex-encodes the raw POST body). See #133 pfp.
      if (blobs) {
        rpc.respond('upload-blob', async ({ bytes, mimeType, token } = {}) => {
          sessions.verifyAccess(token)
          if (!bytes) throw new Error('upload-blob: bytes (hex) required')
          const { cid, size } = await blobs.put(b4a.from(bytes, 'hex'), mimeType || 'application/octet-stream')
          return { cid: cid.toString(), mimeType: mimeType || 'application/octet-stream', size }
        })
      }
    }
  }
  swarm.on('connection', onconn)
  // client:true is load-bearing for holepunch, not just discovery: peer and bridge are both
  // typically firewalled, and a client:false member never punches outbound so its NAT stays shut.
  // Both sides must be client:true to punch simultaneously (see peer.js:serve for the full why).
  const dKey = swarm.join(swarm.keyPair.publicKey, { server: true, client: true })
  const dDid = swarm.join(discoveryTopic(did), { server: true, client: true })
  step('topics joined — serveMembrane returning (the announce flush is the CALLER\'s to await)')
  return {
    repo, seq, serverKey, repoKey, firehoseKey, sync,
    ready: () => Promise.all([dKey.flushed(), dDid.flushed()]),
    close: () => swarm.off('connection', onconn)
  }
}

export { deserializeEntry, projectRepo, projectRepoFrames, projectFirehose, revTime }
// attachPresence — the transport glue for SignerPresence. On a StateBase swarm connection, announce OUR
// member key and learn the PEER's, feeding a SignerPresence so the signer election tracks who is connected.
// Ephemeral by construction — it appends NOTHING to any log; presence lives and dies with the connection.
//
// Mirrors serve-membrane's announce-push channel exactly (`Protomux.from(conn).createChannel` → addMessage →
// open → send), the keet "one mux per connection" model, so it coexists with base.replicate on the same
// stream. The peer's key arrives via onmessage → markPresent; the connection closing → markAbsent (grace).
import Protomux from 'protomux'
import c from 'compact-encoding'

export const PRESENCE_PROTOCOL = 'atproto-room/signer-presence/v1'

// conn: a hyperswarm/replication stream. selfKey: our member key (hex string). presence: a SignerPresence.
// id: an OPTIONAL per-DID channel id (the roomKey buffer). One shared multi-DID daemon connection carries
// several DIDs' presence over ONE mux; protomux keys channels on (protocol, id) (toKey), so distinct ids
// let each DID's presence channel coexist. Without an id every DID collides on (PRESENCE_PROTOCOL, null) and
// createChannel returns null for all but the first → only the first DID's co-owners ever exchange presence
// (the rest each think they're the sole signer → fork). Single-DID callers pass no id (id=null, unchanged).
// Returns a cleanup fn (idempotent). Safe to call on every connection AND to double-attach the same (conn,
// id): protomux returns null on the duplicate, so the 2nd attach is a harmless no-op (the 1st stays live).
// A non-presence peer simply never sends, so it's never marked present (and thus never eligible to sign).
// getHead: optional () => our current signed head rev (a TID string) — announced so the peer's election
// can tell whether WE are caught up (currency). Returns { send(headRev?), close() }: `send` RE-announces
// our head when it changes (the caller wires this to head advances) so a stale head can't mis-elect a
// signer; `close` tears the channel down. (A non-object return would break callers that register `send`.)
export function attachPresence (conn, { selfKey, presence, id = null, getHead = null } = {}) {
  // Returns a DETACH function (call it to tear down — the original contract) with a `.send(headRev)`
  // property for re-announcing our head when it changes. Hybrid so existing callers that use the return
  // as a cleanup fn keep working, while the currency wiring calls `.send`.
  const noop = () => {}; noop.send = () => {}
  if (!conn || !selfKey || !presence) return noop
  const self = String(selfKey)
  let peerKey = null
  let done = false
  const clear = () => { if (peerKey) presence.markAbsent(peerKey) }
  try {
    const chan = Protomux.from(conn).createChannel({ protocol: PRESENCE_PROTOCOL, id })
    if (!chan) return noop // duplicate (protocol,id) on this mux → harmless no-op
    const msg = chan.addMessage({
      encoding: c.json,
      onmessage: (data) => {
        if (!data || !data.key) return
        peerKey = String(data.key)
        presence.markPresent(peerKey) // presence (fires onChange on connect)
        if (data.headRev !== undefined) presence.noteHead(peerKey, data.headRev || null) // currency (fires onChange on a head change)
      }
    })
    chan.open()
    const announce = (headRev) => { try { msg.send({ key: self, headRev: headRev !== undefined ? (headRev || null) : (getHead ? getHead() : null) }) } catch {} }
    announce() // initial announce with our current head
    const onclose = () => { if (done) return; done = true; clear() }
    conn.on('close', onclose)
    const detach = () => { if (done) return; done = true; try { conn.off('close', onclose) } catch {}; clear() }
    detach.send = (headRev) => announce(headRev) // re-announce our head (currency) when it changes
    return detach
  } catch { return noop }
}
// SignerPresence — leak-free single-active-signer election from live CONNECTION PRESENCE.
//
// Replaces the `__lease__ {holder,epoch,ts}` heartbeat (lease.js), which wrote a fresh wall-clock ts to the
// APPEND-ONLY autobase log every ~8s forever (~20MB/day, unreclaimable — see the S1 research). Keet, and
// every other holepunch app, signals liveness EPHEMERALLY over the connection and never persists it. This is
// that idiom: "which device signs" is a deterministic function of who is CONNECTED right now, computed in
// RAM. It appends NOTHING.
//
// Election = the lowest-keyed device among the currently-effective co-owners (a stable, replication-free
// tiebreak every connected peer computes identically → they agree on one signer → only one signs → no fork,
// exactly the guarantee the ts-lease gave in the connected case). A partition still diverges and reconciles
// on merge — identical to the old lease, which also forked on partition (the epoch never prevented that).
//
// GRACE window = blip tolerance: a departed holder stays "effective" for graceMs before failover, so a brief
// disconnect does not thrash the signer (mirrors the old lease's "never steal a live lease for TTL"). Default
// graceMs matches the old ttlMs (15s) so failover timing is unchanged.
//
// Presence is fed by the transport (a co-owner presence handshake on the StateBase swarm): markPresent on
// connect+identify, markAbsent on close. This module is pure + clock-injectable → unit-testable with no swarm.

export class SignerPresence {
  // self: this device's member key (hex). graceMs: how long a departed co-owner stays eligible (blip
  // tolerance / failover delay). clock: injectable now() for deterministic tests.
  // onChange: fired on an ACTUAL presence change (a co-owner connected or departed) — the EVENT that
  // drives zero-timer failover: the daemon re-evaluates holdsSigner + signs on this, plus on every
  // StateBase advance (sb.watch), so no polling timer is needed. Grace expiry itself has no event (a
  // write/replication/presence event after grace picks it up — acceptable failover latency, no loss).
  constructor ({ self, graceMs = 15000, clock = () => Date.now(), onChange = null } = {}) {
    if (!self) throw new Error('SignerPresence: self (this device member key) required')
    this.self = String(self)
    this.graceMs = graceMs
    this.clock = clock
    this.onChange = onChange
    this._present = new Map() // memberKey -> lastSeen: Infinity = connected now; a number = ms it departed
    this._present.set(this.self, Infinity) // we are always present to ourselves
    // CURRENCY (anti-freeze): each co-owner's last-announced signed head rev (a monotonic TID string) or
    // null if unknown. A BEHIND co-owner must not win the election — else it holds the lease but the
    // forward-only sign gate blocks it (it's behind) while the caught-up peer defers to it → the chain
    // FREEZES (the stortron split-brain aftermath). currentSigner filters on this vs the network head.
    this._heads = new Map() // memberKey -> headRev (string) | null
  }

  _fire () { if (this.onChange) { try { this.onChange() } catch {} } }

  // A co-owner (holds the signing key + is attested) is connected. Idempotent. Fires onChange only on
  // an actual transition (not-present/departed -> present) so the daemon re-evaluates the signer.
  markPresent (memberKey, headRev = undefined) {
    const k = String(memberKey)
    if (headRev !== undefined) this._heads.set(k, headRev || null) // learn the peer's signed-head currency
    if (this._present.get(k) === Infinity) return // already connected — no change
    this._present.set(k, Infinity)
    this._fire()
  }

  // Record OUR OWN current signed head rev (from the sign loop) so the election knows we're caught up.
  setSelfHead (rev) { this._heads.set(this.self, rev || null) }
  // Record a co-owner's announced signed head rev (from the presence channel). Fires onChange when the
  // currency changes (a peer catching up may flip who is the elected signer → re-evaluate).
  noteHead (memberKey, rev) {
    const k = String(memberKey)
    const prev = this._heads.get(k)
    if (prev === (rev || null)) return
    this._heads.set(k, rev || null)
    this._fire()
  }
  headOf (memberKey) { const v = this._heads.get(String(memberKey)); return v === undefined ? null : v }

  // A co-owner disconnected — start its grace countdown (do NOT drop it immediately; a blip must not fail
  // the signer over). No-op for a key we never saw. Fires onChange so a departure is noticed event-driven.
  markAbsent (memberKey) {
    const k = String(memberKey)
    if (this._present.has(k) && this._present.get(k) === Infinity) { this._present.set(k, this.clock()); this._fire() }
  }

  // The co-owners eligible to sign right now: connected, or departed within graceMs. Sorted (stable pick).
  effective (now = this.clock()) {
    const out = []
    for (const [k, seen] of this._present) if (seen === Infinity || (now - seen) < this.graceMs) out.push(k)
    return out.sort()
  }

  // The elected signer = lowest-keyed effective co-owner (every connected peer computes the same one).
  // CURRENCY-AWARE (anti-freeze): when netHead is given, a co-owner is only eligible if its known signed
  // head is caught up to netHead (headRev >= netHead; revs are monotonic TID strings, null = unknown =
  // not caught up). This EXCLUDES a behind co-owner so it can't hold the lease while the forward-only
  // gate blocks it → the caught-up peer signs instead. If NONE are known-caught-up (no currency info
  // yet), fall back to the lowest-key effective co-owner — the forward-only sign gate still prevents any
  // behind sign, so the worst case is a transient no-op, never a regression. Deterministic: every peer
  // computes the same signer from the same (presence, announced-heads, netHead) → still exactly one signer.
  currentSigner (now = this.clock(), netHead = null) {
    const e = this.effective(now)
    if (!e.length) return null
    if (!netHead) return e[0]
    const caughtUp = e.filter((k) => { const h = this._heads.get(k); return h != null && h >= netHead })
    return caughtUp.length ? caughtUp[0] : e[0]
  }

  // Do WE hold the signer role right now? (Drop-in for lease.holds() / renewOrClaim() in the sign loop.)
  holds (now = this.clock(), netHead = null) { return this.currentSigner(now, netHead) === this.self }

  // Diagnostics snapshot (no writes).
  state (now = this.clock(), netHead = null) {
    return { self: this.self, signer: this.currentSigner(now, netHead), effective: this.effective(now), holds: this.holds(now, netHead), heads: Object.fromEntries(this._heads) }
  }
}
// Signer — the lease-holder's job: materialize the linearized repo-op view into ONE canonical
// signed atproto commit. This is the "one net-new consumer" of the reskin: it turns the shared
// autobase's linearized record set into the single-writer signed commit chain the atproto world
// consumes. Signing uses the SHARED #atproto key; because ECDSA here is RFC6979-deterministic,
// any lease-holder that signs the same linearized view + rev/prev produces byte-identical output.
//
// This slice owns ONLY the pure materialize step (record set → signed commit). Chain advancement
// (monotonic rev, prev = last head), firehose emission, and lease-gating are wired in later slices.

import * as dagCbor from '@ipld/dag-cbor'
import { buildMst, firehoseProofBlocks } from 'atproto-repo/lib/mst.js'
import { unsignedCommit, signCommit, commitCid } from 'atproto-repo/lib/commit.js'
import { cidForBytesSync } from 'atproto-repo/lib/cid.js'

// records: [{ collection, rkey, record }] — the linearized view (e.g. RepoBase.listRecords()).
// meta: { did, rev, prev=null, privateKey } — the shared #atproto signing key + chain position.
// Returns the signed commit + its CID + the MST data CID + the record blocks (canonical bytes).
export function materialize (records, { did, rev, prev = null, privateKey }) {
  if (!did || !rev || !privateKey) throw new Error('materialize: did, rev, privateKey required')
  const mstRecords = []
  const recordBlocks = []
  for (const { collection, rkey, record } of records) {
    const bytes = dagCbor.encode(record) // canonical DAG-CBOR (content-addressed → preserves record CID)
    const cid = cidForBytesSync(bytes)
    mstRecords.push({ key: collection + '/' + rkey, value: cid })
    recordBlocks.push({ cid, bytes })
  }
  // MST is defined over keys in sorted order — sort so the data root is deterministic regardless
  // of the view's iteration order.
  mstRecords.sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0))
  const { root: dataCid } = buildMst(mstRecords)
  const signed = signCommit(unsignedCommit({ did, rev, data: dataCid, prev }), privateKey)
  return { signedCommit: signed, commitCid: commitCid(signed), dataCid, recordBlocks }
}

// buildCommitWrite — turn a view DIFF (before -> after record sets) into the atproto firehose
// `#commit` write: the signed commit + the MINIMAL Sync-v1.1 covering proof (created |
// deletion_proof | inductive_proof), NOT the whole tree. This is the frame a membrane reads to
// project the swarm to bsky (keyless). Shape matches atproto-store's commitFrame(write, …). The
// lease-holder calls this each sign; because the proof is over the diff, a cold relay can invert
// it with no old-tree state. before/after: [{collection, rkey, record}]. caller supplies chain
// position (prev = last commit CID, since = last rev); prevData is derived from `before`.
export function buildCommitWrite (before, after, { did, rev, prev = null, since = null, privateKey }) {
  if (!did || !rev || !privateKey) throw new Error('buildCommitWrite: did, rev, privateKey required')
  const enc = (recs) => {
    const m = new Map()
    for (const { collection, rkey, record } of recs) {
      const bytes = dagCbor.encode(record)
      m.set(collection + '/' + rkey, { cid: cidForBytesSync(bytes), bytes })
    }
    return m
  }
  const oldM = enc(before)
  const newM = enc(after)

  // diff -> repoOps (create | update | delete). Record blocks travel only for create/update.
  const ops = []
  const opBlocks = []
  for (const [key, { cid, bytes }] of newM) {
    const old = oldM.get(key)
    if (!old) { ops.push({ action: 'create', path: key, cid }); opBlocks.push({ cid, bytes }) } else if (!old.cid.equals(cid)) { ops.push({ action: 'update', path: key, cid, prev: old.cid }); opBlocks.push({ cid, bytes }) }
  }
  for (const [key, { cid }] of oldM) if (!newM.has(key)) ops.push({ action: 'delete', path: key, cid: null, prev: cid })

  const toMst = (m) => [...m.entries()].map(([key, { cid }]) => ({ key, value: cid }))
  // firehoseProofBlocks asserts the covering proof INVERTS to oldRoot (throws otherwise) — so a
  // successful return is itself proof the frame is relay-invertible.
  const proof = firehoseProofBlocks({ oldRecords: toMst(oldM), newRecords: toMst(newM), ops })
  const signed = signCommit(unsignedCommit({ did, rev, data: proof.dataCid, prev }), privateKey)
  const cc = commitCid(signed)
  return {
    commitCid: cc,
    commitBlock: { cid: cc, bytes: dagCbor.encode(signed) },
    signedCommit: signed,
    dataCid: proof.dataCid,
    prevData: proof.oldRoot,
    rev,
    since,
    ops,
    newBlocks: [...proof.blocks.values(), ...opBlocks]
  }
}
/**
 * state-base.js — StateBaseV3: attestation-gated, encrypted multi-writer room (HyperDB view).
 *
 * The core substrate of atproto-room: an Autobase whose view is a HyperDB instance; ops are
 * hyperdispatch-encoded and routed through a generated Router to handlers that write into HyperDB
 * collections inside a per-apply transaction. Admission is cryptographic + in-apply (a joiner
 * appends an optimistic block carrying a keet attestation proof; apply verifies it resolves to a
 * device attested to the room's root identity + a projected role, then addWriters) — NOT
 * owner-mediated. The base key is derived deterministically from the room's members-only
 * encryptionKey and opened encrypted, so non-members can neither derive nor read it.
 *
 * Lineage: originally reskinned from keet-daemon/hyper-tps's per-room gamestate StateBaseV3;
 * extracted here as the shared room engine consumed by hyper-proto-peer (repo devices) and the
 * co-authored labeler. The class name StateBaseV3 is preserved to avoid churn across consumers.
 */

import Corestore from 'corestore'
import Autobase from 'autobase'
import Hypercore from 'hypercore'
import Verifier from 'hypercore/lib/verifier' // encodeManifest/decodeManifest for the keet-writer admission proof (A)
import Hyperswarm from 'hyperswarm'
import HyperDB from 'hyperdb'
import crypto from 'hypercore-crypto'
import fs from 'bare-fs'
import path from 'bare-path'
import process from 'bare-process'

import hyperdbDefinition from '../spec/state-base/contract/hyperdb/index.js'
import dispatch from '../spec/state-base/contract/hyperdispatch/index.js'
import { SignerPresence } from './signer-presence.js'
import { attachPresence } from './signer-presence-channel.js'

const { Router, encode } = dispatch

const STATE_VERSION = 3
// Key-derivation namespace. Renamed from the legacy 'hyper-tps/state/v3' (its keet/hyper-tps
// lineage) to 'atproto-room/state/v3' on the extraction. This is LOAD-BEARING: deriveGsKeyPair
// mixes it into the room's base key, so the rename yields a fresh base key for every room. Existing
// rooms are carried across by the re-adopt migration (the writable creator re-seeds the DID's repo
// records from the adopt bundle; the signed atproto chain continues from the adopted head — see
// hyper-proto-peer device-node.js bootSwarmDevice). Never change this string again without a
// migration story.
const GS_NAMESPACE = Buffer.from('atproto-room/state/v' + STATE_VERSION, 'utf-8')
// The pre-extraction namespace. A room created before the 'hyper-tps/state/v3' -> 'atproto-room/
// state/v3' rename derives its base key from this string. Kept solely so the one-time in-place
// re-adopt migration (_migrateFromLegacyNamespace) can open such a room and seed the renamed one.
const LEGACY_GS_NAMESPACE = Buffer.from('hyper-tps/state/v' + STATE_VERSION, 'utf-8')
const ENTRIES = '@state/entries'
// Reserved op key: a designated admin anchor claims the SOLE indexer slot
// (move-indexer). Carried as the `key` of an optimistic admit op; never inserted.
const MOVE_INDEXER = '__move_indexer__'
// Reserved op key: an admin GROWS the indexer set by adding ITSELF as an indexer
// (keet members/index.js op D `start-indexing`) — NO demote of anyone. This is the
// quorum-resilience path: with >=3 admin-indexers, autobase majority quorum
// ((n>>>1)+1, consensus.js:15) finalizes even when the genesis/creator is offline.
// Proven by test/probe-indexer-quorum.mjs (autobase 7.28.1 holds >2 indexers fine).
const START_INDEXING = '__start_indexing__'
// Reserved op key: BAN a device (atproto-base-REVOCATION.md §3/§6). Value = the target device's
// keet identity hex. Only a role-1 member may issue. Records the target in the durable REMOVED_SET,
// drops it from __members__, and removeWriters its writer(s) — so it can neither write now nor
// re-admit later (the Keet handleRemoveMember + add-guard mechanism). Never inserted as an entry.
const REMOVE_DEVICE = '__remove_device__'
// Reserved op key: ADMIT a member into the room, authored by an EXISTING role-1 member. Value =
// JSON { id: <keet identity hex>, role }. This is keet's addDevice/acceptJoinRequest shape — the room
// decides who belongs, and an existing member writes that decision INTO the room.
//
// It replaces the only mechanism we had: `projectMembers`, which reprojects a roster read from the
// CREATOR's local config file. That made membership a per-machine fact — a co-owner could not admit
// anyone (tabertron sits at rosterLen:0, membersProjected:false and is structurally unable to help),
// and growing a roster on the wrong box did nothing at all (hyper-social #40 §6). Authorization is the
// AUTHOR's role verified in apply, exactly like REMOVE_DEVICE below, so a non-member cannot use it to
// admit itself or anyone else.
//
// A BANNED identity is NOT re-admitted by this op — REMOVED_SET stays authoritative, or a ban would be
// reversible by any member simply re-adding the target. Un-banning is deliberately a separate act.
const ADD_MEMBER = '__add_member__'
// Room ABI. Bumped when an op changes what APPLY does, because apply must be deterministic across
// every node or their views diverge. ADD_MEMBER is exactly such a change: a node that predates it does
// not treat `__add_member__` as reserved, so it INSERTS it as an ordinary entry while a current node
// inserts nothing — same log, two different views. Keet gates this class of change with an in-band ABI
// stamp and refuses to proceed under an unsupported one (skills/keet-abi-upgrades; pear-git-v3 does the
// same for its org schema). We cannot retrofit old nodes, so the gate is on the AUTHOR: refuse to emit
// an op no current writer can apply identically.
const ROOM_ABI = 1
// Per-writer capability stamp: `__abi__/<writer key hex>` -> { v }. An ORDINARY entry, deliberately —
// old nodes store it byte-identically and stay convergent; they simply never write one of their own,
// which is precisely the signal we need.
const ABI_PREFIX = '__abi__/'
// Durable set of banned device identities (hex → { ts }). The admission guard checks it so a
// removed identity cannot (re)admit even with a valid attestation.
const REMOVED_SET = '__removed__'
// Reserved op key: set the MINIMUM attestation epoch (value = a keet receipt, hex). Only a role-1
// member may issue. Admission rejects any attestation whose epoch is below it — bump it + re-attest
// survivors to invalidate ALL stale proofs at once (atproto-base-REVOCATION §3). Never inserted.
const SET_EPOCH = '__set_epoch__'
// Durable current minimum-epoch receipt (hex). Absent → no epoch restriction.
const RECEIPT_KEY = '__receipt__'

function toBuf (k) {
  if (Buffer.isBuffer(k)) return k
  const s = String(k)
  return /^[0-9a-fA-F]{64}$/.test(s) ? Buffer.from(s, 'hex') : Buffer.from(s)
}
// Normalize an identity key to lowercase hex (members keys arrive 64-hex from
// router._stateBaseProviders, which z32-decodes memberIds to hex).
function normKeyHex (k) {
  if (!k) return null
  if (Buffer.isBuffer(k)) return k.toString('hex')
  const s = String(k)
  return /^[0-9a-fA-F]{64}$/.test(s) ? s.toLowerCase() : s
}
// Order-insensitive equality for the small hex->value maps projected into the view (__members__ /
// __devices__), so a re-projection only APPENDS when the view would actually change. Every append
// grows the log forever, and these run on a timer + on every swarm connection.
function sameMap (a, b) {
  const ka = Object.keys(a || {}).sort(); const kb = Object.keys(b || {}).sort()
  if (ka.length !== kb.length) return false
  for (let i = 0; i < ka.length; i++) { if (ka[i] !== kb[i] || String(a[ka[i]]) !== String(b[kb[i]])) return false }
  return true
}
function deriveGsKeyPair (roomSeed, ns = GS_NAMESPACE) { return crypto.keyPair(crypto.hash([ns, toBuf(roomSeed)])) }
function deriveBaseKey (gsPublicKey) { return Hypercore.key({ version: 1, signers: [{ publicKey: gsPublicKey }] }) }

// Router → instance handlers (need instance state for admission). ctx carries
// { tx, base, node, sb }. LWW-by-ts; D1b admission on optimistic writes.
function makeRouter () {
  const r = new Router()
  r.add('@state/set-entry', (rec, ctx) => ctx.sb._applySet(rec, ctx))
  r.add('@state/del-entry', (rec, ctx) => ctx.sb._applyDel(rec, ctx))
  return r
}

export class StateBaseV3 {
  constructor (storagePath, roomKey, opts = {}) {
    this._roomKey = Buffer.isBuffer(roomKey) ? roomKey : Buffer.from(String(roomKey), 'hex')
    if (this._roomKey.length !== 32) throw new Error('roomKey must be 32 bytes (or 64-char hex)')
    this._roomKeyHex = this._roomKey.toString('hex')

    // Distinct v3 path — v2 'state-bases/' is left untouched (clean cutover). Null when a shared
    // Corestore is injected (opts.store, multi-DID): storage is a namespace of the daemon's store,
    // so there is no per-room dir.
    this._storagePath = storagePath ? path.join(storagePath, 'state-bases-v3', this._roomKeyHex) : null
    this._network = opts.network !== false
    this._swarmOpts = opts.swarmOpts || null
    // Designated always-on anchor: on open, claim the SOLE indexer slot via
    // move-indexer so the room finalizes even when the creator is offline.
    this._claimIndexer = !!opts.claimIndexer
    // Indexer eligibility (issue #133 — indexing≠signing). The creator opens AS the bootstrap sole
    // indexer; a regular 2nd device must stay a PLAIN WRITER (making every admin an indexer creates
    // the N=2 quorum trap — majority 2, zero fault tolerance, can't self-heal). Only a DESIGNATED
    // indexer self-promotes: an always-on anchor (opts.claimIndexer/opts.indexer). Default: off.
    this._indexerEligible = !!opts.indexer

    // P3 (#103): admins self-promote to indexers not just at open but whenever their
    // keet role changes at runtime (member→admin), driven by a low-frequency retry
    // timer. _promoteRetryMs = how often to re-check; _promoting guards overlapping
    // runs (timer + projectMembers can race). Q7 (#103): _maxIndexers bounds the
    // ACTUAL indexer set so a large admin room doesn't push the majority-quorum
    // threshold so high that finalization gets fragile — admins past the cap stay
    // plain writers (still admitted, still write; they just don't index).
    this._promoteRetryMs = Number(opts.promoteRetryMs) || Number(process.env.KEET_PROMOTE_RETRY_MS) || 30000
    this._maxIndexers = Number(opts.maxIndexers) || Number(process.env.KEET_MAX_INDEXERS) || 5
    this._promoting = false
    this._promoteTimer = null
    this._promoteFutileLogged = false

    // Membership context. selfKey (this daemon's keet identity pubkey) drives the
    // deterministic creator election; it comes from router._stateBaseProviders as
    // `selfKey` (a 32-byte pubkey), NOT a keypair. selfKeyPair is optional (kept
    // for v3.0b signing). CRITICAL: without a real selfKey the election would
    // default amCreator=true on every daemon → multiple genesis → split-brain.
    this._selfKeyPair = opts.selfKeyPair || null
    this._selfKey = opts.selfKey
      ? toBuf(opts.selfKey)
      : (this._selfKeyPair ? toBuf(this._selfKeyPair.publicKey) : null)
    // Leak-free single-signer election from live CONNECTION PRESENCE (replaces the __lease__ ts-heartbeat,
    // which appended to the log every ~8s forever). self = our member key; graceMs = failover blip-tolerance
    // (default matches the old lease TTL). Fed by attachSignerPresence() on each swarm connection; the sign
    // loop reads holdsSigner(). Null when we have no member identity (read-only opens).
    // onChange routes a presence change (co-owner connect/disconnect) through the SAME watcher fan-out
    // as a view advance, so a single sb.watch(tick) drives ZERO-TIMER failover: the daemon re-evaluates
    // holdsSigner + signs on writes, replication, AND presence events — no polling timer.
    this._presence = this._selfKey ? new SignerPresence({ self: this._selfKey.toString('hex'), graceMs: Number(opts.signerGraceMs) || 15000, onChange: () => this._fireWatchers() }) : null
    this._selfHead = null // our current signed head rev — announced over presence so a BEHIND co-owner is
    this._presenceSenders = new Set() // excluded from the election (anti-freeze); re-announced on head change
    this._getMembers = typeof opts.getMembers === 'function' ? opts.getMembers : null
    // RESYNC heal (force-non-creator): open as a NON-creator even when we're the lowest-key member, so a
    // fresh-corestore re-join gets a FRESH (primaryKey-derived) local writer instead of re-opening the
    // deterministic _gsKeyPair genesis writer (which a fresh store cannot shed and autobase will not
    // linearize when backfilled — see _open + hyper-proto-peer resync). Mirrors keet: a device that lost
    // its store re-joins as a NEW random writer via the doorbell (keet-core pairing/keys.js), never the
    // old writer. Set on a resync boot only (device-node.js passes forceNonCreator: !!resyncStore).
    this._forceNonCreator = opts.forceNonCreator === true
    // forceCreator (assume-genesis heal): the healthy co-owner re-assumes the deterministic genesis
    // writer/indexer after the original creator abandoned it via a resync — see _open. Mutually exclusive
    // with forceNonCreator; exactly one co-owner holds gsKeyPair at a time.
    this._forceCreator = opts.forceCreator === true
    // Injectable crypto for membership-gated admission (keet attestation primitives).
    // attest: sign localKey‖base.key as our keet identity; verifyAttest: IdentityKey.verify.
    this._attest = typeof opts.attest === 'function' ? opts.attest : null
    this._verifyAttest = typeof opts.verifyAttest === 'function' ? opts.verifyAttest : null
    // Admission model (A): prove control of THIS daemon's keet room writer key, which
    // keet maps (via @keet/devices) to our active member. roomWriterKeyPair signs the
    // proof; roomWriterManifest binds the signer to the writer/device key
    // (deviceKey = Hypercore.key(manifest)). Both come from room.base.local in the
    // router. The verifier re-derives the device key and looks it up in __devices__
    // (deviceKey→memberKey) → __members__ (memberKey→role). See hyper-fleeky-dev #99.
    this._roomWriterKeyPair = opts.roomWriterKeyPair || this._selfKeyPair || null
    this._roomWriterManifest = opts.roomWriterManifest || null

    // Deterministic base identity from the room's members-only secret (v2 design).
    this._roomSeed = opts.roomSeed ? toBuf(opts.roomSeed) : null
    // gsNamespace override: defaults to the current GS_NAMESPACE. The one-time re-adopt migration
    // and tests pass LEGACY_GS_NAMESPACE to open a pre-rename room in place.
    this._gsNamespace = opts.gsNamespace ? toBuf(opts.gsNamespace) : GS_NAMESPACE
    this._gsKeyPair = this._roomSeed ? deriveGsKeyPair(this._roomSeed, this._gsNamespace) : null
    this._detBaseKey = this._gsKeyPair ? deriveBaseKey(this._gsKeyPair.publicKey) : null
    this._encryptionKey = opts.encryptionKey ? toBuf(opts.encryptionKey) : null

    // Multi-DID (multi-tenant) support. An injected SHARED Corestore + shared ProtomuxWakeup let ONE
    // daemon host N DIDs: each StateBase opens on a per-DID NAMESPACE of the one store (one dir, one
    // RocksDB lock, cryptographically-isolated cores) and shares one wakeup — exactly how keet-core
    // fronts N rooms over one corestore/swarm. When opts.store is given, pass network:false too: this
    // StateBase then creates NO Corestore and NO swarm; the daemon owns store+swarm+wakeup and drives
    // `wakeup.addStream(conn); store.replicate(conn)` per connection + swarm.join(sb.base.discoveryKey).
    this._injectedStore = opts.store || null
    this._wakeup = opts.wakeup || null

    this._router = makeRouter()
    this.store = null
    this.base = null
    this.swarm = null
    this._ready = false
    this._closing = false
    this._watchers = new Set()
    // Writer-hex keys we've already admitted via addWriter at apply time. A remote
    // member attaches its `admit` proof to EVERY optimistic write until it observes
    // itself become writable, so without this guard apply re-runs addWriter/ackWriter
    // (and logs) once per op — hundreds of redundant calls per peer. addWriter is
    // idempotent, so de-duping the CALL leaves the writer set identical.
    this._admitted = new Set()
    // Cached "self is an ADMITTED, durable writer of this room": our local writer
    // key (base.local.key) is in the autobase linearized system writer set
    // (base.system). This is the signal `writable` reports — it answers "will my
    // durable writes persist?" correctly: true once an indexer has actually
    // admitted us (at/before base.writable's localWriter activation, so it still
    // covers the post-admission lag), and FALSE for a peer that is merely an
    // eligible room member in __members__ but was never admitted by an indexer
    // (the false-green that keying off __members__ produced — see
    // hyper-fleeky-dev #99: a local identity in the roster but absent from the
    // indexer's membership read writable=true while its writes never finalized).
    this._selfIsAdmittedWriter = false
    // __members__ projection is EVENT-DRIVEN + self-terminating (NOT a bounded give-up loop). The
    // creator retains the roster (set by projectMembers) and re-projects on the promote-timer tick +
    // every new swarm connection until __members__ is confirmed in its view. A creator that becomes
    // writable AFTER boot (re-adopt / swarm flap) therefore still lands __members__ and can admit
    // members — the wj62 fork root was the app's 12-try boot loop giving up before writability settled,
    // so __members__ never landed → every admit verified verifiedRole=null → members held their own
    // lines. See test/admission-members-projection.test.mjs.
    this._roster = null
    this._membersProjected = false
  }

  // ── Lifecycle ──────────────────────────────────────────────
  async ready () {
    if (this._ready) return
    if (this._closing) throw new Error('StateBaseV3 is closing')
    if (this._injectedStore) {
      // Shared-store (multi-DID) path: a per-DID NAMESPACE of the daemon's one Corestore — no new
      // dir, no second RocksDB lock (the root's lock covers every namespace; a 2nd Corestore on the
      // same dir fails to lock, a namespace does not). Proven end-to-end in test/multi-did.test.js
      // (2 DIDs, one lock, encrypted admission over one shared wakeup, isolated).
      this.store = this._injectedStore.namespace(this._roomKeyHex)
    } else {
      fs.mkdirSync(this._storagePath, { recursive: true })
      this.store = new Corestore(this._storagePath)
    }
    await this.store.ready()
    try {
      await this._open()
    } catch (err) {
      if (!this._isCorruptionError(err)) throw err
      // Diagnostic mode: report corruption WITHOUT quarantining (non-destructive
      // probe of live storage). Used by tools/probe-room.mjs.
      if (process.env.KEET_PROBE_NO_QUARANTINE) {
        console.error('[state-base-v3] room=%s CORRUPT (%s) — probe mode, NOT quarantining',
          this._roomKeyHex.slice(0, 12), err.message)
        throw err
      }
      console.error('[state-base-v3] room=%s CORRUPT (%s) — quarantining + restarting',
        this._roomKeyHex.slice(0, 12), err.message)
      await this._quarantineAndReset()
    }
    this._ready = true
    // PROJECT A ROSTER RETAINED BEFORE ready(). projectMembers() called before the base exists can only
    // stash the roster (`if (!this._ready || !this.base || !this.base.writable) return false`), so the
    // actual __members__ append waited for whichever came first: a swarm connection, or a promote-timer
    // tick up to promoteRetryMs later.
    //
    // Under network:false — the multi-DID daemon mode — the connection hook that would drive this lives
    // inside `if (this.swarm)` and NEVER RUNS, leaving only the timer. So __members__ landed late, and a
    // member whose optimistic doorbell arrived first was refused by _verifyAdmissionInApply and never
    // re-rang it: admission silently never happened, while __members__ and _membersProjected both read
    // perfectly healthy afterwards — which is why this looked like a replication or daemon-wiring bug.
    //
    // Measured (test/members-projection-order.test.mjs): projectMembers BEFORE ready() left the member
    // unadmitted; AFTER admitted immediately. Same wiring, same DID count — ordering was the ONLY
    // variable. This makes the two equivalent, which is what callers already assume.
    //
    // Awaited so the roster is in the view before ready() returns, hence before any consumer can wire up
    // connections. A no-op when nothing was retained, when not writable, or when already projected.
    await this._ensureMembersProjected().catch(() => {})
    // NO ABI announce at boot. Writing during _open is the fork hazard this file warns about throughout
    // (the resync/joiner rule is to write NOTHING until replication converges) — and it reproduced here
    // immediately: `[hypercore] conflict detected ... (writable=false,quorum=1)` followed by
    // SESSION_CLOSED inside ApplyState._boot. The stamp is only ever needed when another writer is
    // present to read it, so it is announced on connection and on admission instead.
    // One-time in-place re-adopt migration for the namespace rename: if this is the writable creator
    // and the (renamed) base is empty but a legacy-namespace base is present in the same store, copy
    // its durable entries across. Best-effort + awaited so the room is seeded before consumers read.
    await this._migrateFromLegacyNamespace()
    // Admins/mods AUTO-promote to indexers on open (keet model: admins ARE the
    // indexers — members/index.js addWriter(indexer:isIndexing)). Best-effort +
    // background so it never blocks boot; needs an online indexer to land and
    // retries on the next open. Non-admins are untouched (stay plain writers),
    // so a room's indexer set = its online admins (quorum tolerates the creator
    // dropping once ≥3 admins index).
    this._maybePromote().catch(() => {})
    // P3 (#103): the open-time call above only sees our role AS OF open. An admin
    // GRANTED at runtime (member→admin while the daemon stays up) would otherwise
    // need a full reopen to self-promote — the ashatron footgun. Re-fire on a
    // low-frequency timer so a newly-promoted admin becomes an indexer on its own.
    // Cheap when idle: _maybePromote early-returns once we're a durable indexer or
    // while we're not (yet) an admin. unref so it never keeps the process alive.
    if (!this._promoteTimer) {
      this._promoteTimer = setInterval(() => { this._maybePromote().catch(() => {}); this._ensureMembersProjected().catch(() => {}) }, this._promoteRetryMs)
      if (this._promoteTimer && typeof this._promoteTimer.unref === 'function') this._promoteTimer.unref()
    }
  }

  // A DESIGNATED always-on anchor (opts.claimIndexer) automatically claims the
  // sole indexer slot on open, so the room finalizes (quorum 1) even when the
  // creator is offline. NOT every admin — autobase can't hold many indexers, so
  // only the one designated anchor takes the slot; everyone else stays a plain
  // writer (admitted on first write). Best-effort + background; needs the current
  // indexer online once to sign the handoff, then it's durable in the oplog.
  async _maybePromote () {
    if (this._promoting) return // guard the timer/projectMembers race — one attempt at a time
    this._promoting = true
    try {
      if (!this.base) return
      if (this.base.writable && this._isLocalIndexer() === true) return // already an indexer
      // Non-designated devices NEVER self-promote (the N=2-trap fix, #133). The creator is already
      // the bootstrap sole indexer; a regular 2nd device stays a plain writer (it can still hold the
      // lease + sign — signing needs the #atproto key, NOT indexer status). Only an anchor
      // (claimIndexer / opts.indexer) grows the indexer set. See reference_statebase-indexing-vs-did-signing.
      if (!this._claimIndexer && !this._indexerEligible) {
        if (!this._promoteNonDesignatedLogged) { this._promoteNonDesignatedLogged = true; console.log('[state-base-v3] room=%s NOT self-promoting: non-designated device stays a PLAIN WRITER (N=1 posture; set opts.indexer for an anchor)', this._roomKeyHex.slice(0, 12)) }
        return
      }
      // keet model (members/index.js:137 `isIndexing = canAdmin`): EVERY admin is an
      // indexer, so the set grows to = the online admins and majority quorum tolerates
      // any single node (incl. the genesis creator) dropping. Verify we're an admin
      // (role 1); non-admins stay plain writers. Best-effort + background; needs an
      // online indexer to sign the addWriter (autobase invariant) — retries next open.
      if (this._getMembers && this._selfKey) {
        let members; try { members = await this._getMembers() } catch { members = null }
        const selfHex = this._selfKey.toString('hex')
        const me = Array.isArray(members) ? members.find(m => normKeyHex(m.key || m.devicePubkey || m.identity || m.memberId || m.id) === selfHex) : null
        if (!me || Number(me.role) !== 1) return // non-admin → stays a plain writer
      }
      // Q7 (#103): bound the ACTUAL indexer set. Every admin is ELIGIBLE (keet model),
      // but once the live set has _maxIndexers members we stop growing it — a room with
      // many admins would otherwise push the majority threshold ((n>>>1)+1) so high that
      // a couple of offline indexers stall finalization. Admins past the cap stay plain
      // writers (admitted on their writes; they just don't index). We're not already an
      // indexer here (early-returned above), so a full set means: leave it alone.
      let idxLen = 0; try { idxLen = this.base.linearizer.indexers.length } catch { idxLen = 0 }
      if (idxLen >= this._maxIndexers) {
        console.log('[state-base-v3] room=%s admin NOT self-promoting: indexer set full (%d/%d) — staying a plain writer', this._roomKeyHex.slice(0, 12), idxLen, this._maxIndexers)
        return
      }
      // AUTOBASE CONSTRAINT (7.28.1): a writer can only be elevated to indexer while it is
      // FRESH — base.local.length === 0. Reliable promotion is a two-phase protocol anchored
      // at length 0 (addWriter parks the key in pendingIndexers, the writer self-acks — gated
      // on local.length===0, apply-state.js:356 — and the manifest fork fires anchored to that
      // writer's own first confirmed node). A writer that has ALREADY appended data
      // (_seenLength>0) takes system._updateIndexer's immediate branch, binding the fork to an
      // un-anchored tip node authored by another indexer; the reorganising linearizer keeps
      // rolling it back (_rollbackViews) → indexerUpdate is set but the indexer set never
      // advances. So a data-bearing writer CANNOT be promoted in place — retrying is futile and
      // just spams the log. keet has the same constraint: it mints indexers only from FRESH
      // devices/joins (addDevice: addWriter(deviceKey,{indexer:isIndexing})); change-member-role
      // sets the admin CAPABILITY only, never addWriter. So we promote ONLY while fresh; an
      // admin that already wrote game data keeps its admin capability but stays a plain writer
      // (durability is provided by the fresh/anchor indexers, not by every admin). See
      // hyper-fleeky-dev #103 + memory/project_statebase-inplace-indexer-promotion-*.
      let localLen = 0; try { localLen = this.base.local ? this.base.local.length : 0 } catch { localLen = 0 }
      if (localLen > 0) {
        if (!this._promoteFutileLogged) {
          this._promoteFutileLogged = true
          console.log('[state-base-v3] room=%s admin NOT self-promoting: writer already has data (local.length=%d) — autobase only elevates a FRESH (length 0) writer to indexer; keeping admin as a plain writer', this._roomKeyHex.slice(0, 12), localLen)
        }
        return
      }
      // Every admin GROWS the set via start-indexing (no demote → quorum). A DESIGNATED
      // anchor (opts.claimIndexer) still does the SOLE-slot move-indexer for back-compat.
      const mode = this._claimIndexer ? { claimIndexer: true } : { startIndexing: true }
      console.log('[state-base-v3] room=%s admin self-promoting to indexer (%s)', this._roomKeyHex.slice(0, 12), this._claimIndexer ? 'move-indexer anchor' : 'start-indexing grow')
      const r = await this.requestWriter({ timeoutMs: 25000, ...mode })
      console.log('[state-base-v3] room=%s promote result writable=%s indexer=%s', this._roomKeyHex.slice(0, 12), r.writable, r.indexer)
    } catch (e) { console.log('[state-base-v3] promote failed: %s', e.message) } finally { this._promoting = false }
  }

  async _open () {
    if (!this._detBaseKey) throw new Error('StateBaseV3 requires roomSeed (deterministic key)')
    // forceNonCreator (resync heal): never elect as creator → open with keyPair=null → a FRESH local
    // writer; the deterministic genesis (_gsKeyPair) becomes a REMOTE writer that replicates + linearizes
    // normally (the proven non-creator path), instead of an un-sheddable, un-linearizable local writer.
    //
    // forceCreator (notary revival): re-assume the deterministic genesis writer/indexer on a HEALTHY
    // co-owner even when it is NOT the lowest key. Used when the original creator (lowest-key) abandoned
    // the genesis via a resync (forceNonCreator) — leaving the base with NO live indexer (indexedLength
    // frozen, new writes optimistic-only). Because _gsKeyPair is roomSeed-derived (derivable by any
    // co-owner), a healthy co-owner that holds the authoritative state can become the sole live indexer
    // (quorum 1) — breaking the "need-an-indexer-to-make-an-indexer" deadlock keet cannot escape (keet
    // writers are random). Once ONE notary is live again, keet's dynamic start/move/stop-indexing take over.
    //
    // CANONICAL usage = REBUILD-FROM-AUTHORITATIVE: pair forceCreator with a FRESH store + adopt(records,
    // head) — the notary AUTHORS the genesis from the snapshot (adopt continues the atproto chain from the
    // current head, so the relay chain is unbroken). This sidesteps two walls the in-place variant hit:
    // a fresh store has NO stale view core (no autobase view-reindex checkout crash), and AUTHORING (not
    // backfilling) an empty genesis is the normal creation path (diagnostic-1 N/A). Proven in
    // hyper-proto-peer/test/rebuild-from-authoritative.test.js (new post FINALIZES). Do NOT forceCreator an
    // EXISTING store to "continue" the genesis in place — that reindexes the view and crashes on write.
    // EXACTLY ONE co-owner may hold gsKeyPair at a time — the resynced peer MUST be forceNonCreator.
    const amCreator = this._forceCreator ? true : (this._forceNonCreator ? false : ((!this._getMembers || !this._selfKey) ? true : await this._amCreator()))
    // RECORD the decision. `_amCreator` is a METHOD, so every consumer doing `!!sb._amCreator` to ask
    // "is this node the creator?" was reading a truthy function and getting `true` unconditionally — which
    // is exactly what hyper-proto-peer's members-diag did, so that field has always said `true` for every
    // node, creator or not. A diagnostic that cannot report the negative case is worse than none: it was
    // cited as evidence of a role flip during a real incident. This is the answer to that question.
    this._isCreator = amCreator
    const roleTag = this._forceCreator ? ' (assume-genesis: forced creator)' : (this._forceNonCreator ? ' (resync: forced non-creator)' : '')
    console.log('[state-base-v3] room=%s %s%s base=%s', this._roomKeyHex.slice(0, 12),
      amCreator ? 'creator' : 'member', roleTag, this._detBaseKey.toString('hex').slice(0, 12))
    await this._openBase(this._detBaseKey, amCreator ? this._gsKeyPair : null)
  }

  async _openBase (bootstrapKey, keyPair) {
    const baseOpts = {
      // The Autobase view IS a HyperDB. autoUpdate is load-bearing: HyperDB reads
      // a snapshot frozen at construction, advanced only by core 'append'.
      open: (store) => HyperDB.bee(store.get('view'), hyperdbDefinition, { autoUpdate: true }),
      apply: this._apply.bind(this),
      close: async (view) => { if (view) await view.close() },
      valueEncoding: 'binary', // ops are hyperdispatch-encoded buffers
      optimistic: true,
      ackInterval: 1000,
      ackThreshold: 4
    }
    if (keyPair) baseOpts.keyPair = keyPair
    if (this._encryptionKey) { baseOpts.encryptionKey = this._encryptionKey; baseOpts.encrypted = true }
    // Shared wakeup (multi-DID): all DIDs on the daemon share ONE ProtomuxWakeup, so a single
    // `wakeup.addStream(conn)` carries every DID's optimistic/pending-writer announcements — the
    // admission doorbell works over the shared connection with no per-base wakeup (autobase sets
    // wakeupOwner=false when handlers.wakeup is injected). Pair with network:false (daemon-driven repl).
    if (this._wakeup) baseOpts.wakeup = this._wakeup

    this.base = new Autobase(this.store, bootstrapKey, baseOpts)
    await this.base.ready()

    // Fire the watcher fan-out on EVERY autobase view advance — crucially including the BACKGROUND
    // apply-completion of THIS node's OWN optimistic write. Without this, a solo write (e.g. a direct
    // apply-write on the notary) appends but the sb.watch -> tick -> sign() chain never re-fires: the
    // apply-path _fireWatchers() only runs on an explicit base.update() drain with new nodes, and the
    // autoUpdate view advance does not go through _apply. So the write would finalize only when some
    // OTHER event (a co-owner's replication, another write, a presence change) happens to drive an apply
    // — the "direct notary write never finalizes" lag. See test/finalization-lag.repro.test.js. sign() is
    // idempotent (no-ops on an unchanged data root) and the tick coalesces, so extra fires are cheap.
    this.base.on('update', () => this._fireWatchers())

    if (this._network) {
      if (!this.swarm) {
        this.swarm = new Hyperswarm(this._swarmOpts || undefined)
        this.swarm.on('connection', (socket) => {
          // Observability: StateBase swarm peers were invisible in logs, so a device coming up
          // ISOLATED (no base-topic peer) looked identical to connected-but-not-replicating. Log it.
          const rk = socket.remotePublicKey ? socket.remotePublicKey.toString('hex').slice(0, 12) : '?'
          console.log('[state-base-v3] swarm peer CONNECTED room=%s peer=%s conns=%s', this._roomKeyHex.slice(0, 8), rk, this.swarm.connections ? this.swarm.connections.size : '?')
          socket.on('close', () => console.log('[state-base-v3] swarm peer CLOSED room=%s peer=%s', this._roomKeyHex.slice(0, 8), rk))
          // MUST replicate via base.replicate (not store.replicate): it ALSO
          // wires the autobase wakeupProtocol onto the stream, which announces
          // optimistic/pending writer cores. With bare store.replicate the
          // indexer never discovers a not-yet-admitted member's optimistic
          // onboarding block → admission never runs → member stays non-writable
          // (the testy1/AI-Testing-Town "can't write" deadlock). cf. pear-git-v3
          // pear-git.js:447 ("corestore.replicate unreliable for writer cores").
          try { this.base.replicate(socket) } catch (err) { console.error('[state-base-v3] replicate threw:', err.message) }
          try { this.attachSignerPresence(socket) } catch {} // ephemeral signer-presence handshake — feeds the election, appends nothing
          // EVENT-DRIVEN __members__ projection: a peer (a member) just connected. If we're the writable
          // creator and haven't projected the roster yet, (re)project now so its admission verifies —
          // instead of waiting on the slow promote-timer tick. Self-terminating + idempotent.
          this._ensureMembersProjected().catch(() => {})
          this._announceAbi().catch(() => {}) // a peer arrived: stamp our ABI if we have not yet
        })
      }
      this.swarm.join(this.base.discoveryKey)
    }
    console.log('[state-base-v3] room=%s base.key=%s writable=%s', this._roomKeyHex.slice(0, 12),
      this.base.key.toString('hex').slice(0, 12), this.base.writable)
  }

  // Attach the ephemeral signer-presence handshake to a connection (announce our member key, learn the
  // peer's → feed the election). Public so the multi-DID daemon can also attach it on the shared swarm;
  // the single-DID path calls it from the internal connection handler. Returns a detach fn; no-op without a
  // member identity. Appends NOTHING — presence lives and dies with the connection.
  // id: this._roomKey — a per-DID channel id so N DIDs' presence coexist on ONE shared multi-DID daemon
  // connection (protomux keys on (protocol, id); without it every DID collides on a null id and only the
  // first opens). Single-DID and multi-DID both derive the same roomKey per DID, so peers of a DID match.
  attachSignerPresence (conn) {
    if (!this._presence) return () => {}
    const handle = attachPresence(conn, { selfKey: this._selfKey.toString('hex'), presence: this._presence, id: this._roomKey, getHead: () => this._selfHead })
    this._presenceSenders.add(handle.send)
    return () => { this._presenceSenders.delete(handle.send); try { handle() } catch {} } // handle() detaches
  }

  // Feed our current signed head rev into the presence election (currency) + RE-ANNOUNCE it to peers, so a
  // co-owner BEHIND the network head is excluded from the election while it is gate-blocked from signing —
  // the caught-up peer signs instead of the chain freezing. Called by the sign loop after sign/restore.
  setSignerHead (rev) {
    const r = rev || null
    if (r === this._selfHead) return
    this._selfHead = r
    if (this._presence) this._presence.setSelfHead(r)
    for (const send of this._presenceSenders) { try { send(r) } catch {} }
  }

  // Do WE hold the active-signer role right now? Drop-in for the old lease.holds() in the sign loop:
  // election is a deterministic function of who is CONNECTED (lowest-key effective co-owner), computed in
  // RAM. A device with no co-owners connected is the sole signer (holds=true). No writes, ever.
  holdsSigner (now, netHead = null) { return this._presence ? this._presence.holds(now, netHead) : true }
  currentSigner (now, netHead = null) { return this._presence ? this._presence.currentSigner(now, netHead) : (this._selfKey ? this._selfKey.toString('hex') : null) }
  signerState (now, netHead = null) { return this._presence ? this._presence.state(now, netHead) : { self: null, signer: null, effective: [], holds: true } }

  // keet's _autobaseApply commit shape: a per-batch transaction; handlers write
  // into it; flush on success / close on error (never insert on the db directly).
  async _apply (nodes, view, base) {
    if (process.env.SBV3_DIAG) {
      const who = base.writable ? 'WRITABLE' : 'member'
      const froms = nodes.map(n => (n.from && n.from.key ? n.from.key.toString('hex').slice(0, 8) : 'sys')).join(',')
      console.log('[SBV3_DIAG] _apply self=%s(%s) nodes=%d from=[%s]',
        (this._selfKey ? this._selfKey.toString('hex').slice(0, 8) : '?'), who, nodes.length, froms)
    }
    const tx = view.transaction()
    try {
      for (const node of nodes) {
        const op = node.value
        if (op == null || !Buffer.isBuffer(op)) continue // null/system nodes
        await this._router.dispatch(op, { tx, base, node, sb: this })
      }
      await tx.flush()
    } catch (err) {
      try { await tx.close() } catch {}
      throw err
    }
    this._fireWatchers()
  }

  // Notify every sb.watch(fn) subscriber. Fired on a view advance (above) AND on a presence change
  // (SignerPresence.onChange), so one subscription covers writes/replication + signer failover.
  _fireWatchers () { for (const w of this._watchers) { try { w() } catch {} } }

  // ── Public API (generic KV — unchanged surface vs v2) ──────
  async set (key, value) {
    if (!this._ready) throw new Error('StateBaseV3 not ready')
    // DOORBELL (keet block-until-admitted). NEVER fuse durable CONTENT into a pre-admission
    // OPTIMISTIC block: autobase keeps an optimistic block ONLY if the SAME apply admits+acks its
    // writer, else it is rolled back every drain and discarded (apply-state.js:1110-1141). Fusing
    // content+admit therefore reports success while the write silently VANISHES when no indexer is
    // online to ack it — and the author can never read it back (test/silent-loss.repro.mjs). Every
    // durable autobase app (autopass/keet/hyper-rooms/hypernote) instead admits FIRST, writes AFTER.
    // So: if we are not yet an admitted writer, drive a CONTENT-FREE admission and block until we
    // are genuinely in the system writer set; only then append content non-optimistically. If
    // admission cannot be reached, _ensureWritable THROWS (never a silent loss). cf. skills/autobase.
    await this._ensureWritable()
    const rec = { key: String(key), value: this._enc(value), ts: Date.now() }
    await this.base.append(encode('@state/set-entry', rec))
    // BOUNDED: the content is appended (durable-local + replicated); a stalled drain must not hang
    // the writer indefinitely (Phase-2 #6). The value is still readable back via the autoUpdate view.
    await this._updateBounded()
  }

  async del (key) {
    if (!this._ready) throw new Error('StateBaseV3 not ready')
    await this._ensureWritable()
    await this.base.append(encode('@state/del-entry', { key: String(key), ts: Date.now() }))
    await this._updateBounded()
  }

  // Block until we are a genuinely ADMITTED writer (our local writer key is in the linearized
  // system writer set), then return. No-op if already writable. Otherwise ring the CONTENT-FREE
  // admission doorbell (requestWriter, which re-rings until admitted) and wait; if no indexer
  // admits us within the timeout, THROW rather than let a caller write content that autobase would
  // silently roll back. This is the guard that makes set()/del() durable (block-until-admitted).
  async _ensureWritable ({ timeoutMs = 20000 } = {}) {
    if (this.base && this.base.writable) return
    await this.requestWriter({ timeoutMs })
    if (!this.base || !this.base.writable) {
      throw new Error('StateBaseV3: not admitted as a writer (no indexer online within ' + timeoutMs + 'ms) — refusing to write content that would be silently lost')
    }
  }

  // Trigger our OWN admission without writing any game data: append a keyless
  // optimistic block carrying just the admission proof. When an online indexer
  // applies it, _applySet addWriters us (INDEXER if our keet role is admin/mod,
  // role 1/2). So an always-on `--pin-room` anchor that is an admin becomes a
  // durable indexer and can then admit other members even when the original
  // room creator is offline (fixes the "creator went away → room stuck" class).
  // No-op if already writable. Requires an online indexer to land the first
  // promotion (bootstrap); thereafter the writer status is durable in the oplog.
  // claimIndexer: a DESIGNATED admin anchor takes the sole indexer slot (move-
  // indexer). Without it, just become a plain writer. Goal reached when writable
  // (and, if claiming, when we are the indexer).
  async requestWriter ({ timeoutMs = 15000, claimIndexer = false, startIndexing = false } = {}) {
    if (!this._ready) throw new Error('StateBaseV3 not ready')
    const wantIndexer = claimIndexer || startIndexing
    const done = () => this.base.writable && (!wantIndexer || this._isLocalIndexer() === true)
    if (done()) return { writable: true, already: true, indexer: this._isLocalIndexer() }
    // FAIL FAST if this device has been BANNED. Its identity is in the durable, replicated
    // __removed__ set, so the admission guard (_verifyAdmissionInApply) will reject every admit
    // proof it ever sends — ringing the doorbell for the full timeoutMs is pointless and makes every
    // write a removed device attempts stall ~timeoutMs before throwing. Throw immediately instead.
    // Best-effort (see _isSelfRemoved): false on any uncertainty, so a non-banned device is never
    // wrongly rejected — it just falls back to the normal doorbell.
    if (await this._isSelfRemoved()) throw new Error('StateBaseV3: this device has been removed (banned) — cannot become a writer')
    // DO NOT WRITE INTO A ROOM THAT DOES NOT LIST US. This is keet's rule (RoomFirewall.allow resolves
    // a peer through @keet/devices-by-swarm-key and admits only an ACTIVE device; membership is written
    // by an existing member via addDevice). An unlisted device asking to be let in is the 26,953-block
    // loop on wj62: apply resolves its role to null every time, so every append is futile, and the
    // doorbell re-rings on each base advance — including the advance its own append caused.
    //
    // POSITIVE EVIDENCE OF EXCLUSION ONLY. `_isSelfListed` returns null when the room has no roster in
    // our view at all — which is a fresh joiner mid-replication as much as it is an outsider, and those
    // two are indistinguishable from here. Refusing on absence broke a genuine member whose __members__
    // had not landed yet (test/doorbell-durable-write.test.js: its set() threw instead of waiting), so
    // absence must mean "no information" and ring as before. Only a roster that EXISTS and omits us is
    // a refusal — which is the flooding node's state exactly: long converged, listed nobody's business,
    // 26,953 blocks of asking. A device admitted later rings on the very next advance, because
    // __members__ changing IS an advance — event-driven, no timer.
    if ((await this._isSelfListed()) === false) throw new Error('StateBaseV3: this room lists members and this device is not among them — wait for a member to admit it (addMember)')
    const admit = await this._buildAdmissionProof()
    if (!admit) throw new Error('StateBaseV3 cannot request writer: no membership/identity to build an admission proof')
    // key MUST be a string (encoder always writes it; undefined crashes compact-
    // encoding). MOVE_INDEXER = indexer swap (deliberate hand-off); START_INDEXING =
    // grow the indexer set (self-promote, quorum path); '' = plain-writer admission.
    // None insert a game entry.
    const key = claimIndexer ? MOVE_INDEXER : (startIndexing ? START_INDEXING : '')
    await this.base.append(encode('@state/set-entry', { key, admit, ts: Date.now() }), { optimistic: true })
    // BOUNDED, not blocking: an un-converged replica's base.update() can hang forever (Phase-2 #6).
    // The optimistic doorbell block is already appended (durable-local + replicated via the swarm);
    // bounding the drive lets the loop keep re-ringing + re-polling base.writable instead of freezing.
    await this._updateBounded()
    const deadline = Date.now() + timeoutMs
    while (!done() && Date.now() < deadline) {
      await new Promise(r => setTimeout(r, 250))
      // RE-RING the doorbell while still un-admitted: a single optimistic block can be rolled back
      // before an intermittent / just-connected indexer acks it (silent-loss RECOVER mode), so keep
      // a live optimistic block present to re-anchor the tip until admission lands. Once writable,
      // stop — further appends go through the normal (non-optimistic) writer path.
      if (!this.base.writable) {
        try { await this.base.append(encode('@state/set-entry', { key, admit, ts: Date.now() }), { optimistic: true }) } catch {}
      }
      await this._updateBounded()
    }
    if (this.base.writable) this._announceAbi().catch(() => {}) // just admitted: we can stamp now
    return { writable: this.base.writable, indexer: this._isLocalIndexer() }
  }

  // Is THIS daemon's local writer an indexer? autobase tracks it directly.
  _isLocalIndexer () {
    try { return this.base.isIndexer === true } catch { return null }
  }

  // Drive the linearizer, but NEVER hang the caller. base.update() awaits a full drain, which can
  // stall INDEFINITELY on an un-converged plain-writer replica (device-swarm still catching up) —
  // the Phase-2 hang (hyper-social #6): the sign/admission path awaited it and froze, so the
  // re-admission doorbell never re-rang. This bounds how long we AWAIT one drain. It is SAFE to
  // time out: convergence does NOT depend on our awaiting update() — incoming replication triggers
  // background drains (autobase _onwakeup/_onremotewriterchange → _queueBump) that still advance
  // base.writable — so a bounded await lets the doorbell loop keep re-ringing + re-polling the
  // (sync) writable getter while the real work proceeds in the background. Same posture as the
  // getNow/listNow snapshot reads and the boot __members__ time-box.
  async _updateBounded (ms = 800) {
    if (!this.base) return
    let t = null
    try {
      await Promise.race([
        this.base.update().catch(() => {}),
        new Promise((r) => { t = setTimeout(r, ms); if (t && typeof t.unref === 'function') t.unref() })
      ])
    } finally { if (t) clearTimeout(t) }
  }

  // Background, guarded re-admission doorbell for a booted-but-not-yet-writable plain writer.
  // Rationale (Phase 2): a plain writer admitted at RUNTIME may reboot writable=false if an indexer
  // never SIGNED a checkpoint covering its admission that the writer persisted (the power-cut
  // window). Re-admission needs the writer to re-ring requestWriter — but the lease/sign path only
  // writes when it can hold the lease, and a healthy peer (stortron) holds it, so that path never
  // fires the doorbell. This is the independent trigger: the sign loop calls it each tick; it rings
  // requestWriter ONCE at a time (a call while one is in flight is a no-op), so an online indexer
  // re-admits us and signs a durable checkpoint we then persist. No-op once writable.
  async ensureAdmitted ({ timeoutMs = 15000 } = {}) {
    if (!this._ready || !this.base || this.base.writable) return this.base ? this.base.writable : false
    if (this._ensuringAdmit) return false
    this._ensuringAdmit = true
    try { await this.requestWriter({ timeoutMs }) } catch {} finally { this._ensuringAdmit = false }
    return this.base ? this.base.writable : false
  }

  async get (key) {
    if (!this._ready) return null
    await this.base.update()
    const rec = await this.base.view.get(ENTRIES, { key: String(key) })
    return rec ? this._dec(rec.value) : null
  }

  async list (prefix = '') {
    if (!this._ready) return {}
    await this.base.update()
    const out = {}
    const stream = this.base.view.find(ENTRIES, { gte: { key: prefix }, lt: { key: prefix + '~' } })
    for await (const rec of stream) out[rec.key] = this._dec(rec.value)
    return out
  }

  // Non-blocking reads — same as get()/list() but WITHOUT `await base.update()`. base.update() drives the
  // linearizer fully up-to-date, which can HANG on an un-converged plain-writer replica (device-swarm
  // still catching up), stalling any caller (e.g. the device-registry revocation check on login). The
  // view is a HyperDB opened `autoUpdate:true`, so it already reflects the latest MATERIALIZED state —
  // these read that current snapshot instantly (at most a few ms stale). Use for liveness-critical reads
  // that must never block; use get()/list() when you need the freshest fully-drained view.
  async getNow (key) {
    if (!this._ready) return null
    const rec = await this.base.view.get(ENTRIES, { key: String(key) })
    return rec ? this._dec(rec.value) : null
  }

  async listNow (prefix = '') {
    if (!this._ready) return {}
    const out = {}
    const stream = this.base.view.find(ENTRIES, { gte: { key: prefix }, lt: { key: prefix + '~' } })
    for await (const rec of stream) out[rec.key] = this._dec(rec.value)
    return out
  }

  // value is an arbitrary JSON-able Variant from the game; stored as a JSON string.
  _enc (v) { try { return JSON.stringify(v) } catch { return String(v) } }
  _dec (s) { if (typeof s !== 'string') return s; try { return JSON.parse(s) } catch { return s } }

  // ── Apply-side op handlers (called by the router) ──────────
  async _applySet (rec, ctx) {
    // D1b admission: an optimistic write from a not-yet-admitted member carries
    // an `admit` proof. Verify it deterministically (pure crypto + projected
    // __members__, NO external lookup) and ackWriter so the block commits.
    // Unverified optimistic blocks are NOT acked → autobase never applies them.
    if (rec.admit && ctx.node && ctx.node.from && ctx.node.from.key) {
      const fromKeyHex = ctx.node.from.key.toString('hex')
      // Already admitted this writer — addWriter is idempotent, so skip the
      // re-verify + re-addWriter + re-ack (and the log line) that the peer's
      // every-op `admit` proof would otherwise trigger. Once they're a permanent
      // writer their blocks commit via normal acking; no per-block ackWriter.
      const fromKey = ctx.node.from.key
      const fromHex = fromKeyHex.slice(0, 12)
      // Record writer->identity in __devices__ for ANY admit-carrying op (plain admission,
      // START_INDEXING, MOVE_INDEXER all addWriter this key) so a ban (REMOVE_DEVICE) can
      // removeWriter this device by its identity (atproto-base-REVOCATION §6). Harmless if the op is
      // later denied — the key never becomes a writer so removeWriter no-ops; admit.identity is the
      // caller's OWN attested id (it cannot claim another's).
      if (rec.key !== REMOVE_DEVICE && rec.key !== ADD_MEMBER && rec.key !== SET_EPOCH) {
        try {
          const a = typeof rec.admit === 'string' ? JSON.parse(rec.admit) : rec.admit
          const idHex = a && a.identity ? a.identity : null
          if (idHex) {
            const drec = await ctx.tx.get(ENTRIES, { key: '__devices__' })
            const devmap = drec && drec.value ? JSON.parse(drec.value) : {}
            if (devmap[fromKeyHex] !== idHex) { devmap[fromKeyHex] = idHex; await ctx.tx.insert(ENTRIES, { key: '__devices__', value: JSON.stringify(devmap), ts: rec.ts || 0 }) }
          }
        } catch (e) { console.log('[state-base-v3] record device-writer FAIL: %s', e.message) }
      }
      if (rec.key === MOVE_INDEXER) {
        // MOVE-INDEXER (keet members/index.js:258-275): a DESIGNATED admin anchor
        // takes the SOLE indexer slot via an atomic swap — promote the anchor +
        // demote the genesis creator (whose writer key is the deterministic
        // base.key). Count stays 1, so the always-on anchor finalizes (quorum 1)
        // even with the creator offline. We do NOT grow the indexer set: autobase
        // can't reliably exceed ~2 indexers (the 3rd-indexer manifest hang, proven).
        // Re-runnable (idempotent addWriter); not gated by _admitted (it's a
        // promotion, not a first admission). Only admins (role 1) may claim.
        const role = await this._verifyAdmissionInApply(fromKey, rec.admit, ctx.tx)
        if (role !== 1) { console.log('[state-base-v3] MOVE-INDEXER DENIED from=%s role=%s', fromHex, String(role)); return }
        try {
          await ctx.base.addWriter(fromKey, { indexer: true })
          this._admitted.add(fromKeyHex)
          if (this._detBaseKey && Buffer.compare(fromKey, this._detBaseKey) !== 0) {
            await ctx.base.addWriter(this._detBaseKey, { indexer: false }) // demote genesis creator
          }
          // NO preferFastForward: a fast-forwarding indexer refuses to ack/sign (autobase
          // index.js:952), which deadlocks the indexer-set migration so signedLength stalls on
          // ALL peers (audit 2026-07-02). keet's indexer ops don't call it. Removing it lets the
          // new indexer ack and quorum reform. Proven on START_INDEXING (probe-indexer-quorum 8/8
          // + probe-rotation-phantom-check 3/3 inline); MOVE-INDEXER (anchor path) same rationale.
          console.log('[state-base-v3] MOVE-INDEXER: anchor=%s is now SOLE indexer (genesis demoted)', fromHex)
        } catch (e) { console.log('[state-base-v3] move-indexer FAIL from=%s: %s', fromHex, e.message) }
        try { await ctx.base.ackWriter(fromKey) } catch (e) { console.log('[state-base-v3] ackWriter FAIL: %s', e.message) }
      } else if (rec.key === START_INDEXING) {
        // START-INDEXING (keet members/index.js op D): an admin GROWS the indexer set
        // by adding ITSELF as an indexer — NO demote of anyone. With >=3 admin-indexers,
        // autobase majority quorum ((n>>>1)+1) finalizes even when the genesis/creator
        // is offline. Only admins (role 1) may promote; idempotent addWriter (not gated
        // by _admitted — it's a promotion, and combines first-admission + indexer grow).
        const role = await this._verifyAdmissionInApply(fromKey, rec.admit, ctx.tx)
        if (role !== 1) { console.log('[state-base-v3] START-INDEXING DENIED from=%s role=%s', fromHex, String(role)); return }
        try {
          await ctx.base.addWriter(fromKey, { indexer: true })
          this._admitted.add(fromKeyHex)
          // NO preferFastForward — see MOVE-INDEXER note above (FF-deadlock, autobase index.js:952).
          console.log('[state-base-v3] START-INDEXING: %s is now an indexer (grow, no demote)', fromHex)
        } catch (e) { console.log('[state-base-v3] start-indexing FAIL from=%s: %s', fromHex, e.message) }
        try { await ctx.base.ackWriter(fromKey) } catch (e) { console.log('[state-base-v3] ackWriter FAIL: %s', e.message) }
      } else if (rec.key === REMOVE_DEVICE) {
        // BAN (atproto-base-REVOCATION §6): only a role-1 member may issue (authorized via the admit
        // proof, like START_INDEXING). Record the target in REMOVED_SET, drop it from __members__,
        // and removeWriter its writer(s) — so it can neither write now nor re-admit later.
        const role = await this._verifyAdmissionInApply(fromKey, rec.admit, ctx.tx)
        if (role !== 1) { console.log('[state-base-v3] REMOVE-DEVICE DENIED from=%s role=%s', fromHex, String(role)); return }
        const target = String(this._dec(rec.value) || '')
        if (target) {
          const rrec = await ctx.tx.get(ENTRIES, { key: REMOVED_SET }); const removed = rrec && rrec.value ? JSON.parse(rrec.value) : {}
          removed[target] = { ts: rec.ts || 0 }; await ctx.tx.insert(ENTRIES, { key: REMOVED_SET, value: JSON.stringify(removed), ts: rec.ts || 0 })
          const mrec = await ctx.tx.get(ENTRIES, { key: '__members__' }); const members = mrec && mrec.value ? JSON.parse(mrec.value) : {}
          if (members[target] != null || members[normKeyHex(target)] != null) { delete members[target]; delete members[normKeyHex(target)]; await ctx.tx.insert(ENTRIES, { key: '__members__', value: JSON.stringify(members), ts: rec.ts || 0 }) }
          const drec = await ctx.tx.get(ENTRIES, { key: '__devices__' }); const devmap = drec && drec.value ? JSON.parse(drec.value) : {}
          for (const [wk, id] of Object.entries(devmap)) {
            if (id === target || id === normKeyHex(target)) {
              try { await ctx.base.removeWriter(Buffer.from(wk, 'hex'), { indexer: false }); this._admitted.delete(wk); console.log('[state-base-v3] REMOVE-DEVICE: removeWriter %s (identity %s)', wk.slice(0, 12), target.slice(0, 12)) } catch (e) { console.log('[state-base-v3] removeWriter FAIL %s: %s', wk.slice(0, 12), e.message) }
            }
          }
        }
      } else if (rec.key === ADD_MEMBER) {
        // ADMIT A MEMBER (keet contract/members addDevice): authorized by the AUTHOR's role, exactly
        // like REMOVE_DEVICE above. The room records who belongs; the joiner never writes to ask.
        const role = await this._verifyAdmissionInApply(fromKey, rec.admit, ctx.tx)
        if (role !== 1) { console.log('[state-base-v3] ADD-MEMBER DENIED from=%s role=%s', fromHex, String(role)); return }
        let target = null; let targetRole = 1
        try { const v = this._dec(rec.value); if (v && typeof v === 'object') { target = String(v.id || ''); targetRole = Number(v.role) || 1 } else if (v) { target = String(v) } } catch {}
        if (!target) { console.log('[state-base-v3] ADD-MEMBER: no target'); return }
        // A ban outranks an add — otherwise any member could undo a removal by re-adding.
        if (await this._isRemoved(ctx.tx, target)) { console.log('[state-base-v3] ADD-MEMBER REFUSED: %s is in __removed__ (unban first)', target.slice(0, 12)); return }
        const mrec = await ctx.tx.get(ENTRIES, { key: '__members__' })
        const members = mrec && mrec.value ? JSON.parse(mrec.value) : {}
        if (members[target] === targetRole || members[normKeyHex(target)] === targetRole) return // idempotent
        members[normKeyHex(target)] = targetRole
        await ctx.tx.insert(ENTRIES, { key: '__members__', value: JSON.stringify(members), ts: rec.ts || 0 })
        console.log('[state-base-v3] ADD-MEMBER: %s admitted role=%s by %s', target.slice(0, 12), String(targetRole), fromHex)
      } else if (rec.key === SET_EPOCH) {
        // Set the minimum attestation epoch (atproto-base-REVOCATION §3): only a role-1 member. After
        // this, admission rejects any attestation whose epoch is below the receipt — re-attest
        // survivors at the new epoch to keep them, invalidating all stale/revoked proofs at once.
        const role = await this._verifyAdmissionInApply(fromKey, rec.admit, ctx.tx)
        if (role !== 1) { console.log('[state-base-v3] SET-EPOCH DENIED from=%s role=%s', fromHex, String(role)); return }
        const receiptHex = String(this._dec(rec.value) || '')
        if (receiptHex) { await ctx.tx.insert(ENTRIES, { key: RECEIPT_KEY, value: this._enc(receiptHex), ts: rec.ts || 0 }); console.log('[state-base-v3] SET-EPOCH: min-epoch receipt set by %s', fromHex) }
      } else if (!this._admitted.has(fromKeyHex)) {
        const role = await this._verifyAdmissionInApply(fromKey, rec.admit, ctx.tx)
        console.log('[state-base-v3] ADMIT attempt from=%s verifiedRole=%s', fromHex, String(role))
        if (role == null) return
        // Admit as a PLAIN WRITER (indexer:false). We deliberately never grow the
        // indexer set; the sole indexer is the genesis creator OR a move-indexer
        // anchor. Everyone else writes and the indexer signs.
        try { await ctx.base.addWriter(fromKey, { indexer: false }); this._admitted.add(fromKeyHex); console.log('[state-base-v3] addWriter OK from=%s indexer=false', fromHex) } catch (e) { console.log('[state-base-v3] addWriter FAIL from=%s: %s', fromHex, e.message) }
        try { await ctx.base.ackWriter(fromKey) } catch (e) { console.log('[state-base-v3] ackWriter FAIL: %s', e.message) }
      }
    }
    // Empty/null key = a pure admission request; MOVE_INDEXER / START_INDEXING / REMOVE_DEVICE =
    // reserved ops. All ran their effect above; none write a game entry.
    if (!rec.key || rec.key === MOVE_INDEXER || rec.key === START_INDEXING || rec.key === REMOVE_DEVICE || rec.key === ADD_MEMBER || rec.key === SET_EPOCH) return
    const existing = await ctx.tx.get(ENTRIES, { key: rec.key })
    if (existing && typeof existing.ts === 'number' && existing.ts > (rec.ts || 0)) return
    await ctx.tx.insert(ENTRIES, { key: rec.key, value: rec.value, ts: rec.ts || 0 })
  }

  async _applyDel (rec, ctx) {
    const existing = await ctx.tx.get(ENTRIES, { key: rec.key })
    if (existing && typeof existing.ts === 'number' && existing.ts > (rec.ts || 0)) return
    await ctx.tx.delete(ENTRIES, { key: rec.key })
  }

  // Ban a device by its keet identity hex (atproto-base-REVOCATION §6): append a REMOVE_DEVICE op
  // carrying an admission proof so apply authorizes by the CALLER's role (like requestWriter). Apply
  // records the target in REMOVED_SET, drops it from __members__, and removeWriters its writer(s).
  async banDevice (identityHex) {
    if (!this._ready) throw new Error('StateBaseV3 not ready')
    const admit = await this._buildAdmissionProof()
    if (!admit) throw new Error('banDevice: no identity to authorize the ban')
    await this.base.append(encode('@state/set-entry', { key: REMOVE_DEVICE, value: this._enc(String(identityHex)), admit, ts: Date.now() }), { optimistic: true })
    await this.base.update()
  }

  // Admit a member into the room (keet contract/members addDevice). An EXISTING role-1 member authors
  // it; apply authorizes by THIS caller's role. That is the whole point: membership becomes a fact of
  // the ROOM, replicated to every device, instead of a roster in one machine's config file that only
  // the creator could project (hyper-social #40 §6).
  async addMember (identityHex, role = 1, { force = false } = {}) {
    if (!this._ready) throw new Error('StateBaseV3 not ready')
    // ABI GATE. Emitting this op into a room containing a writer that predates it makes the two apply
    // it differently — the old node inserts `__add_member__` as an entry, we insert nothing — and a
    // divergent apply is a forked view, which is far worse than the problem this op solves. Refuse and
    // name the laggards. `force` exists for an operator who has verified the room out of band; it is
    // never the default, and the message says who is missing so the check can be answered rather than
    // bypassed blindly.
    if (!force) {
      const below = await this._writersBelowAbi(ROOM_ABI)
      if (below.length) throw new Error('addMember: room ABI ' + ROOM_ABI + ' not supported by writer(s) ' + below.join(', ') + ' — upgrade them first (or pass force after verifying)')
    }
    const admit = await this._buildAdmissionProof()
    if (!admit) throw new Error('addMember: no identity to authorize the admission')
    await this.base.append(encode('@state/set-entry', { key: ADD_MEMBER, value: this._enc({ id: String(identityHex), role: Number(role) || 1 }), admit, ts: Date.now() }), { optimistic: true })
    await this._updateBounded()
  }

  // Set the minimum attestation epoch (atproto-base-REVOCATION §3). receiptHex = a keet receipt
  // encoding the new minimum epoch (membership.encodeReceipt). Authorized by the caller's admit
  // proof (role 1). After this, attestations below the epoch are rejected on admission.
  async bumpEpoch (receiptHex) {
    if (!this._ready) throw new Error('StateBaseV3 not ready')
    const admit = await this._buildAdmissionProof()
    if (!admit) throw new Error('bumpEpoch: no identity to authorize')
    await this.base.append(encode('@state/set-entry', { key: SET_EPOCH, value: this._enc(String(receiptHex)), admit, ts: Date.now() }), { optimistic: true })
    await this.base.update()
  }

  // Ban guard: is this identity/member in the durable REMOVED_SET? (atproto-base-REVOCATION §3.)
  async _isRemoved (tx, ...keys) {
    const rrec = await tx.get(ENTRIES, { key: REMOVED_SET })
    const removed = rrec && rrec.value ? JSON.parse(rrec.value) : {}
    for (const k of keys) { if (k && (removed[k] || removed[normKeyHex(k)])) return true }
    return false
  }

  // Out-of-apply self-ban check: is THIS device's own identity in the durable __removed__ set (a ban
  // that has replicated to us)? Read against the linearized view exactly like getProjectedRole. Used
  // by requestWriter to fail fast instead of ringing a doorbell the admission guard will never
  // answer. Best-effort: returns false on any uncertainty (no selfKey / view not ready / parse
  // error), so it can never wrongly reject a non-banned device — worst case falls back to the
  // normal doorbell timeout.
  async _isSelfRemoved () {
    try {
      if (!this._ready || !this.base || !this._selfKey) return false
      // BOUNDED (Phase-2 #6): this runs at the TOP of requestWriter, before the doorbell append —
      // a blocking base.update() here would hang the doorbell on an un-converged replica and it
      // would never re-ring. Best-effort anyway (false on uncertainty), so reading a slightly stale
      // ban snapshot is acceptable; the autoUpdate view is still current within a few ms.
      await this._updateBounded()
      const rrec = await this.base.view.get(ENTRIES, { key: REMOVED_SET })
      const removed = rrec && rrec.value ? JSON.parse(rrec.value) : {}
      const hex = this._selfKey.toString('hex')
      return !!(removed[hex] || removed[normKeyHex(hex)])
    } catch { return false }
  }

  // Does the room LIST this device — i.e. could an admission actually succeed? Read against the
  // linearized view exactly like _isSelfRemoved. Two ways to be listed, matching what
  // _verifyAdmissionInApply consults: our keet identity in __members__, or one of our writer keys
  // mapped to a listed member in __devices__ (a device admitted earlier, now rebooting unwritable —
  // the Phase-2 case, which MUST keep ringing).
  //
  // TRI-STATE: true = listed, false = the roster exists and omits us (refuse), null = we cannot tell
  // yet (ring as before). Collapsing null into false is what broke a genuine member whose roster had
  // not replicated — its set() threw instead of waiting. Only positive evidence of exclusion silences
  // a device; that is precisely the flooding node's state and not a joiner's.
  async _isSelfListed () {
    try {
      if (!this._ready || !this.base) return null // unknown — not "no"
      await this._updateBounded()
      const mrec = await this.base.view.get(ENTRIES, { key: '__members__' })
      // NULL, not false: no roster in OUR view is a fresh joiner mid-replication as often as it is an
      // outsider, and the caller must not treat the two alike. Only an existing roster that omits us
      // is a refusal.
      if (!mrec || !mrec.value) return null
      const members = JSON.parse(mrec.value)
      if (this._selfKey) {
        const hex = this._selfKey.toString('hex')
        if (members[hex] != null || members[normKeyHex(hex)] != null) return true
      }
      const drec = await this.base.view.get(ENTRIES, { key: '__devices__' })
      const devmap = drec && drec.value ? JSON.parse(drec.value) : {}
      const localHex = this.base.local && this.base.local.key ? this.base.local.key.toString('hex') : null
      if (localHex) {
        const memberKey = devmap[localHex] != null ? devmap[localHex] : devmap[normKeyHex(localHex)]
        if (memberKey && (members[memberKey] != null || members[normKeyHex(memberKey)] != null)) return true
      }
      return false // the roster EXISTS and does not name us — the one case that is a real refusal
    } catch { return null }
  }

  // Announce THIS writer's room ABI. Written once per writer key, on the events that can make it true
  // (open-while-writable, and admission succeeding) — never on a timer. Idempotent: a re-announce of an
  // unchanged value is skipped, so this cannot become an append loop of its own.
  async _announceAbi () {
    try {
      if (!this._ready || !this.base || !this.base.writable) return false
      const localHex = this.base.local && this.base.local.key ? this.base.local.key.toString('hex') : null
      if (!localHex) return false
      const key = ABI_PREFIX + localHex
      const cur = await this.getNow(key).catch(() => null)
      if (cur && Number(cur.v) === ROOM_ABI) return false
      await this.set(key, { v: ROOM_ABI, ts: Date.now() })
      return true
    } catch { return false }
  }

  // Which active writers have NOT announced support for `abi`? Returns an array of short keys; empty
  // means every writer in the room can apply the op identically. Fails CLOSED: a writer we cannot read
  // a stamp for counts as unsupported, because "no stamp" is exactly what a pre-ABI node looks like.
  async _writersBelowAbi (abi = ROOM_ABI) {
    const below = []
    try {
      await this._updateBounded()
      const writers = (this.base && this.base.activeWriters) ? [...this.base.activeWriters] : []
      for (const w of writers) {
        if (!w || w.isRemoved) continue // a removed writer applies nothing that matters
        const key = w.core && w.core.key ? w.core.key.toString('hex') : null
        if (!key) continue
        const stamp = await this.getNow(ABI_PREFIX + key).catch(() => null)
        if (!stamp || Number(stamp.v) < abi) below.push(key.slice(0, 12))
      }
    } catch { /* fail closed via whatever was collected */ }
    return below
  }

  // ── One-time in-place re-adopt migration (namespace rename) ─────────────────
  // The 'hyper-tps/state/v3' -> 'atproto-room/state/v3' rename changes the derived base key, so a
  // room created under the old namespace opens here as a FRESH, empty base that shares the same
  // on-disk Corestore as its old cores. Seed the renamed base from the legacy one so the room is
  // reconstituted — repo records + the signed __commit__ firehose + membership. Only the writable
  // creator seeds (peers replicate); no-op if the renamed base already has entries, if this instance
  // IS the legacy namespace, or if no legacy base is present. Idempotent across reboots.
  //
  // Carries every DIRECT set-entry entry (repo records, __members__, __devices__, __commit__/*,
  // prefs) verbatim. It does NOT carry the apply-DERIVED governance entries __removed__ (bans) /
  // __receipt__ (min-epoch) — those are produced inside apply from admission-proof ops, not stored as
  // plain set-entry ops, so they re-establish from config (re-issue a ban after migration if needed).
  async _migrateFromLegacyNamespace () {
    try {
      if (!this._roomSeed || !this.base || !this.base.writable) return
      if (Buffer.compare(this._gsNamespace, LEGACY_GS_NAMESPACE) === 0) return // already the legacy view
      const existing = await this.list('')
      if (Object.keys(existing).length > 0) return // renamed base already populated — nothing to do
      const legacyBaseKey = deriveBaseKey(deriveGsKeyPair(this._roomSeed, LEGACY_GS_NAMESPACE).publicKey)
      if (Buffer.compare(legacyBaseKey, this._detBaseKey) === 0) return // no rename in effect
      // Open the legacy base READ-ONLY on the SAME corestore (no fd-lock conflict — one store, two
      // autobases), with a minimal apply that only materializes direct set/del entries.
      const router = this._makeLegacyReadRouter()
      const opts = {
        open: (store) => HyperDB.bee(store.get('view'), hyperdbDefinition, { autoUpdate: true }),
        apply: async (nodes, view) => {
          const tx = view.transaction()
          try {
            for (const node of nodes) { const op = node.value; if (Buffer.isBuffer(op)) await router.dispatch(op, { tx }) }
            await tx.flush()
          } catch (e) { try { await tx.close() } catch {} ; throw e }
        },
        close: async (view) => { if (view) await view.close() },
        valueEncoding: 'binary', optimistic: true, ackInterval: 1000, ackThreshold: 4
      }
      if (this._encryptionKey) { opts.encryptionKey = this._encryptionKey; opts.encrypted = true }
      // Open on a Corestore SESSION, not this.store directly: a session shares the same storage +
      // cores (so it sees the legacy base) but has its own ref-counting, so closing it releases only
      // the migration's core sessions — it never tears down cores the live base is still using
      // (SESSION_CLOSED). No second fd-lock (same underlying storage).
      const legacyStore = this.store.session()
      // Cheap presence probe FIRST: the legacy creator's ops live in the bootstrap core (it opened
      // with that keyPair), so a real legacy room has length > 0 there. A genuinely fresh room has
      // no such data — skip WITHOUT opening a full legacy Autobase (which would spawn ~10 empty
      // cores on every first boot). One tiny empty probe core is the only footprint.
      const probe = legacyStore.get({ key: legacyBaseKey })
      await probe.ready()
      const hasLegacy = probe.length > 0
      if (!hasLegacy) { try { await legacyStore.close() } catch {} ; return }
      const legacy = new Autobase(legacyStore, legacyBaseKey, opts)
      try {
        await legacy.ready()
        await legacy.update()
        const entries = []
        const stream = legacy.view.find(ENTRIES, { gte: { key: '' }, lt: { key: '~' } })
        for await (const rec of stream) entries.push(rec)
        if (entries.length === 0) return
        let n = 0
        for (const rec of entries) {
          // Copy verbatim (value is already the stored encoded string). Direct append — the creator
          // is writable, so no doorbell needed (mirrors projectMembers).
          await this.base.append(encode('@state/set-entry', { key: rec.key, value: rec.value, ts: rec.ts || 0 }))
          n++
        }
        await this.base.update()
        console.log('[state-base-v3] room=%s RE-ADOPT MIGRATED %d entries from legacy namespace (base %s)',
          this._roomKeyHex.slice(0, 12), n, legacyBaseKey.toString('hex').slice(0, 12))
      } finally { try { await legacy.close() } catch {} ; try { await legacyStore.close() } catch {} }
    } catch (e) { console.log('[state-base-v3] legacy migration skipped: %s', e && e.message) }
  }

  // Minimal read-only router for materializing a legacy base's view: LWW-insert direct set-entry
  // ops, LWW-delete del-entry ops. Skips the transient admission/indexer/ban/epoch REQUEST ops
  // (empty key + the reserved __*__ command keys) — those carry no durable entry (their effects are
  // applied by the full router). Enough to reproduce every stored entry we migrate.
  _makeLegacyReadRouter () {
    const TRANSIENT = new Set(['', MOVE_INDEXER, START_INDEXING, REMOVE_DEVICE, SET_EPOCH])
    const r = new Router()
    r.add('@state/set-entry', async (rec, ctx) => {
      if (!rec.key || TRANSIENT.has(rec.key)) return
      const existing = await ctx.tx.get(ENTRIES, { key: rec.key })
      if (existing && typeof existing.ts === 'number' && existing.ts > (rec.ts || 0)) return
      await ctx.tx.insert(ENTRIES, { key: rec.key, value: rec.value, ts: rec.ts || 0 })
    })
    r.add('@state/del-entry', async (rec, ctx) => {
      const existing = await ctx.tx.get(ENTRIES, { key: rec.key })
      if (existing && typeof existing.ts === 'number' && existing.ts > (rec.ts || 0)) return
      await ctx.tx.delete(ENTRIES, { key: rec.key })
    })
    return r
  }

  // ── Membership projection (cross-base sync) ────────────────
  // Daemon's out-of-apply watcher copies keet-room membership in so apply can
  // Event-driven, self-terminating __members__ re-projection (mirrors _maybePromote). Fires on the
  // promote-timer tick + every new swarm connection. If we retain a roster (set by projectMembers),
  // haven't confirmed __members__ yet, and are writable, project it now; once landed it early-returns
  // forever (cheap when done). This is the fix for the wj62 fork: it replaces the app's bounded 12-try
  // boot loop, so a creator that becomes writable AFTER boot still lands __members__ and admits members.
  // No hang: projectMembers's base.update() drains OUR OWN writable base (clean); a non-writable device
  // no-ops here and retries on the next event.
  async _ensureMembersProjected () {
    if (this._membersProjected || !this._roster || !this._ready || !this.base || !this.base.writable) return
    try { await this.projectMembers(this._roster) } catch {}
  }

  // gate admission deterministically. Stored under the reserved key __members__
  // (a memberId-hex → role map). No-op until we're a writer (another writer
  // projects; peers replicate it).
  async projectMembers (members) {
    if (members) this._roster = members // retain the roster for event-driven, self-terminating re-projection
    if (!this._ready || !this.base || !this.base.writable) return false // not writable yet → a later event retries
    const map = {}      // memberKey(hex) -> role
    const devmap = {}   // keet writer/device key(hex) -> memberKey(hex)   (for admission model A)
    if (Array.isArray(members)) {
      for (const m of members) {
        const id = normKeyHex(m.key || m.devicePubkey || m.identity || m.memberId || m.id)
        if (!id) continue
        map[id] = Number(m.role) || 3
        const devs = Array.isArray(m.devices) ? m.devices : []
        for (const d of devs) { const dh = normKeyHex(d); if (dh) devmap[dh] = id }
      }
    } else if (members && typeof members === 'object') {
      for (const id of Object.keys(members)) { const h = normKeyHex(id); if (h) map[h] = Number(members[id]) || 3 }
    }
    // SELF-HEAL: record THIS node's own writer->identity mapping. __devices__ is otherwise written
    // only at ADMISSION time (_applySet, while a writer still carries an `admit` proof), so once an
    // entry is lost it is never rewritten — a device that is already admitted never re-announces. Each
    // node knows its own pair authoritatively, so projecting it here repopulates the map organically.
    // Mirrors atproto-base's projectMembers (base.js:313). ctx.node.from.key in _applySet IS this
    // base.local.key, so the two writers agree on the key space.
    if (this._selfKey && this.base.local && this.base.local.key) {
      devmap[this.base.local.key.toString('hex')] = this._selfKey.toString('hex')
    }

    // MERGE __devices__, never overwrite. hpp's roster is [{key, role}] with NO `devices` array
    // (device-node.js), so devmap was always {} — and an unconditional overwrite stamped with a fresh
    // ts therefore WIPED every entry admission had accumulated. ban()/REMOVE_DEVICE iterates this map
    // to removeWriter a banned member's devices, so an empty map made revocation silently remove
    // NOTHING (observed on both live DIDs: devicesInView {}). Additive only — never drops an entry.
    const prevDev = (await this.getNow('__devices__').catch(() => null)) || {}
    const mergedDev = { ...prevDev, ...devmap }

    // Never write an EMPTY roster over a populated one. Admission verifies every joiner's proof against
    // __members__ (_verifyAdmissionInApply), so wiping it denies every future admission — that is the
    // wj62 fork signature. A caller with no roster must be a no-op, not a wipe.
    const prevMembers = (await this.getNow('__members__').catch(() => null)) || {}
    if (Object.keys(map).length === 0 && Object.keys(prevMembers).length > 0) {
      console.log('[state-base-v3] room=%s projectMembers REFUSED: empty roster would wipe %d existing member(s)',
        this._roomKeyHex.slice(0, 12), Object.keys(prevMembers).length)
      return false
    }

    // Append only what actually changes — these run on the promote timer AND every swarm connection.
    if (!sameMap(prevMembers, map)) await this.base.append(encode('@state/set-entry', { key: '__members__', value: JSON.stringify(map), ts: Date.now() }))
    if (!sameMap(prevDev, mergedDev)) await this.base.append(encode('@state/set-entry', { key: '__devices__', value: JSON.stringify(mergedDev), ts: Date.now() }))
    await this.base.update()
    this._membersProjected = true // __members__ appended + drained into our view → stop re-projecting (early-returns cheaply)
    // P3 (#103): a re-projection is the moment a role change becomes visible. If THIS
    // node was just granted admin, re-check promotion immediately rather than waiting
    // for the next timer tick. Background + best-effort; the timer is the general
    // fallback for role changes replicated in from another writer's projection.
    this._maybePromote().catch(() => {})
    return true
  }

  async getProjectedRole (id) {
    if (!this._ready || !this.base) return null
    await this.base.update()
    const mrec = await this.base.view.get(ENTRIES, { key: '__members__' })
    if (!mrec || !mrec.value) return null
    let members; try { members = JSON.parse(mrec.value) } catch { return null }
    const h = normKeyHex(id)
    const role = members[h] != null ? members[h] : members[id]
    return role != null ? Number(role) : null
  }

  // ── Admission proof (op-embedded) ──────────────────────────
  // Proof attests (over localKey‖base.key, so it can't be replayed onto another
  // base) that `identity` vouches for this writer's local key. keet attestation
  // (preferred) or raw ed25519 (fallback).
  async _buildAdmissionProof () {
    if (!this.base || !this.base.local || !this.base.local.key || !this.base.key) return null
    const localKey = this.base.local.key
    const signData = Buffer.concat([localKey, this.base.key])
    // (A) keet-writer-control: sign signData with our keet ROOM writer keypair and
    // carry that writer's manifest. The verifier derives deviceKey=Hypercore.key(manifest),
    // checks sig against manifest.signers[0].publicKey, maps device→member→role.
    if (this._roomWriterKeyPair && this._roomWriterKeyPair.secretKey && this._roomWriterManifest) {
      const sig = crypto.sign(signData, toBuf(this._roomWriterKeyPair.secretKey))
      const manifestEnc = Verifier.encodeManifest(this._roomWriterManifest)
      return JSON.stringify({ manifest: Buffer.from(manifestEnc).toString('hex'), sig: sig.toString('hex') })
    }
    // legacy keet-attestation / raw-ed25519 fallback (older callers + synthetic tests)
    if (this._attest && this._selfKey) {
      const proof = await this._attest(signData)
      if (!proof) return null
      const pbuf = Buffer.isBuffer(proof) ? proof : Buffer.from(proof)
      return JSON.stringify({ identity: this._selfKey.toString('hex'), proof: pbuf.toString('hex') })
    }
    if (this._selfKeyPair && this._selfKeyPair.secretKey) {
      const sig = crypto.sign(signData, toBuf(this._selfKeyPair.secretKey))
      return JSON.stringify({ identity: toBuf(this._selfKeyPair.publicKey).toString('hex'), proof: sig.toString('hex') })
    }
    return null
  }

  // DETERMINISTIC in-apply verification (pure crypto + projected __members__).
  async _verifyAdmissionInApply (localKey, admitStr, tx) {
    try {
      const admit = typeof admitStr === 'string' ? JSON.parse(admitStr) : admitStr
      if (!admit || !this.base || !this.base.key) return null
      const signData = Buffer.concat([localKey, this.base.key])
      // (A) keet-writer-control proof: { manifest, sig }. Re-derive the keet writer/
      // device key from the manifest, verify the sig against the manifest's signer,
      // then resolve device→member (__devices__) → role (__members__).
      if (admit.manifest && admit.sig) {
        let manifest, device, signerPub
        try {
          manifest = Verifier.decodeManifest(Buffer.from(admit.manifest, 'hex'))
          device = Hypercore.key(manifest)
          signerPub = manifest.signers && manifest.signers[0] && manifest.signers[0].publicKey
        } catch (e) { console.log('[state-base-v3] verify: bad manifest %s', e.message); return null }
        if (!signerPub) { console.log('[state-base-v3] verify: manifest has no signer'); return null }
        if (!crypto.verify(signData, Buffer.from(admit.sig, 'hex'), signerPub)) {
          console.log('[state-base-v3] verify: writer sig INVALID for device=%s', device.toString('hex').slice(0, 12)); return null
        }
        const drec = await tx.get(ENTRIES, { key: '__devices__' })
        const devmap = drec && drec.value ? JSON.parse(drec.value) : {}
        const deviceHex = device.toString('hex')
        const memberKey = devmap[deviceHex] != null ? devmap[deviceHex] : devmap[normKeyHex(deviceHex)]
        if (!memberKey) { console.log('[state-base-v3] verify: device=%s NOT in __devices__', deviceHex.slice(0, 12)); return null }
        const mrec = await tx.get(ENTRIES, { key: '__members__' })
        const members = mrec && mrec.value ? JSON.parse(mrec.value) : {}
        const role = members[memberKey] != null ? members[memberKey] : members[normKeyHex(memberKey)]
        if (role == null) console.log('[state-base-v3] verify: member=%s (device %s) NOT in __members__', String(memberKey).slice(0, 12), deviceHex.slice(0, 12))
        if (role != null && await this._isRemoved(tx, memberKey, deviceHex)) { console.log('[state-base-v3] verify: member=%s is REMOVED (banned)', String(memberKey).slice(0, 12)); return null }
        return role != null ? Number(role) : null
      }
      // legacy keet-attestation / raw-ed25519 proof: { identity, proof }
      if (!admit.identity || !admit.proof) return null
      const identity = Buffer.from(admit.identity, 'hex')
      const proof = Buffer.from(admit.proof, 'hex')
      let ok = false
      if (this._verifyAttest) {
        // Pass the current minimum-epoch receipt: verifyAttest rejects a proof whose epoch is below
        // it (atproto-base-REVOCATION §3 — invalidate stale/revoked proofs after an epoch bump).
        const rcpt = await tx.get(ENTRIES, { key: RECEIPT_KEY })
        const receipt = rcpt && rcpt.value ? Buffer.from(this._dec(rcpt.value), 'hex') : null
        ok = await this._verifyAttest(proof, signData, identity, receipt)
      } else { if (proof.length !== 64) { console.log('[state-base-v3] verify: bad proof len'); return null }; ok = crypto.verify(signData, proof, identity) }
      if (!ok) { console.log('[state-base-v3] verify: proof INVALID or below min-epoch for identity=%s (verifyAttest=%s)', admit.identity.slice(0, 12), !!this._verifyAttest); return null }
      const mrec = await tx.get(ENTRIES, { key: '__members__' })
      if (!mrec || !mrec.value) { console.log('[state-base-v3] verify: no __members__ in view'); return null }
      const members = JSON.parse(mrec.value)
      const role = members[admit.identity] != null ? members[admit.identity]
        : (members[normKeyHex(admit.identity)] != null ? members[normKeyHex(admit.identity)] : null)
      if (role == null) console.log('[state-base-v3] verify: identity=%s NOT in __members__ (keys=%s)', admit.identity.slice(0, 12), Object.keys(members).map(k => k.slice(0, 8)).join(','))
      if (role != null && await this._isRemoved(tx, admit.identity)) { console.log('[state-base-v3] verify: identity=%s is REMOVED (banned)', admit.identity.slice(0, 12)); return null }
      return role != null ? Number(role) : null
    } catch (e) { console.log('[state-base-v3] verify: threw %s', e.message); return null }
  }

  watch (fn) { this._watchers.add(fn); return () => this._watchers.delete(fn) }
  // `writable` answers "will my durable writes persist?" — true once autobase has
  // activated our local writer (base.writable), OR an indexer has already admitted
  // our local writer into the linearized system writer set (cached
  // _selfIsAdmittedWriter). The admitted-writer signal is true at/before
  // base.writable's localWriter activation, so it still covers the post-admission
  // lag WITHOUT the false-positive of keying off __members__: room membership is a
  // SUPERSET of admitted writers, so an eligible member the indexer never admitted
  // (e.g. an identity absent from the indexer's own membership) must NOT read
  // writable. Sync getter uses the cache; callers wanting a fresh answer await
  // effectiveWritable(). See hyper-fleeky-dev #99.
  get writable () { return this.base?.writable || false }

  // Fresh "will my writes persist?" — refreshes the _selfIsAdmittedWriter cache.
  async effectiveWritable () {
    if (this.base && this.base.writable) return true
    return await this._refreshSelfWriter()
  }

  // Re-derive whether our LOCAL WRITER KEY (base.local.key) is in the autobase
  // linearized system writer set (base.system) — i.e. an indexer has durably
  // admitted us, so our writes finalize. This is the authoritative "admitted"
  // signal — the same one autobase's own fast-forward consults
  // (lib/fast-forward.js: system.get(base.local.key)). It is NOT mere room
  // membership: __members__ gates admission (_verifyAdmissionInApply), but being
  // in it does not mean an indexer actually admitted us (#99). base.system
  // (=_applyState.system) is null transiently on reboot/close → keep the cache.
  async _refreshSelfWriter () {
    try {
      if (!this._ready || !this.base || !this.base.local || !this.base.local.key) return this._selfIsAdmittedWriter
      await this.base.update()
      const sys = this.base.system
      if (!sys) return this._selfIsAdmittedWriter
      this._selfIsAdmittedWriter = await sys.has(this.base.local.key)
      return this._selfIsAdmittedWriter
    } catch { return this._selfIsAdmittedWriter }
  }
  get stateBaseKey () { return this.base?.key || null }
  get hasBootstrap () { return !!this._detBaseKey }

  // ── creator election (v2 logic) ────────────────────────────
  async _amCreator () {
    if (!this._getMembers || !this._selfKey) return false
    let members
    try { members = await this._getMembers() } catch { return false }
    if (!Array.isArray(members) || members.length === 0) return false
    const norm = (k) => (Buffer.isBuffer(k) ? k.toString('hex') : String(k)).toLowerCase()
    const eligible = members
      .map(m => ({ key: norm(m.key || m.devicePubkey || m.identity || m.memberId), role: Number(m.role) }))
      .filter(m => m.key && (m.role === 1 || m.role === 2))
      .sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0))
    if (eligible.length === 0) return false
    return eligible[0].key === this._selfKey.toString('hex')
  }

  // ── corruption recovery (same posture as v2 1.0.2) ─────────
  _isCorruptionError (err) {
    const m = (err && err.message ? err.message : String(err)).toUpperCase()
    return m.includes('DECODING_ERROR') || m.includes('UNKNOWN WIRE TYPE') || m.includes('CORRUPT') ||
      m.includes('INVALID DEVICE FILE') || m.includes('CHECKSUM') || m.includes('INVALID OPLOG') || m.includes('INVALID HEADER')
  }

  async _quarantineAndReset () {
    if (this.swarm) { try { await this.swarm.destroy() } catch {} ; this.swarm = null }
    if (this.base) { try { await this.base.close() } catch {} ; this.base = null }
    if (this.store) { try { await this.store.close() } catch {} ; this.store = null }
    const quarantine = this._storagePath + '.corrupt-' + Date.now()
    fs.renameSync(this._storagePath, quarantine)
    console.error('[state-base-v3] room=%s quarantined -> %s', this._roomKeyHex.slice(0, 12), quarantine)
    fs.mkdirSync(this._storagePath, { recursive: true })
    this.store = new Corestore(this._storagePath)
    await this.store.ready()
    await this._open()
  }

  async close () {
    if (this._closing) return
    this._closing = true
    if (this._promoteTimer) { clearInterval(this._promoteTimer); this._promoteTimer = null }
    if (this.swarm) { await this.swarm.destroy(); this.swarm = null }
    if (this.base) { await this.base.close(); this.base = null }
    if (this.store) { await this.store.close(); this.store = null }
    this._watchers.clear()
    this._ready = false
    this._closing = false
  }
}
const { Pull, Push, HEADERBYTES, KEYBYTES, ABYTES } = require('sodium-secretstream')
const sodium = require('sodium-universal')
const crypto = require('hypercore-crypto')
const { Duplex, Writable, getStreamError } = require('streamx')
const b4a = require('b4a')
const Timeout = require('timeout-refresh')
const unslab = require('unslab')
const Bridge = require('./lib/bridge')
const Handshake = require('./lib/handshake')

const IDHEADERBYTES = HEADERBYTES + 32
const [NS_INITIATOR, NS_RESPONDER, NS_SEND] = crypto.namespace('hyperswarm/secret-stream', 3)
const MAX_ATOMIC_WRITE = 256 * 256 * 256 - 1

module.exports = class NoiseSecretStream extends Duplex {
  constructor(isInitiator, rawStream, opts = {}) {
    super({ mapWritable: toBuffer })

    if (typeof isInitiator !== 'boolean') {
      throw new Error('isInitiator should be a boolean')
    }

    this.noiseStream = this
    this.isInitiator = isInitiator
    this.rawStream = null

    this.publicKey = opts.publicKey || null
    this.remotePublicKey = opts.remotePublicKey || null
    this.handshakeHash = null
    this.connected = false
    this.keepAlive = opts.keepAlive || 0
    this.timeout = 0
    this.enableSend = opts.enableSend !== false

    // pointer for upstream to set data here if they want
    this.userData = null

    let openedDone = null
    this.opened = new Promise((resolve) => {
      openedDone = resolve
    })

    this.rawBytesWritten = 0
    this.rawBytesRead = 0

    // metadata used by 'hyperdht'
    this.relay = null
    this.puncher = null

    // unwrapped raw stream
    this._rawStream = null

    // handshake state
    this._handshake = null
    this._handshakePattern = opts.pattern || null
    this._handshakeDone = null

    // message parsing state
    this._state = 0
    this._len = 0
    this._tmp = 1
    this._message = null

    this._openedDone = openedDone
    this._startDone = null
    this._drainDone = null
    this._outgoingPlain = null
    this._outgoingWrapped = null
    this._utp = null
    this._setup = true
    this._ended = 2
    this._encrypt = null
    this._decrypt = null
    this._timeoutTimer = null
    this._keepAliveTimer = null
    this._sendState = null

    if (opts.autoStart !== false) this.start(rawStream, opts)

    // wiggle it to trigger open immediately (TODO add streamx option for this)
    this.resume()
    this.pause()
  }

  static keyPair(seed) {
    return Handshake.keyPair(seed)
  }

  static id(handshakeHash, isInitiator, id) {
    return streamId(handshakeHash, isInitiator, id)
  }

  setTimeout(ms) {
    if (!ms) ms = 0

    this._clearTimeout()
    this.timeout = ms

    if (!ms || this.rawStream === null) return

    this._timeoutTimer = Timeout.once(ms, destroyTimeout, this)
    this._timeoutTimer.unref()
  }

  setKeepAlive(ms) {
    if (!ms) ms = 0

    this._clearKeepAlive()

    this.keepAlive = ms

    if (!ms || this.rawStream === null) return

    this._keepAliveTimer = Timeout.on(ms, sendKeepAlive, this)
    this._keepAliveTimer.unref()
  }

  sendKeepAlive() {
    const empty = this.alloc(0)
    this.write(empty)
  }

  start(rawStream, opts = {}) {
    if (rawStream) {
      this.rawStream = rawStream
      this._rawStream = rawStream
      if (typeof this.rawStream.setContentSize === 'function') {
        this._utp = rawStream
      }
    } else {
      this.rawStream = new Bridge(this)
      this._rawStream = this.rawStream.reverse
    }

    this.rawStream.on('error', this._onrawerror.bind(this))
    this.rawStream.on('close', this._onrawclose.bind(this))

    this._startHandshake(opts.handshake, opts.keyPair || null)
    this._continueOpen(null)

    if (this.destroying) return

    if (opts.data) this._onrawdata(opts.data)
    if (opts.ended) this._onrawend()

    if (this.keepAlive > 0 && this._keepAliveTimer === null) {
      this.setKeepAlive(this.keepAlive)
    }

    if (this.timeout > 0 && this._timeoutTimer === null) {
      this.setTimeout(this.timeout)
    }
  }

  async flush() {
    if ((await this.opened) === false) return false
    if ((await Writable.drained(this)) === false) return false
    if (this.destroying) return false

    if (this.rawStream !== null && this.rawStream.flush) {
      return await this.rawStream.flush()
    }

    return true
  }

  _continueOpen(err) {
    if (err) this.destroy(err)
    if (this._startDone === null) return
    const done = this._startDone
    this._startDone = null
    this._open(done)
  }

  _onkeypairpromise(p) {
    const self = this
    const cont = this._continueOpen.bind(this)

    p.then(onkeypair, cont)

    function onkeypair(kp) {
      self._onkeypair(kp)
      cont(null)
    }
  }

  _onkeypair(keyPair) {
    const pattern = this._handshakePattern || 'XX'
    const remotePublicKey = this.remotePublicKey

    this._handshake = new Handshake(this.isInitiator, keyPair, remotePublicKey, pattern)
    this.publicKey = this._handshake.keyPair.publicKey
  }

  _startHandshake(handshake, keyPair) {
    if (handshake) {
      const { tx, rx, hash, publicKey, remotePublicKey } = handshake
      this._setupSecretStream(tx, rx, hash, publicKey, remotePublicKey)
      return
    }

    if (!keyPair) keyPair = Handshake.keyPair()

    if (typeof keyPair.then === 'function') {
      this._onkeypairpromise(keyPair)
    } else {
      this._onkeypair(keyPair)
    }
  }

  _onrawerror(err) {
    this.destroy(err)
  }

  _onrawclose() {
    if (this._ended !== 0) this.destroy()
  }

  _onrawdata(data) {
    let offset = 0

    if (this._timeoutTimer !== null) {
      this._timeoutTimer.refresh()
    }

    do {
      switch (this._state) {
        case 0: {
          while (this._tmp !== 0x1000000 && offset < data.byteLength) {
            const v = data[offset++]
            this._len += this._tmp * v
            this._tmp *= 256
          }

          if (this._tmp === 0x1000000) {
            this._tmp = 0
            this._state = 1
            const unprocessed = data.byteLength - offset
            if (unprocessed < this._len && this._utp !== null)
              this._utp.setContentSize(this._len - unprocessed)
          }

          break
        }

        case 1: {
          const missing = this._len - this._tmp
          const end = missing + offset

          if (this._message === null && end <= data.byteLength) {
            this._message = data.subarray(offset, end)
            offset += missing
            this._incoming()
            break
          }

          const unprocessed = data.byteLength - offset

          if (this._message === null) {
            this._message = b4a.allocUnsafe(this._len)
          }

          b4a.copy(data, this._message, this._tmp, offset)
          this._tmp += unprocessed

          if (end <= data.byteLength) {
            offset += missing
            this._incoming()
          } else {
            offset += unprocessed
          }

          break
        }
      }
    } while (offset < data.byteLength && !this.destroying)
  }

  _onrawend() {
    this._ended--
    this.push(null)
  }

  _onrawdrain() {
    const drain = this._drainDone
    if (drain === null) return
    this._drainDone = null
    drain()
  }

  _read(cb) {
    this.rawStream.resume()
    cb(null)
  }

  _incoming() {
    const message = this._message

    this._state = 0
    this._len = 0
    this._tmp = 1
    this._message = null

    if (this._setup === true) {
      if (this._handshake) {
        this._onhandshakert(this._handshake.recv(message))
      } else {
        if (message.byteLength !== IDHEADERBYTES) {
          this.destroy(new Error('Invalid header message received'))
          return
        }

        const remoteId = message.subarray(0, 32)
        const expectedId = streamId(this.handshakeHash, !this.isInitiator)
        const header = message.subarray(32)

        if (!b4a.equals(expectedId, remoteId)) {
          this.destroy(new Error('Invalid header received'))
          return
        }

        this._decrypt.init(header)
        this._setup = false // setup is now done
      }
      return
    }

    if (message.byteLength < ABYTES) {
      this.destroy(new Error('Invalid message received'))
      return
    }

    this.rawBytesRead += message.byteLength

    const plain = message.subarray(1, message.byteLength - ABYTES + 1)

    try {
      this._decrypt.next(message, plain)
    } catch (err) {
      this.destroy(err)
      return
    }

    // If keep alive is selective, eat the empty buffers (ie assume the other side has it enabled also)
    if (plain.byteLength === 0 && this.keepAlive !== 0) return

    if (this.push(plain) === false) {
      this.rawStream.pause()
    }
  }

  _onhandshakert(h) {
    if (this._handshakeDone === null) return

    if (h !== null) {
      if (h.data) this._rawStream.write(h.data)
      if (!h.tx) return
    }

    const done = this._handshakeDone
    const publicKey = this._handshake.keyPair.publicKey

    this._handshakeDone = null
    this._handshake = null

    if (h === null) return done(new Error('Noise handshake failed'))

    this._setupSecretStream(h.tx, h.rx, h.hash, publicKey, h.remotePublicKey)
    this._resolveOpened(true)
    done(null)
  }

  _setupSecretStream(tx, rx, handshakeHash, publicKey, remotePublicKey) {
    const buf = b4a.allocUnsafeSlow(3 + IDHEADERBYTES)
    writeUint24le(IDHEADERBYTES, buf)

    this._encrypt = new Push(unslab(tx.subarray(0, KEYBYTES)), undefined, buf.subarray(3 + 32))
    this._decrypt = new Pull(unslab(rx.subarray(0, KEYBYTES)))

    this.publicKey = publicKey
    this.remotePublicKey = remotePublicKey
    this.handshakeHash = handshakeHash

    const id = buf.subarray(3, 3 + 32)
    streamId(handshakeHash, this.isInitiator, id)

    // initialize secretbox state for unordered messages
    this._setupSecretSend(handshakeHash)

    this.emit('handshake')
    // if rawStream is a bridge, also emit it there
    if (this.rawStream !== this._rawStream) this.rawStream.emit('handshake')

    if (this.destroying) return

    this._rawStream.write(buf)
  }

  _setupSecretSend(handshakeHash) {
    this._sendState = b4a.allocUnsafeSlow(32 + 32 + 8 + 8)
    const encrypt = this._sendState.subarray(0, 32) // secrets
    const decrypt = this._sendState.subarray(32, 64)
    const counter = this._sendState.subarray(64, 72) // nonce
    const initial = this._sendState.subarray(72)

    const inputs = this.isInitiator
      ? [
          [NS_INITIATOR, NS_SEND],
          [NS_RESPONDER, NS_SEND]
        ]
      : [
          [NS_RESPONDER, NS_SEND],
          [NS_INITIATOR, NS_SEND]
        ]

    sodium.crypto_generichash_batch(encrypt, inputs[0], handshakeHash)
    sodium.crypto_generichash_batch(decrypt, inputs[1], handshakeHash)

    sodium.randombytes_buf(initial)
    counter.set(initial)
  }

  _open(cb) {
    // no autostart or no handshake yet
    if (this._rawStream === null || (this._handshake === null && this._encrypt === null)) {
      this._startDone = cb
      return
    }

    this._rawStream.on('data', this._onrawdata.bind(this))
    this._rawStream.on('end', this._onrawend.bind(this))
    this._rawStream.on('drain', this._onrawdrain.bind(this))

    if (this.enableSend) this._rawStream.on('message', this._onmessage.bind(this))

    if (this._encrypt !== null) {
      this._resolveOpened(true)
      return cb(null)
    }

    this._handshakeDone = cb

    if (this.isInitiator) this._onhandshakert(this._handshake.send())
  }

  _predestroy() {
    if (this.rawStream) {
      const error = getStreamError(this)
      this.rawStream.destroy(error)
    }

    if (this._startDone !== null) {
      const done = this._startDone
      this._startDone = null
      done(new Error('Stream destroyed'))
    }

    if (this._handshakeDone !== null) {
      const done = this._handshakeDone
      this._handshakeDone = null
      done(new Error('Stream destroyed'))
    }

    if (this._drainDone !== null) {
      const done = this._drainDone
      this._drainDone = null
      done(new Error('Stream destroyed'))
    }
  }

  _write(data, cb) {
    let wrapped = this._outgoingWrapped

    if (data !== this._outgoingPlain) {
      wrapped = b4a.allocUnsafe(data.byteLength + 3 + ABYTES)
      wrapped.set(data, 4)
    } else {
      this._outgoingWrapped = this._outgoingPlain = null
    }

    if (wrapped.byteLength - 3 > MAX_ATOMIC_WRITE) {
      return cb(
        new Error(
          'Message is too large for an atomic write. Max size is ' + MAX_ATOMIC_WRITE + ' bytes.'
        )
      )
    }
    this.rawBytesWritten += wrapped.byteLength

    writeUint24le(wrapped.byteLength - 3, wrapped)
    // offset 4 so we can do it in-place
    this._encrypt.next(wrapped.subarray(4, 4 + data.byteLength), wrapped.subarray(3))

    if (this._keepAliveTimer !== null) this._keepAliveTimer.refresh()

    if (this._rawStream.write(wrapped) === false) {
      this._drainDone = cb
    } else {
      cb(null)
    }
  }

  _final(cb) {
    this._clearKeepAlive()
    this._ended--
    this._rawStream.end()
    cb(null)
  }

  _resolveOpened(val) {
    if (this._openedDone === null) return
    const opened = this._openedDone
    this._openedDone = null
    opened(val)
    if (!val) return
    this.connected = true
    this.emit('connect')
  }

  _clearTimeout() {
    if (this._timeoutTimer === null) return
    this._timeoutTimer.destroy()
    this._timeoutTimer = null
    this.timeout = 0
  }

  _clearKeepAlive() {
    if (this._keepAliveTimer === null) return
    this._keepAliveTimer.destroy()
    this._keepAliveTimer = null
    this.keepAlive = 0
  }

  _destroy(cb) {
    this._clearKeepAlive()
    this._clearTimeout()
    this._resolveOpened(false)
    cb(null)
  }

  _boxMessage(buffer) {
    const MB = sodium.crypto_secretbox_MACBYTES // 16
    const NB = sodium.crypto_secretbox_NONCEBYTES // 24

    const counter = this._sendState.subarray(64, 72)
    sodium.sodium_increment(counter)
    if (b4a.equals(counter, this._sendState.subarray(72))) {
      this.destroy(new Error('udp send nonce exchausted'))
      return
    }

    const secret = this._sendState.subarray(0, 32)
    const envelope = b4a.allocUnsafe(8 + MB + buffer.byteLength)
    const nonce = envelope.subarray(0, NB)
    const ciphertext = envelope.subarray(8)

    b4a.fill(nonce, 0) // pad suffix
    nonce.set(counter)

    sodium.crypto_secretbox_easy(ciphertext, buffer, nonce, secret)
    return envelope
  }

  send(buffer) {
    if (!this._sendState) return
    if (!this.rawStream?.send) return // udx-stream expected

    const message = this._boxMessage(buffer)
    return this.rawStream.send(message)
  }

  trySend(buffer) {
    if (!this._sendState) return
    if (!this.rawStream?.trySend) return // udx-stream expected

    const message = this._boxMessage(buffer)
    this.rawStream.trySend(message)
  }

  _onmessage(buffer) {
    if (!this._sendState) return // messages before handshake are dropped

    const MB = sodium.crypto_secretbox_MACBYTES // 16
    const NB = sodium.crypto_secretbox_NONCEBYTES // 24

    if (buffer.byteLength < NB) return // Invalid message

    const nonce = b4a.allocUnsafe(NB)
    b4a.fill(nonce, 0)
    nonce.set(buffer.subarray(0, 8))

    const secret = this._sendState.subarray(32, 64)
    const ciphertext = buffer.subarray(8)
    const plain = buffer.subarray(8, buffer.byteLength - MB)

    if (ciphertext.byteLength < MB) return // invalid message

    const success = sodium.crypto_secretbox_open_easy(plain, ciphertext, nonce, secret)

    if (success) this.emit('message', plain)
  }

  alloc(len) {
    const buf = b4a.allocUnsafe(len + 3 + ABYTES)
    this._outgoingWrapped = buf
    this._outgoingPlain = buf.subarray(4, buf.byteLength - ABYTES + 1)
    return this._outgoingPlain
  }

  toJSON() {
    return {
      isInitiator: this.isInitiator,
      publicKey: this.publicKey && b4a.toString(this.publicKey, 'hex'),
      remotePublicKey: this.remotePublicKey && b4a.toString(this.remotePublicKey, 'hex'),
      connected: this.connected,
      destroying: this.destroying,
      destroyed: this.destroyed,
      rawStream: this.rawStream && this.rawStream.toJSON ? this.rawStream.toJSON() : null
    }
  }
}

function writeUint24le(n, buf) {
  buf[0] = n & 255
  buf[1] = (n >>> 8) & 255
  buf[2] = (n >>> 16) & 255
}

function streamId(handshakeHash, isInitiator, out = b4a.allocUnsafe(32)) {
  sodium.crypto_generichash(out, isInitiator ? NS_INITIATOR : NS_RESPONDER, handshakeHash)
  return out
}

function toBuffer(data) {
  return typeof data === 'string' ? b4a.from(data) : data
}

function destroyTimeout() {
  this.destroy(new Error('Stream timed out'))
}

function sendKeepAlive() {
  const empty = this.alloc(0)
  this.write(empty)
}
const { Duplex, Writable } = require('streamx')

class ReversePassThrough extends Duplex {
  constructor(s) {
    super()
    this._stream = s
    this._ondrain = null
  }

  _write(data, cb) {
    if (this._stream.push(data) === false) {
      this._stream._ondrain = cb
    } else {
      cb(null)
    }
  }

  _final(cb) {
    this._stream.push(null)
    cb(null)
  }

  _read(cb) {
    const ondrain = this._ondrain
    this._ondrain = null
    if (ondrain) ondrain()
    cb(null)
  }
}

module.exports = class Bridge extends Duplex {
  constructor(noiseStream) {
    super()

    this.noiseStream = noiseStream

    this._ondrain = null
    this.reverse = new ReversePassThrough(this)
  }

  get publicKey() {
    return this.noiseStream.publicKey
  }

  get remotePublicKey() {
    return this.noiseStream.remotePublicKey
  }

  get handshakeHash() {
    return this.noiseStream.handshakeHash
  }

  flush() {
    return Writable.drained(this)
  }

  _read(cb) {
    const ondrain = this._ondrain
    this._ondrain = null
    if (ondrain) ondrain()
    cb(null)
  }

  _write(data, cb) {
    if (this.reverse.push(data) === false) {
      this.reverse._ondrain = cb
    } else {
      cb(null)
    }
  }

  _final(cb) {
    this.reverse.push(null)
    cb(null)
  }
}
const sodium = require('sodium-universal')
const curve = require('noise-curve-ed')
const Noise = require('noise-handshake')
const b4a = require('b4a')

const EMPTY = b4a.alloc(0)

module.exports = class Handshake {
  constructor(isInitiator, keyPair, remotePublicKey, pattern) {
    this.isInitiator = isInitiator
    this.keyPair = keyPair
    this.noise = new Noise(pattern, isInitiator, keyPair, { curve })
    this.noise.initialise(EMPTY, remotePublicKey)
    this.destroyed = false
  }

  static keyPair(seed) {
    const publicKey = b4a.alloc(32)
    const secretKey = b4a.alloc(64)
    if (seed) sodium.crypto_sign_seed_keypair(publicKey, secretKey, seed)
    else sodium.crypto_sign_keypair(publicKey, secretKey)
    return { publicKey, secretKey }
  }

  recv(data) {
    try {
      this.noise.recv(data)
      if (this.noise.complete) return this._return(null)
      return this.send()
    } catch {
      this.destroy()
      return null
    }
  }

  // note that the data returned here is framed so we don't have to do an extra copy
  // when sending it...
  send() {
    try {
      const data = this.noise.send()
      const wrap = b4a.allocUnsafe(data.byteLength + 3)

      writeUint24le(data.byteLength, wrap)
      wrap.set(data, 3)

      return this._return(wrap)
    } catch {
      this.destroy()
      return null
    }
  }

  destroy() {
    if (this.destroyed) return
    this.destroyed = true
  }

  _return(data) {
    const tx = this.noise.complete ? b4a.toBuffer(this.noise.tx) : null
    const rx = this.noise.complete ? b4a.toBuffer(this.noise.rx) : null
    const hash = this.noise.complete ? b4a.toBuffer(this.noise.hash) : null
    const remotePublicKey = this.noise.complete ? b4a.toBuffer(this.noise.rs) : null

    return {
      data,
      remotePublicKey,
      hash,
      tx,
      rx
    }
  }
}

function writeUint24le(n, buf) {
  buf[0] = n & 255
  buf[1] = (n >>> 8) & 255
  buf[2] = (n >>> 16) & 255
}
{
  "name": "@hyperswarm/secret-stream",
  "version": "6.9.1",
  "description": "Secret stream backed by Noise and libsodium's secretstream",
  "main": "index.js",
  "files": [
    "index.js",
    "lib/**.js"
  ],
  "dependencies": {
    "b4a": "^1.1.0",
    "hypercore-crypto": "^3.3.1",
    "noise-curve-ed": "^2.0.1",
    "noise-handshake": "^4.0.0",
    "sodium-secretstream": "^1.1.0",
    "sodium-universal": "^5.0.0",
    "streamx": "^2.14.0",
    "timeout-refresh": "^2.0.0",
    "unslab": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "udx-native": "^1.13.2"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check .",
    "test": "brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/hyperswarm-secret-stream.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/hyperswarm-secret-stream/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperswarm-secret-stream"
}
{
  "name": "@ipld/dag-cbor",
  "version": "9.2.7",
  "description": "JS implementation of DAG-CBOR",
  "author": "Rod <rod@vagg.org> (http://r.va.gg/)",
  "license": "Apache-2.0 OR MIT",
  "homepage": "https://github.com/ipld/js-dag-cbor#readme",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/ipld/js-dag-cbor.git"
  },
  "bugs": {
    "url": "https://github.com/ipld/js-dag-cbor/issues"
  },
  "publishConfig": {
    "access": "public",
    "provenance": true
  },
  "keywords": [
    "ipfs",
    "ipld",
    "multiformats"
  ],
  "type": "module",
  "types": "./dist/src/index.d.ts",
  "typesVersions": {
    "*": {
      "*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ],
      "src/*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ]
    }
  },
  "files": [
    "src",
    "dist",
    "!dist/test",
    "!**/*.tsbuildinfo"
  ],
  "exports": {
    ".": {
      "types": "./dist/src/index.d.ts",
      "import": "./src/index.js",
      "module-sync": "./src/index.js"
    }
  },
  "release": {
    "branches": [
      "master"
    ],
    "plugins": [
      [
        "@semantic-release/commit-analyzer",
        {
          "preset": "conventionalcommits",
          "releaseRules": [
            {
              "breaking": true,
              "release": "major"
            },
            {
              "revert": true,
              "release": "patch"
            },
            {
              "type": "feat",
              "release": "minor"
            },
            {
              "type": "fix",
              "release": "patch"
            },
            {
              "type": "docs",
              "release": "patch"
            },
            {
              "type": "test",
              "release": "patch"
            },
            {
              "type": "deps",
              "release": "patch"
            },
            {
              "scope": "no-release",
              "release": false
            }
          ]
        }
      ],
      [
        "@semantic-release/release-notes-generator",
        {
          "preset": "conventionalcommits",
          "presetConfig": {
            "types": [
              {
                "type": "feat",
                "section": "Features"
              },
              {
                "type": "fix",
                "section": "Bug Fixes"
              },
              {
                "type": "chore",
                "section": "Trivial Changes"
              },
              {
                "type": "docs",
                "section": "Documentation"
              },
              {
                "type": "deps",
                "section": "Dependencies"
              },
              {
                "type": "test",
                "section": "Tests"
              }
            ]
          }
        }
      ],
      "@semantic-release/changelog",
      "@semantic-release/npm",
      "@semantic-release/github",
      [
        "@semantic-release/git",
        {
          "assets": [
            "CHANGELOG.md",
            "package.json"
          ]
        }
      ]
    ]
  },
  "scripts": {
    "clean": "aegir clean",
    "lint": "aegir lint",
    "build": "aegir build",
    "release": "aegir release",
    "test": "npm run lint && aegir test",
    "test:ts": "npm run test --prefix test/ts-use",
    "test:node": "aegir test -t node --cov",
    "test:chrome": "aegir test -t browser --cov",
    "test:chrome-webworker": "aegir test -t webworker",
    "test:firefox": "aegir test -t browser -- --browser firefox",
    "test:firefox-webworker": "aegir test -t webworker -- --browser firefox",
    "test:electron-main": "aegir test -t electron-main",
    "dep-check": "aegir dep-check"
  },
  "dependencies": {
    "cborg": "^5.0.1",
    "multiformats": "^13.1.0"
  },
  "devDependencies": {
    "@ipld/garbage": "^6.0.0",
    "aegir": "^48.0.1"
  }
}
import * as cborg from 'cborg'
import { CID } from 'multiformats/cid'

// https://github.com/ipfs/go-ipfs/issues/3570#issuecomment-273931692
const CID_CBOR_TAG = 42

/**
 * @template T
 * @typedef {import('multiformats/codecs/interface').ByteView<T>} ByteView
 */

/**
 * @template T
 * @typedef {import('multiformats/codecs/interface').ArrayBufferView<T>} ArrayBufferView
 */

/**
 * @template T
 * @param {ByteView<T> | ArrayBufferView<T>} buf
 * @returns {ByteView<T>}
 */
export function toByteView (buf) {
  if (buf instanceof ArrayBuffer) {
    return new Uint8Array(buf, 0, buf.byteLength)
  }

  return buf
}

/**
 * cidEncoder will receive all Objects during encode, it needs to filter out
 * anything that's not a CID and return `null` for that so it's encoded as
 * normal.
 *
 * @param {any} obj
 * @returns {cborg.Token[]|null}
 */
function cidEncoder (obj) {
  if (obj.asCID !== obj && obj['/'] !== obj.bytes) {
    return null // any other kind of object
  }
  const cid = CID.asCID(obj)
  /* c8 ignore next 4 */
  // very unlikely case, and it'll probably throw a recursion error in cborg
  if (!cid) {
    return null
  }
  const bytes = new Uint8Array(cid.bytes.byteLength + 1)
  bytes.set(cid.bytes, 1) // prefix is 0x00, for historical reasons
  return [
    new cborg.Token(cborg.Type.tag, CID_CBOR_TAG),
    new cborg.Token(cborg.Type.bytes, bytes)
  ]
}

// eslint-disable-next-line jsdoc/require-returns-check
/**
 * Intercept all `undefined` values from an object walk and reject the entire
 * object if we find one.
 *
 * @returns {null}
 */
function undefinedEncoder () {
  throw new Error('`undefined` is not supported by the IPLD Data Model and cannot be encoded')
}

/**
 * Intercept all `number` values from an object walk and reject the entire
 * object if we find something that doesn't fit the IPLD data model (NaN &
 * Infinity).
 *
 * @param {number} num
 * @returns {null}
 */
function numberEncoder (num) {
  if (Number.isNaN(num)) {
    throw new Error('`NaN` is not supported by the IPLD Data Model and cannot be encoded')
  }
  if (num === Infinity || num === -Infinity) {
    throw new Error('`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded')
  }
  return null
}

/**
 * @param {Map<any, any>} map
 * @returns {null}
 */
function mapEncoder (map) {
  for (const key of map.keys()) {
    if (typeof key !== 'string' || key.length === 0) {
      throw new Error('Non-string Map keys are not supported by the IPLD Data Model and cannot be encoded')
    }
  }
  return null
}

const _encodeOptions = {
  float64: true,
  typeEncoders: {
    Map: mapEncoder,
    Object: cidEncoder,
    undefined: undefinedEncoder,
    number: numberEncoder
  }
}

export const encodeOptions = {
  ..._encodeOptions,
  typeEncoders: {
    ..._encodeOptions.typeEncoders
  }
}

/**
 * @param {import('cborg').TagDecodeControl} decode
 * @returns {CID}
 */
function cidDecoder (decode) {
  const bytes = /** @type {Uint8Array} */ (decode())
  if (bytes[0] !== 0) {
    throw new Error('Invalid CID for CBOR tag 42; expected leading 0x00')
  }
  return CID.decode(bytes.subarray(1)) // ignore leading 0x00
}

const _decodeOptions = {
  allowIndefinite: false,
  coerceUndefinedToNull: true,
  allowNaN: false,
  allowInfinity: false,
  allowBigInt: true, // this will lead to BigInt for ints outside of
  // safe-integer range, which may surprise users
  strict: true,
  useMaps: false,
  rejectDuplicateMapKeys: true,
  /** @type {{ [tagNumber: number]: import('cborg').TagDecoder }} */
  tags: { [CID_CBOR_TAG]: cidDecoder }
}

export const decodeOptions = {
  ..._decodeOptions,
  tags: { ..._decodeOptions.tags }
}

export const name = 'dag-cbor'
export const code = 0x71

/**
 * @template T
 * @param {T} node
 * @returns {ByteView<T>}
 */
export const encode = (node) => cborg.encode(node, _encodeOptions)

/**
 * @template T
 * @param {ByteView<T> | ArrayBufferView<T>} data
 * @returns {T}
 */
export const decode = (data) => cborg.decode(toByteView(data), _decodeOptions)
const Cache = require('xache')

module.exports = class AdaptiveTimeout {
  constructor(opts = {}) {
    this._cache = new Cache({
      maxSize: opts.maxSize || 65536,
      maxAge: opts.maxAge || 10 * 60 * 1000 // 10 minutes
    })
    this._fallback = opts.fallback || AdaptiveTimeout.TimeoutExponential
    this._min = opts.min ?? 300
    this._max = opts.max || 4000
    this._jitter = opts.jitter ?? 256
  }

  // Default - aggressive ramp
  static TimeoutAggressive = [500, 750, 1000, 1500, 2000]

  // Linear - steady increase
  static TimeoutLinear = [500, 1000, 1500, 2000, 2500]

  // Exponential - slow start, rapid backoff
  static TimeoutExponential = [250, 500, 1000, 2000, 4000]

  // Gentle - conservative, patient
  static TimeoutGentle = [1000, 1250, 1500, 1750, 2000]

  // Fast - rapid fire retries
  static TimeoutFast = [200, 400, 600, 800, 1000]

  // U-shape - long, short, long
  static TimeoutUShape = [1500, 750, 500, 750, 1500]

  // Inverse U - short, long, short
  static TimeoutInverseU = [500, 1000, 1500, 1000, 500]

  // Sawtooth - alternating fast/slow
  static TimeoutSawtooth = [500, 1500, 500, 1500, 500]

  // Plateau - quick ramp then steady
  static TimeoutPlateau = [500, 1000, 2000, 2000, 2000]

  // Logarithmic - diminishing increases
  static TimeoutLogarithmic = [500, 1000, 1300, 1500, 1600]

  getValue(key) {
    return this._cache.get(key)
  }

  put(key, value) {
    let p = this._cache.get(key)

    if (!p) {
      p = { avg: value, variance: value >> 1 }
    } else {
      // blend 75% old + 25% new deviation
      p.variance += (Math.abs(p.avg - value) - p.variance) >> 2
      // blend 87.5% old + 12.5% new sample
      p.avg += (value - p.avg) >> 3
    }

    this._cache.set(key, p)

    return p
  }

  get(key, attempt = 1) {
    const p = this._cache.get(key)
    const jitter = (Math.random() * this._jitter) | 0

    if (p) {
      // known - use adaptive with linear backoff
      const base = p.avg + (p.variance << 1)
      const backoff = base * attempt
      return Math.min(Math.max(backoff + jitter, this._min), this._max)
    } else {
      // unknown - use aggressive fallback
      const base = this._fallback[Math.min(attempt - 1, this._fallback.length - 1)]
      return base + jitter
    }
  }

  has(key) {
    return this._cache.has(key)
  }

  delete(key) {
    return this._cache.delete(key)
  }

  clear() {
    this._cache.clear()
  }
}
{
  "name": "adaptive-timeout",
  "version": "1.0.1",
  "description": "adaptive-timeout",
  "main": "index.js",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    }
  },
  "files": [
    "package.json",
    "index.js",
    "index.d.ts"
  ],
  "devDependencies": {
    "brittle": "^3.19.0",
    "lunte": "^1.2.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && lunte && brittle-bare test/index.js",
    "lint": "lunte"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/adaptive-timeout.git"
  },
  "author": "Holepunch Inc",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/adaptive-timeout/issues"
  },
  "homepage": "https://github.com/holepunchto/adaptive-timeout",
  "dependencies": {
    "xache": "^1.2.1"
  }
}
// keet-identity-key device chain — the P2P-verifiable half of device attestation.
//
// Runs in PARALLEL to the atproto PLC authority (device-attestation.js). atproto's
// rotationKeys/PLC-op-log carry the FEDERATION-visible authority (secp256k1); this keet
// chain carries the authority OUR P2P world verifies (Ed25519). Both anchor on the same
// root identity and vouch for the same device.
//
// Shape (from keet-identity-key): a proof is `{ identity, epoch, chain: [{publicKey,
// signature}], data? }`. `bootstrap` attests a device pubkey under the root identity;
// `attestData` lets the (leaf) device sign arbitrary data — here, the atproto DID — so a
// verifier learns "root → device → this device vouches for did:plc:…". `verify` walks the
// chain back to the identity and checks the data signature.

import IdentityKey from 'keet-identity-key'
import b4a from 'b4a'

// The device's keet-world Ed25519 keypair (derived from the device seed) — distinct from
// its secp256k1 atproto signing key. This is the device's identity in the keet chain.
export async function deviceKeetKeyPair (mnemonic, seed) {
  const idk = await IdentityKey.from({ mnemonic, seed })
  return idk.identityKeyPair // { publicKey, secretKey }
}

// The root identity's Ed25519 public key — the anchor every chain must resolve to.
export async function rootIdentityPublicKey (mnemonic, seed) {
  const idk = await IdentityKey.from({ mnemonic, seed })
  return b4a.from(idk.identityPublicKey)
}

// Root identity attests a device's Ed25519 public key → an encoded proof chain.
export async function attestDeviceChain ({ rootMnemonic, rootSeed, devicePublicKey }) {
  return IdentityKey.bootstrap({ mnemonic: rootMnemonic, seed: rootSeed }, devicePublicKey)
}

// An ALREADY-ATTESTED device attests ANOTHER device, extending the chain: root → parent → child.
// keet's attestDevice signs { epoch, identity, device } with the PARENT's keypair and pushes
// { publicKey, signature } onto the parent's chain, so the result still resolves to the same root
// identity and the same epoch — a chained device passes the identical admission gate and the identical
// minimum-epoch receipt check as a root-attested one.
//
// WHY THIS MATTERS OPERATIONALLY: admitting a new device to a room needs a proof anchored at the room's
// root identity, and attestDeviceChain above needs the ROOT MNEMONIC — which is deliberately not stored
// on any node (config.js: a device "must never hold" it). Read alone, that makes adding a co-owner
// impossible without recovering a secret nobody kept. It is not: an existing attested device already has
// everything required to vouch for the next one. Only the root's PUBLIC key is needed to verify.
//
// parentKeyPair: the attesting device's Ed25519 identity keypair (deviceKeetKeyPair of its mnemonic).
// parentProof: that device's own proof (root-attested, or itself chained — chains nest).
export function attestDeviceViaDevice ({ parentKeyPair, parentProof, devicePublicKey }) {
  if (!parentKeyPair || !parentProof || !devicePublicKey) throw new Error('attestDeviceViaDevice: parentKeyPair, parentProof, devicePublicKey required')
  // Pass the proof as BYTES: keet decodes a fresh copy, so the caller's proof is never mutated by the
  // chain.push inside attestDevice (it would otherwise grow the parent's own proof on every call).
  const proof = b4a.isBuffer(parentProof) ? parentProof : b4a.from(parentProof)
  return IdentityKey.attestDevice(b4a.from(devicePublicKey), parentKeyPair, proof)
}

// The attested (leaf) device vouches for the atproto DID by signing it as attested data,
// extending the proof with `proof.data`. Result: root → device → vouches-for(did).
export function attestAtprotoBinding ({ deviceKeyPair, did, proof }) {
  return IdentityKey.attestData(b4a.from(did), deviceKeyPair, proof)
}

// Verify the full binding: the chain resolves to the root identity AND the device vouched
// for exactly this DID. Returns { receipt, identityPublicKey, devicePublicKey } or null.
export function verifyAtprotoBinding ({ proof, did, expectedIdentity, expectedDevice }) {
  return IdentityKey.verify(proof, b4a.from(did), { expectedIdentity, expectedDevice })
}
// DID-derived P2P discovery (the "sneaky P2P" binding, Option 2).
//
// The rendezvous topic for a DID is DERIVED, not written anywhere: the DID document stays
// 100% vanilla atproto (only atproto_pds -> the bridge), so bsky/HTTP never sees a P2P side.
// A self-custody peer announces on discoveryTopic(did); a bridge, given the DID, derives the
// SAME topic, connects, and AUTHENTICATES the peer on connect (the peer's served repo must
// sign against the DID's key — a squatter on the public topic can't forge that). So the lookup
// is deterministic + unauthenticated; trust is established at the connection, not the address.

import crypto from 'hypercore-crypto'

const NS = 'hyper-proto-peer/discovery/v1:'

// did (string) -> 32-byte Hyperswarm topic. Deterministic; anyone with the DID can compute it.
export function discoveryTopic (did) {
  if (!did || typeof did !== 'string') throw new Error('discoveryTopic: did (string) required')
  return crypto.data(new TextEncoder().encode(NS + did))
}
function isBuffer(value) {
  return Buffer.isBuffer(value) || value instanceof Uint8Array
}

function isEncoding(encoding) {
  return Buffer.isEncoding(encoding)
}

function alloc(size, fill, encoding) {
  return Buffer.alloc(size, fill, encoding)
}

function allocUnsafe(size) {
  return Buffer.allocUnsafe(size)
}

function allocUnsafeSlow(size) {
  return Buffer.allocUnsafeSlow(size)
}

function byteLength(string, encoding) {
  return Buffer.byteLength(string, encoding)
}

function compare(a, b) {
  return Buffer.compare(a, b)
}

function concat(buffers, totalLength) {
  return Buffer.concat(buffers, totalLength)
}

function copy(source, target, targetStart, start, end) {
  return toBuffer(source).copy(target, targetStart, start, end)
}

function equals(a, b) {
  return toBuffer(a).equals(b)
}

function fill(buffer, value, offset, end, encoding) {
  return toBuffer(buffer).fill(value, offset, end, encoding)
}

function from(value, encodingOrOffset, length) {
  return Buffer.from(value, encodingOrOffset, length)
}

function includes(buffer, value, byteOffset, encoding) {
  return toBuffer(buffer).includes(value, byteOffset, encoding)
}

function indexOf(buffer, value, byfeOffset, encoding) {
  return toBuffer(buffer).indexOf(value, byfeOffset, encoding)
}

function lastIndexOf(buffer, value, byteOffset, encoding) {
  return toBuffer(buffer).lastIndexOf(value, byteOffset, encoding)
}

function swap16(buffer) {
  return toBuffer(buffer).swap16()
}

function swap32(buffer) {
  return toBuffer(buffer).swap32()
}

function swap64(buffer) {
  return toBuffer(buffer).swap64()
}

function toBuffer(buffer) {
  if (Buffer.isBuffer(buffer)) return buffer
  return Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

function toString(buffer, encoding, start, end) {
  return toBuffer(buffer).toString(encoding, start, end)
}

function write(buffer, string, offset, length, encoding) {
  return toBuffer(buffer).write(string, offset, length, encoding)
}

function readDoubleBE(buffer, offset) {
  return toBuffer(buffer).readDoubleBE(offset)
}

function readDoubleLE(buffer, offset) {
  return toBuffer(buffer).readDoubleLE(offset)
}

function readFloatBE(buffer, offset) {
  return toBuffer(buffer).readFloatBE(offset)
}

function readFloatLE(buffer, offset) {
  return toBuffer(buffer).readFloatLE(offset)
}

function readInt32BE(buffer, offset) {
  return toBuffer(buffer).readInt32BE(offset)
}

function readInt32LE(buffer, offset) {
  return toBuffer(buffer).readInt32LE(offset)
}

function readUInt32BE(buffer, offset) {
  return toBuffer(buffer).readUInt32BE(offset)
}

function readUInt32LE(buffer, offset) {
  return toBuffer(buffer).readUInt32LE(offset)
}

function writeDoubleBE(buffer, value, offset) {
  return toBuffer(buffer).writeDoubleBE(value, offset)
}

function writeDoubleLE(buffer, value, offset) {
  return toBuffer(buffer).writeDoubleLE(value, offset)
}

function writeFloatBE(buffer, value, offset) {
  return toBuffer(buffer).writeFloatBE(value, offset)
}

function writeFloatLE(buffer, value, offset) {
  return toBuffer(buffer).writeFloatLE(value, offset)
}

function writeInt32BE(buffer, value, offset) {
  return toBuffer(buffer).writeInt32BE(value, offset)
}

function writeInt32LE(buffer, value, offset) {
  return toBuffer(buffer).writeInt32LE(value, offset)
}

function writeUInt32BE(buffer, value, offset) {
  return toBuffer(buffer).writeUInt32BE(value, offset)
}

function writeUInt32LE(buffer, value, offset) {
  return toBuffer(buffer).writeUInt32LE(value, offset)
}

module.exports = {
  isBuffer,
  isEncoding,
  alloc,
  allocUnsafe,
  allocUnsafeSlow,
  byteLength,
  compare,
  concat,
  copy,
  equals,
  fill,
  from,
  includes,
  indexOf,
  lastIndexOf,
  swap16,
  swap32,
  swap64,
  toBuffer,
  toString,
  write,
  readDoubleBE,
  readDoubleLE,
  readFloatBE,
  readFloatLE,
  readInt32BE,
  readInt32LE,
  readUInt32BE,
  readUInt32LE,
  writeDoubleBE,
  writeDoubleLE,
  writeFloatBE,
  writeFloatLE,
  writeInt32BE,
  writeInt32LE,
  writeUInt32BE,
  writeUInt32LE
}
{
  "name": "b4a",
  "version": "1.8.1",
  "description": "Bridging the gap between buffers and typed arrays",
  "exports": {
    "./package": "./package.json",
    ".": {
      "react-native": "./react-native.js",
      "browser": "./browser.js",
      "default": "./index.js"
    }
  },
  "files": [
    "browser.js",
    "index.js",
    "react-native.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:bare && npm run test:node",
    "test:bare": "brittle-bare --coverage test.mjs",
    "test:node": "brittle-node --coverage test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/b4a.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/b4a/issues"
  },
  "homepage": "https://github.com/holepunchto/b4a#readme",
  "devDependencies": {
    "brittle": "^3.5.2",
    "lunte": "^1.7.0",
    "nanobench": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "react-native-b4a": "*"
  },
  "peerDependenciesMeta": {
    "react-native-b4a": {
      "optional": true
    }
  }
}
const ESC = '\x1b'
const CSI = ESC + '['
const SGR = (n) => CSI + n + 'm'

exports.constants = {
  ESC,
  CSI,
  SGR
}

// https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_(Control_Sequence_Introducer)_sequences

exports.cursorHide = CSI + '?25l'
exports.cursorShow = CSI + '?25h'

exports.cursorUp = function cursorUp(n = 1) {
  return CSI + n + 'A'
}

exports.cursorDown = function cursorDown(n = 1) {
  return CSI + n + 'B'
}

exports.cursorForward = function cursorForward(n = 1) {
  return CSI + n + 'C'
}

exports.cursorBack = function cursorBack(n = 1) {
  return CSI + n + 'D'
}

exports.cursorNextLine = function cursorNextLine(n = 1) {
  return CSI + n + 'E'
}

exports.cursorPreviousLine = function cursorPreviousLine(n = 1) {
  return CSI + n + 'F'
}

exports.cursorPosition = function cursorPosition(column, row = 0) {
  if (row === 0) return CSI + (column + 1) + 'G'

  return CSI + (row + 1) + ';' + (column + 1) + 'H'
}

exports.eraseDisplayEnd = CSI + 'J'
exports.eraseDisplayStart = CSI + '1J'
exports.eraseDisplay = CSI + '2J'
exports.eraseLineEnd = CSI + 'K'
exports.eraseLineStart = CSI + '1K'
exports.eraseLine = CSI + '2K'

exports.scrollUp = function scrollUp(n = 1) {
  return CSI + n + 'S'
}

exports.scrollDown = function scrollDown(n = 1) {
  return CSI + n + 'T'
}

// https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_(Select_Graphic_Rendition)_parameters

exports.modifierReset = SGR(0)
exports.modifierBold = SGR(1)
exports.modifierDim = SGR(2)
exports.modifierItalic = SGR(3)
exports.modifierUnderline = SGR(4)
exports.modifierNormal = SGR(22)
exports.modifierNotItalic = SGR(23)
exports.modifierNotUnderline = SGR(24)

// https://en.wikipedia.org/wiki/ANSI_escape_code#Colors

exports.colorBlack = SGR(30)
exports.colorRed = SGR(31)
exports.colorGreen = SGR(32)
exports.colorYellow = SGR(33)
exports.colorBlue = SGR(34)
exports.colorMagenta = SGR(35)
exports.colorCyan = SGR(36)
exports.colorWhite = SGR(37)
exports.colorDefault = SGR(39)
exports.colorBrightBlack = SGR(90)
exports.colorBrightRed = SGR(91)
exports.colorBrightGreen = SGR(92)
exports.colorBrightYellow = SGR(93)
exports.colorBrightBlue = SGR(94)
exports.colorBrightMagenta = SGR(95)
exports.colorBrightCyan = SGR(96)
exports.colorBrightWhite = SGR(97)
{
  "name": "bare-ansi-escapes",
  "version": "2.2.3",
  "description": "Parse and produce ANSI escape sequences",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./key-decoder": {
      "types": "./key-decoder.d.ts",
      "default": "./key-decoder.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "key-decoder.js",
    "key-decoder.d.ts"
  ],
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-ansi-escapes.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-ansi-escapes/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-ansi-escapes#readme",
  "dependencies": {
    "bare-stream": "^2.6.5"
  },
  "devDependencies": {
    "bare-buffer": "^3.0.2",
    "brittle": "^3.3.2",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  },
  "peerDependencies": {
    "bare-buffer": "*"
  },
  "peerDependenciesMeta": {
    "bare-buffer": {
      "optional": true
    }
  }
}
const inspect = require('bare-inspect')

class AssertionError extends Error {
  constructor(opts = {}) {
    let { message = null, actual, expected, operator } = opts

    if (message === null) {
      message = `${inspect(actual)} ${operator} ${inspect(expected)}`
    }

    super(message)

    this.actual = actual
    this.expected = expected
    this.operator = operator
  }

  get name() {
    return 'AssertionError'
  }

  get code() {
    'ASSERTION'
  }
}

function assertFail(opts, fn) {
  if (opts.message instanceof Error) throw opts.message

  const err = new AssertionError(opts)

  if (Error.captureStackTrace) Error.captureStackTrace(err, fn)

  throw err
}

module.exports = exports = function assert(actual, message) {
  if (actual) return

  assertFail({ message, actual, expected: true, operator: '==' }, assert)
}

exports.AssertionError = AssertionError

exports.fail = function fail(message) {
  if (message === undefined) message = 'Failed'

  assertFail({ message, operator: 'fail' }, fail)
}

exports.ok = function ok(actual, message) {
  if (actual) return

  assertFail({ message, actual, expected: true, operator: '==' }, ok)
}

exports.notOk = function ok(actual, message) {
  if (!actual) return

  assertFail({ message, actual, expected: false, operator: '==' }, ok)
}

exports.equal = function equal(actual, expected, message) {
  if (actual == expected || (actual !== actual && expected !== expected)) {
    return
  }

  assertFail({ message, actual, expected, operator: '==' }, equal)
}

exports.notEqual = function notEqual(actual, expected, message) {
  if (actual != expected && (actual === actual || expected === expected)) {
    return
  }

  assertFail({ message, actual, expected, operator: '!=' }, notEqual)
}

exports.strictEqual = function strictEqual(actual, expected, message) {
  if (Object.is(actual, expected)) return

  assertFail(
    { message, actual, expected, operator: 'strictEqual' },
    strictEqual
  )
}

exports.notStrictEqual = function notStrictEqual(actual, expected, message) {
  if (!Object.is(actual, expected)) return

  assertFail(
    { message, actual, expected, operator: 'notStrictEqual' },
    notStrictEqual
  )
}
{
  "name": "bare-assert",
  "version": "1.2.0",
  "description": "Assertion library for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts"
  ],
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-assert.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-assert/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-assert#readme",
  "dependencies": {
    "bare-inspect": "^3.1.2"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  }
}
module.exports = require.addon()
const ansiEscapes = require('bare-ansi-escapes')
const getType = require('bare-type')
const binding = require('./binding')

const PLAIN_KEY = /^[a-zA-Z_][a-zA-Z_0-9]*$/

const defaultDepth = 2
const defaultBreakLength = 80
const defaultMaxArrayLength = 40

module.exports = exports = function inspect(value, opts = {}) {
  const {
    colors = false,
    depth = defaultDepth,
    breakLength = defaultBreakLength,
    stylize = defaultStylize(colors)
  } = opts

  const references = new InspectRefMap()

  const tree = inspectValue(value, 0, {
    colors,
    depth,
    breakLength,
    stylize,
    references
  })

  return tree.toString()
}

exports.styles = {
  bigint: ansiEscapes.colorYellow,
  boolean: ansiEscapes.colorYellow,
  date: ansiEscapes.colorMagenta,
  module: ansiEscapes.modifierUnderline,
  name: ansiEscapes.modifierReset,
  null: ansiEscapes.modifierBold,
  number: ansiEscapes.colorYellow,
  regexp: ansiEscapes.colorRed,
  special: ansiEscapes.colorCyan,
  string: ansiEscapes.colorGreen,
  symbol: ansiEscapes.colorGreen,
  undefined: ansiEscapes.colorBrightBlack
}

const styles = exports.styles

function defaultStylize(colors) {
  return function stylize(value, style) {
    const color = colors && styles[style]

    if (color) return color + value + ansiEscapes.modifierReset

    return value
  }
}

class InspectRefMap {
  constructor() {
    this.refs = new WeakMap()
    this.ids = new WeakMap()
    this.nextId = 1
  }

  has(object) {
    return this.refs.has(object)
  }

  get(object) {
    return this.refs.get(object) || null
  }

  set(object, ref) {
    this.refs.set(object, ref)
  }

  id(object) {
    let id = this.ids.get(object)
    if (id) return id

    id = this.nextId++
    this.ids.set(object, id)

    return id
  }
}

class InspectNode {
  constructor(depth, length, opts) {
    const { breakLength = defaultBreakLength, breakAlways = false } = opts

    this.depth = depth
    this.length = length
    this.breakLength = breakLength
    this.breakAlways = breakAlways
  }

  pad(n, string) {
    return string.padStart(n, ' ')
  }

  indent(n, string) {
    return '  '.repeat(n) + string
  }
}

class InspectRef extends InspectNode {
  constructor(depth, opts) {
    super(depth, '[circular *]'.length, opts)

    this.refs = opts.references
    this.count = 0
    this.circular = false
    this.color = opts.colors && styles.special
  }

  get id() {
    return this.refs.id(this)
  }

  increment() {
    return ++this.count
  }

  decrement() {
    return --this.count
  }

  toString(opts = {}) {
    const { offset = 0, pad = 0, indent = 0 } = opts

    let value = this.pad(pad, '[circular *' + this.id + ']')

    if (this.color) value = this.color + value + ansiEscapes.modifierReset

    return offset ? value : this.indent(indent, value)
  }
}

class InspectLeaf extends InspectNode {
  constructor(value, color, depth, opts) {
    const length = value.length

    if (value.includes('\n')) {
      value = value.replaceAll('\n', '\n' + '  '.repeat(depth))

      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.value = value
    this.color = opts.colors && color
  }

  toString(opts = {}) {
    const { offset = 0, pad = 0, indent = 0 } = opts

    let value = this.pad(pad, this.value)

    if (this.color) value = this.color + value + ansiEscapes.modifierReset

    return offset ? value : this.indent(indent, value)
  }
}

class InspectPair extends InspectNode {
  constructor(delim, left, right, depth, opts) {
    const length = left.length + delim.length + right.length

    if (left.breakAlways || right.breakAlways) {
      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.delim = delim
    this.left = left
    this.right = right
  }

  toString(opts = {}) {
    const { indent = 0 } = opts

    return this.indent(
      indent,
      this.left +
        this.delim +
        this.right.toString({
          indent,
          offset: this.left.length + this.delim.length
        })
    )
  }
}

class InspectSuspension extends InspectNode {
  constructor(overflow, depth, opts) {
    const label = `... ${overflow} more`

    super(depth, label.length, opts)

    this.label = label
  }

  toString(opts = {}) {
    const { indent = 0 } = opts

    return this.indent(indent, this.label)
  }
}

class InspectSequence extends InspectNode {
  constructor(header, footer, delim, values, ref, depth, opts) {
    const { tabulate = false } = opts

    const length =
      (ref.circular ? '<ref *>'.length + 1 : 0) +
      header.length +
      values.reduce(
        (length, value, i) =>
          length + value.length + (i === 0 ? 0 : delim.length),
        0
      ) +
      footer.length

    if (values.some((value) => value.breakAlways)) {
      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.header = header
    this.footer = footer
    this.delim = delim
    this.values = values
    this.ref = ref
    this.tabulate = tabulate
  }

  toString(opts = {}) {
    const { offset = 0, indent = 0 } = opts

    const split =
      this.breakAlways ||
      (this.values.length &&
        (offset + this.length > this.breakLength ||
          indent * 2 + this.length > this.breakLength))

    let header = this.header

    if (this.ref.circular) {
      header = '<ref *' + this.ref.id + '> ' + header
    }

    if (this.values.length === 0) {
      header = header.trimEnd()
    }

    if (offset === 0) {
      header = this.indent(indent, header)
    }

    if (split) {
      header = header.trimEnd() + '\n'
    }

    let string = header

    let columns = 1
    let pad = 0

    if (this.tabulate) {
      const widest = this.values.reduce(
        (length, value) =>
          value.breakAlways ? length : Math.max(length, value.length),
        0
      )

      if (widest) {
        columns = Math.max(
          columns,
          Math.floor(
            (this.breakLength - indent * 2) / (widest + this.delim.length)
          )
        )

        if (columns > 1) pad = widest
      }
    }

    for (let i = 0, n = this.values.length, offset = 0; i < n; i++) {
      const value = this.values[i]

      if (split) {
        let part

        if (i % columns === 0 || value.breakAlways) {
          part = value.toString({ indent: indent + 1, pad })
        } else {
          part = value.toString({ pad })
        }

        string += part

        if (i < n - 1) {
          if (i % columns === columns - 1 || this.values[i + 1].breakAlways) {
            string += this.delim.trimEnd() + '\n'
          } else {
            string += this.delim
          }
        }
      } else {
        if (i > 0) string += this.delim

        string += value.toString({ offset })

        offset += value.length
      }
    }

    let footer = this.footer

    if (this.values.length === 0) {
      footer = footer.trimStart()
    }

    if (split) {
      string += '\n' + this.indent(indent, footer.trimStart())
    } else {
      string += footer
    }

    return string
  }
}

function inspectValue(value, depth, opts) {
  const type = getType(value)

  if (type.isUndefined()) return inspectUndefined(depth, opts)
  if (type.isNull()) return inspectNull(depth, opts)
  if (type.isBoolean()) return inspectBoolean(value, depth, opts)
  if (type.isNumber()) return inspectNumber(value, depth, opts)
  if (type.isBigInt()) return inspectBigInt(value, depth, opts)
  if (type.isString()) return inspectString(value, depth, opts)
  if (type.isSymbol()) return inspectSymbol(value, depth, opts)
  if (type.isObject()) return inspectObject(type, value, depth, opts)
  if (type.isFunction()) return inspectFunction(type, value, depth, opts)
  if (type.isExternal()) return inspectExternal(value, opts, opts)
}

function inspectUndefined(depth, opts) {
  return new InspectLeaf('undefined', styles.undefined, depth, opts)
}

function inspectNull(depth, opts) {
  return new InspectLeaf('null', styles.null, depth, opts)
}

function inspectBoolean(value, depth, opts) {
  return new InspectLeaf(value.toString(), styles.boolean, depth, opts)
}

function inspectNumber(value, depth, opts) {
  let string

  if (Object.is(value, -0)) {
    string = '-0'
  } else {
    string = value.toString(10)
  }

  return new InspectLeaf(string, styles.number, depth, opts)
}

function inspectBigInt(value, depth, opts) {
  return new InspectLeaf(value.toString(10) + 'n', styles.bigint, depth, opts)
}

const STRING_ESCAPES =
  /[\ud800-\udbff][\udc00-\udfff]|[\u0000-\u001f'\\\ud800-\udfff]/g

function inspectString(value, depth, opts) {
  // https://tc39.es/ecma262/multipage/structured-data.html#sec-quotejsonstring
  const string = value.replace(STRING_ESCAPES, (match) => {
    if (match.length === 2) return match

    switch (match) {
      case "'":
        return "\\'"
      case '\\':
        return '\\\\'
      case '\b':
        return '\\b'
      case '\t':
        return '\\t'
      case '\n':
        return '\\n'
      case '\f':
        return '\\f'
      case '\r':
        return '\\r'
      default:
        return '\\u' + match.charCodeAt(0).toString(16).padStart(4, '0')
    }
  })

  return new InspectLeaf("'" + string + "'", styles.string, depth, opts)
}

function inspectSymbol(value, depth, opts) {
  return new InspectLeaf(value.toString(), styles.symbol, depth, opts)
}

function inspectKey(value, depth, opts) {
  if (PLAIN_KEY.test(value)) {
    return new InspectLeaf(value, null, depth, opts)
  } else {
    return inspectValue(value, depth, opts)
  }
}

function inspectObject(type, object, depth, opts) {
  const refs = opts.references

  let ref = refs.get(object)
  if (ref === null) {
    ref = new InspectRef(depth, opts)
    refs.set(object, ref)
  } else if (ref.count) {
    ref.circular = true
    return ref
  }

  const maxDepth = typeof opts.depth === 'number' ? opts.depth : Infinity

  if (maxDepth < depth) {
    const constructor = object.constructor

    return new InspectLeaf(
      '[' +
        (constructor && constructor.name ? constructor.name : 'Object') +
        ']',
      styles.special,
      depth,
      opts
    )
  }

  const inspect =
    object[Symbol.for('bare.inspect')] ||
    object[Symbol.for('nodejs.util.inspect.custom')]

  if (typeof inspect === 'function') {
    const value = inspect.call(
      object,
      typeof opts.depth === 'number' ? opts.depth - depth : null,
      {
        colors: opts.colors,
        breakLength: opts.breakLength,
        stylize: opts.stylize
      },
      exports
    )

    if (typeof value === 'object' && value !== null) {
      refs.set(value, ref)
    }

    if (typeof value !== 'string') {
      return inspectValue(value, depth, opts)
    }

    return new InspectLeaf(value, null, depth, opts)
  }

  if (type.isArray()) return inspectArray(object, ref, depth, opts)
  if (type.isDate()) return inspectDate(object, ref, depth, opts)
  if (type.isRegExp()) return inspectRegExp(object, ref, depth, opts)
  if (type.isError()) return inspectError(object, ref, depth, opts)
  if (type.isPromise()) return inspectPromise(object, ref, depth, opts)
  if (type.isMap()) return inspectMap(object, ref, depth, opts)
  if (type.isSet()) return inspectSet(object, ref, depth, opts)
  if (type.isWeakMap()) return inspectWeakMap(object, ref, depth, opts)
  if (type.isWeakSet()) return inspectWeakSet(object, ref, depth, opts)
  if (type.isWeakRef()) return inspectWeakRef(object, ref, depth, opts)
  if (type.isArrayBuffer()) return inspectArrayBuffer(object, ref, depth, opts)
  if (type.isSharedArrayBuffer())
    return inspectSharedArrayBuffer(object, ref, depth, opts)
  if (type.isTypedArray()) return inspectTypedArray(object, ref, depth, opts)
  if (type.isDataView()) return inspectDataView(object, ref, depth, opts)

  ref.increment()

  const values = []

  for (const key in object) {
    if (key === 'constructor') continue

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(object[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  let header = '{ '

  const tag = object[Symbol.toStringTag]

  if (tag) header = '[' + tag + '] ' + header

  if (object.constructor) {
    const name = object.constructor.name

    if (name && name !== 'Object') {
      header = object.constructor.name + ' ' + header
    }
  }

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectArray(array, ref, depth, opts) {
  const { maxArrayLength = defaultMaxArrayLength } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxArrayLength, 0)

  for (let i = 0, n = array.length; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(array.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(inspectValue(array[i], depth + 1, opts))
  }

  for (const key of binding.getOwnNonIndexPropertyNames(array)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(array[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  let header = '[ '

  if (array.constructor.name !== 'Array') {
    header = array.constructor.name + '(' + array.length + ') ' + header
  }

  return new InspectSequence(header, ' ]', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectDate(date, ref, depth, opts) {
  return new InspectLeaf(date.toISOString(), styles.date, depth, opts)
}

function inspectRegExp(regExp, ref, depth, opts) {
  return new InspectLeaf(regExp.toString(), styles.regexp, depth, opts)
}

function inspectError(error, ref, depth, opts) {
  let header

  if ('stack' in error) {
    header = error.stack

    if (depth > 0) {
      header = header.replaceAll('\n', '\n' + '  '.repeat(depth))
    }
  } else {
    header = error.toString()
  }

  const builtins = ['cause']

  if (error.name === 'AggregateError') {
    builtins.push('errors')
  } else if (error.name === 'SuppressedError') {
    builtins.push('error', 'suppressed')
  }

  const values = []

  for (const key of builtins) {
    if (key in error === false) continue

    values.push(
      new InspectPair(
        ': ',
        new InspectLeaf('[' + key + ']', null, depth + 1, opts),
        inspectValue(error[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key in error) {
    if (key === 'constructor' || builtins.includes(key)) continue

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(error[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  if (values.length === 0) return new InspectLeaf(header, null, depth, opts)

  return new InspectSequence(
    header + ' {',
    ' }',
    ', ',
    values,
    ref,
    depth,
    opts
  )
}

function inspectPromise(promise, ref, depth, opts) {
  ref.increment()

  const state = binding.getPromiseState(promise)

  const values = []

  switch (state) {
    case 0: // Pending
      values.push(new InspectLeaf('<pending>', styles.special, depth, opts))
      break

    case 1: // Fulfilled
      values.push(inspectValue(binding.getPromiseResult(promise), depth, opts))
      break

    case 2: // Rejected
      values.push(
        new InspectLeaf('<rejected>', styles.special, depth, opts),
        inspectValue(binding.getPromiseResult(promise), depth, opts)
      )
  }

  ref.decrement()

  const header = promise.constructor.name + ' { '

  return new InspectSequence(header, ' }', ' ', values, ref, depth, opts)
}

function inspectMap(map, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxMapLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = maxMapLength

  for (const entry of map) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(map.size - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )
      break
    }

    values.push(
      new InspectPair(
        ' => ',
        inspectValue(entry[0], depth + 1, opts),
        inspectValue(entry[1], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key in map) {
    if (key === 'constructor') continue

    const value = inspectValue(map[key], depth + 1, opts)

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        value,
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = map.constructor.name + '(' + map.size + ') { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectSet(set, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxSetLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = maxSetLength

  for (const entry of set) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(set.size - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )
      break
    }

    values.push(inspectValue(entry, depth + 1, opts))
  }

  for (const key in set) {
    if (key === 'constructor') continue

    const value = inspectValue(set[key], depth + 1, opts)

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        value,
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = set.constructor.name + '(' + set.size + ') { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectWeakMap(weakMap, ref, depth, opts) {
  const header = weakMap.constructor.name + ' { '

  return new InspectSequence(
    header,
    ' }',
    ' ',
    [new InspectLeaf('<items unknown>', styles.special, depth + 1, opts)],
    ref,
    depth,
    opts
  )
}

function inspectWeakSet(weakSet, ref, depth, opts) {
  const header = weakSet.constructor.name + ' { '

  return new InspectSequence(
    header,
    ' }',
    ' ',
    [new InspectLeaf('<items unknown>', styles.special, depth + 1, opts)],
    ref,
    depth,
    opts
  )
}

function inspectWeakRef(weakRef, ref, depth, opts) {
  const target = weakRef.deref()

  let value

  if (target === undefined) {
    value = new InspectLeaf('<cleared>', styles.special, depth + 1, opts)
  } else {
    value = inspectValue(target, depth + 1, opts)
  }

  const header = weakRef.constructor.name + ' { '

  return new InspectSequence(header, ' }', ' ', [value], ref, depth, opts)
}

function inspectArrayBuffer(arrayBuffer, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(arrayBuffer[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = arrayBuffer.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectSharedArrayBuffer(sharedArrayBuffer, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(sharedArrayBuffer[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = sharedArrayBuffer.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectTypedArray(typedArray, ref, depth, opts) {
  if (Buffer.isBuffer(typedArray)) {
    return inspectBuffer(typedArray, ref, depth, opts)
  }

  const {
    maxArrayLength = defaultMaxArrayLength,
    maxTypedArrayLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxTypedArrayLength, 0)

  for (let i = 0, n = typedArray.length; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(typedArray.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(inspectValue(typedArray[i], depth + 1, opts))
  }

  for (const key of binding.getOwnNonIndexPropertyNames(typedArray)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(typedArray[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = typedArray.constructor.name + '(' + typedArray.length + ') [ '

  return new InspectSequence(header, ' ]', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectBuffer(buffer, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxBufferLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxBufferLength, 0)

  for (let i = 0, n = buffer.byteLength; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(buffer.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(
      new InspectLeaf(
        buffer[i].toString(16).padStart(2, '0'),
        null,
        depth + 1,
        opts
      )
    )
  }

  for (const key of binding.getOwnNonIndexPropertyNames(buffer)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(buffer[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  return new InspectSequence('<Buffer ', '>', ' ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectDataView(dataView, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength', 'byteOffset', 'buffer']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(dataView[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key of binding.getOwnNonIndexPropertyNames(dataView)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(dataView[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = dataView.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectFunction(type, fn, depth, opts) {
  if (fn.toString().startsWith('class')) return inspectClass(fn, depth, opts)

  let tag = 'function'

  if (type.isGeneratorFunction()) tag = 'generator ' + tag
  if (type.isAsyncFunction()) tag = 'async ' + tag

  return new InspectLeaf(
    '[' + tag + ' ' + (fn.name ? fn.name : '(anonymous)') + ']',
    styles.special,
    depth,
    opts
  )
}

function inspectClass(ctor, depth, opts) {
  return new InspectLeaf(
    '[class ' + (ctor.name ? ctor.name : '(anonymous)') + ']',
    styles.special,
    depth,
    opts
  )
}

function inspectExternal(external, depth, opts) {
  return new InspectLeaf(
    '[external 0x' + binding.getExternal(external).toString(16) + ']',
    styles.special,
    depth,
    opts
  )
}
{
  "name": "bare-inspect",
  "version": "3.1.4",
  "description": "Inspect objects as strings for debugging",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-inspect.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-inspect/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-inspect#readme",
  "engines": {
    "bare": ">=1.18.0"
  },
  "dependencies": {
    "bare-ansi-escapes": "^2.1.0",
    "bare-type": "^1.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
module.exports = require.addon()
const binding = require('./binding')

const t = binding.constants

class Type {
  constructor(type) {
    this._type = type
  }

  isUndefined() {
    return this._type === t.UNDEFINED
  }

  isNull() {
    return this._type === t.NULL
  }

  isBoolean() {
    return this._type === t.BOOLEAN
  }

  isNumber() {
    return (this._type & 0xff) === t.NUMBER
  }

  isInt32() {
    return (this._type & (0xff | t.INT32)) === (t.NUMBER | t.INT32)
  }

  isUint32() {
    return (this._type & (0xff | t.UINT32)) === (t.NUMBER | t.UINT32)
  }

  isString() {
    return this._type === t.STRING
  }

  isSymbol() {
    return this._type === t.SYMBOL
  }

  isObject() {
    return (this._type & 0xff) === t.OBJECT
  }

  isArray() {
    return this._type === (t.OBJECT | t.ARRAY)
  }

  isArguments() {
    return this._type === (t.OBJECT | t.ARGUMENTS)
  }

  isDate() {
    return this._type === (t.OBJECT | t.DATE)
  }

  isRegExp() {
    return this._type === (t.OBJECT | t.REGEXP)
  }

  isError() {
    return this._type === (t.OBJECT | t.ERROR)
  }

  isPromise() {
    return this._type === (t.OBJECT | t.PROMISE)
  }

  isProxy() {
    return this._type === (t.OBJECT | t.PROXY)
  }

  isGenerator() {
    return this._type === (t.OBJECT | t.GENERATOR)
  }

  isMap() {
    return this._type === (t.OBJECT | t.MAP)
  }

  isSet() {
    return this._type === (t.OBJECT | t.SET)
  }

  isWeakMap() {
    return this._type === (t.OBJECT | t.WEAK_MAP)
  }

  isWeakSet() {
    return this._type === (t.OBJECT | t.WEAK_SET)
  }

  isWeakRef() {
    return this._type === (t.OBJECT | t.WEAK_REF)
  }

  isArrayBuffer() {
    return this._type === (t.OBJECT | t.ARRAYBUFFER)
  }

  isSharedArrayBuffer() {
    return this._type === (t.OBJECT | t.SHAREDARRAYBUFFER)
  }

  isTypedArray() {
    return (this._type & 0xffff) === (t.OBJECT | t.TYPEDARRAY)
  }

  isInt8Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT8ARRAY)
  }

  isUint8Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT8ARRAY)
  }

  isUint8ClampedArray() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT8CLAMPEDARRAY)
  }

  isInt16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT16ARRAY)
  }

  isUint16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT16ARRAY)
  }

  isInt32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT32ARRAY)
  }

  isUint32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT32ARRAY)
  }

  isFloat16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT16ARRAY)
  }

  isFloat32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT32ARRAY)
  }

  isFloat64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT64ARRAY)
  }

  isBigInt64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.BIGINT64ARRAY)
  }

  isBigUint64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.BIGUINT64ARRAY)
  }

  isDataView() {
    return this._type === (t.OBJECT | t.DATAVIEW)
  }

  isModuleNamespace() {
    return this._type === (t.OBJECT | t.MODULE_NAMESPACE)
  }

  isFunction() {
    return (this._type & 0xff) === t.FUNCTION
  }

  isAsyncFunction() {
    return (
      (this._type & (0xff | t.ASYNC_FUNCTION)) ===
      (t.FUNCTION | t.ASYNC_FUNCTION)
    )
  }

  isGeneratorFunction() {
    return (
      (this._type & (0xff | t.GENERATOR_FUNCTION)) ===
      (t.FUNCTION | t.GENERATOR_FUNCTION)
    )
  }

  isExternal() {
    return this._type === t.EXTERNAL
  }

  isBigInt() {
    return this._type === t.BIGINT
  }
}

module.exports = exports = function type(value) {
  switch (typeof value) {
    case 'undefined':
      return new Type(t.UNDEFINED)
    case 'boolean':
      return new Type(t.BOOLEAN)
    case 'number':
      return new Type(
        Number.isSafeInteger(value) ? binding.type(value) : t.NUMBER
      )
    case 'string':
      return new Type(t.STRING)
    case 'symbol':
      return new Type(t.SYMBOL)
    case 'object':
      return new Type(value === null ? t.NULL : binding.type(value))
    case 'function':
      return new Type(binding.type(value))
    case 'bigint':
      return new Type(t.BIGINT)
  }
}

exports.createTag = function createTag(...components) {
  const tag = new Uint32Array(4)
  for (let i = 0; i < 4; i++) tag[i] = components[i] || 0
  return tag
}

exports.addTag = function addTag(object, tag) {
  binding.addTag(object, tag)
}

exports.checkTag = function checkTag(object, tag) {
  return binding.checkTag(object, tag)
}
{
  "name": "bare-type",
  "version": "1.1.0",
  "description": "Cross-realm type predicates for Bare",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-type.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-type/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-type#readme",
  "engines": {
    "bare": ">=1.2.0"
  },
  "devDependencies": {
    "brittle": "^3.4.0",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
const sodium = require('sodium-universal')
const b4a = require('b4a')
const assert = require('nanoassert')
const { detectLanguage, loadWordlist } = require('./wordlist')

module.exports = {
  generateEntropy,
  generateMnemonic,
  normalizeMnemonic,
  validateMnemonic,
  mnemonicToEntropy,
  mnemonicToSeed,
  entropyToMnemonic
}

function generateMnemonic ({ entropy = generateEntropy(), language = 'english' } = {}) {
  const wordlist = loadWordlist(language)
  const extended = computeCheckSum(entropy)

  const words = []

  for (const index of uint11Reader(extended)) {
    words.push(wordlist[index])
  }

  const delimiter = language === 'japanese' ? '\u3000' : ' '

  return words.join(delimiter).trim()
}

function entropyToMnemonic (entropy, { language = 'english' } = {}) {
  return generateMnemonic({ entropy, language })
}

function mnemonicToEntropy (mnemonic) {
  const words = mnemonic.replace(/\u3000/g, ' ').trim().split(' ')
  const language = detectLanguage(words)

  if (!language) {
    throw new Error('Language not recognised')
  }

  if (words.length % 3 !== 0) {
    throw new Error('Invalid length')
  }

  const wordlist = loadWordlist(language)

  const indexes = []
  for (const word of words) {
    const index = wordlist.indexOf(word)
    if (index === -1) {
      throw new Error('Bad word')
    }

    indexes.push(index)
  }

  const bits = words.length * 11
  const len = (bits * 32 / 33) >> 3

  const extended = b4a.alloc(Math.ceil(bits / 8))
  const entropy = extended.subarray(0, len)

  uint11Writer(extended, indexes)

  if (!b4a.equals(extended, computeCheckSum(entropy))) {
    throw new Error('Invalid checksum')
  }

  return entropy
}

function normalizeMnemonic (mnemonic) {
  return mnemonic.trim().replace(/\u3000/, ' ').split(/\s+/).map(c => c.toLowerCase()).join(' ')
}

async function mnemonicToSeed (mnemonic, passphrase = '') {
  mnemonic = normalizeMnemonic(mnemonic)

  if (!validateMnemonic(mnemonic)) {
    throw new Error('Invalid mnemonic')
  }

  const input = b4a.from(mnemonic)
  const salt = b4a.from('mnemonic' + passphrase)

  const output = b4a.alloc(64)

  await sodium.extension_pbkdf2_sha512_async(
    output,
    input,
    salt,
    2048,
    64
  )

  return output
}

function validateMnemonic (mnemonic) {
  try {
    mnemonicToEntropy(mnemonic)
  } catch (e) {
    return false
  }
  return true
}

function sha256 (data, output = b4a.alloc(32)) {
  sodium.crypto_hash_sha256(output, data)
  return output
}

function computeCheckSum (seed) {
  assert((seed.byteLength & 4) === 0, 'seed must be a multiple of 4 bytes')

  const len = seed.byteLength
  const cklen = len >> 2 // cksum bits
  const total = len + Math.ceil(cklen / 8)

  const output = b4a.alloc(len + 32)
  output.set(seed)

  const entropy = output.subarray(0, len)
  const cksum = output.subarray(len)

  sha256(entropy, cksum)

  // only append cklen bits
  output[total - 1] &= (0xff ^ (0xff >> cklen))

  return output.subarray(0, total)
}

function generateEntropy (length = 32) {
  const seed = b4a.alloc(length)
  sodium.randombytes_buf(seed)

  return seed
}

function * uint11Reader (state) {
  yield * uintReader(state, 11)
}

function uint11Writer (buf, uints) {
  return uintWriter(buf, uints, 11)
}

function * uintReader (buffer, width) {
  const MASK = (2 << (width - 1)) - 1

  let pos = 0
  let value = 0

  while (true) {
    const offset = pos >> 3 // byte offset

    if (offset >= buffer.byteLength) {
      return value & MASK
    }

    const height = width - (pos % width)
    const leftover = (offset + 1) * 8 - pos

    value += shift(buffer[offset], height - leftover)

    pos += Math.min(height, leftover)
    if (pos % width) continue

    yield value & MASK

    value = 0
  }
}

function uintWriter (buffer, uints, width) {
  let pos = 0

  while (true) {
    const offset = pos >> 3 // byte offset

    const i = Math.floor(pos / width)
    if (i >= uints.length) break

    if (offset >= buffer.length) {
      throw new Error('Failed to encode uints')
    }

    const rem = 8 - pos % 8
    const height = (i + 1) * width - pos

    const value = shift(uints[i], rem - height)

    buffer[offset] += mask(value, rem)

    pos += Math.min(rem, height)
  }

  return buffer
}

// when n is positive, shift left n bits
// when n is negative, shift right -n bits
function shift (val, n) {
  if (n === 0) return val
  if (n > 0) return val << n

  return val >> (-1 * n)
}

function mask (val, bits) {
  if (bits < 32) return val & ((1 << bits) - 1)
  return val % (2 ** bits)
}
{
  "name": "bip39-mnemonic",
  "version": "2.5.0",
  "description": "BIP39 mnemonic for key derivation schemes",
  "main": "index.js",
  "scripts": {
    "generate-wordlist": "node scripts/generate-wordlist.js",
    "test": "standard && brittle test/*.js"
  },
  "author": "Holepunch Inc",
  "license": "Apache-2.0",
  "devDependencies": {
    "brittle": "^3.4.0",
    "standard": "^17.1.0"
  },
  "dependencies": {
    "b4a": "^1.6.6",
    "nanoassert": "^2.0.0",
    "sodium-universal": "^5.0.1"
  },
  "files": [
    "index.js",
    "wordlist"
  ],
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bip39.git"
  },
  "bugs": {
    "url": "https://github.com/holepunchto/bip39/issues"
  },
  "homepage": "https://github.com/holepunchto/bip39#readme"
}
["的","一","是","在","不","了","有","和","人","这","中","大","为","上","个","国","我","以","要","他","时","来","用","们","生","到","作","地","于","出","就","分","对","成","会","可","主","发","年","动","同","工","也","能","下","过","子","说","产","种","面","而","方","后","多","定","行","学","法","所","民","得","经","十","三","之","进","着","等","部","度","家","电","力","里","如","水","化","高","自","二","理","起","小","物","现","实","加","量","都","两","体","制","机","当","使","点","从","业","本","去","把","性","好","应","开","它","合","还","因","由","其","些","然","前","外","天","政","四","日","那","社","义","事","平","形","相","全","表","间","样","与","关","各","重","新","线","内","数","正","心","反","你","明","看","原","又","么","利","比","或","但","质","气","第","向","道","命","此","变","条","只","没","结","解","问","意","建","月","公","无","系","军","很","情","者","最","立","代","想","已","通","并","提","直","题","党","程","展","五","果","料","象","员","革","位","入","常","文","总","次","品","式","活","设","及","管","特","件","长","求","老","头","基","资","边","流","路","级","少","图","山","统","接","知","较","将","组","见","计","别","她","手","角","期","根","论","运","农","指","几","九","区","强","放","决","西","被","干","做","必","战","先","回","则","任","取","据","处","队","南","给","色","光","门","即","保","治","北","造","百","规","热","领","七","海","口","东","导","器","压","志","世","金","增","争","济","阶","油","思","术","极","交","受","联","什","认","六","共","权","收","证","改","清","美","再","采","转","更","单","风","切","打","白","教","速","花","带","安","场","身","车","例","真","务","具","万","每","目","至","达","走","积","示","议","声","报","斗","完","类","八","离","华","名","确","才","科","张","信","马","节","话","米","整","空","元","况","今","集","温","传","土","许","步","群","广","石","记","需","段","研","界","拉","林","律","叫","且","究","观","越","织","装","影","算","低","持","音","众","书","布","复","容","儿","须","际","商","非","验","连","断","深","难","近","矿","千","周","委","素","技","备","半","办","青","省","列","习","响","约","支","般","史","感","劳","便","团","往","酸","历","市","克","何","除","消","构","府","称","太","准","精","值","号","率","族","维","划","选","标","写","存","候","毛","亲","快","效","斯","院","查","江","型","眼","王","按","格","养","易","置","派","层","片","始","却","专","状","育","厂","京","识","适","属","圆","包","火","住","调","满","县","局","照","参","红","细","引","听","该","铁","价","严","首","底","液","官","德","随","病","苏","失","尔","死","讲","配","女","黄","推","显","谈","罪","神","艺","呢","席","含","企","望","密","批","营","项","防","举","球","英","氧","势","告","李","台","落","木","帮","轮","破","亚","师","围","注","远","字","材","排","供","河","态","封","另","施","减","树","溶","怎","止","案","言","士","均","武","固","叶","鱼","波","视","仅","费","紧","爱","左","章","早","朝","害","续","轻","服","试","食","充","兵","源","判","护","司","足","某","练","差","致","板","田","降","黑","犯","负","击","范","继","兴","似","余","坚","曲","输","修","故","城","夫","够","送","笔","船","占","右","财","吃","富","春","职","觉","汉","画","功","巴","跟","虽","杂","飞","检","吸","助","升","阳","互","初","创","抗","考","投","坏","策","古","径","换","未","跑","留","钢","曾","端","责","站","简","述","钱","副","尽","帝","射","草","冲","承","独","令","限","阿","宣","环","双","请","超","微","让","控","州","良","轴","找","否","纪","益","依","优","顶","础","载","倒","房","突","坐","粉","敌","略","客","袁","冷","胜","绝","析","块","剂","测","丝","协","诉","念","陈","仍","罗","盐","友","洋","错","苦","夜","刑","移","频","逐","靠","混","母","短","皮","终","聚","汽","村","云","哪","既","距","卫","停","烈","央","察","烧","迅","境","若","印","洲","刻","括","激","孔","搞","甚","室","待","核","校","散","侵","吧","甲","游","久","菜","味","旧","模","湖","货","损","预","阻","毫","普","稳","乙","妈","植","息","扩","银","语","挥","酒","守","拿","序","纸","医","缺","雨","吗","针","刘","啊","急","唱","误","训","愿","审","附","获","茶","鲜","粮","斤","孩","脱","硫","肥","善","龙","演","父","渐","血","欢","械","掌","歌","沙","刚","攻","谓","盾","讨","晚","粒","乱","燃","矛","乎","杀","药","宁","鲁","贵","钟","煤","读","班","伯","香","介","迫","句","丰","培","握","兰","担","弦","蛋","沉","假","穿","执","答","乐","谁","顺","烟","缩","征","脸","喜","松","脚","困","异","免","背","星","福","买","染","井","概","慢","怕","磁","倍","祖","皇","促","静","补","评","翻","肉","践","尼","衣","宽","扬","棉","希","伤","操","垂","秋","宜","氢","套","督","振","架","亮","末","宪","庆","编","牛","触","映","雷","销","诗","座","居","抓","裂","胞","呼","娘","景","威","绿","晶","厚","盟","衡","鸡","孙","延","危","胶","屋","乡","临","陆","顾","掉","呀","灯","岁","措","束","耐","剧","玉","赵","跳","哥","季","课","凯","胡","额","款","绍","卷","齐","伟","蒸","殖","永","宗","苗","川","炉","岩","弱","零","杨","奏","沿","露","杆","探","滑","镇","饭","浓","航","怀","赶","库","夺","伊","灵","税","途","灭","赛","归","召","鼓","播","盘","裁","险","康","唯","录","菌","纯","借","糖","盖","横","符","私","努","堂","域","枪","润","幅","哈","竟","熟","虫","泽","脑","壤","碳","欧","遍","侧","寨","敢","彻","虑","斜","薄","庭","纳","弹","饲","伸","折","麦","湿","暗","荷","瓦","塞","床","筑","恶","户","访","塔","奇","透","梁","刀","旋","迹","卡","氯","遇","份","毒","泥","退","洗","摆","灰","彩","卖","耗","夏","择","忙","铜","献","硬","予","繁","圈","雪","函","亦","抽","篇","阵","阴","丁","尺","追","堆","雄","迎","泛","爸","楼","避","谋","吨","野","猪","旗","累","偏","典","馆","索","秦","脂","潮","爷","豆","忽","托","惊","塑","遗","愈","朱","替","纤","粗","倾","尚","痛","楚","谢","奋","购","磨","君","池","旁","碎","骨","监","捕","弟","暴","割","贯","殊","释","词","亡","壁","顿","宝","午","尘","闻","揭","炮","残","冬","桥","妇","警","综","招","吴","付","浮","遭","徐","您","摇","谷","赞","箱","隔","订","男","吹","园","纷","唐","败","宋","玻","巨","耕","坦","荣","闭","湾","键","凡","驻","锅","救","恩","剥","凝","碱","齿","截","炼","麻","纺","禁","废","盛","版","缓","净","睛","昌","婚","涉","筒","嘴","插","岸","朗","庄","街","藏","姑","贸","腐","奴","啦","惯","乘","伙","恢","匀","纱","扎","辩","耳","彪","臣","亿","璃","抵","脉","秀","萨","俄","网","舞","店","喷","纵","寸","汗","挂","洪","贺","闪","柬","爆","烯","津","稻","墙","软","勇","像","滚","厘","蒙","芳","肯","坡","柱","荡","腿","仪","旅","尾","轧","冰","贡","登","黎","削","钻","勒","逃","障","氨","郭","峰","币","港","伏","轨","亩","毕","擦","莫","刺","浪","秘","援","株","健","售","股","岛","甘","泡","睡","童","铸","汤","阀","休","汇","舍","牧","绕","炸","哲","磷","绩","朋","淡","尖","启","陷","柴","呈","徒","颜","泪","稍","忘","泵","蓝","拖","洞","授","镜","辛","壮","锋","贫","虚","弯","摩","泰","幼","廷","尊","窗","纲","弄","隶","疑","氏","宫","姐","震","瑞","怪","尤","琴","循","描","膜","违","夹","腰","缘","珠","穷","森","枝","竹","沟","催","绳","忆","邦","剩","幸","浆","栏","拥","牙","贮","礼","滤","钠","纹","罢","拍","咱","喊","袖","埃","勤","罚","焦","潜","伍","墨","欲","缝","姓","刊","饱","仿","奖","铝","鬼","丽","跨","默","挖","链","扫","喝","袋","炭","污","幕","诸","弧","励","梅","奶","洁","灾","舟","鉴","苯","讼","抱","毁","懂","寒","智","埔","寄","届","跃","渡","挑","丹","艰","贝","碰","拔","爹","戴","码","梦","芽","熔","赤","渔","哭","敬","颗","奔","铅","仲","虎","稀","妹","乏","珍","申","桌","遵","允","隆","螺","仓","魏","锐","晓","氮","兼","隐","碍","赫","拨","忠","肃","缸","牵","抢","博","巧","壳","兄","杜","讯","诚","碧","祥","柯","页","巡","矩","悲","灌","龄","伦","票","寻","桂","铺","圣","恐","恰","郑","趣","抬","荒","腾","贴","柔","滴","猛","阔","辆","妻","填","撤","储","签","闹","扰","紫","砂","递","戏","吊","陶","伐","喂","疗","瓶","婆","抚","臂","摸","忍","虾","蜡","邻","胸","巩","挤","偶","弃","槽","劲","乳","邓","吉","仁","烂","砖","租","乌","舰","伴","瓜","浅","丙","暂","燥","橡","柳","迷","暖","牌","秧","胆","详","簧","踏","瓷","谱","呆","宾","糊","洛","辉","愤","竞","隙","怒","粘","乃","绪","肩","籍","敏","涂","熙","皆","侦","悬","掘","享","纠","醒","狂","锁","淀","恨","牲","霸","爬","赏","逆","玩","陵","祝","秒","浙","貌","役","彼","悉","鸭","趋","凤","晨","畜","辈","秩","卵","署","梯","炎","滩","棋","驱","筛","峡","冒","啥","寿","译","浸","泉","帽","迟","硅","疆","贷","漏","稿","冠","嫩","胁","芯","牢","叛","蚀","奥","鸣","岭","羊","凭","串","塘","绘","酵","融","盆","锡","庙","筹","冻","辅","摄","袭","筋","拒","僚","旱","钾","鸟","漆","沈","眉","疏","添","棒","穗","硝","韩","逼","扭","侨","凉","挺","碗","栽","炒","杯","患","馏","劝","豪","辽","勃","鸿","旦","吏","拜","狗","埋","辊","掩","饮","搬","骂","辞","勾","扣","估","蒋","绒","雾","丈","朵","姆","拟","宇","辑","陕","雕","偿","蓄","崇","剪","倡","厅","咬","驶","薯","刷","斥","番","赋","奉","佛","浇","漫","曼","扇","钙","桃","扶","仔","返","俗","亏","腔","鞋","棱","覆","框","悄","叔","撞","骗","勘","旺","沸","孤","吐","孟","渠","屈","疾","妙","惜","仰","狠","胀","谐","抛","霉","桑","岗","嘛","衰","盗","渗","脏","赖","涌","甜","曹","阅","肌","哩","厉","烃","纬","毅","昨","伪","症","煮","叹","钉","搭","茎","笼","酷","偷","弓","锥","恒","杰","坑","鼻","翼","纶","叙","狱","逮","罐","络","棚","抑","膨","蔬","寺","骤","穆","冶","枯","册","尸","凸","绅","坯","牺","焰","轰","欣","晋","瘦","御","锭","锦","丧","旬","锻","垄","搜","扑","邀","亭","酯","迈","舒","脆","酶","闲","忧","酚","顽","羽","涨","卸","仗","陪","辟","惩","杭","姚","肚","捉","飘","漂","昆","欺","吾","郎","烷","汁","呵","饰","萧","雅","邮","迁","燕","撒","姻","赴","宴","烦","债","帐","斑","铃","旨","醇","董","饼","雏","姿","拌","傅","腹","妥","揉","贤","拆","歪","葡","胺","丢","浩","徽","昂","垫","挡","览","贪","慰","缴","汪","慌","冯","诺","姜","谊","凶","劣","诬","耀","昏","躺","盈","骑","乔","溪","丛","卢","抹","闷","咨","刮","驾","缆","悟","摘","铒","掷","颇","幻","柄","惠","惨","佳","仇","腊","窝","涤","剑","瞧","堡","泼","葱","罩","霍","捞","胎","苍","滨","俩","捅","湘","砍","霞","邵","萄","疯","淮","遂","熊","粪","烘","宿","档","戈","驳","嫂","裕","徙","箭","捐","肠","撑","晒","辨","殿","莲","摊","搅","酱","屏","疫","哀","蔡","堵","沫","皱","畅","叠","阁","莱","敲","辖","钩","痕","坝","巷","饿","祸","丘","玄","溜","曰","逻","彭","尝","卿","妨","艇","吞","韦","怨","矮","歇"]["的","一","是","在","不","了","有","和","人","這","中","大","為","上","個","國","我","以","要","他","時","來","用","們","生","到","作","地","於","出","就","分","對","成","會","可","主","發","年","動","同","工","也","能","下","過","子","說","產","種","面","而","方","後","多","定","行","學","法","所","民","得","經","十","三","之","進","著","等","部","度","家","電","力","裡","如","水","化","高","自","二","理","起","小","物","現","實","加","量","都","兩","體","制","機","當","使","點","從","業","本","去","把","性","好","應","開","它","合","還","因","由","其","些","然","前","外","天","政","四","日","那","社","義","事","平","形","相","全","表","間","樣","與","關","各","重","新","線","內","數","正","心","反","你","明","看","原","又","麼","利","比","或","但","質","氣","第","向","道","命","此","變","條","只","沒","結","解","問","意","建","月","公","無","系","軍","很","情","者","最","立","代","想","已","通","並","提","直","題","黨","程","展","五","果","料","象","員","革","位","入","常","文","總","次","品","式","活","設","及","管","特","件","長","求","老","頭","基","資","邊","流","路","級","少","圖","山","統","接","知","較","將","組","見","計","別","她","手","角","期","根","論","運","農","指","幾","九","區","強","放","決","西","被","幹","做","必","戰","先","回","則","任","取","據","處","隊","南","給","色","光","門","即","保","治","北","造","百","規","熱","領","七","海","口","東","導","器","壓","志","世","金","增","爭","濟","階","油","思","術","極","交","受","聯","什","認","六","共","權","收","證","改","清","美","再","採","轉","更","單","風","切","打","白","教","速","花","帶","安","場","身","車","例","真","務","具","萬","每","目","至","達","走","積","示","議","聲","報","鬥","完","類","八","離","華","名","確","才","科","張","信","馬","節","話","米","整","空","元","況","今","集","溫","傳","土","許","步","群","廣","石","記","需","段","研","界","拉","林","律","叫","且","究","觀","越","織","裝","影","算","低","持","音","眾","書","布","复","容","兒","須","際","商","非","驗","連","斷","深","難","近","礦","千","週","委","素","技","備","半","辦","青","省","列","習","響","約","支","般","史","感","勞","便","團","往","酸","歷","市","克","何","除","消","構","府","稱","太","準","精","值","號","率","族","維","劃","選","標","寫","存","候","毛","親","快","效","斯","院","查","江","型","眼","王","按","格","養","易","置","派","層","片","始","卻","專","狀","育","廠","京","識","適","屬","圓","包","火","住","調","滿","縣","局","照","參","紅","細","引","聽","該","鐵","價","嚴","首","底","液","官","德","隨","病","蘇","失","爾","死","講","配","女","黃","推","顯","談","罪","神","藝","呢","席","含","企","望","密","批","營","項","防","舉","球","英","氧","勢","告","李","台","落","木","幫","輪","破","亞","師","圍","注","遠","字","材","排","供","河","態","封","另","施","減","樹","溶","怎","止","案","言","士","均","武","固","葉","魚","波","視","僅","費","緊","愛","左","章","早","朝","害","續","輕","服","試","食","充","兵","源","判","護","司","足","某","練","差","致","板","田","降","黑","犯","負","擊","范","繼","興","似","餘","堅","曲","輸","修","故","城","夫","夠","送","筆","船","佔","右","財","吃","富","春","職","覺","漢","畫","功","巴","跟","雖","雜","飛","檢","吸","助","昇","陽","互","初","創","抗","考","投","壞","策","古","徑","換","未","跑","留","鋼","曾","端","責","站","簡","述","錢","副","盡","帝","射","草","衝","承","獨","令","限","阿","宣","環","雙","請","超","微","讓","控","州","良","軸","找","否","紀","益","依","優","頂","礎","載","倒","房","突","坐","粉","敵","略","客","袁","冷","勝","絕","析","塊","劑","測","絲","協","訴","念","陳","仍","羅","鹽","友","洋","錯","苦","夜","刑","移","頻","逐","靠","混","母","短","皮","終","聚","汽","村","雲","哪","既","距","衛","停","烈","央","察","燒","迅","境","若","印","洲","刻","括","激","孔","搞","甚","室","待","核","校","散","侵","吧","甲","遊","久","菜","味","舊","模","湖","貨","損","預","阻","毫","普","穩","乙","媽","植","息","擴","銀","語","揮","酒","守","拿","序","紙","醫","缺","雨","嗎","針","劉","啊","急","唱","誤","訓","願","審","附","獲","茶","鮮","糧","斤","孩","脫","硫","肥","善","龍","演","父","漸","血","歡","械","掌","歌","沙","剛","攻","謂","盾","討","晚","粒","亂","燃","矛","乎","殺","藥","寧","魯","貴","鐘","煤","讀","班","伯","香","介","迫","句","豐","培","握","蘭","擔","弦","蛋","沉","假","穿","執","答","樂","誰","順","煙","縮","徵","臉","喜","松","腳","困","異","免","背","星","福","買","染","井","概","慢","怕","磁","倍","祖","皇","促","靜","補","評","翻","肉","踐","尼","衣","寬","揚","棉","希","傷","操","垂","秋","宜","氫","套","督","振","架","亮","末","憲","慶","編","牛","觸","映","雷","銷","詩","座","居","抓","裂","胞","呼","娘","景","威","綠","晶","厚","盟","衡","雞","孫","延","危","膠","屋","鄉","臨","陸","顧","掉","呀","燈","歲","措","束","耐","劇","玉","趙","跳","哥","季","課","凱","胡","額","款","紹","卷","齊","偉","蒸","殖","永","宗","苗","川","爐","岩","弱","零","楊","奏","沿","露","桿","探","滑","鎮","飯","濃","航","懷","趕","庫","奪","伊","靈","稅","途","滅","賽","歸","召","鼓","播","盤","裁","險","康","唯","錄","菌","純","借","糖","蓋","橫","符","私","努","堂","域","槍","潤","幅","哈","竟","熟","蟲","澤","腦","壤","碳","歐","遍","側","寨","敢","徹","慮","斜","薄","庭","納","彈","飼","伸","折","麥","濕","暗","荷","瓦","塞","床","築","惡","戶","訪","塔","奇","透","梁","刀","旋","跡","卡","氯","遇","份","毒","泥","退","洗","擺","灰","彩","賣","耗","夏","擇","忙","銅","獻","硬","予","繁","圈","雪","函","亦","抽","篇","陣","陰","丁","尺","追","堆","雄","迎","泛","爸","樓","避","謀","噸","野","豬","旗","累","偏","典","館","索","秦","脂","潮","爺","豆","忽","托","驚","塑","遺","愈","朱","替","纖","粗","傾","尚","痛","楚","謝","奮","購","磨","君","池","旁","碎","骨","監","捕","弟","暴","割","貫","殊","釋","詞","亡","壁","頓","寶","午","塵","聞","揭","炮","殘","冬","橋","婦","警","綜","招","吳","付","浮","遭","徐","您","搖","谷","贊","箱","隔","訂","男","吹","園","紛","唐","敗","宋","玻","巨","耕","坦","榮","閉","灣","鍵","凡","駐","鍋","救","恩","剝","凝","鹼","齒","截","煉","麻","紡","禁","廢","盛","版","緩","淨","睛","昌","婚","涉","筒","嘴","插","岸","朗","莊","街","藏","姑","貿","腐","奴","啦","慣","乘","夥","恢","勻","紗","扎","辯","耳","彪","臣","億","璃","抵","脈","秀","薩","俄","網","舞","店","噴","縱","寸","汗","掛","洪","賀","閃","柬","爆","烯","津","稻","牆","軟","勇","像","滾","厘","蒙","芳","肯","坡","柱","盪","腿","儀","旅","尾","軋","冰","貢","登","黎","削","鑽","勒","逃","障","氨","郭","峰","幣","港","伏","軌","畝","畢","擦","莫","刺","浪","秘","援","株","健","售","股","島","甘","泡","睡","童","鑄","湯","閥","休","匯","舍","牧","繞","炸","哲","磷","績","朋","淡","尖","啟","陷","柴","呈","徒","顏","淚","稍","忘","泵","藍","拖","洞","授","鏡","辛","壯","鋒","貧","虛","彎","摩","泰","幼","廷","尊","窗","綱","弄","隸","疑","氏","宮","姐","震","瑞","怪","尤","琴","循","描","膜","違","夾","腰","緣","珠","窮","森","枝","竹","溝","催","繩","憶","邦","剩","幸","漿","欄","擁","牙","貯","禮","濾","鈉","紋","罷","拍","咱","喊","袖","埃","勤","罰","焦","潛","伍","墨","欲","縫","姓","刊","飽","仿","獎","鋁","鬼","麗","跨","默","挖","鏈","掃","喝","袋","炭","污","幕","諸","弧","勵","梅","奶","潔","災","舟","鑑","苯","訟","抱","毀","懂","寒","智","埔","寄","屆","躍","渡","挑","丹","艱","貝","碰","拔","爹","戴","碼","夢","芽","熔","赤","漁","哭","敬","顆","奔","鉛","仲","虎","稀","妹","乏","珍","申","桌","遵","允","隆","螺","倉","魏","銳","曉","氮","兼","隱","礙","赫","撥","忠","肅","缸","牽","搶","博","巧","殼","兄","杜","訊","誠","碧","祥","柯","頁","巡","矩","悲","灌","齡","倫","票","尋","桂","鋪","聖","恐","恰","鄭","趣","抬","荒","騰","貼","柔","滴","猛","闊","輛","妻","填","撤","儲","簽","鬧","擾","紫","砂","遞","戲","吊","陶","伐","餵","療","瓶","婆","撫","臂","摸","忍","蝦","蠟","鄰","胸","鞏","擠","偶","棄","槽","勁","乳","鄧","吉","仁","爛","磚","租","烏","艦","伴","瓜","淺","丙","暫","燥","橡","柳","迷","暖","牌","秧","膽","詳","簧","踏","瓷","譜","呆","賓","糊","洛","輝","憤","競","隙","怒","粘","乃","緒","肩","籍","敏","塗","熙","皆","偵","懸","掘","享","糾","醒","狂","鎖","淀","恨","牲","霸","爬","賞","逆","玩","陵","祝","秒","浙","貌","役","彼","悉","鴨","趨","鳳","晨","畜","輩","秩","卵","署","梯","炎","灘","棋","驅","篩","峽","冒","啥","壽","譯","浸","泉","帽","遲","矽","疆","貸","漏","稿","冠","嫩","脅","芯","牢","叛","蝕","奧","鳴","嶺","羊","憑","串","塘","繪","酵","融","盆","錫","廟","籌","凍","輔","攝","襲","筋","拒","僚","旱","鉀","鳥","漆","沈","眉","疏","添","棒","穗","硝","韓","逼","扭","僑","涼","挺","碗","栽","炒","杯","患","餾","勸","豪","遼","勃","鴻","旦","吏","拜","狗","埋","輥","掩","飲","搬","罵","辭","勾","扣","估","蔣","絨","霧","丈","朵","姆","擬","宇","輯","陝","雕","償","蓄","崇","剪","倡","廳","咬","駛","薯","刷","斥","番","賦","奉","佛","澆","漫","曼","扇","鈣","桃","扶","仔","返","俗","虧","腔","鞋","棱","覆","框","悄","叔","撞","騙","勘","旺","沸","孤","吐","孟","渠","屈","疾","妙","惜","仰","狠","脹","諧","拋","黴","桑","崗","嘛","衰","盜","滲","臟","賴","湧","甜","曹","閱","肌","哩","厲","烴","緯","毅","昨","偽","症","煮","嘆","釘","搭","莖","籠","酷","偷","弓","錐","恆","傑","坑","鼻","翼","綸","敘","獄","逮","罐","絡","棚","抑","膨","蔬","寺","驟","穆","冶","枯","冊","屍","凸","紳","坯","犧","焰","轟","欣","晉","瘦","禦","錠","錦","喪","旬","鍛","壟","搜","撲","邀","亭","酯","邁","舒","脆","酶","閒","憂","酚","頑","羽","漲","卸","仗","陪","闢","懲","杭","姚","肚","捉","飄","漂","昆","欺","吾","郎","烷","汁","呵","飾","蕭","雅","郵","遷","燕","撒","姻","赴","宴","煩","債","帳","斑","鈴","旨","醇","董","餅","雛","姿","拌","傅","腹","妥","揉","賢","拆","歪","葡","胺","丟","浩","徽","昂","墊","擋","覽","貪","慰","繳","汪","慌","馮","諾","姜","誼","兇","劣","誣","耀","昏","躺","盈","騎","喬","溪","叢","盧","抹","悶","諮","刮","駕","纜","悟","摘","鉺","擲","頗","幻","柄","惠","慘","佳","仇","臘","窩","滌","劍","瞧","堡","潑","蔥","罩","霍","撈","胎","蒼","濱","倆","捅","湘","砍","霞","邵","萄","瘋","淮","遂","熊","糞","烘","宿","檔","戈","駁","嫂","裕","徙","箭","捐","腸","撐","曬","辨","殿","蓮","攤","攪","醬","屏","疫","哀","蔡","堵","沫","皺","暢","疊","閣","萊","敲","轄","鉤","痕","壩","巷","餓","禍","丘","玄","溜","曰","邏","彭","嘗","卿","妨","艇","吞","韋","怨","矮","歇"]["abdikace","abeceda","adresa","agrese","akce","aktovka","alej","alkohol","amputace","ananas","andulka","anekdota","anketa","antika","anulovat","archa","arogance","asfalt","asistent","aspirace","astma","astronom","atlas","atletika","atol","autobus","azyl","babka","bachor","bacil","baculka","badatel","bageta","bagr","bahno","bakterie","balada","baletka","balkon","balonek","balvan","balza","bambus","bankomat","barbar","baret","barman","baroko","barva","baterka","batoh","bavlna","bazalka","bazilika","bazuka","bedna","beran","beseda","bestie","beton","bezinka","bezmoc","beztak","bicykl","bidlo","biftek","bikiny","bilance","biograf","biolog","bitva","bizon","blahobyt","blatouch","blecha","bledule","blesk","blikat","blizna","blokovat","bloudit","blud","bobek","bobr","bodlina","bodnout","bohatost","bojkot","bojovat","bokorys","bolest","borec","borovice","bota","boubel","bouchat","bouda","boule","bourat","boxer","bradavka","brambora","branka","bratr","brepta","briketa","brko","brloh","bronz","broskev","brunetka","brusinka","brzda","brzy","bublina","bubnovat","buchta","buditel","budka","budova","bufet","bujarost","bukvice","buldok","bulva","bunda","bunkr","burza","butik","buvol","buzola","bydlet","bylina","bytovka","bzukot","capart","carevna","cedr","cedule","cejch","cejn","cela","celer","celkem","celnice","cenina","cennost","cenovka","centrum","cenzor","cestopis","cetka","chalupa","chapadlo","charita","chata","chechtat","chemie","chichot","chirurg","chlad","chleba","chlubit","chmel","chmura","chobot","chochol","chodba","cholera","chomout","chopit","choroba","chov","chrapot","chrlit","chrt","chrup","chtivost","chudina","chutnat","chvat","chvilka","chvost","chyba","chystat","chytit","cibule","cigareta","cihelna","cihla","cinkot","cirkus","cisterna","citace","citrus","cizinec","cizost","clona","cokoliv","couvat","ctitel","ctnost","cudnost","cuketa","cukr","cupot","cvaknout","cval","cvik","cvrkot","cyklista","daleko","dareba","datel","datum","dcera","debata","dechovka","decibel","deficit","deflace","dekl","dekret","demokrat","deprese","derby","deska","detektiv","dikobraz","diktovat","dioda","diplom","disk","displej","divadlo","divoch","dlaha","dlouho","dluhopis","dnes","dobro","dobytek","docent","dochutit","dodnes","dohled","dohoda","dohra","dojem","dojnice","doklad","dokola","doktor","dokument","dolar","doleva","dolina","doma","dominant","domluvit","domov","donutit","dopad","dopis","doplnit","doposud","doprovod","dopustit","dorazit","dorost","dort","dosah","doslov","dostatek","dosud","dosyta","dotaz","dotek","dotknout","doufat","doutnat","dovozce","dozadu","doznat","dozorce","drahota","drak","dramatik","dravec","draze","drdol","drobnost","drogerie","drozd","drsnost","drtit","drzost","duben","duchovno","dudek","duha","duhovka","dusit","dusno","dutost","dvojice","dvorec","dynamit","ekolog","ekonomie","elektron","elipsa","email","emise","emoce","empatie","epizoda","epocha","epopej","epos","esej","esence","eskorta","eskymo","etiketa","euforie","evoluce","exekuce","exkurze","expedice","exploze","export","extrakt","facka","fajfka","fakulta","fanatik","fantazie","farmacie","favorit","fazole","federace","fejeton","fenka","fialka","figurant","filozof","filtr","finance","finta","fixace","fjord","flanel","flirt","flotila","fond","fosfor","fotbal","fotka","foton","frakce","freska","fronta","fukar","funkce","fyzika","galeje","garant","genetika","geolog","gilotina","glazura","glejt","golem","golfista","gotika","graf","gramofon","granule","grep","gril","grog","groteska","guma","hadice","hadr","hala","halenka","hanba","hanopis","harfa","harpuna","havran","hebkost","hejkal","hejno","hejtman","hektar","helma","hematom","herec","herna","heslo","hezky","historik","hladovka","hlasivky","hlava","hledat","hlen","hlodavec","hloh","hloupost","hltat","hlubina","hluchota","hmat","hmota","hmyz","hnis","hnojivo","hnout","hoblina","hoboj","hoch","hodiny","hodlat","hodnota","hodovat","hojnost","hokej","holinka","holka","holub","homole","honitba","honorace","horal","horda","horizont","horko","horlivec","hormon","hornina","horoskop","horstvo","hospoda","hostina","hotovost","houba","houf","houpat","houska","hovor","hradba","hranice","hravost","hrazda","hrbolek","hrdina","hrdlo","hrdost","hrnek","hrobka","hromada","hrot","hrouda","hrozen","hrstka","hrubost","hryzat","hubenost","hubnout","hudba","hukot","humr","husita","hustota","hvozd","hybnost","hydrant","hygiena","hymna","hysterik","idylka","ihned","ikona","iluze","imunita","infekce","inflace","inkaso","inovace","inspekce","internet","invalida","investor","inzerce","ironie","jablko","jachta","jahoda","jakmile","jakost","jalovec","jantar","jarmark","jaro","jasan","jasno","jatka","javor","jazyk","jedinec","jedle","jednatel","jehlan","jekot","jelen","jelito","jemnost","jenom","jepice","jeseter","jevit","jezdec","jezero","jinak","jindy","jinoch","jiskra","jistota","jitrnice","jizva","jmenovat","jogurt","jurta","kabaret","kabel","kabinet","kachna","kadet","kadidlo","kahan","kajak","kajuta","kakao","kaktus","kalamita","kalhoty","kalibr","kalnost","kamera","kamkoliv","kamna","kanibal","kanoe","kantor","kapalina","kapela","kapitola","kapka","kaple","kapota","kapr","kapusta","kapybara","karamel","karotka","karton","kasa","katalog","katedra","kauce","kauza","kavalec","kazajka","kazeta","kazivost","kdekoliv","kdesi","kedluben","kemp","keramika","kino","klacek","kladivo","klam","klapot","klasika","klaun","klec","klenba","klepat","klesnout","klid","klima","klisna","klobouk","klokan","klopa","kloub","klubovna","klusat","kluzkost","kmen","kmitat","kmotr","kniha","knot","koalice","koberec","kobka","kobliha","kobyla","kocour","kohout","kojenec","kokos","koktejl","kolaps","koleda","kolize","kolo","komando","kometa","komik","komnata","komora","kompas","komunita","konat","koncept","kondice","konec","konfese","kongres","konina","konkurs","kontakt","konzerva","kopanec","kopie","kopnout","koprovka","korbel","korektor","kormidlo","koroptev","korpus","koruna","koryto","korzet","kosatec","kostka","kotel","kotleta","kotoul","koukat","koupelna","kousek","kouzlo","kovboj","koza","kozoroh","krabice","krach","krajina","kralovat","krasopis","kravata","kredit","krejcar","kresba","kreveta","kriket","kritik","krize","krkavec","krmelec","krmivo","krocan","krok","kronika","kropit","kroupa","krovka","krtek","kruhadlo","krupice","krutost","krvinka","krychle","krypta","krystal","kryt","kudlanka","kufr","kujnost","kukla","kulajda","kulich","kulka","kulomet","kultura","kuna","kupodivu","kurt","kurzor","kutil","kvalita","kvasinka","kvestor","kynolog","kyselina","kytara","kytice","kytka","kytovec","kyvadlo","labrador","lachtan","ladnost","laik","lakomec","lamela","lampa","lanovka","lasice","laso","lastura","latinka","lavina","lebka","leckdy","leden","lednice","ledovka","ledvina","legenda","legie","legrace","lehce","lehkost","lehnout","lektvar","lenochod","lentilka","lepenka","lepidlo","letadlo","letec","letmo","letokruh","levhart","levitace","levobok","libra","lichotka","lidojed","lidskost","lihovina","lijavec","lilek","limetka","linie","linka","linoleum","listopad","litina","litovat","lobista","lodivod","logika","logoped","lokalita","loket","lomcovat","lopata","lopuch","lord","losos","lotr","loudal","louh","louka","louskat","lovec","lstivost","lucerna","lucifer","lump","lusk","lustrace","lvice","lyra","lyrika","lysina","madam","madlo","magistr","mahagon","majetek","majitel","majorita","makak","makovice","makrela","malba","malina","malovat","malvice","maminka","mandle","manko","marnost","masakr","maskot","masopust","matice","matrika","maturita","mazanec","mazivo","mazlit","mazurka","mdloba","mechanik","meditace","medovina","melasa","meloun","mentolka","metla","metoda","metr","mezera","migrace","mihnout","mihule","mikina","mikrofon","milenec","milimetr","milost","mimika","mincovna","minibar","minomet","minulost","miska","mistr","mixovat","mladost","mlha","mlhovina","mlok","mlsat","mluvit","mnich","mnohem","mobil","mocnost","modelka","modlitba","mohyla","mokro","molekula","momentka","monarcha","monokl","monstrum","montovat","monzun","mosaz","moskyt","most","motivace","motorka","motyka","moucha","moudrost","mozaika","mozek","mozol","mramor","mravenec","mrkev","mrtvola","mrzet","mrzutost","mstitel","mudrc","muflon","mulat","mumie","munice","muset","mutace","muzeum","muzikant","myslivec","mzda","nabourat","nachytat","nadace","nadbytek","nadhoz","nadobro","nadpis","nahlas","nahnat","nahodile","nahradit","naivita","najednou","najisto","najmout","naklonit","nakonec","nakrmit","nalevo","namazat","namluvit","nanometr","naoko","naopak","naostro","napadat","napevno","naplnit","napnout","naposled","naprosto","narodit","naruby","narychlo","nasadit","nasekat","naslepo","nastat","natolik","navenek","navrch","navzdory","nazvat","nebe","nechat","necky","nedaleko","nedbat","neduh","negace","nehet","nehoda","nejen","nejprve","neklid","nelibost","nemilost","nemoc","neochota","neonka","nepokoj","nerost","nerv","nesmysl","nesoulad","netvor","neuron","nevina","nezvykle","nicota","nijak","nikam","nikdy","nikl","nikterak","nitro","nocleh","nohavice","nominace","nora","norek","nositel","nosnost","nouze","noviny","novota","nozdra","nuda","nudle","nuget","nutit","nutnost","nutrie","nymfa","obal","obarvit","obava","obdiv","obec","obehnat","obejmout","obezita","obhajoba","obilnice","objasnit","objekt","obklopit","oblast","oblek","obliba","obloha","obluda","obnos","obohatit","obojek","obout","obrazec","obrna","obruba","obrys","obsah","obsluha","obstarat","obuv","obvaz","obvinit","obvod","obvykle","obyvatel","obzor","ocas","ocel","ocenit","ochladit","ochota","ochrana","ocitnout","odboj","odbyt","odchod","odcizit","odebrat","odeslat","odevzdat","odezva","odhadce","odhodit","odjet","odjinud","odkaz","odkoupit","odliv","odluka","odmlka","odolnost","odpad","odpis","odplout","odpor","odpustit","odpykat","odrazka","odsoudit","odstup","odsun","odtok","odtud","odvaha","odveta","odvolat","odvracet","odznak","ofina","ofsajd","ohlas","ohnisko","ohrada","ohrozit","ohryzek","okap","okenice","oklika","okno","okouzlit","okovy","okrasa","okres","okrsek","okruh","okupant","okurka","okusit","olejnina","olizovat","omak","omeleta","omezit","omladina","omlouvat","omluva","omyl","onehdy","opakovat","opasek","operace","opice","opilost","opisovat","opora","opozice","opravdu","oproti","orbital","orchestr","orgie","orlice","orloj","ortel","osada","oschnout","osika","osivo","oslava","oslepit","oslnit","oslovit","osnova","osoba","osolit","ospalec","osten","ostraha","ostuda","ostych","osvojit","oteplit","otisk","otop","otrhat","otrlost","otrok","otruby","otvor","ovanout","ovar","oves","ovlivnit","ovoce","oxid","ozdoba","pachatel","pacient","padouch","pahorek","pakt","palanda","palec","palivo","paluba","pamflet","pamlsek","panenka","panika","panna","panovat","panstvo","pantofle","paprika","parketa","parodie","parta","paruka","paryba","paseka","pasivita","pastelka","patent","patrona","pavouk","pazneht","pazourek","pecka","pedagog","pejsek","peklo","peloton","penalta","pendrek","penze","periskop","pero","pestrost","petarda","petice","petrolej","pevnina","pexeso","pianista","piha","pijavice","pikle","piknik","pilina","pilnost","pilulka","pinzeta","pipeta","pisatel","pistole","pitevna","pivnice","pivovar","placenta","plakat","plamen","planeta","plastika","platit","plavidlo","plaz","plech","plemeno","plenta","ples","pletivo","plevel","plivat","plnit","plno","plocha","plodina","plomba","plout","pluk","plyn","pobavit","pobyt","pochod","pocit","poctivec","podat","podcenit","podepsat","podhled","podivit","podklad","podmanit","podnik","podoba","podpora","podraz","podstata","podvod","podzim","poezie","pohanka","pohnutka","pohovor","pohroma","pohyb","pointa","pojistka","pojmout","pokazit","pokles","pokoj","pokrok","pokuta","pokyn","poledne","polibek","polknout","poloha","polynom","pomalu","pominout","pomlka","pomoc","pomsta","pomyslet","ponechat","ponorka","ponurost","popadat","popel","popisek","poplach","poprosit","popsat","popud","poradce","porce","porod","porucha","poryv","posadit","posed","posila","poskok","poslanec","posoudit","pospolu","postava","posudek","posyp","potah","potkan","potlesk","potomek","potrava","potupa","potvora","poukaz","pouto","pouzdro","povaha","povidla","povlak","povoz","povrch","povstat","povyk","povzdech","pozdrav","pozemek","poznatek","pozor","pozvat","pracovat","prahory","praktika","prales","praotec","praporek","prase","pravda","princip","prkno","probudit","procento","prodej","profese","prohra","projekt","prolomit","promile","pronikat","propad","prorok","prosba","proton","proutek","provaz","prskavka","prsten","prudkost","prut","prvek","prvohory","psanec","psovod","pstruh","ptactvo","puberta","puch","pudl","pukavec","puklina","pukrle","pult","pumpa","punc","pupen","pusa","pusinka","pustina","putovat","putyka","pyramida","pysk","pytel","racek","rachot","radiace","radnice","radon","raft","ragby","raketa","rakovina","rameno","rampouch","rande","rarach","rarita","rasovna","rastr","ratolest","razance","razidlo","reagovat","reakce","recept","redaktor","referent","reflex","rejnok","reklama","rekord","rekrut","rektor","reputace","revize","revma","revolver","rezerva","riskovat","riziko","robotika","rodokmen","rohovka","rokle","rokoko","romaneto","ropovod","ropucha","rorejs","rosol","rostlina","rotmistr","rotoped","rotunda","roubenka","roucho","roup","roura","rovina","rovnice","rozbor","rozchod","rozdat","rozeznat","rozhodce","rozinka","rozjezd","rozkaz","rozloha","rozmar","rozpad","rozruch","rozsah","roztok","rozum","rozvod","rubrika","ruchadlo","rukavice","rukopis","ryba","rybolov","rychlost","rydlo","rypadlo","rytina","ryzost","sadista","sahat","sako","samec","samizdat","samota","sanitka","sardinka","sasanka","satelit","sazba","sazenice","sbor","schovat","sebranka","secese","sedadlo","sediment","sedlo","sehnat","sejmout","sekera","sekta","sekunda","sekvoje","semeno","seno","servis","sesadit","seshora","seskok","seslat","sestra","sesuv","sesypat","setba","setina","setkat","setnout","setrvat","sever","seznam","shoda","shrnout","sifon","silnice","sirka","sirotek","sirup","situace","skafandr","skalisko","skanzen","skaut","skeptik","skica","skladba","sklenice","sklo","skluz","skoba","skokan","skoro","skripta","skrz","skupina","skvost","skvrna","slabika","sladidlo","slanina","slast","slavnost","sledovat","slepec","sleva","slezina","slib","slina","sliznice","slon","sloupek","slovo","sluch","sluha","slunce","slupka","slza","smaragd","smetana","smilstvo","smlouva","smog","smrad","smrk","smrtka","smutek","smysl","snad","snaha","snob","sobota","socha","sodovka","sokol","sopka","sotva","souboj","soucit","soudce","souhlas","soulad","soumrak","souprava","soused","soutok","souviset","spalovna","spasitel","spis","splav","spodek","spojenec","spolu","sponzor","spornost","spousta","sprcha","spustit","sranda","sraz","srdce","srna","srnec","srovnat","srpen","srst","srub","stanice","starosta","statika","stavba","stehno","stezka","stodola","stolek","stopa","storno","stoupat","strach","stres","strhnout","strom","struna","studna","stupnice","stvol","styk","subjekt","subtropy","suchar","sudost","sukno","sundat","sunout","surikata","surovina","svah","svalstvo","svetr","svatba","svazek","svisle","svitek","svoboda","svodidlo","svorka","svrab","sykavka","sykot","synek","synovec","sypat","sypkost","syrovost","sysel","sytost","tabletka","tabule","tahoun","tajemno","tajfun","tajga","tajit","tajnost","taktika","tamhle","tampon","tancovat","tanec","tanker","tapeta","tavenina","tazatel","technika","tehdy","tekutina","telefon","temnota","tendence","tenista","tenor","teplota","tepna","teprve","terapie","termoska","textil","ticho","tiskopis","titulek","tkadlec","tkanina","tlapka","tleskat","tlukot","tlupa","tmel","toaleta","topinka","topol","torzo","touha","toulec","tradice","traktor","tramp","trasa","traverza","trefit","trest","trezor","trhavina","trhlina","trochu","trojice","troska","trouba","trpce","trpitel","trpkost","trubec","truchlit","truhlice","trus","trvat","tudy","tuhnout","tuhost","tundra","turista","turnaj","tuzemsko","tvaroh","tvorba","tvrdost","tvrz","tygr","tykev","ubohost","uboze","ubrat","ubrousek","ubrus","ubytovna","ucho","uctivost","udivit","uhradit","ujednat","ujistit","ujmout","ukazatel","uklidnit","uklonit","ukotvit","ukrojit","ulice","ulita","ulovit","umyvadlo","unavit","uniforma","uniknout","upadnout","uplatnit","uplynout","upoutat","upravit","uran","urazit","usednout","usilovat","usmrtit","usnadnit","usnout","usoudit","ustlat","ustrnout","utahovat","utkat","utlumit","utonout","utopenec","utrousit","uvalit","uvolnit","uvozovka","uzdravit","uzel","uzenina","uzlina","uznat","vagon","valcha","valoun","vana","vandal","vanilka","varan","varhany","varovat","vcelku","vchod","vdova","vedro","vegetace","vejce","velbloud","veletrh","velitel","velmoc","velryba","venkov","veranda","verze","veselka","veskrze","vesnice","vespodu","vesta","veterina","veverka","vibrace","vichr","videohra","vidina","vidle","vila","vinice","viset","vitalita","vize","vizitka","vjezd","vklad","vkus","vlajka","vlak","vlasec","vlevo","vlhkost","vliv","vlnovka","vloupat","vnucovat","vnuk","voda","vodivost","vodoznak","vodstvo","vojensky","vojna","vojsko","volant","volba","volit","volno","voskovka","vozidlo","vozovna","vpravo","vrabec","vracet","vrah","vrata","vrba","vrcholek","vrhat","vrstva","vrtule","vsadit","vstoupit","vstup","vtip","vybavit","vybrat","vychovat","vydat","vydra","vyfotit","vyhledat","vyhnout","vyhodit","vyhradit","vyhubit","vyjasnit","vyjet","vyjmout","vyklopit","vykonat","vylekat","vymazat","vymezit","vymizet","vymyslet","vynechat","vynikat","vynutit","vypadat","vyplatit","vypravit","vypustit","vyrazit","vyrovnat","vyrvat","vyslovit","vysoko","vystavit","vysunout","vysypat","vytasit","vytesat","vytratit","vyvinout","vyvolat","vyvrhel","vyzdobit","vyznat","vzadu","vzbudit","vzchopit","vzdor","vzduch","vzdychat","vzestup","vzhledem","vzkaz","vzlykat","vznik","vzorek","vzpoura","vztah","vztek","xylofon","zabrat","zabydlet","zachovat","zadarmo","zadusit","zafoukat","zahltit","zahodit","zahrada","zahynout","zajatec","zajet","zajistit","zaklepat","zakoupit","zalepit","zamezit","zamotat","zamyslet","zanechat","zanikat","zaplatit","zapojit","zapsat","zarazit","zastavit","zasunout","zatajit","zatemnit","zatknout","zaujmout","zavalit","zavelet","zavinit","zavolat","zavrtat","zazvonit","zbavit","zbrusu","zbudovat","zbytek","zdaleka","zdarma","zdatnost","zdivo","zdobit","zdroj","zdvih","zdymadlo","zelenina","zeman","zemina","zeptat","zezadu","zezdola","zhatit","zhltnout","zhluboka","zhotovit","zhruba","zima","zimnice","zjemnit","zklamat","zkoumat","zkratka","zkumavka","zlato","zlehka","zloba","zlom","zlost","zlozvyk","zmapovat","zmar","zmatek","zmije","zmizet","zmocnit","zmodrat","zmrzlina","zmutovat","znak","znalost","znamenat","znovu","zobrazit","zotavit","zoubek","zoufale","zplodit","zpomalit","zprava","zprostit","zprudka","zprvu","zrada","zranit","zrcadlo","zrnitost","zrno","zrovna","zrychlit","zrzavost","zticha","ztratit","zubovina","zubr","zvednout","zvenku","zvesela","zvon","zvrat","zvukovod","zvyk"]["abandon","ability","able","about","above","absent","absorb","abstract","absurd","abuse","access","accident","account","accuse","achieve","acid","acoustic","acquire","across","act","action","actor","actress","actual","adapt","add","addict","address","adjust","admit","adult","advance","advice","aerobic","affair","afford","afraid","again","age","agent","agree","ahead","aim","air","airport","aisle","alarm","album","alcohol","alert","alien","all","alley","allow","almost","alone","alpha","already","also","alter","always","amateur","amazing","among","amount","amused","analyst","anchor","ancient","anger","angle","angry","animal","ankle","announce","annual","another","answer","antenna","antique","anxiety","any","apart","apology","appear","apple","approve","april","arch","arctic","area","arena","argue","arm","armed","armor","army","around","arrange","arrest","arrive","arrow","art","artefact","artist","artwork","ask","aspect","assault","asset","assist","assume","asthma","athlete","atom","attack","attend","attitude","attract","auction","audit","august","aunt","author","auto","autumn","average","avocado","avoid","awake","aware","away","awesome","awful","awkward","axis","baby","bachelor","bacon","badge","bag","balance","balcony","ball","bamboo","banana","banner","bar","barely","bargain","barrel","base","basic","basket","battle","beach","bean","beauty","because","become","beef","before","begin","behave","behind","believe","below","belt","bench","benefit","best","betray","better","between","beyond","bicycle","bid","bike","bind","biology","bird","birth","bitter","black","blade","blame","blanket","blast","bleak","bless","blind","blood","blossom","blouse","blue","blur","blush","board","boat","body","boil","bomb","bone","bonus","book","boost","border","boring","borrow","boss","bottom","bounce","box","boy","bracket","brain","brand","brass","brave","bread","breeze","brick","bridge","brief","bright","bring","brisk","broccoli","broken","bronze","broom","brother","brown","brush","bubble","buddy","budget","buffalo","build","bulb","bulk","bullet","bundle","bunker","burden","burger","burst","bus","business","busy","butter","buyer","buzz","cabbage","cabin","cable","cactus","cage","cake","call","calm","camera","camp","can","canal","cancel","candy","cannon","canoe","canvas","canyon","capable","capital","captain","car","carbon","card","cargo","carpet","carry","cart","case","cash","casino","castle","casual","cat","catalog","catch","category","cattle","caught","cause","caution","cave","ceiling","celery","cement","census","century","cereal","certain","chair","chalk","champion","change","chaos","chapter","charge","chase","chat","cheap","check","cheese","chef","cherry","chest","chicken","chief","child","chimney","choice","choose","chronic","chuckle","chunk","churn","cigar","cinnamon","circle","citizen","city","civil","claim","clap","clarify","claw","clay","clean","clerk","clever","click","client","cliff","climb","clinic","clip","clock","clog","close","cloth","cloud","clown","club","clump","cluster","clutch","coach","coast","coconut","code","coffee","coil","coin","collect","color","column","combine","come","comfort","comic","common","company","concert","conduct","confirm","congress","connect","consider","control","convince","cook","cool","copper","copy","coral","core","corn","correct","cost","cotton","couch","country","couple","course","cousin","cover","coyote","crack","cradle","craft","cram","crane","crash","crater","crawl","crazy","cream","credit","creek","crew","cricket","crime","crisp","critic","crop","cross","crouch","crowd","crucial","cruel","cruise","crumble","crunch","crush","cry","crystal","cube","culture","cup","cupboard","curious","current","curtain","curve","cushion","custom","cute","cycle","dad","damage","damp","dance","danger","daring","dash","daughter","dawn","day","deal","debate","debris","decade","december","decide","decline","decorate","decrease","deer","defense","define","defy","degree","delay","deliver","demand","demise","denial","dentist","deny","depart","depend","deposit","depth","deputy","derive","describe","desert","design","desk","despair","destroy","detail","detect","develop","device","devote","diagram","dial","diamond","diary","dice","diesel","diet","differ","digital","dignity","dilemma","dinner","dinosaur","direct","dirt","disagree","discover","disease","dish","dismiss","disorder","display","distance","divert","divide","divorce","dizzy","doctor","document","dog","doll","dolphin","domain","donate","donkey","donor","door","dose","double","dove","draft","dragon","drama","drastic","draw","dream","dress","drift","drill","drink","drip","drive","drop","drum","dry","duck","dumb","dune","during","dust","dutch","duty","dwarf","dynamic","eager","eagle","early","earn","earth","easily","east","easy","echo","ecology","economy","edge","edit","educate","effort","egg","eight","either","elbow","elder","electric","elegant","element","elephant","elevator","elite","else","embark","embody","embrace","emerge","emotion","employ","empower","empty","enable","enact","end","endless","endorse","enemy","energy","enforce","engage","engine","enhance","enjoy","enlist","enough","enrich","enroll","ensure","enter","entire","entry","envelope","episode","equal","equip","era","erase","erode","erosion","error","erupt","escape","essay","essence","estate","eternal","ethics","evidence","evil","evoke","evolve","exact","example","excess","exchange","excite","exclude","excuse","execute","exercise","exhaust","exhibit","exile","exist","exit","exotic","expand","expect","expire","explain","expose","express","extend","extra","eye","eyebrow","fabric","face","faculty","fade","faint","faith","fall","false","fame","family","famous","fan","fancy","fantasy","farm","fashion","fat","fatal","father","fatigue","fault","favorite","feature","february","federal","fee","feed","feel","female","fence","festival","fetch","fever","few","fiber","fiction","field","figure","file","film","filter","final","find","fine","finger","finish","fire","firm","first","fiscal","fish","fit","fitness","fix","flag","flame","flash","flat","flavor","flee","flight","flip","float","flock","floor","flower","fluid","flush","fly","foam","focus","fog","foil","fold","follow","food","foot","force","forest","forget","fork","fortune","forum","forward","fossil","foster","found","fox","fragile","frame","frequent","fresh","friend","fringe","frog","front","frost","frown","frozen","fruit","fuel","fun","funny","furnace","fury","future","gadget","gain","galaxy","gallery","game","gap","garage","garbage","garden","garlic","garment","gas","gasp","gate","gather","gauge","gaze","general","genius","genre","gentle","genuine","gesture","ghost","giant","gift","giggle","ginger","giraffe","girl","give","glad","glance","glare","glass","glide","glimpse","globe","gloom","glory","glove","glow","glue","goat","goddess","gold","good","goose","gorilla","gospel","gossip","govern","gown","grab","grace","grain","grant","grape","grass","gravity","great","green","grid","grief","grit","grocery","group","grow","grunt","guard","guess","guide","guilt","guitar","gun","gym","habit","hair","half","hammer","hamster","hand","happy","harbor","hard","harsh","harvest","hat","have","hawk","hazard","head","health","heart","heavy","hedgehog","height","hello","helmet","help","hen","hero","hidden","high","hill","hint","hip","hire","history","hobby","hockey","hold","hole","holiday","hollow","home","honey","hood","hope","horn","horror","horse","hospital","host","hotel","hour","hover","hub","huge","human","humble","humor","hundred","hungry","hunt","hurdle","hurry","hurt","husband","hybrid","ice","icon","idea","identify","idle","ignore","ill","illegal","illness","image","imitate","immense","immune","impact","impose","improve","impulse","inch","include","income","increase","index","indicate","indoor","industry","infant","inflict","inform","inhale","inherit","initial","inject","injury","inmate","inner","innocent","input","inquiry","insane","insect","inside","inspire","install","intact","interest","into","invest","invite","involve","iron","island","isolate","issue","item","ivory","jacket","jaguar","jar","jazz","jealous","jeans","jelly","jewel","job","join","joke","journey","joy","judge","juice","jump","jungle","junior","junk","just","kangaroo","keen","keep","ketchup","key","kick","kid","kidney","kind","kingdom","kiss","kit","kitchen","kite","kitten","kiwi","knee","knife","knock","know","lab","label","labor","ladder","lady","lake","lamp","language","laptop","large","later","latin","laugh","laundry","lava","law","lawn","lawsuit","layer","lazy","leader","leaf","learn","leave","lecture","left","leg","legal","legend","leisure","lemon","lend","length","lens","leopard","lesson","letter","level","liar","liberty","library","license","life","lift","light","like","limb","limit","link","lion","liquid","list","little","live","lizard","load","loan","lobster","local","lock","logic","lonely","long","loop","lottery","loud","lounge","love","loyal","lucky","luggage","lumber","lunar","lunch","luxury","lyrics","machine","mad","magic","magnet","maid","mail","main","major","make","mammal","man","manage","mandate","mango","mansion","manual","maple","marble","march","margin","marine","market","marriage","mask","mass","master","match","material","math","matrix","matter","maximum","maze","meadow","mean","measure","meat","mechanic","medal","media","melody","melt","member","memory","mention","menu","mercy","merge","merit","merry","mesh","message","metal","method","middle","midnight","milk","million","mimic","mind","minimum","minor","minute","miracle","mirror","misery","miss","mistake","mix","mixed","mixture","mobile","model","modify","mom","moment","monitor","monkey","monster","month","moon","moral","more","morning","mosquito","mother","motion","motor","mountain","mouse","move","movie","much","muffin","mule","multiply","muscle","museum","mushroom","music","must","mutual","myself","mystery","myth","naive","name","napkin","narrow","nasty","nation","nature","near","neck","need","negative","neglect","neither","nephew","nerve","nest","net","network","neutral","never","news","next","nice","night","noble","noise","nominee","noodle","normal","north","nose","notable","note","nothing","notice","novel","now","nuclear","number","nurse","nut","oak","obey","object","oblige","obscure","observe","obtain","obvious","occur","ocean","october","odor","off","offer","office","often","oil","okay","old","olive","olympic","omit","once","one","onion","online","only","open","opera","opinion","oppose","option","orange","orbit","orchard","order","ordinary","organ","orient","original","orphan","ostrich","other","outdoor","outer","output","outside","oval","oven","over","own","owner","oxygen","oyster","ozone","pact","paddle","page","pair","palace","palm","panda","panel","panic","panther","paper","parade","parent","park","parrot","party","pass","patch","path","patient","patrol","pattern","pause","pave","payment","peace","peanut","pear","peasant","pelican","pen","penalty","pencil","people","pepper","perfect","permit","person","pet","phone","photo","phrase","physical","piano","picnic","picture","piece","pig","pigeon","pill","pilot","pink","pioneer","pipe","pistol","pitch","pizza","place","planet","plastic","plate","play","please","pledge","pluck","plug","plunge","poem","poet","point","polar","pole","police","pond","pony","pool","popular","portion","position","possible","post","potato","pottery","poverty","powder","power","practice","praise","predict","prefer","prepare","present","pretty","prevent","price","pride","primary","print","priority","prison","private","prize","problem","process","produce","profit","program","project","promote","proof","property","prosper","protect","proud","provide","public","pudding","pull","pulp","pulse","pumpkin","punch","pupil","puppy","purchase","purity","purpose","purse","push","put","puzzle","pyramid","quality","quantum","quarter","question","quick","quit","quiz","quote","rabbit","raccoon","race","rack","radar","radio","rail","rain","raise","rally","ramp","ranch","random","range","rapid","rare","rate","rather","raven","raw","razor","ready","real","reason","rebel","rebuild","recall","receive","recipe","record","recycle","reduce","reflect","reform","refuse","region","regret","regular","reject","relax","release","relief","rely","remain","remember","remind","remove","render","renew","rent","reopen","repair","repeat","replace","report","require","rescue","resemble","resist","resource","response","result","retire","retreat","return","reunion","reveal","review","reward","rhythm","rib","ribbon","rice","rich","ride","ridge","rifle","right","rigid","ring","riot","ripple","risk","ritual","rival","river","road","roast","robot","robust","rocket","romance","roof","rookie","room","rose","rotate","rough","round","route","royal","rubber","rude","rug","rule","run","runway","rural","sad","saddle","sadness","safe","sail","salad","salmon","salon","salt","salute","same","sample","sand","satisfy","satoshi","sauce","sausage","save","say","scale","scan","scare","scatter","scene","scheme","school","science","scissors","scorpion","scout","scrap","screen","script","scrub","sea","search","season","seat","second","secret","section","security","seed","seek","segment","select","sell","seminar","senior","sense","sentence","series","service","session","settle","setup","seven","shadow","shaft","shallow","share","shed","shell","sheriff","shield","shift","shine","ship","shiver","shock","shoe","shoot","shop","short","shoulder","shove","shrimp","shrug","shuffle","shy","sibling","sick","side","siege","sight","sign","silent","silk","silly","silver","similar","simple","since","sing","siren","sister","situate","six","size","skate","sketch","ski","skill","skin","skirt","skull","slab","slam","sleep","slender","slice","slide","slight","slim","slogan","slot","slow","slush","small","smart","smile","smoke","smooth","snack","snake","snap","sniff","snow","soap","soccer","social","sock","soda","soft","solar","soldier","solid","solution","solve","someone","song","soon","sorry","sort","soul","sound","soup","source","south","space","spare","spatial","spawn","speak","special","speed","spell","spend","sphere","spice","spider","spike","spin","spirit","split","spoil","sponsor","spoon","sport","spot","spray","spread","spring","spy","square","squeeze","squirrel","stable","stadium","staff","stage","stairs","stamp","stand","start","state","stay","steak","steel","stem","step","stereo","stick","still","sting","stock","stomach","stone","stool","story","stove","strategy","street","strike","strong","struggle","student","stuff","stumble","style","subject","submit","subway","success","such","sudden","suffer","sugar","suggest","suit","summer","sun","sunny","sunset","super","supply","supreme","sure","surface","surge","surprise","surround","survey","suspect","sustain","swallow","swamp","swap","swarm","swear","sweet","swift","swim","swing","switch","sword","symbol","symptom","syrup","system","table","tackle","tag","tail","talent","talk","tank","tape","target","task","taste","tattoo","taxi","teach","team","tell","ten","tenant","tennis","tent","term","test","text","thank","that","theme","then","theory","there","they","thing","this","thought","three","thrive","throw","thumb","thunder","ticket","tide","tiger","tilt","timber","time","tiny","tip","tired","tissue","title","toast","tobacco","today","toddler","toe","together","toilet","token","tomato","tomorrow","tone","tongue","tonight","tool","tooth","top","topic","topple","torch","tornado","tortoise","toss","total","tourist","toward","tower","town","toy","track","trade","traffic","tragic","train","transfer","trap","trash","travel","tray","treat","tree","trend","trial","tribe","trick","trigger","trim","trip","trophy","trouble","truck","true","truly","trumpet","trust","truth","try","tube","tuition","tumble","tuna","tunnel","turkey","turn","turtle","twelve","twenty","twice","twin","twist","two","type","typical","ugly","umbrella","unable","unaware","uncle","uncover","under","undo","unfair","unfold","unhappy","uniform","unique","unit","universe","unknown","unlock","until","unusual","unveil","update","upgrade","uphold","upon","upper","upset","urban","urge","usage","use","used","useful","useless","usual","utility","vacant","vacuum","vague","valid","valley","valve","van","vanish","vapor","various","vast","vault","vehicle","velvet","vendor","venture","venue","verb","verify","version","very","vessel","veteran","viable","vibrant","vicious","victory","video","view","village","vintage","violin","virtual","virus","visa","visit","visual","vital","vivid","vocal","voice","void","volcano","volume","vote","voyage","wage","wagon","wait","walk","wall","walnut","want","warfare","warm","warrior","wash","wasp","waste","water","wave","way","wealth","weapon","wear","weasel","weather","web","wedding","weekend","weird","welcome","west","wet","whale","what","wheat","wheel","when","where","whip","whisper","wide","width","wife","wild","will","win","window","wine","wing","wink","winner","winter","wire","wisdom","wise","wish","witness","wolf","woman","wonder","wood","wool","word","work","world","worry","worth","wrap","wreck","wrestle","wrist","write","wrong","yard","year","yellow","you","young","youth","zebra","zero","zone","zoo"]["abaisser","abandon","abdiquer","abeille","abolir","aborder","aboutir","aboyer","abrasif","abreuver","abriter","abroger","abrupt","absence","absolu","absurde","abusif","abyssal","académie","acajou","acarien","accabler","accepter","acclamer","accolade","accroche","accuser","acerbe","achat","acheter","aciduler","acier","acompte","acquérir","acronyme","acteur","actif","actuel","adepte","adéquat","adhésif","adjectif","adjuger","admettre","admirer","adopter","adorer","adoucir","adresse","adroit","adulte","adverbe","aérer","aéronef","affaire","affecter","affiche","affreux","affubler","agacer","agencer","agile","agiter","agrafer","agréable","agrume","aider","aiguille","ailier","aimable","aisance","ajouter","ajuster","alarmer","alchimie","alerte","algèbre","algue","aliéner","aliment","alléger","alliage","allouer","allumer","alourdir","alpaga","altesse","alvéole","amateur","ambigu","ambre","aménager","amertume","amidon","amiral","amorcer","amour","amovible","amphibie","ampleur","amusant","analyse","anaphore","anarchie","anatomie","ancien","anéantir","angle","angoisse","anguleux","animal","annexer","annonce","annuel","anodin","anomalie","anonyme","anormal","antenne","antidote","anxieux","apaiser","apéritif","aplanir","apologie","appareil","appeler","apporter","appuyer","aquarium","aqueduc","arbitre","arbuste","ardeur","ardoise","argent","arlequin","armature","armement","armoire","armure","arpenter","arracher","arriver","arroser","arsenic","artériel","article","aspect","asphalte","aspirer","assaut","asservir","assiette","associer","assurer","asticot","astre","astuce","atelier","atome","atrium","atroce","attaque","attentif","attirer","attraper","aubaine","auberge","audace","audible","augurer","aurore","automne","autruche","avaler","avancer","avarice","avenir","averse","aveugle","aviateur","avide","avion","aviser","avoine","avouer","avril","axial","axiome","badge","bafouer","bagage","baguette","baignade","balancer","balcon","baleine","balisage","bambin","bancaire","bandage","banlieue","bannière","banquier","barbier","baril","baron","barque","barrage","bassin","bastion","bataille","bateau","batterie","baudrier","bavarder","belette","bélier","belote","bénéfice","berceau","berger","berline","bermuda","besace","besogne","bétail","beurre","biberon","bicycle","bidule","bijou","bilan","bilingue","billard","binaire","biologie","biopsie","biotype","biscuit","bison","bistouri","bitume","bizarre","blafard","blague","blanchir","blessant","blinder","blond","bloquer","blouson","bobard","bobine","boire","boiser","bolide","bonbon","bondir","bonheur","bonifier","bonus","bordure","borne","botte","boucle","boueux","bougie","boulon","bouquin","bourse","boussole","boutique","boxeur","branche","brasier","brave","brebis","brèche","breuvage","bricoler","brigade","brillant","brioche","brique","brochure","broder","bronzer","brousse","broyeur","brume","brusque","brutal","bruyant","buffle","buisson","bulletin","bureau","burin","bustier","butiner","butoir","buvable","buvette","cabanon","cabine","cachette","cadeau","cadre","caféine","caillou","caisson","calculer","calepin","calibre","calmer","calomnie","calvaire","camarade","caméra","camion","campagne","canal","caneton","canon","cantine","canular","capable","caporal","caprice","capsule","capter","capuche","carabine","carbone","caresser","caribou","carnage","carotte","carreau","carton","cascade","casier","casque","cassure","causer","caution","cavalier","caverne","caviar","cédille","ceinture","céleste","cellule","cendrier","censurer","central","cercle","cérébral","cerise","cerner","cerveau","cesser","chagrin","chaise","chaleur","chambre","chance","chapitre","charbon","chasseur","chaton","chausson","chavirer","chemise","chenille","chéquier","chercher","cheval","chien","chiffre","chignon","chimère","chiot","chlorure","chocolat","choisir","chose","chouette","chrome","chute","cigare","cigogne","cimenter","cinéma","cintrer","circuler","cirer","cirque","citerne","citoyen","citron","civil","clairon","clameur","claquer","classe","clavier","client","cligner","climat","clivage","cloche","clonage","cloporte","cobalt","cobra","cocasse","cocotier","coder","codifier","coffre","cogner","cohésion","coiffer","coincer","colère","colibri","colline","colmater","colonel","combat","comédie","commande","compact","concert","conduire","confier","congeler","connoter","consonne","contact","convexe","copain","copie","corail","corbeau","cordage","corniche","corpus","correct","cortège","cosmique","costume","coton","coude","coupure","courage","couteau","couvrir","coyote","crabe","crainte","cravate","crayon","créature","créditer","crémeux","creuser","crevette","cribler","crier","cristal","critère","croire","croquer","crotale","crucial","cruel","crypter","cubique","cueillir","cuillère","cuisine","cuivre","culminer","cultiver","cumuler","cupide","curatif","curseur","cyanure","cycle","cylindre","cynique","daigner","damier","danger","danseur","dauphin","débattre","débiter","déborder","débrider","débutant","décaler","décembre","déchirer","décider","déclarer","décorer","décrire","décupler","dédale","déductif","déesse","défensif","défiler","défrayer","dégager","dégivrer","déglutir","dégrafer","déjeuner","délice","déloger","demander","demeurer","démolir","dénicher","dénouer","dentelle","dénuder","départ","dépenser","déphaser","déplacer","déposer","déranger","dérober","désastre","descente","désert","désigner","désobéir","dessiner","destrier","détacher","détester","détourer","détresse","devancer","devenir","deviner","devoir","diable","dialogue","diamant","dicter","différer","digérer","digital","digne","diluer","dimanche","diminuer","dioxyde","directif","diriger","discuter","disposer","dissiper","distance","divertir","diviser","docile","docteur","dogme","doigt","domaine","domicile","dompter","donateur","donjon","donner","dopamine","dortoir","dorure","dosage","doseur","dossier","dotation","douanier","double","douceur","douter","doyen","dragon","draper","dresser","dribbler","droiture","duperie","duplexe","durable","durcir","dynastie","éblouir","écarter","écharpe","échelle","éclairer","éclipse","éclore","écluse","école","économie","écorce","écouter","écraser","écrémer","écrivain","écrou","écume","écureuil","édifier","éduquer","effacer","effectif","effigie","effort","effrayer","effusion","égaliser","égarer","éjecter","élaborer","élargir","électron","élégant","éléphant","élève","éligible","élitisme","éloge","élucider","éluder","emballer","embellir","embryon","émeraude","émission","emmener","émotion","émouvoir","empereur","employer","emporter","emprise","émulsion","encadrer","enchère","enclave","encoche","endiguer","endosser","endroit","enduire","énergie","enfance","enfermer","enfouir","engager","engin","englober","énigme","enjamber","enjeu","enlever","ennemi","ennuyeux","enrichir","enrobage","enseigne","entasser","entendre","entier","entourer","entraver","énumérer","envahir","enviable","envoyer","enzyme","éolien","épaissir","épargne","épatant","épaule","épicerie","épidémie","épier","épilogue","épine","épisode","épitaphe","époque","épreuve","éprouver","épuisant","équerre","équipe","ériger","érosion","erreur","éruption","escalier","espadon","espèce","espiègle","espoir","esprit","esquiver","essayer","essence","essieu","essorer","estime","estomac","estrade","étagère","étaler","étanche","étatique","éteindre","étendoir","éternel","éthanol","éthique","ethnie","étirer","étoffer","étoile","étonnant","étourdir","étrange","étroit","étude","euphorie","évaluer","évasion","éventail","évidence","éviter","évolutif","évoquer","exact","exagérer","exaucer","exceller","excitant","exclusif","excuse","exécuter","exemple","exercer","exhaler","exhorter","exigence","exiler","exister","exotique","expédier","explorer","exposer","exprimer","exquis","extensif","extraire","exulter","fable","fabuleux","facette","facile","facture","faiblir","falaise","fameux","famille","farceur","farfelu","farine","farouche","fasciner","fatal","fatigue","faucon","fautif","faveur","favori","fébrile","féconder","fédérer","félin","femme","fémur","fendoir","féodal","fermer","féroce","ferveur","festival","feuille","feutre","février","fiasco","ficeler","fictif","fidèle","figure","filature","filetage","filière","filleul","filmer","filou","filtrer","financer","finir","fiole","firme","fissure","fixer","flairer","flamme","flasque","flatteur","fléau","flèche","fleur","flexion","flocon","flore","fluctuer","fluide","fluvial","folie","fonderie","fongible","fontaine","forcer","forgeron","formuler","fortune","fossile","foudre","fougère","fouiller","foulure","fourmi","fragile","fraise","franchir","frapper","frayeur","frégate","freiner","frelon","frémir","frénésie","frère","friable","friction","frisson","frivole","froid","fromage","frontal","frotter","fruit","fugitif","fuite","fureur","furieux","furtif","fusion","futur","gagner","galaxie","galerie","gambader","garantir","gardien","garnir","garrigue","gazelle","gazon","géant","gélatine","gélule","gendarme","général","génie","genou","gentil","géologie","géomètre","géranium","germe","gestuel","geyser","gibier","gicler","girafe","givre","glace","glaive","glisser","globe","gloire","glorieux","golfeur","gomme","gonfler","gorge","gorille","goudron","gouffre","goulot","goupille","gourmand","goutte","graduel","graffiti","graine","grand","grappin","gratuit","gravir","grenat","griffure","griller","grimper","grogner","gronder","grotte","groupe","gruger","grutier","gruyère","guépard","guerrier","guide","guimauve","guitare","gustatif","gymnaste","gyrostat","habitude","hachoir","halte","hameau","hangar","hanneton","haricot","harmonie","harpon","hasard","hélium","hématome","herbe","hérisson","hermine","héron","hésiter","heureux","hiberner","hibou","hilarant","histoire","hiver","homard","hommage","homogène","honneur","honorer","honteux","horde","horizon","horloge","hormone","horrible","houleux","housse","hublot","huileux","humain","humble","humide","humour","hurler","hydromel","hygiène","hymne","hypnose","idylle","ignorer","iguane","illicite","illusion","image","imbiber","imiter","immense","immobile","immuable","impact","impérial","implorer","imposer","imprimer","imputer","incarner","incendie","incident","incliner","incolore","indexer","indice","inductif","inédit","ineptie","inexact","infini","infliger","informer","infusion","ingérer","inhaler","inhiber","injecter","injure","innocent","inoculer","inonder","inscrire","insecte","insigne","insolite","inspirer","instinct","insulter","intact","intense","intime","intrigue","intuitif","inutile","invasion","inventer","inviter","invoquer","ironique","irradier","irréel","irriter","isoler","ivoire","ivresse","jaguar","jaillir","jambe","janvier","jardin","jauger","jaune","javelot","jetable","jeton","jeudi","jeunesse","joindre","joncher","jongler","joueur","jouissif","journal","jovial","joyau","joyeux","jubiler","jugement","junior","jupon","juriste","justice","juteux","juvénile","kayak","kimono","kiosque","label","labial","labourer","lacérer","lactose","lagune","laine","laisser","laitier","lambeau","lamelle","lampe","lanceur","langage","lanterne","lapin","largeur","larme","laurier","lavabo","lavoir","lecture","légal","léger","légume","lessive","lettre","levier","lexique","lézard","liasse","libérer","libre","licence","licorne","liège","lièvre","ligature","ligoter","ligue","limer","limite","limonade","limpide","linéaire","lingot","lionceau","liquide","lisière","lister","lithium","litige","littoral","livreur","logique","lointain","loisir","lombric","loterie","louer","lourd","loutre","louve","loyal","lubie","lucide","lucratif","lueur","lugubre","luisant","lumière","lunaire","lundi","luron","lutter","luxueux","machine","magasin","magenta","magique","maigre","maillon","maintien","mairie","maison","majorer","malaxer","maléfice","malheur","malice","mallette","mammouth","mandater","maniable","manquant","manteau","manuel","marathon","marbre","marchand","mardi","maritime","marqueur","marron","marteler","mascotte","massif","matériel","matière","matraque","maudire","maussade","mauve","maximal","méchant","méconnu","médaille","médecin","méditer","méduse","meilleur","mélange","mélodie","membre","mémoire","menacer","mener","menhir","mensonge","mentor","mercredi","mérite","merle","messager","mesure","métal","météore","méthode","métier","meuble","miauler","microbe","miette","mignon","migrer","milieu","million","mimique","mince","minéral","minimal","minorer","minute","miracle","miroiter","missile","mixte","mobile","moderne","moelleux","mondial","moniteur","monnaie","monotone","monstre","montagne","monument","moqueur","morceau","morsure","mortier","moteur","motif","mouche","moufle","moulin","mousson","mouton","mouvant","multiple","munition","muraille","murène","murmure","muscle","muséum","musicien","mutation","muter","mutuel","myriade","myrtille","mystère","mythique","nageur","nappe","narquois","narrer","natation","nation","nature","naufrage","nautique","navire","nébuleux","nectar","néfaste","négation","négliger","négocier","neige","nerveux","nettoyer","neurone","neutron","neveu","niche","nickel","nitrate","niveau","noble","nocif","nocturne","noirceur","noisette","nomade","nombreux","nommer","normatif","notable","notifier","notoire","nourrir","nouveau","novateur","novembre","novice","nuage","nuancer","nuire","nuisible","numéro","nuptial","nuque","nutritif","obéir","objectif","obliger","obscur","observer","obstacle","obtenir","obturer","occasion","occuper","océan","octobre","octroyer","octupler","oculaire","odeur","odorant","offenser","officier","offrir","ogive","oiseau","oisillon","olfactif","olivier","ombrage","omettre","onctueux","onduler","onéreux","onirique","opale","opaque","opérer","opinion","opportun","opprimer","opter","optique","orageux","orange","orbite","ordonner","oreille","organe","orgueil","orifice","ornement","orque","ortie","osciller","osmose","ossature","otarie","ouragan","ourson","outil","outrager","ouvrage","ovation","oxyde","oxygène","ozone","paisible","palace","palmarès","palourde","palper","panache","panda","pangolin","paniquer","panneau","panorama","pantalon","papaye","papier","papoter","papyrus","paradoxe","parcelle","paresse","parfumer","parler","parole","parrain","parsemer","partager","parure","parvenir","passion","pastèque","paternel","patience","patron","pavillon","pavoiser","payer","paysage","peigne","peintre","pelage","pélican","pelle","pelouse","peluche","pendule","pénétrer","pénible","pensif","pénurie","pépite","péplum","perdrix","perforer","période","permuter","perplexe","persil","perte","peser","pétale","petit","pétrir","peuple","pharaon","phobie","phoque","photon","phrase","physique","piano","pictural","pièce","pierre","pieuvre","pilote","pinceau","pipette","piquer","pirogue","piscine","piston","pivoter","pixel","pizza","placard","plafond","plaisir","planer","plaque","plastron","plateau","pleurer","plexus","pliage","plomb","plonger","pluie","plumage","pochette","poésie","poète","pointe","poirier","poisson","poivre","polaire","policier","pollen","polygone","pommade","pompier","ponctuel","pondérer","poney","portique","position","posséder","posture","potager","poteau","potion","pouce","poulain","poumon","pourpre","poussin","pouvoir","prairie","pratique","précieux","prédire","préfixe","prélude","prénom","présence","prétexte","prévoir","primitif","prince","prison","priver","problème","procéder","prodige","profond","progrès","proie","projeter","prologue","promener","propre","prospère","protéger","prouesse","proverbe","prudence","pruneau","psychose","public","puceron","puiser","pulpe","pulsar","punaise","punitif","pupitre","purifier","puzzle","pyramide","quasar","querelle","question","quiétude","quitter","quotient","racine","raconter","radieux","ragondin","raideur","raisin","ralentir","rallonge","ramasser","rapide","rasage","ratisser","ravager","ravin","rayonner","réactif","réagir","réaliser","réanimer","recevoir","réciter","réclamer","récolter","recruter","reculer","recycler","rédiger","redouter","refaire","réflexe","réformer","refrain","refuge","régalien","région","réglage","régulier","réitérer","rejeter","rejouer","relatif","relever","relief","remarque","remède","remise","remonter","remplir","remuer","renard","renfort","renifler","renoncer","rentrer","renvoi","replier","reporter","reprise","reptile","requin","réserve","résineux","résoudre","respect","rester","résultat","rétablir","retenir","réticule","retomber","retracer","réunion","réussir","revanche","revivre","révolte","révulsif","richesse","rideau","rieur","rigide","rigoler","rincer","riposter","risible","risque","rituel","rival","rivière","rocheux","romance","rompre","ronce","rondin","roseau","rosier","rotatif","rotor","rotule","rouge","rouille","rouleau","routine","royaume","ruban","rubis","ruche","ruelle","rugueux","ruiner","ruisseau","ruser","rustique","rythme","sabler","saboter","sabre","sacoche","safari","sagesse","saisir","salade","salive","salon","saluer","samedi","sanction","sanglier","sarcasme","sardine","saturer","saugrenu","saumon","sauter","sauvage","savant","savonner","scalpel","scandale","scélérat","scénario","sceptre","schéma","science","scinder","score","scrutin","sculpter","séance","sécable","sécher","secouer","sécréter","sédatif","séduire","seigneur","séjour","sélectif","semaine","sembler","semence","séminal","sénateur","sensible","sentence","séparer","séquence","serein","sergent","sérieux","serrure","sérum","service","sésame","sévir","sevrage","sextuple","sidéral","siècle","siéger","siffler","sigle","signal","silence","silicium","simple","sincère","sinistre","siphon","sirop","sismique","situer","skier","social","socle","sodium","soigneux","soldat","soleil","solitude","soluble","sombre","sommeil","somnoler","sonde","songeur","sonnette","sonore","sorcier","sortir","sosie","sottise","soucieux","soudure","souffle","soulever","soupape","source","soutirer","souvenir","spacieux","spatial","spécial","sphère","spiral","stable","station","sternum","stimulus","stipuler","strict","studieux","stupeur","styliste","sublime","substrat","subtil","subvenir","succès","sucre","suffixe","suggérer","suiveur","sulfate","superbe","supplier","surface","suricate","surmener","surprise","sursaut","survie","suspect","syllabe","symbole","symétrie","synapse","syntaxe","système","tabac","tablier","tactile","tailler","talent","talisman","talonner","tambour","tamiser","tangible","tapis","taquiner","tarder","tarif","tartine","tasse","tatami","tatouage","taupe","taureau","taxer","témoin","temporel","tenaille","tendre","teneur","tenir","tension","terminer","terne","terrible","tétine","texte","thème","théorie","thérapie","thorax","tibia","tiède","timide","tirelire","tiroir","tissu","titane","titre","tituber","toboggan","tolérant","tomate","tonique","tonneau","toponyme","torche","tordre","tornade","torpille","torrent","torse","tortue","totem","toucher","tournage","tousser","toxine","traction","trafic","tragique","trahir","train","trancher","travail","trèfle","tremper","trésor","treuil","triage","tribunal","tricoter","trilogie","triomphe","tripler","triturer","trivial","trombone","tronc","tropical","troupeau","tuile","tulipe","tumulte","tunnel","turbine","tuteur","tutoyer","tuyau","tympan","typhon","typique","tyran","ubuesque","ultime","ultrason","unanime","unifier","union","unique","unitaire","univers","uranium","urbain","urticant","usage","usine","usuel","usure","utile","utopie","vacarme","vaccin","vagabond","vague","vaillant","vaincre","vaisseau","valable","valise","vallon","valve","vampire","vanille","vapeur","varier","vaseux","vassal","vaste","vecteur","vedette","végétal","véhicule","veinard","véloce","vendredi","vénérer","venger","venimeux","ventouse","verdure","vérin","vernir","verrou","verser","vertu","veston","vétéran","vétuste","vexant","vexer","viaduc","viande","victoire","vidange","vidéo","vignette","vigueur","vilain","village","vinaigre","violon","vipère","virement","virtuose","virus","visage","viseur","vision","visqueux","visuel","vital","vitesse","viticole","vitrine","vivace","vivipare","vocation","voguer","voile","voisin","voiture","volaille","volcan","voltiger","volume","vorace","vortex","voter","vouloir","voyage","voyelle","wagon","xénon","yacht","zèbre","zénith","zeste","zoologie"]// note all JSON files in this folder are generated with npm run generate-wordlist
const lookup = require('./lookup.json')

module.exports = {
  loadWordlist,
  detectLanguage
}

function loadWordlist (language) {
  switch (language) {
    case 'chinese_simplified': return require('./chinese_simplified.json')
    case 'chinese_traditional': return require('./chinese_traditional.json')
    case 'czech': return require('./czech.json')
    case 'english': return require('./english.json')
    case 'french': return require('./french.json')
    case 'italian': return require('./italian.json')
    case 'japanese': return require('./japanese.json')
    case 'korean': return require('./korean.json')
    case 'portuguese': return require('./portuguese.json')
    case 'russian': return require('./russian.json')
    case 'spanish': return require('./spanish.json')
    case 'turkish': return require('./turkish.json')
  }

  throw new Error('Unknown language: ' + language)
}

function detectLanguage (words) {
  let candidate = null

  for (const word of words) {
    const languages = lookup[word]
    if (!languages) return null

    if (languages.length === 1) return languages[0]

    if (!candidate) {
      candidate = languages
      continue
    }

    const intersect = candidate.filter(l => languages.includes(l))
    if (intersect.length === 1) return intersect[0]
  }

  return candidate[0]
}
["abaco","abbaglio","abbinato","abete","abisso","abolire","abrasivo","abrogato","accadere","accenno","accusato","acetone","achille","acido","acqua","acre","acrilico","acrobata","acuto","adagio","addebito","addome","adeguato","aderire","adipe","adottare","adulare","affabile","affetto","affisso","affranto","aforisma","afoso","africano","agave","agente","agevole","aggancio","agire","agitare","agonismo","agricolo","agrumeto","aguzzo","alabarda","alato","albatro","alberato","albo","albume","alce","alcolico","alettone","alfa","algebra","aliante","alibi","alimento","allagato","allegro","allievo","allodola","allusivo","almeno","alogeno","alpaca","alpestre","altalena","alterno","alticcio","altrove","alunno","alveolo","alzare","amalgama","amanita","amarena","ambito","ambrato","ameba","america","ametista","amico","ammasso","ammenda","ammirare","ammonito","amore","ampio","ampliare","amuleto","anacardo","anagrafe","analista","anarchia","anatra","anca","ancella","ancora","andare","andrea","anello","angelo","angolare","angusto","anima","annegare","annidato","anno","annuncio","anonimo","anticipo","anzi","apatico","apertura","apode","apparire","appetito","appoggio","approdo","appunto","aprile","arabica","arachide","aragosta","araldica","arancio","aratura","arazzo","arbitro","archivio","ardito","arenile","argento","argine","arguto","aria","armonia","arnese","arredato","arringa","arrosto","arsenico","arso","artefice","arzillo","asciutto","ascolto","asepsi","asettico","asfalto","asino","asola","aspirato","aspro","assaggio","asse","assoluto","assurdo","asta","astenuto","astice","astratto","atavico","ateismo","atomico","atono","attesa","attivare","attorno","attrito","attuale","ausilio","austria","autista","autonomo","autunno","avanzato","avere","avvenire","avviso","avvolgere","azione","azoto","azzimo","azzurro","babele","baccano","bacino","baco","badessa","badilata","bagnato","baita","balcone","baldo","balena","ballata","balzano","bambino","bandire","baraonda","barbaro","barca","baritono","barlume","barocco","basilico","basso","batosta","battuto","baule","bava","bavosa","becco","beffa","belgio","belva","benda","benevole","benigno","benzina","bere","berlina","beta","bibita","bici","bidone","bifido","biga","bilancia","bimbo","binocolo","biologo","bipede","bipolare","birbante","birra","biscotto","bisesto","bisnonno","bisonte","bisturi","bizzarro","blando","blatta","bollito","bonifico","bordo","bosco","botanico","bottino","bozzolo","braccio","bradipo","brama","branca","bravura","bretella","brevetto","brezza","briglia","brillante","brindare","broccolo","brodo","bronzina","brullo","bruno","bubbone","buca","budino","buffone","buio","bulbo","buono","burlone","burrasca","bussola","busta","cadetto","caduco","calamaro","calcolo","calesse","calibro","calmo","caloria","cambusa","camerata","camicia","cammino","camola","campale","canapa","candela","cane","canino","canotto","cantina","capace","capello","capitolo","capogiro","cappero","capra","capsula","carapace","carcassa","cardo","carisma","carovana","carretto","cartolina","casaccio","cascata","caserma","caso","cassone","castello","casuale","catasta","catena","catrame","cauto","cavillo","cedibile","cedrata","cefalo","celebre","cellulare","cena","cenone","centesimo","ceramica","cercare","certo","cerume","cervello","cesoia","cespo","ceto","chela","chiaro","chicca","chiedere","chimera","china","chirurgo","chitarra","ciao","ciclismo","cifrare","cigno","cilindro","ciottolo","circa","cirrosi","citrico","cittadino","ciuffo","civetta","civile","classico","clinica","cloro","cocco","codardo","codice","coerente","cognome","collare","colmato","colore","colposo","coltivato","colza","coma","cometa","commando","comodo","computer","comune","conciso","condurre","conferma","congelare","coniuge","connesso","conoscere","consumo","continuo","convegno","coperto","copione","coppia","copricapo","corazza","cordata","coricato","cornice","corolla","corpo","corredo","corsia","cortese","cosmico","costante","cottura","covato","cratere","cravatta","creato","credere","cremoso","crescita","creta","criceto","crinale","crisi","critico","croce","cronaca","crostata","cruciale","crusca","cucire","cuculo","cugino","cullato","cupola","curatore","cursore","curvo","cuscino","custode","dado","daino","dalmata","damerino","daniela","dannoso","danzare","datato","davanti","davvero","debutto","decennio","deciso","declino","decollo","decreto","dedicato","definito","deforme","degno","delegare","delfino","delirio","delta","demenza","denotato","dentro","deposito","derapata","derivare","deroga","descritto","deserto","desiderio","desumere","detersivo","devoto","diametro","dicembre","diedro","difeso","diffuso","digerire","digitale","diluvio","dinamico","dinnanzi","dipinto","diploma","dipolo","diradare","dire","dirotto","dirupo","disagio","discreto","disfare","disgelo","disposto","distanza","disumano","dito","divano","divelto","dividere","divorato","doblone","docente","doganale","dogma","dolce","domato","domenica","dominare","dondolo","dono","dormire","dote","dottore","dovuto","dozzina","drago","druido","dubbio","dubitare","ducale","duna","duomo","duplice","duraturo","ebano","eccesso","ecco","eclissi","economia","edera","edicola","edile","editoria","educare","egemonia","egli","egoismo","egregio","elaborato","elargire","elegante","elencato","eletto","elevare","elfico","elica","elmo","elsa","eluso","emanato","emblema","emesso","emiro","emotivo","emozione","empirico","emulo","endemico","enduro","energia","enfasi","enoteca","entrare","enzima","epatite","epilogo","episodio","epocale","eppure","equatore","erario","erba","erboso","erede","eremita","erigere","ermetico","eroe","erosivo","errante","esagono","esame","esanime","esaudire","esca","esempio","esercito","esibito","esigente","esistere","esito","esofago","esortato","esoso","espanso","espresso","essenza","esso","esteso","estimare","estonia","estroso","esultare","etilico","etnico","etrusco","etto","euclideo","europa","evaso","evidenza","evitato","evoluto","evviva","fabbrica","faccenda","fachiro","falco","famiglia","fanale","fanfara","fango","fantasma","fare","farfalla","farinoso","farmaco","fascia","fastoso","fasullo","faticare","fato","favoloso","febbre","fecola","fede","fegato","felpa","feltro","femmina","fendere","fenomeno","fermento","ferro","fertile","fessura","festivo","fetta","feudo","fiaba","fiducia","fifa","figurato","filo","finanza","finestra","finire","fiore","fiscale","fisico","fiume","flacone","flamenco","flebo","flemma","florido","fluente","fluoro","fobico","focaccia","focoso","foderato","foglio","folata","folclore","folgore","fondente","fonetico","fonia","fontana","forbito","forchetta","foresta","formica","fornaio","foro","fortezza","forzare","fosfato","fosso","fracasso","frana","frassino","fratello","freccetta","frenata","fresco","frigo","frollino","fronde","frugale","frutta","fucilata","fucsia","fuggente","fulmine","fulvo","fumante","fumetto","fumoso","fune","funzione","fuoco","furbo","furgone","furore","fuso","futile","gabbiano","gaffe","galateo","gallina","galoppo","gambero","gamma","garanzia","garbo","garofano","garzone","gasdotto","gasolio","gastrico","gatto","gaudio","gazebo","gazzella","geco","gelatina","gelso","gemello","gemmato","gene","genitore","gennaio","genotipo","gergo","ghepardo","ghiaccio","ghisa","giallo","gilda","ginepro","giocare","gioiello","giorno","giove","girato","girone","gittata","giudizio","giurato","giusto","globulo","glutine","gnomo","gobba","golf","gomito","gommone","gonfio","gonna","governo","gracile","grado","grafico","grammo","grande","grattare","gravoso","grazia","greca","gregge","grifone","grigio","grinza","grotta","gruppo","guadagno","guaio","guanto","guardare","gufo","guidare","ibernato","icona","identico","idillio","idolo","idra","idrico","idrogeno","igiene","ignaro","ignorato","ilare","illeso","illogico","illudere","imballo","imbevuto","imbocco","imbuto","immane","immerso","immolato","impacco","impeto","impiego","importo","impronta","inalare","inarcare","inattivo","incanto","incendio","inchino","incisivo","incluso","incontro","incrocio","incubo","indagine","india","indole","inedito","infatti","infilare","inflitto","ingaggio","ingegno","inglese","ingordo","ingrosso","innesco","inodore","inoltrare","inondato","insano","insetto","insieme","insonnia","insulina","intasato","intero","intonaco","intuito","inumidire","invalido","invece","invito","iperbole","ipnotico","ipotesi","ippica","iride","irlanda","ironico","irrigato","irrorare","isolato","isotopo","isterico","istituto","istrice","italia","iterare","labbro","labirinto","lacca","lacerato","lacrima","lacuna","laddove","lago","lampo","lancetta","lanterna","lardoso","larga","laringe","lastra","latenza","latino","lattuga","lavagna","lavoro","legale","leggero","lembo","lentezza","lenza","leone","lepre","lesivo","lessato","lesto","letterale","leva","levigato","libero","lido","lievito","lilla","limatura","limitare","limpido","lineare","lingua","liquido","lira","lirica","lisca","lite","litigio","livrea","locanda","lode","logica","lombare","londra","longevo","loquace","lorenzo","loto","lotteria","luce","lucidato","lumaca","luminoso","lungo","lupo","luppolo","lusinga","lusso","lutto","macabro","macchina","macero","macinato","madama","magico","maglia","magnete","magro","maiolica","malafede","malgrado","malinteso","malsano","malto","malumore","mana","mancia","mandorla","mangiare","manifesto","mannaro","manovra","mansarda","mantide","manubrio","mappa","maratona","marcire","maretta","marmo","marsupio","maschera","massaia","mastino","materasso","matricola","mattone","maturo","mazurca","meandro","meccanico","mecenate","medesimo","meditare","mega","melassa","melis","melodia","meninge","meno","mensola","mercurio","merenda","merlo","meschino","mese","messere","mestolo","metallo","metodo","mettere","miagolare","mica","micelio","michele","microbo","midollo","miele","migliore","milano","milite","mimosa","minerale","mini","minore","mirino","mirtillo","miscela","missiva","misto","misurare","mitezza","mitigare","mitra","mittente","mnemonico","modello","modifica","modulo","mogano","mogio","mole","molosso","monastero","monco","mondina","monetario","monile","monotono","monsone","montato","monviso","mora","mordere","morsicato","mostro","motivato","motosega","motto","movenza","movimento","mozzo","mucca","mucosa","muffa","mughetto","mugnaio","mulatto","mulinello","multiplo","mummia","munto","muovere","murale","musa","muscolo","musica","mutevole","muto","nababbo","nafta","nanometro","narciso","narice","narrato","nascere","nastrare","naturale","nautica","naviglio","nebulosa","necrosi","negativo","negozio","nemmeno","neofita","neretto","nervo","nessuno","nettuno","neutrale","neve","nevrotico","nicchia","ninfa","nitido","nobile","nocivo","nodo","nome","nomina","nordico","normale","norvegese","nostrano","notare","notizia","notturno","novella","nucleo","nulla","numero","nuovo","nutrire","nuvola","nuziale","oasi","obbedire","obbligo","obelisco","oblio","obolo","obsoleto","occasione","occhio","occidente","occorrere","occultare","ocra","oculato","odierno","odorare","offerta","offrire","offuscato","oggetto","oggi","ognuno","olandese","olfatto","oliato","oliva","ologramma","oltre","omaggio","ombelico","ombra","omega","omissione","ondoso","onere","onice","onnivoro","onorevole","onta","operato","opinione","opposto","oracolo","orafo","ordine","orecchino","orefice","orfano","organico","origine","orizzonte","orma","ormeggio","ornativo","orologio","orrendo","orribile","ortensia","ortica","orzata","orzo","osare","oscurare","osmosi","ospedale","ospite","ossa","ossidare","ostacolo","oste","otite","otre","ottagono","ottimo","ottobre","ovale","ovest","ovino","oviparo","ovocito","ovunque","ovviare","ozio","pacchetto","pace","pacifico","padella","padrone","paese","paga","pagina","palazzina","palesare","pallido","palo","palude","pandoro","pannello","paolo","paonazzo","paprica","parabola","parcella","parere","pargolo","pari","parlato","parola","partire","parvenza","parziale","passivo","pasticca","patacca","patologia","pattume","pavone","peccato","pedalare","pedonale","peggio","peloso","penare","pendice","penisola","pennuto","penombra","pensare","pentola","pepe","pepita","perbene","percorso","perdonato","perforare","pergamena","periodo","permesso","perno","perplesso","persuaso","pertugio","pervaso","pesatore","pesista","peso","pestifero","petalo","pettine","petulante","pezzo","piacere","pianta","piattino","piccino","picozza","piega","pietra","piffero","pigiama","pigolio","pigro","pila","pilifero","pillola","pilota","pimpante","pineta","pinna","pinolo","pioggia","piombo","piramide","piretico","pirite","pirolisi","pitone","pizzico","placebo","planare","plasma","platano","plenario","pochezza","poderoso","podismo","poesia","poggiare","polenta","poligono","pollice","polmonite","polpetta","polso","poltrona","polvere","pomice","pomodoro","ponte","popoloso","porfido","poroso","porpora","porre","portata","posa","positivo","possesso","postulato","potassio","potere","pranzo","prassi","pratica","precluso","predica","prefisso","pregiato","prelievo","premere","prenotare","preparato","presenza","pretesto","prevalso","prima","principe","privato","problema","procura","produrre","profumo","progetto","prolunga","promessa","pronome","proposta","proroga","proteso","prova","prudente","prugna","prurito","psiche","pubblico","pudica","pugilato","pugno","pulce","pulito","pulsante","puntare","pupazzo","pupilla","puro","quadro","qualcosa","quasi","querela","quota","raccolto","raddoppio","radicale","radunato","raffica","ragazzo","ragione","ragno","ramarro","ramingo","ramo","randagio","rantolare","rapato","rapina","rappreso","rasatura","raschiato","rasente","rassegna","rastrello","rata","ravveduto","reale","recepire","recinto","recluta","recondito","recupero","reddito","redimere","regalato","registro","regola","regresso","relazione","remare","remoto","renna","replica","reprimere","reputare","resa","residente","responso","restauro","rete","retina","retorica","rettifica","revocato","riassunto","ribadire","ribelle","ribrezzo","ricarica","ricco","ricevere","riciclato","ricordo","ricreduto","ridicolo","ridurre","rifasare","riflesso","riforma","rifugio","rigare","rigettato","righello","rilassato","rilevato","rimanere","rimbalzo","rimedio","rimorchio","rinascita","rincaro","rinforzo","rinnovo","rinomato","rinsavito","rintocco","rinuncia","rinvenire","riparato","ripetuto","ripieno","riportare","ripresa","ripulire","risata","rischio","riserva","risibile","riso","rispetto","ristoro","risultato","risvolto","ritardo","ritegno","ritmico","ritrovo","riunione","riva","riverso","rivincita","rivolto","rizoma","roba","robotico","robusto","roccia","roco","rodaggio","rodere","roditore","rogito","rollio","romantico","rompere","ronzio","rosolare","rospo","rotante","rotondo","rotula","rovescio","rubizzo","rubrica","ruga","rullino","rumine","rumoroso","ruolo","rupe","russare","rustico","sabato","sabbiare","sabotato","sagoma","salasso","saldatura","salgemma","salivare","salmone","salone","saltare","saluto","salvo","sapere","sapido","saporito","saraceno","sarcasmo","sarto","sassoso","satellite","satira","satollo","saturno","savana","savio","saziato","sbadiglio","sbalzo","sbancato","sbarra","sbattere","sbavare","sbendare","sbirciare","sbloccato","sbocciato","sbrinare","sbruffone","sbuffare","scabroso","scadenza","scala","scambiare","scandalo","scapola","scarso","scatenare","scavato","scelto","scenico","scettro","scheda","schiena","sciarpa","scienza","scindere","scippo","sciroppo","scivolo","sclerare","scodella","scolpito","scomparto","sconforto","scoprire","scorta","scossone","scozzese","scriba","scrollare","scrutinio","scuderia","scultore","scuola","scuro","scusare","sdebitare","sdoganare","seccatura","secondo","sedano","seggiola","segnalato","segregato","seguito","selciato","selettivo","sella","selvaggio","semaforo","sembrare","seme","seminato","sempre","senso","sentire","sepolto","sequenza","serata","serbato","sereno","serio","serpente","serraglio","servire","sestina","setola","settimana","sfacelo","sfaldare","sfamato","sfarzoso","sfaticato","sfera","sfida","sfilato","sfinge","sfocato","sfoderare","sfogo","sfoltire","sforzato","sfratto","sfruttato","sfuggito","sfumare","sfuso","sgabello","sgarbato","sgonfiare","sgorbio","sgrassato","sguardo","sibilo","siccome","sierra","sigla","signore","silenzio","sillaba","simbolo","simpatico","simulato","sinfonia","singolo","sinistro","sino","sintesi","sinusoide","sipario","sisma","sistole","situato","slitta","slogatura","sloveno","smarrito","smemorato","smentito","smeraldo","smilzo","smontare","smottato","smussato","snellire","snervato","snodo","sobbalzo","sobrio","soccorso","sociale","sodale","soffitto","sogno","soldato","solenne","solido","sollazzo","solo","solubile","solvente","somatico","somma","sonda","sonetto","sonnifero","sopire","soppeso","sopra","sorgere","sorpasso","sorriso","sorso","sorteggio","sorvolato","sospiro","sosta","sottile","spada","spalla","spargere","spatola","spavento","spazzola","specie","spedire","spegnere","spelatura","speranza","spessore","spettrale","spezzato","spia","spigoloso","spillato","spinoso","spirale","splendido","sportivo","sposo","spranga","sprecare","spronato","spruzzo","spuntino","squillo","sradicare","srotolato","stabile","stacco","staffa","stagnare","stampato","stantio","starnuto","stasera","statuto","stelo","steppa","sterzo","stiletto","stima","stirpe","stivale","stizzoso","stonato","storico","strappo","stregato","stridulo","strozzare","strutto","stuccare","stufo","stupendo","subentro","succoso","sudore","suggerito","sugo","sultano","suonare","superbo","supporto","surgelato","surrogato","sussurro","sutura","svagare","svedese","sveglio","svelare","svenuto","svezia","sviluppo","svista","svizzera","svolta","svuotare","tabacco","tabulato","tacciare","taciturno","tale","talismano","tampone","tannino","tara","tardivo","targato","tariffa","tarpare","tartaruga","tasto","tattico","taverna","tavolata","tazza","teca","tecnico","telefono","temerario","tempo","temuto","tendone","tenero","tensione","tentacolo","teorema","terme","terrazzo","terzetto","tesi","tesserato","testato","tetro","tettoia","tifare","tigella","timbro","tinto","tipico","tipografo","tiraggio","tiro","titanio","titolo","titubante","tizio","tizzone","toccare","tollerare","tolto","tombola","tomo","tonfo","tonsilla","topazio","topologia","toppa","torba","tornare","torrone","tortora","toscano","tossire","tostatura","totano","trabocco","trachea","trafila","tragedia","tralcio","tramonto","transito","trapano","trarre","trasloco","trattato","trave","treccia","tremolio","trespolo","tributo","tricheco","trifoglio","trillo","trincea","trio","tristezza","triturato","trivella","tromba","trono","troppo","trottola","trovare","truccato","tubatura","tuffato","tulipano","tumulto","tunisia","turbare","turchino","tuta","tutela","ubicato","uccello","uccisore","udire","uditivo","uffa","ufficio","uguale","ulisse","ultimato","umano","umile","umorismo","uncinetto","ungere","ungherese","unicorno","unificato","unisono","unitario","unte","uovo","upupa","uragano","urgenza","urlo","usanza","usato","uscito","usignolo","usuraio","utensile","utilizzo","utopia","vacante","vaccinato","vagabondo","vagliato","valanga","valgo","valico","valletta","valoroso","valutare","valvola","vampata","vangare","vanitoso","vano","vantaggio","vanvera","vapore","varano","varcato","variante","vasca","vedetta","vedova","veduto","vegetale","veicolo","velcro","velina","velluto","veloce","venato","vendemmia","vento","verace","verbale","vergogna","verifica","vero","verruca","verticale","vescica","vessillo","vestale","veterano","vetrina","vetusto","viandante","vibrante","vicenda","vichingo","vicinanza","vidimare","vigilia","vigneto","vigore","vile","villano","vimini","vincitore","viola","vipera","virgola","virologo","virulento","viscoso","visione","vispo","vissuto","visura","vita","vitello","vittima","vivanda","vivido","viziare","voce","voga","volatile","volere","volpe","voragine","vulcano","zampogna","zanna","zappato","zattera","zavorra","zefiro","zelante","zelo","zenzero","zerbino","zibetto","zinco","zircone","zitto","zolla","zotico","zucchero","zufolo","zulu","zuppa"]["あいこくしん","あいさつ","あいだ","あおぞら","あかちゃん","あきる","あけがた","あける","あこがれる","あさい","あさひ","あしあと","あじわう","あずかる","あずき","あそぶ","あたえる","あたためる","あたりまえ","あたる","あつい","あつかう","あっしゅく","あつまり","あつめる","あてな","あてはまる","あひる","あぶら","あぶる","あふれる","あまい","あまど","あまやかす","あまり","あみもの","あめりか","あやまる","あゆむ","あらいぐま","あらし","あらすじ","あらためる","あらゆる","あらわす","ありがとう","あわせる","あわてる","あんい","あんがい","あんこ","あんぜん","あんてい","あんない","あんまり","いいだす","いおん","いがい","いがく","いきおい","いきなり","いきもの","いきる","いくじ","いくぶん","いけばな","いけん","いこう","いこく","いこつ","いさましい","いさん","いしき","いじゅう","いじょう","いじわる","いずみ","いずれ","いせい","いせえび","いせかい","いせき","いぜん","いそうろう","いそがしい","いだい","いだく","いたずら","いたみ","いたりあ","いちおう","いちじ","いちど","いちば","いちぶ","いちりゅう","いつか","いっしゅん","いっせい","いっそう","いったん","いっち","いってい","いっぽう","いてざ","いてん","いどう","いとこ","いない","いなか","いねむり","いのち","いのる","いはつ","いばる","いはん","いびき","いひん","いふく","いへん","いほう","いみん","いもうと","いもたれ","いもり","いやがる","いやす","いよかん","いよく","いらい","いらすと","いりぐち","いりょう","いれい","いれもの","いれる","いろえんぴつ","いわい","いわう","いわかん","いわば","いわゆる","いんげんまめ","いんさつ","いんしょう","いんよう","うえき","うえる","うおざ","うがい","うかぶ","うかべる","うきわ","うくらいな","うくれれ","うけたまわる","うけつけ","うけとる","うけもつ","うける","うごかす","うごく","うこん","うさぎ","うしなう","うしろがみ","うすい","うすぎ","うすぐらい","うすめる","うせつ","うちあわせ","うちがわ","うちき","うちゅう","うっかり","うつくしい","うったえる","うつる","うどん","うなぎ","うなじ","うなずく","うなる","うねる","うのう","うぶげ","うぶごえ","うまれる","うめる","うもう","うやまう","うよく","うらがえす","うらぐち","うらない","うりあげ","うりきれ","うるさい","うれしい","うれゆき","うれる","うろこ","うわき","うわさ","うんこう","うんちん","うんてん","うんどう","えいえん","えいが","えいきょう","えいご","えいせい","えいぶん","えいよう","えいわ","えおり","えがお","えがく","えきたい","えくせる","えしゃく","えすて","えつらん","えのぐ","えほうまき","えほん","えまき","えもじ","えもの","えらい","えらぶ","えりあ","えんえん","えんかい","えんぎ","えんげき","えんしゅう","えんぜつ","えんそく","えんちょう","えんとつ","おいかける","おいこす","おいしい","おいつく","おうえん","おうさま","おうじ","おうせつ","おうたい","おうふく","おうべい","おうよう","おえる","おおい","おおう","おおどおり","おおや","おおよそ","おかえり","おかず","おがむ","おかわり","おぎなう","おきる","おくさま","おくじょう","おくりがな","おくる","おくれる","おこす","おこなう","おこる","おさえる","おさない","おさめる","おしいれ","おしえる","おじぎ","おじさん","おしゃれ","おそらく","おそわる","おたがい","おたく","おだやか","おちつく","おっと","おつり","おでかけ","おとしもの","おとなしい","おどり","おどろかす","おばさん","おまいり","おめでとう","おもいで","おもう","おもたい","おもちゃ","おやつ","おやゆび","およぼす","おらんだ","おろす","おんがく","おんけい","おんしゃ","おんせん","おんだん","おんちゅう","おんどけい","かあつ","かいが","がいき","がいけん","がいこう","かいさつ","かいしゃ","かいすいよく","かいぜん","かいぞうど","かいつう","かいてん","かいとう","かいふく","がいへき","かいほう","かいよう","がいらい","かいわ","かえる","かおり","かかえる","かがく","かがし","かがみ","かくご","かくとく","かざる","がぞう","かたい","かたち","がちょう","がっきゅう","がっこう","がっさん","がっしょう","かなざわし","かのう","がはく","かぶか","かほう","かほご","かまう","かまぼこ","かめれおん","かゆい","かようび","からい","かるい","かろう","かわく","かわら","がんか","かんけい","かんこう","かんしゃ","かんそう","かんたん","かんち","がんばる","きあい","きあつ","きいろ","ぎいん","きうい","きうん","きえる","きおう","きおく","きおち","きおん","きかい","きかく","きかんしゃ","ききて","きくばり","きくらげ","きけんせい","きこう","きこえる","きこく","きさい","きさく","きさま","きさらぎ","ぎじかがく","ぎしき","ぎじたいけん","ぎじにってい","ぎじゅつしゃ","きすう","きせい","きせき","きせつ","きそう","きぞく","きぞん","きたえる","きちょう","きつえん","ぎっちり","きつつき","きつね","きてい","きどう","きどく","きない","きなが","きなこ","きぬごし","きねん","きのう","きのした","きはく","きびしい","きひん","きふく","きぶん","きぼう","きほん","きまる","きみつ","きむずかしい","きめる","きもだめし","きもち","きもの","きゃく","きやく","ぎゅうにく","きよう","きょうりゅう","きらい","きらく","きりん","きれい","きれつ","きろく","ぎろん","きわめる","ぎんいろ","きんかくじ","きんじょ","きんようび","ぐあい","くいず","くうかん","くうき","くうぐん","くうこう","ぐうせい","くうそう","ぐうたら","くうふく","くうぼ","くかん","くきょう","くげん","ぐこう","くさい","くさき","くさばな","くさる","くしゃみ","くしょう","くすのき","くすりゆび","くせげ","くせん","ぐたいてき","くださる","くたびれる","くちこみ","くちさき","くつした","ぐっすり","くつろぐ","くとうてん","くどく","くなん","くねくね","くのう","くふう","くみあわせ","くみたてる","くめる","くやくしょ","くらす","くらべる","くるま","くれる","くろう","くわしい","ぐんかん","ぐんしょく","ぐんたい","ぐんて","けあな","けいかく","けいけん","けいこ","けいさつ","げいじゅつ","けいたい","げいのうじん","けいれき","けいろ","けおとす","けおりもの","げきか","げきげん","げきだん","げきちん","げきとつ","げきは","げきやく","げこう","げこくじょう","げざい","けさき","げざん","けしき","けしごむ","けしょう","げすと","けたば","けちゃっぷ","けちらす","けつあつ","けつい","けつえき","けっこん","けつじょ","けっせき","けってい","けつまつ","げつようび","げつれい","けつろん","げどく","けとばす","けとる","けなげ","けなす","けなみ","けぬき","げねつ","けねん","けはい","げひん","けぶかい","げぼく","けまり","けみかる","けむし","けむり","けもの","けらい","けろけろ","けわしい","けんい","けんえつ","けんお","けんか","げんき","けんげん","けんこう","けんさく","けんしゅう","けんすう","げんそう","けんちく","けんてい","けんとう","けんない","けんにん","げんぶつ","けんま","けんみん","けんめい","けんらん","けんり","こあくま","こいぬ","こいびと","ごうい","こうえん","こうおん","こうかん","ごうきゅう","ごうけい","こうこう","こうさい","こうじ","こうすい","ごうせい","こうそく","こうたい","こうちゃ","こうつう","こうてい","こうどう","こうない","こうはい","ごうほう","ごうまん","こうもく","こうりつ","こえる","こおり","ごかい","ごがつ","ごかん","こくご","こくさい","こくとう","こくない","こくはく","こぐま","こけい","こける","ここのか","こころ","こさめ","こしつ","こすう","こせい","こせき","こぜん","こそだて","こたい","こたえる","こたつ","こちょう","こっか","こつこつ","こつばん","こつぶ","こてい","こてん","ことがら","ことし","ことば","ことり","こなごな","こねこね","このまま","このみ","このよ","ごはん","こひつじ","こふう","こふん","こぼれる","ごまあぶら","こまかい","ごますり","こまつな","こまる","こむぎこ","こもじ","こもち","こもの","こもん","こやく","こやま","こゆう","こゆび","こよい","こよう","こりる","これくしょん","ころっけ","こわもて","こわれる","こんいん","こんかい","こんき","こんしゅう","こんすい","こんだて","こんとん","こんなん","こんびに","こんぽん","こんまけ","こんや","こんれい","こんわく","ざいえき","さいかい","さいきん","ざいげん","ざいこ","さいしょ","さいせい","ざいたく","ざいちゅう","さいてき","ざいりょう","さうな","さかいし","さがす","さかな","さかみち","さがる","さぎょう","さくし","さくひん","さくら","さこく","さこつ","さずかる","ざせき","さたん","さつえい","ざつおん","ざっか","ざつがく","さっきょく","ざっし","さつじん","ざっそう","さつたば","さつまいも","さてい","さといも","さとう","さとおや","さとし","さとる","さのう","さばく","さびしい","さべつ","さほう","さほど","さます","さみしい","さみだれ","さむけ","さめる","さやえんどう","さゆう","さよう","さよく","さらだ","ざるそば","さわやか","さわる","さんいん","さんか","さんきゃく","さんこう","さんさい","ざんしょ","さんすう","さんせい","さんそ","さんち","さんま","さんみ","さんらん","しあい","しあげ","しあさって","しあわせ","しいく","しいん","しうち","しえい","しおけ","しかい","しかく","じかん","しごと","しすう","じだい","したうけ","したぎ","したて","したみ","しちょう","しちりん","しっかり","しつじ","しつもん","してい","してき","してつ","じてん","じどう","しなぎれ","しなもの","しなん","しねま","しねん","しのぐ","しのぶ","しはい","しばかり","しはつ","しはらい","しはん","しひょう","しふく","じぶん","しへい","しほう","しほん","しまう","しまる","しみん","しむける","じむしょ","しめい","しめる","しもん","しゃいん","しゃうん","しゃおん","じゃがいも","しやくしょ","しゃくほう","しゃけん","しゃこ","しゃざい","しゃしん","しゃせん","しゃそう","しゃたい","しゃちょう","しゃっきん","じゃま","しゃりん","しゃれい","じゆう","じゅうしょ","しゅくはく","じゅしん","しゅっせき","しゅみ","しゅらば","じゅんばん","しょうかい","しょくたく","しょっけん","しょどう","しょもつ","しらせる","しらべる","しんか","しんこう","じんじゃ","しんせいじ","しんちく","しんりん","すあげ","すあし","すあな","ずあん","すいえい","すいか","すいとう","ずいぶん","すいようび","すうがく","すうじつ","すうせん","すおどり","すきま","すくう","すくない","すける","すごい","すこし","ずさん","すずしい","すすむ","すすめる","すっかり","ずっしり","ずっと","すてき","すてる","すねる","すのこ","すはだ","すばらしい","ずひょう","ずぶぬれ","すぶり","すふれ","すべて","すべる","ずほう","すぼん","すまい","すめし","すもう","すやき","すらすら","するめ","すれちがう","すろっと","すわる","すんぜん","すんぽう","せあぶら","せいかつ","せいげん","せいじ","せいよう","せおう","せかいかん","せきにん","せきむ","せきゆ","せきらんうん","せけん","せこう","せすじ","せたい","せたけ","せっかく","せっきゃく","ぜっく","せっけん","せっこつ","せっさたくま","せつぞく","せつだん","せつでん","せっぱん","せつび","せつぶん","せつめい","せつりつ","せなか","せのび","せはば","せびろ","せぼね","せまい","せまる","せめる","せもたれ","せりふ","ぜんあく","せんい","せんえい","せんか","せんきょ","せんく","せんげん","ぜんご","せんさい","せんしゅ","せんすい","せんせい","せんぞ","せんたく","せんちょう","せんてい","せんとう","せんぬき","せんねん","せんぱい","ぜんぶ","ぜんぽう","せんむ","せんめんじょ","せんもん","せんやく","せんゆう","せんよう","ぜんら","ぜんりゃく","せんれい","せんろ","そあく","そいとげる","そいね","そうがんきょう","そうき","そうご","そうしん","そうだん","そうなん","そうび","そうめん","そうり","そえもの","そえん","そがい","そげき","そこう","そこそこ","そざい","そしな","そせい","そせん","そそぐ","そだてる","そつう","そつえん","そっかん","そつぎょう","そっけつ","そっこう","そっせん","そっと","そとがわ","そとづら","そなえる","そなた","そふぼ","そぼく","そぼろ","そまつ","そまる","そむく","そむりえ","そめる","そもそも","そよかぜ","そらまめ","そろう","そんかい","そんけい","そんざい","そんしつ","そんぞく","そんちょう","ぞんび","ぞんぶん","そんみん","たあい","たいいん","たいうん","たいえき","たいおう","だいがく","たいき","たいぐう","たいけん","たいこ","たいざい","だいじょうぶ","だいすき","たいせつ","たいそう","だいたい","たいちょう","たいてい","だいどころ","たいない","たいねつ","たいのう","たいはん","だいひょう","たいふう","たいへん","たいほ","たいまつばな","たいみんぐ","たいむ","たいめん","たいやき","たいよう","たいら","たいりょく","たいる","たいわん","たうえ","たえる","たおす","たおる","たおれる","たかい","たかね","たきび","たくさん","たこく","たこやき","たさい","たしざん","だじゃれ","たすける","たずさわる","たそがれ","たたかう","たたく","ただしい","たたみ","たちばな","だっかい","だっきゃく","だっこ","だっしゅつ","だったい","たてる","たとえる","たなばた","たにん","たぬき","たのしみ","たはつ","たぶん","たべる","たぼう","たまご","たまる","だむる","ためいき","ためす","ためる","たもつ","たやすい","たよる","たらす","たりきほんがん","たりょう","たりる","たると","たれる","たれんと","たろっと","たわむれる","だんあつ","たんい","たんおん","たんか","たんき","たんけん","たんご","たんさん","たんじょうび","だんせい","たんそく","たんたい","だんち","たんてい","たんとう","だんな","たんにん","だんねつ","たんのう","たんぴん","だんぼう","たんまつ","たんめい","だんれつ","だんろ","だんわ","ちあい","ちあん","ちいき","ちいさい","ちえん","ちかい","ちから","ちきゅう","ちきん","ちけいず","ちけん","ちこく","ちさい","ちしき","ちしりょう","ちせい","ちそう","ちたい","ちたん","ちちおや","ちつじょ","ちてき","ちてん","ちぬき","ちぬり","ちのう","ちひょう","ちへいせん","ちほう","ちまた","ちみつ","ちみどろ","ちめいど","ちゃんこなべ","ちゅうい","ちゆりょく","ちょうし","ちょさくけん","ちらし","ちらみ","ちりがみ","ちりょう","ちるど","ちわわ","ちんたい","ちんもく","ついか","ついたち","つうか","つうじょう","つうはん","つうわ","つかう","つかれる","つくね","つくる","つけね","つける","つごう","つたえる","つづく","つつじ","つつむ","つとめる","つながる","つなみ","つねづね","つのる","つぶす","つまらない","つまる","つみき","つめたい","つもり","つもる","つよい","つるぼ","つるみく","つわもの","つわり","てあし","てあて","てあみ","ていおん","ていか","ていき","ていけい","ていこく","ていさつ","ていし","ていせい","ていたい","ていど","ていねい","ていひょう","ていへん","ていぼう","てうち","ておくれ","てきとう","てくび","でこぼこ","てさぎょう","てさげ","てすり","てそう","てちがい","てちょう","てつがく","てつづき","でっぱ","てつぼう","てつや","でぬかえ","てぬき","てぬぐい","てのひら","てはい","てぶくろ","てふだ","てほどき","てほん","てまえ","てまきずし","てみじか","てみやげ","てらす","てれび","てわけ","てわたし","でんあつ","てんいん","てんかい","てんき","てんぐ","てんけん","てんごく","てんさい","てんし","てんすう","でんち","てんてき","てんとう","てんない","てんぷら","てんぼうだい","てんめつ","てんらんかい","でんりょく","でんわ","どあい","といれ","どうかん","とうきゅう","どうぐ","とうし","とうむぎ","とおい","とおか","とおく","とおす","とおる","とかい","とかす","ときおり","ときどき","とくい","とくしゅう","とくてん","とくに","とくべつ","とけい","とける","とこや","とさか","としょかん","とそう","とたん","とちゅう","とっきゅう","とっくん","とつぜん","とつにゅう","とどける","ととのえる","とない","となえる","となり","とのさま","とばす","どぶがわ","とほう","とまる","とめる","ともだち","ともる","どようび","とらえる","とんかつ","どんぶり","ないかく","ないこう","ないしょ","ないす","ないせん","ないそう","なおす","ながい","なくす","なげる","なこうど","なさけ","なたでここ","なっとう","なつやすみ","ななおし","なにごと","なにもの","なにわ","なのか","なふだ","なまいき","なまえ","なまみ","なみだ","なめらか","なめる","なやむ","ならう","ならび","ならぶ","なれる","なわとび","なわばり","にあう","にいがた","にうけ","におい","にかい","にがて","にきび","にくしみ","にくまん","にげる","にさんかたんそ","にしき","にせもの","にちじょう","にちようび","にっか","にっき","にっけい","にっこう","にっさん","にっしょく","にっすう","にっせき","にってい","になう","にほん","にまめ","にもつ","にやり","にゅういん","にりんしゃ","にわとり","にんい","にんか","にんき","にんげん","にんしき","にんずう","にんそう","にんたい","にんち","にんてい","にんにく","にんぷ","にんまり","にんむ","にんめい","にんよう","ぬいくぎ","ぬかす","ぬぐいとる","ぬぐう","ぬくもり","ぬすむ","ぬまえび","ぬめり","ぬらす","ぬんちゃく","ねあげ","ねいき","ねいる","ねいろ","ねぐせ","ねくたい","ねくら","ねこぜ","ねこむ","ねさげ","ねすごす","ねそべる","ねだん","ねつい","ねっしん","ねつぞう","ねったいぎょ","ねぶそく","ねふだ","ねぼう","ねほりはほり","ねまき","ねまわし","ねみみ","ねむい","ねむたい","ねもと","ねらう","ねわざ","ねんいり","ねんおし","ねんかん","ねんきん","ねんぐ","ねんざ","ねんし","ねんちゃく","ねんど","ねんぴ","ねんぶつ","ねんまつ","ねんりょう","ねんれい","のいず","のおづま","のがす","のきなみ","のこぎり","のこす","のこる","のせる","のぞく","のぞむ","のたまう","のちほど","のっく","のばす","のはら","のべる","のぼる","のみもの","のやま","のらいぬ","のらねこ","のりもの","のりゆき","のれん","のんき","ばあい","はあく","ばあさん","ばいか","ばいく","はいけん","はいご","はいしん","はいすい","はいせん","はいそう","はいち","ばいばい","はいれつ","はえる","はおる","はかい","ばかり","はかる","はくしゅ","はけん","はこぶ","はさみ","はさん","はしご","ばしょ","はしる","はせる","ぱそこん","はそん","はたん","はちみつ","はつおん","はっかく","はづき","はっきり","はっくつ","はっけん","はっこう","はっさん","はっしん","はったつ","はっちゅう","はってん","はっぴょう","はっぽう","はなす","はなび","はにかむ","はぶらし","はみがき","はむかう","はめつ","はやい","はやし","はらう","はろうぃん","はわい","はんい","はんえい","はんおん","はんかく","はんきょう","ばんぐみ","はんこ","はんしゃ","はんすう","はんだん","ぱんち","ぱんつ","はんてい","はんとし","はんのう","はんぱ","はんぶん","はんぺん","はんぼうき","はんめい","はんらん","はんろん","ひいき","ひうん","ひえる","ひかく","ひかり","ひかる","ひかん","ひくい","ひけつ","ひこうき","ひこく","ひさい","ひさしぶり","ひさん","びじゅつかん","ひしょ","ひそか","ひそむ","ひたむき","ひだり","ひたる","ひつぎ","ひっこし","ひっし","ひつじゅひん","ひっす","ひつぜん","ぴったり","ぴっちり","ひつよう","ひてい","ひとごみ","ひなまつり","ひなん","ひねる","ひはん","ひびく","ひひょう","ひほう","ひまわり","ひまん","ひみつ","ひめい","ひめじし","ひやけ","ひやす","ひよう","びょうき","ひらがな","ひらく","ひりつ","ひりょう","ひるま","ひるやすみ","ひれい","ひろい","ひろう","ひろき","ひろゆき","ひんかく","ひんけつ","ひんこん","ひんしゅ","ひんそう","ぴんち","ひんぱん","びんぼう","ふあん","ふいうち","ふうけい","ふうせん","ぷうたろう","ふうとう","ふうふ","ふえる","ふおん","ふかい","ふきん","ふくざつ","ふくぶくろ","ふこう","ふさい","ふしぎ","ふじみ","ふすま","ふせい","ふせぐ","ふそく","ぶたにく","ふたん","ふちょう","ふつう","ふつか","ふっかつ","ふっき","ふっこく","ぶどう","ふとる","ふとん","ふのう","ふはい","ふひょう","ふへん","ふまん","ふみん","ふめつ","ふめん","ふよう","ふりこ","ふりる","ふるい","ふんいき","ぶんがく","ぶんぐ","ふんしつ","ぶんせき","ふんそう","ぶんぽう","へいあん","へいおん","へいがい","へいき","へいげん","へいこう","へいさ","へいしゃ","へいせつ","へいそ","へいたく","へいてん","へいねつ","へいわ","へきが","へこむ","べにいろ","べにしょうが","へらす","へんかん","べんきょう","べんごし","へんさい","へんたい","べんり","ほあん","ほいく","ぼうぎょ","ほうこく","ほうそう","ほうほう","ほうもん","ほうりつ","ほえる","ほおん","ほかん","ほきょう","ぼきん","ほくろ","ほけつ","ほけん","ほこう","ほこる","ほしい","ほしつ","ほしゅ","ほしょう","ほせい","ほそい","ほそく","ほたて","ほたる","ぽちぶくろ","ほっきょく","ほっさ","ほったん","ほとんど","ほめる","ほんい","ほんき","ほんけ","ほんしつ","ほんやく","まいにち","まかい","まかせる","まがる","まける","まこと","まさつ","まじめ","ますく","まぜる","まつり","まとめ","まなぶ","まぬけ","まねく","まほう","まもる","まゆげ","まよう","まろやか","まわす","まわり","まわる","まんが","まんきつ","まんぞく","まんなか","みいら","みうち","みえる","みがく","みかた","みかん","みけん","みこん","みじかい","みすい","みすえる","みせる","みっか","みつかる","みつける","みてい","みとめる","みなと","みなみかさい","みねらる","みのう","みのがす","みほん","みもと","みやげ","みらい","みりょく","みわく","みんか","みんぞく","むいか","むえき","むえん","むかい","むかう","むかえ","むかし","むぎちゃ","むける","むげん","むさぼる","むしあつい","むしば","むじゅん","むしろ","むすう","むすこ","むすぶ","むすめ","むせる","むせん","むちゅう","むなしい","むのう","むやみ","むよう","むらさき","むりょう","むろん","めいあん","めいうん","めいえん","めいかく","めいきょく","めいさい","めいし","めいそう","めいぶつ","めいれい","めいわく","めぐまれる","めざす","めした","めずらしい","めだつ","めまい","めやす","めんきょ","めんせき","めんどう","もうしあげる","もうどうけん","もえる","もくし","もくてき","もくようび","もちろん","もどる","もらう","もんく","もんだい","やおや","やける","やさい","やさしい","やすい","やすたろう","やすみ","やせる","やそう","やたい","やちん","やっと","やっぱり","やぶる","やめる","ややこしい","やよい","やわらかい","ゆうき","ゆうびんきょく","ゆうべ","ゆうめい","ゆけつ","ゆしゅつ","ゆせん","ゆそう","ゆたか","ゆちゃく","ゆでる","ゆにゅう","ゆびわ","ゆらい","ゆれる","ようい","ようか","ようきゅう","ようじ","ようす","ようちえん","よかぜ","よかん","よきん","よくせい","よくぼう","よけい","よごれる","よさん","よしゅう","よそう","よそく","よっか","よてい","よどがわく","よねつ","よやく","よゆう","よろこぶ","よろしい","らいう","らくがき","らくご","らくさつ","らくだ","らしんばん","らせん","らぞく","らたい","らっか","られつ","りえき","りかい","りきさく","りきせつ","りくぐん","りくつ","りけん","りこう","りせい","りそう","りそく","りてん","りねん","りゆう","りゅうがく","りよう","りょうり","りょかん","りょくちゃ","りょこう","りりく","りれき","りろん","りんご","るいけい","るいさい","るいじ","るいせき","るすばん","るりがわら","れいかん","れいぎ","れいせい","れいぞうこ","れいとう","れいぼう","れきし","れきだい","れんあい","れんけい","れんこん","れんさい","れんしゅう","れんぞく","れんらく","ろうか","ろうご","ろうじん","ろうそく","ろくが","ろこつ","ろじうら","ろしゅつ","ろせん","ろてん","ろめん","ろれつ","ろんぎ","ろんぱ","ろんぶん","ろんり","わかす","わかめ","わかやま","わかれる","わしつ","わじまし","わすれもの","わらう","われる"]["가격","가끔","가난","가능","가득","가르침","가뭄","가방","가상","가슴","가운데","가을","가이드","가입","가장","가정","가족","가죽","각오","각자","간격","간부","간섭","간장","간접","간판","갈등","갈비","갈색","갈증","감각","감기","감소","감수성","감자","감정","갑자기","강남","강당","강도","강력히","강변","강북","강사","강수량","강아지","강원도","강의","강제","강조","같이","개구리","개나리","개방","개별","개선","개성","개인","객관적","거실","거액","거울","거짓","거품","걱정","건강","건물","건설","건조","건축","걸음","검사","검토","게시판","게임","겨울","견해","결과","결국","결론","결석","결승","결심","결정","결혼","경계","경고","경기","경력","경복궁","경비","경상도","경영","경우","경쟁","경제","경주","경찰","경치","경향","경험","계곡","계단","계란","계산","계속","계약","계절","계층","계획","고객","고구려","고궁","고급","고등학생","고무신","고민","고양이","고장","고전","고집","고춧가루","고통","고향","곡식","골목","골짜기","골프","공간","공개","공격","공군","공급","공기","공동","공무원","공부","공사","공식","공업","공연","공원","공장","공짜","공책","공통","공포","공항","공휴일","과목","과일","과장","과정","과학","관객","관계","관광","관념","관람","관련","관리","관습","관심","관점","관찰","광경","광고","광장","광주","괴로움","굉장히","교과서","교문","교복","교실","교양","교육","교장","교직","교통","교환","교훈","구경","구름","구멍","구별","구분","구석","구성","구속","구역","구입","구청","구체적","국가","국기","국내","국립","국물","국민","국수","국어","국왕","국적","국제","국회","군대","군사","군인","궁극적","권리","권위","권투","귀국","귀신","규정","규칙","균형","그날","그냥","그늘","그러나","그룹","그릇","그림","그제서야","그토록","극복","극히","근거","근교","근래","근로","근무","근본","근원","근육","근처","글씨","글자","금강산","금고","금년","금메달","금액","금연","금요일","금지","긍정적","기간","기관","기념","기능","기독교","기둥","기록","기름","기법","기본","기분","기쁨","기숙사","기술","기억","기업","기온","기운","기원","기적","기준","기침","기혼","기획","긴급","긴장","길이","김밥","김치","김포공항","깍두기","깜빡","깨달음","깨소금","껍질","꼭대기","꽃잎","나들이","나란히","나머지","나물","나침반","나흘","낙엽","난방","날개","날씨","날짜","남녀","남대문","남매","남산","남자","남편","남학생","낭비","낱말","내년","내용","내일","냄비","냄새","냇물","냉동","냉면","냉방","냉장고","넥타이","넷째","노동","노란색","노력","노인","녹음","녹차","녹화","논리","논문","논쟁","놀이","농구","농담","농민","농부","농업","농장","농촌","높이","눈동자","눈물","눈썹","뉴욕","느낌","늑대","능동적","능력","다방","다양성","다음","다이어트","다행","단계","단골","단독","단맛","단순","단어","단위","단점","단체","단추","단편","단풍","달걀","달러","달력","달리","닭고기","담당","담배","담요","담임","답변","답장","당근","당분간","당연히","당장","대규모","대낮","대단히","대답","대도시","대략","대량","대륙","대문","대부분","대신","대응","대장","대전","대접","대중","대책","대출","대충","대통령","대학","대한민국","대합실","대형","덩어리","데이트","도대체","도덕","도둑","도망","도서관","도심","도움","도입","도자기","도저히","도전","도중","도착","독감","독립","독서","독일","독창적","동화책","뒷모습","뒷산","딸아이","마누라","마늘","마당","마라톤","마련","마무리","마사지","마약","마요네즈","마을","마음","마이크","마중","마지막","마찬가지","마찰","마흔","막걸리","막내","막상","만남","만두","만세","만약","만일","만점","만족","만화","많이","말기","말씀","말투","맘대로","망원경","매년","매달","매력","매번","매스컴","매일","매장","맥주","먹이","먼저","먼지","멀리","메일","며느리","며칠","면담","멸치","명단","명령","명예","명의","명절","명칭","명함","모금","모니터","모델","모든","모범","모습","모양","모임","모조리","모집","모퉁이","목걸이","목록","목사","목소리","목숨","목적","목표","몰래","몸매","몸무게","몸살","몸속","몸짓","몸통","몹시","무관심","무궁화","무더위","무덤","무릎","무슨","무엇","무역","무용","무조건","무지개","무척","문구","문득","문법","문서","문제","문학","문화","물가","물건","물결","물고기","물론","물리학","물음","물질","물체","미국","미디어","미사일","미술","미역","미용실","미움","미인","미팅","미혼","민간","민족","민주","믿음","밀가루","밀리미터","밑바닥","바가지","바구니","바나나","바늘","바닥","바닷가","바람","바이러스","바탕","박물관","박사","박수","반대","반드시","반말","반발","반성","반응","반장","반죽","반지","반찬","받침","발가락","발걸음","발견","발달","발레","발목","발바닥","발생","발음","발자국","발전","발톱","발표","밤하늘","밥그릇","밥맛","밥상","밥솥","방금","방면","방문","방바닥","방법","방송","방식","방안","방울","방지","방학","방해","방향","배경","배꼽","배달","배드민턴","백두산","백색","백성","백인","백제","백화점","버릇","버섯","버튼","번개","번역","번지","번호","벌금","벌레","벌써","범위","범인","범죄","법률","법원","법적","법칙","베이징","벨트","변경","변동","변명","변신","변호사","변화","별도","별명","별일","병실","병아리","병원","보관","보너스","보라색","보람","보름","보상","보안","보자기","보장","보전","보존","보통","보편적","보험","복도","복사","복숭아","복습","볶음","본격적","본래","본부","본사","본성","본인","본질","볼펜","봉사","봉지","봉투","부근","부끄러움","부담","부동산","부문","부분","부산","부상","부엌","부인","부작용","부장","부정","부족","부지런히","부친","부탁","부품","부회장","북부","북한","분노","분량","분리","분명","분석","분야","분위기","분필","분홍색","불고기","불과","불교","불꽃","불만","불법","불빛","불안","불이익","불행","브랜드","비극","비난","비닐","비둘기","비디오","비로소","비만","비명","비밀","비바람","비빔밥","비상","비용","비율","비중","비타민","비판","빌딩","빗물","빗방울","빗줄기","빛깔","빨간색","빨래","빨리","사건","사계절","사나이","사냥","사람","사랑","사립","사모님","사물","사방","사상","사생활","사설","사슴","사실","사업","사용","사월","사장","사전","사진","사촌","사춘기","사탕","사투리","사흘","산길","산부인과","산업","산책","살림","살인","살짝","삼계탕","삼국","삼십","삼월","삼촌","상관","상금","상대","상류","상반기","상상","상식","상업","상인","상자","상점","상처","상추","상태","상표","상품","상황","새벽","색깔","색연필","생각","생명","생물","생방송","생산","생선","생신","생일","생활","서랍","서른","서명","서민","서비스","서양","서울","서적","서점","서쪽","서클","석사","석유","선거","선물","선배","선생","선수","선원","선장","선전","선택","선풍기","설거지","설날","설렁탕","설명","설문","설사","설악산","설치","설탕","섭씨","성공","성당","성명","성별","성인","성장","성적","성질","성함","세금","세미나","세상","세월","세종대왕","세탁","센터","센티미터","셋째","소규모","소극적","소금","소나기","소년","소득","소망","소문","소설","소속","소아과","소용","소원","소음","소중히","소지품","소질","소풍","소형","속담","속도","속옷","손가락","손길","손녀","손님","손등","손목","손뼉","손실","손질","손톱","손해","솔직히","솜씨","송아지","송이","송편","쇠고기","쇼핑","수건","수년","수단","수돗물","수동적","수면","수명","수박","수상","수석","수술","수시로","수업","수염","수영","수입","수준","수집","수출","수컷","수필","수학","수험생","수화기","숙녀","숙소","숙제","순간","순서","순수","순식간","순위","숟가락","술병","술집","숫자","스님","스물","스스로","스승","스웨터","스위치","스케이트","스튜디오","스트레스","스포츠","슬쩍","슬픔","습관","습기","승객","승리","승부","승용차","승진","시각","시간","시골","시금치","시나리오","시댁","시리즈","시멘트","시민","시부모","시선","시설","시스템","시아버지","시어머니","시월","시인","시일","시작","시장","시절","시점","시중","시즌","시집","시청","시합","시험","식구","식기","식당","식량","식료품","식물","식빵","식사","식생활","식초","식탁","식품","신고","신규","신념","신문","신발","신비","신사","신세","신용","신제품","신청","신체","신화","실감","실내","실력","실례","실망","실수","실습","실시","실장","실정","실질적","실천","실체","실컷","실태","실패","실험","실현","심리","심부름","심사","심장","심정","심판","쌍둥이","씨름","씨앗","아가씨","아나운서","아드님","아들","아쉬움","아스팔트","아시아","아울러","아저씨","아줌마","아직","아침","아파트","아프리카","아픔","아홉","아흔","악기","악몽","악수","안개","안경","안과","안내","안녕","안동","안방","안부","안주","알루미늄","알코올","암시","암컷","압력","앞날","앞문","애인","애정","액수","앨범","야간","야단","야옹","약간","약국","약속","약수","약점","약품","약혼녀","양념","양력","양말","양배추","양주","양파","어둠","어려움","어른","어젯밤","어쨌든","어쩌다가","어쩐지","언니","언덕","언론","언어","얼굴","얼른","얼음","얼핏","엄마","업무","업종","업체","엉덩이","엉망","엉터리","엊그제","에너지","에어컨","엔진","여건","여고생","여관","여군","여권","여대생","여덟","여동생","여든","여론","여름","여섯","여성","여왕","여인","여전히","여직원","여학생","여행","역사","역시","역할","연결","연구","연극","연기","연락","연설","연세","연속","연습","연애","연예인","연인","연장","연주","연출","연필","연합","연휴","열기","열매","열쇠","열심히","열정","열차","열흘","염려","엽서","영국","영남","영상","영양","영역","영웅","영원히","영하","영향","영혼","영화","옆구리","옆방","옆집","예감","예금","예방","예산","예상","예선","예술","예습","예식장","예약","예전","예절","예정","예컨대","옛날","오늘","오락","오랫동안","오렌지","오로지","오른발","오븐","오십","오염","오월","오전","오직","오징어","오페라","오피스텔","오히려","옥상","옥수수","온갖","온라인","온몸","온종일","온통","올가을","올림픽","올해","옷차림","와이셔츠","와인","완성","완전","왕비","왕자","왜냐하면","왠지","외갓집","외국","외로움","외삼촌","외출","외침","외할머니","왼발","왼손","왼쪽","요금","요일","요즘","요청","용기","용서","용어","우산","우선","우승","우연히","우정","우체국","우편","운동","운명","운반","운전","운행","울산","울음","움직임","웃어른","웃음","워낙","원고","원래","원서","원숭이","원인","원장","원피스","월급","월드컵","월세","월요일","웨이터","위반","위법","위성","위원","위험","위협","윗사람","유난히","유럽","유명","유물","유산","유적","유치원","유학","유행","유형","육군","육상","육십","육체","은행","음력","음료","음반","음성","음식","음악","음주","의견","의논","의문","의복","의식","의심","의외로","의욕","의원","의학","이것","이곳","이념","이놈","이달","이대로","이동","이렇게","이력서","이론적","이름","이민","이발소","이별","이불","이빨","이상","이성","이슬","이야기","이용","이웃","이월","이윽고","이익","이전","이중","이튿날","이틀","이혼","인간","인격","인공","인구","인근","인기","인도","인류","인물","인생","인쇄","인연","인원","인재","인종","인천","인체","인터넷","인하","인형","일곱","일기","일단","일대","일등","일반","일본","일부","일상","일생","일손","일요일","일월","일정","일종","일주일","일찍","일체","일치","일행","일회용","임금","임무","입대","입력","입맛","입사","입술","입시","입원","입장","입학","자가용","자격","자극","자동","자랑","자부심","자식","자신","자연","자원","자율","자전거","자정","자존심","자판","작가","작년","작성","작업","작용","작은딸","작품","잔디","잔뜩","잔치","잘못","잠깐","잠수함","잠시","잠옷","잠자리","잡지","장관","장군","장기간","장래","장례","장르","장마","장면","장모","장미","장비","장사","장소","장식","장애인","장인","장점","장차","장학금","재능","재빨리","재산","재생","재작년","재정","재채기","재판","재학","재활용","저것","저고리","저곳","저녁","저런","저렇게","저번","저울","저절로","저축","적극","적당히","적성","적용","적응","전개","전공","전기","전달","전라도","전망","전문","전반","전부","전세","전시","전용","전자","전쟁","전주","전철","전체","전통","전혀","전후","절대","절망","절반","절약","절차","점검","점수","점심","점원","점점","점차","접근","접시","접촉","젓가락","정거장","정도","정류장","정리","정말","정면","정문","정반대","정보","정부","정비","정상","정성","정오","정원","정장","정지","정치","정확히","제공","제과점","제대로","제목","제발","제법","제삿날","제안","제일","제작","제주도","제출","제품","제한","조각","조건","조금","조깅","조명","조미료","조상","조선","조용히","조절","조정","조직","존댓말","존재","졸업","졸음","종교","종로","종류","종소리","종업원","종종","종합","좌석","죄인","주관적","주름","주말","주머니","주먹","주문","주민","주방","주변","주식","주인","주일","주장","주전자","주택","준비","줄거리","줄기","줄무늬","중간","중계방송","중국","중년","중단","중독","중반","중부","중세","중소기업","중순","중앙","중요","중학교","즉석","즉시","즐거움","증가","증거","증권","증상","증세","지각","지갑","지경","지극히","지금","지급","지능","지름길","지리산","지방","지붕","지식","지역","지우개","지원","지적","지점","지진","지출","직선","직업","직원","직장","진급","진동","진로","진료","진리","진짜","진찰","진출","진통","진행","질문","질병","질서","짐작","집단","집안","집중","짜증","찌꺼기","차남","차라리","차량","차림","차별","차선","차츰","착각","찬물","찬성","참가","참기름","참새","참석","참여","참외","참조","찻잔","창가","창고","창구","창문","창밖","창작","창조","채널","채점","책가방","책방","책상","책임","챔피언","처벌","처음","천국","천둥","천장","천재","천천히","철도","철저히","철학","첫날","첫째","청년","청바지","청소","청춘","체계","체력","체온","체육","체중","체험","초등학생","초반","초밥","초상화","초순","초여름","초원","초저녁","초점","초청","초콜릿","촛불","총각","총리","총장","촬영","최근","최상","최선","최신","최악","최종","추석","추억","추진","추천","추측","축구","축소","축제","축하","출근","출발","출산","출신","출연","출입","출장","출판","충격","충고","충돌","충분히","충청도","취업","취직","취향","치약","친구","친척","칠십","칠월","칠판","침대","침묵","침실","칫솔","칭찬","카메라","카운터","칼국수","캐릭터","캠퍼스","캠페인","커튼","컨디션","컬러","컴퓨터","코끼리","코미디","콘서트","콜라","콤플렉스","콩나물","쾌감","쿠데타","크림","큰길","큰딸","큰소리","큰아들","큰어머니","큰일","큰절","클래식","클럽","킬로","타입","타자기","탁구","탁자","탄생","태권도","태양","태풍","택시","탤런트","터널","터미널","테니스","테스트","테이블","텔레비전","토론","토마토","토요일","통계","통과","통로","통신","통역","통일","통장","통제","통증","통합","통화","퇴근","퇴원","퇴직금","튀김","트럭","특급","특별","특성","특수","특징","특히","튼튼히","티셔츠","파란색","파일","파출소","판결","판단","판매","판사","팔십","팔월","팝송","패션","팩스","팩시밀리","팬티","퍼센트","페인트","편견","편의","편지","편히","평가","평균","평생","평소","평양","평일","평화","포스터","포인트","포장","포함","표면","표정","표준","표현","품목","품질","풍경","풍속","풍습","프랑스","프린터","플라스틱","피곤","피망","피아노","필름","필수","필요","필자","필통","핑계","하느님","하늘","하드웨어","하룻밤","하반기","하숙집","하순","하여튼","하지만","하천","하품","하필","학과","학교","학급","학기","학년","학력","학번","학부모","학비","학생","학술","학습","학용품","학원","학위","학자","학점","한계","한글","한꺼번에","한낮","한눈","한동안","한때","한라산","한마디","한문","한번","한복","한식","한여름","한쪽","할머니","할아버지","할인","함께","함부로","합격","합리적","항공","항구","항상","항의","해결","해군","해답","해당","해물","해석","해설","해수욕장","해안","핵심","핸드백","햄버거","햇볕","햇살","행동","행복","행사","행운","행위","향기","향상","향수","허락","허용","헬기","현관","현금","현대","현상","현실","현장","현재","현지","혈액","협력","형부","형사","형수","형식","형제","형태","형편","혜택","호기심","호남","호랑이","호박","호텔","호흡","혹시","홀로","홈페이지","홍보","홍수","홍차","화면","화분","화살","화요일","화장","화학","확보","확인","확장","확정","환갑","환경","환영","환율","환자","활기","활동","활발히","활용","활짝","회견","회관","회복","회색","회원","회장","회전","횟수","횡단보도","효율적","후반","후춧가루","훈련","훨씬","휴식","휴일","흉내","흐름","흑백","흑인","흔적","흔히","흥미","흥분","희곡","희망","희생","흰색","힘껏"]{"的":["chinese_simplified","chinese_traditional"],"一":["chinese_simplified","chinese_traditional"],"是":["chinese_simplified","chinese_traditional"],"在":["chinese_simplified","chinese_traditional"],"不":["chinese_simplified","chinese_traditional"],"了":["chinese_simplified","chinese_traditional"],"有":["chinese_simplified","chinese_traditional"],"和":["chinese_simplified","chinese_traditional"],"人":["chinese_simplified","chinese_traditional"],"这":["chinese_simplified"],"中":["chinese_simplified","chinese_traditional"],"大":["chinese_simplified","chinese_traditional"],"为":["chinese_simplified"],"上":["chinese_simplified","chinese_traditional"],"个":["chinese_simplified"],"国":["chinese_simplified"],"我":["chinese_simplified","chinese_traditional"],"以":["chinese_simplified","chinese_traditional"],"要":["chinese_simplified","chinese_traditional"],"他":["chinese_simplified","chinese_traditional"],"时":["chinese_simplified"],"来":["chinese_simplified"],"用":["chinese_simplified","chinese_traditional"],"们":["chinese_simplified"],"生":["chinese_simplified","chinese_traditional"],"到":["chinese_simplified","chinese_traditional"],"作":["chinese_simplified","chinese_traditional"],"地":["chinese_simplified","chinese_traditional"],"于":["chinese_simplified"],"出":["chinese_simplified","chinese_traditional"],"就":["chinese_simplified","chinese_traditional"],"分":["chinese_simplified","chinese_traditional"],"对":["chinese_simplified"],"成":["chinese_simplified","chinese_traditional"],"会":["chinese_simplified"],"可":["chinese_simplified","chinese_traditional"],"主":["chinese_simplified","chinese_traditional"],"发":["chinese_simplified"],"年":["chinese_simplified","chinese_traditional"],"动":["chinese_simplified"],"同":["chinese_simplified","chinese_traditional"],"工":["chinese_simplified","chinese_traditional"],"也":["chinese_simplified","chinese_traditional"],"能":["chinese_simplified","chinese_traditional"],"下":["chinese_simplified","chinese_traditional"],"过":["chinese_simplified"],"子":["chinese_simplified","chinese_traditional"],"说":["chinese_simplified"],"产":["chinese_simplified"],"种":["chinese_simplified"],"面":["chinese_simplified","chinese_traditional"],"而":["chinese_simplified","chinese_traditional"],"方":["chinese_simplified","chinese_traditional"],"后":["chinese_simplified"],"多":["chinese_simplified","chinese_traditional"],"定":["chinese_simplified","chinese_traditional"],"行":["chinese_simplified","chinese_traditional"],"学":["chinese_simplified"],"法":["chinese_simplified","chinese_traditional"],"所":["chinese_simplified","chinese_traditional"],"民":["chinese_simplified","chinese_traditional"],"得":["chinese_simplified","chinese_traditional"],"经":["chinese_simplified"],"十":["chinese_simplified","chinese_traditional"],"三":["chinese_simplified","chinese_traditional"],"之":["chinese_simplified","chinese_traditional"],"进":["chinese_simplified"],"着":["chinese_simplified"],"等":["chinese_simplified","chinese_traditional"],"部":["chinese_simplified","chinese_traditional"],"度":["chinese_simplified","chinese_traditional"],"家":["chinese_simplified","chinese_traditional"],"电":["chinese_simplified"],"力":["chinese_simplified","chinese_traditional"],"里":["chinese_simplified"],"如":["chinese_simplified","chinese_traditional"],"水":["chinese_simplified","chinese_traditional"],"化":["chinese_simplified","chinese_traditional"],"高":["chinese_simplified","chinese_traditional"],"自":["chinese_simplified","chinese_traditional"],"二":["chinese_simplified","chinese_traditional"],"理":["chinese_simplified","chinese_traditional"],"起":["chinese_simplified","chinese_traditional"],"小":["chinese_simplified","chinese_traditional"],"物":["chinese_simplified","chinese_traditional"],"现":["chinese_simplified"],"实":["chinese_simplified"],"加":["chinese_simplified","chinese_traditional"],"量":["chinese_simplified","chinese_traditional"],"都":["chinese_simplified","chinese_traditional"],"两":["chinese_simplified"],"体":["chinese_simplified"],"制":["chinese_simplified","chinese_traditional"],"机":["chinese_simplified"],"当":["chinese_simplified"],"使":["chinese_simplified","chinese_traditional"],"点":["chinese_simplified"],"从":["chinese_simplified"],"业":["chinese_simplified"],"本":["chinese_simplified","chinese_traditional"],"去":["chinese_simplified","chinese_traditional"],"把":["chinese_simplified","chinese_traditional"],"性":["chinese_simplified","chinese_traditional"],"好":["chinese_simplified","chinese_traditional"],"应":["chinese_simplified"],"开":["chinese_simplified"],"它":["chinese_simplified","chinese_traditional"],"合":["chinese_simplified","chinese_traditional"],"还":["chinese_simplified"],"因":["chinese_simplified","chinese_traditional"],"由":["chinese_simplified","chinese_traditional"],"其":["chinese_simplified","chinese_traditional"],"些":["chinese_simplified","chinese_traditional"],"然":["chinese_simplified","chinese_traditional"],"前":["chinese_simplified","chinese_traditional"],"外":["chinese_simplified","chinese_traditional"],"天":["chinese_simplified","chinese_traditional"],"政":["chinese_simplified","chinese_traditional"],"四":["chinese_simplified","chinese_traditional"],"日":["chinese_simplified","chinese_traditional"],"那":["chinese_simplified","chinese_traditional"],"社":["chinese_simplified","chinese_traditional"],"义":["chinese_simplified"],"事":["chinese_simplified","chinese_traditional"],"平":["chinese_simplified","chinese_traditional"],"形":["chinese_simplified","chinese_traditional"],"相":["chinese_simplified","chinese_traditional"],"全":["chinese_simplified","chinese_traditional"],"表":["chinese_simplified","chinese_traditional"],"间":["chinese_simplified"],"样":["chinese_simplified"],"与":["chinese_simplified"],"关":["chinese_simplified"],"各":["chinese_simplified","chinese_traditional"],"重":["chinese_simplified","chinese_traditional"],"新":["chinese_simplified","chinese_traditional"],"线":["chinese_simplified"],"内":["chinese_simplified"],"数":["chinese_simplified"],"正":["chinese_simplified","chinese_traditional"],"心":["chinese_simplified","chinese_traditional"],"反":["chinese_simplified","chinese_traditional"],"你":["chinese_simplified","chinese_traditional"],"明":["chinese_simplified","chinese_traditional"],"看":["chinese_simplified","chinese_traditional"],"原":["chinese_simplified","chinese_traditional"],"又":["chinese_simplified","chinese_traditional"],"么":["chinese_simplified"],"利":["chinese_simplified","chinese_traditional"],"比":["chinese_simplified","chinese_traditional"],"或":["chinese_simplified","chinese_traditional"],"但":["chinese_simplified","chinese_traditional"],"质":["chinese_simplified"],"气":["chinese_simplified"],"第":["chinese_simplified","chinese_traditional"],"向":["chinese_simplified","chinese_traditional"],"道":["chinese_simplified","chinese_traditional"],"命":["chinese_simplified","chinese_traditional"],"此":["chinese_simplified","chinese_traditional"],"变":["chinese_simplified"],"条":["chinese_simplified"],"只":["chinese_simplified","chinese_traditional"],"没":["chinese_simplified"],"结":["chinese_simplified"],"解":["chinese_simplified","chinese_traditional"],"问":["chinese_simplified"],"意":["chinese_simplified","chinese_traditional"],"建":["chinese_simplified","chinese_traditional"],"月":["chinese_simplified","chinese_traditional"],"公":["chinese_simplified","chinese_traditional"],"无":["chinese_simplified"],"系":["chinese_simplified","chinese_traditional"],"军":["chinese_simplified"],"很":["chinese_simplified","chinese_traditional"],"情":["chinese_simplified","chinese_traditional"],"者":["chinese_simplified","chinese_traditional"],"最":["chinese_simplified","chinese_traditional"],"立":["chinese_simplified","chinese_traditional"],"代":["chinese_simplified","chinese_traditional"],"想":["chinese_simplified","chinese_traditional"],"已":["chinese_simplified","chinese_traditional"],"通":["chinese_simplified","chinese_traditional"],"并":["chinese_simplified"],"提":["chinese_simplified","chinese_traditional"],"直":["chinese_simplified","chinese_traditional"],"题":["chinese_simplified"],"党":["chinese_simplified"],"程":["chinese_simplified","chinese_traditional"],"展":["chinese_simplified","chinese_traditional"],"五":["chinese_simplified","chinese_traditional"],"果":["chinese_simplified","chinese_traditional"],"料":["chinese_simplified","chinese_traditional"],"象":["chinese_simplified","chinese_traditional"],"员":["chinese_simplified"],"革":["chinese_simplified","chinese_traditional"],"位":["chinese_simplified","chinese_traditional"],"入":["chinese_simplified","chinese_traditional"],"常":["chinese_simplified","chinese_traditional"],"文":["chinese_simplified","chinese_traditional"],"总":["chinese_simplified"],"次":["chinese_simplified","chinese_traditional"],"品":["chinese_simplified","chinese_traditional"],"式":["chinese_simplified","chinese_traditional"],"活":["chinese_simplified","chinese_traditional"],"设":["chinese_simplified"],"及":["chinese_simplified","chinese_traditional"],"管":["chinese_simplified","chinese_traditional"],"特":["chinese_simplified","chinese_traditional"],"件":["chinese_simplified","chinese_traditional"],"长":["chinese_simplified"],"求":["chinese_simplified","chinese_traditional"],"老":["chinese_simplified","chinese_traditional"],"头":["chinese_simplified"],"基":["chinese_simplified","chinese_traditional"],"资":["chinese_simplified"],"边":["chinese_simplified"],"流":["chinese_simplified","chinese_traditional"],"路":["chinese_simplified","chinese_traditional"],"级":["chinese_simplified"],"少":["chinese_simplified","chinese_traditional"],"图":["chinese_simplified"],"山":["chinese_simplified","chinese_traditional"],"统":["chinese_simplified"],"接":["chinese_simplified","chinese_traditional"],"知":["chinese_simplified","chinese_traditional"],"较":["chinese_simplified"],"将":["chinese_simplified"],"组":["chinese_simplified"],"见":["chinese_simplified"],"计":["chinese_simplified"],"别":["chinese_simplified"],"她":["chinese_simplified","chinese_traditional"],"手":["chinese_simplified","chinese_traditional"],"角":["chinese_simplified","chinese_traditional"],"期":["chinese_simplified","chinese_traditional"],"根":["chinese_simplified","chinese_traditional"],"论":["chinese_simplified"],"运":["chinese_simplified"],"农":["chinese_simplified"],"指":["chinese_simplified","chinese_traditional"],"几":["chinese_simplified"],"九":["chinese_simplified","chinese_traditional"],"区":["chinese_simplified"],"强":["chinese_simplified"],"放":["chinese_simplified","chinese_traditional"],"决":["chinese_simplified"],"西":["chinese_simplified","chinese_traditional"],"被":["chinese_simplified","chinese_traditional"],"干":["chinese_simplified"],"做":["chinese_simplified","chinese_traditional"],"必":["chinese_simplified","chinese_traditional"],"战":["chinese_simplified"],"先":["chinese_simplified","chinese_traditional"],"回":["chinese_simplified","chinese_traditional"],"则":["chinese_simplified"],"任":["chinese_simplified","chinese_traditional"],"取":["chinese_simplified","chinese_traditional"],"据":["chinese_simplified"],"处":["chinese_simplified"],"队":["chinese_simplified"],"南":["chinese_simplified","chinese_traditional"],"给":["chinese_simplified"],"色":["chinese_simplified","chinese_traditional"],"光":["chinese_simplified","chinese_traditional"],"门":["chinese_simplified"],"即":["chinese_simplified","chinese_traditional"],"保":["chinese_simplified","chinese_traditional"],"治":["chinese_simplified","chinese_traditional"],"北":["chinese_simplified","chinese_traditional"],"造":["chinese_simplified","chinese_traditional"],"百":["chinese_simplified","chinese_traditional"],"规":["chinese_simplified"],"热":["chinese_simplified"],"领":["chinese_simplified"],"七":["chinese_simplified","chinese_traditional"],"海":["chinese_simplified","chinese_traditional"],"口":["chinese_simplified","chinese_traditional"],"东":["chinese_simplified"],"导":["chinese_simplified"],"器":["chinese_simplified","chinese_traditional"],"压":["chinese_simplified"],"志":["chinese_simplified","chinese_traditional"],"世":["chinese_simplified","chinese_traditional"],"金":["chinese_simplified","chinese_traditional"],"增":["chinese_simplified","chinese_traditional"],"争":["chinese_simplified"],"济":["chinese_simplified"],"阶":["chinese_simplified"],"油":["chinese_simplified","chinese_traditional"],"思":["chinese_simplified","chinese_traditional"],"术":["chinese_simplified"],"极":["chinese_simplified"],"交":["chinese_simplified","chinese_traditional"],"受":["chinese_simplified","chinese_traditional"],"联":["chinese_simplified"],"什":["chinese_simplified","chinese_traditional"],"认":["chinese_simplified"],"六":["chinese_simplified","chinese_traditional"],"共":["chinese_simplified","chinese_traditional"],"权":["chinese_simplified"],"收":["chinese_simplified","chinese_traditional"],"证":["chinese_simplified"],"改":["chinese_simplified","chinese_traditional"],"清":["chinese_simplified","chinese_traditional"],"美":["chinese_simplified","chinese_traditional"],"再":["chinese_simplified","chinese_traditional"],"采":["chinese_simplified"],"转":["chinese_simplified"],"更":["chinese_simplified","chinese_traditional"],"单":["chinese_simplified"],"风":["chinese_simplified"],"切":["chinese_simplified","chinese_traditional"],"打":["chinese_simplified","chinese_traditional"],"白":["chinese_simplified","chinese_traditional"],"教":["chinese_simplified","chinese_traditional"],"速":["chinese_simplified","chinese_traditional"],"花":["chinese_simplified","chinese_traditional"],"带":["chinese_simplified"],"安":["chinese_simplified","chinese_traditional"],"场":["chinese_simplified"],"身":["chinese_simplified","chinese_traditional"],"车":["chinese_simplified"],"例":["chinese_simplified","chinese_traditional"],"真":["chinese_simplified","chinese_traditional"],"务":["chinese_simplified"],"具":["chinese_simplified","chinese_traditional"],"万":["chinese_simplified"],"每":["chinese_simplified","chinese_traditional"],"目":["chinese_simplified","chinese_traditional"],"至":["chinese_simplified","chinese_traditional"],"达":["chinese_simplified"],"走":["chinese_simplified","chinese_traditional"],"积":["chinese_simplified"],"示":["chinese_simplified","chinese_traditional"],"议":["chinese_simplified"],"声":["chinese_simplified"],"报":["chinese_simplified"],"斗":["chinese_simplified"],"完":["chinese_simplified","chinese_traditional"],"类":["chinese_simplified"],"八":["chinese_simplified","chinese_traditional"],"离":["chinese_simplified"],"华":["chinese_simplified"],"名":["chinese_simplified","chinese_traditional"],"确":["chinese_simplified"],"才":["chinese_simplified","chinese_traditional"],"科":["chinese_simplified","chinese_traditional"],"张":["chinese_simplified"],"信":["chinese_simplified","chinese_traditional"],"马":["chinese_simplified"],"节":["chinese_simplified"],"话":["chinese_simplified"],"米":["chinese_simplified","chinese_traditional"],"整":["chinese_simplified","chinese_traditional"],"空":["chinese_simplified","chinese_traditional"],"元":["chinese_simplified","chinese_traditional"],"况":["chinese_simplified"],"今":["chinese_simplified","chinese_traditional"],"集":["chinese_simplified","chinese_traditional"],"温":["chinese_simplified"],"传":["chinese_simplified"],"土":["chinese_simplified","chinese_traditional"],"许":["chinese_simplified"],"步":["chinese_simplified","chinese_traditional"],"群":["chinese_simplified","chinese_traditional"],"广":["chinese_simplified"],"石":["chinese_simplified","chinese_traditional"],"记":["chinese_simplified"],"需":["chinese_simplified","chinese_traditional"],"段":["chinese_simplified","chinese_traditional"],"研":["chinese_simplified","chinese_traditional"],"界":["chinese_simplified","chinese_traditional"],"拉":["chinese_simplified","chinese_traditional"],"林":["chinese_simplified","chinese_traditional"],"律":["chinese_simplified","chinese_traditional"],"叫":["chinese_simplified","chinese_traditional"],"且":["chinese_simplified","chinese_traditional"],"究":["chinese_simplified","chinese_traditional"],"观":["chinese_simplified"],"越":["chinese_simplified","chinese_traditional"],"织":["chinese_simplified"],"装":["chinese_simplified"],"影":["chinese_simplified","chinese_traditional"],"算":["chinese_simplified","chinese_traditional"],"低":["chinese_simplified","chinese_traditional"],"持":["chinese_simplified","chinese_traditional"],"音":["chinese_simplified","chinese_traditional"],"众":["chinese_simplified"],"书":["chinese_simplified"],"布":["chinese_simplified","chinese_traditional"],"复":["chinese_simplified","chinese_traditional"],"容":["chinese_simplified","chinese_traditional"],"儿":["chinese_simplified"],"须":["chinese_simplified"],"际":["chinese_simplified"],"商":["chinese_simplified","chinese_traditional"],"非":["chinese_simplified","chinese_traditional"],"验":["chinese_simplified"],"连":["chinese_simplified"],"断":["chinese_simplified"],"深":["chinese_simplified","chinese_traditional"],"难":["chinese_simplified"],"近":["chinese_simplified","chinese_traditional"],"矿":["chinese_simplified"],"千":["chinese_simplified","chinese_traditional"],"周":["chinese_simplified"],"委":["chinese_simplified","chinese_traditional"],"素":["chinese_simplified","chinese_traditional"],"技":["chinese_simplified","chinese_traditional"],"备":["chinese_simplified"],"半":["chinese_simplified","chinese_traditional"],"办":["chinese_simplified"],"青":["chinese_simplified","chinese_traditional"],"省":["chinese_simplified","chinese_traditional"],"列":["chinese_simplified","chinese_traditional"],"习":["chinese_simplified"],"响":["chinese_simplified"],"约":["chinese_simplified"],"支":["chinese_simplified","chinese_traditional"],"般":["chinese_simplified","chinese_traditional"],"史":["chinese_simplified","chinese_traditional"],"感":["chinese_simplified","chinese_traditional"],"劳":["chinese_simplified"],"便":["chinese_simplified","chinese_traditional"],"团":["chinese_simplified"],"往":["chinese_simplified","chinese_traditional"],"酸":["chinese_simplified","chinese_traditional"],"历":["chinese_simplified"],"市":["chinese_simplified","chinese_traditional"],"克":["chinese_simplified","chinese_traditional"],"何":["chinese_simplified","chinese_traditional"],"除":["chinese_simplified","chinese_traditional"],"消":["chinese_simplified","chinese_traditional"],"构":["chinese_simplified"],"府":["chinese_simplified","chinese_traditional"],"称":["chinese_simplified"],"太":["chinese_simplified","chinese_traditional"],"准":["chinese_simplified"],"精":["chinese_simplified","chinese_traditional"],"值":["chinese_simplified","chinese_traditional"],"号":["chinese_simplified"],"率":["chinese_simplified","chinese_traditional"],"族":["chinese_simplified","chinese_traditional"],"维":["chinese_simplified"],"划":["chinese_simplified"],"选":["chinese_simplified"],"标":["chinese_simplified"],"写":["chinese_simplified"],"存":["chinese_simplified","chinese_traditional"],"候":["chinese_simplified","chinese_traditional"],"毛":["chinese_simplified","chinese_traditional"],"亲":["chinese_simplified"],"快":["chinese_simplified","chinese_traditional"],"效":["chinese_simplified","chinese_traditional"],"斯":["chinese_simplified","chinese_traditional"],"院":["chinese_simplified","chinese_traditional"],"查":["chinese_simplified","chinese_traditional"],"江":["chinese_simplified","chinese_traditional"],"型":["chinese_simplified","chinese_traditional"],"眼":["chinese_simplified","chinese_traditional"],"王":["chinese_simplified","chinese_traditional"],"按":["chinese_simplified","chinese_traditional"],"格":["chinese_simplified","chinese_traditional"],"养":["chinese_simplified"],"易":["chinese_simplified","chinese_traditional"],"置":["chinese_simplified","chinese_traditional"],"派":["chinese_simplified","chinese_traditional"],"层":["chinese_simplified"],"片":["chinese_simplified","chinese_traditional"],"始":["chinese_simplified","chinese_traditional"],"却":["chinese_simplified"],"专":["chinese_simplified"],"状":["chinese_simplified"],"育":["chinese_simplified","chinese_traditional"],"厂":["chinese_simplified"],"京":["chinese_simplified","chinese_traditional"],"识":["chinese_simplified"],"适":["chinese_simplified"],"属":["chinese_simplified"],"圆":["chinese_simplified"],"包":["chinese_simplified","chinese_traditional"],"火":["chinese_simplified","chinese_traditional"],"住":["chinese_simplified","chinese_traditional"],"调":["chinese_simplified"],"满":["chinese_simplified"],"县":["chinese_simplified"],"局":["chinese_simplified","chinese_traditional"],"照":["chinese_simplified","chinese_traditional"],"参":["chinese_simplified"],"红":["chinese_simplified"],"细":["chinese_simplified"],"引":["chinese_simplified","chinese_traditional"],"听":["chinese_simplified"],"该":["chinese_simplified"],"铁":["chinese_simplified"],"价":["chinese_simplified"],"严":["chinese_simplified"],"首":["chinese_simplified","chinese_traditional"],"底":["chinese_simplified","chinese_traditional"],"液":["chinese_simplified","chinese_traditional"],"官":["chinese_simplified","chinese_traditional"],"德":["chinese_simplified","chinese_traditional"],"随":["chinese_simplified"],"病":["chinese_simplified","chinese_traditional"],"苏":["chinese_simplified"],"失":["chinese_simplified","chinese_traditional"],"尔":["chinese_simplified"],"死":["chinese_simplified","chinese_traditional"],"讲":["chinese_simplified"],"配":["chinese_simplified","chinese_traditional"],"女":["chinese_simplified","chinese_traditional"],"黄":["chinese_simplified"],"推":["chinese_simplified","chinese_traditional"],"显":["chinese_simplified"],"谈":["chinese_simplified"],"罪":["chinese_simplified","chinese_traditional"],"神":["chinese_simplified","chinese_traditional"],"艺":["chinese_simplified"],"呢":["chinese_simplified","chinese_traditional"],"席":["chinese_simplified","chinese_traditional"],"含":["chinese_simplified","chinese_traditional"],"企":["chinese_simplified","chinese_traditional"],"望":["chinese_simplified","chinese_traditional"],"密":["chinese_simplified","chinese_traditional"],"批":["chinese_simplified","chinese_traditional"],"营":["chinese_simplified"],"项":["chinese_simplified"],"防":["chinese_simplified","chinese_traditional"],"举":["chinese_simplified"],"球":["chinese_simplified","chinese_traditional"],"英":["chinese_simplified","chinese_traditional"],"氧":["chinese_simplified","chinese_traditional"],"势":["chinese_simplified"],"告":["chinese_simplified","chinese_traditional"],"李":["chinese_simplified","chinese_traditional"],"台":["chinese_simplified","chinese_traditional"],"落":["chinese_simplified","chinese_traditional"],"木":["chinese_simplified","chinese_traditional"],"帮":["chinese_simplified"],"轮":["chinese_simplified"],"破":["chinese_simplified","chinese_traditional"],"亚":["chinese_simplified"],"师":["chinese_simplified"],"围":["chinese_simplified"],"注":["chinese_simplified","chinese_traditional"],"远":["chinese_simplified"],"字":["chinese_simplified","chinese_traditional"],"材":["chinese_simplified","chinese_traditional"],"排":["chinese_simplified","chinese_traditional"],"供":["chinese_simplified","chinese_traditional"],"河":["chinese_simplified","chinese_traditional"],"态":["chinese_simplified"],"封":["chinese_simplified","chinese_traditional"],"另":["chinese_simplified","chinese_traditional"],"施":["chinese_simplified","chinese_traditional"],"减":["chinese_simplified"],"树":["chinese_simplified"],"溶":["chinese_simplified","chinese_traditional"],"怎":["chinese_simplified","chinese_traditional"],"止":["chinese_simplified","chinese_traditional"],"案":["chinese_simplified","chinese_traditional"],"言":["chinese_simplified","chinese_traditional"],"士":["chinese_simplified","chinese_traditional"],"均":["chinese_simplified","chinese_traditional"],"武":["chinese_simplified","chinese_traditional"],"固":["chinese_simplified","chinese_traditional"],"叶":["chinese_simplified"],"鱼":["chinese_simplified"],"波":["chinese_simplified","chinese_traditional"],"视":["chinese_simplified"],"仅":["chinese_simplified"],"费":["chinese_simplified"],"紧":["chinese_simplified"],"爱":["chinese_simplified"],"左":["chinese_simplified","chinese_traditional"],"章":["chinese_simplified","chinese_traditional"],"早":["chinese_simplified","chinese_traditional"],"朝":["chinese_simplified","chinese_traditional"],"害":["chinese_simplified","chinese_traditional"],"续":["chinese_simplified"],"轻":["chinese_simplified"],"服":["chinese_simplified","chinese_traditional"],"试":["chinese_simplified"],"食":["chinese_simplified","chinese_traditional"],"充":["chinese_simplified","chinese_traditional"],"兵":["chinese_simplified","chinese_traditional"],"源":["chinese_simplified","chinese_traditional"],"判":["chinese_simplified","chinese_traditional"],"护":["chinese_simplified"],"司":["chinese_simplified","chinese_traditional"],"足":["chinese_simplified","chinese_traditional"],"某":["chinese_simplified","chinese_traditional"],"练":["chinese_simplified"],"差":["chinese_simplified","chinese_traditional"],"致":["chinese_simplified","chinese_traditional"],"板":["chinese_simplified","chinese_traditional"],"田":["chinese_simplified","chinese_traditional"],"降":["chinese_simplified","chinese_traditional"],"黑":["chinese_simplified","chinese_traditional"],"犯":["chinese_simplified","chinese_traditional"],"负":["chinese_simplified"],"击":["chinese_simplified"],"范":["chinese_simplified","chinese_traditional"],"继":["chinese_simplified"],"兴":["chinese_simplified"],"似":["chinese_simplified","chinese_traditional"],"余":["chinese_simplified"],"坚":["chinese_simplified"],"曲":["chinese_simplified","chinese_traditional"],"输":["chinese_simplified"],"修":["chinese_simplified","chinese_traditional"],"故":["chinese_simplified","chinese_traditional"],"城":["chinese_simplified","chinese_traditional"],"夫":["chinese_simplified","chinese_traditional"],"够":["chinese_simplified"],"送":["chinese_simplified","chinese_traditional"],"笔":["chinese_simplified"],"船":["chinese_simplified","chinese_traditional"],"占":["chinese_simplified"],"右":["chinese_simplified","chinese_traditional"],"财":["chinese_simplified"],"吃":["chinese_simplified","chinese_traditional"],"富":["chinese_simplified","chinese_traditional"],"春":["chinese_simplified","chinese_traditional"],"职":["chinese_simplified"],"觉":["chinese_simplified"],"汉":["chinese_simplified"],"画":["chinese_simplified"],"功":["chinese_simplified","chinese_traditional"],"巴":["chinese_simplified","chinese_traditional"],"跟":["chinese_simplified","chinese_traditional"],"虽":["chinese_simplified"],"杂":["chinese_simplified"],"飞":["chinese_simplified"],"检":["chinese_simplified"],"吸":["chinese_simplified","chinese_traditional"],"助":["chinese_simplified","chinese_traditional"],"升":["chinese_simplified"],"阳":["chinese_simplified"],"互":["chinese_simplified","chinese_traditional"],"初":["chinese_simplified","chinese_traditional"],"创":["chinese_simplified"],"抗":["chinese_simplified","chinese_traditional"],"考":["chinese_simplified","chinese_traditional"],"投":["chinese_simplified","chinese_traditional"],"坏":["chinese_simplified"],"策":["chinese_simplified","chinese_traditional"],"古":["chinese_simplified","chinese_traditional"],"径":["chinese_simplified"],"换":["chinese_simplified"],"未":["chinese_simplified","chinese_traditional"],"跑":["chinese_simplified","chinese_traditional"],"留":["chinese_simplified","chinese_traditional"],"钢":["chinese_simplified"],"曾":["chinese_simplified","chinese_traditional"],"端":["chinese_simplified","chinese_traditional"],"责":["chinese_simplified"],"站":["chinese_simplified","chinese_traditional"],"简":["chinese_simplified"],"述":["chinese_simplified","chinese_traditional"],"钱":["chinese_simplified"],"副":["chinese_simplified","chinese_traditional"],"尽":["chinese_simplified"],"帝":["chinese_simplified","chinese_traditional"],"射":["chinese_simplified","chinese_traditional"],"草":["chinese_simplified","chinese_traditional"],"冲":["chinese_simplified"],"承":["chinese_simplified","chinese_traditional"],"独":["chinese_simplified"],"令":["chinese_simplified","chinese_traditional"],"限":["chinese_simplified","chinese_traditional"],"阿":["chinese_simplified","chinese_traditional"],"宣":["chinese_simplified","chinese_traditional"],"环":["chinese_simplified"],"双":["chinese_simplified"],"请":["chinese_simplified"],"超":["chinese_simplified","chinese_traditional"],"微":["chinese_simplified","chinese_traditional"],"让":["chinese_simplified"],"控":["chinese_simplified","chinese_traditional"],"州":["chinese_simplified","chinese_traditional"],"良":["chinese_simplified","chinese_traditional"],"轴":["chinese_simplified"],"找":["chinese_simplified","chinese_traditional"],"否":["chinese_simplified","chinese_traditional"],"纪":["chinese_simplified"],"益":["chinese_simplified","chinese_traditional"],"依":["chinese_simplified","chinese_traditional"],"优":["chinese_simplified"],"顶":["chinese_simplified"],"础":["chinese_simplified"],"载":["chinese_simplified"],"倒":["chinese_simplified","chinese_traditional"],"房":["chinese_simplified","chinese_traditional"],"突":["chinese_simplified","chinese_traditional"],"坐":["chinese_simplified","chinese_traditional"],"粉":["chinese_simplified","chinese_traditional"],"敌":["chinese_simplified"],"略":["chinese_simplified","chinese_traditional"],"客":["chinese_simplified","chinese_traditional"],"袁":["chinese_simplified","chinese_traditional"],"冷":["chinese_simplified","chinese_traditional"],"胜":["chinese_simplified"],"绝":["chinese_simplified"],"析":["chinese_simplified","chinese_traditional"],"块":["chinese_simplified"],"剂":["chinese_simplified"],"测":["chinese_simplified"],"丝":["chinese_simplified"],"协":["chinese_simplified"],"诉":["chinese_simplified"],"念":["chinese_simplified","chinese_traditional"],"陈":["chinese_simplified"],"仍":["chinese_simplified","chinese_traditional"],"罗":["chinese_simplified"],"盐":["chinese_simplified"],"友":["chinese_simplified","chinese_traditional"],"洋":["chinese_simplified","chinese_traditional"],"错":["chinese_simplified"],"苦":["chinese_simplified","chinese_traditional"],"夜":["chinese_simplified","chinese_traditional"],"刑":["chinese_simplified","chinese_traditional"],"移":["chinese_simplified","chinese_traditional"],"频":["chinese_simplified"],"逐":["chinese_simplified","chinese_traditional"],"靠":["chinese_simplified","chinese_traditional"],"混":["chinese_simplified","chinese_traditional"],"母":["chinese_simplified","chinese_traditional"],"短":["chinese_simplified","chinese_traditional"],"皮":["chinese_simplified","chinese_traditional"],"终":["chinese_simplified"],"聚":["chinese_simplified","chinese_traditional"],"汽":["chinese_simplified","chinese_traditional"],"村":["chinese_simplified","chinese_traditional"],"云":["chinese_simplified"],"哪":["chinese_simplified","chinese_traditional"],"既":["chinese_simplified","chinese_traditional"],"距":["chinese_simplified","chinese_traditional"],"卫":["chinese_simplified"],"停":["chinese_simplified","chinese_traditional"],"烈":["chinese_simplified","chinese_traditional"],"央":["chinese_simplified","chinese_traditional"],"察":["chinese_simplified","chinese_traditional"],"烧":["chinese_simplified"],"迅":["chinese_simplified","chinese_traditional"],"境":["chinese_simplified","chinese_traditional"],"若":["chinese_simplified","chinese_traditional"],"印":["chinese_simplified","chinese_traditional"],"洲":["chinese_simplified","chinese_traditional"],"刻":["chinese_simplified","chinese_traditional"],"括":["chinese_simplified","chinese_traditional"],"激":["chinese_simplified","chinese_traditional"],"孔":["chinese_simplified","chinese_traditional"],"搞":["chinese_simplified","chinese_traditional"],"甚":["chinese_simplified","chinese_traditional"],"室":["chinese_simplified","chinese_traditional"],"待":["chinese_simplified","chinese_traditional"],"核":["chinese_simplified","chinese_traditional"],"校":["chinese_simplified","chinese_traditional"],"散":["chinese_simplified","chinese_traditional"],"侵":["chinese_simplified","chinese_traditional"],"吧":["chinese_simplified","chinese_traditional"],"甲":["chinese_simplified","chinese_traditional"],"游":["chinese_simplified"],"久":["chinese_simplified","chinese_traditional"],"菜":["chinese_simplified","chinese_traditional"],"味":["chinese_simplified","chinese_traditional"],"旧":["chinese_simplified"],"模":["chinese_simplified","chinese_traditional"],"湖":["chinese_simplified","chinese_traditional"],"货":["chinese_simplified"],"损":["chinese_simplified"],"预":["chinese_simplified"],"阻":["chinese_simplified","chinese_traditional"],"毫":["chinese_simplified","chinese_traditional"],"普":["chinese_simplified","chinese_traditional"],"稳":["chinese_simplified"],"乙":["chinese_simplified","chinese_traditional"],"妈":["chinese_simplified"],"植":["chinese_simplified","chinese_traditional"],"息":["chinese_simplified","chinese_traditional"],"扩":["chinese_simplified"],"银":["chinese_simplified"],"语":["chinese_simplified"],"挥":["chinese_simplified"],"酒":["chinese_simplified","chinese_traditional"],"守":["chinese_simplified","chinese_traditional"],"拿":["chinese_simplified","chinese_traditional"],"序":["chinese_simplified","chinese_traditional"],"纸":["chinese_simplified"],"医":["chinese_simplified"],"缺":["chinese_simplified","chinese_traditional"],"雨":["chinese_simplified","chinese_traditional"],"吗":["chinese_simplified"],"针":["chinese_simplified"],"刘":["chinese_simplified"],"啊":["chinese_simplified","chinese_traditional"],"急":["chinese_simplified","chinese_traditional"],"唱":["chinese_simplified","chinese_traditional"],"误":["chinese_simplified"],"训":["chinese_simplified"],"愿":["chinese_simplified"],"审":["chinese_simplified"],"附":["chinese_simplified","chinese_traditional"],"获":["chinese_simplified"],"茶":["chinese_simplified","chinese_traditional"],"鲜":["chinese_simplified"],"粮":["chinese_simplified"],"斤":["chinese_simplified","chinese_traditional"],"孩":["chinese_simplified","chinese_traditional"],"脱":["chinese_simplified"],"硫":["chinese_simplified","chinese_traditional"],"肥":["chinese_simplified","chinese_traditional"],"善":["chinese_simplified","chinese_traditional"],"龙":["chinese_simplified"],"演":["chinese_simplified","chinese_traditional"],"父":["chinese_simplified","chinese_traditional"],"渐":["chinese_simplified"],"血":["chinese_simplified","chinese_traditional"],"欢":["chinese_simplified"],"械":["chinese_simplified","chinese_traditional"],"掌":["chinese_simplified","chinese_traditional"],"歌":["chinese_simplified","chinese_traditional"],"沙":["chinese_simplified","chinese_traditional"],"刚":["chinese_simplified"],"攻":["chinese_simplified","chinese_traditional"],"谓":["chinese_simplified"],"盾":["chinese_simplified","chinese_traditional"],"讨":["chinese_simplified"],"晚":["chinese_simplified","chinese_traditional"],"粒":["chinese_simplified","chinese_traditional"],"乱":["chinese_simplified"],"燃":["chinese_simplified","chinese_traditional"],"矛":["chinese_simplified","chinese_traditional"],"乎":["chinese_simplified","chinese_traditional"],"杀":["chinese_simplified"],"药":["chinese_simplified"],"宁":["chinese_simplified"],"鲁":["chinese_simplified"],"贵":["chinese_simplified"],"钟":["chinese_simplified"],"煤":["chinese_simplified","chinese_traditional"],"读":["chinese_simplified"],"班":["chinese_simplified","chinese_traditional"],"伯":["chinese_simplified","chinese_traditional"],"香":["chinese_simplified","chinese_traditional"],"介":["chinese_simplified","chinese_traditional"],"迫":["chinese_simplified","chinese_traditional"],"句":["chinese_simplified","chinese_traditional"],"丰":["chinese_simplified"],"培":["chinese_simplified","chinese_traditional"],"握":["chinese_simplified","chinese_traditional"],"兰":["chinese_simplified"],"担":["chinese_simplified"],"弦":["chinese_simplified","chinese_traditional"],"蛋":["chinese_simplified","chinese_traditional"],"沉":["chinese_simplified","chinese_traditional"],"假":["chinese_simplified","chinese_traditional"],"穿":["chinese_simplified","chinese_traditional"],"执":["chinese_simplified"],"答":["chinese_simplified","chinese_traditional"],"乐":["chinese_simplified"],"谁":["chinese_simplified"],"顺":["chinese_simplified"],"烟":["chinese_simplified"],"缩":["chinese_simplified"],"征":["chinese_simplified"],"脸":["chinese_simplified"],"喜":["chinese_simplified","chinese_traditional"],"松":["chinese_simplified","chinese_traditional"],"脚":["chinese_simplified"],"困":["chinese_simplified","chinese_traditional"],"异":["chinese_simplified"],"免":["chinese_simplified","chinese_traditional"],"背":["chinese_simplified","chinese_traditional"],"星":["chinese_simplified","chinese_traditional"],"福":["chinese_simplified","chinese_traditional"],"买":["chinese_simplified"],"染":["chinese_simplified","chinese_traditional"],"井":["chinese_simplified","chinese_traditional"],"概":["chinese_simplified","chinese_traditional"],"慢":["chinese_simplified","chinese_traditional"],"怕":["chinese_simplified","chinese_traditional"],"磁":["chinese_simplified","chinese_traditional"],"倍":["chinese_simplified","chinese_traditional"],"祖":["chinese_simplified","chinese_traditional"],"皇":["chinese_simplified","chinese_traditional"],"促":["chinese_simplified","chinese_traditional"],"静":["chinese_simplified"],"补":["chinese_simplified"],"评":["chinese_simplified"],"翻":["chinese_simplified","chinese_traditional"],"肉":["chinese_simplified","chinese_traditional"],"践":["chinese_simplified"],"尼":["chinese_simplified","chinese_traditional"],"衣":["chinese_simplified","chinese_traditional"],"宽":["chinese_simplified"],"扬":["chinese_simplified"],"棉":["chinese_simplified","chinese_traditional"],"希":["chinese_simplified","chinese_traditional"],"伤":["chinese_simplified"],"操":["chinese_simplified","chinese_traditional"],"垂":["chinese_simplified","chinese_traditional"],"秋":["chinese_simplified","chinese_traditional"],"宜":["chinese_simplified","chinese_traditional"],"氢":["chinese_simplified"],"套":["chinese_simplified","chinese_traditional"],"督":["chinese_simplified","chinese_traditional"],"振":["chinese_simplified","chinese_traditional"],"架":["chinese_simplified","chinese_traditional"],"亮":["chinese_simplified","chinese_traditional"],"末":["chinese_simplified","chinese_traditional"],"宪":["chinese_simplified"],"庆":["chinese_simplified"],"编":["chinese_simplified"],"牛":["chinese_simplified","chinese_traditional"],"触":["chinese_simplified"],"映":["chinese_simplified","chinese_traditional"],"雷":["chinese_simplified","chinese_traditional"],"销":["chinese_simplified"],"诗":["chinese_simplified"],"座":["chinese_simplified","chinese_traditional"],"居":["chinese_simplified","chinese_traditional"],"抓":["chinese_simplified","chinese_traditional"],"裂":["chinese_simplified","chinese_traditional"],"胞":["chinese_simplified","chinese_traditional"],"呼":["chinese_simplified","chinese_traditional"],"娘":["chinese_simplified","chinese_traditional"],"景":["chinese_simplified","chinese_traditional"],"威":["chinese_simplified","chinese_traditional"],"绿":["chinese_simplified"],"晶":["chinese_simplified","chinese_traditional"],"厚":["chinese_simplified","chinese_traditional"],"盟":["chinese_simplified","chinese_traditional"],"衡":["chinese_simplified","chinese_traditional"],"鸡":["chinese_simplified"],"孙":["chinese_simplified"],"延":["chinese_simplified","chinese_traditional"],"危":["chinese_simplified","chinese_traditional"],"胶":["chinese_simplified"],"屋":["chinese_simplified","chinese_traditional"],"乡":["chinese_simplified"],"临":["chinese_simplified"],"陆":["chinese_simplified"],"顾":["chinese_simplified"],"掉":["chinese_simplified","chinese_traditional"],"呀":["chinese_simplified","chinese_traditional"],"灯":["chinese_simplified"],"岁":["chinese_simplified"],"措":["chinese_simplified","chinese_traditional"],"束":["chinese_simplified","chinese_traditional"],"耐":["chinese_simplified","chinese_traditional"],"剧":["chinese_simplified"],"玉":["chinese_simplified","chinese_traditional"],"赵":["chinese_simplified"],"跳":["chinese_simplified","chinese_traditional"],"哥":["chinese_simplified","chinese_traditional"],"季":["chinese_simplified","chinese_traditional"],"课":["chinese_simplified"],"凯":["chinese_simplified"],"胡":["chinese_simplified","chinese_traditional"],"额":["chinese_simplified"],"款":["chinese_simplified","chinese_traditional"],"绍":["chinese_simplified"],"卷":["chinese_simplified","chinese_traditional"],"齐":["chinese_simplified"],"伟":["chinese_simplified"],"蒸":["chinese_simplified","chinese_traditional"],"殖":["chinese_simplified","chinese_traditional"],"永":["chinese_simplified","chinese_traditional"],"宗":["chinese_simplified","chinese_traditional"],"苗":["chinese_simplified","chinese_traditional"],"川":["chinese_simplified","chinese_traditional"],"炉":["chinese_simplified"],"岩":["chinese_simplified","chinese_traditional"],"弱":["chinese_simplified","chinese_traditional"],"零":["chinese_simplified","chinese_traditional"],"杨":["chinese_simplified"],"奏":["chinese_simplified","chinese_traditional"],"沿":["chinese_simplified","chinese_traditional"],"露":["chinese_simplified","chinese_traditional"],"杆":["chinese_simplified"],"探":["chinese_simplified","chinese_traditional"],"滑":["chinese_simplified","chinese_traditional"],"镇":["chinese_simplified"],"饭":["chinese_simplified"],"浓":["chinese_simplified"],"航":["chinese_simplified","chinese_traditional"],"怀":["chinese_simplified"],"赶":["chinese_simplified"],"库":["chinese_simplified"],"夺":["chinese_simplified"],"伊":["chinese_simplified","chinese_traditional"],"灵":["chinese_simplified"],"税":["chinese_simplified"],"途":["chinese_simplified","chinese_traditional"],"灭":["chinese_simplified"],"赛":["chinese_simplified"],"归":["chinese_simplified"],"召":["chinese_simplified","chinese_traditional"],"鼓":["chinese_simplified","chinese_traditional"],"播":["chinese_simplified","chinese_traditional"],"盘":["chinese_simplified"],"裁":["chinese_simplified","chinese_traditional"],"险":["chinese_simplified"],"康":["chinese_simplified","chinese_traditional"],"唯":["chinese_simplified","chinese_traditional"],"录":["chinese_simplified"],"菌":["chinese_simplified","chinese_traditional"],"纯":["chinese_simplified"],"借":["chinese_simplified","chinese_traditional"],"糖":["chinese_simplified","chinese_traditional"],"盖":["chinese_simplified"],"横":["chinese_simplified"],"符":["chinese_simplified","chinese_traditional"],"私":["chinese_simplified","chinese_traditional"],"努":["chinese_simplified","chinese_traditional"],"堂":["chinese_simplified","chinese_traditional"],"域":["chinese_simplified","chinese_traditional"],"枪":["chinese_simplified"],"润":["chinese_simplified"],"幅":["chinese_simplified","chinese_traditional"],"哈":["chinese_simplified","chinese_traditional"],"竟":["chinese_simplified","chinese_traditional"],"熟":["chinese_simplified","chinese_traditional"],"虫":["chinese_simplified"],"泽":["chinese_simplified"],"脑":["chinese_simplified"],"壤":["chinese_simplified","chinese_traditional"],"碳":["chinese_simplified","chinese_traditional"],"欧":["chinese_simplified"],"遍":["chinese_simplified","chinese_traditional"],"侧":["chinese_simplified"],"寨":["chinese_simplified","chinese_traditional"],"敢":["chinese_simplified","chinese_traditional"],"彻":["chinese_simplified"],"虑":["chinese_simplified"],"斜":["chinese_simplified","chinese_traditional"],"薄":["chinese_simplified","chinese_traditional"],"庭":["chinese_simplified","chinese_traditional"],"纳":["chinese_simplified"],"弹":["chinese_simplified"],"饲":["chinese_simplified"],"伸":["chinese_simplified","chinese_traditional"],"折":["chinese_simplified","chinese_traditional"],"麦":["chinese_simplified"],"湿":["chinese_simplified"],"暗":["chinese_simplified","chinese_traditional"],"荷":["chinese_simplified","chinese_traditional"],"瓦":["chinese_simplified","chinese_traditional"],"塞":["chinese_simplified","chinese_traditional"],"床":["chinese_simplified","chinese_traditional"],"筑":["chinese_simplified"],"恶":["chinese_simplified"],"户":["chinese_simplified"],"访":["chinese_simplified"],"塔":["chinese_simplified","chinese_traditional"],"奇":["chinese_simplified","chinese_traditional"],"透":["chinese_simplified","chinese_traditional"],"梁":["chinese_simplified","chinese_traditional"],"刀":["chinese_simplified","chinese_traditional"],"旋":["chinese_simplified","chinese_traditional"],"迹":["chinese_simplified"],"卡":["chinese_simplified","chinese_traditional"],"氯":["chinese_simplified","chinese_traditional"],"遇":["chinese_simplified","chinese_traditional"],"份":["chinese_simplified","chinese_traditional"],"毒":["chinese_simplified","chinese_traditional"],"泥":["chinese_simplified","chinese_traditional"],"退":["chinese_simplified","chinese_traditional"],"洗":["chinese_simplified","chinese_traditional"],"摆":["chinese_simplified"],"灰":["chinese_simplified","chinese_traditional"],"彩":["chinese_simplified","chinese_traditional"],"卖":["chinese_simplified"],"耗":["chinese_simplified","chinese_traditional"],"夏":["chinese_simplified","chinese_traditional"],"择":["chinese_simplified"],"忙":["chinese_simplified","chinese_traditional"],"铜":["chinese_simplified"],"献":["chinese_simplified"],"硬":["chinese_simplified","chinese_traditional"],"予":["chinese_simplified","chinese_traditional"],"繁":["chinese_simplified","chinese_traditional"],"圈":["chinese_simplified","chinese_traditional"],"雪":["chinese_simplified","chinese_traditional"],"函":["chinese_simplified","chinese_traditional"],"亦":["chinese_simplified","chinese_traditional"],"抽":["chinese_simplified","chinese_traditional"],"篇":["chinese_simplified","chinese_traditional"],"阵":["chinese_simplified"],"阴":["chinese_simplified"],"丁":["chinese_simplified","chinese_traditional"],"尺":["chinese_simplified","chinese_traditional"],"追":["chinese_simplified","chinese_traditional"],"堆":["chinese_simplified","chinese_traditional"],"雄":["chinese_simplified","chinese_traditional"],"迎":["chinese_simplified","chinese_traditional"],"泛":["chinese_simplified","chinese_traditional"],"爸":["chinese_simplified","chinese_traditional"],"楼":["chinese_simplified"],"避":["chinese_simplified","chinese_traditional"],"谋":["chinese_simplified"],"吨":["chinese_simplified"],"野":["chinese_simplified","chinese_traditional"],"猪":["chinese_simplified"],"旗":["chinese_simplified","chinese_traditional"],"累":["chinese_simplified","chinese_traditional"],"偏":["chinese_simplified","chinese_traditional"],"典":["chinese_simplified","chinese_traditional"],"馆":["chinese_simplified"],"索":["chinese_simplified","chinese_traditional"],"秦":["chinese_simplified","chinese_traditional"],"脂":["chinese_simplified","chinese_traditional"],"潮":["chinese_simplified","chinese_traditional"],"爷":["chinese_simplified"],"豆":["chinese_simplified","chinese_traditional"],"忽":["chinese_simplified","chinese_traditional"],"托":["chinese_simplified","chinese_traditional"],"惊":["chinese_simplified"],"塑":["chinese_simplified","chinese_traditional"],"遗":["chinese_simplified"],"愈":["chinese_simplified","chinese_traditional"],"朱":["chinese_simplified","chinese_traditional"],"替":["chinese_simplified","chinese_traditional"],"纤":["chinese_simplified"],"粗":["chinese_simplified","chinese_traditional"],"倾":["chinese_simplified"],"尚":["chinese_simplified","chinese_traditional"],"痛":["chinese_simplified","chinese_traditional"],"楚":["chinese_simplified","chinese_traditional"],"谢":["chinese_simplified"],"奋":["chinese_simplified"],"购":["chinese_simplified"],"磨":["chinese_simplified","chinese_traditional"],"君":["chinese_simplified","chinese_traditional"],"池":["chinese_simplified","chinese_traditional"],"旁":["chinese_simplified","chinese_traditional"],"碎":["chinese_simplified","chinese_traditional"],"骨":["chinese_simplified","chinese_traditional"],"监":["chinese_simplified"],"捕":["chinese_simplified","chinese_traditional"],"弟":["chinese_simplified","chinese_traditional"],"暴":["chinese_simplified","chinese_traditional"],"割":["chinese_simplified","chinese_traditional"],"贯":["chinese_simplified"],"殊":["chinese_simplified","chinese_traditional"],"释":["chinese_simplified"],"词":["chinese_simplified"],"亡":["chinese_simplified","chinese_traditional"],"壁":["chinese_simplified","chinese_traditional"],"顿":["chinese_simplified"],"宝":["chinese_simplified"],"午":["chinese_simplified","chinese_traditional"],"尘":["chinese_simplified"],"闻":["chinese_simplified"],"揭":["chinese_simplified","chinese_traditional"],"炮":["chinese_simplified","chinese_traditional"],"残":["chinese_simplified"],"冬":["chinese_simplified","chinese_traditional"],"桥":["chinese_simplified"],"妇":["chinese_simplified"],"警":["chinese_simplified","chinese_traditional"],"综":["chinese_simplified"],"招":["chinese_simplified","chinese_traditional"],"吴":["chinese_simplified"],"付":["chinese_simplified","chinese_traditional"],"浮":["chinese_simplified","chinese_traditional"],"遭":["chinese_simplified","chinese_traditional"],"徐":["chinese_simplified","chinese_traditional"],"您":["chinese_simplified","chinese_traditional"],"摇":["chinese_simplified"],"谷":["chinese_simplified","chinese_traditional"],"赞":["chinese_simplified"],"箱":["chinese_simplified","chinese_traditional"],"隔":["chinese_simplified","chinese_traditional"],"订":["chinese_simplified"],"男":["chinese_simplified","chinese_traditional"],"吹":["chinese_simplified","chinese_traditional"],"园":["chinese_simplified"],"纷":["chinese_simplified"],"唐":["chinese_simplified","chinese_traditional"],"败":["chinese_simplified"],"宋":["chinese_simplified","chinese_traditional"],"玻":["chinese_simplified","chinese_traditional"],"巨":["chinese_simplified","chinese_traditional"],"耕":["chinese_simplified","chinese_traditional"],"坦":["chinese_simplified","chinese_traditional"],"荣":["chinese_simplified"],"闭":["chinese_simplified"],"湾":["chinese_simplified"],"键":["chinese_simplified"],"凡":["chinese_simplified","chinese_traditional"],"驻":["chinese_simplified"],"锅":["chinese_simplified"],"救":["chinese_simplified","chinese_traditional"],"恩":["chinese_simplified","chinese_traditional"],"剥":["chinese_simplified"],"凝":["chinese_simplified","chinese_traditional"],"碱":["chinese_simplified"],"齿":["chinese_simplified"],"截":["chinese_simplified","chinese_traditional"],"炼":["chinese_simplified"],"麻":["chinese_simplified","chinese_traditional"],"纺":["chinese_simplified"],"禁":["chinese_simplified","chinese_traditional"],"废":["chinese_simplified"],"盛":["chinese_simplified","chinese_traditional"],"版":["chinese_simplified","chinese_traditional"],"缓":["chinese_simplified"],"净":["chinese_simplified"],"睛":["chinese_simplified","chinese_traditional"],"昌":["chinese_simplified","chinese_traditional"],"婚":["chinese_simplified","chinese_traditional"],"涉":["chinese_simplified","chinese_traditional"],"筒":["chinese_simplified","chinese_traditional"],"嘴":["chinese_simplified","chinese_traditional"],"插":["chinese_simplified","chinese_traditional"],"岸":["chinese_simplified","chinese_traditional"],"朗":["chinese_simplified","chinese_traditional"],"庄":["chinese_simplified"],"街":["chinese_simplified","chinese_traditional"],"藏":["chinese_simplified","chinese_traditional"],"姑":["chinese_simplified","chinese_traditional"],"贸":["chinese_simplified"],"腐":["chinese_simplified","chinese_traditional"],"奴":["chinese_simplified","chinese_traditional"],"啦":["chinese_simplified","chinese_traditional"],"惯":["chinese_simplified"],"乘":["chinese_simplified","chinese_traditional"],"伙":["chinese_simplified"],"恢":["chinese_simplified","chinese_traditional"],"匀":["chinese_simplified"],"纱":["chinese_simplified"],"扎":["chinese_simplified","chinese_traditional"],"辩":["chinese_simplified"],"耳":["chinese_simplified","chinese_traditional"],"彪":["chinese_simplified","chinese_traditional"],"臣":["chinese_simplified","chinese_traditional"],"亿":["chinese_simplified"],"璃":["chinese_simplified","chinese_traditional"],"抵":["chinese_simplified","chinese_traditional"],"脉":["chinese_simplified"],"秀":["chinese_simplified","chinese_traditional"],"萨":["chinese_simplified"],"俄":["chinese_simplified","chinese_traditional"],"网":["chinese_simplified"],"舞":["chinese_simplified","chinese_traditional"],"店":["chinese_simplified","chinese_traditional"],"喷":["chinese_simplified"],"纵":["chinese_simplified"],"寸":["chinese_simplified","chinese_traditional"],"汗":["chinese_simplified","chinese_traditional"],"挂":["chinese_simplified"],"洪":["chinese_simplified","chinese_traditional"],"贺":["chinese_simplified"],"闪":["chinese_simplified"],"柬":["chinese_simplified","chinese_traditional"],"爆":["chinese_simplified","chinese_traditional"],"烯":["chinese_simplified","chinese_traditional"],"津":["chinese_simplified","chinese_traditional"],"稻":["chinese_simplified","chinese_traditional"],"墙":["chinese_simplified"],"软":["chinese_simplified"],"勇":["chinese_simplified","chinese_traditional"],"像":["chinese_simplified","chinese_traditional"],"滚":["chinese_simplified"],"厘":["chinese_simplified","chinese_traditional"],"蒙":["chinese_simplified","chinese_traditional"],"芳":["chinese_simplified","chinese_traditional"],"肯":["chinese_simplified","chinese_traditional"],"坡":["chinese_simplified","chinese_traditional"],"柱":["chinese_simplified","chinese_traditional"],"荡":["chinese_simplified"],"腿":["chinese_simplified","chinese_traditional"],"仪":["chinese_simplified"],"旅":["chinese_simplified","chinese_traditional"],"尾":["chinese_simplified","chinese_traditional"],"轧":["chinese_simplified"],"冰":["chinese_simplified","chinese_traditional"],"贡":["chinese_simplified"],"登":["chinese_simplified","chinese_traditional"],"黎":["chinese_simplified","chinese_traditional"],"削":["chinese_simplified","chinese_traditional"],"钻":["chinese_simplified"],"勒":["chinese_simplified","chinese_traditional"],"逃":["chinese_simplified","chinese_traditional"],"障":["chinese_simplified","chinese_traditional"],"氨":["chinese_simplified","chinese_traditional"],"郭":["chinese_simplified","chinese_traditional"],"峰":["chinese_simplified","chinese_traditional"],"币":["chinese_simplified"],"港":["chinese_simplified","chinese_traditional"],"伏":["chinese_simplified","chinese_traditional"],"轨":["chinese_simplified"],"亩":["chinese_simplified"],"毕":["chinese_simplified"],"擦":["chinese_simplified","chinese_traditional"],"莫":["chinese_simplified","chinese_traditional"],"刺":["chinese_simplified","chinese_traditional"],"浪":["chinese_simplified","chinese_traditional"],"秘":["chinese_simplified","chinese_traditional"],"援":["chinese_simplified","chinese_traditional"],"株":["chinese_simplified","chinese_traditional"],"健":["chinese_simplified","chinese_traditional"],"售":["chinese_simplified","chinese_traditional"],"股":["chinese_simplified","chinese_traditional"],"岛":["chinese_simplified"],"甘":["chinese_simplified","chinese_traditional"],"泡":["chinese_simplified","chinese_traditional"],"睡":["chinese_simplified","chinese_traditional"],"童":["chinese_simplified","chinese_traditional"],"铸":["chinese_simplified"],"汤":["chinese_simplified"],"阀":["chinese_simplified"],"休":["chinese_simplified","chinese_traditional"],"汇":["chinese_simplified"],"舍":["chinese_simplified","chinese_traditional"],"牧":["chinese_simplified","chinese_traditional"],"绕":["chinese_simplified"],"炸":["chinese_simplified","chinese_traditional"],"哲":["chinese_simplified","chinese_traditional"],"磷":["chinese_simplified","chinese_traditional"],"绩":["chinese_simplified"],"朋":["chinese_simplified","chinese_traditional"],"淡":["chinese_simplified","chinese_traditional"],"尖":["chinese_simplified","chinese_traditional"],"启":["chinese_simplified"],"陷":["chinese_simplified","chinese_traditional"],"柴":["chinese_simplified","chinese_traditional"],"呈":["chinese_simplified","chinese_traditional"],"徒":["chinese_simplified","chinese_traditional"],"颜":["chinese_simplified"],"泪":["chinese_simplified"],"稍":["chinese_simplified","chinese_traditional"],"忘":["chinese_simplified","chinese_traditional"],"泵":["chinese_simplified","chinese_traditional"],"蓝":["chinese_simplified"],"拖":["chinese_simplified","chinese_traditional"],"洞":["chinese_simplified","chinese_traditional"],"授":["chinese_simplified","chinese_traditional"],"镜":["chinese_simplified"],"辛":["chinese_simplified","chinese_traditional"],"壮":["chinese_simplified"],"锋":["chinese_simplified"],"贫":["chinese_simplified"],"虚":["chinese_simplified"],"弯":["chinese_simplified"],"摩":["chinese_simplified","chinese_traditional"],"泰":["chinese_simplified","chinese_traditional"],"幼":["chinese_simplified","chinese_traditional"],"廷":["chinese_simplified","chinese_traditional"],"尊":["chinese_simplified","chinese_traditional"],"窗":["chinese_simplified","chinese_traditional"],"纲":["chinese_simplified"],"弄":["chinese_simplified","chinese_traditional"],"隶":["chinese_simplified"],"疑":["chinese_simplified","chinese_traditional"],"氏":["chinese_simplified","chinese_traditional"],"宫":["chinese_simplified"],"姐":["chinese_simplified","chinese_traditional"],"震":["chinese_simplified","chinese_traditional"],"瑞":["chinese_simplified","chinese_traditional"],"怪":["chinese_simplified","chinese_traditional"],"尤":["chinese_simplified","chinese_traditional"],"琴":["chinese_simplified","chinese_traditional"],"循":["chinese_simplified","chinese_traditional"],"描":["chinese_simplified","chinese_traditional"],"膜":["chinese_simplified","chinese_traditional"],"违":["chinese_simplified"],"夹":["chinese_simplified"],"腰":["chinese_simplified","chinese_traditional"],"缘":["chinese_simplified"],"珠":["chinese_simplified","chinese_traditional"],"穷":["chinese_simplified"],"森":["chinese_simplified","chinese_traditional"],"枝":["chinese_simplified","chinese_traditional"],"竹":["chinese_simplified","chinese_traditional"],"沟":["chinese_simplified"],"催":["chinese_simplified","chinese_traditional"],"绳":["chinese_simplified"],"忆":["chinese_simplified"],"邦":["chinese_simplified","chinese_traditional"],"剩":["chinese_simplified","chinese_traditional"],"幸":["chinese_simplified","chinese_traditional"],"浆":["chinese_simplified"],"栏":["chinese_simplified"],"拥":["chinese_simplified"],"牙":["chinese_simplified","chinese_traditional"],"贮":["chinese_simplified"],"礼":["chinese_simplified"],"滤":["chinese_simplified"],"钠":["chinese_simplified"],"纹":["chinese_simplified"],"罢":["chinese_simplified"],"拍":["chinese_simplified","chinese_traditional"],"咱":["chinese_simplified","chinese_traditional"],"喊":["chinese_simplified","chinese_traditional"],"袖":["chinese_simplified","chinese_traditional"],"埃":["chinese_simplified","chinese_traditional"],"勤":["chinese_simplified","chinese_traditional"],"罚":["chinese_simplified"],"焦":["chinese_simplified","chinese_traditional"],"潜":["chinese_simplified"],"伍":["chinese_simplified","chinese_traditional"],"墨":["chinese_simplified","chinese_traditional"],"欲":["chinese_simplified","chinese_traditional"],"缝":["chinese_simplified"],"姓":["chinese_simplified","chinese_traditional"],"刊":["chinese_simplified","chinese_traditional"],"饱":["chinese_simplified"],"仿":["chinese_simplified","chinese_traditional"],"奖":["chinese_simplified"],"铝":["chinese_simplified"],"鬼":["chinese_simplified","chinese_traditional"],"丽":["chinese_simplified"],"跨":["chinese_simplified","chinese_traditional"],"默":["chinese_simplified","chinese_traditional"],"挖":["chinese_simplified","chinese_traditional"],"链":["chinese_simplified"],"扫":["chinese_simplified"],"喝":["chinese_simplified","chinese_traditional"],"袋":["chinese_simplified","chinese_traditional"],"炭":["chinese_simplified","chinese_traditional"],"污":["chinese_simplified","chinese_traditional"],"幕":["chinese_simplified","chinese_traditional"],"诸":["chinese_simplified"],"弧":["chinese_simplified","chinese_traditional"],"励":["chinese_simplified"],"梅":["chinese_simplified","chinese_traditional"],"奶":["chinese_simplified","chinese_traditional"],"洁":["chinese_simplified"],"灾":["chinese_simplified"],"舟":["chinese_simplified","chinese_traditional"],"鉴":["chinese_simplified"],"苯":["chinese_simplified","chinese_traditional"],"讼":["chinese_simplified"],"抱":["chinese_simplified","chinese_traditional"],"毁":["chinese_simplified"],"懂":["chinese_simplified","chinese_traditional"],"寒":["chinese_simplified","chinese_traditional"],"智":["chinese_simplified","chinese_traditional"],"埔":["chinese_simplified","chinese_traditional"],"寄":["chinese_simplified","chinese_traditional"],"届":["chinese_simplified"],"跃":["chinese_simplified"],"渡":["chinese_simplified","chinese_traditional"],"挑":["chinese_simplified","chinese_traditional"],"丹":["chinese_simplified","chinese_traditional"],"艰":["chinese_simplified"],"贝":["chinese_simplified"],"碰":["chinese_simplified","chinese_traditional"],"拔":["chinese_simplified","chinese_traditional"],"爹":["chinese_simplified","chinese_traditional"],"戴":["chinese_simplified","chinese_traditional"],"码":["chinese_simplified"],"梦":["chinese_simplified"],"芽":["chinese_simplified","chinese_traditional"],"熔":["chinese_simplified","chinese_traditional"],"赤":["chinese_simplified","chinese_traditional"],"渔":["chinese_simplified"],"哭":["chinese_simplified","chinese_traditional"],"敬":["chinese_simplified","chinese_traditional"],"颗":["chinese_simplified"],"奔":["chinese_simplified","chinese_traditional"],"铅":["chinese_simplified"],"仲":["chinese_simplified","chinese_traditional"],"虎":["chinese_simplified","chinese_traditional"],"稀":["chinese_simplified","chinese_traditional"],"妹":["chinese_simplified","chinese_traditional"],"乏":["chinese_simplified","chinese_traditional"],"珍":["chinese_simplified","chinese_traditional"],"申":["chinese_simplified","chinese_traditional"],"桌":["chinese_simplified","chinese_traditional"],"遵":["chinese_simplified","chinese_traditional"],"允":["chinese_simplified","chinese_traditional"],"隆":["chinese_simplified","chinese_traditional"],"螺":["chinese_simplified","chinese_traditional"],"仓":["chinese_simplified"],"魏":["chinese_simplified","chinese_traditional"],"锐":["chinese_simplified"],"晓":["chinese_simplified"],"氮":["chinese_simplified","chinese_traditional"],"兼":["chinese_simplified","chinese_traditional"],"隐":["chinese_simplified"],"碍":["chinese_simplified"],"赫":["chinese_simplified","chinese_traditional"],"拨":["chinese_simplified"],"忠":["chinese_simplified","chinese_traditional"],"肃":["chinese_simplified"],"缸":["chinese_simplified","chinese_traditional"],"牵":["chinese_simplified"],"抢":["chinese_simplified"],"博":["chinese_simplified","chinese_traditional"],"巧":["chinese_simplified","chinese_traditional"],"壳":["chinese_simplified"],"兄":["chinese_simplified","chinese_traditional"],"杜":["chinese_simplified","chinese_traditional"],"讯":["chinese_simplified"],"诚":["chinese_simplified"],"碧":["chinese_simplified","chinese_traditional"],"祥":["chinese_simplified","chinese_traditional"],"柯":["chinese_simplified","chinese_traditional"],"页":["chinese_simplified"],"巡":["chinese_simplified","chinese_traditional"],"矩":["chinese_simplified","chinese_traditional"],"悲":["chinese_simplified","chinese_traditional"],"灌":["chinese_simplified","chinese_traditional"],"龄":["chinese_simplified"],"伦":["chinese_simplified"],"票":["chinese_simplified","chinese_traditional"],"寻":["chinese_simplified"],"桂":["chinese_simplified","chinese_traditional"],"铺":["chinese_simplified"],"圣":["chinese_simplified"],"恐":["chinese_simplified","chinese_traditional"],"恰":["chinese_simplified","chinese_traditional"],"郑":["chinese_simplified"],"趣":["chinese_simplified","chinese_traditional"],"抬":["chinese_simplified","chinese_traditional"],"荒":["chinese_simplified","chinese_traditional"],"腾":["chinese_simplified"],"贴":["chinese_simplified"],"柔":["chinese_simplified","chinese_traditional"],"滴":["chinese_simplified","chinese_traditional"],"猛":["chinese_simplified","chinese_traditional"],"阔":["chinese_simplified"],"辆":["chinese_simplified"],"妻":["chinese_simplified","chinese_traditional"],"填":["chinese_simplified","chinese_traditional"],"撤":["chinese_simplified","chinese_traditional"],"储":["chinese_simplified"],"签":["chinese_simplified"],"闹":["chinese_simplified"],"扰":["chinese_simplified"],"紫":["chinese_simplified","chinese_traditional"],"砂":["chinese_simplified","chinese_traditional"],"递":["chinese_simplified"],"戏":["chinese_simplified"],"吊":["chinese_simplified","chinese_traditional"],"陶":["chinese_simplified","chinese_traditional"],"伐":["chinese_simplified","chinese_traditional"],"喂":["chinese_simplified"],"疗":["chinese_simplified"],"瓶":["chinese_simplified","chinese_traditional"],"婆":["chinese_simplified","chinese_traditional"],"抚":["chinese_simplified"],"臂":["chinese_simplified","chinese_traditional"],"摸":["chinese_simplified","chinese_traditional"],"忍":["chinese_simplified","chinese_traditional"],"虾":["chinese_simplified"],"蜡":["chinese_simplified"],"邻":["chinese_simplified"],"胸":["chinese_simplified","chinese_traditional"],"巩":["chinese_simplified"],"挤":["chinese_simplified"],"偶":["chinese_simplified","chinese_traditional"],"弃":["chinese_simplified"],"槽":["chinese_simplified","chinese_traditional"],"劲":["chinese_simplified"],"乳":["chinese_simplified","chinese_traditional"],"邓":["chinese_simplified"],"吉":["chinese_simplified","chinese_traditional"],"仁":["chinese_simplified","chinese_traditional"],"烂":["chinese_simplified"],"砖":["chinese_simplified"],"租":["chinese_simplified","chinese_traditional"],"乌":["chinese_simplified"],"舰":["chinese_simplified"],"伴":["chinese_simplified","chinese_traditional"],"瓜":["chinese_simplified","chinese_traditional"],"浅":["chinese_simplified"],"丙":["chinese_simplified","chinese_traditional"],"暂":["chinese_simplified"],"燥":["chinese_simplified","chinese_traditional"],"橡":["chinese_simplified","chinese_traditional"],"柳":["chinese_simplified","chinese_traditional"],"迷":["chinese_simplified","chinese_traditional"],"暖":["chinese_simplified","chinese_traditional"],"牌":["chinese_simplified","chinese_traditional"],"秧":["chinese_simplified","chinese_traditional"],"胆":["chinese_simplified"],"详":["chinese_simplified"],"簧":["chinese_simplified","chinese_traditional"],"踏":["chinese_simplified","chinese_traditional"],"瓷":["chinese_simplified","chinese_traditional"],"谱":["chinese_simplified"],"呆":["chinese_simplified","chinese_traditional"],"宾":["chinese_simplified"],"糊":["chinese_simplified","chinese_traditional"],"洛":["chinese_simplified","chinese_traditional"],"辉":["chinese_simplified"],"愤":["chinese_simplified"],"竞":["chinese_simplified"],"隙":["chinese_simplified","chinese_traditional"],"怒":["chinese_simplified","chinese_traditional"],"粘":["chinese_simplified","chinese_traditional"],"乃":["chinese_simplified","chinese_traditional"],"绪":["chinese_simplified"],"肩":["chinese_simplified","chinese_traditional"],"籍":["chinese_simplified","chinese_traditional"],"敏":["chinese_simplified","chinese_traditional"],"涂":["chinese_simplified"],"熙":["chinese_simplified","chinese_traditional"],"皆":["chinese_simplified","chinese_traditional"],"侦":["chinese_simplified"],"悬":["chinese_simplified"],"掘":["chinese_simplified","chinese_traditional"],"享":["chinese_simplified","chinese_traditional"],"纠":["chinese_simplified"],"醒":["chinese_simplified","chinese_traditional"],"狂":["chinese_simplified","chinese_traditional"],"锁":["chinese_simplified"],"淀":["chinese_simplified","chinese_traditional"],"恨":["chinese_simplified","chinese_traditional"],"牲":["chinese_simplified","chinese_traditional"],"霸":["chinese_simplified","chinese_traditional"],"爬":["chinese_simplified","chinese_traditional"],"赏":["chinese_simplified"],"逆":["chinese_simplified","chinese_traditional"],"玩":["chinese_simplified","chinese_traditional"],"陵":["chinese_simplified","chinese_traditional"],"祝":["chinese_simplified","chinese_traditional"],"秒":["chinese_simplified","chinese_traditional"],"浙":["chinese_simplified","chinese_traditional"],"貌":["chinese_simplified","chinese_traditional"],"役":["chinese_simplified","chinese_traditional"],"彼":["chinese_simplified","chinese_traditional"],"悉":["chinese_simplified","chinese_traditional"],"鸭":["chinese_simplified"],"趋":["chinese_simplified"],"凤":["chinese_simplified"],"晨":["chinese_simplified","chinese_traditional"],"畜":["chinese_simplified","chinese_traditional"],"辈":["chinese_simplified"],"秩":["chinese_simplified","chinese_traditional"],"卵":["chinese_simplified","chinese_traditional"],"署":["chinese_simplified","chinese_traditional"],"梯":["chinese_simplified","chinese_traditional"],"炎":["chinese_simplified","chinese_traditional"],"滩":["chinese_simplified"],"棋":["chinese_simplified","chinese_traditional"],"驱":["chinese_simplified"],"筛":["chinese_simplified"],"峡":["chinese_simplified"],"冒":["chinese_simplified","chinese_traditional"],"啥":["chinese_simplified","chinese_traditional"],"寿":["chinese_simplified"],"译":["chinese_simplified"],"浸":["chinese_simplified","chinese_traditional"],"泉":["chinese_simplified","chinese_traditional"],"帽":["chinese_simplified","chinese_traditional"],"迟":["chinese_simplified"],"硅":["chinese_simplified"],"疆":["chinese_simplified","chinese_traditional"],"贷":["chinese_simplified"],"漏":["chinese_simplified","chinese_traditional"],"稿":["chinese_simplified","chinese_traditional"],"冠":["chinese_simplified","chinese_traditional"],"嫩":["chinese_simplified","chinese_traditional"],"胁":["chinese_simplified"],"芯":["chinese_simplified","chinese_traditional"],"牢":["chinese_simplified","chinese_traditional"],"叛":["chinese_simplified","chinese_traditional"],"蚀":["chinese_simplified"],"奥":["chinese_simplified"],"鸣":["chinese_simplified"],"岭":["chinese_simplified"],"羊":["chinese_simplified","chinese_traditional"],"凭":["chinese_simplified"],"串":["chinese_simplified","chinese_traditional"],"塘":["chinese_simplified","chinese_traditional"],"绘":["chinese_simplified"],"酵":["chinese_simplified","chinese_traditional"],"融":["chinese_simplified","chinese_traditional"],"盆":["chinese_simplified","chinese_traditional"],"锡":["chinese_simplified"],"庙":["chinese_simplified"],"筹":["chinese_simplified"],"冻":["chinese_simplified"],"辅":["chinese_simplified"],"摄":["chinese_simplified"],"袭":["chinese_simplified"],"筋":["chinese_simplified","chinese_traditional"],"拒":["chinese_simplified","chinese_traditional"],"僚":["chinese_simplified","chinese_traditional"],"旱":["chinese_simplified","chinese_traditional"],"钾":["chinese_simplified"],"鸟":["chinese_simplified"],"漆":["chinese_simplified","chinese_traditional"],"沈":["chinese_simplified","chinese_traditional"],"眉":["chinese_simplified","chinese_traditional"],"疏":["chinese_simplified","chinese_traditional"],"添":["chinese_simplified","chinese_traditional"],"棒":["chinese_simplified","chinese_traditional"],"穗":["chinese_simplified","chinese_traditional"],"硝":["chinese_simplified","chinese_traditional"],"韩":["chinese_simplified"],"逼":["chinese_simplified","chinese_traditional"],"扭":["chinese_simplified","chinese_traditional"],"侨":["chinese_simplified"],"凉":["chinese_simplified"],"挺":["chinese_simplified","chinese_traditional"],"碗":["chinese_simplified","chinese_traditional"],"栽":["chinese_simplified","chinese_traditional"],"炒":["chinese_simplified","chinese_traditional"],"杯":["chinese_simplified","chinese_traditional"],"患":["chinese_simplified","chinese_traditional"],"馏":["chinese_simplified"],"劝":["chinese_simplified"],"豪":["chinese_simplified","chinese_traditional"],"辽":["chinese_simplified"],"勃":["chinese_simplified","chinese_traditional"],"鸿":["chinese_simplified"],"旦":["chinese_simplified","chinese_traditional"],"吏":["chinese_simplified","chinese_traditional"],"拜":["chinese_simplified","chinese_traditional"],"狗":["chinese_simplified","chinese_traditional"],"埋":["chinese_simplified","chinese_traditional"],"辊":["chinese_simplified"],"掩":["chinese_simplified","chinese_traditional"],"饮":["chinese_simplified"],"搬":["chinese_simplified","chinese_traditional"],"骂":["chinese_simplified"],"辞":["chinese_simplified"],"勾":["chinese_simplified","chinese_traditional"],"扣":["chinese_simplified","chinese_traditional"],"估":["chinese_simplified","chinese_traditional"],"蒋":["chinese_simplified"],"绒":["chinese_simplified"],"雾":["chinese_simplified"],"丈":["chinese_simplified","chinese_traditional"],"朵":["chinese_simplified","chinese_traditional"],"姆":["chinese_simplified","chinese_traditional"],"拟":["chinese_simplified"],"宇":["chinese_simplified","chinese_traditional"],"辑":["chinese_simplified"],"陕":["chinese_simplified"],"雕":["chinese_simplified","chinese_traditional"],"偿":["chinese_simplified"],"蓄":["chinese_simplified","chinese_traditional"],"崇":["chinese_simplified","chinese_traditional"],"剪":["chinese_simplified","chinese_traditional"],"倡":["chinese_simplified","chinese_traditional"],"厅":["chinese_simplified"],"咬":["chinese_simplified","chinese_traditional"],"驶":["chinese_simplified"],"薯":["chinese_simplified","chinese_traditional"],"刷":["chinese_simplified","chinese_traditional"],"斥":["chinese_simplified","chinese_traditional"],"番":["chinese_simplified","chinese_traditional"],"赋":["chinese_simplified"],"奉":["chinese_simplified","chinese_traditional"],"佛":["chinese_simplified","chinese_traditional"],"浇":["chinese_simplified"],"漫":["chinese_simplified","chinese_traditional"],"曼":["chinese_simplified","chinese_traditional"],"扇":["chinese_simplified","chinese_traditional"],"钙":["chinese_simplified"],"桃":["chinese_simplified","chinese_traditional"],"扶":["chinese_simplified","chinese_traditional"],"仔":["chinese_simplified","chinese_traditional"],"返":["chinese_simplified","chinese_traditional"],"俗":["chinese_simplified","chinese_traditional"],"亏":["chinese_simplified"],"腔":["chinese_simplified","chinese_traditional"],"鞋":["chinese_simplified","chinese_traditional"],"棱":["chinese_simplified","chinese_traditional"],"覆":["chinese_simplified","chinese_traditional"],"框":["chinese_simplified","chinese_traditional"],"悄":["chinese_simplified","chinese_traditional"],"叔":["chinese_simplified","chinese_traditional"],"撞":["chinese_simplified","chinese_traditional"],"骗":["chinese_simplified"],"勘":["chinese_simplified","chinese_traditional"],"旺":["chinese_simplified","chinese_traditional"],"沸":["chinese_simplified","chinese_traditional"],"孤":["chinese_simplified","chinese_traditional"],"吐":["chinese_simplified","chinese_traditional"],"孟":["chinese_simplified","chinese_traditional"],"渠":["chinese_simplified","chinese_traditional"],"屈":["chinese_simplified","chinese_traditional"],"疾":["chinese_simplified","chinese_traditional"],"妙":["chinese_simplified","chinese_traditional"],"惜":["chinese_simplified","chinese_traditional"],"仰":["chinese_simplified","chinese_traditional"],"狠":["chinese_simplified","chinese_traditional"],"胀":["chinese_simplified"],"谐":["chinese_simplified"],"抛":["chinese_simplified"],"霉":["chinese_simplified"],"桑":["chinese_simplified","chinese_traditional"],"岗":["chinese_simplified"],"嘛":["chinese_simplified","chinese_traditional"],"衰":["chinese_simplified","chinese_traditional"],"盗":["chinese_simplified"],"渗":["chinese_simplified"],"脏":["chinese_simplified"],"赖":["chinese_simplified"],"涌":["chinese_simplified"],"甜":["chinese_simplified","chinese_traditional"],"曹":["chinese_simplified","chinese_traditional"],"阅":["chinese_simplified"],"肌":["chinese_simplified","chinese_traditional"],"哩":["chinese_simplified","chinese_traditional"],"厉":["chinese_simplified"],"烃":["chinese_simplified"],"纬":["chinese_simplified"],"毅":["chinese_simplified","chinese_traditional"],"昨":["chinese_simplified","chinese_traditional"],"伪":["chinese_simplified"],"症":["chinese_simplified","chinese_traditional"],"煮":["chinese_simplified","chinese_traditional"],"叹":["chinese_simplified"],"钉":["chinese_simplified"],"搭":["chinese_simplified","chinese_traditional"],"茎":["chinese_simplified"],"笼":["chinese_simplified"],"酷":["chinese_simplified","chinese_traditional"],"偷":["chinese_simplified","chinese_traditional"],"弓":["chinese_simplified","chinese_traditional"],"锥":["chinese_simplified"],"恒":["chinese_simplified"],"杰":["chinese_simplified"],"坑":["chinese_simplified","chinese_traditional"],"鼻":["chinese_simplified","chinese_traditional"],"翼":["chinese_simplified","chinese_traditional"],"纶":["chinese_simplified"],"叙":["chinese_simplified"],"狱":["chinese_simplified"],"逮":["chinese_simplified","chinese_traditional"],"罐":["chinese_simplified","chinese_traditional"],"络":["chinese_simplified"],"棚":["chinese_simplified","chinese_traditional"],"抑":["chinese_simplified","chinese_traditional"],"膨":["chinese_simplified","chinese_traditional"],"蔬":["chinese_simplified","chinese_traditional"],"寺":["chinese_simplified","chinese_traditional"],"骤":["chinese_simplified"],"穆":["chinese_simplified","chinese_traditional"],"冶":["chinese_simplified","chinese_traditional"],"枯":["chinese_simplified","chinese_traditional"],"册":["chinese_simplified"],"尸":["chinese_simplified"],"凸":["chinese_simplified","chinese_traditional"],"绅":["chinese_simplified"],"坯":["chinese_simplified","chinese_traditional"],"牺":["chinese_simplified"],"焰":["chinese_simplified","chinese_traditional"],"轰":["chinese_simplified"],"欣":["chinese_simplified","chinese_traditional"],"晋":["chinese_simplified"],"瘦":["chinese_simplified","chinese_traditional"],"御":["chinese_simplified"],"锭":["chinese_simplified"],"锦":["chinese_simplified"],"丧":["chinese_simplified"],"旬":["chinese_simplified","chinese_traditional"],"锻":["chinese_simplified"],"垄":["chinese_simplified"],"搜":["chinese_simplified","chinese_traditional"],"扑":["chinese_simplified"],"邀":["chinese_simplified","chinese_traditional"],"亭":["chinese_simplified","chinese_traditional"],"酯":["chinese_simplified","chinese_traditional"],"迈":["chinese_simplified"],"舒":["chinese_simplified","chinese_traditional"],"脆":["chinese_simplified","chinese_traditional"],"酶":["chinese_simplified","chinese_traditional"],"闲":["chinese_simplified"],"忧":["chinese_simplified"],"酚":["chinese_simplified","chinese_traditional"],"顽":["chinese_simplified"],"羽":["chinese_simplified","chinese_traditional"],"涨":["chinese_simplified"],"卸":["chinese_simplified","chinese_traditional"],"仗":["chinese_simplified","chinese_traditional"],"陪":["chinese_simplified","chinese_traditional"],"辟":["chinese_simplified"],"惩":["chinese_simplified"],"杭":["chinese_simplified","chinese_traditional"],"姚":["chinese_simplified","chinese_traditional"],"肚":["chinese_simplified","chinese_traditional"],"捉":["chinese_simplified","chinese_traditional"],"飘":["chinese_simplified"],"漂":["chinese_simplified","chinese_traditional"],"昆":["chinese_simplified","chinese_traditional"],"欺":["chinese_simplified","chinese_traditional"],"吾":["chinese_simplified","chinese_traditional"],"郎":["chinese_simplified","chinese_traditional"],"烷":["chinese_simplified","chinese_traditional"],"汁":["chinese_simplified","chinese_traditional"],"呵":["chinese_simplified","chinese_traditional"],"饰":["chinese_simplified"],"萧":["chinese_simplified"],"雅":["chinese_simplified","chinese_traditional"],"邮":["chinese_simplified"],"迁":["chinese_simplified"],"燕":["chinese_simplified","chinese_traditional"],"撒":["chinese_simplified","chinese_traditional"],"姻":["chinese_simplified","chinese_traditional"],"赴":["chinese_simplified","chinese_traditional"],"宴":["chinese_simplified","chinese_traditional"],"烦":["chinese_simplified"],"债":["chinese_simplified"],"帐":["chinese_simplified"],"斑":["chinese_simplified","chinese_traditional"],"铃":["chinese_simplified"],"旨":["chinese_simplified","chinese_traditional"],"醇":["chinese_simplified","chinese_traditional"],"董":["chinese_simplified","chinese_traditional"],"饼":["chinese_simplified"],"雏":["chinese_simplified"],"姿":["chinese_simplified","chinese_traditional"],"拌":["chinese_simplified","chinese_traditional"],"傅":["chinese_simplified","chinese_traditional"],"腹":["chinese_simplified","chinese_traditional"],"妥":["chinese_simplified","chinese_traditional"],"揉":["chinese_simplified","chinese_traditional"],"贤":["chinese_simplified"],"拆":["chinese_simplified","chinese_traditional"],"歪":["chinese_simplified","chinese_traditional"],"葡":["chinese_simplified","chinese_traditional"],"胺":["chinese_simplified","chinese_traditional"],"丢":["chinese_simplified"],"浩":["chinese_simplified","chinese_traditional"],"徽":["chinese_simplified","chinese_traditional"],"昂":["chinese_simplified","chinese_traditional"],"垫":["chinese_simplified"],"挡":["chinese_simplified"],"览":["chinese_simplified"],"贪":["chinese_simplified"],"慰":["chinese_simplified","chinese_traditional"],"缴":["chinese_simplified"],"汪":["chinese_simplified","chinese_traditional"],"慌":["chinese_simplified","chinese_traditional"],"冯":["chinese_simplified"],"诺":["chinese_simplified"],"姜":["chinese_simplified","chinese_traditional"],"谊":["chinese_simplified"],"凶":["chinese_simplified"],"劣":["chinese_simplified","chinese_traditional"],"诬":["chinese_simplified"],"耀":["chinese_simplified","chinese_traditional"],"昏":["chinese_simplified","chinese_traditional"],"躺":["chinese_simplified","chinese_traditional"],"盈":["chinese_simplified","chinese_traditional"],"骑":["chinese_simplified"],"乔":["chinese_simplified"],"溪":["chinese_simplified","chinese_traditional"],"丛":["chinese_simplified"],"卢":["chinese_simplified"],"抹":["chinese_simplified","chinese_traditional"],"闷":["chinese_simplified"],"咨":["chinese_simplified"],"刮":["chinese_simplified","chinese_traditional"],"驾":["chinese_simplified"],"缆":["chinese_simplified"],"悟":["chinese_simplified","chinese_traditional"],"摘":["chinese_simplified","chinese_traditional"],"铒":["chinese_simplified"],"掷":["chinese_simplified"],"颇":["chinese_simplified"],"幻":["chinese_simplified","chinese_traditional"],"柄":["chinese_simplified","chinese_traditional"],"惠":["chinese_simplified","chinese_traditional"],"惨":["chinese_simplified"],"佳":["chinese_simplified","chinese_traditional"],"仇":["chinese_simplified","chinese_traditional"],"腊":["chinese_simplified"],"窝":["chinese_simplified"],"涤":["chinese_simplified"],"剑":["chinese_simplified"],"瞧":["chinese_simplified","chinese_traditional"],"堡":["chinese_simplified","chinese_traditional"],"泼":["chinese_simplified"],"葱":["chinese_simplified"],"罩":["chinese_simplified","chinese_traditional"],"霍":["chinese_simplified","chinese_traditional"],"捞":["chinese_simplified"],"胎":["chinese_simplified","chinese_traditional"],"苍":["chinese_simplified"],"滨":["chinese_simplified"],"俩":["chinese_simplified"],"捅":["chinese_simplified","chinese_traditional"],"湘":["chinese_simplified","chinese_traditional"],"砍":["chinese_simplified","chinese_traditional"],"霞":["chinese_simplified","chinese_traditional"],"邵":["chinese_simplified","chinese_traditional"],"萄":["chinese_simplified","chinese_traditional"],"疯":["chinese_simplified"],"淮":["chinese_simplified","chinese_traditional"],"遂":["chinese_simplified","chinese_traditional"],"熊":["chinese_simplified","chinese_traditional"],"粪":["chinese_simplified"],"烘":["chinese_simplified","chinese_traditional"],"宿":["chinese_simplified","chinese_traditional"],"档":["chinese_simplified"],"戈":["chinese_simplified","chinese_traditional"],"驳":["chinese_simplified"],"嫂":["chinese_simplified","chinese_traditional"],"裕":["chinese_simplified","chinese_traditional"],"徙":["chinese_simplified","chinese_traditional"],"箭":["chinese_simplified","chinese_traditional"],"捐":["chinese_simplified","chinese_traditional"],"肠":["chinese_simplified"],"撑":["chinese_simplified"],"晒":["chinese_simplified"],"辨":["chinese_simplified","chinese_traditional"],"殿":["chinese_simplified","chinese_traditional"],"莲":["chinese_simplified"],"摊":["chinese_simplified"],"搅":["chinese_simplified"],"酱":["chinese_simplified"],"屏":["chinese_simplified","chinese_traditional"],"疫":["chinese_simplified","chinese_traditional"],"哀":["chinese_simplified","chinese_traditional"],"蔡":["chinese_simplified","chinese_traditional"],"堵":["chinese_simplified","chinese_traditional"],"沫":["chinese_simplified","chinese_traditional"],"皱":["chinese_simplified"],"畅":["chinese_simplified"],"叠":["chinese_simplified"],"阁":["chinese_simplified"],"莱":["chinese_simplified"],"敲":["chinese_simplified","chinese_traditional"],"辖":["chinese_simplified"],"钩":["chinese_simplified"],"痕":["chinese_simplified","chinese_traditional"],"坝":["chinese_simplified"],"巷":["chinese_simplified","chinese_traditional"],"饿":["chinese_simplified"],"祸":["chinese_simplified"],"丘":["chinese_simplified","chinese_traditional"],"玄":["chinese_simplified","chinese_traditional"],"溜":["chinese_simplified","chinese_traditional"],"曰":["chinese_simplified","chinese_traditional"],"逻":["chinese_simplified"],"彭":["chinese_simplified","chinese_traditional"],"尝":["chinese_simplified"],"卿":["chinese_simplified","chinese_traditional"],"妨":["chinese_simplified","chinese_traditional"],"艇":["chinese_simplified","chinese_traditional"],"吞":["chinese_simplified","chinese_traditional"],"韦":["chinese_simplified"],"怨":["chinese_simplified","chinese_traditional"],"矮":["chinese_simplified","chinese_traditional"],"歇":["chinese_simplified","chinese_traditional"],"這":["chinese_traditional"],"為":["chinese_traditional"],"個":["chinese_traditional"],"國":["chinese_traditional"],"時":["chinese_traditional"],"來":["chinese_traditional"],"們":["chinese_traditional"],"於":["chinese_traditional"],"對":["chinese_traditional"],"會":["chinese_traditional"],"發":["chinese_traditional"],"動":["chinese_traditional"],"過":["chinese_traditional"],"說":["chinese_traditional"],"產":["chinese_traditional"],"種":["chinese_traditional"],"後":["chinese_traditional"],"學":["chinese_traditional"],"經":["chinese_traditional"],"進":["chinese_traditional"],"著":["chinese_traditional"],"電":["chinese_traditional"],"裡":["chinese_traditional"],"現":["chinese_traditional"],"實":["chinese_traditional"],"兩":["chinese_traditional"],"體":["chinese_traditional"],"機":["chinese_traditional"],"當":["chinese_traditional"],"點":["chinese_traditional"],"從":["chinese_traditional"],"業":["chinese_traditional"],"應":["chinese_traditional"],"開":["chinese_traditional"],"還":["chinese_traditional"],"義":["chinese_traditional"],"間":["chinese_traditional"],"樣":["chinese_traditional"],"與":["chinese_traditional"],"關":["chinese_traditional"],"線":["chinese_traditional"],"內":["chinese_traditional"],"數":["chinese_traditional"],"麼":["chinese_traditional"],"質":["chinese_traditional"],"氣":["chinese_traditional"],"變":["chinese_traditional"],"條":["chinese_traditional"],"沒":["chinese_traditional"],"結":["chinese_traditional"],"問":["chinese_traditional"],"無":["chinese_traditional"],"軍":["chinese_traditional"],"並":["chinese_traditional"],"題":["chinese_traditional"],"黨":["chinese_traditional"],"員":["chinese_traditional"],"總":["chinese_traditional"],"設":["chinese_traditional"],"長":["chinese_traditional"],"頭":["chinese_traditional"],"資":["chinese_traditional"],"邊":["chinese_traditional"],"級":["chinese_traditional"],"圖":["chinese_traditional"],"統":["chinese_traditional"],"較":["chinese_traditional"],"將":["chinese_traditional"],"組":["chinese_traditional"],"見":["chinese_traditional"],"計":["chinese_traditional"],"別":["chinese_traditional"],"論":["chinese_traditional"],"運":["chinese_traditional"],"農":["chinese_traditional"],"幾":["chinese_traditional"],"區":["chinese_traditional"],"強":["chinese_traditional"],"決":["chinese_traditional"],"幹":["chinese_traditional"],"戰":["chinese_traditional"],"則":["chinese_traditional"],"據":["chinese_traditional"],"處":["chinese_traditional"],"隊":["chinese_traditional"],"給":["chinese_traditional"],"門":["chinese_traditional"],"規":["chinese_traditional"],"熱":["chinese_traditional"],"領":["chinese_traditional"],"東":["chinese_traditional"],"導":["chinese_traditional"],"壓":["chinese_traditional"],"爭":["chinese_traditional"],"濟":["chinese_traditional"],"階":["chinese_traditional"],"術":["chinese_traditional"],"極":["chinese_traditional"],"聯":["chinese_traditional"],"認":["chinese_traditional"],"權":["chinese_traditional"],"證":["chinese_traditional"],"採":["chinese_traditional"],"轉":["chinese_traditional"],"單":["chinese_traditional"],"風":["chinese_traditional"],"帶":["chinese_traditional"],"場":["chinese_traditional"],"車":["chinese_traditional"],"務":["chinese_traditional"],"萬":["chinese_traditional"],"達":["chinese_traditional"],"積":["chinese_traditional"],"議":["chinese_traditional"],"聲":["chinese_traditional"],"報":["chinese_traditional"],"鬥":["chinese_traditional"],"類":["chinese_traditional"],"離":["chinese_traditional"],"華":["chinese_traditional"],"確":["chinese_traditional"],"張":["chinese_traditional"],"馬":["chinese_traditional"],"節":["chinese_traditional"],"話":["chinese_traditional"],"況":["chinese_traditional"],"溫":["chinese_traditional"],"傳":["chinese_traditional"],"許":["chinese_traditional"],"廣":["chinese_traditional"],"記":["chinese_traditional"],"觀":["chinese_traditional"],"織":["chinese_traditional"],"裝":["chinese_traditional"],"眾":["chinese_traditional"],"書":["chinese_traditional"],"兒":["chinese_traditional"],"須":["chinese_traditional"],"際":["chinese_traditional"],"驗":["chinese_traditional"],"連":["chinese_traditional"],"斷":["chinese_traditional"],"難":["chinese_traditional"],"礦":["chinese_traditional"],"週":["chinese_traditional"],"備":["chinese_traditional"],"辦":["chinese_traditional"],"習":["chinese_traditional"],"響":["chinese_traditional"],"約":["chinese_traditional"],"勞":["chinese_traditional"],"團":["chinese_traditional"],"歷":["chinese_traditional"],"構":["chinese_traditional"],"稱":["chinese_traditional"],"準":["chinese_traditional"],"號":["chinese_traditional"],"維":["chinese_traditional"],"劃":["chinese_traditional"],"選":["chinese_traditional"],"標":["chinese_traditional"],"寫":["chinese_traditional"],"親":["chinese_traditional"],"養":["chinese_traditional"],"層":["chinese_traditional"],"卻":["chinese_traditional"],"專":["chinese_traditional"],"狀":["chinese_traditional"],"廠":["chinese_traditional"],"識":["chinese_traditional"],"適":["chinese_traditional"],"屬":["chinese_traditional"],"圓":["chinese_traditional"],"調":["chinese_traditional"],"滿":["chinese_traditional"],"縣":["chinese_traditional"],"參":["chinese_traditional"],"紅":["chinese_traditional"],"細":["chinese_traditional"],"聽":["chinese_traditional"],"該":["chinese_traditional"],"鐵":["chinese_traditional"],"價":["chinese_traditional"],"嚴":["chinese_traditional"],"隨":["chinese_traditional"],"蘇":["chinese_traditional"],"爾":["chinese_traditional"],"講":["chinese_traditional"],"黃":["chinese_traditional"],"顯":["chinese_traditional"],"談":["chinese_traditional"],"藝":["chinese_traditional"],"營":["chinese_traditional"],"項":["chinese_traditional"],"舉":["chinese_traditional"],"勢":["chinese_traditional"],"幫":["chinese_traditional"],"輪":["chinese_traditional"],"亞":["chinese_traditional"],"師":["chinese_traditional"],"圍":["chinese_traditional"],"遠":["chinese_traditional"],"態":["chinese_traditional"],"減":["chinese_traditional"],"樹":["chinese_traditional"],"葉":["chinese_traditional"],"魚":["chinese_traditional"],"視":["chinese_traditional"],"僅":["chinese_traditional"],"費":["chinese_traditional"],"緊":["chinese_traditional"],"愛":["chinese_traditional"],"續":["chinese_traditional"],"輕":["chinese_traditional"],"試":["chinese_traditional"],"護":["chinese_traditional"],"練":["chinese_traditional"],"負":["chinese_traditional"],"擊":["chinese_traditional"],"繼":["chinese_traditional"],"興":["chinese_traditional"],"餘":["chinese_traditional"],"堅":["chinese_traditional"],"輸":["chinese_traditional"],"夠":["chinese_traditional"],"筆":["chinese_traditional"],"佔":["chinese_traditional"],"財":["chinese_traditional"],"職":["chinese_traditional"],"覺":["chinese_traditional"],"漢":["chinese_traditional"],"畫":["chinese_traditional"],"雖":["chinese_traditional"],"雜":["chinese_traditional"],"飛":["chinese_traditional"],"檢":["chinese_traditional"],"昇":["chinese_traditional"],"陽":["chinese_traditional"],"創":["chinese_traditional"],"壞":["chinese_traditional"],"徑":["chinese_traditional"],"換":["chinese_traditional"],"鋼":["chinese_traditional"],"責":["chinese_traditional"],"簡":["chinese_traditional"],"錢":["chinese_traditional"],"盡":["chinese_traditional"],"衝":["chinese_traditional"],"獨":["chinese_traditional"],"環":["chinese_traditional"],"雙":["chinese_traditional"],"請":["chinese_traditional"],"讓":["chinese_traditional"],"軸":["chinese_traditional"],"紀":["chinese_traditional"],"優":["chinese_traditional"],"頂":["chinese_traditional"],"礎":["chinese_traditional"],"載":["chinese_traditional"],"敵":["chinese_traditional"],"勝":["chinese_traditional"],"絕":["chinese_traditional"],"塊":["chinese_traditional"],"劑":["chinese_traditional"],"測":["chinese_traditional"],"絲":["chinese_traditional"],"協":["chinese_traditional"],"訴":["chinese_traditional"],"陳":["chinese_traditional"],"羅":["chinese_traditional"],"鹽":["chinese_traditional"],"錯":["chinese_traditional"],"頻":["chinese_traditional"],"終":["chinese_traditional"],"雲":["chinese_traditional"],"衛":["chinese_traditional"],"燒":["chinese_traditional"],"遊":["chinese_traditional"],"舊":["chinese_traditional"],"貨":["chinese_traditional"],"損":["chinese_traditional"],"預":["chinese_traditional"],"穩":["chinese_traditional"],"媽":["chinese_traditional"],"擴":["chinese_traditional"],"銀":["chinese_traditional"],"語":["chinese_traditional"],"揮":["chinese_traditional"],"紙":["chinese_traditional"],"醫":["chinese_traditional"],"嗎":["chinese_traditional"],"針":["chinese_traditional"],"劉":["chinese_traditional"],"誤":["chinese_traditional"],"訓":["chinese_traditional"],"願":["chinese_traditional"],"審":["chinese_traditional"],"獲":["chinese_traditional"],"鮮":["chinese_traditional"],"糧":["chinese_traditional"],"脫":["chinese_traditional"],"龍":["chinese_traditional"],"漸":["chinese_traditional"],"歡":["chinese_traditional"],"剛":["chinese_traditional"],"謂":["chinese_traditional"],"討":["chinese_traditional"],"亂":["chinese_traditional"],"殺":["chinese_traditional"],"藥":["chinese_traditional"],"寧":["chinese_traditional"],"魯":["chinese_traditional"],"貴":["chinese_traditional"],"鐘":["chinese_traditional"],"讀":["chinese_traditional"],"豐":["chinese_traditional"],"蘭":["chinese_traditional"],"擔":["chinese_traditional"],"執":["chinese_traditional"],"樂":["chinese_traditional"],"誰":["chinese_traditional"],"順":["chinese_traditional"],"煙":["chinese_traditional"],"縮":["chinese_traditional"],"徵":["chinese_traditional"],"臉":["chinese_traditional"],"腳":["chinese_traditional"],"異":["chinese_traditional"],"買":["chinese_traditional"],"靜":["chinese_traditional"],"補":["chinese_traditional"],"評":["chinese_traditional"],"踐":["chinese_traditional"],"寬":["chinese_traditional"],"揚":["chinese_traditional"],"傷":["chinese_traditional"],"氫":["chinese_traditional"],"憲":["chinese_traditional"],"慶":["chinese_traditional"],"編":["chinese_traditional"],"觸":["chinese_traditional"],"銷":["chinese_traditional"],"詩":["chinese_traditional"],"綠":["chinese_traditional"],"雞":["chinese_traditional"],"孫":["chinese_traditional"],"膠":["chinese_traditional"],"鄉":["chinese_traditional"],"臨":["chinese_traditional"],"陸":["chinese_traditional"],"顧":["chinese_traditional"],"燈":["chinese_traditional"],"歲":["chinese_traditional"],"劇":["chinese_traditional"],"趙":["chinese_traditional"],"課":["chinese_traditional"],"凱":["chinese_traditional"],"額":["chinese_traditional"],"紹":["chinese_traditional"],"齊":["chinese_traditional"],"偉":["chinese_traditional"],"爐":["chinese_traditional"],"楊":["chinese_traditional"],"桿":["chinese_traditional"],"鎮":["chinese_traditional"],"飯":["chinese_traditional"],"濃":["chinese_traditional"],"懷":["chinese_traditional"],"趕":["chinese_traditional"],"庫":["chinese_traditional"],"奪":["chinese_traditional"],"靈":["chinese_traditional"],"稅":["chinese_traditional"],"滅":["chinese_traditional"],"賽":["chinese_traditional"],"歸":["chinese_traditional"],"盤":["chinese_traditional"],"險":["chinese_traditional"],"錄":["chinese_traditional"],"純":["chinese_traditional"],"蓋":["chinese_traditional"],"橫":["chinese_traditional"],"槍":["chinese_traditional"],"潤":["chinese_traditional"],"蟲":["chinese_traditional"],"澤":["chinese_traditional"],"腦":["chinese_traditional"],"歐":["chinese_traditional"],"側":["chinese_traditional"],"徹":["chinese_traditional"],"慮":["chinese_traditional"],"納":["chinese_traditional"],"彈":["chinese_traditional"],"飼":["chinese_traditional"],"麥":["chinese_traditional"],"濕":["chinese_traditional"],"築":["chinese_traditional"],"惡":["chinese_traditional"],"戶":["chinese_traditional"],"訪":["chinese_traditional"],"跡":["chinese_traditional"],"擺":["chinese_traditional"],"賣":["chinese_traditional"],"擇":["chinese_traditional"],"銅":["chinese_traditional"],"獻":["chinese_traditional"],"陣":["chinese_traditional"],"陰":["chinese_traditional"],"樓":["chinese_traditional"],"謀":["chinese_traditional"],"噸":["chinese_traditional"],"豬":["chinese_traditional"],"館":["chinese_traditional"],"爺":["chinese_traditional"],"驚":["chinese_traditional"],"遺":["chinese_traditional"],"纖":["chinese_traditional"],"傾":["chinese_traditional"],"謝":["chinese_traditional"],"奮":["chinese_traditional"],"購":["chinese_traditional"],"監":["chinese_traditional"],"貫":["chinese_traditional"],"釋":["chinese_traditional"],"詞":["chinese_traditional"],"頓":["chinese_traditional"],"寶":["chinese_traditional"],"塵":["chinese_traditional"],"聞":["chinese_traditional"],"殘":["chinese_traditional"],"橋":["chinese_traditional"],"婦":["chinese_traditional"],"綜":["chinese_traditional"],"吳":["chinese_traditional"],"搖":["chinese_traditional"],"贊":["chinese_traditional"],"訂":["chinese_traditional"],"園":["chinese_traditional"],"紛":["chinese_traditional"],"敗":["chinese_traditional"],"榮":["chinese_traditional"],"閉":["chinese_traditional"],"灣":["chinese_traditional"],"鍵":["chinese_traditional"],"駐":["chinese_traditional"],"鍋":["chinese_traditional"],"剝":["chinese_traditional"],"鹼":["chinese_traditional"],"齒":["chinese_traditional"],"煉":["chinese_traditional"],"紡":["chinese_traditional"],"廢":["chinese_traditional"],"緩":["chinese_traditional"],"淨":["chinese_traditional"],"莊":["chinese_traditional"],"貿":["chinese_traditional"],"慣":["chinese_traditional"],"夥":["chinese_traditional"],"勻":["chinese_traditional"],"紗":["chinese_traditional"],"辯":["chinese_traditional"],"億":["chinese_traditional"],"脈":["chinese_traditional"],"薩":["chinese_traditional"],"網":["chinese_traditional"],"噴":["chinese_traditional"],"縱":["chinese_traditional"],"掛":["chinese_traditional"],"賀":["chinese_traditional"],"閃":["chinese_traditional"],"牆":["chinese_traditional"],"軟":["chinese_traditional"],"滾":["chinese_traditional"],"盪":["chinese_traditional"],"儀":["chinese_traditional"],"軋":["chinese_traditional"],"貢":["chinese_traditional"],"鑽":["chinese_traditional"],"幣":["chinese_traditional"],"軌":["chinese_traditional"],"畝":["chinese_traditional"],"畢":["chinese_traditional"],"島":["chinese_traditional"],"鑄":["chinese_traditional"],"湯":["chinese_traditional"],"閥":["chinese_traditional"],"匯":["chinese_traditional"],"繞":["chinese_traditional"],"績":["chinese_traditional"],"啟":["chinese_traditional"],"顏":["chinese_traditional"],"淚":["chinese_traditional"],"藍":["chinese_traditional"],"鏡":["chinese_traditional"],"壯":["chinese_traditional"],"鋒":["chinese_traditional"],"貧":["chinese_traditional"],"虛":["chinese_traditional"],"彎":["chinese_traditional"],"綱":["chinese_traditional"],"隸":["chinese_traditional"],"宮":["chinese_traditional"],"違":["chinese_traditional"],"夾":["chinese_traditional"],"緣":["chinese_traditional"],"窮":["chinese_traditional"],"溝":["chinese_traditional"],"繩":["chinese_traditional"],"憶":["chinese_traditional"],"漿":["chinese_traditional"],"欄":["chinese_traditional"],"擁":["chinese_traditional"],"貯":["chinese_traditional"],"禮":["chinese_traditional"],"濾":["chinese_traditional"],"鈉":["chinese_traditional"],"紋":["chinese_traditional"],"罷":["chinese_traditional"],"罰":["chinese_traditional"],"潛":["chinese_traditional"],"縫":["chinese_traditional"],"飽":["chinese_traditional"],"獎":["chinese_traditional"],"鋁":["chinese_traditional"],"麗":["chinese_traditional"],"鏈":["chinese_traditional"],"掃":["chinese_traditional"],"諸":["chinese_traditional"],"勵":["chinese_traditional"],"潔":["chinese_traditional"],"災":["chinese_traditional"],"鑑":["chinese_traditional"],"訟":["chinese_traditional"],"毀":["chinese_traditional"],"屆":["chinese_traditional"],"躍":["chinese_traditional"],"艱":["chinese_traditional"],"貝":["chinese_traditional"],"碼":["chinese_traditional"],"夢":["chinese_traditional"],"漁":["chinese_traditional"],"顆":["chinese_traditional"],"鉛":["chinese_traditional"],"倉":["chinese_traditional"],"銳":["chinese_traditional"],"曉":["chinese_traditional"],"隱":["chinese_traditional"],"礙":["chinese_traditional"],"撥":["chinese_traditional"],"肅":["chinese_traditional"],"牽":["chinese_traditional"],"搶":["chinese_traditional"],"殼":["chinese_traditional"],"訊":["chinese_traditional"],"誠":["chinese_traditional"],"頁":["chinese_traditional"],"齡":["chinese_traditional"],"倫":["chinese_traditional"],"尋":["chinese_traditional"],"鋪":["chinese_traditional"],"聖":["chinese_traditional"],"鄭":["chinese_traditional"],"騰":["chinese_traditional"],"貼":["chinese_traditional"],"闊":["chinese_traditional"],"輛":["chinese_traditional"],"儲":["chinese_traditional"],"簽":["chinese_traditional"],"鬧":["chinese_traditional"],"擾":["chinese_traditional"],"遞":["chinese_traditional"],"戲":["chinese_traditional"],"餵":["chinese_traditional"],"療":["chinese_traditional"],"撫":["chinese_traditional"],"蝦":["chinese_traditional"],"蠟":["chinese_traditional"],"鄰":["chinese_traditional"],"鞏":["chinese_traditional"],"擠":["chinese_traditional"],"棄":["chinese_traditional"],"勁":["chinese_traditional"],"鄧":["chinese_traditional"],"爛":["chinese_traditional"],"磚":["chinese_traditional"],"烏":["chinese_traditional"],"艦":["chinese_traditional"],"淺":["chinese_traditional"],"暫":["chinese_traditional"],"膽":["chinese_traditional"],"詳":["chinese_traditional"],"譜":["chinese_traditional"],"賓":["chinese_traditional"],"輝":["chinese_traditional"],"憤":["chinese_traditional"],"競":["chinese_traditional"],"緒":["chinese_traditional"],"塗":["chinese_traditional"],"偵":["chinese_traditional"],"懸":["chinese_traditional"],"糾":["chinese_traditional"],"鎖":["chinese_traditional"],"賞":["chinese_traditional"],"鴨":["chinese_traditional"],"趨":["chinese_traditional"],"鳳":["chinese_traditional"],"輩":["chinese_traditional"],"灘":["chinese_traditional"],"驅":["chinese_traditional"],"篩":["chinese_traditional"],"峽":["chinese_traditional"],"壽":["chinese_traditional"],"譯":["chinese_traditional"],"遲":["chinese_traditional"],"矽":["chinese_traditional"],"貸":["chinese_traditional"],"脅":["chinese_traditional"],"蝕":["chinese_traditional"],"奧":["chinese_traditional"],"鳴":["chinese_traditional"],"嶺":["chinese_traditional"],"憑":["chinese_traditional"],"繪":["chinese_traditional"],"錫":["chinese_traditional"],"廟":["chinese_traditional"],"籌":["chinese_traditional"],"凍":["chinese_traditional"],"輔":["chinese_traditional"],"攝":["chinese_traditional"],"襲":["chinese_traditional"],"鉀":["chinese_traditional"],"鳥":["chinese_traditional"],"韓":["chinese_traditional"],"僑":["chinese_traditional"],"涼":["chinese_traditional"],"餾":["chinese_traditional"],"勸":["chinese_traditional"],"遼":["chinese_traditional"],"鴻":["chinese_traditional"],"輥":["chinese_traditional"],"飲":["chinese_traditional"],"罵":["chinese_traditional"],"辭":["chinese_traditional"],"蔣":["chinese_traditional"],"絨":["chinese_traditional"],"霧":["chinese_traditional"],"擬":["chinese_traditional"],"輯":["chinese_traditional"],"陝":["chinese_traditional"],"償":["chinese_traditional"],"廳":["chinese_traditional"],"駛":["chinese_traditional"],"賦":["chinese_traditional"],"澆":["chinese_traditional"],"鈣":["chinese_traditional"],"虧":["chinese_traditional"],"騙":["chinese_traditional"],"脹":["chinese_traditional"],"諧":["chinese_traditional"],"拋":["chinese_traditional"],"黴":["chinese_traditional"],"崗":["chinese_traditional"],"盜":["chinese_traditional"],"滲":["chinese_traditional"],"臟":["chinese_traditional"],"賴":["chinese_traditional"],"湧":["chinese_traditional"],"閱":["chinese_traditional"],"厲":["chinese_traditional"],"烴":["chinese_traditional"],"緯":["chinese_traditional"],"偽":["chinese_traditional"],"嘆":["chinese_traditional"],"釘":["chinese_traditional"],"莖":["chinese_traditional"],"籠":["chinese_traditional"],"錐":["chinese_traditional"],"恆":["chinese_traditional"],"傑":["chinese_traditional"],"綸":["chinese_traditional"],"敘":["chinese_traditional"],"獄":["chinese_traditional"],"絡":["chinese_traditional"],"驟":["chinese_traditional"],"冊":["chinese_traditional"],"屍":["chinese_traditional"],"紳":["chinese_traditional"],"犧":["chinese_traditional"],"轟":["chinese_traditional"],"晉":["chinese_traditional"],"禦":["chinese_traditional"],"錠":["chinese_traditional"],"錦":["chinese_traditional"],"喪":["chinese_traditional"],"鍛":["chinese_traditional"],"壟":["chinese_traditional"],"撲":["chinese_traditional"],"邁":["chinese_traditional"],"閒":["chinese_traditional"],"憂":["chinese_traditional"],"頑":["chinese_traditional"],"漲":["chinese_traditional"],"闢":["chinese_traditional"],"懲":["chinese_traditional"],"飄":["chinese_traditional"],"飾":["chinese_traditional"],"蕭":["chinese_traditional"],"郵":["chinese_traditional"],"遷":["chinese_traditional"],"煩":["chinese_traditional"],"債":["chinese_traditional"],"帳":["chinese_traditional"],"鈴":["chinese_traditional"],"餅":["chinese_traditional"],"雛":["chinese_traditional"],"賢":["chinese_traditional"],"丟":["chinese_traditional"],"墊":["chinese_traditional"],"擋":["chinese_traditional"],"覽":["chinese_traditional"],"貪":["chinese_traditional"],"繳":["chinese_traditional"],"馮":["chinese_traditional"],"諾":["chinese_traditional"],"誼":["chinese_traditional"],"兇":["chinese_traditional"],"誣":["chinese_traditional"],"騎":["chinese_traditional"],"喬":["chinese_traditional"],"叢":["chinese_traditional"],"盧":["chinese_traditional"],"悶":["chinese_traditional"],"諮":["chinese_traditional"],"駕":["chinese_traditional"],"纜":["chinese_traditional"],"鉺":["chinese_traditional"],"擲":["chinese_traditional"],"頗":["chinese_traditional"],"慘":["chinese_traditional"],"臘":["chinese_traditional"],"窩":["chinese_traditional"],"滌":["chinese_traditional"],"劍":["chinese_traditional"],"潑":["chinese_traditional"],"蔥":["chinese_traditional"],"撈":["chinese_traditional"],"蒼":["chinese_traditional"],"濱":["chinese_traditional"],"倆":["chinese_traditional"],"瘋":["chinese_traditional"],"糞":["chinese_traditional"],"檔":["chinese_traditional"],"駁":["chinese_traditional"],"腸":["chinese_traditional"],"撐":["chinese_traditional"],"曬":["chinese_traditional"],"蓮":["chinese_traditional"],"攤":["chinese_traditional"],"攪":["chinese_traditional"],"醬":["chinese_traditional"],"皺":["chinese_traditional"],"暢":["chinese_traditional"],"疊":["chinese_traditional"],"閣":["chinese_traditional"],"萊":["chinese_traditional"],"轄":["chinese_traditional"],"鉤":["chinese_traditional"],"壩":["chinese_traditional"],"餓":["chinese_traditional"],"禍":["chinese_traditional"],"邏":["chinese_traditional"],"嘗":["chinese_traditional"],"韋":["chinese_traditional"],"abdikace":["czech"],"abeceda":["czech"],"adresa":["czech"],"agrese":["czech"],"akce":["czech"],"aktovka":["czech"],"alej":["czech"],"alkohol":["czech"],"amputace":["czech"],"ananas":["czech"],"andulka":["czech"],"anekdota":["czech"],"anketa":["czech"],"antika":["czech"],"anulovat":["czech"],"archa":["czech"],"arogance":["czech"],"asfalt":["czech","turkish"],"asistent":["czech"],"aspirace":["czech"],"astma":["czech"],"astronom":["czech"],"atlas":["czech"],"atletika":["czech"],"atol":["czech"],"autobus":["czech"],"azyl":["czech"],"babka":["czech"],"bachor":["czech"],"bacil":["czech"],"baculka":["czech"],"badatel":["czech"],"bageta":["czech"],"bagr":["czech"],"bahno":["czech"],"bakterie":["czech"],"balada":["czech"],"baletka":["czech"],"balkon":["czech"],"balonek":["czech"],"balvan":["czech"],"balza":["czech"],"bambus":["czech"],"bankomat":["czech"],"barbar":["czech"],"baret":["czech"],"barman":["czech"],"baroko":["czech"],"barva":["czech"],"baterka":["czech"],"batoh":["czech"],"bavlna":["czech"],"bazalka":["czech"],"bazilika":["czech"],"bazuka":["czech"],"bedna":["czech"],"beran":["czech"],"beseda":["czech"],"bestie":["czech"],"beton":["czech","turkish"],"bezinka":["czech"],"bezmoc":["czech"],"beztak":["czech"],"bicykl":["czech"],"bidlo":["czech"],"biftek":["czech","turkish"],"bikiny":["czech"],"bilance":["czech"],"biograf":["czech"],"biolog":["czech"],"bitva":["czech"],"bizon":["czech"],"blahobyt":["czech"],"blatouch":["czech"],"blecha":["czech"],"bledule":["czech"],"blesk":["czech"],"blikat":["czech"],"blizna":["czech"],"blokovat":["czech"],"bloudit":["czech"],"blud":["czech"],"bobek":["czech"],"bobr":["czech"],"bodlina":["czech"],"bodnout":["czech"],"bohatost":["czech"],"bojkot":["czech"],"bojovat":["czech"],"bokorys":["czech"],"bolest":["czech"],"borec":["czech"],"borovice":["czech"],"bota":["czech"],"boubel":["czech"],"bouchat":["czech"],"bouda":["czech"],"boule":["czech"],"bourat":["czech"],"boxer":["czech"],"bradavka":["czech"],"brambora":["czech"],"branka":["czech"],"bratr":["czech"],"brepta":["czech"],"briketa":["czech"],"brko":["czech"],"brloh":["czech"],"bronz":["czech"],"broskev":["czech"],"brunetka":["czech"],"brusinka":["czech"],"brzda":["czech"],"brzy":["czech"],"bublina":["czech"],"bubnovat":["czech"],"buchta":["czech"],"buditel":["czech"],"budka":["czech"],"budova":["czech"],"bufet":["czech"],"bujarost":["czech"],"bukvice":["czech"],"buldok":["czech"],"bulva":["czech"],"bunda":["czech"],"bunkr":["czech"],"burza":["czech"],"butik":["czech","turkish"],"buvol":["czech"],"buzola":["czech"],"bydlet":["czech"],"bylina":["czech"],"bytovka":["czech"],"bzukot":["czech"],"capart":["czech"],"carevna":["czech"],"cedr":["czech"],"cedule":["czech"],"cejch":["czech"],"cejn":["czech"],"cela":["czech"],"celer":["czech"],"celkem":["czech"],"celnice":["czech"],"cenina":["czech"],"cennost":["czech"],"cenovka":["czech"],"centrum":["czech"],"cenzor":["czech"],"cestopis":["czech"],"cetka":["czech"],"chalupa":["czech"],"chapadlo":["czech"],"charita":["czech"],"chata":["czech"],"chechtat":["czech"],"chemie":["czech"],"chichot":["czech"],"chirurg":["czech"],"chlad":["czech"],"chleba":["czech"],"chlubit":["czech"],"chmel":["czech"],"chmura":["czech"],"chobot":["czech"],"chochol":["czech"],"chodba":["czech"],"cholera":["czech"],"chomout":["czech"],"chopit":["czech"],"choroba":["czech"],"chov":["czech"],"chrapot":["czech"],"chrlit":["czech"],"chrt":["czech"],"chrup":["czech"],"chtivost":["czech"],"chudina":["czech"],"chutnat":["czech"],"chvat":["czech"],"chvilka":["czech"],"chvost":["czech"],"chyba":["czech"],"chystat":["czech"],"chytit":["czech"],"cibule":["czech"],"cigareta":["czech"],"cihelna":["czech"],"cihla":["czech"],"cinkot":["czech"],"cirkus":["czech"],"cisterna":["czech"],"citace":["czech"],"citrus":["czech"],"cizinec":["czech"],"cizost":["czech"],"clona":["czech"],"cokoliv":["czech"],"couvat":["czech"],"ctitel":["czech"],"ctnost":["czech"],"cudnost":["czech"],"cuketa":["czech"],"cukr":["czech"],"cupot":["czech"],"cvaknout":["czech"],"cval":["czech"],"cvik":["czech"],"cvrkot":["czech"],"cyklista":["czech"],"daleko":["czech"],"dareba":["czech"],"datel":["czech"],"datum":["czech"],"dcera":["czech"],"debata":["czech"],"dechovka":["czech"],"decibel":["czech"],"deficit":["czech"],"deflace":["czech"],"dekl":["czech"],"dekret":["czech"],"demokrat":["czech"],"deprese":["czech"],"derby":["czech"],"deska":["czech"],"detektiv":["czech"],"dikobraz":["czech"],"diktovat":["czech"],"dioda":["czech"],"diplom":["czech"],"disk":["czech","turkish"],"displej":["czech"],"divadlo":["czech"],"divoch":["czech"],"dlaha":["czech"],"dlouho":["czech"],"dluhopis":["czech"],"dnes":["czech"],"dobro":["czech"],"dobytek":["czech"],"docent":["czech"],"dochutit":["czech"],"dodnes":["czech"],"dohled":["czech"],"dohoda":["czech"],"dohra":["czech"],"dojem":["czech"],"dojnice":["czech"],"doklad":["czech"],"dokola":["czech"],"doktor":["czech","turkish"],"dokument":["czech"],"dolar":["czech"],"doleva":["czech"],"dolina":["czech"],"doma":["czech"],"dominant":["czech"],"domluvit":["czech"],"domov":["czech"],"donutit":["czech"],"dopad":["czech"],"dopis":["czech"],"doplnit":["czech"],"doposud":["czech"],"doprovod":["czech"],"dopustit":["czech"],"dorazit":["czech"],"dorost":["czech"],"dort":["czech"],"dosah":["czech"],"doslov":["czech"],"dostatek":["czech"],"dosud":["czech"],"dosyta":["czech"],"dotaz":["czech"],"dotek":["czech"],"dotknout":["czech"],"doufat":["czech"],"doutnat":["czech"],"dovozce":["czech"],"dozadu":["czech"],"doznat":["czech"],"dozorce":["czech"],"drahota":["czech"],"drak":["czech"],"dramatik":["czech"],"dravec":["czech"],"draze":["czech"],"drdol":["czech"],"drobnost":["czech"],"drogerie":["czech"],"drozd":["czech"],"drsnost":["czech"],"drtit":["czech"],"drzost":["czech"],"duben":["czech"],"duchovno":["czech"],"dudek":["czech"],"duha":["czech"],"duhovka":["czech"],"dusit":["czech"],"dusno":["czech"],"dutost":["czech"],"dvojice":["czech"],"dvorec":["czech"],"dynamit":["czech"],"ekolog":["czech"],"ekonomie":["czech"],"elektron":["czech"],"elipsa":["czech"],"email":["czech"],"emise":["czech"],"emoce":["czech"],"empatie":["czech"],"epizoda":["czech"],"epocha":["czech"],"epopej":["czech"],"epos":["czech"],"esej":["czech"],"esence":["czech"],"eskorta":["czech"],"eskymo":["czech"],"etiketa":["czech"],"euforie":["czech"],"evoluce":["czech"],"exekuce":["czech"],"exkurze":["czech"],"expedice":["czech"],"exploze":["czech"],"export":["czech"],"extrakt":["czech"],"facka":["czech"],"fajfka":["czech"],"fakulta":["czech"],"fanatik":["czech","turkish"],"fantazie":["czech"],"farmacie":["czech"],"favorit":["czech"],"fazole":["czech"],"federace":["czech"],"fejeton":["czech"],"fenka":["czech"],"fialka":["czech"],"figurant":["czech"],"filozof":["czech"],"filtr":["czech"],"finance":["czech"],"finta":["czech"],"fixace":["czech"],"fjord":["czech"],"flanel":["czech"],"flirt":["czech"],"flotila":["czech"],"fond":["czech"],"fosfor":["czech"],"fotbal":["czech"],"fotka":["czech"],"foton":["czech"],"frakce":["czech"],"freska":["czech"],"fronta":["czech"],"fukar":["czech"],"funkce":["czech"],"fyzika":["czech"],"galeje":["czech"],"garant":["czech"],"genetika":["czech"],"geolog":["czech"],"gilotina":["czech"],"glazura":["czech"],"glejt":["czech"],"golem":["czech"],"golfista":["czech"],"gotika":["czech"],"graf":["czech"],"gramofon":["czech"],"granule":["czech"],"grep":["czech"],"gril":["czech"],"grog":["czech"],"groteska":["czech"],"guma":["czech"],"hadice":["czech"],"hadr":["czech"],"hala":["czech"],"halenka":["czech"],"hanba":["czech"],"hanopis":["czech"],"harfa":["czech"],"harpuna":["czech"],"havran":["czech"],"hebkost":["czech"],"hejkal":["czech"],"hejno":["czech"],"hejtman":["czech"],"hektar":["czech","turkish"],"helma":["czech"],"hematom":["czech"],"herec":["czech"],"herna":["czech"],"heslo":["czech"],"hezky":["czech"],"historik":["czech"],"hladovka":["czech"],"hlasivky":["czech"],"hlava":["czech"],"hledat":["czech"],"hlen":["czech"],"hlodavec":["czech"],"hloh":["czech"],"hloupost":["czech"],"hltat":["czech"],"hlubina":["czech"],"hluchota":["czech"],"hmat":["czech"],"hmota":["czech"],"hmyz":["czech"],"hnis":["czech"],"hnojivo":["czech"],"hnout":["czech"],"hoblina":["czech"],"hoboj":["czech"],"hoch":["czech"],"hodiny":["czech"],"hodlat":["czech"],"hodnota":["czech"],"hodovat":["czech"],"hojnost":["czech"],"hokej":["czech"],"holinka":["czech"],"holka":["czech"],"holub":["czech"],"homole":["czech"],"honitba":["czech"],"honorace":["czech"],"horal":["czech"],"horda":["czech"],"horizont":["czech"],"horko":["czech"],"horlivec":["czech"],"hormon":["czech","turkish"],"hornina":["czech"],"horoskop":["czech"],"horstvo":["czech"],"hospoda":["czech"],"hostina":["czech"],"hotovost":["czech"],"houba":["czech"],"houf":["czech"],"houpat":["czech"],"houska":["czech"],"hovor":["czech"],"hradba":["czech"],"hranice":["czech"],"hravost":["czech"],"hrazda":["czech"],"hrbolek":["czech"],"hrdina":["czech"],"hrdlo":["czech"],"hrdost":["czech"],"hrnek":["czech"],"hrobka":["czech"],"hromada":["czech"],"hrot":["czech"],"hrouda":["czech"],"hrozen":["czech"],"hrstka":["czech"],"hrubost":["czech"],"hryzat":["czech"],"hubenost":["czech"],"hubnout":["czech"],"hudba":["czech"],"hukot":["czech"],"humr":["czech"],"husita":["czech"],"hustota":["czech"],"hvozd":["czech"],"hybnost":["czech"],"hydrant":["czech"],"hygiena":["czech"],"hymna":["czech"],"hysterik":["czech"],"idylka":["czech"],"ihned":["czech"],"ikona":["czech"],"iluze":["czech"],"imunita":["czech"],"infekce":["czech"],"inflace":["czech"],"inkaso":["czech"],"inovace":["czech"],"inspekce":["czech"],"internet":["czech"],"invalida":["czech"],"investor":["czech"],"inzerce":["czech"],"ironie":["czech"],"jablko":["czech"],"jachta":["czech"],"jahoda":["czech"],"jakmile":["czech"],"jakost":["czech"],"jalovec":["czech"],"jantar":["czech"],"jarmark":["czech"],"jaro":["czech"],"jasan":["czech"],"jasno":["czech"],"jatka":["czech"],"javor":["czech"],"jazyk":["czech"],"jedinec":["czech"],"jedle":["czech"],"jednatel":["czech"],"jehlan":["czech"],"jekot":["czech"],"jelen":["czech"],"jelito":["czech"],"jemnost":["czech"],"jenom":["czech"],"jepice":["czech"],"jeseter":["czech"],"jevit":["czech"],"jezdec":["czech"],"jezero":["czech"],"jinak":["czech"],"jindy":["czech"],"jinoch":["czech"],"jiskra":["czech"],"jistota":["czech"],"jitrnice":["czech"],"jizva":["czech"],"jmenovat":["czech"],"jogurt":["czech"],"jurta":["czech"],"kabaret":["czech"],"kabel":["czech"],"kabinet":["czech"],"kachna":["czech"],"kadet":["czech"],"kadidlo":["czech"],"kahan":["czech"],"kajak":["czech"],"kajuta":["czech"],"kakao":["czech"],"kaktus":["czech"],"kalamita":["czech"],"kalhoty":["czech"],"kalibr":["czech"],"kalnost":["czech"],"kamera":["czech"],"kamkoliv":["czech"],"kamna":["czech"],"kanibal":["czech"],"kanoe":["czech"],"kantor":["czech"],"kapalina":["czech"],"kapela":["czech"],"kapitola":["czech"],"kapka":["czech"],"kaple":["czech"],"kapota":["czech"],"kapr":["czech"],"kapusta":["czech"],"kapybara":["czech"],"karamel":["czech"],"karotka":["czech"],"karton":["czech"],"kasa":["czech"],"katalog":["czech"],"katedra":["czech"],"kauce":["czech"],"kauza":["czech"],"kavalec":["czech"],"kazajka":["czech"],"kazeta":["czech"],"kazivost":["czech"],"kdekoliv":["czech"],"kdesi":["czech"],"kedluben":["czech"],"kemp":["czech"],"keramika":["czech"],"kino":["czech"],"klacek":["czech"],"kladivo":["czech"],"klam":["czech"],"klapot":["czech"],"klasika":["czech"],"klaun":["czech"],"klec":["czech"],"klenba":["czech"],"klepat":["czech"],"klesnout":["czech"],"klid":["czech"],"klima":["czech"],"klisna":["czech"],"klobouk":["czech"],"klokan":["czech"],"klopa":["czech"],"kloub":["czech"],"klubovna":["czech"],"klusat":["czech"],"kluzkost":["czech"],"kmen":["czech"],"kmitat":["czech"],"kmotr":["czech"],"kniha":["czech"],"knot":["czech"],"koalice":["czech"],"koberec":["czech"],"kobka":["czech"],"kobliha":["czech"],"kobyla":["czech"],"kocour":["czech"],"kohout":["czech"],"kojenec":["czech"],"kokos":["czech"],"koktejl":["czech"],"kolaps":["czech"],"koleda":["czech"],"kolize":["czech"],"kolo":["czech"],"komando":["czech"],"kometa":["czech"],"komik":["czech"],"komnata":["czech"],"komora":["czech"],"kompas":["czech"],"komunita":["czech"],"konat":["czech"],"koncept":["czech"],"kondice":["czech"],"konec":["czech"],"konfese":["czech"],"kongres":["czech"],"konina":["czech"],"konkurs":["czech"],"kontakt":["czech"],"konzerva":["czech"],"kopanec":["czech"],"kopie":["czech"],"kopnout":["czech"],"koprovka":["czech"],"korbel":["czech"],"korektor":["czech"],"kormidlo":["czech"],"koroptev":["czech"],"korpus":["czech"],"koruna":["czech"],"koryto":["czech"],"korzet":["czech"],"kosatec":["czech"],"kostka":["czech"],"kotel":["czech"],"kotleta":["czech"],"kotoul":["czech"],"koukat":["czech"],"koupelna":["czech"],"kousek":["czech"],"kouzlo":["czech"],"kovboj":["czech"],"koza":["czech"],"kozoroh":["czech"],"krabice":["czech"],"krach":["czech"],"krajina":["czech"],"kralovat":["czech"],"krasopis":["czech"],"kravata":["czech"],"kredit":["czech"],"krejcar":["czech"],"kresba":["czech"],"kreveta":["czech"],"kriket":["czech"],"kritik":["czech"],"krize":["czech"],"krkavec":["czech"],"krmelec":["czech"],"krmivo":["czech"],"krocan":["czech"],"krok":["czech"],"kronika":["czech"],"kropit":["czech"],"kroupa":["czech"],"krovka":["czech"],"krtek":["czech"],"kruhadlo":["czech"],"krupice":["czech"],"krutost":["czech"],"krvinka":["czech"],"krychle":["czech"],"krypta":["czech"],"krystal":["czech"],"kryt":["czech"],"kudlanka":["czech"],"kufr":["czech"],"kujnost":["czech"],"kukla":["czech"],"kulajda":["czech"],"kulich":["czech"],"kulka":["czech"],"kulomet":["czech"],"kultura":["czech"],"kuna":["czech"],"kupodivu":["czech"],"kurt":["czech"],"kurzor":["czech"],"kutil":["czech"],"kvalita":["czech"],"kvasinka":["czech"],"kvestor":["czech"],"kynolog":["czech"],"kyselina":["czech"],"kytara":["czech"],"kytice":["czech"],"kytka":["czech"],"kytovec":["czech"],"kyvadlo":["czech"],"labrador":["czech"],"lachtan":["czech"],"ladnost":["czech"],"laik":["czech"],"lakomec":["czech"],"lamela":["czech"],"lampa":["czech"],"lanovka":["czech"],"lasice":["czech"],"laso":["czech"],"lastura":["czech"],"latinka":["czech"],"lavina":["czech"],"lebka":["czech"],"leckdy":["czech"],"leden":["czech"],"lednice":["czech"],"ledovka":["czech"],"ledvina":["czech"],"legenda":["czech"],"legie":["czech"],"legrace":["czech"],"lehce":["czech"],"lehkost":["czech"],"lehnout":["czech"],"lektvar":["czech"],"lenochod":["czech"],"lentilka":["czech"],"lepenka":["czech"],"lepidlo":["czech"],"letadlo":["czech"],"letec":["czech"],"letmo":["czech"],"letokruh":["czech"],"levhart":["czech"],"levitace":["czech"],"levobok":["czech"],"libra":["czech"],"lichotka":["czech"],"lidojed":["czech"],"lidskost":["czech"],"lihovina":["czech"],"lijavec":["czech"],"lilek":["czech"],"limetka":["czech"],"linie":["czech"],"linka":["czech"],"linoleum":["czech"],"listopad":["czech"],"litina":["czech"],"litovat":["czech"],"lobista":["czech"],"lodivod":["czech"],"logika":["czech"],"logoped":["czech"],"lokalita":["czech"],"loket":["czech"],"lomcovat":["czech"],"lopata":["czech"],"lopuch":["czech"],"lord":["czech"],"losos":["czech"],"lotr":["czech"],"loudal":["czech"],"louh":["czech"],"louka":["czech"],"louskat":["czech"],"lovec":["czech"],"lstivost":["czech"],"lucerna":["czech"],"lucifer":["czech"],"lump":["czech"],"lusk":["czech"],"lustrace":["czech"],"lvice":["czech"],"lyra":["czech"],"lyrika":["czech"],"lysina":["czech"],"madam":["czech"],"madlo":["czech"],"magistr":["czech"],"mahagon":["czech"],"majetek":["czech"],"majitel":["czech"],"majorita":["czech"],"makak":["czech"],"makovice":["czech"],"makrela":["czech"],"malba":["czech"],"malina":["czech"],"malovat":["czech"],"malvice":["czech"],"maminka":["czech"],"mandle":["czech"],"manko":["czech"],"marnost":["czech"],"masakr":["czech"],"maskot":["czech"],"masopust":["czech"],"matice":["czech"],"matrika":["czech"],"maturita":["czech"],"mazanec":["czech"],"mazivo":["czech"],"mazlit":["czech"],"mazurka":["czech"],"mdloba":["czech"],"mechanik":["czech"],"meditace":["czech"],"medovina":["czech"],"melasa":["czech"],"meloun":["czech"],"mentolka":["czech"],"metla":["czech"],"metoda":["czech"],"metr":["czech"],"mezera":["czech"],"migrace":["czech"],"mihnout":["czech"],"mihule":["czech"],"mikina":["czech"],"mikrofon":["czech","turkish"],"milenec":["czech"],"milimetr":["czech"],"milost":["czech"],"mimika":["czech"],"mincovna":["czech"],"minibar":["czech"],"minomet":["czech"],"minulost":["czech"],"miska":["czech"],"mistr":["czech"],"mixovat":["czech"],"mladost":["czech"],"mlha":["czech"],"mlhovina":["czech"],"mlok":["czech"],"mlsat":["czech"],"mluvit":["czech"],"mnich":["czech"],"mnohem":["czech"],"mobil":["czech"],"mocnost":["czech"],"modelka":["czech"],"modlitba":["czech"],"mohyla":["czech"],"mokro":["czech"],"molekula":["czech"],"momentka":["czech"],"monarcha":["czech"],"monokl":["czech"],"monstrum":["czech"],"montovat":["czech"],"monzun":["czech"],"mosaz":["czech"],"moskyt":["czech"],"most":["czech"],"motivace":["czech"],"motorka":["czech"],"motyka":["czech"],"moucha":["czech"],"moudrost":["czech"],"mozaika":["czech"],"mozek":["czech"],"mozol":["czech"],"mramor":["czech"],"mravenec":["czech"],"mrkev":["czech"],"mrtvola":["czech"],"mrzet":["czech"],"mrzutost":["czech"],"mstitel":["czech"],"mudrc":["czech"],"muflon":["czech"],"mulat":["czech"],"mumie":["czech"],"munice":["czech"],"muset":["czech"],"mutace":["czech"],"muzeum":["czech"],"muzikant":["czech"],"myslivec":["czech"],"mzda":["czech"],"nabourat":["czech"],"nachytat":["czech"],"nadace":["czech"],"nadbytek":["czech"],"nadhoz":["czech"],"nadobro":["czech"],"nadpis":["czech"],"nahlas":["czech"],"nahnat":["czech"],"nahodile":["czech"],"nahradit":["czech"],"naivita":["czech"],"najednou":["czech"],"najisto":["czech"],"najmout":["czech"],"naklonit":["czech"],"nakonec":["czech"],"nakrmit":["czech"],"nalevo":["czech"],"namazat":["czech"],"namluvit":["czech"],"nanometr":["czech"],"naoko":["czech"],"naopak":["czech"],"naostro":["czech"],"napadat":["czech"],"napevno":["czech"],"naplnit":["czech"],"napnout":["czech"],"naposled":["czech"],"naprosto":["czech"],"narodit":["czech"],"naruby":["czech"],"narychlo":["czech"],"nasadit":["czech"],"nasekat":["czech"],"naslepo":["czech"],"nastat":["czech"],"natolik":["czech"],"navenek":["czech"],"navrch":["czech"],"navzdory":["czech"],"nazvat":["czech"],"nebe":["czech"],"nechat":["czech"],"necky":["czech"],"nedaleko":["czech"],"nedbat":["czech"],"neduh":["czech"],"negace":["czech"],"nehet":["czech"],"nehoda":["czech"],"nejen":["czech"],"nejprve":["czech"],"neklid":["czech"],"nelibost":["czech"],"nemilost":["czech"],"nemoc":["czech"],"neochota":["czech"],"neonka":["czech"],"nepokoj":["czech"],"nerost":["czech"],"nerv":["czech"],"nesmysl":["czech"],"nesoulad":["czech"],"netvor":["czech"],"neuron":["czech"],"nevina":["czech"],"nezvykle":["czech"],"nicota":["czech"],"nijak":["czech"],"nikam":["czech"],"nikdy":["czech"],"nikl":["czech"],"nikterak":["czech"],"nitro":["czech"],"nocleh":["czech"],"nohavice":["czech"],"nominace":["czech"],"nora":["czech"],"norek":["czech"],"nositel":["czech"],"nosnost":["czech"],"nouze":["czech"],"noviny":["czech"],"novota":["czech"],"nozdra":["czech"],"nuda":["czech"],"nudle":["czech"],"nuget":["czech"],"nutit":["czech"],"nutnost":["czech"],"nutrie":["czech"],"nymfa":["czech"],"obal":["czech"],"obarvit":["czech"],"obava":["czech"],"obdiv":["czech"],"obec":["czech"],"obehnat":["czech"],"obejmout":["czech"],"obezita":["czech"],"obhajoba":["czech"],"obilnice":["czech"],"objasnit":["czech"],"objekt":["czech"],"obklopit":["czech"],"oblast":["czech"],"oblek":["czech"],"obliba":["czech"],"obloha":["czech"],"obluda":["czech"],"obnos":["czech"],"obohatit":["czech"],"obojek":["czech"],"obout":["czech"],"obrazec":["czech"],"obrna":["czech"],"obruba":["czech"],"obrys":["czech"],"obsah":["czech"],"obsluha":["czech"],"obstarat":["czech"],"obuv":["czech"],"obvaz":["czech"],"obvinit":["czech"],"obvod":["czech"],"obvykle":["czech"],"obyvatel":["czech"],"obzor":["czech"],"ocas":["czech"],"ocel":["czech"],"ocenit":["czech"],"ochladit":["czech"],"ochota":["czech"],"ochrana":["czech"],"ocitnout":["czech"],"odboj":["czech"],"odbyt":["czech"],"odchod":["czech"],"odcizit":["czech"],"odebrat":["czech"],"odeslat":["czech"],"odevzdat":["czech"],"odezva":["czech"],"odhadce":["czech"],"odhodit":["czech"],"odjet":["czech"],"odjinud":["czech"],"odkaz":["czech"],"odkoupit":["czech"],"odliv":["czech"],"odluka":["czech"],"odmlka":["czech"],"odolnost":["czech"],"odpad":["czech"],"odpis":["czech"],"odplout":["czech"],"odpor":["czech"],"odpustit":["czech"],"odpykat":["czech"],"odrazka":["czech"],"odsoudit":["czech"],"odstup":["czech"],"odsun":["czech"],"odtok":["czech"],"odtud":["czech"],"odvaha":["czech"],"odveta":["czech"],"odvolat":["czech"],"odvracet":["czech"],"odznak":["czech"],"ofina":["czech"],"ofsajd":["czech"],"ohlas":["czech"],"ohnisko":["czech"],"ohrada":["czech"],"ohrozit":["czech"],"ohryzek":["czech"],"okap":["czech"],"okenice":["czech"],"oklika":["czech"],"okno":["czech"],"okouzlit":["czech"],"okovy":["czech"],"okrasa":["czech"],"okres":["czech"],"okrsek":["czech"],"okruh":["czech"],"okupant":["czech"],"okurka":["czech"],"okusit":["czech"],"olejnina":["czech"],"olizovat":["czech"],"omak":["czech"],"omeleta":["czech"],"omezit":["czech"],"omladina":["czech"],"omlouvat":["czech"],"omluva":["czech"],"omyl":["czech"],"onehdy":["czech"],"opakovat":["czech"],"opasek":["czech"],"operace":["czech"],"opice":["czech"],"opilost":["czech"],"opisovat":["czech"],"opora":["czech"],"opozice":["czech"],"opravdu":["czech"],"oproti":["czech"],"orbital":["czech"],"orchestr":["czech"],"orgie":["czech"],"orlice":["czech"],"orloj":["czech"],"ortel":["czech"],"osada":["czech"],"oschnout":["czech"],"osika":["czech"],"osivo":["czech"],"oslava":["czech"],"oslepit":["czech"],"oslnit":["czech"],"oslovit":["czech"],"osnova":["czech"],"osoba":["czech"],"osolit":["czech"],"ospalec":["czech"],"osten":["czech"],"ostraha":["czech"],"ostuda":["czech"],"ostych":["czech"],"osvojit":["czech"],"oteplit":["czech"],"otisk":["czech"],"otop":["czech"],"otrhat":["czech"],"otrlost":["czech"],"otrok":["czech"],"otruby":["czech"],"otvor":["czech"],"ovanout":["czech"],"ovar":["czech"],"oves":["czech"],"ovlivnit":["czech"],"ovoce":["czech"],"oxid":["czech"],"ozdoba":["czech"],"pachatel":["czech"],"pacient":["czech"],"padouch":["czech"],"pahorek":["czech"],"pakt":["czech"],"palanda":["czech"],"palec":["czech"],"palivo":["czech"],"paluba":["czech"],"pamflet":["czech"],"pamlsek":["czech"],"panenka":["czech"],"panika":["czech"],"panna":["czech"],"panovat":["czech"],"panstvo":["czech"],"pantofle":["czech"],"paprika":["czech"],"parketa":["czech"],"parodie":["czech"],"parta":["czech"],"paruka":["czech"],"paryba":["czech"],"paseka":["czech"],"pasivita":["czech"],"pastelka":["czech"],"patent":["czech"],"patrona":["czech"],"pavouk":["czech"],"pazneht":["czech"],"pazourek":["czech"],"pecka":["czech"],"pedagog":["czech"],"pejsek":["czech"],"peklo":["czech"],"peloton":["czech"],"penalta":["czech"],"pendrek":["czech"],"penze":["czech"],"periskop":["czech"],"pero":["czech"],"pestrost":["czech"],"petarda":["czech"],"petice":["czech"],"petrolej":["czech"],"pevnina":["czech"],"pexeso":["czech"],"pianista":["czech"],"piha":["czech"],"pijavice":["czech"],"pikle":["czech"],"piknik":["czech","turkish"],"pilina":["czech"],"pilnost":["czech"],"pilulka":["czech"],"pinzeta":["czech"],"pipeta":["czech"],"pisatel":["czech"],"pistole":["czech"],"pitevna":["czech"],"pivnice":["czech"],"pivovar":["czech"],"placenta":["czech"],"plakat":["czech"],"plamen":["czech"],"planeta":["czech"],"plastika":["czech"],"platit":["czech"],"plavidlo":["czech"],"plaz":["czech"],"plech":["czech"],"plemeno":["czech"],"plenta":["czech"],"ples":["czech"],"pletivo":["czech"],"plevel":["czech"],"plivat":["czech"],"plnit":["czech"],"plno":["czech"],"plocha":["czech"],"plodina":["czech"],"plomba":["czech"],"plout":["czech"],"pluk":["czech"],"plyn":["czech"],"pobavit":["czech"],"pobyt":["czech"],"pochod":["czech"],"pocit":["czech"],"poctivec":["czech"],"podat":["czech"],"podcenit":["czech"],"podepsat":["czech"],"podhled":["czech"],"podivit":["czech"],"podklad":["czech"],"podmanit":["czech"],"podnik":["czech"],"podoba":["czech"],"podpora":["czech"],"podraz":["czech"],"podstata":["czech"],"podvod":["czech"],"podzim":["czech"],"poezie":["czech"],"pohanka":["czech"],"pohnutka":["czech"],"pohovor":["czech"],"pohroma":["czech"],"pohyb":["czech"],"pointa":["czech"],"pojistka":["czech"],"pojmout":["czech"],"pokazit":["czech"],"pokles":["czech"],"pokoj":["czech"],"pokrok":["czech"],"pokuta":["czech"],"pokyn":["czech"],"poledne":["czech"],"polibek":["czech"],"polknout":["czech"],"poloha":["czech"],"polynom":["czech"],"pomalu":["czech"],"pominout":["czech"],"pomlka":["czech"],"pomoc":["czech"],"pomsta":["czech"],"pomyslet":["czech"],"ponechat":["czech"],"ponorka":["czech"],"ponurost":["czech"],"popadat":["czech"],"popel":["czech"],"popisek":["czech"],"poplach":["czech"],"poprosit":["czech"],"popsat":["czech"],"popud":["czech"],"poradce":["czech"],"porce":["czech"],"porod":["czech"],"porucha":["czech"],"poryv":["czech"],"posadit":["czech"],"posed":["czech"],"posila":["czech"],"poskok":["czech"],"poslanec":["czech"],"posoudit":["czech"],"pospolu":["czech"],"postava":["czech"],"posudek":["czech"],"posyp":["czech"],"potah":["czech"],"potkan":["czech"],"potlesk":["czech"],"potomek":["czech"],"potrava":["czech"],"potupa":["czech"],"potvora":["czech"],"poukaz":["czech"],"pouto":["czech"],"pouzdro":["czech"],"povaha":["czech"],"povidla":["czech"],"povlak":["czech"],"povoz":["czech"],"povrch":["czech"],"povstat":["czech"],"povyk":["czech"],"povzdech":["czech"],"pozdrav":["czech"],"pozemek":["czech"],"poznatek":["czech"],"pozor":["czech"],"pozvat":["czech"],"pracovat":["czech"],"prahory":["czech"],"praktika":["czech"],"prales":["czech"],"praotec":["czech"],"praporek":["czech"],"prase":["czech"],"pravda":["czech"],"princip":["czech"],"prkno":["czech"],"probudit":["czech"],"procento":["czech"],"prodej":["czech"],"profese":["czech"],"prohra":["czech"],"projekt":["czech"],"prolomit":["czech"],"promile":["czech"],"pronikat":["czech"],"propad":["czech"],"prorok":["czech"],"prosba":["czech"],"proton":["czech"],"proutek":["czech"],"provaz":["czech"],"prskavka":["czech"],"prsten":["czech"],"prudkost":["czech"],"prut":["czech"],"prvek":["czech"],"prvohory":["czech"],"psanec":["czech"],"psovod":["czech"],"pstruh":["czech"],"ptactvo":["czech"],"puberta":["czech"],"puch":["czech"],"pudl":["czech"],"pukavec":["czech"],"puklina":["czech"],"pukrle":["czech"],"pult":["czech"],"pumpa":["czech"],"punc":["czech"],"pupen":["czech"],"pusa":["czech"],"pusinka":["czech"],"pustina":["czech"],"putovat":["czech"],"putyka":["czech"],"pyramida":["czech"],"pysk":["czech"],"pytel":["czech"],"racek":["czech"],"rachot":["czech"],"radiace":["czech"],"radnice":["czech"],"radon":["czech"],"raft":["czech"],"ragby":["czech"],"raketa":["czech"],"rakovina":["czech"],"rameno":["czech"],"rampouch":["czech"],"rande":["czech"],"rarach":["czech"],"rarita":["czech"],"rasovna":["czech"],"rastr":["czech"],"ratolest":["czech"],"razance":["czech"],"razidlo":["czech"],"reagovat":["czech"],"reakce":["czech"],"recept":["czech"],"redaktor":["czech"],"referent":["czech"],"reflex":["czech"],"rejnok":["czech"],"reklama":["czech"],"rekord":["czech"],"rekrut":["czech"],"rektor":["czech"],"reputace":["czech"],"revize":["czech","turkish"],"revma":["czech"],"revolver":["czech"],"rezerva":["czech"],"riskovat":["czech"],"riziko":["czech"],"robotika":["czech"],"rodokmen":["czech"],"rohovka":["czech"],"rokle":["czech"],"rokoko":["czech"],"romaneto":["czech"],"ropovod":["czech"],"ropucha":["czech"],"rorejs":["czech"],"rosol":["czech"],"rostlina":["czech"],"rotmistr":["czech"],"rotoped":["czech"],"rotunda":["czech"],"roubenka":["czech"],"roucho":["czech"],"roup":["czech"],"roura":["czech"],"rovina":["czech"],"rovnice":["czech"],"rozbor":["czech"],"rozchod":["czech"],"rozdat":["czech"],"rozeznat":["czech"],"rozhodce":["czech"],"rozinka":["czech"],"rozjezd":["czech"],"rozkaz":["czech"],"rozloha":["czech"],"rozmar":["czech"],"rozpad":["czech"],"rozruch":["czech"],"rozsah":["czech"],"roztok":["czech"],"rozum":["czech"],"rozvod":["czech"],"rubrika":["czech"],"ruchadlo":["czech"],"rukavice":["czech"],"rukopis":["czech"],"ryba":["czech"],"rybolov":["czech"],"rychlost":["czech"],"rydlo":["czech"],"rypadlo":["czech"],"rytina":["czech"],"ryzost":["czech"],"sadista":["czech"],"sahat":["czech"],"sako":["czech"],"samec":["czech"],"samizdat":["czech"],"samota":["czech"],"sanitka":["czech"],"sardinka":["czech"],"sasanka":["czech"],"satelit":["czech"],"sazba":["czech"],"sazenice":["czech"],"sbor":["czech"],"schovat":["czech"],"sebranka":["czech"],"secese":["czech"],"sedadlo":["czech"],"sediment":["czech"],"sedlo":["czech"],"sehnat":["czech"],"sejmout":["czech"],"sekera":["czech"],"sekta":["czech"],"sekunda":["czech"],"sekvoje":["czech"],"semeno":["czech"],"seno":["czech"],"servis":["czech","turkish"],"sesadit":["czech"],"seshora":["czech"],"seskok":["czech"],"seslat":["czech"],"sestra":["czech"],"sesuv":["czech"],"sesypat":["czech"],"setba":["czech"],"setina":["czech"],"setkat":["czech"],"setnout":["czech"],"setrvat":["czech"],"sever":["czech"],"seznam":["czech"],"shoda":["czech"],"shrnout":["czech"],"sifon":["czech"],"silnice":["czech"],"sirka":["czech"],"sirotek":["czech"],"sirup":["czech"],"situace":["czech"],"skafandr":["czech"],"skalisko":["czech"],"skanzen":["czech"],"skaut":["czech"],"skeptik":["czech"],"skica":["czech"],"skladba":["czech"],"sklenice":["czech"],"sklo":["czech"],"skluz":["czech"],"skoba":["czech"],"skokan":["czech"],"skoro":["czech"],"skripta":["czech"],"skrz":["czech"],"skupina":["czech"],"skvost":["czech"],"skvrna":["czech"],"slabika":["czech"],"sladidlo":["czech"],"slanina":["czech"],"slast":["czech"],"slavnost":["czech"],"sledovat":["czech"],"slepec":["czech"],"sleva":["czech"],"slezina":["czech"],"slib":["czech"],"slina":["czech"],"sliznice":["czech"],"slon":["czech"],"sloupek":["czech"],"slovo":["czech"],"sluch":["czech"],"sluha":["czech"],"slunce":["czech"],"slupka":["czech"],"slza":["czech"],"smaragd":["czech"],"smetana":["czech"],"smilstvo":["czech"],"smlouva":["czech"],"smog":["czech"],"smrad":["czech"],"smrk":["czech"],"smrtka":["czech"],"smutek":["czech"],"smysl":["czech"],"snad":["czech"],"snaha":["czech"],"snob":["czech"],"sobota":["czech"],"socha":["czech"],"sodovka":["czech"],"sokol":["czech"],"sopka":["czech"],"sotva":["czech"],"souboj":["czech"],"soucit":["czech"],"soudce":["czech"],"souhlas":["czech"],"soulad":["czech"],"soumrak":["czech"],"souprava":["czech"],"soused":["czech"],"soutok":["czech"],"souviset":["czech"],"spalovna":["czech"],"spasitel":["czech"],"spis":["czech"],"splav":["czech"],"spodek":["czech"],"spojenec":["czech"],"spolu":["czech"],"sponzor":["czech"],"spornost":["czech"],"spousta":["czech"],"sprcha":["czech"],"spustit":["czech"],"sranda":["czech"],"sraz":["czech"],"srdce":["czech"],"srna":["czech"],"srnec":["czech"],"srovnat":["czech"],"srpen":["czech"],"srst":["czech"],"srub":["czech"],"stanice":["czech"],"starosta":["czech"],"statika":["czech"],"stavba":["czech"],"stehno":["czech"],"stezka":["czech"],"stodola":["czech"],"stolek":["czech"],"stopa":["czech"],"storno":["czech"],"stoupat":["czech"],"strach":["czech"],"stres":["czech"],"strhnout":["czech"],"strom":["czech"],"struna":["czech"],"studna":["czech"],"stupnice":["czech"],"stvol":["czech"],"styk":["czech"],"subjekt":["czech"],"subtropy":["czech"],"suchar":["czech"],"sudost":["czech"],"sukno":["czech"],"sundat":["czech"],"sunout":["czech"],"surikata":["czech"],"surovina":["czech"],"svah":["czech"],"svalstvo":["czech"],"svetr":["czech"],"svatba":["czech"],"svazek":["czech"],"svisle":["czech"],"svitek":["czech"],"svoboda":["czech"],"svodidlo":["czech"],"svorka":["czech"],"svrab":["czech"],"sykavka":["czech"],"sykot":["czech"],"synek":["czech"],"synovec":["czech"],"sypat":["czech"],"sypkost":["czech"],"syrovost":["czech"],"sysel":["czech"],"sytost":["czech"],"tabletka":["czech"],"tabule":["czech"],"tahoun":["czech"],"tajemno":["czech"],"tajfun":["czech"],"tajga":["czech"],"tajit":["czech"],"tajnost":["czech"],"taktika":["czech"],"tamhle":["czech"],"tampon":["czech","turkish"],"tancovat":["czech"],"tanec":["czech"],"tanker":["czech"],"tapeta":["czech"],"tavenina":["czech"],"tazatel":["czech"],"technika":["czech"],"tehdy":["czech"],"tekutina":["czech"],"telefon":["czech"],"temnota":["czech"],"tendence":["czech"],"tenista":["czech"],"tenor":["czech"],"teplota":["czech"],"tepna":["czech"],"teprve":["czech"],"terapie":["czech"],"termoska":["czech"],"textil":["czech"],"ticho":["czech"],"tiskopis":["czech"],"titulek":["czech"],"tkadlec":["czech"],"tkanina":["czech"],"tlapka":["czech"],"tleskat":["czech"],"tlukot":["czech"],"tlupa":["czech"],"tmel":["czech"],"toaleta":["czech"],"topinka":["czech"],"topol":["czech"],"torzo":["czech"],"touha":["czech"],"toulec":["czech"],"tradice":["czech"],"traktor":["czech"],"tramp":["czech"],"trasa":["czech"],"traverza":["czech"],"trefit":["czech"],"trest":["czech"],"trezor":["czech"],"trhavina":["czech"],"trhlina":["czech"],"trochu":["czech"],"trojice":["czech"],"troska":["czech"],"trouba":["czech"],"trpce":["czech"],"trpitel":["czech"],"trpkost":["czech"],"trubec":["czech"],"truchlit":["czech"],"truhlice":["czech"],"trus":["czech"],"trvat":["czech"],"tudy":["czech"],"tuhnout":["czech"],"tuhost":["czech"],"tundra":["czech"],"turista":["czech"],"turnaj":["czech"],"tuzemsko":["czech"],"tvaroh":["czech"],"tvorba":["czech"],"tvrdost":["czech"],"tvrz":["czech"],"tygr":["czech"],"tykev":["czech"],"ubohost":["czech"],"uboze":["czech"],"ubrat":["czech"],"ubrousek":["czech"],"ubrus":["czech"],"ubytovna":["czech"],"ucho":["czech"],"uctivost":["czech"],"udivit":["czech"],"uhradit":["czech"],"ujednat":["czech"],"ujistit":["czech"],"ujmout":["czech"],"ukazatel":["czech"],"uklidnit":["czech"],"uklonit":["czech"],"ukotvit":["czech"],"ukrojit":["czech"],"ulice":["czech"],"ulita":["czech"],"ulovit":["czech"],"umyvadlo":["czech"],"unavit":["czech"],"uniforma":["czech"],"uniknout":["czech"],"upadnout":["czech"],"uplatnit":["czech"],"uplynout":["czech"],"upoutat":["czech"],"upravit":["czech"],"uran":["czech"],"urazit":["czech"],"usednout":["czech"],"usilovat":["czech"],"usmrtit":["czech"],"usnadnit":["czech"],"usnout":["czech"],"usoudit":["czech"],"ustlat":["czech"],"ustrnout":["czech"],"utahovat":["czech"],"utkat":["czech"],"utlumit":["czech"],"utonout":["czech"],"utopenec":["czech"],"utrousit":["czech"],"uvalit":["czech"],"uvolnit":["czech"],"uvozovka":["czech"],"uzdravit":["czech"],"uzel":["czech"],"uzenina":["czech"],"uzlina":["czech"],"uznat":["czech"],"vagon":["czech","turkish"],"valcha":["czech"],"valoun":["czech"],"vana":["czech"],"vandal":["czech"],"vanilka":["czech"],"varan":["czech"],"varhany":["czech"],"varovat":["czech"],"vcelku":["czech"],"vchod":["czech"],"vdova":["czech"],"vedro":["czech"],"vegetace":["czech"],"vejce":["czech"],"velbloud":["czech"],"veletrh":["czech"],"velitel":["czech"],"velmoc":["czech"],"velryba":["czech"],"venkov":["czech"],"veranda":["czech"],"verze":["czech"],"veselka":["czech"],"veskrze":["czech"],"vesnice":["czech"],"vespodu":["czech"],"vesta":["czech"],"veterina":["czech"],"veverka":["czech"],"vibrace":["czech"],"vichr":["czech"],"videohra":["czech"],"vidina":["czech"],"vidle":["czech"],"vila":["czech"],"vinice":["czech"],"viset":["czech"],"vitalita":["czech"],"vize":["czech"],"vizitka":["czech"],"vjezd":["czech"],"vklad":["czech"],"vkus":["czech"],"vlajka":["czech"],"vlak":["czech"],"vlasec":["czech"],"vlevo":["czech"],"vlhkost":["czech"],"vliv":["czech"],"vlnovka":["czech"],"vloupat":["czech"],"vnucovat":["czech"],"vnuk":["czech"],"voda":["czech"],"vodivost":["czech"],"vodoznak":["czech"],"vodstvo":["czech"],"vojensky":["czech"],"vojna":["czech"],"vojsko":["czech"],"volant":["czech"],"volba":["czech"],"volit":["czech"],"volno":["czech"],"voskovka":["czech"],"vozidlo":["czech"],"vozovna":["czech"],"vpravo":["czech"],"vrabec":["czech"],"vracet":["czech"],"vrah":["czech"],"vrata":["czech"],"vrba":["czech"],"vrcholek":["czech"],"vrhat":["czech"],"vrstva":["czech"],"vrtule":["czech"],"vsadit":["czech"],"vstoupit":["czech"],"vstup":["czech"],"vtip":["czech"],"vybavit":["czech"],"vybrat":["czech"],"vychovat":["czech"],"vydat":["czech"],"vydra":["czech"],"vyfotit":["czech"],"vyhledat":["czech"],"vyhnout":["czech"],"vyhodit":["czech"],"vyhradit":["czech"],"vyhubit":["czech"],"vyjasnit":["czech"],"vyjet":["czech"],"vyjmout":["czech"],"vyklopit":["czech"],"vykonat":["czech"],"vylekat":["czech"],"vymazat":["czech"],"vymezit":["czech"],"vymizet":["czech"],"vymyslet":["czech"],"vynechat":["czech"],"vynikat":["czech"],"vynutit":["czech"],"vypadat":["czech"],"vyplatit":["czech"],"vypravit":["czech"],"vypustit":["czech"],"vyrazit":["czech"],"vyrovnat":["czech"],"vyrvat":["czech"],"vyslovit":["czech"],"vysoko":["czech"],"vystavit":["czech"],"vysunout":["czech"],"vysypat":["czech"],"vytasit":["czech"],"vytesat":["czech"],"vytratit":["czech"],"vyvinout":["czech"],"vyvolat":["czech"],"vyvrhel":["czech"],"vyzdobit":["czech"],"vyznat":["czech"],"vzadu":["czech"],"vzbudit":["czech"],"vzchopit":["czech"],"vzdor":["czech"],"vzduch":["czech"],"vzdychat":["czech"],"vzestup":["czech"],"vzhledem":["czech"],"vzkaz":["czech"],"vzlykat":["czech"],"vznik":["czech"],"vzorek":["czech"],"vzpoura":["czech"],"vztah":["czech"],"vztek":["czech"],"xylofon":["czech"],"zabrat":["czech"],"zabydlet":["czech"],"zachovat":["czech"],"zadarmo":["czech"],"zadusit":["czech"],"zafoukat":["czech"],"zahltit":["czech"],"zahodit":["czech"],"zahrada":["czech"],"zahynout":["czech"],"zajatec":["czech"],"zajet":["czech"],"zajistit":["czech"],"zaklepat":["czech"],"zakoupit":["czech"],"zalepit":["czech"],"zamezit":["czech"],"zamotat":["czech"],"zamyslet":["czech"],"zanechat":["czech"],"zanikat":["czech"],"zaplatit":["czech"],"zapojit":["czech"],"zapsat":["czech"],"zarazit":["czech"],"zastavit":["czech"],"zasunout":["czech"],"zatajit":["czech"],"zatemnit":["czech"],"zatknout":["czech"],"zaujmout":["czech"],"zavalit":["czech"],"zavelet":["czech"],"zavinit":["czech"],"zavolat":["czech"],"zavrtat":["czech"],"zazvonit":["czech"],"zbavit":["czech"],"zbrusu":["czech"],"zbudovat":["czech"],"zbytek":["czech"],"zdaleka":["czech"],"zdarma":["czech"],"zdatnost":["czech"],"zdivo":["czech"],"zdobit":["czech"],"zdroj":["czech"],"zdvih":["czech"],"zdymadlo":["czech"],"zelenina":["czech"],"zeman":["czech"],"zemina":["czech"],"zeptat":["czech"],"zezadu":["czech"],"zezdola":["czech"],"zhatit":["czech"],"zhltnout":["czech"],"zhluboka":["czech"],"zhotovit":["czech"],"zhruba":["czech"],"zima":["czech"],"zimnice":["czech"],"zjemnit":["czech"],"zklamat":["czech"],"zkoumat":["czech"],"zkratka":["czech"],"zkumavka":["czech"],"zlato":["czech"],"zlehka":["czech"],"zloba":["czech"],"zlom":["czech"],"zlost":["czech"],"zlozvyk":["czech"],"zmapovat":["czech"],"zmar":["czech"],"zmatek":["czech"],"zmije":["czech"],"zmizet":["czech"],"zmocnit":["czech"],"zmodrat":["czech"],"zmrzlina":["czech"],"zmutovat":["czech"],"znak":["czech"],"znalost":["czech"],"znamenat":["czech"],"znovu":["czech"],"zobrazit":["czech"],"zotavit":["czech"],"zoubek":["czech"],"zoufale":["czech"],"zplodit":["czech"],"zpomalit":["czech"],"zprava":["czech"],"zprostit":["czech"],"zprudka":["czech"],"zprvu":["czech"],"zrada":["czech"],"zranit":["czech"],"zrcadlo":["czech"],"zrnitost":["czech"],"zrno":["czech"],"zrovna":["czech"],"zrychlit":["czech"],"zrzavost":["czech"],"zticha":["czech"],"ztratit":["czech"],"zubovina":["czech"],"zubr":["czech"],"zvednout":["czech"],"zvenku":["czech"],"zvesela":["czech"],"zvon":["czech"],"zvrat":["czech"],"zvukovod":["czech"],"zvyk":["czech"],"abandon":["english","french"],"ability":["english"],"able":["english"],"about":["english"],"above":["english"],"absent":["english"],"absorb":["english"],"abstract":["english"],"absurd":["english"],"abuse":["english"],"access":["english"],"accident":["english"],"account":["english"],"accuse":["english"],"achieve":["english"],"acid":["english"],"acoustic":["english"],"acquire":["english"],"across":["english"],"act":["english"],"action":["english"],"actor":["english"],"actress":["english"],"actual":["english"],"adapt":["english"],"add":["english"],"addict":["english"],"address":["english"],"adjust":["english"],"admit":["english"],"adult":["english"],"advance":["english"],"advice":["english"],"aerobic":["english"],"affair":["english"],"afford":["english"],"afraid":["english"],"again":["english"],"age":["english"],"agent":["english"],"agree":["english"],"ahead":["english"],"aim":["english"],"air":["english"],"airport":["english"],"aisle":["english"],"alarm":["english"],"album":["english"],"alcohol":["english"],"alert":["english"],"alien":["english"],"all":["english"],"alley":["english"],"allow":["english"],"almost":["english"],"alone":["english"],"alpha":["english"],"already":["english"],"also":["english"],"alter":["english"],"always":["english"],"amateur":["english","french"],"amazing":["english"],"among":["english"],"amount":["english"],"amused":["english"],"analyst":["english"],"anchor":["english"],"ancient":["english"],"anger":["english"],"angle":["english","french"],"angry":["english"],"animal":["english","french"],"ankle":["english"],"announce":["english"],"annual":["english"],"another":["english"],"answer":["english"],"antenna":["english"],"antique":["english"],"anxiety":["english"],"any":["english"],"apart":["english"],"apology":["english"],"appear":["english"],"apple":["english"],"approve":["english"],"april":["english"],"arch":["english"],"arctic":["english"],"area":["english"],"arena":["english","turkish"],"argue":["english"],"arm":["english"],"armed":["english"],"armor":["english"],"army":["english"],"around":["english"],"arrange":["english"],"arrest":["english"],"arrive":["english"],"arrow":["english"],"art":["english"],"artefact":["english"],"artist":["english","turkish"],"artwork":["english"],"ask":["english"],"aspect":["english","french"],"assault":["english"],"asset":["english"],"assist":["english"],"assume":["english"],"asthma":["english"],"athlete":["english"],"atom":["english","turkish"],"attack":["english"],"attend":["english"],"attitude":["english"],"attract":["english"],"auction":["english"],"audit":["english"],"august":["english"],"aunt":["english"],"author":["english"],"auto":["english"],"autumn":["english"],"average":["english"],"avocado":["english"],"avoid":["english"],"awake":["english"],"aware":["english"],"away":["english"],"awesome":["english"],"awful":["english"],"awkward":["english"],"axis":["english"],"baby":["english"],"bachelor":["english"],"bacon":["english"],"badge":["english","french"],"bag":["english"],"balance":["english"],"balcony":["english"],"ball":["english"],"bamboo":["english"],"banana":["english"],"banner":["english"],"bar":["english"],"barely":["english"],"bargain":["english"],"barrel":["english"],"base":["english"],"basic":["english"],"basket":["english"],"battle":["english"],"beach":["english"],"bean":["english"],"beauty":["english"],"because":["english"],"become":["english"],"beef":["english"],"before":["english"],"begin":["english"],"behave":["english"],"behind":["english"],"believe":["english"],"below":["english"],"belt":["english"],"bench":["english"],"benefit":["english"],"best":["english"],"betray":["english"],"better":["english"],"between":["english"],"beyond":["english"],"bicycle":["english","french"],"bid":["english"],"bike":["english"],"bind":["english"],"biology":["english"],"bird":["english"],"birth":["english"],"bitter":["english"],"black":["english"],"blade":["english"],"blame":["english"],"blanket":["english"],"blast":["english"],"bleak":["english"],"bless":["english"],"blind":["english"],"blood":["english"],"blossom":["english"],"blouse":["english"],"blue":["english"],"blur":["english"],"blush":["english"],"board":["english"],"boat":["english"],"body":["english"],"boil":["english"],"bomb":["english"],"bone":["english"],"bonus":["english","french"],"book":["english"],"boost":["english"],"border":["english"],"boring":["english"],"borrow":["english"],"boss":["english"],"bottom":["english"],"bounce":["english"],"box":["english"],"boy":["english"],"bracket":["english"],"brain":["english"],"brand":["english"],"brass":["english"],"brave":["english","french"],"bread":["english"],"breeze":["english"],"brick":["english"],"bridge":["english"],"brief":["english"],"bright":["english"],"bring":["english"],"brisk":["english"],"broccoli":["english"],"broken":["english"],"bronze":["english"],"broom":["english"],"brother":["english"],"brown":["english"],"brush":["english"],"bubble":["english"],"buddy":["english"],"budget":["english"],"buffalo":["english"],"build":["english"],"bulb":["english"],"bulk":["english"],"bullet":["english"],"bundle":["english"],"bunker":["english"],"burden":["english"],"burger":["english"],"burst":["english"],"bus":["english"],"business":["english"],"busy":["english"],"butter":["english"],"buyer":["english"],"buzz":["english"],"cabbage":["english"],"cabin":["english"],"cable":["english"],"cactus":["english"],"cage":["english"],"cake":["english"],"call":["english"],"calm":["english"],"camera":["english"],"camp":["english"],"can":["english"],"canal":["english","french"],"cancel":["english"],"candy":["english"],"cannon":["english"],"canoe":["english"],"canvas":["english"],"canyon":["english"],"capable":["english","french"],"capital":["english"],"captain":["english"],"car":["english"],"carbon":["english"],"card":["english"],"cargo":["english"],"carpet":["english"],"carry":["english"],"cart":["english"],"case":["english"],"cash":["english"],"casino":["english"],"castle":["english"],"casual":["english"],"cat":["english"],"catalog":["english"],"catch":["english"],"category":["english"],"cattle":["english"],"caught":["english"],"cause":["english"],"caution":["english","french"],"cave":["english"],"ceiling":["english"],"celery":["english"],"cement":["english"],"census":["english"],"century":["english"],"cereal":["english"],"certain":["english"],"chair":["english"],"chalk":["english"],"champion":["english"],"change":["english"],"chaos":["english"],"chapter":["english"],"charge":["english"],"chase":["english"],"chat":["english"],"cheap":["english"],"check":["english"],"cheese":["english"],"chef":["english"],"cherry":["english"],"chest":["english"],"chicken":["english"],"chief":["english"],"child":["english"],"chimney":["english"],"choice":["english"],"choose":["english"],"chronic":["english"],"chuckle":["english"],"chunk":["english"],"churn":["english"],"cigar":["english"],"cinnamon":["english"],"circle":["english"],"citizen":["english"],"city":["english"],"civil":["english","french"],"claim":["english"],"clap":["english"],"clarify":["english"],"claw":["english"],"clay":["english"],"clean":["english"],"clerk":["english"],"clever":["english"],"click":["english"],"client":["english","french"],"cliff":["english"],"climb":["english"],"clinic":["english"],"clip":["english"],"clock":["english"],"clog":["english"],"close":["english"],"cloth":["english"],"cloud":["english"],"clown":["english"],"club":["english"],"clump":["english"],"cluster":["english"],"clutch":["english"],"coach":["english"],"coast":["english"],"coconut":["english"],"code":["english"],"coffee":["english"],"coil":["english"],"coin":["english"],"collect":["english"],"color":["english"],"column":["english"],"combine":["english"],"come":["english"],"comfort":["english"],"comic":["english"],"common":["english"],"company":["english"],"concert":["english","french"],"conduct":["english"],"confirm":["english"],"congress":["english"],"connect":["english"],"consider":["english"],"control":["english"],"convince":["english"],"cook":["english"],"cool":["english"],"copper":["english"],"copy":["english"],"coral":["english"],"core":["english"],"corn":["english"],"correct":["english","french"],"cost":["english"],"cotton":["english"],"couch":["english"],"country":["english"],"couple":["english"],"course":["english"],"cousin":["english"],"cover":["english"],"coyote":["english","french"],"crack":["english"],"cradle":["english"],"craft":["english"],"cram":["english"],"crane":["english"],"crash":["english"],"crater":["english"],"crawl":["english"],"crazy":["english"],"cream":["english"],"credit":["english"],"creek":["english"],"crew":["english"],"cricket":["english"],"crime":["english"],"crisp":["english"],"critic":["english"],"crop":["english"],"cross":["english"],"crouch":["english"],"crowd":["english"],"crucial":["english","french"],"cruel":["english","french"],"cruise":["english"],"crumble":["english"],"crunch":["english"],"crush":["english"],"cry":["english"],"crystal":["english"],"cube":["english"],"culture":["english"],"cup":["english"],"cupboard":["english"],"curious":["english"],"current":["english"],"curtain":["english"],"curve":["english"],"cushion":["english"],"custom":["english"],"cute":["english"],"cycle":["english","french"],"dad":["english"],"damage":["english"],"damp":["english"],"dance":["english"],"danger":["english","french"],"daring":["english"],"dash":["english"],"daughter":["english"],"dawn":["english"],"day":["english"],"deal":["english"],"debate":["english"],"debris":["english"],"decade":["english"],"december":["english"],"decide":["english"],"decline":["english"],"decorate":["english"],"decrease":["english"],"deer":["english"],"defense":["english"],"define":["english"],"defy":["english"],"degree":["english"],"delay":["english"],"deliver":["english"],"demand":["english"],"demise":["english"],"denial":["english"],"dentist":["english"],"deny":["english"],"depart":["english"],"depend":["english"],"deposit":["english"],"depth":["english"],"deputy":["english"],"derive":["english"],"describe":["english"],"desert":["english"],"design":["english"],"desk":["english"],"despair":["english"],"destroy":["english"],"detail":["english"],"detect":["english"],"develop":["english"],"device":["english"],"devote":["english"],"diagram":["english"],"dial":["english"],"diamond":["english"],"diary":["english"],"dice":["english"],"diesel":["english"],"diet":["english"],"differ":["english"],"digital":["english","french"],"dignity":["english"],"dilemma":["english"],"dinner":["english"],"dinosaur":["english"],"direct":["english"],"dirt":["english"],"disagree":["english"],"discover":["english"],"disease":["english"],"dish":["english"],"dismiss":["english"],"disorder":["english"],"display":["english"],"distance":["english","french"],"divert":["english"],"divide":["english"],"divorce":["english"],"dizzy":["english"],"doctor":["english"],"document":["english"],"dog":["english"],"doll":["english"],"dolphin":["english"],"domain":["english"],"donate":["english"],"donkey":["english"],"donor":["english"],"door":["english"],"dose":["english"],"double":["english","french"],"dove":["english"],"draft":["english"],"dragon":["english","french"],"drama":["english"],"drastic":["english"],"draw":["english"],"dream":["english"],"dress":["english"],"drift":["english"],"drill":["english"],"drink":["english"],"drip":["english"],"drive":["english"],"drop":["english"],"drum":["english"],"dry":["english"],"duck":["english"],"dumb":["english"],"dune":["english"],"during":["english"],"dust":["english"],"dutch":["english"],"duty":["english"],"dwarf":["english"],"dynamic":["english"],"eager":["english"],"eagle":["english"],"early":["english"],"earn":["english"],"earth":["english"],"easily":["english"],"east":["english"],"easy":["english"],"echo":["english"],"ecology":["english"],"economy":["english"],"edge":["english"],"edit":["english"],"educate":["english"],"effort":["english","french"],"egg":["english"],"eight":["english"],"either":["english"],"elbow":["english"],"elder":["english"],"electric":["english"],"elegant":["english"],"element":["english"],"elephant":["english"],"elevator":["english"],"elite":["english"],"else":["english"],"embark":["english"],"embody":["english"],"embrace":["english"],"emerge":["english"],"emotion":["english"],"employ":["english"],"empower":["english"],"empty":["english"],"enable":["english"],"enact":["english"],"end":["english"],"endless":["english"],"endorse":["english"],"enemy":["english"],"energy":["english"],"enforce":["english"],"engage":["english"],"engine":["english"],"enhance":["english"],"enjoy":["english"],"enlist":["english"],"enough":["english"],"enrich":["english"],"enroll":["english"],"ensure":["english"],"enter":["english"],"entire":["english"],"entry":["english"],"envelope":["english"],"episode":["english"],"equal":["english"],"equip":["english"],"era":["english"],"erase":["english"],"erode":["english"],"erosion":["english"],"error":["english"],"erupt":["english"],"escape":["english"],"essay":["english"],"essence":["english","french"],"estate":["english"],"eternal":["english"],"ethics":["english"],"evidence":["english"],"evil":["english"],"evoke":["english"],"evolve":["english"],"exact":["english","french"],"example":["english"],"excess":["english"],"exchange":["english"],"excite":["english"],"exclude":["english"],"excuse":["english","french"],"execute":["english"],"exercise":["english"],"exhaust":["english"],"exhibit":["english"],"exile":["english"],"exist":["english"],"exit":["english"],"exotic":["english"],"expand":["english"],"expect":["english"],"expire":["english"],"explain":["english"],"expose":["english"],"express":["english"],"extend":["english"],"extra":["english"],"eye":["english"],"eyebrow":["english"],"fabric":["english"],"face":["english"],"faculty":["english"],"fade":["english"],"faint":["english"],"faith":["english"],"fall":["english"],"false":["english"],"fame":["english"],"family":["english"],"famous":["english"],"fan":["english"],"fancy":["english"],"fantasy":["english"],"farm":["english"],"fashion":["english"],"fat":["english"],"fatal":["english","french"],"father":["english"],"fatigue":["english","french"],"fault":["english"],"favorite":["english"],"feature":["english"],"february":["english"],"federal":["english","turkish"],"fee":["english"],"feed":["english"],"feel":["english"],"female":["english"],"fence":["english"],"festival":["english","french","turkish"],"fetch":["english"],"fever":["english"],"few":["english"],"fiber":["english"],"fiction":["english"],"field":["english"],"figure":["english","french"],"file":["english"],"film":["english"],"filter":["english"],"final":["english"],"find":["english"],"fine":["english"],"finger":["english"],"finish":["english"],"fire":["english"],"firm":["english"],"first":["english"],"fiscal":["english"],"fish":["english"],"fit":["english"],"fitness":["english"],"fix":["english"],"flag":["english"],"flame":["english"],"flash":["english"],"flat":["english"],"flavor":["english"],"flee":["english"],"flight":["english"],"flip":["english"],"float":["english"],"flock":["english"],"floor":["english"],"flower":["english"],"fluid":["english"],"flush":["english"],"fly":["english"],"foam":["english"],"focus":["english"],"fog":["english"],"foil":["english"],"fold":["english"],"follow":["english"],"food":["english"],"foot":["english"],"force":["english"],"forest":["english"],"forget":["english"],"fork":["english"],"fortune":["english","french"],"forum":["english"],"forward":["english"],"fossil":["english"],"foster":["english"],"found":["english"],"fox":["english"],"fragile":["english","french"],"frame":["english"],"frequent":["english"],"fresh":["english"],"friend":["english"],"fringe":["english"],"frog":["english"],"front":["english"],"frost":["english"],"frown":["english"],"frozen":["english"],"fruit":["english","french"],"fuel":["english"],"fun":["english"],"funny":["english"],"furnace":["english"],"fury":["english"],"future":["english"],"gadget":["english"],"gain":["english"],"galaxy":["english"],"gallery":["english"],"game":["english"],"gap":["english"],"garage":["english"],"garbage":["english"],"garden":["english"],"garlic":["english"],"garment":["english"],"gas":["english"],"gasp":["english"],"gate":["english"],"gather":["english"],"gauge":["english"],"gaze":["english"],"general":["english"],"genius":["english"],"genre":["english"],"gentle":["english"],"genuine":["english"],"gesture":["english"],"ghost":["english"],"giant":["english"],"gift":["english"],"giggle":["english"],"ginger":["english"],"giraffe":["english"],"girl":["english"],"give":["english"],"glad":["english"],"glance":["english"],"glare":["english"],"glass":["english"],"glide":["english"],"glimpse":["english"],"globe":["english","french"],"gloom":["english"],"glory":["english"],"glove":["english"],"glow":["english"],"glue":["english"],"goat":["english"],"goddess":["english"],"gold":["english"],"good":["english"],"goose":["english"],"gorilla":["english"],"gospel":["english"],"gossip":["english"],"govern":["english"],"gown":["english"],"grab":["english"],"grace":["english"],"grain":["english"],"grant":["english"],"grape":["english"],"grass":["english"],"gravity":["english"],"great":["english"],"green":["english"],"grid":["english"],"grief":["english"],"grit":["english"],"grocery":["english"],"group":["english"],"grow":["english"],"grunt":["english"],"guard":["english"],"guess":["english"],"guide":["english","french"],"guilt":["english"],"guitar":["english"],"gun":["english"],"gym":["english"],"habit":["english"],"hair":["english"],"half":["english"],"hammer":["english"],"hamster":["english"],"hand":["english"],"happy":["english"],"harbor":["english"],"hard":["english"],"harsh":["english"],"harvest":["english"],"hat":["english"],"have":["english"],"hawk":["english"],"hazard":["english"],"head":["english"],"health":["english"],"heart":["english"],"heavy":["english"],"hedgehog":["english"],"height":["english"],"hello":["english"],"helmet":["english"],"help":["english"],"hen":["english"],"hero":["english"],"hidden":["english"],"high":["english"],"hill":["english"],"hint":["english"],"hip":["english"],"hire":["english"],"history":["english"],"hobby":["english"],"hockey":["english"],"hold":["english"],"hole":["english"],"holiday":["english"],"hollow":["english"],"home":["english"],"honey":["english"],"hood":["english"],"hope":["english"],"horn":["english"],"horror":["english"],"horse":["english"],"hospital":["english"],"host":["english"],"hotel":["english"],"hour":["english"],"hover":["english"],"hub":["english"],"huge":["english"],"human":["english"],"humble":["english","french"],"humor":["english"],"hundred":["english"],"hungry":["english"],"hunt":["english"],"hurdle":["english"],"hurry":["english"],"hurt":["english"],"husband":["english"],"hybrid":["english"],"ice":["english"],"icon":["english"],"idea":["english"],"identify":["english"],"idle":["english"],"ignore":["english"],"ill":["english"],"illegal":["english"],"illness":["english"],"image":["english","french"],"imitate":["english"],"immense":["english","french"],"immune":["english"],"impact":["english","french"],"impose":["english"],"improve":["english"],"impulse":["english"],"inch":["english"],"include":["english"],"income":["english"],"increase":["english"],"index":["english"],"indicate":["english"],"indoor":["english"],"industry":["english"],"infant":["english"],"inflict":["english"],"inform":["english"],"inhale":["english"],"inherit":["english"],"initial":["english"],"inject":["english"],"injury":["english"],"inmate":["english"],"inner":["english"],"innocent":["english","french"],"input":["english"],"inquiry":["english"],"insane":["english"],"insect":["english"],"inside":["english"],"inspire":["english"],"install":["english"],"intact":["english","french"],"interest":["english"],"into":["english"],"invest":["english"],"invite":["english"],"involve":["english"],"iron":["english"],"island":["english"],"isolate":["english"],"issue":["english"],"item":["english"],"ivory":["english"],"jacket":["english"],"jaguar":["english","french"],"jar":["english"],"jazz":["english"],"jealous":["english"],"jeans":["english"],"jelly":["english"],"jewel":["english"],"job":["english"],"join":["english"],"joke":["english"],"journey":["english"],"joy":["english"],"judge":["english"],"juice":["english"],"jump":["english"],"jungle":["english"],"junior":["english","french"],"junk":["english"],"just":["english"],"kangaroo":["english"],"keen":["english"],"keep":["english"],"ketchup":["english"],"key":["english"],"kick":["english"],"kid":["english"],"kidney":["english"],"kind":["english"],"kingdom":["english"],"kiss":["english"],"kit":["english"],"kitchen":["english"],"kite":["english"],"kitten":["english"],"kiwi":["english"],"knee":["english"],"knife":["english"],"knock":["english"],"know":["english"],"lab":["english"],"label":["english","french"],"labor":["english"],"ladder":["english"],"lady":["english"],"lake":["english"],"lamp":["english"],"language":["english"],"laptop":["english"],"large":["english"],"later":["english"],"latin":["english"],"laugh":["english"],"laundry":["english"],"lava":["english"],"law":["english"],"lawn":["english"],"lawsuit":["english"],"layer":["english"],"lazy":["english"],"leader":["english"],"leaf":["english"],"learn":["english"],"leave":["english"],"lecture":["english","french"],"left":["english"],"leg":["english"],"legal":["english"],"legend":["english"],"leisure":["english"],"lemon":["english"],"lend":["english"],"length":["english"],"lens":["english"],"leopard":["english"],"lesson":["english"],"letter":["english"],"level":["english"],"liar":["english"],"liberty":["english"],"library":["english"],"license":["english"],"life":["english"],"lift":["english"],"light":["english"],"like":["english"],"limb":["english"],"limit":["english"],"link":["english"],"lion":["english"],"liquid":["english"],"list":["english"],"little":["english"],"live":["english"],"lizard":["english"],"load":["english"],"loan":["english"],"lobster":["english"],"local":["english"],"lock":["english"],"logic":["english"],"lonely":["english"],"long":["english"],"loop":["english"],"lottery":["english"],"loud":["english"],"lounge":["english"],"love":["english"],"loyal":["english","french"],"lucky":["english"],"luggage":["english"],"lumber":["english"],"lunar":["english"],"lunch":["english"],"luxury":["english"],"lyrics":["english"],"machine":["english","french"],"mad":["english"],"magic":["english"],"magnet":["english"],"maid":["english"],"mail":["english"],"main":["english"],"major":["english"],"make":["english"],"mammal":["english"],"man":["english"],"manage":["english"],"mandate":["english"],"mango":["english"],"mansion":["english"],"manual":["english"],"maple":["english"],"marble":["english"],"march":["english"],"margin":["english"],"marine":["english"],"market":["english","turkish"],"marriage":["english"],"mask":["english"],"mass":["english"],"master":["english"],"match":["english"],"material":["english"],"math":["english"],"matrix":["english"],"matter":["english"],"maximum":["english"],"maze":["english"],"meadow":["english"],"mean":["english"],"measure":["english"],"meat":["english"],"mechanic":["english"],"medal":["english"],"media":["english"],"melody":["english"],"melt":["english"],"member":["english"],"memory":["english"],"mention":["english"],"menu":["english"],"mercy":["english"],"merge":["english"],"merit":["english"],"merry":["english"],"mesh":["english"],"message":["english"],"metal":["english"],"method":["english"],"middle":["english"],"midnight":["english"],"milk":["english"],"million":["english","french"],"mimic":["english"],"mind":["english"],"minimum":["english"],"minor":["english"],"minute":["english","french"],"miracle":["english","french"],"mirror":["english"],"misery":["english"],"miss":["english"],"mistake":["english"],"mix":["english"],"mixed":["english"],"mixture":["english"],"mobile":["english","french"],"model":["english","turkish"],"modify":["english"],"mom":["english"],"moment":["english"],"monitor":["english"],"monkey":["english"],"monster":["english"],"month":["english"],"moon":["english"],"moral":["english"],"more":["english"],"morning":["english"],"mosquito":["english"],"mother":["english"],"motion":["english"],"motor":["english","turkish"],"mountain":["english"],"mouse":["english"],"move":["english"],"movie":["english"],"much":["english"],"muffin":["english"],"mule":["english"],"multiply":["english"],"muscle":["english","french"],"museum":["english"],"mushroom":["english"],"music":["english"],"must":["english"],"mutual":["english"],"myself":["english"],"mystery":["english"],"myth":["english"],"naive":["english"],"name":["english"],"napkin":["english"],"narrow":["english"],"nasty":["english"],"nation":["english","french"],"nature":["english","french"],"near":["english"],"neck":["english"],"need":["english"],"negative":["english"],"neglect":["english"],"neither":["english"],"nephew":["english"],"nerve":["english"],"nest":["english"],"net":["english"],"network":["english"],"neutral":["english"],"never":["english"],"news":["english"],"next":["english"],"nice":["english"],"night":["english"],"noble":["english","french"],"noise":["english"],"nominee":["english"],"noodle":["english"],"normal":["english","turkish"],"north":["english"],"nose":["english"],"notable":["english","french"],"note":["english"],"nothing":["english"],"notice":["english"],"novel":["english"],"now":["english"],"nuclear":["english"],"number":["english"],"nurse":["english"],"nut":["english"],"oak":["english"],"obey":["english"],"object":["english"],"oblige":["english"],"obscure":["english"],"observe":["english"],"obtain":["english"],"obvious":["english"],"occur":["english"],"ocean":["english"],"october":["english"],"odor":["english"],"off":["english"],"offer":["english"],"office":["english"],"often":["english"],"oil":["english"],"okay":["english"],"old":["english"],"olive":["english"],"olympic":["english"],"omit":["english"],"once":["english"],"one":["english"],"onion":["english"],"online":["english"],"only":["english"],"open":["english"],"opera":["english","turkish"],"opinion":["english","french"],"oppose":["english"],"option":["english"],"orange":["english","french"],"orbit":["english"],"orchard":["english"],"order":["english"],"ordinary":["english"],"organ":["english"],"orient":["english"],"original":["english"],"orphan":["english"],"ostrich":["english"],"other":["english"],"outdoor":["english"],"outer":["english"],"output":["english"],"outside":["english"],"oval":["english"],"oven":["english"],"over":["english"],"own":["english"],"owner":["english"],"oxygen":["english"],"oyster":["english"],"ozone":["english","french"],"pact":["english"],"paddle":["english"],"page":["english"],"pair":["english"],"palace":["english","french"],"palm":["english"],"panda":["english","french","turkish"],"panel":["english","turkish"],"panic":["english"],"panther":["english"],"paper":["english"],"parade":["english"],"parent":["english"],"park":["english"],"parrot":["english"],"party":["english"],"pass":["english"],"patch":["english"],"path":["english"],"patient":["english"],"patrol":["english"],"pattern":["english"],"pause":["english"],"pave":["english"],"payment":["english"],"peace":["english"],"peanut":["english"],"pear":["english"],"peasant":["english"],"pelican":["english"],"pen":["english"],"penalty":["english"],"pencil":["english"],"people":["english"],"pepper":["english"],"perfect":["english"],"permit":["english"],"person":["english"],"pet":["english"],"phone":["english"],"photo":["english"],"phrase":["english","french"],"physical":["english"],"piano":["english","french"],"picnic":["english"],"picture":["english"],"piece":["english"],"pig":["english"],"pigeon":["english"],"pill":["english"],"pilot":["english","turkish"],"pink":["english"],"pioneer":["english"],"pipe":["english"],"pistol":["english"],"pitch":["english"],"pizza":["english","french"],"place":["english"],"planet":["english"],"plastic":["english"],"plate":["english"],"play":["english"],"please":["english"],"pledge":["english"],"pluck":["english"],"plug":["english"],"plunge":["english"],"poem":["english"],"poet":["english"],"point":["english"],"polar":["english"],"pole":["english"],"police":["english"],"pond":["english"],"pony":["english"],"pool":["english"],"popular":["english"],"portion":["english"],"position":["english","french"],"possible":["english"],"post":["english"],"potato":["english"],"pottery":["english"],"poverty":["english"],"powder":["english"],"power":["english"],"practice":["english"],"praise":["english"],"predict":["english"],"prefer":["english"],"prepare":["english"],"present":["english"],"pretty":["english"],"prevent":["english"],"price":["english"],"pride":["english"],"primary":["english"],"print":["english"],"priority":["english"],"prison":["english","french"],"private":["english"],"prize":["english"],"problem":["english","turkish"],"process":["english"],"produce":["english"],"profit":["english"],"program":["english","turkish"],"project":["english"],"promote":["english"],"proof":["english"],"property":["english"],"prosper":["english"],"protect":["english"],"proud":["english"],"provide":["english"],"public":["english","french"],"pudding":["english"],"pull":["english"],"pulp":["english"],"pulse":["english"],"pumpkin":["english"],"punch":["english"],"pupil":["english"],"puppy":["english"],"purchase":["english"],"purity":["english"],"purpose":["english"],"purse":["english"],"push":["english"],"put":["english"],"puzzle":["english","french"],"pyramid":["english"],"quality":["english"],"quantum":["english"],"quarter":["english"],"question":["english","french"],"quick":["english"],"quit":["english"],"quiz":["english"],"quote":["english"],"rabbit":["english"],"raccoon":["english"],"race":["english"],"rack":["english"],"radar":["english","turkish"],"radio":["english"],"rail":["english"],"rain":["english"],"raise":["english"],"rally":["english"],"ramp":["english"],"ranch":["english"],"random":["english"],"range":["english"],"rapid":["english"],"rare":["english"],"rate":["english"],"rather":["english"],"raven":["english"],"raw":["english"],"razor":["english"],"ready":["english"],"real":["english"],"reason":["english"],"rebel":["english"],"rebuild":["english"],"recall":["english"],"receive":["english"],"recipe":["english"],"record":["english"],"recycle":["english"],"reduce":["english"],"reflect":["english"],"reform":["english","turkish"],"refuse":["english"],"region":["english"],"regret":["english"],"regular":["english"],"reject":["english"],"relax":["english"],"release":["english"],"relief":["english","french"],"rely":["english"],"remain":["english"],"remember":["english"],"remind":["english"],"remove":["english"],"render":["english"],"renew":["english"],"rent":["english"],"reopen":["english"],"repair":["english"],"repeat":["english"],"replace":["english"],"report":["english"],"require":["english"],"rescue":["english"],"resemble":["english"],"resist":["english"],"resource":["english"],"response":["english"],"result":["english"],"retire":["english"],"retreat":["english"],"return":["english"],"reunion":["english"],"reveal":["english"],"review":["english"],"reward":["english"],"rhythm":["english"],"rib":["english"],"ribbon":["english"],"rice":["english"],"rich":["english"],"ride":["english"],"ridge":["english"],"rifle":["english"],"right":["english"],"rigid":["english"],"ring":["english"],"riot":["english"],"ripple":["english"],"risk":["english"],"ritual":["english"],"rival":["english","french"],"river":["english"],"road":["english"],"roast":["english"],"robot":["english","turkish"],"robust":["english"],"rocket":["english"],"romance":["english","french"],"roof":["english"],"rookie":["english"],"room":["english"],"rose":["english"],"rotate":["english"],"rough":["english"],"round":["english"],"route":["english"],"royal":["english"],"rubber":["english"],"rude":["english"],"rug":["english"],"rule":["english"],"run":["english"],"runway":["english"],"rural":["english"],"sad":["english"],"saddle":["english"],"sadness":["english"],"safe":["english"],"sail":["english"],"salad":["english"],"salmon":["english"],"salon":["english","french","turkish"],"salt":["english"],"salute":["english"],"same":["english"],"sample":["english"],"sand":["english"],"satisfy":["english"],"satoshi":["english"],"sauce":["english"],"sausage":["english"],"save":["english"],"say":["english"],"scale":["english"],"scan":["english"],"scare":["english"],"scatter":["english"],"scene":["english"],"scheme":["english"],"school":["english"],"science":["english","french"],"scissors":["english"],"scorpion":["english"],"scout":["english"],"scrap":["english"],"screen":["english"],"script":["english"],"scrub":["english"],"sea":["english"],"search":["english"],"season":["english"],"seat":["english"],"second":["english"],"secret":["english"],"section":["english"],"security":["english"],"seed":["english"],"seek":["english"],"segment":["english"],"select":["english"],"sell":["english"],"seminar":["english"],"senior":["english"],"sense":["english"],"sentence":["english","french"],"series":["english"],"service":["english","french"],"session":["english"],"settle":["english"],"setup":["english"],"seven":["english"],"shadow":["english"],"shaft":["english"],"shallow":["english"],"share":["english"],"shed":["english"],"shell":["english"],"sheriff":["english"],"shield":["english"],"shift":["english"],"shine":["english"],"ship":["english"],"shiver":["english"],"shock":["english"],"shoe":["english"],"shoot":["english"],"shop":["english"],"short":["english"],"shoulder":["english"],"shove":["english"],"shrimp":["english"],"shrug":["english"],"shuffle":["english"],"shy":["english"],"sibling":["english"],"sick":["english"],"side":["english"],"siege":["english"],"sight":["english"],"sign":["english"],"silent":["english"],"silk":["english"],"silly":["english"],"silver":["english"],"similar":["english"],"simple":["english","french"],"since":["english"],"sing":["english"],"siren":["english"],"sister":["english"],"situate":["english"],"six":["english"],"size":["english"],"skate":["english"],"sketch":["english"],"ski":["english"],"skill":["english"],"skin":["english"],"skirt":["english"],"skull":["english"],"slab":["english"],"slam":["english"],"sleep":["english"],"slender":["english"],"slice":["english"],"slide":["english"],"slight":["english"],"slim":["english"],"slogan":["english","turkish"],"slot":["english"],"slow":["english"],"slush":["english"],"small":["english"],"smart":["english"],"smile":["english"],"smoke":["english"],"smooth":["english"],"snack":["english"],"snake":["english"],"snap":["english"],"sniff":["english"],"snow":["english"],"soap":["english"],"soccer":["english"],"social":["english","french"],"sock":["english"],"soda":["english"],"soft":["english"],"solar":["english"],"soldier":["english"],"solid":["english"],"solution":["english"],"solve":["english"],"someone":["english"],"song":["english"],"soon":["english"],"sorry":["english"],"sort":["english"],"soul":["english"],"sound":["english"],"soup":["english"],"source":["english","french"],"south":["english"],"space":["english"],"spare":["english"],"spatial":["english","french"],"spawn":["english"],"speak":["english"],"special":["english"],"speed":["english"],"spell":["english"],"spend":["english"],"sphere":["english"],"spice":["english"],"spider":["english"],"spike":["english"],"spin":["english"],"spirit":["english"],"split":["english"],"spoil":["english"],"sponsor":["english","turkish"],"spoon":["english"],"sport":["english"],"spot":["english"],"spray":["english"],"spread":["english"],"spring":["english"],"spy":["english"],"square":["english"],"squeeze":["english"],"squirrel":["english"],"stable":["english","french"],"stadium":["english"],"staff":["english"],"stage":["english"],"stairs":["english"],"stamp":["english"],"stand":["english"],"start":["english"],"state":["english"],"stay":["english"],"steak":["english"],"steel":["english"],"stem":["english"],"step":["english"],"stereo":["english"],"stick":["english"],"still":["english"],"sting":["english"],"stock":["english"],"stomach":["english"],"stone":["english"],"stool":["english"],"story":["english"],"stove":["english"],"strategy":["english"],"street":["english"],"strike":["english"],"strong":["english"],"struggle":["english"],"student":["english"],"stuff":["english"],"stumble":["english"],"style":["english"],"subject":["english"],"submit":["english"],"subway":["english"],"success":["english"],"such":["english"],"sudden":["english"],"suffer":["english"],"sugar":["english"],"suggest":["english"],"suit":["english"],"summer":["english"],"sun":["english"],"sunny":["english"],"sunset":["english"],"super":["english"],"supply":["english"],"supreme":["english"],"sure":["english"],"surface":["english","french"],"surge":["english"],"surprise":["english","french"],"surround":["english"],"survey":["english"],"suspect":["english","french"],"sustain":["english"],"swallow":["english"],"swamp":["english"],"swap":["english"],"swarm":["english"],"swear":["english"],"sweet":["english"],"swift":["english"],"swim":["english"],"swing":["english"],"switch":["english"],"sword":["english"],"symbol":["english"],"symptom":["english"],"syrup":["english"],"system":["english"],"table":["english"],"tackle":["english"],"tag":["english"],"tail":["english"],"talent":["english","french"],"talk":["english"],"tank":["english"],"tape":["english"],"target":["english"],"task":["english"],"taste":["english"],"tattoo":["english"],"taxi":["english"],"teach":["english"],"team":["english"],"tell":["english"],"ten":["english"],"tenant":["english"],"tennis":["english"],"tent":["english"],"term":["english"],"test":["english"],"text":["english"],"thank":["english"],"that":["english"],"theme":["english"],"then":["english"],"theory":["english"],"there":["english"],"they":["english"],"thing":["english"],"this":["english"],"thought":["english"],"three":["english"],"thrive":["english"],"throw":["english"],"thumb":["english"],"thunder":["english"],"ticket":["english"],"tide":["english"],"tiger":["english"],"tilt":["english"],"timber":["english"],"time":["english"],"tiny":["english"],"tip":["english"],"tired":["english"],"tissue":["english"],"title":["english"],"toast":["english"],"tobacco":["english"],"today":["english"],"toddler":["english"],"toe":["english"],"together":["english"],"toilet":["english"],"token":["english"],"tomato":["english"],"tomorrow":["english"],"tone":["english"],"tongue":["english"],"tonight":["english"],"tool":["english"],"tooth":["english"],"top":["english"],"topic":["english"],"topple":["english"],"torch":["english"],"tornado":["english"],"tortoise":["english"],"toss":["english"],"total":["english"],"tourist":["english"],"toward":["english"],"tower":["english"],"town":["english"],"toy":["english"],"track":["english"],"trade":["english"],"traffic":["english"],"tragic":["english"],"train":["english","french"],"transfer":["english","turkish"],"trap":["english"],"trash":["english"],"travel":["english"],"tray":["english"],"treat":["english"],"tree":["english"],"trend":["english"],"trial":["english"],"tribe":["english"],"trick":["english"],"trigger":["english"],"trim":["english"],"trip":["english"],"trophy":["english"],"trouble":["english"],"truck":["english"],"true":["english"],"truly":["english"],"trumpet":["english"],"trust":["english"],"truth":["english"],"try":["english"],"tube":["english"],"tuition":["english"],"tumble":["english"],"tuna":["english"],"tunnel":["english","french"],"turkey":["english"],"turn":["english"],"turtle":["english"],"twelve":["english"],"twenty":["english"],"twice":["english"],"twin":["english"],"twist":["english"],"two":["english"],"type":["english"],"typical":["english"],"ugly":["english"],"umbrella":["english"],"unable":["english"],"unaware":["english"],"uncle":["english"],"uncover":["english"],"under":["english"],"undo":["english"],"unfair":["english"],"unfold":["english"],"unhappy":["english"],"uniform":["english"],"unique":["english","french"],"unit":["english"],"universe":["english"],"unknown":["english"],"unlock":["english"],"until":["english"],"unusual":["english"],"unveil":["english"],"update":["english"],"upgrade":["english"],"uphold":["english"],"upon":["english"],"upper":["english"],"upset":["english"],"urban":["english"],"urge":["english"],"usage":["english","french"],"use":["english"],"used":["english"],"useful":["english"],"useless":["english"],"usual":["english"],"utility":["english"],"vacant":["english"],"vacuum":["english"],"vague":["english","french"],"valid":["english"],"valley":["english"],"valve":["english","french"],"van":["english"],"vanish":["english"],"vapor":["english"],"various":["english"],"vast":["english"],"vault":["english"],"vehicle":["english"],"velvet":["english"],"vendor":["english"],"venture":["english"],"venue":["english"],"verb":["english"],"verify":["english"],"version":["english"],"very":["english"],"vessel":["english"],"veteran":["english"],"viable":["english"],"vibrant":["english"],"vicious":["english"],"victory":["english"],"video":["english"],"view":["english"],"village":["english","french"],"vintage":["english"],"violin":["english"],"virtual":["english"],"virus":["english","french"],"visa":["english"],"visit":["english"],"visual":["english"],"vital":["english","french"],"vivid":["english"],"vocal":["english"],"voice":["english"],"void":["english"],"volcano":["english"],"volume":["english","french"],"vote":["english"],"voyage":["english","french"],"wage":["english"],"wagon":["english","french"],"wait":["english"],"walk":["english"],"wall":["english"],"walnut":["english"],"want":["english"],"warfare":["english"],"warm":["english"],"warrior":["english"],"wash":["english"],"wasp":["english"],"waste":["english"],"water":["english"],"wave":["english"],"way":["english"],"wealth":["english"],"weapon":["english"],"wear":["english"],"weasel":["english"],"weather":["english"],"web":["english"],"wedding":["english"],"weekend":["english"],"weird":["english"],"welcome":["english"],"west":["english"],"wet":["english"],"whale":["english"],"what":["english"],"wheat":["english"],"wheel":["english"],"when":["english"],"where":["english"],"whip":["english"],"whisper":["english"],"wide":["english"],"width":["english"],"wife":["english"],"wild":["english"],"will":["english"],"win":["english"],"window":["english"],"wine":["english"],"wing":["english"],"wink":["english"],"winner":["english"],"winter":["english"],"wire":["english"],"wisdom":["english"],"wise":["english"],"wish":["english"],"witness":["english"],"wolf":["english"],"woman":["english"],"wonder":["english"],"wood":["english"],"wool":["english"],"word":["english"],"work":["english"],"world":["english"],"worry":["english"],"worth":["english"],"wrap":["english"],"wreck":["english"],"wrestle":["english"],"wrist":["english"],"write":["english"],"wrong":["english"],"yard":["english"],"year":["english"],"yellow":["english"],"you":["english"],"young":["english"],"youth":["english"],"zebra":["english"],"zero":["english"],"zone":["english"],"zoo":["english"],"abaisser":["french"],"abdiquer":["french"],"abeille":["french"],"abolir":["french"],"aborder":["french"],"aboutir":["french"],"aboyer":["french"],"abrasif":["french"],"abreuver":["french"],"abriter":["french"],"abroger":["french"],"abrupt":["french"],"absence":["french"],"absolu":["french"],"absurde":["french"],"abusif":["french"],"abyssal":["french"],"académie":["french"],"acajou":["french"],"acarien":["french"],"accabler":["french"],"accepter":["french"],"acclamer":["french"],"accolade":["french"],"accroche":["french"],"accuser":["french"],"acerbe":["french"],"achat":["french"],"acheter":["french"],"aciduler":["french"],"acier":["french"],"acompte":["french"],"acquérir":["french"],"acronyme":["french"],"acteur":["french"],"actif":["french"],"actuel":["french"],"adepte":["french"],"adéquat":["french"],"adhésif":["french"],"adjectif":["french"],"adjuger":["french"],"admettre":["french"],"admirer":["french"],"adopter":["french"],"adorer":["french"],"adoucir":["french"],"adresse":["french"],"adroit":["french"],"adulte":["french"],"adverbe":["french"],"aérer":["french"],"aéronef":["french"],"affaire":["french"],"affecter":["french"],"affiche":["french"],"affreux":["french"],"affubler":["french"],"agacer":["french"],"agencer":["french"],"agile":["french"],"agiter":["french"],"agrafer":["french"],"agréable":["french"],"agrume":["french"],"aider":["french"],"aiguille":["french"],"ailier":["french"],"aimable":["french"],"aisance":["french"],"ajouter":["french"],"ajuster":["french"],"alarmer":["french"],"alchimie":["french"],"alerte":["french"],"algèbre":["french"],"algue":["french"],"aliéner":["french"],"aliment":["french"],"alléger":["french"],"alliage":["french"],"allouer":["french"],"allumer":["french"],"alourdir":["french"],"alpaga":["french"],"altesse":["french"],"alvéole":["french"],"ambigu":["french"],"ambre":["french"],"aménager":["french"],"amertume":["french"],"amidon":["french"],"amiral":["french"],"amorcer":["french"],"amour":["french"],"amovible":["french"],"amphibie":["french"],"ampleur":["french"],"amusant":["french"],"analyse":["french"],"anaphore":["french"],"anarchie":["french"],"anatomie":["french"],"ancien":["french"],"anéantir":["french"],"angoisse":["french"],"anguleux":["french"],"annexer":["french"],"annonce":["french"],"annuel":["french"],"anodin":["french"],"anomalie":["french"],"anonyme":["french"],"anormal":["french"],"antenne":["french"],"antidote":["french"],"anxieux":["french"],"apaiser":["french"],"apéritif":["french"],"aplanir":["french"],"apologie":["french"],"appareil":["french"],"appeler":["french"],"apporter":["french"],"appuyer":["french"],"aquarium":["french"],"aqueduc":["french"],"arbitre":["french"],"arbuste":["french"],"ardeur":["french"],"ardoise":["french"],"argent":["french"],"arlequin":["french"],"armature":["french"],"armement":["french"],"armoire":["french"],"armure":["french"],"arpenter":["french"],"arracher":["french"],"arriver":["french"],"arroser":["french"],"arsenic":["french"],"artériel":["french"],"article":["french"],"asphalte":["french"],"aspirer":["french"],"assaut":["french"],"asservir":["french"],"assiette":["french"],"associer":["french"],"assurer":["french"],"asticot":["french"],"astre":["french"],"astuce":["french"],"atelier":["french"],"atome":["french"],"atrium":["french"],"atroce":["french"],"attaque":["french"],"attentif":["french"],"attirer":["french"],"attraper":["french"],"aubaine":["french"],"auberge":["french"],"audace":["french"],"audible":["french"],"augurer":["french"],"aurore":["french"],"automne":["french"],"autruche":["french"],"avaler":["french"],"avancer":["french"],"avarice":["french"],"avenir":["french"],"averse":["french"],"aveugle":["french"],"aviateur":["french"],"avide":["french"],"avion":["french"],"aviser":["french"],"avoine":["french"],"avouer":["french"],"avril":["french"],"axial":["french"],"axiome":["french"],"bafouer":["french"],"bagage":["french"],"baguette":["french"],"baignade":["french"],"balancer":["french"],"balcon":["french"],"baleine":["french"],"balisage":["french"],"bambin":["french"],"bancaire":["french"],"bandage":["french"],"banlieue":["french"],"bannière":["french"],"banquier":["french"],"barbier":["french"],"baril":["french"],"baron":["french"],"barque":["french"],"barrage":["french"],"bassin":["french"],"bastion":["french"],"bataille":["french"],"bateau":["french"],"batterie":["french"],"baudrier":["french"],"bavarder":["french"],"belette":["french"],"bélier":["french"],"belote":["french"],"bénéfice":["french"],"berceau":["french"],"berger":["french"],"berline":["french"],"bermuda":["french","turkish"],"besace":["french"],"besogne":["french"],"bétail":["french"],"beurre":["french"],"biberon":["french"],"bidule":["french"],"bijou":["french"],"bilan":["french"],"bilingue":["french"],"billard":["french"],"binaire":["french"],"biologie":["french"],"biopsie":["french"],"biotype":["french"],"biscuit":["french"],"bison":["french"],"bistouri":["french"],"bitume":["french"],"bizarre":["french"],"blafard":["french"],"blague":["french"],"blanchir":["french"],"blessant":["french"],"blinder":["french"],"blond":["french"],"bloquer":["french"],"blouson":["french"],"bobard":["french"],"bobine":["french"],"boire":["french"],"boiser":["french"],"bolide":["french"],"bonbon":["french"],"bondir":["french"],"bonheur":["french"],"bonifier":["french"],"bordure":["french"],"borne":["french"],"botte":["french"],"boucle":["french"],"boueux":["french"],"bougie":["french"],"boulon":["french"],"bouquin":["french"],"bourse":["french"],"boussole":["french"],"boutique":["french"],"boxeur":["french"],"branche":["french"],"brasier":["french"],"brebis":["french"],"brèche":["french"],"breuvage":["french"],"bricoler":["french"],"brigade":["french"],"brillant":["french"],"brioche":["french"],"brique":["french"],"brochure":["french"],"broder":["french"],"bronzer":["french"],"brousse":["french"],"broyeur":["french"],"brume":["french"],"brusque":["french"],"brutal":["french"],"bruyant":["french"],"buffle":["french"],"buisson":["french"],"bulletin":["french"],"bureau":["french"],"burin":["french"],"bustier":["french"],"butiner":["french"],"butoir":["french"],"buvable":["french"],"buvette":["french"],"cabanon":["french"],"cabine":["french"],"cachette":["french"],"cadeau":["french"],"cadre":["french"],"caféine":["french"],"caillou":["french"],"caisson":["french"],"calculer":["french"],"calepin":["french"],"calibre":["french"],"calmer":["french"],"calomnie":["french"],"calvaire":["french"],"camarade":["french"],"caméra":["french"],"camion":["french"],"campagne":["french"],"caneton":["french"],"canon":["french"],"cantine":["french"],"canular":["french"],"caporal":["french"],"caprice":["french"],"capsule":["french"],"capter":["french"],"capuche":["french"],"carabine":["french"],"carbone":["french"],"caresser":["french"],"caribou":["french"],"carnage":["french"],"carotte":["french"],"carreau":["french"],"carton":["french"],"cascade":["french"],"casier":["french"],"casque":["french"],"cassure":["french"],"causer":["french"],"cavalier":["french"],"caverne":["french"],"caviar":["french"],"cédille":["french"],"ceinture":["french"],"céleste":["french"],"cellule":["french"],"cendrier":["french"],"censurer":["french"],"central":["french"],"cercle":["french"],"cérébral":["french"],"cerise":["french"],"cerner":["french"],"cerveau":["french"],"cesser":["french"],"chagrin":["french"],"chaise":["french"],"chaleur":["french"],"chambre":["french"],"chance":["french"],"chapitre":["french"],"charbon":["french"],"chasseur":["french"],"chaton":["french"],"chausson":["french"],"chavirer":["french"],"chemise":["french"],"chenille":["french"],"chéquier":["french"],"chercher":["french"],"cheval":["french"],"chien":["french"],"chiffre":["french"],"chignon":["french"],"chimère":["french"],"chiot":["french"],"chlorure":["french"],"chocolat":["french"],"choisir":["french"],"chose":["french"],"chouette":["french"],"chrome":["french"],"chute":["french"],"cigare":["french"],"cigogne":["french"],"cimenter":["french"],"cinéma":["french"],"cintrer":["french"],"circuler":["french"],"cirer":["french"],"cirque":["french"],"citerne":["french"],"citoyen":["french"],"citron":["french"],"clairon":["french"],"clameur":["french"],"claquer":["french"],"classe":["french"],"clavier":["french"],"cligner":["french"],"climat":["french"],"clivage":["french"],"cloche":["french"],"clonage":["french"],"cloporte":["french"],"cobalt":["french"],"cobra":["french"],"cocasse":["french"],"cocotier":["french"],"coder":["french"],"codifier":["french"],"coffre":["french"],"cogner":["french"],"cohésion":["french"],"coiffer":["french"],"coincer":["french"],"colère":["french"],"colibri":["french"],"colline":["french"],"colmater":["french"],"colonel":["french"],"combat":["french"],"comédie":["french"],"commande":["french"],"compact":["french"],"conduire":["french"],"confier":["french"],"congeler":["french"],"connoter":["french"],"consonne":["french"],"contact":["french"],"convexe":["french"],"copain":["french"],"copie":["french"],"corail":["french"],"corbeau":["french"],"cordage":["french"],"corniche":["french"],"corpus":["french"],"cortège":["french"],"cosmique":["french"],"costume":["french"],"coton":["french"],"coude":["french"],"coupure":["french"],"courage":["french"],"couteau":["french"],"couvrir":["french"],"crabe":["french"],"crainte":["french"],"cravate":["french"],"crayon":["french"],"créature":["french"],"créditer":["french"],"crémeux":["french"],"creuser":["french"],"crevette":["french"],"cribler":["french"],"crier":["french"],"cristal":["french"],"critère":["french"],"croire":["french"],"croquer":["french"],"crotale":["french"],"crypter":["french"],"cubique":["french"],"cueillir":["french"],"cuillère":["french"],"cuisine":["french"],"cuivre":["french"],"culminer":["french"],"cultiver":["french"],"cumuler":["french"],"cupide":["french"],"curatif":["french"],"curseur":["french"],"cyanure":["french"],"cylindre":["french"],"cynique":["french"],"daigner":["french"],"damier":["french"],"danseur":["french"],"dauphin":["french"],"débattre":["french"],"débiter":["french"],"déborder":["french"],"débrider":["french"],"débutant":["french"],"décaler":["french"],"décembre":["french"],"déchirer":["french"],"décider":["french"],"déclarer":["french"],"décorer":["french"],"décrire":["french"],"décupler":["french"],"dédale":["french"],"déductif":["french"],"déesse":["french"],"défensif":["french"],"défiler":["french"],"défrayer":["french"],"dégager":["french"],"dégivrer":["french"],"déglutir":["french"],"dégrafer":["french"],"déjeuner":["french"],"délice":["french"],"déloger":["french"],"demander":["french"],"demeurer":["french"],"démolir":["french"],"dénicher":["french"],"dénouer":["french"],"dentelle":["french"],"dénuder":["french"],"départ":["french"],"dépenser":["french"],"déphaser":["french"],"déplacer":["french"],"déposer":["french"],"déranger":["french"],"dérober":["french"],"désastre":["french"],"descente":["french"],"désert":["french"],"désigner":["french"],"désobéir":["french"],"dessiner":["french"],"destrier":["french"],"détacher":["french"],"détester":["french"],"détourer":["french"],"détresse":["french"],"devancer":["french"],"devenir":["french"],"deviner":["french"],"devoir":["french"],"diable":["french"],"dialogue":["french"],"diamant":["french"],"dicter":["french"],"différer":["french"],"digérer":["french"],"digne":["french"],"diluer":["french"],"dimanche":["french"],"diminuer":["french"],"dioxyde":["french"],"directif":["french"],"diriger":["french"],"discuter":["french"],"disposer":["french"],"dissiper":["french"],"divertir":["french"],"diviser":["french"],"docile":["french"],"docteur":["french"],"dogme":["french"],"doigt":["french"],"domaine":["french"],"domicile":["french"],"dompter":["french"],"donateur":["french"],"donjon":["french"],"donner":["french"],"dopamine":["french"],"dortoir":["french"],"dorure":["french"],"dosage":["french"],"doseur":["french"],"dossier":["french"],"dotation":["french"],"douanier":["french"],"douceur":["french"],"douter":["french"],"doyen":["french"],"draper":["french"],"dresser":["french"],"dribbler":["french"],"droiture":["french"],"duperie":["french"],"duplexe":["french"],"durable":["french"],"durcir":["french"],"dynastie":["french"],"éblouir":["french"],"écarter":["french"],"écharpe":["french"],"échelle":["french"],"éclairer":["french"],"éclipse":["french"],"éclore":["french"],"écluse":["french"],"école":["french"],"économie":["french"],"écorce":["french"],"écouter":["french"],"écraser":["french"],"écrémer":["french"],"écrivain":["french"],"écrou":["french"],"écume":["french"],"écureuil":["french"],"édifier":["french"],"éduquer":["french"],"effacer":["french"],"effectif":["french"],"effigie":["french"],"effrayer":["french"],"effusion":["french"],"égaliser":["french"],"égarer":["french"],"éjecter":["french"],"élaborer":["french"],"élargir":["french"],"électron":["french"],"élégant":["french"],"éléphant":["french"],"élève":["french"],"éligible":["french"],"élitisme":["french"],"éloge":["french"],"élucider":["french"],"éluder":["french"],"emballer":["french"],"embellir":["french"],"embryon":["french"],"émeraude":["french"],"émission":["french"],"emmener":["french"],"émotion":["french"],"émouvoir":["french"],"empereur":["french"],"employer":["french"],"emporter":["french"],"emprise":["french"],"émulsion":["french"],"encadrer":["french"],"enchère":["french"],"enclave":["french"],"encoche":["french"],"endiguer":["french"],"endosser":["french"],"endroit":["french"],"enduire":["french"],"énergie":["french"],"enfance":["french"],"enfermer":["french"],"enfouir":["french"],"engager":["french"],"engin":["french","turkish"],"englober":["french"],"énigme":["french"],"enjamber":["french"],"enjeu":["french"],"enlever":["french"],"ennemi":["french"],"ennuyeux":["french"],"enrichir":["french"],"enrobage":["french"],"enseigne":["french"],"entasser":["french"],"entendre":["french"],"entier":["french"],"entourer":["french"],"entraver":["french"],"énumérer":["french"],"envahir":["french"],"enviable":["french"],"envoyer":["french"],"enzyme":["french"],"éolien":["french"],"épaissir":["french"],"épargne":["french"],"épatant":["french"],"épaule":["french"],"épicerie":["french"],"épidémie":["french"],"épier":["french"],"épilogue":["french"],"épine":["french"],"épisode":["french"],"épitaphe":["french"],"époque":["french"],"épreuve":["french"],"éprouver":["french"],"épuisant":["french"],"équerre":["french"],"équipe":["french"],"ériger":["french"],"érosion":["french"],"erreur":["french"],"éruption":["french"],"escalier":["french"],"espadon":["french"],"espèce":["french"],"espiègle":["french"],"espoir":["french"],"esprit":["french"],"esquiver":["french"],"essayer":["french"],"essieu":["french"],"essorer":["french"],"estime":["french"],"estomac":["french"],"estrade":["french"],"étagère":["french"],"étaler":["french"],"étanche":["french"],"étatique":["french"],"éteindre":["french"],"étendoir":["french"],"éternel":["french"],"éthanol":["french"],"éthique":["french"],"ethnie":["french"],"étirer":["french"],"étoffer":["french"],"étoile":["french"],"étonnant":["french"],"étourdir":["french"],"étrange":["french"],"étroit":["french"],"étude":["french"],"euphorie":["french"],"évaluer":["french"],"évasion":["french"],"éventail":["french"],"évidence":["french"],"éviter":["french"],"évolutif":["french"],"évoquer":["french"],"exagérer":["french"],"exaucer":["french"],"exceller":["french"],"excitant":["french"],"exclusif":["french"],"exécuter":["french"],"exemple":["french"],"exercer":["french"],"exhaler":["french"],"exhorter":["french"],"exigence":["french"],"exiler":["french"],"exister":["french"],"exotique":["french"],"expédier":["french"],"explorer":["french"],"exposer":["french"],"exprimer":["french"],"exquis":["french"],"extensif":["french"],"extraire":["french"],"exulter":["french"],"fable":["french"],"fabuleux":["french"],"facette":["french"],"facile":["french"],"facture":["french"],"faiblir":["french"],"falaise":["french"],"fameux":["french"],"famille":["french"],"farceur":["french"],"farfelu":["french"],"farine":["french"],"farouche":["french"],"fasciner":["french"],"faucon":["french"],"fautif":["french"],"faveur":["french"],"favori":["french","turkish"],"fébrile":["french"],"féconder":["french"],"fédérer":["french"],"félin":["french"],"femme":["french"],"fémur":["french"],"fendoir":["french"],"féodal":["french"],"fermer":["french"],"féroce":["french"],"ferveur":["french"],"feuille":["french"],"feutre":["french"],"février":["french"],"fiasco":["french"],"ficeler":["french"],"fictif":["french"],"fidèle":["french"],"filature":["french"],"filetage":["french"],"filière":["french"],"filleul":["french"],"filmer":["french"],"filou":["french"],"filtrer":["french"],"financer":["french"],"finir":["french"],"fiole":["french"],"firme":["french"],"fissure":["french"],"fixer":["french"],"flairer":["french"],"flamme":["french"],"flasque":["french"],"flatteur":["french"],"fléau":["french"],"flèche":["french"],"fleur":["french"],"flexion":["french"],"flocon":["french"],"flore":["french"],"fluctuer":["french"],"fluide":["french"],"fluvial":["french"],"folie":["french"],"fonderie":["french"],"fongible":["french"],"fontaine":["french"],"forcer":["french"],"forgeron":["french"],"formuler":["french"],"fossile":["french"],"foudre":["french"],"fougère":["french"],"fouiller":["french"],"foulure":["french"],"fourmi":["french"],"fraise":["french"],"franchir":["french"],"frapper":["french"],"frayeur":["french"],"frégate":["french"],"freiner":["french"],"frelon":["french"],"frémir":["french"],"frénésie":["french"],"frère":["french"],"friable":["french"],"friction":["french"],"frisson":["french"],"frivole":["french"],"froid":["french"],"fromage":["french"],"frontal":["french"],"frotter":["french"],"fugitif":["french"],"fuite":["french"],"fureur":["french"],"furieux":["french"],"furtif":["french"],"fusion":["french"],"futur":["french"],"gagner":["french"],"galaxie":["french"],"galerie":["french"],"gambader":["french"],"garantir":["french"],"gardien":["french"],"garnir":["french"],"garrigue":["french"],"gazelle":["french"],"gazon":["french"],"géant":["french"],"gélatine":["french"],"gélule":["french"],"gendarme":["french"],"général":["french"],"génie":["french"],"genou":["french"],"gentil":["french"],"géologie":["french"],"géomètre":["french"],"géranium":["french"],"germe":["french"],"gestuel":["french"],"geyser":["french"],"gibier":["french"],"gicler":["french"],"girafe":["french"],"givre":["french"],"glace":["french"],"glaive":["french"],"glisser":["french"],"gloire":["french"],"glorieux":["french"],"golfeur":["french"],"gomme":["french"],"gonfler":["french"],"gorge":["french"],"gorille":["french"],"goudron":["french"],"gouffre":["french"],"goulot":["french"],"goupille":["french"],"gourmand":["french"],"goutte":["french"],"graduel":["french"],"graffiti":["french"],"graine":["french"],"grand":["french"],"grappin":["french"],"gratuit":["french"],"gravir":["french"],"grenat":["french"],"griffure":["french"],"griller":["french"],"grimper":["french"],"grogner":["french"],"gronder":["french"],"grotte":["french"],"groupe":["french"],"gruger":["french"],"grutier":["french"],"gruyère":["french"],"guépard":["french"],"guerrier":["french"],"guimauve":["french"],"guitare":["french"],"gustatif":["french"],"gymnaste":["french"],"gyrostat":["french"],"habitude":["french"],"hachoir":["french"],"halte":["french"],"hameau":["french"],"hangar":["french","turkish"],"hanneton":["french"],"haricot":["french"],"harmonie":["french"],"harpon":["french"],"hasard":["french"],"hélium":["french"],"hématome":["french"],"herbe":["french"],"hérisson":["french"],"hermine":["french"],"héron":["french"],"hésiter":["french"],"heureux":["french"],"hiberner":["french"],"hibou":["french"],"hilarant":["french"],"histoire":["french"],"hiver":["french"],"homard":["french"],"hommage":["french"],"homogène":["french"],"honneur":["french"],"honorer":["french"],"honteux":["french"],"horde":["french"],"horizon":["french"],"horloge":["french"],"hormone":["french"],"horrible":["french"],"houleux":["french"],"housse":["french"],"hublot":["french"],"huileux":["french"],"humain":["french"],"humide":["french"],"humour":["french"],"hurler":["french"],"hydromel":["french"],"hygiène":["french"],"hymne":["french"],"hypnose":["french"],"idylle":["french"],"ignorer":["french"],"iguane":["french"],"illicite":["french"],"illusion":["french"],"imbiber":["french"],"imiter":["french"],"immobile":["french"],"immuable":["french"],"impérial":["french"],"implorer":["french"],"imposer":["french"],"imprimer":["french"],"imputer":["french"],"incarner":["french"],"incendie":["french"],"incident":["french"],"incliner":["french"],"incolore":["french"],"indexer":["french"],"indice":["french"],"inductif":["french"],"inédit":["french"],"ineptie":["french"],"inexact":["french"],"infini":["french"],"infliger":["french"],"informer":["french"],"infusion":["french"],"ingérer":["french"],"inhaler":["french"],"inhiber":["french"],"injecter":["french"],"injure":["french"],"inoculer":["french"],"inonder":["french"],"inscrire":["french"],"insecte":["french"],"insigne":["french"],"insolite":["french"],"inspirer":["french"],"instinct":["french"],"insulter":["french"],"intense":["french"],"intime":["french"],"intrigue":["french"],"intuitif":["french"],"inutile":["french"],"invasion":["french"],"inventer":["french"],"inviter":["french"],"invoquer":["french"],"ironique":["french"],"irradier":["french"],"irréel":["french"],"irriter":["french"],"isoler":["french"],"ivoire":["french"],"ivresse":["french"],"jaillir":["french"],"jambe":["french"],"janvier":["french"],"jardin":["french"],"jauger":["french"],"jaune":["french"],"javelot":["french"],"jetable":["french"],"jeton":["french"],"jeudi":["french"],"jeunesse":["french"],"joindre":["french"],"joncher":["french"],"jongler":["french"],"joueur":["french"],"jouissif":["french"],"journal":["french"],"jovial":["french"],"joyau":["french"],"joyeux":["french"],"jubiler":["french"],"jugement":["french"],"jupon":["french"],"juriste":["french"],"justice":["french"],"juteux":["french"],"juvénile":["french"],"kayak":["french"],"kimono":["french"],"kiosque":["french"],"labial":["french"],"labourer":["french"],"lacérer":["french"],"lactose":["french"],"lagune":["french"],"laine":["french"],"laisser":["french"],"laitier":["french"],"lambeau":["french"],"lamelle":["french"],"lampe":["french"],"lanceur":["french"],"langage":["french"],"lanterne":["french"],"lapin":["french"],"largeur":["french"],"larme":["french"],"laurier":["french"],"lavabo":["french"],"lavoir":["french"],"légal":["french"],"léger":["french"],"légume":["french"],"lessive":["french"],"lettre":["french"],"levier":["french"],"lexique":["french"],"lézard":["french"],"liasse":["french"],"libérer":["french"],"libre":["french"],"licence":["french"],"licorne":["french"],"liège":["french"],"lièvre":["french"],"ligature":["french"],"ligoter":["french"],"ligue":["french"],"limer":["french"],"limite":["french"],"limonade":["french"],"limpide":["french"],"linéaire":["french"],"lingot":["french"],"lionceau":["french"],"liquide":["french"],"lisière":["french"],"lister":["french"],"lithium":["french"],"litige":["french"],"littoral":["french"],"livreur":["french"],"logique":["french"],"lointain":["french"],"loisir":["french"],"lombric":["french"],"loterie":["french"],"louer":["french"],"lourd":["french"],"loutre":["french"],"louve":["french"],"lubie":["french"],"lucide":["french"],"lucratif":["french"],"lueur":["french"],"lugubre":["french"],"luisant":["french"],"lumière":["french"],"lunaire":["french"],"lundi":["french"],"luron":["french"],"lutter":["french"],"luxueux":["french"],"magasin":["french"],"magenta":["french"],"magique":["french"],"maigre":["french"],"maillon":["french"],"maintien":["french"],"mairie":["french"],"maison":["french"],"majorer":["french"],"malaxer":["french"],"maléfice":["french"],"malheur":["french"],"malice":["french"],"mallette":["french"],"mammouth":["french"],"mandater":["french"],"maniable":["french"],"manquant":["french"],"manteau":["french"],"manuel":["french"],"marathon":["french"],"marbre":["french"],"marchand":["french"],"mardi":["french"],"maritime":["french"],"marqueur":["french"],"marron":["french"],"marteler":["french"],"mascotte":["french"],"massif":["french"],"matériel":["french"],"matière":["french"],"matraque":["french"],"maudire":["french"],"maussade":["french"],"mauve":["french"],"maximal":["french"],"méchant":["french"],"méconnu":["french"],"médaille":["french"],"médecin":["french"],"méditer":["french"],"méduse":["french"],"meilleur":["french"],"mélange":["french"],"mélodie":["french"],"membre":["french"],"mémoire":["french"],"menacer":["french"],"mener":["french"],"menhir":["french"],"mensonge":["french"],"mentor":["french"],"mercredi":["french"],"mérite":["french"],"merle":["french"],"messager":["french"],"mesure":["french"],"métal":["french"],"météore":["french"],"méthode":["french"],"métier":["french"],"meuble":["french"],"miauler":["french"],"microbe":["french"],"miette":["french"],"mignon":["french"],"migrer":["french"],"milieu":["french"],"mimique":["french"],"mince":["french"],"minéral":["french"],"minimal":["french"],"minorer":["french"],"miroiter":["french"],"missile":["french"],"mixte":["french"],"moderne":["french"],"moelleux":["french"],"mondial":["french"],"moniteur":["french"],"monnaie":["french"],"monotone":["french"],"monstre":["french"],"montagne":["french"],"monument":["french"],"moqueur":["french"],"morceau":["french"],"morsure":["french"],"mortier":["french"],"moteur":["french"],"motif":["french"],"mouche":["french"],"moufle":["french"],"moulin":["french"],"mousson":["french"],"mouton":["french"],"mouvant":["french"],"multiple":["french"],"munition":["french"],"muraille":["french"],"murène":["french"],"murmure":["french"],"muséum":["french"],"musicien":["french"],"mutation":["french"],"muter":["french"],"mutuel":["french"],"myriade":["french"],"myrtille":["french"],"mystère":["french"],"mythique":["french"],"nageur":["french"],"nappe":["french"],"narquois":["french"],"narrer":["french"],"natation":["french"],"naufrage":["french"],"nautique":["french"],"navire":["french"],"nébuleux":["french"],"nectar":["french"],"néfaste":["french"],"négation":["french"],"négliger":["french"],"négocier":["french"],"neige":["french"],"nerveux":["french"],"nettoyer":["french"],"neurone":["french"],"neutron":["french"],"neveu":["french"],"niche":["french"],"nickel":["french"],"nitrate":["french"],"niveau":["french"],"nocif":["french"],"nocturne":["french"],"noirceur":["french"],"noisette":["french"],"nomade":["french"],"nombreux":["french"],"nommer":["french"],"normatif":["french"],"notifier":["french"],"notoire":["french"],"nourrir":["french"],"nouveau":["french"],"novateur":["french"],"novembre":["french"],"novice":["french"],"nuage":["french"],"nuancer":["french"],"nuire":["french"],"nuisible":["french"],"numéro":["french"],"nuptial":["french"],"nuque":["french"],"nutritif":["french"],"obéir":["french"],"objectif":["french"],"obliger":["french"],"obscur":["french"],"observer":["french"],"obstacle":["french"],"obtenir":["french"],"obturer":["french"],"occasion":["french"],"occuper":["french"],"océan":["french"],"octobre":["french"],"octroyer":["french"],"octupler":["french"],"oculaire":["french"],"odeur":["french"],"odorant":["french"],"offenser":["french"],"officier":["french"],"offrir":["french"],"ogive":["french"],"oiseau":["french"],"oisillon":["french"],"olfactif":["french"],"olivier":["french"],"ombrage":["french"],"omettre":["french"],"onctueux":["french"],"onduler":["french"],"onéreux":["french"],"onirique":["french"],"opale":["french"],"opaque":["french"],"opérer":["french"],"opportun":["french"],"opprimer":["french"],"opter":["french"],"optique":["french"],"orageux":["french"],"orbite":["french"],"ordonner":["french"],"oreille":["french"],"organe":["french"],"orgueil":["french"],"orifice":["french"],"ornement":["french"],"orque":["french"],"ortie":["french"],"osciller":["french"],"osmose":["french"],"ossature":["french"],"otarie":["french"],"ouragan":["french"],"ourson":["french"],"outil":["french"],"outrager":["french"],"ouvrage":["french"],"ovation":["french"],"oxyde":["french"],"oxygène":["french"],"paisible":["french"],"palmarès":["french"],"palourde":["french"],"palper":["french"],"panache":["french"],"pangolin":["french"],"paniquer":["french"],"panneau":["french"],"panorama":["french"],"pantalon":["french"],"papaye":["french"],"papier":["french"],"papoter":["french"],"papyrus":["french"],"paradoxe":["french"],"parcelle":["french"],"paresse":["french"],"parfumer":["french"],"parler":["french"],"parole":["french"],"parrain":["french"],"parsemer":["french"],"partager":["french"],"parure":["french"],"parvenir":["french"],"passion":["french"],"pastèque":["french"],"paternel":["french"],"patience":["french"],"patron":["french","turkish"],"pavillon":["french"],"pavoiser":["french"],"payer":["french"],"paysage":["french"],"peigne":["french"],"peintre":["french"],"pelage":["french"],"pélican":["french"],"pelle":["french"],"pelouse":["french"],"peluche":["french"],"pendule":["french"],"pénétrer":["french"],"pénible":["french"],"pensif":["french"],"pénurie":["french"],"pépite":["french"],"péplum":["french"],"perdrix":["french"],"perforer":["french"],"période":["french"],"permuter":["french"],"perplexe":["french"],"persil":["french"],"perte":["french"],"peser":["french"],"pétale":["french"],"petit":["french"],"pétrir":["french"],"peuple":["french"],"pharaon":["french"],"phobie":["french"],"phoque":["french"],"photon":["french"],"physique":["french"],"pictural":["french"],"pièce":["french"],"pierre":["french"],"pieuvre":["french"],"pilote":["french"],"pinceau":["french"],"pipette":["french"],"piquer":["french"],"pirogue":["french"],"piscine":["french"],"piston":["french"],"pivoter":["french"],"pixel":["french"],"placard":["french"],"plafond":["french"],"plaisir":["french"],"planer":["french"],"plaque":["french"],"plastron":["french"],"plateau":["french"],"pleurer":["french"],"plexus":["french"],"pliage":["french"],"plomb":["french"],"plonger":["french"],"pluie":["french"],"plumage":["french"],"pochette":["french"],"poésie":["french"],"poète":["french"],"pointe":["french"],"poirier":["french"],"poisson":["french"],"poivre":["french"],"polaire":["french"],"policier":["french"],"pollen":["french"],"polygone":["french"],"pommade":["french"],"pompier":["french"],"ponctuel":["french"],"pondérer":["french"],"poney":["french"],"portique":["french"],"posséder":["french"],"posture":["french"],"potager":["french"],"poteau":["french"],"potion":["french"],"pouce":["french"],"poulain":["french"],"poumon":["french"],"pourpre":["french"],"poussin":["french"],"pouvoir":["french"],"prairie":["french"],"pratique":["french"],"précieux":["french"],"prédire":["french"],"préfixe":["french"],"prélude":["french"],"prénom":["french"],"présence":["french"],"prétexte":["french"],"prévoir":["french"],"primitif":["french"],"prince":["french"],"priver":["french"],"problème":["french"],"procéder":["french"],"prodige":["french"],"profond":["french"],"progrès":["french"],"proie":["french"],"projeter":["french"],"prologue":["french"],"promener":["french"],"propre":["french"],"prospère":["french"],"protéger":["french"],"prouesse":["french"],"proverbe":["french"],"prudence":["french"],"pruneau":["french"],"psychose":["french"],"puceron":["french"],"puiser":["french"],"pulpe":["french"],"pulsar":["french"],"punaise":["french"],"punitif":["french"],"pupitre":["french"],"purifier":["french"],"pyramide":["french"],"quasar":["french"],"querelle":["french"],"quiétude":["french"],"quitter":["french"],"quotient":["french"],"racine":["french"],"raconter":["french"],"radieux":["french"],"ragondin":["french"],"raideur":["french"],"raisin":["french"],"ralentir":["french"],"rallonge":["french"],"ramasser":["french"],"rapide":["french"],"rasage":["french"],"ratisser":["french"],"ravager":["french"],"ravin":["french"],"rayonner":["french"],"réactif":["french"],"réagir":["french"],"réaliser":["french"],"réanimer":["french"],"recevoir":["french"],"réciter":["french"],"réclamer":["french"],"récolter":["french"],"recruter":["french"],"reculer":["french"],"recycler":["french"],"rédiger":["french"],"redouter":["french"],"refaire":["french"],"réflexe":["french"],"réformer":["french"],"refrain":["french"],"refuge":["french"],"régalien":["french"],"région":["french"],"réglage":["french"],"régulier":["french"],"réitérer":["french"],"rejeter":["french"],"rejouer":["french"],"relatif":["french"],"relever":["french"],"remarque":["french"],"remède":["french"],"remise":["french"],"remonter":["french"],"remplir":["french"],"remuer":["french"],"renard":["french"],"renfort":["french"],"renifler":["french"],"renoncer":["french"],"rentrer":["french"],"renvoi":["french"],"replier":["french"],"reporter":["french"],"reprise":["french"],"reptile":["french"],"requin":["french"],"réserve":["french"],"résineux":["french"],"résoudre":["french"],"respect":["french"],"rester":["french"],"résultat":["french"],"rétablir":["french"],"retenir":["french"],"réticule":["french"],"retomber":["french"],"retracer":["french"],"réunion":["french"],"réussir":["french"],"revanche":["french"],"revivre":["french"],"révolte":["french"],"révulsif":["french"],"richesse":["french"],"rideau":["french"],"rieur":["french"],"rigide":["french"],"rigoler":["french"],"rincer":["french"],"riposter":["french"],"risible":["french"],"risque":["french"],"rituel":["french"],"rivière":["french"],"rocheux":["french"],"rompre":["french"],"ronce":["french"],"rondin":["french"],"roseau":["french"],"rosier":["french"],"rotatif":["french"],"rotor":["french"],"rotule":["french"],"rouge":["french"],"rouille":["french"],"rouleau":["french"],"routine":["french"],"royaume":["french"],"ruban":["french"],"rubis":["french"],"ruche":["french"],"ruelle":["french"],"rugueux":["french"],"ruiner":["french"],"ruisseau":["french"],"ruser":["french"],"rustique":["french"],"rythme":["french"],"sabler":["french"],"saboter":["french"],"sabre":["french"],"sacoche":["french"],"safari":["french"],"sagesse":["french"],"saisir":["french"],"salade":["french"],"salive":["french"],"saluer":["french"],"samedi":["french"],"sanction":["french"],"sanglier":["french"],"sarcasme":["french"],"sardine":["french"],"saturer":["french"],"saugrenu":["french"],"saumon":["french"],"sauter":["french"],"sauvage":["french"],"savant":["french"],"savonner":["french"],"scalpel":["french"],"scandale":["french"],"scélérat":["french"],"scénario":["french"],"sceptre":["french"],"schéma":["french"],"scinder":["french"],"score":["french"],"scrutin":["french"],"sculpter":["french"],"séance":["french"],"sécable":["french"],"sécher":["french"],"secouer":["french"],"sécréter":["french"],"sédatif":["french"],"séduire":["french"],"seigneur":["french"],"séjour":["french"],"sélectif":["french"],"semaine":["french"],"sembler":["french"],"semence":["french"],"séminal":["french"],"sénateur":["french"],"sensible":["french"],"séparer":["french"],"séquence":["french"],"serein":["french"],"sergent":["french"],"sérieux":["french"],"serrure":["french"],"sérum":["french"],"sésame":["french"],"sévir":["french"],"sevrage":["french"],"sextuple":["french"],"sidéral":["french"],"siècle":["french"],"siéger":["french"],"siffler":["french"],"sigle":["french"],"signal":["french"],"silence":["french"],"silicium":["french"],"sincère":["french"],"sinistre":["french"],"siphon":["french"],"sirop":["french"],"sismique":["french"],"situer":["french"],"skier":["french"],"socle":["french"],"sodium":["french"],"soigneux":["french"],"soldat":["french"],"soleil":["french"],"solitude":["french"],"soluble":["french"],"sombre":["french"],"sommeil":["french"],"somnoler":["french"],"sonde":["french"],"songeur":["french"],"sonnette":["french"],"sonore":["french"],"sorcier":["french"],"sortir":["french"],"sosie":["french"],"sottise":["french"],"soucieux":["french"],"soudure":["french"],"souffle":["french"],"soulever":["french"],"soupape":["french"],"soutirer":["french"],"souvenir":["french"],"spacieux":["french"],"spécial":["french"],"sphère":["french"],"spiral":["french","turkish"],"station":["french"],"sternum":["french"],"stimulus":["french"],"stipuler":["french"],"strict":["french"],"studieux":["french"],"stupeur":["french"],"styliste":["french"],"sublime":["french"],"substrat":["french"],"subtil":["french"],"subvenir":["french"],"succès":["french"],"sucre":["french"],"suffixe":["french"],"suggérer":["french"],"suiveur":["french"],"sulfate":["french"],"superbe":["french"],"supplier":["french"],"suricate":["french"],"surmener":["french"],"sursaut":["french"],"survie":["french"],"syllabe":["french"],"symbole":["french"],"symétrie":["french"],"synapse":["french"],"syntaxe":["french"],"système":["french"],"tabac":["french"],"tablier":["french"],"tactile":["french"],"tailler":["french"],"talisman":["french"],"talonner":["french"],"tambour":["french"],"tamiser":["french"],"tangible":["french"],"tapis":["french"],"taquiner":["french"],"tarder":["french"],"tarif":["french"],"tartine":["french"],"tasse":["french"],"tatami":["french"],"tatouage":["french"],"taupe":["french"],"taureau":["french"],"taxer":["french"],"témoin":["french"],"temporel":["french"],"tenaille":["french"],"tendre":["french"],"teneur":["french"],"tenir":["french"],"tension":["french"],"terminer":["french"],"terne":["french"],"terrible":["french"],"tétine":["french"],"texte":["french"],"thème":["french"],"théorie":["french"],"thérapie":["french"],"thorax":["french"],"tibia":["french"],"tiède":["french"],"timide":["french"],"tirelire":["french"],"tiroir":["french"],"tissu":["french"],"titane":["french"],"titre":["french"],"tituber":["french"],"toboggan":["french"],"tolérant":["french"],"tomate":["french"],"tonique":["french"],"tonneau":["french"],"toponyme":["french"],"torche":["french"],"tordre":["french"],"tornade":["french"],"torpille":["french"],"torrent":["french"],"torse":["french"],"tortue":["french"],"totem":["french"],"toucher":["french"],"tournage":["french"],"tousser":["french"],"toxine":["french"],"traction":["french"],"trafic":["french"],"tragique":["french"],"trahir":["french"],"trancher":["french"],"travail":["french"],"trèfle":["french"],"tremper":["french"],"trésor":["french"],"treuil":["french"],"triage":["french"],"tribunal":["french"],"tricoter":["french"],"trilogie":["french"],"triomphe":["french"],"tripler":["french"],"triturer":["french"],"trivial":["french"],"trombone":["french"],"tronc":["french"],"tropical":["french"],"troupeau":["french"],"tuile":["french"],"tulipe":["french"],"tumulte":["french"],"turbine":["french"],"tuteur":["french"],"tutoyer":["french"],"tuyau":["french"],"tympan":["french"],"typhon":["french"],"typique":["french"],"tyran":["french"],"ubuesque":["french"],"ultime":["french"],"ultrason":["french"],"unanime":["french"],"unifier":["french"],"union":["french"],"unitaire":["french"],"univers":["french"],"uranium":["french"],"urbain":["french"],"urticant":["french"],"usine":["french"],"usuel":["french"],"usure":["french"],"utile":["french"],"utopie":["french"],"vacarme":["french"],"vaccin":["french"],"vagabond":["french"],"vaillant":["french"],"vaincre":["french"],"vaisseau":["french"],"valable":["french"],"valise":["french"],"vallon":["french"],"vampire":["french"],"vanille":["french"],"vapeur":["french"],"varier":["french"],"vaseux":["french"],"vassal":["french"],"vaste":["french"],"vecteur":["french"],"vedette":["french"],"végétal":["french"],"véhicule":["french"],"veinard":["french"],"véloce":["french"],"vendredi":["french"],"vénérer":["french"],"venger":["french"],"venimeux":["french"],"ventouse":["french"],"verdure":["french"],"vérin":["french"],"vernir":["french"],"verrou":["french"],"verser":["french"],"vertu":["french"],"veston":["french"],"vétéran":["french"],"vétuste":["french"],"vexant":["french"],"vexer":["french"],"viaduc":["french"],"viande":["french"],"victoire":["french"],"vidange":["french"],"vidéo":["french"],"vignette":["french"],"vigueur":["french"],"vilain":["french"],"vinaigre":["french"],"violon":["french"],"vipère":["french"],"virement":["french"],"virtuose":["french"],"visage":["french"],"viseur":["french"],"vision":["french"],"visqueux":["french"],"visuel":["french"],"vitesse":["french"],"viticole":["french"],"vitrine":["french"],"vivace":["french"],"vivipare":["french"],"vocation":["french"],"voguer":["french"],"voile":["french"],"voisin":["french"],"voiture":["french"],"volaille":["french"],"volcan":["french"],"voltiger":["french"],"vorace":["french"],"vortex":["french"],"voter":["french"],"vouloir":["french"],"voyelle":["french"],"xénon":["french"],"yacht":["french"],"zèbre":["french"],"zénith":["french"],"zeste":["french"],"zoologie":["french"],"abaco":["italian"],"abbaglio":["italian"],"abbinato":["italian"],"abete":["italian"],"abisso":["italian"],"abolire":["italian"],"abrasivo":["italian"],"abrogato":["italian"],"accadere":["italian"],"accenno":["italian"],"accusato":["italian"],"acetone":["italian"],"achille":["italian"],"acido":["italian"],"acqua":["italian"],"acre":["italian"],"acrilico":["italian"],"acrobata":["italian"],"acuto":["italian"],"adagio":["italian"],"addebito":["italian"],"addome":["italian"],"adeguato":["italian"],"aderire":["italian"],"adipe":["italian"],"adottare":["italian"],"adulare":["italian"],"affabile":["italian"],"affetto":["italian"],"affisso":["italian"],"affranto":["italian"],"aforisma":["italian"],"afoso":["italian"],"africano":["italian"],"agave":["italian"],"agente":["italian"],"agevole":["italian"],"aggancio":["italian"],"agire":["italian"],"agitare":["italian"],"agonismo":["italian"],"agricolo":["italian"],"agrumeto":["italian"],"aguzzo":["italian"],"alabarda":["italian"],"alato":["italian"],"albatro":["italian"],"alberato":["italian"],"albo":["italian"],"albume":["italian"],"alce":["italian"],"alcolico":["italian"],"alettone":["italian"],"alfa":["italian"],"algebra":["italian"],"aliante":["italian"],"alibi":["italian"],"alimento":["italian"],"allagato":["italian"],"allegro":["italian"],"allievo":["italian"],"allodola":["italian"],"allusivo":["italian"],"almeno":["italian"],"alogeno":["italian"],"alpaca":["italian"],"alpestre":["italian"],"altalena":["italian"],"alterno":["italian"],"alticcio":["italian"],"altrove":["italian"],"alunno":["italian"],"alveolo":["italian"],"alzare":["italian"],"amalgama":["italian"],"amanita":["italian"],"amarena":["italian"],"ambito":["italian"],"ambrato":["italian"],"ameba":["italian"],"america":["italian"],"ametista":["italian"],"amico":["italian"],"ammasso":["italian"],"ammenda":["italian"],"ammirare":["italian"],"ammonito":["italian"],"amore":["italian"],"ampio":["italian"],"ampliare":["italian"],"amuleto":["italian"],"anacardo":["italian"],"anagrafe":["italian"],"analista":["italian"],"anarchia":["italian"],"anatra":["italian"],"anca":["italian"],"ancella":["italian"],"ancora":["italian"],"andare":["italian"],"andrea":["italian"],"anello":["italian"],"angelo":["italian"],"angolare":["italian"],"angusto":["italian"],"anima":["italian"],"annegare":["italian"],"annidato":["italian"],"anno":["italian"],"annuncio":["italian"],"anonimo":["italian"],"anticipo":["italian"],"anzi":["italian"],"apatico":["italian"],"apertura":["italian"],"apode":["italian"],"apparire":["italian"],"appetito":["italian"],"appoggio":["italian"],"approdo":["italian"],"appunto":["italian"],"aprile":["italian"],"arabica":["italian"],"arachide":["italian"],"aragosta":["italian"],"araldica":["italian"],"arancio":["italian"],"aratura":["italian"],"arazzo":["italian"],"arbitro":["italian"],"archivio":["italian"],"ardito":["italian"],"arenile":["italian"],"argento":["italian"],"argine":["italian"],"arguto":["italian"],"aria":["italian"],"armonia":["italian"],"arnese":["italian"],"arredato":["italian"],"arringa":["italian"],"arrosto":["italian"],"arsenico":["italian"],"arso":["italian"],"artefice":["italian"],"arzillo":["italian"],"asciutto":["italian"],"ascolto":["italian"],"asepsi":["italian"],"asettico":["italian"],"asfalto":["italian"],"asino":["italian"],"asola":["italian"],"aspirato":["italian"],"aspro":["italian"],"assaggio":["italian"],"asse":["italian"],"assoluto":["italian"],"assurdo":["italian"],"asta":["italian"],"astenuto":["italian"],"astice":["italian"],"astratto":["italian"],"atavico":["italian"],"ateismo":["italian"],"atomico":["italian"],"atono":["italian"],"attesa":["italian"],"attivare":["italian"],"attorno":["italian"],"attrito":["italian"],"attuale":["italian"],"ausilio":["italian"],"austria":["italian"],"autista":["italian"],"autonomo":["italian"],"autunno":["italian"],"avanzato":["italian"],"avere":["italian"],"avvenire":["italian"],"avviso":["italian"],"avvolgere":["italian"],"azione":["italian"],"azoto":["italian"],"azzimo":["italian"],"azzurro":["italian"],"babele":["italian"],"baccano":["italian"],"bacino":["italian"],"baco":["italian"],"badessa":["italian"],"badilata":["italian"],"bagnato":["italian"],"baita":["italian"],"balcone":["italian"],"baldo":["italian"],"balena":["italian"],"ballata":["italian"],"balzano":["italian"],"bambino":["italian"],"bandire":["italian"],"baraonda":["italian"],"barbaro":["italian"],"barca":["italian"],"baritono":["italian"],"barlume":["italian"],"barocco":["italian"],"basilico":["italian"],"basso":["italian"],"batosta":["italian"],"battuto":["italian"],"baule":["italian"],"bava":["italian"],"bavosa":["italian"],"becco":["italian"],"beffa":["italian"],"belgio":["italian"],"belva":["italian"],"benda":["italian"],"benevole":["italian"],"benigno":["italian"],"benzina":["italian"],"bere":["italian"],"berlina":["italian"],"beta":["italian"],"bibita":["italian"],"bici":["italian"],"bidone":["italian"],"bifido":["italian"],"biga":["italian"],"bilancia":["italian"],"bimbo":["italian"],"binocolo":["italian"],"biologo":["italian"],"bipede":["italian"],"bipolare":["italian"],"birbante":["italian"],"birra":["italian"],"biscotto":["italian"],"bisesto":["italian"],"bisnonno":["italian"],"bisonte":["italian"],"bisturi":["italian"],"bizzarro":["italian"],"blando":["italian"],"blatta":["italian"],"bollito":["italian"],"bonifico":["italian"],"bordo":["italian"],"bosco":["italian"],"botanico":["italian"],"bottino":["italian"],"bozzolo":["italian"],"braccio":["italian"],"bradipo":["italian"],"brama":["italian"],"branca":["italian"],"bravura":["italian"],"bretella":["italian"],"brevetto":["italian"],"brezza":["italian"],"briglia":["italian"],"brillante":["italian"],"brindare":["italian"],"broccolo":["italian"],"brodo":["italian"],"bronzina":["italian"],"brullo":["italian"],"bruno":["italian"],"bubbone":["italian"],"buca":["italian"],"budino":["italian"],"buffone":["italian"],"buio":["italian"],"bulbo":["italian"],"buono":["italian"],"burlone":["italian"],"burrasca":["italian"],"bussola":["italian"],"busta":["italian"],"cadetto":["italian"],"caduco":["italian"],"calamaro":["italian"],"calcolo":["italian"],"calesse":["italian"],"calibro":["italian"],"calmo":["italian"],"caloria":["italian"],"cambusa":["italian"],"camerata":["italian"],"camicia":["italian"],"cammino":["italian"],"camola":["italian"],"campale":["italian"],"canapa":["italian"],"candela":["italian"],"cane":["italian"],"canino":["italian"],"canotto":["italian"],"cantina":["italian"],"capace":["italian"],"capello":["italian"],"capitolo":["italian"],"capogiro":["italian"],"cappero":["italian"],"capra":["italian"],"capsula":["italian"],"carapace":["italian"],"carcassa":["italian"],"cardo":["italian"],"carisma":["italian"],"carovana":["italian"],"carretto":["italian"],"cartolina":["italian"],"casaccio":["italian"],"cascata":["italian"],"caserma":["italian"],"caso":["italian"],"cassone":["italian"],"castello":["italian"],"casuale":["italian"],"catasta":["italian"],"catena":["italian"],"catrame":["italian"],"cauto":["italian"],"cavillo":["italian"],"cedibile":["italian"],"cedrata":["italian"],"cefalo":["italian"],"celebre":["italian"],"cellulare":["italian"],"cena":["italian"],"cenone":["italian"],"centesimo":["italian"],"ceramica":["italian"],"cercare":["italian"],"certo":["italian"],"cerume":["italian"],"cervello":["italian"],"cesoia":["italian"],"cespo":["italian"],"ceto":["italian"],"chela":["italian"],"chiaro":["italian"],"chicca":["italian"],"chiedere":["italian"],"chimera":["italian"],"china":["italian"],"chirurgo":["italian"],"chitarra":["italian"],"ciao":["italian"],"ciclismo":["italian"],"cifrare":["italian"],"cigno":["italian"],"cilindro":["italian"],"ciottolo":["italian"],"circa":["italian"],"cirrosi":["italian"],"citrico":["italian"],"cittadino":["italian"],"ciuffo":["italian"],"civetta":["italian"],"civile":["italian"],"classico":["italian"],"clinica":["italian"],"cloro":["italian"],"cocco":["italian"],"codardo":["italian"],"codice":["italian"],"coerente":["italian"],"cognome":["italian"],"collare":["italian"],"colmato":["italian"],"colore":["italian"],"colposo":["italian"],"coltivato":["italian"],"colza":["italian"],"coma":["italian"],"cometa":["italian"],"commando":["italian"],"comodo":["italian"],"computer":["italian"],"comune":["italian"],"conciso":["italian"],"condurre":["italian"],"conferma":["italian"],"congelare":["italian"],"coniuge":["italian"],"connesso":["italian"],"conoscere":["italian"],"consumo":["italian"],"continuo":["italian"],"convegno":["italian"],"coperto":["italian"],"copione":["italian"],"coppia":["italian"],"copricapo":["italian"],"corazza":["italian"],"cordata":["italian"],"coricato":["italian"],"cornice":["italian"],"corolla":["italian"],"corpo":["italian"],"corredo":["italian"],"corsia":["italian"],"cortese":["italian"],"cosmico":["italian"],"costante":["italian"],"cottura":["italian"],"covato":["italian"],"cratere":["italian"],"cravatta":["italian"],"creato":["italian"],"credere":["italian"],"cremoso":["italian"],"crescita":["italian"],"creta":["italian"],"criceto":["italian"],"crinale":["italian"],"crisi":["italian"],"critico":["italian"],"croce":["italian"],"cronaca":["italian"],"crostata":["italian"],"cruciale":["italian"],"crusca":["italian"],"cucire":["italian"],"cuculo":["italian"],"cugino":["italian"],"cullato":["italian"],"cupola":["italian"],"curatore":["italian"],"cursore":["italian"],"curvo":["italian"],"cuscino":["italian"],"custode":["italian"],"dado":["italian"],"daino":["italian"],"dalmata":["italian"],"damerino":["italian"],"daniela":["italian"],"dannoso":["italian"],"danzare":["italian"],"datato":["italian"],"davanti":["italian"],"davvero":["italian"],"debutto":["italian"],"decennio":["italian"],"deciso":["italian"],"declino":["italian"],"decollo":["italian"],"decreto":["italian"],"dedicato":["italian"],"definito":["italian"],"deforme":["italian"],"degno":["italian"],"delegare":["italian"],"delfino":["italian"],"delirio":["italian"],"delta":["italian"],"demenza":["italian"],"denotato":["italian"],"dentro":["italian"],"deposito":["italian"],"derapata":["italian"],"derivare":["italian"],"deroga":["italian"],"descritto":["italian"],"deserto":["italian"],"desiderio":["italian"],"desumere":["italian"],"detersivo":["italian"],"devoto":["italian"],"diametro":["italian"],"dicembre":["italian"],"diedro":["italian"],"difeso":["italian"],"diffuso":["italian"],"digerire":["italian"],"digitale":["italian"],"diluvio":["italian"],"dinamico":["italian"],"dinnanzi":["italian"],"dipinto":["italian"],"diploma":["italian"],"dipolo":["italian"],"diradare":["italian"],"dire":["italian"],"dirotto":["italian"],"dirupo":["italian"],"disagio":["italian"],"discreto":["italian"],"disfare":["italian"],"disgelo":["italian"],"disposto":["italian"],"distanza":["italian"],"disumano":["italian"],"dito":["italian"],"divano":["italian"],"divelto":["italian"],"dividere":["italian"],"divorato":["italian"],"doblone":["italian"],"docente":["italian"],"doganale":["italian"],"dogma":["italian"],"dolce":["italian"],"domato":["italian"],"domenica":["italian"],"dominare":["italian"],"dondolo":["italian"],"dono":["italian"],"dormire":["italian"],"dote":["italian"],"dottore":["italian"],"dovuto":["italian"],"dozzina":["italian"],"drago":["italian"],"druido":["italian"],"dubbio":["italian"],"dubitare":["italian"],"ducale":["italian"],"duna":["italian"],"duomo":["italian"],"duplice":["italian"],"duraturo":["italian"],"ebano":["italian"],"eccesso":["italian"],"ecco":["italian"],"eclissi":["italian"],"economia":["italian"],"edera":["italian"],"edicola":["italian"],"edile":["italian"],"editoria":["italian"],"educare":["italian"],"egemonia":["italian"],"egli":["italian"],"egoismo":["italian"],"egregio":["italian"],"elaborato":["italian"],"elargire":["italian"],"elegante":["italian"],"elencato":["italian"],"eletto":["italian"],"elevare":["italian"],"elfico":["italian"],"elica":["italian"],"elmo":["italian"],"elsa":["italian"],"eluso":["italian"],"emanato":["italian"],"emblema":["italian"],"emesso":["italian"],"emiro":["italian"],"emotivo":["italian"],"emozione":["italian"],"empirico":["italian"],"emulo":["italian"],"endemico":["italian"],"enduro":["italian"],"energia":["italian"],"enfasi":["italian"],"enoteca":["italian"],"entrare":["italian"],"enzima":["italian"],"epatite":["italian"],"epilogo":["italian"],"episodio":["italian"],"epocale":["italian"],"eppure":["italian"],"equatore":["italian"],"erario":["italian"],"erba":["italian"],"erboso":["italian"],"erede":["italian"],"eremita":["italian"],"erigere":["italian"],"ermetico":["italian"],"eroe":["italian"],"erosivo":["italian"],"errante":["italian"],"esagono":["italian"],"esame":["italian"],"esanime":["italian"],"esaudire":["italian"],"esca":["italian"],"esempio":["italian"],"esercito":["italian"],"esibito":["italian"],"esigente":["italian"],"esistere":["italian"],"esito":["italian"],"esofago":["italian"],"esortato":["italian"],"esoso":["italian"],"espanso":["italian"],"espresso":["italian"],"essenza":["italian"],"esso":["italian"],"esteso":["italian"],"estimare":["italian"],"estonia":["italian"],"estroso":["italian"],"esultare":["italian"],"etilico":["italian"],"etnico":["italian"],"etrusco":["italian"],"etto":["italian"],"euclideo":["italian"],"europa":["italian"],"evaso":["italian"],"evidenza":["italian"],"evitato":["italian"],"evoluto":["italian"],"evviva":["italian"],"fabbrica":["italian"],"faccenda":["italian"],"fachiro":["italian"],"falco":["italian"],"famiglia":["italian"],"fanale":["italian"],"fanfara":["italian"],"fango":["italian"],"fantasma":["italian"],"fare":["italian"],"farfalla":["italian"],"farinoso":["italian"],"farmaco":["italian"],"fascia":["italian"],"fastoso":["italian"],"fasullo":["italian"],"faticare":["italian"],"fato":["italian"],"favoloso":["italian"],"febbre":["italian"],"fecola":["italian"],"fede":["italian"],"fegato":["italian"],"felpa":["italian"],"feltro":["italian"],"femmina":["italian"],"fendere":["italian"],"fenomeno":["italian"],"fermento":["italian"],"ferro":["italian"],"fertile":["italian"],"fessura":["italian"],"festivo":["italian"],"fetta":["italian"],"feudo":["italian"],"fiaba":["italian"],"fiducia":["italian"],"fifa":["italian"],"figurato":["italian"],"filo":["italian","turkish"],"finanza":["italian"],"finestra":["italian"],"finire":["italian"],"fiore":["italian"],"fiscale":["italian"],"fisico":["italian"],"fiume":["italian"],"flacone":["italian"],"flamenco":["italian"],"flebo":["italian"],"flemma":["italian"],"florido":["italian"],"fluente":["italian"],"fluoro":["italian"],"fobico":["italian"],"focaccia":["italian"],"focoso":["italian"],"foderato":["italian"],"foglio":["italian"],"folata":["italian"],"folclore":["italian"],"folgore":["italian"],"fondente":["italian"],"fonetico":["italian"],"fonia":["italian"],"fontana":["italian"],"forbito":["italian"],"forchetta":["italian"],"foresta":["italian"],"formica":["italian"],"fornaio":["italian"],"foro":["italian"],"fortezza":["italian"],"forzare":["italian"],"fosfato":["italian"],"fosso":["italian"],"fracasso":["italian"],"frana":["italian"],"frassino":["italian"],"fratello":["italian"],"freccetta":["italian"],"frenata":["italian"],"fresco":["italian"],"frigo":["italian"],"frollino":["italian"],"fronde":["italian"],"frugale":["italian"],"frutta":["italian"],"fucilata":["italian"],"fucsia":["italian"],"fuggente":["italian"],"fulmine":["italian"],"fulvo":["italian"],"fumante":["italian"],"fumetto":["italian"],"fumoso":["italian"],"fune":["italian"],"funzione":["italian"],"fuoco":["italian"],"furbo":["italian"],"furgone":["italian"],"furore":["italian"],"fuso":["italian"],"futile":["italian"],"gabbiano":["italian"],"gaffe":["italian"],"galateo":["italian"],"gallina":["italian"],"galoppo":["italian"],"gambero":["italian"],"gamma":["italian"],"garanzia":["italian"],"garbo":["italian"],"garofano":["italian"],"garzone":["italian"],"gasdotto":["italian"],"gasolio":["italian"],"gastrico":["italian"],"gatto":["italian"],"gaudio":["italian"],"gazebo":["italian"],"gazzella":["italian"],"geco":["italian"],"gelatina":["italian"],"gelso":["italian"],"gemello":["italian"],"gemmato":["italian"],"gene":["italian"],"genitore":["italian"],"gennaio":["italian"],"genotipo":["italian"],"gergo":["italian"],"ghepardo":["italian"],"ghiaccio":["italian"],"ghisa":["italian"],"giallo":["italian"],"gilda":["italian"],"ginepro":["italian"],"giocare":["italian"],"gioiello":["italian"],"giorno":["italian"],"giove":["italian"],"girato":["italian"],"girone":["italian"],"gittata":["italian"],"giudizio":["italian"],"giurato":["italian"],"giusto":["italian"],"globulo":["italian"],"glutine":["italian"],"gnomo":["italian"],"gobba":["italian"],"golf":["italian"],"gomito":["italian"],"gommone":["italian"],"gonfio":["italian"],"gonna":["italian"],"governo":["italian"],"gracile":["italian"],"grado":["italian"],"grafico":["italian"],"grammo":["italian"],"grande":["italian"],"grattare":["italian"],"gravoso":["italian"],"grazia":["italian"],"greca":["italian"],"gregge":["italian"],"grifone":["italian"],"grigio":["italian"],"grinza":["italian"],"grotta":["italian"],"gruppo":["italian"],"guadagno":["italian"],"guaio":["italian"],"guanto":["italian"],"guardare":["italian"],"gufo":["italian"],"guidare":["italian"],"ibernato":["italian"],"icona":["italian"],"identico":["italian"],"idillio":["italian"],"idolo":["italian"],"idra":["italian"],"idrico":["italian"],"idrogeno":["italian"],"igiene":["italian"],"ignaro":["italian"],"ignorato":["italian"],"ilare":["italian"],"illeso":["italian"],"illogico":["italian"],"illudere":["italian"],"imballo":["italian"],"imbevuto":["italian"],"imbocco":["italian"],"imbuto":["italian"],"immane":["italian"],"immerso":["italian"],"immolato":["italian"],"impacco":["italian"],"impeto":["italian"],"impiego":["italian"],"importo":["italian"],"impronta":["italian"],"inalare":["italian"],"inarcare":["italian"],"inattivo":["italian"],"incanto":["italian"],"incendio":["italian"],"inchino":["italian"],"incisivo":["italian"],"incluso":["italian"],"incontro":["italian"],"incrocio":["italian"],"incubo":["italian"],"indagine":["italian"],"india":["italian"],"indole":["italian"],"inedito":["italian"],"infatti":["italian"],"infilare":["italian"],"inflitto":["italian"],"ingaggio":["italian"],"ingegno":["italian"],"inglese":["italian"],"ingordo":["italian"],"ingrosso":["italian"],"innesco":["italian"],"inodore":["italian"],"inoltrare":["italian"],"inondato":["italian"],"insano":["italian"],"insetto":["italian"],"insieme":["italian"],"insonnia":["italian"],"insulina":["italian"],"intasato":["italian"],"intero":["italian"],"intonaco":["italian"],"intuito":["italian"],"inumidire":["italian"],"invalido":["italian"],"invece":["italian"],"invito":["italian"],"iperbole":["italian"],"ipnotico":["italian"],"ipotesi":["italian"],"ippica":["italian"],"iride":["italian"],"irlanda":["italian"],"ironico":["italian"],"irrigato":["italian"],"irrorare":["italian"],"isolato":["italian"],"isotopo":["italian"],"isterico":["italian"],"istituto":["italian"],"istrice":["italian"],"italia":["italian"],"iterare":["italian"],"labbro":["italian"],"labirinto":["italian"],"lacca":["italian"],"lacerato":["italian"],"lacrima":["italian"],"lacuna":["italian"],"laddove":["italian"],"lago":["italian"],"lampo":["italian"],"lancetta":["italian"],"lanterna":["italian"],"lardoso":["italian"],"larga":["italian"],"laringe":["italian"],"lastra":["italian"],"latenza":["italian"],"latino":["italian"],"lattuga":["italian"],"lavagna":["italian"],"lavoro":["italian"],"legale":["italian"],"leggero":["italian"],"lembo":["italian"],"lentezza":["italian"],"lenza":["italian"],"leone":["italian"],"lepre":["italian"],"lesivo":["italian"],"lessato":["italian"],"lesto":["italian"],"letterale":["italian"],"leva":["italian"],"levigato":["italian"],"libero":["italian"],"lido":["italian"],"lievito":["italian"],"lilla":["italian"],"limatura":["italian"],"limitare":["italian"],"limpido":["italian"],"lineare":["italian"],"lingua":["italian"],"liquido":["italian"],"lira":["italian"],"lirica":["italian"],"lisca":["italian"],"lite":["italian"],"litigio":["italian"],"livrea":["italian"],"locanda":["italian"],"lode":["italian"],"logica":["italian"],"lombare":["italian"],"londra":["italian"],"longevo":["italian"],"loquace":["italian"],"lorenzo":["italian"],"loto":["italian"],"lotteria":["italian"],"luce":["italian"],"lucidato":["italian"],"lumaca":["italian"],"luminoso":["italian"],"lungo":["italian"],"lupo":["italian"],"luppolo":["italian"],"lusinga":["italian"],"lusso":["italian"],"lutto":["italian"],"macabro":["italian"],"macchina":["italian"],"macero":["italian"],"macinato":["italian"],"madama":["italian"],"magico":["italian"],"maglia":["italian"],"magnete":["italian"],"magro":["italian"],"maiolica":["italian"],"malafede":["italian"],"malgrado":["italian"],"malinteso":["italian"],"malsano":["italian"],"malto":["italian"],"malumore":["italian"],"mana":["italian"],"mancia":["italian"],"mandorla":["italian"],"mangiare":["italian"],"manifesto":["italian"],"mannaro":["italian"],"manovra":["italian"],"mansarda":["italian"],"mantide":["italian"],"manubrio":["italian"],"mappa":["italian"],"maratona":["italian"],"marcire":["italian"],"maretta":["italian"],"marmo":["italian"],"marsupio":["italian"],"maschera":["italian"],"massaia":["italian"],"mastino":["italian"],"materasso":["italian"],"matricola":["italian"],"mattone":["italian"],"maturo":["italian"],"mazurca":["italian"],"meandro":["italian"],"meccanico":["italian"],"mecenate":["italian"],"medesimo":["italian"],"meditare":["italian"],"mega":["italian"],"melassa":["italian"],"melis":["italian"],"melodia":["italian"],"meninge":["italian"],"meno":["italian"],"mensola":["italian"],"mercurio":["italian"],"merenda":["italian"],"merlo":["italian"],"meschino":["italian"],"mese":["italian"],"messere":["italian"],"mestolo":["italian"],"metallo":["italian"],"metodo":["italian"],"mettere":["italian"],"miagolare":["italian"],"mica":["italian"],"micelio":["italian"],"michele":["italian"],"microbo":["italian"],"midollo":["italian"],"miele":["italian"],"migliore":["italian"],"milano":["italian"],"milite":["italian"],"mimosa":["italian"],"minerale":["italian"],"mini":["italian"],"minore":["italian"],"mirino":["italian"],"mirtillo":["italian"],"miscela":["italian"],"missiva":["italian"],"misto":["italian"],"misurare":["italian"],"mitezza":["italian"],"mitigare":["italian"],"mitra":["italian"],"mittente":["italian"],"mnemonico":["italian"],"modello":["italian"],"modifica":["italian"],"modulo":["italian"],"mogano":["italian"],"mogio":["italian"],"mole":["italian"],"molosso":["italian"],"monastero":["italian"],"monco":["italian"],"mondina":["italian"],"monetario":["italian"],"monile":["italian"],"monotono":["italian"],"monsone":["italian"],"montato":["italian"],"monviso":["italian"],"mora":["italian"],"mordere":["italian"],"morsicato":["italian"],"mostro":["italian"],"motivato":["italian"],"motosega":["italian"],"motto":["italian"],"movenza":["italian"],"movimento":["italian"],"mozzo":["italian"],"mucca":["italian"],"mucosa":["italian"],"muffa":["italian"],"mughetto":["italian"],"mugnaio":["italian"],"mulatto":["italian"],"mulinello":["italian"],"multiplo":["italian"],"mummia":["italian"],"munto":["italian"],"muovere":["italian"],"murale":["italian"],"musa":["italian"],"muscolo":["italian"],"musica":["italian"],"mutevole":["italian"],"muto":["italian"],"nababbo":["italian"],"nafta":["italian"],"nanometro":["italian"],"narciso":["italian"],"narice":["italian"],"narrato":["italian"],"nascere":["italian"],"nastrare":["italian"],"naturale":["italian"],"nautica":["italian"],"naviglio":["italian"],"nebulosa":["italian"],"necrosi":["italian"],"negativo":["italian"],"negozio":["italian"],"nemmeno":["italian"],"neofita":["italian"],"neretto":["italian"],"nervo":["italian"],"nessuno":["italian"],"nettuno":["italian"],"neutrale":["italian"],"neve":["italian"],"nevrotico":["italian"],"nicchia":["italian"],"ninfa":["italian"],"nitido":["italian"],"nobile":["italian"],"nocivo":["italian"],"nodo":["italian"],"nome":["italian"],"nomina":["italian"],"nordico":["italian"],"normale":["italian"],"norvegese":["italian"],"nostrano":["italian"],"notare":["italian"],"notizia":["italian"],"notturno":["italian"],"novella":["italian"],"nucleo":["italian"],"nulla":["italian"],"numero":["italian"],"nuovo":["italian"],"nutrire":["italian"],"nuvola":["italian"],"nuziale":["italian"],"oasi":["italian"],"obbedire":["italian"],"obbligo":["italian"],"obelisco":["italian"],"oblio":["italian"],"obolo":["italian"],"obsoleto":["italian"],"occasione":["italian"],"occhio":["italian"],"occidente":["italian"],"occorrere":["italian"],"occultare":["italian"],"ocra":["italian"],"oculato":["italian"],"odierno":["italian"],"odorare":["italian"],"offerta":["italian"],"offrire":["italian"],"offuscato":["italian"],"oggetto":["italian"],"oggi":["italian"],"ognuno":["italian"],"olandese":["italian"],"olfatto":["italian"],"oliato":["italian"],"oliva":["italian"],"ologramma":["italian"],"oltre":["italian"],"omaggio":["italian"],"ombelico":["italian"],"ombra":["italian"],"omega":["italian"],"omissione":["italian"],"ondoso":["italian"],"onere":["italian"],"onice":["italian"],"onnivoro":["italian"],"onorevole":["italian"],"onta":["italian"],"operato":["italian"],"opinione":["italian"],"opposto":["italian"],"oracolo":["italian"],"orafo":["italian"],"ordine":["italian"],"orecchino":["italian"],"orefice":["italian"],"orfano":["italian"],"organico":["italian"],"origine":["italian"],"orizzonte":["italian"],"orma":["italian"],"ormeggio":["italian"],"ornativo":["italian"],"orologio":["italian"],"orrendo":["italian"],"orribile":["italian"],"ortensia":["italian"],"ortica":["italian"],"orzata":["italian"],"orzo":["italian"],"osare":["italian"],"oscurare":["italian"],"osmosi":["italian"],"ospedale":["italian"],"ospite":["italian"],"ossa":["italian"],"ossidare":["italian"],"ostacolo":["italian"],"oste":["italian"],"otite":["italian"],"otre":["italian"],"ottagono":["italian"],"ottimo":["italian"],"ottobre":["italian"],"ovale":["italian"],"ovest":["italian"],"ovino":["italian"],"oviparo":["italian"],"ovocito":["italian"],"ovunque":["italian"],"ovviare":["italian"],"ozio":["italian"],"pacchetto":["italian"],"pace":["italian"],"pacifico":["italian"],"padella":["italian"],"padrone":["italian"],"paese":["italian"],"paga":["italian"],"pagina":["italian"],"palazzina":["italian"],"palesare":["italian"],"pallido":["italian"],"palo":["italian"],"palude":["italian"],"pandoro":["italian"],"pannello":["italian"],"paolo":["italian"],"paonazzo":["italian"],"paprica":["italian"],"parabola":["italian"],"parcella":["italian"],"parere":["italian"],"pargolo":["italian"],"pari":["italian"],"parlato":["italian"],"parola":["italian"],"partire":["italian"],"parvenza":["italian"],"parziale":["italian"],"passivo":["italian"],"pasticca":["italian"],"patacca":["italian"],"patologia":["italian"],"pattume":["italian"],"pavone":["italian"],"peccato":["italian"],"pedalare":["italian"],"pedonale":["italian"],"peggio":["italian"],"peloso":["italian"],"penare":["italian"],"pendice":["italian"],"penisola":["italian"],"pennuto":["italian"],"penombra":["italian"],"pensare":["italian"],"pentola":["italian"],"pepe":["italian"],"pepita":["italian"],"perbene":["italian"],"percorso":["italian"],"perdonato":["italian"],"perforare":["italian"],"pergamena":["italian"],"periodo":["italian"],"permesso":["italian"],"perno":["italian"],"perplesso":["italian"],"persuaso":["italian"],"pertugio":["italian"],"pervaso":["italian"],"pesatore":["italian"],"pesista":["italian"],"peso":["italian"],"pestifero":["italian"],"petalo":["italian"],"pettine":["italian"],"petulante":["italian"],"pezzo":["italian"],"piacere":["italian"],"pianta":["italian"],"piattino":["italian"],"piccino":["italian"],"picozza":["italian"],"piega":["italian"],"pietra":["italian"],"piffero":["italian"],"pigiama":["italian"],"pigolio":["italian"],"pigro":["italian"],"pila":["italian"],"pilifero":["italian"],"pillola":["italian"],"pilota":["italian"],"pimpante":["italian"],"pineta":["italian"],"pinna":["italian"],"pinolo":["italian"],"pioggia":["italian"],"piombo":["italian"],"piramide":["italian"],"piretico":["italian"],"pirite":["italian"],"pirolisi":["italian"],"pitone":["italian"],"pizzico":["italian"],"placebo":["italian"],"planare":["italian"],"plasma":["italian"],"platano":["italian"],"plenario":["italian"],"pochezza":["italian"],"poderoso":["italian"],"podismo":["italian"],"poesia":["italian"],"poggiare":["italian"],"polenta":["italian"],"poligono":["italian"],"pollice":["italian"],"polmonite":["italian"],"polpetta":["italian"],"polso":["italian"],"poltrona":["italian"],"polvere":["italian"],"pomice":["italian"],"pomodoro":["italian"],"ponte":["italian"],"popoloso":["italian"],"porfido":["italian"],"poroso":["italian"],"porpora":["italian"],"porre":["italian"],"portata":["italian"],"posa":["italian","turkish"],"positivo":["italian"],"possesso":["italian"],"postulato":["italian"],"potassio":["italian"],"potere":["italian"],"pranzo":["italian"],"prassi":["italian"],"pratica":["italian"],"precluso":["italian"],"predica":["italian"],"prefisso":["italian"],"pregiato":["italian"],"prelievo":["italian"],"premere":["italian"],"prenotare":["italian"],"preparato":["italian"],"presenza":["italian"],"pretesto":["italian"],"prevalso":["italian"],"prima":["italian"],"principe":["italian"],"privato":["italian"],"problema":["italian"],"procura":["italian"],"produrre":["italian"],"profumo":["italian"],"progetto":["italian"],"prolunga":["italian"],"promessa":["italian"],"pronome":["italian"],"proposta":["italian"],"proroga":["italian"],"proteso":["italian"],"prova":["italian","turkish"],"prudente":["italian"],"prugna":["italian"],"prurito":["italian"],"psiche":["italian"],"pubblico":["italian"],"pudica":["italian"],"pugilato":["italian"],"pugno":["italian"],"pulce":["italian"],"pulito":["italian"],"pulsante":["italian"],"puntare":["italian"],"pupazzo":["italian"],"pupilla":["italian"],"puro":["italian"],"quadro":["italian"],"qualcosa":["italian"],"quasi":["italian"],"querela":["italian"],"quota":["italian"],"raccolto":["italian"],"raddoppio":["italian"],"radicale":["italian"],"radunato":["italian"],"raffica":["italian"],"ragazzo":["italian"],"ragione":["italian"],"ragno":["italian"],"ramarro":["italian"],"ramingo":["italian"],"ramo":["italian"],"randagio":["italian"],"rantolare":["italian"],"rapato":["italian"],"rapina":["italian"],"rappreso":["italian"],"rasatura":["italian"],"raschiato":["italian"],"rasente":["italian"],"rassegna":["italian"],"rastrello":["italian"],"rata":["italian"],"ravveduto":["italian"],"reale":["italian"],"recepire":["italian"],"recinto":["italian"],"recluta":["italian"],"recondito":["italian"],"recupero":["italian"],"reddito":["italian"],"redimere":["italian"],"regalato":["italian"],"registro":["italian"],"regola":["italian"],"regresso":["italian"],"relazione":["italian"],"remare":["italian"],"remoto":["italian"],"renna":["italian"],"replica":["italian"],"reprimere":["italian"],"reputare":["italian"],"resa":["italian"],"residente":["italian"],"responso":["italian"],"restauro":["italian"],"rete":["italian"],"retina":["italian"],"retorica":["italian"],"rettifica":["italian"],"revocato":["italian"],"riassunto":["italian"],"ribadire":["italian"],"ribelle":["italian"],"ribrezzo":["italian"],"ricarica":["italian"],"ricco":["italian"],"ricevere":["italian"],"riciclato":["italian"],"ricordo":["italian"],"ricreduto":["italian"],"ridicolo":["italian"],"ridurre":["italian"],"rifasare":["italian"],"riflesso":["italian"],"riforma":["italian"],"rifugio":["italian"],"rigare":["italian"],"rigettato":["italian"],"righello":["italian"],"rilassato":["italian"],"rilevato":["italian"],"rimanere":["italian"],"rimbalzo":["italian"],"rimedio":["italian"],"rimorchio":["italian"],"rinascita":["italian"],"rincaro":["italian"],"rinforzo":["italian"],"rinnovo":["italian"],"rinomato":["italian"],"rinsavito":["italian"],"rintocco":["italian"],"rinuncia":["italian"],"rinvenire":["italian"],"riparato":["italian"],"ripetuto":["italian"],"ripieno":["italian"],"riportare":["italian"],"ripresa":["italian"],"ripulire":["italian"],"risata":["italian"],"rischio":["italian"],"riserva":["italian"],"risibile":["italian"],"riso":["italian"],"rispetto":["italian"],"ristoro":["italian"],"risultato":["italian"],"risvolto":["italian"],"ritardo":["italian"],"ritegno":["italian"],"ritmico":["italian"],"ritrovo":["italian"],"riunione":["italian"],"riva":["italian"],"riverso":["italian"],"rivincita":["italian"],"rivolto":["italian"],"rizoma":["italian"],"roba":["italian"],"robotico":["italian"],"robusto":["italian"],"roccia":["italian"],"roco":["italian"],"rodaggio":["italian"],"rodere":["italian"],"roditore":["italian"],"rogito":["italian"],"rollio":["italian"],"romantico":["italian"],"rompere":["italian"],"ronzio":["italian"],"rosolare":["italian"],"rospo":["italian"],"rotante":["italian"],"rotondo":["italian"],"rotula":["italian"],"rovescio":["italian"],"rubizzo":["italian"],"rubrica":["italian"],"ruga":["italian"],"rullino":["italian"],"rumine":["italian"],"rumoroso":["italian"],"ruolo":["italian"],"rupe":["italian"],"russare":["italian"],"rustico":["italian"],"sabato":["italian"],"sabbiare":["italian"],"sabotato":["italian"],"sagoma":["italian"],"salasso":["italian"],"saldatura":["italian"],"salgemma":["italian"],"salivare":["italian"],"salmone":["italian"],"salone":["italian"],"saltare":["italian"],"saluto":["italian"],"salvo":["italian"],"sapere":["italian"],"sapido":["italian"],"saporito":["italian"],"saraceno":["italian"],"sarcasmo":["italian"],"sarto":["italian"],"sassoso":["italian"],"satellite":["italian"],"satira":["italian"],"satollo":["italian"],"saturno":["italian"],"savana":["italian"],"savio":["italian"],"saziato":["italian"],"sbadiglio":["italian"],"sbalzo":["italian"],"sbancato":["italian"],"sbarra":["italian"],"sbattere":["italian"],"sbavare":["italian"],"sbendare":["italian"],"sbirciare":["italian"],"sbloccato":["italian"],"sbocciato":["italian"],"sbrinare":["italian"],"sbruffone":["italian"],"sbuffare":["italian"],"scabroso":["italian"],"scadenza":["italian"],"scala":["italian"],"scambiare":["italian"],"scandalo":["italian"],"scapola":["italian"],"scarso":["italian"],"scatenare":["italian"],"scavato":["italian"],"scelto":["italian"],"scenico":["italian"],"scettro":["italian"],"scheda":["italian"],"schiena":["italian"],"sciarpa":["italian"],"scienza":["italian"],"scindere":["italian"],"scippo":["italian"],"sciroppo":["italian"],"scivolo":["italian"],"sclerare":["italian"],"scodella":["italian"],"scolpito":["italian"],"scomparto":["italian"],"sconforto":["italian"],"scoprire":["italian"],"scorta":["italian"],"scossone":["italian"],"scozzese":["italian"],"scriba":["italian"],"scrollare":["italian"],"scrutinio":["italian"],"scuderia":["italian"],"scultore":["italian"],"scuola":["italian"],"scuro":["italian"],"scusare":["italian"],"sdebitare":["italian"],"sdoganare":["italian"],"seccatura":["italian"],"secondo":["italian"],"sedano":["italian"],"seggiola":["italian"],"segnalato":["italian"],"segregato":["italian"],"seguito":["italian"],"selciato":["italian"],"selettivo":["italian"],"sella":["italian"],"selvaggio":["italian"],"semaforo":["italian"],"sembrare":["italian"],"seme":["italian"],"seminato":["italian"],"sempre":["italian"],"senso":["italian"],"sentire":["italian"],"sepolto":["italian"],"sequenza":["italian"],"serata":["italian"],"serbato":["italian"],"sereno":["italian"],"serio":["italian"],"serpente":["italian"],"serraglio":["italian"],"servire":["italian"],"sestina":["italian"],"setola":["italian"],"settimana":["italian"],"sfacelo":["italian"],"sfaldare":["italian"],"sfamato":["italian"],"sfarzoso":["italian"],"sfaticato":["italian"],"sfera":["italian"],"sfida":["italian"],"sfilato":["italian"],"sfinge":["italian"],"sfocato":["italian"],"sfoderare":["italian"],"sfogo":["italian"],"sfoltire":["italian"],"sforzato":["italian"],"sfratto":["italian"],"sfruttato":["italian"],"sfuggito":["italian"],"sfumare":["italian"],"sfuso":["italian"],"sgabello":["italian"],"sgarbato":["italian"],"sgonfiare":["italian"],"sgorbio":["italian"],"sgrassato":["italian"],"sguardo":["italian"],"sibilo":["italian"],"siccome":["italian"],"sierra":["italian"],"sigla":["italian"],"signore":["italian"],"silenzio":["italian"],"sillaba":["italian"],"simbolo":["italian"],"simpatico":["italian"],"simulato":["italian"],"sinfonia":["italian"],"singolo":["italian"],"sinistro":["italian"],"sino":["italian"],"sintesi":["italian"],"sinusoide":["italian"],"sipario":["italian"],"sisma":["italian"],"sistole":["italian"],"situato":["italian"],"slitta":["italian"],"slogatura":["italian"],"sloveno":["italian"],"smarrito":["italian"],"smemorato":["italian"],"smentito":["italian"],"smeraldo":["italian"],"smilzo":["italian"],"smontare":["italian"],"smottato":["italian"],"smussato":["italian"],"snellire":["italian"],"snervato":["italian"],"snodo":["italian"],"sobbalzo":["italian"],"sobrio":["italian"],"soccorso":["italian"],"sociale":["italian"],"sodale":["italian"],"soffitto":["italian"],"sogno":["italian"],"soldato":["italian"],"solenne":["italian"],"solido":["italian"],"sollazzo":["italian"],"solo":["italian"],"solubile":["italian"],"solvente":["italian"],"somatico":["italian"],"somma":["italian"],"sonda":["italian"],"sonetto":["italian"],"sonnifero":["italian"],"sopire":["italian"],"soppeso":["italian"],"sopra":["italian"],"sorgere":["italian"],"sorpasso":["italian"],"sorriso":["italian"],"sorso":["italian"],"sorteggio":["italian"],"sorvolato":["italian"],"sospiro":["italian"],"sosta":["italian"],"sottile":["italian"],"spada":["italian"],"spalla":["italian"],"spargere":["italian"],"spatola":["italian"],"spavento":["italian"],"spazzola":["italian"],"specie":["italian"],"spedire":["italian"],"spegnere":["italian"],"spelatura":["italian"],"speranza":["italian"],"spessore":["italian"],"spettrale":["italian"],"spezzato":["italian"],"spia":["italian"],"spigoloso":["italian"],"spillato":["italian"],"spinoso":["italian"],"spirale":["italian"],"splendido":["italian"],"sportivo":["italian"],"sposo":["italian"],"spranga":["italian"],"sprecare":["italian"],"spronato":["italian"],"spruzzo":["italian"],"spuntino":["italian"],"squillo":["italian"],"sradicare":["italian"],"srotolato":["italian"],"stabile":["italian"],"stacco":["italian"],"staffa":["italian"],"stagnare":["italian"],"stampato":["italian"],"stantio":["italian"],"starnuto":["italian"],"stasera":["italian"],"statuto":["italian"],"stelo":["italian"],"steppa":["italian"],"sterzo":["italian"],"stiletto":["italian"],"stima":["italian"],"stirpe":["italian"],"stivale":["italian"],"stizzoso":["italian"],"stonato":["italian"],"storico":["italian"],"strappo":["italian"],"stregato":["italian"],"stridulo":["italian"],"strozzare":["italian"],"strutto":["italian"],"stuccare":["italian"],"stufo":["italian"],"stupendo":["italian"],"subentro":["italian"],"succoso":["italian"],"sudore":["italian"],"suggerito":["italian"],"sugo":["italian"],"sultano":["italian"],"suonare":["italian"],"superbo":["italian"],"supporto":["italian"],"surgelato":["italian"],"surrogato":["italian"],"sussurro":["italian"],"sutura":["italian"],"svagare":["italian"],"svedese":["italian"],"sveglio":["italian"],"svelare":["italian"],"svenuto":["italian"],"svezia":["italian"],"sviluppo":["italian"],"svista":["italian"],"svizzera":["italian"],"svolta":["italian"],"svuotare":["italian"],"tabacco":["italian"],"tabulato":["italian"],"tacciare":["italian"],"taciturno":["italian"],"tale":["italian"],"talismano":["italian"],"tampone":["italian"],"tannino":["italian"],"tara":["italian"],"tardivo":["italian"],"targato":["italian"],"tariffa":["italian"],"tarpare":["italian"],"tartaruga":["italian"],"tasto":["italian"],"tattico":["italian"],"taverna":["italian"],"tavolata":["italian"],"tazza":["italian"],"teca":["italian"],"tecnico":["italian"],"telefono":["italian"],"temerario":["italian"],"tempo":["italian","turkish"],"temuto":["italian"],"tendone":["italian"],"tenero":["italian"],"tensione":["italian"],"tentacolo":["italian"],"teorema":["italian"],"terme":["italian"],"terrazzo":["italian"],"terzetto":["italian"],"tesi":["italian"],"tesserato":["italian"],"testato":["italian"],"tetro":["italian"],"tettoia":["italian"],"tifare":["italian"],"tigella":["italian"],"timbro":["italian"],"tinto":["italian"],"tipico":["italian"],"tipografo":["italian"],"tiraggio":["italian"],"tiro":["italian"],"titanio":["italian"],"titolo":["italian"],"titubante":["italian"],"tizio":["italian"],"tizzone":["italian"],"toccare":["italian"],"tollerare":["italian"],"tolto":["italian"],"tombola":["italian"],"tomo":["italian"],"tonfo":["italian"],"tonsilla":["italian"],"topazio":["italian"],"topologia":["italian"],"toppa":["italian"],"torba":["italian"],"tornare":["italian"],"torrone":["italian"],"tortora":["italian"],"toscano":["italian"],"tossire":["italian"],"tostatura":["italian"],"totano":["italian"],"trabocco":["italian"],"trachea":["italian"],"trafila":["italian"],"tragedia":["italian"],"tralcio":["italian"],"tramonto":["italian"],"transito":["italian"],"trapano":["italian"],"trarre":["italian"],"trasloco":["italian"],"trattato":["italian"],"trave":["italian"],"treccia":["italian"],"tremolio":["italian"],"trespolo":["italian"],"tributo":["italian"],"tricheco":["italian"],"trifoglio":["italian"],"trillo":["italian"],"trincea":["italian"],"trio":["italian"],"tristezza":["italian"],"triturato":["italian"],"trivella":["italian"],"tromba":["italian"],"trono":["italian"],"troppo":["italian"],"trottola":["italian"],"trovare":["italian"],"truccato":["italian"],"tubatura":["italian"],"tuffato":["italian"],"tulipano":["italian"],"tumulto":["italian"],"tunisia":["italian"],"turbare":["italian"],"turchino":["italian"],"tuta":["italian"],"tutela":["italian"],"ubicato":["italian"],"uccello":["italian"],"uccisore":["italian"],"udire":["italian"],"uditivo":["italian"],"uffa":["italian"],"ufficio":["italian"],"uguale":["italian"],"ulisse":["italian"],"ultimato":["italian"],"umano":["italian"],"umile":["italian"],"umorismo":["italian"],"uncinetto":["italian"],"ungere":["italian"],"ungherese":["italian"],"unicorno":["italian"],"unificato":["italian"],"unisono":["italian"],"unitario":["italian"],"unte":["italian"],"uovo":["italian"],"upupa":["italian"],"uragano":["italian"],"urgenza":["italian"],"urlo":["italian"],"usanza":["italian"],"usato":["italian"],"uscito":["italian"],"usignolo":["italian"],"usuraio":["italian"],"utensile":["italian"],"utilizzo":["italian"],"utopia":["italian"],"vacante":["italian"],"vaccinato":["italian"],"vagabondo":["italian"],"vagliato":["italian"],"valanga":["italian"],"valgo":["italian"],"valico":["italian"],"valletta":["italian"],"valoroso":["italian"],"valutare":["italian"],"valvola":["italian"],"vampata":["italian"],"vangare":["italian"],"vanitoso":["italian"],"vano":["italian"],"vantaggio":["italian"],"vanvera":["italian"],"vapore":["italian"],"varano":["italian"],"varcato":["italian"],"variante":["italian"],"vasca":["italian"],"vedetta":["italian"],"vedova":["italian"],"veduto":["italian"],"vegetale":["italian"],"veicolo":["italian"],"velcro":["italian"],"velina":["italian"],"velluto":["italian"],"veloce":["italian"],"venato":["italian"],"vendemmia":["italian"],"vento":["italian"],"verace":["italian"],"verbale":["italian"],"vergogna":["italian"],"verifica":["italian"],"vero":["italian"],"verruca":["italian"],"verticale":["italian"],"vescica":["italian"],"vessillo":["italian"],"vestale":["italian"],"veterano":["italian"],"vetrina":["italian"],"vetusto":["italian"],"viandante":["italian"],"vibrante":["italian"],"vicenda":["italian"],"vichingo":["italian"],"vicinanza":["italian"],"vidimare":["italian"],"vigilia":["italian"],"vigneto":["italian"],"vigore":["italian"],"vile":["italian"],"villano":["italian"],"vimini":["italian"],"vincitore":["italian"],"viola":["italian"],"vipera":["italian"],"virgola":["italian"],"virologo":["italian"],"virulento":["italian"],"viscoso":["italian"],"visione":["italian"],"vispo":["italian"],"vissuto":["italian"],"visura":["italian"],"vita":["italian"],"vitello":["italian"],"vittima":["italian"],"vivanda":["italian"],"vivido":["italian"],"viziare":["italian"],"voce":["italian"],"voga":["italian"],"volatile":["italian"],"volere":["italian"],"volpe":["italian"],"voragine":["italian"],"vulcano":["italian"],"zampogna":["italian"],"zanna":["italian"],"zappato":["italian"],"zattera":["italian"],"zavorra":["italian"],"zefiro":["italian"],"zelante":["italian"],"zelo":["italian"],"zenzero":["italian"],"zerbino":["italian"],"zibetto":["italian"],"zinco":["italian"],"zircone":["italian"],"zitto":["italian"],"zolla":["italian"],"zotico":["italian"],"zucchero":["italian"],"zufolo":["italian"],"zulu":["italian"],"zuppa":["italian"],"あいこくしん":["japanese"],"あいさつ":["japanese"],"あいだ":["japanese"],"あおぞら":["japanese"],"あかちゃん":["japanese"],"あきる":["japanese"],"あけがた":["japanese"],"あける":["japanese"],"あこがれる":["japanese"],"あさい":["japanese"],"あさひ":["japanese"],"あしあと":["japanese"],"あじわう":["japanese"],"あずかる":["japanese"],"あずき":["japanese"],"あそぶ":["japanese"],"あたえる":["japanese"],"あたためる":["japanese"],"あたりまえ":["japanese"],"あたる":["japanese"],"あつい":["japanese"],"あつかう":["japanese"],"あっしゅく":["japanese"],"あつまり":["japanese"],"あつめる":["japanese"],"あてな":["japanese"],"あてはまる":["japanese"],"あひる":["japanese"],"あぶら":["japanese"],"あぶる":["japanese"],"あふれる":["japanese"],"あまい":["japanese"],"あまど":["japanese"],"あまやかす":["japanese"],"あまり":["japanese"],"あみもの":["japanese"],"あめりか":["japanese"],"あやまる":["japanese"],"あゆむ":["japanese"],"あらいぐま":["japanese"],"あらし":["japanese"],"あらすじ":["japanese"],"あらためる":["japanese"],"あらゆる":["japanese"],"あらわす":["japanese"],"ありがとう":["japanese"],"あわせる":["japanese"],"あわてる":["japanese"],"あんい":["japanese"],"あんがい":["japanese"],"あんこ":["japanese"],"あんぜん":["japanese"],"あんてい":["japanese"],"あんない":["japanese"],"あんまり":["japanese"],"いいだす":["japanese"],"いおん":["japanese"],"いがい":["japanese"],"いがく":["japanese"],"いきおい":["japanese"],"いきなり":["japanese"],"いきもの":["japanese"],"いきる":["japanese"],"いくじ":["japanese"],"いくぶん":["japanese"],"いけばな":["japanese"],"いけん":["japanese"],"いこう":["japanese"],"いこく":["japanese"],"いこつ":["japanese"],"いさましい":["japanese"],"いさん":["japanese"],"いしき":["japanese"],"いじゅう":["japanese"],"いじょう":["japanese"],"いじわる":["japanese"],"いずみ":["japanese"],"いずれ":["japanese"],"いせい":["japanese"],"いせえび":["japanese"],"いせかい":["japanese"],"いせき":["japanese"],"いぜん":["japanese"],"いそうろう":["japanese"],"いそがしい":["japanese"],"いだい":["japanese"],"いだく":["japanese"],"いたずら":["japanese"],"いたみ":["japanese"],"いたりあ":["japanese"],"いちおう":["japanese"],"いちじ":["japanese"],"いちど":["japanese"],"いちば":["japanese"],"いちぶ":["japanese"],"いちりゅう":["japanese"],"いつか":["japanese"],"いっしゅん":["japanese"],"いっせい":["japanese"],"いっそう":["japanese"],"いったん":["japanese"],"いっち":["japanese"],"いってい":["japanese"],"いっぽう":["japanese"],"いてざ":["japanese"],"いてん":["japanese"],"いどう":["japanese"],"いとこ":["japanese"],"いない":["japanese"],"いなか":["japanese"],"いねむり":["japanese"],"いのち":["japanese"],"いのる":["japanese"],"いはつ":["japanese"],"いばる":["japanese"],"いはん":["japanese"],"いびき":["japanese"],"いひん":["japanese"],"いふく":["japanese"],"いへん":["japanese"],"いほう":["japanese"],"いみん":["japanese"],"いもうと":["japanese"],"いもたれ":["japanese"],"いもり":["japanese"],"いやがる":["japanese"],"いやす":["japanese"],"いよかん":["japanese"],"いよく":["japanese"],"いらい":["japanese"],"いらすと":["japanese"],"いりぐち":["japanese"],"いりょう":["japanese"],"いれい":["japanese"],"いれもの":["japanese"],"いれる":["japanese"],"いろえんぴつ":["japanese"],"いわい":["japanese"],"いわう":["japanese"],"いわかん":["japanese"],"いわば":["japanese"],"いわゆる":["japanese"],"いんげんまめ":["japanese"],"いんさつ":["japanese"],"いんしょう":["japanese"],"いんよう":["japanese"],"うえき":["japanese"],"うえる":["japanese"],"うおざ":["japanese"],"うがい":["japanese"],"うかぶ":["japanese"],"うかべる":["japanese"],"うきわ":["japanese"],"うくらいな":["japanese"],"うくれれ":["japanese"],"うけたまわる":["japanese"],"うけつけ":["japanese"],"うけとる":["japanese"],"うけもつ":["japanese"],"うける":["japanese"],"うごかす":["japanese"],"うごく":["japanese"],"うこん":["japanese"],"うさぎ":["japanese"],"うしなう":["japanese"],"うしろがみ":["japanese"],"うすい":["japanese"],"うすぎ":["japanese"],"うすぐらい":["japanese"],"うすめる":["japanese"],"うせつ":["japanese"],"うちあわせ":["japanese"],"うちがわ":["japanese"],"うちき":["japanese"],"うちゅう":["japanese"],"うっかり":["japanese"],"うつくしい":["japanese"],"うったえる":["japanese"],"うつる":["japanese"],"うどん":["japanese"],"うなぎ":["japanese"],"うなじ":["japanese"],"うなずく":["japanese"],"うなる":["japanese"],"うねる":["japanese"],"うのう":["japanese"],"うぶげ":["japanese"],"うぶごえ":["japanese"],"うまれる":["japanese"],"うめる":["japanese"],"うもう":["japanese"],"うやまう":["japanese"],"うよく":["japanese"],"うらがえす":["japanese"],"うらぐち":["japanese"],"うらない":["japanese"],"うりあげ":["japanese"],"うりきれ":["japanese"],"うるさい":["japanese"],"うれしい":["japanese"],"うれゆき":["japanese"],"うれる":["japanese"],"うろこ":["japanese"],"うわき":["japanese"],"うわさ":["japanese"],"うんこう":["japanese"],"うんちん":["japanese"],"うんてん":["japanese"],"うんどう":["japanese"],"えいえん":["japanese"],"えいが":["japanese"],"えいきょう":["japanese"],"えいご":["japanese"],"えいせい":["japanese"],"えいぶん":["japanese"],"えいよう":["japanese"],"えいわ":["japanese"],"えおり":["japanese"],"えがお":["japanese"],"えがく":["japanese"],"えきたい":["japanese"],"えくせる":["japanese"],"えしゃく":["japanese"],"えすて":["japanese"],"えつらん":["japanese"],"えのぐ":["japanese"],"えほうまき":["japanese"],"えほん":["japanese"],"えまき":["japanese"],"えもじ":["japanese"],"えもの":["japanese"],"えらい":["japanese"],"えらぶ":["japanese"],"えりあ":["japanese"],"えんえん":["japanese"],"えんかい":["japanese"],"えんぎ":["japanese"],"えんげき":["japanese"],"えんしゅう":["japanese"],"えんぜつ":["japanese"],"えんそく":["japanese"],"えんちょう":["japanese"],"えんとつ":["japanese"],"おいかける":["japanese"],"おいこす":["japanese"],"おいしい":["japanese"],"おいつく":["japanese"],"おうえん":["japanese"],"おうさま":["japanese"],"おうじ":["japanese"],"おうせつ":["japanese"],"おうたい":["japanese"],"おうふく":["japanese"],"おうべい":["japanese"],"おうよう":["japanese"],"おえる":["japanese"],"おおい":["japanese"],"おおう":["japanese"],"おおどおり":["japanese"],"おおや":["japanese"],"おおよそ":["japanese"],"おかえり":["japanese"],"おかず":["japanese"],"おがむ":["japanese"],"おかわり":["japanese"],"おぎなう":["japanese"],"おきる":["japanese"],"おくさま":["japanese"],"おくじょう":["japanese"],"おくりがな":["japanese"],"おくる":["japanese"],"おくれる":["japanese"],"おこす":["japanese"],"おこなう":["japanese"],"おこる":["japanese"],"おさえる":["japanese"],"おさない":["japanese"],"おさめる":["japanese"],"おしいれ":["japanese"],"おしえる":["japanese"],"おじぎ":["japanese"],"おじさん":["japanese"],"おしゃれ":["japanese"],"おそらく":["japanese"],"おそわる":["japanese"],"おたがい":["japanese"],"おたく":["japanese"],"おだやか":["japanese"],"おちつく":["japanese"],"おっと":["japanese"],"おつり":["japanese"],"おでかけ":["japanese"],"おとしもの":["japanese"],"おとなしい":["japanese"],"おどり":["japanese"],"おどろかす":["japanese"],"おばさん":["japanese"],"おまいり":["japanese"],"おめでとう":["japanese"],"おもいで":["japanese"],"おもう":["japanese"],"おもたい":["japanese"],"おもちゃ":["japanese"],"おやつ":["japanese"],"おやゆび":["japanese"],"およぼす":["japanese"],"おらんだ":["japanese"],"おろす":["japanese"],"おんがく":["japanese"],"おんけい":["japanese"],"おんしゃ":["japanese"],"おんせん":["japanese"],"おんだん":["japanese"],"おんちゅう":["japanese"],"おんどけい":["japanese"],"かあつ":["japanese"],"かいが":["japanese"],"がいき":["japanese"],"がいけん":["japanese"],"がいこう":["japanese"],"かいさつ":["japanese"],"かいしゃ":["japanese"],"かいすいよく":["japanese"],"かいぜん":["japanese"],"かいぞうど":["japanese"],"かいつう":["japanese"],"かいてん":["japanese"],"かいとう":["japanese"],"かいふく":["japanese"],"がいへき":["japanese"],"かいほう":["japanese"],"かいよう":["japanese"],"がいらい":["japanese"],"かいわ":["japanese"],"かえる":["japanese"],"かおり":["japanese"],"かかえる":["japanese"],"かがく":["japanese"],"かがし":["japanese"],"かがみ":["japanese"],"かくご":["japanese"],"かくとく":["japanese"],"かざる":["japanese"],"がぞう":["japanese"],"かたい":["japanese"],"かたち":["japanese"],"がちょう":["japanese"],"がっきゅう":["japanese"],"がっこう":["japanese"],"がっさん":["japanese"],"がっしょう":["japanese"],"かなざわし":["japanese"],"かのう":["japanese"],"がはく":["japanese"],"かぶか":["japanese"],"かほう":["japanese"],"かほご":["japanese"],"かまう":["japanese"],"かまぼこ":["japanese"],"かめれおん":["japanese"],"かゆい":["japanese"],"かようび":["japanese"],"からい":["japanese"],"かるい":["japanese"],"かろう":["japanese"],"かわく":["japanese"],"かわら":["japanese"],"がんか":["japanese"],"かんけい":["japanese"],"かんこう":["japanese"],"かんしゃ":["japanese"],"かんそう":["japanese"],"かんたん":["japanese"],"かんち":["japanese"],"がんばる":["japanese"],"きあい":["japanese"],"きあつ":["japanese"],"きいろ":["japanese"],"ぎいん":["japanese"],"きうい":["japanese"],"きうん":["japanese"],"きえる":["japanese"],"きおう":["japanese"],"きおく":["japanese"],"きおち":["japanese"],"きおん":["japanese"],"きかい":["japanese"],"きかく":["japanese"],"きかんしゃ":["japanese"],"ききて":["japanese"],"きくばり":["japanese"],"きくらげ":["japanese"],"きけんせい":["japanese"],"きこう":["japanese"],"きこえる":["japanese"],"きこく":["japanese"],"きさい":["japanese"],"きさく":["japanese"],"きさま":["japanese"],"きさらぎ":["japanese"],"ぎじかがく":["japanese"],"ぎしき":["japanese"],"ぎじたいけん":["japanese"],"ぎじにってい":["japanese"],"ぎじゅつしゃ":["japanese"],"きすう":["japanese"],"きせい":["japanese"],"きせき":["japanese"],"きせつ":["japanese"],"きそう":["japanese"],"きぞく":["japanese"],"きぞん":["japanese"],"きたえる":["japanese"],"きちょう":["japanese"],"きつえん":["japanese"],"ぎっちり":["japanese"],"きつつき":["japanese"],"きつね":["japanese"],"きてい":["japanese"],"きどう":["japanese"],"きどく":["japanese"],"きない":["japanese"],"きなが":["japanese"],"きなこ":["japanese"],"きぬごし":["japanese"],"きねん":["japanese"],"きのう":["japanese"],"きのした":["japanese"],"きはく":["japanese"],"きびしい":["japanese"],"きひん":["japanese"],"きふく":["japanese"],"きぶん":["japanese"],"きぼう":["japanese"],"きほん":["japanese"],"きまる":["japanese"],"きみつ":["japanese"],"きむずかしい":["japanese"],"きめる":["japanese"],"きもだめし":["japanese"],"きもち":["japanese"],"きもの":["japanese"],"きゃく":["japanese"],"きやく":["japanese"],"ぎゅうにく":["japanese"],"きよう":["japanese"],"きょうりゅう":["japanese"],"きらい":["japanese"],"きらく":["japanese"],"きりん":["japanese"],"きれい":["japanese"],"きれつ":["japanese"],"きろく":["japanese"],"ぎろん":["japanese"],"きわめる":["japanese"],"ぎんいろ":["japanese"],"きんかくじ":["japanese"],"きんじょ":["japanese"],"きんようび":["japanese"],"ぐあい":["japanese"],"くいず":["japanese"],"くうかん":["japanese"],"くうき":["japanese"],"くうぐん":["japanese"],"くうこう":["japanese"],"ぐうせい":["japanese"],"くうそう":["japanese"],"ぐうたら":["japanese"],"くうふく":["japanese"],"くうぼ":["japanese"],"くかん":["japanese"],"くきょう":["japanese"],"くげん":["japanese"],"ぐこう":["japanese"],"くさい":["japanese"],"くさき":["japanese"],"くさばな":["japanese"],"くさる":["japanese"],"くしゃみ":["japanese"],"くしょう":["japanese"],"くすのき":["japanese"],"くすりゆび":["japanese"],"くせげ":["japanese"],"くせん":["japanese"],"ぐたいてき":["japanese"],"くださる":["japanese"],"くたびれる":["japanese"],"くちこみ":["japanese"],"くちさき":["japanese"],"くつした":["japanese"],"ぐっすり":["japanese"],"くつろぐ":["japanese"],"くとうてん":["japanese"],"くどく":["japanese"],"くなん":["japanese"],"くねくね":["japanese"],"くのう":["japanese"],"くふう":["japanese"],"くみあわせ":["japanese"],"くみたてる":["japanese"],"くめる":["japanese"],"くやくしょ":["japanese"],"くらす":["japanese"],"くらべる":["japanese"],"くるま":["japanese"],"くれる":["japanese"],"くろう":["japanese"],"くわしい":["japanese"],"ぐんかん":["japanese"],"ぐんしょく":["japanese"],"ぐんたい":["japanese"],"ぐんて":["japanese"],"けあな":["japanese"],"けいかく":["japanese"],"けいけん":["japanese"],"けいこ":["japanese"],"けいさつ":["japanese"],"げいじゅつ":["japanese"],"けいたい":["japanese"],"げいのうじん":["japanese"],"けいれき":["japanese"],"けいろ":["japanese"],"けおとす":["japanese"],"けおりもの":["japanese"],"げきか":["japanese"],"げきげん":["japanese"],"げきだん":["japanese"],"げきちん":["japanese"],"げきとつ":["japanese"],"げきは":["japanese"],"げきやく":["japanese"],"げこう":["japanese"],"げこくじょう":["japanese"],"げざい":["japanese"],"けさき":["japanese"],"げざん":["japanese"],"けしき":["japanese"],"けしごむ":["japanese"],"けしょう":["japanese"],"げすと":["japanese"],"けたば":["japanese"],"けちゃっぷ":["japanese"],"けちらす":["japanese"],"けつあつ":["japanese"],"けつい":["japanese"],"けつえき":["japanese"],"けっこん":["japanese"],"けつじょ":["japanese"],"けっせき":["japanese"],"けってい":["japanese"],"けつまつ":["japanese"],"げつようび":["japanese"],"げつれい":["japanese"],"けつろん":["japanese"],"げどく":["japanese"],"けとばす":["japanese"],"けとる":["japanese"],"けなげ":["japanese"],"けなす":["japanese"],"けなみ":["japanese"],"けぬき":["japanese"],"げねつ":["japanese"],"けねん":["japanese"],"けはい":["japanese"],"げひん":["japanese"],"けぶかい":["japanese"],"げぼく":["japanese"],"けまり":["japanese"],"けみかる":["japanese"],"けむし":["japanese"],"けむり":["japanese"],"けもの":["japanese"],"けらい":["japanese"],"けろけろ":["japanese"],"けわしい":["japanese"],"けんい":["japanese"],"けんえつ":["japanese"],"けんお":["japanese"],"けんか":["japanese"],"げんき":["japanese"],"けんげん":["japanese"],"けんこう":["japanese"],"けんさく":["japanese"],"けんしゅう":["japanese"],"けんすう":["japanese"],"げんそう":["japanese"],"けんちく":["japanese"],"けんてい":["japanese"],"けんとう":["japanese"],"けんない":["japanese"],"けんにん":["japanese"],"げんぶつ":["japanese"],"けんま":["japanese"],"けんみん":["japanese"],"けんめい":["japanese"],"けんらん":["japanese"],"けんり":["japanese"],"こあくま":["japanese"],"こいぬ":["japanese"],"こいびと":["japanese"],"ごうい":["japanese"],"こうえん":["japanese"],"こうおん":["japanese"],"こうかん":["japanese"],"ごうきゅう":["japanese"],"ごうけい":["japanese"],"こうこう":["japanese"],"こうさい":["japanese"],"こうじ":["japanese"],"こうすい":["japanese"],"ごうせい":["japanese"],"こうそく":["japanese"],"こうたい":["japanese"],"こうちゃ":["japanese"],"こうつう":["japanese"],"こうてい":["japanese"],"こうどう":["japanese"],"こうない":["japanese"],"こうはい":["japanese"],"ごうほう":["japanese"],"ごうまん":["japanese"],"こうもく":["japanese"],"こうりつ":["japanese"],"こえる":["japanese"],"こおり":["japanese"],"ごかい":["japanese"],"ごがつ":["japanese"],"ごかん":["japanese"],"こくご":["japanese"],"こくさい":["japanese"],"こくとう":["japanese"],"こくない":["japanese"],"こくはく":["japanese"],"こぐま":["japanese"],"こけい":["japanese"],"こける":["japanese"],"ここのか":["japanese"],"こころ":["japanese"],"こさめ":["japanese"],"こしつ":["japanese"],"こすう":["japanese"],"こせい":["japanese"],"こせき":["japanese"],"こぜん":["japanese"],"こそだて":["japanese"],"こたい":["japanese"],"こたえる":["japanese"],"こたつ":["japanese"],"こちょう":["japanese"],"こっか":["japanese"],"こつこつ":["japanese"],"こつばん":["japanese"],"こつぶ":["japanese"],"こてい":["japanese"],"こてん":["japanese"],"ことがら":["japanese"],"ことし":["japanese"],"ことば":["japanese"],"ことり":["japanese"],"こなごな":["japanese"],"こねこね":["japanese"],"このまま":["japanese"],"このみ":["japanese"],"このよ":["japanese"],"ごはん":["japanese"],"こひつじ":["japanese"],"こふう":["japanese"],"こふん":["japanese"],"こぼれる":["japanese"],"ごまあぶら":["japanese"],"こまかい":["japanese"],"ごますり":["japanese"],"こまつな":["japanese"],"こまる":["japanese"],"こむぎこ":["japanese"],"こもじ":["japanese"],"こもち":["japanese"],"こもの":["japanese"],"こもん":["japanese"],"こやく":["japanese"],"こやま":["japanese"],"こゆう":["japanese"],"こゆび":["japanese"],"こよい":["japanese"],"こよう":["japanese"],"こりる":["japanese"],"これくしょん":["japanese"],"ころっけ":["japanese"],"こわもて":["japanese"],"こわれる":["japanese"],"こんいん":["japanese"],"こんかい":["japanese"],"こんき":["japanese"],"こんしゅう":["japanese"],"こんすい":["japanese"],"こんだて":["japanese"],"こんとん":["japanese"],"こんなん":["japanese"],"こんびに":["japanese"],"こんぽん":["japanese"],"こんまけ":["japanese"],"こんや":["japanese"],"こんれい":["japanese"],"こんわく":["japanese"],"ざいえき":["japanese"],"さいかい":["japanese"],"さいきん":["japanese"],"ざいげん":["japanese"],"ざいこ":["japanese"],"さいしょ":["japanese"],"さいせい":["japanese"],"ざいたく":["japanese"],"ざいちゅう":["japanese"],"さいてき":["japanese"],"ざいりょう":["japanese"],"さうな":["japanese"],"さかいし":["japanese"],"さがす":["japanese"],"さかな":["japanese"],"さかみち":["japanese"],"さがる":["japanese"],"さぎょう":["japanese"],"さくし":["japanese"],"さくひん":["japanese"],"さくら":["japanese"],"さこく":["japanese"],"さこつ":["japanese"],"さずかる":["japanese"],"ざせき":["japanese"],"さたん":["japanese"],"さつえい":["japanese"],"ざつおん":["japanese"],"ざっか":["japanese"],"ざつがく":["japanese"],"さっきょく":["japanese"],"ざっし":["japanese"],"さつじん":["japanese"],"ざっそう":["japanese"],"さつたば":["japanese"],"さつまいも":["japanese"],"さてい":["japanese"],"さといも":["japanese"],"さとう":["japanese"],"さとおや":["japanese"],"さとし":["japanese"],"さとる":["japanese"],"さのう":["japanese"],"さばく":["japanese"],"さびしい":["japanese"],"さべつ":["japanese"],"さほう":["japanese"],"さほど":["japanese"],"さます":["japanese"],"さみしい":["japanese"],"さみだれ":["japanese"],"さむけ":["japanese"],"さめる":["japanese"],"さやえんどう":["japanese"],"さゆう":["japanese"],"さよう":["japanese"],"さよく":["japanese"],"さらだ":["japanese"],"ざるそば":["japanese"],"さわやか":["japanese"],"さわる":["japanese"],"さんいん":["japanese"],"さんか":["japanese"],"さんきゃく":["japanese"],"さんこう":["japanese"],"さんさい":["japanese"],"ざんしょ":["japanese"],"さんすう":["japanese"],"さんせい":["japanese"],"さんそ":["japanese"],"さんち":["japanese"],"さんま":["japanese"],"さんみ":["japanese"],"さんらん":["japanese"],"しあい":["japanese"],"しあげ":["japanese"],"しあさって":["japanese"],"しあわせ":["japanese"],"しいく":["japanese"],"しいん":["japanese"],"しうち":["japanese"],"しえい":["japanese"],"しおけ":["japanese"],"しかい":["japanese"],"しかく":["japanese"],"じかん":["japanese"],"しごと":["japanese"],"しすう":["japanese"],"じだい":["japanese"],"したうけ":["japanese"],"したぎ":["japanese"],"したて":["japanese"],"したみ":["japanese"],"しちょう":["japanese"],"しちりん":["japanese"],"しっかり":["japanese"],"しつじ":["japanese"],"しつもん":["japanese"],"してい":["japanese"],"してき":["japanese"],"してつ":["japanese"],"じてん":["japanese"],"じどう":["japanese"],"しなぎれ":["japanese"],"しなもの":["japanese"],"しなん":["japanese"],"しねま":["japanese"],"しねん":["japanese"],"しのぐ":["japanese"],"しのぶ":["japanese"],"しはい":["japanese"],"しばかり":["japanese"],"しはつ":["japanese"],"しはらい":["japanese"],"しはん":["japanese"],"しひょう":["japanese"],"しふく":["japanese"],"じぶん":["japanese"],"しへい":["japanese"],"しほう":["japanese"],"しほん":["japanese"],"しまう":["japanese"],"しまる":["japanese"],"しみん":["japanese"],"しむける":["japanese"],"じむしょ":["japanese"],"しめい":["japanese"],"しめる":["japanese"],"しもん":["japanese"],"しゃいん":["japanese"],"しゃうん":["japanese"],"しゃおん":["japanese"],"じゃがいも":["japanese"],"しやくしょ":["japanese"],"しゃくほう":["japanese"],"しゃけん":["japanese"],"しゃこ":["japanese"],"しゃざい":["japanese"],"しゃしん":["japanese"],"しゃせん":["japanese"],"しゃそう":["japanese"],"しゃたい":["japanese"],"しゃちょう":["japanese"],"しゃっきん":["japanese"],"じゃま":["japanese"],"しゃりん":["japanese"],"しゃれい":["japanese"],"じゆう":["japanese"],"じゅうしょ":["japanese"],"しゅくはく":["japanese"],"じゅしん":["japanese"],"しゅっせき":["japanese"],"しゅみ":["japanese"],"しゅらば":["japanese"],"じゅんばん":["japanese"],"しょうかい":["japanese"],"しょくたく":["japanese"],"しょっけん":["japanese"],"しょどう":["japanese"],"しょもつ":["japanese"],"しらせる":["japanese"],"しらべる":["japanese"],"しんか":["japanese"],"しんこう":["japanese"],"じんじゃ":["japanese"],"しんせいじ":["japanese"],"しんちく":["japanese"],"しんりん":["japanese"],"すあげ":["japanese"],"すあし":["japanese"],"すあな":["japanese"],"ずあん":["japanese"],"すいえい":["japanese"],"すいか":["japanese"],"すいとう":["japanese"],"ずいぶん":["japanese"],"すいようび":["japanese"],"すうがく":["japanese"],"すうじつ":["japanese"],"すうせん":["japanese"],"すおどり":["japanese"],"すきま":["japanese"],"すくう":["japanese"],"すくない":["japanese"],"すける":["japanese"],"すごい":["japanese"],"すこし":["japanese"],"ずさん":["japanese"],"すずしい":["japanese"],"すすむ":["japanese"],"すすめる":["japanese"],"すっかり":["japanese"],"ずっしり":["japanese"],"ずっと":["japanese"],"すてき":["japanese"],"すてる":["japanese"],"すねる":["japanese"],"すのこ":["japanese"],"すはだ":["japanese"],"すばらしい":["japanese"],"ずひょう":["japanese"],"ずぶぬれ":["japanese"],"すぶり":["japanese"],"すふれ":["japanese"],"すべて":["japanese"],"すべる":["japanese"],"ずほう":["japanese"],"すぼん":["japanese"],"すまい":["japanese"],"すめし":["japanese"],"すもう":["japanese"],"すやき":["japanese"],"すらすら":["japanese"],"するめ":["japanese"],"すれちがう":["japanese"],"すろっと":["japanese"],"すわる":["japanese"],"すんぜん":["japanese"],"すんぽう":["japanese"],"せあぶら":["japanese"],"せいかつ":["japanese"],"せいげん":["japanese"],"せいじ":["japanese"],"せいよう":["japanese"],"せおう":["japanese"],"せかいかん":["japanese"],"せきにん":["japanese"],"せきむ":["japanese"],"せきゆ":["japanese"],"せきらんうん":["japanese"],"せけん":["japanese"],"せこう":["japanese"],"せすじ":["japanese"],"せたい":["japanese"],"せたけ":["japanese"],"せっかく":["japanese"],"せっきゃく":["japanese"],"ぜっく":["japanese"],"せっけん":["japanese"],"せっこつ":["japanese"],"せっさたくま":["japanese"],"せつぞく":["japanese"],"せつだん":["japanese"],"せつでん":["japanese"],"せっぱん":["japanese"],"せつび":["japanese"],"せつぶん":["japanese"],"せつめい":["japanese"],"せつりつ":["japanese"],"せなか":["japanese"],"せのび":["japanese"],"せはば":["japanese"],"せびろ":["japanese"],"せぼね":["japanese"],"せまい":["japanese"],"せまる":["japanese"],"せめる":["japanese"],"せもたれ":["japanese"],"せりふ":["japanese"],"ぜんあく":["japanese"],"せんい":["japanese"],"せんえい":["japanese"],"せんか":["japanese"],"せんきょ":["japanese"],"せんく":["japanese"],"せんげん":["japanese"],"ぜんご":["japanese"],"せんさい":["japanese"],"せんしゅ":["japanese"],"せんすい":["japanese"],"せんせい":["japanese"],"せんぞ":["japanese"],"せんたく":["japanese"],"せんちょう":["japanese"],"せんてい":["japanese"],"せんとう":["japanese"],"せんぬき":["japanese"],"せんねん":["japanese"],"せんぱい":["japanese"],"ぜんぶ":["japanese"],"ぜんぽう":["japanese"],"せんむ":["japanese"],"せんめんじょ":["japanese"],"せんもん":["japanese"],"せんやく":["japanese"],"せんゆう":["japanese"],"せんよう":["japanese"],"ぜんら":["japanese"],"ぜんりゃく":["japanese"],"せんれい":["japanese"],"せんろ":["japanese"],"そあく":["japanese"],"そいとげる":["japanese"],"そいね":["japanese"],"そうがんきょう":["japanese"],"そうき":["japanese"],"そうご":["japanese"],"そうしん":["japanese"],"そうだん":["japanese"],"そうなん":["japanese"],"そうび":["japanese"],"そうめん":["japanese"],"そうり":["japanese"],"そえもの":["japanese"],"そえん":["japanese"],"そがい":["japanese"],"そげき":["japanese"],"そこう":["japanese"],"そこそこ":["japanese"],"そざい":["japanese"],"そしな":["japanese"],"そせい":["japanese"],"そせん":["japanese"],"そそぐ":["japanese"],"そだてる":["japanese"],"そつう":["japanese"],"そつえん":["japanese"],"そっかん":["japanese"],"そつぎょう":["japanese"],"そっけつ":["japanese"],"そっこう":["japanese"],"そっせん":["japanese"],"そっと":["japanese"],"そとがわ":["japanese"],"そとづら":["japanese"],"そなえる":["japanese"],"そなた":["japanese"],"そふぼ":["japanese"],"そぼく":["japanese"],"そぼろ":["japanese"],"そまつ":["japanese"],"そまる":["japanese"],"そむく":["japanese"],"そむりえ":["japanese"],"そめる":["japanese"],"そもそも":["japanese"],"そよかぜ":["japanese"],"そらまめ":["japanese"],"そろう":["japanese"],"そんかい":["japanese"],"そんけい":["japanese"],"そんざい":["japanese"],"そんしつ":["japanese"],"そんぞく":["japanese"],"そんちょう":["japanese"],"ぞんび":["japanese"],"ぞんぶん":["japanese"],"そんみん":["japanese"],"たあい":["japanese"],"たいいん":["japanese"],"たいうん":["japanese"],"たいえき":["japanese"],"たいおう":["japanese"],"だいがく":["japanese"],"たいき":["japanese"],"たいぐう":["japanese"],"たいけん":["japanese"],"たいこ":["japanese"],"たいざい":["japanese"],"だいじょうぶ":["japanese"],"だいすき":["japanese"],"たいせつ":["japanese"],"たいそう":["japanese"],"だいたい":["japanese"],"たいちょう":["japanese"],"たいてい":["japanese"],"だいどころ":["japanese"],"たいない":["japanese"],"たいねつ":["japanese"],"たいのう":["japanese"],"たいはん":["japanese"],"だいひょう":["japanese"],"たいふう":["japanese"],"たいへん":["japanese"],"たいほ":["japanese"],"たいまつばな":["japanese"],"たいみんぐ":["japanese"],"たいむ":["japanese"],"たいめん":["japanese"],"たいやき":["japanese"],"たいよう":["japanese"],"たいら":["japanese"],"たいりょく":["japanese"],"たいる":["japanese"],"たいわん":["japanese"],"たうえ":["japanese"],"たえる":["japanese"],"たおす":["japanese"],"たおる":["japanese"],"たおれる":["japanese"],"たかい":["japanese"],"たかね":["japanese"],"たきび":["japanese"],"たくさん":["japanese"],"たこく":["japanese"],"たこやき":["japanese"],"たさい":["japanese"],"たしざん":["japanese"],"だじゃれ":["japanese"],"たすける":["japanese"],"たずさわる":["japanese"],"たそがれ":["japanese"],"たたかう":["japanese"],"たたく":["japanese"],"ただしい":["japanese"],"たたみ":["japanese"],"たちばな":["japanese"],"だっかい":["japanese"],"だっきゃく":["japanese"],"だっこ":["japanese"],"だっしゅつ":["japanese"],"だったい":["japanese"],"たてる":["japanese"],"たとえる":["japanese"],"たなばた":["japanese"],"たにん":["japanese"],"たぬき":["japanese"],"たのしみ":["japanese"],"たはつ":["japanese"],"たぶん":["japanese"],"たべる":["japanese"],"たぼう":["japanese"],"たまご":["japanese"],"たまる":["japanese"],"だむる":["japanese"],"ためいき":["japanese"],"ためす":["japanese"],"ためる":["japanese"],"たもつ":["japanese"],"たやすい":["japanese"],"たよる":["japanese"],"たらす":["japanese"],"たりきほんがん":["japanese"],"たりょう":["japanese"],"たりる":["japanese"],"たると":["japanese"],"たれる":["japanese"],"たれんと":["japanese"],"たろっと":["japanese"],"たわむれる":["japanese"],"だんあつ":["japanese"],"たんい":["japanese"],"たんおん":["japanese"],"たんか":["japanese"],"たんき":["japanese"],"たんけん":["japanese"],"たんご":["japanese"],"たんさん":["japanese"],"たんじょうび":["japanese"],"だんせい":["japanese"],"たんそく":["japanese"],"たんたい":["japanese"],"だんち":["japanese"],"たんてい":["japanese"],"たんとう":["japanese"],"だんな":["japanese"],"たんにん":["japanese"],"だんねつ":["japanese"],"たんのう":["japanese"],"たんぴん":["japanese"],"だんぼう":["japanese"],"たんまつ":["japanese"],"たんめい":["japanese"],"だんれつ":["japanese"],"だんろ":["japanese"],"だんわ":["japanese"],"ちあい":["japanese"],"ちあん":["japanese"],"ちいき":["japanese"],"ちいさい":["japanese"],"ちえん":["japanese"],"ちかい":["japanese"],"ちから":["japanese"],"ちきゅう":["japanese"],"ちきん":["japanese"],"ちけいず":["japanese"],"ちけん":["japanese"],"ちこく":["japanese"],"ちさい":["japanese"],"ちしき":["japanese"],"ちしりょう":["japanese"],"ちせい":["japanese"],"ちそう":["japanese"],"ちたい":["japanese"],"ちたん":["japanese"],"ちちおや":["japanese"],"ちつじょ":["japanese"],"ちてき":["japanese"],"ちてん":["japanese"],"ちぬき":["japanese"],"ちぬり":["japanese"],"ちのう":["japanese"],"ちひょう":["japanese"],"ちへいせん":["japanese"],"ちほう":["japanese"],"ちまた":["japanese"],"ちみつ":["japanese"],"ちみどろ":["japanese"],"ちめいど":["japanese"],"ちゃんこなべ":["japanese"],"ちゅうい":["japanese"],"ちゆりょく":["japanese"],"ちょうし":["japanese"],"ちょさくけん":["japanese"],"ちらし":["japanese"],"ちらみ":["japanese"],"ちりがみ":["japanese"],"ちりょう":["japanese"],"ちるど":["japanese"],"ちわわ":["japanese"],"ちんたい":["japanese"],"ちんもく":["japanese"],"ついか":["japanese"],"ついたち":["japanese"],"つうか":["japanese"],"つうじょう":["japanese"],"つうはん":["japanese"],"つうわ":["japanese"],"つかう":["japanese"],"つかれる":["japanese"],"つくね":["japanese"],"つくる":["japanese"],"つけね":["japanese"],"つける":["japanese"],"つごう":["japanese"],"つたえる":["japanese"],"つづく":["japanese"],"つつじ":["japanese"],"つつむ":["japanese"],"つとめる":["japanese"],"つながる":["japanese"],"つなみ":["japanese"],"つねづね":["japanese"],"つのる":["japanese"],"つぶす":["japanese"],"つまらない":["japanese"],"つまる":["japanese"],"つみき":["japanese"],"つめたい":["japanese"],"つもり":["japanese"],"つもる":["japanese"],"つよい":["japanese"],"つるぼ":["japanese"],"つるみく":["japanese"],"つわもの":["japanese"],"つわり":["japanese"],"てあし":["japanese"],"てあて":["japanese"],"てあみ":["japanese"],"ていおん":["japanese"],"ていか":["japanese"],"ていき":["japanese"],"ていけい":["japanese"],"ていこく":["japanese"],"ていさつ":["japanese"],"ていし":["japanese"],"ていせい":["japanese"],"ていたい":["japanese"],"ていど":["japanese"],"ていねい":["japanese"],"ていひょう":["japanese"],"ていへん":["japanese"],"ていぼう":["japanese"],"てうち":["japanese"],"ておくれ":["japanese"],"てきとう":["japanese"],"てくび":["japanese"],"でこぼこ":["japanese"],"てさぎょう":["japanese"],"てさげ":["japanese"],"てすり":["japanese"],"てそう":["japanese"],"てちがい":["japanese"],"てちょう":["japanese"],"てつがく":["japanese"],"てつづき":["japanese"],"でっぱ":["japanese"],"てつぼう":["japanese"],"てつや":["japanese"],"でぬかえ":["japanese"],"てぬき":["japanese"],"てぬぐい":["japanese"],"てのひら":["japanese"],"てはい":["japanese"],"てぶくろ":["japanese"],"てふだ":["japanese"],"てほどき":["japanese"],"てほん":["japanese"],"てまえ":["japanese"],"てまきずし":["japanese"],"てみじか":["japanese"],"てみやげ":["japanese"],"てらす":["japanese"],"てれび":["japanese"],"てわけ":["japanese"],"てわたし":["japanese"],"でんあつ":["japanese"],"てんいん":["japanese"],"てんかい":["japanese"],"てんき":["japanese"],"てんぐ":["japanese"],"てんけん":["japanese"],"てんごく":["japanese"],"てんさい":["japanese"],"てんし":["japanese"],"てんすう":["japanese"],"でんち":["japanese"],"てんてき":["japanese"],"てんとう":["japanese"],"てんない":["japanese"],"てんぷら":["japanese"],"てんぼうだい":["japanese"],"てんめつ":["japanese"],"てんらんかい":["japanese"],"でんりょく":["japanese"],"でんわ":["japanese"],"どあい":["japanese"],"といれ":["japanese"],"どうかん":["japanese"],"とうきゅう":["japanese"],"どうぐ":["japanese"],"とうし":["japanese"],"とうむぎ":["japanese"],"とおい":["japanese"],"とおか":["japanese"],"とおく":["japanese"],"とおす":["japanese"],"とおる":["japanese"],"とかい":["japanese"],"とかす":["japanese"],"ときおり":["japanese"],"ときどき":["japanese"],"とくい":["japanese"],"とくしゅう":["japanese"],"とくてん":["japanese"],"とくに":["japanese"],"とくべつ":["japanese"],"とけい":["japanese"],"とける":["japanese"],"とこや":["japanese"],"とさか":["japanese"],"としょかん":["japanese"],"とそう":["japanese"],"とたん":["japanese"],"とちゅう":["japanese"],"とっきゅう":["japanese"],"とっくん":["japanese"],"とつぜん":["japanese"],"とつにゅう":["japanese"],"とどける":["japanese"],"ととのえる":["japanese"],"とない":["japanese"],"となえる":["japanese"],"となり":["japanese"],"とのさま":["japanese"],"とばす":["japanese"],"どぶがわ":["japanese"],"とほう":["japanese"],"とまる":["japanese"],"とめる":["japanese"],"ともだち":["japanese"],"ともる":["japanese"],"どようび":["japanese"],"とらえる":["japanese"],"とんかつ":["japanese"],"どんぶり":["japanese"],"ないかく":["japanese"],"ないこう":["japanese"],"ないしょ":["japanese"],"ないす":["japanese"],"ないせん":["japanese"],"ないそう":["japanese"],"なおす":["japanese"],"ながい":["japanese"],"なくす":["japanese"],"なげる":["japanese"],"なこうど":["japanese"],"なさけ":["japanese"],"なたでここ":["japanese"],"なっとう":["japanese"],"なつやすみ":["japanese"],"ななおし":["japanese"],"なにごと":["japanese"],"なにもの":["japanese"],"なにわ":["japanese"],"なのか":["japanese"],"なふだ":["japanese"],"なまいき":["japanese"],"なまえ":["japanese"],"なまみ":["japanese"],"なみだ":["japanese"],"なめらか":["japanese"],"なめる":["japanese"],"なやむ":["japanese"],"ならう":["japanese"],"ならび":["japanese"],"ならぶ":["japanese"],"なれる":["japanese"],"なわとび":["japanese"],"なわばり":["japanese"],"にあう":["japanese"],"にいがた":["japanese"],"にうけ":["japanese"],"におい":["japanese"],"にかい":["japanese"],"にがて":["japanese"],"にきび":["japanese"],"にくしみ":["japanese"],"にくまん":["japanese"],"にげる":["japanese"],"にさんかたんそ":["japanese"],"にしき":["japanese"],"にせもの":["japanese"],"にちじょう":["japanese"],"にちようび":["japanese"],"にっか":["japanese"],"にっき":["japanese"],"にっけい":["japanese"],"にっこう":["japanese"],"にっさん":["japanese"],"にっしょく":["japanese"],"にっすう":["japanese"],"にっせき":["japanese"],"にってい":["japanese"],"になう":["japanese"],"にほん":["japanese"],"にまめ":["japanese"],"にもつ":["japanese"],"にやり":["japanese"],"にゅういん":["japanese"],"にりんしゃ":["japanese"],"にわとり":["japanese"],"にんい":["japanese"],"にんか":["japanese"],"にんき":["japanese"],"にんげん":["japanese"],"にんしき":["japanese"],"にんずう":["japanese"],"にんそう":["japanese"],"にんたい":["japanese"],"にんち":["japanese"],"にんてい":["japanese"],"にんにく":["japanese"],"にんぷ":["japanese"],"にんまり":["japanese"],"にんむ":["japanese"],"にんめい":["japanese"],"にんよう":["japanese"],"ぬいくぎ":["japanese"],"ぬかす":["japanese"],"ぬぐいとる":["japanese"],"ぬぐう":["japanese"],"ぬくもり":["japanese"],"ぬすむ":["japanese"],"ぬまえび":["japanese"],"ぬめり":["japanese"],"ぬらす":["japanese"],"ぬんちゃく":["japanese"],"ねあげ":["japanese"],"ねいき":["japanese"],"ねいる":["japanese"],"ねいろ":["japanese"],"ねぐせ":["japanese"],"ねくたい":["japanese"],"ねくら":["japanese"],"ねこぜ":["japanese"],"ねこむ":["japanese"],"ねさげ":["japanese"],"ねすごす":["japanese"],"ねそべる":["japanese"],"ねだん":["japanese"],"ねつい":["japanese"],"ねっしん":["japanese"],"ねつぞう":["japanese"],"ねったいぎょ":["japanese"],"ねぶそく":["japanese"],"ねふだ":["japanese"],"ねぼう":["japanese"],"ねほりはほり":["japanese"],"ねまき":["japanese"],"ねまわし":["japanese"],"ねみみ":["japanese"],"ねむい":["japanese"],"ねむたい":["japanese"],"ねもと":["japanese"],"ねらう":["japanese"],"ねわざ":["japanese"],"ねんいり":["japanese"],"ねんおし":["japanese"],"ねんかん":["japanese"],"ねんきん":["japanese"],"ねんぐ":["japanese"],"ねんざ":["japanese"],"ねんし":["japanese"],"ねんちゃく":["japanese"],"ねんど":["japanese"],"ねんぴ":["japanese"],"ねんぶつ":["japanese"],"ねんまつ":["japanese"],"ねんりょう":["japanese"],"ねんれい":["japanese"],"のいず":["japanese"],"のおづま":["japanese"],"のがす":["japanese"],"のきなみ":["japanese"],"のこぎり":["japanese"],"のこす":["japanese"],"のこる":["japanese"],"のせる":["japanese"],"のぞく":["japanese"],"のぞむ":["japanese"],"のたまう":["japanese"],"のちほど":["japanese"],"のっく":["japanese"],"のばす":["japanese"],"のはら":["japanese"],"のべる":["japanese"],"のぼる":["japanese"],"のみもの":["japanese"],"のやま":["japanese"],"のらいぬ":["japanese"],"のらねこ":["japanese"],"のりもの":["japanese"],"のりゆき":["japanese"],"のれん":["japanese"],"のんき":["japanese"],"ばあい":["japanese"],"はあく":["japanese"],"ばあさん":["japanese"],"ばいか":["japanese"],"ばいく":["japanese"],"はいけん":["japanese"],"はいご":["japanese"],"はいしん":["japanese"],"はいすい":["japanese"],"はいせん":["japanese"],"はいそう":["japanese"],"はいち":["japanese"],"ばいばい":["japanese"],"はいれつ":["japanese"],"はえる":["japanese"],"はおる":["japanese"],"はかい":["japanese"],"ばかり":["japanese"],"はかる":["japanese"],"はくしゅ":["japanese"],"はけん":["japanese"],"はこぶ":["japanese"],"はさみ":["japanese"],"はさん":["japanese"],"はしご":["japanese"],"ばしょ":["japanese"],"はしる":["japanese"],"はせる":["japanese"],"ぱそこん":["japanese"],"はそん":["japanese"],"はたん":["japanese"],"はちみつ":["japanese"],"はつおん":["japanese"],"はっかく":["japanese"],"はづき":["japanese"],"はっきり":["japanese"],"はっくつ":["japanese"],"はっけん":["japanese"],"はっこう":["japanese"],"はっさん":["japanese"],"はっしん":["japanese"],"はったつ":["japanese"],"はっちゅう":["japanese"],"はってん":["japanese"],"はっぴょう":["japanese"],"はっぽう":["japanese"],"はなす":["japanese"],"はなび":["japanese"],"はにかむ":["japanese"],"はぶらし":["japanese"],"はみがき":["japanese"],"はむかう":["japanese"],"はめつ":["japanese"],"はやい":["japanese"],"はやし":["japanese"],"はらう":["japanese"],"はろうぃん":["japanese"],"はわい":["japanese"],"はんい":["japanese"],"はんえい":["japanese"],"はんおん":["japanese"],"はんかく":["japanese"],"はんきょう":["japanese"],"ばんぐみ":["japanese"],"はんこ":["japanese"],"はんしゃ":["japanese"],"はんすう":["japanese"],"はんだん":["japanese"],"ぱんち":["japanese"],"ぱんつ":["japanese"],"はんてい":["japanese"],"はんとし":["japanese"],"はんのう":["japanese"],"はんぱ":["japanese"],"はんぶん":["japanese"],"はんぺん":["japanese"],"はんぼうき":["japanese"],"はんめい":["japanese"],"はんらん":["japanese"],"はんろん":["japanese"],"ひいき":["japanese"],"ひうん":["japanese"],"ひえる":["japanese"],"ひかく":["japanese"],"ひかり":["japanese"],"ひかる":["japanese"],"ひかん":["japanese"],"ひくい":["japanese"],"ひけつ":["japanese"],"ひこうき":["japanese"],"ひこく":["japanese"],"ひさい":["japanese"],"ひさしぶり":["japanese"],"ひさん":["japanese"],"びじゅつかん":["japanese"],"ひしょ":["japanese"],"ひそか":["japanese"],"ひそむ":["japanese"],"ひたむき":["japanese"],"ひだり":["japanese"],"ひたる":["japanese"],"ひつぎ":["japanese"],"ひっこし":["japanese"],"ひっし":["japanese"],"ひつじゅひん":["japanese"],"ひっす":["japanese"],"ひつぜん":["japanese"],"ぴったり":["japanese"],"ぴっちり":["japanese"],"ひつよう":["japanese"],"ひてい":["japanese"],"ひとごみ":["japanese"],"ひなまつり":["japanese"],"ひなん":["japanese"],"ひねる":["japanese"],"ひはん":["japanese"],"ひびく":["japanese"],"ひひょう":["japanese"],"ひほう":["japanese"],"ひまわり":["japanese"],"ひまん":["japanese"],"ひみつ":["japanese"],"ひめい":["japanese"],"ひめじし":["japanese"],"ひやけ":["japanese"],"ひやす":["japanese"],"ひよう":["japanese"],"びょうき":["japanese"],"ひらがな":["japanese"],"ひらく":["japanese"],"ひりつ":["japanese"],"ひりょう":["japanese"],"ひるま":["japanese"],"ひるやすみ":["japanese"],"ひれい":["japanese"],"ひろい":["japanese"],"ひろう":["japanese"],"ひろき":["japanese"],"ひろゆき":["japanese"],"ひんかく":["japanese"],"ひんけつ":["japanese"],"ひんこん":["japanese"],"ひんしゅ":["japanese"],"ひんそう":["japanese"],"ぴんち":["japanese"],"ひんぱん":["japanese"],"びんぼう":["japanese"],"ふあん":["japanese"],"ふいうち":["japanese"],"ふうけい":["japanese"],"ふうせん":["japanese"],"ぷうたろう":["japanese"],"ふうとう":["japanese"],"ふうふ":["japanese"],"ふえる":["japanese"],"ふおん":["japanese"],"ふかい":["japanese"],"ふきん":["japanese"],"ふくざつ":["japanese"],"ふくぶくろ":["japanese"],"ふこう":["japanese"],"ふさい":["japanese"],"ふしぎ":["japanese"],"ふじみ":["japanese"],"ふすま":["japanese"],"ふせい":["japanese"],"ふせぐ":["japanese"],"ふそく":["japanese"],"ぶたにく":["japanese"],"ふたん":["japanese"],"ふちょう":["japanese"],"ふつう":["japanese"],"ふつか":["japanese"],"ふっかつ":["japanese"],"ふっき":["japanese"],"ふっこく":["japanese"],"ぶどう":["japanese"],"ふとる":["japanese"],"ふとん":["japanese"],"ふのう":["japanese"],"ふはい":["japanese"],"ふひょう":["japanese"],"ふへん":["japanese"],"ふまん":["japanese"],"ふみん":["japanese"],"ふめつ":["japanese"],"ふめん":["japanese"],"ふよう":["japanese"],"ふりこ":["japanese"],"ふりる":["japanese"],"ふるい":["japanese"],"ふんいき":["japanese"],"ぶんがく":["japanese"],"ぶんぐ":["japanese"],"ふんしつ":["japanese"],"ぶんせき":["japanese"],"ふんそう":["japanese"],"ぶんぽう":["japanese"],"へいあん":["japanese"],"へいおん":["japanese"],"へいがい":["japanese"],"へいき":["japanese"],"へいげん":["japanese"],"へいこう":["japanese"],"へいさ":["japanese"],"へいしゃ":["japanese"],"へいせつ":["japanese"],"へいそ":["japanese"],"へいたく":["japanese"],"へいてん":["japanese"],"へいねつ":["japanese"],"へいわ":["japanese"],"へきが":["japanese"],"へこむ":["japanese"],"べにいろ":["japanese"],"べにしょうが":["japanese"],"へらす":["japanese"],"へんかん":["japanese"],"べんきょう":["japanese"],"べんごし":["japanese"],"へんさい":["japanese"],"へんたい":["japanese"],"べんり":["japanese"],"ほあん":["japanese"],"ほいく":["japanese"],"ぼうぎょ":["japanese"],"ほうこく":["japanese"],"ほうそう":["japanese"],"ほうほう":["japanese"],"ほうもん":["japanese"],"ほうりつ":["japanese"],"ほえる":["japanese"],"ほおん":["japanese"],"ほかん":["japanese"],"ほきょう":["japanese"],"ぼきん":["japanese"],"ほくろ":["japanese"],"ほけつ":["japanese"],"ほけん":["japanese"],"ほこう":["japanese"],"ほこる":["japanese"],"ほしい":["japanese"],"ほしつ":["japanese"],"ほしゅ":["japanese"],"ほしょう":["japanese"],"ほせい":["japanese"],"ほそい":["japanese"],"ほそく":["japanese"],"ほたて":["japanese"],"ほたる":["japanese"],"ぽちぶくろ":["japanese"],"ほっきょく":["japanese"],"ほっさ":["japanese"],"ほったん":["japanese"],"ほとんど":["japanese"],"ほめる":["japanese"],"ほんい":["japanese"],"ほんき":["japanese"],"ほんけ":["japanese"],"ほんしつ":["japanese"],"ほんやく":["japanese"],"まいにち":["japanese"],"まかい":["japanese"],"まかせる":["japanese"],"まがる":["japanese"],"まける":["japanese"],"まこと":["japanese"],"まさつ":["japanese"],"まじめ":["japanese"],"ますく":["japanese"],"まぜる":["japanese"],"まつり":["japanese"],"まとめ":["japanese"],"まなぶ":["japanese"],"まぬけ":["japanese"],"まねく":["japanese"],"まほう":["japanese"],"まもる":["japanese"],"まゆげ":["japanese"],"まよう":["japanese"],"まろやか":["japanese"],"まわす":["japanese"],"まわり":["japanese"],"まわる":["japanese"],"まんが":["japanese"],"まんきつ":["japanese"],"まんぞく":["japanese"],"まんなか":["japanese"],"みいら":["japanese"],"みうち":["japanese"],"みえる":["japanese"],"みがく":["japanese"],"みかた":["japanese"],"みかん":["japanese"],"みけん":["japanese"],"みこん":["japanese"],"みじかい":["japanese"],"みすい":["japanese"],"みすえる":["japanese"],"みせる":["japanese"],"みっか":["japanese"],"みつかる":["japanese"],"みつける":["japanese"],"みてい":["japanese"],"みとめる":["japanese"],"みなと":["japanese"],"みなみかさい":["japanese"],"みねらる":["japanese"],"みのう":["japanese"],"みのがす":["japanese"],"みほん":["japanese"],"みもと":["japanese"],"みやげ":["japanese"],"みらい":["japanese"],"みりょく":["japanese"],"みわく":["japanese"],"みんか":["japanese"],"みんぞく":["japanese"],"むいか":["japanese"],"むえき":["japanese"],"むえん":["japanese"],"むかい":["japanese"],"むかう":["japanese"],"むかえ":["japanese"],"むかし":["japanese"],"むぎちゃ":["japanese"],"むける":["japanese"],"むげん":["japanese"],"むさぼる":["japanese"],"むしあつい":["japanese"],"むしば":["japanese"],"むじゅん":["japanese"],"むしろ":["japanese"],"むすう":["japanese"],"むすこ":["japanese"],"むすぶ":["japanese"],"むすめ":["japanese"],"むせる":["japanese"],"むせん":["japanese"],"むちゅう":["japanese"],"むなしい":["japanese"],"むのう":["japanese"],"むやみ":["japanese"],"むよう":["japanese"],"むらさき":["japanese"],"むりょう":["japanese"],"むろん":["japanese"],"めいあん":["japanese"],"めいうん":["japanese"],"めいえん":["japanese"],"めいかく":["japanese"],"めいきょく":["japanese"],"めいさい":["japanese"],"めいし":["japanese"],"めいそう":["japanese"],"めいぶつ":["japanese"],"めいれい":["japanese"],"めいわく":["japanese"],"めぐまれる":["japanese"],"めざす":["japanese"],"めした":["japanese"],"めずらしい":["japanese"],"めだつ":["japanese"],"めまい":["japanese"],"めやす":["japanese"],"めんきょ":["japanese"],"めんせき":["japanese"],"めんどう":["japanese"],"もうしあげる":["japanese"],"もうどうけん":["japanese"],"もえる":["japanese"],"もくし":["japanese"],"もくてき":["japanese"],"もくようび":["japanese"],"もちろん":["japanese"],"もどる":["japanese"],"もらう":["japanese"],"もんく":["japanese"],"もんだい":["japanese"],"やおや":["japanese"],"やける":["japanese"],"やさい":["japanese"],"やさしい":["japanese"],"やすい":["japanese"],"やすたろう":["japanese"],"やすみ":["japanese"],"やせる":["japanese"],"やそう":["japanese"],"やたい":["japanese"],"やちん":["japanese"],"やっと":["japanese"],"やっぱり":["japanese"],"やぶる":["japanese"],"やめる":["japanese"],"ややこしい":["japanese"],"やよい":["japanese"],"やわらかい":["japanese"],"ゆうき":["japanese"],"ゆうびんきょく":["japanese"],"ゆうべ":["japanese"],"ゆうめい":["japanese"],"ゆけつ":["japanese"],"ゆしゅつ":["japanese"],"ゆせん":["japanese"],"ゆそう":["japanese"],"ゆたか":["japanese"],"ゆちゃく":["japanese"],"ゆでる":["japanese"],"ゆにゅう":["japanese"],"ゆびわ":["japanese"],"ゆらい":["japanese"],"ゆれる":["japanese"],"ようい":["japanese"],"ようか":["japanese"],"ようきゅう":["japanese"],"ようじ":["japanese"],"ようす":["japanese"],"ようちえん":["japanese"],"よかぜ":["japanese"],"よかん":["japanese"],"よきん":["japanese"],"よくせい":["japanese"],"よくぼう":["japanese"],"よけい":["japanese"],"よごれる":["japanese"],"よさん":["japanese"],"よしゅう":["japanese"],"よそう":["japanese"],"よそく":["japanese"],"よっか":["japanese"],"よてい":["japanese"],"よどがわく":["japanese"],"よねつ":["japanese"],"よやく":["japanese"],"よゆう":["japanese"],"よろこぶ":["japanese"],"よろしい":["japanese"],"らいう":["japanese"],"らくがき":["japanese"],"らくご":["japanese"],"らくさつ":["japanese"],"らくだ":["japanese"],"らしんばん":["japanese"],"らせん":["japanese"],"らぞく":["japanese"],"らたい":["japanese"],"らっか":["japanese"],"られつ":["japanese"],"りえき":["japanese"],"りかい":["japanese"],"りきさく":["japanese"],"りきせつ":["japanese"],"りくぐん":["japanese"],"りくつ":["japanese"],"りけん":["japanese"],"りこう":["japanese"],"りせい":["japanese"],"りそう":["japanese"],"りそく":["japanese"],"りてん":["japanese"],"りねん":["japanese"],"りゆう":["japanese"],"りゅうがく":["japanese"],"りよう":["japanese"],"りょうり":["japanese"],"りょかん":["japanese"],"りょくちゃ":["japanese"],"りょこう":["japanese"],"りりく":["japanese"],"りれき":["japanese"],"りろん":["japanese"],"りんご":["japanese"],"るいけい":["japanese"],"るいさい":["japanese"],"るいじ":["japanese"],"るいせき":["japanese"],"るすばん":["japanese"],"るりがわら":["japanese"],"れいかん":["japanese"],"れいぎ":["japanese"],"れいせい":["japanese"],"れいぞうこ":["japanese"],"れいとう":["japanese"],"れいぼう":["japanese"],"れきし":["japanese"],"れきだい":["japanese"],"れんあい":["japanese"],"れんけい":["japanese"],"れんこん":["japanese"],"れんさい":["japanese"],"れんしゅう":["japanese"],"れんぞく":["japanese"],"れんらく":["japanese"],"ろうか":["japanese"],"ろうご":["japanese"],"ろうじん":["japanese"],"ろうそく":["japanese"],"ろくが":["japanese"],"ろこつ":["japanese"],"ろじうら":["japanese"],"ろしゅつ":["japanese"],"ろせん":["japanese"],"ろてん":["japanese"],"ろめん":["japanese"],"ろれつ":["japanese"],"ろんぎ":["japanese"],"ろんぱ":["japanese"],"ろんぶん":["japanese"],"ろんり":["japanese"],"わかす":["japanese"],"わかめ":["japanese"],"わかやま":["japanese"],"わかれる":["japanese"],"わしつ":["japanese"],"わじまし":["japanese"],"わすれもの":["japanese"],"わらう":["japanese"],"われる":["japanese"],"가격":["korean"],"가끔":["korean"],"가난":["korean"],"가능":["korean"],"가득":["korean"],"가르침":["korean"],"가뭄":["korean"],"가방":["korean"],"가상":["korean"],"가슴":["korean"],"가운데":["korean"],"가을":["korean"],"가이드":["korean"],"가입":["korean"],"가장":["korean"],"가정":["korean"],"가족":["korean"],"가죽":["korean"],"각오":["korean"],"각자":["korean"],"간격":["korean"],"간부":["korean"],"간섭":["korean"],"간장":["korean"],"간접":["korean"],"간판":["korean"],"갈등":["korean"],"갈비":["korean"],"갈색":["korean"],"갈증":["korean"],"감각":["korean"],"감기":["korean"],"감소":["korean"],"감수성":["korean"],"감자":["korean"],"감정":["korean"],"갑자기":["korean"],"강남":["korean"],"강당":["korean"],"강도":["korean"],"강력히":["korean"],"강변":["korean"],"강북":["korean"],"강사":["korean"],"강수량":["korean"],"강아지":["korean"],"강원도":["korean"],"강의":["korean"],"강제":["korean"],"강조":["korean"],"같이":["korean"],"개구리":["korean"],"개나리":["korean"],"개방":["korean"],"개별":["korean"],"개선":["korean"],"개성":["korean"],"개인":["korean"],"객관적":["korean"],"거실":["korean"],"거액":["korean"],"거울":["korean"],"거짓":["korean"],"거품":["korean"],"걱정":["korean"],"건강":["korean"],"건물":["korean"],"건설":["korean"],"건조":["korean"],"건축":["korean"],"걸음":["korean"],"검사":["korean"],"검토":["korean"],"게시판":["korean"],"게임":["korean"],"겨울":["korean"],"견해":["korean"],"결과":["korean"],"결국":["korean"],"결론":["korean"],"결석":["korean"],"결승":["korean"],"결심":["korean"],"결정":["korean"],"결혼":["korean"],"경계":["korean"],"경고":["korean"],"경기":["korean"],"경력":["korean"],"경복궁":["korean"],"경비":["korean"],"경상도":["korean"],"경영":["korean"],"경우":["korean"],"경쟁":["korean"],"경제":["korean"],"경주":["korean"],"경찰":["korean"],"경치":["korean"],"경향":["korean"],"경험":["korean"],"계곡":["korean"],"계단":["korean"],"계란":["korean"],"계산":["korean"],"계속":["korean"],"계약":["korean"],"계절":["korean"],"계층":["korean"],"계획":["korean"],"고객":["korean"],"고구려":["korean"],"고궁":["korean"],"고급":["korean"],"고등학생":["korean"],"고무신":["korean"],"고민":["korean"],"고양이":["korean"],"고장":["korean"],"고전":["korean"],"고집":["korean"],"고춧가루":["korean"],"고통":["korean"],"고향":["korean"],"곡식":["korean"],"골목":["korean"],"골짜기":["korean"],"골프":["korean"],"공간":["korean"],"공개":["korean"],"공격":["korean"],"공군":["korean"],"공급":["korean"],"공기":["korean"],"공동":["korean"],"공무원":["korean"],"공부":["korean"],"공사":["korean"],"공식":["korean"],"공업":["korean"],"공연":["korean"],"공원":["korean"],"공장":["korean"],"공짜":["korean"],"공책":["korean"],"공통":["korean"],"공포":["korean"],"공항":["korean"],"공휴일":["korean"],"과목":["korean"],"과일":["korean"],"과장":["korean"],"과정":["korean"],"과학":["korean"],"관객":["korean"],"관계":["korean"],"관광":["korean"],"관념":["korean"],"관람":["korean"],"관련":["korean"],"관리":["korean"],"관습":["korean"],"관심":["korean"],"관점":["korean"],"관찰":["korean"],"광경":["korean"],"광고":["korean"],"광장":["korean"],"광주":["korean"],"괴로움":["korean"],"굉장히":["korean"],"교과서":["korean"],"교문":["korean"],"교복":["korean"],"교실":["korean"],"교양":["korean"],"교육":["korean"],"교장":["korean"],"교직":["korean"],"교통":["korean"],"교환":["korean"],"교훈":["korean"],"구경":["korean"],"구름":["korean"],"구멍":["korean"],"구별":["korean"],"구분":["korean"],"구석":["korean"],"구성":["korean"],"구속":["korean"],"구역":["korean"],"구입":["korean"],"구청":["korean"],"구체적":["korean"],"국가":["korean"],"국기":["korean"],"국내":["korean"],"국립":["korean"],"국물":["korean"],"국민":["korean"],"국수":["korean"],"국어":["korean"],"국왕":["korean"],"국적":["korean"],"국제":["korean"],"국회":["korean"],"군대":["korean"],"군사":["korean"],"군인":["korean"],"궁극적":["korean"],"권리":["korean"],"권위":["korean"],"권투":["korean"],"귀국":["korean"],"귀신":["korean"],"규정":["korean"],"규칙":["korean"],"균형":["korean"],"그날":["korean"],"그냥":["korean"],"그늘":["korean"],"그러나":["korean"],"그룹":["korean"],"그릇":["korean"],"그림":["korean"],"그제서야":["korean"],"그토록":["korean"],"극복":["korean"],"극히":["korean"],"근거":["korean"],"근교":["korean"],"근래":["korean"],"근로":["korean"],"근무":["korean"],"근본":["korean"],"근원":["korean"],"근육":["korean"],"근처":["korean"],"글씨":["korean"],"글자":["korean"],"금강산":["korean"],"금고":["korean"],"금년":["korean"],"금메달":["korean"],"금액":["korean"],"금연":["korean"],"금요일":["korean"],"금지":["korean"],"긍정적":["korean"],"기간":["korean"],"기관":["korean"],"기념":["korean"],"기능":["korean"],"기독교":["korean"],"기둥":["korean"],"기록":["korean"],"기름":["korean"],"기법":["korean"],"기본":["korean"],"기분":["korean"],"기쁨":["korean"],"기숙사":["korean"],"기술":["korean"],"기억":["korean"],"기업":["korean"],"기온":["korean"],"기운":["korean"],"기원":["korean"],"기적":["korean"],"기준":["korean"],"기침":["korean"],"기혼":["korean"],"기획":["korean"],"긴급":["korean"],"긴장":["korean"],"길이":["korean"],"김밥":["korean"],"김치":["korean"],"김포공항":["korean"],"깍두기":["korean"],"깜빡":["korean"],"깨달음":["korean"],"깨소금":["korean"],"껍질":["korean"],"꼭대기":["korean"],"꽃잎":["korean"],"나들이":["korean"],"나란히":["korean"],"나머지":["korean"],"나물":["korean"],"나침반":["korean"],"나흘":["korean"],"낙엽":["korean"],"난방":["korean"],"날개":["korean"],"날씨":["korean"],"날짜":["korean"],"남녀":["korean"],"남대문":["korean"],"남매":["korean"],"남산":["korean"],"남자":["korean"],"남편":["korean"],"남학생":["korean"],"낭비":["korean"],"낱말":["korean"],"내년":["korean"],"내용":["korean"],"내일":["korean"],"냄비":["korean"],"냄새":["korean"],"냇물":["korean"],"냉동":["korean"],"냉면":["korean"],"냉방":["korean"],"냉장고":["korean"],"넥타이":["korean"],"넷째":["korean"],"노동":["korean"],"노란색":["korean"],"노력":["korean"],"노인":["korean"],"녹음":["korean"],"녹차":["korean"],"녹화":["korean"],"논리":["korean"],"논문":["korean"],"논쟁":["korean"],"놀이":["korean"],"농구":["korean"],"농담":["korean"],"농민":["korean"],"농부":["korean"],"농업":["korean"],"농장":["korean"],"농촌":["korean"],"높이":["korean"],"눈동자":["korean"],"눈물":["korean"],"눈썹":["korean"],"뉴욕":["korean"],"느낌":["korean"],"늑대":["korean"],"능동적":["korean"],"능력":["korean"],"다방":["korean"],"다양성":["korean"],"다음":["korean"],"다이어트":["korean"],"다행":["korean"],"단계":["korean"],"단골":["korean"],"단독":["korean"],"단맛":["korean"],"단순":["korean"],"단어":["korean"],"단위":["korean"],"단점":["korean"],"단체":["korean"],"단추":["korean"],"단편":["korean"],"단풍":["korean"],"달걀":["korean"],"달러":["korean"],"달력":["korean"],"달리":["korean"],"닭고기":["korean"],"담당":["korean"],"담배":["korean"],"담요":["korean"],"담임":["korean"],"답변":["korean"],"답장":["korean"],"당근":["korean"],"당분간":["korean"],"당연히":["korean"],"당장":["korean"],"대규모":["korean"],"대낮":["korean"],"대단히":["korean"],"대답":["korean"],"대도시":["korean"],"대략":["korean"],"대량":["korean"],"대륙":["korean"],"대문":["korean"],"대부분":["korean"],"대신":["korean"],"대응":["korean"],"대장":["korean"],"대전":["korean"],"대접":["korean"],"대중":["korean"],"대책":["korean"],"대출":["korean"],"대충":["korean"],"대통령":["korean"],"대학":["korean"],"대한민국":["korean"],"대합실":["korean"],"대형":["korean"],"덩어리":["korean"],"데이트":["korean"],"도대체":["korean"],"도덕":["korean"],"도둑":["korean"],"도망":["korean"],"도서관":["korean"],"도심":["korean"],"도움":["korean"],"도입":["korean"],"도자기":["korean"],"도저히":["korean"],"도전":["korean"],"도중":["korean"],"도착":["korean"],"독감":["korean"],"독립":["korean"],"독서":["korean"],"독일":["korean"],"독창적":["korean"],"동화책":["korean"],"뒷모습":["korean"],"뒷산":["korean"],"딸아이":["korean"],"마누라":["korean"],"마늘":["korean"],"마당":["korean"],"마라톤":["korean"],"마련":["korean"],"마무리":["korean"],"마사지":["korean"],"마약":["korean"],"마요네즈":["korean"],"마을":["korean"],"마음":["korean"],"마이크":["korean"],"마중":["korean"],"마지막":["korean"],"마찬가지":["korean"],"마찰":["korean"],"마흔":["korean"],"막걸리":["korean"],"막내":["korean"],"막상":["korean"],"만남":["korean"],"만두":["korean"],"만세":["korean"],"만약":["korean"],"만일":["korean"],"만점":["korean"],"만족":["korean"],"만화":["korean"],"많이":["korean"],"말기":["korean"],"말씀":["korean"],"말투":["korean"],"맘대로":["korean"],"망원경":["korean"],"매년":["korean"],"매달":["korean"],"매력":["korean"],"매번":["korean"],"매스컴":["korean"],"매일":["korean"],"매장":["korean"],"맥주":["korean"],"먹이":["korean"],"먼저":["korean"],"먼지":["korean"],"멀리":["korean"],"메일":["korean"],"며느리":["korean"],"며칠":["korean"],"면담":["korean"],"멸치":["korean"],"명단":["korean"],"명령":["korean"],"명예":["korean"],"명의":["korean"],"명절":["korean"],"명칭":["korean"],"명함":["korean"],"모금":["korean"],"모니터":["korean"],"모델":["korean"],"모든":["korean"],"모범":["korean"],"모습":["korean"],"모양":["korean"],"모임":["korean"],"모조리":["korean"],"모집":["korean"],"모퉁이":["korean"],"목걸이":["korean"],"목록":["korean"],"목사":["korean"],"목소리":["korean"],"목숨":["korean"],"목적":["korean"],"목표":["korean"],"몰래":["korean"],"몸매":["korean"],"몸무게":["korean"],"몸살":["korean"],"몸속":["korean"],"몸짓":["korean"],"몸통":["korean"],"몹시":["korean"],"무관심":["korean"],"무궁화":["korean"],"무더위":["korean"],"무덤":["korean"],"무릎":["korean"],"무슨":["korean"],"무엇":["korean"],"무역":["korean"],"무용":["korean"],"무조건":["korean"],"무지개":["korean"],"무척":["korean"],"문구":["korean"],"문득":["korean"],"문법":["korean"],"문서":["korean"],"문제":["korean"],"문학":["korean"],"문화":["korean"],"물가":["korean"],"물건":["korean"],"물결":["korean"],"물고기":["korean"],"물론":["korean"],"물리학":["korean"],"물음":["korean"],"물질":["korean"],"물체":["korean"],"미국":["korean"],"미디어":["korean"],"미사일":["korean"],"미술":["korean"],"미역":["korean"],"미용실":["korean"],"미움":["korean"],"미인":["korean"],"미팅":["korean"],"미혼":["korean"],"민간":["korean"],"민족":["korean"],"민주":["korean"],"믿음":["korean"],"밀가루":["korean"],"밀리미터":["korean"],"밑바닥":["korean"],"바가지":["korean"],"바구니":["korean"],"바나나":["korean"],"바늘":["korean"],"바닥":["korean"],"바닷가":["korean"],"바람":["korean"],"바이러스":["korean"],"바탕":["korean"],"박물관":["korean"],"박사":["korean"],"박수":["korean"],"반대":["korean"],"반드시":["korean"],"반말":["korean"],"반발":["korean"],"반성":["korean"],"반응":["korean"],"반장":["korean"],"반죽":["korean"],"반지":["korean"],"반찬":["korean"],"받침":["korean"],"발가락":["korean"],"발걸음":["korean"],"발견":["korean"],"발달":["korean"],"발레":["korean"],"발목":["korean"],"발바닥":["korean"],"발생":["korean"],"발음":["korean"],"발자국":["korean"],"발전":["korean"],"발톱":["korean"],"발표":["korean"],"밤하늘":["korean"],"밥그릇":["korean"],"밥맛":["korean"],"밥상":["korean"],"밥솥":["korean"],"방금":["korean"],"방면":["korean"],"방문":["korean"],"방바닥":["korean"],"방법":["korean"],"방송":["korean"],"방식":["korean"],"방안":["korean"],"방울":["korean"],"방지":["korean"],"방학":["korean"],"방해":["korean"],"방향":["korean"],"배경":["korean"],"배꼽":["korean"],"배달":["korean"],"배드민턴":["korean"],"백두산":["korean"],"백색":["korean"],"백성":["korean"],"백인":["korean"],"백제":["korean"],"백화점":["korean"],"버릇":["korean"],"버섯":["korean"],"버튼":["korean"],"번개":["korean"],"번역":["korean"],"번지":["korean"],"번호":["korean"],"벌금":["korean"],"벌레":["korean"],"벌써":["korean"],"범위":["korean"],"범인":["korean"],"범죄":["korean"],"법률":["korean"],"법원":["korean"],"법적":["korean"],"법칙":["korean"],"베이징":["korean"],"벨트":["korean"],"변경":["korean"],"변동":["korean"],"변명":["korean"],"변신":["korean"],"변호사":["korean"],"변화":["korean"],"별도":["korean"],"별명":["korean"],"별일":["korean"],"병실":["korean"],"병아리":["korean"],"병원":["korean"],"보관":["korean"],"보너스":["korean"],"보라색":["korean"],"보람":["korean"],"보름":["korean"],"보상":["korean"],"보안":["korean"],"보자기":["korean"],"보장":["korean"],"보전":["korean"],"보존":["korean"],"보통":["korean"],"보편적":["korean"],"보험":["korean"],"복도":["korean"],"복사":["korean"],"복숭아":["korean"],"복습":["korean"],"볶음":["korean"],"본격적":["korean"],"본래":["korean"],"본부":["korean"],"본사":["korean"],"본성":["korean"],"본인":["korean"],"본질":["korean"],"볼펜":["korean"],"봉사":["korean"],"봉지":["korean"],"봉투":["korean"],"부근":["korean"],"부끄러움":["korean"],"부담":["korean"],"부동산":["korean"],"부문":["korean"],"부분":["korean"],"부산":["korean"],"부상":["korean"],"부엌":["korean"],"부인":["korean"],"부작용":["korean"],"부장":["korean"],"부정":["korean"],"부족":["korean"],"부지런히":["korean"],"부친":["korean"],"부탁":["korean"],"부품":["korean"],"부회장":["korean"],"북부":["korean"],"북한":["korean"],"분노":["korean"],"분량":["korean"],"분리":["korean"],"분명":["korean"],"분석":["korean"],"분야":["korean"],"분위기":["korean"],"분필":["korean"],"분홍색":["korean"],"불고기":["korean"],"불과":["korean"],"불교":["korean"],"불꽃":["korean"],"불만":["korean"],"불법":["korean"],"불빛":["korean"],"불안":["korean"],"불이익":["korean"],"불행":["korean"],"브랜드":["korean"],"비극":["korean"],"비난":["korean"],"비닐":["korean"],"비둘기":["korean"],"비디오":["korean"],"비로소":["korean"],"비만":["korean"],"비명":["korean"],"비밀":["korean"],"비바람":["korean"],"비빔밥":["korean"],"비상":["korean"],"비용":["korean"],"비율":["korean"],"비중":["korean"],"비타민":["korean"],"비판":["korean"],"빌딩":["korean"],"빗물":["korean"],"빗방울":["korean"],"빗줄기":["korean"],"빛깔":["korean"],"빨간색":["korean"],"빨래":["korean"],"빨리":["korean"],"사건":["korean"],"사계절":["korean"],"사나이":["korean"],"사냥":["korean"],"사람":["korean"],"사랑":["korean"],"사립":["korean"],"사모님":["korean"],"사물":["korean"],"사방":["korean"],"사상":["korean"],"사생활":["korean"],"사설":["korean"],"사슴":["korean"],"사실":["korean"],"사업":["korean"],"사용":["korean"],"사월":["korean"],"사장":["korean"],"사전":["korean"],"사진":["korean"],"사촌":["korean"],"사춘기":["korean"],"사탕":["korean"],"사투리":["korean"],"사흘":["korean"],"산길":["korean"],"산부인과":["korean"],"산업":["korean"],"산책":["korean"],"살림":["korean"],"살인":["korean"],"살짝":["korean"],"삼계탕":["korean"],"삼국":["korean"],"삼십":["korean"],"삼월":["korean"],"삼촌":["korean"],"상관":["korean"],"상금":["korean"],"상대":["korean"],"상류":["korean"],"상반기":["korean"],"상상":["korean"],"상식":["korean"],"상업":["korean"],"상인":["korean"],"상자":["korean"],"상점":["korean"],"상처":["korean"],"상추":["korean"],"상태":["korean"],"상표":["korean"],"상품":["korean"],"상황":["korean"],"새벽":["korean"],"색깔":["korean"],"색연필":["korean"],"생각":["korean"],"생명":["korean"],"생물":["korean"],"생방송":["korean"],"생산":["korean"],"생선":["korean"],"생신":["korean"],"생일":["korean"],"생활":["korean"],"서랍":["korean"],"서른":["korean"],"서명":["korean"],"서민":["korean"],"서비스":["korean"],"서양":["korean"],"서울":["korean"],"서적":["korean"],"서점":["korean"],"서쪽":["korean"],"서클":["korean"],"석사":["korean"],"석유":["korean"],"선거":["korean"],"선물":["korean"],"선배":["korean"],"선생":["korean"],"선수":["korean"],"선원":["korean"],"선장":["korean"],"선전":["korean"],"선택":["korean"],"선풍기":["korean"],"설거지":["korean"],"설날":["korean"],"설렁탕":["korean"],"설명":["korean"],"설문":["korean"],"설사":["korean"],"설악산":["korean"],"설치":["korean"],"설탕":["korean"],"섭씨":["korean"],"성공":["korean"],"성당":["korean"],"성명":["korean"],"성별":["korean"],"성인":["korean"],"성장":["korean"],"성적":["korean"],"성질":["korean"],"성함":["korean"],"세금":["korean"],"세미나":["korean"],"세상":["korean"],"세월":["korean"],"세종대왕":["korean"],"세탁":["korean"],"센터":["korean"],"센티미터":["korean"],"셋째":["korean"],"소규모":["korean"],"소극적":["korean"],"소금":["korean"],"소나기":["korean"],"소년":["korean"],"소득":["korean"],"소망":["korean"],"소문":["korean"],"소설":["korean"],"소속":["korean"],"소아과":["korean"],"소용":["korean"],"소원":["korean"],"소음":["korean"],"소중히":["korean"],"소지품":["korean"],"소질":["korean"],"소풍":["korean"],"소형":["korean"],"속담":["korean"],"속도":["korean"],"속옷":["korean"],"손가락":["korean"],"손길":["korean"],"손녀":["korean"],"손님":["korean"],"손등":["korean"],"손목":["korean"],"손뼉":["korean"],"손실":["korean"],"손질":["korean"],"손톱":["korean"],"손해":["korean"],"솔직히":["korean"],"솜씨":["korean"],"송아지":["korean"],"송이":["korean"],"송편":["korean"],"쇠고기":["korean"],"쇼핑":["korean"],"수건":["korean"],"수년":["korean"],"수단":["korean"],"수돗물":["korean"],"수동적":["korean"],"수면":["korean"],"수명":["korean"],"수박":["korean"],"수상":["korean"],"수석":["korean"],"수술":["korean"],"수시로":["korean"],"수업":["korean"],"수염":["korean"],"수영":["korean"],"수입":["korean"],"수준":["korean"],"수집":["korean"],"수출":["korean"],"수컷":["korean"],"수필":["korean"],"수학":["korean"],"수험생":["korean"],"수화기":["korean"],"숙녀":["korean"],"숙소":["korean"],"숙제":["korean"],"순간":["korean"],"순서":["korean"],"순수":["korean"],"순식간":["korean"],"순위":["korean"],"숟가락":["korean"],"술병":["korean"],"술집":["korean"],"숫자":["korean"],"스님":["korean"],"스물":["korean"],"스스로":["korean"],"스승":["korean"],"스웨터":["korean"],"스위치":["korean"],"스케이트":["korean"],"스튜디오":["korean"],"스트레스":["korean"],"스포츠":["korean"],"슬쩍":["korean"],"슬픔":["korean"],"습관":["korean"],"습기":["korean"],"승객":["korean"],"승리":["korean"],"승부":["korean"],"승용차":["korean"],"승진":["korean"],"시각":["korean"],"시간":["korean"],"시골":["korean"],"시금치":["korean"],"시나리오":["korean"],"시댁":["korean"],"시리즈":["korean"],"시멘트":["korean"],"시민":["korean"],"시부모":["korean"],"시선":["korean"],"시설":["korean"],"시스템":["korean"],"시아버지":["korean"],"시어머니":["korean"],"시월":["korean"],"시인":["korean"],"시일":["korean"],"시작":["korean"],"시장":["korean"],"시절":["korean"],"시점":["korean"],"시중":["korean"],"시즌":["korean"],"시집":["korean"],"시청":["korean"],"시합":["korean"],"시험":["korean"],"식구":["korean"],"식기":["korean"],"식당":["korean"],"식량":["korean"],"식료품":["korean"],"식물":["korean"],"식빵":["korean"],"식사":["korean"],"식생활":["korean"],"식초":["korean"],"식탁":["korean"],"식품":["korean"],"신고":["korean"],"신규":["korean"],"신념":["korean"],"신문":["korean"],"신발":["korean"],"신비":["korean"],"신사":["korean"],"신세":["korean"],"신용":["korean"],"신제품":["korean"],"신청":["korean"],"신체":["korean"],"신화":["korean"],"실감":["korean"],"실내":["korean"],"실력":["korean"],"실례":["korean"],"실망":["korean"],"실수":["korean"],"실습":["korean"],"실시":["korean"],"실장":["korean"],"실정":["korean"],"실질적":["korean"],"실천":["korean"],"실체":["korean"],"실컷":["korean"],"실태":["korean"],"실패":["korean"],"실험":["korean"],"실현":["korean"],"심리":["korean"],"심부름":["korean"],"심사":["korean"],"심장":["korean"],"심정":["korean"],"심판":["korean"],"쌍둥이":["korean"],"씨름":["korean"],"씨앗":["korean"],"아가씨":["korean"],"아나운서":["korean"],"아드님":["korean"],"아들":["korean"],"아쉬움":["korean"],"아스팔트":["korean"],"아시아":["korean"],"아울러":["korean"],"아저씨":["korean"],"아줌마":["korean"],"아직":["korean"],"아침":["korean"],"아파트":["korean"],"아프리카":["korean"],"아픔":["korean"],"아홉":["korean"],"아흔":["korean"],"악기":["korean"],"악몽":["korean"],"악수":["korean"],"안개":["korean"],"안경":["korean"],"안과":["korean"],"안내":["korean"],"안녕":["korean"],"안동":["korean"],"안방":["korean"],"안부":["korean"],"안주":["korean"],"알루미늄":["korean"],"알코올":["korean"],"암시":["korean"],"암컷":["korean"],"압력":["korean"],"앞날":["korean"],"앞문":["korean"],"애인":["korean"],"애정":["korean"],"액수":["korean"],"앨범":["korean"],"야간":["korean"],"야단":["korean"],"야옹":["korean"],"약간":["korean"],"약국":["korean"],"약속":["korean"],"약수":["korean"],"약점":["korean"],"약품":["korean"],"약혼녀":["korean"],"양념":["korean"],"양력":["korean"],"양말":["korean"],"양배추":["korean"],"양주":["korean"],"양파":["korean"],"어둠":["korean"],"어려움":["korean"],"어른":["korean"],"어젯밤":["korean"],"어쨌든":["korean"],"어쩌다가":["korean"],"어쩐지":["korean"],"언니":["korean"],"언덕":["korean"],"언론":["korean"],"언어":["korean"],"얼굴":["korean"],"얼른":["korean"],"얼음":["korean"],"얼핏":["korean"],"엄마":["korean"],"업무":["korean"],"업종":["korean"],"업체":["korean"],"엉덩이":["korean"],"엉망":["korean"],"엉터리":["korean"],"엊그제":["korean"],"에너지":["korean"],"에어컨":["korean"],"엔진":["korean"],"여건":["korean"],"여고생":["korean"],"여관":["korean"],"여군":["korean"],"여권":["korean"],"여대생":["korean"],"여덟":["korean"],"여동생":["korean"],"여든":["korean"],"여론":["korean"],"여름":["korean"],"여섯":["korean"],"여성":["korean"],"여왕":["korean"],"여인":["korean"],"여전히":["korean"],"여직원":["korean"],"여학생":["korean"],"여행":["korean"],"역사":["korean"],"역시":["korean"],"역할":["korean"],"연결":["korean"],"연구":["korean"],"연극":["korean"],"연기":["korean"],"연락":["korean"],"연설":["korean"],"연세":["korean"],"연속":["korean"],"연습":["korean"],"연애":["korean"],"연예인":["korean"],"연인":["korean"],"연장":["korean"],"연주":["korean"],"연출":["korean"],"연필":["korean"],"연합":["korean"],"연휴":["korean"],"열기":["korean"],"열매":["korean"],"열쇠":["korean"],"열심히":["korean"],"열정":["korean"],"열차":["korean"],"열흘":["korean"],"염려":["korean"],"엽서":["korean"],"영국":["korean"],"영남":["korean"],"영상":["korean"],"영양":["korean"],"영역":["korean"],"영웅":["korean"],"영원히":["korean"],"영하":["korean"],"영향":["korean"],"영혼":["korean"],"영화":["korean"],"옆구리":["korean"],"옆방":["korean"],"옆집":["korean"],"예감":["korean"],"예금":["korean"],"예방":["korean"],"예산":["korean"],"예상":["korean"],"예선":["korean"],"예술":["korean"],"예습":["korean"],"예식장":["korean"],"예약":["korean"],"예전":["korean"],"예절":["korean"],"예정":["korean"],"예컨대":["korean"],"옛날":["korean"],"오늘":["korean"],"오락":["korean"],"오랫동안":["korean"],"오렌지":["korean"],"오로지":["korean"],"오른발":["korean"],"오븐":["korean"],"오십":["korean"],"오염":["korean"],"오월":["korean"],"오전":["korean"],"오직":["korean"],"오징어":["korean"],"오페라":["korean"],"오피스텔":["korean"],"오히려":["korean"],"옥상":["korean"],"옥수수":["korean"],"온갖":["korean"],"온라인":["korean"],"온몸":["korean"],"온종일":["korean"],"온통":["korean"],"올가을":["korean"],"올림픽":["korean"],"올해":["korean"],"옷차림":["korean"],"와이셔츠":["korean"],"와인":["korean"],"완성":["korean"],"완전":["korean"],"왕비":["korean"],"왕자":["korean"],"왜냐하면":["korean"],"왠지":["korean"],"외갓집":["korean"],"외국":["korean"],"외로움":["korean"],"외삼촌":["korean"],"외출":["korean"],"외침":["korean"],"외할머니":["korean"],"왼발":["korean"],"왼손":["korean"],"왼쪽":["korean"],"요금":["korean"],"요일":["korean"],"요즘":["korean"],"요청":["korean"],"용기":["korean"],"용서":["korean"],"용어":["korean"],"우산":["korean"],"우선":["korean"],"우승":["korean"],"우연히":["korean"],"우정":["korean"],"우체국":["korean"],"우편":["korean"],"운동":["korean"],"운명":["korean"],"운반":["korean"],"운전":["korean"],"운행":["korean"],"울산":["korean"],"울음":["korean"],"움직임":["korean"],"웃어른":["korean"],"웃음":["korean"],"워낙":["korean"],"원고":["korean"],"원래":["korean"],"원서":["korean"],"원숭이":["korean"],"원인":["korean"],"원장":["korean"],"원피스":["korean"],"월급":["korean"],"월드컵":["korean"],"월세":["korean"],"월요일":["korean"],"웨이터":["korean"],"위반":["korean"],"위법":["korean"],"위성":["korean"],"위원":["korean"],"위험":["korean"],"위협":["korean"],"윗사람":["korean"],"유난히":["korean"],"유럽":["korean"],"유명":["korean"],"유물":["korean"],"유산":["korean"],"유적":["korean"],"유치원":["korean"],"유학":["korean"],"유행":["korean"],"유형":["korean"],"육군":["korean"],"육상":["korean"],"육십":["korean"],"육체":["korean"],"은행":["korean"],"음력":["korean"],"음료":["korean"],"음반":["korean"],"음성":["korean"],"음식":["korean"],"음악":["korean"],"음주":["korean"],"의견":["korean"],"의논":["korean"],"의문":["korean"],"의복":["korean"],"의식":["korean"],"의심":["korean"],"의외로":["korean"],"의욕":["korean"],"의원":["korean"],"의학":["korean"],"이것":["korean"],"이곳":["korean"],"이념":["korean"],"이놈":["korean"],"이달":["korean"],"이대로":["korean"],"이동":["korean"],"이렇게":["korean"],"이력서":["korean"],"이론적":["korean"],"이름":["korean"],"이민":["korean"],"이발소":["korean"],"이별":["korean"],"이불":["korean"],"이빨":["korean"],"이상":["korean"],"이성":["korean"],"이슬":["korean"],"이야기":["korean"],"이용":["korean"],"이웃":["korean"],"이월":["korean"],"이윽고":["korean"],"이익":["korean"],"이전":["korean"],"이중":["korean"],"이튿날":["korean"],"이틀":["korean"],"이혼":["korean"],"인간":["korean"],"인격":["korean"],"인공":["korean"],"인구":["korean"],"인근":["korean"],"인기":["korean"],"인도":["korean"],"인류":["korean"],"인물":["korean"],"인생":["korean"],"인쇄":["korean"],"인연":["korean"],"인원":["korean"],"인재":["korean"],"인종":["korean"],"인천":["korean"],"인체":["korean"],"인터넷":["korean"],"인하":["korean"],"인형":["korean"],"일곱":["korean"],"일기":["korean"],"일단":["korean"],"일대":["korean"],"일등":["korean"],"일반":["korean"],"일본":["korean"],"일부":["korean"],"일상":["korean"],"일생":["korean"],"일손":["korean"],"일요일":["korean"],"일월":["korean"],"일정":["korean"],"일종":["korean"],"일주일":["korean"],"일찍":["korean"],"일체":["korean"],"일치":["korean"],"일행":["korean"],"일회용":["korean"],"임금":["korean"],"임무":["korean"],"입대":["korean"],"입력":["korean"],"입맛":["korean"],"입사":["korean"],"입술":["korean"],"입시":["korean"],"입원":["korean"],"입장":["korean"],"입학":["korean"],"자가용":["korean"],"자격":["korean"],"자극":["korean"],"자동":["korean"],"자랑":["korean"],"자부심":["korean"],"자식":["korean"],"자신":["korean"],"자연":["korean"],"자원":["korean"],"자율":["korean"],"자전거":["korean"],"자정":["korean"],"자존심":["korean"],"자판":["korean"],"작가":["korean"],"작년":["korean"],"작성":["korean"],"작업":["korean"],"작용":["korean"],"작은딸":["korean"],"작품":["korean"],"잔디":["korean"],"잔뜩":["korean"],"잔치":["korean"],"잘못":["korean"],"잠깐":["korean"],"잠수함":["korean"],"잠시":["korean"],"잠옷":["korean"],"잠자리":["korean"],"잡지":["korean"],"장관":["korean"],"장군":["korean"],"장기간":["korean"],"장래":["korean"],"장례":["korean"],"장르":["korean"],"장마":["korean"],"장면":["korean"],"장모":["korean"],"장미":["korean"],"장비":["korean"],"장사":["korean"],"장소":["korean"],"장식":["korean"],"장애인":["korean"],"장인":["korean"],"장점":["korean"],"장차":["korean"],"장학금":["korean"],"재능":["korean"],"재빨리":["korean"],"재산":["korean"],"재생":["korean"],"재작년":["korean"],"재정":["korean"],"재채기":["korean"],"재판":["korean"],"재학":["korean"],"재활용":["korean"],"저것":["korean"],"저고리":["korean"],"저곳":["korean"],"저녁":["korean"],"저런":["korean"],"저렇게":["korean"],"저번":["korean"],"저울":["korean"],"저절로":["korean"],"저축":["korean"],"적극":["korean"],"적당히":["korean"],"적성":["korean"],"적용":["korean"],"적응":["korean"],"전개":["korean"],"전공":["korean"],"전기":["korean"],"전달":["korean"],"전라도":["korean"],"전망":["korean"],"전문":["korean"],"전반":["korean"],"전부":["korean"],"전세":["korean"],"전시":["korean"],"전용":["korean"],"전자":["korean"],"전쟁":["korean"],"전주":["korean"],"전철":["korean"],"전체":["korean"],"전통":["korean"],"전혀":["korean"],"전후":["korean"],"절대":["korean"],"절망":["korean"],"절반":["korean"],"절약":["korean"],"절차":["korean"],"점검":["korean"],"점수":["korean"],"점심":["korean"],"점원":["korean"],"점점":["korean"],"점차":["korean"],"접근":["korean"],"접시":["korean"],"접촉":["korean"],"젓가락":["korean"],"정거장":["korean"],"정도":["korean"],"정류장":["korean"],"정리":["korean"],"정말":["korean"],"정면":["korean"],"정문":["korean"],"정반대":["korean"],"정보":["korean"],"정부":["korean"],"정비":["korean"],"정상":["korean"],"정성":["korean"],"정오":["korean"],"정원":["korean"],"정장":["korean"],"정지":["korean"],"정치":["korean"],"정확히":["korean"],"제공":["korean"],"제과점":["korean"],"제대로":["korean"],"제목":["korean"],"제발":["korean"],"제법":["korean"],"제삿날":["korean"],"제안":["korean"],"제일":["korean"],"제작":["korean"],"제주도":["korean"],"제출":["korean"],"제품":["korean"],"제한":["korean"],"조각":["korean"],"조건":["korean"],"조금":["korean"],"조깅":["korean"],"조명":["korean"],"조미료":["korean"],"조상":["korean"],"조선":["korean"],"조용히":["korean"],"조절":["korean"],"조정":["korean"],"조직":["korean"],"존댓말":["korean"],"존재":["korean"],"졸업":["korean"],"졸음":["korean"],"종교":["korean"],"종로":["korean"],"종류":["korean"],"종소리":["korean"],"종업원":["korean"],"종종":["korean"],"종합":["korean"],"좌석":["korean"],"죄인":["korean"],"주관적":["korean"],"주름":["korean"],"주말":["korean"],"주머니":["korean"],"주먹":["korean"],"주문":["korean"],"주민":["korean"],"주방":["korean"],"주변":["korean"],"주식":["korean"],"주인":["korean"],"주일":["korean"],"주장":["korean"],"주전자":["korean"],"주택":["korean"],"준비":["korean"],"줄거리":["korean"],"줄기":["korean"],"줄무늬":["korean"],"중간":["korean"],"중계방송":["korean"],"중국":["korean"],"중년":["korean"],"중단":["korean"],"중독":["korean"],"중반":["korean"],"중부":["korean"],"중세":["korean"],"중소기업":["korean"],"중순":["korean"],"중앙":["korean"],"중요":["korean"],"중학교":["korean"],"즉석":["korean"],"즉시":["korean"],"즐거움":["korean"],"증가":["korean"],"증거":["korean"],"증권":["korean"],"증상":["korean"],"증세":["korean"],"지각":["korean"],"지갑":["korean"],"지경":["korean"],"지극히":["korean"],"지금":["korean"],"지급":["korean"],"지능":["korean"],"지름길":["korean"],"지리산":["korean"],"지방":["korean"],"지붕":["korean"],"지식":["korean"],"지역":["korean"],"지우개":["korean"],"지원":["korean"],"지적":["korean"],"지점":["korean"],"지진":["korean"],"지출":["korean"],"직선":["korean"],"직업":["korean"],"직원":["korean"],"직장":["korean"],"진급":["korean"],"진동":["korean"],"진로":["korean"],"진료":["korean"],"진리":["korean"],"진짜":["korean"],"진찰":["korean"],"진출":["korean"],"진통":["korean"],"진행":["korean"],"질문":["korean"],"질병":["korean"],"질서":["korean"],"짐작":["korean"],"집단":["korean"],"집안":["korean"],"집중":["korean"],"짜증":["korean"],"찌꺼기":["korean"],"차남":["korean"],"차라리":["korean"],"차량":["korean"],"차림":["korean"],"차별":["korean"],"차선":["korean"],"차츰":["korean"],"착각":["korean"],"찬물":["korean"],"찬성":["korean"],"참가":["korean"],"참기름":["korean"],"참새":["korean"],"참석":["korean"],"참여":["korean"],"참외":["korean"],"참조":["korean"],"찻잔":["korean"],"창가":["korean"],"창고":["korean"],"창구":["korean"],"창문":["korean"],"창밖":["korean"],"창작":["korean"],"창조":["korean"],"채널":["korean"],"채점":["korean"],"책가방":["korean"],"책방":["korean"],"책상":["korean"],"책임":["korean"],"챔피언":["korean"],"처벌":["korean"],"처음":["korean"],"천국":["korean"],"천둥":["korean"],"천장":["korean"],"천재":["korean"],"천천히":["korean"],"철도":["korean"],"철저히":["korean"],"철학":["korean"],"첫날":["korean"],"첫째":["korean"],"청년":["korean"],"청바지":["korean"],"청소":["korean"],"청춘":["korean"],"체계":["korean"],"체력":["korean"],"체온":["korean"],"체육":["korean"],"체중":["korean"],"체험":["korean"],"초등학생":["korean"],"초반":["korean"],"초밥":["korean"],"초상화":["korean"],"초순":["korean"],"초여름":["korean"],"초원":["korean"],"초저녁":["korean"],"초점":["korean"],"초청":["korean"],"초콜릿":["korean"],"촛불":["korean"],"총각":["korean"],"총리":["korean"],"총장":["korean"],"촬영":["korean"],"최근":["korean"],"최상":["korean"],"최선":["korean"],"최신":["korean"],"최악":["korean"],"최종":["korean"],"추석":["korean"],"추억":["korean"],"추진":["korean"],"추천":["korean"],"추측":["korean"],"축구":["korean"],"축소":["korean"],"축제":["korean"],"축하":["korean"],"출근":["korean"],"출발":["korean"],"출산":["korean"],"출신":["korean"],"출연":["korean"],"출입":["korean"],"출장":["korean"],"출판":["korean"],"충격":["korean"],"충고":["korean"],"충돌":["korean"],"충분히":["korean"],"충청도":["korean"],"취업":["korean"],"취직":["korean"],"취향":["korean"],"치약":["korean"],"친구":["korean"],"친척":["korean"],"칠십":["korean"],"칠월":["korean"],"칠판":["korean"],"침대":["korean"],"침묵":["korean"],"침실":["korean"],"칫솔":["korean"],"칭찬":["korean"],"카메라":["korean"],"카운터":["korean"],"칼국수":["korean"],"캐릭터":["korean"],"캠퍼스":["korean"],"캠페인":["korean"],"커튼":["korean"],"컨디션":["korean"],"컬러":["korean"],"컴퓨터":["korean"],"코끼리":["korean"],"코미디":["korean"],"콘서트":["korean"],"콜라":["korean"],"콤플렉스":["korean"],"콩나물":["korean"],"쾌감":["korean"],"쿠데타":["korean"],"크림":["korean"],"큰길":["korean"],"큰딸":["korean"],"큰소리":["korean"],"큰아들":["korean"],"큰어머니":["korean"],"큰일":["korean"],"큰절":["korean"],"클래식":["korean"],"클럽":["korean"],"킬로":["korean"],"타입":["korean"],"타자기":["korean"],"탁구":["korean"],"탁자":["korean"],"탄생":["korean"],"태권도":["korean"],"태양":["korean"],"태풍":["korean"],"택시":["korean"],"탤런트":["korean"],"터널":["korean"],"터미널":["korean"],"테니스":["korean"],"테스트":["korean"],"테이블":["korean"],"텔레비전":["korean"],"토론":["korean"],"토마토":["korean"],"토요일":["korean"],"통계":["korean"],"통과":["korean"],"통로":["korean"],"통신":["korean"],"통역":["korean"],"통일":["korean"],"통장":["korean"],"통제":["korean"],"통증":["korean"],"통합":["korean"],"통화":["korean"],"퇴근":["korean"],"퇴원":["korean"],"퇴직금":["korean"],"튀김":["korean"],"트럭":["korean"],"특급":["korean"],"특별":["korean"],"특성":["korean"],"특수":["korean"],"특징":["korean"],"특히":["korean"],"튼튼히":["korean"],"티셔츠":["korean"],"파란색":["korean"],"파일":["korean"],"파출소":["korean"],"판결":["korean"],"판단":["korean"],"판매":["korean"],"판사":["korean"],"팔십":["korean"],"팔월":["korean"],"팝송":["korean"],"패션":["korean"],"팩스":["korean"],"팩시밀리":["korean"],"팬티":["korean"],"퍼센트":["korean"],"페인트":["korean"],"편견":["korean"],"편의":["korean"],"편지":["korean"],"편히":["korean"],"평가":["korean"],"평균":["korean"],"평생":["korean"],"평소":["korean"],"평양":["korean"],"평일":["korean"],"평화":["korean"],"포스터":["korean"],"포인트":["korean"],"포장":["korean"],"포함":["korean"],"표면":["korean"],"표정":["korean"],"표준":["korean"],"표현":["korean"],"품목":["korean"],"품질":["korean"],"풍경":["korean"],"풍속":["korean"],"풍습":["korean"],"프랑스":["korean"],"프린터":["korean"],"플라스틱":["korean"],"피곤":["korean"],"피망":["korean"],"피아노":["korean"],"필름":["korean"],"필수":["korean"],"필요":["korean"],"필자":["korean"],"필통":["korean"],"핑계":["korean"],"하느님":["korean"],"하늘":["korean"],"하드웨어":["korean"],"하룻밤":["korean"],"하반기":["korean"],"하숙집":["korean"],"하순":["korean"],"하여튼":["korean"],"하지만":["korean"],"하천":["korean"],"하품":["korean"],"하필":["korean"],"학과":["korean"],"학교":["korean"],"학급":["korean"],"학기":["korean"],"학년":["korean"],"학력":["korean"],"학번":["korean"],"학부모":["korean"],"학비":["korean"],"학생":["korean"],"학술":["korean"],"학습":["korean"],"학용품":["korean"],"학원":["korean"],"학위":["korean"],"학자":["korean"],"학점":["korean"],"한계":["korean"],"한글":["korean"],"한꺼번에":["korean"],"한낮":["korean"],"한눈":["korean"],"한동안":["korean"],"한때":["korean"],"한라산":["korean"],"한마디":["korean"],"한문":["korean"],"한번":["korean"],"한복":["korean"],"한식":["korean"],"한여름":["korean"],"한쪽":["korean"],"할머니":["korean"],"할아버지":["korean"],"할인":["korean"],"함께":["korean"],"함부로":["korean"],"합격":["korean"],"합리적":["korean"],"항공":["korean"],"항구":["korean"],"항상":["korean"],"항의":["korean"],"해결":["korean"],"해군":["korean"],"해답":["korean"],"해당":["korean"],"해물":["korean"],"해석":["korean"],"해설":["korean"],"해수욕장":["korean"],"해안":["korean"],"핵심":["korean"],"핸드백":["korean"],"햄버거":["korean"],"햇볕":["korean"],"햇살":["korean"],"행동":["korean"],"행복":["korean"],"행사":["korean"],"행운":["korean"],"행위":["korean"],"향기":["korean"],"향상":["korean"],"향수":["korean"],"허락":["korean"],"허용":["korean"],"헬기":["korean"],"현관":["korean"],"현금":["korean"],"현대":["korean"],"현상":["korean"],"현실":["korean"],"현장":["korean"],"현재":["korean"],"현지":["korean"],"혈액":["korean"],"협력":["korean"],"형부":["korean"],"형사":["korean"],"형수":["korean"],"형식":["korean"],"형제":["korean"],"형태":["korean"],"형편":["korean"],"혜택":["korean"],"호기심":["korean"],"호남":["korean"],"호랑이":["korean"],"호박":["korean"],"호텔":["korean"],"호흡":["korean"],"혹시":["korean"],"홀로":["korean"],"홈페이지":["korean"],"홍보":["korean"],"홍수":["korean"],"홍차":["korean"],"화면":["korean"],"화분":["korean"],"화살":["korean"],"화요일":["korean"],"화장":["korean"],"화학":["korean"],"확보":["korean"],"확인":["korean"],"확장":["korean"],"확정":["korean"],"환갑":["korean"],"환경":["korean"],"환영":["korean"],"환율":["korean"],"환자":["korean"],"활기":["korean"],"활동":["korean"],"활발히":["korean"],"활용":["korean"],"활짝":["korean"],"회견":["korean"],"회관":["korean"],"회복":["korean"],"회색":["korean"],"회원":["korean"],"회장":["korean"],"회전":["korean"],"횟수":["korean"],"횡단보도":["korean"],"효율적":["korean"],"후반":["korean"],"후춧가루":["korean"],"훈련":["korean"],"훨씬":["korean"],"휴식":["korean"],"휴일":["korean"],"흉내":["korean"],"흐름":["korean"],"흑백":["korean"],"흑인":["korean"],"흔적":["korean"],"흔히":["korean"],"흥미":["korean"],"흥분":["korean"],"희곡":["korean"],"희망":["korean"],"희생":["korean"],"흰색":["korean"],"힘껏":["korean"],"abacate":["portuguese"],"abaixo":["portuguese"],"abalar":["portuguese"],"abater":["portuguese"],"abduzir":["portuguese"],"abelha":["portuguese"],"aberto":["portuguese"],"abismo":["portuguese"],"abotoar":["portuguese"],"abranger":["portuguese"],"abreviar":["portuguese"],"abrigar":["portuguese"],"abrupto":["portuguese"],"absinto":["portuguese"],"absoluto":["portuguese"],"absurdo":["portuguese"],"abutre":["portuguese"],"acabado":["portuguese"],"acalmar":["portuguese"],"acampar":["portuguese"],"acanhar":["portuguese"],"acaso":["portuguese"],"aceitar":["portuguese"],"acelerar":["portuguese"],"acenar":["portuguese"],"acervo":["portuguese"],"acessar":["portuguese"],"acetona":["portuguese"],"achatar":["portuguese"],"acidez":["portuguese"],"acima":["portuguese"],"acionado":["portuguese"],"acirrar":["portuguese"],"aclamar":["portuguese"],"aclive":["portuguese"],"acolhida":["portuguese"],"acomodar":["portuguese"],"acoplar":["portuguese"],"acordar":["portuguese"],"acumular":["portuguese"],"acusador":["portuguese"],"adaptar":["portuguese"],"adega":["portuguese"],"adentro":["portuguese"],"adepto":["portuguese"],"adequar":["portuguese"],"aderente":["portuguese"],"adesivo":["portuguese"],"adeus":["portuguese"],"adiante":["portuguese"],"aditivo":["portuguese"],"adjetivo":["portuguese"],"adjunto":["portuguese"],"admirar":["portuguese"],"adorar":["portuguese"],"adquirir":["portuguese"],"adubo":["portuguese"],"adverso":["portuguese"],"advogado":["portuguese"],"aeronave":["portuguese"],"afastar":["portuguese"],"aferir":["portuguese"],"afetivo":["portuguese"],"afinador":["portuguese"],"afivelar":["portuguese"],"aflito":["portuguese"],"afluente":["portuguese"],"afrontar":["portuguese"],"agachar":["portuguese"],"agarrar":["portuguese"],"agasalho":["portuguese"],"agenciar":["portuguese"],"agilizar":["portuguese"],"agiota":["portuguese"],"agitado":["portuguese"],"agora":["portuguese"],"agradar":["portuguese"],"agreste":["portuguese"],"agrupar":["portuguese"],"aguardar":["portuguese"],"agulha":["portuguese"],"ajoelhar":["portuguese"],"ajudar":["portuguese"],"ajustar":["portuguese"],"alameda":["portuguese"],"alarme":["portuguese"],"alastrar":["portuguese"],"alavanca":["portuguese"],"albergue":["portuguese"],"albino":["portuguese"],"alcatra":["portuguese"],"aldeia":["portuguese"],"alecrim":["portuguese"],"alegria":["portuguese"],"alertar":["portuguese"],"alface":["portuguese"],"alfinete":["portuguese"],"algum":["portuguese"],"alheio":["portuguese"],"aliar":["portuguese"],"alicate":["portuguese"],"alienar":["portuguese"],"alinhar":["portuguese"],"aliviar":["portuguese"],"almofada":["portuguese"],"alocar":["portuguese"],"alpiste":["portuguese"],"alterar":["portuguese"],"altitude":["portuguese"],"alucinar":["portuguese"],"alugar":["portuguese"],"aluno":["portuguese"],"alusivo":["portuguese"],"alvo":["portuguese"],"amaciar":["portuguese"],"amador":["portuguese"],"amarelo":["portuguese"],"amassar":["portuguese"],"ambas":["portuguese"],"ambiente":["portuguese"],"ameixa":["portuguese"],"amenizar":["portuguese"],"amido":["portuguese"],"amistoso":["portuguese"],"amizade":["portuguese"],"amolador":["portuguese"],"amontoar":["portuguese"],"amoroso":["portuguese"],"amostra":["portuguese"],"amparar":["portuguese"],"ampliar":["portuguese"],"ampola":["portuguese"],"anagrama":["portuguese"],"analisar":["portuguese"],"anarquia":["portuguese"],"anatomia":["portuguese"],"andaime":["portuguese"],"anel":["portuguese"],"anexo":["portuguese"],"angular":["portuguese"],"animar":["portuguese"],"anjo":["portuguese"],"anomalia":["portuguese"],"anotado":["portuguese"],"ansioso":["portuguese"],"anterior":["portuguese"],"anuidade":["portuguese"],"anunciar":["portuguese"],"anzol":["portuguese"],"apagador":["portuguese"],"apalpar":["portuguese"],"apanhado":["portuguese"],"apego":["portuguese"],"apelido":["portuguese"],"apertada":["portuguese"],"apesar":["portuguese"],"apetite":["portuguese"],"apito":["portuguese"],"aplauso":["portuguese"],"aplicada":["portuguese"],"apoio":["portuguese"],"apontar":["portuguese"],"aposta":["portuguese"],"aprendiz":["portuguese"],"aprovar":["portuguese"],"aquecer":["portuguese"],"arame":["portuguese"],"aranha":["portuguese"],"arara":["portuguese"],"arcada":["portuguese"],"ardente":["portuguese"],"areia":["portuguese"],"arejar":["portuguese"],"arenito":["portuguese"],"aresta":["portuguese"],"argiloso":["portuguese"],"argola":["portuguese"],"arma":["portuguese"],"arquivo":["portuguese"],"arraial":["portuguese"],"arrebate":["portuguese"],"arriscar":["portuguese"],"arroba":["portuguese"],"arrumar":["portuguese"],"arsenal":["portuguese"],"arterial":["portuguese"],"artigo":["portuguese"],"arvoredo":["portuguese"],"asfaltar":["portuguese"],"asilado":["portuguese"],"aspirar":["portuguese"],"assador":["portuguese"],"assinar":["portuguese"],"assoalho":["portuguese"],"assunto":["portuguese"],"astral":["portuguese"],"atacado":["portuguese"],"atadura":["portuguese"],"atalho":["portuguese"],"atarefar":["portuguese"],"atear":["portuguese"],"atender":["portuguese"],"aterro":["portuguese"],"ateu":["portuguese"],"atingir":["portuguese"],"atirador":["portuguese"],"ativo":["portuguese"],"atoleiro":["portuguese"],"atracar":["portuguese"],"atrevido":["portuguese"],"atriz":["portuguese"],"atual":["portuguese"],"atum":["portuguese"],"auditor":["portuguese"],"aumentar":["portuguese"],"aura":["portuguese"],"aurora":["portuguese"],"autismo":["portuguese"],"autoria":["portuguese"],"autuar":["portuguese"],"avaliar":["portuguese"],"avante":["portuguese"],"avaria":["portuguese"],"avental":["portuguese"],"avesso":["portuguese"],"aviador":["portuguese"],"avisar":["portuguese"],"avulso":["portuguese"],"axila":["portuguese"],"azarar":["portuguese"],"azedo":["portuguese"],"azeite":["portuguese"],"azulejo":["portuguese"],"babar":["portuguese"],"babosa":["portuguese"],"bacalhau":["portuguese"],"bacharel":["portuguese"],"bacia":["portuguese"],"bagagem":["portuguese"],"baiano":["portuguese"],"bailar":["portuguese"],"baioneta":["portuguese"],"bairro":["portuguese"],"baixista":["portuguese"],"bajular":["portuguese"],"baleia":["portuguese"],"baliza":["portuguese"],"balsa":["portuguese"],"banal":["portuguese"],"bandeira":["portuguese"],"banho":["portuguese"],"banir":["portuguese"],"banquete":["portuguese"],"barato":["portuguese"],"barbado":["portuguese"],"baronesa":["portuguese"],"barraca":["portuguese"],"barulho":["portuguese"],"baseado":["portuguese"],"bastante":["portuguese"],"batata":["portuguese"],"batedor":["portuguese"],"batida":["portuguese"],"batom":["portuguese"],"batucar":["portuguese"],"baunilha":["portuguese"],"beber":["portuguese"],"beijo":["portuguese"],"beirada":["portuguese"],"beisebol":["portuguese"],"beldade":["portuguese"],"beleza":["portuguese"],"belga":["portuguese"],"beliscar":["portuguese"],"bendito":["portuguese"],"bengala":["portuguese"],"benzer":["portuguese","turkish"],"berimbau":["portuguese"],"berlinda":["portuguese"],"berro":["portuguese"],"besouro":["portuguese"],"bexiga":["portuguese"],"bezerro":["portuguese"],"bico":["portuguese"],"bicudo":["portuguese"],"bienal":["portuguese"],"bifocal":["portuguese"],"bifurcar":["portuguese"],"bigorna":["portuguese"],"bilhete":["portuguese"],"bimestre":["portuguese"],"bimotor":["portuguese"],"biologia":["portuguese"],"biombo":["portuguese"],"biosfera":["portuguese"],"bipolar":["portuguese"],"birrento":["portuguese"],"biscoito":["portuguese"],"bisneto":["portuguese"],"bispo":["portuguese"],"bissexto":["portuguese"],"bitola":["portuguese"],"bizarro":["portuguese"],"blindado":["portuguese"],"bloco":["portuguese"],"bloquear":["portuguese"],"boato":["portuguese"],"bobagem":["portuguese"],"bocado":["portuguese"],"bocejo":["portuguese"],"bochecha":["portuguese"],"boicotar":["portuguese"],"bolada":["portuguese"],"boletim":["portuguese"],"bolha":["portuguese"],"bolo":["portuguese"],"bombeiro":["portuguese"],"bonde":["portuguese"],"boneco":["portuguese"],"bonita":["portuguese"],"borbulha":["portuguese"],"borda":["portuguese"],"boreal":["portuguese"],"borracha":["portuguese"],"bovino":["portuguese"],"boxeador":["portuguese"],"branco":["portuguese"],"brasa":["portuguese"],"braveza":["portuguese"],"breu":["portuguese"],"briga":["portuguese"],"brilho":["portuguese"],"brincar":["portuguese"],"broa":["portuguese"],"brochura":["portuguese"],"bronzear":["portuguese"],"broto":["portuguese"],"bruxo":["portuguese"],"bucha":["portuguese"],"budismo":["portuguese"],"bufar":["portuguese"],"bule":["portuguese"],"buraco":["portuguese"],"busca":["portuguese"],"busto":["portuguese"],"buzina":["portuguese"],"cabana":["portuguese"],"cabelo":["portuguese"],"cabide":["portuguese"],"cabo":["portuguese"],"cabrito":["portuguese"],"cacau":["portuguese"],"cacetada":["portuguese"],"cachorro":["portuguese"],"cacique":["portuguese"],"cadastro":["portuguese"],"cadeado":["portuguese"],"cafezal":["portuguese"],"caiaque":["portuguese"],"caipira":["portuguese"],"caixote":["portuguese"],"cajado":["portuguese"],"caju":["portuguese"],"calafrio":["portuguese"],"calcular":["portuguese"],"caldeira":["portuguese"],"calibrar":["portuguese"],"calmante":["portuguese"],"calota":["portuguese"],"camada":["portuguese"],"cambista":["portuguese"],"camisa":["portuguese"],"camomila":["portuguese"],"campanha":["portuguese"],"camuflar":["portuguese"],"canavial":["portuguese"],"cancelar":["portuguese"],"caneta":["portuguese"],"canguru":["portuguese"],"canhoto":["portuguese"],"canivete":["portuguese"],"canoa":["portuguese"],"cansado":["portuguese"],"cantar":["portuguese"],"canudo":["portuguese"],"capacho":["portuguese"],"capela":["portuguese"],"capinar":["portuguese"],"capotar":["portuguese"],"capricho":["portuguese"],"captador":["portuguese"],"capuz":["portuguese"],"caracol":["portuguese"],"carbono":["portuguese"],"cardeal":["portuguese"],"careca":["portuguese"],"carimbar":["portuguese"],"carneiro":["portuguese"],"carpete":["portuguese"],"carreira":["portuguese"],"cartaz":["portuguese"],"carvalho":["portuguese"],"casaco":["portuguese"],"casca":["portuguese"],"casebre":["portuguese"],"castelo":["portuguese"],"casulo":["portuguese"],"catarata":["portuguese"],"cativar":["portuguese"],"caule":["portuguese"],"causador":["portuguese"],"cautelar":["portuguese"],"cavalo":["portuguese"],"caverna":["portuguese"],"cebola":["portuguese"],"cedilha":["portuguese"],"cegonha":["portuguese"],"celebrar":["portuguese"],"celular":["portuguese"],"cenoura":["portuguese"],"censo":["portuguese"],"centeio":["portuguese"],"cercar":["portuguese"],"cerrado":["portuguese"],"certeiro":["portuguese"],"cerveja":["portuguese"],"cetim":["portuguese"],"cevada":["portuguese"],"chacota":["portuguese"],"chaleira":["portuguese"],"chamado":["portuguese"],"chapada":["portuguese"],"charme":["portuguese"],"chatice":["portuguese"],"chave":["portuguese"],"chefe":["portuguese"],"chegada":["portuguese"],"cheiro":["portuguese"],"cheque":["portuguese"],"chicote":["portuguese"],"chifre":["portuguese"],"chinelo":["portuguese"],"chocalho":["portuguese"],"chover":["portuguese"],"chumbo":["portuguese"],"chutar":["portuguese"],"chuva":["portuguese"],"cicatriz":["portuguese"],"ciclone":["portuguese"],"cidade":["portuguese"],"cidreira":["portuguese"],"ciente":["portuguese"],"cigana":["portuguese"],"cimento":["portuguese"],"cinto":["portuguese"],"cinza":["portuguese"],"ciranda":["portuguese"],"circuito":["portuguese"],"cirurgia":["portuguese"],"citar":["portuguese"],"clareza":["portuguese"],"clero":["portuguese"],"clicar":["portuguese"],"clone":["portuguese"],"clube":["portuguese"],"coado":["portuguese"],"coagir":["portuguese"],"cobaia":["portuguese"],"cobertor":["portuguese"],"cobrar":["portuguese"],"cocada":["portuguese"],"coelho":["portuguese"],"coentro":["portuguese"],"coeso":["portuguese"],"cogumelo":["portuguese"],"coibir":["portuguese"],"coifa":["portuguese"],"coiote":["portuguese"],"colar":["portuguese"],"coleira":["portuguese"],"colher":["portuguese"],"colidir":["portuguese"],"colmeia":["portuguese"],"colono":["portuguese"],"coluna":["portuguese"],"comando":["portuguese"],"combinar":["portuguese"],"comentar":["portuguese"],"comitiva":["portuguese"],"comover":["portuguese"],"complexo":["portuguese"],"comum":["portuguese"],"concha":["portuguese"],"condor":["portuguese"],"conectar":["portuguese"],"confuso":["portuguese"],"congelar":["portuguese"],"conhecer":["portuguese"],"conjugar":["portuguese"],"consumir":["portuguese"],"contrato":["portuguese"],"convite":["portuguese"],"cooperar":["portuguese"],"copeiro":["portuguese"],"copiador":["portuguese"],"copo":["portuguese"],"coquetel":["portuguese"],"coragem":["portuguese"],"cordial":["portuguese"],"corneta":["portuguese"],"coronha":["portuguese"],"corporal":["portuguese"],"correio":["portuguese"],"cortejo":["portuguese"],"coruja":["portuguese"],"corvo":["portuguese"],"cosseno":["portuguese"],"costela":["portuguese"],"cotonete":["portuguese"],"couro":["portuguese"],"couve":["portuguese"],"covil":["portuguese"],"cozinha":["portuguese"],"cratera":["portuguese"],"cravo":["portuguese"],"creche":["portuguese"],"credor":["portuguese"],"creme":["portuguese"],"crer":["portuguese"],"crespo":["portuguese"],"criada":["portuguese"],"criminal":["portuguese"],"crioulo":["portuguese"],"crise":["portuguese"],"criticar":["portuguese"],"crosta":["portuguese"],"crua":["portuguese"],"cruzeiro":["portuguese"],"cubano":["portuguese"],"cueca":["portuguese"],"cuidado":["portuguese"],"cujo":["portuguese"],"culatra":["portuguese"],"culminar":["portuguese"],"culpar":["portuguese"],"cultura":["portuguese"],"cumprir":["portuguese"],"cunhado":["portuguese"],"cupido":["portuguese"],"curativo":["portuguese"],"curral":["portuguese"],"cursar":["portuguese"],"curto":["portuguese"],"cuspir":["portuguese"],"custear":["portuguese"],"cutelo":["portuguese"],"damasco":["portuguese"],"datar":["portuguese"],"debater":["portuguese"],"debitar":["portuguese"],"deboche":["portuguese"],"debulhar":["portuguese"],"decalque":["portuguese"],"decimal":["portuguese"],"declive":["portuguese"],"decote":["portuguese"],"decretar":["portuguese"],"dedal":["portuguese"],"dedicado":["portuguese"],"deduzir":["portuguese"],"defesa":["portuguese"],"defumar":["portuguese"],"degelo":["portuguese"],"degrau":["portuguese"],"degustar":["portuguese"],"deitado":["portuguese"],"deixar":["portuguese"],"delator":["portuguese"],"delegado":["portuguese"],"delinear":["portuguese"],"delonga":["portuguese"],"demanda":["portuguese"],"demitir":["portuguese"],"demolido":["portuguese"],"dentista":["portuguese"],"depenado":["portuguese"],"depilar":["portuguese"],"depois":["portuguese"],"depressa":["portuguese"],"depurar":["portuguese"],"deriva":["portuguese"],"derramar":["portuguese"],"desafio":["portuguese"],"desbotar":["portuguese"],"descanso":["portuguese"],"desenho":["portuguese"],"desfiado":["portuguese"],"desgaste":["portuguese"],"desigual":["portuguese"],"deslize":["portuguese"],"desmamar":["portuguese"],"desova":["portuguese"],"despesa":["portuguese"],"destaque":["portuguese"],"desviar":["portuguese"],"detalhar":["portuguese"],"detentor":["portuguese"],"detonar":["portuguese"],"detrito":["portuguese"],"deusa":["portuguese"],"dever":["portuguese"],"devido":["portuguese"],"devotado":["portuguese"],"dezena":["portuguese"],"diagrama":["portuguese"],"dialeto":["portuguese"],"didata":["portuguese"],"difuso":["portuguese"],"digitar":["portuguese"],"dilatado":["portuguese"],"diluente":["portuguese"],"diminuir":["portuguese"],"dinastia":["portuguese"],"dinheiro":["portuguese"],"diocese":["portuguese"],"direto":["portuguese"],"discreta":["portuguese"],"disfarce":["portuguese"],"disparo":["portuguese"],"disquete":["portuguese"],"dissipar":["portuguese"],"distante":["portuguese"],"ditador":["portuguese"],"diurno":["portuguese"],"diverso":["portuguese"],"divisor":["portuguese"],"divulgar":["portuguese"],"dizer":["portuguese"],"dobrador":["portuguese"],"dolorido":["portuguese"],"domador":["portuguese"],"dominado":["portuguese"],"donativo":["portuguese"],"donzela":["portuguese"],"dormente":["portuguese"],"dorsal":["portuguese"],"dosagem":["portuguese"],"dourado":["portuguese"],"doutor":["portuguese"],"drenagem":["portuguese"],"drible":["portuguese"],"drogaria":["portuguese"],"duelar":["portuguese"],"duende":["portuguese"],"dueto":["portuguese"],"duplo":["portuguese"],"duquesa":["portuguese"],"durante":["portuguese"],"duvidoso":["portuguese"],"eclodir":["portuguese"],"ecoar":["portuguese"],"ecologia":["portuguese"],"edificar":["portuguese"],"edital":["portuguese"],"educado":["portuguese"],"efeito":["portuguese"],"efetivar":["portuguese"],"ejetar":["portuguese"],"elaborar":["portuguese"],"eleger":["portuguese"],"eleitor":["portuguese"],"elenco":["portuguese"],"elevador":["portuguese"],"eliminar":["portuguese"],"elogiar":["portuguese"],"embargo":["portuguese"],"embolado":["portuguese"],"embrulho":["portuguese"],"embutido":["portuguese"],"emenda":["portuguese"],"emergir":["portuguese"],"emissor":["portuguese"],"empatia":["portuguese"],"empenho":["portuguese"],"empinado":["portuguese"],"empolgar":["portuguese"],"emprego":["portuguese"],"empurrar":["portuguese"],"emulador":["portuguese"],"encaixe":["portuguese"],"encenado":["portuguese"],"enchente":["portuguese"],"encontro":["portuguese"],"endeusar":["portuguese"],"endossar":["portuguese"],"enfaixar":["portuguese"],"enfeite":["portuguese"],"enfim":["portuguese"],"engajado":["portuguese"],"engenho":["portuguese"],"englobar":["portuguese"],"engomado":["portuguese"],"engraxar":["portuguese"],"enguia":["portuguese"],"enjoar":["portuguese"],"enlatar":["portuguese"],"enquanto":["portuguese"],"enraizar":["portuguese"],"enrolado":["portuguese"],"enrugar":["portuguese"],"ensaio":["portuguese"],"enseada":["portuguese"],"ensino":["portuguese"],"ensopado":["portuguese"],"entanto":["portuguese"],"enteado":["portuguese"],"entidade":["portuguese"],"entortar":["portuguese"],"entrada":["portuguese"],"entulho":["portuguese"],"envergar":["portuguese"],"enviado":["portuguese"],"envolver":["portuguese"],"enxame":["portuguese"],"enxerto":["portuguese"],"enxofre":["portuguese"],"enxuto":["portuguese"],"epiderme":["portuguese"],"equipar":["portuguese"],"ereto":["portuguese"],"erguido":["portuguese"],"errata":["portuguese"],"erva":["portuguese"],"ervilha":["portuguese"],"esbanjar":["portuguese"],"esbelto":["portuguese"],"escama":["portuguese"],"escola":["portuguese"],"escrita":["portuguese"],"escuta":["portuguese"],"esfinge":["portuguese"],"esfolar":["portuguese"],"esfregar":["portuguese"],"esfumado":["portuguese"],"esgrima":["portuguese"],"esmalte":["portuguese"],"espanto":["portuguese"],"espelho":["portuguese"],"espiga":["portuguese"],"esponja":["portuguese"],"espreita":["portuguese"],"espumar":["portuguese"],"esquerda":["portuguese"],"estaca":["portuguese"],"esteira":["portuguese"],"esticar":["portuguese"],"estofado":["portuguese"],"estrela":["portuguese"],"estudo":["portuguese"],"esvaziar":["portuguese"],"etanol":["portuguese"],"etiqueta":["portuguese"],"euforia":["portuguese"],"europeu":["portuguese"],"evacuar":["portuguese"],"evaporar":["portuguese"],"evasivo":["portuguese"],"eventual":["portuguese"],"evidente":["portuguese"],"evoluir":["portuguese"],"exagero":["portuguese"],"exalar":["portuguese"],"examinar":["portuguese"],"exato":["portuguese"],"exausto":["portuguese"],"excesso":["portuguese"],"excitar":["portuguese"],"exclamar":["portuguese"],"executar":["portuguese"],"exemplo":["portuguese"],"exibir":["portuguese"],"exigente":["portuguese"],"exonerar":["portuguese"],"expandir":["portuguese"],"expelir":["portuguese"],"expirar":["portuguese"],"explanar":["portuguese"],"exposto":["portuguese"],"expresso":["portuguese"],"expulsar":["portuguese"],"externo":["portuguese"],"extinto":["portuguese"],"extrato":["portuguese"],"fabricar":["portuguese"],"fabuloso":["portuguese"],"faceta":["portuguese"],"facial":["portuguese"],"fada":["portuguese"],"fadiga":["portuguese"],"faixa":["portuguese"],"falar":["portuguese"],"falta":["portuguese"],"familiar":["portuguese"],"fandango":["portuguese"],"fanfarra":["portuguese"],"fantoche":["portuguese"],"fardado":["portuguese"],"farelo":["portuguese"],"farinha":["portuguese"],"farofa":["portuguese"],"farpa":["portuguese"],"fartura":["portuguese"],"fatia":["portuguese"],"fator":["portuguese"],"favorita":["portuguese"],"faxina":["portuguese"],"fazenda":["portuguese"],"fechado":["portuguese"],"feijoada":["portuguese"],"feirante":["portuguese"],"felino":["portuguese"],"feminino":["portuguese"],"fenda":["portuguese"],"feno":["portuguese"],"fera":["portuguese"],"feriado":["portuguese"],"ferrugem":["portuguese"],"ferver":["portuguese"],"festejar":["portuguese"],"fetal":["portuguese"],"feudal":["portuguese"],"fiapo":["portuguese"],"fibrose":["portuguese"],"ficar":["portuguese"],"ficheiro":["portuguese"],"figurado":["portuguese"],"fileira":["portuguese"],"filho":["portuguese"],"filme":["portuguese"],"filtrar":["portuguese"],"firmeza":["portuguese"],"fisgada":["portuguese"],"fissura":["portuguese"],"fita":["portuguese"],"fivela":["portuguese"],"fixador":["portuguese"],"fixo":["portuguese"],"flacidez":["portuguese"],"flamingo":["portuguese"],"flanela":["portuguese"],"flechada":["portuguese"],"flora":["portuguese"],"flutuar":["portuguese"],"fluxo":["portuguese"],"focal":["portuguese"],"focinho":["portuguese"],"fofocar":["portuguese"],"fogo":["portuguese"],"foguete":["portuguese"],"foice":["portuguese"],"folgado":["portuguese"],"folheto":["portuguese"],"forjar":["portuguese"],"formiga":["portuguese"],"forno":["portuguese"],"forte":["portuguese"],"fosco":["portuguese"],"fossa":["portuguese"],"fragata":["portuguese"],"fralda":["portuguese"],"frango":["portuguese"],"frasco":["portuguese"],"fraterno":["portuguese"],"freira":["portuguese"],"frente":["portuguese"],"fretar":["portuguese"],"frieza":["portuguese"],"friso":["portuguese"],"fritura":["portuguese"],"fronha":["portuguese"],"frustrar":["portuguese"],"fruteira":["portuguese"],"fugir":["portuguese"],"fulano":["portuguese"],"fuligem":["portuguese"],"fundar":["portuguese"],"fungo":["portuguese"],"funil":["portuguese"],"furador":["portuguese"],"furioso":["portuguese"],"futebol":["portuguese"],"gabarito":["portuguese"],"gabinete":["portuguese"],"gado":["portuguese"],"gaiato":["portuguese"],"gaiola":["portuguese"],"gaivota":["portuguese"],"galega":["portuguese"],"galho":["portuguese"],"galinha":["portuguese"],"galocha":["portuguese"],"ganhar":["portuguese"],"garagem":["portuguese"],"garfo":["portuguese"],"gargalo":["portuguese"],"garimpo":["portuguese"],"garoupa":["portuguese"],"garrafa":["portuguese"],"gasoduto":["portuguese"],"gasto":["portuguese"],"gata":["portuguese"],"gatilho":["portuguese"],"gaveta":["portuguese"],"gazela":["portuguese"],"gelado":["portuguese"],"geleia":["portuguese"],"gelo":["portuguese"],"gemada":["portuguese"],"gemer":["portuguese"],"gemido":["portuguese"],"generoso":["portuguese"],"gengiva":["portuguese"],"genial":["portuguese"],"genoma":["portuguese"],"genro":["portuguese"],"geologia":["portuguese"],"gerador":["portuguese"],"germinar":["portuguese"],"gesso":["portuguese"],"gestor":["portuguese"],"ginasta":["portuguese"],"gincana":["portuguese"],"gingado":["portuguese"],"girafa":["portuguese"],"girino":["portuguese"],"glacial":["portuguese"],"glicose":["portuguese"],"global":["portuguese"],"glorioso":["portuguese"],"goela":["portuguese"],"goiaba":["portuguese"],"golfe":["portuguese"],"golpear":["portuguese"],"gordura":["portuguese"],"gorjeta":["portuguese"],"gorro":["portuguese"],"gostoso":["portuguese"],"goteira":["portuguese"],"governar":["portuguese"],"gracejo":["portuguese"],"gradual":["portuguese"],"grafite":["portuguese"],"gralha":["portuguese"],"grampo":["portuguese"],"granada":["portuguese"],"gratuito":["portuguese"],"graveto":["portuguese"],"graxa":["portuguese"],"grego":["portuguese"],"grelhar":["portuguese"],"greve":["portuguese"],"grilo":["portuguese"],"grisalho":["portuguese"],"gritaria":["portuguese"],"grosso":["portuguese"],"grotesco":["portuguese"],"grudado":["portuguese"],"grunhido":["portuguese"],"gruta":["portuguese"],"guache":["portuguese"],"guarani":["portuguese"],"guaxinim":["portuguese"],"guerrear":["portuguese"],"guiar":["portuguese"],"guincho":["portuguese"],"guisado":["portuguese"],"gula":["portuguese"],"guloso":["portuguese"],"guru":["portuguese"],"habitar":["portuguese"],"harmonia":["portuguese"],"haste":["portuguese"],"haver":["portuguese"],"hectare":["portuguese"],"herdar":["portuguese"],"heresia":["portuguese"],"hesitar":["portuguese"],"hiato":["portuguese"],"hibernar":["portuguese"],"hidratar":["portuguese"],"hiena":["portuguese"],"hino":["portuguese"],"hipismo":["portuguese"],"hipnose":["portuguese"],"hipoteca":["portuguese"],"hoje":["portuguese"],"holofote":["portuguese"],"homem":["portuguese"],"honesto":["portuguese"],"honrado":["portuguese"],"hormonal":["portuguese"],"hospedar":["portuguese"],"humorado":["portuguese"],"iate":["portuguese"],"ideia":["portuguese"],"idoso":["portuguese"],"ignorado":["portuguese"],"igreja":["portuguese"],"iguana":["portuguese"],"ileso":["portuguese"],"ilha":["portuguese"],"iludido":["portuguese"],"iluminar":["portuguese"],"ilustrar":["portuguese"],"imagem":["portuguese"],"imediato":["portuguese"],"imenso":["portuguese"],"imersivo":["portuguese"],"iminente":["portuguese"],"imitador":["portuguese"],"imortal":["portuguese"],"impacto":["portuguese"],"impedir":["portuguese"],"implante":["portuguese"],"impor":["portuguese"],"imprensa":["portuguese"],"impune":["portuguese"],"imunizar":["portuguese"],"inalador":["portuguese"],"inapto":["portuguese"],"inativo":["portuguese"],"incenso":["portuguese"],"inchar":["portuguese"],"incidir":["portuguese"],"incluir":["portuguese"],"incolor":["portuguese"],"indeciso":["portuguese"],"indireto":["portuguese"],"indutor":["portuguese"],"ineficaz":["portuguese"],"inerente":["portuguese"],"infantil":["portuguese"],"infestar":["portuguese"],"infinito":["portuguese"],"inflamar":["portuguese"],"informal":["portuguese"],"infrator":["portuguese"],"ingerir":["portuguese"],"inibido":["portuguese"],"inicial":["portuguese"],"inimigo":["portuguese"],"injetar":["portuguese"],"inocente":["portuguese"],"inodoro":["portuguese"],"inovador":["portuguese"],"inox":["portuguese"],"inquieto":["portuguese"],"inscrito":["portuguese"],"inseto":["portuguese"],"insistir":["portuguese"],"inspetor":["portuguese"],"instalar":["portuguese"],"insulto":["portuguese"],"intacto":["portuguese"],"integral":["portuguese"],"intimar":["portuguese"],"intocado":["portuguese"],"intriga":["portuguese"],"invasor":["portuguese"],"inverno":["portuguese"],"invicto":["portuguese"],"invocar":["portuguese"],"iogurte":["portuguese"],"iraniano":["portuguese"],"ironizar":["portuguese"],"irreal":["portuguese"],"irritado":["portuguese"],"isca":["portuguese"],"isento":["portuguese"],"isolado":["portuguese"],"isqueiro":["portuguese"],"italiano":["portuguese"],"janeiro":["portuguese"],"jangada":["portuguese"],"janta":["portuguese"],"jararaca":["portuguese"],"jardim":["portuguese"],"jarro":["portuguese"],"jasmim":["portuguese"],"jato":["portuguese"],"javali":["portuguese"],"jazida":["portuguese"],"jejum":["portuguese"],"joaninha":["portuguese"],"joelhada":["portuguese"],"jogador":["portuguese"],"joia":["portuguese"],"jornal":["portuguese"],"jorrar":["portuguese"],"jovem":["portuguese"],"juba":["portuguese"],"judeu":["portuguese"],"judoca":["portuguese"],"juiz":["portuguese"],"julgador":["portuguese"],"julho":["portuguese"],"jurado":["portuguese"],"jurista":["portuguese"],"juro":["portuguese"],"justa":["portuguese"],"labareda":["portuguese"],"laboral":["portuguese"],"lacre":["portuguese"],"lactante":["portuguese"],"ladrilho":["portuguese"],"lagarta":["portuguese"],"lagoa":["portuguese"],"laje":["portuguese"],"lamber":["portuguese"],"lamentar":["portuguese"],"laminar":["portuguese"],"lampejo":["portuguese"],"lanche":["portuguese"],"lapidar":["portuguese"],"lapso":["portuguese"],"laranja":["portuguese"],"lareira":["portuguese"],"largura":["portuguese"],"lasanha":["portuguese"],"lastro":["portuguese"],"lateral":["portuguese"],"latido":["portuguese"],"lavanda":["portuguese"],"lavoura":["portuguese"],"lavrador":["portuguese"],"laxante":["portuguese"],"lazer":["portuguese"],"lealdade":["portuguese"],"lebre":["portuguese"],"legado":["portuguese"],"legendar":["portuguese"],"legista":["portuguese"],"leigo":["portuguese"],"leiloar":["portuguese"],"leitura":["portuguese"],"lembrete":["portuguese"],"leme":["portuguese"],"lenhador":["portuguese"],"lentilha":["portuguese"],"leoa":["portuguese"],"lesma":["portuguese"],"leste":["portuguese"],"letivo":["portuguese"],"letreiro":["portuguese"],"levar":["portuguese"],"leveza":["portuguese"],"levitar":["portuguese"],"liberal":["portuguese"],"libido":["portuguese"],"liderar":["portuguese"],"ligar":["portuguese"],"ligeiro":["portuguese"],"limitar":["portuguese"],"limoeiro":["portuguese"],"limpador":["portuguese"],"linda":["portuguese"],"linear":["portuguese"],"linhagem":["portuguese"],"liquidez":["portuguese"],"listagem":["portuguese"],"lisura":["portuguese"],"litoral":["portuguese"],"livro":["portuguese"],"lixa":["portuguese"],"lixeira":["portuguese"],"locador":["portuguese"],"locutor":["portuguese"],"lojista":["portuguese"],"lombo":["portuguese"],"lona":["portuguese"],"longe":["portuguese"],"lontra":["portuguese"],"lorde":["portuguese"],"lotado":["portuguese"],"loteria":["portuguese"],"loucura":["portuguese"],"lousa":["portuguese"],"louvar":["portuguese"],"luar":["portuguese"],"lucidez":["portuguese"],"lucro":["portuguese"],"luneta":["portuguese"],"lustre":["portuguese"],"lutador":["portuguese"],"luva":["portuguese"],"macaco":["portuguese"],"macete":["portuguese"],"machado":["portuguese"],"macio":["portuguese"],"madeira":["portuguese"],"madrinha":["portuguese"],"magnata":["portuguese"],"magreza":["portuguese"],"maior":["portuguese"],"mais":["portuguese"],"malandro":["portuguese"],"malha":["portuguese"],"malote":["portuguese"],"maluco":["portuguese"],"mamilo":["portuguese"],"mamoeiro":["portuguese"],"mamute":["portuguese"],"manada":["portuguese"],"mancha":["portuguese"],"mandato":["portuguese"],"manequim":["portuguese"],"manhoso":["portuguese"],"manivela":["portuguese"],"manobrar":["portuguese"],"mansa":["portuguese"],"manter":["portuguese"],"manusear":["portuguese"],"mapeado":["portuguese"],"maquinar":["portuguese"],"marcador":["portuguese"],"maresia":["portuguese"],"marfim":["portuguese"],"margem":["portuguese"],"marinho":["portuguese"],"marmita":["portuguese"],"maroto":["portuguese"],"marquise":["portuguese"],"marreco":["portuguese"],"martelo":["portuguese"],"marujo":["portuguese"],"mascote":["portuguese"],"masmorra":["portuguese"],"massagem":["portuguese"],"mastigar":["portuguese"],"matagal":["portuguese"],"materno":["portuguese"],"matinal":["portuguese"],"matutar":["portuguese"],"maxilar":["portuguese"],"medalha":["portuguese"],"medida":["portuguese"],"medusa":["portuguese"],"megafone":["portuguese"],"meiga":["portuguese"],"melancia":["portuguese"],"melhor":["portuguese"],"membro":["portuguese"],"memorial":["portuguese"],"menino":["portuguese"],"menos":["portuguese"],"mensagem":["portuguese"],"mental":["portuguese"],"merecer":["portuguese"],"mergulho":["portuguese"],"mesada":["portuguese"],"mesclar":["portuguese"],"mesmo":["portuguese"],"mesquita":["portuguese"],"mestre":["portuguese"],"metade":["portuguese"],"meteoro":["portuguese"],"metragem":["portuguese"],"mexer":["portuguese"],"mexicano":["portuguese"],"micro":["portuguese"],"migalha":["portuguese"],"migrar":["portuguese"],"milagre":["portuguese"],"milenar":["portuguese"],"milhar":["portuguese"],"mimado":["portuguese"],"minerar":["portuguese"],"minhoca":["portuguese"],"ministro":["portuguese"],"minoria":["portuguese"],"miolo":["portuguese"],"mirante":["portuguese"],"mirtilo":["portuguese"],"misturar":["portuguese"],"mocidade":["portuguese"],"moderno":["portuguese"],"modular":["portuguese"],"moeda":["portuguese"],"moer":["portuguese"],"moinho":["portuguese"],"moita":["portuguese"],"moldura":["portuguese"],"moleza":["portuguese"],"molho":["portuguese"],"molinete":["portuguese"],"molusco":["portuguese"],"montanha":["portuguese"],"moqueca":["portuguese"],"morango":["portuguese"],"morcego":["portuguese"],"mordomo":["portuguese"],"morena":["portuguese"],"mosaico":["portuguese"],"mosquete":["portuguese"],"mostarda":["portuguese"],"motel":["portuguese"],"motim":["portuguese"],"moto":["portuguese"],"motriz":["portuguese"],"muda":["portuguese"],"muito":["portuguese"],"mulata":["portuguese"],"mulher":["portuguese"],"multar":["portuguese"],"mundial":["portuguese"],"munido":["portuguese"],"muralha":["portuguese"],"murcho":["portuguese"],"muscular":["portuguese"],"museu":["portuguese"],"musical":["portuguese"],"nacional":["portuguese"],"nadador":["portuguese"],"naja":["portuguese"],"namoro":["portuguese"],"narina":["portuguese"],"narrado":["portuguese"],"nascer":["portuguese"],"nativa":["portuguese"],"natureza":["portuguese"],"navalha":["portuguese"],"navegar":["portuguese"],"navio":["portuguese"],"neblina":["portuguese"],"nebuloso":["portuguese"],"negativa":["portuguese"],"negociar":["portuguese"],"negrito":["portuguese"],"nervoso":["portuguese"],"neta":["portuguese"],"neural":["portuguese"],"nevasca":["portuguese"],"nevoeiro":["portuguese"],"ninar":["portuguese"],"ninho":["portuguese"],"nitidez":["portuguese"],"nivelar":["portuguese"],"nobreza":["portuguese"],"noite":["portuguese"],"noiva":["portuguese"],"nomear":["portuguese"],"nominal":["portuguese"],"nordeste":["portuguese"],"nortear":["portuguese"],"notar":["portuguese"],"noticiar":["portuguese"],"noturno":["portuguese"],"novelo":["portuguese"],"novilho":["portuguese"],"novo":["portuguese"],"nublado":["portuguese"],"nudez":["portuguese"],"numeral":["portuguese"],"nupcial":["portuguese"],"nutrir":["portuguese"],"nuvem":["portuguese"],"obcecado":["portuguese"],"obedecer":["portuguese"],"objetivo":["portuguese"],"obrigado":["portuguese"],"obscuro":["portuguese"],"obstetra":["portuguese"],"obter":["portuguese"],"obturar":["portuguese"],"ocidente":["portuguese"],"ocioso":["portuguese"],"ocorrer":["portuguese"],"oculista":["portuguese"],"ocupado":["portuguese"],"ofegante":["portuguese"],"ofensiva":["portuguese"],"oferenda":["portuguese"],"oficina":["portuguese"],"ofuscado":["portuguese"],"ogiva":["portuguese"],"olaria":["portuguese"],"oleoso":["portuguese"],"olhar":["portuguese"],"oliveira":["portuguese"],"ombro":["portuguese"],"omelete":["portuguese"],"omisso":["portuguese"],"omitir":["portuguese"],"ondulado":["portuguese"],"oneroso":["portuguese"],"ontem":["portuguese"],"opcional":["portuguese"],"operador":["portuguese"],"oponente":["portuguese"],"oportuno":["portuguese"],"oposto":["portuguese"],"orar":["portuguese"],"orbitar":["portuguese"],"ordem":["portuguese"],"ordinal":["portuguese"],"orfanato":["portuguese"],"orgasmo":["portuguese"],"orgulho":["portuguese"],"oriental":["portuguese"],"origem":["portuguese"],"oriundo":["portuguese"],"orla":["portuguese"],"ortodoxo":["portuguese"],"orvalho":["portuguese"],"oscilar":["portuguese"],"ossada":["portuguese"],"osso":["portuguese"],"ostentar":["portuguese"],"otimismo":["portuguese"],"ousadia":["portuguese"],"outono":["portuguese"],"outubro":["portuguese"],"ouvido":["portuguese"],"ovelha":["portuguese"],"ovular":["portuguese"],"oxidar":["portuguese"],"oxigenar":["portuguese"],"pacato":["portuguese"],"paciente":["portuguese"],"pacote":["portuguese"],"pactuar":["portuguese"],"padaria":["portuguese"],"padrinho":["portuguese"],"pagar":["portuguese"],"pagode":["portuguese"],"painel":["portuguese"],"pairar":["portuguese"],"paisagem":["portuguese"],"palavra":["portuguese"],"palestra":["portuguese"],"palheta":["portuguese"],"palito":["portuguese"],"palmada":["portuguese"],"palpitar":["portuguese"],"pancada":["portuguese"],"panela":["portuguese"],"panfleto":["portuguese"],"panqueca":["portuguese"],"pantanal":["portuguese"],"papagaio":["portuguese"],"papelada":["portuguese"],"papiro":["portuguese"],"parafina":["portuguese"],"parcial":["portuguese"],"pardal":["portuguese"],"parede":["portuguese"],"partida":["portuguese"],"pasmo":["portuguese"],"passado":["portuguese"],"pastel":["portuguese"],"patamar":["portuguese"],"patente":["portuguese"],"patinar":["portuguese"],"patrono":["portuguese"],"paulada":["portuguese"],"pausar":["portuguese"],"peculiar":["portuguese"],"pedalar":["portuguese"],"pedestre":["portuguese"],"pediatra":["portuguese"],"pedra":["portuguese"],"pegada":["portuguese"],"peitoral":["portuguese"],"peixe":["portuguese"],"pele":["portuguese"],"pelicano":["portuguese"],"penca":["portuguese"],"pendurar":["portuguese"],"peneira":["portuguese"],"penhasco":["portuguese"],"pensador":["portuguese"],"pente":["portuguese"],"perceber":["portuguese"],"perfeito":["portuguese"],"pergunta":["portuguese"],"perito":["portuguese"],"permitir":["portuguese"],"perna":["portuguese"],"perplexo":["portuguese"],"persiana":["portuguese"],"pertence":["portuguese"],"peruca":["portuguese"],"pescado":["portuguese"],"pesquisa":["portuguese"],"pessoa":["portuguese"],"petiscar":["portuguese"],"piada":["portuguese"],"picado":["portuguese"],"piedade":["portuguese"],"pigmento":["portuguese"],"pilastra":["portuguese"],"pilhado":["portuguese"],"pilotar":["portuguese"],"pimenta":["portuguese"],"pincel":["portuguese"],"pinguim":["portuguese"],"pinha":["portuguese"],"pinote":["portuguese"],"pintar":["portuguese"],"pioneiro":["portuguese"],"pipoca":["portuguese"],"piquete":["portuguese"],"piranha":["portuguese"],"pires":["portuguese"],"pirueta":["portuguese"],"piscar":["portuguese"],"pistola":["portuguese"],"pitanga":["portuguese"],"pivete":["portuguese"],"planta":["portuguese"],"plaqueta":["portuguese"],"platina":["portuguese"],"plebeu":["portuguese"],"plumagem":["portuguese"],"pluvial":["portuguese"],"pneu":["portuguese"],"poda":["portuguese"],"poeira":["portuguese"],"poetisa":["portuguese"],"polegada":["portuguese"],"policiar":["portuguese"],"poluente":["portuguese"],"polvilho":["portuguese"],"pomar":["portuguese"],"pomba":["portuguese"],"ponderar":["portuguese"],"pontaria":["portuguese"],"populoso":["portuguese"],"porta":["portuguese"],"possuir":["portuguese"],"postal":["portuguese"],"pote":["portuguese"],"poupar":["portuguese"],"pouso":["portuguese"],"povoar":["portuguese"],"praia":["portuguese"],"prancha":["portuguese"],"prato":["portuguese"],"praxe":["portuguese"],"prece":["portuguese"],"predador":["portuguese"],"prefeito":["portuguese"],"premiar":["portuguese"],"prensar":["portuguese"],"preparar":["portuguese"],"presilha":["portuguese"],"pretexto":["portuguese"],"prevenir":["portuguese"],"prezar":["portuguese"],"primata":["portuguese"],"princesa":["portuguese"],"prisma":["portuguese"],"privado":["portuguese"],"processo":["portuguese"],"produto":["portuguese"],"profeta":["portuguese"],"proibido":["portuguese"],"projeto":["portuguese"],"prometer":["portuguese"],"propagar":["portuguese"],"prosa":["portuguese"],"protetor":["portuguese"],"provador":["portuguese"],"publicar":["portuguese"],"pudim":["portuguese"],"pular":["portuguese"],"pulmonar":["portuguese"],"pulseira":["portuguese"],"punhal":["portuguese"],"punir":["portuguese"],"pupilo":["portuguese"],"pureza":["portuguese"],"puxador":["portuguese"],"quadra":["portuguese"],"quantia":["portuguese"],"quarto":["portuguese"],"quase":["portuguese"],"quebrar":["portuguese"],"queda":["portuguese"],"queijo":["portuguese"],"quente":["portuguese"],"querido":["portuguese"],"quimono":["portuguese"],"quina":["portuguese"],"quiosque":["portuguese"],"rabanada":["portuguese"],"rabisco":["portuguese"],"rachar":["portuguese"],"racionar":["portuguese"],"radial":["portuguese"],"raiar":["portuguese"],"rainha":["portuguese"],"raio":["portuguese"],"raiva":["portuguese"],"rajada":["portuguese"],"ralado":["portuguese"],"ramal":["portuguese"],"ranger":["portuguese"],"ranhura":["portuguese"],"rapadura":["portuguese"],"rapel":["portuguese"],"rapidez":["portuguese"],"raposa":["portuguese"],"raquete":["portuguese"],"raridade":["portuguese"],"rasante":["portuguese"],"rascunho":["portuguese"],"rasgar":["portuguese"],"raspador":["portuguese"],"rasteira":["portuguese"],"rasurar":["portuguese"],"ratazana":["portuguese"],"ratoeira":["portuguese"],"realeza":["portuguese"],"reanimar":["portuguese"],"reaver":["portuguese"],"rebaixar":["portuguese"],"rebelde":["portuguese"],"rebolar":["portuguese"],"recado":["portuguese"],"recente":["portuguese"],"recheio":["portuguese"],"recibo":["portuguese"],"recordar":["portuguese"],"recrutar":["portuguese"],"recuar":["portuguese"],"rede":["portuguese"],"redimir":["portuguese"],"redonda":["portuguese"],"reduzida":["portuguese"],"reenvio":["portuguese"],"refinar":["portuguese"],"refletir":["portuguese"],"refogar":["portuguese"],"refresco":["portuguese"],"refugiar":["portuguese"],"regalia":["portuguese"],"regime":["portuguese"],"regra":["portuguese"],"reinado":["portuguese"],"reitor":["portuguese"],"rejeitar":["portuguese"],"relativo":["portuguese"],"remador":["portuguese"],"remendo":["portuguese"],"remorso":["portuguese"],"renovado":["portuguese"],"reparo":["portuguese"],"repelir":["portuguese"],"repleto":["portuguese"],"repolho":["portuguese"],"represa":["portuguese"],"repudiar":["portuguese"],"requerer":["portuguese"],"resenha":["portuguese"],"resfriar":["portuguese"],"resgatar":["portuguese"],"residir":["portuguese"],"resolver":["portuguese"],"respeito":["portuguese"],"ressaca":["portuguese"],"restante":["portuguese"],"resumir":["portuguese"],"retalho":["portuguese"],"reter":["portuguese"],"retirar":["portuguese"],"retomada":["portuguese"],"retratar":["portuguese"],"revelar":["portuguese"],"revisor":["portuguese"],"revolta":["portuguese"],"riacho":["portuguese"],"rica":["portuguese"],"rigidez":["portuguese"],"rigoroso":["portuguese"],"rimar":["portuguese"],"ringue":["portuguese"],"risada":["portuguese"],"risco":["portuguese"],"risonho":["portuguese"],"robalo":["portuguese"],"rochedo":["portuguese"],"rodada":["portuguese"],"rodeio":["portuguese"],"rodovia":["portuguese"],"roedor":["portuguese"],"roleta":["portuguese"],"romano":["portuguese"],"roncar":["portuguese"],"rosado":["portuguese"],"roseira":["portuguese"],"rosto":["portuguese"],"rota":["portuguese","turkish"],"roteiro":["portuguese"],"rotina":["portuguese"],"rotular":["portuguese"],"rouco":["portuguese"],"roupa":["portuguese"],"roxo":["portuguese"],"rubro":["portuguese"],"rugido":["portuguese"],"rugoso":["portuguese"],"ruivo":["portuguese"],"rumo":["portuguese"],"rupestre":["portuguese"],"russo":["portuguese"],"sabor":["portuguese"],"saciar":["portuguese"],"sacola":["portuguese"],"sacudir":["portuguese"],"sadio":["portuguese"],"safira":["portuguese"],"saga":["portuguese"],"sagrada":["portuguese"],"saibro":["portuguese"],"salada":["portuguese"],"saleiro":["portuguese"],"salgado":["portuguese"],"saliva":["portuguese"],"salpicar":["portuguese"],"salsicha":["portuguese"],"saltar":["portuguese"],"salvador":["portuguese"],"sambar":["portuguese"],"samurai":["portuguese"],"sanar":["portuguese"],"sanfona":["portuguese"],"sangue":["portuguese"],"sanidade":["portuguese"],"sapato":["portuguese"],"sarda":["portuguese"],"sargento":["portuguese"],"sarjeta":["portuguese"],"saturar":["portuguese"],"saudade":["portuguese"],"saxofone":["portuguese"],"sazonal":["portuguese"],"secar":["portuguese"],"secular":["portuguese"],"seda":["portuguese","turkish"],"sedento":["portuguese"],"sediado":["portuguese"],"sedoso":["portuguese"],"sedutor":["portuguese"],"segmento":["portuguese"],"segredo":["portuguese"],"segundo":["portuguese"],"seiva":["portuguese"],"seleto":["portuguese"],"selvagem":["portuguese"],"semanal":["portuguese"],"semente":["portuguese"],"senador":["portuguese"],"senhor":["portuguese"],"sensual":["portuguese"],"sentado":["portuguese"],"separado":["portuguese"],"sereia":["portuguese"],"seringa":["portuguese"],"serra":["portuguese"],"servo":["portuguese"],"setembro":["portuguese"],"setor":["portuguese"],"sigilo":["portuguese"],"silhueta":["portuguese"],"silicone":["portuguese"],"simetria":["portuguese"],"simpatia":["portuguese"],"simular":["portuguese"],"sinal":["portuguese"],"sincero":["portuguese"],"singular":["portuguese"],"sinopse":["portuguese"],"sintonia":["portuguese"],"sirene":["portuguese"],"siri":["portuguese"],"situado":["portuguese"],"soberano":["portuguese"],"sobra":["portuguese"],"socorro":["portuguese"],"sogro":["portuguese"],"soja":["portuguese"],"solda":["portuguese"],"soletrar":["portuguese"],"solteiro":["portuguese"],"sombrio":["portuguese"],"sonata":["portuguese"],"sondar":["portuguese"],"sonegar":["portuguese"],"sonhador":["portuguese"],"sono":["portuguese"],"soprano":["portuguese"],"soquete":["portuguese"],"sorrir":["portuguese"],"sorteio":["portuguese"],"sossego":["portuguese"],"sotaque":["portuguese"],"soterrar":["portuguese"],"sovado":["portuguese"],"sozinho":["portuguese"],"suavizar":["portuguese"],"subida":["portuguese"],"submerso":["portuguese"],"subsolo":["portuguese"],"subtrair":["portuguese"],"sucata":["portuguese"],"sucesso":["portuguese"],"suco":["portuguese"],"sudeste":["portuguese"],"sufixo":["portuguese"],"sugador":["portuguese"],"sugerir":["portuguese"],"sujeito":["portuguese"],"sulfato":["portuguese"],"sumir":["portuguese"],"suor":["portuguese"],"superior":["portuguese"],"suplicar":["portuguese"],"suposto":["portuguese"],"suprimir":["portuguese"],"surdina":["portuguese"],"surfista":["portuguese"],"surpresa":["portuguese"],"surreal":["portuguese"],"surtir":["portuguese"],"suspiro":["portuguese"],"sustento":["portuguese"],"tabela":["portuguese","turkish"],"tablete":["portuguese"],"tabuada":["portuguese"],"tacho":["portuguese"],"tagarela":["portuguese"],"talher":["portuguese"],"talo":["portuguese"],"talvez":["portuguese"],"tamanho":["portuguese"],"tamborim":["portuguese"],"tampa":["portuguese"],"tangente":["portuguese"],"tanto":["portuguese"],"tapar":["portuguese"],"tapioca":["portuguese"],"tardio":["portuguese"],"tarefa":["portuguese"],"tarja":["portuguese"],"tarraxa":["portuguese"],"tatuagem":["portuguese"],"taurino":["portuguese"],"taxativo":["portuguese"],"taxista":["portuguese"],"teatral":["portuguese"],"tecer":["portuguese"],"tecido":["portuguese"],"teclado":["portuguese"],"tedioso":["portuguese"],"teia":["portuguese"],"teimar":["portuguese"],"telefone":["portuguese"],"telhado":["portuguese"],"tempero":["portuguese"],"tenente":["portuguese"],"tensor":["portuguese"],"tentar":["portuguese"],"termal":["portuguese"],"terno":["portuguese"],"terreno":["portuguese"],"tese":["portuguese"],"tesoura":["portuguese"],"testado":["portuguese"],"teto":["portuguese"],"textura":["portuguese"],"texugo":["portuguese"],"tiara":["portuguese"],"tigela":["portuguese"],"tijolo":["portuguese"],"timbrar":["portuguese"],"timidez":["portuguese"],"tingido":["portuguese"],"tinteiro":["portuguese"],"tiragem":["portuguese"],"titular":["portuguese"],"toalha":["portuguese"],"tocha":["portuguese"],"tolerar":["portuguese"],"tolice":["portuguese"],"tomada":["portuguese"],"tomilho":["portuguese"],"tonel":["portuguese"],"tontura":["portuguese"],"topete":["portuguese"],"tora":["portuguese"],"torcido":["portuguese"],"torneio":["portuguese"],"torque":["portuguese"],"torrada":["portuguese"],"torto":["portuguese"],"tostar":["portuguese"],"touca":["portuguese"],"toupeira":["portuguese"],"toxina":["portuguese"],"trabalho":["portuguese"],"tracejar":["portuguese"],"tradutor":["portuguese"],"trafegar":["portuguese"],"trajeto":["portuguese"],"trama":["portuguese"],"trancar":["portuguese"],"trapo":["portuguese"],"traseiro":["portuguese"],"tratador":["portuguese"],"travar":["portuguese"],"treino":["portuguese"],"tremer":["portuguese"],"trepidar":["portuguese"],"trevo":["portuguese"],"triagem":["portuguese"],"tribo":["portuguese"],"triciclo":["portuguese"],"tridente":["portuguese"],"trilogia":["portuguese"],"trindade":["portuguese"],"triplo":["portuguese"],"triturar":["portuguese"],"triunfal":["portuguese"],"trocar":["portuguese"],"trombeta":["portuguese"],"trova":["portuguese"],"trunfo":["portuguese"],"truque":["portuguese"],"tubular":["portuguese"],"tucano":["portuguese"],"tudo":["portuguese"],"tulipa":["portuguese"],"tupi":["portuguese"],"turbo":["portuguese"],"turma":["portuguese"],"turquesa":["portuguese"],"tutelar":["portuguese"],"tutorial":["portuguese"],"uivar":["portuguese"],"umbigo":["portuguese"],"unha":["portuguese"],"unidade":["portuguese"],"uniforme":["portuguese"],"urologia":["portuguese"],"urso":["portuguese"],"urtiga":["portuguese"],"urubu":["portuguese"],"usado":["portuguese"],"usina":["portuguese"],"usufruir":["portuguese"],"vacina":["portuguese"],"vadiar":["portuguese"],"vagaroso":["portuguese"],"vaidoso":["portuguese"],"vala":["portuguese"],"valente":["portuguese"],"validade":["portuguese"],"valores":["portuguese"],"vantagem":["portuguese"],"vaqueiro":["portuguese"],"varanda":["portuguese"],"vareta":["portuguese"],"varrer":["portuguese"],"vascular":["portuguese"],"vasilha":["portuguese"],"vassoura":["portuguese"],"vazar":["portuguese"],"vazio":["portuguese"],"veado":["portuguese"],"vedar":["portuguese"],"vegetar":["portuguese"],"veicular":["portuguese"],"veleiro":["portuguese"],"velhice":["portuguese"],"veludo":["portuguese"],"vencedor":["portuguese"],"vendaval":["portuguese"],"venerar":["portuguese"],"ventre":["portuguese"],"verbal":["portuguese"],"verdade":["portuguese"],"vereador":["portuguese"],"vergonha":["portuguese"],"vermelho":["portuguese"],"verniz":["portuguese"],"versar":["portuguese"],"vertente":["portuguese"],"vespa":["portuguese"],"vestido":["portuguese"],"vetorial":["portuguese"],"viaduto":["portuguese"],"viagem":["portuguese"],"viajar":["portuguese"],"viatura":["portuguese"],"vibrador":["portuguese"],"videira":["portuguese"],"vidraria":["portuguese"],"viela":["portuguese"],"viga":["portuguese"],"vigente":["portuguese"],"vigiar":["portuguese"],"vigorar":["portuguese"],"vilarejo":["portuguese"],"vinco":["portuguese"],"vinheta":["portuguese"],"vinil":["portuguese"],"violeta":["portuguese"],"virada":["portuguese"],"virtude":["portuguese"],"visitar":["portuguese"],"visto":["portuguese"],"vitral":["portuguese"],"viveiro":["portuguese"],"vizinho":["portuguese"],"voador":["portuguese"],"voar":["portuguese"],"vogal":["portuguese"],"volante":["portuguese"],"voleibol":["portuguese"],"voltagem":["portuguese"],"volumoso":["portuguese"],"vontade":["portuguese"],"vulto":["portuguese"],"vuvuzela":["portuguese"],"xadrez":["portuguese"],"xarope":["portuguese"],"xeque":["portuguese"],"xeretar":["portuguese"],"xerife":["portuguese"],"xingar":["portuguese"],"zangado":["portuguese"],"zarpar":["portuguese"],"zebu":["portuguese"],"zelador":["portuguese"],"zombar":["portuguese"],"zoologia":["portuguese"],"zumbido":["portuguese"],"абзац":["russian"],"абонент":["russian"],"абсурд":["russian"],"авангард":["russian"],"авария":["russian"],"август":["russian"],"авиация":["russian"],"автор":["russian"],"агент":["russian"],"агитация":["russian"],"агрегат":["russian"],"адвокат":["russian"],"адмирал":["russian"],"адрес":["russian"],"азарт":["russian"],"азот":["russian"],"академия":["russian"],"аквариум":["russian"],"аксиома":["russian"],"акула":["russian"],"акцент":["russian"],"акция":["russian"],"аллея":["russian"],"алмаз":["russian"],"алтарь":["russian"],"альбом":["russian"],"альянс":["russian"],"амбиция":["russian"],"анализ":["russian"],"анекдот":["russian"],"анкета":["russian"],"ансамбль":["russian"],"антенна":["russian"],"апельсин":["russian"],"аппарат":["russian"],"аппетит":["russian"],"апрель":["russian"],"аптека":["russian"],"арбуз":["russian"],"аргумент":["russian"],"аренда":["russian"],"арест":["russian"],"армия":["russian"],"аромат":["russian"],"арсенал":["russian"],"артерия":["russian"],"артист":["russian"],"архив":["russian"],"аспирант":["russian"],"асфальт":["russian"],"атака":["russian"],"атомный":["russian"],"атрибут":["russian"],"аукцион":["russian"],"афиша":["russian"],"аэропорт":["russian"],"бабочка":["russian"],"бабушка":["russian"],"багаж":["russian"],"база":["russian"],"бактерия":["russian"],"баланс":["russian"],"балерина":["russian"],"балкон":["russian"],"бандит":["russian"],"банк":["russian"],"барабан":["russian"],"барон":["russian"],"барышня":["russian"],"барьер":["russian"],"бассейн":["russian"],"батарея":["russian"],"башмак":["russian"],"башня":["russian"],"бедный":["russian"],"беженец":["russian"],"бездна":["russian"],"белка":["russian"],"белый":["russian"],"бензин":["russian"],"берег":["russian"],"беседа":["russian"],"бешеный":["russian"],"билет":["russian"],"бинокль":["russian"],"биржа":["russian"],"битва":["russian"],"благо":["russian"],"блеск":["russian"],"близкий":["russian"],"блин":["russian"],"блок":["russian"],"блюдо":["russian"],"богатый":["russian"],"бодрый":["russian"],"боец":["russian"],"бокал":["russian"],"боковой":["russian"],"бокс":["russian"],"более":["russian"],"болото":["russian"],"болтать":["russian"],"большой":["russian"],"бомба":["russian"],"борт":["russian"],"борьба":["russian"],"босой":["russian"],"ботинок":["russian"],"бояться":["russian"],"брак":["russian"],"брать":["russian"],"бревно":["russian"],"бред":["russian"],"бригада":["russian"],"бродяга":["russian"],"броня":["russian"],"бросить":["russian"],"брызги":["russian"],"брюки":["russian"],"брюхо":["russian"],"бугор":["russian"],"будка":["russian"],"будни":["russian"],"будущее":["russian"],"буква":["russian"],"букет":["russian"],"бульвар":["russian"],"бумага":["russian"],"бунт":["russian"],"бурный":["russian"],"буря":["russian"],"бутылка":["russian"],"бухта":["russian"],"бывший":["russian"],"быстро":["russian"],"бытовой":["russian"],"быть":["russian"],"бюджет":["russian"],"бюро":["russian"],"бюст":["russian"],"вагон":["russian"],"важный":["russian"],"вакцина":["russian"],"валенок":["russian"],"вальс":["russian"],"валюта":["russian"],"ванная":["russian"],"варенье":["russian"],"вариант":["russian"],"вблизи":["russian"],"вверх":["russian"],"вводить":["russian"],"вдали":["russian"],"вдвое":["russian"],"вдова":["russian"],"вдоль":["russian"],"вдруг":["russian"],"ведро":["russian"],"ведущий":["russian"],"ведьма":["russian"],"вежливо":["russian"],"везде":["russian"],"веко":["russian"],"вексель":["russian"],"велеть":["russian"],"великий":["russian"],"венец":["russian"],"веник":["russian"],"веранда":["russian"],"верблюд":["russian"],"верить":["russian"],"верный":["russian"],"версия":["russian"],"вертеть":["russian"],"верхний":["russian"],"вершина":["russian"],"весело":["russian"],"весна":["russian"],"весомый":["russian"],"вести":["russian"],"весь":["russian"],"ветеран":["russian"],"ветхий":["russian"],"вечер":["russian"],"вечно":["russian"],"вешалка":["russian"],"вещество":["russian"],"взамен":["russian"],"взгляд":["russian"],"вздох":["russian"],"взнос":["russian"],"взойти":["russian"],"взор":["russian"],"взрыв":["russian"],"взять":["russian"],"видеть":["russian"],"видимо":["russian"],"визг":["russian"],"визит":["russian"],"вилка":["russian"],"вина":["russian"],"вирус":["russian"],"висок":["russian"],"витамин":["russian"],"витрина":["russian"],"вихрь":["russian"],"вишня":["russian"],"вкус":["russian"],"влага":["russian"],"владелец":["russian"],"власть":["russian"],"влево":["russian"],"влияние":["russian"],"вложить":["russian"],"вместе":["russian"],"внешний":["russian"],"вникать":["russian"],"внимание":["russian"],"вновь":["russian"],"внук":["russian"],"внутри":["russian"],"внучка":["russian"],"внушать":["russian"],"вовлечь":["russian"],"вовремя":["russian"],"вовсю":["russian"],"вода":["russian"],"водород":["russian"],"водяной":["russian"],"воевать":["russian"],"возврат":["russian"],"возглас":["russian"],"воздух":["russian"],"возить":["russian"],"возле":["russian"],"возня":["russian"],"возраст":["russian"],"война":["russian"],"войско":["russian"],"вокзал":["russian"],"волос":["russian"],"волчий":["russian"],"вольный":["russian"],"воля":["russian"],"вообще":["russian"],"вопль":["russian"],"вопрос":["russian"],"ворота":["russian"],"восемь":["russian"],"восток":["russian"],"вплоть":["russian"],"вполне":["russian"],"вправе":["russian"],"впредь":["russian"],"впрочем":["russian"],"врач":["russian"],"вредный":["russian"],"время":["russian"],"вручить":["russian"],"всадник":["russian"],"всегда":["russian"],"вскоре":["russian"],"вскрыть":["russian"],"всплеск":["russian"],"вспышка":["russian"],"встреча":["russian"],"всюду":["russian"],"всякий":["russian"],"второй":["russian"],"вход":["russian"],"вчера":["russian"],"выбор":["russian"],"вывод":["russian"],"выгнать":["russian"],"выдать":["russian"],"выехать":["russian"],"вызов":["russian"],"выйти":["russian"],"выкуп":["russian"],"вылезти":["russian"],"вымыть":["russian"],"выпасть":["russian"],"выпить":["russian"],"выплата":["russian"],"выпуск":["russian"],"вырасти":["russian"],"выручка":["russian"],"выслать":["russian"],"высокий":["russian"],"выставка":["russian"],"вышка":["russian"],"вязать":["russian"],"вялый":["russian"],"газета":["russian"],"газовый":["russian"],"галерея":["russian"],"галстук":["russian"],"гамма":["russian"],"гарантия":["russian"],"гармония":["russian"],"гарнизон":["russian"],"гастроли":["russian"],"гвардия":["russian"],"гвоздь":["russian"],"гектар":["russian"],"генерал":["russian"],"гений":["russian"],"геном":["russian"],"геолог":["russian"],"герб":["russian"],"герой":["russian"],"гибкий":["russian"],"гигант":["russian"],"гимн":["russian"],"гипотеза":["russian"],"гитара":["russian"],"главный":["russian"],"глагол":["russian"],"гладить":["russian"],"глаз":["russian"],"глина":["russian"],"глоток":["russian"],"глубокий":["russian"],"глупый":["russian"],"глухой":["russian"],"глыба":["russian"],"глядеть":["russian"],"гнев":["russian"],"гнездо":["russian"],"гнилой":["russian"],"годовой":["russian"],"голова":["russian"],"голубой":["russian"],"голый":["russian"],"гонорар":["russian"],"гордость":["russian"],"горизонт":["russian"],"горло":["russian"],"горный":["russian"],"город":["russian"],"горшок":["russian"],"горький":["russian"],"горючее":["russian"],"горячий":["russian"],"готовый":["russian"],"градус":["russian"],"грамм":["russian"],"граница":["russian"],"граф":["russian"],"гребень":["russian"],"гриб":["russian"],"гримаса":["russian"],"грозить":["russian"],"грохот":["russian"],"грош":["russian"],"грубый":["russian"],"грудь":["russian"],"груз":["russian"],"грунт":["russian"],"группа":["russian"],"груша":["russian"],"грязный":["russian"],"губа":["russian"],"гудок":["russian"],"гулкий":["russian"],"гулять":["russian"],"гусеница":["russian"],"густо":["russian"],"гусь":["russian"],"давление":["russian"],"давно":["russian"],"даже":["russian"],"дальний":["russian"],"данный":["russian"],"дарить":["russian"],"датчик":["russian"],"дать":["russian"],"дача":["russian"],"двадцать":["russian"],"дважды":["russian"],"дверь":["russian"],"двигать":["russian"],"движение":["russian"],"двойной":["russian"],"двор":["russian"],"дебют":["russian"],"девятый":["russian"],"дежурный":["russian"],"действие":["russian"],"декабрь":["russian"],"деление":["russian"],"дело":["russian"],"дельфин":["russian"],"день":["russian"],"дерево":["russian"],"держать":["russian"],"дерзкий":["russian"],"десять":["russian"],"деталь":["russian"],"детский":["russian"],"дефект":["russian"],"дефицит":["russian"],"деятель":["russian"],"джаз":["russian"],"джинсы":["russian"],"джунгли":["russian"],"диагноз":["russian"],"диалог":["russian"],"диапазон":["russian"],"диван":["russian"],"дивизия":["russian"],"дивный":["russian"],"диета":["russian"],"дизайн":["russian"],"дикарь":["russian"],"дилер":["russian"],"динамика":["russian"],"диплом":["russian"],"директор":["russian"],"дитя":["russian"],"длинный":["russian"],"дневник":["russian"],"добрый":["russian"],"добыча":["russian"],"доверие":["russian"],"догадка":["russian"],"догнать":["russian"],"дождь":["russian"],"доклад":["russian"],"доктор":["russian"],"документ":["russian"],"долго":["russian"],"должен":["russian"],"долина":["russian"],"донос":["russian"],"дорога":["russian"],"досада":["russian"],"доска":["russian"],"достать":["russian"],"досуг":["russian"],"доход":["russian"],"доцент":["russian"],"дощатый":["russian"],"драка":["russian"],"древний":["russian"],"дремать":["russian"],"дробный":["russian"],"дрова":["russian"],"дрожать":["russian"],"другой":["russian"],"дружба":["russian"],"дубовый":["russian"],"дуга":["russian"],"думать":["russian"],"дурной":["russian"],"духи":["russian"],"душный":["russian"],"дуэль":["russian"],"дуэт":["russian"],"дыра":["russian"],"дыхание":["russian"],"дюжина":["russian"],"дядя":["russian"],"едва":["russian"],"единый":["russian"],"ерунда":["russian"],"если":["russian"],"ехать":["russian"],"жадный":["russian"],"жажда":["russian"],"жалеть":["russian"],"жалоба":["russian"],"жанр":["russian"],"жареный":["russian"],"жаркий":["russian"],"жгучий":["russian"],"жевать":["russian"],"желание":["russian"],"желудок":["russian"],"жена":["russian"],"женщина":["russian"],"жертва":["russian"],"жест":["russian"],"жидкость":["russian"],"житель":["russian"],"жить":["russian"],"жрец":["russian"],"жулик":["russian"],"журнал":["russian"],"жуткий":["russian"],"забрать":["russian"],"забыть":["russian"],"завести":["russian"],"завод":["russian"],"завтра":["russian"],"загадка":["russian"],"загнать":["russian"],"заговор":["russian"],"задача":["russian"],"задеть":["russian"],"задний":["russian"],"задолго":["russian"],"заехать":["russian"],"заказ":["russian"],"закон":["russian"],"закрыть":["russian"],"закуска":["russian"],"залезть":["russian"],"залить":["russian"],"залп":["russian"],"замок":["russian"],"замуж":["russian"],"замысел":["russian"],"занавес":["russian"],"заново":["russian"],"занять":["russian"],"заодно":["russian"],"запись":["russian"],"запрос":["russian"],"запуск":["russian"],"запястье":["russian"],"заранее":["russian"],"заросль":["russian"],"зарплата":["russian"],"заря":["russian"],"засада":["russian"],"заслуга":["russian"],"заснуть":["russian"],"застать":["russian"],"затвор":["russian"],"затеять":["russian"],"затрата":["russian"],"затылок":["russian"],"захват":["russian"],"зачем":["russian"],"защита":["russian"],"заявить":["russian"],"заяц":["russian"],"звезда":["russian"],"звено":["russian"],"звонить":["russian"],"здесь":["russian"],"зелень":["russian"],"земля":["russian"],"зеркало":["russian"],"зерно":["russian"],"зима":["russian"],"злой":["russian"],"змея":["russian"],"знамя":["russian"],"знание":["russian"],"значит":["russian"],"золотой":["russian"],"зона":["russian"],"зонтик":["russian"],"зоопарк":["russian"],"зрачок":["russian"],"зрение":["russian"],"зритель":["russian"],"зубной":["russian"],"зубр":["russian"],"игла":["russian"],"идеал":["russian"],"идеолог":["russian"],"идея":["russian"],"идол":["russian"],"идти":["russian"],"изба":["russian"],"избить":["russian"],"избрать":["russian"],"избыток":["russian"],"извлечь":["russian"],"извне":["russian"],"изгиб":["russian"],"изгнать":["russian"],"издание":["russian"],"изделие":["russian"],"изнутри":["russian"],"изобилие":["russian"],"изоляция":["russian"],"изредка":["russian"],"изрядно":["russian"],"изучение":["russian"],"изъять":["russian"],"изящный":["russian"],"икона":["russian"],"икра":["russian"],"иллюзия":["russian"],"именно":["russian"],"иметь":["russian"],"имидж":["russian"],"империя":["russian"],"импульс":["russian"],"иначе":["russian"],"инвалид":["russian"],"индекс":["russian"],"индивид":["russian"],"инерция":["russian"],"инженер":["russian"],"иногда":["russian"],"иной":["russian"],"институт":["russian"],"интерес":["russian"],"интрига":["russian"],"интуиция":["russian"],"инфаркт":["russian"],"инцидент":["russian"],"ирония":["russian"],"искать":["russian"],"испуг":["russian"],"история":["russian"],"итог":["russian"],"июнь":["russian"],"кабель":["russian"],"кабинет":["russian"],"каблук":["russian"],"кавалер":["russian"],"кадр":["russian"],"каждый":["russian"],"кажется":["russian"],"казино":["russian"],"калитка":["russian"],"камень":["russian"],"камин":["russian"],"канал":["russian"],"кандидат":["russian"],"каникулы":["russian"],"канон":["russian"],"капитан":["russian"],"капля":["russian"],"капот":["russian"],"капуста":["russian"],"карандаш":["russian"],"карета":["russian"],"каркас":["russian"],"карман":["russian"],"картина":["russian"],"карьера":["russian"],"каска":["russian"],"кассета":["russian"],"кастрюля":["russian"],"каталог":["russian"],"катер":["russian"],"каток":["russian"],"катушка":["russian"],"кафедра":["russian"],"качество":["russian"],"каша":["russian"],"кашлять":["russian"],"каюта":["russian"],"квадрат":["russian"],"квартира":["russian"],"квота":["russian"],"кепка":["russian"],"кивнуть":["russian"],"километр":["russian"],"кино":["russian"],"киоск":["russian"],"кипяток":["russian"],"кирпич":["russian"],"кислота":["russian"],"кисть":["russian"],"клавиша":["russian"],"клапан":["russian"],"класс":["russian"],"клей":["russian"],"клетка":["russian"],"клиент":["russian"],"климат":["russian"],"клиника":["russian"],"кличка":["russian"],"клоун":["russian"],"клочок":["russian"],"клуб":["russian"],"клумба":["russian"],"ключ":["russian"],"книга":["russian"],"кнопка":["russian"],"кнут":["russian"],"княгиня":["russian"],"князь":["russian"],"кобура":["russian"],"когда":["russian"],"кодекс":["russian"],"кожа":["russian"],"коктейль":["russian"],"колено":["russian"],"коллега":["russian"],"колонна":["russian"],"колпак":["russian"],"кольцо":["russian"],"колючий":["russian"],"коляска":["russian"],"команда":["russian"],"комедия":["russian"],"комиссия":["russian"],"коммуна":["russian"],"комната":["russian"],"комок":["russian"],"компания":["russian"],"комфорт":["russian"],"конвейер":["russian"],"конгресс":["russian"],"конечно":["russian"],"конкурс":["russian"],"контроль":["russian"],"концерт":["russian"],"конь":["russian"],"конюшня":["russian"],"копать":["russian"],"копейка":["russian"],"копыто":["russian"],"корабль":["russian"],"корень":["russian"],"корзина":["russian"],"коридор":["russian"],"кормить":["russian"],"корпус":["russian"],"космос":["russian"],"костюм":["russian"],"косяк":["russian"],"котел":["russian"],"котлета":["russian"],"который":["russian"],"коттедж":["russian"],"кофе":["russian"],"кофта":["russian"],"кошка":["russian"],"кража":["russian"],"край":["russian"],"красный":["russian"],"краткий":["russian"],"кредит":["russian"],"крем":["russian"],"крепкий":["russian"],"кресло":["russian"],"кривой":["russian"],"кризис":["russian"],"кристалл":["russian"],"критерий":["russian"],"кричать":["russian"],"кровь":["russian"],"крокодил":["russian"],"кролик":["russian"],"кроме":["russian"],"крона":["russian"],"круг":["russian"],"кружка":["russian"],"крупный":["russian"],"крутой":["russian"],"крушение":["russian"],"крыло":["russian"],"крыша":["russian"],"крючок":["russian"],"кстати":["russian"],"кубик":["russian"],"куда":["russian"],"кузов":["russian"],"кукла":["russian"],"кулак":["russian"],"кулиса":["russian"],"культура":["russian"],"кумир":["russian"],"купе":["russian"],"купить":["russian"],"купол":["russian"],"купюра":["russian"],"курица":["russian"],"курорт":["russian"],"курс":["russian"],"куртка":["russian"],"кусок":["russian"],"куст":["russian"],"кухня":["russian"],"кушать":["russian"],"лабиринт":["russian"],"лавка":["russian"],"лагерь":["russian"],"ладно":["russian"],"ладонь":["russian"],"лапа":["russian"],"лауреат":["russian"],"лгать":["russian"],"лебедь":["russian"],"левый":["russian"],"легенда":["russian"],"легкий":["russian"],"ледяной":["russian"],"лежать":["russian"],"лезвие":["russian"],"лезть":["russian"],"лекция":["russian"],"ленивый":["russian"],"лента":["russian"],"лепесток":["russian"],"лесной":["russian"],"лестница":["russian"],"лететь":["russian"],"лето":["russian"],"лечить":["russian"],"лига":["russian"],"лидер":["russian"],"лиловый":["russian"],"лимон":["russian"],"линия":["russian"],"липкий":["russian"],"лист":["russian"],"литр":["russian"],"лихой":["russian"],"лицо":["russian"],"лишить":["russian"],"лишний":["russian"],"ловить":["russian"],"логика":["russian"],"лодка":["russian"],"ложь":["russian"],"лозунг":["russian"],"локоть":["russian"],"лопата":["russian"],"лошадь":["russian"],"лукавый":["russian"],"луна":["russian"],"лучший":["russian"],"лысый":["russian"],"льгота":["russian"],"любить":["russian"],"любой":["russian"],"людской":["russian"],"люстра":["russian"],"лютый":["russian"],"лягушка":["russian"],"магазин":["russian"],"магия":["russian"],"майор":["russian"],"майский":["russian"],"максимум":["russian"],"макушка":["russian"],"мало":["russian"],"мальчик":["russian"],"мама":["russian"],"манера":["russian"],"марка":["russian"],"март":["russian"],"маршрут":["russian"],"масса":["russian"],"мастер":["russian"],"масштаб":["russian"],"материал":["russian"],"матч":["russian"],"махать":["russian"],"машина":["russian"],"маяк":["russian"],"мебель":["russian"],"медаль":["russian"],"медведь":["russian"],"медицина":["russian"],"медь":["russian"],"между":["russian"],"мелкий":["russian"],"мелочь":["russian"],"мемуары":["russian"],"меньше":["russian"],"меню":["russian"],"менять":["russian"],"мера":["russian"],"мерцать":["russian"],"место":["russian"],"месяц":["russian"],"металл":["russian"],"метод":["russian"],"метр":["russian"],"механизм":["russian"],"меховой":["russian"],"мечтать":["russian"],"мешать":["russian"],"мешок":["russian"],"миграция":["russian"],"микрофон":["russian"],"милиция":["russian"],"миллион":["russian"],"милость":["russian"],"миля":["russian"],"мимо":["russian"],"минерал":["russian"],"министр":["russian"],"минута":["russian"],"мирный":["russian"],"миска":["russian"],"миссия":["russian"],"митинг":["russian"],"мишень":["russian"],"младший":["russian"],"мнение":["russian"],"мнимый":["russian"],"много":["russian"],"могучий":["russian"],"модель":["russian"],"может":["russian"],"мозг":["russian"],"мокрый":["russian"],"молекула":["russian"],"молния":["russian"],"молодой":["russian"],"молчать":["russian"],"момент":["russian"],"монета":["russian"],"монитор":["russian"],"монолог":["russian"],"монстр":["russian"],"монтаж":["russian"],"мораль":["russian"],"море":["russian"],"морковь":["russian"],"мороз":["russian"],"морщина":["russian"],"мостовая":["russian"],"мотать":["russian"],"мотив":["russian"],"мотор":["russian"],"мохнатый":["russian"],"мрамор":["russian"],"мрачный":["russian"],"мстить":["russian"],"мудрый":["russian"],"мужество":["russian"],"мужчина":["russian"],"музей":["russian"],"музыка":["russian"],"мундир":["russian"],"муравей":["russian"],"мусор":["russian"],"муха":["russian"],"мчаться":["russian"],"мысль":["russian"],"мыться":["russian"],"мышца":["russian"],"мышь":["russian"],"мюзикл":["russian"],"мягкий":["russian"],"мясо":["russian"],"набор":["russian"],"навык":["russian"],"наглый":["russian"],"нагрузка":["russian"],"надежда":["russian"],"надзор":["russian"],"надо":["russian"],"наедине":["russian"],"назад":["russian"],"название":["russian"],"назло":["russian"],"наивный":["russian"],"найти":["russian"],"наконец":["russian"],"налево":["russian"],"наличие":["russian"],"налог":["russian"],"намерен":["russian"],"нанести":["russian"],"напасть":["russian"],"например":["russian"],"народ":["russian"],"наследие":["russian"],"натура":["russian"],"наука":["russian"],"наутро":["russian"],"начать":["russian"],"небо":["russian"],"неважно":["russian"],"невеста":["russian"],"негодяй":["russian"],"недавно":["russian"],"неделя":["russian"],"недолго":["russian"],"недра":["russian"],"недуг":["russian"],"нежный":["russian"],"незачем":["russian"],"некто":["russian"],"нелепый":["russian"],"неловко":["russian"],"нельзя":["russian"],"немало":["russian"],"немой":["russian"],"неплохо":["russian"],"нервный":["russian"],"нередко":["russian"],"нестись":["russian"],"неудача":["russian"],"неужели":["russian"],"нефть":["russian"],"неясный":["russian"],"нигде":["russian"],"низкий":["russian"],"никакой":["russian"],"никогда":["russian"],"никуда":["russian"],"ничто":["russian"],"ничуть":["russian"],"ниша":["russian"],"нищий":["russian"],"новость":["russian"],"новый":["russian"],"нога":["russian"],"ноготь":["russian"],"ножницы":["russian"],"ноздря":["russian"],"номер":["russian"],"носить":["russian"],"носок":["russian"],"ночь":["russian"],"ноябрь":["russian"],"нрав":["russian"],"нуль":["russian"],"нынче":["russian"],"нырять":["russian"],"нюанс":["russian"],"няня":["russian"],"обаяние":["russian"],"обед":["russian"],"обезьяна":["russian"],"обещать":["russian"],"обжечь":["russian"],"обзор":["russian"],"обилие":["russian"],"обитать":["russian"],"область":["russian"],"облик":["russian"],"обложка":["russian"],"обмен":["russian"],"обморок":["russian"],"обожать":["russian"],"обои":["russian"],"оболочка":["russian"],"оборона":["russian"],"обочина":["russian"],"образ":["russian"],"обрести":["russian"],"обрыв":["russian"],"обувь":["russian"],"обучение":["russian"],"обход":["russian"],"общество":["russian"],"общий":["russian"],"объект":["russian"],"обыск":["russian"],"обычно":["russian"],"обязать":["russian"],"овощи":["russian"],"овраг":["russian"],"овца":["russian"],"оговорка":["russian"],"ограда":["russian"],"огурец":["russian"],"одежда":["russian"],"одеяло":["russian"],"один":["russian"],"однако":["russian"],"одолеть":["russian"],"ожидать":["russian"],"озеро":["russian"],"океан":["russian"],"окно":["russian"],"около":["russian"],"окоп":["russian"],"окраина":["russian"],"октябрь":["russian"],"опасный":["russian"],"опека":["russian"],"операция":["russian"],"описание":["russian"],"оплата":["russian"],"опора":["russian"],"оппонент":["russian"],"оптимизм":["russian"],"оптовый":["russian"],"опухоль":["russian"],"опыт":["russian"],"оратор":["russian"],"орбита":["russian"],"орган":["russian"],"орден":["russian"],"орел":["russian"],"оригинал":["russian"],"ориентир":["russian"],"оркестр":["russian"],"оружие":["russian"],"осенний":["russian"],"осколок":["russian"],"осмотр":["russian"],"остров":["russian"],"отбор":["russian"],"отбыть":["russian"],"отвлечь":["russian"],"отдать":["russian"],"отдел":["russian"],"отдых":["russian"],"отель":["russian"],"отец":["russian"],"отзыв":["russian"],"отказ":["russian"],"отклик":["russian"],"открыть":["russian"],"откуда":["russian"],"отличие":["russian"],"отныне":["russian"],"отойти":["russian"],"отпуск":["russian"],"отрасль":["russian"],"отросток":["russian"],"отрывок":["russian"],"отряд":["russian"],"отсек":["russian"],"отставка":["russian"],"отсюда":["russian"],"оттенок":["russian"],"оттого":["russian"],"отчего":["russian"],"отъезд":["russian"],"офис":["russian"],"офицер":["russian"],"охота":["russian"],"охрана":["russian"],"оценка":["russian"],"очаг":["russian"],"очень":["russian"],"очередь":["russian"],"очищать":["russian"],"ошибка":["russian"],"ощущение":["russian"],"павильон":["russian"],"падать":["russian"],"пазуха":["russian"],"пакет":["russian"],"палата":["russian"],"палец":["russian"],"палуба":["russian"],"пальто":["russian"],"память":["russian"],"панель":["russian"],"паника":["russian"],"пара":["russian"],"парень":["russian"],"пароход":["russian"],"партия":["russian"],"парус":["russian"],"паспорт":["russian"],"пассажир":["russian"],"пастух":["russian"],"патент":["russian"],"патрон":["russian"],"пауза":["russian"],"паук":["russian"],"паутина":["russian"],"пафос":["russian"],"пахнуть":["russian"],"пациент":["russian"],"пачка":["russian"],"певец":["russian"],"педагог":["russian"],"пейзаж":["russian"],"пенсия":["russian"],"пепел":["russian"],"первый":["russian"],"перед":["russian"],"период":["russian"],"перо":["russian"],"перрон":["russian"],"персонаж":["russian"],"перчатка":["russian"],"песня":["russian"],"песок":["russian"],"петля":["russian"],"петрушка":["russian"],"петух":["russian"],"пехота":["russian"],"печать":["russian"],"печень":["russian"],"пешком":["russian"],"пещера":["russian"],"пианист":["russian"],"пиджак":["russian"],"пилот":["russian"],"пионер":["russian"],"пирамида":["russian"],"пирожок":["russian"],"письмо":["russian"],"пища":["russian"],"плавание":["russian"],"плакать":["russian"],"пламя":["russian"],"план":["russian"],"пласт":["russian"],"платить":["russian"],"пленный":["russian"],"плечо":["russian"],"плита":["russian"],"плод":["russian"],"плоский":["russian"],"плотный":["russian"],"плохой":["russian"],"площадь":["russian"],"плыть":["russian"],"плюс":["russian"],"пляж":["russian"],"плясать":["russian"],"победа":["russian"],"повар":["russian"],"повод":["russian"],"повсюду":["russian"],"повязка":["russian"],"погода":["russian"],"погреб":["russian"],"подбор":["russian"],"подвиг":["russian"],"подделка":["russian"],"поджать":["russian"],"поднос":["russian"],"подпись":["russian"],"подруга":["russian"],"подход":["russian"],"подчас":["russian"],"подъезд":["russian"],"поединок":["russian"],"поезд":["russian"],"поесть":["russian"],"поехать":["russian"],"пожалуй":["russian"],"пожилой":["russian"],"позади":["russian"],"позвать":["russian"],"поздний":["russian"],"позиция":["russian"],"позор":["russian"],"поиск":["russian"],"поймать":["russian"],"пойти":["russian"],"поклон":["russian"],"покой":["russian"],"покрыть":["russian"],"полдень":["russian"],"полезный":["russian"],"ползти":["russian"],"полк":["russian"],"полный":["russian"],"половина":["russian"],"полтора":["russian"],"польза":["russian"],"поляна":["russian"],"помидор":["russian"],"помнить":["russian"],"помощь":["russian"],"попасть":["russian"],"поперек":["russian"],"поплыть":["russian"],"пополам":["russian"],"поправка":["russian"],"попугай":["russian"],"попытка":["russian"],"порог":["russian"],"портрет":["russian"],"порция":["russian"],"порыв":["russian"],"порядок":["russian"],"после":["russian"],"посол":["russian"],"посреди":["russian"],"постель":["russian"],"посуда":["russian"],"потом":["russian"],"похвала":["russian"],"похожий":["russian"],"поцелуй":["russian"],"почва":["russian"],"почему":["russian"],"пошлина":["russian"],"поэма":["russian"],"поэтому":["russian"],"право":["russian"],"праздник":["russian"],"практика":["russian"],"прах":["russian"],"преграда":["russian"],"предмет":["russian"],"прежде":["russian"],"прелесть":["russian"],"премия":["russian"],"препарат":["russian"],"пресса":["russian"],"прибыть":["russian"],"прижать":["russian"],"прийти":["russian"],"приказ":["russian"],"прилавок":["russian"],"пример":["russian"],"принять":["russian"],"природа":["russian"],"притом":["russian"],"прихожая":["russian"],"прицел":["russian"],"причина":["russian"],"приют":["russian"],"прогноз":["russian"],"продукт":["russian"],"проект":["russian"],"прожить":["russian"],"прокат":["russian"],"промысел":["russian"],"пропуск":["russian"],"просто":["russian"],"против":["russian"],"профиль":["russian"],"процесс":["russian"],"прочий":["russian"],"прошлый":["russian"],"прощать":["russian"],"пружина":["russian"],"прут":["russian"],"прыжок":["russian"],"прямой":["russian"],"птица":["russian"],"публика":["russian"],"пугать":["russian"],"пуговица":["russian"],"пузырь":["russian"],"пульт":["russian"],"пуля":["russian"],"пункт":["russian"],"пускать":["russian"],"пустой":["russian"],"путь":["russian"],"пухлый":["russian"],"пучок":["russian"],"пушистый":["russian"],"пушка":["russian"],"пчела":["russian"],"пшеница":["russian"],"пылать":["russian"],"пыль":["russian"],"пышный":["russian"],"пьеса":["russian"],"пятка":["russian"],"пятно":["russian"],"пятый":["russian"],"пятьсот":["russian"],"работа":["russian"],"равнина":["russian"],"ради":["russian"],"радость":["russian"],"радуга":["russian"],"разбить":["russian"],"развитие":["russian"],"разговор":["russian"],"раздел":["russian"],"различие":["russian"],"размер":["russian"],"разный":["russian"],"разрыв":["russian"],"разум":["russian"],"район":["russian"],"ракета":["russian"],"раковина":["russian"],"рамка":["russian"],"рано":["russian"],"рапорт":["russian"],"распад":["russian"],"рассказ":["russian"],"расти":["russian"],"расход":["russian"],"расцвет":["russian"],"рация":["russian"],"рвануть":["russian"],"рваться":["russian"],"реакция":["russian"],"ребро":["russian"],"реветь":["russian"],"редактор":["russian"],"редкий":["russian"],"реестр":["russian"],"режим":["russian"],"резать":["russian"],"резерв":["russian"],"резина":["russian"],"резко":["russian"],"резной":["russian"],"рейс":["russian"],"реклама":["russian"],"рекорд":["russian"],"религия":["russian"],"рельс":["russian"],"ремень":["russian"],"ремонт":["russian"],"реплика":["russian"],"репортаж":["russian"],"ресница":["russian"],"ресторан":["russian"],"реформа":["russian"],"рецепт":["russian"],"речь":["russian"],"решение":["russian"],"ржавый":["russian"],"риск":["russian"],"рисунок":["russian"],"ритуал":["russian"],"рифма":["russian"],"робко":["russian"],"робот":["russian"],"ровесник":["russian"],"ровно":["russian"],"родной":["russian"],"рождение":["russian"],"роза":["russian"],"розовый":["russian"],"розыск":["russian"],"роль":["russian"],"роман":["russian"],"роскошь":["russian"],"роспись":["russian"],"рост":["russian"],"рубашка":["russian"],"рубеж":["russian"],"рубить":["russian"],"рубрика":["russian"],"рудник":["russian"],"рука":["russian"],"рукопись":["russian"],"румяный":["russian"],"русло":["russian"],"рухнуть":["russian"],"ручей":["russian"],"ручной":["russian"],"рыба":["russian"],"рыжий":["russian"],"рынок":["russian"],"рыхлый":["russian"],"рыцарь":["russian"],"рычаг":["russian"],"рюкзак":["russian"],"рядом":["russian"],"садовый":["russian"],"сажать":["russian"],"салон":["russian"],"салфетка":["russian"],"салют":["russian"],"самец":["russian"],"самовар":["russian"],"самый":["russian"],"сани":["russian"],"санкция":["russian"],"сапог":["russian"],"сарай":["russian"],"сатира":["russian"],"сахар":["russian"],"сбить":["russian"],"сбоку":["russian"],"сборная":["russian"],"сбыт":["russian"],"свадьба":["russian"],"свалка":["russian"],"сварить":["russian"],"свежий":["russian"],"сверху":["russian"],"свет":["russian"],"свеча":["russian"],"свинья":["russian"],"свист":["russian"],"свитер":["russian"],"свобода":["russian"],"сводка":["russian"],"свой":["russian"],"свыше":["russian"],"связь":["russian"],"сдаться":["russian"],"сделать":["russian"],"сегмент":["russian"],"сегодня":["russian"],"седло":["russian"],"седой":["russian"],"седьмой":["russian"],"сезон":["russian"],"сейф":["russian"],"сейчас":["russian"],"секрет":["russian"],"сектор":["russian"],"секунда":["russian"],"семинар":["russian"],"семья":["russian"],"сенатор":["russian"],"сено":["russian"],"сенсация":["russian"],"сентябрь":["russian"],"сервис":["russian"],"сердце":["russian"],"середина":["russian"],"сержант":["russian"],"серия":["russian"],"серый":["russian"],"сессия":["russian"],"сесть":["russian"],"сетевой":["russian"],"сжатый":["russian"],"сжечь":["russian"],"сзади":["russian"],"сигнал":["russian"],"сиденье":["russian"],"сила":["russian"],"силуэт":["russian"],"сильный":["russian"],"символ":["russian"],"симпатия":["russian"],"симфония":["russian"],"синий":["russian"],"синтез":["russian"],"синяк":["russian"],"сирень":["russian"],"система":["russian"],"ситуация":["russian"],"сияние":["russian"],"сказать":["russian"],"скала":["russian"],"скамейка":["russian"],"скандал":["russian"],"скатерть":["russian"],"скачок":["russian"],"скважина":["russian"],"сквер":["russian"],"сквозь":["russian"],"скелет":["russian"],"скидка":["russian"],"склад":["russian"],"сколько":["russian"],"скорый":["russian"],"скосить":["russian"],"скот":["russian"],"скрипка":["russian"],"скудный":["russian"],"скука":["russian"],"слабый":["russian"],"слава":["russian"],"сладкий":["russian"],"слегка":["russian"],"след":["russian"],"слеза":["russian"],"слепой":["russian"],"слесарь":["russian"],"слишком":["russian"],"слово":["russian"],"слог":["russian"],"сложный":["russian"],"сломать":["russian"],"служба":["russian"],"слух":["russian"],"случай":["russian"],"слышать":["russian"],"слюна":["russian"],"смежный":["russian"],"смелый":["russian"],"сменить":["russian"],"смесь":["russian"],"сметана":["russian"],"смех":["russian"],"смола":["russian"],"смуглый":["russian"],"смутный":["russian"],"смущать":["russian"],"смысл":["russian"],"снайпер":["russian"],"снаряд":["russian"],"сначала":["russian"],"снег":["russian"],"снизу":["russian"],"сниться":["russian"],"сно��а":["russian"],"снять":["russian"],"собака":["russian"],"соблазн":["russian"],"собрание":["russian"],"событие":["russian"],"совесть":["russian"],"совсем":["russian"],"согласие":["russian"],"создать":["russian"],"сознание":["russian"],"созреть":["russian"],"сойтись":["russian"],"сокол":["russian"],"солдат":["russian"],"соленый":["russian"],"солнце":["russian"],"солома":["russian"],"сомнение":["russian"],"сонный":["russian"],"соперник":["russian"],"соратник":["russian"],"сорвать":["russian"],"сосед":["russian"],"сосиска":["russian"],"состав":["russian"],"сотня":["russian"],"соус":["russian"],"союз":["russian"],"спад":["russian"],"спальня":["russian"],"спасти":["russian"],"спектр":["russian"],"сперва":["russian"],"спешить":["russian"],"спина":["russian"],"спирт":["russian"],"список":["russian"],"спичка":["russian"],"сплав":["russian"],"спонсор":["russian"],"спор":["russian"],"способ":["russian"],"справка":["russian"],"спустя":["russian"],"спутник":["russian"],"сразу":["russian"],"средство":["russian"],"срок":["russian"],"срыв":["russian"],"ссора":["russian"],"ссылка":["russian"],"ставить":["russian"],"стадия":["russian"],"стакан":["russian"],"станция":["russian"],"старый":["russian"],"стая":["russian"],"стебель":["russian"],"стекло":["russian"],"стена":["russian"],"степень":["russian"],"стереть":["russian"],"стиль":["russian"],"стимул":["russian"],"стирать":["russian"],"стихи":["russian"],"стоить":["russian"],"стойка":["russian"],"стол":["russian"],"стонать":["russian"],"стопа":["russian"],"сторона":["russian"],"стоянка":["russian"],"страна":["russian"],"стричь":["russian"],"строгий":["russian"],"струя":["russian"],"студент":["russian"],"стук":["russian"],"ступня":["russian"],"стыдно":["russian"],"суббота":["russian"],"субъект":["russian"],"сувенир":["russian"],"сугроб":["russian"],"сугубо":["russian"],"судить":["russian"],"судно":["russian"],"судьба":["russian"],"суета":["russian"],"суметь":["russian"],"сумма":["russian"],"сумрак":["russian"],"сундук":["russian"],"супруг":["russian"],"суровый":["russian"],"сутки":["russian"],"сухой":["russian"],"суша":["russian"],"существо":["russian"],"сфера":["russian"],"схема":["russian"],"схожий":["russian"],"сценарий":["russian"],"счастье":["russian"],"считать":["russian"],"съезд":["russian"],"сыграть":["russian"],"сырой":["russian"],"сытый":["russian"],"сыщик":["russian"],"сюда":["russian"],"сюжет":["russian"],"сюрприз":["russian"],"тайна":["russian"],"также":["russian"],"такой":["russian"],"такси":["russian"],"тактика":["russian"],"талия":["russian"],"таможня":["russian"],"танец":["russian"],"таракан":["russian"],"тарелка":["russian"],"тариф":["russian"],"тащить":["russian"],"таять":["russian"],"тварь":["russian"],"театр":["russian"],"тезис":["russian"],"текст":["russian"],"текущий":["russian"],"телефон":["russian"],"тема":["russian"],"темнота":["russian"],"теневой":["russian"],"теннис":["russian"],"теория":["russian"],"теперь":["russian"],"тепло":["russian"],"терапия":["russian"],"терзать":["russian"],"термин":["russian"],"терпеть":["russian"],"терраса":["russian"],"терять":["russian"],"тесный":["russian"],"тетрадь":["russian"],"техника":["russian"],"течение":["russian"],"тигр":["russian"],"типовой":["russian"],"тираж":["russian"],"титул":["russian"],"тихий":["russian"],"ткань":["russian"],"товарищ":["russian"],"тоже":["russian"],"толпа":["russian"],"толстый":["russian"],"толчок":["russian"],"толщина":["russian"],"только":["russian"],"тонкий":["russian"],"тонна":["russian"],"топить":["russian"],"топор":["russian"],"торговля":["russian"],"тормоз":["russian"],"торчать":["russian"],"тотчас":["russian"],"точка":["russian"],"точно":["russian"],"тощий":["russian"],"трава":["russian"],"традиция":["russian"],"трактор":["russian"],"трамвай":["russian"],"траншея":["russian"],"трасса":["russian"],"тревога":["russian"],"трезвый":["russian"],"тренер":["russian"],"трепет":["russian"],"треск":["russian"],"третий":["russian"],"трещина":["russian"],"трибуна":["russian"],"тридцать":["russian"],"триста":["russian"],"триумф":["russian"],"трогать":["russian"],"тройка":["russian"],"тронуть":["russian"],"тропа":["russian"],"тротуар":["russian"],"трубка":["russian"],"труд":["russian"],"трюк":["russian"],"тряпка":["russian"],"туго":["russian"],"туловище":["russian"],"туман":["russian"],"тумбочка":["russian"],"тундра":["russian"],"тупик":["russian"],"турист":["russian"],"турнир":["russian"],"тусклый":["russian"],"туфля":["russian"],"туча":["russian"],"тысяча":["russian"],"тяга":["russian"],"тяжело":["russian"],"убежать":["russian"],"убогий":["russian"],"уборка":["russian"],"уважение":["russian"],"увезти":["russian"],"уволить":["russian"],"угадать":["russian"],"угол":["russian"],"угощать":["russian"],"угроза":["russian"],"угрюмый":["russian"],"удар":["russian"],"удачный":["russian"],"уделять":["russian"],"удивить":["russian"],"удобный":["russian"],"удочка":["russian"],"уезжать":["russian"],"ужин":["russian"],"узел":["russian"],"узкий":["russian"],"уйти":["russian"],"указание":["russian"],"уклон":["russian"],"украсть":["russian"],"укусить":["russian"],"улетать":["russian"],"улица":["russian"],"улыбка":["russian"],"умело":["russian"],"умение":["russian"],"умный":["russian"],"умолять":["russian"],"унести":["russian"],"унижать":["russian"],"унылый":["russian"],"упаковка":["russian"],"упасть":["russian"],"упорно":["russian"],"упрек":["russian"],"урна":["russian"],"уровень":["russian"],"урожай":["russian"],"уронить":["russian"],"усадьба":["russian"],"усатый":["russian"],"усвоить":["russian"],"усилие":["russian"],"условие":["russian"],"услуга":["russian"],"усмешка":["russian"],"успеть":["russian"],"устав":["russian"],"устоять":["russian"],"утечка":["russian"],"утешать":["russian"],"утро":["russian"],"уцелеть":["russian"],"участие":["russian"],"ученик":["russian"],"учесть":["russian"],"ущелье":["russian"],"ущерб":["russian"],"уютный":["russian"],"фабрика":["russian"],"фаворит":["russian"],"факел":["russian"],"факт":["russian"],"фамилия":["russian"],"фантазия":["russian"],"фасад":["russian"],"февраль":["russian"],"феномен":["russian"],"фермер":["russian"],"фигура":["russian"],"физика":["russian"],"филиал":["russian"],"философ":["russian"],"фильм":["russian"],"финал":["russian"],"флаг":["russian"],"флот":["russian"],"фойе":["russian"],"фокус":["russian"],"фонарь":["russian"],"фонд":["russian"],"фонтан":["russian"],"форма":["russian"],"форум":["russian"],"фото":["russian"],"фрагмент":["russian"],"фраза":["russian"],"фракция":["russian"],"фронт":["russian"],"фрукт":["russian"],"функция":["russian"],"фуражка":["russian"],"футбол":["russian"],"футляр":["russian"],"халат":["russian"],"хаос":["russian"],"характер":["russian"],"хата":["russian"],"хвалить":["russian"],"хватать":["russian"],"хвойный":["russian"],"хвост":["russian"],"химия":["russian"],"хирург":["russian"],"хитрый":["russian"],"хищник":["russian"],"хлеб":["russian"],"хлынуть":["russian"],"хмурый":["russian"],"ходить":["russian"],"хозяин":["russian"],"хоккей":["russian"],"холм":["russian"],"холст":["russian"],"хорошо":["russian"],"хотеть":["russian"],"храбрый":["russian"],"храм":["russian"],"хранить":["russian"],"хребет":["russian"],"хрен":["russian"],"хрипло":["russian"],"хроника":["russian"],"хрупкий":["russian"],"художник":["russian"],"худший":["russian"],"хулиган":["russian"],"хутор":["russian"],"царь":["russian"],"цветок":["russian"],"целевой":["russian"],"целиком":["russian"],"целое":["russian"],"цель":["russian"],"цензура":["russian"],"ценить":["russian"],"центр":["russian"],"цепной":["russian"],"цикл":["russian"],"цилиндр":["russian"],"цирк":["russian"],"цитата":["russian"],"цифра":["russian"],"чайник":["russian"],"часы":["russian"],"чашка":["russian"],"человек":["russian"],"челюсть":["russian"],"чемодан":["russian"],"чемпион":["russian"],"чепуха":["russian"],"червь":["russian"],"чердак":["russian"],"через":["russian"],"чернила":["russian"],"черта":["russian"],"чеснок":["russian"],"честно":["russian"],"четверть":["russian"],"четыре":["russian"],"число":["russian"],"чистый":["russian"],"читатель":["russian"],"чтение":["russian"],"чтобы":["russian"],"чувство":["russian"],"чудак":["russian"],"чудный":["russian"],"чудо":["russian"],"чужой":["russian"],"чулок":["russian"],"чума":["russian"],"чушь":["russian"],"чуять":["russian"],"шагать":["russian"],"шанс":["russian"],"шапка":["russian"],"шарик":["russian"],"шарф":["russian"],"шахматы":["russian"],"шашлык":["russian"],"шедевр":["russian"],"шептать":["russian"],"шерсть":["russian"],"шестой":["russian"],"шинель":["russian"],"ширина":["russian"],"шишка":["russian"],"шкаф":["russian"],"школа":["russian"],"шкура":["russian"],"шланг":["russian"],"шлем":["russian"],"шнур":["russian"],"шоколад":["russian"],"шорох":["russian"],"шоссе":["russian"],"шпион":["russian"],"шприц":["russian"],"штаб":["russian"],"штамм":["russian"],"штаны":["russian"],"штатный":["russian"],"штора":["russian"],"штраф":["russian"],"штурм":["russian"],"штык":["russian"],"шумно":["russian"],"шуршать":["russian"],"шутить":["russian"],"шутка":["russian"],"щедрый":["russian"],"щека":["russian"],"щенок":["russian"],"экзамен":["russian"],"экипаж":["russian"],"экономия":["russian"],"экран":["russian"],"эксперт":["russian"],"элемент":["russian"],"элитный":["russian"],"эмоция":["russian"],"энергия":["russian"],"эпизод":["russian"],"эпоха":["russian"],"эскиз":["russian"],"эстрада":["russian"],"этап":["russian"],"этика":["russian"],"этот":["russian"],"эфир":["russian"],"эффект":["russian"],"эшелон":["russian"],"юбилей":["russian"],"юбка":["russian"],"южный":["russian"],"юмор":["russian"],"юность":["russian"],"юрист":["russian"],"юстиция":["russian"],"яблоко":["russian"],"явление":["russian"],"ягода":["russian"],"ядро":["russian"],"язык":["russian"],"яйцо":["russian"],"якобы":["russian"],"якорь":["russian"],"январь":["russian"],"яркий":["russian"],"ярмарка":["russian"],"ярость":["russian"],"ясный":["russian"],"яхта":["russian"],"ячейка":["russian"],"ящик":["russian"],"ábaco":["spanish"],"abdomen":["spanish"],"abeja":["spanish"],"abierto":["spanish"],"abogado":["spanish"],"abono":["spanish"],"aborto":["spanish"],"abrazo":["spanish"],"abrir":["spanish"],"abuelo":["spanish"],"abuso":["spanish"],"acabar":["spanish"],"academia":["spanish"],"acceso":["spanish"],"acción":["spanish"],"aceite":["spanish"],"acelga":["spanish"],"acento":["spanish"],"aceptar":["spanish"],"ácido":["spanish"],"aclarar":["spanish"],"acné":["spanish"],"acoger":["spanish"],"acoso":["spanish"],"activo":["spanish"],"acto":["spanish"],"actriz":["spanish"],"actuar":["spanish"],"acudir":["spanish"],"acuerdo":["spanish"],"acusar":["spanish"],"adicto":["spanish"],"admitir":["spanish"],"adoptar":["spanish"],"adorno":["spanish"],"aduana":["spanish"],"adulto":["spanish"],"aéreo":["spanish"],"afectar":["spanish"],"afición":["spanish"],"afinar":["spanish"],"afirmar":["spanish"],"ágil":["spanish"],"agitar":["spanish"],"agonía":["spanish"],"agosto":["spanish"],"agotar":["spanish"],"agregar":["spanish"],"agrio":["spanish"],"agua":["spanish"],"agudo":["spanish"],"águila":["spanish"],"aguja":["spanish"],"ahogo":["spanish"],"ahorro":["spanish"],"aire":["spanish"],"aislar":["spanish"],"ajedrez":["spanish"],"ajeno":["spanish"],"ajuste":["spanish"],"alacrán":["spanish"],"alambre":["spanish"],"alarma":["spanish"],"alba":["spanish"],"álbum":["spanish"],"alcalde":["spanish"],"aldea":["spanish"],"alegre":["spanish"],"alejar":["spanish"],"alerta":["spanish"],"aleta":["spanish"],"alfiler":["spanish"],"alga":["spanish"],"algodón":["spanish"],"aliado":["spanish"],"aliento":["spanish"],"alivio":["spanish"],"alma":["spanish"],"almeja":["spanish"],"almíbar":["spanish"],"altar":["spanish"],"alteza":["spanish"],"altivo":["spanish"],"alto":["spanish"],"altura":["spanish"],"alumno":["spanish"],"alzar":["spanish"],"amable":["spanish"],"amante":["spanish"],"amapola":["spanish"],"amargo":["spanish"],"amasar":["spanish"],"ámbar":["spanish"],"ámbito":["spanish"],"ameno":["spanish"],"amigo":["spanish","turkish"],"amistad":["spanish"],"amor":["spanish"],"amparo":["spanish"],"amplio":["spanish"],"ancho":["spanish"],"anciano":["spanish"],"ancla":["spanish"],"andar":["spanish"],"andén":["spanish"],"anemia":["spanish"],"ángulo":["spanish"],"anillo":["spanish"],"ánimo":["spanish"],"anís":["spanish"],"anotar":["spanish"],"antena":["spanish"],"antiguo":["spanish"],"antojo":["spanish"],"anual":["spanish"],"anular":["spanish"],"anuncio":["spanish"],"añadir":["spanish"],"añejo":["spanish"],"año":["spanish"],"apagar":["spanish"],"aparato":["spanish"],"apetito":["spanish"],"apio":["spanish"],"aplicar":["spanish"],"apodo":["spanish"],"aporte":["spanish"],"apoyo":["spanish"],"aprender":["spanish"],"aprobar":["spanish"],"apuesta":["spanish"],"apuro":["spanish"],"arado":["spanish"],"araña":["spanish"],"arar":["spanish"],"árbitro":["spanish"],"árbol":["spanish"],"arbusto":["spanish"],"archivo":["spanish"],"arco":["spanish"],"arder":["spanish"],"ardilla":["spanish"],"arduo":["spanish"],"área":["spanish"],"árido":["spanish"],"aries":["spanish"],"armonía":["spanish"],"arnés":["spanish"],"aroma":["spanish","turkish"],"arpa":["spanish"],"arpón":["spanish"],"arreglo":["spanish"],"arroz":["spanish"],"arruga":["spanish"],"arte":["spanish"],"artista":["spanish"],"asa":["spanish"],"asado":["spanish"],"asalto":["spanish"],"ascenso":["spanish"],"asegurar":["spanish"],"aseo":["spanish"],"asesor":["spanish"],"asiento":["spanish"],"asilo":["spanish"],"asistir":["spanish"],"asno":["spanish"],"asombro":["spanish"],"áspero":["spanish"],"astilla":["spanish"],"astro":["spanish"],"astuto":["spanish"],"asumir":["spanish"],"asunto":["spanish"],"atajo":["spanish"],"ataque":["spanish"],"atar":["spanish"],"atento":["spanish"],"ateo":["spanish"],"ático":["spanish"],"atleta":["spanish"],"átomo":["spanish"],"atraer":["spanish"],"atroz":["spanish"],"atún":["spanish"],"audaz":["spanish"],"audio":["spanish"],"auge":["spanish"],"aula":["spanish"],"aumento":["spanish"],"ausente":["spanish"],"autor":["spanish"],"aval":["spanish"],"avance":["spanish"],"avaro":["spanish"],"ave":["spanish"],"avellana":["spanish"],"avena":["spanish"],"avestruz":["spanish"],"avión":["spanish"],"aviso":["spanish"],"ayer":["spanish"],"ayuda":["spanish"],"ayuno":["spanish"],"azafrán":["spanish"],"azar":["spanish"],"azote":["spanish"],"azúcar":["spanish"],"azufre":["spanish"],"azul":["spanish"],"baba":["spanish"],"babor":["spanish"],"bache":["spanish"],"bahía":["spanish"],"baile":["spanish"],"bajar":["spanish"],"balanza":["spanish"],"balcón":["spanish"],"balde":["spanish"],"bambú":["spanish"],"banco":["spanish"],"banda":["spanish"],"baño":["spanish"],"barba":["spanish"],"barco":["spanish"],"barniz":["spanish"],"barro":["spanish"],"báscula":["spanish"],"bastón":["spanish"],"basura":["spanish"],"batalla":["spanish"],"batería":["spanish"],"batir":["spanish"],"batuta":["spanish"],"baúl":["spanish"],"bazar":["spanish"],"bebé":["spanish"],"bebida":["spanish"],"bello":["spanish"],"besar":["spanish"],"beso":["spanish"],"bestia":["spanish"],"bicho":["spanish"],"bien":["spanish"],"bingo":["spanish"],"blanco":["spanish"],"bloque":["spanish"],"blusa":["spanish"],"boa":["spanish"],"bobina":["spanish"],"bobo":["spanish"],"boca":["spanish"],"bocina":["spanish"],"boda":["spanish"],"bodega":["spanish"],"boina":["spanish"],"bola":["spanish"],"bolero":["spanish","turkish"],"bolsa":["spanish"],"bomba":["spanish"],"bondad":["spanish"],"bonito":["spanish"],"bono":["spanish"],"bonsái":["spanish"],"borde":["spanish"],"borrar":["spanish"],"bosque":["spanish"],"bote":["spanish"],"botín":["spanish"],"bóveda":["spanish"],"bozal":["spanish"],"bravo":["spanish"],"brazo":["spanish"],"brecha":["spanish"],"breve":["spanish"],"brillo":["spanish"],"brinco":["spanish"],"brisa":["spanish"],"broca":["spanish"],"broma":["spanish"],"bronce":["spanish"],"brote":["spanish"],"bruja":["spanish"],"brusco":["spanish"],"bruto":["spanish"],"buceo":["spanish"],"bucle":["spanish"],"bueno":["spanish"],"buey":["spanish"],"bufanda":["spanish"],"bufón":["spanish"],"búho":["spanish"],"buitre":["spanish"],"bulto":["spanish"],"burbuja":["spanish"],"burla":["spanish"],"burro":["spanish"],"buscar":["spanish"],"butaca":["spanish"],"buzón":["spanish"],"caballo":["spanish"],"cabeza":["spanish"],"cabina":["spanish"],"cabra":["spanish"],"cacao":["spanish"],"cadáver":["spanish"],"cadena":["spanish"],"caer":["spanish"],"café":["spanish"],"caída":["spanish"],"caimán":["spanish"],"caja":["spanish"],"cajón":["spanish"],"cal":["spanish"],"calamar":["spanish"],"calcio":["spanish"],"caldo":["spanish"],"calidad":["spanish"],"calle":["spanish"],"calma":["spanish"],"calor":["spanish"],"calvo":["spanish"],"cama":["spanish"],"cambio":["spanish"],"camello":["spanish"],"camino":["spanish"],"campo":["spanish"],"cáncer":["spanish"],"candil":["spanish"],"canela":["spanish"],"canguro":["spanish"],"canica":["spanish"],"canto":["spanish"],"caña":["spanish"],"cañón":["spanish"],"caoba":["spanish"],"caos":["spanish"],"capaz":["spanish"],"capitán":["spanish"],"capote":["spanish"],"captar":["spanish"],"capucha":["spanish"],"cara":["spanish"],"carbón":["spanish"],"cárcel":["spanish"],"careta":["spanish"],"carga":["spanish"],"cariño":["spanish"],"carne":["spanish"],"carpeta":["spanish"],"carro":["spanish"],"carta":["spanish"],"casa":["spanish"],"casco":["spanish"],"casero":["spanish"],"caspa":["spanish"],"castor":["spanish"],"catorce":["spanish"],"catre":["spanish"],"caudal":["spanish"],"causa":["spanish"],"cazo":["spanish"],"cebolla":["spanish"],"ceder":["spanish"],"cedro":["spanish"],"celda":["spanish"],"célebre":["spanish"],"celoso":["spanish"],"célula":["spanish"],"cemento":["spanish"],"ceniza":["spanish"],"centro":["spanish"],"cerca":["spanish"],"cerdo":["spanish"],"cereza":["spanish"],"cero":["spanish"],"cerrar":["spanish"],"certeza":["spanish"],"césped":["spanish"],"cetro":["spanish"],"chacal":["spanish"],"chaleco":["spanish"],"champú":["spanish"],"chancla":["spanish"],"chapa":["spanish"],"charla":["spanish"],"chico":["spanish"],"chiste":["spanish"],"chivo":["spanish"],"choque":["spanish"],"choza":["spanish"],"chuleta":["spanish"],"chupar":["spanish"],"ciclón":["spanish"],"ciego":["spanish"],"cielo":["spanish"],"cien":["spanish"],"cierto":["spanish"],"cifra":["spanish"],"cigarro":["spanish"],"cima":["spanish"],"cinco":["spanish"],"cine":["spanish"],"cinta":["spanish"],"ciprés":["spanish"],"circo":["spanish"],"ciruela":["spanish"],"cisne":["spanish"],"cita":["spanish"],"ciudad":["spanish"],"clamor":["spanish"],"clan":["spanish"],"claro":["spanish"],"clase":["spanish"],"clave":["spanish"],"cliente":["spanish"],"clima":["spanish"],"clínica":["spanish"],"cobre":["spanish"],"cocción":["spanish"],"cochino":["spanish"],"cocina":["spanish"],"coco":["spanish"],"código":["spanish"],"codo":["spanish"],"cofre":["spanish"],"coger":["spanish"],"cohete":["spanish"],"cojín":["spanish"],"cojo":["spanish"],"cola":["spanish"],"colcha":["spanish"],"colegio":["spanish"],"colgar":["spanish"],"colina":["spanish"],"collar":["spanish"],"colmo":["spanish"],"columna":["spanish"],"combate":["spanish"],"comer":["spanish"],"comida":["spanish"],"cómodo":["spanish"],"compra":["spanish"],"conde":["spanish"],"conejo":["spanish"],"conga":["spanish"],"conocer":["spanish"],"consejo":["spanish"],"contar":["spanish"],"copa":["spanish"],"copia":["spanish"],"corazón":["spanish"],"corbata":["spanish"],"corcho":["spanish"],"cordón":["spanish"],"corona":["spanish"],"correr":["spanish"],"coser":["spanish"],"cosmos":["spanish"],"costa":["spanish"],"cráneo":["spanish"],"cráter":["spanish"],"crear":["spanish"],"crecer":["spanish"],"creído":["spanish"],"crema":["spanish"],"cría":["spanish"],"crimen":["spanish"],"cripta":["spanish"],"crisis":["spanish"],"cromo":["spanish"],"crónica":["spanish"],"croqueta":["spanish"],"crudo":["spanish"],"cruz":["spanish"],"cuadro":["spanish"],"cuarto":["spanish"],"cuatro":["spanish"],"cubo":["spanish"],"cubrir":["spanish"],"cuchara":["spanish"],"cuello":["spanish"],"cuento":["spanish"],"cuerda":["spanish"],"cuesta":["spanish"],"cueva":["spanish"],"cuidar":["spanish"],"culebra":["spanish"],"culpa":["spanish"],"culto":["spanish"],"cumbre":["spanish"],"cumplir":["spanish"],"cuna":["spanish"],"cuneta":["spanish"],"cuota":["spanish"],"cupón":["spanish"],"cúpula":["spanish"],"curar":["spanish"],"curioso":["spanish"],"curso":["spanish"],"curva":["spanish"],"cutis":["spanish"],"dama":["spanish"],"danza":["spanish"],"dar":["spanish"],"dardo":["spanish"],"dátil":["spanish"],"deber":["spanish"],"débil":["spanish"],"década":["spanish"],"decir":["spanish"],"dedo":["spanish"],"defensa":["spanish"],"definir":["spanish"],"dejar":["spanish"],"delfín":["spanish"],"delgado":["spanish"],"delito":["spanish"],"demora":["spanish"],"denso":["spanish"],"dental":["spanish"],"deporte":["spanish"],"derecho":["spanish"],"derrota":["spanish"],"desayuno":["spanish"],"deseo":["spanish"],"desfile":["spanish"],"desnudo":["spanish"],"destino":["spanish"],"desvío":["spanish"],"detalle":["spanish"],"detener":["spanish"],"deuda":["spanish"],"día":["spanish"],"diablo":["spanish"],"diadema":["spanish"],"diamante":["spanish"],"diana":["spanish"],"diario":["spanish"],"dibujo":["spanish"],"dictar":["spanish"],"diente":["spanish"],"dieta":["spanish"],"diez":["spanish"],"difícil":["spanish"],"digno":["spanish"],"dilema":["spanish"],"diluir":["spanish"],"dinero":["spanish"],"directo":["spanish"],"dirigir":["spanish"],"disco":["spanish"],"diseño":["spanish"],"disfraz":["spanish"],"diva":["spanish"],"divino":["spanish"],"doble":["spanish"],"doce":["spanish"],"dolor":["spanish"],"domingo":["spanish"],"don":["spanish"],"donar":["spanish"],"dorado":["spanish"],"dormir":["spanish"],"dorso":["spanish"],"dos":["spanish"],"dosis":["spanish"],"dragón":["spanish"],"droga":["spanish"],"ducha":["spanish"],"duda":["spanish"],"duelo":["spanish"],"dueño":["spanish"],"dulce":["spanish"],"dúo":["spanish"],"duque":["spanish"],"durar":["spanish"],"dureza":["spanish"],"duro":["spanish"],"ébano":["spanish"],"ebrio":["spanish"],"echar":["spanish"],"eco":["spanish"],"ecuador":["spanish"],"edad":["spanish"],"edición":["spanish"],"edificio":["spanish"],"editor":["spanish"],"educar":["spanish"],"efecto":["spanish"],"eficaz":["spanish"],"eje":["spanish"],"ejemplo":["spanish"],"elefante":["spanish"],"elegir":["spanish"],"elemento":["spanish"],"elevar":["spanish"],"elipse":["spanish"],"élite":["spanish"],"elixir":["spanish"],"elogio":["spanish"],"eludir":["spanish"],"embudo":["spanish"],"emitir":["spanish"],"emoción":["spanish"],"empate":["spanish"],"empeño":["spanish"],"empleo":["spanish"],"empresa":["spanish"],"enano":["spanish"],"encargo":["spanish"],"enchufe":["spanish"],"encía":["spanish"],"enemigo":["spanish"],"enero":["spanish"],"enfado":["spanish"],"enfermo":["spanish"],"engaño":["spanish"],"enigma":["spanish"],"enlace":["spanish"],"enorme":["spanish"],"enredo":["spanish"],"ensayo":["spanish"],"enseñar":["spanish"],"entero":["spanish"],"entrar":["spanish"],"envase":["spanish"],"envío":["spanish"],"época":["spanish"],"equipo":["spanish"],"erizo":["spanish"],"escala":["spanish"],"escena":["spanish"],"escolar":["spanish"],"escribir":["spanish"],"escudo":["spanish"],"esencia":["spanish"],"esfera":["spanish"],"esfuerzo":["spanish"],"espada":["spanish"],"espejo":["spanish"],"espía":["spanish"],"esposa":["spanish"],"espuma":["spanish"],"esquí":["spanish"],"estar":["spanish"],"este":["spanish"],"estilo":["spanish"],"estufa":["spanish"],"etapa":["spanish"],"eterno":["spanish"],"ética":["spanish"],"etnia":["spanish"],"evadir":["spanish"],"evaluar":["spanish"],"evento":["spanish"],"evitar":["spanish"],"exacto":["spanish"],"examen":["spanish"],"exceso":["spanish"],"excusa":["spanish"],"exento":["spanish"],"exigir":["spanish"],"exilio":["spanish"],"existir":["spanish"],"éxito":["spanish"],"experto":["spanish"],"explicar":["spanish"],"exponer":["spanish"],"extremo":["spanish"],"fábrica":["spanish"],"fábula":["spanish"],"fachada":["spanish"],"fácil":["spanish"],"factor":["spanish"],"faena":["spanish"],"faja":["spanish"],"falda":["spanish"],"fallo":["spanish"],"falso":["spanish"],"faltar":["spanish"],"fama":["spanish"],"familia":["spanish"],"famoso":["spanish"],"faraón":["spanish"],"farmacia":["spanish"],"farol":["spanish"],"farsa":["spanish"],"fase":["spanish"],"fatiga":["spanish"],"fauna":["spanish","turkish"],"favor":["spanish"],"fax":["spanish"],"febrero":["spanish"],"fecha":["spanish"],"feliz":["spanish"],"feo":["spanish"],"feria":["spanish"],"feroz":["spanish"],"fértil":["spanish"],"fervor":["spanish"],"festín":["spanish"],"fiable":["spanish"],"fianza":["spanish"],"fiar":["spanish"],"fibra":["spanish"],"ficción":["spanish"],"ficha":["spanish"],"fideo":["spanish"],"fiebre":["spanish"],"fiel":["spanish"],"fiera":["spanish"],"fiesta":["spanish"],"figura":["spanish"],"fijar":["spanish"],"fijo":["spanish"],"fila":["spanish"],"filete":["spanish"],"filial":["spanish"],"filtro":["spanish"],"fin":["spanish"],"finca":["spanish"],"fingir":["spanish"],"finito":["spanish"],"firma":["spanish"],"flaco":["spanish"],"flauta":["spanish"],"flecha":["spanish"],"flor":["spanish"],"flota":["spanish"],"fluir":["spanish"],"flujo":["spanish"],"flúor":["spanish"],"fobia":["spanish"],"foca":["spanish"],"fogata":["spanish"],"fogón":["spanish"],"folio":["spanish"],"folleto":["spanish"],"fondo":["spanish"],"forma":["spanish"],"forro":["spanish"],"fortuna":["spanish"],"forzar":["spanish"],"fosa":["spanish"],"foto":["spanish"],"fracaso":["spanish"],"frágil":["spanish"],"franja":["spanish"],"frase":["spanish"],"fraude":["spanish"],"freír":["spanish"],"freno":["spanish"],"fresa":["spanish"],"frío":["spanish"],"frito":["spanish"],"fruta":["spanish"],"fuego":["spanish"],"fuente":["spanish"],"fuerza":["spanish"],"fuga":["spanish"],"fumar":["spanish"],"función":["spanish"],"funda":["spanish"],"furgón":["spanish"],"furia":["spanish"],"fusil":["spanish"],"fútbol":["spanish"],"futuro":["spanish"],"gacela":["spanish"],"gafas":["spanish"],"gaita":["spanish"],"gajo":["spanish"],"gala":["spanish"],"galería":["spanish"],"gallo":["spanish"],"gamba":["spanish"],"ganar":["spanish"],"gancho":["spanish"],"ganga":["spanish"],"ganso":["spanish"],"garaje":["spanish"],"garza":["spanish"],"gasolina":["spanish"],"gastar":["spanish"],"gato":["spanish"],"gavilán":["spanish"],"gemelo":["spanish"],"gemir":["spanish"],"gen":["spanish"],"género":["spanish"],"genio":["spanish"],"gente":["spanish"],"geranio":["spanish"],"gerente":["spanish"],"germen":["spanish"],"gesto":["spanish"],"gigante":["spanish"],"gimnasio":["spanish"],"girar":["spanish"],"giro":["spanish"],"glaciar":["spanish"],"globo":["spanish"],"gloria":["spanish"],"gol":["spanish"],"golfo":["spanish"],"goloso":["spanish"],"golpe":["spanish"],"goma":["spanish"],"gordo":["spanish"],"gorila":["spanish"],"gorra":["spanish"],"gota":["spanish"],"goteo":["spanish"],"gozar":["spanish"],"grada":["spanish"],"gráfico":["spanish"],"grano":["spanish"],"grasa":["spanish"],"gratis":["spanish"],"grave":["spanish"],"grieta":["spanish"],"grillo":["spanish"],"gripe":["spanish"],"gris":["spanish"],"grito":["spanish"],"grosor":["spanish"],"grúa":["spanish"],"grueso":["spanish"],"grumo":["spanish"],"grupo":["spanish"],"guante":["spanish"],"guapo":["spanish"],"guardia":["spanish"],"guerra":["spanish"],"guía":["spanish"],"guiño":["spanish"],"guion":["spanish"],"guiso":["spanish"],"guitarra":["spanish"],"gusano":["spanish"],"gustar":["spanish"],"haber":["spanish","turkish"],"hábil":["spanish"],"hablar":["spanish"],"hacer":["spanish"],"hacha":["spanish"],"hada":["spanish"],"hallar":["spanish"],"hamaca":["spanish"],"harina":["spanish"],"haz":["spanish"],"hazaña":["spanish"],"hebilla":["spanish"],"hebra":["spanish"],"hecho":["spanish"],"helado":["spanish"],"helio":["spanish"],"hembra":["spanish"],"herir":["spanish"],"hermano":["spanish"],"héroe":["spanish"],"hervir":["spanish"],"hielo":["spanish"],"hierro":["spanish"],"hígado":["spanish"],"higiene":["spanish"],"hijo":["spanish"],"himno":["spanish"],"historia":["spanish"],"hocico":["spanish"],"hogar":["spanish"],"hoguera":["spanish"],"hoja":["spanish"],"hombre":["spanish"],"hongo":["spanish"],"honor":["spanish"],"honra":["spanish"],"hora":["spanish"],"hormiga":["spanish"],"horno":["spanish"],"hostil":["spanish"],"hoyo":["spanish"],"hueco":["spanish"],"huelga":["spanish"],"huerta":["spanish"],"hueso":["spanish"],"huevo":["spanish"],"huida":["spanish"],"huir":["spanish"],"humano":["spanish"],"húmedo":["spanish"],"humilde":["spanish"],"humo":["spanish"],"hundir":["spanish"],"huracán":["spanish"],"hurto":["spanish"],"icono":["spanish"],"ideal":["spanish"],"idioma":["spanish"],"ídolo":["spanish"],"iglesia":["spanish"],"iglú":["spanish"],"igual":["spanish"],"ilegal":["spanish"],"ilusión":["spanish"],"imagen":["spanish"],"imán":["spanish"],"imitar":["spanish"],"impar":["spanish"],"imperio":["spanish"],"imponer":["spanish"],"impulso":["spanish"],"incapaz":["spanish"],"índice":["spanish"],"inerte":["spanish"],"infiel":["spanish"],"informe":["spanish"],"ingenio":["spanish"],"inicio":["spanish"],"inmenso":["spanish"],"inmune":["spanish"],"innato":["spanish"],"insecto":["spanish"],"instante":["spanish"],"interés":["spanish"],"íntimo":["spanish"],"intuir":["spanish"],"inútil":["spanish"],"invierno":["spanish"],"ira":["spanish"],"iris":["spanish"],"ironía":["spanish"],"isla":["spanish"],"islote":["spanish"],"jabalí":["spanish"],"jabón":["spanish"],"jamón":["spanish"],"jarabe":["spanish"],"jardín":["spanish"],"jarra":["spanish"],"jaula":["spanish"],"jazmín":["spanish"],"jefe":["spanish"],"jeringa":["spanish"],"jinete":["spanish"],"jornada":["spanish"],"joroba":["spanish"],"joven":["spanish"],"joya":["spanish"],"juerga":["spanish"],"jueves":["spanish"],"juez":["spanish"],"jugador":["spanish"],"jugo":["spanish"],"juguete":["spanish"],"juicio":["spanish"],"junco":["spanish"],"jungla":["spanish"],"junio":["spanish"],"juntar":["spanish"],"júpiter":["spanish"],"jurar":["spanish"],"justo":["spanish"],"juvenil":["spanish"],"juzgar":["spanish"],"kilo":["spanish"],"koala":["spanish"],"labio":["spanish"],"lacio":["spanish"],"lacra":["spanish"],"lado":["spanish"],"ladrón":["spanish"],"lagarto":["spanish"],"lágrima":["spanish"],"laguna":["spanish"],"laico":["spanish"],"lamer":["spanish"],"lámina":["spanish"],"lámpara":["spanish"],"lana":["spanish"],"lancha":["spanish"],"langosta":["spanish"],"lanza":["spanish"],"lápiz":["spanish"],"largo":["spanish"],"larva":["spanish"],"lástima":["spanish"],"lata":["spanish"],"látex":["spanish"],"latir":["spanish"],"laurel":["spanish"],"lavar":["spanish"],"lazo":["spanish"],"leal":["spanish"],"lección":["spanish"],"leche":["spanish"],"lector":["spanish"],"leer":["spanish"],"legión":["spanish"],"legumbre":["spanish"],"lejano":["spanish"],"lengua":["spanish"],"lento":["spanish"],"leña":["spanish"],"león":["spanish"],"leopardo":["spanish"],"lesión":["spanish"],"letal":["spanish"],"letra":["spanish"],"leve":["spanish"],"leyenda":["spanish"],"libertad":["spanish"],"libro":["spanish"],"licor":["spanish"],"líder":["spanish"],"lidiar":["spanish"],"lienzo":["spanish"],"liga":["spanish"],"ligero":["spanish"],"lima":["spanish"],"límite":["spanish"],"limón":["spanish"],"limpio":["spanish"],"lince":["spanish"],"lindo":["spanish"],"línea":["spanish"],"lingote":["spanish"],"lino":["spanish"],"linterna":["spanish"],"líquido":["spanish"],"liso":["spanish"],"lista":["spanish"],"litera":["spanish"],"litio":["spanish"],"litro":["spanish"],"llaga":["spanish"],"llama":["spanish"],"llanto":["spanish"],"llave":["spanish"],"llegar":["spanish"],"llenar":["spanish"],"llevar":["spanish"],"llorar":["spanish"],"llover":["spanish"],"lluvia":["spanish"],"lobo":["spanish"],"loción":["spanish"],"loco":["spanish"],"locura":["spanish"],"lógica":["spanish"],"logro":["spanish"],"lombriz":["spanish"],"lomo":["spanish"],"lonja":["spanish"],"lote":["spanish"],"lucha":["spanish"],"lucir":["spanish"],"lugar":["spanish"],"lujo":["spanish"],"luna":["spanish"],"lunes":["spanish"],"lupa":["spanish"],"lustro":["spanish"],"luto":["spanish"],"luz":["spanish"],"maceta":["spanish"],"macho":["spanish"],"madera":["spanish"],"madre":["spanish"],"maduro":["spanish"],"maestro":["spanish"],"mafia":["spanish"],"magia":["spanish"],"mago":["spanish"],"maíz":["spanish"],"maldad":["spanish"],"maleta":["spanish"],"malla":["spanish"],"malo":["spanish"],"mamá":["spanish"],"mambo":["spanish"],"mamut":["spanish"],"manco":["spanish"],"mando":["spanish"],"manejar":["spanish"],"manga":["spanish"],"maniquí":["spanish"],"manjar":["spanish"],"mano":["spanish"],"manso":["spanish"],"manta":["spanish"],"mañana":["spanish"],"mapa":["spanish"],"máquina":["spanish"],"mar":["spanish"],"marco":["spanish"],"marea":["spanish"],"marfil":["spanish"],"margen":["spanish"],"marido":["spanish"],"mármol":["spanish"],"marrón":["spanish"],"martes":["spanish"],"marzo":["spanish"],"masa":["spanish"],"máscara":["spanish"],"masivo":["spanish"],"matar":["spanish"],"materia":["spanish"],"matiz":["spanish"],"matriz":["spanish"],"máximo":["spanish"],"mayor":["spanish"],"mazorca":["spanish"],"mecha":["spanish"],"medalla":["spanish"],"medio":["spanish"],"médula":["spanish"],"mejilla":["spanish"],"mejor":["spanish"],"melena":["spanish"],"melón":["spanish"],"memoria":["spanish"],"menor":["spanish"],"mensaje":["spanish"],"mente":["spanish"],"menú":["spanish"],"mercado":["spanish"],"merengue":["spanish"],"mérito":["spanish"],"mes":["spanish"],"mesón":["spanish"],"meta":["spanish"],"meter":["spanish"],"método":["spanish"],"metro":["spanish"],"mezcla":["spanish"],"miedo":["spanish"],"miel":["spanish"],"miembro":["spanish"],"miga":["spanish"],"mil":["spanish"],"milagro":["spanish"],"militar":["spanish"],"millón":["spanish"],"mimo":["spanish"],"mina":["spanish"],"minero":["spanish"],"mínimo":["spanish"],"minuto":["spanish"],"miope":["spanish"],"mirar":["spanish"],"misa":["spanish"],"miseria":["spanish"],"misil":["spanish"],"mismo":["spanish"],"mitad":["spanish"],"mito":["spanish"],"mochila":["spanish"],"moción":["spanish"],"moda":["spanish"],"modelo":["spanish"],"moho":["spanish"],"mojar":["spanish"],"molde":["spanish"],"moler":["spanish"],"molino":["spanish"],"momento":["spanish"],"momia":["spanish"],"monarca":["spanish"],"moneda":["spanish"],"monja":["spanish"],"monto":["spanish"],"moño":["spanish"],"morada":["spanish"],"morder":["spanish"],"moreno":["spanish"],"morir":["spanish"],"morro":["spanish"],"morsa":["spanish"],"mortal":["spanish"],"mosca":["spanish"],"mostrar":["spanish"],"motivo":["spanish"],"mover":["spanish"],"móvil":["spanish"],"mozo":["spanish"],"mucho":["spanish"],"mudar":["spanish"],"mueble":["spanish"],"muela":["spanish"],"muerte":["spanish"],"muestra":["spanish"],"mugre":["spanish"],"mujer":["spanish"],"mula":["spanish"],"muleta":["spanish"],"multa":["spanish"],"mundo":["spanish"],"muñeca":["spanish"],"mural":["spanish"],"muro":["spanish"],"músculo":["spanish"],"museo":["spanish"],"musgo":["spanish"],"música":["spanish"],"muslo":["spanish"],"nácar":["spanish"],"nación":["spanish"],"nadar":["spanish"],"naipe":["spanish"],"naranja":["spanish"],"nariz":["spanish"],"narrar":["spanish"],"nasal":["spanish"],"natal":["spanish"],"nativo":["spanish"],"natural":["spanish"],"náusea":["spanish"],"naval":["spanish"],"nave":["spanish"],"navidad":["spanish"],"necio":["spanish"],"néctar":["spanish"],"negar":["spanish"],"negocio":["spanish"],"negro":["spanish"],"neón":["spanish"],"nervio":["spanish"],"neto":["spanish"],"neutro":["spanish"],"nevar":["spanish"],"nevera":["spanish"],"nicho":["spanish"],"nido":["spanish"],"niebla":["spanish"],"nieto":["spanish"],"niñez":["spanish"],"niño":["spanish"],"nítido":["spanish"],"nivel":["spanish"],"nobleza":["spanish"],"noche":["spanish"],"nómina":["spanish"],"noria":["spanish"],"norma":["spanish"],"norte":["spanish"],"nota":["spanish"],"noticia":["spanish"],"novato":["spanish"],"novela":["spanish"],"novio":["spanish"],"nube":["spanish"],"nuca":["spanish"],"núcleo":["spanish"],"nudillo":["spanish"],"nudo":["spanish"],"nuera":["spanish"],"nueve":["spanish"],"nuez":["spanish"],"nulo":["spanish"],"número":["spanish"],"nutria":["spanish"],"oasis":["spanish"],"obeso":["spanish"],"obispo":["spanish"],"objeto":["spanish"],"obra":["spanish"],"obrero":["spanish"],"observar":["spanish"],"obtener":["spanish"],"obvio":["spanish"],"oca":["spanish"],"ocaso":["spanish"],"océano":["spanish"],"ochenta":["spanish"],"ocho":["spanish"],"ocio":["spanish"],"ocre":["spanish"],"octavo":["spanish"],"octubre":["spanish"],"oculto":["spanish"],"ocupar":["spanish"],"ocurrir":["spanish"],"odiar":["spanish"],"odio":["spanish"],"odisea":["spanish"],"oeste":["spanish"],"ofensa":["spanish"],"oferta":["spanish"],"oficio":["spanish"],"ofrecer":["spanish"],"ogro":["spanish"],"oído":["spanish"],"oír":["spanish"],"ojo":["spanish"],"ola":["spanish"],"oleada":["spanish"],"olfato":["spanish"],"olivo":["spanish"],"olla":["spanish"],"olmo":["spanish"],"olor":["spanish"],"olvido":["spanish"],"ombligo":["spanish"],"onda":["spanish"],"onza":["spanish"],"opaco":["spanish"],"opción":["spanish"],"ópera":["spanish"],"opinar":["spanish"],"oponer":["spanish"],"optar":["spanish"],"óptica":["spanish"],"opuesto":["spanish"],"oración":["spanish"],"orador":["spanish"],"oral":["spanish","turkish"],"órbita":["spanish"],"orca":["spanish"],"orden":["spanish"],"oreja":["spanish"],"órgano":["spanish"],"orgía":["spanish"],"orgullo":["spanish"],"oriente":["spanish"],"origen":["spanish"],"orilla":["spanish"],"oro":["spanish"],"orquesta":["spanish"],"oruga":["spanish"],"osadía":["spanish"],"oscuro":["spanish"],"osezno":["spanish"],"oso":["spanish"],"ostra":["spanish"],"otoño":["spanish"],"otro":["spanish"],"oveja":["spanish"],"óvulo":["spanish"],"óxido":["spanish"],"oxígeno":["spanish"],"oyente":["spanish"],"ozono":["spanish"],"pacto":["spanish"],"padre":["spanish"],"paella":["spanish"],"página":["spanish"],"pago":["spanish"],"país":["spanish"],"pájaro":["spanish"],"palabra":["spanish"],"palco":["spanish"],"paleta":["spanish"],"pálido":["spanish"],"palma":["spanish"],"paloma":["spanish"],"palpar":["spanish"],"pan":["spanish"],"panal":["spanish"],"pánico":["spanish"],"pantera":["spanish"],"pañuelo":["spanish"],"papá":["spanish"],"papel":["spanish"],"papilla":["spanish"],"paquete":["spanish"],"parar":["spanish"],"parcela":["spanish"],"pared":["spanish"],"parir":["spanish"],"paro":["spanish"],"párpado":["spanish"],"parque":["spanish"],"párrafo":["spanish"],"parte":["spanish"],"pasar":["spanish"],"paseo":["spanish"],"pasión":["spanish"],"paso":["spanish"],"pasta":["spanish"],"pata":["spanish"],"patio":["spanish"],"patria":["spanish"],"pausa":["spanish"],"pauta":["spanish"],"pavo":["spanish"],"payaso":["spanish"],"peatón":["spanish"],"pecado":["spanish"],"pecera":["spanish"],"pecho":["spanish"],"pedal":["spanish","turkish"],"pedir":["spanish"],"pegar":["spanish"],"peine":["spanish"],"pelar":["spanish"],"peldaño":["spanish"],"pelea":["spanish"],"peligro":["spanish"],"pellejo":["spanish"],"pelo":["spanish"],"peluca":["spanish"],"pena":["spanish","turkish"],"pensar":["spanish"],"peñón":["spanish"],"peón":["spanish"],"peor":["spanish"],"pepino":["spanish"],"pequeño":["spanish"],"pera":["spanish"],"percha":["spanish"],"perder":["spanish"],"pereza":["spanish"],"perfil":["spanish"],"perico":["spanish"],"perla":["spanish"],"permiso":["spanish"],"perro":["spanish"],"persona":["spanish"],"pesa":["spanish"],"pesca":["spanish"],"pésimo":["spanish"],"pestaña":["spanish"],"pétalo":["spanish"],"petróleo":["spanish"],"pez":["spanish"],"pezuña":["spanish"],"picar":["spanish"],"pichón":["spanish"],"pie":["spanish"],"piedra":["spanish"],"pierna":["spanish"],"pieza":["spanish"],"pijama":["spanish"],"pilar":["spanish"],"piloto":["spanish"],"pimienta":["spanish"],"pino":["spanish"],"pintor":["spanish"],"pinza":["spanish"],"piña":["spanish"],"piojo":["spanish"],"pipa":["spanish"],"pirata":["spanish"],"pisar":["spanish"],"piscina":["spanish"],"piso":["spanish"],"pista":["spanish"],"pitón":["spanish"],"pizca":["spanish"],"placa":["spanish"],"plan":["spanish"],"plata":["spanish"],"playa":["spanish"],"plaza":["spanish"],"pleito":["spanish"],"pleno":["spanish"],"plomo":["spanish"],"pluma":["spanish"],"plural":["spanish"],"pobre":["spanish"],"poco":["spanish"],"poder":["spanish"],"podio":["spanish"],"poema":["spanish"],"poesía":["spanish"],"poeta":["spanish"],"polen":["spanish","turkish"],"policía":["spanish"],"pollo":["spanish"],"polvo":["spanish"],"pomada":["spanish"],"pomelo":["spanish"],"pomo":["spanish"],"pompa":["spanish","turkish"],"poner":["spanish"],"porción":["spanish"],"portal":["spanish"],"posada":["spanish"],"poseer":["spanish"],"posible":["spanish"],"poste":["spanish"],"potencia":["spanish"],"potro":["spanish"],"pozo":["spanish"],"prado":["spanish"],"precoz":["spanish"],"pregunta":["spanish"],"premio":["spanish"],"prensa":["spanish"],"preso":["spanish"],"previo":["spanish"],"primo":["spanish"],"príncipe":["spanish"],"prisión":["spanish"],"privar":["spanish"],"proa":["spanish"],"probar":["spanish"],"proceso":["spanish"],"producto":["spanish"],"proeza":["spanish"],"profesor":["spanish"],"programa":["spanish"],"prole":["spanish"],"promesa":["spanish"],"pronto":["spanish"],"propio":["spanish"],"próximo":["spanish"],"prueba":["spanish"],"público":["spanish"],"puchero":["spanish"],"pudor":["spanish"],"pueblo":["spanish"],"puerta":["spanish"],"puesto":["spanish"],"pulga":["spanish"],"pulir":["spanish"],"pulmón":["spanish"],"pulpo":["spanish"],"pulso":["spanish"],"puma":["spanish"],"punto":["spanish"],"puñal":["spanish"],"puño":["spanish"],"pupa":["spanish"],"pupila":["spanish"],"puré":["spanish"],"quedar":["spanish"],"queja":["spanish"],"quemar":["spanish"],"querer":["spanish"],"queso":["spanish"],"quieto":["spanish"],"química":["spanish"],"quince":["spanish"],"quitar":["spanish"],"rábano":["spanish"],"rabia":["spanish"],"rabo":["spanish"],"ración":["spanish"],"radical":["spanish"],"raíz":["spanish"],"rama":["spanish"],"rampa":["spanish","turkish"],"rancho":["spanish"],"rango":["spanish"],"rapaz":["spanish"],"rápido":["spanish"],"rapto":["spanish"],"rasgo":["spanish"],"raspa":["spanish"],"rato":["spanish"],"rayo":["spanish"],"raza":["spanish"],"razón":["spanish"],"reacción":["spanish"],"realidad":["spanish"],"rebaño":["spanish"],"rebote":["spanish"],"recaer":["spanish"],"receta":["spanish"],"rechazo":["spanish"],"recoger":["spanish"],"recreo":["spanish"],"recto":["spanish"],"recurso":["spanish"],"red":["spanish"],"redondo":["spanish"],"reducir":["spanish"],"reflejo":["spanish"],"reforma":["spanish"],"refrán":["spanish"],"refugio":["spanish"],"regalo":["spanish"],"regir":["spanish"],"regla":["spanish"],"regreso":["spanish"],"rehén":["spanish"],"reino":["spanish"],"reír":["spanish"],"reja":["spanish"],"relato":["spanish"],"relevo":["spanish"],"relieve":["spanish"],"relleno":["spanish"],"reloj":["spanish"],"remar":["spanish"],"remedio":["spanish"],"remo":["spanish"],"rencor":["spanish"],"rendir":["spanish"],"renta":["spanish"],"reparto":["spanish"],"repetir":["spanish"],"reposo":["spanish"],"reptil":["spanish"],"res":["spanish"],"rescate":["spanish"],"resina":["spanish"],"respeto":["spanish"],"resto":["spanish"],"resumen":["spanish"],"retiro":["spanish"],"retorno":["spanish"],"retrato":["spanish"],"reunir":["spanish"],"revés":["spanish"],"revista":["spanish"],"rey":["spanish"],"rezar":["spanish"],"rico":["spanish"],"riego":["spanish"],"rienda":["spanish"],"riesgo":["spanish"],"rifa":["spanish"],"rígido":["spanish"],"rigor":["spanish"],"rincón":["spanish"],"riñón":["spanish"],"río":["spanish"],"riqueza":["spanish"],"risa":["spanish"],"ritmo":["spanish"],"rito":["spanish"],"rizo":["spanish"],"roble":["spanish"],"roce":["spanish"],"rociar":["spanish"],"rodar":["spanish"],"rodeo":["spanish"],"rodilla":["spanish"],"roer":["spanish"],"rojizo":["spanish"],"rojo":["spanish"],"romero":["spanish"],"romper":["spanish"],"ron":["spanish"],"ronco":["spanish"],"ronda":["spanish"],"ropa":["spanish"],"ropero":["spanish"],"rosa":["spanish"],"rosca":["spanish"],"rostro":["spanish"],"rotar":["spanish"],"rubí":["spanish"],"rubor":["spanish"],"rudo":["spanish"],"rueda":["spanish"],"rugir":["spanish"],"ruido":["spanish"],"ruina":["spanish"],"ruleta":["spanish"],"rulo":["spanish","turkish"],"rumbo":["spanish"],"rumor":["spanish"],"ruptura":["spanish"],"ruta":["spanish"],"rutina":["spanish"],"sábado":["spanish"],"saber":["spanish"],"sabio":["spanish"],"sable":["spanish"],"sacar":["spanish"],"sagaz":["spanish"],"sagrado":["spanish"],"sala":["spanish"],"saldo":["spanish"],"salero":["spanish"],"salir":["spanish"],"salmón":["spanish"],"salón":["spanish"],"salsa":["spanish"],"salto":["spanish"],"salud":["spanish"],"salvar":["spanish"],"samba":["spanish"],"sanción":["spanish"],"sandía":["spanish"],"sanear":["spanish"],"sangre":["spanish"],"sanidad":["spanish"],"sano":["spanish"],"santo":["spanish"],"sapo":["spanish"],"saque":["spanish"],"sardina":["spanish"],"sartén":["spanish"],"sastre":["spanish"],"satán":["spanish"],"sauna":["spanish"],"saxofón":["spanish"],"sección":["spanish"],"seco":["spanish"],"secreto":["spanish"],"secta":["spanish"],"sed":["spanish"],"seguir":["spanish"],"seis":["spanish"],"sello":["spanish"],"selva":["spanish"],"semana":["spanish"],"semilla":["spanish"],"senda":["spanish"],"sensor":["spanish"],"señal":["spanish"],"señor":["spanish"],"separar":["spanish"],"sepia":["spanish"],"sequía":["spanish"],"ser":["spanish"],"serie":["spanish"],"sermón":["spanish"],"servir":["spanish"],"sesenta":["spanish"],"sesión":["spanish"],"seta":["spanish"],"setenta":["spanish"],"severo":["spanish"],"sexo":["spanish"],"sexto":["spanish"],"sidra":["spanish"],"siesta":["spanish"],"siete":["spanish"],"siglo":["spanish"],"signo":["spanish"],"sílaba":["spanish"],"silbar":["spanish"],"silencio":["spanish"],"silla":["spanish"],"símbolo":["spanish"],"simio":["spanish"],"sirena":["spanish"],"sistema":["spanish"],"sitio":["spanish"],"situar":["spanish"],"sobre":["spanish"],"socio":["spanish"],"sodio":["spanish"],"sol":["spanish"],"solapa":["spanish"],"soldado":["spanish"],"soledad":["spanish"],"sólido":["spanish"],"soltar":["spanish"],"solución":["spanish"],"sombra":["spanish"],"sondeo":["spanish"],"sonido":["spanish"],"sonoro":["spanish"],"sonrisa":["spanish"],"sopa":["spanish"],"soplar":["spanish"],"soporte":["spanish"],"sordo":["spanish"],"sorpresa":["spanish"],"sorteo":["spanish"],"sostén":["spanish"],"sótano":["spanish"],"suave":["spanish"],"subir":["spanish"],"suceso":["spanish"],"sudor":["spanish"],"suegra":["spanish"],"suelo":["spanish"],"sueño":["spanish"],"suerte":["spanish"],"sufrir":["spanish"],"sujeto":["spanish"],"sultán":["spanish"],"sumar":["spanish"],"superar":["spanish"],"suplir":["spanish"],"suponer":["spanish"],"supremo":["spanish"],"sur":["spanish"],"surco":["spanish"],"sureño":["spanish"],"surgir":["spanish"],"susto":["spanish"],"sutil":["spanish"],"tabaco":["spanish"],"tabique":["spanish"],"tabla":["spanish"],"tabú":["spanish"],"taco":["spanish"],"tacto":["spanish"],"tajo":["spanish"],"talar":["spanish"],"talco":["spanish"],"talento":["spanish"],"talla":["spanish"],"talón":["spanish"],"tamaño":["spanish"],"tambor":["spanish"],"tango":["spanish"],"tanque":["spanish"],"tapa":["spanish"],"tapete":["spanish"],"tapia":["spanish"],"tapón":["spanish"],"taquilla":["spanish"],"tarde":["spanish"],"tarea":["spanish"],"tarifa":["spanish"],"tarjeta":["spanish"],"tarot":["spanish"],"tarro":["spanish"],"tarta":["spanish"],"tatuaje":["spanish"],"tauro":["spanish"],"taza":["spanish"],"tazón":["spanish"],"teatro":["spanish"],"techo":["spanish"],"tecla":["spanish"],"técnica":["spanish"],"tejado":["spanish"],"tejer":["spanish"],"tejido":["spanish"],"tela":["spanish"],"teléfono":["spanish"],"tema":["spanish"],"temor":["spanish"],"templo":["spanish"],"tenaz":["spanish"],"tender":["spanish"],"tener":["spanish"],"tenis":["spanish"],"tenso":["spanish"],"teoría":["spanish"],"terapia":["spanish"],"terco":["spanish"],"término":["spanish"],"ternura":["spanish"],"terror":["spanish"],"tesis":["spanish"],"tesoro":["spanish"],"testigo":["spanish"],"tetera":["spanish"],"texto":["spanish"],"tez":["spanish"],"tibio":["spanish"],"tiburón":["spanish"],"tiempo":["spanish"],"tienda":["spanish"],"tierra":["spanish"],"tieso":["spanish"],"tigre":["spanish"],"tijera":["spanish"],"tilde":["spanish"],"timbre":["spanish"],"tímido":["spanish"],"timo":["spanish"],"tinta":["spanish"],"tío":["spanish"],"típico":["spanish"],"tipo":["spanish"],"tira":["spanish"],"tirón":["spanish"],"titán":["spanish"],"títere":["spanish"],"título":["spanish"],"tiza":["spanish"],"toalla":["spanish"],"tobillo":["spanish"],"tocar":["spanish"],"tocino":["spanish"],"todo":["spanish"],"toga":["spanish"],"toldo":["spanish"],"tomar":["spanish","turkish"],"tono":["spanish"],"tonto":["spanish"],"topar":["spanish"],"tope":["spanish"],"toque":["spanish"],"tórax":["spanish"],"torero":["spanish"],"tormenta":["spanish"],"torneo":["spanish"],"toro":["spanish"],"torpedo":["spanish"],"torre":["spanish"],"torso":["spanish"],"tortuga":["spanish"],"tos":["spanish"],"tosco":["spanish"],"toser":["spanish"],"tóxico":["spanish"],"trabajo":["spanish"],"tractor":["spanish"],"traer":["spanish"],"tráfico":["spanish"],"trago":["spanish"],"traje":["spanish"],"tramo":["spanish"],"trance":["spanish"],"trato":["spanish"],"trauma":["spanish"],"trazar":["spanish"],"trébol":["spanish"],"tregua":["spanish"],"treinta":["spanish"],"tren":["spanish"],"trepar":["spanish"],"tres":["spanish"],"tribu":["spanish"],"trigo":["spanish"],"tripa":["spanish"],"triste":["spanish"],"triunfo":["spanish"],"trofeo":["spanish"],"trompa":["spanish"],"tronco":["spanish"],"tropa":["spanish"],"trote":["spanish"],"trozo":["spanish"],"truco":["spanish"],"trueno":["spanish"],"trufa":["spanish"],"tubería":["spanish"],"tubo":["spanish"],"tuerto":["spanish"],"tumba":["spanish"],"tumor":["spanish"],"túnel":["spanish"],"túnica":["spanish"],"turbina":["spanish"],"turismo":["spanish"],"turno":["spanish"],"tutor":["spanish"],"ubicar":["spanish"],"úlcera":["spanish"],"umbral":["spanish"],"unidad":["spanish"],"unir":["spanish"],"universo":["spanish"],"uno":["spanish"],"untar":["spanish"],"uña":["spanish"],"urbano":["spanish"],"urbe":["spanish"],"urgente":["spanish"],"urna":["spanish"],"usar":["spanish"],"usuario":["spanish"],"útil":["spanish"],"utopía":["spanish"],"uva":["spanish"],"vaca":["spanish"],"vacío":["spanish"],"vacuna":["spanish"],"vagar":["spanish"],"vago":["spanish"],"vaina":["spanish"],"vajilla":["spanish"],"vale":["spanish"],"válido":["spanish"],"valle":["spanish"],"valor":["spanish"],"válvula":["spanish"],"vampiro":["spanish"],"vara":["spanish"],"variar":["spanish"],"varón":["spanish"],"vaso":["spanish"],"vecino":["spanish"],"vector":["spanish"],"vehículo":["spanish"],"veinte":["spanish"],"vejez":["spanish"],"vela":["spanish"],"velero":["spanish"],"veloz":["spanish"],"vena":["spanish"],"vencer":["spanish"],"venda":["spanish"],"veneno":["spanish"],"vengar":["spanish"],"venir":["spanish"],"venta":["spanish"],"venus":["spanish"],"ver":["spanish"],"verano":["spanish"],"verbo":["spanish"],"verde":["spanish"],"vereda":["spanish"],"verja":["spanish"],"verso":["spanish"],"verter":["spanish"],"vía":["spanish"],"viaje":["spanish"],"vibrar":["spanish"],"vicio":["spanish"],"víctima":["spanish"],"vida":["spanish"],"vídeo":["spanish"],"vidrio":["spanish"],"viejo":["spanish"],"viernes":["spanish"],"vigor":["spanish"],"vil":["spanish"],"villa":["spanish"],"vinagre":["spanish"],"vino":["spanish"],"viñedo":["spanish"],"violín":["spanish"],"viral":["spanish"],"virgo":["spanish"],"virtud":["spanish"],"visor":["spanish"],"víspera":["spanish"],"vista":["spanish"],"vitamina":["spanish"],"viudo":["spanish"],"vivaz":["spanish"],"vivero":["spanish"],"vivir":["spanish"],"vivo":["spanish"],"volcán":["spanish"],"volumen":["spanish"],"volver":["spanish"],"voraz":["spanish"],"votar":["spanish"],"voto":["spanish"],"voz":["spanish"],"vuelo":["spanish"],"vulgar":["spanish"],"yacer":["spanish"],"yate":["spanish"],"yegua":["spanish"],"yema":["spanish"],"yerno":["spanish"],"yeso":["spanish"],"yodo":["spanish"],"yoga":["spanish"],"yogur":["spanish"],"zafiro":["spanish"],"zanja":["spanish"],"zapato":["spanish"],"zarza":["spanish"],"zona":["spanish"],"zorro":["spanish"],"zumo":["spanish"],"zurdo":["spanish"],"abajur":["turkish"],"abaküs":["turkish"],"abartı":["turkish"],"abdal":["turkish"],"abdest":["turkish"],"abiye":["turkish"],"abluka":["turkish"],"abone":["turkish"],"absorbe":["turkish"],"absürt":["turkish"],"acayip":["turkish"],"acele":["turkish"],"acemi":["turkish"],"açıkgöz":["turkish"],"adalet":["turkish"],"adam":["turkish"],"adezyon":["turkish"],"adisyon":["turkish"],"adliye":["turkish"],"adres":["turkish"],"afacan":["turkish"],"afili":["turkish"],"afiş":["turkish"],"afiyet":["turkish"],"aforizm":["turkish"],"afra":["turkish"],"ağaç":["turkish"],"ağır":["turkish"],"ahbap":["turkish"],"ahkam":["turkish"],"ahlak":["turkish"],"ahtapot":["turkish"],"aidat":["turkish"],"aile":["turkish"],"ajan":["turkish"],"akademi":["turkish"],"akarsu":["turkish"],"akbaş":["turkish"],"akciğer":["turkish"],"akdeniz":["turkish"],"akıbet":["turkish"],"akıl":["turkish"],"akıntı":["turkish"],"akide":["turkish"],"akrep":["turkish"],"akrobasi":["turkish"],"aksiyon":["turkish"],"akşam":["turkish"],"aktif":["turkish"],"aktör":["turkish"],"aktris":["turkish"],"akustik":["turkish"],"alaca":["turkish"],"albüm":["turkish"],"alçak":["turkish"],"aldanma":["turkish"],"aleni":["turkish"],"alet":["turkish"],"alfabe":["turkish"],"algılama":["turkish"],"alıngan":["turkish"],"alkış":["turkish"],"alkol":["turkish"],"alpay":["turkish"],"alperen":["turkish"],"altın":["turkish"],"altüst":["turkish"],"altyapı":["turkish"],"alyuvar":["turkish"],"amade":["turkish"],"amatör":["turkish"],"amazon":["turkish"],"ambalaj":["turkish"],"amblem":["turkish"],"ambulans":["turkish"],"amca":["turkish"],"amel":["turkish"],"amir":["turkish"],"amiyane":["turkish"],"amorti":["turkish"],"ampul":["turkish"],"anadolu":["turkish"],"anahtar":["turkish"],"anakonda":["turkish"],"anaokul":["turkish"],"anapara":["turkish"],"anarşi":["turkish"],"anatomi":["turkish"],"anayasa":["turkish"],"anekdot":["turkish"],"anestezi":["turkish"],"angaje":["turkish"],"anka":["turkish"],"anket":["turkish"],"anlamlı":["turkish"],"anne":["turkish"],"anomali":["turkish"],"anonim":["turkish"],"anten":["turkish"],"antlaşma":["turkish"],"apse":["turkish"],"araba":["turkish"],"aracı":["turkish"],"araf":["turkish"],"arbede":["turkish"],"arda":["turkish"],"arefe":["turkish"],"argo":["turkish"],"argüman":["turkish"],"arkadaş":["turkish"],"armoni":["turkish"],"arsa":["turkish"],"arsız":["turkish"],"artı":["turkish"],"aruz":["turkish"],"asansör":["turkish"],"asayiş":["turkish"],"asgari":["turkish"],"asil":["turkish"],"asker":["turkish"],"askı":["turkish"],"aslan":["turkish"],"asosyal":["turkish"],"astsubay":["turkish"],"asya":["turkish"],"aşçı":["turkish"],"aşırı":["turkish"],"aşure":["turkish"],"atabey":["turkish"],"ataman":["turkish"],"ateş":["turkish"],"atmaca":["turkish"],"atmosfer":["turkish"],"atölye":["turkish"],"avcı":["turkish"],"avdet":["turkish"],"avize":["turkish"],"avlu":["turkish"],"avokado":["turkish"],"avrupa":["turkish"],"avukat":["turkish"],"ayaz":["turkish"],"ayçiçeği":["turkish"],"aydın":["turkish"],"aygıt":["turkish"],"ayna":["turkish"],"ayran":["turkish"],"ayrıntı":["turkish"],"azim":["turkish"],"baca":["turkish"],"bagaj":["turkish"],"bağlantı":["turkish"],"bahadır":["turkish"],"bahçe":["turkish"],"baki":["turkish"],"bakkal":["turkish"],"baklava":["turkish"],"bakteri":["turkish"],"balçık":["turkish"],"balina":["turkish"],"balo":["turkish"],"balta":["turkish"],"bant":["turkish"],"banyo":["turkish"],"bardak":["turkish"],"barış":["turkish"],"başbuğ":["turkish"],"başıboş":["turkish"],"başkan":["turkish"],"başlık":["turkish"],"bavul":["turkish"],"bayındır":["turkish"],"baykuş":["turkish"],"bazlama":["turkish"],"bedel":["turkish"],"begüm":["turkish"],"bekçi":["turkish"],"bekle":["turkish"],"belge":["turkish"],"belki":["turkish"],"bencil":["turkish"],"benek":["turkish"],"bengi":["turkish"],"berjer":["turkish"],"berk":["turkish"],"berrak":["turkish"],"beşik":["turkish"],"beyin":["turkish"],"beyoğlu":["turkish"],"bıçak":["turkish"],"biberiye":["turkish"],"bidon":["turkish"],"bihaber":["turkish"],"bikini":["turkish"],"bilezik":["turkish"],"bilinç":["turkish"],"bilye":["turkish"],"bina":["turkish"],"binbaşı":["turkish"],"binyıl":["turkish"],"bisiklet":["turkish"],"bisküvi":["turkish"],"bitki":["turkish"],"bizzat":["turkish"],"bodrum":["turkish"],"boğaz":["turkish"],"bohça":["turkish"],"boncuk":["turkish"],"bonfile":["turkish"],"borsa":["turkish"],"boru":["turkish"],"bostan":["turkish"],"boşboğaz":["turkish"],"botanik":["turkish"],"boya":["turkish"],"boykot":["turkish"],"boynuz":["turkish"],"bozgun":["turkish"],"bozkır":["turkish"],"bölüm":["turkish"],"börek":["turkish"],"buçuk":["turkish"],"bugün":["turkish"],"buğday":["turkish"],"buhar":["turkish"],"buhran":["turkish"],"bulvar":["turkish"],"buram":["turkish"],"burçak":["turkish"],"burs":["turkish"],"burun":["turkish"],"buzdağı":["turkish"],"buzkıran":["turkish"],"bücür":["turkish"],"büfe":["turkish"],"bülten":["turkish"],"bütçe":["turkish"],"bütün":["turkish"],"büyük":["turkish"],"cacık":["turkish"],"cadı":["turkish"],"cahil":["turkish"],"cambaz":["turkish"],"canhıraş":["turkish"],"casus":["turkish"],"cazibe":["turkish"],"cehalet":["turkish"],"cehennem":["turkish"],"ceket":["turkish"],"cemre":["turkish"],"cenin":["turkish"],"cennet":["turkish"],"cepken":["turkish"],"cerrah":["turkish"],"cesur":["turkish"],"cetvel":["turkish"],"cevher":["turkish"],"ceylan":["turkish"],"cılız":["turkish"],"cıva":["turkish"],"cilt":["turkish"],"cisim":["turkish"],"ciyak":["turkish"],"coğrafya":["turkish"],"cömert":["turkish"],"cumba":["turkish"],"cüzdan":["turkish"],"çabucak":["turkish"],"çadır":["turkish"],"çağdaş":["turkish"],"çağlayan":["turkish"],"çağrı":["turkish"],"çakmak":["turkish"],"çalışkan":["turkish"],"çamaşır":["turkish"],"çapa":["turkish"],"çaput":["turkish"],"çarık":["turkish"],"çarpan":["turkish"],"çarşaf":["turkish"],"çayhane":["turkish"],"çekirdek":["turkish"],"çelebi":["turkish"],"çember":["turkish"],"çenet":["turkish"],"çengel":["turkish"],"çerçeve":["turkish"],"çerez":["turkish"],"çeşit":["turkish"],"çeşme":["turkish"],"çete":["turkish"],"çevre":["turkish"],"çeyiz":["turkish"],"çeyrek":["turkish"],"çığır":["turkish"],"çılgın":["turkish"],"çıngırak":["turkish"],"çift":["turkish"],"çiğdem":["turkish"],"çikolata":["turkish"],"çilek":["turkish"],"çimen":["turkish"],"çivi":["turkish"],"çoban":["turkish"],"çocuk":["turkish"],"çokgen":["turkish"],"çomak":["turkish"],"çorba":["turkish"],"çözelti":["turkish"],"çubuk":["turkish"],"çukur":["turkish"],"çuval":["turkish"],"çürük":["turkish"],"dağbaşı":["turkish"],"dağılım":["turkish"],"daktilo":["turkish"],"daldırış":["turkish"],"dalga":["turkish"],"dalkavuk":["turkish"],"damak":["turkish"],"damıtma":["turkish"],"damla":["turkish"],"dana":["turkish"],"dandik":["turkish"],"danışman":["turkish"],"daniska":["turkish"],"dantel":["turkish"],"dargeçit":["turkish"],"darphane":["turkish"],"davet":["turkish"],"dayı":["turkish"],"defter":["turkish"],"değer":["turkish"],"değirmen":["turkish"],"dehşet":["turkish"],"delgeç":["turkish"],"demir":["turkish"],"deneyim":["turkish"],"denge":["turkish"],"depo":["turkish"],"deprem":["turkish"],"derdest":["turkish"],"dere":["turkish"],"derhal":["turkish"],"derman":["turkish"],"dernek":["turkish"],"derviş":["turkish"],"desen":["turkish"],"destan":["turkish"],"dışarı":["turkish"],"dışbükey":["turkish"],"dijital":["turkish"],"dikbaşlı":["turkish"],"dilekçe":["turkish"],"dimağ":["turkish"],"dinamik":["turkish"],"dindar":["turkish"],"dinleme":["turkish"],"dinozor":["turkish"],"dipçik":["turkish"],"dipnot":["turkish"],"direniş":["turkish"],"dirsek":["turkish"],"disiplin":["turkish"],"divriği":["turkish"],"dizüstü":["turkish"],"dobra":["turkish"],"dodurga":["turkish"],"doğalgaz":["turkish"],"doküman":["turkish"],"dolap":["turkish"],"donanım":["turkish"],"dondurma":["turkish"],"donör":["turkish"],"doruk":["turkish"],"dosdoğru":["turkish"],"dost":["turkish"],"dosya":["turkish"],"dozer":["turkish"],"döküm":["turkish"],"dönence":["turkish"],"dörtyol":["turkish"],"dövme":["turkish"],"dram":["turkish"],"dublaj":["turkish"],"durum":["turkish"],"duvak":["turkish"],"duyarga":["turkish"],"duyma":["turkish"],"duyuru":["turkish"],"düğme":["turkish"],"düğüm":["turkish"],"dükkan":["turkish"],"dünür":["turkish"],"düpedüz":["turkish"],"dürbün":["turkish"],"düşünür":["turkish"],"düzayak":["turkish"],"düzeltme":["turkish"],"ebeveyn":["turkish"],"ebru":["turkish"],"ecel":["turkish"],"ecnebi":["turkish"],"ecza":["turkish"],"edat":["turkish"],"edilgen":["turkish"],"efendi":["turkish"],"efor":["turkish"],"efsane":["turkish"],"egemen":["turkish"],"egzersiz":["turkish"],"eğrelti":["turkish"],"ekarte":["turkish"],"ekip":["turkish"],"eklem":["turkish"],"ekmek":["turkish"],"ekol":["turkish"],"ekonomi":["turkish"],"ekose":["turkish"],"ekran":["turkish"],"ekvator":["turkish"],"elaman":["turkish"],"elastik":["turkish"],"elbet":["turkish"],"elbise":["turkish"],"elçi":["turkish"],"eldiven":["turkish"],"elebaşı":["turkish"],"eleştiri":["turkish"],"elma":["turkish"],"eloğlu":["turkish"],"elveda":["turkish"],"emare":["turkish"],"emekçi":["turkish"],"emisyon":["turkish"],"emniyet":["turkish"],"empati":["turkish"],"emsal":["turkish"],"emzik":["turkish"],"endüstri":["turkish"],"enerji":["turkish"],"engebe":["turkish"],"enişte":["turkish"],"enkaz":["turkish"],"entari":["turkish"],"entegre":["turkish"],"entrika":["turkish"],"enzim":["turkish"],"erdem":["turkish"],"ergen":["turkish"],"erguvan":["turkish"],"erkek":["turkish"],"erozyon":["turkish"],"ertesi":["turkish"],"erzak":["turkish"],"esaret":["turkish"],"esenlik":["turkish"],"eser":["turkish"],"eski":["turkish"],"esnek":["turkish"],"eşarp":["turkish"],"eşofman":["turkish"],"eşraf":["turkish"],"eşya":["turkish"],"eşzaman":["turkish"],"etik":["turkish"],"etken":["turkish"],"etkinlik":["turkish"],"etüt":["turkish"],"evet":["turkish"],"evire":["turkish"],"evrak":["turkish"],"evrim":["turkish"],"eyalet":["turkish"],"eyvah":["turkish"],"ezber":["turkish"],"fabrika":["turkish"],"fanus":["turkish"],"fason":["turkish"],"fasulye":["turkish"],"fatih":["turkish"],"fatura":["turkish"],"fayans":["turkish"],"fayton":["turkish"],"fazıl":["turkish"],"fazilet":["turkish"],"felsefe":["turkish"],"fener":["turkish"],"feribot":["turkish"],"fersah":["turkish"],"fesih":["turkish"],"feveran":["turkish"],"feza":["turkish"],"fıçı":["turkish"],"fıldır":["turkish"],"fındık":["turkish"],"fırça":["turkish"],"fırsat":["turkish"],"fırtına":["turkish"],"fıtık":["turkish"],"fidan":["turkish"],"fidye":["turkish"],"figür":["turkish"],"fihrist":["turkish"],"fikir":["turkish"],"fildişi":["turkish"],"filtre":["turkish"],"fincan":["turkish"],"firuze":["turkish"],"fitil":["turkish"],"fiyaka":["turkish"],"fizik":["turkish"],"flaş":["turkish"],"flüt":["turkish"],"fosil":["turkish"],"fren":["turkish"],"fukara":["turkish"],"futbol":["turkish"],"garabet":["turkish"],"gariban":["turkish"],"garnitür":["turkish"],"gazi":["turkish"],"gece":["turkish"],"gedik":["turkish"],"gelenek":["turkish"],"gelin":["turkish"],"gemi":["turkish"],"genç":["turkish"],"geniş":["turkish"],"geometri":["turkish"],"gerçek":["turkish"],"gevrek":["turkish"],"gezegen":["turkish"],"gezgin":["turkish"],"geziyolu":["turkish"],"gıcık":["turkish"],"gıda":["turkish"],"gıybet":["turkish"],"girdap":["turkish"],"girişim":["turkish"],"gitar":["turkish"],"giyecek":["turkish"],"giysi":["turkish"],"gizem":["turkish"],"gofret":["turkish"],"goril":["turkish"],"göbek":["turkish"],"göçebe":["turkish"],"göğüs":["turkish"],"gökdelen":["turkish"],"gökmen":["turkish"],"gökyüzü":["turkish"],"gölge":["turkish"],"gömlek":["turkish"],"gönül":["turkish"],"görenek":["turkish"],"görkemli":["turkish"],"görsel":["turkish"],"gösteri":["turkish"],"gövde":["turkish"],"gözaltı":["turkish"],"gözcü":["turkish"],"gözdağı":["turkish"],"gözleme":["turkish"],"gözyaşı":["turkish"],"grup":["turkish"],"gurbet":["turkish"],"gusül":["turkish"],"gübre":["turkish"],"güfte":["turkish"],"gümüş":["turkish"],"günaydın":["turkish"],"güncel":["turkish"],"gündüz":["turkish"],"güneş":["turkish"],"günyüzü":["turkish"],"gürbüz":["turkish"],"güvercin":["turkish"],"güzel":["turkish"],"hacamat":["turkish"],"hacim":["turkish"],"hademe":["turkish"],"hafız":["turkish"],"hafriyat":["turkish"],"hafta":["turkish"],"hakan":["turkish"],"hakem":["turkish"],"hakikat":["turkish"],"haksever":["turkish"],"halı":["turkish"],"hançer":["turkish"],"hane":["turkish"],"hapis":["turkish"],"hapşırık":["turkish"],"harf":["turkish"],"haseki":["turkish"],"hasret":["turkish"],"hatun":["turkish"],"havuç":["turkish"],"haylaz":["turkish"],"haysiyet":["turkish"],"hayvan":["turkish"],"hedef":["turkish"],"hemen":["turkish"],"hemfikir":["turkish"],"hendek":["turkish"],"hepsi":["turkish"],"hergele":["turkish"],"herhangi":["turkish"],"hesap":["turkish"],"heyecan":["turkish"],"heykel":["turkish"],"hezimet":["turkish"],"hıçkırık":["turkish"],"hızölçer":["turkish"],"hicviye":["turkish"],"hikaye":["turkish"],"hikmet":["turkish"],"hile":["turkish"],"hisse":["turkish"],"hobi":["turkish"],"hoca":["turkish"],"horlama":["turkish"],"hoşbeş":["turkish"],"hoşgörü":["turkish"],"hoyrat":["turkish"],"hörgüç":["turkish"],"höyük":["turkish"],"hudut":["turkish"],"hukuk":["turkish"],"hunhar":["turkish"],"hurda":["turkish"],"huysuz":["turkish"],"huzur":["turkish"],"hücum":["turkish"],"hükümet":["turkish"],"hünkar":["turkish"],"hüviyet":["turkish"],"ırmak":["turkish"],"ısıölçer":["turkish"],"ısıtıcı":["turkish"],"ıspanak":["turkish"],"ısrar":["turkish"],"ışıldak":["turkish"],"ızdırap":["turkish"],"ızgara":["turkish"],"ibadet":["turkish"],"icat":["turkish"],"içbükey":["turkish"],"içecek":["turkish"],"içgüdü":["turkish"],"içsel":["turkish"],"idman":["turkish"],"iftihar":["turkish"],"iğne":["turkish"],"ihanet":["turkish"],"ihbar":["turkish"],"ihdas":["turkish"],"ihmal":["turkish"],"ihracat":["turkish"],"ihsan":["turkish"],"ikilem":["turkish"],"ikindi":["turkish"],"ikircik":["turkish"],"iklim":["turkish"],"iksir":["turkish"],"iktibas":["turkish"],"ilaç":["turkish"],"ilçe":["turkish"],"ileri":["turkish"],"iletişim":["turkish"],"ilgi":["turkish"],"ilhak":["turkish"],"ilkbahar":["turkish"],"ilkokul":["turkish"],"ilmek":["turkish"],"imkan":["turkish"],"imleç":["turkish"],"imsak":["turkish"],"imtihan":["turkish"],"imza":["turkish"],"ince":["turkish"],"inkar":["turkish"],"inşa":["turkish"],"ipek":["turkish"],"ipucu":["turkish"],"irade":["turkish"],"irfan":["turkish"],"irmik":["turkish"],"isabet":["turkish"],"iskele":["turkish"],"israf":["turkish"],"isyan":["turkish"],"işçi":["turkish"],"işgal":["turkish"],"işgüzar":["turkish"],"işlem":["turkish"],"itibar":["turkish"],"itiraf":["turkish"],"ivedi":["turkish"],"ivme":["turkish"],"iyileşme":["turkish"],"iyimser":["turkish"],"izbandut":["turkish"],"izci":["turkish"],"izdiham":["turkish"],"izin":["turkish"],"jakoben":["turkish"],"jandarma":["turkish"],"jargon":["turkish"],"kabadayı":["turkish"],"kablo":["turkish"],"kabus":["turkish"],"kaçamak":["turkish"],"kadeh":["turkish"],"kadın":["turkish"],"kadraj":["turkish"],"kafa":["turkish"],"kafkas":["turkish"],"kağıt":["turkish"],"kağnı":["turkish"],"kahkaha":["turkish"],"kahraman":["turkish"],"kahvaltı":["turkish"],"kakül":["turkish"],"kaldırım":["turkish"],"kale":["turkish"],"kalibre":["turkish"],"kalkan":["turkish"],"kalpak":["turkish"],"kamış":["turkish"],"kamyon":["turkish"],"kanat":["turkish"],"kandaş":["turkish"],"kanepe":["turkish"],"kanser":["turkish"],"kanun":["turkish"],"kaos":["turkish"],"kapı":["turkish"],"kaplıca":["turkish"],"kaptan":["turkish"],"karanlık":["turkish"],"kardeş":["turkish"],"karga":["turkish"],"karınca":["turkish"],"karmaşa":["turkish"],"karşıt":["turkish"],"kasırga":["turkish"],"kask":["turkish"],"kasvet":["turkish"],"katkı":["turkish"],"katman":["turkish"],"kavram":["turkish"],"kaygan":["turkish"],"kaynakça":["turkish"],"kayyum":["turkish"],"kedi":["turkish"],"kehanet":["turkish"],"kekik":["turkish"],"kelebek":["turkish"],"kenar":["turkish"],"kerkenez":["turkish"],"kerpiç":["turkish"],"kesirli":["turkish"],"kesmece":["turkish"],"kestane":["turkish"],"keşkek":["turkish"],"ketçap":["turkish"],"keyfiyet":["turkish"],"kıble":["turkish"],"kıdemli":["turkish"],"kılavuz":["turkish"],"kılçık":["turkish"],"kılıf":["turkish"],"kıraç":["turkish"],"kırmızı":["turkish"],"kırsal":["turkish"],"kısayol":["turkish"],"kısım":["turkish"],"kıskanç":["turkish"],"kısmet":["turkish"],"kışla":["turkish"],"kıvanç":["turkish"],"kıvılcım":["turkish"],"kıvrık":["turkish"],"kıyafet":["turkish"],"kıymetli":["turkish"],"kızak":["turkish"],"kızılcık":["turkish"],"kibar":["turkish"],"kinaye":["turkish"],"kira":["turkish"],"kiremit":["turkish"],"kirli":["turkish"],"kirpik":["turkish"],"kişisel":["turkish"],"kitap":["turkish"],"koçbaşı":["turkish"],"kodaman":["turkish"],"koğuş":["turkish"],"kokteyl":["turkish"],"kolaycı":["turkish"],"kolbastı":["turkish"],"kolonya":["turkish"],"koltuk":["turkish"],"kolye":["turkish"],"kombine":["turkish"],"komedyen":["turkish"],"komiser":["turkish"],"komposto":["turkish"],"komşu":["turkish"],"komuta":["turkish"],"konak":["turkish"],"konfor":["turkish"],"koni":["turkish"],"konsül":["turkish"],"kopya":["turkish"],"korkusuz":["turkish"],"korna":["turkish"],"korse":["turkish"],"korunak":["turkish"],"korvet":["turkish"],"kostüm":["turkish"],"koşul":["turkish"],"koyu":["turkish"],"kozmik":["turkish"],"köfte":["turkish"],"kökensel":["turkish"],"köprücük":["turkish"],"köpük":["turkish"],"kördüğüm":["turkish"],"körfez":["turkish"],"köstebek":["turkish"],"köşegen":["turkish"],"kötü":["turkish"],"kravat":["turkish"],"kriter":["turkish"],"kuantum":["turkish"],"kudurma":["turkish"],"kuluçka":["turkish"],"kulübe":["turkish"],"kumanya":["turkish"],"kumbara":["turkish"],"kumlu":["turkish"],"kumpir":["turkish"],"kumral":["turkish"],"kundura":["turkish"],"kupa":["turkish"],"kupkuru":["turkish"],"kuramsal":["turkish"],"kurbağa":["turkish"],"kurdele":["turkish"],"kurgu":["turkish"],"kurmay":["turkish"],"kurşun":["turkish"],"kurtuluş":["turkish"],"kurultay":["turkish"],"kurye":["turkish"],"kusursuz":["turkish"],"kuşak":["turkish"],"kuşbaşı":["turkish"],"kuşkulu":["turkish"],"kutlama":["turkish"],"kutsal":["turkish"],"kutup":["turkish"],"kuver":["turkish"],"kuyruk":["turkish"],"kuzey":["turkish"],"kuzgun":["turkish"],"küçük":["turkish"],"külçe":["turkish"],"külfet":["turkish"],"külliye":["turkish"],"kültürel":["turkish"],"kümes":["turkish"],"künefe":["turkish"],"küresel":["turkish"],"kütle":["turkish"],"lahana":["turkish"],"lahmacun":["turkish"],"lamba":["turkish"],"lansman":["turkish"],"lavaş":["turkish"],"layık":["turkish"],"leğen":["turkish"],"levent":["turkish"],"leziz":["turkish"],"lezzet":["turkish"],"lider":["turkish"],"likide":["turkish"],"liman":["turkish"],"liste":["turkish"],"litre":["turkish"],"liyakat":["turkish"],"lodos":["turkish"],"lokanta":["turkish"],"lokman":["turkish"],"lokum":["turkish"],"lunapark":["turkish"],"lütfen":["turkish"],"lüzum":["turkish"],"nokta":["turkish"],"mabet":["turkish"],"macera":["turkish"],"macun":["turkish"],"madalya":["turkish"],"madde":["turkish"],"madem":["turkish"],"mağara":["turkish"],"mağdur":["turkish"],"mağfiret":["turkish"],"mağlup":["turkish"],"mahalle":["turkish"],"mahcup":["turkish"],"mahir":["turkish"],"mahkeme":["turkish"],"mahlas":["turkish"],"mahrum":["turkish"],"mahsul":["turkish"],"makas":["turkish"],"makbuz":["turkish"],"makine":["turkish"],"makro":["turkish"],"maksat":["turkish"],"makul":["turkish"],"maliye":["turkish"],"manav":["turkish"],"mangal":["turkish"],"manidar":["turkish"],"manken":["turkish"],"mantık":["turkish"],"manzara":["turkish"],"mareşal":["turkish"],"margarin":["turkish"],"marifet":["turkish"],"marmelat":["turkish"],"masaüstü":["turkish"],"masmavi":["turkish"],"masraf":["turkish"],"masum":["turkish"],"matah":["turkish"],"materyal":["turkish"],"matrak":["turkish"],"maval":["turkish"],"mavra":["turkish"],"maydanoz":["turkish"],"mayhoş":["turkish"],"maytap":["turkish"],"mazbata":["turkish"],"mazeret":["turkish"],"mazlum":["turkish"],"mazot":["turkish"],"mazur":["turkish"],"meblağ":["turkish"],"mebus":["turkish"],"mecaz":["turkish"],"mecbur":["turkish"],"meclis":["turkish"],"mecmua":["turkish"],"mecnun":["turkish"],"meçhul":["turkish"],"medeni":["turkish"],"mehtap":["turkish"],"mekanik":["turkish"],"melodi":["turkish"],"meltem":["turkish"],"memur":["turkish"],"mendil":["turkish"],"menekşe":["turkish"],"menteşe":["turkish"],"meraklı":["turkish"],"mercek":["turkish"],"merdiven":["turkish"],"merhaba":["turkish"],"merinos":["turkish"],"merkez":["turkish"],"mermi":["turkish"],"mert":["turkish"],"mesafe":["turkish"],"mesele":["turkish"],"mesken":["turkish"],"meslek":["turkish"],"meşale":["turkish"],"meşgul":["turkish"],"meşhur":["turkish"],"metafor":["turkish"],"metin":["turkish"],"metre":["turkish"],"mevcut":["turkish"],"mevkidaş":["turkish"],"meydan":["turkish"],"meyil":["turkish"],"meyve":["turkish"],"meziyet":["turkish"],"mezun":["turkish"],"mıknatıs":["turkish"],"mısra":["turkish"],"mızıka":["turkish"],"miğfer":["turkish"],"mihrak":["turkish"],"miktar":["turkish"],"milat":["turkish"],"milli":["turkish"],"mimar":["turkish"],"minare":["turkish"],"mineral":["turkish"],"minik":["turkish"],"minyon":["turkish"],"mirliva":["turkish"],"misafir":["turkish"],"miskin":["turkish"],"miting":["turkish"],"miyop":["turkish"],"mizah":["turkish"],"mobilya":["turkish"],"monitör":["turkish"],"morötesi":["turkish"],"motive":["turkish"],"mozaik":["turkish"],"muavin":["turkish"],"mucize":["turkish"],"muhafız":["turkish"],"muhteşem":["turkish"],"mukayese":["turkish"],"mumya":["turkish"],"musluk":["turkish"],"muşamba":["turkish"],"mutabık":["turkish"],"mutfak":["turkish"],"mutlu":["turkish"],"muzaffer":["turkish"],"muzdarip":["turkish"],"mübarek":["turkish"],"mücadele":["turkish"],"müdür":["turkish"],"müfredat":["turkish"],"müftü":["turkish"],"mühendis":["turkish"],"mühim":["turkish"],"mühlet":["turkish"],"mükemmel":["turkish"],"mülk":["turkish"],"mümkün":["turkish"],"mümtaz":["turkish"],"müsrif":["turkish"],"müstesna":["turkish"],"müşahit":["turkish"],"müşteri":["turkish"],"mütercim":["turkish"],"müthiş":["turkish"],"müze":["turkish"],"müzik":["turkish"],"nabız":["turkish"],"nadas":["turkish"],"nadir":["turkish"],"nahoş":["turkish"],"nakarat":["turkish"],"nakış":["turkish"],"nalbur":["turkish"],"namlu":["turkish"],"namus":["turkish"],"nankör":["turkish"],"nargile":["turkish"],"narkoz":["turkish"],"nasıl":["turkish"],"nasip":["turkish"],"naylon":["turkish"],"nazar":["turkish"],"nazım":["turkish"],"nazik":["turkish"],"neden":["turkish"],"nefes":["turkish"],"negatif":["turkish"],"neon":["turkish"],"neptün":["turkish"],"nerede":["turkish"],"nesil":["turkish"],"nesnel":["turkish"],"neşeli":["turkish"],"netice":["turkish"],"nevresim":["turkish"],"neyse":["turkish"],"neyzen":["turkish"],"nezaket":["turkish"],"nezih":["turkish"],"nezle":["turkish"],"nicel":["turkish"],"nilüfer":["turkish"],"nimet":["turkish"],"nisan":["turkish"],"nispet":["turkish"],"nitekim":["turkish"],"nizam":["turkish"],"nohut":["turkish"],"noksan":["turkish"],"nostalji":["turkish"],"noter":["turkish"],"nöbet":["turkish"],"numara":["turkish"],"numune":["turkish"],"nutuk":["turkish"],"nüfus":["turkish"],"obabaşı":["turkish"],"obez":["turkish"],"obje":["turkish"],"ocak":["turkish"],"odun":["turkish"],"ofansif":["turkish"],"ofis":["turkish"],"oğlak":["turkish"],"oğuz":["turkish"],"okçu":["turkish"],"oklava":["turkish"],"oksijen":["turkish"],"okul":["turkish"],"okumuş":["turkish"],"okutman":["turkish"],"okuyucu":["turkish"],"okyanus":["turkish"],"olağan":["turkish"],"olanak":["turkish"],"olası":["turkish"],"olay":["turkish"],"olgun":["turkish"],"olimpik":["turkish"],"olumlu":["turkish"],"omlet":["turkish"],"omurga":["turkish"],"onarım":["turkish"],"onursal":["turkish"],"optik":["turkish"],"orantı":["turkish"],"ordu":["turkish"],"organik":["turkish"],"orijin":["turkish"],"orkide":["turkish"],"orman":["turkish"],"orta":["turkish"],"oruç":["turkish"],"otağ":["turkish"],"otantik":["turkish"],"otel":["turkish"],"otoban":["turkish"],"otogar":["turkish"],"otomobil":["turkish"],"otonom":["turkish"],"otopark":["turkish"],"otorite":["turkish"],"otoyol":["turkish"],"oturum":["turkish"],"oyuk":["turkish"],"oyuncak":["turkish"],"ozan":["turkish"],"ödeme":["turkish"],"ödenek":["turkish"],"ödev":["turkish"],"ödül":["turkish"],"ödünç":["turkish"],"öfke":["turkish"],"öğlen":["turkish"],"öğrenci":["turkish"],"öğün":["turkish"],"öğütücü":["turkish"],"öksürük":["turkish"],"ölçme":["turkish"],"ölçü":["turkish"],"ölümsüz":["turkish"],"ömür":["turkish"],"önayak":["turkish"],"öncü":["turkish"],"önder":["turkish"],"önem":["turkish"],"önerge":["turkish"],"öngörü":["turkish"],"önlük":["turkish"],"önsezi":["turkish"],"öpücük":["turkish"],"ördek":["turkish"],"örgü":["turkish"],"örtbas":["turkish"],"örtme":["turkish"],"örtü":["turkish"],"örümcek":["turkish"],"örüntü":["turkish"],"öteberi":["turkish"],"öteki":["turkish"],"övünç":["turkish"],"öykü":["turkish"],"öyleyse":["turkish"],"özçekim":["turkish"],"özdeyiş":["turkish"],"özel":["turkish"],"özenti":["turkish"],"özerk":["turkish"],"özgürlük":["turkish"],"özlem":["turkish"],"özlü":["turkish"],"özne":["turkish"],"özsever":["turkish"],"özümseme":["turkish"],"özür":["turkish"],"özveri":["turkish"],"pabuç":["turkish"],"padişah":["turkish"],"palamut":["turkish"],"palmiye":["turkish"],"palto":["turkish"],"palyaço":["turkish"],"pamuk":["turkish"],"panayır":["turkish"],"pancar":["turkish"],"panik":["turkish"],"panjur":["turkish"],"pankart":["turkish"],"pano":["turkish"],"pansuman":["turkish"],"pantolon":["turkish"],"panzehir":["turkish"],"papatya":["turkish"],"papyon":["turkish"],"paraşüt":["turkish"],"parça":["turkish"],"pardösü":["turkish"],"parfüm":["turkish"],"parıltı":["turkish"],"parkur":["turkish"],"parmak":["turkish"],"parodi":["turkish"],"parsel":["turkish"],"partner":["turkish"],"pasaport":["turkish"],"pasif":["turkish"],"paskalya":["turkish"],"pastırma":["turkish"],"paşa":["turkish"],"patates":["turkish"],"paten":["turkish"],"patika":["turkish"],"patlıcan":["turkish"],"patolog":["turkish"],"payanda":["turkish"],"paydaş":["turkish"],"payidar":["turkish"],"paylaşma":["turkish"],"paytak":["turkish"],"peçete":["turkish"],"peder":["turkish"],"pehlivan":["turkish"],"pekala":["turkish"],"pekmez":["turkish"],"pelerin":["turkish"],"pelikan":["turkish"],"pelüş":["turkish"],"pembe":["turkish"],"pencere":["turkish"],"pense":["turkish"],"perçin":["turkish"],"perde":["turkish"],"pergel":["turkish"],"perişan":["turkish"],"peron":["turkish"],"personel":["turkish"],"perşembe":["turkish"],"peruk":["turkish"],"pervane":["turkish"],"pespaye":["turkish"],"pestil":["turkish"],"peşin":["turkish"],"petek":["turkish"],"petrol":["turkish"],"petunya":["turkish"],"peynir":["turkish"],"peyzaj":["turkish"],"pınar":["turkish"],"pırasa":["turkish"],"pırlanta":["turkish"],"pide":["turkish"],"pikap":["turkish"],"pilav":["turkish"],"piliç":["turkish"],"pipet":["turkish"],"pipo":["turkish"],"piramit":["turkish"],"pirinç":["turkish"],"pirzola":["turkish"],"pist":["turkish"],"pişik":["turkish"],"pişman":["turkish"],"piyasa":["turkish"],"piyes":["turkish"],"plaj":["turkish"],"plaket":["turkish"],"planlama":["turkish"],"platform":["turkish"],"plazma":["turkish"],"podyum":["turkish"],"poğaça":["turkish"],"polat":["turkish"],"politika":["turkish"],"popüler":["turkish"],"porselen":["turkish"],"portakal":["turkish"],"poster":["turkish"],"poşet":["turkish"],"poyraz":["turkish"],"pozitif":["turkish"],"pranga":["turkish"],"pratik":["turkish"],"prenses":["turkish"],"prim":["turkish"],"profil":["turkish"],"proje":["turkish"],"protokol":["turkish"],"puan":["turkish"],"pudra":["turkish"],"pusula":["turkish"],"püre":["turkish"],"pürüz":["turkish"],"püstül":["turkish"],"püsür":["turkish"],"racon":["turkish"],"radikal":["turkish"],"radyo":["turkish"],"rafadan":["turkish"],"rafine":["turkish"],"rağbet":["turkish"],"rahat":["turkish"],"rahle":["turkish"],"rakam":["turkish"],"raket":["turkish"],"rakip":["turkish"],"rakun":["turkish"],"ralli":["turkish"],"randevu":["turkish"],"ranza":["turkish"],"rapor":["turkish"],"rastgele":["turkish"],"rasyonel":["turkish"],"razı":["turkish"],"realite":["turkish"],"reçine":["turkish"],"refah":["turkish"],"referans":["turkish"],"refik":["turkish"],"rehber":["turkish"],"rehin":["turkish"],"reis":["turkish"],"rekabet":["turkish"],"reklam":["turkish"],"rekor":["turkish"],"rektör":["turkish"],"renk":["turkish"],"resim":["turkish"],"resmen":["turkish"],"restoran":["turkish"],"retorik":["turkish"],"revaç":["turkish"],"reyon":["turkish"],"rezalet":["turkish"],"rezerv":["turkish"],"rezil":["turkish"],"rıhtım":["turkish"],"rıza":["turkish"],"ritim":["turkish"],"ritüel":["turkish"],"rivayet":["turkish"],"roman":["turkish"],"rozet":["turkish"],"röportaj":["turkish"],"rötar":["turkish"],"ruble":["turkish"],"ruhban":["turkish"],"ruhsat":["turkish"],"rulet":["turkish"],"runik":["turkish"],"rutin":["turkish"],"rutubet":["turkish"],"rüşvet":["turkish"],"rütbe":["turkish"],"rüya":["turkish"],"rüzgar":["turkish"],"sabah":["turkish"],"sabıka":["turkish"],"sabit":["turkish"],"sabun":["turkish"],"saçma":["turkish"],"sade":["turkish"],"sadık":["turkish"],"safahat":["turkish"],"safdil":["turkish"],"safkan":["turkish"],"sağanak":["turkish"],"sağduyu":["turkish"],"sağlam":["turkish"],"saha":["turkish"],"sahiden":["turkish"],"sahne":["turkish"],"sakal":["turkish"],"sakız":["turkish"],"sakin":["turkish"],"saklama":["turkish"],"saksağan":["turkish"],"salamura":["turkish"],"salça":["turkish"],"salgı":["turkish"],"salınım":["turkish"],"salkım":["turkish"],"saltanat":["turkish"],"sanatçı":["turkish"],"sancak":["turkish"],"sandalye":["turkish"],"saniye":["turkish"],"saplantı":["turkish"],"sapsız":["turkish"],"saray":["turkish"],"sarışın":["turkish"],"sarkık":["turkish"],"sarmaşık":["turkish"],"satır":["turkish"],"savaşım":["turkish"],"savunma":["turkish"],"saydam":["turkish"],"sayfa":["turkish"],"saygın":["turkish"],"sayısal":["turkish"],"sebep":["turkish"],"seçenek":["turkish"],"seçim":["turkish"],"seçkin":["turkish"],"seçmen":["turkish"],"sedir":["turkish"],"sedye":["turkish"],"sefer":["turkish"],"sehpa":["turkish"],"sekizgen":["turkish"],"selektör":["turkish"],"selvi":["turkish"],"semavi":["turkish"],"sembol":["turkish"],"seminer":["turkish"],"senaryo":["turkish"],"sendika":["turkish"],"senkron":["turkish"],"sensör":["turkish"],"sentez":["turkish"],"sepet":["turkish"],"seramik":["turkish"],"serbest":["turkish"],"serdar":["turkish"],"seremoni":["turkish"],"sergi":["turkish"],"serhat":["turkish"],"serin":["turkish"],"sermaye":["turkish"],"serpuş":["turkish"],"sersem":["turkish"],"serüven":["turkish"],"sesli":["turkish"],"sesteş":["turkish"],"sevap":["turkish"],"seviye":["turkish"],"seyahat":["turkish"],"seyirci":["turkish"],"sezon":["turkish"],"sıcak":["turkish"],"sıfat":["turkish"],"sıhhi":["turkish"],"sınanma":["turkish"],"sınır":["turkish"],"sıradan":["turkish"],"sırdaş":["turkish"],"sırma":["turkish"],"sırtüstü":["turkish"],"sızgıt":["turkish"],"siftah":["turkish"],"sigorta":["turkish"],"sihirbaz":["turkish"],"silah":["turkish"],"silecek":["turkish"],"silindir":["turkish"],"simetri":["turkish"],"simge":["turkish"],"simit":["turkish"],"sincap":["turkish"],"sindirim":["turkish"],"sinema":["turkish"],"sinirli":["turkish"],"sipariş":["turkish"],"sirke":["turkish"],"siroz":["turkish"],"sistem":["turkish"],"sivilce":["turkish"],"siyasi":["turkish"],"soba":["turkish"],"sofra":["turkish"],"soğuk":["turkish"],"sohbet":["turkish"],"sokak":["turkish"],"solfej":["turkish"],"solunum":["turkish"],"somut":["turkish"],"sonbahar":["turkish"],"sonraki":["turkish"],"sonsuz":["turkish"],"sorunsuz":["turkish"],"sosyete":["turkish"],"soyağacı":["turkish"],"soydaş":["turkish"],"soygun":["turkish"],"soytarı":["turkish"],"söğüş":["turkish"],"sömürge":["turkish"],"sönük":["turkish"],"söylem":["turkish"],"sözcük":["turkish"],"sözde":["turkish"],"spatula":["turkish"],"spektrum":["turkish"],"spiker":["turkish"],"sporcu":["turkish"],"sprey":["turkish"],"stabil":["turkish"],"statü":["turkish"],"stok":["turkish"],"stopaj":["turkish"],"strateji":["turkish"],"subay":["turkish"],"sucuk":["turkish"],"suçüstü":["turkish"],"suhulet":["turkish"],"sulama":["turkish"],"sungur":["turkish"],"sunucu":["turkish"],"surat":["turkish"],"susam":["turkish"],"suskun":["turkish"],"sükse":["turkish"],"sükut":["turkish"],"sülale":["turkish"],"sünger":["turkish"],"süpürge":["turkish"],"sürahi":["turkish"],"süreç":["turkish"],"sürgün":["turkish"],"sürüm":["turkish"],"süsleme":["turkish"],"sütanne":["turkish"],"sütlaç":["turkish"],"sütun":["turkish"],"süvari":["turkish"],"şahane":["turkish"],"şahbaz":["turkish"],"şahit":["turkish"],"şahsiyet":["turkish"],"şakıma":["turkish"],"şaklaban":["turkish"],"şakrak":["turkish"],"şamar":["turkish"],"şampiyon":["turkish"],"şanslı":["turkish"],"şantiye":["turkish"],"şapka":["turkish"],"şarkıcı":["turkish"],"şartname":["turkish"],"şaşırma":["turkish"],"şaşkın":["turkish"],"şatafat":["turkish"],"şayet":["turkish"],"şebeke":["turkish"],"şefkat":["turkish"],"şeftali":["turkish"],"şehir":["turkish"],"şehvet":["turkish"],"şeker":["turkish"],"şekil":["turkish"],"şelale":["turkish"],"şema":["turkish"],"şemsiye":["turkish"],"şerbet":["turkish"],"şeref":["turkish"],"şerit":["turkish"],"şımarık":["turkish"],"şıpıdık":["turkish"],"şifre":["turkish"],"şimdi":["turkish"],"şimşek":["turkish"],"şipşak":["turkish"],"şirin":["turkish"],"şişe":["turkish"],"şişirme":["turkish"],"şofben":["turkish"],"şöhret":["turkish"],"şölen":["turkish"],"şüphe":["turkish"],"tabaka":["turkish"],"tabure":["turkish"],"tadilat":["turkish"],"taharet":["turkish"],"tahıl":["turkish"],"tahkim":["turkish"],"tahlil":["turkish"],"tahmin":["turkish"],"tahrifat":["turkish"],"tahsilat":["turkish"],"tahta":["turkish"],"taklit":["turkish"],"takoz":["turkish"],"taksici":["turkish"],"taktik":["turkish"],"takvim":["turkish"],"talebe":["turkish"],"talip":["turkish"],"tamamen":["turkish"],"tamirci":["turkish"],"tamtakır":["turkish"],"tandır":["turkish"],"tanecik":["turkish"],"tanıtım":["turkish"],"tanrı":["turkish"],"tansiyon":["turkish"],"tapan":["turkish"],"tapınak":["turkish"],"taptaze":["turkish"],"tapu":["turkish"],"tarafgir":["turkish"],"tarhana":["turkish"],"tarım":["turkish"],"tarih":["turkish"],"tarla":["turkish"],"tartak":["turkish"],"tarumar":["turkish"],"tasarım":["turkish"],"tasdik":["turkish"],"taslak":["turkish"],"tastamam":["turkish"],"taşeron":["turkish"],"taşınmaz":["turkish"],"taşra":["turkish"],"tatava":["turkish"],"tatbikat":["turkish"],"tatil":["turkish"],"tatlı":["turkish"],"tavsiye":["turkish"],"tavşan":["turkish"],"tavuk":["turkish"],"taze":["turkish"],"taziye":["turkish"],"tazminat":["turkish"],"tebeşir":["turkish"],"tebrik":["turkish"],"tecrübe":["turkish"],"teçhizat":["turkish"],"tedarik":["turkish"],"tedbir":["turkish"],"teftiş":["turkish"],"teğet":["turkish"],"teğmen":["turkish"],"tehdit":["turkish"],"tehlike":["turkish"],"tekdüze":["turkish"],"tekerlek":["turkish"],"tekme":["turkish"],"teknik":["turkish"],"tekrar":["turkish"],"telef":["turkish"],"telsiz":["turkish"],"telve":["turkish"],"temas":["turkish"],"tembel":["turkish"],"temiz":["turkish"],"temkin":["turkish"],"temsilci":["turkish"],"tendon":["turkish"],"teneke":["turkish"],"tenha":["turkish"],"tenkit":["turkish"],"tepegöz":["turkish"],"tepki":["turkish"],"terazi":["turkish"],"terbiye":["turkish"],"tercih":["turkish"],"tereyağı":["turkish"],"terfi":["turkish"],"terim":["turkish"],"terminal":["turkish"],"tersane":["turkish"],"tertip":["turkish"],"tesadüf":["turkish"],"tescil":["turkish"],"tesir":["turkish"],"teslimat":["turkish"],"tespit":["turkish"],"testere":["turkish"],"teşekkür":["turkish"],"teşhir":["turkish"],"teşrif":["turkish"],"teşvik":["turkish"],"teyze":["turkish"],"tezahür":["turkish"],"tezgah":["turkish"],"tıbbi":["turkish"],"tıkaç":["turkish"],"tıkışık":["turkish"],"tıknaz":["turkish"],"tılsım":["turkish"],"tıpkı":["turkish"],"tıraş":["turkish"],"tırışka":["turkish"],"tırmanış":["turkish"],"tırnak":["turkish"],"tırpan":["turkish"],"tıslama":["turkish"],"ticaret":["turkish"],"tilki":["turkish"],"tiryaki":["turkish"],"titreşim":["turkish"],"tohum":["turkish"],"tokat":["turkish"],"tolere":["turkish"],"tombak":["turkish"],"tomurcuk":["turkish"],"topaç":["turkish"],"toplum":["turkish"],"toprak":["turkish"],"toptan":["turkish"],"toraman":["turkish"],"torpido":["turkish"],"tortu":["turkish"],"tosbağa":["turkish"],"toynak":["turkish"],"tören":["turkish"],"trafik":["turkish"],"trajedi":["turkish"],"tramvay":["turkish"],"tribün":["turkish"],"triko":["turkish"],"tugay":["turkish"],"tuğla":["turkish"],"tuğrul":["turkish"],"tuhaf":["turkish"],"tulumba":["turkish"],"tunç":["turkish"],"turan":["turkish"],"turkuaz":["turkish"],"turnusol":["turkish"],"turşu":["turkish"],"turuncu":["turkish"],"tutanak":["turkish"],"tutkal":["turkish"],"tutsak":["turkish"],"tutum":["turkish"],"tuyuğ":["turkish"],"tuzlu":["turkish"],"tüccar":["turkish"],"tüfek":["turkish"],"tükenmez":["turkish"],"tülbent":["turkish"],"tümleç":["turkish"],"tünel":["turkish"],"türbin":["turkish"],"türev":["turkish"],"türk":["turkish"],"tüzük":["turkish"],"ucube":["turkish"],"ucuz":["turkish"],"uçak":["turkish"],"uçurtma":["turkish"],"ufuk":["turkish"],"uğrak":["turkish"],"uğur":["turkish"],"ukala":["turkish"],"ulaşım":["turkish"],"ulema":["turkish"],"ulus":["turkish"],"ulvi":["turkish"],"umursama":["turkish"],"umut":["turkish"],"unutkan":["turkish"],"uslu":["turkish"],"ustabaşı":["turkish"],"ustura":["turkish"],"usul":["turkish"],"utangaç":["turkish"],"uyanık":["turkish"],"uyarı":["turkish"],"uydu":["turkish"],"uygar":["turkish"],"uygulama":["turkish"],"uykusuz":["turkish"],"uysal":["turkish"],"uyuşma":["turkish"],"uzantı":["turkish"],"uzay":["turkish"],"uzgören":["turkish"],"uzlaşma":["turkish"],"uzman":["turkish"],"uzun":["turkish"],"ücra":["turkish"],"ücret":["turkish"],"üçbudak":["turkish"],"üçgen":["turkish"],"üçkağıt":["turkish"],"üçleme":["turkish"],"üfürük":["turkish"],"ülke":["turkish"],"ümit":["turkish"],"üniforma":["turkish"],"ünite":["turkish"],"ünlem":["turkish"],"üretken":["turkish"],"ürün":["turkish"],"üslup":["turkish"],"üstel":["turkish"],"üstün":["turkish"],"üşengeç":["turkish"],"üşüme":["turkish"],"ütopya":["turkish"],"üvey":["turkish"],"üzengi":["turkish"],"üzgün":["turkish"],"üzüm":["turkish"],"vaka":["turkish"],"vakfiye":["turkish"],"vakıf":["turkish"],"vakit":["turkish"],"vakum":["turkish"],"vapur":["turkish"],"varil":["turkish"],"varlık":["turkish"],"varsayım":["turkish"],"varyemez":["turkish"],"vasıta":["turkish"],"vasiyet":["turkish"],"vatandaş":["turkish"],"vazife":["turkish"],"vazo":["turkish"],"veciz":["turkish"],"vefa":["turkish"],"vehim":["turkish"],"veliaht":["turkish"],"veresiye":["turkish"],"verimli":["turkish"],"verkaç":["turkish"],"vernik":["turkish"],"vertigo":["turkish"],"vesait":["turkish"],"vesika":["turkish"],"vestiyer":["turkish"],"veznedar":["turkish"],"vicdan":["turkish"],"vilayet":["turkish"],"virane":["turkish"],"virgül":["turkish"],"vişne":["turkish"],"vites":["turkish"],"vokal":["turkish"],"volkan":["turkish"],"vurma":["turkish"],"vurucu":["turkish"],"vücut":["turkish"],"yabancı":["turkish"],"yabgu":["turkish"],"yağış":["turkish"],"yağlı":["turkish"],"yağmur":["turkish"],"yakamoz":["turkish"],"yakın":["turkish"],"yaklaşık":["turkish"],"yalçın":["turkish"],"yalıtım":["turkish"],"yaman":["turkish"],"yanardağ":["turkish"],"yangın":["turkish"],"yanıt":["turkish"],"yankı":["turkish"],"yanlış":["turkish"],"yansıma":["turkish"],"yapay":["turkish"],"yapboz":["turkish"],"yapımcı":["turkish"],"yaprak":["turkish"],"yaratık":["turkish"],"yarbay":["turkish"],"yardım":["turkish"],"yargıç":["turkish"],"yarıçap":["turkish"],"yasemin":["turkish"],"yastık":["turkish"],"yaşam":["turkish"],"yatak":["turkish"],"yatırım":["turkish"],"yavru":["turkish"],"yaygara":["turkish"],"yayıncı":["turkish"],"yayla":["turkish"],"yazılım":["turkish"],"yekpare":["turkish"],"yekvücut":["turkish"],"yelkovan":["turkish"],"yelpaze":["turkish"],"yemek":["turkish"],"yemiş":["turkish"],"yengeç":["turkish"],"yeniçeri":["turkish"],"yeraltı":["turkish"],"yerküre":["turkish"],"yerleşke":["turkish"],"yeryüzü":["turkish"],"yeşil":["turkish"],"yetenek":["turkish"],"yetkili":["turkish"],"yığınak":["turkish"],"yıkama":["turkish"],"yılbaşı":["turkish"],"yıldırım":["turkish"],"yılkı":["turkish"],"yılmaz":["turkish"],"yırtıcı":["turkish"],"yiğit":["turkish"],"yoğurt":["turkish"],"yokuş":["turkish"],"yolcu":["turkish"],"yoldaş":["turkish"],"yolgeçen":["turkish"],"yolkesen":["turkish"],"yolüstü":["turkish"],"yordam":["turkish"],"yorgan":["turkish"],"yorumcu":["turkish"],"yosun":["turkish"],"yöndeş":["turkish"],"yönetim":["turkish"],"yönlü":["turkish"],"yöntem":["turkish"],"yöresel":["turkish"],"yörünge":["turkish"],"yufka":["turkish"],"yukarı":["turkish"],"yumruk":["turkish"],"yumurta":["turkish"],"yuvarlak":["turkish"],"yücelme":["turkish"],"yükçeker":["turkish"],"yüklem":["turkish"],"yüksek":["turkish"],"yürek":["turkish"],"yürütme":["turkish"],"yüzde":["turkish"],"yüzeysel":["turkish"],"yüzgeç":["turkish"],"yüzüstü":["turkish"],"yüzyıl":["turkish"],"zabıta":["turkish"],"zafer":["turkish"],"zahmet":["turkish"],"zambak":["turkish"],"zaptiye":["turkish"],"zarafet":["turkish"],"zaruret":["turkish"],"zeka":["turkish"],"zekice":["turkish"],"zemberek":["turkish"],"zemin":["turkish"],"zencefil":["turkish"],"zeplin":["turkish"],"zeytin":["turkish"],"zıbın":["turkish"],"zılgıt":["turkish"],"zımbırtı":["turkish"],"zımpara":["turkish"],"zıpkın":["turkish"],"zigon":["turkish"],"zihinsel":["turkish"],"zihniyet":["turkish"],"zincir":["turkish"],"zindan":["turkish"],"zirzop":["turkish"],"ziyaret":["turkish"],"ziynet":["turkish"],"zoraki":["turkish"],"zorlu":["turkish"],"zorunlu":["turkish"],"züğürt":["turkish"],"zümre":["turkish"]}["abacate","abaixo","abalar","abater","abduzir","abelha","aberto","abismo","abotoar","abranger","abreviar","abrigar","abrupto","absinto","absoluto","absurdo","abutre","acabado","acalmar","acampar","acanhar","acaso","aceitar","acelerar","acenar","acervo","acessar","acetona","achatar","acidez","acima","acionado","acirrar","aclamar","aclive","acolhida","acomodar","acoplar","acordar","acumular","acusador","adaptar","adega","adentro","adepto","adequar","aderente","adesivo","adeus","adiante","aditivo","adjetivo","adjunto","admirar","adorar","adquirir","adubo","adverso","advogado","aeronave","afastar","aferir","afetivo","afinador","afivelar","aflito","afluente","afrontar","agachar","agarrar","agasalho","agenciar","agilizar","agiota","agitado","agora","agradar","agreste","agrupar","aguardar","agulha","ajoelhar","ajudar","ajustar","alameda","alarme","alastrar","alavanca","albergue","albino","alcatra","aldeia","alecrim","alegria","alertar","alface","alfinete","algum","alheio","aliar","alicate","alienar","alinhar","aliviar","almofada","alocar","alpiste","alterar","altitude","alucinar","alugar","aluno","alusivo","alvo","amaciar","amador","amarelo","amassar","ambas","ambiente","ameixa","amenizar","amido","amistoso","amizade","amolador","amontoar","amoroso","amostra","amparar","ampliar","ampola","anagrama","analisar","anarquia","anatomia","andaime","anel","anexo","angular","animar","anjo","anomalia","anotado","ansioso","anterior","anuidade","anunciar","anzol","apagador","apalpar","apanhado","apego","apelido","apertada","apesar","apetite","apito","aplauso","aplicada","apoio","apontar","aposta","aprendiz","aprovar","aquecer","arame","aranha","arara","arcada","ardente","areia","arejar","arenito","aresta","argiloso","argola","arma","arquivo","arraial","arrebate","arriscar","arroba","arrumar","arsenal","arterial","artigo","arvoredo","asfaltar","asilado","aspirar","assador","assinar","assoalho","assunto","astral","atacado","atadura","atalho","atarefar","atear","atender","aterro","ateu","atingir","atirador","ativo","atoleiro","atracar","atrevido","atriz","atual","atum","auditor","aumentar","aura","aurora","autismo","autoria","autuar","avaliar","avante","avaria","avental","avesso","aviador","avisar","avulso","axila","azarar","azedo","azeite","azulejo","babar","babosa","bacalhau","bacharel","bacia","bagagem","baiano","bailar","baioneta","bairro","baixista","bajular","baleia","baliza","balsa","banal","bandeira","banho","banir","banquete","barato","barbado","baronesa","barraca","barulho","baseado","bastante","batata","batedor","batida","batom","batucar","baunilha","beber","beijo","beirada","beisebol","beldade","beleza","belga","beliscar","bendito","bengala","benzer","berimbau","berlinda","berro","besouro","bexiga","bezerro","bico","bicudo","bienal","bifocal","bifurcar","bigorna","bilhete","bimestre","bimotor","biologia","biombo","biosfera","bipolar","birrento","biscoito","bisneto","bispo","bissexto","bitola","bizarro","blindado","bloco","bloquear","boato","bobagem","bocado","bocejo","bochecha","boicotar","bolada","boletim","bolha","bolo","bombeiro","bonde","boneco","bonita","borbulha","borda","boreal","borracha","bovino","boxeador","branco","brasa","braveza","breu","briga","brilho","brincar","broa","brochura","bronzear","broto","bruxo","bucha","budismo","bufar","bule","buraco","busca","busto","buzina","cabana","cabelo","cabide","cabo","cabrito","cacau","cacetada","cachorro","cacique","cadastro","cadeado","cafezal","caiaque","caipira","caixote","cajado","caju","calafrio","calcular","caldeira","calibrar","calmante","calota","camada","cambista","camisa","camomila","campanha","camuflar","canavial","cancelar","caneta","canguru","canhoto","canivete","canoa","cansado","cantar","canudo","capacho","capela","capinar","capotar","capricho","captador","capuz","caracol","carbono","cardeal","careca","carimbar","carneiro","carpete","carreira","cartaz","carvalho","casaco","casca","casebre","castelo","casulo","catarata","cativar","caule","causador","cautelar","cavalo","caverna","cebola","cedilha","cegonha","celebrar","celular","cenoura","censo","centeio","cercar","cerrado","certeiro","cerveja","cetim","cevada","chacota","chaleira","chamado","chapada","charme","chatice","chave","chefe","chegada","cheiro","cheque","chicote","chifre","chinelo","chocalho","chover","chumbo","chutar","chuva","cicatriz","ciclone","cidade","cidreira","ciente","cigana","cimento","cinto","cinza","ciranda","circuito","cirurgia","citar","clareza","clero","clicar","clone","clube","coado","coagir","cobaia","cobertor","cobrar","cocada","coelho","coentro","coeso","cogumelo","coibir","coifa","coiote","colar","coleira","colher","colidir","colmeia","colono","coluna","comando","combinar","comentar","comitiva","comover","complexo","comum","concha","condor","conectar","confuso","congelar","conhecer","conjugar","consumir","contrato","convite","cooperar","copeiro","copiador","copo","coquetel","coragem","cordial","corneta","coronha","corporal","correio","cortejo","coruja","corvo","cosseno","costela","cotonete","couro","couve","covil","cozinha","cratera","cravo","creche","credor","creme","crer","crespo","criada","criminal","crioulo","crise","criticar","crosta","crua","cruzeiro","cubano","cueca","cuidado","cujo","culatra","culminar","culpar","cultura","cumprir","cunhado","cupido","curativo","curral","cursar","curto","cuspir","custear","cutelo","damasco","datar","debater","debitar","deboche","debulhar","decalque","decimal","declive","decote","decretar","dedal","dedicado","deduzir","defesa","defumar","degelo","degrau","degustar","deitado","deixar","delator","delegado","delinear","delonga","demanda","demitir","demolido","dentista","depenado","depilar","depois","depressa","depurar","deriva","derramar","desafio","desbotar","descanso","desenho","desfiado","desgaste","desigual","deslize","desmamar","desova","despesa","destaque","desviar","detalhar","detentor","detonar","detrito","deusa","dever","devido","devotado","dezena","diagrama","dialeto","didata","difuso","digitar","dilatado","diluente","diminuir","dinastia","dinheiro","diocese","direto","discreta","disfarce","disparo","disquete","dissipar","distante","ditador","diurno","diverso","divisor","divulgar","dizer","dobrador","dolorido","domador","dominado","donativo","donzela","dormente","dorsal","dosagem","dourado","doutor","drenagem","drible","drogaria","duelar","duende","dueto","duplo","duquesa","durante","duvidoso","eclodir","ecoar","ecologia","edificar","edital","educado","efeito","efetivar","ejetar","elaborar","eleger","eleitor","elenco","elevador","eliminar","elogiar","embargo","embolado","embrulho","embutido","emenda","emergir","emissor","empatia","empenho","empinado","empolgar","emprego","empurrar","emulador","encaixe","encenado","enchente","encontro","endeusar","endossar","enfaixar","enfeite","enfim","engajado","engenho","englobar","engomado","engraxar","enguia","enjoar","enlatar","enquanto","enraizar","enrolado","enrugar","ensaio","enseada","ensino","ensopado","entanto","enteado","entidade","entortar","entrada","entulho","envergar","enviado","envolver","enxame","enxerto","enxofre","enxuto","epiderme","equipar","ereto","erguido","errata","erva","ervilha","esbanjar","esbelto","escama","escola","escrita","escuta","esfinge","esfolar","esfregar","esfumado","esgrima","esmalte","espanto","espelho","espiga","esponja","espreita","espumar","esquerda","estaca","esteira","esticar","estofado","estrela","estudo","esvaziar","etanol","etiqueta","euforia","europeu","evacuar","evaporar","evasivo","eventual","evidente","evoluir","exagero","exalar","examinar","exato","exausto","excesso","excitar","exclamar","executar","exemplo","exibir","exigente","exonerar","expandir","expelir","expirar","explanar","exposto","expresso","expulsar","externo","extinto","extrato","fabricar","fabuloso","faceta","facial","fada","fadiga","faixa","falar","falta","familiar","fandango","fanfarra","fantoche","fardado","farelo","farinha","farofa","farpa","fartura","fatia","fator","favorita","faxina","fazenda","fechado","feijoada","feirante","felino","feminino","fenda","feno","fera","feriado","ferrugem","ferver","festejar","fetal","feudal","fiapo","fibrose","ficar","ficheiro","figurado","fileira","filho","filme","filtrar","firmeza","fisgada","fissura","fita","fivela","fixador","fixo","flacidez","flamingo","flanela","flechada","flora","flutuar","fluxo","focal","focinho","fofocar","fogo","foguete","foice","folgado","folheto","forjar","formiga","forno","forte","fosco","fossa","fragata","fralda","frango","frasco","fraterno","freira","frente","fretar","frieza","friso","fritura","fronha","frustrar","fruteira","fugir","fulano","fuligem","fundar","fungo","funil","furador","furioso","futebol","gabarito","gabinete","gado","gaiato","gaiola","gaivota","galega","galho","galinha","galocha","ganhar","garagem","garfo","gargalo","garimpo","garoupa","garrafa","gasoduto","gasto","gata","gatilho","gaveta","gazela","gelado","geleia","gelo","gemada","gemer","gemido","generoso","gengiva","genial","genoma","genro","geologia","gerador","germinar","gesso","gestor","ginasta","gincana","gingado","girafa","girino","glacial","glicose","global","glorioso","goela","goiaba","golfe","golpear","gordura","gorjeta","gorro","gostoso","goteira","governar","gracejo","gradual","grafite","gralha","grampo","granada","gratuito","graveto","graxa","grego","grelhar","greve","grilo","grisalho","gritaria","grosso","grotesco","grudado","grunhido","gruta","guache","guarani","guaxinim","guerrear","guiar","guincho","guisado","gula","guloso","guru","habitar","harmonia","haste","haver","hectare","herdar","heresia","hesitar","hiato","hibernar","hidratar","hiena","hino","hipismo","hipnose","hipoteca","hoje","holofote","homem","honesto","honrado","hormonal","hospedar","humorado","iate","ideia","idoso","ignorado","igreja","iguana","ileso","ilha","iludido","iluminar","ilustrar","imagem","imediato","imenso","imersivo","iminente","imitador","imortal","impacto","impedir","implante","impor","imprensa","impune","imunizar","inalador","inapto","inativo","incenso","inchar","incidir","incluir","incolor","indeciso","indireto","indutor","ineficaz","inerente","infantil","infestar","infinito","inflamar","informal","infrator","ingerir","inibido","inicial","inimigo","injetar","inocente","inodoro","inovador","inox","inquieto","inscrito","inseto","insistir","inspetor","instalar","insulto","intacto","integral","intimar","intocado","intriga","invasor","inverno","invicto","invocar","iogurte","iraniano","ironizar","irreal","irritado","isca","isento","isolado","isqueiro","italiano","janeiro","jangada","janta","jararaca","jardim","jarro","jasmim","jato","javali","jazida","jejum","joaninha","joelhada","jogador","joia","jornal","jorrar","jovem","juba","judeu","judoca","juiz","julgador","julho","jurado","jurista","juro","justa","labareda","laboral","lacre","lactante","ladrilho","lagarta","lagoa","laje","lamber","lamentar","laminar","lampejo","lanche","lapidar","lapso","laranja","lareira","largura","lasanha","lastro","lateral","latido","lavanda","lavoura","lavrador","laxante","lazer","lealdade","lebre","legado","legendar","legista","leigo","leiloar","leitura","lembrete","leme","lenhador","lentilha","leoa","lesma","leste","letivo","letreiro","levar","leveza","levitar","liberal","libido","liderar","ligar","ligeiro","limitar","limoeiro","limpador","linda","linear","linhagem","liquidez","listagem","lisura","litoral","livro","lixa","lixeira","locador","locutor","lojista","lombo","lona","longe","lontra","lorde","lotado","loteria","loucura","lousa","louvar","luar","lucidez","lucro","luneta","lustre","lutador","luva","macaco","macete","machado","macio","madeira","madrinha","magnata","magreza","maior","mais","malandro","malha","malote","maluco","mamilo","mamoeiro","mamute","manada","mancha","mandato","manequim","manhoso","manivela","manobrar","mansa","manter","manusear","mapeado","maquinar","marcador","maresia","marfim","margem","marinho","marmita","maroto","marquise","marreco","martelo","marujo","mascote","masmorra","massagem","mastigar","matagal","materno","matinal","matutar","maxilar","medalha","medida","medusa","megafone","meiga","melancia","melhor","membro","memorial","menino","menos","mensagem","mental","merecer","mergulho","mesada","mesclar","mesmo","mesquita","mestre","metade","meteoro","metragem","mexer","mexicano","micro","migalha","migrar","milagre","milenar","milhar","mimado","minerar","minhoca","ministro","minoria","miolo","mirante","mirtilo","misturar","mocidade","moderno","modular","moeda","moer","moinho","moita","moldura","moleza","molho","molinete","molusco","montanha","moqueca","morango","morcego","mordomo","morena","mosaico","mosquete","mostarda","motel","motim","moto","motriz","muda","muito","mulata","mulher","multar","mundial","munido","muralha","murcho","muscular","museu","musical","nacional","nadador","naja","namoro","narina","narrado","nascer","nativa","natureza","navalha","navegar","navio","neblina","nebuloso","negativa","negociar","negrito","nervoso","neta","neural","nevasca","nevoeiro","ninar","ninho","nitidez","nivelar","nobreza","noite","noiva","nomear","nominal","nordeste","nortear","notar","noticiar","noturno","novelo","novilho","novo","nublado","nudez","numeral","nupcial","nutrir","nuvem","obcecado","obedecer","objetivo","obrigado","obscuro","obstetra","obter","obturar","ocidente","ocioso","ocorrer","oculista","ocupado","ofegante","ofensiva","oferenda","oficina","ofuscado","ogiva","olaria","oleoso","olhar","oliveira","ombro","omelete","omisso","omitir","ondulado","oneroso","ontem","opcional","operador","oponente","oportuno","oposto","orar","orbitar","ordem","ordinal","orfanato","orgasmo","orgulho","oriental","origem","oriundo","orla","ortodoxo","orvalho","oscilar","ossada","osso","ostentar","otimismo","ousadia","outono","outubro","ouvido","ovelha","ovular","oxidar","oxigenar","pacato","paciente","pacote","pactuar","padaria","padrinho","pagar","pagode","painel","pairar","paisagem","palavra","palestra","palheta","palito","palmada","palpitar","pancada","panela","panfleto","panqueca","pantanal","papagaio","papelada","papiro","parafina","parcial","pardal","parede","partida","pasmo","passado","pastel","patamar","patente","patinar","patrono","paulada","pausar","peculiar","pedalar","pedestre","pediatra","pedra","pegada","peitoral","peixe","pele","pelicano","penca","pendurar","peneira","penhasco","pensador","pente","perceber","perfeito","pergunta","perito","permitir","perna","perplexo","persiana","pertence","peruca","pescado","pesquisa","pessoa","petiscar","piada","picado","piedade","pigmento","pilastra","pilhado","pilotar","pimenta","pincel","pinguim","pinha","pinote","pintar","pioneiro","pipoca","piquete","piranha","pires","pirueta","piscar","pistola","pitanga","pivete","planta","plaqueta","platina","plebeu","plumagem","pluvial","pneu","poda","poeira","poetisa","polegada","policiar","poluente","polvilho","pomar","pomba","ponderar","pontaria","populoso","porta","possuir","postal","pote","poupar","pouso","povoar","praia","prancha","prato","praxe","prece","predador","prefeito","premiar","prensar","preparar","presilha","pretexto","prevenir","prezar","primata","princesa","prisma","privado","processo","produto","profeta","proibido","projeto","prometer","propagar","prosa","protetor","provador","publicar","pudim","pular","pulmonar","pulseira","punhal","punir","pupilo","pureza","puxador","quadra","quantia","quarto","quase","quebrar","queda","queijo","quente","querido","quimono","quina","quiosque","rabanada","rabisco","rachar","racionar","radial","raiar","rainha","raio","raiva","rajada","ralado","ramal","ranger","ranhura","rapadura","rapel","rapidez","raposa","raquete","raridade","rasante","rascunho","rasgar","raspador","rasteira","rasurar","ratazana","ratoeira","realeza","reanimar","reaver","rebaixar","rebelde","rebolar","recado","recente","recheio","recibo","recordar","recrutar","recuar","rede","redimir","redonda","reduzida","reenvio","refinar","refletir","refogar","refresco","refugiar","regalia","regime","regra","reinado","reitor","rejeitar","relativo","remador","remendo","remorso","renovado","reparo","repelir","repleto","repolho","represa","repudiar","requerer","resenha","resfriar","resgatar","residir","resolver","respeito","ressaca","restante","resumir","retalho","reter","retirar","retomada","retratar","revelar","revisor","revolta","riacho","rica","rigidez","rigoroso","rimar","ringue","risada","risco","risonho","robalo","rochedo","rodada","rodeio","rodovia","roedor","roleta","romano","roncar","rosado","roseira","rosto","rota","roteiro","rotina","rotular","rouco","roupa","roxo","rubro","rugido","rugoso","ruivo","rumo","rupestre","russo","sabor","saciar","sacola","sacudir","sadio","safira","saga","sagrada","saibro","salada","saleiro","salgado","saliva","salpicar","salsicha","saltar","salvador","sambar","samurai","sanar","sanfona","sangue","sanidade","sapato","sarda","sargento","sarjeta","saturar","saudade","saxofone","sazonal","secar","secular","seda","sedento","sediado","sedoso","sedutor","segmento","segredo","segundo","seiva","seleto","selvagem","semanal","semente","senador","senhor","sensual","sentado","separado","sereia","seringa","serra","servo","setembro","setor","sigilo","silhueta","silicone","simetria","simpatia","simular","sinal","sincero","singular","sinopse","sintonia","sirene","siri","situado","soberano","sobra","socorro","sogro","soja","solda","soletrar","solteiro","sombrio","sonata","sondar","sonegar","sonhador","sono","soprano","soquete","sorrir","sorteio","sossego","sotaque","soterrar","sovado","sozinho","suavizar","subida","submerso","subsolo","subtrair","sucata","sucesso","suco","sudeste","sufixo","sugador","sugerir","sujeito","sulfato","sumir","suor","superior","suplicar","suposto","suprimir","surdina","surfista","surpresa","surreal","surtir","suspiro","sustento","tabela","tablete","tabuada","tacho","tagarela","talher","talo","talvez","tamanho","tamborim","tampa","tangente","tanto","tapar","tapioca","tardio","tarefa","tarja","tarraxa","tatuagem","taurino","taxativo","taxista","teatral","tecer","tecido","teclado","tedioso","teia","teimar","telefone","telhado","tempero","tenente","tensor","tentar","termal","terno","terreno","tese","tesoura","testado","teto","textura","texugo","tiara","tigela","tijolo","timbrar","timidez","tingido","tinteiro","tiragem","titular","toalha","tocha","tolerar","tolice","tomada","tomilho","tonel","tontura","topete","tora","torcido","torneio","torque","torrada","torto","tostar","touca","toupeira","toxina","trabalho","tracejar","tradutor","trafegar","trajeto","trama","trancar","trapo","traseiro","tratador","travar","treino","tremer","trepidar","trevo","triagem","tribo","triciclo","tridente","trilogia","trindade","triplo","triturar","triunfal","trocar","trombeta","trova","trunfo","truque","tubular","tucano","tudo","tulipa","tupi","turbo","turma","turquesa","tutelar","tutorial","uivar","umbigo","unha","unidade","uniforme","urologia","urso","urtiga","urubu","usado","usina","usufruir","vacina","vadiar","vagaroso","vaidoso","vala","valente","validade","valores","vantagem","vaqueiro","varanda","vareta","varrer","vascular","vasilha","vassoura","vazar","vazio","veado","vedar","vegetar","veicular","veleiro","velhice","veludo","vencedor","vendaval","venerar","ventre","verbal","verdade","vereador","vergonha","vermelho","verniz","versar","vertente","vespa","vestido","vetorial","viaduto","viagem","viajar","viatura","vibrador","videira","vidraria","viela","viga","vigente","vigiar","vigorar","vilarejo","vinco","vinheta","vinil","violeta","virada","virtude","visitar","visto","vitral","viveiro","vizinho","voador","voar","vogal","volante","voleibol","voltagem","volumoso","vontade","vulto","vuvuzela","xadrez","xarope","xeque","xeretar","xerife","xingar","zangado","zarpar","zebu","zelador","zombar","zoologia","zumbido"]["абзац","абонент","абсурд","авангард","авария","август","авиация","автор","агент","агитация","агрегат","адвокат","адмирал","адрес","азарт","азот","академия","аквариум","аксиома","акула","акцент","акция","аллея","алмаз","алтарь","альбом","альянс","амбиция","анализ","анекдот","анкета","ансамбль","антенна","апельсин","аппарат","аппетит","апрель","аптека","арбуз","аргумент","аренда","арест","армия","аромат","арсенал","артерия","артист","архив","аспирант","асфальт","атака","атомный","атрибут","аукцион","афиша","аэропорт","бабочка","бабушка","багаж","база","бактерия","баланс","балерина","балкон","бандит","банк","барабан","барон","барышня","барьер","бассейн","батарея","башмак","башня","бедный","беженец","бездна","белка","белый","бензин","берег","беседа","бешеный","билет","бинокль","биржа","битва","благо","блеск","близкий","блин","блок","блюдо","богатый","бодрый","боец","бокал","боковой","бокс","более","болото","болтать","большой","бомба","борт","борьба","босой","ботинок","бояться","брак","брать","бревно","бред","бригада","бродяга","броня","бросить","брызги","брюки","брюхо","бугор","будка","будни","будущее","буква","букет","бульвар","бумага","бунт","бурный","буря","бутылка","бухта","бывший","быстро","бытовой","быть","бюджет","бюро","бюст","вагон","важный","вакцина","валенок","вальс","валюта","ванная","варенье","вариант","вблизи","вверх","вводить","вдали","вдвое","вдова","вдоль","вдруг","ведро","ведущий","ведьма","вежливо","везде","веко","вексель","велеть","великий","венец","веник","веранда","верблюд","верить","верный","версия","вертеть","верхний","вершина","весело","весна","весомый","вести","весь","ветеран","ветхий","вечер","вечно","вешалка","вещество","взамен","взгляд","вздох","взнос","взойти","взор","взрыв","взять","видеть","видимо","визг","визит","вилка","вина","вирус","висок","витамин","витрина","вихрь","вишня","вкус","влага","владелец","власть","влево","влияние","вложить","вместе","внешний","вникать","внимание","вновь","внук","внутри","внучка","внушать","вовлечь","вовремя","вовсю","вода","водород","водяной","воевать","возврат","возглас","воздух","возить","возле","возня","возраст","война","войско","вокзал","волос","волчий","вольный","воля","вообще","вопль","вопрос","ворота","восемь","восток","вплоть","вполне","вправе","впредь","впрочем","врач","вредный","время","вручить","всадник","всегда","вскоре","вскрыть","всплеск","вспышка","встреча","всюду","всякий","второй","вход","вчера","выбор","вывод","выгнать","выдать","выехать","вызов","выйти","выкуп","вылезти","вымыть","выпасть","выпить","выплата","выпуск","вырасти","выручка","выслать","высокий","выставка","вышка","вязать","вялый","газета","газовый","галерея","галстук","гамма","гарантия","гармония","гарнизон","гастроли","гвардия","гвоздь","гектар","генерал","гений","геном","геолог","герб","герой","гибкий","гигант","гимн","гипотеза","гитара","главный","глагол","гладить","глаз","глина","глоток","глубокий","глупый","глухой","глыба","глядеть","гнев","гнездо","гнилой","годовой","голова","голубой","голый","гонорар","гордость","горизонт","горло","горный","город","горшок","горький","горючее","горячий","готовый","градус","грамм","граница","граф","гребень","гриб","гримаса","грозить","грохот","грош","грубый","грудь","груз","грунт","группа","груша","грязный","губа","гудок","гулкий","гулять","гусеница","густо","гусь","давление","давно","даже","дальний","данный","дарить","датчик","дать","дача","двадцать","дважды","дверь","двигать","движение","двойной","двор","дебют","девятый","дежурный","действие","декабрь","деление","дело","дельфин","день","дерево","держать","дерзкий","десять","деталь","детский","дефект","дефицит","деятель","джаз","джинсы","джунгли","диагноз","диалог","диапазон","диван","дивизия","дивный","диета","дизайн","дикарь","дилер","динамика","диплом","директор","дитя","длинный","дневник","добрый","добыча","доверие","догадка","догнать","дождь","доклад","доктор","документ","долго","должен","долина","донос","дорога","досада","доска","достать","досуг","доход","доцент","дощатый","драка","древний","дремать","дробный","дрова","дрожать","другой","дружба","дубовый","дуга","думать","дурной","духи","душный","дуэль","дуэт","дыра","дыхание","дюжина","дядя","едва","единый","ерунда","если","ехать","жадный","жажда","жалеть","жалоба","жанр","жареный","жаркий","жгучий","жевать","желание","желудок","жена","женщина","жертва","жест","жидкость","житель","жить","жрец","жулик","журнал","жуткий","забрать","забыть","завести","завод","завтра","загадка","загнать","заговор","задача","задеть","задний","задолго","заехать","заказ","закон","закрыть","закуска","залезть","залить","залп","замок","замуж","замысел","занавес","заново","занять","заодно","запись","запрос","запуск","запястье","заранее","заросль","зарплата","заря","засада","заслуга","заснуть","застать","затвор","затеять","затрата","затылок","захват","зачем","защита","заявить","заяц","звезда","звено","звонить","здесь","зелень","земля","зеркало","зерно","зима","злой","змея","знамя","знание","значит","золотой","зона","зонтик","зоопарк","зрачок","зрение","зритель","зубной","зубр","игла","идеал","идеолог","идея","идол","идти","изба","избить","избрать","избыток","извлечь","извне","изгиб","изгнать","издание","изделие","изнутри","изобилие","изоляция","изредка","изрядно","изучение","изъять","изящный","икона","икра","иллюзия","именно","иметь","имидж","империя","импульс","иначе","инвалид","индекс","индивид","инерция","инженер","иногда","иной","институт","интерес","интрига","интуиция","инфаркт","инцидент","ирония","искать","испуг","история","итог","июнь","кабель","кабинет","каблук","кавалер","кадр","каждый","кажется","казино","калитка","камень","камин","канал","кандидат","каникулы","канон","капитан","капля","капот","капуста","карандаш","карета","каркас","карман","картина","карьера","каска","кассета","кастрюля","каталог","катер","каток","катушка","кафедра","качество","каша","кашлять","каюта","квадрат","квартира","квота","кепка","кивнуть","километр","кино","киоск","кипяток","кирпич","кислота","кисть","клавиша","клапан","класс","клей","клетка","клиент","климат","клиника","кличка","клоун","клочок","клуб","клумба","ключ","книга","кнопка","кнут","княгиня","князь","кобура","когда","кодекс","кожа","коктейль","колено","коллега","колонна","колпак","кольцо","колючий","коляска","команда","комедия","комиссия","коммуна","комната","комок","компания","комфорт","конвейер","конгресс","конечно","конкурс","контроль","концерт","конь","конюшня","копать","копейка","копыто","корабль","корень","корзина","коридор","кормить","корпус","космос","костюм","косяк","котел","котлета","который","коттедж","кофе","кофта","кошка","кража","край","красный","краткий","кредит","крем","крепкий","кресло","кривой","кризис","кристалл","критерий","кричать","кровь","крокодил","кролик","кроме","крона","круг","кружка","крупный","крутой","крушение","крыло","крыша","крючок","кстати","кубик","куда","кузов","кукла","кулак","кулиса","культура","кумир","купе","купить","купол","купюра","курица","курорт","курс","куртка","кусок","куст","кухня","кушать","лабиринт","лавка","лагерь","ладно","ладонь","лапа","лауреат","лгать","лебедь","левый","легенда","легкий","ледяной","лежать","лезвие","лезть","лекция","ленивый","лента","лепесток","лесной","лестница","лететь","лето","лечить","лига","лидер","лиловый","лимон","линия","липкий","лист","литр","лихой","лицо","лишить","лишний","ловить","логика","лодка","ложь","лозунг","локоть","лопата","лошадь","лукавый","луна","лучший","лысый","льгота","любить","любой","людской","люстра","лютый","лягушка","магазин","магия","майор","майский","максимум","макушка","мало","мальчик","мама","манера","марка","март","маршрут","масса","мастер","масштаб","материал","матч","махать","машина","маяк","мебель","медаль","медведь","медицина","медь","между","мелкий","мелочь","мемуары","меньше","меню","менять","мера","мерцать","место","месяц","металл","метод","метр","механизм","меховой","мечтать","мешать","мешок","миграция","микрофон","милиция","миллион","милость","миля","мимо","минерал","министр","минута","мирный","миска","миссия","митинг","мишень","младший","мнение","мнимый","много","могучий","модель","может","мозг","мокрый","молекула","молния","молодой","молчать","момент","монета","монитор","монолог","монстр","монтаж","мораль","море","морковь","мороз","морщина","мостовая","мотать","мотив","мотор","мохнатый","мрамор","мрачный","мстить","мудрый","мужество","мужчина","музей","музыка","мундир","муравей","мусор","муха","мчаться","мысль","мыться","мышца","мышь","мюзикл","мягкий","мясо","набор","навык","наглый","нагрузка","надежда","надзор","надо","наедине","назад","название","назло","наивный","найти","наконец","налево","наличие","налог","намерен","нанести","напасть","например","народ","наследие","натура","наука","наутро","начать","небо","неважно","невеста","негодяй","недавно","неделя","недолго","недра","недуг","нежный","незачем","некто","нелепый","неловко","нельзя","немало","немой","неплохо","нервный","нередко","нестись","неудача","неужели","нефть","неясный","нигде","низкий","никакой","никогда","никуда","ничто","ничуть","ниша","нищий","новость","новый","нога","ноготь","ножницы","ноздря","номер","носить","носок","ночь","ноябрь","нрав","нуль","нынче","нырять","нюанс","няня","обаяние","обед","обезьяна","обещать","обжечь","обзор","обилие","обитать","область","облик","обложка","обмен","обморок","обожать","обои","оболочка","оборона","обочина","образ","обрести","обрыв","обувь","обучение","обход","общество","общий","объект","обыск","обычно","обязать","овощи","овраг","овца","оговорка","ограда","огурец","одежда","одеяло","один","однако","одолеть","ожидать","озеро","океан","окно","около","окоп","окраина","октябрь","опасный","опека","операция","описание","оплата","опора","оппонент","оптимизм","оптовый","опухоль","опыт","оратор","орбита","орган","орден","орел","оригинал","ориентир","оркестр","оружие","осенний","осколок","осмотр","остров","отбор","отбыть","отвлечь","отдать","отдел","отдых","отель","отец","отзыв","отказ","отклик","открыть","откуда","отличие","отныне","отойти","отпуск","отрасль","отросток","отрывок","отряд","отсек","отставка","отсюда","оттенок","оттого","отчего","отъезд","офис","офицер","охота","охрана","оценка","очаг","очень","очередь","очищать","ошибка","ощущение","павильон","падать","пазуха","пакет","палата","палец","палуба","пальто","память","панель","паника","пара","парень","пароход","партия","парус","паспорт","пассажир","пастух","патент","патрон","пауза","паук","паутина","пафос","пахнуть","пациент","пачка","певец","педагог","пейзаж","пенсия","пепел","первый","перед","период","перо","перрон","персонаж","перчатка","песня","песок","петля","петрушка","петух","пехота","печать","печень","пешком","пещера","пианист","пиджак","пилот","пионер","пирамида","пирожок","письмо","пища","плавание","плакать","пламя","план","пласт","платить","пленный","плечо","плита","плод","плоский","плотный","плохой","площадь","плыть","плюс","пляж","плясать","победа","повар","повод","повсюду","повязка","погода","погреб","подбор","подвиг","подделка","поджать","поднос","подпись","подруга","подход","подчас","подъезд","поединок","поезд","поесть","поехать","пожалуй","пожилой","позади","позвать","поздний","позиция","позор","поиск","поймать","пойти","поклон","покой","покрыть","полдень","полезный","ползти","полк","полный","половина","полтора","польза","поляна","помидор","помнить","помощь","попасть","поперек","поплыть","пополам","поправка","попугай","попытка","порог","портрет","порция","порыв","порядок","после","посол","посреди","постель","посуда","потом","похвала","похожий","поцелуй","почва","почему","пошлина","поэма","поэтому","право","праздник","практика","прах","преграда","предмет","прежде","прелесть","премия","препарат","пресса","прибыть","прижать","прийти","приказ","прилавок","пример","принять","природа","притом","прихожая","прицел","причина","приют","прогноз","продукт","проект","прожить","прокат","промысел","пропуск","просто","против","профиль","процесс","прочий","прошлый","прощать","пружина","прут","прыжок","прямой","птица","публика","пугать","пуговица","пузырь","пульт","пуля","пункт","пускать","пустой","путь","пухлый","пучок","пушистый","пушка","пчела","пшеница","пылать","пыль","пышный","пьеса","пятка","пятно","пятый","пятьсот","работа","равнина","ради","радость","радуга","разбить","развитие","разговор","раздел","различие","размер","разный","разрыв","разум","район","ракета","раковина","рамка","рано","рапорт","распад","рассказ","расти","расход","расцвет","рация","рвануть","рваться","реакция","ребро","реветь","редактор","редкий","реестр","режим","резать","резерв","резина","резко","резной","рейс","реклама","рекорд","религия","рельс","ремень","ремонт","реплика","репортаж","ресница","ресторан","реформа","рецепт","речь","решение","ржавый","риск","рисунок","ритуал","рифма","робко","робот","ровесник","ровно","родной","рождение","роза","розовый","розыск","роль","роман","роскошь","роспись","рост","рубашка","рубеж","рубить","рубрика","рудник","рука","рукопись","румяный","русло","рухнуть","ручей","ручной","рыба","рыжий","рынок","рыхлый","рыцарь","рычаг","рюкзак","рядом","садовый","сажать","салон","салфетка","салют","самец","самовар","самый","сани","санкция","сапог","сарай","сатира","сахар","сбить","сбоку","сборная","сбыт","свадьба","свалка","сварить","свежий","сверху","свет","свеча","свинья","свист","свитер","свобода","сводка","свой","свыше","связь","сдаться","сделать","сегмент","сегодня","седло","седой","седьмой","сезон","сейф","сейчас","секрет","сектор","секунда","семинар","семья","сенатор","сено","сенсация","сентябрь","сервис","сердце","середина","сержант","серия","серый","сессия","сесть","сетевой","сжатый","сжечь","сзади","сигнал","сиденье","сила","силуэт","сильный","символ","симпатия","симфония","синий","синтез","синяк","сирень","система","ситуация","сияние","сказать","скала","скамейка","скандал","скатерть","скачок","скважина","сквер","сквозь","скелет","скидка","склад","сколько","скорый","скосить","скот","скрипка","скудный","скука","слабый","слава","сладкий","слегка","след","слеза","слепой","слесарь","слишком","слово","слог","сложный","сломать","служба","слух","случай","слышать","слюна","смежный","смелый","сменить","смесь","сметана","смех","смола","смуглый","смутный","смущать","смысл","снайпер","снаряд","сначала","снег","снизу","сниться","сно��а","снять","собака","соблазн","собрание","событие","совесть","совсем","согласие","создать","сознание","созреть","сойтись","сокол","солдат","соленый","солнце","солома","сомнение","сонный","соперник","соратник","сорвать","сосед","сосиска","состав","сотня","соус","союз","спад","спальня","спасти","спектр","сперва","спешить","спина","спирт","список","спичка","сплав","спонсор","спор","способ","справка","спустя","спутник","сразу","средство","срок","срыв","ссора","ссылка","ставить","стадия","стакан","станция","старый","стая","стебель","стекло","стена","степень","стереть","стиль","стимул","стирать","стихи","стоить","стойка","стол","стонать","стопа","сторона","стоянка","страна","стричь","строгий","струя","студент","стук","ступня","стыдно","суббота","субъект","сувенир","сугроб","сугубо","судить","судно","судьба","суета","суметь","сумма","сумрак","сундук","супруг","суровый","сутки","сухой","суша","существо","сфера","схема","схожий","сценарий","счастье","считать","съезд","сыграть","сырой","сытый","сыщик","сюда","сюжет","сюрприз","тайна","также","такой","такси","тактика","талия","таможня","танец","таракан","тарелка","тариф","тащить","таять","тварь","театр","тезис","текст","текущий","телефон","тема","темнота","теневой","теннис","теория","теперь","тепло","терапия","терзать","термин","терпеть","терраса","терять","тесный","тетрадь","техника","течение","тигр","типовой","тираж","титул","тихий","ткань","товарищ","тоже","толпа","толстый","толчок","толщина","только","тонкий","тонна","топить","топор","торговля","тормоз","торчать","тотчас","точка","точно","тощий","трава","традиция","трактор","трамвай","траншея","трасса","тревога","трезвый","тренер","трепет","треск","третий","трещина","трибуна","тридцать","триста","триумф","трогать","тройка","тронуть","тропа","тротуар","трубка","труд","трюк","тряпка","туго","туловище","туман","тумбочка","тундра","тупик","турист","турнир","тусклый","туфля","туча","тысяча","тяга","тяжело","убежать","убогий","уборка","уважение","увезти","уволить","угадать","угол","угощать","угроза","угрюмый","удар","удачный","уделять","удивить","удобный","удочка","уезжать","ужин","узел","узкий","уйти","указание","уклон","украсть","укусить","улетать","улица","улыбка","умело","умение","умный","умолять","унести","унижать","унылый","упаковка","упасть","упорно","упрек","урна","уровень","урожай","уронить","усадьба","усатый","усвоить","усилие","условие","услуга","усмешка","успеть","устав","устоять","утечка","утешать","утро","уцелеть","участие","ученик","учесть","ущелье","ущерб","уютный","фабрика","фаворит","факел","факт","фамилия","фантазия","фасад","февраль","феномен","фермер","фигура","физика","филиал","философ","фильм","финал","флаг","флот","фойе","фокус","фонарь","фонд","фонтан","форма","форум","фото","фрагмент","фраза","фракция","фронт","фрукт","функция","фуражка","футбол","футляр","халат","хаос","характер","хата","хвалить","хватать","хвойный","хвост","химия","хирург","хитрый","хищник","хлеб","хлынуть","хмурый","ходить","хозяин","хоккей","холм","холст","хорошо","хотеть","храбрый","храм","хранить","хребет","хрен","хрипло","хроника","хрупкий","художник","худший","хулиган","хутор","царь","цветок","целевой","целиком","целое","цель","цензура","ценить","центр","цепной","цикл","цилиндр","цирк","цитата","цифра","чайник","часы","чашка","человек","челюсть","чемодан","чемпион","чепуха","червь","чердак","через","чернила","черта","чеснок","честно","четверть","четыре","число","чистый","читатель","чтение","чтобы","чувство","чудак","чудный","чудо","чужой","чулок","чума","чушь","чуять","шагать","шанс","шапка","шарик","шарф","шахматы","шашлык","шедевр","шептать","шерсть","шестой","шинель","ширина","шишка","шкаф","школа","шкура","шланг","шлем","шнур","шоколад","шорох","шоссе","шпион","шприц","штаб","штамм","штаны","штатный","штора","штраф","штурм","штык","шумно","шуршать","шутить","шутка","щедрый","щека","щенок","экзамен","экипаж","экономия","экран","эксперт","элемент","элитный","эмоция","энергия","эпизод","эпоха","эскиз","эстрада","этап","этика","этот","эфир","эффект","эшелон","юбилей","юбка","южный","юмор","юность","юрист","юстиция","яблоко","явление","ягода","ядро","язык","яйцо","якобы","якорь","январь","яркий","ярмарка","ярость","ясный","яхта","ячейка","ящик"]["ábaco","abdomen","abeja","abierto","abogado","abono","aborto","abrazo","abrir","abuelo","abuso","acabar","academia","acceso","acción","aceite","acelga","acento","aceptar","ácido","aclarar","acné","acoger","acoso","activo","acto","actriz","actuar","acudir","acuerdo","acusar","adicto","admitir","adoptar","adorno","aduana","adulto","aéreo","afectar","afición","afinar","afirmar","ágil","agitar","agonía","agosto","agotar","agregar","agrio","agua","agudo","águila","aguja","ahogo","ahorro","aire","aislar","ajedrez","ajeno","ajuste","alacrán","alambre","alarma","alba","álbum","alcalde","aldea","alegre","alejar","alerta","aleta","alfiler","alga","algodón","aliado","aliento","alivio","alma","almeja","almíbar","altar","alteza","altivo","alto","altura","alumno","alzar","amable","amante","amapola","amargo","amasar","ámbar","ámbito","ameno","amigo","amistad","amor","amparo","amplio","ancho","anciano","ancla","andar","andén","anemia","ángulo","anillo","ánimo","anís","anotar","antena","antiguo","antojo","anual","anular","anuncio","añadir","añejo","año","apagar","aparato","apetito","apio","aplicar","apodo","aporte","apoyo","aprender","aprobar","apuesta","apuro","arado","araña","arar","árbitro","árbol","arbusto","archivo","arco","arder","ardilla","arduo","área","árido","aries","armonía","arnés","aroma","arpa","arpón","arreglo","arroz","arruga","arte","artista","asa","asado","asalto","ascenso","asegurar","aseo","asesor","asiento","asilo","asistir","asno","asombro","áspero","astilla","astro","astuto","asumir","asunto","atajo","ataque","atar","atento","ateo","ático","atleta","átomo","atraer","atroz","atún","audaz","audio","auge","aula","aumento","ausente","autor","aval","avance","avaro","ave","avellana","avena","avestruz","avión","aviso","ayer","ayuda","ayuno","azafrán","azar","azote","azúcar","azufre","azul","baba","babor","bache","bahía","baile","bajar","balanza","balcón","balde","bambú","banco","banda","baño","barba","barco","barniz","barro","báscula","bastón","basura","batalla","batería","batir","batuta","baúl","bazar","bebé","bebida","bello","besar","beso","bestia","bicho","bien","bingo","blanco","bloque","blusa","boa","bobina","bobo","boca","bocina","boda","bodega","boina","bola","bolero","bolsa","bomba","bondad","bonito","bono","bonsái","borde","borrar","bosque","bote","botín","bóveda","bozal","bravo","brazo","brecha","breve","brillo","brinco","brisa","broca","broma","bronce","brote","bruja","brusco","bruto","buceo","bucle","bueno","buey","bufanda","bufón","búho","buitre","bulto","burbuja","burla","burro","buscar","butaca","buzón","caballo","cabeza","cabina","cabra","cacao","cadáver","cadena","caer","café","caída","caimán","caja","cajón","cal","calamar","calcio","caldo","calidad","calle","calma","calor","calvo","cama","cambio","camello","camino","campo","cáncer","candil","canela","canguro","canica","canto","caña","cañón","caoba","caos","capaz","capitán","capote","captar","capucha","cara","carbón","cárcel","careta","carga","cariño","carne","carpeta","carro","carta","casa","casco","casero","caspa","castor","catorce","catre","caudal","causa","cazo","cebolla","ceder","cedro","celda","célebre","celoso","célula","cemento","ceniza","centro","cerca","cerdo","cereza","cero","cerrar","certeza","césped","cetro","chacal","chaleco","champú","chancla","chapa","charla","chico","chiste","chivo","choque","choza","chuleta","chupar","ciclón","ciego","cielo","cien","cierto","cifra","cigarro","cima","cinco","cine","cinta","ciprés","circo","ciruela","cisne","cita","ciudad","clamor","clan","claro","clase","clave","cliente","clima","clínica","cobre","cocción","cochino","cocina","coco","código","codo","cofre","coger","cohete","cojín","cojo","cola","colcha","colegio","colgar","colina","collar","colmo","columna","combate","comer","comida","cómodo","compra","conde","conejo","conga","conocer","consejo","contar","copa","copia","corazón","corbata","corcho","cordón","corona","correr","coser","cosmos","costa","cráneo","cráter","crear","crecer","creído","crema","cría","crimen","cripta","crisis","cromo","crónica","croqueta","crudo","cruz","cuadro","cuarto","cuatro","cubo","cubrir","cuchara","cuello","cuento","cuerda","cuesta","cueva","cuidar","culebra","culpa","culto","cumbre","cumplir","cuna","cuneta","cuota","cupón","cúpula","curar","curioso","curso","curva","cutis","dama","danza","dar","dardo","dátil","deber","débil","década","decir","dedo","defensa","definir","dejar","delfín","delgado","delito","demora","denso","dental","deporte","derecho","derrota","desayuno","deseo","desfile","desnudo","destino","desvío","detalle","detener","deuda","día","diablo","diadema","diamante","diana","diario","dibujo","dictar","diente","dieta","diez","difícil","digno","dilema","diluir","dinero","directo","dirigir","disco","diseño","disfraz","diva","divino","doble","doce","dolor","domingo","don","donar","dorado","dormir","dorso","dos","dosis","dragón","droga","ducha","duda","duelo","dueño","dulce","dúo","duque","durar","dureza","duro","ébano","ebrio","echar","eco","ecuador","edad","edición","edificio","editor","educar","efecto","eficaz","eje","ejemplo","elefante","elegir","elemento","elevar","elipse","élite","elixir","elogio","eludir","embudo","emitir","emoción","empate","empeño","empleo","empresa","enano","encargo","enchufe","encía","enemigo","enero","enfado","enfermo","engaño","enigma","enlace","enorme","enredo","ensayo","enseñar","entero","entrar","envase","envío","época","equipo","erizo","escala","escena","escolar","escribir","escudo","esencia","esfera","esfuerzo","espada","espejo","espía","esposa","espuma","esquí","estar","este","estilo","estufa","etapa","eterno","ética","etnia","evadir","evaluar","evento","evitar","exacto","examen","exceso","excusa","exento","exigir","exilio","existir","éxito","experto","explicar","exponer","extremo","fábrica","fábula","fachada","fácil","factor","faena","faja","falda","fallo","falso","faltar","fama","familia","famoso","faraón","farmacia","farol","farsa","fase","fatiga","fauna","favor","fax","febrero","fecha","feliz","feo","feria","feroz","fértil","fervor","festín","fiable","fianza","fiar","fibra","ficción","ficha","fideo","fiebre","fiel","fiera","fiesta","figura","fijar","fijo","fila","filete","filial","filtro","fin","finca","fingir","finito","firma","flaco","flauta","flecha","flor","flota","fluir","flujo","flúor","fobia","foca","fogata","fogón","folio","folleto","fondo","forma","forro","fortuna","forzar","fosa","foto","fracaso","frágil","franja","frase","fraude","freír","freno","fresa","frío","frito","fruta","fuego","fuente","fuerza","fuga","fumar","función","funda","furgón","furia","fusil","fútbol","futuro","gacela","gafas","gaita","gajo","gala","galería","gallo","gamba","ganar","gancho","ganga","ganso","garaje","garza","gasolina","gastar","gato","gavilán","gemelo","gemir","gen","género","genio","gente","geranio","gerente","germen","gesto","gigante","gimnasio","girar","giro","glaciar","globo","gloria","gol","golfo","goloso","golpe","goma","gordo","gorila","gorra","gota","goteo","gozar","grada","gráfico","grano","grasa","gratis","grave","grieta","grillo","gripe","gris","grito","grosor","grúa","grueso","grumo","grupo","guante","guapo","guardia","guerra","guía","guiño","guion","guiso","guitarra","gusano","gustar","haber","hábil","hablar","hacer","hacha","hada","hallar","hamaca","harina","haz","hazaña","hebilla","hebra","hecho","helado","helio","hembra","herir","hermano","héroe","hervir","hielo","hierro","hígado","higiene","hijo","himno","historia","hocico","hogar","hoguera","hoja","hombre","hongo","honor","honra","hora","hormiga","horno","hostil","hoyo","hueco","huelga","huerta","hueso","huevo","huida","huir","humano","húmedo","humilde","humo","hundir","huracán","hurto","icono","ideal","idioma","ídolo","iglesia","iglú","igual","ilegal","ilusión","imagen","imán","imitar","impar","imperio","imponer","impulso","incapaz","índice","inerte","infiel","informe","ingenio","inicio","inmenso","inmune","innato","insecto","instante","interés","íntimo","intuir","inútil","invierno","ira","iris","ironía","isla","islote","jabalí","jabón","jamón","jarabe","jardín","jarra","jaula","jazmín","jefe","jeringa","jinete","jornada","joroba","joven","joya","juerga","jueves","juez","jugador","jugo","juguete","juicio","junco","jungla","junio","juntar","júpiter","jurar","justo","juvenil","juzgar","kilo","koala","labio","lacio","lacra","lado","ladrón","lagarto","lágrima","laguna","laico","lamer","lámina","lámpara","lana","lancha","langosta","lanza","lápiz","largo","larva","lástima","lata","látex","latir","laurel","lavar","lazo","leal","lección","leche","lector","leer","legión","legumbre","lejano","lengua","lento","leña","león","leopardo","lesión","letal","letra","leve","leyenda","libertad","libro","licor","líder","lidiar","lienzo","liga","ligero","lima","límite","limón","limpio","lince","lindo","línea","lingote","lino","linterna","líquido","liso","lista","litera","litio","litro","llaga","llama","llanto","llave","llegar","llenar","llevar","llorar","llover","lluvia","lobo","loción","loco","locura","lógica","logro","lombriz","lomo","lonja","lote","lucha","lucir","lugar","lujo","luna","lunes","lupa","lustro","luto","luz","maceta","macho","madera","madre","maduro","maestro","mafia","magia","mago","maíz","maldad","maleta","malla","malo","mamá","mambo","mamut","manco","mando","manejar","manga","maniquí","manjar","mano","manso","manta","mañana","mapa","máquina","mar","marco","marea","marfil","margen","marido","mármol","marrón","martes","marzo","masa","máscara","masivo","matar","materia","matiz","matriz","máximo","mayor","mazorca","mecha","medalla","medio","médula","mejilla","mejor","melena","melón","memoria","menor","mensaje","mente","menú","mercado","merengue","mérito","mes","mesón","meta","meter","método","metro","mezcla","miedo","miel","miembro","miga","mil","milagro","militar","millón","mimo","mina","minero","mínimo","minuto","miope","mirar","misa","miseria","misil","mismo","mitad","mito","mochila","moción","moda","modelo","moho","mojar","molde","moler","molino","momento","momia","monarca","moneda","monja","monto","moño","morada","morder","moreno","morir","morro","morsa","mortal","mosca","mostrar","motivo","mover","móvil","mozo","mucho","mudar","mueble","muela","muerte","muestra","mugre","mujer","mula","muleta","multa","mundo","muñeca","mural","muro","músculo","museo","musgo","música","muslo","nácar","nación","nadar","naipe","naranja","nariz","narrar","nasal","natal","nativo","natural","náusea","naval","nave","navidad","necio","néctar","negar","negocio","negro","neón","nervio","neto","neutro","nevar","nevera","nicho","nido","niebla","nieto","niñez","niño","nítido","nivel","nobleza","noche","nómina","noria","norma","norte","nota","noticia","novato","novela","novio","nube","nuca","núcleo","nudillo","nudo","nuera","nueve","nuez","nulo","número","nutria","oasis","obeso","obispo","objeto","obra","obrero","observar","obtener","obvio","oca","ocaso","océano","ochenta","ocho","ocio","ocre","octavo","octubre","oculto","ocupar","ocurrir","odiar","odio","odisea","oeste","ofensa","oferta","oficio","ofrecer","ogro","oído","oír","ojo","ola","oleada","olfato","olivo","olla","olmo","olor","olvido","ombligo","onda","onza","opaco","opción","ópera","opinar","oponer","optar","óptica","opuesto","oración","orador","oral","órbita","orca","orden","oreja","órgano","orgía","orgullo","oriente","origen","orilla","oro","orquesta","oruga","osadía","oscuro","osezno","oso","ostra","otoño","otro","oveja","óvulo","óxido","oxígeno","oyente","ozono","pacto","padre","paella","página","pago","país","pájaro","palabra","palco","paleta","pálido","palma","paloma","palpar","pan","panal","pánico","pantera","pañuelo","papá","papel","papilla","paquete","parar","parcela","pared","parir","paro","párpado","parque","párrafo","parte","pasar","paseo","pasión","paso","pasta","pata","patio","patria","pausa","pauta","pavo","payaso","peatón","pecado","pecera","pecho","pedal","pedir","pegar","peine","pelar","peldaño","pelea","peligro","pellejo","pelo","peluca","pena","pensar","peñón","peón","peor","pepino","pequeño","pera","percha","perder","pereza","perfil","perico","perla","permiso","perro","persona","pesa","pesca","pésimo","pestaña","pétalo","petróleo","pez","pezuña","picar","pichón","pie","piedra","pierna","pieza","pijama","pilar","piloto","pimienta","pino","pintor","pinza","piña","piojo","pipa","pirata","pisar","piscina","piso","pista","pitón","pizca","placa","plan","plata","playa","plaza","pleito","pleno","plomo","pluma","plural","pobre","poco","poder","podio","poema","poesía","poeta","polen","policía","pollo","polvo","pomada","pomelo","pomo","pompa","poner","porción","portal","posada","poseer","posible","poste","potencia","potro","pozo","prado","precoz","pregunta","premio","prensa","preso","previo","primo","príncipe","prisión","privar","proa","probar","proceso","producto","proeza","profesor","programa","prole","promesa","pronto","propio","próximo","prueba","público","puchero","pudor","pueblo","puerta","puesto","pulga","pulir","pulmón","pulpo","pulso","puma","punto","puñal","puño","pupa","pupila","puré","quedar","queja","quemar","querer","queso","quieto","química","quince","quitar","rábano","rabia","rabo","ración","radical","raíz","rama","rampa","rancho","rango","rapaz","rápido","rapto","rasgo","raspa","rato","rayo","raza","razón","reacción","realidad","rebaño","rebote","recaer","receta","rechazo","recoger","recreo","recto","recurso","red","redondo","reducir","reflejo","reforma","refrán","refugio","regalo","regir","regla","regreso","rehén","reino","reír","reja","relato","relevo","relieve","relleno","reloj","remar","remedio","remo","rencor","rendir","renta","reparto","repetir","reposo","reptil","res","rescate","resina","respeto","resto","resumen","retiro","retorno","retrato","reunir","revés","revista","rey","rezar","rico","riego","rienda","riesgo","rifa","rígido","rigor","rincón","riñón","río","riqueza","risa","ritmo","rito","rizo","roble","roce","rociar","rodar","rodeo","rodilla","roer","rojizo","rojo","romero","romper","ron","ronco","ronda","ropa","ropero","rosa","rosca","rostro","rotar","rubí","rubor","rudo","rueda","rugir","ruido","ruina","ruleta","rulo","rumbo","rumor","ruptura","ruta","rutina","sábado","saber","sabio","sable","sacar","sagaz","sagrado","sala","saldo","salero","salir","salmón","salón","salsa","salto","salud","salvar","samba","sanción","sandía","sanear","sangre","sanidad","sano","santo","sapo","saque","sardina","sartén","sastre","satán","sauna","saxofón","sección","seco","secreto","secta","sed","seguir","seis","sello","selva","semana","semilla","senda","sensor","señal","señor","separar","sepia","sequía","ser","serie","sermón","servir","sesenta","sesión","seta","setenta","severo","sexo","sexto","sidra","siesta","siete","siglo","signo","sílaba","silbar","silencio","silla","símbolo","simio","sirena","sistema","sitio","situar","sobre","socio","sodio","sol","solapa","soldado","soledad","sólido","soltar","solución","sombra","sondeo","sonido","sonoro","sonrisa","sopa","soplar","soporte","sordo","sorpresa","sorteo","sostén","sótano","suave","subir","suceso","sudor","suegra","suelo","sueño","suerte","sufrir","sujeto","sultán","sumar","superar","suplir","suponer","supremo","sur","surco","sureño","surgir","susto","sutil","tabaco","tabique","tabla","tabú","taco","tacto","tajo","talar","talco","talento","talla","talón","tamaño","tambor","tango","tanque","tapa","tapete","tapia","tapón","taquilla","tarde","tarea","tarifa","tarjeta","tarot","tarro","tarta","tatuaje","tauro","taza","tazón","teatro","techo","tecla","técnica","tejado","tejer","tejido","tela","teléfono","tema","temor","templo","tenaz","tender","tener","tenis","tenso","teoría","terapia","terco","término","ternura","terror","tesis","tesoro","testigo","tetera","texto","tez","tibio","tiburón","tiempo","tienda","tierra","tieso","tigre","tijera","tilde","timbre","tímido","timo","tinta","tío","típico","tipo","tira","tirón","titán","títere","título","tiza","toalla","tobillo","tocar","tocino","todo","toga","toldo","tomar","tono","tonto","topar","tope","toque","tórax","torero","tormenta","torneo","toro","torpedo","torre","torso","tortuga","tos","tosco","toser","tóxico","trabajo","tractor","traer","tráfico","trago","traje","tramo","trance","trato","trauma","trazar","trébol","tregua","treinta","tren","trepar","tres","tribu","trigo","tripa","triste","triunfo","trofeo","trompa","tronco","tropa","trote","trozo","truco","trueno","trufa","tubería","tubo","tuerto","tumba","tumor","túnel","túnica","turbina","turismo","turno","tutor","ubicar","úlcera","umbral","unidad","unir","universo","uno","untar","uña","urbano","urbe","urgente","urna","usar","usuario","útil","utopía","uva","vaca","vacío","vacuna","vagar","vago","vaina","vajilla","vale","válido","valle","valor","válvula","vampiro","vara","variar","varón","vaso","vecino","vector","vehículo","veinte","vejez","vela","velero","veloz","vena","vencer","venda","veneno","vengar","venir","venta","venus","ver","verano","verbo","verde","vereda","verja","verso","verter","vía","viaje","vibrar","vicio","víctima","vida","vídeo","vidrio","viejo","viernes","vigor","vil","villa","vinagre","vino","viñedo","violín","viral","virgo","virtud","visor","víspera","vista","vitamina","viudo","vivaz","vivero","vivir","vivo","volcán","volumen","volver","voraz","votar","voto","voz","vuelo","vulgar","yacer","yate","yegua","yema","yerno","yeso","yodo","yoga","yogur","zafiro","zanja","zapato","zarza","zona","zorro","zumo","zurdo"]["abajur","abaküs","abartı","abdal","abdest","abiye","abluka","abone","absorbe","absürt","acayip","acele","acemi","açıkgöz","adalet","adam","adezyon","adisyon","adliye","adres","afacan","afili","afiş","afiyet","aforizm","afra","ağaç","ağır","ahbap","ahkam","ahlak","ahtapot","aidat","aile","ajan","akademi","akarsu","akbaş","akciğer","akdeniz","akıbet","akıl","akıntı","akide","akrep","akrobasi","aksiyon","akşam","aktif","aktör","aktris","akustik","alaca","albüm","alçak","aldanma","aleni","alet","alfabe","algılama","alıngan","alkış","alkol","alpay","alperen","altın","altüst","altyapı","alyuvar","amade","amatör","amazon","ambalaj","amblem","ambulans","amca","amel","amigo","amir","amiyane","amorti","ampul","anadolu","anahtar","anakonda","anaokul","anapara","anarşi","anatomi","anayasa","anekdot","anestezi","angaje","anka","anket","anlamlı","anne","anomali","anonim","anten","antlaşma","apse","araba","aracı","araf","arbede","arda","arefe","arena","argo","argüman","arkadaş","armoni","aroma","arsa","arsız","artı","artist","aruz","asansör","asayiş","asfalt","asgari","asil","asker","askı","aslan","asosyal","astsubay","asya","aşçı","aşırı","aşure","atabey","ataman","ateş","atmaca","atmosfer","atom","atölye","avcı","avdet","avize","avlu","avokado","avrupa","avukat","ayaz","ayçiçeği","aydın","aygıt","ayna","ayran","ayrıntı","azim","baca","bagaj","bağlantı","bahadır","bahçe","baki","bakkal","baklava","bakteri","balçık","balina","balo","balta","bant","banyo","bardak","barış","başbuğ","başıboş","başkan","başlık","bavul","bayındır","baykuş","bazlama","bedel","begüm","bekçi","bekle","belge","belki","bencil","benek","bengi","benzer","berjer","berk","bermuda","berrak","beşik","beton","beyin","beyoğlu","bıçak","biberiye","bidon","biftek","bihaber","bikini","bilezik","bilinç","bilye","bina","binbaşı","binyıl","bisiklet","bisküvi","bitki","bizzat","bodrum","boğaz","bohça","bolero","boncuk","bonfile","borsa","boru","bostan","boşboğaz","botanik","boya","boykot","boynuz","bozgun","bozkır","bölüm","börek","buçuk","bugün","buğday","buhar","buhran","bulvar","buram","burçak","burs","burun","butik","buzdağı","buzkıran","bücür","büfe","bülten","bütçe","bütün","büyük","cacık","cadı","cahil","cambaz","canhıraş","casus","cazibe","cehalet","cehennem","ceket","cemre","cenin","cennet","cepken","cerrah","cesur","cetvel","cevher","ceylan","cılız","cıva","cilt","cisim","ciyak","coğrafya","cömert","cumba","cüzdan","çabucak","çadır","çağdaş","çağlayan","çağrı","çakmak","çalışkan","çamaşır","çapa","çaput","çarık","çarpan","çarşaf","çayhane","çekirdek","çelebi","çember","çenet","çengel","çerçeve","çerez","çeşit","çeşme","çete","çevre","çeyiz","çeyrek","çığır","çılgın","çıngırak","çift","çiğdem","çikolata","çilek","çimen","çivi","çoban","çocuk","çokgen","çomak","çorba","çözelti","çubuk","çukur","çuval","çürük","dağbaşı","dağılım","daktilo","daldırış","dalga","dalkavuk","damak","damıtma","damla","dana","dandik","danışman","daniska","dantel","dargeçit","darphane","davet","dayı","defter","değer","değirmen","dehşet","delgeç","demir","deneyim","denge","depo","deprem","derdest","dere","derhal","derman","dernek","derviş","desen","destan","dışarı","dışbükey","dijital","dikbaşlı","dilekçe","dimağ","dinamik","dindar","dinleme","dinozor","dipçik","dipnot","direniş","dirsek","disiplin","disk","divriği","dizüstü","dobra","dodurga","doğalgaz","doktor","doküman","dolap","donanım","dondurma","donör","doruk","dosdoğru","dost","dosya","dozer","döküm","dönence","dörtyol","dövme","dram","dublaj","durum","duvak","duyarga","duyma","duyuru","düğme","düğüm","dükkan","dünür","düpedüz","dürbün","düşünür","düzayak","düzeltme","ebeveyn","ebru","ecel","ecnebi","ecza","edat","edilgen","efendi","efor","efsane","egemen","egzersiz","eğrelti","ekarte","ekip","eklem","ekmek","ekol","ekonomi","ekose","ekran","ekvator","elaman","elastik","elbet","elbise","elçi","eldiven","elebaşı","eleştiri","elma","eloğlu","elveda","emare","emekçi","emisyon","emniyet","empati","emsal","emzik","endüstri","enerji","engebe","engin","enişte","enkaz","entari","entegre","entrika","enzim","erdem","ergen","erguvan","erkek","erozyon","ertesi","erzak","esaret","esenlik","eser","eski","esnek","eşarp","eşofman","eşraf","eşya","eşzaman","etik","etken","etkinlik","etüt","evet","evire","evrak","evrim","eyalet","eyvah","ezber","fabrika","fanatik","fanus","fason","fasulye","fatih","fatura","fauna","favori","fayans","fayton","fazıl","fazilet","federal","felsefe","fener","feribot","fersah","fesih","festival","feveran","feza","fıçı","fıldır","fındık","fırça","fırsat","fırtına","fıtık","fidan","fidye","figür","fihrist","fikir","fildişi","filo","filtre","fincan","firuze","fitil","fiyaka","fizik","flaş","flüt","fosil","fren","fukara","futbol","garabet","gariban","garnitür","gazi","gece","gedik","gelenek","gelin","gemi","genç","geniş","geometri","gerçek","gevrek","gezegen","gezgin","geziyolu","gıcık","gıda","gıybet","girdap","girişim","gitar","giyecek","giysi","gizem","gofret","goril","göbek","göçebe","göğüs","gökdelen","gökmen","gökyüzü","gölge","gömlek","gönül","görenek","görkemli","görsel","gösteri","gövde","gözaltı","gözcü","gözdağı","gözleme","gözyaşı","grup","gurbet","gusül","gübre","güfte","gümüş","günaydın","güncel","gündüz","güneş","günyüzü","gürbüz","güvercin","güzel","haber","hacamat","hacim","hademe","hafız","hafriyat","hafta","hakan","hakem","hakikat","haksever","halı","hançer","hane","hangar","hapis","hapşırık","harf","haseki","hasret","hatun","havuç","haylaz","haysiyet","hayvan","hedef","hektar","hemen","hemfikir","hendek","hepsi","hergele","herhangi","hesap","heyecan","heykel","hezimet","hıçkırık","hızölçer","hicviye","hikaye","hikmet","hile","hisse","hobi","hoca","horlama","hormon","hoşbeş","hoşgörü","hoyrat","hörgüç","höyük","hudut","hukuk","hunhar","hurda","huysuz","huzur","hücum","hükümet","hünkar","hüviyet","ırmak","ısıölçer","ısıtıcı","ıspanak","ısrar","ışıldak","ızdırap","ızgara","ibadet","icat","içbükey","içecek","içgüdü","içsel","idman","iftihar","iğne","ihanet","ihbar","ihdas","ihmal","ihracat","ihsan","ikilem","ikindi","ikircik","iklim","iksir","iktibas","ilaç","ilçe","ileri","iletişim","ilgi","ilhak","ilkbahar","ilkokul","ilmek","imkan","imleç","imsak","imtihan","imza","ince","inkar","inşa","ipek","ipucu","irade","irfan","irmik","isabet","iskele","israf","isyan","işçi","işgal","işgüzar","işlem","itibar","itiraf","ivedi","ivme","iyileşme","iyimser","izbandut","izci","izdiham","izin","jakoben","jandarma","jargon","kabadayı","kablo","kabus","kaçamak","kadeh","kadın","kadraj","kafa","kafkas","kağıt","kağnı","kahkaha","kahraman","kahvaltı","kakül","kaldırım","kale","kalibre","kalkan","kalpak","kamış","kamyon","kanat","kandaş","kanepe","kanser","kanun","kaos","kapı","kaplıca","kaptan","karanlık","kardeş","karga","karınca","karmaşa","karşıt","kasırga","kask","kasvet","katkı","katman","kavram","kaygan","kaynakça","kayyum","kedi","kehanet","kekik","kelebek","kenar","kerkenez","kerpiç","kesirli","kesmece","kestane","keşkek","ketçap","keyfiyet","kıble","kıdemli","kılavuz","kılçık","kılıf","kıraç","kırmızı","kırsal","kısayol","kısım","kıskanç","kısmet","kışla","kıvanç","kıvılcım","kıvrık","kıyafet","kıymetli","kızak","kızılcık","kibar","kinaye","kira","kiremit","kirli","kirpik","kişisel","kitap","koçbaşı","kodaman","koğuş","kokteyl","kolaycı","kolbastı","kolonya","koltuk","kolye","kombine","komedyen","komiser","komposto","komşu","komuta","konak","konfor","koni","konsül","kopya","korkusuz","korna","korse","korunak","korvet","kostüm","koşul","koyu","kozmik","köfte","kökensel","köprücük","köpük","kördüğüm","körfez","köstebek","köşegen","kötü","kravat","kriter","kuantum","kudurma","kuluçka","kulübe","kumanya","kumbara","kumlu","kumpir","kumral","kundura","kupa","kupkuru","kuramsal","kurbağa","kurdele","kurgu","kurmay","kurşun","kurtuluş","kurultay","kurye","kusursuz","kuşak","kuşbaşı","kuşkulu","kutlama","kutsal","kutup","kuver","kuyruk","kuzey","kuzgun","küçük","külçe","külfet","külliye","kültürel","kümes","künefe","küresel","kütle","lahana","lahmacun","lamba","lansman","lavaş","layık","leğen","levent","leziz","lezzet","lider","likide","liman","liste","litre","liyakat","lodos","lokanta","lokman","lokum","lunapark","lütfen","lüzum","nokta","mabet","macera","macun","madalya","madde","madem","mağara","mağdur","mağfiret","mağlup","mahalle","mahcup","mahir","mahkeme","mahlas","mahrum","mahsul","makas","makbuz","makine","makro","maksat","makul","maliye","manav","mangal","manidar","manken","mantık","manzara","mareşal","margarin","marifet","market","marmelat","masaüstü","masmavi","masraf","masum","matah","materyal","matrak","maval","mavra","maydanoz","mayhoş","maytap","mazbata","mazeret","mazlum","mazot","mazur","meblağ","mebus","mecaz","mecbur","meclis","mecmua","mecnun","meçhul","medeni","mehtap","mekanik","melodi","meltem","memur","mendil","menekşe","menteşe","meraklı","mercek","merdiven","merhaba","merinos","merkez","mermi","mert","mesafe","mesele","mesken","meslek","meşale","meşgul","meşhur","metafor","metin","metre","mevcut","mevkidaş","meydan","meyil","meyve","meziyet","mezun","mıknatıs","mısra","mızıka","miğfer","mihrak","mikrofon","miktar","milat","milli","mimar","minare","mineral","minik","minyon","mirliva","misafir","miskin","miting","miyop","mizah","mobilya","model","monitör","morötesi","motive","motor","mozaik","muavin","mucize","muhafız","muhteşem","mukayese","mumya","musluk","muşamba","mutabık","mutfak","mutlu","muzaffer","muzdarip","mübarek","mücadele","müdür","müfredat","müftü","mühendis","mühim","mühlet","mükemmel","mülk","mümkün","mümtaz","müsrif","müstesna","müşahit","müşteri","mütercim","müthiş","müze","müzik","nabız","nadas","nadir","nahoş","nakarat","nakış","nalbur","namlu","namus","nankör","nargile","narkoz","nasıl","nasip","naylon","nazar","nazım","nazik","neden","nefes","negatif","neon","neptün","nerede","nesil","nesnel","neşeli","netice","nevresim","neyse","neyzen","nezaket","nezih","nezle","nicel","nilüfer","nimet","nisan","nispet","nitekim","nizam","nohut","noksan","normal","nostalji","noter","nöbet","numara","numune","nutuk","nüfus","obabaşı","obez","obje","ocak","odun","ofansif","ofis","oğlak","oğuz","okçu","oklava","oksijen","okul","okumuş","okutman","okuyucu","okyanus","olağan","olanak","olası","olay","olgun","olimpik","olumlu","omlet","omurga","onarım","onursal","opera","optik","oral","orantı","ordu","organik","orijin","orkide","orman","orta","oruç","otağ","otantik","otel","otoban","otogar","otomobil","otonom","otopark","otorite","otoyol","oturum","oyuk","oyuncak","ozan","ödeme","ödenek","ödev","ödül","ödünç","öfke","öğlen","öğrenci","öğün","öğütücü","öksürük","ölçme","ölçü","ölümsüz","ömür","önayak","öncü","önder","önem","önerge","öngörü","önlük","önsezi","öpücük","ördek","örgü","örtbas","örtme","örtü","örümcek","örüntü","öteberi","öteki","övünç","öykü","öyleyse","özçekim","özdeyiş","özel","özenti","özerk","özgürlük","özlem","özlü","özne","özsever","özümseme","özür","özveri","pabuç","padişah","palamut","palmiye","palto","palyaço","pamuk","panayır","pancar","panda","panel","panik","panjur","pankart","pano","pansuman","pantolon","panzehir","papatya","papyon","paraşüt","parça","pardösü","parfüm","parıltı","parkur","parmak","parodi","parsel","partner","pasaport","pasif","paskalya","pastırma","paşa","patates","paten","patika","patlıcan","patolog","patron","payanda","paydaş","payidar","paylaşma","paytak","peçete","pedal","peder","pehlivan","pekala","pekmez","pelerin","pelikan","pelüş","pembe","pena","pencere","pense","perçin","perde","pergel","perişan","peron","personel","perşembe","peruk","pervane","pespaye","pestil","peşin","petek","petrol","petunya","peynir","peyzaj","pınar","pırasa","pırlanta","pide","pikap","piknik","pilav","piliç","pilot","pipet","pipo","piramit","pirinç","pirzola","pist","pişik","pişman","piyasa","piyes","plaj","plaket","planlama","platform","plazma","podyum","poğaça","polat","polen","politika","pompa","popüler","porselen","portakal","posa","poster","poşet","poyraz","pozitif","pranga","pratik","prenses","prim","problem","profil","program","proje","protokol","prova","puan","pudra","pusula","püre","pürüz","püstül","püsür","racon","radar","radikal","radyo","rafadan","rafine","rağbet","rahat","rahle","rakam","raket","rakip","rakun","ralli","rampa","randevu","ranza","rapor","rastgele","rasyonel","razı","realite","reçine","refah","referans","refik","reform","rehber","rehin","reis","rekabet","reklam","rekor","rektör","renk","resim","resmen","restoran","retorik","revaç","revize","reyon","rezalet","rezerv","rezil","rıhtım","rıza","ritim","ritüel","rivayet","robot","roman","rota","rozet","röportaj","rötar","ruble","ruhban","ruhsat","rulet","rulo","runik","rutin","rutubet","rüşvet","rütbe","rüya","rüzgar","sabah","sabıka","sabit","sabun","saçma","sade","sadık","safahat","safdil","safkan","sağanak","sağduyu","sağlam","saha","sahiden","sahne","sakal","sakız","sakin","saklama","saksağan","salamura","salça","salgı","salınım","salkım","salon","saltanat","sanatçı","sancak","sandalye","saniye","saplantı","sapsız","saray","sarışın","sarkık","sarmaşık","satır","savaşım","savunma","saydam","sayfa","saygın","sayısal","sebep","seçenek","seçim","seçkin","seçmen","seda","sedir","sedye","sefer","sehpa","sekizgen","selektör","selvi","semavi","sembol","seminer","senaryo","sendika","senkron","sensör","sentez","sepet","seramik","serbest","serdar","seremoni","sergi","serhat","serin","sermaye","serpuş","sersem","serüven","servis","sesli","sesteş","sevap","seviye","seyahat","seyirci","sezon","sıcak","sıfat","sıhhi","sınanma","sınır","sıradan","sırdaş","sırma","sırtüstü","sızgıt","siftah","sigorta","sihirbaz","silah","silecek","silindir","simetri","simge","simit","sincap","sindirim","sinema","sinirli","sipariş","sirke","siroz","sistem","sivilce","siyasi","slogan","soba","sofra","soğuk","sohbet","sokak","solfej","solunum","somut","sonbahar","sonraki","sonsuz","sorunsuz","sosyete","soyağacı","soydaş","soygun","soytarı","söğüş","sömürge","sönük","söylem","sözcük","sözde","spatula","spektrum","spiker","spiral","sponsor","sporcu","sprey","stabil","statü","stok","stopaj","strateji","subay","sucuk","suçüstü","suhulet","sulama","sungur","sunucu","surat","susam","suskun","sükse","sükut","sülale","sünger","süpürge","sürahi","süreç","sürgün","sürüm","süsleme","sütanne","sütlaç","sütun","süvari","şahane","şahbaz","şahit","şahsiyet","şakıma","şaklaban","şakrak","şamar","şampiyon","şanslı","şantiye","şapka","şarkıcı","şartname","şaşırma","şaşkın","şatafat","şayet","şebeke","şefkat","şeftali","şehir","şehvet","şeker","şekil","şelale","şema","şemsiye","şerbet","şeref","şerit","şımarık","şıpıdık","şifre","şimdi","şimşek","şipşak","şirin","şişe","şişirme","şofben","şöhret","şölen","şüphe","tabaka","tabela","tabure","tadilat","taharet","tahıl","tahkim","tahlil","tahmin","tahrifat","tahsilat","tahta","taklit","takoz","taksici","taktik","takvim","talebe","talip","tamamen","tamirci","tampon","tamtakır","tandır","tanecik","tanıtım","tanrı","tansiyon","tapan","tapınak","taptaze","tapu","tarafgir","tarhana","tarım","tarih","tarla","tartak","tarumar","tasarım","tasdik","taslak","tastamam","taşeron","taşınmaz","taşra","tatava","tatbikat","tatil","tatlı","tavsiye","tavşan","tavuk","taze","taziye","tazminat","tebeşir","tebrik","tecrübe","teçhizat","tedarik","tedbir","teftiş","teğet","teğmen","tehdit","tehlike","tekdüze","tekerlek","tekme","teknik","tekrar","telef","telsiz","telve","temas","tembel","temiz","temkin","tempo","temsilci","tendon","teneke","tenha","tenkit","tepegöz","tepki","terazi","terbiye","tercih","tereyağı","terfi","terim","terminal","tersane","tertip","tesadüf","tescil","tesir","teslimat","tespit","testere","teşekkür","teşhir","teşrif","teşvik","teyze","tezahür","tezgah","tıbbi","tıkaç","tıkışık","tıknaz","tılsım","tıpkı","tıraş","tırışka","tırmanış","tırnak","tırpan","tıslama","ticaret","tilki","tiryaki","titreşim","tohum","tokat","tolere","tomar","tombak","tomurcuk","topaç","toplum","toprak","toptan","toraman","torpido","tortu","tosbağa","toynak","tören","trafik","trajedi","tramvay","transfer","tribün","triko","tugay","tuğla","tuğrul","tuhaf","tulumba","tunç","turan","turkuaz","turnusol","turşu","turuncu","tutanak","tutkal","tutsak","tutum","tuyuğ","tuzlu","tüccar","tüfek","tükenmez","tülbent","tümleç","tünel","türbin","türev","türk","tüzük","ucube","ucuz","uçak","uçurtma","ufuk","uğrak","uğur","ukala","ulaşım","ulema","ulus","ulvi","umursama","umut","unutkan","uslu","ustabaşı","ustura","usul","utangaç","uyanık","uyarı","uydu","uygar","uygulama","uykusuz","uysal","uyuşma","uzantı","uzay","uzgören","uzlaşma","uzman","uzun","ücra","ücret","üçbudak","üçgen","üçkağıt","üçleme","üfürük","ülke","ümit","üniforma","ünite","ünlem","üretken","ürün","üslup","üstel","üstün","üşengeç","üşüme","ütopya","üvey","üzengi","üzgün","üzüm","vagon","vaka","vakfiye","vakıf","vakit","vakum","vapur","varil","varlık","varsayım","varyemez","vasıta","vasiyet","vatandaş","vazife","vazo","veciz","vefa","vehim","veliaht","veresiye","verimli","verkaç","vernik","vertigo","vesait","vesika","vestiyer","veznedar","vicdan","vilayet","virane","virgül","vişne","vites","vokal","volkan","vurma","vurucu","vücut","yabancı","yabgu","yağış","yağlı","yağmur","yakamoz","yakın","yaklaşık","yalçın","yalıtım","yaman","yanardağ","yangın","yanıt","yankı","yanlış","yansıma","yapay","yapboz","yapımcı","yaprak","yaratık","yarbay","yardım","yargıç","yarıçap","yasemin","yastık","yaşam","yatak","yatırım","yavru","yaygara","yayıncı","yayla","yazılım","yekpare","yekvücut","yelkovan","yelpaze","yemek","yemiş","yengeç","yeniçeri","yeraltı","yerküre","yerleşke","yeryüzü","yeşil","yetenek","yetkili","yığınak","yıkama","yılbaşı","yıldırım","yılkı","yılmaz","yırtıcı","yiğit","yoğurt","yokuş","yolcu","yoldaş","yolgeçen","yolkesen","yolüstü","yordam","yorgan","yorumcu","yosun","yöndeş","yönetim","yönlü","yöntem","yöresel","yörünge","yufka","yukarı","yumruk","yumurta","yuvarlak","yücelme","yükçeker","yüklem","yüksek","yürek","yürütme","yüzde","yüzeysel","yüzgeç","yüzüstü","yüzyıl","zabıta","zafer","zahmet","zambak","zaptiye","zarafet","zaruret","zeka","zekice","zemberek","zemin","zencefil","zeplin","zeytin","zıbın","zılgıt","zımbırtı","zımpara","zıpkın","zigon","zihinsel","zihniyet","zincir","zindan","zirzop","ziyaret","ziynet","zoraki","zorlu","zorunlu","züğürt","zümre"]const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const b4a = require('b4a')

// https://en.wikipedia.org/wiki/Merkle_tree#Second_preimage_attack
const LEAF_TYPE = b4a.from([0])
const PARENT_TYPE = b4a.from([1])
const ROOT_TYPE = b4a.from([2])

const HYPERCORE = b4a.from('hypercore')

exports.keyPair = function (seed) {
  // key pairs might stay around for a while, so better not to use a default slab to avoid retaining it completely
  const slab = b4a.allocUnsafeSlow(
    sodium.crypto_sign_PUBLICKEYBYTES + sodium.crypto_sign_SECRETKEYBYTES
  )
  const publicKey = slab.subarray(0, sodium.crypto_sign_PUBLICKEYBYTES)
  const secretKey = slab.subarray(sodium.crypto_sign_PUBLICKEYBYTES)

  if (seed) sodium.crypto_sign_seed_keypair(publicKey, secretKey, seed)
  else sodium.crypto_sign_keypair(publicKey, secretKey)

  return {
    publicKey,
    secretKey
  }
}

exports.validateKeyPair = function (keyPair) {
  const pk = b4a.allocUnsafe(sodium.crypto_sign_PUBLICKEYBYTES)
  sodium.crypto_sign_ed25519_sk_to_pk(pk, keyPair.secretKey)
  return b4a.equals(pk, keyPair.publicKey)
}

exports.sign = function (message, secretKey) {
  // Dedicated slab for the signature, to avoid retaining unneeded mem and for security
  const signature = b4a.allocUnsafeSlow(sodium.crypto_sign_BYTES)
  sodium.crypto_sign_detached(signature, message, secretKey)
  return signature
}

exports.verify = function (message, signature, publicKey) {
  if (signature.byteLength !== sodium.crypto_sign_BYTES) return false
  if (publicKey.byteLength !== sodium.crypto_sign_PUBLICKEYBYTES) return false
  return sodium.crypto_sign_verify_detached(signature, message, publicKey)
}

exports.encrypt = function (message, publicKey) {
  const ciphertext = b4a.alloc(message.byteLength + sodium.crypto_box_SEALBYTES)
  sodium.crypto_box_seal(ciphertext, message, publicKey)
  return ciphertext
}

exports.decrypt = function (ciphertext, keyPair) {
  if (ciphertext.byteLength < sodium.crypto_box_SEALBYTES) return null

  const plaintext = b4a.alloc(ciphertext.byteLength - sodium.crypto_box_SEALBYTES)

  if (!sodium.crypto_box_seal_open(plaintext, ciphertext, keyPair.publicKey, keyPair.secretKey)) {
    return null
  }

  return plaintext
}

exports.encryptionKeyPair = function (seed) {
  const publicKey = b4a.alloc(sodium.crypto_box_PUBLICKEYBYTES)
  const secretKey = b4a.alloc(sodium.crypto_box_SECRETKEYBYTES)

  if (seed) {
    sodium.crypto_box_seed_keypair(publicKey, secretKey, seed)
  } else {
    sodium.crypto_box_keypair(publicKey, secretKey)
  }

  return {
    publicKey,
    secretKey
  }
}

exports.data = function (data) {
  const out = b4a.allocUnsafe(32)

  sodium.crypto_generichash_batch(out, [LEAF_TYPE, c.encode(c.uint64, data.byteLength), data])

  return out
}

exports.parent = function (a, b) {
  if (a.index > b.index) {
    const tmp = a
    a = b
    b = tmp
  }

  const out = b4a.allocUnsafe(32)

  sodium.crypto_generichash_batch(out, [
    PARENT_TYPE,
    c.encode(c.uint64, a.size + b.size),
    a.hash,
    b.hash
  ])

  return out
}

exports.tree = function (roots, out) {
  const buffers = new Array(3 * roots.length + 1)
  let j = 0

  buffers[j++] = ROOT_TYPE

  for (let i = 0; i < roots.length; i++) {
    const r = roots[i]
    buffers[j++] = r.hash
    buffers[j++] = c.encode(c.uint64, r.index)
    buffers[j++] = c.encode(c.uint64, r.size)
  }

  if (!out) out = b4a.allocUnsafe(32)
  sodium.crypto_generichash_batch(out, buffers)
  return out
}

exports.hash = function (data, out) {
  if (!out) out = b4a.allocUnsafe(32)
  if (!Array.isArray(data)) data = [data]

  sodium.crypto_generichash_batch(out, data)

  return out
}

exports.randomBytes = function (n) {
  const buf = b4a.allocUnsafe(n)
  sodium.randombytes_buf(buf)
  return buf
}

exports.discoveryKey = function (key) {
  if (!key || key.byteLength !== 32) throw new Error('Must pass a 32 byte buffer')
  // Discovery keys might stay around for a while, so better not to use slab memory (for better gc)
  const digest = b4a.allocUnsafeSlow(32)
  sodium.crypto_generichash(digest, HYPERCORE, key)
  return digest
}

if (sodium.sodium_free) {
  exports.free = function (secureBuf) {
    if (secureBuf.secure) sodium.sodium_free(secureBuf)
  }
} else {
  exports.free = function () {}
}

exports.namespace = function (name, count) {
  const ids = typeof count === 'number' ? range(count) : count

  // Namespaces are long-lived, so better to use a dedicated slab
  const buf = b4a.allocUnsafeSlow(32 * ids.length)

  const list = new Array(ids.length)

  // ns is ephemeral, so default slab
  const ns = b4a.allocUnsafe(33)
  sodium.crypto_generichash(ns.subarray(0, 32), typeof name === 'string' ? b4a.from(name) : name)

  for (let i = 0; i < list.length; i++) {
    list[i] = buf.subarray(32 * i, 32 * i + 32)
    ns[32] = ids[i]
    sodium.crypto_generichash(list[i], ns)
  }

  return list
}

function range(count) {
  const arr = new Array(count)
  for (let i = 0; i < count; i++) arr[i] = i
  return arr
}
{
  "name": "hypercore-crypto",
  "version": "3.7.0",
  "description": "The crypto primitives used in hypercore, extracted into a separate module",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.6.6",
    "compact-encoding": "^3.0.0",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "brittle": "^3.5.0",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/hypercore-crypto.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/hypercore-crypto/issues"
  },
  "homepage": "https://github.com/mafintosh/hypercore-crypto"
}
const c = require('compact-encoding')
const b4a = require('b4a')

const KeyChain = require('./lib/keychain')
const { sign, verify, hash } = require('./lib/crypto')

const {
  ProofEncoding,
  AttestedData,
  AttestedDevice,
  ReceiptEncoding
} = require('./lib/encoding')

const PROOF_VERSION = 1
const KEET_TYPE = 5338

const NS_PROFILE_DISC_ENC = hash(b4a.from('profile discovery'))

module.exports = class IdentityKey {
  constructor (keyChain) {
    this.keyChain = keyChain

    this.identityKeyPair = this.keyChain.get(identityKeyPath(0))
    this.profileDiscoveryKeyPair = this.keyChain.get(discoveryCorePath(0))
  }

  static generateMnemonic () {
    return KeyChain.generateMnemonic()
  }

  static deriveSeed (mnemonic) {
    return KeyChain.deriveSeed(mnemonic)
  }

  get identityPublicKey () {
    return this.identityKeyPair.publicKey
  }

  get profileDiscoveryPublicKey () {
    return this.profileDiscoveryKeyPair.publicKey
  }

  getProfileDiscoveryEncryptionKey () {
    return this.keyChain.getSymmetricKey(encryptionKeyPath(NS_PROFILE_DISC_ENC))
  }

  getEncryptionKey (profileKey) {
    return this.keyChain.getSymmetricKey(encryptionKeyPath(profileKey))
  }

  bootstrap (device) {
    return IdentityKey.bootstrap({ identity: this.identityKeyPair }, device)
  }

  clear () {
    this.keyChain.clear()
    this.identityKeyPair.secretKey.fill(0)
    this.profileDiscoveryKeyPair.secretKey.fill(0)
  }

  static async bootstrap ({ identity, seed, mnemonic }, device) {
    if (!identity) {
      const identityPath = identityKeyPath(0) // accountIndex unused for now
      identity = await KeyChain.from({ seed, mnemonic }, identityPath)
    }

    const proof = {
      version: PROOF_VERSION,
      epoch: Date.now(),
      identity: identity.publicKey,
      chain: []
    }

    return IdentityKey.attestDevice(device, identity, proof)
  }

  static attestDevice (publicKey, parent, proof) {
    if (!proof) return IdentityKey.bootstrap({ identity: parent }, publicKey)

    if (b4a.isBuffer(proof)) {
      proof = c.decode(ProofEncoding, proof)
    }

    if (proof.version === 0) {
      throw new Error('Version 0 proofs are not supported')
    }

    const signable = c.encode(AttestedDevice, {
      epoch: proof.epoch,
      identity: proof.identity,
      device: publicKey
    })

    const signature = sign(signable, parent)

    proof.chain.push({ publicKey, signature })

    return c.encode(ProofEncoding, proof)
  }

  static attestData (attestedData, keyPair, proof) {
    if (attestedData === null) throw new Error('Data is not attestable')

    if (b4a.isBuffer(proof)) {
      proof = c.decode(ProofEncoding, proof)
    }

    if (proof && proof.version === 0) {
      throw new Error('Version 0 proofs are not supported')
    }

    if (!proof) {
      proof = {
        version: PROOF_VERSION,
        epoch: Date.now(),
        identity: keyPair.publicKey,
        chain: []
      }
    }

    const signable = c.encode(AttestedData, {
      epoch: proof.epoch,
      identity: proof.identity,
      data: hash(attestedData)
    })

    proof.data = { signature: sign(signable, keyPair) }

    return c.encode(ProofEncoding, proof)
  }

  static async from ({ seed, mnemonic }) {
    const keyChain = await KeyChain.from({ seed, mnemonic })

    return new IdentityKey(keyChain)
  }

  static verify (proof, attestedData, opts = {}) {
    if (b4a.isBuffer(proof)) {
      proof = c.decode(ProofEncoding, proof)
    }

    if (!validateProof(proof, attestedData, opts)) {
      return null
    }

    const { epoch, identity, chain } = proof

    const candidate = getLastKey(chain) || identity

    if (opts.expectedDevice) {
      if (!b4a.equals(candidate, opts.expectedDevice)) return null
    }

    let parent = identity

    // verify chain
    for (let i = 0; i < chain.length; i++) {
      const { publicKey, signature } = chain[i]

      const signable = c.encode(AttestedDevice, {
        epoch,
        identity,
        device: publicKey
      })

      if (!verify(signable, signature, parent)) {
        return null
      }

      parent = publicKey
    }

    if (proof.data) {
      const signable = c.encode(AttestedData, {
        epoch,
        identity,
        data: hash(attestedData)
      })

      if (!verify(signable, proof.data.signature, parent)) {
        return null
      }
    }

    const receipt = c.encode(ReceiptEncoding, { epoch })

    return {
      receipt,
      identityPublicKey: identity,
      devicePublicKey: candidate
    }
  }
}

function validateProof (proof, attestedData, opts = {}) {
  // version 0 is ignored
  if (proof.version === 0) return false

  // validate version
  if (proof.version > PROOF_VERSION) return false

  // verify epoch
  if (opts.receipt) {
    const { epoch } = c.decode(ReceiptEncoding, opts.receipt)
    if (proof.epoch < epoch) return false
  }

  // verify identity
  if (opts.expectedIdentity) {
    if (!b4a.equals(proof.identity, opts.expectedIdentity)) return false
  }

  return validateAttestedData(proof.data, attestedData)
}

function validateAttestedData (data, attestedData) {
  if (!data && attestedData) return false
  return true
}

function getLastKey (chain) {
  if (!chain.length) return null

  const last = chain[chain.length - 1]
  return last.publicKey
}

// slip48 derivations:
// https://github.com/satoshilabs/slips/blob/master/slip-0048.md

function keyPath (accountIndex, index) {
  // https://github.com/bitcoin/bips/blob/master/bip-0043.mediawiki
  const purpose = 48 // SLIP-48 wallet
  const role = 0 // owner

  return [purpose, KEET_TYPE, role, accountIndex, index]
}

// identityKey -> m/48'/keet'/0'/0'

function identityKeyPath (accountIndex) {
  return keyPath(accountIndex, 0)
}

// identityKey -> m/48'/keet'/0'/1'

function discoveryCorePath (accountIndex) {
  return keyPath(accountIndex, 1)
}

// slip21 derivations
// https://github.com/satoshilabs/slips/blob/master/slip-0021.md

function symmetricPath (...path) {
  const purpose = 'SLIP-0021' // SLIP-21 wallet
  const namespace = 'keet-identity-key' // keet

  return [purpose, namespace, ...path]
}

// encryptionKey  -> m/SLIP-10/keet-identity-key/account/"encryption key"

function encryptionKeyPath (profileKey) {
  return symmetricPath(b4a.toString(profileKey, 'hex'), 'encryption key')
}
const sodium = require('sodium-universal')
const b4a = require('b4a')

module.exports = {
  sign,
  verify,
  hash: blake2b
}

function sign (signable, keyPair) {
  const signature = b4a.alloc(sodium.crypto_sign_BYTES)
  sodium.crypto_sign_detached(signature, signable, keyPair.secretKey)

  return signature
}

function verify (signable, signature, publicKey) {
  return sodium.crypto_sign_verify_detached(signature, signable, publicKey)
}

function blake2b (data, output = b4a.alloc(32)) {
  sodium.crypto_generichash(output, data)
  return output
}
const c = require('compact-encoding')

const ATTESTED_DEVICE = 0
const ATTESTED_DATA = 1

const Epoch = {
  preencode (state, e) {
    c.uint64.preencode(state, Math.floor(e / 1000))
  },
  encode (state, e) {
    c.uint64.encode(state, Math.floor(e / 1000))
  },
  decode (state) {
    return c.uint64.decode(state) * 1000
  }
}

const AttestedDevice = {
  preencode (state, a) {
    c.uint8.preencode(state, ATTESTED_DEVICE)
    Epoch.preencode(state, a.epoch)
    c.fixed32.preencode(state, a.identity)
    c.fixed32.preencode(state, a.device)
  },
  encode (state, a) {
    c.uint8.encode(state, ATTESTED_DEVICE)
    Epoch.encode(state, a.epoch)
    c.fixed32.encode(state, a.identity)
    c.fixed32.encode(state, a.device)
  },
  decode (state) {
    throw new Error('Signed data should only be encoded')
  }
}

const AttestedData = {
  preencode (state, a) {
    c.uint8.preencode(state, ATTESTED_DATA)
    Epoch.preencode(state, a.epoch)
    c.fixed32.preencode(state, a.identity)
    c.fixed32.preencode(state, a.data)
  },
  encode (state, a) {
    c.uint8.encode(state, ATTESTED_DATA)
    Epoch.encode(state, a.epoch)
    c.fixed32.encode(state, a.identity)
    c.fixed32.encode(state, a.data)
  },
  decode (state) {
    throw new Error('Signed data should only be encoded')
  }
}

const DeviceAttestation = {
  preencode (state, a) {
    c.fixed32.preencode(state, a.publicKey)
    c.fixed64.preencode(state, a.signature)
  },
  encode (state, a) {
    c.fixed32.encode(state, a.publicKey)
    c.fixed64.encode(state, a.signature)
  },
  decode (state) {
    return {
      publicKey: c.fixed32.decode(state),
      signature: c.fixed64.decode(state)
    }
  }
}

const DeviceAttestationArray = c.array(DeviceAttestation)

const DataAttestation = {
  preencode (state, a) {
    c.fixed64.preencode(state, a.signature)
  },
  encode (state, a) {
    c.fixed64.encode(state, a.signature)
  },
  decode (state) {
    return {
      signature: c.fixed64.decode(state)
    }
  }
}

const ProofEncoding = {
  preencode (state, proof) {
    c.uint.preencode(state, proof.version)
    Epoch.preencode(state, proof.epoch)
    c.fixed32.preencode(state, proof.identity)
    DeviceAttestationArray.preencode(state, proof.chain)

    let flags = 0
    if (proof.data) flags |= 1
    c.uint.preencode(state, flags)

    if (proof.data) DataAttestation.preencode(state, proof.data)
  },
  encode (state, proof) {
    c.uint.encode(state, proof.version)
    Epoch.encode(state, proof.epoch)
    c.fixed32.encode(state, proof.identity)
    DeviceAttestationArray.encode(state, proof.chain)

    let flags = 0
    if (proof.data) flags |= 1
    c.uint.encode(state, flags)

    if (proof.data) DataAttestation.encode(state, proof.data)
  },
  decode (state) {
    const version = c.uint.decode(state)

    // ignore v0 proofs
    if (version === 0) {
      return {
        version: 0,
        epoch: 0,
        identity: null,
        chain: [],
        data: null
      }
    }

    const epoch = Epoch.decode(state)
    const identity = c.fixed32.decode(state)
    const chain = DeviceAttestationArray.decode(state)

    const flags = c.uint.decode(state)
    const data = flags & 1 ? DataAttestation.decode(state) : null

    return {
      version,
      epoch,
      identity,
      chain,
      data
    }
  }
}

const ReceiptEncoding = {
  preencode (state, receipt) {
    Epoch.preencode(state, receipt.epoch)
  },
  encode (state, receipt) {
    Epoch.encode(state, receipt.epoch)
  },
  decode (state) {
    return {
      epoch: Epoch.decode(state)
    }
  }
}

module.exports = {
  ATTESTED_DEVICE,
  ATTESTED_DATA,
  AttestedDevice,
  AttestedData,
  ProofEncoding,
  ReceiptEncoding
}
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const assert = require('nanoassert')
const b4a = require('b4a')
const { HMAC } = require('sodium-hmac')
const bip39 = require('bip39-mnemonic')

const { sign } = require('./crypto')

const MASTER_CHAIN_CODE = b4a.from('ed25519 seed')
const MASTER_SYMMETRIC_CODE = b4a.from('Symmetric key seed')

const HARDENED_OFFSET = 0x80000000

class KeyChain {
  constructor (seed) {
    this.seed = seed

    this._buffer = b4a.alloc(64)

    this.chainKey = this._buffer.subarray(0, 32)
    this.chainCode = this._buffer.subarray(32)

    this.publicKey = b4a.alloc(sodium.crypto_sign_PUBLICKEYBYTES)
    this.secretKey = b4a.alloc(sodium.crypto_sign_SECRETKEYBYTES)

    this._initialise()
  }

  static generateMnemonic () {
    return bip39.generateMnemonic()
  }

  static deriveSeed (mnemonic) {
    return bip39.mnemonicToSeed(mnemonic)
  }

  static async from ({ mnemonic, seed }, path) {
    assert(mnemonic || seed, 'No mnemonic or seed was passed.')

    if (!seed) seed = await KeyChain.deriveSeed(mnemonic)

    const key = new KeyChain(seed)

    if (!path) return key

    return key.get(path)
  }

  getSymmetricKey (path) {
    const buffer = b4a.alloc(64)

    const chainKey = buffer.subarray(0, 32)
    const key = buffer.subarray(32)

    HMAC.sha512(this.seed, MASTER_SYMMETRIC_CODE, buffer)

    for (const step of path) {
      const label = b4a.alloc(step.length + 1)
      b4a.write(label, step, 1, 'utf8')

      HMAC.sha512(label, chainKey, buffer)
    }

    return key
  }

  get isKeychain () {
    return true
  }

  _initialise () {
    HMAC.sha512(this.seed, MASTER_CHAIN_CODE, this._buffer)
    sodium.crypto_sign_seed_keypair(this.publicKey, this.secretKey, this.chainKey)
  }

  clear () {
    this.secretKey.fill(0)
    this.chainKey.fill(0)
    this.chainCode.fill(0)
  }

  get (path) {
    return this.derive(path)
  }

  sign (signable) {
    return sign(signable, this)
  }

  derive (path) {
    const buffer = b4a.from(this._buffer)

    const chainKey = buffer.subarray(0, 32)
    const chainCode = buffer.subarray(32)

    for (const step of path) {
      const index = ensureHardened(step) // hardened indices are >= 2^31
      HMAC.sha512(encodeDerivationData(chainKey, index), chainCode, buffer)
    }

    return createKeyPair(chainKey)
  }
}

module.exports = KeyChain

function createKeyPair (seed) {
  if (!seed) throw new Error('No seed provided')

  const publicKey = b4a.alloc(sodium.crypto_sign_PUBLICKEYBYTES)
  const secretKey = b4a.alloc(sodium.crypto_sign_SECRETKEYBYTES)

  sodium.crypto_sign_seed_keypair(publicKey, secretKey, seed)

  return {
    publicKey,
    secretKey
  }
}

function encodeDerivationData (key, step) {
  const state = { buffer: b4a.alloc(37), start: 0, end: 37 }

  c.uint8.encode(state, 0)
  c.fixed32.encode(state, key)
  state.buffer.writeUInt32BE(step, state.start)

  state.buffer[33] |= 0x80

  return state.buffer
}

function ensureHardened (n) {
  if (n >= HARDENED_OFFSET) return n
  return n + HARDENED_OFFSET
}
{
  "name": "keet-identity-key",
  "version": "3.2.0",
  "description": "Hierarchical Deterministic Keys for Keet Identities",
  "main": "index.js",
  "scripts": {
    "test": "standard && brittle test/*.js"
  },
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "devDependencies": {
    "brittle": "^3.3.2",
    "hypercore-crypto": "^3.4.0",
    "standard": "^17.1.0"
  },
  "dependencies": {
    "b4a": "^1.6.4",
    "bip39-mnemonic": "^2.2.0",
    "compact-encoding": "^3.0.0",
    "nanoassert": "^2.0.0",
    "sodium-hmac": "^2.0.1",
    "sodium-universal": "^5.0.1"
  },
  "files": [
    "lib/*"
  ],
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/keet-identity-key.git"
  },
  "bugs": {
    "url": "https://github.com/holepunchto/keet-identity-key/issues"
  },
  "homepage": "https://github.com/holepunchto/keet-identity-key#readme"
}
module.exports = assert

class AssertionError extends Error {}
AssertionError.prototype.name = 'AssertionError'

/**
 * Minimal assert function
 * @param  {any} t Value to check if falsy
 * @param  {string=} m Optional assertion error message
 * @throws {AssertionError}
 */
function assert (t, m) {
  if (!t) {
    var err = new AssertionError(m)
    if (Error.captureStackTrace) Error.captureStackTrace(err, assert)
    throw err
  }
}
{
  "name": "nanoassert",
  "version": "2.0.0",
  "description": "Nanoscale assertion module",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "tape": "^4.9.1"
  },
  "scripts": {
    "test": "tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/emilbayes/nanoassert.git"
  },
  "keywords": [
    "assert",
    "unassert",
    "power-assert",
    "tiny",
    "nano",
    "pico"
  ],
  "author": "Emil Bay <github@tixz.dk>",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/emilbayes/nanoassert/issues"
  },
  "homepage": "https://github.com/emilbayes/nanoassert#readme"
}
module.exports = require.addon.bind(require)
{
  "name": "require-addon",
  "version": "1.2.0",
  "description": "Import native addons across JavaScript runtimes",
  "exports": {
    "./package": "./package.json",
    ".": {
      "bare": "./lib/bare.js",
      "node": "./lib/node.js",
      "default": "./lib/default.js"
    }
  },
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    },
    "url": {
      "bare": "bare-url",
      "default": "url"
    }
  },
  "files": [
    "lib"
  ],
  "scripts": {
    "test": "npm run lint && npm run test:bare && npm run test:node",
    "test:bare": "bare test.js",
    "test:node": "node test.js",
    "lint": "prettier --check .",
    "format": "prettier --write ."
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/require-addon.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/require-addon/issues"
  },
  "homepage": "https://github.com/holepunchto/require-addon#readme",
  "engines": {
    "bare": ">=1.10.0"
  },
  "dependencies": {
    "bare-addon-resolve": "^1.3.0"
  },
  "devDependencies": {
    "bare-bundle": "^1.8.1",
    "bare-bundle-evaluate": "^1.1.0",
    "bare-fs": "^4.0.0",
    "bare-path": "^3.0.0",
    "bare-url": "^2.1.0",
    "brittle": "^3.7.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
const sodium = require('sodium-universal')

module.exports = {
  init: sodium.crypto_hash_sha256_init,
  update: sodium.crypto_hash_sha256_update,
  final: sodium.crypto_hash_sha256_final,
  BYTES: sodium.crypto_hash_sha256_BYTES,
  STATEBYTES: sodium.crypto_hash_sha256_STATEBYTES
}
const sodium = require('sodium-universal')

module.exports = {
  init: sodium.crypto_hash_sha512_init,
  update: sodium.crypto_hash_sha512_update,
  final: sodium.crypto_hash_sha512_final,
  BYTES: sodium.crypto_hash_sha512_BYTES,
  STATEBYTES: sodium.crypto_hash_sha512_STATEBYTES
}
const b4a = require('b4a')

const sha256 = require('./hash/sha256')
const sha512 = require('./hash/sha512')

class HMAC {
  constructor (hash, key) {
    this.hash = hash
    this.length = hash.BYTES

    this._blocksize = 2 * hash.BYTES

    this._initialised = false

    this.state = b4a.alloc(hash.STATEBYTES)
    this.pad = b4a.alloc(this._blocksize)

    if (key) this.init(key)
  }

  init (key) {
    if (this._initialised) {
      throw new Error('Already initialised, call final first')
    }

    if (key.length > this._blocksize) {
      this.hash.init(this.state)
      this.hash.update(this.state, key)
      this.hash.final(this.state, this.pad.subarray(0, this.length))
    } else {
      this.pad.set(key)
    }

    bufferByteXor(this.pad, 0x36)

    this.hash.init(this.state)
    this.hash.update(this.state, this.pad)

    bufferByteXor(this.pad, 0x5c ^ 0x36)

    this._initialised = true

    return this
  }

  update (data) {
    if (!this._initialised) {
      throw new Error('First initialise with a key')
    }

    this.hash.update(this.state, data)
    return this
  }

  final (output = b4a.alloc(this.length)) {
    if (!this._initialised) {
      throw new Error('First initialise with a key')
    }

    const out = output.byteLength === this.length
      ? output
      : output.subarray(0, this.hash.BYTES)

    this.hash.final(this.state, out)

    this.hash.init(this.state)
    this.hash.update(this.state, this.pad)
    this.hash.update(this.state, out)
    this.hash.final(this.state, out)

    this.pad.fill(0)
    this.state.fill(0)

    this._initialised = false

    return out
  }

  static sha256 (data, key, output) {
    const hmac = new HMAC(sha256, key)
    return hmac.update(data).final(output)
  }

  static sha512 (data, key, output) {
    const hmac = new HMAC(sha512, key)
    return hmac.update(data).final(output)
  }
}

module.exports = {
  HMAC,
  sha256,
  sha512
}

function bufferByteXor (output, byte) {
  for (let i = 0; i < output.byteLength; i++) {
    output[i] ^= byte
  }

  return output
}
{
  "name": "sodium-hmac",
  "version": "2.1.0",
  "description": "HMAC utility",
  "main": "index.js",
  "scripts": {
    "test": "standard && brittle test/*.js"
  },
  "author": "",
  "license": "Apache-2.0",
  "dependencies": {
    "b4a": "^1.6.6",
    "sodium-universal": "^5.0.1"
  },
  "devDependencies": {
    "brittle": "^3.4.0",
    "standard": "^17.1.0"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sodium-hmac.git"
  },
  "files": [
    "index.js",
    "hash/*"
  ],
  "bugs": {
    "url": "https://github.com/holepunchto/sodium-hmac/issues"
  },
  "homepage": "https://github.com/holepunchto/sodium-hmac#readme"
}
require.addon = require('require-addon')
module.exports = require.addon('.', __filename)
const assert = require('assert')
const binding = require('./binding')
const { isNode } = require('which-runtime')

const OPTIONAL = Buffer.from(new ArrayBuffer(0))

module.exports = exports = { ...binding }

// memory

exports.sodium_memzero = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  binding.sodium_memzero(buf)
}

exports.sodium_mlock = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  const res = binding.sodium_mlock(buf)

  if (res !== 0) throw new Error('memory lock failed')
}

exports.sodium_munlock = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  const res = binding.sodium_munlock(buf)

  if (res !== 0) throw new Error('memory unlock failed')
}

exports.sodium_malloc = function (size) {
  assert(size >= 0, 'invalid size')

  const buf = Buffer.from(binding.sodium_malloc(size))
  buf.secure = true
  return buf
}

exports.sodium_free = function (buf) {
  if (!buf || !buf.secure) return

  binding.sodium_free(buf.buffer)
}

exports.sodium_mprotect_noaccess = function (buf) {
  const res = binding.sodium_mprotect_noaccess(buf.buffer)

  if (res !== 0) throw new Error('failed to lock buffer')
}

exports.sodium_mprotect_readonly = function (buf) {
  const res = binding.sodium_mprotect_readonly(buf.buffer)

  if (res !== 0) throw new Error('failed to unlock buffer')
}

exports.sodium_mprotect_readwrite = function (buf) {
  const res = binding.sodium_mprotect_readwrite(buf.buffer)

  if (res !== 0) throw new Error('failed to unlock buffer')
}

// crypto_randombytes

exports.randombytes_buf = function (buffer) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')

  binding.randombytes_buf(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

exports.randombytes_buf_deterministic = function (buffer, seed) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    seed.byteLength === binding.randombytes_SEEDBYTES,
    "seed must be 'randombytes_SEEDBYTES' bytes"
  )

  binding.randombytes_buf_deterministic(
    buffer.buffer,
    buffer.byteOffset,
    buffer.byteLength,

    seed.buffer,
    seed.byteOffset,
    seed.byteLength
  )
}

// sodium_helpers

exports.sodium_memcmp = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  return binding.sodium_memcmp(a, b)
}

exports.sodium_add = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  binding.sodium_add(a, b)
}

exports.sodium_sub = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  binding.sodium_sub(a, b)
}

exports.sodium_compare = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  return binding.sodium_compare(a, b)
}

exports.sodium_is_zero = function (buffer, length) {
  if (length === undefined) length = buffer.byteLength

  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(length >= 0 && length <= buffer.byteLength, 'invalid length')

  return binding.sodium_is_zero(buffer, length)
}

exports.sodium_pad = function (buffer, unpaddedBuflen, blockSize) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(unpaddedBuflen <= buffer.byteLength, 'unpadded length cannot exceed buffer length')
  assert(blockSize <= buffer.byteLength, 'block size cannot exceed buffer length')
  assert(blockSize >= 1, 'block size must be at least 1 byte')
  assert(
    buffer.byteLength >= unpaddedBuflen + (blockSize - (unpaddedBuflen % blockSize)),
    'buf not long enough'
  )

  return binding.sodium_pad(buffer, unpaddedBuflen, blockSize)
}

exports.sodium_unpad = function (buffer, paddedBuflen, blockSize) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(paddedBuflen <= buffer.byteLength, 'unpadded length cannot exceed buffer length')
  assert(blockSize <= buffer.byteLength, 'block size cannot exceed buffer length')
  assert(blockSize >= 1, 'block size must be at least 1 byte')

  return binding.sodium_unpad(buffer, paddedBuflen, blockSize)
}

// crypto_sign

exports.crypto_sign_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )
  assert(
    seed.byteLength === binding.crypto_sign_SEEDBYTES,
    "seed must be 'crypto_sign_SEEDBYTES' bytes"
  )

  const res = binding.crypto_sign_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign = function (sm, m, sk) {
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sm.byteLength === binding.crypto_sign_BYTES + m.byteLength,
    "sm must be 'm.byteLength + crypto_sign_BYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign(sm, m, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_open = function (m, sm, pk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sm.byteLength >= binding.crypto_sign_BYTES,
    "sm must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    m.byteLength === sm.byteLength - binding.crypto_sign_BYTES,
    "m must be 'sm.byteLength - crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_open(m, sm, pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_open = function (m, sm, pk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sm.byteLength >= binding.crypto_sign_BYTES,
    "sm must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    m.byteLength === sm.byteLength - binding.crypto_sign_BYTES,
    "m must be 'sm.byteLength - crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  return binding.crypto_sign_open(m, sm, pk)
}

exports.crypto_sign_detached = function (sig, m, sk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(sig.byteLength === binding.crypto_sign_BYTES, "sig must be 'crypto_sign_BYTES' bytes")
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_detached(sig, m, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_verify_detached = function (sig, m, pk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sig.byteLength >= binding.crypto_sign_BYTES,
    "sig must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  return binding.crypto_sign_verify_detached(
    sig.buffer,
    sig.byteOffset,
    sig.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    pk.buffer,
    pk.byteOffset,
    pk.byteLength
  )
}

exports.crypto_sign_ed25519_sk_to_pk = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_sk_to_pk(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_ed25519_pk_to_curve25519 = function (x25519pk, ed25519pk) {
  assert(ArrayBuffer.isView(x25519pk), 'x25519pk must be a typed array')
  assert(ArrayBuffer.isView(ed25519pk), 'ed25519pk must be a typed array')
  assert(
    x25519pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "x25519pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    ed25519pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "ed25519pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_pk_to_curve25519(x25519pk, ed25519pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_ed25519_sk_to_curve25519 = function (x25519sk, ed25519sk) {
  assert(ArrayBuffer.isView(x25519sk), 'x25519sk must be a typed array')
  assert(ArrayBuffer.isView(ed25519sk), 'ed25519sk must be a typed array')
  assert(
    x25519sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "x25519sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const edLen = ed25519sk.byteLength

  assert(
    edLen === binding.crypto_sign_SECRETKEYBYTES || edLen === binding.crypto_box_SECRETKEYBYTES,
    "ed25519sk must be 'crypto_sign_SECRETKEYBYTES' or 'crypto_sign_SECRETKEYBYTES - crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_sk_to_curve25519(x25519sk, ed25519sk)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_box

exports.crypto_box_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    seed.byteLength === binding.crypto_box_SEEDBYTES,
    "seed must be 'crypto_box_SEEDBYTES' bytes"
  )

  const res = binding.crypto_box_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_easy = function (c, m, n, pk, sk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength === m.byteLength + exports.crypto_box_MACBYTES,
    "c must be 'm.byteLength + crypto_box_MACBYTES' bytes"
  )
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_easy(c, m, n, pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_detached = function (c, mac, m, n, pk, sk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(mac.byteLength === exports.crypto_box_MACBYTES, "mac must be 'crypto_box_MACBYTES' bytes")
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_detached(c, mac, m, n, pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_open_easy = function (m, c, n, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength >= exports.crypto_box_MACBYTES,
    "c must be at least 'crypto_box_MACBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - exports.crypto_box_MACBYTES,
    "m must be 'c.byteLength - crypto_box_MACBYTES' bytes"
  )
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_open_easy(m, c, n, pk, sk)
}

exports.crypto_box_open_detached = function (m, c, mac, n, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(mac.byteLength === exports.crypto_box_MACBYTES, "mac must be 'crypto_box_MACBYTES' bytes")
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_open_detached(m, c, mac, n, pk, sk)
}

exports.crypto_box_seal = function (c, m, pk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    c.byteLength === m.byteLength + exports.crypto_box_SEALBYTES,
    "c must be 'm.byteLength + crypto_box_SEALBYTES' bytes"
  )
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_box_seal(c, m, pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_seal_open = function (m, c, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength >= exports.crypto_box_SEALBYTES,
    "c must be at least 'crypto_box_SEALBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - exports.crypto_box_SEALBYTES,
    "m must be 'c.byteLength - crypto_box_SEALBYTES' bytes"
  )
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_seal_open(
    m.buffer,
    m.byteOffset,
    m.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    pk.buffer,
    pk.byteOffset,
    pk.byteLength,

    sk.buffer,
    sk.byteOffset,
    sk.byteLength
  )
}

// crypto_secretbox

exports.crypto_secretbox_easy = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_secretbox_MACBYTES,
    "c must be 'm.byteLength + crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretbox_easy(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretbox_open_easy = function (m, c, n, k) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    c.byteLength >= binding.crypto_secretbox_MACBYTES,
    "c must be at least 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - binding.crypto_secretbox_MACBYTES,
    "m must be 'c.byteLength - crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  return binding.crypto_secretbox_open_easy(m, c, n, k)
}

exports.crypto_secretbox_detached = function (c, mac, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    mac.byteLength === binding.crypto_secretbox_MACBYTES,
    "mac must be 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretbox_detached(c, mac, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretbox_open_detached = function (m, c, mac, n, k) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(
    mac.byteLength === binding.crypto_secretbox_MACBYTES,
    "mac must be 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  return binding.crypto_secretbox_open_detached(m, c, mac, n, k)
}

// crypto_generichash

exports.crypto_generichash = function (output, input, key) {
  if (!key) key = OPTIONAL

  assert(ArrayBuffer.isView(output), 'output must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    output.byteLength >= binding.crypto_generichash_BYTES_MIN &&
      output.byteLength <= binding.crypto_generichash_BYTES_MAX,
    'output must be between crypto_generichash_BYTES_MIN and crypto_generichash_BYTES_MAX bytes'
  )

  if (key !== OPTIONAL) {
    assert(ArrayBuffer.isView(key), 'key must be a typed array')
    assert(
      key.byteLength >= binding.crypto_generichash_KEYBYTES_MIN &&
        key.byteLength <= binding.crypto_generichash_KEYBYTES_MAX,
      'key must be between crypto_generichash_KEYBYTES_MIN and crypto_generichash_KEYBYTES_MAX bytes'
    )
  }

  const res = binding.crypto_generichash(
    output.buffer,
    output.byteOffset,
    output.byteLength,

    input.buffer,
    input.byteOffset,
    input.byteLength,

    key.buffer,
    key.byteOffset,
    key.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_batch = function (output, batch, key) {
  assert(ArrayBuffer.isView(output), 'output must be a typed array')

  if (isNode || batch.length < 4) {
    const res = binding.crypto_generichash_batch(output, batch, !!key, key || OPTIONAL)
    if (res !== 0) throw new Error('status: ' + res)
  } else {
    const state = Buffer.alloc(binding.crypto_generichash_STATEBYTES)

    exports.crypto_generichash_init(state, key, output.byteLength)

    for (const buf of batch) {
      exports.crypto_generichash_update(state, buf)
    }

    exports.crypto_generichash_final(state, output)
  }
}

exports.crypto_generichash_keygen = function (key) {
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(
    key.byteLength === binding.crypto_generichash_KEYBYTES,
    "key must be 'crypto_generichash_KEYBYTES' bytes"
  )

  const res = binding.crypto_generichash_keygen(key.buffer, key.byteOffset, key.byteLength)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_init = function (state, key, outputLength) {
  if (!key) key = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_init(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    key.buffer,
    key.byteOffset,
    key.byteLength,

    outputLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_update(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    input.buffer,
    input.byteOffset,
    input.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_final = function (state, output) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(output), 'output must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_final(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    output.buffer,
    output.byteOffset,
    output.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

// secretstream

exports.crypto_secretstream_xchacha20poly1305_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  binding.crypto_secretstream_xchacha20poly1305_keygen(k.buffer, k.byteOffset, k.byteLength)
}

exports.crypto_secretstream_xchacha20poly1305_init_push = function (state, header, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(header), 'header must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    header.byteLength === binding.crypto_secretstream_xchacha20poly1305_HEADERBYTES,
    "header must be 'crypto_secretstream_xchacha20poly1305_HEADERBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_init_push(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    header.buffer,
    header.byteOffset,
    header.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretstream_xchacha20poly1305_init_pull = function (state, header, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(header), 'header must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    header.byteLength === binding.crypto_secretstream_xchacha20poly1305_HEADERBYTES,
    "header must be 'crypto_secretstream_xchacha20poly1305_HEADERBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_init_pull(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    header.buffer,
    header.byteOffset,
    header.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretstream_xchacha20poly1305_push = function (state, c, m, ad, tag) {
  if (!ad) ad = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    c.byteLength === m.byteLength + binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "c must be 'm.byteLength + crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_push(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    ad.buffer,
    ad.byteOffset,
    ad.byteLength,

    tag
  )

  if (res < 0) throw new Error('push failed')

  return res
}

exports.crypto_secretstream_xchacha20poly1305_pull = function (state, m, tag, c, ad) {
  if (!ad) ad = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(tag), 'tag must be a typed array')
  assert(tag.byteLength === 1, 'tag must be 1 byte')

  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    c.byteLength >= binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "c must be at least 'crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "m must be 'c.byteLength - crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_pull(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    tag.buffer,
    tag.byteOffset,
    tag.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    ad.buffer,
    ad.byteOffset,
    ad.byteLength
  )

  if (res < 0) throw new Error('pull failed')

  return res
}

exports.crypto_secretstream_xchacha20poly1305_rekey = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )

  binding.crypto_secretstream_xchacha20poly1305_rekey(
    state.buffer,
    state.byteOffset,
    state.byteLength
  )
}

// crypto_stream

exports.crypto_stream = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xor(
    c.buffer,
    c.byteOffset,
    c.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    n.buffer,
    n.byteOffset,
    n.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_auth

exports.crypto_auth = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(out.byteLength === binding.crypto_auth_BYTES, "out must be 'crypto_auth_BYTES' bytes")
  assert(k.byteLength === binding.crypto_auth_KEYBYTES, "k must be 'crypto_auth_KEYBYTES' bytes")

  const res = binding.crypto_auth(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_auth_verify = function (h, input, k) {
  assert(ArrayBuffer.isView(h), 'h must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(h.byteLength === binding.crypto_auth_BYTES, "h must be 'crypto_auth_BYTES' bytes")
  assert(k.byteLength === binding.crypto_auth_KEYBYTES, "k must be 'crypto_auth_KEYBYTES' bytes")

  return binding.crypto_auth_verify(h, input, k)
}

// crypto_onetimeauth

exports.crypto_onetimeauth = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    out.byteLength === binding.crypto_onetimeauth_BYTES,
    "out must be 'crypto_onetimeauth_BYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_init = function (state, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_init(state, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )
  assert(
    out.byteLength === binding.crypto_onetimeauth_BYTES,
    "out must be 'crypto_onetimeauth_BYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_verify = function (h, input, k) {
  assert(ArrayBuffer.isView(h), 'h must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    h.byteLength === binding.crypto_onetimeauth_BYTES,
    "h must be 'crypto_onetimeauth_BYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  return binding.crypto_onetimeauth_verify(h, input, k)
}

// crypto_pwhash

exports.crypto_pwhash = function (out, passwd, salt, opslimit, memlimit, alg) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_BYTES_MIN,
    "out must be at least 'crypto_pwhash_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_BYTES_MAX,
    "out must be at most 'crypto_pwhash_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_SALTBYTES,
    "salt must be 'crypto_pwhash_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )
  assert(alg >= 1 && alg <= 2, 'alg must be either Argon2i 1.3 or Argon2id 1.3')

  const res = binding.crypto_pwhash(out, passwd, salt, opslimit, memlimit, alg)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_async = function (
  out,
  passwd,
  salt,
  opslimit,
  memlimit,
  alg,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_BYTES_MIN,
    "out must be at least 'crypto_pwhash_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_BYTES_MAX,
    "out must be at most 'crypto_pwhash_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_SALTBYTES,
    "salt must be 'crypto_pwhash_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )
  assert(alg >= 1 && alg <= 2, 'alg must be either Argon2i 1.3 or Argon2id 1.3')

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    opslimit,
    memlimit,
    alg,

    done
  )

  return promise
}

exports.crypto_pwhash_str = function (out, passwd, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_STRBYTES,
    "out must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(typeof opslimit === 'number', 'opslimit must be a number')
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(typeof memlimit === 'number', 'memlimit must be a number')
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_str(out, passwd, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_str_async = function (out, passwd, opslimit, memlimit, callback = undefined) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_STRBYTES,
    "out must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(typeof opslimit === 'number', 'opslimit must be a number')
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(typeof memlimit === 'number', 'memlimit must be a number')
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_str_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_str_verify = function (str, passwd) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )

  return binding.crypto_pwhash_str_verify(str, passwd)
}

exports.crypto_pwhash_str_verify_async = function (str, passwd, callback = undefined) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  const [done, promise] = checkStatus(callback, true)

  binding.crypto_pwhash_str_verify_async(
    str.buffer,
    str.byteOffset,
    str.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    done
  )

  return promise
}

exports.crypto_pwhash_str_needs_rehash = function (str, opslimit, memlimit) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  return binding.crypto_pwhash_str_needs_rehash(str, opslimit, memlimit)
}

exports.crypto_pwhash_scryptsalsa208sha256 = function (out, passwd, salt, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MIN,
    "out must be at least 'crypto_pwhash_scryptsalsa208sha256_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MAX,
    "out must be at most 'crypto_pwhash_scryptsalsa208sha256_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_SALTBYTES,
    "salt must be 'crypto_pwhash_scryptsalsa208sha256_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_scryptsalsa208sha256(out, passwd, salt, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_scryptsalsa208sha256_async = function (
  out,
  passwd,
  salt,
  opslimit,
  memlimit,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MIN,
    "out must be at least 'crypto_pwhash_scryptsalsa208sha256_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MAX,
    "out must be at most 'crypto_pwhash_scryptsalsa208sha256_BYTES_MAX' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    salt.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_SALTBYTES,
    "salt must be 'crypto_pwhash_scryptsalsa208sha256_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_scryptsalsa208sha256_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str_async = function (
  out,
  passwd,
  opslimit,
  memlimit,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "out must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_scryptsalsa208sha256_str_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str = function (out, passwd, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "out must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_scryptsalsa208sha256_str(out, passwd, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_scryptsalsa208sha256_str_verify_async = function (
  str,
  passwd,
  callback = undefined
) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  const [done, promise] = checkStatus(callback, true)

  binding.crypto_pwhash_scryptsalsa208sha256_str_verify_async(
    str.buffer,
    str.byteOffset,
    str.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str_verify = function (str, passwd) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  return binding.crypto_pwhash_scryptsalsa208sha256_str_verify(str, passwd)
}

exports.crypto_pwhash_scryptsalsa208sha256_str_needs_rehash = function (str, opslimit, memlimit) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  return binding.crypto_pwhash_scryptsalsa208sha256_str_needs_rehash(str, opslimit, memlimit)
}

// crypto_kx

exports.crypto_kx_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "pk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "sk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    pk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "pk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "sk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    seed.byteLength === binding.crypto_kx_SEEDBYTES,
    "seed must be 'crypto_kx_SEEDBYTES' bytes"
  )

  const res = binding.crypto_kx_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_client_session_keys = function (rx, tx, clientPk, clientSk, serverPk) {
  if (!rx) rx = undefined
  if (!tx) tx = undefined

  assert(rx || tx, 'at least one session key must be specified')

  if (rx) {
    assert(ArrayBuffer.isView(rx), 'rx must be a typed array')
    assert(
      rx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "rx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  if (tx) {
    assert(ArrayBuffer.isView(tx), 'tx must be a typed array')
    assert(
      tx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "tx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  assert(ArrayBuffer.isView(clientPk), 'clientPk must be a typed array')
  assert(ArrayBuffer.isView(clientSk), 'clientSk must be a typed array')
  assert(ArrayBuffer.isView(serverPk), 'serverPk must be a typed array')
  assert(
    clientPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "clientPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    clientSk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "clientSk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    serverPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "serverPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_client_session_keys(rx, tx, clientPk, clientSk, serverPk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_server_session_keys = function (rx, tx, serverPk, serverSk, clientPk) {
  if (!rx) rx = undefined
  if (!tx) tx = undefined

  assert(rx || tx, 'at least one session key must be specified')

  if (rx) {
    assert(ArrayBuffer.isView(rx), 'rx must be a typed array')
    assert(
      rx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "rx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  if (tx) {
    assert(ArrayBuffer.isView(tx), 'tx must be a typed array')
    assert(
      tx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "tx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  assert(ArrayBuffer.isView(serverPk), 'serverPk must be a typed array')
  assert(ArrayBuffer.isView(serverSk), 'serverSk must be a typed array')
  assert(ArrayBuffer.isView(clientPk), 'clientPk must be a typed array')
  assert(
    serverPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "serverPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    serverSk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "serverSk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    clientPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "clientPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_server_session_keys(rx, tx, serverPk, serverSk, clientPk)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_scalarmult

exports.crypto_scalarmult_base = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_BYTES,
    "q must be 'crypto_scalarmult_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_SCALARBYTES,
    "n must be 'crypto_scalarmult_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_base(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_BYTES,
    "q must be 'crypto_scalarmult_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_SCALARBYTES,
    "n must be 'crypto_scalarmult_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_BYTES,
    "p must be 'crypto_scalarmult_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_base = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_base(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519 = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "p must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_is_valid_point = function (p) {
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )

  return binding.crypto_core_ed25519_is_valid_point(p)
}

exports.crypto_core_ed25519_from_uniform = function (p, r) {
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_UNIFORMBYTES,
    "r must be 'crypto_core_ed25519_UNIFORMBYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_from_uniform(p, r)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_base_noclamp = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_base_noclamp(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_noclamp = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "p must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_noclamp(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_core

exports.crypto_core_ed25519_add = function (r, p, q) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_BYTES,
    "r must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_core_ed25519_BYTES,
    "q must be 'crypto_core_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_add(r, p, q)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_sub = function (r, p, q) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_BYTES,
    "r must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_core_ed25519_BYTES,
    "q must be 'crypto_core_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_sub(r, p, q)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_scalar_random = function (r) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "r must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_random(r)
}

exports.crypto_core_ed25519_scalar_reduce = function (r, s) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "r must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_NONREDUCEDSCALARBYTES,
    "s must be 'crypto_core_ed25519_NONREDUCEDSCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_reduce(r, s)
}

exports.crypto_core_ed25519_scalar_invert = function (recip, s) {
  assert(ArrayBuffer.isView(recip), 'recip must be a typed array')
  assert(
    recip.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "recip must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_invert(recip, s)
}

exports.crypto_core_ed25519_scalar_negate = function (neg, s) {
  assert(ArrayBuffer.isView(neg), 'neg must be a typed array')
  assert(
    neg.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "neg must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_negate(neg, s)
}

exports.crypto_core_ed25519_scalar_complement = function (comp, s) {
  assert(ArrayBuffer.isView(comp), 'comp must be a typed array')
  assert(
    comp.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "comp must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_complement(comp, s)
}

exports.crypto_core_ed25519_scalar_add = function (z, x, y) {
  assert(ArrayBuffer.isView(z), 'z must be a typed array')
  assert(
    z.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "z must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(x), 'x must be a typed array')
  assert(
    x.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "x must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(y), 'y must be a typed array')
  assert(
    y.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "y must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_add(z, x, y)
}

exports.crypto_core_ed25519_scalar_sub = function (z, x, y) {
  assert(ArrayBuffer.isView(z), 'z must be a typed array')
  assert(
    z.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "z must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(x), 'x must be a typed array')
  assert(
    x.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "x must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(y), 'y must be a typed array')
  assert(
    y.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "y must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_sub(z, x, y)
}

// crypto_shorthash

exports.crypto_shorthash = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_shorthash_BYTES,
    "out must be 'crypto_shorthash_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_shorthash_KEYBYTES,
    "k must be 'crypto_shorthash_KEYBYTES' bytes"
  )

  const res = binding.crypto_shorthash(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_kdf

exports.crypto_kdf_keygen = function (key) {
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(key.byteLength === binding.crypto_kdf_KEYBYTES, "key must be 'crypto_kdf_KEYBYTES' bytes")

  binding.crypto_kdf_keygen(key)
}

exports.crypto_kdf_derive_from_key = function (subkey, subkeyId, ctx, key) {
  assert(ArrayBuffer.isView(subkey), 'subkey must be a typed array')
  assert(
    subkey.byteLength >= binding.crypto_kdf_BYTES_MIN,
    "subkey must be at least 'crypto_kdf_BYTES_MIN' bytes"
  )
  assert(
    subkey.byteLength <= binding.crypto_kdf_BYTES_MAX,
    "subkey must be at most 'crypto_kdf_BYTES_MAX' bytes"
  )
  assert(ArrayBuffer.isView(ctx), 'ctx must be a typed array')
  assert(
    ctx.byteLength === binding.crypto_kdf_CONTEXTBYTES,
    "ctx must be 'crypto_kdf_CONTEXTBYTES' bytes"
  )
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(key.byteLength === binding.crypto_kdf_KEYBYTES, "key must be 'crypto_kdf_KEYBYTES' bytes")

  const res = binding.crypto_kdf_derive_from_key(subkey, subkeyId, ctx, key)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_hash

exports.crypto_hash = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(out.byteLength === binding.crypto_hash_BYTES, "out must be 'crypto_hash_BYTES' bytes")

  const res = binding.crypto_hash(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256 = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha256_BYTES,
    "out must be 'crypto_hash_sha256_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha256(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_init = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_init(state)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha256_BYTES,
    "out must be 'crypto_hash_sha256_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512 = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha512_BYTES,
    "out must be 'crypto_hash_sha512_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha512(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_init = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_init(state)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha512_BYTES,
    "out must be 'crypto_hash_sha512_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_aead

exports.crypto_aead_xchacha20poly1305_ietf_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  binding.crypto_aead_xchacha20poly1305_ietf_keygen(k)
}

exports.crypto_aead_xchacha20poly1305_ietf_encrypt = function (c, m, ad, nsec, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "c must be 'm.byteLength + crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(c.byteLength <= 0xffffffff, 'c.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_encrypt(c, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_decrypt = function (m, nsec, c, ad, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "m must be 'c.byteLength - crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(m.byteLength <= 0xffffffff, 'm.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_decrypt(m, c, ad, npub, k)

  if (res < 0) throw new Error('could not verify data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_encrypt_detached = function (
  c,
  mac,
  m,
  ad,
  nsec,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_encrypt_detached(c, mac, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_decrypt_detached = function (
  m,
  nsec,
  c,
  mac,
  ad,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_decrypt_detached(m, c, mac, ad, npub, k)

  if (res !== 0) throw new Error('could not verify data')
}

exports.crypto_aead_chacha20poly1305_ietf_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  binding.crypto_aead_chacha20poly1305_ietf_keygen(k)
}

exports.crypto_aead_chacha20poly1305_ietf_encrypt = function (c, m, ad, nsec, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "c must be 'm.byteLength + crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(c.byteLength <= 0xffffffff, 'c.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_encrypt(c, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_decrypt = function (m, nsec, c, ad, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "m must be 'c.byteLength - crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(m.byteLength <= 0xffffffff, 'm.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_decrypt(m, c, ad, npub, k)

  if (res < 0) throw new Error('could not verify data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_encrypt_detached = function (
  c,
  mac,
  m,
  ad,
  nsec,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_encrypt_detached(c, mac, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_decrypt_detached = function (
  m,
  nsec,
  c,
  mac,
  ad,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_decrypt_detached(m, c, mac, ad, npub, k)

  if (res !== 0) throw new Error('could not verify data')
}

// crypto_stream

exports.crypto_stream_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  binding.crypto_stream_xor_wrap_init(state, n, k)
}

exports.crypto_stream_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_xor_wrap_update(state, c, m)
}

exports.crypto_stream_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_xor_wrap_final(state)
}

exports.crypto_stream_chacha20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  binding.crypto_stream_chacha20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_chacha20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_chacha20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_chacha20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_chacha20_xor_wrap_final(state)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  binding.crypto_stream_chacha20_ietf_xor_wrap_init(state, n, k)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_chacha20_ietf_xor_wrap_update(state, c, m)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_chacha20_ietf_xor_wrap_final(state)
}

exports.crypto_stream_xchacha20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  binding.crypto_stream_xchacha20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_xchacha20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_xchacha20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_xchacha20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_xchacha20_xor_wrap_final(state)
}

exports.crypto_stream_salsa20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  binding.crypto_stream_salsa20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_salsa20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_salsa20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_salsa20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_salsa20_xor_wrap_final(state)
}

// experimental

exports.extension_tweak_ed25519_base = function (n, p, ns) {
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.extension_tweak_ed25519_BYTES,
    "p must be 'extension_tweak_ed25519_BYTES' bytes"
  )

  binding.extension_tweak_ed25519_base(n, p, ns)
}

exports.extension_tweak_ed25519_sign_detached = function (sig, m, scalar, pk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(sig.byteLength === binding.crypto_sign_BYTES, "sig must be 'crypto_sign_BYTES' bytes")
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  if (pk) {
    assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
    assert(
      pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
      "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
    )
  }

  const res = binding.extension_tweak_ed25519_sign_detached(sig, m, scalar, pk)

  if (res !== 0) throw new Error('failed to compute signature')
}

exports.extension_tweak_ed25519_sk_to_scalar = function (n, sk) {
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  binding.extension_tweak_ed25519_sk_to_scalar(n, sk)
}

exports.extension_tweak_ed25519_scalar = function (scalarOut, scalar, ns) {
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_scalar(scalarOut, scalar, ns)
}

exports.extension_tweak_ed25519_pk = function (tpk, pk, ns) {
  assert(ArrayBuffer.isView(tpk), 'tpk must be a typed array')
  assert(
    tpk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "tpk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_pk(tpk, pk, ns)

  if (res !== 0) throw new Error('failed to tweak public key')
}

exports.extension_tweak_ed25519_keypair = function (pk, scalarOut, scalarIn, ns) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.extension_tweak_ed25519_BYTES,
    "pk must be 'extension_tweak_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarIn), 'scalarIn must be a typed array')
  assert(
    scalarIn.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarIn must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_keypair(pk, scalarOut, scalarIn, ns)
}

exports.extension_tweak_ed25519_scalar_add = function (scalarOut, scalar, n) {
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_scalar_add(scalarOut, scalar, n)
}

exports.extension_tweak_ed25519_pk_add = function (tpk, pk, p) {
  assert(ArrayBuffer.isView(tpk), 'tpk must be a typed array')
  assert(
    tpk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "tpk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "p must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_pk_add(tpk, pk, p)

  if (res !== 0) throw new Error('failed to add tweak to public key')
}

exports.extension_tweak_ed25519_keypair_add = function (pk, scalarOut, scalarIn, tweak) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.extension_tweak_ed25519_BYTES,
    "pk must be 'extension_tweak_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarIn), 'scalarIn must be a typed array')
  assert(
    scalarIn.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarIn must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(tweak), 'tweak must be a typed array')
  assert(
    tweak.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "tweak must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_keypair_add(pk, scalarOut, scalarIn, tweak)

  if (res !== 0) throw new Error('failed to add tweak to keypair')
}

exports.extension_pbkdf2_sha512_async = function (out, passwd, salt, iter, outlen, callback) {
  assert(
    iter >= binding.extension_pbkdf2_sha512_ITERATIONS_MIN,
    "iter must be at least 'extension_pbkdf2_sha512_ITERATIONS_MIN'"
  )
  assert(
    outlen <= binding.extension_pbkdf2_sha512_BYTES_MAX,
    "outlen must be at most 'extension_pbkdf2_sha512_BYTES_MAX'"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(out.byteLength >= outlen, "out must be at least 'outlen' bytes")
  assert(out.byteLength > 0, 'out must not be empty')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(salt.byteLength > 0, 'salt must not be empty')

  const [done, promise] = checkStatus(callback)

  binding.extension_pbkdf2_sha512_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    iter,
    outlen,

    done
  )

  return promise
}

exports.extension_pbkdf2_sha512 = function (out, passwd, salt, iter, outlen) {
  assert(
    iter >= binding.extension_pbkdf2_sha512_ITERATIONS_MIN,
    "iter must be at least 'extension_pbkdf2_sha512_ITERATIONS_MIN'"
  )
  assert(
    outlen <= binding.extension_pbkdf2_sha512_BYTES_MAX,
    "outlen must be at most 'extension_pbkdf2_sha512_BYTES_MAX'"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(out.byteLength >= outlen, "out must be at least 'outlen' bytes")
  assert(out.byteLength > 0, 'out must not be empty')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(salt.byteLength > 0, 'salt must not be empty')

  const res = binding.extension_pbkdf2_sha512(out, passwd, salt, iter, outlen)

  if (res !== 0) throw new Error('failed to add tweak to public key')
}

function checkStatus(callback, booleanResult = false) {
  let done, promise

  if (typeof callback === 'function') {
    done = function (status) {
      if (booleanResult) callback(null, status === 0)
      else if (status === 0) callback(null)
      else callback(new Error('status: ' + status))
    }
  } else {
    promise = new Promise(function (resolve, reject) {
      done = function (status) {
        if (booleanResult) resolve(status === 0)
        else if (status === 0) resolve()
        else reject(new Error('status: ' + status))
      }
    })
  }

  return [done, promise]
}
{
  "name": "sodium-native",
  "version": "5.1.0",
  "description": "Low level bindings for libsodium",
  "main": "index.js",
  "files": [
    "index.js",
    "binding.cc",
    "binding.js",
    "extensions",
    "prebuilds",
    "CMakeLists.txt"
  ],
  "imports": {
    "assert": {
      "bare": "bare-assert",
      "node": "assert"
    }
  },
  "addon": true,
  "dependencies": {
    "bare-assert": "^1.2.0",
    "require-addon": "^1.1.0",
    "which-runtime": "^1.2.1"
  },
  "devDependencies": {
    "bare-compat-napi": "^1.3.5",
    "brittle": "^3.16.2",
    "cmake-bare": "^1.6.1",
    "cmake-fetch": "^1.4.3",
    "cmake-napi": "^1.2.1",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "test": "prettier . --check && npm run test:node && npm run test:bare",
    "test:node": "node test/all.js",
    "test:bare": "bare test/all.js"
  },
  "standard": {
    "ignore": [
      "/test/fixtures/*.js"
    ]
  },
  "engines": {
    "bare": ">=1.16.0"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sodium-native.git"
  },
  "contributors": [
    "Emil Bay <github@tixz.dk> (http://bayes.dk)",
    "Mathias Buus <mathiasbuus@gmail.com> (https://mafinto.sh)",
    "Christophe Diederichs <chm-diederichs@hyperdivision.dk>"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/sodium-native/issues"
  },
  "homepage": "https://github.com/holepunchto/sodium-native"
}
module.exports = require('sodium-native')
{
  "name": "sodium-universal",
  "version": "5.0.1",
  "description": "Universal wrapper for sodium-javascript and sodium-native working in Node.js and the Browser",
  "main": "index.js",
  "dependencies": {
    "sodium-native": "^5.0.1"
  },
  "peerDependencies": {
    "sodium-javascript": "~0.8.0"
  },
  "peerDependenciesMeta": {
    "sodium-javascript": {
      "optional": true
    }
  },
  "scripts": {
    "prepublish": "./build-scripts/generate.js"
  },
  "browser": {
    "sodium-native": "sodium-javascript"
  },
  "browserify": {
    "transform": [
      "./build-scripts/transform.js"
    ]
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sodium-universal.git"
  },
  "keywords": [
    "libsodium",
    "sodium",
    "sodium-native",
    "sodium-javascript",
    "browserify"
  ],
  "contributors": [
    "Emil Bay <github@tixz.dk> (http://bayes.dk)",
    "Mathias Buus <mathiasbuus@gmail.com> (https://mafinto.sh)",
    "Christophe Diederichs <chm-diederichs@hyperdivision.dk>"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/sodium-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/sodium-universal#readme"
}
const { runtime, platform, arch, version } =
  typeof Bare !== 'undefined'
    ? {
        runtime: 'bare',
        platform: global.Bare.platform,
        arch: global.Bare.arch,
        version: global.Bare.version
      }
    : typeof process !== 'undefined'
      ? {
          runtime: 'node',
          platform: global.process.platform,
          arch: global.process.arch,
          version: global.process.version
        }
      : typeof Window !== 'undefined'
        ? { runtime: 'browser', platform: 'unknown', arch: 'unknown', version: 'unknown' }
        : { runtime: 'unknown', platform: 'unknown', arch: 'unknown', version: 'unknown' }

exports.runtime = runtime
exports.version = version
exports.platform = platform
exports.arch = arch
exports.isBare = runtime === 'bare'
exports.isBareKit = exports.isBare && typeof BareKit !== 'undefined'
exports.isPear = typeof Pear !== 'undefined'
exports.isNode = runtime === 'node'
exports.isBrowser = runtime === 'browser'
exports.isWindows = platform === 'win32'
exports.isLinux = platform === 'linux'
exports.isMac = platform === 'darwin'
exports.isIOS = platform === 'ios' || platform === 'ios-simulator'
exports.isAndroid = platform === 'android'
exports.isElectron = typeof process !== 'undefined' && !!global.process.versions?.electron
exports.isElectronRenderer = exports.isElectron && global.process.type === 'renderer'
exports.isElectronWorker = exports.isElectron && global.process.type === 'worker'
{
  "name": "which-runtime",
  "version": "1.4.0",
  "description": "Detect if you are in Bare or Node and which os etc",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte .",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/which-runtime.git"
  },
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/which-runtime/issues"
  },
  "homepage": "https://github.com/holepunchto/which-runtime",
  "devDependencies": {
    "brittle": "^3.0.0",
    "lunte": "^1.4.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
{
  "name": "atproto-identity",
  "version": "0.0.4",
  "description": "Seed-anchored atproto identity: one BIP39 mnemonic -> Ed25519 (Hypercore) + secp256k1 (did:plc). Offline did:plc genesis + verification.",
  "type": "module",
  "main": "lib/atproto-identity.js",
  "scripts": {
    "test": "brittle-node test/*.test.js && node test/labels.test.mjs",
    "postinstall": "node scripts/bare-deps.mjs"
  },
  "dependencies": {
    "@ipld/dag-cbor": "^9.2.1",
    "@noble/curves": "^1.6.0",
    "@noble/hashes": "^1.5.0",
    "@scure/bip32": "^1.5.0",
    "@scure/bip39": "^1.4.0",
    "b4a": "^1.6.7",
    "hypercore-crypto": "^3.0.0",
    "keet-identity-key": "^3.2.0",
    "multiformats": "^13.3.0",
    "sodium-native": "^5.1.0"
  },
  "devDependencies": {
    "brittle": "^4.0.2"
  }
}
// atproto block CIDs — CIDv1, dag-cbor codec (0x71), sha2-256 multihash (0x12).
// Every block in a repo (commit, MST node, record) is content-addressed this way,
// so computeCid(dag-cbor(block)) IS the block's identity. This is the anchor for
// byte-exact fidelity: if our re-encoded bytes hash to the same CID the reference
// produced, our encoding is byte-identical.

import { CID } from 'multiformats/cid'
import * as Digest from 'multiformats/hashes/digest'
import { sha256 as nobleSha256 } from '@noble/hashes/sha2'
import * as dagCbor from '@ipld/dag-cbor'
import * as raw from 'multiformats/codecs/raw'

// raw block bytes -> CID. Uses noble's pure-JS sha256 (same as the sync path) rather
// than multiformats' `crypto.subtle` path — identical CID, and no WebCrypto dependency
// (so it loads + runs under Bare, which has no crypto.subtle).
export async function cidForBytes (bytes) {
  return cidForBytesSync(bytes)
}

// Synchronous variant — needed by the recursive MST build. Same result as
// cidForBytes (CIDv1 / dag-cbor 0x71 / sha2-256 0x12), just without the async
// WebCrypto digest.
export function cidForBytesSync (bytes) {
  const digest = Digest.create(0x12, nobleSha256(bytes)) // 0x12 = sha2-256 multihash code
  return CID.createV1(dagCbor.code, digest)
}

// BLOB CID — CIDv1, RAW codec (0x55), sha2-256. atproto blobs (images/avatars) are
// content-addressed with the raw codec (opaque bytes), NOT dag-cbor. This is the CID that
// goes in a blob ref ({$type:'blob', ref:{$link:<this>}, mimeType, size}) and the key
// com.atproto.sync.getBlob serves by.
export function cidForBlobSync (bytes) {
  const digest = Digest.create(0x12, nobleSha256(bytes))
  return CID.createV1(raw.code, digest)
}

// a JS value -> its canonical dag-cbor bytes + CID
export async function cidForValue (value) {
  const bytes = dagCbor.encode(value)
  return { bytes, cid: await cidForBytes(bytes) }
}
// atproto repo commit — sign + verify.
//
// A commit is { did, version: 3, data: <MST root CID>, rev, prev, sig }. The
// signature is ECDSA-secp256k1 (low-S) over sha256(dag-cbor(unsignedCommit)), stored
// as a raw 64-byte CBOR byte string (NOT base64url — that's the did:plc genesis).
// The relay validates this sig against the DID doc's verificationMethod.

import * as dagCbor from '@ipld/dag-cbor'
import { sha256 as nobleSha256 } from '@noble/hashes/sha2'
import { secp256k1 } from '@noble/curves/secp256k1'
import { cidForBytesSync } from './cid.js'

export const REPO_VERSION = 3

// The unsigned commit (everything the signature covers).
export function unsignedCommit ({ did, rev, data, prev = null }) {
  return { did, version: REPO_VERSION, data, rev, prev }
}

// Sign an unsigned commit -> signed commit with `sig` (64 raw bytes).
export function signCommit (unsigned, privateKey) {
  const hash = nobleSha256(dagCbor.encode(unsigned))
  const sig = secp256k1.sign(hash, privateKey, { lowS: true }).toCompactRawBytes()
  return { ...unsigned, sig }
}

export function commitCid (signedCommit) {
  return cidForBytesSync(dagCbor.encode(signedCommit))
}

// Verify a signed commit against a compressed secp256k1 pubkey (33 bytes).
export function verifyCommit (signedCommit, publicKey) {
  const { sig, ...unsigned } = signedCommit
  const hash = nobleSha256(dagCbor.encode(unsigned))
  return secp256k1.verify(sig, hash, publicKey, { lowS: true })
}
// atproto MST — WRITE path (slice 2).
//
// A faithful port of millipds's `atmst` (mst/node.py + node_wrangler.py) — the exact
// code that produced our golden CAR. Byte-exactness is verified two ways: rebuilding
// the golden repo's MST, and matching atmst's own root CIDs for a multi-height tree
// (build + delete oracles). See test/mst-write.test.js.
//
// Node shape (interleaved): subtrees[0], (keys[0],vals[0]), subtrees[1], … ,subtrees[n].
// key layer = leading-zero BITS of sha256(key), // 2 (fanout 4).

import * as dagCbor from '@ipld/dag-cbor'
import { sha256 as nobleSha256 } from '@noble/hashes/sha2'
import { cidForBytesSync } from './cid.js'

const cidEq = (a, b) => (a === null || b === null) ? a === b : a.equals(b)
const replaceAt = (arr, i, v) => { const c = arr.slice(); c[i] = v; return c }
const insertAt = (arr, i, v) => arr.slice(0, i).concat([v], arr.slice(i))
const removeAt = (arr, i) => arr.slice(0, i).concat(arr.slice(i + 1))

export function keyHeight (key) {
  const h = nobleSha256(Buffer.from(key, 'utf8')) // 32 bytes
  let zeros = 0
  for (const byte of h) {
    if (byte === 0) { zeros += 8; continue }
    zeros += Math.clz32(byte) - 24 // leading zero bits within this byte
    break
  }
  return zeros >> 1 // // 2
}

export class MSTNode {
  constructor (keys, vals, subtrees) {
    this.keys = keys // [string]
    this.vals = vals // [CID]
    this.subtrees = subtrees // [CID|null], length keys.length + 1
  }

  static empty () { return new MSTNode([], [], [null]) }

  isEmpty () { return this.keys.length === 0 && this.subtrees.length === 1 && this.subtrees[0] === null }

  serialise () {
    const e = []
    let prevKey = Buffer.alloc(0)
    for (let i = 0; i < this.keys.length; i++) {
      const keyBytes = Buffer.from(this.keys[i], 'utf8')
      const max = Math.min(prevKey.length, keyBytes.length)
      let p = 0
      while (p < max && prevKey[p] === keyBytes[p]) p++
      e.push({ k: keyBytes.subarray(p), p, t: this.subtrees[i + 1], v: this.vals[i] })
      prevKey = keyBytes
    }
    return dagCbor.encode({ e, l: this.subtrees[0] }) // dag-cbor canonicalises map key order
  }

  cid () { return cidForBytesSync(this.serialise()) }

  toOptional () { return this.isEmpty() ? null : this.cid() }

  gteIndex (key) { let i = 0; while (i < this.keys.length && key > this.keys[i]) i++; return i }

  height () {
    if (this.keys.length) return keyHeight(this.keys[0])
    if (this.subtrees[0] === null) return 0
    return null // indeterminate (empty intermediate node)
  }

  static deserialise (bytes) {
    const cbor = dagCbor.decode(bytes)
    const subtrees = [cbor.l]
    const keys = []
    const vals = []
    let prevKey = Buffer.alloc(0)
    for (const e of cbor.e) {
      const suffix = Buffer.from(e.k)
      const thisKey = Buffer.concat([prevKey.subarray(0, e.p), suffix])
      keys.push(thisKey.toString('utf8'))
      vals.push(e.v)
      subtrees.push(e.t)
      prevKey = thisKey
    }
    return new MSTNode(keys, vals, subtrees)
  }
}

// In-memory node store — maps CID string -> { cid, bytes }. get(null) returns the
// (stored) empty node, matching atmst NodeStore.get_node(None).
export class NodeStore {
  constructor () { this.blocks = new Map() }

  storedNode (node) {
    const bytes = node.serialise()
    const cid = cidForBytesSync(bytes)
    this.blocks.set(cid.toString(), { cid, bytes })
    return node
  }

  getNode (cid) {
    if (cid === null || cid === undefined) return this.storedNode(MSTNode.empty())
    const b = this.blocks.get(cid.toString())
    if (!b) throw new Error(`missing MST node ${cid}`)
    return MSTNode.deserialise(b.bytes)
  }
}

export class NodeWrangler {
  constructor (ns) { this.ns = ns }

  putRecord (rootCid, key, val) {
    const root = this.ns.getNode(rootCid)
    if (root.isEmpty()) return this._putHere(root, key, val).cid()
    return this._putRecursive(root, key, val, keyHeight(key), root.height()).cid()
  }

  delRecord (rootCid, key) {
    const root = this.ns.getNode(rootCid)
    const afterDel = this._deleteRecursive(root, key, keyHeight(key), root.height())
    return this.ns.getNode(this._squashTop(afterDel)).cid()
  }

  _putHere (node, key, val) {
    const i = node.gteIndex(key)
    if (i < node.keys.length && node.keys[i] === key) {
      if (cidEq(node.vals[i], val)) return node
      return this.ns.storedNode(new MSTNode(node.keys.slice(), replaceAt(node.vals, i, val), node.subtrees.slice()))
    }
    const [lsub, rsub] = this._splitOnKey(node.subtrees[i], key)
    return this.ns.storedNode(new MSTNode(
      insertAt(node.keys, i, key),
      insertAt(node.vals, i, val),
      node.subtrees.slice(0, i).concat([lsub, rsub], node.subtrees.slice(i + 1))
    ))
  }

  _putRecursive (node, key, val, keyH, treeH) {
    if (keyH > treeH) { // grow the tree upward
      return this.ns.storedNode(this._putRecursive(
        this.ns.storedNode(new MSTNode([], [], [node.cid()])),
        key, val, keyH, treeH + 1
      ))
    }
    if (keyH < treeH) { // descend
      const i = node.gteIndex(key)
      return this.ns.storedNode(new MSTNode(
        node.keys.slice(), node.vals.slice(),
        replaceAt(node.subtrees, i, this._putRecursive(this.ns.getNode(node.subtrees[i]), key, val, keyH, treeH - 1).cid())
      ))
    }
    return this._putHere(node, key, val) // keyH === treeH
  }

  _splitOnKey (nodeCid, key) {
    if (nodeCid === null || nodeCid === undefined) return [null, null]
    const node = this.ns.getNode(nodeCid)
    const i = node.gteIndex(key)
    const [lsub, rsub] = this._splitOnKey(node.subtrees[i], key)
    const left = this.ns.storedNode(new MSTNode(node.keys.slice(0, i), node.vals.slice(0, i), node.subtrees.slice(0, i).concat([lsub]))).toOptional()
    const right = this.ns.storedNode(new MSTNode(node.keys.slice(i), node.vals.slice(i), [rsub].concat(node.subtrees.slice(i + 1)))).toOptional()
    return [left, right]
  }

  _squashTop (nodeCid) {
    const node = this.ns.getNode(nodeCid)
    if (node.keys.length) return nodeCid
    if (node.subtrees[0] === null) return nodeCid
    return this._squashTop(node.subtrees[0])
  }

  _deleteRecursive (node, key, keyH, treeH) {
    if (keyH > treeH) return node.toOptional()
    let i = node.gteIndex(key)
    if (keyH < treeH) {
      if (node.subtrees[i] === null) return node.toOptional()
      return this.ns.storedNode(new MSTNode(
        node.keys.slice(), node.vals.slice(),
        replaceAt(node.subtrees, i, this._deleteRecursive(this.ns.getNode(node.subtrees[i]), key, keyH, treeH - 1))
      )).toOptional()
    }
    i = node.gteIndex(key)
    if (i === node.keys.length || node.keys[i] !== key) return node.toOptional()
    return this.ns.storedNode(new MSTNode(
      removeAt(node.keys, i), removeAt(node.vals, i),
      node.subtrees.slice(0, i).concat([this._merge(node.subtrees[i], node.subtrees[i + 1])], node.subtrees.slice(i + 2))
    )).toOptional()
  }

  _merge (leftCid, rightCid) {
    if (leftCid === null) return rightCid
    if (rightCid === null) return leftCid
    const left = this.ns.getNode(leftCid)
    const right = this.ns.getNode(rightCid)
    return this.ns.storedNode(new MSTNode(
      left.keys.concat(right.keys), left.vals.concat(right.vals),
      left.subtrees.slice(0, -1).concat([this._merge(left.subtrees[left.subtrees.length - 1], right.subtrees[0])], right.subtrees.slice(1))
    )).toOptional()
  }
}

// Build an MST from records [{ key, value: CID }] (any order). Returns
// { root: CID, ns: NodeStore }. ns.blocks holds every node created; use
// reachableBlocks(ns, root) for just the live set (CAR output).
export function buildMst (records) {
  const ns = new NodeStore()
  const w = new NodeWrangler(ns)
  let root = ns.storedNode(MSTNode.empty()).cid()
  for (const { key, value } of records) root = w.putRecord(root, key, value)
  return { root, ns, wrangler: w }
}

// BFS the live MST nodes reachable from root (for CAR block sets).
export function reachableBlocks (ns, rootCid) {
  const out = new Map()
  const stack = [rootCid]
  while (stack.length) {
    const cid = stack.pop()
    if (cid === null || cid === undefined) continue
    const key = cid.toString()
    if (out.has(key)) continue
    const b = ns.blocks.get(key)
    if (!b) throw new Error(`missing node ${key}`)
    out.set(key, b)
    const node = MSTNode.deserialise(b.bytes)
    for (const t of node.subtrees) if (t) stack.push(t)
  }
  return out
}

// ---- Firehose MST-inversion proof (slice 3b) ----
//
// A #commit's `blocks` CAR must be a MINIMAL, self-contained proof of the
// old→new transition — not the whole tree (that would trip a relay's `tooBig`).
// This ports millipds `repo_ops.py:apply_writes` step 2b + `atmst` proof.py:
//   blocks = created | deletion_proof_cids | inductive_proof_nodes  (+ new records)
// where `inductive_proof_nodes` = every MST node READ while replaying the ops
// backward from the new root, which must reproduce the old (prevData) root.
// The prior record CIDs travel in each op's `prev` (like millipds), so a cold
// relay can invert with no old-tree state of its own.

// A NodeStore overlay: writes land in an in-memory upper layer (NOT logged);
// reads that fall through to `lower` are recorded in `.gets`. Mirrors millipds's
// OverlayBlockStore(MemoryBlockStore, LoggingBlockStoreWrapper(bs)).
export class OverlayNodeStore {
  constructor (lower) { this.lower = lower; this.upper = new Map(); this.gets = new Set() }

  storedNode (node) {
    const bytes = node.serialise()
    const cid = cidForBytesSync(bytes)
    this.upper.set(cid.toString(), { cid, bytes })
    return node
  }

  getNode (cid) {
    if (cid === null || cid === undefined) return MSTNode.empty()
    const k = cid.toString()
    const u = this.upper.get(k)
    if (u) return MSTNode.deserialise(u.bytes)
    this.gets.add(k) // a read of a pre-existing node — part of the inductive proof
    return this.lower.getNode(cid)
  }
}

// Follow the search path for `key` from `rootCid`, collecting every node visited.
// Returns { value: CID|null, proof: Set<cidStr> }. value===null ⇒ exclusion proof;
// value!==null ⇒ inclusion proof. Port of atmst find_rpath_and_build_proof.
export function findRpathProof (ns, rootCid, key) {
  const proof = new Set()
  let cid = rootCid
  while (cid !== null && cid !== undefined) {
    const node = ns.getNode(cid)
    proof.add(cid.toString())
    const i = node.gteIndex(key)
    if (i < node.keys.length && node.keys[i] === key) return { value: node.vals[i], proof }
    cid = node.subtrees[i] // descend the subtree left of the first key >= target
  }
  return { value: null, proof }
}

// Build a NodeStore holding exactly the given blocks (cid-string -> { cid, bytes }).
export function nodeStoreFromBlocks (blocks) {
  const ns = new NodeStore()
  for (const [k, v] of blocks) ns.blocks.set(k, v)
  return ns
}

// Compute the minimal firehose block set for a single commit's ops.
//   oldRecords / newRecords : [{ key, value: CID }] — the record sets BEFORE/AFTER.
//   ops : [{ action:'create'|'update'|'delete', path, cid: CID|null, prev: CID|null }]
// Returns { blocks: Map<cidStr,{cid,bytes}>, dataCid, oldRoot } — MST nodes only
// (record + commit blocks are added by the caller). Throws if the backward replay
// does not reproduce the old root (i.e. the proof would be invalid).
export function firehoseProofBlocks ({ oldRecords, newRecords, ops }) {
  const oldB = buildMst(oldRecords)
  const newB = buildMst(newRecords)
  const oldRoot = oldB.root
  const newRoot = newB.root

  const oldSet = reachableBlocks(oldB.ns, oldRoot)
  const newSet = reachableBlocks(newB.ns, newRoot)

  // combined store holds every node of BOTH trees (proof reads span both)
  const combined = new NodeStore()
  for (const [k, v] of oldSet) combined.blocks.set(k, v)
  for (const [k, v] of newSet) combined.blocks.set(k, v)

  const proofCids = new Set()

  // created: new-tree nodes not present in the old tree
  for (const k of newSet.keys()) if (!oldSet.has(k)) proofCids.add(k)

  // deletion proofs: for each delete, the exclusion-proof path in the NEW tree
  for (const op of ops) {
    if (op.action !== 'delete') continue
    const { value, proof } = findRpathProof(combined, newRoot, op.path)
    if (value !== null) throw new Error(`delete proof: ${op.path} still present in new tree`)
    for (const c of proof) proofCids.add(c)
  }

  // inductive proof: replay ops backward from newRoot; every node read is required.
  const overlay = new OverlayNodeStore(combined)
  const w = new NodeWrangler(overlay)
  let inv = newRoot
  for (let i = ops.length - 1; i >= 0; i--) {
    const op = ops[i]
    if (op.action === 'create') {
      inv = w.delRecord(inv, op.path)
    } else { // update | delete → restore the prior value
      if (op.prev === null || op.prev === undefined) throw new Error(`inversion: ${op.action} ${op.path} missing prev`)
      inv = w.putRecord(inv, op.path, op.prev)
    }
  }
  if (!inv.equals(oldRoot)) throw new Error('inversion proof failed: backward replay did not reproduce prevData root')
  for (const k of overlay.gets) proofCids.add(k)

  const blocks = new Map()
  for (const k of proofCids) blocks.set(k, combined.blocks.get(k))
  return { blocks, dataCid: newRoot, oldRoot }
}
{
  "name": "@ipld/dag-cbor",
  "version": "9.2.7",
  "description": "JS implementation of DAG-CBOR",
  "author": "Rod <rod@vagg.org> (http://r.va.gg/)",
  "license": "Apache-2.0 OR MIT",
  "homepage": "https://github.com/ipld/js-dag-cbor#readme",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/ipld/js-dag-cbor.git"
  },
  "bugs": {
    "url": "https://github.com/ipld/js-dag-cbor/issues"
  },
  "publishConfig": {
    "access": "public",
    "provenance": true
  },
  "keywords": [
    "ipfs",
    "ipld",
    "multiformats"
  ],
  "type": "module",
  "types": "./dist/src/index.d.ts",
  "typesVersions": {
    "*": {
      "*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ],
      "src/*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ]
    }
  },
  "files": [
    "src",
    "dist",
    "!dist/test",
    "!**/*.tsbuildinfo"
  ],
  "exports": {
    ".": {
      "types": "./dist/src/index.d.ts",
      "import": "./src/index.js",
      "module-sync": "./src/index.js"
    }
  },
  "release": {
    "branches": [
      "master"
    ],
    "plugins": [
      [
        "@semantic-release/commit-analyzer",
        {
          "preset": "conventionalcommits",
          "releaseRules": [
            {
              "breaking": true,
              "release": "major"
            },
            {
              "revert": true,
              "release": "patch"
            },
            {
              "type": "feat",
              "release": "minor"
            },
            {
              "type": "fix",
              "release": "patch"
            },
            {
              "type": "docs",
              "release": "patch"
            },
            {
              "type": "test",
              "release": "patch"
            },
            {
              "type": "deps",
              "release": "patch"
            },
            {
              "scope": "no-release",
              "release": false
            }
          ]
        }
      ],
      [
        "@semantic-release/release-notes-generator",
        {
          "preset": "conventionalcommits",
          "presetConfig": {
            "types": [
              {
                "type": "feat",
                "section": "Features"
              },
              {
                "type": "fix",
                "section": "Bug Fixes"
              },
              {
                "type": "chore",
                "section": "Trivial Changes"
              },
              {
                "type": "docs",
                "section": "Documentation"
              },
              {
                "type": "deps",
                "section": "Dependencies"
              },
              {
                "type": "test",
                "section": "Tests"
              }
            ]
          }
        }
      ],
      "@semantic-release/changelog",
      "@semantic-release/npm",
      "@semantic-release/github",
      [
        "@semantic-release/git",
        {
          "assets": [
            "CHANGELOG.md",
            "package.json"
          ]
        }
      ]
    ]
  },
  "scripts": {
    "clean": "aegir clean",
    "lint": "aegir lint",
    "build": "aegir build",
    "release": "aegir release",
    "test": "npm run lint && aegir test",
    "test:ts": "npm run test --prefix test/ts-use",
    "test:node": "aegir test -t node --cov",
    "test:chrome": "aegir test -t browser --cov",
    "test:chrome-webworker": "aegir test -t webworker",
    "test:firefox": "aegir test -t browser -- --browser firefox",
    "test:firefox-webworker": "aegir test -t webworker -- --browser firefox",
    "test:electron-main": "aegir test -t electron-main",
    "dep-check": "aegir dep-check"
  },
  "dependencies": {
    "cborg": "^5.0.1",
    "multiformats": "^13.1.0"
  },
  "devDependencies": {
    "@ipld/garbage": "^6.0.0",
    "aegir": "^48.0.1"
  }
}
import * as cborg from 'cborg'
import { CID } from 'multiformats/cid'

// https://github.com/ipfs/go-ipfs/issues/3570#issuecomment-273931692
const CID_CBOR_TAG = 42

/**
 * @template T
 * @typedef {import('multiformats/codecs/interface').ByteView<T>} ByteView
 */

/**
 * @template T
 * @typedef {import('multiformats/codecs/interface').ArrayBufferView<T>} ArrayBufferView
 */

/**
 * @template T
 * @param {ByteView<T> | ArrayBufferView<T>} buf
 * @returns {ByteView<T>}
 */
export function toByteView (buf) {
  if (buf instanceof ArrayBuffer) {
    return new Uint8Array(buf, 0, buf.byteLength)
  }

  return buf
}

/**
 * cidEncoder will receive all Objects during encode, it needs to filter out
 * anything that's not a CID and return `null` for that so it's encoded as
 * normal.
 *
 * @param {any} obj
 * @returns {cborg.Token[]|null}
 */
function cidEncoder (obj) {
  if (obj.asCID !== obj && obj['/'] !== obj.bytes) {
    return null // any other kind of object
  }
  const cid = CID.asCID(obj)
  /* c8 ignore next 4 */
  // very unlikely case, and it'll probably throw a recursion error in cborg
  if (!cid) {
    return null
  }
  const bytes = new Uint8Array(cid.bytes.byteLength + 1)
  bytes.set(cid.bytes, 1) // prefix is 0x00, for historical reasons
  return [
    new cborg.Token(cborg.Type.tag, CID_CBOR_TAG),
    new cborg.Token(cborg.Type.bytes, bytes)
  ]
}

// eslint-disable-next-line jsdoc/require-returns-check
/**
 * Intercept all `undefined` values from an object walk and reject the entire
 * object if we find one.
 *
 * @returns {null}
 */
function undefinedEncoder () {
  throw new Error('`undefined` is not supported by the IPLD Data Model and cannot be encoded')
}

/**
 * Intercept all `number` values from an object walk and reject the entire
 * object if we find something that doesn't fit the IPLD data model (NaN &
 * Infinity).
 *
 * @param {number} num
 * @returns {null}
 */
function numberEncoder (num) {
  if (Number.isNaN(num)) {
    throw new Error('`NaN` is not supported by the IPLD Data Model and cannot be encoded')
  }
  if (num === Infinity || num === -Infinity) {
    throw new Error('`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded')
  }
  return null
}

/**
 * @param {Map<any, any>} map
 * @returns {null}
 */
function mapEncoder (map) {
  for (const key of map.keys()) {
    if (typeof key !== 'string' || key.length === 0) {
      throw new Error('Non-string Map keys are not supported by the IPLD Data Model and cannot be encoded')
    }
  }
  return null
}

const _encodeOptions = {
  float64: true,
  typeEncoders: {
    Map: mapEncoder,
    Object: cidEncoder,
    undefined: undefinedEncoder,
    number: numberEncoder
  }
}

export const encodeOptions = {
  ..._encodeOptions,
  typeEncoders: {
    ..._encodeOptions.typeEncoders
  }
}

/**
 * @param {import('cborg').TagDecodeControl} decode
 * @returns {CID}
 */
function cidDecoder (decode) {
  const bytes = /** @type {Uint8Array} */ (decode())
  if (bytes[0] !== 0) {
    throw new Error('Invalid CID for CBOR tag 42; expected leading 0x00')
  }
  return CID.decode(bytes.subarray(1)) // ignore leading 0x00
}

const _decodeOptions = {
  allowIndefinite: false,
  coerceUndefinedToNull: true,
  allowNaN: false,
  allowInfinity: false,
  allowBigInt: true, // this will lead to BigInt for ints outside of
  // safe-integer range, which may surprise users
  strict: true,
  useMaps: false,
  rejectDuplicateMapKeys: true,
  /** @type {{ [tagNumber: number]: import('cborg').TagDecoder }} */
  tags: { [CID_CBOR_TAG]: cidDecoder }
}

export const decodeOptions = {
  ..._decodeOptions,
  tags: { ..._decodeOptions.tags }
}

export const name = 'dag-cbor'
export const code = 0x71

/**
 * @template T
 * @param {T} node
 * @returns {ByteView<T>}
 */
export const encode = (node) => cborg.encode(node, _encodeOptions)

/**
 * @template T
 * @param {ByteView<T> | ArrayBufferView<T>} data
 * @returns {T}
 */
export const decode = (data) => cborg.decode(toByteView(data), _decodeOptions)
/**
 * Utilities for short weierstrass curves, combined with noble-hashes.
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { weierstrass } from "./abstract/weierstrass.js";
/** connects noble-curves to noble-hashes */
export function getHash(hash) {
    return { hash };
}
/** @deprecated use new `weierstrass()` and `ecdsa()` methods */
export function createCurve(curveDef, defHash) {
    const create = (hash) => weierstrass({ ...curveDef, hash: hash });
    return { ...create(defHash), create };
}
//# sourceMappingURL=_shortw_utils.js.map/**
 * Methods for elliptic curve multiplication by scalars.
 * Contains wNAF, pippenger.
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { bitLen, bitMask, validateObject } from "../utils.js";
import { Field, FpInvertBatch, nLength, validateField } from "./modular.js";
const _0n = BigInt(0);
const _1n = BigInt(1);
export function negateCt(condition, item) {
    const neg = item.negate();
    return condition ? neg : item;
}
/**
 * Takes a bunch of Projective Points but executes only one
 * inversion on all of them. Inversion is very slow operation,
 * so this improves performance massively.
 * Optimization: converts a list of projective points to a list of identical points with Z=1.
 */
export function normalizeZ(c, points) {
    const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
    return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
}
function validateW(W, bits) {
    if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
        throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);
}
function calcWOpts(W, scalarBits) {
    validateW(W, scalarBits);
    const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero
    const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero
    const maxNumber = 2 ** W; // W=8 256
    const mask = bitMask(W); // W=8 255 == mask 0b11111111
    const shiftBy = BigInt(W); // W=8 8
    return { windows, windowSize, mask, maxNumber, shiftBy };
}
function calcOffsets(n, window, wOpts) {
    const { windowSize, mask, maxNumber, shiftBy } = wOpts;
    let wbits = Number(n & mask); // extract W bits.
    let nextN = n >> shiftBy; // shift number by W bits.
    // What actually happens here:
    // const highestBit = Number(mask ^ (mask >> 1n));
    // let wbits2 = wbits - 1; // skip zero
    // if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);
    // split if bits > max: +224 => 256-32
    if (wbits > windowSize) {
        // we skip zero, which means instead of `>= size-1`, we do `> size`
        wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.
        nextN += _1n; // +256 (carry)
    }
    const offsetStart = window * windowSize;
    const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero
    const isZero = wbits === 0; // is current window slice a 0?
    const isNeg = wbits < 0; // is current window slice negative?
    const isNegF = window % 2 !== 0; // fake random statement for noise
    const offsetF = offsetStart; // fake offset for noise
    return { nextN, offset, isZero, isNeg, isNegF, offsetF };
}
function validateMSMPoints(points, c) {
    if (!Array.isArray(points))
        throw new Error('array expected');
    points.forEach((p, i) => {
        if (!(p instanceof c))
            throw new Error('invalid point at index ' + i);
    });
}
function validateMSMScalars(scalars, field) {
    if (!Array.isArray(scalars))
        throw new Error('array of scalars expected');
    scalars.forEach((s, i) => {
        if (!field.isValid(s))
            throw new Error('invalid scalar at index ' + i);
    });
}
// Since points in different groups cannot be equal (different object constructor),
// we can have single place to store precomputes.
// Allows to make points frozen / immutable.
const pointPrecomputes = new WeakMap();
const pointWindowSizes = new WeakMap();
function getW(P) {
    // To disable precomputes:
    // return 1;
    return pointWindowSizes.get(P) || 1;
}
function assert0(n) {
    if (n !== _0n)
        throw new Error('invalid wNAF');
}
/**
 * Elliptic curve multiplication of Point by scalar. Fragile.
 * Table generation takes **30MB of ram and 10ms on high-end CPU**,
 * but may take much longer on slow devices. Actual generation will happen on
 * first call of `multiply()`. By default, `BASE` point is precomputed.
 *
 * Scalars should always be less than curve order: this should be checked inside of a curve itself.
 * Creates precomputation tables for fast multiplication:
 * - private scalar is split by fixed size windows of W bits
 * - every window point is collected from window's table & added to accumulator
 * - since windows are different, same point inside tables won't be accessed more than once per calc
 * - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)
 * - +1 window is neccessary for wNAF
 * - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication
 *
 * @todo Research returning 2d JS array of windows, instead of a single window.
 * This would allow windows to be in different memory locations
 */
export class wNAF {
    // Parametrized with a given Point class (not individual point)
    constructor(Point, bits) {
        this.BASE = Point.BASE;
        this.ZERO = Point.ZERO;
        this.Fn = Point.Fn;
        this.bits = bits;
    }
    // non-const time multiplication ladder
    _unsafeLadder(elm, n, p = this.ZERO) {
        let d = elm;
        while (n > _0n) {
            if (n & _1n)
                p = p.add(d);
            d = d.double();
            n >>= _1n;
        }
        return p;
    }
    /**
     * Creates a wNAF precomputation window. Used for caching.
     * Default window size is set by `utils.precompute()` and is equal to 8.
     * Number of precomputed points depends on the curve size:
     * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
     * - 𝑊 is the window size
     * - 𝑛 is the bitlength of the curve order.
     * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
     * @param point Point instance
     * @param W window size
     * @returns precomputed point tables flattened to a single array
     */
    precomputeWindow(point, W) {
        const { windows, windowSize } = calcWOpts(W, this.bits);
        const points = [];
        let p = point;
        let base = p;
        for (let window = 0; window < windows; window++) {
            base = p;
            points.push(base);
            // i=1, bc we skip 0
            for (let i = 1; i < windowSize; i++) {
                base = base.add(p);
                points.push(base);
            }
            p = base.double();
        }
        return points;
    }
    /**
     * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
     * More compact implementation:
     * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
     * @returns real and fake (for const-time) points
     */
    wNAF(W, precomputes, n) {
        // Scalar should be smaller than field order
        if (!this.Fn.isValid(n))
            throw new Error('invalid scalar');
        // Accumulators
        let p = this.ZERO;
        let f = this.BASE;
        // This code was first written with assumption that 'f' and 'p' will never be infinity point:
        // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,
        // there is negate now: it is possible that negated element from low value
        // would be the same as high element, which will create carry into next window.
        // It's not obvious how this can fail, but still worth investigating later.
        const wo = calcWOpts(W, this.bits);
        for (let window = 0; window < wo.windows; window++) {
            // (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise
            const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
            n = nextN;
            if (isZero) {
                // bits are 0: add garbage to fake point
                // Important part for const-time getPublicKey: add random "noise" point to f.
                f = f.add(negateCt(isNegF, precomputes[offsetF]));
            }
            else {
                // bits are 1: add to result point
                p = p.add(negateCt(isNeg, precomputes[offset]));
            }
        }
        assert0(n);
        // Return both real and fake points: JIT won't eliminate f.
        // At this point there is a way to F be infinity-point even if p is not,
        // which makes it less const-time: around 1 bigint multiply.
        return { p, f };
    }
    /**
     * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
     * @param acc accumulator point to add result of multiplication
     * @returns point
     */
    wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
        const wo = calcWOpts(W, this.bits);
        for (let window = 0; window < wo.windows; window++) {
            if (n === _0n)
                break; // Early-exit, skip 0 value
            const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
            n = nextN;
            if (isZero) {
                // Window bits are 0: skip processing.
                // Move to next window.
                continue;
            }
            else {
                const item = precomputes[offset];
                acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM
            }
        }
        assert0(n);
        return acc;
    }
    getPrecomputes(W, point, transform) {
        // Calculate precomputes on a first run, reuse them after
        let comp = pointPrecomputes.get(point);
        if (!comp) {
            comp = this.precomputeWindow(point, W);
            if (W !== 1) {
                // Doing transform outside of if brings 15% perf hit
                if (typeof transform === 'function')
                    comp = transform(comp);
                pointPrecomputes.set(point, comp);
            }
        }
        return comp;
    }
    cached(point, scalar, transform) {
        const W = getW(point);
        return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
    }
    unsafe(point, scalar, transform, prev) {
        const W = getW(point);
        if (W === 1)
            return this._unsafeLadder(point, scalar, prev); // For W=1 ladder is ~x2 faster
        return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
    }
    // We calculate precomputes for elliptic curve point multiplication
    // using windowed method. This specifies window size and
    // stores precomputed values. Usually only base point would be precomputed.
    createCache(P, W) {
        validateW(W, this.bits);
        pointWindowSizes.set(P, W);
        pointPrecomputes.delete(P);
    }
    hasCache(elm) {
        return getW(elm) !== 1;
    }
}
/**
 * Endomorphism-specific multiplication for Koblitz curves.
 * Cost: 128 dbl, 0-256 adds.
 */
export function mulEndoUnsafe(Point, point, k1, k2) {
    let acc = point;
    let p1 = Point.ZERO;
    let p2 = Point.ZERO;
    while (k1 > _0n || k2 > _0n) {
        if (k1 & _1n)
            p1 = p1.add(acc);
        if (k2 & _1n)
            p2 = p2.add(acc);
        acc = acc.double();
        k1 >>= _1n;
        k2 >>= _1n;
    }
    return { p1, p2 };
}
/**
 * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).
 * 30x faster vs naive addition on L=4096, 10x faster than precomputes.
 * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.
 * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.
 * @param c Curve Point constructor
 * @param fieldN field over CURVE.N - important that it's not over CURVE.P
 * @param points array of L curve points
 * @param scalars array of L scalars (aka secret keys / bigints)
 */
export function pippenger(c, fieldN, points, scalars) {
    // If we split scalars by some window (let's say 8 bits), every chunk will only
    // take 256 buckets even if there are 4096 scalars, also re-uses double.
    // TODO:
    // - https://eprint.iacr.org/2024/750.pdf
    // - https://tches.iacr.org/index.php/TCHES/article/view/10287
    // 0 is accepted in scalars
    validateMSMPoints(points, c);
    validateMSMScalars(scalars, fieldN);
    const plength = points.length;
    const slength = scalars.length;
    if (plength !== slength)
        throw new Error('arrays of points and scalars must have equal length');
    // if (plength === 0) throw new Error('array must be of length >= 2');
    const zero = c.ZERO;
    const wbits = bitLen(BigInt(plength));
    let windowSize = 1; // bits
    if (wbits > 12)
        windowSize = wbits - 3;
    else if (wbits > 4)
        windowSize = wbits - 2;
    else if (wbits > 0)
        windowSize = 2;
    const MASK = bitMask(windowSize);
    const buckets = new Array(Number(MASK) + 1).fill(zero); // +1 for zero array
    const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;
    let sum = zero;
    for (let i = lastBits; i >= 0; i -= windowSize) {
        buckets.fill(zero);
        for (let j = 0; j < slength; j++) {
            const scalar = scalars[j];
            const wbits = Number((scalar >> BigInt(i)) & MASK);
            buckets[wbits] = buckets[wbits].add(points[j]);
        }
        let resI = zero; // not using this will do small speed-up, but will lose ct
        // Skip first bucket, because it is zero
        for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {
            sumI = sumI.add(buckets[j]);
            resI = resI.add(sumI);
        }
        sum = sum.add(resI);
        if (i !== 0)
            for (let j = 0; j < windowSize; j++)
                sum = sum.double();
    }
    return sum;
}
/**
 * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).
 * @param c Curve Point constructor
 * @param fieldN field over CURVE.N - important that it's not over CURVE.P
 * @param points array of L curve points
 * @returns function which multiplies points with scaars
 */
export function precomputeMSMUnsafe(c, fieldN, points, windowSize) {
    /**
     * Performance Analysis of Window-based Precomputation
     *
     * Base Case (256-bit scalar, 8-bit window):
     * - Standard precomputation requires:
     *   - 31 additions per scalar × 256 scalars = 7,936 ops
     *   - Plus 255 summary additions = 8,191 total ops
     *   Note: Summary additions can be optimized via accumulator
     *
     * Chunked Precomputation Analysis:
     * - Using 32 chunks requires:
     *   - 255 additions per chunk
     *   - 256 doublings
     *   - Total: (255 × 32) + 256 = 8,416 ops
     *
     * Memory Usage Comparison:
     * Window Size | Standard Points | Chunked Points
     * ------------|-----------------|---------------
     *     4-bit   |     520         |      15
     *     8-bit   |    4,224        |     255
     *    10-bit   |   13,824        |   1,023
     *    16-bit   |  557,056        |  65,535
     *
     * Key Advantages:
     * 1. Enables larger window sizes due to reduced memory overhead
     * 2. More efficient for smaller scalar counts:
     *    - 16 chunks: (16 × 255) + 256 = 4,336 ops
     *    - ~2x faster than standard 8,191 ops
     *
     * Limitations:
     * - Not suitable for plain precomputes (requires 256 constant doublings)
     * - Performance degrades with larger scalar counts:
     *   - Optimal for ~256 scalars
     *   - Less efficient for 4096+ scalars (Pippenger preferred)
     */
    validateW(windowSize, fieldN.BITS);
    validateMSMPoints(points, c);
    const zero = c.ZERO;
    const tableSize = 2 ** windowSize - 1; // table size (without zero)
    const chunks = Math.ceil(fieldN.BITS / windowSize); // chunks of item
    const MASK = bitMask(windowSize);
    const tables = points.map((p) => {
        const res = [];
        for (let i = 0, acc = p; i < tableSize; i++) {
            res.push(acc);
            acc = acc.add(p);
        }
        return res;
    });
    return (scalars) => {
        validateMSMScalars(scalars, fieldN);
        if (scalars.length > points.length)
            throw new Error('array of scalars must be smaller than array of points');
        let res = zero;
        for (let i = 0; i < chunks; i++) {
            // No need to double if accumulator is still zero.
            if (res !== zero)
                for (let j = 0; j < windowSize; j++)
                    res = res.double();
            const shiftBy = BigInt(chunks * windowSize - (i + 1) * windowSize);
            for (let j = 0; j < scalars.length; j++) {
                const n = scalars[j];
                const curr = Number((n >> shiftBy) & MASK);
                if (!curr)
                    continue; // skip zero scalars chunks
                res = res.add(tables[j][curr - 1]);
            }
        }
        return res;
    };
}
// TODO: remove
/** @deprecated */
export function validateBasic(curve) {
    validateField(curve.Fp);
    validateObject(curve, {
        n: 'bigint',
        h: 'bigint',
        Gx: 'field',
        Gy: 'field',
    }, {
        nBitLength: 'isSafeInteger',
        nByteLength: 'isSafeInteger',
    });
    // Set defaults
    return Object.freeze({
        ...nLength(curve.n, curve.nBitLength),
        ...curve,
        ...{ p: curve.Fp.ORDER },
    });
}
function createField(order, field, isLE) {
    if (field) {
        if (field.ORDER !== order)
            throw new Error('Field.ORDER must match order: Fp == p, Fn == n');
        validateField(field);
        return field;
    }
    else {
        return Field(order, { isLE });
    }
}
/** Validates CURVE opts and creates fields */
export function _createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
    if (FpFnLE === undefined)
        FpFnLE = type === 'edwards';
    if (!CURVE || typeof CURVE !== 'object')
        throw new Error(`expected valid ${type} CURVE object`);
    for (const p of ['p', 'n', 'h']) {
        const val = CURVE[p];
        if (!(typeof val === 'bigint' && val > _0n))
            throw new Error(`CURVE.${p} must be positive bigint`);
    }
    const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);
    const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
    const _b = type === 'weierstrass' ? 'b' : 'd';
    const params = ['Gx', 'Gy', 'a', _b];
    for (const p of params) {
        // @ts-ignore
        if (!Fp.isValid(CURVE[p]))
            throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
    }
    CURVE = Object.freeze(Object.assign({}, CURVE));
    return { CURVE, Fp, Fn };
}
//# sourceMappingURL=curve.js.mapimport { _validateObject, abytes, bytesToNumberBE, concatBytes, isBytes, isHash, utf8ToBytes, } from "../utils.js";
import { FpInvertBatch, mod } from "./modular.js";
// Octet Stream to Integer. "spec" implementation of os2ip is 2.5x slower vs bytesToNumberBE.
const os2ip = bytesToNumberBE;
// Integer to Octet Stream (numberToBytesBE)
function i2osp(value, length) {
    anum(value);
    anum(length);
    if (value < 0 || value >= 1 << (8 * length))
        throw new Error('invalid I2OSP input: ' + value);
    const res = Array.from({ length }).fill(0);
    for (let i = length - 1; i >= 0; i--) {
        res[i] = value & 0xff;
        value >>>= 8;
    }
    return new Uint8Array(res);
}
function strxor(a, b) {
    const arr = new Uint8Array(a.length);
    for (let i = 0; i < a.length; i++) {
        arr[i] = a[i] ^ b[i];
    }
    return arr;
}
function anum(item) {
    if (!Number.isSafeInteger(item))
        throw new Error('number expected');
}
function normDST(DST) {
    if (!isBytes(DST) && typeof DST !== 'string')
        throw new Error('DST must be Uint8Array or string');
    return typeof DST === 'string' ? utf8ToBytes(DST) : DST;
}
/**
 * Produces a uniformly random byte string using a cryptographic hash function H that outputs b bits.
 * [RFC 9380 5.3.1](https://www.rfc-editor.org/rfc/rfc9380#section-5.3.1).
 */
export function expand_message_xmd(msg, DST, lenInBytes, H) {
    abytes(msg);
    anum(lenInBytes);
    DST = normDST(DST);
    // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3
    if (DST.length > 255)
        DST = H(concatBytes(utf8ToBytes('H2C-OVERSIZE-DST-'), DST));
    const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H;
    const ell = Math.ceil(lenInBytes / b_in_bytes);
    if (lenInBytes > 65535 || ell > 255)
        throw new Error('expand_message_xmd: invalid lenInBytes');
    const DST_prime = concatBytes(DST, i2osp(DST.length, 1));
    const Z_pad = i2osp(0, r_in_bytes);
    const l_i_b_str = i2osp(lenInBytes, 2); // len_in_bytes_str
    const b = new Array(ell);
    const b_0 = H(concatBytes(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));
    b[0] = H(concatBytes(b_0, i2osp(1, 1), DST_prime));
    for (let i = 1; i <= ell; i++) {
        const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime];
        b[i] = H(concatBytes(...args));
    }
    const pseudo_random_bytes = concatBytes(...b);
    return pseudo_random_bytes.slice(0, lenInBytes);
}
/**
 * Produces a uniformly random byte string using an extendable-output function (XOF) H.
 * 1. The collision resistance of H MUST be at least k bits.
 * 2. H MUST be an XOF that has been proved indifferentiable from
 *    a random oracle under a reasonable cryptographic assumption.
 * [RFC 9380 5.3.2](https://www.rfc-editor.org/rfc/rfc9380#section-5.3.2).
 */
export function expand_message_xof(msg, DST, lenInBytes, k, H) {
    abytes(msg);
    anum(lenInBytes);
    DST = normDST(DST);
    // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3
    // DST = H('H2C-OVERSIZE-DST-' || a_very_long_DST, Math.ceil((lenInBytes * k) / 8));
    if (DST.length > 255) {
        const dkLen = Math.ceil((2 * k) / 8);
        DST = H.create({ dkLen }).update(utf8ToBytes('H2C-OVERSIZE-DST-')).update(DST).digest();
    }
    if (lenInBytes > 65535 || DST.length > 255)
        throw new Error('expand_message_xof: invalid lenInBytes');
    return (H.create({ dkLen: lenInBytes })
        .update(msg)
        .update(i2osp(lenInBytes, 2))
        // 2. DST_prime = DST || I2OSP(len(DST), 1)
        .update(DST)
        .update(i2osp(DST.length, 1))
        .digest());
}
/**
 * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F.
 * [RFC 9380 5.2](https://www.rfc-editor.org/rfc/rfc9380#section-5.2).
 * @param msg a byte string containing the message to hash
 * @param count the number of elements of F to output
 * @param options `{DST: string, p: bigint, m: number, k: number, expand: 'xmd' | 'xof', hash: H}`, see above
 * @returns [u_0, ..., u_(count - 1)], a list of field elements.
 */
export function hash_to_field(msg, count, options) {
    _validateObject(options, {
        p: 'bigint',
        m: 'number',
        k: 'number',
        hash: 'function',
    });
    const { p, k, m, hash, expand, DST } = options;
    if (!isHash(options.hash))
        throw new Error('expected valid hash');
    abytes(msg);
    anum(count);
    const log2p = p.toString(2).length;
    const L = Math.ceil((log2p + k) / 8); // section 5.1 of ietf draft link above
    const len_in_bytes = count * m * L;
    let prb; // pseudo_random_bytes
    if (expand === 'xmd') {
        prb = expand_message_xmd(msg, DST, len_in_bytes, hash);
    }
    else if (expand === 'xof') {
        prb = expand_message_xof(msg, DST, len_in_bytes, k, hash);
    }
    else if (expand === '_internal_pass') {
        // for internal tests only
        prb = msg;
    }
    else {
        throw new Error('expand must be "xmd" or "xof"');
    }
    const u = new Array(count);
    for (let i = 0; i < count; i++) {
        const e = new Array(m);
        for (let j = 0; j < m; j++) {
            const elm_offset = L * (j + i * m);
            const tv = prb.subarray(elm_offset, elm_offset + L);
            e[j] = mod(os2ip(tv), p);
        }
        u[i] = e;
    }
    return u;
}
export function isogenyMap(field, map) {
    // Make same order as in spec
    const coeff = map.map((i) => Array.from(i).reverse());
    return (x, y) => {
        const [xn, xd, yn, yd] = coeff.map((val) => val.reduce((acc, i) => field.add(field.mul(acc, x), i)));
        // 6.6.3
        // Exceptional cases of iso_map are inputs that cause the denominator of
        // either rational function to evaluate to zero; such cases MUST return
        // the identity point on E.
        const [xd_inv, yd_inv] = FpInvertBatch(field, [xd, yd], true);
        x = field.mul(xn, xd_inv); // xNum / xDen
        y = field.mul(y, field.mul(yn, yd_inv)); // y * (yNum / yDev)
        return { x, y };
    };
}
export const _DST_scalar = utf8ToBytes('HashToScalar-');
/** Creates hash-to-curve methods from EC Point and mapToCurve function. See {@link H2CHasher}. */
export function createHasher(Point, mapToCurve, defaults) {
    if (typeof mapToCurve !== 'function')
        throw new Error('mapToCurve() must be defined');
    function map(num) {
        return Point.fromAffine(mapToCurve(num));
    }
    function clear(initial) {
        const P = initial.clearCofactor();
        if (P.equals(Point.ZERO))
            return Point.ZERO; // zero will throw in assert
        P.assertValidity();
        return P;
    }
    return {
        defaults,
        hashToCurve(msg, options) {
            const opts = Object.assign({}, defaults, options);
            const u = hash_to_field(msg, 2, opts);
            const u0 = map(u[0]);
            const u1 = map(u[1]);
            return clear(u0.add(u1));
        },
        encodeToCurve(msg, options) {
            const optsDst = defaults.encodeDST ? { DST: defaults.encodeDST } : {};
            const opts = Object.assign({}, defaults, optsDst, options);
            const u = hash_to_field(msg, 1, opts);
            const u0 = map(u[0]);
            return clear(u0);
        },
        /** See {@link H2CHasher} */
        mapToCurve(scalars) {
            if (!Array.isArray(scalars))
                throw new Error('expected array of bigints');
            for (const i of scalars)
                if (typeof i !== 'bigint')
                    throw new Error('expected array of bigints');
            return clear(map(scalars));
        },
        // hash_to_scalar can produce 0: https://www.rfc-editor.org/errata/eid8393
        // RFC 9380, draft-irtf-cfrg-bbs-signatures-08
        hashToScalar(msg, options) {
            // @ts-ignore
            const N = Point.Fn.ORDER;
            const opts = Object.assign({}, defaults, { p: N, m: 1, DST: _DST_scalar }, options);
            return hash_to_field(msg, 1, opts)[0][0];
        },
    };
}
//# sourceMappingURL=hash-to-curve.js.map/**
 * Utils for modular division and fields.
 * Field over 11 is a finite (Galois) field is integer number operations `mod 11`.
 * There is no division: it is replaced by modular multiplicative inverse.
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { _validateObject, anumber, bitMask, bytesToNumberBE, bytesToNumberLE, ensureBytes, numberToBytesBE, numberToBytesLE, } from "../utils.js";
// prettier-ignore
const _0n = BigInt(0), _1n = BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3);
// prettier-ignore
const _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5), _7n = /* @__PURE__ */ BigInt(7);
// prettier-ignore
const _8n = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9), _16n = /* @__PURE__ */ BigInt(16);
// Calculates a modulo b
export function mod(a, b) {
    const result = a % b;
    return result >= _0n ? result : b + result;
}
/**
 * Efficiently raise num to power and do modular division.
 * Unsafe in some contexts: uses ladder, so can expose bigint bits.
 * @example
 * pow(2n, 6n, 11n) // 64n % 11n == 9n
 */
export function pow(num, power, modulo) {
    return FpPow(Field(modulo), num, power);
}
/** Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)` */
export function pow2(x, power, modulo) {
    let res = x;
    while (power-- > _0n) {
        res *= res;
        res %= modulo;
    }
    return res;
}
/**
 * Inverses number over modulo.
 * Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).
 */
export function invert(number, modulo) {
    if (number === _0n)
        throw new Error('invert: expected non-zero number');
    if (modulo <= _0n)
        throw new Error('invert: expected positive modulus, got ' + modulo);
    // Fermat's little theorem "CT-like" version inv(n) = n^(m-2) mod m is 30x slower.
    let a = mod(number, modulo);
    let b = modulo;
    // prettier-ignore
    let x = _0n, y = _1n, u = _1n, v = _0n;
    while (a !== _0n) {
        // JIT applies optimization if those two lines follow each other
        const q = b / a;
        const r = b % a;
        const m = x - u * q;
        const n = y - v * q;
        // prettier-ignore
        b = a, a = r, x = u, y = v, u = m, v = n;
    }
    const gcd = b;
    if (gcd !== _1n)
        throw new Error('invert: does not exist');
    return mod(x, modulo);
}
function assertIsSquare(Fp, root, n) {
    if (!Fp.eql(Fp.sqr(root), n))
        throw new Error('Cannot find square root');
}
// Not all roots are possible! Example which will throw:
// const NUM =
// n = 72057594037927816n;
// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));
function sqrt3mod4(Fp, n) {
    const p1div4 = (Fp.ORDER + _1n) / _4n;
    const root = Fp.pow(n, p1div4);
    assertIsSquare(Fp, root, n);
    return root;
}
function sqrt5mod8(Fp, n) {
    const p5div8 = (Fp.ORDER - _5n) / _8n;
    const n2 = Fp.mul(n, _2n);
    const v = Fp.pow(n2, p5div8);
    const nv = Fp.mul(n, v);
    const i = Fp.mul(Fp.mul(nv, _2n), v);
    const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
    assertIsSquare(Fp, root, n);
    return root;
}
// Based on RFC9380, Kong algorithm
// prettier-ignore
function sqrt9mod16(P) {
    const Fp_ = Field(P);
    const tn = tonelliShanks(P);
    const c1 = tn(Fp_, Fp_.neg(Fp_.ONE)); //  1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F
    const c2 = tn(Fp_, c1); //  2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F
    const c3 = tn(Fp_, Fp_.neg(c1)); //  3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F
    const c4 = (P + _7n) / _16n; //  4. c4 = (q + 7) / 16        # Integer arithmetic
    return (Fp, n) => {
        let tv1 = Fp.pow(n, c4); //  1. tv1 = x^c4
        let tv2 = Fp.mul(tv1, c1); //  2. tv2 = c1 * tv1
        const tv3 = Fp.mul(tv1, c2); //  3. tv3 = c2 * tv1
        const tv4 = Fp.mul(tv1, c3); //  4. tv4 = c3 * tv1
        const e1 = Fp.eql(Fp.sqr(tv2), n); //  5.  e1 = (tv2^2) == x
        const e2 = Fp.eql(Fp.sqr(tv3), n); //  6.  e2 = (tv3^2) == x
        tv1 = Fp.cmov(tv1, tv2, e1); //  7. tv1 = CMOV(tv1, tv2, e1)  # Select tv2 if (tv2^2) == x
        tv2 = Fp.cmov(tv4, tv3, e2); //  8. tv2 = CMOV(tv4, tv3, e2)  # Select tv3 if (tv3^2) == x
        const e3 = Fp.eql(Fp.sqr(tv2), n); //  9.  e3 = (tv2^2) == x
        const root = Fp.cmov(tv1, tv2, e3); // 10.  z = CMOV(tv1, tv2, e3)   # Select sqrt from tv1 & tv2
        assertIsSquare(Fp, root, n);
        return root;
    };
}
/**
 * Tonelli-Shanks square root search algorithm.
 * 1. https://eprint.iacr.org/2012/685.pdf (page 12)
 * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks
 * @param P field order
 * @returns function that takes field Fp (created from P) and number n
 */
export function tonelliShanks(P) {
    // Initialization (precomputation).
    // Caching initialization could boost perf by 7%.
    if (P < _3n)
        throw new Error('sqrt is not defined for small field');
    // Factor P - 1 = Q * 2^S, where Q is odd
    let Q = P - _1n;
    let S = 0;
    while (Q % _2n === _0n) {
        Q /= _2n;
        S++;
    }
    // Find the first quadratic non-residue Z >= 2
    let Z = _2n;
    const _Fp = Field(P);
    while (FpLegendre(_Fp, Z) === 1) {
        // Basic primality test for P. After x iterations, chance of
        // not finding quadratic non-residue is 2^x, so 2^1000.
        if (Z++ > 1000)
            throw new Error('Cannot find square root: probably non-prime P');
    }
    // Fast-path; usually done before Z, but we do "primality test".
    if (S === 1)
        return sqrt3mod4;
    // Slow-path
    // TODO: test on Fp2 and others
    let cc = _Fp.pow(Z, Q); // c = z^Q
    const Q1div2 = (Q + _1n) / _2n;
    return function tonelliSlow(Fp, n) {
        if (Fp.is0(n))
            return n;
        // Check if n is a quadratic residue using Legendre symbol
        if (FpLegendre(Fp, n) !== 1)
            throw new Error('Cannot find square root');
        // Initialize variables for the main loop
        let M = S;
        let c = Fp.mul(Fp.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp
        let t = Fp.pow(n, Q); // t = n^Q, first guess at the fudge factor
        let R = Fp.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root
        // Main loop
        // while t != 1
        while (!Fp.eql(t, Fp.ONE)) {
            if (Fp.is0(t))
                return Fp.ZERO; // if t=0 return R=0
            let i = 1;
            // Find the smallest i >= 1 such that t^(2^i) ≡ 1 (mod P)
            let t_tmp = Fp.sqr(t); // t^(2^1)
            while (!Fp.eql(t_tmp, Fp.ONE)) {
                i++;
                t_tmp = Fp.sqr(t_tmp); // t^(2^2)...
                if (i === M)
                    throw new Error('Cannot find square root');
            }
            // Calculate the exponent for b: 2^(M - i - 1)
            const exponent = _1n << BigInt(M - i - 1); // bigint is important
            const b = Fp.pow(c, exponent); // b = 2^(M - i - 1)
            // Update variables
            M = i;
            c = Fp.sqr(b); // c = b^2
            t = Fp.mul(t, c); // t = (t * b^2)
            R = Fp.mul(R, b); // R = R*b
        }
        return R;
    };
}
/**
 * Square root for a finite field. Will try optimized versions first:
 *
 * 1. P ≡ 3 (mod 4)
 * 2. P ≡ 5 (mod 8)
 * 3. P ≡ 9 (mod 16)
 * 4. Tonelli-Shanks algorithm
 *
 * Different algorithms can give different roots, it is up to user to decide which one they want.
 * For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).
 */
export function FpSqrt(P) {
    // P ≡ 3 (mod 4) => √n = n^((P+1)/4)
    if (P % _4n === _3n)
        return sqrt3mod4;
    // P ≡ 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf
    if (P % _8n === _5n)
        return sqrt5mod8;
    // P ≡ 9 (mod 16) => Kong algorithm, page 11 of https://eprint.iacr.org/2012/685.pdf (algorithm 4)
    if (P % _16n === _9n)
        return sqrt9mod16(P);
    // Tonelli-Shanks algorithm
    return tonelliShanks(P);
}
// Little-endian check for first LE bit (last BE bit);
export const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n;
// prettier-ignore
const FIELD_FIELDS = [
    'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',
    'eql', 'add', 'sub', 'mul', 'pow', 'div',
    'addN', 'subN', 'mulN', 'sqrN'
];
export function validateField(field) {
    const initial = {
        ORDER: 'bigint',
        MASK: 'bigint',
        BYTES: 'number',
        BITS: 'number',
    };
    const opts = FIELD_FIELDS.reduce((map, val) => {
        map[val] = 'function';
        return map;
    }, initial);
    _validateObject(field, opts);
    // const max = 16384;
    // if (field.BYTES < 1 || field.BYTES > max) throw new Error('invalid field');
    // if (field.BITS < 1 || field.BITS > 8 * max) throw new Error('invalid field');
    return field;
}
// Generic field functions
/**
 * Same as `pow` but for Fp: non-constant-time.
 * Unsafe in some contexts: uses ladder, so can expose bigint bits.
 */
export function FpPow(Fp, num, power) {
    if (power < _0n)
        throw new Error('invalid exponent, negatives unsupported');
    if (power === _0n)
        return Fp.ONE;
    if (power === _1n)
        return num;
    let p = Fp.ONE;
    let d = num;
    while (power > _0n) {
        if (power & _1n)
            p = Fp.mul(p, d);
        d = Fp.sqr(d);
        power >>= _1n;
    }
    return p;
}
/**
 * Efficiently invert an array of Field elements.
 * Exception-free. Will return `undefined` for 0 elements.
 * @param passZero map 0 to 0 (instead of undefined)
 */
export function FpInvertBatch(Fp, nums, passZero = false) {
    const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : undefined);
    // Walk from first to last, multiply them by each other MOD p
    const multipliedAcc = nums.reduce((acc, num, i) => {
        if (Fp.is0(num))
            return acc;
        inverted[i] = acc;
        return Fp.mul(acc, num);
    }, Fp.ONE);
    // Invert last element
    const invertedAcc = Fp.inv(multipliedAcc);
    // Walk from last to first, multiply them by inverted each other MOD p
    nums.reduceRight((acc, num, i) => {
        if (Fp.is0(num))
            return acc;
        inverted[i] = Fp.mul(acc, inverted[i]);
        return Fp.mul(acc, num);
    }, invertedAcc);
    return inverted;
}
// TODO: remove
export function FpDiv(Fp, lhs, rhs) {
    return Fp.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, Fp.ORDER) : Fp.inv(rhs));
}
/**
 * Legendre symbol.
 * Legendre constant is used to calculate Legendre symbol (a | p)
 * which denotes the value of a^((p-1)/2) (mod p).
 *
 * * (a | p) ≡ 1    if a is a square (mod p), quadratic residue
 * * (a | p) ≡ -1   if a is not a square (mod p), quadratic non residue
 * * (a | p) ≡ 0    if a ≡ 0 (mod p)
 */
export function FpLegendre(Fp, n) {
    // We can use 3rd argument as optional cache of this value
    // but seems unneeded for now. The operation is very fast.
    const p1mod2 = (Fp.ORDER - _1n) / _2n;
    const powered = Fp.pow(n, p1mod2);
    const yes = Fp.eql(powered, Fp.ONE);
    const zero = Fp.eql(powered, Fp.ZERO);
    const no = Fp.eql(powered, Fp.neg(Fp.ONE));
    if (!yes && !zero && !no)
        throw new Error('invalid Legendre symbol result');
    return yes ? 1 : zero ? 0 : -1;
}
// This function returns True whenever the value x is a square in the field F.
export function FpIsSquare(Fp, n) {
    const l = FpLegendre(Fp, n);
    return l === 1;
}
// CURVE.n lengths
export function nLength(n, nBitLength) {
    // Bit size, byte size of CURVE.n
    if (nBitLength !== undefined)
        anumber(nBitLength);
    const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;
    const nByteLength = Math.ceil(_nBitLength / 8);
    return { nBitLength: _nBitLength, nByteLength };
}
/**
 * Creates a finite field. Major performance optimizations:
 * * 1. Denormalized operations like mulN instead of mul.
 * * 2. Identical object shape: never add or remove keys.
 * * 3. `Object.freeze`.
 * Fragile: always run a benchmark on a change.
 * Security note: operations don't check 'isValid' for all elements for performance reasons,
 * it is caller responsibility to check this.
 * This is low-level code, please make sure you know what you're doing.
 *
 * Note about field properties:
 * * CHARACTERISTIC p = prime number, number of elements in main subgroup.
 * * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.
 *
 * @param ORDER field order, probably prime, or could be composite
 * @param bitLen how many bits the field consumes
 * @param isLE (default: false) if encoding / decoding should be in little-endian
 * @param redef optional faster redefinitions of sqrt and other methods
 */
export function Field(ORDER, bitLenOrOpts, // TODO: use opts only in v2?
isLE = false, opts = {}) {
    if (ORDER <= _0n)
        throw new Error('invalid field: expected ORDER > 0, got ' + ORDER);
    let _nbitLength = undefined;
    let _sqrt = undefined;
    let modFromBytes = false;
    let allowedLengths = undefined;
    if (typeof bitLenOrOpts === 'object' && bitLenOrOpts != null) {
        if (opts.sqrt || isLE)
            throw new Error('cannot specify opts in two arguments');
        const _opts = bitLenOrOpts;
        if (_opts.BITS)
            _nbitLength = _opts.BITS;
        if (_opts.sqrt)
            _sqrt = _opts.sqrt;
        if (typeof _opts.isLE === 'boolean')
            isLE = _opts.isLE;
        if (typeof _opts.modFromBytes === 'boolean')
            modFromBytes = _opts.modFromBytes;
        allowedLengths = _opts.allowedLengths;
    }
    else {
        if (typeof bitLenOrOpts === 'number')
            _nbitLength = bitLenOrOpts;
        if (opts.sqrt)
            _sqrt = opts.sqrt;
    }
    const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, _nbitLength);
    if (BYTES > 2048)
        throw new Error('invalid field: expected ORDER of <= 2048 bytes');
    let sqrtP; // cached sqrtP
    const f = Object.freeze({
        ORDER,
        isLE,
        BITS,
        BYTES,
        MASK: bitMask(BITS),
        ZERO: _0n,
        ONE: _1n,
        allowedLengths: allowedLengths,
        create: (num) => mod(num, ORDER),
        isValid: (num) => {
            if (typeof num !== 'bigint')
                throw new Error('invalid field element: expected bigint, got ' + typeof num);
            return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible
        },
        is0: (num) => num === _0n,
        // is valid and invertible
        isValidNot0: (num) => !f.is0(num) && f.isValid(num),
        isOdd: (num) => (num & _1n) === _1n,
        neg: (num) => mod(-num, ORDER),
        eql: (lhs, rhs) => lhs === rhs,
        sqr: (num) => mod(num * num, ORDER),
        add: (lhs, rhs) => mod(lhs + rhs, ORDER),
        sub: (lhs, rhs) => mod(lhs - rhs, ORDER),
        mul: (lhs, rhs) => mod(lhs * rhs, ORDER),
        pow: (num, power) => FpPow(f, num, power),
        div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),
        // Same as above, but doesn't normalize
        sqrN: (num) => num * num,
        addN: (lhs, rhs) => lhs + rhs,
        subN: (lhs, rhs) => lhs - rhs,
        mulN: (lhs, rhs) => lhs * rhs,
        inv: (num) => invert(num, ORDER),
        sqrt: _sqrt ||
            ((n) => {
                if (!sqrtP)
                    sqrtP = FpSqrt(ORDER);
                return sqrtP(f, n);
            }),
        toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),
        fromBytes: (bytes, skipValidation = true) => {
            if (allowedLengths) {
                if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
                    throw new Error('Field.fromBytes: expected ' + allowedLengths + ' bytes, got ' + bytes.length);
                }
                const padded = new Uint8Array(BYTES);
                // isLE add 0 to right, !isLE to the left.
                padded.set(bytes, isLE ? 0 : padded.length - bytes.length);
                bytes = padded;
            }
            if (bytes.length !== BYTES)
                throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);
            let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
            if (modFromBytes)
                scalar = mod(scalar, ORDER);
            if (!skipValidation)
                if (!f.isValid(scalar))
                    throw new Error('invalid field element: outside of range 0..ORDER');
            // NOTE: we don't validate scalar here, please use isValid. This done such way because some
            // protocol may allow non-reduced scalar that reduced later or changed some other way.
            return scalar;
        },
        // TODO: we don't need it here, move out to separate fn
        invertBatch: (lst) => FpInvertBatch(f, lst),
        // We can't move this out because Fp6, Fp12 implement it
        // and it's unclear what to return in there.
        cmov: (a, b, c) => (c ? b : a),
    });
    return Object.freeze(f);
}
// Generic random scalar, we can do same for other fields if via Fp2.mul(Fp2.ONE, Fp2.random)?
// This allows unsafe methods like ignore bias or zero. These unsafe, but often used in different protocols (if deterministic RNG).
// which mean we cannot force this via opts.
// Not sure what to do with randomBytes, we can accept it inside opts if wanted.
// Probably need to export getMinHashLength somewhere?
// random(bytes?: Uint8Array, unsafeAllowZero = false, unsafeAllowBias = false) {
//   const LEN = !unsafeAllowBias ? getMinHashLength(ORDER) : BYTES;
//   if (bytes === undefined) bytes = randomBytes(LEN); // _opts.randomBytes?
//   const num = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
//   // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0
//   const reduced = unsafeAllowZero ? mod(num, ORDER) : mod(num, ORDER - _1n) + _1n;
//   return reduced;
// },
export function FpSqrtOdd(Fp, elm) {
    if (!Fp.isOdd)
        throw new Error("Field doesn't have isOdd");
    const root = Fp.sqrt(elm);
    return Fp.isOdd(root) ? root : Fp.neg(root);
}
export function FpSqrtEven(Fp, elm) {
    if (!Fp.isOdd)
        throw new Error("Field doesn't have isOdd");
    const root = Fp.sqrt(elm);
    return Fp.isOdd(root) ? Fp.neg(root) : root;
}
/**
 * "Constant-time" private key generation utility.
 * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field).
 * Which makes it slightly more biased, less secure.
 * @deprecated use `mapKeyToField` instead
 */
export function hashToPrivateScalar(hash, groupOrder, isLE = false) {
    hash = ensureBytes('privateHash', hash);
    const hashLen = hash.length;
    const minLen = nLength(groupOrder).nByteLength + 8;
    if (minLen < 24 || hashLen < minLen || hashLen > 1024)
        throw new Error('hashToPrivateScalar: expected ' + minLen + '-1024 bytes of input, got ' + hashLen);
    const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash);
    return mod(num, groupOrder - _1n) + _1n;
}
/**
 * Returns total number of bytes consumed by the field element.
 * For example, 32 bytes for usual 256-bit weierstrass curve.
 * @param fieldOrder number of field elements, usually CURVE.n
 * @returns byte length of field
 */
export function getFieldBytesLength(fieldOrder) {
    if (typeof fieldOrder !== 'bigint')
        throw new Error('field order must be bigint');
    const bitLength = fieldOrder.toString(2).length;
    return Math.ceil(bitLength / 8);
}
/**
 * Returns minimal amount of bytes that can be safely reduced
 * by field order.
 * Should be 2^-128 for 128-bit curve such as P256.
 * @param fieldOrder number of field elements, usually CURVE.n
 * @returns byte length of target hash
 */
export function getMinHashLength(fieldOrder) {
    const length = getFieldBytesLength(fieldOrder);
    return length + Math.ceil(length / 2);
}
/**
 * "Constant-time" private key generation utility.
 * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF
 * and convert them into private scalar, with the modulo bias being negligible.
 * Needs at least 48 bytes of input for 32-byte private key.
 * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/
 * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final
 * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5
 * @param hash hash output from SHA3 or a similar function
 * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)
 * @param isLE interpret hash bytes as LE num
 * @returns valid private scalar
 */
export function mapHashToField(key, fieldOrder, isLE = false) {
    const len = key.length;
    const fieldLen = getFieldBytesLength(fieldOrder);
    const minLen = getMinHashLength(fieldOrder);
    // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.
    if (len < 16 || len < minLen || len > 1024)
        throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);
    const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);
    // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0
    const reduced = mod(num, fieldOrder - _1n) + _1n;
    return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
}
//# sourceMappingURL=modular.js.map/**
 * Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.
 *
 * ### Design rationale for types
 *
 * * Interaction between classes from different curves should fail:
 *   `k256.Point.BASE.add(p256.Point.BASE)`
 * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime
 * * Different calls of `curve()` would return different classes -
 *   `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,
 *   it won't affect others
 *
 * TypeScript can't infer types for classes created inside a function. Classes is one instance
 * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create
 * unique type for every function call.
 *
 * We can use generic types via some param, like curve opts, but that would:
 *     1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)
 *     which is hard to debug.
 *     2. Params can be generic and we can't enforce them to be constant value:
 *     if somebody creates curve from non-constant params,
 *     it would be allowed to interact with other curves with non-constant params
 *
 * @todo https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { hmac as nobleHmac } from '@noble/hashes/hmac.js';
import { ahash } from '@noble/hashes/utils';
import { _validateObject, _abool2 as abool, _abytes2 as abytes, aInRange, bitLen, bitMask, bytesToHex, bytesToNumberBE, concatBytes, createHmacDrbg, ensureBytes, hexToBytes, inRange, isBytes, memoized, numberToHexUnpadded, randomBytes as randomBytesWeb, } from "../utils.js";
import { _createCurveFields, mulEndoUnsafe, negateCt, normalizeZ, pippenger, wNAF, } from "./curve.js";
import { Field, FpInvertBatch, getMinHashLength, mapHashToField, nLength, validateField, } from "./modular.js";
// We construct basis in such way that den is always positive and equals n, but num sign depends on basis (not on secret value)
const divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n) / den;
/**
 * Splits scalar for GLV endomorphism.
 */
export function _splitEndoScalar(k, basis, n) {
    // Split scalar into two such that part is ~half bits: `abs(part) < sqrt(N)`
    // Since part can be negative, we need to do this on point.
    // TODO: verifyScalar function which consumes lambda
    const [[a1, b1], [a2, b2]] = basis;
    const c1 = divNearest(b2 * k, n);
    const c2 = divNearest(-b1 * k, n);
    // |k1|/|k2| is < sqrt(N), but can be negative.
    // If we do `k1 mod N`, we'll get big scalar (`> sqrt(N)`): so, we do cheaper negation instead.
    let k1 = k - c1 * a1 - c2 * a2;
    let k2 = -c1 * b1 - c2 * b2;
    const k1neg = k1 < _0n;
    const k2neg = k2 < _0n;
    if (k1neg)
        k1 = -k1;
    if (k2neg)
        k2 = -k2;
    // Double check that resulting scalar less than half bits of N: otherwise wNAF will fail.
    // This should only happen on wrong basises. Also, math inside is too complex and I don't trust it.
    const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n; // Half bits of N
    if (k1 < _0n || k1 >= MAX_NUM || k2 < _0n || k2 >= MAX_NUM) {
        throw new Error('splitScalar (endomorphism): failed, k=' + k);
    }
    return { k1neg, k1, k2neg, k2 };
}
function validateSigFormat(format) {
    if (!['compact', 'recovered', 'der'].includes(format))
        throw new Error('Signature format must be "compact", "recovered", or "der"');
    return format;
}
function validateSigOpts(opts, def) {
    const optsn = {};
    for (let optName of Object.keys(def)) {
        // @ts-ignore
        optsn[optName] = opts[optName] === undefined ? def[optName] : opts[optName];
    }
    abool(optsn.lowS, 'lowS');
    abool(optsn.prehash, 'prehash');
    if (optsn.format !== undefined)
        validateSigFormat(optsn.format);
    return optsn;
}
export class DERErr extends Error {
    constructor(m = '') {
        super(m);
    }
}
/**
 * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:
 *
 *     [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]
 *
 * Docs: https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/, https://luca.ntop.org/Teaching/Appunti/asn1.html
 */
export const DER = {
    // asn.1 DER encoding utils
    Err: DERErr,
    // Basic building block is TLV (Tag-Length-Value)
    _tlv: {
        encode: (tag, data) => {
            const { Err: E } = DER;
            if (tag < 0 || tag > 256)
                throw new E('tlv.encode: wrong tag');
            if (data.length & 1)
                throw new E('tlv.encode: unpadded data');
            const dataLen = data.length / 2;
            const len = numberToHexUnpadded(dataLen);
            if ((len.length / 2) & 128)
                throw new E('tlv.encode: long form length too big');
            // length of length with long form flag
            const lenLen = dataLen > 127 ? numberToHexUnpadded((len.length / 2) | 128) : '';
            const t = numberToHexUnpadded(tag);
            return t + lenLen + len + data;
        },
        // v - value, l - left bytes (unparsed)
        decode(tag, data) {
            const { Err: E } = DER;
            let pos = 0;
            if (tag < 0 || tag > 256)
                throw new E('tlv.encode: wrong tag');
            if (data.length < 2 || data[pos++] !== tag)
                throw new E('tlv.decode: wrong tlv');
            const first = data[pos++];
            const isLong = !!(first & 128); // First bit of first length byte is flag for short/long form
            let length = 0;
            if (!isLong)
                length = first;
            else {
                // Long form: [longFlag(1bit), lengthLength(7bit), length (BE)]
                const lenLen = first & 127;
                if (!lenLen)
                    throw new E('tlv.decode(long): indefinite length not supported');
                if (lenLen > 4)
                    throw new E('tlv.decode(long): byte length is too big'); // this will overflow u32 in js
                const lengthBytes = data.subarray(pos, pos + lenLen);
                if (lengthBytes.length !== lenLen)
                    throw new E('tlv.decode: length bytes not complete');
                if (lengthBytes[0] === 0)
                    throw new E('tlv.decode(long): zero leftmost byte');
                for (const b of lengthBytes)
                    length = (length << 8) | b;
                pos += lenLen;
                if (length < 128)
                    throw new E('tlv.decode(long): not minimal encoding');
            }
            const v = data.subarray(pos, pos + length);
            if (v.length !== length)
                throw new E('tlv.decode: wrong value length');
            return { v, l: data.subarray(pos + length) };
        },
    },
    // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
    // since we always use positive integers here. It must always be empty:
    // - add zero byte if exists
    // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
    _int: {
        encode(num) {
            const { Err: E } = DER;
            if (num < _0n)
                throw new E('integer: negative integers are not allowed');
            let hex = numberToHexUnpadded(num);
            // Pad with zero byte if negative flag is present
            if (Number.parseInt(hex[0], 16) & 0b1000)
                hex = '00' + hex;
            if (hex.length & 1)
                throw new E('unexpected DER parsing assertion: unpadded hex');
            return hex;
        },
        decode(data) {
            const { Err: E } = DER;
            if (data[0] & 128)
                throw new E('invalid signature integer: negative');
            if (data[0] === 0x00 && !(data[1] & 128))
                throw new E('invalid signature integer: unnecessary leading zero');
            return bytesToNumberBE(data);
        },
    },
    toSig(hex) {
        // parse DER signature
        const { Err: E, _int: int, _tlv: tlv } = DER;
        const data = ensureBytes('signature', hex);
        const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);
        if (seqLeftBytes.length)
            throw new E('invalid signature: left bytes after parsing');
        const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);
        const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);
        if (sLeftBytes.length)
            throw new E('invalid signature: left bytes after parsing');
        return { r: int.decode(rBytes), s: int.decode(sBytes) };
    },
    hexFromSig(sig) {
        const { _tlv: tlv, _int: int } = DER;
        const rs = tlv.encode(0x02, int.encode(sig.r));
        const ss = tlv.encode(0x02, int.encode(sig.s));
        const seq = rs + ss;
        return tlv.encode(0x30, seq);
    },
};
// Be friendly to bad ECMAScript parsers by not using bigint literals
// prettier-ignore
const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4);
export function _normFnElement(Fn, key) {
    const { BYTES: expected } = Fn;
    let num;
    if (typeof key === 'bigint') {
        num = key;
    }
    else {
        let bytes = ensureBytes('private key', key);
        try {
            num = Fn.fromBytes(bytes);
        }
        catch (error) {
            throw new Error(`invalid private key: expected ui8a of size ${expected}, got ${typeof key}`);
        }
    }
    if (!Fn.isValidNot0(num))
        throw new Error('invalid private key: out of range [1..N-1]');
    return num;
}
/**
 * Creates weierstrass Point constructor, based on specified curve options.
 *
 * @example
```js
const opts = {
  p: BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff'),
  n: BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551'),
  h: BigInt(1),
  a: BigInt('0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc'),
  b: BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b'),
  Gx: BigInt('0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296'),
  Gy: BigInt('0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5'),
};
const p256_Point = weierstrass(opts);
```
 */
export function weierstrassN(params, extraOpts = {}) {
    const validated = _createCurveFields('weierstrass', params, extraOpts);
    const { Fp, Fn } = validated;
    let CURVE = validated.CURVE;
    const { h: cofactor, n: CURVE_ORDER } = CURVE;
    _validateObject(extraOpts, {}, {
        allowInfinityPoint: 'boolean',
        clearCofactor: 'function',
        isTorsionFree: 'function',
        fromBytes: 'function',
        toBytes: 'function',
        endo: 'object',
        wrapPrivateKey: 'boolean',
    });
    const { endo } = extraOpts;
    if (endo) {
        // validateObject(endo, { beta: 'bigint', splitScalar: 'function' });
        if (!Fp.is0(CURVE.a) || typeof endo.beta !== 'bigint' || !Array.isArray(endo.basises)) {
            throw new Error('invalid endo: expected "beta": bigint and "basises": array');
        }
    }
    const lengths = getWLengths(Fp, Fn);
    function assertCompressionIsSupported() {
        if (!Fp.isOdd)
            throw new Error('compression is not supported: Field does not have .isOdd()');
    }
    // Implements IEEE P1363 point encoding
    function pointToBytes(_c, point, isCompressed) {
        const { x, y } = point.toAffine();
        const bx = Fp.toBytes(x);
        abool(isCompressed, 'isCompressed');
        if (isCompressed) {
            assertCompressionIsSupported();
            const hasEvenY = !Fp.isOdd(y);
            return concatBytes(pprefix(hasEvenY), bx);
        }
        else {
            return concatBytes(Uint8Array.of(0x04), bx, Fp.toBytes(y));
        }
    }
    function pointFromBytes(bytes) {
        abytes(bytes, undefined, 'Point');
        const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths; // e.g. for 32-byte: 33, 65
        const length = bytes.length;
        const head = bytes[0];
        const tail = bytes.subarray(1);
        // No actual validation is done here: use .assertValidity()
        if (length === comp && (head === 0x02 || head === 0x03)) {
            const x = Fp.fromBytes(tail);
            if (!Fp.isValid(x))
                throw new Error('bad point: is not on curve, wrong x');
            const y2 = weierstrassEquation(x); // y² = x³ + ax + b
            let y;
            try {
                y = Fp.sqrt(y2); // y = y² ^ (p+1)/4
            }
            catch (sqrtError) {
                const err = sqrtError instanceof Error ? ': ' + sqrtError.message : '';
                throw new Error('bad point: is not on curve, sqrt error' + err);
            }
            assertCompressionIsSupported();
            const isYOdd = Fp.isOdd(y); // (y & _1n) === _1n;
            const isHeadOdd = (head & 1) === 1; // ECDSA-specific
            if (isHeadOdd !== isYOdd)
                y = Fp.neg(y);
            return { x, y };
        }
        else if (length === uncomp && head === 0x04) {
            // TODO: more checks
            const L = Fp.BYTES;
            const x = Fp.fromBytes(tail.subarray(0, L));
            const y = Fp.fromBytes(tail.subarray(L, L * 2));
            if (!isValidXY(x, y))
                throw new Error('bad point: is not on curve');
            return { x, y };
        }
        else {
            throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);
        }
    }
    const encodePoint = extraOpts.toBytes || pointToBytes;
    const decodePoint = extraOpts.fromBytes || pointFromBytes;
    function weierstrassEquation(x) {
        const x2 = Fp.sqr(x); // x * x
        const x3 = Fp.mul(x2, x); // x² * x
        return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b); // x³ + a * x + b
    }
    // TODO: move top-level
    /** Checks whether equation holds for given x, y: y² == x³ + ax + b */
    function isValidXY(x, y) {
        const left = Fp.sqr(y); // y²
        const right = weierstrassEquation(x); // x³ + ax + b
        return Fp.eql(left, right);
    }
    // Validate whether the passed curve params are valid.
    // Test 1: equation y² = x³ + ax + b should work for generator point.
    if (!isValidXY(CURVE.Gx, CURVE.Gy))
        throw new Error('bad curve params: generator point');
    // Test 2: discriminant Δ part should be non-zero: 4a³ + 27b² != 0.
    // Guarantees curve is genus-1, smooth (non-singular).
    const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n), _4n);
    const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));
    if (Fp.is0(Fp.add(_4a3, _27b2)))
        throw new Error('bad curve params: a or b');
    /** Asserts coordinate is valid: 0 <= n < Fp.ORDER. */
    function acoord(title, n, banZero = false) {
        if (!Fp.isValid(n) || (banZero && Fp.is0(n)))
            throw new Error(`bad point coordinate ${title}`);
        return n;
    }
    function aprjpoint(other) {
        if (!(other instanceof Point))
            throw new Error('ProjectivePoint expected');
    }
    function splitEndoScalarN(k) {
        if (!endo || !endo.basises)
            throw new Error('no endo');
        return _splitEndoScalar(k, endo.basises, Fn.ORDER);
    }
    // Memoized toAffine / validity check. They are heavy. Points are immutable.
    // Converts Projective point to affine (x, y) coordinates.
    // Can accept precomputed Z^-1 - for example, from invertBatch.
    // (X, Y, Z) ∋ (x=X/Z, y=Y/Z)
    const toAffineMemo = memoized((p, iz) => {
        const { X, Y, Z } = p;
        // Fast-path for normalized points
        if (Fp.eql(Z, Fp.ONE))
            return { x: X, y: Y };
        const is0 = p.is0();
        // If invZ was 0, we return zero point. However we still want to execute
        // all operations, so we replace invZ with a random number, 1.
        if (iz == null)
            iz = is0 ? Fp.ONE : Fp.inv(Z);
        const x = Fp.mul(X, iz);
        const y = Fp.mul(Y, iz);
        const zz = Fp.mul(Z, iz);
        if (is0)
            return { x: Fp.ZERO, y: Fp.ZERO };
        if (!Fp.eql(zz, Fp.ONE))
            throw new Error('invZ was invalid');
        return { x, y };
    });
    // NOTE: on exception this will crash 'cached' and no value will be set.
    // Otherwise true will be return
    const assertValidMemo = memoized((p) => {
        if (p.is0()) {
            // (0, 1, 0) aka ZERO is invalid in most contexts.
            // In BLS, ZERO can be serialized, so we allow it.
            // (0, 0, 0) is invalid representation of ZERO.
            if (extraOpts.allowInfinityPoint && !Fp.is0(p.Y))
                return;
            throw new Error('bad point: ZERO');
        }
        // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`
        const { x, y } = p.toAffine();
        if (!Fp.isValid(x) || !Fp.isValid(y))
            throw new Error('bad point: x or y not field elements');
        if (!isValidXY(x, y))
            throw new Error('bad point: equation left != right');
        if (!p.isTorsionFree())
            throw new Error('bad point: not in prime-order subgroup');
        return true;
    });
    function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) {
        k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);
        k1p = negateCt(k1neg, k1p);
        k2p = negateCt(k2neg, k2p);
        return k1p.add(k2p);
    }
    /**
     * Projective Point works in 3d / projective (homogeneous) coordinates:(X, Y, Z) ∋ (x=X/Z, y=Y/Z).
     * Default Point works in 2d / affine coordinates: (x, y).
     * We're doing calculations in projective, because its operations don't require costly inversion.
     */
    class Point {
        /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
        constructor(X, Y, Z) {
            this.X = acoord('x', X);
            this.Y = acoord('y', Y, true);
            this.Z = acoord('z', Z);
            Object.freeze(this);
        }
        static CURVE() {
            return CURVE;
        }
        /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
        static fromAffine(p) {
            const { x, y } = p || {};
            if (!p || !Fp.isValid(x) || !Fp.isValid(y))
                throw new Error('invalid affine point');
            if (p instanceof Point)
                throw new Error('projective point not allowed');
            // (0, 0) would've produced (0, 0, 1) - instead, we need (0, 1, 0)
            if (Fp.is0(x) && Fp.is0(y))
                return Point.ZERO;
            return new Point(x, y, Fp.ONE);
        }
        static fromBytes(bytes) {
            const P = Point.fromAffine(decodePoint(abytes(bytes, undefined, 'point')));
            P.assertValidity();
            return P;
        }
        static fromHex(hex) {
            return Point.fromBytes(ensureBytes('pointHex', hex));
        }
        get x() {
            return this.toAffine().x;
        }
        get y() {
            return this.toAffine().y;
        }
        /**
         *
         * @param windowSize
         * @param isLazy true will defer table computation until the first multiplication
         * @returns
         */
        precompute(windowSize = 8, isLazy = true) {
            wnaf.createCache(this, windowSize);
            if (!isLazy)
                this.multiply(_3n); // random number
            return this;
        }
        // TODO: return `this`
        /** A point on curve is valid if it conforms to equation. */
        assertValidity() {
            assertValidMemo(this);
        }
        hasEvenY() {
            const { y } = this.toAffine();
            if (!Fp.isOdd)
                throw new Error("Field doesn't support isOdd");
            return !Fp.isOdd(y);
        }
        /** Compare one point to another. */
        equals(other) {
            aprjpoint(other);
            const { X: X1, Y: Y1, Z: Z1 } = this;
            const { X: X2, Y: Y2, Z: Z2 } = other;
            const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
            const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
            return U1 && U2;
        }
        /** Flips point to one corresponding to (x, -y) in Affine coordinates. */
        negate() {
            return new Point(this.X, Fp.neg(this.Y), this.Z);
        }
        // Renes-Costello-Batina exception-free doubling formula.
        // There is 30% faster Jacobian formula, but it is not complete.
        // https://eprint.iacr.org/2015/1060, algorithm 3
        // Cost: 8M + 3S + 3*a + 2*b3 + 15add.
        double() {
            const { a, b } = CURVE;
            const b3 = Fp.mul(b, _3n);
            const { X: X1, Y: Y1, Z: Z1 } = this;
            let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore
            let t0 = Fp.mul(X1, X1); // step 1
            let t1 = Fp.mul(Y1, Y1);
            let t2 = Fp.mul(Z1, Z1);
            let t3 = Fp.mul(X1, Y1);
            t3 = Fp.add(t3, t3); // step 5
            Z3 = Fp.mul(X1, Z1);
            Z3 = Fp.add(Z3, Z3);
            X3 = Fp.mul(a, Z3);
            Y3 = Fp.mul(b3, t2);
            Y3 = Fp.add(X3, Y3); // step 10
            X3 = Fp.sub(t1, Y3);
            Y3 = Fp.add(t1, Y3);
            Y3 = Fp.mul(X3, Y3);
            X3 = Fp.mul(t3, X3);
            Z3 = Fp.mul(b3, Z3); // step 15
            t2 = Fp.mul(a, t2);
            t3 = Fp.sub(t0, t2);
            t3 = Fp.mul(a, t3);
            t3 = Fp.add(t3, Z3);
            Z3 = Fp.add(t0, t0); // step 20
            t0 = Fp.add(Z3, t0);
            t0 = Fp.add(t0, t2);
            t0 = Fp.mul(t0, t3);
            Y3 = Fp.add(Y3, t0);
            t2 = Fp.mul(Y1, Z1); // step 25
            t2 = Fp.add(t2, t2);
            t0 = Fp.mul(t2, t3);
            X3 = Fp.sub(X3, t0);
            Z3 = Fp.mul(t2, t1);
            Z3 = Fp.add(Z3, Z3); // step 30
            Z3 = Fp.add(Z3, Z3);
            return new Point(X3, Y3, Z3);
        }
        // Renes-Costello-Batina exception-free addition formula.
        // There is 30% faster Jacobian formula, but it is not complete.
        // https://eprint.iacr.org/2015/1060, algorithm 1
        // Cost: 12M + 0S + 3*a + 3*b3 + 23add.
        add(other) {
            aprjpoint(other);
            const { X: X1, Y: Y1, Z: Z1 } = this;
            const { X: X2, Y: Y2, Z: Z2 } = other;
            let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore
            const a = CURVE.a;
            const b3 = Fp.mul(CURVE.b, _3n);
            let t0 = Fp.mul(X1, X2); // step 1
            let t1 = Fp.mul(Y1, Y2);
            let t2 = Fp.mul(Z1, Z2);
            let t3 = Fp.add(X1, Y1);
            let t4 = Fp.add(X2, Y2); // step 5
            t3 = Fp.mul(t3, t4);
            t4 = Fp.add(t0, t1);
            t3 = Fp.sub(t3, t4);
            t4 = Fp.add(X1, Z1);
            let t5 = Fp.add(X2, Z2); // step 10
            t4 = Fp.mul(t4, t5);
            t5 = Fp.add(t0, t2);
            t4 = Fp.sub(t4, t5);
            t5 = Fp.add(Y1, Z1);
            X3 = Fp.add(Y2, Z2); // step 15
            t5 = Fp.mul(t5, X3);
            X3 = Fp.add(t1, t2);
            t5 = Fp.sub(t5, X3);
            Z3 = Fp.mul(a, t4);
            X3 = Fp.mul(b3, t2); // step 20
            Z3 = Fp.add(X3, Z3);
            X3 = Fp.sub(t1, Z3);
            Z3 = Fp.add(t1, Z3);
            Y3 = Fp.mul(X3, Z3);
            t1 = Fp.add(t0, t0); // step 25
            t1 = Fp.add(t1, t0);
            t2 = Fp.mul(a, t2);
            t4 = Fp.mul(b3, t4);
            t1 = Fp.add(t1, t2);
            t2 = Fp.sub(t0, t2); // step 30
            t2 = Fp.mul(a, t2);
            t4 = Fp.add(t4, t2);
            t0 = Fp.mul(t1, t4);
            Y3 = Fp.add(Y3, t0);
            t0 = Fp.mul(t5, t4); // step 35
            X3 = Fp.mul(t3, X3);
            X3 = Fp.sub(X3, t0);
            t0 = Fp.mul(t3, t1);
            Z3 = Fp.mul(t5, Z3);
            Z3 = Fp.add(Z3, t0); // step 40
            return new Point(X3, Y3, Z3);
        }
        subtract(other) {
            return this.add(other.negate());
        }
        is0() {
            return this.equals(Point.ZERO);
        }
        /**
         * Constant time multiplication.
         * Uses wNAF method. Windowed method may be 10% faster,
         * but takes 2x longer to generate and consumes 2x memory.
         * Uses precomputes when available.
         * Uses endomorphism for Koblitz curves.
         * @param scalar by which the point would be multiplied
         * @returns New point
         */
        multiply(scalar) {
            const { endo } = extraOpts;
            if (!Fn.isValidNot0(scalar))
                throw new Error('invalid scalar: out of range'); // 0 is invalid
            let point, fake; // Fake point is used to const-time mult
            const mul = (n) => wnaf.cached(this, n, (p) => normalizeZ(Point, p));
            /** See docs for {@link EndomorphismOpts} */
            if (endo) {
                const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);
                const { p: k1p, f: k1f } = mul(k1);
                const { p: k2p, f: k2f } = mul(k2);
                fake = k1f.add(k2f);
                point = finishEndo(endo.beta, k1p, k2p, k1neg, k2neg);
            }
            else {
                const { p, f } = mul(scalar);
                point = p;
                fake = f;
            }
            // Normalize `z` for both points, but return only real one
            return normalizeZ(Point, [point, fake])[0];
        }
        /**
         * Non-constant-time multiplication. Uses double-and-add algorithm.
         * It's faster, but should only be used when you don't care about
         * an exposed secret key e.g. sig verification, which works over *public* keys.
         */
        multiplyUnsafe(sc) {
            const { endo } = extraOpts;
            const p = this;
            if (!Fn.isValid(sc))
                throw new Error('invalid scalar: out of range'); // 0 is valid
            if (sc === _0n || p.is0())
                return Point.ZERO;
            if (sc === _1n)
                return p; // fast-path
            if (wnaf.hasCache(this))
                return this.multiply(sc);
            if (endo) {
                const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);
                const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2); // 30% faster vs wnaf.unsafe
                return finishEndo(endo.beta, p1, p2, k1neg, k2neg);
            }
            else {
                return wnaf.unsafe(p, sc);
            }
        }
        multiplyAndAddUnsafe(Q, a, b) {
            const sum = this.multiplyUnsafe(a).add(Q.multiplyUnsafe(b));
            return sum.is0() ? undefined : sum;
        }
        /**
         * Converts Projective point to affine (x, y) coordinates.
         * @param invertedZ Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch
         */
        toAffine(invertedZ) {
            return toAffineMemo(this, invertedZ);
        }
        /**
         * Checks whether Point is free of torsion elements (is in prime subgroup).
         * Always torsion-free for cofactor=1 curves.
         */
        isTorsionFree() {
            const { isTorsionFree } = extraOpts;
            if (cofactor === _1n)
                return true;
            if (isTorsionFree)
                return isTorsionFree(Point, this);
            return wnaf.unsafe(this, CURVE_ORDER).is0();
        }
        clearCofactor() {
            const { clearCofactor } = extraOpts;
            if (cofactor === _1n)
                return this; // Fast-path
            if (clearCofactor)
                return clearCofactor(Point, this);
            return this.multiplyUnsafe(cofactor);
        }
        isSmallOrder() {
            // can we use this.clearCofactor()?
            return this.multiplyUnsafe(cofactor).is0();
        }
        toBytes(isCompressed = true) {
            abool(isCompressed, 'isCompressed');
            this.assertValidity();
            return encodePoint(Point, this, isCompressed);
        }
        toHex(isCompressed = true) {
            return bytesToHex(this.toBytes(isCompressed));
        }
        toString() {
            return `<Point ${this.is0() ? 'ZERO' : this.toHex()}>`;
        }
        // TODO: remove
        get px() {
            return this.X;
        }
        get py() {
            return this.X;
        }
        get pz() {
            return this.Z;
        }
        toRawBytes(isCompressed = true) {
            return this.toBytes(isCompressed);
        }
        _setWindowSize(windowSize) {
            this.precompute(windowSize);
        }
        static normalizeZ(points) {
            return normalizeZ(Point, points);
        }
        static msm(points, scalars) {
            return pippenger(Point, Fn, points, scalars);
        }
        static fromPrivateKey(privateKey) {
            return Point.BASE.multiply(_normFnElement(Fn, privateKey));
        }
    }
    // base / generator point
    Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
    // zero / infinity / identity point
    Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); // 0, 1, 0
    // math field
    Point.Fp = Fp;
    // scalar field
    Point.Fn = Fn;
    const bits = Fn.BITS;
    const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);
    Point.BASE.precompute(8); // Enable precomputes. Slows down first publicKey computation by 20ms.
    return Point;
}
// Points start with byte 0x02 when y is even; otherwise 0x03
function pprefix(hasEvenY) {
    return Uint8Array.of(hasEvenY ? 0x02 : 0x03);
}
/**
 * Implementation of the Shallue and van de Woestijne method for any weierstrass curve.
 * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular.
 * b = True and y = sqrt(u / v) if (u / v) is square in F, and
 * b = False and y = sqrt(Z * (u / v)) otherwise.
 * @param Fp
 * @param Z
 * @returns
 */
export function SWUFpSqrtRatio(Fp, Z) {
    // Generic implementation
    const q = Fp.ORDER;
    let l = _0n;
    for (let o = q - _1n; o % _2n === _0n; o /= _2n)
        l += _1n;
    const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1.
    // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<.
    // 2n ** c1 == 2n << (c1-1)
    const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n);
    const _2n_pow_c1 = _2n_pow_c1_1 * _2n;
    const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1)  # Integer arithmetic
    const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2            # Integer arithmetic
    const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1                # Integer arithmetic
    const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1)                  # Integer arithmetic
    const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2
    const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2)
    let sqrtRatio = (u, v) => {
        let tv1 = c6; // 1. tv1 = c6
        let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4
        let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2
        tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v
        let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3
        tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3
        tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2
        tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v
        tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u
        let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2
        tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5
        let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1
        tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7
        tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1
        tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR)
        tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR)
        // 17. for i in (c1, c1 - 1, ..., 2):
        for (let i = c1; i > _1n; i--) {
            let tv5 = i - _2n; // 18.    tv5 = i - 2
            tv5 = _2n << (tv5 - _1n); // 19.    tv5 = 2^tv5
            let tvv5 = Fp.pow(tv4, tv5); // 20.    tv5 = tv4^tv5
            const e1 = Fp.eql(tvv5, Fp.ONE); // 21.    e1 = tv5 == 1
            tv2 = Fp.mul(tv3, tv1); // 22.    tv2 = tv3 * tv1
            tv1 = Fp.mul(tv1, tv1); // 23.    tv1 = tv1 * tv1
            tvv5 = Fp.mul(tv4, tv1); // 24.    tv5 = tv4 * tv1
            tv3 = Fp.cmov(tv2, tv3, e1); // 25.    tv3 = CMOV(tv2, tv3, e1)
            tv4 = Fp.cmov(tvv5, tv4, e1); // 26.    tv4 = CMOV(tv5, tv4, e1)
        }
        return { isValid: isQR, value: tv3 };
    };
    if (Fp.ORDER % _4n === _3n) {
        // sqrt_ratio_3mod4(u, v)
        const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4     # Integer arithmetic
        const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z)
        sqrtRatio = (u, v) => {
            let tv1 = Fp.sqr(v); // 1. tv1 = v^2
            const tv2 = Fp.mul(u, v); // 2. tv2 = u * v
            tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2
            let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1
            y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2
            const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2
            const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v
            const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u
            let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR)
            return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2
        };
    }
    // No curves uses that
    // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8
    return sqrtRatio;
}
/**
 * Simplified Shallue-van de Woestijne-Ulas Method
 * https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2
 */
export function mapToCurveSimpleSWU(Fp, opts) {
    validateField(Fp);
    const { A, B, Z } = opts;
    if (!Fp.isValid(A) || !Fp.isValid(B) || !Fp.isValid(Z))
        throw new Error('mapToCurveSimpleSWU: invalid opts');
    const sqrtRatio = SWUFpSqrtRatio(Fp, Z);
    if (!Fp.isOdd)
        throw new Error('Field does not have .isOdd()');
    // Input: u, an element of F.
    // Output: (x, y), a point on E.
    return (u) => {
        // prettier-ignore
        let tv1, tv2, tv3, tv4, tv5, tv6, x, y;
        tv1 = Fp.sqr(u); // 1.  tv1 = u^2
        tv1 = Fp.mul(tv1, Z); // 2.  tv1 = Z * tv1
        tv2 = Fp.sqr(tv1); // 3.  tv2 = tv1^2
        tv2 = Fp.add(tv2, tv1); // 4.  tv2 = tv2 + tv1
        tv3 = Fp.add(tv2, Fp.ONE); // 5.  tv3 = tv2 + 1
        tv3 = Fp.mul(tv3, B); // 6.  tv3 = B * tv3
        tv4 = Fp.cmov(Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7.  tv4 = CMOV(Z, -tv2, tv2 != 0)
        tv4 = Fp.mul(tv4, A); // 8.  tv4 = A * tv4
        tv2 = Fp.sqr(tv3); // 9.  tv2 = tv3^2
        tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2
        tv5 = Fp.mul(tv6, A); // 11. tv5 = A * tv6
        tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5
        tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3
        tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4
        tv5 = Fp.mul(tv6, B); // 15. tv5 = B * tv6
        tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5
        x = Fp.mul(tv1, tv3); // 17.   x = tv1 * tv3
        const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6)
        y = Fp.mul(tv1, u); // 19.   y = tv1 * u  -> Z * u^3 * y1
        y = Fp.mul(y, value); // 20.   y = y * y1
        x = Fp.cmov(x, tv3, isValid); // 21.   x = CMOV(x, tv3, is_gx1_square)
        y = Fp.cmov(y, value, isValid); // 22.   y = CMOV(y, y1, is_gx1_square)
        const e1 = Fp.isOdd(u) === Fp.isOdd(y); // 23.  e1 = sgn0(u) == sgn0(y)
        y = Fp.cmov(Fp.neg(y), y, e1); // 24.   y = CMOV(-y, y, e1)
        const tv4_inv = FpInvertBatch(Fp, [tv4], true)[0];
        x = Fp.mul(x, tv4_inv); // 25.   x = x / tv4
        return { x, y };
    };
}
function getWLengths(Fp, Fn) {
    return {
        secretKey: Fn.BYTES,
        publicKey: 1 + Fp.BYTES,
        publicKeyUncompressed: 1 + 2 * Fp.BYTES,
        publicKeyHasPrefix: true,
        signature: 2 * Fn.BYTES,
    };
}
/**
 * Sometimes users only need getPublicKey, getSharedSecret, and secret key handling.
 * This helper ensures no signature functionality is present. Less code, smaller bundle size.
 */
export function ecdh(Point, ecdhOpts = {}) {
    const { Fn } = Point;
    const randomBytes_ = ecdhOpts.randomBytes || randomBytesWeb;
    const lengths = Object.assign(getWLengths(Point.Fp, Fn), { seed: getMinHashLength(Fn.ORDER) });
    function isValidSecretKey(secretKey) {
        try {
            return !!_normFnElement(Fn, secretKey);
        }
        catch (error) {
            return false;
        }
    }
    function isValidPublicKey(publicKey, isCompressed) {
        const { publicKey: comp, publicKeyUncompressed } = lengths;
        try {
            const l = publicKey.length;
            if (isCompressed === true && l !== comp)
                return false;
            if (isCompressed === false && l !== publicKeyUncompressed)
                return false;
            return !!Point.fromBytes(publicKey);
        }
        catch (error) {
            return false;
        }
    }
    /**
     * Produces cryptographically secure secret key from random of size
     * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.
     */
    function randomSecretKey(seed = randomBytes_(lengths.seed)) {
        return mapHashToField(abytes(seed, lengths.seed, 'seed'), Fn.ORDER);
    }
    /**
     * Computes public key for a secret key. Checks for validity of the secret key.
     * @param isCompressed whether to return compact (default), or full key
     * @returns Public key, full when isCompressed=false; short when isCompressed=true
     */
    function getPublicKey(secretKey, isCompressed = true) {
        return Point.BASE.multiply(_normFnElement(Fn, secretKey)).toBytes(isCompressed);
    }
    function keygen(seed) {
        const secretKey = randomSecretKey(seed);
        return { secretKey, publicKey: getPublicKey(secretKey) };
    }
    /**
     * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.
     */
    function isProbPub(item) {
        if (typeof item === 'bigint')
            return false;
        if (item instanceof Point)
            return true;
        const { secretKey, publicKey, publicKeyUncompressed } = lengths;
        if (Fn.allowedLengths || secretKey === publicKey)
            return undefined;
        const l = ensureBytes('key', item).length;
        return l === publicKey || l === publicKeyUncompressed;
    }
    /**
     * ECDH (Elliptic Curve Diffie Hellman).
     * Computes shared public key from secret key A and public key B.
     * Checks: 1) secret key validity 2) shared key is on-curve.
     * Does NOT hash the result.
     * @param isCompressed whether to return compact (default), or full key
     * @returns shared public key
     */
    function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {
        if (isProbPub(secretKeyA) === true)
            throw new Error('first arg must be private key');
        if (isProbPub(publicKeyB) === false)
            throw new Error('second arg must be public key');
        const s = _normFnElement(Fn, secretKeyA);
        const b = Point.fromHex(publicKeyB); // checks for being on-curve
        return b.multiply(s).toBytes(isCompressed);
    }
    const utils = {
        isValidSecretKey,
        isValidPublicKey,
        randomSecretKey,
        // TODO: remove
        isValidPrivateKey: isValidSecretKey,
        randomPrivateKey: randomSecretKey,
        normPrivateKeyToScalar: (key) => _normFnElement(Fn, key),
        precompute(windowSize = 8, point = Point.BASE) {
            return point.precompute(windowSize, false);
        },
    };
    return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point, utils, lengths });
}
/**
 * Creates ECDSA signing interface for given elliptic curve `Point` and `hash` function.
 * We need `hash` for 2 features:
 * 1. Message prehash-ing. NOT used if `sign` / `verify` are called with `prehash: false`
 * 2. k generation in `sign`, using HMAC-drbg(hash)
 *
 * ECDSAOpts are only rarely needed.
 *
 * @example
 * ```js
 * const p256_Point = weierstrass(...);
 * const p256_sha256 = ecdsa(p256_Point, sha256);
 * const p256_sha224 = ecdsa(p256_Point, sha224);
 * const p256_sha224_r = ecdsa(p256_Point, sha224, { randomBytes: (length) => { ... } });
 * ```
 */
export function ecdsa(Point, hash, ecdsaOpts = {}) {
    ahash(hash);
    _validateObject(ecdsaOpts, {}, {
        hmac: 'function',
        lowS: 'boolean',
        randomBytes: 'function',
        bits2int: 'function',
        bits2int_modN: 'function',
    });
    const randomBytes = ecdsaOpts.randomBytes || randomBytesWeb;
    const hmac = ecdsaOpts.hmac ||
        ((key, ...msgs) => nobleHmac(hash, key, concatBytes(...msgs)));
    const { Fp, Fn } = Point;
    const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;
    const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);
    const defaultSigOpts = {
        prehash: false,
        lowS: typeof ecdsaOpts.lowS === 'boolean' ? ecdsaOpts.lowS : false,
        format: undefined, //'compact' as ECDSASigFormat,
        extraEntropy: false,
    };
    const defaultSigOpts_format = 'compact';
    function isBiggerThanHalfOrder(number) {
        const HALF = CURVE_ORDER >> _1n;
        return number > HALF;
    }
    function validateRS(title, num) {
        if (!Fn.isValidNot0(num))
            throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);
        return num;
    }
    function validateSigLength(bytes, format) {
        validateSigFormat(format);
        const size = lengths.signature;
        const sizer = format === 'compact' ? size : format === 'recovered' ? size + 1 : undefined;
        return abytes(bytes, sizer, `${format} signature`);
    }
    /**
     * ECDSA signature with its (r, s) properties. Supports compact, recovered & DER representations.
     */
    class Signature {
        constructor(r, s, recovery) {
            this.r = validateRS('r', r); // r in [1..N-1];
            this.s = validateRS('s', s); // s in [1..N-1];
            if (recovery != null)
                this.recovery = recovery;
            Object.freeze(this);
        }
        static fromBytes(bytes, format = defaultSigOpts_format) {
            validateSigLength(bytes, format);
            let recid;
            if (format === 'der') {
                const { r, s } = DER.toSig(abytes(bytes));
                return new Signature(r, s);
            }
            if (format === 'recovered') {
                recid = bytes[0];
                format = 'compact';
                bytes = bytes.subarray(1);
            }
            const L = Fn.BYTES;
            const r = bytes.subarray(0, L);
            const s = bytes.subarray(L, L * 2);
            return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);
        }
        static fromHex(hex, format) {
            return this.fromBytes(hexToBytes(hex), format);
        }
        addRecoveryBit(recovery) {
            return new Signature(this.r, this.s, recovery);
        }
        recoverPublicKey(messageHash) {
            const FIELD_ORDER = Fp.ORDER;
            const { r, s, recovery: rec } = this;
            if (rec == null || ![0, 1, 2, 3].includes(rec))
                throw new Error('recovery id invalid');
            // ECDSA recovery is hard for cofactor > 1 curves.
            // In sign, `r = q.x mod n`, and here we recover q.x from r.
            // While recovering q.x >= n, we need to add r+n for cofactor=1 curves.
            // However, for cofactor>1, r+n may not get q.x:
            // r+n*i would need to be done instead where i is unknown.
            // To easily get i, we either need to:
            // a. increase amount of valid recid values (4, 5...); OR
            // b. prohibit non-prime-order signatures (recid > 1).
            const hasCofactor = CURVE_ORDER * _2n < FIELD_ORDER;
            if (hasCofactor && rec > 1)
                throw new Error('recovery id is ambiguous for h>1 curve');
            const radj = rec === 2 || rec === 3 ? r + CURVE_ORDER : r;
            if (!Fp.isValid(radj))
                throw new Error('recovery id 2 or 3 invalid');
            const x = Fp.toBytes(radj);
            const R = Point.fromBytes(concatBytes(pprefix((rec & 1) === 0), x));
            const ir = Fn.inv(radj); // r^-1
            const h = bits2int_modN(ensureBytes('msgHash', messageHash)); // Truncate hash
            const u1 = Fn.create(-h * ir); // -hr^-1
            const u2 = Fn.create(s * ir); // sr^-1
            // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1). unsafe is fine: there is no private data.
            const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));
            if (Q.is0())
                throw new Error('point at infinify');
            Q.assertValidity();
            return Q;
        }
        // Signatures should be low-s, to prevent malleability.
        hasHighS() {
            return isBiggerThanHalfOrder(this.s);
        }
        toBytes(format = defaultSigOpts_format) {
            validateSigFormat(format);
            if (format === 'der')
                return hexToBytes(DER.hexFromSig(this));
            const r = Fn.toBytes(this.r);
            const s = Fn.toBytes(this.s);
            if (format === 'recovered') {
                if (this.recovery == null)
                    throw new Error('recovery bit must be present');
                return concatBytes(Uint8Array.of(this.recovery), r, s);
            }
            return concatBytes(r, s);
        }
        toHex(format) {
            return bytesToHex(this.toBytes(format));
        }
        // TODO: remove
        assertValidity() { }
        static fromCompact(hex) {
            return Signature.fromBytes(ensureBytes('sig', hex), 'compact');
        }
        static fromDER(hex) {
            return Signature.fromBytes(ensureBytes('sig', hex), 'der');
        }
        normalizeS() {
            return this.hasHighS() ? new Signature(this.r, Fn.neg(this.s), this.recovery) : this;
        }
        toDERRawBytes() {
            return this.toBytes('der');
        }
        toDERHex() {
            return bytesToHex(this.toBytes('der'));
        }
        toCompactRawBytes() {
            return this.toBytes('compact');
        }
        toCompactHex() {
            return bytesToHex(this.toBytes('compact'));
        }
    }
    // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.
    // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.
    // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.
    // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors
    const bits2int = ecdsaOpts.bits2int ||
        function bits2int_def(bytes) {
            // Our custom check "just in case", for protection against DoS
            if (bytes.length > 8192)
                throw new Error('input is too large');
            // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)
            // for some cases, since bytes.length * 8 is not actual bitLength.
            const num = bytesToNumberBE(bytes); // check for == u8 done here
            const delta = bytes.length * 8 - fnBits; // truncate to nBitLength leftmost bits
            return delta > 0 ? num >> BigInt(delta) : num;
        };
    const bits2int_modN = ecdsaOpts.bits2int_modN ||
        function bits2int_modN_def(bytes) {
            return Fn.create(bits2int(bytes)); // can't use bytesToNumberBE here
        };
    // Pads output with zero as per spec
    const ORDER_MASK = bitMask(fnBits);
    /** Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. */
    function int2octets(num) {
        // IMPORTANT: the check ensures working for case `Fn.BYTES != Fn.BITS * 8`
        aInRange('num < 2^' + fnBits, num, _0n, ORDER_MASK);
        return Fn.toBytes(num);
    }
    function validateMsgAndHash(message, prehash) {
        abytes(message, undefined, 'message');
        return prehash ? abytes(hash(message), undefined, 'prehashed message') : message;
    }
    /**
     * Steps A, D of RFC6979 3.2.
     * Creates RFC6979 seed; converts msg/privKey to numbers.
     * Used only in sign, not in verify.
     *
     * Warning: we cannot assume here that message has same amount of bytes as curve order,
     * this will be invalid at least for P521. Also it can be bigger for P224 + SHA256.
     */
    function prepSig(message, privateKey, opts) {
        if (['recovered', 'canonical'].some((k) => k in opts))
            throw new Error('sign() legacy options not supported');
        const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);
        message = validateMsgAndHash(message, prehash); // RFC6979 3.2 A: h1 = H(m)
        // We can't later call bits2octets, since nested bits2int is broken for curves
        // with fnBits % 8 !== 0. Because of that, we unwrap it here as int2octets call.
        // const bits2octets = (bits) => int2octets(bits2int_modN(bits))
        const h1int = bits2int_modN(message);
        const d = _normFnElement(Fn, privateKey); // validate secret key, convert to bigint
        const seedArgs = [int2octets(d), int2octets(h1int)];
        // extraEntropy. RFC6979 3.6: additional k' (optional).
        if (extraEntropy != null && extraEntropy !== false) {
            // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')
            // gen random bytes OR pass as-is
            const e = extraEntropy === true ? randomBytes(lengths.secretKey) : extraEntropy;
            seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes
        }
        const seed = concatBytes(...seedArgs); // Step D of RFC6979 3.2
        const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash!
        // Converts signature params into point w r/s, checks result for validity.
        // To transform k => Signature:
        // q = k⋅G
        // r = q.x mod n
        // s = k^-1(m + rd) mod n
        // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to
        // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:
        // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT
        function k2sig(kBytes) {
            // RFC 6979 Section 3.2, step 3: k = bits2int(T)
            // Important: all mod() calls here must be done over N
            const k = bits2int(kBytes); // mod n, not mod p
            if (!Fn.isValidNot0(k))
                return; // Valid scalars (including k) must be in 1..N-1
            const ik = Fn.inv(k); // k^-1 mod n
            const q = Point.BASE.multiply(k).toAffine(); // q = k⋅G
            const r = Fn.create(q.x); // r = q.x mod n
            if (r === _0n)
                return;
            const s = Fn.create(ik * Fn.create(m + r * d)); // Not using blinding here, see comment above
            if (s === _0n)
                return;
            let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n)
            let normS = s;
            if (lowS && isBiggerThanHalfOrder(s)) {
                normS = Fn.neg(s); // if lowS was passed, ensure s is always
                recovery ^= 1; // // in the bottom half of N
            }
            return new Signature(r, normS, recovery); // use normS, not s
        }
        return { seed, k2sig };
    }
    /**
     * Signs message hash with a secret key.
     *
     * ```
     * sign(m, d) where
     *   k = rfc6979_hmac_drbg(m, d)
     *   (x, y) = G × k
     *   r = x mod n
     *   s = (m + dr) / k mod n
     * ```
     */
    function sign(message, secretKey, opts = {}) {
        message = ensureBytes('message', message);
        const { seed, k2sig } = prepSig(message, secretKey, opts); // Steps A, D of RFC6979 3.2.
        const drbg = createHmacDrbg(hash.outputLen, Fn.BYTES, hmac);
        const sig = drbg(seed, k2sig); // Steps B, C, D, E, F, G
        return sig;
    }
    function tryParsingSig(sg) {
        // Try to deduce format
        let sig = undefined;
        const isHex = typeof sg === 'string' || isBytes(sg);
        const isObj = !isHex &&
            sg !== null &&
            typeof sg === 'object' &&
            typeof sg.r === 'bigint' &&
            typeof sg.s === 'bigint';
        if (!isHex && !isObj)
            throw new Error('invalid signature, expected Uint8Array, hex string or Signature instance');
        if (isObj) {
            sig = new Signature(sg.r, sg.s);
        }
        else if (isHex) {
            try {
                sig = Signature.fromBytes(ensureBytes('sig', sg), 'der');
            }
            catch (derError) {
                if (!(derError instanceof DER.Err))
                    throw derError;
            }
            if (!sig) {
                try {
                    sig = Signature.fromBytes(ensureBytes('sig', sg), 'compact');
                }
                catch (error) {
                    return false;
                }
            }
        }
        if (!sig)
            return false;
        return sig;
    }
    /**
     * Verifies a signature against message and public key.
     * Rejects lowS signatures by default: see {@link ECDSAVerifyOpts}.
     * Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:
     *
     * ```
     * verify(r, s, h, P) where
     *   u1 = hs^-1 mod n
     *   u2 = rs^-1 mod n
     *   R = u1⋅G + u2⋅P
     *   mod(R.x, n) == r
     * ```
     */
    function verify(signature, message, publicKey, opts = {}) {
        const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);
        publicKey = ensureBytes('publicKey', publicKey);
        message = validateMsgAndHash(ensureBytes('message', message), prehash);
        if ('strict' in opts)
            throw new Error('options.strict was renamed to lowS');
        const sig = format === undefined
            ? tryParsingSig(signature)
            : Signature.fromBytes(ensureBytes('sig', signature), format);
        if (sig === false)
            return false;
        try {
            const P = Point.fromBytes(publicKey);
            if (lowS && sig.hasHighS())
                return false;
            const { r, s } = sig;
            const h = bits2int_modN(message); // mod n, not mod p
            const is = Fn.inv(s); // s^-1 mod n
            const u1 = Fn.create(h * is); // u1 = hs^-1 mod n
            const u2 = Fn.create(r * is); // u2 = rs^-1 mod n
            const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2)); // u1⋅G + u2⋅P
            if (R.is0())
                return false;
            const v = Fn.create(R.x); // v = r.x mod n
            return v === r;
        }
        catch (e) {
            return false;
        }
    }
    function recoverPublicKey(signature, message, opts = {}) {
        const { prehash } = validateSigOpts(opts, defaultSigOpts);
        message = validateMsgAndHash(message, prehash);
        return Signature.fromBytes(signature, 'recovered').recoverPublicKey(message).toBytes();
    }
    return Object.freeze({
        keygen,
        getPublicKey,
        getSharedSecret,
        utils,
        lengths,
        Point,
        sign,
        verify,
        recoverPublicKey,
        Signature,
        hash,
    });
}
/** @deprecated use `weierstrass` in newer releases */
export function weierstrassPoints(c) {
    const { CURVE, curveOpts } = _weierstrass_legacy_opts_to_new(c);
    const Point = weierstrassN(CURVE, curveOpts);
    return _weierstrass_new_output_to_legacy(c, Point);
}
function _weierstrass_legacy_opts_to_new(c) {
    const CURVE = {
        a: c.a,
        b: c.b,
        p: c.Fp.ORDER,
        n: c.n,
        h: c.h,
        Gx: c.Gx,
        Gy: c.Gy,
    };
    const Fp = c.Fp;
    let allowedLengths = c.allowedPrivateKeyLengths
        ? Array.from(new Set(c.allowedPrivateKeyLengths.map((l) => Math.ceil(l / 2))))
        : undefined;
    const Fn = Field(CURVE.n, {
        BITS: c.nBitLength,
        allowedLengths: allowedLengths,
        modFromBytes: c.wrapPrivateKey,
    });
    const curveOpts = {
        Fp,
        Fn,
        allowInfinityPoint: c.allowInfinityPoint,
        endo: c.endo,
        isTorsionFree: c.isTorsionFree,
        clearCofactor: c.clearCofactor,
        fromBytes: c.fromBytes,
        toBytes: c.toBytes,
    };
    return { CURVE, curveOpts };
}
function _ecdsa_legacy_opts_to_new(c) {
    const { CURVE, curveOpts } = _weierstrass_legacy_opts_to_new(c);
    const ecdsaOpts = {
        hmac: c.hmac,
        randomBytes: c.randomBytes,
        lowS: c.lowS,
        bits2int: c.bits2int,
        bits2int_modN: c.bits2int_modN,
    };
    return { CURVE, curveOpts, hash: c.hash, ecdsaOpts };
}
export function _legacyHelperEquat(Fp, a, b) {
    /**
     * y² = x³ + ax + b: Short weierstrass curve formula. Takes x, returns y².
     * @returns y²
     */
    function weierstrassEquation(x) {
        const x2 = Fp.sqr(x); // x * x
        const x3 = Fp.mul(x2, x); // x² * x
        return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x³ + a * x + b
    }
    return weierstrassEquation;
}
function _weierstrass_new_output_to_legacy(c, Point) {
    const { Fp, Fn } = Point;
    function isWithinCurveOrder(num) {
        return inRange(num, _1n, Fn.ORDER);
    }
    const weierstrassEquation = _legacyHelperEquat(Fp, c.a, c.b);
    return Object.assign({}, {
        CURVE: c,
        Point: Point,
        ProjectivePoint: Point,
        normPrivateKeyToScalar: (key) => _normFnElement(Fn, key),
        weierstrassEquation,
        isWithinCurveOrder,
    });
}
function _ecdsa_new_output_to_legacy(c, _ecdsa) {
    const Point = _ecdsa.Point;
    return Object.assign({}, _ecdsa, {
        ProjectivePoint: Point,
        CURVE: Object.assign({}, c, nLength(Point.Fn.ORDER, Point.Fn.BITS)),
    });
}
// _ecdsa_legacy
export function weierstrass(c) {
    const { CURVE, curveOpts, hash, ecdsaOpts } = _ecdsa_legacy_opts_to_new(c);
    const Point = weierstrassN(CURVE, curveOpts);
    const signs = ecdsa(Point, hash, ecdsaOpts);
    return _ecdsa_new_output_to_legacy(c, signs);
}
//# sourceMappingURL=weierstrass.js.map{
  "type": "module",
  "sideEffects": false
}
/**
 * SECG secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).
 *
 * Belongs to Koblitz curves: it has efficiently-computable GLV endomorphism ψ,
 * check out {@link EndomorphismOpts}. Seems to be rigid (not backdoored).
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { sha256 } from '@noble/hashes/sha2.js';
import { randomBytes } from '@noble/hashes/utils.js';
import { createCurve } from "./_shortw_utils.js";
import { createHasher, isogenyMap, } from "./abstract/hash-to-curve.js";
import { Field, mapHashToField, mod, pow2 } from "./abstract/modular.js";
import { _normFnElement, mapToCurveSimpleSWU, } from "./abstract/weierstrass.js";
import { bytesToNumberBE, concatBytes, ensureBytes, inRange, numberToBytesBE, utf8ToBytes, } from "./utils.js";
// Seems like generator was produced from some seed:
// `Point.BASE.multiply(Point.Fn.inv(2n, N)).toAffine().x`
// // gives short x 0x3b78ce563f89a0ed9414f5aa28ad0d96d6795f9c63n
const secp256k1_CURVE = {
    p: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'),
    n: BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'),
    h: BigInt(1),
    a: BigInt(0),
    b: BigInt(7),
    Gx: BigInt('0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'),
    Gy: BigInt('0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8'),
};
const secp256k1_ENDO = {
    beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),
    basises: [
        [BigInt('0x3086d221a7d46bcde86c90e49284eb15'), -BigInt('0xe4437ed6010e88286f547fa90abfe4c3')],
        [BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'), BigInt('0x3086d221a7d46bcde86c90e49284eb15')],
    ],
};
const _0n = /* @__PURE__ */ BigInt(0);
const _1n = /* @__PURE__ */ BigInt(1);
const _2n = /* @__PURE__ */ BigInt(2);
/**
 * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.
 * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]
 */
function sqrtMod(y) {
    const P = secp256k1_CURVE.p;
    // prettier-ignore
    const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
    // prettier-ignore
    const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
    const b2 = (y * y * y) % P; // x^3, 11
    const b3 = (b2 * b2 * y) % P; // x^7
    const b6 = (pow2(b3, _3n, P) * b3) % P;
    const b9 = (pow2(b6, _3n, P) * b3) % P;
    const b11 = (pow2(b9, _2n, P) * b2) % P;
    const b22 = (pow2(b11, _11n, P) * b11) % P;
    const b44 = (pow2(b22, _22n, P) * b22) % P;
    const b88 = (pow2(b44, _44n, P) * b44) % P;
    const b176 = (pow2(b88, _88n, P) * b88) % P;
    const b220 = (pow2(b176, _44n, P) * b44) % P;
    const b223 = (pow2(b220, _3n, P) * b3) % P;
    const t1 = (pow2(b223, _23n, P) * b22) % P;
    const t2 = (pow2(t1, _6n, P) * b2) % P;
    const root = pow2(t2, _2n, P);
    if (!Fpk1.eql(Fpk1.sqr(root), y))
        throw new Error('Cannot find square root');
    return root;
}
const Fpk1 = Field(secp256k1_CURVE.p, { sqrt: sqrtMod });
/**
 * secp256k1 curve, ECDSA and ECDH methods.
 *
 * Field: `2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n`
 *
 * @example
 * ```js
 * import { secp256k1 } from '@noble/curves/secp256k1';
 * const { secretKey, publicKey } = secp256k1.keygen();
 * const msg = new TextEncoder().encode('hello');
 * const sig = secp256k1.sign(msg, secretKey);
 * const isValid = secp256k1.verify(sig, msg, publicKey) === true;
 * ```
 */
export const secp256k1 = createCurve({ ...secp256k1_CURVE, Fp: Fpk1, lowS: true, endo: secp256k1_ENDO }, sha256);
// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.
// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki
/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */
const TAGGED_HASH_PREFIXES = {};
function taggedHash(tag, ...messages) {
    let tagP = TAGGED_HASH_PREFIXES[tag];
    if (tagP === undefined) {
        const tagH = sha256(utf8ToBytes(tag));
        tagP = concatBytes(tagH, tagH);
        TAGGED_HASH_PREFIXES[tag] = tagP;
    }
    return sha256(concatBytes(tagP, ...messages));
}
// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03
const pointToBytes = (point) => point.toBytes(true).slice(1);
const Pointk1 = /* @__PURE__ */ (() => secp256k1.Point)();
const hasEven = (y) => y % _2n === _0n;
// Calculate point, scalar and bytes
function schnorrGetExtPubKey(priv) {
    const { Fn, BASE } = Pointk1;
    const d_ = _normFnElement(Fn, priv);
    const p = BASE.multiply(d_); // P = d'⋅G; 0 < d' < n check is done inside
    const scalar = hasEven(p.y) ? d_ : Fn.neg(d_);
    return { scalar, bytes: pointToBytes(p) };
}
/**
 * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.
 * @returns valid point checked for being on-curve
 */
function lift_x(x) {
    const Fp = Fpk1;
    if (!Fp.isValidNot0(x))
        throw new Error('invalid x: Fail if x ≥ p');
    const xx = Fp.create(x * x);
    const c = Fp.create(xx * x + BigInt(7)); // Let c = x³ + 7 mod p.
    let y = Fp.sqrt(c); // Let y = c^(p+1)/4 mod p. Same as sqrt().
    // Return the unique point P such that x(P) = x and
    // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.
    if (!hasEven(y))
        y = Fp.neg(y);
    const p = Pointk1.fromAffine({ x, y });
    p.assertValidity();
    return p;
}
const num = bytesToNumberBE;
/**
 * Create tagged hash, convert it to bigint, reduce modulo-n.
 */
function challenge(...args) {
    return Pointk1.Fn.create(num(taggedHash('BIP0340/challenge', ...args)));
}
/**
 * Schnorr public key is just `x` coordinate of Point as per BIP340.
 */
function schnorrGetPublicKey(secretKey) {
    return schnorrGetExtPubKey(secretKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G)
}
/**
 * Creates Schnorr signature as per BIP340. Verifies itself before returning anything.
 * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous.
 */
function schnorrSign(message, secretKey, auxRand = randomBytes(32)) {
    const { Fn } = Pointk1;
    const m = ensureBytes('message', message);
    const { bytes: px, scalar: d } = schnorrGetExtPubKey(secretKey); // checks for isWithinCurveOrder
    const a = ensureBytes('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array
    const t = Fn.toBytes(d ^ num(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a)
    const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m)
    // Let k' = int(rand) mod n. Fail if k' = 0. Let R = k'⋅G
    const { bytes: rx, scalar: k } = schnorrGetExtPubKey(rand);
    const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.
    const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n).
    sig.set(rx, 0);
    sig.set(Fn.toBytes(Fn.create(k + e * d)), 32);
    // If Verify(bytes(P), m, sig) (see below) returns failure, abort
    if (!schnorrVerify(sig, m, px))
        throw new Error('sign: Invalid signature produced');
    return sig;
}
/**
 * Verifies Schnorr signature.
 * Will swallow errors & return false except for initial type validation of arguments.
 */
function schnorrVerify(signature, message, publicKey) {
    const { Fn, BASE } = Pointk1;
    const sig = ensureBytes('signature', signature, 64);
    const m = ensureBytes('message', message);
    const pub = ensureBytes('publicKey', publicKey, 32);
    try {
        const P = lift_x(num(pub)); // P = lift_x(int(pk)); fail if that fails
        const r = num(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r ≥ p.
        if (!inRange(r, _1n, secp256k1_CURVE.p))
            return false;
        const s = num(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n.
        if (!inRange(s, _1n, secp256k1_CURVE.n))
            return false;
        // int(challenge(bytes(r)||bytes(P)||m))%n
        const e = challenge(Fn.toBytes(r), pointToBytes(P), m);
        // R = s⋅G - e⋅P, where -eP == (n-e)P
        const R = BASE.multiplyUnsafe(s).add(P.multiplyUnsafe(Fn.neg(e)));
        const { x, y } = R.toAffine();
        // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r.
        if (R.is0() || !hasEven(y) || x !== r)
            return false;
        return true;
    }
    catch (error) {
        return false;
    }
}
/**
 * Schnorr signatures over secp256k1.
 * https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki
 * @example
 * ```js
 * import { schnorr } from '@noble/curves/secp256k1';
 * const { secretKey, publicKey } = schnorr.keygen();
 * // const publicKey = schnorr.getPublicKey(secretKey);
 * const msg = new TextEncoder().encode('hello');
 * const sig = schnorr.sign(msg, secretKey);
 * const isValid = schnorr.verify(sig, msg, publicKey);
 * ```
 */
export const schnorr = /* @__PURE__ */ (() => {
    const size = 32;
    const seedLength = 48;
    const randomSecretKey = (seed = randomBytes(seedLength)) => {
        return mapHashToField(seed, secp256k1_CURVE.n);
    };
    // TODO: remove
    secp256k1.utils.randomSecretKey;
    function keygen(seed) {
        const secretKey = randomSecretKey(seed);
        return { secretKey, publicKey: schnorrGetPublicKey(secretKey) };
    }
    return {
        keygen,
        getPublicKey: schnorrGetPublicKey,
        sign: schnorrSign,
        verify: schnorrVerify,
        Point: Pointk1,
        utils: {
            randomSecretKey: randomSecretKey,
            randomPrivateKey: randomSecretKey,
            taggedHash,
            // TODO: remove
            lift_x,
            pointToBytes,
            numberToBytesBE,
            bytesToNumberBE,
            mod,
        },
        lengths: {
            secretKey: size,
            publicKey: size,
            publicKeyHasPrefix: false,
            signature: size * 2,
            seed: seedLength,
        },
    };
})();
const isoMap = /* @__PURE__ */ (() => isogenyMap(Fpk1, [
    // xNum
    [
        '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7',
        '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581',
        '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262',
        '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c',
    ],
    // xDen
    [
        '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b',
        '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14',
        '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1
    ],
    // yNum
    [
        '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c',
        '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3',
        '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931',
        '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84',
    ],
    // yDen
    [
        '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b',
        '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573',
        '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f',
        '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1
    ],
].map((i) => i.map((j) => BigInt(j)))))();
const mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fpk1, {
    A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),
    B: BigInt('1771'),
    Z: Fpk1.create(BigInt('-11')),
}))();
/** Hashing / encoding to secp256k1 points / field. RFC 9380 methods. */
export const secp256k1_hasher = /* @__PURE__ */ (() => createHasher(secp256k1.Point, (scalars) => {
    const { x, y } = mapSWU(Fpk1.create(scalars[0]));
    return isoMap(x, y);
}, {
    DST: 'secp256k1_XMD:SHA-256_SSWU_RO_',
    encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_',
    p: Fpk1.ORDER,
    m: 1,
    k: 128,
    expand: 'xmd',
    hash: sha256,
}))();
/** @deprecated use `import { secp256k1_hasher } from '@noble/curves/secp256k1.js';` */
export const hashToCurve = /* @__PURE__ */ (() => secp256k1_hasher.hashToCurve)();
/** @deprecated use `import { secp256k1_hasher } from '@noble/curves/secp256k1.js';` */
export const encodeToCurve = /* @__PURE__ */ (() => secp256k1_hasher.encodeToCurve)();
//# sourceMappingURL=secp256k1.js.map/**
 * Hex, bytes and number utilities.
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { abytes as abytes_, bytesToHex as bytesToHex_, concatBytes as concatBytes_, hexToBytes as hexToBytes_, isBytes as isBytes_, } from '@noble/hashes/utils.js';
export { abytes, anumber, bytesToHex, bytesToUtf8, concatBytes, hexToBytes, isBytes, randomBytes, utf8ToBytes, } from '@noble/hashes/utils.js';
const _0n = /* @__PURE__ */ BigInt(0);
const _1n = /* @__PURE__ */ BigInt(1);
export function abool(title, value) {
    if (typeof value !== 'boolean')
        throw new Error(title + ' boolean expected, got ' + value);
}
// tmp name until v2
export function _abool2(value, title = '') {
    if (typeof value !== 'boolean') {
        const prefix = title && `"${title}"`;
        throw new Error(prefix + 'expected boolean, got type=' + typeof value);
    }
    return value;
}
// tmp name until v2
/** Asserts something is Uint8Array. */
export function _abytes2(value, length, title = '') {
    const bytes = isBytes_(value);
    const len = value?.length;
    const needsLen = length !== undefined;
    if (!bytes || (needsLen && len !== length)) {
        const prefix = title && `"${title}" `;
        const ofLen = needsLen ? ` of length ${length}` : '';
        const got = bytes ? `length=${len}` : `type=${typeof value}`;
        throw new Error(prefix + 'expected Uint8Array' + ofLen + ', got ' + got);
    }
    return value;
}
// Used in weierstrass, der
export function numberToHexUnpadded(num) {
    const hex = num.toString(16);
    return hex.length & 1 ? '0' + hex : hex;
}
export function hexToNumber(hex) {
    if (typeof hex !== 'string')
        throw new Error('hex string expected, got ' + typeof hex);
    return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian
}
// BE: Big Endian, LE: Little Endian
export function bytesToNumberBE(bytes) {
    return hexToNumber(bytesToHex_(bytes));
}
export function bytesToNumberLE(bytes) {
    abytes_(bytes);
    return hexToNumber(bytesToHex_(Uint8Array.from(bytes).reverse()));
}
export function numberToBytesBE(n, len) {
    return hexToBytes_(n.toString(16).padStart(len * 2, '0'));
}
export function numberToBytesLE(n, len) {
    return numberToBytesBE(n, len).reverse();
}
// Unpadded, rarely used
export function numberToVarBytesBE(n) {
    return hexToBytes_(numberToHexUnpadded(n));
}
/**
 * Takes hex string or Uint8Array, converts to Uint8Array.
 * Validates output length.
 * Will throw error for other types.
 * @param title descriptive title for an error e.g. 'secret key'
 * @param hex hex string or Uint8Array
 * @param expectedLength optional, will compare to result array's length
 * @returns
 */
export function ensureBytes(title, hex, expectedLength) {
    let res;
    if (typeof hex === 'string') {
        try {
            res = hexToBytes_(hex);
        }
        catch (e) {
            throw new Error(title + ' must be hex string or Uint8Array, cause: ' + e);
        }
    }
    else if (isBytes_(hex)) {
        // Uint8Array.from() instead of hash.slice() because node.js Buffer
        // is instance of Uint8Array, and its slice() creates **mutable** copy
        res = Uint8Array.from(hex);
    }
    else {
        throw new Error(title + ' must be hex string or Uint8Array');
    }
    const len = res.length;
    if (typeof expectedLength === 'number' && len !== expectedLength)
        throw new Error(title + ' of length ' + expectedLength + ' expected, got ' + len);
    return res;
}
// Compares 2 u8a-s in kinda constant time
export function equalBytes(a, b) {
    if (a.length !== b.length)
        return false;
    let diff = 0;
    for (let i = 0; i < a.length; i++)
        diff |= a[i] ^ b[i];
    return diff === 0;
}
/**
 * Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,
 * and Buffer#slice creates mutable copy. Never use Buffers!
 */
export function copyBytes(bytes) {
    return Uint8Array.from(bytes);
}
/**
 * Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols
 * Should be safe to use for things expected to be ASCII.
 * Returns exact same result as utf8ToBytes for ASCII or throws.
 */
export function asciiToBytes(ascii) {
    return Uint8Array.from(ascii, (c, i) => {
        const charCode = c.charCodeAt(0);
        if (c.length !== 1 || charCode > 127) {
            throw new Error(`string contains non-ASCII character "${ascii[i]}" with code ${charCode} at position ${i}`);
        }
        return charCode;
    });
}
/**
 * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
 */
// export const utf8ToBytes: typeof utf8ToBytes_ = utf8ToBytes_;
/**
 * Converts bytes to string using UTF8 encoding.
 * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'
 */
// export const bytesToUtf8: typeof bytesToUtf8_ = bytesToUtf8_;
// Is positive bigint
const isPosBig = (n) => typeof n === 'bigint' && _0n <= n;
export function inRange(n, min, max) {
    return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
}
/**
 * Asserts min <= n < max. NOTE: It's < max and not <= max.
 * @example
 * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)
 */
export function aInRange(title, n, min, max) {
    // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?
    // consider P=256n, min=0n, max=P
    // - a for min=0 would require -1:          `inRange('x', x, -1n, P)`
    // - b would commonly require subtraction:  `inRange('x', x, 0n, P - 1n)`
    // - our way is the cleanest:               `inRange('x', x, 0n, P)
    if (!inRange(n, min, max))
        throw new Error('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);
}
// Bit operations
/**
 * Calculates amount of bits in a bigint.
 * Same as `n.toString(2).length`
 * TODO: merge with nLength in modular
 */
export function bitLen(n) {
    let len;
    for (len = 0; n > _0n; n >>= _1n, len += 1)
        ;
    return len;
}
/**
 * Gets single bit at position.
 * NOTE: first bit position is 0 (same as arrays)
 * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`
 */
export function bitGet(n, pos) {
    return (n >> BigInt(pos)) & _1n;
}
/**
 * Sets single bit at position.
 */
export function bitSet(n, pos, value) {
    return n | ((value ? _1n : _0n) << BigInt(pos));
}
/**
 * Calculate mask for N bits. Not using ** operator with bigints because of old engines.
 * Same as BigInt(`0b${Array(i).fill('1').join('')}`)
 */
export const bitMask = (n) => (_1n << BigInt(n)) - _1n;
/**
 * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
 * @returns function that will call DRBG until 2nd arg returns something meaningful
 * @example
 *   const drbg = createHmacDRBG<Key>(32, 32, hmac);
 *   drbg(seed, bytesToKey); // bytesToKey must return Key or undefined
 */
export function createHmacDrbg(hashLen, qByteLen, hmacFn) {
    if (typeof hashLen !== 'number' || hashLen < 2)
        throw new Error('hashLen must be a number');
    if (typeof qByteLen !== 'number' || qByteLen < 2)
        throw new Error('qByteLen must be a number');
    if (typeof hmacFn !== 'function')
        throw new Error('hmacFn must be a function');
    // Step B, Step C: set hashLen to 8*ceil(hlen/8)
    const u8n = (len) => new Uint8Array(len); // creates Uint8Array
    const u8of = (byte) => Uint8Array.of(byte); // another shortcut
    let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
    let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same
    let i = 0; // Iterations counter, will throw when over 1000
    const reset = () => {
        v.fill(1);
        k.fill(0);
        i = 0;
    };
    const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)
    const reseed = (seed = u8n(0)) => {
        // HMAC-DRBG reseed() function. Steps D-G
        k = h(u8of(0x00), seed); // k = hmac(k || v || 0x00 || seed)
        v = h(); // v = hmac(k || v)
        if (seed.length === 0)
            return;
        k = h(u8of(0x01), seed); // k = hmac(k || v || 0x01 || seed)
        v = h(); // v = hmac(k || v)
    };
    const gen = () => {
        // HMAC-DRBG generate() function
        if (i++ >= 1000)
            throw new Error('drbg: tried 1000 values');
        let len = 0;
        const out = [];
        while (len < qByteLen) {
            v = h();
            const sl = v.slice();
            out.push(sl);
            len += v.length;
        }
        return concatBytes_(...out);
    };
    const genUntil = (seed, pred) => {
        reset();
        reseed(seed); // Steps D-G
        let res = undefined; // Step H: grind until k is in [1..n-1]
        while (!(res = pred(gen())))
            reseed();
        reset();
        return res;
    };
    return genUntil;
}
// Validating curves and fields
const validatorFns = {
    bigint: (val) => typeof val === 'bigint',
    function: (val) => typeof val === 'function',
    boolean: (val) => typeof val === 'boolean',
    string: (val) => typeof val === 'string',
    stringOrUint8Array: (val) => typeof val === 'string' || isBytes_(val),
    isSafeInteger: (val) => Number.isSafeInteger(val),
    array: (val) => Array.isArray(val),
    field: (val, object) => object.Fp.isValid(val),
    hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),
};
// type Record<K extends string | number | symbol, T> = { [P in K]: T; }
export function validateObject(object, validators, optValidators = {}) {
    const checkField = (fieldName, type, isOptional) => {
        const checkVal = validatorFns[type];
        if (typeof checkVal !== 'function')
            throw new Error('invalid validator function');
        const val = object[fieldName];
        if (isOptional && val === undefined)
            return;
        if (!checkVal(val, object)) {
            throw new Error('param ' + String(fieldName) + ' is invalid. Expected ' + type + ', got ' + val);
        }
    };
    for (const [fieldName, type] of Object.entries(validators))
        checkField(fieldName, type, false);
    for (const [fieldName, type] of Object.entries(optValidators))
        checkField(fieldName, type, true);
    return object;
}
// validate type tests
// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };
// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!
// // Should fail type-check
// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });
// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });
// const z3 = validateObject(o, { test: 'boolean', z: 'bug' });
// const z4 = validateObject(o, { a: 'boolean', z: 'bug' });
export function isHash(val) {
    return typeof val === 'function' && Number.isSafeInteger(val.outputLen);
}
export function _validateObject(object, fields, optFields = {}) {
    if (!object || typeof object !== 'object')
        throw new Error('expected valid options object');
    function checkField(fieldName, expectedType, isOpt) {
        const val = object[fieldName];
        if (isOpt && val === undefined)
            return;
        const current = typeof val;
        if (current !== expectedType || val === null)
            throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
    }
    Object.entries(fields).forEach(([k, v]) => checkField(k, v, false));
    Object.entries(optFields).forEach(([k, v]) => checkField(k, v, true));
}
/**
 * throws not implemented error
 */
export const notImplemented = () => {
    throw new Error('not implemented');
};
/**
 * Memoizes (caches) computation result.
 * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.
 */
export function memoized(fn) {
    const map = new WeakMap();
    return (arg, ...args) => {
        const val = map.get(arg);
        if (val !== undefined)
            return val;
        const computed = fn(arg, ...args);
        map.set(arg, computed);
        return computed;
    };
}
//# sourceMappingURL=utils.js.map/**
 * Internal Merkle-Damgard hash utils.
 * @module
 */
import { Hash, abytes, aexists, aoutput, clean, createView, toBytes } from "./utils.js";
/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */
export function setBigUint64(view, byteOffset, value, isLE) {
    if (typeof view.setBigUint64 === 'function')
        return view.setBigUint64(byteOffset, value, isLE);
    const _32n = BigInt(32);
    const _u32_max = BigInt(0xffffffff);
    const wh = Number((value >> _32n) & _u32_max);
    const wl = Number(value & _u32_max);
    const h = isLE ? 4 : 0;
    const l = isLE ? 0 : 4;
    view.setUint32(byteOffset + h, wh, isLE);
    view.setUint32(byteOffset + l, wl, isLE);
}
/** Choice: a ? b : c */
export function Chi(a, b, c) {
    return (a & b) ^ (~a & c);
}
/** Majority function, true if any two inputs is true. */
export function Maj(a, b, c) {
    return (a & b) ^ (a & c) ^ (b & c);
}
/**
 * Merkle-Damgard hash construction base class.
 * Could be used to create MD5, RIPEMD, SHA1, SHA2.
 */
export class HashMD extends Hash {
    constructor(blockLen, outputLen, padOffset, isLE) {
        super();
        this.finished = false;
        this.length = 0;
        this.pos = 0;
        this.destroyed = false;
        this.blockLen = blockLen;
        this.outputLen = outputLen;
        this.padOffset = padOffset;
        this.isLE = isLE;
        this.buffer = new Uint8Array(blockLen);
        this.view = createView(this.buffer);
    }
    update(data) {
        aexists(this);
        data = toBytes(data);
        abytes(data);
        const { view, buffer, blockLen } = this;
        const len = data.length;
        for (let pos = 0; pos < len;) {
            const take = Math.min(blockLen - this.pos, len - pos);
            // Fast path: we have at least one block in input, cast it to view and process
            if (take === blockLen) {
                const dataView = createView(data);
                for (; blockLen <= len - pos; pos += blockLen)
                    this.process(dataView, pos);
                continue;
            }
            buffer.set(data.subarray(pos, pos + take), this.pos);
            this.pos += take;
            pos += take;
            if (this.pos === blockLen) {
                this.process(view, 0);
                this.pos = 0;
            }
        }
        this.length += data.length;
        this.roundClean();
        return this;
    }
    digestInto(out) {
        aexists(this);
        aoutput(out, this);
        this.finished = true;
        // Padding
        // We can avoid allocation of buffer for padding completely if it
        // was previously not allocated here. But it won't change performance.
        const { buffer, view, blockLen, isLE } = this;
        let { pos } = this;
        // append the bit '1' to the message
        buffer[pos++] = 0b10000000;
        clean(this.buffer.subarray(pos));
        // we have less than padOffset left in buffer, so we cannot put length in
        // current block, need process it and pad again
        if (this.padOffset > blockLen - pos) {
            this.process(view, 0);
            pos = 0;
        }
        // Pad until full block byte with zeros
        for (let i = pos; i < blockLen; i++)
            buffer[i] = 0;
        // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that
        // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.
        // So we just write lowest 64 bits of that value.
        setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
        this.process(view, 0);
        const oview = createView(out);
        const len = this.outputLen;
        // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT
        if (len % 4)
            throw new Error('_sha2: outputLen should be aligned to 32bit');
        const outLen = len / 4;
        const state = this.get();
        if (outLen > state.length)
            throw new Error('_sha2: outputLen bigger than state');
        for (let i = 0; i < outLen; i++)
            oview.setUint32(4 * i, state[i], isLE);
    }
    digest() {
        const { buffer, outputLen } = this;
        this.digestInto(buffer);
        const res = buffer.slice(0, outputLen);
        this.destroy();
        return res;
    }
    _cloneInto(to) {
        to || (to = new this.constructor());
        to.set(...this.get());
        const { blockLen, buffer, length, finished, destroyed, pos } = this;
        to.destroyed = destroyed;
        to.finished = finished;
        to.length = length;
        to.pos = pos;
        if (length % blockLen)
            to.buffer.set(buffer);
        return to;
    }
    clone() {
        return this._cloneInto();
    }
}
/**
 * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.
 * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.
 */
/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */
export const SHA256_IV = /* @__PURE__ */ Uint32Array.from([
    0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
]);
/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */
export const SHA224_IV = /* @__PURE__ */ Uint32Array.from([
    0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,
]);
/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */
export const SHA384_IV = /* @__PURE__ */ Uint32Array.from([
    0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,
    0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,
]);
/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */
export const SHA512_IV = /* @__PURE__ */ Uint32Array.from([
    0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,
    0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,
]);
//# sourceMappingURL=_md.js.map/**
 * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.
 * @todo re-check https://issues.chromium.org/issues/42212588
 * @module
 */
const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
const _32n = /* @__PURE__ */ BigInt(32);
function fromBig(n, le = false) {
    if (le)
        return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };
    return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
}
function split(lst, le = false) {
    const len = lst.length;
    let Ah = new Uint32Array(len);
    let Al = new Uint32Array(len);
    for (let i = 0; i < len; i++) {
        const { h, l } = fromBig(lst[i], le);
        [Ah[i], Al[i]] = [h, l];
    }
    return [Ah, Al];
}
const toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);
// for Shift in [0, 32)
const shrSH = (h, _l, s) => h >>> s;
const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
// Right rotate for Shift in [1, 32)
const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));
const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
// Right rotate for Shift in (32, 64), NOTE: 32 is special case.
const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));
const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));
// Right rotate for shift===32 (just swaps l&h)
const rotr32H = (_h, l) => l;
const rotr32L = (h, _l) => h;
// Left rotate for Shift in [1, 32)
const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));
const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));
// Left rotate for Shift in (32, 64), NOTE: 32 is special case.
const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));
const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));
// JS uses 32-bit signed integers for bitwise operations which means we cannot
// simple take carry out of low bit sum by shift, we need to use division.
function add(Ah, Al, Bh, Bl) {
    const l = (Al >>> 0) + (Bl >>> 0);
    return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };
}
// Addition with more than 2 elements
const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;
const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;
const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;
// prettier-ignore
export { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig };
// prettier-ignore
const u64 = {
    fromBig, split, toBig,
    shrSH, shrSL,
    rotrSH, rotrSL, rotrBH, rotrBL,
    rotr32H, rotr32L,
    rotlSH, rotlSL, rotlBH, rotlBL,
    add, add3L, add3H, add4L, add4H, add5H, add5L,
};
export default u64;
//# sourceMappingURL=_u64.js.mapexport const crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;
//# sourceMappingURL=crypto.js.map/**
 * HMAC: RFC2104 message authentication code.
 * @module
 */
import { abytes, aexists, ahash, clean, Hash, toBytes } from "./utils.js";
export class HMAC extends Hash {
    constructor(hash, _key) {
        super();
        this.finished = false;
        this.destroyed = false;
        ahash(hash);
        const key = toBytes(_key);
        this.iHash = hash.create();
        if (typeof this.iHash.update !== 'function')
            throw new Error('Expected instance of class which extends utils.Hash');
        this.blockLen = this.iHash.blockLen;
        this.outputLen = this.iHash.outputLen;
        const blockLen = this.blockLen;
        const pad = new Uint8Array(blockLen);
        // blockLen can be bigger than outputLen
        pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
        for (let i = 0; i < pad.length; i++)
            pad[i] ^= 0x36;
        this.iHash.update(pad);
        // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone
        this.oHash = hash.create();
        // Undo internal XOR && apply outer XOR
        for (let i = 0; i < pad.length; i++)
            pad[i] ^= 0x36 ^ 0x5c;
        this.oHash.update(pad);
        clean(pad);
    }
    update(buf) {
        aexists(this);
        this.iHash.update(buf);
        return this;
    }
    digestInto(out) {
        aexists(this);
        abytes(out, this.outputLen);
        this.finished = true;
        this.iHash.digestInto(out);
        this.oHash.update(out);
        this.oHash.digestInto(out);
        this.destroy();
    }
    digest() {
        const out = new Uint8Array(this.oHash.outputLen);
        this.digestInto(out);
        return out;
    }
    _cloneInto(to) {
        // Create new instance without calling constructor since key already in state and we don't know it.
        to || (to = Object.create(Object.getPrototypeOf(this), {}));
        const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
        to = to;
        to.finished = finished;
        to.destroyed = destroyed;
        to.blockLen = blockLen;
        to.outputLen = outputLen;
        to.oHash = oHash._cloneInto(to.oHash);
        to.iHash = iHash._cloneInto(to.iHash);
        return to;
    }
    clone() {
        return this._cloneInto();
    }
    destroy() {
        this.destroyed = true;
        this.oHash.destroy();
        this.iHash.destroy();
    }
}
/**
 * HMAC: RFC2104 message authentication code.
 * @param hash - function that would be used e.g. sha256
 * @param key - message key
 * @param message - message data
 * @example
 * import { hmac } from '@noble/hashes/hmac';
 * import { sha256 } from '@noble/hashes/sha2';
 * const mac1 = hmac(sha256, 'key', 'message');
 */
export const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
hmac.create = (hash, key) => new HMAC(hash, key);
//# sourceMappingURL=hmac.js.map{
  "type": "module",
  "sideEffects": false,
  "browser": {
    "node:crypto": false
  },
  "node": {
    "./crypto": "./esm/cryptoNode.js"
  }
}
/**
 * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.
 * SHA256 is the fastest hash implementable in JS, even faster than Blake3.
 * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and
 * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).
 * @module
 */
import { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from "./_md.js";
import * as u64 from "./_u64.js";
import { clean, createHasher, rotr } from "./utils.js";
/**
 * Round constants:
 * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)
 */
// prettier-ignore
const SHA256_K = /* @__PURE__ */ Uint32Array.from([
    0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
    0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
    0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
    0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
    0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
    0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
    0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
    0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
]);
/** Reusable temporary buffer. "W" comes straight from spec. */
const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
export class SHA256 extends HashMD {
    constructor(outputLen = 32) {
        super(64, outputLen, 8, false);
        // We cannot use array here since array allows indexing by variable
        // which means optimizer/compiler cannot use registers.
        this.A = SHA256_IV[0] | 0;
        this.B = SHA256_IV[1] | 0;
        this.C = SHA256_IV[2] | 0;
        this.D = SHA256_IV[3] | 0;
        this.E = SHA256_IV[4] | 0;
        this.F = SHA256_IV[5] | 0;
        this.G = SHA256_IV[6] | 0;
        this.H = SHA256_IV[7] | 0;
    }
    get() {
        const { A, B, C, D, E, F, G, H } = this;
        return [A, B, C, D, E, F, G, H];
    }
    // prettier-ignore
    set(A, B, C, D, E, F, G, H) {
        this.A = A | 0;
        this.B = B | 0;
        this.C = C | 0;
        this.D = D | 0;
        this.E = E | 0;
        this.F = F | 0;
        this.G = G | 0;
        this.H = H | 0;
    }
    process(view, offset) {
        // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array
        for (let i = 0; i < 16; i++, offset += 4)
            SHA256_W[i] = view.getUint32(offset, false);
        for (let i = 16; i < 64; i++) {
            const W15 = SHA256_W[i - 15];
            const W2 = SHA256_W[i - 2];
            const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);
            const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);
            SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;
        }
        // Compression function main loop, 64 rounds
        let { A, B, C, D, E, F, G, H } = this;
        for (let i = 0; i < 64; i++) {
            const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
            const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
            const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
            const T2 = (sigma0 + Maj(A, B, C)) | 0;
            H = G;
            G = F;
            F = E;
            E = (D + T1) | 0;
            D = C;
            C = B;
            B = A;
            A = (T1 + T2) | 0;
        }
        // Add the compressed chunk to the current hash value
        A = (A + this.A) | 0;
        B = (B + this.B) | 0;
        C = (C + this.C) | 0;
        D = (D + this.D) | 0;
        E = (E + this.E) | 0;
        F = (F + this.F) | 0;
        G = (G + this.G) | 0;
        H = (H + this.H) | 0;
        this.set(A, B, C, D, E, F, G, H);
    }
    roundClean() {
        clean(SHA256_W);
    }
    destroy() {
        this.set(0, 0, 0, 0, 0, 0, 0, 0);
        clean(this.buffer);
    }
}
export class SHA224 extends SHA256 {
    constructor() {
        super(28);
        this.A = SHA224_IV[0] | 0;
        this.B = SHA224_IV[1] | 0;
        this.C = SHA224_IV[2] | 0;
        this.D = SHA224_IV[3] | 0;
        this.E = SHA224_IV[4] | 0;
        this.F = SHA224_IV[5] | 0;
        this.G = SHA224_IV[6] | 0;
        this.H = SHA224_IV[7] | 0;
    }
}
// SHA2-512 is slower than sha256 in js because u64 operations are slow.
// Round contants
// First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409
// prettier-ignore
const K512 = /* @__PURE__ */ (() => u64.split([
    '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',
    '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',
    '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',
    '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',
    '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',
    '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',
    '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',
    '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',
    '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',
    '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',
    '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',
    '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',
    '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',
    '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',
    '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',
    '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',
    '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',
    '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',
    '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',
    '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'
].map(n => BigInt(n))))();
const SHA512_Kh = /* @__PURE__ */ (() => K512[0])();
const SHA512_Kl = /* @__PURE__ */ (() => K512[1])();
// Reusable temporary buffers
const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
export class SHA512 extends HashMD {
    constructor(outputLen = 64) {
        super(128, outputLen, 16, false);
        // We cannot use array here since array allows indexing by variable
        // which means optimizer/compiler cannot use registers.
        // h -- high 32 bits, l -- low 32 bits
        this.Ah = SHA512_IV[0] | 0;
        this.Al = SHA512_IV[1] | 0;
        this.Bh = SHA512_IV[2] | 0;
        this.Bl = SHA512_IV[3] | 0;
        this.Ch = SHA512_IV[4] | 0;
        this.Cl = SHA512_IV[5] | 0;
        this.Dh = SHA512_IV[6] | 0;
        this.Dl = SHA512_IV[7] | 0;
        this.Eh = SHA512_IV[8] | 0;
        this.El = SHA512_IV[9] | 0;
        this.Fh = SHA512_IV[10] | 0;
        this.Fl = SHA512_IV[11] | 0;
        this.Gh = SHA512_IV[12] | 0;
        this.Gl = SHA512_IV[13] | 0;
        this.Hh = SHA512_IV[14] | 0;
        this.Hl = SHA512_IV[15] | 0;
    }
    // prettier-ignore
    get() {
        const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
        return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
    }
    // prettier-ignore
    set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
        this.Ah = Ah | 0;
        this.Al = Al | 0;
        this.Bh = Bh | 0;
        this.Bl = Bl | 0;
        this.Ch = Ch | 0;
        this.Cl = Cl | 0;
        this.Dh = Dh | 0;
        this.Dl = Dl | 0;
        this.Eh = Eh | 0;
        this.El = El | 0;
        this.Fh = Fh | 0;
        this.Fl = Fl | 0;
        this.Gh = Gh | 0;
        this.Gl = Gl | 0;
        this.Hh = Hh | 0;
        this.Hl = Hl | 0;
    }
    process(view, offset) {
        // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array
        for (let i = 0; i < 16; i++, offset += 4) {
            SHA512_W_H[i] = view.getUint32(offset);
            SHA512_W_L[i] = view.getUint32((offset += 4));
        }
        for (let i = 16; i < 80; i++) {
            // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)
            const W15h = SHA512_W_H[i - 15] | 0;
            const W15l = SHA512_W_L[i - 15] | 0;
            const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);
            const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);
            // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)
            const W2h = SHA512_W_H[i - 2] | 0;
            const W2l = SHA512_W_L[i - 2] | 0;
            const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);
            const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);
            // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];
            const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
            const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
            SHA512_W_H[i] = SUMh | 0;
            SHA512_W_L[i] = SUMl | 0;
        }
        let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
        // Compression function main loop, 80 rounds
        for (let i = 0; i < 80; i++) {
            // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)
            const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);
            const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);
            //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
            const CHIh = (Eh & Fh) ^ (~Eh & Gh);
            const CHIl = (El & Fl) ^ (~El & Gl);
            // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]
            // prettier-ignore
            const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
            const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
            const T1l = T1ll | 0;
            // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)
            const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);
            const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);
            const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);
            const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);
            Hh = Gh | 0;
            Hl = Gl | 0;
            Gh = Fh | 0;
            Gl = Fl | 0;
            Fh = Eh | 0;
            Fl = El | 0;
            ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
            Dh = Ch | 0;
            Dl = Cl | 0;
            Ch = Bh | 0;
            Cl = Bl | 0;
            Bh = Ah | 0;
            Bl = Al | 0;
            const All = u64.add3L(T1l, sigma0l, MAJl);
            Ah = u64.add3H(All, T1h, sigma0h, MAJh);
            Al = All | 0;
        }
        // Add the compressed chunk to the current hash value
        ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
        ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
        ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
        ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
        ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
        ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
        ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
        ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
        this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
    }
    roundClean() {
        clean(SHA512_W_H, SHA512_W_L);
    }
    destroy() {
        clean(this.buffer);
        this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
    }
}
export class SHA384 extends SHA512 {
    constructor() {
        super(48);
        this.Ah = SHA384_IV[0] | 0;
        this.Al = SHA384_IV[1] | 0;
        this.Bh = SHA384_IV[2] | 0;
        this.Bl = SHA384_IV[3] | 0;
        this.Ch = SHA384_IV[4] | 0;
        this.Cl = SHA384_IV[5] | 0;
        this.Dh = SHA384_IV[6] | 0;
        this.Dl = SHA384_IV[7] | 0;
        this.Eh = SHA384_IV[8] | 0;
        this.El = SHA384_IV[9] | 0;
        this.Fh = SHA384_IV[10] | 0;
        this.Fl = SHA384_IV[11] | 0;
        this.Gh = SHA384_IV[12] | 0;
        this.Gl = SHA384_IV[13] | 0;
        this.Hh = SHA384_IV[14] | 0;
        this.Hl = SHA384_IV[15] | 0;
    }
}
/**
 * Truncated SHA512/256 and SHA512/224.
 * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as "intermediary" IV of SHA512/t.
 * Then t hashes string to produce result IV.
 * See `test/misc/sha2-gen-iv.js`.
 */
/** SHA512/224 IV */
const T224_IV = /* @__PURE__ */ Uint32Array.from([
    0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,
    0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,
]);
/** SHA512/256 IV */
const T256_IV = /* @__PURE__ */ Uint32Array.from([
    0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,
    0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,
]);
export class SHA512_224 extends SHA512 {
    constructor() {
        super(28);
        this.Ah = T224_IV[0] | 0;
        this.Al = T224_IV[1] | 0;
        this.Bh = T224_IV[2] | 0;
        this.Bl = T224_IV[3] | 0;
        this.Ch = T224_IV[4] | 0;
        this.Cl = T224_IV[5] | 0;
        this.Dh = T224_IV[6] | 0;
        this.Dl = T224_IV[7] | 0;
        this.Eh = T224_IV[8] | 0;
        this.El = T224_IV[9] | 0;
        this.Fh = T224_IV[10] | 0;
        this.Fl = T224_IV[11] | 0;
        this.Gh = T224_IV[12] | 0;
        this.Gl = T224_IV[13] | 0;
        this.Hh = T224_IV[14] | 0;
        this.Hl = T224_IV[15] | 0;
    }
}
export class SHA512_256 extends SHA512 {
    constructor() {
        super(32);
        this.Ah = T256_IV[0] | 0;
        this.Al = T256_IV[1] | 0;
        this.Bh = T256_IV[2] | 0;
        this.Bl = T256_IV[3] | 0;
        this.Ch = T256_IV[4] | 0;
        this.Cl = T256_IV[5] | 0;
        this.Dh = T256_IV[6] | 0;
        this.Dl = T256_IV[7] | 0;
        this.Eh = T256_IV[8] | 0;
        this.El = T256_IV[9] | 0;
        this.Fh = T256_IV[10] | 0;
        this.Fl = T256_IV[11] | 0;
        this.Gh = T256_IV[12] | 0;
        this.Gl = T256_IV[13] | 0;
        this.Hh = T256_IV[14] | 0;
        this.Hl = T256_IV[15] | 0;
    }
}
/**
 * SHA2-256 hash function from RFC 4634.
 *
 * It is the fastest JS hash, even faster than Blake3.
 * To break sha256 using birthday attack, attackers need to try 2^128 hashes.
 * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
 */
export const sha256 = /* @__PURE__ */ createHasher(() => new SHA256());
/** SHA2-224 hash function from RFC 4634 */
export const sha224 = /* @__PURE__ */ createHasher(() => new SHA224());
/** SHA2-512 hash function from RFC 4634. */
export const sha512 = /* @__PURE__ */ createHasher(() => new SHA512());
/** SHA2-384 hash function from RFC 4634. */
export const sha384 = /* @__PURE__ */ createHasher(() => new SHA384());
/**
 * SHA2-512/256 "truncated" hash function, with improved resistance to length extension attacks.
 * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).
 */
export const sha512_256 = /* @__PURE__ */ createHasher(() => new SHA512_256());
/**
 * SHA2-512/224 "truncated" hash function, with improved resistance to length extension attacks.
 * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).
 */
export const sha512_224 = /* @__PURE__ */ createHasher(() => new SHA512_224());
//# sourceMappingURL=sha2.js.map/**
 * Utilities for hex, bytes, CSPRNG.
 * @module
 */
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
// node.js versions earlier than v19 don't declare it in global scope.
// For node.js, package.json#exports field mapping rewrites import
// from `crypto` to `cryptoNode`, which imports native module.
// Makes the utils un-importable in browsers without a bundler.
// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.
import { crypto } from '@noble/hashes/crypto';
/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */
export function isBytes(a) {
    return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
}
/** Asserts something is positive integer. */
export function anumber(n) {
    if (!Number.isSafeInteger(n) || n < 0)
        throw new Error('positive integer expected, got ' + n);
}
/** Asserts something is Uint8Array. */
export function abytes(b, ...lengths) {
    if (!isBytes(b))
        throw new Error('Uint8Array expected');
    if (lengths.length > 0 && !lengths.includes(b.length))
        throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);
}
/** Asserts something is hash */
export function ahash(h) {
    if (typeof h !== 'function' || typeof h.create !== 'function')
        throw new Error('Hash should be wrapped by utils.createHasher');
    anumber(h.outputLen);
    anumber(h.blockLen);
}
/** Asserts a hash instance has not been destroyed / finished */
export function aexists(instance, checkFinished = true) {
    if (instance.destroyed)
        throw new Error('Hash instance has been destroyed');
    if (checkFinished && instance.finished)
        throw new Error('Hash#digest() has already been called');
}
/** Asserts output is properly-sized byte array */
export function aoutput(out, instance) {
    abytes(out);
    const min = instance.outputLen;
    if (out.length < min) {
        throw new Error('digestInto() expects output buffer of length at least ' + min);
    }
}
/** Cast u8 / u16 / u32 to u8. */
export function u8(arr) {
    return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
}
/** Cast u8 / u16 / u32 to u32. */
export function u32(arr) {
    return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
}
/** Zeroize a byte array. Warning: JS provides no guarantees. */
export function clean(...arrays) {
    for (let i = 0; i < arrays.length; i++) {
        arrays[i].fill(0);
    }
}
/** Create DataView of an array for easy byte-level manipulation. */
export function createView(arr) {
    return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
}
/** The rotate right (circular right shift) operation for uint32 */
export function rotr(word, shift) {
    return (word << (32 - shift)) | (word >>> shift);
}
/** The rotate left (circular left shift) operation for uint32 */
export function rotl(word, shift) {
    return (word << shift) | ((word >>> (32 - shift)) >>> 0);
}
/** Is current platform little-endian? Most are. Big-Endian platform: IBM */
export const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();
/** The byte swap operation for uint32 */
export function byteSwap(word) {
    return (((word << 24) & 0xff000000) |
        ((word << 8) & 0xff0000) |
        ((word >>> 8) & 0xff00) |
        ((word >>> 24) & 0xff));
}
/** Conditionally byte swap if on a big-endian platform */
export const swap8IfBE = isLE
    ? (n) => n
    : (n) => byteSwap(n);
/** @deprecated */
export const byteSwapIfBE = swap8IfBE;
/** In place byte swap for Uint32Array */
export function byteSwap32(arr) {
    for (let i = 0; i < arr.length; i++) {
        arr[i] = byteSwap(arr[i]);
    }
    return arr;
}
export const swap32IfBE = isLE
    ? (u) => u
    : byteSwap32;
// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex
const hasHexBuiltin = /* @__PURE__ */ (() => 
// @ts-ignore
typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();
// Array where index 0xf0 (240) is mapped to string 'f0'
const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
/**
 * Convert byte array to hex string. Uses built-in function, when available.
 * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
 */
export function bytesToHex(bytes) {
    abytes(bytes);
    // @ts-ignore
    if (hasHexBuiltin)
        return bytes.toHex();
    // pre-caching improves the speed 6x
    let hex = '';
    for (let i = 0; i < bytes.length; i++) {
        hex += hexes[bytes[i]];
    }
    return hex;
}
// We use optimized technique to convert hex string to byte array
const asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
function asciiToBase16(ch) {
    if (ch >= asciis._0 && ch <= asciis._9)
        return ch - asciis._0; // '2' => 50-48
    if (ch >= asciis.A && ch <= asciis.F)
        return ch - (asciis.A - 10); // 'B' => 66-(65-10)
    if (ch >= asciis.a && ch <= asciis.f)
        return ch - (asciis.a - 10); // 'b' => 98-(97-10)
    return;
}
/**
 * Convert hex string to byte array. Uses built-in function, when available.
 * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
 */
export function hexToBytes(hex) {
    if (typeof hex !== 'string')
        throw new Error('hex string expected, got ' + typeof hex);
    // @ts-ignore
    if (hasHexBuiltin)
        return Uint8Array.fromHex(hex);
    const hl = hex.length;
    const al = hl / 2;
    if (hl % 2)
        throw new Error('hex string expected, got unpadded hex of length ' + hl);
    const array = new Uint8Array(al);
    for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
        const n1 = asciiToBase16(hex.charCodeAt(hi));
        const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
        if (n1 === undefined || n2 === undefined) {
            const char = hex[hi] + hex[hi + 1];
            throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
        }
        array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163
    }
    return array;
}
/**
 * There is no setImmediate in browser and setTimeout is slow.
 * Call of async fn will return Promise, which will be fullfiled only on
 * next scheduler queue processing step and this is exactly what we need.
 */
export const nextTick = async () => { };
/** Returns control to thread each 'tick' ms to avoid blocking. */
export async function asyncLoop(iters, tick, cb) {
    let ts = Date.now();
    for (let i = 0; i < iters; i++) {
        cb(i);
        // Date.now() is not monotonic, so in case if clock goes backwards we return return control too
        const diff = Date.now() - ts;
        if (diff >= 0 && diff < tick)
            continue;
        await nextTick();
        ts += diff;
    }
}
/**
 * Converts string to bytes using UTF8 encoding.
 * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])
 */
export function utf8ToBytes(str) {
    if (typeof str !== 'string')
        throw new Error('string expected');
    return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
}
/**
 * Converts bytes to string using UTF8 encoding.
 * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'
 */
export function bytesToUtf8(bytes) {
    return new TextDecoder().decode(bytes);
}
/**
 * Normalizes (non-hex) string or Uint8Array to Uint8Array.
 * Warning: when Uint8Array is passed, it would NOT get copied.
 * Keep in mind for future mutable operations.
 */
export function toBytes(data) {
    if (typeof data === 'string')
        data = utf8ToBytes(data);
    abytes(data);
    return data;
}
/**
 * Helper for KDFs: consumes uint8array or string.
 * When string is passed, does utf8 decoding, using TextDecoder.
 */
export function kdfInputToBytes(data) {
    if (typeof data === 'string')
        data = utf8ToBytes(data);
    abytes(data);
    return data;
}
/** Copies several Uint8Arrays into one. */
export function concatBytes(...arrays) {
    let sum = 0;
    for (let i = 0; i < arrays.length; i++) {
        const a = arrays[i];
        abytes(a);
        sum += a.length;
    }
    const res = new Uint8Array(sum);
    for (let i = 0, pad = 0; i < arrays.length; i++) {
        const a = arrays[i];
        res.set(a, pad);
        pad += a.length;
    }
    return res;
}
export function checkOpts(defaults, opts) {
    if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')
        throw new Error('options should be object or undefined');
    const merged = Object.assign(defaults, opts);
    return merged;
}
/** For runtime check if class implements interface */
export class Hash {
}
/** Wraps hash function, creating an interface on top of it */
export function createHasher(hashCons) {
    const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
    const tmp = hashCons();
    hashC.outputLen = tmp.outputLen;
    hashC.blockLen = tmp.blockLen;
    hashC.create = () => hashCons();
    return hashC;
}
export function createOptHasher(hashCons) {
    const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();
    const tmp = hashCons({});
    hashC.outputLen = tmp.outputLen;
    hashC.blockLen = tmp.blockLen;
    hashC.create = (opts) => hashCons(opts);
    return hashC;
}
export function createXOFer(hashCons) {
    const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();
    const tmp = hashCons({});
    hashC.outputLen = tmp.outputLen;
    hashC.blockLen = tmp.blockLen;
    hashC.create = (opts) => hashCons(opts);
    return hashC;
}
export const wrapConstructor = createHasher;
export const wrapConstructorWithOpts = createOptHasher;
export const wrapXOFConstructorWithOpts = createXOFer;
/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */
export function randomBytes(bytesLength = 32) {
    if (crypto && typeof crypto.getRandomValues === 'function') {
        return crypto.getRandomValues(new Uint8Array(bytesLength));
    }
    // Legacy Node.js compatibility
    if (crypto && typeof crypto.randomBytes === 'function') {
        return Uint8Array.from(crypto.randomBytes(bytesLength));
    }
    throw new Error('crypto.getRandomValues must be defined');
}
//# sourceMappingURL=utils.js.mapimport { encode, encodeInto, objectToTokens, rfc8949EncodeOptions } from './lib/encode.js'
import { decode, decodeFirst, Tokeniser, tokensToObject } from './lib/decode.js'
import { Tagged } from './lib/tagged.js'
import { Token, Type } from './lib/token.js'

/**
 * Export the types that were present in the original manual cborg.d.ts
 * @typedef {import('./interface.js').TagDecodeControl} TagDecodeControl
 * @typedef {import('./interface.js').TagDecoder} TagDecoder
 * There was originally just `TypeEncoder` so don't break types by renaming or not exporting
 * @typedef {import('./interface.js').OptionalTypeEncoder} TypeEncoder
 * @typedef {import('./interface.js').DecodeOptions} DecodeOptions
 * @typedef {import('./interface.js').EncodeOptions} EncodeOptions
 */

export {
  decode,
  decodeFirst,
  Tokeniser as Tokenizer,
  tokensToObject,
  encode,
  encodeInto,
  objectToTokens,
  rfc8949EncodeOptions,
  Tagged,
  Token,
  Type
}
/* globals BigInt */

import { Token, Type } from './token.js'
import { decodeErrPrefix, assertEnoughData } from './common.js'

export const uintBoundaries = [24, 256, 65536, 4294967296, BigInt('18446744073709551616')]

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number}
 */
export function readUint8 (data, offset, options) {
  assertEnoughData(data, offset, 1)
  const value = data[offset]
  if (options.strict === true && value < uintBoundaries[0]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  return value
}

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number}
 */
export function readUint16 (data, offset, options) {
  assertEnoughData(data, offset, 2)
  const value = (data[offset] << 8) | data[offset + 1]
  if (options.strict === true && value < uintBoundaries[1]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  return value
}

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number}
 */
export function readUint32 (data, offset, options) {
  assertEnoughData(data, offset, 4)
  const value = (data[offset] * 16777216 /* 2 ** 24 */) + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]
  if (options.strict === true && value < uintBoundaries[2]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  return value
}

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number|bigint}
 */
export function readUint64 (data, offset, options) {
  // assume BigInt, convert back to Number if within safe range
  assertEnoughData(data, offset, 8)
  const hi = (data[offset] * 16777216 /* 2 ** 24 */) + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]
  const lo = (data[offset + 4] * 16777216 /* 2 ** 24 */) + (data[offset + 5] << 16) + (data[offset + 6] << 8) + data[offset + 7]
  const value = (BigInt(hi) << BigInt(32)) + BigInt(lo)
  if (options.strict === true && value < uintBoundaries[3]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  if (value <= Number.MAX_SAFE_INTEGER) {
    return Number(value)
  }
  if (options.allowBigInt === true) {
    return value
  }
  throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`)
}

/* not required thanks to quick[] list
const oneByteTokens = new Array(24).fill(0).map((v, i) => new Token(Type.uint, i, 1))
export function decodeUintCompact (data, pos, minor, options) {
  return oneByteTokens[minor]
}
*/

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint8 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint8(data, pos + 1, options), 2)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint16 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint16(data, pos + 1, options), 3)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint32 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint32(data, pos + 1, options), 5)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint64 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint64(data, pos + 1, options), 9)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeUint (writer, token) {
  return encodeUintValue(writer, 0, token.value)
}

/**
 * @param {ByteWriter} writer
 * @param {number} major
 * @param {number|bigint} uint
 */
export function encodeUintValue (writer, major, uint) {
  if (uint < uintBoundaries[0]) {
    const nuint = Number(uint)
    // pack into one byte, minor=0, additional=value
    writer.push([major | nuint])
  } else if (uint < uintBoundaries[1]) {
    const nuint = Number(uint)
    // pack into two byte, minor=0, additional=24
    writer.push([major | 24, nuint])
  } else if (uint < uintBoundaries[2]) {
    const nuint = Number(uint)
    // pack into three byte, minor=0, additional=25
    writer.push([major | 25, nuint >>> 8, nuint & 0xff])
  } else if (uint < uintBoundaries[3]) {
    const nuint = Number(uint)
    // pack into five byte, minor=0, additional=26
    writer.push([major | 26, (nuint >>> 24) & 0xff, (nuint >>> 16) & 0xff, (nuint >>> 8) & 0xff, nuint & 0xff])
  } else {
    const buint = BigInt(uint)
    if (buint < uintBoundaries[4]) {
      // pack into nine byte, minor=0, additional=27
      const set = [major | 27, 0, 0, 0, 0, 0, 0, 0]
      // simulate bitwise above 32 bits
      let lo = Number(buint & BigInt(0xffffffff))
      let hi = Number(buint >> BigInt(32) & BigInt(0xffffffff))
      set[8] = lo & 0xff
      lo = lo >> 8
      set[7] = lo & 0xff
      lo = lo >> 8
      set[6] = lo & 0xff
      lo = lo >> 8
      set[5] = lo & 0xff
      set[4] = hi & 0xff
      hi = hi >> 8
      set[3] = hi & 0xff
      hi = hi >> 8
      set[2] = hi & 0xff
      hi = hi >> 8
      set[1] = hi & 0xff
      writer.push(set)
    } else {
      throw new Error(`${decodeErrPrefix} encountered BigInt larger than allowable range`)
    }
  }
}

/**
 * @param {Token} token
 * @returns {number}
 */
encodeUint.encodedSize = function encodedSize (token) {
  return encodeUintValue.encodedSize(token.value)
}

/**
 * @param {number} uint
 * @returns {number}
 */
encodeUintValue.encodedSize = function encodedSize (uint) {
  if (uint < uintBoundaries[0]) {
    return 1
  }
  if (uint < uintBoundaries[1]) {
    return 2
  }
  if (uint < uintBoundaries[2]) {
    return 3
  }
  if (uint < uintBoundaries[3]) {
    return 5
  }
  return 9
}

/**
 * @param {Token} tok1
 * @param {Token} tok2
 * @returns {number}
 */
encodeUint.compareTokens = function compareTokens (tok1, tok2) {
  return tok1.value < tok2.value ? -1 : tok1.value > tok2.value ? 1 : 0
}
/* eslint-env es2020 */

import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import { decodeErrPrefix } from './common.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint8 (data, pos, _minor, options) {
  return new Token(Type.negint, -1 - uint.readUint8(data, pos + 1, options), 2)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint16 (data, pos, _minor, options) {
  return new Token(Type.negint, -1 - uint.readUint16(data, pos + 1, options), 3)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint32 (data, pos, _minor, options) {
  return new Token(Type.negint, -1 - uint.readUint32(data, pos + 1, options), 5)
}

const neg1b = BigInt(-1)
const pos1b = BigInt(1)

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint64 (data, pos, _minor, options) {
  const int = uint.readUint64(data, pos + 1, options)
  if (typeof int !== 'bigint') {
    const value = -1 - int
    if (value >= Number.MIN_SAFE_INTEGER) {
      return new Token(Type.negint, value, 9)
    }
  }
  if (options.allowBigInt !== true) {
    throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`)
  }
  return new Token(Type.negint, neg1b - BigInt(int), 9)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeNegint (writer, token) {
  const negint = token.value
  const unsigned = (typeof negint === 'bigint' ? (negint * neg1b - pos1b) : (negint * -1 - 1))
  uint.encodeUintValue(writer, token.type.majorEncoded, unsigned)
}

/**
 * @param {Token} token
 * @returns {number}
 */
encodeNegint.encodedSize = function encodedSize (token) {
  const negint = token.value
  const unsigned = (typeof negint === 'bigint' ? (negint * neg1b - pos1b) : (negint * -1 - 1))
  // handled by quickEncode, we shouldn't get here but it's included for completeness
  if (unsigned < uint.uintBoundaries[0]) {
    return 1
  }
  if (unsigned < uint.uintBoundaries[1]) {
    return 2
  }
  if (unsigned < uint.uintBoundaries[2]) {
    return 3
  }
  if (unsigned < uint.uintBoundaries[3]) {
    return 5
  }
  return 9
}

/**
 * @param {Token} tok1
 * @param {Token} tok2
 * @returns {number}
 */
encodeNegint.compareTokens = function compareTokens (tok1, tok2) {
  // opposite of the uint comparison since we store the uint version in bytes
  return tok1.value < tok2.value ? 1 : tok1.value > tok2.value ? -1 : 0
}
import { Token, Type } from './token.js'
import { assertEnoughData, decodeErrPrefix } from './common.js'
import * as uint from './0uint.js'
import { compare, fromString } from './byte-utils.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} prefix
 * @param {number} length
 * @returns {Token}
 */
function toToken (data, pos, prefix, length) {
  assertEnoughData(data, pos, prefix + length)
  const buf = data.slice(pos + prefix, pos + prefix + length)
  return new Token(Type.bytes, buf, prefix + length)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeBytesCompact (data, pos, minor, _options) {
  return toToken(data, pos, 1, minor)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer bytes lengths not supported`)
  }
  return toToken(data, pos, 9, l)
}

/**
 * `encodedBytes` allows for caching when we do a byte version of a string
 * for key sorting purposes
 * @param {Token} token
 * @returns {Uint8Array}
 */
function tokenBytes (token) {
  if (token.encodedBytes === undefined) {
    token.encodedBytes = Type.equals(token.type, Type.string) ? fromString(token.value) : token.value
  }
  // @ts-ignore c'mon
  return token.encodedBytes
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeBytes (writer, token) {
  const bytes = tokenBytes(token)
  uint.encodeUintValue(writer, token.type.majorEncoded, bytes.length)
  writer.push(bytes)
}

/**
 * @param {Token} token
 * @returns {number}
 */
encodeBytes.encodedSize = function encodedSize (token) {
  const bytes = tokenBytes(token)
  return uint.encodeUintValue.encodedSize(bytes.length) + bytes.length
}

/**
 * @param {Token} tok1
 * @param {Token} tok2
 * @returns {number}
 */
encodeBytes.compareTokens = function compareTokens (tok1, tok2) {
  return compareBytes(tokenBytes(tok1), tokenBytes(tok2))
}

/**
 * @param {Uint8Array} b1
 * @param {Uint8Array} b2
 * @returns {number}
 */
export function compareBytes (b1, b2) {
  return b1.length < b2.length ? -1 : b1.length > b2.length ? 1 : compare(b1, b2)
}
import { Token, Type } from './token.js'
import { assertEnoughData, decodeErrPrefix } from './common.js'
import * as uint from './0uint.js'
import { encodeBytes } from './2bytes.js'

const textDecoder = new TextDecoder()

// Threshold for ASCII fast-path vs TextDecoder. Short ASCII strings (common for
// map keys) are faster to decode with a simple loop than TextDecoder overhead.
const ASCII_THRESHOLD = 32

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * Decode UTF-8 bytes to string. For short ASCII strings (common case for map keys),
 * a simple loop is faster than TextDecoder.
 * @param {Uint8Array} bytes
 * @param {number} start
 * @param {number} end
 * @returns {string}
 */
function toStr (bytes, start, end) {
  const len = end - start
  if (len < ASCII_THRESHOLD) {
    let str = ''
    for (let i = start; i < end; i++) {
      const c = bytes[i]
      if (c & 0x80) { // non-ASCII, fall back to TextDecoder
        return textDecoder.decode(bytes.subarray(start, end))
      }
      str += String.fromCharCode(c)
    }
    return str
  }
  return textDecoder.decode(bytes.subarray(start, end))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} prefix
 * @param {number} length
 * @param {DecodeOptions} options
 * @returns {Token}
 */
function toToken (data, pos, prefix, length, options) {
  const totLength = prefix + length
  assertEnoughData(data, pos, totLength)
  const tok = new Token(Type.string, toStr(data, pos + prefix, pos + totLength), totLength)
  if (options.retainStringBytes === true) {
    tok.byteValue = data.slice(pos + prefix, pos + totLength)
  }
  return tok
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeStringCompact (data, pos, minor, options) {
  return toToken(data, pos, 1, minor, options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options), options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options), options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options), options)
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer string lengths not supported`)
  }
  return toToken(data, pos, 9, l, options)
}

export const encodeString = encodeBytes
import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import { decodeErrPrefix } from './common.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} prefix
 * @param {number} length
 * @returns {Token}
 */
function toToken (_data, _pos, prefix, length) {
  return new Token(Type.array, length, prefix)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeArrayCompact (data, pos, minor, _options) {
  return toToken(data, pos, 1, minor)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer array lengths not supported`)
  }
  return toToken(data, pos, 9, l)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArrayIndefinite (data, pos, _minor, options) {
  if (options.allowIndefinite === false) {
    throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)
  }
  return toToken(data, pos, 1, Infinity)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeArray (writer, token) {
  uint.encodeUintValue(writer, Type.array.majorEncoded, token.value)
}

// using an array as a map key, are you sure about this? we can only sort
// by map length here, it's up to the encoder to decide to look deeper
encodeArray.compareTokens = uint.encodeUint.compareTokens

/**
 * @param {Token} token
 * @returns {number}
 */
encodeArray.encodedSize = function encodedSize (token) {
  return uint.encodeUintValue.encodedSize(token.value)
}
import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import { decodeErrPrefix } from './common.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} prefix
 * @param {number} length
 * @returns {Token}
 */
function toToken (_data, _pos, prefix, length) {
  return new Token(Type.map, length, prefix)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeMapCompact (data, pos, minor, _options) {
  return toToken(data, pos, 1, minor)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer map lengths not supported`)
  }
  return toToken(data, pos, 9, l)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMapIndefinite (data, pos, _minor, options) {
  if (options.allowIndefinite === false) {
    throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)
  }
  return toToken(data, pos, 1, Infinity)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeMap (writer, token) {
  uint.encodeUintValue(writer, Type.map.majorEncoded, token.value)
}

// using a map as a map key, are you sure about this? we can only sort
// by map length here, it's up to the encoder to decide to look deeper
encodeMap.compareTokens = uint.encodeUint.compareTokens

/**
 * @param {Token} token
 * @returns {number}
 */
encodeMap.encodedSize = function encodedSize (token) {
  return uint.encodeUintValue.encodedSize(token.value)
}
import { Token, Type } from './token.js'
import * as uint from './0uint.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeTagCompact (_data, _pos, minor, _options) {
  return new Token(Type.tag, minor, 1)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag8 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint8(data, pos + 1, options), 2)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag16 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint16(data, pos + 1, options), 3)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag32 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint32(data, pos + 1, options), 5)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag64 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint64(data, pos + 1, options), 9)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeTag (writer, token) {
  uint.encodeUintValue(writer, Type.tag.majorEncoded, token.value)
}

encodeTag.compareTokens = uint.encodeUint.compareTokens

/**
 * @param {Token} token
 * @returns {number}
 */
encodeTag.encodedSize = function encodedSize (token) {
  return uint.encodeUintValue.encodedSize(token.value)
}
// TODO: shift some of the bytes logic to bytes-utils so we can use Buffer
// where possible

import { Token, Type } from './token.js'
import { decodeErrPrefix } from './common.js'
import { encodeUint } from './0uint.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 * @typedef {import('../interface.js').EncodeOptions} EncodeOptions
 */

export const MINOR_FALSE = 20
export const MINOR_TRUE = 21
export const MINOR_NULL = 22
export const MINOR_UNDEFINED = 23

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUndefined (_data, _pos, _minor, options) {
  if (options.allowUndefined === false) {
    throw new Error(`${decodeErrPrefix} undefined values are not supported`)
  } else if (options.coerceUndefinedToNull === true) {
    return new Token(Type.null, null, 1)
  }
  return new Token(Type.undefined, undefined, 1)
}

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBreak (_data, _pos, _minor, options) {
  if (options.allowIndefinite === false) {
    throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)
  }
  return new Token(Type.break, undefined, 1)
}

/**
 * @param {number} value
 * @param {number} bytes
 * @param {DecodeOptions} options
 * @returns {Token}
 */
function createToken (value, bytes, options) {
  if (options) {
    if (options.allowNaN === false && Number.isNaN(value)) {
      throw new Error(`${decodeErrPrefix} NaN values are not supported`)
    }
    if (options.allowInfinity === false && (value === Infinity || value === -Infinity)) {
      throw new Error(`${decodeErrPrefix} Infinity values are not supported`)
    }
  }
  return new Token(Type.float, value, bytes)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeFloat16 (data, pos, _minor, options) {
  return createToken(readFloat16(data, pos + 1), 3, options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeFloat32 (data, pos, _minor, options) {
  return createToken(readFloat32(data, pos + 1), 5, options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeFloat64 (data, pos, _minor, options) {
  return createToken(readFloat64(data, pos + 1), 9, options)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 * @param {EncodeOptions} options
 */
export function encodeFloat (writer, token, options) {
  const float = token.value

  if (float === false) {
    writer.push([Type.float.majorEncoded | MINOR_FALSE])
  } else if (float === true) {
    writer.push([Type.float.majorEncoded | MINOR_TRUE])
  } else if (float === null) {
    writer.push([Type.float.majorEncoded | MINOR_NULL])
  } else if (float === undefined) {
    writer.push([Type.float.majorEncoded | MINOR_UNDEFINED])
  } else {
    let decoded
    let success = false
    if (!options || options.float64 !== true) {
      encodeFloat16(float)
      decoded = readFloat16(ui8a, 1)
      if (float === decoded || Number.isNaN(float)) {
        ui8a[0] = 0xf9
        writer.push(ui8a.slice(0, 3))
        success = true
      } else {
        encodeFloat32(float)
        decoded = readFloat32(ui8a, 1)
        if (float === decoded) {
          ui8a[0] = 0xfa
          writer.push(ui8a.slice(0, 5))
          success = true
        }
      }
    }
    if (!success) {
      encodeFloat64(float)
      decoded = readFloat64(ui8a, 1)
      ui8a[0] = 0xfb
      writer.push(ui8a.slice(0, 9))
    }
  }
}

/**
 * @param {Token} token
 * @param {EncodeOptions} options
 * @returns {number}
 */
encodeFloat.encodedSize = function encodedSize (token, options) {
  const float = token.value

  if (float === false || float === true || float === null || float === undefined) {
    return 1
  }

  if (!options || options.float64 !== true) {
    encodeFloat16(float)
    let decoded = readFloat16(ui8a, 1)
    if (float === decoded || Number.isNaN(float)) {
      return 3
    }
    encodeFloat32(float)
    decoded = readFloat32(ui8a, 1)
    if (float === decoded) {
      return 5
    }
  }
  return 9
}

const buffer = new ArrayBuffer(9)
const dataView = new DataView(buffer, 1)
const ui8a = new Uint8Array(buffer, 0)

/**
 * @param {number} inp
 */
function encodeFloat16 (inp) {
  if (inp === Infinity) {
    dataView.setUint16(0, 0x7c00, false)
  } else if (inp === -Infinity) {
    dataView.setUint16(0, 0xfc00, false)
  } else if (Number.isNaN(inp)) {
    dataView.setUint16(0, 0x7e00, false)
  } else {
    dataView.setFloat32(0, inp)
    const valu32 = dataView.getUint32(0)
    const exponent = (valu32 & 0x7f800000) >> 23
    const mantissa = valu32 & 0x7fffff

    if (exponent === 0xff) {
      // too big, Infinity, but this should be hard (impossible?) to trigger
      dataView.setUint16(0, 0x7c00, false)
    } else if (exponent === 0x00) {
      // 0.0, -0.0 and subnormals, shouldn't be possible to get here because 0.0 should be counted as an int
      // Use valu32 for sign bit since bitwise ops on floats lose -0 sign
      dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | (mantissa >> 13), false)
    } else { // standard numbers
      // chunks of logic here borrowed from https://github.com/PJK/libcbor/blob/c78f437182533e3efa8d963ff4b945bb635c2284/src/cbor/encoding.c#L127
      const logicalExponent = exponent - 127
      // Now we know that 2^exponent <= 0 logically
      if (logicalExponent < -24) {
        /* No unambiguous representation exists, this float is not a half float
          and is too small to be represented using a half, round off to zero.
          Consistent with the reference implementation. */
        // should be difficult (impossible?) to get here in JS
        dataView.setUint16(0, 0)
      } else if (logicalExponent < -14) {
        /* Offset the remaining decimal places by shifting the significand, the
          value is lost. This is an implementation decision that works around the
          absence of standard half-float in the language. */
        dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | /* sign bit */ (1 << (24 + logicalExponent)), false)
      } else {
        dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | ((logicalExponent + 15) << 10) | (mantissa >> 13), false)
      }
    }
  }
}

/**
 * @param {Uint8Array} ui8a
 * @param {number} pos
 * @returns {number}
 */
function readFloat16 (ui8a, pos) {
  if (ui8a.length - pos < 2) {
    throw new Error(`${decodeErrPrefix} not enough data for float16`)
  }

  const half = (ui8a[pos] << 8) + ui8a[pos + 1]
  if (half === 0x7c00) {
    return Infinity
  }
  if (half === 0xfc00) {
    return -Infinity
  }
  if (half === 0x7e00) {
    return NaN
  }
  const exp = (half >> 10) & 0x1f
  const mant = half & 0x3ff
  let val
  if (exp === 0) {
    val = mant * (2 ** -24)
  } else if (exp !== 31) {
    val = (mant + 1024) * (2 ** (exp - 25))
  } else {
    // may not be possible to get here
    val = mant === 0 ? Infinity : NaN
  }
  return (half & 0x8000) ? -val : val
}

/**
 * @param {number} inp
 */
function encodeFloat32 (inp) {
  dataView.setFloat32(0, inp, false)
}

/**
 * @param {Uint8Array} ui8a
 * @param {number} pos
 * @returns {number}
 */
function readFloat32 (ui8a, pos) {
  if (ui8a.length - pos < 4) {
    throw new Error(`${decodeErrPrefix} not enough data for float32`)
  }
  const offset = (ui8a.byteOffset || 0) + pos
  return new DataView(ui8a.buffer, offset, 4).getFloat32(0, false)
}

/**
 * @param {number} inp
 */
function encodeFloat64 (inp) {
  dataView.setFloat64(0, inp, false)
}

/**
 * @param {Uint8Array} ui8a
 * @param {number} pos
 * @returns {number}
 */
function readFloat64 (ui8a, pos) {
  if (ui8a.length - pos < 8) {
    throw new Error(`${decodeErrPrefix} not enough data for float64`)
  }
  const offset = (ui8a.byteOffset || 0) + pos
  return new DataView(ui8a.buffer, offset, 8).getFloat64(0, false)
}

/**
 * @param {Token} _tok1
 * @param {Token} _tok2
 * @returns {number}
 */
encodeFloat.compareTokens = encodeUint.compareTokens
/*
encodeFloat.compareTokens = function compareTokens (_tok1, _tok2) {
  return _tok1
  throw new Error(`${encodeErrPrefix} cannot use floats as map keys`)
}
*/
/**
 * Bl is a list of byte chunks, similar to https://github.com/rvagg/bl but for
 * writing rather than reading.
 * A Bl object accepts set() operations for individual bytes and copyTo() for
 * inserting byte arrays. These write operations don't automatically increment
 * the internal cursor so its "length" won't be changed. Instead, increment()
 * must be called to extend its length to cover the inserted data.
 * The toBytes() call will convert all internal memory to a single Uint8Array of
 * the correct length, truncating any data that is stored but hasn't been
 * included by an increment().
 * get() can retrieve a single byte.
 * All operations (except toBytes()) take an "offset" argument that will perform
 * the write at the offset _from the current cursor_. For most operations this
 * will be `0` to write at the current cursor position but it can be ahead of
 * the current cursor. Negative offsets probably work but are untested.
 */

// TODO: ipjs doesn't support this, only for test files: https://github.com/mikeal/ipjs/blob/master/src/package/testFile.js#L39
import { alloc, concat, slice } from './byte-utils.js'

// the ts-ignores in this file are almost all for the `Uint8Array|number[]` duality that exists
// for perf reasons. Consider better approaches to this or removing it entirely, it is quite
// risky because of some assumptions about small chunks === number[] and everything else === Uint8Array.

const defaultChunkSize = 256

export class Bl {
  /**
   * @param {number} [chunkSize]
   */
  constructor (chunkSize = defaultChunkSize) {
    this.chunkSize = chunkSize
    /** @type {number} */
    this.cursor = 0
    /** @type {number} */
    this.maxCursor = -1
    /** @type {(Uint8Array|number[])[]} */
    this.chunks = []
    // keep the first chunk around if we can to save allocations for future encodes
    /** @type {Uint8Array|number[]|null} */
    this._initReuseChunk = null
  }

  reset () {
    this.cursor = 0
    this.maxCursor = -1
    if (this.chunks.length) {
      this.chunks = []
    }
    if (this._initReuseChunk !== null) {
      this.chunks.push(this._initReuseChunk)
      this.maxCursor = this._initReuseChunk.length - 1
    }
  }

  /**
   * @param {Uint8Array|number[]} bytes
   */
  push (bytes) {
    let topChunk = this.chunks[this.chunks.length - 1]
    const newMax = this.cursor + bytes.length
    if (newMax <= this.maxCursor + 1) {
      // we have at least one chunk and we can fit these bytes into that chunk
      const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1
      // @ts-ignore
      topChunk.set(bytes, chunkPos)
    } else {
      // can't fit it in
      if (topChunk) {
        // trip the last chunk to `cursor` if we need to
        const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1
        if (chunkPos < topChunk.length) {
          // @ts-ignore
          this.chunks[this.chunks.length - 1] = topChunk.subarray(0, chunkPos)
          this.maxCursor = this.cursor - 1
        }
      }
      if (bytes.length < 64 && bytes.length < this.chunkSize) {
        // make a new chunk and copy the new one into it
        topChunk = alloc(this.chunkSize)
        this.chunks.push(topChunk)
        this.maxCursor += topChunk.length
        if (this._initReuseChunk === null) {
          this._initReuseChunk = topChunk
        }
        // @ts-ignore
        topChunk.set(bytes, 0)
      } else {
        // push the new bytes in as its own chunk
        this.chunks.push(bytes)
        this.maxCursor += bytes.length
      }
    }
    this.cursor += bytes.length
  }

  /**
   * @param {boolean} [reset]
   * @returns {Uint8Array}
   */
  toBytes (reset = false) {
    let byts
    if (this.chunks.length === 1) {
      const chunk = this.chunks[0]
      if (reset && this.cursor > chunk.length / 2) {
        // @ts-ignore
        byts = this.cursor === chunk.length ? chunk : chunk.subarray(0, this.cursor)
        this._initReuseChunk = null
        this.chunks = []
      } else {
        // @ts-ignore
        byts = slice(chunk, 0, this.cursor)
      }
    } else {
      // @ts-ignore
      byts = concat(this.chunks, this.cursor)
    }
    if (reset) {
      this.reset()
    }
    return byts
  }
}

/**
 * U8Bl is a buffer list that writes directly to a user-provided Uint8Array.
 * It provides the same interface as Bl but writes to a fixed destination.
 */
export class U8Bl {
  /**
   * @param {Uint8Array} dest
   */
  constructor (dest) {
    this.dest = dest
    /** @type {number} */
    this.cursor = 0
    // chunks is for interface compatibility with Bl - encode.js checks chunks.length
    // as a sanity check for pre-calculated sizes. For U8Bl this is always [dest].
    /** @type {Uint8Array[]} */
    this.chunks = [dest]
  }

  reset () {
    this.cursor = 0
  }

  /**
   * @param {Uint8Array|number[]} bytes
   */
  push (bytes) {
    if (this.cursor + bytes.length > this.dest.length) {
      throw new Error('write out of bounds, destination buffer is too small')
    }
    this.dest.set(bytes, this.cursor)
    this.cursor += bytes.length
  }

  /**
   * @param {boolean} [reset]
   * @returns {Uint8Array}
   */
  toBytes (reset = false) {
    const byts = this.dest.subarray(0, this.cursor)
    if (reset) {
      this.reset()
    }
    return byts
  }
}
// Use Uint8Array directly in the browser, use Buffer in Node.js but don't
// speak its name directly to avoid bundlers pulling in the `Buffer` polyfill

// @ts-ignore
export const useBuffer = globalThis.process &&
  // @ts-ignore
  !globalThis.process.browser &&
  // @ts-ignore
  globalThis.Buffer &&
  // @ts-ignore
  typeof globalThis.Buffer.isBuffer === 'function'

const textEncoder = new TextEncoder()

/**
 * @param {Uint8Array} buf
 * @returns {boolean}
 */
function isBuffer (buf) {
  // @ts-ignore
  return useBuffer && globalThis.Buffer.isBuffer(buf)
}

/**
 * @param {Uint8Array|number[]} buf
 * @returns {Uint8Array}
 */
export function asU8A (buf) {
  if (!(buf instanceof Uint8Array)) {
    return Uint8Array.from(buf)
  }
  return isBuffer(buf) ? new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength) : buf
}

// Threshold for manual UTF-8 encoding vs native methods.
// Node.js Buffer.from: crossover ~24 chars
// Browser TextEncoder: crossover ~200 chars
const FROM_STRING_THRESHOLD_BUFFER = 24
const FROM_STRING_THRESHOLD_TEXTENCODER = 200

export const fromString = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {string} string
     */
    (string) => {
      return string.length >= FROM_STRING_THRESHOLD_BUFFER
        ? // eslint-disable-line operator-linebreak
      // @ts-ignore
        globalThis.Buffer.from(string)
        : utf8ToBytes(string)
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {string} string
     */
    (string) => {
      return string.length >= FROM_STRING_THRESHOLD_TEXTENCODER ? textEncoder.encode(string) : utf8ToBytes(string)
    }

/**
 * Buffer variant not fast enough for what we need
 * @param {number[]} arr
 * @returns {Uint8Array}
 */
export const fromArray = (arr) => {
  return Uint8Array.from(arr)
}

export const slice = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} bytes
     * @param {number} start
     * @param {number} end
     */
    // Buffer.slice() returns a view, not a copy, so we need special handling
    (bytes, start, end) => {
      if (isBuffer(bytes)) {
        return new Uint8Array(bytes.subarray(start, end))
      }
      return bytes.slice(start, end)
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} bytes
     * @param {number} start
     * @param {number} end
     */
    (bytes, start, end) => {
      return bytes.slice(start, end)
    }

export const concat = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array[]} chunks
     * @param {number} length
     * @returns {Uint8Array}
     */
    (chunks, length) => {
      // might get a stray plain Array here
      chunks = chunks.map((c) => c instanceof Uint8Array
        ? c
        : // eslint-disable-line operator-linebreak
        // @ts-ignore
        globalThis.Buffer.from(c))
      // @ts-ignore
      return asU8A(globalThis.Buffer.concat(chunks, length))
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array[]} chunks
     * @param {number} length
     * @returns {Uint8Array}
     */
    (chunks, length) => {
      const out = new Uint8Array(length)
      let off = 0
      for (let b of chunks) {
        if (off + b.length > out.length) {
          // final chunk that's bigger than we need
          b = b.subarray(0, out.length - off)
        }
        out.set(b, off)
        off += b.length
      }
      return out
    }

export const alloc = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {number} size
     * @returns {Uint8Array}
     */
    (size) => {
      // we always write over the contents we expose so this should be safe
      // @ts-ignore
      return globalThis.Buffer.allocUnsafe(size)
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {number} size
     * @returns {Uint8Array}
     */
    (size) => {
      return new Uint8Array(size)
    }

export const toHex = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} d
     * @returns {string}
     */
    (d) => {
      if (typeof d === 'string') {
        return d
      }
      // @ts-ignore
      return globalThis.Buffer.from(toBytes(d)).toString('hex')
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} d
     * @returns {string}
     */
    (d) => {
      if (typeof d === 'string') {
        return d
      }
      // @ts-ignore not smart enough to figure this out
      return Array.prototype.reduce.call(toBytes(d), (p, c) => `${p}${c.toString(16).padStart(2, '0')}`, '')
    }

export const fromHex = useBuffer
  ? // eslint-disable-line operator-linebreak
  /**
   * @param {string|Uint8Array} hex
   * @returns {Uint8Array}
   */
    (hex) => {
      if (hex instanceof Uint8Array) {
        return hex
      }
      // @ts-ignore
      return globalThis.Buffer.from(hex, 'hex')
    }
  : // eslint-disable-line operator-linebreak
  /**
   * @param {string|Uint8Array} hex
   * @returns {Uint8Array}
   */
    (hex) => {
      if (hex instanceof Uint8Array) {
        return hex
      }
      if (!hex.length) {
        return new Uint8Array(0)
      }
      return new Uint8Array(hex.split('')
        .map((/** @type {string} */ c, /** @type {number} */ i, /** @type {string[]} */ d) => i % 2 === 0 ? `0x${c}${d[i + 1]}` : '')
        .filter(Boolean)
        .map((/** @type {string} */ e) => parseInt(e, 16)))
    }

/**
 * @param {Uint8Array|ArrayBuffer|ArrayBufferView} obj
 * @returns {Uint8Array}
 */
function toBytes (obj) {
  if (obj instanceof Uint8Array && obj.constructor.name === 'Uint8Array') {
    return obj
  }
  if (obj instanceof ArrayBuffer) {
    return new Uint8Array(obj)
  }
  if (ArrayBuffer.isView(obj)) {
    return new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength)
  }
  throw new Error('Unknown type, must be binary type')
}

/**
 * @param {Uint8Array} b1
 * @param {Uint8Array} b2
 * @returns {number}
 */
export function compare (b1, b2) {
  if (isBuffer(b1) && isBuffer(b2)) {
    // probably not possible to get here in the current API
    // @ts-ignore Buffer
    return b1.compare(b2)
  }
  for (let i = 0; i < b1.length; i++) {
    if (b1[i] === b2[i]) {
      continue
    }
    return b1[i] < b2[i] ? -1 : 1
  }
  return 0
}

// The below code is taken from https://github.com/google/closure-library/blob/8598d87242af59aac233270742c8984e2b2bdbe0/closure/goog/crypt/crypt.js#L117-L143
// Licensed Apache-2.0.

/**
 * @param {string} str
 * @returns {number[]}
 */
function utf8ToBytes (str) {
  const out = []
  let p = 0
  for (let i = 0; i < str.length; i++) {
    let c = str.charCodeAt(i)
    if (c < 128) {
      out[p++] = c
    } else if (c < 2048) {
      out[p++] = (c >> 6) | 192
      out[p++] = (c & 63) | 128
    } else if (
      ((c & 0xFC00) === 0xD800) && (i + 1) < str.length &&
      ((str.charCodeAt(i + 1) & 0xFC00) === 0xDC00)) {
      // Surrogate Pair
      c = 0x10000 + ((c & 0x03FF) << 10) + (str.charCodeAt(++i) & 0x03FF)
      out[p++] = (c >> 18) | 240
      out[p++] = ((c >> 12) & 63) | 128
      out[p++] = ((c >> 6) & 63) | 128
      out[p++] = (c & 63) | 128
    } else {
      if ((c >= 0xD800) && (c <= 0xDFFF)) {
        c = 0xFFFD // Unpaired Surrogate
      }
      out[p++] = (c >> 12) | 224
      out[p++] = ((c >> 6) & 63) | 128
      out[p++] = (c & 63) | 128
    }
  }
  return out
}

// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
const MAX_ARGUMENTS_LENGTH = 0x1000

/**
 * @param {number[]} codePoints
 * @returns {string}
 */
export function decodeCodePointsArray (codePoints) {
  const len = codePoints.length
  if (len <= MAX_ARGUMENTS_LENGTH) {
    return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  }
  // Decode in chunks to avoid "call stack size exceeded".
  let res = ''
  let i = 0
  while (i < len) {
    res += String.fromCharCode.apply(
      String,
      codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
    )
  }
  return res
}
const decodeErrPrefix = 'CBOR decode error:'
const encodeErrPrefix = 'CBOR encode error:'

const uintMinorPrefixBytes = []
uintMinorPrefixBytes[23] = 1
uintMinorPrefixBytes[24] = 2
uintMinorPrefixBytes[25] = 3
uintMinorPrefixBytes[26] = 5
uintMinorPrefixBytes[27] = 9

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} need
 */
function assertEnoughData (data, pos, need) {
  if (data.length - pos < need) {
    throw new Error(`${decodeErrPrefix} not enough data for type`)
  }
}

export {
  decodeErrPrefix,
  encodeErrPrefix,
  uintMinorPrefixBytes,
  assertEnoughData
}
import { decodeErrPrefix } from './common.js'
import { Type } from './token.js'
import { jump, quick } from './jump.js'
import { asU8A } from './byte-utils.js'

/**
 * @typedef {import('./token.js').Token} Token
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 * @typedef {import('../interface.js').DecodeTokenizer} DecodeTokenizer
 * @typedef {import('../interface.js').TagDecodeControl} TagDecodeControl
 */

const defaultDecodeOptions = {
  strict: false,
  allowIndefinite: true,
  allowUndefined: true,
  allowBigInt: true
}

/**
 * @implements {DecodeTokenizer}
 */
class Tokeniser {
  /**
   * @param {Uint8Array} data
   * @param {DecodeOptions} options
   */
  constructor (data, options = {}) {
    this._pos = 0
    this.data = data
    this.options = options
  }

  pos () {
    return this._pos
  }

  done () {
    return this._pos >= this.data.length
  }

  next () {
    const byt = this.data[this._pos]
    let token = quick[byt]
    if (token === undefined) {
      const decoder = jump[byt]
      // if we're here then there's something wrong with our jump or quick lists!
      if (!decoder) {
        throw new Error(`${decodeErrPrefix} no decoder for major type ${byt >>> 5} (byte 0x${byt.toString(16).padStart(2, '0')})`)
      }
      const minor = byt & 31
      token = decoder(this.data, this._pos, minor, this.options)
    }
    // @ts-ignore we get to assume encodedLength is set (crossing fingers slightly)
    this._pos += token.encodedLength
    return token
  }
}

const DONE = Symbol.for('DONE')
const BREAK = Symbol.for('BREAK')

/**
 * @param {Token} token
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {any|BREAK|DONE}
 */
function tokenToArray (token, tokeniser, options) {
  const arr = []
  for (let i = 0; i < token.value; i++) {
    const value = tokensToObject(tokeniser, options)
    if (value === BREAK) {
      if (token.value === Infinity) {
        // normal end to indefinite length array
        break
      }
      throw new Error(`${decodeErrPrefix} got unexpected break to lengthed array`)
    }
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} found array but not enough entries (got ${i}, expected ${token.value})`)
    }
    arr[i] = value
  }
  return arr
}

/**
 * @param {Token} token
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {any|BREAK|DONE}
 */
function tokenToMap (token, tokeniser, options) {
  const useMaps = options.useMaps === true
  const rejectDuplicateMapKeys = options.rejectDuplicateMapKeys === true
  const obj = useMaps ? undefined : {}
  const m = useMaps ? new Map() : undefined
  for (let i = 0; i < token.value; i++) {
    const key = tokensToObject(tokeniser, options)
    if (key === BREAK) {
      if (token.value === Infinity) {
        // normal end to indefinite length map
        break
      }
      throw new Error(`${decodeErrPrefix} got unexpected break to lengthed map`)
    }
    if (key === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no key], expected ${token.value})`)
    }
    if (!useMaps && typeof key !== 'string') {
      throw new Error(`${decodeErrPrefix} non-string keys not supported (got ${typeof key})`)
    }
    if (rejectDuplicateMapKeys) {
      // @ts-ignore
      if ((useMaps && m.has(key)) || (!useMaps && Object.hasOwn(obj, key))) {
        throw new Error(`${decodeErrPrefix} found repeat map key "${key}"`)
      }
    }
    const value = tokensToObject(tokeniser, options)
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no value], expected ${token.value})`)
    }
    if (useMaps) {
      // @ts-ignore TODO reconsider this .. maybe needs to be strict about key types
      m.set(key, value)
    } else {
      // @ts-ignore TODO reconsider this .. maybe needs to be strict about key types
      obj[key] = value
    }
  }
  // @ts-ignore c'mon man
  return useMaps ? m : obj
}

/**
 * Generator that yields [key, value] entries from a CBOR map token.
 * Used by tag decoders that need to preserve key types (e.g., Tag 259 Map).
 * @param {Token} token - The map token
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {Generator<[any, any], void, unknown>}
 */
function * tokenToMapEntries (token, tokeniser, options) {
  for (let i = 0; i < token.value; i++) {
    const key = tokensToObject(tokeniser, options)
    if (key === BREAK) {
      if (token.value === Infinity) {
        // normal end to indefinite length map
        break
      }
      throw new Error(`${decodeErrPrefix} got unexpected break to lengthed map`)
    }
    if (key === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no key], expected ${token.value})`)
    }
    const value = tokensToObject(tokeniser, options)
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no value], expected ${token.value})`)
    }
    yield [key, value]
  }
}

/**
 * Creates a TagDecodeControl object for tag decoders.
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {TagDecodeControl}
 */
function createTagDecodeControl (tokeniser, options) {
  let called = false

  /**
   * @type {TagDecodeControl}
   */
  const decode = function () {
    if (called) {
      throw new Error(`${decodeErrPrefix} tag decode() may only be called once`)
    }
    called = true
    const value = tokensToObject(tokeniser, options)
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} tag content missing`)
    }
    if (value === BREAK) {
      throw new Error(`${decodeErrPrefix} got unexpected break in tag content`)
    }
    return value
  }

  decode.entries = function () {
    if (called) {
      throw new Error(`${decodeErrPrefix} tag decode() may only be called once`)
    }
    called = true

    // Get the next token and ensure it's a map
    const token = tokeniser.next()
    if (!Type.equals(token.type, Type.map)) {
      throw new Error(`${decodeErrPrefix} entries() requires map content, got ${token.type.name}`)
    }

    // Collect all entries into an array (ensures full content consumption)
    const entries = []
    for (const entry of tokenToMapEntries(token, tokeniser, options)) {
      entries.push(entry)
    }
    return entries
  }

  // For internal tracking
  Object.defineProperty(decode, '_called', {
    get () { return called },
    enumerable: false
  })

  return decode
}

/**
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {any|BREAK|DONE}
 */
function tokensToObject (tokeniser, options) {
  // should we support array as an argument?
  // check for tokenIter[Symbol.iterator] and replace tokenIter with what that returns?
  if (tokeniser.done()) {
    return DONE
  }

  const token = tokeniser.next()

  if (Type.equals(token.type, Type.break)) {
    return BREAK
  }

  if (token.type.terminal) {
    return token.value
  }

  if (Type.equals(token.type, Type.array)) {
    return tokenToArray(token, tokeniser, options)
  }

  if (Type.equals(token.type, Type.map)) {
    return tokenToMap(token, tokeniser, options)
  }

  if (Type.equals(token.type, Type.tag)) {
    if (options.tags && typeof options.tags[token.value] === 'function') {
      const decodeControl = createTagDecodeControl(tokeniser, options)
      const result = options.tags[token.value](decodeControl)
      if (!decodeControl._called) {
        throw new Error(`${decodeErrPrefix} tag decoder must call decode() or entries()`)
      }
      return result
    }
    throw new Error(`${decodeErrPrefix} tag not supported (${token.value})`)
  }
  throw new Error('unsupported')
}

/**
 * @param {Uint8Array} data
 * @param {DecodeOptions} [options]
 * @returns {[any, Uint8Array]}
 */
function decodeFirst (data, options) {
  if (!(data instanceof Uint8Array)) {
    throw new Error(`${decodeErrPrefix} data to decode must be a Uint8Array`)
  }
  options = Object.assign({}, defaultDecodeOptions, options)
  // Convert Buffer to plain Uint8Array for faster slicing in decode path
  const u8aData = asU8A(data)
  const tokeniser = options.tokenizer || new Tokeniser(u8aData, options)
  const decoded = tokensToObject(tokeniser, options)
  if (decoded === DONE) {
    throw new Error(`${decodeErrPrefix} did not find any content to decode`)
  }
  if (decoded === BREAK) {
    throw new Error(`${decodeErrPrefix} got unexpected break`)
  }
  return [decoded, data.subarray(tokeniser.pos())]
}

/**
 * @param {Uint8Array} data
 * @param {DecodeOptions} [options]
 * @returns {any}
 */
function decode (data, options) {
  const [decoded, remainder] = decodeFirst(data, options)
  if (remainder.length > 0) {
    throw new Error(`${decodeErrPrefix} too many terminals, data makes no sense`)
  }
  return decoded
}

export { Tokeniser, tokensToObject, decode, decodeFirst }
import { is } from './is.js'
import { Token, Type } from './token.js'
import { Bl, U8Bl } from './bl.js'
import { encodeErrPrefix } from './common.js'
import { quickEncodeToken } from './jump.js'
import { asU8A, compare, fromString } from './byte-utils.js'

import { encodeUint, encodeUintValue } from './0uint.js'
import { encodeNegint } from './1negint.js'
import { encodeBytes } from './2bytes.js'
import { encodeString } from './3string.js'
import { encodeArray } from './4array.js'
import { encodeMap } from './5map.js'
import { encodeTag } from './6tag.js'
import { encodeFloat, MINOR_FALSE, MINOR_TRUE, MINOR_NULL, MINOR_UNDEFINED } from './7float.js'

/**
 * @typedef {import('../interface.js').EncodeOptions} EncodeOptions
 * @typedef {import('../interface.js').OptionalTypeEncoder} OptionalTypeEncoder
 * @typedef {import('../interface.js').Reference} Reference
 * @typedef {import('../interface.js').StrictTypeEncoder} StrictTypeEncoder
 * @typedef {import('../interface.js').TokenTypeEncoder} TokenTypeEncoder
 * @typedef {import('../interface.js').TokenOrNestedTokens} TokenOrNestedTokens
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 */

/** @type {EncodeOptions} */
const defaultEncodeOptions = {
  float64: false,
  mapSorter,
  quickEncodeToken
}

/** @type {EncodeOptions} */
export const rfc8949EncodeOptions = Object.freeze({
  mapSorter: rfc8949MapSorter,
  quickEncodeToken
})

/** @returns {TokenTypeEncoder[]} */
export function makeCborEncoders () {
  const encoders = []
  encoders[Type.uint.major] = encodeUint
  encoders[Type.negint.major] = encodeNegint
  encoders[Type.bytes.major] = encodeBytes
  encoders[Type.string.major] = encodeString
  encoders[Type.array.major] = encodeArray
  encoders[Type.map.major] = encodeMap
  encoders[Type.tag.major] = encodeTag
  encoders[Type.float.major] = encodeFloat
  return encoders
}

const cborEncoders = makeCborEncoders()

const defaultWriter = new Bl()

/** @implements {Reference} */
class Ref {
  /**
   * @param {object|any[]} obj
   * @param {Reference|undefined} parent
   */
  constructor (obj, parent) {
    this.obj = obj
    this.parent = parent
  }

  /**
   * @param {object|any[]} obj
   * @returns {boolean}
   */
  includes (obj) {
    /** @type {Reference|undefined} */
    let p = this
    do {
      if (p.obj === obj) {
        return true
      }
    } while (p = p.parent) // eslint-disable-line
    return false
  }

  /**
   * @param {Reference|undefined} stack
   * @param {object|any[]} obj
   * @returns {Reference}
   */
  static createCheck (stack, obj) {
    if (stack && stack.includes(obj)) {
      throw new Error(`${encodeErrPrefix} object contains circular references`)
    }
    return new Ref(obj, stack)
  }
}

const simpleTokens = {
  null: new Token(Type.null, null),
  undefined: new Token(Type.undefined, undefined),
  true: new Token(Type.true, true),
  false: new Token(Type.false, false),
  emptyArray: new Token(Type.array, 0),
  emptyMap: new Token(Type.map, 0)
}

/** @type {{[typeName: string]: StrictTypeEncoder}} */
const typeEncoders = {
  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  number (obj, _typ, _options, _refStack) {
    if (!Number.isInteger(obj) || !Number.isSafeInteger(obj)) {
      return new Token(Type.float, obj)
    } else if (obj >= 0) {
      return new Token(Type.uint, obj)
    } else {
      return new Token(Type.negint, obj)
    }
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  bigint (obj, _typ, _options, _refStack) {
    if (obj >= BigInt(0)) {
      return new Token(Type.uint, obj)
    } else {
      return new Token(Type.negint, obj)
    }
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  Uint8Array (obj, _typ, _options, _refStack) {
    return new Token(Type.bytes, obj)
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  string (obj, _typ, _options, _refStack) {
    return new Token(Type.string, obj)
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  boolean (obj, _typ, _options, _refStack) {
    return obj ? simpleTokens.true : simpleTokens.false
  },

  /**
   * @param {any} _obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  null (_obj, _typ, _options, _refStack) {
    return simpleTokens.null
  },

  /**
   * @param {any} _obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  undefined (_obj, _typ, _options, _refStack) {
    return simpleTokens.undefined
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  ArrayBuffer (obj, _typ, _options, _refStack) {
    return new Token(Type.bytes, new Uint8Array(obj))
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  DataView (obj, _typ, _options, _refStack) {
    return new Token(Type.bytes, new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength))
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} options
   * @param {Reference} [refStack]
   * @returns {TokenOrNestedTokens}
   */
  Array (obj, _typ, options, refStack) {
    if (!obj.length) {
      if (options.addBreakTokens === true) {
        return [simpleTokens.emptyArray, new Token(Type.break)]
      }
      return simpleTokens.emptyArray
    }
    refStack = Ref.createCheck(refStack, obj)
    const entries = []
    let i = 0
    for (const e of obj) {
      entries[i++] = objectToTokens(e, options, refStack)
    }
    if (options.addBreakTokens) {
      return [new Token(Type.array, obj.length), entries, new Token(Type.break)]
    }
    return [new Token(Type.array, obj.length), entries]
  },

  /**
   * @param {any} obj
   * @param {string} typ
   * @param {EncodeOptions} options
   * @param {Reference} [refStack]
   * @returns {TokenOrNestedTokens}
   */
  Object (obj, typ, options, refStack) {
    // could be an Object or a Map
    const isMap = typ !== 'Object'
    // it's slightly quicker to use Object.keys() than Object.entries()
    const keys = isMap ? obj.keys() : Object.keys(obj)
    const maxLength = isMap ? obj.size : keys.length

    /** @type {undefined | [TokenOrNestedTokens, TokenOrNestedTokens][]} */
    let entries

    if (maxLength) {
      // Pre-allocate the array with the expected size
      entries = new Array(maxLength)
      refStack = Ref.createCheck(refStack, obj)
      const skipUndefined = !isMap && options.ignoreUndefinedProperties

      let i = 0
      for (const key of keys) {
        const value = isMap ? obj.get(key) : obj[key]
        if (skipUndefined && value === undefined) {
          continue
        }
        entries[i++] = [
          objectToTokens(key, options, refStack),
          objectToTokens(value, options, refStack)
        ]
      }

      // Truncate only if properties were skipped
      if (i < maxLength) {
        entries.length = i
      }
    }

    if (!entries?.length) {
      if (options.addBreakTokens === true) {
        return [simpleTokens.emptyMap, new Token(Type.break)]
      }
      return simpleTokens.emptyMap
    }

    sortMapEntries(entries, options)
    if (options.addBreakTokens) {
      return [new Token(Type.map, entries.length), entries, new Token(Type.break)]
    }
    return [new Token(Type.map, entries.length), entries]
  },

  /**
   * Encode a `Tagged` wrapper as a CBOR tag header followed by the encoded
   * form of the wrapped value. The value is recursively tokenised through
   * `objectToTokens()` so any registered `typeEncoders` apply to it.
   *
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} options
   * @param {Reference} [refStack]
   * @returns {TokenOrNestedTokens}
   */
  Tagged (obj, _typ, options, refStack) {
    return [
      new Token(Type.tag, obj.tag),
      objectToTokens(obj.value, options, refStack)
    ]
  }
}

typeEncoders.Map = typeEncoders.Object
typeEncoders.Buffer = typeEncoders.Uint8Array
for (const typ of 'Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64'.split(' ')) {
  typeEncoders[`${typ}Array`] = typeEncoders.DataView
}

/**
 * @param {any} obj
 * @param {EncodeOptions} [options]
 * @param {Reference} [refStack]
 * @returns {TokenOrNestedTokens}
 */
function objectToTokens (obj, options = {}, refStack) {
  const typ = is(obj)
  const customTypeEncoder = (options && options.typeEncoders && /** @type {OptionalTypeEncoder} */ options.typeEncoders[typ]) || typeEncoders[typ]
  if (typeof customTypeEncoder === 'function') {
    const tokens = customTypeEncoder(obj, typ, options, refStack)
    if (tokens != null) {
      return tokens
    }
  }
  const typeEncoder = typeEncoders[typ]
  if (!typeEncoder) {
    throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`)
  }
  return typeEncoder(obj, typ, options, refStack)
}

/*
CBOR key sorting is a mess.

The canonicalisation recommendation from https://tools.ietf.org/html/rfc7049#section-3.9
includes the wording:

> The keys in every map must be sorted lowest value to highest.
> Sorting is performed on the bytes of the representation of the key
> data items without paying attention to the 3/5 bit splitting for
> major types.
> ...
>  *  If two keys have different lengths, the shorter one sorts
      earlier;
>  *  If two keys have the same length, the one with the lower value
      in (byte-wise) lexical order sorts earlier.

1. It is not clear what "bytes of the representation of the key" means: is it
   the CBOR representation, or the binary representation of the object itself?
   Consider the int and uint difference here.
2. It is not clear what "without paying attention to" means: do we include it
   and compare on that? Or do we omit the special prefix byte, (mostly) treating
   the key in its plain binary representation form.

The FIDO 2.0: Client To Authenticator Protocol spec takes the original CBOR
wording and clarifies it according to their understanding.
https://fidoalliance.org/specs/fido-v2.0-rd-20170927/fido-client-to-authenticator-protocol-v2.0-rd-20170927.html#message-encoding

> The keys in every map must be sorted lowest value to highest. Sorting is
> performed on the bytes of the representation of the key data items without
> paying attention to the 3/5 bit splitting for major types. The sorting rules
> are:
>  * If the major types are different, the one with the lower value in numerical
>    order sorts earlier.
>  * If two keys have different lengths, the shorter one sorts earlier;
>  * If two keys have the same length, the one with the lower value in
>    (byte-wise) lexical order sorts earlier.

Some other implementations, such as borc, do a full encode then do a
length-first, byte-wise-second comparison:
https://github.com/dignifiedquire/borc/blob/b6bae8b0bcde7c3976b0f0f0957208095c392a36/src/encoder.js#L358
https://github.com/dignifiedquire/borc/blob/b6bae8b0bcde7c3976b0f0f0957208095c392a36/src/utils.js#L143-L151

This has the benefit of being able to easily handle arbitrary keys, including
complex types (maps and arrays).

We'll opt for the FIDO approach, since it affords some efficies since we don't
need a full encode of each key to determine order and can defer to the types
to determine how to most efficiently order their values (i.e. int and uint
ordering can be done on the numbers, no need for byte-wise, for example).

Recommendation: stick to single key types or you'll get into trouble, and prefer
string keys because it's much simpler that way.
*/

/**
 * @param {TokenOrNestedTokens[]} entries
 * @param {EncodeOptions} options
 */
function sortMapEntries (entries, options) {
  if (options.mapSorter) {
    entries.sort(options.mapSorter)
  }
}

/**
 * @param {(Token|Token[])[]} e1
 * @param {(Token|Token[])[]} e2
 * @returns {number}
 */
function mapSorter (e1, e2) {
  // the key position ([0]) could have a single token or an array
  // almost always it'll be a single token but complex key might get involved
  const keyToken1 = Array.isArray(e1[0]) ? e1[0][0] : e1[0]
  const keyToken2 = Array.isArray(e2[0]) ? e2[0][0] : e2[0]

  // different key types
  if (keyToken1.type !== keyToken2.type) {
    return keyToken1.type.compare(keyToken2.type)
  }

  const major = keyToken1.type.major
  // TODO: handle case where cmp === 0 but there are more keyToken e. complex type)
  const tcmp = cborEncoders[major].compareTokens(keyToken1, keyToken2)
  if (tcmp === 0) {
    // duplicate key or complex type where the first token matched,
    // i.e. a map or array and we're only comparing the opening token
    console.warn('WARNING: complex key types used, CBOR key sorting guarantees are gone')
  }
  return tcmp
}

/**
 * @typedef {Token & { _keyBytes?: Uint8Array }} TokenEx
 *
 * @param {(Token|Token[])[]} e1
 * @param {(Token|Token[])[]} e2
 * @returns {number}
 */
function rfc8949MapSorter (e1, e2) {
  if (e1[0] instanceof Token && e2[0] instanceof Token) {
    const t1 = /** @type {TokenEx} */ (e1[0])
    const t2 = /** @type {TokenEx} */ (e2[0])

    if (!t1._keyBytes) {
      t1._keyBytes = encodeRfc8949(t1.value)
    }

    if (!t2._keyBytes) {
      t2._keyBytes = encodeRfc8949(t2.value)
    }

    return compare(t1._keyBytes, t2._keyBytes)
  }

  throw new Error('rfc8949MapSorter: complex key types are not supported yet')
}

/**
 * @param {any} data
 * @returns {Uint8Array}
 */
function encodeRfc8949 (data) {
  return encodeCustom(data, cborEncoders, rfc8949EncodeOptions)
}

/**
 * @param {ByteWriter} writer
 * @param {TokenOrNestedTokens} tokens
 * @param {TokenTypeEncoder[]} encoders
 * @param {EncodeOptions} options
 */
function tokensToEncoded (writer, tokens, encoders, options) {
  if (Array.isArray(tokens)) {
    for (const token of tokens) {
      tokensToEncoded(writer, token, encoders, options)
    }
  } else {
    encoders[tokens.type.major](writer, tokens, options)
  }
}

// CBOR major type prefixes, cached from Type for hot path performance
const MAJOR_UINT = Type.uint.majorEncoded
const MAJOR_NEGINT = Type.negint.majorEncoded
const MAJOR_BYTES = Type.bytes.majorEncoded
const MAJOR_STRING = Type.string.majorEncoded
const MAJOR_ARRAY = Type.array.majorEncoded

// Simple value bytes (CBOR major type 7 + minor value)
const SIMPLE_FALSE = Type.float.majorEncoded | MINOR_FALSE
const SIMPLE_TRUE = Type.float.majorEncoded | MINOR_TRUE
const SIMPLE_NULL = Type.float.majorEncoded | MINOR_NULL
const SIMPLE_UNDEFINED = Type.float.majorEncoded | MINOR_UNDEFINED

const neg1b = BigInt(-1)
const pos1b = BigInt(1)

/**
 * Check if direct encoding can be used for the given options.
 * Direct encoding bypasses token creation for most values.
 * @param {EncodeOptions} options
 * @returns {boolean}
 */
function canDirectEncode (options) {
  // Cannot use direct encode with addBreakTokens (needs special break token handling).
  // Direct encode checks typeEncoders per-value, falling back to tokens as needed.
  // Maps fall back to token-based encoding for efficient key sorting.
  return options.addBreakTokens !== true
}

/**
 * Direct encode a value to the writer, bypassing token creation for most types.
 * Falls back to token-based encoding for custom type encoders.
 * @param {ByteWriter} writer
 * @param {any} data
 * @param {EncodeOptions} options
 * @param {Reference|undefined} refStack
 */
function directEncode (writer, data, options, refStack) {
  const typ = is(data)

  // Check for custom encoder for THIS specific type
  const customEncoder = options.typeEncoders && options.typeEncoders[typ]
  if (customEncoder) {
    const tokens = customEncoder(data, typ, options, refStack)
    if (tokens != null) {
      // Custom encoder returned tokens, serialize immediately
      tokensToEncoded(writer, tokens, cborEncoders, options)
      return
    }
    // Custom encoder returned null, fall through to default handling
  }

  // Direct encode based on type
  switch (typ) {
    case 'null':
      writer.push([SIMPLE_NULL])
      return

    case 'undefined':
      writer.push([SIMPLE_UNDEFINED])
      return

    case 'boolean':
      writer.push([data ? SIMPLE_TRUE : SIMPLE_FALSE])
      return

    case 'number':
      if (!Number.isInteger(data) || !Number.isSafeInteger(data)) {
        // Float, use token encoder for complex float encoding
        encodeFloat(writer, new Token(Type.float, data), options)
      } else if (data >= 0) {
        encodeUintValue(writer, MAJOR_UINT, data)
      } else {
        // Negative integer
        encodeUintValue(writer, MAJOR_NEGINT, data * -1 - 1)
      }
      return

    case 'bigint':
      if (data >= BigInt(0)) {
        encodeUintValue(writer, MAJOR_UINT, data)
      } else {
        encodeUintValue(writer, MAJOR_NEGINT, data * neg1b - pos1b)
      }
      return

    case 'string': {
      const bytes = fromString(data)
      encodeUintValue(writer, MAJOR_STRING, bytes.length)
      writer.push(bytes)
      return
    }

    case 'Uint8Array':
      encodeUintValue(writer, MAJOR_BYTES, data.length)
      writer.push(data)
      return

    case 'Array':
      if (!data.length) {
        writer.push([MAJOR_ARRAY]) // Empty array: 0x80
        return
      }
      refStack = Ref.createCheck(refStack, data)
      encodeUintValue(writer, MAJOR_ARRAY, data.length)
      for (const elem of data) {
        directEncode(writer, elem, options, refStack)
      }
      return

    case 'Object':
    case 'Map':
      // Maps require key sorting, use token-based encoding for efficiency
      // (pre-encoding all keys for sorting is expensive)
      {
        const tokens = typeEncoders.Object(data, typ, options, refStack)
        tokensToEncoded(writer, tokens, cborEncoders, options)
      }
      return

    default:
    // Fall back to token-based encoding for other types (DataView, TypedArrays, etc.)
    {
      const typeEncoder = typeEncoders[typ]
      if (!typeEncoder) {
        throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`)
      }
      const tokens = typeEncoder(data, typ, options, refStack)
      tokensToEncoded(writer, tokens, cborEncoders, options)
    }
  }
}

/**
 * @param {any} data
 * @param {TokenTypeEncoder[]} encoders
 * @param {EncodeOptions} options
 * @param {Uint8Array} [destination]
 * @returns {Uint8Array}
 */
function encodeCustom (data, encoders, options, destination) {
  // arg ordering is different to encodeInto for backward compatibility
  const hasDest = destination instanceof Uint8Array
  let writeTo = hasDest ? new U8Bl(destination) : defaultWriter

  const tokens = objectToTokens(data, options)
  if (!Array.isArray(tokens) && options.quickEncodeToken) {
    const quickBytes = options.quickEncodeToken(tokens)
    if (quickBytes) {
      if (hasDest) {
        // Copy quick bytes into destination buffer
        writeTo.push(quickBytes)
        return writeTo.toBytes()
      }
      return quickBytes
    }
    const encoder = encoders[tokens.type.major]
    if (encoder.encodedSize) {
      const size = encoder.encodedSize(tokens, options)
      if (!hasDest) {
        writeTo = new Bl(size)
      }
      encoder(writeTo, tokens, options)
      // this would be a problem with encodedSize() functions
      if (writeTo.chunks.length !== 1) {
        throw new Error(`Unexpected error: pre-calculated length for ${tokens} was wrong`)
      }
      return hasDest ? writeTo.toBytes() : asU8A(writeTo.chunks[0])
    }
  }
  writeTo.reset()
  tokensToEncoded(writeTo, tokens, encoders, options)
  return writeTo.toBytes(true)
}

/**
 * @param {any} data
 * @param {EncodeOptions} [options]
 * @returns {Uint8Array}
 */
function encode (data, options) {
  options = Object.assign({}, defaultEncodeOptions, options)

  // Use direct encode path when possible
  if (canDirectEncode(options)) {
    defaultWriter.reset()
    directEncode(defaultWriter, data, options, undefined)
    return defaultWriter.toBytes(true)
  }

  return encodeCustom(data, cborEncoders, options)
}

/**
 * @param {any} data
 * @param {Uint8Array} destination
 * @param {EncodeOptions} [options]
 * @returns {{ written: number }}
 */
function encodeInto (data, destination, options) {
  options = Object.assign({}, defaultEncodeOptions, options)

  // Use direct encode path when possible
  if (canDirectEncode(options)) {
    const writer = new U8Bl(destination)
    directEncode(writer, data, options, undefined)
    return { written: writer.toBytes().length }
  }

  const result = encodeCustom(data, cborEncoders, options, destination)
  return { written: result.length }
}

export { objectToTokens, encode, encodeCustom, encodeInto, Ref }
// This is an unfortunate replacement for @sindresorhus/is that we need to
// re-implement for performance purposes. In particular the is.observable()
// check is expensive, and unnecessary for our purposes. The values returned
// are compatible with @sindresorhus/is, however.

// Types that reach getObjectType() - excludes types with fast-paths above:
// primitives (typeof), Array (isArray), Uint8Array (instanceof), plain Object (constructor)
const objectTypeNames = [
  'Object', // for Object.create(null) and other non-plain objects
  'RegExp',
  'Date',
  'Error',
  'Map',
  'Set',
  'WeakMap',
  'WeakSet',
  'ArrayBuffer',
  'SharedArrayBuffer',
  'DataView',
  'Promise',
  'URL',
  'HTMLElement',
  'Int8Array',
  'Uint8ClampedArray',
  'Int16Array',
  'Uint16Array',
  'Int32Array',
  'Uint32Array',
  'Float32Array',
  'Float64Array',
  'BigInt64Array',
  'BigUint64Array',
  'Tagged'
]

/**
 * @param {any} value
 * @returns {string}
 */
export function is (value) {
  if (value === null) {
    return 'null'
  }
  if (value === undefined) {
    return 'undefined'
  }
  if (value === true || value === false) {
    return 'boolean'
  }
  const typeOf = typeof value
  if (typeOf === 'string' || typeOf === 'number' || typeOf === 'bigint' || typeOf === 'symbol') {
    return typeOf
  }
  if (typeOf === 'function') {
    return 'Function'
  }
  if (Array.isArray(value)) {
    return 'Array'
  }
  // Also catches Node.js Buffer which extends Uint8Array
  if (value instanceof Uint8Array) {
    return 'Uint8Array'
  }
  // Fast path for plain objects (most common case after primitives/arrays/bytes)
  if (value.constructor === Object) {
    return 'Object'
  }
  const objectType = getObjectType(value)
  if (objectType) {
    return objectType
  }
  return 'Object'
}

/**
 * @param {any} value
 * @returns {string|undefined}
 */
function getObjectType (value) {
  const objectTypeName = Object.prototype.toString.call(value).slice(8, -1)
  if (objectTypeNames.includes(objectTypeName)) {
    return objectTypeName
  }
  return undefined
}
import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import * as negint from './1negint.js'
import * as bytes from './2bytes.js'
import * as string from './3string.js'
import * as array from './4array.js'
import * as map from './5map.js'
import * as tag from './6tag.js'
import * as float from './7float.js'
import { decodeErrPrefix } from './common.js'
import { fromArray } from './byte-utils.js'

/**
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 */
function invalidMinor (data, pos, minor) {
  throw new Error(`${decodeErrPrefix} encountered invalid minor (${minor}) for major ${data[pos] >>> 5}`)
}

/**
 * @param {string} msg
 * @returns {()=>any}
 */
function errorer (msg) {
  return () => { throw new Error(`${decodeErrPrefix} ${msg}`) }
}

/** @type {((data:Uint8Array, pos:number, minor:number, options?:DecodeOptions) => any)[]} */
export const jump = []

// unsigned integer, 0x00..0x17 (0..23)
for (let i = 0; i <= 0x17; i++) {
  jump[i] = invalidMinor // uint.decodeUintCompact, handled by quick[]
}
jump[0x18] = uint.decodeUint8 // unsigned integer, one-byte uint8_t follows
jump[0x19] = uint.decodeUint16 // unsigned integer, two-byte uint16_t follows
jump[0x1a] = uint.decodeUint32 // unsigned integer, four-byte uint32_t follows
jump[0x1b] = uint.decodeUint64 // unsigned integer, eight-byte uint64_t follows
jump[0x1c] = invalidMinor
jump[0x1d] = invalidMinor
jump[0x1e] = invalidMinor
jump[0x1f] = invalidMinor
// negative integer, -1-0x00..-1-0x17 (-1..-24)
for (let i = 0x20; i <= 0x37; i++) {
  jump[i] = invalidMinor // negintDecode, handled by quick[]
}
jump[0x38] = negint.decodeNegint8 // negative integer, -1-n one-byte uint8_t for n follows
jump[0x39] = negint.decodeNegint16 // negative integer, -1-n two-byte uint16_t for n follows
jump[0x3a] = negint.decodeNegint32 // negative integer, -1-n four-byte uint32_t for follows
jump[0x3b] = negint.decodeNegint64 // negative integer, -1-n eight-byte uint64_t for follows
jump[0x3c] = invalidMinor
jump[0x3d] = invalidMinor
jump[0x3e] = invalidMinor
jump[0x3f] = invalidMinor
// byte string, 0x00..0x17 bytes follow
for (let i = 0x40; i <= 0x57; i++) {
  jump[i] = bytes.decodeBytesCompact
}
jump[0x58] = bytes.decodeBytes8 // byte string, one-byte uint8_t for n, and then n bytes follow
jump[0x59] = bytes.decodeBytes16 // byte string, two-byte uint16_t for n, and then n bytes follow
jump[0x5a] = bytes.decodeBytes32 // byte string, four-byte uint32_t for n, and then n bytes follow
jump[0x5b] = bytes.decodeBytes64 // byte string, eight-byte uint64_t for n, and then n bytes follow
jump[0x5c] = invalidMinor
jump[0x5d] = invalidMinor
jump[0x5e] = invalidMinor
jump[0x5f] = errorer('indefinite length bytes/strings are not supported') // byte string, byte strings follow, terminated by "break"
// UTF-8 string 0x00..0x17 bytes follow
for (let i = 0x60; i <= 0x77; i++) {
  jump[i] = string.decodeStringCompact
}
jump[0x78] = string.decodeString8 // UTF-8 string, one-byte uint8_t for n, and then n bytes follow
jump[0x79] = string.decodeString16 // UTF-8 string, two-byte uint16_t for n, and then n bytes follow
jump[0x7a] = string.decodeString32 // UTF-8 string, four-byte uint32_t for n, and then n bytes follow
jump[0x7b] = string.decodeString64 // UTF-8 string, eight-byte uint64_t for n, and then n bytes follow
jump[0x7c] = invalidMinor
jump[0x7d] = invalidMinor
jump[0x7e] = invalidMinor
jump[0x7f] = errorer('indefinite length bytes/strings are not supported') // UTF-8 strings follow, terminated by "break"
// array, 0x00..0x17 data items follow
for (let i = 0x80; i <= 0x97; i++) {
  jump[i] = array.decodeArrayCompact
}
jump[0x98] = array.decodeArray8 // array, one-byte uint8_t for n, and then n data items follow
jump[0x99] = array.decodeArray16 // array, two-byte uint16_t for n, and then n data items follow
jump[0x9a] = array.decodeArray32 // array, four-byte uint32_t for n, and then n data items follow
jump[0x9b] = array.decodeArray64 // array, eight-byte uint64_t for n, and then n data items follow
jump[0x9c] = invalidMinor
jump[0x9d] = invalidMinor
jump[0x9e] = invalidMinor
jump[0x9f] = array.decodeArrayIndefinite // array, data items follow, terminated by "break"
// map, 0x00..0x17 pairs of data items follow
for (let i = 0xa0; i <= 0xb7; i++) {
  jump[i] = map.decodeMapCompact
}
jump[0xb8] = map.decodeMap8 // map, one-byte uint8_t for n, and then n pairs of data items follow
jump[0xb9] = map.decodeMap16 // map, two-byte uint16_t for n, and then n pairs of data items follow
jump[0xba] = map.decodeMap32 // map, four-byte uint32_t for n, and then n pairs of data items follow
jump[0xbb] = map.decodeMap64 // map, eight-byte uint64_t for n, and then n pairs of data items follow
jump[0xbc] = invalidMinor
jump[0xbd] = invalidMinor
jump[0xbe] = invalidMinor
jump[0xbf] = map.decodeMapIndefinite // map, pairs of data items follow, terminated by "break"
// tags
for (let i = 0xc0; i <= 0xd7; i++) {
  jump[i] = tag.decodeTagCompact
}
jump[0xd8] = tag.decodeTag8
jump[0xd9] = tag.decodeTag16
jump[0xda] = tag.decodeTag32
jump[0xdb] = tag.decodeTag64
jump[0xdc] = invalidMinor
jump[0xdd] = invalidMinor
jump[0xde] = invalidMinor
jump[0xdf] = invalidMinor
// 0xe0..0xf3 simple values, unsupported
for (let i = 0xe0; i <= 0xf3; i++) {
  jump[i] = errorer('simple values are not supported')
}
jump[0xf4] = invalidMinor // false, handled by quick[]
jump[0xf5] = invalidMinor // true, handled by quick[]
jump[0xf6] = invalidMinor // null, handled by quick[]
jump[0xf7] = float.decodeUndefined // undefined
jump[0xf8] = errorer('simple values are not supported') // simple value, one byte follows, unsupported
jump[0xf9] = float.decodeFloat16 // half-precision float (two-byte IEEE 754)
jump[0xfa] = float.decodeFloat32 // single-precision float (four-byte IEEE 754)
jump[0xfb] = float.decodeFloat64 // double-precision float (eight-byte IEEE 754)
jump[0xfc] = invalidMinor
jump[0xfd] = invalidMinor
jump[0xfe] = invalidMinor
jump[0xff] = float.decodeBreak // "break" stop code

/** @type {Token[]} */
export const quick = []
// ints <24
for (let i = 0; i < 24; i++) {
  quick[i] = new Token(Type.uint, i, 1)
}
// negints >= -24
for (let i = -1; i >= -24; i--) {
  quick[31 - i] = new Token(Type.negint, i, 1)
}
// empty bytes
quick[0x40] = new Token(Type.bytes, new Uint8Array(0), 1)
// empty string
quick[0x60] = new Token(Type.string, '', 1)
// empty list
quick[0x80] = new Token(Type.array, 0, 1)
// empty map
quick[0xa0] = new Token(Type.map, 0, 1)
// false
quick[0xf4] = new Token(Type.false, false, 1)
// true
quick[0xf5] = new Token(Type.true, true, 1)
// null
quick[0xf6] = new Token(Type.null, null, 1)

/**
 * @param {Token} token
 * @returns {Uint8Array|undefined}
 */
export function quickEncodeToken (token) {
  switch (token.type) {
    case Type.false:
      return fromArray([0xf4])
    case Type.true:
      return fromArray([0xf5])
    case Type.null:
      return fromArray([0xf6])
    case Type.bytes:
      if (!token.value.length) {
        return fromArray([0x40])
      }
      return
    case Type.string:
      if (token.value === '') {
        return fromArray([0x60])
      }
      return
    case Type.array:
      if (token.value === 0) {
        return fromArray([0x80])
      }
      // shouldn't be possible if this were called when there was only one token
      return
    case Type.map:
      if (token.value === 0) {
        return fromArray([0xa0])
      }
      // shouldn't be possible if this were called when there was only one token
      return
    case Type.uint:
      if (token.value < 24) {
        return fromArray([Number(token.value)])
      }
      return
    case Type.negint:
      if (token.value >= -24) {
        return fromArray([31 - Number(token.value)])
      }
  }
}
/**
 * @typedef {import('../interface.js').TagDecodeControl} TagDecodeControl
 * @typedef {(decode: TagDecodeControl) => Tagged} TaggedTagDecoder
 */

/**
 * A wrapper class for representing a CBOR tag with an arbitrary nested value.
 *
 * `Tagged` is a symmetric primitive: it can be passed to `encode()` to emit
 * a CBOR tag header followed by the encoded form of `value`, and it can be
 * returned from a tag decoder (via `Tagged.decoder(tag)` or `Tagged.preserve()`)
 * to round-trip a tag through decode without losing the tag number.
 *
 * Use `Tagged` for one-off tag handling where defining a dedicated
 * `typeEncoders` entry and tag decoder pair would be heavyweight, e.g. when
 * wrapping a structure in a single application-specific tag (COSE, dCBOR
 * envelopes, etc.).
 *
 * For systematic mapping of a JS type to a tag (e.g. CID -> tag 42), prefer
 * a dedicated `typeEncoders` entry instead.
 */
export class Tagged {
  /**
   * @param {number} tag - CBOR tag number, a non-negative integer
   * @param {any} value - The value to be tagged; encoded recursively
   */
  constructor (tag, value) {
    if (typeof tag !== 'number' || !Number.isInteger(tag) || tag < 0) {
      throw new TypeError('Tagged: tag must be a non-negative integer')
    }
    this.tag = tag
    this.value = value
  }

  /**
   * Build a tag decoder for use in `decode()`'s `tags` option that returns the
   * decoded content wrapped in a `Tagged` instance, preserving the tag number
   * for the caller to inspect.
   *
   * @param {number} tag - The CBOR tag number this decoder will be registered for
   * @returns {TaggedTagDecoder}
   *
   * @example
   * import { decode, Tagged } from 'cborg'
   * const value = decode(bytes, { tags: { 16: Tagged.decoder(16) } })
   * // value instanceof Tagged; value.tag === 16
   */
  static decoder (tag) {
    return (decode) => new Tagged(tag, decode())
  }

  /**
   * Build a `tags` option for `decode()` that wraps each listed tag number in
   * a `Tagged` instance, preserving those tags through decode without
   * registering a dedicated decoder per tag.
   *
   * @param {...number} tagNumbers - One or more CBOR tag numbers to preserve
   * @returns {{[tagNumber: number]: TaggedTagDecoder}}
   *
   * @example
   * import { decode, Tagged } from 'cborg'
   * const value = decode(bytes, { tags: Tagged.preserve(16, 96) })
   */
  static preserve (...tagNumbers) {
    /** @type {{[tagNumber: number]: TaggedTagDecoder}} */
    const tags = {}
    for (const tag of tagNumbers) {
      tags[tag] = Tagged.decoder(tag)
    }
    return tags
  }
}

// Symbol.toStringTag so the internal `is()` type detection returns 'Tagged'
// for instances, allowing the default Tagged typeEncoder to match.
Object.defineProperty(Tagged.prototype, Symbol.toStringTag, {
  value: 'Tagged'
})
class Type {
  /**
   * @param {number} major
   * @param {string} name
   * @param {boolean} terminal
   */
  constructor (major, name, terminal) {
    this.major = major
    this.majorEncoded = major << 5
    this.name = name
    this.terminal = terminal
  }

  toString () {
    return `Type[${this.major}].${this.name}`
  }

  /**
   * @param {Type} typ
   * @returns {number}
   */
  compare (typ) {
    return this.major < typ.major ? -1 : this.major > typ.major ? 1 : 0
  }

  /**
   * Check equality between two Type instances. Safe to use across different
   * copies of the Type class (e.g., when bundlers duplicate the module).
   * (major, name) uniquely identifies a Type; terminal is implied by these.
   * @param {Type} a
   * @param {Type} b
   * @returns {boolean}
   */
  static equals (a, b) {
    return a === b || (a.major === b.major && a.name === b.name)
  }
}

// convert to static fields when better supported
Type.uint = new Type(0, 'uint', true)
Type.negint = new Type(1, 'negint', true)
Type.bytes = new Type(2, 'bytes', true)
Type.string = new Type(3, 'string', true)
Type.array = new Type(4, 'array', false)
Type.map = new Type(5, 'map', false)
Type.tag = new Type(6, 'tag', false) // terminal?
Type.float = new Type(7, 'float', true)
Type.false = new Type(7, 'false', true)
Type.true = new Type(7, 'true', true)
Type.null = new Type(7, 'null', true)
Type.undefined = new Type(7, 'undefined', true)
Type.break = new Type(7, 'break', true)
// Type.indefiniteLength = new Type(0, 'indefiniteLength', true)

class Token {
  /**
   * @param {Type} type
   * @param {any} [value]
   * @param {number} [encodedLength]
   */
  constructor (type, value, encodedLength) {
    this.type = type
    this.value = value
    this.encodedLength = encodedLength
    /** @type {Uint8Array|undefined} */
    this.encodedBytes = undefined
    /** @type {Uint8Array|undefined} */
    this.byteValue = undefined
  }

  toString () {
    return `Token[${this.type}].${this.value}`
  }
}

export { Type, Token }
{
  "name": "cborg",
  "version": "5.1.6",
  "description": "Fast CBOR with a focus on strictness",
  "main": "cborg.js",
  "type": "module",
  "bin": {
    "cborg": "lib/bin.js"
  },
  "scripts": {
    "lint": "standard *.js lib/*.js test/*.js",
    "build": "npm run build:types",
    "build:types": "tsc --build",
    "prepublishOnly": "npm run build",
    "test:node": "mocha test/test-*.js",
    "test:node-bin": "mocha test/node-test-bin.js",
    "test:browser": "polendina --cleanup test/test-*.js",
    "test": "npm run lint && npm run build && npm run test:node && npm run test:node-bin && npm run test:browser",
    "test:ci": "npm run test"
  },
  "repository": {
    "type": "git",
    "url": "git@github.com:rvagg/cborg.git"
  },
  "keywords": [
    "cbor"
  ],
  "author": "Rod <rod@vagg.org> (http://r.va.gg/)",
  "license": "Apache-2.0",
  "devDependencies": {
    "@semantic-release/changelog": "^6.0.3",
    "@semantic-release/commit-analyzer": "^13.0.1",
    "@semantic-release/git": "^10.0.1",
    "@semantic-release/github": "^12.0.6",
    "@semantic-release/npm": "^13.1.5",
    "@semantic-release/release-notes-generator": "^14.1.0",
    "@types/chai": "^5.2.3",
    "@types/mocha": "^10.0.10",
    "@types/node": "^26.0.1",
    "chai": "^6.2.2",
    "conventional-changelog-conventionalcommits": "^10.0.0",
    "ipld-garbage": "^5.0.0",
    "mocha": "^11.7.5",
    "polendina": "^3.2.20",
    "semantic-release": "^25.0.3",
    "standard": "^17.1.2",
    "typescript": "^6.0.2"
  },
  "exports": {
    ".": {
      "import": "./cborg.js",
      "types": "./types/cborg.d.ts"
    },
    "./length": {
      "import": "./lib/length.js",
      "types": "./types/lib/length.d.ts"
    },
    "./taglib": {
      "import": "./lib/taglib.js",
      "types": "./types/lib/taglib.d.ts"
    },
    "./json": {
      "import": "./lib/json/json.js",
      "types": "./types/lib/json/json.d.ts"
    },
    "./extended": {
      "import": "./lib/extended/extended.js",
      "types": "./types/lib/extended/extended.d.ts"
    },
    "./interface": {
      "types": "./types/interface.d.ts"
    }
  },
  "types": "cborg.d.ts",
  "typesVersions": {
    "*": {
      "json": [
        "types/lib/json/json.d.ts"
      ],
      "length": [
        "types/lib/length.d.ts"
      ],
      "*": [
        "types/*"
      ],
      "types/*": [
        "types/*"
      ]
    }
  },
  "release": {
    "branches": [
      "master"
    ],
    "plugins": [
      [
        "@semantic-release/commit-analyzer",
        {
          "preset": "conventionalcommits",
          "releaseRules": [
            {
              "breaking": true,
              "release": "major"
            },
            {
              "revert": true,
              "release": "patch"
            },
            {
              "type": "feat",
              "release": "minor"
            },
            {
              "type": "fix",
              "release": "patch"
            },
            {
              "type": "chore",
              "release": "patch"
            },
            {
              "type": "docs",
              "release": "patch"
            },
            {
              "type": "test",
              "release": "patch"
            },
            {
              "scope": "no-release",
              "release": false
            }
          ]
        }
      ],
      [
        "@semantic-release/release-notes-generator",
        {
          "preset": "conventionalcommits",
          "presetConfig": {
            "types": [
              {
                "type": "feat",
                "section": "Features"
              },
              {
                "type": "fix",
                "section": "Bug Fixes"
              },
              {
                "type": "chore",
                "section": "Trivial Changes"
              },
              {
                "type": "docs",
                "section": "Trivial Changes"
              },
              {
                "type": "test",
                "section": "Tests"
              }
            ]
          }
        }
      ],
      "@semantic-release/changelog",
      "@semantic-release/npm",
      "@semantic-release/github",
      "@semantic-release/git"
    ]
  }
}
import { coerce } from '../bytes.js';
import basex from '../vendor/base-x.js';
/**
 * Class represents both BaseEncoder and MultibaseEncoder meaning it
 * can be used to encode to multibase or base encode without multibase
 * prefix.
 */
class Encoder {
    name;
    prefix;
    baseEncode;
    constructor(name, prefix, baseEncode) {
        this.name = name;
        this.prefix = prefix;
        this.baseEncode = baseEncode;
    }
    encode(bytes) {
        if (bytes instanceof Uint8Array) {
            return `${this.prefix}${this.baseEncode(bytes)}`;
        }
        else {
            throw Error('Unknown type, must be binary type');
        }
    }
}
/**
 * Class represents both BaseDecoder and MultibaseDecoder so it could be used
 * to decode multibases (with matching prefix) or just base decode strings
 * with corresponding base encoding.
 */
class Decoder {
    name;
    prefix;
    baseDecode;
    prefixCodePoint;
    constructor(name, prefix, baseDecode) {
        this.name = name;
        this.prefix = prefix;
        const prefixCodePoint = prefix.codePointAt(0);
        /* c8 ignore next 3 */
        if (prefixCodePoint === undefined) {
            throw new Error('Invalid prefix character');
        }
        this.prefixCodePoint = prefixCodePoint;
        this.baseDecode = baseDecode;
    }
    decode(text) {
        if (typeof text === 'string') {
            if (text.codePointAt(0) !== this.prefixCodePoint) {
                throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);
            }
            return this.baseDecode(text.slice(this.prefix.length));
        }
        else {
            throw Error('Can only multibase decode strings');
        }
    }
    or(decoder) {
        return or(this, decoder);
    }
}
class ComposedDecoder {
    decoders;
    constructor(decoders) {
        this.decoders = decoders;
    }
    or(decoder) {
        return or(this, decoder);
    }
    decode(input) {
        const prefix = input[0];
        const decoder = this.decoders[prefix];
        if (decoder != null) {
            return decoder.decode(input);
        }
        else {
            throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);
        }
    }
}
export function or(left, right) {
    return new ComposedDecoder({
        ...(left.decoders ?? { [left.prefix]: left }),
        ...(right.decoders ?? { [right.prefix]: right })
    });
}
export class Codec {
    name;
    prefix;
    baseEncode;
    baseDecode;
    encoder;
    decoder;
    constructor(name, prefix, baseEncode, baseDecode) {
        this.name = name;
        this.prefix = prefix;
        this.baseEncode = baseEncode;
        this.baseDecode = baseDecode;
        this.encoder = new Encoder(name, prefix, baseEncode);
        this.decoder = new Decoder(name, prefix, baseDecode);
    }
    encode(input) {
        return this.encoder.encode(input);
    }
    decode(input) {
        return this.decoder.decode(input);
    }
}
export function from({ name, prefix, encode, decode }) {
    return new Codec(name, prefix, encode, decode);
}
export function baseX({ name, prefix, alphabet }) {
    const { encode, decode } = basex(alphabet, name);
    return from({
        prefix,
        name,
        encode,
        decode: (text) => coerce(decode(text))
    });
}
function decode(string, alphabetIdx, bitsPerChar, name) {
    // Count the padding bytes:
    let end = string.length;
    while (string[end - 1] === '=') {
        --end;
    }
    // Allocate the output:
    const out = new Uint8Array((end * bitsPerChar / 8) | 0);
    // Parse the data:
    let bits = 0; // Number of bits currently in the buffer
    let buffer = 0; // Bits waiting to be written out, MSB first
    let written = 0; // Next byte to write
    for (let i = 0; i < end; ++i) {
        // Read one character from the string:
        const value = alphabetIdx[string[i]];
        if (value === undefined) {
            throw new SyntaxError(`Non-${name} character`);
        }
        // Append the bits to the buffer:
        buffer = (buffer << bitsPerChar) | value;
        bits += bitsPerChar;
        // Write out some bits if the buffer has a byte's worth:
        if (bits >= 8) {
            bits -= 8;
            out[written++] = 0xff & (buffer >> bits);
        }
    }
    // Verify that we have received just enough bits:
    if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {
        throw new SyntaxError('Unexpected end of data');
    }
    return out;
}
function encode(data, alphabet, bitsPerChar) {
    const pad = alphabet[alphabet.length - 1] === '=';
    const mask = (1 << bitsPerChar) - 1;
    let out = '';
    let bits = 0; // Number of bits currently in the buffer
    let buffer = 0; // Bits waiting to be written out, MSB first
    for (let i = 0; i < data.length; ++i) {
        // Slurp data into the buffer:
        buffer = (buffer << 8) | data[i];
        bits += 8;
        // Write out as much as we can:
        while (bits > bitsPerChar) {
            bits -= bitsPerChar;
            out += alphabet[mask & (buffer >> bits)];
        }
    }
    // Partial character:
    if (bits !== 0) {
        out += alphabet[mask & (buffer << (bitsPerChar - bits))];
    }
    // Add padding characters until we hit a byte boundary:
    if (pad) {
        while (((out.length * bitsPerChar) & 7) !== 0) {
            out += '=';
        }
    }
    return out;
}
function createAlphabetIdx(alphabet) {
    // Build the character lookup table:
    const alphabetIdx = {};
    for (let i = 0; i < alphabet.length; ++i) {
        alphabetIdx[alphabet[i]] = i;
    }
    return alphabetIdx;
}
/**
 * RFC4648 Factory
 */
export function rfc4648({ name, prefix, bitsPerChar, alphabet }) {
    const alphabetIdx = createAlphabetIdx(alphabet);
    return from({
        prefix,
        name,
        encode(input) {
            return encode(input, alphabet, bitsPerChar);
        },
        decode(input) {
            return decode(input, alphabetIdx, bitsPerChar, name);
        }
    });
}
//# sourceMappingURL=base.js.mapimport { rfc4648 } from './base.js';
export const base32 = rfc4648({
    prefix: 'b',
    name: 'base32',
    alphabet: 'abcdefghijklmnopqrstuvwxyz234567',
    bitsPerChar: 5
});
export const base32upper = rfc4648({
    prefix: 'B',
    name: 'base32upper',
    alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',
    bitsPerChar: 5
});
export const base32pad = rfc4648({
    prefix: 'c',
    name: 'base32pad',
    alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',
    bitsPerChar: 5
});
export const base32padupper = rfc4648({
    prefix: 'C',
    name: 'base32padupper',
    alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',
    bitsPerChar: 5
});
export const base32hex = rfc4648({
    prefix: 'v',
    name: 'base32hex',
    alphabet: '0123456789abcdefghijklmnopqrstuv',
    bitsPerChar: 5
});
export const base32hexupper = rfc4648({
    prefix: 'V',
    name: 'base32hexupper',
    alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',
    bitsPerChar: 5
});
export const base32hexpad = rfc4648({
    prefix: 't',
    name: 'base32hexpad',
    alphabet: '0123456789abcdefghijklmnopqrstuv=',
    bitsPerChar: 5
});
export const base32hexpadupper = rfc4648({
    prefix: 'T',
    name: 'base32hexpadupper',
    alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',
    bitsPerChar: 5
});
export const base32z = rfc4648({
    prefix: 'h',
    name: 'base32z',
    alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',
    bitsPerChar: 5
});
//# sourceMappingURL=base32.js.mapimport { baseX } from './base.js';
export const base36 = baseX({
    prefix: 'k',
    name: 'base36',
    alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'
});
export const base36upper = baseX({
    prefix: 'K',
    name: 'base36upper',
    alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
});
//# sourceMappingURL=base36.js.mapimport { baseX } from './base.js';
export const base58btc = baseX({
    name: 'base58btc',
    prefix: 'z',
    alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
});
export const base58flickr = baseX({
    name: 'base58flickr',
    prefix: 'Z',
    alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'
});
//# sourceMappingURL=base58.js.mapexport const empty = new Uint8Array(0);
export function toHex(d) {
    return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '');
}
export function fromHex(hex) {
    const hexes = hex.match(/../g);
    return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty;
}
export function equals(aa, bb) {
    if (aa === bb) {
        return true;
    }
    if (aa.byteLength !== bb.byteLength) {
        return false;
    }
    for (let ii = 0; ii < aa.byteLength; ii++) {
        if (aa[ii] !== bb[ii]) {
            return false;
        }
    }
    return true;
}
export function coerce(o) {
    if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') {
        return o;
    }
    if (o instanceof ArrayBuffer) {
        return new Uint8Array(o);
    }
    if (ArrayBuffer.isView(o)) {
        return new Uint8Array(o.buffer, o.byteOffset, o.byteLength);
    }
    throw new Error('Unknown type, must be binary type');
}
export function isBinary(o) {
    return o instanceof ArrayBuffer || ArrayBuffer.isView(o);
}
export function fromString(str) {
    return new TextEncoder().encode(str);
}
export function toString(b) {
    return new TextDecoder().decode(b);
}
//# sourceMappingURL=bytes.js.mapimport { base32 } from './bases/base32.js';
import { base36 } from './bases/base36.js';
import { base58btc } from './bases/base58.js';
import { coerce } from './bytes.js';
import * as Digest from './hashes/digest.js';
import * as varint from './varint.js';
// This way TS will also expose all the types from module
export * from './link/interface.js';
export function format(link, base) {
    const { bytes, version } = link;
    switch (version) {
        case 0:
            return toStringV0(bytes, baseCache(link), base ?? base58btc.encoder);
        default:
            return toStringV1(bytes, baseCache(link), (base ?? base32.encoder));
    }
}
export function toJSON(link) {
    return {
        '/': format(link)
    };
}
export function fromJSON(json) {
    return CID.parse(json['/']);
}
const cache = new WeakMap();
function baseCache(cid) {
    const baseCache = cache.get(cid);
    if (baseCache == null) {
        const baseCache = new Map();
        cache.set(cid, baseCache);
        return baseCache;
    }
    return baseCache;
}
export class CID {
    code;
    version;
    multihash;
    bytes;
    '/';
    /**
     * @param version - Version of the CID
     * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
     * @param multihash - (Multi)hash of the of the content.
     */
    constructor(version, code, multihash, bytes) {
        this.code = code;
        this.version = version;
        this.multihash = multihash;
        this.bytes = bytes;
        // flag to serializers that this is a CID and
        // should be treated specially
        this['/'] = bytes;
    }
    /**
     * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`
     * please either use `CID.asCID(cid)` or switch to new signalling mechanism
     *
     * @deprecated
     */
    get asCID() {
        return this;
    }
    // ArrayBufferView
    get byteOffset() {
        return this.bytes.byteOffset;
    }
    // ArrayBufferView
    get byteLength() {
        return this.bytes.byteLength;
    }
    toV0() {
        switch (this.version) {
            case 0: {
                return this;
            }
            case 1: {
                const { code, multihash } = this;
                if (code !== DAG_PB_CODE) {
                    throw new Error('Cannot convert a non dag-pb CID to CIDv0');
                }
                // sha2-256
                if (multihash.code !== SHA_256_CODE) {
                    throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0');
                }
                return (CID.createV0(multihash));
            }
            default: {
                throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);
            }
        }
    }
    toV1() {
        switch (this.version) {
            case 0: {
                const { code, digest } = this.multihash;
                const multihash = Digest.create(code, digest);
                return (CID.createV1(this.code, multihash));
            }
            case 1: {
                return this;
            }
            default: {
                throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);
            }
        }
    }
    equals(other) {
        return CID.equals(this, other);
    }
    static equals(self, other) {
        const unknown = other;
        return (unknown != null &&
            self.code === unknown.code &&
            self.version === unknown.version &&
            Digest.equals(self.multihash, unknown.multihash));
    }
    toString(base) {
        return format(this, base);
    }
    toJSON() {
        return { '/': format(this) };
    }
    link() {
        return this;
    }
    [Symbol.toStringTag] = 'CID';
    // Legacy
    [Symbol.for('nodejs.util.inspect.custom')]() {
        return `CID(${this.toString()})`;
    }
    /**
     * Takes any input `value` and returns a `CID` instance if it was
     * a `CID` otherwise returns `null`. If `value` is instanceof `CID`
     * it will return value back. If `value` is not instance of this CID
     * class, but is compatible CID it will return new instance of this
     * `CID` class. Otherwise returns null.
     *
     * This allows two different incompatible versions of CID library to
     * co-exist and interop as long as binary interface is compatible.
     */
    static asCID(input) {
        if (input == null) {
            return null;
        }
        const value = input;
        if (value instanceof CID) {
            // If value is instance of CID then we're all set.
            return value;
        }
        else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {
            // If value isn't instance of this CID class but `this.asCID === this` or
            // `value['/'] === value.bytes` is true it is CID instance coming from a
            // different implementation (diff version or duplicate). In that case we
            // rebase it to this `CID` implementation so caller is guaranteed to get
            // instance with expected API.
            const { version, code, multihash, bytes } = value;
            return new CID(version, code, multihash, bytes ?? encodeCID(version, code, multihash.bytes));
        }
        else if (value[cidSymbol] === true) {
            // If value is a CID from older implementation that used to be tagged via
            // symbol we still rebase it to the this `CID` implementation by
            // delegating that to a constructor.
            const { version, multihash, code } = value;
            const digest = Digest.decode(multihash);
            return CID.create(version, code, digest);
        }
        else {
            // Otherwise value is not a CID (or an incompatible version of it) in
            // which case we return `null`.
            return null;
        }
    }
    /**
     * @param version - Version of the CID
     * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
     * @param digest - (Multi)hash of the of the content.
     */
    static create(version, code, digest) {
        if (typeof code !== 'number') {
            throw new Error('String codecs are no longer supported');
        }
        if (!(digest.bytes instanceof Uint8Array)) {
            throw new Error('Invalid digest');
        }
        switch (version) {
            case 0: {
                if (code !== DAG_PB_CODE) {
                    throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);
                }
                else {
                    return new CID(version, code, digest, digest.bytes);
                }
            }
            case 1: {
                const bytes = encodeCID(version, code, digest.bytes);
                return new CID(version, code, digest, bytes);
            }
            default: {
                throw new Error('Invalid version');
            }
        }
    }
    /**
     * Simplified version of `create` for CIDv0.
     */
    static createV0(digest) {
        return CID.create(0, DAG_PB_CODE, digest);
    }
    /**
     * Simplified version of `create` for CIDv1.
     *
     * @param code - Content encoding format code.
     * @param digest - Multihash of the content.
     */
    static createV1(code, digest) {
        return CID.create(1, code, digest);
    }
    /**
     * Decoded a CID from its binary representation. The byte array must contain
     * only the CID with no additional bytes.
     *
     * An error will be thrown if the bytes provided do not contain a valid
     * binary representation of a CID.
     */
    static decode(bytes) {
        const [cid, remainder] = CID.decodeFirst(bytes);
        if (remainder.length !== 0) {
            throw new Error('Incorrect length');
        }
        return cid;
    }
    /**
     * Decoded a CID from its binary representation at the beginning of a byte
     * array.
     *
     * Returns an array with the first element containing the CID and the second
     * element containing the remainder of the original byte array. The remainder
     * will be a zero-length byte array if the provided bytes only contained a
     * binary CID representation.
     */
    static decodeFirst(bytes) {
        const specs = CID.inspectBytes(bytes);
        const prefixSize = specs.size - specs.multihashSize;
        const multihashBytes = coerce(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));
        if (multihashBytes.byteLength !== specs.multihashSize) {
            throw new Error('Incorrect length');
        }
        const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);
        const digest = new Digest.Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);
        const cid = specs.version === 0
            ? CID.createV0(digest)
            : CID.createV1(specs.codec, digest);
        return [cid, bytes.subarray(specs.size)];
    }
    /**
     * Inspect the initial bytes of a CID to determine its properties.
     *
     * Involves decoding up to 4 varints. Typically this will require only 4 to 6
     * bytes but for larger multicodec code values and larger multihash digest
     * lengths these varints can be quite large. It is recommended that at least
     * 10 bytes be made available in the `initialBytes` argument for a complete
     * inspection.
     */
    static inspectBytes(initialBytes) {
        let offset = 0;
        const next = () => {
            const [i, length] = varint.decode(initialBytes.subarray(offset));
            offset += length;
            return i;
        };
        let version = next();
        let codec = DAG_PB_CODE;
        if (version === 18) {
            // CIDv0
            version = 0;
            offset = 0;
        }
        else {
            codec = next();
        }
        if (version !== 0 && version !== 1) {
            throw new RangeError(`Invalid CID version ${version}`);
        }
        const prefixSize = offset;
        const multihashCode = next(); // multihash code
        const digestSize = next(); // multihash length
        const size = offset + digestSize;
        const multihashSize = size - prefixSize;
        return { version, codec, multihashCode, digestSize, multihashSize, size };
    }
    /**
     * Takes cid in a string representation and creates an instance. If `base`
     * decoder is not provided will use a default from the configuration. It will
     * throw an error if encoding of the CID is not compatible with supplied (or
     * a default decoder).
     */
    static parse(source, base) {
        const [prefix, bytes] = parseCIDtoBytes(source, base);
        const cid = CID.decode(bytes);
        if (cid.version === 0 && source[0] !== 'Q') {
            throw Error('Version 0 CID string must not include multibase prefix');
        }
        // Cache string representation to avoid computing it on `this.toString()`
        baseCache(cid).set(prefix, source);
        return cid;
    }
}
function parseCIDtoBytes(source, base) {
    switch (source[0]) {
        // CIDv0 is parsed differently
        case 'Q': {
            const decoder = base ?? base58btc;
            return [
                base58btc.prefix,
                decoder.decode(`${base58btc.prefix}${source}`)
            ];
        }
        case base58btc.prefix: {
            const decoder = base ?? base58btc;
            return [base58btc.prefix, decoder.decode(source)];
        }
        case base32.prefix: {
            const decoder = base ?? base32;
            return [base32.prefix, decoder.decode(source)];
        }
        case base36.prefix: {
            const decoder = base ?? base36;
            return [base36.prefix, decoder.decode(source)];
        }
        default: {
            if (base == null) {
                throw Error('To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided');
            }
            return [source[0], base.decode(source)];
        }
    }
}
function toStringV0(bytes, cache, base) {
    const { prefix } = base;
    if (prefix !== base58btc.prefix) {
        throw Error(`Cannot string encode V0 in ${base.name} encoding`);
    }
    const cid = cache.get(prefix);
    if (cid == null) {
        const cid = base.encode(bytes).slice(1);
        cache.set(prefix, cid);
        return cid;
    }
    else {
        return cid;
    }
}
function toStringV1(bytes, cache, base) {
    const { prefix } = base;
    const cid = cache.get(prefix);
    if (cid == null) {
        const cid = base.encode(bytes);
        cache.set(prefix, cid);
        return cid;
    }
    else {
        return cid;
    }
}
const DAG_PB_CODE = 0x70;
const SHA_256_CODE = 0x12;
function encodeCID(version, code, multihash) {
    const codeOffset = varint.encodingLength(version);
    const hashOffset = codeOffset + varint.encodingLength(code);
    const bytes = new Uint8Array(hashOffset + multihash.byteLength);
    varint.encodeTo(version, bytes, 0);
    varint.encodeTo(code, bytes, codeOffset);
    bytes.set(multihash, hashOffset);
    return bytes;
}
const cidSymbol = Symbol.for('@ipld/js-cid/CID');
//# sourceMappingURL=cid.js.mapimport { coerce } from '../bytes.js';
export const name = 'raw';
export const code = 0x55;
export function encode(node) {
    return coerce(node);
}
export function decode(data) {
    return coerce(data);
}
//# sourceMappingURL=raw.js.mapimport { coerce, equals as equalBytes } from '../bytes.js';
import * as varint from '../varint.js';
/**
 * Creates a multihash digest.
 */
export function create(code, digest) {
    const size = digest.byteLength;
    const sizeOffset = varint.encodingLength(code);
    const digestOffset = sizeOffset + varint.encodingLength(size);
    const bytes = new Uint8Array(digestOffset + size);
    varint.encodeTo(code, bytes, 0);
    varint.encodeTo(size, bytes, sizeOffset);
    bytes.set(digest, digestOffset);
    return new Digest(code, size, digest, bytes);
}
/**
 * Turns bytes representation of multihash digest into an instance.
 */
export function decode(multihash) {
    const bytes = coerce(multihash);
    const [code, sizeOffset] = varint.decode(bytes);
    const [size, digestOffset] = varint.decode(bytes.subarray(sizeOffset));
    const digest = bytes.subarray(sizeOffset + digestOffset);
    if (digest.byteLength !== size) {
        throw new Error('Incorrect length');
    }
    return new Digest(code, size, digest, bytes);
}
export function equals(a, b) {
    if (a === b) {
        return true;
    }
    else {
        const data = b;
        return (a.code === data.code &&
            a.size === data.size &&
            data.bytes instanceof Uint8Array &&
            equalBytes(a.bytes, data.bytes));
    }
}
/**
 * Represents a multihash digest which carries information about the
 * hashing algorithm and an actual hash digest.
 */
export class Digest {
    code;
    size;
    digest;
    bytes;
    /**
     * Creates a multihash digest.
     */
    constructor(code, size, digest, bytes) {
        this.code = code;
        this.size = size;
        this.digest = digest;
        this.bytes = bytes;
    }
}
/**
 * Used to check that the passed multihash has the passed code
 */
export function hasCode(digest, code) {
    return digest.code === code;
}
//# sourceMappingURL=digest.js.mapexport {};
//# sourceMappingURL=interface.js.mapimport varint from './vendor/varint.js';
export function decode(data, offset = 0) {
    const code = varint.decode(data, offset);
    return [code, varint.decode.bytes];
}
export function encodeTo(int, target, offset = 0) {
    varint.encode(int, target, offset);
    return target;
}
export function encodingLength(int) {
    return varint.encodingLength(int);
}
//# sourceMappingURL=varint.js.map/* eslint-disable */
// base-x encoding / decoding
// Copyright (c) 2018 base-x contributors
// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)
// Distributed under the MIT software license, see the accompanying
// file LICENSE or http://www.opensource.org/licenses/mit-license.php.
/**
 * @param {string} ALPHABET
 * @param {any} name
 */
function base(ALPHABET, name) {
    if (ALPHABET.length >= 255) {
        throw new TypeError('Alphabet too long');
    }
    var BASE_MAP = new Uint8Array(256);
    for (var j = 0; j < BASE_MAP.length; j++) {
        BASE_MAP[j] = 255;
    }
    for (var i = 0; i < ALPHABET.length; i++) {
        var x = ALPHABET.charAt(i);
        var xc = x.charCodeAt(0);
        if (BASE_MAP[xc] !== 255) {
            throw new TypeError(x + ' is ambiguous');
        }
        BASE_MAP[xc] = i;
    }
    var BASE = ALPHABET.length;
    var LEADER = ALPHABET.charAt(0);
    var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up
    var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up
    /**
     * @param {any[] | Iterable<number>} source
     */
    function encode(source) {
        // @ts-ignore
        if (source instanceof Uint8Array)
            ;
        else if (ArrayBuffer.isView(source)) {
            source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
        }
        else if (Array.isArray(source)) {
            source = Uint8Array.from(source);
        }
        if (!(source instanceof Uint8Array)) {
            throw new TypeError('Expected Uint8Array');
        }
        if (source.length === 0) {
            return '';
        }
        // Skip & count leading zeroes.
        var zeroes = 0;
        var length = 0;
        var pbegin = 0;
        var pend = source.length;
        while (pbegin !== pend && source[pbegin] === 0) {
            pbegin++;
            zeroes++;
        }
        // Allocate enough space in big-endian base58 representation.
        var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;
        var b58 = new Uint8Array(size);
        // Process the bytes.
        while (pbegin !== pend) {
            var carry = source[pbegin];
            // Apply "b58 = b58 * 256 + ch".
            var i = 0;
            for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {
                carry += (256 * b58[it1]) >>> 0;
                b58[it1] = (carry % BASE) >>> 0;
                carry = (carry / BASE) >>> 0;
            }
            if (carry !== 0) {
                throw new Error('Non-zero carry');
            }
            length = i;
            pbegin++;
        }
        // Skip leading zeroes in base58 result.
        var it2 = size - length;
        while (it2 !== size && b58[it2] === 0) {
            it2++;
        }
        // Translate the result into a string.
        var str = LEADER.repeat(zeroes);
        for (; it2 < size; ++it2) {
            str += ALPHABET.charAt(b58[it2]);
        }
        return str;
    }
    /**
     * @param {string | string[]} source
     */
    function decodeUnsafe(source) {
        if (typeof source !== 'string') {
            throw new TypeError('Expected String');
        }
        if (source.length === 0) {
            return new Uint8Array();
        }
        var psz = 0;
        // Skip leading spaces.
        if (source[psz] === ' ') {
            return;
        }
        // Skip and count leading '1's.
        var zeroes = 0;
        var length = 0;
        while (source[psz] === LEADER) {
            zeroes++;
            psz++;
        }
        // Allocate enough space in big-endian base256 representation.
        var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.
        var b256 = new Uint8Array(size);
        // Process the characters.
        while (source[psz]) {
            // Decode character
            var carry = BASE_MAP[source.charCodeAt(psz)];
            // Invalid character
            if (carry === 255) {
                return;
            }
            var i = 0;
            for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {
                carry += (BASE * b256[it3]) >>> 0;
                b256[it3] = (carry % 256) >>> 0;
                carry = (carry / 256) >>> 0;
            }
            if (carry !== 0) {
                throw new Error('Non-zero carry');
            }
            length = i;
            psz++;
        }
        // Skip trailing spaces.
        if (source[psz] === ' ') {
            return;
        }
        // Skip leading zeroes in b256.
        var it4 = size - length;
        while (it4 !== size && b256[it4] === 0) {
            it4++;
        }
        var vch = new Uint8Array(zeroes + (size - it4));
        var j = zeroes;
        while (it4 !== size) {
            vch[j++] = b256[it4++];
        }
        return vch;
    }
    /**
     * @param {string | string[]} string
     */
    function decode(string) {
        var buffer = decodeUnsafe(string);
        if (buffer) {
            return buffer;
        }
        throw new Error(`Non-${name} character`);
    }
    return {
        encode: encode,
        decodeUnsafe: decodeUnsafe,
        decode: decode
    };
}
var src = base;
var _brrp__multiformats_scope_baseX = src;
export default _brrp__multiformats_scope_baseX;
//# sourceMappingURL=base-x.js.map/* eslint-disable */
var encode_1 = encode;
var MSB = 0x80, REST = 0x7F, MSBALL = ~REST, INT = Math.pow(2, 31);
/**
 * @param {number} num
 * @param {number[]} out
 * @param {number} offset
 */
function encode(num, out, offset) {
    out = out || [];
    offset = offset || 0;
    var oldOffset = offset;
    while (num >= INT) {
        out[offset++] = (num & 0xFF) | MSB;
        num /= 128;
    }
    while (num & MSBALL) {
        out[offset++] = (num & 0xFF) | MSB;
        num >>>= 7;
    }
    out[offset] = num | 0;
    // @ts-ignore
    encode.bytes = offset - oldOffset + 1;
    return out;
}
var decode = read;
var MSB$1 = 0x80, REST$1 = 0x7F;
/**
 * @param {string | any[]} buf
 * @param {number} offset
 */
function read(buf, offset) {
    var res = 0, offset = offset || 0, shift = 0, counter = offset, b, l = buf.length;
    do {
        if (counter >= l) {
            // @ts-ignore
            read.bytes = 0;
            throw new RangeError('Could not decode varint');
        }
        b = buf[counter++];
        res += shift < 28
            ? (b & REST$1) << shift
            : (b & REST$1) * Math.pow(2, shift);
        shift += 7;
    } while (b >= MSB$1);
    // @ts-ignore
    read.bytes = counter - offset;
    return res;
}
var N1 = Math.pow(2, 7);
var N2 = Math.pow(2, 14);
var N3 = Math.pow(2, 21);
var N4 = Math.pow(2, 28);
var N5 = Math.pow(2, 35);
var N6 = Math.pow(2, 42);
var N7 = Math.pow(2, 49);
var N8 = Math.pow(2, 56);
var N9 = Math.pow(2, 63);
var length = function (/** @type {number} */ value) {
    return (value < N1 ? 1
        : value < N2 ? 2
            : value < N3 ? 3
                : value < N4 ? 4
                    : value < N5 ? 5
                        : value < N6 ? 6
                            : value < N7 ? 7
                                : value < N8 ? 8
                                    : value < N9 ? 9
                                        : 10);
};
var varint = {
    encode: encode_1,
    decode: decode,
    encodingLength: length
};
var _brrp_varint = varint;
export default _brrp_varint;
//# sourceMappingURL=varint.js.map{
  "name": "multiformats",
  "version": "13.4.2",
  "description": "Interface for multihash, multicodec, multibase and CID",
  "author": "Mikeal Rogers <mikeal.rogers@gmail.com> (https://www.mikealrogers.com/)",
  "license": "Apache-2.0 OR MIT",
  "homepage": "https://github.com/multiformats/js-multiformats#readme",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/multiformats/js-multiformats.git"
  },
  "bugs": {
    "url": "https://github.com/multiformats/js-multiformats/issues"
  },
  "publishConfig": {
    "access": "public",
    "provenance": true
  },
  "keywords": [
    "ipfs",
    "ipld",
    "multiformats"
  ],
  "type": "module",
  "types": "./dist/src/index.d.ts",
  "typesVersions": {
    "*": {
      "*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ],
      "src/*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ]
    }
  },
  "files": [
    "src",
    "dist",
    "!dist/test",
    "!**/*.tsbuildinfo"
  ],
  "exports": {
    ".": {
      "types": "./dist/src/index.d.ts",
      "import": "./dist/src/index.js"
    },
    "./bases/base10": {
      "types": "./dist/src/bases/base10.d.ts",
      "import": "./dist/src/bases/base10.js"
    },
    "./bases/base16": {
      "types": "./dist/src/bases/base16.d.ts",
      "import": "./dist/src/bases/base16.js"
    },
    "./bases/base2": {
      "types": "./dist/src/bases/base2.d.ts",
      "import": "./dist/src/bases/base2.js"
    },
    "./bases/base256emoji": {
      "types": "./dist/src/bases/base256emoji.d.ts",
      "import": "./dist/src/bases/base256emoji.js"
    },
    "./bases/base32": {
      "types": "./dist/src/bases/base32.d.ts",
      "import": "./dist/src/bases/base32.js"
    },
    "./bases/base36": {
      "types": "./dist/src/bases/base36.d.ts",
      "import": "./dist/src/bases/base36.js"
    },
    "./bases/base58": {
      "types": "./dist/src/bases/base58.d.ts",
      "import": "./dist/src/bases/base58.js"
    },
    "./bases/base64": {
      "types": "./dist/src/bases/base64.d.ts",
      "import": "./dist/src/bases/base64.js"
    },
    "./bases/base8": {
      "types": "./dist/src/bases/base8.d.ts",
      "import": "./dist/src/bases/base8.js"
    },
    "./bases/identity": {
      "types": "./dist/src/bases/identity.d.ts",
      "import": "./dist/src/bases/identity.js"
    },
    "./bases/interface": {
      "types": "./dist/src/bases/interface.d.ts",
      "import": "./dist/src/bases/interface.js"
    },
    "./basics": {
      "types": "./dist/src/basics.d.ts",
      "import": "./dist/src/basics.js"
    },
    "./block": {
      "types": "./dist/src/block.d.ts",
      "import": "./dist/src/block.js"
    },
    "./block/interface": {
      "types": "./dist/src/block/interface.d.ts",
      "import": "./dist/src/block/interface.js"
    },
    "./bytes": {
      "types": "./dist/src/bytes.d.ts",
      "import": "./dist/src/bytes.js"
    },
    "./cid": {
      "types": "./dist/src/cid.d.ts",
      "import": "./dist/src/cid.js"
    },
    "./codecs/interface": {
      "types": "./dist/src/codecs/interface.d.ts",
      "import": "./dist/src/codecs/interface.js"
    },
    "./codecs/json": {
      "types": "./dist/src/codecs/json.d.ts",
      "import": "./dist/src/codecs/json.js"
    },
    "./codecs/raw": {
      "types": "./dist/src/codecs/raw.d.ts",
      "import": "./dist/src/codecs/raw.js"
    },
    "./hashes/digest": {
      "types": "./dist/src/hashes/digest.d.ts",
      "import": "./dist/src/hashes/digest.js"
    },
    "./hashes/hasher": {
      "types": "./dist/src/hashes/hasher.d.ts",
      "import": "./dist/src/hashes/hasher.js"
    },
    "./hashes/identity": {
      "types": "./dist/src/hashes/identity.d.ts",
      "import": "./dist/src/hashes/identity.js"
    },
    "./hashes/interface": {
      "types": "./dist/src/hashes/interface.d.ts",
      "import": "./dist/src/hashes/interface.js"
    },
    "./hashes/sha1": {
      "types": "./dist/types/src/hashes/sha1.d.ts",
      "browser": "./dist/src/hashes/sha1-browser.js",
      "import": "./dist/src/hashes/sha1.js"
    },
    "./hashes/sha2": {
      "types": "./dist/src/hashes/sha2.d.ts",
      "browser": "./dist/src/hashes/sha2-browser.js",
      "import": "./dist/src/hashes/sha2.js"
    },
    "./interface": {
      "types": "./dist/src/interface.d.ts",
      "import": "./dist/src/interface.js"
    },
    "./link": {
      "types": "./dist/src/link.d.ts",
      "import": "./dist/src/link.js"
    },
    "./link/interface": {
      "types": "./dist/src/link/interface.d.ts",
      "import": "./dist/src/link/interface.js"
    },
    "./traversal": {
      "types": "./dist/src/traversal.d.ts",
      "import": "./dist/src/traversal.js"
    }
  },
  "eslintConfig": {
    "extends": "ipfs",
    "parserOptions": {
      "project": true,
      "sourceType": "module"
    }
  },
  "release": {
    "branches": [
      "master"
    ],
    "plugins": [
      [
        "@semantic-release/commit-analyzer",
        {
          "preset": "conventionalcommits",
          "releaseRules": [
            {
              "breaking": true,
              "release": "major"
            },
            {
              "revert": true,
              "release": "patch"
            },
            {
              "type": "feat",
              "release": "minor"
            },
            {
              "type": "fix",
              "release": "patch"
            },
            {
              "type": "docs",
              "release": "patch"
            },
            {
              "type": "test",
              "release": "patch"
            },
            {
              "type": "deps",
              "release": "patch"
            },
            {
              "scope": "no-release",
              "release": false
            }
          ]
        }
      ],
      [
        "@semantic-release/release-notes-generator",
        {
          "preset": "conventionalcommits",
          "presetConfig": {
            "types": [
              {
                "type": "feat",
                "section": "Features"
              },
              {
                "type": "fix",
                "section": "Bug Fixes"
              },
              {
                "type": "chore",
                "section": "Trivial Changes"
              },
              {
                "type": "docs",
                "section": "Documentation"
              },
              {
                "type": "deps",
                "section": "Dependencies"
              },
              {
                "type": "test",
                "section": "Tests"
              }
            ]
          }
        }
      ],
      "@semantic-release/changelog",
      "@semantic-release/npm",
      "@semantic-release/github",
      [
        "@semantic-release/git",
        {
          "assets": [
            "CHANGELOG.md",
            "package.json"
          ]
        }
      ]
    ]
  },
  "scripts": {
    "clean": "aegir clean",
    "lint": "aegir lint",
    "build": "aegir build",
    "release": "aegir release",
    "docs": "aegir docs",
    "test": "npm run lint && npm run test:node && npm run test:chrome",
    "test:node": "aegir test -t node --cov",
    "test:chrome": "aegir test -t browser --cov",
    "test:chrome-webworker": "aegir test -t webworker",
    "test:firefox": "aegir test -t browser -- --browser firefox",
    "test:firefox-webworker": "aegir test -t webworker -- --browser firefox",
    "test:electron-main": "aegir test -t electron-main"
  },
  "devDependencies": {
    "@stablelib/sha256": "^2.0.0",
    "@stablelib/sha512": "^2.0.0",
    "@types/node": "^25.0.0",
    "aegir": "^47.0.7",
    "buffer": "^6.0.3",
    "cids": "^1.1.9",
    "crypto-hash": "^4.0.0"
  },
  "aegir": {
    "test": {
      "target": [
        "node",
        "browser"
      ]
    }
  },
  "browser": {
    "./hashes/sha1": "./dist/src/hashes/sha1-browser.js",
    "./dist/src/hashes/sha1.js": "./dist/src/hashes/sha1-browser.js",
    "./hashes/sha2": "./dist/src/hashes/sha2-browser.js",
    "./dist/src/hashes/sha2.js": "./dist/src/hashes/sha2-browser.js"
  }
}
{
  "name": "atproto-repo",
  "version": "0.0.1",
  "description": "Byte-exact atproto repo layer — CAR + DAG-CBOR + CID + MST — over Hypercore-friendly primitives. Verified against real relay-accepted repos.",
  "type": "module",
  "main": "lib/repo.js",
  "scripts": {
    "test": "brittle-node test/*.test.js",
    "postinstall": "node scripts/bare-deps.mjs"
  },
  "dependencies": {
    "@ipld/car": "^5.4.0",
    "@ipld/dag-cbor": "^9.2.1",
    "@noble/curves": "^1.9.7",
    "@noble/hashes": "^1.5.0",
    "multiformats": "^13.3.0"
  },
  "devDependencies": {
    "atproto-identity": "file:../atproto-identity",
    "brittle": "^4.0.2"
  }
}
// The store package owns the Holepunch substrate — so the corestore dependency resolves
// here (store/node_modules), and higher layers (pds) compose store abstractions without
// reaching for corestore directly.

import Corestore from 'corestore'

// A dir path (or an existing Corestore) -> a Corestore. Idempotent on an instance.
export function openCorestore (storage) {
  return isCorestore(storage) ? storage : new Corestore(storage)
}

// ⛔ NOT `instanceof`. That compares against ONE module instance's class object, and a nested
// node_modules tree routinely yields two copies of corestore — which is what bare-pack ships to the
// phone (…/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/corestore
// alongside the daemon's own). A store built by copy A then fails `instanceof` against copy B, and every
// discriminator here reads that as "not a store, therefore a PATH", so Corestore tried to path.join an
// OBJECT and the node died with `Cannot read properties of undefined (reading 'length')` — a message
// that names a JS idiom and no cause (hyper-social #40).
//
// It cannot reproduce on a workstation, where the tree is deduped to one copy. The environments differ
// in their module graph, not their code, so identity is the wrong question: a store is what it DOES.
// `get` + `namespace` + `replicate` are the surface every caller here uses and nothing else implements.
// The instanceof check stays as a fast path for the common single-copy case.
export function isCorestore (x) {
  if (!x || typeof x !== 'object') return false
  if (x instanceof Corestore) return true
  return typeof x.get === 'function' && typeof x.namespace === 'function' && typeof x.replicate === 'function'
}

export { Corestore }
// Firehose #commit frame — the atproto com.atproto.sync.subscribeRepos wire format.
//
// A frame = dag-cbor({t:'#commit', op:1})  ++  dag-cbor(body). Built to match millipds
// (repo_ops.py apply_writes) field-for-field. `seq` and `time` are firehose-server
// state supplied by the caller. `blocks` is a CAR (root = the new commit) of the
// changed blocks.

import * as dagCbor from '@ipld/dag-cbor'
import { writeCar } from 'atproto-repo/lib/repo.js'
import { commitCid } from 'atproto-repo/lib/commit.js'

// subscribeRepos frame = dag-cbor(header {t, op:1}) ++ dag-cbor(body). Each header is
// a constant byte prefix (dag-cbor canonicalises map order), so we emit/detect by it.
export const COMMIT_HEADER = dagCbor.encode({ t: '#commit', op: 1 })
export const IDENTITY_HEADER = dagCbor.encode({ t: '#identity', op: 1 })
export const ACCOUNT_HEADER = dagCbor.encode({ t: '#account', op: 1 })
export const SYNC_HEADER = dagCbor.encode({ t: '#sync', op: 1 })

function frame (header, body) {
  const bodyBytes = dagCbor.encode(body)
  const out = new Uint8Array(header.length + bodyBytes.length)
  out.set(header, 0)
  out.set(bodyBytes, header.length)
  return out
}

// Assemble a #commit frame from a RepoManager.applyWrite() result.
export async function commitFrame (write, { seq, time }) {
  const carBytes = await writeCar(write.commitCid, [write.commitBlock, ...write.newBlocks])
  return frame(COMMIT_HEADER, {
    ops: write.ops,
    seq,
    rev: write.rev,
    since: write.since,
    prev: null,
    repo: write.signedCommit.did,
    time,
    blobs: [],
    blocks: carBytes,
    commit: write.commitCid,
    rebase: false,
    tooBig: false,
    prevData: write.prevData
  })
}

// #identity — tells a relay a repo's handle/DID binding (needed for discovery).
export function identityFrame ({ seq, did, handle, time }) {
  const body = { seq, did, time }
  if (handle) body.handle = handle
  return frame(IDENTITY_HEADER, body)
}

// #account — repo hosting status (active true = "this PDS hosts this repo").
export function accountFrame ({ seq, did, active = true, status, time }) {
  const body = { seq, did, time, active }
  if (status) body.status = status
  return frame(ACCOUNT_HEADER, body)
}

// #sync (Sync 1.1) — tells a relay to RE-BASELINE the repo to `signedCommit` (re-anchor via
// getRepo) instead of applying incremental deltas. This is the sanctioned signal for a repo
// whose commit chain is discontinuous vs the relay's last-known state (e.g. a custodial→
// self-custody migration that re-authored the repo). `blocks` is a CAR carrying ONLY the
// commit block (root = its CID), ≤10KB. `rev`/`did` MUST match the commit object.
export async function syncFrame ({ seq, did, signedCommit, time }) {
  const cid = commitCid(signedCommit)
  const blocks = await writeCar(cid, [{ cid, bytes: dagCbor.encode(signedCommit) }])
  return frame(SYNC_HEADER, { seq, did, blocks, rev: signedCommit.rev, time })
}

const HEADERS = [['#commit', COMMIT_HEADER], ['#identity', IDENTITY_HEADER], ['#account', ACCOUNT_HEADER], ['#sync', SYNC_HEADER]]

// Re-stamp a frame's `seq` (relay egress): a relay aggregates many PDS firehoses and MUST
// present its own monotonic seq in each frame (the cursor contract). Decodes, replaces
// body.seq, re-encodes with the same header. Unknown frames pass through unchanged.
export function restampFrame (frameBytes, seq) {
  const d = decodeFrame(frameBytes)
  if (!d) return frameBytes
  const header = d.t === '#commit' ? COMMIT_HEADER : d.t === '#identity' ? IDENTITY_HEADER : d.t === '#account' ? ACCOUNT_HEADER : SYNC_HEADER
  d.body.seq = seq
  const bodyBytes = dagCbor.encode(d.body)
  const out = new Uint8Array(header.length + bodyBytes.length)
  out.set(header, 0)
  out.set(bodyBytes, header.length)
  return out
}

// Split + decode ANY known subscribeRepos frame → { t, body } (null if unknown).
export function decodeFrame (frameBytes) {
  for (const [t, header] of HEADERS) {
    if (frameBytes.length >= header.length &&
        Buffer.from(frameBytes.subarray(0, header.length)).equals(Buffer.from(header))) {
      return { t, body: dagCbor.decode(frameBytes.subarray(header.length)) }
    }
  }
  return null
}

// Split + decode a #commit frame. Returns { header, body } or null if not a #commit.
export function decodeCommitFrame (frameBytes) {
  const prefix = frameBytes.subarray(0, COMMIT_HEADER.length)
  if (!Buffer.from(prefix).equals(Buffer.from(COMMIT_HEADER))) return null
  return {
    header: { t: '#commit', op: 1 },
    body: dagCbor.decode(frameBytes.subarray(COMMIT_HEADER.length))
  }
}
// RepoStore — the Holepunch-native home for an atproto repo.
//
// Records live in a CLASSIC Hyperbee (matches our production stack — NOT hyperbee2/
// autobee, which are experimental; see the ecosystem audit): key = `collection/rkey`,
// value = the record's canonical DAG-CBOR bytes. Single-writer (one author key);
// multi-device is handled by sharing the mnemonic-derived key. The atproto-repo
// module is the *bridge* that reads this store and emits MST/CAR/commits on demand —
// this layer stores nothing atproto-specific beyond the records themselves.

import Corestore from 'corestore'
import { isCorestore } from './corestore.js'
import Hyperbee from 'hyperbee'
import * as dagCbor from '@ipld/dag-cbor'
import b4a from 'b4a'

// Range upper bound for a `collection/` prefix scan. '/' (0x2f) + 1 = '0' (0x30),
// and all atproto rkey chars sort >= '2' > '/', so `collection/…` < `collection0`.
function prefixUpper (prefix) {
  return prefix.slice(0, -1) + String.fromCharCode(prefix.charCodeAt(prefix.length - 1) + 1)
}

export class RepoStore {
  constructor (storage, opts = {}) {
    // Behavioural check, NOT `instanceof` — a second copy of corestore in a bundled tree makes a real
    // store look like a path and Corestore then path.join()s an object. See lib/corestore.js.
    this._ownStore = !isCorestore(storage)
    this._store = this._ownStore ? new Corestore(storage) : storage
    this._name = opts.name || 'atproto-repo'
    this._key = opts.key || null // open a specific core by KEY (a replica of another instance's repo)
    this.bee = null
    this.core = null
  }

  static key (collection, rkey) { return `${collection}/${rkey}` }

  // The underlying Corestore — so the PDS can open sibling cores (e.g. the firehose
  // sequence log) on the SAME store rather than a second Corestore over the same dir.
  get corestore () { return this._store }

  async ready () {
    // By KEY = replicate another instance's repo (read-only over the swarm); by NAME = our own.
    this.core = this._key ? this._store.get({ key: this._key }) : this._store.get({ name: this._name })
    await this.core.ready()
    // alwaysDuplicate:false enables Hyperbee's byte-identical value-dedup — a re-put of an unchanged
    // (key,value) becomes a no-op READ instead of appending a fresh B-tree path. Without it (the default
    // TRUE), redundant puts (e.g. a projection re-putting the whole record set on a timer) balloon this
    // append-only core to millions of dead blocks. Defense-in-depth under every caller.
    this.bee = new Hyperbee(this.core, { keyEncoding: 'utf-8', valueEncoding: 'binary', alwaysDuplicate: false })
    await this.bee.ready()
    return this
  }

  async put (collection, rkey, record) {
    await this.bee.put(RepoStore.key(collection, rkey), b4a.from(dagCbor.encode(record)))
  }

  async get (collection, rkey) {
    const node = await this.bee.get(RepoStore.key(collection, rkey))
    return node ? dagCbor.decode(node.value) : null
  }

  // Raw stored bytes + decoded record (the bridge CIDs the exact bytes).
  async getRaw (collection, rkey) {
    const node = await this.bee.get(RepoStore.key(collection, rkey))
    return node ? { bytes: node.value, record: dagCbor.decode(node.value) } : null
  }

  async del (collection, rkey) {
    await this.bee.del(RepoStore.key(collection, rkey))
  }

  // Yield { rkey, record } for one collection, in key order.
  async * list (collection) {
    const gte = `${collection}/`
    const lt = prefixUpper(gte)
    for await (const node of this.bee.createReadStream({ gte, lt })) {
      yield { rkey: node.key.slice(gte.length), record: dagCbor.decode(node.value) }
    }
  }

  // All records as { key, bytes, record } in key order. `bytes` is the canonical
  // DAG-CBOR — the bridge CIDs these directly to build the MST (byte-exact).
  async records () {
    const out = []
    for await (const node of this.bee.createReadStream()) {
      out.push({ key: node.key, bytes: node.value, record: dagCbor.decode(node.value) })
    }
    return out
  }

  // Persist the commit head ({ rev, commitCid, dataCid }) as core USER DATA — NOT a record,
  // so it never appears in records()/the MST. This is what makes the head stable across a
  // restart: the rev is restored, not re-minted (which would forge a phantom commit).
  async saveHead (head) {
    await this.core.setUserData('atproto-head', b4a.from(JSON.stringify(head)))
  }

  async loadHead () {
    const v = await this.core.getUserData('atproto-head')
    return v ? JSON.parse(b4a.toString(v)) : null
  }

  async close () {
    if (this.bee) await this.bee.close()
    if (this._ownStore) await this._store.close()
  }
}
// FirehoseSequencer — the atproto firehose as a Hypercore.
//
// Each subscribeRepos message (a framed dag-cbor #commit/#identity/#account) is one
// append to a single-writer Hypercore; the block index + 1 IS the atproto `seq`
// (1-based, monotonic). `subscribe(cursor)` replays persisted frames with seq > cursor
// then live-tails — so a freshly-attached relay gets full history from cursor=0 (the
// fix for the non-archival-relay root cause, POSTMORTEM.md §Federation).
//
// This is both the atproto sequenced-firehose model and the P2P-native thesis: the
// firehose is not a side-channel, it's a replicable append-only log.

import { commitFrame, identityFrame, accountFrame } from './firehose.js'

export class FirehoseSequencer {
  constructor (core) { this.core = core } // a Hypercore, binary values

  async ready () { await this.core.ready(); return this }
  get length () { return this.core.length }        // == the latest seq
  async close () { await this.core.close() }

  // Append a pre-framed message; returns its 1-based seq.
  async append (frameBytes) {
    const seq = this.core.length + 1
    await this.core.append(frameBytes)
    return seq
  }

  // Sequence a #commit: assign the seq FIRST (frame body carries it), then append.
  async sequenceCommit (write, { time }) {
    const seq = this.core.length + 1
    const frame = await commitFrame(write, { seq, time })
    await this.core.append(frame)
    return { seq, frame }
  }

  async sequenceIdentity ({ did, handle, time }) {
    const seq = this.core.length + 1
    const frame = identityFrame({ seq, did, handle, time })
    await this.core.append(frame)
    return { seq, frame }
  }

  async sequenceAccount ({ did, active = true, status, time }) {
    const seq = this.core.length + 1
    const frame = accountFrame({ seq, did, active, status, time })
    await this.core.append(frame)
    return { seq, frame }
  }

  // Async iterator over { seq, bytes }: backfill frames with seq > cursor, then
  // live-tail new appends. cursor is the last seq the consumer holds (0/absent =
  // from the start). Pass an AbortSignal to stop (WS disconnect).
  async * subscribe (cursor = 0, { signal } = {}) {
    let next = Math.max(0, cursor | 0) // seq > cursor  <=>  index >= cursor
    while (true) {
      if (signal && signal.aborted) return
      if (next < this.core.length) {
        const bytes = await this.core.get(next)
        yield { seq: next + 1, bytes }
        next++
        continue
      }
      // caught up — wait for the next append (or abort)
      await new Promise((resolve) => {
        const onAppend = () => { cleanup(); resolve() }
        const onAbort = () => { cleanup(); resolve() }
        const cleanup = () => {
          this.core.off('append', onAppend)
          if (signal) signal.removeEventListener('abort', onAbort)
        }
        this.core.on('append', onAppend)
        if (signal) signal.addEventListener('abort', onAbort, { once: true })
      })
      if (signal && signal.aborted) return
    }
  }
}
const { Pull, Push, HEADERBYTES, KEYBYTES, ABYTES } = require('sodium-secretstream')
const sodium = require('sodium-universal')
const crypto = require('hypercore-crypto')
const { Duplex, Writable, getStreamError } = require('streamx')
const b4a = require('b4a')
const Timeout = require('timeout-refresh')
const unslab = require('unslab')
const Bridge = require('./lib/bridge')
const Handshake = require('./lib/handshake')

const IDHEADERBYTES = HEADERBYTES + 32
const [NS_INITIATOR, NS_RESPONDER, NS_SEND] = crypto.namespace('hyperswarm/secret-stream', 3)
const MAX_ATOMIC_WRITE = 256 * 256 * 256 - 1

module.exports = class NoiseSecretStream extends Duplex {
  constructor(isInitiator, rawStream, opts = {}) {
    super({ mapWritable: toBuffer })

    if (typeof isInitiator !== 'boolean') {
      throw new Error('isInitiator should be a boolean')
    }

    this.noiseStream = this
    this.isInitiator = isInitiator
    this.rawStream = null

    this.publicKey = opts.publicKey || null
    this.remotePublicKey = opts.remotePublicKey || null
    this.handshakeHash = null
    this.connected = false
    this.keepAlive = opts.keepAlive || 0
    this.timeout = 0
    this.enableSend = opts.enableSend !== false

    // pointer for upstream to set data here if they want
    this.userData = null

    let openedDone = null
    this.opened = new Promise((resolve) => {
      openedDone = resolve
    })

    this.rawBytesWritten = 0
    this.rawBytesRead = 0

    // metadata used by 'hyperdht'
    this.relay = null
    this.puncher = null

    // unwrapped raw stream
    this._rawStream = null

    // handshake state
    this._handshake = null
    this._handshakePattern = opts.pattern || null
    this._handshakeDone = null

    // message parsing state
    this._state = 0
    this._len = 0
    this._tmp = 1
    this._message = null

    this._openedDone = openedDone
    this._startDone = null
    this._drainDone = null
    this._outgoingPlain = null
    this._outgoingWrapped = null
    this._utp = null
    this._setup = true
    this._ended = 2
    this._encrypt = null
    this._decrypt = null
    this._timeoutTimer = null
    this._keepAliveTimer = null
    this._sendState = null

    if (opts.autoStart !== false) this.start(rawStream, opts)

    // wiggle it to trigger open immediately (TODO add streamx option for this)
    this.resume()
    this.pause()
  }

  static keyPair(seed) {
    return Handshake.keyPair(seed)
  }

  static id(handshakeHash, isInitiator, id) {
    return streamId(handshakeHash, isInitiator, id)
  }

  setTimeout(ms) {
    if (!ms) ms = 0

    this._clearTimeout()
    this.timeout = ms

    if (!ms || this.rawStream === null) return

    this._timeoutTimer = Timeout.once(ms, destroyTimeout, this)
    this._timeoutTimer.unref()
  }

  setKeepAlive(ms) {
    if (!ms) ms = 0

    this._clearKeepAlive()

    this.keepAlive = ms

    if (!ms || this.rawStream === null) return

    this._keepAliveTimer = Timeout.on(ms, sendKeepAlive, this)
    this._keepAliveTimer.unref()
  }

  sendKeepAlive() {
    const empty = this.alloc(0)
    this.write(empty)
  }

  start(rawStream, opts = {}) {
    if (rawStream) {
      this.rawStream = rawStream
      this._rawStream = rawStream
      if (typeof this.rawStream.setContentSize === 'function') {
        this._utp = rawStream
      }
    } else {
      this.rawStream = new Bridge(this)
      this._rawStream = this.rawStream.reverse
    }

    this.rawStream.on('error', this._onrawerror.bind(this))
    this.rawStream.on('close', this._onrawclose.bind(this))

    this._startHandshake(opts.handshake, opts.keyPair || null)
    this._continueOpen(null)

    if (this.destroying) return

    if (opts.data) this._onrawdata(opts.data)
    if (opts.ended) this._onrawend()

    if (this.keepAlive > 0 && this._keepAliveTimer === null) {
      this.setKeepAlive(this.keepAlive)
    }

    if (this.timeout > 0 && this._timeoutTimer === null) {
      this.setTimeout(this.timeout)
    }
  }

  async flush() {
    if ((await this.opened) === false) return false
    if ((await Writable.drained(this)) === false) return false
    if (this.destroying) return false

    if (this.rawStream !== null && this.rawStream.flush) {
      return await this.rawStream.flush()
    }

    return true
  }

  _continueOpen(err) {
    if (err) this.destroy(err)
    if (this._startDone === null) return
    const done = this._startDone
    this._startDone = null
    this._open(done)
  }

  _onkeypairpromise(p) {
    const self = this
    const cont = this._continueOpen.bind(this)

    p.then(onkeypair, cont)

    function onkeypair(kp) {
      self._onkeypair(kp)
      cont(null)
    }
  }

  _onkeypair(keyPair) {
    const pattern = this._handshakePattern || 'XX'
    const remotePublicKey = this.remotePublicKey

    this._handshake = new Handshake(this.isInitiator, keyPair, remotePublicKey, pattern)
    this.publicKey = this._handshake.keyPair.publicKey
  }

  _startHandshake(handshake, keyPair) {
    if (handshake) {
      const { tx, rx, hash, publicKey, remotePublicKey } = handshake
      this._setupSecretStream(tx, rx, hash, publicKey, remotePublicKey)
      return
    }

    if (!keyPair) keyPair = Handshake.keyPair()

    if (typeof keyPair.then === 'function') {
      this._onkeypairpromise(keyPair)
    } else {
      this._onkeypair(keyPair)
    }
  }

  _onrawerror(err) {
    this.destroy(err)
  }

  _onrawclose() {
    if (this._ended !== 0) this.destroy()
  }

  _onrawdata(data) {
    let offset = 0

    if (this._timeoutTimer !== null) {
      this._timeoutTimer.refresh()
    }

    do {
      switch (this._state) {
        case 0: {
          while (this._tmp !== 0x1000000 && offset < data.byteLength) {
            const v = data[offset++]
            this._len += this._tmp * v
            this._tmp *= 256
          }

          if (this._tmp === 0x1000000) {
            this._tmp = 0
            this._state = 1
            const unprocessed = data.byteLength - offset
            if (unprocessed < this._len && this._utp !== null)
              this._utp.setContentSize(this._len - unprocessed)
          }

          break
        }

        case 1: {
          const missing = this._len - this._tmp
          const end = missing + offset

          if (this._message === null && end <= data.byteLength) {
            this._message = data.subarray(offset, end)
            offset += missing
            this._incoming()
            break
          }

          const unprocessed = data.byteLength - offset

          if (this._message === null) {
            this._message = b4a.allocUnsafe(this._len)
          }

          b4a.copy(data, this._message, this._tmp, offset)
          this._tmp += unprocessed

          if (end <= data.byteLength) {
            offset += missing
            this._incoming()
          } else {
            offset += unprocessed
          }

          break
        }
      }
    } while (offset < data.byteLength && !this.destroying)
  }

  _onrawend() {
    this._ended--
    this.push(null)
  }

  _onrawdrain() {
    const drain = this._drainDone
    if (drain === null) return
    this._drainDone = null
    drain()
  }

  _read(cb) {
    this.rawStream.resume()
    cb(null)
  }

  _incoming() {
    const message = this._message

    this._state = 0
    this._len = 0
    this._tmp = 1
    this._message = null

    if (this._setup === true) {
      if (this._handshake) {
        this._onhandshakert(this._handshake.recv(message))
      } else {
        if (message.byteLength !== IDHEADERBYTES) {
          this.destroy(new Error('Invalid header message received'))
          return
        }

        const remoteId = message.subarray(0, 32)
        const expectedId = streamId(this.handshakeHash, !this.isInitiator)
        const header = message.subarray(32)

        if (!b4a.equals(expectedId, remoteId)) {
          this.destroy(new Error('Invalid header received'))
          return
        }

        this._decrypt.init(header)
        this._setup = false // setup is now done
      }
      return
    }

    if (message.byteLength < ABYTES) {
      this.destroy(new Error('Invalid message received'))
      return
    }

    this.rawBytesRead += message.byteLength

    const plain = message.subarray(1, message.byteLength - ABYTES + 1)

    try {
      this._decrypt.next(message, plain)
    } catch (err) {
      this.destroy(err)
      return
    }

    // If keep alive is selective, eat the empty buffers (ie assume the other side has it enabled also)
    if (plain.byteLength === 0 && this.keepAlive !== 0) return

    if (this.push(plain) === false) {
      this.rawStream.pause()
    }
  }

  _onhandshakert(h) {
    if (this._handshakeDone === null) return

    if (h !== null) {
      if (h.data) this._rawStream.write(h.data)
      if (!h.tx) return
    }

    const done = this._handshakeDone
    const publicKey = this._handshake.keyPair.publicKey

    this._handshakeDone = null
    this._handshake = null

    if (h === null) return done(new Error('Noise handshake failed'))

    this._setupSecretStream(h.tx, h.rx, h.hash, publicKey, h.remotePublicKey)
    this._resolveOpened(true)
    done(null)
  }

  _setupSecretStream(tx, rx, handshakeHash, publicKey, remotePublicKey) {
    const buf = b4a.allocUnsafeSlow(3 + IDHEADERBYTES)
    writeUint24le(IDHEADERBYTES, buf)

    this._encrypt = new Push(unslab(tx.subarray(0, KEYBYTES)), undefined, buf.subarray(3 + 32))
    this._decrypt = new Pull(unslab(rx.subarray(0, KEYBYTES)))

    this.publicKey = publicKey
    this.remotePublicKey = remotePublicKey
    this.handshakeHash = handshakeHash

    const id = buf.subarray(3, 3 + 32)
    streamId(handshakeHash, this.isInitiator, id)

    // initialize secretbox state for unordered messages
    this._setupSecretSend(handshakeHash)

    this.emit('handshake')
    // if rawStream is a bridge, also emit it there
    if (this.rawStream !== this._rawStream) this.rawStream.emit('handshake')

    if (this.destroying) return

    this._rawStream.write(buf)
  }

  _setupSecretSend(handshakeHash) {
    this._sendState = b4a.allocUnsafeSlow(32 + 32 + 8 + 8)
    const encrypt = this._sendState.subarray(0, 32) // secrets
    const decrypt = this._sendState.subarray(32, 64)
    const counter = this._sendState.subarray(64, 72) // nonce
    const initial = this._sendState.subarray(72)

    const inputs = this.isInitiator
      ? [
          [NS_INITIATOR, NS_SEND],
          [NS_RESPONDER, NS_SEND]
        ]
      : [
          [NS_RESPONDER, NS_SEND],
          [NS_INITIATOR, NS_SEND]
        ]

    sodium.crypto_generichash_batch(encrypt, inputs[0], handshakeHash)
    sodium.crypto_generichash_batch(decrypt, inputs[1], handshakeHash)

    sodium.randombytes_buf(initial)
    counter.set(initial)
  }

  _open(cb) {
    // no autostart or no handshake yet
    if (this._rawStream === null || (this._handshake === null && this._encrypt === null)) {
      this._startDone = cb
      return
    }

    this._rawStream.on('data', this._onrawdata.bind(this))
    this._rawStream.on('end', this._onrawend.bind(this))
    this._rawStream.on('drain', this._onrawdrain.bind(this))

    if (this.enableSend) this._rawStream.on('message', this._onmessage.bind(this))

    if (this._encrypt !== null) {
      this._resolveOpened(true)
      return cb(null)
    }

    this._handshakeDone = cb

    if (this.isInitiator) this._onhandshakert(this._handshake.send())
  }

  _predestroy() {
    if (this.rawStream) {
      const error = getStreamError(this)
      this.rawStream.destroy(error)
    }

    if (this._startDone !== null) {
      const done = this._startDone
      this._startDone = null
      done(new Error('Stream destroyed'))
    }

    if (this._handshakeDone !== null) {
      const done = this._handshakeDone
      this._handshakeDone = null
      done(new Error('Stream destroyed'))
    }

    if (this._drainDone !== null) {
      const done = this._drainDone
      this._drainDone = null
      done(new Error('Stream destroyed'))
    }
  }

  _write(data, cb) {
    let wrapped = this._outgoingWrapped

    if (data !== this._outgoingPlain) {
      wrapped = b4a.allocUnsafe(data.byteLength + 3 + ABYTES)
      wrapped.set(data, 4)
    } else {
      this._outgoingWrapped = this._outgoingPlain = null
    }

    if (wrapped.byteLength - 3 > MAX_ATOMIC_WRITE) {
      return cb(
        new Error(
          'Message is too large for an atomic write. Max size is ' + MAX_ATOMIC_WRITE + ' bytes.'
        )
      )
    }
    this.rawBytesWritten += wrapped.byteLength

    writeUint24le(wrapped.byteLength - 3, wrapped)
    // offset 4 so we can do it in-place
    this._encrypt.next(wrapped.subarray(4, 4 + data.byteLength), wrapped.subarray(3))

    if (this._keepAliveTimer !== null) this._keepAliveTimer.refresh()

    if (this._rawStream.write(wrapped) === false) {
      this._drainDone = cb
    } else {
      cb(null)
    }
  }

  _final(cb) {
    this._clearKeepAlive()
    this._ended--
    this._rawStream.end()
    cb(null)
  }

  _resolveOpened(val) {
    if (this._openedDone === null) return
    const opened = this._openedDone
    this._openedDone = null
    opened(val)
    if (!val) return
    this.connected = true
    this.emit('connect')
  }

  _clearTimeout() {
    if (this._timeoutTimer === null) return
    this._timeoutTimer.destroy()
    this._timeoutTimer = null
    this.timeout = 0
  }

  _clearKeepAlive() {
    if (this._keepAliveTimer === null) return
    this._keepAliveTimer.destroy()
    this._keepAliveTimer = null
    this.keepAlive = 0
  }

  _destroy(cb) {
    this._clearKeepAlive()
    this._clearTimeout()
    this._resolveOpened(false)
    cb(null)
  }

  _boxMessage(buffer) {
    const MB = sodium.crypto_secretbox_MACBYTES // 16
    const NB = sodium.crypto_secretbox_NONCEBYTES // 24

    const counter = this._sendState.subarray(64, 72)
    sodium.sodium_increment(counter)
    if (b4a.equals(counter, this._sendState.subarray(72))) {
      this.destroy(new Error('udp send nonce exchausted'))
      return
    }

    const secret = this._sendState.subarray(0, 32)
    const envelope = b4a.allocUnsafe(8 + MB + buffer.byteLength)
    const nonce = envelope.subarray(0, NB)
    const ciphertext = envelope.subarray(8)

    b4a.fill(nonce, 0) // pad suffix
    nonce.set(counter)

    sodium.crypto_secretbox_easy(ciphertext, buffer, nonce, secret)
    return envelope
  }

  send(buffer) {
    if (!this._sendState) return
    if (!this.rawStream?.send) return // udx-stream expected

    const message = this._boxMessage(buffer)
    return this.rawStream.send(message)
  }

  trySend(buffer) {
    if (!this._sendState) return
    if (!this.rawStream?.trySend) return // udx-stream expected

    const message = this._boxMessage(buffer)
    this.rawStream.trySend(message)
  }

  _onmessage(buffer) {
    if (!this._sendState) return // messages before handshake are dropped

    const MB = sodium.crypto_secretbox_MACBYTES // 16
    const NB = sodium.crypto_secretbox_NONCEBYTES // 24

    if (buffer.byteLength < NB) return // Invalid message

    const nonce = b4a.allocUnsafe(NB)
    b4a.fill(nonce, 0)
    nonce.set(buffer.subarray(0, 8))

    const secret = this._sendState.subarray(32, 64)
    const ciphertext = buffer.subarray(8)
    const plain = buffer.subarray(8, buffer.byteLength - MB)

    if (ciphertext.byteLength < MB) return // invalid message

    const success = sodium.crypto_secretbox_open_easy(plain, ciphertext, nonce, secret)

    if (success) this.emit('message', plain)
  }

  alloc(len) {
    const buf = b4a.allocUnsafe(len + 3 + ABYTES)
    this._outgoingWrapped = buf
    this._outgoingPlain = buf.subarray(4, buf.byteLength - ABYTES + 1)
    return this._outgoingPlain
  }

  toJSON() {
    return {
      isInitiator: this.isInitiator,
      publicKey: this.publicKey && b4a.toString(this.publicKey, 'hex'),
      remotePublicKey: this.remotePublicKey && b4a.toString(this.remotePublicKey, 'hex'),
      connected: this.connected,
      destroying: this.destroying,
      destroyed: this.destroyed,
      rawStream: this.rawStream && this.rawStream.toJSON ? this.rawStream.toJSON() : null
    }
  }
}

function writeUint24le(n, buf) {
  buf[0] = n & 255
  buf[1] = (n >>> 8) & 255
  buf[2] = (n >>> 16) & 255
}

function streamId(handshakeHash, isInitiator, out = b4a.allocUnsafe(32)) {
  sodium.crypto_generichash(out, isInitiator ? NS_INITIATOR : NS_RESPONDER, handshakeHash)
  return out
}

function toBuffer(data) {
  return typeof data === 'string' ? b4a.from(data) : data
}

function destroyTimeout() {
  this.destroy(new Error('Stream timed out'))
}

function sendKeepAlive() {
  const empty = this.alloc(0)
  this.write(empty)
}
const { Duplex, Writable } = require('streamx')

class ReversePassThrough extends Duplex {
  constructor(s) {
    super()
    this._stream = s
    this._ondrain = null
  }

  _write(data, cb) {
    if (this._stream.push(data) === false) {
      this._stream._ondrain = cb
    } else {
      cb(null)
    }
  }

  _final(cb) {
    this._stream.push(null)
    cb(null)
  }

  _read(cb) {
    const ondrain = this._ondrain
    this._ondrain = null
    if (ondrain) ondrain()
    cb(null)
  }
}

module.exports = class Bridge extends Duplex {
  constructor(noiseStream) {
    super()

    this.noiseStream = noiseStream

    this._ondrain = null
    this.reverse = new ReversePassThrough(this)
  }

  get publicKey() {
    return this.noiseStream.publicKey
  }

  get remotePublicKey() {
    return this.noiseStream.remotePublicKey
  }

  get handshakeHash() {
    return this.noiseStream.handshakeHash
  }

  flush() {
    return Writable.drained(this)
  }

  _read(cb) {
    const ondrain = this._ondrain
    this._ondrain = null
    if (ondrain) ondrain()
    cb(null)
  }

  _write(data, cb) {
    if (this.reverse.push(data) === false) {
      this.reverse._ondrain = cb
    } else {
      cb(null)
    }
  }

  _final(cb) {
    this.reverse.push(null)
    cb(null)
  }
}
const sodium = require('sodium-universal')
const curve = require('noise-curve-ed')
const Noise = require('noise-handshake')
const b4a = require('b4a')

const EMPTY = b4a.alloc(0)

module.exports = class Handshake {
  constructor(isInitiator, keyPair, remotePublicKey, pattern) {
    this.isInitiator = isInitiator
    this.keyPair = keyPair
    this.noise = new Noise(pattern, isInitiator, keyPair, { curve })
    this.noise.initialise(EMPTY, remotePublicKey)
    this.destroyed = false
  }

  static keyPair(seed) {
    const publicKey = b4a.alloc(32)
    const secretKey = b4a.alloc(64)
    if (seed) sodium.crypto_sign_seed_keypair(publicKey, secretKey, seed)
    else sodium.crypto_sign_keypair(publicKey, secretKey)
    return { publicKey, secretKey }
  }

  recv(data) {
    try {
      this.noise.recv(data)
      if (this.noise.complete) return this._return(null)
      return this.send()
    } catch {
      this.destroy()
      return null
    }
  }

  // note that the data returned here is framed so we don't have to do an extra copy
  // when sending it...
  send() {
    try {
      const data = this.noise.send()
      const wrap = b4a.allocUnsafe(data.byteLength + 3)

      writeUint24le(data.byteLength, wrap)
      wrap.set(data, 3)

      return this._return(wrap)
    } catch {
      this.destroy()
      return null
    }
  }

  destroy() {
    if (this.destroyed) return
    this.destroyed = true
  }

  _return(data) {
    const tx = this.noise.complete ? b4a.toBuffer(this.noise.tx) : null
    const rx = this.noise.complete ? b4a.toBuffer(this.noise.rx) : null
    const hash = this.noise.complete ? b4a.toBuffer(this.noise.hash) : null
    const remotePublicKey = this.noise.complete ? b4a.toBuffer(this.noise.rs) : null

    return {
      data,
      remotePublicKey,
      hash,
      tx,
      rx
    }
  }
}

function writeUint24le(n, buf) {
  buf[0] = n & 255
  buf[1] = (n >>> 8) & 255
  buf[2] = (n >>> 16) & 255
}
{
  "name": "@hyperswarm/secret-stream",
  "version": "6.9.1",
  "description": "Secret stream backed by Noise and libsodium's secretstream",
  "main": "index.js",
  "files": [
    "index.js",
    "lib/**.js"
  ],
  "dependencies": {
    "b4a": "^1.1.0",
    "hypercore-crypto": "^3.3.1",
    "noise-curve-ed": "^2.0.1",
    "noise-handshake": "^4.0.0",
    "sodium-secretstream": "^1.1.0",
    "sodium-universal": "^5.0.0",
    "streamx": "^2.14.0",
    "timeout-refresh": "^2.0.0",
    "unslab": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "udx-native": "^1.13.2"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check .",
    "test": "brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/hyperswarm-secret-stream.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/hyperswarm-secret-stream/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperswarm-secret-stream"
}
{
  "name": "@ipld/dag-cbor",
  "version": "9.2.7",
  "description": "JS implementation of DAG-CBOR",
  "author": "Rod <rod@vagg.org> (http://r.va.gg/)",
  "license": "Apache-2.0 OR MIT",
  "homepage": "https://github.com/ipld/js-dag-cbor#readme",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/ipld/js-dag-cbor.git"
  },
  "bugs": {
    "url": "https://github.com/ipld/js-dag-cbor/issues"
  },
  "publishConfig": {
    "access": "public",
    "provenance": true
  },
  "keywords": [
    "ipfs",
    "ipld",
    "multiformats"
  ],
  "type": "module",
  "types": "./dist/src/index.d.ts",
  "typesVersions": {
    "*": {
      "*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ],
      "src/*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ]
    }
  },
  "files": [
    "src",
    "dist",
    "!dist/test",
    "!**/*.tsbuildinfo"
  ],
  "exports": {
    ".": {
      "types": "./dist/src/index.d.ts",
      "import": "./src/index.js",
      "module-sync": "./src/index.js"
    }
  },
  "release": {
    "branches": [
      "master"
    ],
    "plugins": [
      [
        "@semantic-release/commit-analyzer",
        {
          "preset": "conventionalcommits",
          "releaseRules": [
            {
              "breaking": true,
              "release": "major"
            },
            {
              "revert": true,
              "release": "patch"
            },
            {
              "type": "feat",
              "release": "minor"
            },
            {
              "type": "fix",
              "release": "patch"
            },
            {
              "type": "docs",
              "release": "patch"
            },
            {
              "type": "test",
              "release": "patch"
            },
            {
              "type": "deps",
              "release": "patch"
            },
            {
              "scope": "no-release",
              "release": false
            }
          ]
        }
      ],
      [
        "@semantic-release/release-notes-generator",
        {
          "preset": "conventionalcommits",
          "presetConfig": {
            "types": [
              {
                "type": "feat",
                "section": "Features"
              },
              {
                "type": "fix",
                "section": "Bug Fixes"
              },
              {
                "type": "chore",
                "section": "Trivial Changes"
              },
              {
                "type": "docs",
                "section": "Documentation"
              },
              {
                "type": "deps",
                "section": "Dependencies"
              },
              {
                "type": "test",
                "section": "Tests"
              }
            ]
          }
        }
      ],
      "@semantic-release/changelog",
      "@semantic-release/npm",
      "@semantic-release/github",
      [
        "@semantic-release/git",
        {
          "assets": [
            "CHANGELOG.md",
            "package.json"
          ]
        }
      ]
    ]
  },
  "scripts": {
    "clean": "aegir clean",
    "lint": "aegir lint",
    "build": "aegir build",
    "release": "aegir release",
    "test": "npm run lint && aegir test",
    "test:ts": "npm run test --prefix test/ts-use",
    "test:node": "aegir test -t node --cov",
    "test:chrome": "aegir test -t browser --cov",
    "test:chrome-webworker": "aegir test -t webworker",
    "test:firefox": "aegir test -t browser -- --browser firefox",
    "test:firefox-webworker": "aegir test -t webworker -- --browser firefox",
    "test:electron-main": "aegir test -t electron-main",
    "dep-check": "aegir dep-check"
  },
  "dependencies": {
    "cborg": "^5.0.1",
    "multiformats": "^13.1.0"
  },
  "devDependencies": {
    "@ipld/garbage": "^6.0.0",
    "aegir": "^48.0.1"
  }
}
import * as cborg from 'cborg'
import { CID } from 'multiformats/cid'

// https://github.com/ipfs/go-ipfs/issues/3570#issuecomment-273931692
const CID_CBOR_TAG = 42

/**
 * @template T
 * @typedef {import('multiformats/codecs/interface').ByteView<T>} ByteView
 */

/**
 * @template T
 * @typedef {import('multiformats/codecs/interface').ArrayBufferView<T>} ArrayBufferView
 */

/**
 * @template T
 * @param {ByteView<T> | ArrayBufferView<T>} buf
 * @returns {ByteView<T>}
 */
export function toByteView (buf) {
  if (buf instanceof ArrayBuffer) {
    return new Uint8Array(buf, 0, buf.byteLength)
  }

  return buf
}

/**
 * cidEncoder will receive all Objects during encode, it needs to filter out
 * anything that's not a CID and return `null` for that so it's encoded as
 * normal.
 *
 * @param {any} obj
 * @returns {cborg.Token[]|null}
 */
function cidEncoder (obj) {
  if (obj.asCID !== obj && obj['/'] !== obj.bytes) {
    return null // any other kind of object
  }
  const cid = CID.asCID(obj)
  /* c8 ignore next 4 */
  // very unlikely case, and it'll probably throw a recursion error in cborg
  if (!cid) {
    return null
  }
  const bytes = new Uint8Array(cid.bytes.byteLength + 1)
  bytes.set(cid.bytes, 1) // prefix is 0x00, for historical reasons
  return [
    new cborg.Token(cborg.Type.tag, CID_CBOR_TAG),
    new cborg.Token(cborg.Type.bytes, bytes)
  ]
}

// eslint-disable-next-line jsdoc/require-returns-check
/**
 * Intercept all `undefined` values from an object walk and reject the entire
 * object if we find one.
 *
 * @returns {null}
 */
function undefinedEncoder () {
  throw new Error('`undefined` is not supported by the IPLD Data Model and cannot be encoded')
}

/**
 * Intercept all `number` values from an object walk and reject the entire
 * object if we find something that doesn't fit the IPLD data model (NaN &
 * Infinity).
 *
 * @param {number} num
 * @returns {null}
 */
function numberEncoder (num) {
  if (Number.isNaN(num)) {
    throw new Error('`NaN` is not supported by the IPLD Data Model and cannot be encoded')
  }
  if (num === Infinity || num === -Infinity) {
    throw new Error('`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded')
  }
  return null
}

/**
 * @param {Map<any, any>} map
 * @returns {null}
 */
function mapEncoder (map) {
  for (const key of map.keys()) {
    if (typeof key !== 'string' || key.length === 0) {
      throw new Error('Non-string Map keys are not supported by the IPLD Data Model and cannot be encoded')
    }
  }
  return null
}

const _encodeOptions = {
  float64: true,
  typeEncoders: {
    Map: mapEncoder,
    Object: cidEncoder,
    undefined: undefinedEncoder,
    number: numberEncoder
  }
}

export const encodeOptions = {
  ..._encodeOptions,
  typeEncoders: {
    ..._encodeOptions.typeEncoders
  }
}

/**
 * @param {import('cborg').TagDecodeControl} decode
 * @returns {CID}
 */
function cidDecoder (decode) {
  const bytes = /** @type {Uint8Array} */ (decode())
  if (bytes[0] !== 0) {
    throw new Error('Invalid CID for CBOR tag 42; expected leading 0x00')
  }
  return CID.decode(bytes.subarray(1)) // ignore leading 0x00
}

const _decodeOptions = {
  allowIndefinite: false,
  coerceUndefinedToNull: true,
  allowNaN: false,
  allowInfinity: false,
  allowBigInt: true, // this will lead to BigInt for ints outside of
  // safe-integer range, which may surprise users
  strict: true,
  useMaps: false,
  rejectDuplicateMapKeys: true,
  /** @type {{ [tagNumber: number]: import('cborg').TagDecoder }} */
  tags: { [CID_CBOR_TAG]: cidDecoder }
}

export const decodeOptions = {
  ..._decodeOptions,
  tags: { ..._decodeOptions.tags }
}

export const name = 'dag-cbor'
export const code = 0x71

/**
 * @template T
 * @param {T} node
 * @returns {ByteView<T>}
 */
export const encode = (node) => cborg.encode(node, _encodeOptions)

/**
 * @template T
 * @param {ByteView<T> | ArrayBufferView<T>} data
 * @returns {T}
 */
export const decode = (data) => cborg.decode(toByteView(data), _decodeOptions)
// Minimal CAR v1 codec — bare-safe, dependency-light replacement for @ipld/car.
//
// CAR v1 is a trivial container: varint(headerLen) ++ dag-cbor({version:1, roots:[…]})
// then, per block, varint(len) ++ CIDbytes ++ blockBytes. We only need whole-buffer
// read/write (no streaming, no file I/O), so this is ~40 lines of pure JS over
// multiformats' CID (byte-exact with @ipld/car — verified by the repo tests + the
// @atproto/repo conformance reader). Drops @ipld/car (which imports `fs`/streams and
// won't load under Bare).
//
// ⚠️ LIMITATIONS vs @ipld/car (tracked in memory: bare-car-limitations). Fine for our
// current use (whole-buffer, CARv1, OUR-OWN trusted output); add the feature before the
// gate it guards:
//   - No streaming — whole CAR is buffered in memory. GATE: large repos (getRepo of a
//     big repo could be GBs). Add an async-iterator read/write path.
//   - No untrusted-input hardening — readCar trusts varints/lengths/CIDs. GATE: reading
//     UNTRUSTED CARs (com.atproto.repo.importRepo, ingress bridge). Add bounds/overflow/
//     truncation checks + duplicate-CID handling before then.
//   - CARv1 only (no CARv2/index). atproto is CARv1, so no gate today.
// Fully-featured path: grow this file at each gate, OR extract a standalone bare-native
// `bare-car` package (the holepunch ecosystem lacks one — a real contribution).

import { CID } from 'multiformats/cid'
import * as dagCbor from '@ipld/dag-cbor'

function varintEncode (n) {
  const out = []
  while (n >= 0x80) { out.push((n & 0x7f) | 0x80); n >>>= 7 }
  out.push(n)
  return Uint8Array.from(out)
}

function varintDecode (bytes, offset) {
  let n = 0; let shift = 0; let i = offset
  for (;;) {
    const b = bytes[i++]
    n |= (b & 0x7f) << shift
    if ((b & 0x80) === 0) break
    shift += 7
  }
  return [n >>> 0, i]
}

// Serialise { root, blocks } to CAR bytes. `blocks` is an iterable of { cid, bytes }.
export async function writeCar (rootCid, blocks) {
  const header = dagCbor.encode({ version: 1, roots: [rootCid] })
  const parts = [Buffer.from(varintEncode(header.length)), Buffer.from(header)]
  for (const { cid, bytes } of blocks) {
    const cidBytes = cid.bytes
    const body = new Uint8Array(cidBytes.length + bytes.length)
    body.set(cidBytes, 0)
    body.set(bytes, cidBytes.length)
    parts.push(Buffer.from(varintEncode(body.length)), Buffer.from(body))
  }
  return Buffer.concat(parts)
}

// Read a CAR into { roots, blocks } where blocks maps cid-string -> { cid, bytes }.
export async function readCar (carBytes) {
  const bytes = carBytes instanceof Uint8Array ? carBytes : new Uint8Array(carBytes)
  let [hlen, off] = varintDecode(bytes, 0)
  const header = dagCbor.decode(bytes.subarray(off, off + hlen))
  off += hlen
  const blocks = new Map()
  while (off < bytes.length) {
    const [blen, bodyStart] = varintDecode(bytes, off)
    const end = bodyStart + blen
    const [cid, rest] = CID.decodeFirst(bytes.subarray(bodyStart, end))
    blocks.set(cid.toString(), { cid, bytes: rest })
    off = end
  }
  return { roots: header.roots, blocks }
}
// atproto block CIDs — CIDv1, dag-cbor codec (0x71), sha2-256 multihash (0x12).
// Every block in a repo (commit, MST node, record) is content-addressed this way,
// so computeCid(dag-cbor(block)) IS the block's identity. This is the anchor for
// byte-exact fidelity: if our re-encoded bytes hash to the same CID the reference
// produced, our encoding is byte-identical.

import { CID } from 'multiformats/cid'
import * as Digest from 'multiformats/hashes/digest'
import { sha256 as nobleSha256 } from '@noble/hashes/sha2'
import * as dagCbor from '@ipld/dag-cbor'
import * as raw from 'multiformats/codecs/raw'

// raw block bytes -> CID. Uses noble's pure-JS sha256 (same as the sync path) rather
// than multiformats' `crypto.subtle` path — identical CID, and no WebCrypto dependency
// (so it loads + runs under Bare, which has no crypto.subtle).
export async function cidForBytes (bytes) {
  return cidForBytesSync(bytes)
}

// Synchronous variant — needed by the recursive MST build. Same result as
// cidForBytes (CIDv1 / dag-cbor 0x71 / sha2-256 0x12), just without the async
// WebCrypto digest.
export function cidForBytesSync (bytes) {
  const digest = Digest.create(0x12, nobleSha256(bytes)) // 0x12 = sha2-256 multihash code
  return CID.createV1(dagCbor.code, digest)
}

// BLOB CID — CIDv1, RAW codec (0x55), sha2-256. atproto blobs (images/avatars) are
// content-addressed with the raw codec (opaque bytes), NOT dag-cbor. This is the CID that
// goes in a blob ref ({$type:'blob', ref:{$link:<this>}, mimeType, size}) and the key
// com.atproto.sync.getBlob serves by.
export function cidForBlobSync (bytes) {
  const digest = Digest.create(0x12, nobleSha256(bytes))
  return CID.createV1(raw.code, digest)
}

// a JS value -> its canonical dag-cbor bytes + CID
export async function cidForValue (value) {
  const bytes = dagCbor.encode(value)
  return { bytes, cid: await cidForBytes(bytes) }
}
// atproto repo commit — sign + verify.
//
// A commit is { did, version: 3, data: <MST root CID>, rev, prev, sig }. The
// signature is ECDSA-secp256k1 (low-S) over sha256(dag-cbor(unsignedCommit)), stored
// as a raw 64-byte CBOR byte string (NOT base64url — that's the did:plc genesis).
// The relay validates this sig against the DID doc's verificationMethod.

import * as dagCbor from '@ipld/dag-cbor'
import { sha256 as nobleSha256 } from '@noble/hashes/sha2'
import { secp256k1 } from '@noble/curves/secp256k1'
import { cidForBytesSync } from './cid.js'

export const REPO_VERSION = 3

// The unsigned commit (everything the signature covers).
export function unsignedCommit ({ did, rev, data, prev = null }) {
  return { did, version: REPO_VERSION, data, rev, prev }
}

// Sign an unsigned commit -> signed commit with `sig` (64 raw bytes).
export function signCommit (unsigned, privateKey) {
  const hash = nobleSha256(dagCbor.encode(unsigned))
  const sig = secp256k1.sign(hash, privateKey, { lowS: true }).toCompactRawBytes()
  return { ...unsigned, sig }
}

export function commitCid (signedCommit) {
  return cidForBytesSync(dagCbor.encode(signedCommit))
}

// Verify a signed commit against a compressed secp256k1 pubkey (33 bytes).
export function verifyCommit (signedCommit, publicKey) {
  const { sig, ...unsigned } = signedCommit
  const hash = nobleSha256(dagCbor.encode(unsigned))
  return secp256k1.verify(sig, hash, publicKey, { lowS: true })
}
// atproto MST — WRITE path (slice 2).
//
// A faithful port of millipds's `atmst` (mst/node.py + node_wrangler.py) — the exact
// code that produced our golden CAR. Byte-exactness is verified two ways: rebuilding
// the golden repo's MST, and matching atmst's own root CIDs for a multi-height tree
// (build + delete oracles). See test/mst-write.test.js.
//
// Node shape (interleaved): subtrees[0], (keys[0],vals[0]), subtrees[1], … ,subtrees[n].
// key layer = leading-zero BITS of sha256(key), // 2 (fanout 4).

import * as dagCbor from '@ipld/dag-cbor'
import { sha256 as nobleSha256 } from '@noble/hashes/sha2'
import { cidForBytesSync } from './cid.js'

const cidEq = (a, b) => (a === null || b === null) ? a === b : a.equals(b)
const replaceAt = (arr, i, v) => { const c = arr.slice(); c[i] = v; return c }
const insertAt = (arr, i, v) => arr.slice(0, i).concat([v], arr.slice(i))
const removeAt = (arr, i) => arr.slice(0, i).concat(arr.slice(i + 1))

export function keyHeight (key) {
  const h = nobleSha256(Buffer.from(key, 'utf8')) // 32 bytes
  let zeros = 0
  for (const byte of h) {
    if (byte === 0) { zeros += 8; continue }
    zeros += Math.clz32(byte) - 24 // leading zero bits within this byte
    break
  }
  return zeros >> 1 // // 2
}

export class MSTNode {
  constructor (keys, vals, subtrees) {
    this.keys = keys // [string]
    this.vals = vals // [CID]
    this.subtrees = subtrees // [CID|null], length keys.length + 1
  }

  static empty () { return new MSTNode([], [], [null]) }

  isEmpty () { return this.keys.length === 0 && this.subtrees.length === 1 && this.subtrees[0] === null }

  serialise () {
    const e = []
    let prevKey = Buffer.alloc(0)
    for (let i = 0; i < this.keys.length; i++) {
      const keyBytes = Buffer.from(this.keys[i], 'utf8')
      const max = Math.min(prevKey.length, keyBytes.length)
      let p = 0
      while (p < max && prevKey[p] === keyBytes[p]) p++
      e.push({ k: keyBytes.subarray(p), p, t: this.subtrees[i + 1], v: this.vals[i] })
      prevKey = keyBytes
    }
    return dagCbor.encode({ e, l: this.subtrees[0] }) // dag-cbor canonicalises map key order
  }

  cid () { return cidForBytesSync(this.serialise()) }

  toOptional () { return this.isEmpty() ? null : this.cid() }

  gteIndex (key) { let i = 0; while (i < this.keys.length && key > this.keys[i]) i++; return i }

  height () {
    if (this.keys.length) return keyHeight(this.keys[0])
    if (this.subtrees[0] === null) return 0
    return null // indeterminate (empty intermediate node)
  }

  static deserialise (bytes) {
    const cbor = dagCbor.decode(bytes)
    const subtrees = [cbor.l]
    const keys = []
    const vals = []
    let prevKey = Buffer.alloc(0)
    for (const e of cbor.e) {
      const suffix = Buffer.from(e.k)
      const thisKey = Buffer.concat([prevKey.subarray(0, e.p), suffix])
      keys.push(thisKey.toString('utf8'))
      vals.push(e.v)
      subtrees.push(e.t)
      prevKey = thisKey
    }
    return new MSTNode(keys, vals, subtrees)
  }
}

// In-memory node store — maps CID string -> { cid, bytes }. get(null) returns the
// (stored) empty node, matching atmst NodeStore.get_node(None).
export class NodeStore {
  constructor () { this.blocks = new Map() }

  storedNode (node) {
    const bytes = node.serialise()
    const cid = cidForBytesSync(bytes)
    this.blocks.set(cid.toString(), { cid, bytes })
    return node
  }

  getNode (cid) {
    if (cid === null || cid === undefined) return this.storedNode(MSTNode.empty())
    const b = this.blocks.get(cid.toString())
    if (!b) throw new Error(`missing MST node ${cid}`)
    return MSTNode.deserialise(b.bytes)
  }
}

export class NodeWrangler {
  constructor (ns) { this.ns = ns }

  putRecord (rootCid, key, val) {
    const root = this.ns.getNode(rootCid)
    if (root.isEmpty()) return this._putHere(root, key, val).cid()
    return this._putRecursive(root, key, val, keyHeight(key), root.height()).cid()
  }

  delRecord (rootCid, key) {
    const root = this.ns.getNode(rootCid)
    const afterDel = this._deleteRecursive(root, key, keyHeight(key), root.height())
    return this.ns.getNode(this._squashTop(afterDel)).cid()
  }

  _putHere (node, key, val) {
    const i = node.gteIndex(key)
    if (i < node.keys.length && node.keys[i] === key) {
      if (cidEq(node.vals[i], val)) return node
      return this.ns.storedNode(new MSTNode(node.keys.slice(), replaceAt(node.vals, i, val), node.subtrees.slice()))
    }
    const [lsub, rsub] = this._splitOnKey(node.subtrees[i], key)
    return this.ns.storedNode(new MSTNode(
      insertAt(node.keys, i, key),
      insertAt(node.vals, i, val),
      node.subtrees.slice(0, i).concat([lsub, rsub], node.subtrees.slice(i + 1))
    ))
  }

  _putRecursive (node, key, val, keyH, treeH) {
    if (keyH > treeH) { // grow the tree upward
      return this.ns.storedNode(this._putRecursive(
        this.ns.storedNode(new MSTNode([], [], [node.cid()])),
        key, val, keyH, treeH + 1
      ))
    }
    if (keyH < treeH) { // descend
      const i = node.gteIndex(key)
      return this.ns.storedNode(new MSTNode(
        node.keys.slice(), node.vals.slice(),
        replaceAt(node.subtrees, i, this._putRecursive(this.ns.getNode(node.subtrees[i]), key, val, keyH, treeH - 1).cid())
      ))
    }
    return this._putHere(node, key, val) // keyH === treeH
  }

  _splitOnKey (nodeCid, key) {
    if (nodeCid === null || nodeCid === undefined) return [null, null]
    const node = this.ns.getNode(nodeCid)
    const i = node.gteIndex(key)
    const [lsub, rsub] = this._splitOnKey(node.subtrees[i], key)
    const left = this.ns.storedNode(new MSTNode(node.keys.slice(0, i), node.vals.slice(0, i), node.subtrees.slice(0, i).concat([lsub]))).toOptional()
    const right = this.ns.storedNode(new MSTNode(node.keys.slice(i), node.vals.slice(i), [rsub].concat(node.subtrees.slice(i + 1)))).toOptional()
    return [left, right]
  }

  _squashTop (nodeCid) {
    const node = this.ns.getNode(nodeCid)
    if (node.keys.length) return nodeCid
    if (node.subtrees[0] === null) return nodeCid
    return this._squashTop(node.subtrees[0])
  }

  _deleteRecursive (node, key, keyH, treeH) {
    if (keyH > treeH) return node.toOptional()
    let i = node.gteIndex(key)
    if (keyH < treeH) {
      if (node.subtrees[i] === null) return node.toOptional()
      return this.ns.storedNode(new MSTNode(
        node.keys.slice(), node.vals.slice(),
        replaceAt(node.subtrees, i, this._deleteRecursive(this.ns.getNode(node.subtrees[i]), key, keyH, treeH - 1))
      )).toOptional()
    }
    i = node.gteIndex(key)
    if (i === node.keys.length || node.keys[i] !== key) return node.toOptional()
    return this.ns.storedNode(new MSTNode(
      removeAt(node.keys, i), removeAt(node.vals, i),
      node.subtrees.slice(0, i).concat([this._merge(node.subtrees[i], node.subtrees[i + 1])], node.subtrees.slice(i + 2))
    )).toOptional()
  }

  _merge (leftCid, rightCid) {
    if (leftCid === null) return rightCid
    if (rightCid === null) return leftCid
    const left = this.ns.getNode(leftCid)
    const right = this.ns.getNode(rightCid)
    return this.ns.storedNode(new MSTNode(
      left.keys.concat(right.keys), left.vals.concat(right.vals),
      left.subtrees.slice(0, -1).concat([this._merge(left.subtrees[left.subtrees.length - 1], right.subtrees[0])], right.subtrees.slice(1))
    )).toOptional()
  }
}

// Build an MST from records [{ key, value: CID }] (any order). Returns
// { root: CID, ns: NodeStore }. ns.blocks holds every node created; use
// reachableBlocks(ns, root) for just the live set (CAR output).
export function buildMst (records) {
  const ns = new NodeStore()
  const w = new NodeWrangler(ns)
  let root = ns.storedNode(MSTNode.empty()).cid()
  for (const { key, value } of records) root = w.putRecord(root, key, value)
  return { root, ns, wrangler: w }
}

// BFS the live MST nodes reachable from root (for CAR block sets).
export function reachableBlocks (ns, rootCid) {
  const out = new Map()
  const stack = [rootCid]
  while (stack.length) {
    const cid = stack.pop()
    if (cid === null || cid === undefined) continue
    const key = cid.toString()
    if (out.has(key)) continue
    const b = ns.blocks.get(key)
    if (!b) throw new Error(`missing node ${key}`)
    out.set(key, b)
    const node = MSTNode.deserialise(b.bytes)
    for (const t of node.subtrees) if (t) stack.push(t)
  }
  return out
}

// ---- Firehose MST-inversion proof (slice 3b) ----
//
// A #commit's `blocks` CAR must be a MINIMAL, self-contained proof of the
// old→new transition — not the whole tree (that would trip a relay's `tooBig`).
// This ports millipds `repo_ops.py:apply_writes` step 2b + `atmst` proof.py:
//   blocks = created | deletion_proof_cids | inductive_proof_nodes  (+ new records)
// where `inductive_proof_nodes` = every MST node READ while replaying the ops
// backward from the new root, which must reproduce the old (prevData) root.
// The prior record CIDs travel in each op's `prev` (like millipds), so a cold
// relay can invert with no old-tree state of its own.

// A NodeStore overlay: writes land in an in-memory upper layer (NOT logged);
// reads that fall through to `lower` are recorded in `.gets`. Mirrors millipds's
// OverlayBlockStore(MemoryBlockStore, LoggingBlockStoreWrapper(bs)).
export class OverlayNodeStore {
  constructor (lower) { this.lower = lower; this.upper = new Map(); this.gets = new Set() }

  storedNode (node) {
    const bytes = node.serialise()
    const cid = cidForBytesSync(bytes)
    this.upper.set(cid.toString(), { cid, bytes })
    return node
  }

  getNode (cid) {
    if (cid === null || cid === undefined) return MSTNode.empty()
    const k = cid.toString()
    const u = this.upper.get(k)
    if (u) return MSTNode.deserialise(u.bytes)
    this.gets.add(k) // a read of a pre-existing node — part of the inductive proof
    return this.lower.getNode(cid)
  }
}

// Follow the search path for `key` from `rootCid`, collecting every node visited.
// Returns { value: CID|null, proof: Set<cidStr> }. value===null ⇒ exclusion proof;
// value!==null ⇒ inclusion proof. Port of atmst find_rpath_and_build_proof.
export function findRpathProof (ns, rootCid, key) {
  const proof = new Set()
  let cid = rootCid
  while (cid !== null && cid !== undefined) {
    const node = ns.getNode(cid)
    proof.add(cid.toString())
    const i = node.gteIndex(key)
    if (i < node.keys.length && node.keys[i] === key) return { value: node.vals[i], proof }
    cid = node.subtrees[i] // descend the subtree left of the first key >= target
  }
  return { value: null, proof }
}

// Build a NodeStore holding exactly the given blocks (cid-string -> { cid, bytes }).
export function nodeStoreFromBlocks (blocks) {
  const ns = new NodeStore()
  for (const [k, v] of blocks) ns.blocks.set(k, v)
  return ns
}

// Compute the minimal firehose block set for a single commit's ops.
//   oldRecords / newRecords : [{ key, value: CID }] — the record sets BEFORE/AFTER.
//   ops : [{ action:'create'|'update'|'delete', path, cid: CID|null, prev: CID|null }]
// Returns { blocks: Map<cidStr,{cid,bytes}>, dataCid, oldRoot } — MST nodes only
// (record + commit blocks are added by the caller). Throws if the backward replay
// does not reproduce the old root (i.e. the proof would be invalid).
export function firehoseProofBlocks ({ oldRecords, newRecords, ops }) {
  const oldB = buildMst(oldRecords)
  const newB = buildMst(newRecords)
  const oldRoot = oldB.root
  const newRoot = newB.root

  const oldSet = reachableBlocks(oldB.ns, oldRoot)
  const newSet = reachableBlocks(newB.ns, newRoot)

  // combined store holds every node of BOTH trees (proof reads span both)
  const combined = new NodeStore()
  for (const [k, v] of oldSet) combined.blocks.set(k, v)
  for (const [k, v] of newSet) combined.blocks.set(k, v)

  const proofCids = new Set()

  // created: new-tree nodes not present in the old tree
  for (const k of newSet.keys()) if (!oldSet.has(k)) proofCids.add(k)

  // deletion proofs: for each delete, the exclusion-proof path in the NEW tree
  for (const op of ops) {
    if (op.action !== 'delete') continue
    const { value, proof } = findRpathProof(combined, newRoot, op.path)
    if (value !== null) throw new Error(`delete proof: ${op.path} still present in new tree`)
    for (const c of proof) proofCids.add(c)
  }

  // inductive proof: replay ops backward from newRoot; every node read is required.
  const overlay = new OverlayNodeStore(combined)
  const w = new NodeWrangler(overlay)
  let inv = newRoot
  for (let i = ops.length - 1; i >= 0; i--) {
    const op = ops[i]
    if (op.action === 'create') {
      inv = w.delRecord(inv, op.path)
    } else { // update | delete → restore the prior value
      if (op.prev === null || op.prev === undefined) throw new Error(`inversion: ${op.action} ${op.path} missing prev`)
      inv = w.putRecord(inv, op.path, op.prev)
    }
  }
  if (!inv.equals(oldRoot)) throw new Error('inversion proof failed: backward replay did not reproduce prevData root')
  for (const k of overlay.gets) proofCids.add(k)

  const blocks = new Map()
  for (const k of proofCids) blocks.set(k, combined.blocks.get(k))
  return { blocks, dataCid: newRoot, oldRoot }
}
// atproto repo — READ path (slice 1).
//
// A repo is a CAR whose root is a signed commit; the commit's `data` CID points at
// the root of a Merkle Search Tree (MST) of records. This module reads a CAR, walks
// the MST, and — most importantly — VERIFIES byte-exact fidelity by re-encoding every
// block and checking its CID. Writing/mutating the MST is slice 2.

import * as dagCbor from '@ipld/dag-cbor'
import { cidForBytes, cidForBytesSync } from './cid.js'
import { buildMst, reachableBlocks } from './mst.js'
import { unsignedCommit, signCommit, commitCid } from './commit.js'
import { readCar, writeCar } from './car.js'

// CAR read/write moved to the bare-safe minimal codec in ./car.js (was @ipld/car).
export { readCar, writeCar }

export function getBlock (car, cid) {
  const b = car.blocks.get(cid.toString())
  if (!b) throw new Error(`missing block ${cid}`)
  return b
}

export function decodeBlock (car, cid) {
  return dagCbor.decode(getBlock(car, cid).bytes)
}

// The signed commit at the CAR root.
export function loadCommit (car) {
  if (car.roots.length !== 1) throw new Error(`expected 1 root, got ${car.roots.length}`)
  const commit = decodeBlock(car, car.roots[0])
  if (!commit || !commit.did || commit.data === undefined) throw new Error('root is not a commit')
  return { cid: car.roots[0], value: commit }
}

// Walk the MST in key order, yielding { key, value: recordCid }. MST node shape:
//   { l: CID|null, e: [ { p: int, k: bytes, v: CID, t: CID|null } ] }
// keys are prefix-compressed against the previous key in the SAME node.
export function * walkMst (car, rootCid, _prevKey = '') {
  const node = decodeBlock(car, rootCid)
  if (!node || !Array.isArray(node.e)) throw new Error(`not an MST node: ${rootCid}`)
  if (node.l) yield * walkMst(car, node.l)
  let prev = ''
  for (const e of node.e) {
    const suffix = Buffer.from(e.k).toString('utf8')
    const key = prev.slice(0, e.p) + suffix
    prev = key
    yield { key, value: e.v }
    if (e.t) yield * walkMst(car, e.t)
  }
}

// All records as { key, cid, value } in key order.
export function listRecords (car) {
  const commit = loadCommit(car)
  const out = []
  for (const { key, value } of walkMst(car, commit.value.data)) {
    out.push({ key, cid: value, value: decodeBlock(car, value) })
  }
  return out
}

// Byte-exact fidelity check: re-encode every block and confirm its CID is unchanged.
// Also confirms the commit's data CID and every MST value CID resolve to a present
// block. Returns { blocks, records, ok, mismatches }.
export async function verifyRepo (car) {
  const mismatches = []
  for (const [cidStr, { cid, bytes }] of car.blocks) {
    // re-encode: decode then canonical-encode; must reproduce the exact bytes + CID
    const reencoded = dagCbor.encode(dagCbor.decode(bytes))
    const sameBytes = Buffer.from(reencoded).equals(Buffer.from(bytes))
    const recomputed = await cidForBytes(reencoded)
    if (!sameBytes || !recomputed.equals(cid)) {
      mismatches.push({ cid: cidStr, sameBytes, recomputed: recomputed.toString() })
    }
  }
  const commit = loadCommit(car)
  getBlock(car, commit.value.data) // MST root must be present
  const records = listRecords(car)
  for (const r of records) getBlock(car, r.cid) // each record block present
  return { blocks: car.blocks.size, records: records.length, ok: mismatches.length === 0, mismatches }
}

// ---- WRITE path (slice 3) ----

// Originate a full atproto repo from records. Each record is
// { collection, rkey, record } (or { key, value }). Returns the CAR bytes plus the
// commit/data CIDs. `privateKey` is the atproto secp256k1 signing key.
export async function createRepo ({ records, did, rev, privateKey }) {
  const recordBlocks = new Map()
  const mstRecords = []
  for (const r of records) {
    const key = r.key !== undefined ? r.key : `${r.collection}/${r.rkey}`
    const value = r.record !== undefined ? r.record : r.value
    const bytes = dagCbor.encode(value)
    const cid = cidForBytesSync(bytes)
    recordBlocks.set(cid.toString(), { cid, bytes })
    mstRecords.push({ key, value: cid })
  }
  const { root: dataCid, ns } = buildMst(mstRecords)
  const mstBlocks = reachableBlocks(ns, dataCid)

  const signed = signCommit(unsignedCommit({ did, rev, data: dataCid }), privateKey)
  const cCid = commitCid(signed)
  const commitBytes = dagCbor.encode(signed)

  const blocks = [{ cid: cCid, bytes: commitBytes }, ...mstBlocks.values(), ...recordBlocks.values()]
  const carBytes = await writeCar(cCid, blocks)
  return { carBytes, commitCid: cCid, dataCid, signedCommit: signed }
}
{
  "name": "@ipld/dag-cbor",
  "version": "9.2.7",
  "description": "JS implementation of DAG-CBOR",
  "author": "Rod <rod@vagg.org> (http://r.va.gg/)",
  "license": "Apache-2.0 OR MIT",
  "homepage": "https://github.com/ipld/js-dag-cbor#readme",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/ipld/js-dag-cbor.git"
  },
  "bugs": {
    "url": "https://github.com/ipld/js-dag-cbor/issues"
  },
  "publishConfig": {
    "access": "public",
    "provenance": true
  },
  "keywords": [
    "ipfs",
    "ipld",
    "multiformats"
  ],
  "type": "module",
  "types": "./dist/src/index.d.ts",
  "typesVersions": {
    "*": {
      "*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ],
      "src/*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ]
    }
  },
  "files": [
    "src",
    "dist",
    "!dist/test",
    "!**/*.tsbuildinfo"
  ],
  "exports": {
    ".": {
      "types": "./dist/src/index.d.ts",
      "import": "./src/index.js",
      "module-sync": "./src/index.js"
    }
  },
  "release": {
    "branches": [
      "master"
    ],
    "plugins": [
      [
        "@semantic-release/commit-analyzer",
        {
          "preset": "conventionalcommits",
          "releaseRules": [
            {
              "breaking": true,
              "release": "major"
            },
            {
              "revert": true,
              "release": "patch"
            },
            {
              "type": "feat",
              "release": "minor"
            },
            {
              "type": "fix",
              "release": "patch"
            },
            {
              "type": "docs",
              "release": "patch"
            },
            {
              "type": "test",
              "release": "patch"
            },
            {
              "type": "deps",
              "release": "patch"
            },
            {
              "scope": "no-release",
              "release": false
            }
          ]
        }
      ],
      [
        "@semantic-release/release-notes-generator",
        {
          "preset": "conventionalcommits",
          "presetConfig": {
            "types": [
              {
                "type": "feat",
                "section": "Features"
              },
              {
                "type": "fix",
                "section": "Bug Fixes"
              },
              {
                "type": "chore",
                "section": "Trivial Changes"
              },
              {
                "type": "docs",
                "section": "Documentation"
              },
              {
                "type": "deps",
                "section": "Dependencies"
              },
              {
                "type": "test",
                "section": "Tests"
              }
            ]
          }
        }
      ],
      "@semantic-release/changelog",
      "@semantic-release/npm",
      "@semantic-release/github",
      [
        "@semantic-release/git",
        {
          "assets": [
            "CHANGELOG.md",
            "package.json"
          ]
        }
      ]
    ]
  },
  "scripts": {
    "clean": "aegir clean",
    "lint": "aegir lint",
    "build": "aegir build",
    "release": "aegir release",
    "test": "npm run lint && aegir test",
    "test:ts": "npm run test --prefix test/ts-use",
    "test:node": "aegir test -t node --cov",
    "test:chrome": "aegir test -t browser --cov",
    "test:chrome-webworker": "aegir test -t webworker",
    "test:firefox": "aegir test -t browser -- --browser firefox",
    "test:firefox-webworker": "aegir test -t webworker -- --browser firefox",
    "test:electron-main": "aegir test -t electron-main",
    "dep-check": "aegir dep-check"
  },
  "dependencies": {
    "cborg": "^5.0.1",
    "multiformats": "^13.1.0"
  },
  "devDependencies": {
    "@ipld/garbage": "^6.0.0",
    "aegir": "^48.0.1"
  }
}
import * as cborg from 'cborg'
import { CID } from 'multiformats/cid'

// https://github.com/ipfs/go-ipfs/issues/3570#issuecomment-273931692
const CID_CBOR_TAG = 42

/**
 * @template T
 * @typedef {import('multiformats/codecs/interface').ByteView<T>} ByteView
 */

/**
 * @template T
 * @typedef {import('multiformats/codecs/interface').ArrayBufferView<T>} ArrayBufferView
 */

/**
 * @template T
 * @param {ByteView<T> | ArrayBufferView<T>} buf
 * @returns {ByteView<T>}
 */
export function toByteView (buf) {
  if (buf instanceof ArrayBuffer) {
    return new Uint8Array(buf, 0, buf.byteLength)
  }

  return buf
}

/**
 * cidEncoder will receive all Objects during encode, it needs to filter out
 * anything that's not a CID and return `null` for that so it's encoded as
 * normal.
 *
 * @param {any} obj
 * @returns {cborg.Token[]|null}
 */
function cidEncoder (obj) {
  if (obj.asCID !== obj && obj['/'] !== obj.bytes) {
    return null // any other kind of object
  }
  const cid = CID.asCID(obj)
  /* c8 ignore next 4 */
  // very unlikely case, and it'll probably throw a recursion error in cborg
  if (!cid) {
    return null
  }
  const bytes = new Uint8Array(cid.bytes.byteLength + 1)
  bytes.set(cid.bytes, 1) // prefix is 0x00, for historical reasons
  return [
    new cborg.Token(cborg.Type.tag, CID_CBOR_TAG),
    new cborg.Token(cborg.Type.bytes, bytes)
  ]
}

// eslint-disable-next-line jsdoc/require-returns-check
/**
 * Intercept all `undefined` values from an object walk and reject the entire
 * object if we find one.
 *
 * @returns {null}
 */
function undefinedEncoder () {
  throw new Error('`undefined` is not supported by the IPLD Data Model and cannot be encoded')
}

/**
 * Intercept all `number` values from an object walk and reject the entire
 * object if we find something that doesn't fit the IPLD data model (NaN &
 * Infinity).
 *
 * @param {number} num
 * @returns {null}
 */
function numberEncoder (num) {
  if (Number.isNaN(num)) {
    throw new Error('`NaN` is not supported by the IPLD Data Model and cannot be encoded')
  }
  if (num === Infinity || num === -Infinity) {
    throw new Error('`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded')
  }
  return null
}

/**
 * @param {Map<any, any>} map
 * @returns {null}
 */
function mapEncoder (map) {
  for (const key of map.keys()) {
    if (typeof key !== 'string' || key.length === 0) {
      throw new Error('Non-string Map keys are not supported by the IPLD Data Model and cannot be encoded')
    }
  }
  return null
}

const _encodeOptions = {
  float64: true,
  typeEncoders: {
    Map: mapEncoder,
    Object: cidEncoder,
    undefined: undefinedEncoder,
    number: numberEncoder
  }
}

export const encodeOptions = {
  ..._encodeOptions,
  typeEncoders: {
    ..._encodeOptions.typeEncoders
  }
}

/**
 * @param {import('cborg').TagDecodeControl} decode
 * @returns {CID}
 */
function cidDecoder (decode) {
  const bytes = /** @type {Uint8Array} */ (decode())
  if (bytes[0] !== 0) {
    throw new Error('Invalid CID for CBOR tag 42; expected leading 0x00')
  }
  return CID.decode(bytes.subarray(1)) // ignore leading 0x00
}

const _decodeOptions = {
  allowIndefinite: false,
  coerceUndefinedToNull: true,
  allowNaN: false,
  allowInfinity: false,
  allowBigInt: true, // this will lead to BigInt for ints outside of
  // safe-integer range, which may surprise users
  strict: true,
  useMaps: false,
  rejectDuplicateMapKeys: true,
  /** @type {{ [tagNumber: number]: import('cborg').TagDecoder }} */
  tags: { [CID_CBOR_TAG]: cidDecoder }
}

export const decodeOptions = {
  ..._decodeOptions,
  tags: { ..._decodeOptions.tags }
}

export const name = 'dag-cbor'
export const code = 0x71

/**
 * @template T
 * @param {T} node
 * @returns {ByteView<T>}
 */
export const encode = (node) => cborg.encode(node, _encodeOptions)

/**
 * @template T
 * @param {ByteView<T> | ArrayBufferView<T>} data
 * @returns {T}
 */
export const decode = (data) => cborg.decode(toByteView(data), _decodeOptions)
/**
 * Utilities for short weierstrass curves, combined with noble-hashes.
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { weierstrass } from "./abstract/weierstrass.js";
/** connects noble-curves to noble-hashes */
export function getHash(hash) {
    return { hash };
}
/** @deprecated use new `weierstrass()` and `ecdsa()` methods */
export function createCurve(curveDef, defHash) {
    const create = (hash) => weierstrass({ ...curveDef, hash: hash });
    return { ...create(defHash), create };
}
//# sourceMappingURL=_shortw_utils.js.map/**
 * Methods for elliptic curve multiplication by scalars.
 * Contains wNAF, pippenger.
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { bitLen, bitMask, validateObject } from "../utils.js";
import { Field, FpInvertBatch, nLength, validateField } from "./modular.js";
const _0n = BigInt(0);
const _1n = BigInt(1);
export function negateCt(condition, item) {
    const neg = item.negate();
    return condition ? neg : item;
}
/**
 * Takes a bunch of Projective Points but executes only one
 * inversion on all of them. Inversion is very slow operation,
 * so this improves performance massively.
 * Optimization: converts a list of projective points to a list of identical points with Z=1.
 */
export function normalizeZ(c, points) {
    const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
    return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
}
function validateW(W, bits) {
    if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
        throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);
}
function calcWOpts(W, scalarBits) {
    validateW(W, scalarBits);
    const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero
    const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero
    const maxNumber = 2 ** W; // W=8 256
    const mask = bitMask(W); // W=8 255 == mask 0b11111111
    const shiftBy = BigInt(W); // W=8 8
    return { windows, windowSize, mask, maxNumber, shiftBy };
}
function calcOffsets(n, window, wOpts) {
    const { windowSize, mask, maxNumber, shiftBy } = wOpts;
    let wbits = Number(n & mask); // extract W bits.
    let nextN = n >> shiftBy; // shift number by W bits.
    // What actually happens here:
    // const highestBit = Number(mask ^ (mask >> 1n));
    // let wbits2 = wbits - 1; // skip zero
    // if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);
    // split if bits > max: +224 => 256-32
    if (wbits > windowSize) {
        // we skip zero, which means instead of `>= size-1`, we do `> size`
        wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.
        nextN += _1n; // +256 (carry)
    }
    const offsetStart = window * windowSize;
    const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero
    const isZero = wbits === 0; // is current window slice a 0?
    const isNeg = wbits < 0; // is current window slice negative?
    const isNegF = window % 2 !== 0; // fake random statement for noise
    const offsetF = offsetStart; // fake offset for noise
    return { nextN, offset, isZero, isNeg, isNegF, offsetF };
}
function validateMSMPoints(points, c) {
    if (!Array.isArray(points))
        throw new Error('array expected');
    points.forEach((p, i) => {
        if (!(p instanceof c))
            throw new Error('invalid point at index ' + i);
    });
}
function validateMSMScalars(scalars, field) {
    if (!Array.isArray(scalars))
        throw new Error('array of scalars expected');
    scalars.forEach((s, i) => {
        if (!field.isValid(s))
            throw new Error('invalid scalar at index ' + i);
    });
}
// Since points in different groups cannot be equal (different object constructor),
// we can have single place to store precomputes.
// Allows to make points frozen / immutable.
const pointPrecomputes = new WeakMap();
const pointWindowSizes = new WeakMap();
function getW(P) {
    // To disable precomputes:
    // return 1;
    return pointWindowSizes.get(P) || 1;
}
function assert0(n) {
    if (n !== _0n)
        throw new Error('invalid wNAF');
}
/**
 * Elliptic curve multiplication of Point by scalar. Fragile.
 * Table generation takes **30MB of ram and 10ms on high-end CPU**,
 * but may take much longer on slow devices. Actual generation will happen on
 * first call of `multiply()`. By default, `BASE` point is precomputed.
 *
 * Scalars should always be less than curve order: this should be checked inside of a curve itself.
 * Creates precomputation tables for fast multiplication:
 * - private scalar is split by fixed size windows of W bits
 * - every window point is collected from window's table & added to accumulator
 * - since windows are different, same point inside tables won't be accessed more than once per calc
 * - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)
 * - +1 window is neccessary for wNAF
 * - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication
 *
 * @todo Research returning 2d JS array of windows, instead of a single window.
 * This would allow windows to be in different memory locations
 */
export class wNAF {
    // Parametrized with a given Point class (not individual point)
    constructor(Point, bits) {
        this.BASE = Point.BASE;
        this.ZERO = Point.ZERO;
        this.Fn = Point.Fn;
        this.bits = bits;
    }
    // non-const time multiplication ladder
    _unsafeLadder(elm, n, p = this.ZERO) {
        let d = elm;
        while (n > _0n) {
            if (n & _1n)
                p = p.add(d);
            d = d.double();
            n >>= _1n;
        }
        return p;
    }
    /**
     * Creates a wNAF precomputation window. Used for caching.
     * Default window size is set by `utils.precompute()` and is equal to 8.
     * Number of precomputed points depends on the curve size:
     * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
     * - 𝑊 is the window size
     * - 𝑛 is the bitlength of the curve order.
     * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
     * @param point Point instance
     * @param W window size
     * @returns precomputed point tables flattened to a single array
     */
    precomputeWindow(point, W) {
        const { windows, windowSize } = calcWOpts(W, this.bits);
        const points = [];
        let p = point;
        let base = p;
        for (let window = 0; window < windows; window++) {
            base = p;
            points.push(base);
            // i=1, bc we skip 0
            for (let i = 1; i < windowSize; i++) {
                base = base.add(p);
                points.push(base);
            }
            p = base.double();
        }
        return points;
    }
    /**
     * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
     * More compact implementation:
     * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
     * @returns real and fake (for const-time) points
     */
    wNAF(W, precomputes, n) {
        // Scalar should be smaller than field order
        if (!this.Fn.isValid(n))
            throw new Error('invalid scalar');
        // Accumulators
        let p = this.ZERO;
        let f = this.BASE;
        // This code was first written with assumption that 'f' and 'p' will never be infinity point:
        // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,
        // there is negate now: it is possible that negated element from low value
        // would be the same as high element, which will create carry into next window.
        // It's not obvious how this can fail, but still worth investigating later.
        const wo = calcWOpts(W, this.bits);
        for (let window = 0; window < wo.windows; window++) {
            // (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise
            const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
            n = nextN;
            if (isZero) {
                // bits are 0: add garbage to fake point
                // Important part for const-time getPublicKey: add random "noise" point to f.
                f = f.add(negateCt(isNegF, precomputes[offsetF]));
            }
            else {
                // bits are 1: add to result point
                p = p.add(negateCt(isNeg, precomputes[offset]));
            }
        }
        assert0(n);
        // Return both real and fake points: JIT won't eliminate f.
        // At this point there is a way to F be infinity-point even if p is not,
        // which makes it less const-time: around 1 bigint multiply.
        return { p, f };
    }
    /**
     * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
     * @param acc accumulator point to add result of multiplication
     * @returns point
     */
    wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
        const wo = calcWOpts(W, this.bits);
        for (let window = 0; window < wo.windows; window++) {
            if (n === _0n)
                break; // Early-exit, skip 0 value
            const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
            n = nextN;
            if (isZero) {
                // Window bits are 0: skip processing.
                // Move to next window.
                continue;
            }
            else {
                const item = precomputes[offset];
                acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM
            }
        }
        assert0(n);
        return acc;
    }
    getPrecomputes(W, point, transform) {
        // Calculate precomputes on a first run, reuse them after
        let comp = pointPrecomputes.get(point);
        if (!comp) {
            comp = this.precomputeWindow(point, W);
            if (W !== 1) {
                // Doing transform outside of if brings 15% perf hit
                if (typeof transform === 'function')
                    comp = transform(comp);
                pointPrecomputes.set(point, comp);
            }
        }
        return comp;
    }
    cached(point, scalar, transform) {
        const W = getW(point);
        return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
    }
    unsafe(point, scalar, transform, prev) {
        const W = getW(point);
        if (W === 1)
            return this._unsafeLadder(point, scalar, prev); // For W=1 ladder is ~x2 faster
        return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
    }
    // We calculate precomputes for elliptic curve point multiplication
    // using windowed method. This specifies window size and
    // stores precomputed values. Usually only base point would be precomputed.
    createCache(P, W) {
        validateW(W, this.bits);
        pointWindowSizes.set(P, W);
        pointPrecomputes.delete(P);
    }
    hasCache(elm) {
        return getW(elm) !== 1;
    }
}
/**
 * Endomorphism-specific multiplication for Koblitz curves.
 * Cost: 128 dbl, 0-256 adds.
 */
export function mulEndoUnsafe(Point, point, k1, k2) {
    let acc = point;
    let p1 = Point.ZERO;
    let p2 = Point.ZERO;
    while (k1 > _0n || k2 > _0n) {
        if (k1 & _1n)
            p1 = p1.add(acc);
        if (k2 & _1n)
            p2 = p2.add(acc);
        acc = acc.double();
        k1 >>= _1n;
        k2 >>= _1n;
    }
    return { p1, p2 };
}
/**
 * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).
 * 30x faster vs naive addition on L=4096, 10x faster than precomputes.
 * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.
 * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.
 * @param c Curve Point constructor
 * @param fieldN field over CURVE.N - important that it's not over CURVE.P
 * @param points array of L curve points
 * @param scalars array of L scalars (aka secret keys / bigints)
 */
export function pippenger(c, fieldN, points, scalars) {
    // If we split scalars by some window (let's say 8 bits), every chunk will only
    // take 256 buckets even if there are 4096 scalars, also re-uses double.
    // TODO:
    // - https://eprint.iacr.org/2024/750.pdf
    // - https://tches.iacr.org/index.php/TCHES/article/view/10287
    // 0 is accepted in scalars
    validateMSMPoints(points, c);
    validateMSMScalars(scalars, fieldN);
    const plength = points.length;
    const slength = scalars.length;
    if (plength !== slength)
        throw new Error('arrays of points and scalars must have equal length');
    // if (plength === 0) throw new Error('array must be of length >= 2');
    const zero = c.ZERO;
    const wbits = bitLen(BigInt(plength));
    let windowSize = 1; // bits
    if (wbits > 12)
        windowSize = wbits - 3;
    else if (wbits > 4)
        windowSize = wbits - 2;
    else if (wbits > 0)
        windowSize = 2;
    const MASK = bitMask(windowSize);
    const buckets = new Array(Number(MASK) + 1).fill(zero); // +1 for zero array
    const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;
    let sum = zero;
    for (let i = lastBits; i >= 0; i -= windowSize) {
        buckets.fill(zero);
        for (let j = 0; j < slength; j++) {
            const scalar = scalars[j];
            const wbits = Number((scalar >> BigInt(i)) & MASK);
            buckets[wbits] = buckets[wbits].add(points[j]);
        }
        let resI = zero; // not using this will do small speed-up, but will lose ct
        // Skip first bucket, because it is zero
        for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {
            sumI = sumI.add(buckets[j]);
            resI = resI.add(sumI);
        }
        sum = sum.add(resI);
        if (i !== 0)
            for (let j = 0; j < windowSize; j++)
                sum = sum.double();
    }
    return sum;
}
/**
 * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).
 * @param c Curve Point constructor
 * @param fieldN field over CURVE.N - important that it's not over CURVE.P
 * @param points array of L curve points
 * @returns function which multiplies points with scaars
 */
export function precomputeMSMUnsafe(c, fieldN, points, windowSize) {
    /**
     * Performance Analysis of Window-based Precomputation
     *
     * Base Case (256-bit scalar, 8-bit window):
     * - Standard precomputation requires:
     *   - 31 additions per scalar × 256 scalars = 7,936 ops
     *   - Plus 255 summary additions = 8,191 total ops
     *   Note: Summary additions can be optimized via accumulator
     *
     * Chunked Precomputation Analysis:
     * - Using 32 chunks requires:
     *   - 255 additions per chunk
     *   - 256 doublings
     *   - Total: (255 × 32) + 256 = 8,416 ops
     *
     * Memory Usage Comparison:
     * Window Size | Standard Points | Chunked Points
     * ------------|-----------------|---------------
     *     4-bit   |     520         |      15
     *     8-bit   |    4,224        |     255
     *    10-bit   |   13,824        |   1,023
     *    16-bit   |  557,056        |  65,535
     *
     * Key Advantages:
     * 1. Enables larger window sizes due to reduced memory overhead
     * 2. More efficient for smaller scalar counts:
     *    - 16 chunks: (16 × 255) + 256 = 4,336 ops
     *    - ~2x faster than standard 8,191 ops
     *
     * Limitations:
     * - Not suitable for plain precomputes (requires 256 constant doublings)
     * - Performance degrades with larger scalar counts:
     *   - Optimal for ~256 scalars
     *   - Less efficient for 4096+ scalars (Pippenger preferred)
     */
    validateW(windowSize, fieldN.BITS);
    validateMSMPoints(points, c);
    const zero = c.ZERO;
    const tableSize = 2 ** windowSize - 1; // table size (without zero)
    const chunks = Math.ceil(fieldN.BITS / windowSize); // chunks of item
    const MASK = bitMask(windowSize);
    const tables = points.map((p) => {
        const res = [];
        for (let i = 0, acc = p; i < tableSize; i++) {
            res.push(acc);
            acc = acc.add(p);
        }
        return res;
    });
    return (scalars) => {
        validateMSMScalars(scalars, fieldN);
        if (scalars.length > points.length)
            throw new Error('array of scalars must be smaller than array of points');
        let res = zero;
        for (let i = 0; i < chunks; i++) {
            // No need to double if accumulator is still zero.
            if (res !== zero)
                for (let j = 0; j < windowSize; j++)
                    res = res.double();
            const shiftBy = BigInt(chunks * windowSize - (i + 1) * windowSize);
            for (let j = 0; j < scalars.length; j++) {
                const n = scalars[j];
                const curr = Number((n >> shiftBy) & MASK);
                if (!curr)
                    continue; // skip zero scalars chunks
                res = res.add(tables[j][curr - 1]);
            }
        }
        return res;
    };
}
// TODO: remove
/** @deprecated */
export function validateBasic(curve) {
    validateField(curve.Fp);
    validateObject(curve, {
        n: 'bigint',
        h: 'bigint',
        Gx: 'field',
        Gy: 'field',
    }, {
        nBitLength: 'isSafeInteger',
        nByteLength: 'isSafeInteger',
    });
    // Set defaults
    return Object.freeze({
        ...nLength(curve.n, curve.nBitLength),
        ...curve,
        ...{ p: curve.Fp.ORDER },
    });
}
function createField(order, field, isLE) {
    if (field) {
        if (field.ORDER !== order)
            throw new Error('Field.ORDER must match order: Fp == p, Fn == n');
        validateField(field);
        return field;
    }
    else {
        return Field(order, { isLE });
    }
}
/** Validates CURVE opts and creates fields */
export function _createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
    if (FpFnLE === undefined)
        FpFnLE = type === 'edwards';
    if (!CURVE || typeof CURVE !== 'object')
        throw new Error(`expected valid ${type} CURVE object`);
    for (const p of ['p', 'n', 'h']) {
        const val = CURVE[p];
        if (!(typeof val === 'bigint' && val > _0n))
            throw new Error(`CURVE.${p} must be positive bigint`);
    }
    const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);
    const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
    const _b = type === 'weierstrass' ? 'b' : 'd';
    const params = ['Gx', 'Gy', 'a', _b];
    for (const p of params) {
        // @ts-ignore
        if (!Fp.isValid(CURVE[p]))
            throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
    }
    CURVE = Object.freeze(Object.assign({}, CURVE));
    return { CURVE, Fp, Fn };
}
//# sourceMappingURL=curve.js.mapimport { _validateObject, abytes, bytesToNumberBE, concatBytes, isBytes, isHash, utf8ToBytes, } from "../utils.js";
import { FpInvertBatch, mod } from "./modular.js";
// Octet Stream to Integer. "spec" implementation of os2ip is 2.5x slower vs bytesToNumberBE.
const os2ip = bytesToNumberBE;
// Integer to Octet Stream (numberToBytesBE)
function i2osp(value, length) {
    anum(value);
    anum(length);
    if (value < 0 || value >= 1 << (8 * length))
        throw new Error('invalid I2OSP input: ' + value);
    const res = Array.from({ length }).fill(0);
    for (let i = length - 1; i >= 0; i--) {
        res[i] = value & 0xff;
        value >>>= 8;
    }
    return new Uint8Array(res);
}
function strxor(a, b) {
    const arr = new Uint8Array(a.length);
    for (let i = 0; i < a.length; i++) {
        arr[i] = a[i] ^ b[i];
    }
    return arr;
}
function anum(item) {
    if (!Number.isSafeInteger(item))
        throw new Error('number expected');
}
function normDST(DST) {
    if (!isBytes(DST) && typeof DST !== 'string')
        throw new Error('DST must be Uint8Array or string');
    return typeof DST === 'string' ? utf8ToBytes(DST) : DST;
}
/**
 * Produces a uniformly random byte string using a cryptographic hash function H that outputs b bits.
 * [RFC 9380 5.3.1](https://www.rfc-editor.org/rfc/rfc9380#section-5.3.1).
 */
export function expand_message_xmd(msg, DST, lenInBytes, H) {
    abytes(msg);
    anum(lenInBytes);
    DST = normDST(DST);
    // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3
    if (DST.length > 255)
        DST = H(concatBytes(utf8ToBytes('H2C-OVERSIZE-DST-'), DST));
    const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H;
    const ell = Math.ceil(lenInBytes / b_in_bytes);
    if (lenInBytes > 65535 || ell > 255)
        throw new Error('expand_message_xmd: invalid lenInBytes');
    const DST_prime = concatBytes(DST, i2osp(DST.length, 1));
    const Z_pad = i2osp(0, r_in_bytes);
    const l_i_b_str = i2osp(lenInBytes, 2); // len_in_bytes_str
    const b = new Array(ell);
    const b_0 = H(concatBytes(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));
    b[0] = H(concatBytes(b_0, i2osp(1, 1), DST_prime));
    for (let i = 1; i <= ell; i++) {
        const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime];
        b[i] = H(concatBytes(...args));
    }
    const pseudo_random_bytes = concatBytes(...b);
    return pseudo_random_bytes.slice(0, lenInBytes);
}
/**
 * Produces a uniformly random byte string using an extendable-output function (XOF) H.
 * 1. The collision resistance of H MUST be at least k bits.
 * 2. H MUST be an XOF that has been proved indifferentiable from
 *    a random oracle under a reasonable cryptographic assumption.
 * [RFC 9380 5.3.2](https://www.rfc-editor.org/rfc/rfc9380#section-5.3.2).
 */
export function expand_message_xof(msg, DST, lenInBytes, k, H) {
    abytes(msg);
    anum(lenInBytes);
    DST = normDST(DST);
    // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3
    // DST = H('H2C-OVERSIZE-DST-' || a_very_long_DST, Math.ceil((lenInBytes * k) / 8));
    if (DST.length > 255) {
        const dkLen = Math.ceil((2 * k) / 8);
        DST = H.create({ dkLen }).update(utf8ToBytes('H2C-OVERSIZE-DST-')).update(DST).digest();
    }
    if (lenInBytes > 65535 || DST.length > 255)
        throw new Error('expand_message_xof: invalid lenInBytes');
    return (H.create({ dkLen: lenInBytes })
        .update(msg)
        .update(i2osp(lenInBytes, 2))
        // 2. DST_prime = DST || I2OSP(len(DST), 1)
        .update(DST)
        .update(i2osp(DST.length, 1))
        .digest());
}
/**
 * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F.
 * [RFC 9380 5.2](https://www.rfc-editor.org/rfc/rfc9380#section-5.2).
 * @param msg a byte string containing the message to hash
 * @param count the number of elements of F to output
 * @param options `{DST: string, p: bigint, m: number, k: number, expand: 'xmd' | 'xof', hash: H}`, see above
 * @returns [u_0, ..., u_(count - 1)], a list of field elements.
 */
export function hash_to_field(msg, count, options) {
    _validateObject(options, {
        p: 'bigint',
        m: 'number',
        k: 'number',
        hash: 'function',
    });
    const { p, k, m, hash, expand, DST } = options;
    if (!isHash(options.hash))
        throw new Error('expected valid hash');
    abytes(msg);
    anum(count);
    const log2p = p.toString(2).length;
    const L = Math.ceil((log2p + k) / 8); // section 5.1 of ietf draft link above
    const len_in_bytes = count * m * L;
    let prb; // pseudo_random_bytes
    if (expand === 'xmd') {
        prb = expand_message_xmd(msg, DST, len_in_bytes, hash);
    }
    else if (expand === 'xof') {
        prb = expand_message_xof(msg, DST, len_in_bytes, k, hash);
    }
    else if (expand === '_internal_pass') {
        // for internal tests only
        prb = msg;
    }
    else {
        throw new Error('expand must be "xmd" or "xof"');
    }
    const u = new Array(count);
    for (let i = 0; i < count; i++) {
        const e = new Array(m);
        for (let j = 0; j < m; j++) {
            const elm_offset = L * (j + i * m);
            const tv = prb.subarray(elm_offset, elm_offset + L);
            e[j] = mod(os2ip(tv), p);
        }
        u[i] = e;
    }
    return u;
}
export function isogenyMap(field, map) {
    // Make same order as in spec
    const coeff = map.map((i) => Array.from(i).reverse());
    return (x, y) => {
        const [xn, xd, yn, yd] = coeff.map((val) => val.reduce((acc, i) => field.add(field.mul(acc, x), i)));
        // 6.6.3
        // Exceptional cases of iso_map are inputs that cause the denominator of
        // either rational function to evaluate to zero; such cases MUST return
        // the identity point on E.
        const [xd_inv, yd_inv] = FpInvertBatch(field, [xd, yd], true);
        x = field.mul(xn, xd_inv); // xNum / xDen
        y = field.mul(y, field.mul(yn, yd_inv)); // y * (yNum / yDev)
        return { x, y };
    };
}
export const _DST_scalar = utf8ToBytes('HashToScalar-');
/** Creates hash-to-curve methods from EC Point and mapToCurve function. See {@link H2CHasher}. */
export function createHasher(Point, mapToCurve, defaults) {
    if (typeof mapToCurve !== 'function')
        throw new Error('mapToCurve() must be defined');
    function map(num) {
        return Point.fromAffine(mapToCurve(num));
    }
    function clear(initial) {
        const P = initial.clearCofactor();
        if (P.equals(Point.ZERO))
            return Point.ZERO; // zero will throw in assert
        P.assertValidity();
        return P;
    }
    return {
        defaults,
        hashToCurve(msg, options) {
            const opts = Object.assign({}, defaults, options);
            const u = hash_to_field(msg, 2, opts);
            const u0 = map(u[0]);
            const u1 = map(u[1]);
            return clear(u0.add(u1));
        },
        encodeToCurve(msg, options) {
            const optsDst = defaults.encodeDST ? { DST: defaults.encodeDST } : {};
            const opts = Object.assign({}, defaults, optsDst, options);
            const u = hash_to_field(msg, 1, opts);
            const u0 = map(u[0]);
            return clear(u0);
        },
        /** See {@link H2CHasher} */
        mapToCurve(scalars) {
            if (!Array.isArray(scalars))
                throw new Error('expected array of bigints');
            for (const i of scalars)
                if (typeof i !== 'bigint')
                    throw new Error('expected array of bigints');
            return clear(map(scalars));
        },
        // hash_to_scalar can produce 0: https://www.rfc-editor.org/errata/eid8393
        // RFC 9380, draft-irtf-cfrg-bbs-signatures-08
        hashToScalar(msg, options) {
            // @ts-ignore
            const N = Point.Fn.ORDER;
            const opts = Object.assign({}, defaults, { p: N, m: 1, DST: _DST_scalar }, options);
            return hash_to_field(msg, 1, opts)[0][0];
        },
    };
}
//# sourceMappingURL=hash-to-curve.js.map/**
 * Utils for modular division and fields.
 * Field over 11 is a finite (Galois) field is integer number operations `mod 11`.
 * There is no division: it is replaced by modular multiplicative inverse.
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { _validateObject, anumber, bitMask, bytesToNumberBE, bytesToNumberLE, ensureBytes, numberToBytesBE, numberToBytesLE, } from "../utils.js";
// prettier-ignore
const _0n = BigInt(0), _1n = BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3);
// prettier-ignore
const _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5), _7n = /* @__PURE__ */ BigInt(7);
// prettier-ignore
const _8n = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9), _16n = /* @__PURE__ */ BigInt(16);
// Calculates a modulo b
export function mod(a, b) {
    const result = a % b;
    return result >= _0n ? result : b + result;
}
/**
 * Efficiently raise num to power and do modular division.
 * Unsafe in some contexts: uses ladder, so can expose bigint bits.
 * @example
 * pow(2n, 6n, 11n) // 64n % 11n == 9n
 */
export function pow(num, power, modulo) {
    return FpPow(Field(modulo), num, power);
}
/** Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)` */
export function pow2(x, power, modulo) {
    let res = x;
    while (power-- > _0n) {
        res *= res;
        res %= modulo;
    }
    return res;
}
/**
 * Inverses number over modulo.
 * Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).
 */
export function invert(number, modulo) {
    if (number === _0n)
        throw new Error('invert: expected non-zero number');
    if (modulo <= _0n)
        throw new Error('invert: expected positive modulus, got ' + modulo);
    // Fermat's little theorem "CT-like" version inv(n) = n^(m-2) mod m is 30x slower.
    let a = mod(number, modulo);
    let b = modulo;
    // prettier-ignore
    let x = _0n, y = _1n, u = _1n, v = _0n;
    while (a !== _0n) {
        // JIT applies optimization if those two lines follow each other
        const q = b / a;
        const r = b % a;
        const m = x - u * q;
        const n = y - v * q;
        // prettier-ignore
        b = a, a = r, x = u, y = v, u = m, v = n;
    }
    const gcd = b;
    if (gcd !== _1n)
        throw new Error('invert: does not exist');
    return mod(x, modulo);
}
function assertIsSquare(Fp, root, n) {
    if (!Fp.eql(Fp.sqr(root), n))
        throw new Error('Cannot find square root');
}
// Not all roots are possible! Example which will throw:
// const NUM =
// n = 72057594037927816n;
// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));
function sqrt3mod4(Fp, n) {
    const p1div4 = (Fp.ORDER + _1n) / _4n;
    const root = Fp.pow(n, p1div4);
    assertIsSquare(Fp, root, n);
    return root;
}
function sqrt5mod8(Fp, n) {
    const p5div8 = (Fp.ORDER - _5n) / _8n;
    const n2 = Fp.mul(n, _2n);
    const v = Fp.pow(n2, p5div8);
    const nv = Fp.mul(n, v);
    const i = Fp.mul(Fp.mul(nv, _2n), v);
    const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
    assertIsSquare(Fp, root, n);
    return root;
}
// Based on RFC9380, Kong algorithm
// prettier-ignore
function sqrt9mod16(P) {
    const Fp_ = Field(P);
    const tn = tonelliShanks(P);
    const c1 = tn(Fp_, Fp_.neg(Fp_.ONE)); //  1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F
    const c2 = tn(Fp_, c1); //  2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F
    const c3 = tn(Fp_, Fp_.neg(c1)); //  3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F
    const c4 = (P + _7n) / _16n; //  4. c4 = (q + 7) / 16        # Integer arithmetic
    return (Fp, n) => {
        let tv1 = Fp.pow(n, c4); //  1. tv1 = x^c4
        let tv2 = Fp.mul(tv1, c1); //  2. tv2 = c1 * tv1
        const tv3 = Fp.mul(tv1, c2); //  3. tv3 = c2 * tv1
        const tv4 = Fp.mul(tv1, c3); //  4. tv4 = c3 * tv1
        const e1 = Fp.eql(Fp.sqr(tv2), n); //  5.  e1 = (tv2^2) == x
        const e2 = Fp.eql(Fp.sqr(tv3), n); //  6.  e2 = (tv3^2) == x
        tv1 = Fp.cmov(tv1, tv2, e1); //  7. tv1 = CMOV(tv1, tv2, e1)  # Select tv2 if (tv2^2) == x
        tv2 = Fp.cmov(tv4, tv3, e2); //  8. tv2 = CMOV(tv4, tv3, e2)  # Select tv3 if (tv3^2) == x
        const e3 = Fp.eql(Fp.sqr(tv2), n); //  9.  e3 = (tv2^2) == x
        const root = Fp.cmov(tv1, tv2, e3); // 10.  z = CMOV(tv1, tv2, e3)   # Select sqrt from tv1 & tv2
        assertIsSquare(Fp, root, n);
        return root;
    };
}
/**
 * Tonelli-Shanks square root search algorithm.
 * 1. https://eprint.iacr.org/2012/685.pdf (page 12)
 * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks
 * @param P field order
 * @returns function that takes field Fp (created from P) and number n
 */
export function tonelliShanks(P) {
    // Initialization (precomputation).
    // Caching initialization could boost perf by 7%.
    if (P < _3n)
        throw new Error('sqrt is not defined for small field');
    // Factor P - 1 = Q * 2^S, where Q is odd
    let Q = P - _1n;
    let S = 0;
    while (Q % _2n === _0n) {
        Q /= _2n;
        S++;
    }
    // Find the first quadratic non-residue Z >= 2
    let Z = _2n;
    const _Fp = Field(P);
    while (FpLegendre(_Fp, Z) === 1) {
        // Basic primality test for P. After x iterations, chance of
        // not finding quadratic non-residue is 2^x, so 2^1000.
        if (Z++ > 1000)
            throw new Error('Cannot find square root: probably non-prime P');
    }
    // Fast-path; usually done before Z, but we do "primality test".
    if (S === 1)
        return sqrt3mod4;
    // Slow-path
    // TODO: test on Fp2 and others
    let cc = _Fp.pow(Z, Q); // c = z^Q
    const Q1div2 = (Q + _1n) / _2n;
    return function tonelliSlow(Fp, n) {
        if (Fp.is0(n))
            return n;
        // Check if n is a quadratic residue using Legendre symbol
        if (FpLegendre(Fp, n) !== 1)
            throw new Error('Cannot find square root');
        // Initialize variables for the main loop
        let M = S;
        let c = Fp.mul(Fp.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp
        let t = Fp.pow(n, Q); // t = n^Q, first guess at the fudge factor
        let R = Fp.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root
        // Main loop
        // while t != 1
        while (!Fp.eql(t, Fp.ONE)) {
            if (Fp.is0(t))
                return Fp.ZERO; // if t=0 return R=0
            let i = 1;
            // Find the smallest i >= 1 such that t^(2^i) ≡ 1 (mod P)
            let t_tmp = Fp.sqr(t); // t^(2^1)
            while (!Fp.eql(t_tmp, Fp.ONE)) {
                i++;
                t_tmp = Fp.sqr(t_tmp); // t^(2^2)...
                if (i === M)
                    throw new Error('Cannot find square root');
            }
            // Calculate the exponent for b: 2^(M - i - 1)
            const exponent = _1n << BigInt(M - i - 1); // bigint is important
            const b = Fp.pow(c, exponent); // b = 2^(M - i - 1)
            // Update variables
            M = i;
            c = Fp.sqr(b); // c = b^2
            t = Fp.mul(t, c); // t = (t * b^2)
            R = Fp.mul(R, b); // R = R*b
        }
        return R;
    };
}
/**
 * Square root for a finite field. Will try optimized versions first:
 *
 * 1. P ≡ 3 (mod 4)
 * 2. P ≡ 5 (mod 8)
 * 3. P ≡ 9 (mod 16)
 * 4. Tonelli-Shanks algorithm
 *
 * Different algorithms can give different roots, it is up to user to decide which one they want.
 * For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).
 */
export function FpSqrt(P) {
    // P ≡ 3 (mod 4) => √n = n^((P+1)/4)
    if (P % _4n === _3n)
        return sqrt3mod4;
    // P ≡ 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf
    if (P % _8n === _5n)
        return sqrt5mod8;
    // P ≡ 9 (mod 16) => Kong algorithm, page 11 of https://eprint.iacr.org/2012/685.pdf (algorithm 4)
    if (P % _16n === _9n)
        return sqrt9mod16(P);
    // Tonelli-Shanks algorithm
    return tonelliShanks(P);
}
// Little-endian check for first LE bit (last BE bit);
export const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n;
// prettier-ignore
const FIELD_FIELDS = [
    'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',
    'eql', 'add', 'sub', 'mul', 'pow', 'div',
    'addN', 'subN', 'mulN', 'sqrN'
];
export function validateField(field) {
    const initial = {
        ORDER: 'bigint',
        MASK: 'bigint',
        BYTES: 'number',
        BITS: 'number',
    };
    const opts = FIELD_FIELDS.reduce((map, val) => {
        map[val] = 'function';
        return map;
    }, initial);
    _validateObject(field, opts);
    // const max = 16384;
    // if (field.BYTES < 1 || field.BYTES > max) throw new Error('invalid field');
    // if (field.BITS < 1 || field.BITS > 8 * max) throw new Error('invalid field');
    return field;
}
// Generic field functions
/**
 * Same as `pow` but for Fp: non-constant-time.
 * Unsafe in some contexts: uses ladder, so can expose bigint bits.
 */
export function FpPow(Fp, num, power) {
    if (power < _0n)
        throw new Error('invalid exponent, negatives unsupported');
    if (power === _0n)
        return Fp.ONE;
    if (power === _1n)
        return num;
    let p = Fp.ONE;
    let d = num;
    while (power > _0n) {
        if (power & _1n)
            p = Fp.mul(p, d);
        d = Fp.sqr(d);
        power >>= _1n;
    }
    return p;
}
/**
 * Efficiently invert an array of Field elements.
 * Exception-free. Will return `undefined` for 0 elements.
 * @param passZero map 0 to 0 (instead of undefined)
 */
export function FpInvertBatch(Fp, nums, passZero = false) {
    const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : undefined);
    // Walk from first to last, multiply them by each other MOD p
    const multipliedAcc = nums.reduce((acc, num, i) => {
        if (Fp.is0(num))
            return acc;
        inverted[i] = acc;
        return Fp.mul(acc, num);
    }, Fp.ONE);
    // Invert last element
    const invertedAcc = Fp.inv(multipliedAcc);
    // Walk from last to first, multiply them by inverted each other MOD p
    nums.reduceRight((acc, num, i) => {
        if (Fp.is0(num))
            return acc;
        inverted[i] = Fp.mul(acc, inverted[i]);
        return Fp.mul(acc, num);
    }, invertedAcc);
    return inverted;
}
// TODO: remove
export function FpDiv(Fp, lhs, rhs) {
    return Fp.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, Fp.ORDER) : Fp.inv(rhs));
}
/**
 * Legendre symbol.
 * Legendre constant is used to calculate Legendre symbol (a | p)
 * which denotes the value of a^((p-1)/2) (mod p).
 *
 * * (a | p) ≡ 1    if a is a square (mod p), quadratic residue
 * * (a | p) ≡ -1   if a is not a square (mod p), quadratic non residue
 * * (a | p) ≡ 0    if a ≡ 0 (mod p)
 */
export function FpLegendre(Fp, n) {
    // We can use 3rd argument as optional cache of this value
    // but seems unneeded for now. The operation is very fast.
    const p1mod2 = (Fp.ORDER - _1n) / _2n;
    const powered = Fp.pow(n, p1mod2);
    const yes = Fp.eql(powered, Fp.ONE);
    const zero = Fp.eql(powered, Fp.ZERO);
    const no = Fp.eql(powered, Fp.neg(Fp.ONE));
    if (!yes && !zero && !no)
        throw new Error('invalid Legendre symbol result');
    return yes ? 1 : zero ? 0 : -1;
}
// This function returns True whenever the value x is a square in the field F.
export function FpIsSquare(Fp, n) {
    const l = FpLegendre(Fp, n);
    return l === 1;
}
// CURVE.n lengths
export function nLength(n, nBitLength) {
    // Bit size, byte size of CURVE.n
    if (nBitLength !== undefined)
        anumber(nBitLength);
    const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;
    const nByteLength = Math.ceil(_nBitLength / 8);
    return { nBitLength: _nBitLength, nByteLength };
}
/**
 * Creates a finite field. Major performance optimizations:
 * * 1. Denormalized operations like mulN instead of mul.
 * * 2. Identical object shape: never add or remove keys.
 * * 3. `Object.freeze`.
 * Fragile: always run a benchmark on a change.
 * Security note: operations don't check 'isValid' for all elements for performance reasons,
 * it is caller responsibility to check this.
 * This is low-level code, please make sure you know what you're doing.
 *
 * Note about field properties:
 * * CHARACTERISTIC p = prime number, number of elements in main subgroup.
 * * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.
 *
 * @param ORDER field order, probably prime, or could be composite
 * @param bitLen how many bits the field consumes
 * @param isLE (default: false) if encoding / decoding should be in little-endian
 * @param redef optional faster redefinitions of sqrt and other methods
 */
export function Field(ORDER, bitLenOrOpts, // TODO: use opts only in v2?
isLE = false, opts = {}) {
    if (ORDER <= _0n)
        throw new Error('invalid field: expected ORDER > 0, got ' + ORDER);
    let _nbitLength = undefined;
    let _sqrt = undefined;
    let modFromBytes = false;
    let allowedLengths = undefined;
    if (typeof bitLenOrOpts === 'object' && bitLenOrOpts != null) {
        if (opts.sqrt || isLE)
            throw new Error('cannot specify opts in two arguments');
        const _opts = bitLenOrOpts;
        if (_opts.BITS)
            _nbitLength = _opts.BITS;
        if (_opts.sqrt)
            _sqrt = _opts.sqrt;
        if (typeof _opts.isLE === 'boolean')
            isLE = _opts.isLE;
        if (typeof _opts.modFromBytes === 'boolean')
            modFromBytes = _opts.modFromBytes;
        allowedLengths = _opts.allowedLengths;
    }
    else {
        if (typeof bitLenOrOpts === 'number')
            _nbitLength = bitLenOrOpts;
        if (opts.sqrt)
            _sqrt = opts.sqrt;
    }
    const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, _nbitLength);
    if (BYTES > 2048)
        throw new Error('invalid field: expected ORDER of <= 2048 bytes');
    let sqrtP; // cached sqrtP
    const f = Object.freeze({
        ORDER,
        isLE,
        BITS,
        BYTES,
        MASK: bitMask(BITS),
        ZERO: _0n,
        ONE: _1n,
        allowedLengths: allowedLengths,
        create: (num) => mod(num, ORDER),
        isValid: (num) => {
            if (typeof num !== 'bigint')
                throw new Error('invalid field element: expected bigint, got ' + typeof num);
            return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible
        },
        is0: (num) => num === _0n,
        // is valid and invertible
        isValidNot0: (num) => !f.is0(num) && f.isValid(num),
        isOdd: (num) => (num & _1n) === _1n,
        neg: (num) => mod(-num, ORDER),
        eql: (lhs, rhs) => lhs === rhs,
        sqr: (num) => mod(num * num, ORDER),
        add: (lhs, rhs) => mod(lhs + rhs, ORDER),
        sub: (lhs, rhs) => mod(lhs - rhs, ORDER),
        mul: (lhs, rhs) => mod(lhs * rhs, ORDER),
        pow: (num, power) => FpPow(f, num, power),
        div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),
        // Same as above, but doesn't normalize
        sqrN: (num) => num * num,
        addN: (lhs, rhs) => lhs + rhs,
        subN: (lhs, rhs) => lhs - rhs,
        mulN: (lhs, rhs) => lhs * rhs,
        inv: (num) => invert(num, ORDER),
        sqrt: _sqrt ||
            ((n) => {
                if (!sqrtP)
                    sqrtP = FpSqrt(ORDER);
                return sqrtP(f, n);
            }),
        toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),
        fromBytes: (bytes, skipValidation = true) => {
            if (allowedLengths) {
                if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
                    throw new Error('Field.fromBytes: expected ' + allowedLengths + ' bytes, got ' + bytes.length);
                }
                const padded = new Uint8Array(BYTES);
                // isLE add 0 to right, !isLE to the left.
                padded.set(bytes, isLE ? 0 : padded.length - bytes.length);
                bytes = padded;
            }
            if (bytes.length !== BYTES)
                throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);
            let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
            if (modFromBytes)
                scalar = mod(scalar, ORDER);
            if (!skipValidation)
                if (!f.isValid(scalar))
                    throw new Error('invalid field element: outside of range 0..ORDER');
            // NOTE: we don't validate scalar here, please use isValid. This done such way because some
            // protocol may allow non-reduced scalar that reduced later or changed some other way.
            return scalar;
        },
        // TODO: we don't need it here, move out to separate fn
        invertBatch: (lst) => FpInvertBatch(f, lst),
        // We can't move this out because Fp6, Fp12 implement it
        // and it's unclear what to return in there.
        cmov: (a, b, c) => (c ? b : a),
    });
    return Object.freeze(f);
}
// Generic random scalar, we can do same for other fields if via Fp2.mul(Fp2.ONE, Fp2.random)?
// This allows unsafe methods like ignore bias or zero. These unsafe, but often used in different protocols (if deterministic RNG).
// which mean we cannot force this via opts.
// Not sure what to do with randomBytes, we can accept it inside opts if wanted.
// Probably need to export getMinHashLength somewhere?
// random(bytes?: Uint8Array, unsafeAllowZero = false, unsafeAllowBias = false) {
//   const LEN = !unsafeAllowBias ? getMinHashLength(ORDER) : BYTES;
//   if (bytes === undefined) bytes = randomBytes(LEN); // _opts.randomBytes?
//   const num = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
//   // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0
//   const reduced = unsafeAllowZero ? mod(num, ORDER) : mod(num, ORDER - _1n) + _1n;
//   return reduced;
// },
export function FpSqrtOdd(Fp, elm) {
    if (!Fp.isOdd)
        throw new Error("Field doesn't have isOdd");
    const root = Fp.sqrt(elm);
    return Fp.isOdd(root) ? root : Fp.neg(root);
}
export function FpSqrtEven(Fp, elm) {
    if (!Fp.isOdd)
        throw new Error("Field doesn't have isOdd");
    const root = Fp.sqrt(elm);
    return Fp.isOdd(root) ? Fp.neg(root) : root;
}
/**
 * "Constant-time" private key generation utility.
 * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field).
 * Which makes it slightly more biased, less secure.
 * @deprecated use `mapKeyToField` instead
 */
export function hashToPrivateScalar(hash, groupOrder, isLE = false) {
    hash = ensureBytes('privateHash', hash);
    const hashLen = hash.length;
    const minLen = nLength(groupOrder).nByteLength + 8;
    if (minLen < 24 || hashLen < minLen || hashLen > 1024)
        throw new Error('hashToPrivateScalar: expected ' + minLen + '-1024 bytes of input, got ' + hashLen);
    const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash);
    return mod(num, groupOrder - _1n) + _1n;
}
/**
 * Returns total number of bytes consumed by the field element.
 * For example, 32 bytes for usual 256-bit weierstrass curve.
 * @param fieldOrder number of field elements, usually CURVE.n
 * @returns byte length of field
 */
export function getFieldBytesLength(fieldOrder) {
    if (typeof fieldOrder !== 'bigint')
        throw new Error('field order must be bigint');
    const bitLength = fieldOrder.toString(2).length;
    return Math.ceil(bitLength / 8);
}
/**
 * Returns minimal amount of bytes that can be safely reduced
 * by field order.
 * Should be 2^-128 for 128-bit curve such as P256.
 * @param fieldOrder number of field elements, usually CURVE.n
 * @returns byte length of target hash
 */
export function getMinHashLength(fieldOrder) {
    const length = getFieldBytesLength(fieldOrder);
    return length + Math.ceil(length / 2);
}
/**
 * "Constant-time" private key generation utility.
 * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF
 * and convert them into private scalar, with the modulo bias being negligible.
 * Needs at least 48 bytes of input for 32-byte private key.
 * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/
 * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final
 * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5
 * @param hash hash output from SHA3 or a similar function
 * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)
 * @param isLE interpret hash bytes as LE num
 * @returns valid private scalar
 */
export function mapHashToField(key, fieldOrder, isLE = false) {
    const len = key.length;
    const fieldLen = getFieldBytesLength(fieldOrder);
    const minLen = getMinHashLength(fieldOrder);
    // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.
    if (len < 16 || len < minLen || len > 1024)
        throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);
    const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);
    // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0
    const reduced = mod(num, fieldOrder - _1n) + _1n;
    return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
}
//# sourceMappingURL=modular.js.map/**
 * Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.
 *
 * ### Design rationale for types
 *
 * * Interaction between classes from different curves should fail:
 *   `k256.Point.BASE.add(p256.Point.BASE)`
 * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime
 * * Different calls of `curve()` would return different classes -
 *   `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,
 *   it won't affect others
 *
 * TypeScript can't infer types for classes created inside a function. Classes is one instance
 * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create
 * unique type for every function call.
 *
 * We can use generic types via some param, like curve opts, but that would:
 *     1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)
 *     which is hard to debug.
 *     2. Params can be generic and we can't enforce them to be constant value:
 *     if somebody creates curve from non-constant params,
 *     it would be allowed to interact with other curves with non-constant params
 *
 * @todo https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { hmac as nobleHmac } from '@noble/hashes/hmac.js';
import { ahash } from '@noble/hashes/utils';
import { _validateObject, _abool2 as abool, _abytes2 as abytes, aInRange, bitLen, bitMask, bytesToHex, bytesToNumberBE, concatBytes, createHmacDrbg, ensureBytes, hexToBytes, inRange, isBytes, memoized, numberToHexUnpadded, randomBytes as randomBytesWeb, } from "../utils.js";
import { _createCurveFields, mulEndoUnsafe, negateCt, normalizeZ, pippenger, wNAF, } from "./curve.js";
import { Field, FpInvertBatch, getMinHashLength, mapHashToField, nLength, validateField, } from "./modular.js";
// We construct basis in such way that den is always positive and equals n, but num sign depends on basis (not on secret value)
const divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n) / den;
/**
 * Splits scalar for GLV endomorphism.
 */
export function _splitEndoScalar(k, basis, n) {
    // Split scalar into two such that part is ~half bits: `abs(part) < sqrt(N)`
    // Since part can be negative, we need to do this on point.
    // TODO: verifyScalar function which consumes lambda
    const [[a1, b1], [a2, b2]] = basis;
    const c1 = divNearest(b2 * k, n);
    const c2 = divNearest(-b1 * k, n);
    // |k1|/|k2| is < sqrt(N), but can be negative.
    // If we do `k1 mod N`, we'll get big scalar (`> sqrt(N)`): so, we do cheaper negation instead.
    let k1 = k - c1 * a1 - c2 * a2;
    let k2 = -c1 * b1 - c2 * b2;
    const k1neg = k1 < _0n;
    const k2neg = k2 < _0n;
    if (k1neg)
        k1 = -k1;
    if (k2neg)
        k2 = -k2;
    // Double check that resulting scalar less than half bits of N: otherwise wNAF will fail.
    // This should only happen on wrong basises. Also, math inside is too complex and I don't trust it.
    const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n; // Half bits of N
    if (k1 < _0n || k1 >= MAX_NUM || k2 < _0n || k2 >= MAX_NUM) {
        throw new Error('splitScalar (endomorphism): failed, k=' + k);
    }
    return { k1neg, k1, k2neg, k2 };
}
function validateSigFormat(format) {
    if (!['compact', 'recovered', 'der'].includes(format))
        throw new Error('Signature format must be "compact", "recovered", or "der"');
    return format;
}
function validateSigOpts(opts, def) {
    const optsn = {};
    for (let optName of Object.keys(def)) {
        // @ts-ignore
        optsn[optName] = opts[optName] === undefined ? def[optName] : opts[optName];
    }
    abool(optsn.lowS, 'lowS');
    abool(optsn.prehash, 'prehash');
    if (optsn.format !== undefined)
        validateSigFormat(optsn.format);
    return optsn;
}
export class DERErr extends Error {
    constructor(m = '') {
        super(m);
    }
}
/**
 * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:
 *
 *     [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]
 *
 * Docs: https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/, https://luca.ntop.org/Teaching/Appunti/asn1.html
 */
export const DER = {
    // asn.1 DER encoding utils
    Err: DERErr,
    // Basic building block is TLV (Tag-Length-Value)
    _tlv: {
        encode: (tag, data) => {
            const { Err: E } = DER;
            if (tag < 0 || tag > 256)
                throw new E('tlv.encode: wrong tag');
            if (data.length & 1)
                throw new E('tlv.encode: unpadded data');
            const dataLen = data.length / 2;
            const len = numberToHexUnpadded(dataLen);
            if ((len.length / 2) & 128)
                throw new E('tlv.encode: long form length too big');
            // length of length with long form flag
            const lenLen = dataLen > 127 ? numberToHexUnpadded((len.length / 2) | 128) : '';
            const t = numberToHexUnpadded(tag);
            return t + lenLen + len + data;
        },
        // v - value, l - left bytes (unparsed)
        decode(tag, data) {
            const { Err: E } = DER;
            let pos = 0;
            if (tag < 0 || tag > 256)
                throw new E('tlv.encode: wrong tag');
            if (data.length < 2 || data[pos++] !== tag)
                throw new E('tlv.decode: wrong tlv');
            const first = data[pos++];
            const isLong = !!(first & 128); // First bit of first length byte is flag for short/long form
            let length = 0;
            if (!isLong)
                length = first;
            else {
                // Long form: [longFlag(1bit), lengthLength(7bit), length (BE)]
                const lenLen = first & 127;
                if (!lenLen)
                    throw new E('tlv.decode(long): indefinite length not supported');
                if (lenLen > 4)
                    throw new E('tlv.decode(long): byte length is too big'); // this will overflow u32 in js
                const lengthBytes = data.subarray(pos, pos + lenLen);
                if (lengthBytes.length !== lenLen)
                    throw new E('tlv.decode: length bytes not complete');
                if (lengthBytes[0] === 0)
                    throw new E('tlv.decode(long): zero leftmost byte');
                for (const b of lengthBytes)
                    length = (length << 8) | b;
                pos += lenLen;
                if (length < 128)
                    throw new E('tlv.decode(long): not minimal encoding');
            }
            const v = data.subarray(pos, pos + length);
            if (v.length !== length)
                throw new E('tlv.decode: wrong value length');
            return { v, l: data.subarray(pos + length) };
        },
    },
    // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
    // since we always use positive integers here. It must always be empty:
    // - add zero byte if exists
    // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
    _int: {
        encode(num) {
            const { Err: E } = DER;
            if (num < _0n)
                throw new E('integer: negative integers are not allowed');
            let hex = numberToHexUnpadded(num);
            // Pad with zero byte if negative flag is present
            if (Number.parseInt(hex[0], 16) & 0b1000)
                hex = '00' + hex;
            if (hex.length & 1)
                throw new E('unexpected DER parsing assertion: unpadded hex');
            return hex;
        },
        decode(data) {
            const { Err: E } = DER;
            if (data[0] & 128)
                throw new E('invalid signature integer: negative');
            if (data[0] === 0x00 && !(data[1] & 128))
                throw new E('invalid signature integer: unnecessary leading zero');
            return bytesToNumberBE(data);
        },
    },
    toSig(hex) {
        // parse DER signature
        const { Err: E, _int: int, _tlv: tlv } = DER;
        const data = ensureBytes('signature', hex);
        const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);
        if (seqLeftBytes.length)
            throw new E('invalid signature: left bytes after parsing');
        const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);
        const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);
        if (sLeftBytes.length)
            throw new E('invalid signature: left bytes after parsing');
        return { r: int.decode(rBytes), s: int.decode(sBytes) };
    },
    hexFromSig(sig) {
        const { _tlv: tlv, _int: int } = DER;
        const rs = tlv.encode(0x02, int.encode(sig.r));
        const ss = tlv.encode(0x02, int.encode(sig.s));
        const seq = rs + ss;
        return tlv.encode(0x30, seq);
    },
};
// Be friendly to bad ECMAScript parsers by not using bigint literals
// prettier-ignore
const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4);
export function _normFnElement(Fn, key) {
    const { BYTES: expected } = Fn;
    let num;
    if (typeof key === 'bigint') {
        num = key;
    }
    else {
        let bytes = ensureBytes('private key', key);
        try {
            num = Fn.fromBytes(bytes);
        }
        catch (error) {
            throw new Error(`invalid private key: expected ui8a of size ${expected}, got ${typeof key}`);
        }
    }
    if (!Fn.isValidNot0(num))
        throw new Error('invalid private key: out of range [1..N-1]');
    return num;
}
/**
 * Creates weierstrass Point constructor, based on specified curve options.
 *
 * @example
```js
const opts = {
  p: BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff'),
  n: BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551'),
  h: BigInt(1),
  a: BigInt('0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc'),
  b: BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b'),
  Gx: BigInt('0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296'),
  Gy: BigInt('0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5'),
};
const p256_Point = weierstrass(opts);
```
 */
export function weierstrassN(params, extraOpts = {}) {
    const validated = _createCurveFields('weierstrass', params, extraOpts);
    const { Fp, Fn } = validated;
    let CURVE = validated.CURVE;
    const { h: cofactor, n: CURVE_ORDER } = CURVE;
    _validateObject(extraOpts, {}, {
        allowInfinityPoint: 'boolean',
        clearCofactor: 'function',
        isTorsionFree: 'function',
        fromBytes: 'function',
        toBytes: 'function',
        endo: 'object',
        wrapPrivateKey: 'boolean',
    });
    const { endo } = extraOpts;
    if (endo) {
        // validateObject(endo, { beta: 'bigint', splitScalar: 'function' });
        if (!Fp.is0(CURVE.a) || typeof endo.beta !== 'bigint' || !Array.isArray(endo.basises)) {
            throw new Error('invalid endo: expected "beta": bigint and "basises": array');
        }
    }
    const lengths = getWLengths(Fp, Fn);
    function assertCompressionIsSupported() {
        if (!Fp.isOdd)
            throw new Error('compression is not supported: Field does not have .isOdd()');
    }
    // Implements IEEE P1363 point encoding
    function pointToBytes(_c, point, isCompressed) {
        const { x, y } = point.toAffine();
        const bx = Fp.toBytes(x);
        abool(isCompressed, 'isCompressed');
        if (isCompressed) {
            assertCompressionIsSupported();
            const hasEvenY = !Fp.isOdd(y);
            return concatBytes(pprefix(hasEvenY), bx);
        }
        else {
            return concatBytes(Uint8Array.of(0x04), bx, Fp.toBytes(y));
        }
    }
    function pointFromBytes(bytes) {
        abytes(bytes, undefined, 'Point');
        const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths; // e.g. for 32-byte: 33, 65
        const length = bytes.length;
        const head = bytes[0];
        const tail = bytes.subarray(1);
        // No actual validation is done here: use .assertValidity()
        if (length === comp && (head === 0x02 || head === 0x03)) {
            const x = Fp.fromBytes(tail);
            if (!Fp.isValid(x))
                throw new Error('bad point: is not on curve, wrong x');
            const y2 = weierstrassEquation(x); // y² = x³ + ax + b
            let y;
            try {
                y = Fp.sqrt(y2); // y = y² ^ (p+1)/4
            }
            catch (sqrtError) {
                const err = sqrtError instanceof Error ? ': ' + sqrtError.message : '';
                throw new Error('bad point: is not on curve, sqrt error' + err);
            }
            assertCompressionIsSupported();
            const isYOdd = Fp.isOdd(y); // (y & _1n) === _1n;
            const isHeadOdd = (head & 1) === 1; // ECDSA-specific
            if (isHeadOdd !== isYOdd)
                y = Fp.neg(y);
            return { x, y };
        }
        else if (length === uncomp && head === 0x04) {
            // TODO: more checks
            const L = Fp.BYTES;
            const x = Fp.fromBytes(tail.subarray(0, L));
            const y = Fp.fromBytes(tail.subarray(L, L * 2));
            if (!isValidXY(x, y))
                throw new Error('bad point: is not on curve');
            return { x, y };
        }
        else {
            throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);
        }
    }
    const encodePoint = extraOpts.toBytes || pointToBytes;
    const decodePoint = extraOpts.fromBytes || pointFromBytes;
    function weierstrassEquation(x) {
        const x2 = Fp.sqr(x); // x * x
        const x3 = Fp.mul(x2, x); // x² * x
        return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b); // x³ + a * x + b
    }
    // TODO: move top-level
    /** Checks whether equation holds for given x, y: y² == x³ + ax + b */
    function isValidXY(x, y) {
        const left = Fp.sqr(y); // y²
        const right = weierstrassEquation(x); // x³ + ax + b
        return Fp.eql(left, right);
    }
    // Validate whether the passed curve params are valid.
    // Test 1: equation y² = x³ + ax + b should work for generator point.
    if (!isValidXY(CURVE.Gx, CURVE.Gy))
        throw new Error('bad curve params: generator point');
    // Test 2: discriminant Δ part should be non-zero: 4a³ + 27b² != 0.
    // Guarantees curve is genus-1, smooth (non-singular).
    const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n), _4n);
    const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));
    if (Fp.is0(Fp.add(_4a3, _27b2)))
        throw new Error('bad curve params: a or b');
    /** Asserts coordinate is valid: 0 <= n < Fp.ORDER. */
    function acoord(title, n, banZero = false) {
        if (!Fp.isValid(n) || (banZero && Fp.is0(n)))
            throw new Error(`bad point coordinate ${title}`);
        return n;
    }
    function aprjpoint(other) {
        if (!(other instanceof Point))
            throw new Error('ProjectivePoint expected');
    }
    function splitEndoScalarN(k) {
        if (!endo || !endo.basises)
            throw new Error('no endo');
        return _splitEndoScalar(k, endo.basises, Fn.ORDER);
    }
    // Memoized toAffine / validity check. They are heavy. Points are immutable.
    // Converts Projective point to affine (x, y) coordinates.
    // Can accept precomputed Z^-1 - for example, from invertBatch.
    // (X, Y, Z) ∋ (x=X/Z, y=Y/Z)
    const toAffineMemo = memoized((p, iz) => {
        const { X, Y, Z } = p;
        // Fast-path for normalized points
        if (Fp.eql(Z, Fp.ONE))
            return { x: X, y: Y };
        const is0 = p.is0();
        // If invZ was 0, we return zero point. However we still want to execute
        // all operations, so we replace invZ with a random number, 1.
        if (iz == null)
            iz = is0 ? Fp.ONE : Fp.inv(Z);
        const x = Fp.mul(X, iz);
        const y = Fp.mul(Y, iz);
        const zz = Fp.mul(Z, iz);
        if (is0)
            return { x: Fp.ZERO, y: Fp.ZERO };
        if (!Fp.eql(zz, Fp.ONE))
            throw new Error('invZ was invalid');
        return { x, y };
    });
    // NOTE: on exception this will crash 'cached' and no value will be set.
    // Otherwise true will be return
    const assertValidMemo = memoized((p) => {
        if (p.is0()) {
            // (0, 1, 0) aka ZERO is invalid in most contexts.
            // In BLS, ZERO can be serialized, so we allow it.
            // (0, 0, 0) is invalid representation of ZERO.
            if (extraOpts.allowInfinityPoint && !Fp.is0(p.Y))
                return;
            throw new Error('bad point: ZERO');
        }
        // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`
        const { x, y } = p.toAffine();
        if (!Fp.isValid(x) || !Fp.isValid(y))
            throw new Error('bad point: x or y not field elements');
        if (!isValidXY(x, y))
            throw new Error('bad point: equation left != right');
        if (!p.isTorsionFree())
            throw new Error('bad point: not in prime-order subgroup');
        return true;
    });
    function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) {
        k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);
        k1p = negateCt(k1neg, k1p);
        k2p = negateCt(k2neg, k2p);
        return k1p.add(k2p);
    }
    /**
     * Projective Point works in 3d / projective (homogeneous) coordinates:(X, Y, Z) ∋ (x=X/Z, y=Y/Z).
     * Default Point works in 2d / affine coordinates: (x, y).
     * We're doing calculations in projective, because its operations don't require costly inversion.
     */
    class Point {
        /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
        constructor(X, Y, Z) {
            this.X = acoord('x', X);
            this.Y = acoord('y', Y, true);
            this.Z = acoord('z', Z);
            Object.freeze(this);
        }
        static CURVE() {
            return CURVE;
        }
        /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
        static fromAffine(p) {
            const { x, y } = p || {};
            if (!p || !Fp.isValid(x) || !Fp.isValid(y))
                throw new Error('invalid affine point');
            if (p instanceof Point)
                throw new Error('projective point not allowed');
            // (0, 0) would've produced (0, 0, 1) - instead, we need (0, 1, 0)
            if (Fp.is0(x) && Fp.is0(y))
                return Point.ZERO;
            return new Point(x, y, Fp.ONE);
        }
        static fromBytes(bytes) {
            const P = Point.fromAffine(decodePoint(abytes(bytes, undefined, 'point')));
            P.assertValidity();
            return P;
        }
        static fromHex(hex) {
            return Point.fromBytes(ensureBytes('pointHex', hex));
        }
        get x() {
            return this.toAffine().x;
        }
        get y() {
            return this.toAffine().y;
        }
        /**
         *
         * @param windowSize
         * @param isLazy true will defer table computation until the first multiplication
         * @returns
         */
        precompute(windowSize = 8, isLazy = true) {
            wnaf.createCache(this, windowSize);
            if (!isLazy)
                this.multiply(_3n); // random number
            return this;
        }
        // TODO: return `this`
        /** A point on curve is valid if it conforms to equation. */
        assertValidity() {
            assertValidMemo(this);
        }
        hasEvenY() {
            const { y } = this.toAffine();
            if (!Fp.isOdd)
                throw new Error("Field doesn't support isOdd");
            return !Fp.isOdd(y);
        }
        /** Compare one point to another. */
        equals(other) {
            aprjpoint(other);
            const { X: X1, Y: Y1, Z: Z1 } = this;
            const { X: X2, Y: Y2, Z: Z2 } = other;
            const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
            const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
            return U1 && U2;
        }
        /** Flips point to one corresponding to (x, -y) in Affine coordinates. */
        negate() {
            return new Point(this.X, Fp.neg(this.Y), this.Z);
        }
        // Renes-Costello-Batina exception-free doubling formula.
        // There is 30% faster Jacobian formula, but it is not complete.
        // https://eprint.iacr.org/2015/1060, algorithm 3
        // Cost: 8M + 3S + 3*a + 2*b3 + 15add.
        double() {
            const { a, b } = CURVE;
            const b3 = Fp.mul(b, _3n);
            const { X: X1, Y: Y1, Z: Z1 } = this;
            let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore
            let t0 = Fp.mul(X1, X1); // step 1
            let t1 = Fp.mul(Y1, Y1);
            let t2 = Fp.mul(Z1, Z1);
            let t3 = Fp.mul(X1, Y1);
            t3 = Fp.add(t3, t3); // step 5
            Z3 = Fp.mul(X1, Z1);
            Z3 = Fp.add(Z3, Z3);
            X3 = Fp.mul(a, Z3);
            Y3 = Fp.mul(b3, t2);
            Y3 = Fp.add(X3, Y3); // step 10
            X3 = Fp.sub(t1, Y3);
            Y3 = Fp.add(t1, Y3);
            Y3 = Fp.mul(X3, Y3);
            X3 = Fp.mul(t3, X3);
            Z3 = Fp.mul(b3, Z3); // step 15
            t2 = Fp.mul(a, t2);
            t3 = Fp.sub(t0, t2);
            t3 = Fp.mul(a, t3);
            t3 = Fp.add(t3, Z3);
            Z3 = Fp.add(t0, t0); // step 20
            t0 = Fp.add(Z3, t0);
            t0 = Fp.add(t0, t2);
            t0 = Fp.mul(t0, t3);
            Y3 = Fp.add(Y3, t0);
            t2 = Fp.mul(Y1, Z1); // step 25
            t2 = Fp.add(t2, t2);
            t0 = Fp.mul(t2, t3);
            X3 = Fp.sub(X3, t0);
            Z3 = Fp.mul(t2, t1);
            Z3 = Fp.add(Z3, Z3); // step 30
            Z3 = Fp.add(Z3, Z3);
            return new Point(X3, Y3, Z3);
        }
        // Renes-Costello-Batina exception-free addition formula.
        // There is 30% faster Jacobian formula, but it is not complete.
        // https://eprint.iacr.org/2015/1060, algorithm 1
        // Cost: 12M + 0S + 3*a + 3*b3 + 23add.
        add(other) {
            aprjpoint(other);
            const { X: X1, Y: Y1, Z: Z1 } = this;
            const { X: X2, Y: Y2, Z: Z2 } = other;
            let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore
            const a = CURVE.a;
            const b3 = Fp.mul(CURVE.b, _3n);
            let t0 = Fp.mul(X1, X2); // step 1
            let t1 = Fp.mul(Y1, Y2);
            let t2 = Fp.mul(Z1, Z2);
            let t3 = Fp.add(X1, Y1);
            let t4 = Fp.add(X2, Y2); // step 5
            t3 = Fp.mul(t3, t4);
            t4 = Fp.add(t0, t1);
            t3 = Fp.sub(t3, t4);
            t4 = Fp.add(X1, Z1);
            let t5 = Fp.add(X2, Z2); // step 10
            t4 = Fp.mul(t4, t5);
            t5 = Fp.add(t0, t2);
            t4 = Fp.sub(t4, t5);
            t5 = Fp.add(Y1, Z1);
            X3 = Fp.add(Y2, Z2); // step 15
            t5 = Fp.mul(t5, X3);
            X3 = Fp.add(t1, t2);
            t5 = Fp.sub(t5, X3);
            Z3 = Fp.mul(a, t4);
            X3 = Fp.mul(b3, t2); // step 20
            Z3 = Fp.add(X3, Z3);
            X3 = Fp.sub(t1, Z3);
            Z3 = Fp.add(t1, Z3);
            Y3 = Fp.mul(X3, Z3);
            t1 = Fp.add(t0, t0); // step 25
            t1 = Fp.add(t1, t0);
            t2 = Fp.mul(a, t2);
            t4 = Fp.mul(b3, t4);
            t1 = Fp.add(t1, t2);
            t2 = Fp.sub(t0, t2); // step 30
            t2 = Fp.mul(a, t2);
            t4 = Fp.add(t4, t2);
            t0 = Fp.mul(t1, t4);
            Y3 = Fp.add(Y3, t0);
            t0 = Fp.mul(t5, t4); // step 35
            X3 = Fp.mul(t3, X3);
            X3 = Fp.sub(X3, t0);
            t0 = Fp.mul(t3, t1);
            Z3 = Fp.mul(t5, Z3);
            Z3 = Fp.add(Z3, t0); // step 40
            return new Point(X3, Y3, Z3);
        }
        subtract(other) {
            return this.add(other.negate());
        }
        is0() {
            return this.equals(Point.ZERO);
        }
        /**
         * Constant time multiplication.
         * Uses wNAF method. Windowed method may be 10% faster,
         * but takes 2x longer to generate and consumes 2x memory.
         * Uses precomputes when available.
         * Uses endomorphism for Koblitz curves.
         * @param scalar by which the point would be multiplied
         * @returns New point
         */
        multiply(scalar) {
            const { endo } = extraOpts;
            if (!Fn.isValidNot0(scalar))
                throw new Error('invalid scalar: out of range'); // 0 is invalid
            let point, fake; // Fake point is used to const-time mult
            const mul = (n) => wnaf.cached(this, n, (p) => normalizeZ(Point, p));
            /** See docs for {@link EndomorphismOpts} */
            if (endo) {
                const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);
                const { p: k1p, f: k1f } = mul(k1);
                const { p: k2p, f: k2f } = mul(k2);
                fake = k1f.add(k2f);
                point = finishEndo(endo.beta, k1p, k2p, k1neg, k2neg);
            }
            else {
                const { p, f } = mul(scalar);
                point = p;
                fake = f;
            }
            // Normalize `z` for both points, but return only real one
            return normalizeZ(Point, [point, fake])[0];
        }
        /**
         * Non-constant-time multiplication. Uses double-and-add algorithm.
         * It's faster, but should only be used when you don't care about
         * an exposed secret key e.g. sig verification, which works over *public* keys.
         */
        multiplyUnsafe(sc) {
            const { endo } = extraOpts;
            const p = this;
            if (!Fn.isValid(sc))
                throw new Error('invalid scalar: out of range'); // 0 is valid
            if (sc === _0n || p.is0())
                return Point.ZERO;
            if (sc === _1n)
                return p; // fast-path
            if (wnaf.hasCache(this))
                return this.multiply(sc);
            if (endo) {
                const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);
                const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2); // 30% faster vs wnaf.unsafe
                return finishEndo(endo.beta, p1, p2, k1neg, k2neg);
            }
            else {
                return wnaf.unsafe(p, sc);
            }
        }
        multiplyAndAddUnsafe(Q, a, b) {
            const sum = this.multiplyUnsafe(a).add(Q.multiplyUnsafe(b));
            return sum.is0() ? undefined : sum;
        }
        /**
         * Converts Projective point to affine (x, y) coordinates.
         * @param invertedZ Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch
         */
        toAffine(invertedZ) {
            return toAffineMemo(this, invertedZ);
        }
        /**
         * Checks whether Point is free of torsion elements (is in prime subgroup).
         * Always torsion-free for cofactor=1 curves.
         */
        isTorsionFree() {
            const { isTorsionFree } = extraOpts;
            if (cofactor === _1n)
                return true;
            if (isTorsionFree)
                return isTorsionFree(Point, this);
            return wnaf.unsafe(this, CURVE_ORDER).is0();
        }
        clearCofactor() {
            const { clearCofactor } = extraOpts;
            if (cofactor === _1n)
                return this; // Fast-path
            if (clearCofactor)
                return clearCofactor(Point, this);
            return this.multiplyUnsafe(cofactor);
        }
        isSmallOrder() {
            // can we use this.clearCofactor()?
            return this.multiplyUnsafe(cofactor).is0();
        }
        toBytes(isCompressed = true) {
            abool(isCompressed, 'isCompressed');
            this.assertValidity();
            return encodePoint(Point, this, isCompressed);
        }
        toHex(isCompressed = true) {
            return bytesToHex(this.toBytes(isCompressed));
        }
        toString() {
            return `<Point ${this.is0() ? 'ZERO' : this.toHex()}>`;
        }
        // TODO: remove
        get px() {
            return this.X;
        }
        get py() {
            return this.X;
        }
        get pz() {
            return this.Z;
        }
        toRawBytes(isCompressed = true) {
            return this.toBytes(isCompressed);
        }
        _setWindowSize(windowSize) {
            this.precompute(windowSize);
        }
        static normalizeZ(points) {
            return normalizeZ(Point, points);
        }
        static msm(points, scalars) {
            return pippenger(Point, Fn, points, scalars);
        }
        static fromPrivateKey(privateKey) {
            return Point.BASE.multiply(_normFnElement(Fn, privateKey));
        }
    }
    // base / generator point
    Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
    // zero / infinity / identity point
    Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); // 0, 1, 0
    // math field
    Point.Fp = Fp;
    // scalar field
    Point.Fn = Fn;
    const bits = Fn.BITS;
    const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);
    Point.BASE.precompute(8); // Enable precomputes. Slows down first publicKey computation by 20ms.
    return Point;
}
// Points start with byte 0x02 when y is even; otherwise 0x03
function pprefix(hasEvenY) {
    return Uint8Array.of(hasEvenY ? 0x02 : 0x03);
}
/**
 * Implementation of the Shallue and van de Woestijne method for any weierstrass curve.
 * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular.
 * b = True and y = sqrt(u / v) if (u / v) is square in F, and
 * b = False and y = sqrt(Z * (u / v)) otherwise.
 * @param Fp
 * @param Z
 * @returns
 */
export function SWUFpSqrtRatio(Fp, Z) {
    // Generic implementation
    const q = Fp.ORDER;
    let l = _0n;
    for (let o = q - _1n; o % _2n === _0n; o /= _2n)
        l += _1n;
    const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1.
    // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<.
    // 2n ** c1 == 2n << (c1-1)
    const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n);
    const _2n_pow_c1 = _2n_pow_c1_1 * _2n;
    const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1)  # Integer arithmetic
    const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2            # Integer arithmetic
    const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1                # Integer arithmetic
    const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1)                  # Integer arithmetic
    const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2
    const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2)
    let sqrtRatio = (u, v) => {
        let tv1 = c6; // 1. tv1 = c6
        let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4
        let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2
        tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v
        let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3
        tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3
        tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2
        tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v
        tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u
        let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2
        tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5
        let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1
        tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7
        tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1
        tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR)
        tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR)
        // 17. for i in (c1, c1 - 1, ..., 2):
        for (let i = c1; i > _1n; i--) {
            let tv5 = i - _2n; // 18.    tv5 = i - 2
            tv5 = _2n << (tv5 - _1n); // 19.    tv5 = 2^tv5
            let tvv5 = Fp.pow(tv4, tv5); // 20.    tv5 = tv4^tv5
            const e1 = Fp.eql(tvv5, Fp.ONE); // 21.    e1 = tv5 == 1
            tv2 = Fp.mul(tv3, tv1); // 22.    tv2 = tv3 * tv1
            tv1 = Fp.mul(tv1, tv1); // 23.    tv1 = tv1 * tv1
            tvv5 = Fp.mul(tv4, tv1); // 24.    tv5 = tv4 * tv1
            tv3 = Fp.cmov(tv2, tv3, e1); // 25.    tv3 = CMOV(tv2, tv3, e1)
            tv4 = Fp.cmov(tvv5, tv4, e1); // 26.    tv4 = CMOV(tv5, tv4, e1)
        }
        return { isValid: isQR, value: tv3 };
    };
    if (Fp.ORDER % _4n === _3n) {
        // sqrt_ratio_3mod4(u, v)
        const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4     # Integer arithmetic
        const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z)
        sqrtRatio = (u, v) => {
            let tv1 = Fp.sqr(v); // 1. tv1 = v^2
            const tv2 = Fp.mul(u, v); // 2. tv2 = u * v
            tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2
            let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1
            y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2
            const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2
            const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v
            const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u
            let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR)
            return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2
        };
    }
    // No curves uses that
    // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8
    return sqrtRatio;
}
/**
 * Simplified Shallue-van de Woestijne-Ulas Method
 * https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2
 */
export function mapToCurveSimpleSWU(Fp, opts) {
    validateField(Fp);
    const { A, B, Z } = opts;
    if (!Fp.isValid(A) || !Fp.isValid(B) || !Fp.isValid(Z))
        throw new Error('mapToCurveSimpleSWU: invalid opts');
    const sqrtRatio = SWUFpSqrtRatio(Fp, Z);
    if (!Fp.isOdd)
        throw new Error('Field does not have .isOdd()');
    // Input: u, an element of F.
    // Output: (x, y), a point on E.
    return (u) => {
        // prettier-ignore
        let tv1, tv2, tv3, tv4, tv5, tv6, x, y;
        tv1 = Fp.sqr(u); // 1.  tv1 = u^2
        tv1 = Fp.mul(tv1, Z); // 2.  tv1 = Z * tv1
        tv2 = Fp.sqr(tv1); // 3.  tv2 = tv1^2
        tv2 = Fp.add(tv2, tv1); // 4.  tv2 = tv2 + tv1
        tv3 = Fp.add(tv2, Fp.ONE); // 5.  tv3 = tv2 + 1
        tv3 = Fp.mul(tv3, B); // 6.  tv3 = B * tv3
        tv4 = Fp.cmov(Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7.  tv4 = CMOV(Z, -tv2, tv2 != 0)
        tv4 = Fp.mul(tv4, A); // 8.  tv4 = A * tv4
        tv2 = Fp.sqr(tv3); // 9.  tv2 = tv3^2
        tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2
        tv5 = Fp.mul(tv6, A); // 11. tv5 = A * tv6
        tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5
        tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3
        tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4
        tv5 = Fp.mul(tv6, B); // 15. tv5 = B * tv6
        tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5
        x = Fp.mul(tv1, tv3); // 17.   x = tv1 * tv3
        const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6)
        y = Fp.mul(tv1, u); // 19.   y = tv1 * u  -> Z * u^3 * y1
        y = Fp.mul(y, value); // 20.   y = y * y1
        x = Fp.cmov(x, tv3, isValid); // 21.   x = CMOV(x, tv3, is_gx1_square)
        y = Fp.cmov(y, value, isValid); // 22.   y = CMOV(y, y1, is_gx1_square)
        const e1 = Fp.isOdd(u) === Fp.isOdd(y); // 23.  e1 = sgn0(u) == sgn0(y)
        y = Fp.cmov(Fp.neg(y), y, e1); // 24.   y = CMOV(-y, y, e1)
        const tv4_inv = FpInvertBatch(Fp, [tv4], true)[0];
        x = Fp.mul(x, tv4_inv); // 25.   x = x / tv4
        return { x, y };
    };
}
function getWLengths(Fp, Fn) {
    return {
        secretKey: Fn.BYTES,
        publicKey: 1 + Fp.BYTES,
        publicKeyUncompressed: 1 + 2 * Fp.BYTES,
        publicKeyHasPrefix: true,
        signature: 2 * Fn.BYTES,
    };
}
/**
 * Sometimes users only need getPublicKey, getSharedSecret, and secret key handling.
 * This helper ensures no signature functionality is present. Less code, smaller bundle size.
 */
export function ecdh(Point, ecdhOpts = {}) {
    const { Fn } = Point;
    const randomBytes_ = ecdhOpts.randomBytes || randomBytesWeb;
    const lengths = Object.assign(getWLengths(Point.Fp, Fn), { seed: getMinHashLength(Fn.ORDER) });
    function isValidSecretKey(secretKey) {
        try {
            return !!_normFnElement(Fn, secretKey);
        }
        catch (error) {
            return false;
        }
    }
    function isValidPublicKey(publicKey, isCompressed) {
        const { publicKey: comp, publicKeyUncompressed } = lengths;
        try {
            const l = publicKey.length;
            if (isCompressed === true && l !== comp)
                return false;
            if (isCompressed === false && l !== publicKeyUncompressed)
                return false;
            return !!Point.fromBytes(publicKey);
        }
        catch (error) {
            return false;
        }
    }
    /**
     * Produces cryptographically secure secret key from random of size
     * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.
     */
    function randomSecretKey(seed = randomBytes_(lengths.seed)) {
        return mapHashToField(abytes(seed, lengths.seed, 'seed'), Fn.ORDER);
    }
    /**
     * Computes public key for a secret key. Checks for validity of the secret key.
     * @param isCompressed whether to return compact (default), or full key
     * @returns Public key, full when isCompressed=false; short when isCompressed=true
     */
    function getPublicKey(secretKey, isCompressed = true) {
        return Point.BASE.multiply(_normFnElement(Fn, secretKey)).toBytes(isCompressed);
    }
    function keygen(seed) {
        const secretKey = randomSecretKey(seed);
        return { secretKey, publicKey: getPublicKey(secretKey) };
    }
    /**
     * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.
     */
    function isProbPub(item) {
        if (typeof item === 'bigint')
            return false;
        if (item instanceof Point)
            return true;
        const { secretKey, publicKey, publicKeyUncompressed } = lengths;
        if (Fn.allowedLengths || secretKey === publicKey)
            return undefined;
        const l = ensureBytes('key', item).length;
        return l === publicKey || l === publicKeyUncompressed;
    }
    /**
     * ECDH (Elliptic Curve Diffie Hellman).
     * Computes shared public key from secret key A and public key B.
     * Checks: 1) secret key validity 2) shared key is on-curve.
     * Does NOT hash the result.
     * @param isCompressed whether to return compact (default), or full key
     * @returns shared public key
     */
    function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {
        if (isProbPub(secretKeyA) === true)
            throw new Error('first arg must be private key');
        if (isProbPub(publicKeyB) === false)
            throw new Error('second arg must be public key');
        const s = _normFnElement(Fn, secretKeyA);
        const b = Point.fromHex(publicKeyB); // checks for being on-curve
        return b.multiply(s).toBytes(isCompressed);
    }
    const utils = {
        isValidSecretKey,
        isValidPublicKey,
        randomSecretKey,
        // TODO: remove
        isValidPrivateKey: isValidSecretKey,
        randomPrivateKey: randomSecretKey,
        normPrivateKeyToScalar: (key) => _normFnElement(Fn, key),
        precompute(windowSize = 8, point = Point.BASE) {
            return point.precompute(windowSize, false);
        },
    };
    return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point, utils, lengths });
}
/**
 * Creates ECDSA signing interface for given elliptic curve `Point` and `hash` function.
 * We need `hash` for 2 features:
 * 1. Message prehash-ing. NOT used if `sign` / `verify` are called with `prehash: false`
 * 2. k generation in `sign`, using HMAC-drbg(hash)
 *
 * ECDSAOpts are only rarely needed.
 *
 * @example
 * ```js
 * const p256_Point = weierstrass(...);
 * const p256_sha256 = ecdsa(p256_Point, sha256);
 * const p256_sha224 = ecdsa(p256_Point, sha224);
 * const p256_sha224_r = ecdsa(p256_Point, sha224, { randomBytes: (length) => { ... } });
 * ```
 */
export function ecdsa(Point, hash, ecdsaOpts = {}) {
    ahash(hash);
    _validateObject(ecdsaOpts, {}, {
        hmac: 'function',
        lowS: 'boolean',
        randomBytes: 'function',
        bits2int: 'function',
        bits2int_modN: 'function',
    });
    const randomBytes = ecdsaOpts.randomBytes || randomBytesWeb;
    const hmac = ecdsaOpts.hmac ||
        ((key, ...msgs) => nobleHmac(hash, key, concatBytes(...msgs)));
    const { Fp, Fn } = Point;
    const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;
    const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);
    const defaultSigOpts = {
        prehash: false,
        lowS: typeof ecdsaOpts.lowS === 'boolean' ? ecdsaOpts.lowS : false,
        format: undefined, //'compact' as ECDSASigFormat,
        extraEntropy: false,
    };
    const defaultSigOpts_format = 'compact';
    function isBiggerThanHalfOrder(number) {
        const HALF = CURVE_ORDER >> _1n;
        return number > HALF;
    }
    function validateRS(title, num) {
        if (!Fn.isValidNot0(num))
            throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);
        return num;
    }
    function validateSigLength(bytes, format) {
        validateSigFormat(format);
        const size = lengths.signature;
        const sizer = format === 'compact' ? size : format === 'recovered' ? size + 1 : undefined;
        return abytes(bytes, sizer, `${format} signature`);
    }
    /**
     * ECDSA signature with its (r, s) properties. Supports compact, recovered & DER representations.
     */
    class Signature {
        constructor(r, s, recovery) {
            this.r = validateRS('r', r); // r in [1..N-1];
            this.s = validateRS('s', s); // s in [1..N-1];
            if (recovery != null)
                this.recovery = recovery;
            Object.freeze(this);
        }
        static fromBytes(bytes, format = defaultSigOpts_format) {
            validateSigLength(bytes, format);
            let recid;
            if (format === 'der') {
                const { r, s } = DER.toSig(abytes(bytes));
                return new Signature(r, s);
            }
            if (format === 'recovered') {
                recid = bytes[0];
                format = 'compact';
                bytes = bytes.subarray(1);
            }
            const L = Fn.BYTES;
            const r = bytes.subarray(0, L);
            const s = bytes.subarray(L, L * 2);
            return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);
        }
        static fromHex(hex, format) {
            return this.fromBytes(hexToBytes(hex), format);
        }
        addRecoveryBit(recovery) {
            return new Signature(this.r, this.s, recovery);
        }
        recoverPublicKey(messageHash) {
            const FIELD_ORDER = Fp.ORDER;
            const { r, s, recovery: rec } = this;
            if (rec == null || ![0, 1, 2, 3].includes(rec))
                throw new Error('recovery id invalid');
            // ECDSA recovery is hard for cofactor > 1 curves.
            // In sign, `r = q.x mod n`, and here we recover q.x from r.
            // While recovering q.x >= n, we need to add r+n for cofactor=1 curves.
            // However, for cofactor>1, r+n may not get q.x:
            // r+n*i would need to be done instead where i is unknown.
            // To easily get i, we either need to:
            // a. increase amount of valid recid values (4, 5...); OR
            // b. prohibit non-prime-order signatures (recid > 1).
            const hasCofactor = CURVE_ORDER * _2n < FIELD_ORDER;
            if (hasCofactor && rec > 1)
                throw new Error('recovery id is ambiguous for h>1 curve');
            const radj = rec === 2 || rec === 3 ? r + CURVE_ORDER : r;
            if (!Fp.isValid(radj))
                throw new Error('recovery id 2 or 3 invalid');
            const x = Fp.toBytes(radj);
            const R = Point.fromBytes(concatBytes(pprefix((rec & 1) === 0), x));
            const ir = Fn.inv(radj); // r^-1
            const h = bits2int_modN(ensureBytes('msgHash', messageHash)); // Truncate hash
            const u1 = Fn.create(-h * ir); // -hr^-1
            const u2 = Fn.create(s * ir); // sr^-1
            // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1). unsafe is fine: there is no private data.
            const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));
            if (Q.is0())
                throw new Error('point at infinify');
            Q.assertValidity();
            return Q;
        }
        // Signatures should be low-s, to prevent malleability.
        hasHighS() {
            return isBiggerThanHalfOrder(this.s);
        }
        toBytes(format = defaultSigOpts_format) {
            validateSigFormat(format);
            if (format === 'der')
                return hexToBytes(DER.hexFromSig(this));
            const r = Fn.toBytes(this.r);
            const s = Fn.toBytes(this.s);
            if (format === 'recovered') {
                if (this.recovery == null)
                    throw new Error('recovery bit must be present');
                return concatBytes(Uint8Array.of(this.recovery), r, s);
            }
            return concatBytes(r, s);
        }
        toHex(format) {
            return bytesToHex(this.toBytes(format));
        }
        // TODO: remove
        assertValidity() { }
        static fromCompact(hex) {
            return Signature.fromBytes(ensureBytes('sig', hex), 'compact');
        }
        static fromDER(hex) {
            return Signature.fromBytes(ensureBytes('sig', hex), 'der');
        }
        normalizeS() {
            return this.hasHighS() ? new Signature(this.r, Fn.neg(this.s), this.recovery) : this;
        }
        toDERRawBytes() {
            return this.toBytes('der');
        }
        toDERHex() {
            return bytesToHex(this.toBytes('der'));
        }
        toCompactRawBytes() {
            return this.toBytes('compact');
        }
        toCompactHex() {
            return bytesToHex(this.toBytes('compact'));
        }
    }
    // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.
    // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.
    // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.
    // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors
    const bits2int = ecdsaOpts.bits2int ||
        function bits2int_def(bytes) {
            // Our custom check "just in case", for protection against DoS
            if (bytes.length > 8192)
                throw new Error('input is too large');
            // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)
            // for some cases, since bytes.length * 8 is not actual bitLength.
            const num = bytesToNumberBE(bytes); // check for == u8 done here
            const delta = bytes.length * 8 - fnBits; // truncate to nBitLength leftmost bits
            return delta > 0 ? num >> BigInt(delta) : num;
        };
    const bits2int_modN = ecdsaOpts.bits2int_modN ||
        function bits2int_modN_def(bytes) {
            return Fn.create(bits2int(bytes)); // can't use bytesToNumberBE here
        };
    // Pads output with zero as per spec
    const ORDER_MASK = bitMask(fnBits);
    /** Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. */
    function int2octets(num) {
        // IMPORTANT: the check ensures working for case `Fn.BYTES != Fn.BITS * 8`
        aInRange('num < 2^' + fnBits, num, _0n, ORDER_MASK);
        return Fn.toBytes(num);
    }
    function validateMsgAndHash(message, prehash) {
        abytes(message, undefined, 'message');
        return prehash ? abytes(hash(message), undefined, 'prehashed message') : message;
    }
    /**
     * Steps A, D of RFC6979 3.2.
     * Creates RFC6979 seed; converts msg/privKey to numbers.
     * Used only in sign, not in verify.
     *
     * Warning: we cannot assume here that message has same amount of bytes as curve order,
     * this will be invalid at least for P521. Also it can be bigger for P224 + SHA256.
     */
    function prepSig(message, privateKey, opts) {
        if (['recovered', 'canonical'].some((k) => k in opts))
            throw new Error('sign() legacy options not supported');
        const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);
        message = validateMsgAndHash(message, prehash); // RFC6979 3.2 A: h1 = H(m)
        // We can't later call bits2octets, since nested bits2int is broken for curves
        // with fnBits % 8 !== 0. Because of that, we unwrap it here as int2octets call.
        // const bits2octets = (bits) => int2octets(bits2int_modN(bits))
        const h1int = bits2int_modN(message);
        const d = _normFnElement(Fn, privateKey); // validate secret key, convert to bigint
        const seedArgs = [int2octets(d), int2octets(h1int)];
        // extraEntropy. RFC6979 3.6: additional k' (optional).
        if (extraEntropy != null && extraEntropy !== false) {
            // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')
            // gen random bytes OR pass as-is
            const e = extraEntropy === true ? randomBytes(lengths.secretKey) : extraEntropy;
            seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes
        }
        const seed = concatBytes(...seedArgs); // Step D of RFC6979 3.2
        const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash!
        // Converts signature params into point w r/s, checks result for validity.
        // To transform k => Signature:
        // q = k⋅G
        // r = q.x mod n
        // s = k^-1(m + rd) mod n
        // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to
        // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:
        // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT
        function k2sig(kBytes) {
            // RFC 6979 Section 3.2, step 3: k = bits2int(T)
            // Important: all mod() calls here must be done over N
            const k = bits2int(kBytes); // mod n, not mod p
            if (!Fn.isValidNot0(k))
                return; // Valid scalars (including k) must be in 1..N-1
            const ik = Fn.inv(k); // k^-1 mod n
            const q = Point.BASE.multiply(k).toAffine(); // q = k⋅G
            const r = Fn.create(q.x); // r = q.x mod n
            if (r === _0n)
                return;
            const s = Fn.create(ik * Fn.create(m + r * d)); // Not using blinding here, see comment above
            if (s === _0n)
                return;
            let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n)
            let normS = s;
            if (lowS && isBiggerThanHalfOrder(s)) {
                normS = Fn.neg(s); // if lowS was passed, ensure s is always
                recovery ^= 1; // // in the bottom half of N
            }
            return new Signature(r, normS, recovery); // use normS, not s
        }
        return { seed, k2sig };
    }
    /**
     * Signs message hash with a secret key.
     *
     * ```
     * sign(m, d) where
     *   k = rfc6979_hmac_drbg(m, d)
     *   (x, y) = G × k
     *   r = x mod n
     *   s = (m + dr) / k mod n
     * ```
     */
    function sign(message, secretKey, opts = {}) {
        message = ensureBytes('message', message);
        const { seed, k2sig } = prepSig(message, secretKey, opts); // Steps A, D of RFC6979 3.2.
        const drbg = createHmacDrbg(hash.outputLen, Fn.BYTES, hmac);
        const sig = drbg(seed, k2sig); // Steps B, C, D, E, F, G
        return sig;
    }
    function tryParsingSig(sg) {
        // Try to deduce format
        let sig = undefined;
        const isHex = typeof sg === 'string' || isBytes(sg);
        const isObj = !isHex &&
            sg !== null &&
            typeof sg === 'object' &&
            typeof sg.r === 'bigint' &&
            typeof sg.s === 'bigint';
        if (!isHex && !isObj)
            throw new Error('invalid signature, expected Uint8Array, hex string or Signature instance');
        if (isObj) {
            sig = new Signature(sg.r, sg.s);
        }
        else if (isHex) {
            try {
                sig = Signature.fromBytes(ensureBytes('sig', sg), 'der');
            }
            catch (derError) {
                if (!(derError instanceof DER.Err))
                    throw derError;
            }
            if (!sig) {
                try {
                    sig = Signature.fromBytes(ensureBytes('sig', sg), 'compact');
                }
                catch (error) {
                    return false;
                }
            }
        }
        if (!sig)
            return false;
        return sig;
    }
    /**
     * Verifies a signature against message and public key.
     * Rejects lowS signatures by default: see {@link ECDSAVerifyOpts}.
     * Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:
     *
     * ```
     * verify(r, s, h, P) where
     *   u1 = hs^-1 mod n
     *   u2 = rs^-1 mod n
     *   R = u1⋅G + u2⋅P
     *   mod(R.x, n) == r
     * ```
     */
    function verify(signature, message, publicKey, opts = {}) {
        const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);
        publicKey = ensureBytes('publicKey', publicKey);
        message = validateMsgAndHash(ensureBytes('message', message), prehash);
        if ('strict' in opts)
            throw new Error('options.strict was renamed to lowS');
        const sig = format === undefined
            ? tryParsingSig(signature)
            : Signature.fromBytes(ensureBytes('sig', signature), format);
        if (sig === false)
            return false;
        try {
            const P = Point.fromBytes(publicKey);
            if (lowS && sig.hasHighS())
                return false;
            const { r, s } = sig;
            const h = bits2int_modN(message); // mod n, not mod p
            const is = Fn.inv(s); // s^-1 mod n
            const u1 = Fn.create(h * is); // u1 = hs^-1 mod n
            const u2 = Fn.create(r * is); // u2 = rs^-1 mod n
            const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2)); // u1⋅G + u2⋅P
            if (R.is0())
                return false;
            const v = Fn.create(R.x); // v = r.x mod n
            return v === r;
        }
        catch (e) {
            return false;
        }
    }
    function recoverPublicKey(signature, message, opts = {}) {
        const { prehash } = validateSigOpts(opts, defaultSigOpts);
        message = validateMsgAndHash(message, prehash);
        return Signature.fromBytes(signature, 'recovered').recoverPublicKey(message).toBytes();
    }
    return Object.freeze({
        keygen,
        getPublicKey,
        getSharedSecret,
        utils,
        lengths,
        Point,
        sign,
        verify,
        recoverPublicKey,
        Signature,
        hash,
    });
}
/** @deprecated use `weierstrass` in newer releases */
export function weierstrassPoints(c) {
    const { CURVE, curveOpts } = _weierstrass_legacy_opts_to_new(c);
    const Point = weierstrassN(CURVE, curveOpts);
    return _weierstrass_new_output_to_legacy(c, Point);
}
function _weierstrass_legacy_opts_to_new(c) {
    const CURVE = {
        a: c.a,
        b: c.b,
        p: c.Fp.ORDER,
        n: c.n,
        h: c.h,
        Gx: c.Gx,
        Gy: c.Gy,
    };
    const Fp = c.Fp;
    let allowedLengths = c.allowedPrivateKeyLengths
        ? Array.from(new Set(c.allowedPrivateKeyLengths.map((l) => Math.ceil(l / 2))))
        : undefined;
    const Fn = Field(CURVE.n, {
        BITS: c.nBitLength,
        allowedLengths: allowedLengths,
        modFromBytes: c.wrapPrivateKey,
    });
    const curveOpts = {
        Fp,
        Fn,
        allowInfinityPoint: c.allowInfinityPoint,
        endo: c.endo,
        isTorsionFree: c.isTorsionFree,
        clearCofactor: c.clearCofactor,
        fromBytes: c.fromBytes,
        toBytes: c.toBytes,
    };
    return { CURVE, curveOpts };
}
function _ecdsa_legacy_opts_to_new(c) {
    const { CURVE, curveOpts } = _weierstrass_legacy_opts_to_new(c);
    const ecdsaOpts = {
        hmac: c.hmac,
        randomBytes: c.randomBytes,
        lowS: c.lowS,
        bits2int: c.bits2int,
        bits2int_modN: c.bits2int_modN,
    };
    return { CURVE, curveOpts, hash: c.hash, ecdsaOpts };
}
export function _legacyHelperEquat(Fp, a, b) {
    /**
     * y² = x³ + ax + b: Short weierstrass curve formula. Takes x, returns y².
     * @returns y²
     */
    function weierstrassEquation(x) {
        const x2 = Fp.sqr(x); // x * x
        const x3 = Fp.mul(x2, x); // x² * x
        return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x³ + a * x + b
    }
    return weierstrassEquation;
}
function _weierstrass_new_output_to_legacy(c, Point) {
    const { Fp, Fn } = Point;
    function isWithinCurveOrder(num) {
        return inRange(num, _1n, Fn.ORDER);
    }
    const weierstrassEquation = _legacyHelperEquat(Fp, c.a, c.b);
    return Object.assign({}, {
        CURVE: c,
        Point: Point,
        ProjectivePoint: Point,
        normPrivateKeyToScalar: (key) => _normFnElement(Fn, key),
        weierstrassEquation,
        isWithinCurveOrder,
    });
}
function _ecdsa_new_output_to_legacy(c, _ecdsa) {
    const Point = _ecdsa.Point;
    return Object.assign({}, _ecdsa, {
        ProjectivePoint: Point,
        CURVE: Object.assign({}, c, nLength(Point.Fn.ORDER, Point.Fn.BITS)),
    });
}
// _ecdsa_legacy
export function weierstrass(c) {
    const { CURVE, curveOpts, hash, ecdsaOpts } = _ecdsa_legacy_opts_to_new(c);
    const Point = weierstrassN(CURVE, curveOpts);
    const signs = ecdsa(Point, hash, ecdsaOpts);
    return _ecdsa_new_output_to_legacy(c, signs);
}
//# sourceMappingURL=weierstrass.js.map{
  "type": "module",
  "sideEffects": false
}
/**
 * SECG secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).
 *
 * Belongs to Koblitz curves: it has efficiently-computable GLV endomorphism ψ,
 * check out {@link EndomorphismOpts}. Seems to be rigid (not backdoored).
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { sha256 } from '@noble/hashes/sha2.js';
import { randomBytes } from '@noble/hashes/utils.js';
import { createCurve } from "./_shortw_utils.js";
import { createHasher, isogenyMap, } from "./abstract/hash-to-curve.js";
import { Field, mapHashToField, mod, pow2 } from "./abstract/modular.js";
import { _normFnElement, mapToCurveSimpleSWU, } from "./abstract/weierstrass.js";
import { bytesToNumberBE, concatBytes, ensureBytes, inRange, numberToBytesBE, utf8ToBytes, } from "./utils.js";
// Seems like generator was produced from some seed:
// `Point.BASE.multiply(Point.Fn.inv(2n, N)).toAffine().x`
// // gives short x 0x3b78ce563f89a0ed9414f5aa28ad0d96d6795f9c63n
const secp256k1_CURVE = {
    p: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'),
    n: BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'),
    h: BigInt(1),
    a: BigInt(0),
    b: BigInt(7),
    Gx: BigInt('0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'),
    Gy: BigInt('0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8'),
};
const secp256k1_ENDO = {
    beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),
    basises: [
        [BigInt('0x3086d221a7d46bcde86c90e49284eb15'), -BigInt('0xe4437ed6010e88286f547fa90abfe4c3')],
        [BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'), BigInt('0x3086d221a7d46bcde86c90e49284eb15')],
    ],
};
const _0n = /* @__PURE__ */ BigInt(0);
const _1n = /* @__PURE__ */ BigInt(1);
const _2n = /* @__PURE__ */ BigInt(2);
/**
 * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.
 * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]
 */
function sqrtMod(y) {
    const P = secp256k1_CURVE.p;
    // prettier-ignore
    const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
    // prettier-ignore
    const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
    const b2 = (y * y * y) % P; // x^3, 11
    const b3 = (b2 * b2 * y) % P; // x^7
    const b6 = (pow2(b3, _3n, P) * b3) % P;
    const b9 = (pow2(b6, _3n, P) * b3) % P;
    const b11 = (pow2(b9, _2n, P) * b2) % P;
    const b22 = (pow2(b11, _11n, P) * b11) % P;
    const b44 = (pow2(b22, _22n, P) * b22) % P;
    const b88 = (pow2(b44, _44n, P) * b44) % P;
    const b176 = (pow2(b88, _88n, P) * b88) % P;
    const b220 = (pow2(b176, _44n, P) * b44) % P;
    const b223 = (pow2(b220, _3n, P) * b3) % P;
    const t1 = (pow2(b223, _23n, P) * b22) % P;
    const t2 = (pow2(t1, _6n, P) * b2) % P;
    const root = pow2(t2, _2n, P);
    if (!Fpk1.eql(Fpk1.sqr(root), y))
        throw new Error('Cannot find square root');
    return root;
}
const Fpk1 = Field(secp256k1_CURVE.p, { sqrt: sqrtMod });
/**
 * secp256k1 curve, ECDSA and ECDH methods.
 *
 * Field: `2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n`
 *
 * @example
 * ```js
 * import { secp256k1 } from '@noble/curves/secp256k1';
 * const { secretKey, publicKey } = secp256k1.keygen();
 * const msg = new TextEncoder().encode('hello');
 * const sig = secp256k1.sign(msg, secretKey);
 * const isValid = secp256k1.verify(sig, msg, publicKey) === true;
 * ```
 */
export const secp256k1 = createCurve({ ...secp256k1_CURVE, Fp: Fpk1, lowS: true, endo: secp256k1_ENDO }, sha256);
// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.
// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki
/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */
const TAGGED_HASH_PREFIXES = {};
function taggedHash(tag, ...messages) {
    let tagP = TAGGED_HASH_PREFIXES[tag];
    if (tagP === undefined) {
        const tagH = sha256(utf8ToBytes(tag));
        tagP = concatBytes(tagH, tagH);
        TAGGED_HASH_PREFIXES[tag] = tagP;
    }
    return sha256(concatBytes(tagP, ...messages));
}
// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03
const pointToBytes = (point) => point.toBytes(true).slice(1);
const Pointk1 = /* @__PURE__ */ (() => secp256k1.Point)();
const hasEven = (y) => y % _2n === _0n;
// Calculate point, scalar and bytes
function schnorrGetExtPubKey(priv) {
    const { Fn, BASE } = Pointk1;
    const d_ = _normFnElement(Fn, priv);
    const p = BASE.multiply(d_); // P = d'⋅G; 0 < d' < n check is done inside
    const scalar = hasEven(p.y) ? d_ : Fn.neg(d_);
    return { scalar, bytes: pointToBytes(p) };
}
/**
 * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.
 * @returns valid point checked for being on-curve
 */
function lift_x(x) {
    const Fp = Fpk1;
    if (!Fp.isValidNot0(x))
        throw new Error('invalid x: Fail if x ≥ p');
    const xx = Fp.create(x * x);
    const c = Fp.create(xx * x + BigInt(7)); // Let c = x³ + 7 mod p.
    let y = Fp.sqrt(c); // Let y = c^(p+1)/4 mod p. Same as sqrt().
    // Return the unique point P such that x(P) = x and
    // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.
    if (!hasEven(y))
        y = Fp.neg(y);
    const p = Pointk1.fromAffine({ x, y });
    p.assertValidity();
    return p;
}
const num = bytesToNumberBE;
/**
 * Create tagged hash, convert it to bigint, reduce modulo-n.
 */
function challenge(...args) {
    return Pointk1.Fn.create(num(taggedHash('BIP0340/challenge', ...args)));
}
/**
 * Schnorr public key is just `x` coordinate of Point as per BIP340.
 */
function schnorrGetPublicKey(secretKey) {
    return schnorrGetExtPubKey(secretKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G)
}
/**
 * Creates Schnorr signature as per BIP340. Verifies itself before returning anything.
 * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous.
 */
function schnorrSign(message, secretKey, auxRand = randomBytes(32)) {
    const { Fn } = Pointk1;
    const m = ensureBytes('message', message);
    const { bytes: px, scalar: d } = schnorrGetExtPubKey(secretKey); // checks for isWithinCurveOrder
    const a = ensureBytes('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array
    const t = Fn.toBytes(d ^ num(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a)
    const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m)
    // Let k' = int(rand) mod n. Fail if k' = 0. Let R = k'⋅G
    const { bytes: rx, scalar: k } = schnorrGetExtPubKey(rand);
    const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.
    const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n).
    sig.set(rx, 0);
    sig.set(Fn.toBytes(Fn.create(k + e * d)), 32);
    // If Verify(bytes(P), m, sig) (see below) returns failure, abort
    if (!schnorrVerify(sig, m, px))
        throw new Error('sign: Invalid signature produced');
    return sig;
}
/**
 * Verifies Schnorr signature.
 * Will swallow errors & return false except for initial type validation of arguments.
 */
function schnorrVerify(signature, message, publicKey) {
    const { Fn, BASE } = Pointk1;
    const sig = ensureBytes('signature', signature, 64);
    const m = ensureBytes('message', message);
    const pub = ensureBytes('publicKey', publicKey, 32);
    try {
        const P = lift_x(num(pub)); // P = lift_x(int(pk)); fail if that fails
        const r = num(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r ≥ p.
        if (!inRange(r, _1n, secp256k1_CURVE.p))
            return false;
        const s = num(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n.
        if (!inRange(s, _1n, secp256k1_CURVE.n))
            return false;
        // int(challenge(bytes(r)||bytes(P)||m))%n
        const e = challenge(Fn.toBytes(r), pointToBytes(P), m);
        // R = s⋅G - e⋅P, where -eP == (n-e)P
        const R = BASE.multiplyUnsafe(s).add(P.multiplyUnsafe(Fn.neg(e)));
        const { x, y } = R.toAffine();
        // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r.
        if (R.is0() || !hasEven(y) || x !== r)
            return false;
        return true;
    }
    catch (error) {
        return false;
    }
}
/**
 * Schnorr signatures over secp256k1.
 * https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki
 * @example
 * ```js
 * import { schnorr } from '@noble/curves/secp256k1';
 * const { secretKey, publicKey } = schnorr.keygen();
 * // const publicKey = schnorr.getPublicKey(secretKey);
 * const msg = new TextEncoder().encode('hello');
 * const sig = schnorr.sign(msg, secretKey);
 * const isValid = schnorr.verify(sig, msg, publicKey);
 * ```
 */
export const schnorr = /* @__PURE__ */ (() => {
    const size = 32;
    const seedLength = 48;
    const randomSecretKey = (seed = randomBytes(seedLength)) => {
        return mapHashToField(seed, secp256k1_CURVE.n);
    };
    // TODO: remove
    secp256k1.utils.randomSecretKey;
    function keygen(seed) {
        const secretKey = randomSecretKey(seed);
        return { secretKey, publicKey: schnorrGetPublicKey(secretKey) };
    }
    return {
        keygen,
        getPublicKey: schnorrGetPublicKey,
        sign: schnorrSign,
        verify: schnorrVerify,
        Point: Pointk1,
        utils: {
            randomSecretKey: randomSecretKey,
            randomPrivateKey: randomSecretKey,
            taggedHash,
            // TODO: remove
            lift_x,
            pointToBytes,
            numberToBytesBE,
            bytesToNumberBE,
            mod,
        },
        lengths: {
            secretKey: size,
            publicKey: size,
            publicKeyHasPrefix: false,
            signature: size * 2,
            seed: seedLength,
        },
    };
})();
const isoMap = /* @__PURE__ */ (() => isogenyMap(Fpk1, [
    // xNum
    [
        '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7',
        '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581',
        '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262',
        '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c',
    ],
    // xDen
    [
        '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b',
        '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14',
        '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1
    ],
    // yNum
    [
        '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c',
        '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3',
        '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931',
        '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84',
    ],
    // yDen
    [
        '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b',
        '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573',
        '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f',
        '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1
    ],
].map((i) => i.map((j) => BigInt(j)))))();
const mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fpk1, {
    A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),
    B: BigInt('1771'),
    Z: Fpk1.create(BigInt('-11')),
}))();
/** Hashing / encoding to secp256k1 points / field. RFC 9380 methods. */
export const secp256k1_hasher = /* @__PURE__ */ (() => createHasher(secp256k1.Point, (scalars) => {
    const { x, y } = mapSWU(Fpk1.create(scalars[0]));
    return isoMap(x, y);
}, {
    DST: 'secp256k1_XMD:SHA-256_SSWU_RO_',
    encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_',
    p: Fpk1.ORDER,
    m: 1,
    k: 128,
    expand: 'xmd',
    hash: sha256,
}))();
/** @deprecated use `import { secp256k1_hasher } from '@noble/curves/secp256k1.js';` */
export const hashToCurve = /* @__PURE__ */ (() => secp256k1_hasher.hashToCurve)();
/** @deprecated use `import { secp256k1_hasher } from '@noble/curves/secp256k1.js';` */
export const encodeToCurve = /* @__PURE__ */ (() => secp256k1_hasher.encodeToCurve)();
//# sourceMappingURL=secp256k1.js.map/**
 * Hex, bytes and number utilities.
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { abytes as abytes_, bytesToHex as bytesToHex_, concatBytes as concatBytes_, hexToBytes as hexToBytes_, isBytes as isBytes_, } from '@noble/hashes/utils.js';
export { abytes, anumber, bytesToHex, bytesToUtf8, concatBytes, hexToBytes, isBytes, randomBytes, utf8ToBytes, } from '@noble/hashes/utils.js';
const _0n = /* @__PURE__ */ BigInt(0);
const _1n = /* @__PURE__ */ BigInt(1);
export function abool(title, value) {
    if (typeof value !== 'boolean')
        throw new Error(title + ' boolean expected, got ' + value);
}
// tmp name until v2
export function _abool2(value, title = '') {
    if (typeof value !== 'boolean') {
        const prefix = title && `"${title}"`;
        throw new Error(prefix + 'expected boolean, got type=' + typeof value);
    }
    return value;
}
// tmp name until v2
/** Asserts something is Uint8Array. */
export function _abytes2(value, length, title = '') {
    const bytes = isBytes_(value);
    const len = value?.length;
    const needsLen = length !== undefined;
    if (!bytes || (needsLen && len !== length)) {
        const prefix = title && `"${title}" `;
        const ofLen = needsLen ? ` of length ${length}` : '';
        const got = bytes ? `length=${len}` : `type=${typeof value}`;
        throw new Error(prefix + 'expected Uint8Array' + ofLen + ', got ' + got);
    }
    return value;
}
// Used in weierstrass, der
export function numberToHexUnpadded(num) {
    const hex = num.toString(16);
    return hex.length & 1 ? '0' + hex : hex;
}
export function hexToNumber(hex) {
    if (typeof hex !== 'string')
        throw new Error('hex string expected, got ' + typeof hex);
    return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian
}
// BE: Big Endian, LE: Little Endian
export function bytesToNumberBE(bytes) {
    return hexToNumber(bytesToHex_(bytes));
}
export function bytesToNumberLE(bytes) {
    abytes_(bytes);
    return hexToNumber(bytesToHex_(Uint8Array.from(bytes).reverse()));
}
export function numberToBytesBE(n, len) {
    return hexToBytes_(n.toString(16).padStart(len * 2, '0'));
}
export function numberToBytesLE(n, len) {
    return numberToBytesBE(n, len).reverse();
}
// Unpadded, rarely used
export function numberToVarBytesBE(n) {
    return hexToBytes_(numberToHexUnpadded(n));
}
/**
 * Takes hex string or Uint8Array, converts to Uint8Array.
 * Validates output length.
 * Will throw error for other types.
 * @param title descriptive title for an error e.g. 'secret key'
 * @param hex hex string or Uint8Array
 * @param expectedLength optional, will compare to result array's length
 * @returns
 */
export function ensureBytes(title, hex, expectedLength) {
    let res;
    if (typeof hex === 'string') {
        try {
            res = hexToBytes_(hex);
        }
        catch (e) {
            throw new Error(title + ' must be hex string or Uint8Array, cause: ' + e);
        }
    }
    else if (isBytes_(hex)) {
        // Uint8Array.from() instead of hash.slice() because node.js Buffer
        // is instance of Uint8Array, and its slice() creates **mutable** copy
        res = Uint8Array.from(hex);
    }
    else {
        throw new Error(title + ' must be hex string or Uint8Array');
    }
    const len = res.length;
    if (typeof expectedLength === 'number' && len !== expectedLength)
        throw new Error(title + ' of length ' + expectedLength + ' expected, got ' + len);
    return res;
}
// Compares 2 u8a-s in kinda constant time
export function equalBytes(a, b) {
    if (a.length !== b.length)
        return false;
    let diff = 0;
    for (let i = 0; i < a.length; i++)
        diff |= a[i] ^ b[i];
    return diff === 0;
}
/**
 * Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,
 * and Buffer#slice creates mutable copy. Never use Buffers!
 */
export function copyBytes(bytes) {
    return Uint8Array.from(bytes);
}
/**
 * Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols
 * Should be safe to use for things expected to be ASCII.
 * Returns exact same result as utf8ToBytes for ASCII or throws.
 */
export function asciiToBytes(ascii) {
    return Uint8Array.from(ascii, (c, i) => {
        const charCode = c.charCodeAt(0);
        if (c.length !== 1 || charCode > 127) {
            throw new Error(`string contains non-ASCII character "${ascii[i]}" with code ${charCode} at position ${i}`);
        }
        return charCode;
    });
}
/**
 * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
 */
// export const utf8ToBytes: typeof utf8ToBytes_ = utf8ToBytes_;
/**
 * Converts bytes to string using UTF8 encoding.
 * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'
 */
// export const bytesToUtf8: typeof bytesToUtf8_ = bytesToUtf8_;
// Is positive bigint
const isPosBig = (n) => typeof n === 'bigint' && _0n <= n;
export function inRange(n, min, max) {
    return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
}
/**
 * Asserts min <= n < max. NOTE: It's < max and not <= max.
 * @example
 * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)
 */
export function aInRange(title, n, min, max) {
    // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?
    // consider P=256n, min=0n, max=P
    // - a for min=0 would require -1:          `inRange('x', x, -1n, P)`
    // - b would commonly require subtraction:  `inRange('x', x, 0n, P - 1n)`
    // - our way is the cleanest:               `inRange('x', x, 0n, P)
    if (!inRange(n, min, max))
        throw new Error('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);
}
// Bit operations
/**
 * Calculates amount of bits in a bigint.
 * Same as `n.toString(2).length`
 * TODO: merge with nLength in modular
 */
export function bitLen(n) {
    let len;
    for (len = 0; n > _0n; n >>= _1n, len += 1)
        ;
    return len;
}
/**
 * Gets single bit at position.
 * NOTE: first bit position is 0 (same as arrays)
 * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`
 */
export function bitGet(n, pos) {
    return (n >> BigInt(pos)) & _1n;
}
/**
 * Sets single bit at position.
 */
export function bitSet(n, pos, value) {
    return n | ((value ? _1n : _0n) << BigInt(pos));
}
/**
 * Calculate mask for N bits. Not using ** operator with bigints because of old engines.
 * Same as BigInt(`0b${Array(i).fill('1').join('')}`)
 */
export const bitMask = (n) => (_1n << BigInt(n)) - _1n;
/**
 * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
 * @returns function that will call DRBG until 2nd arg returns something meaningful
 * @example
 *   const drbg = createHmacDRBG<Key>(32, 32, hmac);
 *   drbg(seed, bytesToKey); // bytesToKey must return Key or undefined
 */
export function createHmacDrbg(hashLen, qByteLen, hmacFn) {
    if (typeof hashLen !== 'number' || hashLen < 2)
        throw new Error('hashLen must be a number');
    if (typeof qByteLen !== 'number' || qByteLen < 2)
        throw new Error('qByteLen must be a number');
    if (typeof hmacFn !== 'function')
        throw new Error('hmacFn must be a function');
    // Step B, Step C: set hashLen to 8*ceil(hlen/8)
    const u8n = (len) => new Uint8Array(len); // creates Uint8Array
    const u8of = (byte) => Uint8Array.of(byte); // another shortcut
    let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
    let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same
    let i = 0; // Iterations counter, will throw when over 1000
    const reset = () => {
        v.fill(1);
        k.fill(0);
        i = 0;
    };
    const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)
    const reseed = (seed = u8n(0)) => {
        // HMAC-DRBG reseed() function. Steps D-G
        k = h(u8of(0x00), seed); // k = hmac(k || v || 0x00 || seed)
        v = h(); // v = hmac(k || v)
        if (seed.length === 0)
            return;
        k = h(u8of(0x01), seed); // k = hmac(k || v || 0x01 || seed)
        v = h(); // v = hmac(k || v)
    };
    const gen = () => {
        // HMAC-DRBG generate() function
        if (i++ >= 1000)
            throw new Error('drbg: tried 1000 values');
        let len = 0;
        const out = [];
        while (len < qByteLen) {
            v = h();
            const sl = v.slice();
            out.push(sl);
            len += v.length;
        }
        return concatBytes_(...out);
    };
    const genUntil = (seed, pred) => {
        reset();
        reseed(seed); // Steps D-G
        let res = undefined; // Step H: grind until k is in [1..n-1]
        while (!(res = pred(gen())))
            reseed();
        reset();
        return res;
    };
    return genUntil;
}
// Validating curves and fields
const validatorFns = {
    bigint: (val) => typeof val === 'bigint',
    function: (val) => typeof val === 'function',
    boolean: (val) => typeof val === 'boolean',
    string: (val) => typeof val === 'string',
    stringOrUint8Array: (val) => typeof val === 'string' || isBytes_(val),
    isSafeInteger: (val) => Number.isSafeInteger(val),
    array: (val) => Array.isArray(val),
    field: (val, object) => object.Fp.isValid(val),
    hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),
};
// type Record<K extends string | number | symbol, T> = { [P in K]: T; }
export function validateObject(object, validators, optValidators = {}) {
    const checkField = (fieldName, type, isOptional) => {
        const checkVal = validatorFns[type];
        if (typeof checkVal !== 'function')
            throw new Error('invalid validator function');
        const val = object[fieldName];
        if (isOptional && val === undefined)
            return;
        if (!checkVal(val, object)) {
            throw new Error('param ' + String(fieldName) + ' is invalid. Expected ' + type + ', got ' + val);
        }
    };
    for (const [fieldName, type] of Object.entries(validators))
        checkField(fieldName, type, false);
    for (const [fieldName, type] of Object.entries(optValidators))
        checkField(fieldName, type, true);
    return object;
}
// validate type tests
// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };
// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!
// // Should fail type-check
// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });
// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });
// const z3 = validateObject(o, { test: 'boolean', z: 'bug' });
// const z4 = validateObject(o, { a: 'boolean', z: 'bug' });
export function isHash(val) {
    return typeof val === 'function' && Number.isSafeInteger(val.outputLen);
}
export function _validateObject(object, fields, optFields = {}) {
    if (!object || typeof object !== 'object')
        throw new Error('expected valid options object');
    function checkField(fieldName, expectedType, isOpt) {
        const val = object[fieldName];
        if (isOpt && val === undefined)
            return;
        const current = typeof val;
        if (current !== expectedType || val === null)
            throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
    }
    Object.entries(fields).forEach(([k, v]) => checkField(k, v, false));
    Object.entries(optFields).forEach(([k, v]) => checkField(k, v, true));
}
/**
 * throws not implemented error
 */
export const notImplemented = () => {
    throw new Error('not implemented');
};
/**
 * Memoizes (caches) computation result.
 * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.
 */
export function memoized(fn) {
    const map = new WeakMap();
    return (arg, ...args) => {
        const val = map.get(arg);
        if (val !== undefined)
            return val;
        const computed = fn(arg, ...args);
        map.set(arg, computed);
        return computed;
    };
}
//# sourceMappingURL=utils.js.map/**
 * Internal Merkle-Damgard hash utils.
 * @module
 */
import { Hash, abytes, aexists, aoutput, clean, createView, toBytes } from "./utils.js";
/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */
export function setBigUint64(view, byteOffset, value, isLE) {
    if (typeof view.setBigUint64 === 'function')
        return view.setBigUint64(byteOffset, value, isLE);
    const _32n = BigInt(32);
    const _u32_max = BigInt(0xffffffff);
    const wh = Number((value >> _32n) & _u32_max);
    const wl = Number(value & _u32_max);
    const h = isLE ? 4 : 0;
    const l = isLE ? 0 : 4;
    view.setUint32(byteOffset + h, wh, isLE);
    view.setUint32(byteOffset + l, wl, isLE);
}
/** Choice: a ? b : c */
export function Chi(a, b, c) {
    return (a & b) ^ (~a & c);
}
/** Majority function, true if any two inputs is true. */
export function Maj(a, b, c) {
    return (a & b) ^ (a & c) ^ (b & c);
}
/**
 * Merkle-Damgard hash construction base class.
 * Could be used to create MD5, RIPEMD, SHA1, SHA2.
 */
export class HashMD extends Hash {
    constructor(blockLen, outputLen, padOffset, isLE) {
        super();
        this.finished = false;
        this.length = 0;
        this.pos = 0;
        this.destroyed = false;
        this.blockLen = blockLen;
        this.outputLen = outputLen;
        this.padOffset = padOffset;
        this.isLE = isLE;
        this.buffer = new Uint8Array(blockLen);
        this.view = createView(this.buffer);
    }
    update(data) {
        aexists(this);
        data = toBytes(data);
        abytes(data);
        const { view, buffer, blockLen } = this;
        const len = data.length;
        for (let pos = 0; pos < len;) {
            const take = Math.min(blockLen - this.pos, len - pos);
            // Fast path: we have at least one block in input, cast it to view and process
            if (take === blockLen) {
                const dataView = createView(data);
                for (; blockLen <= len - pos; pos += blockLen)
                    this.process(dataView, pos);
                continue;
            }
            buffer.set(data.subarray(pos, pos + take), this.pos);
            this.pos += take;
            pos += take;
            if (this.pos === blockLen) {
                this.process(view, 0);
                this.pos = 0;
            }
        }
        this.length += data.length;
        this.roundClean();
        return this;
    }
    digestInto(out) {
        aexists(this);
        aoutput(out, this);
        this.finished = true;
        // Padding
        // We can avoid allocation of buffer for padding completely if it
        // was previously not allocated here. But it won't change performance.
        const { buffer, view, blockLen, isLE } = this;
        let { pos } = this;
        // append the bit '1' to the message
        buffer[pos++] = 0b10000000;
        clean(this.buffer.subarray(pos));
        // we have less than padOffset left in buffer, so we cannot put length in
        // current block, need process it and pad again
        if (this.padOffset > blockLen - pos) {
            this.process(view, 0);
            pos = 0;
        }
        // Pad until full block byte with zeros
        for (let i = pos; i < blockLen; i++)
            buffer[i] = 0;
        // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that
        // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.
        // So we just write lowest 64 bits of that value.
        setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
        this.process(view, 0);
        const oview = createView(out);
        const len = this.outputLen;
        // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT
        if (len % 4)
            throw new Error('_sha2: outputLen should be aligned to 32bit');
        const outLen = len / 4;
        const state = this.get();
        if (outLen > state.length)
            throw new Error('_sha2: outputLen bigger than state');
        for (let i = 0; i < outLen; i++)
            oview.setUint32(4 * i, state[i], isLE);
    }
    digest() {
        const { buffer, outputLen } = this;
        this.digestInto(buffer);
        const res = buffer.slice(0, outputLen);
        this.destroy();
        return res;
    }
    _cloneInto(to) {
        to || (to = new this.constructor());
        to.set(...this.get());
        const { blockLen, buffer, length, finished, destroyed, pos } = this;
        to.destroyed = destroyed;
        to.finished = finished;
        to.length = length;
        to.pos = pos;
        if (length % blockLen)
            to.buffer.set(buffer);
        return to;
    }
    clone() {
        return this._cloneInto();
    }
}
/**
 * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.
 * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.
 */
/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */
export const SHA256_IV = /* @__PURE__ */ Uint32Array.from([
    0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
]);
/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */
export const SHA224_IV = /* @__PURE__ */ Uint32Array.from([
    0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,
]);
/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */
export const SHA384_IV = /* @__PURE__ */ Uint32Array.from([
    0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,
    0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,
]);
/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */
export const SHA512_IV = /* @__PURE__ */ Uint32Array.from([
    0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,
    0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,
]);
//# sourceMappingURL=_md.js.map/**
 * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.
 * @todo re-check https://issues.chromium.org/issues/42212588
 * @module
 */
const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
const _32n = /* @__PURE__ */ BigInt(32);
function fromBig(n, le = false) {
    if (le)
        return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };
    return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
}
function split(lst, le = false) {
    const len = lst.length;
    let Ah = new Uint32Array(len);
    let Al = new Uint32Array(len);
    for (let i = 0; i < len; i++) {
        const { h, l } = fromBig(lst[i], le);
        [Ah[i], Al[i]] = [h, l];
    }
    return [Ah, Al];
}
const toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);
// for Shift in [0, 32)
const shrSH = (h, _l, s) => h >>> s;
const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
// Right rotate for Shift in [1, 32)
const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));
const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
// Right rotate for Shift in (32, 64), NOTE: 32 is special case.
const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));
const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));
// Right rotate for shift===32 (just swaps l&h)
const rotr32H = (_h, l) => l;
const rotr32L = (h, _l) => h;
// Left rotate for Shift in [1, 32)
const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));
const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));
// Left rotate for Shift in (32, 64), NOTE: 32 is special case.
const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));
const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));
// JS uses 32-bit signed integers for bitwise operations which means we cannot
// simple take carry out of low bit sum by shift, we need to use division.
function add(Ah, Al, Bh, Bl) {
    const l = (Al >>> 0) + (Bl >>> 0);
    return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };
}
// Addition with more than 2 elements
const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;
const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;
const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;
// prettier-ignore
export { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig };
// prettier-ignore
const u64 = {
    fromBig, split, toBig,
    shrSH, shrSL,
    rotrSH, rotrSL, rotrBH, rotrBL,
    rotr32H, rotr32L,
    rotlSH, rotlSL, rotlBH, rotlBL,
    add, add3L, add3H, add4L, add4H, add5H, add5L,
};
export default u64;
//# sourceMappingURL=_u64.js.mapexport const crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;
//# sourceMappingURL=crypto.js.map/**
 * HMAC: RFC2104 message authentication code.
 * @module
 */
import { abytes, aexists, ahash, clean, Hash, toBytes } from "./utils.js";
export class HMAC extends Hash {
    constructor(hash, _key) {
        super();
        this.finished = false;
        this.destroyed = false;
        ahash(hash);
        const key = toBytes(_key);
        this.iHash = hash.create();
        if (typeof this.iHash.update !== 'function')
            throw new Error('Expected instance of class which extends utils.Hash');
        this.blockLen = this.iHash.blockLen;
        this.outputLen = this.iHash.outputLen;
        const blockLen = this.blockLen;
        const pad = new Uint8Array(blockLen);
        // blockLen can be bigger than outputLen
        pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
        for (let i = 0; i < pad.length; i++)
            pad[i] ^= 0x36;
        this.iHash.update(pad);
        // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone
        this.oHash = hash.create();
        // Undo internal XOR && apply outer XOR
        for (let i = 0; i < pad.length; i++)
            pad[i] ^= 0x36 ^ 0x5c;
        this.oHash.update(pad);
        clean(pad);
    }
    update(buf) {
        aexists(this);
        this.iHash.update(buf);
        return this;
    }
    digestInto(out) {
        aexists(this);
        abytes(out, this.outputLen);
        this.finished = true;
        this.iHash.digestInto(out);
        this.oHash.update(out);
        this.oHash.digestInto(out);
        this.destroy();
    }
    digest() {
        const out = new Uint8Array(this.oHash.outputLen);
        this.digestInto(out);
        return out;
    }
    _cloneInto(to) {
        // Create new instance without calling constructor since key already in state and we don't know it.
        to || (to = Object.create(Object.getPrototypeOf(this), {}));
        const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
        to = to;
        to.finished = finished;
        to.destroyed = destroyed;
        to.blockLen = blockLen;
        to.outputLen = outputLen;
        to.oHash = oHash._cloneInto(to.oHash);
        to.iHash = iHash._cloneInto(to.iHash);
        return to;
    }
    clone() {
        return this._cloneInto();
    }
    destroy() {
        this.destroyed = true;
        this.oHash.destroy();
        this.iHash.destroy();
    }
}
/**
 * HMAC: RFC2104 message authentication code.
 * @param hash - function that would be used e.g. sha256
 * @param key - message key
 * @param message - message data
 * @example
 * import { hmac } from '@noble/hashes/hmac';
 * import { sha256 } from '@noble/hashes/sha2';
 * const mac1 = hmac(sha256, 'key', 'message');
 */
export const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
hmac.create = (hash, key) => new HMAC(hash, key);
//# sourceMappingURL=hmac.js.map{
  "type": "module",
  "sideEffects": false,
  "browser": {
    "node:crypto": false
  },
  "node": {
    "./crypto": "./esm/cryptoNode.js"
  }
}
/**
 * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.
 * SHA256 is the fastest hash implementable in JS, even faster than Blake3.
 * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and
 * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).
 * @module
 */
import { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from "./_md.js";
import * as u64 from "./_u64.js";
import { clean, createHasher, rotr } from "./utils.js";
/**
 * Round constants:
 * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)
 */
// prettier-ignore
const SHA256_K = /* @__PURE__ */ Uint32Array.from([
    0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
    0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
    0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
    0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
    0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
    0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
    0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
    0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
]);
/** Reusable temporary buffer. "W" comes straight from spec. */
const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
export class SHA256 extends HashMD {
    constructor(outputLen = 32) {
        super(64, outputLen, 8, false);
        // We cannot use array here since array allows indexing by variable
        // which means optimizer/compiler cannot use registers.
        this.A = SHA256_IV[0] | 0;
        this.B = SHA256_IV[1] | 0;
        this.C = SHA256_IV[2] | 0;
        this.D = SHA256_IV[3] | 0;
        this.E = SHA256_IV[4] | 0;
        this.F = SHA256_IV[5] | 0;
        this.G = SHA256_IV[6] | 0;
        this.H = SHA256_IV[7] | 0;
    }
    get() {
        const { A, B, C, D, E, F, G, H } = this;
        return [A, B, C, D, E, F, G, H];
    }
    // prettier-ignore
    set(A, B, C, D, E, F, G, H) {
        this.A = A | 0;
        this.B = B | 0;
        this.C = C | 0;
        this.D = D | 0;
        this.E = E | 0;
        this.F = F | 0;
        this.G = G | 0;
        this.H = H | 0;
    }
    process(view, offset) {
        // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array
        for (let i = 0; i < 16; i++, offset += 4)
            SHA256_W[i] = view.getUint32(offset, false);
        for (let i = 16; i < 64; i++) {
            const W15 = SHA256_W[i - 15];
            const W2 = SHA256_W[i - 2];
            const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);
            const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);
            SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;
        }
        // Compression function main loop, 64 rounds
        let { A, B, C, D, E, F, G, H } = this;
        for (let i = 0; i < 64; i++) {
            const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
            const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
            const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
            const T2 = (sigma0 + Maj(A, B, C)) | 0;
            H = G;
            G = F;
            F = E;
            E = (D + T1) | 0;
            D = C;
            C = B;
            B = A;
            A = (T1 + T2) | 0;
        }
        // Add the compressed chunk to the current hash value
        A = (A + this.A) | 0;
        B = (B + this.B) | 0;
        C = (C + this.C) | 0;
        D = (D + this.D) | 0;
        E = (E + this.E) | 0;
        F = (F + this.F) | 0;
        G = (G + this.G) | 0;
        H = (H + this.H) | 0;
        this.set(A, B, C, D, E, F, G, H);
    }
    roundClean() {
        clean(SHA256_W);
    }
    destroy() {
        this.set(0, 0, 0, 0, 0, 0, 0, 0);
        clean(this.buffer);
    }
}
export class SHA224 extends SHA256 {
    constructor() {
        super(28);
        this.A = SHA224_IV[0] | 0;
        this.B = SHA224_IV[1] | 0;
        this.C = SHA224_IV[2] | 0;
        this.D = SHA224_IV[3] | 0;
        this.E = SHA224_IV[4] | 0;
        this.F = SHA224_IV[5] | 0;
        this.G = SHA224_IV[6] | 0;
        this.H = SHA224_IV[7] | 0;
    }
}
// SHA2-512 is slower than sha256 in js because u64 operations are slow.
// Round contants
// First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409
// prettier-ignore
const K512 = /* @__PURE__ */ (() => u64.split([
    '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',
    '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',
    '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',
    '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',
    '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',
    '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',
    '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',
    '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',
    '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',
    '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',
    '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',
    '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',
    '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',
    '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',
    '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',
    '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',
    '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',
    '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',
    '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',
    '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'
].map(n => BigInt(n))))();
const SHA512_Kh = /* @__PURE__ */ (() => K512[0])();
const SHA512_Kl = /* @__PURE__ */ (() => K512[1])();
// Reusable temporary buffers
const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
export class SHA512 extends HashMD {
    constructor(outputLen = 64) {
        super(128, outputLen, 16, false);
        // We cannot use array here since array allows indexing by variable
        // which means optimizer/compiler cannot use registers.
        // h -- high 32 bits, l -- low 32 bits
        this.Ah = SHA512_IV[0] | 0;
        this.Al = SHA512_IV[1] | 0;
        this.Bh = SHA512_IV[2] | 0;
        this.Bl = SHA512_IV[3] | 0;
        this.Ch = SHA512_IV[4] | 0;
        this.Cl = SHA512_IV[5] | 0;
        this.Dh = SHA512_IV[6] | 0;
        this.Dl = SHA512_IV[7] | 0;
        this.Eh = SHA512_IV[8] | 0;
        this.El = SHA512_IV[9] | 0;
        this.Fh = SHA512_IV[10] | 0;
        this.Fl = SHA512_IV[11] | 0;
        this.Gh = SHA512_IV[12] | 0;
        this.Gl = SHA512_IV[13] | 0;
        this.Hh = SHA512_IV[14] | 0;
        this.Hl = SHA512_IV[15] | 0;
    }
    // prettier-ignore
    get() {
        const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
        return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
    }
    // prettier-ignore
    set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
        this.Ah = Ah | 0;
        this.Al = Al | 0;
        this.Bh = Bh | 0;
        this.Bl = Bl | 0;
        this.Ch = Ch | 0;
        this.Cl = Cl | 0;
        this.Dh = Dh | 0;
        this.Dl = Dl | 0;
        this.Eh = Eh | 0;
        this.El = El | 0;
        this.Fh = Fh | 0;
        this.Fl = Fl | 0;
        this.Gh = Gh | 0;
        this.Gl = Gl | 0;
        this.Hh = Hh | 0;
        this.Hl = Hl | 0;
    }
    process(view, offset) {
        // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array
        for (let i = 0; i < 16; i++, offset += 4) {
            SHA512_W_H[i] = view.getUint32(offset);
            SHA512_W_L[i] = view.getUint32((offset += 4));
        }
        for (let i = 16; i < 80; i++) {
            // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)
            const W15h = SHA512_W_H[i - 15] | 0;
            const W15l = SHA512_W_L[i - 15] | 0;
            const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);
            const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);
            // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)
            const W2h = SHA512_W_H[i - 2] | 0;
            const W2l = SHA512_W_L[i - 2] | 0;
            const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);
            const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);
            // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];
            const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
            const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
            SHA512_W_H[i] = SUMh | 0;
            SHA512_W_L[i] = SUMl | 0;
        }
        let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
        // Compression function main loop, 80 rounds
        for (let i = 0; i < 80; i++) {
            // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)
            const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);
            const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);
            //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
            const CHIh = (Eh & Fh) ^ (~Eh & Gh);
            const CHIl = (El & Fl) ^ (~El & Gl);
            // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]
            // prettier-ignore
            const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
            const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
            const T1l = T1ll | 0;
            // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)
            const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);
            const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);
            const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);
            const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);
            Hh = Gh | 0;
            Hl = Gl | 0;
            Gh = Fh | 0;
            Gl = Fl | 0;
            Fh = Eh | 0;
            Fl = El | 0;
            ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
            Dh = Ch | 0;
            Dl = Cl | 0;
            Ch = Bh | 0;
            Cl = Bl | 0;
            Bh = Ah | 0;
            Bl = Al | 0;
            const All = u64.add3L(T1l, sigma0l, MAJl);
            Ah = u64.add3H(All, T1h, sigma0h, MAJh);
            Al = All | 0;
        }
        // Add the compressed chunk to the current hash value
        ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
        ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
        ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
        ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
        ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
        ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
        ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
        ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
        this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
    }
    roundClean() {
        clean(SHA512_W_H, SHA512_W_L);
    }
    destroy() {
        clean(this.buffer);
        this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
    }
}
export class SHA384 extends SHA512 {
    constructor() {
        super(48);
        this.Ah = SHA384_IV[0] | 0;
        this.Al = SHA384_IV[1] | 0;
        this.Bh = SHA384_IV[2] | 0;
        this.Bl = SHA384_IV[3] | 0;
        this.Ch = SHA384_IV[4] | 0;
        this.Cl = SHA384_IV[5] | 0;
        this.Dh = SHA384_IV[6] | 0;
        this.Dl = SHA384_IV[7] | 0;
        this.Eh = SHA384_IV[8] | 0;
        this.El = SHA384_IV[9] | 0;
        this.Fh = SHA384_IV[10] | 0;
        this.Fl = SHA384_IV[11] | 0;
        this.Gh = SHA384_IV[12] | 0;
        this.Gl = SHA384_IV[13] | 0;
        this.Hh = SHA384_IV[14] | 0;
        this.Hl = SHA384_IV[15] | 0;
    }
}
/**
 * Truncated SHA512/256 and SHA512/224.
 * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as "intermediary" IV of SHA512/t.
 * Then t hashes string to produce result IV.
 * See `test/misc/sha2-gen-iv.js`.
 */
/** SHA512/224 IV */
const T224_IV = /* @__PURE__ */ Uint32Array.from([
    0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,
    0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,
]);
/** SHA512/256 IV */
const T256_IV = /* @__PURE__ */ Uint32Array.from([
    0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,
    0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,
]);
export class SHA512_224 extends SHA512 {
    constructor() {
        super(28);
        this.Ah = T224_IV[0] | 0;
        this.Al = T224_IV[1] | 0;
        this.Bh = T224_IV[2] | 0;
        this.Bl = T224_IV[3] | 0;
        this.Ch = T224_IV[4] | 0;
        this.Cl = T224_IV[5] | 0;
        this.Dh = T224_IV[6] | 0;
        this.Dl = T224_IV[7] | 0;
        this.Eh = T224_IV[8] | 0;
        this.El = T224_IV[9] | 0;
        this.Fh = T224_IV[10] | 0;
        this.Fl = T224_IV[11] | 0;
        this.Gh = T224_IV[12] | 0;
        this.Gl = T224_IV[13] | 0;
        this.Hh = T224_IV[14] | 0;
        this.Hl = T224_IV[15] | 0;
    }
}
export class SHA512_256 extends SHA512 {
    constructor() {
        super(32);
        this.Ah = T256_IV[0] | 0;
        this.Al = T256_IV[1] | 0;
        this.Bh = T256_IV[2] | 0;
        this.Bl = T256_IV[3] | 0;
        this.Ch = T256_IV[4] | 0;
        this.Cl = T256_IV[5] | 0;
        this.Dh = T256_IV[6] | 0;
        this.Dl = T256_IV[7] | 0;
        this.Eh = T256_IV[8] | 0;
        this.El = T256_IV[9] | 0;
        this.Fh = T256_IV[10] | 0;
        this.Fl = T256_IV[11] | 0;
        this.Gh = T256_IV[12] | 0;
        this.Gl = T256_IV[13] | 0;
        this.Hh = T256_IV[14] | 0;
        this.Hl = T256_IV[15] | 0;
    }
}
/**
 * SHA2-256 hash function from RFC 4634.
 *
 * It is the fastest JS hash, even faster than Blake3.
 * To break sha256 using birthday attack, attackers need to try 2^128 hashes.
 * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
 */
export const sha256 = /* @__PURE__ */ createHasher(() => new SHA256());
/** SHA2-224 hash function from RFC 4634 */
export const sha224 = /* @__PURE__ */ createHasher(() => new SHA224());
/** SHA2-512 hash function from RFC 4634. */
export const sha512 = /* @__PURE__ */ createHasher(() => new SHA512());
/** SHA2-384 hash function from RFC 4634. */
export const sha384 = /* @__PURE__ */ createHasher(() => new SHA384());
/**
 * SHA2-512/256 "truncated" hash function, with improved resistance to length extension attacks.
 * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).
 */
export const sha512_256 = /* @__PURE__ */ createHasher(() => new SHA512_256());
/**
 * SHA2-512/224 "truncated" hash function, with improved resistance to length extension attacks.
 * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).
 */
export const sha512_224 = /* @__PURE__ */ createHasher(() => new SHA512_224());
//# sourceMappingURL=sha2.js.map/**
 * Utilities for hex, bytes, CSPRNG.
 * @module
 */
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
// node.js versions earlier than v19 don't declare it in global scope.
// For node.js, package.json#exports field mapping rewrites import
// from `crypto` to `cryptoNode`, which imports native module.
// Makes the utils un-importable in browsers without a bundler.
// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.
import { crypto } from '@noble/hashes/crypto';
/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */
export function isBytes(a) {
    return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
}
/** Asserts something is positive integer. */
export function anumber(n) {
    if (!Number.isSafeInteger(n) || n < 0)
        throw new Error('positive integer expected, got ' + n);
}
/** Asserts something is Uint8Array. */
export function abytes(b, ...lengths) {
    if (!isBytes(b))
        throw new Error('Uint8Array expected');
    if (lengths.length > 0 && !lengths.includes(b.length))
        throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);
}
/** Asserts something is hash */
export function ahash(h) {
    if (typeof h !== 'function' || typeof h.create !== 'function')
        throw new Error('Hash should be wrapped by utils.createHasher');
    anumber(h.outputLen);
    anumber(h.blockLen);
}
/** Asserts a hash instance has not been destroyed / finished */
export function aexists(instance, checkFinished = true) {
    if (instance.destroyed)
        throw new Error('Hash instance has been destroyed');
    if (checkFinished && instance.finished)
        throw new Error('Hash#digest() has already been called');
}
/** Asserts output is properly-sized byte array */
export function aoutput(out, instance) {
    abytes(out);
    const min = instance.outputLen;
    if (out.length < min) {
        throw new Error('digestInto() expects output buffer of length at least ' + min);
    }
}
/** Cast u8 / u16 / u32 to u8. */
export function u8(arr) {
    return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
}
/** Cast u8 / u16 / u32 to u32. */
export function u32(arr) {
    return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
}
/** Zeroize a byte array. Warning: JS provides no guarantees. */
export function clean(...arrays) {
    for (let i = 0; i < arrays.length; i++) {
        arrays[i].fill(0);
    }
}
/** Create DataView of an array for easy byte-level manipulation. */
export function createView(arr) {
    return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
}
/** The rotate right (circular right shift) operation for uint32 */
export function rotr(word, shift) {
    return (word << (32 - shift)) | (word >>> shift);
}
/** The rotate left (circular left shift) operation for uint32 */
export function rotl(word, shift) {
    return (word << shift) | ((word >>> (32 - shift)) >>> 0);
}
/** Is current platform little-endian? Most are. Big-Endian platform: IBM */
export const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();
/** The byte swap operation for uint32 */
export function byteSwap(word) {
    return (((word << 24) & 0xff000000) |
        ((word << 8) & 0xff0000) |
        ((word >>> 8) & 0xff00) |
        ((word >>> 24) & 0xff));
}
/** Conditionally byte swap if on a big-endian platform */
export const swap8IfBE = isLE
    ? (n) => n
    : (n) => byteSwap(n);
/** @deprecated */
export const byteSwapIfBE = swap8IfBE;
/** In place byte swap for Uint32Array */
export function byteSwap32(arr) {
    for (let i = 0; i < arr.length; i++) {
        arr[i] = byteSwap(arr[i]);
    }
    return arr;
}
export const swap32IfBE = isLE
    ? (u) => u
    : byteSwap32;
// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex
const hasHexBuiltin = /* @__PURE__ */ (() => 
// @ts-ignore
typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();
// Array where index 0xf0 (240) is mapped to string 'f0'
const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
/**
 * Convert byte array to hex string. Uses built-in function, when available.
 * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
 */
export function bytesToHex(bytes) {
    abytes(bytes);
    // @ts-ignore
    if (hasHexBuiltin)
        return bytes.toHex();
    // pre-caching improves the speed 6x
    let hex = '';
    for (let i = 0; i < bytes.length; i++) {
        hex += hexes[bytes[i]];
    }
    return hex;
}
// We use optimized technique to convert hex string to byte array
const asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
function asciiToBase16(ch) {
    if (ch >= asciis._0 && ch <= asciis._9)
        return ch - asciis._0; // '2' => 50-48
    if (ch >= asciis.A && ch <= asciis.F)
        return ch - (asciis.A - 10); // 'B' => 66-(65-10)
    if (ch >= asciis.a && ch <= asciis.f)
        return ch - (asciis.a - 10); // 'b' => 98-(97-10)
    return;
}
/**
 * Convert hex string to byte array. Uses built-in function, when available.
 * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
 */
export function hexToBytes(hex) {
    if (typeof hex !== 'string')
        throw new Error('hex string expected, got ' + typeof hex);
    // @ts-ignore
    if (hasHexBuiltin)
        return Uint8Array.fromHex(hex);
    const hl = hex.length;
    const al = hl / 2;
    if (hl % 2)
        throw new Error('hex string expected, got unpadded hex of length ' + hl);
    const array = new Uint8Array(al);
    for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
        const n1 = asciiToBase16(hex.charCodeAt(hi));
        const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
        if (n1 === undefined || n2 === undefined) {
            const char = hex[hi] + hex[hi + 1];
            throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
        }
        array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163
    }
    return array;
}
/**
 * There is no setImmediate in browser and setTimeout is slow.
 * Call of async fn will return Promise, which will be fullfiled only on
 * next scheduler queue processing step and this is exactly what we need.
 */
export const nextTick = async () => { };
/** Returns control to thread each 'tick' ms to avoid blocking. */
export async function asyncLoop(iters, tick, cb) {
    let ts = Date.now();
    for (let i = 0; i < iters; i++) {
        cb(i);
        // Date.now() is not monotonic, so in case if clock goes backwards we return return control too
        const diff = Date.now() - ts;
        if (diff >= 0 && diff < tick)
            continue;
        await nextTick();
        ts += diff;
    }
}
/**
 * Converts string to bytes using UTF8 encoding.
 * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])
 */
export function utf8ToBytes(str) {
    if (typeof str !== 'string')
        throw new Error('string expected');
    return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
}
/**
 * Converts bytes to string using UTF8 encoding.
 * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'
 */
export function bytesToUtf8(bytes) {
    return new TextDecoder().decode(bytes);
}
/**
 * Normalizes (non-hex) string or Uint8Array to Uint8Array.
 * Warning: when Uint8Array is passed, it would NOT get copied.
 * Keep in mind for future mutable operations.
 */
export function toBytes(data) {
    if (typeof data === 'string')
        data = utf8ToBytes(data);
    abytes(data);
    return data;
}
/**
 * Helper for KDFs: consumes uint8array or string.
 * When string is passed, does utf8 decoding, using TextDecoder.
 */
export function kdfInputToBytes(data) {
    if (typeof data === 'string')
        data = utf8ToBytes(data);
    abytes(data);
    return data;
}
/** Copies several Uint8Arrays into one. */
export function concatBytes(...arrays) {
    let sum = 0;
    for (let i = 0; i < arrays.length; i++) {
        const a = arrays[i];
        abytes(a);
        sum += a.length;
    }
    const res = new Uint8Array(sum);
    for (let i = 0, pad = 0; i < arrays.length; i++) {
        const a = arrays[i];
        res.set(a, pad);
        pad += a.length;
    }
    return res;
}
export function checkOpts(defaults, opts) {
    if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')
        throw new Error('options should be object or undefined');
    const merged = Object.assign(defaults, opts);
    return merged;
}
/** For runtime check if class implements interface */
export class Hash {
}
/** Wraps hash function, creating an interface on top of it */
export function createHasher(hashCons) {
    const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
    const tmp = hashCons();
    hashC.outputLen = tmp.outputLen;
    hashC.blockLen = tmp.blockLen;
    hashC.create = () => hashCons();
    return hashC;
}
export function createOptHasher(hashCons) {
    const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();
    const tmp = hashCons({});
    hashC.outputLen = tmp.outputLen;
    hashC.blockLen = tmp.blockLen;
    hashC.create = (opts) => hashCons(opts);
    return hashC;
}
export function createXOFer(hashCons) {
    const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();
    const tmp = hashCons({});
    hashC.outputLen = tmp.outputLen;
    hashC.blockLen = tmp.blockLen;
    hashC.create = (opts) => hashCons(opts);
    return hashC;
}
export const wrapConstructor = createHasher;
export const wrapConstructorWithOpts = createOptHasher;
export const wrapXOFConstructorWithOpts = createXOFer;
/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */
export function randomBytes(bytesLength = 32) {
    if (crypto && typeof crypto.getRandomValues === 'function') {
        return crypto.getRandomValues(new Uint8Array(bytesLength));
    }
    // Legacy Node.js compatibility
    if (crypto && typeof crypto.randomBytes === 'function') {
        return Uint8Array.from(crypto.randomBytes(bytesLength));
    }
    throw new Error('crypto.getRandomValues must be defined');
}
//# sourceMappingURL=utils.js.mapimport { encode, encodeInto, objectToTokens, rfc8949EncodeOptions } from './lib/encode.js'
import { decode, decodeFirst, Tokeniser, tokensToObject } from './lib/decode.js'
import { Tagged } from './lib/tagged.js'
import { Token, Type } from './lib/token.js'

/**
 * Export the types that were present in the original manual cborg.d.ts
 * @typedef {import('./interface.js').TagDecodeControl} TagDecodeControl
 * @typedef {import('./interface.js').TagDecoder} TagDecoder
 * There was originally just `TypeEncoder` so don't break types by renaming or not exporting
 * @typedef {import('./interface.js').OptionalTypeEncoder} TypeEncoder
 * @typedef {import('./interface.js').DecodeOptions} DecodeOptions
 * @typedef {import('./interface.js').EncodeOptions} EncodeOptions
 */

export {
  decode,
  decodeFirst,
  Tokeniser as Tokenizer,
  tokensToObject,
  encode,
  encodeInto,
  objectToTokens,
  rfc8949EncodeOptions,
  Tagged,
  Token,
  Type
}
/* globals BigInt */

import { Token, Type } from './token.js'
import { decodeErrPrefix, assertEnoughData } from './common.js'

export const uintBoundaries = [24, 256, 65536, 4294967296, BigInt('18446744073709551616')]

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number}
 */
export function readUint8 (data, offset, options) {
  assertEnoughData(data, offset, 1)
  const value = data[offset]
  if (options.strict === true && value < uintBoundaries[0]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  return value
}

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number}
 */
export function readUint16 (data, offset, options) {
  assertEnoughData(data, offset, 2)
  const value = (data[offset] << 8) | data[offset + 1]
  if (options.strict === true && value < uintBoundaries[1]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  return value
}

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number}
 */
export function readUint32 (data, offset, options) {
  assertEnoughData(data, offset, 4)
  const value = (data[offset] * 16777216 /* 2 ** 24 */) + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]
  if (options.strict === true && value < uintBoundaries[2]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  return value
}

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number|bigint}
 */
export function readUint64 (data, offset, options) {
  // assume BigInt, convert back to Number if within safe range
  assertEnoughData(data, offset, 8)
  const hi = (data[offset] * 16777216 /* 2 ** 24 */) + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]
  const lo = (data[offset + 4] * 16777216 /* 2 ** 24 */) + (data[offset + 5] << 16) + (data[offset + 6] << 8) + data[offset + 7]
  const value = (BigInt(hi) << BigInt(32)) + BigInt(lo)
  if (options.strict === true && value < uintBoundaries[3]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  if (value <= Number.MAX_SAFE_INTEGER) {
    return Number(value)
  }
  if (options.allowBigInt === true) {
    return value
  }
  throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`)
}

/* not required thanks to quick[] list
const oneByteTokens = new Array(24).fill(0).map((v, i) => new Token(Type.uint, i, 1))
export function decodeUintCompact (data, pos, minor, options) {
  return oneByteTokens[minor]
}
*/

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint8 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint8(data, pos + 1, options), 2)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint16 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint16(data, pos + 1, options), 3)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint32 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint32(data, pos + 1, options), 5)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint64 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint64(data, pos + 1, options), 9)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeUint (writer, token) {
  return encodeUintValue(writer, 0, token.value)
}

/**
 * @param {ByteWriter} writer
 * @param {number} major
 * @param {number|bigint} uint
 */
export function encodeUintValue (writer, major, uint) {
  if (uint < uintBoundaries[0]) {
    const nuint = Number(uint)
    // pack into one byte, minor=0, additional=value
    writer.push([major | nuint])
  } else if (uint < uintBoundaries[1]) {
    const nuint = Number(uint)
    // pack into two byte, minor=0, additional=24
    writer.push([major | 24, nuint])
  } else if (uint < uintBoundaries[2]) {
    const nuint = Number(uint)
    // pack into three byte, minor=0, additional=25
    writer.push([major | 25, nuint >>> 8, nuint & 0xff])
  } else if (uint < uintBoundaries[3]) {
    const nuint = Number(uint)
    // pack into five byte, minor=0, additional=26
    writer.push([major | 26, (nuint >>> 24) & 0xff, (nuint >>> 16) & 0xff, (nuint >>> 8) & 0xff, nuint & 0xff])
  } else {
    const buint = BigInt(uint)
    if (buint < uintBoundaries[4]) {
      // pack into nine byte, minor=0, additional=27
      const set = [major | 27, 0, 0, 0, 0, 0, 0, 0]
      // simulate bitwise above 32 bits
      let lo = Number(buint & BigInt(0xffffffff))
      let hi = Number(buint >> BigInt(32) & BigInt(0xffffffff))
      set[8] = lo & 0xff
      lo = lo >> 8
      set[7] = lo & 0xff
      lo = lo >> 8
      set[6] = lo & 0xff
      lo = lo >> 8
      set[5] = lo & 0xff
      set[4] = hi & 0xff
      hi = hi >> 8
      set[3] = hi & 0xff
      hi = hi >> 8
      set[2] = hi & 0xff
      hi = hi >> 8
      set[1] = hi & 0xff
      writer.push(set)
    } else {
      throw new Error(`${decodeErrPrefix} encountered BigInt larger than allowable range`)
    }
  }
}

/**
 * @param {Token} token
 * @returns {number}
 */
encodeUint.encodedSize = function encodedSize (token) {
  return encodeUintValue.encodedSize(token.value)
}

/**
 * @param {number} uint
 * @returns {number}
 */
encodeUintValue.encodedSize = function encodedSize (uint) {
  if (uint < uintBoundaries[0]) {
    return 1
  }
  if (uint < uintBoundaries[1]) {
    return 2
  }
  if (uint < uintBoundaries[2]) {
    return 3
  }
  if (uint < uintBoundaries[3]) {
    return 5
  }
  return 9
}

/**
 * @param {Token} tok1
 * @param {Token} tok2
 * @returns {number}
 */
encodeUint.compareTokens = function compareTokens (tok1, tok2) {
  return tok1.value < tok2.value ? -1 : tok1.value > tok2.value ? 1 : 0
}
/* eslint-env es2020 */

import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import { decodeErrPrefix } from './common.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint8 (data, pos, _minor, options) {
  return new Token(Type.negint, -1 - uint.readUint8(data, pos + 1, options), 2)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint16 (data, pos, _minor, options) {
  return new Token(Type.negint, -1 - uint.readUint16(data, pos + 1, options), 3)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint32 (data, pos, _minor, options) {
  return new Token(Type.negint, -1 - uint.readUint32(data, pos + 1, options), 5)
}

const neg1b = BigInt(-1)
const pos1b = BigInt(1)

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint64 (data, pos, _minor, options) {
  const int = uint.readUint64(data, pos + 1, options)
  if (typeof int !== 'bigint') {
    const value = -1 - int
    if (value >= Number.MIN_SAFE_INTEGER) {
      return new Token(Type.negint, value, 9)
    }
  }
  if (options.allowBigInt !== true) {
    throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`)
  }
  return new Token(Type.negint, neg1b - BigInt(int), 9)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeNegint (writer, token) {
  const negint = token.value
  const unsigned = (typeof negint === 'bigint' ? (negint * neg1b - pos1b) : (negint * -1 - 1))
  uint.encodeUintValue(writer, token.type.majorEncoded, unsigned)
}

/**
 * @param {Token} token
 * @returns {number}
 */
encodeNegint.encodedSize = function encodedSize (token) {
  const negint = token.value
  const unsigned = (typeof negint === 'bigint' ? (negint * neg1b - pos1b) : (negint * -1 - 1))
  // handled by quickEncode, we shouldn't get here but it's included for completeness
  if (unsigned < uint.uintBoundaries[0]) {
    return 1
  }
  if (unsigned < uint.uintBoundaries[1]) {
    return 2
  }
  if (unsigned < uint.uintBoundaries[2]) {
    return 3
  }
  if (unsigned < uint.uintBoundaries[3]) {
    return 5
  }
  return 9
}

/**
 * @param {Token} tok1
 * @param {Token} tok2
 * @returns {number}
 */
encodeNegint.compareTokens = function compareTokens (tok1, tok2) {
  // opposite of the uint comparison since we store the uint version in bytes
  return tok1.value < tok2.value ? 1 : tok1.value > tok2.value ? -1 : 0
}
import { Token, Type } from './token.js'
import { assertEnoughData, decodeErrPrefix } from './common.js'
import * as uint from './0uint.js'
import { compare, fromString } from './byte-utils.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} prefix
 * @param {number} length
 * @returns {Token}
 */
function toToken (data, pos, prefix, length) {
  assertEnoughData(data, pos, prefix + length)
  const buf = data.slice(pos + prefix, pos + prefix + length)
  return new Token(Type.bytes, buf, prefix + length)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeBytesCompact (data, pos, minor, _options) {
  return toToken(data, pos, 1, minor)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer bytes lengths not supported`)
  }
  return toToken(data, pos, 9, l)
}

/**
 * `encodedBytes` allows for caching when we do a byte version of a string
 * for key sorting purposes
 * @param {Token} token
 * @returns {Uint8Array}
 */
function tokenBytes (token) {
  if (token.encodedBytes === undefined) {
    token.encodedBytes = Type.equals(token.type, Type.string) ? fromString(token.value) : token.value
  }
  // @ts-ignore c'mon
  return token.encodedBytes
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeBytes (writer, token) {
  const bytes = tokenBytes(token)
  uint.encodeUintValue(writer, token.type.majorEncoded, bytes.length)
  writer.push(bytes)
}

/**
 * @param {Token} token
 * @returns {number}
 */
encodeBytes.encodedSize = function encodedSize (token) {
  const bytes = tokenBytes(token)
  return uint.encodeUintValue.encodedSize(bytes.length) + bytes.length
}

/**
 * @param {Token} tok1
 * @param {Token} tok2
 * @returns {number}
 */
encodeBytes.compareTokens = function compareTokens (tok1, tok2) {
  return compareBytes(tokenBytes(tok1), tokenBytes(tok2))
}

/**
 * @param {Uint8Array} b1
 * @param {Uint8Array} b2
 * @returns {number}
 */
export function compareBytes (b1, b2) {
  return b1.length < b2.length ? -1 : b1.length > b2.length ? 1 : compare(b1, b2)
}
import { Token, Type } from './token.js'
import { assertEnoughData, decodeErrPrefix } from './common.js'
import * as uint from './0uint.js'
import { encodeBytes } from './2bytes.js'

const textDecoder = new TextDecoder()

// Threshold for ASCII fast-path vs TextDecoder. Short ASCII strings (common for
// map keys) are faster to decode with a simple loop than TextDecoder overhead.
const ASCII_THRESHOLD = 32

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * Decode UTF-8 bytes to string. For short ASCII strings (common case for map keys),
 * a simple loop is faster than TextDecoder.
 * @param {Uint8Array} bytes
 * @param {number} start
 * @param {number} end
 * @returns {string}
 */
function toStr (bytes, start, end) {
  const len = end - start
  if (len < ASCII_THRESHOLD) {
    let str = ''
    for (let i = start; i < end; i++) {
      const c = bytes[i]
      if (c & 0x80) { // non-ASCII, fall back to TextDecoder
        return textDecoder.decode(bytes.subarray(start, end))
      }
      str += String.fromCharCode(c)
    }
    return str
  }
  return textDecoder.decode(bytes.subarray(start, end))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} prefix
 * @param {number} length
 * @param {DecodeOptions} options
 * @returns {Token}
 */
function toToken (data, pos, prefix, length, options) {
  const totLength = prefix + length
  assertEnoughData(data, pos, totLength)
  const tok = new Token(Type.string, toStr(data, pos + prefix, pos + totLength), totLength)
  if (options.retainStringBytes === true) {
    tok.byteValue = data.slice(pos + prefix, pos + totLength)
  }
  return tok
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeStringCompact (data, pos, minor, options) {
  return toToken(data, pos, 1, minor, options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options), options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options), options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options), options)
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer string lengths not supported`)
  }
  return toToken(data, pos, 9, l, options)
}

export const encodeString = encodeBytes
import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import { decodeErrPrefix } from './common.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} prefix
 * @param {number} length
 * @returns {Token}
 */
function toToken (_data, _pos, prefix, length) {
  return new Token(Type.array, length, prefix)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeArrayCompact (data, pos, minor, _options) {
  return toToken(data, pos, 1, minor)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer array lengths not supported`)
  }
  return toToken(data, pos, 9, l)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArrayIndefinite (data, pos, _minor, options) {
  if (options.allowIndefinite === false) {
    throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)
  }
  return toToken(data, pos, 1, Infinity)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeArray (writer, token) {
  uint.encodeUintValue(writer, Type.array.majorEncoded, token.value)
}

// using an array as a map key, are you sure about this? we can only sort
// by map length here, it's up to the encoder to decide to look deeper
encodeArray.compareTokens = uint.encodeUint.compareTokens

/**
 * @param {Token} token
 * @returns {number}
 */
encodeArray.encodedSize = function encodedSize (token) {
  return uint.encodeUintValue.encodedSize(token.value)
}
import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import { decodeErrPrefix } from './common.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} prefix
 * @param {number} length
 * @returns {Token}
 */
function toToken (_data, _pos, prefix, length) {
  return new Token(Type.map, length, prefix)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeMapCompact (data, pos, minor, _options) {
  return toToken(data, pos, 1, minor)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer map lengths not supported`)
  }
  return toToken(data, pos, 9, l)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMapIndefinite (data, pos, _minor, options) {
  if (options.allowIndefinite === false) {
    throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)
  }
  return toToken(data, pos, 1, Infinity)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeMap (writer, token) {
  uint.encodeUintValue(writer, Type.map.majorEncoded, token.value)
}

// using a map as a map key, are you sure about this? we can only sort
// by map length here, it's up to the encoder to decide to look deeper
encodeMap.compareTokens = uint.encodeUint.compareTokens

/**
 * @param {Token} token
 * @returns {number}
 */
encodeMap.encodedSize = function encodedSize (token) {
  return uint.encodeUintValue.encodedSize(token.value)
}
import { Token, Type } from './token.js'
import * as uint from './0uint.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeTagCompact (_data, _pos, minor, _options) {
  return new Token(Type.tag, minor, 1)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag8 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint8(data, pos + 1, options), 2)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag16 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint16(data, pos + 1, options), 3)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag32 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint32(data, pos + 1, options), 5)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag64 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint64(data, pos + 1, options), 9)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeTag (writer, token) {
  uint.encodeUintValue(writer, Type.tag.majorEncoded, token.value)
}

encodeTag.compareTokens = uint.encodeUint.compareTokens

/**
 * @param {Token} token
 * @returns {number}
 */
encodeTag.encodedSize = function encodedSize (token) {
  return uint.encodeUintValue.encodedSize(token.value)
}
// TODO: shift some of the bytes logic to bytes-utils so we can use Buffer
// where possible

import { Token, Type } from './token.js'
import { decodeErrPrefix } from './common.js'
import { encodeUint } from './0uint.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 * @typedef {import('../interface.js').EncodeOptions} EncodeOptions
 */

export const MINOR_FALSE = 20
export const MINOR_TRUE = 21
export const MINOR_NULL = 22
export const MINOR_UNDEFINED = 23

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUndefined (_data, _pos, _minor, options) {
  if (options.allowUndefined === false) {
    throw new Error(`${decodeErrPrefix} undefined values are not supported`)
  } else if (options.coerceUndefinedToNull === true) {
    return new Token(Type.null, null, 1)
  }
  return new Token(Type.undefined, undefined, 1)
}

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBreak (_data, _pos, _minor, options) {
  if (options.allowIndefinite === false) {
    throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)
  }
  return new Token(Type.break, undefined, 1)
}

/**
 * @param {number} value
 * @param {number} bytes
 * @param {DecodeOptions} options
 * @returns {Token}
 */
function createToken (value, bytes, options) {
  if (options) {
    if (options.allowNaN === false && Number.isNaN(value)) {
      throw new Error(`${decodeErrPrefix} NaN values are not supported`)
    }
    if (options.allowInfinity === false && (value === Infinity || value === -Infinity)) {
      throw new Error(`${decodeErrPrefix} Infinity values are not supported`)
    }
  }
  return new Token(Type.float, value, bytes)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeFloat16 (data, pos, _minor, options) {
  return createToken(readFloat16(data, pos + 1), 3, options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeFloat32 (data, pos, _minor, options) {
  return createToken(readFloat32(data, pos + 1), 5, options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeFloat64 (data, pos, _minor, options) {
  return createToken(readFloat64(data, pos + 1), 9, options)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 * @param {EncodeOptions} options
 */
export function encodeFloat (writer, token, options) {
  const float = token.value

  if (float === false) {
    writer.push([Type.float.majorEncoded | MINOR_FALSE])
  } else if (float === true) {
    writer.push([Type.float.majorEncoded | MINOR_TRUE])
  } else if (float === null) {
    writer.push([Type.float.majorEncoded | MINOR_NULL])
  } else if (float === undefined) {
    writer.push([Type.float.majorEncoded | MINOR_UNDEFINED])
  } else {
    let decoded
    let success = false
    if (!options || options.float64 !== true) {
      encodeFloat16(float)
      decoded = readFloat16(ui8a, 1)
      if (float === decoded || Number.isNaN(float)) {
        ui8a[0] = 0xf9
        writer.push(ui8a.slice(0, 3))
        success = true
      } else {
        encodeFloat32(float)
        decoded = readFloat32(ui8a, 1)
        if (float === decoded) {
          ui8a[0] = 0xfa
          writer.push(ui8a.slice(0, 5))
          success = true
        }
      }
    }
    if (!success) {
      encodeFloat64(float)
      decoded = readFloat64(ui8a, 1)
      ui8a[0] = 0xfb
      writer.push(ui8a.slice(0, 9))
    }
  }
}

/**
 * @param {Token} token
 * @param {EncodeOptions} options
 * @returns {number}
 */
encodeFloat.encodedSize = function encodedSize (token, options) {
  const float = token.value

  if (float === false || float === true || float === null || float === undefined) {
    return 1
  }

  if (!options || options.float64 !== true) {
    encodeFloat16(float)
    let decoded = readFloat16(ui8a, 1)
    if (float === decoded || Number.isNaN(float)) {
      return 3
    }
    encodeFloat32(float)
    decoded = readFloat32(ui8a, 1)
    if (float === decoded) {
      return 5
    }
  }
  return 9
}

const buffer = new ArrayBuffer(9)
const dataView = new DataView(buffer, 1)
const ui8a = new Uint8Array(buffer, 0)

/**
 * @param {number} inp
 */
function encodeFloat16 (inp) {
  if (inp === Infinity) {
    dataView.setUint16(0, 0x7c00, false)
  } else if (inp === -Infinity) {
    dataView.setUint16(0, 0xfc00, false)
  } else if (Number.isNaN(inp)) {
    dataView.setUint16(0, 0x7e00, false)
  } else {
    dataView.setFloat32(0, inp)
    const valu32 = dataView.getUint32(0)
    const exponent = (valu32 & 0x7f800000) >> 23
    const mantissa = valu32 & 0x7fffff

    if (exponent === 0xff) {
      // too big, Infinity, but this should be hard (impossible?) to trigger
      dataView.setUint16(0, 0x7c00, false)
    } else if (exponent === 0x00) {
      // 0.0, -0.0 and subnormals, shouldn't be possible to get here because 0.0 should be counted as an int
      // Use valu32 for sign bit since bitwise ops on floats lose -0 sign
      dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | (mantissa >> 13), false)
    } else { // standard numbers
      // chunks of logic here borrowed from https://github.com/PJK/libcbor/blob/c78f437182533e3efa8d963ff4b945bb635c2284/src/cbor/encoding.c#L127
      const logicalExponent = exponent - 127
      // Now we know that 2^exponent <= 0 logically
      if (logicalExponent < -24) {
        /* No unambiguous representation exists, this float is not a half float
          and is too small to be represented using a half, round off to zero.
          Consistent with the reference implementation. */
        // should be difficult (impossible?) to get here in JS
        dataView.setUint16(0, 0)
      } else if (logicalExponent < -14) {
        /* Offset the remaining decimal places by shifting the significand, the
          value is lost. This is an implementation decision that works around the
          absence of standard half-float in the language. */
        dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | /* sign bit */ (1 << (24 + logicalExponent)), false)
      } else {
        dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | ((logicalExponent + 15) << 10) | (mantissa >> 13), false)
      }
    }
  }
}

/**
 * @param {Uint8Array} ui8a
 * @param {number} pos
 * @returns {number}
 */
function readFloat16 (ui8a, pos) {
  if (ui8a.length - pos < 2) {
    throw new Error(`${decodeErrPrefix} not enough data for float16`)
  }

  const half = (ui8a[pos] << 8) + ui8a[pos + 1]
  if (half === 0x7c00) {
    return Infinity
  }
  if (half === 0xfc00) {
    return -Infinity
  }
  if (half === 0x7e00) {
    return NaN
  }
  const exp = (half >> 10) & 0x1f
  const mant = half & 0x3ff
  let val
  if (exp === 0) {
    val = mant * (2 ** -24)
  } else if (exp !== 31) {
    val = (mant + 1024) * (2 ** (exp - 25))
  } else {
    // may not be possible to get here
    val = mant === 0 ? Infinity : NaN
  }
  return (half & 0x8000) ? -val : val
}

/**
 * @param {number} inp
 */
function encodeFloat32 (inp) {
  dataView.setFloat32(0, inp, false)
}

/**
 * @param {Uint8Array} ui8a
 * @param {number} pos
 * @returns {number}
 */
function readFloat32 (ui8a, pos) {
  if (ui8a.length - pos < 4) {
    throw new Error(`${decodeErrPrefix} not enough data for float32`)
  }
  const offset = (ui8a.byteOffset || 0) + pos
  return new DataView(ui8a.buffer, offset, 4).getFloat32(0, false)
}

/**
 * @param {number} inp
 */
function encodeFloat64 (inp) {
  dataView.setFloat64(0, inp, false)
}

/**
 * @param {Uint8Array} ui8a
 * @param {number} pos
 * @returns {number}
 */
function readFloat64 (ui8a, pos) {
  if (ui8a.length - pos < 8) {
    throw new Error(`${decodeErrPrefix} not enough data for float64`)
  }
  const offset = (ui8a.byteOffset || 0) + pos
  return new DataView(ui8a.buffer, offset, 8).getFloat64(0, false)
}

/**
 * @param {Token} _tok1
 * @param {Token} _tok2
 * @returns {number}
 */
encodeFloat.compareTokens = encodeUint.compareTokens
/*
encodeFloat.compareTokens = function compareTokens (_tok1, _tok2) {
  return _tok1
  throw new Error(`${encodeErrPrefix} cannot use floats as map keys`)
}
*/
/**
 * Bl is a list of byte chunks, similar to https://github.com/rvagg/bl but for
 * writing rather than reading.
 * A Bl object accepts set() operations for individual bytes and copyTo() for
 * inserting byte arrays. These write operations don't automatically increment
 * the internal cursor so its "length" won't be changed. Instead, increment()
 * must be called to extend its length to cover the inserted data.
 * The toBytes() call will convert all internal memory to a single Uint8Array of
 * the correct length, truncating any data that is stored but hasn't been
 * included by an increment().
 * get() can retrieve a single byte.
 * All operations (except toBytes()) take an "offset" argument that will perform
 * the write at the offset _from the current cursor_. For most operations this
 * will be `0` to write at the current cursor position but it can be ahead of
 * the current cursor. Negative offsets probably work but are untested.
 */

// TODO: ipjs doesn't support this, only for test files: https://github.com/mikeal/ipjs/blob/master/src/package/testFile.js#L39
import { alloc, concat, slice } from './byte-utils.js'

// the ts-ignores in this file are almost all for the `Uint8Array|number[]` duality that exists
// for perf reasons. Consider better approaches to this or removing it entirely, it is quite
// risky because of some assumptions about small chunks === number[] and everything else === Uint8Array.

const defaultChunkSize = 256

export class Bl {
  /**
   * @param {number} [chunkSize]
   */
  constructor (chunkSize = defaultChunkSize) {
    this.chunkSize = chunkSize
    /** @type {number} */
    this.cursor = 0
    /** @type {number} */
    this.maxCursor = -1
    /** @type {(Uint8Array|number[])[]} */
    this.chunks = []
    // keep the first chunk around if we can to save allocations for future encodes
    /** @type {Uint8Array|number[]|null} */
    this._initReuseChunk = null
  }

  reset () {
    this.cursor = 0
    this.maxCursor = -1
    if (this.chunks.length) {
      this.chunks = []
    }
    if (this._initReuseChunk !== null) {
      this.chunks.push(this._initReuseChunk)
      this.maxCursor = this._initReuseChunk.length - 1
    }
  }

  /**
   * @param {Uint8Array|number[]} bytes
   */
  push (bytes) {
    let topChunk = this.chunks[this.chunks.length - 1]
    const newMax = this.cursor + bytes.length
    if (newMax <= this.maxCursor + 1) {
      // we have at least one chunk and we can fit these bytes into that chunk
      const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1
      // @ts-ignore
      topChunk.set(bytes, chunkPos)
    } else {
      // can't fit it in
      if (topChunk) {
        // trip the last chunk to `cursor` if we need to
        const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1
        if (chunkPos < topChunk.length) {
          // @ts-ignore
          this.chunks[this.chunks.length - 1] = topChunk.subarray(0, chunkPos)
          this.maxCursor = this.cursor - 1
        }
      }
      if (bytes.length < 64 && bytes.length < this.chunkSize) {
        // make a new chunk and copy the new one into it
        topChunk = alloc(this.chunkSize)
        this.chunks.push(topChunk)
        this.maxCursor += topChunk.length
        if (this._initReuseChunk === null) {
          this._initReuseChunk = topChunk
        }
        // @ts-ignore
        topChunk.set(bytes, 0)
      } else {
        // push the new bytes in as its own chunk
        this.chunks.push(bytes)
        this.maxCursor += bytes.length
      }
    }
    this.cursor += bytes.length
  }

  /**
   * @param {boolean} [reset]
   * @returns {Uint8Array}
   */
  toBytes (reset = false) {
    let byts
    if (this.chunks.length === 1) {
      const chunk = this.chunks[0]
      if (reset && this.cursor > chunk.length / 2) {
        // @ts-ignore
        byts = this.cursor === chunk.length ? chunk : chunk.subarray(0, this.cursor)
        this._initReuseChunk = null
        this.chunks = []
      } else {
        // @ts-ignore
        byts = slice(chunk, 0, this.cursor)
      }
    } else {
      // @ts-ignore
      byts = concat(this.chunks, this.cursor)
    }
    if (reset) {
      this.reset()
    }
    return byts
  }
}

/**
 * U8Bl is a buffer list that writes directly to a user-provided Uint8Array.
 * It provides the same interface as Bl but writes to a fixed destination.
 */
export class U8Bl {
  /**
   * @param {Uint8Array} dest
   */
  constructor (dest) {
    this.dest = dest
    /** @type {number} */
    this.cursor = 0
    // chunks is for interface compatibility with Bl - encode.js checks chunks.length
    // as a sanity check for pre-calculated sizes. For U8Bl this is always [dest].
    /** @type {Uint8Array[]} */
    this.chunks = [dest]
  }

  reset () {
    this.cursor = 0
  }

  /**
   * @param {Uint8Array|number[]} bytes
   */
  push (bytes) {
    if (this.cursor + bytes.length > this.dest.length) {
      throw new Error('write out of bounds, destination buffer is too small')
    }
    this.dest.set(bytes, this.cursor)
    this.cursor += bytes.length
  }

  /**
   * @param {boolean} [reset]
   * @returns {Uint8Array}
   */
  toBytes (reset = false) {
    const byts = this.dest.subarray(0, this.cursor)
    if (reset) {
      this.reset()
    }
    return byts
  }
}
// Use Uint8Array directly in the browser, use Buffer in Node.js but don't
// speak its name directly to avoid bundlers pulling in the `Buffer` polyfill

// @ts-ignore
export const useBuffer = globalThis.process &&
  // @ts-ignore
  !globalThis.process.browser &&
  // @ts-ignore
  globalThis.Buffer &&
  // @ts-ignore
  typeof globalThis.Buffer.isBuffer === 'function'

const textEncoder = new TextEncoder()

/**
 * @param {Uint8Array} buf
 * @returns {boolean}
 */
function isBuffer (buf) {
  // @ts-ignore
  return useBuffer && globalThis.Buffer.isBuffer(buf)
}

/**
 * @param {Uint8Array|number[]} buf
 * @returns {Uint8Array}
 */
export function asU8A (buf) {
  if (!(buf instanceof Uint8Array)) {
    return Uint8Array.from(buf)
  }
  return isBuffer(buf) ? new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength) : buf
}

// Threshold for manual UTF-8 encoding vs native methods.
// Node.js Buffer.from: crossover ~24 chars
// Browser TextEncoder: crossover ~200 chars
const FROM_STRING_THRESHOLD_BUFFER = 24
const FROM_STRING_THRESHOLD_TEXTENCODER = 200

export const fromString = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {string} string
     */
    (string) => {
      return string.length >= FROM_STRING_THRESHOLD_BUFFER
        ? // eslint-disable-line operator-linebreak
      // @ts-ignore
        globalThis.Buffer.from(string)
        : utf8ToBytes(string)
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {string} string
     */
    (string) => {
      return string.length >= FROM_STRING_THRESHOLD_TEXTENCODER ? textEncoder.encode(string) : utf8ToBytes(string)
    }

/**
 * Buffer variant not fast enough for what we need
 * @param {number[]} arr
 * @returns {Uint8Array}
 */
export const fromArray = (arr) => {
  return Uint8Array.from(arr)
}

export const slice = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} bytes
     * @param {number} start
     * @param {number} end
     */
    // Buffer.slice() returns a view, not a copy, so we need special handling
    (bytes, start, end) => {
      if (isBuffer(bytes)) {
        return new Uint8Array(bytes.subarray(start, end))
      }
      return bytes.slice(start, end)
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} bytes
     * @param {number} start
     * @param {number} end
     */
    (bytes, start, end) => {
      return bytes.slice(start, end)
    }

export const concat = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array[]} chunks
     * @param {number} length
     * @returns {Uint8Array}
     */
    (chunks, length) => {
      // might get a stray plain Array here
      chunks = chunks.map((c) => c instanceof Uint8Array
        ? c
        : // eslint-disable-line operator-linebreak
        // @ts-ignore
        globalThis.Buffer.from(c))
      // @ts-ignore
      return asU8A(globalThis.Buffer.concat(chunks, length))
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array[]} chunks
     * @param {number} length
     * @returns {Uint8Array}
     */
    (chunks, length) => {
      const out = new Uint8Array(length)
      let off = 0
      for (let b of chunks) {
        if (off + b.length > out.length) {
          // final chunk that's bigger than we need
          b = b.subarray(0, out.length - off)
        }
        out.set(b, off)
        off += b.length
      }
      return out
    }

export const alloc = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {number} size
     * @returns {Uint8Array}
     */
    (size) => {
      // we always write over the contents we expose so this should be safe
      // @ts-ignore
      return globalThis.Buffer.allocUnsafe(size)
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {number} size
     * @returns {Uint8Array}
     */
    (size) => {
      return new Uint8Array(size)
    }

export const toHex = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} d
     * @returns {string}
     */
    (d) => {
      if (typeof d === 'string') {
        return d
      }
      // @ts-ignore
      return globalThis.Buffer.from(toBytes(d)).toString('hex')
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} d
     * @returns {string}
     */
    (d) => {
      if (typeof d === 'string') {
        return d
      }
      // @ts-ignore not smart enough to figure this out
      return Array.prototype.reduce.call(toBytes(d), (p, c) => `${p}${c.toString(16).padStart(2, '0')}`, '')
    }

export const fromHex = useBuffer
  ? // eslint-disable-line operator-linebreak
  /**
   * @param {string|Uint8Array} hex
   * @returns {Uint8Array}
   */
    (hex) => {
      if (hex instanceof Uint8Array) {
        return hex
      }
      // @ts-ignore
      return globalThis.Buffer.from(hex, 'hex')
    }
  : // eslint-disable-line operator-linebreak
  /**
   * @param {string|Uint8Array} hex
   * @returns {Uint8Array}
   */
    (hex) => {
      if (hex instanceof Uint8Array) {
        return hex
      }
      if (!hex.length) {
        return new Uint8Array(0)
      }
      return new Uint8Array(hex.split('')
        .map((/** @type {string} */ c, /** @type {number} */ i, /** @type {string[]} */ d) => i % 2 === 0 ? `0x${c}${d[i + 1]}` : '')
        .filter(Boolean)
        .map((/** @type {string} */ e) => parseInt(e, 16)))
    }

/**
 * @param {Uint8Array|ArrayBuffer|ArrayBufferView} obj
 * @returns {Uint8Array}
 */
function toBytes (obj) {
  if (obj instanceof Uint8Array && obj.constructor.name === 'Uint8Array') {
    return obj
  }
  if (obj instanceof ArrayBuffer) {
    return new Uint8Array(obj)
  }
  if (ArrayBuffer.isView(obj)) {
    return new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength)
  }
  throw new Error('Unknown type, must be binary type')
}

/**
 * @param {Uint8Array} b1
 * @param {Uint8Array} b2
 * @returns {number}
 */
export function compare (b1, b2) {
  if (isBuffer(b1) && isBuffer(b2)) {
    // probably not possible to get here in the current API
    // @ts-ignore Buffer
    return b1.compare(b2)
  }
  for (let i = 0; i < b1.length; i++) {
    if (b1[i] === b2[i]) {
      continue
    }
    return b1[i] < b2[i] ? -1 : 1
  }
  return 0
}

// The below code is taken from https://github.com/google/closure-library/blob/8598d87242af59aac233270742c8984e2b2bdbe0/closure/goog/crypt/crypt.js#L117-L143
// Licensed Apache-2.0.

/**
 * @param {string} str
 * @returns {number[]}
 */
function utf8ToBytes (str) {
  const out = []
  let p = 0
  for (let i = 0; i < str.length; i++) {
    let c = str.charCodeAt(i)
    if (c < 128) {
      out[p++] = c
    } else if (c < 2048) {
      out[p++] = (c >> 6) | 192
      out[p++] = (c & 63) | 128
    } else if (
      ((c & 0xFC00) === 0xD800) && (i + 1) < str.length &&
      ((str.charCodeAt(i + 1) & 0xFC00) === 0xDC00)) {
      // Surrogate Pair
      c = 0x10000 + ((c & 0x03FF) << 10) + (str.charCodeAt(++i) & 0x03FF)
      out[p++] = (c >> 18) | 240
      out[p++] = ((c >> 12) & 63) | 128
      out[p++] = ((c >> 6) & 63) | 128
      out[p++] = (c & 63) | 128
    } else {
      if ((c >= 0xD800) && (c <= 0xDFFF)) {
        c = 0xFFFD // Unpaired Surrogate
      }
      out[p++] = (c >> 12) | 224
      out[p++] = ((c >> 6) & 63) | 128
      out[p++] = (c & 63) | 128
    }
  }
  return out
}

// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
const MAX_ARGUMENTS_LENGTH = 0x1000

/**
 * @param {number[]} codePoints
 * @returns {string}
 */
export function decodeCodePointsArray (codePoints) {
  const len = codePoints.length
  if (len <= MAX_ARGUMENTS_LENGTH) {
    return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  }
  // Decode in chunks to avoid "call stack size exceeded".
  let res = ''
  let i = 0
  while (i < len) {
    res += String.fromCharCode.apply(
      String,
      codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
    )
  }
  return res
}
const decodeErrPrefix = 'CBOR decode error:'
const encodeErrPrefix = 'CBOR encode error:'

const uintMinorPrefixBytes = []
uintMinorPrefixBytes[23] = 1
uintMinorPrefixBytes[24] = 2
uintMinorPrefixBytes[25] = 3
uintMinorPrefixBytes[26] = 5
uintMinorPrefixBytes[27] = 9

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} need
 */
function assertEnoughData (data, pos, need) {
  if (data.length - pos < need) {
    throw new Error(`${decodeErrPrefix} not enough data for type`)
  }
}

export {
  decodeErrPrefix,
  encodeErrPrefix,
  uintMinorPrefixBytes,
  assertEnoughData
}
import { decodeErrPrefix } from './common.js'
import { Type } from './token.js'
import { jump, quick } from './jump.js'
import { asU8A } from './byte-utils.js'

/**
 * @typedef {import('./token.js').Token} Token
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 * @typedef {import('../interface.js').DecodeTokenizer} DecodeTokenizer
 * @typedef {import('../interface.js').TagDecodeControl} TagDecodeControl
 */

const defaultDecodeOptions = {
  strict: false,
  allowIndefinite: true,
  allowUndefined: true,
  allowBigInt: true
}

/**
 * @implements {DecodeTokenizer}
 */
class Tokeniser {
  /**
   * @param {Uint8Array} data
   * @param {DecodeOptions} options
   */
  constructor (data, options = {}) {
    this._pos = 0
    this.data = data
    this.options = options
  }

  pos () {
    return this._pos
  }

  done () {
    return this._pos >= this.data.length
  }

  next () {
    const byt = this.data[this._pos]
    let token = quick[byt]
    if (token === undefined) {
      const decoder = jump[byt]
      // if we're here then there's something wrong with our jump or quick lists!
      if (!decoder) {
        throw new Error(`${decodeErrPrefix} no decoder for major type ${byt >>> 5} (byte 0x${byt.toString(16).padStart(2, '0')})`)
      }
      const minor = byt & 31
      token = decoder(this.data, this._pos, minor, this.options)
    }
    // @ts-ignore we get to assume encodedLength is set (crossing fingers slightly)
    this._pos += token.encodedLength
    return token
  }
}

const DONE = Symbol.for('DONE')
const BREAK = Symbol.for('BREAK')

/**
 * @param {Token} token
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {any|BREAK|DONE}
 */
function tokenToArray (token, tokeniser, options) {
  const arr = []
  for (let i = 0; i < token.value; i++) {
    const value = tokensToObject(tokeniser, options)
    if (value === BREAK) {
      if (token.value === Infinity) {
        // normal end to indefinite length array
        break
      }
      throw new Error(`${decodeErrPrefix} got unexpected break to lengthed array`)
    }
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} found array but not enough entries (got ${i}, expected ${token.value})`)
    }
    arr[i] = value
  }
  return arr
}

/**
 * @param {Token} token
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {any|BREAK|DONE}
 */
function tokenToMap (token, tokeniser, options) {
  const useMaps = options.useMaps === true
  const rejectDuplicateMapKeys = options.rejectDuplicateMapKeys === true
  const obj = useMaps ? undefined : {}
  const m = useMaps ? new Map() : undefined
  for (let i = 0; i < token.value; i++) {
    const key = tokensToObject(tokeniser, options)
    if (key === BREAK) {
      if (token.value === Infinity) {
        // normal end to indefinite length map
        break
      }
      throw new Error(`${decodeErrPrefix} got unexpected break to lengthed map`)
    }
    if (key === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no key], expected ${token.value})`)
    }
    if (!useMaps && typeof key !== 'string') {
      throw new Error(`${decodeErrPrefix} non-string keys not supported (got ${typeof key})`)
    }
    if (rejectDuplicateMapKeys) {
      // @ts-ignore
      if ((useMaps && m.has(key)) || (!useMaps && Object.hasOwn(obj, key))) {
        throw new Error(`${decodeErrPrefix} found repeat map key "${key}"`)
      }
    }
    const value = tokensToObject(tokeniser, options)
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no value], expected ${token.value})`)
    }
    if (useMaps) {
      // @ts-ignore TODO reconsider this .. maybe needs to be strict about key types
      m.set(key, value)
    } else {
      // @ts-ignore TODO reconsider this .. maybe needs to be strict about key types
      obj[key] = value
    }
  }
  // @ts-ignore c'mon man
  return useMaps ? m : obj
}

/**
 * Generator that yields [key, value] entries from a CBOR map token.
 * Used by tag decoders that need to preserve key types (e.g., Tag 259 Map).
 * @param {Token} token - The map token
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {Generator<[any, any], void, unknown>}
 */
function * tokenToMapEntries (token, tokeniser, options) {
  for (let i = 0; i < token.value; i++) {
    const key = tokensToObject(tokeniser, options)
    if (key === BREAK) {
      if (token.value === Infinity) {
        // normal end to indefinite length map
        break
      }
      throw new Error(`${decodeErrPrefix} got unexpected break to lengthed map`)
    }
    if (key === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no key], expected ${token.value})`)
    }
    const value = tokensToObject(tokeniser, options)
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no value], expected ${token.value})`)
    }
    yield [key, value]
  }
}

/**
 * Creates a TagDecodeControl object for tag decoders.
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {TagDecodeControl}
 */
function createTagDecodeControl (tokeniser, options) {
  let called = false

  /**
   * @type {TagDecodeControl}
   */
  const decode = function () {
    if (called) {
      throw new Error(`${decodeErrPrefix} tag decode() may only be called once`)
    }
    called = true
    const value = tokensToObject(tokeniser, options)
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} tag content missing`)
    }
    if (value === BREAK) {
      throw new Error(`${decodeErrPrefix} got unexpected break in tag content`)
    }
    return value
  }

  decode.entries = function () {
    if (called) {
      throw new Error(`${decodeErrPrefix} tag decode() may only be called once`)
    }
    called = true

    // Get the next token and ensure it's a map
    const token = tokeniser.next()
    if (!Type.equals(token.type, Type.map)) {
      throw new Error(`${decodeErrPrefix} entries() requires map content, got ${token.type.name}`)
    }

    // Collect all entries into an array (ensures full content consumption)
    const entries = []
    for (const entry of tokenToMapEntries(token, tokeniser, options)) {
      entries.push(entry)
    }
    return entries
  }

  // For internal tracking
  Object.defineProperty(decode, '_called', {
    get () { return called },
    enumerable: false
  })

  return decode
}

/**
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {any|BREAK|DONE}
 */
function tokensToObject (tokeniser, options) {
  // should we support array as an argument?
  // check for tokenIter[Symbol.iterator] and replace tokenIter with what that returns?
  if (tokeniser.done()) {
    return DONE
  }

  const token = tokeniser.next()

  if (Type.equals(token.type, Type.break)) {
    return BREAK
  }

  if (token.type.terminal) {
    return token.value
  }

  if (Type.equals(token.type, Type.array)) {
    return tokenToArray(token, tokeniser, options)
  }

  if (Type.equals(token.type, Type.map)) {
    return tokenToMap(token, tokeniser, options)
  }

  if (Type.equals(token.type, Type.tag)) {
    if (options.tags && typeof options.tags[token.value] === 'function') {
      const decodeControl = createTagDecodeControl(tokeniser, options)
      const result = options.tags[token.value](decodeControl)
      if (!decodeControl._called) {
        throw new Error(`${decodeErrPrefix} tag decoder must call decode() or entries()`)
      }
      return result
    }
    throw new Error(`${decodeErrPrefix} tag not supported (${token.value})`)
  }
  throw new Error('unsupported')
}

/**
 * @param {Uint8Array} data
 * @param {DecodeOptions} [options]
 * @returns {[any, Uint8Array]}
 */
function decodeFirst (data, options) {
  if (!(data instanceof Uint8Array)) {
    throw new Error(`${decodeErrPrefix} data to decode must be a Uint8Array`)
  }
  options = Object.assign({}, defaultDecodeOptions, options)
  // Convert Buffer to plain Uint8Array for faster slicing in decode path
  const u8aData = asU8A(data)
  const tokeniser = options.tokenizer || new Tokeniser(u8aData, options)
  const decoded = tokensToObject(tokeniser, options)
  if (decoded === DONE) {
    throw new Error(`${decodeErrPrefix} did not find any content to decode`)
  }
  if (decoded === BREAK) {
    throw new Error(`${decodeErrPrefix} got unexpected break`)
  }
  return [decoded, data.subarray(tokeniser.pos())]
}

/**
 * @param {Uint8Array} data
 * @param {DecodeOptions} [options]
 * @returns {any}
 */
function decode (data, options) {
  const [decoded, remainder] = decodeFirst(data, options)
  if (remainder.length > 0) {
    throw new Error(`${decodeErrPrefix} too many terminals, data makes no sense`)
  }
  return decoded
}

export { Tokeniser, tokensToObject, decode, decodeFirst }
import { is } from './is.js'
import { Token, Type } from './token.js'
import { Bl, U8Bl } from './bl.js'
import { encodeErrPrefix } from './common.js'
import { quickEncodeToken } from './jump.js'
import { asU8A, compare, fromString } from './byte-utils.js'

import { encodeUint, encodeUintValue } from './0uint.js'
import { encodeNegint } from './1negint.js'
import { encodeBytes } from './2bytes.js'
import { encodeString } from './3string.js'
import { encodeArray } from './4array.js'
import { encodeMap } from './5map.js'
import { encodeTag } from './6tag.js'
import { encodeFloat, MINOR_FALSE, MINOR_TRUE, MINOR_NULL, MINOR_UNDEFINED } from './7float.js'

/**
 * @typedef {import('../interface.js').EncodeOptions} EncodeOptions
 * @typedef {import('../interface.js').OptionalTypeEncoder} OptionalTypeEncoder
 * @typedef {import('../interface.js').Reference} Reference
 * @typedef {import('../interface.js').StrictTypeEncoder} StrictTypeEncoder
 * @typedef {import('../interface.js').TokenTypeEncoder} TokenTypeEncoder
 * @typedef {import('../interface.js').TokenOrNestedTokens} TokenOrNestedTokens
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 */

/** @type {EncodeOptions} */
const defaultEncodeOptions = {
  float64: false,
  mapSorter,
  quickEncodeToken
}

/** @type {EncodeOptions} */
export const rfc8949EncodeOptions = Object.freeze({
  mapSorter: rfc8949MapSorter,
  quickEncodeToken
})

/** @returns {TokenTypeEncoder[]} */
export function makeCborEncoders () {
  const encoders = []
  encoders[Type.uint.major] = encodeUint
  encoders[Type.negint.major] = encodeNegint
  encoders[Type.bytes.major] = encodeBytes
  encoders[Type.string.major] = encodeString
  encoders[Type.array.major] = encodeArray
  encoders[Type.map.major] = encodeMap
  encoders[Type.tag.major] = encodeTag
  encoders[Type.float.major] = encodeFloat
  return encoders
}

const cborEncoders = makeCborEncoders()

const defaultWriter = new Bl()

/** @implements {Reference} */
class Ref {
  /**
   * @param {object|any[]} obj
   * @param {Reference|undefined} parent
   */
  constructor (obj, parent) {
    this.obj = obj
    this.parent = parent
  }

  /**
   * @param {object|any[]} obj
   * @returns {boolean}
   */
  includes (obj) {
    /** @type {Reference|undefined} */
    let p = this
    do {
      if (p.obj === obj) {
        return true
      }
    } while (p = p.parent) // eslint-disable-line
    return false
  }

  /**
   * @param {Reference|undefined} stack
   * @param {object|any[]} obj
   * @returns {Reference}
   */
  static createCheck (stack, obj) {
    if (stack && stack.includes(obj)) {
      throw new Error(`${encodeErrPrefix} object contains circular references`)
    }
    return new Ref(obj, stack)
  }
}

const simpleTokens = {
  null: new Token(Type.null, null),
  undefined: new Token(Type.undefined, undefined),
  true: new Token(Type.true, true),
  false: new Token(Type.false, false),
  emptyArray: new Token(Type.array, 0),
  emptyMap: new Token(Type.map, 0)
}

/** @type {{[typeName: string]: StrictTypeEncoder}} */
const typeEncoders = {
  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  number (obj, _typ, _options, _refStack) {
    if (!Number.isInteger(obj) || !Number.isSafeInteger(obj)) {
      return new Token(Type.float, obj)
    } else if (obj >= 0) {
      return new Token(Type.uint, obj)
    } else {
      return new Token(Type.negint, obj)
    }
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  bigint (obj, _typ, _options, _refStack) {
    if (obj >= BigInt(0)) {
      return new Token(Type.uint, obj)
    } else {
      return new Token(Type.negint, obj)
    }
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  Uint8Array (obj, _typ, _options, _refStack) {
    return new Token(Type.bytes, obj)
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  string (obj, _typ, _options, _refStack) {
    return new Token(Type.string, obj)
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  boolean (obj, _typ, _options, _refStack) {
    return obj ? simpleTokens.true : simpleTokens.false
  },

  /**
   * @param {any} _obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  null (_obj, _typ, _options, _refStack) {
    return simpleTokens.null
  },

  /**
   * @param {any} _obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  undefined (_obj, _typ, _options, _refStack) {
    return simpleTokens.undefined
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  ArrayBuffer (obj, _typ, _options, _refStack) {
    return new Token(Type.bytes, new Uint8Array(obj))
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  DataView (obj, _typ, _options, _refStack) {
    return new Token(Type.bytes, new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength))
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} options
   * @param {Reference} [refStack]
   * @returns {TokenOrNestedTokens}
   */
  Array (obj, _typ, options, refStack) {
    if (!obj.length) {
      if (options.addBreakTokens === true) {
        return [simpleTokens.emptyArray, new Token(Type.break)]
      }
      return simpleTokens.emptyArray
    }
    refStack = Ref.createCheck(refStack, obj)
    const entries = []
    let i = 0
    for (const e of obj) {
      entries[i++] = objectToTokens(e, options, refStack)
    }
    if (options.addBreakTokens) {
      return [new Token(Type.array, obj.length), entries, new Token(Type.break)]
    }
    return [new Token(Type.array, obj.length), entries]
  },

  /**
   * @param {any} obj
   * @param {string} typ
   * @param {EncodeOptions} options
   * @param {Reference} [refStack]
   * @returns {TokenOrNestedTokens}
   */
  Object (obj, typ, options, refStack) {
    // could be an Object or a Map
    const isMap = typ !== 'Object'
    // it's slightly quicker to use Object.keys() than Object.entries()
    const keys = isMap ? obj.keys() : Object.keys(obj)
    const maxLength = isMap ? obj.size : keys.length

    /** @type {undefined | [TokenOrNestedTokens, TokenOrNestedTokens][]} */
    let entries

    if (maxLength) {
      // Pre-allocate the array with the expected size
      entries = new Array(maxLength)
      refStack = Ref.createCheck(refStack, obj)
      const skipUndefined = !isMap && options.ignoreUndefinedProperties

      let i = 0
      for (const key of keys) {
        const value = isMap ? obj.get(key) : obj[key]
        if (skipUndefined && value === undefined) {
          continue
        }
        entries[i++] = [
          objectToTokens(key, options, refStack),
          objectToTokens(value, options, refStack)
        ]
      }

      // Truncate only if properties were skipped
      if (i < maxLength) {
        entries.length = i
      }
    }

    if (!entries?.length) {
      if (options.addBreakTokens === true) {
        return [simpleTokens.emptyMap, new Token(Type.break)]
      }
      return simpleTokens.emptyMap
    }

    sortMapEntries(entries, options)
    if (options.addBreakTokens) {
      return [new Token(Type.map, entries.length), entries, new Token(Type.break)]
    }
    return [new Token(Type.map, entries.length), entries]
  },

  /**
   * Encode a `Tagged` wrapper as a CBOR tag header followed by the encoded
   * form of the wrapped value. The value is recursively tokenised through
   * `objectToTokens()` so any registered `typeEncoders` apply to it.
   *
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} options
   * @param {Reference} [refStack]
   * @returns {TokenOrNestedTokens}
   */
  Tagged (obj, _typ, options, refStack) {
    return [
      new Token(Type.tag, obj.tag),
      objectToTokens(obj.value, options, refStack)
    ]
  }
}

typeEncoders.Map = typeEncoders.Object
typeEncoders.Buffer = typeEncoders.Uint8Array
for (const typ of 'Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64'.split(' ')) {
  typeEncoders[`${typ}Array`] = typeEncoders.DataView
}

/**
 * @param {any} obj
 * @param {EncodeOptions} [options]
 * @param {Reference} [refStack]
 * @returns {TokenOrNestedTokens}
 */
function objectToTokens (obj, options = {}, refStack) {
  const typ = is(obj)
  const customTypeEncoder = (options && options.typeEncoders && /** @type {OptionalTypeEncoder} */ options.typeEncoders[typ]) || typeEncoders[typ]
  if (typeof customTypeEncoder === 'function') {
    const tokens = customTypeEncoder(obj, typ, options, refStack)
    if (tokens != null) {
      return tokens
    }
  }
  const typeEncoder = typeEncoders[typ]
  if (!typeEncoder) {
    throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`)
  }
  return typeEncoder(obj, typ, options, refStack)
}

/*
CBOR key sorting is a mess.

The canonicalisation recommendation from https://tools.ietf.org/html/rfc7049#section-3.9
includes the wording:

> The keys in every map must be sorted lowest value to highest.
> Sorting is performed on the bytes of the representation of the key
> data items without paying attention to the 3/5 bit splitting for
> major types.
> ...
>  *  If two keys have different lengths, the shorter one sorts
      earlier;
>  *  If two keys have the same length, the one with the lower value
      in (byte-wise) lexical order sorts earlier.

1. It is not clear what "bytes of the representation of the key" means: is it
   the CBOR representation, or the binary representation of the object itself?
   Consider the int and uint difference here.
2. It is not clear what "without paying attention to" means: do we include it
   and compare on that? Or do we omit the special prefix byte, (mostly) treating
   the key in its plain binary representation form.

The FIDO 2.0: Client To Authenticator Protocol spec takes the original CBOR
wording and clarifies it according to their understanding.
https://fidoalliance.org/specs/fido-v2.0-rd-20170927/fido-client-to-authenticator-protocol-v2.0-rd-20170927.html#message-encoding

> The keys in every map must be sorted lowest value to highest. Sorting is
> performed on the bytes of the representation of the key data items without
> paying attention to the 3/5 bit splitting for major types. The sorting rules
> are:
>  * If the major types are different, the one with the lower value in numerical
>    order sorts earlier.
>  * If two keys have different lengths, the shorter one sorts earlier;
>  * If two keys have the same length, the one with the lower value in
>    (byte-wise) lexical order sorts earlier.

Some other implementations, such as borc, do a full encode then do a
length-first, byte-wise-second comparison:
https://github.com/dignifiedquire/borc/blob/b6bae8b0bcde7c3976b0f0f0957208095c392a36/src/encoder.js#L358
https://github.com/dignifiedquire/borc/blob/b6bae8b0bcde7c3976b0f0f0957208095c392a36/src/utils.js#L143-L151

This has the benefit of being able to easily handle arbitrary keys, including
complex types (maps and arrays).

We'll opt for the FIDO approach, since it affords some efficies since we don't
need a full encode of each key to determine order and can defer to the types
to determine how to most efficiently order their values (i.e. int and uint
ordering can be done on the numbers, no need for byte-wise, for example).

Recommendation: stick to single key types or you'll get into trouble, and prefer
string keys because it's much simpler that way.
*/

/**
 * @param {TokenOrNestedTokens[]} entries
 * @param {EncodeOptions} options
 */
function sortMapEntries (entries, options) {
  if (options.mapSorter) {
    entries.sort(options.mapSorter)
  }
}

/**
 * @param {(Token|Token[])[]} e1
 * @param {(Token|Token[])[]} e2
 * @returns {number}
 */
function mapSorter (e1, e2) {
  // the key position ([0]) could have a single token or an array
  // almost always it'll be a single token but complex key might get involved
  const keyToken1 = Array.isArray(e1[0]) ? e1[0][0] : e1[0]
  const keyToken2 = Array.isArray(e2[0]) ? e2[0][0] : e2[0]

  // different key types
  if (keyToken1.type !== keyToken2.type) {
    return keyToken1.type.compare(keyToken2.type)
  }

  const major = keyToken1.type.major
  // TODO: handle case where cmp === 0 but there are more keyToken e. complex type)
  const tcmp = cborEncoders[major].compareTokens(keyToken1, keyToken2)
  if (tcmp === 0) {
    // duplicate key or complex type where the first token matched,
    // i.e. a map or array and we're only comparing the opening token
    console.warn('WARNING: complex key types used, CBOR key sorting guarantees are gone')
  }
  return tcmp
}

/**
 * @typedef {Token & { _keyBytes?: Uint8Array }} TokenEx
 *
 * @param {(Token|Token[])[]} e1
 * @param {(Token|Token[])[]} e2
 * @returns {number}
 */
function rfc8949MapSorter (e1, e2) {
  if (e1[0] instanceof Token && e2[0] instanceof Token) {
    const t1 = /** @type {TokenEx} */ (e1[0])
    const t2 = /** @type {TokenEx} */ (e2[0])

    if (!t1._keyBytes) {
      t1._keyBytes = encodeRfc8949(t1.value)
    }

    if (!t2._keyBytes) {
      t2._keyBytes = encodeRfc8949(t2.value)
    }

    return compare(t1._keyBytes, t2._keyBytes)
  }

  throw new Error('rfc8949MapSorter: complex key types are not supported yet')
}

/**
 * @param {any} data
 * @returns {Uint8Array}
 */
function encodeRfc8949 (data) {
  return encodeCustom(data, cborEncoders, rfc8949EncodeOptions)
}

/**
 * @param {ByteWriter} writer
 * @param {TokenOrNestedTokens} tokens
 * @param {TokenTypeEncoder[]} encoders
 * @param {EncodeOptions} options
 */
function tokensToEncoded (writer, tokens, encoders, options) {
  if (Array.isArray(tokens)) {
    for (const token of tokens) {
      tokensToEncoded(writer, token, encoders, options)
    }
  } else {
    encoders[tokens.type.major](writer, tokens, options)
  }
}

// CBOR major type prefixes, cached from Type for hot path performance
const MAJOR_UINT = Type.uint.majorEncoded
const MAJOR_NEGINT = Type.negint.majorEncoded
const MAJOR_BYTES = Type.bytes.majorEncoded
const MAJOR_STRING = Type.string.majorEncoded
const MAJOR_ARRAY = Type.array.majorEncoded

// Simple value bytes (CBOR major type 7 + minor value)
const SIMPLE_FALSE = Type.float.majorEncoded | MINOR_FALSE
const SIMPLE_TRUE = Type.float.majorEncoded | MINOR_TRUE
const SIMPLE_NULL = Type.float.majorEncoded | MINOR_NULL
const SIMPLE_UNDEFINED = Type.float.majorEncoded | MINOR_UNDEFINED

const neg1b = BigInt(-1)
const pos1b = BigInt(1)

/**
 * Check if direct encoding can be used for the given options.
 * Direct encoding bypasses token creation for most values.
 * @param {EncodeOptions} options
 * @returns {boolean}
 */
function canDirectEncode (options) {
  // Cannot use direct encode with addBreakTokens (needs special break token handling).
  // Direct encode checks typeEncoders per-value, falling back to tokens as needed.
  // Maps fall back to token-based encoding for efficient key sorting.
  return options.addBreakTokens !== true
}

/**
 * Direct encode a value to the writer, bypassing token creation for most types.
 * Falls back to token-based encoding for custom type encoders.
 * @param {ByteWriter} writer
 * @param {any} data
 * @param {EncodeOptions} options
 * @param {Reference|undefined} refStack
 */
function directEncode (writer, data, options, refStack) {
  const typ = is(data)

  // Check for custom encoder for THIS specific type
  const customEncoder = options.typeEncoders && options.typeEncoders[typ]
  if (customEncoder) {
    const tokens = customEncoder(data, typ, options, refStack)
    if (tokens != null) {
      // Custom encoder returned tokens, serialize immediately
      tokensToEncoded(writer, tokens, cborEncoders, options)
      return
    }
    // Custom encoder returned null, fall through to default handling
  }

  // Direct encode based on type
  switch (typ) {
    case 'null':
      writer.push([SIMPLE_NULL])
      return

    case 'undefined':
      writer.push([SIMPLE_UNDEFINED])
      return

    case 'boolean':
      writer.push([data ? SIMPLE_TRUE : SIMPLE_FALSE])
      return

    case 'number':
      if (!Number.isInteger(data) || !Number.isSafeInteger(data)) {
        // Float, use token encoder for complex float encoding
        encodeFloat(writer, new Token(Type.float, data), options)
      } else if (data >= 0) {
        encodeUintValue(writer, MAJOR_UINT, data)
      } else {
        // Negative integer
        encodeUintValue(writer, MAJOR_NEGINT, data * -1 - 1)
      }
      return

    case 'bigint':
      if (data >= BigInt(0)) {
        encodeUintValue(writer, MAJOR_UINT, data)
      } else {
        encodeUintValue(writer, MAJOR_NEGINT, data * neg1b - pos1b)
      }
      return

    case 'string': {
      const bytes = fromString(data)
      encodeUintValue(writer, MAJOR_STRING, bytes.length)
      writer.push(bytes)
      return
    }

    case 'Uint8Array':
      encodeUintValue(writer, MAJOR_BYTES, data.length)
      writer.push(data)
      return

    case 'Array':
      if (!data.length) {
        writer.push([MAJOR_ARRAY]) // Empty array: 0x80
        return
      }
      refStack = Ref.createCheck(refStack, data)
      encodeUintValue(writer, MAJOR_ARRAY, data.length)
      for (const elem of data) {
        directEncode(writer, elem, options, refStack)
      }
      return

    case 'Object':
    case 'Map':
      // Maps require key sorting, use token-based encoding for efficiency
      // (pre-encoding all keys for sorting is expensive)
      {
        const tokens = typeEncoders.Object(data, typ, options, refStack)
        tokensToEncoded(writer, tokens, cborEncoders, options)
      }
      return

    default:
    // Fall back to token-based encoding for other types (DataView, TypedArrays, etc.)
    {
      const typeEncoder = typeEncoders[typ]
      if (!typeEncoder) {
        throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`)
      }
      const tokens = typeEncoder(data, typ, options, refStack)
      tokensToEncoded(writer, tokens, cborEncoders, options)
    }
  }
}

/**
 * @param {any} data
 * @param {TokenTypeEncoder[]} encoders
 * @param {EncodeOptions} options
 * @param {Uint8Array} [destination]
 * @returns {Uint8Array}
 */
function encodeCustom (data, encoders, options, destination) {
  // arg ordering is different to encodeInto for backward compatibility
  const hasDest = destination instanceof Uint8Array
  let writeTo = hasDest ? new U8Bl(destination) : defaultWriter

  const tokens = objectToTokens(data, options)
  if (!Array.isArray(tokens) && options.quickEncodeToken) {
    const quickBytes = options.quickEncodeToken(tokens)
    if (quickBytes) {
      if (hasDest) {
        // Copy quick bytes into destination buffer
        writeTo.push(quickBytes)
        return writeTo.toBytes()
      }
      return quickBytes
    }
    const encoder = encoders[tokens.type.major]
    if (encoder.encodedSize) {
      const size = encoder.encodedSize(tokens, options)
      if (!hasDest) {
        writeTo = new Bl(size)
      }
      encoder(writeTo, tokens, options)
      // this would be a problem with encodedSize() functions
      if (writeTo.chunks.length !== 1) {
        throw new Error(`Unexpected error: pre-calculated length for ${tokens} was wrong`)
      }
      return hasDest ? writeTo.toBytes() : asU8A(writeTo.chunks[0])
    }
  }
  writeTo.reset()
  tokensToEncoded(writeTo, tokens, encoders, options)
  return writeTo.toBytes(true)
}

/**
 * @param {any} data
 * @param {EncodeOptions} [options]
 * @returns {Uint8Array}
 */
function encode (data, options) {
  options = Object.assign({}, defaultEncodeOptions, options)

  // Use direct encode path when possible
  if (canDirectEncode(options)) {
    defaultWriter.reset()
    directEncode(defaultWriter, data, options, undefined)
    return defaultWriter.toBytes(true)
  }

  return encodeCustom(data, cborEncoders, options)
}

/**
 * @param {any} data
 * @param {Uint8Array} destination
 * @param {EncodeOptions} [options]
 * @returns {{ written: number }}
 */
function encodeInto (data, destination, options) {
  options = Object.assign({}, defaultEncodeOptions, options)

  // Use direct encode path when possible
  if (canDirectEncode(options)) {
    const writer = new U8Bl(destination)
    directEncode(writer, data, options, undefined)
    return { written: writer.toBytes().length }
  }

  const result = encodeCustom(data, cborEncoders, options, destination)
  return { written: result.length }
}

export { objectToTokens, encode, encodeCustom, encodeInto, Ref }
// This is an unfortunate replacement for @sindresorhus/is that we need to
// re-implement for performance purposes. In particular the is.observable()
// check is expensive, and unnecessary for our purposes. The values returned
// are compatible with @sindresorhus/is, however.

// Types that reach getObjectType() - excludes types with fast-paths above:
// primitives (typeof), Array (isArray), Uint8Array (instanceof), plain Object (constructor)
const objectTypeNames = [
  'Object', // for Object.create(null) and other non-plain objects
  'RegExp',
  'Date',
  'Error',
  'Map',
  'Set',
  'WeakMap',
  'WeakSet',
  'ArrayBuffer',
  'SharedArrayBuffer',
  'DataView',
  'Promise',
  'URL',
  'HTMLElement',
  'Int8Array',
  'Uint8ClampedArray',
  'Int16Array',
  'Uint16Array',
  'Int32Array',
  'Uint32Array',
  'Float32Array',
  'Float64Array',
  'BigInt64Array',
  'BigUint64Array',
  'Tagged'
]

/**
 * @param {any} value
 * @returns {string}
 */
export function is (value) {
  if (value === null) {
    return 'null'
  }
  if (value === undefined) {
    return 'undefined'
  }
  if (value === true || value === false) {
    return 'boolean'
  }
  const typeOf = typeof value
  if (typeOf === 'string' || typeOf === 'number' || typeOf === 'bigint' || typeOf === 'symbol') {
    return typeOf
  }
  if (typeOf === 'function') {
    return 'Function'
  }
  if (Array.isArray(value)) {
    return 'Array'
  }
  // Also catches Node.js Buffer which extends Uint8Array
  if (value instanceof Uint8Array) {
    return 'Uint8Array'
  }
  // Fast path for plain objects (most common case after primitives/arrays/bytes)
  if (value.constructor === Object) {
    return 'Object'
  }
  const objectType = getObjectType(value)
  if (objectType) {
    return objectType
  }
  return 'Object'
}

/**
 * @param {any} value
 * @returns {string|undefined}
 */
function getObjectType (value) {
  const objectTypeName = Object.prototype.toString.call(value).slice(8, -1)
  if (objectTypeNames.includes(objectTypeName)) {
    return objectTypeName
  }
  return undefined
}
import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import * as negint from './1negint.js'
import * as bytes from './2bytes.js'
import * as string from './3string.js'
import * as array from './4array.js'
import * as map from './5map.js'
import * as tag from './6tag.js'
import * as float from './7float.js'
import { decodeErrPrefix } from './common.js'
import { fromArray } from './byte-utils.js'

/**
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 */
function invalidMinor (data, pos, minor) {
  throw new Error(`${decodeErrPrefix} encountered invalid minor (${minor}) for major ${data[pos] >>> 5}`)
}

/**
 * @param {string} msg
 * @returns {()=>any}
 */
function errorer (msg) {
  return () => { throw new Error(`${decodeErrPrefix} ${msg}`) }
}

/** @type {((data:Uint8Array, pos:number, minor:number, options?:DecodeOptions) => any)[]} */
export const jump = []

// unsigned integer, 0x00..0x17 (0..23)
for (let i = 0; i <= 0x17; i++) {
  jump[i] = invalidMinor // uint.decodeUintCompact, handled by quick[]
}
jump[0x18] = uint.decodeUint8 // unsigned integer, one-byte uint8_t follows
jump[0x19] = uint.decodeUint16 // unsigned integer, two-byte uint16_t follows
jump[0x1a] = uint.decodeUint32 // unsigned integer, four-byte uint32_t follows
jump[0x1b] = uint.decodeUint64 // unsigned integer, eight-byte uint64_t follows
jump[0x1c] = invalidMinor
jump[0x1d] = invalidMinor
jump[0x1e] = invalidMinor
jump[0x1f] = invalidMinor
// negative integer, -1-0x00..-1-0x17 (-1..-24)
for (let i = 0x20; i <= 0x37; i++) {
  jump[i] = invalidMinor // negintDecode, handled by quick[]
}
jump[0x38] = negint.decodeNegint8 // negative integer, -1-n one-byte uint8_t for n follows
jump[0x39] = negint.decodeNegint16 // negative integer, -1-n two-byte uint16_t for n follows
jump[0x3a] = negint.decodeNegint32 // negative integer, -1-n four-byte uint32_t for follows
jump[0x3b] = negint.decodeNegint64 // negative integer, -1-n eight-byte uint64_t for follows
jump[0x3c] = invalidMinor
jump[0x3d] = invalidMinor
jump[0x3e] = invalidMinor
jump[0x3f] = invalidMinor
// byte string, 0x00..0x17 bytes follow
for (let i = 0x40; i <= 0x57; i++) {
  jump[i] = bytes.decodeBytesCompact
}
jump[0x58] = bytes.decodeBytes8 // byte string, one-byte uint8_t for n, and then n bytes follow
jump[0x59] = bytes.decodeBytes16 // byte string, two-byte uint16_t for n, and then n bytes follow
jump[0x5a] = bytes.decodeBytes32 // byte string, four-byte uint32_t for n, and then n bytes follow
jump[0x5b] = bytes.decodeBytes64 // byte string, eight-byte uint64_t for n, and then n bytes follow
jump[0x5c] = invalidMinor
jump[0x5d] = invalidMinor
jump[0x5e] = invalidMinor
jump[0x5f] = errorer('indefinite length bytes/strings are not supported') // byte string, byte strings follow, terminated by "break"
// UTF-8 string 0x00..0x17 bytes follow
for (let i = 0x60; i <= 0x77; i++) {
  jump[i] = string.decodeStringCompact
}
jump[0x78] = string.decodeString8 // UTF-8 string, one-byte uint8_t for n, and then n bytes follow
jump[0x79] = string.decodeString16 // UTF-8 string, two-byte uint16_t for n, and then n bytes follow
jump[0x7a] = string.decodeString32 // UTF-8 string, four-byte uint32_t for n, and then n bytes follow
jump[0x7b] = string.decodeString64 // UTF-8 string, eight-byte uint64_t for n, and then n bytes follow
jump[0x7c] = invalidMinor
jump[0x7d] = invalidMinor
jump[0x7e] = invalidMinor
jump[0x7f] = errorer('indefinite length bytes/strings are not supported') // UTF-8 strings follow, terminated by "break"
// array, 0x00..0x17 data items follow
for (let i = 0x80; i <= 0x97; i++) {
  jump[i] = array.decodeArrayCompact
}
jump[0x98] = array.decodeArray8 // array, one-byte uint8_t for n, and then n data items follow
jump[0x99] = array.decodeArray16 // array, two-byte uint16_t for n, and then n data items follow
jump[0x9a] = array.decodeArray32 // array, four-byte uint32_t for n, and then n data items follow
jump[0x9b] = array.decodeArray64 // array, eight-byte uint64_t for n, and then n data items follow
jump[0x9c] = invalidMinor
jump[0x9d] = invalidMinor
jump[0x9e] = invalidMinor
jump[0x9f] = array.decodeArrayIndefinite // array, data items follow, terminated by "break"
// map, 0x00..0x17 pairs of data items follow
for (let i = 0xa0; i <= 0xb7; i++) {
  jump[i] = map.decodeMapCompact
}
jump[0xb8] = map.decodeMap8 // map, one-byte uint8_t for n, and then n pairs of data items follow
jump[0xb9] = map.decodeMap16 // map, two-byte uint16_t for n, and then n pairs of data items follow
jump[0xba] = map.decodeMap32 // map, four-byte uint32_t for n, and then n pairs of data items follow
jump[0xbb] = map.decodeMap64 // map, eight-byte uint64_t for n, and then n pairs of data items follow
jump[0xbc] = invalidMinor
jump[0xbd] = invalidMinor
jump[0xbe] = invalidMinor
jump[0xbf] = map.decodeMapIndefinite // map, pairs of data items follow, terminated by "break"
// tags
for (let i = 0xc0; i <= 0xd7; i++) {
  jump[i] = tag.decodeTagCompact
}
jump[0xd8] = tag.decodeTag8
jump[0xd9] = tag.decodeTag16
jump[0xda] = tag.decodeTag32
jump[0xdb] = tag.decodeTag64
jump[0xdc] = invalidMinor
jump[0xdd] = invalidMinor
jump[0xde] = invalidMinor
jump[0xdf] = invalidMinor
// 0xe0..0xf3 simple values, unsupported
for (let i = 0xe0; i <= 0xf3; i++) {
  jump[i] = errorer('simple values are not supported')
}
jump[0xf4] = invalidMinor // false, handled by quick[]
jump[0xf5] = invalidMinor // true, handled by quick[]
jump[0xf6] = invalidMinor // null, handled by quick[]
jump[0xf7] = float.decodeUndefined // undefined
jump[0xf8] = errorer('simple values are not supported') // simple value, one byte follows, unsupported
jump[0xf9] = float.decodeFloat16 // half-precision float (two-byte IEEE 754)
jump[0xfa] = float.decodeFloat32 // single-precision float (four-byte IEEE 754)
jump[0xfb] = float.decodeFloat64 // double-precision float (eight-byte IEEE 754)
jump[0xfc] = invalidMinor
jump[0xfd] = invalidMinor
jump[0xfe] = invalidMinor
jump[0xff] = float.decodeBreak // "break" stop code

/** @type {Token[]} */
export const quick = []
// ints <24
for (let i = 0; i < 24; i++) {
  quick[i] = new Token(Type.uint, i, 1)
}
// negints >= -24
for (let i = -1; i >= -24; i--) {
  quick[31 - i] = new Token(Type.negint, i, 1)
}
// empty bytes
quick[0x40] = new Token(Type.bytes, new Uint8Array(0), 1)
// empty string
quick[0x60] = new Token(Type.string, '', 1)
// empty list
quick[0x80] = new Token(Type.array, 0, 1)
// empty map
quick[0xa0] = new Token(Type.map, 0, 1)
// false
quick[0xf4] = new Token(Type.false, false, 1)
// true
quick[0xf5] = new Token(Type.true, true, 1)
// null
quick[0xf6] = new Token(Type.null, null, 1)

/**
 * @param {Token} token
 * @returns {Uint8Array|undefined}
 */
export function quickEncodeToken (token) {
  switch (token.type) {
    case Type.false:
      return fromArray([0xf4])
    case Type.true:
      return fromArray([0xf5])
    case Type.null:
      return fromArray([0xf6])
    case Type.bytes:
      if (!token.value.length) {
        return fromArray([0x40])
      }
      return
    case Type.string:
      if (token.value === '') {
        return fromArray([0x60])
      }
      return
    case Type.array:
      if (token.value === 0) {
        return fromArray([0x80])
      }
      // shouldn't be possible if this were called when there was only one token
      return
    case Type.map:
      if (token.value === 0) {
        return fromArray([0xa0])
      }
      // shouldn't be possible if this were called when there was only one token
      return
    case Type.uint:
      if (token.value < 24) {
        return fromArray([Number(token.value)])
      }
      return
    case Type.negint:
      if (token.value >= -24) {
        return fromArray([31 - Number(token.value)])
      }
  }
}
/**
 * @typedef {import('../interface.js').TagDecodeControl} TagDecodeControl
 * @typedef {(decode: TagDecodeControl) => Tagged} TaggedTagDecoder
 */

/**
 * A wrapper class for representing a CBOR tag with an arbitrary nested value.
 *
 * `Tagged` is a symmetric primitive: it can be passed to `encode()` to emit
 * a CBOR tag header followed by the encoded form of `value`, and it can be
 * returned from a tag decoder (via `Tagged.decoder(tag)` or `Tagged.preserve()`)
 * to round-trip a tag through decode without losing the tag number.
 *
 * Use `Tagged` for one-off tag handling where defining a dedicated
 * `typeEncoders` entry and tag decoder pair would be heavyweight, e.g. when
 * wrapping a structure in a single application-specific tag (COSE, dCBOR
 * envelopes, etc.).
 *
 * For systematic mapping of a JS type to a tag (e.g. CID -> tag 42), prefer
 * a dedicated `typeEncoders` entry instead.
 */
export class Tagged {
  /**
   * @param {number} tag - CBOR tag number, a non-negative integer
   * @param {any} value - The value to be tagged; encoded recursively
   */
  constructor (tag, value) {
    if (typeof tag !== 'number' || !Number.isInteger(tag) || tag < 0) {
      throw new TypeError('Tagged: tag must be a non-negative integer')
    }
    this.tag = tag
    this.value = value
  }

  /**
   * Build a tag decoder for use in `decode()`'s `tags` option that returns the
   * decoded content wrapped in a `Tagged` instance, preserving the tag number
   * for the caller to inspect.
   *
   * @param {number} tag - The CBOR tag number this decoder will be registered for
   * @returns {TaggedTagDecoder}
   *
   * @example
   * import { decode, Tagged } from 'cborg'
   * const value = decode(bytes, { tags: { 16: Tagged.decoder(16) } })
   * // value instanceof Tagged; value.tag === 16
   */
  static decoder (tag) {
    return (decode) => new Tagged(tag, decode())
  }

  /**
   * Build a `tags` option for `decode()` that wraps each listed tag number in
   * a `Tagged` instance, preserving those tags through decode without
   * registering a dedicated decoder per tag.
   *
   * @param {...number} tagNumbers - One or more CBOR tag numbers to preserve
   * @returns {{[tagNumber: number]: TaggedTagDecoder}}
   *
   * @example
   * import { decode, Tagged } from 'cborg'
   * const value = decode(bytes, { tags: Tagged.preserve(16, 96) })
   */
  static preserve (...tagNumbers) {
    /** @type {{[tagNumber: number]: TaggedTagDecoder}} */
    const tags = {}
    for (const tag of tagNumbers) {
      tags[tag] = Tagged.decoder(tag)
    }
    return tags
  }
}

// Symbol.toStringTag so the internal `is()` type detection returns 'Tagged'
// for instances, allowing the default Tagged typeEncoder to match.
Object.defineProperty(Tagged.prototype, Symbol.toStringTag, {
  value: 'Tagged'
})
class Type {
  /**
   * @param {number} major
   * @param {string} name
   * @param {boolean} terminal
   */
  constructor (major, name, terminal) {
    this.major = major
    this.majorEncoded = major << 5
    this.name = name
    this.terminal = terminal
  }

  toString () {
    return `Type[${this.major}].${this.name}`
  }

  /**
   * @param {Type} typ
   * @returns {number}
   */
  compare (typ) {
    return this.major < typ.major ? -1 : this.major > typ.major ? 1 : 0
  }

  /**
   * Check equality between two Type instances. Safe to use across different
   * copies of the Type class (e.g., when bundlers duplicate the module).
   * (major, name) uniquely identifies a Type; terminal is implied by these.
   * @param {Type} a
   * @param {Type} b
   * @returns {boolean}
   */
  static equals (a, b) {
    return a === b || (a.major === b.major && a.name === b.name)
  }
}

// convert to static fields when better supported
Type.uint = new Type(0, 'uint', true)
Type.negint = new Type(1, 'negint', true)
Type.bytes = new Type(2, 'bytes', true)
Type.string = new Type(3, 'string', true)
Type.array = new Type(4, 'array', false)
Type.map = new Type(5, 'map', false)
Type.tag = new Type(6, 'tag', false) // terminal?
Type.float = new Type(7, 'float', true)
Type.false = new Type(7, 'false', true)
Type.true = new Type(7, 'true', true)
Type.null = new Type(7, 'null', true)
Type.undefined = new Type(7, 'undefined', true)
Type.break = new Type(7, 'break', true)
// Type.indefiniteLength = new Type(0, 'indefiniteLength', true)

class Token {
  /**
   * @param {Type} type
   * @param {any} [value]
   * @param {number} [encodedLength]
   */
  constructor (type, value, encodedLength) {
    this.type = type
    this.value = value
    this.encodedLength = encodedLength
    /** @type {Uint8Array|undefined} */
    this.encodedBytes = undefined
    /** @type {Uint8Array|undefined} */
    this.byteValue = undefined
  }

  toString () {
    return `Token[${this.type}].${this.value}`
  }
}

export { Type, Token }
{
  "name": "cborg",
  "version": "5.1.6",
  "description": "Fast CBOR with a focus on strictness",
  "main": "cborg.js",
  "type": "module",
  "bin": {
    "cborg": "lib/bin.js"
  },
  "scripts": {
    "lint": "standard *.js lib/*.js test/*.js",
    "build": "npm run build:types",
    "build:types": "tsc --build",
    "prepublishOnly": "npm run build",
    "test:node": "mocha test/test-*.js",
    "test:node-bin": "mocha test/node-test-bin.js",
    "test:browser": "polendina --cleanup test/test-*.js",
    "test": "npm run lint && npm run build && npm run test:node && npm run test:node-bin && npm run test:browser",
    "test:ci": "npm run test"
  },
  "repository": {
    "type": "git",
    "url": "git@github.com:rvagg/cborg.git"
  },
  "keywords": [
    "cbor"
  ],
  "author": "Rod <rod@vagg.org> (http://r.va.gg/)",
  "license": "Apache-2.0",
  "devDependencies": {
    "@semantic-release/changelog": "^6.0.3",
    "@semantic-release/commit-analyzer": "^13.0.1",
    "@semantic-release/git": "^10.0.1",
    "@semantic-release/github": "^12.0.6",
    "@semantic-release/npm": "^13.1.5",
    "@semantic-release/release-notes-generator": "^14.1.0",
    "@types/chai": "^5.2.3",
    "@types/mocha": "^10.0.10",
    "@types/node": "^26.0.1",
    "chai": "^6.2.2",
    "conventional-changelog-conventionalcommits": "^10.0.0",
    "ipld-garbage": "^5.0.0",
    "mocha": "^11.7.5",
    "polendina": "^3.2.20",
    "semantic-release": "^25.0.3",
    "standard": "^17.1.2",
    "typescript": "^6.0.2"
  },
  "exports": {
    ".": {
      "import": "./cborg.js",
      "types": "./types/cborg.d.ts"
    },
    "./length": {
      "import": "./lib/length.js",
      "types": "./types/lib/length.d.ts"
    },
    "./taglib": {
      "import": "./lib/taglib.js",
      "types": "./types/lib/taglib.d.ts"
    },
    "./json": {
      "import": "./lib/json/json.js",
      "types": "./types/lib/json/json.d.ts"
    },
    "./extended": {
      "import": "./lib/extended/extended.js",
      "types": "./types/lib/extended/extended.d.ts"
    },
    "./interface": {
      "types": "./types/interface.d.ts"
    }
  },
  "types": "cborg.d.ts",
  "typesVersions": {
    "*": {
      "json": [
        "types/lib/json/json.d.ts"
      ],
      "length": [
        "types/lib/length.d.ts"
      ],
      "*": [
        "types/*"
      ],
      "types/*": [
        "types/*"
      ]
    }
  },
  "release": {
    "branches": [
      "master"
    ],
    "plugins": [
      [
        "@semantic-release/commit-analyzer",
        {
          "preset": "conventionalcommits",
          "releaseRules": [
            {
              "breaking": true,
              "release": "major"
            },
            {
              "revert": true,
              "release": "patch"
            },
            {
              "type": "feat",
              "release": "minor"
            },
            {
              "type": "fix",
              "release": "patch"
            },
            {
              "type": "chore",
              "release": "patch"
            },
            {
              "type": "docs",
              "release": "patch"
            },
            {
              "type": "test",
              "release": "patch"
            },
            {
              "scope": "no-release",
              "release": false
            }
          ]
        }
      ],
      [
        "@semantic-release/release-notes-generator",
        {
          "preset": "conventionalcommits",
          "presetConfig": {
            "types": [
              {
                "type": "feat",
                "section": "Features"
              },
              {
                "type": "fix",
                "section": "Bug Fixes"
              },
              {
                "type": "chore",
                "section": "Trivial Changes"
              },
              {
                "type": "docs",
                "section": "Trivial Changes"
              },
              {
                "type": "test",
                "section": "Tests"
              }
            ]
          }
        }
      ],
      "@semantic-release/changelog",
      "@semantic-release/npm",
      "@semantic-release/github",
      "@semantic-release/git"
    ]
  }
}
import { coerce } from '../bytes.js';
import basex from '../vendor/base-x.js';
/**
 * Class represents both BaseEncoder and MultibaseEncoder meaning it
 * can be used to encode to multibase or base encode without multibase
 * prefix.
 */
class Encoder {
    name;
    prefix;
    baseEncode;
    constructor(name, prefix, baseEncode) {
        this.name = name;
        this.prefix = prefix;
        this.baseEncode = baseEncode;
    }
    encode(bytes) {
        if (bytes instanceof Uint8Array) {
            return `${this.prefix}${this.baseEncode(bytes)}`;
        }
        else {
            throw Error('Unknown type, must be binary type');
        }
    }
}
/**
 * Class represents both BaseDecoder and MultibaseDecoder so it could be used
 * to decode multibases (with matching prefix) or just base decode strings
 * with corresponding base encoding.
 */
class Decoder {
    name;
    prefix;
    baseDecode;
    prefixCodePoint;
    constructor(name, prefix, baseDecode) {
        this.name = name;
        this.prefix = prefix;
        const prefixCodePoint = prefix.codePointAt(0);
        /* c8 ignore next 3 */
        if (prefixCodePoint === undefined) {
            throw new Error('Invalid prefix character');
        }
        this.prefixCodePoint = prefixCodePoint;
        this.baseDecode = baseDecode;
    }
    decode(text) {
        if (typeof text === 'string') {
            if (text.codePointAt(0) !== this.prefixCodePoint) {
                throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);
            }
            return this.baseDecode(text.slice(this.prefix.length));
        }
        else {
            throw Error('Can only multibase decode strings');
        }
    }
    or(decoder) {
        return or(this, decoder);
    }
}
class ComposedDecoder {
    decoders;
    constructor(decoders) {
        this.decoders = decoders;
    }
    or(decoder) {
        return or(this, decoder);
    }
    decode(input) {
        const prefix = input[0];
        const decoder = this.decoders[prefix];
        if (decoder != null) {
            return decoder.decode(input);
        }
        else {
            throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);
        }
    }
}
export function or(left, right) {
    return new ComposedDecoder({
        ...(left.decoders ?? { [left.prefix]: left }),
        ...(right.decoders ?? { [right.prefix]: right })
    });
}
export class Codec {
    name;
    prefix;
    baseEncode;
    baseDecode;
    encoder;
    decoder;
    constructor(name, prefix, baseEncode, baseDecode) {
        this.name = name;
        this.prefix = prefix;
        this.baseEncode = baseEncode;
        this.baseDecode = baseDecode;
        this.encoder = new Encoder(name, prefix, baseEncode);
        this.decoder = new Decoder(name, prefix, baseDecode);
    }
    encode(input) {
        return this.encoder.encode(input);
    }
    decode(input) {
        return this.decoder.decode(input);
    }
}
export function from({ name, prefix, encode, decode }) {
    return new Codec(name, prefix, encode, decode);
}
export function baseX({ name, prefix, alphabet }) {
    const { encode, decode } = basex(alphabet, name);
    return from({
        prefix,
        name,
        encode,
        decode: (text) => coerce(decode(text))
    });
}
function decode(string, alphabetIdx, bitsPerChar, name) {
    // Count the padding bytes:
    let end = string.length;
    while (string[end - 1] === '=') {
        --end;
    }
    // Allocate the output:
    const out = new Uint8Array((end * bitsPerChar / 8) | 0);
    // Parse the data:
    let bits = 0; // Number of bits currently in the buffer
    let buffer = 0; // Bits waiting to be written out, MSB first
    let written = 0; // Next byte to write
    for (let i = 0; i < end; ++i) {
        // Read one character from the string:
        const value = alphabetIdx[string[i]];
        if (value === undefined) {
            throw new SyntaxError(`Non-${name} character`);
        }
        // Append the bits to the buffer:
        buffer = (buffer << bitsPerChar) | value;
        bits += bitsPerChar;
        // Write out some bits if the buffer has a byte's worth:
        if (bits >= 8) {
            bits -= 8;
            out[written++] = 0xff & (buffer >> bits);
        }
    }
    // Verify that we have received just enough bits:
    if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {
        throw new SyntaxError('Unexpected end of data');
    }
    return out;
}
function encode(data, alphabet, bitsPerChar) {
    const pad = alphabet[alphabet.length - 1] === '=';
    const mask = (1 << bitsPerChar) - 1;
    let out = '';
    let bits = 0; // Number of bits currently in the buffer
    let buffer = 0; // Bits waiting to be written out, MSB first
    for (let i = 0; i < data.length; ++i) {
        // Slurp data into the buffer:
        buffer = (buffer << 8) | data[i];
        bits += 8;
        // Write out as much as we can:
        while (bits > bitsPerChar) {
            bits -= bitsPerChar;
            out += alphabet[mask & (buffer >> bits)];
        }
    }
    // Partial character:
    if (bits !== 0) {
        out += alphabet[mask & (buffer << (bitsPerChar - bits))];
    }
    // Add padding characters until we hit a byte boundary:
    if (pad) {
        while (((out.length * bitsPerChar) & 7) !== 0) {
            out += '=';
        }
    }
    return out;
}
function createAlphabetIdx(alphabet) {
    // Build the character lookup table:
    const alphabetIdx = {};
    for (let i = 0; i < alphabet.length; ++i) {
        alphabetIdx[alphabet[i]] = i;
    }
    return alphabetIdx;
}
/**
 * RFC4648 Factory
 */
export function rfc4648({ name, prefix, bitsPerChar, alphabet }) {
    const alphabetIdx = createAlphabetIdx(alphabet);
    return from({
        prefix,
        name,
        encode(input) {
            return encode(input, alphabet, bitsPerChar);
        },
        decode(input) {
            return decode(input, alphabetIdx, bitsPerChar, name);
        }
    });
}
//# sourceMappingURL=base.js.mapimport { rfc4648 } from './base.js';
export const base32 = rfc4648({
    prefix: 'b',
    name: 'base32',
    alphabet: 'abcdefghijklmnopqrstuvwxyz234567',
    bitsPerChar: 5
});
export const base32upper = rfc4648({
    prefix: 'B',
    name: 'base32upper',
    alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',
    bitsPerChar: 5
});
export const base32pad = rfc4648({
    prefix: 'c',
    name: 'base32pad',
    alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',
    bitsPerChar: 5
});
export const base32padupper = rfc4648({
    prefix: 'C',
    name: 'base32padupper',
    alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',
    bitsPerChar: 5
});
export const base32hex = rfc4648({
    prefix: 'v',
    name: 'base32hex',
    alphabet: '0123456789abcdefghijklmnopqrstuv',
    bitsPerChar: 5
});
export const base32hexupper = rfc4648({
    prefix: 'V',
    name: 'base32hexupper',
    alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',
    bitsPerChar: 5
});
export const base32hexpad = rfc4648({
    prefix: 't',
    name: 'base32hexpad',
    alphabet: '0123456789abcdefghijklmnopqrstuv=',
    bitsPerChar: 5
});
export const base32hexpadupper = rfc4648({
    prefix: 'T',
    name: 'base32hexpadupper',
    alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',
    bitsPerChar: 5
});
export const base32z = rfc4648({
    prefix: 'h',
    name: 'base32z',
    alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',
    bitsPerChar: 5
});
//# sourceMappingURL=base32.js.mapimport { baseX } from './base.js';
export const base36 = baseX({
    prefix: 'k',
    name: 'base36',
    alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'
});
export const base36upper = baseX({
    prefix: 'K',
    name: 'base36upper',
    alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
});
//# sourceMappingURL=base36.js.mapimport { baseX } from './base.js';
export const base58btc = baseX({
    name: 'base58btc',
    prefix: 'z',
    alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
});
export const base58flickr = baseX({
    name: 'base58flickr',
    prefix: 'Z',
    alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'
});
//# sourceMappingURL=base58.js.mapexport const empty = new Uint8Array(0);
export function toHex(d) {
    return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '');
}
export function fromHex(hex) {
    const hexes = hex.match(/../g);
    return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty;
}
export function equals(aa, bb) {
    if (aa === bb) {
        return true;
    }
    if (aa.byteLength !== bb.byteLength) {
        return false;
    }
    for (let ii = 0; ii < aa.byteLength; ii++) {
        if (aa[ii] !== bb[ii]) {
            return false;
        }
    }
    return true;
}
export function coerce(o) {
    if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') {
        return o;
    }
    if (o instanceof ArrayBuffer) {
        return new Uint8Array(o);
    }
    if (ArrayBuffer.isView(o)) {
        return new Uint8Array(o.buffer, o.byteOffset, o.byteLength);
    }
    throw new Error('Unknown type, must be binary type');
}
export function isBinary(o) {
    return o instanceof ArrayBuffer || ArrayBuffer.isView(o);
}
export function fromString(str) {
    return new TextEncoder().encode(str);
}
export function toString(b) {
    return new TextDecoder().decode(b);
}
//# sourceMappingURL=bytes.js.mapimport { base32 } from './bases/base32.js';
import { base36 } from './bases/base36.js';
import { base58btc } from './bases/base58.js';
import { coerce } from './bytes.js';
import * as Digest from './hashes/digest.js';
import * as varint from './varint.js';
// This way TS will also expose all the types from module
export * from './link/interface.js';
export function format(link, base) {
    const { bytes, version } = link;
    switch (version) {
        case 0:
            return toStringV0(bytes, baseCache(link), base ?? base58btc.encoder);
        default:
            return toStringV1(bytes, baseCache(link), (base ?? base32.encoder));
    }
}
export function toJSON(link) {
    return {
        '/': format(link)
    };
}
export function fromJSON(json) {
    return CID.parse(json['/']);
}
const cache = new WeakMap();
function baseCache(cid) {
    const baseCache = cache.get(cid);
    if (baseCache == null) {
        const baseCache = new Map();
        cache.set(cid, baseCache);
        return baseCache;
    }
    return baseCache;
}
export class CID {
    code;
    version;
    multihash;
    bytes;
    '/';
    /**
     * @param version - Version of the CID
     * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
     * @param multihash - (Multi)hash of the of the content.
     */
    constructor(version, code, multihash, bytes) {
        this.code = code;
        this.version = version;
        this.multihash = multihash;
        this.bytes = bytes;
        // flag to serializers that this is a CID and
        // should be treated specially
        this['/'] = bytes;
    }
    /**
     * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`
     * please either use `CID.asCID(cid)` or switch to new signalling mechanism
     *
     * @deprecated
     */
    get asCID() {
        return this;
    }
    // ArrayBufferView
    get byteOffset() {
        return this.bytes.byteOffset;
    }
    // ArrayBufferView
    get byteLength() {
        return this.bytes.byteLength;
    }
    toV0() {
        switch (this.version) {
            case 0: {
                return this;
            }
            case 1: {
                const { code, multihash } = this;
                if (code !== DAG_PB_CODE) {
                    throw new Error('Cannot convert a non dag-pb CID to CIDv0');
                }
                // sha2-256
                if (multihash.code !== SHA_256_CODE) {
                    throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0');
                }
                return (CID.createV0(multihash));
            }
            default: {
                throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);
            }
        }
    }
    toV1() {
        switch (this.version) {
            case 0: {
                const { code, digest } = this.multihash;
                const multihash = Digest.create(code, digest);
                return (CID.createV1(this.code, multihash));
            }
            case 1: {
                return this;
            }
            default: {
                throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);
            }
        }
    }
    equals(other) {
        return CID.equals(this, other);
    }
    static equals(self, other) {
        const unknown = other;
        return (unknown != null &&
            self.code === unknown.code &&
            self.version === unknown.version &&
            Digest.equals(self.multihash, unknown.multihash));
    }
    toString(base) {
        return format(this, base);
    }
    toJSON() {
        return { '/': format(this) };
    }
    link() {
        return this;
    }
    [Symbol.toStringTag] = 'CID';
    // Legacy
    [Symbol.for('nodejs.util.inspect.custom')]() {
        return `CID(${this.toString()})`;
    }
    /**
     * Takes any input `value` and returns a `CID` instance if it was
     * a `CID` otherwise returns `null`. If `value` is instanceof `CID`
     * it will return value back. If `value` is not instance of this CID
     * class, but is compatible CID it will return new instance of this
     * `CID` class. Otherwise returns null.
     *
     * This allows two different incompatible versions of CID library to
     * co-exist and interop as long as binary interface is compatible.
     */
    static asCID(input) {
        if (input == null) {
            return null;
        }
        const value = input;
        if (value instanceof CID) {
            // If value is instance of CID then we're all set.
            return value;
        }
        else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {
            // If value isn't instance of this CID class but `this.asCID === this` or
            // `value['/'] === value.bytes` is true it is CID instance coming from a
            // different implementation (diff version or duplicate). In that case we
            // rebase it to this `CID` implementation so caller is guaranteed to get
            // instance with expected API.
            const { version, code, multihash, bytes } = value;
            return new CID(version, code, multihash, bytes ?? encodeCID(version, code, multihash.bytes));
        }
        else if (value[cidSymbol] === true) {
            // If value is a CID from older implementation that used to be tagged via
            // symbol we still rebase it to the this `CID` implementation by
            // delegating that to a constructor.
            const { version, multihash, code } = value;
            const digest = Digest.decode(multihash);
            return CID.create(version, code, digest);
        }
        else {
            // Otherwise value is not a CID (or an incompatible version of it) in
            // which case we return `null`.
            return null;
        }
    }
    /**
     * @param version - Version of the CID
     * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
     * @param digest - (Multi)hash of the of the content.
     */
    static create(version, code, digest) {
        if (typeof code !== 'number') {
            throw new Error('String codecs are no longer supported');
        }
        if (!(digest.bytes instanceof Uint8Array)) {
            throw new Error('Invalid digest');
        }
        switch (version) {
            case 0: {
                if (code !== DAG_PB_CODE) {
                    throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);
                }
                else {
                    return new CID(version, code, digest, digest.bytes);
                }
            }
            case 1: {
                const bytes = encodeCID(version, code, digest.bytes);
                return new CID(version, code, digest, bytes);
            }
            default: {
                throw new Error('Invalid version');
            }
        }
    }
    /**
     * Simplified version of `create` for CIDv0.
     */
    static createV0(digest) {
        return CID.create(0, DAG_PB_CODE, digest);
    }
    /**
     * Simplified version of `create` for CIDv1.
     *
     * @param code - Content encoding format code.
     * @param digest - Multihash of the content.
     */
    static createV1(code, digest) {
        return CID.create(1, code, digest);
    }
    /**
     * Decoded a CID from its binary representation. The byte array must contain
     * only the CID with no additional bytes.
     *
     * An error will be thrown if the bytes provided do not contain a valid
     * binary representation of a CID.
     */
    static decode(bytes) {
        const [cid, remainder] = CID.decodeFirst(bytes);
        if (remainder.length !== 0) {
            throw new Error('Incorrect length');
        }
        return cid;
    }
    /**
     * Decoded a CID from its binary representation at the beginning of a byte
     * array.
     *
     * Returns an array with the first element containing the CID and the second
     * element containing the remainder of the original byte array. The remainder
     * will be a zero-length byte array if the provided bytes only contained a
     * binary CID representation.
     */
    static decodeFirst(bytes) {
        const specs = CID.inspectBytes(bytes);
        const prefixSize = specs.size - specs.multihashSize;
        const multihashBytes = coerce(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));
        if (multihashBytes.byteLength !== specs.multihashSize) {
            throw new Error('Incorrect length');
        }
        const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);
        const digest = new Digest.Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);
        const cid = specs.version === 0
            ? CID.createV0(digest)
            : CID.createV1(specs.codec, digest);
        return [cid, bytes.subarray(specs.size)];
    }
    /**
     * Inspect the initial bytes of a CID to determine its properties.
     *
     * Involves decoding up to 4 varints. Typically this will require only 4 to 6
     * bytes but for larger multicodec code values and larger multihash digest
     * lengths these varints can be quite large. It is recommended that at least
     * 10 bytes be made available in the `initialBytes` argument for a complete
     * inspection.
     */
    static inspectBytes(initialBytes) {
        let offset = 0;
        const next = () => {
            const [i, length] = varint.decode(initialBytes.subarray(offset));
            offset += length;
            return i;
        };
        let version = next();
        let codec = DAG_PB_CODE;
        if (version === 18) {
            // CIDv0
            version = 0;
            offset = 0;
        }
        else {
            codec = next();
        }
        if (version !== 0 && version !== 1) {
            throw new RangeError(`Invalid CID version ${version}`);
        }
        const prefixSize = offset;
        const multihashCode = next(); // multihash code
        const digestSize = next(); // multihash length
        const size = offset + digestSize;
        const multihashSize = size - prefixSize;
        return { version, codec, multihashCode, digestSize, multihashSize, size };
    }
    /**
     * Takes cid in a string representation and creates an instance. If `base`
     * decoder is not provided will use a default from the configuration. It will
     * throw an error if encoding of the CID is not compatible with supplied (or
     * a default decoder).
     */
    static parse(source, base) {
        const [prefix, bytes] = parseCIDtoBytes(source, base);
        const cid = CID.decode(bytes);
        if (cid.version === 0 && source[0] !== 'Q') {
            throw Error('Version 0 CID string must not include multibase prefix');
        }
        // Cache string representation to avoid computing it on `this.toString()`
        baseCache(cid).set(prefix, source);
        return cid;
    }
}
function parseCIDtoBytes(source, base) {
    switch (source[0]) {
        // CIDv0 is parsed differently
        case 'Q': {
            const decoder = base ?? base58btc;
            return [
                base58btc.prefix,
                decoder.decode(`${base58btc.prefix}${source}`)
            ];
        }
        case base58btc.prefix: {
            const decoder = base ?? base58btc;
            return [base58btc.prefix, decoder.decode(source)];
        }
        case base32.prefix: {
            const decoder = base ?? base32;
            return [base32.prefix, decoder.decode(source)];
        }
        case base36.prefix: {
            const decoder = base ?? base36;
            return [base36.prefix, decoder.decode(source)];
        }
        default: {
            if (base == null) {
                throw Error('To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided');
            }
            return [source[0], base.decode(source)];
        }
    }
}
function toStringV0(bytes, cache, base) {
    const { prefix } = base;
    if (prefix !== base58btc.prefix) {
        throw Error(`Cannot string encode V0 in ${base.name} encoding`);
    }
    const cid = cache.get(prefix);
    if (cid == null) {
        const cid = base.encode(bytes).slice(1);
        cache.set(prefix, cid);
        return cid;
    }
    else {
        return cid;
    }
}
function toStringV1(bytes, cache, base) {
    const { prefix } = base;
    const cid = cache.get(prefix);
    if (cid == null) {
        const cid = base.encode(bytes);
        cache.set(prefix, cid);
        return cid;
    }
    else {
        return cid;
    }
}
const DAG_PB_CODE = 0x70;
const SHA_256_CODE = 0x12;
function encodeCID(version, code, multihash) {
    const codeOffset = varint.encodingLength(version);
    const hashOffset = codeOffset + varint.encodingLength(code);
    const bytes = new Uint8Array(hashOffset + multihash.byteLength);
    varint.encodeTo(version, bytes, 0);
    varint.encodeTo(code, bytes, codeOffset);
    bytes.set(multihash, hashOffset);
    return bytes;
}
const cidSymbol = Symbol.for('@ipld/js-cid/CID');
//# sourceMappingURL=cid.js.mapimport { coerce } from '../bytes.js';
export const name = 'raw';
export const code = 0x55;
export function encode(node) {
    return coerce(node);
}
export function decode(data) {
    return coerce(data);
}
//# sourceMappingURL=raw.js.mapimport { coerce, equals as equalBytes } from '../bytes.js';
import * as varint from '../varint.js';
/**
 * Creates a multihash digest.
 */
export function create(code, digest) {
    const size = digest.byteLength;
    const sizeOffset = varint.encodingLength(code);
    const digestOffset = sizeOffset + varint.encodingLength(size);
    const bytes = new Uint8Array(digestOffset + size);
    varint.encodeTo(code, bytes, 0);
    varint.encodeTo(size, bytes, sizeOffset);
    bytes.set(digest, digestOffset);
    return new Digest(code, size, digest, bytes);
}
/**
 * Turns bytes representation of multihash digest into an instance.
 */
export function decode(multihash) {
    const bytes = coerce(multihash);
    const [code, sizeOffset] = varint.decode(bytes);
    const [size, digestOffset] = varint.decode(bytes.subarray(sizeOffset));
    const digest = bytes.subarray(sizeOffset + digestOffset);
    if (digest.byteLength !== size) {
        throw new Error('Incorrect length');
    }
    return new Digest(code, size, digest, bytes);
}
export function equals(a, b) {
    if (a === b) {
        return true;
    }
    else {
        const data = b;
        return (a.code === data.code &&
            a.size === data.size &&
            data.bytes instanceof Uint8Array &&
            equalBytes(a.bytes, data.bytes));
    }
}
/**
 * Represents a multihash digest which carries information about the
 * hashing algorithm and an actual hash digest.
 */
export class Digest {
    code;
    size;
    digest;
    bytes;
    /**
     * Creates a multihash digest.
     */
    constructor(code, size, digest, bytes) {
        this.code = code;
        this.size = size;
        this.digest = digest;
        this.bytes = bytes;
    }
}
/**
 * Used to check that the passed multihash has the passed code
 */
export function hasCode(digest, code) {
    return digest.code === code;
}
//# sourceMappingURL=digest.js.mapexport {};
//# sourceMappingURL=interface.js.mapimport varint from './vendor/varint.js';
export function decode(data, offset = 0) {
    const code = varint.decode(data, offset);
    return [code, varint.decode.bytes];
}
export function encodeTo(int, target, offset = 0) {
    varint.encode(int, target, offset);
    return target;
}
export function encodingLength(int) {
    return varint.encodingLength(int);
}
//# sourceMappingURL=varint.js.map/* eslint-disable */
// base-x encoding / decoding
// Copyright (c) 2018 base-x contributors
// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)
// Distributed under the MIT software license, see the accompanying
// file LICENSE or http://www.opensource.org/licenses/mit-license.php.
/**
 * @param {string} ALPHABET
 * @param {any} name
 */
function base(ALPHABET, name) {
    if (ALPHABET.length >= 255) {
        throw new TypeError('Alphabet too long');
    }
    var BASE_MAP = new Uint8Array(256);
    for (var j = 0; j < BASE_MAP.length; j++) {
        BASE_MAP[j] = 255;
    }
    for (var i = 0; i < ALPHABET.length; i++) {
        var x = ALPHABET.charAt(i);
        var xc = x.charCodeAt(0);
        if (BASE_MAP[xc] !== 255) {
            throw new TypeError(x + ' is ambiguous');
        }
        BASE_MAP[xc] = i;
    }
    var BASE = ALPHABET.length;
    var LEADER = ALPHABET.charAt(0);
    var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up
    var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up
    /**
     * @param {any[] | Iterable<number>} source
     */
    function encode(source) {
        // @ts-ignore
        if (source instanceof Uint8Array)
            ;
        else if (ArrayBuffer.isView(source)) {
            source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
        }
        else if (Array.isArray(source)) {
            source = Uint8Array.from(source);
        }
        if (!(source instanceof Uint8Array)) {
            throw new TypeError('Expected Uint8Array');
        }
        if (source.length === 0) {
            return '';
        }
        // Skip & count leading zeroes.
        var zeroes = 0;
        var length = 0;
        var pbegin = 0;
        var pend = source.length;
        while (pbegin !== pend && source[pbegin] === 0) {
            pbegin++;
            zeroes++;
        }
        // Allocate enough space in big-endian base58 representation.
        var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;
        var b58 = new Uint8Array(size);
        // Process the bytes.
        while (pbegin !== pend) {
            var carry = source[pbegin];
            // Apply "b58 = b58 * 256 + ch".
            var i = 0;
            for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {
                carry += (256 * b58[it1]) >>> 0;
                b58[it1] = (carry % BASE) >>> 0;
                carry = (carry / BASE) >>> 0;
            }
            if (carry !== 0) {
                throw new Error('Non-zero carry');
            }
            length = i;
            pbegin++;
        }
        // Skip leading zeroes in base58 result.
        var it2 = size - length;
        while (it2 !== size && b58[it2] === 0) {
            it2++;
        }
        // Translate the result into a string.
        var str = LEADER.repeat(zeroes);
        for (; it2 < size; ++it2) {
            str += ALPHABET.charAt(b58[it2]);
        }
        return str;
    }
    /**
     * @param {string | string[]} source
     */
    function decodeUnsafe(source) {
        if (typeof source !== 'string') {
            throw new TypeError('Expected String');
        }
        if (source.length === 0) {
            return new Uint8Array();
        }
        var psz = 0;
        // Skip leading spaces.
        if (source[psz] === ' ') {
            return;
        }
        // Skip and count leading '1's.
        var zeroes = 0;
        var length = 0;
        while (source[psz] === LEADER) {
            zeroes++;
            psz++;
        }
        // Allocate enough space in big-endian base256 representation.
        var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.
        var b256 = new Uint8Array(size);
        // Process the characters.
        while (source[psz]) {
            // Decode character
            var carry = BASE_MAP[source.charCodeAt(psz)];
            // Invalid character
            if (carry === 255) {
                return;
            }
            var i = 0;
            for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {
                carry += (BASE * b256[it3]) >>> 0;
                b256[it3] = (carry % 256) >>> 0;
                carry = (carry / 256) >>> 0;
            }
            if (carry !== 0) {
                throw new Error('Non-zero carry');
            }
            length = i;
            psz++;
        }
        // Skip trailing spaces.
        if (source[psz] === ' ') {
            return;
        }
        // Skip leading zeroes in b256.
        var it4 = size - length;
        while (it4 !== size && b256[it4] === 0) {
            it4++;
        }
        var vch = new Uint8Array(zeroes + (size - it4));
        var j = zeroes;
        while (it4 !== size) {
            vch[j++] = b256[it4++];
        }
        return vch;
    }
    /**
     * @param {string | string[]} string
     */
    function decode(string) {
        var buffer = decodeUnsafe(string);
        if (buffer) {
            return buffer;
        }
        throw new Error(`Non-${name} character`);
    }
    return {
        encode: encode,
        decodeUnsafe: decodeUnsafe,
        decode: decode
    };
}
var src = base;
var _brrp__multiformats_scope_baseX = src;
export default _brrp__multiformats_scope_baseX;
//# sourceMappingURL=base-x.js.map/* eslint-disable */
var encode_1 = encode;
var MSB = 0x80, REST = 0x7F, MSBALL = ~REST, INT = Math.pow(2, 31);
/**
 * @param {number} num
 * @param {number[]} out
 * @param {number} offset
 */
function encode(num, out, offset) {
    out = out || [];
    offset = offset || 0;
    var oldOffset = offset;
    while (num >= INT) {
        out[offset++] = (num & 0xFF) | MSB;
        num /= 128;
    }
    while (num & MSBALL) {
        out[offset++] = (num & 0xFF) | MSB;
        num >>>= 7;
    }
    out[offset] = num | 0;
    // @ts-ignore
    encode.bytes = offset - oldOffset + 1;
    return out;
}
var decode = read;
var MSB$1 = 0x80, REST$1 = 0x7F;
/**
 * @param {string | any[]} buf
 * @param {number} offset
 */
function read(buf, offset) {
    var res = 0, offset = offset || 0, shift = 0, counter = offset, b, l = buf.length;
    do {
        if (counter >= l) {
            // @ts-ignore
            read.bytes = 0;
            throw new RangeError('Could not decode varint');
        }
        b = buf[counter++];
        res += shift < 28
            ? (b & REST$1) << shift
            : (b & REST$1) * Math.pow(2, shift);
        shift += 7;
    } while (b >= MSB$1);
    // @ts-ignore
    read.bytes = counter - offset;
    return res;
}
var N1 = Math.pow(2, 7);
var N2 = Math.pow(2, 14);
var N3 = Math.pow(2, 21);
var N4 = Math.pow(2, 28);
var N5 = Math.pow(2, 35);
var N6 = Math.pow(2, 42);
var N7 = Math.pow(2, 49);
var N8 = Math.pow(2, 56);
var N9 = Math.pow(2, 63);
var length = function (/** @type {number} */ value) {
    return (value < N1 ? 1
        : value < N2 ? 2
            : value < N3 ? 3
                : value < N4 ? 4
                    : value < N5 ? 5
                        : value < N6 ? 6
                            : value < N7 ? 7
                                : value < N8 ? 8
                                    : value < N9 ? 9
                                        : 10);
};
var varint = {
    encode: encode_1,
    decode: decode,
    encodingLength: length
};
var _brrp_varint = varint;
export default _brrp_varint;
//# sourceMappingURL=varint.js.map{
  "name": "multiformats",
  "version": "13.4.2",
  "description": "Interface for multihash, multicodec, multibase and CID",
  "author": "Mikeal Rogers <mikeal.rogers@gmail.com> (https://www.mikealrogers.com/)",
  "license": "Apache-2.0 OR MIT",
  "homepage": "https://github.com/multiformats/js-multiformats#readme",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/multiformats/js-multiformats.git"
  },
  "bugs": {
    "url": "https://github.com/multiformats/js-multiformats/issues"
  },
  "publishConfig": {
    "access": "public",
    "provenance": true
  },
  "keywords": [
    "ipfs",
    "ipld",
    "multiformats"
  ],
  "type": "module",
  "types": "./dist/src/index.d.ts",
  "typesVersions": {
    "*": {
      "*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ],
      "src/*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ]
    }
  },
  "files": [
    "src",
    "dist",
    "!dist/test",
    "!**/*.tsbuildinfo"
  ],
  "exports": {
    ".": {
      "types": "./dist/src/index.d.ts",
      "import": "./dist/src/index.js"
    },
    "./bases/base10": {
      "types": "./dist/src/bases/base10.d.ts",
      "import": "./dist/src/bases/base10.js"
    },
    "./bases/base16": {
      "types": "./dist/src/bases/base16.d.ts",
      "import": "./dist/src/bases/base16.js"
    },
    "./bases/base2": {
      "types": "./dist/src/bases/base2.d.ts",
      "import": "./dist/src/bases/base2.js"
    },
    "./bases/base256emoji": {
      "types": "./dist/src/bases/base256emoji.d.ts",
      "import": "./dist/src/bases/base256emoji.js"
    },
    "./bases/base32": {
      "types": "./dist/src/bases/base32.d.ts",
      "import": "./dist/src/bases/base32.js"
    },
    "./bases/base36": {
      "types": "./dist/src/bases/base36.d.ts",
      "import": "./dist/src/bases/base36.js"
    },
    "./bases/base58": {
      "types": "./dist/src/bases/base58.d.ts",
      "import": "./dist/src/bases/base58.js"
    },
    "./bases/base64": {
      "types": "./dist/src/bases/base64.d.ts",
      "import": "./dist/src/bases/base64.js"
    },
    "./bases/base8": {
      "types": "./dist/src/bases/base8.d.ts",
      "import": "./dist/src/bases/base8.js"
    },
    "./bases/identity": {
      "types": "./dist/src/bases/identity.d.ts",
      "import": "./dist/src/bases/identity.js"
    },
    "./bases/interface": {
      "types": "./dist/src/bases/interface.d.ts",
      "import": "./dist/src/bases/interface.js"
    },
    "./basics": {
      "types": "./dist/src/basics.d.ts",
      "import": "./dist/src/basics.js"
    },
    "./block": {
      "types": "./dist/src/block.d.ts",
      "import": "./dist/src/block.js"
    },
    "./block/interface": {
      "types": "./dist/src/block/interface.d.ts",
      "import": "./dist/src/block/interface.js"
    },
    "./bytes": {
      "types": "./dist/src/bytes.d.ts",
      "import": "./dist/src/bytes.js"
    },
    "./cid": {
      "types": "./dist/src/cid.d.ts",
      "import": "./dist/src/cid.js"
    },
    "./codecs/interface": {
      "types": "./dist/src/codecs/interface.d.ts",
      "import": "./dist/src/codecs/interface.js"
    },
    "./codecs/json": {
      "types": "./dist/src/codecs/json.d.ts",
      "import": "./dist/src/codecs/json.js"
    },
    "./codecs/raw": {
      "types": "./dist/src/codecs/raw.d.ts",
      "import": "./dist/src/codecs/raw.js"
    },
    "./hashes/digest": {
      "types": "./dist/src/hashes/digest.d.ts",
      "import": "./dist/src/hashes/digest.js"
    },
    "./hashes/hasher": {
      "types": "./dist/src/hashes/hasher.d.ts",
      "import": "./dist/src/hashes/hasher.js"
    },
    "./hashes/identity": {
      "types": "./dist/src/hashes/identity.d.ts",
      "import": "./dist/src/hashes/identity.js"
    },
    "./hashes/interface": {
      "types": "./dist/src/hashes/interface.d.ts",
      "import": "./dist/src/hashes/interface.js"
    },
    "./hashes/sha1": {
      "types": "./dist/types/src/hashes/sha1.d.ts",
      "browser": "./dist/src/hashes/sha1-browser.js",
      "import": "./dist/src/hashes/sha1.js"
    },
    "./hashes/sha2": {
      "types": "./dist/src/hashes/sha2.d.ts",
      "browser": "./dist/src/hashes/sha2-browser.js",
      "import": "./dist/src/hashes/sha2.js"
    },
    "./interface": {
      "types": "./dist/src/interface.d.ts",
      "import": "./dist/src/interface.js"
    },
    "./link": {
      "types": "./dist/src/link.d.ts",
      "import": "./dist/src/link.js"
    },
    "./link/interface": {
      "types": "./dist/src/link/interface.d.ts",
      "import": "./dist/src/link/interface.js"
    },
    "./traversal": {
      "types": "./dist/src/traversal.d.ts",
      "import": "./dist/src/traversal.js"
    }
  },
  "eslintConfig": {
    "extends": "ipfs",
    "parserOptions": {
      "project": true,
      "sourceType": "module"
    }
  },
  "release": {
    "branches": [
      "master"
    ],
    "plugins": [
      [
        "@semantic-release/commit-analyzer",
        {
          "preset": "conventionalcommits",
          "releaseRules": [
            {
              "breaking": true,
              "release": "major"
            },
            {
              "revert": true,
              "release": "patch"
            },
            {
              "type": "feat",
              "release": "minor"
            },
            {
              "type": "fix",
              "release": "patch"
            },
            {
              "type": "docs",
              "release": "patch"
            },
            {
              "type": "test",
              "release": "patch"
            },
            {
              "type": "deps",
              "release": "patch"
            },
            {
              "scope": "no-release",
              "release": false
            }
          ]
        }
      ],
      [
        "@semantic-release/release-notes-generator",
        {
          "preset": "conventionalcommits",
          "presetConfig": {
            "types": [
              {
                "type": "feat",
                "section": "Features"
              },
              {
                "type": "fix",
                "section": "Bug Fixes"
              },
              {
                "type": "chore",
                "section": "Trivial Changes"
              },
              {
                "type": "docs",
                "section": "Documentation"
              },
              {
                "type": "deps",
                "section": "Dependencies"
              },
              {
                "type": "test",
                "section": "Tests"
              }
            ]
          }
        }
      ],
      "@semantic-release/changelog",
      "@semantic-release/npm",
      "@semantic-release/github",
      [
        "@semantic-release/git",
        {
          "assets": [
            "CHANGELOG.md",
            "package.json"
          ]
        }
      ]
    ]
  },
  "scripts": {
    "clean": "aegir clean",
    "lint": "aegir lint",
    "build": "aegir build",
    "release": "aegir release",
    "docs": "aegir docs",
    "test": "npm run lint && npm run test:node && npm run test:chrome",
    "test:node": "aegir test -t node --cov",
    "test:chrome": "aegir test -t browser --cov",
    "test:chrome-webworker": "aegir test -t webworker",
    "test:firefox": "aegir test -t browser -- --browser firefox",
    "test:firefox-webworker": "aegir test -t webworker -- --browser firefox",
    "test:electron-main": "aegir test -t electron-main"
  },
  "devDependencies": {
    "@stablelib/sha256": "^2.0.0",
    "@stablelib/sha512": "^2.0.0",
    "@types/node": "^25.0.0",
    "aegir": "^47.0.7",
    "buffer": "^6.0.3",
    "cids": "^1.1.9",
    "crypto-hash": "^4.0.0"
  },
  "aegir": {
    "test": {
      "target": [
        "node",
        "browser"
      ]
    }
  },
  "browser": {
    "./hashes/sha1": "./dist/src/hashes/sha1-browser.js",
    "./dist/src/hashes/sha1.js": "./dist/src/hashes/sha1-browser.js",
    "./hashes/sha2": "./dist/src/hashes/sha2-browser.js",
    "./dist/src/hashes/sha2.js": "./dist/src/hashes/sha2-browser.js"
  }
}
{
  "name": "atproto-repo",
  "version": "0.0.1",
  "description": "Byte-exact atproto repo layer — CAR + DAG-CBOR + CID + MST — over Hypercore-friendly primitives. Verified against real relay-accepted repos.",
  "type": "module",
  "main": "lib/repo.js",
  "scripts": {
    "test": "brittle-node test/*.test.js",
    "postinstall": "node scripts/bare-deps.mjs"
  },
  "dependencies": {
    "@ipld/car": "^5.4.0",
    "@ipld/dag-cbor": "^9.2.1",
    "@noble/curves": "^1.9.7",
    "@noble/hashes": "^1.5.0",
    "multiformats": "^13.3.0"
  },
  "devDependencies": {
    "atproto-identity": "file:../atproto-identity",
    "brittle": "^4.0.2"
  }
}
function isBuffer(value) {
  return Buffer.isBuffer(value) || value instanceof Uint8Array
}

function isEncoding(encoding) {
  return Buffer.isEncoding(encoding)
}

function alloc(size, fill, encoding) {
  return Buffer.alloc(size, fill, encoding)
}

function allocUnsafe(size) {
  return Buffer.allocUnsafe(size)
}

function allocUnsafeSlow(size) {
  return Buffer.allocUnsafeSlow(size)
}

function byteLength(string, encoding) {
  return Buffer.byteLength(string, encoding)
}

function compare(a, b) {
  return Buffer.compare(a, b)
}

function concat(buffers, totalLength) {
  return Buffer.concat(buffers, totalLength)
}

function copy(source, target, targetStart, start, end) {
  return toBuffer(source).copy(target, targetStart, start, end)
}

function equals(a, b) {
  return toBuffer(a).equals(b)
}

function fill(buffer, value, offset, end, encoding) {
  return toBuffer(buffer).fill(value, offset, end, encoding)
}

function from(value, encodingOrOffset, length) {
  return Buffer.from(value, encodingOrOffset, length)
}

function includes(buffer, value, byteOffset, encoding) {
  return toBuffer(buffer).includes(value, byteOffset, encoding)
}

function indexOf(buffer, value, byfeOffset, encoding) {
  return toBuffer(buffer).indexOf(value, byfeOffset, encoding)
}

function lastIndexOf(buffer, value, byteOffset, encoding) {
  return toBuffer(buffer).lastIndexOf(value, byteOffset, encoding)
}

function swap16(buffer) {
  return toBuffer(buffer).swap16()
}

function swap32(buffer) {
  return toBuffer(buffer).swap32()
}

function swap64(buffer) {
  return toBuffer(buffer).swap64()
}

function toBuffer(buffer) {
  if (Buffer.isBuffer(buffer)) return buffer
  return Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

function toString(buffer, encoding, start, end) {
  return toBuffer(buffer).toString(encoding, start, end)
}

function write(buffer, string, offset, length, encoding) {
  return toBuffer(buffer).write(string, offset, length, encoding)
}

function readDoubleBE(buffer, offset) {
  return toBuffer(buffer).readDoubleBE(offset)
}

function readDoubleLE(buffer, offset) {
  return toBuffer(buffer).readDoubleLE(offset)
}

function readFloatBE(buffer, offset) {
  return toBuffer(buffer).readFloatBE(offset)
}

function readFloatLE(buffer, offset) {
  return toBuffer(buffer).readFloatLE(offset)
}

function readInt32BE(buffer, offset) {
  return toBuffer(buffer).readInt32BE(offset)
}

function readInt32LE(buffer, offset) {
  return toBuffer(buffer).readInt32LE(offset)
}

function readUInt32BE(buffer, offset) {
  return toBuffer(buffer).readUInt32BE(offset)
}

function readUInt32LE(buffer, offset) {
  return toBuffer(buffer).readUInt32LE(offset)
}

function writeDoubleBE(buffer, value, offset) {
  return toBuffer(buffer).writeDoubleBE(value, offset)
}

function writeDoubleLE(buffer, value, offset) {
  return toBuffer(buffer).writeDoubleLE(value, offset)
}

function writeFloatBE(buffer, value, offset) {
  return toBuffer(buffer).writeFloatBE(value, offset)
}

function writeFloatLE(buffer, value, offset) {
  return toBuffer(buffer).writeFloatLE(value, offset)
}

function writeInt32BE(buffer, value, offset) {
  return toBuffer(buffer).writeInt32BE(value, offset)
}

function writeInt32LE(buffer, value, offset) {
  return toBuffer(buffer).writeInt32LE(value, offset)
}

function writeUInt32BE(buffer, value, offset) {
  return toBuffer(buffer).writeUInt32BE(value, offset)
}

function writeUInt32LE(buffer, value, offset) {
  return toBuffer(buffer).writeUInt32LE(value, offset)
}

module.exports = {
  isBuffer,
  isEncoding,
  alloc,
  allocUnsafe,
  allocUnsafeSlow,
  byteLength,
  compare,
  concat,
  copy,
  equals,
  fill,
  from,
  includes,
  indexOf,
  lastIndexOf,
  swap16,
  swap32,
  swap64,
  toBuffer,
  toString,
  write,
  readDoubleBE,
  readDoubleLE,
  readFloatBE,
  readFloatLE,
  readInt32BE,
  readInt32LE,
  readUInt32BE,
  readUInt32LE,
  writeDoubleBE,
  writeDoubleLE,
  writeFloatBE,
  writeFloatLE,
  writeInt32BE,
  writeInt32LE,
  writeUInt32BE,
  writeUInt32LE
}
{
  "name": "b4a",
  "version": "1.8.1",
  "description": "Bridging the gap between buffers and typed arrays",
  "exports": {
    "./package": "./package.json",
    ".": {
      "react-native": "./react-native.js",
      "browser": "./browser.js",
      "default": "./index.js"
    }
  },
  "files": [
    "browser.js",
    "index.js",
    "react-native.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:bare && npm run test:node",
    "test:bare": "brittle-bare --coverage test.mjs",
    "test:node": "brittle-node --coverage test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/b4a.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/b4a/issues"
  },
  "homepage": "https://github.com/holepunchto/b4a#readme",
  "devDependencies": {
    "brittle": "^3.5.2",
    "lunte": "^1.7.0",
    "nanobench": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "react-native-b4a": "*"
  },
  "peerDependenciesMeta": {
    "react-native-b4a": {
      "optional": true
    }
  }
}
const ESC = '\x1b'
const CSI = ESC + '['
const SGR = (n) => CSI + n + 'm'

exports.constants = {
  ESC,
  CSI,
  SGR
}

// https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_(Control_Sequence_Introducer)_sequences

exports.cursorHide = CSI + '?25l'
exports.cursorShow = CSI + '?25h'

exports.cursorUp = function cursorUp(n = 1) {
  return CSI + n + 'A'
}

exports.cursorDown = function cursorDown(n = 1) {
  return CSI + n + 'B'
}

exports.cursorForward = function cursorForward(n = 1) {
  return CSI + n + 'C'
}

exports.cursorBack = function cursorBack(n = 1) {
  return CSI + n + 'D'
}

exports.cursorNextLine = function cursorNextLine(n = 1) {
  return CSI + n + 'E'
}

exports.cursorPreviousLine = function cursorPreviousLine(n = 1) {
  return CSI + n + 'F'
}

exports.cursorPosition = function cursorPosition(column, row = 0) {
  if (row === 0) return CSI + (column + 1) + 'G'

  return CSI + (row + 1) + ';' + (column + 1) + 'H'
}

exports.eraseDisplayEnd = CSI + 'J'
exports.eraseDisplayStart = CSI + '1J'
exports.eraseDisplay = CSI + '2J'
exports.eraseLineEnd = CSI + 'K'
exports.eraseLineStart = CSI + '1K'
exports.eraseLine = CSI + '2K'

exports.scrollUp = function scrollUp(n = 1) {
  return CSI + n + 'S'
}

exports.scrollDown = function scrollDown(n = 1) {
  return CSI + n + 'T'
}

// https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_(Select_Graphic_Rendition)_parameters

exports.modifierReset = SGR(0)
exports.modifierBold = SGR(1)
exports.modifierDim = SGR(2)
exports.modifierItalic = SGR(3)
exports.modifierUnderline = SGR(4)
exports.modifierNormal = SGR(22)
exports.modifierNotItalic = SGR(23)
exports.modifierNotUnderline = SGR(24)

// https://en.wikipedia.org/wiki/ANSI_escape_code#Colors

exports.colorBlack = SGR(30)
exports.colorRed = SGR(31)
exports.colorGreen = SGR(32)
exports.colorYellow = SGR(33)
exports.colorBlue = SGR(34)
exports.colorMagenta = SGR(35)
exports.colorCyan = SGR(36)
exports.colorWhite = SGR(37)
exports.colorDefault = SGR(39)
exports.colorBrightBlack = SGR(90)
exports.colorBrightRed = SGR(91)
exports.colorBrightGreen = SGR(92)
exports.colorBrightYellow = SGR(93)
exports.colorBrightBlue = SGR(94)
exports.colorBrightMagenta = SGR(95)
exports.colorBrightCyan = SGR(96)
exports.colorBrightWhite = SGR(97)
{
  "name": "bare-ansi-escapes",
  "version": "2.2.3",
  "description": "Parse and produce ANSI escape sequences",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./key-decoder": {
      "types": "./key-decoder.d.ts",
      "default": "./key-decoder.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "key-decoder.js",
    "key-decoder.d.ts"
  ],
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-ansi-escapes.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-ansi-escapes/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-ansi-escapes#readme",
  "dependencies": {
    "bare-stream": "^2.6.5"
  },
  "devDependencies": {
    "bare-buffer": "^3.0.2",
    "brittle": "^3.3.2",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  },
  "peerDependencies": {
    "bare-buffer": "*"
  },
  "peerDependenciesMeta": {
    "bare-buffer": {
      "optional": true
    }
  }
}
const inspect = require('bare-inspect')

class AssertionError extends Error {
  constructor(opts = {}) {
    let { message = null, actual, expected, operator } = opts

    if (message === null) {
      message = `${inspect(actual)} ${operator} ${inspect(expected)}`
    }

    super(message)

    this.actual = actual
    this.expected = expected
    this.operator = operator
  }

  get name() {
    return 'AssertionError'
  }

  get code() {
    'ASSERTION'
  }
}

function assertFail(opts, fn) {
  if (opts.message instanceof Error) throw opts.message

  const err = new AssertionError(opts)

  if (Error.captureStackTrace) Error.captureStackTrace(err, fn)

  throw err
}

module.exports = exports = function assert(actual, message) {
  if (actual) return

  assertFail({ message, actual, expected: true, operator: '==' }, assert)
}

exports.AssertionError = AssertionError

exports.fail = function fail(message) {
  if (message === undefined) message = 'Failed'

  assertFail({ message, operator: 'fail' }, fail)
}

exports.ok = function ok(actual, message) {
  if (actual) return

  assertFail({ message, actual, expected: true, operator: '==' }, ok)
}

exports.notOk = function ok(actual, message) {
  if (!actual) return

  assertFail({ message, actual, expected: false, operator: '==' }, ok)
}

exports.equal = function equal(actual, expected, message) {
  if (actual == expected || (actual !== actual && expected !== expected)) {
    return
  }

  assertFail({ message, actual, expected, operator: '==' }, equal)
}

exports.notEqual = function notEqual(actual, expected, message) {
  if (actual != expected && (actual === actual || expected === expected)) {
    return
  }

  assertFail({ message, actual, expected, operator: '!=' }, notEqual)
}

exports.strictEqual = function strictEqual(actual, expected, message) {
  if (Object.is(actual, expected)) return

  assertFail(
    { message, actual, expected, operator: 'strictEqual' },
    strictEqual
  )
}

exports.notStrictEqual = function notStrictEqual(actual, expected, message) {
  if (!Object.is(actual, expected)) return

  assertFail(
    { message, actual, expected, operator: 'notStrictEqual' },
    notStrictEqual
  )
}
{
  "name": "bare-assert",
  "version": "1.2.0",
  "description": "Assertion library for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts"
  ],
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-assert.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-assert/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-assert#readme",
  "dependencies": {
    "bare-inspect": "^3.1.2"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  }
}
const errors = require('./lib/errors')

class EventListener {
  constructor() {
    this.list = []
    this.count = 0
  }

  append(ctx, name, fn, once) {
    this.count++
    ctx.emit('newListener', name, fn) // Emit BEFORE adding
    this.list.push([fn, once])
  }

  prepend(ctx, name, fn, once) {
    this.count++
    ctx.emit('newListener', name, fn) // Emit BEFORE adding
    this.list.unshift([fn, once])
  }

  remove(ctx, name, fn) {
    for (let i = 0, n = this.list.length; i < n; i++) {
      const l = this.list[i]

      if (l[0] === fn) {
        this.list.splice(i, 1)

        if (this.count === 1) delete ctx._events[name]

        ctx.emit('removeListener', name, fn) // Emit AFTER removing

        this.count--
        return
      }
    }
  }

  removeAll(ctx, name) {
    const list = [...this.list]
    this.list = []

    if (this.count === list.length) delete ctx._events[name]

    for (let i = list.length - 1; i >= 0; i--) {
      ctx.emit('removeListener', name, list[i][0]) // Emit AFTER removing
    }

    this.count -= list.length
  }

  emit(ctx, name, ...args) {
    const list = [...this.list]

    for (let i = 0, n = list.length; i < n; i++) {
      const l = list[i]

      if (l[1] === true) this.remove(ctx, name, l[0])

      Reflect.apply(l[0], ctx, args)
    }

    return list.length > 0
  }
}

function appendListener(ctx, name, fn, once) {
  if (ctx._events === undefined) ctx._events = Object.create(null)
  const e = ctx._events[name] || (ctx._events[name] = new EventListener())
  e.append(ctx, name, fn, once)
  return ctx
}

function prependListener(ctx, name, fn, once) {
  if (ctx._events === undefined) ctx._events = Object.create(null)
  const e = ctx._events[name] || (ctx._events[name] = new EventListener())
  e.prepend(ctx, name, fn, once)
  return ctx
}

function removeListener(ctx, name, fn) {
  if (ctx._events === undefined) return ctx
  const e = ctx._events[name]
  if (e !== undefined) e.remove(ctx, name, fn)
  return ctx
}

function throwUnhandledError(...args) {
  let err

  if (args.length > 0) err = args[0]

  if (err instanceof Error === false) err = errors.UNHANDLED_ERROR(err)

  if (Error.captureStackTrace) {
    Error.captureStackTrace(err, exports.prototype.emit)
  }

  queueMicrotask(() => {
    throw err
  })
}

module.exports = exports = class EventEmitter {
  constructor() {
    this._events = Object.create(null)
  }

  addListener(name, fn) {
    return appendListener(this, name, fn, false)
  }

  addOnceListener(name, fn) {
    return appendListener(this, name, fn, true)
  }

  prependListener(name, fn) {
    return prependListener(this, name, fn, false)
  }

  prependOnceListener(name, fn) {
    return prependListener(this, name, fn, true)
  }

  removeListener(name, fn) {
    return removeListener(this, name, fn)
  }

  on(name, fn) {
    return appendListener(this, name, fn, false)
  }

  once(name, fn) {
    return appendListener(this, name, fn, true)
  }

  off(name, fn) {
    return removeListener(this, name, fn)
  }

  emit(name, ...args) {
    if (name === 'error' && this._events !== undefined && this._events.error === undefined) {
      throwUnhandledError(...args)
    }

    if (this._events === undefined) return false
    const e = this._events[name]
    return e === undefined ? false : e.emit(this, name, ...args)
  }

  listeners(name) {
    if (this._events === undefined) return []
    const e = this._events[name]
    return e === undefined ? [] : [...e.list]
  }

  rawListeners(name) {
    if (this._events === undefined) return []
    const e = this._events[name]
    return e === undefined ? [] : e.list.map((l) => l[0])
  }

  eventNames() {
    if (this._events === undefined) return []
    return Reflect.ownKeys(this._events)
  }

  listenerCount(name) {
    if (this._events === undefined) return 0
    const e = this._events[name]
    return e === undefined ? 0 : e.list.length
  }

  getMaxListeners() {
    return EventEmitter.defaultMaxListeners
  }

  setMaxListeners(n) {}

  removeAllListeners(name) {
    if (arguments.length === 0) {
      for (const key of Reflect.ownKeys(this._events)) {
        if (key === 'removeListener') continue
        this.removeAllListeners(key)
      }
      this.removeAllListeners('removeListener')
    } else {
      const e = this._events[name]
      if (e !== undefined) e.removeAll(this, name)
    }
    return this
  }
}

exports.EventEmitter = exports

exports.errors = errors

exports.defaultMaxListeners = 10

exports.on = function on(emitter, name, opts = {}) {
  const { signal } = opts

  if (signal && signal.aborted) {
    throw errors.OPERATION_ABORTED(signal.reason)
  }

  let error = null
  let done = false

  const events = []
  const promises = []

  if (name !== 'error') emitter.on('error', onerror)

  if (signal) signal.addEventListener('abort', onabort)

  emitter.on(name, onevent)

  return {
    next() {
      if (events.length) {
        return Promise.resolve({ value: events.shift(), done: false })
      }

      if (error) {
        const err = error

        error = null

        return Promise.reject(err)
      }

      if (done) return onclose()

      return new Promise((resolve, reject) => promises.push({ resolve, reject }))
    },

    return() {
      return onclose()
    },

    throw(err) {
      return onerror(err)
    },

    [Symbol.asyncIterator]() {
      return this
    }
  }

  function onevent(...args) {
    if (promises.length) {
      promises.shift().resolve({ value: args, done: false })
    } else {
      events.push(args)
    }
  }

  function onerror(err) {
    emitter.off(name, onevent).off('error', onerror)

    if (promises.length) {
      promises.shift().reject(err)
    } else {
      error = err
    }

    return Promise.resolve({ done: true })
  }

  function onabort() {
    signal.removeEventListener('abort', onabort)

    onerror(errors.OPERATION_ABORTED(signal.reason))
  }

  function onclose() {
    emitter.off(name, onevent)

    if (name !== 'error') emitter.off('error', onerror)

    if (signal) signal.removeEventListener('abort', onabort)

    done = true

    if (promises.length) promises.shift().resolve({ done: true })

    return Promise.resolve({ done: true })
  }
}

exports.once = function once(emitter, name, opts = {}) {
  const { signal } = opts

  if (signal && signal.aborted) {
    return Promise.reject(errors.OPERATION_ABORTED(signal.reason))
  }

  return new Promise((resolve, reject) => {
    if (name !== 'error') emitter.on('error', onerror)

    if (signal) signal.addEventListener('abort', onabort)

    emitter.once(name, onevent)

    function onevent(...args) {
      if (name !== 'error') emitter.off('error', onerror)

      if (signal) signal.removeEventListener('abort', onabort)

      resolve(args)
    }

    function onerror(err) {
      emitter.off(name, onevent)

      if (name !== 'error') emitter.off('error', onerror)

      reject(err)
    }

    function onabort() {
      signal.removeEventListener('abort', onabort)

      onerror(errors.OPERATION_ABORTED(signal.reason))
    }
  })
}

exports.forward = function forward(from, to, names, opts = {}) {
  if (typeof names === 'string') names = [names]

  const { emit = to.emit.bind(to) } = opts

  const listeners = names.map(
    (name) =>
      function onevent(...args) {
        emit(name, ...args)
      }
  )

  to.on('newListener', (name) => {
    const i = names.indexOf(name)

    if (i !== -1 && to.listenerCount(name) === 0) {
      from.on(name, listeners[i])
    }
  }).on('removeListener', (name) => {
    const i = names.indexOf(name)

    if (i !== -1 && to.listenerCount(name) === 0) {
      from.off(name, listeners[i])
    }
  })
}

exports.listenerCount = function listenerCount(emitter, name) {
  return emitter.listenerCount(name)
}

exports.getMaxListeners = function getMaxListeners(emitter) {
  if (typeof emitter.getMaxListeners === 'function') {
    return emitter.getMaxListeners()
  }

  return exports.defaultMaxListeners
}

exports.setMaxListeners = function setMaxListeners(n, ...emitters) {
  if (emitters.length === 0) exports.defaultMaxListeners = n
  else {
    for (const emitter of emitters) {
      if (typeof emitter.setMaxListeners === 'function') {
        emitter.setMaxListeners(n)
      }
    }
  }
}
module.exports = class EventEmitterError extends Error {
  constructor(msg, code, fn = EventEmitterError, opts) {
    super(`${code}: ${msg}`, opts)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'EventEmitterError'
  }

  static OPERATION_ABORTED(cause, msg = 'Operation aborted') {
    return new EventEmitterError(msg, 'OPERATION_ABORTED', EventEmitterError.OPERATION_ABORTED, {
      cause
    })
  }

  static UNHANDLED_ERROR(cause, msg = 'Unhandled error') {
    return new EventEmitterError(msg, 'UNHANDLED_ERROR', EventEmitterError.UNHANDLED_ERROR, {
      cause
    })
  }
}
{
  "name": "bare-events",
  "version": "2.9.1",
  "description": "Event emitters for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    },
    "./web": {
      "types": "./web.d.ts",
      "default": "./web.js"
    },
    "./errors": "./lib/errors.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "global.js",
    "global.d.ts",
    "web.js",
    "web.d.ts",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:bare && npm run test:node",
    "test:bare": "brittle-bare --coverage test.js",
    "test:node": "brittle-node --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-events.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-events/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-events#readme",
  "devDependencies": {
    "bare-abort-controller": "^1.0.0",
    "brittle": "^3.3.2",
    "lunte": "^1.8.0",
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^2.0.0",
    "uncaughts": "^1.1.1"
  },
  "peerDependencies": {
    "bare-abort-controller": "*"
  },
  "peerDependenciesMeta": {
    "bare-abort-controller": {
      "optional": true
    }
  }
}
module.exports = require.addon()
const FIFO = require('fast-fifo')
const EventEmitter = require('bare-events')
const path = require('bare-path')
const { isURL, fileURLToPath } = require('bare-url')
const { Readable, Writable } = require('bare-stream')
const binding = require('./binding')
const constants = require('./lib/constants')
const FileError = require('./lib/errors')

const isWindows = Bare.platform === 'win32'

exports.constants = constants

class FileRequest {
  static borrow() {
    if (this._free.length > 0) return this._free.pop()
    return new FileRequest()
  }

  static return(req) {
    if (this._free.length < 32) this._free.push(req.reset())
    else req.destroy()
  }

  constructor() {
    this._reset()
    this._handle = binding.requestInit(this, this._onresult)
  }

  get handle() {
    return this._handle
  }

  retain(value) {
    this._retain = value // Tie the lifetime of `value` to the lifetime of `this`
  }

  reset() {
    if (this._handle === null) return this

    binding.requestReset(this._handle)

    this._reset()

    return this
  }

  destroy() {
    if (this._handle === null) return this

    binding.requestDestroy(this._handle)

    this._reset()
    this._handle = null

    return this
  }

  then(resolve, reject) {
    return this._promise.then(resolve, reject)
  }

  return() {
    if (this._handle === null) return this

    FileRequest.return(this)

    return this
  }

  _reset() {
    this._promise = new Promise((resolve, reject) => {
      this._resolve = resolve
      this._reject = reject
    })
    this._retain = null
  }

  _onresult(err, status) {
    if (err) this._reject(err)
    else this._resolve(status)
  }
}

FileRequest._free = []

function ok(result, cb) {
  if (typeof result === 'function') {
    cb = result
    result = undefined
  }

  if (cb) cb(null, result)
  else return result
}

function fail(err, cb) {
  if (cb) cb(err)
  else throw err
}

function done(err, result, cb) {
  if (typeof result === 'function') {
    cb = result
    result = undefined
  }

  if (err) fail(err, cb)
  else return ok(result, cb)
}

async function open(filepath, flags = 'r', mode = 0o666, cb) {
  if (typeof flags === 'function') {
    cb = flags
    flags = 'r'
    mode = 0o666
  } else if (typeof mode === 'function') {
    cb = mode
    mode = 0o666
  }

  if (typeof flags === 'string') flags = toFlags(flags)
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let fd
  let err = null
  try {
    binding.open(req.handle, filepath, flags, mode)

    fd = await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'open',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, fd, cb)
}

function openSync(filepath, flags = 'r', mode = 0o666) {
  if (typeof flags === 'string') flags = toFlags(flags)
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    return binding.openSync(req.handle, filepath, flags, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'open',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function close(fd, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.close(req.handle, fd)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'close', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function closeSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.closeSync(req.handle, fd)
  } catch (e) {
    throw new FileError(e.message, { operation: 'close', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function access(filepath, mode = constants.F_OK, cb) {
  if (typeof mode === 'function') {
    cb = mode
    mode = constants.F_OK
  }

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.access(req.handle, filepath, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'access',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function accessSync(filepath, mode = constants.F_OK) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.accessSync(req.handle, filepath, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'access',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function exists(filepath, cb) {
  let ok = true
  try {
    await access(filepath)
  } catch {
    ok = false
  }

  return done(null, ok, cb)
}

function existsSync(filepath) {
  try {
    accessSync(filepath)
  } catch {
    return false
  }

  return true
}

async function read(fd, buffer, offset = 0, len = buffer.byteLength - offset, pos = -1, cb) {
  if (typeof offset === 'function') {
    cb = offset
    offset = 0
    len = buffer.byteLength
    pos = -1
  } else if (typeof len === 'function') {
    cb = len
    len = buffer.byteLength - offset
    pos = -1
  } else if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.read(req.handle, fd, buffer, offset, len, pos)

    req.retain(buffer)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'read', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function readSync(fd, buffer, offset = 0, len = buffer.byteLength - offset, pos = -1) {
  const req = FileRequest.borrow()

  try {
    return binding.readSync(req.handle, fd, buffer, offset, len, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'read', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function readv(fd, buffers, pos = -1, cb) {
  if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.readv(req.handle, fd, buffers, pos)

    req.retain(buffers)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'readv', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function readvSync(fd, buffers, pos = -1) {
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  try {
    return binding.readvSync(req.handle, fd, buffers, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'readv', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function write(fd, data, offset, len, pos = -1, cb) {
  if (typeof data === 'string') {
    let encoding = len
    cb = pos
    pos = offset

    if (typeof pos === 'function') {
      cb = pos
      pos = -1
      encoding = 'utf8'
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = 'utf8'
    }

    if (typeof pos === 'string') {
      encoding = pos
      pos = -1
    }

    data = Buffer.from(data, encoding)
    offset = 0
    len = data.byteLength
  } else if (typeof offset === 'function') {
    cb = offset
    offset = 0
    len = data.byteLength
    pos = -1
  } else if (typeof len === 'function') {
    cb = len
    len = data.byteLength - offset
    pos = -1
  } else if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof offset !== 'number') offset = 0
  if (typeof len !== 'number') len = data.byteLength - offset
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.write(req.handle, fd, data, offset, len, pos)

    req.retain(data)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'write', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function writeSync(fd, data, offset, len, pos = -1) {
  if (typeof data === 'string') {
    let encoding = len
    pos = offset

    if (typeof pos === 'string') {
      encoding = pos
      pos = -1
    }

    data = Buffer.from(data, encoding)
    offset = 0
    len = data.byteLength
  }

  if (typeof offset !== 'number') offset = 0
  if (typeof len !== 'number') len = data.byteLength - offset
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  try {
    return binding.writeSync(req.handle, fd, data, offset, len, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'write', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function writev(fd, buffers, pos = -1, cb) {
  if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.writev(req.handle, fd, buffers, pos)

    req.retain(buffers)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'writev', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function writevSync(fd, buffers, pos = -1) {
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  try {
    return binding.writevSync(req.handle, fd, buffers, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'writev', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function stat(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.stat(req.handle, filepath)

    await req

    st = new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'stat', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function statSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.statSync(req.handle, filepath)

    return new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'stat', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function lstat(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.lstat(req.handle, filepath)

    await req

    st = new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'lstat', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function lstatSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.lstatSync(req.handle, filepath)

    return new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'lstat', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function fstat(fd, cb) {
  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.fstat(req.handle, fd)

    await req

    st = new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'fstat', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function fstatSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.fstatSync(req.handle, fd)

    return new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'fstat', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function statfs(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.statfs(req.handle, filepath)

    await req

    st = new StatFs(...binding.requestResultStatfs(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'statfs', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function statfsSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.statfsSync(req.handle, filepath)

    return new StatFs(...binding.requestResultStatfs(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'statfs', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function ftruncate(fd, len = 0, cb) {
  if (typeof len === 'function') {
    cb = len
    len = 0
  }

  if (typeof len !== 'number') len = 0

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.ftruncate(req.handle, fd, len)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'ftruncate', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function ftruncateSync(fd, len = 0) {
  if (typeof len !== 'number') len = 0

  const req = FileRequest.borrow()

  try {
    binding.ftruncateSync(req.handle, fd, len)
  } catch (e) {
    throw new FileError(e.message, { operation: 'ftruncate', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function truncate(filepath, len, cb) {
  let fd = -1
  let err

  try {
    fd = await open(filepath, 'r+')

    await ftruncate(fd, len)
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) await close(fd)
  }

  return done(err, cb)
}

function truncateSync(filepath, len) {
  let fd = -1
  let err

  try {
    fd = openSync(filepath, 'r+')

    ftruncateSync(fd, len)
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) closeSync(fd)
  }
}

async function chmod(filepath, mode, cb) {
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.chmod(req.handle, filepath, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'chmod',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function chmodSync(filepath, mode) {
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.chmodSync(req.handle, filepath, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'chmod',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function fchmod(fd, mode, cb) {
  if (typeof mode === 'string') mode = toMode(mode)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fchmod(req.handle, fd, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fchmod', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fchmodSync(fd, mode) {
  if (typeof mode === 'string') mode = toMode(mode)

  const req = FileRequest.borrow()

  try {
    binding.fchmodSync(req.handle, fd, mode)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fchmod', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function chown(filepath, uid, gid, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.chown(req.handle, filepath, uid, gid)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'chown', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function chownSync(filepath, uid, gid) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.chownSync(req.handle, filepath, uid, gid)
  } catch (e) {
    throw new FileError(e.message, { operation: 'chownSync', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function lchown(filepath, uid, gid, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.lchown(req.handle, filepath, uid, gid)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'lchown', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function lchownSync(filepath, uid, gid) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.lchownSync(req.handle, filepath, uid, gid)
  } catch (e) {
    throw new FileError(e.message, { operation: 'lchownSync', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function fchown(fd, uid, gid, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fchown(req.handle, fd, uid, gid)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fchown', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fchownSync(fd, uid, gid) {
  const req = FileRequest.borrow()

  try {
    binding.fchownSync(req.handle, fd, uid, gid)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fchownSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function utimes(filepath, atime, mtime, cb) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.utimes(req.handle, filepath, atime, mtime)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'utimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function utimesSync(filepath, atime, mtime) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.utimesSync(req.handle, filepath, atime, mtime)
  } catch (e) {
    throw new FileError(e.message, { operation: 'utimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function lutimes(filepath, atime, mtime, cb) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.lutimes(req.handle, filepath, atime, mtime)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'lutimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function lutimesSync(filepath, atime, mtime) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.lutimesSync(req.handle, filepath, atime, mtime)
  } catch (e) {
    throw new FileError(e.message, { operation: 'lutimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function futimes(fd, atime, mtime, cb) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.futimes(req.handle, fd, atime, mtime)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'futimes', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function futimesSync(fd, atime, mtime) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  const req = FileRequest.borrow()

  try {
    binding.futimesSync(req.handle, fd, atime, mtime)
  } catch (e) {
    throw new FileError(e.message, { operation: 'futimesSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function link(src, dst, cb) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.link(req.handle, src, dst)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'link', code: e.code, path: src, destination: dst })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function linkSync(src, dst) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  try {
    binding.linkSync(req.handle, src, dst)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'linkSync',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }
}

async function mkdir(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = { mode: 0o777 }
  }

  if (typeof opts === 'number') opts = { mode: opts }
  else if (!opts) opts = {}

  const mode = typeof opts.mode === 'number' ? opts.mode : 0o777

  filepath = toNamespacedPath(filepath)

  if (opts.recursive) {
    let err = null
    try {
      try {
        await mkdir(filepath, { mode })
      } catch (err) {
        if (err.code !== 'ENOENT') {
          if (!(await stat(filepath)).isDirectory()) throw err
        } else {
          while (filepath.endsWith(path.sep)) filepath = filepath.slice(0, -1)
          const i = filepath.lastIndexOf(path.sep)
          if (i <= 0) throw err

          await mkdir(filepath.slice(0, i), { mode, recursive: true })

          try {
            await mkdir(filepath, { mode })
          } catch (err) {
            if (!(await stat(filepath)).isDirectory()) throw err
          }
        }
      }
    } catch (e) {
      err = e
    }

    return done(err, cb)
  }

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.mkdir(req.handle, filepath, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'mkdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function mkdirSync(filepath, opts) {
  if (typeof opts === 'number') opts = { mode: opts }
  else if (!opts) opts = {}

  const mode = typeof opts.mode === 'number' ? opts.mode : 0o777

  filepath = toNamespacedPath(filepath)

  if (opts.recursive) {
    try {
      mkdirSync(filepath, { mode })
    } catch (err) {
      if (err.code !== 'ENOENT') {
        if (!statSync(filepath).isDirectory()) throw err
      } else {
        while (filepath.endsWith(path.sep)) filepath = filepath.slice(0, -1)
        const i = filepath.lastIndexOf(path.sep)
        if (i <= 0) throw err

        mkdirSync(filepath.slice(0, i), { mode, recursive: true })

        try {
          mkdirSync(filepath, { mode })
        } catch (err) {
          if (!statSync(filepath).isDirectory()) throw err
        }
      }
    }

    return
  }

  const req = FileRequest.borrow()

  try {
    binding.mkdirSync(req.handle, filepath, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'mkdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function mkdtemp(prefix, cb) {
  prefix = toNamespacedPath(prefix)

  const req = FileRequest.borrow()

  let res
  let err = null
  try {
    binding.mkdtemp(req.handle, prefix + 'XXXXXX')

    await req

    res = binding.requestResultPath(req.handle)
  } catch (e) {
    err = new FileError(e.message, { operation: 'mkdtemp', code: e.code, path: prefix })
  } finally {
    req.return()
  }

  return done(err, res, cb)
}

function mkdtempSync(prefix) {
  prefix = toNamespacedPath(prefix)

  const req = FileRequest.borrow()

  try {
    binding.mkdtempSync(req.handle, prefix + 'XXXXXX')

    return binding.requestResultPath(req.handle)
  } catch (e) {
    throw new FileError(e.message, { operation: 'mkdtempSync', code: e.code, path: prefix })
  } finally {
    req.return()
  }
}

async function rmdir(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.rmdir(req.handle, filepath)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'rmdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function rmdirSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.rmdirSync(req.handle, filepath)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'rmdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function rm(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  let err = null
  try {
    const st = await lstat(filepath)

    if (st.isDirectory()) {
      if (opts.recursive) {
        try {
          await rmdir(filepath)
        } catch (err) {
          if (err.code !== 'ENOTEMPTY') throw err

          const files = await readdir(filepath)

          for (const file of files) {
            await rm(filepath + path.sep + file, opts)
          }

          await rmdir(filepath)
        }
      } else {
        throw new FileError('is a directory', {
          operation: 'rm',
          code: 'EISDIR',
          path: filepath
        })
      }
    } else {
      await unlink(filepath)
    }
  } catch (e) {
    if (e.code !== 'ENOENT' || !opts.force) err = e
  }

  return done(err, cb)
}

function rmSync(filepath, opts) {
  if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  try {
    const st = lstatSync(filepath)

    if (st.isDirectory()) {
      if (opts.recursive) {
        try {
          rmdirSync(filepath)
        } catch (err) {
          if (err.code !== 'ENOTEMPTY') throw err

          const files = readdirSync(filepath)

          for (const file of files) {
            rmSync(filepath + path.sep + file, opts)
          }

          rmdirSync(filepath)
        }
      } else {
        throw new FileError('is a directory', {
          operation: 'rm',
          code: 'EISDIR',
          path: filepath
        })
      }
    } else {
      unlinkSync(filepath)
    }
  } catch (err) {
    if (err.code !== 'ENOENT' || !opts.force) throw err
  }
}

async function unlink(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.unlink(req.handle, filepath)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'unlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function unlinkSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.unlinkSync(req.handle, filepath)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'unlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function rename(src, dst, cb) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.rename(req.handle, src, dst)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'rename',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function renameSync(src, dst) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  try {
    binding.renameSync(req.handle, src, dst)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'rename',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }
}

async function copyFile(src, dst, mode = 0, cb) {
  if (typeof mode === 'function') {
    cb = mode
    mode = 0
  }

  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.copyfile(req.handle, src, dst, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'copyfile',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function copyFileSync(src, dst, mode = 0) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  try {
    binding.copyfileSync(req.handle, src, dst, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'copyfile',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }
}

async function cp(src, dst, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (!opts) opts = {}

  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  let err = null
  try {
    const st = await lstat(src)

    if (st.isDirectory()) {
      if (opts.recursive !== true) {
        throw new FileError('is a directory', { operation: 'cp', code: 'EISDIR', path: src })
      }

      try {
        await lstat(dst)
      } catch (e) {
        if (e.code !== 'ENOENT') throw e

        await mkdir(dst, { mode: st.mode, recursive: true })
      }

      const dir = await opendir(src)
      for await (const { name } of dir) {
        await cp(path.join(src, name), path.join(dst, name), opts)
      }
    } else if (st.isFile()) {
      await copyFile(src, dst)
      await chmod(dst, st.mode)
    }
  } catch (e) {
    err = e
  }

  return done(err, cb)
}

function cpSync(src, dst, opts = {}) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const st = lstatSync(src)

  if (st.isDirectory()) {
    if (opts.recursive !== true) {
      throw new FileError('is a directory', { operation: 'cp', code: 'EISDIR', path: src })
    }

    try {
      lstatSync(dst)
    } catch (e) {
      if (e.code !== 'ENOENT') throw e

      mkdirSync(dst, { mode: st.mode, recursive: true })
    }

    const dir = opendirSync(src)
    for (const { name } of dir) {
      cpSync(path.join(src, name), path.join(dst, name), opts)
    }
  } else if (st.isFile()) {
    copyFileSync(src, dst)
    chmodSync(dst, st.mode)
  }
}

async function realpath(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let res
  let err = null
  try {
    binding.realpath(req.handle, filepath)

    await req

    res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'realpath',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, res, cb)
}

function realpathSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.realpathSync(req.handle, filepath)

    let res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)

    return res
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'realpath',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function readlink(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let res
  let err = null
  try {
    binding.readlink(req.handle, filepath)

    await req

    res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'readlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, res, cb)
}

function readlinkSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.readlinkSync(req.handle, filepath)

    let res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)

    return res
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'readlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function fsync(fd, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fsync(req.handle, fd)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fsync', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fsyncSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.fsyncSync(req.handle, fd)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fsyncSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function fdatasync(fd, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fdatasync(req.handle, fd)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fdatasync', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fdatasyncSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.fdatasyncSync(req.handle, fd)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fdatasyncSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

function normalizeSymlinkTarget(target, type, filepath) {
  if (isWindows) {
    if (type === constants.UV_FS_SYMLINK_JUNCTION) target = path.resolve(filepath, '..', target)

    if (path.isAbsolute(target)) return path.toNamespacedPath(target)

    return target.replace(/\//g, path.sep)
  }

  return target
}

async function symlink(target, filepath, type, cb) {
  if (typeof type === 'function') {
    cb = type
    type = null
  }

  filepath = toNamespacedPath(filepath)

  if (typeof type === 'string') {
    switch (type) {
      case 'dir':
        type = constants.UV_FS_SYMLINK_DIR
        break
      case 'junction':
        type = constants.UV_FS_SYMLINK_JUNCTION
        break
      case 'file':
      default:
        type = 0
        break
    }
  } else if (typeof type !== 'number') {
    if (isWindows) {
      target = path.resolve(filepath, '..', target)

      try {
        type = (await stat(target)).isDirectory()
          ? constants.UV_FS_SYMLINK_DIR
          : constants.UV_FS_SYMLINK_JUNCTION
      } catch {
        type = 0
      }
    } else {
      type = 0
    }
  }

  target = normalizeSymlinkTarget(target, type, filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.symlink(req.handle, target, filepath, type)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'symlink',
      code: e.code,
      path: target,
      destination: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function symlinkSync(target, filepath, type) {
  filepath = toNamespacedPath(filepath)

  if (typeof type === 'string') {
    switch (type) {
      case 'dir':
        type = constants.UV_FS_SYMLINK_DIR
        break
      case 'junction':
        type = constants.UV_FS_SYMLINK_JUNCTION
        break
      case 'file':
      default:
        type = 0
        break
    }
  } else if (typeof type !== 'number') {
    if (isWindows) {
      target = path.resolve(filepath, '..', target)

      try {
        type = statSync(target).isDirectory()
          ? constants.UV_FS_SYMLINK_DIR
          : constants.UV_FS_SYMLINK_JUNCTION
      } catch {
        type = 0
      }
    } else {
      type = 0
    }
  }

  target = normalizeSymlinkTarget(target, type, filepath)

  const req = FileRequest.borrow()

  try {
    binding.symlinkSync(req.handle, target, filepath, type)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'symlink',
      code: e.code,
      path: target,
      destination: filepath
    })
  } finally {
    req.return()
  }
}

async function opendir(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let dir
  let err = null
  try {
    binding.opendir(req.handle, filepath)

    await req

    dir = new Dir(filepath, binding.requestResultDir(req.handle), opts)
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'opendir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, dir, cb)
}

function opendirSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.opendirSync(req.handle, filepath)

    return new Dir(filepath, binding.requestResultDir(req.handle), opts)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'opendir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function readdir(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { withFileTypes = false, recursive = false } = opts

  filepath = toNamespacedPath(filepath)

  const queue = [filepath]
  let result = []
  let err = null
  try {
    while (queue.length !== 0) {
      const dir = await opendir(queue.pop())

      for await (const entry of dir) {
        const entryPath = path.join(entry.parentPath, entry.name)

        if (withFileTypes) {
          result.push(entry)
        } else {
          result.push(path.relative(filepath, entryPath))
        }

        if (recursive && entry.isDirectory()) queue.push(entryPath)
      }
    }
  } catch (e) {
    result = []
    err = e
  }

  return done(err, result, cb)
}

function readdirSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { withFileTypes = false, recursive = false } = opts

  filepath = toNamespacedPath(filepath)

  const queue = [filepath]
  const result = []

  while (queue.length !== 0) {
    const dir = opendirSync(queue.pop(), opts)

    for (const entry of dir) {
      const entryPath = path.join(entry.parentPath, entry.name)

      if (withFileTypes) {
        result.push(entry)
      } else {
        result.push(path.relative(filepath, entryPath))
      }

      if (recursive && entry.isDirectory()) queue.push(entryPath)
    }
  }

  return result
}

async function readFile(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'buffer' } = opts

  let fd = -1
  let buffer = null
  let err = null
  try {
    fd = await open(filepath, opts.flag || 'r')

    const st = await fstat(fd)

    let len = 0

    if (st.size === 0) {
      const buffers = []

      while (true) {
        buffer = Buffer.allocUnsafe(8192)
        const r = await read(fd, buffer)
        len += r
        if (r === 0) break
        buffers.push(buffer.subarray(0, r))
      }

      buffer = Buffer.concat(buffers)
    } else {
      buffer = Buffer.allocUnsafe(st.size)

      while (true) {
        const r = await read(fd, len ? buffer.subarray(len) : buffer)
        len += r
        if (r === 0 || len === buffer.byteLength) break
      }

      if (len !== buffer.byteLength) buffer = buffer.subarray(0, len)
    }

    if (encoding !== 'buffer') buffer = buffer.toString(encoding)
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) await close(fd)
  }

  return done(err, buffer, cb)
}

function readFileSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'buffer' } = opts

  let fd = -1
  try {
    fd = openSync(filepath, opts.flag || 'r')

    const st = fstatSync(fd)

    let buffer
    let len = 0

    if (st.size === 0) {
      const buffers = []

      while (true) {
        buffer = Buffer.allocUnsafe(8192)
        const r = readSync(fd, buffer)
        len += r
        if (r === 0) break
        buffers.push(buffer.subarray(0, r))
      }

      buffer = Buffer.concat(buffers)
    } else {
      buffer = Buffer.allocUnsafe(st.size)

      while (true) {
        const r = readSync(fd, len ? buffer.subarray(len) : buffer)
        len += r
        if (r === 0 || len === buffer.byteLength) break
      }

      if (len !== buffer.byteLength) buffer = buffer.subarray(0, len)
    }

    if (encoding !== 'buffer') buffer = buffer.toString(encoding)

    return buffer
  } finally {
    if (fd !== -1) closeSync(fd)
  }
}

async function writeFile(filepath, data, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (typeof data === 'string') data = Buffer.from(data, opts.encoding)

  let fd = -1
  let len = 0
  let err = null
  try {
    fd = await open(filepath, opts.flag || 'w', opts.mode || 0o666)

    while (true) {
      len += await write(fd, len ? data.subarray(len) : data)
      if (len === data.byteLength) break
    }
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) await close(fd)
  }

  return done(err, len, cb)
}

function writeFileSync(filepath, data, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (typeof data === 'string') data = Buffer.from(data, opts.encoding)

  let fd = -1
  try {
    fd = openSync(filepath, opts.flag || 'w', opts.mode || 0o666)

    let len = 0

    while (true) {
      len += writeSync(fd, len ? data.subarray(len) : data)
      if (len === data.byteLength) break
    }
  } finally {
    if (fd !== -1) closeSync(fd)
  }
}

function appendFile(filepath, data, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (!opts.flag) opts = { ...opts, flag: 'a' }

  return writeFile(filepath, data, opts, cb)
}

function appendFileSync(filepath, data, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (!opts.flag) opts = { ...opts, flag: 'a' }

  return writeFileSync(filepath, data, opts)
}

function watch(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  return new Watcher(filepath, opts, cb)
}

class Stats {
  constructor(
    dev,
    mode,
    nlink,
    uid,
    gid,
    rdev,
    blksize,
    ino,
    size,
    blocks,
    atimeMs,
    mtimeMs,
    ctimeMs,
    birthtimeMs
  ) {
    this.dev = dev
    this.mode = mode
    this.nlink = nlink
    this.uid = uid
    this.gid = gid
    this.rdev = rdev
    this.blksize = blksize
    this.ino = ino
    this.size = size
    this.blocks = blocks
    this.atimeMs = atimeMs
    this.mtimeMs = mtimeMs
    this.ctimeMs = ctimeMs
    this.birthtimeMs = birthtimeMs
    this.atime = new Date(atimeMs)
    this.mtime = new Date(mtimeMs)
    this.ctime = new Date(ctimeMs)
    this.birthtime = new Date(birthtimeMs)
  }

  isDirectory() {
    return (this.mode & constants.S_IFMT) === constants.S_IFDIR
  }

  isFile() {
    return (this.mode & constants.S_IFMT) === constants.S_IFREG
  }

  isBlockDevice() {
    return (this.mode & constants.S_IFMT) === constants.S_IFBLK
  }

  isCharacterDevice() {
    return (this.mode & constants.S_IFMT) === constants.S_IFCHR
  }

  isFIFO() {
    return (this.mode & constants.S_IFMT) === constants.S_IFIFO
  }

  isSymbolicLink() {
    return (this.mode & constants.S_IFMT) === constants.S_IFLNK
  }

  isSocket() {
    return (this.mode & constants.S_IFMT) === constants.S_IFSOCK
  }
}

class StatFs {
  constructor(type, bsize, blocks, bfree, bavail, files, ffree) {
    this.type = type
    this.bsize = bsize
    this.blocks = blocks
    this.bfree = bfree
    this.bavail = bavail
    this.files = files
    this.ffree = ffree
  }
}

class Dir {
  constructor(path, handle, opts = {}) {
    const { encoding = 'utf8', bufferSize = 32 } = opts

    this.path = path

    this._encoding = encoding
    this._capacity = bufferSize
    this._buffer = new FIFO()
    this._ended = false
    this._handle = handle
  }

  async read(cb) {
    if (this._buffer.length) return ok(this._buffer.shift(), cb)
    if (this._ended) return ok(null, cb)

    const req = FileRequest.borrow()

    let entries
    let err = null
    try {
      req.retain(binding.readdir(req.handle, this._handle, this._capacity))

      await req

      entries = binding.requestResultDirents(req.handle)
    } catch (e) {
      err = new FileError(e.message, {
        operation: 'readdir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    if (err) return fail(err, cb)

    if (entries.length === 0) {
      this._ended = true

      return ok(null, cb)
    }

    for (const entry of entries) {
      let name = Buffer.from(entry.name)

      if (this._encoding !== 'buffer') name = name.toString(this._encoding)

      this._buffer.push(new Dirent(this.path, name, entry.type))
    }

    return ok(this._buffer.shift(), cb)
  }

  readSync() {
    if (this._buffer.length) return this._buffer.shift()
    if (this._ended) return null

    const req = FileRequest.borrow()

    let entries
    try {
      req.retain(binding.readdirSync(req.handle, this._handle, this._capacity))

      entries = binding.requestResultDirents(req.handle)
    } catch (e) {
      throw new FileError(e.message, {
        operation: 'readdir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    if (entries.length === 0) {
      this._ended = true

      return null
    }

    for (const entry of entries) {
      let name = Buffer.from(entry.name)

      if (this._encoding !== 'buffer') name = name.toString(this._encoding)

      this._buffer.push(new Dirent(this.path, name, entry.type))
    }

    return this._buffer.shift()
  }

  async close(cb) {
    const req = FileRequest.borrow()

    let err = null
    try {
      binding.closedir(req.handle, this._handle)

      await req
    } catch (e) {
      err = new FileError(e.message, {
        operation: 'closedir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    this._handle = null

    return done(err, cb)
  }

  closeSync() {
    const req = FileRequest.borrow()

    try {
      binding.closedirSync(req.handle, this._handle)
    } catch (e) {
      throw new FileError(e.message, {
        operation: 'closedir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    this._handle = null
  }

  [Symbol.dispose]() {
    this.closeSync()
  }

  async [Symbol.asyncDispose]() {
    await this.close()
  }

  *[Symbol.iterator]() {
    while (true) {
      const entry = this.readSync()
      if (entry === null) break
      yield entry
    }

    this.closeSync()
  }

  async *[Symbol.asyncIterator]() {
    while (true) {
      const entry = await this.read()
      if (entry === null) break
      yield entry
    }

    await this.close()
  }
}

class Dirent {
  constructor(parentPath, name, type) {
    this.parentPath = parentPath
    this.name = name
    this.type = type
  }

  isFile() {
    return this.type === constants.UV_DIRENT_FILE
  }

  isDirectory() {
    return this.type === constants.UV_DIRENT_DIR
  }

  isSymbolicLink() {
    return this.type === constants.UV_DIRENT_LINK
  }

  isFIFO() {
    return this.type === constants.UV_DIRENT_FIFO
  }

  isSocket() {
    return this.type === constants.UV_DIRENT_SOCKET
  }

  isCharacterDevice() {
    return this.type === constants.UV_DIRENT_CHAR
  }

  isBlockDevice() {
    return this.type === constants.UV_DIRENT_BLOCK
  }
}

class FileReadStream extends Readable {
  constructor(path, opts = {}) {
    const { eagerOpen = true } = opts

    super({ eagerOpen, ...opts })

    this.path = path
    this.fd = typeof opts.fd === 'number' ? opts.fd : -1
    this.flags = opts.flags || 'r'
    this.mode = opts.mode || 0o666

    this._offset = opts.start || 0
    this._missing = 0

    if (opts.length) {
      this._missing = opts.length
    } else if (typeof opts.end === 'number') {
      this._missing = opts.end - this._offset + 1
    } else {
      this._missing = -1
    }
  }

  async _open(cb) {
    let err

    if (this.fd === -1) {
      err = null
      try {
        this.fd = await open(this.path, this.flags, this.mode)
      } catch (e) {
        err = e
      }

      if (err) return cb(err)
    }

    let st
    err = null
    try {
      st = await fstat(this.fd)
    } catch (e) {
      err = e
    }

    if (err) return cb(err)

    if (this._missing === -1) this._missing = st.size

    if (st.size < this._offset) {
      this._offset = st.size
      this._missing = 0
    } else if (st.size < this._offset + this._missing) {
      this._missing = st.size - this._offset
    }

    cb(null)
  }

  async _read(size) {
    if (this._missing <= 0) return this.push(null)

    const data = Buffer.allocUnsafe(Math.min(this._missing, size))

    let len
    let err = null
    try {
      len = await read(this.fd, data, 0, data.byteLength, this._offset)
    } catch (e) {
      err = e
    }

    if (err) return this.destroy(err)

    if (len === 0) return this.push(null)

    if (this._missing < len) len = this._missing

    this._missing -= len
    this._offset += len

    this.push(data.subarray(0, len))
  }

  async _destroy(err, cb) {
    if (this.fd === -1) return cb(err)

    try {
      await close(this.fd)
    } catch (e) {
      err = err || e
    }

    cb(err)
  }
}

class FileWriteStream extends Writable {
  constructor(path, opts = {}) {
    const { eagerOpen = true } = opts

    super({ eagerOpen, ...opts })

    this.path = path
    this.fd = typeof opts.fd === 'number' ? opts.fd : -1
    this.flags = opts.flags || 'w'
    this.mode = opts.mode || 0o666
  }

  async _open(cb) {
    if (this.fd !== -1) return cb(null)

    let err = null
    try {
      this.fd = await open(this.path, this.flags, this.mode)
    } catch (e) {
      err = e
    }

    cb(err)
  }

  async _writev(batch, cb) {
    let err = null
    try {
      await writev(
        this.fd,
        batch.map(({ chunk }) => chunk)
      )
    } catch (e) {
      err = e
    }

    cb(err)
  }

  async _destroy(err, cb) {
    if (this.fd === -1) return cb(err)

    try {
      await close(this.fd)
    } catch (e) {
      err = err || e
    }

    cb(err)
  }
}

class Watcher extends EventEmitter {
  constructor(path, opts, onchange) {
    if (typeof opts === 'function') {
      onchange = opts
      opts = {}
    }

    if (!opts) opts = {}

    const { persistent = true, recursive = false, encoding = 'utf8' } = opts

    super()

    this._closed = false
    this._encoding = encoding
    this._handle = binding.watcherInit(path, recursive, this, this._onevent, this._onclose)

    if (!persistent) this.unref()

    if (onchange) this.on('change', onchange)
  }

  close() {
    if (this._closed) return
    this._closed = true

    binding.watcherClose(this._handle)
  }

  ref() {
    if (this._handle) binding.watcherRef(this._handle)
    return this
  }

  unref() {
    if (this._handle) binding.watcherUnref(this._handle)
    return this
  }

  [Symbol.asyncIterator]() {
    const buffer = []
    let done = false
    let error = null
    let next = null

    this.on('change', (eventType, filename) => {
      if (next) {
        next.resolve({ done: false, value: { eventType, filename } })
        next = null
      } else {
        buffer.push({ eventType, filename })
      }
    })
      .on('error', (err) => {
        done = true
        error = err

        if (next) {
          next.reject(error)
          next = null
        }
      })
      .on('close', () => {
        done = true

        if (next) {
          next.resolve({ done })
          next = null
        }
      })

    return {
      next: () =>
        new Promise((resolve, reject) => {
          if (error) return reject(error)

          if (buffer.length) return resolve({ done: false, value: buffer.shift() })

          if (done) return resolve({ done })

          next = { resolve, reject }
        })
    }
  }

  _onevent(err, events, filename) {
    if (err) {
      this.close()
      this.emit('error', err)
    } else {
      const path =
        this._encoding === 'buffer'
          ? Buffer.from(filename)
          : Buffer.from(filename).toString(this._encoding)

      if (events & binding.UV_RENAME) {
        this.emit('change', 'rename', path)
      }

      if (events & binding.UV_CHANGE) {
        this.emit('change', 'change', path)
      }
    }
  }

  _onclose() {
    this._handle = null

    this.emit('close')
  }
}

exports.access = access
exports.appendFile = appendFile
exports.chmod = chmod
exports.chown = chown
exports.close = close
exports.copyFile = copyFile
exports.cp = cp
exports.exists = exists
exports.fchmod = fchmod
exports.fchown = fchown
exports.fdatasync = fdatasync
exports.fstat = fstat
exports.fsync = fsync
exports.ftruncate = ftruncate
exports.futimes = futimes
exports.lchown = lchown
exports.lutimes = lutimes
exports.link = link
exports.lstat = lstat
exports.mkdir = mkdir
exports.mkdtemp = mkdtemp
exports.open = open
exports.opendir = opendir
exports.read = read
exports.readFile = readFile
exports.readdir = readdir
exports.readlink = readlink
exports.readv = readv
exports.realpath = realpath
exports.rename = rename
exports.rm = rm
exports.rmdir = rmdir
exports.stat = stat
exports.statfs = statfs
exports.symlink = symlink
exports.truncate = truncate
exports.unlink = unlink
exports.utimes = utimes
exports.watch = watch
exports.write = write
exports.writeFile = writeFile
exports.writev = writev

exports.accessSync = accessSync
exports.appendFileSync = appendFileSync
exports.chmodSync = chmodSync
exports.chownSync = chownSync
exports.closeSync = closeSync
exports.copyFileSync = copyFileSync
exports.cpSync = cpSync
exports.existsSync = existsSync
exports.fchmodSync = fchmodSync
exports.fchownSync = fchownSync
exports.fdatasyncSync = fdatasyncSync
exports.fstatSync = fstatSync
exports.fsyncSync = fsyncSync
exports.ftruncateSync = ftruncateSync
exports.futimesSync = futimesSync
exports.lchownSync = lchownSync
exports.lutimesSync = lutimesSync
exports.linkSync = linkSync
exports.lstatSync = lstatSync
exports.mkdirSync = mkdirSync
exports.mkdtempSync = mkdtempSync
exports.openSync = openSync
exports.opendirSync = opendirSync
exports.readFileSync = readFileSync
exports.readSync = readSync
exports.readdirSync = readdirSync
exports.readlinkSync = readlinkSync
exports.readvSync = readvSync
exports.realpathSync = realpathSync
exports.renameSync = renameSync
exports.rmSync = rmSync
exports.rmdirSync = rmdirSync
exports.statSync = statSync
exports.statfsSync = statfsSync
exports.symlinkSync = symlinkSync
exports.truncateSync = truncateSync
exports.unlinkSync = unlinkSync
exports.utimesSync = utimesSync
exports.writeFileSync = writeFileSync
exports.writeSync = writeSync
exports.writevSync = writevSync

exports.promises = require('./promises')

exports.Stats = Stats
exports.StatFs = StatFs
exports.Dir = Dir
exports.Dirent = Dirent
exports.Watcher = Watcher

exports.ReadStream = FileReadStream

exports.createReadStream = function createReadStream(path, opts) {
  return new FileReadStream(path, opts)
}

exports.WriteStream = FileWriteStream

exports.createWriteStream = function createWriteStream(path, opts) {
  return new FileWriteStream(path, opts)
}

function toNamespacedPath(filepath) {
  if (typeof filepath !== 'string') {
    if (isURL(filepath)) filepath = fileURLToPath(filepath)
    else filepath = filepath.toString()
  }

  return path.toNamespacedPath(filepath)
}

function toFlags(flags) {
  switch (flags) {
    case 'r':
      return constants.O_RDONLY
    case 'rs': // Fall through.
    case 'sr':
      return constants.O_RDONLY | constants.O_SYNC
    case 'r+':
      return constants.O_RDWR
    case 'rs+': // Fall through.
    case 'sr+':
      return constants.O_RDWR | constants.O_SYNC

    case 'w':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_WRONLY
    case 'wx': // Fall through.
    case 'xw':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_WRONLY | constants.O_EXCL

    case 'w+':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_RDWR
    case 'wx+': // Fall through.
    case 'xw+':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_RDWR | constants.O_EXCL

    case 'a':
      return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY
    case 'ax': // Fall through.
    case 'xa':
      return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY | constants.O_EXCL
    case 'as': // Fall through.
    case 'sa':
      return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY | constants.O_SYNC

    case 'a+':
      return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR
    case 'ax+': // Fall through.
    case 'xa+':
      return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR | constants.O_EXCL
    case 'as+': // Fall through.
    case 'sa+':
      return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR | constants.O_SYNC
    default:
      return 0
  }
}

function toMode(mode) {
  return parseInt(mode, 8)
}
const binding = require('../binding')

module.exports = {
  O_RDWR: binding.O_RDWR,
  O_RDONLY: binding.O_RDONLY,
  O_WRONLY: binding.O_WRONLY,
  O_CREAT: binding.O_CREAT,
  O_TRUNC: binding.O_TRUNC,
  O_APPEND: binding.O_APPEND,

  F_OK: binding.F_OK || 0,
  R_OK: binding.R_OK || 0,
  W_OK: binding.W_OK || 0,
  X_OK: binding.X_OK || 0,

  S_IFMT: binding.S_IFMT,
  S_IFREG: binding.S_IFREG,
  S_IFDIR: binding.S_IFDIR,
  S_IFCHR: binding.S_IFCHR,
  S_IFLNK: binding.S_IFLNK,
  S_IFBLK: binding.S_IFBLK || 0,
  S_IFIFO: binding.S_IFIFO || 0,
  S_IFSOCK: binding.S_IFSOCK || 0,

  S_IRUSR: binding.S_IRUSR || 0,
  S_IWUSR: binding.S_IWUSR || 0,
  S_IXUSR: binding.S_IXUSR || 0,
  S_IRGRP: binding.S_IRGRP || 0,
  S_IWGRP: binding.S_IWGRP || 0,
  S_IXGRP: binding.S_IXGRP || 0,
  S_IROTH: binding.S_IROTH || 0,
  S_IWOTH: binding.S_IWOTH || 0,
  S_IXOTH: binding.S_IXOTH || 0,

  UV_DIRENT_UNKNOWN: binding.UV_DIRENT_UNKNOWN,
  UV_DIRENT_FILE: binding.UV_DIRENT_FILE,
  UV_DIRENT_DIR: binding.UV_DIRENT_DIR,
  UV_DIRENT_LINK: binding.UV_DIRENT_LINK,
  UV_DIRENT_FIFO: binding.UV_DIRENT_FIFO,
  UV_DIRENT_SOCKET: binding.UV_DIRENT_SOCKET,
  UV_DIRENT_CHAR: binding.UV_DIRENT_CHAR,
  UV_DIRENT_BLOCK: binding.UV_DIRENT_BLOCK,

  COPYFILE_EXCL: binding.UV_FS_COPYFILE_EXCL,
  COPYFILE_FICLONE: binding.UV_FS_COPYFILE_FICLONE,
  COPYFILE_FICLONE_FORCE: binding.UV_FS_COPYFILE_FICLONE_FORCE,
  UV_FS_SYMLINK_DIR: binding.UV_FS_SYMLINK_DIR,
  UV_FS_SYMLINK_JUNCTION: binding.UV_FS_SYMLINK_JUNCTION
}
const os = require('bare-os')

module.exports = class FileError extends Error {
  constructor(msg, opts = {}) {
    const { code, operation = null, path = null, destination = null, fd = -1 } = opts

    if (operation !== null) msg += describe(operation, opts)

    super(`${code}: ${msg}`)

    this.code = code

    if (operation !== null) this.operation = operation
    if (path !== null) this.path = path
    if (destination !== null) this.destination = destination
    if (fd !== -1) this.fd = fd
  }

  get name() {
    return 'FileError'
  }

  // For Node.js compatibility
  get errno() {
    return os.constants.errnos[this.code]
  }

  // For Node.js compatibility
  get syscall() {
    return this.operation
  }

  // For Node.js compatibility
  get dest() {
    return this.destination
  }
}

function describe(operation, opts) {
  const { path = null, destination = null, fd = -1 } = opts

  let result = `, ${operation}`

  if (path !== null) {
    result += ` ${JSON.stringify(path)}`

    if (destination !== null) {
      result += ` -> ${JSON.stringify(destination)}`
    }
  } else if (fd !== -1) {
    result += ` ${fd}`
  }

  return result
}
{
  "name": "bare-fs",
  "version": "4.7.3",
  "description": "Native file system operations for Bare",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./promises": {
      "types": "./promises.d.ts",
      "default": "./promises.js"
    },
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "promises.js",
    "promises.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-fs.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-fs/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-fs#readme",
  "engines": {
    "bare": ">=1.16.0"
  },
  "dependencies": {
    "bare-events": "^2.5.4",
    "bare-path": "^3.0.0",
    "bare-stream": "^2.6.4",
    "bare-url": "^2.2.2",
    "fast-fifo": "^1.3.2"
  },
  "devDependencies": {
    "bare-buffer": "^3.0.2",
    "bare-crypto": "^1.11.2",
    "brittle": "^3.1.1",
    "cmake-bare": "^1.1.7",
    "lunte": "^1.6.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "bare-buffer": "*"
  },
  "peerDependenciesMeta": {
    "bare-buffer": {
      "optional": true
    }
  }
}
const EventEmitter = require('bare-events')
const fs = require('.')

class FileHandle extends EventEmitter {
  constructor(fd) {
    super()

    this.fd = fd
  }

  async close() {
    await fs.close(this.fd)

    this.fd = -1
    this.emit('close')
  }

  async read(buffer, ...args) {
    return {
      bytesRead: await fs.read(this.fd, buffer, ...args),
      buffer
    }
  }

  async readv(buffers, ...args) {
    return {
      bytesRead: await fs.readv(this.fd, buffers, ...args),
      buffers
    }
  }

  async write(buffer, ...args) {
    return {
      bytesWritten: await fs.write(this.fd, buffer, ...args),
      buffer
    }
  }

  async writev(buffers, ...args) {
    return {
      bytesWritten: await fs.writev(this.fd, buffers, ...args),
      buffers
    }
  }

  async stat() {
    return fs.fstat(this.fd)
  }

  async chmod(mode) {
    await fs.fchmod(this.fd, mode)
  }

  async chown(uid, gid) {
    await fs.fchown(this.fd, uid, gid)
  }

  async datasync() {
    return fs.fdatasync(this.fd)
  }

  async sync() {
    return fs.fsync(this.fd)
  }

  async truncate(len) {
    await fs.ftruncate(this.fd, len)
  }

  async utimes(atime, mtime) {
    await fs.futimes(this.fd, atime, mtime)
  }

  createReadStream(opts) {
    return fs.createReadStream(null, { ...opts, fd: this.fd })
  }

  createWriteStream(opts) {
    return fs.createWriteStream(null, { ...opts, fd: this.fd })
  }

  async [Symbol.asyncDispose]() {
    await this.close()
  }
}

exports.open = async function open(filepath, flags, mode) {
  return new FileHandle(await fs.open(filepath, flags, mode))
}

exports.access = fs.access
exports.appendFile = fs.appendFile
exports.chmod = fs.chmod
exports.chown = fs.chown
exports.constants = fs.constants
exports.copyFile = fs.copyFile
exports.cp = fs.cp
exports.lchown = fs.lchown
exports.lutimes = fs.lutimes
exports.link = fs.link
exports.lstat = fs.lstat
exports.mkdir = fs.mkdir
exports.mkdtemp = fs.mkdtemp
exports.opendir = fs.opendir
exports.readFile = fs.readFile
exports.readdir = fs.readdir
exports.readlink = fs.readlink
exports.realpath = fs.realpath
exports.rename = fs.rename
exports.rm = fs.rm
exports.rmdir = fs.rmdir
exports.stat = fs.stat
exports.statfs = fs.statfs
exports.truncate = fs.truncate
exports.symlink = fs.symlink
exports.unlink = fs.unlink
exports.utimes = fs.utimes
exports.watch = fs.watch
exports.writeFile = fs.writeFile
module.exports = require.addon()
const ansiEscapes = require('bare-ansi-escapes')
const getType = require('bare-type')
const binding = require('./binding')

const PLAIN_KEY = /^[a-zA-Z_][a-zA-Z_0-9]*$/

const defaultDepth = 2
const defaultBreakLength = 80
const defaultMaxArrayLength = 40

module.exports = exports = function inspect(value, opts = {}) {
  const {
    colors = false,
    depth = defaultDepth,
    breakLength = defaultBreakLength,
    stylize = defaultStylize(colors)
  } = opts

  const references = new InspectRefMap()

  const tree = inspectValue(value, 0, {
    colors,
    depth,
    breakLength,
    stylize,
    references
  })

  return tree.toString()
}

exports.styles = {
  bigint: ansiEscapes.colorYellow,
  boolean: ansiEscapes.colorYellow,
  date: ansiEscapes.colorMagenta,
  module: ansiEscapes.modifierUnderline,
  name: ansiEscapes.modifierReset,
  null: ansiEscapes.modifierBold,
  number: ansiEscapes.colorYellow,
  regexp: ansiEscapes.colorRed,
  special: ansiEscapes.colorCyan,
  string: ansiEscapes.colorGreen,
  symbol: ansiEscapes.colorGreen,
  undefined: ansiEscapes.colorBrightBlack
}

const styles = exports.styles

function defaultStylize(colors) {
  return function stylize(value, style) {
    const color = colors && styles[style]

    if (color) return color + value + ansiEscapes.modifierReset

    return value
  }
}

class InspectRefMap {
  constructor() {
    this.refs = new WeakMap()
    this.ids = new WeakMap()
    this.nextId = 1
  }

  has(object) {
    return this.refs.has(object)
  }

  get(object) {
    return this.refs.get(object) || null
  }

  set(object, ref) {
    this.refs.set(object, ref)
  }

  id(object) {
    let id = this.ids.get(object)
    if (id) return id

    id = this.nextId++
    this.ids.set(object, id)

    return id
  }
}

class InspectNode {
  constructor(depth, length, opts) {
    const { breakLength = defaultBreakLength, breakAlways = false } = opts

    this.depth = depth
    this.length = length
    this.breakLength = breakLength
    this.breakAlways = breakAlways
  }

  pad(n, string) {
    return string.padStart(n, ' ')
  }

  indent(n, string) {
    return '  '.repeat(n) + string
  }
}

class InspectRef extends InspectNode {
  constructor(depth, opts) {
    super(depth, '[circular *]'.length, opts)

    this.refs = opts.references
    this.count = 0
    this.circular = false
    this.color = opts.colors && styles.special
  }

  get id() {
    return this.refs.id(this)
  }

  increment() {
    return ++this.count
  }

  decrement() {
    return --this.count
  }

  toString(opts = {}) {
    const { offset = 0, pad = 0, indent = 0 } = opts

    let value = this.pad(pad, '[circular *' + this.id + ']')

    if (this.color) value = this.color + value + ansiEscapes.modifierReset

    return offset ? value : this.indent(indent, value)
  }
}

class InspectLeaf extends InspectNode {
  constructor(value, color, depth, opts) {
    const length = value.length

    if (value.includes('\n')) {
      value = value.replaceAll('\n', '\n' + '  '.repeat(depth))

      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.value = value
    this.color = opts.colors && color
  }

  toString(opts = {}) {
    const { offset = 0, pad = 0, indent = 0 } = opts

    let value = this.pad(pad, this.value)

    if (this.color) value = this.color + value + ansiEscapes.modifierReset

    return offset ? value : this.indent(indent, value)
  }
}

class InspectPair extends InspectNode {
  constructor(delim, left, right, depth, opts) {
    const length = left.length + delim.length + right.length

    if (left.breakAlways || right.breakAlways) {
      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.delim = delim
    this.left = left
    this.right = right
  }

  toString(opts = {}) {
    const { indent = 0 } = opts

    return this.indent(
      indent,
      this.left +
        this.delim +
        this.right.toString({
          indent,
          offset: this.left.length + this.delim.length
        })
    )
  }
}

class InspectSuspension extends InspectNode {
  constructor(overflow, depth, opts) {
    const label = `... ${overflow} more`

    super(depth, label.length, opts)

    this.label = label
  }

  toString(opts = {}) {
    const { indent = 0 } = opts

    return this.indent(indent, this.label)
  }
}

class InspectSequence extends InspectNode {
  constructor(header, footer, delim, values, ref, depth, opts) {
    const { tabulate = false } = opts

    const length =
      (ref.circular ? '<ref *>'.length + 1 : 0) +
      header.length +
      values.reduce(
        (length, value, i) =>
          length + value.length + (i === 0 ? 0 : delim.length),
        0
      ) +
      footer.length

    if (values.some((value) => value.breakAlways)) {
      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.header = header
    this.footer = footer
    this.delim = delim
    this.values = values
    this.ref = ref
    this.tabulate = tabulate
  }

  toString(opts = {}) {
    const { offset = 0, indent = 0 } = opts

    const split =
      this.breakAlways ||
      (this.values.length &&
        (offset + this.length > this.breakLength ||
          indent * 2 + this.length > this.breakLength))

    let header = this.header

    if (this.ref.circular) {
      header = '<ref *' + this.ref.id + '> ' + header
    }

    if (this.values.length === 0) {
      header = header.trimEnd()
    }

    if (offset === 0) {
      header = this.indent(indent, header)
    }

    if (split) {
      header = header.trimEnd() + '\n'
    }

    let string = header

    let columns = 1
    let pad = 0

    if (this.tabulate) {
      const widest = this.values.reduce(
        (length, value) =>
          value.breakAlways ? length : Math.max(length, value.length),
        0
      )

      if (widest) {
        columns = Math.max(
          columns,
          Math.floor(
            (this.breakLength - indent * 2) / (widest + this.delim.length)
          )
        )

        if (columns > 1) pad = widest
      }
    }

    for (let i = 0, n = this.values.length, offset = 0; i < n; i++) {
      const value = this.values[i]

      if (split) {
        let part

        if (i % columns === 0 || value.breakAlways) {
          part = value.toString({ indent: indent + 1, pad })
        } else {
          part = value.toString({ pad })
        }

        string += part

        if (i < n - 1) {
          if (i % columns === columns - 1 || this.values[i + 1].breakAlways) {
            string += this.delim.trimEnd() + '\n'
          } else {
            string += this.delim
          }
        }
      } else {
        if (i > 0) string += this.delim

        string += value.toString({ offset })

        offset += value.length
      }
    }

    let footer = this.footer

    if (this.values.length === 0) {
      footer = footer.trimStart()
    }

    if (split) {
      string += '\n' + this.indent(indent, footer.trimStart())
    } else {
      string += footer
    }

    return string
  }
}

function inspectValue(value, depth, opts) {
  const type = getType(value)

  if (type.isUndefined()) return inspectUndefined(depth, opts)
  if (type.isNull()) return inspectNull(depth, opts)
  if (type.isBoolean()) return inspectBoolean(value, depth, opts)
  if (type.isNumber()) return inspectNumber(value, depth, opts)
  if (type.isBigInt()) return inspectBigInt(value, depth, opts)
  if (type.isString()) return inspectString(value, depth, opts)
  if (type.isSymbol()) return inspectSymbol(value, depth, opts)
  if (type.isObject()) return inspectObject(type, value, depth, opts)
  if (type.isFunction()) return inspectFunction(type, value, depth, opts)
  if (type.isExternal()) return inspectExternal(value, opts, opts)
}

function inspectUndefined(depth, opts) {
  return new InspectLeaf('undefined', styles.undefined, depth, opts)
}

function inspectNull(depth, opts) {
  return new InspectLeaf('null', styles.null, depth, opts)
}

function inspectBoolean(value, depth, opts) {
  return new InspectLeaf(value.toString(), styles.boolean, depth, opts)
}

function inspectNumber(value, depth, opts) {
  let string

  if (Object.is(value, -0)) {
    string = '-0'
  } else {
    string = value.toString(10)
  }

  return new InspectLeaf(string, styles.number, depth, opts)
}

function inspectBigInt(value, depth, opts) {
  return new InspectLeaf(value.toString(10) + 'n', styles.bigint, depth, opts)
}

const STRING_ESCAPES =
  /[\ud800-\udbff][\udc00-\udfff]|[\u0000-\u001f'\\\ud800-\udfff]/g

function inspectString(value, depth, opts) {
  // https://tc39.es/ecma262/multipage/structured-data.html#sec-quotejsonstring
  const string = value.replace(STRING_ESCAPES, (match) => {
    if (match.length === 2) return match

    switch (match) {
      case "'":
        return "\\'"
      case '\\':
        return '\\\\'
      case '\b':
        return '\\b'
      case '\t':
        return '\\t'
      case '\n':
        return '\\n'
      case '\f':
        return '\\f'
      case '\r':
        return '\\r'
      default:
        return '\\u' + match.charCodeAt(0).toString(16).padStart(4, '0')
    }
  })

  return new InspectLeaf("'" + string + "'", styles.string, depth, opts)
}

function inspectSymbol(value, depth, opts) {
  return new InspectLeaf(value.toString(), styles.symbol, depth, opts)
}

function inspectKey(value, depth, opts) {
  if (PLAIN_KEY.test(value)) {
    return new InspectLeaf(value, null, depth, opts)
  } else {
    return inspectValue(value, depth, opts)
  }
}

function inspectObject(type, object, depth, opts) {
  const refs = opts.references

  let ref = refs.get(object)
  if (ref === null) {
    ref = new InspectRef(depth, opts)
    refs.set(object, ref)
  } else if (ref.count) {
    ref.circular = true
    return ref
  }

  const maxDepth = typeof opts.depth === 'number' ? opts.depth : Infinity

  if (maxDepth < depth) {
    const constructor = object.constructor

    return new InspectLeaf(
      '[' +
        (constructor && constructor.name ? constructor.name : 'Object') +
        ']',
      styles.special,
      depth,
      opts
    )
  }

  const inspect =
    object[Symbol.for('bare.inspect')] ||
    object[Symbol.for('nodejs.util.inspect.custom')]

  if (typeof inspect === 'function') {
    const value = inspect.call(
      object,
      typeof opts.depth === 'number' ? opts.depth - depth : null,
      {
        colors: opts.colors,
        breakLength: opts.breakLength,
        stylize: opts.stylize
      },
      exports
    )

    if (typeof value === 'object' && value !== null) {
      refs.set(value, ref)
    }

    if (typeof value !== 'string') {
      return inspectValue(value, depth, opts)
    }

    return new InspectLeaf(value, null, depth, opts)
  }

  if (type.isArray()) return inspectArray(object, ref, depth, opts)
  if (type.isDate()) return inspectDate(object, ref, depth, opts)
  if (type.isRegExp()) return inspectRegExp(object, ref, depth, opts)
  if (type.isError()) return inspectError(object, ref, depth, opts)
  if (type.isPromise()) return inspectPromise(object, ref, depth, opts)
  if (type.isMap()) return inspectMap(object, ref, depth, opts)
  if (type.isSet()) return inspectSet(object, ref, depth, opts)
  if (type.isWeakMap()) return inspectWeakMap(object, ref, depth, opts)
  if (type.isWeakSet()) return inspectWeakSet(object, ref, depth, opts)
  if (type.isWeakRef()) return inspectWeakRef(object, ref, depth, opts)
  if (type.isArrayBuffer()) return inspectArrayBuffer(object, ref, depth, opts)
  if (type.isSharedArrayBuffer())
    return inspectSharedArrayBuffer(object, ref, depth, opts)
  if (type.isTypedArray()) return inspectTypedArray(object, ref, depth, opts)
  if (type.isDataView()) return inspectDataView(object, ref, depth, opts)

  ref.increment()

  const values = []

  for (const key in object) {
    if (key === 'constructor') continue

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(object[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  let header = '{ '

  const tag = object[Symbol.toStringTag]

  if (tag) header = '[' + tag + '] ' + header

  if (object.constructor) {
    const name = object.constructor.name

    if (name && name !== 'Object') {
      header = object.constructor.name + ' ' + header
    }
  }

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectArray(array, ref, depth, opts) {
  const { maxArrayLength = defaultMaxArrayLength } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxArrayLength, 0)

  for (let i = 0, n = array.length; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(array.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(inspectValue(array[i], depth + 1, opts))
  }

  for (const key of binding.getOwnNonIndexPropertyNames(array)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(array[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  let header = '[ '

  if (array.constructor.name !== 'Array') {
    header = array.constructor.name + '(' + array.length + ') ' + header
  }

  return new InspectSequence(header, ' ]', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectDate(date, ref, depth, opts) {
  return new InspectLeaf(date.toISOString(), styles.date, depth, opts)
}

function inspectRegExp(regExp, ref, depth, opts) {
  return new InspectLeaf(regExp.toString(), styles.regexp, depth, opts)
}

function inspectError(error, ref, depth, opts) {
  let header

  if ('stack' in error) {
    header = error.stack

    if (depth > 0) {
      header = header.replaceAll('\n', '\n' + '  '.repeat(depth))
    }
  } else {
    header = error.toString()
  }

  const builtins = ['cause']

  if (error.name === 'AggregateError') {
    builtins.push('errors')
  } else if (error.name === 'SuppressedError') {
    builtins.push('error', 'suppressed')
  }

  const values = []

  for (const key of builtins) {
    if (key in error === false) continue

    values.push(
      new InspectPair(
        ': ',
        new InspectLeaf('[' + key + ']', null, depth + 1, opts),
        inspectValue(error[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key in error) {
    if (key === 'constructor' || builtins.includes(key)) continue

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(error[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  if (values.length === 0) return new InspectLeaf(header, null, depth, opts)

  return new InspectSequence(
    header + ' {',
    ' }',
    ', ',
    values,
    ref,
    depth,
    opts
  )
}

function inspectPromise(promise, ref, depth, opts) {
  ref.increment()

  const state = binding.getPromiseState(promise)

  const values = []

  switch (state) {
    case 0: // Pending
      values.push(new InspectLeaf('<pending>', styles.special, depth, opts))
      break

    case 1: // Fulfilled
      values.push(inspectValue(binding.getPromiseResult(promise), depth, opts))
      break

    case 2: // Rejected
      values.push(
        new InspectLeaf('<rejected>', styles.special, depth, opts),
        inspectValue(binding.getPromiseResult(promise), depth, opts)
      )
  }

  ref.decrement()

  const header = promise.constructor.name + ' { '

  return new InspectSequence(header, ' }', ' ', values, ref, depth, opts)
}

function inspectMap(map, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxMapLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = maxMapLength

  for (const entry of map) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(map.size - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )
      break
    }

    values.push(
      new InspectPair(
        ' => ',
        inspectValue(entry[0], depth + 1, opts),
        inspectValue(entry[1], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key in map) {
    if (key === 'constructor') continue

    const value = inspectValue(map[key], depth + 1, opts)

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        value,
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = map.constructor.name + '(' + map.size + ') { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectSet(set, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxSetLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = maxSetLength

  for (const entry of set) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(set.size - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )
      break
    }

    values.push(inspectValue(entry, depth + 1, opts))
  }

  for (const key in set) {
    if (key === 'constructor') continue

    const value = inspectValue(set[key], depth + 1, opts)

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        value,
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = set.constructor.name + '(' + set.size + ') { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectWeakMap(weakMap, ref, depth, opts) {
  const header = weakMap.constructor.name + ' { '

  return new InspectSequence(
    header,
    ' }',
    ' ',
    [new InspectLeaf('<items unknown>', styles.special, depth + 1, opts)],
    ref,
    depth,
    opts
  )
}

function inspectWeakSet(weakSet, ref, depth, opts) {
  const header = weakSet.constructor.name + ' { '

  return new InspectSequence(
    header,
    ' }',
    ' ',
    [new InspectLeaf('<items unknown>', styles.special, depth + 1, opts)],
    ref,
    depth,
    opts
  )
}

function inspectWeakRef(weakRef, ref, depth, opts) {
  const target = weakRef.deref()

  let value

  if (target === undefined) {
    value = new InspectLeaf('<cleared>', styles.special, depth + 1, opts)
  } else {
    value = inspectValue(target, depth + 1, opts)
  }

  const header = weakRef.constructor.name + ' { '

  return new InspectSequence(header, ' }', ' ', [value], ref, depth, opts)
}

function inspectArrayBuffer(arrayBuffer, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(arrayBuffer[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = arrayBuffer.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectSharedArrayBuffer(sharedArrayBuffer, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(sharedArrayBuffer[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = sharedArrayBuffer.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectTypedArray(typedArray, ref, depth, opts) {
  if (Buffer.isBuffer(typedArray)) {
    return inspectBuffer(typedArray, ref, depth, opts)
  }

  const {
    maxArrayLength = defaultMaxArrayLength,
    maxTypedArrayLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxTypedArrayLength, 0)

  for (let i = 0, n = typedArray.length; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(typedArray.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(inspectValue(typedArray[i], depth + 1, opts))
  }

  for (const key of binding.getOwnNonIndexPropertyNames(typedArray)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(typedArray[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = typedArray.constructor.name + '(' + typedArray.length + ') [ '

  return new InspectSequence(header, ' ]', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectBuffer(buffer, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxBufferLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxBufferLength, 0)

  for (let i = 0, n = buffer.byteLength; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(buffer.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(
      new InspectLeaf(
        buffer[i].toString(16).padStart(2, '0'),
        null,
        depth + 1,
        opts
      )
    )
  }

  for (const key of binding.getOwnNonIndexPropertyNames(buffer)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(buffer[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  return new InspectSequence('<Buffer ', '>', ' ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectDataView(dataView, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength', 'byteOffset', 'buffer']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(dataView[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key of binding.getOwnNonIndexPropertyNames(dataView)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(dataView[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = dataView.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectFunction(type, fn, depth, opts) {
  if (fn.toString().startsWith('class')) return inspectClass(fn, depth, opts)

  let tag = 'function'

  if (type.isGeneratorFunction()) tag = 'generator ' + tag
  if (type.isAsyncFunction()) tag = 'async ' + tag

  return new InspectLeaf(
    '[' + tag + ' ' + (fn.name ? fn.name : '(anonymous)') + ']',
    styles.special,
    depth,
    opts
  )
}

function inspectClass(ctor, depth, opts) {
  return new InspectLeaf(
    '[class ' + (ctor.name ? ctor.name : '(anonymous)') + ']',
    styles.special,
    depth,
    opts
  )
}

function inspectExternal(external, depth, opts) {
  return new InspectLeaf(
    '[external 0x' + binding.getExternal(external).toString(16) + ']',
    styles.special,
    depth,
    opts
  )
}
{
  "name": "bare-inspect",
  "version": "3.1.4",
  "description": "Inspect objects as strings for debugging",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-inspect.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-inspect/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-inspect#readme",
  "engines": {
    "bare": ">=1.18.0"
  },
  "dependencies": {
    "bare-ansi-escapes": "^2.1.0",
    "bare-type": "^1.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
module.exports = require.addon()
const binding = require('./binding')
const errors = require('./lib/errors')
const constants = require('./lib/constants')

exports.constants = constants
exports.errors = errors

exports.EOL = binding.platform === 'win32' ? '\r\n' : '\n'

exports.devNull = binding.platform === 'win32' ? '\\\\.\\nul' : '/dev/null'

exports.platform = function platform() {
  return binding.platform
}

exports.arch = function arch() {
  return binding.arch
}

exports.type = function type() {
  return binding.type()
}

exports.version = function version() {
  return binding.version()
}

exports.release = function release() {
  return binding.release()
}

exports.machine = function machine() {
  return binding.machine()
}

exports.execPath = function execPath() {
  return binding.execPath()
}

exports.pid = function pid() {
  return binding.pid()
}

exports.ppid = function ppid() {
  return binding.ppid()
}

exports.cwd = function cwd() {
  return binding.cwd()
}

exports.chdir = function chdir(dir) {
  validateString(dir, 'Directory')

  binding.chdir(dir)
}

exports.tmpdir = function tmpdir() {
  return binding.tmpdir()
}

exports.homedir = function homedir() {
  return binding.homedir()
}

exports.hostname = function hostname() {
  return binding.hostname()
}

exports.userInfo = function userInfo(uid) {
  if (uid !== undefined) validateInteger(uid, 'User ID')

  return binding.userInfo(uid)
}

exports.groupInfo = function groupInfo(gid) {
  if (gid !== undefined) validateInteger(gid, 'Group ID')

  return binding.groupInfo(gid)
}

exports.networkInterfaces = function networkInterfaces() {
  const result = {}

  for (const entry of binding.networkInterfaces()) {
    const { name, ...properties } = entry

    if (result[name]) result[name].push(properties)
    else result[name] = [properties]
  }

  return result
}

exports.kill = function kill(pid, signal = constants.signals.SIGTERM) {
  validateInteger(pid, 'Process ID')

  if (typeof signal === 'string') {
    if (signal in constants.signals === false) {
      throw errors.UNKNOWN_SIGNAL('Unknown signal: ' + signal)
    }

    signal = constants.signals[signal]
  } else {
    validateInteger(signal, 'Signal')
  }

  binding.kill(pid, signal)
}

exports.endianness = function endianness() {
  return binding.isLittleEndian ? 'LE' : 'BE'
}

exports.availableParallelism = function availableParallelism() {
  return binding.availableParallelism()
}

exports.cpuUsage = function cpuUsage(previous) {
  const current = binding.cpuUsage()

  if (previous) {
    return {
      user: current.user - previous.user,
      system: current.system - previous.system
    }
  }

  return current
}

exports.threadCpuUsage = function threadCpuUsage(previous) {
  const current = binding.threadCpuUsage()

  if (previous) {
    return {
      user: current.user - previous.user,
      system: current.system - previous.system
    }
  }

  return current
}

exports.resourceUsage = function resourceUsage() {
  return binding.resourceUsage()
}

exports.memoryUsage = function memoryUsage() {
  return binding.memoryUsage()
}

exports.freemem = function freemem() {
  return binding.freemem()
}

exports.totalmem = function totalmem() {
  return binding.totalmem()
}

exports.availableMemory = function availableMemory() {
  return binding.availableMemory()
}

exports.constrainedMemory = function constrainedMemory() {
  return binding.constrainedMemory()
}

exports.uptime = function uptime() {
  return binding.uptime()
}

exports.loadavg = function loadavg() {
  return binding.loadavg()
}

exports.cpus = function cpus() {
  return binding.cpus()
}

exports.getProcessTitle = function getProcessTitle() {
  return binding.getProcessTitle()
}

exports.setProcessTitle = function setProcessTitle(title) {
  if (typeof title !== 'string') title = title.toString()

  if (title.length >= 256) {
    throw errors.TITLE_OVERFLOW('Process title is too long')
  }

  binding.setProcessTitle(title)
}

exports.getPriority = function getPriority(pid = 0) {
  validateInteger(pid, 'Process ID')

  return binding.getPriority(pid)
}

exports.setPriority = function setPriority(pid, priority) {
  if (priority === undefined) {
    priority = pid
    pid = 0
  }

  validateInteger(pid, 'Process ID')
  validateInteger(priority, 'Priority')

  binding.setPriority(pid, priority)
}

exports.getEnvKeys = function getEnvKeys() {
  return binding.getEnvKeys()
}

exports.getEnv = function getEnv(name) {
  validateString(name, 'Name')

  return binding.getEnv(name)
}

exports.hasEnv = function hasEnv(name) {
  validateString(name, 'Name')

  return binding.hasEnv(name)
}

exports.setEnv = function setEnv(name, value) {
  validateString(name, 'Name')
  validateString(value, 'Value')

  binding.setEnv(name, value)
}

exports.unsetEnv = function unsetEnv(name) {
  validateString(name, 'Name')

  binding.unsetEnv(name)
}

function validateString(value, name) {
  if (typeof value !== 'string') {
    throw new TypeError(`${name} must be a string. Received type ${typeof value} (${value})`)
  }
}

function validateInteger(value, name) {
  if (!Number.isInteger(value)) {
    throw new TypeError(`${name} must be an integer. Received type ${typeof value} (${value})`)
  }
}
const binding = require('../binding')

module.exports = {
  signals: binding.signals,
  errnos: binding.errnos,
  priority: binding.priority
}
module.exports = class OSError extends Error {
  constructor(msg, fn = OSError, code = fn.name) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'OSError'
  }

  static UNKNOWN_SIGNAL(msg) {
    return new OSError(msg, OSError.UNKNOWN_SIGNAL)
  }

  static TITLE_OVERFLOW(msg) {
    return new OSError(msg, OSError.TITLE_OVERFLOW)
  }
}
{
  "name": "bare-os",
  "version": "3.9.3",
  "description": "Operating system utilities for Bare",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    },
    "./errors": {
      "types": "./lib/errors.d.ts",
      "default": "./lib/errors.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-os.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-os/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-os#readme",
  "engines": {
    "bare": ">=1.14.0"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "cmake-bare": "^1.1.6",
    "lunte": "^1.6.0",
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
// This export SHOULD NOT be shortened in any way as having the full
// `module.exports = require(...)` statement is crucial for synthesizing
// ESM exports.

if (Bare.platform === 'win32') {
  module.exports = require('./lib/win32')
} else {
  module.exports = require('./lib/posix')
}
module.exports = {
  CHAR_UPPERCASE_A: 0x41,
  CHAR_LOWERCASE_A: 0x61,
  CHAR_UPPERCASE_Z: 0x5a,
  CHAR_LOWERCASE_Z: 0x7a,
  CHAR_DOT: 0x2e,
  CHAR_FORWARD_SLASH: 0x2f,
  CHAR_BACKWARD_SLASH: 0x5c,
  CHAR_COLON: 0x3a,
  CHAR_QUESTION_MARK: 0x3f
}
const os = require('bare-os')

const { normalizeString } = require('./shared')
const { CHAR_DOT, CHAR_FORWARD_SLASH } = require('./constants')

function isPosixPathSeparator(code) {
  return code === CHAR_FORWARD_SLASH
}

exports.win32 = require('./win32')
exports.posix = exports

exports.sep = '/'
exports.delimiter = ':'

exports.resolve = function resolve(...args) {
  let resolvedPath = ''
  let resolvedAbsolute = false

  for (let i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) {
    const path = i >= 0 ? args[i] : os.cwd()

    if (path.length === 0) {
      continue
    }

    resolvedPath = `${path}/${resolvedPath}`
    resolvedAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH
  }

  resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute, '/', isPosixPathSeparator)

  if (resolvedAbsolute) {
    return `/${resolvedPath}`
  }

  return resolvedPath.length > 0 ? resolvedPath : '.'
}

exports.normalize = function normalize(path) {
  if (path.length === 0) return '.'

  const isAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH
  const trailingSeparator = path.charCodeAt(path.length - 1) === CHAR_FORWARD_SLASH

  path = normalizeString(path, !isAbsolute, '/', isPosixPathSeparator)

  if (path.length === 0) {
    if (isAbsolute) return '/'
    return trailingSeparator ? './' : '.'
  }

  if (trailingSeparator) path += '/'

  return isAbsolute ? `/${path}` : path
}

exports.isAbsolute = function isAbsolute(path) {
  return path.length > 0 && path.charCodeAt(0) === CHAR_FORWARD_SLASH
}

exports.join = function join(...args) {
  if (args.length === 0) return '.'
  let joined
  for (let i = 0; i < args.length; ++i) {
    const arg = args[i]
    if (arg.length > 0) {
      if (joined === undefined) joined = arg
      else joined += `/${arg}`
    }
  }
  if (joined === undefined) return '.'
  return exports.normalize(joined)
}

exports.relative = function relative(from, to) {
  if (from === to) return ''

  from = exports.resolve(from)
  to = exports.resolve(to)

  if (from === to) return ''

  const fromStart = 1
  const fromEnd = from.length
  const fromLen = fromEnd - fromStart
  const toStart = 1
  const toLen = to.length - toStart

  const length = fromLen < toLen ? fromLen : toLen
  let lastCommonSep = -1
  let i = 0
  for (; i < length; i++) {
    const fromCode = from.charCodeAt(fromStart + i)
    if (fromCode !== to.charCodeAt(toStart + i)) {
      break
    } else if (fromCode === CHAR_FORWARD_SLASH) {
      lastCommonSep = i
    }
  }
  if (i === length) {
    if (toLen > length) {
      if (to.charCodeAt(toStart + i) === CHAR_FORWARD_SLASH) {
        return to.substring(toStart + i + 1)
      }
      if (i === 0) {
        return to.substring(toStart + i)
      }
    } else if (fromLen > length) {
      if (from.charCodeAt(fromStart + i) === CHAR_FORWARD_SLASH) {
        lastCommonSep = i
      } else if (i === 0) {
        lastCommonSep = 0
      }
    }
  }

  let out = ''
  for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
    if (i === fromEnd || from.charCodeAt(i) === CHAR_FORWARD_SLASH) {
      out += out.length === 0 ? '..' : '/..'
    }
  }

  return `${out}${to.substring(toStart + lastCommonSep)}`
}

exports.toNamespacedPath = function toNamespacedPath(path) {
  return path
}

exports.dirname = function dirname(path) {
  if (path.length === 0) return '.'
  const hasRoot = path.charCodeAt(0) === CHAR_FORWARD_SLASH
  let end = -1
  let matchedSlash = true
  for (let i = path.length - 1; i >= 1; --i) {
    if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) {
      if (!matchedSlash) {
        end = i
        break
      }
    } else {
      matchedSlash = false
    }
  }

  if (end === -1) return hasRoot ? '/' : '.'
  if (hasRoot && end === 1) return '//'
  return path.substring(0, end)
}

exports.basename = function basename(path, suffix) {
  let start = 0
  let end = -1
  let matchedSlash = true

  if (suffix !== undefined && suffix.length > 0 && suffix.length <= path.length) {
    if (suffix === path) {
      return ''
    }
    let extIdx = suffix.length - 1
    let firstNonSlashEnd = -1
    for (let i = path.length - 1; i >= 0; --i) {
      const code = path.charCodeAt(i)
      if (code === CHAR_FORWARD_SLASH) {
        if (!matchedSlash) {
          start = i + 1
          break
        }
      } else {
        if (firstNonSlashEnd === -1) {
          matchedSlash = false
          firstNonSlashEnd = i + 1
        }
        if (extIdx >= 0) {
          if (code === suffix.charCodeAt(extIdx)) {
            if (--extIdx === -1) {
              end = i
            }
          } else {
            extIdx = -1
            end = firstNonSlashEnd
          }
        }
      }
    }

    if (start === end) end = firstNonSlashEnd
    else if (end === -1) end = path.length
    return path.substring(start, end)
  }

  for (let i = path.length - 1; i >= 0; --i) {
    if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) {
      if (!matchedSlash) {
        start = i + 1
        break
      }
    } else if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
  }

  if (end === -1) return ''
  return path.substring(start, end)
}

exports.extname = function extname(path) {
  let startDot = -1
  let startPart = 0
  let end = -1
  let matchedSlash = true
  let preDotState = 0
  for (let i = path.length - 1; i >= 0; --i) {
    const code = path.charCodeAt(i)
    if (code === CHAR_FORWARD_SLASH) {
      if (!matchedSlash) {
        startPart = i + 1
        break
      }
      continue
    }
    if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
    if (code === CHAR_DOT) {
      if (startDot === -1) startDot = i
      else if (preDotState !== 1) preDotState = 1
    } else if (startDot !== -1) {
      preDotState = -1
    }
  }

  if (
    startDot === -1 ||
    end === -1 ||
    preDotState === 0 ||
    (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1)
  ) {
    return ''
  }
  return path.substring(startDot, end)
}
const { CHAR_DOT, CHAR_FORWARD_SLASH } = require('./constants')

exports.normalizeString = function normalizeString(
  path,
  allowAboveRoot,
  separator,
  isPathSeparator
) {
  let res = ''
  let lastSegmentLength = 0
  let lastSlash = -1
  let dots = 0
  let code = 0
  for (let i = 0; i <= path.length; ++i) {
    if (i < path.length) {
      code = path.charCodeAt(i)
    } else if (isPathSeparator(code)) {
      break
    } else {
      code = CHAR_FORWARD_SLASH
    }

    if (isPathSeparator(code)) {
      if (lastSlash === i - 1 || dots === 1);
      else if (dots === 2) {
        if (
          res.length < 2 ||
          lastSegmentLength !== 2 ||
          res.charCodeAt(res.length - 1) !== CHAR_DOT ||
          res.charCodeAt(res.length - 2) !== CHAR_DOT
        ) {
          if (res.length > 2) {
            const lastSlashIndex = res.lastIndexOf(separator)
            if (lastSlashIndex === -1) {
              res = ''
              lastSegmentLength = 0
            } else {
              res = res.substring(0, lastSlashIndex)
              lastSegmentLength = res.length - 1 - res.lastIndexOf(separator)
            }
            lastSlash = i
            dots = 0
            continue
          } else if (res.length !== 0) {
            res = ''
            lastSegmentLength = 0
            lastSlash = i
            dots = 0
            continue
          }
        }
        if (allowAboveRoot) {
          res += res.length > 0 ? `${separator}..` : '..'
          lastSegmentLength = 2
        }
      } else {
        if (res.length > 0) {
          res += `${separator}${path.substring(lastSlash + 1, i)}`
        } else {
          res = path.substring(lastSlash + 1, i)
        }
        lastSegmentLength = i - lastSlash - 1
      }
      lastSlash = i
      dots = 0
    } else if (code === CHAR_DOT && dots !== -1) {
      ++dots
    } else {
      dots = -1
    }
  }
  return res
}
const os = require('bare-os')

const { normalizeString } = require('./shared')
const {
  CHAR_UPPERCASE_A,
  CHAR_LOWERCASE_A,
  CHAR_UPPERCASE_Z,
  CHAR_LOWERCASE_Z,
  CHAR_DOT,
  CHAR_FORWARD_SLASH,
  CHAR_BACKWARD_SLASH,
  CHAR_COLON,
  CHAR_QUESTION_MARK
} = require('./constants')

function isWindowsPathSeparator(code) {
  return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH
}

function isWindowsDeviceRoot(code) {
  return (
    (code >= CHAR_UPPERCASE_A && code <= CHAR_UPPERCASE_Z) ||
    (code >= CHAR_LOWERCASE_A && code <= CHAR_LOWERCASE_Z)
  )
}

exports.posix = require('./posix')
exports.win32 = exports

exports.sep = '\\'
exports.delimiter = ';'

exports.resolve = function resolve(...args) {
  let resolvedDevice = ''
  let resolvedTail = ''
  let resolvedAbsolute = false

  for (let i = args.length - 1; i >= -1; i--) {
    let path
    if (i >= 0) {
      path = args[i]

      if (path.length === 0) continue
    } else if (resolvedDevice.length === 0) {
      path = os.cwd()
    } else {
      path = os.getEnv(`=${resolvedDevice}`) || os.cwd()

      if (
        path === undefined ||
        (path.substring(0, 2).toLowerCase() !== resolvedDevice.toLowerCase() &&
          path.charCodeAt(2) === CHAR_BACKWARD_SLASH)
      ) {
        path = `${resolvedDevice}\\`
      }
    }

    const len = path.length
    let rootEnd = 0
    let device = ''
    let isAbsolute = false
    const code = path.charCodeAt(0)

    if (len === 1) {
      if (isWindowsPathSeparator(code)) {
        rootEnd = 1
        isAbsolute = true
      }
    } else if (isWindowsPathSeparator(code)) {
      isAbsolute = true

      if (isWindowsPathSeparator(path.charCodeAt(1))) {
        let j = 2
        let last = j
        while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
          j++
        }
        if (j < len && j !== last) {
          const firstPart = path.substring(last, j)
          last = j
          while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
            j++
          }
          if (j < len && j !== last) {
            last = j
            while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
              j++
            }
            if (j === len || j !== last) {
              device = `\\\\${firstPart}\\${path.substring(last, j)}`
              rootEnd = j
            }
          }
        }
      } else {
        rootEnd = 1
      }
    } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
      device = path.substring(0, 2)
      rootEnd = 2
      if (len > 2 && isWindowsPathSeparator(path.charCodeAt(2))) {
        isAbsolute = true
        rootEnd = 3
      }
    }

    if (device.length > 0) {
      if (resolvedDevice.length > 0) {
        if (device.toLowerCase() !== resolvedDevice.toLowerCase()) {
          continue
        }
      } else {
        resolvedDevice = device
      }
    }

    if (resolvedAbsolute) {
      if (resolvedDevice.length > 0) {
        break
      }
    } else {
      resolvedTail = `${path.substring(rootEnd)}\\${resolvedTail}`
      resolvedAbsolute = isAbsolute
      if (isAbsolute && resolvedDevice.length > 0) {
        break
      }
    }
  }

  resolvedTail = normalizeString(resolvedTail, !resolvedAbsolute, '\\', isWindowsPathSeparator)

  return resolvedAbsolute
    ? `${resolvedDevice}\\${resolvedTail}`
    : `${resolvedDevice}${resolvedTail}` || '.'
}

exports.normalize = function normalize(path) {
  const len = path.length
  if (len === 0) return '.'
  let rootEnd = 0
  let device
  let isAbsolute = false
  const code = path.charCodeAt(0)

  if (len === 1) {
    return code === CHAR_FORWARD_SLASH ? '\\' : path
  }

  if (isWindowsPathSeparator(code)) {
    isAbsolute = true

    if (isWindowsPathSeparator(path.charCodeAt(1))) {
      let j = 2
      let last = j
      while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
        j++
      }
      if (j < len && j !== last) {
        const firstPart = path.substring(last, j)
        last = j
        while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
          j++
        }
        if (j < len && j !== last) {
          last = j
          while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
            j++
          }
          if (j === len) {
            return `\\\\${firstPart}\\${path.substring(last)}\\`
          }
          if (j !== last) {
            device = `\\\\${firstPart}\\${path.substring(last, j)}`
            rootEnd = j
          }
        }
      }
    } else {
      rootEnd = 1
    }
  } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
    device = path.substring(0, 2)
    rootEnd = 2
    if (len > 2 && isWindowsPathSeparator(path.charCodeAt(2))) {
      isAbsolute = true
      rootEnd = 3
    }
  }

  let tail =
    rootEnd < len
      ? normalizeString(path.substring(rootEnd), !isAbsolute, '\\', isWindowsPathSeparator)
      : ''
  if (tail.length === 0 && !isAbsolute) {
    tail = '.'
  }
  if (tail.length > 0 && isWindowsPathSeparator(path.charCodeAt(len - 1))) {
    tail += '\\'
  }
  if (device === undefined) {
    return isAbsolute ? `\\${tail}` : tail
  }
  return isAbsolute ? `${device}\\${tail}` : `${device}${tail}`
}

exports.isAbsolute = function isAbsolute(path) {
  const len = path.length
  if (len === 0) return false

  const code = path.charCodeAt(0)

  return (
    isWindowsPathSeparator(code) ||
    (len > 2 &&
      isWindowsDeviceRoot(code) &&
      path.charCodeAt(1) === CHAR_COLON &&
      isWindowsPathSeparator(path.charCodeAt(2)))
  )
}

exports.join = function join(...args) {
  if (args.length === 0) return '.'

  let joined
  let firstPart
  for (let i = 0; i < args.length; ++i) {
    const arg = args[i]
    if (arg.length > 0) {
      if (joined === undefined) joined = firstPart = arg
      else joined += `\\${arg}`
    }
  }

  if (joined === undefined) return '.'

  let needsReplace = true
  let slashCount = 0
  if (isWindowsPathSeparator(firstPart.charCodeAt(0))) {
    ++slashCount
    const firstLen = firstPart.length
    if (firstLen > 1 && isWindowsPathSeparator(firstPart.charCodeAt(1))) {
      ++slashCount
      if (firstLen > 2) {
        if (isWindowsPathSeparator(firstPart.charCodeAt(2))) {
          ++slashCount
        } else {
          needsReplace = false
        }
      }
    }
  }
  if (needsReplace) {
    while (slashCount < joined.length && isWindowsPathSeparator(joined.charCodeAt(slashCount))) {
      slashCount++
    }

    if (slashCount >= 2) {
      joined = `\\${joined.substring(slashCount)}`
    }
  }

  return exports.normalize(joined)
}

exports.relative = function relative(from, to) {
  if (from === to) return ''

  const fromOrig = exports.resolve(from)
  const toOrig = exports.resolve(to)

  if (fromOrig === toOrig) return ''

  from = fromOrig.toLowerCase()
  to = toOrig.toLowerCase()

  if (from === to) return ''

  let fromStart = 0
  while (fromStart < from.length && from.charCodeAt(fromStart) === CHAR_BACKWARD_SLASH) {
    fromStart++
  }
  let fromEnd = from.length
  while (fromEnd - 1 > fromStart && from.charCodeAt(fromEnd - 1) === CHAR_BACKWARD_SLASH) {
    fromEnd--
  }
  const fromLen = fromEnd - fromStart

  let toStart = 0
  while (toStart < to.length && to.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) {
    toStart++
  }
  let toEnd = to.length
  while (toEnd - 1 > toStart && to.charCodeAt(toEnd - 1) === CHAR_BACKWARD_SLASH) {
    toEnd--
  }
  const toLen = toEnd - toStart

  const length = fromLen < toLen ? fromLen : toLen
  let lastCommonSep = -1
  let i = 0
  for (; i < length; i++) {
    const fromCode = from.charCodeAt(fromStart + i)
    if (fromCode !== to.charCodeAt(toStart + i)) {
      break
    } else if (fromCode === CHAR_BACKWARD_SLASH) {
      lastCommonSep = i
    }
  }

  if (i !== length) {
    if (lastCommonSep === -1) return toOrig
  } else {
    if (toLen > length) {
      if (to.charCodeAt(toStart + i) === CHAR_BACKWARD_SLASH) {
        return toOrig.substring(toStart + i + 1)
      }
      if (i === 2) {
        return toOrig.substring(toStart + i)
      }
    }
    if (fromLen > length) {
      if (from.charCodeAt(fromStart + i) === CHAR_BACKWARD_SLASH) {
        lastCommonSep = i
      } else if (i === 2) {
        lastCommonSep = 3
      }
    }
    if (lastCommonSep === -1) lastCommonSep = 0
  }

  let out = ''
  for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
    if (i === fromEnd || from.charCodeAt(i) === CHAR_BACKWARD_SLASH) {
      out += out.length === 0 ? '..' : '\\..'
    }
  }

  toStart += lastCommonSep

  if (out.length > 0) {
    return `${out}${toOrig.substring(toStart, toEnd)}`
  }
  if (toOrig.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) {
    ++toStart
  }
  return toOrig.substring(toStart, toEnd)
}

exports.toNamespacedPath = function toNamespacedPath(path) {
  if (path.length === 0) return path

  const resolvedPath = exports.resolve(path)

  if (resolvedPath.length <= 2) return path

  if (resolvedPath.charCodeAt(0) === CHAR_BACKWARD_SLASH) {
    if (resolvedPath.charCodeAt(1) === CHAR_BACKWARD_SLASH) {
      const code = resolvedPath.charCodeAt(2)
      if (code !== CHAR_QUESTION_MARK && code !== CHAR_DOT) {
        return `\\\\?\\UNC\\${resolvedPath.substring(2)}`
      }
    }
  } else if (
    isWindowsDeviceRoot(resolvedPath.charCodeAt(0)) &&
    resolvedPath.charCodeAt(1) === CHAR_COLON &&
    resolvedPath.charCodeAt(2) === CHAR_BACKWARD_SLASH
  ) {
    return `\\\\?\\${resolvedPath}`
  }

  return path
}

exports.dirname = function dirname(path) {
  const len = path.length
  if (len === 0) return '.'
  let rootEnd = -1
  let offset = 0
  const code = path.charCodeAt(0)

  if (len === 1) {
    return isWindowsPathSeparator(code) ? path : '.'
  }

  if (isWindowsPathSeparator(code)) {
    rootEnd = offset = 1

    if (isWindowsPathSeparator(path.charCodeAt(1))) {
      let j = 2
      let last = j
      while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
        j++
      }
      if (j < len && j !== last) {
        last = j
        while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
          j++
        }
        if (j < len && j !== last) {
          last = j
          while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
            j++
          }
          if (j === len) {
            return path
          }
          if (j !== last) {
            rootEnd = offset = j + 1
          }
        }
      }
    }
  } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
    rootEnd = len > 2 && isWindowsPathSeparator(path.charCodeAt(2)) ? 3 : 2
    offset = rootEnd
  }

  let end = -1
  let matchedSlash = true
  for (let i = len - 1; i >= offset; --i) {
    if (isWindowsPathSeparator(path.charCodeAt(i))) {
      if (!matchedSlash) {
        end = i
        break
      }
    } else {
      matchedSlash = false
    }
  }

  if (end === -1) {
    if (rootEnd === -1) return '.'

    end = rootEnd
  }
  return path.substring(0, end)
}

exports.basename = function basename(path, suffix) {
  let start = 0
  let end = -1
  let matchedSlash = true

  if (
    path.length >= 2 &&
    isWindowsDeviceRoot(path.charCodeAt(0)) &&
    path.charCodeAt(1) === CHAR_COLON
  ) {
    start = 2
  }

  if (suffix !== undefined && suffix.length > 0 && suffix.length <= path.length) {
    if (suffix === path) return ''
    let extIdx = suffix.length - 1
    let firstNonSlashEnd = -1
    for (let i = path.length - 1; i >= start; --i) {
      const code = path.charCodeAt(i)
      if (isWindowsPathSeparator(code)) {
        if (!matchedSlash) {
          start = i + 1
          break
        }
      } else {
        if (firstNonSlashEnd === -1) {
          matchedSlash = false
          firstNonSlashEnd = i + 1
        }
        if (extIdx >= 0) {
          if (code === suffix.charCodeAt(extIdx)) {
            if (--extIdx === -1) {
              end = i
            }
          } else {
            extIdx = -1
            end = firstNonSlashEnd
          }
        }
      }
    }

    if (start === end) end = firstNonSlashEnd
    else if (end === -1) end = path.length
    return path.substring(start, end)
  }
  for (let i = path.length - 1; i >= start; --i) {
    if (isWindowsPathSeparator(path.charCodeAt(i))) {
      if (!matchedSlash) {
        start = i + 1
        break
      }
    } else if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
  }

  if (end === -1) return ''
  return path.substring(start, end)
}

exports.extname = function extname(path) {
  let start = 0
  let startDot = -1
  let startPart = 0
  let end = -1
  let matchedSlash = true
  let preDotState = 0

  if (
    path.length >= 2 &&
    path.charCodeAt(1) === CHAR_COLON &&
    isWindowsDeviceRoot(path.charCodeAt(0))
  ) {
    start = startPart = 2
  }

  for (let i = path.length - 1; i >= start; --i) {
    const code = path.charCodeAt(i)
    if (isWindowsPathSeparator(code)) {
      if (!matchedSlash) {
        startPart = i + 1
        break
      }
      continue
    }
    if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
    if (code === CHAR_DOT) {
      if (startDot === -1) startDot = i
      else if (preDotState !== 1) preDotState = 1
    } else if (startDot !== -1) {
      preDotState = -1
    }
  }

  if (
    startDot === -1 ||
    end === -1 ||
    preDotState === 0 ||
    (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1)
  ) {
    return ''
  }
  return path.substring(startDot, end)
}
{
  "name": "bare-path",
  "version": "3.0.1",
  "description": "Path manipulation library for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./posix": "./lib/posix.js",
    "./win32": "./lib/win32.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "lib",
    "NOTICE"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-path.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-path/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-path#readme",
  "dependencies": {
    "bare-os": "^3.0.1"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "lunte": "^1.8.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
const b4a = require('b4a')
const stream = require('streamx')
const { ReadableStream, WritableStream } = require('./web')

const defaultEncoding = 'utf8'

module.exports = exports = stream.Stream

exports.pipeline = stream.pipeline

exports.isStream = stream.isStream
exports.isEnding = stream.isEnding
exports.isEnded = stream.isEnded
exports.isFinishing = stream.isFinishing
exports.isFinished = stream.isFinished
exports.isDisturbed = stream.isDisturbed

exports.isErrored = function isErrored(stream) {
  return exports.getStreamError(stream) !== null
}

exports.isReadable = function isReadable(stream) {
  return stream.readable && !stream.destroying && !exports.isEnded(stream)
}

exports.isWritable = function isWritable(stream) {
  return stream.writable && !stream.destroying && !exports.isFinishing(stream)
}

exports.getStreamError = stream.getStreamError

exports.addAbortSignal = function addAbortSignal(signal, stream) {
  function onAbort() {
    stream.destroy(signal.reason)
  }

  if (signal.aborted) onAbort()
  else signal.addEventListener('abort', onAbort)

  return stream
}

exports.Stream = exports

exports.Readable = class Readable extends stream.Readable {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthReadable: null,
      map: null,
      mapReadable: null
    })

    if (this._construct) this._open = this._construct

    if (this._read !== stream.Readable.prototype._read) {
      this._read = read.bind(this, this._read)
    }

    if (this._destroy !== stream.Stream.prototype._destroy) {
      this._destroy = destroy.bind(this, this._destroy)
    }
  }

  get closed() {
    return !exports.isReadable(this)
  }

  get errored() {
    return stream.getStreamError(this)
  }

  push(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    return super.push(chunk)
  }

  unshift(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    super.unshift(chunk)
  }

  static fromWeb(readableStream, opts = {}) {
    const stream = readableStream._stream

    if (opts.encoding) stream.setEncoding(opts.encoding)
    if (opts.signal) exports.addAbortSignal(opts.signal, stream)

    return stream
  }

  static toWeb(readable, opts = {}) {
    return new ReadableStream(readable, opts.strategy)
  }

  async [Symbol.asyncDispose]() {
    if (!this.destroyed) this.destroy()

    await new Promise((resolve) => exports.finished(this, resolve))
  }
}

exports.Writable = class Writable extends stream.Writable {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthWritable,
      map: null,
      mapWritable: null
    })

    if (this._construct) this._open = this._construct

    if (this._write !== stream.Writable.prototype._write) {
      this._write = write.bind(this, this._write)
    }

    if (this._destroy !== stream.Stream.prototype._destroy) {
      this._destroy = destroy.bind(this, this._destroy)
    }
  }

  get closed() {
    return !exports.isWritable(this)
  }

  get errored() {
    return stream.getStreamError(this)
  }

  write(chunk, encoding, cb) {
    if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result = super.write({ chunk, encoding })

    if (cb) stream.Writable.drained(this).then(() => cb(null), cb)

    return result
  }

  end(chunk, encoding, cb) {
    if (typeof chunk === 'function') {
      cb = chunk
      chunk = null
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    } else {
      encoding = 'buffer'
    }

    const result =
      chunk !== undefined && chunk !== null ? super.end({ chunk, encoding }) : super.end()

    if (cb) this.once('finish', () => cb(null))

    return result
  }

  static fromWeb(writableStream, opts = {}) {
    const stream = writableStream._stream

    if (opts.signal) exports.addAbortSignal(opts.signal, stream)

    return stream
  }

  static toWeb(writable) {
    return new WritableStream(writable)
  }

  async [Symbol.asyncDispose]() {
    if (!this.destroyed) this.destroy()

    await new Promise((resolve) => exports.finished(this, resolve))
  }
}

exports.Duplex = class Duplex extends stream.Duplex {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthReadable: null,
      byteLengthWritable,
      map: null,
      mapReadable: null,
      mapWritable: null
    })

    if (this._construct) this._open = this._construct

    if (this._read !== stream.Readable.prototype._read) {
      this._read = read.bind(this, this._read)
    }

    if (this._write !== stream.Duplex.prototype._write) {
      this._write = write.bind(this, this._write)
    }

    if (this._destroy !== stream.Stream.prototype._destroy) {
      this._destroy = destroy.bind(this, this._destroy)
    }
  }

  push(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    return super.push(chunk)
  }

  unshift(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    super.unshift(chunk)
  }

  write(chunk, encoding, cb) {
    if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result = super.write({ chunk, encoding })

    if (cb) stream.Writable.drained(this).then(() => cb(null), cb)

    return result
  }

  end(chunk, encoding, cb) {
    if (typeof chunk === 'function') {
      cb = chunk
      chunk = null
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result =
      chunk !== undefined && chunk !== null ? super.end({ chunk, encoding }) : super.end()

    if (cb) this.once('finish', () => cb(null))

    return result
  }

  static fromWeb({ readable: readableStream, writable: writableStream }, opts) {
    const readable = exports.Readable.fromWeb(readableStream, opts)
    const writable = exports.Writable.fromWeb(writableStream, opts)

    const duplex = new exports.Duplex({
      write(data, encoding, cb) {
        writable.write(data, encoding, cb)
      }
    })

    readable
      .on('data', (data) => duplex.push(data))
      .on('end', () => duplex.push(null))
      .on('error', (err) => duplex.destroy(err))

    writable.on('finish', () => duplex.end()).on('error', (err) => duplex.destroy(err))

    return duplex
  }

  static toWeb(duplex) {
    const readableStream = exports.Readable.toWeb(duplex)
    const writableStream = exports.Writable.toWeb(duplex)

    return { readable: readableStream, writable: writableStream }
  }
}

class DuplexSide extends exports.Duplex {
  constructor(opts) {
    super(opts)

    this._otherSide = null
    this._cb = null
  }

  _read() {
    const cb = this._cb
    if (!cb) return

    this._cb = null
    cb()
  }

  _write(chunk, encoding, cb) {
    this._otherSide.push(chunk, encoding)
    this._otherSide._cb = cb
  }

  _final(cb) {
    this._otherSide.on('end', cb)
    this._otherSide.push(null)
  }
}

exports.duplexPair = function duplexPair(opts) {
  const sideA = new DuplexSide(opts)
  const sideB = new DuplexSide(opts)

  sideA._otherSide = sideB
  sideB._otherSide = sideA

  return [sideA, sideB]
}

exports.Transform = class Transform extends stream.Transform {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthReadable: null,
      byteLengthWritable,
      map: null,
      mapReadable: null,
      mapWritable: null
    })

    if (this._transform !== stream.Transform.prototype._transform) {
      this._transform = transform.bind(this, this._transform)
    } else {
      this._transform = passthrough
    }
  }

  push(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    return super.push(chunk)
  }

  unshift(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    super.unshift(chunk)
  }

  write(chunk, encoding, cb) {
    if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result = super.write({ chunk, encoding })

    if (cb) stream.Writable.drained(this).then(() => cb(null), cb)

    return result
  }

  end(chunk, encoding, cb) {
    if (typeof chunk === 'function') {
      cb = chunk
      chunk = null
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result =
      chunk !== undefined && chunk !== null ? super.end({ chunk, encoding }) : super.end()

    if (cb) this.once('finish', () => cb(null))

    return result
  }
}

exports.PassThrough = class PassThrough extends exports.Transform {}

exports.finished = function finished(stream, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (!opts) opts = {}

  const { cleanup = false } = opts

  const done = () => {
    cb(exports.getStreamError(stream, { all: true }))

    if (cleanup) detach()
  }

  const detach = () => {
    stream.off('close', done)
    stream.off('error', noop)
  }

  if (stream.destroyed) {
    done()
  } else {
    stream.on('close', done)
    stream.on('error', noop)
  }

  return detach
}

function read(read, cb) {
  read.call(this, 65536)

  cb(null)
}

function write(write, data, cb) {
  write.call(this, data.chunk, data.encoding, cb)
}

function transform(transform, data, cb) {
  transform.call(this, data.chunk, data.encoding, cb)
}

function destroy(destroy, cb) {
  destroy.call(this, exports.getStreamError(this), cb)
}

function passthrough(data, cb) {
  cb(null, data.chunk)
}

function byteLengthWritable(data) {
  return data.chunk.byteLength
}

function noop() {}
{
  "name": "bare-stream",
  "version": "2.13.3",
  "description": "Streaming data for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./promises": "./promises.js",
    "./web": {
      "types": "./web.d.ts",
      "default": "./web.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "promises.js",
    "web.js",
    "web.d.ts",
    "global.js",
    "global.d.ts"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-stream.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-stream/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-stream#readme",
  "dependencies": {
    "b4a": "^1.8.1",
    "streamx": "^2.25.0",
    "teex": "^1.0.1"
  },
  "devDependencies": {
    "bare-abort-controller": "^1.1.0",
    "bare-buffer": "^3.0.0",
    "bare-events": "^2.5.4",
    "brittle": "^3.5.2",
    "lunte": "^1.6.0",
    "prettier": "^3.3.3",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "bare-abort-controller": "*",
    "bare-buffer": "*",
    "bare-events": "*"
  },
  "peerDependenciesMeta": {
    "bare-abort-controller": {
      "optional": true
    },
    "bare-buffer": {
      "optional": true
    },
    "bare-events": {
      "optional": true
    }
  }
}
const { Readable, Writable, Transform, getStreamError, isStreamx, isDisturbed } = require('streamx')
const tee = require('teex')

const readableKind = Symbol.for('bare.stream.readable.kind')
const writableKind = Symbol.for('bare.stream.writable.kind')
const transformKind = Symbol.for('bare.stream.transform.kind')

// https://streams.spec.whatwg.org/#readablestreamdefaultreader
exports.ReadableStreamDefaultReader = class ReadableStreamDefaultReader {
  constructor(stream) {
    this._stream = stream
    this._stream._stream.once('close', onclose).once('error', onerror)

    const closed = Promise.withResolvers()

    // Avoid unhandled exceptions
    closed.promise.catch(noop)

    this._closed = closed

    function onclose() {
      closed.resolve()
    }

    function onerror(err) {
      closed.reject(err)
    }
  }

  get closed() {
    return this._closed.promise
  }

  read() {
    const stream = this._stream._stream

    return new Promise((resolve, reject) => {
      const err = getStreamError(stream)

      if (err) return reject(err)

      if (stream.destroyed) {
        return resolve({ value: undefined, done: true })
      }

      const value = stream.read()

      if (value !== null) {
        return resolve({ value, done: false })
      }

      stream.once('readable', onreadable).once('close', onclose).once('error', onerror)

      function onreadable() {
        const value = stream.read()

        ondone(null, value === null ? { value: undefined, done: true } : { value, done: false })
      }

      function onclose() {
        ondone(null, { value: undefined, done: true })
      }

      function onerror(err) {
        ondone(err, null)
      }

      function ondone(err, value) {
        stream.off('readable', onreadable).off('close', onclose).off('error', onerror)

        if (err) reject(err)
        else resolve(value)
      }
    })
  }

  releaseLock() {
    this._closed.reject(new TypeError('Reader was released'))
    this._stream._releaseLock()
    this._stream = null
  }

  cancel(reason = new TypeError('Stream was cancelled')) {
    const stream = this._stream._stream

    if (stream.destroyed) return Promise.resolve()

    return new Promise((resolve) =>
      stream.once('close', resolve).once('error', noop).destroy(reason)
    )
  }
}

// https://streams.spec.whatwg.org/#readablestreamdefaultcontroller
exports.ReadableStreamDefaultController = class ReadableStreamDefaultController {
  constructor(stream) {
    this._stream = stream
  }

  get desiredSize() {
    const stream = this._stream._stream

    return stream._readableState.highWaterMark - stream._readableState.buffered
  }

  enqueue(data) {
    this._stream._stream.push(data)
  }

  close() {
    this._stream._stream.push(null)
  }

  error(err) {
    this._stream._stream.destroy(err)
  }
}

// https://streams.spec.whatwg.org/#readablestream
class ReadableStream {
  static get [readableKind]() {
    return 0 // Compatibility version
  }

  static from(iterable) {
    return new ReadableStream(Readable.from(iterable))
  }

  constructor(underlyingSource = {}, queuingStrategy) {
    if (isStreamx(underlyingSource)) {
      this._stream = underlyingSource
    } else {
      if (queuingStrategy === undefined) {
        queuingStrategy = new exports.CountQueuingStrategy()
      }

      const { start, pull, cancel } = underlyingSource
      const { highWaterMark = 1, size = defaultSize } = queuingStrategy

      this._stream = new Readable({ highWaterMark, byteLength: size })

      const controller = new exports.ReadableStreamDefaultController(this)

      try {
        let starting = Promise.resolve()

        if (start) starting = forwardError(start.call(this, controller), controller)

        if (pull) {
          this._stream._read = this._read.bind(this, starting, pull.bind(this, controller))
        }

        if (cancel) {
          this._stream.once('error', cancel.bind(this))
        }
      } catch (err) {
        controller.error(err)
      }
    }

    this._reader = null
  }

  get [readableKind]() {
    return ReadableStream[readableKind]
  }

  get locked() {
    return this._reader !== null
  }

  getReader() {
    if (this.locked) throw new TypeError('Stream is locked')

    this._reader = new exports.ReadableStreamDefaultReader(this)

    return this._reader
  }

  cancel(reason = new TypeError('Stream was cancelled')) {
    const stream = this._stream

    if (stream.destroyed) return Promise.resolve()

    if (this.locked) return Promise.reject(new TypeError('Stream is locked'))

    return new Promise((resolve) =>
      stream.once('close', resolve).once('error', noop).destroy(reason)
    )
  }

  tee() {
    const [a, b] = tee(this._stream)

    return [new ReadableStream(a), new ReadableStream(b)]
  }

  pipeTo(destination) {
    return new Promise((resolve, reject) =>
      this._stream.pipe(destination._stream, (err) => {
        err ? reject(err) : resolve()
      })
    )
  }

  [Symbol.asyncIterator]() {
    return this._stream[Symbol.asyncIterator]()
  }

  _releaseLock() {
    this._reader = null
  }

  async _read(starting, pull, cb) {
    await starting

    let err = null
    try {
      await pull()
    } catch (e) {
      err = e
    }
    cb(err)
  }
}

function defaultSize() {
  return 1
}

exports.ReadableStream = ReadableStream

// https://streams.spec.whatwg.org/#countqueuingstrategy
exports.CountQueuingStrategy = class CountQueuingStrategy {
  constructor(opts = {}) {
    const { highWaterMark = 1 } = opts

    this.highWaterMark = highWaterMark
  }

  size(chunk) {
    return 1
  }
}

// https://streams.spec.whatwg.org/#bytelengthqueuingstrategy
exports.ByteLengthQueuingStrategy = class ByteLengthQueuingStrategy {
  constructor(opts = {}) {
    const { highWaterMark = 16384 } = opts

    this.highWaterMark = highWaterMark
  }

  size(chunk) {
    return chunk.byteLength
  }
}

exports.isReadableStream = function isReadableStream(value) {
  if (value instanceof ReadableStream) return true

  return (
    typeof value === 'object' &&
    value !== null &&
    value[readableKind] === ReadableStream[readableKind]
  )
}

// https://streams.spec.whatwg.org/#readablestream-errored
exports.isReadableStreamErrored = function isReadableStreamErrored(stream) {
  return getStreamError(stream._stream) !== null
}

// https://streams.spec.whatwg.org/#is-readable-stream-disturbed
exports.isReadableStreamDisturbed = function isReadableStreamDisturbed(stream) {
  return isDisturbed(stream._stream)
}

// https://streams.spec.whatwg.org/#writablestreamdefaultwriter
exports.WritableStreamDefaultWriter = class WritableStreamDefaultWriter {
  constructor(stream) {
    this._stream = stream
    this._stream._stream.once('close', onclose).once('error', onerror)

    const closed = Promise.withResolvers()

    // Avoid unhandled exceptions
    closed.promise.catch(noop)

    this._closed = closed

    function onclose() {
      closed.resolve()
    }

    function onerror(err) {
      closed.reject(err)
    }
  }

  get desiredSize() {
    const stream = this._stream._stream

    return stream._writableState.highWaterMark - stream._writableState.buffered
  }

  get closed() {
    return this._closed.promise
  }

  get ready() {
    const stream = this._stream._stream

    if (getStreamError(stream)) return Promise.reject()

    return Writable.drained(stream).then()
  }

  async write(chunk) {
    const stream = this._stream._stream

    let err = getStreamError(stream)
    if (err) return Promise.reject(err)

    stream.write(chunk)

    await Writable.drained(stream)

    err = getStreamError(stream)
    if (err) return Promise.reject(err)
  }

  releaseLock() {
    this._closed.reject(new TypeError('Writer was released'))
    this._stream._releaseLock()
    this._stream = null
  }

  close() {
    const stream = this._stream._stream

    if (stream.destroyed) return Promise.resolve()

    return new Promise((resolve) => stream.once('close', resolve).end())
  }

  abort(reason = new TypeError('Stream was aborted')) {
    const stream = this._stream._stream

    if (stream.destroyed) return Promise.resolve()

    return new Promise((resolve) => stream.once('close', resolve).destroy(reason))
  }
}

// https://streams.spec.whatwg.org/#writablestreamdefaultcontroller
exports.WritableStreamDefaultController = class WritableStreamDefaultController {
  constructor(stream) {
    this._stream = stream
  }

  error(err) {
    this._stream._stream.destroy(err)
  }
}

// https://streams.spec.whatwg.org/#writablestream
class WritableStream {
  static get [writableKind]() {
    return 0 // Compatibility version
  }

  constructor(underlyingSink = {}, queuingStrategy = {}) {
    if (isStreamx(underlyingSink)) {
      this._stream = underlyingSink
    } else {
      if (queuingStrategy === undefined) {
        queuingStrategy = new exports.CountQueuingStrategy()
      }

      const { start, write, close, abort } = underlyingSink
      const { highWaterMark = 1, size = defaultSize } = queuingStrategy

      this._stream = new Writable({ highWaterMark, byteLength: size })

      const controller = new exports.WritableStreamDefaultController(this)

      this._controller = controller

      try {
        let starting = Promise.resolve()

        if (start) starting = forwardError(start.call(this, controller), controller)

        if (write) {
          this._stream._write = this._write.bind(this, starting, write.bind(this))
        }

        if (close) {
          this._stream._destroy = this._destroy.bind(this, close.call(this))
        }

        if (abort) {
          this._stream.once('error', abort.bind(this))
        }
      } catch (err) {
        controller.error(err)
      }
    }

    this._writer = null
  }

  get [writableKind]() {
    return WritableStream[writableKind]
  }

  get locked() {
    return this._writer !== null
  }

  getWriter() {
    if (this.locked) throw new TypeError('Stream is locked')

    this._writer = new exports.WritableStreamDefaultWriter(this)

    return this._writer
  }

  abort(reason = new TypeError('Stream was aborted')) {
    if (this._stream.destroyed) return Promise.resolve()

    if (this.locked) return Promise.reject(new TypeError('Stream is locked'))

    return new Promise((resolve) => this._stream.once('close', resolve).destroy(reason))
  }

  close() {
    if (this._stream.destroyed) return Promise.resolve()

    if (this.locked) return Promise.reject(new TypeError('Stream is locked'))

    return new Promise((resolve) => this._stream.once('close', resolve).end())
  }

  _releaseLock() {
    this._writer = null
  }

  async _write(starting, write, data, cb) {
    await starting

    let err = null
    try {
      await write(data, this._controller)
    } catch (e) {
      err = e
    }
    cb(err)
  }

  async _destroy(closing, cb) {
    let err = null
    try {
      await closing
    } catch (e) {
      err = e
    }
    cb(err)
  }
}

exports.WritableStream = WritableStream

exports.isWritableStream = function isWritableStream(value) {
  if (value instanceof WritableStream) return true

  return (
    typeof value === 'object' &&
    value !== null &&
    value[writableKind] === WritableStream[writableKind]
  )
}

// https://streams.spec.whatwg.org/#transformstreamdefaultcontroller
exports.TransformStreamDefaultController = class TransformStreamDefaultController {
  constructor(stream) {
    this._stream = stream
  }

  get desiredSize() {
    const stream = this._stream._stream

    return stream._readableState.highWaterMark - stream._readableState.buffered
  }

  enqueue(data) {
    this._stream._stream.push(data)
  }

  error(err) {
    this._stream._stream.destroy(err)
  }

  terminate() {
    const stream = this._stream._stream

    stream.push(null)
    stream.destroy(new TypeError('Stream has been terminated'))
  }
}

// https://streams.spec.whatwg.org/#transformstream
class TransformStream {
  static get [transformKind]() {
    return 0 // Compatibility version
  }

  constructor(transformer = {}, writableStrategy = {}, readableStrategy = {}) {
    if (isStreamx(transformer)) {
      this._stream = transformer
    } else {
      const { start, transform, flush } = transformer

      this._stream = new Transform({ ...writableStrategy, ...readableStrategy })

      const controller = new exports.TransformStreamDefaultController(this)

      this._controller = controller

      try {
        let starting = Promise.resolve()

        if (start) starting = forwardError(start.call(this, controller), controller)

        if (transform) {
          this._stream._transform = this._transform.bind(this, starting, transform.bind(this))
        }

        if (flush) {
          this._stream._flush = this._flush.bind(this, flush.call(this, this._controller))
        }
      } catch (err) {
        controller.error(err)
      }
    }

    this._writable = new WritableStream(this._stream)
    this._readable = new ReadableStream(this._stream)
  }

  get [transformKind]() {
    return TransformStream[transformKind]
  }

  get writable() {
    return this._writable
  }

  get readable() {
    return this._readable
  }

  async _transform(starting, transform, data, cb) {
    await starting

    let err = null
    try {
      await transform(data, this._controller)
    } catch (e) {
      err = e
    }
    cb(err)
  }

  async _flush(flush, cb) {
    let err = null
    try {
      await flush
    } catch (e) {
      err = e
    }
    cb(err)
  }
}

exports.TransformStream = TransformStream

exports.isTransformStream = function isTransformStream(value) {
  if (value instanceof TransformStream) return true

  return (
    typeof value === 'object' &&
    value !== null &&
    value[transformKind] === TransformStream[transformKind]
  )
}

async function forwardError(promise, controller) {
  try {
    await promise
  } catch (err) {
    controller.error(err)
  }
}

function noop() {}
module.exports = require.addon()
const binding = require('./binding')

const t = binding.constants

class Type {
  constructor(type) {
    this._type = type
  }

  isUndefined() {
    return this._type === t.UNDEFINED
  }

  isNull() {
    return this._type === t.NULL
  }

  isBoolean() {
    return this._type === t.BOOLEAN
  }

  isNumber() {
    return (this._type & 0xff) === t.NUMBER
  }

  isInt32() {
    return (this._type & (0xff | t.INT32)) === (t.NUMBER | t.INT32)
  }

  isUint32() {
    return (this._type & (0xff | t.UINT32)) === (t.NUMBER | t.UINT32)
  }

  isString() {
    return this._type === t.STRING
  }

  isSymbol() {
    return this._type === t.SYMBOL
  }

  isObject() {
    return (this._type & 0xff) === t.OBJECT
  }

  isArray() {
    return this._type === (t.OBJECT | t.ARRAY)
  }

  isArguments() {
    return this._type === (t.OBJECT | t.ARGUMENTS)
  }

  isDate() {
    return this._type === (t.OBJECT | t.DATE)
  }

  isRegExp() {
    return this._type === (t.OBJECT | t.REGEXP)
  }

  isError() {
    return this._type === (t.OBJECT | t.ERROR)
  }

  isPromise() {
    return this._type === (t.OBJECT | t.PROMISE)
  }

  isProxy() {
    return this._type === (t.OBJECT | t.PROXY)
  }

  isGenerator() {
    return this._type === (t.OBJECT | t.GENERATOR)
  }

  isMap() {
    return this._type === (t.OBJECT | t.MAP)
  }

  isSet() {
    return this._type === (t.OBJECT | t.SET)
  }

  isWeakMap() {
    return this._type === (t.OBJECT | t.WEAK_MAP)
  }

  isWeakSet() {
    return this._type === (t.OBJECT | t.WEAK_SET)
  }

  isWeakRef() {
    return this._type === (t.OBJECT | t.WEAK_REF)
  }

  isArrayBuffer() {
    return this._type === (t.OBJECT | t.ARRAYBUFFER)
  }

  isSharedArrayBuffer() {
    return this._type === (t.OBJECT | t.SHAREDARRAYBUFFER)
  }

  isTypedArray() {
    return (this._type & 0xffff) === (t.OBJECT | t.TYPEDARRAY)
  }

  isInt8Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT8ARRAY)
  }

  isUint8Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT8ARRAY)
  }

  isUint8ClampedArray() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT8CLAMPEDARRAY)
  }

  isInt16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT16ARRAY)
  }

  isUint16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT16ARRAY)
  }

  isInt32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT32ARRAY)
  }

  isUint32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT32ARRAY)
  }

  isFloat16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT16ARRAY)
  }

  isFloat32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT32ARRAY)
  }

  isFloat64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT64ARRAY)
  }

  isBigInt64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.BIGINT64ARRAY)
  }

  isBigUint64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.BIGUINT64ARRAY)
  }

  isDataView() {
    return this._type === (t.OBJECT | t.DATAVIEW)
  }

  isModuleNamespace() {
    return this._type === (t.OBJECT | t.MODULE_NAMESPACE)
  }

  isFunction() {
    return (this._type & 0xff) === t.FUNCTION
  }

  isAsyncFunction() {
    return (
      (this._type & (0xff | t.ASYNC_FUNCTION)) ===
      (t.FUNCTION | t.ASYNC_FUNCTION)
    )
  }

  isGeneratorFunction() {
    return (
      (this._type & (0xff | t.GENERATOR_FUNCTION)) ===
      (t.FUNCTION | t.GENERATOR_FUNCTION)
    )
  }

  isExternal() {
    return this._type === t.EXTERNAL
  }

  isBigInt() {
    return this._type === t.BIGINT
  }
}

module.exports = exports = function type(value) {
  switch (typeof value) {
    case 'undefined':
      return new Type(t.UNDEFINED)
    case 'boolean':
      return new Type(t.BOOLEAN)
    case 'number':
      return new Type(
        Number.isSafeInteger(value) ? binding.type(value) : t.NUMBER
      )
    case 'string':
      return new Type(t.STRING)
    case 'symbol':
      return new Type(t.SYMBOL)
    case 'object':
      return new Type(value === null ? t.NULL : binding.type(value))
    case 'function':
      return new Type(binding.type(value))
    case 'bigint':
      return new Type(t.BIGINT)
  }
}

exports.createTag = function createTag(...components) {
  const tag = new Uint32Array(4)
  for (let i = 0; i < 4; i++) tag[i] = components[i] || 0
  return tag
}

exports.addTag = function addTag(object, tag) {
  binding.addTag(object, tag)
}

exports.checkTag = function checkTag(object, tag) {
  return binding.checkTag(object, tag)
}
{
  "name": "bare-type",
  "version": "1.1.0",
  "description": "Cross-realm type predicates for Bare",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-type.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-type/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-type#readme",
  "engines": {
    "bare": ">=1.2.0"
  },
  "devDependencies": {
    "brittle": "^3.4.0",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
module.exports = require.addon()
const path = require('bare-path')
const binding = require('./binding')
const errors = require('./lib/errors')
const URLSearchParams = require('./lib/url-search-params')

const kind = Symbol.for('bare.url.kind')

const isWindows = Bare.platform === 'win32'

class URL {
  static get [kind]() {
    return 0 // Compatibility version
  }

  constructor(input, base, opts = {}) {
    if (arguments.length === 0) throw errors.INVALID_URL()

    input = String(input)

    if (base !== undefined) base = String(base)

    this._components = new Uint32Array(8)

    this._parse(input, base, opts.throw !== false)

    if (this._href) this._params = new URLSearchParams(this.search, this)
  }

  get [kind]() {
    return URL[kind]
  }

  // https://url.spec.whatwg.org/#dom-url-href

  get href() {
    return this._href
  }

  set href(value) {
    this._update(value)

    this._params._parse(this.search)
  }

  // https://url.spec.whatwg.org/#dom-url-protocol

  get protocol() {
    return this._slice(0, this._components[0]) + ':'
  }

  set protocol(value) {
    this._update(this._replace(value.replace(/:+$/, ''), 0, this._components[0]))
  }

  // https://url.spec.whatwg.org/#dom-url-username

  get username() {
    return this._slice(this._components[0] + 3 /* :// */, this._components[1])
  }

  set username(value) {
    if (cannotHaveCredentialsOrPort(this)) {
      return
    }

    if (this.username === '') value += '@'

    this._update(this._replace(value, this._components[0] + 3 /* :// */, this._components[1]))
  }

  // https://url.spec.whatwg.org/#dom-url-password

  get password() {
    return this._href.slice(this._components[1] + 1 /* : */, this._components[2] - 1 /* @ */)
  }

  set password(value) {
    if (cannotHaveCredentialsOrPort(this)) {
      return
    }

    let start = this._components[1] + 1 /* : */
    let end = this._components[2] - 1 /* @ */

    if (this.password === '') {
      value = ':' + value
      start--
    }

    if (this.username === '') {
      value += '@'
      end++
    }

    this._update(this._replace(value, start, end))
  }

  // https://url.spec.whatwg.org/#dom-url-host

  get host() {
    return this._slice(this._components[2], this._components[5])
  }

  set host(value) {
    if (hasOpaquePath(this)) {
      return
    }

    this._update(
      this._replace(value, this._components[2], this._components[value.includes(':') ? 5 : 3])
    )
  }

  // https://url.spec.whatwg.org/#dom-url-hostname

  get hostname() {
    return this._slice(this._components[2], this._components[3])
  }

  set hostname(value) {
    if (hasOpaquePath(this)) {
      return
    }

    this._update(this._replace(value, this._components[2], this._components[3]))
  }

  // https://url.spec.whatwg.org/#dom-url-port

  get port() {
    return this._slice(this._components[3] + 1 /* : */, this._components[5])
  }

  set port(value) {
    if (cannotHaveCredentialsOrPort(this)) {
      return
    }

    let start = this._components[3] + 1 /* : */

    if (this.port === '') {
      value = ':' + value
      start--
    }

    this._update(this._replace(value, start, this._components[5]))
  }

  // https://url.spec.whatwg.org/#dom-url-pathname

  get pathname() {
    return this._slice(this._components[5], this._components[6] - 1 /* ? */)
  }

  set pathname(value) {
    if (hasOpaquePath(this)) {
      return
    }

    if (value[0] !== '/' && value[0] !== '\\') {
      value = '/' + value
    }

    this._update(this._replace(value, this._components[5], this._components[6] - 1 /* ? */))
  }

  // https://url.spec.whatwg.org/#dom-url-search

  get search() {
    return this._slice(this._components[6] - 1 /* ? */, this._components[7] - 1 /* # */)
  }

  set search(value) {
    if (value && value[0] !== '?') value = '?' + value

    this._update(
      this._replace(value, this._components[6] - 1 /* ? */, this._components[7] - 1 /* # */)
    )

    this._params._parse(this.search)
  }

  // https://url.spec.whatwg.org/#dom-url-searchparams

  get searchParams() {
    return this._params
  }

  // https://url.spec.whatwg.org/#dom-url-hash

  get hash() {
    return this._slice(this._components[7] - 1 /* # */)
  }

  set hash(value) {
    if (value && value[0] !== '#') value = '#' + value

    this._update(this._replace(value, this._components[7] - 1 /* # */))
  }

  toString() {
    return this._href
  }

  toJSON() {
    return this._href
  }

  [Symbol.for('bare.inspect')]() {
    return {
      __proto__: { constructor: URL },

      href: this.href,
      protocol: this.protocol,
      username: this.username,
      password: this.password,
      host: this.host,
      hostname: this.hostname,
      port: this.port,
      pathname: this.pathname,
      search: this.search,
      searchParams: this.searchParams,
      hash: this.hash
    }
  }

  _slice(start, end = this._href.length) {
    return this._href.slice(start, end)
  }

  _replace(replacement, start, end = this._href.length) {
    return this._slice(0, start) + replacement + this._slice(end)
  }

  _parse(input, base, shouldThrow) {
    try {
      this._href = binding.parse(
        String(input),
        base ? String(base) : null,
        this._components,
        shouldThrow
      )
    } catch (err) {
      if (err instanceof TypeError) throw err

      throw errors.INVALID_URL(`Invalid URL '${input}'`, input)
    }
  }

  _update(input) {
    try {
      this._parse(input, null, true)
    } catch (err) {
      if (err instanceof TypeError) throw err
    }
  }
}

module.exports = exports = URL

// https://url.spec.whatwg.org/#url-opaque-path
function hasOpaquePath(url) {
  return url.pathname[0] !== '/'
}

// https://url.spec.whatwg.org/#cannot-have-a-username-password-port
function cannotHaveCredentialsOrPort(url) {
  return url.hostname === '' || url.protocol === 'file:'
}

exports.URL = URL
exports.URLSearchParams = URLSearchParams

exports.errors = errors

exports.isURL = function isURL(value) {
  if (value instanceof URL) return true

  return typeof value === 'object' && value !== null && value[kind] === URL[kind]
}

exports.isURLSearchParams = URLSearchParams.isURLSearchParams

// https://url.spec.whatwg.org/#dom-url-parse
exports.parse = function parse(input, base) {
  const url = new URL(input, base, { throw: false })
  return url._href ? url : null
}

// https://url.spec.whatwg.org/#dom-url-canparse
exports.canParse = function canParse(input, base) {
  return binding.canParse(String(input), base ? String(base) : null)
}

exports.fileURLToPath = function fileURLToPath(url) {
  if (typeof url === 'string') {
    url = new URL(url)
  }

  if (url.protocol !== 'file:') {
    throw errors.INVALID_URL_SCHEME('The URL must use the file: protocol')
  }

  if (isWindows) {
    if (/%2f|%5c/i.test(url.pathname)) {
      throw errors.INVALID_FILE_URL_PATH(
        'The file: URL path must not include encoded \\ or / characters'
      )
    }
  } else {
    if (url.hostname) {
      throw errors.INVALID_FILE_URL_HOST("The file: URL host must be 'localhost' or empty")
    }

    if (/%2f/i.test(url.pathname)) {
      throw errors.INVALID_FILE_URL_PATH('The file: URL path must not include encoded / characters')
    }
  }

  if (/%00/i.test(url.pathname)) {
    throw errors.INVALID_FILE_URL_PATH('The file: URL path must not include encoded NUL characters')
  }

  const pathname = path.normalize(decodeURIComponent(url.pathname))

  if (isWindows) {
    if (url.hostname) return '\\\\' + url.hostname + pathname

    const letter = pathname.charCodeAt(1) | 0x20

    if (letter < 0x61 /* a */ || letter > 0x7a /* z */ || pathname.charCodeAt(2) !== 0x3a /* : */) {
      throw errors.INVALID_FILE_URL_PATH('The file: URL path must be absolute')
    }

    return pathname.slice(1)
  }

  return pathname
}

exports.pathToFileURL = function pathToFileURL(pathname) {
  let resolved = path.resolve(pathname)

  if (pathname[pathname.length - 1] === '/') {
    resolved += '/'
  } else if (isWindows && pathname[pathname.length - 1] === '\\') {
    resolved += '\\'
  }

  resolved = resolved
    .replaceAll('%', '%25') // Must be first
    .replaceAll('#', '%23')
    .replaceAll('?', '%3f')
    .replaceAll('\n', '%0a')
    .replaceAll('\r', '%0d')
    .replaceAll('\t', '%09')

  if (!isWindows) {
    resolved = resolved.replaceAll('\\', '%5c')
  }

  return new URL('file:' + resolved)
}

exports.format = function format(parts) {
  const { protocol, auth, host, hostname, port, pathname, search, query, hash, slashes } = parts

  let result = ''

  if (typeof protocol === 'string') {
    result += protocol

    if (protocol[protocol.length - 1] !== ':') {
      result += ':'
    }

    if (slashes === true || /https?|ftp|gopher|file/.test(protocol)) {
      result += '//'
    }
  }

  if (typeof auth === 'string') {
    if (host || hostname) result += auth + '@'
  }

  if (typeof host === 'string') result += host
  else {
    result += hostname

    if (port) result += ':' + port
  }

  if (typeof pathname === 'string' && pathname !== '') {
    if (pathname[0] !== '/') result += '/'
    result += pathname
  }

  if (typeof search === 'string') {
    if (search[0] !== '?') result += '?'
    result += search
  } else if (typeof query === 'object' && query !== null) {
    result += '?' + new URLSearchParams(query)
  }

  if (typeof hash === 'string') {
    if (hash[0] !== '#') result += '#'
    result += hash
  }

  return result
}
module.exports = class URLError extends Error {
  constructor(msg, fn = URLError, code = fn.name) {
    super(`${code}: ${msg}`)

    this.code = code

    if (Error.captureStackTrace) Error.captureStackTrace(this, fn)
  }

  get name() {
    return 'URLError'
  }

  static INVALID_URL(msg, input) {
    const err = new URLError(msg, URLError.INVALID_URL)

    err.input = input

    return err
  }

  static INVALID_URL_SCHEME(msg = 'Invalid URL') {
    return new URLError(msg, URLError.INVALID_URL_SCHEME)
  }

  static INVALID_FILE_URL_HOST(msg = 'Invalid file: URL host') {
    return new URLError(msg, URLError.INVALID_FILE_URL_HOST)
  }

  static INVALID_FILE_URL_PATH(msg = 'Invalid file: URL path') {
    return new URLError(msg, URLError.INVALID_FILE_URL_PATH)
  }
}
const kind = Symbol.for('bare.url.search-params.kind')

class URLSearchParams {
  static _urls = new WeakMap()

  static get [kind]() {
    return 0 // Compatibility version
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-urlsearchparams
  constructor(init, url = null) {
    this._params = new Map()

    if (url) URLSearchParams._urls.set(this, url)

    if (typeof init === 'string') {
      this._parse(init)
    } else if (init) {
      for (const [name, value] of typeof init[Symbol.iterator] === 'function'
        ? init
        : Object.entries(init)) {
        this.append(name, value)
      }
    }
  }

  get [kind]() {
    return URLSearchParams[kind]
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-size
  get size() {
    return this._params.length
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-append
  append(name, value = null) {
    if (value === null) return

    let list = this._params.get(name)

    if (list === undefined) {
      list = []
      this._params.set(name, list)
    }

    list.push(value)

    this._update()
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-delete
  delete(name, value = null) {
    if (value === null) this._params.delete(name)
    else {
      let list = this._params.get(name)

      if (list === undefined) return

      list = list.filter((found) => found !== value)

      if (list.length === 0) this._params.delete(name)
      else this._params.set(name, list)
    }

    this._update()
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-get
  get(name) {
    const list = this._params.get(name)

    if (list === undefined) return null

    return list[0]
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-getall
  getAll(name) {
    const list = this._params.get(name)

    if (list === undefined) return []

    return Array.from(list)
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-has
  has(name, value = null) {
    const list = this._params.get(name)

    if (list === undefined) return false

    if (value === null) return true

    return list.includes(value)
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-set
  set(name, value = null) {
    if (value === null) this._params.delete(name)
    else this._params.set(name, [value])

    this._update()
  }

  toString() {
    return this._serialize()
  }

  toJSON() {
    return [...this]
  }

  *[Symbol.iterator]() {
    for (const [name, values] of this._params) {
      for (const value of values) yield [name, value]
    }
  }

  [Symbol.for('bare.inspect')]() {
    const object = {
      __proto__: { constructor: URLSearchParams }
    }

    for (const [name, values] of this._params) {
      if (values.length === 1) object[name] = values[0]
      else object[name] = values
    }

    return object
  }

  // https://url.spec.whatwg.org/#concept-urlsearchparams-update
  _update() {
    const url = URLSearchParams._urls.get(this)

    if (url === undefined) return

    url.search = this._serialize()
  }

  // https://url.spec.whatwg.org/#concept-urlencoded-parser
  _parse(input) {
    if (input[0] === '?') input = input.substring(1)

    this._params = new Map()

    for (let sequence of input.split('&')) {
      if (sequence.length === 0) continue

      sequence = sequence.replace(/\+/g, ' ')

      let i = sequence.indexOf('=')
      if (i === -1) i = sequence.length

      const name = decodeURIComponent(sequence.substring(0, i))
      const value = decodeURIComponent(sequence.substring(i + 1, sequence.length))

      let list = this._params.get(name)

      if (list === undefined) {
        list = []
        this._params.set(name, list)
      }

      list.push(value)
    }
  }

  // https://url.spec.whatwg.org/#concept-urlencoded-serializer
  _serialize() {
    let output = ''

    for (let [name, values] of this._params) {
      name = encodeURIComponent(name)

      for (const value of values) {
        if (output) output += '&'

        output += name + '=' + encodeURIComponent(value)
      }
    }

    return output
  }
}

module.exports = exports = URLSearchParams

exports.isURLSearchParams = function isURLSearchParams(value) {
  if (value instanceof URLSearchParams) return true

  return typeof value === 'object' && value !== null && value[kind] === URLSearchParams[kind]
}
{
  "name": "bare-url",
  "version": "2.4.5",
  "description": "WHATWG URL implementation for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "global.js",
    "global.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-url.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-url/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-url",
  "dependencies": {
    "bare-path": "^3.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "cmake-bare": "^1.1.6",
    "cmake-fetch": "^1.0.0",
    "lunte": "^1.6.0",
    "prettier": "^3.3.3",
    "prettier-config-holepunch": "^2.0.0"
  }
}
const FACTOR = new Uint16Array(8)

function factor4096 (i, n) {
  while (n > 0) {
    const f = i & 4095
    FACTOR[--n] = f
    i = (i - f) / 4096
  }
  return FACTOR
}

module.exports = class BigSparseArray {
  constructor () {
    this.tiny = new TinyArray()
    this.maxLength = 4096
    this.factor = 1
  }

  set (index, val) {
    if (val !== undefined) {
      while (index >= this.maxLength) {
        this.maxLength *= 4096
        this.factor++
        if (!this.tiny.isEmptyish()) {
          const t = new TinyArray()
          t.set(0, this.tiny)
          this.tiny = t
        }
      }
    }

    const f = factor4096(index, this.factor)
    const last = this.factor - 1

    let tiny = this.tiny
    for (let i = 0; i < last; i++) {
      const next = tiny.get(f[i])
      if (next === undefined) {
        if (val === undefined) return
        tiny = tiny.set(f[i], new TinyArray())
      } else {
        tiny = next
      }
    }

    return tiny.set(f[last], val)
  }

  get (index) {
    if (index >= this.maxLength) return

    const f = factor4096(index, this.factor)
    const last = this.factor - 1

    let tiny = this.tiny
    for (let i = 0; i < last; i++) {
      tiny = tiny.get(f[i])
      if (tiny === undefined) return
    }

    return tiny.get(f[last])
  }
}

class TinyArray {
  constructor () {
    this.s = 0
    this.b = new Array(1)
    this.f = new Uint16Array(1)
  }

  isEmptyish () {
    return this.b.length === 1 && this.b[0] === undefined
  }

  get (i) {
    if (this.s === 12) return this.b[i]
    const f = i >>> this.s
    const r = i & (this.b.length - 1)
    return this.f[r] === f ? this.b[r] : undefined
  }

  set (i, v) {
    while (this.s !== 12) {
      const f = i >>> this.s
      const r = i & (this.b.length - 1)
      const o = this.b[r]

      if (o === undefined || f === this.f[r]) {
        this.b[r] = v
        this.f[r] = f
        return v
      }

      this.grow()
    }

    this.b[i] = v
    return v
  }

  grow () {
    const os = this.s
    const ob = this.b
    const of = this.f

    this.s += 4
    this.b = new Array(this.b.length << 4)
    this.f = this.s === 12 ? null : new Uint8Array(this.b.length)

    const m = this.b.length - 1

    for (let or = 0; or < ob.length; or++) {
      if (ob[or] === undefined) continue

      const i = of[or] << os | or
      const f = i >>> this.s
      const r = i & m

      this.b[r] = ob[or]
      if (this.s !== 12) this.f[r] = f
    }
  }
}
{
  "name": "big-sparse-array",
  "version": "1.0.3",
  "description": "A sparse array optimised for low memory whilst still being fast",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "brittle": "^3.1.1",
    "standard": "^16.0.3"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/big-sparse-array.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/big-sparse-array/issues"
  },
  "homepage": "https://github.com/mafintosh/big-sparse-array"
}
import { encode, encodeInto, objectToTokens, rfc8949EncodeOptions } from './lib/encode.js'
import { decode, decodeFirst, Tokeniser, tokensToObject } from './lib/decode.js'
import { Tagged } from './lib/tagged.js'
import { Token, Type } from './lib/token.js'

/**
 * Export the types that were present in the original manual cborg.d.ts
 * @typedef {import('./interface.js').TagDecodeControl} TagDecodeControl
 * @typedef {import('./interface.js').TagDecoder} TagDecoder
 * There was originally just `TypeEncoder` so don't break types by renaming or not exporting
 * @typedef {import('./interface.js').OptionalTypeEncoder} TypeEncoder
 * @typedef {import('./interface.js').DecodeOptions} DecodeOptions
 * @typedef {import('./interface.js').EncodeOptions} EncodeOptions
 */

export {
  decode,
  decodeFirst,
  Tokeniser as Tokenizer,
  tokensToObject,
  encode,
  encodeInto,
  objectToTokens,
  rfc8949EncodeOptions,
  Tagged,
  Token,
  Type
}
/* globals BigInt */

import { Token, Type } from './token.js'
import { decodeErrPrefix, assertEnoughData } from './common.js'

export const uintBoundaries = [24, 256, 65536, 4294967296, BigInt('18446744073709551616')]

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number}
 */
export function readUint8 (data, offset, options) {
  assertEnoughData(data, offset, 1)
  const value = data[offset]
  if (options.strict === true && value < uintBoundaries[0]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  return value
}

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number}
 */
export function readUint16 (data, offset, options) {
  assertEnoughData(data, offset, 2)
  const value = (data[offset] << 8) | data[offset + 1]
  if (options.strict === true && value < uintBoundaries[1]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  return value
}

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number}
 */
export function readUint32 (data, offset, options) {
  assertEnoughData(data, offset, 4)
  const value = (data[offset] * 16777216 /* 2 ** 24 */) + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]
  if (options.strict === true && value < uintBoundaries[2]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  return value
}

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number|bigint}
 */
export function readUint64 (data, offset, options) {
  // assume BigInt, convert back to Number if within safe range
  assertEnoughData(data, offset, 8)
  const hi = (data[offset] * 16777216 /* 2 ** 24 */) + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]
  const lo = (data[offset + 4] * 16777216 /* 2 ** 24 */) + (data[offset + 5] << 16) + (data[offset + 6] << 8) + data[offset + 7]
  const value = (BigInt(hi) << BigInt(32)) + BigInt(lo)
  if (options.strict === true && value < uintBoundaries[3]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  if (value <= Number.MAX_SAFE_INTEGER) {
    return Number(value)
  }
  if (options.allowBigInt === true) {
    return value
  }
  throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`)
}

/* not required thanks to quick[] list
const oneByteTokens = new Array(24).fill(0).map((v, i) => new Token(Type.uint, i, 1))
export function decodeUintCompact (data, pos, minor, options) {
  return oneByteTokens[minor]
}
*/

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint8 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint8(data, pos + 1, options), 2)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint16 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint16(data, pos + 1, options), 3)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint32 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint32(data, pos + 1, options), 5)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint64 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint64(data, pos + 1, options), 9)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeUint (writer, token) {
  return encodeUintValue(writer, 0, token.value)
}

/**
 * @param {ByteWriter} writer
 * @param {number} major
 * @param {number|bigint} uint
 */
export function encodeUintValue (writer, major, uint) {
  if (uint < uintBoundaries[0]) {
    const nuint = Number(uint)
    // pack into one byte, minor=0, additional=value
    writer.push([major | nuint])
  } else if (uint < uintBoundaries[1]) {
    const nuint = Number(uint)
    // pack into two byte, minor=0, additional=24
    writer.push([major | 24, nuint])
  } else if (uint < uintBoundaries[2]) {
    const nuint = Number(uint)
    // pack into three byte, minor=0, additional=25
    writer.push([major | 25, nuint >>> 8, nuint & 0xff])
  } else if (uint < uintBoundaries[3]) {
    const nuint = Number(uint)
    // pack into five byte, minor=0, additional=26
    writer.push([major | 26, (nuint >>> 24) & 0xff, (nuint >>> 16) & 0xff, (nuint >>> 8) & 0xff, nuint & 0xff])
  } else {
    const buint = BigInt(uint)
    if (buint < uintBoundaries[4]) {
      // pack into nine byte, minor=0, additional=27
      const set = [major | 27, 0, 0, 0, 0, 0, 0, 0]
      // simulate bitwise above 32 bits
      let lo = Number(buint & BigInt(0xffffffff))
      let hi = Number(buint >> BigInt(32) & BigInt(0xffffffff))
      set[8] = lo & 0xff
      lo = lo >> 8
      set[7] = lo & 0xff
      lo = lo >> 8
      set[6] = lo & 0xff
      lo = lo >> 8
      set[5] = lo & 0xff
      set[4] = hi & 0xff
      hi = hi >> 8
      set[3] = hi & 0xff
      hi = hi >> 8
      set[2] = hi & 0xff
      hi = hi >> 8
      set[1] = hi & 0xff
      writer.push(set)
    } else {
      throw new Error(`${decodeErrPrefix} encountered BigInt larger than allowable range`)
    }
  }
}

/**
 * @param {Token} token
 * @returns {number}
 */
encodeUint.encodedSize = function encodedSize (token) {
  return encodeUintValue.encodedSize(token.value)
}

/**
 * @param {number} uint
 * @returns {number}
 */
encodeUintValue.encodedSize = function encodedSize (uint) {
  if (uint < uintBoundaries[0]) {
    return 1
  }
  if (uint < uintBoundaries[1]) {
    return 2
  }
  if (uint < uintBoundaries[2]) {
    return 3
  }
  if (uint < uintBoundaries[3]) {
    return 5
  }
  return 9
}

/**
 * @param {Token} tok1
 * @param {Token} tok2
 * @returns {number}
 */
encodeUint.compareTokens = function compareTokens (tok1, tok2) {
  return tok1.value < tok2.value ? -1 : tok1.value > tok2.value ? 1 : 0
}
/* eslint-env es2020 */

import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import { decodeErrPrefix } from './common.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint8 (data, pos, _minor, options) {
  return new Token(Type.negint, -1 - uint.readUint8(data, pos + 1, options), 2)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint16 (data, pos, _minor, options) {
  return new Token(Type.negint, -1 - uint.readUint16(data, pos + 1, options), 3)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint32 (data, pos, _minor, options) {
  return new Token(Type.negint, -1 - uint.readUint32(data, pos + 1, options), 5)
}

const neg1b = BigInt(-1)
const pos1b = BigInt(1)

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint64 (data, pos, _minor, options) {
  const int = uint.readUint64(data, pos + 1, options)
  if (typeof int !== 'bigint') {
    const value = -1 - int
    if (value >= Number.MIN_SAFE_INTEGER) {
      return new Token(Type.negint, value, 9)
    }
  }
  if (options.allowBigInt !== true) {
    throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`)
  }
  return new Token(Type.negint, neg1b - BigInt(int), 9)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeNegint (writer, token) {
  const negint = token.value
  const unsigned = (typeof negint === 'bigint' ? (negint * neg1b - pos1b) : (negint * -1 - 1))
  uint.encodeUintValue(writer, token.type.majorEncoded, unsigned)
}

/**
 * @param {Token} token
 * @returns {number}
 */
encodeNegint.encodedSize = function encodedSize (token) {
  const negint = token.value
  const unsigned = (typeof negint === 'bigint' ? (negint * neg1b - pos1b) : (negint * -1 - 1))
  // handled by quickEncode, we shouldn't get here but it's included for completeness
  if (unsigned < uint.uintBoundaries[0]) {
    return 1
  }
  if (unsigned < uint.uintBoundaries[1]) {
    return 2
  }
  if (unsigned < uint.uintBoundaries[2]) {
    return 3
  }
  if (unsigned < uint.uintBoundaries[3]) {
    return 5
  }
  return 9
}

/**
 * @param {Token} tok1
 * @param {Token} tok2
 * @returns {number}
 */
encodeNegint.compareTokens = function compareTokens (tok1, tok2) {
  // opposite of the uint comparison since we store the uint version in bytes
  return tok1.value < tok2.value ? 1 : tok1.value > tok2.value ? -1 : 0
}
import { Token, Type } from './token.js'
import { assertEnoughData, decodeErrPrefix } from './common.js'
import * as uint from './0uint.js'
import { compare, fromString } from './byte-utils.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} prefix
 * @param {number} length
 * @returns {Token}
 */
function toToken (data, pos, prefix, length) {
  assertEnoughData(data, pos, prefix + length)
  const buf = data.slice(pos + prefix, pos + prefix + length)
  return new Token(Type.bytes, buf, prefix + length)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeBytesCompact (data, pos, minor, _options) {
  return toToken(data, pos, 1, minor)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer bytes lengths not supported`)
  }
  return toToken(data, pos, 9, l)
}

/**
 * `encodedBytes` allows for caching when we do a byte version of a string
 * for key sorting purposes
 * @param {Token} token
 * @returns {Uint8Array}
 */
function tokenBytes (token) {
  if (token.encodedBytes === undefined) {
    token.encodedBytes = Type.equals(token.type, Type.string) ? fromString(token.value) : token.value
  }
  // @ts-ignore c'mon
  return token.encodedBytes
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeBytes (writer, token) {
  const bytes = tokenBytes(token)
  uint.encodeUintValue(writer, token.type.majorEncoded, bytes.length)
  writer.push(bytes)
}

/**
 * @param {Token} token
 * @returns {number}
 */
encodeBytes.encodedSize = function encodedSize (token) {
  const bytes = tokenBytes(token)
  return uint.encodeUintValue.encodedSize(bytes.length) + bytes.length
}

/**
 * @param {Token} tok1
 * @param {Token} tok2
 * @returns {number}
 */
encodeBytes.compareTokens = function compareTokens (tok1, tok2) {
  return compareBytes(tokenBytes(tok1), tokenBytes(tok2))
}

/**
 * @param {Uint8Array} b1
 * @param {Uint8Array} b2
 * @returns {number}
 */
export function compareBytes (b1, b2) {
  return b1.length < b2.length ? -1 : b1.length > b2.length ? 1 : compare(b1, b2)
}
import { Token, Type } from './token.js'
import { assertEnoughData, decodeErrPrefix } from './common.js'
import * as uint from './0uint.js'
import { encodeBytes } from './2bytes.js'

const textDecoder = new TextDecoder()

// Threshold for ASCII fast-path vs TextDecoder. Short ASCII strings (common for
// map keys) are faster to decode with a simple loop than TextDecoder overhead.
const ASCII_THRESHOLD = 32

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * Decode UTF-8 bytes to string. For short ASCII strings (common case for map keys),
 * a simple loop is faster than TextDecoder.
 * @param {Uint8Array} bytes
 * @param {number} start
 * @param {number} end
 * @returns {string}
 */
function toStr (bytes, start, end) {
  const len = end - start
  if (len < ASCII_THRESHOLD) {
    let str = ''
    for (let i = start; i < end; i++) {
      const c = bytes[i]
      if (c & 0x80) { // non-ASCII, fall back to TextDecoder
        return textDecoder.decode(bytes.subarray(start, end))
      }
      str += String.fromCharCode(c)
    }
    return str
  }
  return textDecoder.decode(bytes.subarray(start, end))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} prefix
 * @param {number} length
 * @param {DecodeOptions} options
 * @returns {Token}
 */
function toToken (data, pos, prefix, length, options) {
  const totLength = prefix + length
  assertEnoughData(data, pos, totLength)
  const tok = new Token(Type.string, toStr(data, pos + prefix, pos + totLength), totLength)
  if (options.retainStringBytes === true) {
    tok.byteValue = data.slice(pos + prefix, pos + totLength)
  }
  return tok
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeStringCompact (data, pos, minor, options) {
  return toToken(data, pos, 1, minor, options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options), options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options), options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options), options)
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer string lengths not supported`)
  }
  return toToken(data, pos, 9, l, options)
}

export const encodeString = encodeBytes
import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import { decodeErrPrefix } from './common.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} prefix
 * @param {number} length
 * @returns {Token}
 */
function toToken (_data, _pos, prefix, length) {
  return new Token(Type.array, length, prefix)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeArrayCompact (data, pos, minor, _options) {
  return toToken(data, pos, 1, minor)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer array lengths not supported`)
  }
  return toToken(data, pos, 9, l)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArrayIndefinite (data, pos, _minor, options) {
  if (options.allowIndefinite === false) {
    throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)
  }
  return toToken(data, pos, 1, Infinity)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeArray (writer, token) {
  uint.encodeUintValue(writer, Type.array.majorEncoded, token.value)
}

// using an array as a map key, are you sure about this? we can only sort
// by map length here, it's up to the encoder to decide to look deeper
encodeArray.compareTokens = uint.encodeUint.compareTokens

/**
 * @param {Token} token
 * @returns {number}
 */
encodeArray.encodedSize = function encodedSize (token) {
  return uint.encodeUintValue.encodedSize(token.value)
}
import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import { decodeErrPrefix } from './common.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} prefix
 * @param {number} length
 * @returns {Token}
 */
function toToken (_data, _pos, prefix, length) {
  return new Token(Type.map, length, prefix)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeMapCompact (data, pos, minor, _options) {
  return toToken(data, pos, 1, minor)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer map lengths not supported`)
  }
  return toToken(data, pos, 9, l)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMapIndefinite (data, pos, _minor, options) {
  if (options.allowIndefinite === false) {
    throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)
  }
  return toToken(data, pos, 1, Infinity)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeMap (writer, token) {
  uint.encodeUintValue(writer, Type.map.majorEncoded, token.value)
}

// using a map as a map key, are you sure about this? we can only sort
// by map length here, it's up to the encoder to decide to look deeper
encodeMap.compareTokens = uint.encodeUint.compareTokens

/**
 * @param {Token} token
 * @returns {number}
 */
encodeMap.encodedSize = function encodedSize (token) {
  return uint.encodeUintValue.encodedSize(token.value)
}
import { Token, Type } from './token.js'
import * as uint from './0uint.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeTagCompact (_data, _pos, minor, _options) {
  return new Token(Type.tag, minor, 1)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag8 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint8(data, pos + 1, options), 2)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag16 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint16(data, pos + 1, options), 3)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag32 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint32(data, pos + 1, options), 5)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag64 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint64(data, pos + 1, options), 9)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeTag (writer, token) {
  uint.encodeUintValue(writer, Type.tag.majorEncoded, token.value)
}

encodeTag.compareTokens = uint.encodeUint.compareTokens

/**
 * @param {Token} token
 * @returns {number}
 */
encodeTag.encodedSize = function encodedSize (token) {
  return uint.encodeUintValue.encodedSize(token.value)
}
// TODO: shift some of the bytes logic to bytes-utils so we can use Buffer
// where possible

import { Token, Type } from './token.js'
import { decodeErrPrefix } from './common.js'
import { encodeUint } from './0uint.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 * @typedef {import('../interface.js').EncodeOptions} EncodeOptions
 */

export const MINOR_FALSE = 20
export const MINOR_TRUE = 21
export const MINOR_NULL = 22
export const MINOR_UNDEFINED = 23

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUndefined (_data, _pos, _minor, options) {
  if (options.allowUndefined === false) {
    throw new Error(`${decodeErrPrefix} undefined values are not supported`)
  } else if (options.coerceUndefinedToNull === true) {
    return new Token(Type.null, null, 1)
  }
  return new Token(Type.undefined, undefined, 1)
}

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBreak (_data, _pos, _minor, options) {
  if (options.allowIndefinite === false) {
    throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)
  }
  return new Token(Type.break, undefined, 1)
}

/**
 * @param {number} value
 * @param {number} bytes
 * @param {DecodeOptions} options
 * @returns {Token}
 */
function createToken (value, bytes, options) {
  if (options) {
    if (options.allowNaN === false && Number.isNaN(value)) {
      throw new Error(`${decodeErrPrefix} NaN values are not supported`)
    }
    if (options.allowInfinity === false && (value === Infinity || value === -Infinity)) {
      throw new Error(`${decodeErrPrefix} Infinity values are not supported`)
    }
  }
  return new Token(Type.float, value, bytes)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeFloat16 (data, pos, _minor, options) {
  return createToken(readFloat16(data, pos + 1), 3, options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeFloat32 (data, pos, _minor, options) {
  return createToken(readFloat32(data, pos + 1), 5, options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeFloat64 (data, pos, _minor, options) {
  return createToken(readFloat64(data, pos + 1), 9, options)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 * @param {EncodeOptions} options
 */
export function encodeFloat (writer, token, options) {
  const float = token.value

  if (float === false) {
    writer.push([Type.float.majorEncoded | MINOR_FALSE])
  } else if (float === true) {
    writer.push([Type.float.majorEncoded | MINOR_TRUE])
  } else if (float === null) {
    writer.push([Type.float.majorEncoded | MINOR_NULL])
  } else if (float === undefined) {
    writer.push([Type.float.majorEncoded | MINOR_UNDEFINED])
  } else {
    let decoded
    let success = false
    if (!options || options.float64 !== true) {
      encodeFloat16(float)
      decoded = readFloat16(ui8a, 1)
      if (float === decoded || Number.isNaN(float)) {
        ui8a[0] = 0xf9
        writer.push(ui8a.slice(0, 3))
        success = true
      } else {
        encodeFloat32(float)
        decoded = readFloat32(ui8a, 1)
        if (float === decoded) {
          ui8a[0] = 0xfa
          writer.push(ui8a.slice(0, 5))
          success = true
        }
      }
    }
    if (!success) {
      encodeFloat64(float)
      decoded = readFloat64(ui8a, 1)
      ui8a[0] = 0xfb
      writer.push(ui8a.slice(0, 9))
    }
  }
}

/**
 * @param {Token} token
 * @param {EncodeOptions} options
 * @returns {number}
 */
encodeFloat.encodedSize = function encodedSize (token, options) {
  const float = token.value

  if (float === false || float === true || float === null || float === undefined) {
    return 1
  }

  if (!options || options.float64 !== true) {
    encodeFloat16(float)
    let decoded = readFloat16(ui8a, 1)
    if (float === decoded || Number.isNaN(float)) {
      return 3
    }
    encodeFloat32(float)
    decoded = readFloat32(ui8a, 1)
    if (float === decoded) {
      return 5
    }
  }
  return 9
}

const buffer = new ArrayBuffer(9)
const dataView = new DataView(buffer, 1)
const ui8a = new Uint8Array(buffer, 0)

/**
 * @param {number} inp
 */
function encodeFloat16 (inp) {
  if (inp === Infinity) {
    dataView.setUint16(0, 0x7c00, false)
  } else if (inp === -Infinity) {
    dataView.setUint16(0, 0xfc00, false)
  } else if (Number.isNaN(inp)) {
    dataView.setUint16(0, 0x7e00, false)
  } else {
    dataView.setFloat32(0, inp)
    const valu32 = dataView.getUint32(0)
    const exponent = (valu32 & 0x7f800000) >> 23
    const mantissa = valu32 & 0x7fffff

    if (exponent === 0xff) {
      // too big, Infinity, but this should be hard (impossible?) to trigger
      dataView.setUint16(0, 0x7c00, false)
    } else if (exponent === 0x00) {
      // 0.0, -0.0 and subnormals, shouldn't be possible to get here because 0.0 should be counted as an int
      // Use valu32 for sign bit since bitwise ops on floats lose -0 sign
      dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | (mantissa >> 13), false)
    } else { // standard numbers
      // chunks of logic here borrowed from https://github.com/PJK/libcbor/blob/c78f437182533e3efa8d963ff4b945bb635c2284/src/cbor/encoding.c#L127
      const logicalExponent = exponent - 127
      // Now we know that 2^exponent <= 0 logically
      if (logicalExponent < -24) {
        /* No unambiguous representation exists, this float is not a half float
          and is too small to be represented using a half, round off to zero.
          Consistent with the reference implementation. */
        // should be difficult (impossible?) to get here in JS
        dataView.setUint16(0, 0)
      } else if (logicalExponent < -14) {
        /* Offset the remaining decimal places by shifting the significand, the
          value is lost. This is an implementation decision that works around the
          absence of standard half-float in the language. */
        dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | /* sign bit */ (1 << (24 + logicalExponent)), false)
      } else {
        dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | ((logicalExponent + 15) << 10) | (mantissa >> 13), false)
      }
    }
  }
}

/**
 * @param {Uint8Array} ui8a
 * @param {number} pos
 * @returns {number}
 */
function readFloat16 (ui8a, pos) {
  if (ui8a.length - pos < 2) {
    throw new Error(`${decodeErrPrefix} not enough data for float16`)
  }

  const half = (ui8a[pos] << 8) + ui8a[pos + 1]
  if (half === 0x7c00) {
    return Infinity
  }
  if (half === 0xfc00) {
    return -Infinity
  }
  if (half === 0x7e00) {
    return NaN
  }
  const exp = (half >> 10) & 0x1f
  const mant = half & 0x3ff
  let val
  if (exp === 0) {
    val = mant * (2 ** -24)
  } else if (exp !== 31) {
    val = (mant + 1024) * (2 ** (exp - 25))
  } else {
    // may not be possible to get here
    val = mant === 0 ? Infinity : NaN
  }
  return (half & 0x8000) ? -val : val
}

/**
 * @param {number} inp
 */
function encodeFloat32 (inp) {
  dataView.setFloat32(0, inp, false)
}

/**
 * @param {Uint8Array} ui8a
 * @param {number} pos
 * @returns {number}
 */
function readFloat32 (ui8a, pos) {
  if (ui8a.length - pos < 4) {
    throw new Error(`${decodeErrPrefix} not enough data for float32`)
  }
  const offset = (ui8a.byteOffset || 0) + pos
  return new DataView(ui8a.buffer, offset, 4).getFloat32(0, false)
}

/**
 * @param {number} inp
 */
function encodeFloat64 (inp) {
  dataView.setFloat64(0, inp, false)
}

/**
 * @param {Uint8Array} ui8a
 * @param {number} pos
 * @returns {number}
 */
function readFloat64 (ui8a, pos) {
  if (ui8a.length - pos < 8) {
    throw new Error(`${decodeErrPrefix} not enough data for float64`)
  }
  const offset = (ui8a.byteOffset || 0) + pos
  return new DataView(ui8a.buffer, offset, 8).getFloat64(0, false)
}

/**
 * @param {Token} _tok1
 * @param {Token} _tok2
 * @returns {number}
 */
encodeFloat.compareTokens = encodeUint.compareTokens
/*
encodeFloat.compareTokens = function compareTokens (_tok1, _tok2) {
  return _tok1
  throw new Error(`${encodeErrPrefix} cannot use floats as map keys`)
}
*/
/**
 * Bl is a list of byte chunks, similar to https://github.com/rvagg/bl but for
 * writing rather than reading.
 * A Bl object accepts set() operations for individual bytes and copyTo() for
 * inserting byte arrays. These write operations don't automatically increment
 * the internal cursor so its "length" won't be changed. Instead, increment()
 * must be called to extend its length to cover the inserted data.
 * The toBytes() call will convert all internal memory to a single Uint8Array of
 * the correct length, truncating any data that is stored but hasn't been
 * included by an increment().
 * get() can retrieve a single byte.
 * All operations (except toBytes()) take an "offset" argument that will perform
 * the write at the offset _from the current cursor_. For most operations this
 * will be `0` to write at the current cursor position but it can be ahead of
 * the current cursor. Negative offsets probably work but are untested.
 */

// TODO: ipjs doesn't support this, only for test files: https://github.com/mikeal/ipjs/blob/master/src/package/testFile.js#L39
import { alloc, concat, slice } from './byte-utils.js'

// the ts-ignores in this file are almost all for the `Uint8Array|number[]` duality that exists
// for perf reasons. Consider better approaches to this or removing it entirely, it is quite
// risky because of some assumptions about small chunks === number[] and everything else === Uint8Array.

const defaultChunkSize = 256

export class Bl {
  /**
   * @param {number} [chunkSize]
   */
  constructor (chunkSize = defaultChunkSize) {
    this.chunkSize = chunkSize
    /** @type {number} */
    this.cursor = 0
    /** @type {number} */
    this.maxCursor = -1
    /** @type {(Uint8Array|number[])[]} */
    this.chunks = []
    // keep the first chunk around if we can to save allocations for future encodes
    /** @type {Uint8Array|number[]|null} */
    this._initReuseChunk = null
  }

  reset () {
    this.cursor = 0
    this.maxCursor = -1
    if (this.chunks.length) {
      this.chunks = []
    }
    if (this._initReuseChunk !== null) {
      this.chunks.push(this._initReuseChunk)
      this.maxCursor = this._initReuseChunk.length - 1
    }
  }

  /**
   * @param {Uint8Array|number[]} bytes
   */
  push (bytes) {
    let topChunk = this.chunks[this.chunks.length - 1]
    const newMax = this.cursor + bytes.length
    if (newMax <= this.maxCursor + 1) {
      // we have at least one chunk and we can fit these bytes into that chunk
      const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1
      // @ts-ignore
      topChunk.set(bytes, chunkPos)
    } else {
      // can't fit it in
      if (topChunk) {
        // trip the last chunk to `cursor` if we need to
        const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1
        if (chunkPos < topChunk.length) {
          // @ts-ignore
          this.chunks[this.chunks.length - 1] = topChunk.subarray(0, chunkPos)
          this.maxCursor = this.cursor - 1
        }
      }
      if (bytes.length < 64 && bytes.length < this.chunkSize) {
        // make a new chunk and copy the new one into it
        topChunk = alloc(this.chunkSize)
        this.chunks.push(topChunk)
        this.maxCursor += topChunk.length
        if (this._initReuseChunk === null) {
          this._initReuseChunk = topChunk
        }
        // @ts-ignore
        topChunk.set(bytes, 0)
      } else {
        // push the new bytes in as its own chunk
        this.chunks.push(bytes)
        this.maxCursor += bytes.length
      }
    }
    this.cursor += bytes.length
  }

  /**
   * @param {boolean} [reset]
   * @returns {Uint8Array}
   */
  toBytes (reset = false) {
    let byts
    if (this.chunks.length === 1) {
      const chunk = this.chunks[0]
      if (reset && this.cursor > chunk.length / 2) {
        // @ts-ignore
        byts = this.cursor === chunk.length ? chunk : chunk.subarray(0, this.cursor)
        this._initReuseChunk = null
        this.chunks = []
      } else {
        // @ts-ignore
        byts = slice(chunk, 0, this.cursor)
      }
    } else {
      // @ts-ignore
      byts = concat(this.chunks, this.cursor)
    }
    if (reset) {
      this.reset()
    }
    return byts
  }
}

/**
 * U8Bl is a buffer list that writes directly to a user-provided Uint8Array.
 * It provides the same interface as Bl but writes to a fixed destination.
 */
export class U8Bl {
  /**
   * @param {Uint8Array} dest
   */
  constructor (dest) {
    this.dest = dest
    /** @type {number} */
    this.cursor = 0
    // chunks is for interface compatibility with Bl - encode.js checks chunks.length
    // as a sanity check for pre-calculated sizes. For U8Bl this is always [dest].
    /** @type {Uint8Array[]} */
    this.chunks = [dest]
  }

  reset () {
    this.cursor = 0
  }

  /**
   * @param {Uint8Array|number[]} bytes
   */
  push (bytes) {
    if (this.cursor + bytes.length > this.dest.length) {
      throw new Error('write out of bounds, destination buffer is too small')
    }
    this.dest.set(bytes, this.cursor)
    this.cursor += bytes.length
  }

  /**
   * @param {boolean} [reset]
   * @returns {Uint8Array}
   */
  toBytes (reset = false) {
    const byts = this.dest.subarray(0, this.cursor)
    if (reset) {
      this.reset()
    }
    return byts
  }
}
// Use Uint8Array directly in the browser, use Buffer in Node.js but don't
// speak its name directly to avoid bundlers pulling in the `Buffer` polyfill

// @ts-ignore
export const useBuffer = globalThis.process &&
  // @ts-ignore
  !globalThis.process.browser &&
  // @ts-ignore
  globalThis.Buffer &&
  // @ts-ignore
  typeof globalThis.Buffer.isBuffer === 'function'

const textEncoder = new TextEncoder()

/**
 * @param {Uint8Array} buf
 * @returns {boolean}
 */
function isBuffer (buf) {
  // @ts-ignore
  return useBuffer && globalThis.Buffer.isBuffer(buf)
}

/**
 * @param {Uint8Array|number[]} buf
 * @returns {Uint8Array}
 */
export function asU8A (buf) {
  if (!(buf instanceof Uint8Array)) {
    return Uint8Array.from(buf)
  }
  return isBuffer(buf) ? new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength) : buf
}

// Threshold for manual UTF-8 encoding vs native methods.
// Node.js Buffer.from: crossover ~24 chars
// Browser TextEncoder: crossover ~200 chars
const FROM_STRING_THRESHOLD_BUFFER = 24
const FROM_STRING_THRESHOLD_TEXTENCODER = 200

export const fromString = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {string} string
     */
    (string) => {
      return string.length >= FROM_STRING_THRESHOLD_BUFFER
        ? // eslint-disable-line operator-linebreak
      // @ts-ignore
        globalThis.Buffer.from(string)
        : utf8ToBytes(string)
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {string} string
     */
    (string) => {
      return string.length >= FROM_STRING_THRESHOLD_TEXTENCODER ? textEncoder.encode(string) : utf8ToBytes(string)
    }

/**
 * Buffer variant not fast enough for what we need
 * @param {number[]} arr
 * @returns {Uint8Array}
 */
export const fromArray = (arr) => {
  return Uint8Array.from(arr)
}

export const slice = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} bytes
     * @param {number} start
     * @param {number} end
     */
    // Buffer.slice() returns a view, not a copy, so we need special handling
    (bytes, start, end) => {
      if (isBuffer(bytes)) {
        return new Uint8Array(bytes.subarray(start, end))
      }
      return bytes.slice(start, end)
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} bytes
     * @param {number} start
     * @param {number} end
     */
    (bytes, start, end) => {
      return bytes.slice(start, end)
    }

export const concat = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array[]} chunks
     * @param {number} length
     * @returns {Uint8Array}
     */
    (chunks, length) => {
      // might get a stray plain Array here
      chunks = chunks.map((c) => c instanceof Uint8Array
        ? c
        : // eslint-disable-line operator-linebreak
        // @ts-ignore
        globalThis.Buffer.from(c))
      // @ts-ignore
      return asU8A(globalThis.Buffer.concat(chunks, length))
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array[]} chunks
     * @param {number} length
     * @returns {Uint8Array}
     */
    (chunks, length) => {
      const out = new Uint8Array(length)
      let off = 0
      for (let b of chunks) {
        if (off + b.length > out.length) {
          // final chunk that's bigger than we need
          b = b.subarray(0, out.length - off)
        }
        out.set(b, off)
        off += b.length
      }
      return out
    }

export const alloc = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {number} size
     * @returns {Uint8Array}
     */
    (size) => {
      // we always write over the contents we expose so this should be safe
      // @ts-ignore
      return globalThis.Buffer.allocUnsafe(size)
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {number} size
     * @returns {Uint8Array}
     */
    (size) => {
      return new Uint8Array(size)
    }

export const toHex = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} d
     * @returns {string}
     */
    (d) => {
      if (typeof d === 'string') {
        return d
      }
      // @ts-ignore
      return globalThis.Buffer.from(toBytes(d)).toString('hex')
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} d
     * @returns {string}
     */
    (d) => {
      if (typeof d === 'string') {
        return d
      }
      // @ts-ignore not smart enough to figure this out
      return Array.prototype.reduce.call(toBytes(d), (p, c) => `${p}${c.toString(16).padStart(2, '0')}`, '')
    }

export const fromHex = useBuffer
  ? // eslint-disable-line operator-linebreak
  /**
   * @param {string|Uint8Array} hex
   * @returns {Uint8Array}
   */
    (hex) => {
      if (hex instanceof Uint8Array) {
        return hex
      }
      // @ts-ignore
      return globalThis.Buffer.from(hex, 'hex')
    }
  : // eslint-disable-line operator-linebreak
  /**
   * @param {string|Uint8Array} hex
   * @returns {Uint8Array}
   */
    (hex) => {
      if (hex instanceof Uint8Array) {
        return hex
      }
      if (!hex.length) {
        return new Uint8Array(0)
      }
      return new Uint8Array(hex.split('')
        .map((/** @type {string} */ c, /** @type {number} */ i, /** @type {string[]} */ d) => i % 2 === 0 ? `0x${c}${d[i + 1]}` : '')
        .filter(Boolean)
        .map((/** @type {string} */ e) => parseInt(e, 16)))
    }

/**
 * @param {Uint8Array|ArrayBuffer|ArrayBufferView} obj
 * @returns {Uint8Array}
 */
function toBytes (obj) {
  if (obj instanceof Uint8Array && obj.constructor.name === 'Uint8Array') {
    return obj
  }
  if (obj instanceof ArrayBuffer) {
    return new Uint8Array(obj)
  }
  if (ArrayBuffer.isView(obj)) {
    return new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength)
  }
  throw new Error('Unknown type, must be binary type')
}

/**
 * @param {Uint8Array} b1
 * @param {Uint8Array} b2
 * @returns {number}
 */
export function compare (b1, b2) {
  if (isBuffer(b1) && isBuffer(b2)) {
    // probably not possible to get here in the current API
    // @ts-ignore Buffer
    return b1.compare(b2)
  }
  for (let i = 0; i < b1.length; i++) {
    if (b1[i] === b2[i]) {
      continue
    }
    return b1[i] < b2[i] ? -1 : 1
  }
  return 0
}

// The below code is taken from https://github.com/google/closure-library/blob/8598d87242af59aac233270742c8984e2b2bdbe0/closure/goog/crypt/crypt.js#L117-L143
// Licensed Apache-2.0.

/**
 * @param {string} str
 * @returns {number[]}
 */
function utf8ToBytes (str) {
  const out = []
  let p = 0
  for (let i = 0; i < str.length; i++) {
    let c = str.charCodeAt(i)
    if (c < 128) {
      out[p++] = c
    } else if (c < 2048) {
      out[p++] = (c >> 6) | 192
      out[p++] = (c & 63) | 128
    } else if (
      ((c & 0xFC00) === 0xD800) && (i + 1) < str.length &&
      ((str.charCodeAt(i + 1) & 0xFC00) === 0xDC00)) {
      // Surrogate Pair
      c = 0x10000 + ((c & 0x03FF) << 10) + (str.charCodeAt(++i) & 0x03FF)
      out[p++] = (c >> 18) | 240
      out[p++] = ((c >> 12) & 63) | 128
      out[p++] = ((c >> 6) & 63) | 128
      out[p++] = (c & 63) | 128
    } else {
      if ((c >= 0xD800) && (c <= 0xDFFF)) {
        c = 0xFFFD // Unpaired Surrogate
      }
      out[p++] = (c >> 12) | 224
      out[p++] = ((c >> 6) & 63) | 128
      out[p++] = (c & 63) | 128
    }
  }
  return out
}

// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
const MAX_ARGUMENTS_LENGTH = 0x1000

/**
 * @param {number[]} codePoints
 * @returns {string}
 */
export function decodeCodePointsArray (codePoints) {
  const len = codePoints.length
  if (len <= MAX_ARGUMENTS_LENGTH) {
    return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  }
  // Decode in chunks to avoid "call stack size exceeded".
  let res = ''
  let i = 0
  while (i < len) {
    res += String.fromCharCode.apply(
      String,
      codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
    )
  }
  return res
}
const decodeErrPrefix = 'CBOR decode error:'
const encodeErrPrefix = 'CBOR encode error:'

const uintMinorPrefixBytes = []
uintMinorPrefixBytes[23] = 1
uintMinorPrefixBytes[24] = 2
uintMinorPrefixBytes[25] = 3
uintMinorPrefixBytes[26] = 5
uintMinorPrefixBytes[27] = 9

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} need
 */
function assertEnoughData (data, pos, need) {
  if (data.length - pos < need) {
    throw new Error(`${decodeErrPrefix} not enough data for type`)
  }
}

export {
  decodeErrPrefix,
  encodeErrPrefix,
  uintMinorPrefixBytes,
  assertEnoughData
}
import { decodeErrPrefix } from './common.js'
import { Type } from './token.js'
import { jump, quick } from './jump.js'
import { asU8A } from './byte-utils.js'

/**
 * @typedef {import('./token.js').Token} Token
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 * @typedef {import('../interface.js').DecodeTokenizer} DecodeTokenizer
 * @typedef {import('../interface.js').TagDecodeControl} TagDecodeControl
 */

const defaultDecodeOptions = {
  strict: false,
  allowIndefinite: true,
  allowUndefined: true,
  allowBigInt: true
}

/**
 * @implements {DecodeTokenizer}
 */
class Tokeniser {
  /**
   * @param {Uint8Array} data
   * @param {DecodeOptions} options
   */
  constructor (data, options = {}) {
    this._pos = 0
    this.data = data
    this.options = options
  }

  pos () {
    return this._pos
  }

  done () {
    return this._pos >= this.data.length
  }

  next () {
    const byt = this.data[this._pos]
    let token = quick[byt]
    if (token === undefined) {
      const decoder = jump[byt]
      // if we're here then there's something wrong with our jump or quick lists!
      if (!decoder) {
        throw new Error(`${decodeErrPrefix} no decoder for major type ${byt >>> 5} (byte 0x${byt.toString(16).padStart(2, '0')})`)
      }
      const minor = byt & 31
      token = decoder(this.data, this._pos, minor, this.options)
    }
    // @ts-ignore we get to assume encodedLength is set (crossing fingers slightly)
    this._pos += token.encodedLength
    return token
  }
}

const DONE = Symbol.for('DONE')
const BREAK = Symbol.for('BREAK')

/**
 * @param {Token} token
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {any|BREAK|DONE}
 */
function tokenToArray (token, tokeniser, options) {
  const arr = []
  for (let i = 0; i < token.value; i++) {
    const value = tokensToObject(tokeniser, options)
    if (value === BREAK) {
      if (token.value === Infinity) {
        // normal end to indefinite length array
        break
      }
      throw new Error(`${decodeErrPrefix} got unexpected break to lengthed array`)
    }
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} found array but not enough entries (got ${i}, expected ${token.value})`)
    }
    arr[i] = value
  }
  return arr
}

/**
 * @param {Token} token
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {any|BREAK|DONE}
 */
function tokenToMap (token, tokeniser, options) {
  const useMaps = options.useMaps === true
  const rejectDuplicateMapKeys = options.rejectDuplicateMapKeys === true
  const obj = useMaps ? undefined : {}
  const m = useMaps ? new Map() : undefined
  for (let i = 0; i < token.value; i++) {
    const key = tokensToObject(tokeniser, options)
    if (key === BREAK) {
      if (token.value === Infinity) {
        // normal end to indefinite length map
        break
      }
      throw new Error(`${decodeErrPrefix} got unexpected break to lengthed map`)
    }
    if (key === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no key], expected ${token.value})`)
    }
    if (!useMaps && typeof key !== 'string') {
      throw new Error(`${decodeErrPrefix} non-string keys not supported (got ${typeof key})`)
    }
    if (rejectDuplicateMapKeys) {
      // @ts-ignore
      if ((useMaps && m.has(key)) || (!useMaps && Object.hasOwn(obj, key))) {
        throw new Error(`${decodeErrPrefix} found repeat map key "${key}"`)
      }
    }
    const value = tokensToObject(tokeniser, options)
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no value], expected ${token.value})`)
    }
    if (useMaps) {
      // @ts-ignore TODO reconsider this .. maybe needs to be strict about key types
      m.set(key, value)
    } else {
      // @ts-ignore TODO reconsider this .. maybe needs to be strict about key types
      obj[key] = value
    }
  }
  // @ts-ignore c'mon man
  return useMaps ? m : obj
}

/**
 * Generator that yields [key, value] entries from a CBOR map token.
 * Used by tag decoders that need to preserve key types (e.g., Tag 259 Map).
 * @param {Token} token - The map token
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {Generator<[any, any], void, unknown>}
 */
function * tokenToMapEntries (token, tokeniser, options) {
  for (let i = 0; i < token.value; i++) {
    const key = tokensToObject(tokeniser, options)
    if (key === BREAK) {
      if (token.value === Infinity) {
        // normal end to indefinite length map
        break
      }
      throw new Error(`${decodeErrPrefix} got unexpected break to lengthed map`)
    }
    if (key === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no key], expected ${token.value})`)
    }
    const value = tokensToObject(tokeniser, options)
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no value], expected ${token.value})`)
    }
    yield [key, value]
  }
}

/**
 * Creates a TagDecodeControl object for tag decoders.
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {TagDecodeControl}
 */
function createTagDecodeControl (tokeniser, options) {
  let called = false

  /**
   * @type {TagDecodeControl}
   */
  const decode = function () {
    if (called) {
      throw new Error(`${decodeErrPrefix} tag decode() may only be called once`)
    }
    called = true
    const value = tokensToObject(tokeniser, options)
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} tag content missing`)
    }
    if (value === BREAK) {
      throw new Error(`${decodeErrPrefix} got unexpected break in tag content`)
    }
    return value
  }

  decode.entries = function () {
    if (called) {
      throw new Error(`${decodeErrPrefix} tag decode() may only be called once`)
    }
    called = true

    // Get the next token and ensure it's a map
    const token = tokeniser.next()
    if (!Type.equals(token.type, Type.map)) {
      throw new Error(`${decodeErrPrefix} entries() requires map content, got ${token.type.name}`)
    }

    // Collect all entries into an array (ensures full content consumption)
    const entries = []
    for (const entry of tokenToMapEntries(token, tokeniser, options)) {
      entries.push(entry)
    }
    return entries
  }

  // For internal tracking
  Object.defineProperty(decode, '_called', {
    get () { return called },
    enumerable: false
  })

  return decode
}

/**
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {any|BREAK|DONE}
 */
function tokensToObject (tokeniser, options) {
  // should we support array as an argument?
  // check for tokenIter[Symbol.iterator] and replace tokenIter with what that returns?
  if (tokeniser.done()) {
    return DONE
  }

  const token = tokeniser.next()

  if (Type.equals(token.type, Type.break)) {
    return BREAK
  }

  if (token.type.terminal) {
    return token.value
  }

  if (Type.equals(token.type, Type.array)) {
    return tokenToArray(token, tokeniser, options)
  }

  if (Type.equals(token.type, Type.map)) {
    return tokenToMap(token, tokeniser, options)
  }

  if (Type.equals(token.type, Type.tag)) {
    if (options.tags && typeof options.tags[token.value] === 'function') {
      const decodeControl = createTagDecodeControl(tokeniser, options)
      const result = options.tags[token.value](decodeControl)
      if (!decodeControl._called) {
        throw new Error(`${decodeErrPrefix} tag decoder must call decode() or entries()`)
      }
      return result
    }
    throw new Error(`${decodeErrPrefix} tag not supported (${token.value})`)
  }
  throw new Error('unsupported')
}

/**
 * @param {Uint8Array} data
 * @param {DecodeOptions} [options]
 * @returns {[any, Uint8Array]}
 */
function decodeFirst (data, options) {
  if (!(data instanceof Uint8Array)) {
    throw new Error(`${decodeErrPrefix} data to decode must be a Uint8Array`)
  }
  options = Object.assign({}, defaultDecodeOptions, options)
  // Convert Buffer to plain Uint8Array for faster slicing in decode path
  const u8aData = asU8A(data)
  const tokeniser = options.tokenizer || new Tokeniser(u8aData, options)
  const decoded = tokensToObject(tokeniser, options)
  if (decoded === DONE) {
    throw new Error(`${decodeErrPrefix} did not find any content to decode`)
  }
  if (decoded === BREAK) {
    throw new Error(`${decodeErrPrefix} got unexpected break`)
  }
  return [decoded, data.subarray(tokeniser.pos())]
}

/**
 * @param {Uint8Array} data
 * @param {DecodeOptions} [options]
 * @returns {any}
 */
function decode (data, options) {
  const [decoded, remainder] = decodeFirst(data, options)
  if (remainder.length > 0) {
    throw new Error(`${decodeErrPrefix} too many terminals, data makes no sense`)
  }
  return decoded
}

export { Tokeniser, tokensToObject, decode, decodeFirst }
import { is } from './is.js'
import { Token, Type } from './token.js'
import { Bl, U8Bl } from './bl.js'
import { encodeErrPrefix } from './common.js'
import { quickEncodeToken } from './jump.js'
import { asU8A, compare, fromString } from './byte-utils.js'

import { encodeUint, encodeUintValue } from './0uint.js'
import { encodeNegint } from './1negint.js'
import { encodeBytes } from './2bytes.js'
import { encodeString } from './3string.js'
import { encodeArray } from './4array.js'
import { encodeMap } from './5map.js'
import { encodeTag } from './6tag.js'
import { encodeFloat, MINOR_FALSE, MINOR_TRUE, MINOR_NULL, MINOR_UNDEFINED } from './7float.js'

/**
 * @typedef {import('../interface.js').EncodeOptions} EncodeOptions
 * @typedef {import('../interface.js').OptionalTypeEncoder} OptionalTypeEncoder
 * @typedef {import('../interface.js').Reference} Reference
 * @typedef {import('../interface.js').StrictTypeEncoder} StrictTypeEncoder
 * @typedef {import('../interface.js').TokenTypeEncoder} TokenTypeEncoder
 * @typedef {import('../interface.js').TokenOrNestedTokens} TokenOrNestedTokens
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 */

/** @type {EncodeOptions} */
const defaultEncodeOptions = {
  float64: false,
  mapSorter,
  quickEncodeToken
}

/** @type {EncodeOptions} */
export const rfc8949EncodeOptions = Object.freeze({
  mapSorter: rfc8949MapSorter,
  quickEncodeToken
})

/** @returns {TokenTypeEncoder[]} */
export function makeCborEncoders () {
  const encoders = []
  encoders[Type.uint.major] = encodeUint
  encoders[Type.negint.major] = encodeNegint
  encoders[Type.bytes.major] = encodeBytes
  encoders[Type.string.major] = encodeString
  encoders[Type.array.major] = encodeArray
  encoders[Type.map.major] = encodeMap
  encoders[Type.tag.major] = encodeTag
  encoders[Type.float.major] = encodeFloat
  return encoders
}

const cborEncoders = makeCborEncoders()

const defaultWriter = new Bl()

/** @implements {Reference} */
class Ref {
  /**
   * @param {object|any[]} obj
   * @param {Reference|undefined} parent
   */
  constructor (obj, parent) {
    this.obj = obj
    this.parent = parent
  }

  /**
   * @param {object|any[]} obj
   * @returns {boolean}
   */
  includes (obj) {
    /** @type {Reference|undefined} */
    let p = this
    do {
      if (p.obj === obj) {
        return true
      }
    } while (p = p.parent) // eslint-disable-line
    return false
  }

  /**
   * @param {Reference|undefined} stack
   * @param {object|any[]} obj
   * @returns {Reference}
   */
  static createCheck (stack, obj) {
    if (stack && stack.includes(obj)) {
      throw new Error(`${encodeErrPrefix} object contains circular references`)
    }
    return new Ref(obj, stack)
  }
}

const simpleTokens = {
  null: new Token(Type.null, null),
  undefined: new Token(Type.undefined, undefined),
  true: new Token(Type.true, true),
  false: new Token(Type.false, false),
  emptyArray: new Token(Type.array, 0),
  emptyMap: new Token(Type.map, 0)
}

/** @type {{[typeName: string]: StrictTypeEncoder}} */
const typeEncoders = {
  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  number (obj, _typ, _options, _refStack) {
    if (!Number.isInteger(obj) || !Number.isSafeInteger(obj)) {
      return new Token(Type.float, obj)
    } else if (obj >= 0) {
      return new Token(Type.uint, obj)
    } else {
      return new Token(Type.negint, obj)
    }
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  bigint (obj, _typ, _options, _refStack) {
    if (obj >= BigInt(0)) {
      return new Token(Type.uint, obj)
    } else {
      return new Token(Type.negint, obj)
    }
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  Uint8Array (obj, _typ, _options, _refStack) {
    return new Token(Type.bytes, obj)
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  string (obj, _typ, _options, _refStack) {
    return new Token(Type.string, obj)
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  boolean (obj, _typ, _options, _refStack) {
    return obj ? simpleTokens.true : simpleTokens.false
  },

  /**
   * @param {any} _obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  null (_obj, _typ, _options, _refStack) {
    return simpleTokens.null
  },

  /**
   * @param {any} _obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  undefined (_obj, _typ, _options, _refStack) {
    return simpleTokens.undefined
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  ArrayBuffer (obj, _typ, _options, _refStack) {
    return new Token(Type.bytes, new Uint8Array(obj))
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  DataView (obj, _typ, _options, _refStack) {
    return new Token(Type.bytes, new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength))
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} options
   * @param {Reference} [refStack]
   * @returns {TokenOrNestedTokens}
   */
  Array (obj, _typ, options, refStack) {
    if (!obj.length) {
      if (options.addBreakTokens === true) {
        return [simpleTokens.emptyArray, new Token(Type.break)]
      }
      return simpleTokens.emptyArray
    }
    refStack = Ref.createCheck(refStack, obj)
    const entries = []
    let i = 0
    for (const e of obj) {
      entries[i++] = objectToTokens(e, options, refStack)
    }
    if (options.addBreakTokens) {
      return [new Token(Type.array, obj.length), entries, new Token(Type.break)]
    }
    return [new Token(Type.array, obj.length), entries]
  },

  /**
   * @param {any} obj
   * @param {string} typ
   * @param {EncodeOptions} options
   * @param {Reference} [refStack]
   * @returns {TokenOrNestedTokens}
   */
  Object (obj, typ, options, refStack) {
    // could be an Object or a Map
    const isMap = typ !== 'Object'
    // it's slightly quicker to use Object.keys() than Object.entries()
    const keys = isMap ? obj.keys() : Object.keys(obj)
    const maxLength = isMap ? obj.size : keys.length

    /** @type {undefined | [TokenOrNestedTokens, TokenOrNestedTokens][]} */
    let entries

    if (maxLength) {
      // Pre-allocate the array with the expected size
      entries = new Array(maxLength)
      refStack = Ref.createCheck(refStack, obj)
      const skipUndefined = !isMap && options.ignoreUndefinedProperties

      let i = 0
      for (const key of keys) {
        const value = isMap ? obj.get(key) : obj[key]
        if (skipUndefined && value === undefined) {
          continue
        }
        entries[i++] = [
          objectToTokens(key, options, refStack),
          objectToTokens(value, options, refStack)
        ]
      }

      // Truncate only if properties were skipped
      if (i < maxLength) {
        entries.length = i
      }
    }

    if (!entries?.length) {
      if (options.addBreakTokens === true) {
        return [simpleTokens.emptyMap, new Token(Type.break)]
      }
      return simpleTokens.emptyMap
    }

    sortMapEntries(entries, options)
    if (options.addBreakTokens) {
      return [new Token(Type.map, entries.length), entries, new Token(Type.break)]
    }
    return [new Token(Type.map, entries.length), entries]
  },

  /**
   * Encode a `Tagged` wrapper as a CBOR tag header followed by the encoded
   * form of the wrapped value. The value is recursively tokenised through
   * `objectToTokens()` so any registered `typeEncoders` apply to it.
   *
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} options
   * @param {Reference} [refStack]
   * @returns {TokenOrNestedTokens}
   */
  Tagged (obj, _typ, options, refStack) {
    return [
      new Token(Type.tag, obj.tag),
      objectToTokens(obj.value, options, refStack)
    ]
  }
}

typeEncoders.Map = typeEncoders.Object
typeEncoders.Buffer = typeEncoders.Uint8Array
for (const typ of 'Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64'.split(' ')) {
  typeEncoders[`${typ}Array`] = typeEncoders.DataView
}

/**
 * @param {any} obj
 * @param {EncodeOptions} [options]
 * @param {Reference} [refStack]
 * @returns {TokenOrNestedTokens}
 */
function objectToTokens (obj, options = {}, refStack) {
  const typ = is(obj)
  const customTypeEncoder = (options && options.typeEncoders && /** @type {OptionalTypeEncoder} */ options.typeEncoders[typ]) || typeEncoders[typ]
  if (typeof customTypeEncoder === 'function') {
    const tokens = customTypeEncoder(obj, typ, options, refStack)
    if (tokens != null) {
      return tokens
    }
  }
  const typeEncoder = typeEncoders[typ]
  if (!typeEncoder) {
    throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`)
  }
  return typeEncoder(obj, typ, options, refStack)
}

/*
CBOR key sorting is a mess.

The canonicalisation recommendation from https://tools.ietf.org/html/rfc7049#section-3.9
includes the wording:

> The keys in every map must be sorted lowest value to highest.
> Sorting is performed on the bytes of the representation of the key
> data items without paying attention to the 3/5 bit splitting for
> major types.
> ...
>  *  If two keys have different lengths, the shorter one sorts
      earlier;
>  *  If two keys have the same length, the one with the lower value
      in (byte-wise) lexical order sorts earlier.

1. It is not clear what "bytes of the representation of the key" means: is it
   the CBOR representation, or the binary representation of the object itself?
   Consider the int and uint difference here.
2. It is not clear what "without paying attention to" means: do we include it
   and compare on that? Or do we omit the special prefix byte, (mostly) treating
   the key in its plain binary representation form.

The FIDO 2.0: Client To Authenticator Protocol spec takes the original CBOR
wording and clarifies it according to their understanding.
https://fidoalliance.org/specs/fido-v2.0-rd-20170927/fido-client-to-authenticator-protocol-v2.0-rd-20170927.html#message-encoding

> The keys in every map must be sorted lowest value to highest. Sorting is
> performed on the bytes of the representation of the key data items without
> paying attention to the 3/5 bit splitting for major types. The sorting rules
> are:
>  * If the major types are different, the one with the lower value in numerical
>    order sorts earlier.
>  * If two keys have different lengths, the shorter one sorts earlier;
>  * If two keys have the same length, the one with the lower value in
>    (byte-wise) lexical order sorts earlier.

Some other implementations, such as borc, do a full encode then do a
length-first, byte-wise-second comparison:
https://github.com/dignifiedquire/borc/blob/b6bae8b0bcde7c3976b0f0f0957208095c392a36/src/encoder.js#L358
https://github.com/dignifiedquire/borc/blob/b6bae8b0bcde7c3976b0f0f0957208095c392a36/src/utils.js#L143-L151

This has the benefit of being able to easily handle arbitrary keys, including
complex types (maps and arrays).

We'll opt for the FIDO approach, since it affords some efficies since we don't
need a full encode of each key to determine order and can defer to the types
to determine how to most efficiently order their values (i.e. int and uint
ordering can be done on the numbers, no need for byte-wise, for example).

Recommendation: stick to single key types or you'll get into trouble, and prefer
string keys because it's much simpler that way.
*/

/**
 * @param {TokenOrNestedTokens[]} entries
 * @param {EncodeOptions} options
 */
function sortMapEntries (entries, options) {
  if (options.mapSorter) {
    entries.sort(options.mapSorter)
  }
}

/**
 * @param {(Token|Token[])[]} e1
 * @param {(Token|Token[])[]} e2
 * @returns {number}
 */
function mapSorter (e1, e2) {
  // the key position ([0]) could have a single token or an array
  // almost always it'll be a single token but complex key might get involved
  const keyToken1 = Array.isArray(e1[0]) ? e1[0][0] : e1[0]
  const keyToken2 = Array.isArray(e2[0]) ? e2[0][0] : e2[0]

  // different key types
  if (keyToken1.type !== keyToken2.type) {
    return keyToken1.type.compare(keyToken2.type)
  }

  const major = keyToken1.type.major
  // TODO: handle case where cmp === 0 but there are more keyToken e. complex type)
  const tcmp = cborEncoders[major].compareTokens(keyToken1, keyToken2)
  if (tcmp === 0) {
    // duplicate key or complex type where the first token matched,
    // i.e. a map or array and we're only comparing the opening token
    console.warn('WARNING: complex key types used, CBOR key sorting guarantees are gone')
  }
  return tcmp
}

/**
 * @typedef {Token & { _keyBytes?: Uint8Array }} TokenEx
 *
 * @param {(Token|Token[])[]} e1
 * @param {(Token|Token[])[]} e2
 * @returns {number}
 */
function rfc8949MapSorter (e1, e2) {
  if (e1[0] instanceof Token && e2[0] instanceof Token) {
    const t1 = /** @type {TokenEx} */ (e1[0])
    const t2 = /** @type {TokenEx} */ (e2[0])

    if (!t1._keyBytes) {
      t1._keyBytes = encodeRfc8949(t1.value)
    }

    if (!t2._keyBytes) {
      t2._keyBytes = encodeRfc8949(t2.value)
    }

    return compare(t1._keyBytes, t2._keyBytes)
  }

  throw new Error('rfc8949MapSorter: complex key types are not supported yet')
}

/**
 * @param {any} data
 * @returns {Uint8Array}
 */
function encodeRfc8949 (data) {
  return encodeCustom(data, cborEncoders, rfc8949EncodeOptions)
}

/**
 * @param {ByteWriter} writer
 * @param {TokenOrNestedTokens} tokens
 * @param {TokenTypeEncoder[]} encoders
 * @param {EncodeOptions} options
 */
function tokensToEncoded (writer, tokens, encoders, options) {
  if (Array.isArray(tokens)) {
    for (const token of tokens) {
      tokensToEncoded(writer, token, encoders, options)
    }
  } else {
    encoders[tokens.type.major](writer, tokens, options)
  }
}

// CBOR major type prefixes, cached from Type for hot path performance
const MAJOR_UINT = Type.uint.majorEncoded
const MAJOR_NEGINT = Type.negint.majorEncoded
const MAJOR_BYTES = Type.bytes.majorEncoded
const MAJOR_STRING = Type.string.majorEncoded
const MAJOR_ARRAY = Type.array.majorEncoded

// Simple value bytes (CBOR major type 7 + minor value)
const SIMPLE_FALSE = Type.float.majorEncoded | MINOR_FALSE
const SIMPLE_TRUE = Type.float.majorEncoded | MINOR_TRUE
const SIMPLE_NULL = Type.float.majorEncoded | MINOR_NULL
const SIMPLE_UNDEFINED = Type.float.majorEncoded | MINOR_UNDEFINED

const neg1b = BigInt(-1)
const pos1b = BigInt(1)

/**
 * Check if direct encoding can be used for the given options.
 * Direct encoding bypasses token creation for most values.
 * @param {EncodeOptions} options
 * @returns {boolean}
 */
function canDirectEncode (options) {
  // Cannot use direct encode with addBreakTokens (needs special break token handling).
  // Direct encode checks typeEncoders per-value, falling back to tokens as needed.
  // Maps fall back to token-based encoding for efficient key sorting.
  return options.addBreakTokens !== true
}

/**
 * Direct encode a value to the writer, bypassing token creation for most types.
 * Falls back to token-based encoding for custom type encoders.
 * @param {ByteWriter} writer
 * @param {any} data
 * @param {EncodeOptions} options
 * @param {Reference|undefined} refStack
 */
function directEncode (writer, data, options, refStack) {
  const typ = is(data)

  // Check for custom encoder for THIS specific type
  const customEncoder = options.typeEncoders && options.typeEncoders[typ]
  if (customEncoder) {
    const tokens = customEncoder(data, typ, options, refStack)
    if (tokens != null) {
      // Custom encoder returned tokens, serialize immediately
      tokensToEncoded(writer, tokens, cborEncoders, options)
      return
    }
    // Custom encoder returned null, fall through to default handling
  }

  // Direct encode based on type
  switch (typ) {
    case 'null':
      writer.push([SIMPLE_NULL])
      return

    case 'undefined':
      writer.push([SIMPLE_UNDEFINED])
      return

    case 'boolean':
      writer.push([data ? SIMPLE_TRUE : SIMPLE_FALSE])
      return

    case 'number':
      if (!Number.isInteger(data) || !Number.isSafeInteger(data)) {
        // Float, use token encoder for complex float encoding
        encodeFloat(writer, new Token(Type.float, data), options)
      } else if (data >= 0) {
        encodeUintValue(writer, MAJOR_UINT, data)
      } else {
        // Negative integer
        encodeUintValue(writer, MAJOR_NEGINT, data * -1 - 1)
      }
      return

    case 'bigint':
      if (data >= BigInt(0)) {
        encodeUintValue(writer, MAJOR_UINT, data)
      } else {
        encodeUintValue(writer, MAJOR_NEGINT, data * neg1b - pos1b)
      }
      return

    case 'string': {
      const bytes = fromString(data)
      encodeUintValue(writer, MAJOR_STRING, bytes.length)
      writer.push(bytes)
      return
    }

    case 'Uint8Array':
      encodeUintValue(writer, MAJOR_BYTES, data.length)
      writer.push(data)
      return

    case 'Array':
      if (!data.length) {
        writer.push([MAJOR_ARRAY]) // Empty array: 0x80
        return
      }
      refStack = Ref.createCheck(refStack, data)
      encodeUintValue(writer, MAJOR_ARRAY, data.length)
      for (const elem of data) {
        directEncode(writer, elem, options, refStack)
      }
      return

    case 'Object':
    case 'Map':
      // Maps require key sorting, use token-based encoding for efficiency
      // (pre-encoding all keys for sorting is expensive)
      {
        const tokens = typeEncoders.Object(data, typ, options, refStack)
        tokensToEncoded(writer, tokens, cborEncoders, options)
      }
      return

    default:
    // Fall back to token-based encoding for other types (DataView, TypedArrays, etc.)
    {
      const typeEncoder = typeEncoders[typ]
      if (!typeEncoder) {
        throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`)
      }
      const tokens = typeEncoder(data, typ, options, refStack)
      tokensToEncoded(writer, tokens, cborEncoders, options)
    }
  }
}

/**
 * @param {any} data
 * @param {TokenTypeEncoder[]} encoders
 * @param {EncodeOptions} options
 * @param {Uint8Array} [destination]
 * @returns {Uint8Array}
 */
function encodeCustom (data, encoders, options, destination) {
  // arg ordering is different to encodeInto for backward compatibility
  const hasDest = destination instanceof Uint8Array
  let writeTo = hasDest ? new U8Bl(destination) : defaultWriter

  const tokens = objectToTokens(data, options)
  if (!Array.isArray(tokens) && options.quickEncodeToken) {
    const quickBytes = options.quickEncodeToken(tokens)
    if (quickBytes) {
      if (hasDest) {
        // Copy quick bytes into destination buffer
        writeTo.push(quickBytes)
        return writeTo.toBytes()
      }
      return quickBytes
    }
    const encoder = encoders[tokens.type.major]
    if (encoder.encodedSize) {
      const size = encoder.encodedSize(tokens, options)
      if (!hasDest) {
        writeTo = new Bl(size)
      }
      encoder(writeTo, tokens, options)
      // this would be a problem with encodedSize() functions
      if (writeTo.chunks.length !== 1) {
        throw new Error(`Unexpected error: pre-calculated length for ${tokens} was wrong`)
      }
      return hasDest ? writeTo.toBytes() : asU8A(writeTo.chunks[0])
    }
  }
  writeTo.reset()
  tokensToEncoded(writeTo, tokens, encoders, options)
  return writeTo.toBytes(true)
}

/**
 * @param {any} data
 * @param {EncodeOptions} [options]
 * @returns {Uint8Array}
 */
function encode (data, options) {
  options = Object.assign({}, defaultEncodeOptions, options)

  // Use direct encode path when possible
  if (canDirectEncode(options)) {
    defaultWriter.reset()
    directEncode(defaultWriter, data, options, undefined)
    return defaultWriter.toBytes(true)
  }

  return encodeCustom(data, cborEncoders, options)
}

/**
 * @param {any} data
 * @param {Uint8Array} destination
 * @param {EncodeOptions} [options]
 * @returns {{ written: number }}
 */
function encodeInto (data, destination, options) {
  options = Object.assign({}, defaultEncodeOptions, options)

  // Use direct encode path when possible
  if (canDirectEncode(options)) {
    const writer = new U8Bl(destination)
    directEncode(writer, data, options, undefined)
    return { written: writer.toBytes().length }
  }

  const result = encodeCustom(data, cborEncoders, options, destination)
  return { written: result.length }
}

export { objectToTokens, encode, encodeCustom, encodeInto, Ref }
// This is an unfortunate replacement for @sindresorhus/is that we need to
// re-implement for performance purposes. In particular the is.observable()
// check is expensive, and unnecessary for our purposes. The values returned
// are compatible with @sindresorhus/is, however.

// Types that reach getObjectType() - excludes types with fast-paths above:
// primitives (typeof), Array (isArray), Uint8Array (instanceof), plain Object (constructor)
const objectTypeNames = [
  'Object', // for Object.create(null) and other non-plain objects
  'RegExp',
  'Date',
  'Error',
  'Map',
  'Set',
  'WeakMap',
  'WeakSet',
  'ArrayBuffer',
  'SharedArrayBuffer',
  'DataView',
  'Promise',
  'URL',
  'HTMLElement',
  'Int8Array',
  'Uint8ClampedArray',
  'Int16Array',
  'Uint16Array',
  'Int32Array',
  'Uint32Array',
  'Float32Array',
  'Float64Array',
  'BigInt64Array',
  'BigUint64Array',
  'Tagged'
]

/**
 * @param {any} value
 * @returns {string}
 */
export function is (value) {
  if (value === null) {
    return 'null'
  }
  if (value === undefined) {
    return 'undefined'
  }
  if (value === true || value === false) {
    return 'boolean'
  }
  const typeOf = typeof value
  if (typeOf === 'string' || typeOf === 'number' || typeOf === 'bigint' || typeOf === 'symbol') {
    return typeOf
  }
  if (typeOf === 'function') {
    return 'Function'
  }
  if (Array.isArray(value)) {
    return 'Array'
  }
  // Also catches Node.js Buffer which extends Uint8Array
  if (value instanceof Uint8Array) {
    return 'Uint8Array'
  }
  // Fast path for plain objects (most common case after primitives/arrays/bytes)
  if (value.constructor === Object) {
    return 'Object'
  }
  const objectType = getObjectType(value)
  if (objectType) {
    return objectType
  }
  return 'Object'
}

/**
 * @param {any} value
 * @returns {string|undefined}
 */
function getObjectType (value) {
  const objectTypeName = Object.prototype.toString.call(value).slice(8, -1)
  if (objectTypeNames.includes(objectTypeName)) {
    return objectTypeName
  }
  return undefined
}
import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import * as negint from './1negint.js'
import * as bytes from './2bytes.js'
import * as string from './3string.js'
import * as array from './4array.js'
import * as map from './5map.js'
import * as tag from './6tag.js'
import * as float from './7float.js'
import { decodeErrPrefix } from './common.js'
import { fromArray } from './byte-utils.js'

/**
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 */
function invalidMinor (data, pos, minor) {
  throw new Error(`${decodeErrPrefix} encountered invalid minor (${minor}) for major ${data[pos] >>> 5}`)
}

/**
 * @param {string} msg
 * @returns {()=>any}
 */
function errorer (msg) {
  return () => { throw new Error(`${decodeErrPrefix} ${msg}`) }
}

/** @type {((data:Uint8Array, pos:number, minor:number, options?:DecodeOptions) => any)[]} */
export const jump = []

// unsigned integer, 0x00..0x17 (0..23)
for (let i = 0; i <= 0x17; i++) {
  jump[i] = invalidMinor // uint.decodeUintCompact, handled by quick[]
}
jump[0x18] = uint.decodeUint8 // unsigned integer, one-byte uint8_t follows
jump[0x19] = uint.decodeUint16 // unsigned integer, two-byte uint16_t follows
jump[0x1a] = uint.decodeUint32 // unsigned integer, four-byte uint32_t follows
jump[0x1b] = uint.decodeUint64 // unsigned integer, eight-byte uint64_t follows
jump[0x1c] = invalidMinor
jump[0x1d] = invalidMinor
jump[0x1e] = invalidMinor
jump[0x1f] = invalidMinor
// negative integer, -1-0x00..-1-0x17 (-1..-24)
for (let i = 0x20; i <= 0x37; i++) {
  jump[i] = invalidMinor // negintDecode, handled by quick[]
}
jump[0x38] = negint.decodeNegint8 // negative integer, -1-n one-byte uint8_t for n follows
jump[0x39] = negint.decodeNegint16 // negative integer, -1-n two-byte uint16_t for n follows
jump[0x3a] = negint.decodeNegint32 // negative integer, -1-n four-byte uint32_t for follows
jump[0x3b] = negint.decodeNegint64 // negative integer, -1-n eight-byte uint64_t for follows
jump[0x3c] = invalidMinor
jump[0x3d] = invalidMinor
jump[0x3e] = invalidMinor
jump[0x3f] = invalidMinor
// byte string, 0x00..0x17 bytes follow
for (let i = 0x40; i <= 0x57; i++) {
  jump[i] = bytes.decodeBytesCompact
}
jump[0x58] = bytes.decodeBytes8 // byte string, one-byte uint8_t for n, and then n bytes follow
jump[0x59] = bytes.decodeBytes16 // byte string, two-byte uint16_t for n, and then n bytes follow
jump[0x5a] = bytes.decodeBytes32 // byte string, four-byte uint32_t for n, and then n bytes follow
jump[0x5b] = bytes.decodeBytes64 // byte string, eight-byte uint64_t for n, and then n bytes follow
jump[0x5c] = invalidMinor
jump[0x5d] = invalidMinor
jump[0x5e] = invalidMinor
jump[0x5f] = errorer('indefinite length bytes/strings are not supported') // byte string, byte strings follow, terminated by "break"
// UTF-8 string 0x00..0x17 bytes follow
for (let i = 0x60; i <= 0x77; i++) {
  jump[i] = string.decodeStringCompact
}
jump[0x78] = string.decodeString8 // UTF-8 string, one-byte uint8_t for n, and then n bytes follow
jump[0x79] = string.decodeString16 // UTF-8 string, two-byte uint16_t for n, and then n bytes follow
jump[0x7a] = string.decodeString32 // UTF-8 string, four-byte uint32_t for n, and then n bytes follow
jump[0x7b] = string.decodeString64 // UTF-8 string, eight-byte uint64_t for n, and then n bytes follow
jump[0x7c] = invalidMinor
jump[0x7d] = invalidMinor
jump[0x7e] = invalidMinor
jump[0x7f] = errorer('indefinite length bytes/strings are not supported') // UTF-8 strings follow, terminated by "break"
// array, 0x00..0x17 data items follow
for (let i = 0x80; i <= 0x97; i++) {
  jump[i] = array.decodeArrayCompact
}
jump[0x98] = array.decodeArray8 // array, one-byte uint8_t for n, and then n data items follow
jump[0x99] = array.decodeArray16 // array, two-byte uint16_t for n, and then n data items follow
jump[0x9a] = array.decodeArray32 // array, four-byte uint32_t for n, and then n data items follow
jump[0x9b] = array.decodeArray64 // array, eight-byte uint64_t for n, and then n data items follow
jump[0x9c] = invalidMinor
jump[0x9d] = invalidMinor
jump[0x9e] = invalidMinor
jump[0x9f] = array.decodeArrayIndefinite // array, data items follow, terminated by "break"
// map, 0x00..0x17 pairs of data items follow
for (let i = 0xa0; i <= 0xb7; i++) {
  jump[i] = map.decodeMapCompact
}
jump[0xb8] = map.decodeMap8 // map, one-byte uint8_t for n, and then n pairs of data items follow
jump[0xb9] = map.decodeMap16 // map, two-byte uint16_t for n, and then n pairs of data items follow
jump[0xba] = map.decodeMap32 // map, four-byte uint32_t for n, and then n pairs of data items follow
jump[0xbb] = map.decodeMap64 // map, eight-byte uint64_t for n, and then n pairs of data items follow
jump[0xbc] = invalidMinor
jump[0xbd] = invalidMinor
jump[0xbe] = invalidMinor
jump[0xbf] = map.decodeMapIndefinite // map, pairs of data items follow, terminated by "break"
// tags
for (let i = 0xc0; i <= 0xd7; i++) {
  jump[i] = tag.decodeTagCompact
}
jump[0xd8] = tag.decodeTag8
jump[0xd9] = tag.decodeTag16
jump[0xda] = tag.decodeTag32
jump[0xdb] = tag.decodeTag64
jump[0xdc] = invalidMinor
jump[0xdd] = invalidMinor
jump[0xde] = invalidMinor
jump[0xdf] = invalidMinor
// 0xe0..0xf3 simple values, unsupported
for (let i = 0xe0; i <= 0xf3; i++) {
  jump[i] = errorer('simple values are not supported')
}
jump[0xf4] = invalidMinor // false, handled by quick[]
jump[0xf5] = invalidMinor // true, handled by quick[]
jump[0xf6] = invalidMinor // null, handled by quick[]
jump[0xf7] = float.decodeUndefined // undefined
jump[0xf8] = errorer('simple values are not supported') // simple value, one byte follows, unsupported
jump[0xf9] = float.decodeFloat16 // half-precision float (two-byte IEEE 754)
jump[0xfa] = float.decodeFloat32 // single-precision float (four-byte IEEE 754)
jump[0xfb] = float.decodeFloat64 // double-precision float (eight-byte IEEE 754)
jump[0xfc] = invalidMinor
jump[0xfd] = invalidMinor
jump[0xfe] = invalidMinor
jump[0xff] = float.decodeBreak // "break" stop code

/** @type {Token[]} */
export const quick = []
// ints <24
for (let i = 0; i < 24; i++) {
  quick[i] = new Token(Type.uint, i, 1)
}
// negints >= -24
for (let i = -1; i >= -24; i--) {
  quick[31 - i] = new Token(Type.negint, i, 1)
}
// empty bytes
quick[0x40] = new Token(Type.bytes, new Uint8Array(0), 1)
// empty string
quick[0x60] = new Token(Type.string, '', 1)
// empty list
quick[0x80] = new Token(Type.array, 0, 1)
// empty map
quick[0xa0] = new Token(Type.map, 0, 1)
// false
quick[0xf4] = new Token(Type.false, false, 1)
// true
quick[0xf5] = new Token(Type.true, true, 1)
// null
quick[0xf6] = new Token(Type.null, null, 1)

/**
 * @param {Token} token
 * @returns {Uint8Array|undefined}
 */
export function quickEncodeToken (token) {
  switch (token.type) {
    case Type.false:
      return fromArray([0xf4])
    case Type.true:
      return fromArray([0xf5])
    case Type.null:
      return fromArray([0xf6])
    case Type.bytes:
      if (!token.value.length) {
        return fromArray([0x40])
      }
      return
    case Type.string:
      if (token.value === '') {
        return fromArray([0x60])
      }
      return
    case Type.array:
      if (token.value === 0) {
        return fromArray([0x80])
      }
      // shouldn't be possible if this were called when there was only one token
      return
    case Type.map:
      if (token.value === 0) {
        return fromArray([0xa0])
      }
      // shouldn't be possible if this were called when there was only one token
      return
    case Type.uint:
      if (token.value < 24) {
        return fromArray([Number(token.value)])
      }
      return
    case Type.negint:
      if (token.value >= -24) {
        return fromArray([31 - Number(token.value)])
      }
  }
}
/**
 * @typedef {import('../interface.js').TagDecodeControl} TagDecodeControl
 * @typedef {(decode: TagDecodeControl) => Tagged} TaggedTagDecoder
 */

/**
 * A wrapper class for representing a CBOR tag with an arbitrary nested value.
 *
 * `Tagged` is a symmetric primitive: it can be passed to `encode()` to emit
 * a CBOR tag header followed by the encoded form of `value`, and it can be
 * returned from a tag decoder (via `Tagged.decoder(tag)` or `Tagged.preserve()`)
 * to round-trip a tag through decode without losing the tag number.
 *
 * Use `Tagged` for one-off tag handling where defining a dedicated
 * `typeEncoders` entry and tag decoder pair would be heavyweight, e.g. when
 * wrapping a structure in a single application-specific tag (COSE, dCBOR
 * envelopes, etc.).
 *
 * For systematic mapping of a JS type to a tag (e.g. CID -> tag 42), prefer
 * a dedicated `typeEncoders` entry instead.
 */
export class Tagged {
  /**
   * @param {number} tag - CBOR tag number, a non-negative integer
   * @param {any} value - The value to be tagged; encoded recursively
   */
  constructor (tag, value) {
    if (typeof tag !== 'number' || !Number.isInteger(tag) || tag < 0) {
      throw new TypeError('Tagged: tag must be a non-negative integer')
    }
    this.tag = tag
    this.value = value
  }

  /**
   * Build a tag decoder for use in `decode()`'s `tags` option that returns the
   * decoded content wrapped in a `Tagged` instance, preserving the tag number
   * for the caller to inspect.
   *
   * @param {number} tag - The CBOR tag number this decoder will be registered for
   * @returns {TaggedTagDecoder}
   *
   * @example
   * import { decode, Tagged } from 'cborg'
   * const value = decode(bytes, { tags: { 16: Tagged.decoder(16) } })
   * // value instanceof Tagged; value.tag === 16
   */
  static decoder (tag) {
    return (decode) => new Tagged(tag, decode())
  }

  /**
   * Build a `tags` option for `decode()` that wraps each listed tag number in
   * a `Tagged` instance, preserving those tags through decode without
   * registering a dedicated decoder per tag.
   *
   * @param {...number} tagNumbers - One or more CBOR tag numbers to preserve
   * @returns {{[tagNumber: number]: TaggedTagDecoder}}
   *
   * @example
   * import { decode, Tagged } from 'cborg'
   * const value = decode(bytes, { tags: Tagged.preserve(16, 96) })
   */
  static preserve (...tagNumbers) {
    /** @type {{[tagNumber: number]: TaggedTagDecoder}} */
    const tags = {}
    for (const tag of tagNumbers) {
      tags[tag] = Tagged.decoder(tag)
    }
    return tags
  }
}

// Symbol.toStringTag so the internal `is()` type detection returns 'Tagged'
// for instances, allowing the default Tagged typeEncoder to match.
Object.defineProperty(Tagged.prototype, Symbol.toStringTag, {
  value: 'Tagged'
})
class Type {
  /**
   * @param {number} major
   * @param {string} name
   * @param {boolean} terminal
   */
  constructor (major, name, terminal) {
    this.major = major
    this.majorEncoded = major << 5
    this.name = name
    this.terminal = terminal
  }

  toString () {
    return `Type[${this.major}].${this.name}`
  }

  /**
   * @param {Type} typ
   * @returns {number}
   */
  compare (typ) {
    return this.major < typ.major ? -1 : this.major > typ.major ? 1 : 0
  }

  /**
   * Check equality between two Type instances. Safe to use across different
   * copies of the Type class (e.g., when bundlers duplicate the module).
   * (major, name) uniquely identifies a Type; terminal is implied by these.
   * @param {Type} a
   * @param {Type} b
   * @returns {boolean}
   */
  static equals (a, b) {
    return a === b || (a.major === b.major && a.name === b.name)
  }
}

// convert to static fields when better supported
Type.uint = new Type(0, 'uint', true)
Type.negint = new Type(1, 'negint', true)
Type.bytes = new Type(2, 'bytes', true)
Type.string = new Type(3, 'string', true)
Type.array = new Type(4, 'array', false)
Type.map = new Type(5, 'map', false)
Type.tag = new Type(6, 'tag', false) // terminal?
Type.float = new Type(7, 'float', true)
Type.false = new Type(7, 'false', true)
Type.true = new Type(7, 'true', true)
Type.null = new Type(7, 'null', true)
Type.undefined = new Type(7, 'undefined', true)
Type.break = new Type(7, 'break', true)
// Type.indefiniteLength = new Type(0, 'indefiniteLength', true)

class Token {
  /**
   * @param {Type} type
   * @param {any} [value]
   * @param {number} [encodedLength]
   */
  constructor (type, value, encodedLength) {
    this.type = type
    this.value = value
    this.encodedLength = encodedLength
    /** @type {Uint8Array|undefined} */
    this.encodedBytes = undefined
    /** @type {Uint8Array|undefined} */
    this.byteValue = undefined
  }

  toString () {
    return `Token[${this.type}].${this.value}`
  }
}

export { Type, Token }
{
  "name": "cborg",
  "version": "5.1.6",
  "description": "Fast CBOR with a focus on strictness",
  "main": "cborg.js",
  "type": "module",
  "bin": {
    "cborg": "lib/bin.js"
  },
  "scripts": {
    "lint": "standard *.js lib/*.js test/*.js",
    "build": "npm run build:types",
    "build:types": "tsc --build",
    "prepublishOnly": "npm run build",
    "test:node": "mocha test/test-*.js",
    "test:node-bin": "mocha test/node-test-bin.js",
    "test:browser": "polendina --cleanup test/test-*.js",
    "test": "npm run lint && npm run build && npm run test:node && npm run test:node-bin && npm run test:browser",
    "test:ci": "npm run test"
  },
  "repository": {
    "type": "git",
    "url": "git@github.com:rvagg/cborg.git"
  },
  "keywords": [
    "cbor"
  ],
  "author": "Rod <rod@vagg.org> (http://r.va.gg/)",
  "license": "Apache-2.0",
  "devDependencies": {
    "@semantic-release/changelog": "^6.0.3",
    "@semantic-release/commit-analyzer": "^13.0.1",
    "@semantic-release/git": "^10.0.1",
    "@semantic-release/github": "^12.0.6",
    "@semantic-release/npm": "^13.1.5",
    "@semantic-release/release-notes-generator": "^14.1.0",
    "@types/chai": "^5.2.3",
    "@types/mocha": "^10.0.10",
    "@types/node": "^26.0.1",
    "chai": "^6.2.2",
    "conventional-changelog-conventionalcommits": "^10.0.0",
    "ipld-garbage": "^5.0.0",
    "mocha": "^11.7.5",
    "polendina": "^3.2.20",
    "semantic-release": "^25.0.3",
    "standard": "^17.1.2",
    "typescript": "^6.0.2"
  },
  "exports": {
    ".": {
      "import": "./cborg.js",
      "types": "./types/cborg.d.ts"
    },
    "./length": {
      "import": "./lib/length.js",
      "types": "./types/lib/length.d.ts"
    },
    "./taglib": {
      "import": "./lib/taglib.js",
      "types": "./types/lib/taglib.d.ts"
    },
    "./json": {
      "import": "./lib/json/json.js",
      "types": "./types/lib/json/json.d.ts"
    },
    "./extended": {
      "import": "./lib/extended/extended.js",
      "types": "./types/lib/extended/extended.d.ts"
    },
    "./interface": {
      "types": "./types/interface.d.ts"
    }
  },
  "types": "cborg.d.ts",
  "typesVersions": {
    "*": {
      "json": [
        "types/lib/json/json.d.ts"
      ],
      "length": [
        "types/lib/length.d.ts"
      ],
      "*": [
        "types/*"
      ],
      "types/*": [
        "types/*"
      ]
    }
  },
  "release": {
    "branches": [
      "master"
    ],
    "plugins": [
      [
        "@semantic-release/commit-analyzer",
        {
          "preset": "conventionalcommits",
          "releaseRules": [
            {
              "breaking": true,
              "release": "major"
            },
            {
              "revert": true,
              "release": "patch"
            },
            {
              "type": "feat",
              "release": "minor"
            },
            {
              "type": "fix",
              "release": "patch"
            },
            {
              "type": "chore",
              "release": "patch"
            },
            {
              "type": "docs",
              "release": "patch"
            },
            {
              "type": "test",
              "release": "patch"
            },
            {
              "scope": "no-release",
              "release": false
            }
          ]
        }
      ],
      [
        "@semantic-release/release-notes-generator",
        {
          "preset": "conventionalcommits",
          "presetConfig": {
            "types": [
              {
                "type": "feat",
                "section": "Features"
              },
              {
                "type": "fix",
                "section": "Bug Fixes"
              },
              {
                "type": "chore",
                "section": "Trivial Changes"
              },
              {
                "type": "docs",
                "section": "Trivial Changes"
              },
              {
                "type": "test",
                "section": "Tests"
              }
            ]
          }
        }
      ],
      "@semantic-release/changelog",
      "@semantic-release/npm",
      "@semantic-release/github",
      "@semantic-release/git"
    ]
  }
}
const b4a = require('b4a')

module.exports = codecs

codecs.ascii = createString('ascii')
codecs.utf8 = createString('utf-8')
codecs.hex = createString('hex')
codecs.base64 = createString('base64')
codecs.ucs2 = createString('ucs2')
codecs.utf16le = createString('utf16le')
codecs.ndjson = createJSON(true)
codecs.json = createJSON(false)
codecs.binary = {
  name: 'binary',
  encode: function encodeBinary (obj) {
    return typeof obj === 'string'
      ? b4a.from(obj, 'utf-8')
      : b4a.toBuffer(obj)
  },
  decode: function decodeBinary (buf) {
    return b4a.toBuffer(buf)
  }
}

function isCompactEncoding (c) {
  return !!(c.encode && c.decode && c.preencode)
}

function fromCompactEncoding (c) {
  return {
    name: 'compact-encoding',
    encode: function encodeWithCompact (value) {
      const state = { start: 0, end: 0, buffer: null, cache: null }
      c.preencode(state, value)
      state.buffer = b4a.allocUnsafe(state.end)
      c.encode(state, value)
      return state.buffer
    },
    decode: function decodeWithCompact (buffer) {
      return c.decode({ start: 0, end: buffer.byteLength, buffer, cache: null })
    }
  }
}

function codecs (fmt, fallback) {
  if (typeof fmt === 'object' && fmt) {
    return isCompactEncoding(fmt) ? fromCompactEncoding(fmt) : fmt
  }

  switch (fmt) {
    case 'ndjson': return codecs.ndjson
    case 'json': return codecs.json
    case 'ascii': return codecs.ascii
    case 'utf-8':
    case 'utf8': return codecs.utf8
    case 'hex': return codecs.hex
    case 'base64': return codecs.base64
    case 'ucs-2':
    case 'ucs2': return codecs.ucs2
    case 'utf16-le':
    case 'utf16le': return codecs.utf16le
  }

  return fallback !== undefined ? fallback : codecs.binary
}

function createJSON (newline) {
  return {
    name: newline ? 'ndjson' : 'json',
    encode: newline ? encodeNDJSON : encodeJSON,
    decode: function decodeJSON (buf) {
      return JSON.parse(b4a.toString(buf))
    }
  }

  function encodeJSON (val) {
    return b4a.from(JSON.stringify(val))
  }

  function encodeNDJSON (val) {
    return b4a.from(JSON.stringify(val) + '\n')
  }
}

function createString (type) {
  return {
    name: type,
    encode: function encodeString (val) {
      if (typeof val !== 'string') val = val.toString()
      return b4a.from(val, type)
    },
    decode: function decodeString (buf) {
      return b4a.toString(buf, type)
    }
  }
}
{
  "name": "codecs",
  "version": "3.1.0",
  "description": "Create an binary encoder/decoder for json, utf-8 or custom types",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.6.3"
  },
  "devDependencies": {
    "brittle": "^3.2.1",
    "compact-encoding": "^2.11.0",
    "standard": "^17.0.0"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/codecs.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/codecs/issues"
  },
  "homepage": "https://github.com/mafintosh/codecs"
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
const b4a = require('b4a')
const Hypercore = require('hypercore')
const ReadyResource = require('ready-resource')
const sodium = require('sodium-universal')
const crypto = require('hypercore-crypto')
const ID = require('hypercore-id-encoding')
const { isAndroid } = require('which-runtime')
const { STORAGE_EMPTY, ASSERTION } = require('hypercore-errors')

const auditStore = require('./lib/audit.js')
const GroupNotifyHandle = require('./lib/notify.js')

const [NS] = crypto.namespace('corestore', 1)
const DEFAULT_NAMESPACE = b4a.alloc(32) // This is meant to be 32 0-bytes

class StreamTracker {
  constructor() {
    this.records = []
  }

  add(stream, isExternal) {
    const record = { index: 0, stream, isExternal }
    record.index = this.records.push(record) - 1
    return record
  }

  remove(record) {
    const popped = this.records.pop()
    if (popped === record) return
    this.records[(popped.index = record.index)] = popped
  }

  attachAll(core) {
    for (let i = 0; i < this.records.length; i++) {
      const record = this.records[i]
      const muxer = record.stream.noiseStream.userData
      if (!core.replicator.attached(muxer)) core.replicator.attachTo(muxer)
    }
  }

  destroy() {
    // reverse is safer cause we delete mb
    for (let i = this.records.length - 1; i >= 0; i--) {
      const record = this.records[i]
      if (!record.isExternal) record.stream.destroy()
    }
  }
}

class SessionTracker {
  constructor() {
    this.map = new Map()
  }

  get size() {
    return this.map.size
  }

  get(id) {
    const existing = this.map.get(id)
    if (existing !== undefined) return existing
    const fresh = []
    this.map.set(id, fresh)
    return fresh
  }

  gc(id) {
    this.map.delete(id)
  }

  list(id) {
    return id ? this.map.get(id) || [] : [...this]
  }

  *[Symbol.iterator]() {
    for (const sessions of this.map.values()) {
      yield* sessions[Symbol.iterator]()
    }
  }
}

class CoreTracker {
  constructor() {
    this.map = new Map()
    this.watching = []

    this._gcing = new Set()
    this._gcInterval = null
    this._gcCycleBound = this._gcCycle.bind(this)
  }

  get size() {
    return this.map.size
  }

  watch(store) {
    if (store.watchIndex !== -1) return
    store.watchIndex = this.watching.push(store) - 1
  }

  unwatch(store) {
    if (store.watchIndex === -1) return
    const head = this.watching.pop()
    if (head !== store) this.watching[(head.watchIndex = store.watchIndex)] = head
    store.watchIndex = -1
  }

  resume(id) {
    const core = this.map.get(id)

    if (!core) return null

    // signal back that we have a closing one stored
    if (core.closing) return core

    if (core.gc) {
      this._gcing.delete(core)
      if (this._gcing.size === 0) this._stopGC()
      core.gc = 0
    }

    return core
  }

  opened(id) {
    const core = this.map.get(id)
    return !!(core && core.opened && !core.closing)
  }

  get(id) {
    // we allow you do call this from the outside, so support normal buffers also
    if (b4a.isBuffer(id)) id = b4a.toString(id, 'hex')
    const core = this.map.get(id)
    if (!core || core.closing) return null
    return core
  }

  set(id, core) {
    this.map.set(id, core)
    if (this.watching.length > 0) this._emit(core)
  }

  _emit(core) {
    for (let i = this.watching.length - 1; i >= 0; i--) {
      const store = this.watching[i]
      for (const fn of store.watchers) fn(core)
    }
  }

  _gc(core) {
    const id = toHex(core.discoveryKey)
    if (this.map.get(id) === core) this.map.delete(id)
  }

  _gcCycle() {
    for (const core of this._gcing) {
      if (++core.gc < 4) continue
      const gc = this._gc.bind(this, core)
      core.close().then(gc, gc)
      this._gcing.delete(core)
    }

    if (this._gcing.size === 0) this._stopGC()
  }

  gc(core) {
    core.gc = 1 // first strike
    this._gcing.add(core)
    if (this._gcing.size === 1) this._startGC()
  }

  _stopGC() {
    clearInterval(this._gcInterval)
    this._gcInterval = null
  }

  _startGC() {
    if (this._gcInterval) return
    this._gcInterval = setInterval(this._gcCycleBound, 2000)
    if (this._gcInterval.unref) this._gcInterval.unref()
  }

  close() {
    this._stopGC()
    this._gcing.clear()

    const all = []
    for (const core of this.map.values()) {
      core.onidle = noop // no reentry
      all.push(core.close())
    }
    this.map.clear()

    return Promise.all(all)
  }

  *[Symbol.iterator]() {
    for (const core of this.map.values()) {
      if (!core.closing) yield core
    }
  }
}

class FindingPeers {
  constructor() {
    this.count = 0
    this.pending = []
    this.destroyed = false
  }

  add(core) {
    if (this.count === 0) return
    this.pending.push(core.findingPeers())
  }

  inc(sessions) {
    if (this.destroyed || ++this.count !== 1) return

    for (const core of sessions) {
      this.pending.push(core.findingPeers())
    }
  }

  dec(sessions) {
    if (this.destroyed || --this.count !== 0) return
    while (this.pending.length > 0) this.pending.pop()()
  }

  destroy() {
    this.destroyed = true
    while (this.pending.length > 0) this.pending.pop()()
  }
}

class Corestore extends ReadyResource {
  constructor(storage, opts = {}) {
    super()

    this.root = opts.root || null
    this.storage = this.root
      ? this.root.storage
      : Hypercore.defaultStorage(storage, {
          id: opts.id,
          allowBackup: opts.allowBackup,
          readOnly: opts.readOnly,
          wait: opts.wait
        })
    this.streamTracker = this.root ? this.root.streamTracker : new StreamTracker()
    this.cores = this.root ? this.root.cores : new CoreTracker()
    this.sessions = new SessionTracker()
    this.corestores = this.root ? this.root.corestores : new Set()
    this.readOnly = opts.writable === false || !!opts.readOnly
    this.globalCache = this.root ? this.root.globalCache : opts.globalCache || null
    this.primaryKey = this.root ? this.root.primaryKey : opts.primaryKey || null
    this.ns = opts.namespace || DEFAULT_NAMESPACE
    this.manifestVersion = opts.manifestVersion || 1
    this.shouldSuspend = isAndroid ? !!opts.suspend : opts.suspend !== false
    this.active = opts.active !== false

    this.watchers = null
    this.watchIndex = -1

    this._groupNotifiers = new Map() // group notifications
    this._findingPeers = null // here for legacy
    this._ongcBound = this._ongc.bind(this)
    this._onGroupActiveBound = this._onGroupActive.bind(this)

    if (opts.primaryKey && !this.root && !opts.unsafe) {
      throw ASSERTION(
        'Passing the primary key is unsafe unless you know what you are doing. Set unsafe: true to acknowledge that'
      )
    }

    this.ready().catch(noop)
  }

  watch(fn) {
    if (this.watchers === null) {
      this.watchers = new Set()
      this.cores.watch(this)
    }

    this.watchers.add(fn)
  }

  unwatch(fn) {
    if (this.watchers === null) return

    this.watchers.delete(fn)

    if (this.watchers.size === 0) {
      this.watchers = null
      this.cores.unwatch(this)
    }
  }

  _onGroupActive(topic, update) {
    this.emit('group-active', topic, update)

    const topicHex = b4a.toString(topic, 'hex')
    const handles = this._groupNotifiers.get(topicHex)
    if (!handles) return
    for (const handle of handles) handle.emit('update', update)
  }

  notifyGroup(topic) {
    const topicHex = b4a.toString(topic, 'hex')
    let handles = this._groupNotifiers.get(topicHex)

    if (!handles) {
      handles = []
      this._groupNotifiers.set(topicHex, handles)
    }

    const handle = new GroupNotifyHandle(this, topic)
    const length = handles.push(handle)
    handle.index = length - 1

    return handle
  }

  _removeGroupNotify(handle) {
    if (handle.index === -1) return

    const topicHex = b4a.toString(handle._topic, 'hex')
    const handles = this._groupNotifiers.get(topicHex)
    if (!handles) return

    const popped = handles.pop()
    if (popped !== handle) handles[(popped.index = handle.index)] = popped
    if (handles.length === 0) this._groupNotifiers.delete(topicHex)
    handle.index = -1
  }

  findingPeers() {
    if (this._findingPeers === null) this._findingPeers = new FindingPeers()
    this._findingPeers.inc(this.sessions)
    let done = false
    return () => {
      if (done || !this._findingPeers) return
      done = true
      this._findingPeers.dec(this.sessions)
    }
  }

  audit(opts = {}) {
    return auditStore(this, opts)
  }

  async suspend({ log = noop } = {}) {
    await log('Flushing db...')
    // If readOnly we don't need to flush
    if (!this.storage.readOnly) {
      await this.storage.db.flush()
      await log('Flusing db completed')
    }
    if (!this.shouldSuspend) return
    await log('Suspending db...')
    await this.storage.suspend({ log })
    await log('Suspending db completed')
  }

  resume() {
    return this.storage.resume()
  }

  session(opts) {
    this._maybeClosed()
    const root = this.root || this
    return new Corestore(null, {
      manifestVersion: this.manifestVersion,
      ...opts,
      root
    })
  }

  namespace(name, opts) {
    return this.session({
      ...opts,
      namespace: generateNamespace(this.ns, name)
    })
  }

  list(namespace) {
    return this.storage.createDiscoveryKeyStream(namespace)
  }

  getAuth(discoveryKey) {
    return this.storage.getAuth(discoveryKey)
  }

  _ongc(session) {
    if (session.sessions.length === 0) this.sessions.gc(session.id)
  }

  async _getOrSetSeed() {
    const seed = await this.storage.getSeed()
    if (seed !== null) return seed
    return await this.storage.setSeed(this.primaryKey || crypto.randomBytes(32))
  }

  async _open() {
    if (this.root !== null) {
      this.corestores.add(this)
      if (this.root.opened === false) await this.root.ready()
      this.primaryKey = this.root.primaryKey
      return
    }

    const primaryKey = await this._getOrSetSeed()

    if (this.primaryKey === null) {
      this.primaryKey = primaryKey
      return
    }

    if (!b4a.equals(primaryKey, this.primaryKey)) {
      throw new Error('Another corestore is stored here')
    }
  }

  async _close() {
    const closing = []
    const hanging = [...this.sessions]
    for (const sess of hanging) closing.push(sess.close())

    if (this.watchers !== null) {
      this.cores.unwatch(this)
      this.watchers = null
    }

    if (this._findingPeers !== null) {
      this._findingPeers.destroy()
      this._findingPeers = null
    }

    if (this.root !== null) {
      await Promise.all(closing)
      this.corestores.delete(this)
      return
    }

    for (const store of this.corestores) {
      closing.push(store.close())
    }

    await Promise.all(closing)

    await this.cores.close()
    await this.storage.close()
  }

  async _attachMaybe(muxer, discoveryKey) {
    if (this.opened === false) await this.ready()
    if (
      !this.cores.opened(toHex(discoveryKey)) &&
      !(await this.storage.hasCore(discoveryKey, { ifMigrated: true }))
    ) {
      return
    }
    if (this.closing) return

    const core = this._openCore(discoveryKey, { createIfMissing: false })

    if (!core) return
    if (!core.opened) await core.ready()

    if (!core.replicator.attached(muxer)) {
      core.replicator.attachTo(muxer)
    }

    core.checkIfIdle()
  }

  _shouldReplicate(core, muxer) {
    return (
      core.replicator.downloading && !core.replicator.attached(muxer) && core.opened && this.active
    )
  }

  replicate(isInitiator, opts) {
    this._maybeClosed()

    const isExternal = isStream(isInitiator)
    const stream = Hypercore.createProtocolStream(isInitiator, {
      ...opts,
      ondiscoverykey: (discoveryKey) => {
        if (this.closing) return
        const muxer = stream.noiseStream.userData
        return this._attachMaybe(muxer, discoveryKey)
      }
    })

    if (this.cores.size > 0) {
      const muxer = stream.noiseStream.userData
      const uncork = muxer.uncork.bind(muxer)
      muxer.cork()

      for (const core of this.cores) {
        if (!this._shouldReplicate(core, muxer)) {
          continue
        }
        core.replicator.attachTo(muxer)
      }

      stream.noiseStream.opened.then(uncork)
    }

    const record = this.streamTracker.add(stream, isExternal)
    stream.once('close', () => this.streamTracker.remove(record))
    return stream
  }

  _maybeClosed() {
    if (this.closing || (this.root !== null && this.root.closing)) {
      throw new Error('Corestore is closed')
    }
  }

  async staticify(core, opts) {
    if (!this.opened) await this.ready()
    if (!core.opened) await core.ready()

    const rx = core.state.storage.read()

    const headPromise = rx.getHead()
    const authPromise = rx.getAuth()

    rx.tryFlush()

    const [head, auth] = await Promise.all([headPromise, authPromise])
    if (!head || head.length === 0) throw new Error('Core must have data')

    const prologue = {
      length: head.length,
      hash: head.rootHash
    }

    const manifest = {
      version: 1,
      hash: auth.manifest.hash,
      quorum: 0,
      signers: [],
      prologue
    }

    const c = {
      key: null,
      discoveryKey: null,
      manifest,
      core: core.state.storage.core
    }

    c.key = Hypercore.key(c.manifest)
    c.discoveryKey = Hypercore.discoveryKey(c.key)

    await this.storage.createCore(c)

    const staticCore = this.get({ ...opts, key: c.key })
    await staticCore.ready()
    return staticCore
  }

  get(opts) {
    this._maybeClosed()

    if (b4a.isBuffer(opts) || typeof opts === 'string') opts = { key: opts }
    if (!opts) opts = {}

    const conf = {
      preload: null,
      sessions: null,
      ongc: null,
      core: null,
      active: opts.active !== false,
      encryption: opts.encryption || null,
      encryptionKey: opts.encryptionKey || null, // back compat, should remove
      isBlockKey: !!opts.isBlockKey, // back compat, should remove
      valueEncoding: opts.valueEncoding || null,
      exclusive: !!opts.exclusive,
      manifest: opts.manifest || null,
      keyPair: opts.keyPair || null,
      onwait: opts.onwait || null,
      pushOnly: opts.pushOnly === true,
      wait: opts.wait !== false,
      timeout: opts.timeout || 0,
      draft: !!opts.draft,
      writable: opts.writable === undefined && this.readOnly ? false : opts.writable
    }

    // name requires us to rt to storage + ready, so needs preload
    // same goes if user has defined async preload obvs
    if (opts.name || opts.preload) {
      conf.preload = this._preload(opts)
      return this._makeSession(conf)
    }

    if (opts.discoveryKey && !opts.key && !opts.manifest) {
      conf.preload = this._preloadCheckIfExists(opts)
      return this._makeSession(conf)
    }

    // if not not we can sync create it, which just is easier for the
    // upstream user in terms of guarantees (key is there etc etc)
    const core = this._openCore(null, opts)

    conf.core = core
    conf.sessions = this.sessions.get(core.id)
    conf.ongc = this._ongcBound

    return this._makeSession(conf)
  }

  _makeSession(conf) {
    const session = new Hypercore(null, null, conf)

    if (this._findingPeers !== null) this._findingPeers.add(session)
    return session
  }

  async createKeyPair(name, ns = this.ns) {
    if (this.opened === false) await this.ready()
    return createKeyPair(this.primaryKey, ns, name)
  }

  async _preloadCheckIfExists(opts) {
    const has = await this.storage.hasCore(opts.discoveryKey)
    if (!has) throw STORAGE_EMPTY('No Hypercore is stored here')
    return this._preload(opts)
  }

  async _preload(opts) {
    if (opts.preload) opts = { ...opts, ...(await opts.preload) }
    if (this.opened === false) await this.ready()

    const discoveryKey = opts.name
      ? await this.storage.getAlias({ name: opts.name, namespace: this.ns })
      : null
    this._maybeClosed()

    const core = this._openCore(discoveryKey, opts)

    return {
      core,
      sessions: this.sessions.get(core.id),
      ongc: this._ongcBound,
      manifest: opts.manifest || null,
      encryption: opts.encryption || null,
      encryptionKey: opts.encryptionKey || null, // back compat, should remove
      isBlockKey: !!opts.isBlockKey // back compat, should remove
    }
  }

  _auth(discoveryKey, opts) {
    const result = {
      keyPair: null,
      key: null,
      discoveryKey,
      manifest: null,
      group: null
    }

    if (opts.name) {
      result.keyPair = createKeyPair(this.primaryKey, this.ns, opts.name)
    } else if (opts.keyPair) {
      result.keyPair = opts.keyPair
    }

    if (opts.manifest) {
      result.manifest = opts.manifest
    } else if (result.keyPair && !result.discoveryKey) {
      result.manifest = {
        version: this.manifestVersion,
        signers: [{ publicKey: result.keyPair.publicKey }]
      }
    }

    if (opts.group) {
      result.group = opts.group
    }

    if (opts.key) result.key = ID.decode(opts.key)
    else if (result.manifest) result.key = Hypercore.key(result.manifest)

    if (result.discoveryKey) return result

    if (opts.discoveryKey) result.discoveryKey = ID.decode(opts.discoveryKey)
    else if (result.key) result.discoveryKey = crypto.discoveryKey(result.key)
    else throw new Error('Could not derive discovery from input')

    return result
  }

  _openCore(discoveryKey, opts) {
    const auth = this._auth(discoveryKey, opts)

    const id = toHex(auth.discoveryKey)
    const existing = this.cores.resume(id, auth.group)
    if (existing && !existing.closing) return existing

    const core = Hypercore.createCore(this.storage, {
      preopen: existing && existing.opened ? existing.closing : null, // always wait for the prev one to close first in any case...
      eagerUpgrade: true,
      notDownloadingLinger: opts.notDownloadingLinger,
      allowFork: opts.allowFork !== false,
      allowPush: !!opts.allowPush,
      inflightRange: opts.inflightRange,
      compat: false, // no compat for now :)
      force: opts.force,
      createIfMissing: opts.createIfMissing,
      discoveryKey: auth.discoveryKey,
      overwrite: opts.overwrite,
      key: auth.key,
      keyPair: auth.keyPair,
      legacy: opts.legacy,
      manifest: auth.manifest,
      group: auth.group,
      globalCache: opts.globalCache || this.globalCache || null,
      alias: opts.name ? { name: opts.name, namespace: this.ns } : null
    })

    core.onidle = () => {
      this.cores.gc(core)
    }

    core.ongroupupdate = this._onGroupActiveBound

    core.replicator.ondownloading = () => {
      if (this.active) this.streamTracker.attachAll(core)
    }

    this.cores.set(id, core)
    return core
  }
}

module.exports = Corestore

function isStream(s) {
  return typeof s === 'object' && s && typeof s.pipe === 'function'
}

function generateNamespace(namespace, name) {
  if (!b4a.isBuffer(name)) name = b4a.from(name)
  const out = b4a.allocUnsafeSlow(32)
  sodium.crypto_generichash_batch(out, [namespace, name])
  return out
}

function deriveSeed(primaryKey, namespace, name) {
  if (!b4a.isBuffer(name)) name = b4a.from(name)
  const out = b4a.alloc(32)
  sodium.crypto_generichash_batch(out, [NS, namespace, name], primaryKey)
  return out
}

function createKeyPair(primaryKey, namespace, name) {
  const seed = deriveSeed(primaryKey, namespace, name)
  const buf = b4a.alloc(sodium.crypto_sign_PUBLICKEYBYTES + sodium.crypto_sign_SECRETKEYBYTES)
  const keyPair = {
    publicKey: buf.subarray(0, sodium.crypto_sign_PUBLICKEYBYTES),
    secretKey: buf.subarray(sodium.crypto_sign_PUBLICKEYBYTES)
  }
  sodium.crypto_sign_seed_keypair(keyPair.publicKey, keyPair.secretKey, seed)
  return keyPair
}

function noop() {}

function toHex(discoveryKey) {
  return b4a.toString(discoveryKey, 'hex')
}
module.exports = async function* audit(store, { dryRun = false } = {}) {
  for await (const { discoveryKey, core } of store.storage.createCoreStream()) {
    if (core.version < 1) continue // not migrated, ignore

    const c = store.get({ discoveryKey, active: false })
    await c.ready()

    yield { discoveryKey, key: c.key, audit: await c.core.audit({ dryRun }) }

    try {
      await c.close()
    } catch {
      // ignore if failed, we are auditing...
    }
  }
}
const { EventEmitter } = require('events')
const { Readable } = require('streamx')

class GroupNotifyHandle extends EventEmitter {
  constructor(store, topic) {
    super()
    this._store = store
    this._topic = topic
    this.index = -1
  }

  updates(opts) {
    return Readable.deferred(async () => {
      const groupId = await this._store.storage.getGroup(this._topic).catch(noop)
      if (groupId === null) return null
      return this._store.storage.createGroupUpdateStream(groupId, opts)
    })
  }

  destroy() {
    this._store._removeGroupNotify(this)
  }
}

module.exports = GroupNotifyHandle

function noop() {}
{
  "name": "corestore",
  "version": "7.11.0",
  "description": "A Hypercore factory that simplifies managing collections of cores.",
  "main": "index.js",
  "files": [
    "index.js",
    "lib/*"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "dependencies": {
    "b4a": "^1.6.7",
    "bare-events": "^2.8.3",
    "hypercore": "^11.32.0",
    "hypercore-crypto": "^3.4.2",
    "hypercore-errors": "^1.4.0",
    "hypercore-id-encoding": "^1.3.0",
    "ready-resource": "^1.1.1",
    "sodium-universal": "^5.0.1",
    "streamx": "^2.26.0",
    "which-runtime": "^1.2.1"
  },
  "devDependencies": {
    "brittle": "^3.7.0",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "rache": "^1.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "test": "npm run test:node && npm run test:bare",
    "test:bare": "brittle-bare --coverage test/all.js",
    "lint": "prettier --check . && lunte",
    "test:node": "brittle-node --coverage test/all.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/corestore.git"
  },
  "author": "Holepunch Inc",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/corestore/issues"
  },
  "homepage": "https://github.com/holepunchto/corestore"
}
module.exports = function debounce (worker, context = null) {
  debounced.running = null
  return debounced

  async function debounced () {
    if (debounced.running !== null) {
      try {
        await debounced.running
      } catch (_) {
        // ignore - do not fail on old errors
      }
    }

    // another "thread" beat us to it, just piggy pack on that one
    if (debounced.running !== null) return debounced.running

    debounced.running = worker.call(context)

    try {
      return await debounced.running
    } finally {
      debounced.running = null
    }
  }
}
{
  "name": "debounceify",
  "version": "1.1.0",
  "description": "Tiny async debouncer",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^16.0.3",
    "tape": "^5.1.1"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/debounceify.git"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/debounceify/issues"
  },
  "homepage": "https://github.com/mafintosh/debounceify"
}
const fs = require('fs')
const path = require('path')
const fsx = require('fs-native-extensions')
const b4a = require('b4a')
const ReadyResource = require('ready-resource')
const FDLock = require('fd-lock')

const PLATFORM = global.Bare ? global.Bare.platform : global.process.platform
const IS_WIN = PLATFORM === 'win32'
const IS_LINUX = PLATFORM === 'linux'
const MODIFIED_SLACK = 5000
const EMPTY = b4a.alloc(0)
const ATTR = IS_LINUX ? 'user.device-file' : 'device-file'

const nl = IS_WIN ? '\r\n' : '\n'

class DeviceFile extends ReadyResource {
  constructor(filename, { create = true, wait = false, lock = wait, data = {} } = {}) {
    super()

    this.filename = filename
    this.data = data
    this.lock = null

    this._create = create
    this._wait = wait
    this._lock = lock
  }

  async _open() {
    if (await verifyDeviceFile(this)) return
    if (!this._create) throwDeviceFileError('No device file present', false)
    await writeDeviceFile(this)
  }

  static async validate(filename, data) {
    const file = new DeviceFile(filename, { create: false, wait: false, data })
    try {
      await verifyDeviceFile(file)
    } catch (err) {
      if (err.fatal && err.code === 'DEVICE_FILE') return false
      throw err
    }
    return true
  }

  transfer() {
    return this.lock ? this.lock.transfer() : -1
  }

  async _close() {
    if (this.lock) await this.lock.close()
  }

  async suspend() {
    if (!this.opened) await this.ready()
    if (this.lock) await this.lock.suspend()
  }

  async resume() {
    if (!this.opened) await this.ready()
    if (this.lock) await this.lock.resume()
  }
}

module.exports = DeviceFile

async function writeDeviceFile(device) {
  let s = ''

  for (const [key, value] of Object.entries(device.data)) {
    if (value === null) continue
    s += key + '=' + value + nl
  }

  await fs.promises.mkdir(path.dirname(device.filename), { recursive: true })

  const fd = await open(device.filename, 'w')

  device.lock = device._lock ? new FDLock(fd, { wait: device._wait }) : null

  if (device.lock) {
    try {
      await device.lock.ready()
    } catch (err) {
      await device.lock.close()
      throw err
    }
  }

  const st = await fstat(fd)

  const created = Date.now()

  s += 'device/platform=' + PLATFORM + nl
  s += 'device/inode=' + st.ino + nl
  s += 'device/created=' + created + nl

  if (await setAttr(fd, ATTR, b4a.from('original'))) {
    s += 'device/attribute=original' + nl
  }

  await write(fd, b4a.from(s))

  if (!device.lock) await close(fd)
}

async function verifyDeviceFile(device) {
  let fd = 0

  try {
    fd = await open(device.filename, 'r+')
  } catch (e) {
    fd = 0
  }

  if (fd === 0) return false

  device.lock = device._lock ? new FDLock(fd, { wait: device._wait }) : null

  if (device.lock) {
    try {
      await device.lock.ready()
    } catch (err) {
      await device.lock.close()
      throw err
    }
  }

  const buf = await read(fd)
  const result = {}

  const s = b4a.toString(buf).trim().split('\n')

  let inode = 0
  let created = 0
  let attr = ''
  let platform = ''

  for (const ln of s) {
    const i = ln.indexOf('=')
    if (i === -1) continue

    const k = ln.slice(0, i).trim()
    const v = ln.slice(i + 1).trim()

    switch (k) {
      case 'device/platform':
        platform = v
        break
      case 'device/inode':
        inode = Number(v)
        break
      case 'device/created':
        created = Number(v)
        break
      case 'device/attribute':
        attr = v
        break
      default:
        result[k] = v
        break
    }
  }

  for (const [k, v] of Object.entries(device.data)) {
    if (v === null) continue
    if (result[k] === undefined) continue // allow upserts
    if (result[k] !== '' + v) {
      await teardown()
      throwDeviceFileError(`Invalid device file, ${k} has changed. Was ${result[k]}, is ${v}`, true)
    }
  }

  const st = await fstat(fd)
  const at = await getAttr(fd, ATTR)

  const sameAttr = b4a.toString(at || EMPTY) === attr
  const modified = Math.max(st.mtime.getTime(), st.birthtime.getTime())

  if (platform && platform !== PLATFORM) {
    await teardown()
    throwDeviceFileError('Invalid device file, was made on different platform', true)
  }

  if (!sameAttr) {
    await teardown()
    throwDeviceFileError('Invalid device file, was moved unsafely', true)
  }

  if (st.ino !== inode || (created && Math.abs(modified - created) >= MODIFIED_SLACK)) {
    await teardown()
    throwDeviceFileError('Invalid device file, was modified', true)
  }

  if (!device.lock) await close(fd)

  device.data = result
  return true

  async function teardown() {
    if (device.lock) await device.lock.close()
    else await close(fd)
  }
}

async function getAttr(fd, name) {
  try {
    return await fsx.getAttr(fd, name)
  } catch {
    return null
  }
}

async function setAttr(fd, name, value) {
  try {
    await fsx.setAttr(fd, name, value)
    return true
  } catch {
    return false
  }
}

function fstat(fd) {
  return new Promise((resolve, reject) => {
    fs.fstat(fd, (err, st) => {
      if (err) reject(err)
      resolve(st)
    })
  })
}

function close(fd) {
  return new Promise((resolve, reject) => {
    fs.close(fd, (err, st) => {
      if (err) reject(err)
      resolve(st)
    })
  })
}

function write(fd, buf) {
  return new Promise((resolve, reject) => {
    let offset = 0

    onwrite(null, 0)

    function onwrite(err, wrote) {
      if (err) return reject(err)
      if (offset === buf.byteLength) return resolve()
      offset += wrote
      fs.write(fd, buf, offset, buf.byteLength - offset, offset, onwrite)
    }
  })
}

function read(fd) {
  const buf = b4a.allocUnsafe(4096)

  return new Promise((resolve, reject) => {
    let offset = 0

    fs.read(fd, buf, 0, buf.byteLength, 0, onread)

    function onread(err, read) {
      if (err) return reject(err)
      if (read === 0) return resolve(buf.subarray(0, offset))
      offset += read
      fs.read(fd, buf, offset, buf.byteLength - offset, offset, onread)
    }
  })
}

function open(filename, flags) {
  return new Promise((resolve, reject) => {
    fs.open(filename, flags, (err, fd) => {
      if (err) reject(err)
      resolve(fd)
    })
  })
}

function throwDeviceFileError(message, fatal) {
  const err = new Error(message)
  err.code = 'DEVICE_FILE'
  err.fatal = fatal
  throw err
}
{
  "name": "device-file",
  "version": "2.3.1",
  "description": "Device only file",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.6.7",
    "bare-fs": "^4.0.1",
    "bare-path": "^3.0.0",
    "fd-lock": "^2.1.0",
    "fs-native-extensions": "^1.4.0",
    "ready-resource": "^1.2.0"
  },
  "devDependencies": {
    "brittle": "^3.13.1",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node --coverage test.js",
    "test:bare": "brittle-bare --coverage test.js"
  },
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    }
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/device-file.git"
  },
  "author": "Holepunch Inc",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/device-file/issues"
  },
  "homepage": "https://github.com/holepunchto/device-file"
}
module.exports = require('bare-events')
{
  "name": "events-universal",
  "version": "1.0.1",
  "description": "Universal wrapper for the Node.js events module",
  "exports": {
    "./package": "./package.json",
    ".": {
      "bare": "./bare.js",
      "react-native": "./react-native.js",
      "default": "./default.js"
    }
  },
  "files": [
    "index.js",
    "default.js",
    "bare.js",
    "react-native.js"
  ],
  "scripts": {
    "test": "prettier . --check"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/events-universal.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/events-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/events-universal#readme",
  "dependencies": {
    "bare-events": "^2.7.0"
  },
  "devDependencies": {
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^1.0.0"
  }
}
module.exports = class FixedFIFO {
  constructor (hwm) {
    if (!(hwm > 0) || ((hwm - 1) & hwm) !== 0) throw new Error('Max size for a FixedFIFO should be a power of two')
    this.buffer = new Array(hwm)
    this.mask = hwm - 1
    this.top = 0
    this.btm = 0
    this.next = null
  }

  clear () {
    this.top = this.btm = 0
    this.next = null
    this.buffer.fill(undefined)
  }

  push (data) {
    if (this.buffer[this.top] !== undefined) return false
    this.buffer[this.top] = data
    this.top = (this.top + 1) & this.mask
    return true
  }

  shift () {
    const last = this.buffer[this.btm]
    if (last === undefined) return undefined
    this.buffer[this.btm] = undefined
    this.btm = (this.btm + 1) & this.mask
    return last
  }

  peek () {
    return this.buffer[this.btm]
  }

  isEmpty () {
    return this.buffer[this.btm] === undefined
  }
}
const FixedFIFO = require('./fixed-size')

module.exports = class FastFIFO {
  constructor (hwm) {
    this.hwm = hwm || 16
    this.head = new FixedFIFO(this.hwm)
    this.tail = this.head
    this.length = 0
  }

  clear () {
    this.head = this.tail
    this.head.clear()
    this.length = 0
  }

  push (val) {
    this.length++
    if (!this.head.push(val)) {
      const prev = this.head
      this.head = prev.next = new FixedFIFO(2 * this.head.buffer.length)
      this.head.push(val)
    }
  }

  shift () {
    if (this.length !== 0) this.length--
    const val = this.tail.shift()
    if (val === undefined && this.tail.next) {
      const next = this.tail.next
      this.tail.next = null
      this.tail = next
      return this.tail.shift()
    }

    return val
  }

  peek () {
    const val = this.tail.peek()
    if (val === undefined && this.tail.next) return this.tail.next.peek()
    return val
  }

  isEmpty () {
    return this.length === 0
  }
}
{
  "name": "fast-fifo",
  "version": "1.3.2",
  "description": "A fast fifo implementation similar to the one powering nextTick in Node.js core",
  "main": "index.js",
  "files": [
    "./index.js",
    "./fixed-size.js"
  ],
  "dependencies": {},
  "devDependencies": {
    "standard": "^17.1.0",
    "brittle": "^3.3.2"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/fast-fifo.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/fast-fifo/issues"
  },
  "homepage": "https://github.com/mafintosh/fast-fifo"
}
const fs = require('fs')
const fsx = require('fs-native-extensions')
const onexit = require('resource-on-exit')
const ReadyResource = require('ready-resource')

module.exports = class FDLock extends ReadyResource {
  constructor(fd, opts = {}) {
    const { wait = false } = opts

    super()

    this._fd = fd
    this._wait = wait
    this._locked = false

    onexit.add(this, closeSync)
  }

  get locked() {
    return this._locked
  }

  async _open() {
    try {
      await this._resume()
    } catch (err) {
      onexit.remove(this)
      await close(this)
      throw err
    }
  }

  async _close() {
    onexit.remove(this)
    await close(this)
    this._locked = false
  }

  transfer() {
    const fd = this._fd
    if (fd === -1) throw new Error('Lock has already been transferred')
    this._fd = -1
    onexit.remove(this)
    return fd
  }

  async suspend() {
    if (!this.opened) await this.ready()
    return this._suspend()
  }

  async _suspend() {
    if (this._fd === -1 || this._locked === false) return
    fsx.unlock(this._fd)
    this._locked = false
  }

  async resume() {
    if (!this.opened) await this.ready()
    return this._resume()
  }

  async _resume() {
    if (this._fd === -1 || this._locked === true) return
    if (this._wait) await fsx.waitForLock(this._fd)
    else if (!fsx.tryLock(this._fd)) {
      throw new Error('File descriptor could not be locked')
    }
    this._locked = true
  }
}

function close(lock) {
  const fd = lock._fd
  if (fd === -1) return
  lock._fd = -1
  return new Promise((resolve) => fs.close(fd, () => resolve()))
}

function closeSync(lock) {
  const fd = lock._fd
  if (fd === -1) return
  lock._fd = -1
  lock._locked = false
  try {
    fs.closeSync(fd)
  } catch {}
}
{
  "name": "fd-lock",
  "version": "2.2.0",
  "description": "Stateful file descriptor locks for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": "./index.js"
  },
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    }
  },
  "files": [
    "index.js"
  ],
  "scripts": {
    "test": "npm run lint && npm run test:bare && npm run test:node",
    "test:bare": "bare test.js",
    "test:node": "node test.js",
    "lint": "prettier --check .",
    "format": "prettier --write ."
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/fd-lock.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/fd-lock/issues"
  },
  "homepage": "https://github.com/holepunchto/fd-lock#readme",
  "dependencies": {
    "bare-fs": "^4.5.0",
    "fs-native-extensions": "^1.4.4",
    "ready-resource": "^1.2.0",
    "resource-on-exit": "^1.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
exports.fullRoots = function (index, result) {
  if (index & 1) throw new Error('You can only look up roots for depth(0) blocks')
  if (!result) result = []

  index /= 2

  let offset = 0
  let factor = 1

  while (true) {
    if (!index) return result
    while (factor * 2 <= index) factor *= 2
    result.push(offset + factor - 1)
    offset = offset + 2 * factor
    index -= factor
    factor = 1
  }
}

exports.futureRoots = function (index, result) {
  if (index & 1) throw new Error('You can only look up future roots for depth(0) blocks')
  if (!result) result = []

  let factor = 1

  // make first root
  while (factor * 2 <= index) factor *= 2

  // full factor of 2 - done
  if (factor * 2 - 2 === index) return result

  let pos = factor / 2 - 1

  // while its not a full tree
  while ((pos + factor / 2 - 1) !== index) {
    pos += factor

    // read too far, to to left child
    while ((pos + factor / 2 - 1) > index) {
      factor /= 2
      pos -= factor / 2
    }

    // the "gap" is a future root
    result.push(pos - factor / 2)
  }

  return result
}

exports.patch = function (from, to) {
  if (from === 0 || from >= to) return []

  const roots = exports.fullRoots(from)
  const target = exports.fullRoots(to)

  // first find the first root that is different

  let i = 0
  for (; i < target.length; i++) {
    if (i >= roots.length || roots[i] !== target[i]) break
  }

  const patch = []

  if (i < roots.length) {
    // now we need to grow the newest root until it hits the diff one
    let prev = roots.length - 1

    const ite = exports.iterator(roots[prev--])

    while (ite.index !== target[i]) {
      ite.sibling()

      if (prev >= 0 && ite.index === roots[prev]) {
        prev--
      } else {
        patch.push(ite.index)
      }

      patch.push(ite.parent())
    }

    i++ // patched to next root, so inc
  }

  // include the rest

  for (; i < target.length; i++) patch.push(target[i])

  return patch
}

exports.depth = function (index) {
  let depth = 0

  index += 1
  while (!(index & 1)) {
    depth++
    index = rightShift(index)
  }

  return depth
}

exports.sibling = function (index, depth) {
  if (!depth) depth = exports.depth(index)
  const offset = exports.offset(index, depth)

  return exports.index(depth, offset & 1 ? offset - 1 : offset + 1)
}

exports.parent = function (index, depth) {
  if (!depth) depth = exports.depth(index)
  const offset = exports.offset(index, depth)

  return exports.index(depth + 1, rightShift(offset))
}

exports.leftChild = function (index, depth) {
  if (!(index & 1)) return -1
  if (!depth) depth = exports.depth(index)
  return exports.index(depth - 1, exports.offset(index, depth) * 2)
}

exports.rightChild = function (index, depth) {
  if (!(index & 1)) return -1
  if (!depth) depth = exports.depth(index)
  return exports.index(depth - 1, 1 + (exports.offset(index, depth) * 2))
}

exports.children = function (index, depth) {
  if (!(index & 1)) return null

  if (!depth) depth = exports.depth(index)
  const offset = exports.offset(index, depth) * 2

  return [
    exports.index(depth - 1, offset),
    exports.index(depth - 1, offset + 1)
  ]
}

exports.leftSpan = function (index, depth) {
  if (!(index & 1)) return index
  if (!depth) depth = exports.depth(index)
  return exports.offset(index, depth) * twoPow(depth + 1)
}

exports.rightSpan = function (index, depth) {
  if (!(index & 1)) return index
  if (!depth) depth = exports.depth(index)
  return (exports.offset(index, depth) + 1) * twoPow(depth + 1) - 2
}

exports.nextLeaf = function (index) {
  let factor = 1
  let r = index

  while ((r & 1) === 1) {
    r = (r - 1) / 2
    factor *= 2
  }

  return index + factor + 1
}

exports.count = function (index, depth) {
  if (!(index & 1)) return 1
  if (!depth) depth = exports.depth(index)
  return twoPow(depth + 1) - 1
}

exports.countLeaves = function (index) {
  return (exports.count(index) + 1) / 2
}

exports.spans = function (index, depth) {
  if (!(index & 1)) return [index, index]
  if (!depth) depth = exports.depth(index)

  const offset = exports.offset(index, depth)
  const width = twoPow(depth + 1)

  return [offset * width, (offset + 1) * width - 2]
}

exports.index = function (depth, offset) {
  return (1 + 2 * offset) * twoPow(depth) - 1
}

exports.offset = function (index, depth) {
  if (!(index & 1)) return index / 2
  if (!depth) depth = exports.depth(index)

  return ((index + 1) / twoPow(depth) - 1) / 2
}

exports.iterator = function (index) {
  const ite = new Iterator()
  ite.seek(index || 0)
  return ite
}

function twoPow (n) {
  return n < 31 ? 1 << n : ((1 << 30) * (1 << (n - 30)))
}

function rightShift (n) {
  return (n - (n & 1)) / 2
}

function Iterator () {
  this.index = 0
  this.offset = 0
  this.factor = 0
}

Iterator.prototype.seek = function (index) {
  this.index = index
  if (this.index & 1) {
    this.offset = exports.offset(index)
    this.factor = twoPow(exports.depth(index) + 1)
  } else {
    this.offset = index / 2
    this.factor = 2
  }
}

Iterator.prototype.isLeft = function () {
  return (this.offset & 1) === 0
}

Iterator.prototype.isRight = function () {
  return (this.offset & 1) === 1
}

Iterator.prototype.isRoot = function (length) {
  const currentLength = 1 + (this.index + this.factor / 2 - 1) / 2
  if (length < currentLength) return false

  const factor = this.factor * 2
  const index = (this.offset & 1)
    ? this.index - this.factor / 2
    : this.index + this.factor / 2

  const parentLength = 1 + (index + factor / 2 - 1) / 2
  return parentLength > length
}

Iterator.prototype.contains = function (index) {
  return index > this.index
    ? index < (this.index + this.factor / 2)
    : index < this.index
      ? index > (this.index - this.factor / 2)
      : true
}

Iterator.prototype.prev = function () {
  if (!this.offset) return this.index
  this.offset--
  this.index -= this.factor
  return this.index
}

Iterator.prototype.next = function () {
  this.offset++
  this.index += this.factor
  return this.index
}

Iterator.prototype.count = function () {
  if (!(this.index & 1)) return 1
  return this.factor - 1
}

Iterator.prototype.countLeaves = function () {
  return (this.count() + 1) / 2
}

Iterator.prototype.sibling = function () {
  return this.isLeft() ? this.next() : this.prev()
}

Iterator.prototype.parent = function () {
  if (this.offset & 1) {
    this.index -= this.factor / 2
    this.offset = (this.offset - 1) / 2
  } else {
    this.index += this.factor / 2
    this.offset /= 2
  }
  this.factor *= 2
  return this.index
}

Iterator.prototype.leftSpan = function () {
  this.index = this.index - this.factor / 2 + 1
  this.offset = this.index / 2
  this.factor = 2
  return this.index
}

Iterator.prototype.peekLeftSpan = function () {
  return this.index - this.factor / 2 + 1
}

Iterator.prototype.rightSpan = function () {
  this.index = this.index + this.factor / 2 - 1
  this.offset = this.index / 2
  this.factor = 2
  return this.index
}

Iterator.prototype.peekRightSpan = function () {
  return this.index + this.factor / 2 - 1
}

Iterator.prototype.leftChild = function () {
  if (this.factor === 2) return this.index
  this.factor /= 2
  this.index -= this.factor / 2
  this.offset *= 2
  return this.index
}

Iterator.prototype.rightChild = function () {
  if (this.factor === 2) return this.index
  this.factor /= 2
  this.index += this.factor / 2
  this.offset = 2 * this.offset + 1
  return this.index
}

Iterator.prototype.nextTree = function () {
  this.index = this.index + this.factor / 2 + 1
  this.offset = this.index / 2
  this.factor = 2
  return this.index
}

Iterator.prototype.prevTree = function () {
  if (!this.offset) {
    this.index = 0
    this.factor = 2
  } else {
    this.index = this.index - this.factor / 2 - 1
    this.offset = this.index / 2
    this.factor = 2
  }
  return this.index
}

Iterator.prototype.fullRoot = function (index) {
  if (index <= this.index || (this.index & 1) > 0) return false
  while (index > this.index + this.factor + this.factor / 2) {
    this.index += this.factor / 2
    this.factor *= 2
    this.offset /= 2
  }
  return true
}
{
  "name": "flat-tree",
  "version": "1.13.0",
  "description": "A series of functions to map a binary tree to a list",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {},
  "devDependencies": {
    "brittle": "^3.3.2",
    "standard": "^17.1.0"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/flat-tree.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/flat-tree/issues"
  },
  "homepage": "https://github.com/mafintosh/flat-tree"
}
require.addon = require('require-addon')

module.exports = require.addon('.', __filename)
const { isWindows } = require('which-runtime')
const binding = require('./binding')

function onwork(err, result) {
  if (err) this.reject(err)
  else this.resolve(result)
}

exports.tryLock = function tryLock(fd, offset = 0, length = 0, opts = {}) {
  if (typeof offset === 'object') {
    opts = offset
    offset = 0
  }

  if (typeof length === 'object') {
    opts = length
    length = 0
  }

  if (typeof opts !== 'object' || opts === null) {
    opts = {}
  }

  try {
    binding.tryLock(fd, offset, length, opts.shared !== true)
  } catch (err) {
    if (err.code === 'EAGAIN') return false
    throw err
  }

  return true
}

exports.waitForLock = function waitForLock(fd, offset = 0, length = 0, opts = {}) {
  if (typeof offset === 'object') {
    opts = offset
    offset = 0
  }

  if (typeof length === 'object') {
    opts = length
    length = 0
  }

  if (typeof opts !== 'object' || opts === null) {
    opts = {}
  }

  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.waitForLock(fd, offset, length, opts.shared !== true, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.waitForLockSync = function waitForLockSync(fd, offset = 0, length = 0, opts = {}) {
  if (typeof offset === 'object') {
    opts = offset
    offset = 0
  }

  if (typeof length === 'object') {
    opts = length
    length = 0
  }

  if (typeof opts !== 'object' || opts === null) {
    opts = {}
  }

  binding.waitForLockSync(fd, offset, length, opts.shared !== true)
}

exports.tryDowngradeLock = function tryDowngradeLock(fd, offset = 0, length = 0) {
  try {
    binding.tryDowngradeLock(fd, offset, length)
  } catch (err) {
    if (err.code === 'EAGAIN') return false
    throw err
  }

  return true
}

exports.waitForDowngradeLock = function downgradeLock(fd, offset = 0, length = 0) {
  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.waitForDowngradeLock(fd, offset, length, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.waitForDowngradeLockSync = function waitForDowngradeLockSync(fd, offset = 0, length = 0) {
  binding.waitForDowngradeLockSync(fd, offset, length)
}

exports.tryUpgradeLock = function tryUpgradeLock(fd, offset = 0, length = 0) {
  try {
    binding.tryUpgradeLock(fd, offset, length)
  } catch (err) {
    if (err.code === 'EAGAIN') return false
    throw err
  }

  return true
}

exports.waitForUpgradeLock = function upgradeLock(fd, offset = 0, length = 0) {
  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.waitForUpgradeLock(fd, offset, length, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.waitForUpgradeLockSync = function waitForUpgradeLockSync(fd, offset = 0, length = 0) {
  binding.waitForUpgradeLockSync(fd, offset, length)
}

exports.unlock = function unlock(fd, offset = 0, length = 0) {
  binding.unlock(fd, offset, length)
}

exports.trim = function trim(fd, offset, length) {
  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.trim(fd, offset, length, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.trimSync = function trimSync(fd, offset, length) {
  binding.trimSync(fd, offset, length)
}

exports.sparse = function sparse(fd) {
  // Short circuit on everything but Windows
  if (!isWindows) return Promise.resolve()

  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.sparse(fd, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.sparseSync = function sparseSync(fd) {
  // Short circuit on everything but Windows
  if (!isWindows) return

  binding.sparseSync(fd)
}

exports.swap = function swap(from, to) {
  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.swap(from, to, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.swapSync = function swapSync(from, to) {
  binding.swapSync(from, to)
}

exports.getAttr = function getAttr(fd, name) {
  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.getAttr(fd, name, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise.then((buffer) => (buffer === null ? null : Buffer.from(buffer)))
}

exports.getAttrSync = function getAttrSync(fd, name) {
  const buffer = binding.getAttrSync(fd, name)
  return buffer === null ? null : Buffer.from(buffer)
}

exports.setAttr = function setAttr(fd, name, value, encoding) {
  if (typeof value === 'string') value = Buffer.from(value, encoding)

  const req = {
    value,
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.setAttr(
      fd,
      name,
      value.buffer,
      value.byteOffset,
      value.byteLength,
      req,
      onwork
    )
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.setAttrSync = function setAttrSync(fd, name, value, encoding) {
  if (typeof value === 'string') value = Buffer.from(value, encoding)

  binding.setAttrSync(fd, name, value.buffer, value.byteOffset, value.byteLength)
}

exports.removeAttr = function removeAttr(fd, name) {
  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.removeAttr(fd, name, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.removeAttrSync = function removeAttrSync(fd, name) {
  binding.removeAttrSync(fd, name)
}

exports.listAttrs = function listAttrs(fd) {
  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.listAttrs(fd, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.listAttrsSync = function listAttrsSync(fd) {
  return binding.listAttrsSync(fd)
}
{
  "name": "fs-native-extensions",
  "version": "1.5.0",
  "description": "Native file system extensions for advanced file operations",
  "main": "index.js",
  "files": [
    "index.js",
    "macros.h",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "include",
    "src",
    "prebuilds"
  ],
  "imports": {
    "child_process": {
      "bare": "bare-subprocess",
      "default": "child_process"
    },
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "fs/*": {
      "bare": "bare-fs/*",
      "default": "fs/*"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    }
  },
  "addon": true,
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:bare": "brittle-bare --coverage test.js",
    "test:node": "brittle-node --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/fs-native-extensions.git"
  },
  "author": "Kasper Isager Dalsgarð <kasper@funktionel.co>",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/fs-native-extensions/issues"
  },
  "homepage": "https://github.com/holepunchto/fs-native-extensions#readme",
  "dependencies": {
    "require-addon": "^1.1.0",
    "which-runtime": "^1.2.0"
  },
  "devDependencies": {
    "bare-compat-napi": "^1.3.8",
    "bare-fs": "^4.4.4",
    "bare-path": "^3.0.0",
    "bare-subprocess": "^4.0.5",
    "brittle": "^3.1.1",
    "cmake-bare": "^1.1.10",
    "cmake-fetch": "^1.4.7",
    "cmake-napi": "^1.0.5",
    "cmake-npm": "^1.1.0",
    "lunte": "^1.6.0",
    "minimist": "^1.2.6",
    "prettier": "^3.5.3",
    "prettier-config-holepunch": "^2.0.0",
    "test-tmp": "^1.2.1"
  }
}
const codecs = require('codecs')
const { Readable } = require('streamx')
const mutexify = require('mutexify/promise')
const b4a = require('b4a')
const safetyCatch = require('safety-catch')
const ReadyResource = require('ready-resource')
const debounce = require('debounceify')
const Rache = require('rache')
const rrp = require('resolve-reject-promise')

const { all: unslabAll } = require('unslab')

const RangeIterator = require('./iterators/range')
const HistoryIterator = require('./iterators/history')
const DiffIterator = require('./iterators/diff')
const LocalBlockIterator = require('./iterators/local')
const Extension = require('./lib/extension')
const { YoloIndex, Node, Header } = require('./lib/messages')
const { BLOCK_NOT_AVAILABLE, DECODING_ERROR } = require('hypercore-errors')

const T = 5
const MIN_KEYS = T - 1
const MAX_CHILDREN = MIN_KEYS * 2 + 1

const SEP = b4a.alloc(1)
const EMPTY = b4a.alloc(0)

class Key {
  constructor(seq, value) {
    this.seq = seq
    this.value = value
  }
}

class Child {
  constructor(seq, offset, value) {
    this.seq = seq
    this.offset = offset
    this.value = value
  }
}

class Cache {
  constructor(rache) {
    this.keys = rache
    this.length = 0
  }

  get(seq) {
    return this.keys.get(seq) || null
  }

  set(seq, key) {
    this.keys.set(seq, key)
    if (seq >= this.length) this.length = seq + 1
  }

  gc(length) {
    // if we need to "work" more than 128 ticks, just bust the cache...
    if (this.length - length > 128) {
      this.keys.clear()
    } else {
      for (let i = length; i < this.length; i++) {
        this.keys.delete(i)
      }
    }

    this.length = length
  }

  clear() {
    this.keys.clear()
  }
}

class Pointers {
  constructor(decoded) {
    this.levels = decoded.levels.map((l) => {
      const children = []
      const keys = []

      for (let i = 0; i < l.keys.length; i++) {
        keys.push(new Key(l.keys[i], null))
      }

      for (let i = 0; i < l.children.length; i += 2) {
        children.push(new Child(l.children[i], l.children[i + 1], null))
      }

      return { keys, children }
    })
  }

  get(i) {
    return this.levels[i]
  }

  hasKey(seq) {
    for (const lvl of this.levels) {
      for (const key of lvl.keys) {
        if (key.seq === seq) return true
      }
    }
    return false
  }
}

function inflate(entry) {
  if (entry.inflated === null) {
    entry.inflated = YoloIndex.decode(entry.index)
    entry.index = null
  }
  return new Pointers(entry.inflated)
}

function deflate(index) {
  const levels = index.map((l) => {
    const keys = []
    const children = []

    for (let i = 0; i < l.value.keys.length; i++) {
      keys.push(l.value.keys[i].seq)
    }

    for (let i = 0; i < l.value.children.length; i++) {
      children.push(l.value.children[i].seq, l.value.children[i].offset)
    }

    return { keys, children }
  })

  return YoloIndex.encode({ levels })
}

class TreeNode {
  constructor(block, keys, children, offset) {
    this.block = block
    this.offset = offset
    this.keys = keys
    this.children = children
    this.changed = false

    this.preload()
  }

  preload() {
    if (this.block === null) return

    const core = getBackingCore(this.block.tree.core)
    if (!core) return

    const bitfield = core.core.bitfield
    const blocks = []

    for (let i = 0; i < this.keys.length; i++) {
      const k = this.keys[i]
      if (k.value) continue
      if (k.seq >= core.signedLength || (bitfield && bitfield.get(k.seq))) continue
      blocks.push(k.seq)
    }
    for (let i = 0; i < this.children.length; i++) {
      const c = this.children[i]
      if (c.value) continue
      if (c.seq >= core.signedLength || (bitfield && bitfield.get(c.seq))) continue
      blocks.push(c.seq)
    }

    if (blocks.length) core.download({ blocks })
  }

  async insertKey(key, value, child, node, encoding, cas) {
    let s = 0
    let e = this.keys.length
    let c

    while (s < e) {
      const mid = (s + e) >> 1
      c = b4a.compare(key.value, await this.getKey(mid))

      if (c === 0) {
        if (cas) {
          const prev = await this.getKeyNode(mid)
          if (!(await cas(prev.final(encoding), node))) return true
        }
        if (!this.block.tree.tree.alwaysDuplicate) {
          const prev = await this.getKeyNode(mid)
          if (sameValue(prev.value, value)) return true
        }
        this.changed = true
        this.keys[mid] = key
        return true
      }

      if (c < 0) e = mid
      else s = mid + 1
    }

    const i = c < 0 ? e : s
    this.keys.splice(i, 0, key)
    if (child) this.children.splice(i + 1, 0, new Child(0, 0, child))
    this.changed = true

    return this.keys.length < MAX_CHILDREN
  }

  removeKey(index) {
    this.keys.splice(index, 1)
    if (this.children.length) {
      this.children[index + 1].seq = 0 // mark as freed
      this.children.splice(index + 1, 1)
    }
    this.changed = true
  }

  async siblings(parent) {
    for (let i = 0; i < parent.children.length; i++) {
      if (parent.children[i].value === this) {
        const [left, right] = await Promise.all([
          i ? parent.getChildNode(i - 1) : null,
          i < parent.children.length - 1 ? parent.getChildNode(i + 1) : null
        ])
        return { left, index: i, right }
      }
    }

    throw new Error('Bad parent')
  }

  merge(node, median) {
    this.changed = true
    this.keys.push(median)
    for (let i = 0; i < node.keys.length; i++) this.keys.push(node.keys[i])
    for (let i = 0; i < node.children.length; i++) this.children.push(node.children[i])
  }

  async split() {
    const len = this.keys.length >> 1
    const right = TreeNode.create(this.block)

    while (right.keys.length < len) right.keys.push(this.keys.pop())
    right.keys.reverse()

    await this.getKey(this.keys.length - 1) // make sure the median is loaded
    const median = this.keys.pop()

    if (this.children.length) {
      while (right.children.length < len + 1) right.children.push(this.children.pop())
      right.children.reverse()
    }

    this.changed = true

    return {
      left: this,
      median,
      right
    }
  }

  getKeyNode(index) {
    return this.block.tree.getBlock(this.keys[index].seq)
  }

  async getChildNode(index) {
    const child = this.children[index]
    if (child.value) return child.value
    const block =
      child.seq === this.block.seq ? this.block : await this.block.tree.getBlock(child.seq)
    return (child.value = block.getTreeNode(child.offset))
  }

  setKey(index, key) {
    this.keys[index] = key
    this.changed = true
  }

  async getKey(index) {
    const key = this.keys[index]
    if (key.value) return key.value
    const k = key.seq === this.block.seq ? this.block.key : await this.block.tree.getKey(key.seq)
    return (key.value = k)
  }

  indexChanges(index, seq) {
    const offset = index.push(null) - 1
    this.changed = false

    for (const child of this.children) {
      if (!child.value || !child.value.changed) continue
      child.seq = seq
      child.offset = child.value.indexChanges(index, seq)
      index[child.offset] = child
    }

    return offset
  }

  updateChildren(seq, block) {
    for (const child of this.children) {
      if (!child.value || child.seq !== seq) continue
      child.value.block = block
      child.value.updateChildren(seq, block)
    }
  }

  static create(block) {
    const node = new TreeNode(block, [], [], 0)
    node.changed = true
    return node
  }
}

class BlockEntry {
  constructor(seq, tree, entry) {
    this.seq = seq
    this.tree = tree
    this.index = null
    this.entry = entry
    this.key = entry.key
    this.value = entry.value
  }

  isTarget(key) {
    return b4a.equals(this.key, key)
  }

  inflate() {
    if (this.index === null) {
      this.index = inflate(this.entry)
    }
  }

  isDeletion() {
    if (this.value !== null) return false

    if (this.index === null) {
      this.index = inflate(this.entry)
    }

    return !this.index.hasKey(this.seq)
  }

  final(encoding) {
    return {
      seq: this.seq,
      key: encoding.key ? encoding.key.decode(this.key) : this.key,
      value: this.value && (encoding.value ? encoding.value.decode(this.value) : this.value)
    }
  }

  getTreeNode(offset) {
    if (this.index === null) {
      this.index = inflate(this.entry)
    }
    const entry = this.index.get(offset)
    return new TreeNode(this, entry.keys, entry.children, offset)
  }
}

class CacheLock {
  constructor() {
    this.map = new Map()
  }

  enter(seq) {
    const pending = this.map.get(seq)

    if (!pending) {
      this.map.set(seq, [])
      return Promise.resolve()
    }

    const { resolve, promise } = rrp()
    pending.push(resolve)
    return promise
  }

  exit(seq) {
    const pending = this.map.get(seq)
    if (!pending.length) {
      this.map.delete(seq)
      return
    }

    pending.pop()()
  }
}

class BatchEntry extends BlockEntry {
  constructor(seq, tree, key, value, index) {
    super(seq, tree, { key, value, index: null, inflated: null })
    this.pendingIndex = index
  }

  isTarget(key) {
    return false
  }

  getTreeNode(offset) {
    return this.pendingIndex[offset].value
  }
}

class Hyperbee extends ReadyResource {
  constructor(core, opts = {}) {
    super()
    // this.feed is now deprecated, and will be this.core going forward
    this.feed = core
    this.core = core

    this.keyEncoding = opts.keyEncoding ? codecs(opts.keyEncoding) : null
    this.valueEncoding = opts.valueEncoding ? codecs(opts.valueEncoding) : null
    this.extension = opts.extension !== false ? getExtension(this, opts) : null
    this.metadata = opts.metadata || null
    this.lock = opts.lock || mutexify()
    this.sep = opts.sep || SEP
    this.readonly = !!opts.readonly
    this.prefix = opts.prefix || null

    // In a future version, this should be false by default
    this.alwaysDuplicate = opts.alwaysDuplicate !== false

    this._unprefixedKeyEncoding = this.keyEncoding
    this._sub = !!this.prefix
    this._checkout = opts.checkout || 0
    this._view = !!opts._view

    this._onappendBound = this._view ? null : this._onappend.bind(this)
    this._ontruncateBound = this._view ? null : this._ontruncate.bind(this)
    this._watchers = this._onappendBound ? [] : null
    this._entryWatchers = this._onappendBound ? [] : null
    this._sessions = opts.sessions !== false

    this._keyCache = null
    this._nodeCache = null
    this._cacheLock = new CacheLock()

    this._batches = []

    if (this._watchers) {
      this.core.on('append', this._onappendBound)
      this.core.on('truncate', this._ontruncateBound)
    }

    if (this.prefix && opts._sub) {
      this.keyEncoding = prefixEncoding(this.prefix, this.keyEncoding)
    }

    this.ready().catch(safetyCatch)
  }

  async _open() {
    if (this.core.opened === false) await this.core.ready()
    // bump the internal ranges since the nodes are small
    if (this._watchers && this.core.replicator.setInflightRange) {
      this.core.replicator.setInflightRange(256, 512)
    }

    // snapshot
    if (this._checkout === -1) this._checkout = Math.max(1, this.core.length)

    const baseCache = Rache.from(this.core.globalCache)
    this._keyCache = new Cache(baseCache)
    this._nodeCache = new Cache(Rache.from(baseCache))
  }

  get version() {
    return Math.max(1, this._checkout || this.core.length)
  }

  get id() {
    return this.core.id
  }

  get key() {
    return this.core.key
  }

  get discoveryKey() {
    return this.core.discoveryKey
  }

  get writable() {
    return this.core.writable
  }

  get readable() {
    return this.core.readable
  }

  replicate(isInitiator, opts) {
    return this.core.replicate(isInitiator, opts)
  }

  update(opts) {
    return this.core.update(opts)
  }

  peek(range, opts) {
    return iteratorPeek(this.createRangeIterator(range, { ...opts, limit: 1 }))
  }

  createRangeIterator(range, opts = {}) {
    // backwards compat range arg
    opts = opts ? { ...opts, ...range } : range

    const extension = opts.extension === false && opts.limit !== 0 ? null : this.extension
    const keyEncoding = opts.keyEncoding ? codecs(opts.keyEncoding) : this.keyEncoding

    if (extension) {
      const { onseq, onwait } = opts
      let version = 0
      let next = 0

      opts = encRange(keyEncoding, {
        ...opts,
        sub: this._sub,
        onseq(seq) {
          if (!version) version = seq + 1
          if (next) next--
          if (onseq) onseq(seq)
        },
        onwait(seq) {
          if (!next) {
            next = Extension.BATCH_SIZE
            extension.iterator(ite.snapshot(version))
          }
          if (onwait) onwait(seq)
        }
      })
    } else {
      opts = encRange(keyEncoding, { ...opts, sub: this._sub })
    }

    const ite = new RangeIterator(
      new Batch(this, this._makeSnapshot(), null, false, opts),
      null,
      opts
    )
    return ite
  }

  createReadStream(range, opts) {
    const signal = (opts && opts.signal) || null
    return iteratorToStream(this.createRangeIterator(range, opts), signal)
  }

  createHistoryStream(opts) {
    const session = opts && opts.live ? this.core.session() : this._makeSnapshot()
    const signal = (opts && opts.signal) || null
    return iteratorToStream(
      new HistoryIterator(new Batch(this, session, null, false, opts), opts),
      signal
    )
  }

  createDiffStream(right, range, opts) {
    if (typeof right === 'number') right = this.checkout(Math.max(1, right), { reuseSession: true })

    // backwards compat range arg
    opts = opts ? { ...opts, ...range } : range

    const signal = (opts && opts.signal) || null

    const keyEncoding = opts && opts.keyEncoding ? codecs(opts.keyEncoding) : this.keyEncoding
    if (keyEncoding) opts = encRange(keyEncoding, { ...opts, sub: this._sub })

    let done
    let closing
    let ite

    const left = this

    const rs = new Readable({
      signal,
      eagerOpen: true,
      async open(cb) {
        try {
          if (right.opened === false) await right.ready()
          if (left.opened === false) await left.ready()
        } catch (err) {
          cb(err)
          return
        }

        if (closing) {
          cb(null)
          return
        }

        if (left.core.closing || right.core.closing) {
          cb(new Error('Bee closed'))
          return
        }

        const snapshot = right.version > left.version ? right._makeSnapshot() : left._makeSnapshot()

        done = cb
        ite = new DiffIterator(
          new Batch(left, snapshot, null, false, opts),
          new Batch(right, snapshot, null, false, opts),
          opts
        )
        ite.open().then(fin, fin)
      },
      read(cb) {
        done = cb
        ite.next().then(push, fin)
      },
      predestroy() {
        if (!ite) {
          closing = Promise.resolve()
        } else {
          closing = ite.close()
          closing.catch(noop)
        }
      },
      destroy(cb) {
        done = cb
        if (!closing) closing = ite.close()
        closing.then(fin, fin)
      }
    })

    return rs

    function fin(err) {
      done(err)
    }

    function push(val) {
      rs.push(val)
      done(null)
    }
  }

  get(key, opts) {
    const b = new Batch(this, this._makeSnapshot(), null, true, opts)
    return b.get(key)
  }

  getBySeq(seq, opts) {
    const b = new Batch(this, this._makeSnapshot(), null, true, opts)
    return b.getBySeq(seq)
  }

  put(key, value, opts) {
    const b = new Batch(this, this.core, null, true, opts)
    return b.put(key, value, opts)
  }

  batch(opts) {
    return new Batch(this, this.core, mutexify(), true, opts)
  }

  del(key, opts) {
    const b = new Batch(this, this.core, null, true, opts)
    return b.del(key, opts)
  }

  watch(range, opts) {
    if (!this._watchers) throw new Error('Can only watch the main bee instance')
    return new Watcher(this, range, opts)
  }

  async getAndWatch(key, opts) {
    if (!this._watchers) throw new Error('Can only watch the main bee instance')

    const watcher = new EntryWatcher(this, key, opts)
    await watcher._debouncedUpdate()

    if (this.closing) {
      await watcher.close()
      throw new Error('Bee closed')
    }

    return watcher
  }

  _onappend() {
    for (const watcher of this._watchers) {
      watcher._onappend()
    }

    for (const watcher of this._entryWatchers) {
      watcher._onappend()
    }
  }

  _ontruncate(length) {
    for (const watcher of this._watchers) {
      watcher._ontruncate()
    }

    for (const watcher of this._entryWatchers) {
      watcher._ontruncate()
    }

    this._nodeCache.gc(length)
    this._keyCache.gc(length)
  }

  _makeSnapshot() {
    if (this._sessions === false) return this.core
    // TODO: better if we could encapsulate this in hypercore in the future
    return this._checkout <= this.core.length || this._checkout <= 1
      ? this.core.snapshot()
      : this.core.session({ snapshot: false })
  }

  async clearUnlinked(options = {}) {
    await this.ready()

    const { gte = 0, lt = this.version - 1, batchSize = 4096, wait = true } = options
    const checkout = this.version

    let prev = this.batch({ wait: false, checkout: gte })
    let b = this.batch({ wait, checkout })

    const iteBatch = this.batch({ wait: false, checkout })
    const ite = new LocalBlockIterator(iteBatch, { gte, lt })
    await ite.open()

    let ticks = 0

    while (true) {
      const data = await ite.next()
      if (!data) break

      if (!(await isLinked(b, data))) {
        if (b.core.closing || this.core.closing || this.closing) break
        await this.core.clear(data.seq)
      }

      const prevNode = await prev.get(data.key, { finalize: false }).catch(toNull)

      if (prevNode && !(await isLinked(b, prevNode))) {
        if (b.core.closing || this.core.closing || this.closing) break
        await this.core.clear(prevNode.seq)
      }

      if (ticks++ >= batchSize) {
        ticks = 0
        await prev.close()
        await b.close()

        prev = this.batch({ wait: false, checkout: gte })
        b = this.batch({ wait, checkout })
      }
    }

    if (b.core.closing || this.core.closing || this.closing) throw new Error('Core is closed')

    await b.close()
    await prev.close()
    await ite.close()
    await iteBatch.close()

    return lt
  }

  checkout(version, opts = {}) {
    if (version === 0) version = 1

    // same as above, just checkout isn't set yet...
    const snap =
      opts.reuseSession || this._sessions === false
        ? this.core
        : version <= this.core.length || version <= 1
          ? this.core.snapshot()
          : this.core.session({ snapshot: false })

    return new Hyperbee(snap, {
      _view: true,
      _sub: false,
      prefix: this.prefix,
      sep: this.sep,
      lock: this.lock,
      checkout: version,
      keyEncoding: opts.keyEncoding || this.keyEncoding,
      valueEncoding: opts.valueEncoding || this.valueEncoding,
      extension: this.extension !== null ? this.extension : false
    })
  }

  snapshot(opts) {
    return this.checkout(
      this.core.opened === false || this._checkout <= 0 ? -1 : Math.max(1, this.version),
      opts
    )
  }

  sub(prefix, opts = {}) {
    let sep = opts.sep || this.sep
    if (!b4a.isBuffer(sep)) sep = b4a.from(sep)

    prefix = b4a.concat([this.prefix || EMPTY, b4a.from(prefix), sep])

    const valueEncoding = codecs(opts.valueEncoding || this.valueEncoding)
    const keyEncoding = codecs(opts.keyEncoding || this._unprefixedKeyEncoding)

    return new Hyperbee(this.core, {
      _view: true,
      _sub: true,
      prefix,
      sep: this.sep,
      lock: this.lock,
      checkout: this._checkout,
      valueEncoding,
      keyEncoding,
      extension: this.extension !== null ? this.extension : false,
      metadata: this.metadata
    })
  }

  async getHeader(opts) {
    const blk = await this.core.get(0, opts)
    try {
      return blk && Header.decode(blk)
    } catch {
      throw DECODING_ERROR()
    }
  }

  async _close() {
    if (!this._view) {
      if (this._keyCache) this._keyCache.clear()
      if (this._nodeCache) this._nodeCache.clear()
    }

    if (this._watchers) {
      this.core.off('append', this._onappendBound)
      this.core.off('truncate', this._ontruncateBound)

      while (this._watchers.length) {
        await this._watchers[this._watchers.length - 1].close()
      }
    }

    if (this._entryWatchers) {
      while (this._entryWatchers.length) {
        await this._entryWatchers[this._entryWatchers.length - 1].close()
      }
    }

    while (this._batches.length) {
      await this._batches[this._batches.length - 1].close()
    }

    return this.core.close()
  }

  static async isHyperbee(core, opts) {
    await core.ready()

    const blk0 = await core.get(0, opts)
    if (blk0 === null) throw BLOCK_NOT_AVAILABLE()

    try {
      return Header.decode(blk0).protocol === 'hyperbee'
    } catch (err) {
      // undecodable
      return false
    }
  }
}

class Batch {
  constructor(tree, core, batchLock, cache, options = {}) {
    this.tree = tree
    // this.feed is now deprecated, and will be this.core going forward
    this.feed = core
    this.core = core
    this.index = tree._batches.push(this) - 1
    this.blocks = cache ? new Map() : null
    this.autoFlush = !batchLock
    this.maxBlocksCached = options.maxBlocksCached || 128
    this.rootSeq = 0
    this.root = null
    this.length = 0
    this.checkout = options.checkout === undefined ? -1 : options.checkout
    this.options = options
    this.locked = null
    this.batchLock = batchLock
    this.onseq = this.options.onseq || noop
    this.appending = null
    this.isSnapshot = this.core !== this.tree.core
    this.shouldUpdate = this.options.update !== false
    this.updating = null
    this.encoding = {
      key: options.keyEncoding ? codecs(options.keyEncoding) : tree.keyEncoding,
      value: options.valueEncoding ? codecs(options.valueEncoding) : tree.valueEncoding
    }
  }

  async ready() {
    if (this.core.opened === false) await this.core.ready()
    if (this.tree.opened === false) await this.tree.ready()
  }

  async lock() {
    if (this.tree.readonly) throw new Error('Hyperbee is marked as read-only')
    if (this.locked === null) this.locked = await this.tree.lock()
  }

  get version() {
    if (this.checkout !== -1) return Math.max(1, this.checkout)
    return Math.max(1, this.tree._checkout || this.core.length + this.length)
  }

  async getRoot(ensureHeader) {
    await this.ready()
    if (ensureHeader) {
      if (this.core.length === 0 && this.core.writable && !this.tree.readonly) {
        await this.core.append(
          Header.encode({
            protocol: 'hyperbee',
            metadata: this.tree.metadata
          })
        )
      }
    }
    if (this.tree._checkout === 0 && this.checkout === -1 && this.shouldUpdate) {
      if (this.updating === null) this.updating = this.core.update()
      await this.updating
    }
    if (this.version < 2) return null
    return (await this.getBlock(this.version - 1)).getTreeNode(0)
  }

  async getKey(seq) {
    await this.tree._cacheLock.enter(seq)

    try {
      const k = this.core.fork === this.tree.core.fork ? this.tree._keyCache.get(seq) : null
      if (k !== null) return k
      const key = (await this._getBlock(seq)).key
      if (this.core.fork === this.tree.core.fork) this.tree._keyCache.set(seq, key)
      return key
    } finally {
      this.tree._cacheLock.exit(seq)
    }
  }

  async _getNode(seq) {
    const cached =
      this.tree._nodeCache !== null && this.core.fork === this.tree.core.fork
        ? this.tree._nodeCache.get(seq)
        : null
    if (cached !== null) return cached
    const entry = await this.core.get(seq, {
      ...this.options,
      valueEncoding: Node
    })
    if (entry === null) throw BLOCK_NOT_AVAILABLE()
    const wrap = copyEntry(entry)
    if (this.core.fork === this.tree.core.fork && this.tree._nodeCache !== null) {
      this.tree._nodeCache.set(seq, wrap)
    }
    return wrap
  }

  async getBlock(seq) {
    if (this.rootSeq === 0) this.rootSeq = seq
    await this.tree._cacheLock.enter(seq)

    try {
      return await this._getBlock(seq)
    } finally {
      this.tree._cacheLock.exit(seq)
    }
  }

  async _getBlock(seq) {
    let b = this.blocks && this.blocks.get(seq)
    if (b) return b
    this.onseq(seq)
    const entry = await this._getNode(seq)
    b = this.blocks && this.blocks.get(seq)
    if (b) return b
    b = new BlockEntry(seq, this, entry)
    if (this.blocks && this.blocks.size - this.length < this.maxBlocksCached) {
      this.blocks.set(seq, b)
    }
    return b
  }

  _onwait(key) {
    this.options.onwait = null
    this.tree.extension.get(this.rootSeq + 1, key)
  }

  _getEncoding(opts) {
    if (!opts) return this.encoding
    return {
      key: opts.keyEncoding ? codecs(opts.keyEncoding) : this.encoding.key,
      value: opts.valueEncoding ? codecs(opts.valueEncoding) : this.encoding.value
    }
  }

  peek(range, opts) {
    return iteratorPeek(this.createRangeIterator(range, { ...opts, limit: 1 }))
  }

  createRangeIterator(range, opts = {}) {
    // backwards compat range arg
    opts = opts ? { ...opts, ...range } : range

    const encoding = this._getEncoding(opts)
    return new RangeIterator(
      this,
      encoding,
      encRange(encoding.key, { ...opts, sub: this.tree._sub })
    )
  }

  createReadStream(range, opts) {
    const signal = (opts && opts.signal) || null
    return iteratorToStream(this.createRangeIterator(range, opts), signal)
  }

  async getBySeq(seq, opts) {
    const encoding = this._getEncoding(opts)

    try {
      const block = (await this.getBlock(seq)).final(encoding)
      return { key: block.key, value: block.value }
    } finally {
      await this._closeSnapshot()
    }
  }

  async get(key, opts) {
    const encoding = this._getEncoding(opts)
    const finalize = opts ? opts.finalize !== false : true

    try {
      return await this._get(key, encoding, finalize)
    } finally {
      await this._closeSnapshot()
    }
  }

  async _get(key, encoding, finalize) {
    key = enc(encoding.key, key)

    if (this.tree.extension !== null && this.options.extension !== false) {
      this.options.onwait = this._onwait.bind(this, key)
    }

    let node = await this.getRoot(false)
    if (!node) return null

    while (true) {
      if (node.block.isTarget(key)) {
        return node.block.isDeletion() ? null : finalize ? node.block.final(encoding) : node.block
      }

      let s = 0
      let e = node.keys.length
      let c

      while (s < e) {
        const mid = (s + e) >> 1

        c = b4a.compare(key, await node.getKey(mid))

        if (c === 0) {
          const block = await this.getBlock(node.keys[mid].seq)
          return finalize ? block.final(encoding) : block
        }

        if (c < 0) e = mid
        else s = mid + 1
      }

      if (!node.children.length) return null

      const i = c < 0 ? e : s
      node = await node.getChildNode(i)
    }
  }

  async links(key, seq) {
    let node = await this.getRoot(false)
    if (!node) return false

    if (node.block.seq === seq) return true

    while (true) {
      if (node.block.isTarget(key)) return false

      let s = 0
      let e = node.keys.length
      let c

      while (s < e) {
        const mid = (s + e) >> 1

        if (node.keys[mid].seq === seq) return true
        c = b4a.compare(key, await node.getKey(mid))

        if (c === 0) return false

        if (c < 0) e = mid
        else s = mid + 1
      }

      if (!node.children.length) return false

      const i = c < 0 ? e : s
      node = await node.getChildNode(i)
      if (node.block.seq === seq) return true
    }
  }

  async put(key, value, opts) {
    const release = this.batchLock ? await this.batchLock() : null

    const cas = (opts && opts.cas) || null
    const encoding = this._getEncoding(opts)

    if (!this.locked) await this.lock()
    if (!release) return this._put(key, value, encoding, cas)

    try {
      return await this._put(key, value, encoding, cas)
    } finally {
      release()
    }
  }

  async _put(key, value, encoding, cas) {
    const newNode = {
      seq: 0,
      key,
      value
    }
    key = enc(encoding.key, key)
    value = enc(encoding.value, value)

    const stack = []

    let root
    let node = (root = await this.getRoot(true))
    if (!node) node = root = TreeNode.create(null)

    const seq = (newNode.seq = this.core.length + this.length)
    const target = new Key(seq, key)

    while (node.children.length) {
      stack.push(node)
      node.changed = true // changed, but compressible

      let s = 0
      let e = node.keys.length
      let c

      while (s < e) {
        const mid = (s + e) >> 1
        c = b4a.compare(target.value, await node.getKey(mid))

        if (c === 0) {
          if (cas) {
            const prev = await node.getKeyNode(mid)
            if (!(await cas(prev.final(encoding), newNode))) return this._unlockMaybe()
          }
          if (!this.tree.alwaysDuplicate) {
            const prev = await node.getKeyNode(mid)
            if (sameValue(prev.value, value)) return this._unlockMaybe()
          }
          node.setKey(mid, target)
          return this._append(root, seq, key, value)
        }

        if (c < 0) e = mid
        else s = mid + 1
      }

      const i = c < 0 ? e : s
      node = await node.getChildNode(i)
    }

    let needsSplit = !(await node.insertKey(target, value, null, newNode, encoding, cas))
    if (!node.changed) return this._unlockMaybe()

    while (needsSplit) {
      const parent = stack.pop()
      const { median, right } = await node.split()

      if (parent) {
        needsSplit = !(await parent.insertKey(median, value, right, null, encoding, null))
        node = parent
      } else {
        root = TreeNode.create(node.block)
        root.changed = true
        root.keys.push(median)
        root.children.push(new Child(0, 0, node), new Child(0, 0, right))
        needsSplit = false
      }
    }

    return this._append(root, seq, key, value)
  }

  async del(key, opts) {
    const release = this.batchLock ? await this.batchLock() : null
    const cas = (opts && opts.cas) || null
    const encoding = this._getEncoding(opts)

    if (!this.locked) await this.lock()
    if (!release) return this._del(key, encoding, cas)

    try {
      return await this._del(key, encoding, cas)
    } finally {
      release()
    }
  }

  async _del(key, encoding, cas) {
    const delNode = {
      seq: 0,
      key,
      value: null
    }

    key = enc(encoding.key, key)

    const stack = []

    let node = await this.getRoot(true)
    if (!node) return this._unlockMaybe()

    const seq = (delNode.seq = this.core.length + this.length)

    while (true) {
      stack.push(node)

      let s = 0
      let e = node.keys.length
      let c

      while (s < e) {
        const mid = (s + e) >> 1
        c = b4a.compare(key, await node.getKey(mid))

        if (c === 0) {
          if (cas) {
            const prev = await node.getKeyNode(mid)
            if (!(await cas(prev.final(encoding), delNode))) return this._unlockMaybe()
          }
          if (node.children.length) await setKeyToNearestLeaf(node, mid, stack)
          else node.removeKey(mid)
          // we mark these as changed late, so we don't rewrite them if it is a 404
          for (const node of stack) node.changed = true
          return this._append(await rebalance(stack), seq, key, null)
        }

        if (c < 0) e = mid
        else s = mid + 1
      }

      if (!node.children.length) return this._unlockMaybe()

      const i = c < 0 ? e : s
      node = await node.getChildNode(i)
    }
  }

  async _closeSnapshot() {
    if (this.isSnapshot) {
      await this.core.close()
      this._finalize()
    }
  }

  async close() {
    if (this.isSnapshot) return this._closeSnapshot()

    this.root = null
    if (this.blocks) this.blocks.clear()
    this.length = 0
    this._unlock()
  }

  destroy() {
    // compat, remove later
    this.close().catch(noop)
  }

  toBlocks() {
    if (this.appending) return this.appending

    const batch = new Array(this.length)

    for (let i = 0; i < this.length; i++) {
      const seq = this.core.length + i
      const { pendingIndex, key, value } = this.blocks.get(seq)

      if (i < this.length - 1) {
        pendingIndex[0] = null
        let j = 0

        while (j < pendingIndex.length) {
          const idx = pendingIndex[j]
          if (idx !== null && idx.seq === seq) {
            idx.offset = j++
            continue
          }
          if (j === pendingIndex.length - 1) pendingIndex.pop()
          else pendingIndex[j] = pendingIndex.pop()
        }
      }

      batch[i] = Node.encode({
        key,
        value,
        index: deflate(pendingIndex)
      })
    }

    this.appending = batch
    return batch
  }

  flush() {
    if (!this.length) return this.close()

    const batch = this.toBlocks()

    this.root = null
    this.blocks.clear()
    this.length = 0

    return this._appendBatch(batch)
  }

  _unlockMaybe() {
    if (this.autoFlush) this._unlock()
  }

  _unlock() {
    const locked = this.locked
    this.locked = null
    if (locked !== null) locked()
    this._finalize()
  }

  _finalize() {
    // technically finalize can be called more than once, so here we just check if we already have been removed
    if (this.index >= this.tree._batches.length || this.tree._batches[this.index] !== this) return
    const top = this.tree._batches.pop()
    if (top === this) return
    top.index = this.index
    this.tree._batches[top.index] = top
  }

  _append(root, seq, key, value) {
    const index = []
    root.indexChanges(index, seq)
    index[0] = new Child(seq, 0, root)

    if (!this.autoFlush) {
      const block = new BatchEntry(seq, this, key, value, index)
      root.block = block
      this.root = root
      this.length++
      this.blocks.set(seq, block)

      root.updateChildren(seq, block)
      return
    }

    return this._appendBatch(
      Node.encode({
        key,
        value,
        index: deflate(index)
      })
    )
  }

  async _appendBatch(raw) {
    try {
      await this.core.append(raw)
    } finally {
      this._unlock()
    }
  }
}

class EntryWatcher extends ReadyResource {
  constructor(bee, key, opts = {}) {
    super()

    this.keyEncoding = opts.keyEncoding || bee.keyEncoding
    this.valueEncoding = opts.valueEncoding || bee.valueEncoding

    this.index = bee._entryWatchers.push(this) - 1
    this.bee = bee

    this.key = key
    this.node = null

    this._forceUpdate = false
    this._debouncedUpdate = debounce(this._processUpdate.bind(this))
  }

  _close() {
    const top = this.bee._entryWatchers.pop()
    if (top !== this) {
      top.index = this.index
      this.bee._entryWatchers[top.index] = top
    }
  }

  _onappend() {
    this._debouncedUpdate()
  }

  _ontruncate() {
    this._forceUpdate = true
    this._debouncedUpdate()
  }

  async _processUpdate() {
    const force = this._forceUpdate
    this._forceUpdate = false

    let newNode
    try {
      newNode = await this.bee.get(this.key, {
        keyEncoding: this.keyEncoding,
        valueEncoding: this.valueEncoding
      })
    } catch (e) {
      if (e.code === 'SNAPSHOT_NOT_AVAILABLE') {
        // There was a truncate event before the get resolved
        // So this handler will run again anyway
        return
      } else if (this.bee.closing) {
        this.close().catch(safetyCatch)
        return
      }
      this.emit('error', e)
      return
    }

    if (force || newNode?.seq !== this.node?.seq) {
      this.node = newNode
      this.emit('update')
    }
  }
}

class Watcher extends ReadyResource {
  constructor(bee, range, opts = {}) {
    super()

    this.keyEncoding = opts.keyEncoding || bee.keyEncoding
    this.valueEncoding = opts.valueEncoding || bee.valueEncoding
    this.index = bee._watchers.push(this) - 1
    this.bee = bee
    this.core = bee.core

    this.latestDiff = 0
    this.range = range
    this.map = opts.map || defaultWatchMap

    this.current = null
    this.previous = null
    this.currentMapped = null
    this.previousMapped = null
    this.stream = null

    this._lock = mutexify()
    this._flowing = false
    this._resolveOnChange = null
    this._differ = opts.differ || defaultDiffer
    this._eager = !!opts.eager
    this._onchange = opts.onchange || null

    this.on('newListener', autoFlowOnUpdate)

    this.ready().catch(safetyCatch)
  }

  async _consume() {
    if (this._flowing) return
    try {
      for await (const _ of this) {
      } // eslint-disable-line
    } catch {}
  }

  async _open() {
    await this.bee.ready()

    const opts = {
      keyEncoding: this.keyEncoding,
      valueEncoding: this.valueEncoding
    }

    // Point from which to start watching
    this.current = this._eager ? this.bee.checkout(1, opts) : this.bee.snapshot(opts)
    await this.current.ready()

    if (this._onchange) {
      if (this._eager) await this._onchange()
      this._consume()
    }
  }

  [Symbol.asyncIterator]() {
    this._flowing = true
    return this
  }

  _ontruncate() {
    this._onappend()
  }

  _onappend() {
    const resolve = this._resolveOnChange
    this._resolveOnChange = null
    if (resolve) resolve()
  }

  async _waitForChanges() {
    if (this.current.version < this.bee.version || this.closing) return

    await new Promise((resolve) => {
      this._resolveOnChange = resolve
    })
  }

  async next() {
    try {
      return await this._next()
    } catch (err) {
      if (this.closing) return { value: undefined, done: true }
      await this.close()
      throw err
    }
  }

  async _next() {
    const release = await this._lock()

    try {
      if (this.closing) return { value: undefined, done: true }

      if (!this.opened) await this.ready()

      while (true) {
        await this._waitForChanges()

        if (this.closing) return { value: undefined, done: true }

        await this._closePrevious()
        this.previous = this.current.snapshot()

        await this._closeCurrent()
        this.current = this.bee.snapshot({
          keyEncoding: this.keyEncoding,
          valueEncoding: this.valueEncoding
        })

        await this.current.ready()
        await this.previous.ready()

        if (this.current.core.fork !== this.previous.core.fork) {
          return await this._yield()
        }

        this.stream = this._differ(this.current, this.previous, this.range)

        try {
          for await (const data of this.stream) {
            // eslint-disable-line
            return await this._yield()
          }
        } finally {
          this.stream = null
        }
      }
    } finally {
      release()
    }
  }

  async _yield() {
    this.currentMapped = this.map(this.current)
    this.previousMapped = this.map(this.previous)

    if (this._onchange) {
      try {
        await this._onchange()
      } catch (err) {
        safetyCatch(err)
      }
    }

    this.emit('update')
    return { done: false, value: [this.currentMapped, this.previousMapped] }
  }

  async return() {
    await this.close()
    return { done: true }
  }

  async _close() {
    const top = this.bee._watchers.pop()
    if (top !== this) {
      top.index = this.index
      this.bee._watchers[top.index] = top
    }

    if (this.stream && !this.stream.destroying) {
      this.stream.destroy()
    }

    this._onappend() // Continue execution being closed

    await this._closeCurrent().catch(safetyCatch)
    await this._closePrevious().catch(safetyCatch)

    const release = await this._lock()
    release()
  }

  destroy() {
    return this.close()
  }

  async _closeCurrent() {
    if (this.currentMapped) await this.currentMapped.close()
    if (this.current) await this.current.close()
    this.current = this.currentMapped = null
  }

  async _closePrevious() {
    if (this.previousMapped) await this.previousMapped.close()
    if (this.previous) await this.previous.close()
    this.previous = this.previousMapped = null
  }
}

function autoFlowOnUpdate(name) {
  if (name === 'update') this._consume()
}

function defaultWatchMap(snapshot) {
  return snapshot
}

async function leafSize(node, goLeft) {
  while (node.children.length) node = await node.getChildNode(goLeft ? 0 : node.children.length - 1)
  return node.keys.length
}

async function setKeyToNearestLeaf(node, index, stack) {
  let [left, right] = await Promise.all([node.getChildNode(index), node.getChildNode(index + 1)])
  const [ls, rs] = await Promise.all([leafSize(left, false), leafSize(right, true)])

  if (ls < rs) {
    // if fewer leaves on the left
    stack.push(right)
    while (right.children.length) stack.push((right = right.children[0].value))
    node.keys[index] = right.keys.shift()
  } else {
    // if fewer leaves on the right
    stack.push(left)
    while (left.children.length) stack.push((left = left.children[left.children.length - 1].value))
    node.keys[index] = left.keys.pop()
  }
}

async function rebalance(stack) {
  const root = stack[0]

  while (stack.length > 1) {
    const node = stack.pop()
    const parent = stack[stack.length - 1]

    if (node.keys.length >= MIN_KEYS) return root

    let { left, index, right } = await node.siblings(parent)

    // maybe borrow from left sibling?
    if (left && left.keys.length > MIN_KEYS) {
      left.changed = true
      node.keys.unshift(parent.keys[index - 1])
      if (left.children.length) node.children.unshift(left.children.pop())
      parent.keys[index - 1] = left.keys.pop()
      return root
    }

    // maybe borrow from right sibling?
    if (right && right.keys.length > MIN_KEYS) {
      right.changed = true
      node.keys.push(parent.keys[index])
      if (right.children.length) node.children.push(right.children.shift())
      parent.keys[index] = right.keys.shift()
      return root
    }

    // merge node with another sibling
    if (left) {
      index--
      right = node
    } else {
      left = node
    }

    left.merge(right, parent.keys[index])
    parent.removeKey(index)
  }

  // check if the tree shrunk
  if (!root.keys.length && root.children.length) return root.getChildNode(0)
  return root
}

function iteratorToStream(ite, signal) {
  let done
  let closing

  const rs = new Readable({
    signal,
    open(cb) {
      done = cb
      ite.open().then(fin, fin)
    },
    read(cb) {
      done = cb
      ite.next().then(push, fin)
    },
    predestroy() {
      closing = ite.close()
      closing.catch(noop)
    },
    destroy(cb) {
      done = cb
      if (!closing) closing = ite.close()
      closing.then(fin, fin)
    }
  })

  return rs

  function fin(err) {
    done(err)
  }

  function push(val) {
    rs.push(val)
    done(null)
  }
}

async function iteratorPeek(ite) {
  try {
    await ite.open()
    return await ite.next()
  } finally {
    await ite.close()
  }
}

function encRange(e, opts) {
  if (!e) return opts

  if (e.encodeRange) {
    const r = e.encodeRange({
      gt: opts.gt,
      gte: opts.gte,
      lt: opts.lt,
      lte: opts.lte
    })
    opts.gt = r.gt
    opts.gte = r.gte
    opts.lt = r.lt
    opts.lte = r.lte
    return opts
  }

  if (opts.gt !== undefined) opts.gt = enc(e, opts.gt)
  if (opts.gte !== undefined) opts.gte = enc(e, opts.gte)
  if (opts.lt !== undefined) opts.lt = enc(e, opts.lt)
  if (opts.lte !== undefined) opts.lte = enc(e, opts.lte)
  if (opts.sub && !opts.gt && !opts.gte) opts.gt = enc(e, SEP)
  if (opts.sub && !opts.lt && !opts.lte) opts.lt = bump(enc(e, EMPTY))

  return opts
}

function bump(key) {
  // key should have been copied by enc above before hitting this
  key[key.length - 1]++
  return key
}

function enc(e, v) {
  if (v === undefined || v === null) return null
  if (e !== null) return e.encode(v)
  if (typeof v === 'string') return b4a.from(v)
  return v
}

function prefixEncoding(prefix, keyEncoding) {
  return {
    encode(key) {
      return b4a.concat([prefix, b4a.isBuffer(key) ? key : enc(keyEncoding, key)])
    },
    decode(key) {
      const sliced = key.slice(prefix.length, key.length)
      return keyEncoding ? keyEncoding.decode(sliced) : sliced
    }
  }
}

function copyEntry(entry) {
  let key = entry.key
  let value = entry.value
  let index = entry.index

  // key, value and index all refer to the same buffer (one hypercore block)
  // If together they are larger than half the buffer's byteLength,
  // this means that they got their own private slab (see Buffer.allocUnsafe docs)
  // so no need to unslab
  const size =
    key.byteLength +
    (value === null ? 0 : value.byteLength) +
    (index === null ? 0 : index.byteLength)
  if (2 * size < key.buffer.byteLength) {
    const [newKey, newValue, newIndex] = unslabAll([entry.key, entry.value, entry.index])
    key = newKey
    value = newValue
    index = newIndex
  }

  return {
    key,
    value,
    index,
    inflated: null
  }
}

function defaultDiffer(currentSnap, previousSnap, opts) {
  return currentSnap.createDiffStream(previousSnap, opts)
}

function toNull() {
  return null
}

function getBackingCore(core) {
  if (core.core) return core
  if (core.getBackingCore) return core.getBackingCore().session
  return null
}

function sameValue(a, b) {
  return a === b || (a !== null && b !== null && b4a.equals(a, b))
}

function noop() {}

function getExtension(db, opts) {
  if (opts.extension === false) return null
  if (opts.extension && opts.extension !== true) return opts.extension
  return Extension.register(db)
}

async function isLinked(batch, block) {
  const seq = block.seq
  block.inflate()

  const keys = [block.key]
  const wait = batch.options.wait

  for (const l of block.index.levels) {
    if (!l.keys.length) continue
    batch.options.wait = false
    try {
      keys.push(await batch.getKey(l.keys[0].seq))
    } catch {}
    batch.options.wait = wait
  }

  for (const k of keys) {
    if (await batch.links(k, seq)) return true
  }

  if (batch.core.closing) throw new Error('Core is closed')

  return false
}

module.exports = Hyperbee
const b4a = require('b4a')

class SubTree {
  constructor(node, parent) {
    this.node = node
    this.parent = parent

    this.isKey = node.children.length === 0
    this.i = this.isKey ? 1 : 0
    this.n = 0

    const child = this.isKey ? null : this.node.children[0]
    this.seq = child !== null ? child.seq : this.node.keys[0].seq
    this.offset = child !== null ? child.offset : 0
  }

  next() {
    this.i++
    this.isKey = (this.i & 1) === 1
    if (!this.isKey && !this.node.children.length) this.i++
    return this.update()
  }

  async bisect(key, incl) {
    let s = 0
    let e = this.node.keys.length
    let c

    while (s < e) {
      const mid = (s + e) >> 1
      c = cmp(key, await this.node.getKey(mid))

      if (c === 0) {
        if (incl) this.i = mid * 2 + 1
        else this.i = mid * 2 + (this.node.children.length ? 2 : 3)
        return true
      }

      if (c < 0) e = mid
      else s = mid + 1
    }

    const i = c < 0 ? e : s
    this.i = 2 * i + (this.node.children.length ? 0 : 1)
    return this.node.children.length === 0
  }

  update() {
    this.isKey = (this.i & 1) === 1
    this.n = this.i >> 1
    if (this.n >= (this.isKey ? this.node.keys.length : this.node.children.length)) return false
    const child = this.isKey ? null : this.node.children[this.n]
    this.seq = child !== null ? child.seq : this.node.keys[this.n].seq
    this.offset = child !== null ? child.offset : 0
    return true
  }

  async key() {
    return this.n < this.node.keys.length
      ? this.node.getKey(this.n)
      : this.parent && this.parent.key()
  }

  async compare(tree) {
    const [a, b] = await Promise.all([this.key(), tree.key()])
    return cmp(a, b)
  }
}

class TreeIterator {
  constructor(batch, opts) {
    this.batch = batch
    this.stack = []
    this.lt = opts.lt || opts.lte || null
    this.lte = !!opts.lte
    this.gt = opts.gt || opts.gte || null
    this.gte = !!opts.gte
    this.seeking = !!this.gt
    this.encoding = opts.encoding || batch.encoding
  }

  async open() {
    const node = await this.batch.getRoot(false)
    if (!node || !node.keys.length) return
    const tree = new SubTree(node, null)
    if (this.seeking && !(await this._seek(tree))) return
    this.stack.push(tree)
  }

  async _seek(tree) {
    const done = await tree.bisect(this.gt, this.gte)
    const oob = !tree.update()
    if (done || oob) {
      this.seeking = false
      if (oob) return false
    }
    return true
  }

  peek() {
    if (!this.stack.length) return null
    return this.stack[this.stack.length - 1]
  }

  skip() {
    if (!this.stack.length) return
    if (!this.stack[this.stack.length - 1].next()) this.stack.pop()
  }

  async nextKey() {
    let n = null
    while (this.stack.length && n === null) n = await this.next()
    if (n === null) return null
    if (!this.lt) return n.final(this.encoding)

    const c = cmp(n.key, this.lt)
    if (this.lte ? c <= 0 : c < 0) return n.final(this.encoding)
    this.stack = []
    return null
  }

  async next() {
    if (!this.stack.length) return null

    const top = this.stack[this.stack.length - 1]
    const { isKey, n, seq } = top

    if (!top.next()) {
      this.stack.pop()
    }

    if (isKey) {
      this.seeking = false
      return this.batch.getBlock(seq)
    }

    const child = await top.node.getChildNode(n)
    top.node.children[n] = null // unlink to save memory
    const tree = new SubTree(child, top)
    if (this.seeking && !(await this._seek(tree))) return null
    this.stack.push(tree)

    return null
  }

  close() {
    return this.batch._closeSnapshot()
  }
}

module.exports = class DiffIterator {
  constructor(left, right, opts = {}) {
    this.left = new TreeIterator(left, opts)
    this.right = new TreeIterator(right, opts)
    this.limit = typeof opts.limit === 'number' ? opts.limit : -1
  }

  async open() {
    await Promise.all([this.left.open(), this.right.open()])
  }

  async next() {
    if (this.limit === 0) return null
    const res = await this._next()
    if (!res || (res.left === null && res.right === null)) return null
    this.limit--
    return res
  }

  async _next() {
    const a = this.left
    const b = this.right

    while (true) {
      const [l, r] = await Promise.all([a.peek(), b.peek()])

      if (!l && !r) return null
      if (!l) return { left: null, right: await b.nextKey() }
      if (!r) return { left: await a.nextKey(), right: null }

      if (l.seq === r.seq && l.isKey === r.isKey && l.offset === r.offset) {
        a.skip()
        b.skip()
        continue
      }

      const c = await l.compare(r)

      if (l.isKey && !r.isKey) {
        await b.next()
        continue
      }

      if (!l.isKey && r.isKey) {
        await a.next()
        continue
      }

      if (l.isKey && r.isKey) {
        if (c === 0) return { left: await a.nextKey(), right: await b.nextKey() }
        if (c < 0) return { left: await a.nextKey(), right: null }
        return { left: null, right: await b.nextKey() }
      }

      if (c === 0) await Promise.all([a.next(), b.next()])
      else if (c < 0) await b.next()
      else await a.next()
    }
  }

  async close() {
    await Promise.all([this.left.close(), this.right.close()])
  }
}

function cmp(a, b) {
  if (!a) return b ? 1 : 0
  if (!b) return a ? -1 : 0
  return b4a.compare(a, b)
}
module.exports = class HistoryIterator {
  constructor(batch, opts = {}) {
    this.batch = batch
    this.options = opts
    this.live = !!opts.live
    this.gte = 0
    this.lt = 0
    this.reverse = !!opts.reverse
    this.limit = typeof opts.limit === 'number' ? opts.limit : -1
    this.encoding = opts.encoding || batch.encoding
    if (this.live && this.reverse) {
      throw new Error('Cannot have both live and reverse enabled')
    }
  }

  async open() {
    await this.batch.getRoot(false) // does the update dance
    this.gte = gte(this.options, this.batch.version)
    this.lt = this.live ? Infinity : lt(this.options, this.batch.version)
  }

  async next() {
    if (this.limit === 0) return null
    if (this.limit > 0) this.limit--

    if (this.gte >= this.lt) return null

    if (this.reverse) {
      if (this.lt <= 1) return null
      return final(await this.batch.getBlock(--this.lt), this.encoding)
    }

    return final(await this.batch.getBlock(this.gte++), this.encoding)
  }

  close() {
    return this.batch._closeSnapshot()
  }
}

function final(node, encoding) {
  const type = node.isDeletion() ? 'del' : 'put'
  return { type, ...node.final(encoding) }
}

function gte(opts, version) {
  if (opts.gt) return (opts.gt < 0 ? opts.gt + version : opts.gt) + 1
  const gte = opts.gte || opts.since || 1
  return gte < 0 ? gte + version : gte
}

function lt(opts, version) {
  if (opts.lte === 0 || opts.lt === 0 || opts.end === 0) return 0
  if (opts.lte) return (opts.lte < 0 ? opts.lte + version : opts.lte) + 1
  const lt = opts.lt || opts.end || version
  return lt < 0 ? lt + version : lt
}
module.exports = class LocalBlocksIterator {
  constructor(batch, opts = {}) {
    this.batch = batch
    this.options = opts
    this.gte = 0
    this.lt = 0
    this.limit = typeof opts.limit === 'number' ? opts.limit : -1
  }

  async open() {
    await this.batch.getRoot(false) // does the update dance
    this.gte = gte(this.options, this.batch.version)
    this.lt = lt(this.options, this.batch.version)
  }

  async next() {
    if (this.limit === 0) return null
    if (this.limit > 0) this.limit--

    while (this.gte < this.lt) {
      try {
        return await this.batch.getBlock(this.gte++)
      } catch {
        continue
      }
    }

    return null
  }

  close() {
    return this.batch._closeSnapshot()
  }
}

function gte(opts, version) {
  if (opts.gt) return (opts.gt < 0 ? opts.gt + version : opts.gt) + 1
  const gte = opts.gte || opts.since || 1
  return gte < 0 ? gte + version : gte
}

function lt(opts, version) {
  if (opts.lte === 0 || opts.lt === 0 || opts.end === 0) return 0
  if (opts.lte) return (opts.lte < 0 ? opts.lte + version : opts.lte) + 1
  const lt = opts.lt || opts.end || version
  return lt < 0 ? lt + version : lt
}
const b4a = require('b4a')

module.exports = class RangeIterator {
  constructor(batch, encoding, opts = {}) {
    this.batch = batch
    this.stack = []
    this.opened = false
    this.encoding = encoding || batch.encoding

    this._limit = typeof opts.limit === 'number' ? opts.limit : -1
    this._gIncl = !opts.gt
    this._gKey = opts.gt || opts.gte || null
    this._lIncl = !opts.lt
    this._lKey = opts.lt || opts.lte || null
    this._reverse = !!opts.reverse
    this._version = 0
    this._checkpoint = opts.checkpoint && opts.checkpoint.length ? opts.checkpoint : null
    this._nexting = false
    this._closed = false
  }

  snapshot(version = this.batch.version) {
    const checkpoint = []
    for (const s of this.stack) {
      let { node, i } = s
      if (this._nexting && s === this.stack[this.stack.length - 1]) {
        i = this._reverse ? i + 1 : i - 1
      }
      if (!node.block) continue
      if (i < 0) continue
      checkpoint.push(node.block.seq, node.offset, i)
    }

    return {
      version,
      gte: this._gIncl ? this._gKey : null,
      gt: this._gIncl ? null : this._gKey,
      lte: this._lIncl ? this._lKey : null,
      lt: this._lIncl ? null : this._lKey,
      limit: this._limit,
      reverse: this._reverse,
      ended: this.opened && !checkpoint.length,
      checkpoint: this.opened ? checkpoint : []
    }
  }

  async open() {
    await this._open()
    this.opened = true
  }

  async _open() {
    if (this._checkpoint) {
      for (let j = 0; j < this._checkpoint.length; j += 3) {
        const seq = this._checkpoint[j]
        const offset = this._checkpoint[j + 1]
        const i = this._checkpoint[j + 2]
        this.stack.push({
          node: (await this.batch.getBlock(seq)).getTreeNode(offset),
          i
        })
      }
      return
    }

    this._nexting = true

    let node = await this.batch.getRoot(false)
    if (!node) {
      this._nexting = false
      return
    }

    const incl = this._reverse ? this._lIncl : this._gIncl
    const start = this._reverse ? this._lKey : this._gKey

    if (!start) {
      this.stack.push({ node, i: this._reverse ? node.keys.length << 1 : 0 })
      this._nexting = false
      this._preloadQuery()
      return
    }

    while (true) {
      const entry = { node, i: this._reverse ? node.keys.length << 1 : 0 }

      let s = 0
      let e = node.keys.length
      let c

      while (s < e) {
        const mid = (s + e) >> 1
        c = b4a.compare(start, await node.getKey(mid))

        if (c === 0) {
          if (incl) entry.i = mid * 2 + 1
          else entry.i = mid * 2 + (this._reverse ? 0 : 2)
          this.stack.push(entry)
          this._nexting = false
          this._preloadQuery()
          return
        }

        if (c < 0) e = mid
        else s = mid + 1
      }

      const i = c < 0 ? e : s
      entry.i = 2 * i + (this._reverse ? -1 : 1)

      if (entry.i >= 0 && entry.i <= node.keys.length << 1) this.stack.push(entry)
      if (!node.children.length) {
        this._nexting = false
        this._preloadQuery()
        return
      }

      node = await node.getChildNode(i)
    }
  }

  _preloadQuery() {
    const max = { nodes: 0, max: 2048 }

    if (this._limit === -1 && !this._reverse && this.stack.length) {
      for (const s of this.stack) {
        const k = (s.i - (s.i & 1)) / 2
        this._preload(s.node, k + 1, this._lKey, max).catch(noop)
      }
    }
  }

  async _preload(node, i, end, max) {
    for (; i < node.keys.length; i++) {
      const key = node.keys[i]
      const block = await this.batch.getBlock(key.seq)
      if (this._closed) return
      const c = end ? b4a.compare(block.key, end) : -1
      if (c >= 0 || max.nodes >= max.max || i >= node.children.length) return
      max.nodes++
      const next = await node.getChildNode(i)
      if (this._closed) return
      this._preload(next, 0, end, max).catch(noop)
    }

    if (node.children.length && max.nodes < max.max) {
      const next = await node.getChildNode(node.children.length - 1)
      if (this._closed) return
      this._preload(next, 0, end, max).catch(noop)
    }
  }

  async next() {
    // TODO: this nexting flag is only needed if someone asks for a snapshot during
    // a lookup (ie the extension, pretty important...).
    // A better solution would be to refactor this so top.i is incremented eagerly
    // to get the current block instead of the way it is done now (++i vs i++)
    this._nexting = true

    const end = this._reverse ? this._gKey : this._lKey
    const incl = this._reverse ? this._gIncl : this._lIncl

    while (this.stack.length && (this._limit === -1 || this._limit > 0)) {
      const top = this.stack[this.stack.length - 1]
      const isKey = (top.i & 1) === 1
      const n = this._reverse ? (top.i < 0 ? top.node.keys.length : top.i-- >> 1) : top.i++ >> 1

      if (!isKey) {
        if (!top.node.children.length) continue
        const node = await top.node.getChildNode(n)
        if (top.node.block.seq < this.batch.core.length) {
          top.node.children[n].value = null // unlink it to save memory
        }
        this.stack.push({ i: this._reverse ? node.keys.length << 1 : 0, node })
        continue
      }

      if (n >= top.node.keys.length) {
        this.stack.pop()
        continue
      }

      const key = top.node.keys[n]
      const block = await this.batch.getBlock(key.seq)
      if (end) {
        const c = b4a.compare(block.key, end)
        if (c === 0 ? !incl : this._reverse ? c < 0 : c > 0) {
          this._limit = 0
          break
        }
      }
      if (this._limit > 0) this._limit--
      this._nexting = false
      return block.final(this.encoding)
    }

    this._nexting = false
    return null
  }

  close() {
    this._closed = true
    return this.batch._closeSnapshot()
  }
}

function noop() {}
const { Extension } = require('./messages')

// const MAX_ACTIVE = 32
const FLUSH_BATCH = 128
const MAX_PASSIVE_BATCH = 2048
const MAX_ACTIVE_BATCH = MAX_PASSIVE_BATCH + FLUSH_BATCH

class Batch {
  constructor(outgoing, from) {
    this.blocks = []
    this.start = 0
    this.end = 0
    this.outgoing = outgoing
    this.from = from
  }

  push(seq) {
    const len = this.blocks.push(seq)
    if (len === 1 || seq < this.start) this.start = seq
    if (len === 1 || seq >= this.end) this.end = seq + 1
    if (len >= FLUSH_BATCH) {
      this.send()
      this.clear()
    }
  }

  send() {
    if (!this.blocks.length) return
    this.outgoing.send(
      Extension.encode({
        cache: { blocks: this.blocks, start: this.start, end: this.end }
      }),
      this.from
    )
  }

  clear() {
    this.start = this.end = 0
    this.blocks = []
  }
}

class HyperbeeExtension {
  constructor(db) {
    this.encoding = null
    this.outgoing = null
    this.db = db
    this.active = 0
  }

  get(version, key) {
    this.outgoing.broadcast(Extension.encode({ get: { version, key } }))
  }

  iterator(snapshot) {
    if (snapshot.ended) return
    if (snapshot.limit === 0) return
    if (snapshot.limit === -1) snapshot.limit = 0
    this.outgoing.broadcast(Extension.encode({ iterator: snapshot }))
  }

  onmessage(buf, from) {
    // TODO: handle max active extension messages
    // this.active++

    const message = decode(buf)
    if (!message) return

    if (message.cache) this.oncache(message.cache, from)
    if (message.get) this.onget(message.get, from)
    if (message.iterator) this.oniterator(message.iterator, from)
  }

  oncache(message, from) {
    if (!message.blocks.length) return
    this.db.core.download(message)
  }

  onget(message, from) {
    if (!message.version || message.version > this.db.version) return

    const b = new Batch(this.outgoing, from)
    const db = this.db.checkout(message.version)

    db.get(message.key, {
      extension: false,
      wait: false,
      update: false,
      onseq
    }).then(done, done)

    function done() {
      db.close().catch(noop)
      b.send()
    }

    function onseq(seq) {
      b.push(seq)
    }
  }

  async oniterator(message, from) {
    if (!message.version || message.version > this.db.version) return

    const b = new Batch(this.outgoing, from)
    const seqs = new Set()

    let skip = message.checkpoint.length
    let work = 0

    const db = this.db.checkout(message.version)
    const ite = db.createRangeIterator({
      ...message,
      wait: false,
      extension: false,
      update: false,
      limit: message.limit === 0 ? -1 : message.limit,
      onseq(seq) {
        if (skip && skip--) return
        if (seqs.has(seq)) return
        work++
        seqs.add(seq)
        b.push(seq)
      }
    })

    try {
      await ite.open()
      // eslint-disable-next-line no-unmodified-loop-condition
      while (work < MAX_ACTIVE_BATCH) {
        if (!(await ite.next())) break
      }
    } catch (_) {
      // do nothing
    } finally {
      ite.close().catch(noop)
      db.close().catch(noop)
      b.send()
    }
  }

  static register(db) {
    const e = new this(db)
    e.outgoing = db.core.registerExtension('hyperbee', e)
    return e
  }
}

HyperbeeExtension.BATCH_SIZE = MAX_PASSIVE_BATCH

module.exports = HyperbeeExtension

function decode(buf) {
  try {
    return Extension.decode(buf)
  } catch (err) {
    return null
  }
}

function noop() {}
// This file is auto generated by the protocol-buffers compiler

/* eslint-disable quotes */
/* eslint-disable indent */
/* eslint-disable no-redeclare */
/* eslint-disable camelcase */
/* eslint-disable no-var */

// Remember to `npm install --save protocol-buffers-encodings`
var encodings = require('protocol-buffers-encodings')
var b4a = require('b4a')
var varint = encodings.varint
var skip = encodings.skip

var YoloIndex = exports.YoloIndex = {
  buffer: true,
  encodingLength: null,
  encode: null,
  decode: null
}

var Header = exports.Header = {
  buffer: true,
  encodingLength: null,
  encode: null,
  decode: null
}

var Node = exports.Node = {
  buffer: true,
  encodingLength: null,
  encode: null,
  decode: null
}

var Extension = exports.Extension = {
  buffer: true,
  encodingLength: null,
  encode: null,
  decode: null
}

defineYoloIndex()
defineHeader()
defineNode()
defineExtension()

function defineYoloIndex () {
  var Level = YoloIndex.Level = {
    buffer: true,
    encodingLength: null,
    encode: null,
    decode: null
  }

  defineLevel()

  function defineLevel () {
    Level.encodingLength = encodingLength
    Level.encode = encode
    Level.decode = decode

    function encodingLength (obj) {
      var length = 0
      if (defined(obj.keys)) {
        var packedLen = 0
        for (var i = 0; i < obj.keys.length; i++) {
          if (!defined(obj.keys[i])) continue
          var len = encodings.varint.encodingLength(obj.keys[i])
          packedLen += len
        }
        if (packedLen) {
          length += 1 + packedLen + varint.encodingLength(packedLen)
        }
      }
      if (defined(obj.children)) {
        var packedLen = 0
        for (var i = 0; i < obj.children.length; i++) {
          if (!defined(obj.children[i])) continue
          var len = encodings.varint.encodingLength(obj.children[i])
          packedLen += len
        }
        if (packedLen) {
          length += 1 + packedLen + varint.encodingLength(packedLen)
        }
      }
      return length
    }

    function encode (obj, buf, offset) {
      if (!offset) offset = 0
      if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
      var oldOffset = offset
      if (defined(obj.keys)) {
        var packedLen = 0
        for (var i = 0; i < obj.keys.length; i++) {
          if (!defined(obj.keys[i])) continue
          packedLen += encodings.varint.encodingLength(obj.keys[i])
        }
        if (packedLen) {
          buf[offset++] = 10
          varint.encode(packedLen, buf, offset)
          offset += varint.encode.bytes
        }
        for (var i = 0; i < obj.keys.length; i++) {
          if (!defined(obj.keys[i])) continue
          encodings.varint.encode(obj.keys[i], buf, offset)
          offset += encodings.varint.encode.bytes
        }
      }
      if (defined(obj.children)) {
        var packedLen = 0
        for (var i = 0; i < obj.children.length; i++) {
          if (!defined(obj.children[i])) continue
          packedLen += encodings.varint.encodingLength(obj.children[i])
        }
        if (packedLen) {
          buf[offset++] = 18
          varint.encode(packedLen, buf, offset)
          offset += varint.encode.bytes
        }
        for (var i = 0; i < obj.children.length; i++) {
          if (!defined(obj.children[i])) continue
          encodings.varint.encode(obj.children[i], buf, offset)
          offset += encodings.varint.encode.bytes
        }
      }
      encode.bytes = offset - oldOffset
      return buf
    }

    function decode (buf, offset, end) {
      if (!offset) offset = 0
      if (!end) end = buf.length
      if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
      var oldOffset = offset
      var obj = {
        keys: [],
        children: []
      }
      while (true) {
        if (end <= offset) {
          decode.bytes = offset - oldOffset
          return obj
        }
        var prefix = varint.decode(buf, offset)
        offset += varint.decode.bytes
        var tag = prefix >> 3
        switch (tag) {
          case 1:
          var packedEnd = varint.decode(buf, offset)
          offset += varint.decode.bytes
          packedEnd += offset
          while (offset < packedEnd) {
            obj.keys.push(encodings.varint.decode(buf, offset))
            offset += encodings.varint.decode.bytes
          }
          break
          case 2:
          var packedEnd = varint.decode(buf, offset)
          offset += varint.decode.bytes
          packedEnd += offset
          while (offset < packedEnd) {
            obj.children.push(encodings.varint.decode(buf, offset))
            offset += encodings.varint.decode.bytes
          }
          break
          default:
          offset = skip(prefix & 7, buf, offset)
        }
      }
    }
  }

  YoloIndex.encodingLength = encodingLength
  YoloIndex.encode = encode
  YoloIndex.decode = decode

  function encodingLength (obj) {
    var length = 0
    if (defined(obj.levels)) {
      for (var i = 0; i < obj.levels.length; i++) {
        if (!defined(obj.levels[i])) continue
        var len = Level.encodingLength(obj.levels[i])
        length += varint.encodingLength(len)
        length += 1 + len
      }
    }
    return length
  }

  function encode (obj, buf, offset) {
    if (!offset) offset = 0
    if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
    var oldOffset = offset
    if (defined(obj.levels)) {
      for (var i = 0; i < obj.levels.length; i++) {
        if (!defined(obj.levels[i])) continue
        buf[offset++] = 10
        varint.encode(Level.encodingLength(obj.levels[i]), buf, offset)
        offset += varint.encode.bytes
        Level.encode(obj.levels[i], buf, offset)
        offset += Level.encode.bytes
      }
    }
    encode.bytes = offset - oldOffset
    return buf
  }

  function decode (buf, offset, end) {
    if (!offset) offset = 0
    if (!end) end = buf.length
    if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
    var oldOffset = offset
    var obj = {
      levels: []
    }
    while (true) {
      if (end <= offset) {
        decode.bytes = offset - oldOffset
        return obj
      }
      var prefix = varint.decode(buf, offset)
      offset += varint.decode.bytes
      var tag = prefix >> 3
      switch (tag) {
        case 1:
        var len = varint.decode(buf, offset)
        offset += varint.decode.bytes
        obj.levels.push(Level.decode(buf, offset, offset + len))
        offset += Level.decode.bytes
        break
        default:
        offset = skip(prefix & 7, buf, offset)
      }
    }
  }
}

function defineHeader () {
  var Metadata = Header.Metadata = {
    buffer: true,
    encodingLength: null,
    encode: null,
    decode: null
  }

  defineMetadata()

  function defineMetadata () {
    Metadata.encodingLength = encodingLength
    Metadata.encode = encode
    Metadata.decode = decode

    function encodingLength (obj) {
      var length = 0
      if (defined(obj.contentFeed)) {
        var len = encodings.bytes.encodingLength(obj.contentFeed)
        length += 1 + len
      }
      if (defined(obj.userData)) {
        var len = encodings.bytes.encodingLength(obj.userData)
        length += 1 + len
      }
      return length
    }

    function encode (obj, buf, offset) {
      if (!offset) offset = 0
      if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
      var oldOffset = offset
      if (defined(obj.contentFeed)) {
        buf[offset++] = 10
        encodings.bytes.encode(obj.contentFeed, buf, offset)
        offset += encodings.bytes.encode.bytes
      }
      if (defined(obj.userData)) {
        buf[offset++] = 18
        encodings.bytes.encode(obj.userData, buf, offset)
        offset += encodings.bytes.encode.bytes
      }
      encode.bytes = offset - oldOffset
      return buf
    }

    function decode (buf, offset, end) {
      if (!offset) offset = 0
      if (!end) end = buf.length
      if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
      var oldOffset = offset
      var obj = {
        contentFeed: null,
        userData: null
      }
      while (true) {
        if (end <= offset) {
          decode.bytes = offset - oldOffset
          return obj
        }
        var prefix = varint.decode(buf, offset)
        offset += varint.decode.bytes
        var tag = prefix >> 3
        switch (tag) {
          case 1:
          obj.contentFeed = encodings.bytes.decode(buf, offset)
          offset += encodings.bytes.decode.bytes
          break
          case 2:
          obj.userData = encodings.bytes.decode(buf, offset)
          offset += encodings.bytes.decode.bytes
          break
          default:
          offset = skip(prefix & 7, buf, offset)
        }
      }
    }
  }

  Header.encodingLength = encodingLength
  Header.encode = encode
  Header.decode = decode

  function encodingLength (obj) {
    var length = 0
    if (!defined(obj.protocol)) throw new Error("protocol is required")
    var len = encodings.string.encodingLength(obj.protocol)
    length += 1 + len
    if (defined(obj.metadata)) {
      var len = Metadata.encodingLength(obj.metadata)
      length += varint.encodingLength(len)
      length += 1 + len
    }
    return length
  }

  function encode (obj, buf, offset) {
    if (!offset) offset = 0
    if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
    var oldOffset = offset
    if (!defined(obj.protocol)) throw new Error("protocol is required")
    buf[offset++] = 10
    encodings.string.encode(obj.protocol, buf, offset)
    offset += encodings.string.encode.bytes
    if (defined(obj.metadata)) {
      buf[offset++] = 18
      varint.encode(Metadata.encodingLength(obj.metadata), buf, offset)
      offset += varint.encode.bytes
      Metadata.encode(obj.metadata, buf, offset)
      offset += Metadata.encode.bytes
    }
    encode.bytes = offset - oldOffset
    return buf
  }

  function decode (buf, offset, end) {
    if (!offset) offset = 0
    if (!end) end = buf.length
    if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
    var oldOffset = offset
    var obj = {
      protocol: "",
      metadata: null
    }
    var found0 = false
    while (true) {
      if (end <= offset) {
        if (!found0) throw new Error("Decoded message is not valid")
        decode.bytes = offset - oldOffset
        return obj
      }
      var prefix = varint.decode(buf, offset)
      offset += varint.decode.bytes
      var tag = prefix >> 3
      switch (tag) {
        case 1:
        obj.protocol = encodings.string.decode(buf, offset)
        offset += encodings.string.decode.bytes
        found0 = true
        break
        case 2:
        var len = varint.decode(buf, offset)
        offset += varint.decode.bytes
        obj.metadata = Metadata.decode(buf, offset, offset + len)
        offset += Metadata.decode.bytes
        break
        default:
        offset = skip(prefix & 7, buf, offset)
      }
    }
  }
}

function defineNode () {
  Node.encodingLength = encodingLength
  Node.encode = encode
  Node.decode = decode

  function encodingLength (obj) {
    var length = 0
    if (!defined(obj.index)) throw new Error("index is required")
    var len = encodings.bytes.encodingLength(obj.index)
    length += 1 + len
    if (!defined(obj.key)) throw new Error("key is required")
    var len = encodings.bytes.encodingLength(obj.key)
    length += 1 + len
    if (defined(obj.value)) {
      var len = encodings.bytes.encodingLength(obj.value)
      length += 1 + len
    }
    return length
  }

  function encode (obj, buf, offset) {
    if (!offset) offset = 0
    if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
    var oldOffset = offset
    if (!defined(obj.index)) throw new Error("index is required")
    buf[offset++] = 10
    encodings.bytes.encode(obj.index, buf, offset)
    offset += encodings.bytes.encode.bytes
    if (!defined(obj.key)) throw new Error("key is required")
    buf[offset++] = 18
    encodings.bytes.encode(obj.key, buf, offset)
    offset += encodings.bytes.encode.bytes
    if (defined(obj.value)) {
      buf[offset++] = 26
      encodings.bytes.encode(obj.value, buf, offset)
      offset += encodings.bytes.encode.bytes
    }
    encode.bytes = offset - oldOffset
    return buf
  }

  function decode (buf, offset, end) {
    if (!offset) offset = 0
    if (!end) end = buf.length
    if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
    var oldOffset = offset
    var obj = {
      index: null,
      key: null,
      value: null
    }
    var found0 = false
    var found1 = false
    while (true) {
      if (end <= offset) {
        if (!found0 || !found1) throw new Error("Decoded message is not valid")
        decode.bytes = offset - oldOffset
        return obj
      }
      var prefix = varint.decode(buf, offset)
      offset += varint.decode.bytes
      var tag = prefix >> 3
      switch (tag) {
        case 1:
        obj.index = encodings.bytes.decode(buf, offset)
        offset += encodings.bytes.decode.bytes
        found0 = true
        break
        case 2:
        obj.key = encodings.bytes.decode(buf, offset)
        offset += encodings.bytes.decode.bytes
        found1 = true
        break
        case 3:
        obj.value = encodings.bytes.decode(buf, offset)
        offset += encodings.bytes.decode.bytes
        break
        default:
        offset = skip(prefix & 7, buf, offset)
      }
    }
  }
}

function defineExtension () {
  var Get = Extension.Get = {
    buffer: true,
    encodingLength: null,
    encode: null,
    decode: null
  }

  var Iterator = Extension.Iterator = {
    buffer: true,
    encodingLength: null,
    encode: null,
    decode: null
  }

  var Cache = Extension.Cache = {
    buffer: true,
    encodingLength: null,
    encode: null,
    decode: null
  }

  defineGet()
  defineIterator()
  defineCache()

  function defineGet () {
    Get.encodingLength = encodingLength
    Get.encode = encode
    Get.decode = decode

    function encodingLength (obj) {
      var length = 0
      if (defined(obj.version)) {
        var len = encodings.varint.encodingLength(obj.version)
        length += 1 + len
      }
      if (defined(obj.key)) {
        var len = encodings.bytes.encodingLength(obj.key)
        length += 1 + len
      }
      return length
    }

    function encode (obj, buf, offset) {
      if (!offset) offset = 0
      if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
      var oldOffset = offset
      if (defined(obj.version)) {
        buf[offset++] = 8
        encodings.varint.encode(obj.version, buf, offset)
        offset += encodings.varint.encode.bytes
      }
      if (defined(obj.key)) {
        buf[offset++] = 18
        encodings.bytes.encode(obj.key, buf, offset)
        offset += encodings.bytes.encode.bytes
      }
      encode.bytes = offset - oldOffset
      return buf
    }

    function decode (buf, offset, end) {
      if (!offset) offset = 0
      if (!end) end = buf.length
      if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
      var oldOffset = offset
      var obj = {
        version: 0,
        key: null
      }
      while (true) {
        if (end <= offset) {
          decode.bytes = offset - oldOffset
          return obj
        }
        var prefix = varint.decode(buf, offset)
        offset += varint.decode.bytes
        var tag = prefix >> 3
        switch (tag) {
          case 1:
          obj.version = encodings.varint.decode(buf, offset)
          offset += encodings.varint.decode.bytes
          break
          case 2:
          obj.key = encodings.bytes.decode(buf, offset)
          offset += encodings.bytes.decode.bytes
          break
          default:
          offset = skip(prefix & 7, buf, offset)
        }
      }
    }
  }

  function defineIterator () {
    Iterator.encodingLength = encodingLength
    Iterator.encode = encode
    Iterator.decode = decode

    function encodingLength (obj) {
      var length = 0
      if (defined(obj.version)) {
        var len = encodings.varint.encodingLength(obj.version)
        length += 1 + len
      }
      if (defined(obj.gte)) {
        var len = encodings.bytes.encodingLength(obj.gte)
        length += 1 + len
      }
      if (defined(obj.gt)) {
        var len = encodings.bytes.encodingLength(obj.gt)
        length += 1 + len
      }
      if (defined(obj.lte)) {
        var len = encodings.bytes.encodingLength(obj.lte)
        length += 1 + len
      }
      if (defined(obj.lt)) {
        var len = encodings.bytes.encodingLength(obj.lt)
        length += 1 + len
      }
      if (defined(obj.limit)) {
        var len = encodings.varint.encodingLength(obj.limit)
        length += 1 + len
      }
      if (defined(obj.reverse)) {
        var len = encodings.bool.encodingLength(obj.reverse)
        length += 1 + len
      }
      if (defined(obj.checkpoint)) {
        var packedLen = 0
        for (var i = 0; i < obj.checkpoint.length; i++) {
          if (!defined(obj.checkpoint[i])) continue
          var len = encodings.varint.encodingLength(obj.checkpoint[i])
          packedLen += len
        }
        if (packedLen) {
          length += 1 + packedLen + varint.encodingLength(packedLen)
        }
      }
      return length
    }

    function encode (obj, buf, offset) {
      if (!offset) offset = 0
      if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
      var oldOffset = offset
      if (defined(obj.version)) {
        buf[offset++] = 8
        encodings.varint.encode(obj.version, buf, offset)
        offset += encodings.varint.encode.bytes
      }
      if (defined(obj.gte)) {
        buf[offset++] = 18
        encodings.bytes.encode(obj.gte, buf, offset)
        offset += encodings.bytes.encode.bytes
      }
      if (defined(obj.gt)) {
        buf[offset++] = 26
        encodings.bytes.encode(obj.gt, buf, offset)
        offset += encodings.bytes.encode.bytes
      }
      if (defined(obj.lte)) {
        buf[offset++] = 34
        encodings.bytes.encode(obj.lte, buf, offset)
        offset += encodings.bytes.encode.bytes
      }
      if (defined(obj.lt)) {
        buf[offset++] = 42
        encodings.bytes.encode(obj.lt, buf, offset)
        offset += encodings.bytes.encode.bytes
      }
      if (defined(obj.limit)) {
        buf[offset++] = 48
        encodings.varint.encode(obj.limit, buf, offset)
        offset += encodings.varint.encode.bytes
      }
      if (defined(obj.reverse)) {
        buf[offset++] = 56
        encodings.bool.encode(obj.reverse, buf, offset)
        offset += encodings.bool.encode.bytes
      }
      if (defined(obj.checkpoint)) {
        var packedLen = 0
        for (var i = 0; i < obj.checkpoint.length; i++) {
          if (!defined(obj.checkpoint[i])) continue
          packedLen += encodings.varint.encodingLength(obj.checkpoint[i])
        }
        if (packedLen) {
          buf[offset++] = 66
          varint.encode(packedLen, buf, offset)
          offset += varint.encode.bytes
        }
        for (var i = 0; i < obj.checkpoint.length; i++) {
          if (!defined(obj.checkpoint[i])) continue
          encodings.varint.encode(obj.checkpoint[i], buf, offset)
          offset += encodings.varint.encode.bytes
        }
      }
      encode.bytes = offset - oldOffset
      return buf
    }

    function decode (buf, offset, end) {
      if (!offset) offset = 0
      if (!end) end = buf.length
      if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
      var oldOffset = offset
      var obj = {
        version: 0,
        gte: null,
        gt: null,
        lte: null,
        lt: null,
        limit: 0,
        reverse: false,
        checkpoint: []
      }
      while (true) {
        if (end <= offset) {
          decode.bytes = offset - oldOffset
          return obj
        }
        var prefix = varint.decode(buf, offset)
        offset += varint.decode.bytes
        var tag = prefix >> 3
        switch (tag) {
          case 1:
          obj.version = encodings.varint.decode(buf, offset)
          offset += encodings.varint.decode.bytes
          break
          case 2:
          obj.gte = encodings.bytes.decode(buf, offset)
          offset += encodings.bytes.decode.bytes
          break
          case 3:
          obj.gt = encodings.bytes.decode(buf, offset)
          offset += encodings.bytes.decode.bytes
          break
          case 4:
          obj.lte = encodings.bytes.decode(buf, offset)
          offset += encodings.bytes.decode.bytes
          break
          case 5:
          obj.lt = encodings.bytes.decode(buf, offset)
          offset += encodings.bytes.decode.bytes
          break
          case 6:
          obj.limit = encodings.varint.decode(buf, offset)
          offset += encodings.varint.decode.bytes
          break
          case 7:
          obj.reverse = encodings.bool.decode(buf, offset)
          offset += encodings.bool.decode.bytes
          break
          case 8:
          var packedEnd = varint.decode(buf, offset)
          offset += varint.decode.bytes
          packedEnd += offset
          while (offset < packedEnd) {
            obj.checkpoint.push(encodings.varint.decode(buf, offset))
            offset += encodings.varint.decode.bytes
          }
          break
          default:
          offset = skip(prefix & 7, buf, offset)
        }
      }
    }
  }

  function defineCache () {
    Cache.encodingLength = encodingLength
    Cache.encode = encode
    Cache.decode = decode

    function encodingLength (obj) {
      var length = 0
      if (!defined(obj.start)) throw new Error("start is required")
      var len = encodings.varint.encodingLength(obj.start)
      length += 1 + len
      if (!defined(obj.end)) throw new Error("end is required")
      var len = encodings.varint.encodingLength(obj.end)
      length += 1 + len
      if (defined(obj.blocks)) {
        var packedLen = 0
        for (var i = 0; i < obj.blocks.length; i++) {
          if (!defined(obj.blocks[i])) continue
          var len = encodings.varint.encodingLength(obj.blocks[i])
          packedLen += len
        }
        if (packedLen) {
          length += 1 + packedLen + varint.encodingLength(packedLen)
        }
      }
      return length
    }

    function encode (obj, buf, offset) {
      if (!offset) offset = 0
      if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
      var oldOffset = offset
      if (!defined(obj.start)) throw new Error("start is required")
      buf[offset++] = 8
      encodings.varint.encode(obj.start, buf, offset)
      offset += encodings.varint.encode.bytes
      if (!defined(obj.end)) throw new Error("end is required")
      buf[offset++] = 16
      encodings.varint.encode(obj.end, buf, offset)
      offset += encodings.varint.encode.bytes
      if (defined(obj.blocks)) {
        var packedLen = 0
        for (var i = 0; i < obj.blocks.length; i++) {
          if (!defined(obj.blocks[i])) continue
          packedLen += encodings.varint.encodingLength(obj.blocks[i])
        }
        if (packedLen) {
          buf[offset++] = 26
          varint.encode(packedLen, buf, offset)
          offset += varint.encode.bytes
        }
        for (var i = 0; i < obj.blocks.length; i++) {
          if (!defined(obj.blocks[i])) continue
          encodings.varint.encode(obj.blocks[i], buf, offset)
          offset += encodings.varint.encode.bytes
        }
      }
      encode.bytes = offset - oldOffset
      return buf
    }

    function decode (buf, offset, end) {
      if (!offset) offset = 0
      if (!end) end = buf.length
      if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
      var oldOffset = offset
      var obj = {
        start: 0,
        end: 0,
        blocks: []
      }
      var found0 = false
      var found1 = false
      while (true) {
        if (end <= offset) {
          if (!found0 || !found1) throw new Error("Decoded message is not valid")
          decode.bytes = offset - oldOffset
          return obj
        }
        var prefix = varint.decode(buf, offset)
        offset += varint.decode.bytes
        var tag = prefix >> 3
        switch (tag) {
          case 1:
          obj.start = encodings.varint.decode(buf, offset)
          offset += encodings.varint.decode.bytes
          found0 = true
          break
          case 2:
          obj.end = encodings.varint.decode(buf, offset)
          offset += encodings.varint.decode.bytes
          found1 = true
          break
          case 3:
          var packedEnd = varint.decode(buf, offset)
          offset += varint.decode.bytes
          packedEnd += offset
          while (offset < packedEnd) {
            obj.blocks.push(encodings.varint.decode(buf, offset))
            offset += encodings.varint.decode.bytes
          }
          break
          default:
          offset = skip(prefix & 7, buf, offset)
        }
      }
    }
  }

  Extension.encodingLength = encodingLength
  Extension.encode = encode
  Extension.decode = decode

  function encodingLength (obj) {
    var length = 0
    if (defined(obj.cache)) {
      var len = Cache.encodingLength(obj.cache)
      length += varint.encodingLength(len)
      length += 1 + len
    }
    if (defined(obj.get)) {
      var len = Get.encodingLength(obj.get)
      length += varint.encodingLength(len)
      length += 1 + len
    }
    if (defined(obj.iterator)) {
      var len = Iterator.encodingLength(obj.iterator)
      length += varint.encodingLength(len)
      length += 1 + len
    }
    return length
  }

  function encode (obj, buf, offset) {
    if (!offset) offset = 0
    if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
    var oldOffset = offset
    if (defined(obj.cache)) {
      buf[offset++] = 10
      varint.encode(Cache.encodingLength(obj.cache), buf, offset)
      offset += varint.encode.bytes
      Cache.encode(obj.cache, buf, offset)
      offset += Cache.encode.bytes
    }
    if (defined(obj.get)) {
      buf[offset++] = 18
      varint.encode(Get.encodingLength(obj.get), buf, offset)
      offset += varint.encode.bytes
      Get.encode(obj.get, buf, offset)
      offset += Get.encode.bytes
    }
    if (defined(obj.iterator)) {
      buf[offset++] = 26
      varint.encode(Iterator.encodingLength(obj.iterator), buf, offset)
      offset += varint.encode.bytes
      Iterator.encode(obj.iterator, buf, offset)
      offset += Iterator.encode.bytes
    }
    encode.bytes = offset - oldOffset
    return buf
  }

  function decode (buf, offset, end) {
    if (!offset) offset = 0
    if (!end) end = buf.length
    if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
    var oldOffset = offset
    var obj = {
      cache: null,
      get: null,
      iterator: null
    }
    while (true) {
      if (end <= offset) {
        decode.bytes = offset - oldOffset
        return obj
      }
      var prefix = varint.decode(buf, offset)
      offset += varint.decode.bytes
      var tag = prefix >> 3
      switch (tag) {
        case 1:
        var len = varint.decode(buf, offset)
        offset += varint.decode.bytes
        obj.cache = Cache.decode(buf, offset, offset + len)
        offset += Cache.decode.bytes
        break
        case 2:
        var len = varint.decode(buf, offset)
        offset += varint.decode.bytes
        obj.get = Get.decode(buf, offset, offset + len)
        offset += Get.decode.bytes
        break
        case 3:
        var len = varint.decode(buf, offset)
        offset += varint.decode.bytes
        obj.iterator = Iterator.decode(buf, offset, offset + len)
        offset += Iterator.decode.bytes
        break
        default:
        offset = skip(prefix & 7, buf, offset)
      }
    }
  }
}

function defined (val) {
  return val !== null && val !== undefined && (typeof val !== 'number' || !isNaN(val))
}
{
  "name": "hyperbee",
  "version": "2.27.3",
  "description": "An append-only B-tree running on a Hypercore.",
  "main": "index.js",
  "files": [
    "index.js",
    "lib/**.js",
    "iterators/**.js"
  ],
  "dependencies": {
    "b4a": "^1.6.0",
    "codecs": "^3.0.0",
    "debounceify": "^1.0.0",
    "hypercore-errors": "^1.0.0",
    "mutexify": "^1.4.0",
    "protocol-buffers-encodings": "^1.2.0",
    "rache": "^1.0.0",
    "ready-resource": "^1.0.0",
    "resolve-reject-promise": "^1.1.0",
    "safety-catch": "^1.0.2",
    "streamx": "^2.12.4",
    "unslab": "^1.2.0"
  },
  "devDependencies": {
    "bare-process": "^4.2.2",
    "brittle": "^3.1.0",
    "hypercore": "^11.0.0",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "protocol-buffers": "^4.2.0",
    "sub-encoder": "^1.0.6",
    "tree-to-string": "^1.1.1"
  },
  "imports": {
    "process": {
      "bare": "bare-process",
      "default": "process"
    }
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test/*.js",
    "test:bare": "brittle-bare test/*.js",
    "protobuf": "protocol-buffers schema.proto -o ./lib/messages.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/hyperbee.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/hyperbee/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperbee"
}
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const b4a = require('b4a')

// https://en.wikipedia.org/wiki/Merkle_tree#Second_preimage_attack
const LEAF_TYPE = b4a.from([0])
const PARENT_TYPE = b4a.from([1])
const ROOT_TYPE = b4a.from([2])

const HYPERCORE = b4a.from('hypercore')

exports.keyPair = function (seed) {
  // key pairs might stay around for a while, so better not to use a default slab to avoid retaining it completely
  const slab = b4a.allocUnsafeSlow(
    sodium.crypto_sign_PUBLICKEYBYTES + sodium.crypto_sign_SECRETKEYBYTES
  )
  const publicKey = slab.subarray(0, sodium.crypto_sign_PUBLICKEYBYTES)
  const secretKey = slab.subarray(sodium.crypto_sign_PUBLICKEYBYTES)

  if (seed) sodium.crypto_sign_seed_keypair(publicKey, secretKey, seed)
  else sodium.crypto_sign_keypair(publicKey, secretKey)

  return {
    publicKey,
    secretKey
  }
}

exports.validateKeyPair = function (keyPair) {
  const pk = b4a.allocUnsafe(sodium.crypto_sign_PUBLICKEYBYTES)
  sodium.crypto_sign_ed25519_sk_to_pk(pk, keyPair.secretKey)
  return b4a.equals(pk, keyPair.publicKey)
}

exports.sign = function (message, secretKey) {
  // Dedicated slab for the signature, to avoid retaining unneeded mem and for security
  const signature = b4a.allocUnsafeSlow(sodium.crypto_sign_BYTES)
  sodium.crypto_sign_detached(signature, message, secretKey)
  return signature
}

exports.verify = function (message, signature, publicKey) {
  if (signature.byteLength !== sodium.crypto_sign_BYTES) return false
  if (publicKey.byteLength !== sodium.crypto_sign_PUBLICKEYBYTES) return false
  return sodium.crypto_sign_verify_detached(signature, message, publicKey)
}

exports.encrypt = function (message, publicKey) {
  const ciphertext = b4a.alloc(message.byteLength + sodium.crypto_box_SEALBYTES)
  sodium.crypto_box_seal(ciphertext, message, publicKey)
  return ciphertext
}

exports.decrypt = function (ciphertext, keyPair) {
  if (ciphertext.byteLength < sodium.crypto_box_SEALBYTES) return null

  const plaintext = b4a.alloc(ciphertext.byteLength - sodium.crypto_box_SEALBYTES)

  if (!sodium.crypto_box_seal_open(plaintext, ciphertext, keyPair.publicKey, keyPair.secretKey)) {
    return null
  }

  return plaintext
}

exports.encryptionKeyPair = function (seed) {
  const publicKey = b4a.alloc(sodium.crypto_box_PUBLICKEYBYTES)
  const secretKey = b4a.alloc(sodium.crypto_box_SECRETKEYBYTES)

  if (seed) {
    sodium.crypto_box_seed_keypair(publicKey, secretKey, seed)
  } else {
    sodium.crypto_box_keypair(publicKey, secretKey)
  }

  return {
    publicKey,
    secretKey
  }
}

exports.data = function (data) {
  const out = b4a.allocUnsafe(32)

  sodium.crypto_generichash_batch(out, [LEAF_TYPE, c.encode(c.uint64, data.byteLength), data])

  return out
}

exports.parent = function (a, b) {
  if (a.index > b.index) {
    const tmp = a
    a = b
    b = tmp
  }

  const out = b4a.allocUnsafe(32)

  sodium.crypto_generichash_batch(out, [
    PARENT_TYPE,
    c.encode(c.uint64, a.size + b.size),
    a.hash,
    b.hash
  ])

  return out
}

exports.tree = function (roots, out) {
  const buffers = new Array(3 * roots.length + 1)
  let j = 0

  buffers[j++] = ROOT_TYPE

  for (let i = 0; i < roots.length; i++) {
    const r = roots[i]
    buffers[j++] = r.hash
    buffers[j++] = c.encode(c.uint64, r.index)
    buffers[j++] = c.encode(c.uint64, r.size)
  }

  if (!out) out = b4a.allocUnsafe(32)
  sodium.crypto_generichash_batch(out, buffers)
  return out
}

exports.hash = function (data, out) {
  if (!out) out = b4a.allocUnsafe(32)
  if (!Array.isArray(data)) data = [data]

  sodium.crypto_generichash_batch(out, data)

  return out
}

exports.randomBytes = function (n) {
  const buf = b4a.allocUnsafe(n)
  sodium.randombytes_buf(buf)
  return buf
}

exports.discoveryKey = function (key) {
  if (!key || key.byteLength !== 32) throw new Error('Must pass a 32 byte buffer')
  // Discovery keys might stay around for a while, so better not to use slab memory (for better gc)
  const digest = b4a.allocUnsafeSlow(32)
  sodium.crypto_generichash(digest, HYPERCORE, key)
  return digest
}

if (sodium.sodium_free) {
  exports.free = function (secureBuf) {
    if (secureBuf.secure) sodium.sodium_free(secureBuf)
  }
} else {
  exports.free = function () {}
}

exports.namespace = function (name, count) {
  const ids = typeof count === 'number' ? range(count) : count

  // Namespaces are long-lived, so better to use a dedicated slab
  const buf = b4a.allocUnsafeSlow(32 * ids.length)

  const list = new Array(ids.length)

  // ns is ephemeral, so default slab
  const ns = b4a.allocUnsafe(33)
  sodium.crypto_generichash(ns.subarray(0, 32), typeof name === 'string' ? b4a.from(name) : name)

  for (let i = 0; i < list.length; i++) {
    list[i] = buf.subarray(32 * i, 32 * i + 32)
    ns[32] = ids[i]
    sodium.crypto_generichash(list[i], ns)
  }

  return list
}

function range(count) {
  const arr = new Array(count)
  for (let i = 0; i < count; i++) arr[i] = i
  return arr
}
{
  "name": "hypercore-crypto",
  "version": "3.7.0",
  "description": "The crypto primitives used in hypercore, extracted into a separate module",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.6.6",
    "compact-encoding": "^3.0.0",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "brittle": "^3.5.0",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/hypercore-crypto.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/hypercore-crypto/issues"
  },
  "homepage": "https://github.com/mafintosh/hypercore-crypto"
}
const IdEnc = require('hypercore-id-encoding')

module.exports = class HypercoreError extends Error {
  constructor (msg, code, fn = HypercoreError, discoveryKey = null) {
    if (discoveryKey) msg = `${msg} (discovery key: ${IdEnc.normalize(discoveryKey)})`
    super(`${code}: ${msg}`)

    this.code = code
    this.discoveryKey = discoveryKey

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name () {
    return 'HypercoreError'
  }

  static ASSERTION (msg, discoveryKey = null) { // ERR_ASSERTION is picked up by safety-catch also
    return new HypercoreError(msg, 'ERR_ASSERTION', HypercoreError.ASSERT, discoveryKey)
  }

  static BAD_ARGUMENT (msg, discoveryKey = null) {
    return new HypercoreError(msg, 'BAD_ARGUMENT', HypercoreError.BAD_ARGUMENT, discoveryKey)
  }

  static STORAGE_EMPTY (msg, discoveryKey = null) {
    return new HypercoreError(msg, 'STORAGE_EMPTY', HypercoreError.STORAGE_EMPTY, discoveryKey)
  }

  static STORAGE_CONFLICT (msg, discoveryKey = null) {
    return new HypercoreError(msg, 'STORAGE_CONFLICT', HypercoreError.STORAGE_CONFLICT, discoveryKey)
  }

  static INVALID_SIGNATURE (msg, discoveryKey = null) {
    return new HypercoreError(msg, 'INVALID_SIGNATURE', HypercoreError.INVALID_SIGNATURE, discoveryKey)
  }

  static INVALID_CAPABILITY (msg, discoveryKey = null) {
    return new HypercoreError(msg, 'INVALID_CAPABILITY', HypercoreError.INVALID_CAPABILITY, discoveryKey)
  }

  static INVALID_CHECKSUM (msg = 'Invalid checksum', discoveryKey = null) {
    return new HypercoreError(msg, 'INVALID_CHECKSUM', HypercoreError.INVALID_CHECKSUM, discoveryKey)
  }

  static INVALID_OPERATION (msg, discoveryKey = null) {
    return new HypercoreError(msg, 'INVALID_OPERATION', HypercoreError.INVALID_OPERATION, discoveryKey)
  }

  static INVALID_PROOF (msg = 'Proof not verifiable', discoveryKey = null) {
    return new HypercoreError(msg, 'INVALID_PROOF', HypercoreError.INVALID_PROOF, discoveryKey)
  }

  static BLOCK_NOT_AVAILABLE (msg = 'Block is not available', discoveryKey = null) {
    return new HypercoreError(msg, 'BLOCK_NOT_AVAILABLE', HypercoreError.BLOCK_NOT_AVAILABLE, discoveryKey)
  }

  static SNAPSHOT_NOT_AVAILABLE (msg = 'Snapshot is not available', discoveryKey = null) {
    return new HypercoreError(msg, 'SNAPSHOT_NOT_AVAILABLE', HypercoreError.SNAPSHOT_NOT_AVAILABLE, discoveryKey)
  }

  static REQUEST_CANCELLED (msg = 'Request was cancelled', discoveryKey = null) {
    return new HypercoreError(msg, 'REQUEST_CANCELLED', HypercoreError.REQUEST_CANCELLED, discoveryKey)
  }

  static REQUEST_TIMEOUT (msg = 'Request timed out', discoveryKey = null) {
    return new HypercoreError(msg, 'REQUEST_TIMEOUT', HypercoreError.REQUEST_TIMEOUT, discoveryKey)
  }

  static SESSION_NOT_WRITABLE (msg = 'Session is not writable', discoveryKey = null) {
    return new HypercoreError(msg, 'SESSION_NOT_WRITABLE', HypercoreError.SESSION_NOT_WRITABLE, discoveryKey)
  }

  static SESSION_CLOSED (msg = 'Session is closed', discoveryKey = null) {
    return new HypercoreError(msg, 'SESSION_CLOSED', HypercoreError.SESSION_CLOSED, discoveryKey)
  }

  static BATCH_UNFLUSHED (msg = 'Batch not yet flushed', discoveryKey = null) {
    return new HypercoreError(msg, 'BATCH_UNFLUSHED', HypercoreError.BATCH_UNFLUSHED, discoveryKey)
  }

  static BATCH_ALREADY_EXISTS (msg = 'Batch already exists', discoveryKey = null) {
    return new HypercoreError(msg, 'BATCH_ALREADY_EXISTS', HypercoreError.BATCH_ALREADY_EXISTS, discoveryKey)
  }

  static BATCH_ALREADY_FLUSHED (msg = 'Batch has already been flushed', discoveryKey = null) {
    return new HypercoreError(msg, 'BATCH_ALREADY_FLUSHED', HypercoreError.BATCH_ALREADY_FLUSHED, discoveryKey)
  }

  static OPLOG_CORRUPT (msg = 'Oplog file appears corrupt or out of date', discoveryKey = null) {
    return new HypercoreError(msg, 'OPLOG_CORRUPT', HypercoreError.OPLOG_CORRUPT, discoveryKey)
  }

  static OPLOG_HEADER_OVERFLOW (msg = 'Oplog header exceeds page size', discoveryKey = null) {
    return new HypercoreError(msg, 'OPLOG_HEADER_OVERFLOW', HypercoreError.OPLOG_HEADER_OVERFLOW, discoveryKey)
  }

  static INVALID_OPLOG_VERSION (msg = 'Invalid header version', discoveryKey = null) {
    return new HypercoreError(msg, 'INVALID_OPLOG_VERSION', HypercoreError.INVALID_OPLOG_VERSION, discoveryKey)
  }

  static WRITE_FAILED (msg = 'Write to storage failed', discoveryKey = null) {
    return new HypercoreError(msg, 'WRITE_FAILED', HypercoreError.WRITE_FAILED, discoveryKey)
  }

  static DECODING_ERROR (msg = 'Decoding error', discoveryKey = null) {
    return new HypercoreError(msg, 'DECODING_ERROR', HypercoreError.DECODING_ERROR, discoveryKey)
  }

  static SESSION_MOVED (msg = 'Session moved', discoveryKey = null) {
    return new HypercoreError(msg, 'SESSION_MOVED', HypercoreError.SESSION_MOVED, discoveryKey)
  }
}
{
  "name": "hypercore-errors",
  "version": "1.5.0",
  "description": "Hypercore errors",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/hypercore-errors.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/hypercore-errors/issues"
  },
  "homepage": "https://github.com/holepunchto/hypercore-errors#readme",
  "devDependencies": {
    "b4a": "^1.6.7",
    "brittle": "^3.1.3",
    "standard": "^17.0.0"
  },
  "dependencies": {
    "hypercore-id-encoding": "^1.3.0"
  }
}
const z32 = require('z32')
const b4a = require('b4a')

module.exports = {
  encode,
  decode,
  normalize,
  isValid
}

function encode (key) {
  if (!b4a.isBuffer(key)) throw new Error('Key must be a Buffer')
  if (key.byteLength !== 32) throw new Error('Key must be 32-bytes long')
  return z32.encode(key)
}

function decode (id) {
  if (b4a.isBuffer(id)) {
    if (id.byteLength !== 32) throw new Error('ID must be 32-bytes long')
    return id
  }
  if (typeof id === 'string') {
    if (id.startsWith('pear://')) id = id.slice(7).split('/')[0]
    if (id.length === 52) return z32.decode(id)
    if (id.length === 64) {
      const buf = b4a.from(id, 'hex')
      if (buf.byteLength === 32) return buf
    }
  }
  throw new Error('Invalid Hypercore key')
}

function normalize (any) {
  return encode(decode(any))
}

function isValid (any) {
  try {
    decode(any)
    return true
  } catch {
    return false
  }
}
{
  "name": "hypercore-id-encoding",
  "version": "1.3.0",
  "description": "Convert Hypercore keys to/from z-base32 or hex",
  "main": "index.js",
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.5.3",
    "z32": "^1.0.0"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "hypercore": "^10.0.0",
    "random-access-memory": "^6.0.0",
    "standard": "^17.1.0"
  },
  "license": "Apache-2.0",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/hypercore-id-encoding.git"
  },
  "keywords": [],
  "author": "",
  "bugs": {
    "url": "https://github.com/holepunchto/hypercore-id-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/hypercore-id-encoding#readme"
}
function headLegacyMap(m) {
  return {
    version: 2, // version bumped from 1
    cores: m.allocated.cores,
    datas: m.allocated.datas,
    groups: 0,
    seed: m.seed,
    defaultDiscoveryKey: m.defaultDiscoveryKey
  }
}

module.exports = {
  headLegacyMap
}
// This file is autogenerated by the hyperschema compiler
// Schema Version: 2
/* eslint-disable camelcase */
/* eslint-disable quotes */
/* eslint-disable space-before-function-paren */

const { c } = require('hyperschema/runtime')
const external0 = require('../../external.js')

const VERSION = 2

// eslint-disable-next-line no-unused-vars
let version = VERSION

// @corestore/allocated
const encoding0 = {
  preencode(state, m) {
    c.uint.preencode(state, m.cores)
    c.uint.preencode(state, m.datas)
  },
  encode(state, m) {
    c.uint.encode(state, m.cores)
    c.uint.encode(state, m.datas)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const r1 = c.uint.decode(state)

    return {
      cores: r0,
      datas: r1
    }
  }
}

// @corestore/head-v1
const encoding1 = {
  preencode(state, m) {
    state.end++ // max flag is 4 so always one byte

    if (m.allocated) encoding0.preencode(state, m.allocated)
    if (m.seed) c.fixed32.preencode(state, m.seed)
    if (m.defaultDiscoveryKey) c.fixed32.preencode(state, m.defaultDiscoveryKey)
  },
  encode(state, m) {
    const flags = (m.allocated ? 1 : 0) | (m.seed ? 2 : 0) | (m.defaultDiscoveryKey ? 4 : 0)

    c.uint.encode(state, flags)

    if (m.allocated) encoding0.encode(state, m.allocated)
    if (m.seed) c.fixed32.encode(state, m.seed)
    if (m.defaultDiscoveryKey) c.fixed32.encode(state, m.defaultDiscoveryKey)
  },
  decode(state) {
    const v = c.uint.decode(state)
    const flags = c.uint.decode(state)

    return {
      version: v,
      allocated: (flags & 1) !== 0 ? encoding0.decode(state) : null,
      seed: (flags & 2) !== 0 ? c.fixed32.decode(state) : null,
      defaultDiscoveryKey: (flags & 4) !== 0 ? c.fixed32.decode(state) : null
    }
  }
}

// @corestore/head-v2
const encoding2 = {
  preencode(state, m) {
    c.uint.preencode(state, m.cores)
    c.uint.preencode(state, m.datas)
    c.uint.preencode(state, m.groups)
    state.end++ // max flag is 2 so always one byte

    if (m.seed) c.fixed32.preencode(state, m.seed)
    if (m.defaultDiscoveryKey) c.fixed32.preencode(state, m.defaultDiscoveryKey)
  },
  encode(state, m) {
    const flags = (m.seed ? 1 : 0) | (m.defaultDiscoveryKey ? 2 : 0)

    c.uint.encode(state, m.cores)
    c.uint.encode(state, m.datas)
    c.uint.encode(state, m.groups)
    c.uint.encode(state, flags)

    if (m.seed) c.fixed32.encode(state, m.seed)
    if (m.defaultDiscoveryKey) c.fixed32.encode(state, m.defaultDiscoveryKey)
  },
  decode(state) {
    const v = c.uint.decode(state)
    const r0 = c.uint.decode(state)
    const r1 = c.uint.decode(state)
    const r2 = c.uint.decode(state)
    const flags = c.uint.decode(state)

    return {
      version: v,
      cores: r0,
      datas: r1,
      groups: r2,
      seed: (flags & 1) !== 0 ? c.fixed32.decode(state) : null,
      defaultDiscoveryKey: (flags & 2) !== 0 ? c.fixed32.decode(state) : null
    }
  }
}

// @corestore/head
const encoding3 = {
  preencode(state, m) {
    c.uint.preencode(state, m.version)
    switch (m.version) {
      case 0:
      case 1:
        encoding1.preencode(state, m)
        break
      case 2:
        encoding2.preencode(state, m)
        break
      default:
        throw new Error('Unsupported version')
    }
  },
  encode(state, m) {
    c.uint.encode(state, m.version)
    switch (m.version) {
      case 0:
      case 1:
        encoding1.encode(state, m)
        break
      case 2:
        encoding2.encode(state, m)
        break
      default:
        throw new Error('Unsupported version')
    }
  },
  decode(state) {
    const start = state.start
    const v = c.uint.decode(state)
    state.start = start
    switch (v) {
      case 0:
      case 1: {
        const decoded = encoding1.decode(state)
        const map = external0.headLegacyMap
        return map(decoded)
      }
      case 2: {
        const decoded = encoding2.decode(state)
        return decoded
      }
      default:
        throw new Error('Unsupported version')
    }
  }
}

// @corestore/alias
const encoding4 = {
  preencode(state, m) {
    c.string.preencode(state, m.name)
    c.fixed32.preencode(state, m.namespace)
  },
  encode(state, m) {
    c.string.encode(state, m.name)
    c.fixed32.encode(state, m.namespace)
  },
  decode(state) {
    const r0 = c.string.decode(state)
    const r1 = c.fixed32.decode(state)

    return {
      name: r0,
      namespace: r1
    }
  }
}

// @corestore/core
const encoding5 = {
  preencode(state, m) {
    c.uint.preencode(state, m.version)
    c.uint.preencode(state, m.corePointer)
    c.uint.preencode(state, m.dataPointer)
    state.end++ // max flag is 1 so always one byte

    if (m.alias) encoding4.preencode(state, m.alias)
  },
  encode(state, m) {
    const flags = m.alias ? 1 : 0

    c.uint.encode(state, m.version)
    c.uint.encode(state, m.corePointer)
    c.uint.encode(state, m.dataPointer)
    c.uint.encode(state, flags)

    if (m.alias) encoding4.encode(state, m.alias)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const r1 = c.uint.decode(state)
    const r2 = c.uint.decode(state)
    const flags = c.uint.decode(state)

    return {
      version: r0,
      corePointer: r1,
      dataPointer: r2,
      alias: (flags & 1) !== 0 ? encoding4.decode(state) : null
    }
  }
}

const encoding6_enum = {
  blake2b: 'blake2b'
}

// @core/hashes enum
const encoding6 = {
  preencode(state, m) {
    state.end++ // max enum is 0 so always one byte
  },
  encode(state, m) {
    switch (m) {
      case 'blake2b':
        c.uint.encode(state, 0)
        break
      default:
        throw new Error('Unknown enum')
    }
  },
  decode(state) {
    switch (c.uint.decode(state)) {
      case 0:
        return 'blake2b'
      default:
        return null
    }
  }
}

const encoding7_enum = {
  ed25519: 'ed25519'
}

// @core/signatures enum
const encoding7 = {
  preencode(state, m) {
    state.end++ // max enum is 0 so always one byte
  },
  encode(state, m) {
    switch (m) {
      case 'ed25519':
        c.uint.encode(state, 0)
        break
      default:
        throw new Error('Unknown enum')
    }
  },
  decode(state) {
    switch (c.uint.decode(state)) {
      case 0:
        return 'ed25519'
      default:
        return null
    }
  }
}

// @core/tree-node
const encoding8 = {
  preencode(state, m) {
    c.uint.preencode(state, m.index)
    c.uint.preencode(state, m.size)
    c.fixed32.preencode(state, m.hash)
  },
  encode(state, m) {
    c.uint.encode(state, m.index)
    c.uint.encode(state, m.size)
    c.fixed32.encode(state, m.hash)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const r1 = c.uint.decode(state)
    const r2 = c.fixed32.decode(state)

    return {
      index: r0,
      size: r1,
      hash: r2
    }
  }
}

// @core/signer
const encoding9 = {
  preencode(state, m) {
    encoding7.preencode(state, m.signature)
    c.fixed32.preencode(state, m.namespace)
    c.fixed32.preencode(state, m.publicKey)
  },
  encode(state, m) {
    encoding7.encode(state, m.signature)
    c.fixed32.encode(state, m.namespace)
    c.fixed32.encode(state, m.publicKey)
  },
  decode(state) {
    const r0 = encoding7.decode(state)
    const r1 = c.fixed32.decode(state)
    const r2 = c.fixed32.decode(state)

    return {
      signature: r0,
      namespace: r1,
      publicKey: r2
    }
  }
}

// @core/prologue
const encoding10 = {
  preencode(state, m) {
    c.fixed32.preencode(state, m.hash)
    c.uint.preencode(state, m.length)
  },
  encode(state, m) {
    c.fixed32.encode(state, m.hash)
    c.uint.encode(state, m.length)
  },
  decode(state) {
    const r0 = c.fixed32.decode(state)
    const r1 = c.uint.decode(state)

    return {
      hash: r0,
      length: r1
    }
  }
}

// @core/manifest.signers
const encoding11_4 = c.array(encoding9)
// @core/manifest.linked
const encoding11_6 = c.array(c.fixed32)

// @core/manifest
const encoding11 = {
  preencode(state, m) {
    c.uint.preencode(state, m.version)
    state.end++ // max flag is 8 so always one byte
    encoding6.preencode(state, m.hash)
    c.uint.preencode(state, m.quorum)
    encoding11_4.preencode(state, m.signers)

    if (m.prologue) encoding10.preencode(state, m.prologue)
    if (m.linked) encoding11_6.preencode(state, m.linked)
    if (m.userData) c.buffer.preencode(state, m.userData)
  },
  encode(state, m) {
    const flags =
      (m.allowPatch ? 1 : 0) | (m.prologue ? 2 : 0) | (m.linked ? 4 : 0) | (m.userData ? 8 : 0)

    c.uint.encode(state, m.version)
    c.uint.encode(state, flags)
    encoding6.encode(state, m.hash)
    c.uint.encode(state, m.quorum)
    encoding11_4.encode(state, m.signers)

    if (m.prologue) encoding10.encode(state, m.prologue)
    if (m.linked) encoding11_6.encode(state, m.linked)
    if (m.userData) c.buffer.encode(state, m.userData)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const flags = c.uint.decode(state)

    return {
      version: r0,
      hash: encoding6.decode(state),
      quorum: c.uint.decode(state),
      allowPatch: (flags & 1) !== 0,
      signers: encoding11_4.decode(state),
      prologue: (flags & 2) !== 0 ? encoding10.decode(state) : null,
      linked: (flags & 4) !== 0 ? encoding11_6.decode(state) : null,
      userData: (flags & 8) !== 0 ? c.buffer.decode(state) : null
    }
  }
}

// @core/keyPair
const encoding12 = {
  preencode(state, m) {
    c.buffer.preencode(state, m.publicKey)
    c.optionalBuffer.preencode(state, m.secretKey)
  },
  encode(state, m) {
    c.buffer.encode(state, m.publicKey)
    c.optionalBuffer.encode(state, m.secretKey)
  },
  decode(state) {
    const r0 = c.buffer.decode(state)
    const r1 = c.optionalBuffer.decode(state)

    return {
      publicKey: r0,
      secretKey: r1
    }
  }
}

// @core/group
const encoding13 = {
  preencode(state, m) {
    state.end++ // max flag is 2 so always one byte

    if (m.key) c.fixed32.preencode(state, m.key)
    if (m.pointer) c.uint.preencode(state, m.pointer)
  },
  encode(state, m) {
    const flags = (m.key ? 1 : 0) | (m.pointer ? 2 : 0)

    c.uint.encode(state, flags)

    if (m.key) c.fixed32.encode(state, m.key)
    if (m.pointer) c.uint.encode(state, m.pointer)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      key: (flags & 1) !== 0 ? c.fixed32.decode(state) : null,
      pointer: (flags & 2) !== 0 ? c.uint.decode(state) : 0
    }
  }
}

// @core/auth.manifest
const encoding14_2 = c.frame(encoding11)

// @core/auth
const encoding14 = {
  preencode(state, m) {
    c.fixed32.preencode(state, m.key)
    c.fixed32.preencode(state, m.discoveryKey)
    state.end++ // max flag is 4 so always one byte

    if (m.manifest) encoding14_2.preencode(state, m.manifest)
    if (m.keyPair) encoding12.preencode(state, m.keyPair)
    if (m.encryptionKey) c.buffer.preencode(state, m.encryptionKey)
  },
  encode(state, m) {
    const flags = (m.manifest ? 1 : 0) | (m.keyPair ? 2 : 0) | (m.encryptionKey ? 4 : 0)

    c.fixed32.encode(state, m.key)
    c.fixed32.encode(state, m.discoveryKey)
    c.uint.encode(state, flags)

    if (m.manifest) encoding14_2.encode(state, m.manifest)
    if (m.keyPair) encoding12.encode(state, m.keyPair)
    if (m.encryptionKey) c.buffer.encode(state, m.encryptionKey)
  },
  decode(state) {
    const r0 = c.fixed32.decode(state)
    const r1 = c.fixed32.decode(state)
    const flags = c.uint.decode(state)

    return {
      key: r0,
      discoveryKey: r1,
      manifest: (flags & 1) !== 0 ? encoding14_2.decode(state) : null,
      keyPair: (flags & 2) !== 0 ? encoding12.decode(state) : null,
      encryptionKey: (flags & 4) !== 0 ? c.buffer.decode(state) : null
    }
  }
}

// @core/head
const encoding15 = {
  preencode(state, m) {
    c.uint.preencode(state, m.fork)
    c.uint.preencode(state, m.length)
    c.fixed32.preencode(state, m.rootHash)
    c.optionalBuffer.preencode(state, m.signature)
    state.end++ // max flag is 1 so always one byte

    if (version >= 2 && m.timestamp) c.uint64.preencode(state, m.timestamp)
  },
  encode(state, m) {
    const flags = version >= 2 && m.timestamp ? 1 : 0

    c.uint.encode(state, m.fork)
    c.uint.encode(state, m.length)
    c.fixed32.encode(state, m.rootHash)
    c.optionalBuffer.encode(state, m.signature)
    c.uint.encode(state, flags)

    if (version >= 2 && m.timestamp) c.uint64.encode(state, m.timestamp)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const r1 = c.uint.decode(state)
    const r2 = c.fixed32.decode(state)
    const r3 = c.optionalBuffer.decode(state)
    const flags = state.start < state.end ? c.uint.decode(state) : 0

    return {
      fork: r0,
      length: r1,
      rootHash: r2,
      signature: r3,
      timestamp: version >= 2 && (flags & 1) !== 0 ? c.uint64.decode(state) : 0
    }
  }
}

// @core/hints
const encoding16 = {
  preencode(state, m) {
    state.end++ // max flag is 4 so always one byte

    if (m.contiguousLength) c.uint.preencode(state, m.contiguousLength)
    if (m.remoteContiguousLength) c.uint.preencode(state, m.remoteContiguousLength)
    if (m.recovering) c.uint.preencode(state, m.recovering)
  },
  encode(state, m) {
    const flags =
      (m.contiguousLength ? 1 : 0) | (m.remoteContiguousLength ? 2 : 0) | (m.recovering ? 4 : 0)

    c.uint.encode(state, flags)

    if (m.contiguousLength) c.uint.encode(state, m.contiguousLength)
    if (m.remoteContiguousLength) c.uint.encode(state, m.remoteContiguousLength)
    if (m.recovering) c.uint.encode(state, m.recovering)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      contiguousLength: (flags & 1) !== 0 ? c.uint.decode(state) : 0,
      remoteContiguousLength: (flags & 2) !== 0 ? c.uint.decode(state) : 0,
      recovering: (flags & 4) !== 0 ? c.uint.decode(state) : 0
    }
  }
}

// @core/session
const encoding17 = {
  preencode(state, m) {
    c.string.preencode(state, m.name)
    c.uint.preencode(state, m.dataPointer)
  },
  encode(state, m) {
    c.string.encode(state, m.name)
    c.uint.encode(state, m.dataPointer)
  },
  decode(state) {
    const r0 = c.string.decode(state)
    const r1 = c.uint.decode(state)

    return {
      name: r0,
      dataPointer: r1
    }
  }
}

// @core/sessions
const encoding18 = c.array(encoding17)

// @core/dependency
const encoding19 = {
  preencode(state, m) {
    c.uint.preencode(state, m.dataPointer)
    c.uint.preencode(state, m.length)
  },
  encode(state, m) {
    c.uint.encode(state, m.dataPointer)
    c.uint.encode(state, m.length)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const r1 = c.uint.decode(state)

    return {
      dataPointer: r0,
      length: r1
    }
  }
}

function setVersion(v) {
  version = v
}

function encode(name, value, v = VERSION) {
  version = v
  return c.encode(getEncoding(name), value)
}

function decode(name, buffer, v = VERSION) {
  version = v
  return c.decode(getEncoding(name), buffer)
}

function getEnum(name) {
  switch (name) {
    case '@core/hashes':
      return encoding6_enum
    case '@core/signatures':
      return encoding7_enum
    default:
      throw new Error('Enum not found ' + name)
  }
}

function getEncoding(name) {
  switch (name) {
    case '@corestore/allocated':
      return encoding0
    case '@corestore/head-v1':
      return encoding1
    case '@corestore/head-v2':
      return encoding2
    case '@corestore/head':
      return encoding3
    case '@corestore/alias':
      return encoding4
    case '@corestore/core':
      return encoding5
    case '@core/hashes':
      return encoding6
    case '@core/signatures':
      return encoding7
    case '@core/tree-node':
      return encoding8
    case '@core/signer':
      return encoding9
    case '@core/prologue':
      return encoding10
    case '@core/manifest':
      return encoding11
    case '@core/keyPair':
      return encoding12
    case '@core/group':
      return encoding13
    case '@core/auth':
      return encoding14
    case '@core/head':
      return encoding15
    case '@core/hints':
      return encoding16
    case '@core/session':
      return encoding17
    case '@core/sessions':
      return encoding18
    case '@core/dependency':
      return encoding19
    default:
      throw new Error('Encoder not found ' + name)
  }
}

function getStruct(name, v = VERSION) {
  const enc = getEncoding(name)
  return {
    preencode(state, m) {
      version = v
      enc.preencode(state, m)
    },
    encode(state, m) {
      version = v
      enc.encode(state, m)
    },
    decode(state) {
      version = v
      return enc.decode(state)
    }
  }
}

const resolveStruct = getStruct // compat

module.exports = {
  resolveStruct,
  getStruct,
  getEnum,
  getEncoding,
  encode,
  decode,
  setVersion,
  version
}
const RocksDB = require('rocksdb-native')
const rrp = require('resolve-reject-promise')
const ScopeLock = require('scope-lock')
const DeviceFile = require('device-file')
const path = require('path')
const fs = require('fs')
const Xache = require('xache')

const View = require('./lib/view.js')

const VERSION = 2
const COLUMN_FAMILY = 'corestore'

const { store, core } = require('./lib/keys.js')

const { CorestoreRX, CorestoreTX, CoreTX, CoreRX } = require('./lib/tx.js')

const {
  createCoreStream,
  createAliasStream,
  createDiscoveryKeyStream,
  createBlockStream,
  createBitfieldStream,
  createUserDataStream,
  createTreeNodeStream,
  createMarkStream,
  createLocalStream,
  createGroupUpdateStream
} = require('./lib/streams.js')

const EMPTY = new View()

class Atom {
  constructor(db) {
    this.db = db
    this.view = new View()
    this.flushedPromise = null
    this.flushing = false
    this.preflushes = []
    this.flushes = []
  }

  preflush(fn) {
    this.preflushes.push(fn)
  }

  onflush(fn) {
    this.flushes.push(fn)
  }

  flushed() {
    if (!this.flushing) return Promise.resolve()
    if (this.flushedPromise !== null) return this.flushedPromise.promise
    this.flushedPromise = rrp()
    return this.flushedPromise.promise
  }

  _resolve() {
    const f = this.flushedPromise
    this.flushedPromise = null
    f.resolve()
  }

  async flush() {
    if (this.flushing) throw new Error('Atom already flushing')
    this.flushing = true

    try {
      const plen = this.preflushes.length
      for (let i = 0; i < plen; i++) this.preflushes[i]()

      await View.flush(this.view.changes, this.db)

      const promises = []
      const len = this.flushes.length // in case of reentry
      for (let i = 0; i < len; i++) promises.push(this.flushes[i]())

      await Promise.all(promises)
    } finally {
      this.view.reset()
      this.flushing = false
      if (this.flushedPromise !== null) this._resolve()
    }
  }
}

class HypercoreStorage {
  constructor(store, db, treeCache, core, view, atom) {
    this.store = store
    this.db = db
    this.core = core
    this.view = view
    this.atom = atom

    this.view.readStart()
    this.treeCache = treeCache
  }

  get readOnly() {
    return this.store.readOnly
  }

  get dependencies() {
    return this.core.dependencies
  }

  getDependencyLength() {
    return this.core.dependencies.length
      ? this.core.dependencies[this.core.dependencies.length - 1].length
      : -1
  }

  getDependency(length) {
    for (let i = this.core.dependencies.length - 1; i >= 0; i--) {
      const dep = this.core.dependencies[i]
      if (dep.length < length) return dep
    }

    return null
  }

  setDependencyHead(dep) {
    if (dep === null) {
      this.core.dependencies = []
      return
    }

    const deps = this.core.dependencies

    for (let i = deps.length - 1; i >= 0; i--) {
      const d = deps[i]

      if (d.dataPointer !== dep.dataPointer) continue

      // check if nothing changed
      if (d.length === dep.length && i === deps.length - 1) return

      this.core = {
        corePointer: this.core.corePointer,
        dataPointer: this.core.dataPointer,
        dependencies: deps.slice(0, i + 1)
      }

      this.core.dependencies[i] = {
        dataPointer: dep.dataPointer,
        length: dep.length
      }
      return // updated head so done
    }

    this.core.dependencies = [
      {
        dataPointer: dep.dataPointer,
        length: dep.length
      }
    ]
  }

  // TODO: this might have to be async if the dependents have changed, but prop ok for now
  updateDependencyLength(length, truncated) {
    const deps = this.core.dependencies

    const i = this.findDependencyIndex(length, truncated)
    if (i === -1) throw new Error('Dependency not found')

    this.core = {
      corePointer: this.core.corePointer,
      dataPointer: this.core.dataPointer,
      dependencies: deps.slice(0, i + 1)
    }

    if (this.core.dependencies[i].length !== length) {
      this.core.dependencies[i] = {
        dataPointer: deps[i].dataPointer,
        length
      }
    }
  }

  findDependencyIndex(length, truncated) {
    const deps = this.core.dependencies

    if (truncated) {
      for (let i = 0; i < deps.length; i++) {
        if (deps[i].length >= length) return i
      }

      return -1
    }

    for (let i = deps.length - 1; i >= 0; i--) {
      if (deps[i].length <= length) return i
    }

    return -1
  }

  get snapshotted() {
    return this.db._snapshot !== null
  }

  snapshot() {
    return new HypercoreStorage(
      this.store,
      this.db.snapshot(),
      this.treeCache,
      this.core,
      this.view.snapshot(),
      this.atom
    )
  }

  compact() {
    return Promise.all([
      this.db.compactRange(core.core(this.core.corePointer), core.core(this.core.corePointer)),
      this.db.compactRange(core.data(this.core.dataPointer), core.data(this.core.dataPointer))
    ])
  }

  atomize(atom) {
    if (this.atom && this.atom !== atom) {
      throw new Error('Cannot atomize and atomized session with a new atom')
    }

    return new HypercoreStorage(
      this.store,
      this.db.session(),
      this.treeCache,
      this.core,
      atom.view,
      atom
    )
  }

  createAtom() {
    return this.store.createAtom()
  }

  createBlockStream(opts) {
    return createBlockStream(this.core, this.db, this.view, opts)
  }

  createTreeNodeStream(opts) {
    return createTreeNodeStream(this.core, this.db, this.view, opts)
  }

  createBitfieldStream(opts) {
    return createBitfieldStream(this.core, this.db, this.view, opts)
  }

  createUserDataStream(opts) {
    return createUserDataStream(this.core, this.db, this.view, opts)
  }

  createMarkStream(opts) {
    return createMarkStream(this.core, this.db, this.view, opts)
  }

  createLocalStream(opts) {
    return createLocalStream(this.core, this.db, this.view, opts)
  }

  async resumeSession(name) {
    const rx = this.read()
    const existingSessionsPromise = rx.getSessions()

    rx.tryFlush()
    const existingSessions = await existingSessionsPromise

    const sessions = existingSessions || []
    const session = getSession(sessions, name, false)

    if (session === null) return null

    const core = {
      corePointer: this.core.corePointer,
      dataPointer: session.dataPointer,
      dependencies: []
    }

    const coreRx = new CoreRX(core, this.db, this.view, this.treeCache, this.store.stats, -1)

    const dependencyPromise = coreRx.getDependency()
    coreRx.tryFlush()

    const dependency = await dependencyPromise
    if (dependency) core.dependencies = this._addDependency(dependency)

    return new HypercoreStorage(
      this.store,
      this.db.session(),
      this.treeCache,
      core,
      this.atom ? this.view : new View(),
      this.atom
    )
  }

  async createSession(name, head) {
    const rx = this.read()

    const existingSessionsPromise = rx.getSessions()
    const existingHeadPromise = rx.getHead()

    rx.tryFlush()

    const [existingSessions, existingHead] = await Promise.all([
      existingSessionsPromise,
      existingHeadPromise
    ])
    if (head === null) head = existingHead

    if (existingHead !== null && head.length > existingHead.length) {
      throw new Error('Invalid head passed, ahead of core')
    }

    const sessions = existingSessions || []
    const session = getSession(sessions, name, true)
    const fresh = session.dataPointer === -1

    if (fresh) {
      session.dataPointer = await this.store._allocData()
    }

    const tx = this.write()

    tx.setSessions(sessions)

    const length = head === null ? 0 : head.length
    const core = {
      corePointer: this.core.corePointer,
      dataPointer: session.dataPointer,
      dependencies: this._addDependency({
        dataPointer: this.core.dataPointer,
        length
      })
    }

    const coreTx = new CoreTX(core, this.db, tx.view, tx.changes)

    if (length > 0) coreTx.setHead(head)
    coreTx.setDependency(core.dependencies[core.dependencies.length - 1])

    if (!fresh) {
      // nuke all existing state...
      coreTx.deleteBlockRange(0, -1)
      coreTx.deleteTreeNodeRange(0, -1)
      coreTx.deleteBitfieldPageRange(0, -1)
    }

    await tx.flush()

    return new HypercoreStorage(
      this.store,
      this.db.session(),
      this.treeCache,
      core,
      this.atom ? this.view : new View(),
      this.atom
    )
  }

  async createAtomicSession(atom, head) {
    const length = head === null ? 0 : head.length
    const core = {
      corePointer: this.core.corePointer,
      dataPointer: this.core.dataPointer,
      dependencies: this._addDependency(null)
    }

    const coreTx = new CoreTX(core, this.db, atom.view, [])

    if (length > 0) coreTx.setHead(head)

    await coreTx.flush()

    return this.atomize(atom)
  }

  _addDependency(dep) {
    const deps = []

    for (let i = 0; i < this.core.dependencies.length; i++) {
      const d = this.core.dependencies[i]

      if (dep !== null && d.length > dep.length) {
        if (d.dataPointer !== dep.dataPointer) {
          deps.push({ dataPointer: d.dataPointer, length: dep.length })
        }
        return deps
      }

      deps.push(d)
    }

    if (
      dep !== null &&
      (deps.length === 0 || deps[deps.length - 1].dataPointer !== dep.dataPointer)
    ) {
      deps.push(dep)
    }
    return deps
  }

  async deleteSessions() {
    const rx = this.read()
    const existingSessionsPromise = rx.getSessions()
    rx.tryFlush()

    const existingSessions = await existingSessionsPromise

    // Remove batches
    const coreTx = this.write()
    coreTx.setSessions([]) // Clear sessions record
    await coreTx.flush()

    const tx = this.db.write({ autoDestroy: true })

    for (const { dataPointer } of existingSessions) {
      const start = core.data(dataPointer)
      const end = core.data(dataPointer + 1)
      tx.tryDeleteRange(start, end)
    }

    await tx.flush()
  }

  read(fork = -1) {
    let treeCache = null
    if (!this.atom) treeCache = this.treeCache

    return new CoreRX(this.core, this.db, this.view, treeCache, this.store.stats, fork)
  }

  write() {
    return new CoreTX(this.core, this.db, this.atom ? this.view : null, [])
  }

  close() {
    if (this.view !== null) {
      this.view.readStop()
      this.view = null
    }

    return this.db.close()
  }

  static async export(ptr, db, { batches = false } = {}) {
    const rx = new CoreRX(ptr, db, EMPTY, null, null, -1)

    const core = {
      head: null,
      auth: null,
      sessions: [],
      data: null
    }

    const sessionsPromise = rx.getSessions()
    const headPromise = rx.getHead()
    const authPromise = rx.getAuth()

    rx.tryFlush()

    const [sessions, head, auth] = await Promise.all([sessionsPromise, headPromise, authPromise])

    core.head = head
    core.auth = { ...auth, keyPair: null }
    if (sessions) core.sessions = sessions.map((s) => s.name)

    const data = []

    data.push(exportData(ptr, db))

    if (batches) {
      for (const { dataPointer } of sessions) {
        data.push(exportData({ dataPointer, dependencies: [] }, db))
      }
    }

    core.data = await Promise.all(data)

    return core
  }

  static isParentStorage(storage, parent) {
    const last = getLastDependency(storage)
    return !!last && last.dataPointer === parent.core.dataPointer
  }
}

class CorestoreStorage {
  constructor(db, opts = {}) {
    const storage = typeof db === 'string' ? db : null

    this.bootstrap = storage !== null
    this.path = storage !== null ? storage : path.join(db.path, '..')
    this.alwaysRecover = !!opts.alwaysRecover
    this.readOnly = !!opts.readOnly
    this.allowBackup = !!opts.allowBackup
    this.deviceFile = null
    this.wait = !!opts.wait

    // tmp sync fix for simplicty since not super deployed yet
    if (this.bootstrap && !this.readOnly) tmpFixStorage(this.path)

    this.id = opts.id || null
    this.view = null
    this.enters = 0
    this.lock = new ScopeLock()
    this.flushing = null
    this.version = 0
    this.migrating = null

    if ((this.bootstrap && !this.readOnly && !this.allowBackup) || this.wait) {
      const corestoreFile = path.join(this.path, 'CORESTORE')

      this.deviceFile = new DeviceFile(corestoreFile, {
        lock: true,
        wait: this.wait,
        data: { id: this.id }
      })
    }

    const dbPath = path.join(this.path, 'db')

    this.stats = {
      treeCache: {
        hits: 0,
        misses: 0,
        parallel: 0,
        skips: 0
      }
    }
    this.rocks = storage === null ? db : new RocksDB(dbPath, { ...opts, lock: this.deviceFile })
    this.db = createColumnFamily(this.rocks, opts)

    const { treeCache = { maxSize: 8192 } } = opts
    this.treeCache = new Xache(treeCache)
  }

  get opened() {
    return this.db.opened
  }

  get closed() {
    return this.db.closed
  }

  async ready() {
    if (this.version === 0) await this._migrateStore()
    return this.db.ready()
  }

  compact(opts) {
    return this.db.compactRange(opts)
  }

  async audit() {
    for await (const { core } of this.createCoreStream()) {
      const coreRx = new CoreRX(core, this.db, EMPTY, this.treeCache, this.stats, -1)
      const authPromise = coreRx.getAuth()

      coreRx.tryFlush()

      const auth = await authPromise

      if (!auth.manifest || auth.manifest.version > 0) continue
      if (auth.manifest.linked === null) continue

      auth.manifest.linked = null
      const coreTx = new CoreTX(core, this.db, null, [])
      coreTx.setAuth(auth)
      await coreTx.flush()
    }
  }

  async deleteCore(ptr) {
    const rx = new CoreRX(ptr, this.db, EMPTY, this.treeCache, this.stats, -1)

    const authPromise = rx.getAuth()
    const sessionsPromise = rx.getSessions()

    rx.tryFlush()

    const auth = await authPromise
    const sessions = await sessionsPromise

    // no core stored here
    if (!auth) return

    const tx = this.db.write({ autoDestroy: true })

    tx.tryDelete(store.core(auth.discoveryKey))

    // clear core
    const start = core.core(ptr.corePointer)
    const end = core.core(ptr.corePointer + 1)
    tx.tryDeleteRange(start, end)

    if (sessions) {
      for (const { dataPointer } of sessions) {
        const start = core.data(dataPointer)
        const end = core.data(dataPointer + 1)
        tx.tryDeleteRange(start, end)
      }
    }

    return tx.flush()
  }

  static isCoreStorage(db) {
    return isCorestoreStorage(db)
  }

  static from(db) {
    if (isCorestoreStorage(db)) return db
    return new this(db)
  }

  async _flush() {
    while (this.enters > 0) {
      await this.lock.lock()
      await this.lock.unlock()
    }
  }

  async _maybeRecover(view) {
    const r = path.join(this.db.path, 'RECOVERING')
    if (!(await fileExists(r))) return
    await this.setRecovering(view)
    await fs.promises.unlink(r)
  }

  _maybeRecoverLater(err) {
    if (!shouldRecover(err) && !this.alwaysRecover) return
    fs.writeFileSync(path.join(this.db.path, 'RECOVERING'), '')
    for (const file of fs.readdirSync(this.db.path)) {
      if (file.endsWith('.log')) fs.unlinkSync(path.join(this.db.path, file))
    }
  }

  // runs pre any other mutation and read
  async _migrateStore() {
    const view = await this._enter()

    try {
      if (this.version === VERSION) return

      await this._preopen

      try {
        await this.db.ready()
      } catch (err) {
        this._maybeRecoverLater(err)
        throw err
      }

      await this._maybeRecover(view)

      const rx = new CorestoreRX(this.db, view)
      const headPromise = rx.getHead()

      rx.tryFlush()
      const head = await headPromise

      const version = head === null ? 0 : head.version
      if (version === VERSION) {
        this.version = VERSION
        return
      }

      const target = { version: VERSION, dryRun: false }

      switch (version) {
        case 0: {
          await require('./migrations/0').store(this, target)
          break
        }
        case 1: {
          // implicit migration on write
          break
        }
        default: {
          throw new Error(
            'Unsupported version: ' + version + ' - you should probably upgrade your dependencies'
          )
        }
      }

      this.version = VERSION
    } finally {
      await this._exit()
    }
  }

  // runs pre the core is returned to the user
  async _migrateCore(core, discoveryKey, version, locked) {
    const view = locked ? this.view : await this._enter()
    try {
      if (version === VERSION) return

      const target = { version: VERSION, dryRun: false }

      switch (version) {
        case 0: {
          await require('./migrations/0').core(core, target)
          break
        }
        case 1: {
          await require('./migrations/1').core(core, target)
          break
        }
        default: {
          throw new Error(
            'Unsupported version: ' + version + ' - you should probably upgrade your dependencies'
          )
        }
      }

      if (locked === false) return

      // if its locked, then move the core state into the memview
      // in case the core is reopened from the memview, pre flush

      const rx = new CorestoreRX(this.db, EMPTY)
      const tx = new CorestoreTX(view)

      const corePromise = rx.getCore(discoveryKey)
      rx.tryFlush()

      tx.putCore(discoveryKey, await corePromise)
      tx.apply()
    } finally {
      if (!locked) await this._exit()
    }
  }

  async _enter() {
    this.enters++
    await this.lock.lock()
    if (this.view === null) this.view = new View()
    return this.view
  }

  async _exit() {
    this.enters--

    if (this.flushing === null) this.flushing = rrp()
    const flushed = this.flushing.promise

    if (this.enters === 0 || this.view.size() > 128) {
      try {
        await View.flush(this.view.changes, this.db)
        this.flushing.resolve()
      } catch (err) {
        this.flushing.reject(err)
      } finally {
        this.flushing = null
        this.view = null
      }
    }

    this.lock.unlock()
    return flushed
  }

  // when used with core catches this isnt transactional for simplicity, HOWEVER, its just a number
  // so worth the tradeoff
  async _allocData() {
    let dataPointer = 0

    const view = await this._enter()
    const tx = new CorestoreTX(view)

    try {
      const head = await this._getHead(view)

      dataPointer = head.datas++

      tx.setHead(head)
      tx.apply()
    } finally {
      await this._exit()
    }

    return dataPointer
  }

  // exposes here so migrations can easily access the head in an init state
  async _getHead(view) {
    const rx = new CorestoreRX(this.db, view)
    const headPromise = rx.getHead()
    rx.tryFlush()

    const head = await headPromise
    return head === null ? initStoreHead() : head
  }

  createAtom() {
    return new Atom(this.db)
  }

  async flush() {
    await this.rocks.flush()
  }

  async close() {
    if (this.db.closed) return
    await this._flush()
    await this.db.close()
    await this.rocks.close()
    this.treeCache.destroy()
    if (this.deviceFile) await this.deviceFile.close()
  }

  async clear() {
    if (this.version === 0) await this._migrateStore()

    const view = await this._enter()
    const tx = new CorestoreTX(view)

    tx.clear()
    tx.apply()

    await this._exit()
  }

  createCoreStream() {
    // TODO: be nice to run the mgiration here also, but too much plumbing atm
    return createCoreStream(this.db, EMPTY)
  }

  createAliasStream(namespace) {
    // TODO: be nice to run the mgiration here also, but too much plumbing atm
    return createAliasStream(this.db, EMPTY, namespace)
  }

  createDiscoveryKeyStream(namespace) {
    return createDiscoveryKeyStream(this.db, EMPTY, namespace)
  }

  createGroupUpdateStream(group, { since, reverse } = {}) {
    return createGroupUpdateStream(this.db, EMPTY, group, { gte: since, reverse })
  }

  async getAlias(alias) {
    if (this.version === 0) await this._migrateStore()

    const rx = new CorestoreRX(this.db, EMPTY)
    const discoveryKeyPromise = rx.getCoreByAlias(alias)
    rx.tryFlush()
    return discoveryKeyPromise
  }

  async getSeed() {
    if (this.version === 0) await this._migrateStore()

    const rx = new CorestoreRX(this.db, EMPTY)
    const headPromise = rx.getHead()

    rx.tryFlush()

    const head = await headPromise
    return head === null ? null : head.seed
  }

  async getGroup(topic) {
    if (this.version === 0) await this._migrateStore()

    const rx = new CorestoreRX(this.db, EMPTY)
    const groupPromise = rx.getGroup(topic)
    rx.tryFlush()
    return groupPromise
  }

  async setSeed(seed, { overwrite = true } = {}) {
    if (this.version === 0) await this._migrateStore()

    const view = await this._enter()
    const tx = new CorestoreTX(view)

    try {
      const rx = new CorestoreRX(this.db, view)
      const headPromise = rx.getHead()

      rx.tryFlush()

      const head = (await headPromise) || initStoreHead()

      if (head.seed === null || overwrite) head.seed = seed
      tx.setHead(head)
      tx.apply()

      return head.seed
    } finally {
      await this._exit()
    }
  }

  async setRecovering(view = null) {
    const recovering = Date.now()
    let keys = []

    for await (const data of this.createDiscoveryKeyStream()) {
      keys.push(data)
      if (keys.length > 16 * 1024) {
        await this._flushRecovering(recovering, view, keys)
        keys = []
      }
    }

    if (keys.length) await this._flushRecovering(recovering, view, keys)
  }

  async _flushRecovering(recovering, view, keys) {
    const own = !view
    if (own) view = await this._enter()
    const tx = new CorestoreTX(view)

    try {
      const infos = await this._getInfos(keys, { auth: false, head: false, hints: true })
      for (const inf of infos) {
        tx.setCoreHints(inf.core, { ...inf.hints, recovering })
      }
      tx.apply()
    } finally {
      if (own) await this._exit()
    }
  }

  async getDefaultDiscoveryKey() {
    if (this.version === 0) await this._migrateStore()

    const rx = new CorestoreRX(this.db, EMPTY)
    const headPromise = rx.getHead()

    rx.tryFlush()

    const head = await headPromise
    return head === null ? null : head.defaultDiscoveryKey
  }

  async setDefaultDiscoveryKey(discoveryKey, { overwrite = true } = {}) {
    if (this.version === 0) await this._migrateStore()

    const view = await this._enter()
    const tx = new CorestoreTX(view)

    try {
      const rx = new CorestoreRX(this.db, view)
      const headPromise = rx.getHead()

      rx.tryFlush()

      const head = (await headPromise) || initStoreHead()

      if (head.defaultDiscoveryKey === null || overwrite) head.defaultDiscoveryKey = discoveryKey
      tx.setHead(head)
      tx.apply()

      return head.defaultDiscoveryKey
    } finally {
      await this._exit()
    }
  }

  async hasCore(discoveryKey, { ifMigrated = false } = {}) {
    if (this.version === 0) await this._migrateStore()

    const rx = new CorestoreRX(this.db, EMPTY)
    const promise = rx.getCore(discoveryKey)

    rx.tryFlush()

    const core = await promise

    if (core === null) return false
    if (core.version === 0 && ifMigrated) return false

    return true
  }

  async getAuth(discoveryKey) {
    if (this.version === 0) await this._migrateStore()

    const rx = new CorestoreRX(this.db, EMPTY)
    const corePromise = rx.getCore(discoveryKey)

    rx.tryFlush()

    const core = await corePromise
    if (core === null) return null

    const read = this.db.read({ autoDestroy: true })
    const authPromise = CoreRX.getAuth(read, core)

    read.tryFlush()

    return authPromise
  }

  async getInfo(discoveryKey, opts) {
    return (await this.getInfos([discoveryKey], opts))[0]
  }

  async getInfos(discoveryKeys, opts) {
    if (this.version === 0) await this._migrateStore()
    return this._getInfos(discoveryKeys, opts)
  }

  async _getInfos(discoveryKeys, { auth = true, head = true, hints = true } = {}) {
    const rx = new CorestoreRX(this.db, EMPTY)
    const corePromises = new Array(discoveryKeys.length)

    for (let i = 0; i < discoveryKeys.length; i++) {
      corePromises[i] = rx.getCore(discoveryKeys[i])
    }

    rx.tryFlush()

    const cores = await Promise.all(corePromises)
    const read = this.db.read({ autoDestroy: true })

    const resultPromises = new Array(cores.length)

    for (let i = 0; i < cores.length; i++) {
      resultPromises[i] = cores[i]
        ? getInfoFromBatch(read, cores[i], discoveryKeys[i], auth, head, hints)
        : null
    }

    read.tryFlush()

    return Promise.all(resultPromises)
  }

  async suspend({ log = noop } = {}) {
    await log('Suspending hypercore storage...')
    await this.db.suspend()
    await log('db suspended')
    if (this.deviceFile) {
      await log('suspend deviceFile')
      await this.deviceFile.suspend()
      await log('deviceFile suspended')
    }
  }

  async resume() {
    if (this.deviceFile) await this.deviceFile.resume()
    await this.db.resume()
  }

  async resumeCore(discoveryKey) {
    if (this.version === 0) await this._migrateStore()

    if (!discoveryKey) {
      discoveryKey = await this.getDefaultDiscoveryKey()
      if (!discoveryKey) return null
    }

    const rx = new CorestoreRX(this.db, EMPTY)
    const corePromise = rx.getCore(discoveryKey)

    rx.tryFlush()
    const core = await corePromise

    if (core === null) return null
    return this._resumeFromPointers(EMPTY, discoveryKey, false, core)
  }

  async export(discoveryKey, opts) {
    const rx = new CorestoreRX(this.db, EMPTY)
    const corePromise = rx.getCore(discoveryKey)

    rx.tryFlush()
    const core = await corePromise
    if (core === null) return null

    let { dataPointer, corePointer } = core

    const ptr = { corePointer, dataPointer, dependencies: [] }

    while (true) {
      const rx = new CoreRX(
        { dataPointer, corePointer: 0, dependencies: [] },
        this.db,
        EMPTY,
        this.treeCache,
        this.stats,
        -1
      )
      const dependencyPromise = rx.getDependency()
      rx.tryFlush()
      const dependency = await dependencyPromise
      if (!dependency) break
      ptr.dependencies.push(dependency)
      dataPointer = dependency.dataPointer
    }

    const session = this.db.session()
    try {
      return await HypercoreStorage.export(ptr, session, opts)
    } finally {
      await session.close()
    }
  }

  async _resumeFromPointers(view, discoveryKey, create, { version, corePointer, dataPointer }) {
    const core = { corePointer, dataPointer, dependencies: [] }

    while (true) {
      const rx = new CoreRX(
        { dataPointer, corePointer: 0, dependencies: [] },
        this.db,
        view,
        this.treeCache,
        this.stats,
        -1
      )
      const dependencyPromise = rx.getDependency()
      rx.tryFlush()
      const dependency = await dependencyPromise
      if (!dependency) break
      core.dependencies.push(dependency)
      dataPointer = dependency.dataPointer
    }

    const result = new HypercoreStorage(this, this.db.session(), this.treeCache, core, EMPTY, null)

    if (version < VERSION) await this._migrateCore(result, discoveryKey, version, create)
    return result
  }

  // not allowed to throw validation errors as its a shared tx!
  async _create(
    view,
    { key, manifest, keyPair, encryptionKey, discoveryKey, alias, userData, core: ptrs }
  ) {
    const rx = new CorestoreRX(this.db, view)
    const tx = new CorestoreTX(view)

    const corePromise = rx.getCore(discoveryKey)
    const headPromise = rx.getHead()

    rx.tryFlush()

    let [core, head] = await Promise.all([corePromise, headPromise])
    if (core) return this._resumeFromPointers(view, discoveryKey, true, core)

    if (head === null) head = initStoreHead()
    if (head.defaultDiscoveryKey === null) head.defaultDiscoveryKey = discoveryKey

    const corePointer = ptrs ? ptrs.corePointer : head.cores++
    const dataPointer = ptrs ? ptrs.dataPointer : head.datas++

    core = { version: VERSION, corePointer, dataPointer, alias }

    tx.setHead(head)
    tx.putCore(discoveryKey, core)
    if (alias) tx.putCoreByAlias(alias, discoveryKey)

    const ptr = { corePointer, dataPointer, dependencies: [] }
    const ctx = new CoreTX(ptr, this.db, view, tx.changes)

    ctx.setAuth({
      key,
      discoveryKey,
      manifest,
      keyPair,
      encryptionKey
    })

    if (userData) {
      for (const { key, value } of userData) {
        ctx.putUserData(key, value)
      }
    }

    tx.apply()

    return new HypercoreStorage(this, this.db.session(), this.treeCache, ptr, EMPTY, null)
  }

  async createCore(data) {
    if (this.version === 0) await this._migrateStore()

    const view = await this._enter()

    try {
      return await this._create(view, data)
    } finally {
      await this._exit()
    }
  }

  // not allowed to throw validation errors as its a shared tx!
  async _createGroup(view, topic) {
    const rx = new CorestoreRX(this.db, view)
    const tx = new CorestoreTX(view)

    const groupPromise = rx.getGroup(topic)
    const headPromise = rx.getHead()

    rx.tryFlush()

    let group = await groupPromise
    if (group !== null) {
      return {
        key: topic,
        pointer: group
      }
    }

    let head = await headPromise
    if (head === null) head = initStoreHead()

    group = head.groups++

    tx.putGroup(topic, group)
    tx.setHead(head)
    tx.apply()

    return {
      key: topic,
      pointer: group
    }
  }

  async createGroup(topic) {
    if (this.version === 0) await this._migrateStore()

    const view = await this._enter()

    try {
      return await this._createGroup(view, topic)
    } finally {
      await this._exit()
    }
  }

  static isParentStorage(storage, parent) {
    return HypercoreStorage.isParentStorage(storage, parent)
  }
}

module.exports = CorestoreStorage

function initStoreHead() {
  return {
    version: 0, // cause we wanna run the migration
    datas: 0,
    cores: 0,
    groups: 0,
    seed: null,
    defaultDiscoveryKey: null
  }
}

function getSession(sessions, name, alloc) {
  for (let i = 0; i < sessions.length; i++) {
    if (sessions[i].name === name) return sessions[i]
  }

  if (!alloc) return null

  const result = { name, dataPointer: -1 }
  sessions.push(result)
  return result
}

function isCorestoreStorage(s) {
  return typeof s === 'object' && !!s && typeof s.setDefaultDiscoveryKey === 'function'
}

function createColumnFamily(db, opts = {}) {
  const {
    tableCacheIndexAndFilterBlocks = true,
    blockCache = true,
    optimizeFiltersForMemory = false,
    blobFileSize = 256 * 1024 * 1024,
    blobGarbageCollectionAgeCutOff = 0.25,
    blobGarbageCollectionForceThreshold = 1.0
  } = opts

  const col = new RocksDB.ColumnFamily(COLUMN_FAMILY, {
    enableBlobFiles: true,
    minBlobSize: 4096,
    blobFileSize,
    enableBlobGarbageCollection: true,
    tableBlockSize: 8192,
    tableCacheIndexAndFilterBlocks,
    tableFormatVersion: 6,
    optimizeFiltersForMemory,
    blockCache,
    blobGarbageCollectionAgeCutOff,
    blobGarbageCollectionForceThreshold
  })

  return db.columnFamily(col)
}

function getLastDependency(storage) {
  return storage.dependencies.length ? storage.dependencies[storage.dependencies.length - 1] : null
}

// TODO: remove in like 3-6 mo
function tmpFixStorage(p) {
  // if CORESTORE file is written, new format
  if (fs.existsSync(path.join(p, 'CORESTORE'))) return

  let files = []

  try {
    files = fs.readdirSync(p)
  } catch {}

  const notRocks = new Set([
    'CORESTORE',
    'primary-key',
    'cores',
    'app-preferences',
    'cache',
    'preferences.json',
    'db',
    'clone',
    'core',
    'notifications'
  ])

  for (const f of files) {
    if (notRocks.has(f)) continue

    try {
      fs.mkdirSync(path.join(p, 'db'))
    } catch {}

    fs.renameSync(path.join(p, f), path.join(p, 'db', f))
  }
}

async function exportData(ptr, db, opts) {
  // just need dataPointer
  const reads = [
    toArray(createBlockStream(ptr, db, EMPTY, opts)),
    toArray(createTreeNodeStream(ptr, db, EMPTY, opts)),
    toArray(createBitfieldStream(ptr, db, EMPTY, opts))
  ]

  const [blocks, tree, bitfield] = await Promise.all(reads)

  return {
    blocks,
    tree,
    bitfield
  }
}

async function toArray(stream) {
  const all = []
  for await (const e of stream) all.push(e)
  return all
}

async function fileExists(path) {
  try {
    await fs.promises.stat(path)
    return true
  } catch {
    return false
  }
}

function shouldRecover(err) {
  return err.message.toLowerCase().indexOf('sequence number is being set backwards') > -1
}

function noop() {}

async function getInfoFromBatch(db, c, discoveryKey, getAuth, getHead, getHints) {
  const authPromise = getAuth ? CoreRX.getAuth(db, c) : null
  const headPromise = getHead ? CoreRX.getHead(db, c) : null
  const hintsPromise = getHints ? CoreRX.getHints(db, c) : null

  // ensure no uncaughts
  if (authPromise) authPromise.catch(noop)
  if (headPromise) headPromise.catch(noop)
  if (hintsPromise) hintsPromise.catch(noop)

  return {
    discoveryKey,
    core: c,
    auth: await authPromise,
    head: await headPromise,
    hints: await hintsPromise
  }
}
const { Readable, getStreamError } = require('streamx')
const { core } = require('./keys')

module.exports = class BlockStream extends Readable {
  constructor(core, db, updates, start, end, reverse) {
    super()

    this.core = core
    this.db = db
    this.updates = updates
    this.start = start
    this.end = end
    this.reverse = reverse === true

    this._drained = true
    this._consumed = 0
    this._stream = null
    this._oncloseBound = this._onclose.bind(this)
    this._maybeDrainBound = this._maybeDrain.bind(this)

    this._update()
  }

  _update() {
    if (this._consumed > this.core.dependencies.length) return

    const deps = this.core.dependencies
    const index = this._findDependencyIndex(deps)

    const curr = index < deps.length ? deps[index] : null
    const prev = index > 0 && index - 1 < deps.length ? deps[index - 1] : null

    const start = prev && prev.length > this.start ? prev.length : this.start
    const end = curr && (this.end === -1 || curr.length < this.end) ? curr.length : this.end

    const ptr = curr ? curr.dataPointer : this.core.dataPointer

    this._makeStream(core.block(ptr, start), core.block(ptr, end))
  }

  _findDependencyIndex(deps) {
    if (!this.reverse) return this._consumed++

    let i = deps.length - this._consumed++
    while (i > 0) {
      if (deps[i - 1].length <= this.end) return i
      i--
      this._consumed++
    }

    return 0
  }

  _predestroy() {
    if (this._stream !== null) this._stream.destroy()
  }

  _read(cb) {
    this._drained = this._onreadable()
    cb(null)
  }

  _maybeDrain() {
    if (this._drained === true) return
    this._drained = this._onreadable()
  }

  _onreadable() {
    if (this._stream === null) {
      this.push(null)
      return true
    }

    let data = this._stream.read()

    if (data === null) return false

    do {
      this.push(data)
      data = this._stream.read()
    } while (data !== null)

    return true
  }

  _onclose() {
    if (this.destroying) return

    const err = getStreamError(this._stream)

    if (err !== null) {
      this.destroy(err)
      return
    }

    // empty the current stream
    if (this._onreadable() === true) this._drained = true

    this._stream = null

    this._update()
    this._maybeDrain()
  }

  _makeStream(start, end) {
    this._stream = this.updates.iterator(this.db, start, end, this.reverse)
    this._stream.on('readable', this._maybeDrainBound)
    this._stream.on('error', noop)
    this._stream.on('close', this._oncloseBound)
  }
}

function noop() {}
const { Readable } = require('streamx')

// used for returned a stream that just errors (during read during teardown)

module.exports = class CloseErrorStream extends Readable {
  constructor(err) {
    super()
    this.error = err
  }

  _open(cb) {
    cb(this.error)
  }
}
const { UINT, STRING } = require('index-encoder')
const c = require('compact-encoding')
const b4a = require('b4a')

const TL_HEAD = 0
const TL_CORE_BY_DKEY = 1
const TL_CORE_BY_ALIAS = 2
const TL_CORE = 3
const TL_DATA = 4
const TL_GROUP_BY_TOPIC = 5
const TL_GROUP = 6

const TL_END = TL_GROUP + 1

const CORE_AUTH = 0
const CORE_SESSIONS = 1
const CORE_GROUP = 2

const DATA_HEAD = 0
const DATA_DEPENDENCY = 1
const DATA_HINTS = 2
const DATA_BLOCK = 3
const DATA_TREE = 4
const DATA_BITFIELD = 5
const DATA_USER_DATA = 6
const DATA_LOCAL = 7
const DATA_MARK = 8

const slab = { buffer: b4a.allocUnsafe(65536), start: 0, end: 0 }

const store = {}
const core = {}
const group = {}

store.clear = function () {
  const state = alloc()
  let start = state.start
  UINT.encode(state, 0)
  const a = state.buffer.subarray(start, state.start)
  start = state.start
  UINT.encode(state, TL_END)
  const b = state.buffer.subarray(start, state.start)
  return [a, b]
}

store.head = function () {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_HEAD)
  return state.buffer.subarray(start, state.start)
}

store.core = function (discoveryKey) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE_BY_DKEY)
  c.fixed32.encode(state, discoveryKey)
  return state.buffer.subarray(start, state.start)
}

store.coreStart = function () {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE_BY_DKEY)
  return state.buffer.subarray(start, state.start)
}

store.coreEnd = function () {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE_BY_DKEY + 1)
  return state.buffer.subarray(start, state.start)
}

store.coreByAlias = function ({ namespace, name }) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE_BY_ALIAS)
  c.fixed32.encode(state, namespace)
  STRING.encode(state, name)
  return state.buffer.subarray(start, state.start)
}

store.coreByAliasStart = function (namespace) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE_BY_ALIAS)
  if (namespace) c.fixed32.encode(state, namespace)
  return state.buffer.subarray(start, state.start)
}

store.coreByAliasEnd = function (namespace) {
  const state = alloc()
  const start = state.start

  if (namespace) {
    UINT.encode(state, TL_CORE_BY_ALIAS)
    c.fixed32.encode(state, namespace)
    state.buffer[state.start++] = 0xff
  } else {
    UINT.encode(state, TL_CORE_BY_ALIAS + 1)
  }

  return state.buffer.subarray(start, state.start)
}

store.alias = function (buffer) {
  const state = { buffer, start: 0, end: buffer.byteLength }
  UINT.decode(state) // ns
  const namespace = c.fixed32.decode(state)
  const name = STRING.decode(state)
  return { namespace, name }
}

store.discoveryKey = function (buffer) {
  const state = { buffer, start: 0, end: buffer.byteLength }
  UINT.decode(state) // ns
  return c.fixed32.decode(state)
}

core.core = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE)
  UINT.encode(state, ptr)
  return state.buffer.subarray(start, state.start)
}

core.data = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  return state.buffer.subarray(start, state.start)
}

core.auth = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE)
  UINT.encode(state, ptr)
  UINT.encode(state, CORE_AUTH)
  return state.buffer.subarray(start, state.start)
}

core.group = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE)
  UINT.encode(state, ptr)
  UINT.encode(state, CORE_GROUP)
  return state.buffer.subarray(start, state.start)
}

core.sessions = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE)
  UINT.encode(state, ptr)
  UINT.encode(state, CORE_SESSIONS)
  return state.buffer.subarray(start, state.start)
}

core.head = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_HEAD)
  return state.buffer.subarray(start, state.start)
}

core.dependency = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_DEPENDENCY)
  return state.buffer.subarray(start, state.start)
}

core.hints = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_HINTS)
  return state.buffer.subarray(start, state.start)
}

core.block = function (ptr, index) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_BLOCK)
  UINT.encode(state, index)
  return state.buffer.subarray(start, state.start)
}

core.tree = function (ptr, index) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_TREE)
  UINT.encode(state, index)
  return state.buffer.subarray(start, state.start)
}

core.bitfield = function (ptr, index, type) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_BITFIELD)
  UINT.encode(state, index)
  UINT.encode(state, type)
  return state.buffer.subarray(start, state.start)
}

core.userData = function (ptr, key) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_USER_DATA)
  STRING.encode(state, key)
  return state.buffer.subarray(start, state.start)
}

core.userDataEnd = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_USER_DATA + 1)
  return state.buffer.subarray(start, state.start)
}

core.mark = function (ptr, index) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_MARK)
  UINT.encode(state, index)
  return state.buffer.subarray(start, state.start)
}

core.local = function (ptr, key) {
  if (key.byteLength > 2048) {
    throw new Error('local keys has an upper limit of 2048 bytes atm')
  }

  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_LOCAL)

  state.buffer.set(key, state.start)
  state.start += key.byteLength
  return state.buffer.subarray(start, state.start)
}

core.localEnd = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_LOCAL + 1)
  return state.buffer.subarray(start, state.start)
}

core.blockIndex = function (buffer) {
  const state = { buffer, start: 0, end: buffer.byteLength }
  UINT.decode(state) // ns
  UINT.decode(state) // ptr
  UINT.decode(state) // type
  return UINT.decode(state)
}

core.bitfieldIndexAndType = function (buffer) {
  const state = { buffer, start: 0, end: buffer.byteLength }
  UINT.decode(state) // ns
  UINT.decode(state) // ptr
  UINT.decode(state) // type
  return [UINT.decode(state), UINT.decode(state)]
}

core.userDataKey = function (buffer) {
  const state = { buffer, start: 0, end: buffer.byteLength }
  UINT.decode(state) // ns
  UINT.decode(state) // ptr
  UINT.decode(state) // type
  return STRING.decode(state)
}

core.markKey = function (buffer) {
  const state = { buffer, start: 0, end: buffer.byteLength }
  UINT.decode(state) // ns
  UINT.decode(state) // ptr
  UINT.decode(state) // type
  return UINT.decode(state)
}

core.localKey = function (buffer) {
  const state = { buffer, start: 0, end: buffer.byteLength }
  UINT.decode(state) // ns
  UINT.decode(state) // ptr
  UINT.decode(state) // type
  return state.buffer.subarray(state.start, state.end)
}

group.topic = function (topic) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_GROUP_BY_TOPIC)
  c.fixed32.encode(state, topic)
  return state.buffer.subarray(start, state.start)
}

group.entry = function (group, timestamp, ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_GROUP)
  UINT.encode(state, group)
  c.uint64be.encode(state, timestamp)
  UINT.encode(state, ptr)
  return state.buffer.subarray(start, state.start)
}

module.exports = { store, core, group }

function alloc() {
  if (slab.buffer.byteLength - slab.start < 4096) {
    slab.buffer = b4a.allocUnsafe(slab.buffer.byteLength)
    slab.start = 0
  }
  return slab
}
const b4a = require('b4a')
const BlockDependencyStream = require('./block-dependency-stream.js')
const { core, store, group } = require('./keys.js')
const schema = require('../encoding/spec/hyperschema')

const CORESTORE_CORE = schema.getEncoding('@corestore/core')
const CORE_TREE_NODE = schema.getEncoding('@core/tree-node')
const EMPTY = b4a.alloc(0)

module.exports = {
  createBlockStream,
  createBitfieldStream,
  createUserDataStream,
  createCoreStream,
  createAliasStream,
  createDiscoveryKeyStream,
  createTreeNodeStream,
  createMarkStream,
  createLocalStream,
  createGroupUpdateStream
}

function createCoreStream(db, view) {
  const start = store.coreStart()
  const end = store.coreEnd()

  const ite = view.iterator(db, start, end, false)

  ite._readableState.map = mapCore
  return ite
}

function createDiscoveryKeyStream(db, view, namespace) {
  const start = namespace ? store.coreByAliasStart(namespace) : store.coreStart()
  const end = namespace ? store.coreByAliasEnd(namespace) : store.coreEnd()

  const ite = view.iterator(db, start, end, false)

  ite._readableState.map = namespace ? mapNamespaceDiscoveryKeys : mapAllDiscoveryKeys
  return ite
}

function createAliasStream(db, view, namespace) {
  const start = store.coreByAliasStart(namespace)
  const end = store.coreByAliasEnd(namespace)

  const ite = view.iterator(db, start, end, false)

  ite._readableState.map = mapAlias
  return ite
}

function createGroupUpdateStream(db, view, groupID, { gte = 0, reverse = true } = {}) {
  const start = group.entry(groupID, gte, 0)
  const end = group.entry(groupID + 1, 0, 0)

  const ite = view.iterator(db, start, end, reverse)

  ite._readableState.map = mapGroupUpdate
  return ite
}

function createBlockIterator(ptr, db, view, start, end, reverse) {
  if (ptr.dependencies.length > 0) {
    return new BlockDependencyStream(ptr, db, view, start, end, reverse)
  }

  const s = core.block(ptr.dataPointer, start)
  const e = core.block(ptr.dataPointer, end === -1 ? Infinity : end)
  return view.iterator(db, s, e, reverse)
}

function createBlockStream(
  ptr,
  db,
  view,
  { gt = -1, gte = gt + 1, lte = -1, lt = lte === -1 ? -1 : lte + 1, reverse = false } = {}
) {
  const ite = createBlockIterator(ptr, db, view, gte, lt, reverse)

  ite._readableState.map = mapBlock
  return ite
}

function createBitfieldStream(
  ptr,
  db,
  view,
  { gt = -1, gte = gt + 1, lte = -1, lt = lte === -1 ? -1 : lte + 1, reverse = false } = {}
) {
  const s = core.bitfield(ptr.dataPointer, gte, 0)
  const e = core.bitfield(ptr.dataPointer, lt === -1 ? Infinity : lt, 0)
  const ite = view.iterator(db, s, e, false)

  ite._readableState.map = mapBitfield
  return ite
}

// NOTE: this does not do dependency lookups atm
function createTreeNodeStream(
  ptr,
  db,
  view,
  { gt = -1, gte = gt + 1, lte = -1, lt = lte === -1 ? -1 : lte + 1, reverse = false } = {}
) {
  const s = core.tree(ptr.dataPointer, gte, 0)
  const e = core.tree(ptr.dataPointer, lt === -1 ? Infinity : lt, 0)
  const ite = view.iterator(db, s, e, false)

  ite._readableState.map = mapTreeNode
  return ite
}

function createUserDataStream(
  ptr,
  db,
  view,
  { gt = null, gte = '', lte = null, lt = null, reverse = false } = {}
) {
  if (gt !== null || lte !== null) {
    throw new Error('gt and lte not yet supported for user data streams')
  }

  const s = core.userData(ptr.dataPointer, gte)
  const e = lt === null ? core.userDataEnd(ptr.dataPointer) : core.userData(ptr.dataPointer, lt)
  const ite = view.iterator(db, s, e, false)

  ite._readableState.map = mapUserData
  return ite
}

function createMarkStream(
  ptr,
  db,
  view,
  { gt = -1, gte = gt + 1, lte = -1, lt = lte === -1 ? -1 : lte + 1, reverse = false } = {}
) {
  const s = core.mark(ptr.dataPointer, gte)
  const e = core.mark(ptr.dataPointer, lt === -1 ? Infinity : lt)
  const ite = view.iterator(db, s, e, reverse)

  ite._readableState.map = mapMark
  return ite
}

function createLocalStream(
  ptr,
  db,
  view,
  { gt = null, gte = EMPTY, lte = null, lt = null, reverse = false } = {}
) {
  if (gt !== null || lte !== null) throw new Error('gt and lte not yet supported for local streams')

  const s = core.local(ptr.dataPointer, gte)
  const e = lt === null ? core.localEnd(ptr.dataPointer) : core.local(ptr.dataPointer, lt)
  const ite = view.iterator(db, s, e, false)

  ite._readableState.map = mapLocal
  return ite
}

function mapBitfield(data) {
  const [index, type] = core.bitfieldIndexAndType(data.key)
  if (type !== 0) return null // ignore for now
  return { index, page: data.value }
}

function mapMark(data) {
  const index = core.markKey(data.key)
  return { index, page: data.value }
}

function mapLocal(data) {
  const key = core.localKey(data.key)
  return { key, value: data.value }
}

function mapGroupUpdate(data) {
  return data.value
}

function mapUserData(data) {
  const key = core.userDataKey(data.key)
  return { key, value: data.value }
}

function mapCore(data) {
  const discoveryKey = store.discoveryKey(data.key)
  const core = CORESTORE_CORE.decode({
    start: 0,
    end: data.value.byteLength,
    buffer: data.value
  })
  return { discoveryKey, core }
}

function mapAllDiscoveryKeys(data) {
  return store.discoveryKey(data.key)
}

function mapNamespaceDiscoveryKeys(data) {
  return data.value
}

function mapAlias(data) {
  const alias = store.alias(data.key)
  return { alias, discoveryKey: data.value }
}

function mapBlock(data) {
  return { index: core.blockIndex(data.key), value: data.value }
}

function mapTreeNode(data) {
  return CORE_TREE_NODE.decode({
    start: 0,
    end: data.value.byteLength,
    buffer: data.value
  })
}
const b4a = require('b4a')
const c = require('compact-encoding')
const flat = require('flat-tree')

const schema = require('../encoding/spec/hyperschema')
const { store, core, group } = require('./keys.js')
const View = require('./view.js')

const CORESTORE_HEAD = schema.getEncoding('@corestore/head')
const CORESTORE_CORE = schema.getEncoding('@corestore/core')
const CORESTORE_GROUP = c.uint

const CORE_AUTH = schema.getEncoding('@core/auth')
const CORE_GROUP = schema.getEncoding('@core/group')
const CORE_SESSIONS = schema.getEncoding('@core/sessions')
const CORE_HEAD = schema.getEncoding('@core/head')
const CORE_TREE_NODE = schema.getEncoding('@core/tree-node')
const CORE_DEPENDENCY = schema.getEncoding('@core/dependency')
const CORE_HINTS = schema.getEncoding('@core/hints')

class CoreTX {
  constructor(core, db, view, changes) {
    if (db.snapshotted) throw new Error('Cannot open core tx on snapshot')
    this.core = core
    this.db = db
    this.view = view
    this.changes = changes
  }

  setAuth(auth) {
    this.changes.push([core.auth(this.core.corePointer), encode(CORE_AUTH, auth), null])
  }

  setSessions(sessions) {
    this.changes.push([core.sessions(this.core.corePointer), encode(CORE_SESSIONS, sessions), null])
  }

  setHead(head) {
    this.changes.push([core.head(this.core.dataPointer), encode(CORE_HEAD, head), null])
  }

  deleteHead() {
    this.changes.push([core.head(this.core.dataPointer), null, null])
  }

  setDependency(dep) {
    this.changes.push([core.dependency(this.core.dataPointer), encode(CORE_DEPENDENCY, dep), null])
  }

  setGroup(group) {
    this.changes.push([core.group(this.core.dataPointer), encode(CORE_GROUP, group), null])
  }

  deleteGroup() {
    this.changes.push([core.group(this.core.dataPointer), null, null])
  }

  setHints(hints) {
    this.changes.push([core.hints(this.core.dataPointer), encode(CORE_HINTS, hints), null])
  }

  putBlock(index, data) {
    this.changes.push([core.block(this.core.dataPointer, index), data, null])
  }

  deleteBlock(index) {
    this.changes.push([core.block(this.core.dataPointer, index), null, null])
  }

  deleteBlockRange(start, end) {
    this.changes.push([
      core.block(this.core.dataPointer, start),
      null,
      core.block(this.core.dataPointer, end === -1 ? Infinity : end)
    ])
  }

  putBitfieldPage(index, data) {
    this.changes.push([core.bitfield(this.core.dataPointer, index, 0), data, null])
  }

  deleteBitfieldPage(index) {
    this.changes.push([core.bitfield(this.core.dataPointer, index, 0), null, null])
  }

  deleteBitfieldPageRange(start, end) {
    this.changes.push([
      core.bitfield(this.core.dataPointer, start, 0),
      null,
      core.bitfield(this.core.dataPointer, end === -1 ? Infinity : end, 0)
    ])
  }

  putTreeNode(node) {
    this.changes.push([
      core.tree(this.core.dataPointer, node.index),
      encode(CORE_TREE_NODE, node),
      null
    ])
  }

  deleteTreeNode(index) {
    this.changes.push([core.tree(this.core.dataPointer, index), null, null])
  }

  deleteTreeNodeRange(start, end) {
    this.changes.push([
      core.tree(this.core.dataPointer, start),
      null,
      core.tree(this.core.dataPointer, end === -1 ? Infinity : end)
    ])
  }

  putUserData(key, value) {
    const buffer = typeof value === 'string' ? b4a.from(value) : value
    this.changes.push([core.userData(this.core.dataPointer, key), buffer, null])
  }

  deleteUserData(key) {
    this.changes.push([core.userData(this.core.dataPointer, key), null, null])
  }

  putMark(index, data) {
    this.changes.push([core.mark(this.core.dataPointer, index), data, null])
  }

  deleteMark(index) {
    this.changes.push([core.mark(this.core.dataPointer, index), null, null])
  }

  deleteMarkRange(start, end) {
    this.changes.push([
      core.mark(this.core.dataPointer, start),
      null,
      core.mark(this.core.dataPointer, end === -1 ? Infinity : end)
    ])
  }

  putLocal(key, value) {
    this.changes.push([core.local(this.core.dataPointer, key), value, null])
  }

  deleteLocal(key) {
    this.changes.push([core.local(this.core.dataPointer, key), null, null])
  }

  deleteLocalRange(start, end) {
    this.changes.push([
      core.local(this.core.dataPointer, start),
      null,
      end === null ? core.localEnd(this.core.dataPointer) : core.local(this.core.dataPointer, end)
    ])
  }

  putGroupUpdate(groupPtr, timestamp, key) {
    this.changes.push([group.entry(groupPtr, timestamp, this.core.corePointer), key, null])
  }

  deleteGroupUpdate(groupPtr, timestamp) {
    this.changes.push([group.entry(groupPtr, timestamp, this.core.corePointer), null, null])
  }

  flush() {
    const changes = this.changes
    if (changes === null) return Promise.resolve(!this.view)

    this.changes = null

    if (this.view) {
      this.view.apply(changes)
      return Promise.resolve(false)
    }

    return View.flush(changes, this.db)
  }
}

class CoreRX {
  constructor(core, db, view, treeCache, stats, fork) {
    this.core = core
    this.read = db.read({ autoDestroy: true })
    this.view = view
    this.treeCache = treeCache
    this.fork = fork
    this.stats = stats

    view.readStart()
  }

  static async getAuth(db, c) {
    return decode(CORE_AUTH, await db.get(core.auth(c.corePointer)))
  }

  async getAuth() {
    return decode(CORE_AUTH, await this.view.get(this.read, core.auth(this.core.corePointer)))
  }

  async getSessions() {
    return decode(
      CORE_SESSIONS,
      await this.view.get(this.read, core.sessions(this.core.corePointer))
    )
  }

  static async getHead(db, c) {
    return decode(CORE_HEAD, await db.get(core.head(c.dataPointer)))
  }

  async getHead() {
    return decode(CORE_HEAD, await this.view.get(this.read, core.head(this.core.dataPointer)))
  }

  async getDependency() {
    return decode(
      CORE_DEPENDENCY,
      await this.view.get(this.read, core.dependency(this.core.dataPointer))
    )
  }

  async getGroup() {
    return await decode(
      CORE_GROUP,
      await this.view.get(this.read, core.group(this.core.corePointer))
    )
  }

  static async getHints(db, c) {
    return decode(CORE_HINTS, await db.get(core.hints(c.dataPointer)))
  }

  async getHints() {
    return decode(CORE_HINTS, await this.view.get(this.read, core.hints(this.core.dataPointer)))
  }

  getBlock(index) {
    const dep = findBlockDependency(this.core.dependencies, index)
    const data = dep === null ? this.core.dataPointer : dep.dataPointer
    return this.view.get(this.read, core.block(data, index))
  }

  getBitfieldPage(index) {
    return this.view.get(this.read, core.bitfield(this.core.dataPointer, index, 0))
  }

  async _resolveTreeCache(key, promise, entry) {
    try {
      const value = decode(CORE_TREE_NODE, await promise)
      const cached = this.treeCache.get(key)

      // preflight is gone; no-op
      if (cached !== entry) return value

      if (value !== null) {
        // replace cached entry with value
        this.treeCache.set(key, { pending: null, value })
      } else {
        // discard non-existing values
        this.treeCache.delete(key)
      }

      return value
    } catch (err) {
      // cleanup
      const cached = this.treeCache.get(key)
      if (cached === entry) {
        this.treeCache.delete(key)
      }

      throw err
    }
  }

  async getTreeNode(index) {
    const dep = findTreeDependency(this.core.dependencies, index)
    const data = dep === null ? this.core.dataPointer : dep.dataPointer

    if (!this.treeCache || this.fork < 0) {
      if (this.stats !== null) this.stats.treeCache.skips++
      // no-cache
      return decode(CORE_TREE_NODE, await this.view.get(this.read, core.tree(data, index)))
    }

    const key = `${data}:${index}:${this.fork}`
    let entry = this.treeCache.get(key)
    if (entry) {
      if (entry.pending) {
        if (this.stats !== null) this.stats.treeCache.parallel++
        return entry.pending
      }

      if (this.stats !== null) this.stats.treeCache.hits++
      return entry.value
    }

    if (this.stats !== null) this.stats.treeCache.misses++

    const promise = this.view.get(this.read, core.tree(data, index))
    entry = { pending: null, value: null }
    entry.pending = this._resolveTreeCache(key, promise, entry)
    this.treeCache.set(key, entry)

    return entry.pending
  }

  async hasTreeNode(index) {
    return (await this.getTreeNode(index)) !== null
  }

  getUserData(key) {
    return this.view.get(this.read, core.userData(this.core.dataPointer, key))
  }

  getMark(index) {
    return this.view.get(this.read, core.mark(this.core.dataPointer, index))
  }

  getLocal(key) {
    return this.view.get(this.read, core.local(this.core.dataPointer, key))
  }

  tryFlush() {
    this.read.tryFlush()
    this._free()
  }

  destroy() {
    this.read.destroy()
    this._free()
  }

  _free() {
    if (this.view === null) return
    this.view.readStop()
    this.view = null
  }
}

class CorestoreTX {
  constructor(view) {
    this.view = view
    this.changes = []
  }

  setHead(head) {
    this.changes.push([store.head(), encode(CORESTORE_HEAD, head), null])
  }

  setCoreHints(c, hints) {
    this.changes.push([core.hints(c.dataPointer), encode(CORE_HINTS, hints), null])
  }

  putCore(discoveryKey, ptr) {
    this.changes.push([store.core(discoveryKey), encode(CORESTORE_CORE, ptr), null])
  }

  putCoreByAlias(alias, discoveryKey) {
    this.changes.push([store.coreByAlias(alias), discoveryKey, null])
  }

  putGroup(topic, groupPtr) {
    this.changes.push([group.topic(topic), encode(CORESTORE_GROUP, groupPtr), null])
  }

  deleteGroup(topic) {
    this.changes.push([group.topic(topic), null, null])
  }

  clear() {
    const [start, end] = store.clear()
    this.changes.push([start, null, end])
  }

  apply() {
    if (this.changes === null) return
    this.view.apply(this.changes)
    this.changes = null
  }
}

class CorestoreRX {
  constructor(db, view) {
    this.read = db.read({ autoDestroy: true })
    this.view = view

    view.readStart()
  }

  async getHeadRaw(db) {
    return await this.view.get(this.read, store.head())
  }

  async getHead() {
    return decode(CORESTORE_HEAD, await this.view.get(this.read, store.head()))
  }

  async getCore(discoveryKey) {
    return decode(CORESTORE_CORE, await this.view.get(this.read, store.core(discoveryKey)))
  }

  getCoreByAlias(alias) {
    return this.view.get(this.read, store.coreByAlias(alias))
  }

  async getGroup(topic) {
    return decode(CORESTORE_GROUP, await this.view.get(this.read, group.topic(topic)))
  }

  tryFlush() {
    this.read.tryFlush()
    this._free()
  }

  destroy() {
    this.read.destroy()
    this._free()
  }

  _free() {
    if (this.view === null) return
    this.view.readStop()
    this.view = null
  }
}

module.exports = { CorestoreTX, CorestoreRX, CoreTX, CoreRX }

function findBlockDependency(dependencies, index) {
  for (let i = 0; i < dependencies.length; i++) {
    const dep = dependencies[i]
    if (index < dep.length) return dep
  }

  return null
}

function findTreeDependency(dependencies, index) {
  for (let i = 0; i < dependencies.length; i++) {
    const dep = dependencies[i]
    if (flat.rightSpan(index) <= (dep.length - 1) * 2) return dep
  }

  return null
}

function decode(enc, buffer) {
  if (buffer === null) return null
  return enc.decode({ start: 0, end: buffer.byteLength, buffer })
}

function encode(enc, m) {
  // TODO: use fancy slab for small messages
  const state = { start: 0, end: 0, buffer: null }
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}
const { Readable, getStreamError } = require('streamx')
const CloseErrorStream = require('./close-error-stream.js')
const b4a = require('b4a')

class OverlayStream extends Readable {
  constructor(stream, start, end, reverse, changes, cleared) {
    super()

    this.start = start
    this.end = end
    this.reverse = reverse
    this.changes = changes
    this.cleared = cleared
    this.change = 0
    this.range = 0

    this._stream = stream
    this._drained = false

    this._stream.on('readable', this._drainMaybe.bind(this))
    this._stream.on('error', noop)
    this._stream.on('close', this._onclose.bind(this))
  }

  _drainMaybe() {
    if (this._drained === true) return
    this._drained = this._onreadable()
  }

  _onclose() {
    if (this.destroying) return

    const err = getStreamError(this._stream)

    if (err !== null) {
      this.destroy(err)
      return
    }

    while (this.change < this.changes.length) {
      const c = this.changes[this.change++]
      const key = c[0]
      const value = c[1]

      if (value !== null && this._inRange(key)) this.push({ key, value })
    }

    this.push(null)
    this._stream = null
  }

  _onreadable() {
    let data = this._stream.read()
    if (data === null) return false

    let drained = false

    do {
      if (this._push(data) === true) drained = true
      data = this._stream.read()
    } while (data !== null)

    return drained
  }

  _read(cb) {
    this._drained = this._onreadable()
    cb(null)
  }

  _predestroy() {
    this._stream.destroy()
  }

  _push(entry) {
    const key = entry.key

    while (this.range < this.cleared.length) {
      const c = this.cleared[this.range]

      // we moved past the range
      if (this.reverse ? b4a.compare(key, c[0]) < 0 : b4a.compare(c[2], key) <= 0) {
        this.range++
        continue
      }

      // we didnt move past and are in, drop
      if (b4a.compare(c[0], key) <= 0 && b4a.compare(key, c[2]) < 0) {
        return false
      }

      break
    }

    let updated = false

    while (this.change < this.changes.length) {
      const c = this.changes[this.change]
      const key = c[0]
      const value = typeof c[1] === 'string' ? b4a.from(c[1]) : c[1]
      const cmp = b4a.compare(key, entry.key)

      // same value, if not deleted, return new one
      if (cmp === 0) {
        this.change++
        if (value === null || this._inRange(key) === false) return updated
        this.push({ key, value })
        return true
      }

      // we moved past the change, push it
      if (this.reverse ? cmp > 0 : cmp < 0) {
        this.change++
        if (value === null || this._inRange(key) === false) continue
        this.push({ key, value })
        updated = true
        continue
      }

      this.push(entry)
      return true
    }

    this.push(entry)
    return true
  }

  _inRange(key) {
    return b4a.compare(this.start, key) <= 0 && b4a.compare(key, this.end) < 0
  }
}

class Overlay {
  constructor() {
    this.indexed = 0
    this.changes = null
    this.cleared = null
    this.reverse = false
  }

  update(view, reverse) {
    if (view.indexed === this.indexed) return

    const changes = view.map === null ? [] : [...view.map.values()]
    const cleared = view.cleared === null ? [] : view.cleared.slice(0)

    const cmp = reverse ? cmpChangeReverse : cmpChange

    changes.sort(cmp)
    cleared.sort(cmp)

    this.indexed = view.indexed
    this.changes = changes
    this.cleared = cleared
    this.reverse = reverse
  }

  createStream(stream, start, end, reverse) {
    return new OverlayStream(
      stream,
      start,
      end,
      reverse,
      this.reverse === reverse ? this.changes : reverseArray(this.changes),
      this.reverse === reverse ? this.cleared : reverseArray(this.cleared)
    )
  }
}

class View {
  constructor() {
    this.map = null
    this.indexed = 0
    this.changes = null
    this.cleared = null
    this.overlay = null
    this.snap = null
    this.readers = 0
  }

  snapshot() {
    if (this._attached()) return this.snap.snapshot()

    const snap = new View()

    snap.map = this.map
    snap.indexed = this.indexed
    snap.changes = this.changes
    snap.cleared = this.cleared

    if (this._frozen()) return snap

    this.readers++
    snap.snap = this

    return snap
  }

  readStart() {
    if (this.snap !== null) this.readers++
  }

  readStop() {
    if (this.snap !== null && --this.readers === 0) this.snap.readers--
  }

  size() {
    return this.changes === null ? 0 : this.changes.length
  }

  updated() {
    return this.changes === null
  }

  get(read, key) {
    return this.changes === null ? read.get(key) : this._indexAndGet(read, key)
  }

  reset() {
    this.indexed = 0
    this.snap = this.map = this.changes = this.cleared = this.overlay = null
  }

  iterator(db, start, end, reverse) {
    if (dbClosing(db)) return new CloseErrorStream(new Error('RocksDB session is closed'))

    const stream = db.iterator({ gte: start, lt: end, reverse })
    if (this.changes === null) return stream

    this._index()

    if (this.overlay === null) this.overlay = new Overlay()
    this.overlay.update(this, reverse)
    return this.overlay.createStream(stream, start, end, reverse)
  }

  _indexAndGet(read, key) {
    this._index()
    const change = this.map.get(b4a.toString(key, 'hex'))

    if (change === undefined) {
      return this.cleared === null ? read.get(key) : this._readAndMaybeDrop(read, key)
    }

    return Promise.resolve(change[1])
  }

  async _readAndMaybeDrop(read, key) {
    const cleared = this.cleared // in case its cleared
    const value = await read.get(key)
    if (value === null) return null

    for (let i = 0; i < cleared.length; i++) {
      const c = cleared[i]
      // check if in range
      if (b4a.compare(c[0], key) <= 0 && b4a.compare(key, c[2]) < 0) return null
    }

    return value
  }

  _attached() {
    return this.snap !== null && this.changes === this.snap.changes
  }

  _frozen() {
    return this.changes === null || (this.snap !== null && this.changes !== this.snap.changes)
  }

  _index() {
    // if we are a snap and we are still attached (ie no mutations), simply copy the refs
    if (this._attached()) {
      this.snap._index()
      this.map = this.snap.map
      this.cleared = this.snap.cleared
      this.indexed = this.snap.indexed
      return
    }

    if (this.map === null) this.map = new Map()
    if (this.changes.length === this.indexed) return

    while (this.indexed < this.changes.length) {
      const c = this.changes[this.indexed++]

      if (c[2] === null) this.map.set(b4a.toString(c[0], 'hex'), c)
      else this._indexRange(c)
    }
  }

  _indexRange(range) {
    const s = b4a.toString(range[0], 'hex')
    const e = b4a.toString(range[2], 'hex')

    for (const [key, c] of this.map) {
      if (s <= key && key < e) this.map.set(key, [c[0], null, null])
    }

    if (this.cleared === null) this.cleared = []
    this.cleared.push(range)
  }

  apply(changes) {
    if (this.snap !== null) throw new Error('Illegal to push changes to a snapshot')

    if (this.readers !== 0 && this.changes !== null) {
      this.changes = this.changes.slice(0)
      this.cleared = this.cleared === null ? null : this.cleared.slice(0)
      this.map = this.map === null ? null : new Map([...this.map])
    }

    if (this.changes === null) {
      this.changes = changes
      return
    }

    for (let i = 0; i < changes.length; i++) {
      this.changes.push(changes[i])
    }
  }

  static async flush(changes, db) {
    if (changes === null) return true

    const w = db.write({ autoDestroy: true })

    for (const [start, value, end] of changes) {
      if (end !== null) w.tryDeleteRange(start, end)
      else if (value !== null) w.tryPut(start, value)
      else w.tryDelete(start)
    }

    await w.flush()

    return true
  }
}

module.exports = View

function cmpChange(a, b) {
  const c = b4a.compare(a[0], b[0])
  return c === 0 ? b4a.compare(a[2], b[2]) : c
}

function cmpChangeReverse(a, b) {
  return cmpChange(b, a)
}

function noop() {}

function reverseArray(list) {
  const r = new Array(list.length)
  for (let i = 0; i < list.length; i++) r[r.length - 1 - i] = list[i]
  return r
}

// TODO: expose from rocks instead
function dbClosing(db) {
  return db._state.closing || db._index === -1
}
const fs = require('fs')
const path = require('path')
const { Readable } = require('streamx')
const b4a = require('b4a')
const flat = require('flat-tree')
const crypto = require('hypercore-crypto')
const c = require('compact-encoding')
const m = require('./messages.js')
const View = require('../../lib/view.js')
const { CorestoreTX, CoreTX, CorestoreRX } = require('../../lib/tx.js')

const EMPTY_NODE = b4a.alloc(40)
const EMPTY_PAGE = b4a.alloc(4096)

let TREE_01_SKIP = null
let TREE_04_SKIP = null
let TREE_16_SKIP = null

class CoreListStream extends Readable {
  constructor (storage) {
    super()

    this.storage = storage
    this.stack = []
  }

  async _open (cb) {
    for (const a of await readdir(path.join(this.storage, 'cores'))) {
      for (const b of await readdir(path.join(this.storage, 'cores', a))) {
        for (const dkey of await readdir(path.join(this.storage, 'cores', a, b))) {
          this.stack.push(path.join(this.storage, 'cores', a, b, dkey))
        }
      }
    }

    cb(null)
  }

  async _read (cb) {
    while (true) {
      const next = this.stack.pop()
      if (!next) {
        this.push(null)
        break
      }

      const oplog = path.join(next, 'oplog')
      const result = await readOplog(oplog)
      if (!result) continue

      this.push(result)
      break
    }

    cb(null)
  }
}

function decodeOplogHeader (state) {
  c.uint32.decode(state) // cksum, ignore for now

  const l = c.uint32.decode(state)
  const length = l >> 2
  const headerBit = l & 1
  const partialBit = l & 2

  if (state.end - state.start < length) return null

  const end = state.start + length
  const result = { header: headerBit, partial: partialBit !== 0, byteLength: length + 8, message: null }

  try {
    result.message = m.oplog.header.decode({ start: state.start, end, buffer: state.buffer })
  } catch {
    return null
  }

  state.start = end
  return result
}

function decodeOplogEntry (state) {
  if (state.end - state.start < 8) return null

  c.uint32.decode(state) // cksum, ignore for now

  const l = c.uint32.decode(state)
  const length = l >>> 2
  const headerBit = l & 1
  const partialBit = l & 2

  if (state.end - state.start < length) return null

  const end = state.start + length

  const result = { header: headerBit, partial: partialBit !== 0, byteLength: length + 8, message: null }

  try {
    result.message = m.oplog.entry.decode({ start: state.start, end, buffer: state.buffer })
  } catch {
    return null
  }

  state.start = end

  return result
}

module.exports = { store, core }

async function store (storage, { version, dryRun = true, gc = true }) {
  const stream = new CoreListStream(storage.path)
  const view = new View()

  const tx = new CorestoreTX(view)
  const head = await storage._getHead(view)
  const primaryKeyFile = path.join(storage.path, 'primary-key')

  const primaryKey = await readFile(primaryKeyFile)

  if (!head.seed) head.seed = primaryKey

  for await (const data of stream) {
    const key = data.header.key
    const discoveryKey = crypto.discoveryKey(data.header.key)
    const files = getFiles(data.path)

    if (head.defaultDiscoveryKey === null) head.defaultDiscoveryKey = discoveryKey

    const core = {
      version: 0, // need later migration
      corePointer: head.allocated.cores++,
      dataPointer: head.allocated.datas++,
      alias: null
    }

    const ptr = { version: 0, corePointer: core.corePointer, dataPointer: core.dataPointer, dependencies: [] }
    const ctx = new CoreTX(ptr, storage.db, view, [])
    const userData = new Map()
    const treeNodes = new Map()

    const auth = {
      key,
      discoveryKey,
      manifest: data.header.manifest,
      keyPair: data.header.keyPair,
      encryptionKey: null
    }

    const tree = {
      length: 0,
      fork: 0,
      rootHash: null,
      signature: null
    }

    if (data.header.tree && data.header.tree.length) {
      tree.length = data.header.tree.length
      tree.fork = data.header.tree.fork
      tree.rootHash = data.header.tree.rootHash
      tree.signature = data.header.tree.signature
    }

    for (const { key, value } of data.header.userData) {
      userData.set(key, value)
    }

    for (const e of data.entries) {
      if (e.userData) userData.set(e.userData.key, e.userData.value)

      if (e.treeNodes) {
        for (const node of e.treeNodes) {
          treeNodes.set(node.index, node)
          ctx.putTreeNode(node)
        }
      }

      if (e.treeUpgrade) {
        if (e.treeUpgrade.ancestors !== tree.length) {
          throw new Error('Unflushed truncations not migrate-able atm')
        }

        tree.length = e.treeUpgrade.length
        tree.fork = e.treeUpgrade.fork
        tree.rootHash = null
        tree.signature = e.treeUpgrade.signature
      }
    }

    if (userData.has('corestore/name') && userData.has('corestore/namespace')) {
      core.alias = {
        name: b4a.toString(userData.get('corestore/name')),
        namespace: userData.get('corestore/namespace')
      }
      userData.delete('corestore/name')
      userData.delete('corestore/namespace')
    }

    for (const [key, value] of userData) {
      ctx.putUserData(key, value)
    }

    ctx.setAuth(auth)

    const getTreeNode = (index) => (treeNodes.get(index) || getTreeNodeFromFile(files.tree, index))

    if (tree.length) {
      if (tree.rootHash === null) tree.rootHash = crypto.tree(await getRoots(tree.length, getTreeNode))
      ctx.setHead(tree)
    }

    tx.putCore(discoveryKey, core)
    if (core.alias) tx.putCoreByAlias(core.alias, discoveryKey)

    await ctx.flush()
  }

  head.version = version
  tx.setHead(head)
  tx.apply()

  if (dryRun) return

  await View.flush(view.changes, storage.db)

  if (gc) await rm(primaryKeyFile)
}

class BlockSlicer {
  constructor (filename) {
    this.stream = fs.createReadStream(filename)
    this.closed = new Promise(resolve => this.stream.once('close', resolve))
    this.offset = 0
    this.overflow = null
  }

  async take (offset, size) {
    let buffer = null
    if (offset < this.offset) throw new Error('overread')

    while (true) {
      let data = null

      if (this.overflow) {
        data = this.overflow
        this.overflow = null
      } else {
        data = this.stream.read()

        if (!data) {
          await new Promise(resolve => this.stream.once('readable', resolve))
          continue
        }
      }

      let chunk = null

      if (this.offset === offset || buffer) {
        chunk = data
      } else if (this.offset + data.byteLength > offset) {
        chunk = data.subarray(offset - this.offset)
      }

      this.offset += data.byteLength
      if (!chunk) continue

      if (buffer) buffer = b4a.concat([buffer, chunk])
      else buffer = chunk

      if (buffer.byteLength < size) continue

      const result = buffer.subarray(0, size)
      this.overflow = size === buffer.byteLength ? null : buffer.subarray(result.byteLength)
      this.offset -= (this.overflow ? this.overflow.byteLength : 0)
      return result
    }
  }

  close () {
    this.stream.on('error', noop)
    this.stream.destroy()
    return this.closed
  }
}

class TreeSlicer {
  constructor () {
    this.buffer = null
    this.offset = 0
  }

  get size () {
    return this.buffer === null ? 0 : this.buffer.byteLength
  }

  push (data) {
    if (this.buffer === null) this.buffer = data
    else this.buffer = b4a.concat([this.buffer, data])
    this.offset += data.byteLength
  }

  skip () {
    let skipped = 0

    if (TREE_01_SKIP === null) {
      TREE_16_SKIP = b4a.alloc(16 * 40 * 100)
      TREE_04_SKIP = TREE_16_SKIP.subarray(0, 4 * 40 * 100)
      TREE_01_SKIP = TREE_16_SKIP.subarray(0, 1 * 40 * 100)
    }

    while (true) {
      if (this.buffer.byteLength >= TREE_16_SKIP.byteLength) {
        if (b4a.equals(this.buffer.subarray(0, TREE_16_SKIP.byteLength), TREE_16_SKIP)) {
          this.buffer = this.buffer.subarray(TREE_16_SKIP.byteLength)
          skipped += 1600
          continue
        }
      }

      if (this.buffer.byteLength >= TREE_04_SKIP.byteLength) {
        if (b4a.equals(this.buffer.subarray(0, TREE_04_SKIP.byteLength), TREE_04_SKIP)) {
          this.buffer = this.buffer.subarray(TREE_04_SKIP.byteLength)
          skipped += 400
          continue
        }
      }

      if (this.buffer.byteLength >= TREE_01_SKIP.byteLength) {
        if (b4a.equals(this.buffer.subarray(0, TREE_01_SKIP.byteLength), TREE_01_SKIP)) {
          this.buffer = this.buffer.subarray(TREE_01_SKIP.byteLength)
          skipped += 100
          continue
        }
      }
      break
    }

    return skipped
  }

  take () {
    const len = 40

    if (len <= this.size) {
      const chunk = this.buffer.subarray(0, len)
      this.buffer = this.buffer.subarray(len)
      return chunk
    }

    return null
  }
}

async function core (core, { version, dryRun = true, gc = true }) {
  if (dryRun) return // dryRun mode not supported atm

  const rx = core.read()

  const promises = [rx.getAuth(), rx.getHead()]
  rx.tryFlush()

  const [auth, head] = await Promise.all(promises)

  if (!auth) return

  const dk = b4a.toString(auth.discoveryKey, 'hex')
  const files = getFiles(path.join(core.store.path, 'cores', dk.slice(0, 2), dk.slice(2, 4), dk))

  if (head === null || head.length === 0) {
    await commitCoreMigration(auth, core, version)
    if (gc) await runGC()
    return // no data
  }

  const oplog = await readOplog(files.oplog)
  if (!oplog) {
    const writable = !!auth.keyPair

    if (writable) {
      throw new Error('No oplog available writable core for ' + files.oplog + ', length = ' + (head ? head.length : 0))
    }

    // if not writable, just nuke it to recover, some bad state happened here, prop corruption from earlier versions
    const w = core.write()

    w.deleteBlockRange(0, -1)
    w.deleteTreeNodeRange(0, -1)
    w.deleteBitfieldPageRange(0, -1)
    w.deleteHead()

    await w.flush()

    await commitCoreMigration(auth, core, version)
    if (gc) await runGC()
    return // no data
  }

  const treeData = new TreeSlicer()

  let treeIndex = 0

  if (await exists(files.tree)) {
    for await (const data of fs.createReadStream(files.tree)) {
      treeData.push(data)

      let write = null

      while (true) {
        const skip = treeData.skip()
        treeIndex += skip

        const buf = treeData.take()
        if (buf === null) break

        const index = treeIndex++
        if (b4a.equals(buf, EMPTY_NODE)) continue

        if (write === null) write = core.write()
        write.putTreeNode(decodeTreeNode(index, buf))
      }

      if (write !== null) await write.flush()
    }
  }

  const buf = []
  if (await exists(files.bitfield)) {
    for await (const data of fs.createReadStream(files.bitfield)) {
      buf.push(data)
    }
  }

  let bitfield = b4a.concat(buf)
  if (bitfield.byteLength & 4095) bitfield = b4a.concat([bitfield, b4a.alloc(4096 - (bitfield.byteLength & 4095))])

  const pages = new Map()
  const headerBits = new Map()

  const roots = await getRootsFromStorage(core, head.length)

  for (const e of oplog.entries) {
    if (!e.bitfield) continue

    for (let i = 0; i < e.bitfield.length; i++) {
      headerBits.set(i + e.bitfield.start, !e.bitfield.drop)
    }
  }

  let batch = []

  const cache = new Map()
  const blocks = new BlockSlicer(files.data)

  for (const index of allBits(bitfield)) {
    if (headerBits.get(index) === false) continue
    if (index >= head.length) continue

    setBitInPage(index)

    batch.push(index)
    if (batch.length < 1024) continue

    await writeBlocksBatch()
    continue
  }

  if (batch.length) await writeBlocksBatch()

  await blocks.close()

  const w = core.write()

  for (const [index, bit] of headerBits) {
    if (!bit) continue
    if (index >= head.length) continue

    setBitInPage(index)

    const blk = await getBlockFromFile(files.data, core, index, roots, cache)
    w.putBlock(index, blk)
  }

  for (const [index, page] of pages) {
    w.putBitfieldPage(index, b4a.from(page.buffer, page.byteOffset, page.byteLength))
  }

  await w.flush()

  let contiguousLength = 0
  for await (const data of core.createBlockStream()) {
    if (data.index === contiguousLength) contiguousLength++
    else break
  }

  if (contiguousLength) {
    const w = core.write()
    w.setHints({ contiguousLength })
    await w.flush()
  }

  await commitCoreMigration(auth, core, version)

  if (gc) await runGC()

  async function runGC () {
    await rm(files.path)
    await rmdir(path.join(files.path, '..'))
    await rmdir(path.join(files.path, '../..'))
    await rmdir(path.join(core.store.path, 'cores'))
  }

  function setBitInPage (index) {
    const n = index & 32767
    const p = (index - n) / 32768

    let page = pages.get(p)

    if (!page) {
      page = new Uint32Array(1024)
      pages.set(p, page)
    }

    const o = n & 31
    const b = (n - o) / 32
    const v = 1 << o

    page[b] |= v
  }

  async function writeBlocksBatch () {
    const read = core.read()
    const promises = []
    for (const index of batch) promises.push(getByteRangeFromStorage(read, 2 * index, roots, cache))
    read.tryFlush()

    const r = await Promise.all(promises)
    const tx = core.write()

    for (let i = 0; i < r.length; i++) {
      const index = batch[i]
      const [offset, size] = r[i]

      const blk = await blocks.take(offset, size)
      tx.putBlock(index, blk)
    }

    batch = []
    if (cache.size > 16384) cache.clear()

    await tx.flush()
  }
}

async function commitCoreMigration (auth, core, version) {
  const view = new View()
  const rx = new CorestoreRX(core.db, view)

  const storeCorePromise = rx.getCore(auth.discoveryKey)
  rx.tryFlush()

  const storeCore = await storeCorePromise

  storeCore.version = version

  const tx = new CorestoreTX(view)

  tx.putCore(auth.discoveryKey, storeCore)
  tx.apply()

  await View.flush(view.changes, core.db)
}

async function getBlockFromFile (file, core, index, roots, cache) {
  const rx = core.read()
  const promise = getByteRangeFromStorage(rx, 2 * index, roots, cache)
  rx.tryFlush()
  const [offset, size] = await promise

  return new Promise(function (resolve) {
    readAll(file, size, offset, function (err, buf) {
      if (err) return resolve(null)
      resolve(buf)
    })
  })
}

function getFiles (dir) {
  return {
    path: dir,
    oplog: path.join(dir, 'oplog'),
    data: path.join(dir, 'data'),
    tree: path.join(dir, 'tree'),
    bitfield: path.join(dir, 'bitfield')
  }
}

async function getRootsFromStorage (core, length) {
  const all = []
  const rx = core.read()
  for (const index of flat.fullRoots(2 * length)) {
    all.push(rx.getTreeNode(index))
  }
  rx.tryFlush()
  return Promise.all(all)
}

async function getRoots (length, getTreeNode) {
  const all = []
  for (const index of flat.fullRoots(2 * length)) {
    all.push(await getTreeNode(index))
  }
  return all
}

function getCached (read, cache, index) {
  if (cache.has(index)) return cache.get(index)
  const p = read.getTreeNode(index)
  cache.set(index, p)
  return p
}

async function getByteRangeFromStorage (read, index, roots, cache) {
  const promises = [getCached(read, cache, index), getByteOffsetFromStorage(read, index, roots, cache)]
  const [node, offset] = await Promise.all(promises)
  if (!node) throw new Error('Node not found during migration: ' + index)
  return [offset, node.size]
}

async function getByteOffsetFromStorage (rx, index, roots, cache) {
  if (index === 0) return 0
  if ((index & 1) === 1) index = flat.leftSpan(index)

  let head = 0
  let offset = 0

  for (const node of roots) { // all async ticks happen once we find the root so safe
    head += 2 * ((node.index - head) + 1)

    if (index >= head) {
      offset += node.size
      continue
    }

    const ite = flat.iterator(node.index)
    const promises = []

    while (ite.index !== index) {
      if (index < ite.index) {
        ite.leftChild()
      } else {
        promises.push(getCached(rx, cache, ite.leftChild()))
        ite.sibling()
      }
    }

    const nodes = await Promise.all(promises)
    for (const node of nodes) offset += node.size

    return offset
  }

  throw new Error('Failed to find offset')
}

function decodeTreeNode (index, buf) {
  return { index, size: c.decode(c.uint64, buf), hash: buf.subarray(8) }
}

async function getTreeNodeFromFile (file, index) {
  return new Promise(function (resolve) {
    readAll(file, 40, index * 40, function (err, buf) {
      if (err) return resolve(null)
      resolve(decodeTreeNode(index, buf))
    })
  })
}

function readAll (filename, length, pos, cb) {
  const buf = b4a.alloc(length)

  fs.open(filename, 'r', function (err, fd) {
    if (err) return cb(err)

    let offset = 0

    fs.read(fd, buf, offset, buf.byteLength, pos, function loop (err, read) {
      if (err) return done(err)
      if (read === 0) return done(new Error('Partial read'))
      offset += read
      if (offset === buf.byteLength) return done(null, buf)
      fs.read(fd, offset, buf.byteLength - offset, buf, pos + offset, loop)
    })

    function done (err, value) {
      fs.close(fd, () => cb(err, value))
    }
  })
}

async function readdir (dir) {
  try {
    return await fs.promises.readdir(dir)
  } catch {
    return []
  }
}

async function exists (file) {
  try {
    await fs.promises.stat(file)
    return true
  } catch {
    return false
  }
}

async function readFile (file) {
  try {
    return await fs.promises.readFile(file)
  } catch {
    return null
  }
}

async function rm (dir) {
  try {
    await fs.promises.rm(dir, { recursive: true })
  } catch {}
}

async function rmdir (dir) {
  try {
    await fs.promises.rmdir(dir)
  } catch {}
}

function * allBits (buffer) {
  for (let i = 0; i < buffer.byteLength; i += EMPTY_PAGE.byteLength) {
    const page = buffer.subarray(i, i + EMPTY_NODE.byteLength)
    if (b4a.equals(page, EMPTY_PAGE)) continue

    const view = new Uint32Array(page.buffer, page.byteOffset, EMPTY_PAGE.byteLength / 4)

    for (let j = 0; j < view.length; j++) {
      const n = view[j]
      if (n === 0) continue

      for (let k = 0; k < 32; k++) {
        const m = 1 << k
        if (n & m) yield i * 8 + j * 32 + k
      }
    }
  }
}

function readOplog (oplog) {
  return new Promise(function (resolve) {
    fs.readFile(oplog, function (err, buffer) {
      if (err) return resolve(null)

      const state = { start: 0, end: buffer.byteLength, buffer }
      const headers = [1, 0]

      const h1 = decodeOplogHeader(state)
      state.start = 4096

      const h2 = decodeOplogHeader(state)
      state.start = 4096 * 2

      if (!h1 && !h2) return resolve(null)

      if (h1 && !h2) {
        headers[0] = h1.header
        headers[1] = h1.header
      } else if (!h1 && h2) {
        headers[0] = (h2.header + 1) & 1
        headers[1] = h2.header
      } else {
        headers[0] = h1.header
        headers[1] = h2.header
      }

      const header = (headers[0] + headers[1]) & 1
      const result = { path: path.dirname(oplog), header: null, entries: [] }
      const decoded = []

      result.header = header ? h2.message : h1.message

      if (result.header.external) {
        fs.readFile(path.join(oplog, '../header'), function (err, buffer) {
          if (err) return resolve(null)
          const start = result.header.external.start
          const end = start + result.header.external.length
          result.header = m.oplog.header.decode({ buffer, start, end })
          finish()
        })
        return
      }

      finish()

      function finish () {
        while (true) {
          const entry = decodeOplogEntry(state)
          if (!entry) break
          if (entry.header !== header) break

          decoded.push(entry)
        }

        while (decoded.length > 0 && decoded[decoded.length - 1].partial) decoded.pop()

        for (const e of decoded) {
          result.entries.push(e.message)
        }

        resolve(result)
      }
    })
  })
}

function noop () {}
// needed here for compat, copied from old hypercore, do not change this

const c = require('compact-encoding')
const b4a = require('b4a')

const EMPTY = b4a.alloc(0)
const DEFAULT_NAMESPACE = b4a.from('4144eea531e483d54e0c14f4ca68e0644f355343ff6fcb0f005200e12cd747cb', 'hex')

const hashes = {
  preencode (state, m) {
    state.end++ // small uint
  },
  encode (state, m) {
    if (m === 'blake2b') {
      c.uint.encode(state, 0)
      return
    }

    throw new Error('Unknown hash: ' + m)
  },
  decode (state) {
    const n = c.uint.decode(state)
    if (n === 0) return 'blake2b'
    throw new Error('Unknown hash id: ' + n)
  }
}

const signatures = {
  preencode (state, m) {
    state.end++ // small uint
  },
  encode (state, m) {
    if (m === 'ed25519') {
      c.uint.encode(state, 0)
      return
    }

    throw new Error('Unknown signature: ' + m)
  },
  decode (state) {
    const n = c.uint.decode(state)
    if (n === 0) return 'ed25519'
    throw new Error('Unknown signature id: ' + n)
  }
}

const signer = {
  preencode (state, m) {
    signatures.preencode(state, m.signature)
    c.fixed32.preencode(state, m.namespace)
    c.fixed32.preencode(state, m.publicKey)
  },
  encode (state, m) {
    signatures.encode(state, m.signature)
    c.fixed32.encode(state, m.namespace)
    c.fixed32.encode(state, m.publicKey)
  },
  decode (state) {
    return {
      signature: signatures.decode(state),
      namespace: c.fixed32.decode(state),
      publicKey: c.fixed32.decode(state)
    }
  }
}

const signerArray = c.array(signer)

const prologue = {
  preencode (state, p) {
    c.fixed32.preencode(state, p.hash)
    c.uint.preencode(state, p.length)
  },
  encode (state, p) {
    c.fixed32.encode(state, p.hash)
    c.uint.encode(state, p.length)
  },
  decode (state) {
    return {
      hash: c.fixed32.decode(state),
      length: c.uint.decode(state)
    }
  }
}

const manifestv0 = {
  preencode (state, m) {
    hashes.preencode(state, m.hash)
    state.end++ // type

    if (m.prologue && m.signers.length === 0) {
      c.fixed32.preencode(state, m.prologue.hash)
      return
    }

    if (m.quorum === 1 && m.signers.length === 1 && !m.allowPatch) {
      signer.preencode(state, m.signers[0])
    } else {
      state.end++ // flags
      c.uint.preencode(state, m.quorum)
      signerArray.preencode(state, m.signers)
    }
  },
  encode (state, m) {
    hashes.encode(state, m.hash)

    if (m.prologue && m.signers.length === 0) {
      c.uint.encode(state, 0)
      c.fixed32.encode(state, m.prologue.hash)
      return
    }

    if (m.quorum === 1 && m.signers.length === 1 && !m.allowPatch) {
      c.uint.encode(state, 1)
      signer.encode(state, m.signers[0])
    } else {
      c.uint.encode(state, 2)
      c.uint.encode(state, m.allowPatch ? 1 : 0)
      c.uint.encode(state, m.quorum)
      signerArray.encode(state, m.signers)
    }
  },
  decode (state) {
    const hash = hashes.decode(state)
    const type = c.uint.decode(state)

    if (type > 2) throw new Error('Unknown type: ' + type)

    if (type === 0) {
      return {
        version: 0,
        hash,
        allowPatch: false,
        quorum: 0,
        signers: [],
        prologue: {
          hash: c.fixed32.decode(state),
          length: 0
        }
      }
    }

    if (type === 1) {
      return {
        version: 0,
        hash,
        allowPatch: false,
        quorum: 1,
        signers: [signer.decode(state)],
        prologue: null
      }
    }

    const flags = c.uint.decode(state)

    return {
      version: 0,
      hash,
      allowPatch: (flags & 1) !== 0,
      quorum: c.uint.decode(state),
      signers: signerArray.decode(state),
      prologue: null
    }
  }
}

const manifest = exports.manifest = {
  preencode (state, m) {
    state.end++ // version
    if (m.version === 0) return manifestv0.preencode(state, m)

    state.end++ // flags
    hashes.preencode(state, m.hash)

    c.uint.preencode(state, m.quorum)
    signerArray.preencode(state, m.signers)
    if (m.prologue) prologue.preencode(state, m.prologue)
  },
  encode (state, m) {
    c.uint.encode(state, m.version)
    if (m.version === 0) return manifestv0.encode(state, m)

    c.uint.encode(state, (m.allowPatch ? 1 : 0) | (m.prologue ? 2 : 0) | (m.unencrypted ? 4 : 0))
    hashes.encode(state, m.hash)

    c.uint.encode(state, m.quorum)
    signerArray.encode(state, m.signers)
    if (m.prologue) prologue.encode(state, m.prologue)
  },
  decode (state) {
    const v = c.uint.decode(state)
    if (v === 0) return manifestv0.decode(state)
    if (v !== 1) throw new Error('Unknown version: ' + v)

    const flags = c.uint.decode(state)
    const hash = hashes.decode(state)
    const quorum = c.uint.decode(state)
    const signers = signerArray.decode(state)
    const unencrypted = (flags & 4) !== 0

    return {
      version: 1,
      hash,
      allowPatch: (flags & 1) !== 0,
      quorum,
      signers,
      prologue: (flags & 2) === 0 ? null : prologue.decode(state),
      unencrypted
    }
  }
}

const node = {
  preencode (state, n) {
    c.uint.preencode(state, n.index)
    c.uint.preencode(state, n.size)
    c.fixed32.preencode(state, n.hash)
  },
  encode (state, n) {
    c.uint.encode(state, n.index)
    c.uint.encode(state, n.size)
    c.fixed32.encode(state, n.hash)
  },
  decode (state) {
    return {
      index: c.uint.decode(state),
      size: c.uint.decode(state),
      hash: c.fixed32.decode(state)
    }
  }
}

const nodeArray = c.array(node)

const wire = exports.wire = {}

wire.handshake = {
  preencode (state, m) {
    c.uint.preencode(state, 1)
    c.fixed32.preencode(state, m.capability)
  },
  encode (state, m) {
    c.uint.encode(state, m.seeks ? 1 : 0)
    c.fixed32.encode(state, m.capability)
  },
  decode (state) {
    const flags = c.uint.decode(state)
    return {
      seeks: (flags & 1) !== 0,
      capability: c.fixed32.decode(state)
    }
  }
}

const requestBlock = {
  preencode (state, b) {
    c.uint.preencode(state, b.index)
    c.uint.preencode(state, b.nodes)
  },
  encode (state, b) {
    c.uint.encode(state, b.index)
    c.uint.encode(state, b.nodes)
  },
  decode (state) {
    return {
      index: c.uint.decode(state),
      nodes: c.uint.decode(state)
    }
  }
}

const requestSeek = {
  preencode (state, s) {
    c.uint.preencode(state, s.bytes)
    c.uint.preencode(state, s.padding)
  },
  encode (state, s) {
    c.uint.encode(state, s.bytes)
    c.uint.encode(state, s.padding)
  },
  decode (state) {
    return {
      bytes: c.uint.decode(state),
      padding: c.uint.decode(state)
    }
  }
}

const requestUpgrade = {
  preencode (state, u) {
    c.uint.preencode(state, u.start)
    c.uint.preencode(state, u.length)
  },
  encode (state, u) {
    c.uint.encode(state, u.start)
    c.uint.encode(state, u.length)
  },
  decode (state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

wire.request = {
  preencode (state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.id)
    c.uint.preencode(state, m.fork)

    if (m.block) requestBlock.preencode(state, m.block)
    if (m.hash) requestBlock.preencode(state, m.hash)
    if (m.seek) requestSeek.preencode(state, m.seek)
    if (m.upgrade) requestUpgrade.preencode(state, m.upgrade)
    if (m.priority) c.uint.preencode(state, m.priority)
  },
  encode (state, m) {
    const flags = (m.block ? 1 : 0) | (m.hash ? 2 : 0) | (m.seek ? 4 : 0) | (m.upgrade ? 8 : 0) | (m.manifest ? 16 : 0) | (m.priority ? 32 : 0)

    c.uint.encode(state, flags)
    c.uint.encode(state, m.id)
    c.uint.encode(state, m.fork)

    if (m.block) requestBlock.encode(state, m.block)
    if (m.hash) requestBlock.encode(state, m.hash)
    if (m.seek) requestSeek.encode(state, m.seek)
    if (m.upgrade) requestUpgrade.encode(state, m.upgrade)
    if (m.priority) c.uint.encode(state, m.priority)
  },
  decode (state) {
    const flags = c.uint.decode(state)

    return {
      id: c.uint.decode(state),
      fork: c.uint.decode(state),
      block: flags & 1 ? requestBlock.decode(state) : null,
      hash: flags & 2 ? requestBlock.decode(state) : null,
      seek: flags & 4 ? requestSeek.decode(state) : null,
      upgrade: flags & 8 ? requestUpgrade.decode(state) : null,
      manifest: (flags & 16) !== 0,
      priority: flags & 32 ? c.uint.decode(state) : 0
    }
  }
}

wire.cancel = {
  preencode (state, m) {
    c.uint.preencode(state, m.request)
  },
  encode (state, m) {
    c.uint.encode(state, m.request)
  },
  decode (state, m) {
    return {
      request: c.uint.decode(state)
    }
  }
}

const dataUpgrade = {
  preencode (state, u) {
    c.uint.preencode(state, u.start)
    c.uint.preencode(state, u.length)
    nodeArray.preencode(state, u.nodes)
    nodeArray.preencode(state, u.additionalNodes)
    c.optionalBuffer.preencode(state, u.signature)
  },
  encode (state, u) {
    c.uint.encode(state, u.start)
    c.uint.encode(state, u.length)
    nodeArray.encode(state, u.nodes)
    nodeArray.encode(state, u.additionalNodes)
    c.optionalBuffer.encode(state, u.signature)
  },
  decode (state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state),
      nodes: nodeArray.decode(state),
      additionalNodes: nodeArray.decode(state),
      signature: c.optionalBuffer.decode(state)
    }
  }
}

const dataSeek = {
  preencode (state, s) {
    c.uint.preencode(state, s.bytes)
    nodeArray.preencode(state, s.nodes)
  },
  encode (state, s) {
    c.uint.encode(state, s.bytes)
    nodeArray.encode(state, s.nodes)
  },
  decode (state) {
    return {
      bytes: c.uint.decode(state),
      nodes: nodeArray.decode(state)
    }
  }
}

const dataBlock = {
  preencode (state, b) {
    c.uint.preencode(state, b.index)
    c.optionalBuffer.preencode(state, b.value)
    nodeArray.preencode(state, b.nodes)
  },
  encode (state, b) {
    c.uint.encode(state, b.index)
    c.optionalBuffer.encode(state, b.value)
    nodeArray.encode(state, b.nodes)
  },
  decode (state) {
    return {
      index: c.uint.decode(state),
      value: c.optionalBuffer.decode(state) || EMPTY,
      nodes: nodeArray.decode(state)
    }
  }
}

const dataHash = {
  preencode (state, b) {
    c.uint.preencode(state, b.index)
    nodeArray.preencode(state, b.nodes)
  },
  encode (state, b) {
    c.uint.encode(state, b.index)
    nodeArray.encode(state, b.nodes)
  },
  decode (state) {
    return {
      index: c.uint.decode(state),
      nodes: nodeArray.decode(state)
    }
  }
}

wire.data = {
  preencode (state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.request)
    c.uint.preencode(state, m.fork)

    if (m.block) dataBlock.preencode(state, m.block)
    if (m.hash) dataHash.preencode(state, m.hash)
    if (m.seek) dataSeek.preencode(state, m.seek)
    if (m.upgrade) dataUpgrade.preencode(state, m.upgrade)
    if (m.manifest) manifest.preencode(state, m.manifest)
  },
  encode (state, m) {
    const flags = (m.block ? 1 : 0) | (m.hash ? 2 : 0) | (m.seek ? 4 : 0) | (m.upgrade ? 8 : 0) | (m.manifest ? 16 : 0)

    c.uint.encode(state, flags)
    c.uint.encode(state, m.request)
    c.uint.encode(state, m.fork)

    if (m.block) dataBlock.encode(state, m.block)
    if (m.hash) dataHash.encode(state, m.hash)
    if (m.seek) dataSeek.encode(state, m.seek)
    if (m.upgrade) dataUpgrade.encode(state, m.upgrade)
    if (m.manifest) manifest.encode(state, m.manifest)
  },
  decode (state) {
    const flags = c.uint.decode(state)

    return {
      request: c.uint.decode(state),
      fork: c.uint.decode(state),
      block: flags & 1 ? dataBlock.decode(state) : null,
      hash: flags & 2 ? dataHash.decode(state) : null,
      seek: flags & 4 ? dataSeek.decode(state) : null,
      upgrade: flags & 8 ? dataUpgrade.decode(state) : null,
      manifest: flags & 16 ? manifest.decode(state) : null
    }
  }
}

wire.noData = {
  preencode (state, m) {
    c.uint.preencode(state, m.request)
  },
  encode (state, m) {
    c.uint.encode(state, m.request)
  },
  decode (state, m) {
    return {
      request: c.uint.decode(state)
    }
  }
}

wire.want = {
  preencode (state, m) {
    c.uint.preencode(state, m.start)
    c.uint.preencode(state, m.length)
  },
  encode (state, m) {
    c.uint.encode(state, m.start)
    c.uint.encode(state, m.length)
  },
  decode (state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

wire.unwant = {
  preencode (state, m) {
    c.uint.preencode(state, m.start)
    c.uint.preencode(state, m.length)
  },
  encode (state, m) {
    c.uint.encode(state, m.start)
    c.uint.encode(state, m.length)
  },
  decode (state, m) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

wire.range = {
  preencode (state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.start)
    if (m.length !== 1) c.uint.preencode(state, m.length)
  },
  encode (state, m) {
    c.uint.encode(state, (m.drop ? 1 : 0) | (m.length === 1 ? 2 : 0))
    c.uint.encode(state, m.start)
    if (m.length !== 1) c.uint.encode(state, m.length)
  },
  decode (state) {
    const flags = c.uint.decode(state)

    return {
      drop: (flags & 1) !== 0,
      start: c.uint.decode(state),
      length: (flags & 2) !== 0 ? 1 : c.uint.decode(state)
    }
  }
}

wire.bitfield = {
  preencode (state, m) {
    c.uint.preencode(state, m.start)
    c.uint32array.preencode(state, m.bitfield)
  },
  encode (state, m) {
    c.uint.encode(state, m.start)
    c.uint32array.encode(state, m.bitfield)
  },
  decode (state, m) {
    return {
      start: c.uint.decode(state),
      bitfield: c.uint32array.decode(state)
    }
  }
}

wire.sync = {
  preencode (state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.fork)
    c.uint.preencode(state, m.length)
    c.uint.preencode(state, m.remoteLength)
  },
  encode (state, m) {
    c.uint.encode(state, (m.canUpgrade ? 1 : 0) | (m.uploading ? 2 : 0) | (m.downloading ? 4 : 0) | (m.hasManifest ? 8 : 0))
    c.uint.encode(state, m.fork)
    c.uint.encode(state, m.length)
    c.uint.encode(state, m.remoteLength)
  },
  decode (state) {
    const flags = c.uint.decode(state)

    return {
      fork: c.uint.decode(state),
      length: c.uint.decode(state),
      remoteLength: c.uint.decode(state),
      canUpgrade: (flags & 1) !== 0,
      uploading: (flags & 2) !== 0,
      downloading: (flags & 4) !== 0,
      hasManifest: (flags & 8) !== 0
    }
  }
}

wire.reorgHint = {
  preencode (state, m) {
    c.uint.preencode(state, m.from)
    c.uint.preencode(state, m.to)
    c.uint.preencode(state, m.ancestors)
  },
  encode (state, m) {
    c.uint.encode(state, m.from)
    c.uint.encode(state, m.to)
    c.uint.encode(state, m.ancestors)
  },
  decode (state) {
    return {
      from: c.uint.encode(state),
      to: c.uint.encode(state),
      ancestors: c.uint.encode(state)
    }
  }
}

wire.extension = {
  preencode (state, m) {
    c.string.preencode(state, m.name)
    c.raw.preencode(state, m.message)
  },
  encode (state, m) {
    c.string.encode(state, m.name)
    c.raw.encode(state, m.message)
  },
  decode (state) {
    return {
      name: c.string.decode(state),
      message: c.raw.decode(state)
    }
  }
}

const keyValue = {
  preencode (state, p) {
    c.string.preencode(state, p.key)
    c.optionalBuffer.preencode(state, p.value)
  },
  encode (state, p) {
    c.string.encode(state, p.key)
    c.optionalBuffer.encode(state, p.value)
  },
  decode (state) {
    return {
      key: c.string.decode(state),
      value: c.optionalBuffer.decode(state)
    }
  }
}

const treeUpgrade = {
  preencode (state, u) {
    c.uint.preencode(state, u.fork)
    c.uint.preencode(state, u.ancestors)
    c.uint.preencode(state, u.length)
    c.optionalBuffer.preencode(state, u.signature)
  },
  encode (state, u) {
    c.uint.encode(state, u.fork)
    c.uint.encode(state, u.ancestors)
    c.uint.encode(state, u.length)
    c.optionalBuffer.encode(state, u.signature)
  },
  decode (state) {
    return {
      fork: c.uint.decode(state),
      ancestors: c.uint.decode(state),
      length: c.uint.decode(state),
      signature: c.optionalBuffer.decode(state)
    }
  }
}

const bitfieldUpdate = { // TODO: can maybe be folded into a HAVE later on with the most recent spec
  preencode (state, b) {
    state.end++ // flags
    c.uint.preencode(state, b.start)
    c.uint.preencode(state, b.length)
  },
  encode (state, b) {
    state.buffer[state.start++] = b.drop ? 1 : 0
    c.uint.encode(state, b.start)
    c.uint.encode(state, b.length)
  },
  decode (state) {
    const flags = c.uint.decode(state)
    return {
      drop: (flags & 1) !== 0,
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

const oplog = exports.oplog = {}

oplog.entry = {
  preencode (state, m) {
    state.end++ // flags
    if (m.userData) keyValue.preencode(state, m.userData)
    if (m.treeNodes) nodeArray.preencode(state, m.treeNodes)
    if (m.treeUpgrade) treeUpgrade.preencode(state, m.treeUpgrade)
    if (m.bitfield) bitfieldUpdate.preencode(state, m.bitfield)
  },
  encode (state, m) {
    const s = state.start++
    let flags = 0

    if (m.userData) {
      flags |= 1
      keyValue.encode(state, m.userData)
    }
    if (m.treeNodes) {
      flags |= 2
      nodeArray.encode(state, m.treeNodes)
    }
    if (m.treeUpgrade) {
      flags |= 4
      treeUpgrade.encode(state, m.treeUpgrade)
    }
    if (m.bitfield) {
      flags |= 8
      bitfieldUpdate.encode(state, m.bitfield)
    }

    state.buffer[s] = flags
  },
  decode (state) {
    const flags = c.uint.decode(state)
    return {
      userData: (flags & 1) !== 0 ? keyValue.decode(state) : null,
      treeNodes: (flags & 2) !== 0 ? nodeArray.decode(state) : null,
      treeUpgrade: (flags & 4) !== 0 ? treeUpgrade.decode(state) : null,
      bitfield: (flags & 8) !== 0 ? bitfieldUpdate.decode(state) : null
    }
  }
}

const keyPair = {
  preencode (state, kp) {
    c.optionalBuffer.preencode(state, kp.publicKey)
    c.optionalBuffer.preencode(state, kp.secretKey)
  },
  encode (state, kp) {
    c.optionalBuffer.encode(state, kp.publicKey)
    c.optionalBuffer.encode(state, kp.secretKey)
  },
  decode (state) {
    return {
      publicKey: c.optionalBuffer.decode(state),
      secretKey: c.optionalBuffer.decode(state)
    }
  }
}

const reorgHint = {
  preencode (state, r) {
    c.uint.preencode(state, r.from)
    c.uint.preencode(state, r.to)
    c.uint.preencode(state, r.ancestors)
  },
  encode (state, r) {
    c.uint.encode(state, r.from)
    c.uint.encode(state, r.to)
    c.uint.encode(state, r.ancestors)
  },
  decode (state) {
    return {
      from: c.uint.decode(state),
      to: c.uint.decode(state),
      ancestors: c.uint.decode(state)
    }
  }
}

const reorgHintArray = c.array(reorgHint)

const hints = {
  preencode (state, h) {
    reorgHintArray.preencode(state, h.reorgs)
    c.uint.preencode(state, h.contiguousLength)
  },
  encode (state, h) {
    reorgHintArray.encode(state, h.reorgs)
    c.uint.encode(state, h.contiguousLength)
  },
  decode (state) {
    return {
      reorgs: reorgHintArray.decode(state),
      contiguousLength: state.start < state.end ? c.uint.decode(state) : 0
    }
  }
}

const treeHeader = {
  preencode (state, t) {
    c.uint.preencode(state, t.fork)
    c.uint.preencode(state, t.length)
    c.optionalBuffer.preencode(state, t.rootHash)
    c.optionalBuffer.preencode(state, t.signature)
  },
  encode (state, t) {
    c.uint.encode(state, t.fork)
    c.uint.encode(state, t.length)
    c.optionalBuffer.encode(state, t.rootHash)
    c.optionalBuffer.encode(state, t.signature)
  },
  decode (state) {
    return {
      fork: c.uint.decode(state),
      length: c.uint.decode(state),
      rootHash: c.optionalBuffer.decode(state),
      signature: c.optionalBuffer.decode(state)
    }
  }
}

const types = {
  preencode (state, t) {
    c.string.preencode(state, t.tree)
    c.string.preencode(state, t.bitfield)
    c.string.preencode(state, t.signer)
  },
  encode (state, t) {
    c.string.encode(state, t.tree)
    c.string.encode(state, t.bitfield)
    c.string.encode(state, t.signer)
  },
  decode (state) {
    return {
      tree: c.string.decode(state),
      bitfield: c.string.decode(state),
      signer: c.string.decode(state)
    }
  }
}

const externalHeader = {
  preencode (state, m) {
    c.uint.preencode(state, m.start)
    c.uint.preencode(state, m.length)
  },
  encode (state, m) {
    c.uint.encode(state, m.start)
    c.uint.encode(state, m.length)
  },
  decode (state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

const keyValueArray = c.array(keyValue)

oplog.header = {
  preencode (state, h) {
    state.end += 2 // version + flags
    if (h.external) {
      externalHeader.preencode(state, h.external)
      return
    }
    c.fixed32.preencode(state, h.key)
    if (h.manifest) manifest.preencode(state, h.manifest)
    if (h.keyPair) keyPair.preencode(state, h.keyPair)
    keyValueArray.preencode(state, h.userData)
    treeHeader.preencode(state, h.tree)
    hints.preencode(state, h.hints)
  },
  encode (state, h) {
    c.uint.encode(state, 1)
    if (h.external) {
      c.uint.encode(state, 1) // ONLY set the first big for clarity
      externalHeader.encode(state, h.external)
      return
    }
    c.uint.encode(state, (h.manifest ? 2 : 0) | (h.keyPair ? 4 : 0))
    c.fixed32.encode(state, h.key)
    if (h.manifest) manifest.encode(state, h.manifest)
    if (h.keyPair) keyPair.encode(state, h.keyPair)
    keyValueArray.encode(state, h.userData)
    treeHeader.encode(state, h.tree)
    hints.encode(state, h.hints)
  },
  decode (state) {
    const version = c.uint.decode(state)

    if (version > 1) {
      throw new Error('Invalid header version. Expected <= 1, got ' + version)
    }

    if (version === 0) {
      const old = {
        types: types.decode(state),
        userData: keyValueArray.decode(state),
        tree: treeHeader.decode(state),
        signer: keyPair.decode(state),
        hints: hints.decode(state)
      }

      return {
        external: null,
        key: old.signer.publicKey,
        manifest: {
          version: 0,
          hash: old.types.tree,
          allowPatch: false,
          quorum: 1,
          signers: [{
            signature: old.types.signer,
            namespace: DEFAULT_NAMESPACE,
            publicKey: old.signer.publicKey
          }],
          prologue: null
        },
        keyPair: old.signer.secretKey ? old.signer : null,
        userData: old.userData,
        tree: old.tree,
        hints: old.hints
      }
    }

    const flags = c.uint.decode(state)

    if (flags & 1) {
      return {
        external: externalHeader.decode(state),
        key: null,
        manifest: null,
        keyPair: null,
        userData: null,
        tree: null,
        hints: null
      }
    }

    return {
      external: null,
      key: c.fixed32.decode(state),
      manifest: (flags & 2) !== 0 ? manifest.decode(state) : null,
      keyPair: (flags & 4) !== 0 ? keyPair.decode(state) : null,
      userData: keyValueArray.decode(state),
      tree: treeHeader.decode(state),
      hints: hints.decode(state)
    }
  }
}

const uintArray = c.array(c.uint)

const multisigInput = {
  preencode (state, inp) {
    c.uint.preencode(state, inp.signer)
    c.fixed64.preencode(state, inp.signature)
    c.uint.preencode(state, inp.patch)
  },
  encode (state, inp) {
    c.uint.encode(state, inp.signer)
    c.fixed64.encode(state, inp.signature)
    c.uint.encode(state, inp.patch)
  },
  decode (state) {
    return {
      signer: c.uint.decode(state),
      signature: c.fixed64.decode(state),
      patch: c.uint.decode(state)
    }
  }
}

const patchEncodingv0 = {
  preencode (state, n) {
    c.uint.preencode(state, n.start)
    c.uint.preencode(state, n.length)
    uintArray.preencode(state, n.nodes)
  },
  encode (state, n) {
    c.uint.encode(state, n.start)
    c.uint.encode(state, n.length)
    uintArray.encode(state, n.nodes)
  },
  decode (state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state),
      nodes: uintArray.decode(state)
    }
  }
}

const multisigInputv0 = {
  preencode (state, n) {
    state.end++
    c.uint.preencode(state, n.signer)
    c.fixed64.preencode(state, n.signature)
    if (n.patch) patchEncodingv0.preencode(state, n.patch)
  },
  encode (state, n) {
    c.uint.encode(state, n.patch ? 1 : 0)
    c.uint.encode(state, n.signer)
    c.fixed64.encode(state, n.signature)
    if (n.patch) patchEncodingv0.encode(state, n.patch)
  },
  decode (state) {
    const flags = c.uint.decode(state)
    return {
      signer: c.uint.decode(state),
      signature: c.fixed64.decode(state),
      patch: (flags & 1) ? patchEncodingv0.decode(state) : null
    }
  }
}

const multisigInputArrayv0 = c.array(multisigInputv0)
const multisigInputArray = c.array(multisigInput)

const compactNode = {
  preencode (state, n) {
    c.uint.preencode(state, n.index)
    c.uint.preencode(state, n.size)
    c.fixed32.preencode(state, n.hash)
  },
  encode (state, n) {
    c.uint.encode(state, n.index)
    c.uint.encode(state, n.size)
    c.fixed32.encode(state, n.hash)
  },
  decode (state) {
    return {
      index: c.uint.decode(state),
      size: c.uint.decode(state),
      hash: c.fixed32.decode(state)
    }
  }
}

const compactNodeArray = c.array(compactNode)

exports.multiSignaturev0 = {
  preencode (state, s) {
    multisigInputArrayv0.preencode(state, s.proofs)
    compactNodeArray.preencode(state, s.patch)
  },
  encode (state, s) {
    multisigInputArrayv0.encode(state, s.proofs)
    compactNodeArray.encode(state, s.patch)
  },
  decode (state) {
    return {
      proofs: multisigInputArrayv0.decode(state),
      patch: compactNodeArray.decode(state)
    }
  }
}

exports.multiSignature = {
  preencode (state, s) {
    multisigInputArray.preencode(state, s.proofs)
    compactNodeArray.preencode(state, s.patch)
  },
  encode (state, s) {
    multisigInputArray.encode(state, s.proofs)
    compactNodeArray.encode(state, s.patch)
  },
  decode (state) {
    return {
      proofs: multisigInputArray.decode(state),
      patch: compactNodeArray.decode(state)
    }
  }
}
const c = require('compact-encoding')
const schema = require('../../encoding/spec/hyperschema')
const { core: coreKey } = require('../../lib/keys.js')
const View = require('../../lib/view.js')

const CORE_AUTH = schema.getEncoding('@core/auth')

const { CorestoreRX, CorestoreTX } = require('../../lib/tx.js')

async function core (core, { version, dryRun = false } = {}) {
  if (dryRun) return // dryRun mode not supported atm

  const rx = core.db.read({ autoDestroy: true })
  const storedAuthPromise = rx.get(coreKey.auth(core.core.corePointer))

  rx.tryFlush()

  const storedAuth = await storedAuthPromise
  if (!storedAuth) return

  const auth = c.decode(CORE_AUTH, storedAuth)
  await commitCoreMigration(auth, core, version)
}

module.exports = { core }

async function commitCoreMigration (auth, core, version) {
  const view = new View()
  const rx = new CorestoreRX(core.db, view)

  const storeCorePromise = rx.getCore(auth.discoveryKey)
  rx.tryFlush()

  const storeCore = await storeCorePromise

  storeCore.version = version

  const tx = new CorestoreTX(view)
  tx.putCore(auth.discoveryKey, storeCore)
  tx.apply()

  await View.flush(view.changes, core.db)
}
{
  "name": "hypercore-storage",
  "version": "3.2.0",
  "main": "index.js",
  "files": [
    "index.js",
    "lib/*.js",
    "encoding/*",
    "migrations/0/*.js",
    "migrations/1/*.js"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:bare": "brittle-bare test/all.js",
    "test:generate": "brittle -r test/all.js test/*.js",
    "test:node": "brittle-node test/all.js"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "description": "Storage engine for Hypercore",
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "fs/*": {
      "bare": "bare-fs/*",
      "default": "fs/*"
    },
    "os": {
      "bare": "bare-os",
      "default": "os"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    }
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/hypercore-storage.git"
  },
  "bugs": {
    "url": "https://github.com/holepunchto/hypercore-storage/issues"
  },
  "homepage": "https://github.com/holepunchto/hypercore-storage#readme",
  "dependencies": {
    "b4a": "^1.6.7",
    "bare-path": "^3.0.0",
    "compact-encoding": "^3.1.0",
    "device-file": "^2.1.2",
    "flat-tree": "^1.12.1",
    "hypercore-crypto": "^3.4.2",
    "hyperschema": "^1.21.0",
    "index-encoder": "^3.3.2",
    "resolve-reject-promise": "^1.0.0",
    "rocksdb-native": "^3.11.0",
    "scope-lock": "^1.2.4",
    "streamx": "^2.21.1",
    "xache": "^1.2.1"
  },
  "devDependencies": {
    "bare-os": "^3.9.1",
    "brittle": "^3.7.0",
    "hypercore-storage-2.9.0": "npm:hypercore-storage@^2.9.0",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "test-tmp": "^1.3.1"
  }
}
const { EventEmitter } = require('events')
const isOptions = require('is-options')
const crypto = require('hypercore-crypto')
const CoreStorage = require('hypercore-storage')
const c = require('compact-encoding')
const b4a = require('b4a')
const NoiseSecretStream = require('@hyperswarm/secret-stream')
const Protomux = require('protomux')
const id = require('hypercore-id-encoding')
const safetyCatch = require('safety-catch')
const unslab = require('unslab')
const flat = require('flat-tree')
const assert = require('nanoassert')

const { SMALL_WANTS } = require('./lib/feature-flags')
const { UPDATE_COMPAT } = require('./lib/wants')
const MarkBitfield = require('./lib/mark-bitfield')

const inspect = require('./lib/inspect')
const Core = require('./lib/core')
const Info = require('./lib/info')
const Download = require('./lib/download')
const DefaultEncryption = require('./lib/default-encryption')
const caps = require('./lib/caps')
const Replicator = require('./lib/replicator')
const { manifestHash, createManifest } = require('./lib/verifier')
const { ReadStream, WriteStream, ByteStream } = require('./lib/streams')
const { MerkleTree } = require('./lib/merkle-tree')
const { proof, verify } = require('./lib/fully-remote-proof')
const {
  ASSERTION,
  BAD_ARGUMENT,
  SESSION_CLOSED,
  SESSION_MOVED,
  SESSION_NOT_WRITABLE,
  SNAPSHOT_NOT_AVAILABLE,
  DECODING_ERROR,
  REQUEST_CANCELLED
} = require('hypercore-errors')

// Hypercore actually does not have any notion of max/min block sizes
// but we enforce 15mb to ensure smooth replication (each block is transmitted atomically)
const MAX_SUGGESTED_BLOCK_SIZE = 15 * 1024 * 1024

class Hypercore extends EventEmitter {
  constructor(storage, key, opts) {
    super()

    if (isOptions(storage) && !storage.db) {
      opts = storage
      storage = null
      key = opts.key || null
    } else if (isOptions(key)) {
      opts = key
      key = opts.key || null
    }

    if (key && typeof key === 'string') key = id.decode(key)
    if (!opts) opts = {}

    if (!storage) storage = opts.storage

    this.core = null
    this.state = null
    this.encryption = null
    this.extensions = new Map()

    this.valueEncoding = null
    this.encodeBatch = null
    this.activeRequests = []
    this.sessions = null
    this.ongc = null

    this.keyPair = opts.keyPair || null
    this.readable = true
    this.writable = false
    this.exclusive = false
    this.opened = false
    this.closed = false
    this.weak = !!opts.weak
    this.snapshotted = !!opts.snapshot
    this.onseq = opts.onseq || null
    this.onwait = opts.onwait || null
    this.wait = opts.wait !== false
    this.timeout = opts.timeout || 0
    this.preload = null
    this.closing = null
    this.opening = null

    this._readonly = opts.writable === false
    this._preappend = preappend.bind(this)
    this._snapshot = null
    this._findingPeers = 0
    this._active = opts.weak ? !!opts.active : opts.active !== false

    this.waits = 0

    // Mark & Sweep GC
    this._marking = false
    this._marks = null

    this._sessionIndex = -1
    this._stateIndex = -1 // maintained by session state
    this._monitorIndex = -1 // maintained by replication state

    this.opening = this._open(storage, key, opts)
    this.opening.catch(safetyCatch)

    this.on('newListener', maybeAddMonitor)
  }

  [Symbol.for('nodejs.util.inspect.custom')](depth, opts) {
    return inspect(this, depth, opts)
  }

  static MAX_SUGGESTED_BLOCK_SIZE = MAX_SUGGESTED_BLOCK_SIZE

  static DefaultEncryption = DefaultEncryption

  static SMALL_WANTS = SMALL_WANTS

  static enable(flag) {
    const enableCompat = (flag & SMALL_WANTS) === 0
    UPDATE_COMPAT(enableCompat)
  }

  static setRecoveryPeers(peers) {
    Core.setRecoveryPeers(peers)
  }

  static key(manifest, { compat, version, namespace } = {}) {
    if (b4a.isBuffer(manifest)) {
      manifest = { version, signers: [{ publicKey: manifest, namespace }] }
    }
    return compat ? manifest.signers[0].publicKey : manifestHash(createManifest(manifest))
  }

  static discoveryKey(key) {
    return crypto.discoveryKey(key)
  }

  static blockEncryptionKey(key, encryptionKey) {
    return DefaultEncryption.blockEncryptionKey(key, encryptionKey)
  }

  static getProtocolMuxer(stream) {
    return stream.noiseStream.userData
  }

  static createCore(storage, opts) {
    return new Core(Hypercore.defaultStorage(storage), { autoClose: false, ...opts })
  }

  static createProtocolStream(isInitiator, opts = {}) {
    let outerStream = Protomux.isProtomux(isInitiator)
      ? isInitiator.stream
      : isStream(isInitiator)
        ? isInitiator
        : opts.stream

    let noiseStream = null

    if (outerStream) {
      noiseStream = outerStream.noiseStream
    } else {
      noiseStream = new NoiseSecretStream(isInitiator, null, opts)
      outerStream = noiseStream.rawStream
    }
    if (!noiseStream) throw BAD_ARGUMENT('Invalid stream', this.discoveryKey)

    if (!noiseStream.userData) {
      const protocol = Protomux.from(noiseStream)

      if (opts.keepAlive !== false && noiseStream.keepAlive === 0) {
        noiseStream.setKeepAlive(5000)
      }
      noiseStream.userData = protocol
    }

    if (opts.ondiscoverykey) {
      const ondiscoverykey = createDiscoveryKeyHandler(opts.ondiscoverykey)
      noiseStream.userData.pair({ protocol: 'hypercore/alpha' }, ondiscoverykey)
    }

    return outerStream
  }

  static defaultStorage(storage, opts = {}) {
    if (CoreStorage.isCoreStorage(storage)) return storage

    const directory = storage
    return new CoreStorage(directory, opts)
  }

  static clearRequests(session, err) {
    Replicator.clearRequests(session, err)
  }

  static destroyRequests(session, err) {
    if (isRequestsDestroyed(session)) return
    Replicator.clearRequests(session, err)
    session.push(null) // mark as dead
  }

  static async treeHashFromStorage(session, length = session.length) {
    const roots = await MerkleTree.getRoots(session.state, length)
    return crypto.tree(roots)
  }

  snapshot(opts) {
    return this.session({ ...opts, snapshot: true })
  }

  compact() {
    return this.core.compact()
  }

  session(opts = {}) {
    if (this.closing) {
      // This makes the closing logic a lot easier. If this turns out to be a problem
      // in practice, open an issue and we'll try to make a solution for it.
      throw SESSION_CLOSED('Cannot make sessions on a closing core', this.discoveryKey)
    }
    if (opts.checkout !== undefined && !opts.name && !opts.atom) {
      throw ASSERTION('Checkouts are only supported on atoms or named sessions', this.discoveryKey)
    }

    const wait = opts.wait === false ? false : this.wait
    const writable = opts.writable === undefined ? !this._readonly : opts.writable === true
    const onwait = opts.onwait === undefined ? this.onwait : opts.onwait
    const onseq = opts.onseq === undefined ? this.onseq : opts.onseq
    const timeout = opts.timeout === undefined ? this.timeout : opts.timeout
    const weak = opts.weak === undefined ? this.weak : opts.weak
    const marking = this._marking
    const marks = this._marks
    const Clz = opts.class || Hypercore
    const s = new Clz(null, this.key, {
      ...opts,
      wait,
      onwait,
      onseq,
      timeout,
      writable,
      weak,
      parent: this
    })
    s._marking = marking
    s._marks = marks

    return s
  }

  async setEncryptionKey(key, opts) {
    if (!this.opened) await this.opening
    const encryption = this._getEncryptionProvider({ key, block: !!(opts && opts.block) })
    return this.setEncryption(encryption)
  }

  async setEncryption(encryption) {
    if (!this.opened) await this.opening

    if (encryption === null) {
      this.encryption = encryption
      return
    }

    if (!isEncryptionProvider(encryption)) {
      throw ASSERTION('Provider does not satisfy HypercoreEncryption interface', this.discoveryKey)
    }

    this.encryption = encryption
  }

  async setGroup(topic) {
    if (!this.opened) await this.opening
    return this.core.setGroup(topic)
  }

  setKeyPair(keyPair) {
    this.keyPair = keyPair
  }

  setActive(bool) {
    const active = !!bool
    if (active === this._active || this.closing) return
    this._active = active
    if (!this.opened) return
    this.core.replicator.updateActivity(this._active ? 1 : -1)
  }

  async _open(storage, key, opts) {
    const preload = opts.preload || (opts.parent && opts.parent.preload)

    if (preload) {
      this.sessions = [] // in case someone looks at it like with peers
      this.preload = preload
      opts = { ...opts, ...(await this.preload) }
      this.preload = null
    }

    const parent = opts.parent || null
    const core = opts.core || (parent && parent.core)
    const sessions = opts.sessions || (parent && parent.sessions)
    const ongc = opts.ongc || (parent && parent.ongc)

    if (core) this.core = core
    if (ongc) this.ongc = ongc
    if (sessions) this.sessions = sessions

    if (this.sessions === null) this.sessions = []
    this._sessionIndex = this.sessions.push(this) - 1

    if (this.core === null) initOnce(this, storage, key, opts)
    if (this._monitorIndex === -2) this.core.addMonitor(this)

    try {
      await this._openSession(opts)
    } catch (err) {
      if (this.core.autoClose && this.core.hasSession() === false) await this.core.close()

      if (this.exclusive) this.core.unlockExclusive()

      this.core.removeMonitor(this)
      this._removeSession()

      if (this.state !== null) this.state.removeSession(this)

      this.closed = true
      this.emit('close')
      throw err
    }

    // Setup automatic recovery if in repair mode
    if (this.core._repairMode) {
      const recoverTreeNodeFromPeersBound = this.recoverTreeNodeFromPeers.bind(this)
      this.once('repaired', () => {
        this.off('peer-add', recoverTreeNodeFromPeersBound)
      })
      this.on('peer-add', recoverTreeNodeFromPeersBound)
    }

    this.emit('ready')

    // if we are a weak session the core might have closed...
    if (this.core.closing) this.close().catch(safetyCatch)
  }

  _removeSession() {
    if (this._sessionIndex === -1) return
    const head = this.sessions.pop()
    if (head !== this) this.sessions[(head._sessionIndex = this._sessionIndex)] = head
    this._sessionIndex = -1
    if (this.ongc !== null) this.ongc(this)
  }

  async _openSession(opts) {
    if (this.core.opened === false) await this.core.ready()

    if (this.keyPair === null) this.keyPair = opts.keyPair || this.core.header.keyPair

    const parent = opts.parent || null
    if (parent && parent.encryption) this.encryption = parent.encryption

    const e = getEncryptionOption(opts)
    if (!this.encryption) this.encryption = this._getEncryptionProvider(e)

    this.writable = this._isWritable()

    if (opts.valueEncoding) {
      this.valueEncoding = c.from(opts.valueEncoding)
    }
    if (opts.encodeBatch) {
      this.encodeBatch = opts.encodeBatch
    }

    // one session sets for pushOnly for all
    if (opts.pushOnly === true) {
      this.core.replicator.setPushOnly(true)
    }

    if (parent) {
      if (parent._stateIndex === -1) await parent.ready()
      if (!this.keyPair) this.keyPair = parent.keyPair

      const ps = parent.state

      if (ps) {
        const shouldSnapshot = this.snapshotted && !ps.isSnapshot()
        this.state = shouldSnapshot ? await ps.snapshot() : ps.ref()
      }

      if (this.snapshotted && this.core && !this._snapshot) {
        this._updateSnapshot()
      }
    }

    if (opts.exclusive && opts.writable !== false) {
      this.exclusive = true
      await this.core.lockExclusive()
    }

    const parentState = parent ? parent.state : this.core.state
    const checkout = opts.checkout === undefined ? -1 : opts.checkout
    const state = this.state

    if (opts.atom) {
      this.state = await parentState.createSession(null, false, opts.atom)
      if (state) state.unref()
    } else if (opts.name) {
      // todo: need to make named sessions safe before ready
      // atm we always copy the state in passCapabilities
      this.state = await parentState.createSession(opts.name, !!opts.overwrite, null)
      if (state) state.unref() // ref'ed above in setup session
    }

    if (this.state && checkout !== -1) {
      if (!opts.name && !opts.atom) {
        throw ASSERTION('Checkouts must be named or atomized', this.discoveryKey)
      }
      if (checkout > this.state.length) {
        throw ASSERTION(
          `Invalid checkout ${checkout} for ${opts.name}, length is ${this.state.length}`,
          this.discoveryKey
        )
      }
      if (this.state.prologue && checkout < this.state.prologue.length) {
        throw ASSERTION(
          `Invalid checkout ${checkout} for ${opts.name}, prologue length is ${this.state.prologue.length}`,
          this.discoveryKey
        )
      }
      if (checkout < this.state.length) await this.state.truncate(checkout, this.fork)
    }

    if (this.state === null) {
      this.state = this.core.state.ref()
    }

    this.writable = this._isWritable()

    if (this.snapshotted && this.core) this._updateSnapshot()

    this.state.addSession(this)
    // TODO: we need to rework the core reference flow, as the state and session do not always agree now due to moveTo
    this.core = this.state.core // in case it was wrong...

    if (opts.userData) {
      const tx = this.state.storage.write()
      for (const [key, value] of Object.entries(opts.userData)) {
        tx.putUserData(key, value)
      }
      await tx.flush()
    }

    if (opts.manifest && !this.core.header.manifest) {
      await this.core.setManifest(createManifest(opts.manifest))
    }

    this.core.replicator.updateActivity(this._active ? 1 : 0)

    this.opened = true
  }

  get replicator() {
    return this.core === null ? null : this.core.replicator
  }

  _getSnapshot() {
    return {
      length: this.state.length,
      byteLength: this.state.byteLength,
      fork: this.state.fork
    }
  }

  _updateSnapshot() {
    const prev = this._snapshot
    const next = (this._snapshot = this._getSnapshot())

    if (!prev) return true
    return prev.length !== next.length || prev.fork !== next.fork
  }

  _isWritable() {
    if (this._readonly) return false
    if (this.state && !this.state.isDefault()) return true
    return !!(this.keyPair && this.keyPair.secretKey)
  }

  close({ error } = {}) {
    if (this.closing) return this.closing

    this.closing = this._close(error || null)
    return this.closing
  }

  clearRequests(activeRequests, error) {
    if (!activeRequests.length) return
    if (this.core) this.core.replicator.clearRequests(activeRequests, error)
  }

  async _close(error) {
    if (this.opened === false) {
      try {
        await this.opening
      } catch (err) {
        if (!this.closed) throw err
      }
    }

    if (this.closed === true) return

    this.core.removeMonitor(this)
    this.state.removeSession(this)
    this._removeSession()

    this.readable = false
    this.writable = false
    this.opened = false

    const gc = []
    for (const ext of this.extensions.values()) {
      if (ext.session === this) gc.push(ext)
    }
    for (const ext of gc) ext.destroy()

    this.core.replicator.findingPeers -= this._findingPeers
    this.core.replicator.clearRequests(this.activeRequests, error)
    this.core.replicator.updateActivity(this._active ? -1 : 0)

    this._findingPeers = 0

    this.state.unref()

    if (this.exclusive) this.core.unlockExclusive()

    if (this.core.hasSession()) {
      // emit "fake" close as this is a session
      this.closed = true
      this.emit('close')
      return
    }

    if (this.core.autoClose) await this.core.close()

    this.closed = true
    this.emit('close')
  }

  async commit(session, opts) {
    await this.ready()
    await session.ready()

    return this.state.commit(session.state, { keyPair: this.keyPair, ...opts })
  }

  replicate(isInitiator, opts = {}) {
    // Only limitation here is that ondiscoverykey doesn't work atm when passing a muxer directly,
    // because it doesn't really make a lot of sense.
    if (Protomux.isProtomux(isInitiator)) return this._attachToMuxer(isInitiator)

    // if same stream is passed twice, ignore the 2nd one before we make sessions etc
    if (isStream(isInitiator) && this._isAttached(isInitiator)) return isInitiator

    const protocolStream = Hypercore.createProtocolStream(isInitiator, opts)
    const noiseStream = protocolStream.noiseStream
    const protocol = noiseStream.userData

    this._attachToMuxer(protocol)

    return protocolStream
  }

  _isAttached(stream) {
    return (
      stream.userData &&
      this.core &&
      this.core.replicator &&
      this.core.replicator.attached(stream.userData)
    )
  }

  _attachToMuxer(mux) {
    if (this.opened) {
      this.core.replicator.attachTo(mux)
    } else {
      this.opening.then(() => this.core.replicator.attachTo(mux), mux.destroy.bind(mux))
    }

    return mux
  }

  get id() {
    return this.core === null ? null : this.core.id
  }

  get key() {
    return this.core === null ? null : this.core.key
  }

  get discoveryKey() {
    return this.core === null ? null : this.core.discoveryKey
  }

  get manifest() {
    return this.core === null ? null : this.core.manifest
  }

  get length() {
    if (this._snapshot) return this._snapshot.length
    return this.opened === false ? 0 : this.state.length
  }

  get signedLength() {
    return this.opened === false ? 0 : this.state.signedLength()
  }

  /**
   * Deprecated. Use `const { byteLength } = await core.info()`.
   */
  get byteLength() {
    if (this.opened === false) return 0
    if (this._snapshot) return this._snapshot.byteLength
    return this.state.byteLength - this.state.length * this.padding
  }

  get remoteContiguousLength() {
    if (this.opened === false) return 0
    return Math.min(this.core.state.length, this.core.header.hints.remoteContiguousLength)
  }

  get contiguousLength() {
    if (this.opened === false) return 0
    return Math.min(this.core.state.length, this.core.header.hints.contiguousLength)
  }

  get contiguousByteLength() {
    return 0
  }

  get fork() {
    if (this.opened === false) return 0
    return this.state.fork
  }

  get padding() {
    if (this.encryption && this.key && this.manifest) {
      return this.encryption.padding(this.core, this.length)
    }

    return 0
  }

  get peers() {
    return this.opened === false ? [] : this.core.replicator.peers
  }

  get globalCache() {
    return this.opened === false ? null : this.core.globalCache
  }

  get recovering() {
    return this.opened === false ? 0 : this.core.header.hints.recovering
  }

  ready() {
    return this.opening
  }

  async recover() {
    if (this.opened === false) await this.opening
    return this.state.waitForRecovery()
  }

  async setUserData(key, value) {
    if (this.opened === false) await this.opening
    const existing = await this.getUserData(key)
    if (existing && b4a.isBuffer(value) && b4a.equals(existing, value)) return
    await this.state.setUserData(key, value)
  }

  async getUserData(key) {
    if (this.opened === false) await this.opening
    const batch = this.state.storage.read()
    const p = batch.getUserData(key)
    batch.tryFlush()
    return p
  }

  transferSession(core) {
    // todo: validate we can move

    if (this.weak === false) {
      this.core.activeSessions--
      core.activeSessions++
    }

    if (this._monitorIndex >= 0) {
      this.core.removeMonitor(this)
      core.addMonitor(this)
    }

    const old = this.core

    this.core = core

    old.replicator.clearRequests(this.activeRequests, SESSION_MOVED())

    this.emit('migrate', this.key)
  }

  findingPeers() {
    this._findingPeers++
    if (this.core !== null && !this.closing) this.core.replicator.findingPeers++

    let once = true

    return () => {
      if (this.closing || !once) return
      once = false
      this._findingPeers--
      if (this.core !== null && --this.core.replicator.findingPeers === 0) {
        this.core.replicator.queueUpdateAll()
      }
    }
  }

  async info(opts) {
    if (this.opened === false) await this.opening

    return Info.from(this, opts)
  }

  async update(opts) {
    if (this.opened === false) await this.opening
    if (this.closing !== null) return false
    if (this.snapshotted) return false

    if (this.writable && (!opts || opts.force !== true)) return false

    const remoteWait = this._shouldWait(opts, this.core.replicator.findingPeers > 0)

    let upgraded = false

    if (await this.core.replicator.applyPendingReorg()) {
      upgraded = true
    }

    if (!upgraded && remoteWait) {
      const activeRequests = (opts && opts.activeRequests) || this.activeRequests
      if (isRequestsDestroyed(activeRequests)) throw REQUEST_CANCELLED()

      const req = this.core.replicator.addUpgrade(activeRequests)

      try {
        upgraded = await req.promise
      } catch (err) {
        if (isSessionMoved(err)) return this.update(opts)
        throw err
      }
    }

    if (!upgraded) return false
    return true
  }

  async seek(bytes, opts) {
    if (this.opened === false) await this.opening
    if (!isValidIndex(bytes)) throw ASSERTION('seek is invalid', this.discoveryKey)

    const activeRequests = (opts && opts.activeRequests) || this.activeRequests
    if (isRequestsDestroyed(activeRequests)) throw REQUEST_CANCELLED()

    if (this.encryption && !this.core.manifest) {
      const req = this.replicator.addUpgrade(activeRequests)
      try {
        await req.promise
      } catch (err) {
        if (isSessionMoved(err)) return this.seek(bytes, opts)
        throw err
      }
    }

    const s = MerkleTree.seek(this.state, bytes, this.padding)

    const offset = await s.update()
    if (offset) return offset

    if (this.closing !== null) {
      throw SESSION_CLOSED('cannot seek on a closed session', this.discoveryKey)
    }

    if (!this._shouldWait(opts, this.wait)) return null

    if (isRequestsDestroyed(activeRequests)) throw REQUEST_CANCELLED()
    const req = this.core.replicator.addSeek(activeRequests, s)

    const timeout = opts && opts.timeout !== undefined ? opts.timeout : this.timeout
    if (timeout) req.context.setTimeout(req, timeout)

    try {
      return await req.promise
    } catch (err) {
      if (isSessionMoved(err)) return this.seek(bytes, opts)
      throw err
    }
  }

  async has(start, end = start + 1) {
    if (this.opened === false) await this.opening
    if (!isValidIndex(start) || !isValidIndex(end)) {
      throw ASSERTION('has range is invalid', this.discoveryKey)
    }

    if (this.state.isDefault()) {
      if (end === start + 1) return this.core.bitfield.get(start)

      const i = this.core.bitfield.firstUnset(start)
      return i === -1 || i >= end
    }

    if (end === start + 1) {
      const rx = this.state.storage.read()
      const block = rx.getBlock(start)
      rx.tryFlush()

      return (await block) !== null
    }

    let count = 0

    const stream = this.state.storage.createBlockStream({ gte: start, lt: end })
    for await (const block of stream) {
      if (block === null) return false
      count++
    }

    return count === end - start
  }

  async get(index, opts) {
    if (this.opened === false) await this.opening
    if (!isValidIndex(index)) throw ASSERTION('block index is invalid', this.discoveryKey)

    if (this.closing !== null) {
      throw SESSION_CLOSED('cannot get on a closed session', this.discoveryKey)
    }

    const encoding =
      (opts && opts.valueEncoding && c.from(opts.valueEncoding)) || this.valueEncoding

    if (this.onseq !== null) this.onseq(index, this)
    if (this._marking) await this.markBlock(index)

    const req = this._get(index, opts)

    let block = await req
    if (!block) return null

    if (opts && opts.raw) return block

    if (this.encryption && (!opts || opts.decrypt !== false)) {
      // Copy the block as it might be shared with other sessions.
      block = b4a.from(block)

      await this.encryption.decrypt(index, block, this.core)
    }

    return this._decode(encoding, block, index)
  }

  async clear(start, end = start + 1, opts) {
    if (this.opened === false) await this.opening
    if (this.closing !== null) {
      throw SESSION_CLOSED('cannot clear on a closed session', this.discoveryKey)
    }

    if (typeof end === 'object') {
      opts = end
      end = start + 1
    }

    if (!isValidIndex(start) || !isValidIndex(end)) {
      throw ASSERTION('clear range is invalid', this.discoveryKey)
    }

    const cleared = opts && opts.diff ? { blocks: 0 } : null

    if (start >= end) return cleared
    if (start >= this.length) return cleared

    await this.state.clear(start, end, cleared)

    return cleared
  }

  async purge() {
    await this._closeAllSessions(null)
    await this.core.purge()
  }

  async _get(index, opts) {
    const block = await readBlock(this.state.storage.read(), index)

    if (block !== null) return block

    if (this.closing !== null) {
      throw SESSION_CLOSED('cannot get on a closed session', this.discoveryKey)
    }

    // snapshot should check if core has block
    if (this._snapshot !== null) {
      checkSnapshot(this, index)
      const coreBlock = await readBlock(this.core.state.storage.read(), index)

      checkSnapshot(this, index)
      if (coreBlock !== null) return coreBlock
    }

    // lets check the bitfield to see if we got it during the above async calls
    // this is the last resort before replication, so always safe.
    if (this.core.bitfield.get(index)) {
      const coreBlock = await readBlock(this.state.storage.read(), index)
      // TODO: this should not be needed, only needed atm in case we are doing a moveTo during this (we should fix)
      if (coreBlock !== null) return coreBlock
    }

    if (!this._shouldWait(opts, this.wait)) return null

    this.waits++
    if (opts && opts.onwait) opts.onwait(index, this)
    if (this.onwait) this.onwait(index, this)

    const activeRequests = (opts && opts.activeRequests) || this.activeRequests
    if (isRequestsDestroyed(activeRequests)) throw REQUEST_CANCELLED()

    const force = opts ? opts.force === true : false
    const req = this.core.replicator.addBlock(activeRequests, index, force)
    req.snapshot = index < this.length

    const timeout = opts && opts.timeout !== undefined ? opts.timeout : this.timeout
    if (timeout) req.context.setTimeout(req, timeout)

    let replicatedBlock = null

    try {
      replicatedBlock = await req.promise
    } catch (err) {
      if (isSessionMoved(err)) return this._get(index, opts)
      throw err
    }

    if (this._snapshot !== null) checkSnapshot(this, index)
    return maybeUnslab(replicatedBlock)
  }

  _shouldWait(opts, defaultValue) {
    if (opts) {
      if (opts.wait === false) return false
      if (opts.wait === true) return true
    }
    return defaultValue
  }

  _setupMarks() {
    if (this._marks === null) {
      const storage = this.snapshotted ? this.core.state.storage : this.state.storage
      this._marks = new MarkBitfield(storage)
    }
  }

  async markBlock(start, end = start + 1) {
    if (this.opened === false) await this.opening

    this._setupMarks()

    // TODO support as single rocks batch
    const setPromises = []
    for (let i = start; i < end; i++) {
      setPromises.push(this._marks.set(i, true))
    }

    return Promise.all(setPromises)
  }

  async clearMarkings() {
    if (this.opened === false) await this.opening

    this._setupMarks()

    await this._marks.clear()
    this._marks = null
  }

  async startMarking() {
    if (this._marking) {
      throw ASSERTION("Hypercore cannot be gc'ed when already in gc mode", this.discoveryKey)
    }
    if (this.state && this.state.name) {
      throw ASSERTION("Hypercore cannot be gc'ed when a named session", this.discoveryKey)
    }
    if (this.state && this.state.storage.atom) {
      throw ASSERTION("Hypercore cannot be gc'ed when an atomic session", this.discoveryKey)
    }
    if (this.opened === false) await this.opening
    await this.clearMarkings()

    this._marking = true
  }

  async sweep({ batchSize = 1000 } = {}) {
    if (this.opened === false) await this.opening

    assert(!this.snapshotted, 'Cannot sweep a snapshot')

    // No marks - load from storage
    this._setupMarks()

    let clearing = []
    let prevIndex = this.length
    for await (const index of this._marks.createMarkStream({ reverse: true })) {
      if (index + 1 === prevIndex) {
        prevIndex = index
        continue
      }
      clearing.push(this.clear(index + 1, prevIndex))
      if (clearing.length >= batchSize) {
        await Promise.all(clearing)
        clearing = []
      }
      prevIndex = index
    }
    // Clear range from the very start if not marked
    if (prevIndex > 0) clearing.push(this.clear(0, prevIndex))
    await Promise.all(clearing)

    this._marking = false
    await this.clearMarkings()
  }

  createReadStream(opts) {
    return new ReadStream(this, opts)
  }

  createWriteStream() {
    return new WriteStream(this)
  }

  createByteStream(opts) {
    return new ByteStream(this, opts)
  }

  download(range) {
    return new Download(this, range)
  }

  // TODO: get rid of this / deprecate it?
  undownload(range) {
    range.destroy(null)
  }

  // TODO: get rid of this / deprecate it?
  cancel(request) {
    // Do nothing for now
  }

  async truncate(newLength = 0, opts = {}) {
    if (this.opened === false) await this.opening
    if (this.closing) throw SESSION_CLOSED('Cannot append to a closed session', this.discoveryKey)

    const {
      fork = this.state.fork + 1,
      keyPair = this.keyPair,
      signature = null
    } = typeof opts === 'number' ? { fork: opts } : opts

    const isDefault = this.state === this.core.state
    const writable = !this._readonly && !!(signature || (keyPair && keyPair.secretKey))
    if (isDefault && writable === false && (newLength > 0 || fork !== this.state.fork)) {
      throw SESSION_NOT_WRITABLE('cannot append to a non-writable core', this.discoveryKey)
    }

    await this.state.truncate(newLength, fork, { keyPair, signature })

    // TODO: Should propagate from an event triggered by the oplog
    if (this.state === this.core.state) this.core.replicator.updateAll()
  }

  async append(blocks, opts = {}) {
    if (this.opened === false) await this.opening
    if (this.closing) throw SESSION_CLOSED('Cannot append to a closed session', this.discoveryKey)

    const isDefault = this.state === this.core.state
    const defaultKeyPair = this.state.name === null ? this.keyPair : null

    const { keyPair = defaultKeyPair, signature = null, maxLength, postappend = null } = opts
    const writable =
      !isDefault || !!signature || !!(keyPair && keyPair.secretKey) || opts.writable === true

    if (this._readonly || writable === false) {
      throw SESSION_NOT_WRITABLE('cannot append to a readonly core', this.discoveryKey)
    }

    blocks = Array.isArray(blocks) ? blocks : [blocks]

    const preappend = this.encryption && this._preappend

    const buffers = this.encodeBatch !== null ? this.encodeBatch(blocks) : new Array(blocks.length)

    if (this.encodeBatch === null) {
      for (let i = 0; i < blocks.length; i++) {
        buffers[i] = this._encode(this.valueEncoding, blocks[i])
      }
    }
    for (const b of buffers) {
      if (b.byteLength > MAX_SUGGESTED_BLOCK_SIZE) {
        throw BAD_ARGUMENT(
          'Appended block exceeds the maximum suggested block size',
          this.discoveryKey
        )
      }
    }

    return this.state.append(buffers, { keyPair, signature, preappend, postappend, maxLength })
  }

  async signable(length = -1, fork = -1) {
    if (this.opened === false) await this.opening
    if (length === -1) length = this.length
    if (fork === -1) fork = this.fork

    return caps.treeSignable(this.key, await this.treeHash(length), length, fork)
  }

  async treeHash(length = -1) {
    if (this.opened === false) await this.opening
    if (length === -1) length = this.length
    if (length > 0 && !(await this.has(length - 1))) await this.get(length - 1)

    const roots = await MerkleTree.getRoots(this.state, length)
    return crypto.tree(roots)
  }

  async missingNodes(index) {
    if (this.opened === false) await this.opening
    return await MerkleTree.missingNodes(this.core.state, 2 * index, this.core.state.length)
  }

  async proof(opts) {
    if (this.opened === false) await this.opening
    const rx = this.state.storage.read()
    const proofPromise = MerkleTree.proof(this.state, rx, opts)
    const blockPromise = opts && opts.block ? rx.getBlock(opts.block.index) : null
    rx.tryFlush()
    const [proof, block] = await Promise.all([proofPromise, blockPromise])
    const settled = await proof.settle()
    if (block) settled.block.value = block
    return settled
  }

  async applyProof(proof, from) {
    if (this.opened === false) await this.opening
    return this.core.verify(proof, from)
  }

  async verifyFullyRemote(proof) {
    if (this.opened === false) await this.opening
    const batch = await MerkleTree.verifyFullyRemote(this.state, proof)
    await this.core._verifyBatchUpgrade(batch, proof.manifest)
    return batch
  }

  generateRemoteProofForTreeNode(treeNodeIndex) {
    const blockProofIndex = flat.rightSpan(treeNodeIndex) / 2
    return proof(this, {
      index: blockProofIndex,
      // + 1 to length so the block is included
      upgrade: { start: 0, length: blockProofIndex + 1 }
    })
  }

  async recoverFromRemoteProof(remoteProof) {
    this.core.replicator.setPushOnly(true)
    this.core._repairMode = true

    await this.core.state.mutex.lock()

    try {
      const p = await verify(this.core.db, remoteProof)
      if (!p) return false

      const tx = this.core.storage.write()
      for (const node of p.proof.upgrade.nodes) {
        tx.putTreeNode(node)
      }
      await tx.flush()

      const succeed = p.proof.upgrade.nodes.length !== 0
      if (succeed) {
        this.core.replicator.setPushOnly(false)
      }
      return succeed
    } finally {
      this.core.state.mutex.unlock()
    }
  }

  recoverTreeNodeFromPeers() {
    this.core.replicator.setPushOnly(true)

    for (const peer of this.core.replicator.peers) {
      const req = {
        id: 0,
        fork: this.fork,
        upgrade: {
          start: 0,
          length: this.length
        }
      }
      peer.wireRequest.send(req)
    }
  }

  registerExtension(name, handlers = {}) {
    if (this.extensions.has(name)) {
      const ext = this.extensions.get(name)
      ext.handlers = handlers
      ext.encoding = c.from(handlers.encoding || c.buffer)
      ext.session = this
      return ext
    }

    const ext = {
      name,
      handlers,
      encoding: c.from(handlers.encoding || c.buffer),
      session: this,
      send(message, peer) {
        const buffer = c.encode(this.encoding, message)
        peer.extension(name, buffer)
      },
      broadcast(message) {
        const buffer = c.encode(this.encoding, message)
        for (const peer of this.session.peers) {
          peer.extension(name, buffer)
        }
      },
      destroy() {
        for (const peer of this.session.peers) {
          if (peer.extensions.get(name) === ext) peer.extensions.delete(name)
        }
        this.session.extensions.delete(name)
      },
      _onmessage(state, peer) {
        const m = this.encoding.decode(state)
        if (this.handlers.onmessage) this.handlers.onmessage(m, peer)
      }
    }

    this.extensions.set(name, ext)

    if (this.core === null) this._monitorIndex = -2
    else this.core.addMonitor(this)

    for (const peer of this.peers) {
      peer.extensions.set(name, ext)
    }

    return ext
  }

  _encode(enc, val) {
    const state = { start: this.padding, end: this.padding, buffer: null }

    if (b4a.isBuffer(val)) {
      if (state.start === 0) return val
      state.end += val.byteLength
    } else if (enc) {
      enc.preencode(state, val)
    } else {
      val = b4a.from(val)
      if (state.start === 0) return val
      state.end += val.byteLength
    }

    state.buffer = b4a.allocUnsafe(state.end)

    if (enc) enc.encode(state, val)
    else state.buffer.set(val, state.start)

    return state.buffer
  }

  _decode(enc, block, index) {
    if (this.encryption) block = block.subarray(this.encryption.padding(this.core, index))
    try {
      if (enc) return c.decode(enc, block)
    } catch (err) {
      throw DECODING_ERROR(err.message, this.discoveryKey)
    }
    return block
  }

  _getEncryptionProvider(e) {
    if (isEncryptionProvider(e)) return e
    if (!e || !e.key) return null
    return new DefaultEncryption(e.key, this.key, { block: e.block, compat: this.core.compat })
  }
}

module.exports = Hypercore

function isStream(s) {
  return typeof s === 'object' && s && typeof s.pipe === 'function'
}

async function preappend(blocks) {
  const offset = this.state.length
  const fork = this.state.encryptionFork

  for (let i = 0; i < blocks.length; i++) {
    await this.encryption.encrypt(offset + i, blocks[i], fork, this.core)
  }
}

function isValidIndex(index) {
  return index === 0 || index > 0
}

function maybeUnslab(block) {
  // Unslab only when it takes up less then half the slab
  return block !== null && 2 * block.byteLength < block.buffer.byteLength ? unslab(block) : block
}

function checkSnapshot(snapshot, index) {
  if (index >= snapshot.state.snapshotCompatLength) {
    throw SNAPSHOT_NOT_AVAILABLE(
      `snapshot at index ${index} not available (max compat length ${snapshot.state.snapshotCompatLength})`,
      snapshot.discoveryKey
    )
  }
}

function readBlock(rx, index) {
  const promise = rx.getBlock(index)
  rx.tryFlush()
  return promise
}

function initOnce(session, storage, key, opts) {
  if (storage === null) storage = opts.storage || null
  if (key === null) key = opts.key || null

  session.core = new Core(Hypercore.defaultStorage(storage), {
    preopen: opts.preopen,
    eagerUpgrade: opts.eagerUpgrade !== false,
    notDownloadingLinger: opts.notDownloadingLinger,
    allowFork: opts.allowFork !== false,
    allowPush: !!opts.allowPush,
    pushOnly: !!opts.pushOnly,
    alwaysLatestBlock: !!opts.allowLatestBlock,
    inflightRange: opts.inflightRange,
    compat: opts.compat === true,
    force: opts.force,
    createIfMissing: opts.createIfMissing,
    discoveryKey: opts.discoveryKey,
    overwrite: opts.overwrite,
    key,
    keyPair: opts.keyPair,
    legacy: opts.legacy,
    manifest: opts.manifest,
    group: opts.group,
    globalCache: opts.globalCache || null // session is a temp option, not to be relied on unless you know what you are doing (no semver guarantees)
  })
}

function maybeAddMonitor(name) {
  if (name === 'append' || name === 'truncate') return
  if (this._monitorIndex >= 0 || this.closing) return

  if (this.core === null) {
    this._monitorIndex = -2
  } else {
    this.core.addMonitor(this)
  }
}

function isSessionMoved(err) {
  return err.code === 'SESSION_MOVED'
}

function getEncryptionOption(opts) {
  // old style, supported for now but will go away
  if (opts.encryptionKey) return { key: opts.encryptionKey, block: !!opts.isBlockKey }
  if (!opts.encryption) return null
  return b4a.isBuffer(opts.encryption) ? { key: opts.encryption } : opts.encryption
}

function isEncryptionProvider(e) {
  return e && isFunction(e.padding) && isFunction(e.encrypt) && isFunction(e.decrypt)
}

function isFunction(fn) {
  return !!fn && typeof fn === 'function'
}

function createDiscoveryKeyHandler(fn) {
  return ondiscoverykey
  function ondiscoverykey(id) {
    if (!id || id.byteLength !== 32) throw BAD_ARGUMENT('Invalid discovery key')
    return fn(id)
  }
}

function isRequestsDestroyed(activeRequests) {
  // TODO: move this to an object instead so we can store a property in next major
  return activeRequests.length > 0 && activeRequests[0] === null
}
const crypto = require('hypercore-crypto')
const flat = require('flat-tree')
const b4a = require('b4a')
const { MerkleTree } = require('./merkle-tree')

module.exports = async function auditCore(
  core,
  { tree = true, blocks = true, bitfield = true, dryRun = false } = {}
) {
  const length = core.state.length
  const stats = {
    treeNodes: 0,
    blocks: 0,
    bits: 0,
    droppedTreeNodes: 0,
    droppedBlocks: 0,
    droppedBits: 0,
    corrupt: false
  }

  // audit the tree
  if (tree) {
    let tx = null

    const roots = await MerkleTree.getRootsFromStorage(core.state.storage, length)
    const stack = []

    for (const r of roots) {
      if (r === null) {
        if (!dryRun) {
          const storage = core.state.storage
          await storage.store.deleteCore(storage.core)
          return null
        }

        stats.corrupt = true
      }

      stack.push(r)
    }

    stats.treeNodes += roots.length

    while (stack.length > 0) {
      const node = stack.pop()

      if ((node.index & 1) === 0) continue

      const [left, right] = flat.children(node.index)

      const rx = core.state.storage.read()
      const leftNodePromise = rx.getTreeNode(left)
      const rightNodePromise = rx.getTreeNode(right)

      rx.tryFlush()

      const [leftNode, rightNode] = await Promise.all([leftNodePromise, rightNodePromise])

      if (isBadTree(node, leftNode, rightNode)) {
        if (!tx && !stats.corrupt) tx = core.state.storage.write()
        const [l, r] = flat.spans(node.index)
        tx.deleteTreeNodeRange(l, r + 1)
        stats.droppedTreeNodes++
        continue
      }

      if (!leftNode) continue

      stats.treeNodes += 2
      stack.push(leftNode, rightNode)
    }

    if (tx && !dryRun) await tx.flush()
  }

  // audit the blocks
  if (blocks) {
    let tx = null

    for await (const block of core.state.storage.createBlockStream()) {
      if (!core.bitfield.get(block.index)) {
        if (!tx && !stats.corrupt) tx = core.state.storage.write()
        tx.deleteBlock(block.index)
        stats.droppedBlocks++
      }

      const rx = core.state.storage.read()
      const treeNodePromise = rx.getTreeNode(2 * block.index)

      rx.tryFlush()

      const treeNode = await treeNodePromise

      if (isBadBlock(treeNode, block.value)) {
        if (!tx && !stats.corrupt) tx = core.state.storage.write()
        tx.deleteBlock(block.index)
        stats.droppedBlocks++
        continue
      }

      stats.blocks++
    }

    if (tx && !dryRun) await tx.flush()
  }

  if (bitfield) {
    let tx = null

    for (const index of allBits(core.bitfield)) {
      const rx = core.state.storage.read()
      const blockPromise = rx.getBlock(index)

      rx.tryFlush()

      const block = await blockPromise
      if (!block) {
        stats.droppedBits++
        if (dryRun) continue

        if (!tx && !stats.corrupt) tx = core.state.storage.write()

        core.bitfield.set(index, false)

        const page = core.bitfield.getBitfield(index)
        if (page.bitfield) tx.putBitfieldPage(page.index, page.bitfield)
        else tx.deleteBitfieldPage(page.index)
        continue
      }

      stats.bits++
    }

    if (tx && !dryRun) await tx.flush()
  }

  return stats
}

function isBadBlock(node, block) {
  if (!node) return true
  const hash = crypto.data(block)
  return !b4a.equals(hash, node.hash) || node.size !== block.byteLength
}

function isBadTree(parent, left, right) {
  if (!left && !right) return false
  if (!left || !right) return true
  const hash = crypto.parent(left, right)
  return !b4a.equals(hash, parent.hash) || parent.size !== left.size + right.size
}

function* allBits(bitfield) {
  let i = 0
  if (bitfield.get(0)) yield 0
  while (true) {
    i = bitfield.findFirst(true, i + 1)
    if (i === -1) break
    yield i
  }
}
const b4a = require('b4a')
const quickbit = require('./compat').quickbit

module.exports = class BitInterlude {
  constructor() {
    this.ranges = []
  }

  contiguousLength(from) {
    for (const r of this.ranges) {
      if (r.start > from) break
      if (!r.value && r.start <= from) return r.start
    }

    // TODO: be smarter
    while (this.get(from) === true) from++
    return from
  }

  get(index) {
    let start = 0
    let end = this.ranges.length

    while (start < end) {
      const mid = (start + end) >> 1
      const r = this.ranges[mid]

      if (index < r.start) {
        end = mid
        continue
      }

      if (index >= r.end) {
        if (mid === start) break
        start = mid
        continue
      }

      return r.value
    }

    return false
  }

  setRange(start, end, value) {
    if (start === end) return

    let r = null

    for (let i = 0; i < this.ranges.length; i++) {
      r = this.ranges[i]

      // if already inside, stop
      if (r.start <= start && end <= r.end) {
        if (value === r.value) return

        const ranges = mergeRanges(r, { start, end, value })
        this.ranges.splice(i, 1, ...ranges)

        return
      }

      // we wanna overun the interval
      if (start > r.end) {
        continue
      }

      // we overran but this interval is ending after us, move it back
      if (end >= r.start && end <= r.end) {
        r.start = r.value === value ? start : end
        if (r.value !== value) this.ranges.splice(i, 0, { start, end, value })
        return
      }

      // we overran but our start is contained in this interval, move start back
      if (start >= r.start && start <= r.end) {
        if (r.value !== value) {
          r.end = start // Crop current comparison

          // If there's a next range
          if (this.ranges.length - 1 > i) {
            const next = this.ranges[i + 1]
            // If the same, go next
            if (next.value === value) continue
            // Else we overlap so update next range
            if (next.start < end) next.start = end
          }

          this.ranges.splice(++i, 0, { start, end, value })
          return
        }

        start = r.start
      }

      let remove = 0

      for (let j = i; j < this.ranges.length; j++) {
        const n = this.ranges[j]
        if (n.start > end || n.value !== value) break
        if (n.start <= end && n.end > end) end = n.end
        remove++
      }

      this.ranges.splice(i, remove, { start, end, value })
      return
    }

    if (r !== null) {
      if (start <= r.end && end > r.end) {
        r.end = end
        return
      }

      // we never
      if (r.end > start) return
    }

    this.ranges.push({ start, end, value })
  }

  flush(tx, bitfield) {
    if (!this.ranges.length) return []

    let index = this.ranges[0].start
    const final = this.ranges[this.ranges.length - 1].end

    let i = 0

    while (index < final) {
      const page = bitfield.getBitfield(index) // read only
      const pageIndex = page ? page.index : bitfield.getPageIndex(index)

      const buf = b4a.allocUnsafe(bitfield.getPageByteLength())

      if (page) {
        const src = page.bitfield // Uint32Array
        buf.set(b4a.from(src.buffer, src.byteOffset, src.byteLength), 0)
      } else {
        b4a.fill(buf, 0)
      }

      const last = (pageIndex + 1) * (buf.byteLength << 3)
      const offset = pageIndex * (buf.byteLength << 3)

      let hasValue = false

      while (i < this.ranges.length) {
        const { start, end, value } = this.ranges[i]

        if (!hasValue && value) hasValue = true

        const from = start < index ? index : start
        const to = end < last ? end : last

        quickbit.fill(buf, value, from - offset, to - offset)

        index = to

        if (to === last) break

        i++
      }

      if (page || hasValue) tx.putBitfieldPage(pageIndex, buf)
    }

    return this.ranges
  }
}

function mergeRanges(a, b) {
  const ranges = []
  if (a.start < b.start) ranges.push({ start: a.start, end: b.start, value: a.value })
  ranges.push({ start: b.start, end: b.end, value: b.value })
  if (b.end < a.end) ranges.push({ start: b.end, end: a.end, value: a.value })

  return ranges
}
const BigSparseArray = require('big-sparse-array')
const b4a = require('b4a')
const quickbit = require('./compat').quickbit

const BITS_PER_PAGE = 32768
const BYTES_PER_PAGE = BITS_PER_PAGE / 8
const WORDS_PER_PAGE = BYTES_PER_PAGE / 4
const BITS_PER_SEGMENT = 2097152
const BYTES_PER_SEGMENT = BITS_PER_SEGMENT / 8
const WORDS_PER_SEGMENT = BYTES_PER_SEGMENT / 4
const INITIAL_WORDS_PER_SEGMENT = 1024
const PAGES_PER_SEGMENT = BITS_PER_SEGMENT / BITS_PER_PAGE
const SEGMENT_GROWTH_FACTOR = 4

class BitfieldPage {
  constructor(index, segment) {
    this.index = index
    this.offset = index * BYTES_PER_PAGE - segment.offset
    this.bitfield = null
    this.segment = segment

    segment.add(this)
  }

  get tree() {
    return this.segment.tree
  }

  get(index, dirty) {
    return quickbit.get(this.bitfield, index)
  }

  set(index, val) {
    if (quickbit.set(this.bitfield, index, val)) {
      this.tree.update(this.offset * 8 + index)
    }
  }

  setRange(start, end, val) {
    quickbit.fill(this.bitfield, val, start, end)

    let i = Math.floor(start / 128)
    const n = i + Math.ceil((end - start) / 128)

    while (i <= n) this.tree.update(this.offset * 8 + i++ * 128)
  }

  findFirst(val, position) {
    return quickbit.findFirst(this.bitfield, val, position)
  }

  findLast(val, position) {
    return quickbit.findLast(this.bitfield, val, position)
  }

  count(start, length, val) {
    const end = start + length

    let i = start
    let c = 0

    while (length > 0) {
      const l = this.findFirst(val, i)
      if (l === -1 || l >= end) return c

      const h = this.findFirst(!val, l + 1)
      if (h === -1 || h >= end) return c + end - l

      c += h - l
      length -= h - i
      i = h
    }

    return c
  }
}

class BitfieldSegment {
  constructor(index, bitfield) {
    this.index = index
    this.offset = index * BYTES_PER_SEGMENT
    this.tree = quickbit.Index.from(bitfield, BYTES_PER_SEGMENT)
    this.pages = new Array(PAGES_PER_SEGMENT)
  }

  get bitfield() {
    return this.tree.field
  }

  add(page) {
    const i = page.index - this.index * PAGES_PER_SEGMENT
    this.pages[i] = page

    const start = i * WORDS_PER_PAGE
    const end = start + WORDS_PER_PAGE

    if (end >= this.bitfield.length) this.reallocate(end)

    page.bitfield = this.bitfield.subarray(start, end)
  }

  reallocate(length) {
    let target = this.bitfield.length
    while (target < length) target *= SEGMENT_GROWTH_FACTOR

    const bitfield = new Uint32Array(target)
    bitfield.set(this.bitfield)

    this.tree = quickbit.Index.from(bitfield, BYTES_PER_SEGMENT)

    for (let i = 0; i < this.pages.length; i++) {
      const page = this.pages[i]
      if (!page) continue

      const start = i * WORDS_PER_PAGE
      const end = start + WORDS_PER_PAGE

      page.bitfield = bitfield.subarray(start, end)
    }
  }

  findFirst(val, position) {
    position = this.tree.skipFirst(!val, position)

    let j = position & (BITS_PER_PAGE - 1)
    let i = (position - j) / BITS_PER_PAGE

    if (i >= PAGES_PER_SEGMENT) return -1

    while (i < this.pages.length) {
      const p = this.pages[i]

      let index = -1

      if (p) index = p.findFirst(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_PAGE + index

      j = 0
      i++
    }

    return -1
  }

  findLast(val, position) {
    position = this.tree.skipLast(!val, position)

    let j = position & (BITS_PER_PAGE - 1)
    let i = (position - j) / BITS_PER_PAGE

    if (i >= PAGES_PER_SEGMENT) return -1

    while (i >= 0) {
      const p = this.pages[i]

      let index = -1

      if (p) index = p.findLast(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_PAGE + index

      j = BITS_PER_PAGE - 1
      i--
    }

    return -1
  }
}

module.exports = class Bitfield {
  static BITS_PER_PAGE = BITS_PER_PAGE
  static BYTES_PER_PAGE = BYTES_PER_PAGE

  constructor(buffer) {
    this.resumed = !!(buffer && buffer.byteLength >= 0)

    this._pages = new BigSparseArray()
    this._segments = new BigSparseArray()

    const view = this.resumed
      ? new Uint32Array(buffer.buffer, buffer.byteOffset, Math.floor(buffer.byteLength / 4))
      : new Uint32Array(INITIAL_WORDS_PER_SEGMENT)

    for (let i = 0; i < view.length; i += WORDS_PER_SEGMENT) {
      let bitfield = view.subarray(i, i + WORDS_PER_SEGMENT)
      let length = WORDS_PER_SEGMENT

      if (i === 0) {
        length = INITIAL_WORDS_PER_SEGMENT
        while (length < bitfield.length) length *= SEGMENT_GROWTH_FACTOR
      }

      if (bitfield.length !== length) {
        const copy = new Uint32Array(length)
        copy.set(bitfield, 0)
        bitfield = copy
      }

      const segment = new BitfieldSegment(i / WORDS_PER_SEGMENT, bitfield)
      this._segments.set(segment.index, segment)

      for (let j = 0; j < bitfield.length; j += WORDS_PER_PAGE) {
        const page = new BitfieldPage((i + j) / WORDS_PER_PAGE, segment)
        this._pages.set(page.index, page)
      }
    }
  }

  static from(bitfield) {
    return new Bitfield(bitfield.toBuffer(bitfield._pages.maxLength * BITS_PER_PAGE))
  }

  toBuffer(length) {
    const pages = Math.ceil(length / BITS_PER_PAGE)
    const buffer = b4a.allocUnsafe(pages * BYTES_PER_PAGE)

    for (let i = 0; i < pages; i++) {
      const page = this._pages.get(i)
      const offset = i * BYTES_PER_PAGE

      if (page) {
        const buf = b4a.from(
          page.bitfield.buffer,
          page.bitfield.byteOffset,
          page.bitfield.byteLength
        )

        buffer.set(buf, offset)
      } else {
        buffer.fill(0, offset, offset + BYTES_PER_PAGE)
      }
    }

    return buffer
  }

  getBitfield(index) {
    const i = this.getPageIndex(index)

    const p = this._pages.get(i)
    return p || null
  }

  merge(bitfield, length) {
    let i = 0

    while (i < length) {
      const start = bitfield.firstSet(i)
      if (start === -1) break

      i = bitfield.firstUnset(start)

      if (i === -1 || i > length) i = length

      this.setRange(start, i, true)

      if (i >= length) break
    }
  }

  get(index) {
    const j = index & (BITS_PER_PAGE - 1)
    const i = (index - j) / BITS_PER_PAGE

    const p = this._pages.get(i)

    return p ? p.get(j) : false
  }

  getPageByteLength() {
    return BYTES_PER_PAGE
  }

  getPageIndex(index) {
    const j = index & (BITS_PER_PAGE - 1)
    return (index - j) / BITS_PER_PAGE
  }

  getPage(index, create) {
    const i = this.getPageIndex(index)

    let p = this._pages.get(i)

    if (p) return p

    if (!create) return null

    const k = Math.floor(i / PAGES_PER_SEGMENT)
    const s =
      this._segments.get(k) ||
      this._segments.set(
        k,
        new BitfieldSegment(
          k,
          new Uint32Array(k === 0 ? INITIAL_WORDS_PER_SEGMENT : WORDS_PER_SEGMENT)
        )
      )

    p = this._pages.set(i, new BitfieldPage(i, s))

    return p
  }

  set(index, val) {
    const j = index & (BITS_PER_PAGE - 1)
    const i = (index - j) / BITS_PER_PAGE

    let p = this._pages.get(i)

    if (!p && val) {
      const k = Math.floor(i / PAGES_PER_SEGMENT)
      const s =
        this._segments.get(k) ||
        this._segments.set(
          k,
          new BitfieldSegment(
            k,
            new Uint32Array(k === 0 ? INITIAL_WORDS_PER_SEGMENT : WORDS_PER_SEGMENT)
          )
        )

      p = this._pages.set(i, new BitfieldPage(i, s))
    }

    if (p) p.set(j, val)
  }

  setRange(start, end, val) {
    let j = start & (BITS_PER_PAGE - 1)
    let i = (start - j) / BITS_PER_PAGE

    while (start < end) {
      let p = this._pages.get(i)

      if (!p && val) {
        const k = Math.floor(i / PAGES_PER_SEGMENT)
        const s =
          this._segments.get(k) ||
          this._segments.set(
            k,
            new BitfieldSegment(
              k,
              new Uint32Array(k === 0 ? INITIAL_WORDS_PER_SEGMENT : WORDS_PER_SEGMENT)
            )
          )

        p = this._pages.set(i, new BitfieldPage(i, s))
      }

      const offset = i * BITS_PER_PAGE
      const last = Math.min(end - offset, BITS_PER_PAGE)
      const range = last - j

      if (p) p.setRange(j, last, val)

      j = 0
      i++
      start += range
    }
  }

  findFirst(val, position) {
    let j = position & (BITS_PER_SEGMENT - 1)
    let i = (position - j) / BITS_PER_SEGMENT

    while (i < this._segments.maxLength) {
      const s = this._segments.get(i)

      let index = -1

      if (s) index = s.findFirst(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_SEGMENT + index

      j = 0
      i++
    }

    return val ? -1 : this._segments.maxLength * BITS_PER_SEGMENT
  }

  firstSet(position) {
    return this.findFirst(true, position)
  }

  firstUnset(position) {
    return this.findFirst(false, position)
  }

  findLast(val, position) {
    let j = position & (BITS_PER_SEGMENT - 1)
    let i = (position - j) / BITS_PER_SEGMENT

    while (i >= 0) {
      const s = this._segments.get(i)

      let index = -1

      if (s) index = s.findLast(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_SEGMENT + index

      j = BITS_PER_SEGMENT - 1
      i--
    }

    return -1
  }

  lastSet(position) {
    return this.findLast(true, position)
  }

  lastUnset(position) {
    return this.findLast(false, position)
  }

  hasUnset(start, length) {
    const end = start + length

    let j = start & (BITS_PER_SEGMENT - 1)
    let i = (start - j) / BITS_PER_SEGMENT

    while (i < this._segments.maxLength) {
      const s = this._segments.get(i)
      const index = s ? s.findFirst(false, j) : j
      if (index !== -1) return i * BITS_PER_SEGMENT + index < end

      j = 0
      i++

      if (i * BITS_PER_SEGMENT >= end) return false
    }

    return true
  }

  hasSet(start, length) {
    const end = start + length

    let j = start & (BITS_PER_SEGMENT - 1)
    let i = (start - j) / BITS_PER_SEGMENT

    while (i < this._segments.maxLength) {
      const s = this._segments.get(i)

      let index = -1

      if (s) index = s.findFirst(true, j)

      if (index !== -1) return i * BITS_PER_SEGMENT + index < end

      j = 0
      i++

      if (i * BITS_PER_SEGMENT >= end) return false
    }

    return false
  }

  count(start, length, val) {
    let j = start & (BITS_PER_PAGE - 1)
    let i = (start - j) / BITS_PER_PAGE
    let c = 0

    while (length > 0) {
      const p = this._pages.get(i)

      const end = Math.min(j + length, BITS_PER_PAGE)
      const range = end - j

      if (p) c += p.count(j, range, val)
      else if (!val) c += range

      j = 0
      i++
      length -= range
    }

    return c
  }

  countSet(start, length) {
    return this.count(start, length, true)
  }

  countUnset(start, length) {
    return this.count(start, length, false)
  }

  *want(start, length) {
    if (start & 31) {
      const d = start & 31
      start -= d
      length += d
    }

    let j = start & (BITS_PER_SEGMENT - 1)
    let i = (start - j) / BITS_PER_SEGMENT

    while (length > 0) {
      const s = this._segments.get(i)

      if (s) {
        let end = Math.min(j + length, BITS_PER_SEGMENT)
        if (end & 31) end += 32 - (end & 31)

        yield {
          start: i * BITS_PER_SEGMENT + j,
          bitfield: s.bitfield.subarray(j / 32, end / 32)
        }
      }

      j = 0
      i++
      length -= BITS_PER_SEGMENT
    }
  }

  clear(tx) {
    return tx.deleteBitfieldPageRange(0, -1)
  }

  onupdate(ranges) {
    for (const { start, end, value } of ranges) {
      this.setRange(start, end, value)
    }
  }

  static async open(storage, length) {
    if (length === 0) return new Bitfield(storage, null)

    const pages = Math.ceil(length / BITS_PER_PAGE)
    const buffer = b4a.alloc(pages * BYTES_PER_PAGE)
    const stream = storage.createBitfieldStream({ lt: pages })

    for await (const { index, page } of stream) {
      buffer.set(page, index * BYTES_PER_PAGE)
    }

    return new Bitfield(buffer)
  }
}
const crypto = require('hypercore-crypto')
const sodium = require('sodium-universal')
const b4a = require('b4a')
const c = require('compact-encoding')

// TODO: rename this to "crypto" and move everything hashing related etc in here
// Also lets move the tree stuff from hypercore-crypto here

const [
  TREE,
  REPLICATE_INITIATOR,
  REPLICATE_RESPONDER,
  MANIFEST,
  DEFAULT_NAMESPACE,
  DEFAULT_ENCRYPTION
] = crypto.namespace('hypercore', 6)

exports.MANIFEST = MANIFEST
exports.DEFAULT_NAMESPACE = DEFAULT_NAMESPACE
exports.DEFAULT_ENCRYPTION = DEFAULT_ENCRYPTION

exports.replicate = function (isInitiator, key, handshakeHash) {
  const out = b4a.allocUnsafe(32)
  sodium.crypto_generichash_batch(
    out,
    [isInitiator ? REPLICATE_INITIATOR : REPLICATE_RESPONDER, key],
    handshakeHash
  )
  return out
}

exports.treeSignable = function (manifestHash, treeHash, length, fork) {
  const state = { start: 0, end: 112, buffer: b4a.allocUnsafe(112) }
  c.fixed32.encode(state, TREE)
  c.fixed32.encode(state, manifestHash)
  c.fixed32.encode(state, treeHash)
  c.uint64.encode(state, length)
  c.uint64.encode(state, fork)
  return state.buffer
}

exports.treeSignableCompat = function (hash, length, fork, noHeader) {
  const end = noHeader ? 48 : 80
  const state = { start: 0, end, buffer: b4a.allocUnsafe(end) }
  if (!noHeader) c.fixed32.encode(state, TREE) // ultra legacy mode, kill in future major
  c.fixed32.encode(state, hash)
  c.uint64.encode(state, length)
  c.uint64.encode(state, fork)
  return state.buffer
}
// Export the appropriate version of `quickbit-universal` as the plain import
// may resolve to an older version in some environments
let quickbit = require('quickbit-universal')
if (
  typeof quickbit.findFirst !== 'function' ||
  typeof quickbit.findLast !== 'function' ||
  typeof quickbit.clear !== 'function'
) {
  // This should always load the fallback from the locally installed version
  quickbit = require('quickbit-universal/fallback')
}
exports.quickbit = quickbit
const crypto = require('hypercore-crypto')
const flat = require('flat-tree')
const b4a = require('b4a')
const quickbit = require('quickbit-universal')
const Bitfield = require('./bitfield')

const MAX_BATCH_USED = 4 * 1024 * 1024
const MIN_BATCH_USED = 512 * 1024

// just in its own file as its a bit involved

module.exports = copyPrologue

async function copyPrologue(src, dst) {
  const prologue = dst.header.manifest.prologue

  if (src.length < prologue.length || prologue.length === 0) return

  const stack = []
  const roots = flat.fullRoots(prologue.length * 2)
  const batch = { roots, first: true, last: false, contig: 0, used: 0, tree: [], blocks: [] }

  for (let i = 0; i < roots.length; i++) {
    const node = roots[i]
    batch.tree.push(node)
    stack.push(node)
  }

  let lastPage = -1
  let lastBlock = -1

  for await (const data of src.storage.createBlockStream({
    gte: 0,
    lt: prologue.length,
    reverse: true
  })) {
    if (walkTree(stack, data.index * 2, batch) === false) {
      throw new Error('Missing block or tree node for ' + data.index)
    }

    batch.contig = data.index + 1 === lastBlock ? batch.contig + 1 : 1
    lastBlock = data.index

    const page = getBitfieldPage(data.index)
    batch.blocks.push(data)

    if (lastPage !== page) batch.used += 4096
    batch.used += Math.max(data.value.byteLength, 128) // 128 is just a sanity number to avoid mega batches

    // always safe to partially flush so we do that ondemand to reduce memory usage...
    if ((batch.used >= MIN_BATCH_USED && page !== lastPage) || batch.used >= MAX_BATCH_USED) {
      await flushBatch(prologue, src, dst, batch)
    }

    lastPage = page
  }

  if (lastBlock !== 0) batch.contig = 0

  batch.last = true
  await flushBatch(prologue, src, dst, batch)
}

async function flushBatch(prologue, src, dst, batch) {
  const nodePromises = []

  const srcReader = src.storage.read()
  for (const index of batch.tree) {
    nodePromises.push(srcReader.getTreeNode(index))
  }
  srcReader.tryFlush()

  const nodes = await Promise.all(nodePromises)

  const pagePromises = []
  const dstReader = dst.storage.read()

  const headPromise = batch.first ? dstReader.getHead() : null
  if (headPromise) headPromise.catch(noop)

  let lastPage = -1
  for (const { index } of batch.blocks) {
    const page = getBitfieldPage(index)
    if (page === lastPage) continue
    lastPage = page
    pagePromises.push(dstReader.getBitfieldPage(page))
  }

  dstReader.tryFlush()

  const pages = await Promise.all(pagePromises)
  const head = headPromise === null ? null : await headPromise
  const userData = []

  // reads done!

  if (batch.first) {
    const roots = nodes.slice(0, batch.roots.length)

    for (const node of roots) {
      if (!node) throw new Error('Missing nodes for prologue hash')
    }

    const treeHash = crypto.tree(roots)
    if (!b4a.equals(treeHash, prologue.hash)) throw new Error('Prologue does not match source')
  }

  if (batch.first) {
    for await (const data of src.storage.createUserDataStream()) userData.push(data)
  }

  for (let i = 0; i < pages.length; i++) {
    if (!pages[i]) pages[i] = b4a.alloc(4096)
  }

  const tx = dst.storage.write()

  for (const node of nodes) tx.putTreeNode(node)

  lastPage = -1
  let pageIndex = -1

  for (const { index, value } of batch.blocks) {
    const page = getBitfieldPage(index)

    if (page !== lastPage) {
      lastPage = page
      pageIndex++
      // queue the page now, we mutate it below but its the same ref
      tx.putBitfieldPage(pageIndex, pages[pageIndex])
    }

    const pageBuffer = pages[pageIndex]
    quickbit.set(pageBuffer, getBitfieldOffset(index), true)
    tx.putBlock(index, value)
  }

  for (const { key, value } of userData) {
    tx.putUserData(key, value)
  }

  let upgraded = batch.first && !head
  if (upgraded) {
    tx.setHead(prologueToTree(prologue))
  }

  await tx.flush()

  if (upgraded) {
    const roots = nodes.slice(0, batch.roots.length)
    dst.state.setRoots(roots)
    dst.header.tree = prologueToTree(prologue)
  }

  if (userData.length > 0) {
    dst.header.userData = userData.concat(dst.header.userData)
  }

  if (batch.contig) {
    // TODO: we need to persist this somehow
    dst.header.hints.contiguousLength = batch.contig
  }

  let start = 0
  let length = 0

  // update in memory bitfield
  for (const { index } of batch.blocks) {
    if (start === 0 || start - 1 === index) {
      length++
    } else {
      if (length > 0) signalReplicator(dst, upgraded, start, length)
      upgraded = false
      length = 1
    }

    start = index
    dst.bitfield.set(index, true)
  }

  if (length > 0) signalReplicator(dst, upgraded, start, length)

  // unlink
  batch.tree = []
  batch.blocks = []
  batch.first = false
  batch.used = 0
}

function signalReplicator(core, upgraded, start, length) {
  if (upgraded) {
    core.replicator.cork()
    core.replicator.onhave(start, length, false)
    core.replicator.onupgrade()
    core.replicator.uncork()
  } else {
    core.replicator.onhave(start, length, false)
  }
}

function prologueToTree(prologue) {
  return {
    fork: 0,
    length: prologue.length,
    rootHash: prologue.hash,
    signature: null
  }
}

function getBitfieldPage(index) {
  return Math.floor(index / Bitfield.BITS_PER_PAGE)
}

function getBitfieldOffset(index) {
  return index & (Bitfield.BITS_PER_PAGE - 1)
}

function walkTree(stack, target, batch) {
  while (stack.length > 0) {
    const node = stack.pop()

    if ((node & 1) === 0) {
      if (node === target) return true
      continue
    }

    const ite = flat.iterator(node)
    if (!ite.contains(target)) continue

    while ((ite.index & 1) !== 0) {
      const left = ite.leftChild()
      const right = ite.sibling() // is right child

      batch.tree.push(left, right)

      if (ite.contains(target)) stack.push(left)
      else ite.sibling()
    }

    if (ite.index === target) return true
  }

  return false
}

function noop() {}
const crypto = require('hypercore-crypto')
const b4a = require('b4a')
const unslab = require('unslab')
const z32 = require('z32')
const Mutex = require('./mutex')
const { MerkleTree, ReorgBatch } = require('./merkle-tree')
const BitInterlude = require('./bit-interlude')
const Bitfield = require('./bitfield')
const RemoteBitfield = require('./remote-bitfield')
const {
  BAD_ARGUMENT,
  STORAGE_EMPTY,
  STORAGE_CONFLICT,
  INVALID_SIGNATURE,
  INVALID_CHECKSUM
} = require('hypercore-errors')
const Verifier = require('./verifier')
const audit = require('./audit')
const copyPrologue = require('./copy-prologue')
const SessionState = require('./session-state')
const Replicator = require('./replicator')

module.exports = class Core {
  constructor(db, opts = {}) {
    this.db = db
    this.storage = null
    this.replicator = new Replicator(this, opts)
    this.sessionStates = []
    this.monitors = []
    this.activeSessions = 0
    this.gc = 0 // corestore uses this to main a gc strike pool

    this.id = opts.key ? z32.encode(opts.key) : null
    this.key = opts.key || null
    this.discoveryKey = opts.discoveryKey || (opts.key && crypto.discoveryKey(opts.key)) || null
    this.manifest = null
    this.opening = null
    this.closing = null
    this.exclusive = null

    this.preupdate = null
    this.header = null
    this.compat = false
    this.bitfield = null
    this.verifier = null
    this.truncating = 0
    this.skipBitfield = null
    this.globalCache = opts.globalCache || null
    this.autoClose = opts.autoClose !== false
    this.onidle = noop
    this.ongroupupdate = noop

    this.state = null
    this.opened = false
    this.destroyed = false
    this.closed = false

    this.hintsChanged = false
    this.remoteContiguousLengthChanged = false

    this._bitfield = null
    this._verifies = null
    this._verifiesFlushed = null
    this._legacy = !!opts.legacy
    this._repairMode = false

    this.opening = this._open(opts)
    this.opening.catch(noop)
  }

  static setRecoveryPeers(peers) {
    SessionState.RECOVERY_PEERS = peers
  }

  ready() {
    return this.opening
  }

  addMonitor(s) {
    if (s._monitorIndex >= 0) return
    s._monitorIndex = this.monitors.push(s) - 1
  }

  removeMonitor(s) {
    if (s._monitorIndex < 0) return
    const head = this.monitors.pop()
    if (head !== s) this.monitors[(head._monitorIndex = s._monitorIndex)] = head
    s._monitorIndex = -1
  }

  emitRemoteContiguousLength() {
    if (!this.remoteContiguousLengthChanged) return
    this.remoteContiguousLengthChanged = false

    const length = this.header.hints.remoteContiguousLength

    for (let i = this.monitors.length - 1; i >= 0; i--) {
      this.monitors[i].emit('remote-contiguous-length', length)
    }
  }

  emitManifest() {
    for (let i = this.monitors.length - 1; i >= 0; i--) {
      this.monitors[i].emit('manifest')
    }
  }

  createUserDataStream(opts, session = this.state) {
    return session.storage.createUserDataStream(opts)
  }

  allSessions() {
    const sessions = []
    for (const state of this.sessionStates) {
      if (state.sessions.length) sessions.push(...state.sessions)
    }
    return sessions
  }

  hasSession() {
    return this.activeSessions !== 0
  }

  compact() {
    const compacting = []
    for (const s of this.sessionStates) {
      compacting.push(s.storage.compact())
    }
    return Promise.all(compacting)
  }

  checkIfIdle() {
    if (!this.opened || this.destroyed === true || this.hasSession() === true) return
    if (this.replicator.idle() === false) return
    if (this.state === null || this.state.mutex.idle() === false) return
    this.onidle()
  }

  async lockExclusive() {
    if (this.exclusive === null) this.exclusive = new Mutex()
    await this.exclusive.lock()
  }

  unlockExclusive() {
    if (this.exclusive !== null) this.exclusive.unlock()
  }

  async _open(opts) {
    try {
      await this._tryOpen(opts)
    } catch (err) {
      this.onidle()
      throw err
    }

    this.opened = true
  }

  async _tryOpen(opts) {
    if (opts.preopen) await opts.preopen // just a hook to allow exclusive access here...

    let storage = await this.db.resumeCore(this.discoveryKey)

    let overwrite = opts.overwrite === true

    const force = opts.force === true
    const createIfMissing = opts.createIfMissing !== false
    // kill this flag soon
    const legacy = !!opts.legacy

    // default to true for now if no manifest is provided
    let compat = opts.compat === true || (opts.compat !== false && !opts.manifest)

    let header = storage ? parseHeader(await getCoreInfo(storage)) : null

    const hadManifest = !!header && !!header.manifest && !!header.key
    const hadKeyPair = !!header && !!header.keyPair

    if (force && opts.key && header && !b4a.equals(header.key, opts.key)) {
      overwrite = true
    }

    if (!header && opts.discoveryKey && !(opts.key || opts.manifest)) {
      throw STORAGE_EMPTY('No Hypercore is stored here', this.discoveryKey)
    }

    if (!header || overwrite) {
      if (!createIfMissing) {
        throw STORAGE_EMPTY('No Hypercore is stored here', this.discoveryKey)
      }

      if (compat) {
        if (opts.key && opts.keyPair && !b4a.equals(opts.key, opts.keyPair.publicKey)) {
          throw BAD_ARGUMENT('Key must match publicKey when in compat mode', this.discoveryKey)
        }
      }

      const keyPair = opts.keyPair || (opts.key ? null : crypto.keyPair())

      const defaultManifest =
        !opts.manifest &&
        (!!opts.compat || !opts.key || !!(keyPair && b4a.equals(opts.key, keyPair.publicKey)))
      const manifest = defaultManifest
        ? Verifier.defaultSignerManifest(opts.key || keyPair.publicKey)
        : Verifier.createManifest(opts.manifest)

      header = {
        key: opts.key || (compat ? manifest.signers[0].publicKey : Verifier.manifestHash(manifest)),
        manifest,
        keyPair: keyPair
          ? { publicKey: keyPair.publicKey, secretKey: keyPair.secretKey || null }
          : null,
        frozen: false,
        tree: {
          fork: 0,
          length: 0,
          rootHash: null,
          signature: null,
          timestamp: 0
        },
        group: null,
        hints: {
          reorgs: [],
          contiguousLength: 0,
          remoteContiguousLength: 0,
          recovering: 0
        }
      }

      const discoveryKey = opts.discoveryKey || crypto.discoveryKey(header.key)

      storage = await this.db.createCore({
        key: header.key,
        manifest,
        keyPair,
        frozen: false,
        discoveryKey,
        userData: opts.userData || [],
        alias: opts.alias || null
      })
    }

    // unslab the long lived buffers to avoid keeping the slab alive
    header.key = unslab(header.key)

    if (header.tree) {
      header.tree.rootHash = unslab(header.tree.rootHash)
      header.tree.signature = unslab(header.tree.signature)
    }

    if (header.keyPair) {
      header.keyPair.publicKey = unslab(header.keyPair.publicKey)
      header.keyPair.secretKey = unslab(header.keyPair.secretKey)
    }

    if (header.keyPair) {
      header.keyPair.publicKey = unslab(header.keyPair.publicKey)
      header.keyPair.secretKey = unslab(header.keyPair.secretKey)
    }

    if (opts.manifest) {
      // if we provide a manifest and no key, verify that the stored key is the same
      if (
        !opts.key &&
        !Verifier.isValidManifest(header.key, Verifier.createManifest(opts.manifest))
      ) {
        throw STORAGE_CONFLICT('Manifest does not hash to provided key', this.discoveryKey)
      }

      if (!header.manifest) header.manifest = opts.manifest
    }

    if (opts.key && !b4a.equals(header.key, opts.key)) {
      throw STORAGE_CONFLICT('Another Hypercore is stored here', this.discoveryKey)
    }

    // if we signalled compat, but already now this core isn't disable it
    if (compat && header.manifest && !Verifier.isCompat(header.key, header.manifest)) {
      compat = false
    } else if (!compat && header.manifest && Verifier.isCompat(header.key, header.manifest)) {
      compat = true
    }

    const prologue = header.manifest ? header.manifest.prologue : null

    const bitfield = await Bitfield.open(storage, header.tree.length)

    const treeInfo = {
      fork: header.tree.fork,
      length: header.tree.length,
      signature: header.tree.signature,
      roots: await maybeGetRootsFromStorage(storage, header.tree.length),
      prologue
    }

    this._repairMode = !treeInfo.roots.length && treeInfo.length && !overwrite
    // Set push only mode if in repair mode
    if (this._repairMode) {
      this.replicator.setPushOnly(true)
    }

    if (opts.group) {
      if (!header.group) header.group = await this.db.createGroup(opts.group)
      else if (!b4a.equals(header.group.key, opts.group)) {
        throw STORAGE_CONFLICT(
          'Core is already register to group: ' + b4a.toString(header.group.key, 'hex')
        )
      }

      const tx = storage.write()
      tx.setGroup(header.group)
      await tx.flush()
    }

    if (overwrite) {
      const tx = storage.write()
      tx.deleteTreeNodeRange(0, -1)
      tx.deleteBlockRange(0, -1)
      bitfield.clear(tx)
      await tx.flush()
    }

    const len = bitfield.findFirst(false, header.hints.contiguousLength)
    if (header.hints.contiguousLength !== len && !storage.readOnly) {
      header.hints.contiguousLength = len
      const tx = storage.write()
      tx.setHints(header.hints)
      await tx.flush()
    }

    // to unslab
    if (header.manifest) {
      header.manifest = Verifier.createManifest(header.manifest)
      if (!hadManifest || (header.keyPair && !hadKeyPair)) {
        const tx = storage.write()
        tx.setAuth({
          key: header.key,
          discoveryKey: crypto.discoveryKey(header.key),
          manifest: header.manifest,
          keyPair: header.keyPair
        })
        await tx.flush()
      }
    }

    const verifier = header.manifest
      ? new Verifier(header.key, header.manifest, { crypto, legacy })
      : null

    this.storage = storage
    this.header = header
    this.compat = compat
    this.bitfield = bitfield
    this.verifier = verifier
    this.state = new SessionState(this, null, storage, treeInfo, null)

    if (this.key === null) this.key = this.header.key
    if (this.discoveryKey === null) this.discoveryKey = crypto.discoveryKey(this.key)
    if (this.id === null) this.id = z32.encode(this.key)
    if (this.manifest === null) this.manifest = this.header.manifest
  }

  async audit(opts) {
    await this.state.mutex.lock()

    try {
      return await audit(this, opts)
    } finally {
      this.state._unlock()
    }
  }

  async setGroup(group) {
    await this.state.mutex.lock()
    try {
      if (!this.header.group) this.header.group = await this.db.createGroup(group)
      else if (!b4a.equals(this.header.group.key, group)) {
        throw STORAGE_CONFLICT(
          'Core is already register to group: ' + b4a.toString(this.header.group.key, 'hex')
        )
      }

      const tx = this.storage.write()
      tx.setGroup(this.header.group)
      await tx.flush()
    } finally {
      this.state.mutex.unlock()
    }
  }

  async setManifest(manifest) {
    await this.state.mutex.lock()

    try {
      if (manifest && this.header.manifest === null) {
        if (!Verifier.isValidManifest(this.header.key, manifest)) {
          throw INVALID_CHECKSUM('Manifest hash does not match', this.discoveryKey)
        }

        const tx = this.state.createWriteBatch()
        this._setManifest(tx, Verifier.createManifest(manifest), null)
        await this.state.flush()
      }
    } finally {
      this.state._unlock()
    }
  }

  _setManifest(tx, manifest, keyPair) {
    if (!manifest && b4a.equals(keyPair.publicKey, this.header.key)) {
      manifest = Verifier.defaultSignerManifest(this.header.key)
    }
    if (!manifest) return

    const verifier = new Verifier(this.header.key, manifest, { legacy: this._legacy })

    if (verifier.prologue) this.state.prologue = Object.assign({}, verifier.prologue)

    this.manifest = this.header.manifest = manifest

    tx.setAuth({
      key: this.header.key,
      discoveryKey: this.discoveryKey,
      manifest,
      keyPair: this.header.keyPair
      // TODO: encryptionKey?
    })

    this.compat = verifier.compat
    this.verifier = verifier

    this.replicator.onupgrade()
    this.emitManifest()
  }

  async copyPrologue(src) {
    await this.state.mutex.lock()

    try {
      await src.mutex.lock()
    } catch (err) {
      this.state.mutex.unlock()
      throw err
    }

    try {
      await copyPrologue(src, this)
    } finally {
      src.mutex.unlock()
      this.state.mutex.unlock()
      this.checkIfIdle()
    }
  }

  flushed() {
    return this.state.flushed()
  }

  async _validateCommit(state, treeLength) {
    if (this.state.length > state.length) {
      return false // TODO: partial commit and truncation possible in the future
    }

    if (this.state.length > treeLength) {
      for (const root of this.state.roots) {
        const batchRoot = await MerkleTree.get(state, root.index)
        if (batchRoot.size !== root.size || !b4a.equals(batchRoot.hash, root.hash)) {
          return false
        }
      }
    }

    if (this.verifier === null) {
      return false // easier to assert than upsert
    }

    return true
  }

  _verifyBatchUpgrade(batch, manifest) {
    if (!this.header.manifest) {
      // compat, drop at some point
      if (!manifest) manifest = Verifier.defaultSignerManifest(this.header.key)

      if (
        !manifest ||
        !(
          Verifier.isValidManifest(this.header.key, manifest) ||
          Verifier.isCompat(this.header.key, manifest)
        )
      ) {
        throw INVALID_SIGNATURE('Proof contains an invalid manifest', this.discoveryKey) // TODO: proper error type
      }
    }

    const verifier =
      this.verifier ||
      new Verifier(this.header.key, Verifier.createManifest(manifest), { legacy: this._legacy })

    if (!verifier.verify(batch, batch.signature)) {
      throw INVALID_SIGNATURE('Proof contains an invalid signature', this.discoveryKey)
    }

    return manifest
  }

  async _verifyExclusive({ batch, bitfield, value, manifest }) {
    manifest = this._verifyBatchUpgrade(batch, manifest)

    if (
      !(await this.state._verifyBlock(
        batch,
        bitfield,
        value,
        this.header.manifest ? null : manifest
      ))
    ) {
      return false
    }

    if (!batch.upgraded && bitfield) {
      this.replicator.onhave(bitfield.start, bitfield.length, bitfield.drop)
    }

    return true
  }

  async _verifyShared() {
    if (!this._verifies.length) return false

    await this.state.mutex.lock()

    const tx = this.state.createWriteBatch()

    const verifies = this._verifies
    this._verifies = null
    this._verified = null

    try {
      for (const { batch, bitfield, value } of verifies) {
        if (!batch.commitable()) continue

        if (bitfield) {
          tx.putBlock(bitfield.start, value)
        }
      }

      const bits = new BitInterlude()

      for (let i = 0; i < verifies.length; i++) {
        const { batch, bitfield, manifest } = verifies[i]

        if (!batch.commitable()) {
          verifies[i] = null // signal that we cannot commit this one
          continue
        }

        if (bitfield) {
          bits.setRange(bitfield.start, bitfield.start + 1, true)
        }

        // if we got a manifest AND its strictly a non compat one, lets store it
        if (manifest && this.header.manifest === null) {
          if (!Verifier.isValidManifest(this.header.key, manifest)) {
            throw INVALID_CHECKSUM('Manifest hash does not match', this.discoveryKey)
          }
          this._setManifest(tx, manifest, null)
        }

        if (batch.commitable()) batch.commit(tx)
      }

      const ranges = bits.flush(tx, this.bitfield)

      await this.state.flush()

      for (const { start, end, value } of ranges) {
        this._setBitfieldRanges(start, end, value)
      }

      for (let i = 0; i < verifies.length; i++) {
        const bitfield = verifies[i] && verifies[i].bitfield
        if (bitfield) {
          this.updateContiguousLength(bitfield)
          this.replicator.onhave(bitfield.start, bitfield.length, bitfield.drop)
        }
      }

      if (this.hintsChanged) await this.flushHints()
    } finally {
      this.state._clearActiveBatch()
      this.state.mutex.unlock()
    }

    return verifies[0] !== null
  }

  async flushHints() {
    if (!this.hintsChanged) return
    this.hintsChanged = false // we unset this immediately as a "debounce"

    const tx = this.state.storage.write()

    tx.setHints({
      contiguousLength: this.header.hints.contiguousLength,
      remoteContiguousLength: this.header.hints.remoteContiguousLength,
      recovering: this.header.hints.recovering
    })

    await tx.flush()
  }

  async checkConflict(proof, from) {
    if (this.state.length < proof.upgrade.length || proof.fork !== this.state.fork) {
      // out of date this proof - ignore for now
      return false
    }

    // sanity check -> no manifest, no way to verify
    if (!this.header.manifest) {
      return false
    }

    const batch = MerkleTree.verifyFullyRemote(this.state, proof)

    try {
      this._verifyBatchUpgrade(batch, proof.manifest)
    } catch {
      return true
    }

    const roots = await maybeGetRootsFromStorage(this.storage, proof.upgrade.length)
    const remoteTreeHash = crypto.tree(proof.upgrade.nodes)
    const localTreeHash = crypto.tree(roots)

    try {
      const rx = this.state.storage.read()
      const treeProofPromise = MerkleTree.proof(this.state, rx, {
        block: null,
        hash: null,
        seek: null,
        upgrade: {
          start: 0,
          length: proof.upgrade.length
        }
      })

      rx.tryFlush()

      const treeProof = await treeProofPromise

      const verifyBatch = MerkleTree.verifyFullyRemote(this.state, await treeProof.settle())
      this._verifyBatchUpgrade(verifyBatch, this.header.manifest)
    } catch (err) {
      if (err.code !== 'INVALID_OPERATION') return true

      return !(await this._repairTreeNodes(proof))
    }

    // both proofs are valid, now check if they forked
    if (b4a.equals(localTreeHash, remoteTreeHash)) return false

    await this.state.mutex.lock()

    try {
      const tx = this.state.createWriteBatch()

      this.header.frozen = true

      tx.setAuth({
        key: this.header.key,
        discoveryKey: this.discoveryKey,
        manifest: this.header.manifest,
        keyPair: this.header.keyPair,
        frozen: true
      })

      await this.state.flush()
    } finally {
      this.state.mutex.unlock()
    }

    // tmp log so we can see these
    const id = b4a.toString(this.discoveryKey, 'hex')
    console.log(
      '[hypercore] conflict detected in ' +
        id +
        ' (writable=' +
        !!this.header.keyPair +
        ',quorum=' +
        this.header.manifest.quorum +
        ')'
    )
    await this._onconflict(proof)
    return true
  }

  async _repairTreeNodes(proof) {
    if (!this._repairMode) return false

    await this.state.mutex.lock()

    for (let i = this.monitors.length - 1; i >= 0; i--) {
      this.monitors[i].emit('repairing', proof)
    }

    try {
      const batch = MerkleTree.verifyFullyRemote(this.state, proof)
      this._verifyBatchUpgrade(batch, proof.manifest)
    } catch {
      this.state.mutex.unlock()
      for (let i = this.monitors.length - 1; i >= 0; i--) {
        this.monitors[i].emit('repair-failed')
      }
      return false
    }

    // Attempt to repair local merkle tree with remote roots
    const atom = this.storage.createAtom()
    const atomized = this.storage.atomize(atom)
    const tx = atomized.write()
    for (const node of proof.upgrade.nodes) {
      tx.putTreeNode(node)
    }
    await tx.flush()

    // Try local proof again
    try {
      const rx = atomized.read()
      const treeProofPromise = MerkleTree.proof(this.state, rx, {
        block: null,
        hash: null,
        seek: null,
        upgrade: {
          start: 0,
          length: proof.upgrade.length
        }
      })

      rx.tryFlush()

      const treeProof = await treeProofPromise

      const verifyBatch = MerkleTree.verifyFullyRemote(this.state, await treeProof.settle())
      this._verifyBatchUpgrade(verifyBatch, this.header.manifest)
    } catch (err) {
      this.state.mutex.unlock()
      for (let i = this.monitors.length - 1; i >= 0; i--) {
        this.monitors[i].emit('repair-failed')
      }
      return false
    }

    await atom.flush()

    for (let i = this.monitors.length - 1; i >= 0; i--) {
      this.monitors[i].emit('repaired', proof)
    }
    this.replicator.setPushOnly(false)
    this.state.mutex.unlock()
    return true
  }

  async verifyReorg(proof) {
    const batch = new ReorgBatch(this.state)
    await MerkleTree.reorg(this.state, proof, batch)
    const manifest = this._verifyBatchUpgrade(batch, proof.manifest)

    if (manifest && !this.header.manifest) {
      await this.state.mutex.lock()
      try {
        if (manifest && this.header.manifest === null) {
          const tx = this.state.createWriteBatch()
          this._setManifest(tx, Verifier.createManifest(manifest), null)
          await this.state.flush()
        }
      } finally {
        this.state._unlock()
      }
    }

    return batch
  }

  async verify(proof, from) {
    // We cannot apply "other forks" atm.
    // We should probably still try and they are likely super similar for non upgrades
    // but this is easy atm (and the above layer will just retry)
    if (proof.fork !== this.state.fork) return false

    const batch = await MerkleTree.verify(this.state, proof)

    if (batch.upgraded && batch.length <= this.state.length) {
      await batch.downgrade()
    }

    if (!batch.commitable()) {
      return false
    }

    const value = (proof.block && proof.block.value) || null
    const op = {
      batch,
      bitfield: value && { drop: false, start: proof.block.index, length: 1 },
      value,
      manifest: proof.manifest,
      from
    }

    if (batch.upgraded) {
      return this._verifyExclusive(op)
    }

    if (this._verifies !== null) {
      const verifies = this._verifies
      const i = verifies.push(op)
      await this._verified
      return verifies[i] !== null
    }

    this._verifies = [op]
    this._verified = this._verifyShared()

    return this._verified
  }

  async reorg(batch) {
    if (!batch.commitable()) return false

    this.truncating++

    try {
      await this.state.reorg(batch)
    } finally {
      this.truncating--
    }

    return true
  }

  openSkipBitfield() {
    if (this.skipBitfield !== null) return this.skipBitfield
    this.skipBitfield = new RemoteBitfield()
    const buf = this.bitfield.toBuffer(this.state.length)
    const bitfield = new Uint32Array(buf.buffer, buf.byteOffset, buf.byteLength / 4)
    this.skipBitfield.insert(0, bitfield)
    return this.skipBitfield
  }

  _setBitfieldRanges(start, end, value) {
    this.bitfield.setRange(start, end, value)
    if (this.skipBitfield !== null) this.skipBitfield.setRange(start, end, value)
  }

  close() {
    if (!this.closing) this.closing = this._close()
    return this.closing
  }

  updateContiguousLength(bitfield) {
    const contig = updateContigBatch(this.header.hints.contiguousLength, bitfield, this.bitfield)

    if (contig.length !== -1 && contig.length !== this.header.hints.contiguousLength) {
      this.header.hints.contiguousLength = contig.length
      this.hintsChanged = true
    }
  }

  updateRemoteContiguousLength(length) {
    this.header.hints.remoteContiguousLength = length
    this.hintsChanged = true
    this.remoteContiguousLengthChanged = true
  }

  onappend(tree, bitfield) {
    this.header.tree = tree

    if (!bitfield) {
      this.replicator.onupgrade()
      return
    }

    this.replicator.cork()

    const { start, length, drop } = bitfield

    this._setBitfieldRanges(start, start + length, true)
    this.updateContiguousLength({ start, length, drop: false })

    this.replicator.onupgrade()
    this.replicator.onhave(start, length, drop)
    this.replicator.uncork()
  }

  ontruncate(tree, { start, length }) {
    if (tree) this.header.tree = tree

    this.replicator.cork()

    this.replicator.ontruncate(start, length)
    this.replicator.onhave(start, length, true)
    this.replicator.onupgrade()
    this.replicator.uncork()

    for (const sessionState of this.sessionStates) {
      if (start < sessionState.snapshotCompatLength) sessionState.snapshotCompatLength = start
    }

    this._setBitfieldRanges(start, start + length, false)
    this.updateContiguousLength({ start, length, drop: true })
  }

  async _onconflict(proof) {
    await this.replicator.onconflict()

    for (let i = this.monitors.length - 1; i >= 0; i--) {
      const s = this.monitors[i]
      s.emit('conflict', proof.upgrade.length, proof.fork, proof)
    }

    const err = new Error('Two conflicting signatures exist for length ' + proof.upgrade.length)
    await this.closeAllSessions(err)
  }

  async closeAllSessions(err) {
    // this.sessions modifies itself when a session closes
    // This way we ensure we indeed iterate over all sessions
    const sessions = this.allSessions()

    const all = []
    for (const s of sessions) all.push(s.close({ error: err, force: false })) // force false or else infinite recursion
    await Promise.allSettled(all)
  }

  async destroy() {
    if (this.destroyed === true) return
    this.destroyed = true

    if (this.hasSession() === true) throw new Error('Cannot destroy while sessions are open')

    const weakSessions = this.allSessions()

    if (this.replicator) this.replicator.destroy()
    if (this.state) await this.state.close()

    // close all pending weak sessions...
    for (const s of weakSessions) s.close().catch(noop)
  }

  async _close() {
    if (this.opened === false) await this.opening
    if (this.hasSession() === true) throw new Error('Cannot close while sessions are open')

    if (this.replicator) await this.replicator.close()

    await this.destroy()
    if (this.autoClose) await this.storage.store.close()

    this.closed = true
  }
}

function updateContigBatch(start, upd, bitfield) {
  const end = upd.start + upd.length

  let c = start

  if (upd.drop) {
    // If we dropped a block in the current contig range, "downgrade" it
    if (c > upd.start) {
      c = upd.start
    }
  } else {
    if (c <= end && c >= upd.start) {
      c = end
      while (bitfield.get(c)) c++
    }
  }

  if (c === start) {
    return {
      length: -1
    }
  }

  if (c > start) {
    return {
      length: c
    }
  }

  return {
    length: c
  }
}

function getDefaultTree() {
  return {
    fork: 0,
    length: 0,
    rootHash: null,
    signature: null,
    timestamp: 0
  }
}

function parseHeader(info) {
  if (!info) return null

  return {
    key: info.key,
    manifest: info.manifest,
    external: null,
    keyPair: info.keyPair,
    tree: info.head || getDefaultTree(),
    group: info.group,
    hints: {
      reorgs: [],
      contiguousLength: info.hints ? info.hints.contiguousLength : 0,
      remoteContiguousLength: info.hints ? info.hints.remoteContiguousLength : 0,
      recovering: info.hints ? info.hints.recovering : 0
    }
  }
}

async function maybeGetRootsFromStorage(storage, length) {
  try {
    return length ? await MerkleTree.getRootsFromStorage(storage, length) : []
  } catch (err) {
    if (err.code !== 'INVALID_OPERATION') throw err
    // If INVALID_OPERATION, a root is likely missing so load empty roots to try to recover
    return []
  }
}

function noop() {}

async function getCoreInfo(storage) {
  const r = storage.read()

  const auth = r.getAuth()
  const head = r.getHead()
  const hints = r.getHints()
  const group = r.getGroup()

  r.tryFlush()

  const [authInfo, headInfo, hintsInfo, groupInfo] = await Promise.all([auth, head, hints, group])
  return {
    ...authInfo,
    head: headInfo,
    hints: hintsInfo,
    group: groupInfo
  }
}
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const b4a = require('b4a')
const { DEFAULT_ENCRYPTION } = require('./caps')

const nonce = b4a.alloc(sodium.crypto_stream_NONCEBYTES)

module.exports = class DefaultEncryption {
  static PADDING = 8

  constructor(encryptionKey, hypercoreKey, opts = {}) {
    this.key = encryptionKey
    this.compat = opts.compat === true

    const keys = DefaultEncryption.deriveKeys(encryptionKey, hypercoreKey, opts)

    this.blockKey = keys.block
    this.blindingKey = keys.blinding
  }

  static deriveKeys(encryptionKey, hypercoreKey, { block = false, compat = false } = {}) {
    const subKeys = b4a.alloc(2 * sodium.crypto_stream_KEYBYTES)

    const blockKey = block ? encryptionKey : subKeys.subarray(0, sodium.crypto_stream_KEYBYTES)
    const blindingKey = subKeys.subarray(sodium.crypto_stream_KEYBYTES)

    if (!block) {
      if (compat) {
        sodium.crypto_generichash_batch(blockKey, [encryptionKey], hypercoreKey)
      } else {
        sodium.crypto_generichash_batch(blockKey, [DEFAULT_ENCRYPTION, hypercoreKey, encryptionKey])
      }
    }

    sodium.crypto_generichash(blindingKey, blockKey)

    return {
      blinding: blindingKey,
      block: blockKey
    }
  }

  static blockEncryptionKey(hypercoreKey, encryptionKey) {
    const blockKey = b4a.alloc(sodium.crypto_stream_KEYBYTES)
    sodium.crypto_generichash_batch(blockKey, [DEFAULT_ENCRYPTION, hypercoreKey, encryptionKey])
    return blockKey
  }

  static encrypt(index, block, fork, blockKey, blindingKey) {
    const padding = block.subarray(0, DefaultEncryption.PADDING)
    block = block.subarray(DefaultEncryption.PADDING)

    c.uint64.encode({ start: 0, end: 8, buffer: padding }, fork)
    c.uint64.encode({ start: 0, end: 8, buffer: nonce }, index)

    // Zero out any previous padding.
    nonce.fill(0, 8, 8 + padding.byteLength)

    // Blind the fork ID, possibly risking reusing the nonce on a reorg of the
    // Hypercore. This is fine as the blinding is best-effort and the latest
    // fork ID shared on replication anyway.
    sodium.crypto_stream_xor(padding, padding, nonce, blindingKey)

    nonce.set(padding, 8)

    // The combination of a (blinded) fork ID and a block index is unique for a
    // given Hypercore and is therefore a valid nonce for encrypting the block.
    sodium.crypto_stream_xor(block, block, nonce, blockKey)
  }

  static decrypt(index, block, blockKey) {
    const padding = block.subarray(0, DefaultEncryption.PADDING)
    block = block.subarray(DefaultEncryption.PADDING)

    c.uint64.encode({ start: 0, end: 8, buffer: nonce }, index)

    nonce.set(padding, 8)

    // Decrypt the block using the blinded fork ID.
    sodium.crypto_stream_xor(block, block, nonce, blockKey)
  }

  encrypt(index, block, fork, core) {
    if (core.compat !== this.compat) this._reload(core)
    return DefaultEncryption.encrypt(index, block, fork, this.blockKey, this.blindingKey)
  }

  decrypt(index, block, core) {
    if (core.compat !== this.compat) this._reload(core)
    return DefaultEncryption.decrypt(index, block, this.blockKey)
  }

  padding() {
    return DefaultEncryption.PADDING
  }

  _reload(core) {
    const block = b4a.equals(this.key, this.blockKey)
    const keys = DefaultEncryption.deriveKeys(this.key, core.key, { block, compat: core.compat })

    this.blockKey = keys.blockKey
    this.blindingKey = keys.blindingKey
  }
}
module.exports = class Download {
  constructor(session, range) {
    this.session = session
    this.range = range
    this.request = null
    this.opened = false
    this.opening = this._open()
    this.opening.catch(noop)
  }

  ready() {
    return this.opening
  }

  async _open() {
    if (this.session.opened === false) await this.session.opening
    this._download()
    this.opened = true
  }

  async done() {
    await this.ready()

    try {
      return await this.request.promise
    } catch (err) {
      if (isSessionMoved(err)) return this._download()
      throw err
    }
  }

  _download() {
    const activeRequests = (this.range && this.range.activeRequests) || this.session.activeRequests
    this.request = this.session.core.replicator.addRange(activeRequests, this.range)
    this.request.promise.catch(noop)
    return this.request.promise
  }

  /**
   * Deprecated. Use `range.done()`.
   */
  downloaded() {
    return this.done()
  }

  destroy() {
    this._destroyBackground().catch(noop)
  }

  async _destroyBackground() {
    if (this.opened === false) await this.ready()
    if (this.request.context) this.request.context.detach(this.request)
  }
}

function noop() {}

function isSessionMoved(err) {
  return err.code === 'SESSION_MOVED'
}
module.exports = {
  SMALL_WANTS: 1
}
// this helper is for fully remote proofs, is like in a push notification where no other context exists

const { MerkleTree } = require('./merkle-tree.js')
const messages = require('./messages.js')
const b4a = require('b4a')
const c = require('compact-encoding')
const crypto = require('hypercore-crypto')
const flat = require('flat-tree')

class SlimSession {
  constructor(storage, auth, head, roots) {
    this.fork = head ? head.fork : 0
    this.roots = roots
    this.length = head ? head.length : 0
    this.signature = head ? head.signature : null
    this.ancestors = this.length
    this.byteLength = 0
    this.prologue = auth.manifest.prologue
    this.storage = storage

    for (let i = 0; i < roots.length; i++) this.byteLength += roots[i].size
  }
}

module.exports = { verify, proof }

async function verify(storage, buffer, { referrer = null } = {}) {
  const state = { buffer, start: 0, end: buffer.byteLength }

  const discoveryKey = c.fixed32.decode(state)
  const proof = messages.wire.data.decode(state)

  const result = {
    key: null,
    discoveryKey,
    newer: true,
    length: 0,
    proof,
    block: null
  }

  const core = await storage.resumeCore(discoveryKey)
  if (core === null) return null

  let rx = core.read()
  const authPromise = rx.getAuth()
  const headPromise = rx.getHead()
  const referrerPromise = rx.getUserData('referrer')

  rx.tryFlush()

  const [auth, head, ref] = await Promise.all([authPromise, headPromise, referrerPromise])

  if (auth === null) return null

  if (referrer && (!ref || !b4a.equals(ref, referrer))) return null

  rx = core.read()

  const rootPromises = []

  for (const index of flat.fullRoots(head ? 2 * head.length : 0)) {
    rootPromises.push(rx.getTreeNode(index))
  }

  rx.tryFlush()

  let roots = await Promise.all(rootPromises)
  if (roots.some(isNull)) roots = []

  const length = head ? head.length : 0

  if (!auth.manifest || !auth.manifest.signers.length) return null

  const batch = await MerkleTree.verifyFullyRemote(new SlimSession(core, auth, head, roots), proof)
  const publicKey = auth.manifest.signers[0].publicKey

  let signable = null
  let signature = null

  if (auth.manifest.version === 0) {
    signable = batch.signable(auth.manifest.signers[0].namespace)
    signature = batch.signature
  } else {
    if (batch.signature[0] !== 1) return null
    if (batch.signature[1] !== 0) return null

    signable = batch.signable(auth.key)
    signature = batch.signature.subarray(2, 66)
  }

  if (!crypto.verify(signable, signature, publicKey)) {
    return null
  }

  result.key = auth.key
  result.discoveryKey = discoveryKey
  result.newer = batch.length > length
  result.length = batch.length
  result.block = proof.block

  return result
}

async function proof(sender, { index, block = null, upgrade = null } = {}) {
  const proof = await sender.proof({
    block: block ? { index, nodes: 0 } : null,
    upgrade: upgrade ? upgrade : { start: 0, length: sender.length }
  })

  if (block) proof.block.value = block
  proof.manifest = sender.core.header.manifest

  const state = { buffer: null, start: 0, end: 0 }
  const data = { request: 0, ...proof }

  c.fixed32.preencode(state, sender.discoveryKey)
  messages.wire.data.preencode(state, data)

  state.buffer = b4a.allocUnsafe(state.end)

  c.fixed32.encode(state, sender.discoveryKey)
  messages.wire.data.encode(state, data)

  return state.buffer
}

function isNull(x) {
  return x === null
}
const TICKS = 16

module.exports = class HotswapQueue {
  constructor() {
    this.priorities = [[], [], []]
  }

  *pick(peer) {
    for (let i = 0; i < this.priorities.length; i++) {
      // try first one more than second one etc etc
      let ticks = (this.priorities.length - i) * TICKS
      const queue = this.priorities[i]

      for (let j = 0; j < queue.length; j++) {
        const r = j + Math.floor(Math.random() * queue.length - j)
        const a = queue[j]
        const b = queue[r]

        if (r !== j) {
          queue[(b.hotswap.index = j)] = b
          queue[(a.hotswap.index = r)] = a
        }

        if (hasInflight(b, peer)) continue

        yield b

        if (--ticks <= 0) break
      }
    }
  }

  add(block) {
    if (block.hotswap !== null) this.remove(block)
    if (block.inflight.length === 0 || block.inflight.length >= 3) return

    // TODO: also use other stuff to determine queue prio
    const queue = this.priorities[block.inflight.length - 1]

    const index = queue.push(block) - 1
    block.hotswap = { ref: this, queue, index }
  }

  remove(block) {
    const hotswap = block.hotswap
    if (hotswap === null) return

    block.hotswap = null
    const head = hotswap.queue.pop()
    if (head === block) return
    hotswap.queue[(head.hotswap.index = hotswap.index)] = head
  }
}

function hasInflight(block, peer) {
  for (let j = 0; j < block.inflight.length; j++) {
    if (block.inflight[j].peer === peer) return true
  }
  return false
}
module.exports = class Info {
  constructor(opts = {}) {
    this.key = opts.key
    this.discoveryKey = opts.discoveryKey
    this.length = opts.length || 0
    this.contiguousLength = opts.contiguousLength || 0
    this.byteLength = opts.byteLength || 0
    this.fork = opts.fork || 0
    this.padding = opts.padding || 0
    this.storage = opts.storage || null
  }

  static async from(session, opts = {}) {
    return new Info({
      key: session.key,
      discoveryKey: session.discoveryKey,
      length: session.length,
      contiguousLength: session.contiguousLength,
      byteLength: session.byteLength,
      fork: session.fork,
      padding: session.padding,
      storage: opts.storage ? await this.storage(session) : null
    })
  }

  static async storage(session) {
    const { oplog, tree, blocks, bitfield } = session.core
    try {
      return {
        oplog: await Info.bytesUsed(oplog.storage),
        tree: await Info.bytesUsed(tree.storage),
        blocks: await Info.bytesUsed(blocks.storage),
        bitfield: await Info.bytesUsed(bitfield.storage)
      }
    } catch {
      return null
    }
  }

  static bytesUsed(file) {
    return new Promise((resolve, reject) => {
      file.stat((err, st) => {
        if (err) {
          resolve(0) // prob just file not found (TODO, improve)
        } else if (typeof st.blocks !== 'number') {
          reject(new Error('cannot determine bytes used'))
        } else {
          resolve(st.blocks * 512)
        }
      })
    })
  }
}
const b4a = require('b4a')

module.exports = function (core, depth, opts) {
  let indent = ''
  if (typeof opts.indentationLvl === 'number') {
    while (indent.length < opts.indentationLvl) indent += ' '
  }

  let peers = ''
  const min = Math.min(core.peers.length, 5)

  for (let i = 0; i < min; i++) {
    const peer = core.peers[i]

    peers += `${indent}    Peer(\n`
    peers += `${indent}      remotePublicKey: ${opts.stylize(toHex(peer.remotePublicKey), 'string')}\n`
    peers += `${indent}      remoteLength: ${opts.stylize(peer.remoteLength, 'number')}\n`
    peers += `${indent}      remoteFork: ${opts.stylize(peer.remoteFork, 'number')}\n`
    peers += `${indent}      remoteCanUpgrade: ${opts.stylize(peer.remoteCanUpgrade, 'boolean')}\n`
    peers += `${indent}    )\n`
  }

  if (core.peers.length > 5) {
    peers += `${indent}  ... and ${core.peers.length - 5} more\n`
  }

  if (peers) peers = `[\n${peers}${indent}  ]`
  else peers = `[ ${opts.stylize(0, 'number')} ]`

  return (
    `${core.constructor.name}(\n` +
    `${indent}  id: ${opts.stylize(core.id, 'string')}\n` +
    `${indent}  key: ${opts.stylize(toHex(core.key), 'string')}\n` +
    `${indent}  discoveryKey: ${opts.stylize(toHex(core.discoveryKey), 'string')}\n` +
    `${indent}  opened: ${opts.stylize(core.opened, 'boolean')}\n` +
    `${indent}  closed: ${opts.stylize(core.closed, 'boolean')}\n` +
    `${indent}  snapshotted: ${opts.stylize(core.snapshotted, 'boolean')}\n` +
    `${indent}  writable: ${opts.stylize(core.writable, 'boolean')}\n` +
    `${indent}  length: ${opts.stylize(core.length, 'number')}\n` +
    `${indent}  fork: ${opts.stylize(core.fork, 'number')}\n` +
    `${indent}  sessions: [ ${opts.stylize(core.sessions.length, 'number')} ]\n` +
    `${indent}  activeRequests: [ ${opts.stylize(core.activeRequests.length, 'number')} ]\n` +
    `${indent}  peers: ${peers}\n` +
    `${indent})`
  )
}

function toHex(buf) {
  return buf && b4a.toString(buf, 'hex')
}
const BigSparseArray = require('big-sparse-array')
const { Transform } = require('streamx')
const quickbit = require('./compat').quickbit
const b4a = require('b4a')

const BITS_PER_PAGE = 32768
const BYTES_PER_PAGE = BITS_PER_PAGE / 8

class MarkPage {
  constructor() {
    this.bitfield = null
    this.loaded = new Promise((resolve) => {
      this.load = resolve
    })
  }

  setBitfield(bitfield) {
    this.bitfield = bitfield
    this.load()
  }

  get(index) {
    return quickbit.get(this.bitfield, index)
  }

  set(index, val) {
    quickbit.set(this.bitfield, index, val)
  }
}

module.exports = class MarkBitfield {
  static BITS_PER_PAGE = BITS_PER_PAGE
  static BYTES_PER_PAGE = BYTES_PER_PAGE

  constructor(storage) {
    this.storage = storage
    this._pages = new BigSparseArray()
  }

  async loadPage(pageIndex) {
    const p = this._pages.set(pageIndex, new MarkPage())
    const rx = this.storage.read()
    const pageBuf = rx.getMark(pageIndex)
    rx.tryFlush()
    const bitfield = (await pageBuf) ?? b4a.alloc(BYTES_PER_PAGE)
    await p.setBitfield(bitfield)
    return p
  }

  async get(index) {
    const j = index & (BITS_PER_PAGE - 1)
    const i = (index - j) / BITS_PER_PAGE

    let p = this._pages.get(i)
    if (!p) p = await this.loadPage(i)

    return p.get(j)
  }

  async set(index, val) {
    const j = index & (BITS_PER_PAGE - 1)
    const i = (index - j) / BITS_PER_PAGE

    let p = this._pages.get(i)

    if (!p && val) p = await this.loadPage(i)

    if (p) {
      await p.loaded
      p.set(j, val)
      const tx = this.storage.write()
      tx.putMark(i, p.bitfield)
      await tx.flush()
    }
  }

  async clear() {
    const tx = this.storage.write()
    tx.deleteMarkRange(0, -1)
    await tx.flush()
    this._pages = new BigSparseArray()
  }

  createMarkStream({ reverse = false } = {}) {
    return this.storage.createMarkStream({ reverse }).pipe(
      new Transform({
        transform({ index, page }, cb) {
          let bitIndex = reverse
            ? quickbit.findLast(page, true, BITS_PER_PAGE)
            : quickbit.findFirst(page, true, 0)
          while (bitIndex !== -1) {
            const blockIndex = index * BITS_PER_PAGE + bitIndex
            this.push(blockIndex)

            // Account for `bitIndex` being either causing infinite loop
            if (bitIndex === 0 && reverse) break

            bitIndex = reverse
              ? quickbit.findLast(page, true, bitIndex - 1)
              : quickbit.findFirst(page, true, bitIndex + 1)
          }

          cb(null)
        }
      })
    )
  }
}
const flat = require('flat-tree')
const crypto = require('hypercore-crypto')
const b4a = require('b4a')
const unslab = require('unslab')
const caps = require('./caps')
const {
  INVALID_PROOF,
  INVALID_CHECKSUM,
  INVALID_OPERATION,
  BAD_ARGUMENT,
  ASSERTION
} = require('hypercore-errors')

class NodeQueue {
  constructor(nodes, extra = null) {
    this.i = 0
    this.nodes = nodes
    this.extra = extra
    this.length = nodes.length + (this.extra === null ? 0 : 1)
  }

  shift(index) {
    if (this.extra !== null && this.extra.index === index) {
      const node = this.extra
      this.extra = null
      this.length--
      return node
    }

    if (this.i >= this.nodes.length) {
      throw INVALID_OPERATION('Expected node ' + index + ', got (nil)')
    }

    const node = this.nodes[this.i++]
    if (node.index !== index) {
      throw INVALID_OPERATION('Expected node ' + index + ', got node ' + node.index)
    }

    this.length--
    return node
  }
}

class MerkleTreeBatch {
  constructor(session) {
    this.fork = session.fork
    this.roots = [...session.roots]
    this.length = session.length
    this.signature = session.signature
    this.ancestors = session.length
    this.byteLength = session.byteLength
    this.prologue = session.prologue
    this.hashCached = null

    this.committed = false
    this.truncated = false
    this.treeLength = session.length
    this.treeFork = session.fork
    this.storage = session.storage
    this.session = session
    this.nodes = []
    this.upgraded = false
  }

  checkout(length, additionalRoots) {
    const roots = []
    let r = 0

    const head = 2 * length - 2
    const gaps = new Set()
    const all = new Map()

    // additional roots is so the original roots can be passed (we mutate the array in appendRoot)
    if (additionalRoots) {
      for (const node of additionalRoots) all.set(node.index, node)
    }

    for (const node of this.nodes) all.set(node.index, node)

    for (const index of flat.fullRoots(head + 2)) {
      const left = flat.leftSpan(index)
      if (left !== 0) gaps.add(left - 1)

      if (r < this.roots.length && this.roots[r].index === index) {
        roots.push(this.roots[r++])
        continue
      }
      const node = all.get(index)
      if (!node) throw new BAD_ARGUMENT('root missing for given length')
      roots.push(node)
    }

    this.roots = roots
    this.length = length
    this.byteLength = totalSize(roots)
    this.hashCached = null
    this.signature = null

    for (let i = 0; i < this.nodes.length; i++) {
      const index = this.nodes[i].index
      if (index <= head && !gaps.has(index)) continue
      const last = this.nodes.pop()
      if (i < this.nodes.length) this.nodes[i--] = last
    }
  }

  prune(length) {
    if (length === 0) return

    const head = 2 * length - 2
    const gaps = new Set()

    // TODO: make a function for this in flat-tree
    for (const index of flat.fullRoots(head + 2)) {
      const left = flat.leftSpan(index)
      if (left !== 0) gaps.add(left - 1)
    }

    for (let i = 0; i < this.nodes.length; i++) {
      const index = this.nodes[i].index
      if (index > head || gaps.has(index)) continue
      const last = this.nodes.pop()
      if (i < this.nodes.length) this.nodes[i--] = last
    }
  }

  clone() {
    const b = new MerkleTreeBatch(this.session)

    b.fork = this.fork
    b.roots = [...this.roots]
    b.length = this.length
    b.byteLength = this.byteLength
    b.signature = this.signature
    b.treeLength = this.treeLength
    b.treeFork = this.treeFork
    b.tree = this.tree
    b.nodes = [...this.nodes]
    b.upgraded = this.upgraded

    return b
  }

  hash() {
    if (this.hashCached === null) this.hashCached = unslab(crypto.tree(this.roots))
    return this.hashCached
  }

  signable(manifestHash) {
    return caps.treeSignable(manifestHash, this.hash(), this.length, this.fork)
  }

  signableCompat(noHeader) {
    return caps.treeSignableCompat(this.hash(), this.length, this.fork, noHeader)
  }

  get(index) {
    if (index >= this.length * 2) {
      return null
    }

    for (const n of this.nodes) {
      if (n.index === index) return n
    }

    return getTreeNodeFromStorage(this.session.storage, index)
  }

  // deprecated, use sssion proof instead
  proof(batch, { block, hash, seek, upgrade }) {
    return generateProof(this.session, batch, block, hash, seek, upgrade)
  }

  verifyUpgrade(proof) {
    const unverified = verifyTree(proof, this.nodes)

    if (!proof.upgrade) throw INVALID_OPERATION('Expected upgrade proof')

    return verifyUpgrade(proof, unverified, this)
  }

  addNodesUnsafe(nodes) {
    for (let i = 0; i < nodes.length; i++) {
      this.nodes.push(nodes[i])
    }
  }

  append(buf) {
    const head = this.length * 2
    const ite = flat.iterator(head)
    const node = blockNode(head, buf)

    this.appendRoot(node, ite)
  }

  appendRoot(node, ite) {
    node = unslabNode(node)
    this.hashCached = null
    this.upgraded = true
    this.length += ite.factor / 2
    this.byteLength += node.size
    this.roots.push(node)
    this.nodes.push(node)

    while (this.roots.length > 1) {
      const a = this.roots[this.roots.length - 1]
      const b = this.roots[this.roots.length - 2]

      // TODO: just have a peek sibling instead? (pretty sure it's always the left sib as well)
      if (ite.sibling() !== b.index) {
        ite.sibling() // unset so it always points to last root
        break
      }

      const node = unslabNode(parentNode(ite.parent(), a, b))
      this.nodes.push(node)
      this.roots.pop()
      this.roots.pop()
      this.roots.push(node)
    }
  }

  commitable() {
    return (
      this.treeFork === this.session.fork &&
      (this.upgraded
        ? this.treeLength === this.session.length
        : this.treeLength <= this.session.length)
    )
  }

  commit(tx) {
    if (tx === undefined) throw INVALID_OPERATION('No database batch was passed')

    if (this.session.core._repairMode) {
      throw ASSERTION('Cannot commit while repair mode is on')
    }

    if (!this.commitable()) {
      throw INVALID_OPERATION('Tree was modified during batch, refusing to commit')
    }

    if (this.upgraded) this._commitUpgrade(tx)

    for (let i = 0; i < this.nodes.length; i++) {
      const node = this.nodes[i]
      tx.putTreeNode(node)
    }

    this.committed = true

    return this
  }

  _commitUpgrade(tx) {
    // TODO: If easy to detect, we should refuse an trunc+append here without a fork id
    // change. Will only happen on user error so mostly to prevent that.

    if (this.ancestors < this.treeLength) {
      tx.deleteTreeNodeRange(this.ancestors * 2, this.treeLength * 2)

      if (this.ancestors > 0) {
        const head = this.ancestors * 2
        const ite = flat.iterator(head - 2)

        while (true) {
          if (ite.contains(head) && ite.index < head) {
            tx.deleteTreeNode(ite.index)
          }
          if (ite.offset === 0) break
          ite.parent()
        }

        this.truncated = true
      }
    }
  }

  seek(bytes, padding) {
    return new ByteSeeker(this, this, bytes, padding)
  }

  byteRange(index) {
    const rx = this.storage.read()
    const range = getByteRange(this, index, rx)
    rx.tryFlush()

    return range
  }

  byteOffset(index) {
    if (index === 2 * this.length) return this.byteLength

    const rx = this.storage.read()
    const offset = getByteOffset(this, index, rx)
    rx.tryFlush()

    return offset
  }

  async downgrade() {
    if (!this.upgraded) return true

    const rx = this.storage.read()
    const nodePromises = []

    for (const r of this.roots) {
      nodePromises.push(rx.getTreeNode(r.index))
    }

    rx.tryFlush()

    const nodes = await Promise.all(nodePromises)

    for (let i = 0; i < this.roots.length; i++) {
      const root = this.roots[i]
      const node = nodes[i]

      if (!node) return false
      if (!b4a.equals(node.hash, root.hash)) return false
    }

    this.upgraded = false
    return true
  }

  async restore(length) {
    if (length === this.length) return this

    const roots = unslabNodes(await MerkleTree.getRootsFromStorage(this.storage, length))

    this.roots = roots
    this.length = length
    this.byteLength = totalSize(roots)
    this.ancestors = length

    for (const node of roots) this.byteLength += node.size

    return this
  }
}

class ReorgBatch extends MerkleTreeBatch {
  constructor(session) {
    super(session)

    this.roots = []
    this.length = 0
    this.byteLength = 0
    this.diff = null
    this.ancestors = 0
    // We set upgraded because reorgs are signed so hit will
    // hit the same code paths (like the treeLength check in commit)
    this.upgraded = true
    this.want = {
      nodes: 0,
      start: 0,
      end: 0
    }
  }

  get finished() {
    return this.want === null
  }

  update(proof) {
    if (this.want === null) return true

    const nodes = []
    const root = verifyTree(proof, nodes)

    if (root === null || !b4a.equals(root.hash, this.diff.hash)) return false

    this.nodes.push(...nodes)
    return this._update(nodes)
  }

  async _update(nodes) {
    const n = new Map()
    for (const node of nodes) n.set(node.index, node)

    let diff = null
    const ite = flat.iterator(this.diff.index)
    const startingDiff = this.diff

    while ((ite.index & 1) !== 0) {
      const left = n.get(ite.leftChild())
      if (!left) break

      const existing = await getTreeNodeFromStorage(this.session.storage, left.index)
      if (!existing || !b4a.equals(existing.hash, left.hash)) {
        diff = left
      } else {
        diff = n.get(ite.sibling())
      }
    }

    if ((this.diff.index & 1) === 0) return true
    if (diff === null) return false
    if (startingDiff !== this.diff) return false

    return this._updateDiffRoot(diff)
  }

  _updateDiffRoot(diff) {
    if (this.want === null) return true

    const spans = flat.spans(diff.index)
    const start = spans[0] / 2
    const end = Math.min(this.treeLength, spans[1] / 2 + 1)
    const len = end - start

    this.ancestors = start
    this.diff = diff

    if ((diff.index & 1) === 0 || this.want.start >= this.treeLength || len <= 0) {
      this.want = null
      return true
    }

    this.want.start = start
    this.want.end = end
    this.want.nodes = log2(spans[1] - spans[0] + 2) - 1

    return false
  }
}

class ByteSeeker {
  constructor(session, bytes, padding = 0) {
    this.session = session
    this.bytes = bytes
    this.padding = padding

    const size = session.byteLength - session.length * padding

    this.start = bytes >= size ? session.length : 0
    this.end = bytes < size ? session.length : 0
  }

  async _seek(bytes) {
    if (!bytes) return [0, 0]

    for (const node of this.session.roots) {
      // all async ticks happen once we find the root so safe
      const size = getUnpaddedSize(node, this.padding, null)

      if (bytes === size) return [flat.rightSpan(node.index) + 2, 0]
      if (bytes > size) {
        bytes -= size
        continue
      }

      const ite = flat.iterator(node.index)

      while ((ite.index & 1) !== 0) {
        const l = await getTreeNodeFromStorage(this.session.storage, ite.leftChild())

        if (l) {
          const size = getUnpaddedSize(l, this.padding, ite)

          if (size === bytes) return [ite.rightSpan() + 2, 0]
          if (size > bytes) continue
          bytes -= size
          ite.sibling()
        } else {
          ite.parent()
          return [ite.index, bytes]
        }
      }

      return [ite.index, bytes]
    }

    return null
  }

  async update() {
    // TODO: combine _seek and this, much simpler
    const res = await this._seek(this.bytes)
    if (!res) return null
    if ((res[0] & 1) === 0) return [res[0] / 2, res[1]]

    const span = flat.spans(res[0])
    this.start = span[0] / 2
    this.end = span[1] / 2 + 1

    return null
  }
}

class TreeProof {
  constructor(session, block, hash, seek, upgrade) {
    this.fork = session.fork
    this.signature = session.signature

    this.block = block
    this.hash = hash
    this.seek = seek
    this.upgrade = upgrade

    this.pending = {
      node: null,
      seek: null,
      upgrade: null,
      additionalUpgrade: null
    }
  }

  async settle() {
    const result = {
      fork: this.fork,
      block: null,
      hash: null,
      seek: null,
      upgrade: null,
      manifest: null
    }

    const [pNode, pSeek, pUpgrade, pAdditional] = await settleProof(this.pending)

    if (this.block) {
      if (pNode === null) throw INVALID_OPERATION('Invalid block request')
      result.block = {
        index: this.block.index,
        value: null, // populated upstream, alloc it here for simplicity
        nodes: pNode
      }
    } else if (this.hash) {
      if (pNode === null) throw INVALID_OPERATION('Invalid block request')
      result.hash = {
        index: this.hash.index,
        nodes: pNode
      }
    }

    if (this.seek && pSeek !== null) {
      result.seek = {
        bytes: this.seek.bytes,
        nodes: pSeek
      }
    }

    if (this.upgrade) {
      result.upgrade = {
        start: this.upgrade.start,
        length: this.upgrade.length,
        nodes: pUpgrade,
        additionalNodes: pAdditional || [],
        signature: this.signature
      }
    }

    return result
  }
}

class MerkleTree {
  static hash(s) {
    return unslab(crypto.tree(s.roots))
  }

  static signable(s, namespace) {
    return caps.treeSignable(namespace, MerkleTree.hash(s), s.length, s.fork)
  }

  static size(roots) {
    return totalSize(roots)
  }

  static span(roots) {
    return totalSpan(roots)
  }

  static getRoots(session, length) {
    return MerkleTree.getRootsFromStorage(session.storage, length)
  }

  static getRootsFromStorage(storage, length) {
    const indexes = flat.fullRoots(2 * length)
    const roots = new Array(indexes.length)
    const rx = storage.read()

    for (let i = 0; i < indexes.length; i++) {
      roots[i] = getTreeNodeOrError(rx, indexes[i])
    }

    rx.tryFlush()

    return Promise.all(roots)
  }

  static async upgradeable(session, length) {
    const indexes = flat.fullRoots(2 * length)
    const roots = new Array(indexes.length)
    const rx = session.storage.read()

    for (let i = 0; i < indexes.length; i++) {
      roots[i] = rx.getTreeNode(indexes[i])
    }

    rx.tryFlush()

    for (const node of await Promise.all(roots)) {
      if (node === null) return false
    }

    return true
  }

  static seek(session, bytes, padding) {
    return new ByteSeeker(session, bytes, padding)
  }

  static get(session, index) {
    return getTreeNodeFromStorage(session.storage, index)
  }

  static async truncate(session, length, batch, fork = batch.fork) {
    const head = length * 2
    const fullRoots = flat.fullRoots(head)

    for (let i = 0; i < fullRoots.length; i++) {
      const root = fullRoots[i]
      if (i < batch.roots.length && batch.roots[i].index === root) continue

      while (batch.roots.length > i) batch.roots.pop()
      batch.roots.push(unslabNode(await getTreeNodeFromStorageOrError(session.storage, root)))
    }

    while (batch.roots.length > fullRoots.length) {
      batch.roots.pop()
    }

    batch.fork = fork
    batch.length = length
    batch.ancestors = length
    batch.byteLength = totalSize(batch.roots)
    batch.upgraded = true

    return batch
  }

  static async reorg(session, proof, batch) {
    let unverified = null

    if (proof.block || proof.hash || proof.seek) {
      unverified = verifyTree(proof, batch.nodes)
    }

    if (!verifyUpgrade(proof, unverified, batch)) {
      throw INVALID_PROOF('Fork proof not verifiable')
    }

    for (const root of batch.roots) {
      const existing = await getTreeNodeFromStorage(session.storage, root.index)
      if (existing && b4a.equals(existing.hash, root.hash)) continue
      batch._updateDiffRoot(root)
      break
    }

    if (batch.diff !== null) {
      await batch._update(batch.nodes)
    } else {
      batch.want = null
      batch.ancestors = batch.length
    }

    return batch
  }

  static verifyFullyRemote(session, proof) {
    // TODO: impl this less hackishly
    const batch = new MerkleTreeBatch(session)

    batch.fork = proof.fork
    batch.roots = []
    batch.length = 0
    batch.ancestors = 0
    batch.byteLength = 0

    let unverified = verifyTree(proof, batch.nodes)

    if (proof.upgrade) {
      if (verifyUpgrade(proof, unverified, batch)) {
        unverified = null
      }
    }

    return batch
  }

  static async verify(session, proof) {
    const batch = new MerkleTreeBatch(session)

    let unverified = verifyTree(proof, batch.nodes)

    if (proof.upgrade) {
      if (verifyUpgrade(proof, unverified, batch)) {
        unverified = null
      }
    }

    if (unverified) {
      const verified = await getTreeNodeFromStorageOrError(session.storage, unverified.index)
      if (!b4a.equals(verified.hash, unverified.hash)) {
        throw INVALID_CHECKSUM('Invalid checksum at node ' + unverified.index)
      }
    }

    return batch
  }

  static proof(session, rx, { block, hash, seek, upgrade }) {
    return generateProof(session, rx, block, hash, seek, upgrade)
  }

  static maxMissingNodes(index, length) {
    const head = 2 * length
    const ite = flat.iterator(index)

    // See iterator.rightSpan()
    const iteRightSpan = ite.index + ite.factor / 2 - 1
    // If the index is not in the current tree, we do not know how many missing nodes there are...
    if (iteRightSpan >= head) return 0

    for (const r of flat.fullRoots(head)) {
      if (r === index) return 0
    }

    // need missing nodes not inclusive of index
    ite.parent()

    let cnt = 0
    while (!ite.contains(head)) {
      cnt++
      ite.parent()
    }

    return cnt
  }

  static async missingNodes(session, index, length) {
    const head = 2 * length
    const ite = flat.iterator(index)

    // See iterator.rightSpan()
    const iteRightSpan = ite.index + ite.factor / 2 - 1
    // If the index is not in the current tree, we do not know how many missing nodes there are...
    if (iteRightSpan >= head) return 0

    let cnt = 0
    // TODO: we could prop use a read batch here and do this in blocks of X for perf
    while (!ite.contains(head) && !(await hasTreeNode(session.storage, ite.index))) {
      cnt++
      if (cnt >= 1024) {
        throw ASSERTION('Bad arguments to missingNodes index=' + index + ' at length=' + length)
      }
      ite.parent()
    }

    return cnt
  }

  static byteOffset(session, index) {
    return getByteOffsetSession(session, index, null)
  }

  static byteRange(session, index) {
    const rx = session.storage.read()
    const offset = getByteOffsetSession(session, index, rx)
    const size = getNodeSize(index, rx)
    rx.tryFlush()
    return Promise.all([offset, size])
  }

  static upgradeLength(proof) {
    const extra = proof.additionalNodes

    if (extra.length) {
      const last = extra[extra.length - 1]
      const index = flat.rightSpan(last.index)
      return index / 2 + 1
    }

    return proof.start + proof.length
  }
}

module.exports = {
  MerkleTreeBatch,
  ReorgBatch,
  MerkleTree
}

async function getNodeSize(index, rx) {
  return (await getTreeNodeOrError(rx, index)).size
}

async function getByteOffsetSession(session, index, rx) {
  if (index === 2 * session.length) return session.byteLength

  const treeNodes =
    rx === null
      ? await getByteOffsetBatchFlush(session.roots, index, session.storage.read())
      : await getByteOffsetBatch(session.roots, index, rx)

  let offset = 0
  for (const node of treeNodes) offset += node.size

  return offset
}

async function getByteOffset(tree, index, rx) {
  if (index === 2 * tree.length) return tree.byteLength

  const treeNodes = await getByteOffsetBatch(tree.roots, index, rx)

  let offset = 0
  for (const node of treeNodes) offset += node.size

  return offset
}

function getByteOffsetBatchFlush(roots, index, rx) {
  const treeNodes = getByteOffsetBatch(roots, index, rx)
  rx.tryFlush()
  return treeNodes
}

function getByteOffsetBatch(roots, index, rx) {
  if ((index & 1) === 1) index = flat.leftSpan(index)

  let head = 0
  let cnt = 0

  const promises = []

  for (const node of roots) {
    // all async ticks happen once we find the root so safe
    head += 2 * (node.index - head + 1)

    if (index >= head) {
      promises.push(node.size)
      continue
    }

    const ite = flat.iterator(node.index)

    while (ite.index !== index) {
      if (++cnt >= 1024) throw ASSERTION('Bad getByteOffsetSession index=' + index)

      if (index < ite.index) {
        ite.leftChild()
      } else {
        promises.push(getTreeNodeOrError(rx, ite.leftChild()))
        ite.sibling()
      }
    }

    return Promise.all(promises)
  }

  throw ASSERTION('Failed to find offset')
}

function getByteRange(tree, index, rx) {
  const head = 2 * tree.length
  if (((index & 1) === 0 ? index : flat.rightSpan(index)) >= head) {
    throw BAD_ARGUMENT('Index is out of bounds')
  }

  const offset = getByteOffset(tree, index, rx)
  const size = getNodeSize(index, rx)

  return Promise.all([offset, size])
}

// All the methods needed for proof verification

function verifyTree({ block, hash, seek }, nodes) {
  const untrustedNode = block
    ? { index: 2 * block.index, value: block.value, nodes: block.nodes }
    : hash
      ? { index: hash.index, value: null, nodes: hash.nodes }
      : null

  if (untrustedNode === null && (!seek || !seek.nodes.length)) return null

  let root = null

  if (seek && seek.nodes.length) {
    const ite = flat.iterator(seek.nodes[0].index)
    const q = new NodeQueue(seek.nodes)

    root = q.shift(ite.index)
    nodes.push(root)

    while (q.length > 0) {
      const node = q.shift(ite.sibling())

      root = parentNode(ite.parent(), root, node)
      nodes.push(node)
      nodes.push(root)
    }
  }

  if (untrustedNode === null) return root

  const ite = flat.iterator(untrustedNode.index)
  const blockHash = untrustedNode.value && blockNode(ite.index, untrustedNode.value)

  const q = new NodeQueue(untrustedNode.nodes, root)

  root = blockHash || q.shift(ite.index)
  nodes.push(root)

  while (q.length > 0) {
    const node = q.shift(ite.sibling())

    root = parentNode(ite.parent(), root, node)
    nodes.push(node)
    nodes.push(root)
  }

  return root
}

function verifyUpgrade({ fork, upgrade }, blockRoot, batch) {
  const prologue = batch.prologue

  if (prologue) {
    const { start, length } = upgrade
    if (start < prologue.length && (start !== 0 || length < prologue.length)) {
      throw INVALID_PROOF('Upgrade does not satisfy prologue')
    }
  }

  const q = new NodeQueue(upgrade.nodes, blockRoot)

  let grow = batch.roots.length > 0
  let i = 0

  const to = 2 * (upgrade.start + upgrade.length)
  const ite = flat.iterator(0)

  for (; ite.fullRoot(to); ite.nextTree()) {
    if (i < batch.roots.length && batch.roots[i].index === ite.index) {
      i++
      continue
    }

    if (grow) {
      grow = false
      const root = ite.index
      if (i < batch.roots.length) {
        ite.seek(batch.roots[batch.roots.length - 1].index)
        while (ite.index !== root) {
          batch.appendRoot(q.shift(ite.sibling()), ite)
        }
        continue
      }
    }

    batch.appendRoot(q.shift(ite.index), ite)
  }

  if (prologue && batch.length === prologue.length) {
    if (!b4a.equals(prologue.hash, batch.hash())) {
      throw INVALID_PROOF('Invalid hash')
    }
  }

  const extra = upgrade.additionalNodes

  ite.seek(batch.roots[batch.roots.length - 1].index)
  i = 0

  while (i < extra.length && extra[i].index === ite.sibling()) {
    batch.appendRoot(extra[i++], ite)
  }

  while (i < extra.length) {
    const node = extra[i++]

    while (node.index !== ite.index) {
      if (ite.factor === 2) throw INVALID_OPERATION('Unexpected node: ' + node.index)
      ite.leftChild()
    }

    batch.appendRoot(node, ite)
    ite.sibling()
  }

  batch.signature = unslab(upgrade.signature)
  batch.fork = fork

  return q.extra === null
}

async function seekFromHead(session, head, bytes, padding) {
  const roots = flat.fullRoots(head)

  for (let i = 0; i < roots.length; i++) {
    const root = roots[i]
    const node = await getTreeNodeFromStorage(session.storage, root)
    const size = getUnpaddedSize(node, padding, null)

    if (bytes === size) return root
    if (bytes > size) {
      bytes -= size
      continue
    }

    return seekTrustedTree(session, root, bytes, padding)
  }

  return head
}

// trust that bytes are within the root tree and find the block at bytes

async function seekTrustedTree(session, root, bytes, padding) {
  if (!bytes) return root

  const ite = flat.iterator(root)
  let cnt = 0

  while ((ite.index & 1) !== 0) {
    if (++cnt >= 1024) throw ASSERTION('Bad seekTrusted bytes=' + bytes + ', paddding=' + padding)
    const l = await getTreeNodeFromStorage(session.storage, ite.leftChild())

    if (l) {
      const size = getUnpaddedSize(l, padding, ite)
      if (size === bytes) return ite.index
      if (size > bytes) continue
      bytes -= size
      ite.sibling()
    } else {
      ite.parent()
      return ite.index
    }
  }

  return ite.index
}

// try to find the block at bytes without trusting that is *is* within the root passed

async function seekUntrustedTree(session, root, bytes, padding) {
  const offset =
    (await getByteOffsetSession(session, root, null)) -
    (padding ? (padding * flat.leftSpan(root)) / 2 : 0)

  if (offset > bytes) throw INVALID_OPERATION('Invalid seek')
  if (offset === bytes) return root

  bytes -= offset

  const node = await getTreeNodeFromStorageOrError(session.storage, root)

  if (getUnpaddedSize(node, padding, null) <= bytes) throw INVALID_OPERATION('Invalid seek')

  return seekTrustedTree(session, root, bytes, padding)
}

// Below is proof production, ie, construct proofs to verify a request
// Note, that all these methods are sync as we can statically infer which nodes
// are needed for the remote to verify given they arguments they passed us

function seekProof(session, rx, seekRoot, root, p) {
  const ite = flat.iterator(seekRoot)
  let cnt = 0

  p.seek = []
  p.seek.push(getTreeNodeOrError(rx, ite.index))

  while (ite.index !== root) {
    if (++cnt >= 1024) throw ASSERTION('Bad seekProof seekRoot=' + seekRoot + ', root=' + root)
    ite.sibling()
    p.seek.push(getTreeNodeOrError(rx, ite.index))
    ite.parent()
  }
}

function blockAndSeekProof(session, rx, node, seek, seekRoot, root, p) {
  if (!node) return seekProof(session, rx, seekRoot, root, p)

  const ite = flat.iterator(node.index)
  let cnt = 0

  p.node = []
  if (!node.value) p.node.push(getTreeNodeOrError(rx, ite.index))

  while (ite.index !== root) {
    if (++cnt >= 1024) {
      throw ASSERTION('Bad blockAndSeekProof seekRoot=' + seekRoot + ', root=' + root)
    }
    ite.sibling()

    if (seek && ite.contains(seekRoot) && ite.index !== seekRoot) {
      seekProof(session, rx, seekRoot, ite.index, p)
    } else {
      p.node.push(getTreeNodeOrError(rx, ite.index))
    }

    ite.parent()
  }
}

function upgradeProof(session, rx, node, seek, from, to, subTree, p) {
  if (from === 0) p.upgrade = []

  for (const ite = flat.iterator(0); ite.fullRoot(to); ite.nextTree()) {
    // check if they already have the node
    if (ite.index + ite.factor / 2 < from) continue

    // connect existing tree
    if (p.upgrade === null && ite.contains(from - 2)) {
      p.upgrade = []

      const root = ite.index
      const target = from - 2
      let cnt = 0

      ite.seek(target)

      while (ite.index !== root) {
        if (++cnt >= 1024) throw ASSERTION('Bad upgradeProof target=' + target + ', root=' + root)

        ite.sibling()
        if (ite.index > target) {
          if (p.node === null && p.seek === null && ite.contains(subTree)) {
            blockAndSeekProof(session, rx, node, seek, subTree, ite.index, p)
          } else {
            p.upgrade.push(getTreeNodeOrError(rx, ite.index))
          }
        }
        ite.parent()
      }

      continue
    }

    if (p.upgrade === null) {
      p.upgrade = []
    }

    // if the subtree included is a child of this tree, include that one
    // instead of a dup node
    if (p.node === null && p.seek === null && ite.contains(subTree)) {
      blockAndSeekProof(session, rx, node, seek, subTree, ite.index, p)
      continue
    }

    // add root (can be optimised since the root might be in tree.roots)
    p.upgrade.push(getTreeNodeOrError(rx, ite.index))
  }
}

function additionalUpgradeProof(session, rx, from, to, p) {
  if (from === 0) p.additionalUpgrade = []

  for (const ite = flat.iterator(0); ite.fullRoot(to); ite.nextTree()) {
    // check if they already have the node
    if (ite.index + ite.factor / 2 < from) continue

    // connect existing tree
    if (p.additionalUpgrade === null && ite.contains(from - 2)) {
      p.additionalUpgrade = []

      const root = ite.index
      const target = from - 2
      let cnt = 0

      ite.seek(target)

      while (ite.index !== root) {
        if (++cnt >= 1024) {
          throw ASSERTION(
            'Bad arguments to additionalUpgradeProof root=' + root + ' target=' + target
          )
        }
        ite.sibling()
        if (ite.index > target) {
          p.additionalUpgrade.push(getTreeNodeOrError(rx, ite.index))
        }
        ite.parent()
      }

      continue
    }

    if (p.additionalUpgrade === null) {
      p.additionalUpgrade = []
    }

    // add root (can be optimised since the root is in tree.roots)
    p.additionalUpgrade.push(getTreeNodeOrError(rx, ite.index))
  }
}

function nodesToRoot(index, nodes, head) {
  const ite = flat.iterator(index)

  for (let i = 0; i < nodes; i++) {
    ite.parent()
    if (ite.contains(head)) throw INVALID_OPERATION('Nodes is out of bounds')
  }

  return ite.index
}

function totalSize(nodes) {
  let s = 0
  for (const node of nodes) s += node.size
  return s
}

function totalSpan(nodes) {
  let s = 0
  for (const node of nodes) s += 2 * (node.index - s + 1)
  return s
}

function blockNode(index, value) {
  return { index, size: value.byteLength, hash: crypto.data(value) }
}

function parentNode(index, a, b) {
  return { index, size: a.size + b.size, hash: crypto.parent(a, b) }
}

function log2(n) {
  let res = 1

  while (n > 2) {
    n /= 2
    res++
  }

  return res
}

function normalizeIndexed(block, hash) {
  if (block) {
    return {
      value: true,
      index: block.index * 2,
      nodes: block.nodes,
      lastIndex: block.index
    }
  }
  if (hash) {
    return {
      value: false,
      index: hash.index,
      nodes: hash.nodes,
      lastIndex: flat.rightSpan(hash.index) / 2
    }
  }
  return null
}

async function getTreeNodeOrError(rx, index) {
  const node = await rx.getTreeNode(index)
  if (node === null) {
    throw INVALID_OPERATION('Expected tree node ' + index + ' from storage, got (nil)')
  }
  return node
}

function getTreeNodeFromStorageOrError(storage, index) {
  const rx = storage.read()
  const p = getTreeNodeOrError(rx, index)
  rx.tryFlush()
  return p
}

function getTreeNodeFromStorage(storage, index) {
  const rx = storage.read()
  const node = rx.getTreeNode(index)
  rx.tryFlush()
  return node
}

function hasTreeNode(storage, index) {
  const rx = storage.read()
  const has = rx.hasTreeNode(index)
  rx.tryFlush()
  return has
}

async function settleProof(p) {
  const result = [
    p.node && Promise.all(p.node),
    p.seek && Promise.all(p.seek),
    p.upgrade && Promise.all(p.upgrade),
    p.additionalUpgrade && Promise.all(p.additionalUpgrade)
  ]

  try {
    return await Promise.all(result)
  } catch (err) {
    if (p.node) await Promise.allSettled(p.node)
    if (p.seek) await Promise.allSettled(p.seek)
    if (p.upgrade) await Promise.allSettled(p.upgrade)
    if (p.additionalUpgrade) await Promise.allSettled(p.additionalUpgrade)
    throw err
  }
}

// tree can be either the merkle tree or a merkle tree batch
async function generateProof(session, rx, block, hash, seek, upgrade) {
  // Important that this does not throw inbetween making the promise arrays
  // and finalise being called, otherwise there will be lingering promises in the background

  if (session.prologue && upgrade) {
    upgrade.start = upgrade.start < session.prologue.length ? 0 : upgrade.start
    upgrade.length =
      upgrade.start < session.prologue.length ? session.prologue.length : upgrade.length
  }

  const head = 2 * session.length
  const from = upgrade ? upgrade.start * 2 : 0
  const to = upgrade ? from + upgrade.length * 2 : head
  const node = normalizeIndexed(block, hash)

  // can't do anything as we have no data...
  if (head === 0) return new TreeProof(session, null, null, null, null)

  if (from >= to || to > head) {
    throw INVALID_OPERATION('Invalid upgrade')
  }
  if (seek && upgrade && node !== null && node.index >= from) {
    throw INVALID_OPERATION('Cannot both do a seek and block/hash request when upgrading')
  }

  let subTree = head

  const p = new TreeProof(session, block, hash, seek, upgrade)

  if (node !== null && (!upgrade || node.lastIndex < upgrade.start)) {
    subTree = nodesToRoot(node.index, node.nodes, to)
    const seekRoot = seek
      ? await seekUntrustedTree(session, subTree, seek.bytes, seek.padding)
      : head
    blockAndSeekProof(session, rx, node, seek, seekRoot, subTree, p.pending)
  } else if ((node || seek) && upgrade) {
    subTree = seek ? await seekFromHead(session, to, seek.bytes, seek.padding) : node.index
  }

  if (upgrade) {
    upgradeProof(session, rx, node, seek, from, to, subTree, p.pending)
    if (head > to) additionalUpgradeProof(session, rx, to, head, p.pending)
  }

  return p
}

function getUnpaddedSize(node, padding, ite) {
  return padding === 0
    ? node.size
    : node.size - padding * (ite ? ite.countLeaves() : flat.countLeaves(node.index))
}

function unslabNodes(nodes) {
  for (const node of nodes) unslabNode(node)
  return nodes
}

function unslabNode(node) {
  if (node === null) return node
  node.hash = unslab(node.hash)
  return node
}
const c = require('compact-encoding')
const { DEFAULT_NAMESPACE } = require('./caps')
const { INVALID_OPLOG_VERSION } = require('hypercore-errors')
const unslab = require('unslab')

const MANIFEST_PATCH = 0b00000001
const MANIFEST_PROLOGUE = 0b00000010
const MANIFEST_LINKED = 0b00000100
const MANIFEST_USER_DATA = 0b00001000

const hashes = {
  preencode(state, m) {
    state.end++ // small uint
  },
  encode(state, m) {
    if (m === 'blake2b') {
      c.uint.encode(state, 0)
      return
    }

    throw new Error('Unknown hash: ' + m)
  },
  decode(state) {
    const n = c.uint.decode(state)
    if (n === 0) return 'blake2b'
    throw new Error('Unknown hash id: ' + n)
  }
}

const signatures = {
  preencode(state, m) {
    state.end++ // small uint
  },
  encode(state, m) {
    if (m === 'ed25519') {
      c.uint.encode(state, 0)
      return
    }

    throw new Error('Unknown signature: ' + m)
  },
  decode(state) {
    const n = c.uint.decode(state)
    if (n === 0) return 'ed25519'
    throw new Error('Unknown signature id: ' + n)
  }
}

const signer = {
  preencode(state, m) {
    signatures.preencode(state, m.signature)
    c.fixed32.preencode(state, m.namespace)
    c.fixed32.preencode(state, m.publicKey)
  },
  encode(state, m) {
    signatures.encode(state, m.signature)
    c.fixed32.encode(state, m.namespace)
    c.fixed32.encode(state, m.publicKey)
  },
  decode(state) {
    return {
      signature: signatures.decode(state),
      namespace: c.fixed32.decode(state),
      publicKey: c.fixed32.decode(state)
    }
  }
}

const signerArray = c.array(signer)

const prologue = {
  preencode(state, p) {
    c.fixed32.preencode(state, p.hash)
    c.uint.preencode(state, p.length)
  },
  encode(state, p) {
    c.fixed32.encode(state, p.hash)
    c.uint.encode(state, p.length)
  },
  decode(state) {
    return {
      hash: c.fixed32.decode(state),
      length: c.uint.decode(state)
    }
  }
}

const manifestv0 = {
  preencode(state, m) {
    hashes.preencode(state, m.hash)
    state.end++ // type

    if (m.prologue && m.signers.length === 0) {
      c.fixed32.preencode(state, m.prologue.hash)
      return
    }

    if (m.quorum === 1 && m.signers.length === 1 && !m.allowPatch) {
      signer.preencode(state, m.signers[0])
    } else {
      state.end++ // flags
      c.uint.preencode(state, m.quorum)
      signerArray.preencode(state, m.signers)
    }
  },
  encode(state, m) {
    hashes.encode(state, m.hash)

    if (m.prologue && m.signers.length === 0) {
      c.uint.encode(state, 0)
      c.fixed32.encode(state, m.prologue.hash)
      return
    }

    if (m.quorum === 1 && m.signers.length === 1 && !m.allowPatch) {
      c.uint.encode(state, 1)
      signer.encode(state, m.signers[0])
    } else {
      c.uint.encode(state, 2)
      c.uint.encode(state, m.allowPatch ? 1 : 0)
      c.uint.encode(state, m.quorum)
      signerArray.encode(state, m.signers)
    }
  },
  decode(state) {
    const hash = hashes.decode(state)
    const type = c.uint.decode(state)

    if (type > 2) throw new Error('Unknown type: ' + type)

    if (type === 0) {
      return {
        version: 0,
        hash,
        allowPatch: false,
        quorum: 0,
        signers: [],
        prologue: {
          hash: c.fixed32.decode(state),
          length: 0
        },
        linked: null,
        userData: null
      }
    }

    if (type === 1) {
      return {
        version: 0,
        hash,
        allowPatch: false,
        quorum: 1,
        signers: [signer.decode(state)],
        prologue: null,
        linked: null,
        userData: null
      }
    }

    const flags = c.uint.decode(state)

    return {
      version: 0,
      hash,
      allowPatch: (flags & 1) !== 0,
      quorum: c.uint.decode(state),
      signers: signerArray.decode(state),
      prologue: null,
      linked: null,
      userData: null
    }
  }
}

const fixed32Array = c.array(c.fixed32)

const manifest = (exports.manifest = {
  preencode(state, m) {
    state.end++ // version

    if (m.version === 0) return manifestv0.preencode(state, m)

    state.end++ // flags
    hashes.preencode(state, m.hash)

    c.uint.preencode(state, m.quorum)
    signerArray.preencode(state, m.signers)

    if (m.prologue) prologue.preencode(state, m.prologue)
    if (m.linked) fixed32Array.preencode(state, m.linked)
    if (m.userData) c.buffer.preencode(state, m.userData)
  },
  encode(state, m) {
    c.uint.encode(state, m.version)

    if (m.version === 0) return manifestv0.encode(state, m)

    let flags = 0
    if (m.allowPatch) flags |= MANIFEST_PATCH
    if (m.prologue) flags |= MANIFEST_PROLOGUE
    if (m.linked) flags |= MANIFEST_LINKED
    if (m.userData) flags |= MANIFEST_USER_DATA

    c.uint.encode(state, flags)
    hashes.encode(state, m.hash)

    c.uint.encode(state, m.quorum)
    signerArray.encode(state, m.signers)

    if (m.prologue) prologue.encode(state, m.prologue)
    if (m.linked) fixed32Array.encode(state, m.linked)
    if (m.userData) c.buffer.encode(state, m.userData)
  },
  decode(state) {
    const version = c.uint.decode(state)

    if (version === 0) return manifestv0.decode(state)
    if (version > 2) throw new Error('Unknown version: ' + version)

    const flags = c.uint.decode(state)
    const hash = hashes.decode(state)
    const quorum = c.uint.decode(state)
    const signers = signerArray.decode(state)

    const hasPatch = (flags & MANIFEST_PATCH) !== 0
    const hasPrologue = (flags & MANIFEST_PROLOGUE) !== 0
    const hasLinked = (flags & MANIFEST_LINKED) !== 0
    const hasUserData = (flags & MANIFEST_USER_DATA) !== 0

    return {
      version,
      hash,
      allowPatch: hasPatch,
      quorum,
      signers,
      prologue: hasPrologue ? prologue.decode(state) : null,
      linked: hasLinked ? fixed32Array.decode(state) : null,
      userData: hasUserData ? c.buffer.decode(state) : null
    }
  }
})

const node = {
  preencode(state, n) {
    c.uint.preencode(state, n.index)
    c.uint.preencode(state, n.size)
    c.fixed32.preencode(state, n.hash)
  },
  encode(state, n) {
    c.uint.encode(state, n.index)
    c.uint.encode(state, n.size)
    c.fixed32.encode(state, n.hash)
  },
  decode(state) {
    return {
      index: c.uint.decode(state),
      size: c.uint.decode(state),
      hash: c.fixed32.decode(state)
    }
  }
}

const nodeArray = c.array(node)

const wire = (exports.wire = {})

wire.handshake = {
  preencode(state, m) {
    c.uint.preencode(state, 1)
    c.fixed32.preencode(state, m.capability)
  },
  encode(state, m) {
    c.uint.encode(state, m.seeks ? 1 : 0)
    c.fixed32.encode(state, m.capability)
  },
  decode(state) {
    const flags = c.uint.decode(state)
    return {
      seeks: (flags & 1) !== 0,
      capability: unslab(c.fixed32.decode(state))
    }
  }
}

const requestBlock = {
  preencode(state, b) {
    c.uint.preencode(state, b.index)
    c.uint.preencode(state, b.nodes)
  },
  encode(state, b) {
    c.uint.encode(state, b.index)
    c.uint.encode(state, b.nodes)
  },
  decode(state) {
    return {
      index: c.uint.decode(state),
      nodes: c.uint.decode(state)
    }
  }
}

const requestSeek = {
  preencode(state, s) {
    c.uint.preencode(state, s.bytes)
    c.uint.preencode(state, s.padding)
  },
  encode(state, s) {
    c.uint.encode(state, s.bytes)
    c.uint.encode(state, s.padding)
  },
  decode(state) {
    return {
      bytes: c.uint.decode(state),
      padding: c.uint.decode(state)
    }
  }
}

const requestUpgrade = {
  preencode(state, u) {
    c.uint.preencode(state, u.start)
    c.uint.preencode(state, u.length)
  },
  encode(state, u) {
    c.uint.encode(state, u.start)
    c.uint.encode(state, u.length)
  },
  decode(state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

wire.request = {
  preencode(state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.id)
    c.uint.preencode(state, m.fork)

    if (m.block) requestBlock.preencode(state, m.block)
    if (m.hash) requestBlock.preencode(state, m.hash)
    if (m.seek) requestSeek.preencode(state, m.seek)
    if (m.upgrade) requestUpgrade.preencode(state, m.upgrade)
    if (m.priority) c.uint.preencode(state, m.priority)
  },
  encode(state, m) {
    const flags =
      (m.block ? 1 : 0) |
      (m.hash ? 2 : 0) |
      (m.seek ? 4 : 0) |
      (m.upgrade ? 8 : 0) |
      (m.manifest ? 16 : 0) |
      (m.priority ? 32 : 0)

    c.uint.encode(state, flags)
    c.uint.encode(state, m.id)
    c.uint.encode(state, m.fork)

    if (m.block) requestBlock.encode(state, m.block)
    if (m.hash) requestBlock.encode(state, m.hash)
    if (m.seek) requestSeek.encode(state, m.seek)
    if (m.upgrade) requestUpgrade.encode(state, m.upgrade)
    if (m.priority) c.uint.encode(state, m.priority)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      id: c.uint.decode(state),
      fork: c.uint.decode(state),
      block: flags & 1 ? requestBlock.decode(state) : null,
      hash: flags & 2 ? requestBlock.decode(state) : null,
      seek: flags & 4 ? requestSeek.decode(state) : null,
      upgrade: flags & 8 ? requestUpgrade.decode(state) : null,
      manifest: (flags & 16) !== 0,
      priority: flags & 32 ? c.uint.decode(state) : 0
    }
  }
}

wire.cancel = {
  preencode(state, m) {
    c.uint.preencode(state, m.request)
  },
  encode(state, m) {
    c.uint.encode(state, m.request)
  },
  decode(state, m) {
    return {
      request: c.uint.decode(state)
    }
  }
}

const dataUpgrade = {
  preencode(state, u) {
    c.uint.preencode(state, u.start)
    c.uint.preencode(state, u.length)
    nodeArray.preencode(state, u.nodes)
    nodeArray.preencode(state, u.additionalNodes)
    c.optionalBuffer.preencode(state, u.signature)
  },
  encode(state, u) {
    c.uint.encode(state, u.start)
    c.uint.encode(state, u.length)
    nodeArray.encode(state, u.nodes)
    nodeArray.encode(state, u.additionalNodes)
    c.optionalBuffer.encode(state, u.signature)
  },
  decode(state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state),
      nodes: nodeArray.decode(state),
      additionalNodes: nodeArray.decode(state),
      signature: c.optionalBuffer.decode(state)
    }
  }
}

const dataSeek = {
  preencode(state, s) {
    c.uint.preencode(state, s.bytes)
    nodeArray.preencode(state, s.nodes)
  },
  encode(state, s) {
    c.uint.encode(state, s.bytes)
    nodeArray.encode(state, s.nodes)
  },
  decode(state) {
    return {
      bytes: c.uint.decode(state),
      nodes: nodeArray.decode(state)
    }
  }
}

const dataBlock = {
  preencode(state, b) {
    c.uint.preencode(state, b.index)
    c.buffer.preencode(state, b.value)
    nodeArray.preencode(state, b.nodes)
  },
  encode(state, b) {
    c.uint.encode(state, b.index)
    c.buffer.encode(state, b.value)
    nodeArray.encode(state, b.nodes)
  },
  decode(state) {
    return {
      index: c.uint.decode(state),
      value: c.buffer.decode(state),
      nodes: nodeArray.decode(state)
    }
  }
}

const dataHash = {
  preencode(state, b) {
    c.uint.preencode(state, b.index)
    nodeArray.preencode(state, b.nodes)
  },
  encode(state, b) {
    c.uint.encode(state, b.index)
    nodeArray.encode(state, b.nodes)
  },
  decode(state) {
    return {
      index: c.uint.decode(state),
      nodes: nodeArray.decode(state)
    }
  }
}

wire.data = {
  preencode(state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.request)
    c.uint.preencode(state, m.fork)

    if (m.block) dataBlock.preencode(state, m.block)
    if (m.hash) dataHash.preencode(state, m.hash)
    if (m.seek) dataSeek.preencode(state, m.seek)
    if (m.upgrade) dataUpgrade.preencode(state, m.upgrade)
    if (m.manifest) manifest.preencode(state, m.manifest)
  },
  encode(state, m) {
    const flags =
      (m.block ? 1 : 0) |
      (m.hash ? 2 : 0) |
      (m.seek ? 4 : 0) |
      (m.upgrade ? 8 : 0) |
      (m.manifest ? 16 : 0)

    c.uint.encode(state, flags)
    c.uint.encode(state, m.request)
    c.uint.encode(state, m.fork)

    if (m.block) dataBlock.encode(state, m.block)
    if (m.hash) dataHash.encode(state, m.hash)
    if (m.seek) dataSeek.encode(state, m.seek)
    if (m.upgrade) dataUpgrade.encode(state, m.upgrade)
    if (m.manifest) manifest.encode(state, m.manifest)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      request: c.uint.decode(state),
      fork: c.uint.decode(state),
      block: flags & 1 ? dataBlock.decode(state) : null,
      hash: flags & 2 ? dataHash.decode(state) : null,
      seek: flags & 4 ? dataSeek.decode(state) : null,
      upgrade: flags & 8 ? dataUpgrade.decode(state) : null,
      manifest: flags & 16 ? manifest.decode(state) : null
    }
  }
}

wire.noData = {
  preencode(state, m) {
    c.uint.preencode(state, m.request)
    c.uint.preencode(state, m.reason ? 1 : 0)
    if (m.reason) c.uint.preencode(state, m.reason)
  },
  encode(state, m) {
    c.uint.encode(state, m.request)
    c.uint.encode(state, m.reason ? 1 : 0)
    if (m.reason) c.uint.encode(state, m.reason)
  },
  decode(state, m) {
    const request = c.uint.decode(state)
    const flags = state.start < state.end ? c.uint.decode(state) : 0
    return {
      request,
      reason: flags & 1 ? c.uint.decode(state) : 0
    }
  }
}

// TODO: we should move to having these have a handle like in data, easier since they
// allocate state in practice
wire.want = {
  preencode(state, m) {
    c.uint.preencode(state, m.start)
    c.uint.preencode(state, m.length)

    const flags = m.any ? 1 : 0
    if (flags !== 0) c.uint.preencode(state, flags)
  },
  encode(state, m) {
    c.uint.encode(state, m.start)
    c.uint.encode(state, m.length)

    const flags = m.any ? 1 : 0
    if (flags !== 0) c.uint.encode(state, flags)
  },
  decode(state) {
    const start = c.uint.decode(state)
    const length = c.uint.decode(state)
    const flags = state.start < state.end ? c.uint.decode(state) : 0

    return {
      start,
      length,
      any: (flags & 1) !== 0
    }
  }
}

wire.unwant = {
  preencode(state, m) {
    c.uint.preencode(state, m.start)
    c.uint.preencode(state, m.length)

    const flags = m.any ? 1 : 0
    if (flags !== 0) c.uint.preencode(state, flags)
  },
  encode(state, m) {
    c.uint.encode(state, m.start)
    c.uint.encode(state, m.length)

    const flags = m.any ? 1 : 0
    if (flags !== 0) c.uint.encode(state, flags)
  },
  decode(state, m) {
    const start = c.uint.decode(state)
    const length = c.uint.decode(state)
    const flags = state.start < state.end ? c.uint.decode(state) : 0

    return {
      start,
      length,
      any: (flags & 1) !== 0
    }
  }
}

wire.range = {
  preencode(state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.start)
    if (m.length !== 1) c.uint.preencode(state, m.length)
  },
  encode(state, m) {
    c.uint.encode(state, (m.drop ? 1 : 0) | (m.length === 1 ? 2 : 0))
    c.uint.encode(state, m.start)
    if (m.length !== 1) c.uint.encode(state, m.length)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      drop: (flags & 1) !== 0,
      start: c.uint.decode(state),
      length: (flags & 2) !== 0 ? 1 : c.uint.decode(state)
    }
  }
}

wire.bitfield = {
  preencode(state, m) {
    c.uint.preencode(state, m.start)
    c.uint32array.preencode(state, m.bitfield)
  },
  encode(state, m) {
    c.uint.encode(state, m.start)
    c.uint32array.encode(state, m.bitfield)
  },
  decode(state, m) {
    return {
      start: c.uint.decode(state),
      bitfield: c.uint32array.decode(state)
    }
  }
}

wire.sync = {
  preencode(state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.fork)
    c.uint.preencode(state, m.length)
    c.uint.preencode(state, m.remoteLength)
  },
  encode(state, m) {
    c.uint.encode(
      state,
      (m.canUpgrade ? 1 : 0) |
        (m.uploading ? 2 : 0) |
        (m.downloading ? 4 : 0) |
        (m.hasManifest ? 8 : 0) |
        (m.allowPush ? 16 : 0)
    )
    c.uint.encode(state, m.fork)
    c.uint.encode(state, m.length)
    c.uint.encode(state, m.remoteLength)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      fork: c.uint.decode(state),
      length: c.uint.decode(state),
      remoteLength: c.uint.decode(state),
      canUpgrade: (flags & 1) !== 0,
      uploading: (flags & 2) !== 0,
      downloading: (flags & 4) !== 0,
      hasManifest: (flags & 8) !== 0,
      allowPush: (flags & 16) !== 0
    }
  }
}

wire.reorgHint = {
  preencode(state, m) {
    c.uint.preencode(state, m.from)
    c.uint.preencode(state, m.to)
    c.uint.preencode(state, m.ancestors)
  },
  encode(state, m) {
    c.uint.encode(state, m.from)
    c.uint.encode(state, m.to)
    c.uint.encode(state, m.ancestors)
  },
  decode(state) {
    return {
      from: c.uint.decode(state),
      to: c.uint.decode(state),
      ancestors: c.uint.decode(state)
    }
  }
}

wire.extension = {
  preencode(state, m) {
    c.string.preencode(state, m.name)
    c.raw.preencode(state, m.message)
  },
  encode(state, m) {
    c.string.encode(state, m.name)
    c.raw.encode(state, m.message)
  },
  decode(state) {
    return {
      name: c.string.decode(state),
      message: c.raw.decode(state)
    }
  }
}

const keyValue = {
  preencode(state, p) {
    c.string.preencode(state, p.key)
    c.buffer.preencode(state, p.value)
  },
  encode(state, p) {
    c.string.encode(state, p.key)
    c.buffer.encode(state, p.value)
  },
  decode(state) {
    return {
      key: c.string.decode(state),
      value: c.buffer.decode(state)
    }
  }
}

const treeUpgrade = {
  preencode(state, u) {
    c.uint.preencode(state, u.fork)
    c.uint.preencode(state, u.ancestors)
    c.uint.preencode(state, u.length)
    c.buffer.preencode(state, u.signature)
  },
  encode(state, u) {
    c.uint.encode(state, u.fork)
    c.uint.encode(state, u.ancestors)
    c.uint.encode(state, u.length)
    c.buffer.encode(state, u.signature)
  },
  decode(state) {
    return {
      fork: c.uint.decode(state),
      ancestors: c.uint.decode(state),
      length: c.uint.decode(state),
      signature: c.buffer.decode(state)
    }
  }
}

const bitfieldUpdate = {
  // TODO: can maybe be folded into a HAVE later on with the most recent spec
  preencode(state, b) {
    state.end++ // flags
    c.uint.preencode(state, b.start)
    c.uint.preencode(state, b.length)
  },
  encode(state, b) {
    state.buffer[state.start++] = b.drop ? 1 : 0
    c.uint.encode(state, b.start)
    c.uint.encode(state, b.length)
  },
  decode(state) {
    const flags = c.uint.decode(state)
    return {
      drop: (flags & 1) !== 0,
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

const oplog = (exports.oplog = {})

oplog.entry = {
  preencode(state, m) {
    state.end++ // flags
    if (m.userData) keyValue.preencode(state, m.userData)
    if (m.treeNodes) nodeArray.preencode(state, m.treeNodes)
    if (m.treeUpgrade) treeUpgrade.preencode(state, m.treeUpgrade)
    if (m.bitfield) bitfieldUpdate.preencode(state, m.bitfield)
  },
  encode(state, m) {
    const s = state.start++
    let flags = 0

    if (m.userData) {
      flags |= 1
      keyValue.encode(state, m.userData)
    }
    if (m.treeNodes) {
      flags |= 2
      nodeArray.encode(state, m.treeNodes)
    }
    if (m.treeUpgrade) {
      flags |= 4
      treeUpgrade.encode(state, m.treeUpgrade)
    }
    if (m.bitfield) {
      flags |= 8
      bitfieldUpdate.encode(state, m.bitfield)
    }

    state.buffer[s] = flags
  },
  decode(state) {
    const flags = c.uint.decode(state)
    return {
      userData: (flags & 1) !== 0 ? keyValue.decode(state) : null,
      treeNodes: (flags & 2) !== 0 ? nodeArray.decode(state) : null,
      treeUpgrade: (flags & 4) !== 0 ? treeUpgrade.decode(state) : null,
      bitfield: (flags & 8) !== 0 ? bitfieldUpdate.decode(state) : null
    }
  }
}

const keyPair = {
  preencode(state, kp) {
    c.buffer.preencode(state, kp.publicKey)
    c.buffer.preencode(state, kp.secretKey)
  },
  encode(state, kp) {
    c.buffer.encode(state, kp.publicKey)
    c.buffer.encode(state, kp.secretKey)
  },
  decode(state) {
    return {
      publicKey: c.buffer.decode(state),
      secretKey: c.buffer.decode(state)
    }
  }
}

const reorgHint = {
  preencode(state, r) {
    c.uint.preencode(state, r.from)
    c.uint.preencode(state, r.to)
    c.uint.preencode(state, r.ancestors)
  },
  encode(state, r) {
    c.uint.encode(state, r.from)
    c.uint.encode(state, r.to)
    c.uint.encode(state, r.ancestors)
  },
  decode(state) {
    return {
      from: c.uint.decode(state),
      to: c.uint.decode(state),
      ancestors: c.uint.decode(state)
    }
  }
}

const reorgHintArray = c.array(reorgHint)

const hints = {
  preencode(state, h) {
    reorgHintArray.preencode(state, h.reorgs)
    c.uint.preencode(state, h.contiguousLength)
  },
  encode(state, h) {
    reorgHintArray.encode(state, h.reorgs)
    c.uint.encode(state, h.contiguousLength)
  },
  decode(state) {
    return {
      reorgs: reorgHintArray.decode(state),
      contiguousLength: state.start < state.end ? c.uint.decode(state) : 0
    }
  }
}

const treeHeader = {
  preencode(state, t) {
    c.uint.preencode(state, t.fork)
    c.uint.preencode(state, t.length)
    c.buffer.preencode(state, t.rootHash)
    c.buffer.preencode(state, t.signature)
  },
  encode(state, t) {
    c.uint.encode(state, t.fork)
    c.uint.encode(state, t.length)
    c.buffer.encode(state, t.rootHash)
    c.buffer.encode(state, t.signature)
  },
  decode(state) {
    return {
      fork: c.uint.decode(state),
      length: c.uint.decode(state),
      rootHash: c.buffer.decode(state),
      signature: c.buffer.decode(state)
    }
  }
}

const types = {
  preencode(state, t) {
    c.string.preencode(state, t.tree)
    c.string.preencode(state, t.bitfield)
    c.string.preencode(state, t.signer)
  },
  encode(state, t) {
    c.string.encode(state, t.tree)
    c.string.encode(state, t.bitfield)
    c.string.encode(state, t.signer)
  },
  decode(state) {
    return {
      tree: c.string.decode(state),
      bitfield: c.string.decode(state),
      signer: c.string.decode(state)
    }
  }
}

const externalHeader = {
  preencode(state, m) {
    c.uint.preencode(state, m.start)
    c.uint.preencode(state, m.length)
  },
  encode(state, m) {
    c.uint.encode(state, m.start)
    c.uint.encode(state, m.length)
  },
  decode(state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

const keyValueArray = c.array(keyValue)

oplog.header = {
  preencode(state, h) {
    state.end += 2 // version + flags
    if (h.external) {
      externalHeader.preencode(state, h.external)
      return
    }
    c.fixed32.preencode(state, h.key)
    if (h.manifest) manifest.preencode(state, h.manifest)
    if (h.keyPair) keyPair.preencode(state, h.keyPair)
    keyValueArray.preencode(state, h.userData)
    treeHeader.preencode(state, h.tree)
    hints.preencode(state, h.hints)
  },
  encode(state, h) {
    c.uint.encode(state, 1)
    if (h.external) {
      c.uint.encode(state, 1) // ONLY set the first big for clarity
      externalHeader.encode(state, h.external)
      return
    }
    c.uint.encode(state, (h.manifest ? 2 : 0) | (h.keyPair ? 4 : 0))
    c.fixed32.encode(state, h.key)
    if (h.manifest) manifest.encode(state, h.manifest)
    if (h.keyPair) keyPair.encode(state, h.keyPair)
    keyValueArray.encode(state, h.userData)
    treeHeader.encode(state, h.tree)
    hints.encode(state, h.hints)
  },
  decode(state) {
    const version = c.uint.decode(state)

    if (version > 1) {
      throw INVALID_OPLOG_VERSION('Invalid header version. Expected <= 1, got ' + version)
    }

    if (version === 0) {
      const old = {
        types: types.decode(state),
        userData: keyValueArray.decode(state),
        tree: treeHeader.decode(state),
        signer: keyPair.decode(state),
        hints: hints.decode(state)
      }

      return {
        external: null,
        key: old.signer.publicKey,
        manifest: {
          version: 0,
          hash: old.types.tree,
          allowPatch: false,
          quorum: 1,
          signers: [
            {
              signature: old.types.signer,
              namespace: DEFAULT_NAMESPACE,
              publicKey: old.signer.publicKey
            }
          ],
          prologue: null,
          linked: null,
          userData: null
        },
        keyPair: old.signer.secretKey ? old.signer : null,
        userData: old.userData,
        tree: old.tree,
        hints: old.hints
      }
    }

    const flags = c.uint.decode(state)

    if (flags & 1) {
      return {
        external: externalHeader.decode(state),
        key: null,
        manifest: null,
        keyPair: null,
        userData: null,
        tree: null,
        hints: null
      }
    }

    return {
      external: null,
      key: c.fixed32.decode(state),
      manifest: (flags & 2) !== 0 ? manifest.decode(state) : null,
      keyPair: (flags & 4) !== 0 ? keyPair.decode(state) : null,
      userData: keyValueArray.decode(state),
      tree: treeHeader.decode(state),
      hints: hints.decode(state)
    }
  }
}

const uintArray = c.array(c.uint)

const multisigInput = {
  preencode(state, inp) {
    c.uint.preencode(state, inp.signer)
    c.fixed64.preencode(state, inp.signature)
    c.uint.preencode(state, inp.patch)
  },
  encode(state, inp) {
    c.uint.encode(state, inp.signer)
    c.fixed64.encode(state, inp.signature)
    c.uint.encode(state, inp.patch)
  },
  decode(state) {
    return {
      signer: c.uint.decode(state),
      signature: c.fixed64.decode(state),
      patch: c.uint.decode(state)
    }
  }
}

const patchEncodingv0 = {
  preencode(state, n) {
    c.uint.preencode(state, n.start)
    c.uint.preencode(state, n.length)
    uintArray.preencode(state, n.nodes)
  },
  encode(state, n) {
    c.uint.encode(state, n.start)
    c.uint.encode(state, n.length)
    uintArray.encode(state, n.nodes)
  },
  decode(state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state),
      nodes: uintArray.decode(state)
    }
  }
}

const multisigInputv0 = {
  preencode(state, n) {
    state.end++
    c.uint.preencode(state, n.signer)
    c.fixed64.preencode(state, n.signature)
    if (n.patch) patchEncodingv0.preencode(state, n.patch)
  },
  encode(state, n) {
    c.uint.encode(state, n.patch ? 1 : 0)
    c.uint.encode(state, n.signer)
    c.fixed64.encode(state, n.signature)
    if (n.patch) patchEncodingv0.encode(state, n.patch)
  },
  decode(state) {
    const flags = c.uint.decode(state)
    return {
      signer: c.uint.decode(state),
      signature: c.fixed64.decode(state),
      patch: flags & 1 ? patchEncodingv0.decode(state) : null
    }
  }
}

const multisigInputArrayv0 = c.array(multisigInputv0)
const multisigInputArray = c.array(multisigInput)

const compactNode = {
  preencode(state, n) {
    c.uint.preencode(state, n.index)
    c.uint.preencode(state, n.size)
    c.fixed32.preencode(state, n.hash)
  },
  encode(state, n) {
    c.uint.encode(state, n.index)
    c.uint.encode(state, n.size)
    c.fixed32.encode(state, n.hash)
  },
  decode(state) {
    return {
      index: c.uint.decode(state),
      size: c.uint.decode(state),
      hash: c.fixed32.decode(state)
    }
  }
}

const compactNodeArray = c.array(compactNode)

exports.multiSignaturev0 = {
  preencode(state, s) {
    multisigInputArrayv0.preencode(state, s.proofs)
    compactNodeArray.preencode(state, s.patch)
  },
  encode(state, s) {
    multisigInputArrayv0.encode(state, s.proofs)
    compactNodeArray.encode(state, s.patch)
  },
  decode(state) {
    return {
      proofs: multisigInputArrayv0.decode(state),
      patch: compactNodeArray.decode(state)
    }
  }
}

exports.multiSignature = {
  preencode(state, s) {
    multisigInputArray.preencode(state, s.proofs)
    compactNodeArray.preencode(state, s.patch)
  },
  encode(state, s) {
    multisigInputArray.encode(state, s.proofs)
    compactNodeArray.encode(state, s.patch)
  },
  decode(state) {
    return {
      proofs: multisigInputArray.decode(state),
      patch: compactNodeArray.decode(state)
    }
  }
}
const c = require('compact-encoding')
const b4a = require('b4a')
const flat = require('flat-tree')
const { MerkleTree } = require('./merkle-tree')
const { multiSignature, multiSignaturev0 } = require('./messages')

module.exports = {
  assemblev0,
  assemble,
  inflatev0,
  inflate,
  partialSignature,
  signableLength
}

function inflatev0(data) {
  return c.decode(multiSignaturev0, data)
}

function inflate(data) {
  return c.decode(multiSignature, data)
}

async function partialSignature(
  core,
  signer,
  from,
  to = core.state.length,
  signature = core.state.signature
) {
  if (from > core.state.length) return null
  const nodes = to <= from ? null : await upgradeNodes(core, from, to)

  if (signature.byteLength !== 64) {
    signature = c.decode(multiSignature, signature).proofs[0].signature
  }

  return {
    signer,
    signature,
    patch: nodes ? to - from : 0,
    nodes
  }
}

async function upgradeNodes(core, from, to) {
  const rx = core.state.storage.read()
  let p = null
  try {
    p = await MerkleTree.proof(core.state, rx, { upgrade: { start: from, length: to - from } })
  } catch (err) {
    rx.destroy()
    throw err
  }
  rx.tryFlush()
  return (await p.settle()).upgrade.nodes
}

function signableLength(lengths, quorum) {
  if (quorum <= 0) quorum = 1
  if (quorum > lengths.length) return 0

  return lengths.sort(cmp)[quorum - 1]
}

function cmp(a, b) {
  return b - a
}

function assemblev0(inputs) {
  const proofs = []
  const patch = []

  for (const u of inputs) {
    proofs.push(compressProof(u, patch))
  }

  return c.encode(multiSignaturev0, { proofs, patch })
}

function assemble(inputs) {
  const proofs = []
  const patch = []
  const seen = new Set()

  for (const u of inputs) {
    if (u.nodes) {
      for (const node of u.nodes) {
        if (seen.has(node.index)) continue
        seen.add(node.index)
        patch.push(node)
      }
    }

    proofs.push({
      signer: u.signer,
      signature: u.signature,
      patch: u.patch
    })
  }

  return c.encode(multiSignature, { proofs, patch })
}

function compareNode(a, b) {
  if (a.index !== b.index) return false
  if (a.size !== b.size) return false
  return b4a.equals(a.hash, b.hash)
}

function compressProof(proof, nodes) {
  return {
    signer: proof.signer,
    signature: proof.signature,
    patch: proof.patch ? compressUpgrade(proof, nodes) : null
  }
}

function compressUpgrade(p, nodes) {
  const u = {
    start: flat.rightSpan(p.nodes[p.nodes.length - 1].index) / 2 + 1,
    length: p.patch,
    nodes: []
  }

  for (const node of p.nodes) {
    let present = false
    for (let i = 0; i < nodes.length; i++) {
      if (!compareNode(nodes[i], node)) continue

      u.nodes.push(i)
      present = true
      break
    }

    if (present) continue
    u.nodes.push(nodes.push(node) - 1)
  }

  return u
}
module.exports = class Mutex {
  constructor() {
    this.locked = false
    this.destroyed = false

    this._destroying = null
    this._destroyError = null
    this._queue = []
    this._enqueue = (resolve, reject) => this._queue.push([resolve, reject])
  }

  idle() {
    return this._queue.length === 0 && this.locked === false
  }

  lock() {
    if (this.destroyed) {
      return Promise.reject(this._destroyError || new Error('Mutex has been destroyed'))
    }
    if (this.locked) return new Promise(this._enqueue)
    this.locked = true
    return Promise.resolve()
  }

  unlock() {
    if (!this._queue.length) {
      this.locked = false
      return
    }
    this._queue.shift()[0]()
  }

  destroy(err) {
    if (!this._destroying) {
      this._destroying = this.locked ? this.lock().catch(() => {}) : Promise.resolve()
    }

    this.destroyed = true
    if (err) this._destroyError = err

    if (err) {
      while (this._queue.length) this._queue.shift()[1](err)
    }

    return this._destroying
  }
}
const FIFO = require('fast-fifo')

module.exports = class ReceiverQueue {
  constructor() {
    this.queue = new FIFO()
    this.priority = []
    this.requests = new Map()
    this.length = 0
  }

  push(req) {
    // TODO: use a heap at some point if we wanna support multiple prios
    if (req.priority > 0) this.priority.push(req)
    else this.queue.push(req)

    this.requests.set(req.id, req)
    this.length++
  }

  shift() {
    while (this.priority.length > 0) {
      const msg = this.priority.pop()
      const req = this._processRequest(msg)
      if (req !== null) return req
    }

    while (this.queue.length > 0) {
      const msg = this.queue.shift()
      const req = this._processRequest(msg)
      if (req !== null) return req
    }

    return null
  }

  _processRequest(req) {
    if (req.block || req.hash || req.seek || req.upgrade || req.manifest) {
      this.requests.delete(req.id)
      this.length--
      return req
    }

    return null
  }

  clear() {
    this.queue.clear()
    this.priority = []
    this.length = 0
    this.requests.clear()
  }

  delete(id) {
    const req = this.requests.get(id)
    if (!req) return

    req.block = null
    req.hash = null
    req.seek = null
    req.upgrade = null
    req.manifest = false

    this.requests.delete(id)
    this.length--

    if (this.length === 0) {
      this.queue.clear()
      this.priority = []
    }
  }
}
const BigSparseArray = require('big-sparse-array')
const quickbit = require('./compat').quickbit

const BITS_PER_PAGE = 32768
const BYTES_PER_PAGE = BITS_PER_PAGE / 8
const WORDS_PER_PAGE = BYTES_PER_PAGE / 4
const BITS_PER_SEGMENT = 2097152
const BYTES_PER_SEGMENT = BITS_PER_SEGMENT / 8
const PAGES_PER_SEGMENT = BITS_PER_SEGMENT / BITS_PER_PAGE

class RemoteBitfieldPage {
  constructor(index, bitfield, segment) {
    this.index = index
    this.offset = index * BYTES_PER_PAGE - segment.offset
    this.bitfield = bitfield
    this.segment = segment

    segment.add(this)
  }

  get tree() {
    return this.segment.tree
  }

  get(index) {
    return quickbit.get(this.bitfield, index)
  }

  set(index, val) {
    if (quickbit.set(this.bitfield, index, val)) {
      this.tree.update(this.offset * 8 + index)
    }
  }

  setRange(start, end, val) {
    quickbit.fill(this.bitfield, val, start, end)

    let i = Math.floor(start / 128)
    const n = i + Math.ceil((end - start) / 128)

    while (i <= n) this.tree.update(this.offset * 8 + i++ * 128)
  }

  findFirst(val, position) {
    return quickbit.findFirst(this.bitfield, val, position)
  }

  findLast(val, position) {
    return quickbit.findLast(this.bitfield, val, position)
  }

  insert(start, bitfield) {
    this.bitfield.set(bitfield, start / 32)
    this.segment.refresh()
  }

  clear(start, bitfield) {
    quickbit.clear(this.bitfield, { field: bitfield, offset: start })
  }
}

class RemoteBitfieldSegment {
  constructor(index) {
    this.index = index
    this.offset = index * BYTES_PER_SEGMENT
    this.tree = quickbit.Index.from([], BYTES_PER_SEGMENT)
    this.pages = new Array(PAGES_PER_SEGMENT)
    this.pagesLength = 0
  }

  get chunks() {
    return this.tree.chunks
  }

  refresh() {
    this.tree = quickbit.Index.from(this.tree.chunks, BYTES_PER_SEGMENT)
  }

  add(page) {
    const pageIndex = page.index - this.index * PAGES_PER_SEGMENT
    if (pageIndex >= this.pagesLength) this.pagesLength = pageIndex + 1

    this.pages[pageIndex] = page

    const chunk = { field: page.bitfield, offset: page.offset }

    this.chunks.push(chunk)

    for (let i = this.chunks.length - 2; i >= 0; i--) {
      const prev = this.chunks[i]
      if (prev.offset <= chunk.offset) break
      this.chunks[i] = chunk
      this.chunks[i + 1] = prev
    }
  }

  findFirst(val, position) {
    position = this.tree.skipFirst(!val, position)

    let j = position & (BITS_PER_PAGE - 1)
    let i = (position - j) / BITS_PER_PAGE

    if (i >= PAGES_PER_SEGMENT) return -1

    while (i < this.pagesLength) {
      const p = this.pages[i]

      let index = -1

      if (p) index = p.findFirst(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_PAGE + index

      j = 0
      i++
    }

    return val || this.pagesLength === PAGES_PER_SEGMENT ? -1 : this.pagesLength * BITS_PER_PAGE
  }

  findLast(val, position) {
    position = this.tree.skipLast(!val, position)

    let j = position & (BITS_PER_PAGE - 1)
    let i = (position - j) / BITS_PER_PAGE

    if (i >= PAGES_PER_SEGMENT) return -1

    while (i >= 0) {
      const p = this.pages[i]

      let index = -1

      if (p) index = p.findLast(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_PAGE + index

      j = BITS_PER_PAGE - 1
      i--
    }

    return -1
  }
}

module.exports = class RemoteBitfield {
  static BITS_PER_PAGE = BITS_PER_PAGE
  static BITS_PER_SEGMENT = BITS_PER_SEGMENT

  constructor() {
    this._pages = new BigSparseArray()
    this._segments = new BigSparseArray()
    this._maxSegments = 0
  }

  getBitfield(index) {
    const j = index & (BITS_PER_PAGE - 1)
    const i = (index - j) / BITS_PER_PAGE

    const p = this._pages.get(i)
    return p || null
  }

  get(index) {
    const j = index & (BITS_PER_PAGE - 1)
    const i = (index - j) / BITS_PER_PAGE

    const p = this._pages.get(i)

    return p ? p.get(j) : false
  }

  set(index, val) {
    const j = index & (BITS_PER_PAGE - 1)
    const i = (index - j) / BITS_PER_PAGE

    let p = this._pages.get(i)

    if (!p && val) {
      const k = Math.floor(i / PAGES_PER_SEGMENT)
      const s = this._segments.get(k) || this._segments.set(k, new RemoteBitfieldSegment(k))
      if (this._maxSegments <= k) this._maxSegments = k + 1

      p = this._pages.set(i, new RemoteBitfieldPage(i, new Uint32Array(WORDS_PER_PAGE), s))
    }

    if (p) p.set(j, val)
  }

  setRange(start, end, val) {
    let j = start & (BITS_PER_PAGE - 1)
    let i = (start - j) / BITS_PER_PAGE

    while (start < end) {
      let p = this._pages.get(i)

      if (!p && val) {
        const k = Math.floor(i / PAGES_PER_SEGMENT)
        const s = this._segments.get(k) || this._segments.set(k, new RemoteBitfieldSegment(k))
        if (this._maxSegments <= k) this._maxSegments = k + 1

        p = this._pages.set(i, new RemoteBitfieldPage(i, new Uint32Array(WORDS_PER_PAGE), s))
      }

      const offset = i * BITS_PER_PAGE
      const last = Math.min(end - offset, BITS_PER_PAGE)
      const range = last - j

      if (p) p.setRange(j, last, val)

      j = 0
      i++
      start += range
    }
  }

  findFirst(val, position) {
    let j = position & (BITS_PER_SEGMENT - 1)
    let i = (position - j) / BITS_PER_SEGMENT

    while (i < this._maxSegments) {
      const s = this._segments.get(i)

      let index = -1

      if (s) index = s.findFirst(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_SEGMENT + index

      j = 0
      i++
    }

    // For the val === false case, we always return at least
    // the 'position', also if nothing was found
    return val ? -1 : Math.max(position, this._maxSegments * BITS_PER_SEGMENT)
  }

  firstSet(position) {
    return this.findFirst(true, position)
  }

  firstUnset(position) {
    return this.findFirst(false, position)
  }

  findLast(val, position) {
    let j = position & (BITS_PER_SEGMENT - 1)
    let i = (position - j) / BITS_PER_SEGMENT

    while (i >= 0) {
      const s = this._segments.get(i)

      let index = -1

      if (s) index = s.findLast(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_SEGMENT + index

      j = BITS_PER_SEGMENT - 1
      i--
    }

    return -1
  }

  lastSet(position) {
    return this.findLast(true, position)
  }

  lastUnset(position) {
    return this.findLast(false, position)
  }

  insert(start, bitfield) {
    if (start % 32 !== 0) return false

    let length = bitfield.byteLength * 8

    let j = start & (BITS_PER_PAGE - 1)
    let i = (start - j) / BITS_PER_PAGE

    while (length > 0) {
      let p = this._pages.get(i)

      if (!p) {
        const k = Math.floor(i / PAGES_PER_SEGMENT)
        const s = this._segments.get(k) || this._segments.set(k, new RemoteBitfieldSegment(k))
        if (this._maxSegments <= k) this._maxSegments = k + 1

        p = this._pages.set(i, new RemoteBitfieldPage(i, new Uint32Array(WORDS_PER_PAGE), s))
      }

      const end = Math.min(j + length, BITS_PER_PAGE)
      const range = end - j

      p.insert(j, bitfield.subarray(0, range / 32))

      bitfield = bitfield.subarray(range / 32)

      j = 0
      i++
      length -= range
    }

    return true
  }

  clear(start, bitfield) {
    if (start % 32 !== 0) return false

    let length = bitfield.byteLength * 8

    let j = start & (BITS_PER_PAGE - 1)
    let i = (start - j) / BITS_PER_PAGE

    while (length > 0) {
      let p = this._pages.get(i)

      if (!p) {
        const k = Math.floor(i / PAGES_PER_SEGMENT)
        const s = this._segments.get(k) || this._segments.set(k, new RemoteBitfieldSegment(k))
        if (this._maxSegments <= k) this._maxSegments = k + 1

        p = this._pages.set(i, new RemoteBitfieldPage(i, new Uint32Array(WORDS_PER_PAGE), s))
      }

      const end = Math.min(j + length, BITS_PER_PAGE)
      const range = end - j

      p.clear(j, bitfield.subarray(0, range / 32))

      bitfield = bitfield.subarray(range / 32)

      j = 0
      i++
      length -= range
    }

    return true
  }
}
/* DEV DOCS
  Every hypercore has one Replicator object managing its connections to other peers.
  There is one Peer object per peer connected to the Hypercore.
  Hypercores do not know about other hypercores, so when a peer is connected to multiple cores, there exists one Peer object per core.

  Hypercore indicates block should be downloaded through methods like Replicator.addRange or Replicator.addBlock
  Hypercore calls Replicator.updateActivity every time a hypercore session opens/closes
  Replicator.updateActivity ensures the Hypercore is downloading blocks as expected
  Replicator keeps track of:
    - Which blocks need to be downloaded (Replicator._blocks)
    - Which blocks currently have inflight requests (Replicator._inflight)

  Blocks are requested from remote peers by Peer objects. The flow is:
    - The replicator's updatePeer method gets called
    - The replicator detects whether the Peer can accept more requests (for example by checking if it's maxed out on inflight blocks)
    - The replicator then tells the Peer what to request (e.g. Peer_requestRange or Peer._requestBlock methods)

  The Peer object is responsible for tracking
    - Which blocks does the Peer have available (tracked in remoteBitfield)
    - Which blocks are you actively looking for from this peer (tracked in missingBlocks)
    - How many blocks are currently inflight (tracked in inflight)
  The Peer uses this information to decide which blocks to request from the peer in response to _requestRange requests and the like.
*/

const b4a = require('b4a')
const safetyCatch = require('safety-catch')
const RandomIterator = require('random-array-iterator')
const flatTree = require('flat-tree')
const Mutex = require('./mutex')
const ReceiverQueue = require('./receiver-queue')
const HotswapQueue = require('./hotswap-queue')
const RemoteBitfield = require('./remote-bitfield')
const { MerkleTree } = require('./merkle-tree')
const w = require('./wants')
const { LocalWants, RemoteWants } = w
const {
  REQUEST_CANCELLED,
  REQUEST_TIMEOUT,
  INVALID_CAPABILITY,
  SNAPSHOT_NOT_AVAILABLE,
  ASSERTION
} = require('hypercore-errors')
const m = require('./messages')
const caps = require('./caps')

const DEFAULT_MAX_INFLIGHT = [16, 512]
const SCALE_LATENCY = 50
const NOT_DOWNLOADING_SLACK = (20000 + Math.random() * 20000) | 0
const MAX_PEERS_UPGRADE = 3
const LAST_BLOCKS = 256
const MAX_RANGES = 64
const MIN_PEER_UPDATE_ALL = 40

const NOT_AVAILABLE = 1
const INVALID_REQUEST = 2
const MAX_INVALID_REQUESTS = 64
const MAX_BACKOFFS = MAX_INVALID_REQUESTS / 2

const PRIORITY = {
  NORMAL: 0,
  HIGH: 1,
  VERY_HIGH: 2,
  CANCELLED: 255 // reserved to mark cancellation
}

class Attachable {
  constructor(replicator) {
    this.replicator = replicator
    this.resolved = false
    this.processing = false
    this.refs = []
    this.wants = null
  }

  addWant(w) {
    if (this.wants === null) this.wants = new Set()
    this.wants.add(w)
  }

  removeWant(w) {
    if (this.wants === null) return
    this.wants.delete(w)
  }

  attach(session) {
    const r = {
      context: this,
      session,
      sindex: 0,
      rindex: 0,
      snapshot: true,
      resolve: null,
      reject: null,
      promise: null,
      timeout: null
    }

    r.sindex = session.push(r) - 1
    r.rindex = this.refs.push(r) - 1
    r.promise = new Promise((resolve, reject) => {
      r.resolve = resolve
      r.reject = reject
    })

    return r
  }

  detach(r, err = null) {
    if (r.context !== this) return false

    this._detach(r)
    this._cancel(r, err)
    this.gc()

    return true
  }

  _detach(r) {
    const rh = this.refs.pop()
    const sh = r.session.pop()

    if (r.rindex < this.refs.length) this.refs[(rh.rindex = r.rindex)] = rh
    if (r.sindex < r.session.length) r.session[(sh.sindex = r.sindex)] = sh

    destroyRequestTimeout(r)
    r.context = null

    return r
  }

  gc() {
    if (this.refs.length > 0 || this.processing) return
    this._unref()

    if (this.wants === null) return

    const wants = this.wants
    this.wants = null

    let update = null

    for (const w of wants) {
      if (w.any) {
        const removed = w.wants.removeAnyRange(w.start, w.length, this)
        if (!removed) continue
        if (update === null) update = new Set()
        update.add(w.wants.peer)
        // TODO: should also use a free list for simplicity
        w.wants.peer.wireUnwant.send(removed)
        continue
      }

      if (w.wants.removeBatch(w.start, this)) {
        if (update === null) update = new Set()
        update.add(w.wants.peer)
      }
    }

    if (update === null) return
    for (const peer of update) {
      this.replicator.updatePeer(peer)
    }
  }

  processed() {
    this.processing = false
    this.gc()
  }

  _cancel(r, err) {
    r.reject(err || REQUEST_CANCELLED())
  }

  _unref() {
    // overwrite me
  }

  resolve(val) {
    this.resolved = true
    while (this.refs.length > 0) {
      this._detach(this.refs[this.refs.length - 1]).resolve(val)
    }
    this.gc()
  }

  reject(err) {
    this.resolved = true
    while (this.refs.length > 0) {
      this._detach(this.refs[this.refs.length - 1]).reject(err)
    }
    this.gc()
  }

  setTimeout(r, ms) {
    destroyRequestTimeout(r)
    r.timeout = setTimeout(onrequesttimeout, ms, r)
  }
}

class BlockRequest extends Attachable {
  constructor(replicator, tracker, index, priority, force) {
    super(replicator)

    this.index = index
    this.priority = priority
    this.inflight = []
    this.queued = false
    this.hotswap = null
    this.tracker = tracker
    this.force = force
  }

  _unref() {
    if (this.resolved) return
    this.queued = false

    for (const req of this.inflight) {
      req.peer._cancelRequest(req)
    }

    this.tracker.remove(this.index)
    removeHotswap(this)
  }
}

class RangeBatchRequest extends Attachable {
  constructor(replicator, batch) {
    super(replicator)

    this.batch = batch
    this.index = 0
  }
}

class RangeRequest extends Attachable {
  constructor(replicator, ranges, start, end, linear, blocks) {
    super(replicator)

    this.start = start
    this.end = end
    this.linear = linear
    this.blocks = blocks
    this.ranges = ranges
    this.batches = []

    ranges.push(this)

    if (this.end === -1) {
      this.replicator._alwaysLatestBlock++
    }

    // As passed by the user, immut
    this.userStart = start
    this.userEnd = end
  }

  addBatch(batch) {
    for (let i = 0; i < this.batches.length; i++) {
      const b = this.batches[i]
      if (b.batch === batch) return false
    }
    const b = new RangeBatchRequest(this.replicator, batch)
    b.index = this.batches.length
    this.batches.push(b)
    return true
  }

  removeBatch(batch) {
    const head = this.batches.pop()

    if (head !== batch) {
      head.index = batch.index
      this.batches[head.index] = head
    }

    batch.gc()
  }

  _unref() {
    const rangeIndex = this.ranges.indexOf(this)
    if (rangeIndex === -1) return

    const h = this.ranges.pop()
    if (h !== this) {
      this.ranges[rangeIndex] = h
    }

    if (this.end === -1) {
      this.replicator._alwaysLatestBlock--
    }

    while (this.batches.length) {
      this.batches.pop().gc()
    }
  }

  _cancel(r) {
    r.resolve(false)
  }
}

class UpgradeRequest extends Attachable {
  constructor(replicator, fork, length) {
    super(replicator)

    this.fork = fork
    this.length = length
    this.inflight = []
  }

  _unref() {
    if (this.resolved) return
    if (this.replicator.eagerUpgrade === true || this.inflight.length > 0) return
    this.replicator._upgrade = null
  }

  _cancel(r) {
    r.resolve(false)
  }
}

class SeekRequest extends Attachable {
  constructor(replicator, seeks, seeker) {
    super(replicator)

    this.seeker = seeker
    this.inflight = []
    this.seeks = seeks
  }

  _unref() {
    if (this.resolved) return
    if (this.inflight.length > 0) return
    const i = this.seeks.indexOf(this)
    if (i === -1) return
    const h = this.seeks.pop()
    if (i < this.seeks.length) this.seeks[i] = h
  }
}

class ForkRequest extends Attachable {
  constructor(replicator, fork) {
    super(replicator)
    this.fork = fork
    this.inflight = []
    this.batch = null
  }
}

class InflightTracker {
  constructor() {
    this._requests = []
    this._free = []
    this._active = 0
  }

  get idle() {
    return this._active === 0
  }

  *[Symbol.iterator]() {
    for (const req of this._requests) {
      if (req !== null) yield req
    }
  }

  add(req) {
    const id = this._free.length ? this._free.pop() : this._requests.push(null)
    req.id = id
    this._requests[id - 1] = req
    this._active++
    return req
  }

  get(id) {
    return id <= this._requests.length ? this._requests[id - 1] : null
  }

  remove(id, roundtrip) {
    if (id > this._requests.length) return
    if (this._requests[id - 1]) this._active--
    this._requests[id - 1] = null
    if (roundtrip === true) this._free.push(id)
  }

  reusable(id) {
    this._free.push(id)
  }
}

class BlockTracker {
  constructor(replicator) {
    this._replicator = replicator
    this._map = new Map()
  }

  [Symbol.iterator]() {
    return this._map.values()
  }

  isEmpty() {
    return this._map.size === 0
  }

  has(index) {
    return this._map.has(index)
  }

  get(index) {
    return this._map.get(index) || null
  }

  add(index, priority, force) {
    let b = this._map.get(index)
    if (b) return b

    b = new BlockRequest(this._replicator, this, index, priority, force)
    this._map.set(index, b)

    return b
  }

  remove(index) {
    const b = this.get(index)
    this._map.delete(index)
    return b
  }
}

class RoundtripQueue {
  constructor() {
    this.queue = []
    this.tick = 0
  }

  clear() {
    const ids = new Array(this.queue.length)
    for (let i = 0; i < ids.length; i++) {
      ids[i] = this.queue[i][1]
    }

    this.queue = []

    return ids
  }

  add(id) {
    this.queue.push([++this.tick, id])
  }

  flush(tick) {
    let flushed = null

    for (let i = 0; i < this.queue.length; i++) {
      if (this.queue[i][0] > tick) break
      if (flushed === null) flushed = []
      flushed.push(this.queue[i][1])
    }

    if (flushed !== null) this.queue.splice(0, flushed.length)
    return flushed
  }
}

class ProofRequest {
  constructor(msg, proof, block, manifest) {
    this.msg = msg
    this.proof = proof
    this.block = block
    this.manifest = manifest
  }

  async fulfill() {
    if (this.proof === null) return null

    const [proof, block] = await Promise.all([this.proof.settle(), this.block])

    if (this.manifest) proof.manifest = this.manifest
    if (!block && proof.block) return null

    if (block) proof.block.value = block
    return proof
  }
}

class Peer {
  constructor(replicator, protomux, channel, inflightRange) {
    this.core = replicator.core
    this.replicator = replicator
    this.stream = protomux.stream
    this.protomux = protomux
    this.remotePublicKey = this.stream.remotePublicKey
    this.remoteSupportsSeeks = false
    this.inflightRange = inflightRange
    this.fullyDownloadedSignaled = 0

    this.paused = false
    this.removed = false

    this.channel = channel
    this.channel.userData = this

    this.wireSync = this.channel.messages[0]
    this.wireRequest = this.channel.messages[1]
    this.wireCancel = this.channel.messages[2]
    this.wireData = this.channel.messages[3]
    this.wireNoData = this.channel.messages[4]
    this.wireWant = this.channel.messages[5]
    this.wireUnwant = this.channel.messages[6]
    this.wireBitfield = this.channel.messages[7]
    this.wireRange = this.channel.messages[8]
    this.wireExtension = this.channel.messages[9]

    // Same stats as replicator, but for this specific peer
    this.stats = {
      wireSync: { tx: 0, rx: 0 },
      wireRequest: { tx: 0, rx: 0 },
      wireCancel: { tx: 0, rx: 0 },
      wireData: { tx: 0, rx: 0 },
      wireWant: { tx: 0, rx: 0 },
      wireUnwant: { tx: 0, rx: 0 },
      wireBitfield: { tx: 0, rx: 0 },
      wireRange: { tx: 0, rx: 0 },
      wireExtension: { tx: 0, rx: 0 },
      hotswaps: 0,
      invalidData: 0,
      invalidRequests: 0,
      backoffs: 0,
      notAvailableBackoffs: 0
    }

    this.receiverQueue = new ReceiverQueue()
    this.receiverBusy = false

    // most often not used, so made on demand
    this.roundtripQueue = null

    this.inflight = 0
    this.dataProcessing = 0

    this.canUpgrade = true

    this.needsSync = false
    this.syncsProcessing = 0
    this.lastUpgradableLength = 0
    this.lastUpgradableFork = 0

    this._remoteContiguousLength = 0

    // TODO: tweak pipelining so that data sent BEFORE remoteOpened is not cap verified!
    // we might wanna tweak that with some crypto, ie use the cap to encrypt it...
    // or just be aware of that, to only push non leaky data

    this.remoteOpened = false
    this.remoteBitfield = new RemoteBitfield()
    this.missingBlocks = new RemoteBitfield()

    this.pushedLength = 0

    this.remoteFork = 0
    this.remoteLength = 0
    this.remoteCanUpgrade = false
    this.remoteUploading = true
    this.remoteDownloading = true
    this.remoteSynced = false
    this.remoteHasManifest = false
    this.remoteAllowPush = false
    this.remoteRequests = new Map()

    this.segmentsWanted = new Set()
    this.broadcastedNonSparse = false

    this.wants = new LocalWants(this)
    this.remoteWants = new RemoteWants(this)

    this.lengthAcked = 0

    this.extensions = new Map()
    this.lastExtensionSent = ''
    this.lastExtensionRecv = ''

    replicator._ifAvailable++
    replicator._active++
  }

  get remoteContiguousLength() {
    return this.remoteBitfield.findFirst(false, this._remoteContiguousLength)
  }

  getMaxInflight() {
    const stream = this.stream.rawStream
    if (!stream.udx) return Math.min(this.inflightRange[1], this.inflightRange[0] * 3)

    const scale =
      stream.rtt <= SCALE_LATENCY
        ? 1
        : (stream.rtt / SCALE_LATENCY) * Math.min(1, 2 / this.replicator.peers.length)
    return Math.max(
      this.inflightRange[0],
      Math.round(Math.min(this.inflightRange[1], this.inflightRange[0] * scale))
    )
  }

  getMaxHotswapInflight() {
    const inf = this.getMaxInflight()
    return Math.max(16, inf / 2)
  }

  signalUpgrade() {
    if (this._shouldUpdateCanUpgrade() === true) this._updateCanUpgradeAndSync()
    else this.sendSync()
  }

  _markInflight(index) {
    this.missingBlocks.set(index, false)
  }

  broadcastRange(start, length, drop) {
    if (!this.isActive()) return

    if (drop) this._unclearLocalRange(start, length)
    else this._clearLocalRange(start, length)

    const fullyContig = this.core.header.hints.contiguousLength === this.core.state.length

    if (start + LAST_BLOCKS < this.core.state.length && !drop && !fullyContig) {
      if (!this.remoteWants.hasRange(start, length)) return
    }

    let force = false
    if (fullyContig && !drop) {
      start = 0
      length = this.core.state.length

      // Always send the broadcast when we switch from sparse to fully contiguous, so remote knows too
      if (this.fullyDownloadedSignaled < length) {
        this.fullyDownloadedSignaled = length
        force = true
      }
    }

    // TODO: consider also adding early-returns on the drop===true case
    if (!force && !drop) {
      // No need to broadcast if the remote already has this range

      if (this._remoteContiguousLength >= start + length) return

      if (length === 1) {
        if (this.remoteBitfield.get(start)) return
      } else {
        if (this.remoteBitfield.firstUnset(start) >= start + length) return
      }
    }

    this.wireRange.send({
      drop,
      start,
      length
    })
    incrementTx(this.stats.wireRange, this.replicator.stats.wireRange)
  }

  extension(name, message) {
    this.wireExtension.send({ name: name === this.lastExtensionSent ? '' : name, message })
    incrementTx(this.stats.wireExtension, this.replicator.stats.wireExtension)
    this.lastExtensionSent = name
  }

  onextension(message) {
    const name = message.name || this.lastExtensionRecv
    this.lastExtensionRecv = name
    const ext = this.extensions.get(name)
    if (ext) {
      ext._onmessage({ start: 0, end: message.message.byteLength, buffer: message.message }, this)
    }
  }

  sendSync() {
    // Skip syncs if in repair mode
    if (this.core._repairMode) return

    if (this.syncsProcessing !== 0) {
      this.needsSync = true
      return
    }

    if (this.core.state.fork !== this.remoteFork) {
      this.canUpgrade = false
    }

    this.needsSync = false

    this.wireSync.send({
      fork: this.core.state.fork,
      length: this.core.state.length,
      remoteLength: this.core.state.fork === this.remoteFork ? this.remoteLength : 0,
      canUpgrade: this.canUpgrade,
      uploading: true,
      downloading: this.replicator.isDownloading(),
      hasManifest: !!this.core.header.manifest && this.core.compat === false,
      allowPush: this.replicator.isAllowingPush()
    })
    incrementTx(this.stats.wireSync, this.replicator.stats.wireSync)
  }

  onopen({ seeks, capability }) {
    const expected = caps.replicate(
      this.stream.isInitiator === false,
      this.core.key,
      this.stream.handshakeHash
    )

    if (b4a.equals(capability, expected) !== true) {
      // TODO: change this to a rejection instead, less leakage
      throw INVALID_CAPABILITY('Remote sent an invalid replication capability')
    }

    if (this.remoteOpened === true) return
    this.remoteOpened = true
    this.remoteSupportsSeeks = seeks

    this.protomux.cork()

    this.sendSync()

    const contig = Math.min(this.core.state.length, this.core.header.hints.contiguousLength)
    if (contig > 0) {
      this.broadcastRange(0, contig, false)

      if (contig === this.core.state.length) {
        this.broadcastedNonSparse = true
      }
    }

    this.replicator._ifAvailable--
    this.replicator._addPeer(this)

    this.protomux.uncork()

    this.core.checkIfIdle()
  }

  onclose(isRemote) {
    // we might have signalled to the remote that we are done (ie not downloading) and the remote might agree on that
    // if that happens, the channel might be closed by the remote. if so just renegotiate it.
    // TODO: add a CLOSE_REASON to mux to we can make this cleaner...
    const reopen =
      isRemote === true &&
      this.remoteOpened === true &&
      this.remoteDownloading === false &&
      this.remoteUploading === true &&
      this.replicator.downloading === true

    if (this.remoteOpened === false) {
      this.replicator._ifAvailable--
      this.replicator.queueUpdateAll()
      return
    }

    this.remoteOpened = false
    this.removed = true
    this.remoteRequests.clear() // cancel all
    this.receiverQueue.clear()

    if (this.roundtripQueue !== null) {
      for (const id of this.roundtripQueue.clear()) this.replicator._inflight.reusable(id)
    }

    this.replicator._removePeer(this)

    if (reopen) {
      this.replicator._makePeer(this.protomux)
    }
  }

  closeIfIdle() {
    if (this.remoteDownloading === false && this.replicator.isDownloading() === false) {
      // idling, shut it down...
      this.channel.close()
      return true
    }

    return false
  }

  async onsync(msg) {
    const {
      fork,
      length,
      remoteLength,
      canUpgrade,
      uploading,
      downloading,
      hasManifest,
      allowPush
    } = msg

    const lengthChanged = length !== this.remoteLength
    const sameFork = fork === this.core.state.fork

    this.remoteSynced = true
    this.remoteFork = fork
    this.remoteLength = length
    this.remoteCanUpgrade = canUpgrade
    this.remoteUploading = uploading
    this.remoteDownloading = downloading
    this.remoteHasManifest = hasManifest
    this.remoteAllowPush = allowPush

    if (this.closeIfIdle()) return

    this.lengthAcked = sameFork ? remoteLength : 0
    this.syncsProcessing++

    this.replicator._updateFork(this)

    if (this.remoteLength > this.core.state.length && this.lengthAcked === this.core.state.length) {
      if (this.replicator._addUpgradeMaybe() !== null) this._update()
    }

    const upgrade =
      lengthChanged === false || sameFork === false
        ? this.canUpgrade && sameFork
        : await this._canUpgrade(length, fork)

    if (length === this.remoteLength && fork === this.core.state.fork) {
      this.canUpgrade = upgrade
      if (upgrade) {
        this.lastUpgradableFork = fork
        this.lastUpgradableLength = length
      }
    }

    if (--this.syncsProcessing !== 0) return // ie not latest

    if (
      this.needsSync === true ||
      (this.core.state.fork === this.remoteFork && this.core.state.length > this.remoteLength)
    ) {
      this.signalUpgrade()
    }

    this._update()
  }

  _shouldUpdateCanUpgrade() {
    return (
      this.core.state.fork === this.remoteFork &&
      this.core.state.length > this.remoteLength &&
      this.canUpgrade === false &&
      this.syncsProcessing === 0
    )
  }

  async _updateCanUpgradeAndSync() {
    const { length, fork } = this.core.state

    const remoteLength = this.remoteLength
    const remoteFork = this.remoteFork
    const canUpgrade = await this._canUpgrade(this.remoteLength, this.remoteFork)

    if (
      this.syncsProcessing > 0 ||
      length !== this.core.state.length ||
      fork !== this.core.state.fork
    ) {
      return
    }
    if (remoteLength !== this.remoteLength || remoteFork !== this.remoteFork) {
      return
    }
    if (canUpgrade === this.canUpgrade) {
      return
    }

    this.canUpgrade = canUpgrade
    if (canUpgrade) {
      this.lastUpgradableLength = this.remoteLength
      this.lastUpgradableFork = this.remoteFork
    }

    this.sendSync()
  }

  // Safe to call in the background - never fails
  async _canUpgrade(remoteLength, remoteFork) {
    if (remoteFork !== this.core.state.fork) return false

    if (remoteLength === 0) return true
    if (remoteLength >= this.core.state.length) return false

    try {
      // Rely on caching to make sure this is cheap...
      const canUpgrade = await MerkleTree.upgradeable(this.core.state, remoteLength)

      if (remoteFork !== this.core.state.fork) return false

      return canUpgrade
    } catch {
      return false
    }
  }

  async _getProof(batch, msg, pushing) {
    let block = null

    if (msg.block) {
      const index = msg.block.index

      if (!pushing && (msg.fork !== this.core.state.fork || !this.core.bitfield.get(index))) {
        return new ProofRequest(msg, null, null, null)
      }

      block = batch.getBlock(index)
      block.catch(noop)
    }

    const manifest = msg.manifest && !this.core.compat ? this.core.header.manifest : null

    try {
      const proof = await MerkleTree.proof(this.core.state, batch, msg)
      return new ProofRequest(msg, proof, block, manifest)
    } catch (err) {
      batch.destroy()

      this.replicator._oninvalidrequest(err, msg, this)

      if (this.stats.invalidRequests >= MAX_INVALID_REQUESTS) throw err

      await backoff(this.stats.invalidRequests)
      return null
    }
  }

  async onrequest(msg) {
    const size = this.remoteRequests.size
    this.remoteRequests.set(msg.id, msg)

    // if size didnt change -> id overwrite -> old one is deleted, cancel current and re-add
    if (size === this.remoteRequests.size) {
      this._cancel(msg.id)
      this.remoteRequests.set(msg.id, msg)
    }

    if (!this.protomux.drained || this.receiverQueue.length) {
      this.receiverQueue.push(msg)
      return
    }

    if (this.replicator.destroyed) return

    await this._handleRequest(msg)
  }

  oncancel(msg) {
    this._cancel(msg.request)
  }

  _cancel(id) {
    this.remoteRequests.delete(id)
    this.receiverQueue.delete(id)
  }

  ondrain() {
    return this._handleRequests()
  }

  async _handleRequests() {
    if (this.receiverBusy || this.replicator.destroyed) return
    this.receiverBusy = true
    this.protomux.cork()

    while (
      this.remoteOpened &&
      this.protomux.drained &&
      this.receiverQueue.length > 0 &&
      !this.removed
    ) {
      const msg = this.receiverQueue.shift()
      await this._handleRequest(msg)
    }

    this.protomux.uncork()
    this.receiverBusy = false
  }

  async push(index) {
    if (!this.remoteAllowPush) return
    if (!this.remoteDownloading) return
    if (this.core.state.length <= index) return
    if (this.core.state.fork !== this.remoteFork) return
    if (this.remoteBitfield.get(index)) return

    const msg = {
      id: 0,
      fork: this.core.state.fork,
      block: null,
      hash: null,
      seek: null,
      upgrade: null,
      manifest: this.remoteLength === 0,
      priority: 0
    }

    await this.replicator._txLock.lock()
    try {
      const remoteLength = Math.max(this.remoteLength, this.pushedLength)

      msg.block = {
        index,
        nodes: MerkleTree.maxMissingNodes(2 * index, remoteLength)
      }

      if (index >= remoteLength) {
        msg.upgrade = {
          start: remoteLength,
          length: this.core.state.length - remoteLength
        }
      }

      let req = null
      const batch = this.core.storage.read()
      try {
        req = await this._getProof(batch, msg, true)
      } catch (err) {
        this.replicator._oninvalidrequest(err, msg, this)
        return
      }

      if (req === null) return
      batch.tryFlush()

      await this._fulfillRequest(req, true)
    } finally {
      this.replicator._txLock.unlock()
    }
  }

  async _handleRequest(msg) {
    const locked = !!msg.upgrade && this.remoteAllowPush

    if (locked) {
      // ensure contig push proofs
      await this.replicator._txLock.lock()
      const end = msg.upgrade.start + msg.upgrade.length

      if (this.pushedLength < end) {
        msg.upgrade.start = this.pushedLength
        msg.upgrade.length = end - this.pushedLength
      }
    }

    try {
      const batch = this.core.storage.read()

      // TODO: could still be answerable if (index, fork) is an ancestor of the current fork
      const req =
        msg.fork === this.core.state.fork
          ? await this._getProof(batch, msg, false)
          : new ProofRequest(msg, null, null, null)

      if (req === null) {
        this.wireNoData.send({ request: msg.id, reason: INVALID_REQUEST })
        return
      }

      batch.tryFlush()

      await this._fulfillRequest(req, false)
    } finally {
      if (locked) this.replicator._txLock.unlock()
    }
  }

  async _fulfillRequest(req, pushing) {
    if (this.core._repairMode) {
      // if cancelled do not reply
      if (this.remoteRequests.get(req.msg.id) !== req.msg) {
        return
      }

      // sync from now on, so safe to delete from the map
      this.remoteRequests.delete(req.msg.id)

      // If cutting off the fulfillment, ensure promise is caught.
      // While repairing merkle tree nodes can be `nil` so can throw.
      req.fulfill().catch(safetyCatch)
      return
    }

    const proof = await req.fulfill()

    if (!pushing) {
      // if cancelled do not reply
      if (this.remoteRequests.get(req.msg.id) !== req.msg) {
        return
      }

      // sync from now on, so safe to delete from the map
      this.remoteRequests.delete(req.msg.id)
    } else if (!this.remoteAllowPush) {
      // if pushing but remote disabled it, just drop it
      return
    }

    if (!this.isActive() && proof.block !== null) {
      return
    }

    if (proof === null) {
      if (req.msg.manifest && this.core.header.manifest) {
        const manifest = this.core.header.manifest
        this.wireData.send({
          request: req.msg.id,
          fork: this.core.state.fork,
          block: null,
          hash: null,
          seek: null,
          upgrade: null,
          manifest
        })
        incrementTx(this.stats.wireData, this.replicator.stats.wireData)
        return
      }

      this.wireNoData.send({ request: req.msg.id, reason: NOT_AVAILABLE })
      return
    }

    if (proof.block !== null) {
      this.replicator._onupload(proof.block.index, proof.block.value.byteLength, this)
    }

    if (proof.upgrade) {
      const remoteLength = MerkleTree.upgradeLength(proof.upgrade)
      if (remoteLength > this.pushedLength) this.pushedLength = remoteLength
    }

    this.wireData.send({
      request: req.msg.id,
      fork: req.msg.fork,
      block: proof.block,
      hash: proof.hash,
      seek: proof.seek,
      upgrade: proof.upgrade,
      manifest: proof.manifest
    })
    incrementTx(this.stats.wireData, this.replicator.stats.wireData)
  }

  _cancelRequest(req) {
    if (req.priority === PRIORITY.CANCELLED) return
    // mark as cancelled also and avoid re-entry
    req.priority = PRIORITY.CANCELLED

    this.inflight--
    this.replicator._requestDone(req.id, false)

    // clear inflight state
    if (isBlockRequest(req)) this.replicator._unmarkInflight(req.block.index)
    if (isUpgradeRequest(req)) this.replicator._clearInflightUpgrade(req)

    if (this.roundtripQueue === null) this.roundtripQueue = new RoundtripQueue()
    this.roundtripQueue.add(req.id)
    this.wireCancel.send({ request: req.id })
    incrementTx(this.stats.wireCancel, this.replicator.stats.wireCancel)
  }

  _checkIfConflict() {
    this.paused = true

    const length = Math.min(this.core.state.length, this.remoteLength)
    if (length === 0) return // pause and ignore

    this.wireRequest.send({
      id: 0, // TODO: use an more explicit id for this eventually...
      fork: this.remoteFork,
      block: null,
      hash: null,
      seek: null,
      upgrade: {
        start: 0,
        length
      }
    })

    incrementTx(this.stats.wireRequest, this.replicator.stats.wireRequest)
  }

  _unmarkInflightBlockRequest(req, data) {
    if (isBlockRequest(req)) this.replicator._unmarkInflight(req.block.index)
    else if (data.block && !req) this.replicator._unmarkInflight(data.block.index)
  }

  async ondata(data) {
    if (data.request !== 0 && !data.upgrade) return this._handleData(data)

    await this.replicator._rxLock.lock()
    try {
      await this._handleData(data)
    } finally {
      this.replicator._rxLock.unlock()
    }
  }

  async _handleData(data) {
    // always allow a fork conflict proof to be sent
    if (data.request === 0 && data.upgrade && data.upgrade.start === 0) {
      if (await this.core.checkConflict(data, this)) return
      this.paused = false
    }

    const req = data.request > 0 ? this.replicator._inflight.get(data.request) : null
    const reorg = data.fork > this.core.state.fork

    // no push atm, TODO: check if this satisfies another pending request
    // allow reorg pushes tho as those are not written to storage so we'll take all the help we can get
    if (req === null && reorg === false && !this.replicator.allowPush) {
      return
    }

    // Skip accepting data if in repair mode to avoid corruption
    if (this.core._repairMode) {
      this.replicator._onnodata(this, req, NOT_AVAILABLE)
      return
    }

    if (req === null && reorg === false && data.block) {
      // mark this as inflight to avoid parallel requests
      this.replicator._markInflight(data.block.index)
    }

    if (req !== null) {
      if (req.peer !== this) return
      this._onrequestroundtrip(req)
    }

    try {
      if (reorg === true) return await this.replicator._onreorgdata(this, req, data)
    } catch (err) {
      safetyCatch(err)
      this._unmarkInflightBlockRequest(req, data)

      this.paused = true
      this.replicator._oninvaliddata(err, req, data, this)
      return
    }

    this.dataProcessing++
    if (isBlockRequest(req)) this.replicator._markProcessing(req.block.index)

    try {
      if (!this.replicator._matchingRequest(req, data) || !(await this.core.verify(data, this))) {
        this.replicator._onnodata(this, req, 0)
        return
      }
    } catch (err) {
      safetyCatch(err)
      this._unmarkInflightBlockRequest(req, data)

      if (err.code === 'WRITE_FAILED') {
        // For example, we don't want to keep pulling data when storage is full
        // TODO: notify the user somehow
        this.paused = true
        return
      }

      if (this.core.closed && !isCriticalError(err)) return

      if (err.code !== 'INVALID_OPERATION') {
        // might be a fork, verify
        this._checkIfConflict()
      }

      // if push mode, we MIGHT get an occasional bad message
      // no need to mega bail for that. TODO: rate limit instead as a general thing
      if (!this.replicator.allowPush) {
        this.paused = true
      }

      this.replicator._onnodata(this, req, 0)
      this.replicator._oninvaliddata(err, req, data, this)
      return
    } finally {
      if (isBlockRequest(req)) this.replicator._markProcessed(req.block.index)
      this.dataProcessing--
    }

    this.replicator._ondata(this, req, data)

    if (this._shouldUpdateCanUpgrade() === true) {
      this._updateCanUpgradeAndSync()
    }
  }

  onnodata({ request, reason }) {
    const req = request > 0 ? this.replicator._inflight.get(request) : null

    if (req === null || req.peer !== this) {
      this.replicator.queueUpdateAll()
      return
    }

    this._onrequestroundtrip(req)
    this.replicator._onnodata(this, req, reason)
  }

  _onrequestroundtrip(req) {
    if (req.priority === PRIORITY.CANCELLED) return
    // to avoid re-entry we also just mark it as cancelled
    req.priority = PRIORITY.CANCELLED

    this.inflight--
    this.replicator._requestDone(req.id, true)
    if (this.roundtripQueue === null) return
    const flushed = this.roundtripQueue.flush(req.rt)
    if (flushed === null) return
    for (const id of flushed) this.replicator._inflight.reusable(id)
  }

  onwant(range) {
    if (!this.remoteWants.add(range)) return
    this.replicator._onwant(this, range.start, range.length, range.any)
  }

  onunwant(range) {
    this.remoteWants.remove(range)
  }

  onbitfield({ start, bitfield }) {
    if (start < this._remoteContiguousLength) this._remoteContiguousLength = start // bitfield is always the truth
    this.remoteBitfield.insert(start, bitfield)
    this.missingBlocks.insert(start, bitfield)
    this._clearLocalRange(start, bitfield.byteLength * 8)
    this._update()
  }

  _clearLocalRange(start, length) {
    const bitfield = this.core.skipBitfield === null ? this.core.bitfield : this.core.skipBitfield

    if (length === 1) {
      this.missingBlocks.set(start, this._remoteHasBlock(start) && !bitfield.get(start))
      return
    }

    const contig = Math.min(this.core.state.length, this.core.header.hints.contiguousLength)

    if (start + length < contig) {
      this.missingBlocks.setRange(start, contig, false)
      return
    }

    const rem = start & 32767
    if (rem > 0) {
      start -= rem
      length += rem
    }

    const end = start + Math.min(length, this.core.state.length)
    while (start < end) {
      const local = bitfield.getBitfield(start)

      if (local && local.bitfield) {
        this.missingBlocks.clear(start, local.bitfield)
      }

      start += 32768
    }
  }

  _resetMissingBlock(index) {
    const bitfield = this.core.skipBitfield === null ? this.core.bitfield : this.core.skipBitfield
    this.missingBlocks.set(index, this._remoteHasBlock(index) && !bitfield.get(index))
  }

  _unclearLocalRange(start, length) {
    if (length === 1) {
      this._resetMissingBlock(start)
      return
    }

    const rem = start & (RemoteBitfield.BITS_PER_SEGMENT - 1)
    if (rem > 0) {
      start -= rem
      length += rem
    }

    const fixedStart = start

    const end = start + Math.min(length, this.remoteLength)
    while (start < end) {
      const remote = this.remoteBitfield.getBitfield(start)
      if (remote && remote.bitfield) {
        this.missingBlocks.insert(start, remote.bitfield)
      }

      start += RemoteBitfield.BITS_PER_SEGMENT
    }

    this._clearLocalRange(fixedStart, length)
  }

  async onrange({ drop, start, length }) {
    const has = drop === false

    if (drop === true && start < this._remoteContiguousLength) {
      this._remoteContiguousLength = start
    }

    if (start === 0 && drop === false) {
      if (length > this._remoteContiguousLength) {
        this._remoteContiguousLength = length
        if (
          this.remoteFork === this.core.state.fork &&
          length > this.core.header.hints.remoteContiguousLength
        ) {
          this.core.updateRemoteContiguousLength(length)
        }
      }
    } else if (length === 1) {
      const bitfield = this.core.skipBitfield === null ? this.core.bitfield : this.core.skipBitfield
      this.remoteBitfield.set(start, has)
      this.missingBlocks.set(start, has && !bitfield.get(start))
    } else {
      const rangeStart = this.remoteBitfield.findFirst(!has, start)
      const rangeEnd = length + start

      if (rangeStart !== -1 && rangeStart < rangeEnd) {
        this.remoteBitfield.setRange(rangeStart, rangeEnd, has)
        this.missingBlocks.setRange(rangeStart, rangeEnd, has)
        if (has) this._clearLocalRange(rangeStart, rangeEnd - rangeStart)
      }
    }

    if (this.core.hintsChanged) await this.core.flushHints()
    if (drop === false) this._update()

    this.core.emitRemoteContiguousLength()
  }

  onreorghint() {
    // TODO
  }

  _update() {
    // TODO: if this is in a batch or similar it would be better to defer it
    // we could do that with nextTick/microtick mb? (combined with a property on the session to signal read buffer mb)
    this.replicator.updatePeer(this)
  }

  async _onconflict() {
    this.protomux.cork()
    if (this.remoteLength > 0 && this.core.state.fork === this.remoteFork) {
      await this.onrequest({
        id: 0,
        fork: this.core.state.fork,
        block: null,
        hash: null,
        seek: null,
        upgrade: {
          start: 0,
          length: Math.min(this.core.state.length, this.remoteLength)
        }
      })
    }
    this.channel.close()
    this.protomux.uncork()
  }

  _makeRequest(needsUpgrade, priority, minLength) {
    if (needsUpgrade === true && this.replicator._shouldUpgrade(this) === false) {
      return null
    }

    // ensure that the remote has signalled they have the length we request
    if (this.remoteLength < minLength) {
      return null
    }

    if (needsUpgrade === false && this.replicator._autoUpgrade(this) === true) {
      needsUpgrade = true
    }

    return {
      peer: this,
      rt: this.roundtripQueue === null ? 0 : this.roundtripQueue.tick,
      id: 0,
      fork: this.remoteFork,
      block: null,
      hash: null,
      seek: null,
      upgrade:
        needsUpgrade === false
          ? null
          : { start: this.core.state.length, length: this.remoteLength - this.core.state.length },
      // remote manifest check can be removed eventually...
      manifest: this.core.header.manifest === null && this.remoteHasManifest === true,
      priority,
      timestamp: Date.now(),
      elapsed: 0
    }
  }

  _requestManifest() {
    const req = this._makeRequest(false, 0, 0)
    if (req === null) return

    this._send(req)
  }

  _includeLastBlock() {
    if (this.replicator._alwaysLatestBlock === 0) return null

    const index = this.remoteLength - 1

    // only valid if its an OOB get
    if (index < this.core.state.length) return null

    // do the normal checks
    if (!this._remoteHasBlock(index)) return null
    if (!this._canRequest(index, false)) return null

    // atm we only ever do one upgrade request in parallel, if that changes
    // then we should add some check here for inflights to avoid over requesting
    const b = this.replicator._blocks.add(index, PRIORITY.NORMAL, false)
    return b
  }

  _requestUpgrade(u) {
    if (this.replicator.pushOnly) return false

    const req = this._makeRequest(true, 0, 0)
    if (req === null) return false

    const b = this._includeLastBlock()

    if (b) this._sendBlockRequest(req, b)
    else this._send(req)

    return true
  }

  _requestSeek(s) {
    // if replicator is updating the seeks etc, bail and wait for it to drain
    if (this.replicator._updatesPending > 0) return false
    if (this.replicator.pushOnly) return false

    const { length, fork } = this.core.state

    if (fork !== this.remoteFork) return false

    if (s.seeker.start >= length) {
      const req = this._makeRequest(true, 0, 0)

      // We need an upgrade for the seek, if non can be provided, skip
      if (req === null) return false

      req.seek = this.remoteSupportsSeeks
        ? { bytes: s.seeker.bytes, padding: s.seeker.padding }
        : null

      s.inflight.push(req)
      this._send(req)

      return true
    }

    const len = s.seeker.end - s.seeker.start
    const off = s.seeker.start + Math.floor(Math.random() * len)

    for (let i = 0; i < len; i++) {
      let index = off + i
      if (index > s.seeker.end) index -= len

      if (this._remoteHasBlock(index) === false) continue
      if (this.core.bitfield.get(index) === true) continue
      if (!this._canRequest(index, false)) continue

      // Check if this block is currently inflight - if so pick another
      const b = this.replicator._blocks.get(index)
      if (b !== null && b.inflight.length > 0) continue

      // Block is not inflight, but we only want the hash, check if that is inflight
      const h = this.replicator._hashes.add(index, PRIORITY.NORMAL, false)
      if (h.inflight.length > 0) continue

      const req = this._makeRequest(false, h.priority, index + 1)
      if (req === null) continue

      const nodes = flatTree.depth(s.seeker.start + s.seeker.end - 1)

      req.hash = { index: 2 * index, nodes }
      req.seek = this.remoteSupportsSeeks
        ? { bytes: s.seeker.bytes, padding: s.seeker.padding }
        : null

      s.inflight.push(req)
      h.inflight.push(req)
      this._send(req)

      return true
    }

    this._maybeWantAnyRange(s.seeker.start, len, s)
    return false
  }

  _canRequest(index, force) {
    if (!(index >= 0)) throw ASSERTION('bad index to _canRequest: ' + index)

    if (!force && this.replicator.pushOnly) {
      return false
    }

    if (this.remoteLength >= this.core.state.length) {
      return true
    }

    if (index < this.lastUpgradableLength && this.lastUpgradableFork === this.core.state.fork) {
      return true
    }

    if (this.canUpgrade && this.syncsProcessing === 0) {
      return true
    }

    return false
  }

  _remoteHasBlock(index) {
    return index < this._remoteContiguousLength || this.remoteBitfield.get(index) === true
  }

  _sendBlockRequest(req, b) {
    if (this.core._repairMode) return

    req.block = { index: b.index, nodes: 0 }
    this.replicator._markInflight(b.index)

    b.inflight.push(req)
    this.replicator.hotswaps.add(b)
    this._send(req)
  }

  _requestBlock(b) {
    const { length, fork } = this.core.state

    if (this._remoteHasBlock(b.index) === false || fork !== this.remoteFork) {
      if (!this.core.bitfield.get(b.index)) this._maybeWant(b.index, b)
      return false
    }

    if (!this._canRequest(b.index, b.force)) return false

    const req = this._makeRequest(b.index >= length, b.priority, b.index + 1)
    if (req === null) return false

    this._sendBlockRequest(req, b)

    return true
  }

  _maybeWant(index, handle) {
    if (index < this.remoteContiguousLength) return

    const res = this.wants.add(index, handle)
    if (!res) return

    const batch = res.want && res.unwant
    if (batch) this.protomux.cork()

    if (res.unwant) {
      this.wireUnwant.send(res.unwant)
      incrementTx(this.stats.wireUnwant, this.replicator.stats.wireUnwant)
    }
    if (res.want) {
      this.wireWant.send(res.want)
      incrementTx(this.stats.wireWant, this.replicator.stats.wireWant)
    }

    if (batch) this.protomux.uncork()
  }

  _maybeWantAnyRange(start, length, handle) {
    if (handle.wants) {
      for (const w of handle.wants) {
        if ((w.start !== start || w.length !== length) && w.any) {
          const req = this.wants.removeAnyRange(w.start, w.length, handle)
          if (req) this.wireUnwant.send(req)
        }
      }
    }

    if (start + length <= this.remoteContiguousLength) return

    const req = this.wants.addAnyRange(start, length, handle)
    if (req) this.wireWant.send(req)
  }

  _requestRangeBlock(index, length) {
    if (this.core.bitfield.get(index) === true || !this._canRequest(index, false)) return false

    const b = this.replicator._blocks.add(index, PRIORITY.NORMAL, false)
    if (b.inflight.length > 0) {
      this.missingBlocks.set(index, false) // in case we missed some states just set them ondemand, nbd
      return false
    }

    const req = this._makeRequest(index >= length, b.priority, index + 1)

    // If the request cannot be satisfied, dealloc the block request if no one is subscribed to it
    if (req === null) {
      b.gc()
      return false
    }

    this._sendBlockRequest(req, b)

    // Don't think this will ever happen, as the pending queue is drained before the range queue
    // but doesn't hurt to check this explicitly here also.
    if (b.queued) b.queued = false
    return true
  }

  _findNext(i) {
    if (i < this._remoteContiguousLength) {
      if (this.core.skipBitfield === null) this.replicator._openSkipBitfield()
      i = this.core.skipBitfield.findFirst(false, i)
      if (i < this._remoteContiguousLength && i > -1) return i
      i = this._remoteContiguousLength
    }

    return this.missingBlocks.findFirst(true, i)
  }

  _addRangeBatch(r, offset, end) {
    const { WANT_BATCH } = w
    while (offset < end) {
      const next = this.core.bitfield.findFirst(false, offset)
      if (next === -1 || next >= end) return false

      const b = (next - (next & (WANT_BATCH - 1))) / WANT_BATCH

      if (r.addBatch(b)) return true

      offset = (b + 1) * WANT_BATCH
    }

    return false
  }

  _populateRangeBatches(r) {
    const { WANT_BATCH } = w
    for (let i = r.batches.length - 1; i >= 0; i--) {
      const b = r.batches[i]
      const minStart = b.batch * WANT_BATCH
      const maxEnd = minStart + WANT_BATCH

      const start = Math.max(r.start, minStart)
      const end = Math.min(r.end === -1 ? maxEnd : r.end, maxEnd)

      if (start < end && this.core.bitfield.hasUnset(start, end - start)) continue

      r.removeBatch(b)
    }

    while (r.batches.length < 3) {
      const end = r.end === -1 ? this.core.state.length : r.end
      if (end <= r.start) return

      const len = end - r.start
      const off = r.start + (r.linear ? 0 : Math.floor(Math.random() * len))

      if (!this._addRangeBatch(r, off, end) && !this._addRangeBatch(r, r.start, end)) break
    }
  }

  _requestRangeBatch(start, end, length) {
    let tries = this.inflight

    do {
      start = this._findNext(start)
      if (start === -1 || start >= end) break

      if (this._requestRangeBlock(start, length)) return true
      start++
    } while (tries-- > 0)

    return false
  }

  _getValidEnd(maxEnd) {
    // if we can upgrade the remote, or the remote is ahead, then all the remotes blocks are valid
    // otherwise truncate to the last length the remote has acked for us
    const maxLocalLength =
      this.canUpgrade || this.remoteLength >= this.core.state.length
        ? this.core.state.length
        : this.core.state.fork === this.lastUpgradableFork
          ? Math.min(this.lastUpgradableLength, this.core.state.length)
          : 0

    return Math.min(
      maxLocalLength,
      Math.min(maxEnd === -1 ? this.remoteLength : maxEnd, this.remoteLength)
    )
  }

  _requestRange(r) {
    const { WANT_BATCH } = w
    if (this.syncsProcessing > 0) return false

    const { length, fork } = this.core.state

    if (r.blocks) {
      for (let i = r.start; i < r.end; i++) {
        const index = r.blocks[i]
        const has = index < this._remoteContiguousLength || this.missingBlocks.get(index) === true
        if (has === true && this._requestRangeBlock(index, length)) return true
        this._maybeWant(index, r)
      }

      return false
    }

    this._populateRangeBatches(r)

    const end = this._getValidEnd(r.end)

    if (end <= r.start || fork !== this.remoteFork) return false

    for (let i = 0; i < r.batches.length; i++) {
      const b = r.batches[i]

      const batchStart = Math.max(b.batch * WANT_BATCH, r.start)
      const batchEnd = Math.min((b.batch + 1) * WANT_BATCH, end)
      const len = batchEnd - batchStart
      const off = batchStart + (r.linear ? 0 : Math.floor(Math.random() * len))

      if (
        this._requestRangeBatch(off, end, length) ||
        this._requestRangeBatch(batchStart, off, length)
      ) {
        return true
      }

      this._maybeWant(batchStart, b)
    }

    // Here we should consider making an OOB request (ie if the remote says they have a newer block)
    // but the upgrade code already does that, so no big deal for now

    return false
  }

  _requestForkProof(f) {
    if (!this.remoteLength) return
    if (this.replicator.pushOnly) return

    const req = this._makeRequest(false, 0, 0)
    if (req === null) return

    req.upgrade = { start: 0, length: this.remoteLength }
    req.manifest = !this.core.header.manifest

    f.inflight.push(req)
    this._send(req)
  }

  _requestForkRange(f) {
    if (f.fork !== this.remoteFork || f.batch.want === null) return false
    if (this.replicator.pushOnly) return false

    const end = Math.min(f.batch.want.end, this.remoteLength)
    if (end < f.batch.want.start) return false

    const len = end - f.batch.want.start
    const off = f.batch.want.start + Math.floor(Math.random() * len)

    for (let i = 0; i < len; i++) {
      let index = off + i
      if (index >= end) index -= len

      if (this._remoteHasBlock(index) === false) continue

      const req = this._makeRequest(false, 0, 0)
      if (req === null) return false

      req.hash = { index: 2 * index, nodes: f.batch.want.nodes }

      f.inflight.push(req)
      this._send(req)

      return true
    }

    this._maybeWantAnyRange(f.batch.want.start, len, f)
    return false
  }

  isActive() {
    if (this.paused || this.removed || this.core.header.frozen) return false
    return true
  }

  async _send(req) {
    const fork = this.core.state.fork

    this.inflight++
    this.replicator._inflight.add(req)

    if (req.upgrade !== null && req.fork === fork) {
      const u = this.replicator._addUpgrade()
      u.inflight.push(req)
    }

    try {
      if (req.block !== null && req.fork === fork) {
        req.block.nodes = await MerkleTree.missingNodes(
          this.core.state,
          2 * req.block.index,
          this.core.state.length
        )
        if (req.priority === PRIORITY.CANCELLED) return
      }
      if (req.hash !== null && req.fork === fork && req.hash.nodes === 0) {
        req.hash.nodes = await MerkleTree.missingNodes(
          this.core.state,
          req.hash.index,
          this.core.state.length
        )
        if (req.priority === PRIORITY.CANCELLED) return

        // nodes === 0, we already have it, bail
        if (req.hash.nodes === 0 && (req.hash.index & 1) === 0) {
          this.inflight--
          this.replicator._resolveHashLocally(this, req)
          return
        }
      }
    } catch (err) {
      this.stream.destroy(err)
      return
    }

    this.wireRequest.send(req)
    incrementTx(this.stats.wireRequest, this.replicator.stats.wireRequest)
  }
}

module.exports = class Replicator {
  static Peer = Peer // hack to be able to access Peer from outside this module

  constructor(
    core,
    {
      notDownloadingLinger = NOT_DOWNLOADING_SLACK,
      eagerUpgrade = true,
      allowFork = true,
      allowPush = false,
      alwaysLatestBlock = false,
      inflightRange = null
    } = {}
  ) {
    this.core = core
    this.eagerUpgrade = eagerUpgrade
    this.allowFork = allowFork
    this.allowPush = allowPush
    this.ondownloading = null // optional external hook for monitoring downloading status
    this.peers = []
    this.findingPeers = 0 // updatable from the outside
    this.destroyed = false
    this.downloading = false
    this.pushOnly = false
    this.activeSessions = 0

    this.hotswaps = new HotswapQueue()
    this.inflightRange = inflightRange || DEFAULT_MAX_INFLIGHT

    // Note: nodata and unwant not currently tracked
    // tx = transmitted, rx = received
    this.stats = {
      wireSync: { tx: 0, rx: 0 },
      wireRequest: { tx: 0, rx: 0 },
      wireCancel: { tx: 0, rx: 0 },
      wireData: { tx: 0, rx: 0 },
      wireWant: { tx: 0, rx: 0 },
      wireUnwant: { tx: 0, rx: 0 },
      wireBitfield: { tx: 0, rx: 0 },
      wireRange: { tx: 0, rx: 0 },
      wireExtension: { tx: 0, rx: 0 },
      hotswaps: 0,
      invalidData: 0,
      invalidRequests: 0,
      backoffs: 0,
      notAvailableBackoffs: 0
    }

    this._attached = new Set()
    this._inflight = new InflightTracker()
    this._blocks = new BlockTracker(this)
    this._hashes = new BlockTracker(this)

    this._alwaysLatestBlock = alwaysLatestBlock ? 1 : 0
    this._queued = []

    this._seeks = []
    this._upgrade = null
    this._reorgs = []
    this._ranges = []

    this._rxLock = new Mutex()
    this._txLock = new Mutex()

    this._hadPeers = false
    this._active = 0
    this._ifAvailable = 0
    this._updatesPending = 0
    this._applyingReorg = null
    this._manifestPeer = null
    this._notDownloadingLinger = notDownloadingLinger
    this._notDownloadingTimer = null

    this._updateAllBump = null
    this._updateAllBound = this.updateAll.bind(this)

    const self = this
    this._onstreamclose = onstreamclose

    function onstreamclose() {
      self.detachFrom(this.userData)
    }
  }

  setInflightRange(min, max) {
    const def = this.inflightRange
    this.inflightRange = [min, max]
    for (const peer of this.peers) {
      if (peer.inflightRange !== def) continue
      peer.inflightRange = this.inflightRange
    }
  }

  updateActivity(inc, session) {
    this.activeSessions += inc
    this.setDownloading(this.activeSessions !== 0, session)
  }

  isDownloading() {
    return this.downloading || !this._inflight.idle
  }

  async push(index) {
    const all = []
    for (const peer of this.peers) {
      all.push(peer.push(index))
    }
    await Promise.all(all)
  }

  setAllowPush(allowPush) {
    if (allowPush === this.allowPush) return
    this.allowPush = allowPush
    for (const peer of this.peers) peer.sendSync()
  }

  isAllowingPush() {
    if (!this.allowPush) return false
    if (this._notDownloadingTimer) return false
    return this.downloading
  }

  setPushOnly(pushOnly) {
    if (pushOnly === this.pushOnly) return
    this.pushOnly = pushOnly
  }

  setDownloading(downloading) {
    const allowPush = this.isAllowingPush()
    const linger = this._notDownloadingLinger

    if (this._notDownloadingTimer) {
      clearTimeout(this._notDownloadingTimer)
      this._notDownloadingTimer = null
    }

    if (this.destroyed) return

    if (downloading || linger === 0) {
      if (!this._setDownloadingNow(downloading)) this.signalAllowPush(allowPush)
      return
    }

    this._notDownloadingTimer = setTimeout(setNotDownloadingLater, linger, this)
    if (this._notDownloadingTimer.unref) this._notDownloadingTimer.unref()
    this.signalAllowPush(allowPush)
  }

  signalAllowPush(allowPush) {
    if (allowPush === this.isAllowingPush()) return
    for (const peer of this.peers) peer.signalUpgrade()
  }

  _setDownloadingNow(downloading) {
    this._notDownloadingTimer = null

    if (this.downloading === downloading) return false
    this.downloading = downloading

    if (!downloading && this.isDownloading()) return false

    for (const peer of this.peers) peer.signalUpgrade()

    if (downloading) {
      // restart channel if needed...
      for (const protomux of this._attached) {
        if (!protomux.stream.handshakeHash) continue
        if (protomux.opened({ protocol: 'hypercore/alpha', id: this.core.discoveryKey })) continue
        this._makePeer(protomux, true)
      }
    } else {
      for (const peer of this.peers) peer.closeIfIdle()
    }

    if (this.ondownloading !== null && downloading) this.ondownloading()
    return true
  }

  cork() {
    for (const peer of this.peers) peer.protomux.cork()
  }

  uncork() {
    for (const peer of this.peers) peer.protomux.uncork()
  }

  // Called externally when a range of new blocks has been processed/removed
  onhave(start, length, drop = false) {
    for (const peer of this.peers) peer.broadcastRange(start, length, drop)
  }

  // Called externally when a truncation upgrade has been processed
  ontruncate(newLength, truncated) {
    const notify = []

    for (const blk of this._blocks) {
      if (blk.index < newLength) continue
      notify.push(blk)
    }

    for (const blk of notify) {
      for (const r of blk.refs) {
        if (r.snapshot === false) continue
        blk.detach(r, SNAPSHOT_NOT_AVAILABLE())
      }
    }

    for (const peer of this.peers) {
      peer.fullyDownloadedSignaled = Math.min(newLength, peer.fullyDownloadedSignaled)
      peer._unclearLocalRange(newLength, truncated)
    }
  }

  // Called externally when a upgrade has been processed
  onupgrade() {
    for (const peer of this.peers) peer.signalUpgrade()
    if (this._blocks.isEmpty() === false) this._resolveBlocksLocally()
    if (this._upgrade !== null) this._resolveUpgradeRequest(null)
    if (!this._blocks.isEmpty() || this._ranges.length !== 0 || this._seeks.length !== 0) {
      this._updateNonPrimary(true)
    }
  }

  // Called externally when a conflict has been detected and verified
  async onconflict() {
    const all = []
    for (const peer of this.peers) {
      all.push(peer._onconflict())
    }
    await Promise.allSettled(all)
  }

  async applyPendingReorg() {
    if (this._applyingReorg !== null) {
      await this._applyingReorg
      return true
    }

    for (let i = this._reorgs.length - 1; i >= 0; i--) {
      const f = this._reorgs[i]
      if (f.batch !== null && f.batch.finished) {
        await this._applyReorg(f)
        return true
      }
    }

    return false
  }

  addUpgrade(session) {
    if (this._upgrade !== null) {
      const ref = this._upgrade.attach(session)
      this._checkUpgradeIfAvailable()
      return ref
    }

    const ref = this._addUpgrade().attach(session)

    this.queueUpdateAll()

    return ref
  }

  addBlock(session, index, force) {
    const b = this._blocks.add(index, PRIORITY.HIGH, force)
    const ref = b.attach(session)

    this._queueBlock(b)
    this.queueUpdateAll()

    return ref
  }

  addSeek(session, seeker) {
    const s = new SeekRequest(this, this._seeks, seeker)
    const ref = s.attach(session)

    this._seeks.push(s)
    this.queueUpdateAll()

    return ref
  }

  addRange(
    session,
    { start = 0, end = -1, length = toLength(start, end), blocks = null, linear = false } = {}
  ) {
    if (blocks !== null) {
      // if using blocks, start, end just acts as frames around the blocks array
      start = 0
      end = length = blocks.length
    }

    const r = new RangeRequest(
      this,
      this._ranges,
      start,
      length === -1 ? -1 : start + length,
      linear,
      blocks
    )

    const ref = r.attach(session)

    // Trigger this to see if this is already resolved...
    // Also auto compresses the range based on local bitfield
    clampRange(this.core, r)

    if (r.end !== -1 && r.start >= r.end) {
      this._resolveRangeRequest(r)
      return ref
    }

    this.queueUpdateAll()

    return ref
  }

  cancel(ref) {
    ref.context.detach(ref, null)
  }

  static clearRequests(session, err) {
    if (session.length === 0) return
    if (session.length === 1 && session[0] === null) return

    const updated = new Set()

    while (session.length > 0) {
      const ref = session[session.length - 1]
      updated.add(ref.context.replicator)
      ref.context.detach(ref, err)
    }

    for (const replicator of updated) {
      replicator.queueUpdateAll()
    }
  }

  clearRequests(session, err = null) {
    let cleared = false
    while (session.length > 0) {
      const ref = session[session.length - 1]
      ref.context.detach(ref, err)
      cleared = true
    }

    if (cleared) this.queueUpdateAll()
  }

  _matchingRequest(req, data) {
    if (this.allowPush) {
      return true
    }
    if (data.block !== null && (req.block === null || req.block.index !== data.block.index)) {
      return false
    }
    if (data.hash !== null && (req.hash === null || req.hash.index !== data.hash.index)) {
      return false
    }
    if (data.seek !== null && (req.seek === null || req.seek.bytes !== data.seek.bytes)) {
      return false
    }
    if (data.upgrade !== null && req.upgrade === null) {
      return false
    }
    return req.fork === data.fork
  }

  _addUpgradeMaybe() {
    return this.eagerUpgrade === true ? this._addUpgrade() : this._upgrade
  }

  // TODO: this function is OVER called atm, at each updatePeer/updateAll
  // instead its more efficient to only call it when the conditions in here change - ie on sync/add/remove peer
  // Do this when we have more tests.
  _checkUpgradeIfAvailable() {
    if (this._ifAvailable > 0 && this.peers.length < MAX_PEERS_UPGRADE) return
    if (this._upgrade === null || this._upgrade.refs.length === 0) return
    if (this._hadPeers === false && this.findingPeers > 0) return

    const maxPeers = Math.min(this.peers.length, MAX_PEERS_UPGRADE)

    // check if a peer can upgrade us

    for (let i = 0; i < maxPeers; i++) {
      const peer = this.peers[i]

      if (peer.remoteSynced === false) return

      if (this.core.state.length === 0 && peer.remoteLength > 0) return

      if (peer.remoteLength <= this._upgrade.length || peer.remoteFork !== this._upgrade.fork) {
        continue
      }

      if (peer.syncsProcessing > 0) return

      if (peer.lengthAcked !== this.core.state.length && peer.remoteFork === this.core.state.fork) {
        return
      }

      if (peer.remoteCanUpgrade === true) return
    }

    // check if reorgs in progress...

    if (this._applyingReorg !== null) return

    // TODO: we prob should NOT wait for inflight reorgs here, seems better to just resolve the upgrade
    // and then apply the reorg on the next call in case it's slow - needs some testing in practice

    for (let i = 0; i < this._reorgs.length; i++) {
      const r = this._reorgs[i]
      if (r.inflight.length > 0) return
    }

    // if something is inflight, wait for that first
    if (this._upgrade.inflight.length > 0) return

    // nothing to do, indicate no update avail

    const u = this._upgrade
    this._upgrade = null
    u.resolve(false)
  }

  _addUpgrade() {
    if (this._upgrade !== null) return this._upgrade

    // TODO: needs a reorg: true/false flag to indicate if the user requested a reorg
    this._upgrade = new UpgradeRequest(this, this.core.state.fork, this.core.state.length)

    return this._upgrade
  }

  _addReorg(fork, peer) {
    if (this.allowFork === false) return null

    // TODO: eager gc old reorgs from the same peer
    // not super important because they'll get gc'ed when the request finishes
    // but just spam the remote can do ...

    for (const f of this._reorgs) {
      if (f.fork > fork && f.batch !== null) return null
      if (f.fork === fork) return f
    }

    const f = new ForkRequest(this, fork)

    this._reorgs.push(f)

    // maintain sorted by fork
    let i = this._reorgs.length - 1
    while (i > 0 && this._reorgs[i - 1].fork > fork) {
      this._reorgs[i] = this._reorgs[i - 1]
      this._reorgs[--i] = f
    }

    return f
  }

  _shouldUpgrade(peer) {
    if (this._upgrade !== null && this._upgrade.inflight.length > 0) return false
    return (
      peer.remoteCanUpgrade === true &&
      peer.remoteLength > this.core.state.length &&
      peer.lengthAcked === this.core.state.length
    )
  }

  _autoUpgrade(peer) {
    return (
      this._upgrade !== null &&
      peer.remoteFork === this.core.state.fork &&
      this._shouldUpgrade(peer)
    )
  }

  _addPeer(peer) {
    this._hadPeers = true
    this.peers.push(peer)
    this.updatePeer(peer)
    this._onpeerupdate(true, peer)
  }

  _requestDone(id, roundtrip) {
    this._inflight.remove(id, roundtrip)
    if (this.isDownloading() === true) return
    for (const peer of this.peers) peer.signalUpgrade()
  }

  _removePeer(peer) {
    this.peers.splice(this.peers.indexOf(peer), 1)
    peer.wants.destroy()

    if (this._manifestPeer === peer) this._manifestPeer = null

    let inflight = false
    for (const req of this._inflight) {
      if (req.peer !== peer) continue
      inflight = true
      this._inflight.remove(req.id, true)
      this._clearRequest(peer, req)
    }

    this._onpeerupdate(false, peer)
    if (inflight) {
      this.queueUpdateAll()
    } else {
      this._checkUpgradeIfAvailable()
    }
  }

  _queueBlock(b) {
    if (b.inflight.length > 0 || b.queued === true) return
    b.queued = true
    this._queued.push(b)
  }

  _resolveHashLocally(peer, req) {
    this._requestDone(req.id, false)
    this._resolveBlockRequest(this._hashes, req.hash.index / 2, null, req)
    this.updatePeer(peer)
  }

  // Runs in the background - not allowed to throw
  async _resolveBlocksLocally() {
    // TODO: check if fork compat etc. Requires that we pass down truncation info

    const clear = []
    const blocks = []

    const reader = this.core.storage.read()
    for (const b of this._blocks) {
      if (this.core.bitfield.get(b.index) === false) continue
      blocks.push(this._resolveLocalBlock(b, reader, clear))
    }
    reader.tryFlush()

    await Promise.all(blocks)

    if (!clear.length) return

    // Currently the block tracker does not support deletes during iteration, so we make
    // sure to clear them afterwards.
    for (const b of clear) {
      this._blocks.remove(b.index)
      removeHotswap(b)
    }
  }

  async _resolveLocalBlock(b, reader, resolved) {
    try {
      b.resolve(await reader.getBlock(b.index))
    } catch (err) {
      b.reject(err)
      return
    }

    resolved.push(b)
  }

  _resolveBlockRequest(tracker, index, value, req) {
    const b = tracker.remove(index)
    if (b === null) return false

    removeInflight(b.inflight, req)
    removeHotswap(b)
    b.queued = false

    b.resolve(value)

    if (b.inflight.length > 0) {
      // if anything is still inflight, cancel it
      for (let i = b.inflight.length - 1; i >= 0; i--) {
        const req = b.inflight[i]
        req.peer._cancelRequest(req)
      }
    }

    return true
  }

  _resolveUpgradeRequest(req) {
    if (req !== null) removeInflight(this._upgrade.inflight, req)

    if (
      this.core.state.length === this._upgrade.length &&
      this.core.state.fork === this._upgrade.fork
    ) {
      return false
    }

    const u = this._upgrade
    this._upgrade = null
    u.resolve(true)

    return true
  }

  _resolveRangeRequest(req) {
    req.resolve(true)
    req.gc()
  }

  _clearInflightBlock(tracker, req) {
    const isBlock = tracker === this._blocks
    const index = isBlock === true ? req.block.index : req.hash.index / 2
    const b = tracker.get(index)

    if (b === null || removeInflight(b.inflight, req) === false) return

    if (removeHotswap(b) === true && b.inflight.length > 0) {
      this.hotswaps.add(b)
    }

    if (b.refs.length > 0 && isBlock === true) {
      this._queueBlock(b)
      return
    }

    b.gc()
  }

  _clearInflightUpgrade(req) {
    if (this._upgrade === null || removeInflight(this._upgrade.inflight, req) === false) return
    this._upgrade.gc()
  }

  _clearInflightSeeks(req) {
    for (const s of this._seeks) {
      if (removeInflight(s.inflight, req) === false) continue
      s.gc()
    }
  }

  _clearInflightReorgs(req) {
    for (const r of this._reorgs) {
      removeInflight(r.inflight, req)
    }
  }

  _clearOldReorgs(fork) {
    for (let i = 0; i < this._reorgs.length; i++) {
      const f = this._reorgs[i]
      if (f.fork >= fork) continue
      if (i === this._reorgs.length - 1) this._reorgs.pop()
      else this._reorgs[i] = this._reorgs.pop()
      i--
    }
  }

  // "slow" updates here - async but not allowed to ever throw
  async _updateNonPrimary(updateAll) {
    // Check if running, if so skip it and the running one will issue another update for us (debounce)
    while (++this._updatesPending === 1) {
      let len = Math.min(MAX_RANGES, this._ranges.length)

      for (let i = 0; i < len; i++) {
        const r = this._ranges[i]

        clampRange(this.core, r)

        if (r.end !== -1 && r.start >= r.end) {
          this._resolveRangeRequest(r)
          i--
          if (len > this._ranges.length) len--
          if (this._ranges.length === MAX_RANGES) updateAll = true
        }
      }

      for (let i = 0; i < this._seeks.length; i++) {
        const s = this._seeks[i]

        let err = null
        let res = null

        try {
          res = await s.seeker.update()
        } catch (error) {
          err = error
        }

        if (!res && !err) continue

        if (i < this._seeks.length - 1) this._seeks[i] = this._seeks.pop()
        else this._seeks.pop()

        i--

        if (err) s.reject(err)
        else s.resolve(res)
      }

      // No additional updates scheduled - break
      if (--this._updatesPending === 0) break
      // Debounce the additional updates - continue
      this._updatesPending = 0
    }

    if (this._inflight.idle || updateAll) this.queueUpdateAll()
  }

  _clearRequest(peer, req) {
    if (req.block !== null) {
      this._clearInflightBlock(this._blocks, req)
      this._unmarkInflight(req.block.index)
    }

    if (req.hash !== null) {
      this._clearInflightBlock(this._hashes, req)
    }

    if (req.upgrade !== null && this._upgrade !== null) {
      this._clearInflightUpgrade(req)
    }

    if (this._seeks.length > 0) {
      this._clearInflightSeeks(req)
    }

    if (this._reorgs.length > 0) {
      this._clearInflightReorgs(req)
    }
  }

  _onnodata(peer, req, reason) {
    if (reason === NOT_AVAILABLE) {
      peer.stats.notAvailableBackoffs++
      this.stats.notAvailableBackoffs++

      if (peer.stats.notAvailableBackoffs >= MAX_BACKOFFS) {
        peer.paused = true
      }
    }

    if (reason === INVALID_REQUEST) {
      peer.stats.backoffs++
      this.stats.backoffs++

      if (peer.stats.backoffs >= MAX_BACKOFFS) {
        peer.paused = true
      }
    }

    if (req) {
      this._clearRequest(peer, req)
    }

    this.queueUpdateAll()
  }

  _openSkipBitfield() {
    // technically the skip bitfield gets bits cleared if .clear() is called
    // also which might be in inflight also, but that just results in that section being overcalled shortly
    // worst case, so ok for now

    const bitfield = this.core.openSkipBitfield()

    for (const req of this._inflight) {
      if (req.block) bitfield.set(req.block.index, true) // skip
    }
  }

  _markProcessing(index) {
    const b = this._blocks.get(index)
    if (b) {
      b.processing = true
      return
    }

    const h = this._hashes.get(index)
    if (h) h.processing = true
  }

  _markProcessed(index) {
    const b = this._blocks.get(index)
    if (b) return b.processed()

    const h = this._hashes.get(index)
    if (h) h.processed()
  }

  _markInflight(index) {
    if (this.core.skipBitfield !== null) this.core.skipBitfield.set(index, true)
    for (const peer of this.peers) peer._markInflight(index)
  }

  _unmarkInflight(index) {
    if (this.core.skipBitfield !== null) {
      this.core.skipBitfield.set(index, this.core.bitfield.get(index))
    }
    for (const peer of this.peers) peer._resetMissingBlock(index)
  }

  _ondata(peer, req, data) {
    if (req) {
      req.elapsed = Date.now() - req.timestamp
    }

    if (data.block !== null) {
      this._resolveBlockRequest(this._blocks, data.block.index, data.block.value, req)
      this._ondownload(data.block.index, data.block.value.byteLength, peer, req)
    }

    if (data.hash !== null && (data.hash.index & 1) === 0) {
      this._resolveBlockRequest(this._hashes, data.hash.index / 2, null, req)
    }

    if (this._upgrade !== null) {
      this._resolveUpgradeRequest(req)
    }

    if (this._seeks.length > 0) {
      this._clearInflightSeeks(req)
    }

    if (this._reorgs.length > 0) {
      this._clearInflightReorgs(req)
    }

    if (this._manifestPeer === peer && this.core.header.manifest !== null) {
      this._manifestPeer = null
    }

    if (this._seeks.length > 0 || this._ranges.length > 0) {
      this._updateNonPrimary(this._seeks.length > 0)
    }

    this.updatePeer(peer)
  }

  _onwant(peer, start, length, any) {
    if (!peer.isActive()) return

    const contig = Math.min(this.core.state.length, this.core.header.hints.contiguousLength)

    if (start + length < contig || this.core.state.length === contig || (any && start < contig)) {
      peer.wireRange.send({
        drop: false,
        start: 0,
        length: contig
      })
      incrementTx(peer.stats.wireRange, this.stats.wireRange)
      return
    }

    length = Math.min(length, this.core.state.length - start)

    if (any) {
      const bit = this.core.bitfield.firstSet(start)
      if (bit > -1 && bit < start + length) {
        peer.wireRange.send({
          drop: false,
          start: bit,
          length: 1
        })
      }
      return
    }

    for (const msg of this.core.bitfield.want(start, length)) {
      peer.wireBitfield.send(msg)
      incrementTx(peer.stats.wireBitfield, this.stats.wireBitfield)
    }
  }

  async _onreorgdata(peer, req, data) {
    const newBatch = data.upgrade && (await this.core.verifyReorg(data))
    const f = this._addReorg(data.fork, peer)

    if (f === null) {
      this.queueUpdateAll()
      return
    }

    removeInflight(f.inflight, req)

    if (f.batch) {
      await f.batch.update(data)
    } else if (data.upgrade) {
      f.batch = newBatch

      // Remove "older" reorgs in progress as we just verified this one.
      this._clearOldReorgs(f.fork)
    }

    if (f.batch && f.batch.finished) {
      if (this._addUpgradeMaybe() !== null) {
        await this._applyReorg(f)
      }
    }

    this.queueUpdateAll()
  }

  // Never throws, allowed to run in the background
  async _applyReorg(f) {
    // TODO: more optimal here to check if potentially a better reorg
    // is available, ie higher fork, and request that one first.
    // This will request that one after this finishes, which is fine, but we
    // should investigate the complexity in going the other way

    const u = this._upgrade
    const old = this._reorgs

    this._reorgs = [] // clear all as the nodes are against the old tree - easier
    this._applyingReorg = this.core.reorg(f.batch, null) // TODO: null should be the first/last peer?

    try {
      await this._applyingReorg
    } catch (err) {
      this._upgrade = null
      u.reject(err)
    }

    this._applyingReorg = null

    if (this._upgrade !== null) {
      this._resolveUpgradeRequest(null)
    }

    for (const peer of this.peers) this._updateFork(peer)

    // TODO: all the remaining is a tmp workaround until we have a flag/way for ANY_FORK
    for (const r of this._ranges) {
      r.start = r.userStart
      r.end = r.userEnd
    }

    for (const f of old) f.resolve()
    f.resolve()

    this.queueUpdateAll()
  }

  _maybeUpdate() {
    return this._upgrade !== null && this._upgrade.inflight.length === 0
  }

  _maybeRequestManifest() {
    return this.core.header.manifest === null && this._manifestPeer === null
  }

  _updateFork(peer) {
    if (
      this._applyingReorg !== null ||
      this.allowFork === false ||
      peer.remoteFork <= this.core.state.fork
    ) {
      return false
    }

    const f = this._addReorg(peer.remoteFork, peer)

    // TODO: one per peer is better
    if (f !== null && f.batch === null && f.inflight.length === 0) {
      return peer._requestForkProof(f)
    }

    return false
  }

  _updateHotswap(peer) {
    const maxHotswaps = peer.getMaxHotswapInflight()
    if (!peer.isActive() || peer.inflight >= maxHotswaps) return

    for (const b of this.hotswaps.pick(peer)) {
      if (peer._requestBlock(b) === false) continue
      peer.stats.hotswaps++
      peer.replicator.stats.hotswaps++
      if (peer.inflight >= maxHotswaps) break
    }
  }

  _updatePeer(peer) {
    if (!peer.isActive() || peer.inflight >= peer.getMaxInflight() || !peer.remoteUploading) {
      return false
    }

    // Eagerly request the manifest even if the remote length is 0. If not 0 we'll get as part of the upgrade request...
    if (
      this._maybeRequestManifest() === true &&
      peer.remoteLength === 0 &&
      peer.remoteHasManifest === true
    ) {
      this._manifestPeer = peer
      peer._requestManifest()
    }

    for (const s of this._seeks) {
      if (s.inflight.length > 0) continue // TODO: one per peer is better
      if (peer._requestSeek(s) === true) {
        return true
      }
    }

    // Implied that any block in the queue should be requested, no matter how many inflights
    const blks = new RandomIterator(this._queued)

    for (const b of blks) {
      if (b.queued === false || peer._requestBlock(b) === true) {
        b.queued = false
        blks.dequeue()
        return true
      }
    }

    return false
  }

  _updatePeerNonPrimary(peer) {
    if (!peer.isActive() || peer.inflight >= peer.getMaxInflight() || !peer.remoteUploading) {
      return false
    }

    const ranges = new RandomIterator(this._ranges)
    let tried = 0

    for (const r of ranges) {
      if (peer._requestRange(r) === true) {
        return true
      }
      if (++tried >= MAX_RANGES) break
    }

    // Iterate from newest fork to oldest fork...
    for (let i = this._reorgs.length - 1; i >= 0; i--) {
      const f = this._reorgs[i]
      if (f.batch !== null && f.inflight.length === 0 && peer._requestForkRange(f) === true) {
        return true
      }
    }

    if (this._maybeUpdate() === true && peer._requestUpgrade(this._upgrade) === true) {
      return true
    }

    return false
  }

  updatePeer(peer) {
    // Quick shortcut to wait for flushing reorgs - not needed but less waisted requests
    if (this._applyingReorg !== null) return

    while (this._updatePeer(peer) === true);
    while (this._updatePeerNonPrimary(peer) === true);

    if (this.peers.length > 1 && this._blocks.isEmpty() === false) {
      this._updateHotswap(peer)
    }

    this._checkUpgradeIfAvailable()
  }

  updateSubset() {
    return this.updateAll(false)
  }

  updateAll(all = true) {
    // Clear queued scan if a full scan
    if (this._updateAllBump !== null && all) {
      clearTimeout(this._updateAllBump)
      this._updateAllBump = null
    }

    // Quick shortcut to wait for flushing reorgs - not needed but less waisted requests
    if (this._applyingReorg !== null) return

    const peers = new RandomIterator(this.peers)

    const limit = all ? peers.length : MIN_PEER_UPDATE_ALL
    let tried = 0
    for (const peer of peers) {
      tried++
      if (this._updatePeer(peer) === true) {
        peers.requeue()
      }
      if (tried >= limit) break
    }

    // Check if we can skip the non primary check fully
    if (this._maybeUpdate() === false && this._ranges.length === 0 && this._reorgs.length === 0) {
      this._checkUpgradeIfAvailable()
      return
    }

    tried = 0
    for (const peer of peers.restart()) {
      tried++
      if (this._updatePeerNonPrimary(peer) === true) {
        peers.requeue()
      }
      if (tried >= limit) break
    }

    this._checkUpgradeIfAvailable()
  }

  getUpdateAllDelay(peers) {
    return Math.min(3000, Math.max(100, (peers.length - MIN_PEER_UPDATE_ALL) * 5))
  }

  queueUpdateAll() {
    if (this.peers.length < MIN_PEER_UPDATE_ALL) return this.updateAll()

    // Immediately scan subset
    this.updateSubset()

    // Schedule full scan
    if (this._updateAllBump !== null) return //skip if already scheduled
    this._updateAllBump = setTimeout(this._updateAllBound, this.getUpdateAllDelay(this.peers))
  }

  onpeerdestroy() {
    if (--this._active === 0) this.core.checkIfIdle()
  }

  attached(protomux) {
    return this._attached.has(protomux)
  }

  attachTo(protomux) {
    if (this.core.closed) return

    const makePeer = this._makePeer.bind(this, protomux)

    this._attached.add(protomux)
    protomux.pair({ protocol: 'hypercore/alpha', id: this.core.discoveryKey }, makePeer)
    protomux.stream.setMaxListeners(0)
    protomux.stream.on('close', this._onstreamclose)

    this._ifAvailable++
    this._active++

    protomux.stream.opened.then((opened) => {
      this._ifAvailable--
      this._active--

      if (opened && !this.destroyed) makePeer()
      this._checkUpgradeIfAvailable()

      this.core.checkIfIdle()
    })
  }

  detachFrom(protomux) {
    if (this._attached.delete(protomux)) {
      protomux.stream.removeListener('close', this._onstreamclose)
      protomux.unpair({ protocol: 'hypercore/alpha', id: this.core.discoveryKey })
    }
  }

  idle() {
    return this.peers.length === 0 && this._active === 0
  }

  close() {
    const waiting = []

    for (const peer of this.peers) {
      waiting.push(peer.channel.fullyClosed())
    }

    this.destroy()
    return Promise.all(waiting)
  }

  destroy() {
    if (this.destroyed) return
    this.destroyed = true

    if (this._notDownloadingTimer) {
      clearTimeout(this._notDownloadingTimer)
      this._notDownloadingTimer = null
    }

    if (this._updateAllBump) {
      clearTimeout(this._updateAllBump)
      this._updateAllBump = null
    }

    while (this.peers.length) {
      const peer = this.peers[this.peers.length - 1]
      this.detachFrom(peer.protomux)
      peer.channel.close() // peer is removed from array in onclose
    }

    for (const protomux of this._attached) {
      this.detachFrom(protomux)
    }
  }

  _makePeer(protomux) {
    const replicator = this
    if (protomux.opened({ protocol: 'hypercore/alpha', id: this.core.discoveryKey })) {
      return onnochannel()
    }

    const channel = protomux.createChannel({
      userData: null,
      protocol: 'hypercore/alpha',
      aliases: ['hypercore'],
      id: this.core.discoveryKey,
      handshake: m.wire.handshake,
      messages: [
        { encoding: m.wire.sync, onmessage: onwiresync },
        { encoding: m.wire.request, onmessage: onwirerequest },
        { encoding: m.wire.cancel, onmessage: onwirecancel },
        { encoding: m.wire.data, onmessage: onwiredata },
        { encoding: m.wire.noData, onmessage: onwirenodata },
        { encoding: m.wire.want, onmessage: onwirewant },
        { encoding: m.wire.unwant, onmessage: onwireunwant },
        { encoding: m.wire.bitfield, onmessage: onwirebitfield },
        { encoding: m.wire.range, onmessage: onwirerange },
        { encoding: m.wire.extension, onmessage: onwireextension }
      ],
      onopen: onwireopen,
      onclose: onwireclose,
      ondrain: onwiredrain,
      ondestroy: onwiredestroy
    })

    if (channel === null) return onnochannel()

    const peer = new Peer(replicator, protomux, channel, this.inflightRange)
    const stream = protomux.stream

    peer.channel.open({
      seeks: true,
      capability: caps.replicate(stream.isInitiator, this.core.key, stream.handshakeHash)
    })

    return true

    function onnochannel() {
      return false
    }
  }

  _onpeerupdate(added, peer) {
    const name = added ? 'peer-add' : 'peer-remove'
    const sessions = this.core.monitors

    for (let i = sessions.length - 1; i >= 0; i--) {
      sessions[i].emit(name, peer)

      if (added) {
        for (const ext of sessions[i].extensions.values()) {
          peer.extensions.set(ext.name, ext)
        }
      }
    }
  }

  _ondownload(index, byteLength, from, req) {
    const sessions = this.core.monitors

    for (let i = sessions.length - 1; i >= 0; i--) {
      const s = sessions[i]
      s.emit('download', index, byteLength - s.padding, from, req)
    }
  }

  _onupload(index, byteLength, from) {
    const sessions = this.core.monitors

    for (let i = sessions.length - 1; i >= 0; i--) {
      const s = sessions[i]
      s.emit('upload', index, byteLength - s.padding, from)
    }
  }

  _oninvaliddata(err, req, res, from) {
    const sessions = this.core.monitors

    this.stats.invalidData++
    from.stats.invalidData++
    for (let i = 0; i < sessions.length; i++) {
      sessions[i].emit('verification-error', err, req, res, from)
    }
  }

  _oninvalidrequest(err, req, from) {
    const sessions = this.core.monitors

    from.stats.invalidRequests++
    this.stats.invalidRequests++
    for (let i = 0; i < sessions.length; i++) {
      sessions[i].emit('invalid-request', err, req, from)
    }
  }
}

function removeHotswap(block) {
  if (block.hotswap === null) return false
  block.hotswap.ref.remove(block)
  return true
}

function removeInflight(inf, req) {
  const i = inf.indexOf(req)
  if (i === -1) return false
  if (i < inf.length - 1) inf[i] = inf.pop()
  else inf.pop()
  return true
}

function toLength(start, end) {
  return end === -1 ? -1 : end < start ? 0 : end - start
}

function clampRange(core, r) {
  if (r.blocks === null) {
    const start = core.bitfield.firstUnset(r.start)

    if (r.end === -1) r.start = start === -1 ? core.state.length : start
    else if (start === -1 || start >= r.end) r.start = r.end
    else {
      r.start = start

      const end = core.bitfield.lastUnset(r.end - 1)

      if (end === -1 || start >= end + 1) r.end = r.start
      else r.end = end + 1
    }
  } else {
    while (r.start < r.end && core.bitfield.get(r.blocks[r.start])) r.start++
    while (r.start < r.end && core.bitfield.get(r.blocks[r.end - 1])) r.end--
  }
}

function onrequesttimeout(req) {
  if (req.context) req.context.detach(req, REQUEST_TIMEOUT())
}

function destroyRequestTimeout(req) {
  if (req.timeout !== null) {
    clearTimeout(req.timeout)
    req.timeout = null
  }
}

function isCriticalError(err) {
  // TODO: expose .critical or similar on the hypercore errors that are critical (if all not are)
  return err.name === 'HypercoreError'
}

function onwireopen(m, c) {
  return c.userData.onopen(m)
}

function onwireclose(isRemote, c) {
  return c.userData.onclose(isRemote)
}

function onwiredestroy(c) {
  c.userData.replicator.onpeerdestroy()
}

function onwiredrain(c) {
  return c.userData.ondrain()
}

function onwiresync(m, c) {
  incrementRx(c.userData.stats.wireSync, c.userData.replicator.stats.wireSync)
  return c.userData.onsync(m)
}

function onwirerequest(m, c) {
  incrementRx(c.userData.stats.wireRequest, c.userData.replicator.stats.wireRequest)
  return c.userData.onrequest(m)
}

function onwirecancel(m, c) {
  incrementRx(c.userData.stats.wireCancel, c.userData.replicator.stats.wireCancel)
  return c.userData.oncancel(m)
}

function onwiredata(m, c) {
  incrementRx(c.userData.stats.wireData, c.userData.replicator.stats.wireData)
  return c.userData.ondata(m)
}

function onwirenodata(m, c) {
  return c.userData.onnodata(m)
}

function onwirewant(m, c) {
  incrementRx(c.userData.stats.wireWant, c.userData.replicator.stats.wireWant)
  return c.userData.onwant(m)
}

function onwireunwant(m, c) {
  return c.userData.onunwant(m)
}

function onwirebitfield(m, c) {
  incrementRx(c.userData.stats.wireBitfield, c.userData.replicator.stats.wireBitfield)
  return c.userData.onbitfield(m)
}

function onwirerange(m, c) {
  incrementRx(c.userData.stats.wireRange, c.userData.replicator.stats.wireRange)
  return c.userData.onrange(m)
}

function onwireextension(m, c) {
  incrementRx(c.userData.stats.wireExtension, c.userData.replicator.stats.wireExtension)
  return c.userData.onextension(m)
}

function setNotDownloadingLater(repl, session) {
  repl._setDownloadingNow(false, session)
}

function isBlockRequest(req) {
  return req !== null && req.block !== null
}

function isUpgradeRequest(req) {
  return req !== null && req.upgrade !== null
}

function incrementTx(stats1, stats2) {
  stats1.tx++
  stats2.tx++
}

function incrementRx(stats1, stats2) {
  stats1.rx++
  stats2.rx++
}

function noop() {}

function backoff(times) {
  const sleep = times < 2 ? 200 : times < 5 ? 500 : times < 40 ? 1000 : 5000
  return new Promise((resolve) => setTimeout(resolve, sleep))
}
const crypto = require('hypercore-crypto')
const b4a = require('b4a')
const assert = require('nanoassert')
const flat = require('flat-tree')
const quickbit = require('quickbit-universal')
const HypercoreStorage = require('hypercore-storage')

const {
  INVALID_OPERATION,
  INVALID_SIGNATURE,
  ASSERTION,
  SESSION_CLOSED,
  SESSION_NOT_WRITABLE
} = require('hypercore-errors')

const Mutex = require('./mutex')
const Bitfield = require('./bitfield')
const { MerkleTree, MerkleTreeBatch } = require('./merkle-tree')

class SessionState {
  constructor(core, parent, storage, treeInfo, name) {
    this.core = core
    this.index = this.core.sessionStates.push(this) - 1

    this.storage = storage
    this.name = name
    this.sessions = []

    // small hack to close old storages as late as possible.
    // TODO: add a read lock so we can avoid that
    this.lingers = null

    this.parent = parent
    this.atomized = null
    this.mutex = new Mutex()

    // merkle state
    this.roots = treeInfo.roots.length ? treeInfo.roots : []
    this.fork = treeInfo.fork || 0
    this.length = this.roots.length ? MerkleTree.span(this.roots) / 2 : treeInfo.length
    this.byteLength = MerkleTree.size(this.roots)
    this.prologue = treeInfo.prologue || null
    this.signature = treeInfo.signature || null

    this.snapshotCompatLength = this.isSnapshot()
      ? Math.min(this.length, this.core.state.length)
      : -1
    this.lastTruncation = null
    this.groupUpdated = false

    this.active = 0

    this._activeTx = null
    this._pendingBitfield = null

    this.ref()
  }

  static RECOVERY_PEERS = null

  isSnapshot() {
    return this.storage.snapshotted
  }

  isDefault() {
    return this.core.state === this || this.isAtomicDefault()
  }

  isAtomicDefault() {
    return !!this.storage.atom && !!this.parent && this.parent.isDefault()
  }

  createTreeBatch() {
    return new MerkleTreeBatch(this)
  }

  addSession(s) {
    if (s._stateIndex !== -1) return
    s._stateIndex = this.sessions.push(s) - 1
    if (s.weak === false) this.core.activeSessions++
  }

  removeSession(s) {
    if (s._stateIndex === -1) return
    const head = this.sessions.pop()
    if (head !== s) this.sessions[(head._stateIndex = s._stateIndex)] = head
    s._stateIndex = -1
    if (s.weak === false) this.core.activeSessions--
    this.core.checkIfIdle()
  }

  flushedLength() {
    if (this.isDefault() || this.isSnapshot()) return this.length
    const deps = this.storage.dependencies
    if (deps.length) return deps[deps.length - 1].length
    return 0
  }

  signedLength() {
    const l = Math.min(this.flushedLength(), this.core.state.length)
    return this.isSnapshot() && l > this.snapshotCompatLength ? this.snapshotCompatLength : l
  }

  unref() {
    if (--this.active > 0) return
    this.close().catch(noop) // technically async, but only for the last db session
  }

  ref() {
    this.active++
    return this
  }

  hash() {
    return MerkleTree.hash(this)
  }

  setRoots(roots) {
    this.roots = roots
    this.length = MerkleTree.span(roots) / 2
    this.byteLength = MerkleTree.size(roots)
  }

  get encryptionFork() {
    return this.core.header.tree.fork
  }

  async _updateSnapshotStorage(storage) {
    if (!this.atomized || !this.atomized.flushing) return this.treeInfo()
    while (this.atomized.flushing) await this.atomized.flushed()

    let rx = storage.read()
    const headPromise = rx.getHead()
    const authPromise = rx.getAuth()
    const depPromise = rx.getDependency()

    rx.tryFlush()
    const [head, auth, dep] = await Promise.all([headPromise, authPromise, depPromise])

    storage.setDependencyHead(dep)

    const fork = head ? head.fork : 0
    const length = head ? head.length : 0

    rx = storage.read()
    const rootPromises = []
    for (const r of flat.fullRoots(length * 2)) {
      rootPromises.push(rx.getTreeNode(r))
    }

    rx.tryFlush()

    const roots = await Promise.all(rootPromises)

    // dbl check if we are hitting an regression from earler
    for (const root of roots) {
      if (root === null) {
        throw new Error(
          'Bad snapshot from atomized session, id = ' +
            this.core.id +
            ' length = ' +
            length +
            ' fork = ' +
            fork
        )
      }
    }

    return {
      fork,
      roots,
      length,
      prologue: auth.manifest && auth.manifest.prologue,
      signature: head && head.signature
    }
  }

  treeInfo() {
    return {
      fork: this.fork,
      roots: this.roots.slice(),
      length: this.length,
      prologue: this.prologue,
      signature: this.signature
    }
  }

  async close() {
    if (this.index === -1) return

    this.active = 0
    this.mutex.destroy(new Error('Closed')).catch(noop)
    if (this.parent && this.parent.atomized) this.parent.atomized = null

    const closing = this.storage.close()

    const head = this.core.sessionStates.pop()
    if (head !== this) this.core.sessionStates[(head.index = this.index)] = head

    this.index = -1
    this.core.checkIfIdle()

    if (this.lingers !== null) {
      for (const storage of this.lingers) await storage.close()
    }

    return closing
  }

  async snapshot() {
    const storage = this.storage.snapshot()
    const treeInfo = await this._updateSnapshotStorage(storage)

    return new SessionState(this.core, null, storage, treeInfo, this.name)
  }

  updateDependency(tx, length) {
    const dependency = updateDependency(this, length, false)
    if (dependency) tx.setDependency(dependency)
    return dependency
  }

  updateGroupIndex(tx, tree) {
    const { pointer } = this.core.header.group

    tx.deleteGroupUpdate(pointer, this.core.header.tree.timestamp)
    tx.putGroupUpdate(pointer, tree.timestamp, this.core.header.key)

    this.groupUpdated = true
  }

  _clearActiveBatch() {
    this._activeTx = null
  }

  createWriteBatch() {
    assert(!this._activeTx && !this.storage.snapshotted)

    this._activeTx = this.storage.write()
    return this._activeTx
  }

  _unlock() {
    this._clearActiveBatch()
    this.mutex.unlock()
    this.core.checkIfIdle()
  }

  _flushHooks() {
    if (!this.groupUpdated) return
    this.groupUpdated = false
    this.core.ongroupupdate(this.core.header.group.key, {
      key: this.core.key,
      length: this.length,
      fork: this.fork
    })
  }

  async flush() {
    const tx = this._activeTx
    this._activeTx = null

    try {
      if (!(await tx.flush())) return false
    } finally {
      this._clearActiveBatch()
    }

    this.lastTruncation = null
    return true
  }

  _precommit(state) {
    assert(
      state.parent === this && state.storage.core.dataPointer === this.storage.core.dataPointer,
      'Atomic state must flush to parent'
    )
  }

  async _commit() {
    await this.mutex.lock()

    try {
      const bitfield = this._pendingBitfield
      this._pendingBitfield = null
      this.lastTruncation = null
      await this.parent._oncommit(this, bitfield)
    } finally {
      this.mutex.unlock()
    }
  }

  async _oncommit(src, bitfield) {
    await this.mutex.lock()

    try {
      const currLength = this.length

      // load dependency into memory
      const rx = this.storage.read()
      const dependencyPromise = rx.getDependency()

      rx.tryFlush()

      const dependency = await dependencyPromise

      this.fork = src.fork
      this.length = src.length
      this.byteLength = src.byteLength
      this.roots = src.roots.slice()
      this.signature = src.signature

      const tree = {
        fork: this.fork,
        length: this.length,
        rootHash: this.hash(),
        signature: this.signature,
        timestamp: Date.now()
      }

      if (this.isDefault() && this.core.header.group) {
        const tx = this.createWriteBatch()
        this.updateGroupIndex(tx, tree)
        await this.flush()
        this._flushHooks()
      }

      if (dependency) this.storage.setDependencyHead(dependency)

      const b = bitfield

      if (b && b.truncated && b.start < currLength) {
        this.ontruncate(tree, b.start, currLength, true)
        if (!b || b.appends === 0) return
      }

      const append = b ? { start: b.start, length: b.appends, drop: false } : null

      this.onappend(tree, append, true)

      if (this.core.hintsChanged && this.isDefault()) await this.core.flushHints()
    } finally {
      this._unlock()
    }
  }

  async setUserData(key, value) {
    await this.mutex.lock()

    try {
      const tx = this.createWriteBatch()
      tx.putUserData(key, value)

      return await this.flush()
    } finally {
      this._unlock()
    }
  }

  async _verifyBlock(batch, bitfield, value, manifest, from) {
    await this.mutex.lock()

    try {
      if (batch.upgraded && batch.length <= this.length) {
        await batch.downgrade()
      }

      if (!batch.commitable()) {
        return false
      }

      if (this.core.preupdate !== null) {
        await this.core.preupdate(batch, this.core.header.key)
      }

      const tx = this.createWriteBatch()

      if (bitfield) {
        tx.putBlock(bitfield.start, value)
      }

      if (bitfield && this.isDefault()) {
        await storeBitfieldRange(this.storage, tx, bitfield.start, bitfield.start + 1, true)
      }

      if (manifest) this.core._setManifest(tx, manifest, null)

      assert(batch.commitable(), 'Should still be commitable')
      batch.commit(tx)

      const head = {
        fork: batch.fork,
        length: batch.length,
        rootHash: batch.hash(),
        signature: batch.signature,
        timestamp: Date.now()
      }

      if (batch.upgraded) {
        tx.setHead(head)

        if (this.core.header.group) {
          this.updateGroupIndex(tx, head)
        }
      }

      const flushed = await this.flush()

      if (batch.upgraded) {
        this.roots = batch.roots
        this.length = batch.length
        this.byteLength = batch.byteLength
        this.fork = batch.fork
        this.signature = batch.signature

        this.onappend(head, bitfield, flushed)
      }

      if (this.core.hintsChanged && this.isDefault()) await this.core.flushHints()
    } finally {
      this._unlock()
    }

    return true
  }

  async truncate(length, fork, { signature, keyPair } = {}) {
    if (!keyPair && this.isDefault()) keyPair = this.core.header.keyPair

    await this.mutex.lock()

    try {
      if (this.prologue && length < this.prologue.length) {
        throw INVALID_OPERATION('Truncation breaks prologue', this.core.discoveryKey)
      }
      if (length > this.length) {
        throw INVALID_OPERATION(
          'Not a truncation, ' + length + ' must be less or equal to ' + this.length,
          this.core.discoveryKey
        )
      }

      const batch = this.createTreeBatch()
      await MerkleTree.truncate(this, length, batch, fork)

      if (signature) {
        batch.signature = signature
        this.core._verifyBatchUpgrade(batch)
      } else if (keyPair) {
        batch.signature = this.core.verifier.sign(batch, keyPair)
      }

      const tx = this.createWriteBatch()

      // upsert compat manifest
      if (this.core.verifier === null && keyPair) this.core._setManifest(tx, null, keyPair)

      const { dependency, tree, roots } = await this._truncate(tx, batch)

      for (const sessionState of this.core.sessionStates) {
        if (
          sessionState.isSnapshot() &&
          sessionState.name === this.name &&
          length < sessionState.snapshotCompatLength
        ) {
          sessionState.snapshotCompatLength = length
        }
      }

      const flushed = await this.flush()

      this.fork = tree.fork
      this.length = tree.length
      this.byteLength = MerkleTree.size(roots)
      this.roots = roots
      this.signature = tree.signature

      if (dependency) this.storage.setDependencyHead(dependency)

      this.ontruncate(tree, tree.length, batch.treeLength, flushed)

      if (this.core.hintsChanged && this.isDefault()) await this.core.flushHints()
    } finally {
      this._unlock()
    }
  }

  async reorg(batch) {
    await this.mutex.lock()

    const storage = this.createWriteBatch()

    try {
      if (!batch.commitable()) return false

      const { dependency, tree } = await this._truncate(storage, batch)

      const flushed = await this.flush()

      this.fork = batch.fork
      this.length = batch.length
      this.byteLength = batch.byteLength
      this.roots = batch.roots
      this.signature = batch.signature

      if (dependency) this.storage.setDependencyHead(dependency)

      this.ontruncate(tree, batch.ancestors, batch.treeLength, flushed)

      if (this.core.hintsChanged && this.isDefault()) await this.core.flushHints()
    } finally {
      this._unlock()
    }
  }

  async _truncate(storage, batch) {
    storage.deleteBlockRange(batch.ancestors, batch.treeLength)

    assert(batch.commitable(), 'Batch must be commitable')

    const tree = {
      fork: batch.fork,
      length: batch.length,
      rootHash: batch.hash(),
      signature: batch.signature,
      timestamp: Date.now()
    }

    if (this.isDefault() && this.core.header.group) {
      this.updateGroupIndex(storage, tree)
    }

    storage.setHead(tree)
    batch.commit(storage)

    const truncated = batch.length < this.flushedLength()
    const dependency = truncated ? updateDependency(this, batch.length, true) : null

    if (dependency) storage.setDependency(dependency)

    if (this.isDefault()) {
      await storeBitfieldRange(this.storage, storage, batch.ancestors, batch.treeLength, false)
      if (batch.ancestors < this.core.header.hints.contiguousLength) {
        this.core.header.hints.remoteContiguousLength = Math.min(
          batch.length,
          this.core.header.hints.remoteContiguousLength
        )
        storage.setHints({
          contiguousLength: batch.ancestors,
          remoteContiguousLength: this.core.header.hints.remoteContiguousLength
        })
      }
    }

    return { dependency, tree, roots: batch.roots }
  }

  async clear(start, end, cleared) {
    await this.mutex.lock()

    try {
      const tx = this.createWriteBatch()

      const ite = flat.iterator(start * 2)
      while (!isRootIndex(ite.index, this.roots)) {
        const a = ite.index
        const b = ite.sibling()
        ite.parent()

        const [left, right] = flat.spans(b)
        const s = left / 2
        const e = right / 2 + 1
        const has = s <= start && e <= end ? false : this.core.bitfield.hasSet(s, e - s)
        if (has) break

        tx.deleteTreeNode(a)
        tx.deleteTreeNode(b)
      }

      if (this.isDefault()) {
        await storeBitfieldRange(this.storage, tx, start, end, false)
        if (start < this.core.header.hints.contiguousLength) {
          tx.setHints({
            contiguousLength: start,
            remoteContiguousLength: this.core.header.hints.remoteContiguousLength
          })
        }
      }

      if (end - start === 1) tx.deleteBlock(start)
      else tx.deleteBlockRange(start, end)

      const dependency = start < this.flushedLength() ? updateDependency(this, start, true) : null

      const flushed = await this.flush()

      if (dependency) this.storage.setDependencyHead(dependency)

      // todo: atomic event handle
      if (this.isDefault() && flushed) {
        const length = end - start

        this.core.updateContiguousLength({ start, length, drop: true })
        this.core._setBitfieldRanges(start, end, false)
        this.core.replicator.onhave(start, length, true)

        if (this.core.hintsChanged) await this.core.flushHints()
      }
    } finally {
      this._unlock()
    }
  }

  // simple tool to wait for other peers to catch us up
  async waitForRecovery() {
    const length = this.length
    const replicator = this.core.replicator

    while (!this.closing) {
      let peers = getRecoveryPeers(replicator.peers)

      if (peers.length < 1) {
        await new Promise((resolve) => setTimeout(resolve, 5000))
        continue
      }

      let restart = false

      for (let i = 0; i < 32; i++) {
        await new Promise((resolve) => setTimeout(resolve, 250))

        peers = getRecoveryPeers(replicator.peers)

        if (this.closing || !validateRecoveryPeers(peers, this.length)) {
          restart = true
          break
        }
      }

      if (restart) continue

      if (this.length !== length) {
        throw SESSION_NOT_WRITABLE('core recovered during append')
      }

      this.core.header.hints.recovering = 0
      this.core.hintsChanged = true

      await this.mutex.lock()
      try {
        await this.core.flushHints()
        return
      } finally {
        this.mutex.unlock()
      }
    }

    throw SESSION_CLOSED('Cannot recover a closed session', this.discoveryKey)
  }

  async append(values, { signature, keyPair, preappend, postappend, maxLength = -1 } = {}) {
    if (!keyPair && this.isDefault()) keyPair = this.core.header.keyPair

    if (this.isDefault() && this.core.header.hints.recovering) await this.waitForRecovery()

    await this.mutex.lock()

    try {
      if (maxLength >= 0 && this.length + values.length > maxLength) {
        return { length: this.length, byteLength: this.byteLength }
      }

      const tx = this.createWriteBatch()

      // upsert compat manifest
      if (this.core.verifier === null && keyPair) this.core._setManifest(tx, null, keyPair)

      if (preappend) await preappend(values)

      if (!values.length) {
        await this.flush()
        return { length: this.length, byteLength: this.byteLength }
      }

      const batch = this.createTreeBatch()
      for (const val of values) batch.append(val)

      // only multisig can have prologue so signature is always present
      if (this.prologue && batch.length < this.prologue.length) {
        throw INVALID_OPERATION('Append is not consistent with prologue', this.core.discoveryKey)
      }

      if (signature) {
        batch.signature = signature
        this.core._verifyBatchUpgrade(batch)
      } else if (keyPair) {
        batch.signature = this.core.verifier.sign(batch, keyPair)
      }

      batch.commit(tx)

      const tree = {
        fork: batch.fork,
        length: batch.length,
        rootHash: batch.hash(),
        signature: batch.signature,
        timestamp: Date.now()
      }

      tx.setHead(tree)

      if (this.isDefault()) {
        await storeBitfieldRange(this.storage, tx, batch.ancestors, batch.length, true)
        if (this.length === this.core.header.hints.contiguousLength) {
          tx.setHints({
            contiguousLength: this.length + values.length,
            remoteContiguousLength: this.core.header.hints.remoteContiguousLength
          })
        }

        if (this.core.header.group) {
          this.updateGroupIndex(tx, tree)
        }
      }

      for (let i = 0; i < values.length; i++) {
        tx.putBlock(this.length + i, values[i])
      }

      const bitfield = {
        drop: false,
        start: batch.ancestors,
        length: values.length
      }

      const flushed = await this.flush()

      this.fork = batch.fork
      this.roots = batch.roots
      this.length = batch.length
      this.byteLength = batch.byteLength
      this.signature = batch.signature

      if (postappend) await postappend(values)

      this.onappend(tree, bitfield, flushed)

      if (this.core.hintsChanged && this.isDefault()) await this.core.flushHints()

      return { length: this.length, byteLength: this.byteLength }
    } finally {
      this._unlock()
    }
  }

  onappend(tree, bitfield, flushed) {
    if (!flushed) this._updateBitfield(bitfield)
    else if (this.isDefault()) this.core.onappend(tree, bitfield)

    for (let i = this.sessions.length - 1; i >= 0; i--) {
      this.sessions[i].emit('append')
    }

    this._flushHooks()
  }

  ontruncate(tree, to, from, flushed) {
    const bitfield = { start: to, length: from - to, drop: true }

    this.lastTruncation = { from, to }

    if (!flushed) this._updateBitfield(bitfield)
    else if (this.isDefault()) this.core.ontruncate(tree, bitfield)

    for (const sessionState of this.core.sessionStates) {
      if (
        sessionState.isSnapshot() &&
        sessionState.name === this.name &&
        to < sessionState.snapshotCompatLength
      ) {
        sessionState.snapshotCompatLength = to
      }
    }

    for (let i = this.sessions.length - 1; i >= 0; i--) {
      this.sessions[i].emit('truncate', to, tree.fork)
    }

    this._flushHooks()
  }

  _updateBitfield(bitfield, flushed) {
    if (!bitfield) return

    const p = this._pendingBitfield
    const b = bitfield

    if (b.drop) {
      // truncation must be from end
      if (p && b.start + b.length !== p.start + p.appends) {
        throw INVALID_OPERATION('Atomic truncations must be contiguous', this.core.discoveryKey)
      }

      // actual truncation
      if (p === null || b.start < p.start) {
        this._pendingBitfield = { truncated: true, start: b.start, appends: 0 }
        return
      }

      // just clearing batch data
      p.appends = b.start - p.start

      // we cleared the current batch
      if (p.appends === 0) this._pendingBitfield = null

      return
    }

    if (p === null) {
      this._pendingBitfield = { truncated: false, start: b.start, appends: b.length }
      return
    }

    if (b.start !== p.start + p.appends) {
      throw INVALID_OPERATION('Atomic operations must be contiguous', this.core.discoveryKey)
    }

    p.appends += b.length
  }

  async catchup(length) {
    assert(!this.isDefault(), 'Cannot catchup signed state') // TODO: make this check better

    await this.mutex.lock()

    try {
      const origLength = this.length

      let sharedLength = 0
      for (let i = this.storage.dependencies.length - 1; i >= 0; i--) {
        const dep = this.storage.dependencies[i]
        if (dep.dataPointer === this.core.state.storage.core.dataPointer) {
          sharedLength = dep.length
          break
        }
      }

      const tx = this.createWriteBatch()
      const rx = this.core.state.storage.read()
      const rootPromises = []

      for (const root of flat.fullRoots(length * 2)) {
        rootPromises.push(rx.getTreeNode(root))
      }

      rx.tryFlush()

      const roots = await Promise.all(rootPromises)
      const truncating = sharedLength < origLength

      for (const node of roots) {
        if (node === null) {
          throw INVALID_OPERATION(
            'Invalid catchup length, tree nodes not available',
            this.core.discoveryKey
          )
        }
      }

      const fork = truncating ? this.fork + 1 : this.fork

      // overwrite it atm, TODO: keep what we can connect to the tree
      tx.deleteBlockRange(0, -1)
      tx.deleteTreeNodeRange(0, -1)
      tx.deleteBitfieldPageRange(0, -1)

      const tree = {
        fork,
        length,
        rootHash: crypto.tree(roots),
        signature: null,
        timestamp: Date.now()
      }

      // never default state so do not update group index
      tx.setHead(tree)

      // prop a better way to do this
      const dep = updateDependency(this, sharedLength, true)
      dep.length = length

      tx.setDependency(dep)

      const flushed = await this.flush()

      this.storage.setDependencyHead(dep)

      this.fork = tree.fork
      this.roots = roots
      this.length = tree.length
      this.byteLength = MerkleTree.size(roots)

      if (truncating) this.ontruncate(tree, sharedLength, origLength, flushed)
      if (sharedLength < length) this.onappend(tree, null, flushed)

      if (this.core.hintsChanged && this.isDefault()) await this.core.flushHints()
    } finally {
      this._unlock()
    }
  }

  async _overwrite(source, fork, length, treeLength, signature) {
    const blockPromises = []
    const treePromises = []
    const rootPromises = []

    const rx = source.storage.read()

    for (const root of flat.fullRoots(length * 2)) {
      rootPromises.push(rx.getTreeNode(root))
    }

    for (const index of flat.patch(treeLength * 2, length * 2)) {
      treePromises.push(rx.getTreeNode(index))
    }

    for (let i = treeLength; i < length; i++) {
      treePromises.push(rx.getTreeNode(i * 2))
      treePromises.push(rx.getTreeNode(i * 2 + 1))
      blockPromises.push(rx.getBlock(i))
    }

    rx.tryFlush()

    const [blocks, nodes, roots] = await Promise.all([
      Promise.all(blockPromises),
      Promise.all(treePromises),
      Promise.all(rootPromises)
    ])

    if (this.core.destroyed) throw new Error('Core destroyed')

    if (signature) {
      const batch = this.createTreeBatch()
      batch.roots = roots
      batch.length = length

      if (!this.core.verifier.verify(batch, signature)) {
        throw INVALID_SIGNATURE(
          'Signature is not valid over committed tree',
          this.core.discoveryKey
        )
      }
    }

    const tx = this.createWriteBatch()

    // truncate existing tree
    if (treeLength < this.length) {
      tx.deleteBlockRange(treeLength, this.length)
    }

    for (const root of roots) tx.putTreeNode(root)

    // no nodes will be copied in shallow mode
    for (const node of nodes) {
      if (node !== null) tx.putTreeNode(node)
    }

    for (let i = 0; i < blocks.length; i++) {
      assert(blocks[i] !== null, 'has block')
      tx.putBlock(i + treeLength, blocks[i])
    }

    const totalLength = Math.max(length, this.length)

    if (totalLength > treeLength) {
      const firstPage = getBitfieldPage(treeLength)
      const lastPage = getBitfieldPage(totalLength - 1)

      const srx = this.storage.read()
      const bitfieldPagePromise = srx.getBitfieldPage(firstPage)
      srx.tryFlush()

      const bitfieldPage = await bitfieldPagePromise

      let index = treeLength

      for (let i = firstPage; i <= lastPage; i++) {
        const page = b4a.alloc(Bitfield.BYTES_PER_PAGE)
        tx.putBitfieldPage(i, page)

        // copy existing bits in
        if (i === firstPage && bitfieldPage) page.set(bitfieldPage)

        if (index < length) {
          index = fillBitfieldPage(page, index, length, i, true)
          if (index < length) continue
        }

        if (index < this.length) {
          index = fillBitfieldPage(page, index, this.length, i, false)
        }
      }
    }

    const tree = {
      fork,
      length,
      rootHash: crypto.tree(roots),
      signature,
      timestamp: Date.now()
    }

    if (this.isDefault() && this.core.header.group) {
      this.updateGroupIndex(tx, tree)
    }

    const upgraded = treeLength < this.length || this.length < length || tree.fork !== this.fork

    if (upgraded) tx.setHead(tree)

    const flushed = await this.flush()

    this.fork = tree.fork
    this.roots = roots
    this.length = length
    this.byteLength = MerkleTree.size(roots)
    this.signature = signature

    return { tree, flushed }
  }

  static isParent(state, parent) {
    // atomic batches have parent set
    if (state.parent && state.parent === parent) return true

    return HypercoreStorage.isParentStorage(state.storage, parent.storage)
  }

  async commit(state, { signature, keyPair, length = state.length, treeLength = -1 } = {}) {
    assert(
      this.isDefault() || (this.parent && this.parent.isDefault()),
      'Can only commit into default state'
    )

    assert(SessionState.isParent(state, this), 'Cannot commit across cores')

    if (this.core._repairMode) {
      throw ASSERTION('Cannot commit while repair mode is on')
    }

    if (this.core.header.hints.recovering) await this.waitForRecovery()

    let srcLocked = false
    await this.mutex.lock()

    try {
      await state.mutex.lock()
      srcLocked = true

      if (treeLength === -1) treeLength = state.flushedLength()

      if (!(await this.core._validateCommit(state, treeLength))) return null
      if (this.length > length) return null

      if (this.length < length && !signature) {
        if (!keyPair) keyPair = this.core.header.keyPair
        const batch = state.createTreeBatch()
        if (length !== batch.length) await batch.restore(length)
        signature = this.core.verifier.sign(batch, keyPair)
      }

      const { tree, flushed } = await this._overwrite(
        state,
        this.fork,
        length,
        treeLength,
        signature
      )

      // gc blocks from source
      if (treeLength < length) {
        const tx = state.createWriteBatch()

        tx.deleteBlockRange(treeLength, length)
        const dependency = state.updateDependency(tx, length)

        await state.flush(tx)

        if (dependency) state.storage.setDependencyHead(dependency)
      }

      const bitfield = { start: treeLength, length: length - treeLength, drop: false }
      this.onappend(tree, bitfield, flushed)

      return {
        length: this.length,
        byteLength: this.byteLength
      }
    } finally {
      if (srcLocked) state._unlock()
      this._unlock()
    }
  }

  async _getTreeHeadAt(length) {
    if (length === null) return this.treeInfo()

    const head = getDefaultTree()

    head.length = length

    const roots = await MerkleTree.getRootsFromStorage(this.storage, length)
    const rootHash = crypto.tree(roots)

    head.fork = this.fork
    head.rootHash = rootHash

    if (length === this.length) head.signature = this.signature

    return head
  }

  _moveToCore(core, truncated, appended) {
    const head = this.core.sessionStates.pop()
    if (head !== this) this.core.sessionStates[(head.index = this.index)] = head

    this.core = core
    this.index = this.core.sessionStates.push(this) - 1

    for (let i = this.sessions.length - 1; i >= 0; i--) {
      const s = this.sessions[i]
      const manifest = s.manifest
      s.transferSession(this.core)
      if (!manifest && s.manifest) s.emit('manifest')
      if (truncated) s.emit('truncate', truncated.to, truncated.fork)
      if (appended) s.emit('append')
    }
  }

  async moveTo(core, length) {
    const state = core.state

    await this.mutex.lock()

    try {
      // if (state.storage && (await state.storage.resumeSession(this.name)) !== null) {
      //   throw STORAGE_CONFLICT('Batch has already been created')
      // }

      const treeLength = this.length

      let truncated = null
      let appended = false

      if (!this.isSnapshot()) {
        if (this.lingers === null) this.lingers = []
        this.lingers.push(this.storage)

        const resumed = await state.storage.resumeSession(this.name)

        const truncation = length < this.length ? await truncateAndFlush(this, length) : null
        const treeInfo = truncation
          ? truncation.tree
          : resumed
            ? null
            : await state._getTreeHeadAt(this.length)

        const fork = truncation ? this.fork + 1 : this.fork

        // todo: validate treeInfo

        let storage = null

        if (resumed) {
          storage = resumed
        } else {
          treeInfo.fork = fork
          storage = await state.storage.createSession(this.name, treeInfo)
        }

        const roots = await MerkleTree.getRootsFromStorage(storage, length)

        this.storage = storage
        this.prologue = state.prologue
        this.fork = fork
        this.length = length
        this.byteLength = MerkleTree.size(roots)
        this.roots = roots

        if (truncation) {
          const { dependency } = truncation

          if (dependency) this.storage.setDependencyHead(dependency)
          truncated = { to: treeLength, fork }
        }

        if (this.length > treeLength) {
          appended = true
        }
      }

      for (let i = this.core.sessionStates.length - 1; i >= 0; i--) {
        const state = this.core.sessionStates[i]
        if (state === this) continue
        if (state.name === this.name) state._moveToCore(core.core)
      }

      this._moveToCore(core.core, truncated, appended)
    } finally {
      this._unlock()
    }
  }

  async createSession(name, overwrite, atom) {
    await this.mutex.lock()

    try {
      let storage = null
      let treeInfo = null

      if (!atom && !overwrite && this.storage) {
        storage = await this.storage.resumeSession(name)

        if (storage !== null) treeInfo = (await getCoreHead(storage)) || getDefaultTree()
      }

      const length = treeInfo ? treeInfo.length : this.length

      if (storage === null) {
        treeInfo = await this._getTreeHeadAt(length)

        if (atom) {
          storage = await this.storage.createAtomicSession(atom, treeInfo)
        } else {
          storage = await this.storage.createSession(name, treeInfo)
        }
      }

      if (this.atomized && atom) {
        throw new Error('Session already atomized')
      }

      const head = {
        fork: this.fork,
        roots:
          length === this.length
            ? this.roots.slice()
            : await MerkleTree.getRootsFromStorage(storage, length),
        length,
        prologue: this.prologue,
        signature: length === this.length ? this.signature : null
      }

      const state = new SessionState(
        this.core,
        atom ? this : null,
        storage,
        head,
        atom ? this.name : name
      )

      if (atom) {
        this.atomized = atom
        atom.preflush(this._precommit.bind(this, state))
        atom.onflush(state._commit.bind(state))
      }

      return state
    } finally {
      this._unlock()
    }
  }
}

module.exports = SessionState

function noop() {}

function getBitfieldPage(index) {
  return Math.floor(index / Bitfield.BITS_PER_PAGE)
}

function fillBitfieldPage(page, start, end, pageIndex, value) {
  const offset = pageIndex * Bitfield.BITS_PER_PAGE
  const max = offset + Bitfield.BITS_PER_PAGE

  const index = max < end ? max : end

  const from = start - offset
  const to = index - offset

  quickbit.fill(page, value, from, to)

  return index
}

async function storeBitfieldRange(storage, tx, from, to, value) {
  if (from >= to) return

  const firstPage = getBitfieldPage(from)
  const lastPage = getBitfieldPage(to - 1)

  let index = from

  const rx = storage.read()

  const promises = []
  for (let i = firstPage; i <= lastPage; i++) {
    promises.push(rx.getBitfieldPage(i))
  }

  rx.tryFlush()

  const pages = await Promise.all(promises)
  const cnt = lastPage - firstPage + 1

  for (let i = 0; i < cnt; i++) {
    const pageIndex = i + firstPage
    if (!pages[i]) pages[i] = b4a.alloc(Bitfield.BYTES_PER_PAGE)

    index = fillBitfieldPage(pages[i], index, to, pageIndex, value)
    tx.putBitfieldPage(pageIndex, pages[i])
  }
}

async function truncateAndFlush(s, length) {
  const batch = s.createTreeBatch()
  await MerkleTree.truncate(s, length, batch, s.fork)
  const tx = s.createWriteBatch()

  const info = await s._truncate(tx, batch)
  const flushed = await s.flush()

  return {
    tree: info.tree,
    roots: info.roots,
    dependency: info.dependency,
    flushed
  }
}

function updateDependency(state, length, truncated) {
  const i = state.storage.findDependencyIndex(length, truncated)
  if (i === -1) return null // skip default state and overlays of default

  return {
    dataPointer: state.storage.dependencies[i].dataPointer,
    length
  }
}

function getDefaultTree() {
  return {
    fork: 0,
    length: 0,
    rootHash: null,
    signature: null
  }
}

function getCoreHead(storage) {
  const b = storage.read()
  const p = b.getHead()
  b.tryFlush()
  return p
}

function isRootIndex(index, roots) {
  for (const node of roots) {
    if (node.index === index) return true
  }

  return false
}

function getRecoveryPeers(peers) {
  if (!SessionState.RECOVERY_PEERS) return peers

  const actual = []

  for (const p of peers) {
    for (const r of SessionState.RECOVERY_PEERS) {
      if (b4a.equals(p.remotePublicKey, r)) {
        actual.push(p)
        break
      }
    }
  }

  return actual
}

function validateRecoveryPeers(peers, length) {
  if (peers.length < 1) return false

  for (const p of peers) {
    if (p.remoteLength > length) return false
    if (p.remoteLength === 0 && !p.remoteSynced) return false
  }

  return true
}
const { Writable, Readable } = require('streamx')

class ReadStream extends Readable {
  constructor(core, opts = {}) {
    super()

    this.core = core
    this.start = opts.start || 0
    this.end = typeof opts.end === 'number' ? opts.end : -1
    this.snapshot = !opts.live && opts.snapshot !== false
    this.live = this.end === -1 ? !!opts.live : false
    this.wait = typeof opts.wait === 'boolean' ? opts.wait : this.core.wait
    this.timeout = opts.timeout || core.timeout
  }

  _open(cb) {
    this._openP().then(cb, cb)
  }

  _read(cb) {
    this._readP().then(cb, cb)
  }

  async _openP() {
    if (this.end === -1) await this.core.update()
    else await this.core.ready()
    if (this.snapshot && this.end === -1) this.end = this.core.length
  }

  async _readP() {
    const end = this.live ? -1 : this.end === -1 ? this.core.length : this.end
    if (end >= 0 && this.start >= end) {
      this.push(null)
      return
    }

    this.push(await this.core.get(this.start++, { wait: this.wait, timeout: this.timeout }))
  }
}

exports.ReadStream = ReadStream

class WriteStream extends Writable {
  constructor(core) {
    super()
    this.core = core
  }

  _writev(batch, cb) {
    this._writevP(batch).then(cb, cb)
  }

  async _writevP(batch) {
    await this.core.append(batch)
  }
}

exports.WriteStream = WriteStream

class ByteStream extends Readable {
  constructor(core, opts = {}) {
    super()

    this._core = core
    this._index = 0
    this._range = null

    this._byteOffset = opts.byteOffset || 0
    this._byteLength = typeof opts.byteLength === 'number' ? opts.byteLength : -1
    this._prefetch = typeof opts.prefetch === 'number' ? opts.prefetch : 32

    this._applyOffset = this._byteOffset > 0
  }

  _open(cb) {
    this._openp().then(cb, cb)
  }

  _read(cb) {
    this._readp().then(cb, cb)
  }

  async _openp() {
    if (this._byteLength === -1) {
      await this._core.update()
      this._byteLength = Math.max(this._core.byteLength - this._byteOffset, 0)
    }
  }

  async _readp() {
    let data = null

    if (this._byteLength === 0) {
      this.push(null)
      return
    }

    let relativeOffset = 0

    if (this._applyOffset) {
      this._applyOffset = false

      const [block, byteOffset] = await this._core.seek(this._byteOffset)

      this._index = block
      relativeOffset = byteOffset
    }

    this._predownload(this._index + 1)
    data = await this._core.get(this._index++, { valueEncoding: 'binary' })

    if (relativeOffset > 0) data = data.subarray(relativeOffset)

    if (data.byteLength > this._byteLength) data = data.subarray(0, this._byteLength)
    this._byteLength -= data.byteLength

    this.push(data)
    if (this._byteLength === 0) this.push(null)
  }

  _predownload(index) {
    if (this._range) this._range.destroy()
    this._range = this._core.download({ start: index, end: index + this._prefetch, linear: true })
  }

  _destroy(cb) {
    if (this._range) this._range.destroy()
    cb(null)
  }
}

exports.ByteStream = ByteStream
const crypto = require('hypercore-crypto')
const b4a = require('b4a')
const c = require('compact-encoding')
const flat = require('flat-tree')
const { BAD_ARGUMENT } = require('hypercore-errors')
const unslab = require('unslab')

const m = require('./messages')
const multisig = require('./multisig')
const caps = require('./caps')

class Signer {
  constructor(
    manifestHash,
    version,
    index,
    { signature = 'ed25519', publicKey, namespace = caps.DEFAULT_NAMESPACE } = {}
  ) {
    if (!publicKey) throw BAD_ARGUMENT('public key is required for a signer')
    if (signature !== 'ed25519') throw BAD_ARGUMENT('Only Ed25519 signatures are supported')

    this.manifestHash = manifestHash
    this.version = version
    this.signer = index
    this.signature = signature
    this.publicKey = publicKey
    this.namespace = namespace
  }

  _ctx() {
    return this.version === 0 ? this.namespace : this.manifestHash
  }

  verify(batch, signature) {
    return crypto.verify(batch.signable(this._ctx()), signature, this.publicKey)
  }

  sign(batch, keyPair) {
    return crypto.sign(batch.signable(this._ctx()), keyPair.secretKey)
  }
}

class CompatSigner extends Signer {
  constructor(index, signer, legacy) {
    super(null, 0, index, signer)
    this.legacy = legacy
  }

  verify(batch, signature) {
    return crypto.verify(batch.signableCompat(this.legacy), signature, this.publicKey)
  }

  sign(batch, keyPair) {
    return crypto.sign(batch.signableCompat(this.legacy), keyPair.secretKey)
  }
}

module.exports = class Verifier {
  constructor(
    manifestHash,
    manifest,
    { compat = isCompat(manifestHash, manifest), legacy = false } = {}
  ) {
    const self = this

    this.manifestHash = manifestHash
    this.compat = compat || manifest === null
    this.version = this.compat ? 0 : typeof manifest.version === 'number' ? manifest.version : 1
    this.hash = manifest.hash || 'blake2b'
    this.allowPatch = !this.compat && !!manifest.allowPatch
    this.quorum = this.compat ? 1 : defaultQuorum(manifest)

    this.signers = manifest.signers ? manifest.signers.map(createSigner) : []
    this.prologue = this.compat ? null : manifest.prologue || null

    function createSigner(signer, index) {
      return self.compat
        ? new CompatSigner(index, signer, legacy)
        : new Signer(manifestHash, self.version, index, signer)
    }
  }

  _verifyCompat(batch, signature) {
    if (!signature) return false

    if (this.compat || (!this.allowPatch && this.signers.length === 1)) {
      return !!signature && this.signers[0].verify(batch, signature)
    }

    return this._verifyMulti(batch, signature)
  }

  _inflate(signature) {
    if (this.version >= 1) return multisig.inflate(signature)
    const { proofs, patch } = multisig.inflatev0(signature)

    return {
      proofs: proofs.map(proofToVersion1),
      patch
    }
  }

  _verifyMulti(batch, signature) {
    if (!signature || this.quorum === 0) return false

    const { proofs, patch } = this._inflate(signature)
    if (proofs.length < this.quorum) return false

    const tried = new Uint8Array(this.signers.length)
    const nodes = this.allowPatch && patch.length ? toMap(patch) : null

    for (let i = 0; i < this.quorum; i++) {
      const inp = proofs[i]

      let tree = batch

      if (inp.patch && this.allowPatch) {
        tree = batch.clone()

        const upgrade = generateUpgrade(nodes, batch.length, inp.patch)
        const proof = {
          fork: tree.fork,
          block: null,
          hash: null,
          seek: null,
          upgrade,
          manifest: null
        }

        try {
          if (!tree.verifyUpgrade(proof)) return false
        } catch {
          return false
        }
      }

      if (inp.signer >= this.signers.length || tried[inp.signer]) return false
      tried[inp.signer] = 1

      const s = this.signers[inp.signer]
      if (!s.verify(tree, inp.signature)) return false
    }

    return true
  }

  verify(batch, signature) {
    if (this.version === 0) {
      return this._verifyCompat(batch, signature)
    }

    if (this.prologue !== null && batch.length <= this.prologue.length) {
      return batch.length === this.prologue.length && b4a.equals(batch.hash(), this.prologue.hash)
    }

    return this._verifyMulti(batch, signature)
  }

  // TODO: better api for this that is more ... multisig-ey
  sign(batch, keyPair) {
    if (!keyPair || !keyPair.secretKey) throw BAD_ARGUMENT('No key pair was passed')

    for (const s of this.signers) {
      if (b4a.equals(s.publicKey, keyPair.publicKey)) {
        const signature = s.sign(batch, keyPair)
        if (this.signers.length !== 1 || this.version === 0) return signature
        return this.assemble([{ signer: 0, signature, patch: 0, nodes: null }])
      }
    }

    throw BAD_ARGUMENT('Public key is not a declared signer')
  }

  assemble(inputs) {
    return this.version === 0 ? multisig.assemblev0(inputs) : multisig.assemble(inputs)
  }

  static manifestHash(manifest) {
    return manifestHash(manifest)
  }

  static encodeManifest(manifest) {
    return c.encode(m.manifest, manifest)
  }

  static decodeManifest(manifest) {
    return c.decode(m.manifest, manifest)
  }

  static defaultSignerManifest(publicKey) {
    return {
      version: 1,
      hash: 'blake2b',
      allowPatch: false,
      quorum: 1,
      signers: [
        {
          signature: 'ed25519',
          namespace: caps.DEFAULT_NAMESPACE,
          publicKey
        }
      ],
      prologue: null,
      linked: null,
      userData: null
    }
  }

  static fromManifest(manifest, opts) {
    const m = this.createManifest(manifest)
    return new this(manifestHash(m), m, opts)
  }

  static createManifest(inp) {
    if (!inp) return null

    if (inp.quorum && inp.quorum < 0) throw BAD_ARGUMENT('Quorum cannot be negative')
    if (inp.quorum && inp.signers && inp.quorum > inp.signers.length) {
      throw BAD_ARGUMENT('Quorum should not be higher than the number of signers')
    }

    const manifest = {
      version: getManifestVersion(inp), // defaults to v1
      hash: 'blake2b',
      allowPatch: !!inp.allowPatch,
      quorum: defaultQuorum(inp),
      signers: inp.signers ? inp.signers.map(parseSigner) : [],
      prologue: null,
      linked: null,
      userData: inp.userData || null
    }

    if (inp.hash && inp.hash !== 'blake2b') throw BAD_ARGUMENT('Only Blake2b hashes are supported')

    if (inp.prologue) {
      if (
        !(b4a.isBuffer(inp.prologue.hash) && inp.prologue.hash.byteLength === 32) ||
        !(inp.prologue.length >= 0)
      ) {
        throw BAD_ARGUMENT('Invalid prologue')
      }

      manifest.prologue = inp.prologue
      manifest.prologue.hash = unslab(manifest.prologue.hash)
    }

    if (manifest.userData !== null && manifest.version < 2) {
      throw BAD_ARGUMENT('Invalid field: userData')
    }

    if (inp.linked && inp.linked.length) {
      if (manifest.version < 2) throw BAD_ARGUMENT('Invalid field: linked')

      for (const key of inp.linked) {
        if (!(b4a.isBuffer(key) && key.byteLength === 32)) {
          throw BAD_ARGUMENT('Invalid key')
        }
      }

      manifest.linked = inp.linked
    }

    return manifest
  }

  static isValidManifest(key, manifest) {
    return b4a.equals(key, manifestHash(manifest))
  }

  static isCompat(key, manifest) {
    return isCompat(key, manifest)
  }

  static sign(manifest, batch, keyPair, opts) {
    return Verifier.fromManifest(manifest, opts).sign(batch, keyPair)
  }
}

function toMap(nodes) {
  const m = new Map()
  for (const node of nodes) m.set(node.index, node)
  return m
}

function isCompat(key, manifest) {
  return !!(
    manifest &&
    manifest.signers.length === 1 &&
    b4a.equals(key, manifest.signers[0].publicKey)
  )
}

function defaultQuorum(man) {
  if (typeof man.quorum === 'number') return man.quorum
  if (!man.signers || !man.signers.length) return 0
  return (man.signers.length >> 1) + 1
}

function generateUpgrade(patch, start, length) {
  const upgrade = { start, length, nodes: null, additionalNodes: [], signature: null }

  const from = start * 2
  const to = from + length * 2

  for (const ite = flat.iterator(0); ite.fullRoot(to); ite.nextTree()) {
    if (ite.index + ite.factor / 2 < from) continue

    if (upgrade.nodes === null && ite.contains(from - 2)) {
      upgrade.nodes = []

      const root = ite.index
      const target = from - 2

      ite.seek(target)

      while (ite.index !== root) {
        ite.sibling()
        if (ite.index > target) upgrade.nodes.push(patch.get(ite.index))
        ite.parent()
      }

      continue
    }

    if (upgrade.nodes === null) upgrade.nodes = []
    upgrade.nodes.push(patch.get(ite.index))
  }

  if (upgrade.nodes === null) upgrade.nodes = []
  return upgrade
}

function parseSigner(signer) {
  validateSigner(signer)
  return {
    signature: 'ed25519',
    namespace: unslab(signer.namespace || caps.DEFAULT_NAMESPACE),
    publicKey: unslab(signer.publicKey)
  }
}

function validateSigner(signer) {
  if (!signer || !signer.publicKey) throw BAD_ARGUMENT('Signer missing public key')
  if (signer.signature && signer.signature !== 'ed25519') {
    throw BAD_ARGUMENT('Only Ed25519 signatures are supported')
  }
}

function manifestHash(manifest) {
  const state = { start: 0, end: 32, buffer: null }
  m.manifest.preencode(state, manifest)
  state.buffer = b4a.allocUnsafe(state.end)
  c.raw.encode(state, caps.MANIFEST)
  m.manifest.encode(state, manifest)
  return crypto.hash(state.buffer)
}

function proofToVersion1(proof) {
  return {
    signer: proof.signer,
    signature: proof.signature,
    patch: proof.patch ? proof.patch.length : 0
  }
}

function getManifestVersion(inp) {
  if (typeof inp.version === 'number') return inp.version
  if (inp.linked && inp.linked.length) return 2
  if (inp.userData) return 2
  return 1
}
let COMPAT = true
let BATCH_UINTS = COMPAT ? 65536 : 128
let BATCH_BYTES = BATCH_UINTS * 4
let BATCH = BATCH_BYTES * 8 // in bits
const MAX_REMOTE_BATCHES = 4
const MAX_RANGE = 8 * 256 * 1024
const MIN_RANGE = 32 // 4bit ints
const MAX = 512
const MAX_ANY = 16

class LocalWants {
  constructor(peer) {
    this.destroyed = false
    this.peer = peer
    this.wants = new Map()
    this.free = new Set()
    this.any = null
  }

  add(index, handle) {
    const b = (index - (index & (BATCH - 1))) / BATCH
    return this.addBatch(b, handle)
  }

  addAnyRange(start, length, handle) {
    if (this.destroyed) return null
    if (this.any === null) this.any = []

    if (COMPAT) {
      let r = start & (BATCH - 1)
      start -= r
      length += r
      r = length & (BATCH - 1)
      if (r) length = length - r + BATCH
    }

    for (let i = 0; i < this.any.length; i++) {
      const w = this.any[i]
      if (w.start === start && w.length === length) {
        w.handles.add(handle)
        handle.addWant(w)
        return null
      }
    }

    const w = { wants: this, start, length, any: true, handles: new Set([handle]) }
    this.any.push(w)
    handle.addWant(w)

    return { start, length, any: !COMPAT }
  }

  removeAnyRange(start, length, handle) {
    if (this.any === null) return null

    for (let i = 0; i < this.any.length; i++) {
      const w = this.any[i]
      if (w.start !== start || w.length !== length) continue

      w.handles.delete(handle)
      handle.removeWant(w)
      if (w.handles.size > 0) return null

      const head = this.any.pop()
      if (head !== w) this.any[i] = head
      return { start, length, any: !COMPAT }
    }

    return null
  }

  addBatch(index, handle) {
    if (this.destroyed) return null
    let w = this.wants.get(index)

    if (w) {
      const size = w.handles.size
      w.handles.add(handle)
      if (w.handles.size !== size) {
        handle.addWant(w)
      }
      return null
    }

    // start here is the batch number for simplicity....
    w = { wants: this, start: index, length: 0, any: false, handles: new Set([handle]) }

    if (this.free.has(index)) {
      this.free.delete(index)
      this.wants.set(index, w)
      handle.addWant(w)
      return null
    }

    let unwant = null
    if (this.wants.size + this.free.size === MAX) {
      if (this.free.size === 0) {
        return null
      }
      unwant = this._unwant()
    }

    this.wants.set(index, w)
    handle.addWant(w)

    return {
      want: { start: index * BATCH, length: BATCH, any: false },
      unwant
    }
  }

  remove(index, handle) {
    const b = (index - (index & (BATCH - 1))) / BATCH
    return this.removeBatch(b, handle)
  }

  removeBatch(index, handle) {
    if (this.destroyed) return false

    const w = this.wants.get(index)
    if (!w) {
      return false
    }

    w.handles.delete(handle)
    handle.removeWant(w)

    if (w.handles.size === 0) {
      this.free.add(index)
      this.wants.delete(index)
      return this.free.size === 1 && this.wants.size === MAX - 1
    }

    return false
  }

  destroy() {
    if (this.destroyed) return
    this.destroyed = true

    for (const w of this.wants.values()) {
      for (const handle of w.handles) {
        handle.removeWant(w)
      }
    }

    this.wants.clear()
  }

  _unwant() {
    for (const index of this.free) {
      this.free.delete(index)
      return { start: index * BATCH, length: BATCH, any: false }
    }
    return null
  }
}

class RemoteWants {
  constructor() {
    this.any = null
    this.all = false
    this.size = 0
    this.batches = []
  }

  hasAny(start, length) {
    for (let i = 0; i < this.any.length; i++) {
      const a = this.any[i]
      const e = start + length
      const end = a.start + a.length

      if (a.start <= start && start < end) return true
      if (a.start < e && e <= end) return true
    }

    return this.all
  }

  hasRange(start, length) {
    if (this.any !== null && this.hasAny(start, length)) return true
    if (length === 1) return this.has(start)

    let smallest = -1

    for (let i = 0; i < this.batches.length; i++) {
      const b = this.batches[i]
      if (b.length < smallest || smallest === -1) smallest = b.length
    }

    if (smallest === -1) return this.all

    const r = start & (smallest - 1)
    const end = start + length

    let max = 3

    for (let i = start - r; i < end; i += smallest) {
      if (max-- === 0) return true // just to save work
      if (this.has(i)) return true
    }

    return this.all
  }

  has(index) {
    for (let i = 0; i < this.batches.length; i++) {
      const b = this.batches[i]
      const block = (index - (index & (b.length - 1))) / b.length
      if (b.ranges.has(block)) return true
    }

    return this.all
  }

  add(range) {
    if (range.any) {
      if (this.any === null) this.any = []
      if (this.any.length < MAX_ANY) this.any.push(range)
      else this.all = true
      return true
    }

    if (range.length > MAX_RANGE) return false

    if (!validateBatchRange(range)) {
      this.all = true
      return true
    }

    if (this.size >= MAX) {
      this.all = true
      return true
    }

    for (let i = 0; i < this.batches.length; i++) {
      const b = this.batches[i]
      if (b.length === range.length) {
        b.ranges.add(range.start / range.length)
        this.size++
        return true
      }
    }

    if (this.batches.length >= MAX_REMOTE_BATCHES) {
      this.all = true
      return true
    }

    this.batches.push({
      length: range.length,
      ranges: new Set([range.start / range.length])
    })
    this.size++

    return true
  }

  remove(range) {
    if (range.any) {
      if (this.any === null) return false

      for (let i = 0; i < this.any.length; i++) {
        const a = this.any[i]

        if (a.start === range.start && a.length === range.length) {
          const head = this.any.pop()
          if (head !== a) this.any[i] = head
          return true
        }
      }

      return false
    }

    if (!validateBatchRange(range)) return false

    for (let i = 0; i < this.batches.length; i++) {
      const b = this.batches[i]
      if (b.length !== range.length) continue

      const size = b.ranges.size
      b.ranges.delete(range.start / range.length)
      if (b.ranges.size !== size) this.size--

      if (b.ranges.size === 0) {
        const head = this.batches.pop()
        if (head !== b) this.batches[i] = head
      }

      return true
    }

    return false
  }
}

function UPDATE_COMPAT(isCompat) {
  COMPAT = isCompat
  BATCH_UINTS = COMPAT ? 65536 : 128
  BATCH_BYTES = BATCH_UINTS * 4
  BATCH = BATCH_BYTES * 8 // in bits
  exports.WANT_BATCH = BATCH
}

exports.LocalWants = LocalWants
exports.RemoteWants = RemoteWants
exports.WANT_BATCH = BATCH
exports.UPDATE_COMPAT = UPDATE_COMPAT

function validateBatchRange(range) {
  if (range.length > MAX_RANGE || range.length < MIN_RANGE) {
    return false
  }
  // check if power of two
  if ((range.length & (range.length - 1)) !== 0) {
    return false
  }
  // start must be a multiple of the length
  if (range.start & (range.length - 1)) {
    return false
  }

  return true
}
{
  "name": "hypercore",
  "version": "11.33.5",
  "description": "Hypercore is a secure, distributed append-only log",
  "main": "index.js",
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "brittle test/all.js",
    "test:bare": "bare test/all.js",
    "test:generate": "brittle -r test/all.js test/*.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/hypercore.git"
  },
  "contributors": [
    {
      "name": "Mathias Buus",
      "email": "mathiasbuus@gmail.com",
      "url": "https://mafinto.sh"
    },
    {
      "name": "Andrew Osheroff",
      "email": "andrewosh@gmail.com",
      "url": "https://andrewosh.com"
    }
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/hypercore/issues"
  },
  "homepage": "https://github.com/holepunchto/hypercore#readme",
  "files": [
    "index.js",
    "errors.js",
    "messages.js",
    "lib/**.js"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "dependencies": {
    "@hyperswarm/secret-stream": "^6.0.0",
    "b4a": "^1.1.0",
    "bare-events": "^2.2.0",
    "big-sparse-array": "^1.0.3",
    "compact-encoding": "^3.0.0",
    "fast-fifo": "^1.3.0",
    "flat-tree": "^1.9.0",
    "hypercore-crypto": "^3.2.1",
    "hypercore-errors": "^1.5.0",
    "hypercore-id-encoding": "^1.2.0",
    "hypercore-storage": "^3.0.0",
    "is-options": "^1.0.1",
    "nanoassert": "^2.0.0",
    "protomux": "^3.5.0",
    "quickbit-universal": "^2.2.0",
    "random-array-iterator": "^1.0.0",
    "safety-catch": "^1.0.1",
    "sodium-universal": "^5.0.1",
    "streamx": "^2.12.4",
    "unslab": "^1.3.0",
    "z32": "^1.0.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "debugging-stream": "^3.1.0",
    "hyperswarm": "^4.3.6",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "rache": "^1.0.0",
    "range-parser": "^1.2.1",
    "resolve-reject-promise": "^1.1.0",
    "speedometer": "^1.1.0",
    "test-tmp": "^1.0.2",
    "tiny-byte-size": "^1.1.0",
    "udx-native": "^1.6.1",
    "uncaughts": "^1.1.0"
  }
}
{
  "name": "hyperschema",
  "version": "1.21.0",
  "description": "Create registries of declarative compact-encoding schemas",
  "files": [
    "lib/*.js",
    "builder.mjs",
    "builder.cjs",
    "runtime.mjs",
    "runtime.cjs",
    "primitives.mjs",
    "primitives.cjs"
  ],
  "exports": {
    "./package": "./package.json",
    ".": {
      "import": "./builder.mjs",
      "default": "./builder.cjs"
    },
    "./runtime": {
      "import": "./runtime.mjs",
      "default": "./runtime.cjs"
    },
    "./primitives": {
      "import": "./primitives.mjs",
      "default": "./primitives.cjs"
    }
  },
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    }
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test/index.js",
    "test:bare": "prettier . --check && bare test/index.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/hyperschema.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/hyperschema/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperschema#readme",
  "dependencies": {
    "bare-fs": "^4.0.1",
    "compact-encoding": "^3.0.0",
    "generate-object-property": "^2.0.0",
    "generate-string": "^1.0.1"
  },
  "devDependencies": {
    "brittle": "^3.7.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "test-tmp": "^1.3.0"
  }
}
module.exports = {
  c: require('compact-encoding')
}
const b4a = require('b4a')

const EMPTY = b4a.alloc(0)
const MAX = b4a.from([0xff])
const BUFFER = {}

BUFFER.preencode = function (state, buf) {
  if (buf === null) buf = EMPTY

  let i = 0
  let extra = 3

  while ((i = b4a.indexOf(buf, 0x00, i)) > -1) {
    i++
    extra++
  }

  state.end += buf.byteLength + extra
}

BUFFER.encode = function (state, buf) {
  if (buf === null) buf = EMPTY

  state.buffer[state.start++] = 0x00

  let prev = 0
  let i = 0

  while ((i = b4a.indexOf(buf, 0x00, i)) > -1) {
    const slice = buf.subarray(prev, ++i)

    state.buffer.set(slice, state.start)
    state.start += slice.byteLength
    state.buffer[state.start++] = 0x02
    prev = i
  }

  const slice = buf.subarray(prev)

  state.buffer.set(slice, state.start)
  state.start += slice.byteLength

  state.buffer[state.start++] = 0x00
  state.buffer[state.start++] = 0x01
}

BUFFER.decode = function (state) {
  if (state.start >= state.end) throw new Error('Out of bounds')
  if (state.buffer[state.start++] !== 0x00) {
    throw new Error('Invalid start of string')
  }

  let escaped = null

  let prev = state.start
  let i = state.start

  while ((i = b4a.indexOf(state.buffer, 0x00, i)) > -1) {
    const next = ++i < state.end ? state.buffer[i] : 0x00

    i++

    if (next === 0x01) {
      break
    }

    if (next === 0x02) {
      if (escaped === null) escaped = []
      escaped.push(state.buffer.subarray(prev, i - 1))
      prev = i
      continue
    }

    throw new Error('Unknown value in terminator')
  }

  if (i === -1) {
    throw new Error('No terminator found')
  }

  state.start = i
  const last = state.buffer.subarray(prev, i - 2)
  if (escaped === null) return last

  escaped.push(last)
  return b4a.concat(escaped)
}

// TODO: can be optimised a lot

const STRING = {}

STRING.preencode = function (state, str) {
  BUFFER.preencode(state, b4a.from(str || ''))
}

STRING.encode = function (state, str) {
  BUFFER.encode(state, b4a.from(str || ''))
}

STRING.decode = function (state, str) {
  return b4a.toString(BUFFER.decode(state))
}

const UINT = {}

UINT.preencode = function (state, n) {
  state.end += n <= 0xfb ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : n === Infinity ? 1 : 9
}

UINT.encode = function (state, n) {
  if (n === Infinity) {
    state.buffer[state.start++] = 0xff
    return
  }

  if (n <= 0xfb) {
    state.buffer[state.start++] = n
    return
  }

  if (n <= 0xffff) {
    state.buffer[state.start++] = 0xfc
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
    return
  }

  if (n <= 0xffffffff) {
    state.buffer[state.start++] = 0xfd
    encodeUint32(state, n)
    return
  }

  if (Number.isSafeInteger(n)) {
    state.buffer[state.start++] = 0xfe

    const r = Math.floor(n / 0x100000000)
    encodeUint32(state, r)
    encodeUint32(state, n)
    return
  }

  throw new Error('Invalid number ' + n)
}

UINT.decode = function (state) {
  if (state.start >= state.end) throw new Error('Out of bounds')

  const a = state.buffer[state.start++]

  if (a <= 0xfb) return a

  if (a === 0xfc) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] * 0x100 + state.buffer[state.start++]
  }

  if (a === 0xfd) {
    return decodeUint32(state)
  }

  if (a === 0xfe) {
    return decodeUint32(state) * 0x100000000 + decodeUint32(state)
  }

  return Infinity
}

const INT = {}

INT.preencode = function (state, n) {
  // One asymmetric condition
  if (n >= -0xff && n < 0) {
    state.end += 2
    return
  }
  n = Math.abs(n)
  state.end += n <= 0xf6 ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : n === Infinity ? 1 : 9
}

INT.encode = function (state, n) {
  if (n === Infinity) {
    state.buffer[state.start++] = 0xff
    return
  }

  if (n === -Infinity) {
    state.buffer[state.start++] = 0x00
    return
  }

  // Negative 64 bit
  if (n < -0xffffffff) {
    if (!Number.isSafeInteger(n)) throw new Error('Invalid number ' + n)
    state.buffer[state.start++] = 0x01

    const r = Math.floor(-n / 0x100000000)
    encodeUint32(state, -r + 0xffffffff)
    encodeUint32(state, -(-n % 0x100000000) + 0xffffffff)
    return
  }

  // Negative 32 bit
  if (n < -0xffff) {
    state.buffer[state.start++] = 0x02

    n += 0xffffffff
    encodeUint32(state, n)
    return
  }

  // Negative 16bit
  if (n < -0xff) {
    state.buffer[state.start++] = 0x03

    n += 0xffff
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
    return
  }

  // Negative 8bit
  if (n < 0) {
    state.buffer[state.start++] = 0x04

    n += 0xff
    state.buffer[state.start++] = n
    return
  }

  // Remainder of 8bit space for positive int
  if (n <= 0xf6) {
    state.buffer[state.start++] = n + 0x05
    return
  }

  // Positive 16bit
  if (n <= 0xffff) {
    state.buffer[state.start++] = 0xfc
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
    return
  }

  // Positive 32bit
  if (n <= 0xffffffff) {
    state.buffer[state.start++] = 0xfd
    encodeUint32(state, n)
    return
  }

  // Positive 64bit
  if (Number.isSafeInteger(n)) {
    state.buffer[state.start++] = 0xfe

    const r = Math.floor(n / 0x100000000)
    encodeUint32(state, r)
    encodeUint32(state, n)
    return
  }

  throw new Error('Invalid number ' + n)
}

INT.decode = function (state) {
  if (state.start >= state.end) throw new Error('Out of bounds')

  const a = state.buffer[state.start++]

  if (a === 0x00) return -Infinity

  if (a === 0x01) {
    // Split (2^64 - 1) into its 32 bit components
    // r * 0x100000000 + n - (2^64 - 1)
    // r * 0x100000000 + n - (0xffffffff * 0x100000000) - 0xffffffff
    // (r - 0xffffffff) * 0x100000000 + n - 0xffffffff
    return (decodeUint32(state) - 0xffffffff) * 0x100000000 + decodeUint32(state) - 0xffffffff
  }

  if (a === 0x02) {
    return decodeUint32(state) - 0xffffffff
  }

  if (a === 0x03) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] * 0x100 + state.buffer[state.start++] - 0xffff
  }

  if (a === 0x04) return state.buffer[state.start++] - 0xff

  if (a <= 0xfb) return a - 0x05

  if (a === 0xfc) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] * 0x100 + state.buffer[state.start++]
  }

  if (a === 0xfd) {
    return decodeUint32(state)
  }

  if (a === 0xfe) {
    return decodeUint32(state) * 0x100000000 + decodeUint32(state)
  }

  return Infinity
}

const DATE = {}

DATE.preencode = (state, d) => INT.preencode(state, d.getTime())
DATE.encode = (state, d) => INT.encode(state, d.getTime())
DATE.decode = (state) => new Date(INT.decode(state))

const BOOL = {}

BOOL.preencode = (state, b) => UINT.preencode(state, b ? 1 : 0)
BOOL.encode = (state, b) => UINT.encode(state, b ? 1 : 0)
BOOL.decode = (state) => !!UINT.decode(state)

module.exports = class IndexEncoder {
  constructor(encodings, { prefix = -1 } = {}) {
    this.encodings = encodings
    this.prefix = prefix
  }

  static BUFFER = BUFFER
  static STRING = STRING
  static UINT = UINT
  static INT = INT
  static DATE = DATE
  static BOOL = BOOL

  static lookup(c) {
    switch (c) {
      case 'uint':
        return UINT
      case 'uint8':
        return UINT
      case 'uint16':
        return UINT
      case 'uint24':
        return UINT
      case 'uint32':
        return UINT
      case 'uint40':
        return UINT
      case 'uint48':
        return UINT
      case 'uint56':
        return UINT
      case 'uint64':
        return UINT
      case 'int':
        return INT
      case 'int8':
        return INT
      case 'int16':
        return INT
      case 'int24':
        return INT
      case 'int32':
        return INT
      case 'int40':
        return INT
      case 'int48':
        return INT
      case 'int56':
        return INT
      case 'int64':
        return INT
      case 'string':
        return STRING
      case 'utf8':
        return STRING
      case 'ascii':
        return STRING
      case 'hex':
        return STRING
      case 'base64':
        return STRING
      case 'fixed32':
        return BUFFER
      case 'fixed64':
        return BUFFER
      case 'buffer':
        return BUFFER
      case 'date':
        return DATE
      case 'bool':
        return BOOL
    }

    throw new Error('Unknown type')
  }

  encode(keys) {
    return this._encode(keys, false)
  }

  _encode(keys, terminate) {
    if (b4a.isBuffer(keys)) return keys

    const state = { start: 0, end: 0, buffer: null }

    if (this.prefix !== -1) UINT.preencode(state, this.prefix)
    for (let i = 0; i < keys.length; i++) {
      this.encodings[i].preencode(state, keys[i])
    }

    if (terminate && keys.length < this.encodings.length) {
      state.end++
    }

    state.buffer = b4a.allocUnsafe(state.end)

    if (this.prefix !== -1) UINT.encode(state, this.prefix)
    for (let i = 0; i < keys.length; i++) {
      this.encodings[i].encode(state, keys[i])
    }

    if (terminate && keys.length < this.encodings.length) {
      state.buffer[state.start++] = MAX[0]
    }

    return state.buffer
  }

  decode(buffer) {
    const state = { start: 0, end: buffer.byteLength, buffer }
    const result = []

    if (this.prefix !== -1) UINT.decode(state)
    for (const enc of this.encodings) {
      const key = state.start < state.end ? enc.decode(state) : enc === UINT ? 0 : null
      result.push(key)
    }

    return result
  }

  encodeRange({ gt, gte, lt, lte }) {
    const range = {
      gt: gt && this._encode(gt, true),
      gte: gte && this._encode(gte, false),
      lt: lt && this._encode(lt, false),
      lte: lte && this._encode(lte, true)
    }

    if (this.prefix !== -1) {
      if (!gt && !gte) range.gte = encodeUint(this.prefix)
      if (!lt && !lte) range.lt = encodeUint(this.prefix + 1)
    }

    return range
  }
}

function encodeUint(n) {
  const state = { start: 0, end: 0, buffer: null }
  UINT.preencode(state, n)
  state.buffer = b4a.allocUnsafe(state.end)
  UINT.encode(state, n)
  return state.buffer
}

function encodeUint32(state, n) {
  state.buffer[state.start++] = n >>> 24
  state.buffer[state.start++] = n >>> 16
  state.buffer[state.start++] = n >>> 8
  state.buffer[state.start++] = n
}

function decodeUint32(state) {
  if (state.end - state.start < 4) throw new Error('Out of bounds')
  return (
    state.buffer[state.start++] * 0x1000000 +
    state.buffer[state.start++] * 0x10000 +
    state.buffer[state.start++] * 0x100 +
    state.buffer[state.start++]
  )
}
{
  "name": "index-encoder",
  "version": "3.5.0",
  "description": "Encode multiple values into sorted keys",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.6.4"
  },
  "devDependencies": {
    "brittle": "^3.2.1",
    "hyperbee": "^2.10.5",
    "hypercore": "^11.0.0",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/index-encoder.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/index-encoder/issues"
  },
  "homepage": "https://github.com/holepunchto/index-encoder"
}
const b4a = require('b4a')

module.exports = function isOptions (opts) {
  return typeof opts === 'object' && opts && !b4a.isBuffer(opts)
}
{
  "name": "is-options",
  "version": "1.0.2",
  "description": "Easily check if input is an options map",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.1.1"
  },
  "devDependencies": {
    "standard": "^11.0.1",
    "tape": "^4.9.0"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/is-options.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/is-options/issues"
  },
  "homepage": "https://github.com/mafintosh/is-options"
}
import { coerce } from '../bytes.js';
import basex from '../vendor/base-x.js';
/**
 * Class represents both BaseEncoder and MultibaseEncoder meaning it
 * can be used to encode to multibase or base encode without multibase
 * prefix.
 */
class Encoder {
    name;
    prefix;
    baseEncode;
    constructor(name, prefix, baseEncode) {
        this.name = name;
        this.prefix = prefix;
        this.baseEncode = baseEncode;
    }
    encode(bytes) {
        if (bytes instanceof Uint8Array) {
            return `${this.prefix}${this.baseEncode(bytes)}`;
        }
        else {
            throw Error('Unknown type, must be binary type');
        }
    }
}
/**
 * Class represents both BaseDecoder and MultibaseDecoder so it could be used
 * to decode multibases (with matching prefix) or just base decode strings
 * with corresponding base encoding.
 */
class Decoder {
    name;
    prefix;
    baseDecode;
    prefixCodePoint;
    constructor(name, prefix, baseDecode) {
        this.name = name;
        this.prefix = prefix;
        const prefixCodePoint = prefix.codePointAt(0);
        /* c8 ignore next 3 */
        if (prefixCodePoint === undefined) {
            throw new Error('Invalid prefix character');
        }
        this.prefixCodePoint = prefixCodePoint;
        this.baseDecode = baseDecode;
    }
    decode(text) {
        if (typeof text === 'string') {
            if (text.codePointAt(0) !== this.prefixCodePoint) {
                throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);
            }
            return this.baseDecode(text.slice(this.prefix.length));
        }
        else {
            throw Error('Can only multibase decode strings');
        }
    }
    or(decoder) {
        return or(this, decoder);
    }
}
class ComposedDecoder {
    decoders;
    constructor(decoders) {
        this.decoders = decoders;
    }
    or(decoder) {
        return or(this, decoder);
    }
    decode(input) {
        const prefix = input[0];
        const decoder = this.decoders[prefix];
        if (decoder != null) {
            return decoder.decode(input);
        }
        else {
            throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);
        }
    }
}
export function or(left, right) {
    return new ComposedDecoder({
        ...(left.decoders ?? { [left.prefix]: left }),
        ...(right.decoders ?? { [right.prefix]: right })
    });
}
export class Codec {
    name;
    prefix;
    baseEncode;
    baseDecode;
    encoder;
    decoder;
    constructor(name, prefix, baseEncode, baseDecode) {
        this.name = name;
        this.prefix = prefix;
        this.baseEncode = baseEncode;
        this.baseDecode = baseDecode;
        this.encoder = new Encoder(name, prefix, baseEncode);
        this.decoder = new Decoder(name, prefix, baseDecode);
    }
    encode(input) {
        return this.encoder.encode(input);
    }
    decode(input) {
        return this.decoder.decode(input);
    }
}
export function from({ name, prefix, encode, decode }) {
    return new Codec(name, prefix, encode, decode);
}
export function baseX({ name, prefix, alphabet }) {
    const { encode, decode } = basex(alphabet, name);
    return from({
        prefix,
        name,
        encode,
        decode: (text) => coerce(decode(text))
    });
}
function decode(string, alphabetIdx, bitsPerChar, name) {
    // Count the padding bytes:
    let end = string.length;
    while (string[end - 1] === '=') {
        --end;
    }
    // Allocate the output:
    const out = new Uint8Array((end * bitsPerChar / 8) | 0);
    // Parse the data:
    let bits = 0; // Number of bits currently in the buffer
    let buffer = 0; // Bits waiting to be written out, MSB first
    let written = 0; // Next byte to write
    for (let i = 0; i < end; ++i) {
        // Read one character from the string:
        const value = alphabetIdx[string[i]];
        if (value === undefined) {
            throw new SyntaxError(`Non-${name} character`);
        }
        // Append the bits to the buffer:
        buffer = (buffer << bitsPerChar) | value;
        bits += bitsPerChar;
        // Write out some bits if the buffer has a byte's worth:
        if (bits >= 8) {
            bits -= 8;
            out[written++] = 0xff & (buffer >> bits);
        }
    }
    // Verify that we have received just enough bits:
    if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {
        throw new SyntaxError('Unexpected end of data');
    }
    return out;
}
function encode(data, alphabet, bitsPerChar) {
    const pad = alphabet[alphabet.length - 1] === '=';
    const mask = (1 << bitsPerChar) - 1;
    let out = '';
    let bits = 0; // Number of bits currently in the buffer
    let buffer = 0; // Bits waiting to be written out, MSB first
    for (let i = 0; i < data.length; ++i) {
        // Slurp data into the buffer:
        buffer = (buffer << 8) | data[i];
        bits += 8;
        // Write out as much as we can:
        while (bits > bitsPerChar) {
            bits -= bitsPerChar;
            out += alphabet[mask & (buffer >> bits)];
        }
    }
    // Partial character:
    if (bits !== 0) {
        out += alphabet[mask & (buffer << (bitsPerChar - bits))];
    }
    // Add padding characters until we hit a byte boundary:
    if (pad) {
        while (((out.length * bitsPerChar) & 7) !== 0) {
            out += '=';
        }
    }
    return out;
}
function createAlphabetIdx(alphabet) {
    // Build the character lookup table:
    const alphabetIdx = {};
    for (let i = 0; i < alphabet.length; ++i) {
        alphabetIdx[alphabet[i]] = i;
    }
    return alphabetIdx;
}
/**
 * RFC4648 Factory
 */
export function rfc4648({ name, prefix, bitsPerChar, alphabet }) {
    const alphabetIdx = createAlphabetIdx(alphabet);
    return from({
        prefix,
        name,
        encode(input) {
            return encode(input, alphabet, bitsPerChar);
        },
        decode(input) {
            return decode(input, alphabetIdx, bitsPerChar, name);
        }
    });
}
//# sourceMappingURL=base.js.mapimport { rfc4648 } from './base.js';
export const base32 = rfc4648({
    prefix: 'b',
    name: 'base32',
    alphabet: 'abcdefghijklmnopqrstuvwxyz234567',
    bitsPerChar: 5
});
export const base32upper = rfc4648({
    prefix: 'B',
    name: 'base32upper',
    alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',
    bitsPerChar: 5
});
export const base32pad = rfc4648({
    prefix: 'c',
    name: 'base32pad',
    alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',
    bitsPerChar: 5
});
export const base32padupper = rfc4648({
    prefix: 'C',
    name: 'base32padupper',
    alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',
    bitsPerChar: 5
});
export const base32hex = rfc4648({
    prefix: 'v',
    name: 'base32hex',
    alphabet: '0123456789abcdefghijklmnopqrstuv',
    bitsPerChar: 5
});
export const base32hexupper = rfc4648({
    prefix: 'V',
    name: 'base32hexupper',
    alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',
    bitsPerChar: 5
});
export const base32hexpad = rfc4648({
    prefix: 't',
    name: 'base32hexpad',
    alphabet: '0123456789abcdefghijklmnopqrstuv=',
    bitsPerChar: 5
});
export const base32hexpadupper = rfc4648({
    prefix: 'T',
    name: 'base32hexpadupper',
    alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',
    bitsPerChar: 5
});
export const base32z = rfc4648({
    prefix: 'h',
    name: 'base32z',
    alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',
    bitsPerChar: 5
});
//# sourceMappingURL=base32.js.mapimport { baseX } from './base.js';
export const base36 = baseX({
    prefix: 'k',
    name: 'base36',
    alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'
});
export const base36upper = baseX({
    prefix: 'K',
    name: 'base36upper',
    alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
});
//# sourceMappingURL=base36.js.mapimport { baseX } from './base.js';
export const base58btc = baseX({
    name: 'base58btc',
    prefix: 'z',
    alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
});
export const base58flickr = baseX({
    name: 'base58flickr',
    prefix: 'Z',
    alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'
});
//# sourceMappingURL=base58.js.mapexport const empty = new Uint8Array(0);
export function toHex(d) {
    return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '');
}
export function fromHex(hex) {
    const hexes = hex.match(/../g);
    return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty;
}
export function equals(aa, bb) {
    if (aa === bb) {
        return true;
    }
    if (aa.byteLength !== bb.byteLength) {
        return false;
    }
    for (let ii = 0; ii < aa.byteLength; ii++) {
        if (aa[ii] !== bb[ii]) {
            return false;
        }
    }
    return true;
}
export function coerce(o) {
    if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') {
        return o;
    }
    if (o instanceof ArrayBuffer) {
        return new Uint8Array(o);
    }
    if (ArrayBuffer.isView(o)) {
        return new Uint8Array(o.buffer, o.byteOffset, o.byteLength);
    }
    throw new Error('Unknown type, must be binary type');
}
export function isBinary(o) {
    return o instanceof ArrayBuffer || ArrayBuffer.isView(o);
}
export function fromString(str) {
    return new TextEncoder().encode(str);
}
export function toString(b) {
    return new TextDecoder().decode(b);
}
//# sourceMappingURL=bytes.js.mapimport { base32 } from './bases/base32.js';
import { base36 } from './bases/base36.js';
import { base58btc } from './bases/base58.js';
import { coerce } from './bytes.js';
import * as Digest from './hashes/digest.js';
import * as varint from './varint.js';
// This way TS will also expose all the types from module
export * from './link/interface.js';
export function format(link, base) {
    const { bytes, version } = link;
    switch (version) {
        case 0:
            return toStringV0(bytes, baseCache(link), base ?? base58btc.encoder);
        default:
            return toStringV1(bytes, baseCache(link), (base ?? base32.encoder));
    }
}
export function toJSON(link) {
    return {
        '/': format(link)
    };
}
export function fromJSON(json) {
    return CID.parse(json['/']);
}
const cache = new WeakMap();
function baseCache(cid) {
    const baseCache = cache.get(cid);
    if (baseCache == null) {
        const baseCache = new Map();
        cache.set(cid, baseCache);
        return baseCache;
    }
    return baseCache;
}
export class CID {
    code;
    version;
    multihash;
    bytes;
    '/';
    /**
     * @param version - Version of the CID
     * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
     * @param multihash - (Multi)hash of the of the content.
     */
    constructor(version, code, multihash, bytes) {
        this.code = code;
        this.version = version;
        this.multihash = multihash;
        this.bytes = bytes;
        // flag to serializers that this is a CID and
        // should be treated specially
        this['/'] = bytes;
    }
    /**
     * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`
     * please either use `CID.asCID(cid)` or switch to new signalling mechanism
     *
     * @deprecated
     */
    get asCID() {
        return this;
    }
    // ArrayBufferView
    get byteOffset() {
        return this.bytes.byteOffset;
    }
    // ArrayBufferView
    get byteLength() {
        return this.bytes.byteLength;
    }
    toV0() {
        switch (this.version) {
            case 0: {
                return this;
            }
            case 1: {
                const { code, multihash } = this;
                if (code !== DAG_PB_CODE) {
                    throw new Error('Cannot convert a non dag-pb CID to CIDv0');
                }
                // sha2-256
                if (multihash.code !== SHA_256_CODE) {
                    throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0');
                }
                return (CID.createV0(multihash));
            }
            default: {
                throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);
            }
        }
    }
    toV1() {
        switch (this.version) {
            case 0: {
                const { code, digest } = this.multihash;
                const multihash = Digest.create(code, digest);
                return (CID.createV1(this.code, multihash));
            }
            case 1: {
                return this;
            }
            default: {
                throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);
            }
        }
    }
    equals(other) {
        return CID.equals(this, other);
    }
    static equals(self, other) {
        const unknown = other;
        return (unknown != null &&
            self.code === unknown.code &&
            self.version === unknown.version &&
            Digest.equals(self.multihash, unknown.multihash));
    }
    toString(base) {
        return format(this, base);
    }
    toJSON() {
        return { '/': format(this) };
    }
    link() {
        return this;
    }
    [Symbol.toStringTag] = 'CID';
    // Legacy
    [Symbol.for('nodejs.util.inspect.custom')]() {
        return `CID(${this.toString()})`;
    }
    /**
     * Takes any input `value` and returns a `CID` instance if it was
     * a `CID` otherwise returns `null`. If `value` is instanceof `CID`
     * it will return value back. If `value` is not instance of this CID
     * class, but is compatible CID it will return new instance of this
     * `CID` class. Otherwise returns null.
     *
     * This allows two different incompatible versions of CID library to
     * co-exist and interop as long as binary interface is compatible.
     */
    static asCID(input) {
        if (input == null) {
            return null;
        }
        const value = input;
        if (value instanceof CID) {
            // If value is instance of CID then we're all set.
            return value;
        }
        else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {
            // If value isn't instance of this CID class but `this.asCID === this` or
            // `value['/'] === value.bytes` is true it is CID instance coming from a
            // different implementation (diff version or duplicate). In that case we
            // rebase it to this `CID` implementation so caller is guaranteed to get
            // instance with expected API.
            const { version, code, multihash, bytes } = value;
            return new CID(version, code, multihash, bytes ?? encodeCID(version, code, multihash.bytes));
        }
        else if (value[cidSymbol] === true) {
            // If value is a CID from older implementation that used to be tagged via
            // symbol we still rebase it to the this `CID` implementation by
            // delegating that to a constructor.
            const { version, multihash, code } = value;
            const digest = Digest.decode(multihash);
            return CID.create(version, code, digest);
        }
        else {
            // Otherwise value is not a CID (or an incompatible version of it) in
            // which case we return `null`.
            return null;
        }
    }
    /**
     * @param version - Version of the CID
     * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
     * @param digest - (Multi)hash of the of the content.
     */
    static create(version, code, digest) {
        if (typeof code !== 'number') {
            throw new Error('String codecs are no longer supported');
        }
        if (!(digest.bytes instanceof Uint8Array)) {
            throw new Error('Invalid digest');
        }
        switch (version) {
            case 0: {
                if (code !== DAG_PB_CODE) {
                    throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);
                }
                else {
                    return new CID(version, code, digest, digest.bytes);
                }
            }
            case 1: {
                const bytes = encodeCID(version, code, digest.bytes);
                return new CID(version, code, digest, bytes);
            }
            default: {
                throw new Error('Invalid version');
            }
        }
    }
    /**
     * Simplified version of `create` for CIDv0.
     */
    static createV0(digest) {
        return CID.create(0, DAG_PB_CODE, digest);
    }
    /**
     * Simplified version of `create` for CIDv1.
     *
     * @param code - Content encoding format code.
     * @param digest - Multihash of the content.
     */
    static createV1(code, digest) {
        return CID.create(1, code, digest);
    }
    /**
     * Decoded a CID from its binary representation. The byte array must contain
     * only the CID with no additional bytes.
     *
     * An error will be thrown if the bytes provided do not contain a valid
     * binary representation of a CID.
     */
    static decode(bytes) {
        const [cid, remainder] = CID.decodeFirst(bytes);
        if (remainder.length !== 0) {
            throw new Error('Incorrect length');
        }
        return cid;
    }
    /**
     * Decoded a CID from its binary representation at the beginning of a byte
     * array.
     *
     * Returns an array with the first element containing the CID and the second
     * element containing the remainder of the original byte array. The remainder
     * will be a zero-length byte array if the provided bytes only contained a
     * binary CID representation.
     */
    static decodeFirst(bytes) {
        const specs = CID.inspectBytes(bytes);
        const prefixSize = specs.size - specs.multihashSize;
        const multihashBytes = coerce(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));
        if (multihashBytes.byteLength !== specs.multihashSize) {
            throw new Error('Incorrect length');
        }
        const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);
        const digest = new Digest.Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);
        const cid = specs.version === 0
            ? CID.createV0(digest)
            : CID.createV1(specs.codec, digest);
        return [cid, bytes.subarray(specs.size)];
    }
    /**
     * Inspect the initial bytes of a CID to determine its properties.
     *
     * Involves decoding up to 4 varints. Typically this will require only 4 to 6
     * bytes but for larger multicodec code values and larger multihash digest
     * lengths these varints can be quite large. It is recommended that at least
     * 10 bytes be made available in the `initialBytes` argument for a complete
     * inspection.
     */
    static inspectBytes(initialBytes) {
        let offset = 0;
        const next = () => {
            const [i, length] = varint.decode(initialBytes.subarray(offset));
            offset += length;
            return i;
        };
        let version = next();
        let codec = DAG_PB_CODE;
        if (version === 18) {
            // CIDv0
            version = 0;
            offset = 0;
        }
        else {
            codec = next();
        }
        if (version !== 0 && version !== 1) {
            throw new RangeError(`Invalid CID version ${version}`);
        }
        const prefixSize = offset;
        const multihashCode = next(); // multihash code
        const digestSize = next(); // multihash length
        const size = offset + digestSize;
        const multihashSize = size - prefixSize;
        return { version, codec, multihashCode, digestSize, multihashSize, size };
    }
    /**
     * Takes cid in a string representation and creates an instance. If `base`
     * decoder is not provided will use a default from the configuration. It will
     * throw an error if encoding of the CID is not compatible with supplied (or
     * a default decoder).
     */
    static parse(source, base) {
        const [prefix, bytes] = parseCIDtoBytes(source, base);
        const cid = CID.decode(bytes);
        if (cid.version === 0 && source[0] !== 'Q') {
            throw Error('Version 0 CID string must not include multibase prefix');
        }
        // Cache string representation to avoid computing it on `this.toString()`
        baseCache(cid).set(prefix, source);
        return cid;
    }
}
function parseCIDtoBytes(source, base) {
    switch (source[0]) {
        // CIDv0 is parsed differently
        case 'Q': {
            const decoder = base ?? base58btc;
            return [
                base58btc.prefix,
                decoder.decode(`${base58btc.prefix}${source}`)
            ];
        }
        case base58btc.prefix: {
            const decoder = base ?? base58btc;
            return [base58btc.prefix, decoder.decode(source)];
        }
        case base32.prefix: {
            const decoder = base ?? base32;
            return [base32.prefix, decoder.decode(source)];
        }
        case base36.prefix: {
            const decoder = base ?? base36;
            return [base36.prefix, decoder.decode(source)];
        }
        default: {
            if (base == null) {
                throw Error('To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided');
            }
            return [source[0], base.decode(source)];
        }
    }
}
function toStringV0(bytes, cache, base) {
    const { prefix } = base;
    if (prefix !== base58btc.prefix) {
        throw Error(`Cannot string encode V0 in ${base.name} encoding`);
    }
    const cid = cache.get(prefix);
    if (cid == null) {
        const cid = base.encode(bytes).slice(1);
        cache.set(prefix, cid);
        return cid;
    }
    else {
        return cid;
    }
}
function toStringV1(bytes, cache, base) {
    const { prefix } = base;
    const cid = cache.get(prefix);
    if (cid == null) {
        const cid = base.encode(bytes);
        cache.set(prefix, cid);
        return cid;
    }
    else {
        return cid;
    }
}
const DAG_PB_CODE = 0x70;
const SHA_256_CODE = 0x12;
function encodeCID(version, code, multihash) {
    const codeOffset = varint.encodingLength(version);
    const hashOffset = codeOffset + varint.encodingLength(code);
    const bytes = new Uint8Array(hashOffset + multihash.byteLength);
    varint.encodeTo(version, bytes, 0);
    varint.encodeTo(code, bytes, codeOffset);
    bytes.set(multihash, hashOffset);
    return bytes;
}
const cidSymbol = Symbol.for('@ipld/js-cid/CID');
//# sourceMappingURL=cid.js.mapimport { coerce, equals as equalBytes } from '../bytes.js';
import * as varint from '../varint.js';
/**
 * Creates a multihash digest.
 */
export function create(code, digest) {
    const size = digest.byteLength;
    const sizeOffset = varint.encodingLength(code);
    const digestOffset = sizeOffset + varint.encodingLength(size);
    const bytes = new Uint8Array(digestOffset + size);
    varint.encodeTo(code, bytes, 0);
    varint.encodeTo(size, bytes, sizeOffset);
    bytes.set(digest, digestOffset);
    return new Digest(code, size, digest, bytes);
}
/**
 * Turns bytes representation of multihash digest into an instance.
 */
export function decode(multihash) {
    const bytes = coerce(multihash);
    const [code, sizeOffset] = varint.decode(bytes);
    const [size, digestOffset] = varint.decode(bytes.subarray(sizeOffset));
    const digest = bytes.subarray(sizeOffset + digestOffset);
    if (digest.byteLength !== size) {
        throw new Error('Incorrect length');
    }
    return new Digest(code, size, digest, bytes);
}
export function equals(a, b) {
    if (a === b) {
        return true;
    }
    else {
        const data = b;
        return (a.code === data.code &&
            a.size === data.size &&
            data.bytes instanceof Uint8Array &&
            equalBytes(a.bytes, data.bytes));
    }
}
/**
 * Represents a multihash digest which carries information about the
 * hashing algorithm and an actual hash digest.
 */
export class Digest {
    code;
    size;
    digest;
    bytes;
    /**
     * Creates a multihash digest.
     */
    constructor(code, size, digest, bytes) {
        this.code = code;
        this.size = size;
        this.digest = digest;
        this.bytes = bytes;
    }
}
/**
 * Used to check that the passed multihash has the passed code
 */
export function hasCode(digest, code) {
    return digest.code === code;
}
//# sourceMappingURL=digest.js.mapexport {};
//# sourceMappingURL=interface.js.mapimport varint from './vendor/varint.js';
export function decode(data, offset = 0) {
    const code = varint.decode(data, offset);
    return [code, varint.decode.bytes];
}
export function encodeTo(int, target, offset = 0) {
    varint.encode(int, target, offset);
    return target;
}
export function encodingLength(int) {
    return varint.encodingLength(int);
}
//# sourceMappingURL=varint.js.map/* eslint-disable */
// base-x encoding / decoding
// Copyright (c) 2018 base-x contributors
// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)
// Distributed under the MIT software license, see the accompanying
// file LICENSE or http://www.opensource.org/licenses/mit-license.php.
/**
 * @param {string} ALPHABET
 * @param {any} name
 */
function base(ALPHABET, name) {
    if (ALPHABET.length >= 255) {
        throw new TypeError('Alphabet too long');
    }
    var BASE_MAP = new Uint8Array(256);
    for (var j = 0; j < BASE_MAP.length; j++) {
        BASE_MAP[j] = 255;
    }
    for (var i = 0; i < ALPHABET.length; i++) {
        var x = ALPHABET.charAt(i);
        var xc = x.charCodeAt(0);
        if (BASE_MAP[xc] !== 255) {
            throw new TypeError(x + ' is ambiguous');
        }
        BASE_MAP[xc] = i;
    }
    var BASE = ALPHABET.length;
    var LEADER = ALPHABET.charAt(0);
    var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up
    var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up
    /**
     * @param {any[] | Iterable<number>} source
     */
    function encode(source) {
        // @ts-ignore
        if (source instanceof Uint8Array)
            ;
        else if (ArrayBuffer.isView(source)) {
            source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
        }
        else if (Array.isArray(source)) {
            source = Uint8Array.from(source);
        }
        if (!(source instanceof Uint8Array)) {
            throw new TypeError('Expected Uint8Array');
        }
        if (source.length === 0) {
            return '';
        }
        // Skip & count leading zeroes.
        var zeroes = 0;
        var length = 0;
        var pbegin = 0;
        var pend = source.length;
        while (pbegin !== pend && source[pbegin] === 0) {
            pbegin++;
            zeroes++;
        }
        // Allocate enough space in big-endian base58 representation.
        var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;
        var b58 = new Uint8Array(size);
        // Process the bytes.
        while (pbegin !== pend) {
            var carry = source[pbegin];
            // Apply "b58 = b58 * 256 + ch".
            var i = 0;
            for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {
                carry += (256 * b58[it1]) >>> 0;
                b58[it1] = (carry % BASE) >>> 0;
                carry = (carry / BASE) >>> 0;
            }
            if (carry !== 0) {
                throw new Error('Non-zero carry');
            }
            length = i;
            pbegin++;
        }
        // Skip leading zeroes in base58 result.
        var it2 = size - length;
        while (it2 !== size && b58[it2] === 0) {
            it2++;
        }
        // Translate the result into a string.
        var str = LEADER.repeat(zeroes);
        for (; it2 < size; ++it2) {
            str += ALPHABET.charAt(b58[it2]);
        }
        return str;
    }
    /**
     * @param {string | string[]} source
     */
    function decodeUnsafe(source) {
        if (typeof source !== 'string') {
            throw new TypeError('Expected String');
        }
        if (source.length === 0) {
            return new Uint8Array();
        }
        var psz = 0;
        // Skip leading spaces.
        if (source[psz] === ' ') {
            return;
        }
        // Skip and count leading '1's.
        var zeroes = 0;
        var length = 0;
        while (source[psz] === LEADER) {
            zeroes++;
            psz++;
        }
        // Allocate enough space in big-endian base256 representation.
        var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.
        var b256 = new Uint8Array(size);
        // Process the characters.
        while (source[psz]) {
            // Decode character
            var carry = BASE_MAP[source.charCodeAt(psz)];
            // Invalid character
            if (carry === 255) {
                return;
            }
            var i = 0;
            for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {
                carry += (BASE * b256[it3]) >>> 0;
                b256[it3] = (carry % 256) >>> 0;
                carry = (carry / 256) >>> 0;
            }
            if (carry !== 0) {
                throw new Error('Non-zero carry');
            }
            length = i;
            psz++;
        }
        // Skip trailing spaces.
        if (source[psz] === ' ') {
            return;
        }
        // Skip leading zeroes in b256.
        var it4 = size - length;
        while (it4 !== size && b256[it4] === 0) {
            it4++;
        }
        var vch = new Uint8Array(zeroes + (size - it4));
        var j = zeroes;
        while (it4 !== size) {
            vch[j++] = b256[it4++];
        }
        return vch;
    }
    /**
     * @param {string | string[]} string
     */
    function decode(string) {
        var buffer = decodeUnsafe(string);
        if (buffer) {
            return buffer;
        }
        throw new Error(`Non-${name} character`);
    }
    return {
        encode: encode,
        decodeUnsafe: decodeUnsafe,
        decode: decode
    };
}
var src = base;
var _brrp__multiformats_scope_baseX = src;
export default _brrp__multiformats_scope_baseX;
//# sourceMappingURL=base-x.js.map/* eslint-disable */
var encode_1 = encode;
var MSB = 0x80, REST = 0x7F, MSBALL = ~REST, INT = Math.pow(2, 31);
/**
 * @param {number} num
 * @param {number[]} out
 * @param {number} offset
 */
function encode(num, out, offset) {
    out = out || [];
    offset = offset || 0;
    var oldOffset = offset;
    while (num >= INT) {
        out[offset++] = (num & 0xFF) | MSB;
        num /= 128;
    }
    while (num & MSBALL) {
        out[offset++] = (num & 0xFF) | MSB;
        num >>>= 7;
    }
    out[offset] = num | 0;
    // @ts-ignore
    encode.bytes = offset - oldOffset + 1;
    return out;
}
var decode = read;
var MSB$1 = 0x80, REST$1 = 0x7F;
/**
 * @param {string | any[]} buf
 * @param {number} offset
 */
function read(buf, offset) {
    var res = 0, offset = offset || 0, shift = 0, counter = offset, b, l = buf.length;
    do {
        if (counter >= l) {
            // @ts-ignore
            read.bytes = 0;
            throw new RangeError('Could not decode varint');
        }
        b = buf[counter++];
        res += shift < 28
            ? (b & REST$1) << shift
            : (b & REST$1) * Math.pow(2, shift);
        shift += 7;
    } while (b >= MSB$1);
    // @ts-ignore
    read.bytes = counter - offset;
    return res;
}
var N1 = Math.pow(2, 7);
var N2 = Math.pow(2, 14);
var N3 = Math.pow(2, 21);
var N4 = Math.pow(2, 28);
var N5 = Math.pow(2, 35);
var N6 = Math.pow(2, 42);
var N7 = Math.pow(2, 49);
var N8 = Math.pow(2, 56);
var N9 = Math.pow(2, 63);
var length = function (/** @type {number} */ value) {
    return (value < N1 ? 1
        : value < N2 ? 2
            : value < N3 ? 3
                : value < N4 ? 4
                    : value < N5 ? 5
                        : value < N6 ? 6
                            : value < N7 ? 7
                                : value < N8 ? 8
                                    : value < N9 ? 9
                                        : 10);
};
var varint = {
    encode: encode_1,
    decode: decode,
    encodingLength: length
};
var _brrp_varint = varint;
export default _brrp_varint;
//# sourceMappingURL=varint.js.map{
  "name": "multiformats",
  "version": "13.4.2",
  "description": "Interface for multihash, multicodec, multibase and CID",
  "author": "Mikeal Rogers <mikeal.rogers@gmail.com> (https://www.mikealrogers.com/)",
  "license": "Apache-2.0 OR MIT",
  "homepage": "https://github.com/multiformats/js-multiformats#readme",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/multiformats/js-multiformats.git"
  },
  "bugs": {
    "url": "https://github.com/multiformats/js-multiformats/issues"
  },
  "publishConfig": {
    "access": "public",
    "provenance": true
  },
  "keywords": [
    "ipfs",
    "ipld",
    "multiformats"
  ],
  "type": "module",
  "types": "./dist/src/index.d.ts",
  "typesVersions": {
    "*": {
      "*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ],
      "src/*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ]
    }
  },
  "files": [
    "src",
    "dist",
    "!dist/test",
    "!**/*.tsbuildinfo"
  ],
  "exports": {
    ".": {
      "types": "./dist/src/index.d.ts",
      "import": "./dist/src/index.js"
    },
    "./bases/base10": {
      "types": "./dist/src/bases/base10.d.ts",
      "import": "./dist/src/bases/base10.js"
    },
    "./bases/base16": {
      "types": "./dist/src/bases/base16.d.ts",
      "import": "./dist/src/bases/base16.js"
    },
    "./bases/base2": {
      "types": "./dist/src/bases/base2.d.ts",
      "import": "./dist/src/bases/base2.js"
    },
    "./bases/base256emoji": {
      "types": "./dist/src/bases/base256emoji.d.ts",
      "import": "./dist/src/bases/base256emoji.js"
    },
    "./bases/base32": {
      "types": "./dist/src/bases/base32.d.ts",
      "import": "./dist/src/bases/base32.js"
    },
    "./bases/base36": {
      "types": "./dist/src/bases/base36.d.ts",
      "import": "./dist/src/bases/base36.js"
    },
    "./bases/base58": {
      "types": "./dist/src/bases/base58.d.ts",
      "import": "./dist/src/bases/base58.js"
    },
    "./bases/base64": {
      "types": "./dist/src/bases/base64.d.ts",
      "import": "./dist/src/bases/base64.js"
    },
    "./bases/base8": {
      "types": "./dist/src/bases/base8.d.ts",
      "import": "./dist/src/bases/base8.js"
    },
    "./bases/identity": {
      "types": "./dist/src/bases/identity.d.ts",
      "import": "./dist/src/bases/identity.js"
    },
    "./bases/interface": {
      "types": "./dist/src/bases/interface.d.ts",
      "import": "./dist/src/bases/interface.js"
    },
    "./basics": {
      "types": "./dist/src/basics.d.ts",
      "import": "./dist/src/basics.js"
    },
    "./block": {
      "types": "./dist/src/block.d.ts",
      "import": "./dist/src/block.js"
    },
    "./block/interface": {
      "types": "./dist/src/block/interface.d.ts",
      "import": "./dist/src/block/interface.js"
    },
    "./bytes": {
      "types": "./dist/src/bytes.d.ts",
      "import": "./dist/src/bytes.js"
    },
    "./cid": {
      "types": "./dist/src/cid.d.ts",
      "import": "./dist/src/cid.js"
    },
    "./codecs/interface": {
      "types": "./dist/src/codecs/interface.d.ts",
      "import": "./dist/src/codecs/interface.js"
    },
    "./codecs/json": {
      "types": "./dist/src/codecs/json.d.ts",
      "import": "./dist/src/codecs/json.js"
    },
    "./codecs/raw": {
      "types": "./dist/src/codecs/raw.d.ts",
      "import": "./dist/src/codecs/raw.js"
    },
    "./hashes/digest": {
      "types": "./dist/src/hashes/digest.d.ts",
      "import": "./dist/src/hashes/digest.js"
    },
    "./hashes/hasher": {
      "types": "./dist/src/hashes/hasher.d.ts",
      "import": "./dist/src/hashes/hasher.js"
    },
    "./hashes/identity": {
      "types": "./dist/src/hashes/identity.d.ts",
      "import": "./dist/src/hashes/identity.js"
    },
    "./hashes/interface": {
      "types": "./dist/src/hashes/interface.d.ts",
      "import": "./dist/src/hashes/interface.js"
    },
    "./hashes/sha1": {
      "types": "./dist/types/src/hashes/sha1.d.ts",
      "browser": "./dist/src/hashes/sha1-browser.js",
      "import": "./dist/src/hashes/sha1.js"
    },
    "./hashes/sha2": {
      "types": "./dist/src/hashes/sha2.d.ts",
      "browser": "./dist/src/hashes/sha2-browser.js",
      "import": "./dist/src/hashes/sha2.js"
    },
    "./interface": {
      "types": "./dist/src/interface.d.ts",
      "import": "./dist/src/interface.js"
    },
    "./link": {
      "types": "./dist/src/link.d.ts",
      "import": "./dist/src/link.js"
    },
    "./link/interface": {
      "types": "./dist/src/link/interface.d.ts",
      "import": "./dist/src/link/interface.js"
    },
    "./traversal": {
      "types": "./dist/src/traversal.d.ts",
      "import": "./dist/src/traversal.js"
    }
  },
  "eslintConfig": {
    "extends": "ipfs",
    "parserOptions": {
      "project": true,
      "sourceType": "module"
    }
  },
  "release": {
    "branches": [
      "master"
    ],
    "plugins": [
      [
        "@semantic-release/commit-analyzer",
        {
          "preset": "conventionalcommits",
          "releaseRules": [
            {
              "breaking": true,
              "release": "major"
            },
            {
              "revert": true,
              "release": "patch"
            },
            {
              "type": "feat",
              "release": "minor"
            },
            {
              "type": "fix",
              "release": "patch"
            },
            {
              "type": "docs",
              "release": "patch"
            },
            {
              "type": "test",
              "release": "patch"
            },
            {
              "type": "deps",
              "release": "patch"
            },
            {
              "scope": "no-release",
              "release": false
            }
          ]
        }
      ],
      [
        "@semantic-release/release-notes-generator",
        {
          "preset": "conventionalcommits",
          "presetConfig": {
            "types": [
              {
                "type": "feat",
                "section": "Features"
              },
              {
                "type": "fix",
                "section": "Bug Fixes"
              },
              {
                "type": "chore",
                "section": "Trivial Changes"
              },
              {
                "type": "docs",
                "section": "Documentation"
              },
              {
                "type": "deps",
                "section": "Dependencies"
              },
              {
                "type": "test",
                "section": "Tests"
              }
            ]
          }
        }
      ],
      "@semantic-release/changelog",
      "@semantic-release/npm",
      "@semantic-release/github",
      [
        "@semantic-release/git",
        {
          "assets": [
            "CHANGELOG.md",
            "package.json"
          ]
        }
      ]
    ]
  },
  "scripts": {
    "clean": "aegir clean",
    "lint": "aegir lint",
    "build": "aegir build",
    "release": "aegir release",
    "docs": "aegir docs",
    "test": "npm run lint && npm run test:node && npm run test:chrome",
    "test:node": "aegir test -t node --cov",
    "test:chrome": "aegir test -t browser --cov",
    "test:chrome-webworker": "aegir test -t webworker",
    "test:firefox": "aegir test -t browser -- --browser firefox",
    "test:firefox-webworker": "aegir test -t webworker -- --browser firefox",
    "test:electron-main": "aegir test -t electron-main"
  },
  "devDependencies": {
    "@stablelib/sha256": "^2.0.0",
    "@stablelib/sha512": "^2.0.0",
    "@types/node": "^25.0.0",
    "aegir": "^47.0.7",
    "buffer": "^6.0.3",
    "cids": "^1.1.9",
    "crypto-hash": "^4.0.0"
  },
  "aegir": {
    "test": {
      "target": [
        "node",
        "browser"
      ]
    }
  },
  "browser": {
    "./hashes/sha1": "./dist/src/hashes/sha1-browser.js",
    "./dist/src/hashes/sha1.js": "./dist/src/hashes/sha1-browser.js",
    "./hashes/sha2": "./dist/src/hashes/sha2-browser.js",
    "./dist/src/hashes/sha2.js": "./dist/src/hashes/sha2-browser.js"
  }
}
var queueTick = require('queue-tick')

var mutexify = function () {
  var queue = []
  var used = null

  var call = function () {
    used(release)
  }

  var acquire = function (fn) {
    if (used) return queue.push(fn)
    used = fn
    acquire.locked = true
    queueTick(call)
    return 0
  }

  acquire.locked = false

  var release = function (fn, err, value) {
    used = null
    acquire.locked = false
    if (queue.length) acquire(queue.shift())
    if (fn) fn(err, value)
  }

  return acquire
}

module.exports = mutexify
{
  "name": "mutexify",
  "version": "1.4.0",
  "description": "mutex lock for javascript",
  "main": "index.js",
  "dependencies": {
    "queue-tick": "^1.0.0"
  },
  "devDependencies": {
    "standard": "^14.3.3",
    "tape": "^3.0.2"
  },
  "scripts": {
    "test": "tape test.js",
    "posttest": "npm run lint",
    "lint": "standard"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/mutexify.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/mutexify/issues"
  },
  "keywords": [
    "mutex",
    "lock"
  ],
  "homepage": "https://github.com/mafintosh/mutexify"
}
var mutexify = require('.')

var mutexifyPromise = function () {
  var lock = mutexify()

  var acquire = function () {
    return new Promise(lock)
  }

  Object.defineProperty(acquire, 'locked', {
    get: function () { return lock.locked },
    enumerable: true
  })

  return acquire
}

module.exports = mutexifyPromise
module.exports = assert

class AssertionError extends Error {}
AssertionError.prototype.name = 'AssertionError'

/**
 * Minimal assert function
 * @param  {any} t Value to check if falsy
 * @param  {string=} m Optional assertion error message
 * @throws {AssertionError}
 */
function assert (t, m) {
  if (!t) {
    var err = new AssertionError(m)
    if (Error.captureStackTrace) Error.captureStackTrace(err, assert)
    throw err
  }
}
{
  "name": "nanoassert",
  "version": "2.0.0",
  "description": "Nanoscale assertion module",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "tape": "^4.9.1"
  },
  "scripts": {
    "test": "tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/emilbayes/nanoassert.git"
  },
  "keywords": [
    "assert",
    "unassert",
    "power-assert",
    "tiny",
    "nano",
    "pico"
  ],
  "author": "Emil Bay <github@tixz.dk>",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/emilbayes/nanoassert/issues"
  },
  "homepage": "https://github.com/emilbayes/nanoassert#readme"
}
/* eslint-disable camelcase */
const sodium = require('sodium-universal')
const assert = require('nanoassert')
const b4a = require('b4a')

const DHLEN = sodium.crypto_scalarmult_ed25519_BYTES
const PKLEN = sodium.crypto_scalarmult_ed25519_BYTES
const SCALARLEN = sodium.crypto_scalarmult_ed25519_BYTES
const SKLEN = sodium.crypto_sign_SECRETKEYBYTES
const ALG = 'Ed25519'

module.exports = {
  DHLEN,
  PKLEN,
  SCALARLEN,
  SKLEN,
  ALG,
  name: ALG,
  generateKeyPair,
  dh
}

function generateKeyPair (privKey) {
  if (privKey) return generateSeedKeyPair(privKey.subarray(0, 32))

  const keyPair = {}
  keyPair.secretKey = b4a.alloc(SKLEN)
  keyPair.publicKey = b4a.alloc(PKLEN)

  sodium.crypto_sign_keypair(keyPair.publicKey, keyPair.secretKey)
  return keyPair
}

function generateSeedKeyPair (seed) {
  const keyPair = {}
  keyPair.secretKey = b4a.alloc(SKLEN)
  keyPair.publicKey = b4a.alloc(PKLEN)

  sodium.crypto_sign_seed_keypair(keyPair.publicKey, keyPair.secretKey, seed)
  return keyPair
}

function dh (publicKey, { scalar, secretKey }) {
  // tweaked keys expose scalar directly
  if (!scalar) {
    assert(secretKey.byteLength === SKLEN)

    // libsodium stores seed not actual scalar
    const sk = b4a.alloc(64)
    sodium.crypto_hash_sha512(sk, secretKey.subarray(0, 32))
    sk[0] &= 248
    sk[31] &= 127
    sk[31] |= 64

    scalar = sk.subarray(0, 32)
  }

  assert(scalar.byteLength === SCALARLEN)
  assert(publicKey.byteLength === PKLEN)

  const output = b4a.alloc(DHLEN)

  // we clamp if necessary above
  sodium.crypto_scalarmult_ed25519_noclamp(
    output,
    scalar,
    publicKey
  )

  return output
}
{
  "name": "noise-curve-ed",
  "version": "2.1.0",
  "description": "Ed25519 elliptic curve operations for [`noise-handshake`](https://github.com/chm-diederichs/noise-handshake)",
  "main": "index.js",
  "scripts": {
    "test": "npx standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/chm-diederichs/noise-curve-ed.git"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/chm-diederichs/noise-curve-ed/issues"
  },
  "homepage": "https://github.com/chm-diederichs/noise-curve-ed#readme",
  "dependencies": {
    "b4a": "^1.1.0",
    "nanoassert": "^2.0.0",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "noise-handshake": "^3.0.0",
    "standard": "^16.0.3",
    "tape": "^5.2.2"
  }
}
const sodium = require('sodium-universal')
const b4a = require('b4a')

module.exports = class CipherState {
  constructor (key) {
    this.key = key || null
    this.nonce = 0
    this.CIPHER_ALG = 'ChaChaPoly'
  }

  initialiseKey (key) {
    this.key = key
    this.nonce = 0
  }

  setNonce (nonce) {
    this.nonce = nonce
  }

  encrypt (plaintext, ad) {
    if (!this.hasKey) return plaintext
    if (!ad) ad = b4a.alloc(0)

    const ciphertext = encryptWithAD(this.key, this.nonce, ad, plaintext)
    if (ciphertext.length > 65535) throw new Error(`ciphertext length of ${ciphertext.length} exceeds maximum Noise message length of 65535`)
    this.nonce++

    return ciphertext
  }

  decrypt (ciphertext, ad) {
    if (!this.hasKey) return ciphertext
    if (!ad) ad = b4a.alloc(0)
    if (ciphertext.length > 65535) throw new Error(`ciphertext length of ${ciphertext.length} exceeds maximum Noise message length of 65535`)

    const plaintext = decryptWithAD(this.key, this.nonce, ad, ciphertext)
    this.nonce++

    return plaintext
  }

  get hasKey () {
    return this.key !== null
  }

  _clear () {
    sodium.sodium_memzero(this.key)
    this.key = null
    this.nonce = null
  }

  static get MACBYTES () {
    return 16
  }

  static get NONCEBYTES () {
    return 8
  }

  static get KEYBYTES () {
    return 32
  }
}

function encryptWithAD (key, counter, additionalData, plaintext) {
  // for our purposes, additionalData will always be a pubkey so we encode from hex
  if (!b4a.isBuffer(additionalData)) additionalData = b4a.from(additionalData, 'hex')
  if (!b4a.isBuffer(plaintext)) plaintext = b4a.from(plaintext, 'hex')

  const nonce = b4a.alloc(sodium.crypto_aead_chacha20poly1305_ietf_NPUBBYTES)
  const view = new DataView(nonce.buffer, nonce.byteOffset, nonce.byteLength)
  view.setUint32(4, counter, true)

  const ciphertext = b4a.alloc(plaintext.byteLength + sodium.crypto_aead_chacha20poly1305_ietf_ABYTES)

  sodium.crypto_aead_chacha20poly1305_ietf_encrypt(ciphertext, plaintext, additionalData, null, nonce, key)
  return ciphertext
}

function decryptWithAD (key, counter, additionalData, ciphertext) {
  // for our purposes, additionalData will always be a pubkey so we encode from hex
  if (!b4a.isBuffer(additionalData)) additionalData = b4a.from(additionalData, 'hex')
  if (!b4a.isBuffer(ciphertext)) ciphertext = b4a.from(ciphertext, 'hex')

  const nonce = b4a.alloc(sodium.crypto_aead_chacha20poly1305_ietf_NPUBBYTES)
  const view = new DataView(nonce.buffer, nonce.byteOffset, nonce.byteLength)
  view.setUint32(4, counter, true)

  const plaintext = b4a.alloc(ciphertext.byteLength - sodium.crypto_aead_chacha20poly1305_ietf_ABYTES)

  sodium.crypto_aead_chacha20poly1305_ietf_decrypt(plaintext, null, ciphertext, additionalData, nonce, key)
  return plaintext
}
/* eslint-disable camelcase */
const {
  crypto_kx_SEEDBYTES,
  crypto_kx_keypair,
  crypto_kx_seed_keypair,
  crypto_scalarmult_BYTES,
  crypto_scalarmult_SCALARBYTES,
  crypto_scalarmult,
  crypto_scalarmult_base
} = require('sodium-universal')

const assert = require('nanoassert')
const b4a = require('b4a')

const DHLEN = crypto_scalarmult_BYTES
const PKLEN = crypto_scalarmult_BYTES
const SKLEN = crypto_scalarmult_SCALARBYTES
const SEEDLEN = crypto_kx_SEEDBYTES
const ALG = '25519'

module.exports = {
  DHLEN,
  PKLEN,
  SKLEN,
  SEEDLEN,
  ALG,
  generateKeyPair,
  generateSeedKeyPair,
  dh
}

function generateKeyPair (privKey) {
  const keyPair = {}

  keyPair.secretKey = privKey || b4a.alloc(SKLEN)
  keyPair.publicKey = b4a.alloc(PKLEN)

  if (privKey) {
    crypto_scalarmult_base(keyPair.publicKey, keyPair.secretKey)
  } else {
    crypto_kx_keypair(keyPair.publicKey, keyPair.secretKey)
  }

  return keyPair
}

function generateSeedKeyPair (seed) {
  assert(seed.byteLength === SKLEN)

  const keyPair = {}
  keyPair.secretKey = b4a.alloc(SKLEN)
  keyPair.publicKey = b4a.alloc(PKLEN)

  crypto_kx_seed_keypair(keyPair.publicKey, keyPair.secretKey, seed)
  return keyPair
}

function dh (publicKey, { secretKey }) {
  assert(secretKey.byteLength === SKLEN)
  assert(publicKey.byteLength === PKLEN)

  const output = b4a.alloc(DHLEN)

  crypto_scalarmult(
    output,
    secretKey,
    publicKey
  )

  return output
}
const hmacBlake2b = require('./hmac')
const b4a = require('b4a')

const HASHLEN = 64

module.exports = {
  hkdf,
  HASHLEN
}

// HMAC-based Extract-and-Expand KDF
// https://www.ietf.org/rfc/rfc5869.txt

function hkdf (salt, inputKeyMaterial, info = '', length = 2 * HASHLEN) {
  const pseudoRandomKey = hkdfExtract(salt, inputKeyMaterial)
  return hkdfExpand(pseudoRandomKey, info, length)
}

function hkdfExtract (salt, inputKeyMaterial) {
  const hmac = b4a.alloc(HASHLEN)
  return hmacDigest(hmac, salt, inputKeyMaterial)
}

function hkdfExpand (key, info, length) {
  // Put in dedicated slab to avoid keeping shared slab from being gc'ed
  const buffer = b4a.allocUnsafeSlow(length)

  const infoBuf = b4a.from(info)
  let prev = infoBuf

  const result = []
  for (let i = 0; i < length; i += HASHLEN) {
    const pos = b4a.from([(i / HASHLEN) + 1])

    const out = buffer.subarray(i, i + HASHLEN)
    result.push(out)

    prev = hmacDigest(out, key, [prev, infoBuf, pos])
  }

  return result
}

function hmacDigest (out, key, input) {
  hmacBlake2b(out, input, key)
  return out
}
/* eslint-disable camelcase */
const b4a = require('b4a')
const { sodium_memzero, crypto_generichash, crypto_generichash_batch } = require('sodium-universal')

const HASHLEN = 64
const BLOCKLEN = 128
const scratch = b4a.alloc(BLOCKLEN * 3)
const HMACKey = scratch.subarray(BLOCKLEN * 0, BLOCKLEN * 1)
const OuterKeyPad = scratch.subarray(BLOCKLEN * 1, BLOCKLEN * 2)
const InnerKeyPad = scratch.subarray(BLOCKLEN * 2, BLOCKLEN * 3)

// Post-fill is done in the cases where someone caught an exception that
// happened before we were able to clear data at the end

module.exports = function hmac (out, batch, key) {
  if (key.byteLength > BLOCKLEN) {
    crypto_generichash(HMACKey.subarray(0, HASHLEN), key)
    sodium_memzero(HMACKey.subarray(HASHLEN))
  } else {
    // Covers key <= BLOCKLEN
    HMACKey.set(key)
    sodium_memzero(HMACKey.subarray(key.byteLength))
  }

  for (let i = 0; i < HMACKey.byteLength; i++) {
    OuterKeyPad[i] = 0x5c ^ HMACKey[i]
    InnerKeyPad[i] = 0x36 ^ HMACKey[i]
  }
  sodium_memzero(HMACKey)

  crypto_generichash_batch(out, [InnerKeyPad].concat(batch))
  sodium_memzero(InnerKeyPad)
  crypto_generichash_batch(out, [OuterKeyPad, out])
  sodium_memzero(OuterKeyPad)
}

module.exports.BYTES = HASHLEN
module.exports.KEYBYTES = BLOCKLEN
const assert = require('nanoassert')
const b4a = require('b4a')

const SymmetricState = require('./symmetric-state')
const { HASHLEN } = require('./hkdf')

const PRESHARE_IS = Symbol('initiator static key preshared')
const PRESHARE_RS = Symbol('responder static key preshared')

const TOK_PSK = Symbol('psk')

const TOK_S = Symbol('s')
const TOK_E = Symbol('e')

const TOK_ES = Symbol('es')
const TOK_SE = Symbol('se')
const TOK_EE = Symbol('ee')
const TOK_SS = Symbol('ss')

const HANDSHAKES = Object.freeze({
  NN: [
    [TOK_E],
    [TOK_E, TOK_EE]
  ],
  NNpsk0: [
    [TOK_PSK, TOK_E],
    [TOK_E, TOK_EE]
  ],
  XX: [
    [TOK_E],
    [TOK_E, TOK_EE, TOK_S, TOK_ES],
    [TOK_S, TOK_SE]
  ],
  XXpsk0: [
    [TOK_PSK, TOK_E],
    [TOK_E, TOK_EE, TOK_S, TOK_ES],
    [TOK_S, TOK_SE]
  ],
  IK: [
    PRESHARE_RS,
    [TOK_E, TOK_ES, TOK_S, TOK_SS],
    [TOK_E, TOK_EE, TOK_SE]
  ],
  XK: [
    PRESHARE_RS,
    [TOK_E, TOK_ES],
    [TOK_E, TOK_EE],
    [TOK_S, TOK_SE]
  ]
})

class Writer {
  constructor () {
    this.size = 0
    this.buffers = []
  }

  push (b) {
    this.size += b.byteLength
    this.buffers.push(b)
  }

  end () {
    const all = b4a.alloc(this.size)
    let offset = 0
    for (const b of this.buffers) {
      all.set(b, offset)
      offset += b.byteLength
    }
    return all
  }
}

class Reader {
  constructor (buf) {
    this.offset = 0
    this.buffer = buf
  }

  shift (n) {
    const start = this.offset
    const end = this.offset += n
    if (end > this.buffer.byteLength) throw new Error('Insufficient bytes')
    return this.buffer.subarray(start, end)
  }

  end () {
    return this.shift(this.buffer.byteLength - this.offset)
  }
}

module.exports = class NoiseState extends SymmetricState {
  constructor (pattern, initiator, staticKeypair, opts = {}) {
    super(opts)

    this.s = staticKeypair || this.curve.generateKeyPair()
    this.e = null

    this.psk = null
    if (opts && opts.psk) this.psk = opts.psk

    this.re = null
    this.rs = null

    this.pattern = pattern
    this.handshake = HANDSHAKES[this.pattern].slice()

    this.isPskHandshake = !!this.psk && hasPskToken(this.handshake)

    this.protocol = b4a.from([
      'Noise',
      this.pattern,
      this.DH_ALG,
      this.CIPHER_ALG,
      'BLAKE2b'
    ].join('_'))

    this.initiator = initiator
    this.complete = false

    this.rx = null
    this.tx = null
    this.hash = null
  }

  initialise (prologue, remoteStatic) {
    if (this.protocol.byteLength <= HASHLEN) this.digest.set(this.protocol)
    else this.mixHash(this.protocol)

    this.chainingKey = b4a.from(this.digest)

    this.mixHash(prologue)

    while (!Array.isArray(this.handshake[0])) {
      const message = this.handshake.shift()

      // handshake steps should be as arrays, only
      // preshare tokens are provided otherwise
      assert(message === PRESHARE_RS || message === PRESHARE_IS,
        'Unexpected pattern')

      const takeRemoteKey = this.initiator
        ? message === PRESHARE_RS
        : message === PRESHARE_IS

      if (takeRemoteKey) this.rs = remoteStatic

      const key = takeRemoteKey ? this.rs : this.s.publicKey
      assert(key != null, 'Remote pubkey required')

      this.mixHash(key)
    }
  }

  final () {
    const [k1, k2] = this.split()

    this.tx = this.initiator ? k1 : k2
    this.rx = this.initiator ? k2 : k1

    this.complete = true
    this.hash = this.getHandshakeHash()

    this._clear()
  }

  recv (buf) {
    const r = new Reader(buf)

    for (const pattern of this.handshake.shift()) {
      switch (pattern) {
        case TOK_PSK :
          this.mixKeyAndHash(this.psk)
          break

        case TOK_E :
          this.re = r.shift(this.curve.PKLEN)
          this.mixHash(this.re)
          if (this.isPskHandshake) this.mixKeyNormal(this.re)
          break

        case TOK_S : {
          const klen = this.hasKey ? this.curve.PKLEN + 16 : this.curve.PKLEN
          this.rs = this.decryptAndHash(r.shift(klen))
          break
        }

        case TOK_EE :
        case TOK_ES :
        case TOK_SE :
        case TOK_SS : {
          const useStatic = keyPattern(pattern, this.initiator)

          const localKey = useStatic.local ? this.s : this.e
          const remoteKey = useStatic.remote ? this.rs : this.re

          this.mixKey(remoteKey, localKey)
          break
        }

        default :
          throw new Error('Unexpected message')
      }
    }

    const payload = this.decryptAndHash(r.end())

    if (!this.handshake.length) this.final()
    return payload
  }

  send (payload = b4a.alloc(0)) {
    const w = new Writer()

    for (const pattern of this.handshake.shift()) {
      switch (pattern) {
        case TOK_PSK :
          this.mixKeyAndHash(this.psk)
          break

        case TOK_E :
          if (this.e === null) this.e = this.curve.generateKeyPair()
          this.mixHash(this.e.publicKey)
          if (this.isPskHandshake) this.mixKeyNormal(this.e.publicKey)
          w.push(this.e.publicKey)
          break

        case TOK_S :
          w.push(this.encryptAndHash(this.s.publicKey))
          break

        case TOK_ES :
        case TOK_SE :
        case TOK_EE :
        case TOK_SS : {
          const useStatic = keyPattern(pattern, this.initiator)

          const localKey = useStatic.local ? this.s : this.e
          const remoteKey = useStatic.remote ? this.rs : this.re

          this.mixKey(remoteKey, localKey)
          break
        }

        default :
          throw new Error('Unexpected message')
      }
    }

    w.push(this.encryptAndHash(payload))
    const response = w.end()

    if (!this.handshake.length) this.final()
    return response
  }

  _clear () {
    super._clear()

    this.e.secretKey.fill(0)
    this.e.publicKey.fill(0)

    this.re.fill(0)

    this.e = null
    this.re = null
  }
}

function keyPattern (pattern, initiator) {
  const ret = {
    local: false,
    remote: false
  }

  switch (pattern) {
    case TOK_EE:
      return ret

    case TOK_ES:
      ret.local ^= !initiator
      ret.remote ^= initiator
      return ret

    case TOK_SE:
      ret.local ^= initiator
      ret.remote ^= !initiator
      return ret

    case TOK_SS:
      ret.local ^= 1
      ret.remote ^= 1
      return ret
  }
}

function hasPskToken (handshake) {
  return handshake.some(x => {
    return Array.isArray(x) && x.indexOf(TOK_PSK) !== -1
  })
}
{
  "name": "noise-handshake",
  "version": "4.2.0",
  "description": "Noise protocol handshake",
  "main": "noise.js",
  "files": [
    "*.js"
  ],
  "scripts": {
    "test": "standard && brittle test/*.js"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/noise-handshake.git"
  },
  "dependencies": {
    "b4a": "^1.1.0",
    "nanoassert": "^2.0.0",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "noise-protocol": "chm-diederichs/noise-protocol.git#xx-ephemeral-key",
    "standard": "^16.0.3"
  }
}
const sodium = require('sodium-universal')
const assert = require('nanoassert')
const b4a = require('b4a')
const CipherState = require('./cipher')
const curve = require('./dh')
const { HASHLEN, hkdf } = require('./hkdf')

module.exports = class SymmetricState extends CipherState {
  constructor (opts = {}) {
    super()

    this.curve = opts.curve || curve
    this.digest = b4a.alloc(HASHLEN)
    this.chainingKey = null
    this.offset = 0

    this.DH_ALG = this.curve.ALG
  }

  mixHash (data) {
    accumulateDigest(this.digest, data)
  }

  mixKeyAndHash (key) {
    const [ck, tempH, tempK] = hkdf(this.chainingKey, key, '', 3 * HASHLEN)
    this.chainingKey = ck
    this.mixHash(tempH)
    this.initialiseKey(tempK.subarray(0, 32))
  }

  mixKeyNormal (key) {
    const [ck, tempK] = hkdf(this.chainingKey, key)
    this.chainingKey = ck
    this.initialiseKey(tempK.subarray(0, 32))
  }

  mixKey (remoteKey, localKey) {
    const dh = this.curve.dh(remoteKey, localKey)
    const hkdfResult = hkdf(this.chainingKey, dh)
    this.chainingKey = hkdfResult[0]
    this.initialiseKey(hkdfResult[1].subarray(0, 32))
  }

  encryptAndHash (plaintext) {
    const ciphertext = this.encrypt(plaintext, this.digest)
    accumulateDigest(this.digest, ciphertext)
    return ciphertext
  }

  decryptAndHash (ciphertext) {
    const plaintext = this.decrypt(ciphertext, this.digest)
    accumulateDigest(this.digest, ciphertext)
    return plaintext
  }

  getHandshakeHash (out) {
    if (!out) return this.getHandshakeHash(b4a.alloc(HASHLEN))
    assert(out.byteLength === HASHLEN, `output must be ${HASHLEN} bytes`)

    out.set(this.digest)
    return out
  }

  split () {
    const res = hkdf(this.chainingKey, b4a.alloc(0))
    return res.map(k => k.subarray(0, 32))
  }

  _clear () {
    super._clear()

    sodium.sodium_memzero(this.digest)
    sodium.sodium_memzero(this.chainingKey)

    this.digest = null
    this.chainingKey = null
    this.offset = null

    this.curve = null
  }

  static get alg () {
    return CipherState.alg + '_BLAKE2b'
  }
}

function accumulateDigest (digest, input) {
  const toHash = b4a.concat([digest, input])
  sodium.crypto_generichash(digest, toHash)
}
var varint = require('varint')
var svarint = require('signed-varint')
var b4a = require('b4a')

exports.make = encoder

exports.name = function (enc) {
  var keys = Object.keys(exports)
  for (var i = 0; i < keys.length; i++) {
    if (exports[keys[i]] === enc) return keys[i]
  }
  return null
}

exports.skip = function (type, buffer, offset) {
  switch (type) {
    case 0:
      varint.decode(buffer, offset)
      return offset + varint.decode.bytes

    case 1:
      return offset + 8

    case 2:
      var len = varint.decode(buffer, offset)
      return offset + varint.decode.bytes + len

    case 3:
    case 4:
      throw new Error('Groups are not supported')

    case 5:
      return offset + 4
  }

  throw new Error('Unknown wire type: ' + type)
}

exports.bytes = encoder(2,
  function encode (val, buffer, offset) {
    var oldOffset = offset
    var len = bufferLength(val)

    varint.encode(len, buffer, offset)
    offset += varint.encode.bytes

    if (b4a.isBuffer(val)) b4a.copy(val, buffer, offset)
    else b4a.write(buffer, val, offset, len)
    offset += len

    encode.bytes = offset - oldOffset
    return buffer
  },
  function decode (buffer, offset) {
    var oldOffset = offset

    var len = varint.decode(buffer, offset)
    offset += varint.decode.bytes

    var val = buffer.subarray(offset, offset + len)
    offset += val.length

    decode.bytes = offset - oldOffset
    return val
  },
  function encodingLength (val) {
    var len = bufferLength(val)
    return varint.encodingLength(len) + len
  }
)

exports.string = encoder(2,
  function encode (val, buffer, offset) {
    var oldOffset = offset
    var len = b4a.byteLength(val)

    varint.encode(len, buffer, offset, 'utf-8')
    offset += varint.encode.bytes

    b4a.write(buffer, val, offset, len)
    offset += len

    encode.bytes = offset - oldOffset
    return buffer
  },
  function decode (buffer, offset) {
    var oldOffset = offset

    var len = varint.decode(buffer, offset)
    offset += varint.decode.bytes

    var val = b4a.toString(buffer, 'utf-8', offset, offset + len)
    offset += len

    decode.bytes = offset - oldOffset
    return val
  },
  function encodingLength (val) {
    var len = b4a.byteLength(val)
    return varint.encodingLength(len) + len
  }
)

exports.bool = encoder(0,
  function encode (val, buffer, offset) {
    buffer[offset] = val ? 1 : 0
    encode.bytes = 1
    return buffer
  },
  function decode (buffer, offset) {
    var bool = buffer[offset] > 0
    decode.bytes = 1
    return bool
  },
  function encodingLength () {
    return 1
  }
)

exports.int32 = encoder(0,
  function encode (val, buffer, offset) {
    varint.encode(val < 0 ? val + 4294967296 : val, buffer, offset)
    encode.bytes = varint.encode.bytes
    return buffer
  },
  function decode (buffer, offset) {
    var val = varint.decode(buffer, offset)
    decode.bytes = varint.decode.bytes
    return val > 2147483647 ? val - 4294967296 : val
  },
  function encodingLength (val) {
    return varint.encodingLength(val < 0 ? val + 4294967296 : val)
  }
)

exports.int64 = encoder(0,
  function encode (val, buffer, offset) {
    if (val < 0) {
      var last = offset + 9
      varint.encode(val * -1, buffer, offset)
      offset += varint.encode.bytes - 1
      buffer[offset] = buffer[offset] | 0x80
      while (offset < last - 1) {
        offset++
        buffer[offset] = 0xff
      }
      buffer[last] = 0x01
      encode.bytes = 10
    } else {
      varint.encode(val, buffer, offset)
      encode.bytes = varint.encode.bytes
    }
    return buffer
  },
  function decode (buffer, offset) {
    var val = varint.decode(buffer, offset)
    if (val >= Math.pow(2, 63)) {
      var limit = 9
      while (buffer[offset + limit - 1] === 0xff) limit--
      limit = limit || 9
      var subset = b4a.allocUnsafe(limit)
      b4a.copy(buffer, subset, 0, offset, offset + limit)
      subset[limit - 1] = subset[limit - 1] & 0x7f
      val = -1 * varint.decode(subset, 0)
      decode.bytes = 10
    } else {
      decode.bytes = varint.decode.bytes
    }
    return val
  },
  function encodingLength (val) {
    return val < 0 ? 10 : varint.encodingLength(val)
  }
)

exports.sint32 =
exports.sint64 = encoder(0,
  svarint.encode,
  svarint.decode,
  svarint.encodingLength
)

exports.uint32 =
exports.uint64 =
exports.enum =
exports.varint = encoder(0,
  varint.encode,
  varint.decode,
  varint.encodingLength
)

// we cannot represent these in javascript so we just use buffers
exports.fixed64 =
exports.sfixed64 = encoder(1,
  function encode (val, buffer, offset) {
    b4a.copy(val, buffer, offset)
    encode.bytes = 8
    return buffer
  },
  function decode (buffer, offset) {
    var val = buffer.subarray(offset, offset + 8)
    decode.bytes = 8
    return val
  },
  function encodingLength () {
    return 8
  }
)

exports.double = encoder(1,
  function encode (val, buffer, offset) {
    b4a.writeDoubleLE(buffer, val, offset)
    encode.bytes = 8
    return buffer
  },
  function decode (buffer, offset) {
    var val = b4a.readDoubleLE(buffer, offset)
    decode.bytes = 8
    return val
  },
  function encodingLength () {
    return 8
  }
)

exports.fixed32 = encoder(5,
  function encode (val, buffer, offset) {
    b4a.writeUInt32LE(buffer, val, offset)
    encode.bytes = 4
    return buffer
  },
  function decode (buffer, offset) {
    var val = b4a.readUInt32LE(buffer, offset)
    decode.bytes = 4
    return val
  },
  function encodingLength () {
    return 4
  }
)

exports.sfixed32 = encoder(5,
  function encode (val, buffer, offset) {
    b4a.writeInt32LE(buffer, val, offset)
    encode.bytes = 4
    return buffer
  },
  function decode (buffer, offset) {
    var val = b4a.readInt32LE(buffer, offset)
    decode.bytes = 4
    return val
  },
  function encodingLength () {
    return 4
  }
)

exports.float = encoder(5,
  function encode (val, buffer, offset) {
    b4a.writeFloatLE(buffer, val, offset)
    encode.bytes = 4
    return buffer
  },
  function decode (buffer, offset) {
    var val = b4a.readFloatLE(buffer, offset)
    decode.bytes = 4
    return val
  },
  function encodingLength () {
    return 4
  }
)

function encoder (type, encode, decode, encodingLength) {
  encode.bytes = decode.bytes = 0

  return {
    type: type,
    encode: encode,
    decode: decode,
    encodingLength: encodingLength
  }
}

function bufferLength (val) {
  return b4a.isBuffer(val) ? val.length : b4a.byteLength(val)
}
{
  "name": "protocol-buffers-encodings",
  "version": "1.2.0",
  "description": "Base encodings for protocol-buffers",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.6.0",
    "signed-varint": "^2.0.1",
    "varint": "5.0.0"
  },
  "devDependencies": {
    "standard": "^14.3.4",
    "tape": "^5.0.1"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/protocol-buffers-encodings.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/protocol-buffers-encodings/issues"
  },
  "homepage": "https://github.com/mafintosh/protocol-buffers-encodings"
}
const b4a = require('b4a')
const c = require('compact-encoding')
const queueTick = require('queue-tick')
const safetyCatch = require('safety-catch')
const unslab = require('unslab')

const MAX_BUFFERED = 32768
const MAX_BACKLOG = Infinity // TODO: impl "open" backpressure
const MAX_BATCH = 8 * 1024 * 1024

class Channel {
  constructor(
    mux,
    info,
    userData,
    protocol,
    aliases,
    id,
    handshake,
    messages,
    onopen,
    onclose,
    ondestroy,
    ondrain
  ) {
    this.userData = userData
    this.protocol = protocol
    this.aliases = aliases
    this.id = id
    this.handshake = null
    this.messages = []

    this.opened = false
    this.closed = false
    this.destroyed = false

    this.onopen = onopen
    this.onclose = onclose
    this.ondestroy = ondestroy
    this.ondrain = ondrain

    this._handshake = handshake
    this._mux = mux
    this._info = info
    this._localId = 0
    this._remoteId = 0
    this._active = 0
    this._extensions = null

    this._decBound = this._dec.bind(this)
    this._decAndDestroyBound = this._decAndDestroy.bind(this)

    this._openedPromise = null
    this._openedResolve = null

    this._destroyedPromise = null
    this._destroyedResolve = null

    for (const m of messages) this.addMessage(m)
  }

  get drained() {
    return this._mux.drained
  }

  fullyOpened() {
    if (this.opened) return Promise.resolve(true)
    if (this.closed) return Promise.resolve(false)
    if (this._openedPromise) return this._openedPromise

    this._openedPromise = new Promise((resolve) => {
      this._openedResolve = resolve
    })
    return this._openedPromise
  }

  fullyClosed() {
    if (this.destroyed) return Promise.resolve()
    if (this._destroyedPromise) return this._destroyedPromise

    this._destroyedPromise = new Promise((resolve) => {
      this._destroyedResolve = resolve
    })
    return this._destroyedPromise
  }

  open(handshake) {
    const id = this._mux._free.length > 0 ? this._mux._free.pop() : this._mux._local.push(null) - 1

    this._info.opened++
    this._info.lastChannel = this
    this._localId = id + 1
    this._mux._local[id] = this

    if (this._remoteId === 0) {
      this._info.outgoing.push(this._localId)
    }

    const state = { buffer: null, start: 2, end: 2 }

    c.uint.preencode(state, this._localId)
    c.string.preencode(state, this.protocol)
    c.optionalBuffer.preencode(state, this.id)
    if (this._handshake) this._handshake.preencode(state, handshake)

    state.buffer = this._mux._alloc(state.end)

    state.buffer[0] = 0
    state.buffer[1] = 1
    c.uint.encode(state, this._localId)
    c.string.encode(state, this.protocol)
    c.optionalBuffer.encode(state, this.id)
    if (this._handshake) this._handshake.encode(state, handshake)

    this._mux._write0(state.buffer)
  }

  _dec() {
    if (--this._active === 0 && this.closed === true) this._destroy()
  }

  _decAndDestroy(err) {
    this._dec()
    this._mux._safeDestroy(err)
  }

  _fullyOpenSoon() {
    this._mux._remote[this._remoteId - 1].session = this
    queueTick(this._fullyOpenOrDestroy.bind(this))
  }

  _fullyOpenOrDestroy() {
    try {
      this._fullyOpen()
    } catch (err) {
      this._mux._safeDestroyBound(err)
    }
  }

  _fullyOpen() {
    if (this.opened === true || this.closed === true) return

    const remote = this._mux._remote[this._remoteId - 1]

    this.handshake = this._handshake ? this._handshake.decode(remote.state) : null
    this._track(this.onopen(this.handshake, this))

    remote.session = this
    remote.state = null
    if (remote.pending !== null) this._drain(remote)
    if (this._mux._destroying === true) return

    this.opened = true
    this._resolveOpen(true)
  }

  _resolveOpen(opened) {
    if (this._openedResolve !== null) {
      this._openedResolve(opened)
      this._openedResolve = this._openedPromise = null
    }
  }

  _resolveDestroyed() {
    if (this._destroyedResolve !== null) {
      this._destroyedResolve()
      this._destroyedResolve = this._destroyedPromise = null
    }
  }

  _drain(remote) {
    for (let i = 0; i < remote.pending.length; i++) {
      const p = remote.pending[i]
      this._mux._buffered -= byteSize(p.state)
      this._recv(p.type, p.state)
      if (this._mux._destroying === true) return
    }

    remote.pending = null
    this._mux._resumeMaybe()
  }

  _track(p) {
    if (isPromise(p) === true) {
      this._active++
      return p.then(this._decBound, this._decAndDestroyBound)
    }

    return null
  }

  _close(isRemote) {
    if (this.closed === true) return
    this.closed = true

    this._info.opened--
    if (this._info.lastChannel === this) this._info.lastChannel = null

    if (this._remoteId > 0) {
      this._mux._remote[this._remoteId - 1] = null
      this._remoteId = 0
      // If remote has acked, we can reuse the local id now
      // otherwise, we need to wait for the "ack" to arrive
      this._mux._free.push(this._localId - 1)
    }

    this._mux._local[this._localId - 1] = null
    this._localId = 0

    this._mux._gc(this._info)
    this._track(this.onclose(isRemote, this))

    if (this._active === 0) this._destroy()

    this._resolveOpen(false)
  }

  _destroy() {
    if (this.destroyed === true) return
    this.destroyed = true
    this._track(this.ondestroy(this))
    this._resolveDestroyed()
  }

  _recv(type, state) {
    if (type < this.messages.length) {
      const m = this.messages[type]
      const p = m.recv(state, this)
      if (m.autoBatch === true) return p
    }
    return null
  }

  cork() {
    this._mux.cork()
  }

  uncork() {
    this._mux.uncork()
  }

  close() {
    if (this.closed === true) return

    const state = { buffer: null, start: 2, end: 2 }

    c.uint.preencode(state, this._localId)

    state.buffer = this._mux._alloc(state.end)

    state.buffer[0] = 0
    state.buffer[1] = 3
    c.uint.encode(state, this._localId)

    this._close(false)
    this._mux._write0(state.buffer)
  }

  addMessage(opts) {
    if (!opts) return this._skipMessage()

    const type = this.messages.length
    const autoBatch = opts.autoBatch !== false
    const encoding = opts.encoding || c.raw
    const onmessage = opts.onmessage || noop

    const s = this
    const typeLen = encodingLength(c.uint, type)

    const m = {
      type,
      autoBatch,
      encoding,
      onmessage,
      recv(state, session) {
        return session._track(m.onmessage(encoding.decode(state), session))
      },
      send(m, session = s) {
        if (session.closed === true) return false

        const mux = session._mux
        const state = { buffer: null, start: 0, end: typeLen }

        if (mux._batch !== null) {
          encoding.preencode(state, m)
          state.buffer = mux._alloc(state.end)

          c.uint.encode(state, type)
          encoding.encode(state, m)

          mux._pushBatch(session._localId, state.buffer)
          return true
        }

        c.uint.preencode(state, session._localId)
        encoding.preencode(state, m)

        state.buffer = mux._alloc(state.end)

        c.uint.encode(state, session._localId)
        c.uint.encode(state, type)
        encoding.encode(state, m)

        mux.drained = mux.stream.write(state.buffer)

        return mux.drained
      }
    }

    this.messages.push(m)

    return m
  }

  _skipMessage() {
    const type = this.messages.length
    const m = {
      type,
      encoding: c.raw,
      onmessage: noop,
      recv(state, session) {},
      send(m, session) {}
    }

    this.messages.push(m)
    return m
  }
}

module.exports = class Protomux {
  constructor(stream, { alloc } = {}) {
    if (stream.userData === null) stream.userData = this

    this.isProtomux = true
    this.stream = stream
    this.corked = 0
    this.drained = true

    this._alloc =
      alloc || (typeof stream.alloc === 'function' ? stream.alloc.bind(stream) : b4a.allocUnsafe)
    this._safeDestroyBound = this._safeDestroy.bind(this)
    this._uncorkBound = this.uncork.bind(this)

    this._remoteBacklog = 0
    this._buffered = 0
    this._paused = false
    this._remote = []
    this._local = []
    this._free = []
    this._batch = null
    this._batchState = null

    this._infos = new Map()
    this._notify = new Map()
    // stream.destroyed flips asynchronously on streamx-based transports.
    this._destroying = false

    this.stream.on('data', this._ondata.bind(this))
    this.stream.on('drain', this._ondrain.bind(this))
    this.stream.on('end', this._onend.bind(this))
    this.stream.on('error', noop) // we handle this in "close"
    this.stream.on('close', this._shutdown.bind(this))
  }

  static from(stream, opts) {
    if (stream.userData && stream.userData.isProtomux) return stream.userData
    if (stream.isProtomux) return stream
    return new this(stream, opts)
  }

  static isProtomux(mux) {
    return typeof mux === 'object' && mux.isProtomux === true
  }

  *[Symbol.iterator]() {
    for (const session of this._local) {
      if (session !== null) yield session
    }
  }

  isIdle() {
    return this._local.length === this._free.length
  }

  cork() {
    if (++this.corked === 1) {
      this._batch = []
      this._batchState = { buffer: null, start: 0, end: 1 }
    }
  }

  uncork() {
    if (--this.corked === 0) {
      this._sendBatch(this._batch, this._batchState)
      this._batch = null
      this._batchState = null
    }
  }

  getLastChannel({ protocol, id = null }) {
    const key = toKey(protocol, id)
    const info = this._infos.get(key)
    if (info) return info.lastChannel
    return null
  }

  pair({ protocol, id = null }, notify) {
    this._notify.set(toKey(protocol, id), notify)
  }

  unpair({ protocol, id = null }) {
    this._notify.delete(toKey(protocol, id))
  }

  opened({ protocol, id = null }) {
    const key = toKey(protocol, id)
    const info = this._infos.get(key)
    return info ? info.opened > 0 : false
  }

  createChannel({
    userData = null,
    protocol,
    aliases = [],
    id = null,
    unique = true,
    handshake = null,
    messages = [],
    onopen = noop,
    onclose = noop,
    ondestroy = noop,
    ondrain = noop
  }) {
    if (this.stream.destroyed) return null

    const info = this._get(protocol, id, aliases)
    if (unique && info.opened > 0) return null

    if (info.incoming.length === 0) {
      return new Channel(
        this,
        info,
        userData,
        protocol,
        aliases,
        id,
        handshake,
        messages,
        onopen,
        onclose,
        ondestroy,
        ondrain
      )
    }

    this._remoteBacklog--

    const remoteId = info.incoming.shift()
    const r = this._remote[remoteId - 1]
    if (r === null) return null

    const session = new Channel(
      this,
      info,
      userData,
      protocol,
      aliases,
      id,
      handshake,
      messages,
      onopen,
      onclose,
      ondestroy,
      ondrain
    )

    session._remoteId = remoteId
    session._fullyOpenSoon()

    return session
  }

  _pushBatch(localId, buffer) {
    if (this._batchState.end >= MAX_BATCH) {
      this._sendBatch(this._batch, this._batchState)
      this._batch = []
      this._batchState = { buffer: null, start: 0, end: 1 }
    }

    if (this._batch.length === 0 || this._batch[this._batch.length - 1].localId !== localId) {
      this._batchState.end++
      c.uint.preencode(this._batchState, localId)
    }
    c.buffer.preencode(this._batchState, buffer)
    this._batch.push({ localId, buffer })
  }

  _sendBatch(batch, state) {
    if (batch.length === 0) return

    let prev = batch[0].localId

    state.buffer = this._alloc(state.end)
    state.buffer[state.start++] = 0
    state.buffer[state.start++] = 0

    c.uint.encode(state, prev)

    for (let i = 0; i < batch.length; i++) {
      const b = batch[i]
      if (prev !== b.localId) {
        state.buffer[state.start++] = 0
        c.uint.encode(state, (prev = b.localId))
      }
      c.buffer.encode(state, b.buffer)
    }

    this.drained = this.stream.write(state.buffer)
  }

  _get(protocol, id, aliases = []) {
    const key = toKey(protocol, id)

    let info = this._infos.get(key)
    if (info) return info

    info = {
      key,
      protocol,
      aliases: [],
      id,
      pairing: 0,
      opened: 0,
      incoming: [],
      outgoing: [],
      lastChannel: null
    }
    this._infos.set(key, info)

    for (const alias of aliases) {
      const key = toKey(alias, id)
      info.aliases.push(key)

      this._infos.set(key, info)
    }

    return info
  }

  _gc(info) {
    if (info.opened === 0 && info.outgoing.length === 0 && info.incoming.length === 0) {
      this._infos.delete(info.key)

      for (const alias of info.aliases) this._infos.delete(alias)
    }
  }

  _ondata(buffer) {
    if (buffer.byteLength === 0) return // ignore empty frames...
    try {
      const state = { buffer, start: 0, end: buffer.byteLength }
      this._decode(c.uint.decode(state), state)
    } catch (err) {
      this._safeDestroy(err)
    }
  }

  _ondrain() {
    this.drained = true

    for (const s of this._local) {
      if (s !== null) s._track(s.ondrain(s))
    }
  }

  _onend() {
    // TODO: support half open mode for the users who wants that here
    this.stream.end()
  }

  _decode(remoteId, state) {
    const type = c.uint.decode(state)

    if (remoteId === 0) {
      return this._oncontrolsession(type, state)
    }

    const r = remoteId <= this._remote.length ? this._remote[remoteId - 1] : null

    // if the channel is closed ignore - could just be a pipeline message...
    if (r === null) return null

    if (r.pending !== null) {
      this._bufferMessage(r, type, state)
      return null
    }

    return r.session._recv(type, state)
  }

  _oncontrolsession(type, state) {
    switch (type) {
      case 0:
        this._onbatch(state)
        break

      case 1:
        // return the promise back up as this has sideeffects so we can batch reply
        return this._onopensession(state)

      case 2:
        this._onrejectsession(state)
        break

      case 3:
        this._onclosesession(state)
        break
    }

    return null
  }

  _bufferMessage(r, type, { buffer, start, end }) {
    const state = { buffer, start, end } // copy
    r.pending.push({ type, state })
    this._buffered += byteSize(state)
    this._pauseMaybe()
  }

  _pauseMaybe() {
    if (this._paused === true || this._buffered <= MAX_BUFFERED) return
    this._paused = true
    this.stream.pause()
  }

  _resumeMaybe() {
    if (this._paused === false || this._buffered > MAX_BUFFERED) return
    this._paused = false
    this.stream.resume()
  }

  _onbatch(state) {
    const end = state.end
    let remoteId = c.uint.decode(state)

    let waiting = null

    while (state.end > state.start) {
      const len = c.uint.decode(state)
      if (len === 0) {
        remoteId = c.uint.decode(state)
        continue
      }
      state.end = state.start + len
      // if batch contains more than one message, cork it so we reply back with a batch
      if (end !== state.end && waiting === null) {
        waiting = []
        this.cork()
      }
      const p = this._decode(remoteId, state)
      if (waiting !== null && p !== null) waiting.push(p)
      state.start = state.end
      state.end = end
    }

    if (waiting !== null) {
      // the waiting promises are not allowed to throw but we destroy the stream in case we are wrong
      Promise.all(waiting).then(this._uncorkBound, this._safeDestroyBound)
    }
  }

  _onopensession(state) {
    const remoteId = c.uint.decode(state)
    const protocol = c.string.decode(state)
    const id = unslab(c.optionalBuffer.decode(state))

    // remote tried to open the control session - auto reject for now
    // as we can use as an explicit control protocol declaration if we need to
    if (remoteId === 0) {
      this._rejectSession(0)
      return null
    }

    const rid = remoteId - 1
    const info = this._get(protocol, id)

    // allow the remote to grow the ids by one
    if (this._remote.length === rid) {
      this._remote.push(null)
    }

    if (rid >= this._remote.length || this._remote[rid] !== null) {
      throw new Error('Invalid open message')
    }

    if (info.outgoing.length > 0) {
      const localId = info.outgoing.shift()
      const session = this._local[localId - 1]

      if (session === null) {
        // we already closed the channel - ignore
        this._free.push(localId - 1)
        return null
      }

      this._remote[rid] = { state, pending: null, session: null }

      session._remoteId = remoteId
      session._fullyOpen()
      return null
    }

    const copyState = { buffer: state.buffer, start: state.start, end: state.end }
    this._remote[rid] = { state: copyState, pending: [], session: null }

    if (++this._remoteBacklog > MAX_BACKLOG) {
      throw new Error('Remote exceeded backlog')
    }

    info.pairing++
    info.incoming.push(remoteId)

    return this._requestSession(protocol, id, info).catch(this._safeDestroyBound)
  }

  _onrejectsession(state) {
    const localId = c.uint.decode(state)

    // TODO: can be done smarter...
    for (const info of this._infos.values()) {
      const i = info.outgoing.indexOf(localId)
      if (i === -1) continue

      info.outgoing.splice(i, 1)

      const session = this._local[localId - 1]

      this._free.push(localId - 1)
      if (session !== null) session._close(true)

      this._gc(info)
      return
    }

    throw new Error('Invalid reject message')
  }

  _onclosesession(state) {
    const remoteId = c.uint.decode(state)

    if (remoteId === 0) return // ignore

    const rid = remoteId - 1
    const r = rid < this._remote.length ? this._remote[rid] : null

    if (r === null) return

    if (r.session !== null) r.session._close(true)
  }

  async _requestSession(protocol, id, info) {
    const notify = this._notify.get(toKey(protocol, id)) || this._notify.get(toKey(protocol, null))

    if (notify) await notify(id)

    if (--info.pairing > 0) return

    while (info.incoming.length > 0) {
      this._rejectSession(info, info.incoming.shift())
    }

    this._gc(info)
  }

  _rejectSession(info, remoteId) {
    if (remoteId > 0) {
      const r = this._remote[remoteId - 1]

      if (r.pending !== null) {
        for (let i = 0; i < r.pending.length; i++) {
          this._buffered -= byteSize(r.pending[i].state)
        }
      }

      this._remote[remoteId - 1] = null
      this._resumeMaybe()
    }

    const state = { buffer: null, start: 2, end: 2 }

    c.uint.preencode(state, remoteId)

    state.buffer = this._alloc(state.end)

    state.buffer[0] = 0
    state.buffer[1] = 2
    c.uint.encode(state, remoteId)

    this._write0(state.buffer)
  }

  _write0(buffer) {
    if (this._batch !== null) {
      this._pushBatch(0, buffer.subarray(1))
      return
    }

    this.drained = this.stream.write(buffer)
  }

  destroy(err) {
    this._destroying = true
    this.stream.destroy(err)
  }

  _safeDestroy(err) {
    safetyCatch(err)
    this._destroying = true
    this.stream.destroy(err)
  }

  _shutdown() {
    this._destroying = true
    for (const s of this._local) {
      if (s !== null) s._close(true)
    }
  }
}

function noop() {}

function toKey(protocol, id) {
  return protocol + '##' + (id ? b4a.toString(id, 'hex') : '')
}

function byteSize(state) {
  return 512 + (state.end - state.start)
}

function isPromise(p) {
  return !!(p && typeof p.then === 'function')
}

function encodingLength(enc, val) {
  const state = { buffer: null, start: 0, end: 0 }
  enc.preencode(state, val)
  return state.end
}
{
  "name": "protomux",
  "version": "3.11.0",
  "description": "Multiplex multiple message oriented protocols over a stream",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.3.1",
    "compact-encoding": "^3.0.0",
    "queue-tick": "^1.0.0",
    "safety-catch": "^1.0.1",
    "unslab": "^1.3.0"
  },
  "devDependencies": {
    "@hyperswarm/secret-stream": "^6.0.0",
    "brittle": "^3.0.0",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/protomux.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/protomux/issues"
  },
  "homepage": "https://github.com/holepunchto/protomux"
}
{
  "name": "queue-tick",
  "version": "1.0.1",
  "description": "Next tick shim that prefers process.nextTick over queueMicrotask for compat",
  "main": "./process-next-tick.js",
  "browser": "./queue-microtask.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^16.0.3",
    "tape": "^5.3.1"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/queue-tick.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/queue-tick/issues"
  },
  "homepage": "https://github.com/mafintosh/queue-tick"
}
module.exports = (typeof process !== 'undefined' && typeof process.nextTick === 'function')
  ? process.nextTick.bind(process)
  : require('./queue-microtask')
module.exports = typeof queueMicrotask === 'function' ? queueMicrotask : (fn) => Promise.resolve().then(fn)
require.addon = require('require-addon')

module.exports = require.addon('.', __filename)
const binding = require('./binding')

exports.get = function get(field, bit) {
  const n = field.byteLength * 8

  if (bit < 0) bit += n
  if (bit < 0 || bit >= n) return false

  return binding.quickbit_napi_get(toBuffer(field), bit) !== 0
}

exports.set = function set(field, bit, value = true) {
  const n = field.byteLength * 8

  if (bit < 0) bit += n
  if (bit < 0 || bit >= n) return false

  return binding.quickbit_napi_set(toBuffer(field), bit, value ? 1 : 0) !== 0
}

exports.fill = function fill(
  field,
  value,
  start = 0,
  end = field.byteLength * 8
) {
  const n = field.byteLength * 8

  if (start < 0) start += n
  if (end < 0) end += n
  if (start < 0 || start >= field.byteLength * 8 || start >= end) return field

  binding.quickbit_napi_fill(toBuffer(field), value ? 1 : 0, start, end)
  return field
}

exports.clear = function clear(field, ...chunks) {
  binding.quickbit_napi_clear(toBuffer(field), chunks.map(toBufferChunk))
}

exports.findFirst = function findFirst(field, value, position = 0) {
  const n = field.byteLength * 8

  if (position < 0) position += n
  if (position < 0) position = 0
  if (position >= n) return -1

  return binding.quickbit_napi_find_first(
    toBuffer(field),
    value ? 1 : 0,
    position
  )
}

exports.findLast = function findLast(
  field,
  value,
  position = field.byteLength * 8 - 1
) {
  const n = field.byteLength * 8

  if (position < 0) position += n
  if (position < 0) return -1
  if (position >= n) position = n - 1

  return binding.quickbit_napi_find_last(
    toBuffer(field),
    value ? 1 : 0,
    position
  )
}

function toBuffer(field) {
  if (field.BYTES_PER_ELEMENT === 1) return field
  return new Uint8Array(field.buffer, field.byteOffset, field.byteLength)
}

function toBufferChunk(chunk) {
  return { field: toBuffer(chunk.field), offset: chunk.offset }
}

class Index {
  static from(fieldOrChunks, byteLength = -1) {
    if (Array.isArray(fieldOrChunks)) {
      return new SparseIndex(fieldOrChunks, byteLength)
    } else {
      return new DenseIndex(fieldOrChunks, byteLength)
    }
  }

  constructor(byteLength) {
    this._byteLength = byteLength
    this.handle = Buffer.allocUnsafe(binding.sizeof_quickbit_index_t)
  }

  get byteLength() {
    return this._byteLength
  }

  skipFirst(value, position = 0) {
    const n = this.byteLength * 8

    if (position < 0) position += n
    if (position < 0) position = 0
    if (position >= n) return n - 1

    return binding.quickbit_napi_skip_first(
      this.handle,
      this.byteLength,
      value ? 1 : 0,
      position
    )
  }

  skipLast(value, position = this.byteLength * 8 - 1) {
    const n = this.byteLength * 8

    if (position < 0) position += n
    if (position < 0) return 0
    if (position >= n) position = n - 1

    return binding.quickbit_napi_skip_last(
      this.handle,
      this.byteLength,
      value ? 1 : 0,
      position
    )
  }
}

exports.Index = Index

class DenseIndex extends Index {
  constructor(field, byteLength) {
    super(byteLength)
    this.field = field

    binding.quickbit_napi_index_init(this.handle, toBuffer(this.field))
  }

  get byteLength() {
    if (this._byteLength !== -1) return this._byteLength
    return this.field.byteLength
  }

  update(bit) {
    const n = this.byteLength * 8

    if (bit < 0) bit += n
    if (bit < 0 || bit >= n) return false

    return (
      binding.quickbit_napi_index_update(
        this.handle,
        toBuffer(this.field),
        bit
      ) !== 0
    )
  }
}

function selectChunk(chunks, offset) {
  for (let i = 0; i < chunks.length; i++) {
    const next = chunks[i]

    const start = next.offset
    const end = next.offset + next.field.byteLength

    if (offset >= start && offset + 16 <= end) {
      return next
    }
  }

  return null
}

class SparseIndex extends Index {
  constructor(chunks, byteLength) {
    super(byteLength)
    this.chunks = chunks

    binding.quickbit_napi_index_init_sparse(
      this.handle,
      this.chunks.map(toBufferChunk)
    )
  }

  get byteLength() {
    if (this._byteLength !== -1) return this._byteLength
    const last = this.chunks[this.chunks.length - 1]
    return last ? last.offset + last.field.byteLength : 0
  }

  update(bit) {
    const n = this.byteLength * 8

    if (bit < 0) bit += n
    if (bit < 0 || bit >= n) return false

    const j = Math.floor(bit / 128)

    const offset = j * 16

    const chunk = selectChunk(this.chunks, offset)

    if (chunk === null) return false

    return (
      binding.quickbit_napi_index_update_sparse(
        this.handle,
        toBuffer(chunk.field),
        chunk.offset,
        bit
      ) !== 0
    )
  }
}
{
  "name": "quickbit-native",
  "version": "2.4.8",
  "description": "libquickbit JavaScript bindings for Node.js",
  "main": "index.js",
  "files": [
    "index.js",
    "macros.h",
    "binding.cc",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "npm run lint && npm run test:bare && npm run test:node",
    "test:bare": "bare test.mjs",
    "test:node": "node test.mjs",
    "lint": "prettier . --check"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/quickbit-native.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/quickbit-native/issues"
  },
  "homepage": "https://github.com/holepunchto/quickbit-native#readme",
  "dependencies": {
    "require-addon": "^1.1.0"
  },
  "devDependencies": {
    "b4a": "^1.6.7",
    "bare-compat-napi": "^1.3.2",
    "brittle": "^3.1.0",
    "cmake-bare": "^1.1.7",
    "cmake-fetch": "^1.1.0",
    "cmake-napi": "^1.0.2",
    "prettier": "^3.5.3",
    "prettier-config-standard": "^7.0.0"
  }
}
const simdle = require('simdle-universal')

const INDEX_LEN = (16 /* root */ + 128 * 16 /* children */) * 2

const get = exports.get = function get (field, bit) {
  const n = field.byteLength * 8

  if (bit < 0) bit += n
  if (bit < 0 || bit >= n) return false

  const m = field.BYTES_PER_ELEMENT * 8

  const offset = bit & (m - 1)
  const i = (bit - offset) / m

  return (field[i] & (1 << offset)) !== 0
}

const set = exports.set = function set (field, bit, value = true) {
  const n = field.byteLength * 8

  if (bit < 0) bit += n
  if (bit < 0 || bit >= n) return false

  const m = field.BYTES_PER_ELEMENT * 8

  const offset = bit & (m - 1)
  const i = (bit - offset) / m
  const mask = 1 << offset

  if (value) {
    if ((field[i] & mask) !== 0) return false
  } else {
    if ((field[i] & mask) === 0) return false
  }

  field[i] ^= mask

  return true
}

exports.fill = function fill (field, value, start = 0, end = field.byteLength * 8) {
  const n = field.byteLength * 8

  if (start < 0) start += n
  if (end < 0) end += n
  if (start < 0 || start >= field.byteLength * 8 || start >= end) return field

  const m = field.BYTES_PER_ELEMENT * 8

  let i, j

  {
    const offset = start & (m - 1)
    i = (start - offset) / m

    if (offset !== 0) {
      let shift = m - offset
      if (end - start < shift) shift = end - start

      const mask = ((1 << shift) - 1) << offset

      if (value) field[i] |= mask
      else field[i] &= ~mask

      i++
    }
  }

  {
    const offset = end & (m - 1)
    j = (end - offset) / m

    if (offset !== 0 && j >= i) {
      const mask = (1 << offset) - 1

      if (value) field[j] |= mask
      else field[j] &= ~mask
    }
  }

  if (i < j) field.fill(value ? (2 ** m) - 1 : 0, i, j)

  return field
}

exports.clear = function clear (field, ...chunks) {
  const n = field.byteLength

  for (const chunk of chunks) {
    if (chunk.offset >= n) continue

    const m = chunk.field.byteLength

    let i = chunk.offset
    let j = 0

    while (((i & 15) !== 0 || (j & 15) !== 0) && i < n && j < m) {
      field[i] = field[i] & ~chunk.field[j]
      i++
      j++
    }

    if (i + 15 < n && j + 15 < m) {
      const len = Math.min(n - (n & 15) - i, m - (m & 15) - j)

      simdle.clear(field.subarray(i, i + len), chunk.field.subarray(j, j + len), field.subarray(i, i + len))
    }

    while (i < n && j < m) {
      field[i] = field[i] & ~chunk.field[j]
      i++
      j++
    }
  }
}

function bitOffset (bit, offset) {
  return !bit ? offset : (INDEX_LEN * 8 / 2) + offset
}

function byteOffset (bit, offset) {
  return !bit ? offset : (INDEX_LEN / 2) + offset
}

exports.findFirst = function findFirst (field, value, position = 0) {
  const n = field.byteLength * 8

  if (position < 0) position += n
  if (position < 0) position = 0
  if (position >= n) return -1

  value = !!value

  for (let i = position; i < n; i++) {
    if (get(field, i) === value) return i
  }

  return -1
}

exports.findLast = function findLast (field, value, position = field.byteLength * 8 - 1) {
  const n = field.byteLength * 8

  if (position < 0) position += n
  if (position < 0) return -1
  if (position >= n) position = n - 1

  value = !!value

  for (let i = position; i >= 0; i--) {
    if (get(field, i) === value) return i
  }

  return -1
}

const Index = exports.Index = class Index {
  static from (fieldOrChunks, byteLength = -1) {
    if (Array.isArray(fieldOrChunks)) {
      return new SparseIndex(fieldOrChunks, byteLength)
    } else {
      return new DenseIndex(fieldOrChunks, byteLength)
    }
  }

  constructor (byteLength) {
    this._byteLength = byteLength
    this.handle = new Uint32Array(INDEX_LEN / 4)
  }

  get byteLength () {
    return this._byteLength
  }

  skipFirst (value, position = 0) {
    const n = this.byteLength * 8

    if (position < 0) position += n
    if (position < 0) position = 0
    if (position >= n) return n - 1

    let i = Math.floor(position / 16384)

    if (i > 127) return position

    while (i <= 127 && get(this.handle, bitOffset(value, i))) {
      i++
    }

    if (i === 128) return n - 1

    let k = i * 16384
    let j = 0

    if (position > k) j = Math.floor((position - k) / 128)

    while (j <= 127 && get(this.handle, bitOffset(value, i * 128 + j + 128))) {
      j++
      k += 128
    }

    if (j === 128 && i !== 127) return this.skipFirst(value, (i + 1) * 16384)

    if (k > position) position = k

    return position < n ? position : n - 1
  }

  skipLast (value, position = this.byteLength * 8 - 1) {
    const n = this.byteLength * 8

    if (position < 0) position += n
    if (position < 0) return 0
    if (position >= n) position = n - 1

    let i = Math.floor(position / 16384)

    if (i > 127) return position

    while (i >= 0 && get(this.handle, bitOffset(value, i))) {
      i--
    }

    if (i === -1) return 0

    let k = ((i + 1) * 16384) - 1
    let j = 127

    if (position < k) j = 128 - Math.ceil((k - position) / 128)

    while (j >= 0 && get(this.handle, bitOffset(value, i * 128 + j + 128))) {
      j--
      k -= 128
    }

    if (j === -1 && i !== 0) return this.skipLast(value, i * 16384 - 1)

    if (k < position) position = k

    return position
  }
}

class DenseIndex extends Index {
  constructor (field, byteLength) {
    super(byteLength)
    this.field = field

    const m = field.BYTES_PER_ELEMENT

    for (let i = 0; i < 128; i++) {
      for (let j = 0; j < 128; j++) {
        const offset = (i * 128 + j) * 16
        let allz = true
        let allo = false

        if (offset + 16 <= this.field.byteLength) {
          const vec = this.field.subarray(offset / m, (offset + 16) / m)

          allz = simdle.allz(vec)
          allo = simdle.allo(vec)
        }

        const k = i * 128 + 128 + j

        set(this.handle, bitOffset(false, k), allz)
        set(this.handle, bitOffset(true, k), allo)
      }

      {
        const offset = byteOffset(false, i * 16 + 16) / 4
        const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

        set(this.handle, bitOffset(false, i), allo)
      }

      {
        const offset = byteOffset(true, i * 16 + 16) / 4
        const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

        set(this.handle, bitOffset(true, i), allo)
      }
    }
  }

  get byteLength () {
    if (this._byteLength !== -1) return this._byteLength
    return this.field.byteLength
  }

  update (bit) {
    const n = this.byteLength * 8

    if (bit < 0) bit += n
    if (bit < 0 || bit >= n) return false

    const m = this.field.BYTES_PER_ELEMENT

    const i = Math.floor(bit / 16384)
    const j = Math.floor(bit / 128)

    const offset = (j * 16) / m
    const vec = this.field.subarray(offset, offset + (16 / m))

    const allz = simdle.allz(vec)
    const allo = simdle.allo(vec)

    let changed = false

    if (set(this.handle, bitOffset(false, 128 + j), allz)) {
      changed = true

      const offset = byteOffset(false, i * 16 + 16) / 4
      const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

      set(this.handle, bitOffset(false, i), allo)
    }

    if (set(this.handle, bitOffset(true, 128 + j), allo)) {
      changed = true

      const offset = byteOffset(true, i * 16 + 16) / 4
      const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

      set(this.handle, bitOffset(true, i), allo)
    }

    return changed
  }
}

function selectChunk (chunks, offset) {
  for (let i = 0; i < chunks.length; i++) {
    const next = chunks[i]

    const start = next.offset
    const end = next.offset + next.field.byteLength

    if (offset >= start && offset + 16 <= end) {
      return next
    }
  }

  return null
}

class SparseIndex extends Index {
  constructor (chunks, byteLength) {
    super(byteLength)
    this.chunks = chunks

    for (let i = 0; i < 128; i++) {
      for (let j = 0; j < 128; j++) {
        const offset = (i * 128 + j) * 16
        let allz = true
        let allo = false

        const chunk = selectChunk(this.chunks, offset)

        if (chunk !== null) {
          const m = chunk.field.BYTES_PER_ELEMENT

          const vec = chunk.field.subarray((offset - chunk.offset) / m, (offset - chunk.offset + 16) / m)

          allz = simdle.allz(vec)
          allo = simdle.allo(vec)
        }

        const k = i * 128 + 128 + j

        set(this.handle, bitOffset(false, k), allz)
        set(this.handle, bitOffset(true, k), allo)
      }

      {
        const offset = byteOffset(false, i * 16 + 16) / 4
        const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

        set(this.handle, bitOffset(false, i), allo)
      }

      {
        const offset = byteOffset(true, i * 16 + 16) / 4
        const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

        set(this.handle, bitOffset(true, i), allo)
      }
    }
  }

  get byteLength () {
    if (this._byteLength !== -1) return this._byteLength
    const last = this.chunks[this.chunks.length - 1]
    return last ? last.offset + last.field.byteLength : 0
  }

  update (bit) {
    const n = this.byteLength * 8

    if (bit < 0) bit += n
    if (bit < 0 || bit >= n) return false

    const i = Math.floor(bit / 16384)
    const j = Math.floor(bit / 128)

    const offset = j * 16

    const chunk = selectChunk(this.chunks, offset)

    if (chunk === null) return false

    const m = chunk.field.BYTES_PER_ELEMENT

    const vec = chunk.field.subarray((offset - chunk.offset) / m, (offset - chunk.offset + 16) / m)

    const allz = simdle.allz(vec)
    const allo = simdle.allo(vec)

    let changed = false

    if (set(this.handle, bitOffset(false, 128 + j), allz)) {
      changed = true

      const offset = byteOffset(false, i * 16 + 16) / 4
      const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

      set(this.handle, bitOffset(false, i), allo)
    }

    if (set(this.handle, bitOffset(true, 128 + j), allo)) {
      changed = true

      const offset = byteOffset(true, i * 16 + 16) / 4
      const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

      set(this.handle, bitOffset(true, i), allo)
    }

    return changed
  }
}
const fallback = require('./fallback')

try {
  const native = require('quickbit-native')

  // These functions are faster in JavaScript
  exports.get = fallback.get
  exports.set = fallback.set
  exports.fill = fallback.fill

  // These functions are faster in C
  exports.clear = native.clear
  exports.findFirst = native.findFirst
  exports.findLast = native.findLast
  exports.Index = native.Index
} catch {
  module.exports = fallback
}
{
  "name": "quickbit-universal",
  "version": "2.2.0",
  "description": "Universal wrapper for libquickbit with a JavaScript fallback",
  "main": "index.js",
  "files": [
    "fallback.js",
    "index.js"
  ],
  "browser": {
    "./index.js": "./fallback.js"
  },
  "scripts": {
    "test": "standard && brittle test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/quickbit-universal.git"
  },
  "author": "Kasper Isager Dalsgarð <kasper@funktionel.co>",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/holepunchto/quickbit-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/quickbit-universal#readme",
  "dependencies": {
    "b4a": "^1.6.0",
    "simdle-universal": "^1.1.0"
  },
  "optionalDependencies": {
    "quickbit-native": "^2.2.0"
  },
  "devDependencies": {
    "brittle": "^3.1.0",
    "standard": "^17.0.0"
  }
}
class CacheEntry {
  constructor (key, index, map) {
    this.key = key
    this.index = index
    this.map = map
  }
}

class CacheValue {
  constructor (entry, value) {
    this.entry = entry
    this.value = value
  }
}

class Rache {
  constructor ({ maxSize = 65536, parent = null } = {}) {
    this.maxSize = parent?.maxSize || maxSize

    this._array = parent?._array || []
    this._map = new Map()
  }

  static from (cache) {
    return cache ? new this({ parent: cache }) : new this()
  }

  get globalSize () {
    return this._array.length
  }

  get size () {
    return this._map.size
  }

  sub () {
    return new Rache({ parent: this })
  }

  set (key, value) { // ~constant time
    const existing = this._map.get(key)
    if (existing !== undefined) {
      existing.value = value
      return
    }

    if (this._array.length >= this.maxSize) this._gc()

    const entry = new CacheEntry(key, this._array.length, this._map)
    this._array.push(entry)
    const cacheValue = new CacheValue(entry, value)
    this._map.set(key, cacheValue)
  }

  delete (key) {
    const existing = this._map.get(key)
    if (existing === undefined) return false

    this._delete(existing.entry.index)
    return true
  }

  get (key) {
    const existing = this._map.get(key)
    return existing === undefined ? undefined : existing.value
  }

  * [Symbol.iterator] () {
    for (const [key, { value }] of this._map) {
      yield [key, value]
    }
  }

  keys () {
    return this._map.keys()
  }

  * values () {
    for (const { value } of this._map.values()) {
      yield value
    }
  }

  clear () {
    // The entries in map linger on in _array,
    // so on top of clearing the map, we also kill the ref,
    // so that any gc running later on the old map won't interfere
    // (in case a new entry was added with the same key as a cleared entry)

    this._map.clear()
    this._map = new Map()
  }

  destroy () {
    this._map = null
    this._array = null
  }

  _gc () {
    this._delete(Math.floor(Math.random() * this._array.length))
  }

  _delete (index) { // ~constant time
    if (index >= this._array.length) throw new Error('Cannot delete unused index (logic bug?)')

    const head = this._array.pop()
    let removed = head

    if (index < this._array.length) {
      removed = this._array[index]
      head.index = index
      this._array[index] = head
    }

    removed.map.delete(removed.key)
  }
}

module.exports = Rache
{
  "name": "rache",
  "version": "1.0.0",
  "description": "Random-eviction cache",
  "main": "index.js",
  "scripts": {
    "test": "standard && brittle test.js --coverage"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/rache.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/rache/issues"
  },
  "homepage": "https://github.com/holepunchto/rache#readme",
  "files": [
    "index.js"
  ],
  "dependencies": {},
  "devDependencies": {
    "brittle": "^3.5.2",
    "standard": "^17.1.0"
  }
}
module.exports = class RandomArrayIterator {
  constructor (values) {
    this.values = values
    this.start = 0
    this.length = this.values.length
  }

  next () {
    if (this.length === 0) {
      if (this.start === 0) return { done: true, value: undefined }
      this.length = this.start
      this.start = 0
    }

    const i = this.start + ((Math.random() * this.length) | 0)
    const j = this.start + --this.length
    const value = this.values[i]

    this.values[i] = this.values[j]
    this.values[j] = value

    return { done: false, value }
  }

  dequeue () {
    this.values[this.start + this.length] = this.values[this.values.length - 1]
    this.values.pop()
  }

  requeue () {
    const i = this.start + this.length
    const value = this.values[i]
    this.values[i] = this.values[this.start]
    this.values[this.start++] = value
  }

  restart () {
    this.start = 0
    this.length = this.values.length
    return this
  }

  [Symbol.iterator] () {
    return this
  }
}
{
  "name": "random-array-iterator",
  "version": "1.0.0",
  "description": "An iterator to iterate an array in random order with controls to requeue or dequeue elements during the iteration",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^16.0.3",
    "tape": "^5.0.1"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/random-array-iterator.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/random-array-iterator/issues"
  },
  "homepage": "https://github.com/mafintosh/random-array-iterator"
}
const EventEmitter = require('events')

module.exports = class ReadyResource extends EventEmitter {
  constructor () {
    super()

    this.opening = null
    this.closing = null

    this.opened = false
    this.closed = false
  }

  ready () {
    if (this.opening !== null) return this.opening
    this.opening = open(this)
    return this.opening
  }

  close () {
    if (this.closing !== null) return this.closing
    this.closing = close(this)
    return this.closing
  }

  async _open () {
    // add impl here
  }

  async _close () {
    // add impl here
  }
}

async function open (self) {
  // open after close
  if (self.closing !== null) return

  try {
    await self._open()
  } catch (err) {
    self.close() // safe to run in bg
    throw err
  }

  self.opened = true
  self.emit('ready')
}

async function close (self) {
  try {
    if (self.opened === false && self.opening !== null) await self.opening
  } catch {
    // ignore errors on closing
  }
  if (self.opened === true || self.opening === null) await self._close()
  self.closed = true
  self.emit('close')
}
{
  "name": "ready-resource",
  "version": "1.2.0",
  "description": "Modern single resource management",
  "main": "index.js",
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "types": "index.d.ts",
  "files": [
    "index.js",
    "index.d.ts"
  ],
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "devDependencies": {
    "brittle": "^3.1.0",
    "standard": "^17.0.0"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/ready-resource.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/ready-resource/issues"
  },
  "homepage": "https://github.com/holepunchto/ready-resource",
  "dependencies": {
    "bare-events": "^2.2.0"
  }
}
module.exports = class RefCounter {
  constructor() {
    this.count = 0

    this._onidle = null
    this._idle = null
  }

  isIdle() {
    return this.count === 0
  }

  idle() {
    if (this.count === 0) return Promise.resolve()
    if (this._idle !== null) return this._idle

    this._idle = new Promise((resolve) => {
      this._onidle = resolve
    })

    return this._idle
  }

  inc() {
    this.count++
  }

  dec() {
    if (--this.count > 0) return

    if (this._onidle !== null) {
      const resolve = this._onidle
      this._idle = null
      this._onidle = null
      resolve()
    }
  }
}
{
  "name": "refcounter",
  "version": "1.0.0",
  "description": "Simple refcounter",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {},
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/refcounter.git"
  },
  "author": "Holepunch Inc",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/refcounter/issues"
  },
  "homepage": "https://github.com/holepunchto/refcounter"
}
module.exports = require.addon.bind(require)
{
  "name": "require-addon",
  "version": "1.2.0",
  "description": "Import native addons across JavaScript runtimes",
  "exports": {
    "./package": "./package.json",
    ".": {
      "bare": "./lib/bare.js",
      "node": "./lib/node.js",
      "default": "./lib/default.js"
    }
  },
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    },
    "url": {
      "bare": "bare-url",
      "default": "url"
    }
  },
  "files": [
    "lib"
  ],
  "scripts": {
    "test": "npm run lint && npm run test:bare && npm run test:node",
    "test:bare": "bare test.js",
    "test:node": "node test.js",
    "lint": "prettier --check .",
    "format": "prettier --write ."
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/require-addon.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/require-addon/issues"
  },
  "homepage": "https://github.com/holepunchto/require-addon#readme",
  "engines": {
    "bare": ">=1.10.0"
  },
  "dependencies": {
    "bare-addon-resolve": "^1.3.0"
  },
  "devDependencies": {
    "bare-bundle": "^1.8.1",
    "bare-bundle-evaluate": "^1.1.0",
    "bare-fs": "^4.0.0",
    "bare-path": "^3.0.0",
    "bare-url": "^2.1.0",
    "brittle": "^3.7.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
let tmpResolve = null
let tmpReject = null

if (Promise.withResolvers) {
  module.exports = Promise.withResolvers.bind(Promise)
} else {
  module.exports = function resolveRejectPromise () {
    const promise = new Promise(setTmp)
    const result = { promise, resolve: tmpResolve, reject: tmpReject }
    tmpResolve = tmpReject = null
    return result
  }
}

function setTmp (resolve, reject) {
  tmpResolve = resolve
  tmpReject = reject
}
{
  "name": "resolve-reject-promise",
  "version": "1.1.0",
  "description": "Create an inverted promise with no function allocs",
  "main": "index.js",
  "scripts": {
    "test": "standard"
  },
  "devDependencies": {
    "standard": "^17.1.2"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/resolve-reject-promise.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/resolve-reject-promise/issues"
  },
  "homepage": "https://github.com/mafintosh/resolve-reject-promise"
}
const resources = new Map()

exports.add = function(resource, teardown) {
  resources.set(resource, teardown)
}

exports.remove = function(resource) {
  resources.delete(resource)
}

if (global.Bare) global.Bare.on('exit', run)
else global.process.on('exit', run)

function run() {
  for (const [resource, teardown] of resources) {
    teardown(resource)
  }
}
{
  "name": "resource-on-exit",
  "version": "1.0.0",
  "description": "Register sync teardown handlers for a resource",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {},
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/bare-teardown.git"
  },
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-teardown/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-teardown"
}
require.addon = require('require-addon')

module.exports = require.addon('.', __filename)
const ColumnFamily = require('./lib/column-family')
const Iterator = require('./lib/iterator')
const Snapshot = require('./lib/snapshot')
const State = require('./lib/state')
const { BloomFilterPolicy, RibbonFilterPolicy } = require('./lib/filter-policy')
const constants = require('./lib/constants')

class RocksDB {
  constructor(path, opts = {}) {
    const {
      columnFamily,
      state = new State(this, path, opts),
      snapshot = null,
      keyEncoding = null,
      valueEncoding = null
    } = opts

    this._state = state
    this._snapshot = snapshot
    this._columnFamily = state.getColumnFamily(columnFamily)
    this._keyEncoding = keyEncoding
    this._valueEncoding = valueEncoding
    this._index = -1

    this._state.addSession(this)
  }

  get opened() {
    return this._state.opened
  }

  get closed() {
    return this.isRoot() ? this._state.closed : this._index === -1
  }

  get path() {
    return this._state.path
  }

  get stats() {
    return this._state.stats
  }

  get snapshotted() {
    return this._snapshot !== null
  }

  get defaultColumnFamily() {
    return this._columnFamily
  }

  session({
    columnFamily = this._columnFamily,
    snapshot = this._snapshot !== null,
    keyEncoding = this._keyEncoding,
    valueEncoding = this._valueEncoding
  } = {}) {
    maybeClosed(this)

    return new RocksDB(null, {
      state: this._state,
      columnFamily,
      snapshot: snapshot ? this._snapshot || new Snapshot(this._state) : null,
      keyEncoding,
      valueEncoding
    })
  }

  columnFamily(name, opts) {
    return this.session({ ...opts, columnFamily: name })
  }

  snapshot() {
    return this.session({ snapshot: true })
  }

  isRoot() {
    return this === this._state.db
  }

  ready() {
    return this._state.ready()
  }

  async close({ force } = {}) {
    if (!this._state.opened) await this._state.ready()

    if (this._index !== -1) this._state.removeSession(this)

    if (force) {
      while (this._state.sessions.length > 0) {
        await this._state.sessions[this._state.sessions.length - 1].close()
      }
    }

    return this.isRoot() ? this._state.close() : Promise.resolve()
  }

  suspend() {
    maybeClosed(this)

    return this._state.suspend()
  }

  resume() {
    maybeClosed(this)

    return this._state.resume()
  }

  isIdle() {
    return this._state.handles.isIdle()
  }

  idle() {
    return this._state.handles.idle()
  }

  iterator(range, opts) {
    maybeClosed(this)

    return new Iterator(this, { ...range, ...opts })
  }

  async *keys(range, opts) {
    for await (const { key } of this.iterator(range, {
      ...opts,
      values: false
    })) {
      yield key
    }
  }

  async peek(range, opts) {
    for await (const value of this.iterator({ ...range, ...opts, limit: 1 })) {
      return value
    }

    return null
  }

  read(opts) {
    maybeClosed(this)

    return this._state.createReadBatch(this, opts)
  }

  write(opts) {
    maybeClosed(this)

    return this._state.createWriteBatch(this, opts)
  }

  flush(opts) {
    maybeClosed(this)

    return this._state.flush(this, opts)
  }

  async get(key, opts) {
    const batch = this.read({ ...opts, capacity: 1, autoDestroy: true })
    const value = batch.get(key)
    batch.tryFlush()
    return value
  }

  async put(key, value, opts) {
    const batch = this.write({ ...opts, capacity: 1, autoDestroy: true })
    batch.tryPut(key, value)
    await batch.flush()
  }

  async delete(key, opts) {
    const batch = this.write({ ...opts, capacity: 1, autoDestroy: true })
    batch.tryDelete(key)
    await batch.flush()
  }

  async deleteRange(start, end, opts) {
    const batch = this.write({ ...opts, capacity: 1, autoDestroy: true })
    batch.tryDeleteRange(start, end)
    await batch.flush()
  }

  async compact(opts = {}) {
    maybeClosed(this)

    await this._state.compact(this, opts)
  }

  async compactRange(start = null, end = null, opts = {}) {
    if (typeof end === 'object' && end !== null) {
      opts = end
      end = null
    } else if (typeof start === 'object' && start !== null) {
      opts = start
      start = null
      end = null
    }

    await this._state.compactRange(this, start, end, opts)
  }

  async approximateSize(start, end, opts = {}) {
    return this._state.approximateSize(this, start, end, opts)
  }

  async currentWalFile() {
    maybeClosed(this)

    return this._state.currentWalFile()
  }

  async getStatsLevel() {
    maybeClosed(this)

    return this._state.getStatsLevel()
  }

  async setStatsLevel(level) {
    maybeClosed(this)

    await this._state.setStatsLevel(level)
  }

  async getProperty(name) {
    maybeClosed(this)

    return this._state.getProperty(name)
  }

  _ref() {
    if (this._snapshot) this._snapshot.ref()
    this._state.handles.inc()
  }

  _unref() {
    if (this._snapshot) this._snapshot.unref()
    this._state.handles.dec()
  }

  diagnostics() {
    return this._state.diagnostics()
  }
}

module.exports = exports = RocksDB

exports.constants = constants

exports.ColumnFamily = ColumnFamily
exports.BloomFilterPolicy = BloomFilterPolicy
exports.RibbonFilterPolicy = RibbonFilterPolicy

function maybeClosed(db) {
  if (db._state.closing || db._index === -1) throw new Error('RocksDB session is closed')
}
const c = require('compact-encoding')
const binding = require('../binding')

const empty = Buffer.alloc(0)
const resolved = Promise.resolve()

class RocksDBBatch {
  constructor(db, opts = {}) {
    const { capacity = 8, autoDestroy = false } = opts

    db._ref()

    this._db = db
    this._destroyed = false
    this._capacity = capacity
    this._operations = []
    this._promises = []

    this._enqueuePromise = this._enqueuePromise.bind(this)

    this._request = null
    this._resolve = null
    this._reject = null

    this._handle = null
    this._buffer = null
    this._autoDestroy = autoDestroy
    this._stats = null

    this._resetStats()

    if (db._state.opened === true) this.ready()
  }

  _reuse(db, opts = {}) {
    const { autoDestroy = false } = opts

    db._ref()

    this._db = db
    this._destroyed = false
    this._autoDestroy = autoDestroy
  }

  _onfinished(err) {
    const resolve = this._resolve
    const reject = this._reject

    if (this._request) this._db._state.io.dec()

    this._operations = []
    this._promises = []
    this._request = null
    this._resolve = null
    this._reject = null

    this._resetStats()

    if (this._autoDestroy === true) this.destroy()

    if (reject !== null && err) reject(err)
    else if (resolve !== null) resolve()
  }

  _resize() {
    if (this._operations.length <= this._capacity) return false

    while (this._operations.length > this._capacity) {
      this._capacity *= 2
    }

    return true
  }

  async ready() {
    if (this._handle !== null) return

    if (this._db._state.opened === false) await this._db._state.ready()

    this._init()
  }

  destroy() {
    if (this._request) throw new Error('Request in progress')
    if (this._destroyed) return

    this._destroyed = true

    if (this._promises.length) this._abort()

    this._db._unref()
    this._onfree()
  }

  _onfree() {
    this._resetStats()
    this._db._state.freeBatch(this, false)
    this._db = null
  }

  _abort() {
    for (let i = 0; i < this._promises.length; i++) {
      const promise = this._promises[i]
      if (promise !== null) promise.reject(new Error('Batch is destroyed'))
    }

    this._onfinished(new Error('Batch is destroyed'))
  }

  _resetStats() {}

  async flush() {
    if (this._request) throw new Error('Request in progress')
    if (this._destroyed) throw new Error('Batch is destroyed')

    this._request = new Promise((resolve, reject) => {
      this._resolve = resolve
      this._reject = reject
    })

    this._flush()

    return this._request
  }

  tryFlush() {
    if (this._request) throw new Error('Request in progress')
    if (this._destroyed) throw new Error('Batch is destroyed')

    this._request = resolved

    this._flush()
  }

  async _flush() {
    if (this._handle === null) await this.ready()

    this._db._state.io.inc()

    if (this._db._state.resumed !== null) {
      const resumed = await this._db._state.resumed.promise

      if (!resumed) {
        if (this._destroyed) {
          this._db._state.io.dec()
        } else {
          this._destroyed = true
          this._abort()
          this._db._unref()
        }
      }
    }
  }

  _enqueuePromise(resolve, reject) {
    this._promises.push({ resolve, reject })
  }

  _encodeKey(k) {
    if (this._db._keyEncoding) return c.encode(this._db._keyEncoding, k)
    if (typeof k === 'string') return Buffer.from(k)
    return k
  }

  _encodeValue(v) {
    if (this._db._valueEncoding) return c.encode(this._db._valueEncoding, v)
    if (v === null) return empty
    if (typeof v === 'string') return Buffer.from(v)
    return v
  }

  _decodeValue(b) {
    if (this._db._valueEncoding) return c.decode(this._db._valueEncoding, b)
    return b
  }
}

exports.ReadBatch = class RocksDBReadBatch extends RocksDBBatch {
  constructor(db, opts = {}) {
    super(db, opts)

    const { asyncIO = false, fillCache = true } = opts

    this._asyncIO = asyncIO
    this._fillCache = fillCache
  }

  _init() {
    this._handle = binding.readInit()
    this._buffer = binding.readBuffer(this._handle, this._capacity)
  }

  _resize() {
    if (super._resize() && this._handle !== null) {
      this._buffer = binding.readBuffer(this._handle, this._capacity)
    }
  }

  async _flush() {
    await super._flush()

    if (this._destroyed) return

    try {
      binding.read(
        this._db._state._handle,
        this._handle,
        this._operations,
        this._db._snapshot ? this._db._snapshot._handle : undefined,
        this._asyncIO,
        this._fillCache,
        this,
        this._onread
      )
    } catch (err) {
      this._db._state.io.dec()
      throw err
    }

    this._db._state.stats.gets += this._stats.gets
    this._db._state.stats.readBatches++
  }

  _onread(errs, values) {
    let applied = true

    for (let i = 0, n = this._promises.length; i < n; i++) {
      const err = errs[i]
      if (err) applied = false

      const promise = this._promises[i]
      if (promise === null) continue

      if (err) promise.reject(err)
      else promise.resolve(values[i] ? this._decodeValue(Buffer.from(values[i])) : null)
    }

    this._onfinished(applied ? null : new AggregateError(errs, 'Batch was not applied'))
  }

  _resetStats() {
    this._stats = { gets: 0 }
  }

  get(key) {
    if (this._request) throw new Error('Request already in progress')
    this._stats.gets++

    const promise = new Promise(this._enqueuePromise)

    this._operations.push(new RocksDBGet(this._encodeKey(key), this._db._columnFamily))

    this._resize()

    return promise
  }
}

exports.WriteBatch = class RocksDBWriteBatch extends RocksDBBatch {
  _init() {
    this._handle = binding.writeInit()
    this._buffer = binding.writeBuffer(this._handle, this._capacity)
  }

  _resize() {
    if (super._resize() && this._handle !== null) {
      this._buffer = binding.writeBuffer(this._handle, this._capacity)
    }
  }

  _onfree() {
    this._resetStats()
    this._db._state.freeBatch(this, true)
    this._db = null
  }

  async _flush() {
    await super._flush()

    if (this._destroyed) return

    try {
      binding.write(this._db._state._handle, this._handle, this._operations, this, this._onwrite)
    } catch (err) {
      this._db._state.io.dec()
      throw err
    }

    this._db._state.stats.puts += this._stats.puts
    this._db._state.stats.deletes += this._stats.deletes
    this._db._state.stats.rangeDeletes += this._stats.rangeDeletes
    this._db._state.stats.writeBatches++
  }

  _onwrite(err) {
    const applied = !err

    for (let i = 0, n = this._promises.length; i < n; i++) {
      const promise = this._promises[i]
      if (promise === null) continue

      if (err) promise.reject(err)
      else promise.resolve()
    }

    this._onfinished(applied ? null : new Error('Batch was not applied', { cause: err }))
  }

  _resetStats() {
    this._stats = { puts: 0, deletes: 0, rangeDeletes: 0 }
  }

  put(key, value) {
    if (this._request) throw new Error('Request already in progress')
    this._stats.puts++

    const promise = new Promise(this._enqueuePromise)

    this._operations.push(
      new RocksDBPut(this._encodeKey(key), this._encodeValue(value), this._db._columnFamily)
    )

    this._resize()

    return promise
  }

  tryPut(key, value) {
    if (this._request) throw new Error('Request already in progress')
    this._stats.puts++

    this._operations.push(
      new RocksDBPut(this._encodeKey(key), this._encodeValue(value), this._db._columnFamily)
    )

    this._promises.push(null)

    this._resize()
  }

  delete(key) {
    if (this._request) throw new Error('Request already in progress')
    this._stats.deletes++

    const promise = new Promise(this._enqueuePromise)

    this._operations.push(new RocksDBDelete(this._encodeKey(key), this._db._columnFamily))

    this._resize()

    return promise
  }

  tryDelete(key) {
    if (this._request) throw new Error('Request already in progress')
    this._stats.deletes++

    this._operations.push(new RocksDBDelete(this._encodeKey(key), this._db._columnFamily))

    this._promises.push(null)

    this._resize()
  }

  deleteRange(start, end) {
    if (this._request) throw new Error('Request already in progress')
    this._stats.rangeDeletes++

    const promise = new Promise(this._enqueuePromise)

    this._operations.push(
      new RocksDBDeleteRange(this._encodeKey(start), this._encodeKey(end), this._db._columnFamily)
    )

    this._resize()

    return promise
  }

  tryDeleteRange(start, end) {
    if (this._request) throw new Error('Request already in progress')
    this._stats.rangeDeletes++

    this._operations.push(
      new RocksDBDeleteRange(this._encodeKey(start), this._encodeKey(end), this._db._columnFamily)
    )

    this._promises.push(null)

    this._resize()
  }
}

class RocksDBGet {
  constructor(key, columnFamily) {
    this.key = key
    this.columnFamily = columnFamily._handle
  }

  get type() {
    return binding.GET
  }
}

class RocksDBPut {
  constructor(key, value, columnFamily) {
    this.key = key
    this.value = value
    this.columnFamily = columnFamily._handle
  }

  get type() {
    return binding.PUT
  }
}

class RocksDBDelete {
  constructor(key, columnFamily) {
    this.key = key
    this.columnFamily = columnFamily._handle
  }

  get type() {
    return binding.DELETE
  }
}

class RocksDBDeleteRange {
  constructor(start, end, columnFamily) {
    this.start = start
    this.end = end
    this.columnFamily = columnFamily._handle
  }

  get type() {
    return binding.DELETE_RANGE
  }
}
const binding = require('../binding')
const constants = require('./constants')
const { BloomFilterPolicy } = require('./filter-policy')

class RocksDBColumnFamily {
  constructor(name, opts = {}) {
    const {
      // Blob options
      enableBlobFiles = false,
      minBlobSize = 0,
      blobFileSize = 0,
      enableBlobGarbageCollection = true,
      // Block table options
      tableBlockSize = 8192,
      tableCacheIndexAndFilterBlocks = true,
      tableFormatVersion = 6,
      optimizeFiltersForMemory = false,
      blockCache = true,
      filterPolicy = new BloomFilterPolicy(10),
      topLevelIndexPinningTier = constants.pinningTier.ALL,
      partitionPinningTier = constants.pinningTier.ALL,
      unpartitionedPinningTier = constants.pinningTier.ALL,
      optimizeFiltersForHits = false,
      numLevels = 7,
      maxWriteBufferNumber = 2,
      blobGarbageCollectionAgeCutOff = 0.25,
      blobGarbageCollectionForceThreshold = 1.0
    } = opts

    this._name = name
    this._flushing = null
    this._options = {
      enableBlobFiles,
      minBlobSize,
      blobFileSize,
      enableBlobGarbageCollection,
      tableBlockSize,
      tableCacheIndexAndFilterBlocks,
      tableFormatVersion,
      optimizeFiltersForMemory,
      blockCache,
      filterPolicy,
      topLevelIndexPinningTier,
      partitionPinningTier,
      unpartitionedPinningTier,
      optimizeFiltersForHits,
      numLevels,
      maxWriteBufferNumber,
      blobGarbageCollectionAgeCutOff,
      blobGarbageCollectionForceThreshold
    }

    const filterPolicyArguments = [0, 0, 0]

    if (filterPolicy !== null) {
      filterPolicyArguments[0] = filterPolicy.type

      switch (filterPolicy.type) {
        case 1: // Bloom filter policy
          filterPolicyArguments[1] = filterPolicy.bitsPerKey
          break
        case 2: // Ribbon filter policy
          filterPolicyArguments[1] = filterPolicy.bloomEquivalentBitsPerKey
          filterPolicyArguments[2] = filterPolicy.bloomBeforeLevel

          break
      }
    }

    this._handle = binding.columnFamilyInit(
      name,
      enableBlobFiles,
      minBlobSize,
      blobFileSize,
      enableBlobGarbageCollection,
      tableBlockSize,
      tableCacheIndexAndFilterBlocks,
      tableFormatVersion,
      optimizeFiltersForMemory,
      blockCache === false,
      ...filterPolicyArguments,
      topLevelIndexPinningTier,
      partitionPinningTier,
      unpartitionedPinningTier,
      optimizeFiltersForHits,
      numLevels,
      maxWriteBufferNumber,
      blobGarbageCollectionAgeCutOff,
      blobGarbageCollectionForceThreshold
    )
  }

  cloneSettings(name) {
    return new RocksDBColumnFamily(name, this._options)
  }

  get name() {
    return this._name
  }

  destroy() {
    if (this._handle === null) return

    binding.columnFamilyDestroy(this._handle)

    this._handle = null
  }
}

module.exports = RocksDBColumnFamily
module.exports = {
  pinningTier: {
    NONE: 0,
    FLUSHED_AND_SIMILAR: 1,
    ALL: 2
  },
  garbageCollectionPolicy: {
    DEFAULT: 0,
    FORCE: 1,
    DISABLE: 2
  },
  bottommostLevelCompaction: {
    NONE: 0,
    SKIP: 1,
    FORCE: 2
  },
  walRecoveryMode: {
    TOLERATE_CORRUPTED_TAIL_RECORDS: 0,
    ABSOLUTE_CONSISTENCY: 1,
    POINT_IN_TIME: 2,
    SKIP_ANY_CORRUPTED_RECORDS: 3
  },
  statsLevel: {
    DISABLE_ALL: 0,
    EXCEPT_HISTOGRAM_OR_TIMERS: 1,
    EXCEPT_TIMERS: 2,
    EXCEPT_DETAILED_TIMERS: 3,
    EXCEPT_TIME_FOR_MUTEX: 4,
    ALL: 5
  },
  walFileType: {
    ARCHIVED: 0,
    ALIVE: 1
  }
}
exports.BloomFilterPolicy = class RocksDBBloomFilterPolicy {
  get type() {
    return 1
  }

  constructor(bitsPerKey) {
    this.bitsPerKey = bitsPerKey
  }
}

exports.RibbonFilterPolicy = class RocksDBRibbonFilterPolicy {
  get type() {
    return 2
  }

  constructor(bloomEquivalentBitsPerKey, bloomBeforeLevel = 0) {
    this.bloomEquivalentBitsPerKey = bloomEquivalentBitsPerKey
    this.bloomBeforeLevel = bloomBeforeLevel
  }
}
const { Readable } = require('streamx')
const c = require('compact-encoding')
const binding = require('../binding')

const empty = Buffer.alloc(0)

module.exports = class RocksDBIterator extends Readable {
  constructor(db, opts = {}) {
    const {
      gt = null,
      gte = null,
      lt = null,
      lte = null,
      reverse = false,
      values = true,
      limit = Infinity,
      capacity = 8
    } = opts

    super()

    db._ref()

    this._db = db

    this._gt = gt ? this._encodeKey(gt) : empty
    this._gte = gte ? this._encodeKey(gte) : empty
    this._lt = lt ? this._encodeKey(lt) : empty
    this._lte = lte ? this._encodeKey(lte) : empty

    this._reverse = reverse
    this._values = values
    this._limit = limit < 0 ? Infinity : limit
    this._capacity = capacity
    this._opened = false

    this._pendingOpen = null
    this._pendingRead = null
    this._pendingDestroy = null

    this._buffer = null
    this._handle = null

    if (this._db._state.opened === true) this.ready()
  }

  _onopen(err) {
    const cb = this._pendingOpen
    this._pendingOpen = null
    this._opened = true
    this._db._state.io.dec()
    cb(err)
  }

  _onread(err, keys, values) {
    const cb = this._pendingRead
    this._pendingRead = null
    this._db._state.io.dec()
    if (err) return cb(err)

    const n = keys.length

    this._limit -= n

    for (let i = 0; i < n; i++) {
      this.push({
        key: this._decodeKey(Buffer.from(keys[i])),
        value: this._values ? this._decodeValue(Buffer.from(values[i])) : null
      })
    }

    if (n < this._capacity) this.push(null)

    cb(null)
  }

  _onclose(err) {
    const cb = this._pendingDestroy
    this._pendingDestroy = null
    this._db._state.io.dec()
    this._db._unref()
    cb(err)
  }

  _resize() {
    if (this._handle !== null) {
      this._buffer = binding.iteratorBuffer(this._handle, this._capacity)
    }
  }

  async ready() {
    if (this._handle !== null) return

    if (this._db._state.opened === false) await this._db._state.ready()

    this._init()
  }

  _init() {
    this._handle = binding.iteratorInit()
    this._buffer = binding.iteratorBuffer(this._handle, this._capacity)
  }

  async _open(cb) {
    await this.ready()

    this._db._state.io.inc()

    if (this._db._state.resumed !== null) {
      const resumed = await this._db._state.resumed.promise

      if (!resumed) {
        this._db._state.io.dec()

        return cb(new Error('RocksDB session is closed'))
      }
    }

    this._pendingOpen = cb

    try {
      binding.iteratorOpen(
        this._db._state._handle,
        this._handle,
        this._db._columnFamily._handle,
        this._gt,
        this._gte,
        this._lt,
        this._lte,
        this._reverse,
        !this._values, // Keys only
        this._db._snapshot ? this._db._snapshot._handle : undefined,
        this,
        this._onopen,
        this._onclose,
        this._onread
      )
    } catch (err) {
      this._db._state.io.dec()

      cb(err)
    }
  }

  async _read(cb) {
    this._db._state.io.inc()

    if (this._db._state.resumed !== null) {
      const resumed = await this._db._state.resumed.promise

      if (!resumed) {
        this._db._state.io.dec()

        return cb(new Error('RocksDB session is closed'))
      }
    }

    this._pendingRead = cb

    try {
      binding.iteratorRead(this._handle, Math.min(this._capacity, this._limit))
    } catch (err) {
      this._db._state.io.dec()

      cb(err)
    }
  }

  async _destroy(cb) {
    await this.ready()

    this._db._state.io.inc()

    if (this._opened === false) {
      this._db._state.io.dec()
      this._db._unref()

      return cb(null)
    }

    this._pendingDestroy = cb

    try {
      binding.iteratorClose(this._handle)
    } catch (err) {
      this._db._state.io.dec()
      this._db._unref()

      cb(err)
    }
  }

  _encodeKey(k) {
    if (this._db._keyEncoding !== null) return c.encode(this._db._keyEncoding, k)
    if (typeof k === 'string') return Buffer.from(k)
    return k
  }

  _decodeKey(b) {
    if (this._db._keyEncoding !== null) return c.decode(this._db._keyEncoding, b)
    return b
  }

  _decodeValue(b) {
    if (this._db._valueEncoding !== null) return c.decode(this._db._valueEncoding, b)
    return b
  }
}
const binding = require('../binding')

module.exports = class RocksDBSnapshot {
  constructor(state) {
    this._state = state

    this._handle = null
    this._refs = 0

    if (state.deferSnapshotInit === false) this._init()
  }

  _init() {
    this._handle = binding.snapshotCreate(this._state._handle)
  }

  ref() {
    this._refs++
  }

  unref() {
    if (--this._refs > 0) return

    if (this._handle === null) return

    binding.snapshotDestroy(this._handle)

    this._handle = null
  }
}
const ReadyResource = require('ready-resource')
const RefCounter = require('refcounter')
const rrp = require('resolve-reject-promise')
const SignalPromise = require('signal-promise')
const c = require('compact-encoding')
const { ReadBatch, WriteBatch } = require('./batch')
const ColumnFamily = require('./column-family')
const binding = require('../binding')
const constants = require('./constants')

const MAX_BATCH_REUSE = 64
const empty = Buffer.alloc(0)

module.exports = class RocksDBState extends ReadyResource {
  constructor(db, path, opts) {
    super()

    const {
      columnFamily = new ColumnFamily('default', opts),
      columnFamilies = [],
      readOnly = false,
      createIfMissing = true,
      createMissingColumnFamilies = true,
      maxBackgroundJobs = 6,
      bytesPerSync = 1048576,
      maxOpenFiles = -1,
      useDirectReads = false,
      avoidUnnecessaryBlockingIO = false,
      skipStatsUpdateOnOpen = false,
      useDirectIOForFlushAndCompaction = false,
      maxFileOpeningThreads = 16,
      lock = null,
      walRecoveryMode = constants.walRecoveryMode.POINT_IN_TIME,
      bestEffortsRecovery = false,
      enableStatistics = false,
      statsLevel = constants.statsLevel.EXCEPT_HISTOGRAM_OR_TIMERS,
      walTtlSeconds = 0,
      walSizeLimitMegabytes = 0,
      avoidFlushDuringShutdown = false,
      walFilterPrefixes = []
    } = opts

    this.path = path
    this.db = db
    this.handles = new RefCounter()
    this.io = new RefCounter()
    this.sessions = []
    this.columnFamilies = [columnFamily]
    this.deferSnapshotInit = true
    this.resumed = null
    this.stats = {
      gets: 0,
      puts: 0,
      deletes: 0,
      rangeDeletes: 0,
      readBatches: 0,
      writeBatches: 0
    }

    this._suspended = false
    this._suspending = false
    this._updating = false
    this._updatingSignal = new SignalPromise()
    this._columnsFlushed = false
    this._lock = lock
    this._readBatches = []
    this._writeBatches = []

    for (const columnFamily of columnFamilies) {
      this.columnFamilies.push(
        typeof columnFamily === 'string' ? new ColumnFamily(columnFamily, opts) : columnFamily
      )
    }

    this._handle = binding.init(
      readOnly,
      createIfMissing,
      createMissingColumnFamilies,
      maxBackgroundJobs,
      bytesPerSync,
      maxOpenFiles,
      useDirectReads,
      avoidUnnecessaryBlockingIO,
      skipStatsUpdateOnOpen,
      useDirectIOForFlushAndCompaction,
      maxFileOpeningThreads,
      walRecoveryMode,
      bestEffortsRecovery,
      enableStatistics,
      statsLevel,
      walTtlSeconds,
      walSizeLimitMegabytes,
      avoidFlushDuringShutdown,
      walFilterPrefixes.map(encodePrefix)
    )
  }

  createReadBatch(db, opts) {
    if (this._readBatches.length === 0) return new ReadBatch(db, opts)
    const batch = this._readBatches.pop()
    batch._reuse(db, opts)
    return batch
  }

  createWriteBatch(db, opts) {
    if (this._writeBatches.length === 0) return new WriteBatch(db, opts)
    const batch = this._writeBatches.pop()
    batch._reuse(db, opts)
    return batch
  }

  freeBatch(batch, writable) {
    if (batch._capacity > 16) return
    const queue = writable ? this._writeBatches : this._readBatches
    if (queue.length >= MAX_BATCH_REUSE) return
    queue.push(batch)
  }

  addSession(db) {
    db._index = this.sessions.push(db) - 1
    if (db._snapshot) db._snapshot.ref()
  }

  removeSession(db) {
    const head = this.sessions.pop()
    if (head !== db) this.sessions[(head._index = db._index)] = head
    db._index = -1
    if (db._snapshot) db._snapshot.unref()
  }

  upsertColumnFamily(c) {
    if (typeof c === 'string') {
      let col = this.getColumnFamilyByName(c)
      if (col) return col
      col = this.columnFamilies[0].cloneSettings(c)
      this.columnFamilies.push(col)
      return col
    }

    if (this.columnFamilies.includes(c)) return c
    this.columnFamilies.push(c)
    return c
  }

  getColumnFamily(c) {
    if (!c) return this.columnFamilies[0]
    if (!this._columnsFlushed) return this.upsertColumnFamily(c)

    if (typeof c !== 'string') return c

    const col = this.getColumnFamilyByName(c)
    if (col === null) throw new Error('Unknown column family')
    return col
  }

  getColumnFamilyByName(name) {
    for (const col of this.columnFamilies) {
      if (col.name === name) return col
    }
    return null
  }

  async _open() {
    await Promise.resolve() // Allow column families to populate if on-demand

    if (this._lock) await this._lock.ready()

    const req = { resolve: null, reject: null, handle: null }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    this._columnsFlushed = true

    const lock = this._lock === null ? -1 : this._lock.transfer()

    req.handle = binding.open(
      this._handle,
      this,
      this.path,
      this.columnFamilies.map((c) => c._handle),
      lock,
      req,
      onopen
    )

    await promise

    this.deferSnapshotInit = false

    for (const session of this.sessions) {
      if (session._snapshot) session._snapshot._init()
    }

    function onopen(err) {
      if (err) req.reject(err)
      else req.resolve()
    }
  }

  async _close() {
    while (this._updating) await this._updatingSignal.wait()
    if (this.resumed) this.resumed.resolve(false)

    while (!this.io.isIdle()) await this.io.idle()
    while (!this.handles.isIdle()) await this.handles.idle()

    while (this.sessions.length > 0) {
      await this.sessions[this.sessions.length - 1].close()
    }

    for (const columnFamily of this.columnFamilies) columnFamily.destroy()

    const req = { resolve: null, reject: null, handle: null }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    req.handle = binding.close(this._handle, req, onclose)

    try {
      await promise
    } finally {
      if (this._lock) await this._lock.close()
    }

    function onclose(err) {
      if (err) req.reject(err)
      else req.resolve()
    }
  }

  async flush(db, opts) {
    if (this.opened === false) await this.ready()

    this.io.inc()

    if (this.resumed !== null) {
      const resumed = await this.resumed.promise

      if (!resumed) {
        this.io.dec()

        throw new Error('RocksDB session is closed')
      }
    }

    const req = { resolve: null, reject: null, handle: null }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    try {
      req.handle = binding.flush(this._handle, db._columnFamily._handle, req, onflush)

      await promise
    } finally {
      this.io.dec()
    }

    function onflush(err) {
      if (err) req.reject(err)
      else req.resolve()
    }
  }

  suspend() {
    this._suspending = true
    return this.update()
  }

  resume() {
    this._suspending = false
    return this.update()
  }

  async update() {
    while (this._updating) await this._updatingSignal.wait()
    if (this._suspending === this._suspended || this.closing) return
    this._updating = true
    try {
      if (this._suspending) await this._suspend()
      else await this._resume()
    } finally {
      this._updating = false
      this._updatingSignal.notify()
    }
  }

  async _suspend() {
    if (this._suspended === true) return

    while (!this.io.isIdle()) await this.io.idle()

    this.io.inc()
    this.resumed = rrp()

    const req = { resolve: null, reject: null, handle: null }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    try {
      req.handle = binding.suspend(this._handle, req, onsuspend)

      await promise

      this._suspended = true
    } finally {
      this.io.dec()
    }

    function onsuspend(err) {
      if (err) req.reject(err)
      else req.resolve()
    }
  }

  async _resume() {
    if (this._suspended === false) return

    const req = { resolve: null, reject: null, handle: null }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    req.handle = binding.resume(this._handle, req, onresume)

    await promise

    this._suspended = false

    const resumed = this.resumed
    this.resumed = null
    resumed.resolve(true)

    function onresume(err) {
      if (err) req.reject(err)
      else req.resolve()
    }
  }

  async compact(db, opts) {
    if (this.opened === false) await this.ready()

    this.io.inc()

    const {
      exclusive = false,
      blobGarbageCollectionPolicy = constants.garbageCollectionPolicy.DEFAULT,
      blobGarbageCollectionAgeCutoff = 0.25,
      bottommostLevelCompaction = constants.bottommostLevelCompaction.NONE
    } = opts

    const req = { resolve: null, reject: null, handle: null }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    try {
      req.handle = binding.compact(
        this._handle,
        db._columnFamily._handle,
        exclusive,
        blobGarbageCollectionPolicy,
        blobGarbageCollectionAgeCutoff,
        bottommostLevelCompaction,
        req,
        oncompact
      )

      await promise
    } finally {
      this.io.dec()
    }

    function oncompact(err) {
      if (err) req.reject(err)
      else req.resolve()
    }
  }

  async compactRange(db, start, end, opts) {
    if (this.opened === false) await this.ready()

    this.io.inc()

    const {
      exclusive = false,
      blobGarbageCollectionPolicy = constants.garbageCollectionPolicy.DEFAULT,
      blobGarbageCollectionAgeCutoff = 0.25,
      bottommostLevelCompaction = constants.bottommostLevelCompaction.NONE
    } = opts

    start = this._encodeKey(start)
    end = this._encodeKey(end)

    const req = { resolve: null, reject: null, handle: null, start, end }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    try {
      req.handle = binding.compactRange(
        this._handle,
        db._columnFamily._handle,
        start,
        end,
        exclusive,
        blobGarbageCollectionPolicy,
        blobGarbageCollectionAgeCutoff,
        bottommostLevelCompaction,
        req,
        oncompactrange
      )

      await promise
    } finally {
      this.io.dec()
    }

    function oncompactrange(err) {
      if (err) req.reject(err)
      else req.resolve()
    }
  }

  async approximateSize(db, start, end, opts) {
    if (this.opened === false) await this.ready()

    this.io.inc()

    const { includeMemtables = false, includeFiles = true, filesSizeErrorMargin = -1 } = opts

    start = this._encodeKey(start)
    end = this._encodeKey(end)

    const req = { resolve: null, reject: null, handle: null, start, end }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    try {
      req.handle = binding.approximateSize(
        this._handle,
        db._columnFamily._handle,
        start,
        end,
        includeMemtables,
        includeFiles,
        filesSizeErrorMargin,
        req,
        onapproximatesize
      )

      return await promise
    } finally {
      this.io.dec()
    }

    function onapproximatesize(err, result) {
      if (err) req.reject(err)
      else req.resolve(result)
    }
  }

  async currentWalFile() {
    if (this.opened === false) await this.ready()

    this.io.inc()

    const req = { resolve: null, reject: null, handle: null }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    try {
      req.handle = binding.currentWalFile(this._handle, req, oncurrentwalfile)

      return await promise
    } finally {
      this.io.dec()
    }

    function oncurrentwalfile(err, path, number, type, startSequence, size) {
      if (err) req.reject(err)
      else req.resolve({ path, number, type, startSequence, size })
    }
  }

  async getStatsLevel() {
    if (this.opened === false) await this.ready()

    return binding.statsLevelGet(this._handle)
  }

  async setStatsLevel(level) {
    if (this.opened === false) await this.ready()

    binding.statsLevelSet(this._handle, level)
  }

  async getProperty(name) {
    if (this.opened === false) await this.ready()

    return binding.propertyGet(this._handle, name)
  }

  _encodeKey(k) {
    if (this.db._keyEncoding) return c.encode(this.db._keyEncoding, k)
    if (typeof k === 'string') return Buffer.from(k)
    if (k === null) return empty
    return k
  }

  diagnostics() {
    return {
      suspended: this._suspended,
      suspending: this._suspending,
      updating: this._updating,
      resumedPending: this.resumed !== null,
      io: this.io.count,
      handles: this.handles.count,
      sessions: this.sessions.length
    }
  }
}

function encodePrefix(prefix) {
  if (typeof prefix === 'string') return Buffer.from(prefix)
  return prefix
}
{
  "name": "rocksdb-native",
  "version": "3.17.2",
  "description": "librocksdb bindings for JavaScript",
  "exports": {
    ".": "./index.js",
    "./package": "./package.json"
  },
  "imports": {
    "crypto": {
      "bare": "bare-crypto",
      "default": "crypto"
    },
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    }
  },
  "files": [
    "index.js",
    "binding.cc",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds",
    "!prebuilds/android-*/**/*.node"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:bare && npm run test:node",
    "test:bare": "brittle-bare --coverage test.js",
    "test:node": "brittle-node --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/rocksdb-native.git"
  },
  "author": "Holepunch Inc",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/rocksdb-native/issues"
  },
  "homepage": "https://github.com/holepunchto/rocksdb-native",
  "engines": {
    "bare": ">=1.16.0"
  },
  "dependencies": {
    "compact-encoding": "^3.0.0",
    "ready-resource": "^1.0.0",
    "refcounter": "^1.0.0",
    "require-addon": "^1.0.2",
    "resolve-reject-promise": "^1.1.0",
    "signal-promise": "^1.0.3",
    "streamx": "^2.16.1"
  },
  "devDependencies": {
    "bare-compat-napi": "^1.3.0",
    "bare-crypto": "^1.12.0",
    "bare-fs": "^4.5.0",
    "bare-path": "^3.0.0",
    "brittle": "^3.5.0",
    "cmake-bare": "^1.1.14",
    "cmake-fetch": "^1.0.1",
    "cmake-napi": "^1.0.6",
    "fd-lock": "^2.0.0",
    "lunte": "^1.8.0",
    "paparam": "^1.9.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = safetyCatch

function isActuallyUncaught (err) {
  if (!err) return false
  return err instanceof TypeError ||
    err instanceof SyntaxError ||
    err instanceof ReferenceError ||
    err instanceof EvalError ||
    err instanceof RangeError ||
    err instanceof URIError ||
    err.code === 'ERR_ASSERTION' ||
    err.name === 'AssertionError'
}

function throwErrorNT (err) {
  queueMicrotask(() => { throw err })
}

function safetyCatch (err) {
  if (isActuallyUncaught(err)) {
    throwErrorNT(err)
    throw err
  }
}
{
  "name": "safety-catch",
  "version": "1.0.3",
  "description": "Small module that makes sure your catch, caught an actual error and not a programming mistake or assertion",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {},
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/safety-catch.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/safety-catch/issues"
  },
  "homepage": "https://github.com/mafintosh/safety-catch"
}
let tmpResolve = null

module.exports = class ScopeLock {
  constructor ({ debounce = false } = {}) {
    this.debounce = debounce
    this.waiting = []
    this.locked = false
    this.skip = 0
    this.destroyed = false
  }

  flush () {
    if (this.locked === false && this.waiting.length === 0) return Promise.resolve(this.destroyed === false)

    const promise = new Promise(setTmpResolve)
    const resolve = tmpResolve

    tmpResolve = null
    this.waiting.push({ lock: false, resolve })

    return promise
  }

  destroy () {
    this.destroyed = true
  }

  lock () {
    const promise = new Promise(setTmpResolve)
    const resolve = tmpResolve

    tmpResolve = null

    if (this.locked === true) {
      this.waiting.push({ lock: true, resolve })
      return promise
    }

    if (this.destroyed === true) {
      resolve(false)
      return promise
    }

    this.locked = true
    resolve(true)

    return promise
  }

  unlock () {
    if (this.destroyed === true) {
      for (let i = 0; i < this.waiting.length; i++) {
        this.waiting[i].resolve(false)
      }
      this.waiting = []
      this.skip = 0
      this.locked = false
      return
    }

    if (this.skip !== 0) {
      for (let i = 0; i < this.skip; i++) {
        const { lock, resolve } = this.waiting[i]
        resolve(lock === false)
      }

      this.waiting = this.waiting.slice(this.skip)
      this.skip = 0
    }

    while (this.waiting.length > 0 && this.waiting[0].lock === false) {
      this.waiting.shift().resolve(true)
    }

    if (this.waiting.length === 0) {
      this.locked = false
      return
    }

    const { resolve } = this.waiting.shift()
    if (this.debounce === true) this.skip = this.waiting.length

    resolve(true)
  }
}

function setTmpResolve (resolve) {
  tmpResolve = resolve
}
{
  "name": "scope-lock",
  "version": "1.2.4",
  "description": "Some concurrency semantics around entering scopes",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "devDependencies": {
    "brittle": "^3.7.0",
    "standard": "^17.1.2"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/scope-lock.git"
  },
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/scope-lock/issues"
  },
  "homepage": "https://github.com/holepunchto/scope-lock"
}
module.exports = class Signal {
  constructor () {
    this._resolve = null
    this._reject = null
    this._promise = null
    this._bind = bind.bind(this)
    this._onerror = clear.bind(this)
    this._onsuccess = clear.bind(this, null)
    this._timers = new Set()
  }

  wait (max) {
    if (!this._promise) {
      this._promise = new Promise(this._bind)
      this._promise.then(this._onsuccess).catch(this._onerror)
    }
    if (max) return this._sleep(max)
    return this._promise
  }

  _sleep (max) {
    const s = new Promise((resolve, reject) => {
      const done = () => {
        this._timers.delete(state)
        resolve(true)
      }
      const id = setTimeout(done, max)
      const state = { id, resolve, reject }
      this._timers.add(state)
    })

    return s
  }

  notify (err) {
    if (!this._promise) return
    const resolve = this._resolve
    const reject = this._reject
    this._promise = null
    if (err) reject(err)
    else resolve(true)
  }
}

function clear (err) {
  for (const { id, resolve, reject } of this._timers) {
    clearTimeout(id)
    if (err) reject(err)
    else resolve(true)
  }
  this._timers.clear()
}

function bind (resolve, reject) {
  this._resolve = resolve
  this._reject = reject
}
{
  "name": "signal-promise",
  "version": "1.0.3",
  "description": "Simple wait/notify promise with optional max wait time",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {},
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/signal-promise.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/signal-promise/issues"
  },
  "homepage": "https://github.com/mafintosh/signal-promise"
}
var varint = require('varint')
exports.encode = function encode (v, b, o) {
  v = v >= 0 ? v*2 : v*-2 - 1
  var r = varint.encode(v, b, o)
  encode.bytes = varint.encode.bytes
  return r
}
exports.decode = function decode (b, o) {
  var v = varint.decode(b, o)
  decode.bytes = varint.decode.bytes
  return v & 1 ? (v+1) / -2 : v / 2
}

exports.encodingLength = function (v) {
  return varint.encodingLength(v >= 0 ? v*2 : v*-2 - 1)
}
{
  "name": "signed-varint",
  "description": "efficiently store signed integers in varint",
  "version": "2.0.1",
  "homepage": "https://github.com/dominictarr/signed-varint",
  "repository": {
    "type": "git",
    "url": "git://github.com/dominictarr/signed-varint.git"
  },
  "dependencies": {
    "varint": "~5.0.0"
  },
  "devDependencies": {
    "tape": "~2.12.3"
  },
  "scripts": {
    "test": "node test.js"
  },
  "author": "Dominic Tarr <dominic.tarr@gmail.com> (http://dominictarr.com)",
  "license": "MIT"
}
require.addon = require('require-addon')

module.exports = require.addon('.', __filename)
const binding = require('./binding')
const b4a = require('b4a')

function predicate(u8, u16, u32) {
  return function predicate(buf) {
    if (buf.byteLength % 16 !== 0) {
      throw new Error('Buffer length must be a multiple of 16')
    }

    const n = buf.BYTES_PER_ELEMENT

    if (n === 1) return u8(buf)
    if (n === 2) return u16(buf)
    return u32(buf)
  }
}

function unary(u8, u16, u32) {
  return function unary(buf, result = b4a.allocUnsafe(buf.byteLength)) {
    if (buf.byteLength % 16 !== 0) {
      throw new Error('Buffer length must be a multiple of 16')
    }

    if (buf.byteLength !== result.byteLength) {
      throw new Error('Length of result buffer is insufficient')
    }

    const n = buf.BYTES_PER_ELEMENT

    if (n === 1) u8(buf, result)
    else if (n === 2) u16(buf, result)
    else u32(buf, result)

    return result
  }
}

function binary(u8, u16, u32) {
  return function binary(a, b, result = b4a.allocUnsafe(a.byteLength)) {
    if (a.byteLength % 16 !== 0) {
      throw new Error('Buffer length must be a multiple of 16')
    }

    if (a.byteLength !== b.byteLength || a.byteLength !== result.byteLength) {
      throw new Error('Buffers must be the same length')
    }

    const n = a.BYTES_PER_ELEMENT

    if (n === 1) u8(a, b, result)
    else if (n === 2) u16(a, b, result)
    else u32(a, b, result)

    return result
  }
}

function reduce(u8, u16, u32) {
  return function reduce(buf) {
    if (buf.byteLength % 16 !== 0) {
      throw new Error('Buffer length must be a multiple of 16')
    }

    const n = buf.BYTES_PER_ELEMENT

    if (n === 1) return u8(buf)
    if (n === 2) return u16(buf)
    return u32(buf)
  }
}

exports.allo = predicate(
  binding.simdle_native_allo_v128_u8,
  binding.simdle_native_allo_v128_u16,
  binding.simdle_native_allo_v128_u32
)

exports.allz = predicate(
  binding.simdle_native_allz_v128_u8,
  binding.simdle_native_allz_v128_u16,
  binding.simdle_native_allz_v128_u32
)

exports.and = binary(
  binding.simdle_native_and_v128_u8,
  binding.simdle_native_and_v128_u16,
  binding.simdle_native_and_v128_u32
)

exports.clear = binary(
  binding.simdle_native_clear_v128_u8,
  binding.simdle_native_clear_v128_u16,
  binding.simdle_native_clear_v128_u32
)

exports.clo = unary(
  binding.simdle_native_clo_v128_u8,
  binding.simdle_native_clo_v128_u16,
  binding.simdle_native_clo_v128_u32
)

exports.clz = unary(
  binding.simdle_native_clz_v128_u8,
  binding.simdle_native_clz_v128_u16,
  binding.simdle_native_clz_v128_u32
)

exports.cnt = unary(
  binding.simdle_native_cnt_v128_u8,
  binding.simdle_native_cnt_v128_u16,
  binding.simdle_native_cnt_v128_u32
)

exports.cto = unary(
  binding.simdle_native_cto_v128_u8,
  binding.simdle_native_cto_v128_u16,
  binding.simdle_native_cto_v128_u32
)

exports.ctz = unary(
  binding.simdle_native_ctz_v128_u8,
  binding.simdle_native_ctz_v128_u16,
  binding.simdle_native_ctz_v128_u32
)

exports.not = unary(
  binding.simdle_native_not_v128_u8,
  binding.simdle_native_not_v128_u16,
  binding.simdle_native_not_v128_u32
)

exports.or = binary(
  binding.simdle_native_or_v128_u8,
  binding.simdle_native_or_v128_u16,
  binding.simdle_native_or_v128_u32
)

exports.sum = reduce(
  binding.simdle_native_sum_v128_u8,
  binding.simdle_native_sum_v128_u16,
  binding.simdle_native_sum_v128_u32
)

exports.xor = binary(
  binding.simdle_native_xor_v128_u8,
  binding.simdle_native_xor_v128_u16,
  binding.simdle_native_xor_v128_u32
)
{
  "name": "simdle-native",
  "version": "1.3.9",
  "description": "libsimdle JavaScript bindings for Node.js",
  "main": "index.js",
  "files": [
    "index.js",
    "binding.cc",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check .",
    "test": "npm run lint && npm run test:bare && npm run test:node",
    "test:bare": "bare test.mjs",
    "test:node": "node test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/simdle-native.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/simdle-native/issues"
  },
  "homepage": "https://github.com/holepunchto/simdle-native#readme",
  "dependencies": {
    "b4a": "^1.6.0",
    "require-addon": "^1.1.0"
  },
  "devDependencies": {
    "bare-compat-napi": "^1.3.2",
    "brittle": "^3.1.0",
    "cmake-bare": "^1.1.7",
    "cmake-fetch": "^1.1.0",
    "cmake-napi": "^1.0.2",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  }
}
const b4a = require('b4a')
const scalar = require('./scalar')

function view (buf, n) {
  if (n === buf.BYTES_PER_ELEMENT) return buf

  let TypedArray

  if (n === 1) TypedArray = Uint8Array
  else if (n === 2) TypedArray = Uint16Array
  else TypedArray = Uint32Array

  return new TypedArray(buf.buffer, buf.byteOffset, buf.byteLength / n)
}

function unary (u8, u16 = u8, u32 = u16) {
  return function unary (buf, result = b4a.allocUnsafe(buf.byteLength)) {
    if (buf.byteLength % 16 !== 0) {
      throw new Error('Buffer length must be a multiple of 16')
    }

    if (buf.byteLength !== result.byteLength) {
      throw new Error('Length of result buffer is insufficient')
    }

    const n = buf.BYTES_PER_ELEMENT

    if (n === 1) u8(buf, view(result, n))
    else if (n === 2) u16(buf, view(result, n))
    else u32(buf, view(result, n))

    return result
  }
}

function binary (u8, u16 = u8, u32 = u16) {
  return function binary (a, b, result = b4a.allocUnsafe(a.byteLength)) {
    if (a.byteLength % 16 !== 0) {
      throw new Error('Buffer length must be a multiple of 16')
    }

    if (a.byteLength !== b.byteLength || a.byteLength !== result.byteLength) {
      throw new Error('Buffers must be the same length')
    }

    const n = a.BYTES_PER_ELEMENT

    if (n === 1) u8(a, b, view(result, n))
    else if (n === 2) u16(a, b, view(result, n))
    else u32(a, b, view(result, n))

    return result
  }
}

function reduce (u8, u16 = u8, u32 = u16) {
  return function reduce (buf) {
    if (buf.byteLength % 16 !== 0) {
      throw new Error('Buffer length must be a multiple of 16')
    }

    const n = buf.BYTES_PER_ELEMENT

    if (n === 1) return u8(buf)
    if (n === 2) return u16(buf)
    return u32(buf)
  }
}

exports.allo = function allo (buf) {
  if (buf.byteLength % 16 !== 0) {
    throw new Error('Buffer length must be a multiple of 16')
  }

  const m = 2 ** (buf.BYTES_PER_ELEMENT * 8) - 1

  for (let i = 0, n = buf.length; i < n; i++) {
    if (buf[i] !== m) return false
  }

  return true
}

exports.allz = function allz (buf) {
  if (buf.byteLength % 16 !== 0) {
    throw new Error('Buffer length must be a multiple of 16')
  }

  for (let i = 0, n = buf.length; i < n; i++) {
    if (buf[i] !== 0) return false
  }

  return true
}

exports.and = binary(
  (a, b, result) => {
    for (let i = 0, n = result.length; i < n; i++) {
      result[i] = a[i] & b[i]
    }
  }
)

exports.clear = binary(
  (a, b, result) => {
    for (let i = 0, n = result.length; i < n; i++) {
      result[i] = a[i] & ~b[i]
    }
  }
)

exports.clo = unary(
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = 24 - scalar.clo(buf[i])
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = 16 - scalar.clo(buf[i])
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = scalar.clo(buf[i])
    }
  }
)

exports.clz = unary(
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = 24 - scalar.clz(buf[i])
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = 16 - scalar.clz(buf[i])
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = scalar.clz(buf[i])
    }
  }
)

exports.cnt = unary(
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = scalar.cnt(buf[i]) & 0xff
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = scalar.cnt(buf[i]) & 0xffff
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = scalar.cnt(buf[i])
    }
  }
)

exports.cto = unary(
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = Math.min(scalar.cto(buf[i]), 8)
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = Math.min(scalar.cto(buf[i]), 16)
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = scalar.cto(buf[i])
    }
  }
)

exports.ctz = unary(
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = Math.min(scalar.ctz(buf[i]), 8)
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = Math.min(scalar.ctz(buf[i]), 16)
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = scalar.ctz(buf[i])
    }
  }
)

exports.not = unary(
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = ~buf[i]
    }
  }
)

exports.or = binary(
  (a, b, result) => {
    for (let i = 0, n = result.length; i < n; i++) {
      result[i] = a[i] | b[i]
    }
  }
)

exports.sum = reduce(
  (buf) => {
    let result = 0n

    for (let i = 0, n = buf.length; i < n; i++) {
      result += BigInt(buf[i])
    }

    return result
  }
)

exports.xor = binary(
  (a, b, result) => {
    for (let i = 0, n = result.length; i < n; i++) {
      result[i] = a[i] ^ b[i]
    }
  }
)
try {
  module.exports = require('simdle-native')
} catch {
  module.exports = require('./fallback')
}
{
  "name": "simdle-universal",
  "version": "1.1.2",
  "description": "Universal wrapper for libsimdle with a JavaScript fallback",
  "main": "index.js",
  "files": [
    "fallback.js",
    "index.js",
    "scalar.js"
  ],
  "browser": {
    "./index.js": "./fallback.js"
  },
  "scripts": {
    "test": "standard && brittle test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/simdle-universal.git"
  },
  "author": "Kasper Isager Dalsgarð <kasper@funktionel.co>",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/holepunchto/simdle-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/simdle-universal#readme",
  "dependencies": {
    "b4a": "^1.6.0"
  },
  "optionalDependencies": {
    "simdle-native": "^1.1.1"
  },
  "devDependencies": {
    "brittle": "^3.1.0",
    "standard": "^17.0.0"
  }
}
const clz = exports.clz = function clz (n) {
  return Math.clz32(n)
}

exports.clo = function clo (n) {
  return clz(~n)
}

const ctz = exports.ctz = function ctz (n) {
  return 32 - (n === 0 ? 0 : (clz(n & -n) + 1))
}

exports.cto = function cto (n) {
  return ctz(~n)
}

exports.cnt = function cnt (n) {
  n = n - ((n >>> 1) & 0x55555555)
  n = (n & 0x33333333) + ((n >>> 2) & 0x33333333)
  n = (n + (n >>> 4)) & 0x0f0f0f0f
  n = (n * 0x01010101) >>> 24
  return n
}
require.addon = require('require-addon')
module.exports = require.addon('.', __filename)
const assert = require('assert')
const binding = require('./binding')
const { isNode } = require('which-runtime')

const OPTIONAL = Buffer.from(new ArrayBuffer(0))

module.exports = exports = { ...binding }

// memory

exports.sodium_memzero = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  binding.sodium_memzero(buf)
}

exports.sodium_mlock = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  const res = binding.sodium_mlock(buf)

  if (res !== 0) throw new Error('memory lock failed')
}

exports.sodium_munlock = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  const res = binding.sodium_munlock(buf)

  if (res !== 0) throw new Error('memory unlock failed')
}

exports.sodium_malloc = function (size) {
  assert(size >= 0, 'invalid size')

  const buf = Buffer.from(binding.sodium_malloc(size))
  buf.secure = true
  return buf
}

exports.sodium_free = function (buf) {
  if (!buf || !buf.secure) return

  binding.sodium_free(buf.buffer)
}

exports.sodium_mprotect_noaccess = function (buf) {
  const res = binding.sodium_mprotect_noaccess(buf.buffer)

  if (res !== 0) throw new Error('failed to lock buffer')
}

exports.sodium_mprotect_readonly = function (buf) {
  const res = binding.sodium_mprotect_readonly(buf.buffer)

  if (res !== 0) throw new Error('failed to unlock buffer')
}

exports.sodium_mprotect_readwrite = function (buf) {
  const res = binding.sodium_mprotect_readwrite(buf.buffer)

  if (res !== 0) throw new Error('failed to unlock buffer')
}

// crypto_randombytes

exports.randombytes_buf = function (buffer) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')

  binding.randombytes_buf(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

exports.randombytes_buf_deterministic = function (buffer, seed) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    seed.byteLength === binding.randombytes_SEEDBYTES,
    "seed must be 'randombytes_SEEDBYTES' bytes"
  )

  binding.randombytes_buf_deterministic(
    buffer.buffer,
    buffer.byteOffset,
    buffer.byteLength,

    seed.buffer,
    seed.byteOffset,
    seed.byteLength
  )
}

// sodium_helpers

exports.sodium_memcmp = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  return binding.sodium_memcmp(a, b)
}

exports.sodium_add = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  binding.sodium_add(a, b)
}

exports.sodium_sub = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  binding.sodium_sub(a, b)
}

exports.sodium_compare = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  return binding.sodium_compare(a, b)
}

exports.sodium_is_zero = function (buffer, length) {
  if (length === undefined) length = buffer.byteLength

  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(length >= 0 && length <= buffer.byteLength, 'invalid length')

  return binding.sodium_is_zero(buffer, length)
}

exports.sodium_pad = function (buffer, unpaddedBuflen, blockSize) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(unpaddedBuflen <= buffer.byteLength, 'unpadded length cannot exceed buffer length')
  assert(blockSize <= buffer.byteLength, 'block size cannot exceed buffer length')
  assert(blockSize >= 1, 'block size must be at least 1 byte')
  assert(
    buffer.byteLength >= unpaddedBuflen + (blockSize - (unpaddedBuflen % blockSize)),
    'buf not long enough'
  )

  return binding.sodium_pad(buffer, unpaddedBuflen, blockSize)
}

exports.sodium_unpad = function (buffer, paddedBuflen, blockSize) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(paddedBuflen <= buffer.byteLength, 'unpadded length cannot exceed buffer length')
  assert(blockSize <= buffer.byteLength, 'block size cannot exceed buffer length')
  assert(blockSize >= 1, 'block size must be at least 1 byte')

  return binding.sodium_unpad(buffer, paddedBuflen, blockSize)
}

// crypto_sign

exports.crypto_sign_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )
  assert(
    seed.byteLength === binding.crypto_sign_SEEDBYTES,
    "seed must be 'crypto_sign_SEEDBYTES' bytes"
  )

  const res = binding.crypto_sign_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign = function (sm, m, sk) {
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sm.byteLength === binding.crypto_sign_BYTES + m.byteLength,
    "sm must be 'm.byteLength + crypto_sign_BYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign(sm, m, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_open = function (m, sm, pk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sm.byteLength >= binding.crypto_sign_BYTES,
    "sm must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    m.byteLength === sm.byteLength - binding.crypto_sign_BYTES,
    "m must be 'sm.byteLength - crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_open(m, sm, pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_open = function (m, sm, pk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sm.byteLength >= binding.crypto_sign_BYTES,
    "sm must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    m.byteLength === sm.byteLength - binding.crypto_sign_BYTES,
    "m must be 'sm.byteLength - crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  return binding.crypto_sign_open(m, sm, pk)
}

exports.crypto_sign_detached = function (sig, m, sk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(sig.byteLength === binding.crypto_sign_BYTES, "sig must be 'crypto_sign_BYTES' bytes")
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_detached(sig, m, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_verify_detached = function (sig, m, pk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sig.byteLength >= binding.crypto_sign_BYTES,
    "sig must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  return binding.crypto_sign_verify_detached(
    sig.buffer,
    sig.byteOffset,
    sig.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    pk.buffer,
    pk.byteOffset,
    pk.byteLength
  )
}

exports.crypto_sign_ed25519_sk_to_pk = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_sk_to_pk(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_ed25519_pk_to_curve25519 = function (x25519pk, ed25519pk) {
  assert(ArrayBuffer.isView(x25519pk), 'x25519pk must be a typed array')
  assert(ArrayBuffer.isView(ed25519pk), 'ed25519pk must be a typed array')
  assert(
    x25519pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "x25519pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    ed25519pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "ed25519pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_pk_to_curve25519(x25519pk, ed25519pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_ed25519_sk_to_curve25519 = function (x25519sk, ed25519sk) {
  assert(ArrayBuffer.isView(x25519sk), 'x25519sk must be a typed array')
  assert(ArrayBuffer.isView(ed25519sk), 'ed25519sk must be a typed array')
  assert(
    x25519sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "x25519sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const edLen = ed25519sk.byteLength

  assert(
    edLen === binding.crypto_sign_SECRETKEYBYTES || edLen === binding.crypto_box_SECRETKEYBYTES,
    "ed25519sk must be 'crypto_sign_SECRETKEYBYTES' or 'crypto_sign_SECRETKEYBYTES - crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_sk_to_curve25519(x25519sk, ed25519sk)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_box

exports.crypto_box_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    seed.byteLength === binding.crypto_box_SEEDBYTES,
    "seed must be 'crypto_box_SEEDBYTES' bytes"
  )

  const res = binding.crypto_box_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_easy = function (c, m, n, pk, sk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength === m.byteLength + exports.crypto_box_MACBYTES,
    "c must be 'm.byteLength + crypto_box_MACBYTES' bytes"
  )
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_easy(c, m, n, pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_detached = function (c, mac, m, n, pk, sk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(mac.byteLength === exports.crypto_box_MACBYTES, "mac must be 'crypto_box_MACBYTES' bytes")
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_detached(c, mac, m, n, pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_open_easy = function (m, c, n, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength >= exports.crypto_box_MACBYTES,
    "c must be at least 'crypto_box_MACBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - exports.crypto_box_MACBYTES,
    "m must be 'c.byteLength - crypto_box_MACBYTES' bytes"
  )
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_open_easy(m, c, n, pk, sk)
}

exports.crypto_box_open_detached = function (m, c, mac, n, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(mac.byteLength === exports.crypto_box_MACBYTES, "mac must be 'crypto_box_MACBYTES' bytes")
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_open_detached(m, c, mac, n, pk, sk)
}

exports.crypto_box_seal = function (c, m, pk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    c.byteLength === m.byteLength + exports.crypto_box_SEALBYTES,
    "c must be 'm.byteLength + crypto_box_SEALBYTES' bytes"
  )
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_box_seal(c, m, pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_seal_open = function (m, c, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength >= exports.crypto_box_SEALBYTES,
    "c must be at least 'crypto_box_SEALBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - exports.crypto_box_SEALBYTES,
    "m must be 'c.byteLength - crypto_box_SEALBYTES' bytes"
  )
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_seal_open(
    m.buffer,
    m.byteOffset,
    m.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    pk.buffer,
    pk.byteOffset,
    pk.byteLength,

    sk.buffer,
    sk.byteOffset,
    sk.byteLength
  )
}

// crypto_secretbox

exports.crypto_secretbox_easy = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_secretbox_MACBYTES,
    "c must be 'm.byteLength + crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretbox_easy(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretbox_open_easy = function (m, c, n, k) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    c.byteLength >= binding.crypto_secretbox_MACBYTES,
    "c must be at least 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - binding.crypto_secretbox_MACBYTES,
    "m must be 'c.byteLength - crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  return binding.crypto_secretbox_open_easy(m, c, n, k)
}

exports.crypto_secretbox_detached = function (c, mac, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    mac.byteLength === binding.crypto_secretbox_MACBYTES,
    "mac must be 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretbox_detached(c, mac, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretbox_open_detached = function (m, c, mac, n, k) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(
    mac.byteLength === binding.crypto_secretbox_MACBYTES,
    "mac must be 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  return binding.crypto_secretbox_open_detached(m, c, mac, n, k)
}

// crypto_generichash

exports.crypto_generichash = function (output, input, key) {
  if (!key) key = OPTIONAL

  assert(ArrayBuffer.isView(output), 'output must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    output.byteLength >= binding.crypto_generichash_BYTES_MIN &&
      output.byteLength <= binding.crypto_generichash_BYTES_MAX,
    'output must be between crypto_generichash_BYTES_MIN and crypto_generichash_BYTES_MAX bytes'
  )

  if (key !== OPTIONAL) {
    assert(ArrayBuffer.isView(key), 'key must be a typed array')
    assert(
      key.byteLength >= binding.crypto_generichash_KEYBYTES_MIN &&
        key.byteLength <= binding.crypto_generichash_KEYBYTES_MAX,
      'key must be between crypto_generichash_KEYBYTES_MIN and crypto_generichash_KEYBYTES_MAX bytes'
    )
  }

  const res = binding.crypto_generichash(
    output.buffer,
    output.byteOffset,
    output.byteLength,

    input.buffer,
    input.byteOffset,
    input.byteLength,

    key.buffer,
    key.byteOffset,
    key.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_batch = function (output, batch, key) {
  assert(ArrayBuffer.isView(output), 'output must be a typed array')

  if (isNode || batch.length < 4) {
    const res = binding.crypto_generichash_batch(output, batch, !!key, key || OPTIONAL)
    if (res !== 0) throw new Error('status: ' + res)
  } else {
    const state = Buffer.alloc(binding.crypto_generichash_STATEBYTES)

    exports.crypto_generichash_init(state, key, output.byteLength)

    for (const buf of batch) {
      exports.crypto_generichash_update(state, buf)
    }

    exports.crypto_generichash_final(state, output)
  }
}

exports.crypto_generichash_keygen = function (key) {
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(
    key.byteLength === binding.crypto_generichash_KEYBYTES,
    "key must be 'crypto_generichash_KEYBYTES' bytes"
  )

  const res = binding.crypto_generichash_keygen(key.buffer, key.byteOffset, key.byteLength)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_init = function (state, key, outputLength) {
  if (!key) key = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_init(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    key.buffer,
    key.byteOffset,
    key.byteLength,

    outputLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_update(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    input.buffer,
    input.byteOffset,
    input.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_final = function (state, output) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(output), 'output must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_final(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    output.buffer,
    output.byteOffset,
    output.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

// secretstream

exports.crypto_secretstream_xchacha20poly1305_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  binding.crypto_secretstream_xchacha20poly1305_keygen(k.buffer, k.byteOffset, k.byteLength)
}

exports.crypto_secretstream_xchacha20poly1305_init_push = function (state, header, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(header), 'header must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    header.byteLength === binding.crypto_secretstream_xchacha20poly1305_HEADERBYTES,
    "header must be 'crypto_secretstream_xchacha20poly1305_HEADERBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_init_push(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    header.buffer,
    header.byteOffset,
    header.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretstream_xchacha20poly1305_init_pull = function (state, header, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(header), 'header must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    header.byteLength === binding.crypto_secretstream_xchacha20poly1305_HEADERBYTES,
    "header must be 'crypto_secretstream_xchacha20poly1305_HEADERBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_init_pull(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    header.buffer,
    header.byteOffset,
    header.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretstream_xchacha20poly1305_push = function (state, c, m, ad, tag) {
  if (!ad) ad = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    c.byteLength === m.byteLength + binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "c must be 'm.byteLength + crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_push(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    ad.buffer,
    ad.byteOffset,
    ad.byteLength,

    tag
  )

  if (res < 0) throw new Error('push failed')

  return res
}

exports.crypto_secretstream_xchacha20poly1305_pull = function (state, m, tag, c, ad) {
  if (!ad) ad = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(tag), 'tag must be a typed array')
  assert(tag.byteLength === 1, 'tag must be 1 byte')

  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    c.byteLength >= binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "c must be at least 'crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "m must be 'c.byteLength - crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_pull(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    tag.buffer,
    tag.byteOffset,
    tag.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    ad.buffer,
    ad.byteOffset,
    ad.byteLength
  )

  if (res < 0) throw new Error('pull failed')

  return res
}

exports.crypto_secretstream_xchacha20poly1305_rekey = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )

  binding.crypto_secretstream_xchacha20poly1305_rekey(
    state.buffer,
    state.byteOffset,
    state.byteLength
  )
}

// crypto_stream

exports.crypto_stream = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xor(
    c.buffer,
    c.byteOffset,
    c.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    n.buffer,
    n.byteOffset,
    n.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_auth

exports.crypto_auth = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(out.byteLength === binding.crypto_auth_BYTES, "out must be 'crypto_auth_BYTES' bytes")
  assert(k.byteLength === binding.crypto_auth_KEYBYTES, "k must be 'crypto_auth_KEYBYTES' bytes")

  const res = binding.crypto_auth(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_auth_verify = function (h, input, k) {
  assert(ArrayBuffer.isView(h), 'h must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(h.byteLength === binding.crypto_auth_BYTES, "h must be 'crypto_auth_BYTES' bytes")
  assert(k.byteLength === binding.crypto_auth_KEYBYTES, "k must be 'crypto_auth_KEYBYTES' bytes")

  return binding.crypto_auth_verify(h, input, k)
}

// crypto_onetimeauth

exports.crypto_onetimeauth = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    out.byteLength === binding.crypto_onetimeauth_BYTES,
    "out must be 'crypto_onetimeauth_BYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_init = function (state, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_init(state, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )
  assert(
    out.byteLength === binding.crypto_onetimeauth_BYTES,
    "out must be 'crypto_onetimeauth_BYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_verify = function (h, input, k) {
  assert(ArrayBuffer.isView(h), 'h must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    h.byteLength === binding.crypto_onetimeauth_BYTES,
    "h must be 'crypto_onetimeauth_BYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  return binding.crypto_onetimeauth_verify(h, input, k)
}

// crypto_pwhash

exports.crypto_pwhash = function (out, passwd, salt, opslimit, memlimit, alg) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_BYTES_MIN,
    "out must be at least 'crypto_pwhash_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_BYTES_MAX,
    "out must be at most 'crypto_pwhash_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_SALTBYTES,
    "salt must be 'crypto_pwhash_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )
  assert(alg >= 1 && alg <= 2, 'alg must be either Argon2i 1.3 or Argon2id 1.3')

  const res = binding.crypto_pwhash(out, passwd, salt, opslimit, memlimit, alg)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_async = function (
  out,
  passwd,
  salt,
  opslimit,
  memlimit,
  alg,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_BYTES_MIN,
    "out must be at least 'crypto_pwhash_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_BYTES_MAX,
    "out must be at most 'crypto_pwhash_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_SALTBYTES,
    "salt must be 'crypto_pwhash_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )
  assert(alg >= 1 && alg <= 2, 'alg must be either Argon2i 1.3 or Argon2id 1.3')

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    opslimit,
    memlimit,
    alg,

    done
  )

  return promise
}

exports.crypto_pwhash_str = function (out, passwd, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_STRBYTES,
    "out must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(typeof opslimit === 'number', 'opslimit must be a number')
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(typeof memlimit === 'number', 'memlimit must be a number')
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_str(out, passwd, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_str_async = function (out, passwd, opslimit, memlimit, callback = undefined) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_STRBYTES,
    "out must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(typeof opslimit === 'number', 'opslimit must be a number')
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(typeof memlimit === 'number', 'memlimit must be a number')
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_str_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_str_verify = function (str, passwd) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )

  return binding.crypto_pwhash_str_verify(str, passwd)
}

exports.crypto_pwhash_str_verify_async = function (str, passwd, callback = undefined) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  const [done, promise] = checkStatus(callback, true)

  binding.crypto_pwhash_str_verify_async(
    str.buffer,
    str.byteOffset,
    str.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    done
  )

  return promise
}

exports.crypto_pwhash_str_needs_rehash = function (str, opslimit, memlimit) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  return binding.crypto_pwhash_str_needs_rehash(str, opslimit, memlimit)
}

exports.crypto_pwhash_scryptsalsa208sha256 = function (out, passwd, salt, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MIN,
    "out must be at least 'crypto_pwhash_scryptsalsa208sha256_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MAX,
    "out must be at most 'crypto_pwhash_scryptsalsa208sha256_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_SALTBYTES,
    "salt must be 'crypto_pwhash_scryptsalsa208sha256_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_scryptsalsa208sha256(out, passwd, salt, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_scryptsalsa208sha256_async = function (
  out,
  passwd,
  salt,
  opslimit,
  memlimit,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MIN,
    "out must be at least 'crypto_pwhash_scryptsalsa208sha256_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MAX,
    "out must be at most 'crypto_pwhash_scryptsalsa208sha256_BYTES_MAX' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    salt.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_SALTBYTES,
    "salt must be 'crypto_pwhash_scryptsalsa208sha256_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_scryptsalsa208sha256_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str_async = function (
  out,
  passwd,
  opslimit,
  memlimit,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "out must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_scryptsalsa208sha256_str_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str = function (out, passwd, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "out must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_scryptsalsa208sha256_str(out, passwd, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_scryptsalsa208sha256_str_verify_async = function (
  str,
  passwd,
  callback = undefined
) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  const [done, promise] = checkStatus(callback, true)

  binding.crypto_pwhash_scryptsalsa208sha256_str_verify_async(
    str.buffer,
    str.byteOffset,
    str.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str_verify = function (str, passwd) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  return binding.crypto_pwhash_scryptsalsa208sha256_str_verify(str, passwd)
}

exports.crypto_pwhash_scryptsalsa208sha256_str_needs_rehash = function (str, opslimit, memlimit) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  return binding.crypto_pwhash_scryptsalsa208sha256_str_needs_rehash(str, opslimit, memlimit)
}

// crypto_kx

exports.crypto_kx_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "pk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "sk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    pk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "pk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "sk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    seed.byteLength === binding.crypto_kx_SEEDBYTES,
    "seed must be 'crypto_kx_SEEDBYTES' bytes"
  )

  const res = binding.crypto_kx_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_client_session_keys = function (rx, tx, clientPk, clientSk, serverPk) {
  if (!rx) rx = undefined
  if (!tx) tx = undefined

  assert(rx || tx, 'at least one session key must be specified')

  if (rx) {
    assert(ArrayBuffer.isView(rx), 'rx must be a typed array')
    assert(
      rx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "rx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  if (tx) {
    assert(ArrayBuffer.isView(tx), 'tx must be a typed array')
    assert(
      tx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "tx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  assert(ArrayBuffer.isView(clientPk), 'clientPk must be a typed array')
  assert(ArrayBuffer.isView(clientSk), 'clientSk must be a typed array')
  assert(ArrayBuffer.isView(serverPk), 'serverPk must be a typed array')
  assert(
    clientPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "clientPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    clientSk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "clientSk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    serverPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "serverPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_client_session_keys(rx, tx, clientPk, clientSk, serverPk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_server_session_keys = function (rx, tx, serverPk, serverSk, clientPk) {
  if (!rx) rx = undefined
  if (!tx) tx = undefined

  assert(rx || tx, 'at least one session key must be specified')

  if (rx) {
    assert(ArrayBuffer.isView(rx), 'rx must be a typed array')
    assert(
      rx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "rx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  if (tx) {
    assert(ArrayBuffer.isView(tx), 'tx must be a typed array')
    assert(
      tx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "tx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  assert(ArrayBuffer.isView(serverPk), 'serverPk must be a typed array')
  assert(ArrayBuffer.isView(serverSk), 'serverSk must be a typed array')
  assert(ArrayBuffer.isView(clientPk), 'clientPk must be a typed array')
  assert(
    serverPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "serverPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    serverSk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "serverSk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    clientPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "clientPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_server_session_keys(rx, tx, serverPk, serverSk, clientPk)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_scalarmult

exports.crypto_scalarmult_base = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_BYTES,
    "q must be 'crypto_scalarmult_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_SCALARBYTES,
    "n must be 'crypto_scalarmult_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_base(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_BYTES,
    "q must be 'crypto_scalarmult_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_SCALARBYTES,
    "n must be 'crypto_scalarmult_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_BYTES,
    "p must be 'crypto_scalarmult_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_base = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_base(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519 = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "p must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_is_valid_point = function (p) {
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )

  return binding.crypto_core_ed25519_is_valid_point(p)
}

exports.crypto_core_ed25519_from_uniform = function (p, r) {
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_UNIFORMBYTES,
    "r must be 'crypto_core_ed25519_UNIFORMBYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_from_uniform(p, r)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_base_noclamp = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_base_noclamp(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_noclamp = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "p must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_noclamp(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_core

exports.crypto_core_ed25519_add = function (r, p, q) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_BYTES,
    "r must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_core_ed25519_BYTES,
    "q must be 'crypto_core_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_add(r, p, q)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_sub = function (r, p, q) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_BYTES,
    "r must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_core_ed25519_BYTES,
    "q must be 'crypto_core_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_sub(r, p, q)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_scalar_random = function (r) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "r must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_random(r)
}

exports.crypto_core_ed25519_scalar_reduce = function (r, s) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "r must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_NONREDUCEDSCALARBYTES,
    "s must be 'crypto_core_ed25519_NONREDUCEDSCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_reduce(r, s)
}

exports.crypto_core_ed25519_scalar_invert = function (recip, s) {
  assert(ArrayBuffer.isView(recip), 'recip must be a typed array')
  assert(
    recip.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "recip must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_invert(recip, s)
}

exports.crypto_core_ed25519_scalar_negate = function (neg, s) {
  assert(ArrayBuffer.isView(neg), 'neg must be a typed array')
  assert(
    neg.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "neg must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_negate(neg, s)
}

exports.crypto_core_ed25519_scalar_complement = function (comp, s) {
  assert(ArrayBuffer.isView(comp), 'comp must be a typed array')
  assert(
    comp.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "comp must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_complement(comp, s)
}

exports.crypto_core_ed25519_scalar_add = function (z, x, y) {
  assert(ArrayBuffer.isView(z), 'z must be a typed array')
  assert(
    z.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "z must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(x), 'x must be a typed array')
  assert(
    x.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "x must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(y), 'y must be a typed array')
  assert(
    y.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "y must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_add(z, x, y)
}

exports.crypto_core_ed25519_scalar_sub = function (z, x, y) {
  assert(ArrayBuffer.isView(z), 'z must be a typed array')
  assert(
    z.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "z must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(x), 'x must be a typed array')
  assert(
    x.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "x must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(y), 'y must be a typed array')
  assert(
    y.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "y must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_sub(z, x, y)
}

// crypto_shorthash

exports.crypto_shorthash = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_shorthash_BYTES,
    "out must be 'crypto_shorthash_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_shorthash_KEYBYTES,
    "k must be 'crypto_shorthash_KEYBYTES' bytes"
  )

  const res = binding.crypto_shorthash(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_kdf

exports.crypto_kdf_keygen = function (key) {
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(key.byteLength === binding.crypto_kdf_KEYBYTES, "key must be 'crypto_kdf_KEYBYTES' bytes")

  binding.crypto_kdf_keygen(key)
}

exports.crypto_kdf_derive_from_key = function (subkey, subkeyId, ctx, key) {
  assert(ArrayBuffer.isView(subkey), 'subkey must be a typed array')
  assert(
    subkey.byteLength >= binding.crypto_kdf_BYTES_MIN,
    "subkey must be at least 'crypto_kdf_BYTES_MIN' bytes"
  )
  assert(
    subkey.byteLength <= binding.crypto_kdf_BYTES_MAX,
    "subkey must be at most 'crypto_kdf_BYTES_MAX' bytes"
  )
  assert(ArrayBuffer.isView(ctx), 'ctx must be a typed array')
  assert(
    ctx.byteLength === binding.crypto_kdf_CONTEXTBYTES,
    "ctx must be 'crypto_kdf_CONTEXTBYTES' bytes"
  )
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(key.byteLength === binding.crypto_kdf_KEYBYTES, "key must be 'crypto_kdf_KEYBYTES' bytes")

  const res = binding.crypto_kdf_derive_from_key(subkey, subkeyId, ctx, key)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_hash

exports.crypto_hash = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(out.byteLength === binding.crypto_hash_BYTES, "out must be 'crypto_hash_BYTES' bytes")

  const res = binding.crypto_hash(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256 = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha256_BYTES,
    "out must be 'crypto_hash_sha256_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha256(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_init = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_init(state)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha256_BYTES,
    "out must be 'crypto_hash_sha256_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512 = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha512_BYTES,
    "out must be 'crypto_hash_sha512_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha512(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_init = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_init(state)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha512_BYTES,
    "out must be 'crypto_hash_sha512_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_aead

exports.crypto_aead_xchacha20poly1305_ietf_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  binding.crypto_aead_xchacha20poly1305_ietf_keygen(k)
}

exports.crypto_aead_xchacha20poly1305_ietf_encrypt = function (c, m, ad, nsec, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "c must be 'm.byteLength + crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(c.byteLength <= 0xffffffff, 'c.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_encrypt(c, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_decrypt = function (m, nsec, c, ad, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "m must be 'c.byteLength - crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(m.byteLength <= 0xffffffff, 'm.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_decrypt(m, c, ad, npub, k)

  if (res < 0) throw new Error('could not verify data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_encrypt_detached = function (
  c,
  mac,
  m,
  ad,
  nsec,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_encrypt_detached(c, mac, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_decrypt_detached = function (
  m,
  nsec,
  c,
  mac,
  ad,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_decrypt_detached(m, c, mac, ad, npub, k)

  if (res !== 0) throw new Error('could not verify data')
}

exports.crypto_aead_chacha20poly1305_ietf_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  binding.crypto_aead_chacha20poly1305_ietf_keygen(k)
}

exports.crypto_aead_chacha20poly1305_ietf_encrypt = function (c, m, ad, nsec, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "c must be 'm.byteLength + crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(c.byteLength <= 0xffffffff, 'c.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_encrypt(c, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_decrypt = function (m, nsec, c, ad, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "m must be 'c.byteLength - crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(m.byteLength <= 0xffffffff, 'm.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_decrypt(m, c, ad, npub, k)

  if (res < 0) throw new Error('could not verify data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_encrypt_detached = function (
  c,
  mac,
  m,
  ad,
  nsec,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_encrypt_detached(c, mac, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_decrypt_detached = function (
  m,
  nsec,
  c,
  mac,
  ad,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_decrypt_detached(m, c, mac, ad, npub, k)

  if (res !== 0) throw new Error('could not verify data')
}

// crypto_stream

exports.crypto_stream_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  binding.crypto_stream_xor_wrap_init(state, n, k)
}

exports.crypto_stream_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_xor_wrap_update(state, c, m)
}

exports.crypto_stream_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_xor_wrap_final(state)
}

exports.crypto_stream_chacha20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  binding.crypto_stream_chacha20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_chacha20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_chacha20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_chacha20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_chacha20_xor_wrap_final(state)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  binding.crypto_stream_chacha20_ietf_xor_wrap_init(state, n, k)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_chacha20_ietf_xor_wrap_update(state, c, m)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_chacha20_ietf_xor_wrap_final(state)
}

exports.crypto_stream_xchacha20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  binding.crypto_stream_xchacha20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_xchacha20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_xchacha20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_xchacha20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_xchacha20_xor_wrap_final(state)
}

exports.crypto_stream_salsa20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  binding.crypto_stream_salsa20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_salsa20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_salsa20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_salsa20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_salsa20_xor_wrap_final(state)
}

// experimental

exports.extension_tweak_ed25519_base = function (n, p, ns) {
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.extension_tweak_ed25519_BYTES,
    "p must be 'extension_tweak_ed25519_BYTES' bytes"
  )

  binding.extension_tweak_ed25519_base(n, p, ns)
}

exports.extension_tweak_ed25519_sign_detached = function (sig, m, scalar, pk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(sig.byteLength === binding.crypto_sign_BYTES, "sig must be 'crypto_sign_BYTES' bytes")
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  if (pk) {
    assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
    assert(
      pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
      "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
    )
  }

  const res = binding.extension_tweak_ed25519_sign_detached(sig, m, scalar, pk)

  if (res !== 0) throw new Error('failed to compute signature')
}

exports.extension_tweak_ed25519_sk_to_scalar = function (n, sk) {
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  binding.extension_tweak_ed25519_sk_to_scalar(n, sk)
}

exports.extension_tweak_ed25519_scalar = function (scalarOut, scalar, ns) {
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_scalar(scalarOut, scalar, ns)
}

exports.extension_tweak_ed25519_pk = function (tpk, pk, ns) {
  assert(ArrayBuffer.isView(tpk), 'tpk must be a typed array')
  assert(
    tpk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "tpk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_pk(tpk, pk, ns)

  if (res !== 0) throw new Error('failed to tweak public key')
}

exports.extension_tweak_ed25519_keypair = function (pk, scalarOut, scalarIn, ns) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.extension_tweak_ed25519_BYTES,
    "pk must be 'extension_tweak_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarIn), 'scalarIn must be a typed array')
  assert(
    scalarIn.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarIn must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_keypair(pk, scalarOut, scalarIn, ns)
}

exports.extension_tweak_ed25519_scalar_add = function (scalarOut, scalar, n) {
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_scalar_add(scalarOut, scalar, n)
}

exports.extension_tweak_ed25519_pk_add = function (tpk, pk, p) {
  assert(ArrayBuffer.isView(tpk), 'tpk must be a typed array')
  assert(
    tpk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "tpk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "p must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_pk_add(tpk, pk, p)

  if (res !== 0) throw new Error('failed to add tweak to public key')
}

exports.extension_tweak_ed25519_keypair_add = function (pk, scalarOut, scalarIn, tweak) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.extension_tweak_ed25519_BYTES,
    "pk must be 'extension_tweak_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarIn), 'scalarIn must be a typed array')
  assert(
    scalarIn.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarIn must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(tweak), 'tweak must be a typed array')
  assert(
    tweak.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "tweak must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_keypair_add(pk, scalarOut, scalarIn, tweak)

  if (res !== 0) throw new Error('failed to add tweak to keypair')
}

exports.extension_pbkdf2_sha512_async = function (out, passwd, salt, iter, outlen, callback) {
  assert(
    iter >= binding.extension_pbkdf2_sha512_ITERATIONS_MIN,
    "iter must be at least 'extension_pbkdf2_sha512_ITERATIONS_MIN'"
  )
  assert(
    outlen <= binding.extension_pbkdf2_sha512_BYTES_MAX,
    "outlen must be at most 'extension_pbkdf2_sha512_BYTES_MAX'"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(out.byteLength >= outlen, "out must be at least 'outlen' bytes")
  assert(out.byteLength > 0, 'out must not be empty')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(salt.byteLength > 0, 'salt must not be empty')

  const [done, promise] = checkStatus(callback)

  binding.extension_pbkdf2_sha512_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    iter,
    outlen,

    done
  )

  return promise
}

exports.extension_pbkdf2_sha512 = function (out, passwd, salt, iter, outlen) {
  assert(
    iter >= binding.extension_pbkdf2_sha512_ITERATIONS_MIN,
    "iter must be at least 'extension_pbkdf2_sha512_ITERATIONS_MIN'"
  )
  assert(
    outlen <= binding.extension_pbkdf2_sha512_BYTES_MAX,
    "outlen must be at most 'extension_pbkdf2_sha512_BYTES_MAX'"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(out.byteLength >= outlen, "out must be at least 'outlen' bytes")
  assert(out.byteLength > 0, 'out must not be empty')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(salt.byteLength > 0, 'salt must not be empty')

  const res = binding.extension_pbkdf2_sha512(out, passwd, salt, iter, outlen)

  if (res !== 0) throw new Error('failed to add tweak to public key')
}

function checkStatus(callback, booleanResult = false) {
  let done, promise

  if (typeof callback === 'function') {
    done = function (status) {
      if (booleanResult) callback(null, status === 0)
      else if (status === 0) callback(null)
      else callback(new Error('status: ' + status))
    }
  } else {
    promise = new Promise(function (resolve, reject) {
      done = function (status) {
        if (booleanResult) resolve(status === 0)
        else if (status === 0) resolve()
        else reject(new Error('status: ' + status))
      }
    })
  }

  return [done, promise]
}
{
  "name": "sodium-native",
  "version": "5.1.0",
  "description": "Low level bindings for libsodium",
  "main": "index.js",
  "files": [
    "index.js",
    "binding.cc",
    "binding.js",
    "extensions",
    "prebuilds",
    "CMakeLists.txt"
  ],
  "imports": {
    "assert": {
      "bare": "bare-assert",
      "node": "assert"
    }
  },
  "addon": true,
  "dependencies": {
    "bare-assert": "^1.2.0",
    "require-addon": "^1.1.0",
    "which-runtime": "^1.2.1"
  },
  "devDependencies": {
    "bare-compat-napi": "^1.3.5",
    "brittle": "^3.16.2",
    "cmake-bare": "^1.6.1",
    "cmake-fetch": "^1.4.3",
    "cmake-napi": "^1.2.1",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "test": "prettier . --check && npm run test:node && npm run test:bare",
    "test:node": "node test/all.js",
    "test:bare": "bare test/all.js"
  },
  "standard": {
    "ignore": [
      "/test/fixtures/*.js"
    ]
  },
  "engines": {
    "bare": ">=1.16.0"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sodium-native.git"
  },
  "contributors": [
    "Emil Bay <github@tixz.dk> (http://bayes.dk)",
    "Mathias Buus <mathiasbuus@gmail.com> (https://mafinto.sh)",
    "Christophe Diederichs <chm-diederichs@hyperdivision.dk>"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/sodium-native/issues"
  },
  "homepage": "https://github.com/holepunchto/sodium-native"
}
const sodium = require('sodium-universal')
const b4a = require('b4a')

const ABYTES = sodium.crypto_secretstream_xchacha20poly1305_ABYTES
const TAG_MESSAGE = sodium.crypto_secretstream_xchacha20poly1305_TAG_MESSAGE
const TAG_FINAL = sodium.crypto_secretstream_xchacha20poly1305_TAG_FINAL
const STATEBYTES = sodium.crypto_secretstream_xchacha20poly1305_STATEBYTES
const HEADERBYTES = sodium.crypto_secretstream_xchacha20poly1305_HEADERBYTES
const KEYBYTES = sodium.crypto_secretstream_xchacha20poly1305_KEYBYTES
const TAG_FINAL_BYTE = b4a.isBuffer(TAG_FINAL) ? TAG_FINAL[0] : TAG_FINAL

const EMPTY = b4a.alloc(0)
const TAG = b4a.alloc(1)

class Push {
  constructor (key, state = b4a.allocUnsafeSlow(STATEBYTES), header = b4a.allocUnsafeSlow(HEADERBYTES)) {
    if (!TAG_FINAL) throw new Error('JavaScript sodium version needs to support crypto_secretstream_xchacha20poly')

    this.key = key
    this.state = state
    this.header = header

    sodium.crypto_secretstream_xchacha20poly1305_init_push(this.state, this.header, this.key)
  }

  next (message, cipher = b4a.allocUnsafe(message.byteLength + ABYTES)) {
    sodium.crypto_secretstream_xchacha20poly1305_push(this.state, cipher, message, null, TAG_MESSAGE)
    return cipher
  }

  final (message = EMPTY, cipher = b4a.allocUnsafe(ABYTES)) {
    sodium.crypto_secretstream_xchacha20poly1305_push(this.state, cipher, message, null, TAG_FINAL)
    return cipher
  }
}

class Pull {
  constructor (key, state = b4a.allocUnsafeSlow(STATEBYTES)) {
    if (!TAG_FINAL) throw new Error('JavaScript sodium version needs to support crypto_secretstream_xchacha20poly')

    this.key = key
    this.state = state
    this.final = false
  }

  init (header) {
    sodium.crypto_secretstream_xchacha20poly1305_init_pull(this.state, header, this.key)
  }

  next (cipher, message = b4a.allocUnsafe(cipher.byteLength - ABYTES)) {
    sodium.crypto_secretstream_xchacha20poly1305_pull(this.state, message, TAG, cipher, null)
    this.final = TAG[0] === TAG_FINAL_BYTE
    return message
  }
}

function keygen (buf = b4a.alloc(KEYBYTES)) {
  sodium.crypto_secretstream_xchacha20poly1305_keygen(buf)
  return buf
}

module.exports = {
  keygen,
  KEYBYTES,
  ABYTES,
  STATEBYTES,
  HEADERBYTES,
  Push,
  Pull
}
{
  "name": "sodium-secretstream",
  "version": "1.2.0",
  "description": "Wraps libsodiums secretstream in a higher level abstraction",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.1.1",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "standard": "^17.0.0"
  },
  "scripts": {
    "test": "standard"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/sodium-secretstream.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/sodium-secretstream/issues"
  },
  "homepage": "https://github.com/mafintosh/sodium-secretstream"
}
module.exports = require('sodium-native')
{
  "name": "sodium-universal",
  "version": "5.0.1",
  "description": "Universal wrapper for sodium-javascript and sodium-native working in Node.js and the Browser",
  "main": "index.js",
  "dependencies": {
    "sodium-native": "^5.0.1"
  },
  "peerDependencies": {
    "sodium-javascript": "~0.8.0"
  },
  "peerDependenciesMeta": {
    "sodium-javascript": {
      "optional": true
    }
  },
  "scripts": {
    "prepublish": "./build-scripts/generate.js"
  },
  "browser": {
    "sodium-native": "sodium-javascript"
  },
  "browserify": {
    "transform": [
      "./build-scripts/transform.js"
    ]
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sodium-universal.git"
  },
  "keywords": [
    "libsodium",
    "sodium",
    "sodium-native",
    "sodium-javascript",
    "browserify"
  ],
  "contributors": [
    "Emil Bay <github@tixz.dk> (http://bayes.dk)",
    "Mathias Buus <mathiasbuus@gmail.com> (https://mafinto.sh)",
    "Christophe Diederichs <chm-diederichs@hyperdivision.dk>"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/sodium-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/sodium-universal#readme"
}
const { EventEmitter } = require('events-universal')
const FIFO = require('fast-fifo')
const TextDecoder = require('text-decoder')

const StreamError = require('./lib/errors.js')

// if we do a future major, expect queue microtask to be there always, for now a bit defensive
const qmt =
  typeof queueMicrotask === 'undefined' ? (fn) => global.process.nextTick(fn) : queueMicrotask

// 29 bits used total (4 from shared, 14 from read, and 11 from write)
const MAX = (1 << 29) - 1

// Shared state
const OPENING = 0b0001
const PREDESTROYING = 0b0010
const DESTROYING = 0b0100
const DESTROYED = 0b1000

const NOT_OPENING = MAX ^ OPENING
const NOT_PREDESTROYING = MAX ^ PREDESTROYING

// Read state (4 bit offset from shared state)
const READ_ACTIVE = 0b00000000000001 << 4
const READ_UPDATING = 0b00000000000010 << 4
const READ_PRIMARY = 0b00000000000100 << 4
const READ_QUEUED = 0b00000000001000 << 4
const READ_RESUMED = 0b00000000010000 << 4
const READ_PIPE_DRAINED = 0b00000000100000 << 4
const READ_ENDING = 0b00000001000000 << 4
const READ_EMIT_DATA = 0b00000010000000 << 4
const READ_EMIT_READABLE = 0b00000100000000 << 4
const READ_EMITTED_READABLE = 0b00001000000000 << 4
const READ_DONE = 0b00010000000000 << 4
const READ_NEXT_TICK = 0b00100000000000 << 4
const READ_NEEDS_PUSH = 0b01000000000000 << 4
const READ_READ_AHEAD = 0b10000000000000 << 4

// Combined read state
const READ_FLOWING = READ_RESUMED | READ_PIPE_DRAINED
const READ_ACTIVE_AND_NEEDS_PUSH = READ_ACTIVE | READ_NEEDS_PUSH
const READ_PRIMARY_AND_ACTIVE = READ_PRIMARY | READ_ACTIVE
const READ_EMIT_READABLE_AND_QUEUED = READ_EMIT_READABLE | READ_QUEUED
const READ_RESUMED_READ_AHEAD = READ_RESUMED | READ_READ_AHEAD

const READ_NOT_ACTIVE = MAX ^ READ_ACTIVE
const READ_NON_PRIMARY = MAX ^ READ_PRIMARY
const READ_NON_PRIMARY_AND_PUSHED = MAX ^ (READ_PRIMARY | READ_NEEDS_PUSH)
const READ_PUSHED = MAX ^ READ_NEEDS_PUSH
const READ_PAUSED = MAX ^ READ_RESUMED
const READ_NOT_QUEUED = MAX ^ (READ_QUEUED | READ_EMITTED_READABLE)
const READ_NOT_ENDING = MAX ^ READ_ENDING
const READ_PIPE_NOT_DRAINED = MAX ^ READ_FLOWING
const READ_NOT_NEXT_TICK = MAX ^ READ_NEXT_TICK
const READ_NOT_UPDATING = MAX ^ READ_UPDATING
const READ_NO_READ_AHEAD = MAX ^ READ_READ_AHEAD
const READ_PAUSED_NO_READ_AHEAD = MAX ^ READ_RESUMED_READ_AHEAD

// Write state (18 bit offset, 4 bit offset from shared state and 14 from read state)
const WRITE_ACTIVE = 0b00000000001 << 18
const WRITE_UPDATING = 0b00000000010 << 18
const WRITE_PRIMARY = 0b00000000100 << 18
const WRITE_QUEUED = 0b00000001000 << 18
const WRITE_UNDRAINED = 0b00000010000 << 18
const WRITE_DONE = 0b00000100000 << 18
const WRITE_EMIT_DRAIN = 0b00001000000 << 18
const WRITE_NEXT_TICK = 0b00010000000 << 18
const WRITE_WRITING = 0b00100000000 << 18
const WRITE_FINISHING = 0b01000000000 << 18
const WRITE_CORKED = 0b10000000000 << 18

const WRITE_NOT_ACTIVE = MAX ^ (WRITE_ACTIVE | WRITE_WRITING)
const WRITE_NON_PRIMARY = MAX ^ WRITE_PRIMARY
const WRITE_NOT_FINISHING = MAX ^ (WRITE_ACTIVE | WRITE_FINISHING)
const WRITE_DRAINED = MAX ^ WRITE_UNDRAINED
const WRITE_NOT_QUEUED = MAX ^ WRITE_QUEUED
const WRITE_NOT_NEXT_TICK = MAX ^ WRITE_NEXT_TICK
const WRITE_NOT_UPDATING = MAX ^ WRITE_UPDATING
const WRITE_NOT_CORKED = MAX ^ WRITE_CORKED

// Combined shared state
const ACTIVE = READ_ACTIVE | WRITE_ACTIVE
const NOT_ACTIVE = MAX ^ ACTIVE
const DONE = READ_DONE | WRITE_DONE
const DESTROY_STATUS = DESTROYING | DESTROYED | PREDESTROYING
const OPEN_STATUS = DESTROY_STATUS | OPENING
const AUTO_DESTROY = DESTROY_STATUS | DONE
const NON_PRIMARY = WRITE_NON_PRIMARY & READ_NON_PRIMARY
const ACTIVE_OR_TICKING = WRITE_NEXT_TICK | READ_NEXT_TICK
const TICKING = ACTIVE_OR_TICKING & NOT_ACTIVE
const IS_OPENING = OPEN_STATUS | TICKING

// Combined shared state and read state
const READ_PRIMARY_STATUS = OPEN_STATUS | READ_ENDING | READ_DONE
const READ_STATUS = OPEN_STATUS | READ_DONE | READ_QUEUED
const READ_ENDING_STATUS = OPEN_STATUS | READ_ENDING | READ_QUEUED
const READ_READABLE_STATUS = OPEN_STATUS | READ_EMIT_READABLE | READ_QUEUED | READ_EMITTED_READABLE
const SHOULD_NOT_READ =
  OPEN_STATUS | READ_ACTIVE | READ_ENDING | READ_DONE | READ_NEEDS_PUSH | READ_READ_AHEAD
const READ_BACKPRESSURE_STATUS = DESTROY_STATUS | READ_ENDING | READ_DONE
const READ_UPDATE_SYNC_STATUS = READ_UPDATING | OPEN_STATUS | READ_NEXT_TICK | READ_PRIMARY
const READ_NEXT_TICK_OR_OPENING = READ_NEXT_TICK | OPENING

// Combined write state
const WRITE_PRIMARY_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_DONE
const WRITE_QUEUED_AND_UNDRAINED = WRITE_QUEUED | WRITE_UNDRAINED
const WRITE_QUEUED_AND_ACTIVE = WRITE_QUEUED | WRITE_ACTIVE
const WRITE_DRAIN_STATUS = WRITE_QUEUED | WRITE_UNDRAINED | OPEN_STATUS | WRITE_ACTIVE
const WRITE_STATUS = OPEN_STATUS | WRITE_ACTIVE | WRITE_QUEUED | WRITE_CORKED
const WRITE_PRIMARY_AND_ACTIVE = WRITE_PRIMARY | WRITE_ACTIVE
const WRITE_ACTIVE_AND_WRITING = WRITE_ACTIVE | WRITE_WRITING
const WRITE_FINISHING_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_QUEUED_AND_ACTIVE | WRITE_DONE
const WRITE_BACKPRESSURE_STATUS = WRITE_UNDRAINED | DESTROY_STATUS | WRITE_FINISHING | WRITE_DONE
const WRITE_UPDATE_SYNC_STATUS = WRITE_UPDATING | OPEN_STATUS | WRITE_NEXT_TICK | WRITE_PRIMARY
const WRITE_DROP_DATA = WRITE_FINISHING | WRITE_DONE | DESTROY_STATUS

const asyncIterator = Symbol.asyncIterator || Symbol('asyncIterator')

class WritableState {
  constructor(
    stream,
    { highWaterMark = 16384, map = null, mapWritable, byteLength, byteLengthWritable } = {}
  ) {
    this.stream = stream
    this.queue = new FIFO()
    this.highWaterMark = highWaterMark
    this.buffered = 0
    this.error = null
    this.pipeline = null
    this.drains = null // if we add more seldomly used helpers we might them into a subobject so its a single ptr
    this.byteLength = byteLengthWritable || byteLength || defaultByteLength
    this.map = mapWritable || map
    this.afterWrite = afterWrite.bind(this)
    this.afterUpdateNextTick = updateWriteNT.bind(this)
  }

  get ending() {
    return (this.stream._duplexState & WRITE_FINISHING) !== 0
  }

  get ended() {
    return (this.stream._duplexState & WRITE_DONE) !== 0
  }

  push(data) {
    if ((this.stream._duplexState & WRITE_DROP_DATA) !== 0) return false
    if (this.map !== null) data = this.map(data)

    this.buffered += this.byteLength(data)
    this.queue.push(data)

    if (this.buffered < this.highWaterMark) {
      this.stream._duplexState |= WRITE_QUEUED
      return true
    }

    this.stream._duplexState |= WRITE_QUEUED_AND_UNDRAINED
    return false
  }

  shift() {
    const data = this.queue.shift()

    this.buffered -= this.byteLength(data)
    if (this.buffered === 0) this.stream._duplexState &= WRITE_NOT_QUEUED

    return data
  }

  end(data) {
    if (typeof data === 'function') {
      this.stream.once('finish', data)
    } else if (data !== undefined && data !== null) {
      this.push(data)
    }

    this.stream._duplexState = (this.stream._duplexState | WRITE_FINISHING) & WRITE_NON_PRIMARY
  }

  autoBatch(data, cb) {
    const buffer = []
    const stream = this.stream

    buffer.push(data)
    while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED_AND_ACTIVE) {
      buffer.push(stream._writableState.shift())
    }

    if ((stream._duplexState & OPEN_STATUS) !== 0) return cb(null)
    stream._writev(buffer, cb)
  }

  update() {
    const stream = this.stream

    stream._duplexState |= WRITE_UPDATING

    do {
      while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED) {
        const data = this.shift()
        stream._duplexState |= WRITE_ACTIVE_AND_WRITING
        stream._write(data, this.afterWrite)
      }

      if ((stream._duplexState & WRITE_PRIMARY_AND_ACTIVE) === 0) this.updateNonPrimary()
    } while (this.continueUpdate() === true)

    stream._duplexState &= WRITE_NOT_UPDATING
  }

  updateNonPrimary() {
    const stream = this.stream

    if ((stream._duplexState & WRITE_FINISHING_STATUS) === WRITE_FINISHING) {
      stream._duplexState = stream._duplexState | WRITE_ACTIVE
      stream._final(afterFinal.bind(this))
      return
    }

    if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
      if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
        stream._duplexState |= ACTIVE
        stream._destroy(afterDestroy.bind(this))
      }
      return
    }

    if ((stream._duplexState & IS_OPENING) === OPENING) {
      stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING
      stream._open(afterOpen.bind(this))
    }
  }

  continueUpdate() {
    if ((this.stream._duplexState & WRITE_NEXT_TICK) === 0) return false
    this.stream._duplexState &= WRITE_NOT_NEXT_TICK
    return true
  }

  updateCallback() {
    if ((this.stream._duplexState & WRITE_UPDATE_SYNC_STATUS) === WRITE_PRIMARY) {
      this.update()
    } else {
      this.updateNextTick()
    }
  }

  updateNextTick() {
    if ((this.stream._duplexState & WRITE_NEXT_TICK) !== 0) return
    this.stream._duplexState |= WRITE_NEXT_TICK
    if ((this.stream._duplexState & WRITE_UPDATING) === 0) qmt(this.afterUpdateNextTick)
  }
}

class ReadableState {
  constructor(
    stream,
    { highWaterMark = 16384, map = null, mapReadable, byteLength, byteLengthReadable } = {}
  ) {
    this.stream = stream
    this.queue = new FIFO()
    this.highWaterMark = highWaterMark === 0 ? 1 : highWaterMark
    this.buffered = 0
    this.readAhead = highWaterMark > 0
    this.error = null
    this.pipeline = null
    this.byteLength = byteLengthReadable || byteLength || defaultByteLength
    this.map = mapReadable || map
    this.pipeTo = null
    this.afterRead = afterRead.bind(this)
    this.afterUpdateNextTick = updateReadNT.bind(this)
  }

  get ending() {
    return (this.stream._duplexState & READ_ENDING) !== 0
  }

  get ended() {
    return (this.stream._duplexState & READ_DONE) !== 0
  }

  pipe(pipeTo, cb) {
    if (this.pipeTo !== null) throw StreamError.BAD_ARGUMENT('Can only pipe to one destination')
    if (typeof cb !== 'function') cb = null

    this.stream._duplexState |= READ_PIPE_DRAINED
    this.pipeTo = pipeTo
    this.pipeline = new Pipeline(this.stream, pipeTo, cb)

    if (cb) this.stream.on('error', noop) // We already error handle this so supress crashes

    if (isStreamx(pipeTo)) {
      pipeTo._writableState.pipeline = this.pipeline
      if (cb) pipeTo.on('error', noop) // We already error handle this so supress crashes
      pipeTo.on('finish', this.pipeline.finished.bind(this.pipeline)) // TODO: just call finished from pipeTo itself
    } else {
      const onerror = this.pipeline.done.bind(this.pipeline, pipeTo)
      const onclose = this.pipeline.done.bind(this.pipeline, pipeTo, null) // onclose has a weird bool arg
      pipeTo.on('error', onerror)
      pipeTo.on('close', onclose)
      pipeTo.on('finish', this.pipeline.finished.bind(this.pipeline))
    }

    pipeTo.on('drain', afterDrain.bind(this))
    this.stream.emit('piping', pipeTo)
    pipeTo.emit('pipe', this.stream)
  }

  push(data) {
    const stream = this.stream

    if (data === null) {
      this.highWaterMark = 0
      stream._duplexState = (stream._duplexState | READ_ENDING) & READ_NON_PRIMARY_AND_PUSHED
      return false
    }

    if (this.map !== null) {
      data = this.map(data)
      if (data === null) {
        stream._duplexState &= READ_PUSHED
        return this.buffered < this.highWaterMark
      }
    }

    this.buffered += this.byteLength(data)
    this.queue.push(data)

    stream._duplexState = (stream._duplexState | READ_QUEUED) & READ_PUSHED

    return this.buffered < this.highWaterMark
  }

  shift() {
    const data = this.queue.shift()

    this.buffered -= this.byteLength(data)
    if (this.buffered === 0) {
      this.stream._duplexState &= READ_NOT_QUEUED
    }

    return data
  }

  unshift(data) {
    const pending = [this.map !== null ? this.map(data) : data]
    while (this.buffered > 0) pending.push(this.shift())

    for (let i = 0; i < pending.length - 1; i++) {
      const data = pending[i]
      this.buffered += this.byteLength(data)
      this.queue.push(data)
    }

    this.push(pending[pending.length - 1])
  }

  read() {
    const stream = this.stream

    if ((stream._duplexState & READ_STATUS) === READ_QUEUED) {
      const data = this.shift()

      if (this.pipeTo !== null && this.pipeTo.write(data) === false) {
        stream._duplexState &= READ_PIPE_NOT_DRAINED
      }

      if ((stream._duplexState & READ_EMIT_DATA) !== 0) {
        stream.emit('data', data)
      }

      return data
    }

    if (this.readAhead === false) {
      stream._duplexState |= READ_READ_AHEAD
      this.updateNextTick()
    }

    return null
  }

  drain() {
    const stream = this.stream

    while (
      (stream._duplexState & READ_STATUS) === READ_QUEUED &&
      (stream._duplexState & READ_FLOWING) !== 0
    ) {
      const data = this.shift()

      if (this.pipeTo !== null && this.pipeTo.write(data) === false) {
        stream._duplexState &= READ_PIPE_NOT_DRAINED
      }

      if ((stream._duplexState & READ_EMIT_DATA) !== 0) {
        stream.emit('data', data)
      }
    }
  }

  update() {
    const stream = this.stream

    stream._duplexState |= READ_UPDATING

    do {
      this.drain()

      while (
        this.buffered < this.highWaterMark &&
        (stream._duplexState & SHOULD_NOT_READ) === READ_READ_AHEAD
      ) {
        stream._duplexState |= READ_ACTIVE_AND_NEEDS_PUSH
        stream._read(this.afterRead)
        this.drain()
      }

      if ((stream._duplexState & READ_READABLE_STATUS) === READ_EMIT_READABLE_AND_QUEUED) {
        stream._duplexState |= READ_EMITTED_READABLE
        stream.emit('readable')
      }

      if ((stream._duplexState & READ_PRIMARY_AND_ACTIVE) === 0) {
        this.updateNonPrimary()
      }
    } while (this.continueUpdate() === true)

    stream._duplexState &= READ_NOT_UPDATING
  }

  updateNonPrimary() {
    const stream = this.stream

    if ((stream._duplexState & READ_ENDING_STATUS) === READ_ENDING) {
      stream._duplexState = (stream._duplexState | READ_DONE) & READ_NOT_ENDING
      stream.emit('end')

      if ((stream._duplexState & AUTO_DESTROY) === DONE) {
        stream._duplexState |= DESTROYING
      }

      if (this.pipeTo !== null) {
        this.pipeTo.end()
      }
    }

    if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
      if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
        stream._duplexState |= ACTIVE
        stream._destroy(afterDestroy.bind(this))
      }
      return
    }

    if ((stream._duplexState & IS_OPENING) === OPENING) {
      stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING
      stream._open(afterOpen.bind(this))
    }
  }

  continueUpdate() {
    if ((this.stream._duplexState & READ_NEXT_TICK) === 0) return false
    this.stream._duplexState &= READ_NOT_NEXT_TICK
    return true
  }

  updateCallback() {
    if ((this.stream._duplexState & READ_UPDATE_SYNC_STATUS) === READ_PRIMARY) {
      this.update()
    } else {
      this.updateNextTick()
    }
  }

  updateNextTickIfOpen() {
    if ((this.stream._duplexState & READ_NEXT_TICK_OR_OPENING) !== 0) return
    this.stream._duplexState |= READ_NEXT_TICK
    if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick)
  }

  updateNextTick() {
    if ((this.stream._duplexState & READ_NEXT_TICK) !== 0) return
    this.stream._duplexState |= READ_NEXT_TICK
    if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick)
  }
}

class TransformState {
  constructor(stream) {
    this.data = null
    this.afterTransform = afterTransform.bind(stream)
    this.afterFinal = null
  }
}

class Pipeline {
  constructor(src, dst, cb) {
    this.from = src
    this.to = dst
    this.afterPipe = cb
    this.error = null
    this.pipeToFinished = false
  }

  finished() {
    this.pipeToFinished = true
  }

  done(stream, err) {
    if (err) this.error = err

    if (stream === this.to) {
      this.to = null

      if (this.from !== null) {
        if ((this.from._duplexState & READ_DONE) === 0 || !this.pipeToFinished) {
          this.from.destroy(this.error || StreamError.PREMATURE_CLOSE('Writable stream closed'))
        }
        return
      }
    }

    if (stream === this.from) {
      this.from = null

      if (this.to !== null) {
        if ((stream._duplexState & READ_DONE) === 0) {
          this.to.destroy(this.error || StreamError.PREMATURE_CLOSE('Readable stream closed'))
        }
        return
      }
    }

    if (this.afterPipe !== null) this.afterPipe(this.error)
    this.to = this.from = this.afterPipe = null
  }
}

function afterDrain() {
  this.stream._duplexState |= READ_PIPE_DRAINED
  this.updateCallback()
}

function afterFinal(err) {
  const stream = this.stream
  if (err) stream.destroy(err)

  if ((stream._duplexState & DESTROY_STATUS) === 0) {
    stream._duplexState |= WRITE_DONE
    stream.emit('finish')
  }

  if ((stream._duplexState & AUTO_DESTROY) === DONE) {
    stream._duplexState |= DESTROYING
  }

  stream._duplexState &= WRITE_NOT_FINISHING

  // no need to wait the extra tick here, so we short circuit that
  if ((stream._duplexState & WRITE_UPDATING) === 0) {
    this.update()
  } else {
    this.updateNextTick()
  }
}

function afterDestroy(err) {
  const stream = this.stream

  if (!err && !StreamError.isStreamDestroyed(this.error)) err = this.error
  if (err) stream.emit('error', err)

  stream._duplexState |= DESTROYED
  stream.emit('close')

  const rs = stream._readableState
  const ws = stream._writableState

  if (rs !== null && rs.pipeline !== null) {
    rs.pipeline.done(stream, err)
  }

  if (ws !== null) {
    while (ws.drains !== null && ws.drains.length > 0) {
      ws.drains.shift().resolve(false)
    }

    if (ws.pipeline !== null) {
      ws.pipeline.done(stream, err)
    }
  }
}

function afterWrite(err) {
  const stream = this.stream

  if (err) stream.destroy(err)
  stream._duplexState &= WRITE_NOT_ACTIVE

  if (this.drains !== null) tickDrains(this.drains)

  if ((stream._duplexState & WRITE_DRAIN_STATUS) === WRITE_UNDRAINED) {
    stream._duplexState &= WRITE_DRAINED

    if ((stream._duplexState & WRITE_EMIT_DRAIN) === WRITE_EMIT_DRAIN) {
      stream.emit('drain')
    }
  }

  this.updateCallback()
}

function afterRead(err) {
  if (err) this.stream.destroy(err)
  this.stream._duplexState &= READ_NOT_ACTIVE

  if (this.readAhead === false && (this.stream._duplexState & READ_RESUMED) === 0) {
    this.stream._duplexState &= READ_NO_READ_AHEAD
  }

  this.updateCallback()
}

function updateReadNT() {
  if ((this.stream._duplexState & READ_UPDATING) === 0) {
    this.stream._duplexState &= READ_NOT_NEXT_TICK
    this.update()
  }
}

function updateWriteNT() {
  if ((this.stream._duplexState & WRITE_UPDATING) === 0) {
    this.stream._duplexState &= WRITE_NOT_NEXT_TICK
    this.update()
  }
}

function tickDrains(drains) {
  for (let i = 0; i < drains.length; i++) {
    // drains.writes are monotonic, so if one is 0 its always the first one
    if (--drains[i].writes === 0) {
      drains.shift().resolve(true)
      i--
    }
  }
}

function afterOpen(err) {
  const stream = this.stream

  if (err) stream.destroy(err)

  if ((stream._duplexState & DESTROYING) === 0) {
    if ((stream._duplexState & READ_PRIMARY_STATUS) === 0) {
      stream._duplexState |= READ_PRIMARY
    }

    if ((stream._duplexState & WRITE_PRIMARY_STATUS) === 0) {
      stream._duplexState |= WRITE_PRIMARY
    }

    stream.emit('open')
  }

  stream._duplexState &= NOT_ACTIVE

  if (stream._writableState !== null) {
    stream._writableState.updateCallback()
  }

  if (stream._readableState !== null) {
    stream._readableState.updateCallback()
  }
}

function afterTransform(err, data) {
  if (data !== undefined && data !== null) this.push(data)
  this._writableState.afterWrite(err)
}

function newListener(name) {
  if (this._readableState !== null) {
    if (name === 'data') {
      this._duplexState |= READ_EMIT_DATA | READ_RESUMED_READ_AHEAD
      this._readableState.updateNextTick()
    }
    if (name === 'readable') {
      this._duplexState |= READ_EMIT_READABLE
      this._readableState.updateNextTick()
    }
  }

  if (this._writableState !== null) {
    if (name === 'drain') {
      this._duplexState |= WRITE_EMIT_DRAIN
      this._writableState.updateNextTick()
    }
  }
}

class Stream extends EventEmitter {
  constructor(opts) {
    super()

    this._duplexState = 0
    this._readableState = null
    this._writableState = null

    if (opts) {
      if (opts.open) this._open = opts.open
      if (opts.destroy) this._destroy = opts.destroy
      if (opts.predestroy) this._predestroy = opts.predestroy
      if (opts.signal) opts.signal.addEventListener('abort', abort.bind(this))
    }

    this.on('newListener', newListener)
  }

  _open(cb) {
    cb(null)
  }

  _destroy(cb) {
    cb(null)
  }

  _predestroy() {
    // does nothing
  }

  get readable() {
    return this._readableState !== null ? true : undefined
  }

  get writable() {
    return this._writableState !== null ? true : undefined
  }

  get destroyed() {
    return (this._duplexState & DESTROYED) !== 0
  }

  get destroying() {
    return (this._duplexState & DESTROY_STATUS) !== 0
  }

  destroy(err) {
    if ((this._duplexState & DESTROY_STATUS) === 0) {
      if (!err) err = StreamError.STREAM_DESTROYED()
      this._duplexState = (this._duplexState | DESTROYING) & NON_PRIMARY

      if (this._readableState !== null) {
        this._readableState.highWaterMark = 0
        this._readableState.error = err
      }

      if (this._writableState !== null) {
        this._writableState.highWaterMark = 0
        this._writableState.error = err
      }

      this._duplexState |= PREDESTROYING
      this._predestroy()
      this._duplexState &= NOT_PREDESTROYING

      if (this._readableState !== null) {
        this._readableState.updateNextTick()
      }

      if (this._writableState !== null) {
        this._writableState.updateNextTick()
      }
    }
  }
}

class Readable extends Stream {
  constructor(opts) {
    super(opts)

    this._duplexState |= OPENING | WRITE_DONE | READ_READ_AHEAD
    this._readableState = new ReadableState(this, opts)

    if (opts) {
      if (this._readableState.readAhead === false) this._duplexState &= READ_NO_READ_AHEAD
      if (opts.read) this._read = opts.read
      if (opts.eagerOpen) this._readableState.updateNextTick()
      if (opts.encoding) this.setEncoding(opts.encoding)
    }
  }

  static deferred(fn, opts) {
    const out = new PassThrough(opts)

    fn()
      .then((src) => {
        if (src === null) return out.end()
        if (out.destroying) return
        pipeline(src, out, noop)
      })
      .catch((err) => out.destroy(err))

    return out
  }

  setEncoding(encoding) {
    const dec = new TextDecoder(encoding)
    const map = this._readableState.map || echo
    this._readableState.map = mapOrSkip
    return this

    function mapOrSkip(data) {
      const next = dec.push(data)
      return next === '' && (data.byteLength !== 0 || dec.remaining > 0) ? null : map(next)
    }
  }

  _read(cb) {
    cb(null)
  }

  pipe(dest, cb) {
    this._readableState.updateNextTick()
    this._readableState.pipe(dest, cb)
    return dest
  }

  read() {
    this._readableState.updateNextTick()
    return this._readableState.read()
  }

  push(data) {
    this._readableState.updateNextTickIfOpen()
    return this._readableState.push(data)
  }

  unshift(data) {
    this._readableState.updateNextTickIfOpen()
    return this._readableState.unshift(data)
  }

  resume() {
    this._duplexState |= READ_RESUMED_READ_AHEAD
    this._readableState.updateNextTick()
    return this
  }

  pause() {
    this._duplexState &=
      this._readableState.readAhead === false ? READ_PAUSED_NO_READ_AHEAD : READ_PAUSED
    return this
  }

  static _fromAsyncIterator(ite, opts) {
    let destroy

    const rs = new Readable({
      ...opts,
      read(cb) {
        ite.next().then(push).then(cb.bind(null, null)).catch(cb)
      },
      predestroy() {
        destroy = ite.return()
      },
      destroy(cb) {
        if (!destroy) return cb(null)
        destroy.then(cb.bind(null, null)).catch(cb)
      }
    })

    return rs

    function push(data) {
      if (data.done) rs.push(null)
      else rs.push(data.value)
    }
  }

  static from(data, opts) {
    if (isReadStreamx(data)) return data
    if (data[asyncIterator]) return this._fromAsyncIterator(data[asyncIterator](), opts)
    if (!Array.isArray(data)) data = data === undefined ? [] : [data]

    let i = 0
    return new Readable({
      ...opts,
      read(cb) {
        this.push(i === data.length ? null : data[i++])
        cb(null)
      }
    })
  }

  static isBackpressured(rs) {
    return (
      (rs._duplexState & READ_BACKPRESSURE_STATUS) !== 0 ||
      rs._readableState.buffered >= rs._readableState.highWaterMark
    )
  }

  static isPaused(rs) {
    return (rs._duplexState & READ_RESUMED) === 0
  }

  [asyncIterator]() {
    const stream = this

    let error = null
    let promiseResolve = null
    let promiseReject = null

    this.on('error', (err) => {
      error = err
    })
    this.on('readable', onreadable)
    this.on('close', onclose)

    return {
      [asyncIterator]() {
        return this
      },
      next() {
        return new Promise(function (resolve, reject) {
          promiseResolve = resolve
          promiseReject = reject
          const data = stream.read()
          if (data !== null) ondata(data)
          else if ((stream._duplexState & DESTROYED) !== 0) ondata(null)
        })
      },
      return() {
        return destroy(null)
      },
      throw(err) {
        return destroy(err)
      }
    }

    function onreadable() {
      if (promiseResolve !== null) ondata(stream.read())
    }

    function onclose() {
      if (promiseResolve !== null) ondata(null)
    }

    function ondata(data) {
      if (promiseReject === null) return
      if (error) {
        promiseReject(error)
      } else if (data === null && (stream._duplexState & READ_DONE) === 0) {
        promiseReject(StreamError.STREAM_DESTROYED())
      } else {
        promiseResolve({ value: data, done: data === null })
      }
      promiseReject = promiseResolve = null
    }

    function destroy(err) {
      stream.destroy(err)
      return new Promise((resolve, reject) => {
        if (stream._duplexState & DESTROYED) return resolve({ value: undefined, done: true })
        stream.once('close', function () {
          if (err) reject(err)
          else resolve({ value: undefined, done: true })
        })
      })
    }
  }
}

class Writable extends Stream {
  constructor(opts) {
    super(opts)

    this._duplexState |= OPENING | READ_DONE
    this._writableState = new WritableState(this, opts)

    if (opts) {
      if (opts.writev) this._writev = opts.writev
      if (opts.write) this._write = opts.write
      if (opts.final) this._final = opts.final
      if (opts.eagerOpen) this._writableState.updateNextTick()
    }
  }

  cork() {
    this._duplexState |= WRITE_CORKED
  }

  uncork() {
    this._duplexState &= WRITE_NOT_CORKED
    this._writableState.updateNextTick()
  }

  _writev(batch, cb) {
    cb(null)
  }

  _write(data, cb) {
    this._writableState.autoBatch(data, cb)
  }

  _final(cb) {
    cb(null)
  }

  static isBackpressured(ws) {
    return (ws._duplexState & WRITE_BACKPRESSURE_STATUS) !== 0
  }

  static drained(ws) {
    if (ws.destroyed) return Promise.resolve(false)

    const state = ws._writableState
    const pending = isWritev(ws) ? Math.min(1, state.queue.length) : state.queue.length
    const writes = pending + (ws._duplexState & WRITE_WRITING ? 1 : 0)
    if (writes === 0) return Promise.resolve(true)

    if (state.drains === null) state.drains = []
    return new Promise((resolve) => {
      state.drains.push({ writes, resolve })
    })
  }

  write(data) {
    this._writableState.updateNextTick()
    return this._writableState.push(data)
  }

  end(data) {
    this._writableState.updateNextTick()
    this._writableState.end(data)
    return this
  }
}

class Duplex extends Readable {
  // and Writable
  constructor(opts) {
    super(opts)

    this._duplexState = OPENING | (this._duplexState & READ_READ_AHEAD)
    this._writableState = new WritableState(this, opts)

    if (opts) {
      if (opts.writev) this._writev = opts.writev
      if (opts.write) this._write = opts.write
      if (opts.final) this._final = opts.final
    }
  }

  cork() {
    this._duplexState |= WRITE_CORKED
  }

  uncork() {
    this._duplexState &= WRITE_NOT_CORKED
    this._writableState.updateNextTick()
  }

  _writev(batch, cb) {
    cb(null)
  }

  _write(data, cb) {
    this._writableState.autoBatch(data, cb)
  }

  _final(cb) {
    cb(null)
  }

  write(data) {
    this._writableState.updateNextTick()
    return this._writableState.push(data)
  }

  end(data) {
    this._writableState.updateNextTick()
    this._writableState.end(data)
    return this
  }
}

class Transform extends Duplex {
  constructor(opts) {
    super(opts)
    this._transformState = new TransformState(this)

    if (opts) {
      if (opts.transform) this._transform = opts.transform
      if (opts.flush) this._flush = opts.flush
    }
  }

  _write(data, cb) {
    if (this._readableState.buffered >= this._readableState.highWaterMark) {
      this._transformState.data = data
    } else {
      this._transform(data, this._transformState.afterTransform)
    }
  }

  _read(cb) {
    if (this._transformState.data !== null) {
      const data = this._transformState.data
      this._transformState.data = null
      cb(null)
      this._transform(data, this._transformState.afterTransform)
    } else {
      cb(null)
    }
  }

  destroy(err) {
    super.destroy(err)
    if (this._transformState.data !== null) {
      this._transformState.data = null
      this._transformState.afterTransform()
    }
  }

  _transform(data, cb) {
    cb(null, data)
  }

  _flush(cb) {
    cb(null)
  }

  _final(cb) {
    this._transformState.afterFinal = cb
    this._flush(transformAfterFlush.bind(this))
  }
}

class PassThrough extends Transform {}

function transformAfterFlush(err, data) {
  const cb = this._transformState.afterFinal
  if (err) return cb(err)

  if (data !== null && data !== undefined) this.push(data)
  this.push(null)
  cb(null)
}

function pipelinePromise(...streams) {
  return new Promise((resolve, reject) => {
    return pipeline(...streams, (err) => {
      if (err) return reject(err)
      resolve()
    })
  })
}

function pipeline(stream, ...streams) {
  const all = Array.isArray(stream) ? [...stream, ...streams] : [stream, ...streams]
  const done = all.length && typeof all[all.length - 1] === 'function' ? all.pop() : null

  if (all.length < 2) throw StreamError.BAD_ARGUMENT('Pipeline requires at least 2 streams')

  let src = all[0]
  let dest = null
  let error = null

  for (let i = 1; i < all.length; i++) {
    dest = all[i]

    if (isStreamx(src)) {
      src.pipe(dest, onerror)
    } else {
      errorHandle(src, true, i > 1, onerror)
      src.pipe(dest)
    }

    src = dest
  }

  if (done) {
    let fin = false

    const autoDestroy =
      isStreamx(dest) || !!(dest._writableState && dest._writableState.autoDestroy)

    dest.on('error', (err) => {
      if (error === null) error = err
    })

    dest.on('finish', () => {
      fin = true
      if (!autoDestroy) done(error)
    })

    if (autoDestroy) {
      dest.on('close', () => done(error || (fin ? null : StreamError.PREMATURE_CLOSE())))
    }
  }

  return dest

  function errorHandle(s, rd, wr, onerror) {
    s.on('error', onerror)
    s.on('close', onclose)

    function onclose() {
      if (rd && s._readableState && !s._readableState.ended) {
        return onerror(StreamError.PREMATURE_CLOSE())
      }
      if (wr && s._writableState && !s._writableState.ended) {
        return onerror(StreamError.PREMATURE_CLOSE())
      }
    }
  }

  function onerror(err) {
    if (!err || error) return
    error = err

    for (const s of all) {
      s.destroy(err)
    }
  }
}

function echo(s) {
  return s
}

function isStream(stream) {
  return !!stream._readableState || !!stream._writableState
}

function isStreamx(stream) {
  return typeof stream._duplexState === 'number' && isStream(stream)
}

function isEnding(stream) {
  return !!stream._readableState && stream._readableState.ending
}

function isEnded(stream) {
  return !!stream._readableState && stream._readableState.ended
}

function isFinishing(stream) {
  return !!stream._writableState && stream._writableState.ending
}

function isFinished(stream) {
  return !!stream._writableState && stream._writableState.ended
}

function getStreamError(stream, opts = {}) {
  const err =
    (stream._readableState && stream._readableState.error) ||
    (stream._writableState && stream._writableState.error)

  // avoid implicit errors by default
  return !opts.all && StreamError.isStreamDestroyed(err) ? null : err
}

function isReadStreamx(stream) {
  return isStreamx(stream) && stream.readable
}

function isDisturbed(stream) {
  return (
    (stream._duplexState & OPENING) !== OPENING ||
    (stream._duplexState & DESTROYING) === DESTROYING ||
    (stream._duplexState & ACTIVE_OR_TICKING) !== 0
  )
}

function isTypedArray(data) {
  return typeof data === 'object' && data !== null && typeof data.byteLength === 'number'
}

function defaultByteLength(data) {
  return isTypedArray(data) ? data.byteLength : 1024
}

function noop() {}

function abort() {
  this.destroy(StreamError.ABORTED())
}

function isWritev(s) {
  return s._writev !== Writable.prototype._writev && s._writev !== Duplex.prototype._writev
}

module.exports = {
  pipeline,
  pipelinePromise,
  isStream,
  isStreamx,
  isEnding,
  isEnded,
  isFinishing,
  isFinished,
  isDisturbed,
  getStreamError,
  Stream,
  Writable,
  Readable,
  Duplex,
  Transform,
  // Export PassThrough for compatibility with Node.js core's stream module
  PassThrough
}
module.exports = class StreamError extends Error {
  constructor(msg, code, fn = StreamError) {
    super(msg)

    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  static isStreamDestroyed(err) {
    return err && err.code === 'STREAM_DESTROYED'
  }

  static isPrematureClose(err) {
    return err && err.code === 'PREMATURE_CLOSE'
  }

  static isAborted(err) {
    return err && err.code === 'ABORTED'
  }

  static isBadArgument(err) {
    return err && err.code === 'BAD_ARGUMENT'
  }

  get name() {
    return 'StreamError'
  }

  static STREAM_DESTROYED() {
    return new StreamError('Stream was destroyed', 'STREAM_DESTROYED', StreamError.STREAM_DESTROYED)
  }

  static PREMATURE_CLOSE(msg = 'Premature close') {
    return new StreamError(msg, 'PREMATURE_CLOSE', StreamError.PREMATURE_CLOSE)
  }

  static ABORTED() {
    return new StreamError('Stream aborted', 'ABORTED', StreamError.ABORTED)
  }

  static BAD_ARGUMENT(msg = 'Bad argument') {
    return new StreamError(msg, 'BAD_ARGUMENT', StreamError.BAD_ARGUMENT)
  }
}
{
  "name": "streamx",
  "version": "2.28.0",
  "description": "An iteration of the Node.js core streams with a series of improvements",
  "main": "index.js",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./errors": {
      "types": "./lib/errors.d.ts",
      "default": "./lib/errors"
    }
  },
  "dependencies": {
    "events-universal": "^1.0.0",
    "fast-fifo": "^1.3.2",
    "text-decoder": "^1.1.0"
  },
  "devDependencies": {
    "b4a": "^1.6.6",
    "brittle": "^3.1.1",
    "end-of-stream": "^1.4.4",
    "lunte": "^1.8.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "runtime.d.ts",
    "lib"
  ],
  "scripts": {
    "format": "prettier . --write",
    "test": "brittle test/all.js && brittle-bare test/all.js",
    "lint": "prettier . --check && lunte"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/streamx.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/streamx/issues"
  },
  "homepage": "https://github.com/mafintosh/streamx"
}
const { Readable } = require('streamx')

module.exports = function (s, forks = 2) {
  const streams = new Array(forks)
  const status = new Array(forks).fill(true)

  let ended = false

  for (let i = 0; i < forks; i++) {
    streams[i] = new Readable({
      read (cb) {
        const check = !status[i]
        status[i] = true
        if (check && allReadable()) s.resume()
        cb(null)
      }
    })
  }

  s.on('end', function () {
    ended = true
    for (const stream of streams) stream.push(null)
  })

  s.on('error', function (err) {
    for (const stream of streams) stream.destroy(err)
  })

  s.on('close', function () {
    if (ended) return
    for (const stream of streams) stream.destroy()
  })

  s.on('data', function (data) {
    let needsPause = false
    for (let i = 0; i < streams.length; i++) {
      if (!(status[i] = streams[i].push(data))) {
        needsPause = true
      }
    }
    if (needsPause) s.pause()
  })

  return streams

  function allReadable () {
    for (let j = 0; j < status.length; j++) {
      if (!status[j]) return false
    }
    return true
  }
}
{
  "name": "teex",
  "version": "1.0.1",
  "description": "Turn a readable stream into multiple readable streamx streams",
  "main": "index.js",
  "dependencies": {
    "streamx": "^2.12.5"
  },
  "devDependencies": {
    "standard": "^14.3.4",
    "tape": "^5.0.1"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/teex.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/teex/issues"
  },
  "homepage": "https://github.com/mafintosh/teex"
}
const PassThroughDecoder = require('./lib/pass-through-decoder')
const UTF8Decoder = require('./lib/utf8-decoder')

module.exports = class TextDecoder {
  constructor(encoding = 'utf8') {
    this.encoding = normalizeEncoding(encoding)

    switch (this.encoding) {
      case 'utf8':
        this.decoder = new UTF8Decoder()
        break
      case 'utf16le':
      case 'base64':
        throw new Error('Unsupported encoding: ' + this.encoding)
      default:
        this.decoder = new PassThroughDecoder(this.encoding)
    }
  }

  get remaining() {
    return this.decoder.remaining
  }

  push(data) {
    if (typeof data === 'string') return data
    return this.decoder.decode(data)
  }

  // For Node.js compatibility
  write(data) {
    return this.push(data)
  }

  end(data) {
    let result = ''
    if (data) result = this.push(data)
    result += this.decoder.flush()
    return result
  }
}

function normalizeEncoding(encoding) {
  encoding = encoding.toLowerCase()

  switch (encoding) {
    case 'utf8':
    case 'utf-8':
      return 'utf8'
    case 'ucs2':
    case 'ucs-2':
    case 'utf16le':
    case 'utf-16le':
      return 'utf16le'
    case 'latin1':
    case 'binary':
      return 'latin1'
    case 'base64':
    case 'ascii':
    case 'hex':
      return encoding
    default:
      throw new Error('Unknown encoding: ' + encoding)
  }
}
const b4a = require('b4a')

module.exports = class PassThroughDecoder {
  constructor(encoding) {
    this.encoding = encoding
  }

  get remaining() {
    return 0
  }

  decode(data) {
    return b4a.toString(data, this.encoding)
  }

  flush() {
    return ''
  }
}
const b4a = require('b4a')

/**
 * https://encoding.spec.whatwg.org/#utf-8-decoder
 */
module.exports = class UTF8Decoder {
  constructor() {
    this._reset()
  }

  get remaining() {
    return this.bytesSeen
  }

  decode(data) {
    if (data.byteLength === 0) return ''

    if (this.bytesNeeded === 0 && trailingIncomplete(data, 0) === 0) {
      this.bytesSeen = trailingBytesSeen(data)
      return b4a.toString(data, 'utf8')
    }

    let result = ''
    let start = 0

    if (this.bytesNeeded > 0) {
      while (start < data.byteLength) {
        const byte = data[start]

        if (byte < this.lowerBoundary || byte > this.upperBoundary) {
          result += '\ufffd'
          this._reset()
          break
        }

        this.lowerBoundary = 0x80
        this.upperBoundary = 0xbf
        this.codePoint = (this.codePoint << 6) | (byte & 0x3f)
        this.bytesSeen++
        start++

        if (this.bytesSeen === this.bytesNeeded) {
          result += String.fromCodePoint(this.codePoint)
          this._reset()
          break
        }
      }

      if (this.bytesNeeded > 0) return result
    }

    const trailing = trailingIncomplete(data, start)
    const end = data.byteLength - trailing

    if (end > start) result += b4a.toString(data, 'utf8', start, end)

    for (let i = end; i < data.byteLength; i++) {
      const byte = data[i]

      if (this.bytesNeeded === 0) {
        if (byte <= 0x7f) {
          this.bytesSeen = 0
          result += String.fromCharCode(byte)
        } else if (byte >= 0xc2 && byte <= 0xdf) {
          this.bytesNeeded = 2
          this.bytesSeen = 1
          this.codePoint = byte & 0x1f
        } else if (byte >= 0xe0 && byte <= 0xef) {
          if (byte === 0xe0) this.lowerBoundary = 0xa0
          else if (byte === 0xed) this.upperBoundary = 0x9f
          this.bytesNeeded = 3
          this.bytesSeen = 1
          this.codePoint = byte & 0xf
        } else if (byte >= 0xf0 && byte <= 0xf4) {
          if (byte === 0xf0) this.lowerBoundary = 0x90
          else if (byte === 0xf4) this.upperBoundary = 0x8f
          this.bytesNeeded = 4
          this.bytesSeen = 1
          this.codePoint = byte & 0x7
        } else {
          this.bytesSeen = 1
          result += '\ufffd'
        }

        continue
      }

      if (byte < this.lowerBoundary || byte > this.upperBoundary) {
        result += '\ufffd'
        i--
        this._reset()

        continue
      }

      this.lowerBoundary = 0x80
      this.upperBoundary = 0xbf

      this.codePoint = (this.codePoint << 6) | (byte & 0x3f)
      this.bytesSeen++

      if (this.bytesSeen === this.bytesNeeded) {
        result += String.fromCodePoint(this.codePoint)
        this._reset()
      }
    }

    return result
  }

  flush() {
    const result = this.bytesNeeded > 0 ? '\ufffd' : ''
    this._reset()
    return result
  }

  _reset() {
    this.codePoint = 0
    this.bytesNeeded = 0
    this.bytesSeen = 0
    this.lowerBoundary = 0x80
    this.upperBoundary = 0xbf
  }
}

function trailingIncomplete(data, start) {
  const len = data.byteLength
  if (len <= start) return 0

  const limit = Math.max(start, len - 4)

  let i = len - 1
  while (i > limit && (data[i] & 0xc0) === 0x80) i--

  if (i < start) return 0

  const byte = data[i]

  let needed
  if (byte <= 0x7f) return 0
  if (byte >= 0xc2 && byte <= 0xdf) needed = 2
  else if (byte >= 0xe0 && byte <= 0xef) needed = 3
  else if (byte >= 0xf0 && byte <= 0xf4) needed = 4
  else return 0

  const available = len - i
  return available < needed ? available : 0
}

function trailingBytesSeen(data) {
  const len = data.byteLength
  if (len === 0) return 0

  const last = data[len - 1]

  if (last <= 0x7f) return 0
  if ((last & 0xc0) !== 0x80) return 1

  const limit = Math.max(0, len - 4)

  let i = len - 2
  while (i >= limit && (data[i] & 0xc0) === 0x80) i--

  if (i < 0) return 1

  const first = data[i]

  let needed
  if (first >= 0xc2 && first <= 0xdf) needed = 2
  else if (first >= 0xe0 && first <= 0xef) needed = 3
  else if (first >= 0xf0 && first <= 0xf4) needed = 4
  else return 1

  if (len - i !== needed) return 1

  if (needed >= 3) {
    const second = data[i + 1]
    if (first === 0xe0 && second < 0xa0) return 1
    if (first === 0xed && second > 0x9f) return 1
    if (first === 0xf0 && second < 0x90) return 1
    if (first === 0xf4 && second > 0x8f) return 1
  }

  return 0
}
{
  "name": "text-decoder",
  "version": "1.2.7",
  "description": "Streaming text decoder that preserves multibyte Unicode characters",
  "exports": {
    "./package": "./package.json",
    ".": "./index.js"
  },
  "files": [
    "index.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/text-decoder.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/text-decoder/issues"
  },
  "homepage": "https://github.com/holepunchto/text-decoder#readme",
  "dependencies": {
    "b4a": "^1.6.4"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  }
}
module.exports = class TimerBrowser {
  constructor (ms, fn, ctx = null, interval = false) {
    this.ms = ms
    this.ontimeout = fn
    this.context = ctx || null
    this.interval = interval
    this.done = false

    this._timer = interval
      ? setInterval(callInterval, ms, this)
      : setTimeout(callTimeout, ms, this)
  }

  unref () {}

  ref () {}

  refresh () {
    if (this.done) return

    if (this.interval) {
      clearInterval(this._timer)
      this._timer = setInterval(callInterval, this.ms, this)
    } else {
      clearTimeout(this._timer)
      this._timer = setTimeout(callTimeout, this.ms, this)
    }
  }

  destroy () {
    this.done = true
    this.ontimeout = null

    if (this.interval) clearInterval(this._timer)
    else clearTimeout(this._timer)
  }

  static once (ms, fn, ctx) {
    return new this(ms, fn, ctx, false)
  }

  static on (ms, fn, ctx) {
    return new this(ms, fn, ctx, true)
  }
}

function callTimeout (self) {
  self.done = true
  self.ontimeout.call(self.context)
}

function callInterval (self) {
  self.ontimeout.call(self.context)
}
module.exports = isNode()
  ? require('./node')
  : require('./browser')

function isNode () {
  const to = setTimeout(function () {}, 1000)
  clearTimeout(to)
  return !!to.refresh
}
module.exports = class Timer {
  constructor (ms, fn, ctx = null, interval = false) {
    this.ms = ms
    this.ontimeout = fn
    this.context = ctx
    this.interval = interval
    this.done = false

    this._timer = interval
      ? setInterval(callInterval, ms, this)
      : setTimeout(callTimeout, ms, this)
  }

  unref () {
    this._timer.unref()
  }

  ref () {
    this._timer.ref()
  }

  refresh () {
    if (this.done !== true) this._timer.refresh()
  }

  destroy () {
    this.done = true
    this.ontimeout = null
    if (this.interval) clearInterval(this._timer)
    else clearTimeout(this._timer)
  }

  static once (ms, fn, ctx) {
    return new this(ms, fn, ctx, false)
  }

  static on (ms, fn, ctx) {
    return new this(ms, fn, ctx, true)
  }
}

function callTimeout (self) {
  self.done = true
  self.ontimeout.call(self.context)
}

function callInterval (self) {
  self.ontimeout.call(self.context)
}
{
  "name": "timeout-refresh",
  "version": "2.0.1",
  "description": "Efficiently refresh a timer",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^16.0.4",
    "tape": "^5.5.2"
  },
  "browser": "./browser.js",
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/timeout-refresh.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/timeout-refresh/issues"
  },
  "homepage": "https://github.com/mafintosh/timeout-refresh"
}
const b4a = require('b4a')

unslab.all = all
unslab.is = is

module.exports = unslab

function unslab (buf) {
  if (buf === null || buf.buffer.byteLength === buf.byteLength) return buf
  const copy = b4a.allocUnsafeSlow(buf.byteLength)
  copy.set(buf, 0)
  return copy
}

function is (buf) {
  return buf.buffer.byteLength !== buf.byteLength
}

function all (list) {
  let size = 0
  for (let i = 0; i < list.length; i++) {
    const buf = list[i]
    size += buf === null || buf.buffer.byteLength === buf.byteLength ? 0 : buf.byteLength
  }

  const copy = b4a.allocUnsafeSlow(size)
  const result = new Array(list.length)

  let offset = 0
  for (let i = 0; i < list.length; i++) {
    let buf = list[i]

    if (buf !== null && buf.buffer.byteLength !== buf.byteLength) {
      copy.set(buf, offset)
      buf = copy.subarray(offset, offset += buf.byteLength)
    }

    result[i] = buf
  }

  return result
}
{
  "name": "unslab",
  "version": "1.3.0",
  "description": "Unslab some slab'ed buffers",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.6.6"
  },
  "devDependencies": {
    "brittle": "^3.5.2",
    "standard": "^17.1.0"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/unslab.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/unslab/issues"
  },
  "homepage": "https://github.com/holepunchto/unslab"
}
module.exports = read

var MSB = 0x80
  , REST = 0x7F

function read(buf, offset) {
  var res    = 0
    , offset = offset || 0
    , shift  = 0
    , counter = offset
    , b
    , l = buf.length

  do {
    if (counter >= l) {
      read.bytes = 0
      throw new RangeError('Could not decode varint')
    }
    b = buf[counter++]
    res += shift < 28
      ? (b & REST) << shift
      : (b & REST) * Math.pow(2, shift)
    shift += 7
  } while (b >= MSB)

  read.bytes = counter - offset

  return res
}
module.exports = encode

var MSB = 0x80
  , REST = 0x7F
  , MSBALL = ~REST
  , INT = Math.pow(2, 31)

function encode(num, out, offset) {
  out = out || []
  offset = offset || 0
  var oldOffset = offset

  while(num >= INT) {
    out[offset++] = (num & 0xFF) | MSB
    num /= 128
  }
  while(num & MSBALL) {
    out[offset++] = (num & 0xFF) | MSB
    num >>>= 7
  }
  out[offset] = num | 0
  
  encode.bytes = offset - oldOffset + 1
  
  return out
}
module.exports = {
    encode: require('./encode.js')
  , decode: require('./decode.js')
  , encodingLength: require('./length.js')
}

var N1 = Math.pow(2,  7)
var N2 = Math.pow(2, 14)
var N3 = Math.pow(2, 21)
var N4 = Math.pow(2, 28)
var N5 = Math.pow(2, 35)
var N6 = Math.pow(2, 42)
var N7 = Math.pow(2, 49)
var N8 = Math.pow(2, 56)
var N9 = Math.pow(2, 63)

module.exports = function (value) {
  return (
    value < N1 ? 1
  : value < N2 ? 2
  : value < N3 ? 3
  : value < N4 ? 4
  : value < N5 ? 5
  : value < N6 ? 6
  : value < N7 ? 7
  : value < N8 ? 8
  : value < N9 ? 9
  :              10
  )
}
{
  "name": "varint",
  "version": "5.0.0",
  "description": "protobuf-style varint bytes - use msb to create integer values of varying sizes",
  "main": "index.js",
  "scripts": {
    "test": "node test.js"
  },
  "repository": {
    "type": "git",
    "url": "git://github.com/chrisdickinson/varint.git"
  },
  "keywords": [
    "varint",
    "protobuf",
    "encode",
    "decode"
  ],
  "author": "Chris Dickinson <chris@neversaw.us>",
  "license": "MIT",
  "devDependencies": {
    "tape": "~2.12.3"
  }
}
const { runtime, platform, arch, version } =
  typeof Bare !== 'undefined'
    ? {
        runtime: 'bare',
        platform: global.Bare.platform,
        arch: global.Bare.arch,
        version: global.Bare.version
      }
    : typeof process !== 'undefined'
      ? {
          runtime: 'node',
          platform: global.process.platform,
          arch: global.process.arch,
          version: global.process.version
        }
      : typeof Window !== 'undefined'
        ? { runtime: 'browser', platform: 'unknown', arch: 'unknown', version: 'unknown' }
        : { runtime: 'unknown', platform: 'unknown', arch: 'unknown', version: 'unknown' }

exports.runtime = runtime
exports.version = version
exports.platform = platform
exports.arch = arch
exports.isBare = runtime === 'bare'
exports.isBareKit = exports.isBare && typeof BareKit !== 'undefined'
exports.isPear = typeof Pear !== 'undefined'
exports.isNode = runtime === 'node'
exports.isBrowser = runtime === 'browser'
exports.isWindows = platform === 'win32'
exports.isLinux = platform === 'linux'
exports.isMac = platform === 'darwin'
exports.isIOS = platform === 'ios' || platform === 'ios-simulator'
exports.isAndroid = platform === 'android'
exports.isElectron = typeof process !== 'undefined' && !!global.process.versions?.electron
exports.isElectronRenderer = exports.isElectron && global.process.type === 'renderer'
exports.isElectronWorker = exports.isElectron && global.process.type === 'worker'
{
  "name": "which-runtime",
  "version": "1.4.0",
  "description": "Detect if you are in Bare or Node and which os etc",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte .",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/which-runtime.git"
  },
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/which-runtime/issues"
  },
  "homepage": "https://github.com/holepunchto/which-runtime",
  "devDependencies": {
    "brittle": "^3.0.0",
    "lunte": "^1.4.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = class MaxCache {
  constructor({ maxSize, maxAge, createMap, ongc }) {
    this.maxSize = maxSize
    this.maxAge = maxAge
    this.ongc = ongc || null

    this._createMap = createMap || defaultCreateMap
    this._latest = this._createMap()
    this._oldest = this._createMap()
    this._retained = this._createMap()
    this._gced = false
    this._interval = null

    if (this.maxAge > 0 && this.maxAge < Infinity) {
      const tick = Math.ceil((2 / 3) * this.maxAge)
      this._interval = setInterval(this._gcAuto.bind(this), tick)
      if (this._interval.unref) this._interval.unref()
    }
  }

  get size() {
    return this._latest.size + this._oldest.size + this._retained.size
  }

  *[Symbol.iterator]() {
    for (const it of [this._latest, this._oldest, this._retained]) {
      yield* it
    }
  }

  *keys() {
    for (const it of [this._latest, this._oldest, this._retained]) {
      yield* it.keys()
    }
  }

  *values() {
    for (const it of [this._latest, this._oldest, this._retained]) {
      yield* it.values()
    }
  }

  destroy() {
    this.clear()
    clearInterval(this._interval)
    this._interval = null
  }

  clear() {
    this._gced = true
    this._latest.clear()
    this._oldest.clear()
    this._retained.clear()
  }

  set(k, v) {
    if (this._retained.has(k)) return this
    this._latest.set(k, v)
    this._oldest.delete(k) || this._retained.delete(k)
    if (this._latest.size >= this.maxSize) this._gc()
    return this
  }

  retain(k, v) {
    this._retained.set(k, v)
    this._latest.delete(k) || this._oldest.delete(k)
    return this
  }

  delete(k) {
    return (
      this._latest.delete(k) ||
      this._oldest.delete(k) ||
      this._retained.delete(k)
    )
  }

  has(k) {
    return this._latest.has(k) || this._oldest.has(k) || this._retained.has(k)
  }

  get(k) {
    if (this._latest.has(k)) {
      return this._latest.get(k)
    }

    if (this._oldest.has(k)) {
      const v = this._oldest.get(k)
      this._latest.set(k, v)
      this._oldest.delete(k)
      return v
    }

    if (this._retained.has(k)) {
      return this._retained.get(k)
    }

    return null
  }

  _gcAuto() {
    if (!this._gced) this._gc()
    this._gced = false
  }

  _gc() {
    this._gced = true
    if (this.ongc !== null && this._oldest.size > 0) this.ongc(this._oldest)
    this._oldest = this._latest
    this._latest = this._createMap()
  }
}

function defaultCreateMap() {
  return new Map()
}
{
  "name": "xache",
  "version": "1.3.0",
  "description": "Yet another auto expiring, max sizable cache",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "devDependencies": {
    "brittle": "^3.3.2",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "test": "prettier --check . && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/xache.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/xache/issues"
  },
  "homepage": "https://github.com/mafintosh/xache"
}
const b4a = require('b4a')

const ALPHABET = 'ybndrfg8ejkmcpqxot1uwisza345h769'
const MIN = 0x31 // 1
const MAX = 0x7a // z
const REVERSE = new Int8Array(1 + MAX - MIN)

REVERSE.fill(-1)

for (let i = 0; i < ALPHABET.length; i++) {
  const v = ALPHABET.charCodeAt(i) - MIN
  REVERSE[v] = i
}

exports.encode = encode
exports.decode = decode
exports.ALPHABET = ALPHABET

function decode (s, out) {
  let pb = 0
  let ps = 0

  const r = s.length & 7
  const q = (s.length - r) / 8

  if (!out) out = b4a.allocUnsafe(Math.ceil(s.length * 5 / 8))

  // 0 5 2 7 4 1 6 3 (+5 mod 8)
  for (let i = 0; i < q; i++) {
    const a = quintet(s, ps++)
    const b = quintet(s, ps++)
    const c = quintet(s, ps++)
    const d = quintet(s, ps++)
    const e = quintet(s, ps++)
    const f = quintet(s, ps++)
    const g = quintet(s, ps++)
    const h = quintet(s, ps++)

    out[pb++] = (a << 3) | (b >>> 2)
    out[pb++] = ((b & 0b11) << 6) | (c << 1) | (d >>> 4)
    out[pb++] = ((d & 0b1111) << 4) | (e >>> 1)
    out[pb++] = ((e & 0b1) << 7) | (f << 2) | (g >>> 3)
    out[pb++] = ((g & 0b111) << 5) | h
  }

  if (r === 0) return out.subarray(0, pb)

  const a = quintet(s, ps++)
  const b = quintet(s, ps++)

  out[pb++] = (a << 3) | (b >>> 2)

  if (r <= 2) return out.subarray(0, pb)

  const c = quintet(s, ps++)
  const d = quintet(s, ps++)

  out[pb++] = ((b & 0b11) << 6) | (c << 1) | (d >>> 4)

  if (r <= 4) return out.subarray(0, pb)

  const e = quintet(s, ps++)

  out[pb++] = ((d & 0b1111) << 4) | (e >>> 1)

  if (r <= 5) return out.subarray(0, pb)

  const f = quintet(s, ps++)
  const g = quintet(s, ps++)

  out[pb++] = ((e & 0b1) << 7) | (f << 2) | (g >>> 3)

  if (r <= 7) return out.subarray(0, pb)

  const h = quintet(s, ps++)

  out[pb++] = ((g & 0b111) << 5) | h

  return out.subarray(0, pb)
}

function encode (buf) {
  if (typeof buf === 'string') buf = b4a.from(buf)

  const max = buf.byteLength * 8

  let s = ''

  for (let p = 0; p < max; p += 5) {
    const i = p >>> 3
    const j = p & 7

    if (j <= 3) {
      s += ALPHABET[(buf[i] >>> (3 - j)) & 0b11111]
      continue
    }

    const of = j - 3
    const h = (buf[i] << of) & 0b11111
    const l = (i >= buf.byteLength ? 0 : buf[i + 1]) >>> (8 - of)

    s += ALPHABET[h | l]
  }

  return s
}

function quintet (s, i) {
  if (i > s.length) {
    return 0
  }

  const v = s.charCodeAt(i)

  if (v < MIN || v > MAX) {
    throw Error('Invalid character in base32 input: "' + s[i] + '" at position ' + i)
  }

  const bits = REVERSE[v - MIN]

  if (bits === -1) {
    throw Error('Invalid character in base32 input: "' + s[i] + '" at position ' + i)
  }

  return bits
}
{
  "name": "z32",
  "version": "1.1.0",
  "description": "Encode & decode z-base32",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.5.3"
  },
  "devDependencies": {
    "base-x": "^4.0.0",
    "base32": "0.0.7",
    "brittle": "^3.1.3",
    "nanobench": "^3.0.0",
    "rfc4648": "^1.5.2",
    "standard": "^17.0.0"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/z32.git"
  },
  "scripts": {
    "test": "standard && brittle test.js",
    "bench": "node benchmark.js"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/z32/issues"
  },
  "homepage": "https://github.com/mafintosh/z32"
}
{
  "name": "atproto-store",
  "version": "0.0.25",
  "description": "Holepunch-native atproto repo store — records in a classic Hyperbee (collection/rkey -> DAG-CBOR). The P2P home; the atproto-repo module is the bridge serializer over it.",
  "type": "module",
  "main": "lib/repo-store.js",
  "scripts": {
    "test": "brittle-node test/*.test.js"
  },
  "dependencies": {
    "atproto-repo": "file:../atproto-repo",
    "@ipld/dag-cbor": "^9.2.1",
    "b4a": "^1.6.0",
    "corestore": "^7.4.0",
    "hyperbee": "^2.20.0",
    "random-access-memory": "^6.2.0",
    "bare-fs": "^4.7.3",
    "bare-path": "^3.0.1"
  },
  "devDependencies": {
    "brittle": "^4.0.2"
  },
  "imports": {
    "#node:fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "#node:path": {
      "bare": "bare-path",
      "default": "path"
    }
  },
  "overrides": {
    "rocksdb-native": "3.17.2",
    "hypercore-storage": "3.2.0"
  }
}
const c = require('compact-encoding')
const IndexEncoder = require('index-encoder')

const Checkout = {
  preencode(state, m) {
    c.fixed32.preencode(state, m.key)
    c.uint.preencode(state, m.length)
  },
  encode(state, m) {
    c.fixed32.encode(state, m.key)
    c.uint.encode(state, m.length)
  },
  decode(state) {
    return {
      key: c.fixed32.decode(state),
      length: c.uint.decode(state)
    }
  }
}

const Clock = c.array(Checkout)

const IndexCheckpoint = {
  preencode(state, m) {
    c.fixed64.preencode(state, m.signature)
    c.uint.preencode(state, m.length)
  },
  encode(state, m) {
    c.fixed64.encode(state, m.signature)
    c.uint.encode(state, m.length)
  },
  decode(state) {
    return {
      signature: c.fixed64.decode(state),
      length: c.uint.decode(state)
    }
  }
}

const KeyV0 = {
  preencode(state, m) {
    c.fixed32.preencode(state, m.key)
  },
  encode(state, m) {
    c.fixed32.encode(state, m.key)
  },
  decode(state) {
    return {
      key: c.fixed32.decode(state),
      length: -1
    }
  }
}

const KeysV0 = c.array(KeyV0)

const WakeupV0 = {
  preencode(state, m) {
    c.uint.preencode(state, 0) // version
    c.uint.preencode(state, m.type)

    if (m.type === 1) {
      KeysV0.preencode(state, m.writers)
    }
  },
  encode(state, m) {
    c.uint.encode(state, 0) // version
    c.uint.encode(state, m.type)

    if (m.type === 1) {
      KeysV0.encode(state, m.writers)
    }
  },
  decode(state) {
    const v = c.uint.decode(state)
    if (v !== 0) throw new Error('Unsupported version: ' + v)

    const type = c.uint.decode(state)
    const m = { version: 0, type, writers: null }

    if (m.type === 1) {
      m.writers = KeysV0.decode(state)
    }

    return m
  }
}

const Wakeup = {
  preencode(state, m) {
    if (m.version === 0) return WakeupV0.preencode(state, m)

    c.uint.preencode(state, 1) // version
    c.uint.preencode(state, m.type)

    if (m.type === 1) {
      Clock.preencode(state, m.writers)
    }
  },
  encode(state, m) {
    if (m.version === 0) return WakeupV0.encode(state, m)

    c.uint.encode(state, 1) // version
    c.uint.encode(state, m.type)

    if (m.type === 1) {
      Clock.encode(state, m.writers)
    }
  },
  decode(state) {
    const start = state.start
    const v = c.uint.decode(state)

    if (v > 1) throw new Error('Unsupported version: ' + v)

    if (v === 0) {
      state.start = start
      return WakeupV0.decode(state)
    }

    const type = c.uint.decode(state)
    const m = { version: 1, type, writers: null }

    if (m.type === 1) {
      m.writers = Clock.decode(state)
    }

    return m
  }
}

const BootRecordV0 = {
  preencode() {
    throw new Error('version 0 records cannot be encoded')
  },
  encode() {
    throw new Error('version 0 records cannot be encoded')
  },
  decode(state) {
    c.uint.decode(state)
    const indexed = Checkout.decode(state)
    const heads = Clock.decode(state)

    // one cause initial recover is not ff recovery
    return {
      version: 0,
      key: indexed.key,
      systemLength: indexed.length,
      indexersUpdated: false,
      fastForwarding: false,
      recoveries: 1,
      migrating: false,
      heads
    }
  }
}

const Checkpointer = {
  preencode(state, idx) {
    c.uint.preencode(state, idx.checkpointer)
    if (idx.checkpoint !== null) IndexCheckpoint.preencode(state, idx.checkpoint)
  },
  encode(state, idx) {
    c.uint.encode(state, idx.checkpointer)
    if (idx.checkpoint !== null) IndexCheckpoint.encode(state, idx.checkpoint)
  },
  decode(state) {
    const checkpointer = c.uint.decode(state)
    const checkpoint = checkpointer ? null : IndexCheckpoint.decode(state)

    return {
      checkpointer,
      checkpoint
    }
  }
}

const CheckpointerArray = c.array(Checkpointer)

const Indexer = {
  preencode(state, m) {
    c.uint.preencode(state, m.signature)
    c.fixed32.preencode(state, m.namespace)
    c.fixed32.preencode(state, m.publicKey)
  },
  encode(state, m) {
    c.uint.encode(state, m.signature)
    c.fixed32.encode(state, m.namespace)
    c.fixed32.encode(state, m.publicKey)
  },
  decode(state) {
    return {
      signature: c.uint.decode(state),
      namespace: c.fixed32.decode(state),
      publicKey: c.fixed32.decode(state)
    }
  }
}

const Indexers = c.array(Indexer)

const DigestV0 = {
  preencode(state, m) {
    c.uint.preencode(state, m.pointer)
    if (m.pointer === 0) {
      Indexers.preencode(state, m.indexers)
    }
  },
  encode(state, m) {
    c.uint.encode(state, m.pointer)
    if (m.pointer === 0) {
      Indexers.encode(state, m.indexers)
    }
  },
  decode(state) {
    const pointer = c.uint.decode(state)
    return {
      pointer,
      indexers: pointer === 0 ? Indexers.decode(state) : null
    }
  }
}

const Digest = {
  preencode(state, m) {
    c.uint.preencode(state, m.pointer)
    if (m.pointer === 0) {
      c.fixed32.preencode(state, m.key)
    }
  },
  encode(state, m) {
    c.uint.encode(state, m.pointer)
    if (m.pointer === 0) {
      c.fixed32.encode(state, m.key)
    }
  },
  decode(state) {
    const pointer = c.uint.decode(state)
    return {
      pointer,
      key: pointer === 0 ? c.fixed32.decode(state) : null
    }
  }
}

const Node = {
  preencode(state, m) {
    Clock.preencode(state, m.heads)
    c.uint.preencode(state, m.batch)
    c.optionalBuffer.preencode(state, m.value)
  },
  encode(state, m) {
    Clock.encode(state, m.heads)
    c.uint.encode(state, m.batch)
    c.optionalBuffer.encode(state, m.value)
  },
  decode(state, m) {
    return {
      heads: Clock.decode(state),
      batch: c.uint.decode(state),
      value: c.optionalBuffer.decode(state)
    }
  }
}

const Additional = {
  preencode(state, m) {
    c.uint.preencode(state, m.pointer)
    if (m.pointer === 0) {
      AdditionalData.preencode(state, m.data)
    }
  },
  encode(state, m) {
    c.uint.encode(state, m.pointer)
    if (m.pointer === 0) {
      AdditionalData.encode(state, m.data)
    }
  },
  decode(state) {
    const pointer = c.uint.decode(state)
    return {
      pointer,
      data: pointer === 0 ? AdditionalData.decode(state) : null
    }
  }
}

const AdditionalData = {
  preencode(state, m) {
    c.uint.preencode(state, 0)
  },
  encode(state, m) {
    c.uint.encode(state, 0) // empty for now, for the future
  },
  decode(state) {
    const flags = c.uint.decode(state)
    return {
      encryptionId: flags & 1 ? c.fixed32.decode(state) : null, // to help validate the encryption key used
      abi: flags & 2 ? c.uint.decode(state) : 0
    }
  }
}

const OplogMessageV1 = {
  preencode(state, m) {
    throw new Error('Encoding not supported')
  },
  encode(state, m) {
    throw new Error('Encoding not supported')
  },
  decode(state) {
    c.uint.decode(state) // version
    const maxSupportedVersion = c.uint.decode(state)

    const flags = c.uint.decode(state)

    const isCheckpointer = (flags & 1) !== 0

    const chk = isCheckpointer ? CheckpointerArray.decode(state) : null
    const digest = isCheckpointer ? Digest.decode(state) : null

    const node = Node.decode(state)

    return {
      version: 1,
      maxSupportedVersion,
      digest,
      checkpoint: chk ? { system: chk[0], encryption: null, user: chk.slice(1) } : null,
      optimistic: (flags & 2) !== 0,
      node
    }
  }
}

const OplogMessageV0 = {
  preencode(state, m) {
    throw new Error('Encoding not supported')
  },
  encode(state, m) {
    throw new Error('Encoding not supported')
  },
  decode(state) {
    c.uint.decode(state) // version
    const flags = c.uint.decode(state)

    const isCheckpointer = (flags & 1) !== 0

    if (isCheckpointer) DigestV0.decode(state)
    const chk = isCheckpointer ? CheckpointerArray.decode(state) : null
    const node = Node.decode(state)
    Additional.decode(state)
    const maxSupportedVersion = state.start < state.end ? c.uint.decode(state) : 0

    return {
      version: 0,
      maxSupportedVersion,
      digest: null,
      checkpoint: chk ? { system: chk[0], encryption: null, user: chk.slice(1) } : null,
      optimistic: null,
      node
    }
  }
}

// prefix 0 is reserved for future manifest
const LINEARIZER_PREFIX = 1

const LinearizerKey = {
  preencode(state, seq) {
    IndexEncoder.UINT.preencode(state, LINEARIZER_PREFIX)
    IndexEncoder.UINT.preencode(state, seq)
  },
  encode(state, seq) {
    IndexEncoder.UINT.encode(state, LINEARIZER_PREFIX)
    IndexEncoder.UINT.encode(state, seq)
  },
  decode(state) {
    IndexEncoder.UINT.decode(state)
    return IndexEncoder.UINT.decode(state)
  }
}

function infoLegacyMap(info) {
  return {
    version: info.version,
    members: info.members,
    pendingIndexers: info.pendingIndexers,
    indexers: info.indexers,
    heads: info.heads,
    views: info.views,
    encryptionLength: 0,
    entropy: null
  }
}

module.exports = {
  Wakeup,
  BootRecordV0,
  OplogMessageV0,
  OplogMessageV1,
  LinearizerKey,
  infoLegacyMap
}
// This file is autogenerated by the hyperschema compiler
// Schema Version: 1
/* eslint-disable camelcase */
/* eslint-disable quotes */
/* eslint-disable space-before-function-paren */

const { c } = require('hyperschema/runtime')
const external0 = require('../../legacy.js')

const VERSION = 1

// eslint-disable-next-line no-unused-vars
let version = VERSION

// @autobase/checkout
const encoding0 = {
  preencode(state, m) {
    c.fixed32.preencode(state, m.key)
    c.uint.preencode(state, m.length)
  },
  encode(state, m) {
    c.fixed32.encode(state, m.key)
    c.uint.encode(state, m.length)
  },
  decode(state) {
    const r0 = c.fixed32.decode(state)
    const r1 = c.uint.decode(state)

    return {
      key: r0,
      length: r1
    }
  }
}

// @autobase/clock
const encoding1 = c.array(encoding0)

// @autobase/index-checkpoint
const encoding2 = {
  preencode(state, m) {
    c.fixed64.preencode(state, m.signature)
    c.uint.preencode(state, m.length)
  },
  encode(state, m) {
    c.fixed64.encode(state, m.signature)
    c.uint.encode(state, m.length)
  },
  decode(state) {
    const r0 = c.fixed64.decode(state)
    const r1 = c.uint.decode(state)

    return {
      signature: r0,
      length: r1
    }
  }
}

const encoding3 = external0.Wakeup

const encoding4 = external0.BootRecordV0

// @autobase/boot-record-raw
const encoding5 = {
  preencode(state, m) {
    c.fixed32.preencode(state, m.key)
    c.uint.preencode(state, m.systemLength)
    state.end++ // max flag is 4 so always one byte

    if (m.recoveries) c.uint.preencode(state, m.recoveries)
  },
  encode(state, m) {
    const flags = (m.indexersUpdated ? 1 : 0) | (m.fastForwarding ? 2 : 0) | (m.recoveries ? 4 : 0)

    c.fixed32.encode(state, m.key)
    c.uint.encode(state, m.systemLength)
    c.uint.encode(state, flags)

    if (m.recoveries) c.uint.encode(state, m.recoveries)
  },
  decode(state) {
    const v = c.uint.decode(state)
    const r0 = c.fixed32.decode(state)
    const r1 = c.uint.decode(state)
    const flags = c.uint.decode(state)

    return {
      version: v,
      key: r0,
      systemLength: r1,
      indexersUpdated: (flags & 1) !== 0,
      fastForwarding: (flags & 2) !== 0,
      recoveries: (flags & 4) !== 0 ? c.uint.decode(state) : 0
    }
  }
}

// @autobase/boot-record
const encoding6 = {
  preencode(state, m) {
    c.uint.preencode(state, m.version)
    switch (m.version) {
      case 0:
        encoding4.preencode(state, m)
        break
      case 1:
      case 2:
      case 3:
        encoding5.preencode(state, m)
        break
      default:
        throw new Error('Unsupported version')
    }
  },
  encode(state, m) {
    c.uint.encode(state, m.version)
    switch (m.version) {
      case 0:
        encoding4.encode(state, m)
        break
      case 1:
      case 2:
      case 3:
        encoding5.encode(state, m)
        break
      default:
        throw new Error('Unsupported version')
    }
  },
  decode(state) {
    const start = state.start
    const v = c.uint.decode(state)
    state.start = start
    switch (v) {
      case 0: {
        const decoded = encoding4.decode(state)
        return decoded
      }
      case 1:
      case 2:
      case 3: {
        const decoded = encoding5.decode(state)
        return decoded
      }
      default:
        throw new Error('Unsupported version')
    }
  }
}

// @autobase/checkpointer
const encoding7 = {
  preencode(state, m) {
    state.end++ // flags are fixed size

    if (m.checkpointer) c.uint.preencode(state, m.checkpointer)
    if (m.checkpoint) encoding2.preencode(state, m.checkpoint)
  },
  encode(state, m) {
    const flags = (m.checkpointer ? 1 : 0) | (m.checkpoint ? 2 : 0)

    c.uint8.encode(state, flags)

    if (m.checkpointer) c.uint.encode(state, m.checkpointer)
    if (m.checkpoint) encoding2.encode(state, m.checkpoint)
  },
  decode(state) {
    const flags = c.uint8.decode(state)

    return {
      checkpointer: (flags & 1) !== 0 ? c.uint.decode(state) : 0,
      checkpoint: (flags & 2) !== 0 ? encoding2.decode(state) : null
    }
  }
}

// @autobase/checkpoint.user
const encoding8_2 = c.array(encoding7)

// @autobase/checkpoint
const encoding8 = {
  preencode(state, m) {
    state.end++ // max flag is 4 so always one byte

    if (m.system) encoding7.preencode(state, m.system)
    if (m.encryption) encoding7.preencode(state, m.encryption)
    if (m.user) encoding8_2.preencode(state, m.user)
  },
  encode(state, m) {
    const flags = (m.system ? 1 : 0) | (m.encryption ? 2 : 0) | (m.user ? 4 : 0)

    c.uint.encode(state, flags)

    if (m.system) encoding7.encode(state, m.system)
    if (m.encryption) encoding7.encode(state, m.encryption)
    if (m.user) encoding8_2.encode(state, m.user)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      system: (flags & 1) !== 0 ? encoding7.decode(state) : null,
      encryption: (flags & 2) !== 0 ? encoding7.decode(state) : null,
      user: (flags & 4) !== 0 ? encoding8_2.decode(state) : null
    }
  }
}

// @autobase/digest
const encoding9 = {
  preencode(state, m) {
    state.end++ // max flag is 2 so always one byte

    if (m.pointer) c.uint.preencode(state, m.pointer)
    if (m.key) c.fixed32.preencode(state, m.key)
  },
  encode(state, m) {
    const flags = (m.pointer ? 1 : 0) | (m.key ? 2 : 0)

    c.uint.encode(state, flags)

    if (m.pointer) c.uint.encode(state, m.pointer)
    if (m.key) c.fixed32.encode(state, m.key)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      pointer: (flags & 1) !== 0 ? c.uint.decode(state) : 0,
      key: (flags & 2) !== 0 ? c.fixed32.decode(state) : null
    }
  }
}

// @autobase/node
const encoding10 = {
  preencode(state, m) {
    encoding1.preencode(state, m.heads)
    c.uint.preencode(state, m.batch)
    c.optionalBuffer.preencode(state, m.value)
  },
  encode(state, m) {
    encoding1.encode(state, m.heads)
    c.uint.encode(state, m.batch)
    c.optionalBuffer.encode(state, m.value)
  },
  decode(state) {
    const r0 = encoding1.decode(state)
    const r1 = c.uint.decode(state)
    const r2 = c.optionalBuffer.decode(state)

    return {
      heads: r0,
      batch: r1,
      value: r2
    }
  }
}

// @autobase/user-view-trace.blocks
const encoding11_1 = c.array(c.uint)

// @autobase/user-view-trace
const encoding11 = {
  preencode(state, m) {
    c.uint.preencode(state, m.view)
    encoding11_1.preencode(state, m.blocks)
  },
  encode(state, m) {
    c.uint.encode(state, m.view)
    encoding11_1.encode(state, m.blocks)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const r1 = encoding11_1.decode(state)

    return {
      view: r0,
      blocks: r1
    }
  }
}

// @autobase/trace.system
const encoding12_0 = encoding11_1
// @autobase/trace.encryption
const encoding12_1 = encoding11_1
// @autobase/trace.user
const encoding12_2 = c.array(encoding11)

// @autobase/trace
const encoding12 = {
  preencode(state, m) {
    encoding12_0.preencode(state, m.system)
    encoding12_1.preencode(state, m.encryption)
    encoding12_2.preencode(state, m.user)
  },
  encode(state, m) {
    encoding12_0.encode(state, m.system)
    encoding12_1.encode(state, m.encryption)
    encoding12_2.encode(state, m.user)
  },
  decode(state) {
    const r0 = encoding12_0.decode(state)
    const r1 = encoding12_1.decode(state)
    const r2 = encoding12_2.decode(state)

    return {
      system: r0,
      encryption: r1,
      user: r2
    }
  }
}

const encoding13 = external0.OplogMessageV0

const encoding14 = external0.OplogMessageV1

// @autobase/oplog-message-v2.checkpoint
const encoding15_1 = c.frame(encoding8)
// @autobase/oplog-message-v2.digest
const encoding15_2 = c.frame(encoding9)
// @autobase/oplog-message-v2.trace
const encoding15_4 = c.frame(encoding12)

// @autobase/oplog-message-v2
const encoding15 = {
  preencode(state, m) {
    encoding10.preencode(state, m.node)
    state.end++ // max flag is 8 so always one byte

    if (m.checkpoint) encoding15_1.preencode(state, m.checkpoint)
    if (m.digest) encoding15_2.preencode(state, m.digest)
    if (m.trace) encoding15_4.preencode(state, m.trace)
  },
  encode(state, m) {
    const flags =
      (m.checkpoint ? 1 : 0) | (m.digest ? 2 : 0) | (m.optimistic ? 4 : 0) | (m.trace ? 8 : 0)

    encoding10.encode(state, m.node)
    c.uint.encode(state, flags)

    if (m.checkpoint) encoding15_1.encode(state, m.checkpoint)
    if (m.digest) encoding15_2.encode(state, m.digest)
    if (m.trace) encoding15_4.encode(state, m.trace)
  },
  decode(state) {
    const v = c.uint.decode(state)
    const r0 = encoding10.decode(state)
    const flags = c.uint.decode(state)

    return {
      version: v,
      node: r0,
      checkpoint: (flags & 1) !== 0 ? encoding15_1.decode(state) : null,
      digest: (flags & 2) !== 0 ? encoding15_2.decode(state) : null,
      optimistic: (flags & 4) !== 0,
      trace: (flags & 8) !== 0 ? encoding15_4.decode(state) : null
    }
  }
}

// @autobase/oplog-message
const encoding16 = {
  preencode(state, m) {
    c.uint.preencode(state, m.version)
    switch (m.version) {
      case 0:
        encoding13.preencode(state, m)
        break
      case 1:
        encoding14.preencode(state, m)
        break
      case 2:
        encoding15.preencode(state, m)
        break
      default:
        throw new Error('Unsupported version')
    }
  },
  encode(state, m) {
    c.uint.encode(state, m.version)
    switch (m.version) {
      case 0:
        encoding13.encode(state, m)
        break
      case 1:
        encoding14.encode(state, m)
        break
      case 2:
        encoding15.encode(state, m)
        break
      default:
        throw new Error('Unsupported version')
    }
  },
  decode(state) {
    const start = state.start
    const v = c.uint.decode(state)
    state.start = start
    switch (v) {
      case 0: {
        const decoded = encoding13.decode(state)
        return decoded
      }
      case 1: {
        const decoded = encoding14.decode(state)
        return decoded
      }
      case 2: {
        const decoded = encoding15.decode(state)
        return decoded
      }
      default:
        throw new Error('Unsupported version')
    }
  }
}

// @autobase/info-v1.pendingIndexers
const encoding17_1 = c.array(c.fixed32)

// @autobase/info-v1
const encoding17 = {
  preencode(state, m) {
    c.uint.preencode(state, m.members)
    encoding17_1.preencode(state, m.pendingIndexers)
    encoding1.preencode(state, m.indexers)
    encoding1.preencode(state, m.heads)
    encoding1.preencode(state, m.views)
  },
  encode(state, m) {
    c.uint.encode(state, m.members)
    encoding17_1.encode(state, m.pendingIndexers)
    encoding1.encode(state, m.indexers)
    encoding1.encode(state, m.heads)
    encoding1.encode(state, m.views)
  },
  decode(state) {
    const v = c.uint.decode(state)
    const r0 = c.uint.decode(state)
    const r1 = encoding17_1.decode(state)
    const r2 = encoding1.decode(state)
    const r3 = encoding1.decode(state)
    const r4 = encoding1.decode(state)

    return {
      version: v,
      members: r0,
      pendingIndexers: r1,
      indexers: r2,
      heads: r3,
      views: r4
    }
  }
}

// @autobase/info-v2.pendingIndexers
const encoding18_1 = encoding17_1

// @autobase/info-v2
const encoding18 = {
  preencode(state, m) {
    c.uint.preencode(state, m.members)
    encoding18_1.preencode(state, m.pendingIndexers)
    encoding1.preencode(state, m.indexers)
    encoding1.preencode(state, m.heads)
    encoding1.preencode(state, m.views)
    c.uint.preencode(state, m.encryptionLength)
    state.end++ // max flag is 1 so always one byte

    if (m.entropy) c.fixed32.preencode(state, m.entropy)
  },
  encode(state, m) {
    const flags = m.entropy ? 1 : 0

    c.uint.encode(state, m.members)
    encoding18_1.encode(state, m.pendingIndexers)
    encoding1.encode(state, m.indexers)
    encoding1.encode(state, m.heads)
    encoding1.encode(state, m.views)
    c.uint.encode(state, m.encryptionLength)
    c.uint.encode(state, flags)

    if (m.entropy) c.fixed32.encode(state, m.entropy)
  },
  decode(state) {
    const v = c.uint.decode(state)
    const r0 = c.uint.decode(state)
    const r1 = encoding18_1.decode(state)
    const r2 = encoding1.decode(state)
    const r3 = encoding1.decode(state)
    const r4 = encoding1.decode(state)
    const r5 = c.uint.decode(state)
    const flags = c.uint.decode(state)

    return {
      version: v,
      members: r0,
      pendingIndexers: r1,
      indexers: r2,
      heads: r3,
      views: r4,
      encryptionLength: r5,
      entropy: (flags & 1) !== 0 ? c.fixed32.decode(state) : null
    }
  }
}

// @autobase/info
const encoding19 = {
  preencode(state, m) {
    c.uint.preencode(state, m.version)
    switch (m.version) {
      case 0:
      case 1:
        encoding17.preencode(state, m)
        break
      case 2:
        encoding18.preencode(state, m)
        break
      default:
        throw new Error('Unsupported version')
    }
  },
  encode(state, m) {
    c.uint.encode(state, m.version)
    switch (m.version) {
      case 0:
      case 1:
        encoding17.encode(state, m)
        break
      case 2:
        encoding18.encode(state, m)
        break
      default:
        throw new Error('Unsupported version')
    }
  },
  decode(state) {
    const start = state.start
    const v = c.uint.decode(state)
    state.start = start
    switch (v) {
      case 0:
      case 1: {
        const decoded = encoding17.decode(state)
        const map = external0.infoLegacyMap
        return map(decoded)
      }
      case 2: {
        const decoded = encoding18.decode(state)
        return decoded
      }
      default:
        throw new Error('Unsupported version')
    }
  }
}

// @autobase/member
const encoding20 = {
  preencode(state, m) {
    state.end++ // max flag is 2 so always one byte
    c.uint.preencode(state, m.length)
  },
  encode(state, m) {
    const flags = (m.isIndexer ? 1 : 0) | (m.isRemoved ? 2 : 0)

    c.uint.encode(state, flags)
    c.uint.encode(state, m.length)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      isIndexer: (flags & 1) !== 0,
      isRemoved: (flags & 2) !== 0,
      length: c.uint.decode(state)
    }
  }
}

const encoding21 = external0.LinearizerKey

// @autobase/linearizer-update
const encoding22 = {
  preencode(state, m) {
    c.fixed32.preencode(state, m.key)
    c.uint.preencode(state, m.length)
    c.uint.preencode(state, m.batch)
    c.uint.preencode(state, m.systemLength)
    state.end++ // max flag is 1 so always one byte
  },
  encode(state, m) {
    const flags = m.indexers ? 1 : 0

    c.fixed32.encode(state, m.key)
    c.uint.encode(state, m.length)
    c.uint.encode(state, m.batch)
    c.uint.encode(state, m.systemLength)
    c.uint.encode(state, flags)
  },
  decode(state) {
    const r0 = c.fixed32.decode(state)
    const r1 = c.uint.decode(state)
    const r2 = c.uint.decode(state)
    const r3 = c.uint.decode(state)
    const flags = c.uint.decode(state)

    return {
      key: r0,
      length: r1,
      batch: r2,
      systemLength: r3,
      indexers: (flags & 1) !== 0
    }
  }
}

// @autobase/encryption-descriptor
const encoding23 = {
  preencode(state, m) {
    c.uint.preencode(state, m.type)
    c.optionalBuffer.preencode(state, m.payload)
  },
  encode(state, m) {
    c.uint.encode(state, m.type)
    c.optionalBuffer.encode(state, m.payload)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const r1 = c.optionalBuffer.decode(state)

    return {
      type: r0,
      payload: r1
    }
  }
}

// @autobase/manifest-data
const encoding24 = {
  preencode(state, m) {
    c.uint.preencode(state, m.version)
    state.end++ // max flag is 2 so always one byte

    if (m.legacyBlocks) c.uint.preencode(state, m.legacyBlocks)
    if (m.namespace) c.fixed32.preencode(state, m.namespace)
  },
  encode(state, m) {
    const flags = (m.legacyBlocks ? 1 : 0) | (m.namespace ? 2 : 0)

    c.uint.encode(state, m.version)
    c.uint.encode(state, flags)

    if (m.legacyBlocks) c.uint.encode(state, m.legacyBlocks)
    if (m.namespace) c.fixed32.encode(state, m.namespace)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const flags = c.uint.decode(state)

    return {
      version: r0,
      legacyBlocks: (flags & 1) !== 0 ? c.uint.decode(state) : 0,
      namespace: (flags & 2) !== 0 ? c.fixed32.decode(state) : null
    }
  }
}

function setVersion(v) {
  version = v
}

function encode(name, value, v = VERSION) {
  version = v
  return c.encode(getEncoding(name), value)
}

function decode(name, buffer, v = VERSION) {
  version = v
  return c.decode(getEncoding(name), buffer)
}

function getEnum(name) {
  switch (name) {
    default:
      throw new Error('Enum not found ' + name)
  }
}

function getEncoding(name) {
  switch (name) {
    case '@autobase/checkout':
      return encoding0
    case '@autobase/clock':
      return encoding1
    case '@autobase/index-checkpoint':
      return encoding2
    case '@autobase/wakeup':
      return encoding3
    case '@autobase/boot-record-v0':
      return encoding4
    case '@autobase/boot-record-raw':
      return encoding5
    case '@autobase/boot-record':
      return encoding6
    case '@autobase/checkpointer':
      return encoding7
    case '@autobase/checkpoint':
      return encoding8
    case '@autobase/digest':
      return encoding9
    case '@autobase/node':
      return encoding10
    case '@autobase/user-view-trace':
      return encoding11
    case '@autobase/trace':
      return encoding12
    case '@autobase/oplog-message-v0':
      return encoding13
    case '@autobase/oplog-message-v1':
      return encoding14
    case '@autobase/oplog-message-v2':
      return encoding15
    case '@autobase/oplog-message':
      return encoding16
    case '@autobase/info-v1':
      return encoding17
    case '@autobase/info-v2':
      return encoding18
    case '@autobase/info':
      return encoding19
    case '@autobase/member':
      return encoding20
    case '@autobase/linearizer-key':
      return encoding21
    case '@autobase/linearizer-update':
      return encoding22
    case '@autobase/encryption-descriptor':
      return encoding23
    case '@autobase/manifest-data':
      return encoding24
    default:
      throw new Error('Encoder not found ' + name)
  }
}

function getStruct(name, v = VERSION) {
  const enc = getEncoding(name)
  return {
    preencode(state, m) {
      version = v
      enc.preencode(state, m)
    },
    encode(state, m) {
      version = v
      enc.encode(state, m)
    },
    decode(state) {
      version = v
      return enc.decode(state)
    }
  }
}

const resolveStruct = getStruct // compat

module.exports = {
  resolveStruct,
  getStruct,
  getEnum,
  getEncoding,
  encode,
  decode,
  setVersion,
  version
}
const b4a = require('b4a')
const ReadyResource = require('ready-resource')
const debounceify = require('debounceify')
const c = require('compact-encoding')
const safetyCatch = require('safety-catch')
const hypercoreId = require('hypercore-id-encoding')
const assert = require('nanoassert')
const SignalPromise = require('signal-promise')
const CoreCoupler = require('core-coupler')
const ProtomuxWakeup = require('protomux-wakeup')
const rrp = require('resolve-reject-promise')
const Hypercore = require('hypercore')
const ScopeLock = require('scope-lock')
const encryptionEncoding = require('encryption-encoding')

const LocalState = require('./lib/local-state.js')
const Linearizer = require('./lib/linearizer.js')
const SystemView = require('./lib/system.js')
const { EncryptionView } = require('./lib/encryption.js')
const UpdateChanges = require('./lib/updates.js')
const messages = require('./lib/messages.js')
const Timer = require('./lib/timer.js')
const Writer = require('./lib/writer.js')
const { encodeValue, decodeValue } = require('./lib/values.js')
const ActiveWriters = require('./lib/active-writers.js')
const AutoWakeup = require('./lib/wakeup.js')

const FastForward = require('./lib/fast-forward.js')
const AutoStore = require('./lib/store.js')
const ApplyState = require('./lib/apply-state.js')
const AppendBatch = require('./lib/append-batch.js')
const { PublicApplyCalls } = require('./lib/apply-calls.js')
const boot = require('./lib/boot.js')
const { MAX_AUTOBASE_VERSION, BOOT_RECORD_VERSION } = require('./lib/caps.js')

const inspect = Symbol.for('nodejs.util.inspect.custom')
const INTERRUPT = new Error('Apply interrupted')
const BINARY_ENCODING = c.from('binary')

const RECOVERIES = 3

// default is to automatically ack
const DEFAULT_ACK_INTERVAL = 10_000
const DEFAULT_ACK_THRESHOLD = 4

const REMOTE_ADD_BATCH = 64
const REMOTE_ADD_BATCH_SANITY = 4096
const MIN_FF_WAIT = 300_000 // wait at least 5min before attempting to ff again after failure

class WakeupHandler {
  constructor(base, discoveryKey) {
    this.active = true
    this.discoveryKey = discoveryKey
    this.base = base
  }

  onpeeractive(peer, session) {
    this.base._bumpWakeupPeer(peer)
  }

  onlookup(req, peer, session) {
    const wakeup = this.base._getWakeup()
    if (wakeup.length === 0) return
    session.announce(peer, wakeup)
  }

  onannounce(wakeup, peer, session) {
    if (this.base.isFastForwarding()) {
      this.base._needsWakeupRequest = true
      return
    }
    this.base.hintWakeup(wakeup)
  }
}

module.exports = class Autobase extends ReadyResource {
  constructor(store, bootstrap, handlers = {}) {
    if (Array.isArray(bootstrap)) bootstrap = bootstrap[0] // TODO: just a quick compat, lets remove soon

    if (bootstrap && typeof bootstrap !== 'string' && !b4a.isBuffer(bootstrap)) {
      handlers = bootstrap
      bootstrap = null
    }

    super()

    const key = bootstrap ? toKey(bootstrap) : null

    this.id = null
    this.key = key
    this.discoveryKey = null
    this.backoff = handlers.backoff || null

    this.keyPair = null
    this.valueEncoding = c.from(handlers.valueEncoding || 'binary')
    this.store = store
    this.globalCache = store.globalCache || null
    this.migrated = false

    this.encrypted = handlers.encrypted || !!handlers.encryptionKey
    this.encrypt = !!handlers.encrypt
    this.encryptionKey = null
    this.encryption = null
    this.blindEncryption = handlers.blindEncryption || null

    this.activeBatch = null // maintained by the append-batch

    this.local = null
    this.localWriter = null
    this.isIndexer = false

    this.activeWriters = new ActiveWriters()
    this.linearizer = null
    this.updating = false

    this.nukeTip = !!handlers.nukeTip

    this.wakeupOwner = !handlers.wakeup
    this.wakeupCapability = null
    this.wakeupProtocol = handlers.wakeup || new ProtomuxWakeup()
    this.wakeupSession = null

    this._primaryBootstrap = null

    this.fastForwardEnabled = handlers.fastForward !== false
    this.fastForwarding = null
    this.fastForwardTo = null
    this.fastForwardFailedAt = 0
    this.fastForwardMinimum = FastForward.MINIMUM

    this.bigBatches = !!handlers.bigBatches

    this._bootstrapWriters = [] // might contain dups, but thats ok
    this._bootstrapWritersChanged = false

    this._flushSignal = new SignalPromise()
    this._flushing = 0

    this._checkWriters = []
    this._optimistic = -1
    this._appended = 0
    this._appending = null
    this._wakeup = new AutoWakeup(this)
    this._wakeupHints = new Map()
    this._wakeupPeerBound = this._wakeupPeer.bind(this)
    this._coupler = null

    this._updateLocalCore = null
    this._lock = new ScopeLock()

    this._needsWakeupRequest = false
    this._needsWakeup = true
    this._needsWakeupHeads = true

    this._updates = []
    this._handlers = handlers || {}
    this._warn = emitWarning.bind(this)
    this._lastError = null

    this._draining = false
    this._writable = null
    this._advancing = null
    this._interrupting = false
    this._caughtup = false

    this.paused = false

    this._bump = debounceify(() => {
      this._advancing = this._advance()
      return this._advancing
    })

    this._onremotewriterchangeBound = this._onremotewriterchange.bind(this)
    this._onlocalwriterchangeBound = this._onlocalwriterchange.bind(this)

    this._preopen = null

    this._hasOpen = !!this._handlers.open
    this._hasApply = !!this._handlers.apply
    this._hasOptimisticApply = !!this._handlers.optimistic
    this._hasUpdate = !!this._handlers.update
    this._hasClose = !!this._handlers.close

    this._viewStore = new AutoStore(this)
    this._applyState = null

    this.view = null
    this.core = null
    this.version = -1
    this.interrupted = null
    this.recoveries = RECOVERIES

    const { ackInterval = DEFAULT_ACK_INTERVAL, ackThreshold = DEFAULT_ACK_THRESHOLD } = handlers

    this._ackInterval = ackInterval
    this._ackThreshold = ackThreshold
    this._ackTickThreshold = ackThreshold
    this._ackTick = 0

    this._ackTimer = null
    this._acking = false

    this._waiting = new SignalPromise()

    this.view = this._hasOpen
      ? this._handlers.open(this._viewStore, new PublicApplyCalls(this))
      : null
    this.core = this._viewStore.get({ name: '_system' })

    if (this.fastForwardEnabled && isObject(handlers.fastForward)) {
      this._runFastForward(
        new FastForward(this, handlers.fastForward.key, { verified: false })
      ).catch(noop)
    }

    this.ready().catch(safetyCatch)
  }

  [inspect](depth, opts) {
    let indent = ''
    if (typeof opts.indentationLvl === 'number') {
      while (indent.length < opts.indentationLvl) indent += ' '
    }

    return indent + 'Autobase { ... }'
  }

  // just compat, use .key
  get bootstrap() {
    return this.key
  }

  // TODO: compat, will be removed
  get bootstraps() {
    return [this.bootstrap]
  }

  get appending() {
    return this._appending !== null && this._appending.length > 0
  }

  get writable() {
    return this.localWriter !== null && !this.localWriter.isRemoved
  }

  get ackable() {
    return this.localWriter !== null && this.localWriter.isActiveIndexer
  }

  get signedLength() {
    return this.core.signedLength
  }

  get indexedLength() {
    return this._applyState ? this._applyState.indexedLength : 0
  }

  get length() {
    return this.core.length
  }

  get flushing() {
    return this._flushing > 0
  }

  hash() {
    return this.core.treeHash()
  }

  // deprecated, use .core.key
  getSystemKey() {
    return this.core.key
  }

  get system() {
    return this._applyState && this._applyState.system
  }

  // deprecated
  async getIndexedInfo() {
    if (this.opened === false) await this.ready()
    return (
      this._applyState && this._applyState.system.getIndexedInfo(this._applyState.indexedLength)
    )
  }

  _isActiveIndexer() {
    return this.localWriter ? this.localWriter.isActiveIndexer : false
  }

  replicate(isInitiator, opts) {
    const stream = this.store.replicate(isInitiator, opts)
    this.wakeupProtocol.addStream(stream)
    return stream
  }

  heads() {
    if (!this._applyState || !this._applyState.opened) return []
    const nodes = new Array(this._applyState.system.heads.length)
    for (let i = 0; i < this._applyState.system.heads.length; i++)
      nodes[i] = this._applyState.system.heads[i]
    return nodes.sort(compareNodes)
  }

  async export() {
    const exporting = [this.store.storage.export(this.local.discoveryKey), this._viewStore.export()]

    const [local, views] = await Promise.all(exporting)

    return {
      local,
      views
    }
  }

  hintWakeup(hints) {
    if (!Array.isArray(hints)) hints = [hints]
    for (const { key, length } of hints) {
      const hex = b4a.toString(key, 'hex')
      const prev = this._wakeupHints.get(hex)
      if (!prev || length === -1 || prev < length) this._wakeupHints.set(hex, length)
    }
    this._queueBump()
  }

  setBigBatches(bool = true) {
    this.bigBatches = bool
  }

  _queueBump() {
    this._bump().catch(safetyCatch)
  }

  async _runPreOpen() {
    if (this._handlers.wait) await this._handlers.wait()

    await this.store.ready()

    this.keyPair = (await this._handlers.keyPair) || null

    if (this._handlers.encryptionKey !== null) {
      this.encryptionKey = await this._handlers.encryptionKey
    }

    const result = await boot(this.store, this.key, {
      encryptionKey: this.encryptionKey,
      encrypt: this.encrypt,
      keyPair: this.keyPair,
      blindEncryption: this.blindEncryption
    })

    this._primaryBootstrap = result.bootstrap
    this.local = result.local

    this.key = result.bootstrap.key
    this.discoveryKey = result.bootstrap.discoveryKey
    this.id = result.bootstrap.id

    this.encryptionKey = result.encryptionKey

    if (this.encrypted) {
      assert(this.encryptionKey !== null, 'Encryption key is expected')
    }

    if (this.encryptionKey) {
      this.encryption = new EncryptionView(this, null)

      this.local.setEncryption(this.getWriterEncryption())
      this._primaryBootstrap.setEncryption(this.getWriterEncryption())
    }

    if (this.nukeTip) await this._nukeTip()

    this.local.on('append', this._onlocalwriterchangeBound)

    this.wakeupCapability = (await this._handlers.wakeupCapability) || {
      key: this.key,
      discoveryKey: this.discoveryKey
    }
    this.setWakeup(this.wakeupCapability.key, this.wakeupCapability.discoveryKey)
  }

  async _nukeTipBatch(key, length) {
    const core = this.store.get({ key, active: false })
    await core.ready()

    const batch = core.session({ name: 'batch' })
    await batch.ready()
    if (batch.length > length) await batch.truncate(length)
    await batch.close()

    await core.close()
  }

  // TODO: not atomic atm, so more of a (very useful) debug helper
  async _nukeTip() {
    const pointer = await this.local.getUserData('autobase/boot')
    if (!pointer) return

    const boot = c.decode(messages.BootRecord, pointer)

    await LocalState.clear(this.local)

    await this._nukeTipBatch(boot.key, boot.systemLength)

    const core = this.store.get({ key: boot.key, active: false, encryption: null })
    const encCore = await EncryptionView.setSystemEncryption(this, core)

    const batch = core.session({ name: 'batch' })
    await batch.ready()

    const info = await SystemView.getIndexedInfo(batch, boot.systemLength)
    await batch.close()

    for (const view of info.views) {
      // ensure any views ref'ed by system are consistent as well
      await this._nukeTipBatch(view.key, view.length)
    }

    if (boot.heads) this.hintWakeup(boot.heads)
    if (this.local.length) this.hintWakeup([{ key: this.local.key, length: this.local.length }])

    await core.close()
    if (encCore) await encCore.close()
  }

  _bumpWakeupPeer(peer) {
    if (this._coupler) this._coupler.update(peer.stream)
  }

  async _rotateLocalWriter(newLocal) {
    assert(!this.appending, 'Cannot rotate a newLocal writer if an append is in progress')

    const oldLocal = this.local

    if (this._applyState) await this._applyState.close()

    this.local = newLocal
    this.local.on('append', this._onlocalwriterchangeBound)

    this.localWriter = null
    this._updateLocalCore = null

    const store = this._viewStore.atomize()

    const local = store.getLocal()
    await local.ready()

    await LocalState.moveTo(oldLocal, local)

    await local.setUserData('referrer', this.key)
    if (this.encryptionKey) {
      if (this.blindEncryption) {
        const encrypted = await encryptionEncoding.encrypt(
          this.encryptionKey,
          this.blindEncryption.encrypt
        )
        await local.setUserData('autobase/blind-encryption', encrypted)
      } else {
        await local.setUserData('autobase/encryption', this.encryptionKey)
      }
    }

    await store.flush()
    await store.close()

    await this._primaryBootstrap.setUserData('autobase/local', local.key)

    await this._clearWriters()
    await oldLocal.close()

    // done, soft reboot

    await this._viewStore.updateLocal()

    await this._clearWriters()

    this._applyState = new ApplyState(this)
    await this._applyState.ready()
    await this._makeLinearizerFromViewState()

    this._caughtup = false

    this._rebooted()

    this.emit('rotate-local-writer')
  }

  async setLocal(key, { keyPair } = {}) {
    if (!this.opened) await this.ready()

    const manifest = keyPair
      ? { version: this.store.manifestVersion, signers: [{ publicKey: keyPair.publicKey }] }
      : null
    if (!key) key = Hypercore.key(manifest)
    // If the keys are the same, no need to rotate
    if (b4a.equals(key, this.local.key)) return

    const encryption = this.encryptionKey ? this.getWriterEncryption() : null

    const local = this.store.get({
      key,
      manifest,
      active: false,
      exclusive: true,
      encryption,
      valueEncoding: messages.OplogMessage
    })
    await local.ready()

    this._updateLocalCore = local

    let runs = 0
    while (!this._interrupting && this.appending && runs++ < 16) await this.update()
    await this._bump()
  }

  setWakeup(cap, discoveryKey) {
    if (this.wakeupSession) this.wakeupSession.destroy()
    if (!discoveryKey && b4a.equals(cap, this.key)) discoveryKey = this.discoveryKey
    this.wakeupSession = this.wakeupProtocol.session(
      cap,
      new WakeupHandler(this, discoveryKey || null)
    )

    // incase this session has active peers already, bump the coupler
    for (const peer of this.wakeupSession.peers) {
      if (peer.active) this._bumpWakeupPeer(peer)
    }
  }

  async _getMigrationPointer(key, length) {
    const core = this.store.get({ key, active: false, encryption: null })
    const encCore = await EncryptionView.setSystemEncryption(this, core)

    const min = core.manifest && core.manifest.prologue ? core.manifest.prologue.length : 0

    for (let i = length - 1; i >= min; i--) {
      if (!(await core.has(i))) continue

      const sys = new SystemView(core, { checkout: i + 1 })
      await sys.ready()

      let good = true

      for (const v of sys.views) {
        const vc = this.store.get({ key: v.key, active: false })
        await vc.ready()
        if (vc.length < v.length) good = false
        await vc.close()
      }

      await sys.close()
      if (!good) continue

      return i + 1
    }

    await core.close()
    if (encCore) await encCore.close()

    return min
  }

  // migrating from 6 -> latest
  async _migrate6(key, length) {
    const core = this.store.get({ key, active: false })
    await core.ready()
    const batch = core.session({ name: 'batch', overwrite: true, checkout: length })
    await batch.ready()
    await batch.close()
    await core.close()
  }

  // called by view-store for bootstrapping
  async _getSystemInfo() {
    const boot = await this._getBootRecord()
    if (!boot.key) return null

    const migrated = !!boot.heads
    const indexedLength = boot.systemLength

    if (migrated) {
      // ensure system batch is consistent on initial migration
      await this._migrate6(boot.key, indexedLength)
    }

    const core = this.store.get({ key: boot.key, encryption: null, active: false })
    await core.ready()

    const batch = core.session({ name: 'batch' })
    const encCore = await EncryptionView.setSystemEncryption(this, batch)

    await batch.ready()
    if (encCore) await encCore.ready()

    const info = await SystemView.getIndexedInfo(batch, indexedLength)

    if (encCore) await encCore.close()
    await batch.close()
    await core.close()

    if (info.version > MAX_AUTOBASE_VERSION) {
      throw new Error('Autobase upgrade required.')
    }

    // just compat
    if (migrated) {
      this.migrated = true

      for (const view of info.views) {
        // ensure any views ref'ed by system are consistent as well
        await this._migrate6(view.key, view.length)
      }

      if (boot.heads) this.hintWakeup(boot.heads)
      if (this.local.length) this.hintWakeup([{ key: this.local.key, length: this.local.length }])
    }

    return {
      key: boot.key,
      indexers: info.indexers,
      views: info.views,
      entropy: info.entropy
    }
  }

  // called by the apply state for bootstrapping
  async _getBootRecord() {
    await this._preopen

    const pointer = await this.local.getUserData('autobase/boot')

    const boot = pointer
      ? c.decode(messages.BootRecord, pointer)
      : {
          version: BOOT_RECORD_VERSION,
          key: null,
          systemLength: 0,
          indexersUpdated: false,
          fastForwarding: false,
          recoveries: RECOVERIES,
          heads: null
        }

    if (boot.heads) {
      const len = await this._getMigrationPointer(boot.key, boot.systemLength)
      if (len !== boot.systemLength)
        this._warn(
          new Error(
            'Invalid pointer in migration, correcting (' + len + ' vs ' + boot.systemLength + ')'
          )
        )
      boot.systemLength = len
    }

    return boot
  }

  static async getBootRecord(store, key) {
    const result = await boot(store, key, { exclusive: false })
    await result.bootstrap.close()
    await result.local.close()
    return result.boot
  }

  _interrupt(reason) {
    assert(!!this._applyState.applying, 'Interrupt is only allowed in apply')
    this._interrupting = true
    if (reason) this.interrupted = reason
    throw INTERRUPT
  }

  async flush() {
    if (this._flushing === 0) return
    return this._flushSignal.wait()
  }

  async advance() {
    if (this.opened === false) await this.ready()
    await this._advancing
  }

  recouple() {
    if (this._coupler) this._coupler.destroy()
    const core = this._viewStore.getSystemCore()
    this._coupler = new CoreCoupler(core, this._wakeupPeerBound)
  }

  _updateBootstrapWriters() {
    const writers = this.linearizer.getBootstrapWriters()

    // first clear all, but without applying it for churn reasons
    for (const writer of this._bootstrapWriters) {
      writer.isBootstrap = false
      writer.isCoupled = false
    }

    // all passed are bootstraps
    for (const writer of writers) {
      writer.isCoupled = true
      writer.setBootstrap(true)
    }

    // reset activity on old ones, all should be in sync now
    for (const writer of this._bootstrapWriters) {
      if (writer.isBootstrap === false) writer.setBootstrap(false)
    }

    this._bootstrapWriters = writers
    this._bootstrapWritersChanged = false
  }

  async _openLinearizer() {
    if (this._applyState.system.bootstrapping) {
      await this._makeLinearizer(null)
      this._bootstrapLinearizer()
      return
    }

    await this._makeLinearizerFromViewState()
  }

  async _catchupApplyState() {
    if (await this._applyState.shouldMigrate()) {
      await this._migrate()
    } else if (!(await this._applyState.catchup(this.linearizer))) {
      return false
    }

    this._caughtup = true
    return true
  }

  async _open() {
    this._preopen = this._runPreOpen()
    await this._preopen

    if (this.closing) return

    this._applyState = new ApplyState(this)

    try {
      await this._applyState.ready()
    } catch (err) {
      if (this.closing) return

      try {
        await this._applyState.close()
      } catch {}

      try {
        await this.core.ready()
      } catch {}

      this._applyState = null
      if (this.closing) return

      throw err
    }

    try {
      await this._openLinearizer()
      await this.core.ready()
      await this._wakeup.ready()
    } catch (err) {
      if (this.closing) return
      throw err
    }

    if (this.core.length - this._applyState.indexedLength > this._ackTickThreshold) {
      this._ackTick = this._ackTickThreshold
    }
    if (this.localWriter && this._ackInterval) {
      this._startAckTimer()
    }

    this._updateBootstrapWriters()

    this.recouple()
    this._queueFastForward()

    // queue a full bump that handles wakeup etc (not legal to wait for that here)
    this._queueBump()
  }

  async _close() {
    await this.flush() // flush all pending non network io
    this._interrupting = true
    await Promise.resolve() // defer one tick

    if (this.wakeupSession) this.wakeupSession.destroy()
    if (this.wakeupOwner) this.wakeupProtocol.destroy()

    if (this.fastForwarding) await this.fastForwarding.close()

    if (this._coupler) this._coupler.destroy()
    this._coupler = null
    this._waiting.notify(null)

    await this.activeWriters.clear()

    const closing = this._advancing ? this._advancing.catch(safetyCatch) : null

    await this._clearWriters()
    if (this._primaryBootstrap) await this._primaryBootstrap.close()
    await this.local.close()

    if (this._ackTimer) {
      this._ackTimer.stop()
      await this._ackTimer.flush()
    }

    await this._wakeup.close()

    if (this._hasClose) await this._handlers.close(this.view)
    if (this._applyState) await this._applyState.close()

    await this._viewStore.close()
    await this.core.close()
    await this.store.close()

    if (this._writable) this._writable.resolve(false)

    await closing
  }

  getLastError() {
    return this._lastError
  }

  _onError(err) {
    if (this.closing) return

    this._lastError = err

    if (err === INTERRUPT) {
      this.emit('interrupt', this.interrupted)
      this.emit('update')
      return
    }

    this.close().catch(safetyCatch)

    // if no one is listening we should crash! we cannot rely on the EE here
    // as this is wrapped in a promise so instead of nextTick throw it
    if (ReadyResource.listenerCount(this, 'error') === 0) {
      crashSoon(err)
      return
    }

    this.emit('error', err)
  }

  async _closeWriter(w) {
    this.activeWriters.delete(w)
    await w.close()
  }

  async _gcWriters() {
    // just return early, why not
    if (this._checkWriters.length === 0) return

    while (this._checkWriters.length > 0) {
      const w = this._checkWriters.pop()

      // doesnt hurt
      w.updateActivity()

      if (!w.flushed()) continue

      const unqueued = this._wakeup.unqueue(w.core.key, w.core.length)

      if (!unqueued || w.isActiveIndexer) continue
      if (this.localWriter === w) continue

      await this._closeWriter(w)
    }

    await this._wakeup.flush()
  }

  _startAckTimer() {
    if (this._ackTimer) return
    this._ackTimer = new Timer(this._backgroundAck.bind(this), this._ackInterval)
    this._bumpAckTimer()
  }

  _bumpAckTimer() {
    if (!this._ackTimer) return
    this._ackTimer.bump()
  }

  async update() {
    if (this.opened === false) await this.ready()

    try {
      await this._bump()
      if (this._acking) await this._bump() // if acking just rebump incase it was triggered from above...
    } catch (err) {
      if (this._interrupting) return
      throw err
    }
  }

  // runs in bg, not allowed to throw
  // TODO: refactor so this only moves the writer affected to a updated set
  async _onremotewriterchange() {
    this._bumpAckTimer()

    try {
      await this._bump()
    } catch {}
  }

  _onlocalwriterchange() {
    if (!this.localWriter || this.localWriter.isRemoved) this._queueBump()
  }

  _onwakeup() {
    this._needsWakeup = true
    this._queueBump()
  }

  isFastForwarding() {
    if (this.fastForwardTo !== null) return true
    return this.fastForwardEnabled && this.fastForwarding !== null
  }

  _backgroundAck() {
    return this.ack(true)
  }

  async ack(bg = false) {
    if (this.opened === false) await this.ready()
    if (this.localWriter === null || this._acking || this._interrupting || this._appending !== null)
      return

    if (this._applyState === null) {
      try {
        await this._bump()
      } catch {}
      if (this._applyState === null || this._interrupting) return
    }

    const applyState = this._applyState
    if (applyState.opened === false) await applyState.ready()

    const isPendingIndexer = applyState.isLocalPendingIndexer()

    // if no one is waiting for our index manifest, wait for FF before pushing an ack
    if ((!isPendingIndexer && this.isFastForwarding()) || this._interrupting) return

    const isIndexer = applyState.isLocalIndexer() || isPendingIndexer
    if (!isIndexer) return

    this._acking = true

    try {
      await this._bump()
    } catch (err) {
      if (!this._interrupting) throw err
    }

    if (this._interrupting || !this.localWriter || this.localWriter.closed) {
      this._acking = false
      return
    }

    // avoid lumping acks together due to the bump wait here
    if (this._ackTimer && bg) await this._ackTimer.asapStandalone()
    if (this._interrupting || applyState.closing) {
      this._acking = false
      return
    }

    const alwaysWrite = isPendingIndexer || (await applyState.shouldWrite())
    if (this._interrupting || applyState.closing) {
      this._acking = false
      return
    }

    const hasPendingIndexers = applyState.system.indexers.length > this.linearizer.indexers.length

    if (alwaysWrite || this.linearizer.shouldAck(this.localWriter, hasPendingIndexers)) {
      try {
        if (this.localWriter && !this.localWriter.closed) await this.append(null)
      } catch (err) {
        if (!this._interrupting) throw err
      }
    }

    if (!this._interrupting) {
      this._updateAckThreshold()
      this._bumpAckTimer()
    }

    this._acking = false
  }

  views() {
    if (this._applyState) return this._applyState.store.listViews()
    return this._viewStore.listViews()
  }

  batch() {
    return new AppendBatch(this)
  }

  async append(value, opts) {
    if (this.opened === false) await this.ready()
    if (this._advancing !== null) await this._advancing
    while (this.activeBatch) await this.activeBatch.flushed()
    return this._appendBatch(value, opts)
  }

  async _appendBatch(value, opts) {
    if (this._interrupting) throw new Error('Autobase is closing')
    if (value && this.valueEncoding !== BINARY_ENCODING)
      value = normalize(this.valueEncoding, value)

    const optimistic = !!opts && !!opts.optimistic && !!value

    // we wanna allow acks so interdexers can flush
    if (
      !optimistic &&
      (this.localWriter === null || (this.localWriter.isRemoved && value !== null))
    ) {
      throw new Error('Not writable')
    }

    if (this._appending === null) this._appending = []

    let len = 0
    if (Array.isArray(value)) {
      for (const v of value) len = this._append(v)
    } else {
      len = this._append(value)
    }

    const localLength = this.local.length

    if (optimistic) this._optimistic = this._appending.length - 1
    const target = this._appended + this._appending.length

    // await in case append is in current tick
    if (this._advancing) await this._advancing

    let runs = 0

    // bump until we've flushed the nodes
    while (this._appended < target && !this._interrupting) {
      await this._bump()
      // safety
      if (runs++ >= 16 && this.localWriter && this.localWriter.idle()) break
    }

    if (this._advancing) await this._advancing
    if (this._interrupting) throw new Error('Autobase is closing')

    return localLength + len
  }

  _append(value) {
    // if prev value is an ack that hasnt been flushed, skip it
    if (this._appending.length > 0) {
      if (value === null) return this._appending.length
      if (this._appending[this._appending.length - 1] === null) {
        this._appending.pop()
      }
    }
    return this._appending.push(value)
  }

  static decodeValue(value, opts) {
    return decodeValue(value, opts)
  }

  static encodeValue(value, opts) {
    return encodeValue(value, opts)
  }

  static async getLocalKey(store, opts = {}) {
    const core = opts.keyPair
      ? store.get({ ...opts, active: false })
      : store.get({ ...opts, name: 'local', active: false })
    await core.ready()
    const key = core.key
    await core.close()
    return key
  }

  static getLocalCore(store, handlers, encryptionKey) {
    const encryption = !encryptionKey ? null : { key: encryptionKey }
    const opts = {
      ...handlers,
      compat: false,
      active: false,
      exclusive: true,
      valueEncoding: messages.OplogMessage,
      encryption
    }
    return opts.keyPair ? store.get(opts) : store.get({ ...opts, name: 'local' })
  }

  static async getUserData(core) {
    const view = await core.getUserData('autobase/view')

    return {
      referrer: await core.getUserData('referrer'),
      view: view ? b4a.toString(view) : null
    }
  }

  static async isAutobase(core, opts = {}) {
    const block = await core.get(0, opts)
    if (!block) throw new Error('Core is empty.')
    if (!b4a.isBuffer(block)) return isAutobaseMessage(block)

    try {
      const m = c.decode(messages.OplogMessage, block)
      return isAutobaseMessage(m)
    } catch {
      return false
    }
  }

  // no guarantees where the user data is stored, just that its associated with the base
  async setUserData(key, val) {
    await this._preopen
    const core = this._primaryBootstrap === null ? this.local : this._primaryBootstrap

    await core.setUserData(key, val)
  }

  async getUserData(key) {
    await this._preopen
    const core = this._primaryBootstrap === null ? this.local : this._primaryBootstrap

    return await core.getUserData(key)
  }

  _needsLocalWriter() {
    return this.localWriter === null || this.localWriter.closed
  }

  // no guarantees about writer.isActiveIndexer property here
  async _getWriterByKey(key, len, seen, allowGC, isAdded, system) {
    assert(this._draining === true || (this.opening && !this.opened) || this._optimistic > -1)

    await this._lock.lock()

    if (this._interrupting) {
      this._lock.unlock()
      throw new Error('Autobase is closing')
    }

    try {
      let w = this.activeWriters.get(key)

      const alreadyActive = !!w
      const sys = system || this._applyState.system
      const writerInfo = await sys.get(key)

      if (len === -1) {
        if (!allowGC && writerInfo === null) {
          if (w) w.isRemoved = !isAdded
          return null
        }

        len = writerInfo === null ? 0 : writerInfo.length
      }

      const isActive = writerInfo !== null && (isAdded || !writerInfo.isRemoved)
      const isRemoved = !isActive

      if (w) {
        w.isRemoved = isRemoved
      } else {
        w = this._makeWriter(key, len, isActive, isRemoved)
        if (!w) return null
      }

      if (isRemoved && sys.bootstrapping && b4a.equals(w.core.key, this.key)) {
        w.isRemoved = false
      }

      if (this._isLocalCore(w.core) && this._needsLocalWriter()) {
        this._setLocalWriter(w)
      }

      w.seen(seen)

      if (alreadyActive) return w

      await w.ready()

      if (this._isLocalCore(w.core) && this._needsLocalWriter()) {
        this._setLocalWriter(w)
      }

      if (allowGC && w.flushed()) {
        this._wakeup.unqueue(key, len)
        if (w !== this.localWriter) {
          await w.close()
          return w
        }
      }

      this.activeWriters.add(w)
      this._checkWriters.push(w)

      assert(w.opened)
      assert(!w.closed)

      w.updateActivity()
      return w
    } finally {
      this._lock.unlock()
    }
  }

  _updateAll() {
    const p = []
    for (const w of this.activeWriters) p.push(w.update(null).catch(safetyCatch))
    return Promise.all(p)
  }

  getWriterEncryption() {
    if (!this.encryptionKey) return null
    return this.encryption.getWriterEncryption()
  }

  _makeWriterCore(key) {
    if (this.closing) throw new Error('Autobase is closing')
    if (this._interrupting) throw INTERRUPT()

    const local = b4a.equals(key, this.local.key)
    const encryption = this.getWriterEncryption()

    const core = local
      ? this.local.session({ valueEncoding: messages.OplogMessage, encryption, active: false })
      : this.store.get({
          key,
          compat: false,
          writable: false,
          valueEncoding: messages.OplogMessage,
          encryption,
          active: false
        })

    return core
  }

  _makeWriter(key, length, isActive, isRemoved) {
    const core = this._makeWriterCore(key)
    const w = new Writer(this, core, length, isRemoved)

    if (this._isLocalCore(core)) {
      if (isActive) this._setLocalWriter(w) // only set active writer
      return w
    }

    core.on('append', this._onremotewriterchangeBound)
    core.on('download', this._onremotewriterchangeBound)
    core.on('manifest', this._onremotewriterchangeBound)

    return w
  }

  _updateLinearizer(indexers, heads) {
    // only current active indexers are reset to true below
    for (const w of this.activeWriters) w.isActiveIndexer = false
    if (this.localWriter) this.localWriter.isActiveIndexer = false

    for (const writer of indexers) writer.isActiveIndexer = true

    if (this._isActiveIndexer() && !this.isIndexer) {
      this._setLocalIndexer()
    } else if (!this._isActiveIndexer() && this.isIndexer) {
      this._clearLocalIndexer()
    }

    this.linearizer = new Linearizer(indexers, { heads, writers: this.activeWriters })

    this._updateAckThreshold()
  }

  async _updateLocalWriter(sys) {
    if (this.localWriter !== null && !this.localWriter.closed) return
    await this._getWriterByKey(this.local.key, -1, 0, true, false, sys)
  }

  async _bootstrapLinearizer() {
    const bootstrap = this._makeWriter(this.key, 0, true, false)

    this.activeWriters.add(bootstrap)
    this._checkWriters.push(bootstrap)
    await bootstrap.ready()
    this._ensureWakeup(bootstrap)

    this._updateLinearizer([bootstrap], [])
  }

  async _makeLinearizer(sys) {
    if (sys === null) {
      return this._bootstrapLinearizer()
    }

    if (this.opened || (await sys.hasLocal(this.local.key))) {
      await this._updateLocalWriter(sys)
    }

    const indexers = []

    for (const head of sys.indexers) {
      const writer = await this._getWriterByKey(head.key, head.length, 0, false, false, sys)
      indexers.push(writer)
    }

    if (!this._isActiveIndexer()) {
      for (const key of sys.pendingIndexers) {
        if (b4a.equals(key, this.local.key)) {
          this._setLocalIndexer()
          break
        }
      }
    }

    this._updateLinearizer(indexers, sys.heads)

    for (const { key, length } of sys.heads) {
      await this._getWriterByKey(key, length, 0, false, false, sys)
    }
  }

  async _clearWriters() {
    await this.activeWriters.clear()
    if (this.localWriter !== null) await this.localWriter.close()
    this._checkWriters = []
  }

  async _moveTo() {
    assert(this._applyState.closed)
    for (const ref of this._viewStore.byName.values()) {
      if (!ref.moveTo) continue
      const [batch, next] = ref.moveTo
      ref.moveTo = null
      await ref.batch.state.moveTo(batch, batch.length)
      await batch.close()
      ref.migrated(this, next)
    }
  }

  async _makeLinearizerFromViewState() {
    const sys = await this._applyState.getIndexedSystem()
    await this._makeLinearizer(sys)
    await sys.close()
  }

  async _runForceFastForward() {
    await this.core.ready()
    if (this.closing) return
    const rec = this._applyState ? await this._applyState.recoverAt() : null
    await this._runFastForward(
      new FastForward(this, this.core.key, { force: true, length: rec ? rec.length : 0 })
    )
  }

  // general repair method for trying to recover
  async repair() {
    await this.forceFastForward()
  }

  async forceFastForward() {
    if (this.isFastForwarding()) return
    await this._runForceFastForward()
    await this.update()
  }

  async _applyFastForward() {
    if (
      !this.fastForwardTo.force &&
      this.fastForwardTo.length < this.core.length + this.fastForwardTo.minimum
    ) {
      this.fastForwardTo = null
      this._updateActivity()
      // still not worth it
      return
    }

    const changes = this._hasUpdate ? new UpdateChanges(this) : null
    if (changes) changes.track(this._applyState)

    // close existing state
    if (this._applyState) await this._applyState.close()

    const { key, length, views, indexers, manifestVersion, entropy } = this.fastForwardTo

    const from = this.core.signedLength
    const ffed = new Set()

    this._flushing++
    try {
      const store = this._viewStore.atomize()

      const systemRef = await this._viewStore.findViewByKey(key, indexers, manifestVersion, entropy)
      const migrated = !b4a.equals(key, systemRef.core.key)

      ffed.add(systemRef)

      if (migrated) {
        await this._applyFastForwardMigration(systemRef, { key, length })
      } else {
        await systemRef.catchup(store.atom, length)
      }

      for (const v of views) {
        const ref = await this._viewStore.findViewByKey(v.key, indexers, manifestVersion, entropy)
        if (!ref) continue // unknown, view ignored

        const migrated = !b4a.equals(ref.core.key, v.key)

        ffed.add(ref)

        if (migrated) {
          await this._applyFastForwardMigration(ref, v)
        } else {
          await ref.catchup(store.atom, v.length)
        }
      }

      if (ffed.size !== store.getViewCount()) {
        for (const ref of store.getViews()) {
          if (ffed.has(ref)) continue
          await ref.catchup(store.atom, 0) // its gone
        }
      }

      // migrate zero length cores
      if (migrated) {
        const manifests = await this._viewStore.getIndexerManifests(indexers)

        for (const [name, ref] of this._viewStore.byName) {
          if (ffed.has(ref)) continue
          await this._migrateView(manifests, null, name, 0, manifestVersion, entropy, [], null)
        }
      }

      const value = c.encode(messages.BootRecord, {
        version: BOOT_RECORD_VERSION,
        key,
        systemLength: length,
        indexersUpdated: false,
        fastForwarding: true,
        recoveries: RECOVERIES
      })

      const local = store.getLocal()
      await local.ready()
      await local.setUserData('autobase/boot', value)

      await LocalState.clear(local)

      await store.flush()
      await store.close()
    } finally {
      if (--this._flushing === 0) this._flushSignal.notify()
    }

    for (const ref of this._viewStore.byName.values()) await ref.release()

    this.recoveries = RECOVERIES
    this.fastForwardTo = null
    this._queueFastForward()

    await this._clearWriters()
    await this._moveTo()
    const to = this.core.signedLength

    if (changes) changes.finalise()

    this._applyState = new ApplyState(this)
    await this._applyState.ready()

    if (changes) await this._handlers.update(this._applyState.view, changes)

    if (await this._applyState.shouldMigrate()) {
      await this._migrate()
    } else {
      await this._makeLinearizerFromViewState()
      await this._applyState.catchup(this.linearizer)
    }

    if (!this.localWriter || this.localWriter.closed) {
      await this._updateLocalWriter(this._applyState.system)
    }

    this._caughtup = true

    this._rebooted()
    this.emit('fast-forward', to, from)
  }

  // TODO: not atomic in regards to the ff, fix that
  async _applyFastForwardMigration(ref, v) {
    await ref.batch.ready()

    const next = this.store.get(v.key)
    await next.ready()

    const prologue = next.manifest && next.manifest.prologue

    if (prologue && prologue.length > 0 && ref.core.length >= prologue.length) {
      try {
        await next.core.copyPrologue(ref.core.state)
      } catch {
        // we might be missing some nodes for this, just ignore, only an optimisation
      }
    }

    const batch = next.session({ name: 'batch', overwrite: true, checkout: v.length })
    await batch.ready()

    // remake the batch, reset from our prologue in case it replicated inbetween
    // TODO: we should really have an HC function for this

    ref.moveTo = [batch, next]
  }

  async _migrateView(
    indexerManifests,
    source,
    name,
    indexedLength,
    manifestVersion,
    entropy,
    linked,
    manifestData
  ) {
    const ref = this._viewStore.byName.get(name)
    await ref.batch.ready()

    const prologue =
      indexedLength === 0
        ? null
        : { length: indexedLength, hash: await source.treeHash(indexedLength) }

    if (manifestData === null && ref.core.manifest.userData !== null) {
      manifestData = ref.core.manifest.userData
    }

    const next = this._viewStore.getViewCore(
      indexerManifests,
      name,
      prologue,
      manifestVersion,
      entropy,
      linked,
      manifestData
    )
    await next.ready()

    if (indexedLength > 0) {
      await next.core.copyPrologue(source.state)
    }

    // remake the batch, reset from our prologue in case it replicated inbetween
    // TODO: we should really have an HC function for this
    const batch = next.session({ name: 'batch', overwrite: true, checkout: indexedLength })
    await batch.ready()

    if (source !== null) {
      while (batch.length < source.length) {
        await batch.append(await source.get(batch.length))
      }
    }

    ref.moveTo = [batch, next]

    return ref
  }

  async _premigrate() {
    this._flushing++
    try {
      const length = this._applyState.indexedLength
      const system = this._applyState.system

      const info = await system.getIndexedInfo(length)
      const indexerManifests = await this._viewStore.getIndexerManifests(info.indexers)

      const { views, systemView, encryptionView } = this._applyState

      const manifestVersion = this._applyState.system.core.manifest.version

      for (const view of views) {
        const v = this._applyState.getViewFromSystem(view, info)
        const indexedLength = v ? v.length : 0

        const ref = this._viewStore.getViewByName(view.name)
        const source = ref.getCore()
        await source.ready()

        await this._migrateView(
          indexerManifests,
          source,
          view.name,
          indexedLength,
          manifestVersion,
          info.entropy,
          null,
          null
        )
      }

      const source = encryptionView.ref.getCore()
      await source.ready()

      const enc = await this._migrateView(
        indexerManifests,
        source,
        '_encryption',
        info.encryptionLength,
        manifestVersion,
        info.entropy,
        null,
        null
      )

      const linked = [enc.core.key]

      const sysCore = systemView.ref.getCore()
      const ref = await this._migrateView(
        indexerManifests,
        sysCore,
        '_system',
        length,
        manifestVersion,
        info.entropy,
        linked,
        null,
        null
      )

      const sysKey = ref.getNextKey()
      if (sysKey === null) {
        throw new Error('Migration failed, expected core to be moved')
      }

      return sysKey
    } finally {
      if (--this._flushing === 0) this._flushSignal.notify()
    }
  }

  async _migrate() {
    return this._reboot(await this._premigrate())
  }

  async _reboot(key) {
    await this._clearWriters()
    await this._makeLinearizerFromViewState()

    await this._applyState.finalize(key)
    await this._moveTo()

    this._applyState = new ApplyState(this)

    await this._applyState.ready()
    await this._applyState.catchup(this.linearizer)

    // end soft shutdown

    this._queueFastForward()

    this._rebooted()
  }

  _rebooted() {
    this.recouple()
    this._updateActivity()

    this.emit('reboot')

    // ensure we re-evalute our state
    this._bootstrapWritersChanged = true
    this._needsWakeup = true

    this.updating = true
    this._queueBump()
  }

  _setLocalWriter(w) {
    this.localWriter = w
    if (this._ackInterval) this._startAckTimer()
  }

  _unsetLocalWriter() {
    if (!this.localWriter) return

    this._closeWriter(this.localWriter)
    if (this.localWriter.isActiveIndexer) this._clearLocalIndexer()

    this.localWriter = null
  }

  _setLocalIndexer() {
    assert(this.localWriter !== null)

    this.isIndexer = true
    this.emit('is-indexer')
  }

  _clearLocalIndexer() {
    assert(this.localWriter !== null)

    if (this._ackTimer) this._ackTimer.stop()

    this.isIndexer = false
    this._ackTimer = null

    this.emit('is-non-indexer')
  }

  _isLocalCore(core) {
    return core.writable && core.id === this.local.id
  }

  _addLocalHeads() {
    // not writable atm, will prop be writable in a subsequent bump tho
    if (!this.localWriter || this.localWriter.closed) return null
    // safety, localwriter is still processing, should prop be an assertion
    if (!this.localWriter.idle()) return null

    const length = this._optimistic === -1 ? this._appending.length : this._optimistic || 1

    const nodes = new Array(length)
    for (let i = 0; i < length; i++) {
      const heads = this.linearizer.getHeads()
      const deps = new Set(this.linearizer.heads)
      const batch = length - i
      const value = this._appending[i]

      const node = this.localWriter.append(value, heads, batch, deps, this._optimistic === 0)

      this.linearizer.addHead(node)
      nodes[i] = node
    }

    return nodes
  }

  _flushLocalHeads(length) {
    this._appending = length === this._appending.length ? null : this._appending.slice(length)
    this._appended += length

    if (this._optimistic > -1 && this._optimistic < length) this._optimistic = -1
  }

  async _addRemoteHeads() {
    let added = 0

    while (
      added < REMOTE_ADD_BATCH ||
      (this.bigBatches && !this._indexersIdle() && added < REMOTE_ADD_BATCH_SANITY)
    ) {
      await this._updateAll()

      let advanced = 0

      for (const w of this.activeWriters) {
        let node = w.advance()
        if (node === null) continue

        advanced += node.batch

        while (true) {
          this.linearizer.addHead(node)
          if (node.batch === 1) break
          node = w.advance()
        }
      }

      if (advanced === 0) {
        if (this.bigBatches && !this._indexersIdle() && (await this._waitForIndexers())) continue
        break
      }

      added += advanced
    }

    return added
  }

  async _waitForIndexers() {
    const promises = []

    for (const w of this.linearizer.indexers) {
      if (w.idle()) continue
      if (await w.core.has(w.length)) continue
      promises.push(w.core.get(w.length, { timeout: 3000 }))
    }

    for (const result of await Promise.allSettled(promises)) {
      if (result.status !== 'rejected') return true
    }

    return false
  }

  _indexersIdle() {
    for (const w of this.linearizer.indexers) {
      if (!w.idle()) return false
    }
    return true
  }

  async _drain() {
    const writable = this.writable

    while (!this._interrupting && !this.paused) {
      if (this.local.recovering) {
        try {
          await this.local.recover()
        } catch {
          await this._runForceFastForward()
        }
        continue
      }

      if (this.fastForwardTo !== null) {
        await this._applyFastForward()
        continue // revaluate conditions...
      }

      // we defer this to post ready so its not blocking reading the views
      if (this._caughtup === false) {
        // if the catchup fails, just force ff it to recover, less user pain
        if (!(await this._catchupApplyState())) {
          await this._runForceFastForward()
        }
        continue
      }

      const remoteAdded = await this._addRemoteHeads()
      const localNodes = this._appending !== null ? this._addLocalHeads() : null

      if (this._interrupting) return

      if (remoteAdded > 0 || localNodes !== null) {
        this.updating = true
      }

      const u = this.linearizer.update()
      const update = u
        ? await this._applyState.update(u, localNodes)
        : { reboot: false, migrated: false }

      if (localNodes) this._flushLocalHeads(localNodes.length)

      if (!update.reboot) {
        if (this._applyState.shouldFlush()) {
          await this._applyState.flush()
          this.updating = true
        }

        if (this._checkWriters.length > 0) {
          await this._gcWriters()
          continue // rerun the update loop as a writer might have been added
        }
        if (remoteAdded >= REMOTE_ADD_BATCH) continue
        break
      }

      await this._gcWriters()
      await this._reboot(this._applyState.key)
    }

    // emit state changes post drain
    if (writable !== this.writable) {
      if (this.writable && this._writable) this._writable.resolve(true)
      this.emit(writable ? 'unwritable' : 'writable')
    }
  }

  _wakeupPeer(stream) {
    if (!this.wakeupSession) return
    const wakeup = this._getWakeup()
    if (wakeup.length === 0) return
    this.wakeupSession.announceByStream(stream, wakeup)
  }

  _getWakeup() {
    const writers = []

    for (const w of this.activeWriters) {
      if (w.isActiveIndexer || w.flushed()) continue
      writers.push({ key: w.core.key, length: w.length })
    }

    return writers
  }

  async _wakeupWriter(key, length) {
    this._ensureWakeup(await this._getWriterByKey(key, -1, length, true, false, null))
  }

  // ensure wakeup on an existing writer (the writer calls this in addition to above)
  _ensureWakeup(w) {
    if (w === null || w.isBootstrap === true) return
    w.setBootstrap(true) // even if turn false at end of drain, hypercore makes them linger a bit so no churn
    this._bootstrapWriters.push(w)
    this._bootstrapWritersChanged = true
  }

  async _drainWakeup() {
    const promises = []

    // warmup all the below gets
    if (this._needsWakeup) {
      for (const { key, length } of this._wakeup) {
        const w = this.activeWriters.get(key)
        if (w) {
          if (w.length < length) w.seen(length)
          continue
        }
        promises.push(this._applyState.system.get(key))
      }

      if (this._needsWakeupHeads) {
        for (const { key } of await this._applyState.system.heads) {
          if (this.activeWriters.has(key)) continue
          promises.push(this._applyState.system.get(key))
        }
      }
    }
    for (const [hex, length] of this._wakeupHints) {
      const key = b4a.from(hex, 'hex')
      if (length !== -1) {
        const w = this.activeWriters.get(key)
        if (w) {
          if (w.length < length) w.seen(length)
          continue
        }
      }
      promises.push(this._applyState.system.get(key))
    }

    await Promise.allSettled(promises)

    if (this._needsWakeup === true) {
      this._needsWakeup = false

      for (const { key, length } of this._wakeup) {
        if (this.activeWriters.has(key)) continue
        await this._wakeupWriter(key, length)
      }

      if (this._needsWakeupHeads === true) {
        this._needsWakeupHeads = false

        for (const { key } of await this._applyState.system.heads) {
          if (this.activeWriters.has(key)) continue
          await this._wakeupWriter(key, 0)
        }
      }
    }

    for (const [hex, length] of this._wakeupHints) {
      const key = b4a.from(hex, 'hex')
      if (this.activeWriters.has(key)) continue
      if (length !== -1) {
        const info = await this._applyState.system.get(key)
        if (info && length <= info.length) continue // stale hint
      }
      await this._wakeupWriter(key, length === -1 ? 0 : length)
    }

    this._wakeupHints.clear()
  }

  pause() {
    this.paused = true
  }

  resume() {
    this.paused = false
    this._queueBump()
  }

  waitForWritable() {
    if (this.writable) return Promise.resolve(true)
    if (!this._writable) this._writable = rrp()
    return this._writable.promise
  }

  async _drainWithInterupt() {
    while (true) {
      try {
        await this._drain()
        return
      } catch (err) {
        if (this.closing || !this.fastForwardTo) throw err
        if (Date.now() - this.fastForwardFailedAt < MIN_FF_WAIT) throw err
        this.fastForwardFailedAt = Date.now()
        // if an FF is enabled retry
      }
    }
  }

  async _advance() {
    if (this.opened === false) await this.ready()
    if (this.paused || this._interrupting) return

    this._draining = true

    if (this._updateLocalCore !== null) {
      await this._rotateLocalWriter(this._updateLocalCore)
    }

    const local = this.local.length

    try {
      await this._drainWithInterupt()

      // must run post drain so the linearizer is caught up
      if (this._caughtup && (this._needsWakeup === true || this._wakeupHints.size > 0))
        await this._drainWakeup()

      // check if we should update local writer
      if (!this.localWriter || this.localWriter.closed) {
        await this._updateLocalWriter(this._applyState.system)
      }

      this._draining = false
    } catch (err) {
      this._onError(err)
      return
    }

    if (this._interrupting) return

    if (this.localWriter && !this.localWriter.closed) {
      if (this._applyState.isLocalPendingIndexer()) this.ack().catch(noop)
      else if (this._triggerAckAsap()) this._ackTimer.asap()
    }

    // keep bootstraps in sync with linearizer
    if (this.updating === true || this._bootstrapWritersChanged === true) {
      this._updateBootstrapWriters()
    }

    if (this.updating === true) {
      this.updating = false

      if (local !== this.local.length) this._resetAckTick()
      else this._ackTick++

      if (!this._interrupting) this.emit('update')
      this._waiting.notify(null)
    }

    if (!this._interrupting) await this._gcWriters()
  }

  _triggerAckAsap() {
    if (!this._ackTimer) return false

    // flush if threshold is reached and we are not already acking
    if (this._ackTickThreshold && !this._acking && this._ackTick >= this._ackTickThreshold) {
      if (this._ackTimer) {
        for (const w of this.linearizer.indexers) {
          if (w.core.length > w.length) return false // wait for the normal ack cycle in this case
        }
      }

      return true
    }

    return false
  }

  _queueFastForward() {
    if (!this.core.opened) return
    // should have a better way to get this
    const latestSignedLength = this.core.core.state.length

    if (!this.fastForwardEnabled || this.fastForwarding !== null || this._interrupting) return

    if (latestSignedLength - this.core.length < this.fastForwardMinimum) return
    if (this.fastForwardTo !== null) return
    if (Date.now() - this.fastForwardFailedAt < MIN_FF_WAIT) return

    this._runFastForward(
      new FastForward(this, this.core.key, { minimum: this.fastForwardMinimum })
    ).catch(noop)
  }

  _queueStaticFastForward(key) {
    if (!this.fastForwardEnabled || this.fastForwarding !== null || this._interrupting) return
    if (this.fastForwardTo !== null) return
    if (Date.now() - this.fastForwardFailedAt < MIN_FF_WAIT) return

    this._runFastForward(new FastForward(this, key, { verified: false })).catch(noop)
  }

  _updateActivity() {
    this.activeWriters.updateActivity()
    if (this._applyState) {
      if (this.isFastForwarding()) this._applyState.pause()
      else this._applyState.resume()
    }

    // in case we ignored wakeups case we were fast forwarding, request them now if not
    if (this._needsWakeupRequest && !this.isFastForwarding() && this.wakeupSession) {
      this._needsWakeupRequest = false

      this.wakeupSession.broadcastLookup({})
    }
  }

  _preferFastForward() {
    this.fastForwardMinimum = 1
    this._queueFastForward()
  }

  _postApply() {
    this.fastForwardMinimum = FastForward.MINIMUM
  }

  async _runFastForward(ff) {
    this.fastForwarding = ff

    this._updateActivity()

    const result = await ff.upgrade()
    await ff.close()

    if (this.fastForwarding === ff) this.fastForwarding = null

    if (!result) {
      if (ff.failed) this.fastForwardFailedAt = Date.now()
      else this._queueFastForward()
      this._updateActivity()
      return
    }

    this.fastForwardFailedAt = 0
    this.fastForwardTo = result

    if (this._applyState && this._applyState.applying && this.fastForwardMinimum === 1) {
      await this._applyState.close()
    }

    this._bumpAckTimer()
    this._queueBump()
  }

  // triggered from apply
  async _addWriter(key, sys) {
    // just compat for old version
    assert(!!this._applyState.applying, 'System changes are only allowed in apply')

    const writer =
      (await this._getWriterByKey(key, -1, 0, false, true, sys)) ||
      this._makeWriter(key, 0, true, false)
    await writer.ready()

    if (!this.activeWriters.has(key)) {
      this.activeWriters.add(writer)
      this._checkWriters.push(writer)
      this._ensureWakeup(writer)
    }

    // fetch any nodes needed for dependents
    this._queueBump()
  }

  // triggered from apply
  _removeWriter(key) {
    // just compat for old version
    const w = this.activeWriters.get(key)
    if (w) w.isRemoved = true

    this._queueBump()
  }

  removeable(key) {
    return this._applyState ? this._applyState.removeable(key) : false
  }

  _updateAckThreshold() {
    if (this._ackThreshold === 0) return
    if (this._ackTimer) this._ackTimer.bau()
    this._ackTick = 0
    this._ackTickThreshold = random2over1(this.linearizer.indexers.length * this._ackThreshold)
  }

  _resetAckTick() {
    this._ackTick = 0
    if (this._ackTimer) this._ackTimer.bau()
  }

  _shiftWriter(w) {
    w.shift()
    if (w.flushed()) this._checkWriters.push(w)
  }
}

function toKey(k) {
  return b4a.isBuffer(k) ? k : hypercoreId.decode(k)
}

function isAutobaseMessage(msg) {
  return msg.checkpoint ? msg.checkpoint.length > 0 : msg.checkpoint === null
}

function compareNodes(a, b) {
  return b4a.compare(a.key, b.key)
}

function random2over1(n) {
  return Math.floor(n + Math.random() * n)
}

function noop() {}

function crashSoon(err) {
  queueMicrotask(() => {
    throw err
  })
  throw err
}

function isObject(obj) {
  return typeof obj === 'object' && obj !== null
}

function emitWarning(err) {
  safetyCatch(err)
  this.emit('warning', err)
}

function normalize(valueEncoding, value) {
  const state = { buffer: null, start: 0, end: 0 }
  valueEncoding.preencode(state, value)
  state.buffer = b4a.allocUnsafe(state.end)
  valueEncoding.encode(state, value)
  state.start = 0
  return valueEncoding.decode(state)
}
const b4a = require('b4a')

module.exports = class ActiveWriters {
  constructor() {
    this.map = new Map()
  }

  get size() {
    return this.map.size
  }

  [Symbol.iterator]() {
    return this.map.values()
  }

  get(key) {
    return this.map.get(b4a.toString(key, 'hex')) || null
  }

  has(key) {
    return this.get(key) !== null
  }

  add(writer) {
    this.map.set(b4a.toString(writer.core.key, 'hex'), writer)
  }

  delete(writer) {
    this.map.delete(b4a.toString(writer.core.key, 'hex'))
  }

  updateActivity() {
    for (const w of this.map.values()) w.updateActivity()
  }

  clear() {
    const p = []
    for (const w of this.map.values()) p.push(w.close())
    this.map.clear()

    return Promise.all(p)
  }
}
const SignalPromise = require('signal-promise')

module.exports = class AppendBatch {
  constructor(base) {
    this.base = base
    this.blocks = []
    this.closed = false
    this.flushing = false
    this._flushed = null
  }

  async _acquire() {
    while (this.base.activeBatch !== null && this.base.activeBatch !== this)
      await this.base.activeBatch.flushed()
    this.base.activeBatch = this
  }

  async append(value) {
    if (this.base.opened === false) await this.base.ready()
    if (this.base._advancing !== null) await this.base._advancing

    if (this.closed) throw new Error('Batch is closed')
    if (this.base.activeBatch !== this) await this._acquire()
    if (this.closed) throw new Error('Batch is closed')

    this.blocks.push(value)
    return this.base.local.length + this.blocks.length
  }

  async flush() {
    if (this.closed) throw new Error('Batch is closed')
    if (this.flushing) return this.flushed()
    this.flushing = true
    if (this.blocks.length) await this.base._appendBatch(this.blocks)
    return this.close()
  }

  flushed() {
    if (this.closed) return Promise.resolve()
    if (this._flushed) return this._flushed.wait()
    this._flushed = new SignalPromise()
    return this._flushed.wait()
  }

  close() {
    if (this.base.activeBatch !== this) return
    this.base.activeBatch = null
    this.closed = true
    if (this._flushed) this._flushed.notify(null)
  }
}
class PublicApplyCalls {
  constructor(base) {
    this.base = base
    this.internal = false
  }

  get discoveryKey() {
    return this.base.discoveryKey
  }

  get key() {
    return this.base.key
  }

  get id() {
    return this.base.id
  }

  async addWriter() {
    throw new Error('Not allowed on the public view')
  }

  async ackWriter() {
    throw new Error('Not allowed on the public view')
  }

  async removeWriter() {
    throw new Error('Not allowed on the public view')
  }

  preferFastForward() {
    throw new Error('Not allowed on the public view')
  }

  interrupt() {
    throw new Error('Not allowed on the public view')
  }

  removeable() {
    throw new Error('Not allowed on the public view')
  }

  fork() {
    throw new Error('Not allowed on the public view')
  }

  anchor() {
    throw new Error('Not allowed on the public view')
  }
}

class PrivateApplyCalls extends PublicApplyCalls {
  constructor(state) {
    super(state.base)
    this.state = state
    this.internal = true
  }

  get system() {
    return this.state.system
  }

  async addWriter(key, { indexer = true, isIndexer = indexer } = {}) {
    // just compat for old version
    await this.state.system.add(key, { isIndexer })
    await this.base._addWriter(key, this.state.system)
  }

  async ackWriter(key) {
    await this.state.system.ack(key)
  }

  async removeWriter(key) {
    // just compat for old version
    if (!this.state.removeable(key)) {
      throw new Error('Not allowed to remove the last indexer')
    }

    await this.state.system.remove(key)
    this.base._removeWriter(key)
  }

  preferFastForward() {
    this.base._preferFastForward()
  }

  interrupt(reason) {
    this.base._interrupt(reason)
  }

  removeable(key) {
    return this.state.removeable(key)
  }

  async fork(indexerKeys, system) {
    if (!(await this.state.validateFork(indexerKeys, system))) return false

    const indexers = indexerKeys.map(toIndexer)

    this.state.pendingFork = { indexers, length: system.length }

    return true
  }

  async createAnchor() {
    return await this.state.createAnchor()
  }
}

module.exports = { PublicApplyCalls, PrivateApplyCalls }

function toIndexer(key) {
  return { key, length: 0 } // length is not used, just for api compat
}
const ReadyResource = require('ready-resource')
const assert = require('nanoassert')
const c = require('compact-encoding')
const crypto = require('hypercore-crypto')
const b4a = require('b4a')
const safetyCatch = require('safety-catch')
const Hypercore = require('hypercore')

const { partialSignature } = require('hypercore/lib/multisig.js')

const SystemView = require('./system.js')
const { AutobaseEncryption, EncryptionView } = require('./encryption.js')
const UpdateChanges = require('./updates.js')
const messages = require('./messages.js')
const { PrivateApplyCalls } = require('./apply-calls.js')
const { encodeValue } = require('./values.js')
const Fork = require('./fork.js')
const LocalState = require('./local-state.js')
const { OPLOG_VERSION, BOOT_RECORD_VERSION } = require('./caps.js')

// todo: expose this as an option
const SHOULD_SIGN_THRESHOLD = 0

class CheckpointCore {
  constructor(view, core, signer, paused) {
    this.view = view
    this.core = core
    this.signer = signer
    this.length = 0
    this.digest = null
    this.signatures = { system: null, encryption: null, user: [] }
    this.closed = false
    this.paused = paused
  }

  pause() {
    this.paused = true
  }

  resume() {
    if (!this.paused) return
    this.paused = false
    this.updateBackground()
  }

  async update() {
    if (await this.updateCheckpoints()) await this.view.maybeSigned()
  }

  async updateCheckpoints() {
    if (this.core.length <= this.length || this.closed || this.paused) return false

    const length = this.core.length
    const value = await this.core.get(length - 1)

    if (length <= this.length || this.closed || !value.digest || this.paused) return false

    const [digest, checkpoints] = await Promise.all([
      this._inflateDigest(length, value.digest),
      this._inflateAllCheckpoints(length, value.checkpoint)
    ])

    if (length <= this.length || this.closed || !digest || !checkpoints || this.paused) return false
    for (let i = 0; i < checkpoints.length; i++) {
      if (checkpoints[i] === null) return false
    }

    this.length = length
    this.digest = digest
    this.signatures = checkpoints

    return true
  }

  updateBackground() {
    return this.update().catch(safetyCatch)
  }

  updateInternalSignatures(length, signatures) {
    this.signatures.system = updateSignature(length, signatures.system, this.signatures.system)
    this.signatures.encryption = updateSignature(
      length,
      signatures.encryption,
      this.signatures.encryption
    )
  }

  updateUserSignatures(length, signatures) {
    this.signatures.user = updateSignatures(length, signatures, this.signatures.user)
  }

  makeCheckpoints(length) {
    return {
      system: makeCheckpoint(length, this.signatures.system),
      encryption: makeCheckpoint(length, this.signatures.encryption),
      user: makeCheckpoints(length, this.signatures.user)
    }
  }

  makeDigest(length, key) {
    if (this.digest && (this.digest.key === key || b4a.equals(this.digest.key, key))) {
      return { key: null, pointer: length - this.digest.at }
    }
    this.digest = { key, at: length }
    return { key, pointer: 0 }
  }

  async ready() {
    await this.core.ready()
    this.core.on('append', this.updateBackground.bind(this))
    if (this.core.writable) await this.updateCheckpoints()
    this.updateBackground()
  }

  signedLength() {
    return this.signatures.system ? this.signatures.system.length : 0
  }

  close() {
    this.closed = true
    return this.core.close()
  }

  async _inflateDigest(length, dig) {
    if (!dig) return null

    if (dig.pointer === 0) {
      return { key: dig.key, at: length }
    }

    const len = length - dig.pointer

    if (this.digest && len === this.digest.at) return this.digest
    if (len <= 0) return null

    const { digest } = await this.core.get(len - 1)
    if (!digest || !digest.key) return null

    return { key: digest.key, at: len }
  }

  _sameSignatures(b, a) {
    return (
      sameSignature(a.system, b.system) &&
      sameSignature(a.encryption, b.encryption) &&
      sameSignatures(a.user, b.user)
    )
  }

  async _inflateAllCheckpoints(length, checkpoints) {
    if (!checkpoints) return { system: null, encryption: null, user: [] }
    if (this._sameSignatures(checkpoints, this.signatures)) return this.signatures

    const system = this._inflateSystemCheckpoint(checkpoints.system, length)
    const encryption = this._inflateEncryptionCheckpoint(checkpoints.encryption, length)

    const user = checkpoints.user ? new Array(checkpoints.user.length) : []

    for (let i = 0; i < user.length; i++) {
      const chk = checkpoints.user[i]
      user[i] = this._inflateUserCheckpoint(chk, i, length)
    }

    const [systemCheckpoint, encryptionCheckpoint, userCheckpoints] = await Promise.all([
      system,
      encryption,
      Promise.all(user)
    ])

    return {
      system: systemCheckpoint,
      encryption: encryptionCheckpoint,
      user: userCheckpoints
    }
  }

  async _inflateSystemCheckpoint(chk, coreLength) {
    if (chk.checkpoint) {
      const { signature, length } = chk.checkpoint
      return { signature, length, at: coreLength }
    }

    const len = coreLength - chk.checkpointer
    if (this.signatures.system && this.signatures.system.at === len) {
      return this.signatures.system
    }

    if (len <= 0) return null

    const { checkpoint } = await this.core.get(len - 1)
    if (!checkpoint || !checkpoint.system || !checkpoint.system.checkpoint) return null

    const { signature, length } = checkpoint.system.checkpoint
    return { signature, length, at: len }
  }

  async _inflateEncryptionCheckpoint(chk, coreLength) {
    if (!chk) return { length: 0, signature: null, at: 0 }

    if (chk.checkpoint) {
      const { signature, length } = chk.checkpoint
      return { signature, length, at: coreLength }
    }

    const len = coreLength - chk.checkpointer
    if (this.signatures.encryption && this.signatures.encryption.at === len) {
      return this.signatures.encryption
    }

    if (len <= 0) return null

    const { checkpoint } = await this.core.get(len - 1)
    if (!checkpoint || !checkpoint.encryption || !checkpoint.encryption.checkpoint) return null

    const { signature, length } = checkpoint.encryption.checkpoint
    return { signature, length, at: len }
  }

  async _inflateUserCheckpoint(chk, i, coreLength) {
    if (chk.checkpoint) {
      const { signature, length } = chk.checkpoint
      return { signature, length, at: coreLength }
    }

    const len = coreLength - chk.checkpointer
    if (i < this.signatures.user.length && this.signatures.user[i].at === len) {
      return this.signatures.user[i]
    }

    if (len <= 0) return null

    const { checkpoint } = await this.core.get(len - 1)
    if (!checkpoint || i >= checkpoint.user.length || !checkpoint.user[i].checkpoint) return null

    const { signature, length } = checkpoint.user[i].checkpoint
    return { signature, length, at: len }
  }
}

module.exports = class ApplyState extends ReadyResource {
  constructor(base) {
    super()

    this.base = base
    this.encryption = this.base.encryption
    this.valueEncoding = base.valueEncoding
    this.store = base._viewStore.atomize()
    this.key = null
    this.system = null
    this.view = null
    this.views = []
    this.systemView = null
    this.encryptionView = null
    this.hostcalls = null
    this.changes = base._hasUpdate ? new UpdateChanges(base) : null

    this.updates = []

    this.local = null
    this.localState = null

    this.fastForwarding = false
    this.indexersUpdated = false
    this.quorum = 0
    this.needsIndexedLengthUpdate = false
    this.interrupted = false
    this.applying = null
    this.applyBatch = null

    this.localCheckpoint = null
    this.localIndexer = false

    this.systemUpgrade = null

    this.checkpoints = []
    this.pendingViews = null
    this.pendingFork = null
    this.dirty = false
  }

  shouldFlush() {
    return this.dirty
  }

  async shouldWrite() {
    if (!this.localIndexer || !this.localCheckpoint || !this.localCheckpoint.core.opened) {
      return false
    }

    const info = await this.system.getIndexedInfo(this.indexedLength)
    if (!info.views.length) return false

    const { encryption, user } = this.localCheckpoint.signatures

    // todo: does this condition hold for soft-fork?
    if (info.views.length > user.length) return true

    for (let i = 0; i < info.views.length; i++) {
      if (user[i].length + SHOULD_SIGN_THRESHOLD < info.views[i].length) return true
    }

    // always flush encryption signature
    if (info.encryptionLength !== 0) {
      if (!encryption || encryption.length < info.encryptionLength) return true
    }

    return false
  }

  get indexedLength() {
    return this.systemView ? this.systemView.indexedLength : 0
  }

  get systemRef() {
    return this.systemView ? this.systemView.ref : null
  }

  async validateFork(indexerKeys, system) {
    if (!b4a.equals(system.key, this.system.core.key)) return false
    if (this.pendingIndexedLength() < system.length) return false
    for (const key of indexerKeys) {
      const info = await this.system.get(key)

      // writer should be active and we need manifest
      if (!info || !info.length || info.isRemoved) return false
    }
    return true
  }

  async shouldMigrate() {
    if (!this.fastForwarding && !this.indexersUpdated) return false
    if (this.system.indexers.length === 0) return false // genesis

    // sanity, prefer migration
    if (!this.system.core.manifest || !this.system.core.manifest.signers) return true

    // easy mode
    if (this.system.indexers.length !== this.system.core.manifest.signers.length) {
      return true
    }

    const manifests = await this.store.getIndexerManifests(this.system.indexers)

    for (let i = 0; i < this.system.core.manifest.signers.length; i++) {
      const { publicKey } = this.system.core.manifest.signers[i]
      if (!b4a.equals(publicKey, manifests[i].signers[0].publicKey)) return true
    }

    return false
  }

  isLocalPendingIndexer() {
    if (this.system.pendingIndexers.length === 0) return false
    const key = this.base.local.key
    for (const k of this.system.pendingIndexers) {
      if (b4a.equals(k, key)) return !b4a.equals(this.base.key, key) && this.base.local.length === 0
    }
    return false
  }

  removeable(key) {
    if (this.system.indexers.length !== 1) return true
    return !b4a.equals(this.system.indexers[0].key, key)
  }

  isLocalIndexer() {
    return !!this.localCheckpoint
  }

  _createCheckpointCore(key, active, signer, paused) {
    const encryption = this.base.getWriterEncryption(key)

    const session = this.base.store.get({
      key,
      valueEncoding: messages.OplogMessage,
      encryption,
      active
    })

    return new CheckpointCore(this, session, signer, paused)
  }

  async _openInternalView(name, indexedLength) {
    const core = this.store.get({ name })
    await core.ready()
    await core.setUserData('referrer', this.base.key)
    await core.setUserData('autobase/view', b4a.from(name))

    const ref = this.store.getViewByName(name)

    return { ref, core, indexedLength }
  }

  async _open() {
    try {
      await this._boot()
    } catch (err) {
      if (isViewCorruption(err)) {
        for (const v of this.store.opened) {
          await v.core.ready()
          await v.core.state.storage.deleteSessions()
        }
        if (this.systemView) {
          const core = this.systemView.ref.core
          await core.ready()
          await core.state.storage.deleteSessions()
        }
        if (this.encryptionView) {
          const core = this.encryptionView.ref.core
          await core.ready()
          await core.state.storage.deleteSessions()
        }

        await LocalState.clear(this.base.local)
      }

      await this._free()
      throw err
    }
  }

  async _boot() {
    const boot = await this.base._getBootRecord()

    this.systemView = await this._openInternalView('_system', boot.systemLength)
    this.encryptionView = await this._openInternalView('_encryption', -1)

    const sysCore = this.systemView.core
    if (sysCore.manifest.version >= 2) {
      if (this.encryption !== null) await this.encryption.reload(this.encryptionView.core)
    }

    const system = new SystemView(sysCore)
    await system.ready()

    // reset so we dont track _system or _encryption
    this.store.opened = []

    this.hostcalls = new PrivateApplyCalls(this)
    const view = this.base._hasOpen ? this.base._handlers.open(this.store, this.hostcalls) : null

    this.view = view
    this.system = system

    // ensure all are ready
    for (const v of this.store.opened) await v.atomicBatch.ready()

    this.key = system.core.key

    this.fastForwarding = boot.fastForwarding
    this.indexersUpdated = boot.indexersUpdated
    this.quorum = sysCore.manifest ? sysCore.manifest.quorum : 0

    const added = new Set()

    for (let i = 0; i < system.views.length; i++) {
      const { key, length } = system.views[i]
      const v = await this.store.findViewByKey(
        key,
        system.indexers,
        sysCore.manifest.version,
        system.entropy
      )

      if (v === null) {
        this.views.push({ name: null, key, length, core: null, ref: null, mappedIndex: i })
        continue
      }

      await v.atomicBatch.ready()
      await v.core.setUserData('referrer', this.base.key)
      await v.core.setUserData('autobase/view', b4a.from(v.name))

      this.views.push({ name: v.name, key, length, core: v.atomicBatch, ref: v, mappedIndex: i })

      added.add(v)
    }

    for (const v of this.store.opened) {
      if (added.has(v)) continue
      const core = v.atomicBatch

      this.views.push({
        name: v.name,
        key: core.key,
        length: core.length,
        core,
        ref: v,
        mappedIndex: -1
      })
    }

    this.local = this.store.getLocal()
    await this.local.ready()

    this.localState = new LocalState(this.local)

    let isLocalIndexer = false

    const paused = this.base.isFastForwarding()
    const inf = await this.system.getIndexedInfo()

    for (let i = 0; i < inf.indexers.length; i++) {
      const idx = inf.indexers[i]
      const chk = this._createCheckpointCore(idx.key, true, i, paused)
      await chk.ready()
      this.checkpoints.push(chk)
      if (b4a.equals(idx.key, this.base.local.key)) isLocalIndexer = true
    }

    const shouldSign = this.quorum > 0 && isLocalIndexer

    if (shouldSign) {
      this.localIndexer = true
      await this._startLocalCheckpoint()
    }

    await this._refreshWriters()

    // deferred
    this.maybeSigned().catch(noop)
  }

  async _startLocalCheckpoint() {
    for (const chk of this.checkpoints) {
      if (chk.core.id === this.base.local.id) {
        this.localCheckpoint = chk
        return
      }
    }

    this.localCheckpoint = this._createCheckpointCore(this.base.local.key, false, 0, false)
    await this.localCheckpoint.ready()
  }

  interrupt() {
    this.interrupted = true
    this.pause()
  }

  pause() {
    for (const chk of this.checkpoints) {
      if (chk !== this.localCheckpoint) chk.pause()
    }
  }

  resume() {
    for (const chk of this.checkpoints) {
      if (chk !== this.localCheckpoint) chk.resume()
    }
  }

  _checkSystemUpgrade() {
    if (this.systemUpgrade) return

    const tally = new Map()

    for (const chk of this.checkpoints) {
      if (chk.signedLength() <= this.system.core.signedLength) continue
      if (!chk.digest) continue

      const id = b4a.toString(chk.digest.key, 'hex')
      const cnt = (tally.get(id) || 0) + 1

      if (cnt >= this.quorum) {
        this.systemUpgrade = chk.digest.key
        this.base._queueStaticFastForward(this.systemUpgrade)
        return
      }

      tally.set(id, cnt)
    }
  }

  mapIndexToView(index) {
    for (const { mappedIndex, ref } of this.views) {
      if (mappedIndex === index) return ref
    }
  }

  async maybeSigned() {
    if (this.opened === false) await this.ready()
    if (this.interrupted) return

    const thres = this.checkpoints.length - this.quorum
    if (thres < 0 || this.checkpoints.length <= thres) return

    this.checkpoints.sort(cmpCheckpoints)

    const signableLength = this.checkpoints[thres].signedLength()
    if (signableLength <= this.system.core.signedLength) return

    const expected = this.system.core.key

    if (signableLength > this.indexedLength) {
      if (!b4a.equals(expected, this.checkpoints[thres].digest.key)) this._checkSystemUpgrade()
      this.needsIndexedLengthUpdate = true
      return
    }

    for (let i = thres; i < this.checkpoints.length; i++) {
      const chk = this.checkpoints[i]
      // we must agree on what the system is obvs
      if (!b4a.equals(expected, chk.digest.key)) {
        this._checkSystemUpgrade()
        return
      }
      // if we dont have the indexed state ourself, then no way for us to verify / patch
      if (!chk.signatures.system || chk.signatures.system.length > this.indexedLength) {
        this.needsIndexedLengthUpdate = true
        return
      }
    }

    this.needsIndexedLengthUpdate = false

    const chk = []
    for (let i = thres; i < this.checkpoints.length; i++) {
      chk.push({ signer: this.checkpoints[i].signer, signatures: this.checkpoints[i].signatures })
    }

    const { system } = this.checkpoints[thres].signatures

    await this._assembleMultisig(system.length, chk)
  }

  async _assembleMultisig(signableLength, checkpoints) {
    const views = new Array(this.views.length + 2) // +2 is system + encryption

    const sys = await this.system.getIndexedInfo(signableLength)

    if (this.interrupted) return

    if (this.pendingViews && this.pendingViews[0].length >= signableLength) {
      return
    }

    views[0] = createCheckpointSignature(signableLength, this.systemView, checkpoints.length)

    if (sys.encryptionLength) {
      views[1] = createCheckpointSignature(
        sys.encryptionLength,
        this.encryptionView,
        checkpoints.length
      )
    }

    const offset = 2 // system + encryption

    for (let i = offset; i < views.length; i++) {
      const view = this.views[i - offset]
      const core = view.core

      const v = this.getViewFromSystem(view, sys)
      const length = v ? v.length : 0

      if (!core || length <= core.signedLength) continue

      const viewIndex = view.mappedIndex + offset
      views[viewIndex] = createCheckpointSignature(length, view, checkpoints.length)
    }

    for (let i = 0; i < checkpoints.length; i++) {
      addCheckpointSignatures(views, checkpoints, i)
    }

    const promises = []
    for (const view of views) {
      if (!view) continue

      for (let i = 0; i < view.signatures.length; i++) {
        promises.push(setPartialSignature(view, i))
      }
    }

    await Promise.all(promises)

    // check that the state still looks good, couple replicate inbetween...
    for (const v of views) {
      if (!v) continue

      for (let i = 0; i < v.signatures.length; i++) {
        if (!v.partials[i]) return
      }
    }

    if (this.interrupted) return

    if (this.pendingViews && this.pendingViews[0].length >= signableLength) {
      return
    }
    // skipped system for whatever reason...
    if (!views[0]) return

    this.pendingViews = views
    this.dirty = true

    // TODO: only needed if not updating, wont crash so keeping for now, just less efficient
    this.base._queueBump()
  }

  _close() {
    if (this.interrupted) return
    return this._free()
  }

  async _free() {
    this.interrupted = true
    if (this.applying) this._postApply()
    for (const chk of this.checkpoints) await chk.close()
    if (this.localCheckpoint) await this.localCheckpoint.close()
    if (this.view && this.base._hasClose) await this.base._handlers.close(this.view)
    if (this.system) await this.system.close()

    const promises = []
    for (const v of this.views) {
      if (v.ref) promises.push(v.ref.release())
    }

    if (this.systemView) promises.push(this.systemView.ref.release())
    if (this.encryptionView) promises.push(this.encryptionView.ref.release())

    await Promise.all(promises)
    await this.store.close()
  }

  _pushUpdate(u) {
    u.version = 1
    u.seq = this.updates.length === 0 ? 0 : this.updates[this.updates.length - 1].seq + 1
    u.systemLength = this.systemView.core.length
    this.updates.push(u)
    this.localState.insertUpdate(u)
  }

  async catchup(linearizer) {
    if (!this.opened) await this.ready()
    if (!this.system.heads.length) return true

    const writers = new Map()

    // load linearizer...
    const updates = await this.localState.listUpdates()
    const sys = await this.system.checkout(this.indexedLength)

    for (const node of updates) {
      const hex = b4a.toString(node.key, 'hex')

      let w = writers.get(hex)

      if (w === undefined) {
        // TODO: we actually have all the writer info already but our current methods make it hard to reuse that
        w = await this.base._getWriterByKey(node.key, -1, 0, true, false, sys)
        writers.set(hex, w)
      }

      if (w.length >= node.length) {
        this.base._warn(new Error('Update expects writer to be consumed here'))
        return false
      }

      while (w.length < node.length) {
        await w.update(sys)

        const next = w.advance()
        if (!next) {
          this.base._warn(new Error('Node must exist for catchup'))
          return false
        }

        linearizer.addHead(next)
      }
    }

    await sys.close()

    this.updates = updates

    if (this.indexersUpdated) {
      this.indexersUpdated = false
      // if we updated the indexers, invalidate all the internal state and reapply it
      await this.truncate(this.indexedLength)
      await this._rollbackViews()

      if (this.tx === null) this.tx = this.local.state.storage.write()

      while (
        this.updates.length > 0 &&
        this.updates[this.updates.length - 1].systemLength >= this.indexedLength
      ) {
        const u = this.updates.pop()
        this.localState.deleteUpdate(u)
      }
    } else {
      // otherwise we know the internal state is correct, so we carry on
      linearizer.update()
    }

    // must refresh the writers here so isRemoved is up to date
    await this._refreshWriters()
    return true
  }

  async getIndexedSystem() {
    if (this.opened === false) await this.ready()

    const indexedLength = this.pendingFork ? this.pendingFork.length : this.indexedLength

    const sys = await this.system.checkout(indexedLength)
    await sys.ready()
    return sys
  }

  getViewFromSystem(view, sys = this.system) {
    if (view.mappedIndex === -1 || view.mappedIndex >= sys.views.length) return null
    return sys.views[view.mappedIndex]
  }

  async recoverAt() {
    if (!this.systemRef) await this.ready()

    await this.systemRef.core.ready()

    const lt = this.systemRef.core.core.state.length

    for await (const { length, info } of SystemView.flushes(this.systemRef.core.session(), {
      reverse: true,
      lt
    })) {
      let consistent = true

      for (let i = 0; i < info.views.length; i++) {
        if (i >= this.views.length) continue
        if (!b4a.equals(info.views[i].key, this.views[i].key)) continue

        if (info.views[i].length > this.views[i].core.core.state.length) {
          consistent = false
          break
        }
      }

      if (consistent) {
        return {
          length,
          force: true,
          key: this.system.core.key,
          indexers: info.indexers,
          views: info.views
        }
      }
    }

    return null
  }

  bootstrap() {
    return this.system.add(this.base.key, { isIndexer: true, isPending: false })
  }

  async undo(popped) {
    if (!popped) return

    let indexersUpdated = false
    while (popped > 0) {
      const u = this.updates.pop()
      this.localState.deleteUpdate(u)
      popped -= u.batch
      if (u.indexers) indexersUpdated = true
    }

    const u = this.updates.length === 0 ? null : this.updates[this.updates.length - 1]
    const systemLength = u ? u.systemLength : this.indexedLength

    await this.truncate(systemLength)
    if (indexersUpdated) await this._rollbackViews()
  }

  async truncate(systemLength) {
    if (this.opened === false) await this.ready()
    if (systemLength === this.system.core.length) return

    await this.system.core.truncate(systemLength)

    const migrated = await this.system.update()

    if (this.encryptionView.core.length !== this.system.encryptionLength) {
      await this.encryptionView.core.truncate(this.system.encryptionLength)
    }

    for (const view of this.views) {
      if (!view.core) continue

      const v = this.getViewFromSystem(view)

      if (v && view.core.length === v.length) continue
      if (v === null) view.mappedIndex = -1 // unmap

      await view.core.truncate(v ? v.length : 0)
    }

    if (!migrated) return

    await this._refreshWriters()
    await this._rollbackViews()
  }

  async _refreshWriters() {
    // TODO: add the seq at which we updated the state to the writer instance.
    // then we know if it was truncated out without the lookup, meaning faster truncations
    for (const w of this.base.activeWriters) {
      const data = await this.system.get(w.core.key)
      const bootstrapper = this.system.core.length === 0 && b4a.equals(w.core.key, this.base.key)
      const isRemoved = data ? data.isRemoved : !bootstrapper
      w.isRemoved = isRemoved
    }
  }

  async _updateSystem() {
    if (!(await this.system.update())) return
    await this._refreshWriters()
    await this._rollbackViews()
  }

  async _signViewCore(core, length) {
    const s = await core.signable(length, 0)
    const signature = crypto.sign(s, this.base.local.keyPair.secretKey)
    return { signature, length }
  }

  async _signInternalViewCores(sys) {
    return {
      system: await this._signViewCore(this.systemView.core, this.systemView.indexedLength),
      encryption: await this._signViewCore(this.encryptionView.core, sys.encryptionLength)
    }
  }

  async _signUserViewCores(sys) {
    const promises = new Array(sys.views.length)

    for (let i = 0; i < this.views.length; i++) {
      const view = this.views[i]

      const v = this.getViewFromSystem(view, sys)
      const indexedLength = v ? v.length : 0

      if (!indexedLength) continue

      const viewIndex = view.mappedIndex
      promises[viewIndex] = this._signViewCore(view.ref.atomicBatch, indexedLength)
    }

    return Promise.all(promises)
  }

  async finalize(key) {
    this.localState.setBootRecord({
      version: BOOT_RECORD_VERSION,
      key,
      systemLength: this.systemView.indexedLength,
      indexersUpdated: true,
      fastForwarding: false,
      recoveries: this.base.recoveries
    })

    await this.localState.flush()

    await this.store.flush()
    await this.close()
  }

  async _flush(localNodes) {
    if (localNodes) await this._appendLocalNodes(localNodes)

    if (this.localCheckpoint) {
      // we have to flush here so the chkpoint can update
      // could run the checkpoint on the batch but also no big dead
      // as the "should we sign" check is rerun on boot...
      await this.store.flush()
      await this.localCheckpoint.update()
    }

    this.localState.setBootRecord({
      version: BOOT_RECORD_VERSION,
      key: this.key,
      systemLength: this.systemView.indexedLength,
      indexersUpdated: false,
      fastForwarding: false,
      recoveries: this.base.recoveries
    })

    await this.localState.flush()

    if (this.pendingViews) {
      const views = this.pendingViews
      this.pendingViews = null

      for (let i = views.length - 1; i >= 0; i--) {
        const v = views[i]
        if (!v || v.length <= v.core.signedLength) continue
        const signature = v.core.core.verifier.assemble(v.partials)
        try {
          await v.ref.commit(this.store.atom, v.length, signature)
        } catch (err) {
          if (isAssertion(err)) {
            throw err
          }

          // TODO: we should prevalidate all signatures instead of during commit so it can be all or nothing, just slighly
          // friendlier ux. missing hc api for that
          if (!this.base.closing) this.base._warn(err)
          break
        }
      }
    }

    await this.store.flush()

    this.fastForwarding = false
    if (this.pendingViews === null) this.dirty = false
  }

  _indexUpdates(indexed) {
    let shift = 0
    while (indexed > 0) indexed -= this.updates[shift++].batch

    const last = this.updates[shift - 1]

    this.systemView.indexedLength = last.systemLength

    for (let i = 0; i < shift; i++) this.localState.deleteUpdate(this.updates[i])
    this.updates.splice(0, shift)

    if (!this.needsIndexedLengthUpdate) return
    this.maybeSigned().catch(noop)
  }

  pendingIndexedLength() {
    let indexed = this.applying.indexed.length
    if (!this.applying || !this.updates.length || !indexed) return this.indexedLength

    let pos = 0
    while (indexed > 0 && pos < this.updates.length) {
      indexed -= this.updates[pos++].batch
    }

    const last = this.updates[pos - 1]
    return last.systemLength
  }

  async _assertNode(node, batch) {
    // helpful dag helper, so kept here

    const v = (await this.system.get(node.writer.core.key)) || { length: 0, isRemoved: false }
    const expected = v.length + batch
    if (node.length === expected) return

    console.trace(
      'INVALID_INSERTION',
      'length=',
      node.length,
      'key=',
      node.writer.core.key,
      'local=',
      node.writer.core.writable,
      'batch=',
      batch,
      'dag=',
      v
    )

    process.exit(1)
  }

  _postApply() {
    this.applyBatch = this.applying = null
    this.base._postApply()
  }

  async _optimisticApply(u, node, indexed) {
    const checkpoint = this.system.checkpoint()

    this.system.addHead(node)

    const applyBatch = []
    const key = node.writer.core.key

    applyBatch.push({
      indexed,
      optimistic: true,
      from: node.writer.core,
      length: node.length,
      value: node.value,
      heads: node.actualHeads
    })

    const pre = await this.system.get(key)
    const preLength = pre ? pre.length : 0

    let failed = false

    this.applying = u
    this.applyBatch = applyBatch
    try {
      await this.base._handlers.apply(applyBatch, this.view, this.hostcalls)
    } catch (err) {
      if (this.base.closing) throw err
      failed = true
    }
    this._postApply()

    if (!failed) {
      const post = await this.system.get(key)
      // check if acked by addWriter/removeWriter/ackWriter
      if (!post || preLength === post.length) failed = true
    }

    if (!failed) {
      // technically we only need to to this is the writer was removed, but hey, tricky logic
      await this._refreshWriters()
      return true
    }

    // it failed! rollback...

    this.system.applyCheckpoint(checkpoint)

    if (this.encryptionView.core.length !== this.system.encryptionLength) {
      await this.encryptionView.core.truncate(this.system.encryptionLength)
    }

    for (const view of this.views) {
      const viewLength = view.core ? view.core.length : view.length
      const viewLookup = this.getViewFromSystem(view)
      const viewSystemLength = viewLookup ? viewLookup.length : 0
      if (viewSystemLength === viewLength) continue
      await view.core.truncate(viewSystemLength)
    }

    await this._refreshWriters()

    await this._rollbackViews()
    return false
  }

  _startTrace(node) {
    this.systemRef.tracer.start()
    this.encryptionView.ref.tracer.start()
    for (let i = 0; i < this.views.length; i++) this.views[i].ref.tracer.start()
  }

  _endTrace(node) {
    const trace = {
      system: this.systemRef.tracer.end(),
      encryption: this.encryptionView.ref.tracer.end(),
      user: []
    }

    for (let i = 0; i < this.views.length; i++) {
      const blocks = this.views[i].ref.tracer.end()
      if (blocks.length) trace.user.push({ view: i, blocks })
    }

    if (trace.system.length || trace.encryption.length || trace.user.length) node.trace = trace
  }

  async update(u, localNodes) {
    if (this.changes !== null) this.changes.track(this)

    let batch = 0
    let applyBatch = []
    let indexersUpdated = 0

    let j = 0
    let i = 0
    let forkedAt = -1

    while (i < Math.min(u.indexed.length, u.shared)) {
      const node = u.indexed[i++]

      if (node.batch > 1) continue
      this.base._shiftWriter(node.writer)

      const update = this.updates[j++]

      if (update.indexers) {
        indexersUpdated = i
        break
      }
    }

    if (u.undo) await this.undo(u.undo)

    if (this.system.bootstrapping) await this.bootstrap()

    await this._updateSystem()

    // Organize by view
    const warmupSystemView = []
    const warmupEncryptionView = []
    const warmupUserView = new Array(this.views.length)

    for (let k = u.shared; k < u.length; k++) {
      const indexed = k < u.indexed.length
      const node = indexed ? u.indexed[k] : u.tip[k - u.indexed.length]
      if (!node.trace) continue

      if (node.trace.system.length) warmupSystemView.push(...node.trace.system)
      if (node.trace.encryption.length) warmupEncryptionView.push(...node.trace.encryption)

      for (const trace of node.trace.user) {
        // Assert (as warning) that trace view should only be currently indexed views
        if (trace.view >= this.views.length) {
          console.warn(
            'Oplog block trace contains OOB view index',
            'trace view',
            trace.view,
            'views.length',
            this.views.length
          )
          continue
        }

        warmupUserView[trace.view] = warmupUserView[trace.view] || []
        warmupUserView[trace.view].push(...trace.blocks)
      }
    }

    // Request per view
    if (warmupSystemView.length) this.systemView.core.download({ blocks: warmupSystemView })
    if (warmupEncryptionView.length)
      this.encryptionView.core.download({ blocks: warmupEncryptionView })
    for (let k = 0; k < warmupUserView.length; k++) {
      const blocks = warmupUserView[k]
      if (!blocks) continue

      const view = this.views[k]
      view.core.download({ blocks })
    }

    for (i = u.shared; i < u.length; i++) {
      if (this.base.backoff !== null && this.base.backoff.backoff()) await this.base.backoff.wait()

      const indexed = i < u.indexed.length
      const node = indexed ? u.indexed[i] : u.tip[i - u.indexed.length]

      batch++

      if (node.writer.core.writable) this._startTrace(node)

      const optimist =
        node.writer.isRemoved &&
        node.optimistic &&
        batch === 1 &&
        this.base._hasOptimisticApply === true &&
        (await this._optimisticApply(u, node, indexed))

      if (!optimist) {
        if (node.writer.isRemoved && !node.writer.isActiveIndexer) {
          if (node.batch > 1) continue
          // in case someone is linking this node and they are not removed
          const u = {
            seq: 0,
            key: node.writer.core.key,
            length: node.length,
            batch,
            systemLength: 0,
            indexers: false
          }
          this._pushUpdate(u)
          batch = 0
          assert(applyBatch.length === 0, 'Apply batch should not have been modified')
          continue
        }

        // in prod we prop need to disable this assertion as its pretty expensive,
        // but it catches a lot of bugs, so here for debugs
        // await this._assertNode(node, batch)

        const deps = node.causalDependencies()

        // oldest -> newest
        for (let i = deps.length - 1; i >= 1; i--) {
          const d = deps[i]
          if (await this.system.linkable(d.writer.core.key, d.length)) {
            this.system.addHead(deps[i])
          }
        }

        this.system.addHead(deps[0])

        if (node.value !== null && !node.writer.isRemoved) {
          applyBatch.push({
            indexed,
            optimistic: false,
            from: node.writer.core,
            length: node.length,
            value: node.value,
            heads: node.actualHeads
          })
        }

        if (node.batch > 1) continue

        if (applyBatch.length && this.base._hasApply === true) {
          this.applying = u
          this.applyBatch = applyBatch
          await this.base._handlers.apply(applyBatch, this.view, this.hostcalls)
          if (forkedAt === -1 && this.pendingFork) forkedAt = i
          this._postApply()
        }
      }

      const update = {
        seq: 0,
        key: node.writer.core.key,
        length: node.length,
        batch,
        systemLength: 0,
        indexers: false
      }

      update.indexers = !!this.system.indexerUpdate

      if (this.system.indexerUpdate) await this._generateNextViews()

      await this.system.flush(this.views)
      await this.system.update()

      if (node.writer.core.writable) this._endTrace(node)

      batch = 0
      applyBatch = []

      this._pushUpdate(update)

      if (!indexed || indexersUpdated) continue

      this.base._shiftWriter(node.writer)

      if (update.indexers) {
        indexersUpdated = i + 1
      }
    }

    if (this.pendingFork) {
      const pending = this.pendingFork
      if (pending.length > this.indexedLength) this._indexUpdates(u.indexed.length)

      const fork = new Fork(this.base, this.store, this, pending)
      const forked = await fork.upgrade()

      if (!forked) throw new Error('Fork failed')

      await this._flush(localNodes)

      return {
        reboot: true,
        migrated: false
      }
    }

    if (u.indexed.length) {
      this._indexUpdates(indexersUpdated || u.indexed.length)
    }

    const migrated = indexersUpdated !== 0
    if (migrated) this.key = await this.base._premigrate()

    if (this.changes !== null) {
      this.changes.finalise()
      await this.base._handlers.update(this.view, this.changes)
    }

    await this._flush(localNodes)

    return {
      reboot: migrated,
      migrated
    }
  }

  flush() {
    return this._flush(null)
  }

  async _appendLocalNodes(localNodes) {
    if (localNodes.length === 0) return // just in case

    const blocks = new Array(localNodes.length)
    const local = this.local

    if (!local.opened) await local.ready()

    for (let i = 0; i < blocks.length; i++) {
      const { value, heads, batch, optimistic, trace } = localNodes[i]

      blocks[i] = {
        version: OPLOG_VERSION,
        maxSupportedVersion: this.base.maxSupportedVersion,
        checkpoint: null,
        digest: null,
        optimistic,
        node: {
          heads,
          batch,
          value: value === null ? null : c.encode(this.base.valueEncoding, value)
        },
        trace
      }
    }

    if (this.localIndexer) {
      const signedLength = this.localCheckpoint.signedLength()
      const local = this.local

      let signedAt = 0
      let internalSignatures = null
      let signatures = null

      if (this.indexedLength > signedLength) {
        const sys = await this.system.getIndexedInfo(this.indexedLength)
        internalSignatures = await this._signInternalViewCores(sys)
        signatures = await this._signUserViewCores(sys)
        signedAt = local.length + blocks.length
      }

      for (let i = 0; i < blocks.length; i++) {
        const length = local.length + i + 1
        if (length === signedAt) {
          this.localCheckpoint.updateInternalSignatures(length, internalSignatures)
          this.localCheckpoint.updateUserSignatures(length, signatures)
        }

        const blk = blocks[i]

        blk.checkpoint = this.localCheckpoint.makeCheckpoints(length)
        blk.digest = this.localCheckpoint.makeDigest(length, this.key)
      }
    } else {
      if (!this.localCheckpoint) await this._startLocalCheckpoint()

      for (let i = 0; i < blocks.length; i++) {
        const length = local.length + i + 1
        blocks[i].digest = this.localCheckpoint.makeDigest(length, this.key)
      }
    }

    await local.append(blocks)
  }

  async _rollbackViews() {
    // encryption view key is not in system so no need to handle here
    for (const view of this.views) {
      const v = this.getViewFromSystem(view)

      if (v) {
        view.key = v.key
      } else {
        await this._resetView(view)
      }
    }
  }

  async createAnchor() {
    const node = this.applyBatch[this.applyBatch.length - 1]
    const key = node.from.key
    const length = node.length

    const info = await this.system.get(key, { unflushed: true })

    if (!info || info.length < length) throw new Error('Anchor node is not in system')

    const state = { start: 0, end: 40, buffer: b4a.alloc(40) }
    c.fixed32.encode(state, key)
    c.uint64.encode(state, length)

    const namespace = crypto.hash(state.buffer)
    const manifestData = c.encode(messages.ManifestData, { version: 0, legacyBlocks: 0, namespace })

    const padding = this.encryption ? AutobaseEncryption.PADDING : 0
    const block = encodeValue(null, { heads: [{ key, length }], padding })
    if (this.encryption) await this.encryption.encryptAnchor(block, namespace)

    const root = { index: 0, size: block.byteLength, hash: crypto.data(block) }
    const hash = crypto.tree([root])
    const prologue = { hash, length: 1 }

    const core = this.store.createAnchorCore(prologue, manifestData)
    await core.ready()

    if (core.length === 0) await core.append(block, { writable: true, maxLength: 1 })

    await this.system.add(core.key, { isIndexer: false, length: 0 })
    await this.base._addWriter(core.key, this.system)

    const anchor = { key: core.key, length: core.length }

    await core.close()
    await this.base.hintWakeup(anchor)

    return anchor
  }

  async _resetView(view) {
    const manifests = await this.store.getIndexerManifests(this.system.indexers)

    const manifestData = view.core ? view.core.manifest.userData : null
    view.key = await this.store.createView(
      manifests,
      view.name,
      null,
      this.system.core.manifest.version,
      this.system.entropy,
      null,
      manifestData
    ) // will never be system so no linked
    view.length = 0
  }

  async _generateNextViews() {
    const sys = this.system

    // note, this is very state dependent so can ONLY be called at the exact time an indexer upgrade occurs
    const manifests = await this.store.getIndexerManifests(sys.indexers)
    const entropy = sys.version < 2 ? null : sys.getEntropy(sys.indexers, sys.flushLength())

    for (const v of this.views) {
      const manifestData = v.core ? v.core.manifest.userData : null

      const prologue = await getPrologue(v)
      const key = await this.store.createView(
        manifests,
        v.name,
        prologue,
        sys.core.manifest.version,
        entropy,
        null,
        manifestData
      )

      v.key = key
    }
  }
}

async function getPrologue(view) {
  const length = view.core ? view.core.length : view.length
  if (!length) return null

  const hash = await view.core.treeHash(length)

  return {
    hash,
    length
  }
}

function noop() {}

function cmpCheckpoints(a, b) {
  return a.signedLength() - b.signedLength()
}

function sameSignature(a, b) {
  if (!a || !b) return a === b
  return a.length === b.length
}

function sameSignatures(a, b) {
  if (!a || !b) return a === b
  if (a.length !== b.length) return false
  for (let i = 0; i < a.length; i++) {
    if (a[i].length !== b[i].length) return false
  }
  return true
}

function createCheckpointSignature(length, view, checkpoints) {
  return {
    length,
    core: view.core,
    ref: view.ref,
    signatures: new Array(checkpoints),
    partials: new Array(checkpoints)
  }
}

function addCheckpointSignatures(pending, checkpoints, index) {
  const { signer, signatures } = checkpoints[index]

  pending[0].signatures[index] = {
    signature: signatures.system.signature,
    length: signatures.system.length,
    signer
  }

  if (pending[1]) {
    pending[1].signatures[index] = {
      signature: signatures.encryption.signature,
      length: signatures.encryption.length,
      signer
    }
  }

  for (let i = 2; i < pending.length; i++) {
    if (!pending[i]) continue

    const { length, signature } = signatures.user[i - 2]

    pending[i].signatures[index] = {
      signature,
      length,
      signer
    }
  }
}

async function setPartialSignature(view, index) {
  const sig = view.signatures[index]
  if (sig.length < view.length && sig.length > 0) await view.core.get(sig.length - 1)

  view.partials[index] = await partialSignature(
    view.core,
    sig.signer,
    view.length,
    sig.length,
    sig.signature
  )
}

function updateSignature(length, sig, existing) {
  return sig ? { signature: sig.signature, length: sig.length, at: length } : existing
}

function updateSignatures(length, signatures, existing) {
  const updated = new Array(signatures.length)

  for (let i = 0; i < updated.length; i++) {
    updated[i] = updateSignature(length, signatures[i], i < existing.length ? existing[i] : null)
  }

  return updated
}

function makeCheckpoint(length, chk) {
  if (!chk) return null

  const checkpointer = length - chk.at

  return {
    checkpointer,
    checkpoint: checkpointer === 0 ? { signature: chk.signature, length: chk.length } : null
  }
}

function makeCheckpoints(length, signatures) {
  if (!signatures.length) return null

  const checkpoints = new Array(signatures.length)

  for (let i = 0; i < signatures.length; i++) {
    checkpoints[i] = makeCheckpoint(length, signatures[i])
  }

  return checkpoints
}

function isViewCorruption(err) {
  return err.code === 'INVALID_OPERATION'
}

function isAssertion(err) {
  return err.code === 'ERR_ASSERTION' || err.name === 'AssertionError'
}
const c = require('compact-encoding')
const encryptionEncoding = require('encryption-encoding')
const messages = require('./messages.js')

module.exports = async function boot(
  corestore,
  key,
  { encrypt, encryptionKey, keyPair, exclusive = true, blindEncryption } = {}
) {
  const result = {
    key: null,
    local: null,
    bootstrap: null,
    encryptionKey: null,
    boot: null
  }

  const manifest = keyPair
    ? { version: corestore.manifestVersion, signers: [{ publicKey: keyPair.publicKey }] }
    : null

  if (key) {
    result.key = key

    const bootstrap = corestore.get({ key, active: false, valueEncoding: messages.OplogMessage })
    await bootstrap.ready()

    const localKey = await bootstrap.getUserData('autobase/local')

    if (keyPair) {
      result.local = corestore.get({
        keyPair,
        active: false,
        exclusive,
        valueEncoding: messages.OplogMessage,
        manifest
      })
    } else {
      if (bootstrap.writable && !localKey) {
        result.local = bootstrap.session({
          active: false,
          exclusive,
          valueEncoding: messages.OplogMessage
        })
      } else {
        const local = localKey
          ? corestore.get({
              key: localKey,
              active: false,
              exclusive,
              valueEncoding: messages.OplogMessage
            })
          : corestore.get({
              name: 'local',
              active: false,
              exclusive,
              valueEncoding: messages.OplogMessage
            })

        await local.ready()
        result.local = local
      }
    }

    result.bootstrap = bootstrap
  } else {
    result.local = keyPair
      ? corestore.get({
          keyPair,
          manifest,
          active: false,
          exclusive,
          valueEncoding: messages.OplogMessage
        })
      : corestore.get({
          name: 'local',
          active: false,
          exclusive,
          valueEncoding: messages.OplogMessage
        })
    await result.local.ready()

    const key = await result.local.getUserData('referrer')
    if (key) {
      result.key = key
      result.bootstrap = corestore.get({ key, active: false, valueEncoding: messages.OplogMessage })
      await result.bootstrap.ready()
    } else {
      result.key = result.local.key
      result.bootstrap = result.local.session({
        active: false,
        valueEncoding: messages.OplogMessage
      })
      await result.bootstrap.setUserData('autobase/local', result.local.key)
    }
  }

  if (key || keyPair) {
    await result.bootstrap.setUserData('referrer', result.key)
    await result.bootstrap.setUserData('autobase/local', result.local.key)
    await result.local.setUserData('referrer', result.key)
  }

  const [encryptionKeyBuffer, encryptionKeyEncryptedBuffer, pointer] = await Promise.all([
    result.local.getUserData('autobase/encryption'),
    result.local.getUserData('autobase/blind-encryption'),
    result.local.getUserData('autobase/boot')
  ])

  if (pointer) {
    result.boot = c.decode(messages.BootRecord, pointer)
  }

  if (encryptionKeyBuffer) {
    // if not encoded, replace
    if (blindEncryption) {
      const encrypted = await encryptionEncoding.encrypt(
        encryptionKeyBuffer,
        blindEncryption.encrypt
      )
      await result.local.setUserData('autobase/blind-encryption', encrypted)
      await result.local.setUserData('autobase/encryption', null)
    }

    result.encryptionKey = encryptionKeyBuffer
  }

  if (encryptionKeyEncryptedBuffer) {
    const { value, rotated } = await encryptionEncoding.decrypt(
      encryptionKeyEncryptedBuffer,
      blindEncryption.decrypt
    )

    if (rotated) {
      const encrypted = await encryptionEncoding.encrypt(value, blindEncryption.encrypt)
      await result.local.setUserData('autobase/blind-encryption', encrypted)
    }

    result.encryptionKey = value
  }

  if (!result.encryptionKey && (encryptionKey || encrypt)) {
    if (!encryptionKey) {
      encryptionKey = (await corestore.createKeyPair('autobase/encryption')).secretKey.subarray(
        0,
        32
      )
    }

    if (blindEncryption) {
      const encrypted = await encryptionEncoding.encrypt(encryptionKey, blindEncryption.encrypt)
      await result.local.setUserData('autobase/blind-encryption', encrypted)
    } else {
      await result.bootstrap.setUserData('autobase/encryption', encryptionKey) // legacy support
      await result.local.setUserData('autobase/encryption', encryptionKey)
    }
    result.encryptionKey = encryptionKey
  }

  return result
}
const crypto = require('hypercore-crypto')

const OPLOG_VERSION = 2
const DEFAULT_AUTOBASE_VERSION = 1 // default
const MAX_AUTOBASE_VERSION = 2 // optional fork support
const BOOT_RECORD_VERSION = 3

const [NS_SIGNER_NAMESPACE, NS_VIEW_BLOCK_KEY, NS_HASH_KEY, NS_ENCRYPTION] = crypto.namespace(
  'autobase',
  4
)

module.exports = {
  OPLOG_VERSION,
  DEFAULT_AUTOBASE_VERSION,
  MAX_AUTOBASE_VERSION,
  BOOT_RECORD_VERSION,
  NS_SIGNER_NAMESPACE,
  NS_VIEW_BLOCK_KEY,
  NS_HASH_KEY,
  NS_ENCRYPTION
}
const BufferMap = require('tiny-buffer-map')

// This is basically just a Map atm, but leaving it as an abstraction for now
// in case we wanna optimize it for our exact usecase

module.exports = class Clock {
  constructor() {
    this.seen = new BufferMap()
  }

  get size() {
    return this.seen.size
  }

  has(key) {
    return this.seen.has(key)
  }

  includes(key, length) {
    return this.seen.has(key) && this.seen.get(key) >= length
  }

  get(key) {
    return this.seen.get(key) || 0
  }

  set(key, len) {
    this.seen.set(key, len)
    return len
  }

  add(clock) {
    for (const [key, l] of clock) {
      if (this.get(key) < l) this.set(key, l)
    }
  }

  [Symbol.iterator]() {
    return this.seen[Symbol.iterator]()
  }
}
const BufferMap = require('tiny-buffer-map')

const Clock = require('./clock.js')

const UNSEEN = 0
const NEWER = 1
const ACKED = 2

// Consensus machine for Autobase. Sort DAG nodes using
// vector clocks to determine a globally consistent view

module.exports = class Consensus {
  constructor(indexers) {
    this.merges = new Set()
    this.majority = (indexers.length >>> 1) + 1
    this.indexers = indexers
    this.removed = new Clock()
    this.updated = false

    this.writers = new BufferMap()
    for (const idx of this.indexers) {
      this.writers.set(idx.core.key, idx)
    }
  }

  addHead(node) {
    if (!node.writer.isActiveIndexer) return
    if (this._isMerge(node)) this.merges.add(node)
    this.updated = true
    return node
  }

  /* Indexer Only DAG methods */

  _tails(node, tails) {
    const tailSet = new Set()
    for (const t of tails) {
      if (node.clock.includes(t.writer.core.key, t.length)) tailSet.add(t)
    }

    return tailSet
  }

  _tailsAndMerges(node, tails) {
    const all = this._tails(node, tails)
    for (const m of this.merges) {
      if (m !== node && node.clock.includes(m.writer.core.key, m.length)) {
        all.add(m)
      }
    }
    return all
  }

  _isMerge(node) {
    if (!node.writer.isActiveIndexer) return false

    const deps = []

    for (const idx of this.indexers) {
      let seq = node.clock.get(idx.core.key) - 1

      if (idx === node.writer) seq--

      const head = idx.get(seq)
      if (!head || this.removed.includes(head.writer.core.key, head.length)) continue

      let isDep = true
      for (let i = 0; i < deps.length; i++) {
        const d = deps[i]
        if (d === head) continue

        if (d.clock.includes(head.writer.core.key, head.length)) {
          isDep = false
          break
        }

        if (head.clock.includes(d.writer.core.key, d.length)) {
          const popped = deps.pop()
          if (d === popped) continue
          deps[i--] = popped
        }
      }

      if (isDep) deps.push(head)
    }

    return deps.length > 1
  }

  _indexerTails() {
    const tails = new Set()
    for (const idx of this.indexers) {
      const length = this.removed.has(idx.core.key) ? this.removed.get(idx.core.key) : idx.indexed

      const head = idx.get(length)
      if (!head || this.removed.includes(head.writer.core.key, head.length)) continue

      let isTail = true
      for (const t of tails) {
        if (head.clock.includes(t.writer.core.key, t.length)) {
          isTail = false
          break
        }

        if (t.clock.includes(head.writer.core.key, head.length)) {
          tails.delete(t)
        }
      }

      if (isTail) tails.add(head)
    }

    return tails
  }

  // parent is newer if for any node in parent's view,
  // either node can see object or object can see node
  _strictlyNewer(object, parent) {
    if (!parent.clock.includes(object.writer.core.key, object.length)) return false

    for (const [key, latest] of parent.clock) {
      const oldest = this.removed.get(key)
      if (latest <= oldest) continue // check quickly if we removed it

      // get the NEXT node from the writer from the objects pov, adjust if its removed
      let length = object.clock.get(key)
      if (length <= oldest) length = oldest

      // sanity check, likely not needed as someone has checked this before, but it's free
      if (latest < length) return false

      // if the same, they have both seen it, continue
      if (latest === length) continue

      const writer = this.writers.get(key)

      // might not be in the removed set but the writer can tell us if it was indexed...
      const next = writer && writer.get(length >= writer.indexed ? length : writer.indexed)

      // no next, its been indexed, both seen it
      if (!next) continue

      // if the NEXT node has seen the object its fine - newer
      if (next.clock.includes(object.writer.core.key, object.length)) continue

      // otherwise the parent must also NOT have seen the next node
      if (latest < next.length) continue

      return false
    }

    return true
  }

  _acks(target) {
    const acks = target.writer.isActiveIndexer ? [target] : [] // TODO: can be cached on the target node in future (ie if we add one we dont have to check it again)

    for (const idx of this.indexers) {
      if (idx === target.writer) continue

      let next = target.clock.get(idx.core.key)
      if (next < idx.nodes.offset) next = idx.nodes.offset

      const nextIndexNode = idx.get(next >= idx.indexed ? next : idx.indexed)

      // no node - no ack
      if (!nextIndexNode) continue

      // if the next index node does not see the target, no ack
      if (!nextIndexNode.clock.includes(target.writer.core.key, target.length)) continue

      // if the next index node is not strictly newer, skip to avoid ambig...
      if (!this._strictlyNewer(target, nextIndexNode)) continue

      acks.push(nextIndexNode)
    }

    return acks
  }

  acksFromNode(target, view) {
    const acks = new Set()

    if (!view || !view.clock.includes(target.writer.core.key, target.length)) return acks

    acks.add(view.writer)

    for (const idx of this.indexers) {
      if (idx === view.writer) continue

      const length = view.clock.get(idx.core.key)
      if (!length) continue

      if (target.clock.includes(idx.core.key, length)) continue

      const head = idx.get(length - 1)
      if (!head) continue

      if (head.clock.includes(target.writer.core.key, target.length)) {
        acks.add(idx)
      }
    }

    return acks
  }

  _ackedAt(acks, parent) {
    let seen = 0
    let missing = acks.length

    for (const node of acks) {
      missing--

      if (!parent.clock.includes(node.writer.core.key, node.length)) {
        if (seen + missing < this.majority) return false
        continue
      }

      if (++seen >= this.majority) return true
    }

    return false
  }

  confirms(indexer, target, acks, length) {
    if (!length || this.removed.get(indexer.core.key) >= length) return UNSEEN
    // def feels like there is a smarter way of doing this part
    // ie we just wanna find a node from the indexer that is strictly newer than target
    // and seens a maj of the acks - thats it

    let jump = true
    let newer = true

    for (let i = length - 1; i >= 0; i--) {
      const head = indexer.get(i)
      if (head === null) return UNSEEN

      let seen = 0

      for (const node of acks) {
        // if (node.writer === indexer) continue
        if (!head.clock.includes(node.writer.core.key, node.length)) continue
        if (++seen >= this.majority) break
      }

      if (!newer && seen < this.majority) {
        break
      }

      if (!this._strictlyNewer(target, head)) {
        // all strictly newer nodes are clustered together so bisect until we find the cluster
        if (jump) {
          jump = false

          let t = length - 1
          let b = 0

          while (t > b) {
            const mid = (t + b) >>> 1
            const node = indexer.get(mid)

            if (
              node === null ||
              !node.clock.includes(target.writer.core.key, target.length) ||
              this._strictlyNewer(target, node)
            ) {
              b = mid + 1
            } else {
              t = mid - 1
            }
          }

          // + 2 in case we are off by one and the i--. its fine, just an optimisation
          if (b + 1 < i) i = b + 2
        }

        newer = false
        continue
      } else if (seen < this.majority) {
        return NEWER
      }

      return ACKED
    }

    return UNSEEN
  }

  _isConfirmed(target, parent = null) {
    const acks = this._acks(target)
    const confs = new Set()

    if (acks.length < this.majority) return false
    let allNewer = true

    for (const indexer of this.indexers) {
      const length = parent
        ? parent.writer === indexer
          ? parent.length - 1
          : parent.clock.get(indexer.core.key)
        : indexer.length

      const result = this.confirms(indexer, target, acks, length)

      if (result === ACKED) {
        confs.add(indexer)
        if (confs.size >= this.majority) {
          return true
        }
      }

      if (result === UNSEEN) allNewer = false
    }

    if (parent) return this._isConfirmableAt(target, parent, acks, confs)

    return allNewer
  }

  _isConfirmableAt(target, parent, acks, confs) {
    if (!this._ackedAt(acks, parent)) return false

    let potential = confs.size

    for (const indexer of this.indexers) {
      if (confs.has(indexer)) continue

      const length = parent.clock.get(indexer.core.key)
      const isSeen = target.clock.includes(indexer.core.key, length)

      // if the target has seen the latest node, it can freely be used to confirm the target later
      // otherwise, check if a newer node is strictly newer...
      if (!isSeen) {
        const head = indexer.get(length - 1)

        // the next indexer head HAS to be strictly newer - meaning the current one has to be also.
        if (
          head &&
          !this.removed.includes(head.writer.core.key, head.length) &&
          !this._strictlyNewer(target, head)
        ) {
          continue
        }
      }

      if (++potential >= this.majority) return true
    }

    return false
  }

  // this can get called multiple times for same node
  remove(node) {
    this.merges.delete(node)
    this.removed.set(node.writer.core.key, node.length)
    return node
  }

  shift() {
    if (!this.updated) return []

    const tails = this._indexerTails()

    for (const tail of tails) {
      if (this._isConfirmed(tail)) {
        return [this.remove(tail)]
      }
    }

    for (const merge of this.merges) {
      if (this._isConfirmed(merge)) {
        return this._yieldNext(merge, tails)
      }
    }

    this.updated = false
    return []
  }

  // yields next indexer node
  _yieldNext(node, tails) {
    // only stop when we find a tail
    while (!tails.has(node)) {
      let next = null

      // for merges check if one fork is confirmed
      for (const t of this._tailsAndMerges(node, tails)) {
        if (this._isConfirmed(t, node)) {
          next = t
          break
        }
      }

      if (next) {
        node = next
        continue
      }

      // otherwise yield all tails
      const tailSet = []
      for (const t of this._tails(node, tails)) {
        tailSet.push(this.remove(t))
      }

      return tailSet
    }

    return [this.remove(node)]
  }

  shouldAck(writer) {
    for (const t of this._indexerTails()) {
      if (t.writer === writer) continue
      if (this._shouldAckNode(t, writer)) return true
    }

    return false
  }

  _shouldAckNode(target, writer) {
    const head = writer.head()
    const next = target.clock.get(writer.core.key)
    const nextIndexNode = writer.get(next >= writer.indexed ? next : writer.indexed)

    // if we have no next node and we didn't write target then ack
    if (!nextIndexNode && writer !== target.writer) return true

    // shortcuts if we have next node
    if (nextIndexNode) {
      // if the next node does not see the target, should ack
      if (!nextIndexNode.clock.includes(target.writer.core.key, target.length)) {
        return !head.clock.includes(target.writer.core.key, target.length)
      }

      // if the next node is not strictly newer, no point acking
      if (!this._strictlyNewer(target, nextIndexNode)) return false
    }

    // now check if we can double confirm
    const acks = this._acks(target)

    // need enough to double confirm
    if (acks.length >= this.majority) {
      return this.confirms(writer, target, acks, writer.length) === UNSEEN
    }

    return false
  }
}
const HypercoreEncryption = require('hypercore/lib/default-encryption.js')
const sodium = require('sodium-universal')
const crypto = require('hypercore-crypto')
const c = require('compact-encoding')
const b4a = require('b4a')
const rrp = require('resolve-reject-promise')
const ReadyResource = require('ready-resource')

const SystemView = require('./system.js')
const { EncryptionDescriptor, ManifestData } = require('./messages.js')
const { NS_VIEW_BLOCK_KEY, NS_HASH_KEY, NS_ENCRYPTION } = require('./caps.js')

const nonce = b4a.alloc(sodium.crypto_stream_NONCEBYTES)
const hash = nonce.subarray(0, sodium.crypto_generichash_BYTES_MIN)

class AutobaseEncryption {
  static PADDING = 8

  constructor(encryption) {
    this.encryption = encryption

    this.compat = null
    this.keys = null
    this.keysById = new Map()
  }

  get id() {
    return this.keys ? this.keys.id : 0
  }

  padding() {
    return AutobaseEncryption.PADDING
  }

  isCompat() {
    return false
  }

  load(keys) {
    if (this.keys === null) this.keys = keys
  }

  async update(ctx) {
    if (this.id !== 0 && this.id === this.encryption.id) return
    const keys = await this.get(this.encryption.id, ctx)
    if (keys) this.keys = keys
  }

  async get(id, ctx) {
    if (this.keysById.has(id)) return this.keysById.get(id)

    const keys = await this.getKeys(id, ctx)
    this.keysById.set(id, keys)

    return keys
  }

  async getKeys(id, ctx) {
    const entropy = await this.encryption.get(id)
    if (!entropy) return null

    const block = this.blockKey(entropy, ctx)
    const hash = crypto.hash([NS_HASH_KEY, block])

    return {
      id,
      block,
      hash
    }
  }

  blockKey(entropy, ctx) {
    return this.encryption.blockKey(entropy, ctx)
  }

  async _ensureCompat(ctx) {
    if (!this.compat) this.compat = this.compatKeys(ctx)
  }

  compatKeys() {
    throw new Error('Compatibility method is not specified')
  }

  async encrypt(index, block, fork, ctx) {
    if (this.isCompat(ctx, index)) {
      this._ensureCompat(ctx)
      return HypercoreEncryption.encrypt(
        index,
        block,
        fork,
        this.compat.block,
        this.compat.blinding
      )
    }

    await this.update(ctx)

    encryptBlock(index, block, this.keys.id, this.keys.block, this.keys.hash)
  }

  async decrypt(index, block, ctx) {
    if (this.isCompat(ctx, index)) {
      this._ensureCompat(ctx)
      return HypercoreEncryption.decrypt(index, block, this.compat.block)
    }

    const padding = block.subarray(0, AutobaseEncryption.PADDING)
    block = block.subarray(AutobaseEncryption.PADDING)

    const type = padding[0]
    switch (type) {
      case 0:
        return block // unencrypted

      case 1:
        break

      default:
        throw new Error('Unrecognised encryption type')
    }

    const id = c.uint32.decode({ start: 4, end: 8, buffer: padding })

    const keys = await this.get(id, ctx)

    c.uint64.encode({ start: 0, end: 8, buffer: nonce }, index)
    nonce.set(padding, 8, 16)

    // Decrypt the block using the full nonce
    decrypt(block, nonce, keys.block)
  }
}

class ViewEncryption extends AutobaseEncryption {
  constructor(encryption, name) {
    super(encryption)
    this.name = name
  }

  isCompat(ctx, index) {
    if (ctx.manifest.version <= 1) return true
    if (!ctx.manifest.userData) return false
    const { legacyBlocks } = c.decode(ManifestData, ctx.manifest.userData)
    return index < legacyBlocks
  }

  compatKeys() {
    const { bootstrap, encryptionKey } = this.encryption.base
    const block = getCompatBlockKey(bootstrap, encryptionKey, this.name)
    return {
      block,
      blinding: crypto.hash(block)
    }
  }

  blockKey(entropy) {
    return getCompatBlockKey(this.encryption.base.bootstrap, entropy, this.name)
  }
}

class WriterEncryption extends AutobaseEncryption {
  isCompat(ctx) {
    return ctx.manifest.version <= 1
  }

  compatKeys(ctx) {
    return HypercoreEncryption.deriveKeys(this.encryption.base.encryptionKey, ctx.key)
  }

  blockKey(entropy, ctx) {
    if (ctx.manifest.userData) {
      const userData = c.decode(ManifestData, ctx.manifest.userData)
      if (userData.namespace !== null) {
        return this.encryption.blockKey(entropy, { key: userData.namespace })
      }
    }

    return this.encryption.blockKey(entropy, ctx)
  }
}

class EncryptionView extends ReadyResource {
  constructor(base, core) {
    super()

    this.base = base
    this.core = core || null

    this.sessions = new Map()

    this._initialising = null
  }

  async _open() {
    await this.initialised()
    await this.core.ready()
  }

  initialised() {
    if (this.core !== null) return this.core.ready()
    if (this._initialising) return this._initialising

    this._initialising = rrp()

    return this._initialising.promise
  }

  _close() {
    if (this._initialising) {
      this._initialising.reject(new Error('Encryption closed'))
      this._initialising = null
    }

    if (this.core) return this.core.close()
  }

  get bootstrapped() {
    return !!(this.core && this.core.length > 0)
  }

  get id() {
    return this.core ? this.core.length : 0
  }

  _createPayload(key) {
    return key
  }

  async reload(core) {
    if (this.core) await this.core.close()

    this.core = core
    await this.core.ready()

    if (this._initialising) {
      this._initialising.resolve()
      this._initialising = null
    }
  }

  unpack(type, payload) {
    if (type > 0) throw new Error('Unsupported version')
    return payload
  }

  async update(key) {
    const payload = await this._createPayload(key)
    const desc = { type: 0, payload }

    await this.core.append(c.encode(EncryptionDescriptor, desc))
  }

  async _preload() {
    await this.ready()
    return this.id()
  }

  getViewEncryption(name) {
    if (this.sessions.has(name)) return this.sessions.get(name)

    const encryption = new ViewEncryption(this, name)
    this.sessions.set(name, encryption)

    return encryption
  }

  getWriterEncryption() {
    return new WriterEncryption(this)
  }

  async encryptAnchor(block, namespace) {
    const entropy = await this.get(this.id)
    if (!entropy) return null

    const blockKey = this.blockKey(entropy, { key: namespace })
    const hashKey = crypto.hash([NS_HASH_KEY, block])

    encryptBlock(0, block, this.id, blockKey, hashKey)
  }

  blockKey(entropy, ctx) {
    return getBlockKey(this.base.bootstrap, this.base.encryptionKey, entropy, ctx.key)
  }

  async get(encryptionId) {
    if (encryptionId === 0) return SystemView.GENESIS_ENTROPY

    if (!this.core) await this.initialised()

    const index = encryptionId - 1
    const desc = await this.core.get(index)
    const { type, payload } = c.decode(EncryptionDescriptor, desc)

    const key = this.unpack(type, payload)
    return key
  }

  getSystemEncryption() {
    return this.getViewEncryption('_system')
  }

  static namespace(entropy) {
    return crypto.hash([NS_ENCRYPTION, entropy])
  }

  static getBlockKey(bootstrap, encryptionKey, entropy, hypercoreKey) {
    return getBlockKey(bootstrap, encryptionKey, entropy, hypercoreKey)
  }

  static getSystemEncryption(base, core) {
    const view = new EncryptionView(base, core)
    return view.getSystemEncryption()
  }

  static async setSystemEncryption(base, core, opts) {
    if (base.encryptionKey === null) return null

    await core.ready()
    if (core.manifest.version === 1) {
      const key = getCompatBlockKey(base.bootstrap, base.encryptionKey, '_system')
      return core.setEncryptionKey(key, { block: true })
    }

    if (!core.manifest.linked.length) {
      throw new Error('System manifest does not link encryption view')
    }

    const enc = base.store.get({ key: core.manifest.linked[0], active: false })
    const encryption = EncryptionView.getSystemEncryption(base, enc)

    await core.setEncryption(encryption, opts)

    return enc
  }
}

module.exports = {
  AutobaseEncryption,
  EncryptionView
}

function encrypt(block, nonce, key) {
  sodium.crypto_stream_xor(block, block, nonce, key)
}

function decrypt(block, nonce, key) {
  return encrypt(block, nonce, key) // symmetric
}

function getBlockKey(bootstrap, encryptionKey, entropy, hypercoreKey) {
  return (
    encryptionKey &&
    crypto.hash([NS_VIEW_BLOCK_KEY, bootstrap, encryptionKey, entropy, hypercoreKey])
  )
}

function getCompatBlockKey(bootstrap, encryptionKey, name) {
  if (typeof name === 'string') return getCompatBlockKey(bootstrap, encryptionKey, b4a.from(name))
  return encryptionKey && crypto.hash([NS_VIEW_BLOCK_KEY, bootstrap, encryptionKey, name])
}

function blockhash(block, padding, hashKey) {
  sodium.crypto_generichash(hash, block, hashKey)
  padding.set(hash.subarray(0, 8)) // copy first 8 bytes of hash
  hash.fill(0) // clear nonce buffer
}

function encryptBlock(index, block, id, blockKey, hashKey) {
  const padding = block.subarray(0, AutobaseEncryption.PADDING)
  block = block.subarray(AutobaseEncryption.PADDING)

  blockhash(block, padding, hashKey)
  c.uint32.encode({ start: 4, end: 8, buffer: padding }, id)

  c.uint64.encode({ start: 0, end: 8, buffer: nonce }, index)

  padding[0] = 1 // version in plaintext

  nonce.set(padding, 8, 16)

  // The combination of index, key id, fork id and block hash is very likely
  // to be unique for a given Hypercore and therefore our nonce is suitable
  encrypt(block, nonce, blockKey)
}
const rrp = require('resolve-reject-promise')
const safetyCatch = require('safety-catch')

const SystemView = require('./system.js')
const { EncryptionView } = require('./encryption.js')

const DEFAULT_OP_TIMEOUT = 5_000
const DEFAULT_MIN_FF = 16

module.exports = class FastForward {
  constructor(
    base,
    key,
    {
      timeout = DEFAULT_OP_TIMEOUT,
      verified = true,
      minimum = DEFAULT_MIN_FF,
      force = false,
      length = 0
    } = {}
  ) {
    this.base = base
    this.key = key
    this.timeout = timeout
    this.force = force
    this.core = base.store.get({ key, active: true, encryption: null })
    this.length = length
    this.views = []
    this.encryption = null
    this.entropy = null
    this.indexers = []
    this.minimum = minimum
    this.verified = verified
    this.waiting = new Set()
    this.cores = [this.core]
    this.system = null
    this.destroyed = false
    this.upgrading = null
    this.failed = false
  }

  static MINIMUM = DEFAULT_MIN_FF

  async upgrade() {
    try {
      if (!this.upgrading) this.upgrading = this._upgrade()

      if (!(await this.upgrading)) return null

      return {
        length: this.length,
        force: this.force,
        key: this.key,
        indexers: this.indexers,
        views: this.views,
        entropy: this.entropy,
        manifestVersion: this.core.manifest.version,
        minimum: this.minimum
      }
    } catch (err) {
      safetyCatch(err)
      this.failed = true
      return null
    } finally {
      await this.close()
    }
  }

  _waitForAppend(core) {
    if (core.length > 0) return Promise.resolve()

    const promise = rrp()
    const timeout = setTimeout(this.close.bind(this), this.timeout)
    const wait = { promise, timeout }

    this.waiting.add(wait)

    core.once('append', () => {
      this.waiting.delete(wait)
      clearTimeout(timeout)
      promise.resolve()
    })

    return promise.promise
  }

  _minLength() {
    return this.base.core.length + this.minimum
  }

  async _upgrade() {
    await this.core.ready()

    if (!this.verified) await this._waitForAppend(this.core)
    if (this.destroyed) return false

    if (this.core.manifest.linked) {
      const appends = []

      for (const key of this.core.manifest.linked) {
        const core = this.base.store.get({ key, active: true })
        this.cores.push(core)

        await core.ready()
        appends.push(this._waitForAppend(core))
      }

      await Promise.all(appends)
    }

    if (this.length === 0) this.length = this.core.length

    // note we use the persisted length here, as we might as well continue that work as thats ~ the same length
    if (!this.force && this.length < this._minLength()) return false
    if (this.length === 0) return false

    await this.core.get(this.length - 1, { timeout: this.timeout })
    await this.base.ready()

    if (this.destroyed) return false

    if (this.base.encryptionKey && !(await this._ensureEncryption())) return false
    if (this.destroyed) return false

    this.system = new SystemView(this.core, { checkout: this.length })
    await this.system.ready()
    if (this.destroyed) return false

    this.entropy = this.system.entropy

    if (this.core.manifest.version >= 2) {
      const linked = this.core.manifest.linked

      if (this.system.encryptionLength === 0 || linked === null || !linked.length) {
        return false
      }

      // technically diverges from system.views to include encryption here, but makes sense
      this.views.push({
        key: linked[0],
        length: this.system.encryptionLength
      })
    }

    const promises = []

    // ensure local key is locally available always
    promises.push(this.system.get(this.base.local.key, { timeout: this.timeout }))

    if (this.encryption && this.encryption.core) {
      promises.push(
        this.encryption.core.get(this.system.encryptionLength - 1, { timeout: this.timeout })
      )
    }

    for (const v of this.system.views) {
      this.views.push(v)
      const core = this.base.store.get({ key: v.key, active: true })
      this.cores.push(core)
      if (!v.length) continue // encryption view can be 0 length
      promises.push(core.get(v.length - 1, { timeout: this.timeout }))
    }

    for (const idx of this.system.indexers) {
      this.indexers.push(idx)
      if (idx.length === 0) continue // need to make sure we have manifest...
      const core = this.base.store.get({ key: idx.key, active: true })
      this.cores.push(core)
      promises.push(core.get(idx.length - 1, { timeout: this.timeout }))
      promises.push(this.system.get(idx.key, { timeout: this.timeout }))
    }

    for (const head of this.system.heads) {
      promises.push(this.system.get(head.key, { timeout: this.timeout }))
    }

    await Promise.all(promises)
    if (this.destroyed) return false

    return true
  }

  async _ensureEncryption() {
    // only need encryption if we migrated
    if (this.core.encryption !== null) return true

    const encCore = this.core.manifest.version <= 1 ? null : this.cores[1]

    // expects internal views to be loaded in order
    this.encryption = new EncryptionView(this.base, encCore)
    const encryption = this.encryption.getViewEncryption('_system')

    await this.core.setEncryption(encryption)

    return true
  }

  async close() {
    this.destroyed = true
    for (const { promise, timeout } of this.waiting) {
      clearTimeout(timeout)
      promise.resolve() // silently bail
    }
    if (this.system) await this.system.close()
    if (this.encryption) await this.encryption.close()
    for (const core of this.cores) await core.close()
    await this.core.close()
  }
}
const c = require('compact-encoding')

const SystemView = require('./system.js')
const { EncryptionView } = require('./encryption.js')
const { ManifestData } = require('./messages.js')

module.exports = class Fork {
  constructor(base, store, state, fork) {
    this.base = base
    this.store = store
    this.state = state
    this.indexers = fork.indexers
    this.length = fork.length
    this.system = null
    this.encryption = null
    this.manifests = null
    this.cores = []
  }

  async upgrade() {
    try {
      await this._upgrade()
      return true
    } catch {
      return false
    } finally {
      await this.close()
    }
  }

  async _upgrade() {
    this.manifests = await this.store.getIndexerManifests(this.indexers)

    this.system = new SystemView(await this._get('_system', this.length))
    this.encryption = new EncryptionView(this, await this._get('_encryption', -1))

    await this.system.ready()
    await this.encryption.ready()

    this.entropy = this.system.getEntropy(this.indexers, this.length)
    this.manifestVersion = Math.max(this.system.core.manifest.version, 2) // >= 2 to signal new encryption

    const views = []
    for (const view of this.state.views) {
      const v = this.getViewFromSystem(view, this.system)
      const indexedLength = v ? v.length : 0

      const session = await this._get(view.name, indexedLength)
      await session.ready()

      const next = await this.createView(view.name, session, null)
      await next.ready()

      await this._migrate(view.ref, next, view.core, indexedLength)

      // update key
      views.push({ key: next.key, length: indexedLength })
    }

    // internal views are explicitly migrated

    const entropy = EncryptionView.namespace(this.entropy)
    await this.encryption.update(entropy)

    const system = this.store.getViewByName('_system')
    const encryption = this.store.getViewByName('_encryption')

    const enc = await this.createView('_encryption', this.encryption.core, null)
    await enc.ready()

    await this._migrate(encryption, enc, this.encryption.core, this.encryption.core.length)

    await this.system.fork(this.indexers, this.manifests, this.encryption.core.length, views)

    const sys = await this.createView('_system', this.system.core, [enc.key])
    await sys.ready()

    await this._migrate(system, sys, this.system.core, this.system.core.length)
  }

  async createView(name, core, linked) {
    const prologue = await getPrologue(core)
    const manifestData = this._manifestData(core)

    return this.store.getViewCore(
      this.manifests,
      name,
      prologue,
      this.manifestVersion,
      this.entropy,
      linked,
      manifestData
    )
  }

  async _get(name, length) {
    const core = this.store.get({ name })
    this.cores.push(core)

    if (length !== -1) await core.truncate(length)

    return core
  }

  getViewFromSystem(view) {
    if (view.mappedIndex === -1 || view.mappedIndex >= this.system.views.length) return null
    return this.system.views[view.mappedIndex]
  }

  _manifestData(session) {
    if (session.manifest.version > 1) return session.manifest.userData
    return c.encode(ManifestData, { version: 0, legacyBlocks: session.length })
  }

  async _migrate(ref, next, source, length) {
    if (length > 0) {
      await next.core.copyPrologue(source.state)
    }

    // remake the batch, reset from our prologue in case it replicated inbetween
    // TODO: we should really have an HC function for this
    const batch = next.session({ name: 'batch', overwrite: true, checkout: length })
    await batch.ready()

    if (source !== null) {
      while (batch.length < source.length) {
        await batch.append(await source.get(batch.length))
      }
    }

    ref.moveTo = [batch, next]
  }

  async close() {
    this.destroyed = true
    if (this.system) await this.system.close()
    if (this.encryption) await this.encryption.close()
    for (const core of this.cores) await core.close()
  }
}

async function getPrologue(core) {
  if (!core.length) return null

  return {
    hash: await core.treeHash(),
    length: core.length
  }
}
const b4a = require('b4a')
const assert = require('nanoassert')

const Clock = require('./clock.js')
const Consensus = require('./consensus.js')
const Topolist = require('./topolist.js')

class Node {
  constructor(writer, length, value, heads, batch, dependencies, optimistic, trace) {
    this.writer = writer
    this.length = length
    this.value = value
    this.heads = heads
    this.actualHeads = heads.slice(0) // TODO: we should remove this and just not mutate heads...

    this.dependents = new Set()
    this.dependencies = dependencies
    this.index = 0 // used by topolist

    this.optimistic = optimistic && batch === 1 && !!value

    this.batch = batch
    this.dropped = 0
    this.trace = trace

    this.clock = new Clock()

    this.yielded = false
    this.yielding = false
  }

  isTail() {
    return this.dependencies.size === this.dropped
  }

  causalDependencies(idx) {
    const order = [this]
    const stack = [this]

    let visited = null

    while (stack.length > 0) {
      const node = stack.pop()
      for (const dep of node.dependencies) {
        if (!dep.writer.isRemoved || dep.writer.isActiveIndexer) continue

        // TODO: replace with "coloring" but ok for now, tiny set
        if (visited === null) visited = new Set()
        if (visited.has(dep)) continue
        visited.add(dep)

        stack.push(dep)
        order.push(dep)
      }
    }

    return order
  }

  clear() {
    this.clock = null
    this.dependents = null
    return this
  }

  reset() {
    this.yielded = false
    this.yielding = false
    for (const dep of this.dependents) dep.dependencies.add(this)
    this.dependents.clear()
  }

  active() {
    for (const dep of this.dependencies) {
      if (dep.yielded) {
        this.dependencies.delete(dep) // nodes might be yielded during buffering
      } else {
        dep.dependents.add(this)
        this.clock.add(dep.clock)
      }
    }

    if (this.writer.isActiveIndexer) this.clock.set(this.writer.core.key, this.length)
  }

  tieBreak(node) {
    return tieBreak(this, node)
  }

  hasDependency(dep) {
    for (const h of this.actualHeads) {
      if (sameNode(h, dep)) return true
    }
    return false
  }

  get ref() {
    return this.writer.core.key.toString('hex').slice(0, 2) + ':' + this.length
  }
}

module.exports = class Linearizer {
  constructor(indexers, { heads = [], writers = new Map() } = {}) {
    this.heads = new Set()
    this.tails = new Set()
    this.tip = new Topolist()
    this.size = 0 // useful for debugging
    this.updated = false
    this.indexersUpdated = false
    this.writers = writers

    this.consensus = new Consensus(indexers)
    this._initialHeads = heads.slice(0)
    this._strictlyAdded = null

    for (const { key, length } of heads) {
      this.consensus.removed.set(key, length)
    }
  }

  get indexers() {
    return this.consensus.indexers
  }

  static createNode(writer, length, value, heads, batch, dependencies, optimistic, trace) {
    return new Node(writer, length, value, heads, batch, dependencies, optimistic, trace)
  }

  // returns the global links of the dag, use this to link against the current state of the dag
  // TODO: rename to heads() and move the sets to _ props
  getHeads() {
    const heads = this._initialHeads.slice(0)
    for (const node of this.heads) heads.push({ key: node.writer.core.key, length: node.length })
    return heads
  }

  // TODO: might contain dups atm, nbd for how we use it, returns an array of writers you can "pull"
  // to get the full dag view at any time
  getBootstrapWriters() {
    const writers = []

    for (const head of this.heads) writers.push(head.writer)
    for (let i = 0; i < this.consensus.indexers.length; i++)
      writers.push(this.consensus.indexers[i])

    return writers
  }

  addHead(node) {
    node.active()

    // 99.99% of the time _initialHeads is empty...
    if (this._initialHeads.length > 0) this._updateInitialHeads(node)

    if (node.isTail()) {
      this.tails.add(node)
    }

    for (const head of this.heads) {
      if (node.hasDependency(head)) {
        this.heads.delete(head)
      }
    }

    this.tip.add(node)
    if (node.writer.isActiveIndexer) this.consensus.addHead(node)

    this.size++
    this.heads.add(node)

    this.updated = true

    return node
  }

  update() {
    if (!this.updated) return null
    this.updated = false

    // get the indexed nodes
    const indexed = []
    while (true) {
      const nodes = this.consensus.shift()
      if (!nodes.length) break

      this._yield(nodes, indexed)
    }

    return this.tip.flush(indexed)
  }

  _updateInitialHeads(node) {
    for (const head of node.actualHeads) {
      for (let i = 0; i < this._initialHeads.length; i++) {
        const { key, length } = this._initialHeads[i]
        if (length !== head.length || !b4a.equals(key, head.key)) continue
        this._initialHeads.splice(i--, 1)
      }
    }
  }

  /* Ack methods */

  shouldAck(writer, pending = false) {
    if (!writer || !writer.isActiveIndexer) return false

    // all indexers have to flushed to the dag before we ack as a quick "debounce"
    for (const w of this.indexers) {
      if (w.length !== w.available) return false
    }

    let isHead = false

    // if ANY head is not an indexer ack
    for (const head of this.heads) {
      if (!head.writer.isActiveIndexer) return true
      if (head.writer === writer) isHead = true
    }

    if (this.heads.size === 1 && isHead) {
      return false // never self-ack!
    }

    const visited = new Set()

    // check if there is non-null value
    let valueCheck = false

    for (const tail of this.tails) {
      if (pending || this._nonNull(tail, visited)) {
        valueCheck = true
        break
      }
    }

    if (!valueCheck) return false

    if (this.consensus.shouldAck(writer)) return true

    return this._shouldAckHeads(writer, pending)
  }

  // check if there is any value above this node
  _nonNull(target, visited) {
    const stack = [target]

    while (stack.length) {
      const node = stack.pop()

      if (visited.has(node)) continue
      if (node.value !== null) return true

      visited.add(node)

      for (const dep of node.dependents) {
        stack.push(dep)
      }
    }

    return false
  }

  // ack if any head is closer to confirming a value
  _shouldAckHeads(writer, pending) {
    const prev = writer.head()

    for (const head of this.heads) {
      // only check other writers heads
      if (head.writer === writer) continue

      const stack = [head]
      const visited = new Set()

      while (stack.length) {
        const node = stack.pop()

        if (visited.has(node)) continue
        visited.add(node)

        if (pending || node.value !== null) {
          const acks = this.consensus.acksFromNode(node, head)
          const prevAcks = this.consensus.acksFromNode(node, prev)

          // head sees more acks
          if (acks.size > prevAcks.size) return true

          for (const idx of acks) {
            // head sees acks that writer does not
            if (!prevAcks.has(idx)) return true
          }

          // both seen, no point going any further down
          if (prevAcks.size && acks.size) continue
        }

        stack.push(...node.dependencies)
      }
    }

    return false
  }

  /* Full DAG methods */

  _yield(nodes, indexed = []) {
    const offset = indexed.length
    const tails = []

    // determine which nodes are yielded
    while (nodes.length) {
      const node = nodes.pop()

      if (node.yielding) continue
      node.yielding = true

      if (node.isTail()) tails.push(node)

      nodes.push(...node.dependencies)
    }

    while (tails.length) {
      let tail = tails.pop()

      for (tail of this._removeBatch(tail)) {
        Topolist.add(tail, indexed, offset)
      }

      for (const dep of tail.dependents) {
        if (dep.isTail() && dep.yielding) tails.push(dep)
      }
    }

    return indexed
  }

  _isFutureTail(node) {
    let dropped = node.dropped

    // a tail has no unyielded dependencies
    for (const dep of node.dependencies) {
      if (dep.yielded) continue
      if (dropped === 0) return false
      dropped--
    }

    return true
  }

  _removeNode(node) {
    this.tails.delete(node)
    this.heads.delete(node)
    this.consensus.remove(node)

    // update the tailset
    for (const d of node.dependents) {
      if (d.yielding && d.dependencies.has(node))
        d.dropped++ // keep links for the indexed batch
      else d.dependencies.delete(node)
      if (this._isFutureTail(d)) this.tails.add(d)
    }

    node.yielded = true
    this.size--

    if (this.heads.size === 0) {
      // in case of a single writer the dag might drain immediately...
      this._initialHeads.push({ key: node.writer.core.key, length: node.length })
    }

    return node
  }

  _removeBatch(node) {
    const batch = [this._removeNode(node)]

    while (node.batch !== 1) {
      // its a batch!
      if (node.dependents.size === 0) {
        // bad batch node, auto correct
        const next = node.writer.get(node.length)
        if (next && next.batch === node.batch - 1) node.dependents.add(next)
      }

      assert(node.dependents.size === 1, 'Batch is linked partially, which is not allowed')

      node = getFirst(node.dependents)
      batch.push(this._removeNode(node))
    }

    return batch
  }
}

function tieBreak(a, b) {
  return Topolist.compare(a, b) < 0 // lowest key wis
}

function getFirst(set) {
  return set[Symbol.iterator]().next().value
}

function sameNode(a, b) {
  return b4a.equals(a.key, b.writer.core.key) && a.length === b.length
}
const c = require('compact-encoding')
const b4a = require('b4a')

const messages = require('./messages.js')

const GTE = b4a.from([messages.LINEARIZER_PREFIX])
const LT = b4a.from([messages.LINEARIZER_PREFIX + 1])

module.exports = class LocalState {
  constructor(core) {
    this.core = core
    this.tx = null
  }

  static clear(core) {
    const tx = core.state.storage.write()
    tx.deleteLocalRange(GTE, LT)
    return tx.flush()
  }

  static async moveTo(src, dst) {
    const boot = await src.getUserData('autobase/boot')
    const tx = dst.state.storage.write()

    tx.deleteLocalRange(GTE, LT)

    for await (const data of src.state.storage.createLocalStream({ gte: GTE, lt: LT })) {
      tx.putLocal(data.key, data.value)
    }

    tx.putUserData('autobase/boot', boot)

    await tx.flush()
  }

  setBootRecord(boot) {
    if (this.tx === null) this.tx = this.core.state.storage.write()

    this.tx.putUserData('autobase/boot', c.encode(messages.BootRecord, boot))
  }

  async listUpdates() {
    const updates = []

    for await (const data of this.core.state.storage.createLocalStream({ gte: GTE, lt: LT })) {
      const update = c.decode(messages.LinearizerUpdate, data.value)
      const seq = c.decode(messages.LinearizerKey, data.key)
      update.seq = seq
      updates.push(update)
    }

    return updates
  }

  clearUpdates() {
    if (this.tx === null) this.tx = this.core.state.storage.write()

    this.tx.deleteLocalRange(GTE, LT)
  }

  deleteUpdate(update) {
    if (this.tx === null) this.tx = this.core.state.storage.write()

    this.tx.deleteLocal(c.encode(messages.LinearizerKey, update.seq))
  }

  insertUpdate(update) {
    if (this.tx === null) this.tx = this.core.state.storage.write()

    this.tx.putLocal(
      c.encode(messages.LinearizerKey, update.seq),
      c.encode(messages.LinearizerUpdate, update)
    )
  }

  flush() {
    if (!this.tx) return Promise.resolve()

    const flushing = this.tx.flush()
    this.tx = null
    return flushing
  }
}
const schema = require('../encoding/spec/autobase')

module.exports = {
  Wakeup: schema.resolveStruct('@autobase/wakeup'),
  Clock: schema.resolveStruct('@autobase/clock'),
  Checkout: schema.resolveStruct('@autobase/checkout'),
  BootRecord: schema.resolveStruct('@autobase/boot-record'),
  OplogMessage: schema.resolveStruct('@autobase/oplog-message'),
  Checkpoint: schema.resolveStruct('@autobase/checkpoint'),
  Info: schema.resolveStruct('@autobase/info'),
  Member: schema.resolveStruct('@autobase/member'),
  ManifestData: schema.resolveStruct('@autobase/manifest-data'),
  LINEARIZER_PREFIX: 1,
  LinearizerKey: schema.resolveStruct('@autobase/linearizer-key'),
  LinearizerUpdate: schema.resolveStruct('@autobase/linearizer-update'),
  EncryptionDescriptor: schema.resolveStruct('@autobase/encryption-descriptor')
}
const DEFAULT_SIZE = 32

module.exports = class NodeBuffer {
  constructor(offset, hwm) {
    this.hwm = hwm || DEFAULT_SIZE
    this.defaultHwm = this.hwm
    this.mask = this.hwm - 1
    this.top = 0
    this.btm = 0
    this.buffer = new Array(this.hwm)
    this.offset = offset || 0
    this.length = this.offset
  }

  get size() {
    return this.length - this.offset
  }

  isEmpty() {
    return this.length === this.offset
  }

  isFull() {
    return this.size === this.buffer.length
  }

  grow() {
    this.hwm <<= 1

    const size = this.size
    const buffer = new Array(this.hwm)
    const mask = this.hwm - 1

    for (let i = 0; i < size; i++) {
      buffer[i] = this.buffer[(this.btm + i) & this.mask]
    }

    this.mask = mask
    this.top = size
    this.btm = 0
    this.buffer = buffer
  }

  push(data) {
    if (this.isFull()) this.grow()

    this.buffer[this.top] = data
    this.top = (this.top + 1) & this.mask

    return this.length++
  }

  shift() {
    if (this.isEmpty()) return null

    const last = this.buffer[this.btm]

    this.buffer[this.btm] = undefined
    this.btm = (this.btm + 1) & this.mask
    this.offset++

    // reset on empty
    if (this.isEmpty() && this.hwm !== this.defaultHwm) {
      this.buffer = new Array(this.defaultHwm)
      this.hwm = this.buffer.length
      this.mask = this.hwm - 1
      this.top = this.btm = 0
    }

    return last
  }

  get(seq) {
    if (seq < this.offset || seq >= this.length) return null
    return this.buffer[(this.btm + (seq - this.offset)) & this.mask]
  }
}
const b4a = require('b4a')
const c = require('compact-encoding')
const crypto = require('hypercore-crypto')
const Hypercore = require('hypercore')

const messages = require('./messages.js')

const DEFAULT_MANIFEST_VERSION = 1
const INDEX_VERSION = 1
const MAX_TRACE_PER_VIEW = 256

const EMPTY = b4a.alloc(0)

const [NS_SIGNER_NAMESPACE] = crypto.namespace('autobase', 1)

class ViewCore {
  constructor(name, core, base) {
    this.name = name
    this.core = null
    this.batch = null
    this.atomicBatch = null
    this.moveTo = null
    this.tracer = new Tracer()
    this.shared = 0

    this.ontruncate = (length) => {
      this.shared = Math.min(this.shared, length)
    }
    this.migrated(base, core)
  }

  getCore() {
    return this.atomicBatch || this.batch || this.core
  }

  migrated(base, core) {
    // TODO: close old core if present, for now we just close when the autobase is closed indirectly
    // atm its unsafe to do as moveTo has a bug due to a missing read lock in hc
    this.core = core

    if (this.name === '_system') {
      const ff = base._queueFastForward.bind(base)
      this.core.on('append', ff)
      this.core.ready().then(ff, ff)
    }
  }

  async matchesKey(key) {
    if (!this.core.opened) await this.core.ready()
    return b4a.equals(this.core.key, key)
  }

  async matchesNamespace(target) {
    if (!this.core.opened) await this.core.ready()

    if (this.core.manifest && this.core.manifest.signers.length > 0) {
      const ns = this.core.manifest.signers[0].namespace
      if (b4a.equals(ns, target)) return true
    }

    return false
  }

  getNextKey() {
    return this.moveTo ? this.moveTo[0].key : null
  }

  async commit(atom, length, signature) {
    // TODO: is this how its supposed be done atomic wise?
    await this.core.commit(this._getAtomicBatch(atom), { length, signature })
  }

  async release() {
    if (!this.atomicBatch) return
    await this.atomicBatch.ready()

    while (this.atomicBatch.state.sessions.length) {
      await this.atomicBatch.state.sessions[0].close()
    }

    await this.atomicBatch.close()
    this.atomicBatch = null
  }

  _getAtomicBatch(atom) {
    if (this.atomicBatch === null) {
      this.atomicBatch = this.batch.session({ atom, writable: true })
      this.atomicBatch.on('truncate', this.ontruncate)
    }

    return this.atomicBatch
  }

  async catchup(atom, length) {
    await this.release()
    const batch = this._getAtomicBatch(atom)
    await batch.ready()
    await batch.state.catchup(length)
  }

  createSession(atom, valueEncoding) {
    if (this.batch === null) {
      this.batch = this.core.session({ name: 'batch', writable: true })
      this.batch.on('truncate', this.ontruncate)
    }

    const s = atom
      ? this._getAtomicBatch(atom).session({
          valueEncoding,
          writable: true,
          onseq: this.tracer.onseq.bind(this.tracer)
        })
      : this.batch.session({ valueEncoding, writable: false })

    return s
  }
}

class Tracer {
  constructor() {
    this.enabled = false
    this.seen = new Set()
  }

  start() {
    this.enabled = true
    this.seen.clear()
  }

  end() {
    this.enabled = false
    return [...this.seen.values()]
  }

  onseq(seq, core) {
    if (!this.enabled) return
    if (this.seen.size >= MAX_TRACE_PER_VIEW) return
    if (seq >= core.signedLength) return

    this.seen.add(seq)
  }
}

class AutoStore {
  constructor(base, byName) {
    this.base = base
    this.store = base.store
    this.byName = byName || new Map()
    this.opened = []
    this.atom = null
    this.local = null
  }

  async close() {
    if (this.local) await this.local.close()
    for (const v of this.byName.values()) {
      await v.release()
    }
    if (this.atom) return
    for (const v of this.byName.values()) {
      if (v.core) await v.core.close()
      if (v.batch) await v.batch.close()
    }
  }

  async export() {
    const views = []

    for (const [name, value] of this.byName) {
      const core = await this.store.storage.export(value.core.discoveryKey, { batches: true })
      views.push({ name, core })
    }

    return views
  }

  atomize() {
    const store = new AutoStore(this.base, this.byName)
    store.atom = this.store.storage.createAtom()
    return store
  }

  async updateLocal() {
    if (!this.local) return
    await this.local.close()
    this.local = null
  }

  flush() {
    return this.atom ? this.atom.flush() : Promise.resolve()
  }

  get(opts, moreOpts) {
    if (typeof opts === 'string') opts = { name: opts }
    if (moreOpts) opts = { ...opts, ...moreOpts }

    const { name, valueEncoding = null } = opts

    if (!name) throw new Error('name is required')
    return this.getViewByName(name).createSession(this.atom, valueEncoding)
  }

  getViewByName(name) {
    let view = this.byName.get(name)

    if (!view) {
      const preload = this._preload(name)
      const core = this.base.store.get({ preload })
      view = new ViewCore(name, core, this.base)
      this.byName.set(name, view)
    }

    if (this.opened.indexOf(view) === -1) {
      this.opened.push(view)
    }

    return view
  }

  getLocal() {
    if (this.local !== null) return this.local

    this.local = this.base.local.session({
      atom: this.atom,
      valueEncoding: messages.OplogMessage,
      encryption: this.base.getWriterEncryption(this.base.local.key),
      active: false
    })

    return this.local
  }

  getViews() {
    return [...this.byName.values()]
  }

  getViewCount() {
    return this.byName.size
  }

  getSystemView() {
    return this.getViewByName('_system')
  }

  getSystemCore() {
    return this.getSystemView().core
  }

  getEncryption(name) {
    if (!this.base.encryptionKey) return null
    if (name === '_encryption') return null

    return this.base.encryption.getViewEncryption(name)
  }

  async getIndexerManifests(entries) {
    const manifests = []
    for (const { key } of entries) {
      const core = this.store.get({ key, active: false })
      await core.ready()
      if (!core.manifest) continue // danger but only for bootstrapping...
      manifests.push(core.manifest)
      await core.close()
    }
    return manifests
  }

  getViewCore(indexerManifests, name, prologue, manifestVersion, entropy, linked, manifestData) {
    const manifest = this._createManifest(
      indexerManifests,
      name,
      prologue,
      manifestVersion,
      entropy,
      linked,
      manifestData
    )

    return this.base.store.get({
      manifest,
      exclusive: false,
      encryption: this.getEncryption(name)
    })
  }

  listViews() {
    const views = []
    for (const [name, ref] of this.byName) {
      const core = ref.batch || ref.core
      views.push({ name, key: core.key, length: core.length, signedLength: core.signedLength })
    }
    return views
  }

  createAnchorCore(prologue, manifestData) {
    const manifest = {
      version: 2,
      hash: 'blake2b',
      prologue,
      allowPatch: false,
      quorum: 0,
      signers: [],
      userData: manifestData,
      linked: null
    }

    const core = this.store.get({
      manifest,
      active: false
    })

    return core
  }

  async createView(
    indexerManifests,
    name,
    prologue,
    manifestVersion,
    entropy,
    linked,
    manifestData
  ) {
    const manifest = this._createManifest(
      indexerManifests,
      name,
      prologue,
      manifestVersion,
      entropy,
      linked,
      manifestData
    )

    const core = this.store.get({
      key: Hypercore.key(manifest),
      manifest,
      active: false
    })

    await core.ready()
    const key = core.key

    await core.close()
    return key
  }

  async _preload(name) {
    await Promise.resolve()

    if (!this.base.opening) throw new Error('Autobase failed to open')
    await this.base._preopen

    const boot = (await this.base._getSystemInfo()) || {
      key: this.getBootstrapSystemKey(),
      indexers: [],
      views: [],
      entropy: null
    }
    const indexerManifests = await this.getIndexerManifests(boot.indexers)

    // no system, everything is fresh
    if (boot.indexers.length === 0) {
      return this._freshCorePreload(indexerManifests, name, boot.entropy)
    }

    // asking for the system, just return it, easy
    if (name === '_system') {
      return {
        key: boot.key,
        exclusive: false,
        encryption: this.getEncryption(name)
      }
    }

    if (name === '_encryption') {
      const core = this.getSystemCore()
      await core.ready()

      if (!core.manifest.linked) {
        return this._freshCorePreload(indexerManifests, name, boot.entropy)
      }

      return {
        key: core.manifest.linked[0],
        exclusive: false,
        encryption: null
      }
    }

    // infer which view
    const v = await this.findViewByName(indexerManifests, boot.views, name, boot.entropy)

    // new view, fresh
    if (v === null) {
      return this._freshCorePreload(indexerManifests, name, boot.entropy)
    }

    return {
      key: v.key,
      exclusive: false,
      encryption: this.getEncryption(name)
    }
  }

  _freshCorePreload(indexerManifests, name, entropy) {
    if (name === '_system') return this._freshSystemPreload(indexerManifests, entropy)

    return {
      manifest: this._createManifest(
        indexerManifests,
        name,
        null,
        DEFAULT_MANIFEST_VERSION,
        entropy,
        [],
        null
      ),
      exclusive: true,
      encryption: this.getEncryption(name)
    }
  }

  _freshSystemPreload(indexerManifests, entropy) {
    return {
      manifest: this._createSystemManifest(
        indexerManifests,
        null,
        DEFAULT_MANIFEST_VERSION,
        entropy,
        null
      ),
      exclusive: true,
      encryption: this.getEncryption('_system')
    }
  }

  _deriveStaticHash(name) {
    // key doesnt matter...
    return crypto.hash([this.base.key, b4a.from(name)])
  }

  _deriveNamespace(name, entropy) {
    const encryptionId = crypto.hash(this.base.encryptionKey || EMPTY)
    const version = c.encode(c.uint, INDEX_VERSION)
    const bootstrap = this.base.key

    return crypto.hash([
      NS_SIGNER_NAMESPACE,
      version,
      bootstrap,
      encryptionId,
      entropy,
      b4a.from(name)
    ])
  }

  async _getCoreManifest(key) {
    const core = this.store.get({ key, active: false })
    await core.ready()
    const manifest = core.manifest
    await core.close()
    return manifest
  }

  getBootstrapSystemKey() {
    return Hypercore.key(this._createSystemManifest([], null, DEFAULT_MANIFEST_VERSION, null))
  }

  async findViewByKey(key, indexers, manifestVersion, entropy) {
    for (const v of this.byName.values()) {
      if (await v.matchesKey(key)) return v
    }

    const manifest = await this._getCoreManifest(key)
    const target = manifest && manifest.signers.length ? manifest.signers[0].namespace : null

    if (target) {
      for (const v of this.byName.values()) {
        if (await v.matchesNamespace(target)) return v
      }
    }

    const indexerManifests = await this.getIndexerManifests(indexers)

    if (entropy === null) {
      entropy = indexerManifests[0].signers[0].namespace
    }

    if (target) {
      for (const v of this.byName.values()) {
        const namespace = this._deriveNamespace(v.name, entropy)
        if (b4a.equals(namespace, target)) return v
      }
    }

    // prob the empty prologue, we dont have manifest for those in FF if len=0
    for (const v of this.byName.values()) {
      const manifestData = v.core ? v.core.manifest.userData : null
      const manifest = this._createManifest(
        indexerManifests,
        v.name,
        null,
        manifestVersion,
        entropy,
        [],
        manifestData
      )
      const manifestKey = Hypercore.key(manifest)

      if (!b4a.equals(manifestKey, key)) continue

      // we didnt have the core! this is because it is empty, ensure its on disk
      const core = this.store.get({ key: manifestKey, manifest, active: false })
      await core.ready()
      await core.close()

      return v
    }

    return null
  }

  async findViewByName(indexerManifests, views, name, entropy) {
    if (indexerManifests.length === 0) return null

    if (entropy === null) entropy = indexerManifests[0].signers[0].namespace
    const namespace = this._deriveNamespace(name, entropy)

    for (const v of views) {
      const manifest = await this._getCoreManifest(v.key)
      if (manifest.signers.length === 0) continue

      const signer = manifest.signers[0]

      if (b4a.equals(signer.namespace, namespace)) return v
    }

    return null
  }

  _createManifest(indexerManifests, name, prologue, version, entropy, linked, manifestData) {
    if (!indexerManifests.length) {
      prologue = {
        hash: this._deriveStaticHash(name),
        length: 0
      }
    } else if (prologue && prologue.length === 0) {
      // just in case
      prologue = null
    }

    const signers = []

    if (indexerManifests.length && entropy === null) {
      entropy = indexerManifests[0].signers[0].namespace
    }

    for (const manifest of indexerManifests) {
      const signer = manifest.signers[0]

      signers.push({
        namespace: this._deriveNamespace(name, entropy),
        signature: 'ed25519',
        publicKey: signer.publicKey
      })
    }

    return {
      version,
      hash: 'blake2b',
      prologue,
      allowPatch: true,
      quorum: Math.min(signers.length, (signers.length >> 1) + 1),
      signers,
      userData: manifestData,
      linked: version > 1 ? linked : null
    }
  }

  _createSystemManifest(indexerManifests, prologue, version, entropy, manifestData) {
    if (prologue !== null) throw new Error('Can only derive fresh system core')

    const linked = []

    if (version > DEFAULT_MANIFEST_VERSION) {
      const encManifest = this._createManifest(
        indexerManifests,
        '_encryption',
        null,
        version,
        entropy,
        [],
        manifestData
      )
      linked.push(Hypercore.key(encManifest))
    }

    return this._createManifest(
      indexerManifests,
      '_system',
      null,
      version,
      entropy,
      linked,
      manifestData
    )
  }
}

module.exports = AutoStore
const Hyperbee = require('hyperbee')
const SubEncoder = require('sub-encoder')
const ReadyResource = require('ready-resource')
const b4a = require('b4a')
const c = require('compact-encoding')
const crypto = require('hypercore-crypto')

const { Info, Member } = require('./messages.js')
const { DEFAULT_AUTOBASE_VERSION } = require('./caps.js')

const subs = new SubEncoder()

const DIGEST = subs.sub(b4a.from([0]))
const MEMBERS = subs.sub(b4a.from([1]))

const INFO_KEY = DIGEST.encode('info')

const [GENESIS_ENTROPY, NS_ENTROPY] = crypto.namespace('autobase/entropy', 2)

module.exports = class SystemView extends ReadyResource {
  constructor(core, { checkout = 0, empty = false } = {}) {
    super()

    this.core = core

    // sessions is a workaround for batches not having sessions atm...
    this.db = new Hyperbee(core, {
      keyEncoding: 'binary',
      extension: false,
      checkout,
      sessions: typeof core.session === 'function'
    })

    this.version = DEFAULT_AUTOBASE_VERSION
    this.members = 0
    this.pendingIndexers = []
    this.indexers = []
    this.heads = []
    this.views = []
    this.encryptionLength = 0
    this.entropy = null

    this.indexerUpdate = false

    this._empty = empty
    this._fork = 0
    this._length = 0
    this._changes = []
    this._indexerMap = new Map()
    this._clockUpdates = new Map()
  }

  static GENESIS_ENTROPY = GENESIS_ENTROPY

  static async getIndexedInfo(core, length) {
    const sys = new this(core.session())

    try {
      return await sys.getIndexedInfo(length)
    } finally {
      await sys.close()
    }
  }

  static async *flushes(core, { reverse, lt = core.length, gte = 0, wait = true } = {}) {
    if (lt <= 0) return

    // ensure block
    await core.get(lt - 1)
    const sys = new SystemView(core)

    try {
      for await (const data of sys.db.createHistoryStream({ lt, gte, wait, reverse: true })) {
        if (!b4a.equals(data.key, INFO_KEY)) continue
        const info = c.decode(Info, data.value)
        yield { length: data.seq + 1, info }
      }
    } finally {
      await sys.close()
    }
  }

  get bootstrapping() {
    return this.members === 0
  }

  async checkout(length) {
    const checkout = new SystemView(this.core.session(), {
      checkout: length,
      empty: length === 0
    })

    await checkout.ready()

    return checkout
  }

  async _open() {
    // this should NEVER fail, if so we have a bug elsewhere (should always be consistent)
    const info = this._empty
      ? null
      : await this.db.get('info', {
          valueEncoding: Info,
          keyEncoding: DIGEST,
          update: false,
          wait: false
        })
    await this._reset(info)
  }

  async _close() {
    await this.db.close()
  }

  async getIndexedInfo(length = this.core.signedLength) {
    if (this.opened === false) await this.ready()

    if (length === this.core.length) {
      return {
        version: this.version,
        members: this.members,
        pendingIndexers: this.pendingIndexers,
        indexers: this.indexers,
        heads: this.heads,
        views: this.views,
        encryptionLength: this.encryptionLength,
        entropy: this.entropy
      }
    }

    const node = length === 0 ? null : await this.db.getBySeq(length - 1)
    if (node === null) {
      return {
        version: DEFAULT_AUTOBASE_VERSION,
        members: 0,
        pendingIndexers: [],
        indexers: [],
        heads: [],
        views: [],
        encryptionLength: 0,
        entropy: null
      }
    }

    return c.decode(Info, node.value)
  }

  static sameIndexers(a, b) {
    if (a.length !== b.length) return false

    for (let i = 0; i < a.length; i++) {
      if (!b4a.equals(a[i].key, b[i].core.key)) return false
    }

    return true
  }

  sameIndexers(indexers) {
    return SystemView.sameIndexers(this.indexers, indexers)
  }

  async history(since) {
    const checkout = this.db.checkout(since)
    const seen = new Map()

    const nodes = []
    const updates = []

    const checkoutNode = since === 0 ? null : await this.db.getBySeq(since - 1)

    let prevInfo = checkoutNode === null ? null : c.decode(Info, checkoutNode.value)
    let updateBatch = 0

    for await (const data of this.db.createHistoryStream({ gte: since })) {
      if (b4a.equals(data.key, INFO_KEY)) {
        const info = c.decode(Info, data.value)

        updates.push({
          batch: updateBatch,
          indexers: prevInfo === null || !sameIndexers(info, prevInfo),
          systemLength: data.seq + 1
        })

        prevInfo = info
        updateBatch = 0
        continue
      }

      const key = data.key.subarray(2)
      const hex = b4a.toString(key, 'hex')
      const len = c.decode(Member, data.value).length

      if (!seen.has(hex)) {
        const node = await checkout.get(data.key)
        if (node === null) {
          seen.set(hex, 0)
        } else {
          const { length } = c.decode(Member, node.value)
          seen.set(hex, length)
        }
      }

      const prev = seen.get(hex)
      const batch = len - prev
      seen.set(hex, len)

      if (batch === 0) continue

      updateBatch += batch

      if (nodes.length > 0) {
        const top = nodes[nodes.length - 1]
        if (b4a.equals(top.key, key)) {
          top.length = len
          top.batch += batch
          continue
        }
      }

      nodes.push({
        key,
        length: len,
        batch
      })
    }

    await checkout.close()

    return { updates, nodes }
  }

  async update() {
    if (this.opened === false) await this.ready()

    if (this._fork === this.core.fork && this._length === this.core.length) return false

    await this._reset(
      this._empty ? null : await this.db.get('info', { valueEncoding: Info, keyEncoding: DIGEST })
    )
    return true
  }

  async _reset(info) {
    this.version = info === null ? DEFAULT_AUTOBASE_VERSION : info.value.version
    this.members = info === null ? 0 : info.value.members
    this.pendingIndexers = info === null ? [] : info.value.pendingIndexers
    this.indexers = info === null ? [] : info.value.indexers
    this.heads = info === null ? [] : info.value.heads
    this.views = info === null ? [] : info.value.views
    this.encryptionLength = info === null ? 0 : info.value.encryptionLength
    this.entropy = info === null ? null : info.value.entropy

    this.indexerUpdate = false
    this._indexerMap.clear()
    this._clockUpdates.clear()
    this._length = this.core.length
    this._fork = this.core.fork
    this._changes = []

    for (const idx of this.indexers) {
      this._indexerMap.set(b4a.toString(idx.key, 'hex'), idx)
    }
  }

  // helper used by apply-state
  flushLength() {
    const header = this.core.length ? 0 : 1 // account for header

    let updates = this._changes.length + this._clockUpdates.size
    for (const { key } of this._changes) {
      const hex = b4a.toString(key, 'hex')
      if (this._clockUpdates.has(hex)) updates-- // shared are skipped
    }

    return header + this.core.length + updates + 1
  }

  async flush(views) {
    const batch = this.db.batch({ update: false })

    for (let i = 0; i < this._changes.length; i++) {
      const c = this._changes[i]
      if (this._clockUpdates.has(b4a.toString(c.key, 'hex'))) continue
      await batch.put(c.key, c.value, { valueEncoding: Member, keyEncoding: MEMBERS })
    }

    for (const [hex, length] of this._clockUpdates) {
      const isIndexer = this._indexerMap.get(hex) !== undefined
      const key = b4a.from(hex, 'hex')

      const info = await this._get(key, 0)

      const value = { isIndexer, isRemoved: info ? info.isRemoved : true, length }
      await batch.put(key, value, { valueEncoding: Member, keyEncoding: MEMBERS })
    }

    if (this.indexerUpdate) {
      this._refreshEntropy(this.core.length + batch.length + 1)
    }

    this._clockUpdates.clear()

    let maxIndex = -1
    for (const view of views) {
      if (view.mappedIndex > maxIndex) maxIndex = view.mappedIndex
    }

    while (this.views.length > maxIndex + 1) this.views.pop()

    for (const view of views) {
      const length = view.core ? view.core.length : view.length
      if (!length) continue

      const v = { key: view.key, length }

      if (view.mappedIndex !== -1) {
        this.views[view.mappedIndex] = v
      } else {
        view.mappedIndex = this.views.push(v) - 1
      }
    }

    const info = {
      version: this.version,
      members: this.members,
      pendingIndexers: this.pendingIndexers,
      indexers: this.indexers,
      heads: this.heads,
      views: this.views,
      encryptionLength: this.encryptionLength,
      entropy: this.entropy
    }

    await batch.put('info', info, { valueEncoding: Info, keyEncoding: DIGEST })
    await batch.flush()

    this._length = this.core.length // should be ok
    this._changes = []

    if (this.indexerUpdate) this.indexerUpdate = false
  }

  getEntropy(indexers, length) {
    return generateEntropy(indexers, length, this.entropy)
  }

  _refreshEntropy(length) {
    if (this.version < 2) return
    this.entropy = this.getEntropy(this.indexers, length)
  }

  checkpoint() {
    return {
      version: this.version,
      members: this.members,
      pendingIndexers: this.pendingIndexers.slice(0),
      indexers: cloneNodes(this.indexers),
      heads: cloneNodes(this.heads),
      views: cloneNodes(this.views),
      indexerUpdate: this.indexerUpdate,
      encryptionLength: this.encryptionLength,
      entropy: this.entropy ? b4a.from(this.entropy) : null,
      changes: this._changes.slice(0),
      clockUpdates: new Map([...this._clockUpdates])
    }
  }

  applyCheckpoint(checkpoint) {
    this.version = checkpoint.version
    this.members = checkpoint.members
    this.pendingIndexers = checkpoint.pendingIndexers
    this.indexers = checkpoint.indexers
    this.heads = checkpoint.heads
    this.views = checkpoint.views
    this.indexerUpdate = checkpoint.indexerUpdate
    this.encryptionLength = checkpoint.encryptionLength
    this.entropy = checkpoint.entropy

    this._changes = checkpoint.changes
    this._clockUpdates = checkpoint.clockUpdates

    this._indexerMap = new Map()
    for (const idx of this.indexers) {
      this._indexerMap.set(b4a.toString(idx.key, 'hex'), idx)
    }
  }

  addHead(node) {
    const h = { key: node.writer.core.key, length: node.length }

    for (let i = 0; i < this.heads.length; i++) {
      const head = this.heads[i]

      if (!hasDependency(node, head)) {
        if (!b4a.equals(node.writer.core.key, head.key)) continue

        // todo: remove in next major because bug was fixed here:
        // https://github.com/holepunchto/autobase-next/pull/237

        // filter out any bad heads introduced by a bug to
        // prevent inconsistencies being written to the oplog
        if (head.length > h.length) return false
      }

      const popped = this.heads.pop()
      if (popped !== head) this.heads[i--] = popped
    }

    this.heads.push(h)

    const hex = b4a.toString(h.key, 'hex')

    this._clockUpdates.set(hex, h.length)

    if (this.pendingIndexers.length > 0) {
      for (let i = 0; i < this.pendingIndexers.length; i++) {
        if (!b4a.equals(this.pendingIndexers[i], h.key)) continue
        this._updateIndexer(h.key, h.length, true, i)
        return true
      }
    }

    const idx = this._indexerMap.get(hex)
    if (idx !== undefined) {
      idx.length = h.length
    }

    return false
  }

  _updateIndexer(key, length, isIndexer, i) {
    const hex = b4a.toString(key, 'hex')

    if (!isIndexer) {
      const existing = this._indexerMap.get(hex)
      if (existing) {
        this.indexerUpdate = true
        this.indexers.splice(this.indexers.indexOf(existing), 1)
        this._indexerMap.delete(hex)
      }
      return
    }

    for (; i < this.pendingIndexers.length; i++) {
      if (b4a.equals(this.pendingIndexers[i], key)) {
        break
      }
    }

    if (length === 0) {
      if (i >= this.pendingIndexers.length) this.pendingIndexers.push(key)
      return
    }

    if (i < this.pendingIndexers.length) {
      const top = this.pendingIndexers.pop()
      if (i < this.pendingIndexers.length) this.pendingIndexers[i] = top
    }

    const idx = this._indexerMap.get(hex)

    if (idx === undefined) {
      const newIdx = { key, length }
      this._indexerMap.set(hex, newIdx)
      this.indexers.push(newIdx)

      // bootstrap is "silently" added so that initial views have no prologue
      if (!this.bootstrapping) this.indexerUpdate = true
    } else {
      idx.length = length
    }
  }

  _seenLength(key) {
    return this._clockUpdates.get(b4a.toString(key, 'hex')) || 0
  }

  async ack(key) {
    const value = await this._get(key, 0)
    const length = this._seenLength(key)
    if (value && value.length === length) return

    const isIndexer = value ? value.isIndexer : false
    const isRemoved = value ? value.isRemoved : true

    this._changes.push({ key, value: { isIndexer, isRemoved, length } })
  }

  async add(key, { isIndexer = false, length = this._seenLength(key) } = {}) {
    let value = null
    let found = false
    let changed = true

    for (let i = this._changes.length - 1; i >= 0; i--) {
      const c = this._changes[i]
      if (b4a.equals(key, c.key)) {
        value = c.value
        found = true
        break
      }
    }

    if (!found) {
      const node = await this.db.get(key, { valueEncoding: Member, keyEncoding: MEMBERS })

      if (node) {
        value = node.value
        found = true
      }
    }

    let wasTracked = false
    let wasIndexer = false

    if (found) {
      if (!value.isRemoved) wasTracked = true
      if (value.isIndexer) wasIndexer = true
      if (length < value.length) length = value.length
      if (value.length === length && value.isIndexer === isIndexer && value.isRemoved === false)
        changed = false
    }

    if (changed) {
      this._changes.push({ key, value: { isIndexer, isRemoved: false, length } })
    }

    if (!wasTracked) this.members++
    if (wasIndexer || isIndexer) this._updateIndexer(key, length, isIndexer, 0)
  }

  async remove(key) {
    let isIndexer = false

    for (const idx of this.indexers) {
      isIndexer = b4a.equals(idx.key, key)
      if (isIndexer) break
    }

    if (isIndexer) this._updateIndexer(key, null, false, 0)

    let value = null
    let found = false

    for (let i = this._changes.length - 1; i >= 0; i--) {
      const c = this._changes[i]
      if (b4a.equals(key, c.key)) {
        value = c.value
        found = true
        break
      }
    }

    if (!found) {
      const node = await this.db.get(key, { valueEncoding: Member, keyEncoding: MEMBERS })
      if (node) {
        value = node.value
        found = true
      }
    }

    const changed = !found || !value.isRemoved
    const wasTracked = found && !value.isRemoved
    const length = found ? value.length : 0

    if (changed) {
      this._changes.push({ key, value: { isIndexer: false, isRemoved: true, length } })
    }

    if (wasTracked) this.members--

    return isIndexer
  }

  async linkable(key, length) {
    const len = this._seenLength(key)
    if (len > 0) return length > len

    const info = await this._get(key, 0)
    const prevLength = info ? info.length : 0

    return length > prevLength
  }

  async has(key, opts) {
    // could be optimised...
    return (await this.get(key, opts)) !== null
  }

  async _get(key, timeout) {
    let value = null
    let found = false

    for (let i = this._changes.length - 1; i >= 0; i--) {
      const c = this._changes[i]
      if (b4a.equals(key, c.key)) {
        value = c.value
        found = true
        break
      }
    }

    if (!found) {
      const node = await this.db.get(key, { timeout, valueEncoding: Member, keyEncoding: MEMBERS })
      if (node) {
        value = node.value
        found = true
      }
    }

    return found ? value : null
  }

  async get(key, opts = {}) {
    if (this._empty) return null

    let value = await this._get(key, opts.timeout || 0)

    if (opts.unflushed) {
      const hex = b4a.toString(key, 'hex')

      for (let i = this._changes.length - 1; i >= 0; i--) {
        const c = this._changes[i]
        if (b4a.equals(c.key, key)) value = c.value
      }

      if (this._clockUpdates.has(hex)) value.length = this._clockUpdates.get(hex)
    }

    return opts.onlyActive !== false || !value.isRemoved ? value : null
  }

  async hasLocal(key) {
    if (this._empty) return false
    try {
      const node = await this.db.get(key, {
        valueEncoding: Member,
        keyEncoding: MEMBERS,
        update: false,
        wait: false
      })
      return node !== null
    } catch {
      return false
    }
  }

  async getLocalLength(key) {
    if (this._empty) return 0
    try {
      const node = await this.db.get(key, {
        valueEncoding: Member,
        keyEncoding: MEMBERS,
        update: false,
        wait: false
      })
      return node === null ? 0 : node.value.length
    } catch {
      return 0
    }
  }

  list() {
    // note, NOT safe to use during apply atm
    return this.db.createReadStream({
      valueEncoding: Member,
      keyEncoding: MEMBERS
    })
  }

  async isIndexed(key, length) {
    const co = this.db.checkout(this.core.indexedLength)
    try {
      const node = await co.get(key, { valueEncoding: Member, keyEncoding: MEMBERS })
      return node !== null && node.value.length >= length
    } finally {
      await co.close()
    }
  }

  async fork(indexers, manifests, encryptionLength, views) {
    this.indexers = []
    this.pendingIndexers = []
    this.views = views

    if (this.version < 2) this.version = 2 // bump to enable entropy

    for (const { key } of indexers) {
      // todo: probably need to check isRemoved etc
      const { length } = await this.get(key)
      this.indexers.push({ key, length })
    }

    this._refreshEntropy(this.core.length)

    const blocks = []

    // truncate needs to respect hypercore batch
    let truncate = this.core.length - 1
    for await (const data of this.db.createHistoryStream({ lt: truncate, reverse: true })) {
      if (b4a.equals(data.key, INFO_KEY)) {
        truncate = data.seq + 1
        break
      }

      blocks.push(data)
    }

    await this.core.truncate(truncate, this.core.fork)

    const batch = this.db.batch({ update: false })
    await batch.ready()

    for (const { key, value } of blocks) {
      await batch.put(key, value)
    }

    const info = {
      version: this.version,
      members: this.members,
      pendingIndexers: this.pendingIndexers,
      indexers: this.indexers,
      heads: this.heads,
      views: this.views,
      encryptionLength,
      entropy: this.entropy
    }

    await batch.put('info', info, { valueEncoding: Info, keyEncoding: DIGEST })
    await batch.flush()

    await this._reset(await this.db.get('info', { valueEncoding: Info, keyEncoding: DIGEST }))

    return truncate
  }
}

function hasDependency(node, dep) {
  for (const h of node.actualHeads) {
    if (sameNode(h, dep)) return true
  }
  return false
}

function sameNode(a, b) {
  return b4a.equals(a.key, b.key) && a.length === b.length
}

function sameIndexers(a, b) {
  if (a.views.length > 0 && b.views.length > 0) return b4a.equals(a.views[0].key, b.views[0].key)
  if (a.indexers.length !== b.indexers.length) return false

  for (let i = 0; i < a.indexers.length; i++) {
    if (!b4a.equals(a.indexers[i].key, b.indexers[i].key)) return false
  }

  return true
}

function cloneNodes(arr) {
  const c = []
  for (let i = 0; i < arr.length; i++) {
    c.push({ key: arr[i].key, length: arr[i].length })
  }
  return c
}

function generateEntropy(indexers, length, entropy) {
  const buffer = b4a.alloc(8 + 32 + indexers.length * 32)
  const state = { start: 0, end: buffer.byteLength, buffer }

  c.uint64.encode(state, length)
  c.fixed32.encode(state, entropy || GENESIS_ENTROPY)
  for (const { key } of indexers) c.fixed32.encode(state, key)

  return crypto.hash([NS_ENTROPY, buffer])
}
const safetyCatch = require('safety-catch')

const MAX_WAIT = 2 * 60 * 1000
const DEFAULT_INTERVAL = 10 * 1000

module.exports = class Timer {
  constructor(handler, interval, opts = {}) {
    this.handler = handler || noop
    this.interval = interval || DEFAULT_INTERVAL
    this.limit = opts.limit || MAX_WAIT

    this._executing = null

    this._limit = random2over1(this.limit)
    this._timer = null
    this._resolve = null
    this._start = 0
    this._stopped = false
    this._asap = false
    this._standalone = new Set()

    this._unref = opts.unref !== false
    this._timerCallback = this._executeBackground.bind(this)
  }

  _executeBackground() {
    this._executing = this._execute()
    this._executing.catch(safetyCatch) // make sure it doesnt crash in the bg
  }

  async _execute() {
    this._asap = false
    await this.handler()
    this._start = 0
    this._executing = null
    this.bump()
  }

  bump() {
    if (this._stopped || this._executing || this._asap) return

    if (!this._start) this._start = Date.now()
    else if (Date.now() - this._start > this._limit) return

    const interval = random2over1(this.interval)

    clearTimeout(this._timer)
    this._timer = setTimeout(this._timerCallback, interval)
    if (this._unref && this._timer.unref) this._timer.unref()
  }

  async trigger() {
    if (this._stopped) return
    if (this._executing) await this._executing
    if (this._stopped) return

    clearTimeout(this._timer)
    this._timer = null

    this._executeBackground()
    await this._executing
  }

  async flush() {
    if (this._executing) await this._executing
  }

  // business-as-usual
  bau() {
    if (!this._asap) return
    this._asap = false
    this.bump()
  }

  asap() {
    if (this._asap) return
    this._asap = true

    const interval = Math.floor((Math.random() * this.interval) / 3)
    clearTimeout(this._timer)
    this._timer = setTimeout(this._timerCallback, interval)
    if (this._unref && this._timer.unref) this._timer.unref()
  }

  stop() {
    if (this._timer) clearTimeout(this._timer)
    this._timer = null
    this._start = 0
    this._asap = false
    this._stopped = true

    for (const { timer, resolve } of this._standalone) {
      clearTimeout(timer)
      resolve()
    }

    this._standalone.clear()
  }

  asapStandalone() {
    const interval = Math.floor((Math.random() * this.interval) / 3)
    return new Promise((resolve) => {
      const ref = { timer: null, resolve }
      ref.timer = setTimeout(resolveStandalone, interval, ref, this._standalone)
      if (ref.timer.unref) ref.timer.unref()
      this._standalone.add(ref)
    })
  }

  unref() {
    if (this._timer && this._timer.unref) this._timer.unref()
  }
}

function resolveStandalone(ref, set) {
  set.delete(ref)
  ref.resolve()
}

// random value x between n <= x < 2n
function random2over1(n) {
  return Math.floor(n + Math.random() * n)
}

function noop() {}
const b4a = require('b4a')
const assert = require('nanoassert')

module.exports = class TopoList {
  constructor() {
    this.tip = []
    this.undo = 0
    this.shared = 0
  }

  static compare(a, b) {
    return cmp(a, b)
  }

  static add(node, indexed, offset) {
    addSorted(node, indexed, offset)
  }

  mark() {
    this.shared = this.tip.length
    this.undo = 0
  }

  // todo: bump to new api that just tracks undo
  flush(indexed = []) {
    if (indexed.length) this._applyIndexed(indexed)

    const u = {
      shared: this.shared,
      undo: this.undo,
      length: indexed.length + this.tip.length,
      indexed,
      tip: this.tip
    }

    this.mark()

    return u
  }

  print() {
    return this.tip.map((n) => n.writer.core.key.toString() + n.length)
  }

  _applyIndexed(nodes) {
    assert(nodes.length <= this.tip.length, 'Indexed batch cannot exceed tip')

    let shared = 0

    for (; shared < nodes.length; shared++) {
      if (this.tip[shared] !== nodes[shared]) break
    }

    // reordering
    if (shared < nodes.length) this._track(shared)

    const tip = []

    for (let i = shared; i < this.tip.length; i++) {
      const node = this.tip[i]
      if (node.yielded) continue
      const s = addSorted(node, tip, 0)
      if (s === tip.length - 1) continue
      this._track(shared + s)
    }

    this.tip = tip
  }

  add(node) {
    const shared = addSorted(node, this.tip, 0)
    this._track(shared)
  }

  _track(shared) {
    if (shared < this.shared) {
      this.undo += this.shared - shared
      this.shared = shared
    }
  }
}

function hasOptimisticDeps(node) {
  for (const d of node.dependencies) {
    if (d.optimistic) return true
  }
  return false
}

// this can be optimised to only return optimistic nodes that we will "touch" when moving down the node
function getOptimisticDeps(node, list) {
  const deps = new Set()
  const stack = [node]

  while (stack.length > 0) {
    const next = stack.pop()
    if (deps.has(next)) continue
    if (next.optimistic && next !== node) deps.add(next)
    for (const d of next.dependencies) {
      if (d.optimistic) stack.push(d)
    }
  }

  const result = []

  for (let i = list.length - 1; deps.size !== result.length && i >= 0; i--) {
    const n = list[i]
    if (deps.has(n)) result.push(n)
  }

  return result.reverse()
}

function addSortedOptimistic(node, list, offset) {
  const opt = getOptimisticDeps(node, list)
  const pos = new Uint32Array(opt.length)

  for (let i = 0; i < opt.length; i++) {
    const n = opt[i]
    pos[i] = n.index
    moveDown(n, list, offset)
  }

  moveDownAndUp(node, list, offset)

  for (let i = opt.length - 1; i >= 0; i--) {
    moveOptimisticUp(opt[i], list, offset)
  }

  let shared = node.index

  for (let i = 0; i < opt.length; i++) {
    const idx = pos[i]
    const n = opt[i]

    if (idx === n.index) continue

    if (idx < shared) shared = idx
    if (n.index < shared) shared = n.index
  }

  return shared
}

function addSorted(node, list, offset) {
  list.push(node)
  node.index = list.length - 1

  // "slow" path, 1% of nodes
  if (hasOptimisticDeps(node)) return addSortedOptimistic(node, list, offset)

  moveDownAndUp(node, list, offset)
  return node.index
}

function moveDown(node, list, offset) {
  while (node.index > offset) {
    const prev = list[node.index - 1]
    if (links(node, prev)) break
    list[(prev.index = node.index)] = prev
    list[--node.index] = node
  }
}

function moveOptimisticUp(node, list, offset) {
  // if optimistic move all the way up
  while (node.index < list.length - 1) {
    const next = list[node.index + 1]
    if (links(next, node)) break
    list[(next.index = node.index)] = next
    list[++node.index] = node
  }

  // stable sort in case multiple children
  while (node.index > offset) {
    const prev = list[node.index - 1]
    if (!prev.optimistic) break
    const c = cmp(prev, node)
    if (c <= 0) break
    list[(prev.index = node.index)] = prev
    list[--node.index] = node
  }
}

function moveNonOptimisticUp(node, list, offset) {
  // stable sort against next non optimistic node
  while (node.index < list.length - 1) {
    const next = list[node.index + 1]
    const c = cmpNonOptimistic(node, next, list)
    if (c <= 0) break
    list[(next.index = node.index)] = next
    list[++node.index] = node
  }
}

function moveDownAndUp(node, list, offset) {
  moveDown(node, list, offset)

  if (node.optimistic) moveOptimisticUp(node, list, offset)
  else moveNonOptimisticUp(node, list, offset)
}

function links(a, b) {
  if (b.dependents.has(a)) return true
  return a.length > 0 && b.length === a.length - 1 && a.writer === b.writer
}

function cmpNonOptimistic(a, b, list) {
  if (!b.optimistic) return cmp(a, b)

  for (let i = b.index + 1; i < list.length; i++) {
    const node = list[i]
    if (!node.optimistic) return cmp(a, node)
  }

  return -1
}

function cmp(a, b) {
  return links(b, a) ? -1 : cmpUnlinked(a, b)
}

function cmpUnlinked(a, b) {
  const c = b4a.compare(a.writer.core.key, b.writer.core.key)
  return c === 0 ? (a.length < b.length ? -1 : 1) : c
}
module.exports = class UpdateChanges {
  constructor(base) {
    this.base = base
    this.byName = new Map()
    this.tracking = null
  }

  get discoveryKey() {
    return this.base.discoveryKey
  }

  get key() {
    return this.base.key
  }

  get id() {
    return this.base.id
  }

  get system() {
    return this.base.system
  }

  track(state) {
    this.tracking = []
    this.byName.clear()

    if (!state) return

    for (const v of state.views) {
      if (v.ref) this._add(v.ref)
    }

    this._add(state.systemView.ref)
    this._add(state.encryptionView.ref)
  }

  _add(ref) {
    const core = ref.atomicBatch || ref.batch
    const from = core.length
    const inf = { ref, from }
    ref.shared = from
    this.tracking.push(inf)
  }

  finalise() {
    if (this.tracking === null) return

    for (const { ref, from } of this.tracking) {
      const core = ref.atomicBatch || ref.batch
      this.byName.set(ref.name, {
        from,
        to: core.length,
        shared: ref.shared
      })
    }

    this.tracking = null
  }

  get(name) {
    return this.byName.get(name)
  }
}
const crypto = require('hypercore-crypto')
const c = require('compact-encoding')
const b4a = require('b4a')

const { OPLOG_VERSION } = require('./caps.js')
const { OplogMessage } = require('./messages.js')
const { EncryptionView } = require('./encryption.js')

module.exports = {
  encodeValue,
  decodeValue
}

function encodeValue(value, opts = {}) {
  const state = { start: 0, end: 0, buffer: null }

  const message = {
    version: opts.version || OPLOG_VERSION,
    digest: null,
    checkpoint: null,
    optimistic: !!opts.optimistic,
    node: {
      heads: opts.heads || [],
      batch: 1,
      value
    }
  }

  OplogMessage.preencode(state, message)

  if (opts.padding) {
    state.start = opts.padding
    state.end += opts.padding
  }

  state.buffer = b4a.alloc(state.end)

  OplogMessage.encode(state, message)

  if (!opts.encrypted) return state.buffer

  if (!opts.optimistic) {
    throw new Error('Encoding an encrypted value is not supported')
  }

  const padding = b4a.alloc(16) // min hash length is 16
  crypto.hash(state.buffer, padding)
  padding[0] = 0

  return b4a.concat([padding.subarray(0, 8), state.buffer])
}

async function decodeValue(value, { autobase, encryptionKey, key, manifest, index = 0 } = {}) {
  if (encryptionKey) {
    const e = new EncryptionView({ encryptionKey, bootstrap: autobase })
    const w = e.getWriterEncryption()

    await w.decrypt(index, value, { key, manifest })
    value = value.subarray(8)
  }

  const op = c.decode(OplogMessage, value)
  return op.node.value
}
const b4a = require('b4a')
const c = require('compact-encoding')
const safetyCatch = require('safety-catch')
const ReadyResource = require('ready-resource')

const WakeupEntry = {
  preencode(state, m) {
    c.fixed32.preencode(state, m.key)
    c.uint.preencode(state, m.length)
  },
  encode(state, m) {
    c.fixed32.encode(state, m.key)
    c.uint.encode(state, m.length)
  },
  decode(state) {
    return {
      key: c.fixed32.decode(state),
      length: c.uint.decode(state)
    }
  }
}

module.exports = class AutoWakeup extends ReadyResource {
  constructor(base) {
    super()

    this.base = base
    this.flushing = null

    this._rootStore = this.base.store
    this._addBound = this.add.bind(this)
    this._preupdateBound = this._preupdate.bind(this)
    this._needsFlush = false
    this._map = new Map()
  }

  [Symbol.iterator]() {
    return this._map.values()
  }

  async _preupdate(batch, key) {
    this.queue(key, batch.length)
    await this.flush()
    this.base._onwakeup()
  }

  async _save() {
    const slab = b4a.allocUnsafe(8 + this._map.size * 40) // 32 + 8
    const state = { start: 0, end: 0, buffer: slab }

    c.uint.encode(state, this._map.size)
    for (const m of this._map.values()) WakeupEntry.encode(state, m)

    await this.base.local.setUserData('autobase/wakeup', slab.subarray(0, state.start))
  }

  async _load() {
    const buffer = await this.base.local.getUserData('autobase/wakeup')
    if (!buffer) return

    const state = { start: 0, end: buffer.byteLength, buffer }

    let len = c.uint.decode(state)
    while (len-- > 0) {
      const m = WakeupEntry.decode(state)
      this._map.set(b4a.toString(m.key, 'hex'), m)
    }
  }

  async _open() {
    await this._load()

    this._rootStore.watch(this._addBound)

    for (const core of this._rootStore.cores) {
      if (core.opened === false) await core.ready().catch(noop)
      if (!core.closing) this.add(core)
    }
  }

  async _close() {
    this._rootStore.unwatch(this._addBound)

    for (const core of this._rootStore.cores) {
      if (core.opened && !core.closing) this.remove(core)
    }

    this._map.clear()

    while (this.flushing) {
      try {
        await this.flushing
      } catch {}
    }
  }

  queue(key, length) {
    const hex = b4a.toString(key, 'hex')
    const m = this._map.get(hex)

    if (m && m.length > length) {
      return false
    }

    this._needsFlush = true
    this._map.set(hex, { key, length })

    return true
  }

  unqueue(key, length) {
    const hex = b4a.toString(key, 'hex')
    const m = this._map.get(hex)

    if (!m) return true
    if (m.length > length) return false

    this._needsFlush = true
    this._map.delete(hex)

    return true
  }

  async flush() {
    if (this.closing) throw new Error('Closing')

    // wait for someone
    if (this.flushing) await this.flushing

    // if another still active they flushed us
    if (this.flushing) return this.flushing

    if (this._needsFlush === false) return
    this._needsFlush = false

    try {
      this.flushing = this._save()
      return await this.flushing
    } finally {
      this.flushing = null
    }
  }

  add(core) {
    return this._add(core).catch(safetyCatch)
  }

  remove(core) {
    return this._remove(core)
  }

  async _add(core) {
    if (core.opened === false) await core.ready()
    if (core.closing) return false

    // local writer, no need
    if (core === this.base.local.core) return false

    const rx = core.storage.read()

    const referrerPromise = rx.getUserData('referrer')
    const viewPromise = rx.getUserData('autobase/view')

    rx.tryFlush()

    const [referrer, view] = await Promise.all([referrerPromise, viewPromise])
    if (view) return false

    if (referrer === null || !b4a.equals(referrer, this.base.key)) return false

    core.preupdate = this._preupdateBound

    return true
  }

  _remove(core) {
    if (core.preupdate !== this._preupdateBound) return false
    core.preupdate = null
    return true
  }
}

function noop() {}
const c = require('compact-encoding')
const b4a = require('b4a')
const ReadyResource = require('ready-resource')
const assert = require('nanoassert')
const SignalPromise = require('signal-promise')

const Linearizer = require('./linearizer.js')
const NodeBuffer = require('./node-buffer.js')

const MAX_PRELOAD = 4
const MAX_PREFETCH = 256

module.exports = class Writer extends ReadyResource {
  constructor(base, core, length, isRemoved) {
    super()

    this.base = base
    this.core = core
    this.isRemoved = isRemoved
    this.updated = false
    this.range = null
    this.nodes = new NodeBuffer(length)
    this.node = null
    this.isActive = false
    this.isCurrentlyCoupled = false
    this.isCoupled = false // maintained by updateBootstrapWriters
    this.isBootstrap = false // maintained by updateBootstrapWriters
    this.isActiveIndexer = false
    this.available = length
    this.length = length
    this.seenLength = 0
    this.recover = false
    this.frozen = false

    this.syncSignal = null
  }

  _pause() {
    if (!this.range) return
    this.range.destroy()
    this.range = null
  }

  _resume() {
    if (this.range) {
      // if we didnt fill up the preload buffer yet, do not commit to more work
      if (this.range.range.end === this.nodes.length + MAX_PREFETCH) return
      this.range.destroy()
    }
    this.range = this.core.download({
      start: this.nodes.length,
      end: this.nodes.length + MAX_PREFETCH,
      linear: true
    })
  }

  _updateCoupling() {
    if (!this.base._coupler || this.isCoupled === this.isCurrentlyCoupled) return

    if (this.isCurrentlyCoupled) this.base._coupler.remove(this.core)
    else this.base._coupler.add(this.core)

    this.isCurrentlyCoupled = this.isCoupled
  }

  _removeCouple() {
    if (this.base._coupler && !this.isCoupled && this.isCurrentlyCoupled) {
      this.isCurrentlyCoupled = false
      this.base._coupler.remove(this.core)
    }
  }

  updateActivity() {
    if (!this.core.opened) return

    if (this.seenLength > this.core.length || this.length < this.core.length || this.isBootstrap) {
      // if we have seen a later core, or if we are behind, or if bootstrap
      this.isActive = true
      this.core.setActive(true)
    } else if (this.length === this.core.length) {
      // things look steady
      this.isActive = false
      this.core.setActive(false)
    }

    this._updateCoupling()

    if (this.core.writable) return

    if (this.base.isFastForwarding() || !this.isActive) {
      this._pause()
    } else {
      this._resume()
    }
  }

  setBootstrap(bool) {
    this.isBootstrap = bool
    this.updateActivity()
  }

  seen(length) {
    if (length > this.seenLength) this.seenLength = length
    this.updateActivity()
  }

  waitForSynced() {
    if (this.core.length === this.length) return Promise.resolve()
    if (this.syncSignal === null) this.syncSignal = new SignalPromise()
    return this.syncSignal.wait()
  }

  async _open() {
    await this.core.ready()
    await this.core.setUserData('referrer', this.base.key)

    // base might be closing here
    if (this.base.closing) return

    // remove later
    this.recover = autoRecover(this.core)

    // add it again incase it wasn't readied before, only needed if this is the first time we set the referrer...
    await this.base._wakeup.add(this.core.core)

    this.updateActivity()

    if (this.core.length > this.length) this.base._queueBump()

    this.base.emit('writer', this)
  }

  _close() {
    if (this.syncSignal !== null) this.syncSignal.notify()
    return this.core.close()
  }

  get indexed() {
    return this.nodes.offset
  }

  idle() {
    return this.length === this.available && this.length === this.core.length && this.core.opened
  }

  flushed() {
    // TODO: prop a cleaner way to express this...
    return (
      this.seenLength <= this.length &&
      this.length === this.available &&
      this.length === this.core.length &&
      this.shiftable() === false &&
      !this.core.core.upgrading &&
      this.core.opened
    )
  }

  compare(writer) {
    return b4a.compare(this.core.key, writer.core.key)
  }

  head() {
    return this.nodes.get(this.length - 1)
  }

  advance() {
    if (this.syncSignal !== null && this.length + 1 === this.core.length) this.syncSignal.notify()
    return this.length < this.available ? this.nodes.get(this.length++) : null
  }

  shiftable() {
    return this.length > this.nodes.offset
  }

  shift() {
    if (this.shiftable() === false) return false

    let node = this._shiftAndClear()
    while (node.batch > 1) node = this._shiftAndClear()

    return true
  }

  get(seq) {
    return seq < this.length ? this.nodes.get(seq) : null
  }

  append(value, heads, batch, dependencies, optimistic) {
    const node = Linearizer.createNode(
      this,
      this.nodes.length + 1,
      value,
      heads,
      batch,
      dependencies,
      optimistic
    )

    node.actualHeads = node.heads.slice(0)

    this.nodes.push(node)
    this.available++
    this.length++

    return node
  }

  async update(boot) {
    if (this.opened === false) await this.ready()
    if (this.frozen) return false

    // if this is a boot node, DO NOT, preload as that will make it load
    // and reject nodes based on the tmp state of the system.
    // prop needs a better solution but this works for now
    const preload = boot ? 1 : MAX_PRELOAD

    while (this.available - this.length < preload) {
      // quick sanity check
      if (this.nodes.length === this.core.length || this.core.length === 0) break

      // load next node
      if (this.node === null && !(await this._loadNextNode())) break
      if (!(await this._ensureNodeDependencies(boot))) break

      if (this.recover) this.node.value = null

      this.nodes.push(this.node)
      if (this.node.batch === 1) this.available = this.nodes.length
      this.node = null
    }

    this.updateActivity()

    return this.length < this.available
  }

  _shiftAndClear() {
    const node = this.nodes.shift()
    node.clear()
    return node
  }

  async _loadNextNode() {
    const seq = this.nodes.length

    if (!(await this.core.has(seq))) return false

    try {
      const { node, optimistic, trace } = await this.core.get(seq, { wait: false })

      const value = node.value == null ? null : c.decode(this.base.valueEncoding, node.value)
      this.node = Linearizer.createNode(
        this,
        seq + 1,
        value,
        node.heads,
        node.batch,
        new Set(),
        optimistic,
        trace
      )
      return true
    } catch (err) {
      this.frozen = true
      throw err
    }
  }

  async _ensureNodeDependencies(boot) {
    while (this.node.dependencies.size < this.node.heads.length) {
      const rawHead = this.node.heads[this.node.dependencies.size]

      const headWriter = await this.base._getWriterByKey(
        rawHead.key,
        -1,
        rawHead.length,
        true,
        false,
        boot
      )

      if (headWriter !== this && (headWriter === null || headWriter.length < rawHead.length)) {
        if (!boot) this.base._ensureWakeup(headWriter)
        return false
      }

      let headNode = headWriter.nodes.get(rawHead.length - 1)

      // could be a stub node
      if (!headNode) {
        for (const node of this.base.linearizer.heads) {
          if (!compareHead(node, rawHead)) continue
          headNode = node
          break
        }
      }

      // TODO: generalise DAG validation and freeze the writer
      assert(!this.node.dependencies.has(headNode), 'Corrupted DAG')

      // TODO: better way to solve the stub check is to never mutate heads below
      if (headNode === null) {
        // already yielded
        this.node.heads.splice(this.node.dependencies.size, 1)
        continue
      }

      this.node.dependencies.add(headNode)
    }

    // always link previous node if it's not indexed
    const offset = this.node.length - 1
    if (offset > this.indexed) {
      this.node.dependencies.add(this.nodes.get(offset - 1))
    }

    return true
  }
}

function compareHead(node, head) {
  if (node.length !== head.length) return false
  return b4a.equals(node.writer.core.key, head.key)
}

// this is a list of peers we bugged in the btc and planb room.
// adding them here so migration can run, can be removed in a month or so from time of commit
// note, no security implications of this, we just null them out.

function autoRecover(core) {
  assert(core.opened)

  switch (core.id) {
    case 'ghrpexaboutdm46ombqho7mroxknassnntrxx3cubfux4qi6w6hy':
    case 'qoaanao71s4he1rcd197d336qepykk4467geo1uq8cwnzmpb786o':
    case 'fomhdxgn4j4tzjqy6y7iskhffimzokt7kraddyd8orcht3r8q61o':
    case 'd8f5taxxrit51apftoi38e5b86hb98cgfd7dfp3uo1uoh95qt49o':
    case 'objyf75uggsqpjcut69xdgj46ks8r71jjrq7oxdfsz95sstchkno':
      return true
  }

  return false
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "autobase",
  "version": "7.28.1",
  "description": "A multiwriter data structure for Hypercore",
  "main": "index.js",
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test/all.js",
    "test:encrypted": "prettier . --check && brittle test/all.js --encrypt-all",
    "test:fixtures": "prettier . --check && brittle test/fixtures/tests/*.js",
    "test:bare": "bare test/all.js",
    "fuzz:generated": "brittle test/reference/fuzz/generated/*.js",
    "fuzz:main": "node test/fuzz/index.js",
    "fuzz": "node test/reference/fuzz/fuzz.js",
    "generate-fixtures": "node test/fixtures/generate/all.js"
  },
  "files": [
    "index.js",
    "lib/**",
    "encoding/**"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/autobase.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/autobase/issues"
  },
  "homepage": "https://github.com/holepunchto/autobase#readme",
  "dependencies": {
    "b4a": "^1.6.1",
    "bare-events": "^2.2.0",
    "compact-encoding": "^3.0.0",
    "core-coupler": "^2.0.0",
    "debounceify": "^1.0.0",
    "encryption-encoding": "^1.0.3",
    "hyperbee": "^2.22.0",
    "hypercore": "^11.27.12",
    "hypercore-crypto": "^3.4.0",
    "hypercore-id-encoding": "^1.2.0",
    "hyperschema": "^1.12.1",
    "index-encoder": "^3.3.2",
    "nanoassert": "^2.0.0",
    "protomux-wakeup": "^2.0.0",
    "ready-resource": "^1.0.0",
    "resolve-reject-promise": "^1.1.0",
    "safety-catch": "^1.0.2",
    "scope-lock": "^1.2.4",
    "signal-promise": "^1.0.3",
    "sodium-universal": "^5.0.1",
    "sub-encoder": "^2.1.1",
    "tiny-buffer-map": "^1.1.1"
  },
  "devDependencies": {
    "autobase-test-helpers": "^3.0.0",
    "blind-encryption-sodium": "^2.0.0",
    "brittle": "^3.1.1",
    "corestore": "^7.9.1",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "rache": "^1.0.0",
    "same-data": "^1.0.0",
    "task-backoff": "^1.0.0",
    "test-tmp": "^1.2.0",
    "uncaughts": "^1.1.0"
  },
  "standard": {
    "ignore": [
      "**/test/fuzz/generated/**",
      "**/test/reference/**",
      "example.mjs"
    ]
  }
}
function isBuffer(value) {
  return Buffer.isBuffer(value) || value instanceof Uint8Array
}

function isEncoding(encoding) {
  return Buffer.isEncoding(encoding)
}

function alloc(size, fill, encoding) {
  return Buffer.alloc(size, fill, encoding)
}

function allocUnsafe(size) {
  return Buffer.allocUnsafe(size)
}

function allocUnsafeSlow(size) {
  return Buffer.allocUnsafeSlow(size)
}

function byteLength(string, encoding) {
  return Buffer.byteLength(string, encoding)
}

function compare(a, b) {
  return Buffer.compare(a, b)
}

function concat(buffers, totalLength) {
  return Buffer.concat(buffers, totalLength)
}

function copy(source, target, targetStart, start, end) {
  return toBuffer(source).copy(target, targetStart, start, end)
}

function equals(a, b) {
  return toBuffer(a).equals(b)
}

function fill(buffer, value, offset, end, encoding) {
  return toBuffer(buffer).fill(value, offset, end, encoding)
}

function from(value, encodingOrOffset, length) {
  return Buffer.from(value, encodingOrOffset, length)
}

function includes(buffer, value, byteOffset, encoding) {
  return toBuffer(buffer).includes(value, byteOffset, encoding)
}

function indexOf(buffer, value, byfeOffset, encoding) {
  return toBuffer(buffer).indexOf(value, byfeOffset, encoding)
}

function lastIndexOf(buffer, value, byteOffset, encoding) {
  return toBuffer(buffer).lastIndexOf(value, byteOffset, encoding)
}

function swap16(buffer) {
  return toBuffer(buffer).swap16()
}

function swap32(buffer) {
  return toBuffer(buffer).swap32()
}

function swap64(buffer) {
  return toBuffer(buffer).swap64()
}

function toBuffer(buffer) {
  if (Buffer.isBuffer(buffer)) return buffer
  return Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

function toString(buffer, encoding, start, end) {
  return toBuffer(buffer).toString(encoding, start, end)
}

function write(buffer, string, offset, length, encoding) {
  return toBuffer(buffer).write(string, offset, length, encoding)
}

function readDoubleBE(buffer, offset) {
  return toBuffer(buffer).readDoubleBE(offset)
}

function readDoubleLE(buffer, offset) {
  return toBuffer(buffer).readDoubleLE(offset)
}

function readFloatBE(buffer, offset) {
  return toBuffer(buffer).readFloatBE(offset)
}

function readFloatLE(buffer, offset) {
  return toBuffer(buffer).readFloatLE(offset)
}

function readInt32BE(buffer, offset) {
  return toBuffer(buffer).readInt32BE(offset)
}

function readInt32LE(buffer, offset) {
  return toBuffer(buffer).readInt32LE(offset)
}

function readUInt32BE(buffer, offset) {
  return toBuffer(buffer).readUInt32BE(offset)
}

function readUInt32LE(buffer, offset) {
  return toBuffer(buffer).readUInt32LE(offset)
}

function writeDoubleBE(buffer, value, offset) {
  return toBuffer(buffer).writeDoubleBE(value, offset)
}

function writeDoubleLE(buffer, value, offset) {
  return toBuffer(buffer).writeDoubleLE(value, offset)
}

function writeFloatBE(buffer, value, offset) {
  return toBuffer(buffer).writeFloatBE(value, offset)
}

function writeFloatLE(buffer, value, offset) {
  return toBuffer(buffer).writeFloatLE(value, offset)
}

function writeInt32BE(buffer, value, offset) {
  return toBuffer(buffer).writeInt32BE(value, offset)
}

function writeInt32LE(buffer, value, offset) {
  return toBuffer(buffer).writeInt32LE(value, offset)
}

function writeUInt32BE(buffer, value, offset) {
  return toBuffer(buffer).writeUInt32BE(value, offset)
}

function writeUInt32LE(buffer, value, offset) {
  return toBuffer(buffer).writeUInt32LE(value, offset)
}

module.exports = {
  isBuffer,
  isEncoding,
  alloc,
  allocUnsafe,
  allocUnsafeSlow,
  byteLength,
  compare,
  concat,
  copy,
  equals,
  fill,
  from,
  includes,
  indexOf,
  lastIndexOf,
  swap16,
  swap32,
  swap64,
  toBuffer,
  toString,
  write,
  readDoubleBE,
  readDoubleLE,
  readFloatBE,
  readFloatLE,
  readInt32BE,
  readInt32LE,
  readUInt32BE,
  readUInt32LE,
  writeDoubleBE,
  writeDoubleLE,
  writeFloatBE,
  writeFloatLE,
  writeInt32BE,
  writeInt32LE,
  writeUInt32BE,
  writeUInt32LE
}
{
  "name": "b4a",
  "version": "1.8.1",
  "description": "Bridging the gap between buffers and typed arrays",
  "exports": {
    "./package": "./package.json",
    ".": {
      "react-native": "./react-native.js",
      "browser": "./browser.js",
      "default": "./index.js"
    }
  },
  "files": [
    "browser.js",
    "index.js",
    "react-native.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:bare && npm run test:node",
    "test:bare": "brittle-bare --coverage test.mjs",
    "test:node": "brittle-node --coverage test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/b4a.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/b4a/issues"
  },
  "homepage": "https://github.com/holepunchto/b4a#readme",
  "devDependencies": {
    "brittle": "^3.5.2",
    "lunte": "^1.7.0",
    "nanobench": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "react-native-b4a": "*"
  },
  "peerDependenciesMeta": {
    "react-native-b4a": {
      "optional": true
    }
  }
}
module.exports = require.addon()
const binding = require('./binding')

module.exports = binding.abort
{
  "name": "bare-abort",
  "version": "2.0.13",
  "description": "Cause abnormal program termination and generate a crash report",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-abort.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-abort/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-abort#readme",
  "devDependencies": {
    "cmake-bare": "^1.1.7",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  }
}
const ESC = '\x1b'
const CSI = ESC + '['
const SGR = (n) => CSI + n + 'm'

exports.constants = {
  ESC,
  CSI,
  SGR
}

// https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_(Control_Sequence_Introducer)_sequences

exports.cursorHide = CSI + '?25l'
exports.cursorShow = CSI + '?25h'

exports.cursorUp = function cursorUp(n = 1) {
  return CSI + n + 'A'
}

exports.cursorDown = function cursorDown(n = 1) {
  return CSI + n + 'B'
}

exports.cursorForward = function cursorForward(n = 1) {
  return CSI + n + 'C'
}

exports.cursorBack = function cursorBack(n = 1) {
  return CSI + n + 'D'
}

exports.cursorNextLine = function cursorNextLine(n = 1) {
  return CSI + n + 'E'
}

exports.cursorPreviousLine = function cursorPreviousLine(n = 1) {
  return CSI + n + 'F'
}

exports.cursorPosition = function cursorPosition(column, row = 0) {
  if (row === 0) return CSI + (column + 1) + 'G'

  return CSI + (row + 1) + ';' + (column + 1) + 'H'
}

exports.eraseDisplayEnd = CSI + 'J'
exports.eraseDisplayStart = CSI + '1J'
exports.eraseDisplay = CSI + '2J'
exports.eraseLineEnd = CSI + 'K'
exports.eraseLineStart = CSI + '1K'
exports.eraseLine = CSI + '2K'

exports.scrollUp = function scrollUp(n = 1) {
  return CSI + n + 'S'
}

exports.scrollDown = function scrollDown(n = 1) {
  return CSI + n + 'T'
}

// https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_(Select_Graphic_Rendition)_parameters

exports.modifierReset = SGR(0)
exports.modifierBold = SGR(1)
exports.modifierDim = SGR(2)
exports.modifierItalic = SGR(3)
exports.modifierUnderline = SGR(4)
exports.modifierNormal = SGR(22)
exports.modifierNotItalic = SGR(23)
exports.modifierNotUnderline = SGR(24)

// https://en.wikipedia.org/wiki/ANSI_escape_code#Colors

exports.colorBlack = SGR(30)
exports.colorRed = SGR(31)
exports.colorGreen = SGR(32)
exports.colorYellow = SGR(33)
exports.colorBlue = SGR(34)
exports.colorMagenta = SGR(35)
exports.colorCyan = SGR(36)
exports.colorWhite = SGR(37)
exports.colorDefault = SGR(39)
exports.colorBrightBlack = SGR(90)
exports.colorBrightRed = SGR(91)
exports.colorBrightGreen = SGR(92)
exports.colorBrightYellow = SGR(93)
exports.colorBrightBlue = SGR(94)
exports.colorBrightMagenta = SGR(95)
exports.colorBrightCyan = SGR(96)
exports.colorBrightWhite = SGR(97)
{
  "name": "bare-ansi-escapes",
  "version": "2.2.3",
  "description": "Parse and produce ANSI escape sequences",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./key-decoder": {
      "types": "./key-decoder.d.ts",
      "default": "./key-decoder.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "key-decoder.js",
    "key-decoder.d.ts"
  ],
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-ansi-escapes.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-ansi-escapes/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-ansi-escapes#readme",
  "dependencies": {
    "bare-stream": "^2.6.5"
  },
  "devDependencies": {
    "bare-buffer": "^3.0.2",
    "brittle": "^3.3.2",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  },
  "peerDependencies": {
    "bare-buffer": "*"
  },
  "peerDependenciesMeta": {
    "bare-buffer": {
      "optional": true
    }
  }
}
const inspect = require('bare-inspect')

class AssertionError extends Error {
  constructor(opts = {}) {
    let { message = null, actual, expected, operator } = opts

    if (message === null) {
      message = `${inspect(actual)} ${operator} ${inspect(expected)}`
    }

    super(message)

    this.actual = actual
    this.expected = expected
    this.operator = operator
  }

  get name() {
    return 'AssertionError'
  }

  get code() {
    'ASSERTION'
  }
}

function assertFail(opts, fn) {
  if (opts.message instanceof Error) throw opts.message

  const err = new AssertionError(opts)

  if (Error.captureStackTrace) Error.captureStackTrace(err, fn)

  throw err
}

module.exports = exports = function assert(actual, message) {
  if (actual) return

  assertFail({ message, actual, expected: true, operator: '==' }, assert)
}

exports.AssertionError = AssertionError

exports.fail = function fail(message) {
  if (message === undefined) message = 'Failed'

  assertFail({ message, operator: 'fail' }, fail)
}

exports.ok = function ok(actual, message) {
  if (actual) return

  assertFail({ message, actual, expected: true, operator: '==' }, ok)
}

exports.notOk = function ok(actual, message) {
  if (!actual) return

  assertFail({ message, actual, expected: false, operator: '==' }, ok)
}

exports.equal = function equal(actual, expected, message) {
  if (actual == expected || (actual !== actual && expected !== expected)) {
    return
  }

  assertFail({ message, actual, expected, operator: '==' }, equal)
}

exports.notEqual = function notEqual(actual, expected, message) {
  if (actual != expected && (actual === actual || expected === expected)) {
    return
  }

  assertFail({ message, actual, expected, operator: '!=' }, notEqual)
}

exports.strictEqual = function strictEqual(actual, expected, message) {
  if (Object.is(actual, expected)) return

  assertFail(
    { message, actual, expected, operator: 'strictEqual' },
    strictEqual
  )
}

exports.notStrictEqual = function notStrictEqual(actual, expected, message) {
  if (!Object.is(actual, expected)) return

  assertFail(
    { message, actual, expected, operator: 'notStrictEqual' },
    notStrictEqual
  )
}
{
  "name": "bare-assert",
  "version": "1.2.0",
  "description": "Assertion library for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts"
  ],
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-assert.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-assert/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-assert#readme",
  "dependencies": {
    "bare-inspect": "^3.1.2"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  }
}
const os = require('bare-os')

module.exports = new Proxy(Object.create(null), {
  ownKeys(target) {
    return os.getEnvKeys()
  },

  get(target, property) {
    if (typeof property !== 'string') return

    return os.getEnv(property)
  },

  has(target, property) {
    if (typeof property !== 'string') return false

    return os.hasEnv(property)
  },

  set(target, property, value) {
    if (typeof property !== 'string') return

    const type = typeof value

    if (type !== 'string' && type !== 'number' && type !== 'boolean') {
      throw new Error('Environment variable must be of type string, number, or boolean')
    }

    value = String(value)

    os.setEnv(property, value)

    return true
  },

  deleteProperty(target, property) {
    if (typeof property !== 'string') return

    os.unsetEnv(property)
  },

  getOwnPropertyDescriptor(target, property) {
    return {
      value: this.get(target, property),
      enumerable: true,
      configurable: true,
      writable: true
    }
  }
})
{
  "name": "bare-env",
  "version": "3.0.1",
  "description": "Environment variable support for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-env.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-env/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-env#readme",
  "dependencies": {
    "bare-os": "^3.0.1"
  },
  "devDependencies": {
    "brittle": "^3.2.1",
    "lunte": "^1.8.3",
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
const errors = require('./lib/errors')

class EventListener {
  constructor() {
    this.list = []
    this.count = 0
  }

  append(ctx, name, fn, once) {
    this.count++
    ctx.emit('newListener', name, fn) // Emit BEFORE adding
    this.list.push([fn, once])
  }

  prepend(ctx, name, fn, once) {
    this.count++
    ctx.emit('newListener', name, fn) // Emit BEFORE adding
    this.list.unshift([fn, once])
  }

  remove(ctx, name, fn) {
    for (let i = 0, n = this.list.length; i < n; i++) {
      const l = this.list[i]

      if (l[0] === fn) {
        this.list.splice(i, 1)

        if (this.count === 1) delete ctx._events[name]

        ctx.emit('removeListener', name, fn) // Emit AFTER removing

        this.count--
        return
      }
    }
  }

  removeAll(ctx, name) {
    const list = [...this.list]
    this.list = []

    if (this.count === list.length) delete ctx._events[name]

    for (let i = list.length - 1; i >= 0; i--) {
      ctx.emit('removeListener', name, list[i][0]) // Emit AFTER removing
    }

    this.count -= list.length
  }

  emit(ctx, name, ...args) {
    const list = [...this.list]

    for (let i = 0, n = list.length; i < n; i++) {
      const l = list[i]

      if (l[1] === true) this.remove(ctx, name, l[0])

      Reflect.apply(l[0], ctx, args)
    }

    return list.length > 0
  }
}

function appendListener(ctx, name, fn, once) {
  if (ctx._events === undefined) ctx._events = Object.create(null)
  const e = ctx._events[name] || (ctx._events[name] = new EventListener())
  e.append(ctx, name, fn, once)
  return ctx
}

function prependListener(ctx, name, fn, once) {
  if (ctx._events === undefined) ctx._events = Object.create(null)
  const e = ctx._events[name] || (ctx._events[name] = new EventListener())
  e.prepend(ctx, name, fn, once)
  return ctx
}

function removeListener(ctx, name, fn) {
  if (ctx._events === undefined) return ctx
  const e = ctx._events[name]
  if (e !== undefined) e.remove(ctx, name, fn)
  return ctx
}

function throwUnhandledError(...args) {
  let err

  if (args.length > 0) err = args[0]

  if (err instanceof Error === false) err = errors.UNHANDLED_ERROR(err)

  if (Error.captureStackTrace) {
    Error.captureStackTrace(err, exports.prototype.emit)
  }

  queueMicrotask(() => {
    throw err
  })
}

module.exports = exports = class EventEmitter {
  constructor() {
    this._events = Object.create(null)
  }

  addListener(name, fn) {
    return appendListener(this, name, fn, false)
  }

  addOnceListener(name, fn) {
    return appendListener(this, name, fn, true)
  }

  prependListener(name, fn) {
    return prependListener(this, name, fn, false)
  }

  prependOnceListener(name, fn) {
    return prependListener(this, name, fn, true)
  }

  removeListener(name, fn) {
    return removeListener(this, name, fn)
  }

  on(name, fn) {
    return appendListener(this, name, fn, false)
  }

  once(name, fn) {
    return appendListener(this, name, fn, true)
  }

  off(name, fn) {
    return removeListener(this, name, fn)
  }

  emit(name, ...args) {
    if (name === 'error' && this._events !== undefined && this._events.error === undefined) {
      throwUnhandledError(...args)
    }

    if (this._events === undefined) return false
    const e = this._events[name]
    return e === undefined ? false : e.emit(this, name, ...args)
  }

  listeners(name) {
    if (this._events === undefined) return []
    const e = this._events[name]
    return e === undefined ? [] : [...e.list]
  }

  rawListeners(name) {
    if (this._events === undefined) return []
    const e = this._events[name]
    return e === undefined ? [] : e.list.map((l) => l[0])
  }

  eventNames() {
    if (this._events === undefined) return []
    return Reflect.ownKeys(this._events)
  }

  listenerCount(name) {
    if (this._events === undefined) return 0
    const e = this._events[name]
    return e === undefined ? 0 : e.list.length
  }

  getMaxListeners() {
    return EventEmitter.defaultMaxListeners
  }

  setMaxListeners(n) {}

  removeAllListeners(name) {
    if (arguments.length === 0) {
      for (const key of Reflect.ownKeys(this._events)) {
        if (key === 'removeListener') continue
        this.removeAllListeners(key)
      }
      this.removeAllListeners('removeListener')
    } else {
      const e = this._events[name]
      if (e !== undefined) e.removeAll(this, name)
    }
    return this
  }
}

exports.EventEmitter = exports

exports.errors = errors

exports.defaultMaxListeners = 10

exports.on = function on(emitter, name, opts = {}) {
  const { signal } = opts

  if (signal && signal.aborted) {
    throw errors.OPERATION_ABORTED(signal.reason)
  }

  let error = null
  let done = false

  const events = []
  const promises = []

  if (name !== 'error') emitter.on('error', onerror)

  if (signal) signal.addEventListener('abort', onabort)

  emitter.on(name, onevent)

  return {
    next() {
      if (events.length) {
        return Promise.resolve({ value: events.shift(), done: false })
      }

      if (error) {
        const err = error

        error = null

        return Promise.reject(err)
      }

      if (done) return onclose()

      return new Promise((resolve, reject) => promises.push({ resolve, reject }))
    },

    return() {
      return onclose()
    },

    throw(err) {
      return onerror(err)
    },

    [Symbol.asyncIterator]() {
      return this
    }
  }

  function onevent(...args) {
    if (promises.length) {
      promises.shift().resolve({ value: args, done: false })
    } else {
      events.push(args)
    }
  }

  function onerror(err) {
    emitter.off(name, onevent).off('error', onerror)

    if (promises.length) {
      promises.shift().reject(err)
    } else {
      error = err
    }

    return Promise.resolve({ done: true })
  }

  function onabort() {
    signal.removeEventListener('abort', onabort)

    onerror(errors.OPERATION_ABORTED(signal.reason))
  }

  function onclose() {
    emitter.off(name, onevent)

    if (name !== 'error') emitter.off('error', onerror)

    if (signal) signal.removeEventListener('abort', onabort)

    done = true

    if (promises.length) promises.shift().resolve({ done: true })

    return Promise.resolve({ done: true })
  }
}

exports.once = function once(emitter, name, opts = {}) {
  const { signal } = opts

  if (signal && signal.aborted) {
    return Promise.reject(errors.OPERATION_ABORTED(signal.reason))
  }

  return new Promise((resolve, reject) => {
    if (name !== 'error') emitter.on('error', onerror)

    if (signal) signal.addEventListener('abort', onabort)

    emitter.once(name, onevent)

    function onevent(...args) {
      if (name !== 'error') emitter.off('error', onerror)

      if (signal) signal.removeEventListener('abort', onabort)

      resolve(args)
    }

    function onerror(err) {
      emitter.off(name, onevent)

      if (name !== 'error') emitter.off('error', onerror)

      reject(err)
    }

    function onabort() {
      signal.removeEventListener('abort', onabort)

      onerror(errors.OPERATION_ABORTED(signal.reason))
    }
  })
}

exports.forward = function forward(from, to, names, opts = {}) {
  if (typeof names === 'string') names = [names]

  const { emit = to.emit.bind(to) } = opts

  const listeners = names.map(
    (name) =>
      function onevent(...args) {
        emit(name, ...args)
      }
  )

  to.on('newListener', (name) => {
    const i = names.indexOf(name)

    if (i !== -1 && to.listenerCount(name) === 0) {
      from.on(name, listeners[i])
    }
  }).on('removeListener', (name) => {
    const i = names.indexOf(name)

    if (i !== -1 && to.listenerCount(name) === 0) {
      from.off(name, listeners[i])
    }
  })
}

exports.listenerCount = function listenerCount(emitter, name) {
  return emitter.listenerCount(name)
}

exports.getMaxListeners = function getMaxListeners(emitter) {
  if (typeof emitter.getMaxListeners === 'function') {
    return emitter.getMaxListeners()
  }

  return exports.defaultMaxListeners
}

exports.setMaxListeners = function setMaxListeners(n, ...emitters) {
  if (emitters.length === 0) exports.defaultMaxListeners = n
  else {
    for (const emitter of emitters) {
      if (typeof emitter.setMaxListeners === 'function') {
        emitter.setMaxListeners(n)
      }
    }
  }
}
module.exports = class EventEmitterError extends Error {
  constructor(msg, code, fn = EventEmitterError, opts) {
    super(`${code}: ${msg}`, opts)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'EventEmitterError'
  }

  static OPERATION_ABORTED(cause, msg = 'Operation aborted') {
    return new EventEmitterError(msg, 'OPERATION_ABORTED', EventEmitterError.OPERATION_ABORTED, {
      cause
    })
  }

  static UNHANDLED_ERROR(cause, msg = 'Unhandled error') {
    return new EventEmitterError(msg, 'UNHANDLED_ERROR', EventEmitterError.UNHANDLED_ERROR, {
      cause
    })
  }
}
{
  "name": "bare-events",
  "version": "2.9.1",
  "description": "Event emitters for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    },
    "./web": {
      "types": "./web.d.ts",
      "default": "./web.js"
    },
    "./errors": "./lib/errors.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "global.js",
    "global.d.ts",
    "web.js",
    "web.d.ts",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:bare && npm run test:node",
    "test:bare": "brittle-bare --coverage test.js",
    "test:node": "brittle-node --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-events.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-events/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-events#readme",
  "devDependencies": {
    "bare-abort-controller": "^1.0.0",
    "brittle": "^3.3.2",
    "lunte": "^1.8.0",
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^2.0.0",
    "uncaughts": "^1.1.1"
  },
  "peerDependencies": {
    "bare-abort-controller": "*"
  },
  "peerDependenciesMeta": {
    "bare-abort-controller": {
      "optional": true
    }
  }
}
module.exports = require.addon()
const FIFO = require('fast-fifo')
const EventEmitter = require('bare-events')
const path = require('bare-path')
const { isURL, fileURLToPath } = require('bare-url')
const { Readable, Writable } = require('bare-stream')
const binding = require('./binding')
const constants = require('./lib/constants')
const FileError = require('./lib/errors')

const isWindows = Bare.platform === 'win32'

exports.constants = constants

class FileRequest {
  static borrow() {
    if (this._free.length > 0) return this._free.pop()
    return new FileRequest()
  }

  static return(req) {
    if (this._free.length < 32) this._free.push(req.reset())
    else req.destroy()
  }

  constructor() {
    this._reset()
    this._handle = binding.requestInit(this, this._onresult)
  }

  get handle() {
    return this._handle
  }

  retain(value) {
    this._retain = value // Tie the lifetime of `value` to the lifetime of `this`
  }

  reset() {
    if (this._handle === null) return this

    binding.requestReset(this._handle)

    this._reset()

    return this
  }

  destroy() {
    if (this._handle === null) return this

    binding.requestDestroy(this._handle)

    this._reset()
    this._handle = null

    return this
  }

  then(resolve, reject) {
    return this._promise.then(resolve, reject)
  }

  return() {
    if (this._handle === null) return this

    FileRequest.return(this)

    return this
  }

  _reset() {
    this._promise = new Promise((resolve, reject) => {
      this._resolve = resolve
      this._reject = reject
    })
    this._retain = null
  }

  _onresult(err, status) {
    if (err) this._reject(err)
    else this._resolve(status)
  }
}

FileRequest._free = []

function ok(result, cb) {
  if (typeof result === 'function') {
    cb = result
    result = undefined
  }

  if (cb) cb(null, result)
  else return result
}

function fail(err, cb) {
  if (cb) cb(err)
  else throw err
}

function done(err, result, cb) {
  if (typeof result === 'function') {
    cb = result
    result = undefined
  }

  if (err) fail(err, cb)
  else return ok(result, cb)
}

async function open(filepath, flags = 'r', mode = 0o666, cb) {
  if (typeof flags === 'function') {
    cb = flags
    flags = 'r'
    mode = 0o666
  } else if (typeof mode === 'function') {
    cb = mode
    mode = 0o666
  }

  if (typeof flags === 'string') flags = toFlags(flags)
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let fd
  let err = null
  try {
    binding.open(req.handle, filepath, flags, mode)

    fd = await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'open',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, fd, cb)
}

function openSync(filepath, flags = 'r', mode = 0o666) {
  if (typeof flags === 'string') flags = toFlags(flags)
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    return binding.openSync(req.handle, filepath, flags, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'open',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function close(fd, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.close(req.handle, fd)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'close', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function closeSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.closeSync(req.handle, fd)
  } catch (e) {
    throw new FileError(e.message, { operation: 'close', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function access(filepath, mode = constants.F_OK, cb) {
  if (typeof mode === 'function') {
    cb = mode
    mode = constants.F_OK
  }

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.access(req.handle, filepath, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'access',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function accessSync(filepath, mode = constants.F_OK) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.accessSync(req.handle, filepath, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'access',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function exists(filepath, cb) {
  let ok = true
  try {
    await access(filepath)
  } catch {
    ok = false
  }

  return done(null, ok, cb)
}

function existsSync(filepath) {
  try {
    accessSync(filepath)
  } catch {
    return false
  }

  return true
}

async function read(fd, buffer, offset = 0, len = buffer.byteLength - offset, pos = -1, cb) {
  if (typeof offset === 'function') {
    cb = offset
    offset = 0
    len = buffer.byteLength
    pos = -1
  } else if (typeof len === 'function') {
    cb = len
    len = buffer.byteLength - offset
    pos = -1
  } else if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.read(req.handle, fd, buffer, offset, len, pos)

    req.retain(buffer)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'read', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function readSync(fd, buffer, offset = 0, len = buffer.byteLength - offset, pos = -1) {
  const req = FileRequest.borrow()

  try {
    return binding.readSync(req.handle, fd, buffer, offset, len, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'read', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function readv(fd, buffers, pos = -1, cb) {
  if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.readv(req.handle, fd, buffers, pos)

    req.retain(buffers)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'readv', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function readvSync(fd, buffers, pos = -1) {
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  try {
    return binding.readvSync(req.handle, fd, buffers, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'readv', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function write(fd, data, offset, len, pos = -1, cb) {
  if (typeof data === 'string') {
    let encoding = len
    cb = pos
    pos = offset

    if (typeof pos === 'function') {
      cb = pos
      pos = -1
      encoding = 'utf8'
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = 'utf8'
    }

    if (typeof pos === 'string') {
      encoding = pos
      pos = -1
    }

    data = Buffer.from(data, encoding)
    offset = 0
    len = data.byteLength
  } else if (typeof offset === 'function') {
    cb = offset
    offset = 0
    len = data.byteLength
    pos = -1
  } else if (typeof len === 'function') {
    cb = len
    len = data.byteLength - offset
    pos = -1
  } else if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof offset !== 'number') offset = 0
  if (typeof len !== 'number') len = data.byteLength - offset
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.write(req.handle, fd, data, offset, len, pos)

    req.retain(data)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'write', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function writeSync(fd, data, offset, len, pos = -1) {
  if (typeof data === 'string') {
    let encoding = len
    pos = offset

    if (typeof pos === 'string') {
      encoding = pos
      pos = -1
    }

    data = Buffer.from(data, encoding)
    offset = 0
    len = data.byteLength
  }

  if (typeof offset !== 'number') offset = 0
  if (typeof len !== 'number') len = data.byteLength - offset
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  try {
    return binding.writeSync(req.handle, fd, data, offset, len, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'write', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function writev(fd, buffers, pos = -1, cb) {
  if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.writev(req.handle, fd, buffers, pos)

    req.retain(buffers)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'writev', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function writevSync(fd, buffers, pos = -1) {
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  try {
    return binding.writevSync(req.handle, fd, buffers, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'writev', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function stat(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.stat(req.handle, filepath)

    await req

    st = new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'stat', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function statSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.statSync(req.handle, filepath)

    return new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'stat', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function lstat(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.lstat(req.handle, filepath)

    await req

    st = new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'lstat', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function lstatSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.lstatSync(req.handle, filepath)

    return new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'lstat', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function fstat(fd, cb) {
  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.fstat(req.handle, fd)

    await req

    st = new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'fstat', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function fstatSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.fstatSync(req.handle, fd)

    return new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'fstat', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function statfs(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.statfs(req.handle, filepath)

    await req

    st = new StatFs(...binding.requestResultStatfs(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'statfs', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function statfsSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.statfsSync(req.handle, filepath)

    return new StatFs(...binding.requestResultStatfs(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'statfs', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function ftruncate(fd, len = 0, cb) {
  if (typeof len === 'function') {
    cb = len
    len = 0
  }

  if (typeof len !== 'number') len = 0

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.ftruncate(req.handle, fd, len)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'ftruncate', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function ftruncateSync(fd, len = 0) {
  if (typeof len !== 'number') len = 0

  const req = FileRequest.borrow()

  try {
    binding.ftruncateSync(req.handle, fd, len)
  } catch (e) {
    throw new FileError(e.message, { operation: 'ftruncate', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function truncate(filepath, len, cb) {
  let fd = -1
  let err

  try {
    fd = await open(filepath, 'r+')

    await ftruncate(fd, len)
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) await close(fd)
  }

  return done(err, cb)
}

function truncateSync(filepath, len) {
  let fd = -1
  let err

  try {
    fd = openSync(filepath, 'r+')

    ftruncateSync(fd, len)
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) closeSync(fd)
  }
}

async function chmod(filepath, mode, cb) {
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.chmod(req.handle, filepath, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'chmod',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function chmodSync(filepath, mode) {
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.chmodSync(req.handle, filepath, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'chmod',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function fchmod(fd, mode, cb) {
  if (typeof mode === 'string') mode = toMode(mode)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fchmod(req.handle, fd, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fchmod', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fchmodSync(fd, mode) {
  if (typeof mode === 'string') mode = toMode(mode)

  const req = FileRequest.borrow()

  try {
    binding.fchmodSync(req.handle, fd, mode)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fchmod', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function chown(filepath, uid, gid, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.chown(req.handle, filepath, uid, gid)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'chown', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function chownSync(filepath, uid, gid) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.chownSync(req.handle, filepath, uid, gid)
  } catch (e) {
    throw new FileError(e.message, { operation: 'chownSync', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function lchown(filepath, uid, gid, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.lchown(req.handle, filepath, uid, gid)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'lchown', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function lchownSync(filepath, uid, gid) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.lchownSync(req.handle, filepath, uid, gid)
  } catch (e) {
    throw new FileError(e.message, { operation: 'lchownSync', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function fchown(fd, uid, gid, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fchown(req.handle, fd, uid, gid)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fchown', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fchownSync(fd, uid, gid) {
  const req = FileRequest.borrow()

  try {
    binding.fchownSync(req.handle, fd, uid, gid)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fchownSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function utimes(filepath, atime, mtime, cb) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.utimes(req.handle, filepath, atime, mtime)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'utimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function utimesSync(filepath, atime, mtime) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.utimesSync(req.handle, filepath, atime, mtime)
  } catch (e) {
    throw new FileError(e.message, { operation: 'utimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function lutimes(filepath, atime, mtime, cb) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.lutimes(req.handle, filepath, atime, mtime)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'lutimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function lutimesSync(filepath, atime, mtime) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.lutimesSync(req.handle, filepath, atime, mtime)
  } catch (e) {
    throw new FileError(e.message, { operation: 'lutimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function futimes(fd, atime, mtime, cb) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.futimes(req.handle, fd, atime, mtime)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'futimes', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function futimesSync(fd, atime, mtime) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  const req = FileRequest.borrow()

  try {
    binding.futimesSync(req.handle, fd, atime, mtime)
  } catch (e) {
    throw new FileError(e.message, { operation: 'futimesSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function link(src, dst, cb) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.link(req.handle, src, dst)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'link', code: e.code, path: src, destination: dst })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function linkSync(src, dst) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  try {
    binding.linkSync(req.handle, src, dst)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'linkSync',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }
}

async function mkdir(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = { mode: 0o777 }
  }

  if (typeof opts === 'number') opts = { mode: opts }
  else if (!opts) opts = {}

  const mode = typeof opts.mode === 'number' ? opts.mode : 0o777

  filepath = toNamespacedPath(filepath)

  if (opts.recursive) {
    let err = null
    try {
      try {
        await mkdir(filepath, { mode })
      } catch (err) {
        if (err.code !== 'ENOENT') {
          if (!(await stat(filepath)).isDirectory()) throw err
        } else {
          while (filepath.endsWith(path.sep)) filepath = filepath.slice(0, -1)
          const i = filepath.lastIndexOf(path.sep)
          if (i <= 0) throw err

          await mkdir(filepath.slice(0, i), { mode, recursive: true })

          try {
            await mkdir(filepath, { mode })
          } catch (err) {
            if (!(await stat(filepath)).isDirectory()) throw err
          }
        }
      }
    } catch (e) {
      err = e
    }

    return done(err, cb)
  }

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.mkdir(req.handle, filepath, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'mkdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function mkdirSync(filepath, opts) {
  if (typeof opts === 'number') opts = { mode: opts }
  else if (!opts) opts = {}

  const mode = typeof opts.mode === 'number' ? opts.mode : 0o777

  filepath = toNamespacedPath(filepath)

  if (opts.recursive) {
    try {
      mkdirSync(filepath, { mode })
    } catch (err) {
      if (err.code !== 'ENOENT') {
        if (!statSync(filepath).isDirectory()) throw err
      } else {
        while (filepath.endsWith(path.sep)) filepath = filepath.slice(0, -1)
        const i = filepath.lastIndexOf(path.sep)
        if (i <= 0) throw err

        mkdirSync(filepath.slice(0, i), { mode, recursive: true })

        try {
          mkdirSync(filepath, { mode })
        } catch (err) {
          if (!statSync(filepath).isDirectory()) throw err
        }
      }
    }

    return
  }

  const req = FileRequest.borrow()

  try {
    binding.mkdirSync(req.handle, filepath, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'mkdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function mkdtemp(prefix, cb) {
  prefix = toNamespacedPath(prefix)

  const req = FileRequest.borrow()

  let res
  let err = null
  try {
    binding.mkdtemp(req.handle, prefix + 'XXXXXX')

    await req

    res = binding.requestResultPath(req.handle)
  } catch (e) {
    err = new FileError(e.message, { operation: 'mkdtemp', code: e.code, path: prefix })
  } finally {
    req.return()
  }

  return done(err, res, cb)
}

function mkdtempSync(prefix) {
  prefix = toNamespacedPath(prefix)

  const req = FileRequest.borrow()

  try {
    binding.mkdtempSync(req.handle, prefix + 'XXXXXX')

    return binding.requestResultPath(req.handle)
  } catch (e) {
    throw new FileError(e.message, { operation: 'mkdtempSync', code: e.code, path: prefix })
  } finally {
    req.return()
  }
}

async function rmdir(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.rmdir(req.handle, filepath)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'rmdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function rmdirSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.rmdirSync(req.handle, filepath)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'rmdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function rm(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  let err = null
  try {
    const st = await lstat(filepath)

    if (st.isDirectory()) {
      if (opts.recursive) {
        try {
          await rmdir(filepath)
        } catch (err) {
          if (err.code !== 'ENOTEMPTY') throw err

          const files = await readdir(filepath)

          for (const file of files) {
            await rm(filepath + path.sep + file, opts)
          }

          await rmdir(filepath)
        }
      } else {
        throw new FileError('is a directory', {
          operation: 'rm',
          code: 'EISDIR',
          path: filepath
        })
      }
    } else {
      await unlink(filepath)
    }
  } catch (e) {
    if (e.code !== 'ENOENT' || !opts.force) err = e
  }

  return done(err, cb)
}

function rmSync(filepath, opts) {
  if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  try {
    const st = lstatSync(filepath)

    if (st.isDirectory()) {
      if (opts.recursive) {
        try {
          rmdirSync(filepath)
        } catch (err) {
          if (err.code !== 'ENOTEMPTY') throw err

          const files = readdirSync(filepath)

          for (const file of files) {
            rmSync(filepath + path.sep + file, opts)
          }

          rmdirSync(filepath)
        }
      } else {
        throw new FileError('is a directory', {
          operation: 'rm',
          code: 'EISDIR',
          path: filepath
        })
      }
    } else {
      unlinkSync(filepath)
    }
  } catch (err) {
    if (err.code !== 'ENOENT' || !opts.force) throw err
  }
}

async function unlink(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.unlink(req.handle, filepath)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'unlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function unlinkSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.unlinkSync(req.handle, filepath)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'unlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function rename(src, dst, cb) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.rename(req.handle, src, dst)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'rename',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function renameSync(src, dst) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  try {
    binding.renameSync(req.handle, src, dst)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'rename',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }
}

async function copyFile(src, dst, mode = 0, cb) {
  if (typeof mode === 'function') {
    cb = mode
    mode = 0
  }

  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.copyfile(req.handle, src, dst, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'copyfile',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function copyFileSync(src, dst, mode = 0) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  try {
    binding.copyfileSync(req.handle, src, dst, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'copyfile',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }
}

async function cp(src, dst, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (!opts) opts = {}

  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  let err = null
  try {
    const st = await lstat(src)

    if (st.isDirectory()) {
      if (opts.recursive !== true) {
        throw new FileError('is a directory', { operation: 'cp', code: 'EISDIR', path: src })
      }

      try {
        await lstat(dst)
      } catch (e) {
        if (e.code !== 'ENOENT') throw e

        await mkdir(dst, { mode: st.mode, recursive: true })
      }

      const dir = await opendir(src)
      for await (const { name } of dir) {
        await cp(path.join(src, name), path.join(dst, name), opts)
      }
    } else if (st.isFile()) {
      await copyFile(src, dst)
      await chmod(dst, st.mode)
    }
  } catch (e) {
    err = e
  }

  return done(err, cb)
}

function cpSync(src, dst, opts = {}) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const st = lstatSync(src)

  if (st.isDirectory()) {
    if (opts.recursive !== true) {
      throw new FileError('is a directory', { operation: 'cp', code: 'EISDIR', path: src })
    }

    try {
      lstatSync(dst)
    } catch (e) {
      if (e.code !== 'ENOENT') throw e

      mkdirSync(dst, { mode: st.mode, recursive: true })
    }

    const dir = opendirSync(src)
    for (const { name } of dir) {
      cpSync(path.join(src, name), path.join(dst, name), opts)
    }
  } else if (st.isFile()) {
    copyFileSync(src, dst)
    chmodSync(dst, st.mode)
  }
}

async function realpath(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let res
  let err = null
  try {
    binding.realpath(req.handle, filepath)

    await req

    res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'realpath',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, res, cb)
}

function realpathSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.realpathSync(req.handle, filepath)

    let res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)

    return res
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'realpath',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function readlink(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let res
  let err = null
  try {
    binding.readlink(req.handle, filepath)

    await req

    res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'readlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, res, cb)
}

function readlinkSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.readlinkSync(req.handle, filepath)

    let res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)

    return res
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'readlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function fsync(fd, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fsync(req.handle, fd)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fsync', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fsyncSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.fsyncSync(req.handle, fd)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fsyncSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function fdatasync(fd, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fdatasync(req.handle, fd)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fdatasync', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fdatasyncSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.fdatasyncSync(req.handle, fd)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fdatasyncSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

function normalizeSymlinkTarget(target, type, filepath) {
  if (isWindows) {
    if (type === constants.UV_FS_SYMLINK_JUNCTION) target = path.resolve(filepath, '..', target)

    if (path.isAbsolute(target)) return path.toNamespacedPath(target)

    return target.replace(/\//g, path.sep)
  }

  return target
}

async function symlink(target, filepath, type, cb) {
  if (typeof type === 'function') {
    cb = type
    type = null
  }

  filepath = toNamespacedPath(filepath)

  if (typeof type === 'string') {
    switch (type) {
      case 'dir':
        type = constants.UV_FS_SYMLINK_DIR
        break
      case 'junction':
        type = constants.UV_FS_SYMLINK_JUNCTION
        break
      case 'file':
      default:
        type = 0
        break
    }
  } else if (typeof type !== 'number') {
    if (isWindows) {
      target = path.resolve(filepath, '..', target)

      try {
        type = (await stat(target)).isDirectory()
          ? constants.UV_FS_SYMLINK_DIR
          : constants.UV_FS_SYMLINK_JUNCTION
      } catch {
        type = 0
      }
    } else {
      type = 0
    }
  }

  target = normalizeSymlinkTarget(target, type, filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.symlink(req.handle, target, filepath, type)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'symlink',
      code: e.code,
      path: target,
      destination: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function symlinkSync(target, filepath, type) {
  filepath = toNamespacedPath(filepath)

  if (typeof type === 'string') {
    switch (type) {
      case 'dir':
        type = constants.UV_FS_SYMLINK_DIR
        break
      case 'junction':
        type = constants.UV_FS_SYMLINK_JUNCTION
        break
      case 'file':
      default:
        type = 0
        break
    }
  } else if (typeof type !== 'number') {
    if (isWindows) {
      target = path.resolve(filepath, '..', target)

      try {
        type = statSync(target).isDirectory()
          ? constants.UV_FS_SYMLINK_DIR
          : constants.UV_FS_SYMLINK_JUNCTION
      } catch {
        type = 0
      }
    } else {
      type = 0
    }
  }

  target = normalizeSymlinkTarget(target, type, filepath)

  const req = FileRequest.borrow()

  try {
    binding.symlinkSync(req.handle, target, filepath, type)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'symlink',
      code: e.code,
      path: target,
      destination: filepath
    })
  } finally {
    req.return()
  }
}

async function opendir(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let dir
  let err = null
  try {
    binding.opendir(req.handle, filepath)

    await req

    dir = new Dir(filepath, binding.requestResultDir(req.handle), opts)
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'opendir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, dir, cb)
}

function opendirSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.opendirSync(req.handle, filepath)

    return new Dir(filepath, binding.requestResultDir(req.handle), opts)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'opendir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function readdir(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { withFileTypes = false, recursive = false } = opts

  filepath = toNamespacedPath(filepath)

  const queue = [filepath]
  let result = []
  let err = null
  try {
    while (queue.length !== 0) {
      const dir = await opendir(queue.pop())

      for await (const entry of dir) {
        const entryPath = path.join(entry.parentPath, entry.name)

        if (withFileTypes) {
          result.push(entry)
        } else {
          result.push(path.relative(filepath, entryPath))
        }

        if (recursive && entry.isDirectory()) queue.push(entryPath)
      }
    }
  } catch (e) {
    result = []
    err = e
  }

  return done(err, result, cb)
}

function readdirSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { withFileTypes = false, recursive = false } = opts

  filepath = toNamespacedPath(filepath)

  const queue = [filepath]
  const result = []

  while (queue.length !== 0) {
    const dir = opendirSync(queue.pop(), opts)

    for (const entry of dir) {
      const entryPath = path.join(entry.parentPath, entry.name)

      if (withFileTypes) {
        result.push(entry)
      } else {
        result.push(path.relative(filepath, entryPath))
      }

      if (recursive && entry.isDirectory()) queue.push(entryPath)
    }
  }

  return result
}

async function readFile(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'buffer' } = opts

  let fd = -1
  let buffer = null
  let err = null
  try {
    fd = await open(filepath, opts.flag || 'r')

    const st = await fstat(fd)

    let len = 0

    if (st.size === 0) {
      const buffers = []

      while (true) {
        buffer = Buffer.allocUnsafe(8192)
        const r = await read(fd, buffer)
        len += r
        if (r === 0) break
        buffers.push(buffer.subarray(0, r))
      }

      buffer = Buffer.concat(buffers)
    } else {
      buffer = Buffer.allocUnsafe(st.size)

      while (true) {
        const r = await read(fd, len ? buffer.subarray(len) : buffer)
        len += r
        if (r === 0 || len === buffer.byteLength) break
      }

      if (len !== buffer.byteLength) buffer = buffer.subarray(0, len)
    }

    if (encoding !== 'buffer') buffer = buffer.toString(encoding)
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) await close(fd)
  }

  return done(err, buffer, cb)
}

function readFileSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'buffer' } = opts

  let fd = -1
  try {
    fd = openSync(filepath, opts.flag || 'r')

    const st = fstatSync(fd)

    let buffer
    let len = 0

    if (st.size === 0) {
      const buffers = []

      while (true) {
        buffer = Buffer.allocUnsafe(8192)
        const r = readSync(fd, buffer)
        len += r
        if (r === 0) break
        buffers.push(buffer.subarray(0, r))
      }

      buffer = Buffer.concat(buffers)
    } else {
      buffer = Buffer.allocUnsafe(st.size)

      while (true) {
        const r = readSync(fd, len ? buffer.subarray(len) : buffer)
        len += r
        if (r === 0 || len === buffer.byteLength) break
      }

      if (len !== buffer.byteLength) buffer = buffer.subarray(0, len)
    }

    if (encoding !== 'buffer') buffer = buffer.toString(encoding)

    return buffer
  } finally {
    if (fd !== -1) closeSync(fd)
  }
}

async function writeFile(filepath, data, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (typeof data === 'string') data = Buffer.from(data, opts.encoding)

  let fd = -1
  let len = 0
  let err = null
  try {
    fd = await open(filepath, opts.flag || 'w', opts.mode || 0o666)

    while (true) {
      len += await write(fd, len ? data.subarray(len) : data)
      if (len === data.byteLength) break
    }
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) await close(fd)
  }

  return done(err, len, cb)
}

function writeFileSync(filepath, data, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (typeof data === 'string') data = Buffer.from(data, opts.encoding)

  let fd = -1
  try {
    fd = openSync(filepath, opts.flag || 'w', opts.mode || 0o666)

    let len = 0

    while (true) {
      len += writeSync(fd, len ? data.subarray(len) : data)
      if (len === data.byteLength) break
    }
  } finally {
    if (fd !== -1) closeSync(fd)
  }
}

function appendFile(filepath, data, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (!opts.flag) opts = { ...opts, flag: 'a' }

  return writeFile(filepath, data, opts, cb)
}

function appendFileSync(filepath, data, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (!opts.flag) opts = { ...opts, flag: 'a' }

  return writeFileSync(filepath, data, opts)
}

function watch(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  return new Watcher(filepath, opts, cb)
}

class Stats {
  constructor(
    dev,
    mode,
    nlink,
    uid,
    gid,
    rdev,
    blksize,
    ino,
    size,
    blocks,
    atimeMs,
    mtimeMs,
    ctimeMs,
    birthtimeMs
  ) {
    this.dev = dev
    this.mode = mode
    this.nlink = nlink
    this.uid = uid
    this.gid = gid
    this.rdev = rdev
    this.blksize = blksize
    this.ino = ino
    this.size = size
    this.blocks = blocks
    this.atimeMs = atimeMs
    this.mtimeMs = mtimeMs
    this.ctimeMs = ctimeMs
    this.birthtimeMs = birthtimeMs
    this.atime = new Date(atimeMs)
    this.mtime = new Date(mtimeMs)
    this.ctime = new Date(ctimeMs)
    this.birthtime = new Date(birthtimeMs)
  }

  isDirectory() {
    return (this.mode & constants.S_IFMT) === constants.S_IFDIR
  }

  isFile() {
    return (this.mode & constants.S_IFMT) === constants.S_IFREG
  }

  isBlockDevice() {
    return (this.mode & constants.S_IFMT) === constants.S_IFBLK
  }

  isCharacterDevice() {
    return (this.mode & constants.S_IFMT) === constants.S_IFCHR
  }

  isFIFO() {
    return (this.mode & constants.S_IFMT) === constants.S_IFIFO
  }

  isSymbolicLink() {
    return (this.mode & constants.S_IFMT) === constants.S_IFLNK
  }

  isSocket() {
    return (this.mode & constants.S_IFMT) === constants.S_IFSOCK
  }
}

class StatFs {
  constructor(type, bsize, blocks, bfree, bavail, files, ffree) {
    this.type = type
    this.bsize = bsize
    this.blocks = blocks
    this.bfree = bfree
    this.bavail = bavail
    this.files = files
    this.ffree = ffree
  }
}

class Dir {
  constructor(path, handle, opts = {}) {
    const { encoding = 'utf8', bufferSize = 32 } = opts

    this.path = path

    this._encoding = encoding
    this._capacity = bufferSize
    this._buffer = new FIFO()
    this._ended = false
    this._handle = handle
  }

  async read(cb) {
    if (this._buffer.length) return ok(this._buffer.shift(), cb)
    if (this._ended) return ok(null, cb)

    const req = FileRequest.borrow()

    let entries
    let err = null
    try {
      req.retain(binding.readdir(req.handle, this._handle, this._capacity))

      await req

      entries = binding.requestResultDirents(req.handle)
    } catch (e) {
      err = new FileError(e.message, {
        operation: 'readdir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    if (err) return fail(err, cb)

    if (entries.length === 0) {
      this._ended = true

      return ok(null, cb)
    }

    for (const entry of entries) {
      let name = Buffer.from(entry.name)

      if (this._encoding !== 'buffer') name = name.toString(this._encoding)

      this._buffer.push(new Dirent(this.path, name, entry.type))
    }

    return ok(this._buffer.shift(), cb)
  }

  readSync() {
    if (this._buffer.length) return this._buffer.shift()
    if (this._ended) return null

    const req = FileRequest.borrow()

    let entries
    try {
      req.retain(binding.readdirSync(req.handle, this._handle, this._capacity))

      entries = binding.requestResultDirents(req.handle)
    } catch (e) {
      throw new FileError(e.message, {
        operation: 'readdir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    if (entries.length === 0) {
      this._ended = true

      return null
    }

    for (const entry of entries) {
      let name = Buffer.from(entry.name)

      if (this._encoding !== 'buffer') name = name.toString(this._encoding)

      this._buffer.push(new Dirent(this.path, name, entry.type))
    }

    return this._buffer.shift()
  }

  async close(cb) {
    const req = FileRequest.borrow()

    let err = null
    try {
      binding.closedir(req.handle, this._handle)

      await req
    } catch (e) {
      err = new FileError(e.message, {
        operation: 'closedir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    this._handle = null

    return done(err, cb)
  }

  closeSync() {
    const req = FileRequest.borrow()

    try {
      binding.closedirSync(req.handle, this._handle)
    } catch (e) {
      throw new FileError(e.message, {
        operation: 'closedir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    this._handle = null
  }

  [Symbol.dispose]() {
    this.closeSync()
  }

  async [Symbol.asyncDispose]() {
    await this.close()
  }

  *[Symbol.iterator]() {
    while (true) {
      const entry = this.readSync()
      if (entry === null) break
      yield entry
    }

    this.closeSync()
  }

  async *[Symbol.asyncIterator]() {
    while (true) {
      const entry = await this.read()
      if (entry === null) break
      yield entry
    }

    await this.close()
  }
}

class Dirent {
  constructor(parentPath, name, type) {
    this.parentPath = parentPath
    this.name = name
    this.type = type
  }

  isFile() {
    return this.type === constants.UV_DIRENT_FILE
  }

  isDirectory() {
    return this.type === constants.UV_DIRENT_DIR
  }

  isSymbolicLink() {
    return this.type === constants.UV_DIRENT_LINK
  }

  isFIFO() {
    return this.type === constants.UV_DIRENT_FIFO
  }

  isSocket() {
    return this.type === constants.UV_DIRENT_SOCKET
  }

  isCharacterDevice() {
    return this.type === constants.UV_DIRENT_CHAR
  }

  isBlockDevice() {
    return this.type === constants.UV_DIRENT_BLOCK
  }
}

class FileReadStream extends Readable {
  constructor(path, opts = {}) {
    const { eagerOpen = true } = opts

    super({ eagerOpen, ...opts })

    this.path = path
    this.fd = typeof opts.fd === 'number' ? opts.fd : -1
    this.flags = opts.flags || 'r'
    this.mode = opts.mode || 0o666

    this._offset = opts.start || 0
    this._missing = 0

    if (opts.length) {
      this._missing = opts.length
    } else if (typeof opts.end === 'number') {
      this._missing = opts.end - this._offset + 1
    } else {
      this._missing = -1
    }
  }

  async _open(cb) {
    let err

    if (this.fd === -1) {
      err = null
      try {
        this.fd = await open(this.path, this.flags, this.mode)
      } catch (e) {
        err = e
      }

      if (err) return cb(err)
    }

    let st
    err = null
    try {
      st = await fstat(this.fd)
    } catch (e) {
      err = e
    }

    if (err) return cb(err)

    if (this._missing === -1) this._missing = st.size

    if (st.size < this._offset) {
      this._offset = st.size
      this._missing = 0
    } else if (st.size < this._offset + this._missing) {
      this._missing = st.size - this._offset
    }

    cb(null)
  }

  async _read(size) {
    if (this._missing <= 0) return this.push(null)

    const data = Buffer.allocUnsafe(Math.min(this._missing, size))

    let len
    let err = null
    try {
      len = await read(this.fd, data, 0, data.byteLength, this._offset)
    } catch (e) {
      err = e
    }

    if (err) return this.destroy(err)

    if (len === 0) return this.push(null)

    if (this._missing < len) len = this._missing

    this._missing -= len
    this._offset += len

    this.push(data.subarray(0, len))
  }

  async _destroy(err, cb) {
    if (this.fd === -1) return cb(err)

    try {
      await close(this.fd)
    } catch (e) {
      err = err || e
    }

    cb(err)
  }
}

class FileWriteStream extends Writable {
  constructor(path, opts = {}) {
    const { eagerOpen = true } = opts

    super({ eagerOpen, ...opts })

    this.path = path
    this.fd = typeof opts.fd === 'number' ? opts.fd : -1
    this.flags = opts.flags || 'w'
    this.mode = opts.mode || 0o666
  }

  async _open(cb) {
    if (this.fd !== -1) return cb(null)

    let err = null
    try {
      this.fd = await open(this.path, this.flags, this.mode)
    } catch (e) {
      err = e
    }

    cb(err)
  }

  async _writev(batch, cb) {
    let err = null
    try {
      await writev(
        this.fd,
        batch.map(({ chunk }) => chunk)
      )
    } catch (e) {
      err = e
    }

    cb(err)
  }

  async _destroy(err, cb) {
    if (this.fd === -1) return cb(err)

    try {
      await close(this.fd)
    } catch (e) {
      err = err || e
    }

    cb(err)
  }
}

class Watcher extends EventEmitter {
  constructor(path, opts, onchange) {
    if (typeof opts === 'function') {
      onchange = opts
      opts = {}
    }

    if (!opts) opts = {}

    const { persistent = true, recursive = false, encoding = 'utf8' } = opts

    super()

    this._closed = false
    this._encoding = encoding
    this._handle = binding.watcherInit(path, recursive, this, this._onevent, this._onclose)

    if (!persistent) this.unref()

    if (onchange) this.on('change', onchange)
  }

  close() {
    if (this._closed) return
    this._closed = true

    binding.watcherClose(this._handle)
  }

  ref() {
    if (this._handle) binding.watcherRef(this._handle)
    return this
  }

  unref() {
    if (this._handle) binding.watcherUnref(this._handle)
    return this
  }

  [Symbol.asyncIterator]() {
    const buffer = []
    let done = false
    let error = null
    let next = null

    this.on('change', (eventType, filename) => {
      if (next) {
        next.resolve({ done: false, value: { eventType, filename } })
        next = null
      } else {
        buffer.push({ eventType, filename })
      }
    })
      .on('error', (err) => {
        done = true
        error = err

        if (next) {
          next.reject(error)
          next = null
        }
      })
      .on('close', () => {
        done = true

        if (next) {
          next.resolve({ done })
          next = null
        }
      })

    return {
      next: () =>
        new Promise((resolve, reject) => {
          if (error) return reject(error)

          if (buffer.length) return resolve({ done: false, value: buffer.shift() })

          if (done) return resolve({ done })

          next = { resolve, reject }
        })
    }
  }

  _onevent(err, events, filename) {
    if (err) {
      this.close()
      this.emit('error', err)
    } else {
      const path =
        this._encoding === 'buffer'
          ? Buffer.from(filename)
          : Buffer.from(filename).toString(this._encoding)

      if (events & binding.UV_RENAME) {
        this.emit('change', 'rename', path)
      }

      if (events & binding.UV_CHANGE) {
        this.emit('change', 'change', path)
      }
    }
  }

  _onclose() {
    this._handle = null

    this.emit('close')
  }
}

exports.access = access
exports.appendFile = appendFile
exports.chmod = chmod
exports.chown = chown
exports.close = close
exports.copyFile = copyFile
exports.cp = cp
exports.exists = exists
exports.fchmod = fchmod
exports.fchown = fchown
exports.fdatasync = fdatasync
exports.fstat = fstat
exports.fsync = fsync
exports.ftruncate = ftruncate
exports.futimes = futimes
exports.lchown = lchown
exports.lutimes = lutimes
exports.link = link
exports.lstat = lstat
exports.mkdir = mkdir
exports.mkdtemp = mkdtemp
exports.open = open
exports.opendir = opendir
exports.read = read
exports.readFile = readFile
exports.readdir = readdir
exports.readlink = readlink
exports.readv = readv
exports.realpath = realpath
exports.rename = rename
exports.rm = rm
exports.rmdir = rmdir
exports.stat = stat
exports.statfs = statfs
exports.symlink = symlink
exports.truncate = truncate
exports.unlink = unlink
exports.utimes = utimes
exports.watch = watch
exports.write = write
exports.writeFile = writeFile
exports.writev = writev

exports.accessSync = accessSync
exports.appendFileSync = appendFileSync
exports.chmodSync = chmodSync
exports.chownSync = chownSync
exports.closeSync = closeSync
exports.copyFileSync = copyFileSync
exports.cpSync = cpSync
exports.existsSync = existsSync
exports.fchmodSync = fchmodSync
exports.fchownSync = fchownSync
exports.fdatasyncSync = fdatasyncSync
exports.fstatSync = fstatSync
exports.fsyncSync = fsyncSync
exports.ftruncateSync = ftruncateSync
exports.futimesSync = futimesSync
exports.lchownSync = lchownSync
exports.lutimesSync = lutimesSync
exports.linkSync = linkSync
exports.lstatSync = lstatSync
exports.mkdirSync = mkdirSync
exports.mkdtempSync = mkdtempSync
exports.openSync = openSync
exports.opendirSync = opendirSync
exports.readFileSync = readFileSync
exports.readSync = readSync
exports.readdirSync = readdirSync
exports.readlinkSync = readlinkSync
exports.readvSync = readvSync
exports.realpathSync = realpathSync
exports.renameSync = renameSync
exports.rmSync = rmSync
exports.rmdirSync = rmdirSync
exports.statSync = statSync
exports.statfsSync = statfsSync
exports.symlinkSync = symlinkSync
exports.truncateSync = truncateSync
exports.unlinkSync = unlinkSync
exports.utimesSync = utimesSync
exports.writeFileSync = writeFileSync
exports.writeSync = writeSync
exports.writevSync = writevSync

exports.promises = require('./promises')

exports.Stats = Stats
exports.StatFs = StatFs
exports.Dir = Dir
exports.Dirent = Dirent
exports.Watcher = Watcher

exports.ReadStream = FileReadStream

exports.createReadStream = function createReadStream(path, opts) {
  return new FileReadStream(path, opts)
}

exports.WriteStream = FileWriteStream

exports.createWriteStream = function createWriteStream(path, opts) {
  return new FileWriteStream(path, opts)
}

function toNamespacedPath(filepath) {
  if (typeof filepath !== 'string') {
    if (isURL(filepath)) filepath = fileURLToPath(filepath)
    else filepath = filepath.toString()
  }

  return path.toNamespacedPath(filepath)
}

function toFlags(flags) {
  switch (flags) {
    case 'r':
      return constants.O_RDONLY
    case 'rs': // Fall through.
    case 'sr':
      return constants.O_RDONLY | constants.O_SYNC
    case 'r+':
      return constants.O_RDWR
    case 'rs+': // Fall through.
    case 'sr+':
      return constants.O_RDWR | constants.O_SYNC

    case 'w':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_WRONLY
    case 'wx': // Fall through.
    case 'xw':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_WRONLY | constants.O_EXCL

    case 'w+':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_RDWR
    case 'wx+': // Fall through.
    case 'xw+':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_RDWR | constants.O_EXCL

    case 'a':
      return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY
    case 'ax': // Fall through.
    case 'xa':
      return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY | constants.O_EXCL
    case 'as': // Fall through.
    case 'sa':
      return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY | constants.O_SYNC

    case 'a+':
      return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR
    case 'ax+': // Fall through.
    case 'xa+':
      return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR | constants.O_EXCL
    case 'as+': // Fall through.
    case 'sa+':
      return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR | constants.O_SYNC
    default:
      return 0
  }
}

function toMode(mode) {
  return parseInt(mode, 8)
}
const binding = require('../binding')

module.exports = {
  O_RDWR: binding.O_RDWR,
  O_RDONLY: binding.O_RDONLY,
  O_WRONLY: binding.O_WRONLY,
  O_CREAT: binding.O_CREAT,
  O_TRUNC: binding.O_TRUNC,
  O_APPEND: binding.O_APPEND,

  F_OK: binding.F_OK || 0,
  R_OK: binding.R_OK || 0,
  W_OK: binding.W_OK || 0,
  X_OK: binding.X_OK || 0,

  S_IFMT: binding.S_IFMT,
  S_IFREG: binding.S_IFREG,
  S_IFDIR: binding.S_IFDIR,
  S_IFCHR: binding.S_IFCHR,
  S_IFLNK: binding.S_IFLNK,
  S_IFBLK: binding.S_IFBLK || 0,
  S_IFIFO: binding.S_IFIFO || 0,
  S_IFSOCK: binding.S_IFSOCK || 0,

  S_IRUSR: binding.S_IRUSR || 0,
  S_IWUSR: binding.S_IWUSR || 0,
  S_IXUSR: binding.S_IXUSR || 0,
  S_IRGRP: binding.S_IRGRP || 0,
  S_IWGRP: binding.S_IWGRP || 0,
  S_IXGRP: binding.S_IXGRP || 0,
  S_IROTH: binding.S_IROTH || 0,
  S_IWOTH: binding.S_IWOTH || 0,
  S_IXOTH: binding.S_IXOTH || 0,

  UV_DIRENT_UNKNOWN: binding.UV_DIRENT_UNKNOWN,
  UV_DIRENT_FILE: binding.UV_DIRENT_FILE,
  UV_DIRENT_DIR: binding.UV_DIRENT_DIR,
  UV_DIRENT_LINK: binding.UV_DIRENT_LINK,
  UV_DIRENT_FIFO: binding.UV_DIRENT_FIFO,
  UV_DIRENT_SOCKET: binding.UV_DIRENT_SOCKET,
  UV_DIRENT_CHAR: binding.UV_DIRENT_CHAR,
  UV_DIRENT_BLOCK: binding.UV_DIRENT_BLOCK,

  COPYFILE_EXCL: binding.UV_FS_COPYFILE_EXCL,
  COPYFILE_FICLONE: binding.UV_FS_COPYFILE_FICLONE,
  COPYFILE_FICLONE_FORCE: binding.UV_FS_COPYFILE_FICLONE_FORCE,
  UV_FS_SYMLINK_DIR: binding.UV_FS_SYMLINK_DIR,
  UV_FS_SYMLINK_JUNCTION: binding.UV_FS_SYMLINK_JUNCTION
}
const binding = require('../binding')

module.exports = class FileError extends Error {
  constructor(msg, opts = {}) {
    const { code, operation = null, path = null, destination = null, fd = -1 } = opts

    if (operation !== null) msg += describe(operation, opts)

    super(`${code}: ${msg}`)

    this.code = code

    if (operation !== null) this.operation = operation
    if (path !== null) this.path = path
    if (destination !== null) this.destination = destination
    if (fd !== -1) this.fd = fd
  }

  get name() {
    return 'FileError'
  }

  // For Node.js compatibility
  get errno() {
    return binding.errnos[this.code]
  }

  // For Node.js compatibility
  get syscall() {
    return this.operation
  }

  // For Node.js compatibility
  get dest() {
    return this.destination
  }
}

function describe(operation, opts) {
  const { path = null, destination = null, fd = -1 } = opts

  let result = `, ${operation}`

  if (path !== null) {
    result += ` ${JSON.stringify(path)}`

    if (destination !== null) {
      result += ` -> ${JSON.stringify(destination)}`
    }
  } else if (fd !== -1) {
    result += ` ${fd}`
  }

  return result
}
{
  "name": "bare-fs",
  "version": "4.7.4",
  "description": "Native file system operations for Bare",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./promises": {
      "types": "./promises.d.ts",
      "default": "./promises.js"
    },
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "promises.js",
    "promises.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-fs.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-fs/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-fs#readme",
  "engines": {
    "bare": ">=1.16.0"
  },
  "dependencies": {
    "bare-events": "^2.5.4",
    "bare-path": "^3.0.0",
    "bare-stream": "^2.6.4",
    "bare-url": "^2.2.2",
    "fast-fifo": "^1.3.2"
  },
  "devDependencies": {
    "bare-buffer": "^3.0.2",
    "bare-crypto": "^1.11.2",
    "brittle": "^3.1.1",
    "cmake-bare": "^1.1.7",
    "lunte": "^1.6.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "bare-buffer": "*"
  },
  "peerDependenciesMeta": {
    "bare-buffer": {
      "optional": true
    }
  }
}
const EventEmitter = require('bare-events')
const fs = require('.')

class FileHandle extends EventEmitter {
  constructor(fd) {
    super()

    this.fd = fd
  }

  async close() {
    await fs.close(this.fd)

    this.fd = -1
    this.emit('close')
  }

  async read(buffer, ...args) {
    return {
      bytesRead: await fs.read(this.fd, buffer, ...args),
      buffer
    }
  }

  async readv(buffers, ...args) {
    return {
      bytesRead: await fs.readv(this.fd, buffers, ...args),
      buffers
    }
  }

  async write(buffer, ...args) {
    return {
      bytesWritten: await fs.write(this.fd, buffer, ...args),
      buffer
    }
  }

  async writev(buffers, ...args) {
    return {
      bytesWritten: await fs.writev(this.fd, buffers, ...args),
      buffers
    }
  }

  async stat() {
    return fs.fstat(this.fd)
  }

  async chmod(mode) {
    await fs.fchmod(this.fd, mode)
  }

  async chown(uid, gid) {
    await fs.fchown(this.fd, uid, gid)
  }

  async datasync() {
    return fs.fdatasync(this.fd)
  }

  async sync() {
    return fs.fsync(this.fd)
  }

  async truncate(len) {
    await fs.ftruncate(this.fd, len)
  }

  async utimes(atime, mtime) {
    await fs.futimes(this.fd, atime, mtime)
  }

  createReadStream(opts) {
    return fs.createReadStream(null, { ...opts, fd: this.fd })
  }

  createWriteStream(opts) {
    return fs.createWriteStream(null, { ...opts, fd: this.fd })
  }

  async [Symbol.asyncDispose]() {
    await this.close()
  }
}

exports.open = async function open(filepath, flags, mode) {
  return new FileHandle(await fs.open(filepath, flags, mode))
}

exports.access = fs.access
exports.appendFile = fs.appendFile
exports.chmod = fs.chmod
exports.chown = fs.chown
exports.constants = fs.constants
exports.copyFile = fs.copyFile
exports.cp = fs.cp
exports.lchown = fs.lchown
exports.lutimes = fs.lutimes
exports.link = fs.link
exports.lstat = fs.lstat
exports.mkdir = fs.mkdir
exports.mkdtemp = fs.mkdtemp
exports.opendir = fs.opendir
exports.readFile = fs.readFile
exports.readdir = fs.readdir
exports.readlink = fs.readlink
exports.realpath = fs.realpath
exports.rename = fs.rename
exports.rm = fs.rm
exports.rmdir = fs.rmdir
exports.stat = fs.stat
exports.statfs = fs.statfs
exports.truncate = fs.truncate
exports.symlink = fs.symlink
exports.unlink = fs.unlink
exports.utimes = fs.utimes
exports.watch = fs.watch
exports.writeFile = fs.writeFile
module.exports = require.addon()
const binding = require('./binding')

module.exports = exports = function hrtime(past) {
  let now = binding.hrtime()

  if (past) now -= BigInt(past[0]) * 1000000000n + BigInt(past[1])

  return [Number(now / 1000000000n), Number(now % 1000000000n)]
}

exports.bigint = function hrtime() {
  return binding.hrtime()
}
{
  "name": "bare-hrtime",
  "version": "2.1.1",
  "description": "High-resolution timers for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-hrtime.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-hrtime/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-hrtime#readme",
  "devDependencies": {
    "brittle": "^3.2.1",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  }
}
module.exports = require.addon()
const ansiEscapes = require('bare-ansi-escapes')
const getType = require('bare-type')
const binding = require('./binding')

const PLAIN_KEY = /^[a-zA-Z_][a-zA-Z_0-9]*$/

const defaultDepth = 2
const defaultBreakLength = 80
const defaultMaxArrayLength = 40

module.exports = exports = function inspect(value, opts = {}) {
  const {
    colors = false,
    depth = defaultDepth,
    breakLength = defaultBreakLength,
    stylize = defaultStylize(colors)
  } = opts

  const references = new InspectRefMap()

  const tree = inspectValue(value, 0, {
    colors,
    depth,
    breakLength,
    stylize,
    references
  })

  return tree.toString()
}

exports.styles = {
  bigint: ansiEscapes.colorYellow,
  boolean: ansiEscapes.colorYellow,
  date: ansiEscapes.colorMagenta,
  module: ansiEscapes.modifierUnderline,
  name: ansiEscapes.modifierReset,
  null: ansiEscapes.modifierBold,
  number: ansiEscapes.colorYellow,
  regexp: ansiEscapes.colorRed,
  special: ansiEscapes.colorCyan,
  string: ansiEscapes.colorGreen,
  symbol: ansiEscapes.colorGreen,
  undefined: ansiEscapes.colorBrightBlack
}

const styles = exports.styles

function defaultStylize(colors) {
  return function stylize(value, style) {
    const color = colors && styles[style]

    if (color) return color + value + ansiEscapes.modifierReset

    return value
  }
}

class InspectRefMap {
  constructor() {
    this.refs = new WeakMap()
    this.ids = new WeakMap()
    this.nextId = 1
  }

  has(object) {
    return this.refs.has(object)
  }

  get(object) {
    return this.refs.get(object) || null
  }

  set(object, ref) {
    this.refs.set(object, ref)
  }

  id(object) {
    let id = this.ids.get(object)
    if (id) return id

    id = this.nextId++
    this.ids.set(object, id)

    return id
  }
}

class InspectNode {
  constructor(depth, length, opts) {
    const { breakLength = defaultBreakLength, breakAlways = false } = opts

    this.depth = depth
    this.length = length
    this.breakLength = breakLength
    this.breakAlways = breakAlways
  }

  pad(n, string) {
    return string.padStart(n, ' ')
  }

  indent(n, string) {
    return '  '.repeat(n) + string
  }
}

class InspectRef extends InspectNode {
  constructor(depth, opts) {
    super(depth, '[circular *]'.length, opts)

    this.refs = opts.references
    this.count = 0
    this.circular = false
    this.color = opts.colors && styles.special
  }

  get id() {
    return this.refs.id(this)
  }

  increment() {
    return ++this.count
  }

  decrement() {
    return --this.count
  }

  toString(opts = {}) {
    const { offset = 0, pad = 0, indent = 0 } = opts

    let value = this.pad(pad, '[circular *' + this.id + ']')

    if (this.color) value = this.color + value + ansiEscapes.modifierReset

    return offset ? value : this.indent(indent, value)
  }
}

class InspectLeaf extends InspectNode {
  constructor(value, color, depth, opts) {
    const length = value.length

    if (value.includes('\n')) {
      value = value.replaceAll('\n', '\n' + '  '.repeat(depth))

      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.value = value
    this.color = opts.colors && color
  }

  toString(opts = {}) {
    const { offset = 0, pad = 0, indent = 0 } = opts

    let value = this.pad(pad, this.value)

    if (this.color) value = this.color + value + ansiEscapes.modifierReset

    return offset ? value : this.indent(indent, value)
  }
}

class InspectPair extends InspectNode {
  constructor(delim, left, right, depth, opts) {
    const length = left.length + delim.length + right.length

    if (left.breakAlways || right.breakAlways) {
      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.delim = delim
    this.left = left
    this.right = right
  }

  toString(opts = {}) {
    const { indent = 0 } = opts

    return this.indent(
      indent,
      this.left +
        this.delim +
        this.right.toString({
          indent,
          offset: this.left.length + this.delim.length
        })
    )
  }
}

class InspectSuspension extends InspectNode {
  constructor(overflow, depth, opts) {
    const label = `... ${overflow} more`

    super(depth, label.length, opts)

    this.label = label
  }

  toString(opts = {}) {
    const { indent = 0 } = opts

    return this.indent(indent, this.label)
  }
}

class InspectSequence extends InspectNode {
  constructor(header, footer, delim, values, ref, depth, opts) {
    const { tabulate = false } = opts

    const length =
      (ref.circular ? '<ref *>'.length + 1 : 0) +
      header.length +
      values.reduce(
        (length, value, i) =>
          length + value.length + (i === 0 ? 0 : delim.length),
        0
      ) +
      footer.length

    if (values.some((value) => value.breakAlways)) {
      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.header = header
    this.footer = footer
    this.delim = delim
    this.values = values
    this.ref = ref
    this.tabulate = tabulate
  }

  toString(opts = {}) {
    const { offset = 0, indent = 0 } = opts

    const split =
      this.breakAlways ||
      (this.values.length &&
        (offset + this.length > this.breakLength ||
          indent * 2 + this.length > this.breakLength))

    let header = this.header

    if (this.ref.circular) {
      header = '<ref *' + this.ref.id + '> ' + header
    }

    if (this.values.length === 0) {
      header = header.trimEnd()
    }

    if (offset === 0) {
      header = this.indent(indent, header)
    }

    if (split) {
      header = header.trimEnd() + '\n'
    }

    let string = header

    let columns = 1
    let pad = 0

    if (this.tabulate) {
      const widest = this.values.reduce(
        (length, value) =>
          value.breakAlways ? length : Math.max(length, value.length),
        0
      )

      if (widest) {
        columns = Math.max(
          columns,
          Math.floor(
            (this.breakLength - indent * 2) / (widest + this.delim.length)
          )
        )

        if (columns > 1) pad = widest
      }
    }

    for (let i = 0, n = this.values.length, offset = 0; i < n; i++) {
      const value = this.values[i]

      if (split) {
        let part

        if (i % columns === 0 || value.breakAlways) {
          part = value.toString({ indent: indent + 1, pad })
        } else {
          part = value.toString({ pad })
        }

        string += part

        if (i < n - 1) {
          if (i % columns === columns - 1 || this.values[i + 1].breakAlways) {
            string += this.delim.trimEnd() + '\n'
          } else {
            string += this.delim
          }
        }
      } else {
        if (i > 0) string += this.delim

        string += value.toString({ offset })

        offset += value.length
      }
    }

    let footer = this.footer

    if (this.values.length === 0) {
      footer = footer.trimStart()
    }

    if (split) {
      string += '\n' + this.indent(indent, footer.trimStart())
    } else {
      string += footer
    }

    return string
  }
}

function inspectValue(value, depth, opts) {
  const type = getType(value)

  if (type.isUndefined()) return inspectUndefined(depth, opts)
  if (type.isNull()) return inspectNull(depth, opts)
  if (type.isBoolean()) return inspectBoolean(value, depth, opts)
  if (type.isNumber()) return inspectNumber(value, depth, opts)
  if (type.isBigInt()) return inspectBigInt(value, depth, opts)
  if (type.isString()) return inspectString(value, depth, opts)
  if (type.isSymbol()) return inspectSymbol(value, depth, opts)
  if (type.isObject()) return inspectObject(type, value, depth, opts)
  if (type.isFunction()) return inspectFunction(type, value, depth, opts)
  if (type.isExternal()) return inspectExternal(value, opts, opts)
}

function inspectUndefined(depth, opts) {
  return new InspectLeaf('undefined', styles.undefined, depth, opts)
}

function inspectNull(depth, opts) {
  return new InspectLeaf('null', styles.null, depth, opts)
}

function inspectBoolean(value, depth, opts) {
  return new InspectLeaf(value.toString(), styles.boolean, depth, opts)
}

function inspectNumber(value, depth, opts) {
  let string

  if (Object.is(value, -0)) {
    string = '-0'
  } else {
    string = value.toString(10)
  }

  return new InspectLeaf(string, styles.number, depth, opts)
}

function inspectBigInt(value, depth, opts) {
  return new InspectLeaf(value.toString(10) + 'n', styles.bigint, depth, opts)
}

const STRING_ESCAPES =
  /[\ud800-\udbff][\udc00-\udfff]|[\u0000-\u001f'\\\ud800-\udfff]/g

function inspectString(value, depth, opts) {
  // https://tc39.es/ecma262/multipage/structured-data.html#sec-quotejsonstring
  const string = value.replace(STRING_ESCAPES, (match) => {
    if (match.length === 2) return match

    switch (match) {
      case "'":
        return "\\'"
      case '\\':
        return '\\\\'
      case '\b':
        return '\\b'
      case '\t':
        return '\\t'
      case '\n':
        return '\\n'
      case '\f':
        return '\\f'
      case '\r':
        return '\\r'
      default:
        return '\\u' + match.charCodeAt(0).toString(16).padStart(4, '0')
    }
  })

  return new InspectLeaf("'" + string + "'", styles.string, depth, opts)
}

function inspectSymbol(value, depth, opts) {
  return new InspectLeaf(value.toString(), styles.symbol, depth, opts)
}

function inspectKey(value, depth, opts) {
  if (PLAIN_KEY.test(value)) {
    return new InspectLeaf(value, null, depth, opts)
  } else {
    return inspectValue(value, depth, opts)
  }
}

function inspectObject(type, object, depth, opts) {
  const refs = opts.references

  let ref = refs.get(object)
  if (ref === null) {
    ref = new InspectRef(depth, opts)
    refs.set(object, ref)
  } else if (ref.count) {
    ref.circular = true
    return ref
  }

  const maxDepth = typeof opts.depth === 'number' ? opts.depth : Infinity

  if (maxDepth < depth) {
    const constructor = object.constructor

    return new InspectLeaf(
      '[' +
        (constructor && constructor.name ? constructor.name : 'Object') +
        ']',
      styles.special,
      depth,
      opts
    )
  }

  const inspect =
    object[Symbol.for('bare.inspect')] ||
    object[Symbol.for('nodejs.util.inspect.custom')]

  if (typeof inspect === 'function') {
    const value = inspect.call(
      object,
      typeof opts.depth === 'number' ? opts.depth - depth : null,
      {
        colors: opts.colors,
        breakLength: opts.breakLength,
        stylize: opts.stylize
      },
      exports
    )

    if (typeof value === 'object' && value !== null) {
      refs.set(value, ref)
    }

    if (typeof value !== 'string') {
      return inspectValue(value, depth, opts)
    }

    return new InspectLeaf(value, null, depth, opts)
  }

  if (type.isArray()) return inspectArray(object, ref, depth, opts)
  if (type.isDate()) return inspectDate(object, ref, depth, opts)
  if (type.isRegExp()) return inspectRegExp(object, ref, depth, opts)
  if (type.isError()) return inspectError(object, ref, depth, opts)
  if (type.isPromise()) return inspectPromise(object, ref, depth, opts)
  if (type.isMap()) return inspectMap(object, ref, depth, opts)
  if (type.isSet()) return inspectSet(object, ref, depth, opts)
  if (type.isWeakMap()) return inspectWeakMap(object, ref, depth, opts)
  if (type.isWeakSet()) return inspectWeakSet(object, ref, depth, opts)
  if (type.isWeakRef()) return inspectWeakRef(object, ref, depth, opts)
  if (type.isArrayBuffer()) return inspectArrayBuffer(object, ref, depth, opts)
  if (type.isSharedArrayBuffer())
    return inspectSharedArrayBuffer(object, ref, depth, opts)
  if (type.isTypedArray()) return inspectTypedArray(object, ref, depth, opts)
  if (type.isDataView()) return inspectDataView(object, ref, depth, opts)

  ref.increment()

  const values = []

  for (const key in object) {
    if (key === 'constructor') continue

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(object[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  let header = '{ '

  const tag = object[Symbol.toStringTag]

  if (tag) header = '[' + tag + '] ' + header

  if (object.constructor) {
    const name = object.constructor.name

    if (name && name !== 'Object') {
      header = object.constructor.name + ' ' + header
    }
  }

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectArray(array, ref, depth, opts) {
  const { maxArrayLength = defaultMaxArrayLength } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxArrayLength, 0)

  for (let i = 0, n = array.length; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(array.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(inspectValue(array[i], depth + 1, opts))
  }

  for (const key of binding.getOwnNonIndexPropertyNames(array)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(array[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  let header = '[ '

  if (array.constructor.name !== 'Array') {
    header = array.constructor.name + '(' + array.length + ') ' + header
  }

  return new InspectSequence(header, ' ]', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectDate(date, ref, depth, opts) {
  return new InspectLeaf(date.toISOString(), styles.date, depth, opts)
}

function inspectRegExp(regExp, ref, depth, opts) {
  return new InspectLeaf(regExp.toString(), styles.regexp, depth, opts)
}

function inspectError(error, ref, depth, opts) {
  let header

  if ('stack' in error) {
    header = error.stack

    if (depth > 0) {
      header = header.replaceAll('\n', '\n' + '  '.repeat(depth))
    }
  } else {
    header = error.toString()
  }

  const builtins = ['cause']

  if (error.name === 'AggregateError') {
    builtins.push('errors')
  } else if (error.name === 'SuppressedError') {
    builtins.push('error', 'suppressed')
  }

  const values = []

  for (const key of builtins) {
    if (key in error === false) continue

    values.push(
      new InspectPair(
        ': ',
        new InspectLeaf('[' + key + ']', null, depth + 1, opts),
        inspectValue(error[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key in error) {
    if (key === 'constructor' || builtins.includes(key)) continue

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(error[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  if (values.length === 0) return new InspectLeaf(header, null, depth, opts)

  return new InspectSequence(
    header + ' {',
    ' }',
    ', ',
    values,
    ref,
    depth,
    opts
  )
}

function inspectPromise(promise, ref, depth, opts) {
  ref.increment()

  const state = binding.getPromiseState(promise)

  const values = []

  switch (state) {
    case 0: // Pending
      values.push(new InspectLeaf('<pending>', styles.special, depth, opts))
      break

    case 1: // Fulfilled
      values.push(inspectValue(binding.getPromiseResult(promise), depth, opts))
      break

    case 2: // Rejected
      values.push(
        new InspectLeaf('<rejected>', styles.special, depth, opts),
        inspectValue(binding.getPromiseResult(promise), depth, opts)
      )
  }

  ref.decrement()

  const header = promise.constructor.name + ' { '

  return new InspectSequence(header, ' }', ' ', values, ref, depth, opts)
}

function inspectMap(map, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxMapLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = maxMapLength

  for (const entry of map) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(map.size - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )
      break
    }

    values.push(
      new InspectPair(
        ' => ',
        inspectValue(entry[0], depth + 1, opts),
        inspectValue(entry[1], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key in map) {
    if (key === 'constructor') continue

    const value = inspectValue(map[key], depth + 1, opts)

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        value,
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = map.constructor.name + '(' + map.size + ') { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectSet(set, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxSetLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = maxSetLength

  for (const entry of set) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(set.size - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )
      break
    }

    values.push(inspectValue(entry, depth + 1, opts))
  }

  for (const key in set) {
    if (key === 'constructor') continue

    const value = inspectValue(set[key], depth + 1, opts)

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        value,
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = set.constructor.name + '(' + set.size + ') { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectWeakMap(weakMap, ref, depth, opts) {
  const header = weakMap.constructor.name + ' { '

  return new InspectSequence(
    header,
    ' }',
    ' ',
    [new InspectLeaf('<items unknown>', styles.special, depth + 1, opts)],
    ref,
    depth,
    opts
  )
}

function inspectWeakSet(weakSet, ref, depth, opts) {
  const header = weakSet.constructor.name + ' { '

  return new InspectSequence(
    header,
    ' }',
    ' ',
    [new InspectLeaf('<items unknown>', styles.special, depth + 1, opts)],
    ref,
    depth,
    opts
  )
}

function inspectWeakRef(weakRef, ref, depth, opts) {
  const target = weakRef.deref()

  let value

  if (target === undefined) {
    value = new InspectLeaf('<cleared>', styles.special, depth + 1, opts)
  } else {
    value = inspectValue(target, depth + 1, opts)
  }

  const header = weakRef.constructor.name + ' { '

  return new InspectSequence(header, ' }', ' ', [value], ref, depth, opts)
}

function inspectArrayBuffer(arrayBuffer, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(arrayBuffer[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = arrayBuffer.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectSharedArrayBuffer(sharedArrayBuffer, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(sharedArrayBuffer[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = sharedArrayBuffer.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectTypedArray(typedArray, ref, depth, opts) {
  if (Buffer.isBuffer(typedArray)) {
    return inspectBuffer(typedArray, ref, depth, opts)
  }

  const {
    maxArrayLength = defaultMaxArrayLength,
    maxTypedArrayLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxTypedArrayLength, 0)

  for (let i = 0, n = typedArray.length; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(typedArray.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(inspectValue(typedArray[i], depth + 1, opts))
  }

  for (const key of binding.getOwnNonIndexPropertyNames(typedArray)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(typedArray[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = typedArray.constructor.name + '(' + typedArray.length + ') [ '

  return new InspectSequence(header, ' ]', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectBuffer(buffer, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxBufferLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxBufferLength, 0)

  for (let i = 0, n = buffer.byteLength; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(buffer.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(
      new InspectLeaf(
        buffer[i].toString(16).padStart(2, '0'),
        null,
        depth + 1,
        opts
      )
    )
  }

  for (const key of binding.getOwnNonIndexPropertyNames(buffer)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(buffer[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  return new InspectSequence('<Buffer ', '>', ' ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectDataView(dataView, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength', 'byteOffset', 'buffer']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(dataView[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key of binding.getOwnNonIndexPropertyNames(dataView)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(dataView[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = dataView.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectFunction(type, fn, depth, opts) {
  if (fn.toString().startsWith('class')) return inspectClass(fn, depth, opts)

  let tag = 'function'

  if (type.isGeneratorFunction()) tag = 'generator ' + tag
  if (type.isAsyncFunction()) tag = 'async ' + tag

  return new InspectLeaf(
    '[' + tag + ' ' + (fn.name ? fn.name : '(anonymous)') + ']',
    styles.special,
    depth,
    opts
  )
}

function inspectClass(ctor, depth, opts) {
  return new InspectLeaf(
    '[class ' + (ctor.name ? ctor.name : '(anonymous)') + ']',
    styles.special,
    depth,
    opts
  )
}

function inspectExternal(external, depth, opts) {
  return new InspectLeaf(
    '[external 0x' + binding.getExternal(external).toString(16) + ']',
    styles.special,
    depth,
    opts
  )
}
{
  "name": "bare-inspect",
  "version": "3.1.4",
  "description": "Inspect objects as strings for debugging",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-inspect.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-inspect/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-inspect#readme",
  "engines": {
    "bare": ">=1.18.0"
  },
  "dependencies": {
    "bare-ansi-escapes": "^2.1.0",
    "bare-type": "^1.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
module.exports = require.addon()
const binding = require('./binding')
const errors = require('./lib/errors')
const constants = require('./lib/constants')

exports.constants = constants
exports.errors = errors

exports.EOL = binding.platform === 'win32' ? '\r\n' : '\n'

exports.devNull = binding.platform === 'win32' ? '\\\\.\\nul' : '/dev/null'

exports.platform = function platform() {
  return binding.platform
}

exports.arch = function arch() {
  return binding.arch
}

exports.type = function type() {
  return binding.type()
}

exports.version = function version() {
  return binding.version()
}

exports.release = function release() {
  return binding.release()
}

exports.machine = function machine() {
  return binding.machine()
}

exports.execPath = function execPath() {
  return binding.execPath()
}

exports.pid = function pid() {
  return binding.pid()
}

exports.ppid = function ppid() {
  return binding.ppid()
}

exports.cwd = function cwd() {
  return binding.cwd()
}

exports.chdir = function chdir(dir) {
  validateString(dir, 'Directory')

  binding.chdir(dir)
}

exports.tmpdir = function tmpdir() {
  return binding.tmpdir()
}

exports.homedir = function homedir() {
  return binding.homedir()
}

exports.hostname = function hostname() {
  return binding.hostname()
}

exports.userInfo = function userInfo(uid) {
  if (uid !== undefined) validateInteger(uid, 'User ID')

  return binding.userInfo(uid)
}

exports.groupInfo = function groupInfo(gid) {
  if (gid !== undefined) validateInteger(gid, 'Group ID')

  return binding.groupInfo(gid)
}

exports.networkInterfaces = function networkInterfaces() {
  const result = {}

  for (const entry of binding.networkInterfaces()) {
    const { name, ...properties } = entry

    if (result[name]) result[name].push(properties)
    else result[name] = [properties]
  }

  return result
}

exports.kill = function kill(pid, signal = constants.signals.SIGTERM) {
  validateInteger(pid, 'Process ID')

  if (typeof signal === 'string') {
    if (signal in constants.signals === false) {
      throw errors.UNKNOWN_SIGNAL('Unknown signal: ' + signal)
    }

    signal = constants.signals[signal]
  } else {
    validateInteger(signal, 'Signal')
  }

  binding.kill(pid, signal)
}

exports.endianness = function endianness() {
  return binding.isLittleEndian ? 'LE' : 'BE'
}

exports.availableParallelism = function availableParallelism() {
  return binding.availableParallelism()
}

exports.cpuUsage = function cpuUsage(previous) {
  const current = binding.cpuUsage()

  if (previous) {
    return {
      user: current.user - previous.user,
      system: current.system - previous.system
    }
  }

  return current
}

exports.threadCpuUsage = function threadCpuUsage(previous) {
  const current = binding.threadCpuUsage()

  if (previous) {
    return {
      user: current.user - previous.user,
      system: current.system - previous.system
    }
  }

  return current
}

exports.resourceUsage = function resourceUsage() {
  return binding.resourceUsage()
}

exports.memoryUsage = function memoryUsage() {
  return binding.memoryUsage()
}

exports.freemem = function freemem() {
  return binding.freemem()
}

exports.totalmem = function totalmem() {
  return binding.totalmem()
}

exports.availableMemory = function availableMemory() {
  return binding.availableMemory()
}

exports.constrainedMemory = function constrainedMemory() {
  return binding.constrainedMemory()
}

exports.uptime = function uptime() {
  return binding.uptime()
}

exports.loadavg = function loadavg() {
  return binding.loadavg()
}

exports.cpus = function cpus() {
  return binding.cpus()
}

exports.getProcessTitle = function getProcessTitle() {
  return binding.getProcessTitle()
}

exports.setProcessTitle = function setProcessTitle(title) {
  if (typeof title !== 'string') title = title.toString()

  if (title.length >= 256) {
    throw errors.TITLE_OVERFLOW('Process title is too long')
  }

  binding.setProcessTitle(title)
}

exports.getPriority = function getPriority(pid = 0) {
  validateInteger(pid, 'Process ID')

  return binding.getPriority(pid)
}

exports.setPriority = function setPriority(pid, priority) {
  if (priority === undefined) {
    priority = pid
    pid = 0
  }

  validateInteger(pid, 'Process ID')
  validateInteger(priority, 'Priority')

  binding.setPriority(pid, priority)
}

exports.getEnvKeys = function getEnvKeys() {
  return binding.getEnvKeys()
}

exports.getEnv = function getEnv(name) {
  validateString(name, 'Name')

  return binding.getEnv(name)
}

exports.hasEnv = function hasEnv(name) {
  validateString(name, 'Name')

  return binding.hasEnv(name)
}

exports.setEnv = function setEnv(name, value) {
  validateString(name, 'Name')
  validateString(value, 'Value')

  binding.setEnv(name, value)
}

exports.unsetEnv = function unsetEnv(name) {
  validateString(name, 'Name')

  binding.unsetEnv(name)
}

function validateString(value, name) {
  if (typeof value !== 'string') {
    throw new TypeError(`${name} must be a string. Received type ${typeof value} (${value})`)
  }
}

function validateInteger(value, name) {
  if (!Number.isInteger(value)) {
    throw new TypeError(`${name} must be an integer. Received type ${typeof value} (${value})`)
  }
}
const binding = require('../binding')

module.exports = {
  signals: binding.signals,
  errnos: binding.errnos,
  priority: binding.priority
}
module.exports = class OSError extends Error {
  constructor(msg, fn = OSError, code = fn.name) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'OSError'
  }

  static UNKNOWN_SIGNAL(msg) {
    return new OSError(msg, OSError.UNKNOWN_SIGNAL)
  }

  static TITLE_OVERFLOW(msg) {
    return new OSError(msg, OSError.TITLE_OVERFLOW)
  }
}
{
  "name": "bare-os",
  "version": "3.9.3",
  "description": "Operating system utilities for Bare",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    },
    "./errors": {
      "types": "./lib/errors.d.ts",
      "default": "./lib/errors.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-os.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-os/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-os#readme",
  "engines": {
    "bare": ">=1.14.0"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "cmake-bare": "^1.1.6",
    "lunte": "^1.6.0",
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = require.addon()
// This export SHOULD NOT be shortened in any way as having the full
// `module.exports = require(...)` statement is crucial for synthesizing
// ESM exports.

if (Bare.platform === 'win32') {
  module.exports = require('./lib/win32')
} else {
  module.exports = require('./lib/posix')
}
module.exports = {
  CHAR_UPPERCASE_A: 0x41,
  CHAR_LOWERCASE_A: 0x61,
  CHAR_UPPERCASE_Z: 0x5a,
  CHAR_LOWERCASE_Z: 0x7a,
  CHAR_DOT: 0x2e,
  CHAR_FORWARD_SLASH: 0x2f,
  CHAR_BACKWARD_SLASH: 0x5c,
  CHAR_COLON: 0x3a,
  CHAR_QUESTION_MARK: 0x3f
}
const binding = require('../binding')

const { normalizeString, validateString } = require('./shared')
const { CHAR_DOT, CHAR_FORWARD_SLASH } = require('./constants')

function isPosixPathSeparator(code) {
  return code === CHAR_FORWARD_SLASH
}

exports.win32 = require('./win32')
exports.posix = exports

exports.sep = '/'
exports.delimiter = ':'

exports.resolve = function resolve(...args) {
  let resolvedPath = ''
  let resolvedAbsolute = false

  for (let i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) {
    const path = i >= 0 ? args[i] : binding.cwd()

    if (i >= 0) validateString(path, `paths[${i}]`)

    if (path.length === 0) {
      continue
    }

    resolvedPath = `${path}/${resolvedPath}`
    resolvedAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH
  }

  resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute, '/', isPosixPathSeparator)

  if (resolvedAbsolute) {
    return `/${resolvedPath}`
  }

  return resolvedPath.length > 0 ? resolvedPath : '.'
}

exports.normalize = function normalize(path) {
  validateString(path, 'path')

  if (path.length === 0) return '.'

  const isAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH
  const trailingSeparator = path.charCodeAt(path.length - 1) === CHAR_FORWARD_SLASH

  path = normalizeString(path, !isAbsolute, '/', isPosixPathSeparator)

  if (path.length === 0) {
    if (isAbsolute) return '/'
    return trailingSeparator ? './' : '.'
  }

  if (trailingSeparator) path += '/'

  return isAbsolute ? `/${path}` : path
}

exports.isAbsolute = function isAbsolute(path) {
  validateString(path, 'path')

  return path.length > 0 && path.charCodeAt(0) === CHAR_FORWARD_SLASH
}

exports.join = function join(...args) {
  if (args.length === 0) return '.'
  let joined
  for (let i = 0; i < args.length; ++i) {
    const arg = args[i]
    validateString(arg, 'path')
    if (arg.length > 0) {
      if (joined === undefined) joined = arg
      else joined += `/${arg}`
    }
  }
  if (joined === undefined) return '.'
  return exports.normalize(joined)
}

exports.relative = function relative(from, to) {
  validateString(from, 'from')
  validateString(to, 'to')

  if (from === to) return ''

  from = exports.resolve(from)
  to = exports.resolve(to)

  if (from === to) return ''

  const fromStart = 1
  const fromEnd = from.length
  const fromLen = fromEnd - fromStart
  const toStart = 1
  const toLen = to.length - toStart

  const length = fromLen < toLen ? fromLen : toLen
  let lastCommonSep = -1
  let i = 0
  for (; i < length; i++) {
    const fromCode = from.charCodeAt(fromStart + i)
    if (fromCode !== to.charCodeAt(toStart + i)) {
      break
    } else if (fromCode === CHAR_FORWARD_SLASH) {
      lastCommonSep = i
    }
  }
  if (i === length) {
    if (toLen > length) {
      if (to.charCodeAt(toStart + i) === CHAR_FORWARD_SLASH) {
        return to.substring(toStart + i + 1)
      }
      if (i === 0) {
        return to.substring(toStart + i)
      }
    } else if (fromLen > length) {
      if (from.charCodeAt(fromStart + i) === CHAR_FORWARD_SLASH) {
        lastCommonSep = i
      } else if (i === 0) {
        lastCommonSep = 0
      }
    }
  }

  let out = ''
  for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
    if (i === fromEnd || from.charCodeAt(i) === CHAR_FORWARD_SLASH) {
      out += out.length === 0 ? '..' : '/..'
    }
  }

  return `${out}${to.substring(toStart + lastCommonSep)}`
}

exports.toNamespacedPath = function toNamespacedPath(path) {
  return path
}

exports.dirname = function dirname(path) {
  validateString(path, 'path')

  if (path.length === 0) return '.'
  const hasRoot = path.charCodeAt(0) === CHAR_FORWARD_SLASH
  let end = -1
  let matchedSlash = true
  for (let i = path.length - 1; i >= 1; --i) {
    if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) {
      if (!matchedSlash) {
        end = i
        break
      }
    } else {
      matchedSlash = false
    }
  }

  if (end === -1) return hasRoot ? '/' : '.'
  if (hasRoot && end === 1) return '//'
  return path.substring(0, end)
}

exports.basename = function basename(path, suffix) {
  if (suffix !== undefined) validateString(suffix, 'suffix')
  validateString(path, 'path')

  let start = 0
  let end = -1
  let matchedSlash = true

  if (suffix !== undefined && suffix.length > 0 && suffix.length <= path.length) {
    if (suffix === path) {
      return ''
    }
    let extIdx = suffix.length - 1
    let firstNonSlashEnd = -1
    for (let i = path.length - 1; i >= 0; --i) {
      const code = path.charCodeAt(i)
      if (code === CHAR_FORWARD_SLASH) {
        if (!matchedSlash) {
          start = i + 1
          break
        }
      } else {
        if (firstNonSlashEnd === -1) {
          matchedSlash = false
          firstNonSlashEnd = i + 1
        }
        if (extIdx >= 0) {
          if (code === suffix.charCodeAt(extIdx)) {
            if (--extIdx === -1) {
              end = i
            }
          } else {
            extIdx = -1
            end = firstNonSlashEnd
          }
        }
      }
    }

    if (start === end) end = firstNonSlashEnd
    else if (end === -1) end = path.length
    return path.substring(start, end)
  }

  for (let i = path.length - 1; i >= 0; --i) {
    if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) {
      if (!matchedSlash) {
        start = i + 1
        break
      }
    } else if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
  }

  if (end === -1) return ''
  return path.substring(start, end)
}

exports.extname = function extname(path) {
  validateString(path, 'path')

  let startDot = -1
  let startPart = 0
  let end = -1
  let matchedSlash = true
  let preDotState = 0
  for (let i = path.length - 1; i >= 0; --i) {
    const code = path.charCodeAt(i)
    if (code === CHAR_FORWARD_SLASH) {
      if (!matchedSlash) {
        startPart = i + 1
        break
      }
      continue
    }
    if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
    if (code === CHAR_DOT) {
      if (startDot === -1) startDot = i
      else if (preDotState !== 1) preDotState = 1
    } else if (startDot !== -1) {
      preDotState = -1
    }
  }

  if (
    startDot === -1 ||
    end === -1 ||
    preDotState === 0 ||
    (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1)
  ) {
    return ''
  }
  return path.substring(startDot, end)
}
const { CHAR_DOT, CHAR_FORWARD_SLASH } = require('./constants')

exports.validateString = function validateString(value, name) {
  if (typeof value !== 'string') {
    throw new TypeError(
      `The "${name}" argument must be of type string. Received type ${typeof value}`
    )
  }
}

exports.normalizeString = function normalizeString(
  path,
  allowAboveRoot,
  separator,
  isPathSeparator
) {
  let res = ''
  let lastSegmentLength = 0
  let lastSlash = -1
  let dots = 0
  let code = 0
  for (let i = 0; i <= path.length; ++i) {
    if (i < path.length) {
      code = path.charCodeAt(i)
    } else if (isPathSeparator(code)) {
      break
    } else {
      code = CHAR_FORWARD_SLASH
    }

    if (isPathSeparator(code)) {
      if (lastSlash === i - 1 || dots === 1);
      else if (dots === 2) {
        if (
          res.length < 2 ||
          lastSegmentLength !== 2 ||
          res.charCodeAt(res.length - 1) !== CHAR_DOT ||
          res.charCodeAt(res.length - 2) !== CHAR_DOT
        ) {
          if (res.length > 2) {
            const lastSlashIndex = res.lastIndexOf(separator)
            if (lastSlashIndex === -1) {
              res = ''
              lastSegmentLength = 0
            } else {
              res = res.substring(0, lastSlashIndex)
              lastSegmentLength = res.length - 1 - res.lastIndexOf(separator)
            }
            lastSlash = i
            dots = 0
            continue
          } else if (res.length !== 0) {
            res = ''
            lastSegmentLength = 0
            lastSlash = i
            dots = 0
            continue
          }
        }
        if (allowAboveRoot) {
          res += res.length > 0 ? `${separator}..` : '..'
          lastSegmentLength = 2
        }
      } else {
        if (res.length > 0) {
          res += `${separator}${path.substring(lastSlash + 1, i)}`
        } else {
          res = path.substring(lastSlash + 1, i)
        }
        lastSegmentLength = i - lastSlash - 1
      }
      lastSlash = i
      dots = 0
    } else if (code === CHAR_DOT && dots !== -1) {
      ++dots
    } else {
      dots = -1
    }
  }
  return res
}
const binding = require('../binding')

const { normalizeString, validateString } = require('./shared')
const {
  CHAR_UPPERCASE_A,
  CHAR_LOWERCASE_A,
  CHAR_UPPERCASE_Z,
  CHAR_LOWERCASE_Z,
  CHAR_DOT,
  CHAR_FORWARD_SLASH,
  CHAR_BACKWARD_SLASH,
  CHAR_COLON,
  CHAR_QUESTION_MARK
} = require('./constants')

function isWindowsPathSeparator(code) {
  return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH
}

function isWindowsDeviceRoot(code) {
  return (
    (code >= CHAR_UPPERCASE_A && code <= CHAR_UPPERCASE_Z) ||
    (code >= CHAR_LOWERCASE_A && code <= CHAR_LOWERCASE_Z)
  )
}

exports.posix = require('./posix')
exports.win32 = exports

exports.sep = '\\'
exports.delimiter = ';'

exports.resolve = function resolve(...args) {
  let resolvedDevice = ''
  let resolvedTail = ''
  let resolvedAbsolute = false

  for (let i = args.length - 1; i >= -1; i--) {
    let path
    if (i >= 0) {
      path = args[i]

      validateString(path, `paths[${i}]`)

      if (path.length === 0) continue
    } else if (resolvedDevice.length === 0) {
      path = binding.cwd()
    } else {
      path = binding.cwd(resolvedDevice)

      if (
        path === undefined ||
        (path.substring(0, 2).toLowerCase() !== resolvedDevice.toLowerCase() &&
          path.charCodeAt(2) === CHAR_BACKWARD_SLASH)
      ) {
        path = `${resolvedDevice}\\`
      }
    }

    const len = path.length
    let rootEnd = 0
    let device = ''
    let isAbsolute = false
    const code = path.charCodeAt(0)

    if (len === 1) {
      if (isWindowsPathSeparator(code)) {
        rootEnd = 1
        isAbsolute = true
      }
    } else if (isWindowsPathSeparator(code)) {
      isAbsolute = true

      if (isWindowsPathSeparator(path.charCodeAt(1))) {
        let j = 2
        let last = j
        while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
          j++
        }
        if (j < len && j !== last) {
          const firstPart = path.substring(last, j)
          last = j
          while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
            j++
          }
          if (j < len && j !== last) {
            last = j
            while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
              j++
            }
            if (j === len || j !== last) {
              device = `\\\\${firstPart}\\${path.substring(last, j)}`
              rootEnd = j
            }
          }
        }
      } else {
        rootEnd = 1
      }
    } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
      device = path.substring(0, 2)
      rootEnd = 2
      if (len > 2 && isWindowsPathSeparator(path.charCodeAt(2))) {
        isAbsolute = true
        rootEnd = 3
      }
    }

    if (device.length > 0) {
      if (resolvedDevice.length > 0) {
        if (device.toLowerCase() !== resolvedDevice.toLowerCase()) {
          continue
        }
      } else {
        resolvedDevice = device
      }
    }

    if (resolvedAbsolute) {
      if (resolvedDevice.length > 0) {
        break
      }
    } else {
      resolvedTail = `${path.substring(rootEnd)}\\${resolvedTail}`
      resolvedAbsolute = isAbsolute
      if (isAbsolute && resolvedDevice.length > 0) {
        break
      }
    }
  }

  resolvedTail = normalizeString(resolvedTail, !resolvedAbsolute, '\\', isWindowsPathSeparator)

  return resolvedAbsolute
    ? `${resolvedDevice}\\${resolvedTail}`
    : `${resolvedDevice}${resolvedTail}` || '.'
}

exports.normalize = function normalize(path) {
  validateString(path, 'path')

  const len = path.length
  if (len === 0) return '.'
  let rootEnd = 0
  let device
  let isAbsolute = false
  const code = path.charCodeAt(0)

  if (len === 1) {
    return code === CHAR_FORWARD_SLASH ? '\\' : path
  }

  if (isWindowsPathSeparator(code)) {
    isAbsolute = true

    if (isWindowsPathSeparator(path.charCodeAt(1))) {
      let j = 2
      let last = j
      while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
        j++
      }
      if (j < len && j !== last) {
        const firstPart = path.substring(last, j)
        last = j
        while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
          j++
        }
        if (j < len && j !== last) {
          last = j
          while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
            j++
          }
          if (j === len) {
            return `\\\\${firstPart}\\${path.substring(last)}\\`
          }
          if (j !== last) {
            device = `\\\\${firstPart}\\${path.substring(last, j)}`
            rootEnd = j
          }
        }
      }
    } else {
      rootEnd = 1
    }
  } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
    device = path.substring(0, 2)
    rootEnd = 2
    if (len > 2 && isWindowsPathSeparator(path.charCodeAt(2))) {
      isAbsolute = true
      rootEnd = 3
    }
  }

  let tail =
    rootEnd < len
      ? normalizeString(path.substring(rootEnd), !isAbsolute, '\\', isWindowsPathSeparator)
      : ''
  if (tail.length === 0 && !isAbsolute) {
    tail = '.'
  }
  if (tail.length > 0 && isWindowsPathSeparator(path.charCodeAt(len - 1))) {
    tail += '\\'
  }
  if (device === undefined) {
    return isAbsolute ? `\\${tail}` : tail
  }
  return isAbsolute ? `${device}\\${tail}` : `${device}${tail}`
}

exports.isAbsolute = function isAbsolute(path) {
  validateString(path, 'path')

  const len = path.length
  if (len === 0) return false

  const code = path.charCodeAt(0)

  return (
    isWindowsPathSeparator(code) ||
    (len > 2 &&
      isWindowsDeviceRoot(code) &&
      path.charCodeAt(1) === CHAR_COLON &&
      isWindowsPathSeparator(path.charCodeAt(2)))
  )
}

exports.join = function join(...args) {
  if (args.length === 0) return '.'

  let joined
  let firstPart
  for (let i = 0; i < args.length; ++i) {
    const arg = args[i]
    validateString(arg, 'path')
    if (arg.length > 0) {
      if (joined === undefined) joined = firstPart = arg
      else joined += `\\${arg}`
    }
  }

  if (joined === undefined) return '.'

  let needsReplace = true
  let slashCount = 0
  if (isWindowsPathSeparator(firstPart.charCodeAt(0))) {
    ++slashCount
    const firstLen = firstPart.length
    if (firstLen > 1 && isWindowsPathSeparator(firstPart.charCodeAt(1))) {
      ++slashCount
      if (firstLen > 2) {
        if (isWindowsPathSeparator(firstPart.charCodeAt(2))) {
          ++slashCount
        } else {
          needsReplace = false
        }
      }
    }
  }
  if (needsReplace) {
    while (slashCount < joined.length && isWindowsPathSeparator(joined.charCodeAt(slashCount))) {
      slashCount++
    }

    if (slashCount >= 2) {
      joined = `\\${joined.substring(slashCount)}`
    }
  }

  return exports.normalize(joined)
}

exports.relative = function relative(from, to) {
  validateString(from, 'from')
  validateString(to, 'to')

  if (from === to) return ''

  const fromOrig = exports.resolve(from)
  const toOrig = exports.resolve(to)

  if (fromOrig === toOrig) return ''

  from = fromOrig.toLowerCase()
  to = toOrig.toLowerCase()

  if (from === to) return ''

  let fromStart = 0
  while (fromStart < from.length && from.charCodeAt(fromStart) === CHAR_BACKWARD_SLASH) {
    fromStart++
  }
  let fromEnd = from.length
  while (fromEnd - 1 > fromStart && from.charCodeAt(fromEnd - 1) === CHAR_BACKWARD_SLASH) {
    fromEnd--
  }
  const fromLen = fromEnd - fromStart

  let toStart = 0
  while (toStart < to.length && to.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) {
    toStart++
  }
  let toEnd = to.length
  while (toEnd - 1 > toStart && to.charCodeAt(toEnd - 1) === CHAR_BACKWARD_SLASH) {
    toEnd--
  }
  const toLen = toEnd - toStart

  const length = fromLen < toLen ? fromLen : toLen
  let lastCommonSep = -1
  let i = 0
  for (; i < length; i++) {
    const fromCode = from.charCodeAt(fromStart + i)
    if (fromCode !== to.charCodeAt(toStart + i)) {
      break
    } else if (fromCode === CHAR_BACKWARD_SLASH) {
      lastCommonSep = i
    }
  }

  if (i !== length) {
    if (lastCommonSep === -1) return toOrig
  } else {
    if (toLen > length) {
      if (to.charCodeAt(toStart + i) === CHAR_BACKWARD_SLASH) {
        return toOrig.substring(toStart + i + 1)
      }
      if (i === 2) {
        return toOrig.substring(toStart + i)
      }
    }
    if (fromLen > length) {
      if (from.charCodeAt(fromStart + i) === CHAR_BACKWARD_SLASH) {
        lastCommonSep = i
      } else if (i === 2) {
        lastCommonSep = 3
      }
    }
    if (lastCommonSep === -1) lastCommonSep = 0
  }

  let out = ''
  for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
    if (i === fromEnd || from.charCodeAt(i) === CHAR_BACKWARD_SLASH) {
      out += out.length === 0 ? '..' : '\\..'
    }
  }

  toStart += lastCommonSep

  if (out.length > 0) {
    return `${out}${toOrig.substring(toStart, toEnd)}`
  }
  if (toOrig.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) {
    ++toStart
  }
  return toOrig.substring(toStart, toEnd)
}

exports.toNamespacedPath = function toNamespacedPath(path) {
  if (typeof path !== 'string' || path.length === 0) return path

  const resolvedPath = exports.resolve(path)

  if (resolvedPath.length <= 2) return path

  if (resolvedPath.charCodeAt(0) === CHAR_BACKWARD_SLASH) {
    if (resolvedPath.charCodeAt(1) === CHAR_BACKWARD_SLASH) {
      const code = resolvedPath.charCodeAt(2)
      if (code !== CHAR_QUESTION_MARK && code !== CHAR_DOT) {
        return `\\\\?\\UNC\\${resolvedPath.substring(2)}`
      }
    }
  } else if (
    isWindowsDeviceRoot(resolvedPath.charCodeAt(0)) &&
    resolvedPath.charCodeAt(1) === CHAR_COLON &&
    resolvedPath.charCodeAt(2) === CHAR_BACKWARD_SLASH
  ) {
    return `\\\\?\\${resolvedPath}`
  }

  return path
}

exports.dirname = function dirname(path) {
  validateString(path, 'path')

  const len = path.length
  if (len === 0) return '.'
  let rootEnd = -1
  let offset = 0
  const code = path.charCodeAt(0)

  if (len === 1) {
    return isWindowsPathSeparator(code) ? path : '.'
  }

  if (isWindowsPathSeparator(code)) {
    rootEnd = offset = 1

    if (isWindowsPathSeparator(path.charCodeAt(1))) {
      let j = 2
      let last = j
      while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
        j++
      }
      if (j < len && j !== last) {
        last = j
        while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
          j++
        }
        if (j < len && j !== last) {
          last = j
          while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
            j++
          }
          if (j === len) {
            return path
          }
          if (j !== last) {
            rootEnd = offset = j + 1
          }
        }
      }
    }
  } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
    rootEnd = len > 2 && isWindowsPathSeparator(path.charCodeAt(2)) ? 3 : 2
    offset = rootEnd
  }

  let end = -1
  let matchedSlash = true
  for (let i = len - 1; i >= offset; --i) {
    if (isWindowsPathSeparator(path.charCodeAt(i))) {
      if (!matchedSlash) {
        end = i
        break
      }
    } else {
      matchedSlash = false
    }
  }

  if (end === -1) {
    if (rootEnd === -1) return '.'

    end = rootEnd
  }
  return path.substring(0, end)
}

exports.basename = function basename(path, suffix) {
  if (suffix !== undefined) validateString(suffix, 'suffix')
  validateString(path, 'path')

  let start = 0
  let end = -1
  let matchedSlash = true

  if (
    path.length >= 2 &&
    isWindowsDeviceRoot(path.charCodeAt(0)) &&
    path.charCodeAt(1) === CHAR_COLON
  ) {
    start = 2
  }

  if (suffix !== undefined && suffix.length > 0 && suffix.length <= path.length) {
    if (suffix === path) return ''
    let extIdx = suffix.length - 1
    let firstNonSlashEnd = -1
    for (let i = path.length - 1; i >= start; --i) {
      const code = path.charCodeAt(i)
      if (isWindowsPathSeparator(code)) {
        if (!matchedSlash) {
          start = i + 1
          break
        }
      } else {
        if (firstNonSlashEnd === -1) {
          matchedSlash = false
          firstNonSlashEnd = i + 1
        }
        if (extIdx >= 0) {
          if (code === suffix.charCodeAt(extIdx)) {
            if (--extIdx === -1) {
              end = i
            }
          } else {
            extIdx = -1
            end = firstNonSlashEnd
          }
        }
      }
    }

    if (start === end) end = firstNonSlashEnd
    else if (end === -1) end = path.length
    return path.substring(start, end)
  }
  for (let i = path.length - 1; i >= start; --i) {
    if (isWindowsPathSeparator(path.charCodeAt(i))) {
      if (!matchedSlash) {
        start = i + 1
        break
      }
    } else if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
  }

  if (end === -1) return ''
  return path.substring(start, end)
}

exports.extname = function extname(path) {
  validateString(path, 'path')

  let start = 0
  let startDot = -1
  let startPart = 0
  let end = -1
  let matchedSlash = true
  let preDotState = 0

  if (
    path.length >= 2 &&
    path.charCodeAt(1) === CHAR_COLON &&
    isWindowsDeviceRoot(path.charCodeAt(0))
  ) {
    start = startPart = 2
  }

  for (let i = path.length - 1; i >= start; --i) {
    const code = path.charCodeAt(i)
    if (isWindowsPathSeparator(code)) {
      if (!matchedSlash) {
        startPart = i + 1
        break
      }
      continue
    }
    if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
    if (code === CHAR_DOT) {
      if (startDot === -1) startDot = i
      else if (preDotState !== 1) preDotState = 1
    } else if (startDot !== -1) {
      preDotState = -1
    }
  }

  if (
    startDot === -1 ||
    end === -1 ||
    preDotState === 0 ||
    (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1)
  ) {
    return ''
  }
  return path.substring(startDot, end)
}
{
  "name": "bare-path",
  "version": "3.1.1",
  "description": "Path manipulation library for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./posix": "./lib/posix.js",
    "./win32": "./lib/win32.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds",
    "NOTICE"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-path.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-path/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-path#readme",
  "devDependencies": {
    "brittle": "^3.3.2",
    "cmake-bare": "^1.1.6",
    "lunte": "^1.8.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = require.addon()
const EventEmitter = require('bare-events')
const { Duplex } = require('bare-stream')
const binding = require('./binding')
const constants = require('./lib/constants')
const errors = require('./lib/errors')

const defaultReadBufferSize = 65536
const empty = Buffer.alloc(0)

const ipcHandle = Symbol.for('bare.ipc.handle')
const ipcAccept = Symbol.for('bare.ipc.accept')

module.exports = exports = class Pipe extends Duplex {
  constructor(path, opts = {}) {
    if (typeof path === 'object' && path !== null) {
      opts = path
      path = null
    }

    const {
      readBufferSize = defaultReadBufferSize,
      allowHalfOpen = true,
      eagerOpen = true,
      ipc = false
    } = opts

    super({ eagerOpen })

    this._state = 0

    this._allowHalfOpen = allowHalfOpen
    this._ipc = ipc

    this._fd = -1
    this._path = null

    this._pendingOpen = null
    this._pendingWrite = null
    this._pendingWriteBatch = null
    this._pendingWriteSegments = null
    this._pendingWriteIdx = 0
    this._pendingFinal = null
    this._pendingDestroy = null

    this._handleQueue = []
    this._handleQueueSize = 0

    this._buffer = Buffer.alloc(readBufferSize)

    this._handle = binding.init(
      this._buffer,
      ipc,
      this,
      noop,
      this._onconnect,
      this._onwrite,
      this._onfinal,
      this._onread,
      this._onhandle,
      this._onclose
    )

    if (typeof path === 'number') {
      this.open(path)
    } else if (typeof path === 'string') {
      this.connect(path)
    }
  }

  get connecting() {
    return (this._state & constants.state.CONNECTING) !== 0
  }

  get pending() {
    return (this._state & constants.state.CONNECTED) === 0
  }

  get readyState() {
    if (this._state & constants.state.READABLE && this._state & constants.state.WRITABLE) {
      return 'open'
    }

    if (this._state & constants.state.READABLE) {
      return 'readOnly'
    }

    if (this._state & constants.state.WRITABLE) {
      return 'writeOnly'
    }

    return 'opening'
  }

  get [ipcHandle]() {
    return this._handle
  }

  open(fd, opts = {}, onconnect) {
    if (typeof opts === 'function') {
      onconnect = opts
      opts = {}
    }

    if (typeof fd === 'object' && fd !== null) {
      opts = fd || {}
      fd = opts.fd
    }

    try {
      const status = binding.open(this._handle, fd)

      this._state |= constants.state.CONNECTED
      this._fd = fd

      if (status & binding.READABLE) {
        this._state |= constants.state.READABLE
      } else {
        this.push(null)
      }

      if (status & binding.WRITABLE) {
        this._state |= constants.state.WRITABLE
      } else {
        this.end()
      }

      if (onconnect) this.once('connect', onconnect)

      queueMicrotask(() => this.emit('connect'))
    } catch (err) {
      queueMicrotask(() => {
        if (this._pendingOpen) this._pendingOpen(err)
        else this.destroy(err)
      })
    }

    return this
  }

  connect(path, opts = {}, onconnect) {
    if (this._state & constants.state.CONNECTING || this._state & constants.state.CONNECTED) {
      throw errors.PIPE_ALREADY_CONNECTED('Pipe is already connected')
    }

    this._state |= constants.state.CONNECTING

    if (typeof opts === 'function') {
      onconnect = opts
      opts = {}
    }

    if (typeof path === 'object' && path !== null) {
      opts = path || {}
      path = opts.path
    }

    try {
      binding.connect(this._handle, path)

      this._path = path

      if (onconnect) this.once('connect', onconnect)
    } catch (err) {
      queueMicrotask(() => {
        if (this._pendingOpen) this._pendingOpen(err)
        else this.destroy(err)
      })
    }

    return this
  }

  write(chunk, encoding, handle, cb) {
    if (typeof encoding === 'function') {
      cb = encoding
      encoding = undefined
      handle = null
    } else if (typeof encoding === 'object' && encoding !== null) {
      if (typeof handle === 'function') cb = handle
      handle = encoding
      encoding = undefined
    } else if (typeof handle === 'function') {
      cb = handle
      handle = null
    }

    if (handle) this._handleQueueSize++

    this._handleQueue.push(handle || null)

    if (encoding) return super.write(chunk, encoding, cb)

    return super.write(chunk, cb)
  }

  accept(target) {
    const handle = target[ipcHandle]

    if (handle === undefined) {
      throw errors.INVALID_IPC_TARGET('Target does not implement the IPC handle protocol')
    }

    binding.accept(this._handle, handle)

    if (typeof target[ipcAccept] === 'function') target[ipcAccept]()

    return target
  }

  ref() {
    binding.ref(this._handle)

    return this
  }

  unref() {
    binding.unref(this._handle)

    return this
  }

  [ipcAccept]() {
    this._onaccept()
  }

  _open(cb) {
    if (this._state & constants.state.CONNECTED) return cb(null)

    this._pendingOpen = cb
  }

  _read() {
    if ((this._state & constants.state.READING) === 0) {
      this._state |= constants.state.READING

      binding.resume(this._handle)
    }
  }

  _writev(batch, cb) {
    this._pendingWrite = cb
    this._pendingWriteBatch = batch

    if (this._handleQueueSize === 0) {
      this._handleQueue = []
      this._pendingWriteSegments = null

      try {
        binding.writev(
          this._handle,
          batch.map(({ chunk }) => chunk),
          null
        )
      } catch (err) {
        this._continueWrite(err)
      }
      return
    }

    const handles = this._handleQueue.splice(0, batch.length)

    // Fill any holes in the batch for messages that don't carry a handle. Each
    // message that does carry a handle decrements the handle queue size.
    for (let i = 0; i < batch.length; i++) {
      if (handles[i] === undefined) handles[i] = null
      else if (handles[i] !== null) this._handleQueueSize--
    }

    const segments = []

    let i = 0
    while (i < batch.length) {
      if (handles[i] !== null) {
        segments.push({ chunks: [batch[i]], handle: handles[i] })
        i++
      } else {
        const start = i
        while (i < batch.length && handles[i] === null) i++
        segments.push({ chunks: batch.slice(start, i), handle: null })
      }
    }

    this._pendingWriteSegments = segments
    this._pendingWriteIdx = 0

    this._writeNextSegment()
  }

  _writeNextSegment() {
    const segment = this._pendingWriteSegments[this._pendingWriteIdx]

    const chunks = []
    for (let i = 0; i < segment.chunks.length; i++) {
      chunks.push(segment.chunks[i].chunk)
    }

    let sendHandle = null
    if (segment.handle !== null) sendHandle = segment.handle[ipcHandle]

    try {
      binding.writev(this._handle, chunks, sendHandle)
    } catch (err) {
      this._continueWrite(err)
    }
  }

  _final(cb) {
    if (this._state & constants.state.READABLE && this._state & constants.state.WRITABLE) {
      this._pendingFinal = cb

      binding.end(this._handle)
    } else {
      cb(null)
    }
  }

  _predestroy() {
    if (this._state & constants.state.CLOSING) return
    this._state |= constants.state.CLOSING

    binding.close(this._handle)
  }

  _destroy(err, cb) {
    if (this._state & constants.state.CLOSING) return cb(err)
    this._state |= constants.state.CLOSING

    this._pendingDestroy = cb

    binding.close(this._handle)
  }

  _continueOpen(err) {
    if (this._pendingOpen === null) return
    const cb = this._pendingOpen
    this._pendingOpen = null
    cb(err)
  }

  _continueWrite(err) {
    if (this._pendingWrite === null) return

    if (this._pendingWriteSegments === null) {
      const cb = this._pendingWrite
      this._pendingWrite = null
      this._pendingWriteBatch = null
      cb(err)
      return
    }

    this._pendingWriteIdx++

    if (err === null && this._pendingWriteIdx < this._pendingWriteSegments.length) {
      this._writeNextSegment()
      return
    }

    const cb = this._pendingWrite
    this._pendingWrite = null
    this._pendingWriteBatch = null
    this._pendingWriteSegments = null
    this._pendingWriteIdx = 0
    cb(err)
  }

  _continueFinal(err) {
    if (this._pendingFinal === null) return
    const cb = this._pendingFinal
    this._pendingFinal = null
    cb(err)
  }

  _continueDestroy() {
    if (this._pendingDestroy === null) return
    const cb = this._pendingDestroy
    this._pendingDestroy = null
    cb(null)
  }

  _onconnect(err) {
    if (err) {
      if (this._pendingOpen) this._continueOpen(err)
      else this.destroy(err)
      return
    }

    this._state |= constants.state.CONNECTED | constants.state.READABLE | constants.state.WRITABLE
    this._state &= ~constants.state.CONNECTING
    this._continueOpen()

    this.emit('connect')
  }

  _onaccept() {
    this._state |= constants.state.CONNECTED | constants.state.READABLE | constants.state.WRITABLE
    this._continueOpen()
  }

  _onread(err, read) {
    if (err) {
      this.destroy(err)
      return
    }

    if (read === 0) {
      this.push(null)
      if (this._allowHalfOpen === false) this.end()
      return
    }

    const copy = Buffer.allocUnsafe(read)
    copy.set(this._buffer.subarray(0, read))

    if (this.push(copy) === false && this.destroying === false) {
      this._state &= ~constants.state.READING

      binding.pause(this._handle)
    }
  }

  _onhandle(type) {
    this.emit('handle', type)
  }

  _onwrite(err) {
    this._continueWrite(err)
  }

  _onfinal(err) {
    this._continueFinal(err === null || err.code === 'ENOTCONN' ? null : err)
  }

  _onclose() {
    this._continueDestroy()
  }

  _onspawn(readable, writable) {
    this._state |= constants.state.CONNECTED

    if (readable) {
      this._state |= constants.state.READABLE
    } else {
      this.push(null)
    }

    if (writable) {
      this._state |= constants.state.WRITABLE
    } else {
      this.end()
    }

    this._continueOpen()
  }
}

exports.Pipe = exports

exports.pipe = function pipe() {
  return binding.pipe()
}

exports.Server = class PipeServer extends EventEmitter {
  constructor(opts = {}, onconnection) {
    if (typeof opts === 'function') {
      onconnection = opts
      opts = {}
    }

    super()

    const {
      readBufferSize = defaultReadBufferSize,
      allowHalfOpen = true,
      pauseOnConnect = false,
      ipc = false
    } = opts

    this._state = 0

    this._readBufferSize = readBufferSize
    this._allowHalfOpen = allowHalfOpen
    this._pauseOnConnect = pauseOnConnect
    this._ipc = ipc

    this._path = null
    this._connections = new Set()

    this._error = null
    this._handle = null

    if (onconnection) this.on('connection', onconnection)
  }

  get listening() {
    return (this._state & constants.state.BOUND) !== 0
  }

  address() {
    if ((this._state & constants.state.BOUND) === 0) {
      return null
    }

    return this._path
  }

  listen(path, backlog = 511, opts = {}, onlistening) {
    if (this._state & constants.state.BINDING || this._state & constants.state.BOUND) {
      throw errors.SERVER_ALREADY_LISTENING('Server is already listening')
    }

    if (this._state & constants.state.CLOSING) {
      throw errors.SERVER_IS_CLOSED('Server is closed')
    }

    this._state |= constants.state.BINDING

    if (typeof backlog === 'function') {
      onlistening = backlog
      backlog = 511
    } else if (typeof opts === 'function') {
      onlistening = opts
      opts = {}
    }

    if (typeof path === 'object' && path !== null) {
      opts = path || {}
      path = opts.path
      backlog = opts.backlog || 511
    }

    this._handle = binding.init(
      empty,
      this._ipc,
      this,
      this._onconnection,
      noop,
      noop,
      noop,
      noop,
      noop,
      this._onclose
    )

    if (this._state & constants.state.UNREFED) binding.unref(this._handle)

    try {
      binding.bind(this._handle, path, backlog)

      this._path = path
      this._state |= constants.state.BOUND
      this._state &= ~constants.state.BINDING

      if (onlistening) this.once('listening', onlistening)

      queueMicrotask(() => this.emit('listening'))
    } catch (err) {
      this._error = err

      binding.close(this._handle)
    }

    return this
  }

  close(onclose) {
    if (onclose) this.once('close', onclose)

    if (this._state & constants.state.CLOSING) return
    this._state |= constants.state.CLOSING

    this._closeMaybe()

    return this
  }

  ref() {
    this._state &= ~constants.state.UNREFED

    if (this._handle !== null) binding.ref(this._handle)

    return this
  }

  unref() {
    this._state |= constants.state.UNREFED

    if (this._handle !== null) binding.unref(this._handle)

    return this
  }

  _closeMaybe() {
    if (this._state & constants.state.CLOSING && this._connections.size === 0) {
      if (this._handle !== null) binding.close(this._handle)
      else queueMicrotask(() => this.emit('close'))
    }
  }

  _onconnection(err) {
    if (err) {
      this.emit('error', err)
      return
    }

    if (this._state & constants.state.CLOSING) return

    const pipe = new exports.Pipe({
      readBufferSize: this._readBufferSize,
      allowHalfOpen: this._allowHalfOpen,
      eagerOpen: !this._pauseOnConnect,
      ipc: this._ipc
    })

    try {
      binding.accept(this._handle, pipe._handle)

      pipe._path = this._path
      pipe._onaccept()

      this._connections.add(pipe)

      pipe.on('close', () => {
        this._connections.delete(pipe)
        this._closeMaybe()
      })

      this.emit('connection', pipe)
    } catch (err) {
      pipe.destroy()

      throw err
    }
  }

  _onclose() {
    const err = this._error

    this._state &= ~constants.state.BINDING
    this._error = null
    this._handle = null

    if (err) this.emit('error', err)
    else this.emit('close')
  }
}

exports.constants = constants
exports.errors = errors

exports.createConnection = function createConnection(path, opts, onconnect) {
  if (typeof opts === 'function') {
    onconnect = opts
    opts = {}
  }

  if (typeof path === 'object' && path !== null) {
    opts = path || {}
    path = opts.path
  }

  return new exports.Pipe(opts).connect(path, opts, onconnect)
}

exports.createServer = function createServer(opts, onconnection) {
  return new exports.Server(opts, onconnection)
}

function noop() {}
const binding = require('../binding')

module.exports = {
  state: {
    CONNECTING: 0x1,
    CONNECTED: 0x2,
    BINDING: 0x4,
    BOUND: 0x8,
    READING: 0x10,
    CLOSING: 0x20,
    READABLE: 0x40,
    WRITABLE: 0x80,
    UNREFED: 0x100
  },
  handle: {
    NAMED_PIPE: binding.UV_NAMED_PIPE,
    TCP: binding.UV_TCP,
    UDP: binding.UV_UDP
  }
}
module.exports = class PipeError extends Error {
  constructor(msg, fn = PipeError, code = fn.name) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'PipeError'
  }

  static PIPE_ALREADY_CONNECTED(msg) {
    return new PipeError(msg, PipeError.PIPE_ALREADY_CONNECTED)
  }

  static SERVER_ALREADY_LISTENING(msg) {
    return new PipeError(msg, PipeError.SERVER_ALREADY_LISTENING)
  }

  static SERVER_IS_CLOSED(msg) {
    return new PipeError(msg, PipeError.SERVER_IS_CLOSED)
  }

  static INVALID_IPC_TARGET(msg) {
    return new PipeError(msg, PipeError.INVALID_IPC_TARGET)
  }
}
{
  "name": "bare-pipe",
  "version": "4.2.2",
  "description": "Native I/O pipes for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    },
    "./errors": {
      "types": "./lib/errors.d.ts",
      "default": "./lib/errors.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-pipe.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-pipe/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-pipe#readme",
  "engines": {
    "bare": ">=1.16.0"
  },
  "dependencies": {
    "bare-events": "^2.0.0",
    "bare-stream": "^2.0.0"
  },
  "devDependencies": {
    "bare-path": "^3.0.0",
    "bare-tcp": "^2.4.1",
    "brittle": "^3.2.1",
    "cmake-bare": "^1.1.6",
    "lunte": "^1.8.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  }
}
{
  "name": "bare-posix",
  "version": "1.0.1",
  "description": "POSIX-specific bindings for Bare",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "android": "./unsupported.js",
      "win32": "./unsupported.js",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "unsupported.js",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-posix.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-posix/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-posix#readme",
  "devDependencies": {
    "brittle": "^3.19.1",
    "cmake-bare": "^1.7.7",
    "lunte": "^1.6.0",
    "prettier": "^3.8.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
exports.getgid = function getgid() {
  return -1
}

exports.setgid = function setgid() {
  throw new Error('Platform not supported')
}

exports.getegid = function getegid() {
  return -1
}

exports.setegid = function setgid() {
  throw new Error('Platform not supported')
}

exports.getuid = function getuid() {
  return -1
}

exports.setuid = function setgid() {
  throw new Error('Platform not supported')
}

exports.geteuid = function geteuid() {
  return -1
}

exports.seteuid = function setgid() {
  throw new Error('Platform not supported')
}

exports.getgroups = function getgroups() {
  return []
}

exports.getgrnam = function getgrnam() {
  return null
}

exports.getpwnam = function getpwnam() {
  return null
}
const abort = require('bare-abort')
const EventEmitter = require('bare-events')
const Signal = require('bare-signals')
const os = require('bare-os')
const env = require('bare-env')
const hrtime = require('bare-hrtime')
const stdio = require('bare-stdio')
const posix = require('bare-posix')

class Process extends EventEmitter {
  constructor() {
    super()

    this._startTime = hrtime.bigint()

    EventEmitter.forward(Bare, this, [
      'uncaughtException',
      'unhandledRejection',
      'beforeExit',
      'exit',
      'suspend',
      'wakeup',
      'idle',
      'resume'
    ])

    const signals = new Signal.Emitter()

    signals.unref()

    EventEmitter.forward(signals, this, Object.keys(os.constants.signals))
  }

  get stdin() {
    return stdio.in
  }

  get stdout() {
    return stdio.out
  }

  get stderr() {
    return stdio.err
  }

  get platform() {
    return os.platform()
  }

  get arch() {
    return os.arch()
  }

  get title() {
    return os.getProcessTitle()
  }

  set title(title) {
    os.setProcessTitle(title)
  }

  get pid() {
    return os.pid()
  }

  get ppid() {
    return os.ppid()
  }

  get argv() {
    return Bare.argv
  }

  get execArgv() {
    return []
  }

  get execPath() {
    return os.execPath()
  }

  get exitCode() {
    return Bare.exitCode
  }

  set exitCode(code) {
    Bare.exitCode = code
  }

  get version() {
    return Bare.version
  }

  get versions() {
    return Bare.versions
  }

  get env() {
    return env
  }

  get hrtime() {
    return hrtime
  }

  abort() {
    abort()
  }

  exit(code) {
    Bare.exit(code)
  }

  suspend() {
    Bare.suspend()
  }

  resume() {
    Bare.resume()
  }

  cwd() {
    return os.cwd()
  }

  chdir(directory) {
    os.chdir(directory)
  }

  kill(pid, signal) {
    os.kill(pid, signal)
  }

  uptime() {
    return Number(hrtime.bigint() - this._startTime) / 1e9
  }

  cpuUsage(previous) {
    return os.cpuUsage(previous)
  }

  threadCpuUsage(previous) {
    return os.threadCpuUsage(previous)
  }

  resourceUsage() {
    return os.resourceUsage()
  }

  availableMemory() {
    return os.availableMemory()
  }

  constrainedMemory() {
    return os.constrainedMemory()
  }

  memoryUsage() {
    return os.memoryUsage()
  }

  getgid() {
    return posix.getgid()
  }

  setgid(id) {
    return posix.setgid(id)
  }

  getegid() {
    return posix.getegid()
  }

  setegid(id) {
    return posix.setegid(id)
  }

  getuid() {
    return posix.getuid()
  }

  setuid(id) {
    return posix.setuid(id)
  }

  geteuid() {
    return posix.geteuid()
  }

  seteuid(id) {
    return posix.seteuid(id)
  }

  getgroups() {
    return posix.getgroups()
  }

  nextTick(cb, ...args) {
    queueMicrotask(cb.bind(null, ...args))
  }

  [Symbol.for('bare.inspect')]() {
    return {
      __proto__: { constructor: Process },

      platform: this.platform,
      arch: this.arch,
      title: this.title,
      pid: this.pid,
      ppid: this.ppid,
      argv: this.argv,
      execPath: this.execPath,
      exitCode: this.exitCode,
      version: this.version,
      versions: this.versions,
      env: this.env
    }
  }
}

module.exports = new Process()
{
  "name": "bare-process",
  "version": "4.5.1",
  "description": "Node.js-compatible process control for Bare",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "global.js",
    "global.d.ts"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-process.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-process/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-process#readme",
  "dependencies": {
    "bare-abort": "^2.0.13",
    "bare-env": "^3.0.0",
    "bare-events": "^2.3.1",
    "bare-hrtime": "^2.0.0",
    "bare-os": "^3.7.1",
    "bare-posix": "^1.0.1",
    "bare-signals": "^5.0.0",
    "bare-stdio": "^1.0.1"
  },
  "devDependencies": {
    "brittle": "^3.2.1",
    "lunte": "^1.6.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = require.addon()
const EventEmitter = require('bare-events')
const binding = require('./binding')
const errors = require('./lib/errors')

const signals = binding.signals

module.exports = exports = class Signal extends EventEmitter {
  constructor(signum) {
    super()

    if (typeof signum === 'string') {
      if (signum in signals === false) {
        throw errors.UNKNOWN_SIGNAL(`Unknown signal '${signum}'`)
      }

      signum = signals[signum]
    }

    this._signum = signum
    this._closing = null
    this._handle = binding.init(this, this._onsignal, this._onclose)
  }

  start() {
    if (this._closing) throw errors.SIGNAL_CLOSED('Signal is closed')
    binding.start(this._handle, this._signum)
    return this
  }

  stop() {
    if (this._closing) return this
    binding.stop(this._handle)
    return this
  }

  ref() {
    if (this._closing) return this
    binding.ref(this._handle)
    return this
  }

  unref() {
    if (this._closing) return this
    binding.unref(this._handle)
    return this
  }

  close() {
    if (this._closing) return this._closing
    this._closing = EventEmitter.once(this, 'close')

    binding.close(this._handle)

    return this._closing
  }

  _onsignal() {
    this.emit('signal', this._signum)
  }

  _onclose() {
    this._handle = null

    this.emit('close')
  }
}

exports.Emitter = require('./lib/emitter')

exports.constants = signals
exports.errors = errors
const EventEmitter = require('bare-events')
const Signal = require('..')

module.exports = class SignalEmitter extends EventEmitter {
  constructor() {
    super()

    this._signals = new Map()
    this._unrefed = false

    this.on('newListener', this._onnewlistener).on('removeListener', this._onremovelistener)
  }

  ref() {
    this._unrefed = false
    for (const signal of this._signals.values()) signal.ref()
    return this
  }

  unref() {
    this._unrefed = true
    for (const signal of this._signals.values()) signal.unref()
    return this
  }

  _onnewlistener(name) {
    if (name === 'newListener' || name === 'removeListener') return

    if (this.listenerCount(name) === 0) {
      const signal = new Signal(name)

      signal.on('signal', this._onsignal.bind(this, name)).start()

      if (this._unrefed) signal.unref()

      this._signals.set(name, signal)
    }
  }

  _onremovelistener(name) {
    if (name === 'newListener' || name === 'removeListener') return

    if (this.listenerCount(name) === 0) {
      const signal = this._signals.get(name)

      if (this._unrefed) signal.ref()

      signal.close()

      this._signals.delete(name)
    }
  }

  _onsignal(name) {
    this.emit(name, name, Signal.constants[name])
  }
}
module.exports = class SignalError extends Error {
  constructor(msg, fn = SignalError, code = fn.name) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'SignalError'
  }

  static UNKNOWN_SIGNAL(msg) {
    return new SignalError(msg, SignalError.UNKNOWN_SIGNAL)
  }

  static SIGNAL_CLOSED(msg) {
    return new SignalError(msg, SignalError.SIGNAL_CLOSED)
  }
}
{
  "name": "bare-signals",
  "version": "5.0.0",
  "description": "Native signal handling for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./errors": "./lib/errors.js",
    "./emitter": "./lib/emitter.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-signals.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-signals/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-signals#readme",
  "engines": {
    "bare": ">=1.7.0"
  },
  "dependencies": {
    "bare-events": "^2.5.3"
  },
  "devDependencies": {
    "bare-os": "^3.3.1",
    "brittle": "^3.2.1",
    "cmake-bare": "^1.1.6",
    "lunte": "^1.8.3",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = require.addon()
const fs = require('bare-fs')
const tty = require('bare-tty')
const Pipe = require('bare-pipe')
const binding = require('./binding')

const { TTY, NAMED_PIPE } = binding

class IO {
  constructor() {
    this._in = null
    this._out = null
    this._err = null
  }

  get in() {
    if (this._in === null) {
      switch (binding.guessType(0)) {
        case TTY:
          this._in = new tty.ReadStream(0)
          break
        case NAMED_PIPE:
          this._in = new Pipe(0, { eagerOpen: false })
          break
        default:
          this._in = fs.createReadStream(null, { fd: 0, eagerOpen: false })
      }
    }

    return this._in
  }

  get out() {
    if (this._out === null) {
      switch (binding.guessType(1)) {
        case TTY:
          this._out = new tty.WriteStream(1)
          break
        case NAMED_PIPE:
          this._out = new Pipe(1, { eagerOpen: false })
          this._out.unref()
          break
        default:
          this._out = fs.createWriteStream(null, { fd: 1, eagerOpen: false })
      }
    }

    return this._out
  }

  get err() {
    if (this._err === null) {
      switch (binding.guessType(2)) {
        case TTY:
          this._err = new tty.WriteStream(2)
          break
        case NAMED_PIPE:
          this._err = new Pipe(2, { eagerOpen: false })
          this._err.unref()
          break
        default:
          this._err = fs.createWriteStream(null, { fd: 2, eagerOpen: false })
      }
    }

    return this._err
  }
}

module.exports = new IO()
{
  "name": "bare-stdio",
  "version": "1.0.3",
  "description": "Standard input/output streams for Bare",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-stdio.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-stdio/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-stdio#readme",
  "dependencies": {
    "bare-fs": "^4.5.2",
    "bare-pipe": "^4.1.5",
    "bare-tty": "^5.0.3"
  },
  "devDependencies": {
    "bare-os": "^3.6.2",
    "bare-path": "^3.0.0",
    "bare-subprocess": "^6.0.0",
    "brittle": "^3.19.1",
    "cmake-bare": "^1.7.7",
    "lunte": "^1.4.0",
    "prettier": "^3.8.1",
    "prettier-config-holepunch": "^2.0.0",
    "tt-native": "^1.1.1"
  }
}
const b4a = require('b4a')
const stream = require('streamx')
const { ReadableStream, WritableStream } = require('./web')

const defaultEncoding = 'utf8'

module.exports = exports = stream.Stream

exports.pipeline = stream.pipeline

exports.isStream = stream.isStream
exports.isEnding = stream.isEnding
exports.isEnded = stream.isEnded
exports.isFinishing = stream.isFinishing
exports.isFinished = stream.isFinished
exports.isDisturbed = stream.isDisturbed

exports.isErrored = function isErrored(stream) {
  return exports.getStreamError(stream) !== null
}

exports.isReadable = function isReadable(stream) {
  return stream.readable && !stream.destroying && !exports.isEnded(stream)
}

exports.isWritable = function isWritable(stream) {
  return stream.writable && !stream.destroying && !exports.isFinishing(stream)
}

exports.getStreamError = stream.getStreamError

exports.addAbortSignal = function addAbortSignal(signal, stream) {
  function onAbort() {
    stream.destroy(signal.reason)
  }

  if (signal.aborted) onAbort()
  else signal.addEventListener('abort', onAbort)

  return stream
}

exports.Stream = exports

exports.Readable = class Readable extends stream.Readable {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthReadable: null,
      map: null,
      mapReadable: null
    })

    if (this._construct) this._open = this._construct

    if (this._read !== stream.Readable.prototype._read) {
      this._read = read.bind(this, this._read)
    }

    if (this._destroy !== stream.Stream.prototype._destroy) {
      this._destroy = destroy.bind(this, this._destroy)
    }
  }

  get closed() {
    return !exports.isReadable(this)
  }

  get errored() {
    return stream.getStreamError(this)
  }

  push(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    return super.push(chunk)
  }

  unshift(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    super.unshift(chunk)
  }

  static fromWeb(readableStream, opts = {}) {
    const stream = readableStream._stream

    if (opts.encoding) stream.setEncoding(opts.encoding)
    if (opts.signal) exports.addAbortSignal(opts.signal, stream)

    return stream
  }

  static toWeb(readable, opts = {}) {
    return new ReadableStream(readable, opts.strategy)
  }

  async [Symbol.asyncDispose]() {
    if (!this.destroyed) this.destroy()

    await new Promise((resolve) => exports.finished(this, resolve))
  }
}

exports.Writable = class Writable extends stream.Writable {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthWritable,
      map: null,
      mapWritable: null
    })

    if (this._construct) this._open = this._construct

    if (this._write !== stream.Writable.prototype._write) {
      this._write = write.bind(this, this._write)
    }

    if (this._destroy !== stream.Stream.prototype._destroy) {
      this._destroy = destroy.bind(this, this._destroy)
    }
  }

  get closed() {
    return !exports.isWritable(this)
  }

  get errored() {
    return stream.getStreamError(this)
  }

  write(chunk, encoding, cb) {
    if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result = super.write({ chunk, encoding })

    if (cb) stream.Writable.drained(this).then(() => cb(null), cb)

    return result
  }

  end(chunk, encoding, cb) {
    if (typeof chunk === 'function') {
      cb = chunk
      chunk = null
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    } else {
      encoding = 'buffer'
    }

    const result =
      chunk !== undefined && chunk !== null ? super.end({ chunk, encoding }) : super.end()

    if (cb) this.once('finish', () => cb(null))

    return result
  }

  static fromWeb(writableStream, opts = {}) {
    const stream = writableStream._stream

    if (opts.signal) exports.addAbortSignal(opts.signal, stream)

    return stream
  }

  static toWeb(writable) {
    return new WritableStream(writable)
  }

  async [Symbol.asyncDispose]() {
    if (!this.destroyed) this.destroy()

    await new Promise((resolve) => exports.finished(this, resolve))
  }
}

exports.Duplex = class Duplex extends stream.Duplex {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthReadable: null,
      byteLengthWritable,
      map: null,
      mapReadable: null,
      mapWritable: null
    })

    if (this._construct) this._open = this._construct

    if (this._read !== stream.Readable.prototype._read) {
      this._read = read.bind(this, this._read)
    }

    if (this._write !== stream.Duplex.prototype._write) {
      this._write = write.bind(this, this._write)
    }

    if (this._destroy !== stream.Stream.prototype._destroy) {
      this._destroy = destroy.bind(this, this._destroy)
    }
  }

  push(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    return super.push(chunk)
  }

  unshift(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    super.unshift(chunk)
  }

  write(chunk, encoding, cb) {
    if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result = super.write({ chunk, encoding })

    if (cb) stream.Writable.drained(this).then(() => cb(null), cb)

    return result
  }

  end(chunk, encoding, cb) {
    if (typeof chunk === 'function') {
      cb = chunk
      chunk = null
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result =
      chunk !== undefined && chunk !== null ? super.end({ chunk, encoding }) : super.end()

    if (cb) this.once('finish', () => cb(null))

    return result
  }

  static fromWeb({ readable: readableStream, writable: writableStream }, opts) {
    const readable = exports.Readable.fromWeb(readableStream, opts)
    const writable = exports.Writable.fromWeb(writableStream, opts)

    const duplex = new exports.Duplex({
      write(data, encoding, cb) {
        writable.write(data, encoding, cb)
      }
    })

    readable
      .on('data', (data) => duplex.push(data))
      .on('end', () => duplex.push(null))
      .on('error', (err) => duplex.destroy(err))

    writable.on('finish', () => duplex.end()).on('error', (err) => duplex.destroy(err))

    return duplex
  }

  static toWeb(duplex) {
    const readableStream = exports.Readable.toWeb(duplex)
    const writableStream = exports.Writable.toWeb(duplex)

    return { readable: readableStream, writable: writableStream }
  }
}

class DuplexSide extends exports.Duplex {
  constructor(opts) {
    super(opts)

    this._otherSide = null
    this._cb = null
  }

  _read() {
    const cb = this._cb
    if (!cb) return

    this._cb = null
    cb()
  }

  _write(chunk, encoding, cb) {
    this._otherSide.push(chunk, encoding)
    this._otherSide._cb = cb
  }

  _final(cb) {
    this._otherSide.on('end', cb)
    this._otherSide.push(null)
  }
}

exports.duplexPair = function duplexPair(opts) {
  const sideA = new DuplexSide(opts)
  const sideB = new DuplexSide(opts)

  sideA._otherSide = sideB
  sideB._otherSide = sideA

  return [sideA, sideB]
}

exports.Transform = class Transform extends stream.Transform {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthReadable: null,
      byteLengthWritable,
      map: null,
      mapReadable: null,
      mapWritable: null
    })

    if (this._transform !== stream.Transform.prototype._transform) {
      this._transform = transform.bind(this, this._transform)
    } else {
      this._transform = passthrough
    }
  }

  push(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    return super.push(chunk)
  }

  unshift(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    super.unshift(chunk)
  }

  write(chunk, encoding, cb) {
    if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result = super.write({ chunk, encoding })

    if (cb) stream.Writable.drained(this).then(() => cb(null), cb)

    return result
  }

  end(chunk, encoding, cb) {
    if (typeof chunk === 'function') {
      cb = chunk
      chunk = null
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result =
      chunk !== undefined && chunk !== null ? super.end({ chunk, encoding }) : super.end()

    if (cb) this.once('finish', () => cb(null))

    return result
  }
}

exports.PassThrough = class PassThrough extends exports.Transform {}

exports.finished = function finished(stream, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (!opts) opts = {}

  const { cleanup = false } = opts

  const done = () => {
    cb(exports.getStreamError(stream, { all: true }))

    if (cleanup) detach()
  }

  const detach = () => {
    stream.off('close', done)
    stream.off('error', noop)
  }

  if (stream.destroyed) {
    done()
  } else {
    stream.on('close', done)
    stream.on('error', noop)
  }

  return detach
}

function read(read, cb) {
  read.call(this, 65536)

  cb(null)
}

function write(write, data, cb) {
  write.call(this, data.chunk, data.encoding, cb)
}

function transform(transform, data, cb) {
  transform.call(this, data.chunk, data.encoding, cb)
}

function destroy(destroy, cb) {
  destroy.call(this, exports.getStreamError(this), cb)
}

function passthrough(data, cb) {
  cb(null, data.chunk)
}

function byteLengthWritable(data) {
  return data.chunk.byteLength
}

function noop() {}
{
  "name": "bare-stream",
  "version": "2.13.3",
  "description": "Streaming data for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./promises": "./promises.js",
    "./web": {
      "types": "./web.d.ts",
      "default": "./web.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "promises.js",
    "web.js",
    "web.d.ts",
    "global.js",
    "global.d.ts"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-stream.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-stream/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-stream#readme",
  "dependencies": {
    "b4a": "^1.8.1",
    "streamx": "^2.25.0",
    "teex": "^1.0.1"
  },
  "devDependencies": {
    "bare-abort-controller": "^1.1.0",
    "bare-buffer": "^3.0.0",
    "bare-events": "^2.5.4",
    "brittle": "^3.5.2",
    "lunte": "^1.6.0",
    "prettier": "^3.3.3",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "bare-abort-controller": "*",
    "bare-buffer": "*",
    "bare-events": "*"
  },
  "peerDependenciesMeta": {
    "bare-abort-controller": {
      "optional": true
    },
    "bare-buffer": {
      "optional": true
    },
    "bare-events": {
      "optional": true
    }
  }
}
const { Readable, Writable, Transform, getStreamError, isStreamx, isDisturbed } = require('streamx')
const tee = require('teex')

const readableKind = Symbol.for('bare.stream.readable.kind')
const writableKind = Symbol.for('bare.stream.writable.kind')
const transformKind = Symbol.for('bare.stream.transform.kind')

// https://streams.spec.whatwg.org/#readablestreamdefaultreader
exports.ReadableStreamDefaultReader = class ReadableStreamDefaultReader {
  constructor(stream) {
    this._stream = stream
    this._stream._stream.once('close', onclose).once('error', onerror)

    const closed = Promise.withResolvers()

    // Avoid unhandled exceptions
    closed.promise.catch(noop)

    this._closed = closed

    function onclose() {
      closed.resolve()
    }

    function onerror(err) {
      closed.reject(err)
    }
  }

  get closed() {
    return this._closed.promise
  }

  read() {
    const stream = this._stream._stream

    return new Promise((resolve, reject) => {
      const err = getStreamError(stream)

      if (err) return reject(err)

      if (stream.destroyed) {
        return resolve({ value: undefined, done: true })
      }

      const value = stream.read()

      if (value !== null) {
        return resolve({ value, done: false })
      }

      stream.once('readable', onreadable).once('close', onclose).once('error', onerror)

      function onreadable() {
        const value = stream.read()

        ondone(null, value === null ? { value: undefined, done: true } : { value, done: false })
      }

      function onclose() {
        ondone(null, { value: undefined, done: true })
      }

      function onerror(err) {
        ondone(err, null)
      }

      function ondone(err, value) {
        stream.off('readable', onreadable).off('close', onclose).off('error', onerror)

        if (err) reject(err)
        else resolve(value)
      }
    })
  }

  releaseLock() {
    this._closed.reject(new TypeError('Reader was released'))
    this._stream._releaseLock()
    this._stream = null
  }

  cancel(reason = new TypeError('Stream was cancelled')) {
    const stream = this._stream._stream

    if (stream.destroyed) return Promise.resolve()

    return new Promise((resolve) =>
      stream.once('close', resolve).once('error', noop).destroy(reason)
    )
  }
}

// https://streams.spec.whatwg.org/#readablestreamdefaultcontroller
exports.ReadableStreamDefaultController = class ReadableStreamDefaultController {
  constructor(stream) {
    this._stream = stream
  }

  get desiredSize() {
    const stream = this._stream._stream

    return stream._readableState.highWaterMark - stream._readableState.buffered
  }

  enqueue(data) {
    this._stream._stream.push(data)
  }

  close() {
    this._stream._stream.push(null)
  }

  error(err) {
    this._stream._stream.destroy(err)
  }
}

// https://streams.spec.whatwg.org/#readablestream
class ReadableStream {
  static get [readableKind]() {
    return 0 // Compatibility version
  }

  static from(iterable) {
    return new ReadableStream(Readable.from(iterable))
  }

  constructor(underlyingSource = {}, queuingStrategy) {
    if (isStreamx(underlyingSource)) {
      this._stream = underlyingSource
    } else {
      if (queuingStrategy === undefined) {
        queuingStrategy = new exports.CountQueuingStrategy()
      }

      const { start, pull, cancel } = underlyingSource
      const { highWaterMark = 1, size = defaultSize } = queuingStrategy

      this._stream = new Readable({ highWaterMark, byteLength: size })

      const controller = new exports.ReadableStreamDefaultController(this)

      try {
        let starting = Promise.resolve()

        if (start) starting = forwardError(start.call(this, controller), controller)

        if (pull) {
          this._stream._read = this._read.bind(this, starting, pull.bind(this, controller))
        }

        if (cancel) {
          this._stream.once('error', cancel.bind(this))
        }
      } catch (err) {
        controller.error(err)
      }
    }

    this._reader = null
  }

  get [readableKind]() {
    return ReadableStream[readableKind]
  }

  get locked() {
    return this._reader !== null
  }

  getReader() {
    if (this.locked) throw new TypeError('Stream is locked')

    this._reader = new exports.ReadableStreamDefaultReader(this)

    return this._reader
  }

  cancel(reason = new TypeError('Stream was cancelled')) {
    const stream = this._stream

    if (stream.destroyed) return Promise.resolve()

    if (this.locked) return Promise.reject(new TypeError('Stream is locked'))

    return new Promise((resolve) =>
      stream.once('close', resolve).once('error', noop).destroy(reason)
    )
  }

  tee() {
    const [a, b] = tee(this._stream)

    return [new ReadableStream(a), new ReadableStream(b)]
  }

  pipeTo(destination) {
    return new Promise((resolve, reject) =>
      this._stream.pipe(destination._stream, (err) => {
        err ? reject(err) : resolve()
      })
    )
  }

  [Symbol.asyncIterator]() {
    return this._stream[Symbol.asyncIterator]()
  }

  _releaseLock() {
    this._reader = null
  }

  async _read(starting, pull, cb) {
    await starting

    let err = null
    try {
      await pull()
    } catch (e) {
      err = e
    }
    cb(err)
  }
}

function defaultSize() {
  return 1
}

exports.ReadableStream = ReadableStream

// https://streams.spec.whatwg.org/#countqueuingstrategy
exports.CountQueuingStrategy = class CountQueuingStrategy {
  constructor(opts = {}) {
    const { highWaterMark = 1 } = opts

    this.highWaterMark = highWaterMark
  }

  size(chunk) {
    return 1
  }
}

// https://streams.spec.whatwg.org/#bytelengthqueuingstrategy
exports.ByteLengthQueuingStrategy = class ByteLengthQueuingStrategy {
  constructor(opts = {}) {
    const { highWaterMark = 16384 } = opts

    this.highWaterMark = highWaterMark
  }

  size(chunk) {
    return chunk.byteLength
  }
}

exports.isReadableStream = function isReadableStream(value) {
  if (value instanceof ReadableStream) return true

  return (
    typeof value === 'object' &&
    value !== null &&
    value[readableKind] === ReadableStream[readableKind]
  )
}

// https://streams.spec.whatwg.org/#readablestream-errored
exports.isReadableStreamErrored = function isReadableStreamErrored(stream) {
  return getStreamError(stream._stream) !== null
}

// https://streams.spec.whatwg.org/#is-readable-stream-disturbed
exports.isReadableStreamDisturbed = function isReadableStreamDisturbed(stream) {
  return isDisturbed(stream._stream)
}

// https://streams.spec.whatwg.org/#writablestreamdefaultwriter
exports.WritableStreamDefaultWriter = class WritableStreamDefaultWriter {
  constructor(stream) {
    this._stream = stream
    this._stream._stream.once('close', onclose).once('error', onerror)

    const closed = Promise.withResolvers()

    // Avoid unhandled exceptions
    closed.promise.catch(noop)

    this._closed = closed

    function onclose() {
      closed.resolve()
    }

    function onerror(err) {
      closed.reject(err)
    }
  }

  get desiredSize() {
    const stream = this._stream._stream

    return stream._writableState.highWaterMark - stream._writableState.buffered
  }

  get closed() {
    return this._closed.promise
  }

  get ready() {
    const stream = this._stream._stream

    if (getStreamError(stream)) return Promise.reject()

    return Writable.drained(stream).then()
  }

  async write(chunk) {
    const stream = this._stream._stream

    let err = getStreamError(stream)
    if (err) return Promise.reject(err)

    stream.write(chunk)

    await Writable.drained(stream)

    err = getStreamError(stream)
    if (err) return Promise.reject(err)
  }

  releaseLock() {
    this._closed.reject(new TypeError('Writer was released'))
    this._stream._releaseLock()
    this._stream = null
  }

  close() {
    const stream = this._stream._stream

    if (stream.destroyed) return Promise.resolve()

    return new Promise((resolve) => stream.once('close', resolve).end())
  }

  abort(reason = new TypeError('Stream was aborted')) {
    const stream = this._stream._stream

    if (stream.destroyed) return Promise.resolve()

    return new Promise((resolve) => stream.once('close', resolve).destroy(reason))
  }
}

// https://streams.spec.whatwg.org/#writablestreamdefaultcontroller
exports.WritableStreamDefaultController = class WritableStreamDefaultController {
  constructor(stream) {
    this._stream = stream
  }

  error(err) {
    this._stream._stream.destroy(err)
  }
}

// https://streams.spec.whatwg.org/#writablestream
class WritableStream {
  static get [writableKind]() {
    return 0 // Compatibility version
  }

  constructor(underlyingSink = {}, queuingStrategy = {}) {
    if (isStreamx(underlyingSink)) {
      this._stream = underlyingSink
    } else {
      if (queuingStrategy === undefined) {
        queuingStrategy = new exports.CountQueuingStrategy()
      }

      const { start, write, close, abort } = underlyingSink
      const { highWaterMark = 1, size = defaultSize } = queuingStrategy

      this._stream = new Writable({ highWaterMark, byteLength: size })

      const controller = new exports.WritableStreamDefaultController(this)

      this._controller = controller

      try {
        let starting = Promise.resolve()

        if (start) starting = forwardError(start.call(this, controller), controller)

        if (write) {
          this._stream._write = this._write.bind(this, starting, write.bind(this))
        }

        if (close) {
          this._stream._destroy = this._destroy.bind(this, close.call(this))
        }

        if (abort) {
          this._stream.once('error', abort.bind(this))
        }
      } catch (err) {
        controller.error(err)
      }
    }

    this._writer = null
  }

  get [writableKind]() {
    return WritableStream[writableKind]
  }

  get locked() {
    return this._writer !== null
  }

  getWriter() {
    if (this.locked) throw new TypeError('Stream is locked')

    this._writer = new exports.WritableStreamDefaultWriter(this)

    return this._writer
  }

  abort(reason = new TypeError('Stream was aborted')) {
    if (this._stream.destroyed) return Promise.resolve()

    if (this.locked) return Promise.reject(new TypeError('Stream is locked'))

    return new Promise((resolve) => this._stream.once('close', resolve).destroy(reason))
  }

  close() {
    if (this._stream.destroyed) return Promise.resolve()

    if (this.locked) return Promise.reject(new TypeError('Stream is locked'))

    return new Promise((resolve) => this._stream.once('close', resolve).end())
  }

  _releaseLock() {
    this._writer = null
  }

  async _write(starting, write, data, cb) {
    await starting

    let err = null
    try {
      await write(data, this._controller)
    } catch (e) {
      err = e
    }
    cb(err)
  }

  async _destroy(closing, cb) {
    let err = null
    try {
      await closing
    } catch (e) {
      err = e
    }
    cb(err)
  }
}

exports.WritableStream = WritableStream

exports.isWritableStream = function isWritableStream(value) {
  if (value instanceof WritableStream) return true

  return (
    typeof value === 'object' &&
    value !== null &&
    value[writableKind] === WritableStream[writableKind]
  )
}

// https://streams.spec.whatwg.org/#transformstreamdefaultcontroller
exports.TransformStreamDefaultController = class TransformStreamDefaultController {
  constructor(stream) {
    this._stream = stream
  }

  get desiredSize() {
    const stream = this._stream._stream

    return stream._readableState.highWaterMark - stream._readableState.buffered
  }

  enqueue(data) {
    this._stream._stream.push(data)
  }

  error(err) {
    this._stream._stream.destroy(err)
  }

  terminate() {
    const stream = this._stream._stream

    stream.push(null)
    stream.destroy(new TypeError('Stream has been terminated'))
  }
}

// https://streams.spec.whatwg.org/#transformstream
class TransformStream {
  static get [transformKind]() {
    return 0 // Compatibility version
  }

  constructor(transformer = {}, writableStrategy = {}, readableStrategy = {}) {
    if (isStreamx(transformer)) {
      this._stream = transformer
    } else {
      const { start, transform, flush } = transformer

      this._stream = new Transform({ ...writableStrategy, ...readableStrategy })

      const controller = new exports.TransformStreamDefaultController(this)

      this._controller = controller

      try {
        let starting = Promise.resolve()

        if (start) starting = forwardError(start.call(this, controller), controller)

        if (transform) {
          this._stream._transform = this._transform.bind(this, starting, transform.bind(this))
        }

        if (flush) {
          this._stream._flush = this._flush.bind(this, flush.call(this, this._controller))
        }
      } catch (err) {
        controller.error(err)
      }
    }

    this._writable = new WritableStream(this._stream)
    this._readable = new ReadableStream(this._stream)
  }

  get [transformKind]() {
    return TransformStream[transformKind]
  }

  get writable() {
    return this._writable
  }

  get readable() {
    return this._readable
  }

  async _transform(starting, transform, data, cb) {
    await starting

    let err = null
    try {
      await transform(data, this._controller)
    } catch (e) {
      err = e
    }
    cb(err)
  }

  async _flush(flush, cb) {
    let err = null
    try {
      await flush
    } catch (e) {
      err = e
    }
    cb(err)
  }
}

exports.TransformStream = TransformStream

exports.isTransformStream = function isTransformStream(value) {
  if (value instanceof TransformStream) return true

  return (
    typeof value === 'object' &&
    value !== null &&
    value[transformKind] === TransformStream[transformKind]
  )
}

async function forwardError(promise, controller) {
  try {
    await promise
  } catch (err) {
    controller.error(err)
  }
}

function noop() {}
module.exports = require.addon()
const { Readable, Writable } = require('bare-stream')
const Signal = require('bare-signals')
const binding = require('./binding')
const constants = require('./lib/constants')

const defaultReadBufferSize = 65536
const empty = Buffer.alloc(0)

exports.ReadStream = class TTYReadStream extends Readable {
  constructor(fd, opts = {}) {
    super()

    const { readBufferSize = defaultReadBufferSize, allowHalfOpen = true } = opts

    this._fd = fd
    this._state = 0
    this._allowHalfOpen = allowHalfOpen
    this._buffer = Buffer.alloc(readBufferSize)

    this._pendingDestroy = null

    this._handle = binding.init(fd, this._buffer, this, noop, this._onread, this._onclose)
  }

  get fd() {
    return this._fd
  }

  get isTTY() {
    return true
  }

  setMode(mode) {
    binding.setMode(this._handle, mode)
    return this
  }

  setRawMode(enabled) {
    return this.setMode(enabled ? constants.mode.RAW : constants.mode.NORMAL)
  }

  _read() {
    if ((this._state & constants.state.READING) === 0) {
      this._state |= constants.state.READING

      binding.resume(this._handle)
    }
  }

  _predestroy() {
    if (this._state & constants.state.CLOSING) return
    this._state |= constants.state.CLOSING

    binding.close(this._handle)
  }

  _destroy(err, cb) {
    if (this._state & constants.state.CLOSING) return cb(err)
    this._state |= constants.state.CLOSING

    this._pendingDestroy = cb

    binding.close(this._handle)
  }

  _continueDestroy() {
    if (this._pendingDestroy === null) return
    const cb = this._pendingDestroy
    this._pendingDestroy = null
    cb(null)
  }

  _onread(err, read) {
    if (err) {
      this.destroy(err)
      return
    }

    if (read === 0) {
      this.push(null)
      if (this._allowHalfOpen === false) this.end()
      return
    }

    const copy = Buffer.allocUnsafe(read)
    copy.set(this._buffer.subarray(0, read))

    if (this.push(copy) === false && this.destroying === false) {
      this._state &= ~constants.state.READING

      binding.pause(this._handle)
    }
  }

  _onclose() {
    this._handle = null

    this._continueDestroy()
  }
}

exports.WriteStream = class TTYWriteStream extends Writable {
  constructor(fd, opts = {}) {
    super()

    this._fd = fd
    this._state = 0
    this._size = null

    this._pendingWrite = null
    this._pendingWriteBatch = null
    this._pendingDestroy = null

    this._handle = binding.init(fd, empty, this, this._onwrite, noop, this._onclose)

    this._size = this.getWindowSize()

    if (TTYWriteStream._streams.size === 0) TTYWriteStream._resize.start()

    TTYWriteStream._streams.add(this)
  }

  get fd() {
    return this._fd
  }

  get isTTY() {
    return true
  }

  get columns() {
    return this._size[0]
  }

  get rows() {
    return this._size[1]
  }

  getWindowSize() {
    return binding.getWindowSize(this._handle)
  }

  _writev(batch, cb) {
    this._pendingWrite = cb
    this._pendingWriteBatch = batch

    try {
      binding.writev(
        this._handle,
        batch.map(({ chunk }) => chunk)
      )
    } catch (err) {
      this._continueWrite(err)
    }
  }

  _predestroy() {
    if (this._state & constants.state.CLOSING) return
    this._state |= constants.state.CLOSING

    binding.close(this._handle)

    TTYWriteStream._streams.delete(this)

    if (TTYWriteStream._streams.size === 0) TTYWriteStream._resize.stop()
  }

  _destroy(err, cb) {
    if (this._state & constants.state.CLOSING) return cb(err)
    this._state |= constants.state.CLOSING

    this._pendingDestroy = cb

    binding.close(this._handle)

    TTYWriteStream._streams.delete(this)

    if (TTYWriteStream._streams.size === 0) TTYWriteStream._resize.stop()
  }

  _continueWrite(err) {
    if (this._pendingWrite === null) return
    const cb = this._pendingWrite
    this._pendingWrite = null
    this._pendingWriteBatch = null
    cb(err)
  }

  _continueDestroy() {
    if (this._pendingDestroy === null) return
    const cb = this._pendingDestroy
    this._pendingDestroy = null
    cb(null)
  }

  _onwrite(err) {
    this._continueWrite(err)
  }

  _onclose() {
    this._handle = null

    this._continueDestroy()
  }

  _onresize() {
    this._size = this.getWindowSize()

    this.emit('resize')
  }

  static _streams = new Set()

  static _resize = new Signal('SIGWINCH')
}

exports.constants = constants

exports.isTTY = binding.isTTY

exports.isatty = exports.isTTY // For Node.js compatibility

exports.WriteStream._resize
  .on('signal', () => {
    for (const stream of exports.WriteStream._streams) {
      stream._onresize()
    }
  })
  .unref()

function noop() {}
const binding = require('../binding')

module.exports = exports = {
  mode: {
    NORMAL: binding.MODE_NORMAL,
    RAW: binding.MODE_RAW,
    IO: binding.MODE_IO || 0
  },

  state: {
    READING: 0x1,
    CLOSING: 0x2
  }
}

/** @deprecated Use `mode.NORMAL` */
exports.MODE_NORMAL = exports.mode.NORMAL
/** @deprecated Use `mode.RAW` */
exports.MODE_RAW = exports.mode.RAW
/** @deprecated Use `mode.IO` */
exports.MODE_IO = exports.mode.IO
{
  "name": "bare-tty",
  "version": "5.1.2",
  "description": "Native TTY streams for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./constants": "./lib/constants.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-tty.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-tty/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-tty#readme",
  "engines": {
    "bare": ">=1.16.0"
  },
  "dependencies": {
    "bare-events": "^2.2.0",
    "bare-signals": "^5.0.0",
    "bare-stream": "^2.0.0"
  },
  "devDependencies": {
    "brittle": "^3.2.1",
    "cmake-bare": "^1.1.6",
    "lunte": "^1.8.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = require.addon()
const binding = require('./binding')

const t = binding.constants

class Type {
  constructor(type) {
    this._type = type
  }

  isUndefined() {
    return this._type === t.UNDEFINED
  }

  isNull() {
    return this._type === t.NULL
  }

  isBoolean() {
    return this._type === t.BOOLEAN
  }

  isNumber() {
    return (this._type & 0xff) === t.NUMBER
  }

  isInt32() {
    return (this._type & (0xff | t.INT32)) === (t.NUMBER | t.INT32)
  }

  isUint32() {
    return (this._type & (0xff | t.UINT32)) === (t.NUMBER | t.UINT32)
  }

  isString() {
    return this._type === t.STRING
  }

  isSymbol() {
    return this._type === t.SYMBOL
  }

  isObject() {
    return (this._type & 0xff) === t.OBJECT
  }

  isArray() {
    return this._type === (t.OBJECT | t.ARRAY)
  }

  isArguments() {
    return this._type === (t.OBJECT | t.ARGUMENTS)
  }

  isDate() {
    return this._type === (t.OBJECT | t.DATE)
  }

  isRegExp() {
    return this._type === (t.OBJECT | t.REGEXP)
  }

  isError() {
    return this._type === (t.OBJECT | t.ERROR)
  }

  isPromise() {
    return this._type === (t.OBJECT | t.PROMISE)
  }

  isProxy() {
    return this._type === (t.OBJECT | t.PROXY)
  }

  isGenerator() {
    return this._type === (t.OBJECT | t.GENERATOR)
  }

  isMap() {
    return this._type === (t.OBJECT | t.MAP)
  }

  isSet() {
    return this._type === (t.OBJECT | t.SET)
  }

  isWeakMap() {
    return this._type === (t.OBJECT | t.WEAK_MAP)
  }

  isWeakSet() {
    return this._type === (t.OBJECT | t.WEAK_SET)
  }

  isWeakRef() {
    return this._type === (t.OBJECT | t.WEAK_REF)
  }

  isArrayBuffer() {
    return this._type === (t.OBJECT | t.ARRAYBUFFER)
  }

  isSharedArrayBuffer() {
    return this._type === (t.OBJECT | t.SHAREDARRAYBUFFER)
  }

  isTypedArray() {
    return (this._type & 0xffff) === (t.OBJECT | t.TYPEDARRAY)
  }

  isInt8Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT8ARRAY)
  }

  isUint8Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT8ARRAY)
  }

  isUint8ClampedArray() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT8CLAMPEDARRAY)
  }

  isInt16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT16ARRAY)
  }

  isUint16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT16ARRAY)
  }

  isInt32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT32ARRAY)
  }

  isUint32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT32ARRAY)
  }

  isFloat16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT16ARRAY)
  }

  isFloat32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT32ARRAY)
  }

  isFloat64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT64ARRAY)
  }

  isBigInt64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.BIGINT64ARRAY)
  }

  isBigUint64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.BIGUINT64ARRAY)
  }

  isDataView() {
    return this._type === (t.OBJECT | t.DATAVIEW)
  }

  isModuleNamespace() {
    return this._type === (t.OBJECT | t.MODULE_NAMESPACE)
  }

  isFunction() {
    return (this._type & 0xff) === t.FUNCTION
  }

  isAsyncFunction() {
    return (
      (this._type & (0xff | t.ASYNC_FUNCTION)) ===
      (t.FUNCTION | t.ASYNC_FUNCTION)
    )
  }

  isGeneratorFunction() {
    return (
      (this._type & (0xff | t.GENERATOR_FUNCTION)) ===
      (t.FUNCTION | t.GENERATOR_FUNCTION)
    )
  }

  isExternal() {
    return this._type === t.EXTERNAL
  }

  isBigInt() {
    return this._type === t.BIGINT
  }
}

module.exports = exports = function type(value) {
  switch (typeof value) {
    case 'undefined':
      return new Type(t.UNDEFINED)
    case 'boolean':
      return new Type(t.BOOLEAN)
    case 'number':
      return new Type(
        Number.isSafeInteger(value) ? binding.type(value) : t.NUMBER
      )
    case 'string':
      return new Type(t.STRING)
    case 'symbol':
      return new Type(t.SYMBOL)
    case 'object':
      return new Type(value === null ? t.NULL : binding.type(value))
    case 'function':
      return new Type(binding.type(value))
    case 'bigint':
      return new Type(t.BIGINT)
  }
}

exports.createTag = function createTag(...components) {
  const tag = new Uint32Array(4)
  for (let i = 0; i < 4; i++) tag[i] = components[i] || 0
  return tag
}

exports.addTag = function addTag(object, tag) {
  binding.addTag(object, tag)
}

exports.checkTag = function checkTag(object, tag) {
  return binding.checkTag(object, tag)
}
{
  "name": "bare-type",
  "version": "1.1.0",
  "description": "Cross-realm type predicates for Bare",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-type.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-type/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-type#readme",
  "engines": {
    "bare": ">=1.2.0"
  },
  "devDependencies": {
    "brittle": "^3.4.0",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
module.exports = require.addon()
const path = require('bare-path')
const binding = require('./binding')
const errors = require('./lib/errors')
const URLSearchParams = require('./lib/url-search-params')

const kind = Symbol.for('bare.url.kind')

const isWindows = Bare.platform === 'win32'

class URL {
  static get [kind]() {
    return 0 // Compatibility version
  }

  constructor(input, base, opts = {}) {
    if (arguments.length === 0) throw errors.INVALID_URL()

    input = String(input)

    if (base !== undefined) base = String(base)

    this._components = new Uint32Array(8)

    this._parse(input, base, opts.throw !== false)

    if (this._href) this._params = new URLSearchParams(this.search, this)
  }

  get [kind]() {
    return URL[kind]
  }

  // https://url.spec.whatwg.org/#dom-url-href

  get href() {
    return this._href
  }

  set href(value) {
    this._update(value)

    this._params._parse(this.search)
  }

  // https://url.spec.whatwg.org/#dom-url-protocol

  get protocol() {
    return this._slice(0, this._components[0]) + ':'
  }

  set protocol(value) {
    this._update(this._replace(value.replace(/:+$/, ''), 0, this._components[0]))
  }

  // https://url.spec.whatwg.org/#dom-url-username

  get username() {
    return this._slice(this._components[0] + 3 /* :// */, this._components[1])
  }

  set username(value) {
    if (cannotHaveCredentialsOrPort(this)) {
      return
    }

    if (this.username === '') value += '@'

    this._update(this._replace(value, this._components[0] + 3 /* :// */, this._components[1]))
  }

  // https://url.spec.whatwg.org/#dom-url-password

  get password() {
    return this._href.slice(this._components[1] + 1 /* : */, this._components[2] - 1 /* @ */)
  }

  set password(value) {
    if (cannotHaveCredentialsOrPort(this)) {
      return
    }

    let start = this._components[1] + 1 /* : */
    let end = this._components[2] - 1 /* @ */

    if (this.password === '') {
      value = ':' + value
      start--
    }

    if (this.username === '') {
      value += '@'
      end++
    }

    this._update(this._replace(value, start, end))
  }

  // https://url.spec.whatwg.org/#dom-url-host

  get host() {
    return this._slice(this._components[2], this._components[5])
  }

  set host(value) {
    if (hasOpaquePath(this)) {
      return
    }

    this._update(
      this._replace(value, this._components[2], this._components[value.includes(':') ? 5 : 3])
    )
  }

  // https://url.spec.whatwg.org/#dom-url-hostname

  get hostname() {
    return this._slice(this._components[2], this._components[3])
  }

  set hostname(value) {
    if (hasOpaquePath(this)) {
      return
    }

    this._update(this._replace(value, this._components[2], this._components[3]))
  }

  // https://url.spec.whatwg.org/#dom-url-port

  get port() {
    return this._slice(this._components[3] + 1 /* : */, this._components[5])
  }

  set port(value) {
    if (cannotHaveCredentialsOrPort(this)) {
      return
    }

    let start = this._components[3] + 1 /* : */

    if (this.port === '') {
      value = ':' + value
      start--
    }

    this._update(this._replace(value, start, this._components[5]))
  }

  // https://url.spec.whatwg.org/#dom-url-pathname

  get pathname() {
    return this._slice(this._components[5], this._components[6] - 1 /* ? */)
  }

  set pathname(value) {
    if (hasOpaquePath(this)) {
      return
    }

    if (value[0] !== '/' && value[0] !== '\\') {
      value = '/' + value
    }

    this._update(this._replace(value, this._components[5], this._components[6] - 1 /* ? */))
  }

  // https://url.spec.whatwg.org/#dom-url-search

  get search() {
    return this._slice(this._components[6] - 1 /* ? */, this._components[7] - 1 /* # */)
  }

  set search(value) {
    if (value && value[0] !== '?') value = '?' + value

    this._update(
      this._replace(value, this._components[6] - 1 /* ? */, this._components[7] - 1 /* # */)
    )

    this._params._parse(this.search)
  }

  // https://url.spec.whatwg.org/#dom-url-searchparams

  get searchParams() {
    return this._params
  }

  // https://url.spec.whatwg.org/#dom-url-hash

  get hash() {
    return this._slice(this._components[7] - 1 /* # */)
  }

  set hash(value) {
    if (value && value[0] !== '#') value = '#' + value

    this._update(this._replace(value, this._components[7] - 1 /* # */))
  }

  toString() {
    return this._href
  }

  toJSON() {
    return this._href
  }

  [Symbol.for('bare.inspect')]() {
    return {
      __proto__: { constructor: URL },

      href: this.href,
      protocol: this.protocol,
      username: this.username,
      password: this.password,
      host: this.host,
      hostname: this.hostname,
      port: this.port,
      pathname: this.pathname,
      search: this.search,
      searchParams: this.searchParams,
      hash: this.hash
    }
  }

  _slice(start, end = this._href.length) {
    return this._href.slice(start, end)
  }

  _replace(replacement, start, end = this._href.length) {
    return this._slice(0, start) + replacement + this._slice(end)
  }

  _parse(input, base, shouldThrow) {
    try {
      this._href = binding.parse(
        String(input),
        base ? String(base) : null,
        this._components,
        shouldThrow
      )
    } catch (err) {
      if (err instanceof TypeError) throw err

      throw errors.INVALID_URL(`Invalid URL '${input}'`, input)
    }
  }

  _update(input) {
    try {
      this._parse(input, null, true)
    } catch (err) {
      if (err instanceof TypeError) throw err
    }
  }
}

module.exports = exports = URL

// https://url.spec.whatwg.org/#url-opaque-path
function hasOpaquePath(url) {
  return url.pathname[0] !== '/'
}

// https://url.spec.whatwg.org/#cannot-have-a-username-password-port
function cannotHaveCredentialsOrPort(url) {
  return url.hostname === '' || url.protocol === 'file:'
}

exports.URL = URL
exports.URLSearchParams = URLSearchParams

exports.errors = errors

exports.isURL = function isURL(value) {
  if (value instanceof URL) return true

  return typeof value === 'object' && value !== null && value[kind] === URL[kind]
}

exports.isURLSearchParams = URLSearchParams.isURLSearchParams

// https://url.spec.whatwg.org/#dom-url-parse
exports.parse = function parse(input, base) {
  const url = new URL(input, base, { throw: false })
  return url._href ? url : null
}

// https://url.spec.whatwg.org/#dom-url-canparse
exports.canParse = function canParse(input, base) {
  return binding.canParse(String(input), base ? String(base) : null)
}

exports.fileURLToPath = function fileURLToPath(url) {
  if (typeof url === 'string') {
    url = new URL(url)
  }

  if (url.protocol !== 'file:') {
    throw errors.INVALID_URL_SCHEME('The URL must use the file: protocol')
  }

  if (isWindows) {
    if (/%2f|%5c/i.test(url.pathname)) {
      throw errors.INVALID_FILE_URL_PATH(
        'The file: URL path must not include encoded \\ or / characters'
      )
    }
  } else {
    if (url.hostname) {
      throw errors.INVALID_FILE_URL_HOST("The file: URL host must be 'localhost' or empty")
    }

    if (/%2f/i.test(url.pathname)) {
      throw errors.INVALID_FILE_URL_PATH('The file: URL path must not include encoded / characters')
    }
  }

  if (/%00/i.test(url.pathname)) {
    throw errors.INVALID_FILE_URL_PATH('The file: URL path must not include encoded NUL characters')
  }

  const pathname = path.normalize(decodeURIComponent(url.pathname))

  if (isWindows) {
    if (url.hostname) return '\\\\' + url.hostname + pathname

    const letter = pathname.charCodeAt(1) | 0x20

    if (letter < 0x61 /* a */ || letter > 0x7a /* z */ || pathname.charCodeAt(2) !== 0x3a /* : */) {
      throw errors.INVALID_FILE_URL_PATH('The file: URL path must be absolute')
    }

    return pathname.slice(1)
  }

  return pathname
}

exports.pathToFileURL = function pathToFileURL(pathname) {
  let resolved = path.resolve(pathname)

  if (pathname[pathname.length - 1] === '/') {
    resolved += '/'
  } else if (isWindows && pathname[pathname.length - 1] === '\\') {
    resolved += '\\'
  }

  resolved = resolved
    .replaceAll('%', '%25') // Must be first
    .replaceAll('#', '%23')
    .replaceAll('?', '%3f')
    .replaceAll('\n', '%0a')
    .replaceAll('\r', '%0d')
    .replaceAll('\t', '%09')

  if (!isWindows) {
    resolved = resolved.replaceAll('\\', '%5c')
  }

  return new URL('file:' + resolved)
}

exports.format = function format(parts) {
  const { protocol, auth, host, hostname, port, pathname, search, query, hash, slashes } = parts

  let result = ''

  if (typeof protocol === 'string') {
    result += protocol

    if (protocol[protocol.length - 1] !== ':') {
      result += ':'
    }

    if (slashes === true || /https?|ftp|gopher|file/.test(protocol)) {
      result += '//'
    }
  }

  if (typeof auth === 'string') {
    if (host || hostname) result += auth + '@'
  }

  if (typeof host === 'string') result += host
  else {
    result += hostname

    if (port) result += ':' + port
  }

  if (typeof pathname === 'string' && pathname !== '') {
    if (pathname[0] !== '/') result += '/'
    result += pathname
  }

  if (typeof search === 'string') {
    if (search[0] !== '?') result += '?'
    result += search
  } else if (typeof query === 'object' && query !== null) {
    result += '?' + new URLSearchParams(query)
  }

  if (typeof hash === 'string') {
    if (hash[0] !== '#') result += '#'
    result += hash
  }

  return result
}
module.exports = class URLError extends Error {
  constructor(msg, fn = URLError, code = fn.name) {
    super(`${code}: ${msg}`)

    this.code = code

    if (Error.captureStackTrace) Error.captureStackTrace(this, fn)
  }

  get name() {
    return 'URLError'
  }

  static INVALID_URL(msg, input) {
    const err = new URLError(msg, URLError.INVALID_URL)

    err.input = input

    return err
  }

  static INVALID_URL_SCHEME(msg = 'Invalid URL') {
    return new URLError(msg, URLError.INVALID_URL_SCHEME)
  }

  static INVALID_FILE_URL_HOST(msg = 'Invalid file: URL host') {
    return new URLError(msg, URLError.INVALID_FILE_URL_HOST)
  }

  static INVALID_FILE_URL_PATH(msg = 'Invalid file: URL path') {
    return new URLError(msg, URLError.INVALID_FILE_URL_PATH)
  }
}
const kind = Symbol.for('bare.url.search-params.kind')

class URLSearchParams {
  static _urls = new WeakMap()

  static get [kind]() {
    return 0 // Compatibility version
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-urlsearchparams
  constructor(init, url = null) {
    this._params = new Map()

    if (url) URLSearchParams._urls.set(this, url)

    if (typeof init === 'string') {
      this._parse(init)
    } else if (init) {
      for (const [name, value] of typeof init[Symbol.iterator] === 'function'
        ? init
        : Object.entries(init)) {
        this.append(name, value)
      }
    }
  }

  get [kind]() {
    return URLSearchParams[kind]
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-size
  get size() {
    return this._params.length
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-append
  append(name, value = null) {
    if (value === null) return

    let list = this._params.get(name)

    if (list === undefined) {
      list = []
      this._params.set(name, list)
    }

    list.push(value)

    this._update()
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-delete
  delete(name, value = null) {
    if (value === null) this._params.delete(name)
    else {
      let list = this._params.get(name)

      if (list === undefined) return

      list = list.filter((found) => found !== value)

      if (list.length === 0) this._params.delete(name)
      else this._params.set(name, list)
    }

    this._update()
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-get
  get(name) {
    const list = this._params.get(name)

    if (list === undefined) return null

    return list[0]
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-getall
  getAll(name) {
    const list = this._params.get(name)

    if (list === undefined) return []

    return Array.from(list)
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-has
  has(name, value = null) {
    const list = this._params.get(name)

    if (list === undefined) return false

    if (value === null) return true

    return list.includes(value)
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-set
  set(name, value = null) {
    if (value === null) this._params.delete(name)
    else this._params.set(name, [value])

    this._update()
  }

  toString() {
    return this._serialize()
  }

  toJSON() {
    return [...this]
  }

  *[Symbol.iterator]() {
    for (const [name, values] of this._params) {
      for (const value of values) yield [name, value]
    }
  }

  [Symbol.for('bare.inspect')]() {
    const object = {
      __proto__: { constructor: URLSearchParams }
    }

    for (const [name, values] of this._params) {
      if (values.length === 1) object[name] = values[0]
      else object[name] = values
    }

    return object
  }

  // https://url.spec.whatwg.org/#concept-urlsearchparams-update
  _update() {
    const url = URLSearchParams._urls.get(this)

    if (url === undefined) return

    url.search = this._serialize()
  }

  // https://url.spec.whatwg.org/#concept-urlencoded-parser
  _parse(input) {
    if (input[0] === '?') input = input.substring(1)

    this._params = new Map()

    for (let sequence of input.split('&')) {
      if (sequence.length === 0) continue

      sequence = sequence.replace(/\+/g, ' ')

      let i = sequence.indexOf('=')
      if (i === -1) i = sequence.length

      const name = decodeURIComponent(sequence.substring(0, i))
      const value = decodeURIComponent(sequence.substring(i + 1, sequence.length))

      let list = this._params.get(name)

      if (list === undefined) {
        list = []
        this._params.set(name, list)
      }

      list.push(value)
    }
  }

  // https://url.spec.whatwg.org/#concept-urlencoded-serializer
  _serialize() {
    let output = ''

    for (let [name, values] of this._params) {
      name = encodeURIComponent(name)

      for (const value of values) {
        if (output) output += '&'

        output += name + '=' + encodeURIComponent(value)
      }
    }

    return output
  }
}

module.exports = exports = URLSearchParams

exports.isURLSearchParams = function isURLSearchParams(value) {
  if (value instanceof URLSearchParams) return true

  return typeof value === 'object' && value !== null && value[kind] === URLSearchParams[kind]
}
{
  "name": "bare-url",
  "version": "2.4.5",
  "description": "WHATWG URL implementation for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "global.js",
    "global.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-url.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-url/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-url",
  "dependencies": {
    "bare-path": "^3.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "cmake-bare": "^1.1.6",
    "cmake-fetch": "^1.0.0",
    "lunte": "^1.6.0",
    "prettier": "^3.3.3",
    "prettier-config-holepunch": "^2.0.0"
  }
}
const FACTOR = new Uint16Array(8)

function factor4096 (i, n) {
  while (n > 0) {
    const f = i & 4095
    FACTOR[--n] = f
    i = (i - f) / 4096
  }
  return FACTOR
}

module.exports = class BigSparseArray {
  constructor () {
    this.tiny = new TinyArray()
    this.maxLength = 4096
    this.factor = 1
  }

  set (index, val) {
    if (val !== undefined) {
      while (index >= this.maxLength) {
        this.maxLength *= 4096
        this.factor++
        if (!this.tiny.isEmptyish()) {
          const t = new TinyArray()
          t.set(0, this.tiny)
          this.tiny = t
        }
      }
    }

    const f = factor4096(index, this.factor)
    const last = this.factor - 1

    let tiny = this.tiny
    for (let i = 0; i < last; i++) {
      const next = tiny.get(f[i])
      if (next === undefined) {
        if (val === undefined) return
        tiny = tiny.set(f[i], new TinyArray())
      } else {
        tiny = next
      }
    }

    return tiny.set(f[last], val)
  }

  get (index) {
    if (index >= this.maxLength) return

    const f = factor4096(index, this.factor)
    const last = this.factor - 1

    let tiny = this.tiny
    for (let i = 0; i < last; i++) {
      tiny = tiny.get(f[i])
      if (tiny === undefined) return
    }

    return tiny.get(f[last])
  }
}

class TinyArray {
  constructor () {
    this.s = 0
    this.b = new Array(1)
    this.f = new Uint16Array(1)
  }

  isEmptyish () {
    return this.b.length === 1 && this.b[0] === undefined
  }

  get (i) {
    if (this.s === 12) return this.b[i]
    const f = i >>> this.s
    const r = i & (this.b.length - 1)
    return this.f[r] === f ? this.b[r] : undefined
  }

  set (i, v) {
    while (this.s !== 12) {
      const f = i >>> this.s
      const r = i & (this.b.length - 1)
      const o = this.b[r]

      if (o === undefined || f === this.f[r]) {
        this.b[r] = v
        this.f[r] = f
        return v
      }

      this.grow()
    }

    this.b[i] = v
    return v
  }

  grow () {
    const os = this.s
    const ob = this.b
    const of = this.f

    this.s += 4
    this.b = new Array(this.b.length << 4)
    this.f = this.s === 12 ? null : new Uint8Array(this.b.length)

    const m = this.b.length - 1

    for (let or = 0; or < ob.length; or++) {
      if (ob[or] === undefined) continue

      const i = of[or] << os | or
      const f = i >>> this.s
      const r = i & m

      this.b[r] = ob[or]
      if (this.s !== 12) this.f[r] = f
    }
  }
}
{
  "name": "big-sparse-array",
  "version": "1.0.3",
  "description": "A sparse array optimised for low memory whilst still being fast",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "brittle": "^3.1.1",
    "standard": "^16.0.3"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/big-sparse-array.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/big-sparse-array/issues"
  },
  "homepage": "https://github.com/mafintosh/big-sparse-array"
}
const sodium = require('sodium-universal')
const b4a = require('b4a')
const assert = require('nanoassert')
const { detectLanguage, loadWordlist } = require('./wordlist')

module.exports = {
  generateEntropy,
  generateMnemonic,
  normalizeMnemonic,
  validateMnemonic,
  mnemonicToEntropy,
  mnemonicToSeed,
  entropyToMnemonic
}

function generateMnemonic ({ entropy = generateEntropy(), language = 'english' } = {}) {
  const wordlist = loadWordlist(language)
  const extended = computeCheckSum(entropy)

  const words = []

  for (const index of uint11Reader(extended)) {
    words.push(wordlist[index])
  }

  const delimiter = language === 'japanese' ? '\u3000' : ' '

  return words.join(delimiter).trim()
}

function entropyToMnemonic (entropy, { language = 'english' } = {}) {
  return generateMnemonic({ entropy, language })
}

function mnemonicToEntropy (mnemonic) {
  const words = mnemonic.replace(/\u3000/g, ' ').trim().split(' ')
  const language = detectLanguage(words)

  if (!language) {
    throw new Error('Language not recognised')
  }

  if (words.length % 3 !== 0) {
    throw new Error('Invalid length')
  }

  const wordlist = loadWordlist(language)

  const indexes = []
  for (const word of words) {
    const index = wordlist.indexOf(word)
    if (index === -1) {
      throw new Error('Bad word')
    }

    indexes.push(index)
  }

  const bits = words.length * 11
  const len = (bits * 32 / 33) >> 3

  const extended = b4a.alloc(Math.ceil(bits / 8))
  const entropy = extended.subarray(0, len)

  uint11Writer(extended, indexes)

  if (!b4a.equals(extended, computeCheckSum(entropy))) {
    throw new Error('Invalid checksum')
  }

  return entropy
}

function normalizeMnemonic (mnemonic) {
  return mnemonic.trim().replace(/\u3000/, ' ').split(/\s+/).map(c => c.toLowerCase()).join(' ')
}

async function mnemonicToSeed (mnemonic, passphrase = '') {
  mnemonic = normalizeMnemonic(mnemonic)

  if (!validateMnemonic(mnemonic)) {
    throw new Error('Invalid mnemonic')
  }

  const input = b4a.from(mnemonic)
  const salt = b4a.from('mnemonic' + passphrase)

  const output = b4a.alloc(64)

  await sodium.extension_pbkdf2_sha512_async(
    output,
    input,
    salt,
    2048,
    64
  )

  return output
}

function validateMnemonic (mnemonic) {
  try {
    mnemonicToEntropy(mnemonic)
  } catch (e) {
    return false
  }
  return true
}

function sha256 (data, output = b4a.alloc(32)) {
  sodium.crypto_hash_sha256(output, data)
  return output
}

function computeCheckSum (seed) {
  assert((seed.byteLength & 4) === 0, 'seed must be a multiple of 4 bytes')

  const len = seed.byteLength
  const cklen = len >> 2 // cksum bits
  const total = len + Math.ceil(cklen / 8)

  const output = b4a.alloc(len + 32)
  output.set(seed)

  const entropy = output.subarray(0, len)
  const cksum = output.subarray(len)

  sha256(entropy, cksum)

  // only append cklen bits
  output[total - 1] &= (0xff ^ (0xff >> cklen))

  return output.subarray(0, total)
}

function generateEntropy (length = 32) {
  const seed = b4a.alloc(length)
  sodium.randombytes_buf(seed)

  return seed
}

function * uint11Reader (state) {
  yield * uintReader(state, 11)
}

function uint11Writer (buf, uints) {
  return uintWriter(buf, uints, 11)
}

function * uintReader (buffer, width) {
  const MASK = (2 << (width - 1)) - 1

  let pos = 0
  let value = 0

  while (true) {
    const offset = pos >> 3 // byte offset

    if (offset >= buffer.byteLength) {
      return value & MASK
    }

    const height = width - (pos % width)
    const leftover = (offset + 1) * 8 - pos

    value += shift(buffer[offset], height - leftover)

    pos += Math.min(height, leftover)
    if (pos % width) continue

    yield value & MASK

    value = 0
  }
}

function uintWriter (buffer, uints, width) {
  let pos = 0

  while (true) {
    const offset = pos >> 3 // byte offset

    const i = Math.floor(pos / width)
    if (i >= uints.length) break

    if (offset >= buffer.length) {
      throw new Error('Failed to encode uints')
    }

    const rem = 8 - pos % 8
    const height = (i + 1) * width - pos

    const value = shift(uints[i], rem - height)

    buffer[offset] += mask(value, rem)

    pos += Math.min(rem, height)
  }

  return buffer
}

// when n is positive, shift left n bits
// when n is negative, shift right -n bits
function shift (val, n) {
  if (n === 0) return val
  if (n > 0) return val << n

  return val >> (-1 * n)
}

function mask (val, bits) {
  if (bits < 32) return val & ((1 << bits) - 1)
  return val % (2 ** bits)
}
{
  "name": "bip39-mnemonic",
  "version": "2.5.0",
  "description": "BIP39 mnemonic for key derivation schemes",
  "main": "index.js",
  "scripts": {
    "generate-wordlist": "node scripts/generate-wordlist.js",
    "test": "standard && brittle test/*.js"
  },
  "author": "Holepunch Inc",
  "license": "Apache-2.0",
  "devDependencies": {
    "brittle": "^3.4.0",
    "standard": "^17.1.0"
  },
  "dependencies": {
    "b4a": "^1.6.6",
    "nanoassert": "^2.0.0",
    "sodium-universal": "^5.0.1"
  },
  "files": [
    "index.js",
    "wordlist"
  ],
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bip39.git"
  },
  "bugs": {
    "url": "https://github.com/holepunchto/bip39/issues"
  },
  "homepage": "https://github.com/holepunchto/bip39#readme"
}
["的","一","是","在","不","了","有","和","人","这","中","大","为","上","个","国","我","以","要","他","时","来","用","们","生","到","作","地","于","出","就","分","对","成","会","可","主","发","年","动","同","工","也","能","下","过","子","说","产","种","面","而","方","后","多","定","行","学","法","所","民","得","经","十","三","之","进","着","等","部","度","家","电","力","里","如","水","化","高","自","二","理","起","小","物","现","实","加","量","都","两","体","制","机","当","使","点","从","业","本","去","把","性","好","应","开","它","合","还","因","由","其","些","然","前","外","天","政","四","日","那","社","义","事","平","形","相","全","表","间","样","与","关","各","重","新","线","内","数","正","心","反","你","明","看","原","又","么","利","比","或","但","质","气","第","向","道","命","此","变","条","只","没","结","解","问","意","建","月","公","无","系","军","很","情","者","最","立","代","想","已","通","并","提","直","题","党","程","展","五","果","料","象","员","革","位","入","常","文","总","次","品","式","活","设","及","管","特","件","长","求","老","头","基","资","边","流","路","级","少","图","山","统","接","知","较","将","组","见","计","别","她","手","角","期","根","论","运","农","指","几","九","区","强","放","决","西","被","干","做","必","战","先","回","则","任","取","据","处","队","南","给","色","光","门","即","保","治","北","造","百","规","热","领","七","海","口","东","导","器","压","志","世","金","增","争","济","阶","油","思","术","极","交","受","联","什","认","六","共","权","收","证","改","清","美","再","采","转","更","单","风","切","打","白","教","速","花","带","安","场","身","车","例","真","务","具","万","每","目","至","达","走","积","示","议","声","报","斗","完","类","八","离","华","名","确","才","科","张","信","马","节","话","米","整","空","元","况","今","集","温","传","土","许","步","群","广","石","记","需","段","研","界","拉","林","律","叫","且","究","观","越","织","装","影","算","低","持","音","众","书","布","复","容","儿","须","际","商","非","验","连","断","深","难","近","矿","千","周","委","素","技","备","半","办","青","省","列","习","响","约","支","般","史","感","劳","便","团","往","酸","历","市","克","何","除","消","构","府","称","太","准","精","值","号","率","族","维","划","选","标","写","存","候","毛","亲","快","效","斯","院","查","江","型","眼","王","按","格","养","易","置","派","层","片","始","却","专","状","育","厂","京","识","适","属","圆","包","火","住","调","满","县","局","照","参","红","细","引","听","该","铁","价","严","首","底","液","官","德","随","病","苏","失","尔","死","讲","配","女","黄","推","显","谈","罪","神","艺","呢","席","含","企","望","密","批","营","项","防","举","球","英","氧","势","告","李","台","落","木","帮","轮","破","亚","师","围","注","远","字","材","排","供","河","态","封","另","施","减","树","溶","怎","止","案","言","士","均","武","固","叶","鱼","波","视","仅","费","紧","爱","左","章","早","朝","害","续","轻","服","试","食","充","兵","源","判","护","司","足","某","练","差","致","板","田","降","黑","犯","负","击","范","继","兴","似","余","坚","曲","输","修","故","城","夫","够","送","笔","船","占","右","财","吃","富","春","职","觉","汉","画","功","巴","跟","虽","杂","飞","检","吸","助","升","阳","互","初","创","抗","考","投","坏","策","古","径","换","未","跑","留","钢","曾","端","责","站","简","述","钱","副","尽","帝","射","草","冲","承","独","令","限","阿","宣","环","双","请","超","微","让","控","州","良","轴","找","否","纪","益","依","优","顶","础","载","倒","房","突","坐","粉","敌","略","客","袁","冷","胜","绝","析","块","剂","测","丝","协","诉","念","陈","仍","罗","盐","友","洋","错","苦","夜","刑","移","频","逐","靠","混","母","短","皮","终","聚","汽","村","云","哪","既","距","卫","停","烈","央","察","烧","迅","境","若","印","洲","刻","括","激","孔","搞","甚","室","待","核","校","散","侵","吧","甲","游","久","菜","味","旧","模","湖","货","损","预","阻","毫","普","稳","乙","妈","植","息","扩","银","语","挥","酒","守","拿","序","纸","医","缺","雨","吗","针","刘","啊","急","唱","误","训","愿","审","附","获","茶","鲜","粮","斤","孩","脱","硫","肥","善","龙","演","父","渐","血","欢","械","掌","歌","沙","刚","攻","谓","盾","讨","晚","粒","乱","燃","矛","乎","杀","药","宁","鲁","贵","钟","煤","读","班","伯","香","介","迫","句","丰","培","握","兰","担","弦","蛋","沉","假","穿","执","答","乐","谁","顺","烟","缩","征","脸","喜","松","脚","困","异","免","背","星","福","买","染","井","概","慢","怕","磁","倍","祖","皇","促","静","补","评","翻","肉","践","尼","衣","宽","扬","棉","希","伤","操","垂","秋","宜","氢","套","督","振","架","亮","末","宪","庆","编","牛","触","映","雷","销","诗","座","居","抓","裂","胞","呼","娘","景","威","绿","晶","厚","盟","衡","鸡","孙","延","危","胶","屋","乡","临","陆","顾","掉","呀","灯","岁","措","束","耐","剧","玉","赵","跳","哥","季","课","凯","胡","额","款","绍","卷","齐","伟","蒸","殖","永","宗","苗","川","炉","岩","弱","零","杨","奏","沿","露","杆","探","滑","镇","饭","浓","航","怀","赶","库","夺","伊","灵","税","途","灭","赛","归","召","鼓","播","盘","裁","险","康","唯","录","菌","纯","借","糖","盖","横","符","私","努","堂","域","枪","润","幅","哈","竟","熟","虫","泽","脑","壤","碳","欧","遍","侧","寨","敢","彻","虑","斜","薄","庭","纳","弹","饲","伸","折","麦","湿","暗","荷","瓦","塞","床","筑","恶","户","访","塔","奇","透","梁","刀","旋","迹","卡","氯","遇","份","毒","泥","退","洗","摆","灰","彩","卖","耗","夏","择","忙","铜","献","硬","予","繁","圈","雪","函","亦","抽","篇","阵","阴","丁","尺","追","堆","雄","迎","泛","爸","楼","避","谋","吨","野","猪","旗","累","偏","典","馆","索","秦","脂","潮","爷","豆","忽","托","惊","塑","遗","愈","朱","替","纤","粗","倾","尚","痛","楚","谢","奋","购","磨","君","池","旁","碎","骨","监","捕","弟","暴","割","贯","殊","释","词","亡","壁","顿","宝","午","尘","闻","揭","炮","残","冬","桥","妇","警","综","招","吴","付","浮","遭","徐","您","摇","谷","赞","箱","隔","订","男","吹","园","纷","唐","败","宋","玻","巨","耕","坦","荣","闭","湾","键","凡","驻","锅","救","恩","剥","凝","碱","齿","截","炼","麻","纺","禁","废","盛","版","缓","净","睛","昌","婚","涉","筒","嘴","插","岸","朗","庄","街","藏","姑","贸","腐","奴","啦","惯","乘","伙","恢","匀","纱","扎","辩","耳","彪","臣","亿","璃","抵","脉","秀","萨","俄","网","舞","店","喷","纵","寸","汗","挂","洪","贺","闪","柬","爆","烯","津","稻","墙","软","勇","像","滚","厘","蒙","芳","肯","坡","柱","荡","腿","仪","旅","尾","轧","冰","贡","登","黎","削","钻","勒","逃","障","氨","郭","峰","币","港","伏","轨","亩","毕","擦","莫","刺","浪","秘","援","株","健","售","股","岛","甘","泡","睡","童","铸","汤","阀","休","汇","舍","牧","绕","炸","哲","磷","绩","朋","淡","尖","启","陷","柴","呈","徒","颜","泪","稍","忘","泵","蓝","拖","洞","授","镜","辛","壮","锋","贫","虚","弯","摩","泰","幼","廷","尊","窗","纲","弄","隶","疑","氏","宫","姐","震","瑞","怪","尤","琴","循","描","膜","违","夹","腰","缘","珠","穷","森","枝","竹","沟","催","绳","忆","邦","剩","幸","浆","栏","拥","牙","贮","礼","滤","钠","纹","罢","拍","咱","喊","袖","埃","勤","罚","焦","潜","伍","墨","欲","缝","姓","刊","饱","仿","奖","铝","鬼","丽","跨","默","挖","链","扫","喝","袋","炭","污","幕","诸","弧","励","梅","奶","洁","灾","舟","鉴","苯","讼","抱","毁","懂","寒","智","埔","寄","届","跃","渡","挑","丹","艰","贝","碰","拔","爹","戴","码","梦","芽","熔","赤","渔","哭","敬","颗","奔","铅","仲","虎","稀","妹","乏","珍","申","桌","遵","允","隆","螺","仓","魏","锐","晓","氮","兼","隐","碍","赫","拨","忠","肃","缸","牵","抢","博","巧","壳","兄","杜","讯","诚","碧","祥","柯","页","巡","矩","悲","灌","龄","伦","票","寻","桂","铺","圣","恐","恰","郑","趣","抬","荒","腾","贴","柔","滴","猛","阔","辆","妻","填","撤","储","签","闹","扰","紫","砂","递","戏","吊","陶","伐","喂","疗","瓶","婆","抚","臂","摸","忍","虾","蜡","邻","胸","巩","挤","偶","弃","槽","劲","乳","邓","吉","仁","烂","砖","租","乌","舰","伴","瓜","浅","丙","暂","燥","橡","柳","迷","暖","牌","秧","胆","详","簧","踏","瓷","谱","呆","宾","糊","洛","辉","愤","竞","隙","怒","粘","乃","绪","肩","籍","敏","涂","熙","皆","侦","悬","掘","享","纠","醒","狂","锁","淀","恨","牲","霸","爬","赏","逆","玩","陵","祝","秒","浙","貌","役","彼","悉","鸭","趋","凤","晨","畜","辈","秩","卵","署","梯","炎","滩","棋","驱","筛","峡","冒","啥","寿","译","浸","泉","帽","迟","硅","疆","贷","漏","稿","冠","嫩","胁","芯","牢","叛","蚀","奥","鸣","岭","羊","凭","串","塘","绘","酵","融","盆","锡","庙","筹","冻","辅","摄","袭","筋","拒","僚","旱","钾","鸟","漆","沈","眉","疏","添","棒","穗","硝","韩","逼","扭","侨","凉","挺","碗","栽","炒","杯","患","馏","劝","豪","辽","勃","鸿","旦","吏","拜","狗","埋","辊","掩","饮","搬","骂","辞","勾","扣","估","蒋","绒","雾","丈","朵","姆","拟","宇","辑","陕","雕","偿","蓄","崇","剪","倡","厅","咬","驶","薯","刷","斥","番","赋","奉","佛","浇","漫","曼","扇","钙","桃","扶","仔","返","俗","亏","腔","鞋","棱","覆","框","悄","叔","撞","骗","勘","旺","沸","孤","吐","孟","渠","屈","疾","妙","惜","仰","狠","胀","谐","抛","霉","桑","岗","嘛","衰","盗","渗","脏","赖","涌","甜","曹","阅","肌","哩","厉","烃","纬","毅","昨","伪","症","煮","叹","钉","搭","茎","笼","酷","偷","弓","锥","恒","杰","坑","鼻","翼","纶","叙","狱","逮","罐","络","棚","抑","膨","蔬","寺","骤","穆","冶","枯","册","尸","凸","绅","坯","牺","焰","轰","欣","晋","瘦","御","锭","锦","丧","旬","锻","垄","搜","扑","邀","亭","酯","迈","舒","脆","酶","闲","忧","酚","顽","羽","涨","卸","仗","陪","辟","惩","杭","姚","肚","捉","飘","漂","昆","欺","吾","郎","烷","汁","呵","饰","萧","雅","邮","迁","燕","撒","姻","赴","宴","烦","债","帐","斑","铃","旨","醇","董","饼","雏","姿","拌","傅","腹","妥","揉","贤","拆","歪","葡","胺","丢","浩","徽","昂","垫","挡","览","贪","慰","缴","汪","慌","冯","诺","姜","谊","凶","劣","诬","耀","昏","躺","盈","骑","乔","溪","丛","卢","抹","闷","咨","刮","驾","缆","悟","摘","铒","掷","颇","幻","柄","惠","惨","佳","仇","腊","窝","涤","剑","瞧","堡","泼","葱","罩","霍","捞","胎","苍","滨","俩","捅","湘","砍","霞","邵","萄","疯","淮","遂","熊","粪","烘","宿","档","戈","驳","嫂","裕","徙","箭","捐","肠","撑","晒","辨","殿","莲","摊","搅","酱","屏","疫","哀","蔡","堵","沫","皱","畅","叠","阁","莱","敲","辖","钩","痕","坝","巷","饿","祸","丘","玄","溜","曰","逻","彭","尝","卿","妨","艇","吞","韦","怨","矮","歇"]["的","一","是","在","不","了","有","和","人","這","中","大","為","上","個","國","我","以","要","他","時","來","用","們","生","到","作","地","於","出","就","分","對","成","會","可","主","發","年","動","同","工","也","能","下","過","子","說","產","種","面","而","方","後","多","定","行","學","法","所","民","得","經","十","三","之","進","著","等","部","度","家","電","力","裡","如","水","化","高","自","二","理","起","小","物","現","實","加","量","都","兩","體","制","機","當","使","點","從","業","本","去","把","性","好","應","開","它","合","還","因","由","其","些","然","前","外","天","政","四","日","那","社","義","事","平","形","相","全","表","間","樣","與","關","各","重","新","線","內","數","正","心","反","你","明","看","原","又","麼","利","比","或","但","質","氣","第","向","道","命","此","變","條","只","沒","結","解","問","意","建","月","公","無","系","軍","很","情","者","最","立","代","想","已","通","並","提","直","題","黨","程","展","五","果","料","象","員","革","位","入","常","文","總","次","品","式","活","設","及","管","特","件","長","求","老","頭","基","資","邊","流","路","級","少","圖","山","統","接","知","較","將","組","見","計","別","她","手","角","期","根","論","運","農","指","幾","九","區","強","放","決","西","被","幹","做","必","戰","先","回","則","任","取","據","處","隊","南","給","色","光","門","即","保","治","北","造","百","規","熱","領","七","海","口","東","導","器","壓","志","世","金","增","爭","濟","階","油","思","術","極","交","受","聯","什","認","六","共","權","收","證","改","清","美","再","採","轉","更","單","風","切","打","白","教","速","花","帶","安","場","身","車","例","真","務","具","萬","每","目","至","達","走","積","示","議","聲","報","鬥","完","類","八","離","華","名","確","才","科","張","信","馬","節","話","米","整","空","元","況","今","集","溫","傳","土","許","步","群","廣","石","記","需","段","研","界","拉","林","律","叫","且","究","觀","越","織","裝","影","算","低","持","音","眾","書","布","复","容","兒","須","際","商","非","驗","連","斷","深","難","近","礦","千","週","委","素","技","備","半","辦","青","省","列","習","響","約","支","般","史","感","勞","便","團","往","酸","歷","市","克","何","除","消","構","府","稱","太","準","精","值","號","率","族","維","劃","選","標","寫","存","候","毛","親","快","效","斯","院","查","江","型","眼","王","按","格","養","易","置","派","層","片","始","卻","專","狀","育","廠","京","識","適","屬","圓","包","火","住","調","滿","縣","局","照","參","紅","細","引","聽","該","鐵","價","嚴","首","底","液","官","德","隨","病","蘇","失","爾","死","講","配","女","黃","推","顯","談","罪","神","藝","呢","席","含","企","望","密","批","營","項","防","舉","球","英","氧","勢","告","李","台","落","木","幫","輪","破","亞","師","圍","注","遠","字","材","排","供","河","態","封","另","施","減","樹","溶","怎","止","案","言","士","均","武","固","葉","魚","波","視","僅","費","緊","愛","左","章","早","朝","害","續","輕","服","試","食","充","兵","源","判","護","司","足","某","練","差","致","板","田","降","黑","犯","負","擊","范","繼","興","似","餘","堅","曲","輸","修","故","城","夫","夠","送","筆","船","佔","右","財","吃","富","春","職","覺","漢","畫","功","巴","跟","雖","雜","飛","檢","吸","助","昇","陽","互","初","創","抗","考","投","壞","策","古","徑","換","未","跑","留","鋼","曾","端","責","站","簡","述","錢","副","盡","帝","射","草","衝","承","獨","令","限","阿","宣","環","雙","請","超","微","讓","控","州","良","軸","找","否","紀","益","依","優","頂","礎","載","倒","房","突","坐","粉","敵","略","客","袁","冷","勝","絕","析","塊","劑","測","絲","協","訴","念","陳","仍","羅","鹽","友","洋","錯","苦","夜","刑","移","頻","逐","靠","混","母","短","皮","終","聚","汽","村","雲","哪","既","距","衛","停","烈","央","察","燒","迅","境","若","印","洲","刻","括","激","孔","搞","甚","室","待","核","校","散","侵","吧","甲","遊","久","菜","味","舊","模","湖","貨","損","預","阻","毫","普","穩","乙","媽","植","息","擴","銀","語","揮","酒","守","拿","序","紙","醫","缺","雨","嗎","針","劉","啊","急","唱","誤","訓","願","審","附","獲","茶","鮮","糧","斤","孩","脫","硫","肥","善","龍","演","父","漸","血","歡","械","掌","歌","沙","剛","攻","謂","盾","討","晚","粒","亂","燃","矛","乎","殺","藥","寧","魯","貴","鐘","煤","讀","班","伯","香","介","迫","句","豐","培","握","蘭","擔","弦","蛋","沉","假","穿","執","答","樂","誰","順","煙","縮","徵","臉","喜","松","腳","困","異","免","背","星","福","買","染","井","概","慢","怕","磁","倍","祖","皇","促","靜","補","評","翻","肉","踐","尼","衣","寬","揚","棉","希","傷","操","垂","秋","宜","氫","套","督","振","架","亮","末","憲","慶","編","牛","觸","映","雷","銷","詩","座","居","抓","裂","胞","呼","娘","景","威","綠","晶","厚","盟","衡","雞","孫","延","危","膠","屋","鄉","臨","陸","顧","掉","呀","燈","歲","措","束","耐","劇","玉","趙","跳","哥","季","課","凱","胡","額","款","紹","卷","齊","偉","蒸","殖","永","宗","苗","川","爐","岩","弱","零","楊","奏","沿","露","桿","探","滑","鎮","飯","濃","航","懷","趕","庫","奪","伊","靈","稅","途","滅","賽","歸","召","鼓","播","盤","裁","險","康","唯","錄","菌","純","借","糖","蓋","橫","符","私","努","堂","域","槍","潤","幅","哈","竟","熟","蟲","澤","腦","壤","碳","歐","遍","側","寨","敢","徹","慮","斜","薄","庭","納","彈","飼","伸","折","麥","濕","暗","荷","瓦","塞","床","築","惡","戶","訪","塔","奇","透","梁","刀","旋","跡","卡","氯","遇","份","毒","泥","退","洗","擺","灰","彩","賣","耗","夏","擇","忙","銅","獻","硬","予","繁","圈","雪","函","亦","抽","篇","陣","陰","丁","尺","追","堆","雄","迎","泛","爸","樓","避","謀","噸","野","豬","旗","累","偏","典","館","索","秦","脂","潮","爺","豆","忽","托","驚","塑","遺","愈","朱","替","纖","粗","傾","尚","痛","楚","謝","奮","購","磨","君","池","旁","碎","骨","監","捕","弟","暴","割","貫","殊","釋","詞","亡","壁","頓","寶","午","塵","聞","揭","炮","殘","冬","橋","婦","警","綜","招","吳","付","浮","遭","徐","您","搖","谷","贊","箱","隔","訂","男","吹","園","紛","唐","敗","宋","玻","巨","耕","坦","榮","閉","灣","鍵","凡","駐","鍋","救","恩","剝","凝","鹼","齒","截","煉","麻","紡","禁","廢","盛","版","緩","淨","睛","昌","婚","涉","筒","嘴","插","岸","朗","莊","街","藏","姑","貿","腐","奴","啦","慣","乘","夥","恢","勻","紗","扎","辯","耳","彪","臣","億","璃","抵","脈","秀","薩","俄","網","舞","店","噴","縱","寸","汗","掛","洪","賀","閃","柬","爆","烯","津","稻","牆","軟","勇","像","滾","厘","蒙","芳","肯","坡","柱","盪","腿","儀","旅","尾","軋","冰","貢","登","黎","削","鑽","勒","逃","障","氨","郭","峰","幣","港","伏","軌","畝","畢","擦","莫","刺","浪","秘","援","株","健","售","股","島","甘","泡","睡","童","鑄","湯","閥","休","匯","舍","牧","繞","炸","哲","磷","績","朋","淡","尖","啟","陷","柴","呈","徒","顏","淚","稍","忘","泵","藍","拖","洞","授","鏡","辛","壯","鋒","貧","虛","彎","摩","泰","幼","廷","尊","窗","綱","弄","隸","疑","氏","宮","姐","震","瑞","怪","尤","琴","循","描","膜","違","夾","腰","緣","珠","窮","森","枝","竹","溝","催","繩","憶","邦","剩","幸","漿","欄","擁","牙","貯","禮","濾","鈉","紋","罷","拍","咱","喊","袖","埃","勤","罰","焦","潛","伍","墨","欲","縫","姓","刊","飽","仿","獎","鋁","鬼","麗","跨","默","挖","鏈","掃","喝","袋","炭","污","幕","諸","弧","勵","梅","奶","潔","災","舟","鑑","苯","訟","抱","毀","懂","寒","智","埔","寄","屆","躍","渡","挑","丹","艱","貝","碰","拔","爹","戴","碼","夢","芽","熔","赤","漁","哭","敬","顆","奔","鉛","仲","虎","稀","妹","乏","珍","申","桌","遵","允","隆","螺","倉","魏","銳","曉","氮","兼","隱","礙","赫","撥","忠","肅","缸","牽","搶","博","巧","殼","兄","杜","訊","誠","碧","祥","柯","頁","巡","矩","悲","灌","齡","倫","票","尋","桂","鋪","聖","恐","恰","鄭","趣","抬","荒","騰","貼","柔","滴","猛","闊","輛","妻","填","撤","儲","簽","鬧","擾","紫","砂","遞","戲","吊","陶","伐","餵","療","瓶","婆","撫","臂","摸","忍","蝦","蠟","鄰","胸","鞏","擠","偶","棄","槽","勁","乳","鄧","吉","仁","爛","磚","租","烏","艦","伴","瓜","淺","丙","暫","燥","橡","柳","迷","暖","牌","秧","膽","詳","簧","踏","瓷","譜","呆","賓","糊","洛","輝","憤","競","隙","怒","粘","乃","緒","肩","籍","敏","塗","熙","皆","偵","懸","掘","享","糾","醒","狂","鎖","淀","恨","牲","霸","爬","賞","逆","玩","陵","祝","秒","浙","貌","役","彼","悉","鴨","趨","鳳","晨","畜","輩","秩","卵","署","梯","炎","灘","棋","驅","篩","峽","冒","啥","壽","譯","浸","泉","帽","遲","矽","疆","貸","漏","稿","冠","嫩","脅","芯","牢","叛","蝕","奧","鳴","嶺","羊","憑","串","塘","繪","酵","融","盆","錫","廟","籌","凍","輔","攝","襲","筋","拒","僚","旱","鉀","鳥","漆","沈","眉","疏","添","棒","穗","硝","韓","逼","扭","僑","涼","挺","碗","栽","炒","杯","患","餾","勸","豪","遼","勃","鴻","旦","吏","拜","狗","埋","輥","掩","飲","搬","罵","辭","勾","扣","估","蔣","絨","霧","丈","朵","姆","擬","宇","輯","陝","雕","償","蓄","崇","剪","倡","廳","咬","駛","薯","刷","斥","番","賦","奉","佛","澆","漫","曼","扇","鈣","桃","扶","仔","返","俗","虧","腔","鞋","棱","覆","框","悄","叔","撞","騙","勘","旺","沸","孤","吐","孟","渠","屈","疾","妙","惜","仰","狠","脹","諧","拋","黴","桑","崗","嘛","衰","盜","滲","臟","賴","湧","甜","曹","閱","肌","哩","厲","烴","緯","毅","昨","偽","症","煮","嘆","釘","搭","莖","籠","酷","偷","弓","錐","恆","傑","坑","鼻","翼","綸","敘","獄","逮","罐","絡","棚","抑","膨","蔬","寺","驟","穆","冶","枯","冊","屍","凸","紳","坯","犧","焰","轟","欣","晉","瘦","禦","錠","錦","喪","旬","鍛","壟","搜","撲","邀","亭","酯","邁","舒","脆","酶","閒","憂","酚","頑","羽","漲","卸","仗","陪","闢","懲","杭","姚","肚","捉","飄","漂","昆","欺","吾","郎","烷","汁","呵","飾","蕭","雅","郵","遷","燕","撒","姻","赴","宴","煩","債","帳","斑","鈴","旨","醇","董","餅","雛","姿","拌","傅","腹","妥","揉","賢","拆","歪","葡","胺","丟","浩","徽","昂","墊","擋","覽","貪","慰","繳","汪","慌","馮","諾","姜","誼","兇","劣","誣","耀","昏","躺","盈","騎","喬","溪","叢","盧","抹","悶","諮","刮","駕","纜","悟","摘","鉺","擲","頗","幻","柄","惠","慘","佳","仇","臘","窩","滌","劍","瞧","堡","潑","蔥","罩","霍","撈","胎","蒼","濱","倆","捅","湘","砍","霞","邵","萄","瘋","淮","遂","熊","糞","烘","宿","檔","戈","駁","嫂","裕","徙","箭","捐","腸","撐","曬","辨","殿","蓮","攤","攪","醬","屏","疫","哀","蔡","堵","沫","皺","暢","疊","閣","萊","敲","轄","鉤","痕","壩","巷","餓","禍","丘","玄","溜","曰","邏","彭","嘗","卿","妨","艇","吞","韋","怨","矮","歇"]["abdikace","abeceda","adresa","agrese","akce","aktovka","alej","alkohol","amputace","ananas","andulka","anekdota","anketa","antika","anulovat","archa","arogance","asfalt","asistent","aspirace","astma","astronom","atlas","atletika","atol","autobus","azyl","babka","bachor","bacil","baculka","badatel","bageta","bagr","bahno","bakterie","balada","baletka","balkon","balonek","balvan","balza","bambus","bankomat","barbar","baret","barman","baroko","barva","baterka","batoh","bavlna","bazalka","bazilika","bazuka","bedna","beran","beseda","bestie","beton","bezinka","bezmoc","beztak","bicykl","bidlo","biftek","bikiny","bilance","biograf","biolog","bitva","bizon","blahobyt","blatouch","blecha","bledule","blesk","blikat","blizna","blokovat","bloudit","blud","bobek","bobr","bodlina","bodnout","bohatost","bojkot","bojovat","bokorys","bolest","borec","borovice","bota","boubel","bouchat","bouda","boule","bourat","boxer","bradavka","brambora","branka","bratr","brepta","briketa","brko","brloh","bronz","broskev","brunetka","brusinka","brzda","brzy","bublina","bubnovat","buchta","buditel","budka","budova","bufet","bujarost","bukvice","buldok","bulva","bunda","bunkr","burza","butik","buvol","buzola","bydlet","bylina","bytovka","bzukot","capart","carevna","cedr","cedule","cejch","cejn","cela","celer","celkem","celnice","cenina","cennost","cenovka","centrum","cenzor","cestopis","cetka","chalupa","chapadlo","charita","chata","chechtat","chemie","chichot","chirurg","chlad","chleba","chlubit","chmel","chmura","chobot","chochol","chodba","cholera","chomout","chopit","choroba","chov","chrapot","chrlit","chrt","chrup","chtivost","chudina","chutnat","chvat","chvilka","chvost","chyba","chystat","chytit","cibule","cigareta","cihelna","cihla","cinkot","cirkus","cisterna","citace","citrus","cizinec","cizost","clona","cokoliv","couvat","ctitel","ctnost","cudnost","cuketa","cukr","cupot","cvaknout","cval","cvik","cvrkot","cyklista","daleko","dareba","datel","datum","dcera","debata","dechovka","decibel","deficit","deflace","dekl","dekret","demokrat","deprese","derby","deska","detektiv","dikobraz","diktovat","dioda","diplom","disk","displej","divadlo","divoch","dlaha","dlouho","dluhopis","dnes","dobro","dobytek","docent","dochutit","dodnes","dohled","dohoda","dohra","dojem","dojnice","doklad","dokola","doktor","dokument","dolar","doleva","dolina","doma","dominant","domluvit","domov","donutit","dopad","dopis","doplnit","doposud","doprovod","dopustit","dorazit","dorost","dort","dosah","doslov","dostatek","dosud","dosyta","dotaz","dotek","dotknout","doufat","doutnat","dovozce","dozadu","doznat","dozorce","drahota","drak","dramatik","dravec","draze","drdol","drobnost","drogerie","drozd","drsnost","drtit","drzost","duben","duchovno","dudek","duha","duhovka","dusit","dusno","dutost","dvojice","dvorec","dynamit","ekolog","ekonomie","elektron","elipsa","email","emise","emoce","empatie","epizoda","epocha","epopej","epos","esej","esence","eskorta","eskymo","etiketa","euforie","evoluce","exekuce","exkurze","expedice","exploze","export","extrakt","facka","fajfka","fakulta","fanatik","fantazie","farmacie","favorit","fazole","federace","fejeton","fenka","fialka","figurant","filozof","filtr","finance","finta","fixace","fjord","flanel","flirt","flotila","fond","fosfor","fotbal","fotka","foton","frakce","freska","fronta","fukar","funkce","fyzika","galeje","garant","genetika","geolog","gilotina","glazura","glejt","golem","golfista","gotika","graf","gramofon","granule","grep","gril","grog","groteska","guma","hadice","hadr","hala","halenka","hanba","hanopis","harfa","harpuna","havran","hebkost","hejkal","hejno","hejtman","hektar","helma","hematom","herec","herna","heslo","hezky","historik","hladovka","hlasivky","hlava","hledat","hlen","hlodavec","hloh","hloupost","hltat","hlubina","hluchota","hmat","hmota","hmyz","hnis","hnojivo","hnout","hoblina","hoboj","hoch","hodiny","hodlat","hodnota","hodovat","hojnost","hokej","holinka","holka","holub","homole","honitba","honorace","horal","horda","horizont","horko","horlivec","hormon","hornina","horoskop","horstvo","hospoda","hostina","hotovost","houba","houf","houpat","houska","hovor","hradba","hranice","hravost","hrazda","hrbolek","hrdina","hrdlo","hrdost","hrnek","hrobka","hromada","hrot","hrouda","hrozen","hrstka","hrubost","hryzat","hubenost","hubnout","hudba","hukot","humr","husita","hustota","hvozd","hybnost","hydrant","hygiena","hymna","hysterik","idylka","ihned","ikona","iluze","imunita","infekce","inflace","inkaso","inovace","inspekce","internet","invalida","investor","inzerce","ironie","jablko","jachta","jahoda","jakmile","jakost","jalovec","jantar","jarmark","jaro","jasan","jasno","jatka","javor","jazyk","jedinec","jedle","jednatel","jehlan","jekot","jelen","jelito","jemnost","jenom","jepice","jeseter","jevit","jezdec","jezero","jinak","jindy","jinoch","jiskra","jistota","jitrnice","jizva","jmenovat","jogurt","jurta","kabaret","kabel","kabinet","kachna","kadet","kadidlo","kahan","kajak","kajuta","kakao","kaktus","kalamita","kalhoty","kalibr","kalnost","kamera","kamkoliv","kamna","kanibal","kanoe","kantor","kapalina","kapela","kapitola","kapka","kaple","kapota","kapr","kapusta","kapybara","karamel","karotka","karton","kasa","katalog","katedra","kauce","kauza","kavalec","kazajka","kazeta","kazivost","kdekoliv","kdesi","kedluben","kemp","keramika","kino","klacek","kladivo","klam","klapot","klasika","klaun","klec","klenba","klepat","klesnout","klid","klima","klisna","klobouk","klokan","klopa","kloub","klubovna","klusat","kluzkost","kmen","kmitat","kmotr","kniha","knot","koalice","koberec","kobka","kobliha","kobyla","kocour","kohout","kojenec","kokos","koktejl","kolaps","koleda","kolize","kolo","komando","kometa","komik","komnata","komora","kompas","komunita","konat","koncept","kondice","konec","konfese","kongres","konina","konkurs","kontakt","konzerva","kopanec","kopie","kopnout","koprovka","korbel","korektor","kormidlo","koroptev","korpus","koruna","koryto","korzet","kosatec","kostka","kotel","kotleta","kotoul","koukat","koupelna","kousek","kouzlo","kovboj","koza","kozoroh","krabice","krach","krajina","kralovat","krasopis","kravata","kredit","krejcar","kresba","kreveta","kriket","kritik","krize","krkavec","krmelec","krmivo","krocan","krok","kronika","kropit","kroupa","krovka","krtek","kruhadlo","krupice","krutost","krvinka","krychle","krypta","krystal","kryt","kudlanka","kufr","kujnost","kukla","kulajda","kulich","kulka","kulomet","kultura","kuna","kupodivu","kurt","kurzor","kutil","kvalita","kvasinka","kvestor","kynolog","kyselina","kytara","kytice","kytka","kytovec","kyvadlo","labrador","lachtan","ladnost","laik","lakomec","lamela","lampa","lanovka","lasice","laso","lastura","latinka","lavina","lebka","leckdy","leden","lednice","ledovka","ledvina","legenda","legie","legrace","lehce","lehkost","lehnout","lektvar","lenochod","lentilka","lepenka","lepidlo","letadlo","letec","letmo","letokruh","levhart","levitace","levobok","libra","lichotka","lidojed","lidskost","lihovina","lijavec","lilek","limetka","linie","linka","linoleum","listopad","litina","litovat","lobista","lodivod","logika","logoped","lokalita","loket","lomcovat","lopata","lopuch","lord","losos","lotr","loudal","louh","louka","louskat","lovec","lstivost","lucerna","lucifer","lump","lusk","lustrace","lvice","lyra","lyrika","lysina","madam","madlo","magistr","mahagon","majetek","majitel","majorita","makak","makovice","makrela","malba","malina","malovat","malvice","maminka","mandle","manko","marnost","masakr","maskot","masopust","matice","matrika","maturita","mazanec","mazivo","mazlit","mazurka","mdloba","mechanik","meditace","medovina","melasa","meloun","mentolka","metla","metoda","metr","mezera","migrace","mihnout","mihule","mikina","mikrofon","milenec","milimetr","milost","mimika","mincovna","minibar","minomet","minulost","miska","mistr","mixovat","mladost","mlha","mlhovina","mlok","mlsat","mluvit","mnich","mnohem","mobil","mocnost","modelka","modlitba","mohyla","mokro","molekula","momentka","monarcha","monokl","monstrum","montovat","monzun","mosaz","moskyt","most","motivace","motorka","motyka","moucha","moudrost","mozaika","mozek","mozol","mramor","mravenec","mrkev","mrtvola","mrzet","mrzutost","mstitel","mudrc","muflon","mulat","mumie","munice","muset","mutace","muzeum","muzikant","myslivec","mzda","nabourat","nachytat","nadace","nadbytek","nadhoz","nadobro","nadpis","nahlas","nahnat","nahodile","nahradit","naivita","najednou","najisto","najmout","naklonit","nakonec","nakrmit","nalevo","namazat","namluvit","nanometr","naoko","naopak","naostro","napadat","napevno","naplnit","napnout","naposled","naprosto","narodit","naruby","narychlo","nasadit","nasekat","naslepo","nastat","natolik","navenek","navrch","navzdory","nazvat","nebe","nechat","necky","nedaleko","nedbat","neduh","negace","nehet","nehoda","nejen","nejprve","neklid","nelibost","nemilost","nemoc","neochota","neonka","nepokoj","nerost","nerv","nesmysl","nesoulad","netvor","neuron","nevina","nezvykle","nicota","nijak","nikam","nikdy","nikl","nikterak","nitro","nocleh","nohavice","nominace","nora","norek","nositel","nosnost","nouze","noviny","novota","nozdra","nuda","nudle","nuget","nutit","nutnost","nutrie","nymfa","obal","obarvit","obava","obdiv","obec","obehnat","obejmout","obezita","obhajoba","obilnice","objasnit","objekt","obklopit","oblast","oblek","obliba","obloha","obluda","obnos","obohatit","obojek","obout","obrazec","obrna","obruba","obrys","obsah","obsluha","obstarat","obuv","obvaz","obvinit","obvod","obvykle","obyvatel","obzor","ocas","ocel","ocenit","ochladit","ochota","ochrana","ocitnout","odboj","odbyt","odchod","odcizit","odebrat","odeslat","odevzdat","odezva","odhadce","odhodit","odjet","odjinud","odkaz","odkoupit","odliv","odluka","odmlka","odolnost","odpad","odpis","odplout","odpor","odpustit","odpykat","odrazka","odsoudit","odstup","odsun","odtok","odtud","odvaha","odveta","odvolat","odvracet","odznak","ofina","ofsajd","ohlas","ohnisko","ohrada","ohrozit","ohryzek","okap","okenice","oklika","okno","okouzlit","okovy","okrasa","okres","okrsek","okruh","okupant","okurka","okusit","olejnina","olizovat","omak","omeleta","omezit","omladina","omlouvat","omluva","omyl","onehdy","opakovat","opasek","operace","opice","opilost","opisovat","opora","opozice","opravdu","oproti","orbital","orchestr","orgie","orlice","orloj","ortel","osada","oschnout","osika","osivo","oslava","oslepit","oslnit","oslovit","osnova","osoba","osolit","ospalec","osten","ostraha","ostuda","ostych","osvojit","oteplit","otisk","otop","otrhat","otrlost","otrok","otruby","otvor","ovanout","ovar","oves","ovlivnit","ovoce","oxid","ozdoba","pachatel","pacient","padouch","pahorek","pakt","palanda","palec","palivo","paluba","pamflet","pamlsek","panenka","panika","panna","panovat","panstvo","pantofle","paprika","parketa","parodie","parta","paruka","paryba","paseka","pasivita","pastelka","patent","patrona","pavouk","pazneht","pazourek","pecka","pedagog","pejsek","peklo","peloton","penalta","pendrek","penze","periskop","pero","pestrost","petarda","petice","petrolej","pevnina","pexeso","pianista","piha","pijavice","pikle","piknik","pilina","pilnost","pilulka","pinzeta","pipeta","pisatel","pistole","pitevna","pivnice","pivovar","placenta","plakat","plamen","planeta","plastika","platit","plavidlo","plaz","plech","plemeno","plenta","ples","pletivo","plevel","plivat","plnit","plno","plocha","plodina","plomba","plout","pluk","plyn","pobavit","pobyt","pochod","pocit","poctivec","podat","podcenit","podepsat","podhled","podivit","podklad","podmanit","podnik","podoba","podpora","podraz","podstata","podvod","podzim","poezie","pohanka","pohnutka","pohovor","pohroma","pohyb","pointa","pojistka","pojmout","pokazit","pokles","pokoj","pokrok","pokuta","pokyn","poledne","polibek","polknout","poloha","polynom","pomalu","pominout","pomlka","pomoc","pomsta","pomyslet","ponechat","ponorka","ponurost","popadat","popel","popisek","poplach","poprosit","popsat","popud","poradce","porce","porod","porucha","poryv","posadit","posed","posila","poskok","poslanec","posoudit","pospolu","postava","posudek","posyp","potah","potkan","potlesk","potomek","potrava","potupa","potvora","poukaz","pouto","pouzdro","povaha","povidla","povlak","povoz","povrch","povstat","povyk","povzdech","pozdrav","pozemek","poznatek","pozor","pozvat","pracovat","prahory","praktika","prales","praotec","praporek","prase","pravda","princip","prkno","probudit","procento","prodej","profese","prohra","projekt","prolomit","promile","pronikat","propad","prorok","prosba","proton","proutek","provaz","prskavka","prsten","prudkost","prut","prvek","prvohory","psanec","psovod","pstruh","ptactvo","puberta","puch","pudl","pukavec","puklina","pukrle","pult","pumpa","punc","pupen","pusa","pusinka","pustina","putovat","putyka","pyramida","pysk","pytel","racek","rachot","radiace","radnice","radon","raft","ragby","raketa","rakovina","rameno","rampouch","rande","rarach","rarita","rasovna","rastr","ratolest","razance","razidlo","reagovat","reakce","recept","redaktor","referent","reflex","rejnok","reklama","rekord","rekrut","rektor","reputace","revize","revma","revolver","rezerva","riskovat","riziko","robotika","rodokmen","rohovka","rokle","rokoko","romaneto","ropovod","ropucha","rorejs","rosol","rostlina","rotmistr","rotoped","rotunda","roubenka","roucho","roup","roura","rovina","rovnice","rozbor","rozchod","rozdat","rozeznat","rozhodce","rozinka","rozjezd","rozkaz","rozloha","rozmar","rozpad","rozruch","rozsah","roztok","rozum","rozvod","rubrika","ruchadlo","rukavice","rukopis","ryba","rybolov","rychlost","rydlo","rypadlo","rytina","ryzost","sadista","sahat","sako","samec","samizdat","samota","sanitka","sardinka","sasanka","satelit","sazba","sazenice","sbor","schovat","sebranka","secese","sedadlo","sediment","sedlo","sehnat","sejmout","sekera","sekta","sekunda","sekvoje","semeno","seno","servis","sesadit","seshora","seskok","seslat","sestra","sesuv","sesypat","setba","setina","setkat","setnout","setrvat","sever","seznam","shoda","shrnout","sifon","silnice","sirka","sirotek","sirup","situace","skafandr","skalisko","skanzen","skaut","skeptik","skica","skladba","sklenice","sklo","skluz","skoba","skokan","skoro","skripta","skrz","skupina","skvost","skvrna","slabika","sladidlo","slanina","slast","slavnost","sledovat","slepec","sleva","slezina","slib","slina","sliznice","slon","sloupek","slovo","sluch","sluha","slunce","slupka","slza","smaragd","smetana","smilstvo","smlouva","smog","smrad","smrk","smrtka","smutek","smysl","snad","snaha","snob","sobota","socha","sodovka","sokol","sopka","sotva","souboj","soucit","soudce","souhlas","soulad","soumrak","souprava","soused","soutok","souviset","spalovna","spasitel","spis","splav","spodek","spojenec","spolu","sponzor","spornost","spousta","sprcha","spustit","sranda","sraz","srdce","srna","srnec","srovnat","srpen","srst","srub","stanice","starosta","statika","stavba","stehno","stezka","stodola","stolek","stopa","storno","stoupat","strach","stres","strhnout","strom","struna","studna","stupnice","stvol","styk","subjekt","subtropy","suchar","sudost","sukno","sundat","sunout","surikata","surovina","svah","svalstvo","svetr","svatba","svazek","svisle","svitek","svoboda","svodidlo","svorka","svrab","sykavka","sykot","synek","synovec","sypat","sypkost","syrovost","sysel","sytost","tabletka","tabule","tahoun","tajemno","tajfun","tajga","tajit","tajnost","taktika","tamhle","tampon","tancovat","tanec","tanker","tapeta","tavenina","tazatel","technika","tehdy","tekutina","telefon","temnota","tendence","tenista","tenor","teplota","tepna","teprve","terapie","termoska","textil","ticho","tiskopis","titulek","tkadlec","tkanina","tlapka","tleskat","tlukot","tlupa","tmel","toaleta","topinka","topol","torzo","touha","toulec","tradice","traktor","tramp","trasa","traverza","trefit","trest","trezor","trhavina","trhlina","trochu","trojice","troska","trouba","trpce","trpitel","trpkost","trubec","truchlit","truhlice","trus","trvat","tudy","tuhnout","tuhost","tundra","turista","turnaj","tuzemsko","tvaroh","tvorba","tvrdost","tvrz","tygr","tykev","ubohost","uboze","ubrat","ubrousek","ubrus","ubytovna","ucho","uctivost","udivit","uhradit","ujednat","ujistit","ujmout","ukazatel","uklidnit","uklonit","ukotvit","ukrojit","ulice","ulita","ulovit","umyvadlo","unavit","uniforma","uniknout","upadnout","uplatnit","uplynout","upoutat","upravit","uran","urazit","usednout","usilovat","usmrtit","usnadnit","usnout","usoudit","ustlat","ustrnout","utahovat","utkat","utlumit","utonout","utopenec","utrousit","uvalit","uvolnit","uvozovka","uzdravit","uzel","uzenina","uzlina","uznat","vagon","valcha","valoun","vana","vandal","vanilka","varan","varhany","varovat","vcelku","vchod","vdova","vedro","vegetace","vejce","velbloud","veletrh","velitel","velmoc","velryba","venkov","veranda","verze","veselka","veskrze","vesnice","vespodu","vesta","veterina","veverka","vibrace","vichr","videohra","vidina","vidle","vila","vinice","viset","vitalita","vize","vizitka","vjezd","vklad","vkus","vlajka","vlak","vlasec","vlevo","vlhkost","vliv","vlnovka","vloupat","vnucovat","vnuk","voda","vodivost","vodoznak","vodstvo","vojensky","vojna","vojsko","volant","volba","volit","volno","voskovka","vozidlo","vozovna","vpravo","vrabec","vracet","vrah","vrata","vrba","vrcholek","vrhat","vrstva","vrtule","vsadit","vstoupit","vstup","vtip","vybavit","vybrat","vychovat","vydat","vydra","vyfotit","vyhledat","vyhnout","vyhodit","vyhradit","vyhubit","vyjasnit","vyjet","vyjmout","vyklopit","vykonat","vylekat","vymazat","vymezit","vymizet","vymyslet","vynechat","vynikat","vynutit","vypadat","vyplatit","vypravit","vypustit","vyrazit","vyrovnat","vyrvat","vyslovit","vysoko","vystavit","vysunout","vysypat","vytasit","vytesat","vytratit","vyvinout","vyvolat","vyvrhel","vyzdobit","vyznat","vzadu","vzbudit","vzchopit","vzdor","vzduch","vzdychat","vzestup","vzhledem","vzkaz","vzlykat","vznik","vzorek","vzpoura","vztah","vztek","xylofon","zabrat","zabydlet","zachovat","zadarmo","zadusit","zafoukat","zahltit","zahodit","zahrada","zahynout","zajatec","zajet","zajistit","zaklepat","zakoupit","zalepit","zamezit","zamotat","zamyslet","zanechat","zanikat","zaplatit","zapojit","zapsat","zarazit","zastavit","zasunout","zatajit","zatemnit","zatknout","zaujmout","zavalit","zavelet","zavinit","zavolat","zavrtat","zazvonit","zbavit","zbrusu","zbudovat","zbytek","zdaleka","zdarma","zdatnost","zdivo","zdobit","zdroj","zdvih","zdymadlo","zelenina","zeman","zemina","zeptat","zezadu","zezdola","zhatit","zhltnout","zhluboka","zhotovit","zhruba","zima","zimnice","zjemnit","zklamat","zkoumat","zkratka","zkumavka","zlato","zlehka","zloba","zlom","zlost","zlozvyk","zmapovat","zmar","zmatek","zmije","zmizet","zmocnit","zmodrat","zmrzlina","zmutovat","znak","znalost","znamenat","znovu","zobrazit","zotavit","zoubek","zoufale","zplodit","zpomalit","zprava","zprostit","zprudka","zprvu","zrada","zranit","zrcadlo","zrnitost","zrno","zrovna","zrychlit","zrzavost","zticha","ztratit","zubovina","zubr","zvednout","zvenku","zvesela","zvon","zvrat","zvukovod","zvyk"]["abandon","ability","able","about","above","absent","absorb","abstract","absurd","abuse","access","accident","account","accuse","achieve","acid","acoustic","acquire","across","act","action","actor","actress","actual","adapt","add","addict","address","adjust","admit","adult","advance","advice","aerobic","affair","afford","afraid","again","age","agent","agree","ahead","aim","air","airport","aisle","alarm","album","alcohol","alert","alien","all","alley","allow","almost","alone","alpha","already","also","alter","always","amateur","amazing","among","amount","amused","analyst","anchor","ancient","anger","angle","angry","animal","ankle","announce","annual","another","answer","antenna","antique","anxiety","any","apart","apology","appear","apple","approve","april","arch","arctic","area","arena","argue","arm","armed","armor","army","around","arrange","arrest","arrive","arrow","art","artefact","artist","artwork","ask","aspect","assault","asset","assist","assume","asthma","athlete","atom","attack","attend","attitude","attract","auction","audit","august","aunt","author","auto","autumn","average","avocado","avoid","awake","aware","away","awesome","awful","awkward","axis","baby","bachelor","bacon","badge","bag","balance","balcony","ball","bamboo","banana","banner","bar","barely","bargain","barrel","base","basic","basket","battle","beach","bean","beauty","because","become","beef","before","begin","behave","behind","believe","below","belt","bench","benefit","best","betray","better","between","beyond","bicycle","bid","bike","bind","biology","bird","birth","bitter","black","blade","blame","blanket","blast","bleak","bless","blind","blood","blossom","blouse","blue","blur","blush","board","boat","body","boil","bomb","bone","bonus","book","boost","border","boring","borrow","boss","bottom","bounce","box","boy","bracket","brain","brand","brass","brave","bread","breeze","brick","bridge","brief","bright","bring","brisk","broccoli","broken","bronze","broom","brother","brown","brush","bubble","buddy","budget","buffalo","build","bulb","bulk","bullet","bundle","bunker","burden","burger","burst","bus","business","busy","butter","buyer","buzz","cabbage","cabin","cable","cactus","cage","cake","call","calm","camera","camp","can","canal","cancel","candy","cannon","canoe","canvas","canyon","capable","capital","captain","car","carbon","card","cargo","carpet","carry","cart","case","cash","casino","castle","casual","cat","catalog","catch","category","cattle","caught","cause","caution","cave","ceiling","celery","cement","census","century","cereal","certain","chair","chalk","champion","change","chaos","chapter","charge","chase","chat","cheap","check","cheese","chef","cherry","chest","chicken","chief","child","chimney","choice","choose","chronic","chuckle","chunk","churn","cigar","cinnamon","circle","citizen","city","civil","claim","clap","clarify","claw","clay","clean","clerk","clever","click","client","cliff","climb","clinic","clip","clock","clog","close","cloth","cloud","clown","club","clump","cluster","clutch","coach","coast","coconut","code","coffee","coil","coin","collect","color","column","combine","come","comfort","comic","common","company","concert","conduct","confirm","congress","connect","consider","control","convince","cook","cool","copper","copy","coral","core","corn","correct","cost","cotton","couch","country","couple","course","cousin","cover","coyote","crack","cradle","craft","cram","crane","crash","crater","crawl","crazy","cream","credit","creek","crew","cricket","crime","crisp","critic","crop","cross","crouch","crowd","crucial","cruel","cruise","crumble","crunch","crush","cry","crystal","cube","culture","cup","cupboard","curious","current","curtain","curve","cushion","custom","cute","cycle","dad","damage","damp","dance","danger","daring","dash","daughter","dawn","day","deal","debate","debris","decade","december","decide","decline","decorate","decrease","deer","defense","define","defy","degree","delay","deliver","demand","demise","denial","dentist","deny","depart","depend","deposit","depth","deputy","derive","describe","desert","design","desk","despair","destroy","detail","detect","develop","device","devote","diagram","dial","diamond","diary","dice","diesel","diet","differ","digital","dignity","dilemma","dinner","dinosaur","direct","dirt","disagree","discover","disease","dish","dismiss","disorder","display","distance","divert","divide","divorce","dizzy","doctor","document","dog","doll","dolphin","domain","donate","donkey","donor","door","dose","double","dove","draft","dragon","drama","drastic","draw","dream","dress","drift","drill","drink","drip","drive","drop","drum","dry","duck","dumb","dune","during","dust","dutch","duty","dwarf","dynamic","eager","eagle","early","earn","earth","easily","east","easy","echo","ecology","economy","edge","edit","educate","effort","egg","eight","either","elbow","elder","electric","elegant","element","elephant","elevator","elite","else","embark","embody","embrace","emerge","emotion","employ","empower","empty","enable","enact","end","endless","endorse","enemy","energy","enforce","engage","engine","enhance","enjoy","enlist","enough","enrich","enroll","ensure","enter","entire","entry","envelope","episode","equal","equip","era","erase","erode","erosion","error","erupt","escape","essay","essence","estate","eternal","ethics","evidence","evil","evoke","evolve","exact","example","excess","exchange","excite","exclude","excuse","execute","exercise","exhaust","exhibit","exile","exist","exit","exotic","expand","expect","expire","explain","expose","express","extend","extra","eye","eyebrow","fabric","face","faculty","fade","faint","faith","fall","false","fame","family","famous","fan","fancy","fantasy","farm","fashion","fat","fatal","father","fatigue","fault","favorite","feature","february","federal","fee","feed","feel","female","fence","festival","fetch","fever","few","fiber","fiction","field","figure","file","film","filter","final","find","fine","finger","finish","fire","firm","first","fiscal","fish","fit","fitness","fix","flag","flame","flash","flat","flavor","flee","flight","flip","float","flock","floor","flower","fluid","flush","fly","foam","focus","fog","foil","fold","follow","food","foot","force","forest","forget","fork","fortune","forum","forward","fossil","foster","found","fox","fragile","frame","frequent","fresh","friend","fringe","frog","front","frost","frown","frozen","fruit","fuel","fun","funny","furnace","fury","future","gadget","gain","galaxy","gallery","game","gap","garage","garbage","garden","garlic","garment","gas","gasp","gate","gather","gauge","gaze","general","genius","genre","gentle","genuine","gesture","ghost","giant","gift","giggle","ginger","giraffe","girl","give","glad","glance","glare","glass","glide","glimpse","globe","gloom","glory","glove","glow","glue","goat","goddess","gold","good","goose","gorilla","gospel","gossip","govern","gown","grab","grace","grain","grant","grape","grass","gravity","great","green","grid","grief","grit","grocery","group","grow","grunt","guard","guess","guide","guilt","guitar","gun","gym","habit","hair","half","hammer","hamster","hand","happy","harbor","hard","harsh","harvest","hat","have","hawk","hazard","head","health","heart","heavy","hedgehog","height","hello","helmet","help","hen","hero","hidden","high","hill","hint","hip","hire","history","hobby","hockey","hold","hole","holiday","hollow","home","honey","hood","hope","horn","horror","horse","hospital","host","hotel","hour","hover","hub","huge","human","humble","humor","hundred","hungry","hunt","hurdle","hurry","hurt","husband","hybrid","ice","icon","idea","identify","idle","ignore","ill","illegal","illness","image","imitate","immense","immune","impact","impose","improve","impulse","inch","include","income","increase","index","indicate","indoor","industry","infant","inflict","inform","inhale","inherit","initial","inject","injury","inmate","inner","innocent","input","inquiry","insane","insect","inside","inspire","install","intact","interest","into","invest","invite","involve","iron","island","isolate","issue","item","ivory","jacket","jaguar","jar","jazz","jealous","jeans","jelly","jewel","job","join","joke","journey","joy","judge","juice","jump","jungle","junior","junk","just","kangaroo","keen","keep","ketchup","key","kick","kid","kidney","kind","kingdom","kiss","kit","kitchen","kite","kitten","kiwi","knee","knife","knock","know","lab","label","labor","ladder","lady","lake","lamp","language","laptop","large","later","latin","laugh","laundry","lava","law","lawn","lawsuit","layer","lazy","leader","leaf","learn","leave","lecture","left","leg","legal","legend","leisure","lemon","lend","length","lens","leopard","lesson","letter","level","liar","liberty","library","license","life","lift","light","like","limb","limit","link","lion","liquid","list","little","live","lizard","load","loan","lobster","local","lock","logic","lonely","long","loop","lottery","loud","lounge","love","loyal","lucky","luggage","lumber","lunar","lunch","luxury","lyrics","machine","mad","magic","magnet","maid","mail","main","major","make","mammal","man","manage","mandate","mango","mansion","manual","maple","marble","march","margin","marine","market","marriage","mask","mass","master","match","material","math","matrix","matter","maximum","maze","meadow","mean","measure","meat","mechanic","medal","media","melody","melt","member","memory","mention","menu","mercy","merge","merit","merry","mesh","message","metal","method","middle","midnight","milk","million","mimic","mind","minimum","minor","minute","miracle","mirror","misery","miss","mistake","mix","mixed","mixture","mobile","model","modify","mom","moment","monitor","monkey","monster","month","moon","moral","more","morning","mosquito","mother","motion","motor","mountain","mouse","move","movie","much","muffin","mule","multiply","muscle","museum","mushroom","music","must","mutual","myself","mystery","myth","naive","name","napkin","narrow","nasty","nation","nature","near","neck","need","negative","neglect","neither","nephew","nerve","nest","net","network","neutral","never","news","next","nice","night","noble","noise","nominee","noodle","normal","north","nose","notable","note","nothing","notice","novel","now","nuclear","number","nurse","nut","oak","obey","object","oblige","obscure","observe","obtain","obvious","occur","ocean","october","odor","off","offer","office","often","oil","okay","old","olive","olympic","omit","once","one","onion","online","only","open","opera","opinion","oppose","option","orange","orbit","orchard","order","ordinary","organ","orient","original","orphan","ostrich","other","outdoor","outer","output","outside","oval","oven","over","own","owner","oxygen","oyster","ozone","pact","paddle","page","pair","palace","palm","panda","panel","panic","panther","paper","parade","parent","park","parrot","party","pass","patch","path","patient","patrol","pattern","pause","pave","payment","peace","peanut","pear","peasant","pelican","pen","penalty","pencil","people","pepper","perfect","permit","person","pet","phone","photo","phrase","physical","piano","picnic","picture","piece","pig","pigeon","pill","pilot","pink","pioneer","pipe","pistol","pitch","pizza","place","planet","plastic","plate","play","please","pledge","pluck","plug","plunge","poem","poet","point","polar","pole","police","pond","pony","pool","popular","portion","position","possible","post","potato","pottery","poverty","powder","power","practice","praise","predict","prefer","prepare","present","pretty","prevent","price","pride","primary","print","priority","prison","private","prize","problem","process","produce","profit","program","project","promote","proof","property","prosper","protect","proud","provide","public","pudding","pull","pulp","pulse","pumpkin","punch","pupil","puppy","purchase","purity","purpose","purse","push","put","puzzle","pyramid","quality","quantum","quarter","question","quick","quit","quiz","quote","rabbit","raccoon","race","rack","radar","radio","rail","rain","raise","rally","ramp","ranch","random","range","rapid","rare","rate","rather","raven","raw","razor","ready","real","reason","rebel","rebuild","recall","receive","recipe","record","recycle","reduce","reflect","reform","refuse","region","regret","regular","reject","relax","release","relief","rely","remain","remember","remind","remove","render","renew","rent","reopen","repair","repeat","replace","report","require","rescue","resemble","resist","resource","response","result","retire","retreat","return","reunion","reveal","review","reward","rhythm","rib","ribbon","rice","rich","ride","ridge","rifle","right","rigid","ring","riot","ripple","risk","ritual","rival","river","road","roast","robot","robust","rocket","romance","roof","rookie","room","rose","rotate","rough","round","route","royal","rubber","rude","rug","rule","run","runway","rural","sad","saddle","sadness","safe","sail","salad","salmon","salon","salt","salute","same","sample","sand","satisfy","satoshi","sauce","sausage","save","say","scale","scan","scare","scatter","scene","scheme","school","science","scissors","scorpion","scout","scrap","screen","script","scrub","sea","search","season","seat","second","secret","section","security","seed","seek","segment","select","sell","seminar","senior","sense","sentence","series","service","session","settle","setup","seven","shadow","shaft","shallow","share","shed","shell","sheriff","shield","shift","shine","ship","shiver","shock","shoe","shoot","shop","short","shoulder","shove","shrimp","shrug","shuffle","shy","sibling","sick","side","siege","sight","sign","silent","silk","silly","silver","similar","simple","since","sing","siren","sister","situate","six","size","skate","sketch","ski","skill","skin","skirt","skull","slab","slam","sleep","slender","slice","slide","slight","slim","slogan","slot","slow","slush","small","smart","smile","smoke","smooth","snack","snake","snap","sniff","snow","soap","soccer","social","sock","soda","soft","solar","soldier","solid","solution","solve","someone","song","soon","sorry","sort","soul","sound","soup","source","south","space","spare","spatial","spawn","speak","special","speed","spell","spend","sphere","spice","spider","spike","spin","spirit","split","spoil","sponsor","spoon","sport","spot","spray","spread","spring","spy","square","squeeze","squirrel","stable","stadium","staff","stage","stairs","stamp","stand","start","state","stay","steak","steel","stem","step","stereo","stick","still","sting","stock","stomach","stone","stool","story","stove","strategy","street","strike","strong","struggle","student","stuff","stumble","style","subject","submit","subway","success","such","sudden","suffer","sugar","suggest","suit","summer","sun","sunny","sunset","super","supply","supreme","sure","surface","surge","surprise","surround","survey","suspect","sustain","swallow","swamp","swap","swarm","swear","sweet","swift","swim","swing","switch","sword","symbol","symptom","syrup","system","table","tackle","tag","tail","talent","talk","tank","tape","target","task","taste","tattoo","taxi","teach","team","tell","ten","tenant","tennis","tent","term","test","text","thank","that","theme","then","theory","there","they","thing","this","thought","three","thrive","throw","thumb","thunder","ticket","tide","tiger","tilt","timber","time","tiny","tip","tired","tissue","title","toast","tobacco","today","toddler","toe","together","toilet","token","tomato","tomorrow","tone","tongue","tonight","tool","tooth","top","topic","topple","torch","tornado","tortoise","toss","total","tourist","toward","tower","town","toy","track","trade","traffic","tragic","train","transfer","trap","trash","travel","tray","treat","tree","trend","trial","tribe","trick","trigger","trim","trip","trophy","trouble","truck","true","truly","trumpet","trust","truth","try","tube","tuition","tumble","tuna","tunnel","turkey","turn","turtle","twelve","twenty","twice","twin","twist","two","type","typical","ugly","umbrella","unable","unaware","uncle","uncover","under","undo","unfair","unfold","unhappy","uniform","unique","unit","universe","unknown","unlock","until","unusual","unveil","update","upgrade","uphold","upon","upper","upset","urban","urge","usage","use","used","useful","useless","usual","utility","vacant","vacuum","vague","valid","valley","valve","van","vanish","vapor","various","vast","vault","vehicle","velvet","vendor","venture","venue","verb","verify","version","very","vessel","veteran","viable","vibrant","vicious","victory","video","view","village","vintage","violin","virtual","virus","visa","visit","visual","vital","vivid","vocal","voice","void","volcano","volume","vote","voyage","wage","wagon","wait","walk","wall","walnut","want","warfare","warm","warrior","wash","wasp","waste","water","wave","way","wealth","weapon","wear","weasel","weather","web","wedding","weekend","weird","welcome","west","wet","whale","what","wheat","wheel","when","where","whip","whisper","wide","width","wife","wild","will","win","window","wine","wing","wink","winner","winter","wire","wisdom","wise","wish","witness","wolf","woman","wonder","wood","wool","word","work","world","worry","worth","wrap","wreck","wrestle","wrist","write","wrong","yard","year","yellow","you","young","youth","zebra","zero","zone","zoo"]["abaisser","abandon","abdiquer","abeille","abolir","aborder","aboutir","aboyer","abrasif","abreuver","abriter","abroger","abrupt","absence","absolu","absurde","abusif","abyssal","académie","acajou","acarien","accabler","accepter","acclamer","accolade","accroche","accuser","acerbe","achat","acheter","aciduler","acier","acompte","acquérir","acronyme","acteur","actif","actuel","adepte","adéquat","adhésif","adjectif","adjuger","admettre","admirer","adopter","adorer","adoucir","adresse","adroit","adulte","adverbe","aérer","aéronef","affaire","affecter","affiche","affreux","affubler","agacer","agencer","agile","agiter","agrafer","agréable","agrume","aider","aiguille","ailier","aimable","aisance","ajouter","ajuster","alarmer","alchimie","alerte","algèbre","algue","aliéner","aliment","alléger","alliage","allouer","allumer","alourdir","alpaga","altesse","alvéole","amateur","ambigu","ambre","aménager","amertume","amidon","amiral","amorcer","amour","amovible","amphibie","ampleur","amusant","analyse","anaphore","anarchie","anatomie","ancien","anéantir","angle","angoisse","anguleux","animal","annexer","annonce","annuel","anodin","anomalie","anonyme","anormal","antenne","antidote","anxieux","apaiser","apéritif","aplanir","apologie","appareil","appeler","apporter","appuyer","aquarium","aqueduc","arbitre","arbuste","ardeur","ardoise","argent","arlequin","armature","armement","armoire","armure","arpenter","arracher","arriver","arroser","arsenic","artériel","article","aspect","asphalte","aspirer","assaut","asservir","assiette","associer","assurer","asticot","astre","astuce","atelier","atome","atrium","atroce","attaque","attentif","attirer","attraper","aubaine","auberge","audace","audible","augurer","aurore","automne","autruche","avaler","avancer","avarice","avenir","averse","aveugle","aviateur","avide","avion","aviser","avoine","avouer","avril","axial","axiome","badge","bafouer","bagage","baguette","baignade","balancer","balcon","baleine","balisage","bambin","bancaire","bandage","banlieue","bannière","banquier","barbier","baril","baron","barque","barrage","bassin","bastion","bataille","bateau","batterie","baudrier","bavarder","belette","bélier","belote","bénéfice","berceau","berger","berline","bermuda","besace","besogne","bétail","beurre","biberon","bicycle","bidule","bijou","bilan","bilingue","billard","binaire","biologie","biopsie","biotype","biscuit","bison","bistouri","bitume","bizarre","blafard","blague","blanchir","blessant","blinder","blond","bloquer","blouson","bobard","bobine","boire","boiser","bolide","bonbon","bondir","bonheur","bonifier","bonus","bordure","borne","botte","boucle","boueux","bougie","boulon","bouquin","bourse","boussole","boutique","boxeur","branche","brasier","brave","brebis","brèche","breuvage","bricoler","brigade","brillant","brioche","brique","brochure","broder","bronzer","brousse","broyeur","brume","brusque","brutal","bruyant","buffle","buisson","bulletin","bureau","burin","bustier","butiner","butoir","buvable","buvette","cabanon","cabine","cachette","cadeau","cadre","caféine","caillou","caisson","calculer","calepin","calibre","calmer","calomnie","calvaire","camarade","caméra","camion","campagne","canal","caneton","canon","cantine","canular","capable","caporal","caprice","capsule","capter","capuche","carabine","carbone","caresser","caribou","carnage","carotte","carreau","carton","cascade","casier","casque","cassure","causer","caution","cavalier","caverne","caviar","cédille","ceinture","céleste","cellule","cendrier","censurer","central","cercle","cérébral","cerise","cerner","cerveau","cesser","chagrin","chaise","chaleur","chambre","chance","chapitre","charbon","chasseur","chaton","chausson","chavirer","chemise","chenille","chéquier","chercher","cheval","chien","chiffre","chignon","chimère","chiot","chlorure","chocolat","choisir","chose","chouette","chrome","chute","cigare","cigogne","cimenter","cinéma","cintrer","circuler","cirer","cirque","citerne","citoyen","citron","civil","clairon","clameur","claquer","classe","clavier","client","cligner","climat","clivage","cloche","clonage","cloporte","cobalt","cobra","cocasse","cocotier","coder","codifier","coffre","cogner","cohésion","coiffer","coincer","colère","colibri","colline","colmater","colonel","combat","comédie","commande","compact","concert","conduire","confier","congeler","connoter","consonne","contact","convexe","copain","copie","corail","corbeau","cordage","corniche","corpus","correct","cortège","cosmique","costume","coton","coude","coupure","courage","couteau","couvrir","coyote","crabe","crainte","cravate","crayon","créature","créditer","crémeux","creuser","crevette","cribler","crier","cristal","critère","croire","croquer","crotale","crucial","cruel","crypter","cubique","cueillir","cuillère","cuisine","cuivre","culminer","cultiver","cumuler","cupide","curatif","curseur","cyanure","cycle","cylindre","cynique","daigner","damier","danger","danseur","dauphin","débattre","débiter","déborder","débrider","débutant","décaler","décembre","déchirer","décider","déclarer","décorer","décrire","décupler","dédale","déductif","déesse","défensif","défiler","défrayer","dégager","dégivrer","déglutir","dégrafer","déjeuner","délice","déloger","demander","demeurer","démolir","dénicher","dénouer","dentelle","dénuder","départ","dépenser","déphaser","déplacer","déposer","déranger","dérober","désastre","descente","désert","désigner","désobéir","dessiner","destrier","détacher","détester","détourer","détresse","devancer","devenir","deviner","devoir","diable","dialogue","diamant","dicter","différer","digérer","digital","digne","diluer","dimanche","diminuer","dioxyde","directif","diriger","discuter","disposer","dissiper","distance","divertir","diviser","docile","docteur","dogme","doigt","domaine","domicile","dompter","donateur","donjon","donner","dopamine","dortoir","dorure","dosage","doseur","dossier","dotation","douanier","double","douceur","douter","doyen","dragon","draper","dresser","dribbler","droiture","duperie","duplexe","durable","durcir","dynastie","éblouir","écarter","écharpe","échelle","éclairer","éclipse","éclore","écluse","école","économie","écorce","écouter","écraser","écrémer","écrivain","écrou","écume","écureuil","édifier","éduquer","effacer","effectif","effigie","effort","effrayer","effusion","égaliser","égarer","éjecter","élaborer","élargir","électron","élégant","éléphant","élève","éligible","élitisme","éloge","élucider","éluder","emballer","embellir","embryon","émeraude","émission","emmener","émotion","émouvoir","empereur","employer","emporter","emprise","émulsion","encadrer","enchère","enclave","encoche","endiguer","endosser","endroit","enduire","énergie","enfance","enfermer","enfouir","engager","engin","englober","énigme","enjamber","enjeu","enlever","ennemi","ennuyeux","enrichir","enrobage","enseigne","entasser","entendre","entier","entourer","entraver","énumérer","envahir","enviable","envoyer","enzyme","éolien","épaissir","épargne","épatant","épaule","épicerie","épidémie","épier","épilogue","épine","épisode","épitaphe","époque","épreuve","éprouver","épuisant","équerre","équipe","ériger","érosion","erreur","éruption","escalier","espadon","espèce","espiègle","espoir","esprit","esquiver","essayer","essence","essieu","essorer","estime","estomac","estrade","étagère","étaler","étanche","étatique","éteindre","étendoir","éternel","éthanol","éthique","ethnie","étirer","étoffer","étoile","étonnant","étourdir","étrange","étroit","étude","euphorie","évaluer","évasion","éventail","évidence","éviter","évolutif","évoquer","exact","exagérer","exaucer","exceller","excitant","exclusif","excuse","exécuter","exemple","exercer","exhaler","exhorter","exigence","exiler","exister","exotique","expédier","explorer","exposer","exprimer","exquis","extensif","extraire","exulter","fable","fabuleux","facette","facile","facture","faiblir","falaise","fameux","famille","farceur","farfelu","farine","farouche","fasciner","fatal","fatigue","faucon","fautif","faveur","favori","fébrile","féconder","fédérer","félin","femme","fémur","fendoir","féodal","fermer","féroce","ferveur","festival","feuille","feutre","février","fiasco","ficeler","fictif","fidèle","figure","filature","filetage","filière","filleul","filmer","filou","filtrer","financer","finir","fiole","firme","fissure","fixer","flairer","flamme","flasque","flatteur","fléau","flèche","fleur","flexion","flocon","flore","fluctuer","fluide","fluvial","folie","fonderie","fongible","fontaine","forcer","forgeron","formuler","fortune","fossile","foudre","fougère","fouiller","foulure","fourmi","fragile","fraise","franchir","frapper","frayeur","frégate","freiner","frelon","frémir","frénésie","frère","friable","friction","frisson","frivole","froid","fromage","frontal","frotter","fruit","fugitif","fuite","fureur","furieux","furtif","fusion","futur","gagner","galaxie","galerie","gambader","garantir","gardien","garnir","garrigue","gazelle","gazon","géant","gélatine","gélule","gendarme","général","génie","genou","gentil","géologie","géomètre","géranium","germe","gestuel","geyser","gibier","gicler","girafe","givre","glace","glaive","glisser","globe","gloire","glorieux","golfeur","gomme","gonfler","gorge","gorille","goudron","gouffre","goulot","goupille","gourmand","goutte","graduel","graffiti","graine","grand","grappin","gratuit","gravir","grenat","griffure","griller","grimper","grogner","gronder","grotte","groupe","gruger","grutier","gruyère","guépard","guerrier","guide","guimauve","guitare","gustatif","gymnaste","gyrostat","habitude","hachoir","halte","hameau","hangar","hanneton","haricot","harmonie","harpon","hasard","hélium","hématome","herbe","hérisson","hermine","héron","hésiter","heureux","hiberner","hibou","hilarant","histoire","hiver","homard","hommage","homogène","honneur","honorer","honteux","horde","horizon","horloge","hormone","horrible","houleux","housse","hublot","huileux","humain","humble","humide","humour","hurler","hydromel","hygiène","hymne","hypnose","idylle","ignorer","iguane","illicite","illusion","image","imbiber","imiter","immense","immobile","immuable","impact","impérial","implorer","imposer","imprimer","imputer","incarner","incendie","incident","incliner","incolore","indexer","indice","inductif","inédit","ineptie","inexact","infini","infliger","informer","infusion","ingérer","inhaler","inhiber","injecter","injure","innocent","inoculer","inonder","inscrire","insecte","insigne","insolite","inspirer","instinct","insulter","intact","intense","intime","intrigue","intuitif","inutile","invasion","inventer","inviter","invoquer","ironique","irradier","irréel","irriter","isoler","ivoire","ivresse","jaguar","jaillir","jambe","janvier","jardin","jauger","jaune","javelot","jetable","jeton","jeudi","jeunesse","joindre","joncher","jongler","joueur","jouissif","journal","jovial","joyau","joyeux","jubiler","jugement","junior","jupon","juriste","justice","juteux","juvénile","kayak","kimono","kiosque","label","labial","labourer","lacérer","lactose","lagune","laine","laisser","laitier","lambeau","lamelle","lampe","lanceur","langage","lanterne","lapin","largeur","larme","laurier","lavabo","lavoir","lecture","légal","léger","légume","lessive","lettre","levier","lexique","lézard","liasse","libérer","libre","licence","licorne","liège","lièvre","ligature","ligoter","ligue","limer","limite","limonade","limpide","linéaire","lingot","lionceau","liquide","lisière","lister","lithium","litige","littoral","livreur","logique","lointain","loisir","lombric","loterie","louer","lourd","loutre","louve","loyal","lubie","lucide","lucratif","lueur","lugubre","luisant","lumière","lunaire","lundi","luron","lutter","luxueux","machine","magasin","magenta","magique","maigre","maillon","maintien","mairie","maison","majorer","malaxer","maléfice","malheur","malice","mallette","mammouth","mandater","maniable","manquant","manteau","manuel","marathon","marbre","marchand","mardi","maritime","marqueur","marron","marteler","mascotte","massif","matériel","matière","matraque","maudire","maussade","mauve","maximal","méchant","méconnu","médaille","médecin","méditer","méduse","meilleur","mélange","mélodie","membre","mémoire","menacer","mener","menhir","mensonge","mentor","mercredi","mérite","merle","messager","mesure","métal","météore","méthode","métier","meuble","miauler","microbe","miette","mignon","migrer","milieu","million","mimique","mince","minéral","minimal","minorer","minute","miracle","miroiter","missile","mixte","mobile","moderne","moelleux","mondial","moniteur","monnaie","monotone","monstre","montagne","monument","moqueur","morceau","morsure","mortier","moteur","motif","mouche","moufle","moulin","mousson","mouton","mouvant","multiple","munition","muraille","murène","murmure","muscle","muséum","musicien","mutation","muter","mutuel","myriade","myrtille","mystère","mythique","nageur","nappe","narquois","narrer","natation","nation","nature","naufrage","nautique","navire","nébuleux","nectar","néfaste","négation","négliger","négocier","neige","nerveux","nettoyer","neurone","neutron","neveu","niche","nickel","nitrate","niveau","noble","nocif","nocturne","noirceur","noisette","nomade","nombreux","nommer","normatif","notable","notifier","notoire","nourrir","nouveau","novateur","novembre","novice","nuage","nuancer","nuire","nuisible","numéro","nuptial","nuque","nutritif","obéir","objectif","obliger","obscur","observer","obstacle","obtenir","obturer","occasion","occuper","océan","octobre","octroyer","octupler","oculaire","odeur","odorant","offenser","officier","offrir","ogive","oiseau","oisillon","olfactif","olivier","ombrage","omettre","onctueux","onduler","onéreux","onirique","opale","opaque","opérer","opinion","opportun","opprimer","opter","optique","orageux","orange","orbite","ordonner","oreille","organe","orgueil","orifice","ornement","orque","ortie","osciller","osmose","ossature","otarie","ouragan","ourson","outil","outrager","ouvrage","ovation","oxyde","oxygène","ozone","paisible","palace","palmarès","palourde","palper","panache","panda","pangolin","paniquer","panneau","panorama","pantalon","papaye","papier","papoter","papyrus","paradoxe","parcelle","paresse","parfumer","parler","parole","parrain","parsemer","partager","parure","parvenir","passion","pastèque","paternel","patience","patron","pavillon","pavoiser","payer","paysage","peigne","peintre","pelage","pélican","pelle","pelouse","peluche","pendule","pénétrer","pénible","pensif","pénurie","pépite","péplum","perdrix","perforer","période","permuter","perplexe","persil","perte","peser","pétale","petit","pétrir","peuple","pharaon","phobie","phoque","photon","phrase","physique","piano","pictural","pièce","pierre","pieuvre","pilote","pinceau","pipette","piquer","pirogue","piscine","piston","pivoter","pixel","pizza","placard","plafond","plaisir","planer","plaque","plastron","plateau","pleurer","plexus","pliage","plomb","plonger","pluie","plumage","pochette","poésie","poète","pointe","poirier","poisson","poivre","polaire","policier","pollen","polygone","pommade","pompier","ponctuel","pondérer","poney","portique","position","posséder","posture","potager","poteau","potion","pouce","poulain","poumon","pourpre","poussin","pouvoir","prairie","pratique","précieux","prédire","préfixe","prélude","prénom","présence","prétexte","prévoir","primitif","prince","prison","priver","problème","procéder","prodige","profond","progrès","proie","projeter","prologue","promener","propre","prospère","protéger","prouesse","proverbe","prudence","pruneau","psychose","public","puceron","puiser","pulpe","pulsar","punaise","punitif","pupitre","purifier","puzzle","pyramide","quasar","querelle","question","quiétude","quitter","quotient","racine","raconter","radieux","ragondin","raideur","raisin","ralentir","rallonge","ramasser","rapide","rasage","ratisser","ravager","ravin","rayonner","réactif","réagir","réaliser","réanimer","recevoir","réciter","réclamer","récolter","recruter","reculer","recycler","rédiger","redouter","refaire","réflexe","réformer","refrain","refuge","régalien","région","réglage","régulier","réitérer","rejeter","rejouer","relatif","relever","relief","remarque","remède","remise","remonter","remplir","remuer","renard","renfort","renifler","renoncer","rentrer","renvoi","replier","reporter","reprise","reptile","requin","réserve","résineux","résoudre","respect","rester","résultat","rétablir","retenir","réticule","retomber","retracer","réunion","réussir","revanche","revivre","révolte","révulsif","richesse","rideau","rieur","rigide","rigoler","rincer","riposter","risible","risque","rituel","rival","rivière","rocheux","romance","rompre","ronce","rondin","roseau","rosier","rotatif","rotor","rotule","rouge","rouille","rouleau","routine","royaume","ruban","rubis","ruche","ruelle","rugueux","ruiner","ruisseau","ruser","rustique","rythme","sabler","saboter","sabre","sacoche","safari","sagesse","saisir","salade","salive","salon","saluer","samedi","sanction","sanglier","sarcasme","sardine","saturer","saugrenu","saumon","sauter","sauvage","savant","savonner","scalpel","scandale","scélérat","scénario","sceptre","schéma","science","scinder","score","scrutin","sculpter","séance","sécable","sécher","secouer","sécréter","sédatif","séduire","seigneur","séjour","sélectif","semaine","sembler","semence","séminal","sénateur","sensible","sentence","séparer","séquence","serein","sergent","sérieux","serrure","sérum","service","sésame","sévir","sevrage","sextuple","sidéral","siècle","siéger","siffler","sigle","signal","silence","silicium","simple","sincère","sinistre","siphon","sirop","sismique","situer","skier","social","socle","sodium","soigneux","soldat","soleil","solitude","soluble","sombre","sommeil","somnoler","sonde","songeur","sonnette","sonore","sorcier","sortir","sosie","sottise","soucieux","soudure","souffle","soulever","soupape","source","soutirer","souvenir","spacieux","spatial","spécial","sphère","spiral","stable","station","sternum","stimulus","stipuler","strict","studieux","stupeur","styliste","sublime","substrat","subtil","subvenir","succès","sucre","suffixe","suggérer","suiveur","sulfate","superbe","supplier","surface","suricate","surmener","surprise","sursaut","survie","suspect","syllabe","symbole","symétrie","synapse","syntaxe","système","tabac","tablier","tactile","tailler","talent","talisman","talonner","tambour","tamiser","tangible","tapis","taquiner","tarder","tarif","tartine","tasse","tatami","tatouage","taupe","taureau","taxer","témoin","temporel","tenaille","tendre","teneur","tenir","tension","terminer","terne","terrible","tétine","texte","thème","théorie","thérapie","thorax","tibia","tiède","timide","tirelire","tiroir","tissu","titane","titre","tituber","toboggan","tolérant","tomate","tonique","tonneau","toponyme","torche","tordre","tornade","torpille","torrent","torse","tortue","totem","toucher","tournage","tousser","toxine","traction","trafic","tragique","trahir","train","trancher","travail","trèfle","tremper","trésor","treuil","triage","tribunal","tricoter","trilogie","triomphe","tripler","triturer","trivial","trombone","tronc","tropical","troupeau","tuile","tulipe","tumulte","tunnel","turbine","tuteur","tutoyer","tuyau","tympan","typhon","typique","tyran","ubuesque","ultime","ultrason","unanime","unifier","union","unique","unitaire","univers","uranium","urbain","urticant","usage","usine","usuel","usure","utile","utopie","vacarme","vaccin","vagabond","vague","vaillant","vaincre","vaisseau","valable","valise","vallon","valve","vampire","vanille","vapeur","varier","vaseux","vassal","vaste","vecteur","vedette","végétal","véhicule","veinard","véloce","vendredi","vénérer","venger","venimeux","ventouse","verdure","vérin","vernir","verrou","verser","vertu","veston","vétéran","vétuste","vexant","vexer","viaduc","viande","victoire","vidange","vidéo","vignette","vigueur","vilain","village","vinaigre","violon","vipère","virement","virtuose","virus","visage","viseur","vision","visqueux","visuel","vital","vitesse","viticole","vitrine","vivace","vivipare","vocation","voguer","voile","voisin","voiture","volaille","volcan","voltiger","volume","vorace","vortex","voter","vouloir","voyage","voyelle","wagon","xénon","yacht","zèbre","zénith","zeste","zoologie"]// note all JSON files in this folder are generated with npm run generate-wordlist
const lookup = require('./lookup.json')

module.exports = {
  loadWordlist,
  detectLanguage
}

function loadWordlist (language) {
  switch (language) {
    case 'chinese_simplified': return require('./chinese_simplified.json')
    case 'chinese_traditional': return require('./chinese_traditional.json')
    case 'czech': return require('./czech.json')
    case 'english': return require('./english.json')
    case 'french': return require('./french.json')
    case 'italian': return require('./italian.json')
    case 'japanese': return require('./japanese.json')
    case 'korean': return require('./korean.json')
    case 'portuguese': return require('./portuguese.json')
    case 'russian': return require('./russian.json')
    case 'spanish': return require('./spanish.json')
    case 'turkish': return require('./turkish.json')
  }

  throw new Error('Unknown language: ' + language)
}

function detectLanguage (words) {
  let candidate = null

  for (const word of words) {
    const languages = lookup[word]
    if (!languages) return null

    if (languages.length === 1) return languages[0]

    if (!candidate) {
      candidate = languages
      continue
    }

    const intersect = candidate.filter(l => languages.includes(l))
    if (intersect.length === 1) return intersect[0]
  }

  return candidate[0]
}
["abaco","abbaglio","abbinato","abete","abisso","abolire","abrasivo","abrogato","accadere","accenno","accusato","acetone","achille","acido","acqua","acre","acrilico","acrobata","acuto","adagio","addebito","addome","adeguato","aderire","adipe","adottare","adulare","affabile","affetto","affisso","affranto","aforisma","afoso","africano","agave","agente","agevole","aggancio","agire","agitare","agonismo","agricolo","agrumeto","aguzzo","alabarda","alato","albatro","alberato","albo","albume","alce","alcolico","alettone","alfa","algebra","aliante","alibi","alimento","allagato","allegro","allievo","allodola","allusivo","almeno","alogeno","alpaca","alpestre","altalena","alterno","alticcio","altrove","alunno","alveolo","alzare","amalgama","amanita","amarena","ambito","ambrato","ameba","america","ametista","amico","ammasso","ammenda","ammirare","ammonito","amore","ampio","ampliare","amuleto","anacardo","anagrafe","analista","anarchia","anatra","anca","ancella","ancora","andare","andrea","anello","angelo","angolare","angusto","anima","annegare","annidato","anno","annuncio","anonimo","anticipo","anzi","apatico","apertura","apode","apparire","appetito","appoggio","approdo","appunto","aprile","arabica","arachide","aragosta","araldica","arancio","aratura","arazzo","arbitro","archivio","ardito","arenile","argento","argine","arguto","aria","armonia","arnese","arredato","arringa","arrosto","arsenico","arso","artefice","arzillo","asciutto","ascolto","asepsi","asettico","asfalto","asino","asola","aspirato","aspro","assaggio","asse","assoluto","assurdo","asta","astenuto","astice","astratto","atavico","ateismo","atomico","atono","attesa","attivare","attorno","attrito","attuale","ausilio","austria","autista","autonomo","autunno","avanzato","avere","avvenire","avviso","avvolgere","azione","azoto","azzimo","azzurro","babele","baccano","bacino","baco","badessa","badilata","bagnato","baita","balcone","baldo","balena","ballata","balzano","bambino","bandire","baraonda","barbaro","barca","baritono","barlume","barocco","basilico","basso","batosta","battuto","baule","bava","bavosa","becco","beffa","belgio","belva","benda","benevole","benigno","benzina","bere","berlina","beta","bibita","bici","bidone","bifido","biga","bilancia","bimbo","binocolo","biologo","bipede","bipolare","birbante","birra","biscotto","bisesto","bisnonno","bisonte","bisturi","bizzarro","blando","blatta","bollito","bonifico","bordo","bosco","botanico","bottino","bozzolo","braccio","bradipo","brama","branca","bravura","bretella","brevetto","brezza","briglia","brillante","brindare","broccolo","brodo","bronzina","brullo","bruno","bubbone","buca","budino","buffone","buio","bulbo","buono","burlone","burrasca","bussola","busta","cadetto","caduco","calamaro","calcolo","calesse","calibro","calmo","caloria","cambusa","camerata","camicia","cammino","camola","campale","canapa","candela","cane","canino","canotto","cantina","capace","capello","capitolo","capogiro","cappero","capra","capsula","carapace","carcassa","cardo","carisma","carovana","carretto","cartolina","casaccio","cascata","caserma","caso","cassone","castello","casuale","catasta","catena","catrame","cauto","cavillo","cedibile","cedrata","cefalo","celebre","cellulare","cena","cenone","centesimo","ceramica","cercare","certo","cerume","cervello","cesoia","cespo","ceto","chela","chiaro","chicca","chiedere","chimera","china","chirurgo","chitarra","ciao","ciclismo","cifrare","cigno","cilindro","ciottolo","circa","cirrosi","citrico","cittadino","ciuffo","civetta","civile","classico","clinica","cloro","cocco","codardo","codice","coerente","cognome","collare","colmato","colore","colposo","coltivato","colza","coma","cometa","commando","comodo","computer","comune","conciso","condurre","conferma","congelare","coniuge","connesso","conoscere","consumo","continuo","convegno","coperto","copione","coppia","copricapo","corazza","cordata","coricato","cornice","corolla","corpo","corredo","corsia","cortese","cosmico","costante","cottura","covato","cratere","cravatta","creato","credere","cremoso","crescita","creta","criceto","crinale","crisi","critico","croce","cronaca","crostata","cruciale","crusca","cucire","cuculo","cugino","cullato","cupola","curatore","cursore","curvo","cuscino","custode","dado","daino","dalmata","damerino","daniela","dannoso","danzare","datato","davanti","davvero","debutto","decennio","deciso","declino","decollo","decreto","dedicato","definito","deforme","degno","delegare","delfino","delirio","delta","demenza","denotato","dentro","deposito","derapata","derivare","deroga","descritto","deserto","desiderio","desumere","detersivo","devoto","diametro","dicembre","diedro","difeso","diffuso","digerire","digitale","diluvio","dinamico","dinnanzi","dipinto","diploma","dipolo","diradare","dire","dirotto","dirupo","disagio","discreto","disfare","disgelo","disposto","distanza","disumano","dito","divano","divelto","dividere","divorato","doblone","docente","doganale","dogma","dolce","domato","domenica","dominare","dondolo","dono","dormire","dote","dottore","dovuto","dozzina","drago","druido","dubbio","dubitare","ducale","duna","duomo","duplice","duraturo","ebano","eccesso","ecco","eclissi","economia","edera","edicola","edile","editoria","educare","egemonia","egli","egoismo","egregio","elaborato","elargire","elegante","elencato","eletto","elevare","elfico","elica","elmo","elsa","eluso","emanato","emblema","emesso","emiro","emotivo","emozione","empirico","emulo","endemico","enduro","energia","enfasi","enoteca","entrare","enzima","epatite","epilogo","episodio","epocale","eppure","equatore","erario","erba","erboso","erede","eremita","erigere","ermetico","eroe","erosivo","errante","esagono","esame","esanime","esaudire","esca","esempio","esercito","esibito","esigente","esistere","esito","esofago","esortato","esoso","espanso","espresso","essenza","esso","esteso","estimare","estonia","estroso","esultare","etilico","etnico","etrusco","etto","euclideo","europa","evaso","evidenza","evitato","evoluto","evviva","fabbrica","faccenda","fachiro","falco","famiglia","fanale","fanfara","fango","fantasma","fare","farfalla","farinoso","farmaco","fascia","fastoso","fasullo","faticare","fato","favoloso","febbre","fecola","fede","fegato","felpa","feltro","femmina","fendere","fenomeno","fermento","ferro","fertile","fessura","festivo","fetta","feudo","fiaba","fiducia","fifa","figurato","filo","finanza","finestra","finire","fiore","fiscale","fisico","fiume","flacone","flamenco","flebo","flemma","florido","fluente","fluoro","fobico","focaccia","focoso","foderato","foglio","folata","folclore","folgore","fondente","fonetico","fonia","fontana","forbito","forchetta","foresta","formica","fornaio","foro","fortezza","forzare","fosfato","fosso","fracasso","frana","frassino","fratello","freccetta","frenata","fresco","frigo","frollino","fronde","frugale","frutta","fucilata","fucsia","fuggente","fulmine","fulvo","fumante","fumetto","fumoso","fune","funzione","fuoco","furbo","furgone","furore","fuso","futile","gabbiano","gaffe","galateo","gallina","galoppo","gambero","gamma","garanzia","garbo","garofano","garzone","gasdotto","gasolio","gastrico","gatto","gaudio","gazebo","gazzella","geco","gelatina","gelso","gemello","gemmato","gene","genitore","gennaio","genotipo","gergo","ghepardo","ghiaccio","ghisa","giallo","gilda","ginepro","giocare","gioiello","giorno","giove","girato","girone","gittata","giudizio","giurato","giusto","globulo","glutine","gnomo","gobba","golf","gomito","gommone","gonfio","gonna","governo","gracile","grado","grafico","grammo","grande","grattare","gravoso","grazia","greca","gregge","grifone","grigio","grinza","grotta","gruppo","guadagno","guaio","guanto","guardare","gufo","guidare","ibernato","icona","identico","idillio","idolo","idra","idrico","idrogeno","igiene","ignaro","ignorato","ilare","illeso","illogico","illudere","imballo","imbevuto","imbocco","imbuto","immane","immerso","immolato","impacco","impeto","impiego","importo","impronta","inalare","inarcare","inattivo","incanto","incendio","inchino","incisivo","incluso","incontro","incrocio","incubo","indagine","india","indole","inedito","infatti","infilare","inflitto","ingaggio","ingegno","inglese","ingordo","ingrosso","innesco","inodore","inoltrare","inondato","insano","insetto","insieme","insonnia","insulina","intasato","intero","intonaco","intuito","inumidire","invalido","invece","invito","iperbole","ipnotico","ipotesi","ippica","iride","irlanda","ironico","irrigato","irrorare","isolato","isotopo","isterico","istituto","istrice","italia","iterare","labbro","labirinto","lacca","lacerato","lacrima","lacuna","laddove","lago","lampo","lancetta","lanterna","lardoso","larga","laringe","lastra","latenza","latino","lattuga","lavagna","lavoro","legale","leggero","lembo","lentezza","lenza","leone","lepre","lesivo","lessato","lesto","letterale","leva","levigato","libero","lido","lievito","lilla","limatura","limitare","limpido","lineare","lingua","liquido","lira","lirica","lisca","lite","litigio","livrea","locanda","lode","logica","lombare","londra","longevo","loquace","lorenzo","loto","lotteria","luce","lucidato","lumaca","luminoso","lungo","lupo","luppolo","lusinga","lusso","lutto","macabro","macchina","macero","macinato","madama","magico","maglia","magnete","magro","maiolica","malafede","malgrado","malinteso","malsano","malto","malumore","mana","mancia","mandorla","mangiare","manifesto","mannaro","manovra","mansarda","mantide","manubrio","mappa","maratona","marcire","maretta","marmo","marsupio","maschera","massaia","mastino","materasso","matricola","mattone","maturo","mazurca","meandro","meccanico","mecenate","medesimo","meditare","mega","melassa","melis","melodia","meninge","meno","mensola","mercurio","merenda","merlo","meschino","mese","messere","mestolo","metallo","metodo","mettere","miagolare","mica","micelio","michele","microbo","midollo","miele","migliore","milano","milite","mimosa","minerale","mini","minore","mirino","mirtillo","miscela","missiva","misto","misurare","mitezza","mitigare","mitra","mittente","mnemonico","modello","modifica","modulo","mogano","mogio","mole","molosso","monastero","monco","mondina","monetario","monile","monotono","monsone","montato","monviso","mora","mordere","morsicato","mostro","motivato","motosega","motto","movenza","movimento","mozzo","mucca","mucosa","muffa","mughetto","mugnaio","mulatto","mulinello","multiplo","mummia","munto","muovere","murale","musa","muscolo","musica","mutevole","muto","nababbo","nafta","nanometro","narciso","narice","narrato","nascere","nastrare","naturale","nautica","naviglio","nebulosa","necrosi","negativo","negozio","nemmeno","neofita","neretto","nervo","nessuno","nettuno","neutrale","neve","nevrotico","nicchia","ninfa","nitido","nobile","nocivo","nodo","nome","nomina","nordico","normale","norvegese","nostrano","notare","notizia","notturno","novella","nucleo","nulla","numero","nuovo","nutrire","nuvola","nuziale","oasi","obbedire","obbligo","obelisco","oblio","obolo","obsoleto","occasione","occhio","occidente","occorrere","occultare","ocra","oculato","odierno","odorare","offerta","offrire","offuscato","oggetto","oggi","ognuno","olandese","olfatto","oliato","oliva","ologramma","oltre","omaggio","ombelico","ombra","omega","omissione","ondoso","onere","onice","onnivoro","onorevole","onta","operato","opinione","opposto","oracolo","orafo","ordine","orecchino","orefice","orfano","organico","origine","orizzonte","orma","ormeggio","ornativo","orologio","orrendo","orribile","ortensia","ortica","orzata","orzo","osare","oscurare","osmosi","ospedale","ospite","ossa","ossidare","ostacolo","oste","otite","otre","ottagono","ottimo","ottobre","ovale","ovest","ovino","oviparo","ovocito","ovunque","ovviare","ozio","pacchetto","pace","pacifico","padella","padrone","paese","paga","pagina","palazzina","palesare","pallido","palo","palude","pandoro","pannello","paolo","paonazzo","paprica","parabola","parcella","parere","pargolo","pari","parlato","parola","partire","parvenza","parziale","passivo","pasticca","patacca","patologia","pattume","pavone","peccato","pedalare","pedonale","peggio","peloso","penare","pendice","penisola","pennuto","penombra","pensare","pentola","pepe","pepita","perbene","percorso","perdonato","perforare","pergamena","periodo","permesso","perno","perplesso","persuaso","pertugio","pervaso","pesatore","pesista","peso","pestifero","petalo","pettine","petulante","pezzo","piacere","pianta","piattino","piccino","picozza","piega","pietra","piffero","pigiama","pigolio","pigro","pila","pilifero","pillola","pilota","pimpante","pineta","pinna","pinolo","pioggia","piombo","piramide","piretico","pirite","pirolisi","pitone","pizzico","placebo","planare","plasma","platano","plenario","pochezza","poderoso","podismo","poesia","poggiare","polenta","poligono","pollice","polmonite","polpetta","polso","poltrona","polvere","pomice","pomodoro","ponte","popoloso","porfido","poroso","porpora","porre","portata","posa","positivo","possesso","postulato","potassio","potere","pranzo","prassi","pratica","precluso","predica","prefisso","pregiato","prelievo","premere","prenotare","preparato","presenza","pretesto","prevalso","prima","principe","privato","problema","procura","produrre","profumo","progetto","prolunga","promessa","pronome","proposta","proroga","proteso","prova","prudente","prugna","prurito","psiche","pubblico","pudica","pugilato","pugno","pulce","pulito","pulsante","puntare","pupazzo","pupilla","puro","quadro","qualcosa","quasi","querela","quota","raccolto","raddoppio","radicale","radunato","raffica","ragazzo","ragione","ragno","ramarro","ramingo","ramo","randagio","rantolare","rapato","rapina","rappreso","rasatura","raschiato","rasente","rassegna","rastrello","rata","ravveduto","reale","recepire","recinto","recluta","recondito","recupero","reddito","redimere","regalato","registro","regola","regresso","relazione","remare","remoto","renna","replica","reprimere","reputare","resa","residente","responso","restauro","rete","retina","retorica","rettifica","revocato","riassunto","ribadire","ribelle","ribrezzo","ricarica","ricco","ricevere","riciclato","ricordo","ricreduto","ridicolo","ridurre","rifasare","riflesso","riforma","rifugio","rigare","rigettato","righello","rilassato","rilevato","rimanere","rimbalzo","rimedio","rimorchio","rinascita","rincaro","rinforzo","rinnovo","rinomato","rinsavito","rintocco","rinuncia","rinvenire","riparato","ripetuto","ripieno","riportare","ripresa","ripulire","risata","rischio","riserva","risibile","riso","rispetto","ristoro","risultato","risvolto","ritardo","ritegno","ritmico","ritrovo","riunione","riva","riverso","rivincita","rivolto","rizoma","roba","robotico","robusto","roccia","roco","rodaggio","rodere","roditore","rogito","rollio","romantico","rompere","ronzio","rosolare","rospo","rotante","rotondo","rotula","rovescio","rubizzo","rubrica","ruga","rullino","rumine","rumoroso","ruolo","rupe","russare","rustico","sabato","sabbiare","sabotato","sagoma","salasso","saldatura","salgemma","salivare","salmone","salone","saltare","saluto","salvo","sapere","sapido","saporito","saraceno","sarcasmo","sarto","sassoso","satellite","satira","satollo","saturno","savana","savio","saziato","sbadiglio","sbalzo","sbancato","sbarra","sbattere","sbavare","sbendare","sbirciare","sbloccato","sbocciato","sbrinare","sbruffone","sbuffare","scabroso","scadenza","scala","scambiare","scandalo","scapola","scarso","scatenare","scavato","scelto","scenico","scettro","scheda","schiena","sciarpa","scienza","scindere","scippo","sciroppo","scivolo","sclerare","scodella","scolpito","scomparto","sconforto","scoprire","scorta","scossone","scozzese","scriba","scrollare","scrutinio","scuderia","scultore","scuola","scuro","scusare","sdebitare","sdoganare","seccatura","secondo","sedano","seggiola","segnalato","segregato","seguito","selciato","selettivo","sella","selvaggio","semaforo","sembrare","seme","seminato","sempre","senso","sentire","sepolto","sequenza","serata","serbato","sereno","serio","serpente","serraglio","servire","sestina","setola","settimana","sfacelo","sfaldare","sfamato","sfarzoso","sfaticato","sfera","sfida","sfilato","sfinge","sfocato","sfoderare","sfogo","sfoltire","sforzato","sfratto","sfruttato","sfuggito","sfumare","sfuso","sgabello","sgarbato","sgonfiare","sgorbio","sgrassato","sguardo","sibilo","siccome","sierra","sigla","signore","silenzio","sillaba","simbolo","simpatico","simulato","sinfonia","singolo","sinistro","sino","sintesi","sinusoide","sipario","sisma","sistole","situato","slitta","slogatura","sloveno","smarrito","smemorato","smentito","smeraldo","smilzo","smontare","smottato","smussato","snellire","snervato","snodo","sobbalzo","sobrio","soccorso","sociale","sodale","soffitto","sogno","soldato","solenne","solido","sollazzo","solo","solubile","solvente","somatico","somma","sonda","sonetto","sonnifero","sopire","soppeso","sopra","sorgere","sorpasso","sorriso","sorso","sorteggio","sorvolato","sospiro","sosta","sottile","spada","spalla","spargere","spatola","spavento","spazzola","specie","spedire","spegnere","spelatura","speranza","spessore","spettrale","spezzato","spia","spigoloso","spillato","spinoso","spirale","splendido","sportivo","sposo","spranga","sprecare","spronato","spruzzo","spuntino","squillo","sradicare","srotolato","stabile","stacco","staffa","stagnare","stampato","stantio","starnuto","stasera","statuto","stelo","steppa","sterzo","stiletto","stima","stirpe","stivale","stizzoso","stonato","storico","strappo","stregato","stridulo","strozzare","strutto","stuccare","stufo","stupendo","subentro","succoso","sudore","suggerito","sugo","sultano","suonare","superbo","supporto","surgelato","surrogato","sussurro","sutura","svagare","svedese","sveglio","svelare","svenuto","svezia","sviluppo","svista","svizzera","svolta","svuotare","tabacco","tabulato","tacciare","taciturno","tale","talismano","tampone","tannino","tara","tardivo","targato","tariffa","tarpare","tartaruga","tasto","tattico","taverna","tavolata","tazza","teca","tecnico","telefono","temerario","tempo","temuto","tendone","tenero","tensione","tentacolo","teorema","terme","terrazzo","terzetto","tesi","tesserato","testato","tetro","tettoia","tifare","tigella","timbro","tinto","tipico","tipografo","tiraggio","tiro","titanio","titolo","titubante","tizio","tizzone","toccare","tollerare","tolto","tombola","tomo","tonfo","tonsilla","topazio","topologia","toppa","torba","tornare","torrone","tortora","toscano","tossire","tostatura","totano","trabocco","trachea","trafila","tragedia","tralcio","tramonto","transito","trapano","trarre","trasloco","trattato","trave","treccia","tremolio","trespolo","tributo","tricheco","trifoglio","trillo","trincea","trio","tristezza","triturato","trivella","tromba","trono","troppo","trottola","trovare","truccato","tubatura","tuffato","tulipano","tumulto","tunisia","turbare","turchino","tuta","tutela","ubicato","uccello","uccisore","udire","uditivo","uffa","ufficio","uguale","ulisse","ultimato","umano","umile","umorismo","uncinetto","ungere","ungherese","unicorno","unificato","unisono","unitario","unte","uovo","upupa","uragano","urgenza","urlo","usanza","usato","uscito","usignolo","usuraio","utensile","utilizzo","utopia","vacante","vaccinato","vagabondo","vagliato","valanga","valgo","valico","valletta","valoroso","valutare","valvola","vampata","vangare","vanitoso","vano","vantaggio","vanvera","vapore","varano","varcato","variante","vasca","vedetta","vedova","veduto","vegetale","veicolo","velcro","velina","velluto","veloce","venato","vendemmia","vento","verace","verbale","vergogna","verifica","vero","verruca","verticale","vescica","vessillo","vestale","veterano","vetrina","vetusto","viandante","vibrante","vicenda","vichingo","vicinanza","vidimare","vigilia","vigneto","vigore","vile","villano","vimini","vincitore","viola","vipera","virgola","virologo","virulento","viscoso","visione","vispo","vissuto","visura","vita","vitello","vittima","vivanda","vivido","viziare","voce","voga","volatile","volere","volpe","voragine","vulcano","zampogna","zanna","zappato","zattera","zavorra","zefiro","zelante","zelo","zenzero","zerbino","zibetto","zinco","zircone","zitto","zolla","zotico","zucchero","zufolo","zulu","zuppa"]["あいこくしん","あいさつ","あいだ","あおぞら","あかちゃん","あきる","あけがた","あける","あこがれる","あさい","あさひ","あしあと","あじわう","あずかる","あずき","あそぶ","あたえる","あたためる","あたりまえ","あたる","あつい","あつかう","あっしゅく","あつまり","あつめる","あてな","あてはまる","あひる","あぶら","あぶる","あふれる","あまい","あまど","あまやかす","あまり","あみもの","あめりか","あやまる","あゆむ","あらいぐま","あらし","あらすじ","あらためる","あらゆる","あらわす","ありがとう","あわせる","あわてる","あんい","あんがい","あんこ","あんぜん","あんてい","あんない","あんまり","いいだす","いおん","いがい","いがく","いきおい","いきなり","いきもの","いきる","いくじ","いくぶん","いけばな","いけん","いこう","いこく","いこつ","いさましい","いさん","いしき","いじゅう","いじょう","いじわる","いずみ","いずれ","いせい","いせえび","いせかい","いせき","いぜん","いそうろう","いそがしい","いだい","いだく","いたずら","いたみ","いたりあ","いちおう","いちじ","いちど","いちば","いちぶ","いちりゅう","いつか","いっしゅん","いっせい","いっそう","いったん","いっち","いってい","いっぽう","いてざ","いてん","いどう","いとこ","いない","いなか","いねむり","いのち","いのる","いはつ","いばる","いはん","いびき","いひん","いふく","いへん","いほう","いみん","いもうと","いもたれ","いもり","いやがる","いやす","いよかん","いよく","いらい","いらすと","いりぐち","いりょう","いれい","いれもの","いれる","いろえんぴつ","いわい","いわう","いわかん","いわば","いわゆる","いんげんまめ","いんさつ","いんしょう","いんよう","うえき","うえる","うおざ","うがい","うかぶ","うかべる","うきわ","うくらいな","うくれれ","うけたまわる","うけつけ","うけとる","うけもつ","うける","うごかす","うごく","うこん","うさぎ","うしなう","うしろがみ","うすい","うすぎ","うすぐらい","うすめる","うせつ","うちあわせ","うちがわ","うちき","うちゅう","うっかり","うつくしい","うったえる","うつる","うどん","うなぎ","うなじ","うなずく","うなる","うねる","うのう","うぶげ","うぶごえ","うまれる","うめる","うもう","うやまう","うよく","うらがえす","うらぐち","うらない","うりあげ","うりきれ","うるさい","うれしい","うれゆき","うれる","うろこ","うわき","うわさ","うんこう","うんちん","うんてん","うんどう","えいえん","えいが","えいきょう","えいご","えいせい","えいぶん","えいよう","えいわ","えおり","えがお","えがく","えきたい","えくせる","えしゃく","えすて","えつらん","えのぐ","えほうまき","えほん","えまき","えもじ","えもの","えらい","えらぶ","えりあ","えんえん","えんかい","えんぎ","えんげき","えんしゅう","えんぜつ","えんそく","えんちょう","えんとつ","おいかける","おいこす","おいしい","おいつく","おうえん","おうさま","おうじ","おうせつ","おうたい","おうふく","おうべい","おうよう","おえる","おおい","おおう","おおどおり","おおや","おおよそ","おかえり","おかず","おがむ","おかわり","おぎなう","おきる","おくさま","おくじょう","おくりがな","おくる","おくれる","おこす","おこなう","おこる","おさえる","おさない","おさめる","おしいれ","おしえる","おじぎ","おじさん","おしゃれ","おそらく","おそわる","おたがい","おたく","おだやか","おちつく","おっと","おつり","おでかけ","おとしもの","おとなしい","おどり","おどろかす","おばさん","おまいり","おめでとう","おもいで","おもう","おもたい","おもちゃ","おやつ","おやゆび","およぼす","おらんだ","おろす","おんがく","おんけい","おんしゃ","おんせん","おんだん","おんちゅう","おんどけい","かあつ","かいが","がいき","がいけん","がいこう","かいさつ","かいしゃ","かいすいよく","かいぜん","かいぞうど","かいつう","かいてん","かいとう","かいふく","がいへき","かいほう","かいよう","がいらい","かいわ","かえる","かおり","かかえる","かがく","かがし","かがみ","かくご","かくとく","かざる","がぞう","かたい","かたち","がちょう","がっきゅう","がっこう","がっさん","がっしょう","かなざわし","かのう","がはく","かぶか","かほう","かほご","かまう","かまぼこ","かめれおん","かゆい","かようび","からい","かるい","かろう","かわく","かわら","がんか","かんけい","かんこう","かんしゃ","かんそう","かんたん","かんち","がんばる","きあい","きあつ","きいろ","ぎいん","きうい","きうん","きえる","きおう","きおく","きおち","きおん","きかい","きかく","きかんしゃ","ききて","きくばり","きくらげ","きけんせい","きこう","きこえる","きこく","きさい","きさく","きさま","きさらぎ","ぎじかがく","ぎしき","ぎじたいけん","ぎじにってい","ぎじゅつしゃ","きすう","きせい","きせき","きせつ","きそう","きぞく","きぞん","きたえる","きちょう","きつえん","ぎっちり","きつつき","きつね","きてい","きどう","きどく","きない","きなが","きなこ","きぬごし","きねん","きのう","きのした","きはく","きびしい","きひん","きふく","きぶん","きぼう","きほん","きまる","きみつ","きむずかしい","きめる","きもだめし","きもち","きもの","きゃく","きやく","ぎゅうにく","きよう","きょうりゅう","きらい","きらく","きりん","きれい","きれつ","きろく","ぎろん","きわめる","ぎんいろ","きんかくじ","きんじょ","きんようび","ぐあい","くいず","くうかん","くうき","くうぐん","くうこう","ぐうせい","くうそう","ぐうたら","くうふく","くうぼ","くかん","くきょう","くげん","ぐこう","くさい","くさき","くさばな","くさる","くしゃみ","くしょう","くすのき","くすりゆび","くせげ","くせん","ぐたいてき","くださる","くたびれる","くちこみ","くちさき","くつした","ぐっすり","くつろぐ","くとうてん","くどく","くなん","くねくね","くのう","くふう","くみあわせ","くみたてる","くめる","くやくしょ","くらす","くらべる","くるま","くれる","くろう","くわしい","ぐんかん","ぐんしょく","ぐんたい","ぐんて","けあな","けいかく","けいけん","けいこ","けいさつ","げいじゅつ","けいたい","げいのうじん","けいれき","けいろ","けおとす","けおりもの","げきか","げきげん","げきだん","げきちん","げきとつ","げきは","げきやく","げこう","げこくじょう","げざい","けさき","げざん","けしき","けしごむ","けしょう","げすと","けたば","けちゃっぷ","けちらす","けつあつ","けつい","けつえき","けっこん","けつじょ","けっせき","けってい","けつまつ","げつようび","げつれい","けつろん","げどく","けとばす","けとる","けなげ","けなす","けなみ","けぬき","げねつ","けねん","けはい","げひん","けぶかい","げぼく","けまり","けみかる","けむし","けむり","けもの","けらい","けろけろ","けわしい","けんい","けんえつ","けんお","けんか","げんき","けんげん","けんこう","けんさく","けんしゅう","けんすう","げんそう","けんちく","けんてい","けんとう","けんない","けんにん","げんぶつ","けんま","けんみん","けんめい","けんらん","けんり","こあくま","こいぬ","こいびと","ごうい","こうえん","こうおん","こうかん","ごうきゅう","ごうけい","こうこう","こうさい","こうじ","こうすい","ごうせい","こうそく","こうたい","こうちゃ","こうつう","こうてい","こうどう","こうない","こうはい","ごうほう","ごうまん","こうもく","こうりつ","こえる","こおり","ごかい","ごがつ","ごかん","こくご","こくさい","こくとう","こくない","こくはく","こぐま","こけい","こける","ここのか","こころ","こさめ","こしつ","こすう","こせい","こせき","こぜん","こそだて","こたい","こたえる","こたつ","こちょう","こっか","こつこつ","こつばん","こつぶ","こてい","こてん","ことがら","ことし","ことば","ことり","こなごな","こねこね","このまま","このみ","このよ","ごはん","こひつじ","こふう","こふん","こぼれる","ごまあぶら","こまかい","ごますり","こまつな","こまる","こむぎこ","こもじ","こもち","こもの","こもん","こやく","こやま","こゆう","こゆび","こよい","こよう","こりる","これくしょん","ころっけ","こわもて","こわれる","こんいん","こんかい","こんき","こんしゅう","こんすい","こんだて","こんとん","こんなん","こんびに","こんぽん","こんまけ","こんや","こんれい","こんわく","ざいえき","さいかい","さいきん","ざいげん","ざいこ","さいしょ","さいせい","ざいたく","ざいちゅう","さいてき","ざいりょう","さうな","さかいし","さがす","さかな","さかみち","さがる","さぎょう","さくし","さくひん","さくら","さこく","さこつ","さずかる","ざせき","さたん","さつえい","ざつおん","ざっか","ざつがく","さっきょく","ざっし","さつじん","ざっそう","さつたば","さつまいも","さてい","さといも","さとう","さとおや","さとし","さとる","さのう","さばく","さびしい","さべつ","さほう","さほど","さます","さみしい","さみだれ","さむけ","さめる","さやえんどう","さゆう","さよう","さよく","さらだ","ざるそば","さわやか","さわる","さんいん","さんか","さんきゃく","さんこう","さんさい","ざんしょ","さんすう","さんせい","さんそ","さんち","さんま","さんみ","さんらん","しあい","しあげ","しあさって","しあわせ","しいく","しいん","しうち","しえい","しおけ","しかい","しかく","じかん","しごと","しすう","じだい","したうけ","したぎ","したて","したみ","しちょう","しちりん","しっかり","しつじ","しつもん","してい","してき","してつ","じてん","じどう","しなぎれ","しなもの","しなん","しねま","しねん","しのぐ","しのぶ","しはい","しばかり","しはつ","しはらい","しはん","しひょう","しふく","じぶん","しへい","しほう","しほん","しまう","しまる","しみん","しむける","じむしょ","しめい","しめる","しもん","しゃいん","しゃうん","しゃおん","じゃがいも","しやくしょ","しゃくほう","しゃけん","しゃこ","しゃざい","しゃしん","しゃせん","しゃそう","しゃたい","しゃちょう","しゃっきん","じゃま","しゃりん","しゃれい","じゆう","じゅうしょ","しゅくはく","じゅしん","しゅっせき","しゅみ","しゅらば","じゅんばん","しょうかい","しょくたく","しょっけん","しょどう","しょもつ","しらせる","しらべる","しんか","しんこう","じんじゃ","しんせいじ","しんちく","しんりん","すあげ","すあし","すあな","ずあん","すいえい","すいか","すいとう","ずいぶん","すいようび","すうがく","すうじつ","すうせん","すおどり","すきま","すくう","すくない","すける","すごい","すこし","ずさん","すずしい","すすむ","すすめる","すっかり","ずっしり","ずっと","すてき","すてる","すねる","すのこ","すはだ","すばらしい","ずひょう","ずぶぬれ","すぶり","すふれ","すべて","すべる","ずほう","すぼん","すまい","すめし","すもう","すやき","すらすら","するめ","すれちがう","すろっと","すわる","すんぜん","すんぽう","せあぶら","せいかつ","せいげん","せいじ","せいよう","せおう","せかいかん","せきにん","せきむ","せきゆ","せきらんうん","せけん","せこう","せすじ","せたい","せたけ","せっかく","せっきゃく","ぜっく","せっけん","せっこつ","せっさたくま","せつぞく","せつだん","せつでん","せっぱん","せつび","せつぶん","せつめい","せつりつ","せなか","せのび","せはば","せびろ","せぼね","せまい","せまる","せめる","せもたれ","せりふ","ぜんあく","せんい","せんえい","せんか","せんきょ","せんく","せんげん","ぜんご","せんさい","せんしゅ","せんすい","せんせい","せんぞ","せんたく","せんちょう","せんてい","せんとう","せんぬき","せんねん","せんぱい","ぜんぶ","ぜんぽう","せんむ","せんめんじょ","せんもん","せんやく","せんゆう","せんよう","ぜんら","ぜんりゃく","せんれい","せんろ","そあく","そいとげる","そいね","そうがんきょう","そうき","そうご","そうしん","そうだん","そうなん","そうび","そうめん","そうり","そえもの","そえん","そがい","そげき","そこう","そこそこ","そざい","そしな","そせい","そせん","そそぐ","そだてる","そつう","そつえん","そっかん","そつぎょう","そっけつ","そっこう","そっせん","そっと","そとがわ","そとづら","そなえる","そなた","そふぼ","そぼく","そぼろ","そまつ","そまる","そむく","そむりえ","そめる","そもそも","そよかぜ","そらまめ","そろう","そんかい","そんけい","そんざい","そんしつ","そんぞく","そんちょう","ぞんび","ぞんぶん","そんみん","たあい","たいいん","たいうん","たいえき","たいおう","だいがく","たいき","たいぐう","たいけん","たいこ","たいざい","だいじょうぶ","だいすき","たいせつ","たいそう","だいたい","たいちょう","たいてい","だいどころ","たいない","たいねつ","たいのう","たいはん","だいひょう","たいふう","たいへん","たいほ","たいまつばな","たいみんぐ","たいむ","たいめん","たいやき","たいよう","たいら","たいりょく","たいる","たいわん","たうえ","たえる","たおす","たおる","たおれる","たかい","たかね","たきび","たくさん","たこく","たこやき","たさい","たしざん","だじゃれ","たすける","たずさわる","たそがれ","たたかう","たたく","ただしい","たたみ","たちばな","だっかい","だっきゃく","だっこ","だっしゅつ","だったい","たてる","たとえる","たなばた","たにん","たぬき","たのしみ","たはつ","たぶん","たべる","たぼう","たまご","たまる","だむる","ためいき","ためす","ためる","たもつ","たやすい","たよる","たらす","たりきほんがん","たりょう","たりる","たると","たれる","たれんと","たろっと","たわむれる","だんあつ","たんい","たんおん","たんか","たんき","たんけん","たんご","たんさん","たんじょうび","だんせい","たんそく","たんたい","だんち","たんてい","たんとう","だんな","たんにん","だんねつ","たんのう","たんぴん","だんぼう","たんまつ","たんめい","だんれつ","だんろ","だんわ","ちあい","ちあん","ちいき","ちいさい","ちえん","ちかい","ちから","ちきゅう","ちきん","ちけいず","ちけん","ちこく","ちさい","ちしき","ちしりょう","ちせい","ちそう","ちたい","ちたん","ちちおや","ちつじょ","ちてき","ちてん","ちぬき","ちぬり","ちのう","ちひょう","ちへいせん","ちほう","ちまた","ちみつ","ちみどろ","ちめいど","ちゃんこなべ","ちゅうい","ちゆりょく","ちょうし","ちょさくけん","ちらし","ちらみ","ちりがみ","ちりょう","ちるど","ちわわ","ちんたい","ちんもく","ついか","ついたち","つうか","つうじょう","つうはん","つうわ","つかう","つかれる","つくね","つくる","つけね","つける","つごう","つたえる","つづく","つつじ","つつむ","つとめる","つながる","つなみ","つねづね","つのる","つぶす","つまらない","つまる","つみき","つめたい","つもり","つもる","つよい","つるぼ","つるみく","つわもの","つわり","てあし","てあて","てあみ","ていおん","ていか","ていき","ていけい","ていこく","ていさつ","ていし","ていせい","ていたい","ていど","ていねい","ていひょう","ていへん","ていぼう","てうち","ておくれ","てきとう","てくび","でこぼこ","てさぎょう","てさげ","てすり","てそう","てちがい","てちょう","てつがく","てつづき","でっぱ","てつぼう","てつや","でぬかえ","てぬき","てぬぐい","てのひら","てはい","てぶくろ","てふだ","てほどき","てほん","てまえ","てまきずし","てみじか","てみやげ","てらす","てれび","てわけ","てわたし","でんあつ","てんいん","てんかい","てんき","てんぐ","てんけん","てんごく","てんさい","てんし","てんすう","でんち","てんてき","てんとう","てんない","てんぷら","てんぼうだい","てんめつ","てんらんかい","でんりょく","でんわ","どあい","といれ","どうかん","とうきゅう","どうぐ","とうし","とうむぎ","とおい","とおか","とおく","とおす","とおる","とかい","とかす","ときおり","ときどき","とくい","とくしゅう","とくてん","とくに","とくべつ","とけい","とける","とこや","とさか","としょかん","とそう","とたん","とちゅう","とっきゅう","とっくん","とつぜん","とつにゅう","とどける","ととのえる","とない","となえる","となり","とのさま","とばす","どぶがわ","とほう","とまる","とめる","ともだち","ともる","どようび","とらえる","とんかつ","どんぶり","ないかく","ないこう","ないしょ","ないす","ないせん","ないそう","なおす","ながい","なくす","なげる","なこうど","なさけ","なたでここ","なっとう","なつやすみ","ななおし","なにごと","なにもの","なにわ","なのか","なふだ","なまいき","なまえ","なまみ","なみだ","なめらか","なめる","なやむ","ならう","ならび","ならぶ","なれる","なわとび","なわばり","にあう","にいがた","にうけ","におい","にかい","にがて","にきび","にくしみ","にくまん","にげる","にさんかたんそ","にしき","にせもの","にちじょう","にちようび","にっか","にっき","にっけい","にっこう","にっさん","にっしょく","にっすう","にっせき","にってい","になう","にほん","にまめ","にもつ","にやり","にゅういん","にりんしゃ","にわとり","にんい","にんか","にんき","にんげん","にんしき","にんずう","にんそう","にんたい","にんち","にんてい","にんにく","にんぷ","にんまり","にんむ","にんめい","にんよう","ぬいくぎ","ぬかす","ぬぐいとる","ぬぐう","ぬくもり","ぬすむ","ぬまえび","ぬめり","ぬらす","ぬんちゃく","ねあげ","ねいき","ねいる","ねいろ","ねぐせ","ねくたい","ねくら","ねこぜ","ねこむ","ねさげ","ねすごす","ねそべる","ねだん","ねつい","ねっしん","ねつぞう","ねったいぎょ","ねぶそく","ねふだ","ねぼう","ねほりはほり","ねまき","ねまわし","ねみみ","ねむい","ねむたい","ねもと","ねらう","ねわざ","ねんいり","ねんおし","ねんかん","ねんきん","ねんぐ","ねんざ","ねんし","ねんちゃく","ねんど","ねんぴ","ねんぶつ","ねんまつ","ねんりょう","ねんれい","のいず","のおづま","のがす","のきなみ","のこぎり","のこす","のこる","のせる","のぞく","のぞむ","のたまう","のちほど","のっく","のばす","のはら","のべる","のぼる","のみもの","のやま","のらいぬ","のらねこ","のりもの","のりゆき","のれん","のんき","ばあい","はあく","ばあさん","ばいか","ばいく","はいけん","はいご","はいしん","はいすい","はいせん","はいそう","はいち","ばいばい","はいれつ","はえる","はおる","はかい","ばかり","はかる","はくしゅ","はけん","はこぶ","はさみ","はさん","はしご","ばしょ","はしる","はせる","ぱそこん","はそん","はたん","はちみつ","はつおん","はっかく","はづき","はっきり","はっくつ","はっけん","はっこう","はっさん","はっしん","はったつ","はっちゅう","はってん","はっぴょう","はっぽう","はなす","はなび","はにかむ","はぶらし","はみがき","はむかう","はめつ","はやい","はやし","はらう","はろうぃん","はわい","はんい","はんえい","はんおん","はんかく","はんきょう","ばんぐみ","はんこ","はんしゃ","はんすう","はんだん","ぱんち","ぱんつ","はんてい","はんとし","はんのう","はんぱ","はんぶん","はんぺん","はんぼうき","はんめい","はんらん","はんろん","ひいき","ひうん","ひえる","ひかく","ひかり","ひかる","ひかん","ひくい","ひけつ","ひこうき","ひこく","ひさい","ひさしぶり","ひさん","びじゅつかん","ひしょ","ひそか","ひそむ","ひたむき","ひだり","ひたる","ひつぎ","ひっこし","ひっし","ひつじゅひん","ひっす","ひつぜん","ぴったり","ぴっちり","ひつよう","ひてい","ひとごみ","ひなまつり","ひなん","ひねる","ひはん","ひびく","ひひょう","ひほう","ひまわり","ひまん","ひみつ","ひめい","ひめじし","ひやけ","ひやす","ひよう","びょうき","ひらがな","ひらく","ひりつ","ひりょう","ひるま","ひるやすみ","ひれい","ひろい","ひろう","ひろき","ひろゆき","ひんかく","ひんけつ","ひんこん","ひんしゅ","ひんそう","ぴんち","ひんぱん","びんぼう","ふあん","ふいうち","ふうけい","ふうせん","ぷうたろう","ふうとう","ふうふ","ふえる","ふおん","ふかい","ふきん","ふくざつ","ふくぶくろ","ふこう","ふさい","ふしぎ","ふじみ","ふすま","ふせい","ふせぐ","ふそく","ぶたにく","ふたん","ふちょう","ふつう","ふつか","ふっかつ","ふっき","ふっこく","ぶどう","ふとる","ふとん","ふのう","ふはい","ふひょう","ふへん","ふまん","ふみん","ふめつ","ふめん","ふよう","ふりこ","ふりる","ふるい","ふんいき","ぶんがく","ぶんぐ","ふんしつ","ぶんせき","ふんそう","ぶんぽう","へいあん","へいおん","へいがい","へいき","へいげん","へいこう","へいさ","へいしゃ","へいせつ","へいそ","へいたく","へいてん","へいねつ","へいわ","へきが","へこむ","べにいろ","べにしょうが","へらす","へんかん","べんきょう","べんごし","へんさい","へんたい","べんり","ほあん","ほいく","ぼうぎょ","ほうこく","ほうそう","ほうほう","ほうもん","ほうりつ","ほえる","ほおん","ほかん","ほきょう","ぼきん","ほくろ","ほけつ","ほけん","ほこう","ほこる","ほしい","ほしつ","ほしゅ","ほしょう","ほせい","ほそい","ほそく","ほたて","ほたる","ぽちぶくろ","ほっきょく","ほっさ","ほったん","ほとんど","ほめる","ほんい","ほんき","ほんけ","ほんしつ","ほんやく","まいにち","まかい","まかせる","まがる","まける","まこと","まさつ","まじめ","ますく","まぜる","まつり","まとめ","まなぶ","まぬけ","まねく","まほう","まもる","まゆげ","まよう","まろやか","まわす","まわり","まわる","まんが","まんきつ","まんぞく","まんなか","みいら","みうち","みえる","みがく","みかた","みかん","みけん","みこん","みじかい","みすい","みすえる","みせる","みっか","みつかる","みつける","みてい","みとめる","みなと","みなみかさい","みねらる","みのう","みのがす","みほん","みもと","みやげ","みらい","みりょく","みわく","みんか","みんぞく","むいか","むえき","むえん","むかい","むかう","むかえ","むかし","むぎちゃ","むける","むげん","むさぼる","むしあつい","むしば","むじゅん","むしろ","むすう","むすこ","むすぶ","むすめ","むせる","むせん","むちゅう","むなしい","むのう","むやみ","むよう","むらさき","むりょう","むろん","めいあん","めいうん","めいえん","めいかく","めいきょく","めいさい","めいし","めいそう","めいぶつ","めいれい","めいわく","めぐまれる","めざす","めした","めずらしい","めだつ","めまい","めやす","めんきょ","めんせき","めんどう","もうしあげる","もうどうけん","もえる","もくし","もくてき","もくようび","もちろん","もどる","もらう","もんく","もんだい","やおや","やける","やさい","やさしい","やすい","やすたろう","やすみ","やせる","やそう","やたい","やちん","やっと","やっぱり","やぶる","やめる","ややこしい","やよい","やわらかい","ゆうき","ゆうびんきょく","ゆうべ","ゆうめい","ゆけつ","ゆしゅつ","ゆせん","ゆそう","ゆたか","ゆちゃく","ゆでる","ゆにゅう","ゆびわ","ゆらい","ゆれる","ようい","ようか","ようきゅう","ようじ","ようす","ようちえん","よかぜ","よかん","よきん","よくせい","よくぼう","よけい","よごれる","よさん","よしゅう","よそう","よそく","よっか","よてい","よどがわく","よねつ","よやく","よゆう","よろこぶ","よろしい","らいう","らくがき","らくご","らくさつ","らくだ","らしんばん","らせん","らぞく","らたい","らっか","られつ","りえき","りかい","りきさく","りきせつ","りくぐん","りくつ","りけん","りこう","りせい","りそう","りそく","りてん","りねん","りゆう","りゅうがく","りよう","りょうり","りょかん","りょくちゃ","りょこう","りりく","りれき","りろん","りんご","るいけい","るいさい","るいじ","るいせき","るすばん","るりがわら","れいかん","れいぎ","れいせい","れいぞうこ","れいとう","れいぼう","れきし","れきだい","れんあい","れんけい","れんこん","れんさい","れんしゅう","れんぞく","れんらく","ろうか","ろうご","ろうじん","ろうそく","ろくが","ろこつ","ろじうら","ろしゅつ","ろせん","ろてん","ろめん","ろれつ","ろんぎ","ろんぱ","ろんぶん","ろんり","わかす","わかめ","わかやま","わかれる","わしつ","わじまし","わすれもの","わらう","われる"]["가격","가끔","가난","가능","가득","가르침","가뭄","가방","가상","가슴","가운데","가을","가이드","가입","가장","가정","가족","가죽","각오","각자","간격","간부","간섭","간장","간접","간판","갈등","갈비","갈색","갈증","감각","감기","감소","감수성","감자","감정","갑자기","강남","강당","강도","강력히","강변","강북","강사","강수량","강아지","강원도","강의","강제","강조","같이","개구리","개나리","개방","개별","개선","개성","개인","객관적","거실","거액","거울","거짓","거품","걱정","건강","건물","건설","건조","건축","걸음","검사","검토","게시판","게임","겨울","견해","결과","결국","결론","결석","결승","결심","결정","결혼","경계","경고","경기","경력","경복궁","경비","경상도","경영","경우","경쟁","경제","경주","경찰","경치","경향","경험","계곡","계단","계란","계산","계속","계약","계절","계층","계획","고객","고구려","고궁","고급","고등학생","고무신","고민","고양이","고장","고전","고집","고춧가루","고통","고향","곡식","골목","골짜기","골프","공간","공개","공격","공군","공급","공기","공동","공무원","공부","공사","공식","공업","공연","공원","공장","공짜","공책","공통","공포","공항","공휴일","과목","과일","과장","과정","과학","관객","관계","관광","관념","관람","관련","관리","관습","관심","관점","관찰","광경","광고","광장","광주","괴로움","굉장히","교과서","교문","교복","교실","교양","교육","교장","교직","교통","교환","교훈","구경","구름","구멍","구별","구분","구석","구성","구속","구역","구입","구청","구체적","국가","국기","국내","국립","국물","국민","국수","국어","국왕","국적","국제","국회","군대","군사","군인","궁극적","권리","권위","권투","귀국","귀신","규정","규칙","균형","그날","그냥","그늘","그러나","그룹","그릇","그림","그제서야","그토록","극복","극히","근거","근교","근래","근로","근무","근본","근원","근육","근처","글씨","글자","금강산","금고","금년","금메달","금액","금연","금요일","금지","긍정적","기간","기관","기념","기능","기독교","기둥","기록","기름","기법","기본","기분","기쁨","기숙사","기술","기억","기업","기온","기운","기원","기적","기준","기침","기혼","기획","긴급","긴장","길이","김밥","김치","김포공항","깍두기","깜빡","깨달음","깨소금","껍질","꼭대기","꽃잎","나들이","나란히","나머지","나물","나침반","나흘","낙엽","난방","날개","날씨","날짜","남녀","남대문","남매","남산","남자","남편","남학생","낭비","낱말","내년","내용","내일","냄비","냄새","냇물","냉동","냉면","냉방","냉장고","넥타이","넷째","노동","노란색","노력","노인","녹음","녹차","녹화","논리","논문","논쟁","놀이","농구","농담","농민","농부","농업","농장","농촌","높이","눈동자","눈물","눈썹","뉴욕","느낌","늑대","능동적","능력","다방","다양성","다음","다이어트","다행","단계","단골","단독","단맛","단순","단어","단위","단점","단체","단추","단편","단풍","달걀","달러","달력","달리","닭고기","담당","담배","담요","담임","답변","답장","당근","당분간","당연히","당장","대규모","대낮","대단히","대답","대도시","대략","대량","대륙","대문","대부분","대신","대응","대장","대전","대접","대중","대책","대출","대충","대통령","대학","대한민국","대합실","대형","덩어리","데이트","도대체","도덕","도둑","도망","도서관","도심","도움","도입","도자기","도저히","도전","도중","도착","독감","독립","독서","독일","독창적","동화책","뒷모습","뒷산","딸아이","마누라","마늘","마당","마라톤","마련","마무리","마사지","마약","마요네즈","마을","마음","마이크","마중","마지막","마찬가지","마찰","마흔","막걸리","막내","막상","만남","만두","만세","만약","만일","만점","만족","만화","많이","말기","말씀","말투","맘대로","망원경","매년","매달","매력","매번","매스컴","매일","매장","맥주","먹이","먼저","먼지","멀리","메일","며느리","며칠","면담","멸치","명단","명령","명예","명의","명절","명칭","명함","모금","모니터","모델","모든","모범","모습","모양","모임","모조리","모집","모퉁이","목걸이","목록","목사","목소리","목숨","목적","목표","몰래","몸매","몸무게","몸살","몸속","몸짓","몸통","몹시","무관심","무궁화","무더위","무덤","무릎","무슨","무엇","무역","무용","무조건","무지개","무척","문구","문득","문법","문서","문제","문학","문화","물가","물건","물결","물고기","물론","물리학","물음","물질","물체","미국","미디어","미사일","미술","미역","미용실","미움","미인","미팅","미혼","민간","민족","민주","믿음","밀가루","밀리미터","밑바닥","바가지","바구니","바나나","바늘","바닥","바닷가","바람","바이러스","바탕","박물관","박사","박수","반대","반드시","반말","반발","반성","반응","반장","반죽","반지","반찬","받침","발가락","발걸음","발견","발달","발레","발목","발바닥","발생","발음","발자국","발전","발톱","발표","밤하늘","밥그릇","밥맛","밥상","밥솥","방금","방면","방문","방바닥","방법","방송","방식","방안","방울","방지","방학","방해","방향","배경","배꼽","배달","배드민턴","백두산","백색","백성","백인","백제","백화점","버릇","버섯","버튼","번개","번역","번지","번호","벌금","벌레","벌써","범위","범인","범죄","법률","법원","법적","법칙","베이징","벨트","변경","변동","변명","변신","변호사","변화","별도","별명","별일","병실","병아리","병원","보관","보너스","보라색","보람","보름","보상","보안","보자기","보장","보전","보존","보통","보편적","보험","복도","복사","복숭아","복습","볶음","본격적","본래","본부","본사","본성","본인","본질","볼펜","봉사","봉지","봉투","부근","부끄러움","부담","부동산","부문","부분","부산","부상","부엌","부인","부작용","부장","부정","부족","부지런히","부친","부탁","부품","부회장","북부","북한","분노","분량","분리","분명","분석","분야","분위기","분필","분홍색","불고기","불과","불교","불꽃","불만","불법","불빛","불안","불이익","불행","브랜드","비극","비난","비닐","비둘기","비디오","비로소","비만","비명","비밀","비바람","비빔밥","비상","비용","비율","비중","비타민","비판","빌딩","빗물","빗방울","빗줄기","빛깔","빨간색","빨래","빨리","사건","사계절","사나이","사냥","사람","사랑","사립","사모님","사물","사방","사상","사생활","사설","사슴","사실","사업","사용","사월","사장","사전","사진","사촌","사춘기","사탕","사투리","사흘","산길","산부인과","산업","산책","살림","살인","살짝","삼계탕","삼국","삼십","삼월","삼촌","상관","상금","상대","상류","상반기","상상","상식","상업","상인","상자","상점","상처","상추","상태","상표","상품","상황","새벽","색깔","색연필","생각","생명","생물","생방송","생산","생선","생신","생일","생활","서랍","서른","서명","서민","서비스","서양","서울","서적","서점","서쪽","서클","석사","석유","선거","선물","선배","선생","선수","선원","선장","선전","선택","선풍기","설거지","설날","설렁탕","설명","설문","설사","설악산","설치","설탕","섭씨","성공","성당","성명","성별","성인","성장","성적","성질","성함","세금","세미나","세상","세월","세종대왕","세탁","센터","센티미터","셋째","소규모","소극적","소금","소나기","소년","소득","소망","소문","소설","소속","소아과","소용","소원","소음","소중히","소지품","소질","소풍","소형","속담","속도","속옷","손가락","손길","손녀","손님","손등","손목","손뼉","손실","손질","손톱","손해","솔직히","솜씨","송아지","송이","송편","쇠고기","쇼핑","수건","수년","수단","수돗물","수동적","수면","수명","수박","수상","수석","수술","수시로","수업","수염","수영","수입","수준","수집","수출","수컷","수필","수학","수험생","수화기","숙녀","숙소","숙제","순간","순서","순수","순식간","순위","숟가락","술병","술집","숫자","스님","스물","스스로","스승","스웨터","스위치","스케이트","스튜디오","스트레스","스포츠","슬쩍","슬픔","습관","습기","승객","승리","승부","승용차","승진","시각","시간","시골","시금치","시나리오","시댁","시리즈","시멘트","시민","시부모","시선","시설","시스템","시아버지","시어머니","시월","시인","시일","시작","시장","시절","시점","시중","시즌","시집","시청","시합","시험","식구","식기","식당","식량","식료품","식물","식빵","식사","식생활","식초","식탁","식품","신고","신규","신념","신문","신발","신비","신사","신세","신용","신제품","신청","신체","신화","실감","실내","실력","실례","실망","실수","실습","실시","실장","실정","실질적","실천","실체","실컷","실태","실패","실험","실현","심리","심부름","심사","심장","심정","심판","쌍둥이","씨름","씨앗","아가씨","아나운서","아드님","아들","아쉬움","아스팔트","아시아","아울러","아저씨","아줌마","아직","아침","아파트","아프리카","아픔","아홉","아흔","악기","악몽","악수","안개","안경","안과","안내","안녕","안동","안방","안부","안주","알루미늄","알코올","암시","암컷","압력","앞날","앞문","애인","애정","액수","앨범","야간","야단","야옹","약간","약국","약속","약수","약점","약품","약혼녀","양념","양력","양말","양배추","양주","양파","어둠","어려움","어른","어젯밤","어쨌든","어쩌다가","어쩐지","언니","언덕","언론","언어","얼굴","얼른","얼음","얼핏","엄마","업무","업종","업체","엉덩이","엉망","엉터리","엊그제","에너지","에어컨","엔진","여건","여고생","여관","여군","여권","여대생","여덟","여동생","여든","여론","여름","여섯","여성","여왕","여인","여전히","여직원","여학생","여행","역사","역시","역할","연결","연구","연극","연기","연락","연설","연세","연속","연습","연애","연예인","연인","연장","연주","연출","연필","연합","연휴","열기","열매","열쇠","열심히","열정","열차","열흘","염려","엽서","영국","영남","영상","영양","영역","영웅","영원히","영하","영향","영혼","영화","옆구리","옆방","옆집","예감","예금","예방","예산","예상","예선","예술","예습","예식장","예약","예전","예절","예정","예컨대","옛날","오늘","오락","오랫동안","오렌지","오로지","오른발","오븐","오십","오염","오월","오전","오직","오징어","오페라","오피스텔","오히려","옥상","옥수수","온갖","온라인","온몸","온종일","온통","올가을","올림픽","올해","옷차림","와이셔츠","와인","완성","완전","왕비","왕자","왜냐하면","왠지","외갓집","외국","외로움","외삼촌","외출","외침","외할머니","왼발","왼손","왼쪽","요금","요일","요즘","요청","용기","용서","용어","우산","우선","우승","우연히","우정","우체국","우편","운동","운명","운반","운전","운행","울산","울음","움직임","웃어른","웃음","워낙","원고","원래","원서","원숭이","원인","원장","원피스","월급","월드컵","월세","월요일","웨이터","위반","위법","위성","위원","위험","위협","윗사람","유난히","유럽","유명","유물","유산","유적","유치원","유학","유행","유형","육군","육상","육십","육체","은행","음력","음료","음반","음성","음식","음악","음주","의견","의논","의문","의복","의식","의심","의외로","의욕","의원","의학","이것","이곳","이념","이놈","이달","이대로","이동","이렇게","이력서","이론적","이름","이민","이발소","이별","이불","이빨","이상","이성","이슬","이야기","이용","이웃","이월","이윽고","이익","이전","이중","이튿날","이틀","이혼","인간","인격","인공","인구","인근","인기","인도","인류","인물","인생","인쇄","인연","인원","인재","인종","인천","인체","인터넷","인하","인형","일곱","일기","일단","일대","일등","일반","일본","일부","일상","일생","일손","일요일","일월","일정","일종","일주일","일찍","일체","일치","일행","일회용","임금","임무","입대","입력","입맛","입사","입술","입시","입원","입장","입학","자가용","자격","자극","자동","자랑","자부심","자식","자신","자연","자원","자율","자전거","자정","자존심","자판","작가","작년","작성","작업","작용","작은딸","작품","잔디","잔뜩","잔치","잘못","잠깐","잠수함","잠시","잠옷","잠자리","잡지","장관","장군","장기간","장래","장례","장르","장마","장면","장모","장미","장비","장사","장소","장식","장애인","장인","장점","장차","장학금","재능","재빨리","재산","재생","재작년","재정","재채기","재판","재학","재활용","저것","저고리","저곳","저녁","저런","저렇게","저번","저울","저절로","저축","적극","적당히","적성","적용","적응","전개","전공","전기","전달","전라도","전망","전문","전반","전부","전세","전시","전용","전자","전쟁","전주","전철","전체","전통","전혀","전후","절대","절망","절반","절약","절차","점검","점수","점심","점원","점점","점차","접근","접시","접촉","젓가락","정거장","정도","정류장","정리","정말","정면","정문","정반대","정보","정부","정비","정상","정성","정오","정원","정장","정지","정치","정확히","제공","제과점","제대로","제목","제발","제법","제삿날","제안","제일","제작","제주도","제출","제품","제한","조각","조건","조금","조깅","조명","조미료","조상","조선","조용히","조절","조정","조직","존댓말","존재","졸업","졸음","종교","종로","종류","종소리","종업원","종종","종합","좌석","죄인","주관적","주름","주말","주머니","주먹","주문","주민","주방","주변","주식","주인","주일","주장","주전자","주택","준비","줄거리","줄기","줄무늬","중간","중계방송","중국","중년","중단","중독","중반","중부","중세","중소기업","중순","중앙","중요","중학교","즉석","즉시","즐거움","증가","증거","증권","증상","증세","지각","지갑","지경","지극히","지금","지급","지능","지름길","지리산","지방","지붕","지식","지역","지우개","지원","지적","지점","지진","지출","직선","직업","직원","직장","진급","진동","진로","진료","진리","진짜","진찰","진출","진통","진행","질문","질병","질서","짐작","집단","집안","집중","짜증","찌꺼기","차남","차라리","차량","차림","차별","차선","차츰","착각","찬물","찬성","참가","참기름","참새","참석","참여","참외","참조","찻잔","창가","창고","창구","창문","창밖","창작","창조","채널","채점","책가방","책방","책상","책임","챔피언","처벌","처음","천국","천둥","천장","천재","천천히","철도","철저히","철학","첫날","첫째","청년","청바지","청소","청춘","체계","체력","체온","체육","체중","체험","초등학생","초반","초밥","초상화","초순","초여름","초원","초저녁","초점","초청","초콜릿","촛불","총각","총리","총장","촬영","최근","최상","최선","최신","최악","최종","추석","추억","추진","추천","추측","축구","축소","축제","축하","출근","출발","출산","출신","출연","출입","출장","출판","충격","충고","충돌","충분히","충청도","취업","취직","취향","치약","친구","친척","칠십","칠월","칠판","침대","침묵","침실","칫솔","칭찬","카메라","카운터","칼국수","캐릭터","캠퍼스","캠페인","커튼","컨디션","컬러","컴퓨터","코끼리","코미디","콘서트","콜라","콤플렉스","콩나물","쾌감","쿠데타","크림","큰길","큰딸","큰소리","큰아들","큰어머니","큰일","큰절","클래식","클럽","킬로","타입","타자기","탁구","탁자","탄생","태권도","태양","태풍","택시","탤런트","터널","터미널","테니스","테스트","테이블","텔레비전","토론","토마토","토요일","통계","통과","통로","통신","통역","통일","통장","통제","통증","통합","통화","퇴근","퇴원","퇴직금","튀김","트럭","특급","특별","특성","특수","특징","특히","튼튼히","티셔츠","파란색","파일","파출소","판결","판단","판매","판사","팔십","팔월","팝송","패션","팩스","팩시밀리","팬티","퍼센트","페인트","편견","편의","편지","편히","평가","평균","평생","평소","평양","평일","평화","포스터","포인트","포장","포함","표면","표정","표준","표현","품목","품질","풍경","풍속","풍습","프랑스","프린터","플라스틱","피곤","피망","피아노","필름","필수","필요","필자","필통","핑계","하느님","하늘","하드웨어","하룻밤","하반기","하숙집","하순","하여튼","하지만","하천","하품","하필","학과","학교","학급","학기","학년","학력","학번","학부모","학비","학생","학술","학습","학용품","학원","학위","학자","학점","한계","한글","한꺼번에","한낮","한눈","한동안","한때","한라산","한마디","한문","한번","한복","한식","한여름","한쪽","할머니","할아버지","할인","함께","함부로","합격","합리적","항공","항구","항상","항의","해결","해군","해답","해당","해물","해석","해설","해수욕장","해안","핵심","핸드백","햄버거","햇볕","햇살","행동","행복","행사","행운","행위","향기","향상","향수","허락","허용","헬기","현관","현금","현대","현상","현실","현장","현재","현지","혈액","협력","형부","형사","형수","형식","형제","형태","형편","혜택","호기심","호남","호랑이","호박","호텔","호흡","혹시","홀로","홈페이지","홍보","홍수","홍차","화면","화분","화살","화요일","화장","화학","확보","확인","확장","확정","환갑","환경","환영","환율","환자","활기","활동","활발히","활용","활짝","회견","회관","회복","회색","회원","회장","회전","횟수","횡단보도","효율적","후반","후춧가루","훈련","훨씬","휴식","휴일","흉내","흐름","흑백","흑인","흔적","흔히","흥미","흥분","희곡","희망","희생","흰색","힘껏"]{"的":["chinese_simplified","chinese_traditional"],"一":["chinese_simplified","chinese_traditional"],"是":["chinese_simplified","chinese_traditional"],"在":["chinese_simplified","chinese_traditional"],"不":["chinese_simplified","chinese_traditional"],"了":["chinese_simplified","chinese_traditional"],"有":["chinese_simplified","chinese_traditional"],"和":["chinese_simplified","chinese_traditional"],"人":["chinese_simplified","chinese_traditional"],"这":["chinese_simplified"],"中":["chinese_simplified","chinese_traditional"],"大":["chinese_simplified","chinese_traditional"],"为":["chinese_simplified"],"上":["chinese_simplified","chinese_traditional"],"个":["chinese_simplified"],"国":["chinese_simplified"],"我":["chinese_simplified","chinese_traditional"],"以":["chinese_simplified","chinese_traditional"],"要":["chinese_simplified","chinese_traditional"],"他":["chinese_simplified","chinese_traditional"],"时":["chinese_simplified"],"来":["chinese_simplified"],"用":["chinese_simplified","chinese_traditional"],"们":["chinese_simplified"],"生":["chinese_simplified","chinese_traditional"],"到":["chinese_simplified","chinese_traditional"],"作":["chinese_simplified","chinese_traditional"],"地":["chinese_simplified","chinese_traditional"],"于":["chinese_simplified"],"出":["chinese_simplified","chinese_traditional"],"就":["chinese_simplified","chinese_traditional"],"分":["chinese_simplified","chinese_traditional"],"对":["chinese_simplified"],"成":["chinese_simplified","chinese_traditional"],"会":["chinese_simplified"],"可":["chinese_simplified","chinese_traditional"],"主":["chinese_simplified","chinese_traditional"],"发":["chinese_simplified"],"年":["chinese_simplified","chinese_traditional"],"动":["chinese_simplified"],"同":["chinese_simplified","chinese_traditional"],"工":["chinese_simplified","chinese_traditional"],"也":["chinese_simplified","chinese_traditional"],"能":["chinese_simplified","chinese_traditional"],"下":["chinese_simplified","chinese_traditional"],"过":["chinese_simplified"],"子":["chinese_simplified","chinese_traditional"],"说":["chinese_simplified"],"产":["chinese_simplified"],"种":["chinese_simplified"],"面":["chinese_simplified","chinese_traditional"],"而":["chinese_simplified","chinese_traditional"],"方":["chinese_simplified","chinese_traditional"],"后":["chinese_simplified"],"多":["chinese_simplified","chinese_traditional"],"定":["chinese_simplified","chinese_traditional"],"行":["chinese_simplified","chinese_traditional"],"学":["chinese_simplified"],"法":["chinese_simplified","chinese_traditional"],"所":["chinese_simplified","chinese_traditional"],"民":["chinese_simplified","chinese_traditional"],"得":["chinese_simplified","chinese_traditional"],"经":["chinese_simplified"],"十":["chinese_simplified","chinese_traditional"],"三":["chinese_simplified","chinese_traditional"],"之":["chinese_simplified","chinese_traditional"],"进":["chinese_simplified"],"着":["chinese_simplified"],"等":["chinese_simplified","chinese_traditional"],"部":["chinese_simplified","chinese_traditional"],"度":["chinese_simplified","chinese_traditional"],"家":["chinese_simplified","chinese_traditional"],"电":["chinese_simplified"],"力":["chinese_simplified","chinese_traditional"],"里":["chinese_simplified"],"如":["chinese_simplified","chinese_traditional"],"水":["chinese_simplified","chinese_traditional"],"化":["chinese_simplified","chinese_traditional"],"高":["chinese_simplified","chinese_traditional"],"自":["chinese_simplified","chinese_traditional"],"二":["chinese_simplified","chinese_traditional"],"理":["chinese_simplified","chinese_traditional"],"起":["chinese_simplified","chinese_traditional"],"小":["chinese_simplified","chinese_traditional"],"物":["chinese_simplified","chinese_traditional"],"现":["chinese_simplified"],"实":["chinese_simplified"],"加":["chinese_simplified","chinese_traditional"],"量":["chinese_simplified","chinese_traditional"],"都":["chinese_simplified","chinese_traditional"],"两":["chinese_simplified"],"体":["chinese_simplified"],"制":["chinese_simplified","chinese_traditional"],"机":["chinese_simplified"],"当":["chinese_simplified"],"使":["chinese_simplified","chinese_traditional"],"点":["chinese_simplified"],"从":["chinese_simplified"],"业":["chinese_simplified"],"本":["chinese_simplified","chinese_traditional"],"去":["chinese_simplified","chinese_traditional"],"把":["chinese_simplified","chinese_traditional"],"性":["chinese_simplified","chinese_traditional"],"好":["chinese_simplified","chinese_traditional"],"应":["chinese_simplified"],"开":["chinese_simplified"],"它":["chinese_simplified","chinese_traditional"],"合":["chinese_simplified","chinese_traditional"],"还":["chinese_simplified"],"因":["chinese_simplified","chinese_traditional"],"由":["chinese_simplified","chinese_traditional"],"其":["chinese_simplified","chinese_traditional"],"些":["chinese_simplified","chinese_traditional"],"然":["chinese_simplified","chinese_traditional"],"前":["chinese_simplified","chinese_traditional"],"外":["chinese_simplified","chinese_traditional"],"天":["chinese_simplified","chinese_traditional"],"政":["chinese_simplified","chinese_traditional"],"四":["chinese_simplified","chinese_traditional"],"日":["chinese_simplified","chinese_traditional"],"那":["chinese_simplified","chinese_traditional"],"社":["chinese_simplified","chinese_traditional"],"义":["chinese_simplified"],"事":["chinese_simplified","chinese_traditional"],"平":["chinese_simplified","chinese_traditional"],"形":["chinese_simplified","chinese_traditional"],"相":["chinese_simplified","chinese_traditional"],"全":["chinese_simplified","chinese_traditional"],"表":["chinese_simplified","chinese_traditional"],"间":["chinese_simplified"],"样":["chinese_simplified"],"与":["chinese_simplified"],"关":["chinese_simplified"],"各":["chinese_simplified","chinese_traditional"],"重":["chinese_simplified","chinese_traditional"],"新":["chinese_simplified","chinese_traditional"],"线":["chinese_simplified"],"内":["chinese_simplified"],"数":["chinese_simplified"],"正":["chinese_simplified","chinese_traditional"],"心":["chinese_simplified","chinese_traditional"],"反":["chinese_simplified","chinese_traditional"],"你":["chinese_simplified","chinese_traditional"],"明":["chinese_simplified","chinese_traditional"],"看":["chinese_simplified","chinese_traditional"],"原":["chinese_simplified","chinese_traditional"],"又":["chinese_simplified","chinese_traditional"],"么":["chinese_simplified"],"利":["chinese_simplified","chinese_traditional"],"比":["chinese_simplified","chinese_traditional"],"或":["chinese_simplified","chinese_traditional"],"但":["chinese_simplified","chinese_traditional"],"质":["chinese_simplified"],"气":["chinese_simplified"],"第":["chinese_simplified","chinese_traditional"],"向":["chinese_simplified","chinese_traditional"],"道":["chinese_simplified","chinese_traditional"],"命":["chinese_simplified","chinese_traditional"],"此":["chinese_simplified","chinese_traditional"],"变":["chinese_simplified"],"条":["chinese_simplified"],"只":["chinese_simplified","chinese_traditional"],"没":["chinese_simplified"],"结":["chinese_simplified"],"解":["chinese_simplified","chinese_traditional"],"问":["chinese_simplified"],"意":["chinese_simplified","chinese_traditional"],"建":["chinese_simplified","chinese_traditional"],"月":["chinese_simplified","chinese_traditional"],"公":["chinese_simplified","chinese_traditional"],"无":["chinese_simplified"],"系":["chinese_simplified","chinese_traditional"],"军":["chinese_simplified"],"很":["chinese_simplified","chinese_traditional"],"情":["chinese_simplified","chinese_traditional"],"者":["chinese_simplified","chinese_traditional"],"最":["chinese_simplified","chinese_traditional"],"立":["chinese_simplified","chinese_traditional"],"代":["chinese_simplified","chinese_traditional"],"想":["chinese_simplified","chinese_traditional"],"已":["chinese_simplified","chinese_traditional"],"通":["chinese_simplified","chinese_traditional"],"并":["chinese_simplified"],"提":["chinese_simplified","chinese_traditional"],"直":["chinese_simplified","chinese_traditional"],"题":["chinese_simplified"],"党":["chinese_simplified"],"程":["chinese_simplified","chinese_traditional"],"展":["chinese_simplified","chinese_traditional"],"五":["chinese_simplified","chinese_traditional"],"果":["chinese_simplified","chinese_traditional"],"料":["chinese_simplified","chinese_traditional"],"象":["chinese_simplified","chinese_traditional"],"员":["chinese_simplified"],"革":["chinese_simplified","chinese_traditional"],"位":["chinese_simplified","chinese_traditional"],"入":["chinese_simplified","chinese_traditional"],"常":["chinese_simplified","chinese_traditional"],"文":["chinese_simplified","chinese_traditional"],"总":["chinese_simplified"],"次":["chinese_simplified","chinese_traditional"],"品":["chinese_simplified","chinese_traditional"],"式":["chinese_simplified","chinese_traditional"],"活":["chinese_simplified","chinese_traditional"],"设":["chinese_simplified"],"及":["chinese_simplified","chinese_traditional"],"管":["chinese_simplified","chinese_traditional"],"特":["chinese_simplified","chinese_traditional"],"件":["chinese_simplified","chinese_traditional"],"长":["chinese_simplified"],"求":["chinese_simplified","chinese_traditional"],"老":["chinese_simplified","chinese_traditional"],"头":["chinese_simplified"],"基":["chinese_simplified","chinese_traditional"],"资":["chinese_simplified"],"边":["chinese_simplified"],"流":["chinese_simplified","chinese_traditional"],"路":["chinese_simplified","chinese_traditional"],"级":["chinese_simplified"],"少":["chinese_simplified","chinese_traditional"],"图":["chinese_simplified"],"山":["chinese_simplified","chinese_traditional"],"统":["chinese_simplified"],"接":["chinese_simplified","chinese_traditional"],"知":["chinese_simplified","chinese_traditional"],"较":["chinese_simplified"],"将":["chinese_simplified"],"组":["chinese_simplified"],"见":["chinese_simplified"],"计":["chinese_simplified"],"别":["chinese_simplified"],"她":["chinese_simplified","chinese_traditional"],"手":["chinese_simplified","chinese_traditional"],"角":["chinese_simplified","chinese_traditional"],"期":["chinese_simplified","chinese_traditional"],"根":["chinese_simplified","chinese_traditional"],"论":["chinese_simplified"],"运":["chinese_simplified"],"农":["chinese_simplified"],"指":["chinese_simplified","chinese_traditional"],"几":["chinese_simplified"],"九":["chinese_simplified","chinese_traditional"],"区":["chinese_simplified"],"强":["chinese_simplified"],"放":["chinese_simplified","chinese_traditional"],"决":["chinese_simplified"],"西":["chinese_simplified","chinese_traditional"],"被":["chinese_simplified","chinese_traditional"],"干":["chinese_simplified"],"做":["chinese_simplified","chinese_traditional"],"必":["chinese_simplified","chinese_traditional"],"战":["chinese_simplified"],"先":["chinese_simplified","chinese_traditional"],"回":["chinese_simplified","chinese_traditional"],"则":["chinese_simplified"],"任":["chinese_simplified","chinese_traditional"],"取":["chinese_simplified","chinese_traditional"],"据":["chinese_simplified"],"处":["chinese_simplified"],"队":["chinese_simplified"],"南":["chinese_simplified","chinese_traditional"],"给":["chinese_simplified"],"色":["chinese_simplified","chinese_traditional"],"光":["chinese_simplified","chinese_traditional"],"门":["chinese_simplified"],"即":["chinese_simplified","chinese_traditional"],"保":["chinese_simplified","chinese_traditional"],"治":["chinese_simplified","chinese_traditional"],"北":["chinese_simplified","chinese_traditional"],"造":["chinese_simplified","chinese_traditional"],"百":["chinese_simplified","chinese_traditional"],"规":["chinese_simplified"],"热":["chinese_simplified"],"领":["chinese_simplified"],"七":["chinese_simplified","chinese_traditional"],"海":["chinese_simplified","chinese_traditional"],"口":["chinese_simplified","chinese_traditional"],"东":["chinese_simplified"],"导":["chinese_simplified"],"器":["chinese_simplified","chinese_traditional"],"压":["chinese_simplified"],"志":["chinese_simplified","chinese_traditional"],"世":["chinese_simplified","chinese_traditional"],"金":["chinese_simplified","chinese_traditional"],"增":["chinese_simplified","chinese_traditional"],"争":["chinese_simplified"],"济":["chinese_simplified"],"阶":["chinese_simplified"],"油":["chinese_simplified","chinese_traditional"],"思":["chinese_simplified","chinese_traditional"],"术":["chinese_simplified"],"极":["chinese_simplified"],"交":["chinese_simplified","chinese_traditional"],"受":["chinese_simplified","chinese_traditional"],"联":["chinese_simplified"],"什":["chinese_simplified","chinese_traditional"],"认":["chinese_simplified"],"六":["chinese_simplified","chinese_traditional"],"共":["chinese_simplified","chinese_traditional"],"权":["chinese_simplified"],"收":["chinese_simplified","chinese_traditional"],"证":["chinese_simplified"],"改":["chinese_simplified","chinese_traditional"],"清":["chinese_simplified","chinese_traditional"],"美":["chinese_simplified","chinese_traditional"],"再":["chinese_simplified","chinese_traditional"],"采":["chinese_simplified"],"转":["chinese_simplified"],"更":["chinese_simplified","chinese_traditional"],"单":["chinese_simplified"],"风":["chinese_simplified"],"切":["chinese_simplified","chinese_traditional"],"打":["chinese_simplified","chinese_traditional"],"白":["chinese_simplified","chinese_traditional"],"教":["chinese_simplified","chinese_traditional"],"速":["chinese_simplified","chinese_traditional"],"花":["chinese_simplified","chinese_traditional"],"带":["chinese_simplified"],"安":["chinese_simplified","chinese_traditional"],"场":["chinese_simplified"],"身":["chinese_simplified","chinese_traditional"],"车":["chinese_simplified"],"例":["chinese_simplified","chinese_traditional"],"真":["chinese_simplified","chinese_traditional"],"务":["chinese_simplified"],"具":["chinese_simplified","chinese_traditional"],"万":["chinese_simplified"],"每":["chinese_simplified","chinese_traditional"],"目":["chinese_simplified","chinese_traditional"],"至":["chinese_simplified","chinese_traditional"],"达":["chinese_simplified"],"走":["chinese_simplified","chinese_traditional"],"积":["chinese_simplified"],"示":["chinese_simplified","chinese_traditional"],"议":["chinese_simplified"],"声":["chinese_simplified"],"报":["chinese_simplified"],"斗":["chinese_simplified"],"完":["chinese_simplified","chinese_traditional"],"类":["chinese_simplified"],"八":["chinese_simplified","chinese_traditional"],"离":["chinese_simplified"],"华":["chinese_simplified"],"名":["chinese_simplified","chinese_traditional"],"确":["chinese_simplified"],"才":["chinese_simplified","chinese_traditional"],"科":["chinese_simplified","chinese_traditional"],"张":["chinese_simplified"],"信":["chinese_simplified","chinese_traditional"],"马":["chinese_simplified"],"节":["chinese_simplified"],"话":["chinese_simplified"],"米":["chinese_simplified","chinese_traditional"],"整":["chinese_simplified","chinese_traditional"],"空":["chinese_simplified","chinese_traditional"],"元":["chinese_simplified","chinese_traditional"],"况":["chinese_simplified"],"今":["chinese_simplified","chinese_traditional"],"集":["chinese_simplified","chinese_traditional"],"温":["chinese_simplified"],"传":["chinese_simplified"],"土":["chinese_simplified","chinese_traditional"],"许":["chinese_simplified"],"步":["chinese_simplified","chinese_traditional"],"群":["chinese_simplified","chinese_traditional"],"广":["chinese_simplified"],"石":["chinese_simplified","chinese_traditional"],"记":["chinese_simplified"],"需":["chinese_simplified","chinese_traditional"],"段":["chinese_simplified","chinese_traditional"],"研":["chinese_simplified","chinese_traditional"],"界":["chinese_simplified","chinese_traditional"],"拉":["chinese_simplified","chinese_traditional"],"林":["chinese_simplified","chinese_traditional"],"律":["chinese_simplified","chinese_traditional"],"叫":["chinese_simplified","chinese_traditional"],"且":["chinese_simplified","chinese_traditional"],"究":["chinese_simplified","chinese_traditional"],"观":["chinese_simplified"],"越":["chinese_simplified","chinese_traditional"],"织":["chinese_simplified"],"装":["chinese_simplified"],"影":["chinese_simplified","chinese_traditional"],"算":["chinese_simplified","chinese_traditional"],"低":["chinese_simplified","chinese_traditional"],"持":["chinese_simplified","chinese_traditional"],"音":["chinese_simplified","chinese_traditional"],"众":["chinese_simplified"],"书":["chinese_simplified"],"布":["chinese_simplified","chinese_traditional"],"复":["chinese_simplified","chinese_traditional"],"容":["chinese_simplified","chinese_traditional"],"儿":["chinese_simplified"],"须":["chinese_simplified"],"际":["chinese_simplified"],"商":["chinese_simplified","chinese_traditional"],"非":["chinese_simplified","chinese_traditional"],"验":["chinese_simplified"],"连":["chinese_simplified"],"断":["chinese_simplified"],"深":["chinese_simplified","chinese_traditional"],"难":["chinese_simplified"],"近":["chinese_simplified","chinese_traditional"],"矿":["chinese_simplified"],"千":["chinese_simplified","chinese_traditional"],"周":["chinese_simplified"],"委":["chinese_simplified","chinese_traditional"],"素":["chinese_simplified","chinese_traditional"],"技":["chinese_simplified","chinese_traditional"],"备":["chinese_simplified"],"半":["chinese_simplified","chinese_traditional"],"办":["chinese_simplified"],"青":["chinese_simplified","chinese_traditional"],"省":["chinese_simplified","chinese_traditional"],"列":["chinese_simplified","chinese_traditional"],"习":["chinese_simplified"],"响":["chinese_simplified"],"约":["chinese_simplified"],"支":["chinese_simplified","chinese_traditional"],"般":["chinese_simplified","chinese_traditional"],"史":["chinese_simplified","chinese_traditional"],"感":["chinese_simplified","chinese_traditional"],"劳":["chinese_simplified"],"便":["chinese_simplified","chinese_traditional"],"团":["chinese_simplified"],"往":["chinese_simplified","chinese_traditional"],"酸":["chinese_simplified","chinese_traditional"],"历":["chinese_simplified"],"市":["chinese_simplified","chinese_traditional"],"克":["chinese_simplified","chinese_traditional"],"何":["chinese_simplified","chinese_traditional"],"除":["chinese_simplified","chinese_traditional"],"消":["chinese_simplified","chinese_traditional"],"构":["chinese_simplified"],"府":["chinese_simplified","chinese_traditional"],"称":["chinese_simplified"],"太":["chinese_simplified","chinese_traditional"],"准":["chinese_simplified"],"精":["chinese_simplified","chinese_traditional"],"值":["chinese_simplified","chinese_traditional"],"号":["chinese_simplified"],"率":["chinese_simplified","chinese_traditional"],"族":["chinese_simplified","chinese_traditional"],"维":["chinese_simplified"],"划":["chinese_simplified"],"选":["chinese_simplified"],"标":["chinese_simplified"],"写":["chinese_simplified"],"存":["chinese_simplified","chinese_traditional"],"候":["chinese_simplified","chinese_traditional"],"毛":["chinese_simplified","chinese_traditional"],"亲":["chinese_simplified"],"快":["chinese_simplified","chinese_traditional"],"效":["chinese_simplified","chinese_traditional"],"斯":["chinese_simplified","chinese_traditional"],"院":["chinese_simplified","chinese_traditional"],"查":["chinese_simplified","chinese_traditional"],"江":["chinese_simplified","chinese_traditional"],"型":["chinese_simplified","chinese_traditional"],"眼":["chinese_simplified","chinese_traditional"],"王":["chinese_simplified","chinese_traditional"],"按":["chinese_simplified","chinese_traditional"],"格":["chinese_simplified","chinese_traditional"],"养":["chinese_simplified"],"易":["chinese_simplified","chinese_traditional"],"置":["chinese_simplified","chinese_traditional"],"派":["chinese_simplified","chinese_traditional"],"层":["chinese_simplified"],"片":["chinese_simplified","chinese_traditional"],"始":["chinese_simplified","chinese_traditional"],"却":["chinese_simplified"],"专":["chinese_simplified"],"状":["chinese_simplified"],"育":["chinese_simplified","chinese_traditional"],"厂":["chinese_simplified"],"京":["chinese_simplified","chinese_traditional"],"识":["chinese_simplified"],"适":["chinese_simplified"],"属":["chinese_simplified"],"圆":["chinese_simplified"],"包":["chinese_simplified","chinese_traditional"],"火":["chinese_simplified","chinese_traditional"],"住":["chinese_simplified","chinese_traditional"],"调":["chinese_simplified"],"满":["chinese_simplified"],"县":["chinese_simplified"],"局":["chinese_simplified","chinese_traditional"],"照":["chinese_simplified","chinese_traditional"],"参":["chinese_simplified"],"红":["chinese_simplified"],"细":["chinese_simplified"],"引":["chinese_simplified","chinese_traditional"],"听":["chinese_simplified"],"该":["chinese_simplified"],"铁":["chinese_simplified"],"价":["chinese_simplified"],"严":["chinese_simplified"],"首":["chinese_simplified","chinese_traditional"],"底":["chinese_simplified","chinese_traditional"],"液":["chinese_simplified","chinese_traditional"],"官":["chinese_simplified","chinese_traditional"],"德":["chinese_simplified","chinese_traditional"],"随":["chinese_simplified"],"病":["chinese_simplified","chinese_traditional"],"苏":["chinese_simplified"],"失":["chinese_simplified","chinese_traditional"],"尔":["chinese_simplified"],"死":["chinese_simplified","chinese_traditional"],"讲":["chinese_simplified"],"配":["chinese_simplified","chinese_traditional"],"女":["chinese_simplified","chinese_traditional"],"黄":["chinese_simplified"],"推":["chinese_simplified","chinese_traditional"],"显":["chinese_simplified"],"谈":["chinese_simplified"],"罪":["chinese_simplified","chinese_traditional"],"神":["chinese_simplified","chinese_traditional"],"艺":["chinese_simplified"],"呢":["chinese_simplified","chinese_traditional"],"席":["chinese_simplified","chinese_traditional"],"含":["chinese_simplified","chinese_traditional"],"企":["chinese_simplified","chinese_traditional"],"望":["chinese_simplified","chinese_traditional"],"密":["chinese_simplified","chinese_traditional"],"批":["chinese_simplified","chinese_traditional"],"营":["chinese_simplified"],"项":["chinese_simplified"],"防":["chinese_simplified","chinese_traditional"],"举":["chinese_simplified"],"球":["chinese_simplified","chinese_traditional"],"英":["chinese_simplified","chinese_traditional"],"氧":["chinese_simplified","chinese_traditional"],"势":["chinese_simplified"],"告":["chinese_simplified","chinese_traditional"],"李":["chinese_simplified","chinese_traditional"],"台":["chinese_simplified","chinese_traditional"],"落":["chinese_simplified","chinese_traditional"],"木":["chinese_simplified","chinese_traditional"],"帮":["chinese_simplified"],"轮":["chinese_simplified"],"破":["chinese_simplified","chinese_traditional"],"亚":["chinese_simplified"],"师":["chinese_simplified"],"围":["chinese_simplified"],"注":["chinese_simplified","chinese_traditional"],"远":["chinese_simplified"],"字":["chinese_simplified","chinese_traditional"],"材":["chinese_simplified","chinese_traditional"],"排":["chinese_simplified","chinese_traditional"],"供":["chinese_simplified","chinese_traditional"],"河":["chinese_simplified","chinese_traditional"],"态":["chinese_simplified"],"封":["chinese_simplified","chinese_traditional"],"另":["chinese_simplified","chinese_traditional"],"施":["chinese_simplified","chinese_traditional"],"减":["chinese_simplified"],"树":["chinese_simplified"],"溶":["chinese_simplified","chinese_traditional"],"怎":["chinese_simplified","chinese_traditional"],"止":["chinese_simplified","chinese_traditional"],"案":["chinese_simplified","chinese_traditional"],"言":["chinese_simplified","chinese_traditional"],"士":["chinese_simplified","chinese_traditional"],"均":["chinese_simplified","chinese_traditional"],"武":["chinese_simplified","chinese_traditional"],"固":["chinese_simplified","chinese_traditional"],"叶":["chinese_simplified"],"鱼":["chinese_simplified"],"波":["chinese_simplified","chinese_traditional"],"视":["chinese_simplified"],"仅":["chinese_simplified"],"费":["chinese_simplified"],"紧":["chinese_simplified"],"爱":["chinese_simplified"],"左":["chinese_simplified","chinese_traditional"],"章":["chinese_simplified","chinese_traditional"],"早":["chinese_simplified","chinese_traditional"],"朝":["chinese_simplified","chinese_traditional"],"害":["chinese_simplified","chinese_traditional"],"续":["chinese_simplified"],"轻":["chinese_simplified"],"服":["chinese_simplified","chinese_traditional"],"试":["chinese_simplified"],"食":["chinese_simplified","chinese_traditional"],"充":["chinese_simplified","chinese_traditional"],"兵":["chinese_simplified","chinese_traditional"],"源":["chinese_simplified","chinese_traditional"],"判":["chinese_simplified","chinese_traditional"],"护":["chinese_simplified"],"司":["chinese_simplified","chinese_traditional"],"足":["chinese_simplified","chinese_traditional"],"某":["chinese_simplified","chinese_traditional"],"练":["chinese_simplified"],"差":["chinese_simplified","chinese_traditional"],"致":["chinese_simplified","chinese_traditional"],"板":["chinese_simplified","chinese_traditional"],"田":["chinese_simplified","chinese_traditional"],"降":["chinese_simplified","chinese_traditional"],"黑":["chinese_simplified","chinese_traditional"],"犯":["chinese_simplified","chinese_traditional"],"负":["chinese_simplified"],"击":["chinese_simplified"],"范":["chinese_simplified","chinese_traditional"],"继":["chinese_simplified"],"兴":["chinese_simplified"],"似":["chinese_simplified","chinese_traditional"],"余":["chinese_simplified"],"坚":["chinese_simplified"],"曲":["chinese_simplified","chinese_traditional"],"输":["chinese_simplified"],"修":["chinese_simplified","chinese_traditional"],"故":["chinese_simplified","chinese_traditional"],"城":["chinese_simplified","chinese_traditional"],"夫":["chinese_simplified","chinese_traditional"],"够":["chinese_simplified"],"送":["chinese_simplified","chinese_traditional"],"笔":["chinese_simplified"],"船":["chinese_simplified","chinese_traditional"],"占":["chinese_simplified"],"右":["chinese_simplified","chinese_traditional"],"财":["chinese_simplified"],"吃":["chinese_simplified","chinese_traditional"],"富":["chinese_simplified","chinese_traditional"],"春":["chinese_simplified","chinese_traditional"],"职":["chinese_simplified"],"觉":["chinese_simplified"],"汉":["chinese_simplified"],"画":["chinese_simplified"],"功":["chinese_simplified","chinese_traditional"],"巴":["chinese_simplified","chinese_traditional"],"跟":["chinese_simplified","chinese_traditional"],"虽":["chinese_simplified"],"杂":["chinese_simplified"],"飞":["chinese_simplified"],"检":["chinese_simplified"],"吸":["chinese_simplified","chinese_traditional"],"助":["chinese_simplified","chinese_traditional"],"升":["chinese_simplified"],"阳":["chinese_simplified"],"互":["chinese_simplified","chinese_traditional"],"初":["chinese_simplified","chinese_traditional"],"创":["chinese_simplified"],"抗":["chinese_simplified","chinese_traditional"],"考":["chinese_simplified","chinese_traditional"],"投":["chinese_simplified","chinese_traditional"],"坏":["chinese_simplified"],"策":["chinese_simplified","chinese_traditional"],"古":["chinese_simplified","chinese_traditional"],"径":["chinese_simplified"],"换":["chinese_simplified"],"未":["chinese_simplified","chinese_traditional"],"跑":["chinese_simplified","chinese_traditional"],"留":["chinese_simplified","chinese_traditional"],"钢":["chinese_simplified"],"曾":["chinese_simplified","chinese_traditional"],"端":["chinese_simplified","chinese_traditional"],"责":["chinese_simplified"],"站":["chinese_simplified","chinese_traditional"],"简":["chinese_simplified"],"述":["chinese_simplified","chinese_traditional"],"钱":["chinese_simplified"],"副":["chinese_simplified","chinese_traditional"],"尽":["chinese_simplified"],"帝":["chinese_simplified","chinese_traditional"],"射":["chinese_simplified","chinese_traditional"],"草":["chinese_simplified","chinese_traditional"],"冲":["chinese_simplified"],"承":["chinese_simplified","chinese_traditional"],"独":["chinese_simplified"],"令":["chinese_simplified","chinese_traditional"],"限":["chinese_simplified","chinese_traditional"],"阿":["chinese_simplified","chinese_traditional"],"宣":["chinese_simplified","chinese_traditional"],"环":["chinese_simplified"],"双":["chinese_simplified"],"请":["chinese_simplified"],"超":["chinese_simplified","chinese_traditional"],"微":["chinese_simplified","chinese_traditional"],"让":["chinese_simplified"],"控":["chinese_simplified","chinese_traditional"],"州":["chinese_simplified","chinese_traditional"],"良":["chinese_simplified","chinese_traditional"],"轴":["chinese_simplified"],"找":["chinese_simplified","chinese_traditional"],"否":["chinese_simplified","chinese_traditional"],"纪":["chinese_simplified"],"益":["chinese_simplified","chinese_traditional"],"依":["chinese_simplified","chinese_traditional"],"优":["chinese_simplified"],"顶":["chinese_simplified"],"础":["chinese_simplified"],"载":["chinese_simplified"],"倒":["chinese_simplified","chinese_traditional"],"房":["chinese_simplified","chinese_traditional"],"突":["chinese_simplified","chinese_traditional"],"坐":["chinese_simplified","chinese_traditional"],"粉":["chinese_simplified","chinese_traditional"],"敌":["chinese_simplified"],"略":["chinese_simplified","chinese_traditional"],"客":["chinese_simplified","chinese_traditional"],"袁":["chinese_simplified","chinese_traditional"],"冷":["chinese_simplified","chinese_traditional"],"胜":["chinese_simplified"],"绝":["chinese_simplified"],"析":["chinese_simplified","chinese_traditional"],"块":["chinese_simplified"],"剂":["chinese_simplified"],"测":["chinese_simplified"],"丝":["chinese_simplified"],"协":["chinese_simplified"],"诉":["chinese_simplified"],"念":["chinese_simplified","chinese_traditional"],"陈":["chinese_simplified"],"仍":["chinese_simplified","chinese_traditional"],"罗":["chinese_simplified"],"盐":["chinese_simplified"],"友":["chinese_simplified","chinese_traditional"],"洋":["chinese_simplified","chinese_traditional"],"错":["chinese_simplified"],"苦":["chinese_simplified","chinese_traditional"],"夜":["chinese_simplified","chinese_traditional"],"刑":["chinese_simplified","chinese_traditional"],"移":["chinese_simplified","chinese_traditional"],"频":["chinese_simplified"],"逐":["chinese_simplified","chinese_traditional"],"靠":["chinese_simplified","chinese_traditional"],"混":["chinese_simplified","chinese_traditional"],"母":["chinese_simplified","chinese_traditional"],"短":["chinese_simplified","chinese_traditional"],"皮":["chinese_simplified","chinese_traditional"],"终":["chinese_simplified"],"聚":["chinese_simplified","chinese_traditional"],"汽":["chinese_simplified","chinese_traditional"],"村":["chinese_simplified","chinese_traditional"],"云":["chinese_simplified"],"哪":["chinese_simplified","chinese_traditional"],"既":["chinese_simplified","chinese_traditional"],"距":["chinese_simplified","chinese_traditional"],"卫":["chinese_simplified"],"停":["chinese_simplified","chinese_traditional"],"烈":["chinese_simplified","chinese_traditional"],"央":["chinese_simplified","chinese_traditional"],"察":["chinese_simplified","chinese_traditional"],"烧":["chinese_simplified"],"迅":["chinese_simplified","chinese_traditional"],"境":["chinese_simplified","chinese_traditional"],"若":["chinese_simplified","chinese_traditional"],"印":["chinese_simplified","chinese_traditional"],"洲":["chinese_simplified","chinese_traditional"],"刻":["chinese_simplified","chinese_traditional"],"括":["chinese_simplified","chinese_traditional"],"激":["chinese_simplified","chinese_traditional"],"孔":["chinese_simplified","chinese_traditional"],"搞":["chinese_simplified","chinese_traditional"],"甚":["chinese_simplified","chinese_traditional"],"室":["chinese_simplified","chinese_traditional"],"待":["chinese_simplified","chinese_traditional"],"核":["chinese_simplified","chinese_traditional"],"校":["chinese_simplified","chinese_traditional"],"散":["chinese_simplified","chinese_traditional"],"侵":["chinese_simplified","chinese_traditional"],"吧":["chinese_simplified","chinese_traditional"],"甲":["chinese_simplified","chinese_traditional"],"游":["chinese_simplified"],"久":["chinese_simplified","chinese_traditional"],"菜":["chinese_simplified","chinese_traditional"],"味":["chinese_simplified","chinese_traditional"],"旧":["chinese_simplified"],"模":["chinese_simplified","chinese_traditional"],"湖":["chinese_simplified","chinese_traditional"],"货":["chinese_simplified"],"损":["chinese_simplified"],"预":["chinese_simplified"],"阻":["chinese_simplified","chinese_traditional"],"毫":["chinese_simplified","chinese_traditional"],"普":["chinese_simplified","chinese_traditional"],"稳":["chinese_simplified"],"乙":["chinese_simplified","chinese_traditional"],"妈":["chinese_simplified"],"植":["chinese_simplified","chinese_traditional"],"息":["chinese_simplified","chinese_traditional"],"扩":["chinese_simplified"],"银":["chinese_simplified"],"语":["chinese_simplified"],"挥":["chinese_simplified"],"酒":["chinese_simplified","chinese_traditional"],"守":["chinese_simplified","chinese_traditional"],"拿":["chinese_simplified","chinese_traditional"],"序":["chinese_simplified","chinese_traditional"],"纸":["chinese_simplified"],"医":["chinese_simplified"],"缺":["chinese_simplified","chinese_traditional"],"雨":["chinese_simplified","chinese_traditional"],"吗":["chinese_simplified"],"针":["chinese_simplified"],"刘":["chinese_simplified"],"啊":["chinese_simplified","chinese_traditional"],"急":["chinese_simplified","chinese_traditional"],"唱":["chinese_simplified","chinese_traditional"],"误":["chinese_simplified"],"训":["chinese_simplified"],"愿":["chinese_simplified"],"审":["chinese_simplified"],"附":["chinese_simplified","chinese_traditional"],"获":["chinese_simplified"],"茶":["chinese_simplified","chinese_traditional"],"鲜":["chinese_simplified"],"粮":["chinese_simplified"],"斤":["chinese_simplified","chinese_traditional"],"孩":["chinese_simplified","chinese_traditional"],"脱":["chinese_simplified"],"硫":["chinese_simplified","chinese_traditional"],"肥":["chinese_simplified","chinese_traditional"],"善":["chinese_simplified","chinese_traditional"],"龙":["chinese_simplified"],"演":["chinese_simplified","chinese_traditional"],"父":["chinese_simplified","chinese_traditional"],"渐":["chinese_simplified"],"血":["chinese_simplified","chinese_traditional"],"欢":["chinese_simplified"],"械":["chinese_simplified","chinese_traditional"],"掌":["chinese_simplified","chinese_traditional"],"歌":["chinese_simplified","chinese_traditional"],"沙":["chinese_simplified","chinese_traditional"],"刚":["chinese_simplified"],"攻":["chinese_simplified","chinese_traditional"],"谓":["chinese_simplified"],"盾":["chinese_simplified","chinese_traditional"],"讨":["chinese_simplified"],"晚":["chinese_simplified","chinese_traditional"],"粒":["chinese_simplified","chinese_traditional"],"乱":["chinese_simplified"],"燃":["chinese_simplified","chinese_traditional"],"矛":["chinese_simplified","chinese_traditional"],"乎":["chinese_simplified","chinese_traditional"],"杀":["chinese_simplified"],"药":["chinese_simplified"],"宁":["chinese_simplified"],"鲁":["chinese_simplified"],"贵":["chinese_simplified"],"钟":["chinese_simplified"],"煤":["chinese_simplified","chinese_traditional"],"读":["chinese_simplified"],"班":["chinese_simplified","chinese_traditional"],"伯":["chinese_simplified","chinese_traditional"],"香":["chinese_simplified","chinese_traditional"],"介":["chinese_simplified","chinese_traditional"],"迫":["chinese_simplified","chinese_traditional"],"句":["chinese_simplified","chinese_traditional"],"丰":["chinese_simplified"],"培":["chinese_simplified","chinese_traditional"],"握":["chinese_simplified","chinese_traditional"],"兰":["chinese_simplified"],"担":["chinese_simplified"],"弦":["chinese_simplified","chinese_traditional"],"蛋":["chinese_simplified","chinese_traditional"],"沉":["chinese_simplified","chinese_traditional"],"假":["chinese_simplified","chinese_traditional"],"穿":["chinese_simplified","chinese_traditional"],"执":["chinese_simplified"],"答":["chinese_simplified","chinese_traditional"],"乐":["chinese_simplified"],"谁":["chinese_simplified"],"顺":["chinese_simplified"],"烟":["chinese_simplified"],"缩":["chinese_simplified"],"征":["chinese_simplified"],"脸":["chinese_simplified"],"喜":["chinese_simplified","chinese_traditional"],"松":["chinese_simplified","chinese_traditional"],"脚":["chinese_simplified"],"困":["chinese_simplified","chinese_traditional"],"异":["chinese_simplified"],"免":["chinese_simplified","chinese_traditional"],"背":["chinese_simplified","chinese_traditional"],"星":["chinese_simplified","chinese_traditional"],"福":["chinese_simplified","chinese_traditional"],"买":["chinese_simplified"],"染":["chinese_simplified","chinese_traditional"],"井":["chinese_simplified","chinese_traditional"],"概":["chinese_simplified","chinese_traditional"],"慢":["chinese_simplified","chinese_traditional"],"怕":["chinese_simplified","chinese_traditional"],"磁":["chinese_simplified","chinese_traditional"],"倍":["chinese_simplified","chinese_traditional"],"祖":["chinese_simplified","chinese_traditional"],"皇":["chinese_simplified","chinese_traditional"],"促":["chinese_simplified","chinese_traditional"],"静":["chinese_simplified"],"补":["chinese_simplified"],"评":["chinese_simplified"],"翻":["chinese_simplified","chinese_traditional"],"肉":["chinese_simplified","chinese_traditional"],"践":["chinese_simplified"],"尼":["chinese_simplified","chinese_traditional"],"衣":["chinese_simplified","chinese_traditional"],"宽":["chinese_simplified"],"扬":["chinese_simplified"],"棉":["chinese_simplified","chinese_traditional"],"希":["chinese_simplified","chinese_traditional"],"伤":["chinese_simplified"],"操":["chinese_simplified","chinese_traditional"],"垂":["chinese_simplified","chinese_traditional"],"秋":["chinese_simplified","chinese_traditional"],"宜":["chinese_simplified","chinese_traditional"],"氢":["chinese_simplified"],"套":["chinese_simplified","chinese_traditional"],"督":["chinese_simplified","chinese_traditional"],"振":["chinese_simplified","chinese_traditional"],"架":["chinese_simplified","chinese_traditional"],"亮":["chinese_simplified","chinese_traditional"],"末":["chinese_simplified","chinese_traditional"],"宪":["chinese_simplified"],"庆":["chinese_simplified"],"编":["chinese_simplified"],"牛":["chinese_simplified","chinese_traditional"],"触":["chinese_simplified"],"映":["chinese_simplified","chinese_traditional"],"雷":["chinese_simplified","chinese_traditional"],"销":["chinese_simplified"],"诗":["chinese_simplified"],"座":["chinese_simplified","chinese_traditional"],"居":["chinese_simplified","chinese_traditional"],"抓":["chinese_simplified","chinese_traditional"],"裂":["chinese_simplified","chinese_traditional"],"胞":["chinese_simplified","chinese_traditional"],"呼":["chinese_simplified","chinese_traditional"],"娘":["chinese_simplified","chinese_traditional"],"景":["chinese_simplified","chinese_traditional"],"威":["chinese_simplified","chinese_traditional"],"绿":["chinese_simplified"],"晶":["chinese_simplified","chinese_traditional"],"厚":["chinese_simplified","chinese_traditional"],"盟":["chinese_simplified","chinese_traditional"],"衡":["chinese_simplified","chinese_traditional"],"鸡":["chinese_simplified"],"孙":["chinese_simplified"],"延":["chinese_simplified","chinese_traditional"],"危":["chinese_simplified","chinese_traditional"],"胶":["chinese_simplified"],"屋":["chinese_simplified","chinese_traditional"],"乡":["chinese_simplified"],"临":["chinese_simplified"],"陆":["chinese_simplified"],"顾":["chinese_simplified"],"掉":["chinese_simplified","chinese_traditional"],"呀":["chinese_simplified","chinese_traditional"],"灯":["chinese_simplified"],"岁":["chinese_simplified"],"措":["chinese_simplified","chinese_traditional"],"束":["chinese_simplified","chinese_traditional"],"耐":["chinese_simplified","chinese_traditional"],"剧":["chinese_simplified"],"玉":["chinese_simplified","chinese_traditional"],"赵":["chinese_simplified"],"跳":["chinese_simplified","chinese_traditional"],"哥":["chinese_simplified","chinese_traditional"],"季":["chinese_simplified","chinese_traditional"],"课":["chinese_simplified"],"凯":["chinese_simplified"],"胡":["chinese_simplified","chinese_traditional"],"额":["chinese_simplified"],"款":["chinese_simplified","chinese_traditional"],"绍":["chinese_simplified"],"卷":["chinese_simplified","chinese_traditional"],"齐":["chinese_simplified"],"伟":["chinese_simplified"],"蒸":["chinese_simplified","chinese_traditional"],"殖":["chinese_simplified","chinese_traditional"],"永":["chinese_simplified","chinese_traditional"],"宗":["chinese_simplified","chinese_traditional"],"苗":["chinese_simplified","chinese_traditional"],"川":["chinese_simplified","chinese_traditional"],"炉":["chinese_simplified"],"岩":["chinese_simplified","chinese_traditional"],"弱":["chinese_simplified","chinese_traditional"],"零":["chinese_simplified","chinese_traditional"],"杨":["chinese_simplified"],"奏":["chinese_simplified","chinese_traditional"],"沿":["chinese_simplified","chinese_traditional"],"露":["chinese_simplified","chinese_traditional"],"杆":["chinese_simplified"],"探":["chinese_simplified","chinese_traditional"],"滑":["chinese_simplified","chinese_traditional"],"镇":["chinese_simplified"],"饭":["chinese_simplified"],"浓":["chinese_simplified"],"航":["chinese_simplified","chinese_traditional"],"怀":["chinese_simplified"],"赶":["chinese_simplified"],"库":["chinese_simplified"],"夺":["chinese_simplified"],"伊":["chinese_simplified","chinese_traditional"],"灵":["chinese_simplified"],"税":["chinese_simplified"],"途":["chinese_simplified","chinese_traditional"],"灭":["chinese_simplified"],"赛":["chinese_simplified"],"归":["chinese_simplified"],"召":["chinese_simplified","chinese_traditional"],"鼓":["chinese_simplified","chinese_traditional"],"播":["chinese_simplified","chinese_traditional"],"盘":["chinese_simplified"],"裁":["chinese_simplified","chinese_traditional"],"险":["chinese_simplified"],"康":["chinese_simplified","chinese_traditional"],"唯":["chinese_simplified","chinese_traditional"],"录":["chinese_simplified"],"菌":["chinese_simplified","chinese_traditional"],"纯":["chinese_simplified"],"借":["chinese_simplified","chinese_traditional"],"糖":["chinese_simplified","chinese_traditional"],"盖":["chinese_simplified"],"横":["chinese_simplified"],"符":["chinese_simplified","chinese_traditional"],"私":["chinese_simplified","chinese_traditional"],"努":["chinese_simplified","chinese_traditional"],"堂":["chinese_simplified","chinese_traditional"],"域":["chinese_simplified","chinese_traditional"],"枪":["chinese_simplified"],"润":["chinese_simplified"],"幅":["chinese_simplified","chinese_traditional"],"哈":["chinese_simplified","chinese_traditional"],"竟":["chinese_simplified","chinese_traditional"],"熟":["chinese_simplified","chinese_traditional"],"虫":["chinese_simplified"],"泽":["chinese_simplified"],"脑":["chinese_simplified"],"壤":["chinese_simplified","chinese_traditional"],"碳":["chinese_simplified","chinese_traditional"],"欧":["chinese_simplified"],"遍":["chinese_simplified","chinese_traditional"],"侧":["chinese_simplified"],"寨":["chinese_simplified","chinese_traditional"],"敢":["chinese_simplified","chinese_traditional"],"彻":["chinese_simplified"],"虑":["chinese_simplified"],"斜":["chinese_simplified","chinese_traditional"],"薄":["chinese_simplified","chinese_traditional"],"庭":["chinese_simplified","chinese_traditional"],"纳":["chinese_simplified"],"弹":["chinese_simplified"],"饲":["chinese_simplified"],"伸":["chinese_simplified","chinese_traditional"],"折":["chinese_simplified","chinese_traditional"],"麦":["chinese_simplified"],"湿":["chinese_simplified"],"暗":["chinese_simplified","chinese_traditional"],"荷":["chinese_simplified","chinese_traditional"],"瓦":["chinese_simplified","chinese_traditional"],"塞":["chinese_simplified","chinese_traditional"],"床":["chinese_simplified","chinese_traditional"],"筑":["chinese_simplified"],"恶":["chinese_simplified"],"户":["chinese_simplified"],"访":["chinese_simplified"],"塔":["chinese_simplified","chinese_traditional"],"奇":["chinese_simplified","chinese_traditional"],"透":["chinese_simplified","chinese_traditional"],"梁":["chinese_simplified","chinese_traditional"],"刀":["chinese_simplified","chinese_traditional"],"旋":["chinese_simplified","chinese_traditional"],"迹":["chinese_simplified"],"卡":["chinese_simplified","chinese_traditional"],"氯":["chinese_simplified","chinese_traditional"],"遇":["chinese_simplified","chinese_traditional"],"份":["chinese_simplified","chinese_traditional"],"毒":["chinese_simplified","chinese_traditional"],"泥":["chinese_simplified","chinese_traditional"],"退":["chinese_simplified","chinese_traditional"],"洗":["chinese_simplified","chinese_traditional"],"摆":["chinese_simplified"],"灰":["chinese_simplified","chinese_traditional"],"彩":["chinese_simplified","chinese_traditional"],"卖":["chinese_simplified"],"耗":["chinese_simplified","chinese_traditional"],"夏":["chinese_simplified","chinese_traditional"],"择":["chinese_simplified"],"忙":["chinese_simplified","chinese_traditional"],"铜":["chinese_simplified"],"献":["chinese_simplified"],"硬":["chinese_simplified","chinese_traditional"],"予":["chinese_simplified","chinese_traditional"],"繁":["chinese_simplified","chinese_traditional"],"圈":["chinese_simplified","chinese_traditional"],"雪":["chinese_simplified","chinese_traditional"],"函":["chinese_simplified","chinese_traditional"],"亦":["chinese_simplified","chinese_traditional"],"抽":["chinese_simplified","chinese_traditional"],"篇":["chinese_simplified","chinese_traditional"],"阵":["chinese_simplified"],"阴":["chinese_simplified"],"丁":["chinese_simplified","chinese_traditional"],"尺":["chinese_simplified","chinese_traditional"],"追":["chinese_simplified","chinese_traditional"],"堆":["chinese_simplified","chinese_traditional"],"雄":["chinese_simplified","chinese_traditional"],"迎":["chinese_simplified","chinese_traditional"],"泛":["chinese_simplified","chinese_traditional"],"爸":["chinese_simplified","chinese_traditional"],"楼":["chinese_simplified"],"避":["chinese_simplified","chinese_traditional"],"谋":["chinese_simplified"],"吨":["chinese_simplified"],"野":["chinese_simplified","chinese_traditional"],"猪":["chinese_simplified"],"旗":["chinese_simplified","chinese_traditional"],"累":["chinese_simplified","chinese_traditional"],"偏":["chinese_simplified","chinese_traditional"],"典":["chinese_simplified","chinese_traditional"],"馆":["chinese_simplified"],"索":["chinese_simplified","chinese_traditional"],"秦":["chinese_simplified","chinese_traditional"],"脂":["chinese_simplified","chinese_traditional"],"潮":["chinese_simplified","chinese_traditional"],"爷":["chinese_simplified"],"豆":["chinese_simplified","chinese_traditional"],"忽":["chinese_simplified","chinese_traditional"],"托":["chinese_simplified","chinese_traditional"],"惊":["chinese_simplified"],"塑":["chinese_simplified","chinese_traditional"],"遗":["chinese_simplified"],"愈":["chinese_simplified","chinese_traditional"],"朱":["chinese_simplified","chinese_traditional"],"替":["chinese_simplified","chinese_traditional"],"纤":["chinese_simplified"],"粗":["chinese_simplified","chinese_traditional"],"倾":["chinese_simplified"],"尚":["chinese_simplified","chinese_traditional"],"痛":["chinese_simplified","chinese_traditional"],"楚":["chinese_simplified","chinese_traditional"],"谢":["chinese_simplified"],"奋":["chinese_simplified"],"购":["chinese_simplified"],"磨":["chinese_simplified","chinese_traditional"],"君":["chinese_simplified","chinese_traditional"],"池":["chinese_simplified","chinese_traditional"],"旁":["chinese_simplified","chinese_traditional"],"碎":["chinese_simplified","chinese_traditional"],"骨":["chinese_simplified","chinese_traditional"],"监":["chinese_simplified"],"捕":["chinese_simplified","chinese_traditional"],"弟":["chinese_simplified","chinese_traditional"],"暴":["chinese_simplified","chinese_traditional"],"割":["chinese_simplified","chinese_traditional"],"贯":["chinese_simplified"],"殊":["chinese_simplified","chinese_traditional"],"释":["chinese_simplified"],"词":["chinese_simplified"],"亡":["chinese_simplified","chinese_traditional"],"壁":["chinese_simplified","chinese_traditional"],"顿":["chinese_simplified"],"宝":["chinese_simplified"],"午":["chinese_simplified","chinese_traditional"],"尘":["chinese_simplified"],"闻":["chinese_simplified"],"揭":["chinese_simplified","chinese_traditional"],"炮":["chinese_simplified","chinese_traditional"],"残":["chinese_simplified"],"冬":["chinese_simplified","chinese_traditional"],"桥":["chinese_simplified"],"妇":["chinese_simplified"],"警":["chinese_simplified","chinese_traditional"],"综":["chinese_simplified"],"招":["chinese_simplified","chinese_traditional"],"吴":["chinese_simplified"],"付":["chinese_simplified","chinese_traditional"],"浮":["chinese_simplified","chinese_traditional"],"遭":["chinese_simplified","chinese_traditional"],"徐":["chinese_simplified","chinese_traditional"],"您":["chinese_simplified","chinese_traditional"],"摇":["chinese_simplified"],"谷":["chinese_simplified","chinese_traditional"],"赞":["chinese_simplified"],"箱":["chinese_simplified","chinese_traditional"],"隔":["chinese_simplified","chinese_traditional"],"订":["chinese_simplified"],"男":["chinese_simplified","chinese_traditional"],"吹":["chinese_simplified","chinese_traditional"],"园":["chinese_simplified"],"纷":["chinese_simplified"],"唐":["chinese_simplified","chinese_traditional"],"败":["chinese_simplified"],"宋":["chinese_simplified","chinese_traditional"],"玻":["chinese_simplified","chinese_traditional"],"巨":["chinese_simplified","chinese_traditional"],"耕":["chinese_simplified","chinese_traditional"],"坦":["chinese_simplified","chinese_traditional"],"荣":["chinese_simplified"],"闭":["chinese_simplified"],"湾":["chinese_simplified"],"键":["chinese_simplified"],"凡":["chinese_simplified","chinese_traditional"],"驻":["chinese_simplified"],"锅":["chinese_simplified"],"救":["chinese_simplified","chinese_traditional"],"恩":["chinese_simplified","chinese_traditional"],"剥":["chinese_simplified"],"凝":["chinese_simplified","chinese_traditional"],"碱":["chinese_simplified"],"齿":["chinese_simplified"],"截":["chinese_simplified","chinese_traditional"],"炼":["chinese_simplified"],"麻":["chinese_simplified","chinese_traditional"],"纺":["chinese_simplified"],"禁":["chinese_simplified","chinese_traditional"],"废":["chinese_simplified"],"盛":["chinese_simplified","chinese_traditional"],"版":["chinese_simplified","chinese_traditional"],"缓":["chinese_simplified"],"净":["chinese_simplified"],"睛":["chinese_simplified","chinese_traditional"],"昌":["chinese_simplified","chinese_traditional"],"婚":["chinese_simplified","chinese_traditional"],"涉":["chinese_simplified","chinese_traditional"],"筒":["chinese_simplified","chinese_traditional"],"嘴":["chinese_simplified","chinese_traditional"],"插":["chinese_simplified","chinese_traditional"],"岸":["chinese_simplified","chinese_traditional"],"朗":["chinese_simplified","chinese_traditional"],"庄":["chinese_simplified"],"街":["chinese_simplified","chinese_traditional"],"藏":["chinese_simplified","chinese_traditional"],"姑":["chinese_simplified","chinese_traditional"],"贸":["chinese_simplified"],"腐":["chinese_simplified","chinese_traditional"],"奴":["chinese_simplified","chinese_traditional"],"啦":["chinese_simplified","chinese_traditional"],"惯":["chinese_simplified"],"乘":["chinese_simplified","chinese_traditional"],"伙":["chinese_simplified"],"恢":["chinese_simplified","chinese_traditional"],"匀":["chinese_simplified"],"纱":["chinese_simplified"],"扎":["chinese_simplified","chinese_traditional"],"辩":["chinese_simplified"],"耳":["chinese_simplified","chinese_traditional"],"彪":["chinese_simplified","chinese_traditional"],"臣":["chinese_simplified","chinese_traditional"],"亿":["chinese_simplified"],"璃":["chinese_simplified","chinese_traditional"],"抵":["chinese_simplified","chinese_traditional"],"脉":["chinese_simplified"],"秀":["chinese_simplified","chinese_traditional"],"萨":["chinese_simplified"],"俄":["chinese_simplified","chinese_traditional"],"网":["chinese_simplified"],"舞":["chinese_simplified","chinese_traditional"],"店":["chinese_simplified","chinese_traditional"],"喷":["chinese_simplified"],"纵":["chinese_simplified"],"寸":["chinese_simplified","chinese_traditional"],"汗":["chinese_simplified","chinese_traditional"],"挂":["chinese_simplified"],"洪":["chinese_simplified","chinese_traditional"],"贺":["chinese_simplified"],"闪":["chinese_simplified"],"柬":["chinese_simplified","chinese_traditional"],"爆":["chinese_simplified","chinese_traditional"],"烯":["chinese_simplified","chinese_traditional"],"津":["chinese_simplified","chinese_traditional"],"稻":["chinese_simplified","chinese_traditional"],"墙":["chinese_simplified"],"软":["chinese_simplified"],"勇":["chinese_simplified","chinese_traditional"],"像":["chinese_simplified","chinese_traditional"],"滚":["chinese_simplified"],"厘":["chinese_simplified","chinese_traditional"],"蒙":["chinese_simplified","chinese_traditional"],"芳":["chinese_simplified","chinese_traditional"],"肯":["chinese_simplified","chinese_traditional"],"坡":["chinese_simplified","chinese_traditional"],"柱":["chinese_simplified","chinese_traditional"],"荡":["chinese_simplified"],"腿":["chinese_simplified","chinese_traditional"],"仪":["chinese_simplified"],"旅":["chinese_simplified","chinese_traditional"],"尾":["chinese_simplified","chinese_traditional"],"轧":["chinese_simplified"],"冰":["chinese_simplified","chinese_traditional"],"贡":["chinese_simplified"],"登":["chinese_simplified","chinese_traditional"],"黎":["chinese_simplified","chinese_traditional"],"削":["chinese_simplified","chinese_traditional"],"钻":["chinese_simplified"],"勒":["chinese_simplified","chinese_traditional"],"逃":["chinese_simplified","chinese_traditional"],"障":["chinese_simplified","chinese_traditional"],"氨":["chinese_simplified","chinese_traditional"],"郭":["chinese_simplified","chinese_traditional"],"峰":["chinese_simplified","chinese_traditional"],"币":["chinese_simplified"],"港":["chinese_simplified","chinese_traditional"],"伏":["chinese_simplified","chinese_traditional"],"轨":["chinese_simplified"],"亩":["chinese_simplified"],"毕":["chinese_simplified"],"擦":["chinese_simplified","chinese_traditional"],"莫":["chinese_simplified","chinese_traditional"],"刺":["chinese_simplified","chinese_traditional"],"浪":["chinese_simplified","chinese_traditional"],"秘":["chinese_simplified","chinese_traditional"],"援":["chinese_simplified","chinese_traditional"],"株":["chinese_simplified","chinese_traditional"],"健":["chinese_simplified","chinese_traditional"],"售":["chinese_simplified","chinese_traditional"],"股":["chinese_simplified","chinese_traditional"],"岛":["chinese_simplified"],"甘":["chinese_simplified","chinese_traditional"],"泡":["chinese_simplified","chinese_traditional"],"睡":["chinese_simplified","chinese_traditional"],"童":["chinese_simplified","chinese_traditional"],"铸":["chinese_simplified"],"汤":["chinese_simplified"],"阀":["chinese_simplified"],"休":["chinese_simplified","chinese_traditional"],"汇":["chinese_simplified"],"舍":["chinese_simplified","chinese_traditional"],"牧":["chinese_simplified","chinese_traditional"],"绕":["chinese_simplified"],"炸":["chinese_simplified","chinese_traditional"],"哲":["chinese_simplified","chinese_traditional"],"磷":["chinese_simplified","chinese_traditional"],"绩":["chinese_simplified"],"朋":["chinese_simplified","chinese_traditional"],"淡":["chinese_simplified","chinese_traditional"],"尖":["chinese_simplified","chinese_traditional"],"启":["chinese_simplified"],"陷":["chinese_simplified","chinese_traditional"],"柴":["chinese_simplified","chinese_traditional"],"呈":["chinese_simplified","chinese_traditional"],"徒":["chinese_simplified","chinese_traditional"],"颜":["chinese_simplified"],"泪":["chinese_simplified"],"稍":["chinese_simplified","chinese_traditional"],"忘":["chinese_simplified","chinese_traditional"],"泵":["chinese_simplified","chinese_traditional"],"蓝":["chinese_simplified"],"拖":["chinese_simplified","chinese_traditional"],"洞":["chinese_simplified","chinese_traditional"],"授":["chinese_simplified","chinese_traditional"],"镜":["chinese_simplified"],"辛":["chinese_simplified","chinese_traditional"],"壮":["chinese_simplified"],"锋":["chinese_simplified"],"贫":["chinese_simplified"],"虚":["chinese_simplified"],"弯":["chinese_simplified"],"摩":["chinese_simplified","chinese_traditional"],"泰":["chinese_simplified","chinese_traditional"],"幼":["chinese_simplified","chinese_traditional"],"廷":["chinese_simplified","chinese_traditional"],"尊":["chinese_simplified","chinese_traditional"],"窗":["chinese_simplified","chinese_traditional"],"纲":["chinese_simplified"],"弄":["chinese_simplified","chinese_traditional"],"隶":["chinese_simplified"],"疑":["chinese_simplified","chinese_traditional"],"氏":["chinese_simplified","chinese_traditional"],"宫":["chinese_simplified"],"姐":["chinese_simplified","chinese_traditional"],"震":["chinese_simplified","chinese_traditional"],"瑞":["chinese_simplified","chinese_traditional"],"怪":["chinese_simplified","chinese_traditional"],"尤":["chinese_simplified","chinese_traditional"],"琴":["chinese_simplified","chinese_traditional"],"循":["chinese_simplified","chinese_traditional"],"描":["chinese_simplified","chinese_traditional"],"膜":["chinese_simplified","chinese_traditional"],"违":["chinese_simplified"],"夹":["chinese_simplified"],"腰":["chinese_simplified","chinese_traditional"],"缘":["chinese_simplified"],"珠":["chinese_simplified","chinese_traditional"],"穷":["chinese_simplified"],"森":["chinese_simplified","chinese_traditional"],"枝":["chinese_simplified","chinese_traditional"],"竹":["chinese_simplified","chinese_traditional"],"沟":["chinese_simplified"],"催":["chinese_simplified","chinese_traditional"],"绳":["chinese_simplified"],"忆":["chinese_simplified"],"邦":["chinese_simplified","chinese_traditional"],"剩":["chinese_simplified","chinese_traditional"],"幸":["chinese_simplified","chinese_traditional"],"浆":["chinese_simplified"],"栏":["chinese_simplified"],"拥":["chinese_simplified"],"牙":["chinese_simplified","chinese_traditional"],"贮":["chinese_simplified"],"礼":["chinese_simplified"],"滤":["chinese_simplified"],"钠":["chinese_simplified"],"纹":["chinese_simplified"],"罢":["chinese_simplified"],"拍":["chinese_simplified","chinese_traditional"],"咱":["chinese_simplified","chinese_traditional"],"喊":["chinese_simplified","chinese_traditional"],"袖":["chinese_simplified","chinese_traditional"],"埃":["chinese_simplified","chinese_traditional"],"勤":["chinese_simplified","chinese_traditional"],"罚":["chinese_simplified"],"焦":["chinese_simplified","chinese_traditional"],"潜":["chinese_simplified"],"伍":["chinese_simplified","chinese_traditional"],"墨":["chinese_simplified","chinese_traditional"],"欲":["chinese_simplified","chinese_traditional"],"缝":["chinese_simplified"],"姓":["chinese_simplified","chinese_traditional"],"刊":["chinese_simplified","chinese_traditional"],"饱":["chinese_simplified"],"仿":["chinese_simplified","chinese_traditional"],"奖":["chinese_simplified"],"铝":["chinese_simplified"],"鬼":["chinese_simplified","chinese_traditional"],"丽":["chinese_simplified"],"跨":["chinese_simplified","chinese_traditional"],"默":["chinese_simplified","chinese_traditional"],"挖":["chinese_simplified","chinese_traditional"],"链":["chinese_simplified"],"扫":["chinese_simplified"],"喝":["chinese_simplified","chinese_traditional"],"袋":["chinese_simplified","chinese_traditional"],"炭":["chinese_simplified","chinese_traditional"],"污":["chinese_simplified","chinese_traditional"],"幕":["chinese_simplified","chinese_traditional"],"诸":["chinese_simplified"],"弧":["chinese_simplified","chinese_traditional"],"励":["chinese_simplified"],"梅":["chinese_simplified","chinese_traditional"],"奶":["chinese_simplified","chinese_traditional"],"洁":["chinese_simplified"],"灾":["chinese_simplified"],"舟":["chinese_simplified","chinese_traditional"],"鉴":["chinese_simplified"],"苯":["chinese_simplified","chinese_traditional"],"讼":["chinese_simplified"],"抱":["chinese_simplified","chinese_traditional"],"毁":["chinese_simplified"],"懂":["chinese_simplified","chinese_traditional"],"寒":["chinese_simplified","chinese_traditional"],"智":["chinese_simplified","chinese_traditional"],"埔":["chinese_simplified","chinese_traditional"],"寄":["chinese_simplified","chinese_traditional"],"届":["chinese_simplified"],"跃":["chinese_simplified"],"渡":["chinese_simplified","chinese_traditional"],"挑":["chinese_simplified","chinese_traditional"],"丹":["chinese_simplified","chinese_traditional"],"艰":["chinese_simplified"],"贝":["chinese_simplified"],"碰":["chinese_simplified","chinese_traditional"],"拔":["chinese_simplified","chinese_traditional"],"爹":["chinese_simplified","chinese_traditional"],"戴":["chinese_simplified","chinese_traditional"],"码":["chinese_simplified"],"梦":["chinese_simplified"],"芽":["chinese_simplified","chinese_traditional"],"熔":["chinese_simplified","chinese_traditional"],"赤":["chinese_simplified","chinese_traditional"],"渔":["chinese_simplified"],"哭":["chinese_simplified","chinese_traditional"],"敬":["chinese_simplified","chinese_traditional"],"颗":["chinese_simplified"],"奔":["chinese_simplified","chinese_traditional"],"铅":["chinese_simplified"],"仲":["chinese_simplified","chinese_traditional"],"虎":["chinese_simplified","chinese_traditional"],"稀":["chinese_simplified","chinese_traditional"],"妹":["chinese_simplified","chinese_traditional"],"乏":["chinese_simplified","chinese_traditional"],"珍":["chinese_simplified","chinese_traditional"],"申":["chinese_simplified","chinese_traditional"],"桌":["chinese_simplified","chinese_traditional"],"遵":["chinese_simplified","chinese_traditional"],"允":["chinese_simplified","chinese_traditional"],"隆":["chinese_simplified","chinese_traditional"],"螺":["chinese_simplified","chinese_traditional"],"仓":["chinese_simplified"],"魏":["chinese_simplified","chinese_traditional"],"锐":["chinese_simplified"],"晓":["chinese_simplified"],"氮":["chinese_simplified","chinese_traditional"],"兼":["chinese_simplified","chinese_traditional"],"隐":["chinese_simplified"],"碍":["chinese_simplified"],"赫":["chinese_simplified","chinese_traditional"],"拨":["chinese_simplified"],"忠":["chinese_simplified","chinese_traditional"],"肃":["chinese_simplified"],"缸":["chinese_simplified","chinese_traditional"],"牵":["chinese_simplified"],"抢":["chinese_simplified"],"博":["chinese_simplified","chinese_traditional"],"巧":["chinese_simplified","chinese_traditional"],"壳":["chinese_simplified"],"兄":["chinese_simplified","chinese_traditional"],"杜":["chinese_simplified","chinese_traditional"],"讯":["chinese_simplified"],"诚":["chinese_simplified"],"碧":["chinese_simplified","chinese_traditional"],"祥":["chinese_simplified","chinese_traditional"],"柯":["chinese_simplified","chinese_traditional"],"页":["chinese_simplified"],"巡":["chinese_simplified","chinese_traditional"],"矩":["chinese_simplified","chinese_traditional"],"悲":["chinese_simplified","chinese_traditional"],"灌":["chinese_simplified","chinese_traditional"],"龄":["chinese_simplified"],"伦":["chinese_simplified"],"票":["chinese_simplified","chinese_traditional"],"寻":["chinese_simplified"],"桂":["chinese_simplified","chinese_traditional"],"铺":["chinese_simplified"],"圣":["chinese_simplified"],"恐":["chinese_simplified","chinese_traditional"],"恰":["chinese_simplified","chinese_traditional"],"郑":["chinese_simplified"],"趣":["chinese_simplified","chinese_traditional"],"抬":["chinese_simplified","chinese_traditional"],"荒":["chinese_simplified","chinese_traditional"],"腾":["chinese_simplified"],"贴":["chinese_simplified"],"柔":["chinese_simplified","chinese_traditional"],"滴":["chinese_simplified","chinese_traditional"],"猛":["chinese_simplified","chinese_traditional"],"阔":["chinese_simplified"],"辆":["chinese_simplified"],"妻":["chinese_simplified","chinese_traditional"],"填":["chinese_simplified","chinese_traditional"],"撤":["chinese_simplified","chinese_traditional"],"储":["chinese_simplified"],"签":["chinese_simplified"],"闹":["chinese_simplified"],"扰":["chinese_simplified"],"紫":["chinese_simplified","chinese_traditional"],"砂":["chinese_simplified","chinese_traditional"],"递":["chinese_simplified"],"戏":["chinese_simplified"],"吊":["chinese_simplified","chinese_traditional"],"陶":["chinese_simplified","chinese_traditional"],"伐":["chinese_simplified","chinese_traditional"],"喂":["chinese_simplified"],"疗":["chinese_simplified"],"瓶":["chinese_simplified","chinese_traditional"],"婆":["chinese_simplified","chinese_traditional"],"抚":["chinese_simplified"],"臂":["chinese_simplified","chinese_traditional"],"摸":["chinese_simplified","chinese_traditional"],"忍":["chinese_simplified","chinese_traditional"],"虾":["chinese_simplified"],"蜡":["chinese_simplified"],"邻":["chinese_simplified"],"胸":["chinese_simplified","chinese_traditional"],"巩":["chinese_simplified"],"挤":["chinese_simplified"],"偶":["chinese_simplified","chinese_traditional"],"弃":["chinese_simplified"],"槽":["chinese_simplified","chinese_traditional"],"劲":["chinese_simplified"],"乳":["chinese_simplified","chinese_traditional"],"邓":["chinese_simplified"],"吉":["chinese_simplified","chinese_traditional"],"仁":["chinese_simplified","chinese_traditional"],"烂":["chinese_simplified"],"砖":["chinese_simplified"],"租":["chinese_simplified","chinese_traditional"],"乌":["chinese_simplified"],"舰":["chinese_simplified"],"伴":["chinese_simplified","chinese_traditional"],"瓜":["chinese_simplified","chinese_traditional"],"浅":["chinese_simplified"],"丙":["chinese_simplified","chinese_traditional"],"暂":["chinese_simplified"],"燥":["chinese_simplified","chinese_traditional"],"橡":["chinese_simplified","chinese_traditional"],"柳":["chinese_simplified","chinese_traditional"],"迷":["chinese_simplified","chinese_traditional"],"暖":["chinese_simplified","chinese_traditional"],"牌":["chinese_simplified","chinese_traditional"],"秧":["chinese_simplified","chinese_traditional"],"胆":["chinese_simplified"],"详":["chinese_simplified"],"簧":["chinese_simplified","chinese_traditional"],"踏":["chinese_simplified","chinese_traditional"],"瓷":["chinese_simplified","chinese_traditional"],"谱":["chinese_simplified"],"呆":["chinese_simplified","chinese_traditional"],"宾":["chinese_simplified"],"糊":["chinese_simplified","chinese_traditional"],"洛":["chinese_simplified","chinese_traditional"],"辉":["chinese_simplified"],"愤":["chinese_simplified"],"竞":["chinese_simplified"],"隙":["chinese_simplified","chinese_traditional"],"怒":["chinese_simplified","chinese_traditional"],"粘":["chinese_simplified","chinese_traditional"],"乃":["chinese_simplified","chinese_traditional"],"绪":["chinese_simplified"],"肩":["chinese_simplified","chinese_traditional"],"籍":["chinese_simplified","chinese_traditional"],"敏":["chinese_simplified","chinese_traditional"],"涂":["chinese_simplified"],"熙":["chinese_simplified","chinese_traditional"],"皆":["chinese_simplified","chinese_traditional"],"侦":["chinese_simplified"],"悬":["chinese_simplified"],"掘":["chinese_simplified","chinese_traditional"],"享":["chinese_simplified","chinese_traditional"],"纠":["chinese_simplified"],"醒":["chinese_simplified","chinese_traditional"],"狂":["chinese_simplified","chinese_traditional"],"锁":["chinese_simplified"],"淀":["chinese_simplified","chinese_traditional"],"恨":["chinese_simplified","chinese_traditional"],"牲":["chinese_simplified","chinese_traditional"],"霸":["chinese_simplified","chinese_traditional"],"爬":["chinese_simplified","chinese_traditional"],"赏":["chinese_simplified"],"逆":["chinese_simplified","chinese_traditional"],"玩":["chinese_simplified","chinese_traditional"],"陵":["chinese_simplified","chinese_traditional"],"祝":["chinese_simplified","chinese_traditional"],"秒":["chinese_simplified","chinese_traditional"],"浙":["chinese_simplified","chinese_traditional"],"貌":["chinese_simplified","chinese_traditional"],"役":["chinese_simplified","chinese_traditional"],"彼":["chinese_simplified","chinese_traditional"],"悉":["chinese_simplified","chinese_traditional"],"鸭":["chinese_simplified"],"趋":["chinese_simplified"],"凤":["chinese_simplified"],"晨":["chinese_simplified","chinese_traditional"],"畜":["chinese_simplified","chinese_traditional"],"辈":["chinese_simplified"],"秩":["chinese_simplified","chinese_traditional"],"卵":["chinese_simplified","chinese_traditional"],"署":["chinese_simplified","chinese_traditional"],"梯":["chinese_simplified","chinese_traditional"],"炎":["chinese_simplified","chinese_traditional"],"滩":["chinese_simplified"],"棋":["chinese_simplified","chinese_traditional"],"驱":["chinese_simplified"],"筛":["chinese_simplified"],"峡":["chinese_simplified"],"冒":["chinese_simplified","chinese_traditional"],"啥":["chinese_simplified","chinese_traditional"],"寿":["chinese_simplified"],"译":["chinese_simplified"],"浸":["chinese_simplified","chinese_traditional"],"泉":["chinese_simplified","chinese_traditional"],"帽":["chinese_simplified","chinese_traditional"],"迟":["chinese_simplified"],"硅":["chinese_simplified"],"疆":["chinese_simplified","chinese_traditional"],"贷":["chinese_simplified"],"漏":["chinese_simplified","chinese_traditional"],"稿":["chinese_simplified","chinese_traditional"],"冠":["chinese_simplified","chinese_traditional"],"嫩":["chinese_simplified","chinese_traditional"],"胁":["chinese_simplified"],"芯":["chinese_simplified","chinese_traditional"],"牢":["chinese_simplified","chinese_traditional"],"叛":["chinese_simplified","chinese_traditional"],"蚀":["chinese_simplified"],"奥":["chinese_simplified"],"鸣":["chinese_simplified"],"岭":["chinese_simplified"],"羊":["chinese_simplified","chinese_traditional"],"凭":["chinese_simplified"],"串":["chinese_simplified","chinese_traditional"],"塘":["chinese_simplified","chinese_traditional"],"绘":["chinese_simplified"],"酵":["chinese_simplified","chinese_traditional"],"融":["chinese_simplified","chinese_traditional"],"盆":["chinese_simplified","chinese_traditional"],"锡":["chinese_simplified"],"庙":["chinese_simplified"],"筹":["chinese_simplified"],"冻":["chinese_simplified"],"辅":["chinese_simplified"],"摄":["chinese_simplified"],"袭":["chinese_simplified"],"筋":["chinese_simplified","chinese_traditional"],"拒":["chinese_simplified","chinese_traditional"],"僚":["chinese_simplified","chinese_traditional"],"旱":["chinese_simplified","chinese_traditional"],"钾":["chinese_simplified"],"鸟":["chinese_simplified"],"漆":["chinese_simplified","chinese_traditional"],"沈":["chinese_simplified","chinese_traditional"],"眉":["chinese_simplified","chinese_traditional"],"疏":["chinese_simplified","chinese_traditional"],"添":["chinese_simplified","chinese_traditional"],"棒":["chinese_simplified","chinese_traditional"],"穗":["chinese_simplified","chinese_traditional"],"硝":["chinese_simplified","chinese_traditional"],"韩":["chinese_simplified"],"逼":["chinese_simplified","chinese_traditional"],"扭":["chinese_simplified","chinese_traditional"],"侨":["chinese_simplified"],"凉":["chinese_simplified"],"挺":["chinese_simplified","chinese_traditional"],"碗":["chinese_simplified","chinese_traditional"],"栽":["chinese_simplified","chinese_traditional"],"炒":["chinese_simplified","chinese_traditional"],"杯":["chinese_simplified","chinese_traditional"],"患":["chinese_simplified","chinese_traditional"],"馏":["chinese_simplified"],"劝":["chinese_simplified"],"豪":["chinese_simplified","chinese_traditional"],"辽":["chinese_simplified"],"勃":["chinese_simplified","chinese_traditional"],"鸿":["chinese_simplified"],"旦":["chinese_simplified","chinese_traditional"],"吏":["chinese_simplified","chinese_traditional"],"拜":["chinese_simplified","chinese_traditional"],"狗":["chinese_simplified","chinese_traditional"],"埋":["chinese_simplified","chinese_traditional"],"辊":["chinese_simplified"],"掩":["chinese_simplified","chinese_traditional"],"饮":["chinese_simplified"],"搬":["chinese_simplified","chinese_traditional"],"骂":["chinese_simplified"],"辞":["chinese_simplified"],"勾":["chinese_simplified","chinese_traditional"],"扣":["chinese_simplified","chinese_traditional"],"估":["chinese_simplified","chinese_traditional"],"蒋":["chinese_simplified"],"绒":["chinese_simplified"],"雾":["chinese_simplified"],"丈":["chinese_simplified","chinese_traditional"],"朵":["chinese_simplified","chinese_traditional"],"姆":["chinese_simplified","chinese_traditional"],"拟":["chinese_simplified"],"宇":["chinese_simplified","chinese_traditional"],"辑":["chinese_simplified"],"陕":["chinese_simplified"],"雕":["chinese_simplified","chinese_traditional"],"偿":["chinese_simplified"],"蓄":["chinese_simplified","chinese_traditional"],"崇":["chinese_simplified","chinese_traditional"],"剪":["chinese_simplified","chinese_traditional"],"倡":["chinese_simplified","chinese_traditional"],"厅":["chinese_simplified"],"咬":["chinese_simplified","chinese_traditional"],"驶":["chinese_simplified"],"薯":["chinese_simplified","chinese_traditional"],"刷":["chinese_simplified","chinese_traditional"],"斥":["chinese_simplified","chinese_traditional"],"番":["chinese_simplified","chinese_traditional"],"赋":["chinese_simplified"],"奉":["chinese_simplified","chinese_traditional"],"佛":["chinese_simplified","chinese_traditional"],"浇":["chinese_simplified"],"漫":["chinese_simplified","chinese_traditional"],"曼":["chinese_simplified","chinese_traditional"],"扇":["chinese_simplified","chinese_traditional"],"钙":["chinese_simplified"],"桃":["chinese_simplified","chinese_traditional"],"扶":["chinese_simplified","chinese_traditional"],"仔":["chinese_simplified","chinese_traditional"],"返":["chinese_simplified","chinese_traditional"],"俗":["chinese_simplified","chinese_traditional"],"亏":["chinese_simplified"],"腔":["chinese_simplified","chinese_traditional"],"鞋":["chinese_simplified","chinese_traditional"],"棱":["chinese_simplified","chinese_traditional"],"覆":["chinese_simplified","chinese_traditional"],"框":["chinese_simplified","chinese_traditional"],"悄":["chinese_simplified","chinese_traditional"],"叔":["chinese_simplified","chinese_traditional"],"撞":["chinese_simplified","chinese_traditional"],"骗":["chinese_simplified"],"勘":["chinese_simplified","chinese_traditional"],"旺":["chinese_simplified","chinese_traditional"],"沸":["chinese_simplified","chinese_traditional"],"孤":["chinese_simplified","chinese_traditional"],"吐":["chinese_simplified","chinese_traditional"],"孟":["chinese_simplified","chinese_traditional"],"渠":["chinese_simplified","chinese_traditional"],"屈":["chinese_simplified","chinese_traditional"],"疾":["chinese_simplified","chinese_traditional"],"妙":["chinese_simplified","chinese_traditional"],"惜":["chinese_simplified","chinese_traditional"],"仰":["chinese_simplified","chinese_traditional"],"狠":["chinese_simplified","chinese_traditional"],"胀":["chinese_simplified"],"谐":["chinese_simplified"],"抛":["chinese_simplified"],"霉":["chinese_simplified"],"桑":["chinese_simplified","chinese_traditional"],"岗":["chinese_simplified"],"嘛":["chinese_simplified","chinese_traditional"],"衰":["chinese_simplified","chinese_traditional"],"盗":["chinese_simplified"],"渗":["chinese_simplified"],"脏":["chinese_simplified"],"赖":["chinese_simplified"],"涌":["chinese_simplified"],"甜":["chinese_simplified","chinese_traditional"],"曹":["chinese_simplified","chinese_traditional"],"阅":["chinese_simplified"],"肌":["chinese_simplified","chinese_traditional"],"哩":["chinese_simplified","chinese_traditional"],"厉":["chinese_simplified"],"烃":["chinese_simplified"],"纬":["chinese_simplified"],"毅":["chinese_simplified","chinese_traditional"],"昨":["chinese_simplified","chinese_traditional"],"伪":["chinese_simplified"],"症":["chinese_simplified","chinese_traditional"],"煮":["chinese_simplified","chinese_traditional"],"叹":["chinese_simplified"],"钉":["chinese_simplified"],"搭":["chinese_simplified","chinese_traditional"],"茎":["chinese_simplified"],"笼":["chinese_simplified"],"酷":["chinese_simplified","chinese_traditional"],"偷":["chinese_simplified","chinese_traditional"],"弓":["chinese_simplified","chinese_traditional"],"锥":["chinese_simplified"],"恒":["chinese_simplified"],"杰":["chinese_simplified"],"坑":["chinese_simplified","chinese_traditional"],"鼻":["chinese_simplified","chinese_traditional"],"翼":["chinese_simplified","chinese_traditional"],"纶":["chinese_simplified"],"叙":["chinese_simplified"],"狱":["chinese_simplified"],"逮":["chinese_simplified","chinese_traditional"],"罐":["chinese_simplified","chinese_traditional"],"络":["chinese_simplified"],"棚":["chinese_simplified","chinese_traditional"],"抑":["chinese_simplified","chinese_traditional"],"膨":["chinese_simplified","chinese_traditional"],"蔬":["chinese_simplified","chinese_traditional"],"寺":["chinese_simplified","chinese_traditional"],"骤":["chinese_simplified"],"穆":["chinese_simplified","chinese_traditional"],"冶":["chinese_simplified","chinese_traditional"],"枯":["chinese_simplified","chinese_traditional"],"册":["chinese_simplified"],"尸":["chinese_simplified"],"凸":["chinese_simplified","chinese_traditional"],"绅":["chinese_simplified"],"坯":["chinese_simplified","chinese_traditional"],"牺":["chinese_simplified"],"焰":["chinese_simplified","chinese_traditional"],"轰":["chinese_simplified"],"欣":["chinese_simplified","chinese_traditional"],"晋":["chinese_simplified"],"瘦":["chinese_simplified","chinese_traditional"],"御":["chinese_simplified"],"锭":["chinese_simplified"],"锦":["chinese_simplified"],"丧":["chinese_simplified"],"旬":["chinese_simplified","chinese_traditional"],"锻":["chinese_simplified"],"垄":["chinese_simplified"],"搜":["chinese_simplified","chinese_traditional"],"扑":["chinese_simplified"],"邀":["chinese_simplified","chinese_traditional"],"亭":["chinese_simplified","chinese_traditional"],"酯":["chinese_simplified","chinese_traditional"],"迈":["chinese_simplified"],"舒":["chinese_simplified","chinese_traditional"],"脆":["chinese_simplified","chinese_traditional"],"酶":["chinese_simplified","chinese_traditional"],"闲":["chinese_simplified"],"忧":["chinese_simplified"],"酚":["chinese_simplified","chinese_traditional"],"顽":["chinese_simplified"],"羽":["chinese_simplified","chinese_traditional"],"涨":["chinese_simplified"],"卸":["chinese_simplified","chinese_traditional"],"仗":["chinese_simplified","chinese_traditional"],"陪":["chinese_simplified","chinese_traditional"],"辟":["chinese_simplified"],"惩":["chinese_simplified"],"杭":["chinese_simplified","chinese_traditional"],"姚":["chinese_simplified","chinese_traditional"],"肚":["chinese_simplified","chinese_traditional"],"捉":["chinese_simplified","chinese_traditional"],"飘":["chinese_simplified"],"漂":["chinese_simplified","chinese_traditional"],"昆":["chinese_simplified","chinese_traditional"],"欺":["chinese_simplified","chinese_traditional"],"吾":["chinese_simplified","chinese_traditional"],"郎":["chinese_simplified","chinese_traditional"],"烷":["chinese_simplified","chinese_traditional"],"汁":["chinese_simplified","chinese_traditional"],"呵":["chinese_simplified","chinese_traditional"],"饰":["chinese_simplified"],"萧":["chinese_simplified"],"雅":["chinese_simplified","chinese_traditional"],"邮":["chinese_simplified"],"迁":["chinese_simplified"],"燕":["chinese_simplified","chinese_traditional"],"撒":["chinese_simplified","chinese_traditional"],"姻":["chinese_simplified","chinese_traditional"],"赴":["chinese_simplified","chinese_traditional"],"宴":["chinese_simplified","chinese_traditional"],"烦":["chinese_simplified"],"债":["chinese_simplified"],"帐":["chinese_simplified"],"斑":["chinese_simplified","chinese_traditional"],"铃":["chinese_simplified"],"旨":["chinese_simplified","chinese_traditional"],"醇":["chinese_simplified","chinese_traditional"],"董":["chinese_simplified","chinese_traditional"],"饼":["chinese_simplified"],"雏":["chinese_simplified"],"姿":["chinese_simplified","chinese_traditional"],"拌":["chinese_simplified","chinese_traditional"],"傅":["chinese_simplified","chinese_traditional"],"腹":["chinese_simplified","chinese_traditional"],"妥":["chinese_simplified","chinese_traditional"],"揉":["chinese_simplified","chinese_traditional"],"贤":["chinese_simplified"],"拆":["chinese_simplified","chinese_traditional"],"歪":["chinese_simplified","chinese_traditional"],"葡":["chinese_simplified","chinese_traditional"],"胺":["chinese_simplified","chinese_traditional"],"丢":["chinese_simplified"],"浩":["chinese_simplified","chinese_traditional"],"徽":["chinese_simplified","chinese_traditional"],"昂":["chinese_simplified","chinese_traditional"],"垫":["chinese_simplified"],"挡":["chinese_simplified"],"览":["chinese_simplified"],"贪":["chinese_simplified"],"慰":["chinese_simplified","chinese_traditional"],"缴":["chinese_simplified"],"汪":["chinese_simplified","chinese_traditional"],"慌":["chinese_simplified","chinese_traditional"],"冯":["chinese_simplified"],"诺":["chinese_simplified"],"姜":["chinese_simplified","chinese_traditional"],"谊":["chinese_simplified"],"凶":["chinese_simplified"],"劣":["chinese_simplified","chinese_traditional"],"诬":["chinese_simplified"],"耀":["chinese_simplified","chinese_traditional"],"昏":["chinese_simplified","chinese_traditional"],"躺":["chinese_simplified","chinese_traditional"],"盈":["chinese_simplified","chinese_traditional"],"骑":["chinese_simplified"],"乔":["chinese_simplified"],"溪":["chinese_simplified","chinese_traditional"],"丛":["chinese_simplified"],"卢":["chinese_simplified"],"抹":["chinese_simplified","chinese_traditional"],"闷":["chinese_simplified"],"咨":["chinese_simplified"],"刮":["chinese_simplified","chinese_traditional"],"驾":["chinese_simplified"],"缆":["chinese_simplified"],"悟":["chinese_simplified","chinese_traditional"],"摘":["chinese_simplified","chinese_traditional"],"铒":["chinese_simplified"],"掷":["chinese_simplified"],"颇":["chinese_simplified"],"幻":["chinese_simplified","chinese_traditional"],"柄":["chinese_simplified","chinese_traditional"],"惠":["chinese_simplified","chinese_traditional"],"惨":["chinese_simplified"],"佳":["chinese_simplified","chinese_traditional"],"仇":["chinese_simplified","chinese_traditional"],"腊":["chinese_simplified"],"窝":["chinese_simplified"],"涤":["chinese_simplified"],"剑":["chinese_simplified"],"瞧":["chinese_simplified","chinese_traditional"],"堡":["chinese_simplified","chinese_traditional"],"泼":["chinese_simplified"],"葱":["chinese_simplified"],"罩":["chinese_simplified","chinese_traditional"],"霍":["chinese_simplified","chinese_traditional"],"捞":["chinese_simplified"],"胎":["chinese_simplified","chinese_traditional"],"苍":["chinese_simplified"],"滨":["chinese_simplified"],"俩":["chinese_simplified"],"捅":["chinese_simplified","chinese_traditional"],"湘":["chinese_simplified","chinese_traditional"],"砍":["chinese_simplified","chinese_traditional"],"霞":["chinese_simplified","chinese_traditional"],"邵":["chinese_simplified","chinese_traditional"],"萄":["chinese_simplified","chinese_traditional"],"疯":["chinese_simplified"],"淮":["chinese_simplified","chinese_traditional"],"遂":["chinese_simplified","chinese_traditional"],"熊":["chinese_simplified","chinese_traditional"],"粪":["chinese_simplified"],"烘":["chinese_simplified","chinese_traditional"],"宿":["chinese_simplified","chinese_traditional"],"档":["chinese_simplified"],"戈":["chinese_simplified","chinese_traditional"],"驳":["chinese_simplified"],"嫂":["chinese_simplified","chinese_traditional"],"裕":["chinese_simplified","chinese_traditional"],"徙":["chinese_simplified","chinese_traditional"],"箭":["chinese_simplified","chinese_traditional"],"捐":["chinese_simplified","chinese_traditional"],"肠":["chinese_simplified"],"撑":["chinese_simplified"],"晒":["chinese_simplified"],"辨":["chinese_simplified","chinese_traditional"],"殿":["chinese_simplified","chinese_traditional"],"莲":["chinese_simplified"],"摊":["chinese_simplified"],"搅":["chinese_simplified"],"酱":["chinese_simplified"],"屏":["chinese_simplified","chinese_traditional"],"疫":["chinese_simplified","chinese_traditional"],"哀":["chinese_simplified","chinese_traditional"],"蔡":["chinese_simplified","chinese_traditional"],"堵":["chinese_simplified","chinese_traditional"],"沫":["chinese_simplified","chinese_traditional"],"皱":["chinese_simplified"],"畅":["chinese_simplified"],"叠":["chinese_simplified"],"阁":["chinese_simplified"],"莱":["chinese_simplified"],"敲":["chinese_simplified","chinese_traditional"],"辖":["chinese_simplified"],"钩":["chinese_simplified"],"痕":["chinese_simplified","chinese_traditional"],"坝":["chinese_simplified"],"巷":["chinese_simplified","chinese_traditional"],"饿":["chinese_simplified"],"祸":["chinese_simplified"],"丘":["chinese_simplified","chinese_traditional"],"玄":["chinese_simplified","chinese_traditional"],"溜":["chinese_simplified","chinese_traditional"],"曰":["chinese_simplified","chinese_traditional"],"逻":["chinese_simplified"],"彭":["chinese_simplified","chinese_traditional"],"尝":["chinese_simplified"],"卿":["chinese_simplified","chinese_traditional"],"妨":["chinese_simplified","chinese_traditional"],"艇":["chinese_simplified","chinese_traditional"],"吞":["chinese_simplified","chinese_traditional"],"韦":["chinese_simplified"],"怨":["chinese_simplified","chinese_traditional"],"矮":["chinese_simplified","chinese_traditional"],"歇":["chinese_simplified","chinese_traditional"],"這":["chinese_traditional"],"為":["chinese_traditional"],"個":["chinese_traditional"],"國":["chinese_traditional"],"時":["chinese_traditional"],"來":["chinese_traditional"],"們":["chinese_traditional"],"於":["chinese_traditional"],"對":["chinese_traditional"],"會":["chinese_traditional"],"發":["chinese_traditional"],"動":["chinese_traditional"],"過":["chinese_traditional"],"說":["chinese_traditional"],"產":["chinese_traditional"],"種":["chinese_traditional"],"後":["chinese_traditional"],"學":["chinese_traditional"],"經":["chinese_traditional"],"進":["chinese_traditional"],"著":["chinese_traditional"],"電":["chinese_traditional"],"裡":["chinese_traditional"],"現":["chinese_traditional"],"實":["chinese_traditional"],"兩":["chinese_traditional"],"體":["chinese_traditional"],"機":["chinese_traditional"],"當":["chinese_traditional"],"點":["chinese_traditional"],"從":["chinese_traditional"],"業":["chinese_traditional"],"應":["chinese_traditional"],"開":["chinese_traditional"],"還":["chinese_traditional"],"義":["chinese_traditional"],"間":["chinese_traditional"],"樣":["chinese_traditional"],"與":["chinese_traditional"],"關":["chinese_traditional"],"線":["chinese_traditional"],"內":["chinese_traditional"],"數":["chinese_traditional"],"麼":["chinese_traditional"],"質":["chinese_traditional"],"氣":["chinese_traditional"],"變":["chinese_traditional"],"條":["chinese_traditional"],"沒":["chinese_traditional"],"結":["chinese_traditional"],"問":["chinese_traditional"],"無":["chinese_traditional"],"軍":["chinese_traditional"],"並":["chinese_traditional"],"題":["chinese_traditional"],"黨":["chinese_traditional"],"員":["chinese_traditional"],"總":["chinese_traditional"],"設":["chinese_traditional"],"長":["chinese_traditional"],"頭":["chinese_traditional"],"資":["chinese_traditional"],"邊":["chinese_traditional"],"級":["chinese_traditional"],"圖":["chinese_traditional"],"統":["chinese_traditional"],"較":["chinese_traditional"],"將":["chinese_traditional"],"組":["chinese_traditional"],"見":["chinese_traditional"],"計":["chinese_traditional"],"別":["chinese_traditional"],"論":["chinese_traditional"],"運":["chinese_traditional"],"農":["chinese_traditional"],"幾":["chinese_traditional"],"區":["chinese_traditional"],"強":["chinese_traditional"],"決":["chinese_traditional"],"幹":["chinese_traditional"],"戰":["chinese_traditional"],"則":["chinese_traditional"],"據":["chinese_traditional"],"處":["chinese_traditional"],"隊":["chinese_traditional"],"給":["chinese_traditional"],"門":["chinese_traditional"],"規":["chinese_traditional"],"熱":["chinese_traditional"],"領":["chinese_traditional"],"東":["chinese_traditional"],"導":["chinese_traditional"],"壓":["chinese_traditional"],"爭":["chinese_traditional"],"濟":["chinese_traditional"],"階":["chinese_traditional"],"術":["chinese_traditional"],"極":["chinese_traditional"],"聯":["chinese_traditional"],"認":["chinese_traditional"],"權":["chinese_traditional"],"證":["chinese_traditional"],"採":["chinese_traditional"],"轉":["chinese_traditional"],"單":["chinese_traditional"],"風":["chinese_traditional"],"帶":["chinese_traditional"],"場":["chinese_traditional"],"車":["chinese_traditional"],"務":["chinese_traditional"],"萬":["chinese_traditional"],"達":["chinese_traditional"],"積":["chinese_traditional"],"議":["chinese_traditional"],"聲":["chinese_traditional"],"報":["chinese_traditional"],"鬥":["chinese_traditional"],"類":["chinese_traditional"],"離":["chinese_traditional"],"華":["chinese_traditional"],"確":["chinese_traditional"],"張":["chinese_traditional"],"馬":["chinese_traditional"],"節":["chinese_traditional"],"話":["chinese_traditional"],"況":["chinese_traditional"],"溫":["chinese_traditional"],"傳":["chinese_traditional"],"許":["chinese_traditional"],"廣":["chinese_traditional"],"記":["chinese_traditional"],"觀":["chinese_traditional"],"織":["chinese_traditional"],"裝":["chinese_traditional"],"眾":["chinese_traditional"],"書":["chinese_traditional"],"兒":["chinese_traditional"],"須":["chinese_traditional"],"際":["chinese_traditional"],"驗":["chinese_traditional"],"連":["chinese_traditional"],"斷":["chinese_traditional"],"難":["chinese_traditional"],"礦":["chinese_traditional"],"週":["chinese_traditional"],"備":["chinese_traditional"],"辦":["chinese_traditional"],"習":["chinese_traditional"],"響":["chinese_traditional"],"約":["chinese_traditional"],"勞":["chinese_traditional"],"團":["chinese_traditional"],"歷":["chinese_traditional"],"構":["chinese_traditional"],"稱":["chinese_traditional"],"準":["chinese_traditional"],"號":["chinese_traditional"],"維":["chinese_traditional"],"劃":["chinese_traditional"],"選":["chinese_traditional"],"標":["chinese_traditional"],"寫":["chinese_traditional"],"親":["chinese_traditional"],"養":["chinese_traditional"],"層":["chinese_traditional"],"卻":["chinese_traditional"],"專":["chinese_traditional"],"狀":["chinese_traditional"],"廠":["chinese_traditional"],"識":["chinese_traditional"],"適":["chinese_traditional"],"屬":["chinese_traditional"],"圓":["chinese_traditional"],"調":["chinese_traditional"],"滿":["chinese_traditional"],"縣":["chinese_traditional"],"參":["chinese_traditional"],"紅":["chinese_traditional"],"細":["chinese_traditional"],"聽":["chinese_traditional"],"該":["chinese_traditional"],"鐵":["chinese_traditional"],"價":["chinese_traditional"],"嚴":["chinese_traditional"],"隨":["chinese_traditional"],"蘇":["chinese_traditional"],"爾":["chinese_traditional"],"講":["chinese_traditional"],"黃":["chinese_traditional"],"顯":["chinese_traditional"],"談":["chinese_traditional"],"藝":["chinese_traditional"],"營":["chinese_traditional"],"項":["chinese_traditional"],"舉":["chinese_traditional"],"勢":["chinese_traditional"],"幫":["chinese_traditional"],"輪":["chinese_traditional"],"亞":["chinese_traditional"],"師":["chinese_traditional"],"圍":["chinese_traditional"],"遠":["chinese_traditional"],"態":["chinese_traditional"],"減":["chinese_traditional"],"樹":["chinese_traditional"],"葉":["chinese_traditional"],"魚":["chinese_traditional"],"視":["chinese_traditional"],"僅":["chinese_traditional"],"費":["chinese_traditional"],"緊":["chinese_traditional"],"愛":["chinese_traditional"],"續":["chinese_traditional"],"輕":["chinese_traditional"],"試":["chinese_traditional"],"護":["chinese_traditional"],"練":["chinese_traditional"],"負":["chinese_traditional"],"擊":["chinese_traditional"],"繼":["chinese_traditional"],"興":["chinese_traditional"],"餘":["chinese_traditional"],"堅":["chinese_traditional"],"輸":["chinese_traditional"],"夠":["chinese_traditional"],"筆":["chinese_traditional"],"佔":["chinese_traditional"],"財":["chinese_traditional"],"職":["chinese_traditional"],"覺":["chinese_traditional"],"漢":["chinese_traditional"],"畫":["chinese_traditional"],"雖":["chinese_traditional"],"雜":["chinese_traditional"],"飛":["chinese_traditional"],"檢":["chinese_traditional"],"昇":["chinese_traditional"],"陽":["chinese_traditional"],"創":["chinese_traditional"],"壞":["chinese_traditional"],"徑":["chinese_traditional"],"換":["chinese_traditional"],"鋼":["chinese_traditional"],"責":["chinese_traditional"],"簡":["chinese_traditional"],"錢":["chinese_traditional"],"盡":["chinese_traditional"],"衝":["chinese_traditional"],"獨":["chinese_traditional"],"環":["chinese_traditional"],"雙":["chinese_traditional"],"請":["chinese_traditional"],"讓":["chinese_traditional"],"軸":["chinese_traditional"],"紀":["chinese_traditional"],"優":["chinese_traditional"],"頂":["chinese_traditional"],"礎":["chinese_traditional"],"載":["chinese_traditional"],"敵":["chinese_traditional"],"勝":["chinese_traditional"],"絕":["chinese_traditional"],"塊":["chinese_traditional"],"劑":["chinese_traditional"],"測":["chinese_traditional"],"絲":["chinese_traditional"],"協":["chinese_traditional"],"訴":["chinese_traditional"],"陳":["chinese_traditional"],"羅":["chinese_traditional"],"鹽":["chinese_traditional"],"錯":["chinese_traditional"],"頻":["chinese_traditional"],"終":["chinese_traditional"],"雲":["chinese_traditional"],"衛":["chinese_traditional"],"燒":["chinese_traditional"],"遊":["chinese_traditional"],"舊":["chinese_traditional"],"貨":["chinese_traditional"],"損":["chinese_traditional"],"預":["chinese_traditional"],"穩":["chinese_traditional"],"媽":["chinese_traditional"],"擴":["chinese_traditional"],"銀":["chinese_traditional"],"語":["chinese_traditional"],"揮":["chinese_traditional"],"紙":["chinese_traditional"],"醫":["chinese_traditional"],"嗎":["chinese_traditional"],"針":["chinese_traditional"],"劉":["chinese_traditional"],"誤":["chinese_traditional"],"訓":["chinese_traditional"],"願":["chinese_traditional"],"審":["chinese_traditional"],"獲":["chinese_traditional"],"鮮":["chinese_traditional"],"糧":["chinese_traditional"],"脫":["chinese_traditional"],"龍":["chinese_traditional"],"漸":["chinese_traditional"],"歡":["chinese_traditional"],"剛":["chinese_traditional"],"謂":["chinese_traditional"],"討":["chinese_traditional"],"亂":["chinese_traditional"],"殺":["chinese_traditional"],"藥":["chinese_traditional"],"寧":["chinese_traditional"],"魯":["chinese_traditional"],"貴":["chinese_traditional"],"鐘":["chinese_traditional"],"讀":["chinese_traditional"],"豐":["chinese_traditional"],"蘭":["chinese_traditional"],"擔":["chinese_traditional"],"執":["chinese_traditional"],"樂":["chinese_traditional"],"誰":["chinese_traditional"],"順":["chinese_traditional"],"煙":["chinese_traditional"],"縮":["chinese_traditional"],"徵":["chinese_traditional"],"臉":["chinese_traditional"],"腳":["chinese_traditional"],"異":["chinese_traditional"],"買":["chinese_traditional"],"靜":["chinese_traditional"],"補":["chinese_traditional"],"評":["chinese_traditional"],"踐":["chinese_traditional"],"寬":["chinese_traditional"],"揚":["chinese_traditional"],"傷":["chinese_traditional"],"氫":["chinese_traditional"],"憲":["chinese_traditional"],"慶":["chinese_traditional"],"編":["chinese_traditional"],"觸":["chinese_traditional"],"銷":["chinese_traditional"],"詩":["chinese_traditional"],"綠":["chinese_traditional"],"雞":["chinese_traditional"],"孫":["chinese_traditional"],"膠":["chinese_traditional"],"鄉":["chinese_traditional"],"臨":["chinese_traditional"],"陸":["chinese_traditional"],"顧":["chinese_traditional"],"燈":["chinese_traditional"],"歲":["chinese_traditional"],"劇":["chinese_traditional"],"趙":["chinese_traditional"],"課":["chinese_traditional"],"凱":["chinese_traditional"],"額":["chinese_traditional"],"紹":["chinese_traditional"],"齊":["chinese_traditional"],"偉":["chinese_traditional"],"爐":["chinese_traditional"],"楊":["chinese_traditional"],"桿":["chinese_traditional"],"鎮":["chinese_traditional"],"飯":["chinese_traditional"],"濃":["chinese_traditional"],"懷":["chinese_traditional"],"趕":["chinese_traditional"],"庫":["chinese_traditional"],"奪":["chinese_traditional"],"靈":["chinese_traditional"],"稅":["chinese_traditional"],"滅":["chinese_traditional"],"賽":["chinese_traditional"],"歸":["chinese_traditional"],"盤":["chinese_traditional"],"險":["chinese_traditional"],"錄":["chinese_traditional"],"純":["chinese_traditional"],"蓋":["chinese_traditional"],"橫":["chinese_traditional"],"槍":["chinese_traditional"],"潤":["chinese_traditional"],"蟲":["chinese_traditional"],"澤":["chinese_traditional"],"腦":["chinese_traditional"],"歐":["chinese_traditional"],"側":["chinese_traditional"],"徹":["chinese_traditional"],"慮":["chinese_traditional"],"納":["chinese_traditional"],"彈":["chinese_traditional"],"飼":["chinese_traditional"],"麥":["chinese_traditional"],"濕":["chinese_traditional"],"築":["chinese_traditional"],"惡":["chinese_traditional"],"戶":["chinese_traditional"],"訪":["chinese_traditional"],"跡":["chinese_traditional"],"擺":["chinese_traditional"],"賣":["chinese_traditional"],"擇":["chinese_traditional"],"銅":["chinese_traditional"],"獻":["chinese_traditional"],"陣":["chinese_traditional"],"陰":["chinese_traditional"],"樓":["chinese_traditional"],"謀":["chinese_traditional"],"噸":["chinese_traditional"],"豬":["chinese_traditional"],"館":["chinese_traditional"],"爺":["chinese_traditional"],"驚":["chinese_traditional"],"遺":["chinese_traditional"],"纖":["chinese_traditional"],"傾":["chinese_traditional"],"謝":["chinese_traditional"],"奮":["chinese_traditional"],"購":["chinese_traditional"],"監":["chinese_traditional"],"貫":["chinese_traditional"],"釋":["chinese_traditional"],"詞":["chinese_traditional"],"頓":["chinese_traditional"],"寶":["chinese_traditional"],"塵":["chinese_traditional"],"聞":["chinese_traditional"],"殘":["chinese_traditional"],"橋":["chinese_traditional"],"婦":["chinese_traditional"],"綜":["chinese_traditional"],"吳":["chinese_traditional"],"搖":["chinese_traditional"],"贊":["chinese_traditional"],"訂":["chinese_traditional"],"園":["chinese_traditional"],"紛":["chinese_traditional"],"敗":["chinese_traditional"],"榮":["chinese_traditional"],"閉":["chinese_traditional"],"灣":["chinese_traditional"],"鍵":["chinese_traditional"],"駐":["chinese_traditional"],"鍋":["chinese_traditional"],"剝":["chinese_traditional"],"鹼":["chinese_traditional"],"齒":["chinese_traditional"],"煉":["chinese_traditional"],"紡":["chinese_traditional"],"廢":["chinese_traditional"],"緩":["chinese_traditional"],"淨":["chinese_traditional"],"莊":["chinese_traditional"],"貿":["chinese_traditional"],"慣":["chinese_traditional"],"夥":["chinese_traditional"],"勻":["chinese_traditional"],"紗":["chinese_traditional"],"辯":["chinese_traditional"],"億":["chinese_traditional"],"脈":["chinese_traditional"],"薩":["chinese_traditional"],"網":["chinese_traditional"],"噴":["chinese_traditional"],"縱":["chinese_traditional"],"掛":["chinese_traditional"],"賀":["chinese_traditional"],"閃":["chinese_traditional"],"牆":["chinese_traditional"],"軟":["chinese_traditional"],"滾":["chinese_traditional"],"盪":["chinese_traditional"],"儀":["chinese_traditional"],"軋":["chinese_traditional"],"貢":["chinese_traditional"],"鑽":["chinese_traditional"],"幣":["chinese_traditional"],"軌":["chinese_traditional"],"畝":["chinese_traditional"],"畢":["chinese_traditional"],"島":["chinese_traditional"],"鑄":["chinese_traditional"],"湯":["chinese_traditional"],"閥":["chinese_traditional"],"匯":["chinese_traditional"],"繞":["chinese_traditional"],"績":["chinese_traditional"],"啟":["chinese_traditional"],"顏":["chinese_traditional"],"淚":["chinese_traditional"],"藍":["chinese_traditional"],"鏡":["chinese_traditional"],"壯":["chinese_traditional"],"鋒":["chinese_traditional"],"貧":["chinese_traditional"],"虛":["chinese_traditional"],"彎":["chinese_traditional"],"綱":["chinese_traditional"],"隸":["chinese_traditional"],"宮":["chinese_traditional"],"違":["chinese_traditional"],"夾":["chinese_traditional"],"緣":["chinese_traditional"],"窮":["chinese_traditional"],"溝":["chinese_traditional"],"繩":["chinese_traditional"],"憶":["chinese_traditional"],"漿":["chinese_traditional"],"欄":["chinese_traditional"],"擁":["chinese_traditional"],"貯":["chinese_traditional"],"禮":["chinese_traditional"],"濾":["chinese_traditional"],"鈉":["chinese_traditional"],"紋":["chinese_traditional"],"罷":["chinese_traditional"],"罰":["chinese_traditional"],"潛":["chinese_traditional"],"縫":["chinese_traditional"],"飽":["chinese_traditional"],"獎":["chinese_traditional"],"鋁":["chinese_traditional"],"麗":["chinese_traditional"],"鏈":["chinese_traditional"],"掃":["chinese_traditional"],"諸":["chinese_traditional"],"勵":["chinese_traditional"],"潔":["chinese_traditional"],"災":["chinese_traditional"],"鑑":["chinese_traditional"],"訟":["chinese_traditional"],"毀":["chinese_traditional"],"屆":["chinese_traditional"],"躍":["chinese_traditional"],"艱":["chinese_traditional"],"貝":["chinese_traditional"],"碼":["chinese_traditional"],"夢":["chinese_traditional"],"漁":["chinese_traditional"],"顆":["chinese_traditional"],"鉛":["chinese_traditional"],"倉":["chinese_traditional"],"銳":["chinese_traditional"],"曉":["chinese_traditional"],"隱":["chinese_traditional"],"礙":["chinese_traditional"],"撥":["chinese_traditional"],"肅":["chinese_traditional"],"牽":["chinese_traditional"],"搶":["chinese_traditional"],"殼":["chinese_traditional"],"訊":["chinese_traditional"],"誠":["chinese_traditional"],"頁":["chinese_traditional"],"齡":["chinese_traditional"],"倫":["chinese_traditional"],"尋":["chinese_traditional"],"鋪":["chinese_traditional"],"聖":["chinese_traditional"],"鄭":["chinese_traditional"],"騰":["chinese_traditional"],"貼":["chinese_traditional"],"闊":["chinese_traditional"],"輛":["chinese_traditional"],"儲":["chinese_traditional"],"簽":["chinese_traditional"],"鬧":["chinese_traditional"],"擾":["chinese_traditional"],"遞":["chinese_traditional"],"戲":["chinese_traditional"],"餵":["chinese_traditional"],"療":["chinese_traditional"],"撫":["chinese_traditional"],"蝦":["chinese_traditional"],"蠟":["chinese_traditional"],"鄰":["chinese_traditional"],"鞏":["chinese_traditional"],"擠":["chinese_traditional"],"棄":["chinese_traditional"],"勁":["chinese_traditional"],"鄧":["chinese_traditional"],"爛":["chinese_traditional"],"磚":["chinese_traditional"],"烏":["chinese_traditional"],"艦":["chinese_traditional"],"淺":["chinese_traditional"],"暫":["chinese_traditional"],"膽":["chinese_traditional"],"詳":["chinese_traditional"],"譜":["chinese_traditional"],"賓":["chinese_traditional"],"輝":["chinese_traditional"],"憤":["chinese_traditional"],"競":["chinese_traditional"],"緒":["chinese_traditional"],"塗":["chinese_traditional"],"偵":["chinese_traditional"],"懸":["chinese_traditional"],"糾":["chinese_traditional"],"鎖":["chinese_traditional"],"賞":["chinese_traditional"],"鴨":["chinese_traditional"],"趨":["chinese_traditional"],"鳳":["chinese_traditional"],"輩":["chinese_traditional"],"灘":["chinese_traditional"],"驅":["chinese_traditional"],"篩":["chinese_traditional"],"峽":["chinese_traditional"],"壽":["chinese_traditional"],"譯":["chinese_traditional"],"遲":["chinese_traditional"],"矽":["chinese_traditional"],"貸":["chinese_traditional"],"脅":["chinese_traditional"],"蝕":["chinese_traditional"],"奧":["chinese_traditional"],"鳴":["chinese_traditional"],"嶺":["chinese_traditional"],"憑":["chinese_traditional"],"繪":["chinese_traditional"],"錫":["chinese_traditional"],"廟":["chinese_traditional"],"籌":["chinese_traditional"],"凍":["chinese_traditional"],"輔":["chinese_traditional"],"攝":["chinese_traditional"],"襲":["chinese_traditional"],"鉀":["chinese_traditional"],"鳥":["chinese_traditional"],"韓":["chinese_traditional"],"僑":["chinese_traditional"],"涼":["chinese_traditional"],"餾":["chinese_traditional"],"勸":["chinese_traditional"],"遼":["chinese_traditional"],"鴻":["chinese_traditional"],"輥":["chinese_traditional"],"飲":["chinese_traditional"],"罵":["chinese_traditional"],"辭":["chinese_traditional"],"蔣":["chinese_traditional"],"絨":["chinese_traditional"],"霧":["chinese_traditional"],"擬":["chinese_traditional"],"輯":["chinese_traditional"],"陝":["chinese_traditional"],"償":["chinese_traditional"],"廳":["chinese_traditional"],"駛":["chinese_traditional"],"賦":["chinese_traditional"],"澆":["chinese_traditional"],"鈣":["chinese_traditional"],"虧":["chinese_traditional"],"騙":["chinese_traditional"],"脹":["chinese_traditional"],"諧":["chinese_traditional"],"拋":["chinese_traditional"],"黴":["chinese_traditional"],"崗":["chinese_traditional"],"盜":["chinese_traditional"],"滲":["chinese_traditional"],"臟":["chinese_traditional"],"賴":["chinese_traditional"],"湧":["chinese_traditional"],"閱":["chinese_traditional"],"厲":["chinese_traditional"],"烴":["chinese_traditional"],"緯":["chinese_traditional"],"偽":["chinese_traditional"],"嘆":["chinese_traditional"],"釘":["chinese_traditional"],"莖":["chinese_traditional"],"籠":["chinese_traditional"],"錐":["chinese_traditional"],"恆":["chinese_traditional"],"傑":["chinese_traditional"],"綸":["chinese_traditional"],"敘":["chinese_traditional"],"獄":["chinese_traditional"],"絡":["chinese_traditional"],"驟":["chinese_traditional"],"冊":["chinese_traditional"],"屍":["chinese_traditional"],"紳":["chinese_traditional"],"犧":["chinese_traditional"],"轟":["chinese_traditional"],"晉":["chinese_traditional"],"禦":["chinese_traditional"],"錠":["chinese_traditional"],"錦":["chinese_traditional"],"喪":["chinese_traditional"],"鍛":["chinese_traditional"],"壟":["chinese_traditional"],"撲":["chinese_traditional"],"邁":["chinese_traditional"],"閒":["chinese_traditional"],"憂":["chinese_traditional"],"頑":["chinese_traditional"],"漲":["chinese_traditional"],"闢":["chinese_traditional"],"懲":["chinese_traditional"],"飄":["chinese_traditional"],"飾":["chinese_traditional"],"蕭":["chinese_traditional"],"郵":["chinese_traditional"],"遷":["chinese_traditional"],"煩":["chinese_traditional"],"債":["chinese_traditional"],"帳":["chinese_traditional"],"鈴":["chinese_traditional"],"餅":["chinese_traditional"],"雛":["chinese_traditional"],"賢":["chinese_traditional"],"丟":["chinese_traditional"],"墊":["chinese_traditional"],"擋":["chinese_traditional"],"覽":["chinese_traditional"],"貪":["chinese_traditional"],"繳":["chinese_traditional"],"馮":["chinese_traditional"],"諾":["chinese_traditional"],"誼":["chinese_traditional"],"兇":["chinese_traditional"],"誣":["chinese_traditional"],"騎":["chinese_traditional"],"喬":["chinese_traditional"],"叢":["chinese_traditional"],"盧":["chinese_traditional"],"悶":["chinese_traditional"],"諮":["chinese_traditional"],"駕":["chinese_traditional"],"纜":["chinese_traditional"],"鉺":["chinese_traditional"],"擲":["chinese_traditional"],"頗":["chinese_traditional"],"慘":["chinese_traditional"],"臘":["chinese_traditional"],"窩":["chinese_traditional"],"滌":["chinese_traditional"],"劍":["chinese_traditional"],"潑":["chinese_traditional"],"蔥":["chinese_traditional"],"撈":["chinese_traditional"],"蒼":["chinese_traditional"],"濱":["chinese_traditional"],"倆":["chinese_traditional"],"瘋":["chinese_traditional"],"糞":["chinese_traditional"],"檔":["chinese_traditional"],"駁":["chinese_traditional"],"腸":["chinese_traditional"],"撐":["chinese_traditional"],"曬":["chinese_traditional"],"蓮":["chinese_traditional"],"攤":["chinese_traditional"],"攪":["chinese_traditional"],"醬":["chinese_traditional"],"皺":["chinese_traditional"],"暢":["chinese_traditional"],"疊":["chinese_traditional"],"閣":["chinese_traditional"],"萊":["chinese_traditional"],"轄":["chinese_traditional"],"鉤":["chinese_traditional"],"壩":["chinese_traditional"],"餓":["chinese_traditional"],"禍":["chinese_traditional"],"邏":["chinese_traditional"],"嘗":["chinese_traditional"],"韋":["chinese_traditional"],"abdikace":["czech"],"abeceda":["czech"],"adresa":["czech"],"agrese":["czech"],"akce":["czech"],"aktovka":["czech"],"alej":["czech"],"alkohol":["czech"],"amputace":["czech"],"ananas":["czech"],"andulka":["czech"],"anekdota":["czech"],"anketa":["czech"],"antika":["czech"],"anulovat":["czech"],"archa":["czech"],"arogance":["czech"],"asfalt":["czech","turkish"],"asistent":["czech"],"aspirace":["czech"],"astma":["czech"],"astronom":["czech"],"atlas":["czech"],"atletika":["czech"],"atol":["czech"],"autobus":["czech"],"azyl":["czech"],"babka":["czech"],"bachor":["czech"],"bacil":["czech"],"baculka":["czech"],"badatel":["czech"],"bageta":["czech"],"bagr":["czech"],"bahno":["czech"],"bakterie":["czech"],"balada":["czech"],"baletka":["czech"],"balkon":["czech"],"balonek":["czech"],"balvan":["czech"],"balza":["czech"],"bambus":["czech"],"bankomat":["czech"],"barbar":["czech"],"baret":["czech"],"barman":["czech"],"baroko":["czech"],"barva":["czech"],"baterka":["czech"],"batoh":["czech"],"bavlna":["czech"],"bazalka":["czech"],"bazilika":["czech"],"bazuka":["czech"],"bedna":["czech"],"beran":["czech"],"beseda":["czech"],"bestie":["czech"],"beton":["czech","turkish"],"bezinka":["czech"],"bezmoc":["czech"],"beztak":["czech"],"bicykl":["czech"],"bidlo":["czech"],"biftek":["czech","turkish"],"bikiny":["czech"],"bilance":["czech"],"biograf":["czech"],"biolog":["czech"],"bitva":["czech"],"bizon":["czech"],"blahobyt":["czech"],"blatouch":["czech"],"blecha":["czech"],"bledule":["czech"],"blesk":["czech"],"blikat":["czech"],"blizna":["czech"],"blokovat":["czech"],"bloudit":["czech"],"blud":["czech"],"bobek":["czech"],"bobr":["czech"],"bodlina":["czech"],"bodnout":["czech"],"bohatost":["czech"],"bojkot":["czech"],"bojovat":["czech"],"bokorys":["czech"],"bolest":["czech"],"borec":["czech"],"borovice":["czech"],"bota":["czech"],"boubel":["czech"],"bouchat":["czech"],"bouda":["czech"],"boule":["czech"],"bourat":["czech"],"boxer":["czech"],"bradavka":["czech"],"brambora":["czech"],"branka":["czech"],"bratr":["czech"],"brepta":["czech"],"briketa":["czech"],"brko":["czech"],"brloh":["czech"],"bronz":["czech"],"broskev":["czech"],"brunetka":["czech"],"brusinka":["czech"],"brzda":["czech"],"brzy":["czech"],"bublina":["czech"],"bubnovat":["czech"],"buchta":["czech"],"buditel":["czech"],"budka":["czech"],"budova":["czech"],"bufet":["czech"],"bujarost":["czech"],"bukvice":["czech"],"buldok":["czech"],"bulva":["czech"],"bunda":["czech"],"bunkr":["czech"],"burza":["czech"],"butik":["czech","turkish"],"buvol":["czech"],"buzola":["czech"],"bydlet":["czech"],"bylina":["czech"],"bytovka":["czech"],"bzukot":["czech"],"capart":["czech"],"carevna":["czech"],"cedr":["czech"],"cedule":["czech"],"cejch":["czech"],"cejn":["czech"],"cela":["czech"],"celer":["czech"],"celkem":["czech"],"celnice":["czech"],"cenina":["czech"],"cennost":["czech"],"cenovka":["czech"],"centrum":["czech"],"cenzor":["czech"],"cestopis":["czech"],"cetka":["czech"],"chalupa":["czech"],"chapadlo":["czech"],"charita":["czech"],"chata":["czech"],"chechtat":["czech"],"chemie":["czech"],"chichot":["czech"],"chirurg":["czech"],"chlad":["czech"],"chleba":["czech"],"chlubit":["czech"],"chmel":["czech"],"chmura":["czech"],"chobot":["czech"],"chochol":["czech"],"chodba":["czech"],"cholera":["czech"],"chomout":["czech"],"chopit":["czech"],"choroba":["czech"],"chov":["czech"],"chrapot":["czech"],"chrlit":["czech"],"chrt":["czech"],"chrup":["czech"],"chtivost":["czech"],"chudina":["czech"],"chutnat":["czech"],"chvat":["czech"],"chvilka":["czech"],"chvost":["czech"],"chyba":["czech"],"chystat":["czech"],"chytit":["czech"],"cibule":["czech"],"cigareta":["czech"],"cihelna":["czech"],"cihla":["czech"],"cinkot":["czech"],"cirkus":["czech"],"cisterna":["czech"],"citace":["czech"],"citrus":["czech"],"cizinec":["czech"],"cizost":["czech"],"clona":["czech"],"cokoliv":["czech"],"couvat":["czech"],"ctitel":["czech"],"ctnost":["czech"],"cudnost":["czech"],"cuketa":["czech"],"cukr":["czech"],"cupot":["czech"],"cvaknout":["czech"],"cval":["czech"],"cvik":["czech"],"cvrkot":["czech"],"cyklista":["czech"],"daleko":["czech"],"dareba":["czech"],"datel":["czech"],"datum":["czech"],"dcera":["czech"],"debata":["czech"],"dechovka":["czech"],"decibel":["czech"],"deficit":["czech"],"deflace":["czech"],"dekl":["czech"],"dekret":["czech"],"demokrat":["czech"],"deprese":["czech"],"derby":["czech"],"deska":["czech"],"detektiv":["czech"],"dikobraz":["czech"],"diktovat":["czech"],"dioda":["czech"],"diplom":["czech"],"disk":["czech","turkish"],"displej":["czech"],"divadlo":["czech"],"divoch":["czech"],"dlaha":["czech"],"dlouho":["czech"],"dluhopis":["czech"],"dnes":["czech"],"dobro":["czech"],"dobytek":["czech"],"docent":["czech"],"dochutit":["czech"],"dodnes":["czech"],"dohled":["czech"],"dohoda":["czech"],"dohra":["czech"],"dojem":["czech"],"dojnice":["czech"],"doklad":["czech"],"dokola":["czech"],"doktor":["czech","turkish"],"dokument":["czech"],"dolar":["czech"],"doleva":["czech"],"dolina":["czech"],"doma":["czech"],"dominant":["czech"],"domluvit":["czech"],"domov":["czech"],"donutit":["czech"],"dopad":["czech"],"dopis":["czech"],"doplnit":["czech"],"doposud":["czech"],"doprovod":["czech"],"dopustit":["czech"],"dorazit":["czech"],"dorost":["czech"],"dort":["czech"],"dosah":["czech"],"doslov":["czech"],"dostatek":["czech"],"dosud":["czech"],"dosyta":["czech"],"dotaz":["czech"],"dotek":["czech"],"dotknout":["czech"],"doufat":["czech"],"doutnat":["czech"],"dovozce":["czech"],"dozadu":["czech"],"doznat":["czech"],"dozorce":["czech"],"drahota":["czech"],"drak":["czech"],"dramatik":["czech"],"dravec":["czech"],"draze":["czech"],"drdol":["czech"],"drobnost":["czech"],"drogerie":["czech"],"drozd":["czech"],"drsnost":["czech"],"drtit":["czech"],"drzost":["czech"],"duben":["czech"],"duchovno":["czech"],"dudek":["czech"],"duha":["czech"],"duhovka":["czech"],"dusit":["czech"],"dusno":["czech"],"dutost":["czech"],"dvojice":["czech"],"dvorec":["czech"],"dynamit":["czech"],"ekolog":["czech"],"ekonomie":["czech"],"elektron":["czech"],"elipsa":["czech"],"email":["czech"],"emise":["czech"],"emoce":["czech"],"empatie":["czech"],"epizoda":["czech"],"epocha":["czech"],"epopej":["czech"],"epos":["czech"],"esej":["czech"],"esence":["czech"],"eskorta":["czech"],"eskymo":["czech"],"etiketa":["czech"],"euforie":["czech"],"evoluce":["czech"],"exekuce":["czech"],"exkurze":["czech"],"expedice":["czech"],"exploze":["czech"],"export":["czech"],"extrakt":["czech"],"facka":["czech"],"fajfka":["czech"],"fakulta":["czech"],"fanatik":["czech","turkish"],"fantazie":["czech"],"farmacie":["czech"],"favorit":["czech"],"fazole":["czech"],"federace":["czech"],"fejeton":["czech"],"fenka":["czech"],"fialka":["czech"],"figurant":["czech"],"filozof":["czech"],"filtr":["czech"],"finance":["czech"],"finta":["czech"],"fixace":["czech"],"fjord":["czech"],"flanel":["czech"],"flirt":["czech"],"flotila":["czech"],"fond":["czech"],"fosfor":["czech"],"fotbal":["czech"],"fotka":["czech"],"foton":["czech"],"frakce":["czech"],"freska":["czech"],"fronta":["czech"],"fukar":["czech"],"funkce":["czech"],"fyzika":["czech"],"galeje":["czech"],"garant":["czech"],"genetika":["czech"],"geolog":["czech"],"gilotina":["czech"],"glazura":["czech"],"glejt":["czech"],"golem":["czech"],"golfista":["czech"],"gotika":["czech"],"graf":["czech"],"gramofon":["czech"],"granule":["czech"],"grep":["czech"],"gril":["czech"],"grog":["czech"],"groteska":["czech"],"guma":["czech"],"hadice":["czech"],"hadr":["czech"],"hala":["czech"],"halenka":["czech"],"hanba":["czech"],"hanopis":["czech"],"harfa":["czech"],"harpuna":["czech"],"havran":["czech"],"hebkost":["czech"],"hejkal":["czech"],"hejno":["czech"],"hejtman":["czech"],"hektar":["czech","turkish"],"helma":["czech"],"hematom":["czech"],"herec":["czech"],"herna":["czech"],"heslo":["czech"],"hezky":["czech"],"historik":["czech"],"hladovka":["czech"],"hlasivky":["czech"],"hlava":["czech"],"hledat":["czech"],"hlen":["czech"],"hlodavec":["czech"],"hloh":["czech"],"hloupost":["czech"],"hltat":["czech"],"hlubina":["czech"],"hluchota":["czech"],"hmat":["czech"],"hmota":["czech"],"hmyz":["czech"],"hnis":["czech"],"hnojivo":["czech"],"hnout":["czech"],"hoblina":["czech"],"hoboj":["czech"],"hoch":["czech"],"hodiny":["czech"],"hodlat":["czech"],"hodnota":["czech"],"hodovat":["czech"],"hojnost":["czech"],"hokej":["czech"],"holinka":["czech"],"holka":["czech"],"holub":["czech"],"homole":["czech"],"honitba":["czech"],"honorace":["czech"],"horal":["czech"],"horda":["czech"],"horizont":["czech"],"horko":["czech"],"horlivec":["czech"],"hormon":["czech","turkish"],"hornina":["czech"],"horoskop":["czech"],"horstvo":["czech"],"hospoda":["czech"],"hostina":["czech"],"hotovost":["czech"],"houba":["czech"],"houf":["czech"],"houpat":["czech"],"houska":["czech"],"hovor":["czech"],"hradba":["czech"],"hranice":["czech"],"hravost":["czech"],"hrazda":["czech"],"hrbolek":["czech"],"hrdina":["czech"],"hrdlo":["czech"],"hrdost":["czech"],"hrnek":["czech"],"hrobka":["czech"],"hromada":["czech"],"hrot":["czech"],"hrouda":["czech"],"hrozen":["czech"],"hrstka":["czech"],"hrubost":["czech"],"hryzat":["czech"],"hubenost":["czech"],"hubnout":["czech"],"hudba":["czech"],"hukot":["czech"],"humr":["czech"],"husita":["czech"],"hustota":["czech"],"hvozd":["czech"],"hybnost":["czech"],"hydrant":["czech"],"hygiena":["czech"],"hymna":["czech"],"hysterik":["czech"],"idylka":["czech"],"ihned":["czech"],"ikona":["czech"],"iluze":["czech"],"imunita":["czech"],"infekce":["czech"],"inflace":["czech"],"inkaso":["czech"],"inovace":["czech"],"inspekce":["czech"],"internet":["czech"],"invalida":["czech"],"investor":["czech"],"inzerce":["czech"],"ironie":["czech"],"jablko":["czech"],"jachta":["czech"],"jahoda":["czech"],"jakmile":["czech"],"jakost":["czech"],"jalovec":["czech"],"jantar":["czech"],"jarmark":["czech"],"jaro":["czech"],"jasan":["czech"],"jasno":["czech"],"jatka":["czech"],"javor":["czech"],"jazyk":["czech"],"jedinec":["czech"],"jedle":["czech"],"jednatel":["czech"],"jehlan":["czech"],"jekot":["czech"],"jelen":["czech"],"jelito":["czech"],"jemnost":["czech"],"jenom":["czech"],"jepice":["czech"],"jeseter":["czech"],"jevit":["czech"],"jezdec":["czech"],"jezero":["czech"],"jinak":["czech"],"jindy":["czech"],"jinoch":["czech"],"jiskra":["czech"],"jistota":["czech"],"jitrnice":["czech"],"jizva":["czech"],"jmenovat":["czech"],"jogurt":["czech"],"jurta":["czech"],"kabaret":["czech"],"kabel":["czech"],"kabinet":["czech"],"kachna":["czech"],"kadet":["czech"],"kadidlo":["czech"],"kahan":["czech"],"kajak":["czech"],"kajuta":["czech"],"kakao":["czech"],"kaktus":["czech"],"kalamita":["czech"],"kalhoty":["czech"],"kalibr":["czech"],"kalnost":["czech"],"kamera":["czech"],"kamkoliv":["czech"],"kamna":["czech"],"kanibal":["czech"],"kanoe":["czech"],"kantor":["czech"],"kapalina":["czech"],"kapela":["czech"],"kapitola":["czech"],"kapka":["czech"],"kaple":["czech"],"kapota":["czech"],"kapr":["czech"],"kapusta":["czech"],"kapybara":["czech"],"karamel":["czech"],"karotka":["czech"],"karton":["czech"],"kasa":["czech"],"katalog":["czech"],"katedra":["czech"],"kauce":["czech"],"kauza":["czech"],"kavalec":["czech"],"kazajka":["czech"],"kazeta":["czech"],"kazivost":["czech"],"kdekoliv":["czech"],"kdesi":["czech"],"kedluben":["czech"],"kemp":["czech"],"keramika":["czech"],"kino":["czech"],"klacek":["czech"],"kladivo":["czech"],"klam":["czech"],"klapot":["czech"],"klasika":["czech"],"klaun":["czech"],"klec":["czech"],"klenba":["czech"],"klepat":["czech"],"klesnout":["czech"],"klid":["czech"],"klima":["czech"],"klisna":["czech"],"klobouk":["czech"],"klokan":["czech"],"klopa":["czech"],"kloub":["czech"],"klubovna":["czech"],"klusat":["czech"],"kluzkost":["czech"],"kmen":["czech"],"kmitat":["czech"],"kmotr":["czech"],"kniha":["czech"],"knot":["czech"],"koalice":["czech"],"koberec":["czech"],"kobka":["czech"],"kobliha":["czech"],"kobyla":["czech"],"kocour":["czech"],"kohout":["czech"],"kojenec":["czech"],"kokos":["czech"],"koktejl":["czech"],"kolaps":["czech"],"koleda":["czech"],"kolize":["czech"],"kolo":["czech"],"komando":["czech"],"kometa":["czech"],"komik":["czech"],"komnata":["czech"],"komora":["czech"],"kompas":["czech"],"komunita":["czech"],"konat":["czech"],"koncept":["czech"],"kondice":["czech"],"konec":["czech"],"konfese":["czech"],"kongres":["czech"],"konina":["czech"],"konkurs":["czech"],"kontakt":["czech"],"konzerva":["czech"],"kopanec":["czech"],"kopie":["czech"],"kopnout":["czech"],"koprovka":["czech"],"korbel":["czech"],"korektor":["czech"],"kormidlo":["czech"],"koroptev":["czech"],"korpus":["czech"],"koruna":["czech"],"koryto":["czech"],"korzet":["czech"],"kosatec":["czech"],"kostka":["czech"],"kotel":["czech"],"kotleta":["czech"],"kotoul":["czech"],"koukat":["czech"],"koupelna":["czech"],"kousek":["czech"],"kouzlo":["czech"],"kovboj":["czech"],"koza":["czech"],"kozoroh":["czech"],"krabice":["czech"],"krach":["czech"],"krajina":["czech"],"kralovat":["czech"],"krasopis":["czech"],"kravata":["czech"],"kredit":["czech"],"krejcar":["czech"],"kresba":["czech"],"kreveta":["czech"],"kriket":["czech"],"kritik":["czech"],"krize":["czech"],"krkavec":["czech"],"krmelec":["czech"],"krmivo":["czech"],"krocan":["czech"],"krok":["czech"],"kronika":["czech"],"kropit":["czech"],"kroupa":["czech"],"krovka":["czech"],"krtek":["czech"],"kruhadlo":["czech"],"krupice":["czech"],"krutost":["czech"],"krvinka":["czech"],"krychle":["czech"],"krypta":["czech"],"krystal":["czech"],"kryt":["czech"],"kudlanka":["czech"],"kufr":["czech"],"kujnost":["czech"],"kukla":["czech"],"kulajda":["czech"],"kulich":["czech"],"kulka":["czech"],"kulomet":["czech"],"kultura":["czech"],"kuna":["czech"],"kupodivu":["czech"],"kurt":["czech"],"kurzor":["czech"],"kutil":["czech"],"kvalita":["czech"],"kvasinka":["czech"],"kvestor":["czech"],"kynolog":["czech"],"kyselina":["czech"],"kytara":["czech"],"kytice":["czech"],"kytka":["czech"],"kytovec":["czech"],"kyvadlo":["czech"],"labrador":["czech"],"lachtan":["czech"],"ladnost":["czech"],"laik":["czech"],"lakomec":["czech"],"lamela":["czech"],"lampa":["czech"],"lanovka":["czech"],"lasice":["czech"],"laso":["czech"],"lastura":["czech"],"latinka":["czech"],"lavina":["czech"],"lebka":["czech"],"leckdy":["czech"],"leden":["czech"],"lednice":["czech"],"ledovka":["czech"],"ledvina":["czech"],"legenda":["czech"],"legie":["czech"],"legrace":["czech"],"lehce":["czech"],"lehkost":["czech"],"lehnout":["czech"],"lektvar":["czech"],"lenochod":["czech"],"lentilka":["czech"],"lepenka":["czech"],"lepidlo":["czech"],"letadlo":["czech"],"letec":["czech"],"letmo":["czech"],"letokruh":["czech"],"levhart":["czech"],"levitace":["czech"],"levobok":["czech"],"libra":["czech"],"lichotka":["czech"],"lidojed":["czech"],"lidskost":["czech"],"lihovina":["czech"],"lijavec":["czech"],"lilek":["czech"],"limetka":["czech"],"linie":["czech"],"linka":["czech"],"linoleum":["czech"],"listopad":["czech"],"litina":["czech"],"litovat":["czech"],"lobista":["czech"],"lodivod":["czech"],"logika":["czech"],"logoped":["czech"],"lokalita":["czech"],"loket":["czech"],"lomcovat":["czech"],"lopata":["czech"],"lopuch":["czech"],"lord":["czech"],"losos":["czech"],"lotr":["czech"],"loudal":["czech"],"louh":["czech"],"louka":["czech"],"louskat":["czech"],"lovec":["czech"],"lstivost":["czech"],"lucerna":["czech"],"lucifer":["czech"],"lump":["czech"],"lusk":["czech"],"lustrace":["czech"],"lvice":["czech"],"lyra":["czech"],"lyrika":["czech"],"lysina":["czech"],"madam":["czech"],"madlo":["czech"],"magistr":["czech"],"mahagon":["czech"],"majetek":["czech"],"majitel":["czech"],"majorita":["czech"],"makak":["czech"],"makovice":["czech"],"makrela":["czech"],"malba":["czech"],"malina":["czech"],"malovat":["czech"],"malvice":["czech"],"maminka":["czech"],"mandle":["czech"],"manko":["czech"],"marnost":["czech"],"masakr":["czech"],"maskot":["czech"],"masopust":["czech"],"matice":["czech"],"matrika":["czech"],"maturita":["czech"],"mazanec":["czech"],"mazivo":["czech"],"mazlit":["czech"],"mazurka":["czech"],"mdloba":["czech"],"mechanik":["czech"],"meditace":["czech"],"medovina":["czech"],"melasa":["czech"],"meloun":["czech"],"mentolka":["czech"],"metla":["czech"],"metoda":["czech"],"metr":["czech"],"mezera":["czech"],"migrace":["czech"],"mihnout":["czech"],"mihule":["czech"],"mikina":["czech"],"mikrofon":["czech","turkish"],"milenec":["czech"],"milimetr":["czech"],"milost":["czech"],"mimika":["czech"],"mincovna":["czech"],"minibar":["czech"],"minomet":["czech"],"minulost":["czech"],"miska":["czech"],"mistr":["czech"],"mixovat":["czech"],"mladost":["czech"],"mlha":["czech"],"mlhovina":["czech"],"mlok":["czech"],"mlsat":["czech"],"mluvit":["czech"],"mnich":["czech"],"mnohem":["czech"],"mobil":["czech"],"mocnost":["czech"],"modelka":["czech"],"modlitba":["czech"],"mohyla":["czech"],"mokro":["czech"],"molekula":["czech"],"momentka":["czech"],"monarcha":["czech"],"monokl":["czech"],"monstrum":["czech"],"montovat":["czech"],"monzun":["czech"],"mosaz":["czech"],"moskyt":["czech"],"most":["czech"],"motivace":["czech"],"motorka":["czech"],"motyka":["czech"],"moucha":["czech"],"moudrost":["czech"],"mozaika":["czech"],"mozek":["czech"],"mozol":["czech"],"mramor":["czech"],"mravenec":["czech"],"mrkev":["czech"],"mrtvola":["czech"],"mrzet":["czech"],"mrzutost":["czech"],"mstitel":["czech"],"mudrc":["czech"],"muflon":["czech"],"mulat":["czech"],"mumie":["czech"],"munice":["czech"],"muset":["czech"],"mutace":["czech"],"muzeum":["czech"],"muzikant":["czech"],"myslivec":["czech"],"mzda":["czech"],"nabourat":["czech"],"nachytat":["czech"],"nadace":["czech"],"nadbytek":["czech"],"nadhoz":["czech"],"nadobro":["czech"],"nadpis":["czech"],"nahlas":["czech"],"nahnat":["czech"],"nahodile":["czech"],"nahradit":["czech"],"naivita":["czech"],"najednou":["czech"],"najisto":["czech"],"najmout":["czech"],"naklonit":["czech"],"nakonec":["czech"],"nakrmit":["czech"],"nalevo":["czech"],"namazat":["czech"],"namluvit":["czech"],"nanometr":["czech"],"naoko":["czech"],"naopak":["czech"],"naostro":["czech"],"napadat":["czech"],"napevno":["czech"],"naplnit":["czech"],"napnout":["czech"],"naposled":["czech"],"naprosto":["czech"],"narodit":["czech"],"naruby":["czech"],"narychlo":["czech"],"nasadit":["czech"],"nasekat":["czech"],"naslepo":["czech"],"nastat":["czech"],"natolik":["czech"],"navenek":["czech"],"navrch":["czech"],"navzdory":["czech"],"nazvat":["czech"],"nebe":["czech"],"nechat":["czech"],"necky":["czech"],"nedaleko":["czech"],"nedbat":["czech"],"neduh":["czech"],"negace":["czech"],"nehet":["czech"],"nehoda":["czech"],"nejen":["czech"],"nejprve":["czech"],"neklid":["czech"],"nelibost":["czech"],"nemilost":["czech"],"nemoc":["czech"],"neochota":["czech"],"neonka":["czech"],"nepokoj":["czech"],"nerost":["czech"],"nerv":["czech"],"nesmysl":["czech"],"nesoulad":["czech"],"netvor":["czech"],"neuron":["czech"],"nevina":["czech"],"nezvykle":["czech"],"nicota":["czech"],"nijak":["czech"],"nikam":["czech"],"nikdy":["czech"],"nikl":["czech"],"nikterak":["czech"],"nitro":["czech"],"nocleh":["czech"],"nohavice":["czech"],"nominace":["czech"],"nora":["czech"],"norek":["czech"],"nositel":["czech"],"nosnost":["czech"],"nouze":["czech"],"noviny":["czech"],"novota":["czech"],"nozdra":["czech"],"nuda":["czech"],"nudle":["czech"],"nuget":["czech"],"nutit":["czech"],"nutnost":["czech"],"nutrie":["czech"],"nymfa":["czech"],"obal":["czech"],"obarvit":["czech"],"obava":["czech"],"obdiv":["czech"],"obec":["czech"],"obehnat":["czech"],"obejmout":["czech"],"obezita":["czech"],"obhajoba":["czech"],"obilnice":["czech"],"objasnit":["czech"],"objekt":["czech"],"obklopit":["czech"],"oblast":["czech"],"oblek":["czech"],"obliba":["czech"],"obloha":["czech"],"obluda":["czech"],"obnos":["czech"],"obohatit":["czech"],"obojek":["czech"],"obout":["czech"],"obrazec":["czech"],"obrna":["czech"],"obruba":["czech"],"obrys":["czech"],"obsah":["czech"],"obsluha":["czech"],"obstarat":["czech"],"obuv":["czech"],"obvaz":["czech"],"obvinit":["czech"],"obvod":["czech"],"obvykle":["czech"],"obyvatel":["czech"],"obzor":["czech"],"ocas":["czech"],"ocel":["czech"],"ocenit":["czech"],"ochladit":["czech"],"ochota":["czech"],"ochrana":["czech"],"ocitnout":["czech"],"odboj":["czech"],"odbyt":["czech"],"odchod":["czech"],"odcizit":["czech"],"odebrat":["czech"],"odeslat":["czech"],"odevzdat":["czech"],"odezva":["czech"],"odhadce":["czech"],"odhodit":["czech"],"odjet":["czech"],"odjinud":["czech"],"odkaz":["czech"],"odkoupit":["czech"],"odliv":["czech"],"odluka":["czech"],"odmlka":["czech"],"odolnost":["czech"],"odpad":["czech"],"odpis":["czech"],"odplout":["czech"],"odpor":["czech"],"odpustit":["czech"],"odpykat":["czech"],"odrazka":["czech"],"odsoudit":["czech"],"odstup":["czech"],"odsun":["czech"],"odtok":["czech"],"odtud":["czech"],"odvaha":["czech"],"odveta":["czech"],"odvolat":["czech"],"odvracet":["czech"],"odznak":["czech"],"ofina":["czech"],"ofsajd":["czech"],"ohlas":["czech"],"ohnisko":["czech"],"ohrada":["czech"],"ohrozit":["czech"],"ohryzek":["czech"],"okap":["czech"],"okenice":["czech"],"oklika":["czech"],"okno":["czech"],"okouzlit":["czech"],"okovy":["czech"],"okrasa":["czech"],"okres":["czech"],"okrsek":["czech"],"okruh":["czech"],"okupant":["czech"],"okurka":["czech"],"okusit":["czech"],"olejnina":["czech"],"olizovat":["czech"],"omak":["czech"],"omeleta":["czech"],"omezit":["czech"],"omladina":["czech"],"omlouvat":["czech"],"omluva":["czech"],"omyl":["czech"],"onehdy":["czech"],"opakovat":["czech"],"opasek":["czech"],"operace":["czech"],"opice":["czech"],"opilost":["czech"],"opisovat":["czech"],"opora":["czech"],"opozice":["czech"],"opravdu":["czech"],"oproti":["czech"],"orbital":["czech"],"orchestr":["czech"],"orgie":["czech"],"orlice":["czech"],"orloj":["czech"],"ortel":["czech"],"osada":["czech"],"oschnout":["czech"],"osika":["czech"],"osivo":["czech"],"oslava":["czech"],"oslepit":["czech"],"oslnit":["czech"],"oslovit":["czech"],"osnova":["czech"],"osoba":["czech"],"osolit":["czech"],"ospalec":["czech"],"osten":["czech"],"ostraha":["czech"],"ostuda":["czech"],"ostych":["czech"],"osvojit":["czech"],"oteplit":["czech"],"otisk":["czech"],"otop":["czech"],"otrhat":["czech"],"otrlost":["czech"],"otrok":["czech"],"otruby":["czech"],"otvor":["czech"],"ovanout":["czech"],"ovar":["czech"],"oves":["czech"],"ovlivnit":["czech"],"ovoce":["czech"],"oxid":["czech"],"ozdoba":["czech"],"pachatel":["czech"],"pacient":["czech"],"padouch":["czech"],"pahorek":["czech"],"pakt":["czech"],"palanda":["czech"],"palec":["czech"],"palivo":["czech"],"paluba":["czech"],"pamflet":["czech"],"pamlsek":["czech"],"panenka":["czech"],"panika":["czech"],"panna":["czech"],"panovat":["czech"],"panstvo":["czech"],"pantofle":["czech"],"paprika":["czech"],"parketa":["czech"],"parodie":["czech"],"parta":["czech"],"paruka":["czech"],"paryba":["czech"],"paseka":["czech"],"pasivita":["czech"],"pastelka":["czech"],"patent":["czech"],"patrona":["czech"],"pavouk":["czech"],"pazneht":["czech"],"pazourek":["czech"],"pecka":["czech"],"pedagog":["czech"],"pejsek":["czech"],"peklo":["czech"],"peloton":["czech"],"penalta":["czech"],"pendrek":["czech"],"penze":["czech"],"periskop":["czech"],"pero":["czech"],"pestrost":["czech"],"petarda":["czech"],"petice":["czech"],"petrolej":["czech"],"pevnina":["czech"],"pexeso":["czech"],"pianista":["czech"],"piha":["czech"],"pijavice":["czech"],"pikle":["czech"],"piknik":["czech","turkish"],"pilina":["czech"],"pilnost":["czech"],"pilulka":["czech"],"pinzeta":["czech"],"pipeta":["czech"],"pisatel":["czech"],"pistole":["czech"],"pitevna":["czech"],"pivnice":["czech"],"pivovar":["czech"],"placenta":["czech"],"plakat":["czech"],"plamen":["czech"],"planeta":["czech"],"plastika":["czech"],"platit":["czech"],"plavidlo":["czech"],"plaz":["czech"],"plech":["czech"],"plemeno":["czech"],"plenta":["czech"],"ples":["czech"],"pletivo":["czech"],"plevel":["czech"],"plivat":["czech"],"plnit":["czech"],"plno":["czech"],"plocha":["czech"],"plodina":["czech"],"plomba":["czech"],"plout":["czech"],"pluk":["czech"],"plyn":["czech"],"pobavit":["czech"],"pobyt":["czech"],"pochod":["czech"],"pocit":["czech"],"poctivec":["czech"],"podat":["czech"],"podcenit":["czech"],"podepsat":["czech"],"podhled":["czech"],"podivit":["czech"],"podklad":["czech"],"podmanit":["czech"],"podnik":["czech"],"podoba":["czech"],"podpora":["czech"],"podraz":["czech"],"podstata":["czech"],"podvod":["czech"],"podzim":["czech"],"poezie":["czech"],"pohanka":["czech"],"pohnutka":["czech"],"pohovor":["czech"],"pohroma":["czech"],"pohyb":["czech"],"pointa":["czech"],"pojistka":["czech"],"pojmout":["czech"],"pokazit":["czech"],"pokles":["czech"],"pokoj":["czech"],"pokrok":["czech"],"pokuta":["czech"],"pokyn":["czech"],"poledne":["czech"],"polibek":["czech"],"polknout":["czech"],"poloha":["czech"],"polynom":["czech"],"pomalu":["czech"],"pominout":["czech"],"pomlka":["czech"],"pomoc":["czech"],"pomsta":["czech"],"pomyslet":["czech"],"ponechat":["czech"],"ponorka":["czech"],"ponurost":["czech"],"popadat":["czech"],"popel":["czech"],"popisek":["czech"],"poplach":["czech"],"poprosit":["czech"],"popsat":["czech"],"popud":["czech"],"poradce":["czech"],"porce":["czech"],"porod":["czech"],"porucha":["czech"],"poryv":["czech"],"posadit":["czech"],"posed":["czech"],"posila":["czech"],"poskok":["czech"],"poslanec":["czech"],"posoudit":["czech"],"pospolu":["czech"],"postava":["czech"],"posudek":["czech"],"posyp":["czech"],"potah":["czech"],"potkan":["czech"],"potlesk":["czech"],"potomek":["czech"],"potrava":["czech"],"potupa":["czech"],"potvora":["czech"],"poukaz":["czech"],"pouto":["czech"],"pouzdro":["czech"],"povaha":["czech"],"povidla":["czech"],"povlak":["czech"],"povoz":["czech"],"povrch":["czech"],"povstat":["czech"],"povyk":["czech"],"povzdech":["czech"],"pozdrav":["czech"],"pozemek":["czech"],"poznatek":["czech"],"pozor":["czech"],"pozvat":["czech"],"pracovat":["czech"],"prahory":["czech"],"praktika":["czech"],"prales":["czech"],"praotec":["czech"],"praporek":["czech"],"prase":["czech"],"pravda":["czech"],"princip":["czech"],"prkno":["czech"],"probudit":["czech"],"procento":["czech"],"prodej":["czech"],"profese":["czech"],"prohra":["czech"],"projekt":["czech"],"prolomit":["czech"],"promile":["czech"],"pronikat":["czech"],"propad":["czech"],"prorok":["czech"],"prosba":["czech"],"proton":["czech"],"proutek":["czech"],"provaz":["czech"],"prskavka":["czech"],"prsten":["czech"],"prudkost":["czech"],"prut":["czech"],"prvek":["czech"],"prvohory":["czech"],"psanec":["czech"],"psovod":["czech"],"pstruh":["czech"],"ptactvo":["czech"],"puberta":["czech"],"puch":["czech"],"pudl":["czech"],"pukavec":["czech"],"puklina":["czech"],"pukrle":["czech"],"pult":["czech"],"pumpa":["czech"],"punc":["czech"],"pupen":["czech"],"pusa":["czech"],"pusinka":["czech"],"pustina":["czech"],"putovat":["czech"],"putyka":["czech"],"pyramida":["czech"],"pysk":["czech"],"pytel":["czech"],"racek":["czech"],"rachot":["czech"],"radiace":["czech"],"radnice":["czech"],"radon":["czech"],"raft":["czech"],"ragby":["czech"],"raketa":["czech"],"rakovina":["czech"],"rameno":["czech"],"rampouch":["czech"],"rande":["czech"],"rarach":["czech"],"rarita":["czech"],"rasovna":["czech"],"rastr":["czech"],"ratolest":["czech"],"razance":["czech"],"razidlo":["czech"],"reagovat":["czech"],"reakce":["czech"],"recept":["czech"],"redaktor":["czech"],"referent":["czech"],"reflex":["czech"],"rejnok":["czech"],"reklama":["czech"],"rekord":["czech"],"rekrut":["czech"],"rektor":["czech"],"reputace":["czech"],"revize":["czech","turkish"],"revma":["czech"],"revolver":["czech"],"rezerva":["czech"],"riskovat":["czech"],"riziko":["czech"],"robotika":["czech"],"rodokmen":["czech"],"rohovka":["czech"],"rokle":["czech"],"rokoko":["czech"],"romaneto":["czech"],"ropovod":["czech"],"ropucha":["czech"],"rorejs":["czech"],"rosol":["czech"],"rostlina":["czech"],"rotmistr":["czech"],"rotoped":["czech"],"rotunda":["czech"],"roubenka":["czech"],"roucho":["czech"],"roup":["czech"],"roura":["czech"],"rovina":["czech"],"rovnice":["czech"],"rozbor":["czech"],"rozchod":["czech"],"rozdat":["czech"],"rozeznat":["czech"],"rozhodce":["czech"],"rozinka":["czech"],"rozjezd":["czech"],"rozkaz":["czech"],"rozloha":["czech"],"rozmar":["czech"],"rozpad":["czech"],"rozruch":["czech"],"rozsah":["czech"],"roztok":["czech"],"rozum":["czech"],"rozvod":["czech"],"rubrika":["czech"],"ruchadlo":["czech"],"rukavice":["czech"],"rukopis":["czech"],"ryba":["czech"],"rybolov":["czech"],"rychlost":["czech"],"rydlo":["czech"],"rypadlo":["czech"],"rytina":["czech"],"ryzost":["czech"],"sadista":["czech"],"sahat":["czech"],"sako":["czech"],"samec":["czech"],"samizdat":["czech"],"samota":["czech"],"sanitka":["czech"],"sardinka":["czech"],"sasanka":["czech"],"satelit":["czech"],"sazba":["czech"],"sazenice":["czech"],"sbor":["czech"],"schovat":["czech"],"sebranka":["czech"],"secese":["czech"],"sedadlo":["czech"],"sediment":["czech"],"sedlo":["czech"],"sehnat":["czech"],"sejmout":["czech"],"sekera":["czech"],"sekta":["czech"],"sekunda":["czech"],"sekvoje":["czech"],"semeno":["czech"],"seno":["czech"],"servis":["czech","turkish"],"sesadit":["czech"],"seshora":["czech"],"seskok":["czech"],"seslat":["czech"],"sestra":["czech"],"sesuv":["czech"],"sesypat":["czech"],"setba":["czech"],"setina":["czech"],"setkat":["czech"],"setnout":["czech"],"setrvat":["czech"],"sever":["czech"],"seznam":["czech"],"shoda":["czech"],"shrnout":["czech"],"sifon":["czech"],"silnice":["czech"],"sirka":["czech"],"sirotek":["czech"],"sirup":["czech"],"situace":["czech"],"skafandr":["czech"],"skalisko":["czech"],"skanzen":["czech"],"skaut":["czech"],"skeptik":["czech"],"skica":["czech"],"skladba":["czech"],"sklenice":["czech"],"sklo":["czech"],"skluz":["czech"],"skoba":["czech"],"skokan":["czech"],"skoro":["czech"],"skripta":["czech"],"skrz":["czech"],"skupina":["czech"],"skvost":["czech"],"skvrna":["czech"],"slabika":["czech"],"sladidlo":["czech"],"slanina":["czech"],"slast":["czech"],"slavnost":["czech"],"sledovat":["czech"],"slepec":["czech"],"sleva":["czech"],"slezina":["czech"],"slib":["czech"],"slina":["czech"],"sliznice":["czech"],"slon":["czech"],"sloupek":["czech"],"slovo":["czech"],"sluch":["czech"],"sluha":["czech"],"slunce":["czech"],"slupka":["czech"],"slza":["czech"],"smaragd":["czech"],"smetana":["czech"],"smilstvo":["czech"],"smlouva":["czech"],"smog":["czech"],"smrad":["czech"],"smrk":["czech"],"smrtka":["czech"],"smutek":["czech"],"smysl":["czech"],"snad":["czech"],"snaha":["czech"],"snob":["czech"],"sobota":["czech"],"socha":["czech"],"sodovka":["czech"],"sokol":["czech"],"sopka":["czech"],"sotva":["czech"],"souboj":["czech"],"soucit":["czech"],"soudce":["czech"],"souhlas":["czech"],"soulad":["czech"],"soumrak":["czech"],"souprava":["czech"],"soused":["czech"],"soutok":["czech"],"souviset":["czech"],"spalovna":["czech"],"spasitel":["czech"],"spis":["czech"],"splav":["czech"],"spodek":["czech"],"spojenec":["czech"],"spolu":["czech"],"sponzor":["czech"],"spornost":["czech"],"spousta":["czech"],"sprcha":["czech"],"spustit":["czech"],"sranda":["czech"],"sraz":["czech"],"srdce":["czech"],"srna":["czech"],"srnec":["czech"],"srovnat":["czech"],"srpen":["czech"],"srst":["czech"],"srub":["czech"],"stanice":["czech"],"starosta":["czech"],"statika":["czech"],"stavba":["czech"],"stehno":["czech"],"stezka":["czech"],"stodola":["czech"],"stolek":["czech"],"stopa":["czech"],"storno":["czech"],"stoupat":["czech"],"strach":["czech"],"stres":["czech"],"strhnout":["czech"],"strom":["czech"],"struna":["czech"],"studna":["czech"],"stupnice":["czech"],"stvol":["czech"],"styk":["czech"],"subjekt":["czech"],"subtropy":["czech"],"suchar":["czech"],"sudost":["czech"],"sukno":["czech"],"sundat":["czech"],"sunout":["czech"],"surikata":["czech"],"surovina":["czech"],"svah":["czech"],"svalstvo":["czech"],"svetr":["czech"],"svatba":["czech"],"svazek":["czech"],"svisle":["czech"],"svitek":["czech"],"svoboda":["czech"],"svodidlo":["czech"],"svorka":["czech"],"svrab":["czech"],"sykavka":["czech"],"sykot":["czech"],"synek":["czech"],"synovec":["czech"],"sypat":["czech"],"sypkost":["czech"],"syrovost":["czech"],"sysel":["czech"],"sytost":["czech"],"tabletka":["czech"],"tabule":["czech"],"tahoun":["czech"],"tajemno":["czech"],"tajfun":["czech"],"tajga":["czech"],"tajit":["czech"],"tajnost":["czech"],"taktika":["czech"],"tamhle":["czech"],"tampon":["czech","turkish"],"tancovat":["czech"],"tanec":["czech"],"tanker":["czech"],"tapeta":["czech"],"tavenina":["czech"],"tazatel":["czech"],"technika":["czech"],"tehdy":["czech"],"tekutina":["czech"],"telefon":["czech"],"temnota":["czech"],"tendence":["czech"],"tenista":["czech"],"tenor":["czech"],"teplota":["czech"],"tepna":["czech"],"teprve":["czech"],"terapie":["czech"],"termoska":["czech"],"textil":["czech"],"ticho":["czech"],"tiskopis":["czech"],"titulek":["czech"],"tkadlec":["czech"],"tkanina":["czech"],"tlapka":["czech"],"tleskat":["czech"],"tlukot":["czech"],"tlupa":["czech"],"tmel":["czech"],"toaleta":["czech"],"topinka":["czech"],"topol":["czech"],"torzo":["czech"],"touha":["czech"],"toulec":["czech"],"tradice":["czech"],"traktor":["czech"],"tramp":["czech"],"trasa":["czech"],"traverza":["czech"],"trefit":["czech"],"trest":["czech"],"trezor":["czech"],"trhavina":["czech"],"trhlina":["czech"],"trochu":["czech"],"trojice":["czech"],"troska":["czech"],"trouba":["czech"],"trpce":["czech"],"trpitel":["czech"],"trpkost":["czech"],"trubec":["czech"],"truchlit":["czech"],"truhlice":["czech"],"trus":["czech"],"trvat":["czech"],"tudy":["czech"],"tuhnout":["czech"],"tuhost":["czech"],"tundra":["czech"],"turista":["czech"],"turnaj":["czech"],"tuzemsko":["czech"],"tvaroh":["czech"],"tvorba":["czech"],"tvrdost":["czech"],"tvrz":["czech"],"tygr":["czech"],"tykev":["czech"],"ubohost":["czech"],"uboze":["czech"],"ubrat":["czech"],"ubrousek":["czech"],"ubrus":["czech"],"ubytovna":["czech"],"ucho":["czech"],"uctivost":["czech"],"udivit":["czech"],"uhradit":["czech"],"ujednat":["czech"],"ujistit":["czech"],"ujmout":["czech"],"ukazatel":["czech"],"uklidnit":["czech"],"uklonit":["czech"],"ukotvit":["czech"],"ukrojit":["czech"],"ulice":["czech"],"ulita":["czech"],"ulovit":["czech"],"umyvadlo":["czech"],"unavit":["czech"],"uniforma":["czech"],"uniknout":["czech"],"upadnout":["czech"],"uplatnit":["czech"],"uplynout":["czech"],"upoutat":["czech"],"upravit":["czech"],"uran":["czech"],"urazit":["czech"],"usednout":["czech"],"usilovat":["czech"],"usmrtit":["czech"],"usnadnit":["czech"],"usnout":["czech"],"usoudit":["czech"],"ustlat":["czech"],"ustrnout":["czech"],"utahovat":["czech"],"utkat":["czech"],"utlumit":["czech"],"utonout":["czech"],"utopenec":["czech"],"utrousit":["czech"],"uvalit":["czech"],"uvolnit":["czech"],"uvozovka":["czech"],"uzdravit":["czech"],"uzel":["czech"],"uzenina":["czech"],"uzlina":["czech"],"uznat":["czech"],"vagon":["czech","turkish"],"valcha":["czech"],"valoun":["czech"],"vana":["czech"],"vandal":["czech"],"vanilka":["czech"],"varan":["czech"],"varhany":["czech"],"varovat":["czech"],"vcelku":["czech"],"vchod":["czech"],"vdova":["czech"],"vedro":["czech"],"vegetace":["czech"],"vejce":["czech"],"velbloud":["czech"],"veletrh":["czech"],"velitel":["czech"],"velmoc":["czech"],"velryba":["czech"],"venkov":["czech"],"veranda":["czech"],"verze":["czech"],"veselka":["czech"],"veskrze":["czech"],"vesnice":["czech"],"vespodu":["czech"],"vesta":["czech"],"veterina":["czech"],"veverka":["czech"],"vibrace":["czech"],"vichr":["czech"],"videohra":["czech"],"vidina":["czech"],"vidle":["czech"],"vila":["czech"],"vinice":["czech"],"viset":["czech"],"vitalita":["czech"],"vize":["czech"],"vizitka":["czech"],"vjezd":["czech"],"vklad":["czech"],"vkus":["czech"],"vlajka":["czech"],"vlak":["czech"],"vlasec":["czech"],"vlevo":["czech"],"vlhkost":["czech"],"vliv":["czech"],"vlnovka":["czech"],"vloupat":["czech"],"vnucovat":["czech"],"vnuk":["czech"],"voda":["czech"],"vodivost":["czech"],"vodoznak":["czech"],"vodstvo":["czech"],"vojensky":["czech"],"vojna":["czech"],"vojsko":["czech"],"volant":["czech"],"volba":["czech"],"volit":["czech"],"volno":["czech"],"voskovka":["czech"],"vozidlo":["czech"],"vozovna":["czech"],"vpravo":["czech"],"vrabec":["czech"],"vracet":["czech"],"vrah":["czech"],"vrata":["czech"],"vrba":["czech"],"vrcholek":["czech"],"vrhat":["czech"],"vrstva":["czech"],"vrtule":["czech"],"vsadit":["czech"],"vstoupit":["czech"],"vstup":["czech"],"vtip":["czech"],"vybavit":["czech"],"vybrat":["czech"],"vychovat":["czech"],"vydat":["czech"],"vydra":["czech"],"vyfotit":["czech"],"vyhledat":["czech"],"vyhnout":["czech"],"vyhodit":["czech"],"vyhradit":["czech"],"vyhubit":["czech"],"vyjasnit":["czech"],"vyjet":["czech"],"vyjmout":["czech"],"vyklopit":["czech"],"vykonat":["czech"],"vylekat":["czech"],"vymazat":["czech"],"vymezit":["czech"],"vymizet":["czech"],"vymyslet":["czech"],"vynechat":["czech"],"vynikat":["czech"],"vynutit":["czech"],"vypadat":["czech"],"vyplatit":["czech"],"vypravit":["czech"],"vypustit":["czech"],"vyrazit":["czech"],"vyrovnat":["czech"],"vyrvat":["czech"],"vyslovit":["czech"],"vysoko":["czech"],"vystavit":["czech"],"vysunout":["czech"],"vysypat":["czech"],"vytasit":["czech"],"vytesat":["czech"],"vytratit":["czech"],"vyvinout":["czech"],"vyvolat":["czech"],"vyvrhel":["czech"],"vyzdobit":["czech"],"vyznat":["czech"],"vzadu":["czech"],"vzbudit":["czech"],"vzchopit":["czech"],"vzdor":["czech"],"vzduch":["czech"],"vzdychat":["czech"],"vzestup":["czech"],"vzhledem":["czech"],"vzkaz":["czech"],"vzlykat":["czech"],"vznik":["czech"],"vzorek":["czech"],"vzpoura":["czech"],"vztah":["czech"],"vztek":["czech"],"xylofon":["czech"],"zabrat":["czech"],"zabydlet":["czech"],"zachovat":["czech"],"zadarmo":["czech"],"zadusit":["czech"],"zafoukat":["czech"],"zahltit":["czech"],"zahodit":["czech"],"zahrada":["czech"],"zahynout":["czech"],"zajatec":["czech"],"zajet":["czech"],"zajistit":["czech"],"zaklepat":["czech"],"zakoupit":["czech"],"zalepit":["czech"],"zamezit":["czech"],"zamotat":["czech"],"zamyslet":["czech"],"zanechat":["czech"],"zanikat":["czech"],"zaplatit":["czech"],"zapojit":["czech"],"zapsat":["czech"],"zarazit":["czech"],"zastavit":["czech"],"zasunout":["czech"],"zatajit":["czech"],"zatemnit":["czech"],"zatknout":["czech"],"zaujmout":["czech"],"zavalit":["czech"],"zavelet":["czech"],"zavinit":["czech"],"zavolat":["czech"],"zavrtat":["czech"],"zazvonit":["czech"],"zbavit":["czech"],"zbrusu":["czech"],"zbudovat":["czech"],"zbytek":["czech"],"zdaleka":["czech"],"zdarma":["czech"],"zdatnost":["czech"],"zdivo":["czech"],"zdobit":["czech"],"zdroj":["czech"],"zdvih":["czech"],"zdymadlo":["czech"],"zelenina":["czech"],"zeman":["czech"],"zemina":["czech"],"zeptat":["czech"],"zezadu":["czech"],"zezdola":["czech"],"zhatit":["czech"],"zhltnout":["czech"],"zhluboka":["czech"],"zhotovit":["czech"],"zhruba":["czech"],"zima":["czech"],"zimnice":["czech"],"zjemnit":["czech"],"zklamat":["czech"],"zkoumat":["czech"],"zkratka":["czech"],"zkumavka":["czech"],"zlato":["czech"],"zlehka":["czech"],"zloba":["czech"],"zlom":["czech"],"zlost":["czech"],"zlozvyk":["czech"],"zmapovat":["czech"],"zmar":["czech"],"zmatek":["czech"],"zmije":["czech"],"zmizet":["czech"],"zmocnit":["czech"],"zmodrat":["czech"],"zmrzlina":["czech"],"zmutovat":["czech"],"znak":["czech"],"znalost":["czech"],"znamenat":["czech"],"znovu":["czech"],"zobrazit":["czech"],"zotavit":["czech"],"zoubek":["czech"],"zoufale":["czech"],"zplodit":["czech"],"zpomalit":["czech"],"zprava":["czech"],"zprostit":["czech"],"zprudka":["czech"],"zprvu":["czech"],"zrada":["czech"],"zranit":["czech"],"zrcadlo":["czech"],"zrnitost":["czech"],"zrno":["czech"],"zrovna":["czech"],"zrychlit":["czech"],"zrzavost":["czech"],"zticha":["czech"],"ztratit":["czech"],"zubovina":["czech"],"zubr":["czech"],"zvednout":["czech"],"zvenku":["czech"],"zvesela":["czech"],"zvon":["czech"],"zvrat":["czech"],"zvukovod":["czech"],"zvyk":["czech"],"abandon":["english","french"],"ability":["english"],"able":["english"],"about":["english"],"above":["english"],"absent":["english"],"absorb":["english"],"abstract":["english"],"absurd":["english"],"abuse":["english"],"access":["english"],"accident":["english"],"account":["english"],"accuse":["english"],"achieve":["english"],"acid":["english"],"acoustic":["english"],"acquire":["english"],"across":["english"],"act":["english"],"action":["english"],"actor":["english"],"actress":["english"],"actual":["english"],"adapt":["english"],"add":["english"],"addict":["english"],"address":["english"],"adjust":["english"],"admit":["english"],"adult":["english"],"advance":["english"],"advice":["english"],"aerobic":["english"],"affair":["english"],"afford":["english"],"afraid":["english"],"again":["english"],"age":["english"],"agent":["english"],"agree":["english"],"ahead":["english"],"aim":["english"],"air":["english"],"airport":["english"],"aisle":["english"],"alarm":["english"],"album":["english"],"alcohol":["english"],"alert":["english"],"alien":["english"],"all":["english"],"alley":["english"],"allow":["english"],"almost":["english"],"alone":["english"],"alpha":["english"],"already":["english"],"also":["english"],"alter":["english"],"always":["english"],"amateur":["english","french"],"amazing":["english"],"among":["english"],"amount":["english"],"amused":["english"],"analyst":["english"],"anchor":["english"],"ancient":["english"],"anger":["english"],"angle":["english","french"],"angry":["english"],"animal":["english","french"],"ankle":["english"],"announce":["english"],"annual":["english"],"another":["english"],"answer":["english"],"antenna":["english"],"antique":["english"],"anxiety":["english"],"any":["english"],"apart":["english"],"apology":["english"],"appear":["english"],"apple":["english"],"approve":["english"],"april":["english"],"arch":["english"],"arctic":["english"],"area":["english"],"arena":["english","turkish"],"argue":["english"],"arm":["english"],"armed":["english"],"armor":["english"],"army":["english"],"around":["english"],"arrange":["english"],"arrest":["english"],"arrive":["english"],"arrow":["english"],"art":["english"],"artefact":["english"],"artist":["english","turkish"],"artwork":["english"],"ask":["english"],"aspect":["english","french"],"assault":["english"],"asset":["english"],"assist":["english"],"assume":["english"],"asthma":["english"],"athlete":["english"],"atom":["english","turkish"],"attack":["english"],"attend":["english"],"attitude":["english"],"attract":["english"],"auction":["english"],"audit":["english"],"august":["english"],"aunt":["english"],"author":["english"],"auto":["english"],"autumn":["english"],"average":["english"],"avocado":["english"],"avoid":["english"],"awake":["english"],"aware":["english"],"away":["english"],"awesome":["english"],"awful":["english"],"awkward":["english"],"axis":["english"],"baby":["english"],"bachelor":["english"],"bacon":["english"],"badge":["english","french"],"bag":["english"],"balance":["english"],"balcony":["english"],"ball":["english"],"bamboo":["english"],"banana":["english"],"banner":["english"],"bar":["english"],"barely":["english"],"bargain":["english"],"barrel":["english"],"base":["english"],"basic":["english"],"basket":["english"],"battle":["english"],"beach":["english"],"bean":["english"],"beauty":["english"],"because":["english"],"become":["english"],"beef":["english"],"before":["english"],"begin":["english"],"behave":["english"],"behind":["english"],"believe":["english"],"below":["english"],"belt":["english"],"bench":["english"],"benefit":["english"],"best":["english"],"betray":["english"],"better":["english"],"between":["english"],"beyond":["english"],"bicycle":["english","french"],"bid":["english"],"bike":["english"],"bind":["english"],"biology":["english"],"bird":["english"],"birth":["english"],"bitter":["english"],"black":["english"],"blade":["english"],"blame":["english"],"blanket":["english"],"blast":["english"],"bleak":["english"],"bless":["english"],"blind":["english"],"blood":["english"],"blossom":["english"],"blouse":["english"],"blue":["english"],"blur":["english"],"blush":["english"],"board":["english"],"boat":["english"],"body":["english"],"boil":["english"],"bomb":["english"],"bone":["english"],"bonus":["english","french"],"book":["english"],"boost":["english"],"border":["english"],"boring":["english"],"borrow":["english"],"boss":["english"],"bottom":["english"],"bounce":["english"],"box":["english"],"boy":["english"],"bracket":["english"],"brain":["english"],"brand":["english"],"brass":["english"],"brave":["english","french"],"bread":["english"],"breeze":["english"],"brick":["english"],"bridge":["english"],"brief":["english"],"bright":["english"],"bring":["english"],"brisk":["english"],"broccoli":["english"],"broken":["english"],"bronze":["english"],"broom":["english"],"brother":["english"],"brown":["english"],"brush":["english"],"bubble":["english"],"buddy":["english"],"budget":["english"],"buffalo":["english"],"build":["english"],"bulb":["english"],"bulk":["english"],"bullet":["english"],"bundle":["english"],"bunker":["english"],"burden":["english"],"burger":["english"],"burst":["english"],"bus":["english"],"business":["english"],"busy":["english"],"butter":["english"],"buyer":["english"],"buzz":["english"],"cabbage":["english"],"cabin":["english"],"cable":["english"],"cactus":["english"],"cage":["english"],"cake":["english"],"call":["english"],"calm":["english"],"camera":["english"],"camp":["english"],"can":["english"],"canal":["english","french"],"cancel":["english"],"candy":["english"],"cannon":["english"],"canoe":["english"],"canvas":["english"],"canyon":["english"],"capable":["english","french"],"capital":["english"],"captain":["english"],"car":["english"],"carbon":["english"],"card":["english"],"cargo":["english"],"carpet":["english"],"carry":["english"],"cart":["english"],"case":["english"],"cash":["english"],"casino":["english"],"castle":["english"],"casual":["english"],"cat":["english"],"catalog":["english"],"catch":["english"],"category":["english"],"cattle":["english"],"caught":["english"],"cause":["english"],"caution":["english","french"],"cave":["english"],"ceiling":["english"],"celery":["english"],"cement":["english"],"census":["english"],"century":["english"],"cereal":["english"],"certain":["english"],"chair":["english"],"chalk":["english"],"champion":["english"],"change":["english"],"chaos":["english"],"chapter":["english"],"charge":["english"],"chase":["english"],"chat":["english"],"cheap":["english"],"check":["english"],"cheese":["english"],"chef":["english"],"cherry":["english"],"chest":["english"],"chicken":["english"],"chief":["english"],"child":["english"],"chimney":["english"],"choice":["english"],"choose":["english"],"chronic":["english"],"chuckle":["english"],"chunk":["english"],"churn":["english"],"cigar":["english"],"cinnamon":["english"],"circle":["english"],"citizen":["english"],"city":["english"],"civil":["english","french"],"claim":["english"],"clap":["english"],"clarify":["english"],"claw":["english"],"clay":["english"],"clean":["english"],"clerk":["english"],"clever":["english"],"click":["english"],"client":["english","french"],"cliff":["english"],"climb":["english"],"clinic":["english"],"clip":["english"],"clock":["english"],"clog":["english"],"close":["english"],"cloth":["english"],"cloud":["english"],"clown":["english"],"club":["english"],"clump":["english"],"cluster":["english"],"clutch":["english"],"coach":["english"],"coast":["english"],"coconut":["english"],"code":["english"],"coffee":["english"],"coil":["english"],"coin":["english"],"collect":["english"],"color":["english"],"column":["english"],"combine":["english"],"come":["english"],"comfort":["english"],"comic":["english"],"common":["english"],"company":["english"],"concert":["english","french"],"conduct":["english"],"confirm":["english"],"congress":["english"],"connect":["english"],"consider":["english"],"control":["english"],"convince":["english"],"cook":["english"],"cool":["english"],"copper":["english"],"copy":["english"],"coral":["english"],"core":["english"],"corn":["english"],"correct":["english","french"],"cost":["english"],"cotton":["english"],"couch":["english"],"country":["english"],"couple":["english"],"course":["english"],"cousin":["english"],"cover":["english"],"coyote":["english","french"],"crack":["english"],"cradle":["english"],"craft":["english"],"cram":["english"],"crane":["english"],"crash":["english"],"crater":["english"],"crawl":["english"],"crazy":["english"],"cream":["english"],"credit":["english"],"creek":["english"],"crew":["english"],"cricket":["english"],"crime":["english"],"crisp":["english"],"critic":["english"],"crop":["english"],"cross":["english"],"crouch":["english"],"crowd":["english"],"crucial":["english","french"],"cruel":["english","french"],"cruise":["english"],"crumble":["english"],"crunch":["english"],"crush":["english"],"cry":["english"],"crystal":["english"],"cube":["english"],"culture":["english"],"cup":["english"],"cupboard":["english"],"curious":["english"],"current":["english"],"curtain":["english"],"curve":["english"],"cushion":["english"],"custom":["english"],"cute":["english"],"cycle":["english","french"],"dad":["english"],"damage":["english"],"damp":["english"],"dance":["english"],"danger":["english","french"],"daring":["english"],"dash":["english"],"daughter":["english"],"dawn":["english"],"day":["english"],"deal":["english"],"debate":["english"],"debris":["english"],"decade":["english"],"december":["english"],"decide":["english"],"decline":["english"],"decorate":["english"],"decrease":["english"],"deer":["english"],"defense":["english"],"define":["english"],"defy":["english"],"degree":["english"],"delay":["english"],"deliver":["english"],"demand":["english"],"demise":["english"],"denial":["english"],"dentist":["english"],"deny":["english"],"depart":["english"],"depend":["english"],"deposit":["english"],"depth":["english"],"deputy":["english"],"derive":["english"],"describe":["english"],"desert":["english"],"design":["english"],"desk":["english"],"despair":["english"],"destroy":["english"],"detail":["english"],"detect":["english"],"develop":["english"],"device":["english"],"devote":["english"],"diagram":["english"],"dial":["english"],"diamond":["english"],"diary":["english"],"dice":["english"],"diesel":["english"],"diet":["english"],"differ":["english"],"digital":["english","french"],"dignity":["english"],"dilemma":["english"],"dinner":["english"],"dinosaur":["english"],"direct":["english"],"dirt":["english"],"disagree":["english"],"discover":["english"],"disease":["english"],"dish":["english"],"dismiss":["english"],"disorder":["english"],"display":["english"],"distance":["english","french"],"divert":["english"],"divide":["english"],"divorce":["english"],"dizzy":["english"],"doctor":["english"],"document":["english"],"dog":["english"],"doll":["english"],"dolphin":["english"],"domain":["english"],"donate":["english"],"donkey":["english"],"donor":["english"],"door":["english"],"dose":["english"],"double":["english","french"],"dove":["english"],"draft":["english"],"dragon":["english","french"],"drama":["english"],"drastic":["english"],"draw":["english"],"dream":["english"],"dress":["english"],"drift":["english"],"drill":["english"],"drink":["english"],"drip":["english"],"drive":["english"],"drop":["english"],"drum":["english"],"dry":["english"],"duck":["english"],"dumb":["english"],"dune":["english"],"during":["english"],"dust":["english"],"dutch":["english"],"duty":["english"],"dwarf":["english"],"dynamic":["english"],"eager":["english"],"eagle":["english"],"early":["english"],"earn":["english"],"earth":["english"],"easily":["english"],"east":["english"],"easy":["english"],"echo":["english"],"ecology":["english"],"economy":["english"],"edge":["english"],"edit":["english"],"educate":["english"],"effort":["english","french"],"egg":["english"],"eight":["english"],"either":["english"],"elbow":["english"],"elder":["english"],"electric":["english"],"elegant":["english"],"element":["english"],"elephant":["english"],"elevator":["english"],"elite":["english"],"else":["english"],"embark":["english"],"embody":["english"],"embrace":["english"],"emerge":["english"],"emotion":["english"],"employ":["english"],"empower":["english"],"empty":["english"],"enable":["english"],"enact":["english"],"end":["english"],"endless":["english"],"endorse":["english"],"enemy":["english"],"energy":["english"],"enforce":["english"],"engage":["english"],"engine":["english"],"enhance":["english"],"enjoy":["english"],"enlist":["english"],"enough":["english"],"enrich":["english"],"enroll":["english"],"ensure":["english"],"enter":["english"],"entire":["english"],"entry":["english"],"envelope":["english"],"episode":["english"],"equal":["english"],"equip":["english"],"era":["english"],"erase":["english"],"erode":["english"],"erosion":["english"],"error":["english"],"erupt":["english"],"escape":["english"],"essay":["english"],"essence":["english","french"],"estate":["english"],"eternal":["english"],"ethics":["english"],"evidence":["english"],"evil":["english"],"evoke":["english"],"evolve":["english"],"exact":["english","french"],"example":["english"],"excess":["english"],"exchange":["english"],"excite":["english"],"exclude":["english"],"excuse":["english","french"],"execute":["english"],"exercise":["english"],"exhaust":["english"],"exhibit":["english"],"exile":["english"],"exist":["english"],"exit":["english"],"exotic":["english"],"expand":["english"],"expect":["english"],"expire":["english"],"explain":["english"],"expose":["english"],"express":["english"],"extend":["english"],"extra":["english"],"eye":["english"],"eyebrow":["english"],"fabric":["english"],"face":["english"],"faculty":["english"],"fade":["english"],"faint":["english"],"faith":["english"],"fall":["english"],"false":["english"],"fame":["english"],"family":["english"],"famous":["english"],"fan":["english"],"fancy":["english"],"fantasy":["english"],"farm":["english"],"fashion":["english"],"fat":["english"],"fatal":["english","french"],"father":["english"],"fatigue":["english","french"],"fault":["english"],"favorite":["english"],"feature":["english"],"february":["english"],"federal":["english","turkish"],"fee":["english"],"feed":["english"],"feel":["english"],"female":["english"],"fence":["english"],"festival":["english","french","turkish"],"fetch":["english"],"fever":["english"],"few":["english"],"fiber":["english"],"fiction":["english"],"field":["english"],"figure":["english","french"],"file":["english"],"film":["english"],"filter":["english"],"final":["english"],"find":["english"],"fine":["english"],"finger":["english"],"finish":["english"],"fire":["english"],"firm":["english"],"first":["english"],"fiscal":["english"],"fish":["english"],"fit":["english"],"fitness":["english"],"fix":["english"],"flag":["english"],"flame":["english"],"flash":["english"],"flat":["english"],"flavor":["english"],"flee":["english"],"flight":["english"],"flip":["english"],"float":["english"],"flock":["english"],"floor":["english"],"flower":["english"],"fluid":["english"],"flush":["english"],"fly":["english"],"foam":["english"],"focus":["english"],"fog":["english"],"foil":["english"],"fold":["english"],"follow":["english"],"food":["english"],"foot":["english"],"force":["english"],"forest":["english"],"forget":["english"],"fork":["english"],"fortune":["english","french"],"forum":["english"],"forward":["english"],"fossil":["english"],"foster":["english"],"found":["english"],"fox":["english"],"fragile":["english","french"],"frame":["english"],"frequent":["english"],"fresh":["english"],"friend":["english"],"fringe":["english"],"frog":["english"],"front":["english"],"frost":["english"],"frown":["english"],"frozen":["english"],"fruit":["english","french"],"fuel":["english"],"fun":["english"],"funny":["english"],"furnace":["english"],"fury":["english"],"future":["english"],"gadget":["english"],"gain":["english"],"galaxy":["english"],"gallery":["english"],"game":["english"],"gap":["english"],"garage":["english"],"garbage":["english"],"garden":["english"],"garlic":["english"],"garment":["english"],"gas":["english"],"gasp":["english"],"gate":["english"],"gather":["english"],"gauge":["english"],"gaze":["english"],"general":["english"],"genius":["english"],"genre":["english"],"gentle":["english"],"genuine":["english"],"gesture":["english"],"ghost":["english"],"giant":["english"],"gift":["english"],"giggle":["english"],"ginger":["english"],"giraffe":["english"],"girl":["english"],"give":["english"],"glad":["english"],"glance":["english"],"glare":["english"],"glass":["english"],"glide":["english"],"glimpse":["english"],"globe":["english","french"],"gloom":["english"],"glory":["english"],"glove":["english"],"glow":["english"],"glue":["english"],"goat":["english"],"goddess":["english"],"gold":["english"],"good":["english"],"goose":["english"],"gorilla":["english"],"gospel":["english"],"gossip":["english"],"govern":["english"],"gown":["english"],"grab":["english"],"grace":["english"],"grain":["english"],"grant":["english"],"grape":["english"],"grass":["english"],"gravity":["english"],"great":["english"],"green":["english"],"grid":["english"],"grief":["english"],"grit":["english"],"grocery":["english"],"group":["english"],"grow":["english"],"grunt":["english"],"guard":["english"],"guess":["english"],"guide":["english","french"],"guilt":["english"],"guitar":["english"],"gun":["english"],"gym":["english"],"habit":["english"],"hair":["english"],"half":["english"],"hammer":["english"],"hamster":["english"],"hand":["english"],"happy":["english"],"harbor":["english"],"hard":["english"],"harsh":["english"],"harvest":["english"],"hat":["english"],"have":["english"],"hawk":["english"],"hazard":["english"],"head":["english"],"health":["english"],"heart":["english"],"heavy":["english"],"hedgehog":["english"],"height":["english"],"hello":["english"],"helmet":["english"],"help":["english"],"hen":["english"],"hero":["english"],"hidden":["english"],"high":["english"],"hill":["english"],"hint":["english"],"hip":["english"],"hire":["english"],"history":["english"],"hobby":["english"],"hockey":["english"],"hold":["english"],"hole":["english"],"holiday":["english"],"hollow":["english"],"home":["english"],"honey":["english"],"hood":["english"],"hope":["english"],"horn":["english"],"horror":["english"],"horse":["english"],"hospital":["english"],"host":["english"],"hotel":["english"],"hour":["english"],"hover":["english"],"hub":["english"],"huge":["english"],"human":["english"],"humble":["english","french"],"humor":["english"],"hundred":["english"],"hungry":["english"],"hunt":["english"],"hurdle":["english"],"hurry":["english"],"hurt":["english"],"husband":["english"],"hybrid":["english"],"ice":["english"],"icon":["english"],"idea":["english"],"identify":["english"],"idle":["english"],"ignore":["english"],"ill":["english"],"illegal":["english"],"illness":["english"],"image":["english","french"],"imitate":["english"],"immense":["english","french"],"immune":["english"],"impact":["english","french"],"impose":["english"],"improve":["english"],"impulse":["english"],"inch":["english"],"include":["english"],"income":["english"],"increase":["english"],"index":["english"],"indicate":["english"],"indoor":["english"],"industry":["english"],"infant":["english"],"inflict":["english"],"inform":["english"],"inhale":["english"],"inherit":["english"],"initial":["english"],"inject":["english"],"injury":["english"],"inmate":["english"],"inner":["english"],"innocent":["english","french"],"input":["english"],"inquiry":["english"],"insane":["english"],"insect":["english"],"inside":["english"],"inspire":["english"],"install":["english"],"intact":["english","french"],"interest":["english"],"into":["english"],"invest":["english"],"invite":["english"],"involve":["english"],"iron":["english"],"island":["english"],"isolate":["english"],"issue":["english"],"item":["english"],"ivory":["english"],"jacket":["english"],"jaguar":["english","french"],"jar":["english"],"jazz":["english"],"jealous":["english"],"jeans":["english"],"jelly":["english"],"jewel":["english"],"job":["english"],"join":["english"],"joke":["english"],"journey":["english"],"joy":["english"],"judge":["english"],"juice":["english"],"jump":["english"],"jungle":["english"],"junior":["english","french"],"junk":["english"],"just":["english"],"kangaroo":["english"],"keen":["english"],"keep":["english"],"ketchup":["english"],"key":["english"],"kick":["english"],"kid":["english"],"kidney":["english"],"kind":["english"],"kingdom":["english"],"kiss":["english"],"kit":["english"],"kitchen":["english"],"kite":["english"],"kitten":["english"],"kiwi":["english"],"knee":["english"],"knife":["english"],"knock":["english"],"know":["english"],"lab":["english"],"label":["english","french"],"labor":["english"],"ladder":["english"],"lady":["english"],"lake":["english"],"lamp":["english"],"language":["english"],"laptop":["english"],"large":["english"],"later":["english"],"latin":["english"],"laugh":["english"],"laundry":["english"],"lava":["english"],"law":["english"],"lawn":["english"],"lawsuit":["english"],"layer":["english"],"lazy":["english"],"leader":["english"],"leaf":["english"],"learn":["english"],"leave":["english"],"lecture":["english","french"],"left":["english"],"leg":["english"],"legal":["english"],"legend":["english"],"leisure":["english"],"lemon":["english"],"lend":["english"],"length":["english"],"lens":["english"],"leopard":["english"],"lesson":["english"],"letter":["english"],"level":["english"],"liar":["english"],"liberty":["english"],"library":["english"],"license":["english"],"life":["english"],"lift":["english"],"light":["english"],"like":["english"],"limb":["english"],"limit":["english"],"link":["english"],"lion":["english"],"liquid":["english"],"list":["english"],"little":["english"],"live":["english"],"lizard":["english"],"load":["english"],"loan":["english"],"lobster":["english"],"local":["english"],"lock":["english"],"logic":["english"],"lonely":["english"],"long":["english"],"loop":["english"],"lottery":["english"],"loud":["english"],"lounge":["english"],"love":["english"],"loyal":["english","french"],"lucky":["english"],"luggage":["english"],"lumber":["english"],"lunar":["english"],"lunch":["english"],"luxury":["english"],"lyrics":["english"],"machine":["english","french"],"mad":["english"],"magic":["english"],"magnet":["english"],"maid":["english"],"mail":["english"],"main":["english"],"major":["english"],"make":["english"],"mammal":["english"],"man":["english"],"manage":["english"],"mandate":["english"],"mango":["english"],"mansion":["english"],"manual":["english"],"maple":["english"],"marble":["english"],"march":["english"],"margin":["english"],"marine":["english"],"market":["english","turkish"],"marriage":["english"],"mask":["english"],"mass":["english"],"master":["english"],"match":["english"],"material":["english"],"math":["english"],"matrix":["english"],"matter":["english"],"maximum":["english"],"maze":["english"],"meadow":["english"],"mean":["english"],"measure":["english"],"meat":["english"],"mechanic":["english"],"medal":["english"],"media":["english"],"melody":["english"],"melt":["english"],"member":["english"],"memory":["english"],"mention":["english"],"menu":["english"],"mercy":["english"],"merge":["english"],"merit":["english"],"merry":["english"],"mesh":["english"],"message":["english"],"metal":["english"],"method":["english"],"middle":["english"],"midnight":["english"],"milk":["english"],"million":["english","french"],"mimic":["english"],"mind":["english"],"minimum":["english"],"minor":["english"],"minute":["english","french"],"miracle":["english","french"],"mirror":["english"],"misery":["english"],"miss":["english"],"mistake":["english"],"mix":["english"],"mixed":["english"],"mixture":["english"],"mobile":["english","french"],"model":["english","turkish"],"modify":["english"],"mom":["english"],"moment":["english"],"monitor":["english"],"monkey":["english"],"monster":["english"],"month":["english"],"moon":["english"],"moral":["english"],"more":["english"],"morning":["english"],"mosquito":["english"],"mother":["english"],"motion":["english"],"motor":["english","turkish"],"mountain":["english"],"mouse":["english"],"move":["english"],"movie":["english"],"much":["english"],"muffin":["english"],"mule":["english"],"multiply":["english"],"muscle":["english","french"],"museum":["english"],"mushroom":["english"],"music":["english"],"must":["english"],"mutual":["english"],"myself":["english"],"mystery":["english"],"myth":["english"],"naive":["english"],"name":["english"],"napkin":["english"],"narrow":["english"],"nasty":["english"],"nation":["english","french"],"nature":["english","french"],"near":["english"],"neck":["english"],"need":["english"],"negative":["english"],"neglect":["english"],"neither":["english"],"nephew":["english"],"nerve":["english"],"nest":["english"],"net":["english"],"network":["english"],"neutral":["english"],"never":["english"],"news":["english"],"next":["english"],"nice":["english"],"night":["english"],"noble":["english","french"],"noise":["english"],"nominee":["english"],"noodle":["english"],"normal":["english","turkish"],"north":["english"],"nose":["english"],"notable":["english","french"],"note":["english"],"nothing":["english"],"notice":["english"],"novel":["english"],"now":["english"],"nuclear":["english"],"number":["english"],"nurse":["english"],"nut":["english"],"oak":["english"],"obey":["english"],"object":["english"],"oblige":["english"],"obscure":["english"],"observe":["english"],"obtain":["english"],"obvious":["english"],"occur":["english"],"ocean":["english"],"october":["english"],"odor":["english"],"off":["english"],"offer":["english"],"office":["english"],"often":["english"],"oil":["english"],"okay":["english"],"old":["english"],"olive":["english"],"olympic":["english"],"omit":["english"],"once":["english"],"one":["english"],"onion":["english"],"online":["english"],"only":["english"],"open":["english"],"opera":["english","turkish"],"opinion":["english","french"],"oppose":["english"],"option":["english"],"orange":["english","french"],"orbit":["english"],"orchard":["english"],"order":["english"],"ordinary":["english"],"organ":["english"],"orient":["english"],"original":["english"],"orphan":["english"],"ostrich":["english"],"other":["english"],"outdoor":["english"],"outer":["english"],"output":["english"],"outside":["english"],"oval":["english"],"oven":["english"],"over":["english"],"own":["english"],"owner":["english"],"oxygen":["english"],"oyster":["english"],"ozone":["english","french"],"pact":["english"],"paddle":["english"],"page":["english"],"pair":["english"],"palace":["english","french"],"palm":["english"],"panda":["english","french","turkish"],"panel":["english","turkish"],"panic":["english"],"panther":["english"],"paper":["english"],"parade":["english"],"parent":["english"],"park":["english"],"parrot":["english"],"party":["english"],"pass":["english"],"patch":["english"],"path":["english"],"patient":["english"],"patrol":["english"],"pattern":["english"],"pause":["english"],"pave":["english"],"payment":["english"],"peace":["english"],"peanut":["english"],"pear":["english"],"peasant":["english"],"pelican":["english"],"pen":["english"],"penalty":["english"],"pencil":["english"],"people":["english"],"pepper":["english"],"perfect":["english"],"permit":["english"],"person":["english"],"pet":["english"],"phone":["english"],"photo":["english"],"phrase":["english","french"],"physical":["english"],"piano":["english","french"],"picnic":["english"],"picture":["english"],"piece":["english"],"pig":["english"],"pigeon":["english"],"pill":["english"],"pilot":["english","turkish"],"pink":["english"],"pioneer":["english"],"pipe":["english"],"pistol":["english"],"pitch":["english"],"pizza":["english","french"],"place":["english"],"planet":["english"],"plastic":["english"],"plate":["english"],"play":["english"],"please":["english"],"pledge":["english"],"pluck":["english"],"plug":["english"],"plunge":["english"],"poem":["english"],"poet":["english"],"point":["english"],"polar":["english"],"pole":["english"],"police":["english"],"pond":["english"],"pony":["english"],"pool":["english"],"popular":["english"],"portion":["english"],"position":["english","french"],"possible":["english"],"post":["english"],"potato":["english"],"pottery":["english"],"poverty":["english"],"powder":["english"],"power":["english"],"practice":["english"],"praise":["english"],"predict":["english"],"prefer":["english"],"prepare":["english"],"present":["english"],"pretty":["english"],"prevent":["english"],"price":["english"],"pride":["english"],"primary":["english"],"print":["english"],"priority":["english"],"prison":["english","french"],"private":["english"],"prize":["english"],"problem":["english","turkish"],"process":["english"],"produce":["english"],"profit":["english"],"program":["english","turkish"],"project":["english"],"promote":["english"],"proof":["english"],"property":["english"],"prosper":["english"],"protect":["english"],"proud":["english"],"provide":["english"],"public":["english","french"],"pudding":["english"],"pull":["english"],"pulp":["english"],"pulse":["english"],"pumpkin":["english"],"punch":["english"],"pupil":["english"],"puppy":["english"],"purchase":["english"],"purity":["english"],"purpose":["english"],"purse":["english"],"push":["english"],"put":["english"],"puzzle":["english","french"],"pyramid":["english"],"quality":["english"],"quantum":["english"],"quarter":["english"],"question":["english","french"],"quick":["english"],"quit":["english"],"quiz":["english"],"quote":["english"],"rabbit":["english"],"raccoon":["english"],"race":["english"],"rack":["english"],"radar":["english","turkish"],"radio":["english"],"rail":["english"],"rain":["english"],"raise":["english"],"rally":["english"],"ramp":["english"],"ranch":["english"],"random":["english"],"range":["english"],"rapid":["english"],"rare":["english"],"rate":["english"],"rather":["english"],"raven":["english"],"raw":["english"],"razor":["english"],"ready":["english"],"real":["english"],"reason":["english"],"rebel":["english"],"rebuild":["english"],"recall":["english"],"receive":["english"],"recipe":["english"],"record":["english"],"recycle":["english"],"reduce":["english"],"reflect":["english"],"reform":["english","turkish"],"refuse":["english"],"region":["english"],"regret":["english"],"regular":["english"],"reject":["english"],"relax":["english"],"release":["english"],"relief":["english","french"],"rely":["english"],"remain":["english"],"remember":["english"],"remind":["english"],"remove":["english"],"render":["english"],"renew":["english"],"rent":["english"],"reopen":["english"],"repair":["english"],"repeat":["english"],"replace":["english"],"report":["english"],"require":["english"],"rescue":["english"],"resemble":["english"],"resist":["english"],"resource":["english"],"response":["english"],"result":["english"],"retire":["english"],"retreat":["english"],"return":["english"],"reunion":["english"],"reveal":["english"],"review":["english"],"reward":["english"],"rhythm":["english"],"rib":["english"],"ribbon":["english"],"rice":["english"],"rich":["english"],"ride":["english"],"ridge":["english"],"rifle":["english"],"right":["english"],"rigid":["english"],"ring":["english"],"riot":["english"],"ripple":["english"],"risk":["english"],"ritual":["english"],"rival":["english","french"],"river":["english"],"road":["english"],"roast":["english"],"robot":["english","turkish"],"robust":["english"],"rocket":["english"],"romance":["english","french"],"roof":["english"],"rookie":["english"],"room":["english"],"rose":["english"],"rotate":["english"],"rough":["english"],"round":["english"],"route":["english"],"royal":["english"],"rubber":["english"],"rude":["english"],"rug":["english"],"rule":["english"],"run":["english"],"runway":["english"],"rural":["english"],"sad":["english"],"saddle":["english"],"sadness":["english"],"safe":["english"],"sail":["english"],"salad":["english"],"salmon":["english"],"salon":["english","french","turkish"],"salt":["english"],"salute":["english"],"same":["english"],"sample":["english"],"sand":["english"],"satisfy":["english"],"satoshi":["english"],"sauce":["english"],"sausage":["english"],"save":["english"],"say":["english"],"scale":["english"],"scan":["english"],"scare":["english"],"scatter":["english"],"scene":["english"],"scheme":["english"],"school":["english"],"science":["english","french"],"scissors":["english"],"scorpion":["english"],"scout":["english"],"scrap":["english"],"screen":["english"],"script":["english"],"scrub":["english"],"sea":["english"],"search":["english"],"season":["english"],"seat":["english"],"second":["english"],"secret":["english"],"section":["english"],"security":["english"],"seed":["english"],"seek":["english"],"segment":["english"],"select":["english"],"sell":["english"],"seminar":["english"],"senior":["english"],"sense":["english"],"sentence":["english","french"],"series":["english"],"service":["english","french"],"session":["english"],"settle":["english"],"setup":["english"],"seven":["english"],"shadow":["english"],"shaft":["english"],"shallow":["english"],"share":["english"],"shed":["english"],"shell":["english"],"sheriff":["english"],"shield":["english"],"shift":["english"],"shine":["english"],"ship":["english"],"shiver":["english"],"shock":["english"],"shoe":["english"],"shoot":["english"],"shop":["english"],"short":["english"],"shoulder":["english"],"shove":["english"],"shrimp":["english"],"shrug":["english"],"shuffle":["english"],"shy":["english"],"sibling":["english"],"sick":["english"],"side":["english"],"siege":["english"],"sight":["english"],"sign":["english"],"silent":["english"],"silk":["english"],"silly":["english"],"silver":["english"],"similar":["english"],"simple":["english","french"],"since":["english"],"sing":["english"],"siren":["english"],"sister":["english"],"situate":["english"],"six":["english"],"size":["english"],"skate":["english"],"sketch":["english"],"ski":["english"],"skill":["english"],"skin":["english"],"skirt":["english"],"skull":["english"],"slab":["english"],"slam":["english"],"sleep":["english"],"slender":["english"],"slice":["english"],"slide":["english"],"slight":["english"],"slim":["english"],"slogan":["english","turkish"],"slot":["english"],"slow":["english"],"slush":["english"],"small":["english"],"smart":["english"],"smile":["english"],"smoke":["english"],"smooth":["english"],"snack":["english"],"snake":["english"],"snap":["english"],"sniff":["english"],"snow":["english"],"soap":["english"],"soccer":["english"],"social":["english","french"],"sock":["english"],"soda":["english"],"soft":["english"],"solar":["english"],"soldier":["english"],"solid":["english"],"solution":["english"],"solve":["english"],"someone":["english"],"song":["english"],"soon":["english"],"sorry":["english"],"sort":["english"],"soul":["english"],"sound":["english"],"soup":["english"],"source":["english","french"],"south":["english"],"space":["english"],"spare":["english"],"spatial":["english","french"],"spawn":["english"],"speak":["english"],"special":["english"],"speed":["english"],"spell":["english"],"spend":["english"],"sphere":["english"],"spice":["english"],"spider":["english"],"spike":["english"],"spin":["english"],"spirit":["english"],"split":["english"],"spoil":["english"],"sponsor":["english","turkish"],"spoon":["english"],"sport":["english"],"spot":["english"],"spray":["english"],"spread":["english"],"spring":["english"],"spy":["english"],"square":["english"],"squeeze":["english"],"squirrel":["english"],"stable":["english","french"],"stadium":["english"],"staff":["english"],"stage":["english"],"stairs":["english"],"stamp":["english"],"stand":["english"],"start":["english"],"state":["english"],"stay":["english"],"steak":["english"],"steel":["english"],"stem":["english"],"step":["english"],"stereo":["english"],"stick":["english"],"still":["english"],"sting":["english"],"stock":["english"],"stomach":["english"],"stone":["english"],"stool":["english"],"story":["english"],"stove":["english"],"strategy":["english"],"street":["english"],"strike":["english"],"strong":["english"],"struggle":["english"],"student":["english"],"stuff":["english"],"stumble":["english"],"style":["english"],"subject":["english"],"submit":["english"],"subway":["english"],"success":["english"],"such":["english"],"sudden":["english"],"suffer":["english"],"sugar":["english"],"suggest":["english"],"suit":["english"],"summer":["english"],"sun":["english"],"sunny":["english"],"sunset":["english"],"super":["english"],"supply":["english"],"supreme":["english"],"sure":["english"],"surface":["english","french"],"surge":["english"],"surprise":["english","french"],"surround":["english"],"survey":["english"],"suspect":["english","french"],"sustain":["english"],"swallow":["english"],"swamp":["english"],"swap":["english"],"swarm":["english"],"swear":["english"],"sweet":["english"],"swift":["english"],"swim":["english"],"swing":["english"],"switch":["english"],"sword":["english"],"symbol":["english"],"symptom":["english"],"syrup":["english"],"system":["english"],"table":["english"],"tackle":["english"],"tag":["english"],"tail":["english"],"talent":["english","french"],"talk":["english"],"tank":["english"],"tape":["english"],"target":["english"],"task":["english"],"taste":["english"],"tattoo":["english"],"taxi":["english"],"teach":["english"],"team":["english"],"tell":["english"],"ten":["english"],"tenant":["english"],"tennis":["english"],"tent":["english"],"term":["english"],"test":["english"],"text":["english"],"thank":["english"],"that":["english"],"theme":["english"],"then":["english"],"theory":["english"],"there":["english"],"they":["english"],"thing":["english"],"this":["english"],"thought":["english"],"three":["english"],"thrive":["english"],"throw":["english"],"thumb":["english"],"thunder":["english"],"ticket":["english"],"tide":["english"],"tiger":["english"],"tilt":["english"],"timber":["english"],"time":["english"],"tiny":["english"],"tip":["english"],"tired":["english"],"tissue":["english"],"title":["english"],"toast":["english"],"tobacco":["english"],"today":["english"],"toddler":["english"],"toe":["english"],"together":["english"],"toilet":["english"],"token":["english"],"tomato":["english"],"tomorrow":["english"],"tone":["english"],"tongue":["english"],"tonight":["english"],"tool":["english"],"tooth":["english"],"top":["english"],"topic":["english"],"topple":["english"],"torch":["english"],"tornado":["english"],"tortoise":["english"],"toss":["english"],"total":["english"],"tourist":["english"],"toward":["english"],"tower":["english"],"town":["english"],"toy":["english"],"track":["english"],"trade":["english"],"traffic":["english"],"tragic":["english"],"train":["english","french"],"transfer":["english","turkish"],"trap":["english"],"trash":["english"],"travel":["english"],"tray":["english"],"treat":["english"],"tree":["english"],"trend":["english"],"trial":["english"],"tribe":["english"],"trick":["english"],"trigger":["english"],"trim":["english"],"trip":["english"],"trophy":["english"],"trouble":["english"],"truck":["english"],"true":["english"],"truly":["english"],"trumpet":["english"],"trust":["english"],"truth":["english"],"try":["english"],"tube":["english"],"tuition":["english"],"tumble":["english"],"tuna":["english"],"tunnel":["english","french"],"turkey":["english"],"turn":["english"],"turtle":["english"],"twelve":["english"],"twenty":["english"],"twice":["english"],"twin":["english"],"twist":["english"],"two":["english"],"type":["english"],"typical":["english"],"ugly":["english"],"umbrella":["english"],"unable":["english"],"unaware":["english"],"uncle":["english"],"uncover":["english"],"under":["english"],"undo":["english"],"unfair":["english"],"unfold":["english"],"unhappy":["english"],"uniform":["english"],"unique":["english","french"],"unit":["english"],"universe":["english"],"unknown":["english"],"unlock":["english"],"until":["english"],"unusual":["english"],"unveil":["english"],"update":["english"],"upgrade":["english"],"uphold":["english"],"upon":["english"],"upper":["english"],"upset":["english"],"urban":["english"],"urge":["english"],"usage":["english","french"],"use":["english"],"used":["english"],"useful":["english"],"useless":["english"],"usual":["english"],"utility":["english"],"vacant":["english"],"vacuum":["english"],"vague":["english","french"],"valid":["english"],"valley":["english"],"valve":["english","french"],"van":["english"],"vanish":["english"],"vapor":["english"],"various":["english"],"vast":["english"],"vault":["english"],"vehicle":["english"],"velvet":["english"],"vendor":["english"],"venture":["english"],"venue":["english"],"verb":["english"],"verify":["english"],"version":["english"],"very":["english"],"vessel":["english"],"veteran":["english"],"viable":["english"],"vibrant":["english"],"vicious":["english"],"victory":["english"],"video":["english"],"view":["english"],"village":["english","french"],"vintage":["english"],"violin":["english"],"virtual":["english"],"virus":["english","french"],"visa":["english"],"visit":["english"],"visual":["english"],"vital":["english","french"],"vivid":["english"],"vocal":["english"],"voice":["english"],"void":["english"],"volcano":["english"],"volume":["english","french"],"vote":["english"],"voyage":["english","french"],"wage":["english"],"wagon":["english","french"],"wait":["english"],"walk":["english"],"wall":["english"],"walnut":["english"],"want":["english"],"warfare":["english"],"warm":["english"],"warrior":["english"],"wash":["english"],"wasp":["english"],"waste":["english"],"water":["english"],"wave":["english"],"way":["english"],"wealth":["english"],"weapon":["english"],"wear":["english"],"weasel":["english"],"weather":["english"],"web":["english"],"wedding":["english"],"weekend":["english"],"weird":["english"],"welcome":["english"],"west":["english"],"wet":["english"],"whale":["english"],"what":["english"],"wheat":["english"],"wheel":["english"],"when":["english"],"where":["english"],"whip":["english"],"whisper":["english"],"wide":["english"],"width":["english"],"wife":["english"],"wild":["english"],"will":["english"],"win":["english"],"window":["english"],"wine":["english"],"wing":["english"],"wink":["english"],"winner":["english"],"winter":["english"],"wire":["english"],"wisdom":["english"],"wise":["english"],"wish":["english"],"witness":["english"],"wolf":["english"],"woman":["english"],"wonder":["english"],"wood":["english"],"wool":["english"],"word":["english"],"work":["english"],"world":["english"],"worry":["english"],"worth":["english"],"wrap":["english"],"wreck":["english"],"wrestle":["english"],"wrist":["english"],"write":["english"],"wrong":["english"],"yard":["english"],"year":["english"],"yellow":["english"],"you":["english"],"young":["english"],"youth":["english"],"zebra":["english"],"zero":["english"],"zone":["english"],"zoo":["english"],"abaisser":["french"],"abdiquer":["french"],"abeille":["french"],"abolir":["french"],"aborder":["french"],"aboutir":["french"],"aboyer":["french"],"abrasif":["french"],"abreuver":["french"],"abriter":["french"],"abroger":["french"],"abrupt":["french"],"absence":["french"],"absolu":["french"],"absurde":["french"],"abusif":["french"],"abyssal":["french"],"académie":["french"],"acajou":["french"],"acarien":["french"],"accabler":["french"],"accepter":["french"],"acclamer":["french"],"accolade":["french"],"accroche":["french"],"accuser":["french"],"acerbe":["french"],"achat":["french"],"acheter":["french"],"aciduler":["french"],"acier":["french"],"acompte":["french"],"acquérir":["french"],"acronyme":["french"],"acteur":["french"],"actif":["french"],"actuel":["french"],"adepte":["french"],"adéquat":["french"],"adhésif":["french"],"adjectif":["french"],"adjuger":["french"],"admettre":["french"],"admirer":["french"],"adopter":["french"],"adorer":["french"],"adoucir":["french"],"adresse":["french"],"adroit":["french"],"adulte":["french"],"adverbe":["french"],"aérer":["french"],"aéronef":["french"],"affaire":["french"],"affecter":["french"],"affiche":["french"],"affreux":["french"],"affubler":["french"],"agacer":["french"],"agencer":["french"],"agile":["french"],"agiter":["french"],"agrafer":["french"],"agréable":["french"],"agrume":["french"],"aider":["french"],"aiguille":["french"],"ailier":["french"],"aimable":["french"],"aisance":["french"],"ajouter":["french"],"ajuster":["french"],"alarmer":["french"],"alchimie":["french"],"alerte":["french"],"algèbre":["french"],"algue":["french"],"aliéner":["french"],"aliment":["french"],"alléger":["french"],"alliage":["french"],"allouer":["french"],"allumer":["french"],"alourdir":["french"],"alpaga":["french"],"altesse":["french"],"alvéole":["french"],"ambigu":["french"],"ambre":["french"],"aménager":["french"],"amertume":["french"],"amidon":["french"],"amiral":["french"],"amorcer":["french"],"amour":["french"],"amovible":["french"],"amphibie":["french"],"ampleur":["french"],"amusant":["french"],"analyse":["french"],"anaphore":["french"],"anarchie":["french"],"anatomie":["french"],"ancien":["french"],"anéantir":["french"],"angoisse":["french"],"anguleux":["french"],"annexer":["french"],"annonce":["french"],"annuel":["french"],"anodin":["french"],"anomalie":["french"],"anonyme":["french"],"anormal":["french"],"antenne":["french"],"antidote":["french"],"anxieux":["french"],"apaiser":["french"],"apéritif":["french"],"aplanir":["french"],"apologie":["french"],"appareil":["french"],"appeler":["french"],"apporter":["french"],"appuyer":["french"],"aquarium":["french"],"aqueduc":["french"],"arbitre":["french"],"arbuste":["french"],"ardeur":["french"],"ardoise":["french"],"argent":["french"],"arlequin":["french"],"armature":["french"],"armement":["french"],"armoire":["french"],"armure":["french"],"arpenter":["french"],"arracher":["french"],"arriver":["french"],"arroser":["french"],"arsenic":["french"],"artériel":["french"],"article":["french"],"asphalte":["french"],"aspirer":["french"],"assaut":["french"],"asservir":["french"],"assiette":["french"],"associer":["french"],"assurer":["french"],"asticot":["french"],"astre":["french"],"astuce":["french"],"atelier":["french"],"atome":["french"],"atrium":["french"],"atroce":["french"],"attaque":["french"],"attentif":["french"],"attirer":["french"],"attraper":["french"],"aubaine":["french"],"auberge":["french"],"audace":["french"],"audible":["french"],"augurer":["french"],"aurore":["french"],"automne":["french"],"autruche":["french"],"avaler":["french"],"avancer":["french"],"avarice":["french"],"avenir":["french"],"averse":["french"],"aveugle":["french"],"aviateur":["french"],"avide":["french"],"avion":["french"],"aviser":["french"],"avoine":["french"],"avouer":["french"],"avril":["french"],"axial":["french"],"axiome":["french"],"bafouer":["french"],"bagage":["french"],"baguette":["french"],"baignade":["french"],"balancer":["french"],"balcon":["french"],"baleine":["french"],"balisage":["french"],"bambin":["french"],"bancaire":["french"],"bandage":["french"],"banlieue":["french"],"bannière":["french"],"banquier":["french"],"barbier":["french"],"baril":["french"],"baron":["french"],"barque":["french"],"barrage":["french"],"bassin":["french"],"bastion":["french"],"bataille":["french"],"bateau":["french"],"batterie":["french"],"baudrier":["french"],"bavarder":["french"],"belette":["french"],"bélier":["french"],"belote":["french"],"bénéfice":["french"],"berceau":["french"],"berger":["french"],"berline":["french"],"bermuda":["french","turkish"],"besace":["french"],"besogne":["french"],"bétail":["french"],"beurre":["french"],"biberon":["french"],"bidule":["french"],"bijou":["french"],"bilan":["french"],"bilingue":["french"],"billard":["french"],"binaire":["french"],"biologie":["french"],"biopsie":["french"],"biotype":["french"],"biscuit":["french"],"bison":["french"],"bistouri":["french"],"bitume":["french"],"bizarre":["french"],"blafard":["french"],"blague":["french"],"blanchir":["french"],"blessant":["french"],"blinder":["french"],"blond":["french"],"bloquer":["french"],"blouson":["french"],"bobard":["french"],"bobine":["french"],"boire":["french"],"boiser":["french"],"bolide":["french"],"bonbon":["french"],"bondir":["french"],"bonheur":["french"],"bonifier":["french"],"bordure":["french"],"borne":["french"],"botte":["french"],"boucle":["french"],"boueux":["french"],"bougie":["french"],"boulon":["french"],"bouquin":["french"],"bourse":["french"],"boussole":["french"],"boutique":["french"],"boxeur":["french"],"branche":["french"],"brasier":["french"],"brebis":["french"],"brèche":["french"],"breuvage":["french"],"bricoler":["french"],"brigade":["french"],"brillant":["french"],"brioche":["french"],"brique":["french"],"brochure":["french"],"broder":["french"],"bronzer":["french"],"brousse":["french"],"broyeur":["french"],"brume":["french"],"brusque":["french"],"brutal":["french"],"bruyant":["french"],"buffle":["french"],"buisson":["french"],"bulletin":["french"],"bureau":["french"],"burin":["french"],"bustier":["french"],"butiner":["french"],"butoir":["french"],"buvable":["french"],"buvette":["french"],"cabanon":["french"],"cabine":["french"],"cachette":["french"],"cadeau":["french"],"cadre":["french"],"caféine":["french"],"caillou":["french"],"caisson":["french"],"calculer":["french"],"calepin":["french"],"calibre":["french"],"calmer":["french"],"calomnie":["french"],"calvaire":["french"],"camarade":["french"],"caméra":["french"],"camion":["french"],"campagne":["french"],"caneton":["french"],"canon":["french"],"cantine":["french"],"canular":["french"],"caporal":["french"],"caprice":["french"],"capsule":["french"],"capter":["french"],"capuche":["french"],"carabine":["french"],"carbone":["french"],"caresser":["french"],"caribou":["french"],"carnage":["french"],"carotte":["french"],"carreau":["french"],"carton":["french"],"cascade":["french"],"casier":["french"],"casque":["french"],"cassure":["french"],"causer":["french"],"cavalier":["french"],"caverne":["french"],"caviar":["french"],"cédille":["french"],"ceinture":["french"],"céleste":["french"],"cellule":["french"],"cendrier":["french"],"censurer":["french"],"central":["french"],"cercle":["french"],"cérébral":["french"],"cerise":["french"],"cerner":["french"],"cerveau":["french"],"cesser":["french"],"chagrin":["french"],"chaise":["french"],"chaleur":["french"],"chambre":["french"],"chance":["french"],"chapitre":["french"],"charbon":["french"],"chasseur":["french"],"chaton":["french"],"chausson":["french"],"chavirer":["french"],"chemise":["french"],"chenille":["french"],"chéquier":["french"],"chercher":["french"],"cheval":["french"],"chien":["french"],"chiffre":["french"],"chignon":["french"],"chimère":["french"],"chiot":["french"],"chlorure":["french"],"chocolat":["french"],"choisir":["french"],"chose":["french"],"chouette":["french"],"chrome":["french"],"chute":["french"],"cigare":["french"],"cigogne":["french"],"cimenter":["french"],"cinéma":["french"],"cintrer":["french"],"circuler":["french"],"cirer":["french"],"cirque":["french"],"citerne":["french"],"citoyen":["french"],"citron":["french"],"clairon":["french"],"clameur":["french"],"claquer":["french"],"classe":["french"],"clavier":["french"],"cligner":["french"],"climat":["french"],"clivage":["french"],"cloche":["french"],"clonage":["french"],"cloporte":["french"],"cobalt":["french"],"cobra":["french"],"cocasse":["french"],"cocotier":["french"],"coder":["french"],"codifier":["french"],"coffre":["french"],"cogner":["french"],"cohésion":["french"],"coiffer":["french"],"coincer":["french"],"colère":["french"],"colibri":["french"],"colline":["french"],"colmater":["french"],"colonel":["french"],"combat":["french"],"comédie":["french"],"commande":["french"],"compact":["french"],"conduire":["french"],"confier":["french"],"congeler":["french"],"connoter":["french"],"consonne":["french"],"contact":["french"],"convexe":["french"],"copain":["french"],"copie":["french"],"corail":["french"],"corbeau":["french"],"cordage":["french"],"corniche":["french"],"corpus":["french"],"cortège":["french"],"cosmique":["french"],"costume":["french"],"coton":["french"],"coude":["french"],"coupure":["french"],"courage":["french"],"couteau":["french"],"couvrir":["french"],"crabe":["french"],"crainte":["french"],"cravate":["french"],"crayon":["french"],"créature":["french"],"créditer":["french"],"crémeux":["french"],"creuser":["french"],"crevette":["french"],"cribler":["french"],"crier":["french"],"cristal":["french"],"critère":["french"],"croire":["french"],"croquer":["french"],"crotale":["french"],"crypter":["french"],"cubique":["french"],"cueillir":["french"],"cuillère":["french"],"cuisine":["french"],"cuivre":["french"],"culminer":["french"],"cultiver":["french"],"cumuler":["french"],"cupide":["french"],"curatif":["french"],"curseur":["french"],"cyanure":["french"],"cylindre":["french"],"cynique":["french"],"daigner":["french"],"damier":["french"],"danseur":["french"],"dauphin":["french"],"débattre":["french"],"débiter":["french"],"déborder":["french"],"débrider":["french"],"débutant":["french"],"décaler":["french"],"décembre":["french"],"déchirer":["french"],"décider":["french"],"déclarer":["french"],"décorer":["french"],"décrire":["french"],"décupler":["french"],"dédale":["french"],"déductif":["french"],"déesse":["french"],"défensif":["french"],"défiler":["french"],"défrayer":["french"],"dégager":["french"],"dégivrer":["french"],"déglutir":["french"],"dégrafer":["french"],"déjeuner":["french"],"délice":["french"],"déloger":["french"],"demander":["french"],"demeurer":["french"],"démolir":["french"],"dénicher":["french"],"dénouer":["french"],"dentelle":["french"],"dénuder":["french"],"départ":["french"],"dépenser":["french"],"déphaser":["french"],"déplacer":["french"],"déposer":["french"],"déranger":["french"],"dérober":["french"],"désastre":["french"],"descente":["french"],"désert":["french"],"désigner":["french"],"désobéir":["french"],"dessiner":["french"],"destrier":["french"],"détacher":["french"],"détester":["french"],"détourer":["french"],"détresse":["french"],"devancer":["french"],"devenir":["french"],"deviner":["french"],"devoir":["french"],"diable":["french"],"dialogue":["french"],"diamant":["french"],"dicter":["french"],"différer":["french"],"digérer":["french"],"digne":["french"],"diluer":["french"],"dimanche":["french"],"diminuer":["french"],"dioxyde":["french"],"directif":["french"],"diriger":["french"],"discuter":["french"],"disposer":["french"],"dissiper":["french"],"divertir":["french"],"diviser":["french"],"docile":["french"],"docteur":["french"],"dogme":["french"],"doigt":["french"],"domaine":["french"],"domicile":["french"],"dompter":["french"],"donateur":["french"],"donjon":["french"],"donner":["french"],"dopamine":["french"],"dortoir":["french"],"dorure":["french"],"dosage":["french"],"doseur":["french"],"dossier":["french"],"dotation":["french"],"douanier":["french"],"douceur":["french"],"douter":["french"],"doyen":["french"],"draper":["french"],"dresser":["french"],"dribbler":["french"],"droiture":["french"],"duperie":["french"],"duplexe":["french"],"durable":["french"],"durcir":["french"],"dynastie":["french"],"éblouir":["french"],"écarter":["french"],"écharpe":["french"],"échelle":["french"],"éclairer":["french"],"éclipse":["french"],"éclore":["french"],"écluse":["french"],"école":["french"],"économie":["french"],"écorce":["french"],"écouter":["french"],"écraser":["french"],"écrémer":["french"],"écrivain":["french"],"écrou":["french"],"écume":["french"],"écureuil":["french"],"édifier":["french"],"éduquer":["french"],"effacer":["french"],"effectif":["french"],"effigie":["french"],"effrayer":["french"],"effusion":["french"],"égaliser":["french"],"égarer":["french"],"éjecter":["french"],"élaborer":["french"],"élargir":["french"],"électron":["french"],"élégant":["french"],"éléphant":["french"],"élève":["french"],"éligible":["french"],"élitisme":["french"],"éloge":["french"],"élucider":["french"],"éluder":["french"],"emballer":["french"],"embellir":["french"],"embryon":["french"],"émeraude":["french"],"émission":["french"],"emmener":["french"],"émotion":["french"],"émouvoir":["french"],"empereur":["french"],"employer":["french"],"emporter":["french"],"emprise":["french"],"émulsion":["french"],"encadrer":["french"],"enchère":["french"],"enclave":["french"],"encoche":["french"],"endiguer":["french"],"endosser":["french"],"endroit":["french"],"enduire":["french"],"énergie":["french"],"enfance":["french"],"enfermer":["french"],"enfouir":["french"],"engager":["french"],"engin":["french","turkish"],"englober":["french"],"énigme":["french"],"enjamber":["french"],"enjeu":["french"],"enlever":["french"],"ennemi":["french"],"ennuyeux":["french"],"enrichir":["french"],"enrobage":["french"],"enseigne":["french"],"entasser":["french"],"entendre":["french"],"entier":["french"],"entourer":["french"],"entraver":["french"],"énumérer":["french"],"envahir":["french"],"enviable":["french"],"envoyer":["french"],"enzyme":["french"],"éolien":["french"],"épaissir":["french"],"épargne":["french"],"épatant":["french"],"épaule":["french"],"épicerie":["french"],"épidémie":["french"],"épier":["french"],"épilogue":["french"],"épine":["french"],"épisode":["french"],"épitaphe":["french"],"époque":["french"],"épreuve":["french"],"éprouver":["french"],"épuisant":["french"],"équerre":["french"],"équipe":["french"],"ériger":["french"],"érosion":["french"],"erreur":["french"],"éruption":["french"],"escalier":["french"],"espadon":["french"],"espèce":["french"],"espiègle":["french"],"espoir":["french"],"esprit":["french"],"esquiver":["french"],"essayer":["french"],"essieu":["french"],"essorer":["french"],"estime":["french"],"estomac":["french"],"estrade":["french"],"étagère":["french"],"étaler":["french"],"étanche":["french"],"étatique":["french"],"éteindre":["french"],"étendoir":["french"],"éternel":["french"],"éthanol":["french"],"éthique":["french"],"ethnie":["french"],"étirer":["french"],"étoffer":["french"],"étoile":["french"],"étonnant":["french"],"étourdir":["french"],"étrange":["french"],"étroit":["french"],"étude":["french"],"euphorie":["french"],"évaluer":["french"],"évasion":["french"],"éventail":["french"],"évidence":["french"],"éviter":["french"],"évolutif":["french"],"évoquer":["french"],"exagérer":["french"],"exaucer":["french"],"exceller":["french"],"excitant":["french"],"exclusif":["french"],"exécuter":["french"],"exemple":["french"],"exercer":["french"],"exhaler":["french"],"exhorter":["french"],"exigence":["french"],"exiler":["french"],"exister":["french"],"exotique":["french"],"expédier":["french"],"explorer":["french"],"exposer":["french"],"exprimer":["french"],"exquis":["french"],"extensif":["french"],"extraire":["french"],"exulter":["french"],"fable":["french"],"fabuleux":["french"],"facette":["french"],"facile":["french"],"facture":["french"],"faiblir":["french"],"falaise":["french"],"fameux":["french"],"famille":["french"],"farceur":["french"],"farfelu":["french"],"farine":["french"],"farouche":["french"],"fasciner":["french"],"faucon":["french"],"fautif":["french"],"faveur":["french"],"favori":["french","turkish"],"fébrile":["french"],"féconder":["french"],"fédérer":["french"],"félin":["french"],"femme":["french"],"fémur":["french"],"fendoir":["french"],"féodal":["french"],"fermer":["french"],"féroce":["french"],"ferveur":["french"],"feuille":["french"],"feutre":["french"],"février":["french"],"fiasco":["french"],"ficeler":["french"],"fictif":["french"],"fidèle":["french"],"filature":["french"],"filetage":["french"],"filière":["french"],"filleul":["french"],"filmer":["french"],"filou":["french"],"filtrer":["french"],"financer":["french"],"finir":["french"],"fiole":["french"],"firme":["french"],"fissure":["french"],"fixer":["french"],"flairer":["french"],"flamme":["french"],"flasque":["french"],"flatteur":["french"],"fléau":["french"],"flèche":["french"],"fleur":["french"],"flexion":["french"],"flocon":["french"],"flore":["french"],"fluctuer":["french"],"fluide":["french"],"fluvial":["french"],"folie":["french"],"fonderie":["french"],"fongible":["french"],"fontaine":["french"],"forcer":["french"],"forgeron":["french"],"formuler":["french"],"fossile":["french"],"foudre":["french"],"fougère":["french"],"fouiller":["french"],"foulure":["french"],"fourmi":["french"],"fraise":["french"],"franchir":["french"],"frapper":["french"],"frayeur":["french"],"frégate":["french"],"freiner":["french"],"frelon":["french"],"frémir":["french"],"frénésie":["french"],"frère":["french"],"friable":["french"],"friction":["french"],"frisson":["french"],"frivole":["french"],"froid":["french"],"fromage":["french"],"frontal":["french"],"frotter":["french"],"fugitif":["french"],"fuite":["french"],"fureur":["french"],"furieux":["french"],"furtif":["french"],"fusion":["french"],"futur":["french"],"gagner":["french"],"galaxie":["french"],"galerie":["french"],"gambader":["french"],"garantir":["french"],"gardien":["french"],"garnir":["french"],"garrigue":["french"],"gazelle":["french"],"gazon":["french"],"géant":["french"],"gélatine":["french"],"gélule":["french"],"gendarme":["french"],"général":["french"],"génie":["french"],"genou":["french"],"gentil":["french"],"géologie":["french"],"géomètre":["french"],"géranium":["french"],"germe":["french"],"gestuel":["french"],"geyser":["french"],"gibier":["french"],"gicler":["french"],"girafe":["french"],"givre":["french"],"glace":["french"],"glaive":["french"],"glisser":["french"],"gloire":["french"],"glorieux":["french"],"golfeur":["french"],"gomme":["french"],"gonfler":["french"],"gorge":["french"],"gorille":["french"],"goudron":["french"],"gouffre":["french"],"goulot":["french"],"goupille":["french"],"gourmand":["french"],"goutte":["french"],"graduel":["french"],"graffiti":["french"],"graine":["french"],"grand":["french"],"grappin":["french"],"gratuit":["french"],"gravir":["french"],"grenat":["french"],"griffure":["french"],"griller":["french"],"grimper":["french"],"grogner":["french"],"gronder":["french"],"grotte":["french"],"groupe":["french"],"gruger":["french"],"grutier":["french"],"gruyère":["french"],"guépard":["french"],"guerrier":["french"],"guimauve":["french"],"guitare":["french"],"gustatif":["french"],"gymnaste":["french"],"gyrostat":["french"],"habitude":["french"],"hachoir":["french"],"halte":["french"],"hameau":["french"],"hangar":["french","turkish"],"hanneton":["french"],"haricot":["french"],"harmonie":["french"],"harpon":["french"],"hasard":["french"],"hélium":["french"],"hématome":["french"],"herbe":["french"],"hérisson":["french"],"hermine":["french"],"héron":["french"],"hésiter":["french"],"heureux":["french"],"hiberner":["french"],"hibou":["french"],"hilarant":["french"],"histoire":["french"],"hiver":["french"],"homard":["french"],"hommage":["french"],"homogène":["french"],"honneur":["french"],"honorer":["french"],"honteux":["french"],"horde":["french"],"horizon":["french"],"horloge":["french"],"hormone":["french"],"horrible":["french"],"houleux":["french"],"housse":["french"],"hublot":["french"],"huileux":["french"],"humain":["french"],"humide":["french"],"humour":["french"],"hurler":["french"],"hydromel":["french"],"hygiène":["french"],"hymne":["french"],"hypnose":["french"],"idylle":["french"],"ignorer":["french"],"iguane":["french"],"illicite":["french"],"illusion":["french"],"imbiber":["french"],"imiter":["french"],"immobile":["french"],"immuable":["french"],"impérial":["french"],"implorer":["french"],"imposer":["french"],"imprimer":["french"],"imputer":["french"],"incarner":["french"],"incendie":["french"],"incident":["french"],"incliner":["french"],"incolore":["french"],"indexer":["french"],"indice":["french"],"inductif":["french"],"inédit":["french"],"ineptie":["french"],"inexact":["french"],"infini":["french"],"infliger":["french"],"informer":["french"],"infusion":["french"],"ingérer":["french"],"inhaler":["french"],"inhiber":["french"],"injecter":["french"],"injure":["french"],"inoculer":["french"],"inonder":["french"],"inscrire":["french"],"insecte":["french"],"insigne":["french"],"insolite":["french"],"inspirer":["french"],"instinct":["french"],"insulter":["french"],"intense":["french"],"intime":["french"],"intrigue":["french"],"intuitif":["french"],"inutile":["french"],"invasion":["french"],"inventer":["french"],"inviter":["french"],"invoquer":["french"],"ironique":["french"],"irradier":["french"],"irréel":["french"],"irriter":["french"],"isoler":["french"],"ivoire":["french"],"ivresse":["french"],"jaillir":["french"],"jambe":["french"],"janvier":["french"],"jardin":["french"],"jauger":["french"],"jaune":["french"],"javelot":["french"],"jetable":["french"],"jeton":["french"],"jeudi":["french"],"jeunesse":["french"],"joindre":["french"],"joncher":["french"],"jongler":["french"],"joueur":["french"],"jouissif":["french"],"journal":["french"],"jovial":["french"],"joyau":["french"],"joyeux":["french"],"jubiler":["french"],"jugement":["french"],"jupon":["french"],"juriste":["french"],"justice":["french"],"juteux":["french"],"juvénile":["french"],"kayak":["french"],"kimono":["french"],"kiosque":["french"],"labial":["french"],"labourer":["french"],"lacérer":["french"],"lactose":["french"],"lagune":["french"],"laine":["french"],"laisser":["french"],"laitier":["french"],"lambeau":["french"],"lamelle":["french"],"lampe":["french"],"lanceur":["french"],"langage":["french"],"lanterne":["french"],"lapin":["french"],"largeur":["french"],"larme":["french"],"laurier":["french"],"lavabo":["french"],"lavoir":["french"],"légal":["french"],"léger":["french"],"légume":["french"],"lessive":["french"],"lettre":["french"],"levier":["french"],"lexique":["french"],"lézard":["french"],"liasse":["french"],"libérer":["french"],"libre":["french"],"licence":["french"],"licorne":["french"],"liège":["french"],"lièvre":["french"],"ligature":["french"],"ligoter":["french"],"ligue":["french"],"limer":["french"],"limite":["french"],"limonade":["french"],"limpide":["french"],"linéaire":["french"],"lingot":["french"],"lionceau":["french"],"liquide":["french"],"lisière":["french"],"lister":["french"],"lithium":["french"],"litige":["french"],"littoral":["french"],"livreur":["french"],"logique":["french"],"lointain":["french"],"loisir":["french"],"lombric":["french"],"loterie":["french"],"louer":["french"],"lourd":["french"],"loutre":["french"],"louve":["french"],"lubie":["french"],"lucide":["french"],"lucratif":["french"],"lueur":["french"],"lugubre":["french"],"luisant":["french"],"lumière":["french"],"lunaire":["french"],"lundi":["french"],"luron":["french"],"lutter":["french"],"luxueux":["french"],"magasin":["french"],"magenta":["french"],"magique":["french"],"maigre":["french"],"maillon":["french"],"maintien":["french"],"mairie":["french"],"maison":["french"],"majorer":["french"],"malaxer":["french"],"maléfice":["french"],"malheur":["french"],"malice":["french"],"mallette":["french"],"mammouth":["french"],"mandater":["french"],"maniable":["french"],"manquant":["french"],"manteau":["french"],"manuel":["french"],"marathon":["french"],"marbre":["french"],"marchand":["french"],"mardi":["french"],"maritime":["french"],"marqueur":["french"],"marron":["french"],"marteler":["french"],"mascotte":["french"],"massif":["french"],"matériel":["french"],"matière":["french"],"matraque":["french"],"maudire":["french"],"maussade":["french"],"mauve":["french"],"maximal":["french"],"méchant":["french"],"méconnu":["french"],"médaille":["french"],"médecin":["french"],"méditer":["french"],"méduse":["french"],"meilleur":["french"],"mélange":["french"],"mélodie":["french"],"membre":["french"],"mémoire":["french"],"menacer":["french"],"mener":["french"],"menhir":["french"],"mensonge":["french"],"mentor":["french"],"mercredi":["french"],"mérite":["french"],"merle":["french"],"messager":["french"],"mesure":["french"],"métal":["french"],"météore":["french"],"méthode":["french"],"métier":["french"],"meuble":["french"],"miauler":["french"],"microbe":["french"],"miette":["french"],"mignon":["french"],"migrer":["french"],"milieu":["french"],"mimique":["french"],"mince":["french"],"minéral":["french"],"minimal":["french"],"minorer":["french"],"miroiter":["french"],"missile":["french"],"mixte":["french"],"moderne":["french"],"moelleux":["french"],"mondial":["french"],"moniteur":["french"],"monnaie":["french"],"monotone":["french"],"monstre":["french"],"montagne":["french"],"monument":["french"],"moqueur":["french"],"morceau":["french"],"morsure":["french"],"mortier":["french"],"moteur":["french"],"motif":["french"],"mouche":["french"],"moufle":["french"],"moulin":["french"],"mousson":["french"],"mouton":["french"],"mouvant":["french"],"multiple":["french"],"munition":["french"],"muraille":["french"],"murène":["french"],"murmure":["french"],"muséum":["french"],"musicien":["french"],"mutation":["french"],"muter":["french"],"mutuel":["french"],"myriade":["french"],"myrtille":["french"],"mystère":["french"],"mythique":["french"],"nageur":["french"],"nappe":["french"],"narquois":["french"],"narrer":["french"],"natation":["french"],"naufrage":["french"],"nautique":["french"],"navire":["french"],"nébuleux":["french"],"nectar":["french"],"néfaste":["french"],"négation":["french"],"négliger":["french"],"négocier":["french"],"neige":["french"],"nerveux":["french"],"nettoyer":["french"],"neurone":["french"],"neutron":["french"],"neveu":["french"],"niche":["french"],"nickel":["french"],"nitrate":["french"],"niveau":["french"],"nocif":["french"],"nocturne":["french"],"noirceur":["french"],"noisette":["french"],"nomade":["french"],"nombreux":["french"],"nommer":["french"],"normatif":["french"],"notifier":["french"],"notoire":["french"],"nourrir":["french"],"nouveau":["french"],"novateur":["french"],"novembre":["french"],"novice":["french"],"nuage":["french"],"nuancer":["french"],"nuire":["french"],"nuisible":["french"],"numéro":["french"],"nuptial":["french"],"nuque":["french"],"nutritif":["french"],"obéir":["french"],"objectif":["french"],"obliger":["french"],"obscur":["french"],"observer":["french"],"obstacle":["french"],"obtenir":["french"],"obturer":["french"],"occasion":["french"],"occuper":["french"],"océan":["french"],"octobre":["french"],"octroyer":["french"],"octupler":["french"],"oculaire":["french"],"odeur":["french"],"odorant":["french"],"offenser":["french"],"officier":["french"],"offrir":["french"],"ogive":["french"],"oiseau":["french"],"oisillon":["french"],"olfactif":["french"],"olivier":["french"],"ombrage":["french"],"omettre":["french"],"onctueux":["french"],"onduler":["french"],"onéreux":["french"],"onirique":["french"],"opale":["french"],"opaque":["french"],"opérer":["french"],"opportun":["french"],"opprimer":["french"],"opter":["french"],"optique":["french"],"orageux":["french"],"orbite":["french"],"ordonner":["french"],"oreille":["french"],"organe":["french"],"orgueil":["french"],"orifice":["french"],"ornement":["french"],"orque":["french"],"ortie":["french"],"osciller":["french"],"osmose":["french"],"ossature":["french"],"otarie":["french"],"ouragan":["french"],"ourson":["french"],"outil":["french"],"outrager":["french"],"ouvrage":["french"],"ovation":["french"],"oxyde":["french"],"oxygène":["french"],"paisible":["french"],"palmarès":["french"],"palourde":["french"],"palper":["french"],"panache":["french"],"pangolin":["french"],"paniquer":["french"],"panneau":["french"],"panorama":["french"],"pantalon":["french"],"papaye":["french"],"papier":["french"],"papoter":["french"],"papyrus":["french"],"paradoxe":["french"],"parcelle":["french"],"paresse":["french"],"parfumer":["french"],"parler":["french"],"parole":["french"],"parrain":["french"],"parsemer":["french"],"partager":["french"],"parure":["french"],"parvenir":["french"],"passion":["french"],"pastèque":["french"],"paternel":["french"],"patience":["french"],"patron":["french","turkish"],"pavillon":["french"],"pavoiser":["french"],"payer":["french"],"paysage":["french"],"peigne":["french"],"peintre":["french"],"pelage":["french"],"pélican":["french"],"pelle":["french"],"pelouse":["french"],"peluche":["french"],"pendule":["french"],"pénétrer":["french"],"pénible":["french"],"pensif":["french"],"pénurie":["french"],"pépite":["french"],"péplum":["french"],"perdrix":["french"],"perforer":["french"],"période":["french"],"permuter":["french"],"perplexe":["french"],"persil":["french"],"perte":["french"],"peser":["french"],"pétale":["french"],"petit":["french"],"pétrir":["french"],"peuple":["french"],"pharaon":["french"],"phobie":["french"],"phoque":["french"],"photon":["french"],"physique":["french"],"pictural":["french"],"pièce":["french"],"pierre":["french"],"pieuvre":["french"],"pilote":["french"],"pinceau":["french"],"pipette":["french"],"piquer":["french"],"pirogue":["french"],"piscine":["french"],"piston":["french"],"pivoter":["french"],"pixel":["french"],"placard":["french"],"plafond":["french"],"plaisir":["french"],"planer":["french"],"plaque":["french"],"plastron":["french"],"plateau":["french"],"pleurer":["french"],"plexus":["french"],"pliage":["french"],"plomb":["french"],"plonger":["french"],"pluie":["french"],"plumage":["french"],"pochette":["french"],"poésie":["french"],"poète":["french"],"pointe":["french"],"poirier":["french"],"poisson":["french"],"poivre":["french"],"polaire":["french"],"policier":["french"],"pollen":["french"],"polygone":["french"],"pommade":["french"],"pompier":["french"],"ponctuel":["french"],"pondérer":["french"],"poney":["french"],"portique":["french"],"posséder":["french"],"posture":["french"],"potager":["french"],"poteau":["french"],"potion":["french"],"pouce":["french"],"poulain":["french"],"poumon":["french"],"pourpre":["french"],"poussin":["french"],"pouvoir":["french"],"prairie":["french"],"pratique":["french"],"précieux":["french"],"prédire":["french"],"préfixe":["french"],"prélude":["french"],"prénom":["french"],"présence":["french"],"prétexte":["french"],"prévoir":["french"],"primitif":["french"],"prince":["french"],"priver":["french"],"problème":["french"],"procéder":["french"],"prodige":["french"],"profond":["french"],"progrès":["french"],"proie":["french"],"projeter":["french"],"prologue":["french"],"promener":["french"],"propre":["french"],"prospère":["french"],"protéger":["french"],"prouesse":["french"],"proverbe":["french"],"prudence":["french"],"pruneau":["french"],"psychose":["french"],"puceron":["french"],"puiser":["french"],"pulpe":["french"],"pulsar":["french"],"punaise":["french"],"punitif":["french"],"pupitre":["french"],"purifier":["french"],"pyramide":["french"],"quasar":["french"],"querelle":["french"],"quiétude":["french"],"quitter":["french"],"quotient":["french"],"racine":["french"],"raconter":["french"],"radieux":["french"],"ragondin":["french"],"raideur":["french"],"raisin":["french"],"ralentir":["french"],"rallonge":["french"],"ramasser":["french"],"rapide":["french"],"rasage":["french"],"ratisser":["french"],"ravager":["french"],"ravin":["french"],"rayonner":["french"],"réactif":["french"],"réagir":["french"],"réaliser":["french"],"réanimer":["french"],"recevoir":["french"],"réciter":["french"],"réclamer":["french"],"récolter":["french"],"recruter":["french"],"reculer":["french"],"recycler":["french"],"rédiger":["french"],"redouter":["french"],"refaire":["french"],"réflexe":["french"],"réformer":["french"],"refrain":["french"],"refuge":["french"],"régalien":["french"],"région":["french"],"réglage":["french"],"régulier":["french"],"réitérer":["french"],"rejeter":["french"],"rejouer":["french"],"relatif":["french"],"relever":["french"],"remarque":["french"],"remède":["french"],"remise":["french"],"remonter":["french"],"remplir":["french"],"remuer":["french"],"renard":["french"],"renfort":["french"],"renifler":["french"],"renoncer":["french"],"rentrer":["french"],"renvoi":["french"],"replier":["french"],"reporter":["french"],"reprise":["french"],"reptile":["french"],"requin":["french"],"réserve":["french"],"résineux":["french"],"résoudre":["french"],"respect":["french"],"rester":["french"],"résultat":["french"],"rétablir":["french"],"retenir":["french"],"réticule":["french"],"retomber":["french"],"retracer":["french"],"réunion":["french"],"réussir":["french"],"revanche":["french"],"revivre":["french"],"révolte":["french"],"révulsif":["french"],"richesse":["french"],"rideau":["french"],"rieur":["french"],"rigide":["french"],"rigoler":["french"],"rincer":["french"],"riposter":["french"],"risible":["french"],"risque":["french"],"rituel":["french"],"rivière":["french"],"rocheux":["french"],"rompre":["french"],"ronce":["french"],"rondin":["french"],"roseau":["french"],"rosier":["french"],"rotatif":["french"],"rotor":["french"],"rotule":["french"],"rouge":["french"],"rouille":["french"],"rouleau":["french"],"routine":["french"],"royaume":["french"],"ruban":["french"],"rubis":["french"],"ruche":["french"],"ruelle":["french"],"rugueux":["french"],"ruiner":["french"],"ruisseau":["french"],"ruser":["french"],"rustique":["french"],"rythme":["french"],"sabler":["french"],"saboter":["french"],"sabre":["french"],"sacoche":["french"],"safari":["french"],"sagesse":["french"],"saisir":["french"],"salade":["french"],"salive":["french"],"saluer":["french"],"samedi":["french"],"sanction":["french"],"sanglier":["french"],"sarcasme":["french"],"sardine":["french"],"saturer":["french"],"saugrenu":["french"],"saumon":["french"],"sauter":["french"],"sauvage":["french"],"savant":["french"],"savonner":["french"],"scalpel":["french"],"scandale":["french"],"scélérat":["french"],"scénario":["french"],"sceptre":["french"],"schéma":["french"],"scinder":["french"],"score":["french"],"scrutin":["french"],"sculpter":["french"],"séance":["french"],"sécable":["french"],"sécher":["french"],"secouer":["french"],"sécréter":["french"],"sédatif":["french"],"séduire":["french"],"seigneur":["french"],"séjour":["french"],"sélectif":["french"],"semaine":["french"],"sembler":["french"],"semence":["french"],"séminal":["french"],"sénateur":["french"],"sensible":["french"],"séparer":["french"],"séquence":["french"],"serein":["french"],"sergent":["french"],"sérieux":["french"],"serrure":["french"],"sérum":["french"],"sésame":["french"],"sévir":["french"],"sevrage":["french"],"sextuple":["french"],"sidéral":["french"],"siècle":["french"],"siéger":["french"],"siffler":["french"],"sigle":["french"],"signal":["french"],"silence":["french"],"silicium":["french"],"sincère":["french"],"sinistre":["french"],"siphon":["french"],"sirop":["french"],"sismique":["french"],"situer":["french"],"skier":["french"],"socle":["french"],"sodium":["french"],"soigneux":["french"],"soldat":["french"],"soleil":["french"],"solitude":["french"],"soluble":["french"],"sombre":["french"],"sommeil":["french"],"somnoler":["french"],"sonde":["french"],"songeur":["french"],"sonnette":["french"],"sonore":["french"],"sorcier":["french"],"sortir":["french"],"sosie":["french"],"sottise":["french"],"soucieux":["french"],"soudure":["french"],"souffle":["french"],"soulever":["french"],"soupape":["french"],"soutirer":["french"],"souvenir":["french"],"spacieux":["french"],"spécial":["french"],"sphère":["french"],"spiral":["french","turkish"],"station":["french"],"sternum":["french"],"stimulus":["french"],"stipuler":["french"],"strict":["french"],"studieux":["french"],"stupeur":["french"],"styliste":["french"],"sublime":["french"],"substrat":["french"],"subtil":["french"],"subvenir":["french"],"succès":["french"],"sucre":["french"],"suffixe":["french"],"suggérer":["french"],"suiveur":["french"],"sulfate":["french"],"superbe":["french"],"supplier":["french"],"suricate":["french"],"surmener":["french"],"sursaut":["french"],"survie":["french"],"syllabe":["french"],"symbole":["french"],"symétrie":["french"],"synapse":["french"],"syntaxe":["french"],"système":["french"],"tabac":["french"],"tablier":["french"],"tactile":["french"],"tailler":["french"],"talisman":["french"],"talonner":["french"],"tambour":["french"],"tamiser":["french"],"tangible":["french"],"tapis":["french"],"taquiner":["french"],"tarder":["french"],"tarif":["french"],"tartine":["french"],"tasse":["french"],"tatami":["french"],"tatouage":["french"],"taupe":["french"],"taureau":["french"],"taxer":["french"],"témoin":["french"],"temporel":["french"],"tenaille":["french"],"tendre":["french"],"teneur":["french"],"tenir":["french"],"tension":["french"],"terminer":["french"],"terne":["french"],"terrible":["french"],"tétine":["french"],"texte":["french"],"thème":["french"],"théorie":["french"],"thérapie":["french"],"thorax":["french"],"tibia":["french"],"tiède":["french"],"timide":["french"],"tirelire":["french"],"tiroir":["french"],"tissu":["french"],"titane":["french"],"titre":["french"],"tituber":["french"],"toboggan":["french"],"tolérant":["french"],"tomate":["french"],"tonique":["french"],"tonneau":["french"],"toponyme":["french"],"torche":["french"],"tordre":["french"],"tornade":["french"],"torpille":["french"],"torrent":["french"],"torse":["french"],"tortue":["french"],"totem":["french"],"toucher":["french"],"tournage":["french"],"tousser":["french"],"toxine":["french"],"traction":["french"],"trafic":["french"],"tragique":["french"],"trahir":["french"],"trancher":["french"],"travail":["french"],"trèfle":["french"],"tremper":["french"],"trésor":["french"],"treuil":["french"],"triage":["french"],"tribunal":["french"],"tricoter":["french"],"trilogie":["french"],"triomphe":["french"],"tripler":["french"],"triturer":["french"],"trivial":["french"],"trombone":["french"],"tronc":["french"],"tropical":["french"],"troupeau":["french"],"tuile":["french"],"tulipe":["french"],"tumulte":["french"],"turbine":["french"],"tuteur":["french"],"tutoyer":["french"],"tuyau":["french"],"tympan":["french"],"typhon":["french"],"typique":["french"],"tyran":["french"],"ubuesque":["french"],"ultime":["french"],"ultrason":["french"],"unanime":["french"],"unifier":["french"],"union":["french"],"unitaire":["french"],"univers":["french"],"uranium":["french"],"urbain":["french"],"urticant":["french"],"usine":["french"],"usuel":["french"],"usure":["french"],"utile":["french"],"utopie":["french"],"vacarme":["french"],"vaccin":["french"],"vagabond":["french"],"vaillant":["french"],"vaincre":["french"],"vaisseau":["french"],"valable":["french"],"valise":["french"],"vallon":["french"],"vampire":["french"],"vanille":["french"],"vapeur":["french"],"varier":["french"],"vaseux":["french"],"vassal":["french"],"vaste":["french"],"vecteur":["french"],"vedette":["french"],"végétal":["french"],"véhicule":["french"],"veinard":["french"],"véloce":["french"],"vendredi":["french"],"vénérer":["french"],"venger":["french"],"venimeux":["french"],"ventouse":["french"],"verdure":["french"],"vérin":["french"],"vernir":["french"],"verrou":["french"],"verser":["french"],"vertu":["french"],"veston":["french"],"vétéran":["french"],"vétuste":["french"],"vexant":["french"],"vexer":["french"],"viaduc":["french"],"viande":["french"],"victoire":["french"],"vidange":["french"],"vidéo":["french"],"vignette":["french"],"vigueur":["french"],"vilain":["french"],"vinaigre":["french"],"violon":["french"],"vipère":["french"],"virement":["french"],"virtuose":["french"],"visage":["french"],"viseur":["french"],"vision":["french"],"visqueux":["french"],"visuel":["french"],"vitesse":["french"],"viticole":["french"],"vitrine":["french"],"vivace":["french"],"vivipare":["french"],"vocation":["french"],"voguer":["french"],"voile":["french"],"voisin":["french"],"voiture":["french"],"volaille":["french"],"volcan":["french"],"voltiger":["french"],"vorace":["french"],"vortex":["french"],"voter":["french"],"vouloir":["french"],"voyelle":["french"],"xénon":["french"],"yacht":["french"],"zèbre":["french"],"zénith":["french"],"zeste":["french"],"zoologie":["french"],"abaco":["italian"],"abbaglio":["italian"],"abbinato":["italian"],"abete":["italian"],"abisso":["italian"],"abolire":["italian"],"abrasivo":["italian"],"abrogato":["italian"],"accadere":["italian"],"accenno":["italian"],"accusato":["italian"],"acetone":["italian"],"achille":["italian"],"acido":["italian"],"acqua":["italian"],"acre":["italian"],"acrilico":["italian"],"acrobata":["italian"],"acuto":["italian"],"adagio":["italian"],"addebito":["italian"],"addome":["italian"],"adeguato":["italian"],"aderire":["italian"],"adipe":["italian"],"adottare":["italian"],"adulare":["italian"],"affabile":["italian"],"affetto":["italian"],"affisso":["italian"],"affranto":["italian"],"aforisma":["italian"],"afoso":["italian"],"africano":["italian"],"agave":["italian"],"agente":["italian"],"agevole":["italian"],"aggancio":["italian"],"agire":["italian"],"agitare":["italian"],"agonismo":["italian"],"agricolo":["italian"],"agrumeto":["italian"],"aguzzo":["italian"],"alabarda":["italian"],"alato":["italian"],"albatro":["italian"],"alberato":["italian"],"albo":["italian"],"albume":["italian"],"alce":["italian"],"alcolico":["italian"],"alettone":["italian"],"alfa":["italian"],"algebra":["italian"],"aliante":["italian"],"alibi":["italian"],"alimento":["italian"],"allagato":["italian"],"allegro":["italian"],"allievo":["italian"],"allodola":["italian"],"allusivo":["italian"],"almeno":["italian"],"alogeno":["italian"],"alpaca":["italian"],"alpestre":["italian"],"altalena":["italian"],"alterno":["italian"],"alticcio":["italian"],"altrove":["italian"],"alunno":["italian"],"alveolo":["italian"],"alzare":["italian"],"amalgama":["italian"],"amanita":["italian"],"amarena":["italian"],"ambito":["italian"],"ambrato":["italian"],"ameba":["italian"],"america":["italian"],"ametista":["italian"],"amico":["italian"],"ammasso":["italian"],"ammenda":["italian"],"ammirare":["italian"],"ammonito":["italian"],"amore":["italian"],"ampio":["italian"],"ampliare":["italian"],"amuleto":["italian"],"anacardo":["italian"],"anagrafe":["italian"],"analista":["italian"],"anarchia":["italian"],"anatra":["italian"],"anca":["italian"],"ancella":["italian"],"ancora":["italian"],"andare":["italian"],"andrea":["italian"],"anello":["italian"],"angelo":["italian"],"angolare":["italian"],"angusto":["italian"],"anima":["italian"],"annegare":["italian"],"annidato":["italian"],"anno":["italian"],"annuncio":["italian"],"anonimo":["italian"],"anticipo":["italian"],"anzi":["italian"],"apatico":["italian"],"apertura":["italian"],"apode":["italian"],"apparire":["italian"],"appetito":["italian"],"appoggio":["italian"],"approdo":["italian"],"appunto":["italian"],"aprile":["italian"],"arabica":["italian"],"arachide":["italian"],"aragosta":["italian"],"araldica":["italian"],"arancio":["italian"],"aratura":["italian"],"arazzo":["italian"],"arbitro":["italian"],"archivio":["italian"],"ardito":["italian"],"arenile":["italian"],"argento":["italian"],"argine":["italian"],"arguto":["italian"],"aria":["italian"],"armonia":["italian"],"arnese":["italian"],"arredato":["italian"],"arringa":["italian"],"arrosto":["italian"],"arsenico":["italian"],"arso":["italian"],"artefice":["italian"],"arzillo":["italian"],"asciutto":["italian"],"ascolto":["italian"],"asepsi":["italian"],"asettico":["italian"],"asfalto":["italian"],"asino":["italian"],"asola":["italian"],"aspirato":["italian"],"aspro":["italian"],"assaggio":["italian"],"asse":["italian"],"assoluto":["italian"],"assurdo":["italian"],"asta":["italian"],"astenuto":["italian"],"astice":["italian"],"astratto":["italian"],"atavico":["italian"],"ateismo":["italian"],"atomico":["italian"],"atono":["italian"],"attesa":["italian"],"attivare":["italian"],"attorno":["italian"],"attrito":["italian"],"attuale":["italian"],"ausilio":["italian"],"austria":["italian"],"autista":["italian"],"autonomo":["italian"],"autunno":["italian"],"avanzato":["italian"],"avere":["italian"],"avvenire":["italian"],"avviso":["italian"],"avvolgere":["italian"],"azione":["italian"],"azoto":["italian"],"azzimo":["italian"],"azzurro":["italian"],"babele":["italian"],"baccano":["italian"],"bacino":["italian"],"baco":["italian"],"badessa":["italian"],"badilata":["italian"],"bagnato":["italian"],"baita":["italian"],"balcone":["italian"],"baldo":["italian"],"balena":["italian"],"ballata":["italian"],"balzano":["italian"],"bambino":["italian"],"bandire":["italian"],"baraonda":["italian"],"barbaro":["italian"],"barca":["italian"],"baritono":["italian"],"barlume":["italian"],"barocco":["italian"],"basilico":["italian"],"basso":["italian"],"batosta":["italian"],"battuto":["italian"],"baule":["italian"],"bava":["italian"],"bavosa":["italian"],"becco":["italian"],"beffa":["italian"],"belgio":["italian"],"belva":["italian"],"benda":["italian"],"benevole":["italian"],"benigno":["italian"],"benzina":["italian"],"bere":["italian"],"berlina":["italian"],"beta":["italian"],"bibita":["italian"],"bici":["italian"],"bidone":["italian"],"bifido":["italian"],"biga":["italian"],"bilancia":["italian"],"bimbo":["italian"],"binocolo":["italian"],"biologo":["italian"],"bipede":["italian"],"bipolare":["italian"],"birbante":["italian"],"birra":["italian"],"biscotto":["italian"],"bisesto":["italian"],"bisnonno":["italian"],"bisonte":["italian"],"bisturi":["italian"],"bizzarro":["italian"],"blando":["italian"],"blatta":["italian"],"bollito":["italian"],"bonifico":["italian"],"bordo":["italian"],"bosco":["italian"],"botanico":["italian"],"bottino":["italian"],"bozzolo":["italian"],"braccio":["italian"],"bradipo":["italian"],"brama":["italian"],"branca":["italian"],"bravura":["italian"],"bretella":["italian"],"brevetto":["italian"],"brezza":["italian"],"briglia":["italian"],"brillante":["italian"],"brindare":["italian"],"broccolo":["italian"],"brodo":["italian"],"bronzina":["italian"],"brullo":["italian"],"bruno":["italian"],"bubbone":["italian"],"buca":["italian"],"budino":["italian"],"buffone":["italian"],"buio":["italian"],"bulbo":["italian"],"buono":["italian"],"burlone":["italian"],"burrasca":["italian"],"bussola":["italian"],"busta":["italian"],"cadetto":["italian"],"caduco":["italian"],"calamaro":["italian"],"calcolo":["italian"],"calesse":["italian"],"calibro":["italian"],"calmo":["italian"],"caloria":["italian"],"cambusa":["italian"],"camerata":["italian"],"camicia":["italian"],"cammino":["italian"],"camola":["italian"],"campale":["italian"],"canapa":["italian"],"candela":["italian"],"cane":["italian"],"canino":["italian"],"canotto":["italian"],"cantina":["italian"],"capace":["italian"],"capello":["italian"],"capitolo":["italian"],"capogiro":["italian"],"cappero":["italian"],"capra":["italian"],"capsula":["italian"],"carapace":["italian"],"carcassa":["italian"],"cardo":["italian"],"carisma":["italian"],"carovana":["italian"],"carretto":["italian"],"cartolina":["italian"],"casaccio":["italian"],"cascata":["italian"],"caserma":["italian"],"caso":["italian"],"cassone":["italian"],"castello":["italian"],"casuale":["italian"],"catasta":["italian"],"catena":["italian"],"catrame":["italian"],"cauto":["italian"],"cavillo":["italian"],"cedibile":["italian"],"cedrata":["italian"],"cefalo":["italian"],"celebre":["italian"],"cellulare":["italian"],"cena":["italian"],"cenone":["italian"],"centesimo":["italian"],"ceramica":["italian"],"cercare":["italian"],"certo":["italian"],"cerume":["italian"],"cervello":["italian"],"cesoia":["italian"],"cespo":["italian"],"ceto":["italian"],"chela":["italian"],"chiaro":["italian"],"chicca":["italian"],"chiedere":["italian"],"chimera":["italian"],"china":["italian"],"chirurgo":["italian"],"chitarra":["italian"],"ciao":["italian"],"ciclismo":["italian"],"cifrare":["italian"],"cigno":["italian"],"cilindro":["italian"],"ciottolo":["italian"],"circa":["italian"],"cirrosi":["italian"],"citrico":["italian"],"cittadino":["italian"],"ciuffo":["italian"],"civetta":["italian"],"civile":["italian"],"classico":["italian"],"clinica":["italian"],"cloro":["italian"],"cocco":["italian"],"codardo":["italian"],"codice":["italian"],"coerente":["italian"],"cognome":["italian"],"collare":["italian"],"colmato":["italian"],"colore":["italian"],"colposo":["italian"],"coltivato":["italian"],"colza":["italian"],"coma":["italian"],"cometa":["italian"],"commando":["italian"],"comodo":["italian"],"computer":["italian"],"comune":["italian"],"conciso":["italian"],"condurre":["italian"],"conferma":["italian"],"congelare":["italian"],"coniuge":["italian"],"connesso":["italian"],"conoscere":["italian"],"consumo":["italian"],"continuo":["italian"],"convegno":["italian"],"coperto":["italian"],"copione":["italian"],"coppia":["italian"],"copricapo":["italian"],"corazza":["italian"],"cordata":["italian"],"coricato":["italian"],"cornice":["italian"],"corolla":["italian"],"corpo":["italian"],"corredo":["italian"],"corsia":["italian"],"cortese":["italian"],"cosmico":["italian"],"costante":["italian"],"cottura":["italian"],"covato":["italian"],"cratere":["italian"],"cravatta":["italian"],"creato":["italian"],"credere":["italian"],"cremoso":["italian"],"crescita":["italian"],"creta":["italian"],"criceto":["italian"],"crinale":["italian"],"crisi":["italian"],"critico":["italian"],"croce":["italian"],"cronaca":["italian"],"crostata":["italian"],"cruciale":["italian"],"crusca":["italian"],"cucire":["italian"],"cuculo":["italian"],"cugino":["italian"],"cullato":["italian"],"cupola":["italian"],"curatore":["italian"],"cursore":["italian"],"curvo":["italian"],"cuscino":["italian"],"custode":["italian"],"dado":["italian"],"daino":["italian"],"dalmata":["italian"],"damerino":["italian"],"daniela":["italian"],"dannoso":["italian"],"danzare":["italian"],"datato":["italian"],"davanti":["italian"],"davvero":["italian"],"debutto":["italian"],"decennio":["italian"],"deciso":["italian"],"declino":["italian"],"decollo":["italian"],"decreto":["italian"],"dedicato":["italian"],"definito":["italian"],"deforme":["italian"],"degno":["italian"],"delegare":["italian"],"delfino":["italian"],"delirio":["italian"],"delta":["italian"],"demenza":["italian"],"denotato":["italian"],"dentro":["italian"],"deposito":["italian"],"derapata":["italian"],"derivare":["italian"],"deroga":["italian"],"descritto":["italian"],"deserto":["italian"],"desiderio":["italian"],"desumere":["italian"],"detersivo":["italian"],"devoto":["italian"],"diametro":["italian"],"dicembre":["italian"],"diedro":["italian"],"difeso":["italian"],"diffuso":["italian"],"digerire":["italian"],"digitale":["italian"],"diluvio":["italian"],"dinamico":["italian"],"dinnanzi":["italian"],"dipinto":["italian"],"diploma":["italian"],"dipolo":["italian"],"diradare":["italian"],"dire":["italian"],"dirotto":["italian"],"dirupo":["italian"],"disagio":["italian"],"discreto":["italian"],"disfare":["italian"],"disgelo":["italian"],"disposto":["italian"],"distanza":["italian"],"disumano":["italian"],"dito":["italian"],"divano":["italian"],"divelto":["italian"],"dividere":["italian"],"divorato":["italian"],"doblone":["italian"],"docente":["italian"],"doganale":["italian"],"dogma":["italian"],"dolce":["italian"],"domato":["italian"],"domenica":["italian"],"dominare":["italian"],"dondolo":["italian"],"dono":["italian"],"dormire":["italian"],"dote":["italian"],"dottore":["italian"],"dovuto":["italian"],"dozzina":["italian"],"drago":["italian"],"druido":["italian"],"dubbio":["italian"],"dubitare":["italian"],"ducale":["italian"],"duna":["italian"],"duomo":["italian"],"duplice":["italian"],"duraturo":["italian"],"ebano":["italian"],"eccesso":["italian"],"ecco":["italian"],"eclissi":["italian"],"economia":["italian"],"edera":["italian"],"edicola":["italian"],"edile":["italian"],"editoria":["italian"],"educare":["italian"],"egemonia":["italian"],"egli":["italian"],"egoismo":["italian"],"egregio":["italian"],"elaborato":["italian"],"elargire":["italian"],"elegante":["italian"],"elencato":["italian"],"eletto":["italian"],"elevare":["italian"],"elfico":["italian"],"elica":["italian"],"elmo":["italian"],"elsa":["italian"],"eluso":["italian"],"emanato":["italian"],"emblema":["italian"],"emesso":["italian"],"emiro":["italian"],"emotivo":["italian"],"emozione":["italian"],"empirico":["italian"],"emulo":["italian"],"endemico":["italian"],"enduro":["italian"],"energia":["italian"],"enfasi":["italian"],"enoteca":["italian"],"entrare":["italian"],"enzima":["italian"],"epatite":["italian"],"epilogo":["italian"],"episodio":["italian"],"epocale":["italian"],"eppure":["italian"],"equatore":["italian"],"erario":["italian"],"erba":["italian"],"erboso":["italian"],"erede":["italian"],"eremita":["italian"],"erigere":["italian"],"ermetico":["italian"],"eroe":["italian"],"erosivo":["italian"],"errante":["italian"],"esagono":["italian"],"esame":["italian"],"esanime":["italian"],"esaudire":["italian"],"esca":["italian"],"esempio":["italian"],"esercito":["italian"],"esibito":["italian"],"esigente":["italian"],"esistere":["italian"],"esito":["italian"],"esofago":["italian"],"esortato":["italian"],"esoso":["italian"],"espanso":["italian"],"espresso":["italian"],"essenza":["italian"],"esso":["italian"],"esteso":["italian"],"estimare":["italian"],"estonia":["italian"],"estroso":["italian"],"esultare":["italian"],"etilico":["italian"],"etnico":["italian"],"etrusco":["italian"],"etto":["italian"],"euclideo":["italian"],"europa":["italian"],"evaso":["italian"],"evidenza":["italian"],"evitato":["italian"],"evoluto":["italian"],"evviva":["italian"],"fabbrica":["italian"],"faccenda":["italian"],"fachiro":["italian"],"falco":["italian"],"famiglia":["italian"],"fanale":["italian"],"fanfara":["italian"],"fango":["italian"],"fantasma":["italian"],"fare":["italian"],"farfalla":["italian"],"farinoso":["italian"],"farmaco":["italian"],"fascia":["italian"],"fastoso":["italian"],"fasullo":["italian"],"faticare":["italian"],"fato":["italian"],"favoloso":["italian"],"febbre":["italian"],"fecola":["italian"],"fede":["italian"],"fegato":["italian"],"felpa":["italian"],"feltro":["italian"],"femmina":["italian"],"fendere":["italian"],"fenomeno":["italian"],"fermento":["italian"],"ferro":["italian"],"fertile":["italian"],"fessura":["italian"],"festivo":["italian"],"fetta":["italian"],"feudo":["italian"],"fiaba":["italian"],"fiducia":["italian"],"fifa":["italian"],"figurato":["italian"],"filo":["italian","turkish"],"finanza":["italian"],"finestra":["italian"],"finire":["italian"],"fiore":["italian"],"fiscale":["italian"],"fisico":["italian"],"fiume":["italian"],"flacone":["italian"],"flamenco":["italian"],"flebo":["italian"],"flemma":["italian"],"florido":["italian"],"fluente":["italian"],"fluoro":["italian"],"fobico":["italian"],"focaccia":["italian"],"focoso":["italian"],"foderato":["italian"],"foglio":["italian"],"folata":["italian"],"folclore":["italian"],"folgore":["italian"],"fondente":["italian"],"fonetico":["italian"],"fonia":["italian"],"fontana":["italian"],"forbito":["italian"],"forchetta":["italian"],"foresta":["italian"],"formica":["italian"],"fornaio":["italian"],"foro":["italian"],"fortezza":["italian"],"forzare":["italian"],"fosfato":["italian"],"fosso":["italian"],"fracasso":["italian"],"frana":["italian"],"frassino":["italian"],"fratello":["italian"],"freccetta":["italian"],"frenata":["italian"],"fresco":["italian"],"frigo":["italian"],"frollino":["italian"],"fronde":["italian"],"frugale":["italian"],"frutta":["italian"],"fucilata":["italian"],"fucsia":["italian"],"fuggente":["italian"],"fulmine":["italian"],"fulvo":["italian"],"fumante":["italian"],"fumetto":["italian"],"fumoso":["italian"],"fune":["italian"],"funzione":["italian"],"fuoco":["italian"],"furbo":["italian"],"furgone":["italian"],"furore":["italian"],"fuso":["italian"],"futile":["italian"],"gabbiano":["italian"],"gaffe":["italian"],"galateo":["italian"],"gallina":["italian"],"galoppo":["italian"],"gambero":["italian"],"gamma":["italian"],"garanzia":["italian"],"garbo":["italian"],"garofano":["italian"],"garzone":["italian"],"gasdotto":["italian"],"gasolio":["italian"],"gastrico":["italian"],"gatto":["italian"],"gaudio":["italian"],"gazebo":["italian"],"gazzella":["italian"],"geco":["italian"],"gelatina":["italian"],"gelso":["italian"],"gemello":["italian"],"gemmato":["italian"],"gene":["italian"],"genitore":["italian"],"gennaio":["italian"],"genotipo":["italian"],"gergo":["italian"],"ghepardo":["italian"],"ghiaccio":["italian"],"ghisa":["italian"],"giallo":["italian"],"gilda":["italian"],"ginepro":["italian"],"giocare":["italian"],"gioiello":["italian"],"giorno":["italian"],"giove":["italian"],"girato":["italian"],"girone":["italian"],"gittata":["italian"],"giudizio":["italian"],"giurato":["italian"],"giusto":["italian"],"globulo":["italian"],"glutine":["italian"],"gnomo":["italian"],"gobba":["italian"],"golf":["italian"],"gomito":["italian"],"gommone":["italian"],"gonfio":["italian"],"gonna":["italian"],"governo":["italian"],"gracile":["italian"],"grado":["italian"],"grafico":["italian"],"grammo":["italian"],"grande":["italian"],"grattare":["italian"],"gravoso":["italian"],"grazia":["italian"],"greca":["italian"],"gregge":["italian"],"grifone":["italian"],"grigio":["italian"],"grinza":["italian"],"grotta":["italian"],"gruppo":["italian"],"guadagno":["italian"],"guaio":["italian"],"guanto":["italian"],"guardare":["italian"],"gufo":["italian"],"guidare":["italian"],"ibernato":["italian"],"icona":["italian"],"identico":["italian"],"idillio":["italian"],"idolo":["italian"],"idra":["italian"],"idrico":["italian"],"idrogeno":["italian"],"igiene":["italian"],"ignaro":["italian"],"ignorato":["italian"],"ilare":["italian"],"illeso":["italian"],"illogico":["italian"],"illudere":["italian"],"imballo":["italian"],"imbevuto":["italian"],"imbocco":["italian"],"imbuto":["italian"],"immane":["italian"],"immerso":["italian"],"immolato":["italian"],"impacco":["italian"],"impeto":["italian"],"impiego":["italian"],"importo":["italian"],"impronta":["italian"],"inalare":["italian"],"inarcare":["italian"],"inattivo":["italian"],"incanto":["italian"],"incendio":["italian"],"inchino":["italian"],"incisivo":["italian"],"incluso":["italian"],"incontro":["italian"],"incrocio":["italian"],"incubo":["italian"],"indagine":["italian"],"india":["italian"],"indole":["italian"],"inedito":["italian"],"infatti":["italian"],"infilare":["italian"],"inflitto":["italian"],"ingaggio":["italian"],"ingegno":["italian"],"inglese":["italian"],"ingordo":["italian"],"ingrosso":["italian"],"innesco":["italian"],"inodore":["italian"],"inoltrare":["italian"],"inondato":["italian"],"insano":["italian"],"insetto":["italian"],"insieme":["italian"],"insonnia":["italian"],"insulina":["italian"],"intasato":["italian"],"intero":["italian"],"intonaco":["italian"],"intuito":["italian"],"inumidire":["italian"],"invalido":["italian"],"invece":["italian"],"invito":["italian"],"iperbole":["italian"],"ipnotico":["italian"],"ipotesi":["italian"],"ippica":["italian"],"iride":["italian"],"irlanda":["italian"],"ironico":["italian"],"irrigato":["italian"],"irrorare":["italian"],"isolato":["italian"],"isotopo":["italian"],"isterico":["italian"],"istituto":["italian"],"istrice":["italian"],"italia":["italian"],"iterare":["italian"],"labbro":["italian"],"labirinto":["italian"],"lacca":["italian"],"lacerato":["italian"],"lacrima":["italian"],"lacuna":["italian"],"laddove":["italian"],"lago":["italian"],"lampo":["italian"],"lancetta":["italian"],"lanterna":["italian"],"lardoso":["italian"],"larga":["italian"],"laringe":["italian"],"lastra":["italian"],"latenza":["italian"],"latino":["italian"],"lattuga":["italian"],"lavagna":["italian"],"lavoro":["italian"],"legale":["italian"],"leggero":["italian"],"lembo":["italian"],"lentezza":["italian"],"lenza":["italian"],"leone":["italian"],"lepre":["italian"],"lesivo":["italian"],"lessato":["italian"],"lesto":["italian"],"letterale":["italian"],"leva":["italian"],"levigato":["italian"],"libero":["italian"],"lido":["italian"],"lievito":["italian"],"lilla":["italian"],"limatura":["italian"],"limitare":["italian"],"limpido":["italian"],"lineare":["italian"],"lingua":["italian"],"liquido":["italian"],"lira":["italian"],"lirica":["italian"],"lisca":["italian"],"lite":["italian"],"litigio":["italian"],"livrea":["italian"],"locanda":["italian"],"lode":["italian"],"logica":["italian"],"lombare":["italian"],"londra":["italian"],"longevo":["italian"],"loquace":["italian"],"lorenzo":["italian"],"loto":["italian"],"lotteria":["italian"],"luce":["italian"],"lucidato":["italian"],"lumaca":["italian"],"luminoso":["italian"],"lungo":["italian"],"lupo":["italian"],"luppolo":["italian"],"lusinga":["italian"],"lusso":["italian"],"lutto":["italian"],"macabro":["italian"],"macchina":["italian"],"macero":["italian"],"macinato":["italian"],"madama":["italian"],"magico":["italian"],"maglia":["italian"],"magnete":["italian"],"magro":["italian"],"maiolica":["italian"],"malafede":["italian"],"malgrado":["italian"],"malinteso":["italian"],"malsano":["italian"],"malto":["italian"],"malumore":["italian"],"mana":["italian"],"mancia":["italian"],"mandorla":["italian"],"mangiare":["italian"],"manifesto":["italian"],"mannaro":["italian"],"manovra":["italian"],"mansarda":["italian"],"mantide":["italian"],"manubrio":["italian"],"mappa":["italian"],"maratona":["italian"],"marcire":["italian"],"maretta":["italian"],"marmo":["italian"],"marsupio":["italian"],"maschera":["italian"],"massaia":["italian"],"mastino":["italian"],"materasso":["italian"],"matricola":["italian"],"mattone":["italian"],"maturo":["italian"],"mazurca":["italian"],"meandro":["italian"],"meccanico":["italian"],"mecenate":["italian"],"medesimo":["italian"],"meditare":["italian"],"mega":["italian"],"melassa":["italian"],"melis":["italian"],"melodia":["italian"],"meninge":["italian"],"meno":["italian"],"mensola":["italian"],"mercurio":["italian"],"merenda":["italian"],"merlo":["italian"],"meschino":["italian"],"mese":["italian"],"messere":["italian"],"mestolo":["italian"],"metallo":["italian"],"metodo":["italian"],"mettere":["italian"],"miagolare":["italian"],"mica":["italian"],"micelio":["italian"],"michele":["italian"],"microbo":["italian"],"midollo":["italian"],"miele":["italian"],"migliore":["italian"],"milano":["italian"],"milite":["italian"],"mimosa":["italian"],"minerale":["italian"],"mini":["italian"],"minore":["italian"],"mirino":["italian"],"mirtillo":["italian"],"miscela":["italian"],"missiva":["italian"],"misto":["italian"],"misurare":["italian"],"mitezza":["italian"],"mitigare":["italian"],"mitra":["italian"],"mittente":["italian"],"mnemonico":["italian"],"modello":["italian"],"modifica":["italian"],"modulo":["italian"],"mogano":["italian"],"mogio":["italian"],"mole":["italian"],"molosso":["italian"],"monastero":["italian"],"monco":["italian"],"mondina":["italian"],"monetario":["italian"],"monile":["italian"],"monotono":["italian"],"monsone":["italian"],"montato":["italian"],"monviso":["italian"],"mora":["italian"],"mordere":["italian"],"morsicato":["italian"],"mostro":["italian"],"motivato":["italian"],"motosega":["italian"],"motto":["italian"],"movenza":["italian"],"movimento":["italian"],"mozzo":["italian"],"mucca":["italian"],"mucosa":["italian"],"muffa":["italian"],"mughetto":["italian"],"mugnaio":["italian"],"mulatto":["italian"],"mulinello":["italian"],"multiplo":["italian"],"mummia":["italian"],"munto":["italian"],"muovere":["italian"],"murale":["italian"],"musa":["italian"],"muscolo":["italian"],"musica":["italian"],"mutevole":["italian"],"muto":["italian"],"nababbo":["italian"],"nafta":["italian"],"nanometro":["italian"],"narciso":["italian"],"narice":["italian"],"narrato":["italian"],"nascere":["italian"],"nastrare":["italian"],"naturale":["italian"],"nautica":["italian"],"naviglio":["italian"],"nebulosa":["italian"],"necrosi":["italian"],"negativo":["italian"],"negozio":["italian"],"nemmeno":["italian"],"neofita":["italian"],"neretto":["italian"],"nervo":["italian"],"nessuno":["italian"],"nettuno":["italian"],"neutrale":["italian"],"neve":["italian"],"nevrotico":["italian"],"nicchia":["italian"],"ninfa":["italian"],"nitido":["italian"],"nobile":["italian"],"nocivo":["italian"],"nodo":["italian"],"nome":["italian"],"nomina":["italian"],"nordico":["italian"],"normale":["italian"],"norvegese":["italian"],"nostrano":["italian"],"notare":["italian"],"notizia":["italian"],"notturno":["italian"],"novella":["italian"],"nucleo":["italian"],"nulla":["italian"],"numero":["italian"],"nuovo":["italian"],"nutrire":["italian"],"nuvola":["italian"],"nuziale":["italian"],"oasi":["italian"],"obbedire":["italian"],"obbligo":["italian"],"obelisco":["italian"],"oblio":["italian"],"obolo":["italian"],"obsoleto":["italian"],"occasione":["italian"],"occhio":["italian"],"occidente":["italian"],"occorrere":["italian"],"occultare":["italian"],"ocra":["italian"],"oculato":["italian"],"odierno":["italian"],"odorare":["italian"],"offerta":["italian"],"offrire":["italian"],"offuscato":["italian"],"oggetto":["italian"],"oggi":["italian"],"ognuno":["italian"],"olandese":["italian"],"olfatto":["italian"],"oliato":["italian"],"oliva":["italian"],"ologramma":["italian"],"oltre":["italian"],"omaggio":["italian"],"ombelico":["italian"],"ombra":["italian"],"omega":["italian"],"omissione":["italian"],"ondoso":["italian"],"onere":["italian"],"onice":["italian"],"onnivoro":["italian"],"onorevole":["italian"],"onta":["italian"],"operato":["italian"],"opinione":["italian"],"opposto":["italian"],"oracolo":["italian"],"orafo":["italian"],"ordine":["italian"],"orecchino":["italian"],"orefice":["italian"],"orfano":["italian"],"organico":["italian"],"origine":["italian"],"orizzonte":["italian"],"orma":["italian"],"ormeggio":["italian"],"ornativo":["italian"],"orologio":["italian"],"orrendo":["italian"],"orribile":["italian"],"ortensia":["italian"],"ortica":["italian"],"orzata":["italian"],"orzo":["italian"],"osare":["italian"],"oscurare":["italian"],"osmosi":["italian"],"ospedale":["italian"],"ospite":["italian"],"ossa":["italian"],"ossidare":["italian"],"ostacolo":["italian"],"oste":["italian"],"otite":["italian"],"otre":["italian"],"ottagono":["italian"],"ottimo":["italian"],"ottobre":["italian"],"ovale":["italian"],"ovest":["italian"],"ovino":["italian"],"oviparo":["italian"],"ovocito":["italian"],"ovunque":["italian"],"ovviare":["italian"],"ozio":["italian"],"pacchetto":["italian"],"pace":["italian"],"pacifico":["italian"],"padella":["italian"],"padrone":["italian"],"paese":["italian"],"paga":["italian"],"pagina":["italian"],"palazzina":["italian"],"palesare":["italian"],"pallido":["italian"],"palo":["italian"],"palude":["italian"],"pandoro":["italian"],"pannello":["italian"],"paolo":["italian"],"paonazzo":["italian"],"paprica":["italian"],"parabola":["italian"],"parcella":["italian"],"parere":["italian"],"pargolo":["italian"],"pari":["italian"],"parlato":["italian"],"parola":["italian"],"partire":["italian"],"parvenza":["italian"],"parziale":["italian"],"passivo":["italian"],"pasticca":["italian"],"patacca":["italian"],"patologia":["italian"],"pattume":["italian"],"pavone":["italian"],"peccato":["italian"],"pedalare":["italian"],"pedonale":["italian"],"peggio":["italian"],"peloso":["italian"],"penare":["italian"],"pendice":["italian"],"penisola":["italian"],"pennuto":["italian"],"penombra":["italian"],"pensare":["italian"],"pentola":["italian"],"pepe":["italian"],"pepita":["italian"],"perbene":["italian"],"percorso":["italian"],"perdonato":["italian"],"perforare":["italian"],"pergamena":["italian"],"periodo":["italian"],"permesso":["italian"],"perno":["italian"],"perplesso":["italian"],"persuaso":["italian"],"pertugio":["italian"],"pervaso":["italian"],"pesatore":["italian"],"pesista":["italian"],"peso":["italian"],"pestifero":["italian"],"petalo":["italian"],"pettine":["italian"],"petulante":["italian"],"pezzo":["italian"],"piacere":["italian"],"pianta":["italian"],"piattino":["italian"],"piccino":["italian"],"picozza":["italian"],"piega":["italian"],"pietra":["italian"],"piffero":["italian"],"pigiama":["italian"],"pigolio":["italian"],"pigro":["italian"],"pila":["italian"],"pilifero":["italian"],"pillola":["italian"],"pilota":["italian"],"pimpante":["italian"],"pineta":["italian"],"pinna":["italian"],"pinolo":["italian"],"pioggia":["italian"],"piombo":["italian"],"piramide":["italian"],"piretico":["italian"],"pirite":["italian"],"pirolisi":["italian"],"pitone":["italian"],"pizzico":["italian"],"placebo":["italian"],"planare":["italian"],"plasma":["italian"],"platano":["italian"],"plenario":["italian"],"pochezza":["italian"],"poderoso":["italian"],"podismo":["italian"],"poesia":["italian"],"poggiare":["italian"],"polenta":["italian"],"poligono":["italian"],"pollice":["italian"],"polmonite":["italian"],"polpetta":["italian"],"polso":["italian"],"poltrona":["italian"],"polvere":["italian"],"pomice":["italian"],"pomodoro":["italian"],"ponte":["italian"],"popoloso":["italian"],"porfido":["italian"],"poroso":["italian"],"porpora":["italian"],"porre":["italian"],"portata":["italian"],"posa":["italian","turkish"],"positivo":["italian"],"possesso":["italian"],"postulato":["italian"],"potassio":["italian"],"potere":["italian"],"pranzo":["italian"],"prassi":["italian"],"pratica":["italian"],"precluso":["italian"],"predica":["italian"],"prefisso":["italian"],"pregiato":["italian"],"prelievo":["italian"],"premere":["italian"],"prenotare":["italian"],"preparato":["italian"],"presenza":["italian"],"pretesto":["italian"],"prevalso":["italian"],"prima":["italian"],"principe":["italian"],"privato":["italian"],"problema":["italian"],"procura":["italian"],"produrre":["italian"],"profumo":["italian"],"progetto":["italian"],"prolunga":["italian"],"promessa":["italian"],"pronome":["italian"],"proposta":["italian"],"proroga":["italian"],"proteso":["italian"],"prova":["italian","turkish"],"prudente":["italian"],"prugna":["italian"],"prurito":["italian"],"psiche":["italian"],"pubblico":["italian"],"pudica":["italian"],"pugilato":["italian"],"pugno":["italian"],"pulce":["italian"],"pulito":["italian"],"pulsante":["italian"],"puntare":["italian"],"pupazzo":["italian"],"pupilla":["italian"],"puro":["italian"],"quadro":["italian"],"qualcosa":["italian"],"quasi":["italian"],"querela":["italian"],"quota":["italian"],"raccolto":["italian"],"raddoppio":["italian"],"radicale":["italian"],"radunato":["italian"],"raffica":["italian"],"ragazzo":["italian"],"ragione":["italian"],"ragno":["italian"],"ramarro":["italian"],"ramingo":["italian"],"ramo":["italian"],"randagio":["italian"],"rantolare":["italian"],"rapato":["italian"],"rapina":["italian"],"rappreso":["italian"],"rasatura":["italian"],"raschiato":["italian"],"rasente":["italian"],"rassegna":["italian"],"rastrello":["italian"],"rata":["italian"],"ravveduto":["italian"],"reale":["italian"],"recepire":["italian"],"recinto":["italian"],"recluta":["italian"],"recondito":["italian"],"recupero":["italian"],"reddito":["italian"],"redimere":["italian"],"regalato":["italian"],"registro":["italian"],"regola":["italian"],"regresso":["italian"],"relazione":["italian"],"remare":["italian"],"remoto":["italian"],"renna":["italian"],"replica":["italian"],"reprimere":["italian"],"reputare":["italian"],"resa":["italian"],"residente":["italian"],"responso":["italian"],"restauro":["italian"],"rete":["italian"],"retina":["italian"],"retorica":["italian"],"rettifica":["italian"],"revocato":["italian"],"riassunto":["italian"],"ribadire":["italian"],"ribelle":["italian"],"ribrezzo":["italian"],"ricarica":["italian"],"ricco":["italian"],"ricevere":["italian"],"riciclato":["italian"],"ricordo":["italian"],"ricreduto":["italian"],"ridicolo":["italian"],"ridurre":["italian"],"rifasare":["italian"],"riflesso":["italian"],"riforma":["italian"],"rifugio":["italian"],"rigare":["italian"],"rigettato":["italian"],"righello":["italian"],"rilassato":["italian"],"rilevato":["italian"],"rimanere":["italian"],"rimbalzo":["italian"],"rimedio":["italian"],"rimorchio":["italian"],"rinascita":["italian"],"rincaro":["italian"],"rinforzo":["italian"],"rinnovo":["italian"],"rinomato":["italian"],"rinsavito":["italian"],"rintocco":["italian"],"rinuncia":["italian"],"rinvenire":["italian"],"riparato":["italian"],"ripetuto":["italian"],"ripieno":["italian"],"riportare":["italian"],"ripresa":["italian"],"ripulire":["italian"],"risata":["italian"],"rischio":["italian"],"riserva":["italian"],"risibile":["italian"],"riso":["italian"],"rispetto":["italian"],"ristoro":["italian"],"risultato":["italian"],"risvolto":["italian"],"ritardo":["italian"],"ritegno":["italian"],"ritmico":["italian"],"ritrovo":["italian"],"riunione":["italian"],"riva":["italian"],"riverso":["italian"],"rivincita":["italian"],"rivolto":["italian"],"rizoma":["italian"],"roba":["italian"],"robotico":["italian"],"robusto":["italian"],"roccia":["italian"],"roco":["italian"],"rodaggio":["italian"],"rodere":["italian"],"roditore":["italian"],"rogito":["italian"],"rollio":["italian"],"romantico":["italian"],"rompere":["italian"],"ronzio":["italian"],"rosolare":["italian"],"rospo":["italian"],"rotante":["italian"],"rotondo":["italian"],"rotula":["italian"],"rovescio":["italian"],"rubizzo":["italian"],"rubrica":["italian"],"ruga":["italian"],"rullino":["italian"],"rumine":["italian"],"rumoroso":["italian"],"ruolo":["italian"],"rupe":["italian"],"russare":["italian"],"rustico":["italian"],"sabato":["italian"],"sabbiare":["italian"],"sabotato":["italian"],"sagoma":["italian"],"salasso":["italian"],"saldatura":["italian"],"salgemma":["italian"],"salivare":["italian"],"salmone":["italian"],"salone":["italian"],"saltare":["italian"],"saluto":["italian"],"salvo":["italian"],"sapere":["italian"],"sapido":["italian"],"saporito":["italian"],"saraceno":["italian"],"sarcasmo":["italian"],"sarto":["italian"],"sassoso":["italian"],"satellite":["italian"],"satira":["italian"],"satollo":["italian"],"saturno":["italian"],"savana":["italian"],"savio":["italian"],"saziato":["italian"],"sbadiglio":["italian"],"sbalzo":["italian"],"sbancato":["italian"],"sbarra":["italian"],"sbattere":["italian"],"sbavare":["italian"],"sbendare":["italian"],"sbirciare":["italian"],"sbloccato":["italian"],"sbocciato":["italian"],"sbrinare":["italian"],"sbruffone":["italian"],"sbuffare":["italian"],"scabroso":["italian"],"scadenza":["italian"],"scala":["italian"],"scambiare":["italian"],"scandalo":["italian"],"scapola":["italian"],"scarso":["italian"],"scatenare":["italian"],"scavato":["italian"],"scelto":["italian"],"scenico":["italian"],"scettro":["italian"],"scheda":["italian"],"schiena":["italian"],"sciarpa":["italian"],"scienza":["italian"],"scindere":["italian"],"scippo":["italian"],"sciroppo":["italian"],"scivolo":["italian"],"sclerare":["italian"],"scodella":["italian"],"scolpito":["italian"],"scomparto":["italian"],"sconforto":["italian"],"scoprire":["italian"],"scorta":["italian"],"scossone":["italian"],"scozzese":["italian"],"scriba":["italian"],"scrollare":["italian"],"scrutinio":["italian"],"scuderia":["italian"],"scultore":["italian"],"scuola":["italian"],"scuro":["italian"],"scusare":["italian"],"sdebitare":["italian"],"sdoganare":["italian"],"seccatura":["italian"],"secondo":["italian"],"sedano":["italian"],"seggiola":["italian"],"segnalato":["italian"],"segregato":["italian"],"seguito":["italian"],"selciato":["italian"],"selettivo":["italian"],"sella":["italian"],"selvaggio":["italian"],"semaforo":["italian"],"sembrare":["italian"],"seme":["italian"],"seminato":["italian"],"sempre":["italian"],"senso":["italian"],"sentire":["italian"],"sepolto":["italian"],"sequenza":["italian"],"serata":["italian"],"serbato":["italian"],"sereno":["italian"],"serio":["italian"],"serpente":["italian"],"serraglio":["italian"],"servire":["italian"],"sestina":["italian"],"setola":["italian"],"settimana":["italian"],"sfacelo":["italian"],"sfaldare":["italian"],"sfamato":["italian"],"sfarzoso":["italian"],"sfaticato":["italian"],"sfera":["italian"],"sfida":["italian"],"sfilato":["italian"],"sfinge":["italian"],"sfocato":["italian"],"sfoderare":["italian"],"sfogo":["italian"],"sfoltire":["italian"],"sforzato":["italian"],"sfratto":["italian"],"sfruttato":["italian"],"sfuggito":["italian"],"sfumare":["italian"],"sfuso":["italian"],"sgabello":["italian"],"sgarbato":["italian"],"sgonfiare":["italian"],"sgorbio":["italian"],"sgrassato":["italian"],"sguardo":["italian"],"sibilo":["italian"],"siccome":["italian"],"sierra":["italian"],"sigla":["italian"],"signore":["italian"],"silenzio":["italian"],"sillaba":["italian"],"simbolo":["italian"],"simpatico":["italian"],"simulato":["italian"],"sinfonia":["italian"],"singolo":["italian"],"sinistro":["italian"],"sino":["italian"],"sintesi":["italian"],"sinusoide":["italian"],"sipario":["italian"],"sisma":["italian"],"sistole":["italian"],"situato":["italian"],"slitta":["italian"],"slogatura":["italian"],"sloveno":["italian"],"smarrito":["italian"],"smemorato":["italian"],"smentito":["italian"],"smeraldo":["italian"],"smilzo":["italian"],"smontare":["italian"],"smottato":["italian"],"smussato":["italian"],"snellire":["italian"],"snervato":["italian"],"snodo":["italian"],"sobbalzo":["italian"],"sobrio":["italian"],"soccorso":["italian"],"sociale":["italian"],"sodale":["italian"],"soffitto":["italian"],"sogno":["italian"],"soldato":["italian"],"solenne":["italian"],"solido":["italian"],"sollazzo":["italian"],"solo":["italian"],"solubile":["italian"],"solvente":["italian"],"somatico":["italian"],"somma":["italian"],"sonda":["italian"],"sonetto":["italian"],"sonnifero":["italian"],"sopire":["italian"],"soppeso":["italian"],"sopra":["italian"],"sorgere":["italian"],"sorpasso":["italian"],"sorriso":["italian"],"sorso":["italian"],"sorteggio":["italian"],"sorvolato":["italian"],"sospiro":["italian"],"sosta":["italian"],"sottile":["italian"],"spada":["italian"],"spalla":["italian"],"spargere":["italian"],"spatola":["italian"],"spavento":["italian"],"spazzola":["italian"],"specie":["italian"],"spedire":["italian"],"spegnere":["italian"],"spelatura":["italian"],"speranza":["italian"],"spessore":["italian"],"spettrale":["italian"],"spezzato":["italian"],"spia":["italian"],"spigoloso":["italian"],"spillato":["italian"],"spinoso":["italian"],"spirale":["italian"],"splendido":["italian"],"sportivo":["italian"],"sposo":["italian"],"spranga":["italian"],"sprecare":["italian"],"spronato":["italian"],"spruzzo":["italian"],"spuntino":["italian"],"squillo":["italian"],"sradicare":["italian"],"srotolato":["italian"],"stabile":["italian"],"stacco":["italian"],"staffa":["italian"],"stagnare":["italian"],"stampato":["italian"],"stantio":["italian"],"starnuto":["italian"],"stasera":["italian"],"statuto":["italian"],"stelo":["italian"],"steppa":["italian"],"sterzo":["italian"],"stiletto":["italian"],"stima":["italian"],"stirpe":["italian"],"stivale":["italian"],"stizzoso":["italian"],"stonato":["italian"],"storico":["italian"],"strappo":["italian"],"stregato":["italian"],"stridulo":["italian"],"strozzare":["italian"],"strutto":["italian"],"stuccare":["italian"],"stufo":["italian"],"stupendo":["italian"],"subentro":["italian"],"succoso":["italian"],"sudore":["italian"],"suggerito":["italian"],"sugo":["italian"],"sultano":["italian"],"suonare":["italian"],"superbo":["italian"],"supporto":["italian"],"surgelato":["italian"],"surrogato":["italian"],"sussurro":["italian"],"sutura":["italian"],"svagare":["italian"],"svedese":["italian"],"sveglio":["italian"],"svelare":["italian"],"svenuto":["italian"],"svezia":["italian"],"sviluppo":["italian"],"svista":["italian"],"svizzera":["italian"],"svolta":["italian"],"svuotare":["italian"],"tabacco":["italian"],"tabulato":["italian"],"tacciare":["italian"],"taciturno":["italian"],"tale":["italian"],"talismano":["italian"],"tampone":["italian"],"tannino":["italian"],"tara":["italian"],"tardivo":["italian"],"targato":["italian"],"tariffa":["italian"],"tarpare":["italian"],"tartaruga":["italian"],"tasto":["italian"],"tattico":["italian"],"taverna":["italian"],"tavolata":["italian"],"tazza":["italian"],"teca":["italian"],"tecnico":["italian"],"telefono":["italian"],"temerario":["italian"],"tempo":["italian","turkish"],"temuto":["italian"],"tendone":["italian"],"tenero":["italian"],"tensione":["italian"],"tentacolo":["italian"],"teorema":["italian"],"terme":["italian"],"terrazzo":["italian"],"terzetto":["italian"],"tesi":["italian"],"tesserato":["italian"],"testato":["italian"],"tetro":["italian"],"tettoia":["italian"],"tifare":["italian"],"tigella":["italian"],"timbro":["italian"],"tinto":["italian"],"tipico":["italian"],"tipografo":["italian"],"tiraggio":["italian"],"tiro":["italian"],"titanio":["italian"],"titolo":["italian"],"titubante":["italian"],"tizio":["italian"],"tizzone":["italian"],"toccare":["italian"],"tollerare":["italian"],"tolto":["italian"],"tombola":["italian"],"tomo":["italian"],"tonfo":["italian"],"tonsilla":["italian"],"topazio":["italian"],"topologia":["italian"],"toppa":["italian"],"torba":["italian"],"tornare":["italian"],"torrone":["italian"],"tortora":["italian"],"toscano":["italian"],"tossire":["italian"],"tostatura":["italian"],"totano":["italian"],"trabocco":["italian"],"trachea":["italian"],"trafila":["italian"],"tragedia":["italian"],"tralcio":["italian"],"tramonto":["italian"],"transito":["italian"],"trapano":["italian"],"trarre":["italian"],"trasloco":["italian"],"trattato":["italian"],"trave":["italian"],"treccia":["italian"],"tremolio":["italian"],"trespolo":["italian"],"tributo":["italian"],"tricheco":["italian"],"trifoglio":["italian"],"trillo":["italian"],"trincea":["italian"],"trio":["italian"],"tristezza":["italian"],"triturato":["italian"],"trivella":["italian"],"tromba":["italian"],"trono":["italian"],"troppo":["italian"],"trottola":["italian"],"trovare":["italian"],"truccato":["italian"],"tubatura":["italian"],"tuffato":["italian"],"tulipano":["italian"],"tumulto":["italian"],"tunisia":["italian"],"turbare":["italian"],"turchino":["italian"],"tuta":["italian"],"tutela":["italian"],"ubicato":["italian"],"uccello":["italian"],"uccisore":["italian"],"udire":["italian"],"uditivo":["italian"],"uffa":["italian"],"ufficio":["italian"],"uguale":["italian"],"ulisse":["italian"],"ultimato":["italian"],"umano":["italian"],"umile":["italian"],"umorismo":["italian"],"uncinetto":["italian"],"ungere":["italian"],"ungherese":["italian"],"unicorno":["italian"],"unificato":["italian"],"unisono":["italian"],"unitario":["italian"],"unte":["italian"],"uovo":["italian"],"upupa":["italian"],"uragano":["italian"],"urgenza":["italian"],"urlo":["italian"],"usanza":["italian"],"usato":["italian"],"uscito":["italian"],"usignolo":["italian"],"usuraio":["italian"],"utensile":["italian"],"utilizzo":["italian"],"utopia":["italian"],"vacante":["italian"],"vaccinato":["italian"],"vagabondo":["italian"],"vagliato":["italian"],"valanga":["italian"],"valgo":["italian"],"valico":["italian"],"valletta":["italian"],"valoroso":["italian"],"valutare":["italian"],"valvola":["italian"],"vampata":["italian"],"vangare":["italian"],"vanitoso":["italian"],"vano":["italian"],"vantaggio":["italian"],"vanvera":["italian"],"vapore":["italian"],"varano":["italian"],"varcato":["italian"],"variante":["italian"],"vasca":["italian"],"vedetta":["italian"],"vedova":["italian"],"veduto":["italian"],"vegetale":["italian"],"veicolo":["italian"],"velcro":["italian"],"velina":["italian"],"velluto":["italian"],"veloce":["italian"],"venato":["italian"],"vendemmia":["italian"],"vento":["italian"],"verace":["italian"],"verbale":["italian"],"vergogna":["italian"],"verifica":["italian"],"vero":["italian"],"verruca":["italian"],"verticale":["italian"],"vescica":["italian"],"vessillo":["italian"],"vestale":["italian"],"veterano":["italian"],"vetrina":["italian"],"vetusto":["italian"],"viandante":["italian"],"vibrante":["italian"],"vicenda":["italian"],"vichingo":["italian"],"vicinanza":["italian"],"vidimare":["italian"],"vigilia":["italian"],"vigneto":["italian"],"vigore":["italian"],"vile":["italian"],"villano":["italian"],"vimini":["italian"],"vincitore":["italian"],"viola":["italian"],"vipera":["italian"],"virgola":["italian"],"virologo":["italian"],"virulento":["italian"],"viscoso":["italian"],"visione":["italian"],"vispo":["italian"],"vissuto":["italian"],"visura":["italian"],"vita":["italian"],"vitello":["italian"],"vittima":["italian"],"vivanda":["italian"],"vivido":["italian"],"viziare":["italian"],"voce":["italian"],"voga":["italian"],"volatile":["italian"],"volere":["italian"],"volpe":["italian"],"voragine":["italian"],"vulcano":["italian"],"zampogna":["italian"],"zanna":["italian"],"zappato":["italian"],"zattera":["italian"],"zavorra":["italian"],"zefiro":["italian"],"zelante":["italian"],"zelo":["italian"],"zenzero":["italian"],"zerbino":["italian"],"zibetto":["italian"],"zinco":["italian"],"zircone":["italian"],"zitto":["italian"],"zolla":["italian"],"zotico":["italian"],"zucchero":["italian"],"zufolo":["italian"],"zulu":["italian"],"zuppa":["italian"],"あいこくしん":["japanese"],"あいさつ":["japanese"],"あいだ":["japanese"],"あおぞら":["japanese"],"あかちゃん":["japanese"],"あきる":["japanese"],"あけがた":["japanese"],"あける":["japanese"],"あこがれる":["japanese"],"あさい":["japanese"],"あさひ":["japanese"],"あしあと":["japanese"],"あじわう":["japanese"],"あずかる":["japanese"],"あずき":["japanese"],"あそぶ":["japanese"],"あたえる":["japanese"],"あたためる":["japanese"],"あたりまえ":["japanese"],"あたる":["japanese"],"あつい":["japanese"],"あつかう":["japanese"],"あっしゅく":["japanese"],"あつまり":["japanese"],"あつめる":["japanese"],"あてな":["japanese"],"あてはまる":["japanese"],"あひる":["japanese"],"あぶら":["japanese"],"あぶる":["japanese"],"あふれる":["japanese"],"あまい":["japanese"],"あまど":["japanese"],"あまやかす":["japanese"],"あまり":["japanese"],"あみもの":["japanese"],"あめりか":["japanese"],"あやまる":["japanese"],"あゆむ":["japanese"],"あらいぐま":["japanese"],"あらし":["japanese"],"あらすじ":["japanese"],"あらためる":["japanese"],"あらゆる":["japanese"],"あらわす":["japanese"],"ありがとう":["japanese"],"あわせる":["japanese"],"あわてる":["japanese"],"あんい":["japanese"],"あんがい":["japanese"],"あんこ":["japanese"],"あんぜん":["japanese"],"あんてい":["japanese"],"あんない":["japanese"],"あんまり":["japanese"],"いいだす":["japanese"],"いおん":["japanese"],"いがい":["japanese"],"いがく":["japanese"],"いきおい":["japanese"],"いきなり":["japanese"],"いきもの":["japanese"],"いきる":["japanese"],"いくじ":["japanese"],"いくぶん":["japanese"],"いけばな":["japanese"],"いけん":["japanese"],"いこう":["japanese"],"いこく":["japanese"],"いこつ":["japanese"],"いさましい":["japanese"],"いさん":["japanese"],"いしき":["japanese"],"いじゅう":["japanese"],"いじょう":["japanese"],"いじわる":["japanese"],"いずみ":["japanese"],"いずれ":["japanese"],"いせい":["japanese"],"いせえび":["japanese"],"いせかい":["japanese"],"いせき":["japanese"],"いぜん":["japanese"],"いそうろう":["japanese"],"いそがしい":["japanese"],"いだい":["japanese"],"いだく":["japanese"],"いたずら":["japanese"],"いたみ":["japanese"],"いたりあ":["japanese"],"いちおう":["japanese"],"いちじ":["japanese"],"いちど":["japanese"],"いちば":["japanese"],"いちぶ":["japanese"],"いちりゅう":["japanese"],"いつか":["japanese"],"いっしゅん":["japanese"],"いっせい":["japanese"],"いっそう":["japanese"],"いったん":["japanese"],"いっち":["japanese"],"いってい":["japanese"],"いっぽう":["japanese"],"いてざ":["japanese"],"いてん":["japanese"],"いどう":["japanese"],"いとこ":["japanese"],"いない":["japanese"],"いなか":["japanese"],"いねむり":["japanese"],"いのち":["japanese"],"いのる":["japanese"],"いはつ":["japanese"],"いばる":["japanese"],"いはん":["japanese"],"いびき":["japanese"],"いひん":["japanese"],"いふく":["japanese"],"いへん":["japanese"],"いほう":["japanese"],"いみん":["japanese"],"いもうと":["japanese"],"いもたれ":["japanese"],"いもり":["japanese"],"いやがる":["japanese"],"いやす":["japanese"],"いよかん":["japanese"],"いよく":["japanese"],"いらい":["japanese"],"いらすと":["japanese"],"いりぐち":["japanese"],"いりょう":["japanese"],"いれい":["japanese"],"いれもの":["japanese"],"いれる":["japanese"],"いろえんぴつ":["japanese"],"いわい":["japanese"],"いわう":["japanese"],"いわかん":["japanese"],"いわば":["japanese"],"いわゆる":["japanese"],"いんげんまめ":["japanese"],"いんさつ":["japanese"],"いんしょう":["japanese"],"いんよう":["japanese"],"うえき":["japanese"],"うえる":["japanese"],"うおざ":["japanese"],"うがい":["japanese"],"うかぶ":["japanese"],"うかべる":["japanese"],"うきわ":["japanese"],"うくらいな":["japanese"],"うくれれ":["japanese"],"うけたまわる":["japanese"],"うけつけ":["japanese"],"うけとる":["japanese"],"うけもつ":["japanese"],"うける":["japanese"],"うごかす":["japanese"],"うごく":["japanese"],"うこん":["japanese"],"うさぎ":["japanese"],"うしなう":["japanese"],"うしろがみ":["japanese"],"うすい":["japanese"],"うすぎ":["japanese"],"うすぐらい":["japanese"],"うすめる":["japanese"],"うせつ":["japanese"],"うちあわせ":["japanese"],"うちがわ":["japanese"],"うちき":["japanese"],"うちゅう":["japanese"],"うっかり":["japanese"],"うつくしい":["japanese"],"うったえる":["japanese"],"うつる":["japanese"],"うどん":["japanese"],"うなぎ":["japanese"],"うなじ":["japanese"],"うなずく":["japanese"],"うなる":["japanese"],"うねる":["japanese"],"うのう":["japanese"],"うぶげ":["japanese"],"うぶごえ":["japanese"],"うまれる":["japanese"],"うめる":["japanese"],"うもう":["japanese"],"うやまう":["japanese"],"うよく":["japanese"],"うらがえす":["japanese"],"うらぐち":["japanese"],"うらない":["japanese"],"うりあげ":["japanese"],"うりきれ":["japanese"],"うるさい":["japanese"],"うれしい":["japanese"],"うれゆき":["japanese"],"うれる":["japanese"],"うろこ":["japanese"],"うわき":["japanese"],"うわさ":["japanese"],"うんこう":["japanese"],"うんちん":["japanese"],"うんてん":["japanese"],"うんどう":["japanese"],"えいえん":["japanese"],"えいが":["japanese"],"えいきょう":["japanese"],"えいご":["japanese"],"えいせい":["japanese"],"えいぶん":["japanese"],"えいよう":["japanese"],"えいわ":["japanese"],"えおり":["japanese"],"えがお":["japanese"],"えがく":["japanese"],"えきたい":["japanese"],"えくせる":["japanese"],"えしゃく":["japanese"],"えすて":["japanese"],"えつらん":["japanese"],"えのぐ":["japanese"],"えほうまき":["japanese"],"えほん":["japanese"],"えまき":["japanese"],"えもじ":["japanese"],"えもの":["japanese"],"えらい":["japanese"],"えらぶ":["japanese"],"えりあ":["japanese"],"えんえん":["japanese"],"えんかい":["japanese"],"えんぎ":["japanese"],"えんげき":["japanese"],"えんしゅう":["japanese"],"えんぜつ":["japanese"],"えんそく":["japanese"],"えんちょう":["japanese"],"えんとつ":["japanese"],"おいかける":["japanese"],"おいこす":["japanese"],"おいしい":["japanese"],"おいつく":["japanese"],"おうえん":["japanese"],"おうさま":["japanese"],"おうじ":["japanese"],"おうせつ":["japanese"],"おうたい":["japanese"],"おうふく":["japanese"],"おうべい":["japanese"],"おうよう":["japanese"],"おえる":["japanese"],"おおい":["japanese"],"おおう":["japanese"],"おおどおり":["japanese"],"おおや":["japanese"],"おおよそ":["japanese"],"おかえり":["japanese"],"おかず":["japanese"],"おがむ":["japanese"],"おかわり":["japanese"],"おぎなう":["japanese"],"おきる":["japanese"],"おくさま":["japanese"],"おくじょう":["japanese"],"おくりがな":["japanese"],"おくる":["japanese"],"おくれる":["japanese"],"おこす":["japanese"],"おこなう":["japanese"],"おこる":["japanese"],"おさえる":["japanese"],"おさない":["japanese"],"おさめる":["japanese"],"おしいれ":["japanese"],"おしえる":["japanese"],"おじぎ":["japanese"],"おじさん":["japanese"],"おしゃれ":["japanese"],"おそらく":["japanese"],"おそわる":["japanese"],"おたがい":["japanese"],"おたく":["japanese"],"おだやか":["japanese"],"おちつく":["japanese"],"おっと":["japanese"],"おつり":["japanese"],"おでかけ":["japanese"],"おとしもの":["japanese"],"おとなしい":["japanese"],"おどり":["japanese"],"おどろかす":["japanese"],"おばさん":["japanese"],"おまいり":["japanese"],"おめでとう":["japanese"],"おもいで":["japanese"],"おもう":["japanese"],"おもたい":["japanese"],"おもちゃ":["japanese"],"おやつ":["japanese"],"おやゆび":["japanese"],"およぼす":["japanese"],"おらんだ":["japanese"],"おろす":["japanese"],"おんがく":["japanese"],"おんけい":["japanese"],"おんしゃ":["japanese"],"おんせん":["japanese"],"おんだん":["japanese"],"おんちゅう":["japanese"],"おんどけい":["japanese"],"かあつ":["japanese"],"かいが":["japanese"],"がいき":["japanese"],"がいけん":["japanese"],"がいこう":["japanese"],"かいさつ":["japanese"],"かいしゃ":["japanese"],"かいすいよく":["japanese"],"かいぜん":["japanese"],"かいぞうど":["japanese"],"かいつう":["japanese"],"かいてん":["japanese"],"かいとう":["japanese"],"かいふく":["japanese"],"がいへき":["japanese"],"かいほう":["japanese"],"かいよう":["japanese"],"がいらい":["japanese"],"かいわ":["japanese"],"かえる":["japanese"],"かおり":["japanese"],"かかえる":["japanese"],"かがく":["japanese"],"かがし":["japanese"],"かがみ":["japanese"],"かくご":["japanese"],"かくとく":["japanese"],"かざる":["japanese"],"がぞう":["japanese"],"かたい":["japanese"],"かたち":["japanese"],"がちょう":["japanese"],"がっきゅう":["japanese"],"がっこう":["japanese"],"がっさん":["japanese"],"がっしょう":["japanese"],"かなざわし":["japanese"],"かのう":["japanese"],"がはく":["japanese"],"かぶか":["japanese"],"かほう":["japanese"],"かほご":["japanese"],"かまう":["japanese"],"かまぼこ":["japanese"],"かめれおん":["japanese"],"かゆい":["japanese"],"かようび":["japanese"],"からい":["japanese"],"かるい":["japanese"],"かろう":["japanese"],"かわく":["japanese"],"かわら":["japanese"],"がんか":["japanese"],"かんけい":["japanese"],"かんこう":["japanese"],"かんしゃ":["japanese"],"かんそう":["japanese"],"かんたん":["japanese"],"かんち":["japanese"],"がんばる":["japanese"],"きあい":["japanese"],"きあつ":["japanese"],"きいろ":["japanese"],"ぎいん":["japanese"],"きうい":["japanese"],"きうん":["japanese"],"きえる":["japanese"],"きおう":["japanese"],"きおく":["japanese"],"きおち":["japanese"],"きおん":["japanese"],"きかい":["japanese"],"きかく":["japanese"],"きかんしゃ":["japanese"],"ききて":["japanese"],"きくばり":["japanese"],"きくらげ":["japanese"],"きけんせい":["japanese"],"きこう":["japanese"],"きこえる":["japanese"],"きこく":["japanese"],"きさい":["japanese"],"きさく":["japanese"],"きさま":["japanese"],"きさらぎ":["japanese"],"ぎじかがく":["japanese"],"ぎしき":["japanese"],"ぎじたいけん":["japanese"],"ぎじにってい":["japanese"],"ぎじゅつしゃ":["japanese"],"きすう":["japanese"],"きせい":["japanese"],"きせき":["japanese"],"きせつ":["japanese"],"きそう":["japanese"],"きぞく":["japanese"],"きぞん":["japanese"],"きたえる":["japanese"],"きちょう":["japanese"],"きつえん":["japanese"],"ぎっちり":["japanese"],"きつつき":["japanese"],"きつね":["japanese"],"きてい":["japanese"],"きどう":["japanese"],"きどく":["japanese"],"きない":["japanese"],"きなが":["japanese"],"きなこ":["japanese"],"きぬごし":["japanese"],"きねん":["japanese"],"きのう":["japanese"],"きのした":["japanese"],"きはく":["japanese"],"きびしい":["japanese"],"きひん":["japanese"],"きふく":["japanese"],"きぶん":["japanese"],"きぼう":["japanese"],"きほん":["japanese"],"きまる":["japanese"],"きみつ":["japanese"],"きむずかしい":["japanese"],"きめる":["japanese"],"きもだめし":["japanese"],"きもち":["japanese"],"きもの":["japanese"],"きゃく":["japanese"],"きやく":["japanese"],"ぎゅうにく":["japanese"],"きよう":["japanese"],"きょうりゅう":["japanese"],"きらい":["japanese"],"きらく":["japanese"],"きりん":["japanese"],"きれい":["japanese"],"きれつ":["japanese"],"きろく":["japanese"],"ぎろん":["japanese"],"きわめる":["japanese"],"ぎんいろ":["japanese"],"きんかくじ":["japanese"],"きんじょ":["japanese"],"きんようび":["japanese"],"ぐあい":["japanese"],"くいず":["japanese"],"くうかん":["japanese"],"くうき":["japanese"],"くうぐん":["japanese"],"くうこう":["japanese"],"ぐうせい":["japanese"],"くうそう":["japanese"],"ぐうたら":["japanese"],"くうふく":["japanese"],"くうぼ":["japanese"],"くかん":["japanese"],"くきょう":["japanese"],"くげん":["japanese"],"ぐこう":["japanese"],"くさい":["japanese"],"くさき":["japanese"],"くさばな":["japanese"],"くさる":["japanese"],"くしゃみ":["japanese"],"くしょう":["japanese"],"くすのき":["japanese"],"くすりゆび":["japanese"],"くせげ":["japanese"],"くせん":["japanese"],"ぐたいてき":["japanese"],"くださる":["japanese"],"くたびれる":["japanese"],"くちこみ":["japanese"],"くちさき":["japanese"],"くつした":["japanese"],"ぐっすり":["japanese"],"くつろぐ":["japanese"],"くとうてん":["japanese"],"くどく":["japanese"],"くなん":["japanese"],"くねくね":["japanese"],"くのう":["japanese"],"くふう":["japanese"],"くみあわせ":["japanese"],"くみたてる":["japanese"],"くめる":["japanese"],"くやくしょ":["japanese"],"くらす":["japanese"],"くらべる":["japanese"],"くるま":["japanese"],"くれる":["japanese"],"くろう":["japanese"],"くわしい":["japanese"],"ぐんかん":["japanese"],"ぐんしょく":["japanese"],"ぐんたい":["japanese"],"ぐんて":["japanese"],"けあな":["japanese"],"けいかく":["japanese"],"けいけん":["japanese"],"けいこ":["japanese"],"けいさつ":["japanese"],"げいじゅつ":["japanese"],"けいたい":["japanese"],"げいのうじん":["japanese"],"けいれき":["japanese"],"けいろ":["japanese"],"けおとす":["japanese"],"けおりもの":["japanese"],"げきか":["japanese"],"げきげん":["japanese"],"げきだん":["japanese"],"げきちん":["japanese"],"げきとつ":["japanese"],"げきは":["japanese"],"げきやく":["japanese"],"げこう":["japanese"],"げこくじょう":["japanese"],"げざい":["japanese"],"けさき":["japanese"],"げざん":["japanese"],"けしき":["japanese"],"けしごむ":["japanese"],"けしょう":["japanese"],"げすと":["japanese"],"けたば":["japanese"],"けちゃっぷ":["japanese"],"けちらす":["japanese"],"けつあつ":["japanese"],"けつい":["japanese"],"けつえき":["japanese"],"けっこん":["japanese"],"けつじょ":["japanese"],"けっせき":["japanese"],"けってい":["japanese"],"けつまつ":["japanese"],"げつようび":["japanese"],"げつれい":["japanese"],"けつろん":["japanese"],"げどく":["japanese"],"けとばす":["japanese"],"けとる":["japanese"],"けなげ":["japanese"],"けなす":["japanese"],"けなみ":["japanese"],"けぬき":["japanese"],"げねつ":["japanese"],"けねん":["japanese"],"けはい":["japanese"],"げひん":["japanese"],"けぶかい":["japanese"],"げぼく":["japanese"],"けまり":["japanese"],"けみかる":["japanese"],"けむし":["japanese"],"けむり":["japanese"],"けもの":["japanese"],"けらい":["japanese"],"けろけろ":["japanese"],"けわしい":["japanese"],"けんい":["japanese"],"けんえつ":["japanese"],"けんお":["japanese"],"けんか":["japanese"],"げんき":["japanese"],"けんげん":["japanese"],"けんこう":["japanese"],"けんさく":["japanese"],"けんしゅう":["japanese"],"けんすう":["japanese"],"げんそう":["japanese"],"けんちく":["japanese"],"けんてい":["japanese"],"けんとう":["japanese"],"けんない":["japanese"],"けんにん":["japanese"],"げんぶつ":["japanese"],"けんま":["japanese"],"けんみん":["japanese"],"けんめい":["japanese"],"けんらん":["japanese"],"けんり":["japanese"],"こあくま":["japanese"],"こいぬ":["japanese"],"こいびと":["japanese"],"ごうい":["japanese"],"こうえん":["japanese"],"こうおん":["japanese"],"こうかん":["japanese"],"ごうきゅう":["japanese"],"ごうけい":["japanese"],"こうこう":["japanese"],"こうさい":["japanese"],"こうじ":["japanese"],"こうすい":["japanese"],"ごうせい":["japanese"],"こうそく":["japanese"],"こうたい":["japanese"],"こうちゃ":["japanese"],"こうつう":["japanese"],"こうてい":["japanese"],"こうどう":["japanese"],"こうない":["japanese"],"こうはい":["japanese"],"ごうほう":["japanese"],"ごうまん":["japanese"],"こうもく":["japanese"],"こうりつ":["japanese"],"こえる":["japanese"],"こおり":["japanese"],"ごかい":["japanese"],"ごがつ":["japanese"],"ごかん":["japanese"],"こくご":["japanese"],"こくさい":["japanese"],"こくとう":["japanese"],"こくない":["japanese"],"こくはく":["japanese"],"こぐま":["japanese"],"こけい":["japanese"],"こける":["japanese"],"ここのか":["japanese"],"こころ":["japanese"],"こさめ":["japanese"],"こしつ":["japanese"],"こすう":["japanese"],"こせい":["japanese"],"こせき":["japanese"],"こぜん":["japanese"],"こそだて":["japanese"],"こたい":["japanese"],"こたえる":["japanese"],"こたつ":["japanese"],"こちょう":["japanese"],"こっか":["japanese"],"こつこつ":["japanese"],"こつばん":["japanese"],"こつぶ":["japanese"],"こてい":["japanese"],"こてん":["japanese"],"ことがら":["japanese"],"ことし":["japanese"],"ことば":["japanese"],"ことり":["japanese"],"こなごな":["japanese"],"こねこね":["japanese"],"このまま":["japanese"],"このみ":["japanese"],"このよ":["japanese"],"ごはん":["japanese"],"こひつじ":["japanese"],"こふう":["japanese"],"こふん":["japanese"],"こぼれる":["japanese"],"ごまあぶら":["japanese"],"こまかい":["japanese"],"ごますり":["japanese"],"こまつな":["japanese"],"こまる":["japanese"],"こむぎこ":["japanese"],"こもじ":["japanese"],"こもち":["japanese"],"こもの":["japanese"],"こもん":["japanese"],"こやく":["japanese"],"こやま":["japanese"],"こゆう":["japanese"],"こゆび":["japanese"],"こよい":["japanese"],"こよう":["japanese"],"こりる":["japanese"],"これくしょん":["japanese"],"ころっけ":["japanese"],"こわもて":["japanese"],"こわれる":["japanese"],"こんいん":["japanese"],"こんかい":["japanese"],"こんき":["japanese"],"こんしゅう":["japanese"],"こんすい":["japanese"],"こんだて":["japanese"],"こんとん":["japanese"],"こんなん":["japanese"],"こんびに":["japanese"],"こんぽん":["japanese"],"こんまけ":["japanese"],"こんや":["japanese"],"こんれい":["japanese"],"こんわく":["japanese"],"ざいえき":["japanese"],"さいかい":["japanese"],"さいきん":["japanese"],"ざいげん":["japanese"],"ざいこ":["japanese"],"さいしょ":["japanese"],"さいせい":["japanese"],"ざいたく":["japanese"],"ざいちゅう":["japanese"],"さいてき":["japanese"],"ざいりょう":["japanese"],"さうな":["japanese"],"さかいし":["japanese"],"さがす":["japanese"],"さかな":["japanese"],"さかみち":["japanese"],"さがる":["japanese"],"さぎょう":["japanese"],"さくし":["japanese"],"さくひん":["japanese"],"さくら":["japanese"],"さこく":["japanese"],"さこつ":["japanese"],"さずかる":["japanese"],"ざせき":["japanese"],"さたん":["japanese"],"さつえい":["japanese"],"ざつおん":["japanese"],"ざっか":["japanese"],"ざつがく":["japanese"],"さっきょく":["japanese"],"ざっし":["japanese"],"さつじん":["japanese"],"ざっそう":["japanese"],"さつたば":["japanese"],"さつまいも":["japanese"],"さてい":["japanese"],"さといも":["japanese"],"さとう":["japanese"],"さとおや":["japanese"],"さとし":["japanese"],"さとる":["japanese"],"さのう":["japanese"],"さばく":["japanese"],"さびしい":["japanese"],"さべつ":["japanese"],"さほう":["japanese"],"さほど":["japanese"],"さます":["japanese"],"さみしい":["japanese"],"さみだれ":["japanese"],"さむけ":["japanese"],"さめる":["japanese"],"さやえんどう":["japanese"],"さゆう":["japanese"],"さよう":["japanese"],"さよく":["japanese"],"さらだ":["japanese"],"ざるそば":["japanese"],"さわやか":["japanese"],"さわる":["japanese"],"さんいん":["japanese"],"さんか":["japanese"],"さんきゃく":["japanese"],"さんこう":["japanese"],"さんさい":["japanese"],"ざんしょ":["japanese"],"さんすう":["japanese"],"さんせい":["japanese"],"さんそ":["japanese"],"さんち":["japanese"],"さんま":["japanese"],"さんみ":["japanese"],"さんらん":["japanese"],"しあい":["japanese"],"しあげ":["japanese"],"しあさって":["japanese"],"しあわせ":["japanese"],"しいく":["japanese"],"しいん":["japanese"],"しうち":["japanese"],"しえい":["japanese"],"しおけ":["japanese"],"しかい":["japanese"],"しかく":["japanese"],"じかん":["japanese"],"しごと":["japanese"],"しすう":["japanese"],"じだい":["japanese"],"したうけ":["japanese"],"したぎ":["japanese"],"したて":["japanese"],"したみ":["japanese"],"しちょう":["japanese"],"しちりん":["japanese"],"しっかり":["japanese"],"しつじ":["japanese"],"しつもん":["japanese"],"してい":["japanese"],"してき":["japanese"],"してつ":["japanese"],"じてん":["japanese"],"じどう":["japanese"],"しなぎれ":["japanese"],"しなもの":["japanese"],"しなん":["japanese"],"しねま":["japanese"],"しねん":["japanese"],"しのぐ":["japanese"],"しのぶ":["japanese"],"しはい":["japanese"],"しばかり":["japanese"],"しはつ":["japanese"],"しはらい":["japanese"],"しはん":["japanese"],"しひょう":["japanese"],"しふく":["japanese"],"じぶん":["japanese"],"しへい":["japanese"],"しほう":["japanese"],"しほん":["japanese"],"しまう":["japanese"],"しまる":["japanese"],"しみん":["japanese"],"しむける":["japanese"],"じむしょ":["japanese"],"しめい":["japanese"],"しめる":["japanese"],"しもん":["japanese"],"しゃいん":["japanese"],"しゃうん":["japanese"],"しゃおん":["japanese"],"じゃがいも":["japanese"],"しやくしょ":["japanese"],"しゃくほう":["japanese"],"しゃけん":["japanese"],"しゃこ":["japanese"],"しゃざい":["japanese"],"しゃしん":["japanese"],"しゃせん":["japanese"],"しゃそう":["japanese"],"しゃたい":["japanese"],"しゃちょう":["japanese"],"しゃっきん":["japanese"],"じゃま":["japanese"],"しゃりん":["japanese"],"しゃれい":["japanese"],"じゆう":["japanese"],"じゅうしょ":["japanese"],"しゅくはく":["japanese"],"じゅしん":["japanese"],"しゅっせき":["japanese"],"しゅみ":["japanese"],"しゅらば":["japanese"],"じゅんばん":["japanese"],"しょうかい":["japanese"],"しょくたく":["japanese"],"しょっけん":["japanese"],"しょどう":["japanese"],"しょもつ":["japanese"],"しらせる":["japanese"],"しらべる":["japanese"],"しんか":["japanese"],"しんこう":["japanese"],"じんじゃ":["japanese"],"しんせいじ":["japanese"],"しんちく":["japanese"],"しんりん":["japanese"],"すあげ":["japanese"],"すあし":["japanese"],"すあな":["japanese"],"ずあん":["japanese"],"すいえい":["japanese"],"すいか":["japanese"],"すいとう":["japanese"],"ずいぶん":["japanese"],"すいようび":["japanese"],"すうがく":["japanese"],"すうじつ":["japanese"],"すうせん":["japanese"],"すおどり":["japanese"],"すきま":["japanese"],"すくう":["japanese"],"すくない":["japanese"],"すける":["japanese"],"すごい":["japanese"],"すこし":["japanese"],"ずさん":["japanese"],"すずしい":["japanese"],"すすむ":["japanese"],"すすめる":["japanese"],"すっかり":["japanese"],"ずっしり":["japanese"],"ずっと":["japanese"],"すてき":["japanese"],"すてる":["japanese"],"すねる":["japanese"],"すのこ":["japanese"],"すはだ":["japanese"],"すばらしい":["japanese"],"ずひょう":["japanese"],"ずぶぬれ":["japanese"],"すぶり":["japanese"],"すふれ":["japanese"],"すべて":["japanese"],"すべる":["japanese"],"ずほう":["japanese"],"すぼん":["japanese"],"すまい":["japanese"],"すめし":["japanese"],"すもう":["japanese"],"すやき":["japanese"],"すらすら":["japanese"],"するめ":["japanese"],"すれちがう":["japanese"],"すろっと":["japanese"],"すわる":["japanese"],"すんぜん":["japanese"],"すんぽう":["japanese"],"せあぶら":["japanese"],"せいかつ":["japanese"],"せいげん":["japanese"],"せいじ":["japanese"],"せいよう":["japanese"],"せおう":["japanese"],"せかいかん":["japanese"],"せきにん":["japanese"],"せきむ":["japanese"],"せきゆ":["japanese"],"せきらんうん":["japanese"],"せけん":["japanese"],"せこう":["japanese"],"せすじ":["japanese"],"せたい":["japanese"],"せたけ":["japanese"],"せっかく":["japanese"],"せっきゃく":["japanese"],"ぜっく":["japanese"],"せっけん":["japanese"],"せっこつ":["japanese"],"せっさたくま":["japanese"],"せつぞく":["japanese"],"せつだん":["japanese"],"せつでん":["japanese"],"せっぱん":["japanese"],"せつび":["japanese"],"せつぶん":["japanese"],"せつめい":["japanese"],"せつりつ":["japanese"],"せなか":["japanese"],"せのび":["japanese"],"せはば":["japanese"],"せびろ":["japanese"],"せぼね":["japanese"],"せまい":["japanese"],"せまる":["japanese"],"せめる":["japanese"],"せもたれ":["japanese"],"せりふ":["japanese"],"ぜんあく":["japanese"],"せんい":["japanese"],"せんえい":["japanese"],"せんか":["japanese"],"せんきょ":["japanese"],"せんく":["japanese"],"せんげん":["japanese"],"ぜんご":["japanese"],"せんさい":["japanese"],"せんしゅ":["japanese"],"せんすい":["japanese"],"せんせい":["japanese"],"せんぞ":["japanese"],"せんたく":["japanese"],"せんちょう":["japanese"],"せんてい":["japanese"],"せんとう":["japanese"],"せんぬき":["japanese"],"せんねん":["japanese"],"せんぱい":["japanese"],"ぜんぶ":["japanese"],"ぜんぽう":["japanese"],"せんむ":["japanese"],"せんめんじょ":["japanese"],"せんもん":["japanese"],"せんやく":["japanese"],"せんゆう":["japanese"],"せんよう":["japanese"],"ぜんら":["japanese"],"ぜんりゃく":["japanese"],"せんれい":["japanese"],"せんろ":["japanese"],"そあく":["japanese"],"そいとげる":["japanese"],"そいね":["japanese"],"そうがんきょう":["japanese"],"そうき":["japanese"],"そうご":["japanese"],"そうしん":["japanese"],"そうだん":["japanese"],"そうなん":["japanese"],"そうび":["japanese"],"そうめん":["japanese"],"そうり":["japanese"],"そえもの":["japanese"],"そえん":["japanese"],"そがい":["japanese"],"そげき":["japanese"],"そこう":["japanese"],"そこそこ":["japanese"],"そざい":["japanese"],"そしな":["japanese"],"そせい":["japanese"],"そせん":["japanese"],"そそぐ":["japanese"],"そだてる":["japanese"],"そつう":["japanese"],"そつえん":["japanese"],"そっかん":["japanese"],"そつぎょう":["japanese"],"そっけつ":["japanese"],"そっこう":["japanese"],"そっせん":["japanese"],"そっと":["japanese"],"そとがわ":["japanese"],"そとづら":["japanese"],"そなえる":["japanese"],"そなた":["japanese"],"そふぼ":["japanese"],"そぼく":["japanese"],"そぼろ":["japanese"],"そまつ":["japanese"],"そまる":["japanese"],"そむく":["japanese"],"そむりえ":["japanese"],"そめる":["japanese"],"そもそも":["japanese"],"そよかぜ":["japanese"],"そらまめ":["japanese"],"そろう":["japanese"],"そんかい":["japanese"],"そんけい":["japanese"],"そんざい":["japanese"],"そんしつ":["japanese"],"そんぞく":["japanese"],"そんちょう":["japanese"],"ぞんび":["japanese"],"ぞんぶん":["japanese"],"そんみん":["japanese"],"たあい":["japanese"],"たいいん":["japanese"],"たいうん":["japanese"],"たいえき":["japanese"],"たいおう":["japanese"],"だいがく":["japanese"],"たいき":["japanese"],"たいぐう":["japanese"],"たいけん":["japanese"],"たいこ":["japanese"],"たいざい":["japanese"],"だいじょうぶ":["japanese"],"だいすき":["japanese"],"たいせつ":["japanese"],"たいそう":["japanese"],"だいたい":["japanese"],"たいちょう":["japanese"],"たいてい":["japanese"],"だいどころ":["japanese"],"たいない":["japanese"],"たいねつ":["japanese"],"たいのう":["japanese"],"たいはん":["japanese"],"だいひょう":["japanese"],"たいふう":["japanese"],"たいへん":["japanese"],"たいほ":["japanese"],"たいまつばな":["japanese"],"たいみんぐ":["japanese"],"たいむ":["japanese"],"たいめん":["japanese"],"たいやき":["japanese"],"たいよう":["japanese"],"たいら":["japanese"],"たいりょく":["japanese"],"たいる":["japanese"],"たいわん":["japanese"],"たうえ":["japanese"],"たえる":["japanese"],"たおす":["japanese"],"たおる":["japanese"],"たおれる":["japanese"],"たかい":["japanese"],"たかね":["japanese"],"たきび":["japanese"],"たくさん":["japanese"],"たこく":["japanese"],"たこやき":["japanese"],"たさい":["japanese"],"たしざん":["japanese"],"だじゃれ":["japanese"],"たすける":["japanese"],"たずさわる":["japanese"],"たそがれ":["japanese"],"たたかう":["japanese"],"たたく":["japanese"],"ただしい":["japanese"],"たたみ":["japanese"],"たちばな":["japanese"],"だっかい":["japanese"],"だっきゃく":["japanese"],"だっこ":["japanese"],"だっしゅつ":["japanese"],"だったい":["japanese"],"たてる":["japanese"],"たとえる":["japanese"],"たなばた":["japanese"],"たにん":["japanese"],"たぬき":["japanese"],"たのしみ":["japanese"],"たはつ":["japanese"],"たぶん":["japanese"],"たべる":["japanese"],"たぼう":["japanese"],"たまご":["japanese"],"たまる":["japanese"],"だむる":["japanese"],"ためいき":["japanese"],"ためす":["japanese"],"ためる":["japanese"],"たもつ":["japanese"],"たやすい":["japanese"],"たよる":["japanese"],"たらす":["japanese"],"たりきほんがん":["japanese"],"たりょう":["japanese"],"たりる":["japanese"],"たると":["japanese"],"たれる":["japanese"],"たれんと":["japanese"],"たろっと":["japanese"],"たわむれる":["japanese"],"だんあつ":["japanese"],"たんい":["japanese"],"たんおん":["japanese"],"たんか":["japanese"],"たんき":["japanese"],"たんけん":["japanese"],"たんご":["japanese"],"たんさん":["japanese"],"たんじょうび":["japanese"],"だんせい":["japanese"],"たんそく":["japanese"],"たんたい":["japanese"],"だんち":["japanese"],"たんてい":["japanese"],"たんとう":["japanese"],"だんな":["japanese"],"たんにん":["japanese"],"だんねつ":["japanese"],"たんのう":["japanese"],"たんぴん":["japanese"],"だんぼう":["japanese"],"たんまつ":["japanese"],"たんめい":["japanese"],"だんれつ":["japanese"],"だんろ":["japanese"],"だんわ":["japanese"],"ちあい":["japanese"],"ちあん":["japanese"],"ちいき":["japanese"],"ちいさい":["japanese"],"ちえん":["japanese"],"ちかい":["japanese"],"ちから":["japanese"],"ちきゅう":["japanese"],"ちきん":["japanese"],"ちけいず":["japanese"],"ちけん":["japanese"],"ちこく":["japanese"],"ちさい":["japanese"],"ちしき":["japanese"],"ちしりょう":["japanese"],"ちせい":["japanese"],"ちそう":["japanese"],"ちたい":["japanese"],"ちたん":["japanese"],"ちちおや":["japanese"],"ちつじょ":["japanese"],"ちてき":["japanese"],"ちてん":["japanese"],"ちぬき":["japanese"],"ちぬり":["japanese"],"ちのう":["japanese"],"ちひょう":["japanese"],"ちへいせん":["japanese"],"ちほう":["japanese"],"ちまた":["japanese"],"ちみつ":["japanese"],"ちみどろ":["japanese"],"ちめいど":["japanese"],"ちゃんこなべ":["japanese"],"ちゅうい":["japanese"],"ちゆりょく":["japanese"],"ちょうし":["japanese"],"ちょさくけん":["japanese"],"ちらし":["japanese"],"ちらみ":["japanese"],"ちりがみ":["japanese"],"ちりょう":["japanese"],"ちるど":["japanese"],"ちわわ":["japanese"],"ちんたい":["japanese"],"ちんもく":["japanese"],"ついか":["japanese"],"ついたち":["japanese"],"つうか":["japanese"],"つうじょう":["japanese"],"つうはん":["japanese"],"つうわ":["japanese"],"つかう":["japanese"],"つかれる":["japanese"],"つくね":["japanese"],"つくる":["japanese"],"つけね":["japanese"],"つける":["japanese"],"つごう":["japanese"],"つたえる":["japanese"],"つづく":["japanese"],"つつじ":["japanese"],"つつむ":["japanese"],"つとめる":["japanese"],"つながる":["japanese"],"つなみ":["japanese"],"つねづね":["japanese"],"つのる":["japanese"],"つぶす":["japanese"],"つまらない":["japanese"],"つまる":["japanese"],"つみき":["japanese"],"つめたい":["japanese"],"つもり":["japanese"],"つもる":["japanese"],"つよい":["japanese"],"つるぼ":["japanese"],"つるみく":["japanese"],"つわもの":["japanese"],"つわり":["japanese"],"てあし":["japanese"],"てあて":["japanese"],"てあみ":["japanese"],"ていおん":["japanese"],"ていか":["japanese"],"ていき":["japanese"],"ていけい":["japanese"],"ていこく":["japanese"],"ていさつ":["japanese"],"ていし":["japanese"],"ていせい":["japanese"],"ていたい":["japanese"],"ていど":["japanese"],"ていねい":["japanese"],"ていひょう":["japanese"],"ていへん":["japanese"],"ていぼう":["japanese"],"てうち":["japanese"],"ておくれ":["japanese"],"てきとう":["japanese"],"てくび":["japanese"],"でこぼこ":["japanese"],"てさぎょう":["japanese"],"てさげ":["japanese"],"てすり":["japanese"],"てそう":["japanese"],"てちがい":["japanese"],"てちょう":["japanese"],"てつがく":["japanese"],"てつづき":["japanese"],"でっぱ":["japanese"],"てつぼう":["japanese"],"てつや":["japanese"],"でぬかえ":["japanese"],"てぬき":["japanese"],"てぬぐい":["japanese"],"てのひら":["japanese"],"てはい":["japanese"],"てぶくろ":["japanese"],"てふだ":["japanese"],"てほどき":["japanese"],"てほん":["japanese"],"てまえ":["japanese"],"てまきずし":["japanese"],"てみじか":["japanese"],"てみやげ":["japanese"],"てらす":["japanese"],"てれび":["japanese"],"てわけ":["japanese"],"てわたし":["japanese"],"でんあつ":["japanese"],"てんいん":["japanese"],"てんかい":["japanese"],"てんき":["japanese"],"てんぐ":["japanese"],"てんけん":["japanese"],"てんごく":["japanese"],"てんさい":["japanese"],"てんし":["japanese"],"てんすう":["japanese"],"でんち":["japanese"],"てんてき":["japanese"],"てんとう":["japanese"],"てんない":["japanese"],"てんぷら":["japanese"],"てんぼうだい":["japanese"],"てんめつ":["japanese"],"てんらんかい":["japanese"],"でんりょく":["japanese"],"でんわ":["japanese"],"どあい":["japanese"],"といれ":["japanese"],"どうかん":["japanese"],"とうきゅう":["japanese"],"どうぐ":["japanese"],"とうし":["japanese"],"とうむぎ":["japanese"],"とおい":["japanese"],"とおか":["japanese"],"とおく":["japanese"],"とおす":["japanese"],"とおる":["japanese"],"とかい":["japanese"],"とかす":["japanese"],"ときおり":["japanese"],"ときどき":["japanese"],"とくい":["japanese"],"とくしゅう":["japanese"],"とくてん":["japanese"],"とくに":["japanese"],"とくべつ":["japanese"],"とけい":["japanese"],"とける":["japanese"],"とこや":["japanese"],"とさか":["japanese"],"としょかん":["japanese"],"とそう":["japanese"],"とたん":["japanese"],"とちゅう":["japanese"],"とっきゅう":["japanese"],"とっくん":["japanese"],"とつぜん":["japanese"],"とつにゅう":["japanese"],"とどける":["japanese"],"ととのえる":["japanese"],"とない":["japanese"],"となえる":["japanese"],"となり":["japanese"],"とのさま":["japanese"],"とばす":["japanese"],"どぶがわ":["japanese"],"とほう":["japanese"],"とまる":["japanese"],"とめる":["japanese"],"ともだち":["japanese"],"ともる":["japanese"],"どようび":["japanese"],"とらえる":["japanese"],"とんかつ":["japanese"],"どんぶり":["japanese"],"ないかく":["japanese"],"ないこう":["japanese"],"ないしょ":["japanese"],"ないす":["japanese"],"ないせん":["japanese"],"ないそう":["japanese"],"なおす":["japanese"],"ながい":["japanese"],"なくす":["japanese"],"なげる":["japanese"],"なこうど":["japanese"],"なさけ":["japanese"],"なたでここ":["japanese"],"なっとう":["japanese"],"なつやすみ":["japanese"],"ななおし":["japanese"],"なにごと":["japanese"],"なにもの":["japanese"],"なにわ":["japanese"],"なのか":["japanese"],"なふだ":["japanese"],"なまいき":["japanese"],"なまえ":["japanese"],"なまみ":["japanese"],"なみだ":["japanese"],"なめらか":["japanese"],"なめる":["japanese"],"なやむ":["japanese"],"ならう":["japanese"],"ならび":["japanese"],"ならぶ":["japanese"],"なれる":["japanese"],"なわとび":["japanese"],"なわばり":["japanese"],"にあう":["japanese"],"にいがた":["japanese"],"にうけ":["japanese"],"におい":["japanese"],"にかい":["japanese"],"にがて":["japanese"],"にきび":["japanese"],"にくしみ":["japanese"],"にくまん":["japanese"],"にげる":["japanese"],"にさんかたんそ":["japanese"],"にしき":["japanese"],"にせもの":["japanese"],"にちじょう":["japanese"],"にちようび":["japanese"],"にっか":["japanese"],"にっき":["japanese"],"にっけい":["japanese"],"にっこう":["japanese"],"にっさん":["japanese"],"にっしょく":["japanese"],"にっすう":["japanese"],"にっせき":["japanese"],"にってい":["japanese"],"になう":["japanese"],"にほん":["japanese"],"にまめ":["japanese"],"にもつ":["japanese"],"にやり":["japanese"],"にゅういん":["japanese"],"にりんしゃ":["japanese"],"にわとり":["japanese"],"にんい":["japanese"],"にんか":["japanese"],"にんき":["japanese"],"にんげん":["japanese"],"にんしき":["japanese"],"にんずう":["japanese"],"にんそう":["japanese"],"にんたい":["japanese"],"にんち":["japanese"],"にんてい":["japanese"],"にんにく":["japanese"],"にんぷ":["japanese"],"にんまり":["japanese"],"にんむ":["japanese"],"にんめい":["japanese"],"にんよう":["japanese"],"ぬいくぎ":["japanese"],"ぬかす":["japanese"],"ぬぐいとる":["japanese"],"ぬぐう":["japanese"],"ぬくもり":["japanese"],"ぬすむ":["japanese"],"ぬまえび":["japanese"],"ぬめり":["japanese"],"ぬらす":["japanese"],"ぬんちゃく":["japanese"],"ねあげ":["japanese"],"ねいき":["japanese"],"ねいる":["japanese"],"ねいろ":["japanese"],"ねぐせ":["japanese"],"ねくたい":["japanese"],"ねくら":["japanese"],"ねこぜ":["japanese"],"ねこむ":["japanese"],"ねさげ":["japanese"],"ねすごす":["japanese"],"ねそべる":["japanese"],"ねだん":["japanese"],"ねつい":["japanese"],"ねっしん":["japanese"],"ねつぞう":["japanese"],"ねったいぎょ":["japanese"],"ねぶそく":["japanese"],"ねふだ":["japanese"],"ねぼう":["japanese"],"ねほりはほり":["japanese"],"ねまき":["japanese"],"ねまわし":["japanese"],"ねみみ":["japanese"],"ねむい":["japanese"],"ねむたい":["japanese"],"ねもと":["japanese"],"ねらう":["japanese"],"ねわざ":["japanese"],"ねんいり":["japanese"],"ねんおし":["japanese"],"ねんかん":["japanese"],"ねんきん":["japanese"],"ねんぐ":["japanese"],"ねんざ":["japanese"],"ねんし":["japanese"],"ねんちゃく":["japanese"],"ねんど":["japanese"],"ねんぴ":["japanese"],"ねんぶつ":["japanese"],"ねんまつ":["japanese"],"ねんりょう":["japanese"],"ねんれい":["japanese"],"のいず":["japanese"],"のおづま":["japanese"],"のがす":["japanese"],"のきなみ":["japanese"],"のこぎり":["japanese"],"のこす":["japanese"],"のこる":["japanese"],"のせる":["japanese"],"のぞく":["japanese"],"のぞむ":["japanese"],"のたまう":["japanese"],"のちほど":["japanese"],"のっく":["japanese"],"のばす":["japanese"],"のはら":["japanese"],"のべる":["japanese"],"のぼる":["japanese"],"のみもの":["japanese"],"のやま":["japanese"],"のらいぬ":["japanese"],"のらねこ":["japanese"],"のりもの":["japanese"],"のりゆき":["japanese"],"のれん":["japanese"],"のんき":["japanese"],"ばあい":["japanese"],"はあく":["japanese"],"ばあさん":["japanese"],"ばいか":["japanese"],"ばいく":["japanese"],"はいけん":["japanese"],"はいご":["japanese"],"はいしん":["japanese"],"はいすい":["japanese"],"はいせん":["japanese"],"はいそう":["japanese"],"はいち":["japanese"],"ばいばい":["japanese"],"はいれつ":["japanese"],"はえる":["japanese"],"はおる":["japanese"],"はかい":["japanese"],"ばかり":["japanese"],"はかる":["japanese"],"はくしゅ":["japanese"],"はけん":["japanese"],"はこぶ":["japanese"],"はさみ":["japanese"],"はさん":["japanese"],"はしご":["japanese"],"ばしょ":["japanese"],"はしる":["japanese"],"はせる":["japanese"],"ぱそこん":["japanese"],"はそん":["japanese"],"はたん":["japanese"],"はちみつ":["japanese"],"はつおん":["japanese"],"はっかく":["japanese"],"はづき":["japanese"],"はっきり":["japanese"],"はっくつ":["japanese"],"はっけん":["japanese"],"はっこう":["japanese"],"はっさん":["japanese"],"はっしん":["japanese"],"はったつ":["japanese"],"はっちゅう":["japanese"],"はってん":["japanese"],"はっぴょう":["japanese"],"はっぽう":["japanese"],"はなす":["japanese"],"はなび":["japanese"],"はにかむ":["japanese"],"はぶらし":["japanese"],"はみがき":["japanese"],"はむかう":["japanese"],"はめつ":["japanese"],"はやい":["japanese"],"はやし":["japanese"],"はらう":["japanese"],"はろうぃん":["japanese"],"はわい":["japanese"],"はんい":["japanese"],"はんえい":["japanese"],"はんおん":["japanese"],"はんかく":["japanese"],"はんきょう":["japanese"],"ばんぐみ":["japanese"],"はんこ":["japanese"],"はんしゃ":["japanese"],"はんすう":["japanese"],"はんだん":["japanese"],"ぱんち":["japanese"],"ぱんつ":["japanese"],"はんてい":["japanese"],"はんとし":["japanese"],"はんのう":["japanese"],"はんぱ":["japanese"],"はんぶん":["japanese"],"はんぺん":["japanese"],"はんぼうき":["japanese"],"はんめい":["japanese"],"はんらん":["japanese"],"はんろん":["japanese"],"ひいき":["japanese"],"ひうん":["japanese"],"ひえる":["japanese"],"ひかく":["japanese"],"ひかり":["japanese"],"ひかる":["japanese"],"ひかん":["japanese"],"ひくい":["japanese"],"ひけつ":["japanese"],"ひこうき":["japanese"],"ひこく":["japanese"],"ひさい":["japanese"],"ひさしぶり":["japanese"],"ひさん":["japanese"],"びじゅつかん":["japanese"],"ひしょ":["japanese"],"ひそか":["japanese"],"ひそむ":["japanese"],"ひたむき":["japanese"],"ひだり":["japanese"],"ひたる":["japanese"],"ひつぎ":["japanese"],"ひっこし":["japanese"],"ひっし":["japanese"],"ひつじゅひん":["japanese"],"ひっす":["japanese"],"ひつぜん":["japanese"],"ぴったり":["japanese"],"ぴっちり":["japanese"],"ひつよう":["japanese"],"ひてい":["japanese"],"ひとごみ":["japanese"],"ひなまつり":["japanese"],"ひなん":["japanese"],"ひねる":["japanese"],"ひはん":["japanese"],"ひびく":["japanese"],"ひひょう":["japanese"],"ひほう":["japanese"],"ひまわり":["japanese"],"ひまん":["japanese"],"ひみつ":["japanese"],"ひめい":["japanese"],"ひめじし":["japanese"],"ひやけ":["japanese"],"ひやす":["japanese"],"ひよう":["japanese"],"びょうき":["japanese"],"ひらがな":["japanese"],"ひらく":["japanese"],"ひりつ":["japanese"],"ひりょう":["japanese"],"ひるま":["japanese"],"ひるやすみ":["japanese"],"ひれい":["japanese"],"ひろい":["japanese"],"ひろう":["japanese"],"ひろき":["japanese"],"ひろゆき":["japanese"],"ひんかく":["japanese"],"ひんけつ":["japanese"],"ひんこん":["japanese"],"ひんしゅ":["japanese"],"ひんそう":["japanese"],"ぴんち":["japanese"],"ひんぱん":["japanese"],"びんぼう":["japanese"],"ふあん":["japanese"],"ふいうち":["japanese"],"ふうけい":["japanese"],"ふうせん":["japanese"],"ぷうたろう":["japanese"],"ふうとう":["japanese"],"ふうふ":["japanese"],"ふえる":["japanese"],"ふおん":["japanese"],"ふかい":["japanese"],"ふきん":["japanese"],"ふくざつ":["japanese"],"ふくぶくろ":["japanese"],"ふこう":["japanese"],"ふさい":["japanese"],"ふしぎ":["japanese"],"ふじみ":["japanese"],"ふすま":["japanese"],"ふせい":["japanese"],"ふせぐ":["japanese"],"ふそく":["japanese"],"ぶたにく":["japanese"],"ふたん":["japanese"],"ふちょう":["japanese"],"ふつう":["japanese"],"ふつか":["japanese"],"ふっかつ":["japanese"],"ふっき":["japanese"],"ふっこく":["japanese"],"ぶどう":["japanese"],"ふとる":["japanese"],"ふとん":["japanese"],"ふのう":["japanese"],"ふはい":["japanese"],"ふひょう":["japanese"],"ふへん":["japanese"],"ふまん":["japanese"],"ふみん":["japanese"],"ふめつ":["japanese"],"ふめん":["japanese"],"ふよう":["japanese"],"ふりこ":["japanese"],"ふりる":["japanese"],"ふるい":["japanese"],"ふんいき":["japanese"],"ぶんがく":["japanese"],"ぶんぐ":["japanese"],"ふんしつ":["japanese"],"ぶんせき":["japanese"],"ふんそう":["japanese"],"ぶんぽう":["japanese"],"へいあん":["japanese"],"へいおん":["japanese"],"へいがい":["japanese"],"へいき":["japanese"],"へいげん":["japanese"],"へいこう":["japanese"],"へいさ":["japanese"],"へいしゃ":["japanese"],"へいせつ":["japanese"],"へいそ":["japanese"],"へいたく":["japanese"],"へいてん":["japanese"],"へいねつ":["japanese"],"へいわ":["japanese"],"へきが":["japanese"],"へこむ":["japanese"],"べにいろ":["japanese"],"べにしょうが":["japanese"],"へらす":["japanese"],"へんかん":["japanese"],"べんきょう":["japanese"],"べんごし":["japanese"],"へんさい":["japanese"],"へんたい":["japanese"],"べんり":["japanese"],"ほあん":["japanese"],"ほいく":["japanese"],"ぼうぎょ":["japanese"],"ほうこく":["japanese"],"ほうそう":["japanese"],"ほうほう":["japanese"],"ほうもん":["japanese"],"ほうりつ":["japanese"],"ほえる":["japanese"],"ほおん":["japanese"],"ほかん":["japanese"],"ほきょう":["japanese"],"ぼきん":["japanese"],"ほくろ":["japanese"],"ほけつ":["japanese"],"ほけん":["japanese"],"ほこう":["japanese"],"ほこる":["japanese"],"ほしい":["japanese"],"ほしつ":["japanese"],"ほしゅ":["japanese"],"ほしょう":["japanese"],"ほせい":["japanese"],"ほそい":["japanese"],"ほそく":["japanese"],"ほたて":["japanese"],"ほたる":["japanese"],"ぽちぶくろ":["japanese"],"ほっきょく":["japanese"],"ほっさ":["japanese"],"ほったん":["japanese"],"ほとんど":["japanese"],"ほめる":["japanese"],"ほんい":["japanese"],"ほんき":["japanese"],"ほんけ":["japanese"],"ほんしつ":["japanese"],"ほんやく":["japanese"],"まいにち":["japanese"],"まかい":["japanese"],"まかせる":["japanese"],"まがる":["japanese"],"まける":["japanese"],"まこと":["japanese"],"まさつ":["japanese"],"まじめ":["japanese"],"ますく":["japanese"],"まぜる":["japanese"],"まつり":["japanese"],"まとめ":["japanese"],"まなぶ":["japanese"],"まぬけ":["japanese"],"まねく":["japanese"],"まほう":["japanese"],"まもる":["japanese"],"まゆげ":["japanese"],"まよう":["japanese"],"まろやか":["japanese"],"まわす":["japanese"],"まわり":["japanese"],"まわる":["japanese"],"まんが":["japanese"],"まんきつ":["japanese"],"まんぞく":["japanese"],"まんなか":["japanese"],"みいら":["japanese"],"みうち":["japanese"],"みえる":["japanese"],"みがく":["japanese"],"みかた":["japanese"],"みかん":["japanese"],"みけん":["japanese"],"みこん":["japanese"],"みじかい":["japanese"],"みすい":["japanese"],"みすえる":["japanese"],"みせる":["japanese"],"みっか":["japanese"],"みつかる":["japanese"],"みつける":["japanese"],"みてい":["japanese"],"みとめる":["japanese"],"みなと":["japanese"],"みなみかさい":["japanese"],"みねらる":["japanese"],"みのう":["japanese"],"みのがす":["japanese"],"みほん":["japanese"],"みもと":["japanese"],"みやげ":["japanese"],"みらい":["japanese"],"みりょく":["japanese"],"みわく":["japanese"],"みんか":["japanese"],"みんぞく":["japanese"],"むいか":["japanese"],"むえき":["japanese"],"むえん":["japanese"],"むかい":["japanese"],"むかう":["japanese"],"むかえ":["japanese"],"むかし":["japanese"],"むぎちゃ":["japanese"],"むける":["japanese"],"むげん":["japanese"],"むさぼる":["japanese"],"むしあつい":["japanese"],"むしば":["japanese"],"むじゅん":["japanese"],"むしろ":["japanese"],"むすう":["japanese"],"むすこ":["japanese"],"むすぶ":["japanese"],"むすめ":["japanese"],"むせる":["japanese"],"むせん":["japanese"],"むちゅう":["japanese"],"むなしい":["japanese"],"むのう":["japanese"],"むやみ":["japanese"],"むよう":["japanese"],"むらさき":["japanese"],"むりょう":["japanese"],"むろん":["japanese"],"めいあん":["japanese"],"めいうん":["japanese"],"めいえん":["japanese"],"めいかく":["japanese"],"めいきょく":["japanese"],"めいさい":["japanese"],"めいし":["japanese"],"めいそう":["japanese"],"めいぶつ":["japanese"],"めいれい":["japanese"],"めいわく":["japanese"],"めぐまれる":["japanese"],"めざす":["japanese"],"めした":["japanese"],"めずらしい":["japanese"],"めだつ":["japanese"],"めまい":["japanese"],"めやす":["japanese"],"めんきょ":["japanese"],"めんせき":["japanese"],"めんどう":["japanese"],"もうしあげる":["japanese"],"もうどうけん":["japanese"],"もえる":["japanese"],"もくし":["japanese"],"もくてき":["japanese"],"もくようび":["japanese"],"もちろん":["japanese"],"もどる":["japanese"],"もらう":["japanese"],"もんく":["japanese"],"もんだい":["japanese"],"やおや":["japanese"],"やける":["japanese"],"やさい":["japanese"],"やさしい":["japanese"],"やすい":["japanese"],"やすたろう":["japanese"],"やすみ":["japanese"],"やせる":["japanese"],"やそう":["japanese"],"やたい":["japanese"],"やちん":["japanese"],"やっと":["japanese"],"やっぱり":["japanese"],"やぶる":["japanese"],"やめる":["japanese"],"ややこしい":["japanese"],"やよい":["japanese"],"やわらかい":["japanese"],"ゆうき":["japanese"],"ゆうびんきょく":["japanese"],"ゆうべ":["japanese"],"ゆうめい":["japanese"],"ゆけつ":["japanese"],"ゆしゅつ":["japanese"],"ゆせん":["japanese"],"ゆそう":["japanese"],"ゆたか":["japanese"],"ゆちゃく":["japanese"],"ゆでる":["japanese"],"ゆにゅう":["japanese"],"ゆびわ":["japanese"],"ゆらい":["japanese"],"ゆれる":["japanese"],"ようい":["japanese"],"ようか":["japanese"],"ようきゅう":["japanese"],"ようじ":["japanese"],"ようす":["japanese"],"ようちえん":["japanese"],"よかぜ":["japanese"],"よかん":["japanese"],"よきん":["japanese"],"よくせい":["japanese"],"よくぼう":["japanese"],"よけい":["japanese"],"よごれる":["japanese"],"よさん":["japanese"],"よしゅう":["japanese"],"よそう":["japanese"],"よそく":["japanese"],"よっか":["japanese"],"よてい":["japanese"],"よどがわく":["japanese"],"よねつ":["japanese"],"よやく":["japanese"],"よゆう":["japanese"],"よろこぶ":["japanese"],"よろしい":["japanese"],"らいう":["japanese"],"らくがき":["japanese"],"らくご":["japanese"],"らくさつ":["japanese"],"らくだ":["japanese"],"らしんばん":["japanese"],"らせん":["japanese"],"らぞく":["japanese"],"らたい":["japanese"],"らっか":["japanese"],"られつ":["japanese"],"りえき":["japanese"],"りかい":["japanese"],"りきさく":["japanese"],"りきせつ":["japanese"],"りくぐん":["japanese"],"りくつ":["japanese"],"りけん":["japanese"],"りこう":["japanese"],"りせい":["japanese"],"りそう":["japanese"],"りそく":["japanese"],"りてん":["japanese"],"りねん":["japanese"],"りゆう":["japanese"],"りゅうがく":["japanese"],"りよう":["japanese"],"りょうり":["japanese"],"りょかん":["japanese"],"りょくちゃ":["japanese"],"りょこう":["japanese"],"りりく":["japanese"],"りれき":["japanese"],"りろん":["japanese"],"りんご":["japanese"],"るいけい":["japanese"],"るいさい":["japanese"],"るいじ":["japanese"],"るいせき":["japanese"],"るすばん":["japanese"],"るりがわら":["japanese"],"れいかん":["japanese"],"れいぎ":["japanese"],"れいせい":["japanese"],"れいぞうこ":["japanese"],"れいとう":["japanese"],"れいぼう":["japanese"],"れきし":["japanese"],"れきだい":["japanese"],"れんあい":["japanese"],"れんけい":["japanese"],"れんこん":["japanese"],"れんさい":["japanese"],"れんしゅう":["japanese"],"れんぞく":["japanese"],"れんらく":["japanese"],"ろうか":["japanese"],"ろうご":["japanese"],"ろうじん":["japanese"],"ろうそく":["japanese"],"ろくが":["japanese"],"ろこつ":["japanese"],"ろじうら":["japanese"],"ろしゅつ":["japanese"],"ろせん":["japanese"],"ろてん":["japanese"],"ろめん":["japanese"],"ろれつ":["japanese"],"ろんぎ":["japanese"],"ろんぱ":["japanese"],"ろんぶん":["japanese"],"ろんり":["japanese"],"わかす":["japanese"],"わかめ":["japanese"],"わかやま":["japanese"],"わかれる":["japanese"],"わしつ":["japanese"],"わじまし":["japanese"],"わすれもの":["japanese"],"わらう":["japanese"],"われる":["japanese"],"가격":["korean"],"가끔":["korean"],"가난":["korean"],"가능":["korean"],"가득":["korean"],"가르침":["korean"],"가뭄":["korean"],"가방":["korean"],"가상":["korean"],"가슴":["korean"],"가운데":["korean"],"가을":["korean"],"가이드":["korean"],"가입":["korean"],"가장":["korean"],"가정":["korean"],"가족":["korean"],"가죽":["korean"],"각오":["korean"],"각자":["korean"],"간격":["korean"],"간부":["korean"],"간섭":["korean"],"간장":["korean"],"간접":["korean"],"간판":["korean"],"갈등":["korean"],"갈비":["korean"],"갈색":["korean"],"갈증":["korean"],"감각":["korean"],"감기":["korean"],"감소":["korean"],"감수성":["korean"],"감자":["korean"],"감정":["korean"],"갑자기":["korean"],"강남":["korean"],"강당":["korean"],"강도":["korean"],"강력히":["korean"],"강변":["korean"],"강북":["korean"],"강사":["korean"],"강수량":["korean"],"강아지":["korean"],"강원도":["korean"],"강의":["korean"],"강제":["korean"],"강조":["korean"],"같이":["korean"],"개구리":["korean"],"개나리":["korean"],"개방":["korean"],"개별":["korean"],"개선":["korean"],"개성":["korean"],"개인":["korean"],"객관적":["korean"],"거실":["korean"],"거액":["korean"],"거울":["korean"],"거짓":["korean"],"거품":["korean"],"걱정":["korean"],"건강":["korean"],"건물":["korean"],"건설":["korean"],"건조":["korean"],"건축":["korean"],"걸음":["korean"],"검사":["korean"],"검토":["korean"],"게시판":["korean"],"게임":["korean"],"겨울":["korean"],"견해":["korean"],"결과":["korean"],"결국":["korean"],"결론":["korean"],"결석":["korean"],"결승":["korean"],"결심":["korean"],"결정":["korean"],"결혼":["korean"],"경계":["korean"],"경고":["korean"],"경기":["korean"],"경력":["korean"],"경복궁":["korean"],"경비":["korean"],"경상도":["korean"],"경영":["korean"],"경우":["korean"],"경쟁":["korean"],"경제":["korean"],"경주":["korean"],"경찰":["korean"],"경치":["korean"],"경향":["korean"],"경험":["korean"],"계곡":["korean"],"계단":["korean"],"계란":["korean"],"계산":["korean"],"계속":["korean"],"계약":["korean"],"계절":["korean"],"계층":["korean"],"계획":["korean"],"고객":["korean"],"고구려":["korean"],"고궁":["korean"],"고급":["korean"],"고등학생":["korean"],"고무신":["korean"],"고민":["korean"],"고양이":["korean"],"고장":["korean"],"고전":["korean"],"고집":["korean"],"고춧가루":["korean"],"고통":["korean"],"고향":["korean"],"곡식":["korean"],"골목":["korean"],"골짜기":["korean"],"골프":["korean"],"공간":["korean"],"공개":["korean"],"공격":["korean"],"공군":["korean"],"공급":["korean"],"공기":["korean"],"공동":["korean"],"공무원":["korean"],"공부":["korean"],"공사":["korean"],"공식":["korean"],"공업":["korean"],"공연":["korean"],"공원":["korean"],"공장":["korean"],"공짜":["korean"],"공책":["korean"],"공통":["korean"],"공포":["korean"],"공항":["korean"],"공휴일":["korean"],"과목":["korean"],"과일":["korean"],"과장":["korean"],"과정":["korean"],"과학":["korean"],"관객":["korean"],"관계":["korean"],"관광":["korean"],"관념":["korean"],"관람":["korean"],"관련":["korean"],"관리":["korean"],"관습":["korean"],"관심":["korean"],"관점":["korean"],"관찰":["korean"],"광경":["korean"],"광고":["korean"],"광장":["korean"],"광주":["korean"],"괴로움":["korean"],"굉장히":["korean"],"교과서":["korean"],"교문":["korean"],"교복":["korean"],"교실":["korean"],"교양":["korean"],"교육":["korean"],"교장":["korean"],"교직":["korean"],"교통":["korean"],"교환":["korean"],"교훈":["korean"],"구경":["korean"],"구름":["korean"],"구멍":["korean"],"구별":["korean"],"구분":["korean"],"구석":["korean"],"구성":["korean"],"구속":["korean"],"구역":["korean"],"구입":["korean"],"구청":["korean"],"구체적":["korean"],"국가":["korean"],"국기":["korean"],"국내":["korean"],"국립":["korean"],"국물":["korean"],"국민":["korean"],"국수":["korean"],"국어":["korean"],"국왕":["korean"],"국적":["korean"],"국제":["korean"],"국회":["korean"],"군대":["korean"],"군사":["korean"],"군인":["korean"],"궁극적":["korean"],"권리":["korean"],"권위":["korean"],"권투":["korean"],"귀국":["korean"],"귀신":["korean"],"규정":["korean"],"규칙":["korean"],"균형":["korean"],"그날":["korean"],"그냥":["korean"],"그늘":["korean"],"그러나":["korean"],"그룹":["korean"],"그릇":["korean"],"그림":["korean"],"그제서야":["korean"],"그토록":["korean"],"극복":["korean"],"극히":["korean"],"근거":["korean"],"근교":["korean"],"근래":["korean"],"근로":["korean"],"근무":["korean"],"근본":["korean"],"근원":["korean"],"근육":["korean"],"근처":["korean"],"글씨":["korean"],"글자":["korean"],"금강산":["korean"],"금고":["korean"],"금년":["korean"],"금메달":["korean"],"금액":["korean"],"금연":["korean"],"금요일":["korean"],"금지":["korean"],"긍정적":["korean"],"기간":["korean"],"기관":["korean"],"기념":["korean"],"기능":["korean"],"기독교":["korean"],"기둥":["korean"],"기록":["korean"],"기름":["korean"],"기법":["korean"],"기본":["korean"],"기분":["korean"],"기쁨":["korean"],"기숙사":["korean"],"기술":["korean"],"기억":["korean"],"기업":["korean"],"기온":["korean"],"기운":["korean"],"기원":["korean"],"기적":["korean"],"기준":["korean"],"기침":["korean"],"기혼":["korean"],"기획":["korean"],"긴급":["korean"],"긴장":["korean"],"길이":["korean"],"김밥":["korean"],"김치":["korean"],"김포공항":["korean"],"깍두기":["korean"],"깜빡":["korean"],"깨달음":["korean"],"깨소금":["korean"],"껍질":["korean"],"꼭대기":["korean"],"꽃잎":["korean"],"나들이":["korean"],"나란히":["korean"],"나머지":["korean"],"나물":["korean"],"나침반":["korean"],"나흘":["korean"],"낙엽":["korean"],"난방":["korean"],"날개":["korean"],"날씨":["korean"],"날짜":["korean"],"남녀":["korean"],"남대문":["korean"],"남매":["korean"],"남산":["korean"],"남자":["korean"],"남편":["korean"],"남학생":["korean"],"낭비":["korean"],"낱말":["korean"],"내년":["korean"],"내용":["korean"],"내일":["korean"],"냄비":["korean"],"냄새":["korean"],"냇물":["korean"],"냉동":["korean"],"냉면":["korean"],"냉방":["korean"],"냉장고":["korean"],"넥타이":["korean"],"넷째":["korean"],"노동":["korean"],"노란색":["korean"],"노력":["korean"],"노인":["korean"],"녹음":["korean"],"녹차":["korean"],"녹화":["korean"],"논리":["korean"],"논문":["korean"],"논쟁":["korean"],"놀이":["korean"],"농구":["korean"],"농담":["korean"],"농민":["korean"],"농부":["korean"],"농업":["korean"],"농장":["korean"],"농촌":["korean"],"높이":["korean"],"눈동자":["korean"],"눈물":["korean"],"눈썹":["korean"],"뉴욕":["korean"],"느낌":["korean"],"늑대":["korean"],"능동적":["korean"],"능력":["korean"],"다방":["korean"],"다양성":["korean"],"다음":["korean"],"다이어트":["korean"],"다행":["korean"],"단계":["korean"],"단골":["korean"],"단독":["korean"],"단맛":["korean"],"단순":["korean"],"단어":["korean"],"단위":["korean"],"단점":["korean"],"단체":["korean"],"단추":["korean"],"단편":["korean"],"단풍":["korean"],"달걀":["korean"],"달러":["korean"],"달력":["korean"],"달리":["korean"],"닭고기":["korean"],"담당":["korean"],"담배":["korean"],"담요":["korean"],"담임":["korean"],"답변":["korean"],"답장":["korean"],"당근":["korean"],"당분간":["korean"],"당연히":["korean"],"당장":["korean"],"대규모":["korean"],"대낮":["korean"],"대단히":["korean"],"대답":["korean"],"대도시":["korean"],"대략":["korean"],"대량":["korean"],"대륙":["korean"],"대문":["korean"],"대부분":["korean"],"대신":["korean"],"대응":["korean"],"대장":["korean"],"대전":["korean"],"대접":["korean"],"대중":["korean"],"대책":["korean"],"대출":["korean"],"대충":["korean"],"대통령":["korean"],"대학":["korean"],"대한민국":["korean"],"대합실":["korean"],"대형":["korean"],"덩어리":["korean"],"데이트":["korean"],"도대체":["korean"],"도덕":["korean"],"도둑":["korean"],"도망":["korean"],"도서관":["korean"],"도심":["korean"],"도움":["korean"],"도입":["korean"],"도자기":["korean"],"도저히":["korean"],"도전":["korean"],"도중":["korean"],"도착":["korean"],"독감":["korean"],"독립":["korean"],"독서":["korean"],"독일":["korean"],"독창적":["korean"],"동화책":["korean"],"뒷모습":["korean"],"뒷산":["korean"],"딸아이":["korean"],"마누라":["korean"],"마늘":["korean"],"마당":["korean"],"마라톤":["korean"],"마련":["korean"],"마무리":["korean"],"마사지":["korean"],"마약":["korean"],"마요네즈":["korean"],"마을":["korean"],"마음":["korean"],"마이크":["korean"],"마중":["korean"],"마지막":["korean"],"마찬가지":["korean"],"마찰":["korean"],"마흔":["korean"],"막걸리":["korean"],"막내":["korean"],"막상":["korean"],"만남":["korean"],"만두":["korean"],"만세":["korean"],"만약":["korean"],"만일":["korean"],"만점":["korean"],"만족":["korean"],"만화":["korean"],"많이":["korean"],"말기":["korean"],"말씀":["korean"],"말투":["korean"],"맘대로":["korean"],"망원경":["korean"],"매년":["korean"],"매달":["korean"],"매력":["korean"],"매번":["korean"],"매스컴":["korean"],"매일":["korean"],"매장":["korean"],"맥주":["korean"],"먹이":["korean"],"먼저":["korean"],"먼지":["korean"],"멀리":["korean"],"메일":["korean"],"며느리":["korean"],"며칠":["korean"],"면담":["korean"],"멸치":["korean"],"명단":["korean"],"명령":["korean"],"명예":["korean"],"명의":["korean"],"명절":["korean"],"명칭":["korean"],"명함":["korean"],"모금":["korean"],"모니터":["korean"],"모델":["korean"],"모든":["korean"],"모범":["korean"],"모습":["korean"],"모양":["korean"],"모임":["korean"],"모조리":["korean"],"모집":["korean"],"모퉁이":["korean"],"목걸이":["korean"],"목록":["korean"],"목사":["korean"],"목소리":["korean"],"목숨":["korean"],"목적":["korean"],"목표":["korean"],"몰래":["korean"],"몸매":["korean"],"몸무게":["korean"],"몸살":["korean"],"몸속":["korean"],"몸짓":["korean"],"몸통":["korean"],"몹시":["korean"],"무관심":["korean"],"무궁화":["korean"],"무더위":["korean"],"무덤":["korean"],"무릎":["korean"],"무슨":["korean"],"무엇":["korean"],"무역":["korean"],"무용":["korean"],"무조건":["korean"],"무지개":["korean"],"무척":["korean"],"문구":["korean"],"문득":["korean"],"문법":["korean"],"문서":["korean"],"문제":["korean"],"문학":["korean"],"문화":["korean"],"물가":["korean"],"물건":["korean"],"물결":["korean"],"물고기":["korean"],"물론":["korean"],"물리학":["korean"],"물음":["korean"],"물질":["korean"],"물체":["korean"],"미국":["korean"],"미디어":["korean"],"미사일":["korean"],"미술":["korean"],"미역":["korean"],"미용실":["korean"],"미움":["korean"],"미인":["korean"],"미팅":["korean"],"미혼":["korean"],"민간":["korean"],"민족":["korean"],"민주":["korean"],"믿음":["korean"],"밀가루":["korean"],"밀리미터":["korean"],"밑바닥":["korean"],"바가지":["korean"],"바구니":["korean"],"바나나":["korean"],"바늘":["korean"],"바닥":["korean"],"바닷가":["korean"],"바람":["korean"],"바이러스":["korean"],"바탕":["korean"],"박물관":["korean"],"박사":["korean"],"박수":["korean"],"반대":["korean"],"반드시":["korean"],"반말":["korean"],"반발":["korean"],"반성":["korean"],"반응":["korean"],"반장":["korean"],"반죽":["korean"],"반지":["korean"],"반찬":["korean"],"받침":["korean"],"발가락":["korean"],"발걸음":["korean"],"발견":["korean"],"발달":["korean"],"발레":["korean"],"발목":["korean"],"발바닥":["korean"],"발생":["korean"],"발음":["korean"],"발자국":["korean"],"발전":["korean"],"발톱":["korean"],"발표":["korean"],"밤하늘":["korean"],"밥그릇":["korean"],"밥맛":["korean"],"밥상":["korean"],"밥솥":["korean"],"방금":["korean"],"방면":["korean"],"방문":["korean"],"방바닥":["korean"],"방법":["korean"],"방송":["korean"],"방식":["korean"],"방안":["korean"],"방울":["korean"],"방지":["korean"],"방학":["korean"],"방해":["korean"],"방향":["korean"],"배경":["korean"],"배꼽":["korean"],"배달":["korean"],"배드민턴":["korean"],"백두산":["korean"],"백색":["korean"],"백성":["korean"],"백인":["korean"],"백제":["korean"],"백화점":["korean"],"버릇":["korean"],"버섯":["korean"],"버튼":["korean"],"번개":["korean"],"번역":["korean"],"번지":["korean"],"번호":["korean"],"벌금":["korean"],"벌레":["korean"],"벌써":["korean"],"범위":["korean"],"범인":["korean"],"범죄":["korean"],"법률":["korean"],"법원":["korean"],"법적":["korean"],"법칙":["korean"],"베이징":["korean"],"벨트":["korean"],"변경":["korean"],"변동":["korean"],"변명":["korean"],"변신":["korean"],"변호사":["korean"],"변화":["korean"],"별도":["korean"],"별명":["korean"],"별일":["korean"],"병실":["korean"],"병아리":["korean"],"병원":["korean"],"보관":["korean"],"보너스":["korean"],"보라색":["korean"],"보람":["korean"],"보름":["korean"],"보상":["korean"],"보안":["korean"],"보자기":["korean"],"보장":["korean"],"보전":["korean"],"보존":["korean"],"보통":["korean"],"보편적":["korean"],"보험":["korean"],"복도":["korean"],"복사":["korean"],"복숭아":["korean"],"복습":["korean"],"볶음":["korean"],"본격적":["korean"],"본래":["korean"],"본부":["korean"],"본사":["korean"],"본성":["korean"],"본인":["korean"],"본질":["korean"],"볼펜":["korean"],"봉사":["korean"],"봉지":["korean"],"봉투":["korean"],"부근":["korean"],"부끄러움":["korean"],"부담":["korean"],"부동산":["korean"],"부문":["korean"],"부분":["korean"],"부산":["korean"],"부상":["korean"],"부엌":["korean"],"부인":["korean"],"부작용":["korean"],"부장":["korean"],"부정":["korean"],"부족":["korean"],"부지런히":["korean"],"부친":["korean"],"부탁":["korean"],"부품":["korean"],"부회장":["korean"],"북부":["korean"],"북한":["korean"],"분노":["korean"],"분량":["korean"],"분리":["korean"],"분명":["korean"],"분석":["korean"],"분야":["korean"],"분위기":["korean"],"분필":["korean"],"분홍색":["korean"],"불고기":["korean"],"불과":["korean"],"불교":["korean"],"불꽃":["korean"],"불만":["korean"],"불법":["korean"],"불빛":["korean"],"불안":["korean"],"불이익":["korean"],"불행":["korean"],"브랜드":["korean"],"비극":["korean"],"비난":["korean"],"비닐":["korean"],"비둘기":["korean"],"비디오":["korean"],"비로소":["korean"],"비만":["korean"],"비명":["korean"],"비밀":["korean"],"비바람":["korean"],"비빔밥":["korean"],"비상":["korean"],"비용":["korean"],"비율":["korean"],"비중":["korean"],"비타민":["korean"],"비판":["korean"],"빌딩":["korean"],"빗물":["korean"],"빗방울":["korean"],"빗줄기":["korean"],"빛깔":["korean"],"빨간색":["korean"],"빨래":["korean"],"빨리":["korean"],"사건":["korean"],"사계절":["korean"],"사나이":["korean"],"사냥":["korean"],"사람":["korean"],"사랑":["korean"],"사립":["korean"],"사모님":["korean"],"사물":["korean"],"사방":["korean"],"사상":["korean"],"사생활":["korean"],"사설":["korean"],"사슴":["korean"],"사실":["korean"],"사업":["korean"],"사용":["korean"],"사월":["korean"],"사장":["korean"],"사전":["korean"],"사진":["korean"],"사촌":["korean"],"사춘기":["korean"],"사탕":["korean"],"사투리":["korean"],"사흘":["korean"],"산길":["korean"],"산부인과":["korean"],"산업":["korean"],"산책":["korean"],"살림":["korean"],"살인":["korean"],"살짝":["korean"],"삼계탕":["korean"],"삼국":["korean"],"삼십":["korean"],"삼월":["korean"],"삼촌":["korean"],"상관":["korean"],"상금":["korean"],"상대":["korean"],"상류":["korean"],"상반기":["korean"],"상상":["korean"],"상식":["korean"],"상업":["korean"],"상인":["korean"],"상자":["korean"],"상점":["korean"],"상처":["korean"],"상추":["korean"],"상태":["korean"],"상표":["korean"],"상품":["korean"],"상황":["korean"],"새벽":["korean"],"색깔":["korean"],"색연필":["korean"],"생각":["korean"],"생명":["korean"],"생물":["korean"],"생방송":["korean"],"생산":["korean"],"생선":["korean"],"생신":["korean"],"생일":["korean"],"생활":["korean"],"서랍":["korean"],"서른":["korean"],"서명":["korean"],"서민":["korean"],"서비스":["korean"],"서양":["korean"],"서울":["korean"],"서적":["korean"],"서점":["korean"],"서쪽":["korean"],"서클":["korean"],"석사":["korean"],"석유":["korean"],"선거":["korean"],"선물":["korean"],"선배":["korean"],"선생":["korean"],"선수":["korean"],"선원":["korean"],"선장":["korean"],"선전":["korean"],"선택":["korean"],"선풍기":["korean"],"설거지":["korean"],"설날":["korean"],"설렁탕":["korean"],"설명":["korean"],"설문":["korean"],"설사":["korean"],"설악산":["korean"],"설치":["korean"],"설탕":["korean"],"섭씨":["korean"],"성공":["korean"],"성당":["korean"],"성명":["korean"],"성별":["korean"],"성인":["korean"],"성장":["korean"],"성적":["korean"],"성질":["korean"],"성함":["korean"],"세금":["korean"],"세미나":["korean"],"세상":["korean"],"세월":["korean"],"세종대왕":["korean"],"세탁":["korean"],"센터":["korean"],"센티미터":["korean"],"셋째":["korean"],"소규모":["korean"],"소극적":["korean"],"소금":["korean"],"소나기":["korean"],"소년":["korean"],"소득":["korean"],"소망":["korean"],"소문":["korean"],"소설":["korean"],"소속":["korean"],"소아과":["korean"],"소용":["korean"],"소원":["korean"],"소음":["korean"],"소중히":["korean"],"소지품":["korean"],"소질":["korean"],"소풍":["korean"],"소형":["korean"],"속담":["korean"],"속도":["korean"],"속옷":["korean"],"손가락":["korean"],"손길":["korean"],"손녀":["korean"],"손님":["korean"],"손등":["korean"],"손목":["korean"],"손뼉":["korean"],"손실":["korean"],"손질":["korean"],"손톱":["korean"],"손해":["korean"],"솔직히":["korean"],"솜씨":["korean"],"송아지":["korean"],"송이":["korean"],"송편":["korean"],"쇠고기":["korean"],"쇼핑":["korean"],"수건":["korean"],"수년":["korean"],"수단":["korean"],"수돗물":["korean"],"수동적":["korean"],"수면":["korean"],"수명":["korean"],"수박":["korean"],"수상":["korean"],"수석":["korean"],"수술":["korean"],"수시로":["korean"],"수업":["korean"],"수염":["korean"],"수영":["korean"],"수입":["korean"],"수준":["korean"],"수집":["korean"],"수출":["korean"],"수컷":["korean"],"수필":["korean"],"수학":["korean"],"수험생":["korean"],"수화기":["korean"],"숙녀":["korean"],"숙소":["korean"],"숙제":["korean"],"순간":["korean"],"순서":["korean"],"순수":["korean"],"순식간":["korean"],"순위":["korean"],"숟가락":["korean"],"술병":["korean"],"술집":["korean"],"숫자":["korean"],"스님":["korean"],"스물":["korean"],"스스로":["korean"],"스승":["korean"],"스웨터":["korean"],"스위치":["korean"],"스케이트":["korean"],"스튜디오":["korean"],"스트레스":["korean"],"스포츠":["korean"],"슬쩍":["korean"],"슬픔":["korean"],"습관":["korean"],"습기":["korean"],"승객":["korean"],"승리":["korean"],"승부":["korean"],"승용차":["korean"],"승진":["korean"],"시각":["korean"],"시간":["korean"],"시골":["korean"],"시금치":["korean"],"시나리오":["korean"],"시댁":["korean"],"시리즈":["korean"],"시멘트":["korean"],"시민":["korean"],"시부모":["korean"],"시선":["korean"],"시설":["korean"],"시스템":["korean"],"시아버지":["korean"],"시어머니":["korean"],"시월":["korean"],"시인":["korean"],"시일":["korean"],"시작":["korean"],"시장":["korean"],"시절":["korean"],"시점":["korean"],"시중":["korean"],"시즌":["korean"],"시집":["korean"],"시청":["korean"],"시합":["korean"],"시험":["korean"],"식구":["korean"],"식기":["korean"],"식당":["korean"],"식량":["korean"],"식료품":["korean"],"식물":["korean"],"식빵":["korean"],"식사":["korean"],"식생활":["korean"],"식초":["korean"],"식탁":["korean"],"식품":["korean"],"신고":["korean"],"신규":["korean"],"신념":["korean"],"신문":["korean"],"신발":["korean"],"신비":["korean"],"신사":["korean"],"신세":["korean"],"신용":["korean"],"신제품":["korean"],"신청":["korean"],"신체":["korean"],"신화":["korean"],"실감":["korean"],"실내":["korean"],"실력":["korean"],"실례":["korean"],"실망":["korean"],"실수":["korean"],"실습":["korean"],"실시":["korean"],"실장":["korean"],"실정":["korean"],"실질적":["korean"],"실천":["korean"],"실체":["korean"],"실컷":["korean"],"실태":["korean"],"실패":["korean"],"실험":["korean"],"실현":["korean"],"심리":["korean"],"심부름":["korean"],"심사":["korean"],"심장":["korean"],"심정":["korean"],"심판":["korean"],"쌍둥이":["korean"],"씨름":["korean"],"씨앗":["korean"],"아가씨":["korean"],"아나운서":["korean"],"아드님":["korean"],"아들":["korean"],"아쉬움":["korean"],"아스팔트":["korean"],"아시아":["korean"],"아울러":["korean"],"아저씨":["korean"],"아줌마":["korean"],"아직":["korean"],"아침":["korean"],"아파트":["korean"],"아프리카":["korean"],"아픔":["korean"],"아홉":["korean"],"아흔":["korean"],"악기":["korean"],"악몽":["korean"],"악수":["korean"],"안개":["korean"],"안경":["korean"],"안과":["korean"],"안내":["korean"],"안녕":["korean"],"안동":["korean"],"안방":["korean"],"안부":["korean"],"안주":["korean"],"알루미늄":["korean"],"알코올":["korean"],"암시":["korean"],"암컷":["korean"],"압력":["korean"],"앞날":["korean"],"앞문":["korean"],"애인":["korean"],"애정":["korean"],"액수":["korean"],"앨범":["korean"],"야간":["korean"],"야단":["korean"],"야옹":["korean"],"약간":["korean"],"약국":["korean"],"약속":["korean"],"약수":["korean"],"약점":["korean"],"약품":["korean"],"약혼녀":["korean"],"양념":["korean"],"양력":["korean"],"양말":["korean"],"양배추":["korean"],"양주":["korean"],"양파":["korean"],"어둠":["korean"],"어려움":["korean"],"어른":["korean"],"어젯밤":["korean"],"어쨌든":["korean"],"어쩌다가":["korean"],"어쩐지":["korean"],"언니":["korean"],"언덕":["korean"],"언론":["korean"],"언어":["korean"],"얼굴":["korean"],"얼른":["korean"],"얼음":["korean"],"얼핏":["korean"],"엄마":["korean"],"업무":["korean"],"업종":["korean"],"업체":["korean"],"엉덩이":["korean"],"엉망":["korean"],"엉터리":["korean"],"엊그제":["korean"],"에너지":["korean"],"에어컨":["korean"],"엔진":["korean"],"여건":["korean"],"여고생":["korean"],"여관":["korean"],"여군":["korean"],"여권":["korean"],"여대생":["korean"],"여덟":["korean"],"여동생":["korean"],"여든":["korean"],"여론":["korean"],"여름":["korean"],"여섯":["korean"],"여성":["korean"],"여왕":["korean"],"여인":["korean"],"여전히":["korean"],"여직원":["korean"],"여학생":["korean"],"여행":["korean"],"역사":["korean"],"역시":["korean"],"역할":["korean"],"연결":["korean"],"연구":["korean"],"연극":["korean"],"연기":["korean"],"연락":["korean"],"연설":["korean"],"연세":["korean"],"연속":["korean"],"연습":["korean"],"연애":["korean"],"연예인":["korean"],"연인":["korean"],"연장":["korean"],"연주":["korean"],"연출":["korean"],"연필":["korean"],"연합":["korean"],"연휴":["korean"],"열기":["korean"],"열매":["korean"],"열쇠":["korean"],"열심히":["korean"],"열정":["korean"],"열차":["korean"],"열흘":["korean"],"염려":["korean"],"엽서":["korean"],"영국":["korean"],"영남":["korean"],"영상":["korean"],"영양":["korean"],"영역":["korean"],"영웅":["korean"],"영원히":["korean"],"영하":["korean"],"영향":["korean"],"영혼":["korean"],"영화":["korean"],"옆구리":["korean"],"옆방":["korean"],"옆집":["korean"],"예감":["korean"],"예금":["korean"],"예방":["korean"],"예산":["korean"],"예상":["korean"],"예선":["korean"],"예술":["korean"],"예습":["korean"],"예식장":["korean"],"예약":["korean"],"예전":["korean"],"예절":["korean"],"예정":["korean"],"예컨대":["korean"],"옛날":["korean"],"오늘":["korean"],"오락":["korean"],"오랫동안":["korean"],"오렌지":["korean"],"오로지":["korean"],"오른발":["korean"],"오븐":["korean"],"오십":["korean"],"오염":["korean"],"오월":["korean"],"오전":["korean"],"오직":["korean"],"오징어":["korean"],"오페라":["korean"],"오피스텔":["korean"],"오히려":["korean"],"옥상":["korean"],"옥수수":["korean"],"온갖":["korean"],"온라인":["korean"],"온몸":["korean"],"온종일":["korean"],"온통":["korean"],"올가을":["korean"],"올림픽":["korean"],"올해":["korean"],"옷차림":["korean"],"와이셔츠":["korean"],"와인":["korean"],"완성":["korean"],"완전":["korean"],"왕비":["korean"],"왕자":["korean"],"왜냐하면":["korean"],"왠지":["korean"],"외갓집":["korean"],"외국":["korean"],"외로움":["korean"],"외삼촌":["korean"],"외출":["korean"],"외침":["korean"],"외할머니":["korean"],"왼발":["korean"],"왼손":["korean"],"왼쪽":["korean"],"요금":["korean"],"요일":["korean"],"요즘":["korean"],"요청":["korean"],"용기":["korean"],"용서":["korean"],"용어":["korean"],"우산":["korean"],"우선":["korean"],"우승":["korean"],"우연히":["korean"],"우정":["korean"],"우체국":["korean"],"우편":["korean"],"운동":["korean"],"운명":["korean"],"운반":["korean"],"운전":["korean"],"운행":["korean"],"울산":["korean"],"울음":["korean"],"움직임":["korean"],"웃어른":["korean"],"웃음":["korean"],"워낙":["korean"],"원고":["korean"],"원래":["korean"],"원서":["korean"],"원숭이":["korean"],"원인":["korean"],"원장":["korean"],"원피스":["korean"],"월급":["korean"],"월드컵":["korean"],"월세":["korean"],"월요일":["korean"],"웨이터":["korean"],"위반":["korean"],"위법":["korean"],"위성":["korean"],"위원":["korean"],"위험":["korean"],"위협":["korean"],"윗사람":["korean"],"유난히":["korean"],"유럽":["korean"],"유명":["korean"],"유물":["korean"],"유산":["korean"],"유적":["korean"],"유치원":["korean"],"유학":["korean"],"유행":["korean"],"유형":["korean"],"육군":["korean"],"육상":["korean"],"육십":["korean"],"육체":["korean"],"은행":["korean"],"음력":["korean"],"음료":["korean"],"음반":["korean"],"음성":["korean"],"음식":["korean"],"음악":["korean"],"음주":["korean"],"의견":["korean"],"의논":["korean"],"의문":["korean"],"의복":["korean"],"의식":["korean"],"의심":["korean"],"의외로":["korean"],"의욕":["korean"],"의원":["korean"],"의학":["korean"],"이것":["korean"],"이곳":["korean"],"이념":["korean"],"이놈":["korean"],"이달":["korean"],"이대로":["korean"],"이동":["korean"],"이렇게":["korean"],"이력서":["korean"],"이론적":["korean"],"이름":["korean"],"이민":["korean"],"이발소":["korean"],"이별":["korean"],"이불":["korean"],"이빨":["korean"],"이상":["korean"],"이성":["korean"],"이슬":["korean"],"이야기":["korean"],"이용":["korean"],"이웃":["korean"],"이월":["korean"],"이윽고":["korean"],"이익":["korean"],"이전":["korean"],"이중":["korean"],"이튿날":["korean"],"이틀":["korean"],"이혼":["korean"],"인간":["korean"],"인격":["korean"],"인공":["korean"],"인구":["korean"],"인근":["korean"],"인기":["korean"],"인도":["korean"],"인류":["korean"],"인물":["korean"],"인생":["korean"],"인쇄":["korean"],"인연":["korean"],"인원":["korean"],"인재":["korean"],"인종":["korean"],"인천":["korean"],"인체":["korean"],"인터넷":["korean"],"인하":["korean"],"인형":["korean"],"일곱":["korean"],"일기":["korean"],"일단":["korean"],"일대":["korean"],"일등":["korean"],"일반":["korean"],"일본":["korean"],"일부":["korean"],"일상":["korean"],"일생":["korean"],"일손":["korean"],"일요일":["korean"],"일월":["korean"],"일정":["korean"],"일종":["korean"],"일주일":["korean"],"일찍":["korean"],"일체":["korean"],"일치":["korean"],"일행":["korean"],"일회용":["korean"],"임금":["korean"],"임무":["korean"],"입대":["korean"],"입력":["korean"],"입맛":["korean"],"입사":["korean"],"입술":["korean"],"입시":["korean"],"입원":["korean"],"입장":["korean"],"입학":["korean"],"자가용":["korean"],"자격":["korean"],"자극":["korean"],"자동":["korean"],"자랑":["korean"],"자부심":["korean"],"자식":["korean"],"자신":["korean"],"자연":["korean"],"자원":["korean"],"자율":["korean"],"자전거":["korean"],"자정":["korean"],"자존심":["korean"],"자판":["korean"],"작가":["korean"],"작년":["korean"],"작성":["korean"],"작업":["korean"],"작용":["korean"],"작은딸":["korean"],"작품":["korean"],"잔디":["korean"],"잔뜩":["korean"],"잔치":["korean"],"잘못":["korean"],"잠깐":["korean"],"잠수함":["korean"],"잠시":["korean"],"잠옷":["korean"],"잠자리":["korean"],"잡지":["korean"],"장관":["korean"],"장군":["korean"],"장기간":["korean"],"장래":["korean"],"장례":["korean"],"장르":["korean"],"장마":["korean"],"장면":["korean"],"장모":["korean"],"장미":["korean"],"장비":["korean"],"장사":["korean"],"장소":["korean"],"장식":["korean"],"장애인":["korean"],"장인":["korean"],"장점":["korean"],"장차":["korean"],"장학금":["korean"],"재능":["korean"],"재빨리":["korean"],"재산":["korean"],"재생":["korean"],"재작년":["korean"],"재정":["korean"],"재채기":["korean"],"재판":["korean"],"재학":["korean"],"재활용":["korean"],"저것":["korean"],"저고리":["korean"],"저곳":["korean"],"저녁":["korean"],"저런":["korean"],"저렇게":["korean"],"저번":["korean"],"저울":["korean"],"저절로":["korean"],"저축":["korean"],"적극":["korean"],"적당히":["korean"],"적성":["korean"],"적용":["korean"],"적응":["korean"],"전개":["korean"],"전공":["korean"],"전기":["korean"],"전달":["korean"],"전라도":["korean"],"전망":["korean"],"전문":["korean"],"전반":["korean"],"전부":["korean"],"전세":["korean"],"전시":["korean"],"전용":["korean"],"전자":["korean"],"전쟁":["korean"],"전주":["korean"],"전철":["korean"],"전체":["korean"],"전통":["korean"],"전혀":["korean"],"전후":["korean"],"절대":["korean"],"절망":["korean"],"절반":["korean"],"절약":["korean"],"절차":["korean"],"점검":["korean"],"점수":["korean"],"점심":["korean"],"점원":["korean"],"점점":["korean"],"점차":["korean"],"접근":["korean"],"접시":["korean"],"접촉":["korean"],"젓가락":["korean"],"정거장":["korean"],"정도":["korean"],"정류장":["korean"],"정리":["korean"],"정말":["korean"],"정면":["korean"],"정문":["korean"],"정반대":["korean"],"정보":["korean"],"정부":["korean"],"정비":["korean"],"정상":["korean"],"정성":["korean"],"정오":["korean"],"정원":["korean"],"정장":["korean"],"정지":["korean"],"정치":["korean"],"정확히":["korean"],"제공":["korean"],"제과점":["korean"],"제대로":["korean"],"제목":["korean"],"제발":["korean"],"제법":["korean"],"제삿날":["korean"],"제안":["korean"],"제일":["korean"],"제작":["korean"],"제주도":["korean"],"제출":["korean"],"제품":["korean"],"제한":["korean"],"조각":["korean"],"조건":["korean"],"조금":["korean"],"조깅":["korean"],"조명":["korean"],"조미료":["korean"],"조상":["korean"],"조선":["korean"],"조용히":["korean"],"조절":["korean"],"조정":["korean"],"조직":["korean"],"존댓말":["korean"],"존재":["korean"],"졸업":["korean"],"졸음":["korean"],"종교":["korean"],"종로":["korean"],"종류":["korean"],"종소리":["korean"],"종업원":["korean"],"종종":["korean"],"종합":["korean"],"좌석":["korean"],"죄인":["korean"],"주관적":["korean"],"주름":["korean"],"주말":["korean"],"주머니":["korean"],"주먹":["korean"],"주문":["korean"],"주민":["korean"],"주방":["korean"],"주변":["korean"],"주식":["korean"],"주인":["korean"],"주일":["korean"],"주장":["korean"],"주전자":["korean"],"주택":["korean"],"준비":["korean"],"줄거리":["korean"],"줄기":["korean"],"줄무늬":["korean"],"중간":["korean"],"중계방송":["korean"],"중국":["korean"],"중년":["korean"],"중단":["korean"],"중독":["korean"],"중반":["korean"],"중부":["korean"],"중세":["korean"],"중소기업":["korean"],"중순":["korean"],"중앙":["korean"],"중요":["korean"],"중학교":["korean"],"즉석":["korean"],"즉시":["korean"],"즐거움":["korean"],"증가":["korean"],"증거":["korean"],"증권":["korean"],"증상":["korean"],"증세":["korean"],"지각":["korean"],"지갑":["korean"],"지경":["korean"],"지극히":["korean"],"지금":["korean"],"지급":["korean"],"지능":["korean"],"지름길":["korean"],"지리산":["korean"],"지방":["korean"],"지붕":["korean"],"지식":["korean"],"지역":["korean"],"지우개":["korean"],"지원":["korean"],"지적":["korean"],"지점":["korean"],"지진":["korean"],"지출":["korean"],"직선":["korean"],"직업":["korean"],"직원":["korean"],"직장":["korean"],"진급":["korean"],"진동":["korean"],"진로":["korean"],"진료":["korean"],"진리":["korean"],"진짜":["korean"],"진찰":["korean"],"진출":["korean"],"진통":["korean"],"진행":["korean"],"질문":["korean"],"질병":["korean"],"질서":["korean"],"짐작":["korean"],"집단":["korean"],"집안":["korean"],"집중":["korean"],"짜증":["korean"],"찌꺼기":["korean"],"차남":["korean"],"차라리":["korean"],"차량":["korean"],"차림":["korean"],"차별":["korean"],"차선":["korean"],"차츰":["korean"],"착각":["korean"],"찬물":["korean"],"찬성":["korean"],"참가":["korean"],"참기름":["korean"],"참새":["korean"],"참석":["korean"],"참여":["korean"],"참외":["korean"],"참조":["korean"],"찻잔":["korean"],"창가":["korean"],"창고":["korean"],"창구":["korean"],"창문":["korean"],"창밖":["korean"],"창작":["korean"],"창조":["korean"],"채널":["korean"],"채점":["korean"],"책가방":["korean"],"책방":["korean"],"책상":["korean"],"책임":["korean"],"챔피언":["korean"],"처벌":["korean"],"처음":["korean"],"천국":["korean"],"천둥":["korean"],"천장":["korean"],"천재":["korean"],"천천히":["korean"],"철도":["korean"],"철저히":["korean"],"철학":["korean"],"첫날":["korean"],"첫째":["korean"],"청년":["korean"],"청바지":["korean"],"청소":["korean"],"청춘":["korean"],"체계":["korean"],"체력":["korean"],"체온":["korean"],"체육":["korean"],"체중":["korean"],"체험":["korean"],"초등학생":["korean"],"초반":["korean"],"초밥":["korean"],"초상화":["korean"],"초순":["korean"],"초여름":["korean"],"초원":["korean"],"초저녁":["korean"],"초점":["korean"],"초청":["korean"],"초콜릿":["korean"],"촛불":["korean"],"총각":["korean"],"총리":["korean"],"총장":["korean"],"촬영":["korean"],"최근":["korean"],"최상":["korean"],"최선":["korean"],"최신":["korean"],"최악":["korean"],"최종":["korean"],"추석":["korean"],"추억":["korean"],"추진":["korean"],"추천":["korean"],"추측":["korean"],"축구":["korean"],"축소":["korean"],"축제":["korean"],"축하":["korean"],"출근":["korean"],"출발":["korean"],"출산":["korean"],"출신":["korean"],"출연":["korean"],"출입":["korean"],"출장":["korean"],"출판":["korean"],"충격":["korean"],"충고":["korean"],"충돌":["korean"],"충분히":["korean"],"충청도":["korean"],"취업":["korean"],"취직":["korean"],"취향":["korean"],"치약":["korean"],"친구":["korean"],"친척":["korean"],"칠십":["korean"],"칠월":["korean"],"칠판":["korean"],"침대":["korean"],"침묵":["korean"],"침실":["korean"],"칫솔":["korean"],"칭찬":["korean"],"카메라":["korean"],"카운터":["korean"],"칼국수":["korean"],"캐릭터":["korean"],"캠퍼스":["korean"],"캠페인":["korean"],"커튼":["korean"],"컨디션":["korean"],"컬러":["korean"],"컴퓨터":["korean"],"코끼리":["korean"],"코미디":["korean"],"콘서트":["korean"],"콜라":["korean"],"콤플렉스":["korean"],"콩나물":["korean"],"쾌감":["korean"],"쿠데타":["korean"],"크림":["korean"],"큰길":["korean"],"큰딸":["korean"],"큰소리":["korean"],"큰아들":["korean"],"큰어머니":["korean"],"큰일":["korean"],"큰절":["korean"],"클래식":["korean"],"클럽":["korean"],"킬로":["korean"],"타입":["korean"],"타자기":["korean"],"탁구":["korean"],"탁자":["korean"],"탄생":["korean"],"태권도":["korean"],"태양":["korean"],"태풍":["korean"],"택시":["korean"],"탤런트":["korean"],"터널":["korean"],"터미널":["korean"],"테니스":["korean"],"테스트":["korean"],"테이블":["korean"],"텔레비전":["korean"],"토론":["korean"],"토마토":["korean"],"토요일":["korean"],"통계":["korean"],"통과":["korean"],"통로":["korean"],"통신":["korean"],"통역":["korean"],"통일":["korean"],"통장":["korean"],"통제":["korean"],"통증":["korean"],"통합":["korean"],"통화":["korean"],"퇴근":["korean"],"퇴원":["korean"],"퇴직금":["korean"],"튀김":["korean"],"트럭":["korean"],"특급":["korean"],"특별":["korean"],"특성":["korean"],"특수":["korean"],"특징":["korean"],"특히":["korean"],"튼튼히":["korean"],"티셔츠":["korean"],"파란색":["korean"],"파일":["korean"],"파출소":["korean"],"판결":["korean"],"판단":["korean"],"판매":["korean"],"판사":["korean"],"팔십":["korean"],"팔월":["korean"],"팝송":["korean"],"패션":["korean"],"팩스":["korean"],"팩시밀리":["korean"],"팬티":["korean"],"퍼센트":["korean"],"페인트":["korean"],"편견":["korean"],"편의":["korean"],"편지":["korean"],"편히":["korean"],"평가":["korean"],"평균":["korean"],"평생":["korean"],"평소":["korean"],"평양":["korean"],"평일":["korean"],"평화":["korean"],"포스터":["korean"],"포인트":["korean"],"포장":["korean"],"포함":["korean"],"표면":["korean"],"표정":["korean"],"표준":["korean"],"표현":["korean"],"품목":["korean"],"품질":["korean"],"풍경":["korean"],"풍속":["korean"],"풍습":["korean"],"프랑스":["korean"],"프린터":["korean"],"플라스틱":["korean"],"피곤":["korean"],"피망":["korean"],"피아노":["korean"],"필름":["korean"],"필수":["korean"],"필요":["korean"],"필자":["korean"],"필통":["korean"],"핑계":["korean"],"하느님":["korean"],"하늘":["korean"],"하드웨어":["korean"],"하룻밤":["korean"],"하반기":["korean"],"하숙집":["korean"],"하순":["korean"],"하여튼":["korean"],"하지만":["korean"],"하천":["korean"],"하품":["korean"],"하필":["korean"],"학과":["korean"],"학교":["korean"],"학급":["korean"],"학기":["korean"],"학년":["korean"],"학력":["korean"],"학번":["korean"],"학부모":["korean"],"학비":["korean"],"학생":["korean"],"학술":["korean"],"학습":["korean"],"학용품":["korean"],"학원":["korean"],"학위":["korean"],"학자":["korean"],"학점":["korean"],"한계":["korean"],"한글":["korean"],"한꺼번에":["korean"],"한낮":["korean"],"한눈":["korean"],"한동안":["korean"],"한때":["korean"],"한라산":["korean"],"한마디":["korean"],"한문":["korean"],"한번":["korean"],"한복":["korean"],"한식":["korean"],"한여름":["korean"],"한쪽":["korean"],"할머니":["korean"],"할아버지":["korean"],"할인":["korean"],"함께":["korean"],"함부로":["korean"],"합격":["korean"],"합리적":["korean"],"항공":["korean"],"항구":["korean"],"항상":["korean"],"항의":["korean"],"해결":["korean"],"해군":["korean"],"해답":["korean"],"해당":["korean"],"해물":["korean"],"해석":["korean"],"해설":["korean"],"해수욕장":["korean"],"해안":["korean"],"핵심":["korean"],"핸드백":["korean"],"햄버거":["korean"],"햇볕":["korean"],"햇살":["korean"],"행동":["korean"],"행복":["korean"],"행사":["korean"],"행운":["korean"],"행위":["korean"],"향기":["korean"],"향상":["korean"],"향수":["korean"],"허락":["korean"],"허용":["korean"],"헬기":["korean"],"현관":["korean"],"현금":["korean"],"현대":["korean"],"현상":["korean"],"현실":["korean"],"현장":["korean"],"현재":["korean"],"현지":["korean"],"혈액":["korean"],"협력":["korean"],"형부":["korean"],"형사":["korean"],"형수":["korean"],"형식":["korean"],"형제":["korean"],"형태":["korean"],"형편":["korean"],"혜택":["korean"],"호기심":["korean"],"호남":["korean"],"호랑이":["korean"],"호박":["korean"],"호텔":["korean"],"호흡":["korean"],"혹시":["korean"],"홀로":["korean"],"홈페이지":["korean"],"홍보":["korean"],"홍수":["korean"],"홍차":["korean"],"화면":["korean"],"화분":["korean"],"화살":["korean"],"화요일":["korean"],"화장":["korean"],"화학":["korean"],"확보":["korean"],"확인":["korean"],"확장":["korean"],"확정":["korean"],"환갑":["korean"],"환경":["korean"],"환영":["korean"],"환율":["korean"],"환자":["korean"],"활기":["korean"],"활동":["korean"],"활발히":["korean"],"활용":["korean"],"활짝":["korean"],"회견":["korean"],"회관":["korean"],"회복":["korean"],"회색":["korean"],"회원":["korean"],"회장":["korean"],"회전":["korean"],"횟수":["korean"],"횡단보도":["korean"],"효율적":["korean"],"후반":["korean"],"후춧가루":["korean"],"훈련":["korean"],"훨씬":["korean"],"휴식":["korean"],"휴일":["korean"],"흉내":["korean"],"흐름":["korean"],"흑백":["korean"],"흑인":["korean"],"흔적":["korean"],"흔히":["korean"],"흥미":["korean"],"흥분":["korean"],"희곡":["korean"],"희망":["korean"],"희생":["korean"],"흰색":["korean"],"힘껏":["korean"],"abacate":["portuguese"],"abaixo":["portuguese"],"abalar":["portuguese"],"abater":["portuguese"],"abduzir":["portuguese"],"abelha":["portuguese"],"aberto":["portuguese"],"abismo":["portuguese"],"abotoar":["portuguese"],"abranger":["portuguese"],"abreviar":["portuguese"],"abrigar":["portuguese"],"abrupto":["portuguese"],"absinto":["portuguese"],"absoluto":["portuguese"],"absurdo":["portuguese"],"abutre":["portuguese"],"acabado":["portuguese"],"acalmar":["portuguese"],"acampar":["portuguese"],"acanhar":["portuguese"],"acaso":["portuguese"],"aceitar":["portuguese"],"acelerar":["portuguese"],"acenar":["portuguese"],"acervo":["portuguese"],"acessar":["portuguese"],"acetona":["portuguese"],"achatar":["portuguese"],"acidez":["portuguese"],"acima":["portuguese"],"acionado":["portuguese"],"acirrar":["portuguese"],"aclamar":["portuguese"],"aclive":["portuguese"],"acolhida":["portuguese"],"acomodar":["portuguese"],"acoplar":["portuguese"],"acordar":["portuguese"],"acumular":["portuguese"],"acusador":["portuguese"],"adaptar":["portuguese"],"adega":["portuguese"],"adentro":["portuguese"],"adepto":["portuguese"],"adequar":["portuguese"],"aderente":["portuguese"],"adesivo":["portuguese"],"adeus":["portuguese"],"adiante":["portuguese"],"aditivo":["portuguese"],"adjetivo":["portuguese"],"adjunto":["portuguese"],"admirar":["portuguese"],"adorar":["portuguese"],"adquirir":["portuguese"],"adubo":["portuguese"],"adverso":["portuguese"],"advogado":["portuguese"],"aeronave":["portuguese"],"afastar":["portuguese"],"aferir":["portuguese"],"afetivo":["portuguese"],"afinador":["portuguese"],"afivelar":["portuguese"],"aflito":["portuguese"],"afluente":["portuguese"],"afrontar":["portuguese"],"agachar":["portuguese"],"agarrar":["portuguese"],"agasalho":["portuguese"],"agenciar":["portuguese"],"agilizar":["portuguese"],"agiota":["portuguese"],"agitado":["portuguese"],"agora":["portuguese"],"agradar":["portuguese"],"agreste":["portuguese"],"agrupar":["portuguese"],"aguardar":["portuguese"],"agulha":["portuguese"],"ajoelhar":["portuguese"],"ajudar":["portuguese"],"ajustar":["portuguese"],"alameda":["portuguese"],"alarme":["portuguese"],"alastrar":["portuguese"],"alavanca":["portuguese"],"albergue":["portuguese"],"albino":["portuguese"],"alcatra":["portuguese"],"aldeia":["portuguese"],"alecrim":["portuguese"],"alegria":["portuguese"],"alertar":["portuguese"],"alface":["portuguese"],"alfinete":["portuguese"],"algum":["portuguese"],"alheio":["portuguese"],"aliar":["portuguese"],"alicate":["portuguese"],"alienar":["portuguese"],"alinhar":["portuguese"],"aliviar":["portuguese"],"almofada":["portuguese"],"alocar":["portuguese"],"alpiste":["portuguese"],"alterar":["portuguese"],"altitude":["portuguese"],"alucinar":["portuguese"],"alugar":["portuguese"],"aluno":["portuguese"],"alusivo":["portuguese"],"alvo":["portuguese"],"amaciar":["portuguese"],"amador":["portuguese"],"amarelo":["portuguese"],"amassar":["portuguese"],"ambas":["portuguese"],"ambiente":["portuguese"],"ameixa":["portuguese"],"amenizar":["portuguese"],"amido":["portuguese"],"amistoso":["portuguese"],"amizade":["portuguese"],"amolador":["portuguese"],"amontoar":["portuguese"],"amoroso":["portuguese"],"amostra":["portuguese"],"amparar":["portuguese"],"ampliar":["portuguese"],"ampola":["portuguese"],"anagrama":["portuguese"],"analisar":["portuguese"],"anarquia":["portuguese"],"anatomia":["portuguese"],"andaime":["portuguese"],"anel":["portuguese"],"anexo":["portuguese"],"angular":["portuguese"],"animar":["portuguese"],"anjo":["portuguese"],"anomalia":["portuguese"],"anotado":["portuguese"],"ansioso":["portuguese"],"anterior":["portuguese"],"anuidade":["portuguese"],"anunciar":["portuguese"],"anzol":["portuguese"],"apagador":["portuguese"],"apalpar":["portuguese"],"apanhado":["portuguese"],"apego":["portuguese"],"apelido":["portuguese"],"apertada":["portuguese"],"apesar":["portuguese"],"apetite":["portuguese"],"apito":["portuguese"],"aplauso":["portuguese"],"aplicada":["portuguese"],"apoio":["portuguese"],"apontar":["portuguese"],"aposta":["portuguese"],"aprendiz":["portuguese"],"aprovar":["portuguese"],"aquecer":["portuguese"],"arame":["portuguese"],"aranha":["portuguese"],"arara":["portuguese"],"arcada":["portuguese"],"ardente":["portuguese"],"areia":["portuguese"],"arejar":["portuguese"],"arenito":["portuguese"],"aresta":["portuguese"],"argiloso":["portuguese"],"argola":["portuguese"],"arma":["portuguese"],"arquivo":["portuguese"],"arraial":["portuguese"],"arrebate":["portuguese"],"arriscar":["portuguese"],"arroba":["portuguese"],"arrumar":["portuguese"],"arsenal":["portuguese"],"arterial":["portuguese"],"artigo":["portuguese"],"arvoredo":["portuguese"],"asfaltar":["portuguese"],"asilado":["portuguese"],"aspirar":["portuguese"],"assador":["portuguese"],"assinar":["portuguese"],"assoalho":["portuguese"],"assunto":["portuguese"],"astral":["portuguese"],"atacado":["portuguese"],"atadura":["portuguese"],"atalho":["portuguese"],"atarefar":["portuguese"],"atear":["portuguese"],"atender":["portuguese"],"aterro":["portuguese"],"ateu":["portuguese"],"atingir":["portuguese"],"atirador":["portuguese"],"ativo":["portuguese"],"atoleiro":["portuguese"],"atracar":["portuguese"],"atrevido":["portuguese"],"atriz":["portuguese"],"atual":["portuguese"],"atum":["portuguese"],"auditor":["portuguese"],"aumentar":["portuguese"],"aura":["portuguese"],"aurora":["portuguese"],"autismo":["portuguese"],"autoria":["portuguese"],"autuar":["portuguese"],"avaliar":["portuguese"],"avante":["portuguese"],"avaria":["portuguese"],"avental":["portuguese"],"avesso":["portuguese"],"aviador":["portuguese"],"avisar":["portuguese"],"avulso":["portuguese"],"axila":["portuguese"],"azarar":["portuguese"],"azedo":["portuguese"],"azeite":["portuguese"],"azulejo":["portuguese"],"babar":["portuguese"],"babosa":["portuguese"],"bacalhau":["portuguese"],"bacharel":["portuguese"],"bacia":["portuguese"],"bagagem":["portuguese"],"baiano":["portuguese"],"bailar":["portuguese"],"baioneta":["portuguese"],"bairro":["portuguese"],"baixista":["portuguese"],"bajular":["portuguese"],"baleia":["portuguese"],"baliza":["portuguese"],"balsa":["portuguese"],"banal":["portuguese"],"bandeira":["portuguese"],"banho":["portuguese"],"banir":["portuguese"],"banquete":["portuguese"],"barato":["portuguese"],"barbado":["portuguese"],"baronesa":["portuguese"],"barraca":["portuguese"],"barulho":["portuguese"],"baseado":["portuguese"],"bastante":["portuguese"],"batata":["portuguese"],"batedor":["portuguese"],"batida":["portuguese"],"batom":["portuguese"],"batucar":["portuguese"],"baunilha":["portuguese"],"beber":["portuguese"],"beijo":["portuguese"],"beirada":["portuguese"],"beisebol":["portuguese"],"beldade":["portuguese"],"beleza":["portuguese"],"belga":["portuguese"],"beliscar":["portuguese"],"bendito":["portuguese"],"bengala":["portuguese"],"benzer":["portuguese","turkish"],"berimbau":["portuguese"],"berlinda":["portuguese"],"berro":["portuguese"],"besouro":["portuguese"],"bexiga":["portuguese"],"bezerro":["portuguese"],"bico":["portuguese"],"bicudo":["portuguese"],"bienal":["portuguese"],"bifocal":["portuguese"],"bifurcar":["portuguese"],"bigorna":["portuguese"],"bilhete":["portuguese"],"bimestre":["portuguese"],"bimotor":["portuguese"],"biologia":["portuguese"],"biombo":["portuguese"],"biosfera":["portuguese"],"bipolar":["portuguese"],"birrento":["portuguese"],"biscoito":["portuguese"],"bisneto":["portuguese"],"bispo":["portuguese"],"bissexto":["portuguese"],"bitola":["portuguese"],"bizarro":["portuguese"],"blindado":["portuguese"],"bloco":["portuguese"],"bloquear":["portuguese"],"boato":["portuguese"],"bobagem":["portuguese"],"bocado":["portuguese"],"bocejo":["portuguese"],"bochecha":["portuguese"],"boicotar":["portuguese"],"bolada":["portuguese"],"boletim":["portuguese"],"bolha":["portuguese"],"bolo":["portuguese"],"bombeiro":["portuguese"],"bonde":["portuguese"],"boneco":["portuguese"],"bonita":["portuguese"],"borbulha":["portuguese"],"borda":["portuguese"],"boreal":["portuguese"],"borracha":["portuguese"],"bovino":["portuguese"],"boxeador":["portuguese"],"branco":["portuguese"],"brasa":["portuguese"],"braveza":["portuguese"],"breu":["portuguese"],"briga":["portuguese"],"brilho":["portuguese"],"brincar":["portuguese"],"broa":["portuguese"],"brochura":["portuguese"],"bronzear":["portuguese"],"broto":["portuguese"],"bruxo":["portuguese"],"bucha":["portuguese"],"budismo":["portuguese"],"bufar":["portuguese"],"bule":["portuguese"],"buraco":["portuguese"],"busca":["portuguese"],"busto":["portuguese"],"buzina":["portuguese"],"cabana":["portuguese"],"cabelo":["portuguese"],"cabide":["portuguese"],"cabo":["portuguese"],"cabrito":["portuguese"],"cacau":["portuguese"],"cacetada":["portuguese"],"cachorro":["portuguese"],"cacique":["portuguese"],"cadastro":["portuguese"],"cadeado":["portuguese"],"cafezal":["portuguese"],"caiaque":["portuguese"],"caipira":["portuguese"],"caixote":["portuguese"],"cajado":["portuguese"],"caju":["portuguese"],"calafrio":["portuguese"],"calcular":["portuguese"],"caldeira":["portuguese"],"calibrar":["portuguese"],"calmante":["portuguese"],"calota":["portuguese"],"camada":["portuguese"],"cambista":["portuguese"],"camisa":["portuguese"],"camomila":["portuguese"],"campanha":["portuguese"],"camuflar":["portuguese"],"canavial":["portuguese"],"cancelar":["portuguese"],"caneta":["portuguese"],"canguru":["portuguese"],"canhoto":["portuguese"],"canivete":["portuguese"],"canoa":["portuguese"],"cansado":["portuguese"],"cantar":["portuguese"],"canudo":["portuguese"],"capacho":["portuguese"],"capela":["portuguese"],"capinar":["portuguese"],"capotar":["portuguese"],"capricho":["portuguese"],"captador":["portuguese"],"capuz":["portuguese"],"caracol":["portuguese"],"carbono":["portuguese"],"cardeal":["portuguese"],"careca":["portuguese"],"carimbar":["portuguese"],"carneiro":["portuguese"],"carpete":["portuguese"],"carreira":["portuguese"],"cartaz":["portuguese"],"carvalho":["portuguese"],"casaco":["portuguese"],"casca":["portuguese"],"casebre":["portuguese"],"castelo":["portuguese"],"casulo":["portuguese"],"catarata":["portuguese"],"cativar":["portuguese"],"caule":["portuguese"],"causador":["portuguese"],"cautelar":["portuguese"],"cavalo":["portuguese"],"caverna":["portuguese"],"cebola":["portuguese"],"cedilha":["portuguese"],"cegonha":["portuguese"],"celebrar":["portuguese"],"celular":["portuguese"],"cenoura":["portuguese"],"censo":["portuguese"],"centeio":["portuguese"],"cercar":["portuguese"],"cerrado":["portuguese"],"certeiro":["portuguese"],"cerveja":["portuguese"],"cetim":["portuguese"],"cevada":["portuguese"],"chacota":["portuguese"],"chaleira":["portuguese"],"chamado":["portuguese"],"chapada":["portuguese"],"charme":["portuguese"],"chatice":["portuguese"],"chave":["portuguese"],"chefe":["portuguese"],"chegada":["portuguese"],"cheiro":["portuguese"],"cheque":["portuguese"],"chicote":["portuguese"],"chifre":["portuguese"],"chinelo":["portuguese"],"chocalho":["portuguese"],"chover":["portuguese"],"chumbo":["portuguese"],"chutar":["portuguese"],"chuva":["portuguese"],"cicatriz":["portuguese"],"ciclone":["portuguese"],"cidade":["portuguese"],"cidreira":["portuguese"],"ciente":["portuguese"],"cigana":["portuguese"],"cimento":["portuguese"],"cinto":["portuguese"],"cinza":["portuguese"],"ciranda":["portuguese"],"circuito":["portuguese"],"cirurgia":["portuguese"],"citar":["portuguese"],"clareza":["portuguese"],"clero":["portuguese"],"clicar":["portuguese"],"clone":["portuguese"],"clube":["portuguese"],"coado":["portuguese"],"coagir":["portuguese"],"cobaia":["portuguese"],"cobertor":["portuguese"],"cobrar":["portuguese"],"cocada":["portuguese"],"coelho":["portuguese"],"coentro":["portuguese"],"coeso":["portuguese"],"cogumelo":["portuguese"],"coibir":["portuguese"],"coifa":["portuguese"],"coiote":["portuguese"],"colar":["portuguese"],"coleira":["portuguese"],"colher":["portuguese"],"colidir":["portuguese"],"colmeia":["portuguese"],"colono":["portuguese"],"coluna":["portuguese"],"comando":["portuguese"],"combinar":["portuguese"],"comentar":["portuguese"],"comitiva":["portuguese"],"comover":["portuguese"],"complexo":["portuguese"],"comum":["portuguese"],"concha":["portuguese"],"condor":["portuguese"],"conectar":["portuguese"],"confuso":["portuguese"],"congelar":["portuguese"],"conhecer":["portuguese"],"conjugar":["portuguese"],"consumir":["portuguese"],"contrato":["portuguese"],"convite":["portuguese"],"cooperar":["portuguese"],"copeiro":["portuguese"],"copiador":["portuguese"],"copo":["portuguese"],"coquetel":["portuguese"],"coragem":["portuguese"],"cordial":["portuguese"],"corneta":["portuguese"],"coronha":["portuguese"],"corporal":["portuguese"],"correio":["portuguese"],"cortejo":["portuguese"],"coruja":["portuguese"],"corvo":["portuguese"],"cosseno":["portuguese"],"costela":["portuguese"],"cotonete":["portuguese"],"couro":["portuguese"],"couve":["portuguese"],"covil":["portuguese"],"cozinha":["portuguese"],"cratera":["portuguese"],"cravo":["portuguese"],"creche":["portuguese"],"credor":["portuguese"],"creme":["portuguese"],"crer":["portuguese"],"crespo":["portuguese"],"criada":["portuguese"],"criminal":["portuguese"],"crioulo":["portuguese"],"crise":["portuguese"],"criticar":["portuguese"],"crosta":["portuguese"],"crua":["portuguese"],"cruzeiro":["portuguese"],"cubano":["portuguese"],"cueca":["portuguese"],"cuidado":["portuguese"],"cujo":["portuguese"],"culatra":["portuguese"],"culminar":["portuguese"],"culpar":["portuguese"],"cultura":["portuguese"],"cumprir":["portuguese"],"cunhado":["portuguese"],"cupido":["portuguese"],"curativo":["portuguese"],"curral":["portuguese"],"cursar":["portuguese"],"curto":["portuguese"],"cuspir":["portuguese"],"custear":["portuguese"],"cutelo":["portuguese"],"damasco":["portuguese"],"datar":["portuguese"],"debater":["portuguese"],"debitar":["portuguese"],"deboche":["portuguese"],"debulhar":["portuguese"],"decalque":["portuguese"],"decimal":["portuguese"],"declive":["portuguese"],"decote":["portuguese"],"decretar":["portuguese"],"dedal":["portuguese"],"dedicado":["portuguese"],"deduzir":["portuguese"],"defesa":["portuguese"],"defumar":["portuguese"],"degelo":["portuguese"],"degrau":["portuguese"],"degustar":["portuguese"],"deitado":["portuguese"],"deixar":["portuguese"],"delator":["portuguese"],"delegado":["portuguese"],"delinear":["portuguese"],"delonga":["portuguese"],"demanda":["portuguese"],"demitir":["portuguese"],"demolido":["portuguese"],"dentista":["portuguese"],"depenado":["portuguese"],"depilar":["portuguese"],"depois":["portuguese"],"depressa":["portuguese"],"depurar":["portuguese"],"deriva":["portuguese"],"derramar":["portuguese"],"desafio":["portuguese"],"desbotar":["portuguese"],"descanso":["portuguese"],"desenho":["portuguese"],"desfiado":["portuguese"],"desgaste":["portuguese"],"desigual":["portuguese"],"deslize":["portuguese"],"desmamar":["portuguese"],"desova":["portuguese"],"despesa":["portuguese"],"destaque":["portuguese"],"desviar":["portuguese"],"detalhar":["portuguese"],"detentor":["portuguese"],"detonar":["portuguese"],"detrito":["portuguese"],"deusa":["portuguese"],"dever":["portuguese"],"devido":["portuguese"],"devotado":["portuguese"],"dezena":["portuguese"],"diagrama":["portuguese"],"dialeto":["portuguese"],"didata":["portuguese"],"difuso":["portuguese"],"digitar":["portuguese"],"dilatado":["portuguese"],"diluente":["portuguese"],"diminuir":["portuguese"],"dinastia":["portuguese"],"dinheiro":["portuguese"],"diocese":["portuguese"],"direto":["portuguese"],"discreta":["portuguese"],"disfarce":["portuguese"],"disparo":["portuguese"],"disquete":["portuguese"],"dissipar":["portuguese"],"distante":["portuguese"],"ditador":["portuguese"],"diurno":["portuguese"],"diverso":["portuguese"],"divisor":["portuguese"],"divulgar":["portuguese"],"dizer":["portuguese"],"dobrador":["portuguese"],"dolorido":["portuguese"],"domador":["portuguese"],"dominado":["portuguese"],"donativo":["portuguese"],"donzela":["portuguese"],"dormente":["portuguese"],"dorsal":["portuguese"],"dosagem":["portuguese"],"dourado":["portuguese"],"doutor":["portuguese"],"drenagem":["portuguese"],"drible":["portuguese"],"drogaria":["portuguese"],"duelar":["portuguese"],"duende":["portuguese"],"dueto":["portuguese"],"duplo":["portuguese"],"duquesa":["portuguese"],"durante":["portuguese"],"duvidoso":["portuguese"],"eclodir":["portuguese"],"ecoar":["portuguese"],"ecologia":["portuguese"],"edificar":["portuguese"],"edital":["portuguese"],"educado":["portuguese"],"efeito":["portuguese"],"efetivar":["portuguese"],"ejetar":["portuguese"],"elaborar":["portuguese"],"eleger":["portuguese"],"eleitor":["portuguese"],"elenco":["portuguese"],"elevador":["portuguese"],"eliminar":["portuguese"],"elogiar":["portuguese"],"embargo":["portuguese"],"embolado":["portuguese"],"embrulho":["portuguese"],"embutido":["portuguese"],"emenda":["portuguese"],"emergir":["portuguese"],"emissor":["portuguese"],"empatia":["portuguese"],"empenho":["portuguese"],"empinado":["portuguese"],"empolgar":["portuguese"],"emprego":["portuguese"],"empurrar":["portuguese"],"emulador":["portuguese"],"encaixe":["portuguese"],"encenado":["portuguese"],"enchente":["portuguese"],"encontro":["portuguese"],"endeusar":["portuguese"],"endossar":["portuguese"],"enfaixar":["portuguese"],"enfeite":["portuguese"],"enfim":["portuguese"],"engajado":["portuguese"],"engenho":["portuguese"],"englobar":["portuguese"],"engomado":["portuguese"],"engraxar":["portuguese"],"enguia":["portuguese"],"enjoar":["portuguese"],"enlatar":["portuguese"],"enquanto":["portuguese"],"enraizar":["portuguese"],"enrolado":["portuguese"],"enrugar":["portuguese"],"ensaio":["portuguese"],"enseada":["portuguese"],"ensino":["portuguese"],"ensopado":["portuguese"],"entanto":["portuguese"],"enteado":["portuguese"],"entidade":["portuguese"],"entortar":["portuguese"],"entrada":["portuguese"],"entulho":["portuguese"],"envergar":["portuguese"],"enviado":["portuguese"],"envolver":["portuguese"],"enxame":["portuguese"],"enxerto":["portuguese"],"enxofre":["portuguese"],"enxuto":["portuguese"],"epiderme":["portuguese"],"equipar":["portuguese"],"ereto":["portuguese"],"erguido":["portuguese"],"errata":["portuguese"],"erva":["portuguese"],"ervilha":["portuguese"],"esbanjar":["portuguese"],"esbelto":["portuguese"],"escama":["portuguese"],"escola":["portuguese"],"escrita":["portuguese"],"escuta":["portuguese"],"esfinge":["portuguese"],"esfolar":["portuguese"],"esfregar":["portuguese"],"esfumado":["portuguese"],"esgrima":["portuguese"],"esmalte":["portuguese"],"espanto":["portuguese"],"espelho":["portuguese"],"espiga":["portuguese"],"esponja":["portuguese"],"espreita":["portuguese"],"espumar":["portuguese"],"esquerda":["portuguese"],"estaca":["portuguese"],"esteira":["portuguese"],"esticar":["portuguese"],"estofado":["portuguese"],"estrela":["portuguese"],"estudo":["portuguese"],"esvaziar":["portuguese"],"etanol":["portuguese"],"etiqueta":["portuguese"],"euforia":["portuguese"],"europeu":["portuguese"],"evacuar":["portuguese"],"evaporar":["portuguese"],"evasivo":["portuguese"],"eventual":["portuguese"],"evidente":["portuguese"],"evoluir":["portuguese"],"exagero":["portuguese"],"exalar":["portuguese"],"examinar":["portuguese"],"exato":["portuguese"],"exausto":["portuguese"],"excesso":["portuguese"],"excitar":["portuguese"],"exclamar":["portuguese"],"executar":["portuguese"],"exemplo":["portuguese"],"exibir":["portuguese"],"exigente":["portuguese"],"exonerar":["portuguese"],"expandir":["portuguese"],"expelir":["portuguese"],"expirar":["portuguese"],"explanar":["portuguese"],"exposto":["portuguese"],"expresso":["portuguese"],"expulsar":["portuguese"],"externo":["portuguese"],"extinto":["portuguese"],"extrato":["portuguese"],"fabricar":["portuguese"],"fabuloso":["portuguese"],"faceta":["portuguese"],"facial":["portuguese"],"fada":["portuguese"],"fadiga":["portuguese"],"faixa":["portuguese"],"falar":["portuguese"],"falta":["portuguese"],"familiar":["portuguese"],"fandango":["portuguese"],"fanfarra":["portuguese"],"fantoche":["portuguese"],"fardado":["portuguese"],"farelo":["portuguese"],"farinha":["portuguese"],"farofa":["portuguese"],"farpa":["portuguese"],"fartura":["portuguese"],"fatia":["portuguese"],"fator":["portuguese"],"favorita":["portuguese"],"faxina":["portuguese"],"fazenda":["portuguese"],"fechado":["portuguese"],"feijoada":["portuguese"],"feirante":["portuguese"],"felino":["portuguese"],"feminino":["portuguese"],"fenda":["portuguese"],"feno":["portuguese"],"fera":["portuguese"],"feriado":["portuguese"],"ferrugem":["portuguese"],"ferver":["portuguese"],"festejar":["portuguese"],"fetal":["portuguese"],"feudal":["portuguese"],"fiapo":["portuguese"],"fibrose":["portuguese"],"ficar":["portuguese"],"ficheiro":["portuguese"],"figurado":["portuguese"],"fileira":["portuguese"],"filho":["portuguese"],"filme":["portuguese"],"filtrar":["portuguese"],"firmeza":["portuguese"],"fisgada":["portuguese"],"fissura":["portuguese"],"fita":["portuguese"],"fivela":["portuguese"],"fixador":["portuguese"],"fixo":["portuguese"],"flacidez":["portuguese"],"flamingo":["portuguese"],"flanela":["portuguese"],"flechada":["portuguese"],"flora":["portuguese"],"flutuar":["portuguese"],"fluxo":["portuguese"],"focal":["portuguese"],"focinho":["portuguese"],"fofocar":["portuguese"],"fogo":["portuguese"],"foguete":["portuguese"],"foice":["portuguese"],"folgado":["portuguese"],"folheto":["portuguese"],"forjar":["portuguese"],"formiga":["portuguese"],"forno":["portuguese"],"forte":["portuguese"],"fosco":["portuguese"],"fossa":["portuguese"],"fragata":["portuguese"],"fralda":["portuguese"],"frango":["portuguese"],"frasco":["portuguese"],"fraterno":["portuguese"],"freira":["portuguese"],"frente":["portuguese"],"fretar":["portuguese"],"frieza":["portuguese"],"friso":["portuguese"],"fritura":["portuguese"],"fronha":["portuguese"],"frustrar":["portuguese"],"fruteira":["portuguese"],"fugir":["portuguese"],"fulano":["portuguese"],"fuligem":["portuguese"],"fundar":["portuguese"],"fungo":["portuguese"],"funil":["portuguese"],"furador":["portuguese"],"furioso":["portuguese"],"futebol":["portuguese"],"gabarito":["portuguese"],"gabinete":["portuguese"],"gado":["portuguese"],"gaiato":["portuguese"],"gaiola":["portuguese"],"gaivota":["portuguese"],"galega":["portuguese"],"galho":["portuguese"],"galinha":["portuguese"],"galocha":["portuguese"],"ganhar":["portuguese"],"garagem":["portuguese"],"garfo":["portuguese"],"gargalo":["portuguese"],"garimpo":["portuguese"],"garoupa":["portuguese"],"garrafa":["portuguese"],"gasoduto":["portuguese"],"gasto":["portuguese"],"gata":["portuguese"],"gatilho":["portuguese"],"gaveta":["portuguese"],"gazela":["portuguese"],"gelado":["portuguese"],"geleia":["portuguese"],"gelo":["portuguese"],"gemada":["portuguese"],"gemer":["portuguese"],"gemido":["portuguese"],"generoso":["portuguese"],"gengiva":["portuguese"],"genial":["portuguese"],"genoma":["portuguese"],"genro":["portuguese"],"geologia":["portuguese"],"gerador":["portuguese"],"germinar":["portuguese"],"gesso":["portuguese"],"gestor":["portuguese"],"ginasta":["portuguese"],"gincana":["portuguese"],"gingado":["portuguese"],"girafa":["portuguese"],"girino":["portuguese"],"glacial":["portuguese"],"glicose":["portuguese"],"global":["portuguese"],"glorioso":["portuguese"],"goela":["portuguese"],"goiaba":["portuguese"],"golfe":["portuguese"],"golpear":["portuguese"],"gordura":["portuguese"],"gorjeta":["portuguese"],"gorro":["portuguese"],"gostoso":["portuguese"],"goteira":["portuguese"],"governar":["portuguese"],"gracejo":["portuguese"],"gradual":["portuguese"],"grafite":["portuguese"],"gralha":["portuguese"],"grampo":["portuguese"],"granada":["portuguese"],"gratuito":["portuguese"],"graveto":["portuguese"],"graxa":["portuguese"],"grego":["portuguese"],"grelhar":["portuguese"],"greve":["portuguese"],"grilo":["portuguese"],"grisalho":["portuguese"],"gritaria":["portuguese"],"grosso":["portuguese"],"grotesco":["portuguese"],"grudado":["portuguese"],"grunhido":["portuguese"],"gruta":["portuguese"],"guache":["portuguese"],"guarani":["portuguese"],"guaxinim":["portuguese"],"guerrear":["portuguese"],"guiar":["portuguese"],"guincho":["portuguese"],"guisado":["portuguese"],"gula":["portuguese"],"guloso":["portuguese"],"guru":["portuguese"],"habitar":["portuguese"],"harmonia":["portuguese"],"haste":["portuguese"],"haver":["portuguese"],"hectare":["portuguese"],"herdar":["portuguese"],"heresia":["portuguese"],"hesitar":["portuguese"],"hiato":["portuguese"],"hibernar":["portuguese"],"hidratar":["portuguese"],"hiena":["portuguese"],"hino":["portuguese"],"hipismo":["portuguese"],"hipnose":["portuguese"],"hipoteca":["portuguese"],"hoje":["portuguese"],"holofote":["portuguese"],"homem":["portuguese"],"honesto":["portuguese"],"honrado":["portuguese"],"hormonal":["portuguese"],"hospedar":["portuguese"],"humorado":["portuguese"],"iate":["portuguese"],"ideia":["portuguese"],"idoso":["portuguese"],"ignorado":["portuguese"],"igreja":["portuguese"],"iguana":["portuguese"],"ileso":["portuguese"],"ilha":["portuguese"],"iludido":["portuguese"],"iluminar":["portuguese"],"ilustrar":["portuguese"],"imagem":["portuguese"],"imediato":["portuguese"],"imenso":["portuguese"],"imersivo":["portuguese"],"iminente":["portuguese"],"imitador":["portuguese"],"imortal":["portuguese"],"impacto":["portuguese"],"impedir":["portuguese"],"implante":["portuguese"],"impor":["portuguese"],"imprensa":["portuguese"],"impune":["portuguese"],"imunizar":["portuguese"],"inalador":["portuguese"],"inapto":["portuguese"],"inativo":["portuguese"],"incenso":["portuguese"],"inchar":["portuguese"],"incidir":["portuguese"],"incluir":["portuguese"],"incolor":["portuguese"],"indeciso":["portuguese"],"indireto":["portuguese"],"indutor":["portuguese"],"ineficaz":["portuguese"],"inerente":["portuguese"],"infantil":["portuguese"],"infestar":["portuguese"],"infinito":["portuguese"],"inflamar":["portuguese"],"informal":["portuguese"],"infrator":["portuguese"],"ingerir":["portuguese"],"inibido":["portuguese"],"inicial":["portuguese"],"inimigo":["portuguese"],"injetar":["portuguese"],"inocente":["portuguese"],"inodoro":["portuguese"],"inovador":["portuguese"],"inox":["portuguese"],"inquieto":["portuguese"],"inscrito":["portuguese"],"inseto":["portuguese"],"insistir":["portuguese"],"inspetor":["portuguese"],"instalar":["portuguese"],"insulto":["portuguese"],"intacto":["portuguese"],"integral":["portuguese"],"intimar":["portuguese"],"intocado":["portuguese"],"intriga":["portuguese"],"invasor":["portuguese"],"inverno":["portuguese"],"invicto":["portuguese"],"invocar":["portuguese"],"iogurte":["portuguese"],"iraniano":["portuguese"],"ironizar":["portuguese"],"irreal":["portuguese"],"irritado":["portuguese"],"isca":["portuguese"],"isento":["portuguese"],"isolado":["portuguese"],"isqueiro":["portuguese"],"italiano":["portuguese"],"janeiro":["portuguese"],"jangada":["portuguese"],"janta":["portuguese"],"jararaca":["portuguese"],"jardim":["portuguese"],"jarro":["portuguese"],"jasmim":["portuguese"],"jato":["portuguese"],"javali":["portuguese"],"jazida":["portuguese"],"jejum":["portuguese"],"joaninha":["portuguese"],"joelhada":["portuguese"],"jogador":["portuguese"],"joia":["portuguese"],"jornal":["portuguese"],"jorrar":["portuguese"],"jovem":["portuguese"],"juba":["portuguese"],"judeu":["portuguese"],"judoca":["portuguese"],"juiz":["portuguese"],"julgador":["portuguese"],"julho":["portuguese"],"jurado":["portuguese"],"jurista":["portuguese"],"juro":["portuguese"],"justa":["portuguese"],"labareda":["portuguese"],"laboral":["portuguese"],"lacre":["portuguese"],"lactante":["portuguese"],"ladrilho":["portuguese"],"lagarta":["portuguese"],"lagoa":["portuguese"],"laje":["portuguese"],"lamber":["portuguese"],"lamentar":["portuguese"],"laminar":["portuguese"],"lampejo":["portuguese"],"lanche":["portuguese"],"lapidar":["portuguese"],"lapso":["portuguese"],"laranja":["portuguese"],"lareira":["portuguese"],"largura":["portuguese"],"lasanha":["portuguese"],"lastro":["portuguese"],"lateral":["portuguese"],"latido":["portuguese"],"lavanda":["portuguese"],"lavoura":["portuguese"],"lavrador":["portuguese"],"laxante":["portuguese"],"lazer":["portuguese"],"lealdade":["portuguese"],"lebre":["portuguese"],"legado":["portuguese"],"legendar":["portuguese"],"legista":["portuguese"],"leigo":["portuguese"],"leiloar":["portuguese"],"leitura":["portuguese"],"lembrete":["portuguese"],"leme":["portuguese"],"lenhador":["portuguese"],"lentilha":["portuguese"],"leoa":["portuguese"],"lesma":["portuguese"],"leste":["portuguese"],"letivo":["portuguese"],"letreiro":["portuguese"],"levar":["portuguese"],"leveza":["portuguese"],"levitar":["portuguese"],"liberal":["portuguese"],"libido":["portuguese"],"liderar":["portuguese"],"ligar":["portuguese"],"ligeiro":["portuguese"],"limitar":["portuguese"],"limoeiro":["portuguese"],"limpador":["portuguese"],"linda":["portuguese"],"linear":["portuguese"],"linhagem":["portuguese"],"liquidez":["portuguese"],"listagem":["portuguese"],"lisura":["portuguese"],"litoral":["portuguese"],"livro":["portuguese"],"lixa":["portuguese"],"lixeira":["portuguese"],"locador":["portuguese"],"locutor":["portuguese"],"lojista":["portuguese"],"lombo":["portuguese"],"lona":["portuguese"],"longe":["portuguese"],"lontra":["portuguese"],"lorde":["portuguese"],"lotado":["portuguese"],"loteria":["portuguese"],"loucura":["portuguese"],"lousa":["portuguese"],"louvar":["portuguese"],"luar":["portuguese"],"lucidez":["portuguese"],"lucro":["portuguese"],"luneta":["portuguese"],"lustre":["portuguese"],"lutador":["portuguese"],"luva":["portuguese"],"macaco":["portuguese"],"macete":["portuguese"],"machado":["portuguese"],"macio":["portuguese"],"madeira":["portuguese"],"madrinha":["portuguese"],"magnata":["portuguese"],"magreza":["portuguese"],"maior":["portuguese"],"mais":["portuguese"],"malandro":["portuguese"],"malha":["portuguese"],"malote":["portuguese"],"maluco":["portuguese"],"mamilo":["portuguese"],"mamoeiro":["portuguese"],"mamute":["portuguese"],"manada":["portuguese"],"mancha":["portuguese"],"mandato":["portuguese"],"manequim":["portuguese"],"manhoso":["portuguese"],"manivela":["portuguese"],"manobrar":["portuguese"],"mansa":["portuguese"],"manter":["portuguese"],"manusear":["portuguese"],"mapeado":["portuguese"],"maquinar":["portuguese"],"marcador":["portuguese"],"maresia":["portuguese"],"marfim":["portuguese"],"margem":["portuguese"],"marinho":["portuguese"],"marmita":["portuguese"],"maroto":["portuguese"],"marquise":["portuguese"],"marreco":["portuguese"],"martelo":["portuguese"],"marujo":["portuguese"],"mascote":["portuguese"],"masmorra":["portuguese"],"massagem":["portuguese"],"mastigar":["portuguese"],"matagal":["portuguese"],"materno":["portuguese"],"matinal":["portuguese"],"matutar":["portuguese"],"maxilar":["portuguese"],"medalha":["portuguese"],"medida":["portuguese"],"medusa":["portuguese"],"megafone":["portuguese"],"meiga":["portuguese"],"melancia":["portuguese"],"melhor":["portuguese"],"membro":["portuguese"],"memorial":["portuguese"],"menino":["portuguese"],"menos":["portuguese"],"mensagem":["portuguese"],"mental":["portuguese"],"merecer":["portuguese"],"mergulho":["portuguese"],"mesada":["portuguese"],"mesclar":["portuguese"],"mesmo":["portuguese"],"mesquita":["portuguese"],"mestre":["portuguese"],"metade":["portuguese"],"meteoro":["portuguese"],"metragem":["portuguese"],"mexer":["portuguese"],"mexicano":["portuguese"],"micro":["portuguese"],"migalha":["portuguese"],"migrar":["portuguese"],"milagre":["portuguese"],"milenar":["portuguese"],"milhar":["portuguese"],"mimado":["portuguese"],"minerar":["portuguese"],"minhoca":["portuguese"],"ministro":["portuguese"],"minoria":["portuguese"],"miolo":["portuguese"],"mirante":["portuguese"],"mirtilo":["portuguese"],"misturar":["portuguese"],"mocidade":["portuguese"],"moderno":["portuguese"],"modular":["portuguese"],"moeda":["portuguese"],"moer":["portuguese"],"moinho":["portuguese"],"moita":["portuguese"],"moldura":["portuguese"],"moleza":["portuguese"],"molho":["portuguese"],"molinete":["portuguese"],"molusco":["portuguese"],"montanha":["portuguese"],"moqueca":["portuguese"],"morango":["portuguese"],"morcego":["portuguese"],"mordomo":["portuguese"],"morena":["portuguese"],"mosaico":["portuguese"],"mosquete":["portuguese"],"mostarda":["portuguese"],"motel":["portuguese"],"motim":["portuguese"],"moto":["portuguese"],"motriz":["portuguese"],"muda":["portuguese"],"muito":["portuguese"],"mulata":["portuguese"],"mulher":["portuguese"],"multar":["portuguese"],"mundial":["portuguese"],"munido":["portuguese"],"muralha":["portuguese"],"murcho":["portuguese"],"muscular":["portuguese"],"museu":["portuguese"],"musical":["portuguese"],"nacional":["portuguese"],"nadador":["portuguese"],"naja":["portuguese"],"namoro":["portuguese"],"narina":["portuguese"],"narrado":["portuguese"],"nascer":["portuguese"],"nativa":["portuguese"],"natureza":["portuguese"],"navalha":["portuguese"],"navegar":["portuguese"],"navio":["portuguese"],"neblina":["portuguese"],"nebuloso":["portuguese"],"negativa":["portuguese"],"negociar":["portuguese"],"negrito":["portuguese"],"nervoso":["portuguese"],"neta":["portuguese"],"neural":["portuguese"],"nevasca":["portuguese"],"nevoeiro":["portuguese"],"ninar":["portuguese"],"ninho":["portuguese"],"nitidez":["portuguese"],"nivelar":["portuguese"],"nobreza":["portuguese"],"noite":["portuguese"],"noiva":["portuguese"],"nomear":["portuguese"],"nominal":["portuguese"],"nordeste":["portuguese"],"nortear":["portuguese"],"notar":["portuguese"],"noticiar":["portuguese"],"noturno":["portuguese"],"novelo":["portuguese"],"novilho":["portuguese"],"novo":["portuguese"],"nublado":["portuguese"],"nudez":["portuguese"],"numeral":["portuguese"],"nupcial":["portuguese"],"nutrir":["portuguese"],"nuvem":["portuguese"],"obcecado":["portuguese"],"obedecer":["portuguese"],"objetivo":["portuguese"],"obrigado":["portuguese"],"obscuro":["portuguese"],"obstetra":["portuguese"],"obter":["portuguese"],"obturar":["portuguese"],"ocidente":["portuguese"],"ocioso":["portuguese"],"ocorrer":["portuguese"],"oculista":["portuguese"],"ocupado":["portuguese"],"ofegante":["portuguese"],"ofensiva":["portuguese"],"oferenda":["portuguese"],"oficina":["portuguese"],"ofuscado":["portuguese"],"ogiva":["portuguese"],"olaria":["portuguese"],"oleoso":["portuguese"],"olhar":["portuguese"],"oliveira":["portuguese"],"ombro":["portuguese"],"omelete":["portuguese"],"omisso":["portuguese"],"omitir":["portuguese"],"ondulado":["portuguese"],"oneroso":["portuguese"],"ontem":["portuguese"],"opcional":["portuguese"],"operador":["portuguese"],"oponente":["portuguese"],"oportuno":["portuguese"],"oposto":["portuguese"],"orar":["portuguese"],"orbitar":["portuguese"],"ordem":["portuguese"],"ordinal":["portuguese"],"orfanato":["portuguese"],"orgasmo":["portuguese"],"orgulho":["portuguese"],"oriental":["portuguese"],"origem":["portuguese"],"oriundo":["portuguese"],"orla":["portuguese"],"ortodoxo":["portuguese"],"orvalho":["portuguese"],"oscilar":["portuguese"],"ossada":["portuguese"],"osso":["portuguese"],"ostentar":["portuguese"],"otimismo":["portuguese"],"ousadia":["portuguese"],"outono":["portuguese"],"outubro":["portuguese"],"ouvido":["portuguese"],"ovelha":["portuguese"],"ovular":["portuguese"],"oxidar":["portuguese"],"oxigenar":["portuguese"],"pacato":["portuguese"],"paciente":["portuguese"],"pacote":["portuguese"],"pactuar":["portuguese"],"padaria":["portuguese"],"padrinho":["portuguese"],"pagar":["portuguese"],"pagode":["portuguese"],"painel":["portuguese"],"pairar":["portuguese"],"paisagem":["portuguese"],"palavra":["portuguese"],"palestra":["portuguese"],"palheta":["portuguese"],"palito":["portuguese"],"palmada":["portuguese"],"palpitar":["portuguese"],"pancada":["portuguese"],"panela":["portuguese"],"panfleto":["portuguese"],"panqueca":["portuguese"],"pantanal":["portuguese"],"papagaio":["portuguese"],"papelada":["portuguese"],"papiro":["portuguese"],"parafina":["portuguese"],"parcial":["portuguese"],"pardal":["portuguese"],"parede":["portuguese"],"partida":["portuguese"],"pasmo":["portuguese"],"passado":["portuguese"],"pastel":["portuguese"],"patamar":["portuguese"],"patente":["portuguese"],"patinar":["portuguese"],"patrono":["portuguese"],"paulada":["portuguese"],"pausar":["portuguese"],"peculiar":["portuguese"],"pedalar":["portuguese"],"pedestre":["portuguese"],"pediatra":["portuguese"],"pedra":["portuguese"],"pegada":["portuguese"],"peitoral":["portuguese"],"peixe":["portuguese"],"pele":["portuguese"],"pelicano":["portuguese"],"penca":["portuguese"],"pendurar":["portuguese"],"peneira":["portuguese"],"penhasco":["portuguese"],"pensador":["portuguese"],"pente":["portuguese"],"perceber":["portuguese"],"perfeito":["portuguese"],"pergunta":["portuguese"],"perito":["portuguese"],"permitir":["portuguese"],"perna":["portuguese"],"perplexo":["portuguese"],"persiana":["portuguese"],"pertence":["portuguese"],"peruca":["portuguese"],"pescado":["portuguese"],"pesquisa":["portuguese"],"pessoa":["portuguese"],"petiscar":["portuguese"],"piada":["portuguese"],"picado":["portuguese"],"piedade":["portuguese"],"pigmento":["portuguese"],"pilastra":["portuguese"],"pilhado":["portuguese"],"pilotar":["portuguese"],"pimenta":["portuguese"],"pincel":["portuguese"],"pinguim":["portuguese"],"pinha":["portuguese"],"pinote":["portuguese"],"pintar":["portuguese"],"pioneiro":["portuguese"],"pipoca":["portuguese"],"piquete":["portuguese"],"piranha":["portuguese"],"pires":["portuguese"],"pirueta":["portuguese"],"piscar":["portuguese"],"pistola":["portuguese"],"pitanga":["portuguese"],"pivete":["portuguese"],"planta":["portuguese"],"plaqueta":["portuguese"],"platina":["portuguese"],"plebeu":["portuguese"],"plumagem":["portuguese"],"pluvial":["portuguese"],"pneu":["portuguese"],"poda":["portuguese"],"poeira":["portuguese"],"poetisa":["portuguese"],"polegada":["portuguese"],"policiar":["portuguese"],"poluente":["portuguese"],"polvilho":["portuguese"],"pomar":["portuguese"],"pomba":["portuguese"],"ponderar":["portuguese"],"pontaria":["portuguese"],"populoso":["portuguese"],"porta":["portuguese"],"possuir":["portuguese"],"postal":["portuguese"],"pote":["portuguese"],"poupar":["portuguese"],"pouso":["portuguese"],"povoar":["portuguese"],"praia":["portuguese"],"prancha":["portuguese"],"prato":["portuguese"],"praxe":["portuguese"],"prece":["portuguese"],"predador":["portuguese"],"prefeito":["portuguese"],"premiar":["portuguese"],"prensar":["portuguese"],"preparar":["portuguese"],"presilha":["portuguese"],"pretexto":["portuguese"],"prevenir":["portuguese"],"prezar":["portuguese"],"primata":["portuguese"],"princesa":["portuguese"],"prisma":["portuguese"],"privado":["portuguese"],"processo":["portuguese"],"produto":["portuguese"],"profeta":["portuguese"],"proibido":["portuguese"],"projeto":["portuguese"],"prometer":["portuguese"],"propagar":["portuguese"],"prosa":["portuguese"],"protetor":["portuguese"],"provador":["portuguese"],"publicar":["portuguese"],"pudim":["portuguese"],"pular":["portuguese"],"pulmonar":["portuguese"],"pulseira":["portuguese"],"punhal":["portuguese"],"punir":["portuguese"],"pupilo":["portuguese"],"pureza":["portuguese"],"puxador":["portuguese"],"quadra":["portuguese"],"quantia":["portuguese"],"quarto":["portuguese"],"quase":["portuguese"],"quebrar":["portuguese"],"queda":["portuguese"],"queijo":["portuguese"],"quente":["portuguese"],"querido":["portuguese"],"quimono":["portuguese"],"quina":["portuguese"],"quiosque":["portuguese"],"rabanada":["portuguese"],"rabisco":["portuguese"],"rachar":["portuguese"],"racionar":["portuguese"],"radial":["portuguese"],"raiar":["portuguese"],"rainha":["portuguese"],"raio":["portuguese"],"raiva":["portuguese"],"rajada":["portuguese"],"ralado":["portuguese"],"ramal":["portuguese"],"ranger":["portuguese"],"ranhura":["portuguese"],"rapadura":["portuguese"],"rapel":["portuguese"],"rapidez":["portuguese"],"raposa":["portuguese"],"raquete":["portuguese"],"raridade":["portuguese"],"rasante":["portuguese"],"rascunho":["portuguese"],"rasgar":["portuguese"],"raspador":["portuguese"],"rasteira":["portuguese"],"rasurar":["portuguese"],"ratazana":["portuguese"],"ratoeira":["portuguese"],"realeza":["portuguese"],"reanimar":["portuguese"],"reaver":["portuguese"],"rebaixar":["portuguese"],"rebelde":["portuguese"],"rebolar":["portuguese"],"recado":["portuguese"],"recente":["portuguese"],"recheio":["portuguese"],"recibo":["portuguese"],"recordar":["portuguese"],"recrutar":["portuguese"],"recuar":["portuguese"],"rede":["portuguese"],"redimir":["portuguese"],"redonda":["portuguese"],"reduzida":["portuguese"],"reenvio":["portuguese"],"refinar":["portuguese"],"refletir":["portuguese"],"refogar":["portuguese"],"refresco":["portuguese"],"refugiar":["portuguese"],"regalia":["portuguese"],"regime":["portuguese"],"regra":["portuguese"],"reinado":["portuguese"],"reitor":["portuguese"],"rejeitar":["portuguese"],"relativo":["portuguese"],"remador":["portuguese"],"remendo":["portuguese"],"remorso":["portuguese"],"renovado":["portuguese"],"reparo":["portuguese"],"repelir":["portuguese"],"repleto":["portuguese"],"repolho":["portuguese"],"represa":["portuguese"],"repudiar":["portuguese"],"requerer":["portuguese"],"resenha":["portuguese"],"resfriar":["portuguese"],"resgatar":["portuguese"],"residir":["portuguese"],"resolver":["portuguese"],"respeito":["portuguese"],"ressaca":["portuguese"],"restante":["portuguese"],"resumir":["portuguese"],"retalho":["portuguese"],"reter":["portuguese"],"retirar":["portuguese"],"retomada":["portuguese"],"retratar":["portuguese"],"revelar":["portuguese"],"revisor":["portuguese"],"revolta":["portuguese"],"riacho":["portuguese"],"rica":["portuguese"],"rigidez":["portuguese"],"rigoroso":["portuguese"],"rimar":["portuguese"],"ringue":["portuguese"],"risada":["portuguese"],"risco":["portuguese"],"risonho":["portuguese"],"robalo":["portuguese"],"rochedo":["portuguese"],"rodada":["portuguese"],"rodeio":["portuguese"],"rodovia":["portuguese"],"roedor":["portuguese"],"roleta":["portuguese"],"romano":["portuguese"],"roncar":["portuguese"],"rosado":["portuguese"],"roseira":["portuguese"],"rosto":["portuguese"],"rota":["portuguese","turkish"],"roteiro":["portuguese"],"rotina":["portuguese"],"rotular":["portuguese"],"rouco":["portuguese"],"roupa":["portuguese"],"roxo":["portuguese"],"rubro":["portuguese"],"rugido":["portuguese"],"rugoso":["portuguese"],"ruivo":["portuguese"],"rumo":["portuguese"],"rupestre":["portuguese"],"russo":["portuguese"],"sabor":["portuguese"],"saciar":["portuguese"],"sacola":["portuguese"],"sacudir":["portuguese"],"sadio":["portuguese"],"safira":["portuguese"],"saga":["portuguese"],"sagrada":["portuguese"],"saibro":["portuguese"],"salada":["portuguese"],"saleiro":["portuguese"],"salgado":["portuguese"],"saliva":["portuguese"],"salpicar":["portuguese"],"salsicha":["portuguese"],"saltar":["portuguese"],"salvador":["portuguese"],"sambar":["portuguese"],"samurai":["portuguese"],"sanar":["portuguese"],"sanfona":["portuguese"],"sangue":["portuguese"],"sanidade":["portuguese"],"sapato":["portuguese"],"sarda":["portuguese"],"sargento":["portuguese"],"sarjeta":["portuguese"],"saturar":["portuguese"],"saudade":["portuguese"],"saxofone":["portuguese"],"sazonal":["portuguese"],"secar":["portuguese"],"secular":["portuguese"],"seda":["portuguese","turkish"],"sedento":["portuguese"],"sediado":["portuguese"],"sedoso":["portuguese"],"sedutor":["portuguese"],"segmento":["portuguese"],"segredo":["portuguese"],"segundo":["portuguese"],"seiva":["portuguese"],"seleto":["portuguese"],"selvagem":["portuguese"],"semanal":["portuguese"],"semente":["portuguese"],"senador":["portuguese"],"senhor":["portuguese"],"sensual":["portuguese"],"sentado":["portuguese"],"separado":["portuguese"],"sereia":["portuguese"],"seringa":["portuguese"],"serra":["portuguese"],"servo":["portuguese"],"setembro":["portuguese"],"setor":["portuguese"],"sigilo":["portuguese"],"silhueta":["portuguese"],"silicone":["portuguese"],"simetria":["portuguese"],"simpatia":["portuguese"],"simular":["portuguese"],"sinal":["portuguese"],"sincero":["portuguese"],"singular":["portuguese"],"sinopse":["portuguese"],"sintonia":["portuguese"],"sirene":["portuguese"],"siri":["portuguese"],"situado":["portuguese"],"soberano":["portuguese"],"sobra":["portuguese"],"socorro":["portuguese"],"sogro":["portuguese"],"soja":["portuguese"],"solda":["portuguese"],"soletrar":["portuguese"],"solteiro":["portuguese"],"sombrio":["portuguese"],"sonata":["portuguese"],"sondar":["portuguese"],"sonegar":["portuguese"],"sonhador":["portuguese"],"sono":["portuguese"],"soprano":["portuguese"],"soquete":["portuguese"],"sorrir":["portuguese"],"sorteio":["portuguese"],"sossego":["portuguese"],"sotaque":["portuguese"],"soterrar":["portuguese"],"sovado":["portuguese"],"sozinho":["portuguese"],"suavizar":["portuguese"],"subida":["portuguese"],"submerso":["portuguese"],"subsolo":["portuguese"],"subtrair":["portuguese"],"sucata":["portuguese"],"sucesso":["portuguese"],"suco":["portuguese"],"sudeste":["portuguese"],"sufixo":["portuguese"],"sugador":["portuguese"],"sugerir":["portuguese"],"sujeito":["portuguese"],"sulfato":["portuguese"],"sumir":["portuguese"],"suor":["portuguese"],"superior":["portuguese"],"suplicar":["portuguese"],"suposto":["portuguese"],"suprimir":["portuguese"],"surdina":["portuguese"],"surfista":["portuguese"],"surpresa":["portuguese"],"surreal":["portuguese"],"surtir":["portuguese"],"suspiro":["portuguese"],"sustento":["portuguese"],"tabela":["portuguese","turkish"],"tablete":["portuguese"],"tabuada":["portuguese"],"tacho":["portuguese"],"tagarela":["portuguese"],"talher":["portuguese"],"talo":["portuguese"],"talvez":["portuguese"],"tamanho":["portuguese"],"tamborim":["portuguese"],"tampa":["portuguese"],"tangente":["portuguese"],"tanto":["portuguese"],"tapar":["portuguese"],"tapioca":["portuguese"],"tardio":["portuguese"],"tarefa":["portuguese"],"tarja":["portuguese"],"tarraxa":["portuguese"],"tatuagem":["portuguese"],"taurino":["portuguese"],"taxativo":["portuguese"],"taxista":["portuguese"],"teatral":["portuguese"],"tecer":["portuguese"],"tecido":["portuguese"],"teclado":["portuguese"],"tedioso":["portuguese"],"teia":["portuguese"],"teimar":["portuguese"],"telefone":["portuguese"],"telhado":["portuguese"],"tempero":["portuguese"],"tenente":["portuguese"],"tensor":["portuguese"],"tentar":["portuguese"],"termal":["portuguese"],"terno":["portuguese"],"terreno":["portuguese"],"tese":["portuguese"],"tesoura":["portuguese"],"testado":["portuguese"],"teto":["portuguese"],"textura":["portuguese"],"texugo":["portuguese"],"tiara":["portuguese"],"tigela":["portuguese"],"tijolo":["portuguese"],"timbrar":["portuguese"],"timidez":["portuguese"],"tingido":["portuguese"],"tinteiro":["portuguese"],"tiragem":["portuguese"],"titular":["portuguese"],"toalha":["portuguese"],"tocha":["portuguese"],"tolerar":["portuguese"],"tolice":["portuguese"],"tomada":["portuguese"],"tomilho":["portuguese"],"tonel":["portuguese"],"tontura":["portuguese"],"topete":["portuguese"],"tora":["portuguese"],"torcido":["portuguese"],"torneio":["portuguese"],"torque":["portuguese"],"torrada":["portuguese"],"torto":["portuguese"],"tostar":["portuguese"],"touca":["portuguese"],"toupeira":["portuguese"],"toxina":["portuguese"],"trabalho":["portuguese"],"tracejar":["portuguese"],"tradutor":["portuguese"],"trafegar":["portuguese"],"trajeto":["portuguese"],"trama":["portuguese"],"trancar":["portuguese"],"trapo":["portuguese"],"traseiro":["portuguese"],"tratador":["portuguese"],"travar":["portuguese"],"treino":["portuguese"],"tremer":["portuguese"],"trepidar":["portuguese"],"trevo":["portuguese"],"triagem":["portuguese"],"tribo":["portuguese"],"triciclo":["portuguese"],"tridente":["portuguese"],"trilogia":["portuguese"],"trindade":["portuguese"],"triplo":["portuguese"],"triturar":["portuguese"],"triunfal":["portuguese"],"trocar":["portuguese"],"trombeta":["portuguese"],"trova":["portuguese"],"trunfo":["portuguese"],"truque":["portuguese"],"tubular":["portuguese"],"tucano":["portuguese"],"tudo":["portuguese"],"tulipa":["portuguese"],"tupi":["portuguese"],"turbo":["portuguese"],"turma":["portuguese"],"turquesa":["portuguese"],"tutelar":["portuguese"],"tutorial":["portuguese"],"uivar":["portuguese"],"umbigo":["portuguese"],"unha":["portuguese"],"unidade":["portuguese"],"uniforme":["portuguese"],"urologia":["portuguese"],"urso":["portuguese"],"urtiga":["portuguese"],"urubu":["portuguese"],"usado":["portuguese"],"usina":["portuguese"],"usufruir":["portuguese"],"vacina":["portuguese"],"vadiar":["portuguese"],"vagaroso":["portuguese"],"vaidoso":["portuguese"],"vala":["portuguese"],"valente":["portuguese"],"validade":["portuguese"],"valores":["portuguese"],"vantagem":["portuguese"],"vaqueiro":["portuguese"],"varanda":["portuguese"],"vareta":["portuguese"],"varrer":["portuguese"],"vascular":["portuguese"],"vasilha":["portuguese"],"vassoura":["portuguese"],"vazar":["portuguese"],"vazio":["portuguese"],"veado":["portuguese"],"vedar":["portuguese"],"vegetar":["portuguese"],"veicular":["portuguese"],"veleiro":["portuguese"],"velhice":["portuguese"],"veludo":["portuguese"],"vencedor":["portuguese"],"vendaval":["portuguese"],"venerar":["portuguese"],"ventre":["portuguese"],"verbal":["portuguese"],"verdade":["portuguese"],"vereador":["portuguese"],"vergonha":["portuguese"],"vermelho":["portuguese"],"verniz":["portuguese"],"versar":["portuguese"],"vertente":["portuguese"],"vespa":["portuguese"],"vestido":["portuguese"],"vetorial":["portuguese"],"viaduto":["portuguese"],"viagem":["portuguese"],"viajar":["portuguese"],"viatura":["portuguese"],"vibrador":["portuguese"],"videira":["portuguese"],"vidraria":["portuguese"],"viela":["portuguese"],"viga":["portuguese"],"vigente":["portuguese"],"vigiar":["portuguese"],"vigorar":["portuguese"],"vilarejo":["portuguese"],"vinco":["portuguese"],"vinheta":["portuguese"],"vinil":["portuguese"],"violeta":["portuguese"],"virada":["portuguese"],"virtude":["portuguese"],"visitar":["portuguese"],"visto":["portuguese"],"vitral":["portuguese"],"viveiro":["portuguese"],"vizinho":["portuguese"],"voador":["portuguese"],"voar":["portuguese"],"vogal":["portuguese"],"volante":["portuguese"],"voleibol":["portuguese"],"voltagem":["portuguese"],"volumoso":["portuguese"],"vontade":["portuguese"],"vulto":["portuguese"],"vuvuzela":["portuguese"],"xadrez":["portuguese"],"xarope":["portuguese"],"xeque":["portuguese"],"xeretar":["portuguese"],"xerife":["portuguese"],"xingar":["portuguese"],"zangado":["portuguese"],"zarpar":["portuguese"],"zebu":["portuguese"],"zelador":["portuguese"],"zombar":["portuguese"],"zoologia":["portuguese"],"zumbido":["portuguese"],"абзац":["russian"],"абонент":["russian"],"абсурд":["russian"],"авангард":["russian"],"авария":["russian"],"август":["russian"],"авиация":["russian"],"автор":["russian"],"агент":["russian"],"агитация":["russian"],"агрегат":["russian"],"адвокат":["russian"],"адмирал":["russian"],"адрес":["russian"],"азарт":["russian"],"азот":["russian"],"академия":["russian"],"аквариум":["russian"],"аксиома":["russian"],"акула":["russian"],"акцент":["russian"],"акция":["russian"],"аллея":["russian"],"алмаз":["russian"],"алтарь":["russian"],"альбом":["russian"],"альянс":["russian"],"амбиция":["russian"],"анализ":["russian"],"анекдот":["russian"],"анкета":["russian"],"ансамбль":["russian"],"антенна":["russian"],"апельсин":["russian"],"аппарат":["russian"],"аппетит":["russian"],"апрель":["russian"],"аптека":["russian"],"арбуз":["russian"],"аргумент":["russian"],"аренда":["russian"],"арест":["russian"],"армия":["russian"],"аромат":["russian"],"арсенал":["russian"],"артерия":["russian"],"артист":["russian"],"архив":["russian"],"аспирант":["russian"],"асфальт":["russian"],"атака":["russian"],"атомный":["russian"],"атрибут":["russian"],"аукцион":["russian"],"афиша":["russian"],"аэропорт":["russian"],"бабочка":["russian"],"бабушка":["russian"],"багаж":["russian"],"база":["russian"],"бактерия":["russian"],"баланс":["russian"],"балерина":["russian"],"балкон":["russian"],"бандит":["russian"],"банк":["russian"],"барабан":["russian"],"барон":["russian"],"барышня":["russian"],"барьер":["russian"],"бассейн":["russian"],"батарея":["russian"],"башмак":["russian"],"башня":["russian"],"бедный":["russian"],"беженец":["russian"],"бездна":["russian"],"белка":["russian"],"белый":["russian"],"бензин":["russian"],"берег":["russian"],"беседа":["russian"],"бешеный":["russian"],"билет":["russian"],"бинокль":["russian"],"биржа":["russian"],"битва":["russian"],"благо":["russian"],"блеск":["russian"],"близкий":["russian"],"блин":["russian"],"блок":["russian"],"блюдо":["russian"],"богатый":["russian"],"бодрый":["russian"],"боец":["russian"],"бокал":["russian"],"боковой":["russian"],"бокс":["russian"],"более":["russian"],"болото":["russian"],"болтать":["russian"],"большой":["russian"],"бомба":["russian"],"борт":["russian"],"борьба":["russian"],"босой":["russian"],"ботинок":["russian"],"бояться":["russian"],"брак":["russian"],"брать":["russian"],"бревно":["russian"],"бред":["russian"],"бригада":["russian"],"бродяга":["russian"],"броня":["russian"],"бросить":["russian"],"брызги":["russian"],"брюки":["russian"],"брюхо":["russian"],"бугор":["russian"],"будка":["russian"],"будни":["russian"],"будущее":["russian"],"буква":["russian"],"букет":["russian"],"бульвар":["russian"],"бумага":["russian"],"бунт":["russian"],"бурный":["russian"],"буря":["russian"],"бутылка":["russian"],"бухта":["russian"],"бывший":["russian"],"быстро":["russian"],"бытовой":["russian"],"быть":["russian"],"бюджет":["russian"],"бюро":["russian"],"бюст":["russian"],"вагон":["russian"],"важный":["russian"],"вакцина":["russian"],"валенок":["russian"],"вальс":["russian"],"валюта":["russian"],"ванная":["russian"],"варенье":["russian"],"вариант":["russian"],"вблизи":["russian"],"вверх":["russian"],"вводить":["russian"],"вдали":["russian"],"вдвое":["russian"],"вдова":["russian"],"вдоль":["russian"],"вдруг":["russian"],"ведро":["russian"],"ведущий":["russian"],"ведьма":["russian"],"вежливо":["russian"],"везде":["russian"],"веко":["russian"],"вексель":["russian"],"велеть":["russian"],"великий":["russian"],"венец":["russian"],"веник":["russian"],"веранда":["russian"],"верблюд":["russian"],"верить":["russian"],"верный":["russian"],"версия":["russian"],"вертеть":["russian"],"верхний":["russian"],"вершина":["russian"],"весело":["russian"],"весна":["russian"],"весомый":["russian"],"вести":["russian"],"весь":["russian"],"ветеран":["russian"],"ветхий":["russian"],"вечер":["russian"],"вечно":["russian"],"вешалка":["russian"],"вещество":["russian"],"взамен":["russian"],"взгляд":["russian"],"вздох":["russian"],"взнос":["russian"],"взойти":["russian"],"взор":["russian"],"взрыв":["russian"],"взять":["russian"],"видеть":["russian"],"видимо":["russian"],"визг":["russian"],"визит":["russian"],"вилка":["russian"],"вина":["russian"],"вирус":["russian"],"висок":["russian"],"витамин":["russian"],"витрина":["russian"],"вихрь":["russian"],"вишня":["russian"],"вкус":["russian"],"влага":["russian"],"владелец":["russian"],"власть":["russian"],"влево":["russian"],"влияние":["russian"],"вложить":["russian"],"вместе":["russian"],"внешний":["russian"],"вникать":["russian"],"внимание":["russian"],"вновь":["russian"],"внук":["russian"],"внутри":["russian"],"внучка":["russian"],"внушать":["russian"],"вовлечь":["russian"],"вовремя":["russian"],"вовсю":["russian"],"вода":["russian"],"водород":["russian"],"водяной":["russian"],"воевать":["russian"],"возврат":["russian"],"возглас":["russian"],"воздух":["russian"],"возить":["russian"],"возле":["russian"],"возня":["russian"],"возраст":["russian"],"война":["russian"],"войско":["russian"],"вокзал":["russian"],"волос":["russian"],"волчий":["russian"],"вольный":["russian"],"воля":["russian"],"вообще":["russian"],"вопль":["russian"],"вопрос":["russian"],"ворота":["russian"],"восемь":["russian"],"восток":["russian"],"вплоть":["russian"],"вполне":["russian"],"вправе":["russian"],"впредь":["russian"],"впрочем":["russian"],"врач":["russian"],"вредный":["russian"],"время":["russian"],"вручить":["russian"],"всадник":["russian"],"всегда":["russian"],"вскоре":["russian"],"вскрыть":["russian"],"всплеск":["russian"],"вспышка":["russian"],"встреча":["russian"],"всюду":["russian"],"всякий":["russian"],"второй":["russian"],"вход":["russian"],"вчера":["russian"],"выбор":["russian"],"вывод":["russian"],"выгнать":["russian"],"выдать":["russian"],"выехать":["russian"],"вызов":["russian"],"выйти":["russian"],"выкуп":["russian"],"вылезти":["russian"],"вымыть":["russian"],"выпасть":["russian"],"выпить":["russian"],"выплата":["russian"],"выпуск":["russian"],"вырасти":["russian"],"выручка":["russian"],"выслать":["russian"],"высокий":["russian"],"выставка":["russian"],"вышка":["russian"],"вязать":["russian"],"вялый":["russian"],"газета":["russian"],"газовый":["russian"],"галерея":["russian"],"галстук":["russian"],"гамма":["russian"],"гарантия":["russian"],"гармония":["russian"],"гарнизон":["russian"],"гастроли":["russian"],"гвардия":["russian"],"гвоздь":["russian"],"гектар":["russian"],"генерал":["russian"],"гений":["russian"],"геном":["russian"],"геолог":["russian"],"герб":["russian"],"герой":["russian"],"гибкий":["russian"],"гигант":["russian"],"гимн":["russian"],"гипотеза":["russian"],"гитара":["russian"],"главный":["russian"],"глагол":["russian"],"гладить":["russian"],"глаз":["russian"],"глина":["russian"],"глоток":["russian"],"глубокий":["russian"],"глупый":["russian"],"глухой":["russian"],"глыба":["russian"],"глядеть":["russian"],"гнев":["russian"],"гнездо":["russian"],"гнилой":["russian"],"годовой":["russian"],"голова":["russian"],"голубой":["russian"],"голый":["russian"],"гонорар":["russian"],"гордость":["russian"],"горизонт":["russian"],"горло":["russian"],"горный":["russian"],"город":["russian"],"горшок":["russian"],"горький":["russian"],"горючее":["russian"],"горячий":["russian"],"готовый":["russian"],"градус":["russian"],"грамм":["russian"],"граница":["russian"],"граф":["russian"],"гребень":["russian"],"гриб":["russian"],"гримаса":["russian"],"грозить":["russian"],"грохот":["russian"],"грош":["russian"],"грубый":["russian"],"грудь":["russian"],"груз":["russian"],"грунт":["russian"],"группа":["russian"],"груша":["russian"],"грязный":["russian"],"губа":["russian"],"гудок":["russian"],"гулкий":["russian"],"гулять":["russian"],"гусеница":["russian"],"густо":["russian"],"гусь":["russian"],"давление":["russian"],"давно":["russian"],"даже":["russian"],"дальний":["russian"],"данный":["russian"],"дарить":["russian"],"датчик":["russian"],"дать":["russian"],"дача":["russian"],"двадцать":["russian"],"дважды":["russian"],"дверь":["russian"],"двигать":["russian"],"движение":["russian"],"двойной":["russian"],"двор":["russian"],"дебют":["russian"],"девятый":["russian"],"дежурный":["russian"],"действие":["russian"],"декабрь":["russian"],"деление":["russian"],"дело":["russian"],"дельфин":["russian"],"день":["russian"],"дерево":["russian"],"держать":["russian"],"дерзкий":["russian"],"десять":["russian"],"деталь":["russian"],"детский":["russian"],"дефект":["russian"],"дефицит":["russian"],"деятель":["russian"],"джаз":["russian"],"джинсы":["russian"],"джунгли":["russian"],"диагноз":["russian"],"диалог":["russian"],"диапазон":["russian"],"диван":["russian"],"дивизия":["russian"],"дивный":["russian"],"диета":["russian"],"дизайн":["russian"],"дикарь":["russian"],"дилер":["russian"],"динамика":["russian"],"диплом":["russian"],"директор":["russian"],"дитя":["russian"],"длинный":["russian"],"дневник":["russian"],"добрый":["russian"],"добыча":["russian"],"доверие":["russian"],"догадка":["russian"],"догнать":["russian"],"дождь":["russian"],"доклад":["russian"],"доктор":["russian"],"документ":["russian"],"долго":["russian"],"должен":["russian"],"долина":["russian"],"донос":["russian"],"дорога":["russian"],"досада":["russian"],"доска":["russian"],"достать":["russian"],"досуг":["russian"],"доход":["russian"],"доцент":["russian"],"дощатый":["russian"],"драка":["russian"],"древний":["russian"],"дремать":["russian"],"дробный":["russian"],"дрова":["russian"],"дрожать":["russian"],"другой":["russian"],"дружба":["russian"],"дубовый":["russian"],"дуга":["russian"],"думать":["russian"],"дурной":["russian"],"духи":["russian"],"душный":["russian"],"дуэль":["russian"],"дуэт":["russian"],"дыра":["russian"],"дыхание":["russian"],"дюжина":["russian"],"дядя":["russian"],"едва":["russian"],"единый":["russian"],"ерунда":["russian"],"если":["russian"],"ехать":["russian"],"жадный":["russian"],"жажда":["russian"],"жалеть":["russian"],"жалоба":["russian"],"жанр":["russian"],"жареный":["russian"],"жаркий":["russian"],"жгучий":["russian"],"жевать":["russian"],"желание":["russian"],"желудок":["russian"],"жена":["russian"],"женщина":["russian"],"жертва":["russian"],"жест":["russian"],"жидкость":["russian"],"житель":["russian"],"жить":["russian"],"жрец":["russian"],"жулик":["russian"],"журнал":["russian"],"жуткий":["russian"],"забрать":["russian"],"забыть":["russian"],"завести":["russian"],"завод":["russian"],"завтра":["russian"],"загадка":["russian"],"загнать":["russian"],"заговор":["russian"],"задача":["russian"],"задеть":["russian"],"задний":["russian"],"задолго":["russian"],"заехать":["russian"],"заказ":["russian"],"закон":["russian"],"закрыть":["russian"],"закуска":["russian"],"залезть":["russian"],"залить":["russian"],"залп":["russian"],"замок":["russian"],"замуж":["russian"],"замысел":["russian"],"занавес":["russian"],"заново":["russian"],"занять":["russian"],"заодно":["russian"],"запись":["russian"],"запрос":["russian"],"запуск":["russian"],"запястье":["russian"],"заранее":["russian"],"заросль":["russian"],"зарплата":["russian"],"заря":["russian"],"засада":["russian"],"заслуга":["russian"],"заснуть":["russian"],"застать":["russian"],"затвор":["russian"],"затеять":["russian"],"затрата":["russian"],"затылок":["russian"],"захват":["russian"],"зачем":["russian"],"защита":["russian"],"заявить":["russian"],"заяц":["russian"],"звезда":["russian"],"звено":["russian"],"звонить":["russian"],"здесь":["russian"],"зелень":["russian"],"земля":["russian"],"зеркало":["russian"],"зерно":["russian"],"зима":["russian"],"злой":["russian"],"змея":["russian"],"знамя":["russian"],"знание":["russian"],"значит":["russian"],"золотой":["russian"],"зона":["russian"],"зонтик":["russian"],"зоопарк":["russian"],"зрачок":["russian"],"зрение":["russian"],"зритель":["russian"],"зубной":["russian"],"зубр":["russian"],"игла":["russian"],"идеал":["russian"],"идеолог":["russian"],"идея":["russian"],"идол":["russian"],"идти":["russian"],"изба":["russian"],"избить":["russian"],"избрать":["russian"],"избыток":["russian"],"извлечь":["russian"],"извне":["russian"],"изгиб":["russian"],"изгнать":["russian"],"издание":["russian"],"изделие":["russian"],"изнутри":["russian"],"изобилие":["russian"],"изоляция":["russian"],"изредка":["russian"],"изрядно":["russian"],"изучение":["russian"],"изъять":["russian"],"изящный":["russian"],"икона":["russian"],"икра":["russian"],"иллюзия":["russian"],"именно":["russian"],"иметь":["russian"],"имидж":["russian"],"империя":["russian"],"импульс":["russian"],"иначе":["russian"],"инвалид":["russian"],"индекс":["russian"],"индивид":["russian"],"инерция":["russian"],"инженер":["russian"],"иногда":["russian"],"иной":["russian"],"институт":["russian"],"интерес":["russian"],"интрига":["russian"],"интуиция":["russian"],"инфаркт":["russian"],"инцидент":["russian"],"ирония":["russian"],"искать":["russian"],"испуг":["russian"],"история":["russian"],"итог":["russian"],"июнь":["russian"],"кабель":["russian"],"кабинет":["russian"],"каблук":["russian"],"кавалер":["russian"],"кадр":["russian"],"каждый":["russian"],"кажется":["russian"],"казино":["russian"],"калитка":["russian"],"камень":["russian"],"камин":["russian"],"канал":["russian"],"кандидат":["russian"],"каникулы":["russian"],"канон":["russian"],"капитан":["russian"],"капля":["russian"],"капот":["russian"],"капуста":["russian"],"карандаш":["russian"],"карета":["russian"],"каркас":["russian"],"карман":["russian"],"картина":["russian"],"карьера":["russian"],"каска":["russian"],"кассета":["russian"],"кастрюля":["russian"],"каталог":["russian"],"катер":["russian"],"каток":["russian"],"катушка":["russian"],"кафедра":["russian"],"качество":["russian"],"каша":["russian"],"кашлять":["russian"],"каюта":["russian"],"квадрат":["russian"],"квартира":["russian"],"квота":["russian"],"кепка":["russian"],"кивнуть":["russian"],"километр":["russian"],"кино":["russian"],"киоск":["russian"],"кипяток":["russian"],"кирпич":["russian"],"кислота":["russian"],"кисть":["russian"],"клавиша":["russian"],"клапан":["russian"],"класс":["russian"],"клей":["russian"],"клетка":["russian"],"клиент":["russian"],"климат":["russian"],"клиника":["russian"],"кличка":["russian"],"клоун":["russian"],"клочок":["russian"],"клуб":["russian"],"клумба":["russian"],"ключ":["russian"],"книга":["russian"],"кнопка":["russian"],"кнут":["russian"],"княгиня":["russian"],"князь":["russian"],"кобура":["russian"],"когда":["russian"],"кодекс":["russian"],"кожа":["russian"],"коктейль":["russian"],"колено":["russian"],"коллега":["russian"],"колонна":["russian"],"колпак":["russian"],"кольцо":["russian"],"колючий":["russian"],"коляска":["russian"],"команда":["russian"],"комедия":["russian"],"комиссия":["russian"],"коммуна":["russian"],"комната":["russian"],"комок":["russian"],"компания":["russian"],"комфорт":["russian"],"конвейер":["russian"],"конгресс":["russian"],"конечно":["russian"],"конкурс":["russian"],"контроль":["russian"],"концерт":["russian"],"конь":["russian"],"конюшня":["russian"],"копать":["russian"],"копейка":["russian"],"копыто":["russian"],"корабль":["russian"],"корень":["russian"],"корзина":["russian"],"коридор":["russian"],"кормить":["russian"],"корпус":["russian"],"космос":["russian"],"костюм":["russian"],"косяк":["russian"],"котел":["russian"],"котлета":["russian"],"который":["russian"],"коттедж":["russian"],"кофе":["russian"],"кофта":["russian"],"кошка":["russian"],"кража":["russian"],"край":["russian"],"красный":["russian"],"краткий":["russian"],"кредит":["russian"],"крем":["russian"],"крепкий":["russian"],"кресло":["russian"],"кривой":["russian"],"кризис":["russian"],"кристалл":["russian"],"критерий":["russian"],"кричать":["russian"],"кровь":["russian"],"крокодил":["russian"],"кролик":["russian"],"кроме":["russian"],"крона":["russian"],"круг":["russian"],"кружка":["russian"],"крупный":["russian"],"крутой":["russian"],"крушение":["russian"],"крыло":["russian"],"крыша":["russian"],"крючок":["russian"],"кстати":["russian"],"кубик":["russian"],"куда":["russian"],"кузов":["russian"],"кукла":["russian"],"кулак":["russian"],"кулиса":["russian"],"культура":["russian"],"кумир":["russian"],"купе":["russian"],"купить":["russian"],"купол":["russian"],"купюра":["russian"],"курица":["russian"],"курорт":["russian"],"курс":["russian"],"куртка":["russian"],"кусок":["russian"],"куст":["russian"],"кухня":["russian"],"кушать":["russian"],"лабиринт":["russian"],"лавка":["russian"],"лагерь":["russian"],"ладно":["russian"],"ладонь":["russian"],"лапа":["russian"],"лауреат":["russian"],"лгать":["russian"],"лебедь":["russian"],"левый":["russian"],"легенда":["russian"],"легкий":["russian"],"ледяной":["russian"],"лежать":["russian"],"лезвие":["russian"],"лезть":["russian"],"лекция":["russian"],"ленивый":["russian"],"лента":["russian"],"лепесток":["russian"],"лесной":["russian"],"лестница":["russian"],"лететь":["russian"],"лето":["russian"],"лечить":["russian"],"лига":["russian"],"лидер":["russian"],"лиловый":["russian"],"лимон":["russian"],"линия":["russian"],"липкий":["russian"],"лист":["russian"],"литр":["russian"],"лихой":["russian"],"лицо":["russian"],"лишить":["russian"],"лишний":["russian"],"ловить":["russian"],"логика":["russian"],"лодка":["russian"],"ложь":["russian"],"лозунг":["russian"],"локоть":["russian"],"лопата":["russian"],"лошадь":["russian"],"лукавый":["russian"],"луна":["russian"],"лучший":["russian"],"лысый":["russian"],"льгота":["russian"],"любить":["russian"],"любой":["russian"],"людской":["russian"],"люстра":["russian"],"лютый":["russian"],"лягушка":["russian"],"магазин":["russian"],"магия":["russian"],"майор":["russian"],"майский":["russian"],"максимум":["russian"],"макушка":["russian"],"мало":["russian"],"мальчик":["russian"],"мама":["russian"],"манера":["russian"],"марка":["russian"],"март":["russian"],"маршрут":["russian"],"масса":["russian"],"мастер":["russian"],"масштаб":["russian"],"материал":["russian"],"матч":["russian"],"махать":["russian"],"машина":["russian"],"маяк":["russian"],"мебель":["russian"],"медаль":["russian"],"медведь":["russian"],"медицина":["russian"],"медь":["russian"],"между":["russian"],"мелкий":["russian"],"мелочь":["russian"],"мемуары":["russian"],"меньше":["russian"],"меню":["russian"],"менять":["russian"],"мера":["russian"],"мерцать":["russian"],"место":["russian"],"месяц":["russian"],"металл":["russian"],"метод":["russian"],"метр":["russian"],"механизм":["russian"],"меховой":["russian"],"мечтать":["russian"],"мешать":["russian"],"мешок":["russian"],"миграция":["russian"],"микрофон":["russian"],"милиция":["russian"],"миллион":["russian"],"милость":["russian"],"миля":["russian"],"мимо":["russian"],"минерал":["russian"],"министр":["russian"],"минута":["russian"],"мирный":["russian"],"миска":["russian"],"миссия":["russian"],"митинг":["russian"],"мишень":["russian"],"младший":["russian"],"мнение":["russian"],"мнимый":["russian"],"много":["russian"],"могучий":["russian"],"модель":["russian"],"может":["russian"],"мозг":["russian"],"мокрый":["russian"],"молекула":["russian"],"молния":["russian"],"молодой":["russian"],"молчать":["russian"],"момент":["russian"],"монета":["russian"],"монитор":["russian"],"монолог":["russian"],"монстр":["russian"],"монтаж":["russian"],"мораль":["russian"],"море":["russian"],"морковь":["russian"],"мороз":["russian"],"морщина":["russian"],"мостовая":["russian"],"мотать":["russian"],"мотив":["russian"],"мотор":["russian"],"мохнатый":["russian"],"мрамор":["russian"],"мрачный":["russian"],"мстить":["russian"],"мудрый":["russian"],"мужество":["russian"],"мужчина":["russian"],"музей":["russian"],"музыка":["russian"],"мундир":["russian"],"муравей":["russian"],"мусор":["russian"],"муха":["russian"],"мчаться":["russian"],"мысль":["russian"],"мыться":["russian"],"мышца":["russian"],"мышь":["russian"],"мюзикл":["russian"],"мягкий":["russian"],"мясо":["russian"],"набор":["russian"],"навык":["russian"],"наглый":["russian"],"нагрузка":["russian"],"надежда":["russian"],"надзор":["russian"],"надо":["russian"],"наедине":["russian"],"назад":["russian"],"название":["russian"],"назло":["russian"],"наивный":["russian"],"найти":["russian"],"наконец":["russian"],"налево":["russian"],"наличие":["russian"],"налог":["russian"],"намерен":["russian"],"нанести":["russian"],"напасть":["russian"],"например":["russian"],"народ":["russian"],"наследие":["russian"],"натура":["russian"],"наука":["russian"],"наутро":["russian"],"начать":["russian"],"небо":["russian"],"неважно":["russian"],"невеста":["russian"],"негодяй":["russian"],"недавно":["russian"],"неделя":["russian"],"недолго":["russian"],"недра":["russian"],"недуг":["russian"],"нежный":["russian"],"незачем":["russian"],"некто":["russian"],"нелепый":["russian"],"неловко":["russian"],"нельзя":["russian"],"немало":["russian"],"немой":["russian"],"неплохо":["russian"],"нервный":["russian"],"нередко":["russian"],"нестись":["russian"],"неудача":["russian"],"неужели":["russian"],"нефть":["russian"],"неясный":["russian"],"нигде":["russian"],"низкий":["russian"],"никакой":["russian"],"никогда":["russian"],"никуда":["russian"],"ничто":["russian"],"ничуть":["russian"],"ниша":["russian"],"нищий":["russian"],"новость":["russian"],"новый":["russian"],"нога":["russian"],"ноготь":["russian"],"ножницы":["russian"],"ноздря":["russian"],"номер":["russian"],"носить":["russian"],"носок":["russian"],"ночь":["russian"],"ноябрь":["russian"],"нрав":["russian"],"нуль":["russian"],"нынче":["russian"],"нырять":["russian"],"нюанс":["russian"],"няня":["russian"],"обаяние":["russian"],"обед":["russian"],"обезьяна":["russian"],"обещать":["russian"],"обжечь":["russian"],"обзор":["russian"],"обилие":["russian"],"обитать":["russian"],"область":["russian"],"облик":["russian"],"обложка":["russian"],"обмен":["russian"],"обморок":["russian"],"обожать":["russian"],"обои":["russian"],"оболочка":["russian"],"оборона":["russian"],"обочина":["russian"],"образ":["russian"],"обрести":["russian"],"обрыв":["russian"],"обувь":["russian"],"обучение":["russian"],"обход":["russian"],"общество":["russian"],"общий":["russian"],"объект":["russian"],"обыск":["russian"],"обычно":["russian"],"обязать":["russian"],"овощи":["russian"],"овраг":["russian"],"овца":["russian"],"оговорка":["russian"],"ограда":["russian"],"огурец":["russian"],"одежда":["russian"],"одеяло":["russian"],"один":["russian"],"однако":["russian"],"одолеть":["russian"],"ожидать":["russian"],"озеро":["russian"],"океан":["russian"],"окно":["russian"],"около":["russian"],"окоп":["russian"],"окраина":["russian"],"октябрь":["russian"],"опасный":["russian"],"опека":["russian"],"операция":["russian"],"описание":["russian"],"оплата":["russian"],"опора":["russian"],"оппонент":["russian"],"оптимизм":["russian"],"оптовый":["russian"],"опухоль":["russian"],"опыт":["russian"],"оратор":["russian"],"орбита":["russian"],"орган":["russian"],"орден":["russian"],"орел":["russian"],"оригинал":["russian"],"ориентир":["russian"],"оркестр":["russian"],"оружие":["russian"],"осенний":["russian"],"осколок":["russian"],"осмотр":["russian"],"остров":["russian"],"отбор":["russian"],"отбыть":["russian"],"отвлечь":["russian"],"отдать":["russian"],"отдел":["russian"],"отдых":["russian"],"отель":["russian"],"отец":["russian"],"отзыв":["russian"],"отказ":["russian"],"отклик":["russian"],"открыть":["russian"],"откуда":["russian"],"отличие":["russian"],"отныне":["russian"],"отойти":["russian"],"отпуск":["russian"],"отрасль":["russian"],"отросток":["russian"],"отрывок":["russian"],"отряд":["russian"],"отсек":["russian"],"отставка":["russian"],"отсюда":["russian"],"оттенок":["russian"],"оттого":["russian"],"отчего":["russian"],"отъезд":["russian"],"офис":["russian"],"офицер":["russian"],"охота":["russian"],"охрана":["russian"],"оценка":["russian"],"очаг":["russian"],"очень":["russian"],"очередь":["russian"],"очищать":["russian"],"ошибка":["russian"],"ощущение":["russian"],"павильон":["russian"],"падать":["russian"],"пазуха":["russian"],"пакет":["russian"],"палата":["russian"],"палец":["russian"],"палуба":["russian"],"пальто":["russian"],"память":["russian"],"панель":["russian"],"паника":["russian"],"пара":["russian"],"парень":["russian"],"пароход":["russian"],"партия":["russian"],"парус":["russian"],"паспорт":["russian"],"пассажир":["russian"],"пастух":["russian"],"патент":["russian"],"патрон":["russian"],"пауза":["russian"],"паук":["russian"],"паутина":["russian"],"пафос":["russian"],"пахнуть":["russian"],"пациент":["russian"],"пачка":["russian"],"певец":["russian"],"педагог":["russian"],"пейзаж":["russian"],"пенсия":["russian"],"пепел":["russian"],"первый":["russian"],"перед":["russian"],"период":["russian"],"перо":["russian"],"перрон":["russian"],"персонаж":["russian"],"перчатка":["russian"],"песня":["russian"],"песок":["russian"],"петля":["russian"],"петрушка":["russian"],"петух":["russian"],"пехота":["russian"],"печать":["russian"],"печень":["russian"],"пешком":["russian"],"пещера":["russian"],"пианист":["russian"],"пиджак":["russian"],"пилот":["russian"],"пионер":["russian"],"пирамида":["russian"],"пирожок":["russian"],"письмо":["russian"],"пища":["russian"],"плавание":["russian"],"плакать":["russian"],"пламя":["russian"],"план":["russian"],"пласт":["russian"],"платить":["russian"],"пленный":["russian"],"плечо":["russian"],"плита":["russian"],"плод":["russian"],"плоский":["russian"],"плотный":["russian"],"плохой":["russian"],"площадь":["russian"],"плыть":["russian"],"плюс":["russian"],"пляж":["russian"],"плясать":["russian"],"победа":["russian"],"повар":["russian"],"повод":["russian"],"повсюду":["russian"],"повязка":["russian"],"погода":["russian"],"погреб":["russian"],"подбор":["russian"],"подвиг":["russian"],"подделка":["russian"],"поджать":["russian"],"поднос":["russian"],"подпись":["russian"],"подруга":["russian"],"подход":["russian"],"подчас":["russian"],"подъезд":["russian"],"поединок":["russian"],"поезд":["russian"],"поесть":["russian"],"поехать":["russian"],"пожалуй":["russian"],"пожилой":["russian"],"позади":["russian"],"позвать":["russian"],"поздний":["russian"],"позиция":["russian"],"позор":["russian"],"поиск":["russian"],"поймать":["russian"],"пойти":["russian"],"поклон":["russian"],"покой":["russian"],"покрыть":["russian"],"полдень":["russian"],"полезный":["russian"],"ползти":["russian"],"полк":["russian"],"полный":["russian"],"половина":["russian"],"полтора":["russian"],"польза":["russian"],"поляна":["russian"],"помидор":["russian"],"помнить":["russian"],"помощь":["russian"],"попасть":["russian"],"поперек":["russian"],"поплыть":["russian"],"пополам":["russian"],"поправка":["russian"],"попугай":["russian"],"попытка":["russian"],"порог":["russian"],"портрет":["russian"],"порция":["russian"],"порыв":["russian"],"порядок":["russian"],"после":["russian"],"посол":["russian"],"посреди":["russian"],"постель":["russian"],"посуда":["russian"],"потом":["russian"],"похвала":["russian"],"похожий":["russian"],"поцелуй":["russian"],"почва":["russian"],"почему":["russian"],"пошлина":["russian"],"поэма":["russian"],"поэтому":["russian"],"право":["russian"],"праздник":["russian"],"практика":["russian"],"прах":["russian"],"преграда":["russian"],"предмет":["russian"],"прежде":["russian"],"прелесть":["russian"],"премия":["russian"],"препарат":["russian"],"пресса":["russian"],"прибыть":["russian"],"прижать":["russian"],"прийти":["russian"],"приказ":["russian"],"прилавок":["russian"],"пример":["russian"],"принять":["russian"],"природа":["russian"],"притом":["russian"],"прихожая":["russian"],"прицел":["russian"],"причина":["russian"],"приют":["russian"],"прогноз":["russian"],"продукт":["russian"],"проект":["russian"],"прожить":["russian"],"прокат":["russian"],"промысел":["russian"],"пропуск":["russian"],"просто":["russian"],"против":["russian"],"профиль":["russian"],"процесс":["russian"],"прочий":["russian"],"прошлый":["russian"],"прощать":["russian"],"пружина":["russian"],"прут":["russian"],"прыжок":["russian"],"прямой":["russian"],"птица":["russian"],"публика":["russian"],"пугать":["russian"],"пуговица":["russian"],"пузырь":["russian"],"пульт":["russian"],"пуля":["russian"],"пункт":["russian"],"пускать":["russian"],"пустой":["russian"],"путь":["russian"],"пухлый":["russian"],"пучок":["russian"],"пушистый":["russian"],"пушка":["russian"],"пчела":["russian"],"пшеница":["russian"],"пылать":["russian"],"пыль":["russian"],"пышный":["russian"],"пьеса":["russian"],"пятка":["russian"],"пятно":["russian"],"пятый":["russian"],"пятьсот":["russian"],"работа":["russian"],"равнина":["russian"],"ради":["russian"],"радость":["russian"],"радуга":["russian"],"разбить":["russian"],"развитие":["russian"],"разговор":["russian"],"раздел":["russian"],"различие":["russian"],"размер":["russian"],"разный":["russian"],"разрыв":["russian"],"разум":["russian"],"район":["russian"],"ракета":["russian"],"раковина":["russian"],"рамка":["russian"],"рано":["russian"],"рапорт":["russian"],"распад":["russian"],"рассказ":["russian"],"расти":["russian"],"расход":["russian"],"расцвет":["russian"],"рация":["russian"],"рвануть":["russian"],"рваться":["russian"],"реакция":["russian"],"ребро":["russian"],"реветь":["russian"],"редактор":["russian"],"редкий":["russian"],"реестр":["russian"],"режим":["russian"],"резать":["russian"],"резерв":["russian"],"резина":["russian"],"резко":["russian"],"резной":["russian"],"рейс":["russian"],"реклама":["russian"],"рекорд":["russian"],"религия":["russian"],"рельс":["russian"],"ремень":["russian"],"ремонт":["russian"],"реплика":["russian"],"репортаж":["russian"],"ресница":["russian"],"ресторан":["russian"],"реформа":["russian"],"рецепт":["russian"],"речь":["russian"],"решение":["russian"],"ржавый":["russian"],"риск":["russian"],"рисунок":["russian"],"ритуал":["russian"],"рифма":["russian"],"робко":["russian"],"робот":["russian"],"ровесник":["russian"],"ровно":["russian"],"родной":["russian"],"рождение":["russian"],"роза":["russian"],"розовый":["russian"],"розыск":["russian"],"роль":["russian"],"роман":["russian"],"роскошь":["russian"],"роспись":["russian"],"рост":["russian"],"рубашка":["russian"],"рубеж":["russian"],"рубить":["russian"],"рубрика":["russian"],"рудник":["russian"],"рука":["russian"],"рукопись":["russian"],"румяный":["russian"],"русло":["russian"],"рухнуть":["russian"],"ручей":["russian"],"ручной":["russian"],"рыба":["russian"],"рыжий":["russian"],"рынок":["russian"],"рыхлый":["russian"],"рыцарь":["russian"],"рычаг":["russian"],"рюкзак":["russian"],"рядом":["russian"],"садовый":["russian"],"сажать":["russian"],"салон":["russian"],"салфетка":["russian"],"салют":["russian"],"самец":["russian"],"самовар":["russian"],"самый":["russian"],"сани":["russian"],"санкция":["russian"],"сапог":["russian"],"сарай":["russian"],"сатира":["russian"],"сахар":["russian"],"сбить":["russian"],"сбоку":["russian"],"сборная":["russian"],"сбыт":["russian"],"свадьба":["russian"],"свалка":["russian"],"сварить":["russian"],"свежий":["russian"],"сверху":["russian"],"свет":["russian"],"свеча":["russian"],"свинья":["russian"],"свист":["russian"],"свитер":["russian"],"свобода":["russian"],"сводка":["russian"],"свой":["russian"],"свыше":["russian"],"связь":["russian"],"сдаться":["russian"],"сделать":["russian"],"сегмент":["russian"],"сегодня":["russian"],"седло":["russian"],"седой":["russian"],"седьмой":["russian"],"сезон":["russian"],"сейф":["russian"],"сейчас":["russian"],"секрет":["russian"],"сектор":["russian"],"секунда":["russian"],"семинар":["russian"],"семья":["russian"],"сенатор":["russian"],"сено":["russian"],"сенсация":["russian"],"сентябрь":["russian"],"сервис":["russian"],"сердце":["russian"],"середина":["russian"],"сержант":["russian"],"серия":["russian"],"серый":["russian"],"сессия":["russian"],"сесть":["russian"],"сетевой":["russian"],"сжатый":["russian"],"сжечь":["russian"],"сзади":["russian"],"сигнал":["russian"],"сиденье":["russian"],"сила":["russian"],"силуэт":["russian"],"сильный":["russian"],"символ":["russian"],"симпатия":["russian"],"симфония":["russian"],"синий":["russian"],"синтез":["russian"],"синяк":["russian"],"сирень":["russian"],"система":["russian"],"ситуация":["russian"],"сияние":["russian"],"сказать":["russian"],"скала":["russian"],"скамейка":["russian"],"скандал":["russian"],"скатерть":["russian"],"скачок":["russian"],"скважина":["russian"],"сквер":["russian"],"сквозь":["russian"],"скелет":["russian"],"скидка":["russian"],"склад":["russian"],"сколько":["russian"],"скорый":["russian"],"скосить":["russian"],"скот":["russian"],"скрипка":["russian"],"скудный":["russian"],"скука":["russian"],"слабый":["russian"],"слава":["russian"],"сладкий":["russian"],"слегка":["russian"],"след":["russian"],"слеза":["russian"],"слепой":["russian"],"слесарь":["russian"],"слишком":["russian"],"слово":["russian"],"слог":["russian"],"сложный":["russian"],"сломать":["russian"],"служба":["russian"],"слух":["russian"],"случай":["russian"],"слышать":["russian"],"слюна":["russian"],"смежный":["russian"],"смелый":["russian"],"сменить":["russian"],"смесь":["russian"],"сметана":["russian"],"смех":["russian"],"смола":["russian"],"смуглый":["russian"],"смутный":["russian"],"смущать":["russian"],"смысл":["russian"],"снайпер":["russian"],"снаряд":["russian"],"сначала":["russian"],"снег":["russian"],"снизу":["russian"],"сниться":["russian"],"сно��а":["russian"],"снять":["russian"],"собака":["russian"],"соблазн":["russian"],"собрание":["russian"],"событие":["russian"],"совесть":["russian"],"совсем":["russian"],"согласие":["russian"],"создать":["russian"],"сознание":["russian"],"созреть":["russian"],"сойтись":["russian"],"сокол":["russian"],"солдат":["russian"],"соленый":["russian"],"солнце":["russian"],"солома":["russian"],"сомнение":["russian"],"сонный":["russian"],"соперник":["russian"],"соратник":["russian"],"сорвать":["russian"],"сосед":["russian"],"сосиска":["russian"],"состав":["russian"],"сотня":["russian"],"соус":["russian"],"союз":["russian"],"спад":["russian"],"спальня":["russian"],"спасти":["russian"],"спектр":["russian"],"сперва":["russian"],"спешить":["russian"],"спина":["russian"],"спирт":["russian"],"список":["russian"],"спичка":["russian"],"сплав":["russian"],"спонсор":["russian"],"спор":["russian"],"способ":["russian"],"справка":["russian"],"спустя":["russian"],"спутник":["russian"],"сразу":["russian"],"средство":["russian"],"срок":["russian"],"срыв":["russian"],"ссора":["russian"],"ссылка":["russian"],"ставить":["russian"],"стадия":["russian"],"стакан":["russian"],"станция":["russian"],"старый":["russian"],"стая":["russian"],"стебель":["russian"],"стекло":["russian"],"стена":["russian"],"степень":["russian"],"стереть":["russian"],"стиль":["russian"],"стимул":["russian"],"стирать":["russian"],"стихи":["russian"],"стоить":["russian"],"стойка":["russian"],"стол":["russian"],"стонать":["russian"],"стопа":["russian"],"сторона":["russian"],"стоянка":["russian"],"страна":["russian"],"стричь":["russian"],"строгий":["russian"],"струя":["russian"],"студент":["russian"],"стук":["russian"],"ступня":["russian"],"стыдно":["russian"],"суббота":["russian"],"субъект":["russian"],"сувенир":["russian"],"сугроб":["russian"],"сугубо":["russian"],"судить":["russian"],"судно":["russian"],"судьба":["russian"],"суета":["russian"],"суметь":["russian"],"сумма":["russian"],"сумрак":["russian"],"сундук":["russian"],"супруг":["russian"],"суровый":["russian"],"сутки":["russian"],"сухой":["russian"],"суша":["russian"],"существо":["russian"],"сфера":["russian"],"схема":["russian"],"схожий":["russian"],"сценарий":["russian"],"счастье":["russian"],"считать":["russian"],"съезд":["russian"],"сыграть":["russian"],"сырой":["russian"],"сытый":["russian"],"сыщик":["russian"],"сюда":["russian"],"сюжет":["russian"],"сюрприз":["russian"],"тайна":["russian"],"также":["russian"],"такой":["russian"],"такси":["russian"],"тактика":["russian"],"талия":["russian"],"таможня":["russian"],"танец":["russian"],"таракан":["russian"],"тарелка":["russian"],"тариф":["russian"],"тащить":["russian"],"таять":["russian"],"тварь":["russian"],"театр":["russian"],"тезис":["russian"],"текст":["russian"],"текущий":["russian"],"телефон":["russian"],"тема":["russian"],"темнота":["russian"],"теневой":["russian"],"теннис":["russian"],"теория":["russian"],"теперь":["russian"],"тепло":["russian"],"терапия":["russian"],"терзать":["russian"],"термин":["russian"],"терпеть":["russian"],"терраса":["russian"],"терять":["russian"],"тесный":["russian"],"тетрадь":["russian"],"техника":["russian"],"течение":["russian"],"тигр":["russian"],"типовой":["russian"],"тираж":["russian"],"титул":["russian"],"тихий":["russian"],"ткань":["russian"],"товарищ":["russian"],"тоже":["russian"],"толпа":["russian"],"толстый":["russian"],"толчок":["russian"],"толщина":["russian"],"только":["russian"],"тонкий":["russian"],"тонна":["russian"],"топить":["russian"],"топор":["russian"],"торговля":["russian"],"тормоз":["russian"],"торчать":["russian"],"тотчас":["russian"],"точка":["russian"],"точно":["russian"],"тощий":["russian"],"трава":["russian"],"традиция":["russian"],"трактор":["russian"],"трамвай":["russian"],"траншея":["russian"],"трасса":["russian"],"тревога":["russian"],"трезвый":["russian"],"тренер":["russian"],"трепет":["russian"],"треск":["russian"],"третий":["russian"],"трещина":["russian"],"трибуна":["russian"],"тридцать":["russian"],"триста":["russian"],"триумф":["russian"],"трогать":["russian"],"тройка":["russian"],"тронуть":["russian"],"тропа":["russian"],"тротуар":["russian"],"трубка":["russian"],"труд":["russian"],"трюк":["russian"],"тряпка":["russian"],"туго":["russian"],"туловище":["russian"],"туман":["russian"],"тумбочка":["russian"],"тундра":["russian"],"тупик":["russian"],"турист":["russian"],"турнир":["russian"],"тусклый":["russian"],"туфля":["russian"],"туча":["russian"],"тысяча":["russian"],"тяга":["russian"],"тяжело":["russian"],"убежать":["russian"],"убогий":["russian"],"уборка":["russian"],"уважение":["russian"],"увезти":["russian"],"уволить":["russian"],"угадать":["russian"],"угол":["russian"],"угощать":["russian"],"угроза":["russian"],"угрюмый":["russian"],"удар":["russian"],"удачный":["russian"],"уделять":["russian"],"удивить":["russian"],"удобный":["russian"],"удочка":["russian"],"уезжать":["russian"],"ужин":["russian"],"узел":["russian"],"узкий":["russian"],"уйти":["russian"],"указание":["russian"],"уклон":["russian"],"украсть":["russian"],"укусить":["russian"],"улетать":["russian"],"улица":["russian"],"улыбка":["russian"],"умело":["russian"],"умение":["russian"],"умный":["russian"],"умолять":["russian"],"унести":["russian"],"унижать":["russian"],"унылый":["russian"],"упаковка":["russian"],"упасть":["russian"],"упорно":["russian"],"упрек":["russian"],"урна":["russian"],"уровень":["russian"],"урожай":["russian"],"уронить":["russian"],"усадьба":["russian"],"усатый":["russian"],"усвоить":["russian"],"усилие":["russian"],"условие":["russian"],"услуга":["russian"],"усмешка":["russian"],"успеть":["russian"],"устав":["russian"],"устоять":["russian"],"утечка":["russian"],"утешать":["russian"],"утро":["russian"],"уцелеть":["russian"],"участие":["russian"],"ученик":["russian"],"учесть":["russian"],"ущелье":["russian"],"ущерб":["russian"],"уютный":["russian"],"фабрика":["russian"],"фаворит":["russian"],"факел":["russian"],"факт":["russian"],"фамилия":["russian"],"фантазия":["russian"],"фасад":["russian"],"февраль":["russian"],"феномен":["russian"],"фермер":["russian"],"фигура":["russian"],"физика":["russian"],"филиал":["russian"],"философ":["russian"],"фильм":["russian"],"финал":["russian"],"флаг":["russian"],"флот":["russian"],"фойе":["russian"],"фокус":["russian"],"фонарь":["russian"],"фонд":["russian"],"фонтан":["russian"],"форма":["russian"],"форум":["russian"],"фото":["russian"],"фрагмент":["russian"],"фраза":["russian"],"фракция":["russian"],"фронт":["russian"],"фрукт":["russian"],"функция":["russian"],"фуражка":["russian"],"футбол":["russian"],"футляр":["russian"],"халат":["russian"],"хаос":["russian"],"характер":["russian"],"хата":["russian"],"хвалить":["russian"],"хватать":["russian"],"хвойный":["russian"],"хвост":["russian"],"химия":["russian"],"хирург":["russian"],"хитрый":["russian"],"хищник":["russian"],"хлеб":["russian"],"хлынуть":["russian"],"хмурый":["russian"],"ходить":["russian"],"хозяин":["russian"],"хоккей":["russian"],"холм":["russian"],"холст":["russian"],"хорошо":["russian"],"хотеть":["russian"],"храбрый":["russian"],"храм":["russian"],"хранить":["russian"],"хребет":["russian"],"хрен":["russian"],"хрипло":["russian"],"хроника":["russian"],"хрупкий":["russian"],"художник":["russian"],"худший":["russian"],"хулиган":["russian"],"хутор":["russian"],"царь":["russian"],"цветок":["russian"],"целевой":["russian"],"целиком":["russian"],"целое":["russian"],"цель":["russian"],"цензура":["russian"],"ценить":["russian"],"центр":["russian"],"цепной":["russian"],"цикл":["russian"],"цилиндр":["russian"],"цирк":["russian"],"цитата":["russian"],"цифра":["russian"],"чайник":["russian"],"часы":["russian"],"чашка":["russian"],"человек":["russian"],"челюсть":["russian"],"чемодан":["russian"],"чемпион":["russian"],"чепуха":["russian"],"червь":["russian"],"чердак":["russian"],"через":["russian"],"чернила":["russian"],"черта":["russian"],"чеснок":["russian"],"честно":["russian"],"четверть":["russian"],"четыре":["russian"],"число":["russian"],"чистый":["russian"],"читатель":["russian"],"чтение":["russian"],"чтобы":["russian"],"чувство":["russian"],"чудак":["russian"],"чудный":["russian"],"чудо":["russian"],"чужой":["russian"],"чулок":["russian"],"чума":["russian"],"чушь":["russian"],"чуять":["russian"],"шагать":["russian"],"шанс":["russian"],"шапка":["russian"],"шарик":["russian"],"шарф":["russian"],"шахматы":["russian"],"шашлык":["russian"],"шедевр":["russian"],"шептать":["russian"],"шерсть":["russian"],"шестой":["russian"],"шинель":["russian"],"ширина":["russian"],"шишка":["russian"],"шкаф":["russian"],"школа":["russian"],"шкура":["russian"],"шланг":["russian"],"шлем":["russian"],"шнур":["russian"],"шоколад":["russian"],"шорох":["russian"],"шоссе":["russian"],"шпион":["russian"],"шприц":["russian"],"штаб":["russian"],"штамм":["russian"],"штаны":["russian"],"штатный":["russian"],"штора":["russian"],"штраф":["russian"],"штурм":["russian"],"штык":["russian"],"шумно":["russian"],"шуршать":["russian"],"шутить":["russian"],"шутка":["russian"],"щедрый":["russian"],"щека":["russian"],"щенок":["russian"],"экзамен":["russian"],"экипаж":["russian"],"экономия":["russian"],"экран":["russian"],"эксперт":["russian"],"элемент":["russian"],"элитный":["russian"],"эмоция":["russian"],"энергия":["russian"],"эпизод":["russian"],"эпоха":["russian"],"эскиз":["russian"],"эстрада":["russian"],"этап":["russian"],"этика":["russian"],"этот":["russian"],"эфир":["russian"],"эффект":["russian"],"эшелон":["russian"],"юбилей":["russian"],"юбка":["russian"],"южный":["russian"],"юмор":["russian"],"юность":["russian"],"юрист":["russian"],"юстиция":["russian"],"яблоко":["russian"],"явление":["russian"],"ягода":["russian"],"ядро":["russian"],"язык":["russian"],"яйцо":["russian"],"якобы":["russian"],"якорь":["russian"],"январь":["russian"],"яркий":["russian"],"ярмарка":["russian"],"ярость":["russian"],"ясный":["russian"],"яхта":["russian"],"ячейка":["russian"],"ящик":["russian"],"ábaco":["spanish"],"abdomen":["spanish"],"abeja":["spanish"],"abierto":["spanish"],"abogado":["spanish"],"abono":["spanish"],"aborto":["spanish"],"abrazo":["spanish"],"abrir":["spanish"],"abuelo":["spanish"],"abuso":["spanish"],"acabar":["spanish"],"academia":["spanish"],"acceso":["spanish"],"acción":["spanish"],"aceite":["spanish"],"acelga":["spanish"],"acento":["spanish"],"aceptar":["spanish"],"ácido":["spanish"],"aclarar":["spanish"],"acné":["spanish"],"acoger":["spanish"],"acoso":["spanish"],"activo":["spanish"],"acto":["spanish"],"actriz":["spanish"],"actuar":["spanish"],"acudir":["spanish"],"acuerdo":["spanish"],"acusar":["spanish"],"adicto":["spanish"],"admitir":["spanish"],"adoptar":["spanish"],"adorno":["spanish"],"aduana":["spanish"],"adulto":["spanish"],"aéreo":["spanish"],"afectar":["spanish"],"afición":["spanish"],"afinar":["spanish"],"afirmar":["spanish"],"ágil":["spanish"],"agitar":["spanish"],"agonía":["spanish"],"agosto":["spanish"],"agotar":["spanish"],"agregar":["spanish"],"agrio":["spanish"],"agua":["spanish"],"agudo":["spanish"],"águila":["spanish"],"aguja":["spanish"],"ahogo":["spanish"],"ahorro":["spanish"],"aire":["spanish"],"aislar":["spanish"],"ajedrez":["spanish"],"ajeno":["spanish"],"ajuste":["spanish"],"alacrán":["spanish"],"alambre":["spanish"],"alarma":["spanish"],"alba":["spanish"],"álbum":["spanish"],"alcalde":["spanish"],"aldea":["spanish"],"alegre":["spanish"],"alejar":["spanish"],"alerta":["spanish"],"aleta":["spanish"],"alfiler":["spanish"],"alga":["spanish"],"algodón":["spanish"],"aliado":["spanish"],"aliento":["spanish"],"alivio":["spanish"],"alma":["spanish"],"almeja":["spanish"],"almíbar":["spanish"],"altar":["spanish"],"alteza":["spanish"],"altivo":["spanish"],"alto":["spanish"],"altura":["spanish"],"alumno":["spanish"],"alzar":["spanish"],"amable":["spanish"],"amante":["spanish"],"amapola":["spanish"],"amargo":["spanish"],"amasar":["spanish"],"ámbar":["spanish"],"ámbito":["spanish"],"ameno":["spanish"],"amigo":["spanish","turkish"],"amistad":["spanish"],"amor":["spanish"],"amparo":["spanish"],"amplio":["spanish"],"ancho":["spanish"],"anciano":["spanish"],"ancla":["spanish"],"andar":["spanish"],"andén":["spanish"],"anemia":["spanish"],"ángulo":["spanish"],"anillo":["spanish"],"ánimo":["spanish"],"anís":["spanish"],"anotar":["spanish"],"antena":["spanish"],"antiguo":["spanish"],"antojo":["spanish"],"anual":["spanish"],"anular":["spanish"],"anuncio":["spanish"],"añadir":["spanish"],"añejo":["spanish"],"año":["spanish"],"apagar":["spanish"],"aparato":["spanish"],"apetito":["spanish"],"apio":["spanish"],"aplicar":["spanish"],"apodo":["spanish"],"aporte":["spanish"],"apoyo":["spanish"],"aprender":["spanish"],"aprobar":["spanish"],"apuesta":["spanish"],"apuro":["spanish"],"arado":["spanish"],"araña":["spanish"],"arar":["spanish"],"árbitro":["spanish"],"árbol":["spanish"],"arbusto":["spanish"],"archivo":["spanish"],"arco":["spanish"],"arder":["spanish"],"ardilla":["spanish"],"arduo":["spanish"],"área":["spanish"],"árido":["spanish"],"aries":["spanish"],"armonía":["spanish"],"arnés":["spanish"],"aroma":["spanish","turkish"],"arpa":["spanish"],"arpón":["spanish"],"arreglo":["spanish"],"arroz":["spanish"],"arruga":["spanish"],"arte":["spanish"],"artista":["spanish"],"asa":["spanish"],"asado":["spanish"],"asalto":["spanish"],"ascenso":["spanish"],"asegurar":["spanish"],"aseo":["spanish"],"asesor":["spanish"],"asiento":["spanish"],"asilo":["spanish"],"asistir":["spanish"],"asno":["spanish"],"asombro":["spanish"],"áspero":["spanish"],"astilla":["spanish"],"astro":["spanish"],"astuto":["spanish"],"asumir":["spanish"],"asunto":["spanish"],"atajo":["spanish"],"ataque":["spanish"],"atar":["spanish"],"atento":["spanish"],"ateo":["spanish"],"ático":["spanish"],"atleta":["spanish"],"átomo":["spanish"],"atraer":["spanish"],"atroz":["spanish"],"atún":["spanish"],"audaz":["spanish"],"audio":["spanish"],"auge":["spanish"],"aula":["spanish"],"aumento":["spanish"],"ausente":["spanish"],"autor":["spanish"],"aval":["spanish"],"avance":["spanish"],"avaro":["spanish"],"ave":["spanish"],"avellana":["spanish"],"avena":["spanish"],"avestruz":["spanish"],"avión":["spanish"],"aviso":["spanish"],"ayer":["spanish"],"ayuda":["spanish"],"ayuno":["spanish"],"azafrán":["spanish"],"azar":["spanish"],"azote":["spanish"],"azúcar":["spanish"],"azufre":["spanish"],"azul":["spanish"],"baba":["spanish"],"babor":["spanish"],"bache":["spanish"],"bahía":["spanish"],"baile":["spanish"],"bajar":["spanish"],"balanza":["spanish"],"balcón":["spanish"],"balde":["spanish"],"bambú":["spanish"],"banco":["spanish"],"banda":["spanish"],"baño":["spanish"],"barba":["spanish"],"barco":["spanish"],"barniz":["spanish"],"barro":["spanish"],"báscula":["spanish"],"bastón":["spanish"],"basura":["spanish"],"batalla":["spanish"],"batería":["spanish"],"batir":["spanish"],"batuta":["spanish"],"baúl":["spanish"],"bazar":["spanish"],"bebé":["spanish"],"bebida":["spanish"],"bello":["spanish"],"besar":["spanish"],"beso":["spanish"],"bestia":["spanish"],"bicho":["spanish"],"bien":["spanish"],"bingo":["spanish"],"blanco":["spanish"],"bloque":["spanish"],"blusa":["spanish"],"boa":["spanish"],"bobina":["spanish"],"bobo":["spanish"],"boca":["spanish"],"bocina":["spanish"],"boda":["spanish"],"bodega":["spanish"],"boina":["spanish"],"bola":["spanish"],"bolero":["spanish","turkish"],"bolsa":["spanish"],"bomba":["spanish"],"bondad":["spanish"],"bonito":["spanish"],"bono":["spanish"],"bonsái":["spanish"],"borde":["spanish"],"borrar":["spanish"],"bosque":["spanish"],"bote":["spanish"],"botín":["spanish"],"bóveda":["spanish"],"bozal":["spanish"],"bravo":["spanish"],"brazo":["spanish"],"brecha":["spanish"],"breve":["spanish"],"brillo":["spanish"],"brinco":["spanish"],"brisa":["spanish"],"broca":["spanish"],"broma":["spanish"],"bronce":["spanish"],"brote":["spanish"],"bruja":["spanish"],"brusco":["spanish"],"bruto":["spanish"],"buceo":["spanish"],"bucle":["spanish"],"bueno":["spanish"],"buey":["spanish"],"bufanda":["spanish"],"bufón":["spanish"],"búho":["spanish"],"buitre":["spanish"],"bulto":["spanish"],"burbuja":["spanish"],"burla":["spanish"],"burro":["spanish"],"buscar":["spanish"],"butaca":["spanish"],"buzón":["spanish"],"caballo":["spanish"],"cabeza":["spanish"],"cabina":["spanish"],"cabra":["spanish"],"cacao":["spanish"],"cadáver":["spanish"],"cadena":["spanish"],"caer":["spanish"],"café":["spanish"],"caída":["spanish"],"caimán":["spanish"],"caja":["spanish"],"cajón":["spanish"],"cal":["spanish"],"calamar":["spanish"],"calcio":["spanish"],"caldo":["spanish"],"calidad":["spanish"],"calle":["spanish"],"calma":["spanish"],"calor":["spanish"],"calvo":["spanish"],"cama":["spanish"],"cambio":["spanish"],"camello":["spanish"],"camino":["spanish"],"campo":["spanish"],"cáncer":["spanish"],"candil":["spanish"],"canela":["spanish"],"canguro":["spanish"],"canica":["spanish"],"canto":["spanish"],"caña":["spanish"],"cañón":["spanish"],"caoba":["spanish"],"caos":["spanish"],"capaz":["spanish"],"capitán":["spanish"],"capote":["spanish"],"captar":["spanish"],"capucha":["spanish"],"cara":["spanish"],"carbón":["spanish"],"cárcel":["spanish"],"careta":["spanish"],"carga":["spanish"],"cariño":["spanish"],"carne":["spanish"],"carpeta":["spanish"],"carro":["spanish"],"carta":["spanish"],"casa":["spanish"],"casco":["spanish"],"casero":["spanish"],"caspa":["spanish"],"castor":["spanish"],"catorce":["spanish"],"catre":["spanish"],"caudal":["spanish"],"causa":["spanish"],"cazo":["spanish"],"cebolla":["spanish"],"ceder":["spanish"],"cedro":["spanish"],"celda":["spanish"],"célebre":["spanish"],"celoso":["spanish"],"célula":["spanish"],"cemento":["spanish"],"ceniza":["spanish"],"centro":["spanish"],"cerca":["spanish"],"cerdo":["spanish"],"cereza":["spanish"],"cero":["spanish"],"cerrar":["spanish"],"certeza":["spanish"],"césped":["spanish"],"cetro":["spanish"],"chacal":["spanish"],"chaleco":["spanish"],"champú":["spanish"],"chancla":["spanish"],"chapa":["spanish"],"charla":["spanish"],"chico":["spanish"],"chiste":["spanish"],"chivo":["spanish"],"choque":["spanish"],"choza":["spanish"],"chuleta":["spanish"],"chupar":["spanish"],"ciclón":["spanish"],"ciego":["spanish"],"cielo":["spanish"],"cien":["spanish"],"cierto":["spanish"],"cifra":["spanish"],"cigarro":["spanish"],"cima":["spanish"],"cinco":["spanish"],"cine":["spanish"],"cinta":["spanish"],"ciprés":["spanish"],"circo":["spanish"],"ciruela":["spanish"],"cisne":["spanish"],"cita":["spanish"],"ciudad":["spanish"],"clamor":["spanish"],"clan":["spanish"],"claro":["spanish"],"clase":["spanish"],"clave":["spanish"],"cliente":["spanish"],"clima":["spanish"],"clínica":["spanish"],"cobre":["spanish"],"cocción":["spanish"],"cochino":["spanish"],"cocina":["spanish"],"coco":["spanish"],"código":["spanish"],"codo":["spanish"],"cofre":["spanish"],"coger":["spanish"],"cohete":["spanish"],"cojín":["spanish"],"cojo":["spanish"],"cola":["spanish"],"colcha":["spanish"],"colegio":["spanish"],"colgar":["spanish"],"colina":["spanish"],"collar":["spanish"],"colmo":["spanish"],"columna":["spanish"],"combate":["spanish"],"comer":["spanish"],"comida":["spanish"],"cómodo":["spanish"],"compra":["spanish"],"conde":["spanish"],"conejo":["spanish"],"conga":["spanish"],"conocer":["spanish"],"consejo":["spanish"],"contar":["spanish"],"copa":["spanish"],"copia":["spanish"],"corazón":["spanish"],"corbata":["spanish"],"corcho":["spanish"],"cordón":["spanish"],"corona":["spanish"],"correr":["spanish"],"coser":["spanish"],"cosmos":["spanish"],"costa":["spanish"],"cráneo":["spanish"],"cráter":["spanish"],"crear":["spanish"],"crecer":["spanish"],"creído":["spanish"],"crema":["spanish"],"cría":["spanish"],"crimen":["spanish"],"cripta":["spanish"],"crisis":["spanish"],"cromo":["spanish"],"crónica":["spanish"],"croqueta":["spanish"],"crudo":["spanish"],"cruz":["spanish"],"cuadro":["spanish"],"cuarto":["spanish"],"cuatro":["spanish"],"cubo":["spanish"],"cubrir":["spanish"],"cuchara":["spanish"],"cuello":["spanish"],"cuento":["spanish"],"cuerda":["spanish"],"cuesta":["spanish"],"cueva":["spanish"],"cuidar":["spanish"],"culebra":["spanish"],"culpa":["spanish"],"culto":["spanish"],"cumbre":["spanish"],"cumplir":["spanish"],"cuna":["spanish"],"cuneta":["spanish"],"cuota":["spanish"],"cupón":["spanish"],"cúpula":["spanish"],"curar":["spanish"],"curioso":["spanish"],"curso":["spanish"],"curva":["spanish"],"cutis":["spanish"],"dama":["spanish"],"danza":["spanish"],"dar":["spanish"],"dardo":["spanish"],"dátil":["spanish"],"deber":["spanish"],"débil":["spanish"],"década":["spanish"],"decir":["spanish"],"dedo":["spanish"],"defensa":["spanish"],"definir":["spanish"],"dejar":["spanish"],"delfín":["spanish"],"delgado":["spanish"],"delito":["spanish"],"demora":["spanish"],"denso":["spanish"],"dental":["spanish"],"deporte":["spanish"],"derecho":["spanish"],"derrota":["spanish"],"desayuno":["spanish"],"deseo":["spanish"],"desfile":["spanish"],"desnudo":["spanish"],"destino":["spanish"],"desvío":["spanish"],"detalle":["spanish"],"detener":["spanish"],"deuda":["spanish"],"día":["spanish"],"diablo":["spanish"],"diadema":["spanish"],"diamante":["spanish"],"diana":["spanish"],"diario":["spanish"],"dibujo":["spanish"],"dictar":["spanish"],"diente":["spanish"],"dieta":["spanish"],"diez":["spanish"],"difícil":["spanish"],"digno":["spanish"],"dilema":["spanish"],"diluir":["spanish"],"dinero":["spanish"],"directo":["spanish"],"dirigir":["spanish"],"disco":["spanish"],"diseño":["spanish"],"disfraz":["spanish"],"diva":["spanish"],"divino":["spanish"],"doble":["spanish"],"doce":["spanish"],"dolor":["spanish"],"domingo":["spanish"],"don":["spanish"],"donar":["spanish"],"dorado":["spanish"],"dormir":["spanish"],"dorso":["spanish"],"dos":["spanish"],"dosis":["spanish"],"dragón":["spanish"],"droga":["spanish"],"ducha":["spanish"],"duda":["spanish"],"duelo":["spanish"],"dueño":["spanish"],"dulce":["spanish"],"dúo":["spanish"],"duque":["spanish"],"durar":["spanish"],"dureza":["spanish"],"duro":["spanish"],"ébano":["spanish"],"ebrio":["spanish"],"echar":["spanish"],"eco":["spanish"],"ecuador":["spanish"],"edad":["spanish"],"edición":["spanish"],"edificio":["spanish"],"editor":["spanish"],"educar":["spanish"],"efecto":["spanish"],"eficaz":["spanish"],"eje":["spanish"],"ejemplo":["spanish"],"elefante":["spanish"],"elegir":["spanish"],"elemento":["spanish"],"elevar":["spanish"],"elipse":["spanish"],"élite":["spanish"],"elixir":["spanish"],"elogio":["spanish"],"eludir":["spanish"],"embudo":["spanish"],"emitir":["spanish"],"emoción":["spanish"],"empate":["spanish"],"empeño":["spanish"],"empleo":["spanish"],"empresa":["spanish"],"enano":["spanish"],"encargo":["spanish"],"enchufe":["spanish"],"encía":["spanish"],"enemigo":["spanish"],"enero":["spanish"],"enfado":["spanish"],"enfermo":["spanish"],"engaño":["spanish"],"enigma":["spanish"],"enlace":["spanish"],"enorme":["spanish"],"enredo":["spanish"],"ensayo":["spanish"],"enseñar":["spanish"],"entero":["spanish"],"entrar":["spanish"],"envase":["spanish"],"envío":["spanish"],"época":["spanish"],"equipo":["spanish"],"erizo":["spanish"],"escala":["spanish"],"escena":["spanish"],"escolar":["spanish"],"escribir":["spanish"],"escudo":["spanish"],"esencia":["spanish"],"esfera":["spanish"],"esfuerzo":["spanish"],"espada":["spanish"],"espejo":["spanish"],"espía":["spanish"],"esposa":["spanish"],"espuma":["spanish"],"esquí":["spanish"],"estar":["spanish"],"este":["spanish"],"estilo":["spanish"],"estufa":["spanish"],"etapa":["spanish"],"eterno":["spanish"],"ética":["spanish"],"etnia":["spanish"],"evadir":["spanish"],"evaluar":["spanish"],"evento":["spanish"],"evitar":["spanish"],"exacto":["spanish"],"examen":["spanish"],"exceso":["spanish"],"excusa":["spanish"],"exento":["spanish"],"exigir":["spanish"],"exilio":["spanish"],"existir":["spanish"],"éxito":["spanish"],"experto":["spanish"],"explicar":["spanish"],"exponer":["spanish"],"extremo":["spanish"],"fábrica":["spanish"],"fábula":["spanish"],"fachada":["spanish"],"fácil":["spanish"],"factor":["spanish"],"faena":["spanish"],"faja":["spanish"],"falda":["spanish"],"fallo":["spanish"],"falso":["spanish"],"faltar":["spanish"],"fama":["spanish"],"familia":["spanish"],"famoso":["spanish"],"faraón":["spanish"],"farmacia":["spanish"],"farol":["spanish"],"farsa":["spanish"],"fase":["spanish"],"fatiga":["spanish"],"fauna":["spanish","turkish"],"favor":["spanish"],"fax":["spanish"],"febrero":["spanish"],"fecha":["spanish"],"feliz":["spanish"],"feo":["spanish"],"feria":["spanish"],"feroz":["spanish"],"fértil":["spanish"],"fervor":["spanish"],"festín":["spanish"],"fiable":["spanish"],"fianza":["spanish"],"fiar":["spanish"],"fibra":["spanish"],"ficción":["spanish"],"ficha":["spanish"],"fideo":["spanish"],"fiebre":["spanish"],"fiel":["spanish"],"fiera":["spanish"],"fiesta":["spanish"],"figura":["spanish"],"fijar":["spanish"],"fijo":["spanish"],"fila":["spanish"],"filete":["spanish"],"filial":["spanish"],"filtro":["spanish"],"fin":["spanish"],"finca":["spanish"],"fingir":["spanish"],"finito":["spanish"],"firma":["spanish"],"flaco":["spanish"],"flauta":["spanish"],"flecha":["spanish"],"flor":["spanish"],"flota":["spanish"],"fluir":["spanish"],"flujo":["spanish"],"flúor":["spanish"],"fobia":["spanish"],"foca":["spanish"],"fogata":["spanish"],"fogón":["spanish"],"folio":["spanish"],"folleto":["spanish"],"fondo":["spanish"],"forma":["spanish"],"forro":["spanish"],"fortuna":["spanish"],"forzar":["spanish"],"fosa":["spanish"],"foto":["spanish"],"fracaso":["spanish"],"frágil":["spanish"],"franja":["spanish"],"frase":["spanish"],"fraude":["spanish"],"freír":["spanish"],"freno":["spanish"],"fresa":["spanish"],"frío":["spanish"],"frito":["spanish"],"fruta":["spanish"],"fuego":["spanish"],"fuente":["spanish"],"fuerza":["spanish"],"fuga":["spanish"],"fumar":["spanish"],"función":["spanish"],"funda":["spanish"],"furgón":["spanish"],"furia":["spanish"],"fusil":["spanish"],"fútbol":["spanish"],"futuro":["spanish"],"gacela":["spanish"],"gafas":["spanish"],"gaita":["spanish"],"gajo":["spanish"],"gala":["spanish"],"galería":["spanish"],"gallo":["spanish"],"gamba":["spanish"],"ganar":["spanish"],"gancho":["spanish"],"ganga":["spanish"],"ganso":["spanish"],"garaje":["spanish"],"garza":["spanish"],"gasolina":["spanish"],"gastar":["spanish"],"gato":["spanish"],"gavilán":["spanish"],"gemelo":["spanish"],"gemir":["spanish"],"gen":["spanish"],"género":["spanish"],"genio":["spanish"],"gente":["spanish"],"geranio":["spanish"],"gerente":["spanish"],"germen":["spanish"],"gesto":["spanish"],"gigante":["spanish"],"gimnasio":["spanish"],"girar":["spanish"],"giro":["spanish"],"glaciar":["spanish"],"globo":["spanish"],"gloria":["spanish"],"gol":["spanish"],"golfo":["spanish"],"goloso":["spanish"],"golpe":["spanish"],"goma":["spanish"],"gordo":["spanish"],"gorila":["spanish"],"gorra":["spanish"],"gota":["spanish"],"goteo":["spanish"],"gozar":["spanish"],"grada":["spanish"],"gráfico":["spanish"],"grano":["spanish"],"grasa":["spanish"],"gratis":["spanish"],"grave":["spanish"],"grieta":["spanish"],"grillo":["spanish"],"gripe":["spanish"],"gris":["spanish"],"grito":["spanish"],"grosor":["spanish"],"grúa":["spanish"],"grueso":["spanish"],"grumo":["spanish"],"grupo":["spanish"],"guante":["spanish"],"guapo":["spanish"],"guardia":["spanish"],"guerra":["spanish"],"guía":["spanish"],"guiño":["spanish"],"guion":["spanish"],"guiso":["spanish"],"guitarra":["spanish"],"gusano":["spanish"],"gustar":["spanish"],"haber":["spanish","turkish"],"hábil":["spanish"],"hablar":["spanish"],"hacer":["spanish"],"hacha":["spanish"],"hada":["spanish"],"hallar":["spanish"],"hamaca":["spanish"],"harina":["spanish"],"haz":["spanish"],"hazaña":["spanish"],"hebilla":["spanish"],"hebra":["spanish"],"hecho":["spanish"],"helado":["spanish"],"helio":["spanish"],"hembra":["spanish"],"herir":["spanish"],"hermano":["spanish"],"héroe":["spanish"],"hervir":["spanish"],"hielo":["spanish"],"hierro":["spanish"],"hígado":["spanish"],"higiene":["spanish"],"hijo":["spanish"],"himno":["spanish"],"historia":["spanish"],"hocico":["spanish"],"hogar":["spanish"],"hoguera":["spanish"],"hoja":["spanish"],"hombre":["spanish"],"hongo":["spanish"],"honor":["spanish"],"honra":["spanish"],"hora":["spanish"],"hormiga":["spanish"],"horno":["spanish"],"hostil":["spanish"],"hoyo":["spanish"],"hueco":["spanish"],"huelga":["spanish"],"huerta":["spanish"],"hueso":["spanish"],"huevo":["spanish"],"huida":["spanish"],"huir":["spanish"],"humano":["spanish"],"húmedo":["spanish"],"humilde":["spanish"],"humo":["spanish"],"hundir":["spanish"],"huracán":["spanish"],"hurto":["spanish"],"icono":["spanish"],"ideal":["spanish"],"idioma":["spanish"],"ídolo":["spanish"],"iglesia":["spanish"],"iglú":["spanish"],"igual":["spanish"],"ilegal":["spanish"],"ilusión":["spanish"],"imagen":["spanish"],"imán":["spanish"],"imitar":["spanish"],"impar":["spanish"],"imperio":["spanish"],"imponer":["spanish"],"impulso":["spanish"],"incapaz":["spanish"],"índice":["spanish"],"inerte":["spanish"],"infiel":["spanish"],"informe":["spanish"],"ingenio":["spanish"],"inicio":["spanish"],"inmenso":["spanish"],"inmune":["spanish"],"innato":["spanish"],"insecto":["spanish"],"instante":["spanish"],"interés":["spanish"],"íntimo":["spanish"],"intuir":["spanish"],"inútil":["spanish"],"invierno":["spanish"],"ira":["spanish"],"iris":["spanish"],"ironía":["spanish"],"isla":["spanish"],"islote":["spanish"],"jabalí":["spanish"],"jabón":["spanish"],"jamón":["spanish"],"jarabe":["spanish"],"jardín":["spanish"],"jarra":["spanish"],"jaula":["spanish"],"jazmín":["spanish"],"jefe":["spanish"],"jeringa":["spanish"],"jinete":["spanish"],"jornada":["spanish"],"joroba":["spanish"],"joven":["spanish"],"joya":["spanish"],"juerga":["spanish"],"jueves":["spanish"],"juez":["spanish"],"jugador":["spanish"],"jugo":["spanish"],"juguete":["spanish"],"juicio":["spanish"],"junco":["spanish"],"jungla":["spanish"],"junio":["spanish"],"juntar":["spanish"],"júpiter":["spanish"],"jurar":["spanish"],"justo":["spanish"],"juvenil":["spanish"],"juzgar":["spanish"],"kilo":["spanish"],"koala":["spanish"],"labio":["spanish"],"lacio":["spanish"],"lacra":["spanish"],"lado":["spanish"],"ladrón":["spanish"],"lagarto":["spanish"],"lágrima":["spanish"],"laguna":["spanish"],"laico":["spanish"],"lamer":["spanish"],"lámina":["spanish"],"lámpara":["spanish"],"lana":["spanish"],"lancha":["spanish"],"langosta":["spanish"],"lanza":["spanish"],"lápiz":["spanish"],"largo":["spanish"],"larva":["spanish"],"lástima":["spanish"],"lata":["spanish"],"látex":["spanish"],"latir":["spanish"],"laurel":["spanish"],"lavar":["spanish"],"lazo":["spanish"],"leal":["spanish"],"lección":["spanish"],"leche":["spanish"],"lector":["spanish"],"leer":["spanish"],"legión":["spanish"],"legumbre":["spanish"],"lejano":["spanish"],"lengua":["spanish"],"lento":["spanish"],"leña":["spanish"],"león":["spanish"],"leopardo":["spanish"],"lesión":["spanish"],"letal":["spanish"],"letra":["spanish"],"leve":["spanish"],"leyenda":["spanish"],"libertad":["spanish"],"libro":["spanish"],"licor":["spanish"],"líder":["spanish"],"lidiar":["spanish"],"lienzo":["spanish"],"liga":["spanish"],"ligero":["spanish"],"lima":["spanish"],"límite":["spanish"],"limón":["spanish"],"limpio":["spanish"],"lince":["spanish"],"lindo":["spanish"],"línea":["spanish"],"lingote":["spanish"],"lino":["spanish"],"linterna":["spanish"],"líquido":["spanish"],"liso":["spanish"],"lista":["spanish"],"litera":["spanish"],"litio":["spanish"],"litro":["spanish"],"llaga":["spanish"],"llama":["spanish"],"llanto":["spanish"],"llave":["spanish"],"llegar":["spanish"],"llenar":["spanish"],"llevar":["spanish"],"llorar":["spanish"],"llover":["spanish"],"lluvia":["spanish"],"lobo":["spanish"],"loción":["spanish"],"loco":["spanish"],"locura":["spanish"],"lógica":["spanish"],"logro":["spanish"],"lombriz":["spanish"],"lomo":["spanish"],"lonja":["spanish"],"lote":["spanish"],"lucha":["spanish"],"lucir":["spanish"],"lugar":["spanish"],"lujo":["spanish"],"luna":["spanish"],"lunes":["spanish"],"lupa":["spanish"],"lustro":["spanish"],"luto":["spanish"],"luz":["spanish"],"maceta":["spanish"],"macho":["spanish"],"madera":["spanish"],"madre":["spanish"],"maduro":["spanish"],"maestro":["spanish"],"mafia":["spanish"],"magia":["spanish"],"mago":["spanish"],"maíz":["spanish"],"maldad":["spanish"],"maleta":["spanish"],"malla":["spanish"],"malo":["spanish"],"mamá":["spanish"],"mambo":["spanish"],"mamut":["spanish"],"manco":["spanish"],"mando":["spanish"],"manejar":["spanish"],"manga":["spanish"],"maniquí":["spanish"],"manjar":["spanish"],"mano":["spanish"],"manso":["spanish"],"manta":["spanish"],"mañana":["spanish"],"mapa":["spanish"],"máquina":["spanish"],"mar":["spanish"],"marco":["spanish"],"marea":["spanish"],"marfil":["spanish"],"margen":["spanish"],"marido":["spanish"],"mármol":["spanish"],"marrón":["spanish"],"martes":["spanish"],"marzo":["spanish"],"masa":["spanish"],"máscara":["spanish"],"masivo":["spanish"],"matar":["spanish"],"materia":["spanish"],"matiz":["spanish"],"matriz":["spanish"],"máximo":["spanish"],"mayor":["spanish"],"mazorca":["spanish"],"mecha":["spanish"],"medalla":["spanish"],"medio":["spanish"],"médula":["spanish"],"mejilla":["spanish"],"mejor":["spanish"],"melena":["spanish"],"melón":["spanish"],"memoria":["spanish"],"menor":["spanish"],"mensaje":["spanish"],"mente":["spanish"],"menú":["spanish"],"mercado":["spanish"],"merengue":["spanish"],"mérito":["spanish"],"mes":["spanish"],"mesón":["spanish"],"meta":["spanish"],"meter":["spanish"],"método":["spanish"],"metro":["spanish"],"mezcla":["spanish"],"miedo":["spanish"],"miel":["spanish"],"miembro":["spanish"],"miga":["spanish"],"mil":["spanish"],"milagro":["spanish"],"militar":["spanish"],"millón":["spanish"],"mimo":["spanish"],"mina":["spanish"],"minero":["spanish"],"mínimo":["spanish"],"minuto":["spanish"],"miope":["spanish"],"mirar":["spanish"],"misa":["spanish"],"miseria":["spanish"],"misil":["spanish"],"mismo":["spanish"],"mitad":["spanish"],"mito":["spanish"],"mochila":["spanish"],"moción":["spanish"],"moda":["spanish"],"modelo":["spanish"],"moho":["spanish"],"mojar":["spanish"],"molde":["spanish"],"moler":["spanish"],"molino":["spanish"],"momento":["spanish"],"momia":["spanish"],"monarca":["spanish"],"moneda":["spanish"],"monja":["spanish"],"monto":["spanish"],"moño":["spanish"],"morada":["spanish"],"morder":["spanish"],"moreno":["spanish"],"morir":["spanish"],"morro":["spanish"],"morsa":["spanish"],"mortal":["spanish"],"mosca":["spanish"],"mostrar":["spanish"],"motivo":["spanish"],"mover":["spanish"],"móvil":["spanish"],"mozo":["spanish"],"mucho":["spanish"],"mudar":["spanish"],"mueble":["spanish"],"muela":["spanish"],"muerte":["spanish"],"muestra":["spanish"],"mugre":["spanish"],"mujer":["spanish"],"mula":["spanish"],"muleta":["spanish"],"multa":["spanish"],"mundo":["spanish"],"muñeca":["spanish"],"mural":["spanish"],"muro":["spanish"],"músculo":["spanish"],"museo":["spanish"],"musgo":["spanish"],"música":["spanish"],"muslo":["spanish"],"nácar":["spanish"],"nación":["spanish"],"nadar":["spanish"],"naipe":["spanish"],"naranja":["spanish"],"nariz":["spanish"],"narrar":["spanish"],"nasal":["spanish"],"natal":["spanish"],"nativo":["spanish"],"natural":["spanish"],"náusea":["spanish"],"naval":["spanish"],"nave":["spanish"],"navidad":["spanish"],"necio":["spanish"],"néctar":["spanish"],"negar":["spanish"],"negocio":["spanish"],"negro":["spanish"],"neón":["spanish"],"nervio":["spanish"],"neto":["spanish"],"neutro":["spanish"],"nevar":["spanish"],"nevera":["spanish"],"nicho":["spanish"],"nido":["spanish"],"niebla":["spanish"],"nieto":["spanish"],"niñez":["spanish"],"niño":["spanish"],"nítido":["spanish"],"nivel":["spanish"],"nobleza":["spanish"],"noche":["spanish"],"nómina":["spanish"],"noria":["spanish"],"norma":["spanish"],"norte":["spanish"],"nota":["spanish"],"noticia":["spanish"],"novato":["spanish"],"novela":["spanish"],"novio":["spanish"],"nube":["spanish"],"nuca":["spanish"],"núcleo":["spanish"],"nudillo":["spanish"],"nudo":["spanish"],"nuera":["spanish"],"nueve":["spanish"],"nuez":["spanish"],"nulo":["spanish"],"número":["spanish"],"nutria":["spanish"],"oasis":["spanish"],"obeso":["spanish"],"obispo":["spanish"],"objeto":["spanish"],"obra":["spanish"],"obrero":["spanish"],"observar":["spanish"],"obtener":["spanish"],"obvio":["spanish"],"oca":["spanish"],"ocaso":["spanish"],"océano":["spanish"],"ochenta":["spanish"],"ocho":["spanish"],"ocio":["spanish"],"ocre":["spanish"],"octavo":["spanish"],"octubre":["spanish"],"oculto":["spanish"],"ocupar":["spanish"],"ocurrir":["spanish"],"odiar":["spanish"],"odio":["spanish"],"odisea":["spanish"],"oeste":["spanish"],"ofensa":["spanish"],"oferta":["spanish"],"oficio":["spanish"],"ofrecer":["spanish"],"ogro":["spanish"],"oído":["spanish"],"oír":["spanish"],"ojo":["spanish"],"ola":["spanish"],"oleada":["spanish"],"olfato":["spanish"],"olivo":["spanish"],"olla":["spanish"],"olmo":["spanish"],"olor":["spanish"],"olvido":["spanish"],"ombligo":["spanish"],"onda":["spanish"],"onza":["spanish"],"opaco":["spanish"],"opción":["spanish"],"ópera":["spanish"],"opinar":["spanish"],"oponer":["spanish"],"optar":["spanish"],"óptica":["spanish"],"opuesto":["spanish"],"oración":["spanish"],"orador":["spanish"],"oral":["spanish","turkish"],"órbita":["spanish"],"orca":["spanish"],"orden":["spanish"],"oreja":["spanish"],"órgano":["spanish"],"orgía":["spanish"],"orgullo":["spanish"],"oriente":["spanish"],"origen":["spanish"],"orilla":["spanish"],"oro":["spanish"],"orquesta":["spanish"],"oruga":["spanish"],"osadía":["spanish"],"oscuro":["spanish"],"osezno":["spanish"],"oso":["spanish"],"ostra":["spanish"],"otoño":["spanish"],"otro":["spanish"],"oveja":["spanish"],"óvulo":["spanish"],"óxido":["spanish"],"oxígeno":["spanish"],"oyente":["spanish"],"ozono":["spanish"],"pacto":["spanish"],"padre":["spanish"],"paella":["spanish"],"página":["spanish"],"pago":["spanish"],"país":["spanish"],"pájaro":["spanish"],"palabra":["spanish"],"palco":["spanish"],"paleta":["spanish"],"pálido":["spanish"],"palma":["spanish"],"paloma":["spanish"],"palpar":["spanish"],"pan":["spanish"],"panal":["spanish"],"pánico":["spanish"],"pantera":["spanish"],"pañuelo":["spanish"],"papá":["spanish"],"papel":["spanish"],"papilla":["spanish"],"paquete":["spanish"],"parar":["spanish"],"parcela":["spanish"],"pared":["spanish"],"parir":["spanish"],"paro":["spanish"],"párpado":["spanish"],"parque":["spanish"],"párrafo":["spanish"],"parte":["spanish"],"pasar":["spanish"],"paseo":["spanish"],"pasión":["spanish"],"paso":["spanish"],"pasta":["spanish"],"pata":["spanish"],"patio":["spanish"],"patria":["spanish"],"pausa":["spanish"],"pauta":["spanish"],"pavo":["spanish"],"payaso":["spanish"],"peatón":["spanish"],"pecado":["spanish"],"pecera":["spanish"],"pecho":["spanish"],"pedal":["spanish","turkish"],"pedir":["spanish"],"pegar":["spanish"],"peine":["spanish"],"pelar":["spanish"],"peldaño":["spanish"],"pelea":["spanish"],"peligro":["spanish"],"pellejo":["spanish"],"pelo":["spanish"],"peluca":["spanish"],"pena":["spanish","turkish"],"pensar":["spanish"],"peñón":["spanish"],"peón":["spanish"],"peor":["spanish"],"pepino":["spanish"],"pequeño":["spanish"],"pera":["spanish"],"percha":["spanish"],"perder":["spanish"],"pereza":["spanish"],"perfil":["spanish"],"perico":["spanish"],"perla":["spanish"],"permiso":["spanish"],"perro":["spanish"],"persona":["spanish"],"pesa":["spanish"],"pesca":["spanish"],"pésimo":["spanish"],"pestaña":["spanish"],"pétalo":["spanish"],"petróleo":["spanish"],"pez":["spanish"],"pezuña":["spanish"],"picar":["spanish"],"pichón":["spanish"],"pie":["spanish"],"piedra":["spanish"],"pierna":["spanish"],"pieza":["spanish"],"pijama":["spanish"],"pilar":["spanish"],"piloto":["spanish"],"pimienta":["spanish"],"pino":["spanish"],"pintor":["spanish"],"pinza":["spanish"],"piña":["spanish"],"piojo":["spanish"],"pipa":["spanish"],"pirata":["spanish"],"pisar":["spanish"],"piscina":["spanish"],"piso":["spanish"],"pista":["spanish"],"pitón":["spanish"],"pizca":["spanish"],"placa":["spanish"],"plan":["spanish"],"plata":["spanish"],"playa":["spanish"],"plaza":["spanish"],"pleito":["spanish"],"pleno":["spanish"],"plomo":["spanish"],"pluma":["spanish"],"plural":["spanish"],"pobre":["spanish"],"poco":["spanish"],"poder":["spanish"],"podio":["spanish"],"poema":["spanish"],"poesía":["spanish"],"poeta":["spanish"],"polen":["spanish","turkish"],"policía":["spanish"],"pollo":["spanish"],"polvo":["spanish"],"pomada":["spanish"],"pomelo":["spanish"],"pomo":["spanish"],"pompa":["spanish","turkish"],"poner":["spanish"],"porción":["spanish"],"portal":["spanish"],"posada":["spanish"],"poseer":["spanish"],"posible":["spanish"],"poste":["spanish"],"potencia":["spanish"],"potro":["spanish"],"pozo":["spanish"],"prado":["spanish"],"precoz":["spanish"],"pregunta":["spanish"],"premio":["spanish"],"prensa":["spanish"],"preso":["spanish"],"previo":["spanish"],"primo":["spanish"],"príncipe":["spanish"],"prisión":["spanish"],"privar":["spanish"],"proa":["spanish"],"probar":["spanish"],"proceso":["spanish"],"producto":["spanish"],"proeza":["spanish"],"profesor":["spanish"],"programa":["spanish"],"prole":["spanish"],"promesa":["spanish"],"pronto":["spanish"],"propio":["spanish"],"próximo":["spanish"],"prueba":["spanish"],"público":["spanish"],"puchero":["spanish"],"pudor":["spanish"],"pueblo":["spanish"],"puerta":["spanish"],"puesto":["spanish"],"pulga":["spanish"],"pulir":["spanish"],"pulmón":["spanish"],"pulpo":["spanish"],"pulso":["spanish"],"puma":["spanish"],"punto":["spanish"],"puñal":["spanish"],"puño":["spanish"],"pupa":["spanish"],"pupila":["spanish"],"puré":["spanish"],"quedar":["spanish"],"queja":["spanish"],"quemar":["spanish"],"querer":["spanish"],"queso":["spanish"],"quieto":["spanish"],"química":["spanish"],"quince":["spanish"],"quitar":["spanish"],"rábano":["spanish"],"rabia":["spanish"],"rabo":["spanish"],"ración":["spanish"],"radical":["spanish"],"raíz":["spanish"],"rama":["spanish"],"rampa":["spanish","turkish"],"rancho":["spanish"],"rango":["spanish"],"rapaz":["spanish"],"rápido":["spanish"],"rapto":["spanish"],"rasgo":["spanish"],"raspa":["spanish"],"rato":["spanish"],"rayo":["spanish"],"raza":["spanish"],"razón":["spanish"],"reacción":["spanish"],"realidad":["spanish"],"rebaño":["spanish"],"rebote":["spanish"],"recaer":["spanish"],"receta":["spanish"],"rechazo":["spanish"],"recoger":["spanish"],"recreo":["spanish"],"recto":["spanish"],"recurso":["spanish"],"red":["spanish"],"redondo":["spanish"],"reducir":["spanish"],"reflejo":["spanish"],"reforma":["spanish"],"refrán":["spanish"],"refugio":["spanish"],"regalo":["spanish"],"regir":["spanish"],"regla":["spanish"],"regreso":["spanish"],"rehén":["spanish"],"reino":["spanish"],"reír":["spanish"],"reja":["spanish"],"relato":["spanish"],"relevo":["spanish"],"relieve":["spanish"],"relleno":["spanish"],"reloj":["spanish"],"remar":["spanish"],"remedio":["spanish"],"remo":["spanish"],"rencor":["spanish"],"rendir":["spanish"],"renta":["spanish"],"reparto":["spanish"],"repetir":["spanish"],"reposo":["spanish"],"reptil":["spanish"],"res":["spanish"],"rescate":["spanish"],"resina":["spanish"],"respeto":["spanish"],"resto":["spanish"],"resumen":["spanish"],"retiro":["spanish"],"retorno":["spanish"],"retrato":["spanish"],"reunir":["spanish"],"revés":["spanish"],"revista":["spanish"],"rey":["spanish"],"rezar":["spanish"],"rico":["spanish"],"riego":["spanish"],"rienda":["spanish"],"riesgo":["spanish"],"rifa":["spanish"],"rígido":["spanish"],"rigor":["spanish"],"rincón":["spanish"],"riñón":["spanish"],"río":["spanish"],"riqueza":["spanish"],"risa":["spanish"],"ritmo":["spanish"],"rito":["spanish"],"rizo":["spanish"],"roble":["spanish"],"roce":["spanish"],"rociar":["spanish"],"rodar":["spanish"],"rodeo":["spanish"],"rodilla":["spanish"],"roer":["spanish"],"rojizo":["spanish"],"rojo":["spanish"],"romero":["spanish"],"romper":["spanish"],"ron":["spanish"],"ronco":["spanish"],"ronda":["spanish"],"ropa":["spanish"],"ropero":["spanish"],"rosa":["spanish"],"rosca":["spanish"],"rostro":["spanish"],"rotar":["spanish"],"rubí":["spanish"],"rubor":["spanish"],"rudo":["spanish"],"rueda":["spanish"],"rugir":["spanish"],"ruido":["spanish"],"ruina":["spanish"],"ruleta":["spanish"],"rulo":["spanish","turkish"],"rumbo":["spanish"],"rumor":["spanish"],"ruptura":["spanish"],"ruta":["spanish"],"rutina":["spanish"],"sábado":["spanish"],"saber":["spanish"],"sabio":["spanish"],"sable":["spanish"],"sacar":["spanish"],"sagaz":["spanish"],"sagrado":["spanish"],"sala":["spanish"],"saldo":["spanish"],"salero":["spanish"],"salir":["spanish"],"salmón":["spanish"],"salón":["spanish"],"salsa":["spanish"],"salto":["spanish"],"salud":["spanish"],"salvar":["spanish"],"samba":["spanish"],"sanción":["spanish"],"sandía":["spanish"],"sanear":["spanish"],"sangre":["spanish"],"sanidad":["spanish"],"sano":["spanish"],"santo":["spanish"],"sapo":["spanish"],"saque":["spanish"],"sardina":["spanish"],"sartén":["spanish"],"sastre":["spanish"],"satán":["spanish"],"sauna":["spanish"],"saxofón":["spanish"],"sección":["spanish"],"seco":["spanish"],"secreto":["spanish"],"secta":["spanish"],"sed":["spanish"],"seguir":["spanish"],"seis":["spanish"],"sello":["spanish"],"selva":["spanish"],"semana":["spanish"],"semilla":["spanish"],"senda":["spanish"],"sensor":["spanish"],"señal":["spanish"],"señor":["spanish"],"separar":["spanish"],"sepia":["spanish"],"sequía":["spanish"],"ser":["spanish"],"serie":["spanish"],"sermón":["spanish"],"servir":["spanish"],"sesenta":["spanish"],"sesión":["spanish"],"seta":["spanish"],"setenta":["spanish"],"severo":["spanish"],"sexo":["spanish"],"sexto":["spanish"],"sidra":["spanish"],"siesta":["spanish"],"siete":["spanish"],"siglo":["spanish"],"signo":["spanish"],"sílaba":["spanish"],"silbar":["spanish"],"silencio":["spanish"],"silla":["spanish"],"símbolo":["spanish"],"simio":["spanish"],"sirena":["spanish"],"sistema":["spanish"],"sitio":["spanish"],"situar":["spanish"],"sobre":["spanish"],"socio":["spanish"],"sodio":["spanish"],"sol":["spanish"],"solapa":["spanish"],"soldado":["spanish"],"soledad":["spanish"],"sólido":["spanish"],"soltar":["spanish"],"solución":["spanish"],"sombra":["spanish"],"sondeo":["spanish"],"sonido":["spanish"],"sonoro":["spanish"],"sonrisa":["spanish"],"sopa":["spanish"],"soplar":["spanish"],"soporte":["spanish"],"sordo":["spanish"],"sorpresa":["spanish"],"sorteo":["spanish"],"sostén":["spanish"],"sótano":["spanish"],"suave":["spanish"],"subir":["spanish"],"suceso":["spanish"],"sudor":["spanish"],"suegra":["spanish"],"suelo":["spanish"],"sueño":["spanish"],"suerte":["spanish"],"sufrir":["spanish"],"sujeto":["spanish"],"sultán":["spanish"],"sumar":["spanish"],"superar":["spanish"],"suplir":["spanish"],"suponer":["spanish"],"supremo":["spanish"],"sur":["spanish"],"surco":["spanish"],"sureño":["spanish"],"surgir":["spanish"],"susto":["spanish"],"sutil":["spanish"],"tabaco":["spanish"],"tabique":["spanish"],"tabla":["spanish"],"tabú":["spanish"],"taco":["spanish"],"tacto":["spanish"],"tajo":["spanish"],"talar":["spanish"],"talco":["spanish"],"talento":["spanish"],"talla":["spanish"],"talón":["spanish"],"tamaño":["spanish"],"tambor":["spanish"],"tango":["spanish"],"tanque":["spanish"],"tapa":["spanish"],"tapete":["spanish"],"tapia":["spanish"],"tapón":["spanish"],"taquilla":["spanish"],"tarde":["spanish"],"tarea":["spanish"],"tarifa":["spanish"],"tarjeta":["spanish"],"tarot":["spanish"],"tarro":["spanish"],"tarta":["spanish"],"tatuaje":["spanish"],"tauro":["spanish"],"taza":["spanish"],"tazón":["spanish"],"teatro":["spanish"],"techo":["spanish"],"tecla":["spanish"],"técnica":["spanish"],"tejado":["spanish"],"tejer":["spanish"],"tejido":["spanish"],"tela":["spanish"],"teléfono":["spanish"],"tema":["spanish"],"temor":["spanish"],"templo":["spanish"],"tenaz":["spanish"],"tender":["spanish"],"tener":["spanish"],"tenis":["spanish"],"tenso":["spanish"],"teoría":["spanish"],"terapia":["spanish"],"terco":["spanish"],"término":["spanish"],"ternura":["spanish"],"terror":["spanish"],"tesis":["spanish"],"tesoro":["spanish"],"testigo":["spanish"],"tetera":["spanish"],"texto":["spanish"],"tez":["spanish"],"tibio":["spanish"],"tiburón":["spanish"],"tiempo":["spanish"],"tienda":["spanish"],"tierra":["spanish"],"tieso":["spanish"],"tigre":["spanish"],"tijera":["spanish"],"tilde":["spanish"],"timbre":["spanish"],"tímido":["spanish"],"timo":["spanish"],"tinta":["spanish"],"tío":["spanish"],"típico":["spanish"],"tipo":["spanish"],"tira":["spanish"],"tirón":["spanish"],"titán":["spanish"],"títere":["spanish"],"título":["spanish"],"tiza":["spanish"],"toalla":["spanish"],"tobillo":["spanish"],"tocar":["spanish"],"tocino":["spanish"],"todo":["spanish"],"toga":["spanish"],"toldo":["spanish"],"tomar":["spanish","turkish"],"tono":["spanish"],"tonto":["spanish"],"topar":["spanish"],"tope":["spanish"],"toque":["spanish"],"tórax":["spanish"],"torero":["spanish"],"tormenta":["spanish"],"torneo":["spanish"],"toro":["spanish"],"torpedo":["spanish"],"torre":["spanish"],"torso":["spanish"],"tortuga":["spanish"],"tos":["spanish"],"tosco":["spanish"],"toser":["spanish"],"tóxico":["spanish"],"trabajo":["spanish"],"tractor":["spanish"],"traer":["spanish"],"tráfico":["spanish"],"trago":["spanish"],"traje":["spanish"],"tramo":["spanish"],"trance":["spanish"],"trato":["spanish"],"trauma":["spanish"],"trazar":["spanish"],"trébol":["spanish"],"tregua":["spanish"],"treinta":["spanish"],"tren":["spanish"],"trepar":["spanish"],"tres":["spanish"],"tribu":["spanish"],"trigo":["spanish"],"tripa":["spanish"],"triste":["spanish"],"triunfo":["spanish"],"trofeo":["spanish"],"trompa":["spanish"],"tronco":["spanish"],"tropa":["spanish"],"trote":["spanish"],"trozo":["spanish"],"truco":["spanish"],"trueno":["spanish"],"trufa":["spanish"],"tubería":["spanish"],"tubo":["spanish"],"tuerto":["spanish"],"tumba":["spanish"],"tumor":["spanish"],"túnel":["spanish"],"túnica":["spanish"],"turbina":["spanish"],"turismo":["spanish"],"turno":["spanish"],"tutor":["spanish"],"ubicar":["spanish"],"úlcera":["spanish"],"umbral":["spanish"],"unidad":["spanish"],"unir":["spanish"],"universo":["spanish"],"uno":["spanish"],"untar":["spanish"],"uña":["spanish"],"urbano":["spanish"],"urbe":["spanish"],"urgente":["spanish"],"urna":["spanish"],"usar":["spanish"],"usuario":["spanish"],"útil":["spanish"],"utopía":["spanish"],"uva":["spanish"],"vaca":["spanish"],"vacío":["spanish"],"vacuna":["spanish"],"vagar":["spanish"],"vago":["spanish"],"vaina":["spanish"],"vajilla":["spanish"],"vale":["spanish"],"válido":["spanish"],"valle":["spanish"],"valor":["spanish"],"válvula":["spanish"],"vampiro":["spanish"],"vara":["spanish"],"variar":["spanish"],"varón":["spanish"],"vaso":["spanish"],"vecino":["spanish"],"vector":["spanish"],"vehículo":["spanish"],"veinte":["spanish"],"vejez":["spanish"],"vela":["spanish"],"velero":["spanish"],"veloz":["spanish"],"vena":["spanish"],"vencer":["spanish"],"venda":["spanish"],"veneno":["spanish"],"vengar":["spanish"],"venir":["spanish"],"venta":["spanish"],"venus":["spanish"],"ver":["spanish"],"verano":["spanish"],"verbo":["spanish"],"verde":["spanish"],"vereda":["spanish"],"verja":["spanish"],"verso":["spanish"],"verter":["spanish"],"vía":["spanish"],"viaje":["spanish"],"vibrar":["spanish"],"vicio":["spanish"],"víctima":["spanish"],"vida":["spanish"],"vídeo":["spanish"],"vidrio":["spanish"],"viejo":["spanish"],"viernes":["spanish"],"vigor":["spanish"],"vil":["spanish"],"villa":["spanish"],"vinagre":["spanish"],"vino":["spanish"],"viñedo":["spanish"],"violín":["spanish"],"viral":["spanish"],"virgo":["spanish"],"virtud":["spanish"],"visor":["spanish"],"víspera":["spanish"],"vista":["spanish"],"vitamina":["spanish"],"viudo":["spanish"],"vivaz":["spanish"],"vivero":["spanish"],"vivir":["spanish"],"vivo":["spanish"],"volcán":["spanish"],"volumen":["spanish"],"volver":["spanish"],"voraz":["spanish"],"votar":["spanish"],"voto":["spanish"],"voz":["spanish"],"vuelo":["spanish"],"vulgar":["spanish"],"yacer":["spanish"],"yate":["spanish"],"yegua":["spanish"],"yema":["spanish"],"yerno":["spanish"],"yeso":["spanish"],"yodo":["spanish"],"yoga":["spanish"],"yogur":["spanish"],"zafiro":["spanish"],"zanja":["spanish"],"zapato":["spanish"],"zarza":["spanish"],"zona":["spanish"],"zorro":["spanish"],"zumo":["spanish"],"zurdo":["spanish"],"abajur":["turkish"],"abaküs":["turkish"],"abartı":["turkish"],"abdal":["turkish"],"abdest":["turkish"],"abiye":["turkish"],"abluka":["turkish"],"abone":["turkish"],"absorbe":["turkish"],"absürt":["turkish"],"acayip":["turkish"],"acele":["turkish"],"acemi":["turkish"],"açıkgöz":["turkish"],"adalet":["turkish"],"adam":["turkish"],"adezyon":["turkish"],"adisyon":["turkish"],"adliye":["turkish"],"adres":["turkish"],"afacan":["turkish"],"afili":["turkish"],"afiş":["turkish"],"afiyet":["turkish"],"aforizm":["turkish"],"afra":["turkish"],"ağaç":["turkish"],"ağır":["turkish"],"ahbap":["turkish"],"ahkam":["turkish"],"ahlak":["turkish"],"ahtapot":["turkish"],"aidat":["turkish"],"aile":["turkish"],"ajan":["turkish"],"akademi":["turkish"],"akarsu":["turkish"],"akbaş":["turkish"],"akciğer":["turkish"],"akdeniz":["turkish"],"akıbet":["turkish"],"akıl":["turkish"],"akıntı":["turkish"],"akide":["turkish"],"akrep":["turkish"],"akrobasi":["turkish"],"aksiyon":["turkish"],"akşam":["turkish"],"aktif":["turkish"],"aktör":["turkish"],"aktris":["turkish"],"akustik":["turkish"],"alaca":["turkish"],"albüm":["turkish"],"alçak":["turkish"],"aldanma":["turkish"],"aleni":["turkish"],"alet":["turkish"],"alfabe":["turkish"],"algılama":["turkish"],"alıngan":["turkish"],"alkış":["turkish"],"alkol":["turkish"],"alpay":["turkish"],"alperen":["turkish"],"altın":["turkish"],"altüst":["turkish"],"altyapı":["turkish"],"alyuvar":["turkish"],"amade":["turkish"],"amatör":["turkish"],"amazon":["turkish"],"ambalaj":["turkish"],"amblem":["turkish"],"ambulans":["turkish"],"amca":["turkish"],"amel":["turkish"],"amir":["turkish"],"amiyane":["turkish"],"amorti":["turkish"],"ampul":["turkish"],"anadolu":["turkish"],"anahtar":["turkish"],"anakonda":["turkish"],"anaokul":["turkish"],"anapara":["turkish"],"anarşi":["turkish"],"anatomi":["turkish"],"anayasa":["turkish"],"anekdot":["turkish"],"anestezi":["turkish"],"angaje":["turkish"],"anka":["turkish"],"anket":["turkish"],"anlamlı":["turkish"],"anne":["turkish"],"anomali":["turkish"],"anonim":["turkish"],"anten":["turkish"],"antlaşma":["turkish"],"apse":["turkish"],"araba":["turkish"],"aracı":["turkish"],"araf":["turkish"],"arbede":["turkish"],"arda":["turkish"],"arefe":["turkish"],"argo":["turkish"],"argüman":["turkish"],"arkadaş":["turkish"],"armoni":["turkish"],"arsa":["turkish"],"arsız":["turkish"],"artı":["turkish"],"aruz":["turkish"],"asansör":["turkish"],"asayiş":["turkish"],"asgari":["turkish"],"asil":["turkish"],"asker":["turkish"],"askı":["turkish"],"aslan":["turkish"],"asosyal":["turkish"],"astsubay":["turkish"],"asya":["turkish"],"aşçı":["turkish"],"aşırı":["turkish"],"aşure":["turkish"],"atabey":["turkish"],"ataman":["turkish"],"ateş":["turkish"],"atmaca":["turkish"],"atmosfer":["turkish"],"atölye":["turkish"],"avcı":["turkish"],"avdet":["turkish"],"avize":["turkish"],"avlu":["turkish"],"avokado":["turkish"],"avrupa":["turkish"],"avukat":["turkish"],"ayaz":["turkish"],"ayçiçeği":["turkish"],"aydın":["turkish"],"aygıt":["turkish"],"ayna":["turkish"],"ayran":["turkish"],"ayrıntı":["turkish"],"azim":["turkish"],"baca":["turkish"],"bagaj":["turkish"],"bağlantı":["turkish"],"bahadır":["turkish"],"bahçe":["turkish"],"baki":["turkish"],"bakkal":["turkish"],"baklava":["turkish"],"bakteri":["turkish"],"balçık":["turkish"],"balina":["turkish"],"balo":["turkish"],"balta":["turkish"],"bant":["turkish"],"banyo":["turkish"],"bardak":["turkish"],"barış":["turkish"],"başbuğ":["turkish"],"başıboş":["turkish"],"başkan":["turkish"],"başlık":["turkish"],"bavul":["turkish"],"bayındır":["turkish"],"baykuş":["turkish"],"bazlama":["turkish"],"bedel":["turkish"],"begüm":["turkish"],"bekçi":["turkish"],"bekle":["turkish"],"belge":["turkish"],"belki":["turkish"],"bencil":["turkish"],"benek":["turkish"],"bengi":["turkish"],"berjer":["turkish"],"berk":["turkish"],"berrak":["turkish"],"beşik":["turkish"],"beyin":["turkish"],"beyoğlu":["turkish"],"bıçak":["turkish"],"biberiye":["turkish"],"bidon":["turkish"],"bihaber":["turkish"],"bikini":["turkish"],"bilezik":["turkish"],"bilinç":["turkish"],"bilye":["turkish"],"bina":["turkish"],"binbaşı":["turkish"],"binyıl":["turkish"],"bisiklet":["turkish"],"bisküvi":["turkish"],"bitki":["turkish"],"bizzat":["turkish"],"bodrum":["turkish"],"boğaz":["turkish"],"bohça":["turkish"],"boncuk":["turkish"],"bonfile":["turkish"],"borsa":["turkish"],"boru":["turkish"],"bostan":["turkish"],"boşboğaz":["turkish"],"botanik":["turkish"],"boya":["turkish"],"boykot":["turkish"],"boynuz":["turkish"],"bozgun":["turkish"],"bozkır":["turkish"],"bölüm":["turkish"],"börek":["turkish"],"buçuk":["turkish"],"bugün":["turkish"],"buğday":["turkish"],"buhar":["turkish"],"buhran":["turkish"],"bulvar":["turkish"],"buram":["turkish"],"burçak":["turkish"],"burs":["turkish"],"burun":["turkish"],"buzdağı":["turkish"],"buzkıran":["turkish"],"bücür":["turkish"],"büfe":["turkish"],"bülten":["turkish"],"bütçe":["turkish"],"bütün":["turkish"],"büyük":["turkish"],"cacık":["turkish"],"cadı":["turkish"],"cahil":["turkish"],"cambaz":["turkish"],"canhıraş":["turkish"],"casus":["turkish"],"cazibe":["turkish"],"cehalet":["turkish"],"cehennem":["turkish"],"ceket":["turkish"],"cemre":["turkish"],"cenin":["turkish"],"cennet":["turkish"],"cepken":["turkish"],"cerrah":["turkish"],"cesur":["turkish"],"cetvel":["turkish"],"cevher":["turkish"],"ceylan":["turkish"],"cılız":["turkish"],"cıva":["turkish"],"cilt":["turkish"],"cisim":["turkish"],"ciyak":["turkish"],"coğrafya":["turkish"],"cömert":["turkish"],"cumba":["turkish"],"cüzdan":["turkish"],"çabucak":["turkish"],"çadır":["turkish"],"çağdaş":["turkish"],"çağlayan":["turkish"],"çağrı":["turkish"],"çakmak":["turkish"],"çalışkan":["turkish"],"çamaşır":["turkish"],"çapa":["turkish"],"çaput":["turkish"],"çarık":["turkish"],"çarpan":["turkish"],"çarşaf":["turkish"],"çayhane":["turkish"],"çekirdek":["turkish"],"çelebi":["turkish"],"çember":["turkish"],"çenet":["turkish"],"çengel":["turkish"],"çerçeve":["turkish"],"çerez":["turkish"],"çeşit":["turkish"],"çeşme":["turkish"],"çete":["turkish"],"çevre":["turkish"],"çeyiz":["turkish"],"çeyrek":["turkish"],"çığır":["turkish"],"çılgın":["turkish"],"çıngırak":["turkish"],"çift":["turkish"],"çiğdem":["turkish"],"çikolata":["turkish"],"çilek":["turkish"],"çimen":["turkish"],"çivi":["turkish"],"çoban":["turkish"],"çocuk":["turkish"],"çokgen":["turkish"],"çomak":["turkish"],"çorba":["turkish"],"çözelti":["turkish"],"çubuk":["turkish"],"çukur":["turkish"],"çuval":["turkish"],"çürük":["turkish"],"dağbaşı":["turkish"],"dağılım":["turkish"],"daktilo":["turkish"],"daldırış":["turkish"],"dalga":["turkish"],"dalkavuk":["turkish"],"damak":["turkish"],"damıtma":["turkish"],"damla":["turkish"],"dana":["turkish"],"dandik":["turkish"],"danışman":["turkish"],"daniska":["turkish"],"dantel":["turkish"],"dargeçit":["turkish"],"darphane":["turkish"],"davet":["turkish"],"dayı":["turkish"],"defter":["turkish"],"değer":["turkish"],"değirmen":["turkish"],"dehşet":["turkish"],"delgeç":["turkish"],"demir":["turkish"],"deneyim":["turkish"],"denge":["turkish"],"depo":["turkish"],"deprem":["turkish"],"derdest":["turkish"],"dere":["turkish"],"derhal":["turkish"],"derman":["turkish"],"dernek":["turkish"],"derviş":["turkish"],"desen":["turkish"],"destan":["turkish"],"dışarı":["turkish"],"dışbükey":["turkish"],"dijital":["turkish"],"dikbaşlı":["turkish"],"dilekçe":["turkish"],"dimağ":["turkish"],"dinamik":["turkish"],"dindar":["turkish"],"dinleme":["turkish"],"dinozor":["turkish"],"dipçik":["turkish"],"dipnot":["turkish"],"direniş":["turkish"],"dirsek":["turkish"],"disiplin":["turkish"],"divriği":["turkish"],"dizüstü":["turkish"],"dobra":["turkish"],"dodurga":["turkish"],"doğalgaz":["turkish"],"doküman":["turkish"],"dolap":["turkish"],"donanım":["turkish"],"dondurma":["turkish"],"donör":["turkish"],"doruk":["turkish"],"dosdoğru":["turkish"],"dost":["turkish"],"dosya":["turkish"],"dozer":["turkish"],"döküm":["turkish"],"dönence":["turkish"],"dörtyol":["turkish"],"dövme":["turkish"],"dram":["turkish"],"dublaj":["turkish"],"durum":["turkish"],"duvak":["turkish"],"duyarga":["turkish"],"duyma":["turkish"],"duyuru":["turkish"],"düğme":["turkish"],"düğüm":["turkish"],"dükkan":["turkish"],"dünür":["turkish"],"düpedüz":["turkish"],"dürbün":["turkish"],"düşünür":["turkish"],"düzayak":["turkish"],"düzeltme":["turkish"],"ebeveyn":["turkish"],"ebru":["turkish"],"ecel":["turkish"],"ecnebi":["turkish"],"ecza":["turkish"],"edat":["turkish"],"edilgen":["turkish"],"efendi":["turkish"],"efor":["turkish"],"efsane":["turkish"],"egemen":["turkish"],"egzersiz":["turkish"],"eğrelti":["turkish"],"ekarte":["turkish"],"ekip":["turkish"],"eklem":["turkish"],"ekmek":["turkish"],"ekol":["turkish"],"ekonomi":["turkish"],"ekose":["turkish"],"ekran":["turkish"],"ekvator":["turkish"],"elaman":["turkish"],"elastik":["turkish"],"elbet":["turkish"],"elbise":["turkish"],"elçi":["turkish"],"eldiven":["turkish"],"elebaşı":["turkish"],"eleştiri":["turkish"],"elma":["turkish"],"eloğlu":["turkish"],"elveda":["turkish"],"emare":["turkish"],"emekçi":["turkish"],"emisyon":["turkish"],"emniyet":["turkish"],"empati":["turkish"],"emsal":["turkish"],"emzik":["turkish"],"endüstri":["turkish"],"enerji":["turkish"],"engebe":["turkish"],"enişte":["turkish"],"enkaz":["turkish"],"entari":["turkish"],"entegre":["turkish"],"entrika":["turkish"],"enzim":["turkish"],"erdem":["turkish"],"ergen":["turkish"],"erguvan":["turkish"],"erkek":["turkish"],"erozyon":["turkish"],"ertesi":["turkish"],"erzak":["turkish"],"esaret":["turkish"],"esenlik":["turkish"],"eser":["turkish"],"eski":["turkish"],"esnek":["turkish"],"eşarp":["turkish"],"eşofman":["turkish"],"eşraf":["turkish"],"eşya":["turkish"],"eşzaman":["turkish"],"etik":["turkish"],"etken":["turkish"],"etkinlik":["turkish"],"etüt":["turkish"],"evet":["turkish"],"evire":["turkish"],"evrak":["turkish"],"evrim":["turkish"],"eyalet":["turkish"],"eyvah":["turkish"],"ezber":["turkish"],"fabrika":["turkish"],"fanus":["turkish"],"fason":["turkish"],"fasulye":["turkish"],"fatih":["turkish"],"fatura":["turkish"],"fayans":["turkish"],"fayton":["turkish"],"fazıl":["turkish"],"fazilet":["turkish"],"felsefe":["turkish"],"fener":["turkish"],"feribot":["turkish"],"fersah":["turkish"],"fesih":["turkish"],"feveran":["turkish"],"feza":["turkish"],"fıçı":["turkish"],"fıldır":["turkish"],"fındık":["turkish"],"fırça":["turkish"],"fırsat":["turkish"],"fırtına":["turkish"],"fıtık":["turkish"],"fidan":["turkish"],"fidye":["turkish"],"figür":["turkish"],"fihrist":["turkish"],"fikir":["turkish"],"fildişi":["turkish"],"filtre":["turkish"],"fincan":["turkish"],"firuze":["turkish"],"fitil":["turkish"],"fiyaka":["turkish"],"fizik":["turkish"],"flaş":["turkish"],"flüt":["turkish"],"fosil":["turkish"],"fren":["turkish"],"fukara":["turkish"],"futbol":["turkish"],"garabet":["turkish"],"gariban":["turkish"],"garnitür":["turkish"],"gazi":["turkish"],"gece":["turkish"],"gedik":["turkish"],"gelenek":["turkish"],"gelin":["turkish"],"gemi":["turkish"],"genç":["turkish"],"geniş":["turkish"],"geometri":["turkish"],"gerçek":["turkish"],"gevrek":["turkish"],"gezegen":["turkish"],"gezgin":["turkish"],"geziyolu":["turkish"],"gıcık":["turkish"],"gıda":["turkish"],"gıybet":["turkish"],"girdap":["turkish"],"girişim":["turkish"],"gitar":["turkish"],"giyecek":["turkish"],"giysi":["turkish"],"gizem":["turkish"],"gofret":["turkish"],"goril":["turkish"],"göbek":["turkish"],"göçebe":["turkish"],"göğüs":["turkish"],"gökdelen":["turkish"],"gökmen":["turkish"],"gökyüzü":["turkish"],"gölge":["turkish"],"gömlek":["turkish"],"gönül":["turkish"],"görenek":["turkish"],"görkemli":["turkish"],"görsel":["turkish"],"gösteri":["turkish"],"gövde":["turkish"],"gözaltı":["turkish"],"gözcü":["turkish"],"gözdağı":["turkish"],"gözleme":["turkish"],"gözyaşı":["turkish"],"grup":["turkish"],"gurbet":["turkish"],"gusül":["turkish"],"gübre":["turkish"],"güfte":["turkish"],"gümüş":["turkish"],"günaydın":["turkish"],"güncel":["turkish"],"gündüz":["turkish"],"güneş":["turkish"],"günyüzü":["turkish"],"gürbüz":["turkish"],"güvercin":["turkish"],"güzel":["turkish"],"hacamat":["turkish"],"hacim":["turkish"],"hademe":["turkish"],"hafız":["turkish"],"hafriyat":["turkish"],"hafta":["turkish"],"hakan":["turkish"],"hakem":["turkish"],"hakikat":["turkish"],"haksever":["turkish"],"halı":["turkish"],"hançer":["turkish"],"hane":["turkish"],"hapis":["turkish"],"hapşırık":["turkish"],"harf":["turkish"],"haseki":["turkish"],"hasret":["turkish"],"hatun":["turkish"],"havuç":["turkish"],"haylaz":["turkish"],"haysiyet":["turkish"],"hayvan":["turkish"],"hedef":["turkish"],"hemen":["turkish"],"hemfikir":["turkish"],"hendek":["turkish"],"hepsi":["turkish"],"hergele":["turkish"],"herhangi":["turkish"],"hesap":["turkish"],"heyecan":["turkish"],"heykel":["turkish"],"hezimet":["turkish"],"hıçkırık":["turkish"],"hızölçer":["turkish"],"hicviye":["turkish"],"hikaye":["turkish"],"hikmet":["turkish"],"hile":["turkish"],"hisse":["turkish"],"hobi":["turkish"],"hoca":["turkish"],"horlama":["turkish"],"hoşbeş":["turkish"],"hoşgörü":["turkish"],"hoyrat":["turkish"],"hörgüç":["turkish"],"höyük":["turkish"],"hudut":["turkish"],"hukuk":["turkish"],"hunhar":["turkish"],"hurda":["turkish"],"huysuz":["turkish"],"huzur":["turkish"],"hücum":["turkish"],"hükümet":["turkish"],"hünkar":["turkish"],"hüviyet":["turkish"],"ırmak":["turkish"],"ısıölçer":["turkish"],"ısıtıcı":["turkish"],"ıspanak":["turkish"],"ısrar":["turkish"],"ışıldak":["turkish"],"ızdırap":["turkish"],"ızgara":["turkish"],"ibadet":["turkish"],"icat":["turkish"],"içbükey":["turkish"],"içecek":["turkish"],"içgüdü":["turkish"],"içsel":["turkish"],"idman":["turkish"],"iftihar":["turkish"],"iğne":["turkish"],"ihanet":["turkish"],"ihbar":["turkish"],"ihdas":["turkish"],"ihmal":["turkish"],"ihracat":["turkish"],"ihsan":["turkish"],"ikilem":["turkish"],"ikindi":["turkish"],"ikircik":["turkish"],"iklim":["turkish"],"iksir":["turkish"],"iktibas":["turkish"],"ilaç":["turkish"],"ilçe":["turkish"],"ileri":["turkish"],"iletişim":["turkish"],"ilgi":["turkish"],"ilhak":["turkish"],"ilkbahar":["turkish"],"ilkokul":["turkish"],"ilmek":["turkish"],"imkan":["turkish"],"imleç":["turkish"],"imsak":["turkish"],"imtihan":["turkish"],"imza":["turkish"],"ince":["turkish"],"inkar":["turkish"],"inşa":["turkish"],"ipek":["turkish"],"ipucu":["turkish"],"irade":["turkish"],"irfan":["turkish"],"irmik":["turkish"],"isabet":["turkish"],"iskele":["turkish"],"israf":["turkish"],"isyan":["turkish"],"işçi":["turkish"],"işgal":["turkish"],"işgüzar":["turkish"],"işlem":["turkish"],"itibar":["turkish"],"itiraf":["turkish"],"ivedi":["turkish"],"ivme":["turkish"],"iyileşme":["turkish"],"iyimser":["turkish"],"izbandut":["turkish"],"izci":["turkish"],"izdiham":["turkish"],"izin":["turkish"],"jakoben":["turkish"],"jandarma":["turkish"],"jargon":["turkish"],"kabadayı":["turkish"],"kablo":["turkish"],"kabus":["turkish"],"kaçamak":["turkish"],"kadeh":["turkish"],"kadın":["turkish"],"kadraj":["turkish"],"kafa":["turkish"],"kafkas":["turkish"],"kağıt":["turkish"],"kağnı":["turkish"],"kahkaha":["turkish"],"kahraman":["turkish"],"kahvaltı":["turkish"],"kakül":["turkish"],"kaldırım":["turkish"],"kale":["turkish"],"kalibre":["turkish"],"kalkan":["turkish"],"kalpak":["turkish"],"kamış":["turkish"],"kamyon":["turkish"],"kanat":["turkish"],"kandaş":["turkish"],"kanepe":["turkish"],"kanser":["turkish"],"kanun":["turkish"],"kaos":["turkish"],"kapı":["turkish"],"kaplıca":["turkish"],"kaptan":["turkish"],"karanlık":["turkish"],"kardeş":["turkish"],"karga":["turkish"],"karınca":["turkish"],"karmaşa":["turkish"],"karşıt":["turkish"],"kasırga":["turkish"],"kask":["turkish"],"kasvet":["turkish"],"katkı":["turkish"],"katman":["turkish"],"kavram":["turkish"],"kaygan":["turkish"],"kaynakça":["turkish"],"kayyum":["turkish"],"kedi":["turkish"],"kehanet":["turkish"],"kekik":["turkish"],"kelebek":["turkish"],"kenar":["turkish"],"kerkenez":["turkish"],"kerpiç":["turkish"],"kesirli":["turkish"],"kesmece":["turkish"],"kestane":["turkish"],"keşkek":["turkish"],"ketçap":["turkish"],"keyfiyet":["turkish"],"kıble":["turkish"],"kıdemli":["turkish"],"kılavuz":["turkish"],"kılçık":["turkish"],"kılıf":["turkish"],"kıraç":["turkish"],"kırmızı":["turkish"],"kırsal":["turkish"],"kısayol":["turkish"],"kısım":["turkish"],"kıskanç":["turkish"],"kısmet":["turkish"],"kışla":["turkish"],"kıvanç":["turkish"],"kıvılcım":["turkish"],"kıvrık":["turkish"],"kıyafet":["turkish"],"kıymetli":["turkish"],"kızak":["turkish"],"kızılcık":["turkish"],"kibar":["turkish"],"kinaye":["turkish"],"kira":["turkish"],"kiremit":["turkish"],"kirli":["turkish"],"kirpik":["turkish"],"kişisel":["turkish"],"kitap":["turkish"],"koçbaşı":["turkish"],"kodaman":["turkish"],"koğuş":["turkish"],"kokteyl":["turkish"],"kolaycı":["turkish"],"kolbastı":["turkish"],"kolonya":["turkish"],"koltuk":["turkish"],"kolye":["turkish"],"kombine":["turkish"],"komedyen":["turkish"],"komiser":["turkish"],"komposto":["turkish"],"komşu":["turkish"],"komuta":["turkish"],"konak":["turkish"],"konfor":["turkish"],"koni":["turkish"],"konsül":["turkish"],"kopya":["turkish"],"korkusuz":["turkish"],"korna":["turkish"],"korse":["turkish"],"korunak":["turkish"],"korvet":["turkish"],"kostüm":["turkish"],"koşul":["turkish"],"koyu":["turkish"],"kozmik":["turkish"],"köfte":["turkish"],"kökensel":["turkish"],"köprücük":["turkish"],"köpük":["turkish"],"kördüğüm":["turkish"],"körfez":["turkish"],"köstebek":["turkish"],"köşegen":["turkish"],"kötü":["turkish"],"kravat":["turkish"],"kriter":["turkish"],"kuantum":["turkish"],"kudurma":["turkish"],"kuluçka":["turkish"],"kulübe":["turkish"],"kumanya":["turkish"],"kumbara":["turkish"],"kumlu":["turkish"],"kumpir":["turkish"],"kumral":["turkish"],"kundura":["turkish"],"kupa":["turkish"],"kupkuru":["turkish"],"kuramsal":["turkish"],"kurbağa":["turkish"],"kurdele":["turkish"],"kurgu":["turkish"],"kurmay":["turkish"],"kurşun":["turkish"],"kurtuluş":["turkish"],"kurultay":["turkish"],"kurye":["turkish"],"kusursuz":["turkish"],"kuşak":["turkish"],"kuşbaşı":["turkish"],"kuşkulu":["turkish"],"kutlama":["turkish"],"kutsal":["turkish"],"kutup":["turkish"],"kuver":["turkish"],"kuyruk":["turkish"],"kuzey":["turkish"],"kuzgun":["turkish"],"küçük":["turkish"],"külçe":["turkish"],"külfet":["turkish"],"külliye":["turkish"],"kültürel":["turkish"],"kümes":["turkish"],"künefe":["turkish"],"küresel":["turkish"],"kütle":["turkish"],"lahana":["turkish"],"lahmacun":["turkish"],"lamba":["turkish"],"lansman":["turkish"],"lavaş":["turkish"],"layık":["turkish"],"leğen":["turkish"],"levent":["turkish"],"leziz":["turkish"],"lezzet":["turkish"],"lider":["turkish"],"likide":["turkish"],"liman":["turkish"],"liste":["turkish"],"litre":["turkish"],"liyakat":["turkish"],"lodos":["turkish"],"lokanta":["turkish"],"lokman":["turkish"],"lokum":["turkish"],"lunapark":["turkish"],"lütfen":["turkish"],"lüzum":["turkish"],"nokta":["turkish"],"mabet":["turkish"],"macera":["turkish"],"macun":["turkish"],"madalya":["turkish"],"madde":["turkish"],"madem":["turkish"],"mağara":["turkish"],"mağdur":["turkish"],"mağfiret":["turkish"],"mağlup":["turkish"],"mahalle":["turkish"],"mahcup":["turkish"],"mahir":["turkish"],"mahkeme":["turkish"],"mahlas":["turkish"],"mahrum":["turkish"],"mahsul":["turkish"],"makas":["turkish"],"makbuz":["turkish"],"makine":["turkish"],"makro":["turkish"],"maksat":["turkish"],"makul":["turkish"],"maliye":["turkish"],"manav":["turkish"],"mangal":["turkish"],"manidar":["turkish"],"manken":["turkish"],"mantık":["turkish"],"manzara":["turkish"],"mareşal":["turkish"],"margarin":["turkish"],"marifet":["turkish"],"marmelat":["turkish"],"masaüstü":["turkish"],"masmavi":["turkish"],"masraf":["turkish"],"masum":["turkish"],"matah":["turkish"],"materyal":["turkish"],"matrak":["turkish"],"maval":["turkish"],"mavra":["turkish"],"maydanoz":["turkish"],"mayhoş":["turkish"],"maytap":["turkish"],"mazbata":["turkish"],"mazeret":["turkish"],"mazlum":["turkish"],"mazot":["turkish"],"mazur":["turkish"],"meblağ":["turkish"],"mebus":["turkish"],"mecaz":["turkish"],"mecbur":["turkish"],"meclis":["turkish"],"mecmua":["turkish"],"mecnun":["turkish"],"meçhul":["turkish"],"medeni":["turkish"],"mehtap":["turkish"],"mekanik":["turkish"],"melodi":["turkish"],"meltem":["turkish"],"memur":["turkish"],"mendil":["turkish"],"menekşe":["turkish"],"menteşe":["turkish"],"meraklı":["turkish"],"mercek":["turkish"],"merdiven":["turkish"],"merhaba":["turkish"],"merinos":["turkish"],"merkez":["turkish"],"mermi":["turkish"],"mert":["turkish"],"mesafe":["turkish"],"mesele":["turkish"],"mesken":["turkish"],"meslek":["turkish"],"meşale":["turkish"],"meşgul":["turkish"],"meşhur":["turkish"],"metafor":["turkish"],"metin":["turkish"],"metre":["turkish"],"mevcut":["turkish"],"mevkidaş":["turkish"],"meydan":["turkish"],"meyil":["turkish"],"meyve":["turkish"],"meziyet":["turkish"],"mezun":["turkish"],"mıknatıs":["turkish"],"mısra":["turkish"],"mızıka":["turkish"],"miğfer":["turkish"],"mihrak":["turkish"],"miktar":["turkish"],"milat":["turkish"],"milli":["turkish"],"mimar":["turkish"],"minare":["turkish"],"mineral":["turkish"],"minik":["turkish"],"minyon":["turkish"],"mirliva":["turkish"],"misafir":["turkish"],"miskin":["turkish"],"miting":["turkish"],"miyop":["turkish"],"mizah":["turkish"],"mobilya":["turkish"],"monitör":["turkish"],"morötesi":["turkish"],"motive":["turkish"],"mozaik":["turkish"],"muavin":["turkish"],"mucize":["turkish"],"muhafız":["turkish"],"muhteşem":["turkish"],"mukayese":["turkish"],"mumya":["turkish"],"musluk":["turkish"],"muşamba":["turkish"],"mutabık":["turkish"],"mutfak":["turkish"],"mutlu":["turkish"],"muzaffer":["turkish"],"muzdarip":["turkish"],"mübarek":["turkish"],"mücadele":["turkish"],"müdür":["turkish"],"müfredat":["turkish"],"müftü":["turkish"],"mühendis":["turkish"],"mühim":["turkish"],"mühlet":["turkish"],"mükemmel":["turkish"],"mülk":["turkish"],"mümkün":["turkish"],"mümtaz":["turkish"],"müsrif":["turkish"],"müstesna":["turkish"],"müşahit":["turkish"],"müşteri":["turkish"],"mütercim":["turkish"],"müthiş":["turkish"],"müze":["turkish"],"müzik":["turkish"],"nabız":["turkish"],"nadas":["turkish"],"nadir":["turkish"],"nahoş":["turkish"],"nakarat":["turkish"],"nakış":["turkish"],"nalbur":["turkish"],"namlu":["turkish"],"namus":["turkish"],"nankör":["turkish"],"nargile":["turkish"],"narkoz":["turkish"],"nasıl":["turkish"],"nasip":["turkish"],"naylon":["turkish"],"nazar":["turkish"],"nazım":["turkish"],"nazik":["turkish"],"neden":["turkish"],"nefes":["turkish"],"negatif":["turkish"],"neon":["turkish"],"neptün":["turkish"],"nerede":["turkish"],"nesil":["turkish"],"nesnel":["turkish"],"neşeli":["turkish"],"netice":["turkish"],"nevresim":["turkish"],"neyse":["turkish"],"neyzen":["turkish"],"nezaket":["turkish"],"nezih":["turkish"],"nezle":["turkish"],"nicel":["turkish"],"nilüfer":["turkish"],"nimet":["turkish"],"nisan":["turkish"],"nispet":["turkish"],"nitekim":["turkish"],"nizam":["turkish"],"nohut":["turkish"],"noksan":["turkish"],"nostalji":["turkish"],"noter":["turkish"],"nöbet":["turkish"],"numara":["turkish"],"numune":["turkish"],"nutuk":["turkish"],"nüfus":["turkish"],"obabaşı":["turkish"],"obez":["turkish"],"obje":["turkish"],"ocak":["turkish"],"odun":["turkish"],"ofansif":["turkish"],"ofis":["turkish"],"oğlak":["turkish"],"oğuz":["turkish"],"okçu":["turkish"],"oklava":["turkish"],"oksijen":["turkish"],"okul":["turkish"],"okumuş":["turkish"],"okutman":["turkish"],"okuyucu":["turkish"],"okyanus":["turkish"],"olağan":["turkish"],"olanak":["turkish"],"olası":["turkish"],"olay":["turkish"],"olgun":["turkish"],"olimpik":["turkish"],"olumlu":["turkish"],"omlet":["turkish"],"omurga":["turkish"],"onarım":["turkish"],"onursal":["turkish"],"optik":["turkish"],"orantı":["turkish"],"ordu":["turkish"],"organik":["turkish"],"orijin":["turkish"],"orkide":["turkish"],"orman":["turkish"],"orta":["turkish"],"oruç":["turkish"],"otağ":["turkish"],"otantik":["turkish"],"otel":["turkish"],"otoban":["turkish"],"otogar":["turkish"],"otomobil":["turkish"],"otonom":["turkish"],"otopark":["turkish"],"otorite":["turkish"],"otoyol":["turkish"],"oturum":["turkish"],"oyuk":["turkish"],"oyuncak":["turkish"],"ozan":["turkish"],"ödeme":["turkish"],"ödenek":["turkish"],"ödev":["turkish"],"ödül":["turkish"],"ödünç":["turkish"],"öfke":["turkish"],"öğlen":["turkish"],"öğrenci":["turkish"],"öğün":["turkish"],"öğütücü":["turkish"],"öksürük":["turkish"],"ölçme":["turkish"],"ölçü":["turkish"],"ölümsüz":["turkish"],"ömür":["turkish"],"önayak":["turkish"],"öncü":["turkish"],"önder":["turkish"],"önem":["turkish"],"önerge":["turkish"],"öngörü":["turkish"],"önlük":["turkish"],"önsezi":["turkish"],"öpücük":["turkish"],"ördek":["turkish"],"örgü":["turkish"],"örtbas":["turkish"],"örtme":["turkish"],"örtü":["turkish"],"örümcek":["turkish"],"örüntü":["turkish"],"öteberi":["turkish"],"öteki":["turkish"],"övünç":["turkish"],"öykü":["turkish"],"öyleyse":["turkish"],"özçekim":["turkish"],"özdeyiş":["turkish"],"özel":["turkish"],"özenti":["turkish"],"özerk":["turkish"],"özgürlük":["turkish"],"özlem":["turkish"],"özlü":["turkish"],"özne":["turkish"],"özsever":["turkish"],"özümseme":["turkish"],"özür":["turkish"],"özveri":["turkish"],"pabuç":["turkish"],"padişah":["turkish"],"palamut":["turkish"],"palmiye":["turkish"],"palto":["turkish"],"palyaço":["turkish"],"pamuk":["turkish"],"panayır":["turkish"],"pancar":["turkish"],"panik":["turkish"],"panjur":["turkish"],"pankart":["turkish"],"pano":["turkish"],"pansuman":["turkish"],"pantolon":["turkish"],"panzehir":["turkish"],"papatya":["turkish"],"papyon":["turkish"],"paraşüt":["turkish"],"parça":["turkish"],"pardösü":["turkish"],"parfüm":["turkish"],"parıltı":["turkish"],"parkur":["turkish"],"parmak":["turkish"],"parodi":["turkish"],"parsel":["turkish"],"partner":["turkish"],"pasaport":["turkish"],"pasif":["turkish"],"paskalya":["turkish"],"pastırma":["turkish"],"paşa":["turkish"],"patates":["turkish"],"paten":["turkish"],"patika":["turkish"],"patlıcan":["turkish"],"patolog":["turkish"],"payanda":["turkish"],"paydaş":["turkish"],"payidar":["turkish"],"paylaşma":["turkish"],"paytak":["turkish"],"peçete":["turkish"],"peder":["turkish"],"pehlivan":["turkish"],"pekala":["turkish"],"pekmez":["turkish"],"pelerin":["turkish"],"pelikan":["turkish"],"pelüş":["turkish"],"pembe":["turkish"],"pencere":["turkish"],"pense":["turkish"],"perçin":["turkish"],"perde":["turkish"],"pergel":["turkish"],"perişan":["turkish"],"peron":["turkish"],"personel":["turkish"],"perşembe":["turkish"],"peruk":["turkish"],"pervane":["turkish"],"pespaye":["turkish"],"pestil":["turkish"],"peşin":["turkish"],"petek":["turkish"],"petrol":["turkish"],"petunya":["turkish"],"peynir":["turkish"],"peyzaj":["turkish"],"pınar":["turkish"],"pırasa":["turkish"],"pırlanta":["turkish"],"pide":["turkish"],"pikap":["turkish"],"pilav":["turkish"],"piliç":["turkish"],"pipet":["turkish"],"pipo":["turkish"],"piramit":["turkish"],"pirinç":["turkish"],"pirzola":["turkish"],"pist":["turkish"],"pişik":["turkish"],"pişman":["turkish"],"piyasa":["turkish"],"piyes":["turkish"],"plaj":["turkish"],"plaket":["turkish"],"planlama":["turkish"],"platform":["turkish"],"plazma":["turkish"],"podyum":["turkish"],"poğaça":["turkish"],"polat":["turkish"],"politika":["turkish"],"popüler":["turkish"],"porselen":["turkish"],"portakal":["turkish"],"poster":["turkish"],"poşet":["turkish"],"poyraz":["turkish"],"pozitif":["turkish"],"pranga":["turkish"],"pratik":["turkish"],"prenses":["turkish"],"prim":["turkish"],"profil":["turkish"],"proje":["turkish"],"protokol":["turkish"],"puan":["turkish"],"pudra":["turkish"],"pusula":["turkish"],"püre":["turkish"],"pürüz":["turkish"],"püstül":["turkish"],"püsür":["turkish"],"racon":["turkish"],"radikal":["turkish"],"radyo":["turkish"],"rafadan":["turkish"],"rafine":["turkish"],"rağbet":["turkish"],"rahat":["turkish"],"rahle":["turkish"],"rakam":["turkish"],"raket":["turkish"],"rakip":["turkish"],"rakun":["turkish"],"ralli":["turkish"],"randevu":["turkish"],"ranza":["turkish"],"rapor":["turkish"],"rastgele":["turkish"],"rasyonel":["turkish"],"razı":["turkish"],"realite":["turkish"],"reçine":["turkish"],"refah":["turkish"],"referans":["turkish"],"refik":["turkish"],"rehber":["turkish"],"rehin":["turkish"],"reis":["turkish"],"rekabet":["turkish"],"reklam":["turkish"],"rekor":["turkish"],"rektör":["turkish"],"renk":["turkish"],"resim":["turkish"],"resmen":["turkish"],"restoran":["turkish"],"retorik":["turkish"],"revaç":["turkish"],"reyon":["turkish"],"rezalet":["turkish"],"rezerv":["turkish"],"rezil":["turkish"],"rıhtım":["turkish"],"rıza":["turkish"],"ritim":["turkish"],"ritüel":["turkish"],"rivayet":["turkish"],"roman":["turkish"],"rozet":["turkish"],"röportaj":["turkish"],"rötar":["turkish"],"ruble":["turkish"],"ruhban":["turkish"],"ruhsat":["turkish"],"rulet":["turkish"],"runik":["turkish"],"rutin":["turkish"],"rutubet":["turkish"],"rüşvet":["turkish"],"rütbe":["turkish"],"rüya":["turkish"],"rüzgar":["turkish"],"sabah":["turkish"],"sabıka":["turkish"],"sabit":["turkish"],"sabun":["turkish"],"saçma":["turkish"],"sade":["turkish"],"sadık":["turkish"],"safahat":["turkish"],"safdil":["turkish"],"safkan":["turkish"],"sağanak":["turkish"],"sağduyu":["turkish"],"sağlam":["turkish"],"saha":["turkish"],"sahiden":["turkish"],"sahne":["turkish"],"sakal":["turkish"],"sakız":["turkish"],"sakin":["turkish"],"saklama":["turkish"],"saksağan":["turkish"],"salamura":["turkish"],"salça":["turkish"],"salgı":["turkish"],"salınım":["turkish"],"salkım":["turkish"],"saltanat":["turkish"],"sanatçı":["turkish"],"sancak":["turkish"],"sandalye":["turkish"],"saniye":["turkish"],"saplantı":["turkish"],"sapsız":["turkish"],"saray":["turkish"],"sarışın":["turkish"],"sarkık":["turkish"],"sarmaşık":["turkish"],"satır":["turkish"],"savaşım":["turkish"],"savunma":["turkish"],"saydam":["turkish"],"sayfa":["turkish"],"saygın":["turkish"],"sayısal":["turkish"],"sebep":["turkish"],"seçenek":["turkish"],"seçim":["turkish"],"seçkin":["turkish"],"seçmen":["turkish"],"sedir":["turkish"],"sedye":["turkish"],"sefer":["turkish"],"sehpa":["turkish"],"sekizgen":["turkish"],"selektör":["turkish"],"selvi":["turkish"],"semavi":["turkish"],"sembol":["turkish"],"seminer":["turkish"],"senaryo":["turkish"],"sendika":["turkish"],"senkron":["turkish"],"sensör":["turkish"],"sentez":["turkish"],"sepet":["turkish"],"seramik":["turkish"],"serbest":["turkish"],"serdar":["turkish"],"seremoni":["turkish"],"sergi":["turkish"],"serhat":["turkish"],"serin":["turkish"],"sermaye":["turkish"],"serpuş":["turkish"],"sersem":["turkish"],"serüven":["turkish"],"sesli":["turkish"],"sesteş":["turkish"],"sevap":["turkish"],"seviye":["turkish"],"seyahat":["turkish"],"seyirci":["turkish"],"sezon":["turkish"],"sıcak":["turkish"],"sıfat":["turkish"],"sıhhi":["turkish"],"sınanma":["turkish"],"sınır":["turkish"],"sıradan":["turkish"],"sırdaş":["turkish"],"sırma":["turkish"],"sırtüstü":["turkish"],"sızgıt":["turkish"],"siftah":["turkish"],"sigorta":["turkish"],"sihirbaz":["turkish"],"silah":["turkish"],"silecek":["turkish"],"silindir":["turkish"],"simetri":["turkish"],"simge":["turkish"],"simit":["turkish"],"sincap":["turkish"],"sindirim":["turkish"],"sinema":["turkish"],"sinirli":["turkish"],"sipariş":["turkish"],"sirke":["turkish"],"siroz":["turkish"],"sistem":["turkish"],"sivilce":["turkish"],"siyasi":["turkish"],"soba":["turkish"],"sofra":["turkish"],"soğuk":["turkish"],"sohbet":["turkish"],"sokak":["turkish"],"solfej":["turkish"],"solunum":["turkish"],"somut":["turkish"],"sonbahar":["turkish"],"sonraki":["turkish"],"sonsuz":["turkish"],"sorunsuz":["turkish"],"sosyete":["turkish"],"soyağacı":["turkish"],"soydaş":["turkish"],"soygun":["turkish"],"soytarı":["turkish"],"söğüş":["turkish"],"sömürge":["turkish"],"sönük":["turkish"],"söylem":["turkish"],"sözcük":["turkish"],"sözde":["turkish"],"spatula":["turkish"],"spektrum":["turkish"],"spiker":["turkish"],"sporcu":["turkish"],"sprey":["turkish"],"stabil":["turkish"],"statü":["turkish"],"stok":["turkish"],"stopaj":["turkish"],"strateji":["turkish"],"subay":["turkish"],"sucuk":["turkish"],"suçüstü":["turkish"],"suhulet":["turkish"],"sulama":["turkish"],"sungur":["turkish"],"sunucu":["turkish"],"surat":["turkish"],"susam":["turkish"],"suskun":["turkish"],"sükse":["turkish"],"sükut":["turkish"],"sülale":["turkish"],"sünger":["turkish"],"süpürge":["turkish"],"sürahi":["turkish"],"süreç":["turkish"],"sürgün":["turkish"],"sürüm":["turkish"],"süsleme":["turkish"],"sütanne":["turkish"],"sütlaç":["turkish"],"sütun":["turkish"],"süvari":["turkish"],"şahane":["turkish"],"şahbaz":["turkish"],"şahit":["turkish"],"şahsiyet":["turkish"],"şakıma":["turkish"],"şaklaban":["turkish"],"şakrak":["turkish"],"şamar":["turkish"],"şampiyon":["turkish"],"şanslı":["turkish"],"şantiye":["turkish"],"şapka":["turkish"],"şarkıcı":["turkish"],"şartname":["turkish"],"şaşırma":["turkish"],"şaşkın":["turkish"],"şatafat":["turkish"],"şayet":["turkish"],"şebeke":["turkish"],"şefkat":["turkish"],"şeftali":["turkish"],"şehir":["turkish"],"şehvet":["turkish"],"şeker":["turkish"],"şekil":["turkish"],"şelale":["turkish"],"şema":["turkish"],"şemsiye":["turkish"],"şerbet":["turkish"],"şeref":["turkish"],"şerit":["turkish"],"şımarık":["turkish"],"şıpıdık":["turkish"],"şifre":["turkish"],"şimdi":["turkish"],"şimşek":["turkish"],"şipşak":["turkish"],"şirin":["turkish"],"şişe":["turkish"],"şişirme":["turkish"],"şofben":["turkish"],"şöhret":["turkish"],"şölen":["turkish"],"şüphe":["turkish"],"tabaka":["turkish"],"tabure":["turkish"],"tadilat":["turkish"],"taharet":["turkish"],"tahıl":["turkish"],"tahkim":["turkish"],"tahlil":["turkish"],"tahmin":["turkish"],"tahrifat":["turkish"],"tahsilat":["turkish"],"tahta":["turkish"],"taklit":["turkish"],"takoz":["turkish"],"taksici":["turkish"],"taktik":["turkish"],"takvim":["turkish"],"talebe":["turkish"],"talip":["turkish"],"tamamen":["turkish"],"tamirci":["turkish"],"tamtakır":["turkish"],"tandır":["turkish"],"tanecik":["turkish"],"tanıtım":["turkish"],"tanrı":["turkish"],"tansiyon":["turkish"],"tapan":["turkish"],"tapınak":["turkish"],"taptaze":["turkish"],"tapu":["turkish"],"tarafgir":["turkish"],"tarhana":["turkish"],"tarım":["turkish"],"tarih":["turkish"],"tarla":["turkish"],"tartak":["turkish"],"tarumar":["turkish"],"tasarım":["turkish"],"tasdik":["turkish"],"taslak":["turkish"],"tastamam":["turkish"],"taşeron":["turkish"],"taşınmaz":["turkish"],"taşra":["turkish"],"tatava":["turkish"],"tatbikat":["turkish"],"tatil":["turkish"],"tatlı":["turkish"],"tavsiye":["turkish"],"tavşan":["turkish"],"tavuk":["turkish"],"taze":["turkish"],"taziye":["turkish"],"tazminat":["turkish"],"tebeşir":["turkish"],"tebrik":["turkish"],"tecrübe":["turkish"],"teçhizat":["turkish"],"tedarik":["turkish"],"tedbir":["turkish"],"teftiş":["turkish"],"teğet":["turkish"],"teğmen":["turkish"],"tehdit":["turkish"],"tehlike":["turkish"],"tekdüze":["turkish"],"tekerlek":["turkish"],"tekme":["turkish"],"teknik":["turkish"],"tekrar":["turkish"],"telef":["turkish"],"telsiz":["turkish"],"telve":["turkish"],"temas":["turkish"],"tembel":["turkish"],"temiz":["turkish"],"temkin":["turkish"],"temsilci":["turkish"],"tendon":["turkish"],"teneke":["turkish"],"tenha":["turkish"],"tenkit":["turkish"],"tepegöz":["turkish"],"tepki":["turkish"],"terazi":["turkish"],"terbiye":["turkish"],"tercih":["turkish"],"tereyağı":["turkish"],"terfi":["turkish"],"terim":["turkish"],"terminal":["turkish"],"tersane":["turkish"],"tertip":["turkish"],"tesadüf":["turkish"],"tescil":["turkish"],"tesir":["turkish"],"teslimat":["turkish"],"tespit":["turkish"],"testere":["turkish"],"teşekkür":["turkish"],"teşhir":["turkish"],"teşrif":["turkish"],"teşvik":["turkish"],"teyze":["turkish"],"tezahür":["turkish"],"tezgah":["turkish"],"tıbbi":["turkish"],"tıkaç":["turkish"],"tıkışık":["turkish"],"tıknaz":["turkish"],"tılsım":["turkish"],"tıpkı":["turkish"],"tıraş":["turkish"],"tırışka":["turkish"],"tırmanış":["turkish"],"tırnak":["turkish"],"tırpan":["turkish"],"tıslama":["turkish"],"ticaret":["turkish"],"tilki":["turkish"],"tiryaki":["turkish"],"titreşim":["turkish"],"tohum":["turkish"],"tokat":["turkish"],"tolere":["turkish"],"tombak":["turkish"],"tomurcuk":["turkish"],"topaç":["turkish"],"toplum":["turkish"],"toprak":["turkish"],"toptan":["turkish"],"toraman":["turkish"],"torpido":["turkish"],"tortu":["turkish"],"tosbağa":["turkish"],"toynak":["turkish"],"tören":["turkish"],"trafik":["turkish"],"trajedi":["turkish"],"tramvay":["turkish"],"tribün":["turkish"],"triko":["turkish"],"tugay":["turkish"],"tuğla":["turkish"],"tuğrul":["turkish"],"tuhaf":["turkish"],"tulumba":["turkish"],"tunç":["turkish"],"turan":["turkish"],"turkuaz":["turkish"],"turnusol":["turkish"],"turşu":["turkish"],"turuncu":["turkish"],"tutanak":["turkish"],"tutkal":["turkish"],"tutsak":["turkish"],"tutum":["turkish"],"tuyuğ":["turkish"],"tuzlu":["turkish"],"tüccar":["turkish"],"tüfek":["turkish"],"tükenmez":["turkish"],"tülbent":["turkish"],"tümleç":["turkish"],"tünel":["turkish"],"türbin":["turkish"],"türev":["turkish"],"türk":["turkish"],"tüzük":["turkish"],"ucube":["turkish"],"ucuz":["turkish"],"uçak":["turkish"],"uçurtma":["turkish"],"ufuk":["turkish"],"uğrak":["turkish"],"uğur":["turkish"],"ukala":["turkish"],"ulaşım":["turkish"],"ulema":["turkish"],"ulus":["turkish"],"ulvi":["turkish"],"umursama":["turkish"],"umut":["turkish"],"unutkan":["turkish"],"uslu":["turkish"],"ustabaşı":["turkish"],"ustura":["turkish"],"usul":["turkish"],"utangaç":["turkish"],"uyanık":["turkish"],"uyarı":["turkish"],"uydu":["turkish"],"uygar":["turkish"],"uygulama":["turkish"],"uykusuz":["turkish"],"uysal":["turkish"],"uyuşma":["turkish"],"uzantı":["turkish"],"uzay":["turkish"],"uzgören":["turkish"],"uzlaşma":["turkish"],"uzman":["turkish"],"uzun":["turkish"],"ücra":["turkish"],"ücret":["turkish"],"üçbudak":["turkish"],"üçgen":["turkish"],"üçkağıt":["turkish"],"üçleme":["turkish"],"üfürük":["turkish"],"ülke":["turkish"],"ümit":["turkish"],"üniforma":["turkish"],"ünite":["turkish"],"ünlem":["turkish"],"üretken":["turkish"],"ürün":["turkish"],"üslup":["turkish"],"üstel":["turkish"],"üstün":["turkish"],"üşengeç":["turkish"],"üşüme":["turkish"],"ütopya":["turkish"],"üvey":["turkish"],"üzengi":["turkish"],"üzgün":["turkish"],"üzüm":["turkish"],"vaka":["turkish"],"vakfiye":["turkish"],"vakıf":["turkish"],"vakit":["turkish"],"vakum":["turkish"],"vapur":["turkish"],"varil":["turkish"],"varlık":["turkish"],"varsayım":["turkish"],"varyemez":["turkish"],"vasıta":["turkish"],"vasiyet":["turkish"],"vatandaş":["turkish"],"vazife":["turkish"],"vazo":["turkish"],"veciz":["turkish"],"vefa":["turkish"],"vehim":["turkish"],"veliaht":["turkish"],"veresiye":["turkish"],"verimli":["turkish"],"verkaç":["turkish"],"vernik":["turkish"],"vertigo":["turkish"],"vesait":["turkish"],"vesika":["turkish"],"vestiyer":["turkish"],"veznedar":["turkish"],"vicdan":["turkish"],"vilayet":["turkish"],"virane":["turkish"],"virgül":["turkish"],"vişne":["turkish"],"vites":["turkish"],"vokal":["turkish"],"volkan":["turkish"],"vurma":["turkish"],"vurucu":["turkish"],"vücut":["turkish"],"yabancı":["turkish"],"yabgu":["turkish"],"yağış":["turkish"],"yağlı":["turkish"],"yağmur":["turkish"],"yakamoz":["turkish"],"yakın":["turkish"],"yaklaşık":["turkish"],"yalçın":["turkish"],"yalıtım":["turkish"],"yaman":["turkish"],"yanardağ":["turkish"],"yangın":["turkish"],"yanıt":["turkish"],"yankı":["turkish"],"yanlış":["turkish"],"yansıma":["turkish"],"yapay":["turkish"],"yapboz":["turkish"],"yapımcı":["turkish"],"yaprak":["turkish"],"yaratık":["turkish"],"yarbay":["turkish"],"yardım":["turkish"],"yargıç":["turkish"],"yarıçap":["turkish"],"yasemin":["turkish"],"yastık":["turkish"],"yaşam":["turkish"],"yatak":["turkish"],"yatırım":["turkish"],"yavru":["turkish"],"yaygara":["turkish"],"yayıncı":["turkish"],"yayla":["turkish"],"yazılım":["turkish"],"yekpare":["turkish"],"yekvücut":["turkish"],"yelkovan":["turkish"],"yelpaze":["turkish"],"yemek":["turkish"],"yemiş":["turkish"],"yengeç":["turkish"],"yeniçeri":["turkish"],"yeraltı":["turkish"],"yerküre":["turkish"],"yerleşke":["turkish"],"yeryüzü":["turkish"],"yeşil":["turkish"],"yetenek":["turkish"],"yetkili":["turkish"],"yığınak":["turkish"],"yıkama":["turkish"],"yılbaşı":["turkish"],"yıldırım":["turkish"],"yılkı":["turkish"],"yılmaz":["turkish"],"yırtıcı":["turkish"],"yiğit":["turkish"],"yoğurt":["turkish"],"yokuş":["turkish"],"yolcu":["turkish"],"yoldaş":["turkish"],"yolgeçen":["turkish"],"yolkesen":["turkish"],"yolüstü":["turkish"],"yordam":["turkish"],"yorgan":["turkish"],"yorumcu":["turkish"],"yosun":["turkish"],"yöndeş":["turkish"],"yönetim":["turkish"],"yönlü":["turkish"],"yöntem":["turkish"],"yöresel":["turkish"],"yörünge":["turkish"],"yufka":["turkish"],"yukarı":["turkish"],"yumruk":["turkish"],"yumurta":["turkish"],"yuvarlak":["turkish"],"yücelme":["turkish"],"yükçeker":["turkish"],"yüklem":["turkish"],"yüksek":["turkish"],"yürek":["turkish"],"yürütme":["turkish"],"yüzde":["turkish"],"yüzeysel":["turkish"],"yüzgeç":["turkish"],"yüzüstü":["turkish"],"yüzyıl":["turkish"],"zabıta":["turkish"],"zafer":["turkish"],"zahmet":["turkish"],"zambak":["turkish"],"zaptiye":["turkish"],"zarafet":["turkish"],"zaruret":["turkish"],"zeka":["turkish"],"zekice":["turkish"],"zemberek":["turkish"],"zemin":["turkish"],"zencefil":["turkish"],"zeplin":["turkish"],"zeytin":["turkish"],"zıbın":["turkish"],"zılgıt":["turkish"],"zımbırtı":["turkish"],"zımpara":["turkish"],"zıpkın":["turkish"],"zigon":["turkish"],"zihinsel":["turkish"],"zihniyet":["turkish"],"zincir":["turkish"],"zindan":["turkish"],"zirzop":["turkish"],"ziyaret":["turkish"],"ziynet":["turkish"],"zoraki":["turkish"],"zorlu":["turkish"],"zorunlu":["turkish"],"züğürt":["turkish"],"zümre":["turkish"]}["abacate","abaixo","abalar","abater","abduzir","abelha","aberto","abismo","abotoar","abranger","abreviar","abrigar","abrupto","absinto","absoluto","absurdo","abutre","acabado","acalmar","acampar","acanhar","acaso","aceitar","acelerar","acenar","acervo","acessar","acetona","achatar","acidez","acima","acionado","acirrar","aclamar","aclive","acolhida","acomodar","acoplar","acordar","acumular","acusador","adaptar","adega","adentro","adepto","adequar","aderente","adesivo","adeus","adiante","aditivo","adjetivo","adjunto","admirar","adorar","adquirir","adubo","adverso","advogado","aeronave","afastar","aferir","afetivo","afinador","afivelar","aflito","afluente","afrontar","agachar","agarrar","agasalho","agenciar","agilizar","agiota","agitado","agora","agradar","agreste","agrupar","aguardar","agulha","ajoelhar","ajudar","ajustar","alameda","alarme","alastrar","alavanca","albergue","albino","alcatra","aldeia","alecrim","alegria","alertar","alface","alfinete","algum","alheio","aliar","alicate","alienar","alinhar","aliviar","almofada","alocar","alpiste","alterar","altitude","alucinar","alugar","aluno","alusivo","alvo","amaciar","amador","amarelo","amassar","ambas","ambiente","ameixa","amenizar","amido","amistoso","amizade","amolador","amontoar","amoroso","amostra","amparar","ampliar","ampola","anagrama","analisar","anarquia","anatomia","andaime","anel","anexo","angular","animar","anjo","anomalia","anotado","ansioso","anterior","anuidade","anunciar","anzol","apagador","apalpar","apanhado","apego","apelido","apertada","apesar","apetite","apito","aplauso","aplicada","apoio","apontar","aposta","aprendiz","aprovar","aquecer","arame","aranha","arara","arcada","ardente","areia","arejar","arenito","aresta","argiloso","argola","arma","arquivo","arraial","arrebate","arriscar","arroba","arrumar","arsenal","arterial","artigo","arvoredo","asfaltar","asilado","aspirar","assador","assinar","assoalho","assunto","astral","atacado","atadura","atalho","atarefar","atear","atender","aterro","ateu","atingir","atirador","ativo","atoleiro","atracar","atrevido","atriz","atual","atum","auditor","aumentar","aura","aurora","autismo","autoria","autuar","avaliar","avante","avaria","avental","avesso","aviador","avisar","avulso","axila","azarar","azedo","azeite","azulejo","babar","babosa","bacalhau","bacharel","bacia","bagagem","baiano","bailar","baioneta","bairro","baixista","bajular","baleia","baliza","balsa","banal","bandeira","banho","banir","banquete","barato","barbado","baronesa","barraca","barulho","baseado","bastante","batata","batedor","batida","batom","batucar","baunilha","beber","beijo","beirada","beisebol","beldade","beleza","belga","beliscar","bendito","bengala","benzer","berimbau","berlinda","berro","besouro","bexiga","bezerro","bico","bicudo","bienal","bifocal","bifurcar","bigorna","bilhete","bimestre","bimotor","biologia","biombo","biosfera","bipolar","birrento","biscoito","bisneto","bispo","bissexto","bitola","bizarro","blindado","bloco","bloquear","boato","bobagem","bocado","bocejo","bochecha","boicotar","bolada","boletim","bolha","bolo","bombeiro","bonde","boneco","bonita","borbulha","borda","boreal","borracha","bovino","boxeador","branco","brasa","braveza","breu","briga","brilho","brincar","broa","brochura","bronzear","broto","bruxo","bucha","budismo","bufar","bule","buraco","busca","busto","buzina","cabana","cabelo","cabide","cabo","cabrito","cacau","cacetada","cachorro","cacique","cadastro","cadeado","cafezal","caiaque","caipira","caixote","cajado","caju","calafrio","calcular","caldeira","calibrar","calmante","calota","camada","cambista","camisa","camomila","campanha","camuflar","canavial","cancelar","caneta","canguru","canhoto","canivete","canoa","cansado","cantar","canudo","capacho","capela","capinar","capotar","capricho","captador","capuz","caracol","carbono","cardeal","careca","carimbar","carneiro","carpete","carreira","cartaz","carvalho","casaco","casca","casebre","castelo","casulo","catarata","cativar","caule","causador","cautelar","cavalo","caverna","cebola","cedilha","cegonha","celebrar","celular","cenoura","censo","centeio","cercar","cerrado","certeiro","cerveja","cetim","cevada","chacota","chaleira","chamado","chapada","charme","chatice","chave","chefe","chegada","cheiro","cheque","chicote","chifre","chinelo","chocalho","chover","chumbo","chutar","chuva","cicatriz","ciclone","cidade","cidreira","ciente","cigana","cimento","cinto","cinza","ciranda","circuito","cirurgia","citar","clareza","clero","clicar","clone","clube","coado","coagir","cobaia","cobertor","cobrar","cocada","coelho","coentro","coeso","cogumelo","coibir","coifa","coiote","colar","coleira","colher","colidir","colmeia","colono","coluna","comando","combinar","comentar","comitiva","comover","complexo","comum","concha","condor","conectar","confuso","congelar","conhecer","conjugar","consumir","contrato","convite","cooperar","copeiro","copiador","copo","coquetel","coragem","cordial","corneta","coronha","corporal","correio","cortejo","coruja","corvo","cosseno","costela","cotonete","couro","couve","covil","cozinha","cratera","cravo","creche","credor","creme","crer","crespo","criada","criminal","crioulo","crise","criticar","crosta","crua","cruzeiro","cubano","cueca","cuidado","cujo","culatra","culminar","culpar","cultura","cumprir","cunhado","cupido","curativo","curral","cursar","curto","cuspir","custear","cutelo","damasco","datar","debater","debitar","deboche","debulhar","decalque","decimal","declive","decote","decretar","dedal","dedicado","deduzir","defesa","defumar","degelo","degrau","degustar","deitado","deixar","delator","delegado","delinear","delonga","demanda","demitir","demolido","dentista","depenado","depilar","depois","depressa","depurar","deriva","derramar","desafio","desbotar","descanso","desenho","desfiado","desgaste","desigual","deslize","desmamar","desova","despesa","destaque","desviar","detalhar","detentor","detonar","detrito","deusa","dever","devido","devotado","dezena","diagrama","dialeto","didata","difuso","digitar","dilatado","diluente","diminuir","dinastia","dinheiro","diocese","direto","discreta","disfarce","disparo","disquete","dissipar","distante","ditador","diurno","diverso","divisor","divulgar","dizer","dobrador","dolorido","domador","dominado","donativo","donzela","dormente","dorsal","dosagem","dourado","doutor","drenagem","drible","drogaria","duelar","duende","dueto","duplo","duquesa","durante","duvidoso","eclodir","ecoar","ecologia","edificar","edital","educado","efeito","efetivar","ejetar","elaborar","eleger","eleitor","elenco","elevador","eliminar","elogiar","embargo","embolado","embrulho","embutido","emenda","emergir","emissor","empatia","empenho","empinado","empolgar","emprego","empurrar","emulador","encaixe","encenado","enchente","encontro","endeusar","endossar","enfaixar","enfeite","enfim","engajado","engenho","englobar","engomado","engraxar","enguia","enjoar","enlatar","enquanto","enraizar","enrolado","enrugar","ensaio","enseada","ensino","ensopado","entanto","enteado","entidade","entortar","entrada","entulho","envergar","enviado","envolver","enxame","enxerto","enxofre","enxuto","epiderme","equipar","ereto","erguido","errata","erva","ervilha","esbanjar","esbelto","escama","escola","escrita","escuta","esfinge","esfolar","esfregar","esfumado","esgrima","esmalte","espanto","espelho","espiga","esponja","espreita","espumar","esquerda","estaca","esteira","esticar","estofado","estrela","estudo","esvaziar","etanol","etiqueta","euforia","europeu","evacuar","evaporar","evasivo","eventual","evidente","evoluir","exagero","exalar","examinar","exato","exausto","excesso","excitar","exclamar","executar","exemplo","exibir","exigente","exonerar","expandir","expelir","expirar","explanar","exposto","expresso","expulsar","externo","extinto","extrato","fabricar","fabuloso","faceta","facial","fada","fadiga","faixa","falar","falta","familiar","fandango","fanfarra","fantoche","fardado","farelo","farinha","farofa","farpa","fartura","fatia","fator","favorita","faxina","fazenda","fechado","feijoada","feirante","felino","feminino","fenda","feno","fera","feriado","ferrugem","ferver","festejar","fetal","feudal","fiapo","fibrose","ficar","ficheiro","figurado","fileira","filho","filme","filtrar","firmeza","fisgada","fissura","fita","fivela","fixador","fixo","flacidez","flamingo","flanela","flechada","flora","flutuar","fluxo","focal","focinho","fofocar","fogo","foguete","foice","folgado","folheto","forjar","formiga","forno","forte","fosco","fossa","fragata","fralda","frango","frasco","fraterno","freira","frente","fretar","frieza","friso","fritura","fronha","frustrar","fruteira","fugir","fulano","fuligem","fundar","fungo","funil","furador","furioso","futebol","gabarito","gabinete","gado","gaiato","gaiola","gaivota","galega","galho","galinha","galocha","ganhar","garagem","garfo","gargalo","garimpo","garoupa","garrafa","gasoduto","gasto","gata","gatilho","gaveta","gazela","gelado","geleia","gelo","gemada","gemer","gemido","generoso","gengiva","genial","genoma","genro","geologia","gerador","germinar","gesso","gestor","ginasta","gincana","gingado","girafa","girino","glacial","glicose","global","glorioso","goela","goiaba","golfe","golpear","gordura","gorjeta","gorro","gostoso","goteira","governar","gracejo","gradual","grafite","gralha","grampo","granada","gratuito","graveto","graxa","grego","grelhar","greve","grilo","grisalho","gritaria","grosso","grotesco","grudado","grunhido","gruta","guache","guarani","guaxinim","guerrear","guiar","guincho","guisado","gula","guloso","guru","habitar","harmonia","haste","haver","hectare","herdar","heresia","hesitar","hiato","hibernar","hidratar","hiena","hino","hipismo","hipnose","hipoteca","hoje","holofote","homem","honesto","honrado","hormonal","hospedar","humorado","iate","ideia","idoso","ignorado","igreja","iguana","ileso","ilha","iludido","iluminar","ilustrar","imagem","imediato","imenso","imersivo","iminente","imitador","imortal","impacto","impedir","implante","impor","imprensa","impune","imunizar","inalador","inapto","inativo","incenso","inchar","incidir","incluir","incolor","indeciso","indireto","indutor","ineficaz","inerente","infantil","infestar","infinito","inflamar","informal","infrator","ingerir","inibido","inicial","inimigo","injetar","inocente","inodoro","inovador","inox","inquieto","inscrito","inseto","insistir","inspetor","instalar","insulto","intacto","integral","intimar","intocado","intriga","invasor","inverno","invicto","invocar","iogurte","iraniano","ironizar","irreal","irritado","isca","isento","isolado","isqueiro","italiano","janeiro","jangada","janta","jararaca","jardim","jarro","jasmim","jato","javali","jazida","jejum","joaninha","joelhada","jogador","joia","jornal","jorrar","jovem","juba","judeu","judoca","juiz","julgador","julho","jurado","jurista","juro","justa","labareda","laboral","lacre","lactante","ladrilho","lagarta","lagoa","laje","lamber","lamentar","laminar","lampejo","lanche","lapidar","lapso","laranja","lareira","largura","lasanha","lastro","lateral","latido","lavanda","lavoura","lavrador","laxante","lazer","lealdade","lebre","legado","legendar","legista","leigo","leiloar","leitura","lembrete","leme","lenhador","lentilha","leoa","lesma","leste","letivo","letreiro","levar","leveza","levitar","liberal","libido","liderar","ligar","ligeiro","limitar","limoeiro","limpador","linda","linear","linhagem","liquidez","listagem","lisura","litoral","livro","lixa","lixeira","locador","locutor","lojista","lombo","lona","longe","lontra","lorde","lotado","loteria","loucura","lousa","louvar","luar","lucidez","lucro","luneta","lustre","lutador","luva","macaco","macete","machado","macio","madeira","madrinha","magnata","magreza","maior","mais","malandro","malha","malote","maluco","mamilo","mamoeiro","mamute","manada","mancha","mandato","manequim","manhoso","manivela","manobrar","mansa","manter","manusear","mapeado","maquinar","marcador","maresia","marfim","margem","marinho","marmita","maroto","marquise","marreco","martelo","marujo","mascote","masmorra","massagem","mastigar","matagal","materno","matinal","matutar","maxilar","medalha","medida","medusa","megafone","meiga","melancia","melhor","membro","memorial","menino","menos","mensagem","mental","merecer","mergulho","mesada","mesclar","mesmo","mesquita","mestre","metade","meteoro","metragem","mexer","mexicano","micro","migalha","migrar","milagre","milenar","milhar","mimado","minerar","minhoca","ministro","minoria","miolo","mirante","mirtilo","misturar","mocidade","moderno","modular","moeda","moer","moinho","moita","moldura","moleza","molho","molinete","molusco","montanha","moqueca","morango","morcego","mordomo","morena","mosaico","mosquete","mostarda","motel","motim","moto","motriz","muda","muito","mulata","mulher","multar","mundial","munido","muralha","murcho","muscular","museu","musical","nacional","nadador","naja","namoro","narina","narrado","nascer","nativa","natureza","navalha","navegar","navio","neblina","nebuloso","negativa","negociar","negrito","nervoso","neta","neural","nevasca","nevoeiro","ninar","ninho","nitidez","nivelar","nobreza","noite","noiva","nomear","nominal","nordeste","nortear","notar","noticiar","noturno","novelo","novilho","novo","nublado","nudez","numeral","nupcial","nutrir","nuvem","obcecado","obedecer","objetivo","obrigado","obscuro","obstetra","obter","obturar","ocidente","ocioso","ocorrer","oculista","ocupado","ofegante","ofensiva","oferenda","oficina","ofuscado","ogiva","olaria","oleoso","olhar","oliveira","ombro","omelete","omisso","omitir","ondulado","oneroso","ontem","opcional","operador","oponente","oportuno","oposto","orar","orbitar","ordem","ordinal","orfanato","orgasmo","orgulho","oriental","origem","oriundo","orla","ortodoxo","orvalho","oscilar","ossada","osso","ostentar","otimismo","ousadia","outono","outubro","ouvido","ovelha","ovular","oxidar","oxigenar","pacato","paciente","pacote","pactuar","padaria","padrinho","pagar","pagode","painel","pairar","paisagem","palavra","palestra","palheta","palito","palmada","palpitar","pancada","panela","panfleto","panqueca","pantanal","papagaio","papelada","papiro","parafina","parcial","pardal","parede","partida","pasmo","passado","pastel","patamar","patente","patinar","patrono","paulada","pausar","peculiar","pedalar","pedestre","pediatra","pedra","pegada","peitoral","peixe","pele","pelicano","penca","pendurar","peneira","penhasco","pensador","pente","perceber","perfeito","pergunta","perito","permitir","perna","perplexo","persiana","pertence","peruca","pescado","pesquisa","pessoa","petiscar","piada","picado","piedade","pigmento","pilastra","pilhado","pilotar","pimenta","pincel","pinguim","pinha","pinote","pintar","pioneiro","pipoca","piquete","piranha","pires","pirueta","piscar","pistola","pitanga","pivete","planta","plaqueta","platina","plebeu","plumagem","pluvial","pneu","poda","poeira","poetisa","polegada","policiar","poluente","polvilho","pomar","pomba","ponderar","pontaria","populoso","porta","possuir","postal","pote","poupar","pouso","povoar","praia","prancha","prato","praxe","prece","predador","prefeito","premiar","prensar","preparar","presilha","pretexto","prevenir","prezar","primata","princesa","prisma","privado","processo","produto","profeta","proibido","projeto","prometer","propagar","prosa","protetor","provador","publicar","pudim","pular","pulmonar","pulseira","punhal","punir","pupilo","pureza","puxador","quadra","quantia","quarto","quase","quebrar","queda","queijo","quente","querido","quimono","quina","quiosque","rabanada","rabisco","rachar","racionar","radial","raiar","rainha","raio","raiva","rajada","ralado","ramal","ranger","ranhura","rapadura","rapel","rapidez","raposa","raquete","raridade","rasante","rascunho","rasgar","raspador","rasteira","rasurar","ratazana","ratoeira","realeza","reanimar","reaver","rebaixar","rebelde","rebolar","recado","recente","recheio","recibo","recordar","recrutar","recuar","rede","redimir","redonda","reduzida","reenvio","refinar","refletir","refogar","refresco","refugiar","regalia","regime","regra","reinado","reitor","rejeitar","relativo","remador","remendo","remorso","renovado","reparo","repelir","repleto","repolho","represa","repudiar","requerer","resenha","resfriar","resgatar","residir","resolver","respeito","ressaca","restante","resumir","retalho","reter","retirar","retomada","retratar","revelar","revisor","revolta","riacho","rica","rigidez","rigoroso","rimar","ringue","risada","risco","risonho","robalo","rochedo","rodada","rodeio","rodovia","roedor","roleta","romano","roncar","rosado","roseira","rosto","rota","roteiro","rotina","rotular","rouco","roupa","roxo","rubro","rugido","rugoso","ruivo","rumo","rupestre","russo","sabor","saciar","sacola","sacudir","sadio","safira","saga","sagrada","saibro","salada","saleiro","salgado","saliva","salpicar","salsicha","saltar","salvador","sambar","samurai","sanar","sanfona","sangue","sanidade","sapato","sarda","sargento","sarjeta","saturar","saudade","saxofone","sazonal","secar","secular","seda","sedento","sediado","sedoso","sedutor","segmento","segredo","segundo","seiva","seleto","selvagem","semanal","semente","senador","senhor","sensual","sentado","separado","sereia","seringa","serra","servo","setembro","setor","sigilo","silhueta","silicone","simetria","simpatia","simular","sinal","sincero","singular","sinopse","sintonia","sirene","siri","situado","soberano","sobra","socorro","sogro","soja","solda","soletrar","solteiro","sombrio","sonata","sondar","sonegar","sonhador","sono","soprano","soquete","sorrir","sorteio","sossego","sotaque","soterrar","sovado","sozinho","suavizar","subida","submerso","subsolo","subtrair","sucata","sucesso","suco","sudeste","sufixo","sugador","sugerir","sujeito","sulfato","sumir","suor","superior","suplicar","suposto","suprimir","surdina","surfista","surpresa","surreal","surtir","suspiro","sustento","tabela","tablete","tabuada","tacho","tagarela","talher","talo","talvez","tamanho","tamborim","tampa","tangente","tanto","tapar","tapioca","tardio","tarefa","tarja","tarraxa","tatuagem","taurino","taxativo","taxista","teatral","tecer","tecido","teclado","tedioso","teia","teimar","telefone","telhado","tempero","tenente","tensor","tentar","termal","terno","terreno","tese","tesoura","testado","teto","textura","texugo","tiara","tigela","tijolo","timbrar","timidez","tingido","tinteiro","tiragem","titular","toalha","tocha","tolerar","tolice","tomada","tomilho","tonel","tontura","topete","tora","torcido","torneio","torque","torrada","torto","tostar","touca","toupeira","toxina","trabalho","tracejar","tradutor","trafegar","trajeto","trama","trancar","trapo","traseiro","tratador","travar","treino","tremer","trepidar","trevo","triagem","tribo","triciclo","tridente","trilogia","trindade","triplo","triturar","triunfal","trocar","trombeta","trova","trunfo","truque","tubular","tucano","tudo","tulipa","tupi","turbo","turma","turquesa","tutelar","tutorial","uivar","umbigo","unha","unidade","uniforme","urologia","urso","urtiga","urubu","usado","usina","usufruir","vacina","vadiar","vagaroso","vaidoso","vala","valente","validade","valores","vantagem","vaqueiro","varanda","vareta","varrer","vascular","vasilha","vassoura","vazar","vazio","veado","vedar","vegetar","veicular","veleiro","velhice","veludo","vencedor","vendaval","venerar","ventre","verbal","verdade","vereador","vergonha","vermelho","verniz","versar","vertente","vespa","vestido","vetorial","viaduto","viagem","viajar","viatura","vibrador","videira","vidraria","viela","viga","vigente","vigiar","vigorar","vilarejo","vinco","vinheta","vinil","violeta","virada","virtude","visitar","visto","vitral","viveiro","vizinho","voador","voar","vogal","volante","voleibol","voltagem","volumoso","vontade","vulto","vuvuzela","xadrez","xarope","xeque","xeretar","xerife","xingar","zangado","zarpar","zebu","zelador","zombar","zoologia","zumbido"]["абзац","абонент","абсурд","авангард","авария","август","авиация","автор","агент","агитация","агрегат","адвокат","адмирал","адрес","азарт","азот","академия","аквариум","аксиома","акула","акцент","акция","аллея","алмаз","алтарь","альбом","альянс","амбиция","анализ","анекдот","анкета","ансамбль","антенна","апельсин","аппарат","аппетит","апрель","аптека","арбуз","аргумент","аренда","арест","армия","аромат","арсенал","артерия","артист","архив","аспирант","асфальт","атака","атомный","атрибут","аукцион","афиша","аэропорт","бабочка","бабушка","багаж","база","бактерия","баланс","балерина","балкон","бандит","банк","барабан","барон","барышня","барьер","бассейн","батарея","башмак","башня","бедный","беженец","бездна","белка","белый","бензин","берег","беседа","бешеный","билет","бинокль","биржа","битва","благо","блеск","близкий","блин","блок","блюдо","богатый","бодрый","боец","бокал","боковой","бокс","более","болото","болтать","большой","бомба","борт","борьба","босой","ботинок","бояться","брак","брать","бревно","бред","бригада","бродяга","броня","бросить","брызги","брюки","брюхо","бугор","будка","будни","будущее","буква","букет","бульвар","бумага","бунт","бурный","буря","бутылка","бухта","бывший","быстро","бытовой","быть","бюджет","бюро","бюст","вагон","важный","вакцина","валенок","вальс","валюта","ванная","варенье","вариант","вблизи","вверх","вводить","вдали","вдвое","вдова","вдоль","вдруг","ведро","ведущий","ведьма","вежливо","везде","веко","вексель","велеть","великий","венец","веник","веранда","верблюд","верить","верный","версия","вертеть","верхний","вершина","весело","весна","весомый","вести","весь","ветеран","ветхий","вечер","вечно","вешалка","вещество","взамен","взгляд","вздох","взнос","взойти","взор","взрыв","взять","видеть","видимо","визг","визит","вилка","вина","вирус","висок","витамин","витрина","вихрь","вишня","вкус","влага","владелец","власть","влево","влияние","вложить","вместе","внешний","вникать","внимание","вновь","внук","внутри","внучка","внушать","вовлечь","вовремя","вовсю","вода","водород","водяной","воевать","возврат","возглас","воздух","возить","возле","возня","возраст","война","войско","вокзал","волос","волчий","вольный","воля","вообще","вопль","вопрос","ворота","восемь","восток","вплоть","вполне","вправе","впредь","впрочем","врач","вредный","время","вручить","всадник","всегда","вскоре","вскрыть","всплеск","вспышка","встреча","всюду","всякий","второй","вход","вчера","выбор","вывод","выгнать","выдать","выехать","вызов","выйти","выкуп","вылезти","вымыть","выпасть","выпить","выплата","выпуск","вырасти","выручка","выслать","высокий","выставка","вышка","вязать","вялый","газета","газовый","галерея","галстук","гамма","гарантия","гармония","гарнизон","гастроли","гвардия","гвоздь","гектар","генерал","гений","геном","геолог","герб","герой","гибкий","гигант","гимн","гипотеза","гитара","главный","глагол","гладить","глаз","глина","глоток","глубокий","глупый","глухой","глыба","глядеть","гнев","гнездо","гнилой","годовой","голова","голубой","голый","гонорар","гордость","горизонт","горло","горный","город","горшок","горький","горючее","горячий","готовый","градус","грамм","граница","граф","гребень","гриб","гримаса","грозить","грохот","грош","грубый","грудь","груз","грунт","группа","груша","грязный","губа","гудок","гулкий","гулять","гусеница","густо","гусь","давление","давно","даже","дальний","данный","дарить","датчик","дать","дача","двадцать","дважды","дверь","двигать","движение","двойной","двор","дебют","девятый","дежурный","действие","декабрь","деление","дело","дельфин","день","дерево","держать","дерзкий","десять","деталь","детский","дефект","дефицит","деятель","джаз","джинсы","джунгли","диагноз","диалог","диапазон","диван","дивизия","дивный","диета","дизайн","дикарь","дилер","динамика","диплом","директор","дитя","длинный","дневник","добрый","добыча","доверие","догадка","догнать","дождь","доклад","доктор","документ","долго","должен","долина","донос","дорога","досада","доска","достать","досуг","доход","доцент","дощатый","драка","древний","дремать","дробный","дрова","дрожать","другой","дружба","дубовый","дуга","думать","дурной","духи","душный","дуэль","дуэт","дыра","дыхание","дюжина","дядя","едва","единый","ерунда","если","ехать","жадный","жажда","жалеть","жалоба","жанр","жареный","жаркий","жгучий","жевать","желание","желудок","жена","женщина","жертва","жест","жидкость","житель","жить","жрец","жулик","журнал","жуткий","забрать","забыть","завести","завод","завтра","загадка","загнать","заговор","задача","задеть","задний","задолго","заехать","заказ","закон","закрыть","закуска","залезть","залить","залп","замок","замуж","замысел","занавес","заново","занять","заодно","запись","запрос","запуск","запястье","заранее","заросль","зарплата","заря","засада","заслуга","заснуть","застать","затвор","затеять","затрата","затылок","захват","зачем","защита","заявить","заяц","звезда","звено","звонить","здесь","зелень","земля","зеркало","зерно","зима","злой","змея","знамя","знание","значит","золотой","зона","зонтик","зоопарк","зрачок","зрение","зритель","зубной","зубр","игла","идеал","идеолог","идея","идол","идти","изба","избить","избрать","избыток","извлечь","извне","изгиб","изгнать","издание","изделие","изнутри","изобилие","изоляция","изредка","изрядно","изучение","изъять","изящный","икона","икра","иллюзия","именно","иметь","имидж","империя","импульс","иначе","инвалид","индекс","индивид","инерция","инженер","иногда","иной","институт","интерес","интрига","интуиция","инфаркт","инцидент","ирония","искать","испуг","история","итог","июнь","кабель","кабинет","каблук","кавалер","кадр","каждый","кажется","казино","калитка","камень","камин","канал","кандидат","каникулы","канон","капитан","капля","капот","капуста","карандаш","карета","каркас","карман","картина","карьера","каска","кассета","кастрюля","каталог","катер","каток","катушка","кафедра","качество","каша","кашлять","каюта","квадрат","квартира","квота","кепка","кивнуть","километр","кино","киоск","кипяток","кирпич","кислота","кисть","клавиша","клапан","класс","клей","клетка","клиент","климат","клиника","кличка","клоун","клочок","клуб","клумба","ключ","книга","кнопка","кнут","княгиня","князь","кобура","когда","кодекс","кожа","коктейль","колено","коллега","колонна","колпак","кольцо","колючий","коляска","команда","комедия","комиссия","коммуна","комната","комок","компания","комфорт","конвейер","конгресс","конечно","конкурс","контроль","концерт","конь","конюшня","копать","копейка","копыто","корабль","корень","корзина","коридор","кормить","корпус","космос","костюм","косяк","котел","котлета","который","коттедж","кофе","кофта","кошка","кража","край","красный","краткий","кредит","крем","крепкий","кресло","кривой","кризис","кристалл","критерий","кричать","кровь","крокодил","кролик","кроме","крона","круг","кружка","крупный","крутой","крушение","крыло","крыша","крючок","кстати","кубик","куда","кузов","кукла","кулак","кулиса","культура","кумир","купе","купить","купол","купюра","курица","курорт","курс","куртка","кусок","куст","кухня","кушать","лабиринт","лавка","лагерь","ладно","ладонь","лапа","лауреат","лгать","лебедь","левый","легенда","легкий","ледяной","лежать","лезвие","лезть","лекция","ленивый","лента","лепесток","лесной","лестница","лететь","лето","лечить","лига","лидер","лиловый","лимон","линия","липкий","лист","литр","лихой","лицо","лишить","лишний","ловить","логика","лодка","ложь","лозунг","локоть","лопата","лошадь","лукавый","луна","лучший","лысый","льгота","любить","любой","людской","люстра","лютый","лягушка","магазин","магия","майор","майский","максимум","макушка","мало","мальчик","мама","манера","марка","март","маршрут","масса","мастер","масштаб","материал","матч","махать","машина","маяк","мебель","медаль","медведь","медицина","медь","между","мелкий","мелочь","мемуары","меньше","меню","менять","мера","мерцать","место","месяц","металл","метод","метр","механизм","меховой","мечтать","мешать","мешок","миграция","микрофон","милиция","миллион","милость","миля","мимо","минерал","министр","минута","мирный","миска","миссия","митинг","мишень","младший","мнение","мнимый","много","могучий","модель","может","мозг","мокрый","молекула","молния","молодой","молчать","момент","монета","монитор","монолог","монстр","монтаж","мораль","море","морковь","мороз","морщина","мостовая","мотать","мотив","мотор","мохнатый","мрамор","мрачный","мстить","мудрый","мужество","мужчина","музей","музыка","мундир","муравей","мусор","муха","мчаться","мысль","мыться","мышца","мышь","мюзикл","мягкий","мясо","набор","навык","наглый","нагрузка","надежда","надзор","надо","наедине","назад","название","назло","наивный","найти","наконец","налево","наличие","налог","намерен","нанести","напасть","например","народ","наследие","натура","наука","наутро","начать","небо","неважно","невеста","негодяй","недавно","неделя","недолго","недра","недуг","нежный","незачем","некто","нелепый","неловко","нельзя","немало","немой","неплохо","нервный","нередко","нестись","неудача","неужели","нефть","неясный","нигде","низкий","никакой","никогда","никуда","ничто","ничуть","ниша","нищий","новость","новый","нога","ноготь","ножницы","ноздря","номер","носить","носок","ночь","ноябрь","нрав","нуль","нынче","нырять","нюанс","няня","обаяние","обед","обезьяна","обещать","обжечь","обзор","обилие","обитать","область","облик","обложка","обмен","обморок","обожать","обои","оболочка","оборона","обочина","образ","обрести","обрыв","обувь","обучение","обход","общество","общий","объект","обыск","обычно","обязать","овощи","овраг","овца","оговорка","ограда","огурец","одежда","одеяло","один","однако","одолеть","ожидать","озеро","океан","окно","около","окоп","окраина","октябрь","опасный","опека","операция","описание","оплата","опора","оппонент","оптимизм","оптовый","опухоль","опыт","оратор","орбита","орган","орден","орел","оригинал","ориентир","оркестр","оружие","осенний","осколок","осмотр","остров","отбор","отбыть","отвлечь","отдать","отдел","отдых","отель","отец","отзыв","отказ","отклик","открыть","откуда","отличие","отныне","отойти","отпуск","отрасль","отросток","отрывок","отряд","отсек","отставка","отсюда","оттенок","оттого","отчего","отъезд","офис","офицер","охота","охрана","оценка","очаг","очень","очередь","очищать","ошибка","ощущение","павильон","падать","пазуха","пакет","палата","палец","палуба","пальто","память","панель","паника","пара","парень","пароход","партия","парус","паспорт","пассажир","пастух","патент","патрон","пауза","паук","паутина","пафос","пахнуть","пациент","пачка","певец","педагог","пейзаж","пенсия","пепел","первый","перед","период","перо","перрон","персонаж","перчатка","песня","песок","петля","петрушка","петух","пехота","печать","печень","пешком","пещера","пианист","пиджак","пилот","пионер","пирамида","пирожок","письмо","пища","плавание","плакать","пламя","план","пласт","платить","пленный","плечо","плита","плод","плоский","плотный","плохой","площадь","плыть","плюс","пляж","плясать","победа","повар","повод","повсюду","повязка","погода","погреб","подбор","подвиг","подделка","поджать","поднос","подпись","подруга","подход","подчас","подъезд","поединок","поезд","поесть","поехать","пожалуй","пожилой","позади","позвать","поздний","позиция","позор","поиск","поймать","пойти","поклон","покой","покрыть","полдень","полезный","ползти","полк","полный","половина","полтора","польза","поляна","помидор","помнить","помощь","попасть","поперек","поплыть","пополам","поправка","попугай","попытка","порог","портрет","порция","порыв","порядок","после","посол","посреди","постель","посуда","потом","похвала","похожий","поцелуй","почва","почему","пошлина","поэма","поэтому","право","праздник","практика","прах","преграда","предмет","прежде","прелесть","премия","препарат","пресса","прибыть","прижать","прийти","приказ","прилавок","пример","принять","природа","притом","прихожая","прицел","причина","приют","прогноз","продукт","проект","прожить","прокат","промысел","пропуск","просто","против","профиль","процесс","прочий","прошлый","прощать","пружина","прут","прыжок","прямой","птица","публика","пугать","пуговица","пузырь","пульт","пуля","пункт","пускать","пустой","путь","пухлый","пучок","пушистый","пушка","пчела","пшеница","пылать","пыль","пышный","пьеса","пятка","пятно","пятый","пятьсот","работа","равнина","ради","радость","радуга","разбить","развитие","разговор","раздел","различие","размер","разный","разрыв","разум","район","ракета","раковина","рамка","рано","рапорт","распад","рассказ","расти","расход","расцвет","рация","рвануть","рваться","реакция","ребро","реветь","редактор","редкий","реестр","режим","резать","резерв","резина","резко","резной","рейс","реклама","рекорд","религия","рельс","ремень","ремонт","реплика","репортаж","ресница","ресторан","реформа","рецепт","речь","решение","ржавый","риск","рисунок","ритуал","рифма","робко","робот","ровесник","ровно","родной","рождение","роза","розовый","розыск","роль","роман","роскошь","роспись","рост","рубашка","рубеж","рубить","рубрика","рудник","рука","рукопись","румяный","русло","рухнуть","ручей","ручной","рыба","рыжий","рынок","рыхлый","рыцарь","рычаг","рюкзак","рядом","садовый","сажать","салон","салфетка","салют","самец","самовар","самый","сани","санкция","сапог","сарай","сатира","сахар","сбить","сбоку","сборная","сбыт","свадьба","свалка","сварить","свежий","сверху","свет","свеча","свинья","свист","свитер","свобода","сводка","свой","свыше","связь","сдаться","сделать","сегмент","сегодня","седло","седой","седьмой","сезон","сейф","сейчас","секрет","сектор","секунда","семинар","семья","сенатор","сено","сенсация","сентябрь","сервис","сердце","середина","сержант","серия","серый","сессия","сесть","сетевой","сжатый","сжечь","сзади","сигнал","сиденье","сила","силуэт","сильный","символ","симпатия","симфония","синий","синтез","синяк","сирень","система","ситуация","сияние","сказать","скала","скамейка","скандал","скатерть","скачок","скважина","сквер","сквозь","скелет","скидка","склад","сколько","скорый","скосить","скот","скрипка","скудный","скука","слабый","слава","сладкий","слегка","след","слеза","слепой","слесарь","слишком","слово","слог","сложный","сломать","служба","слух","случай","слышать","слюна","смежный","смелый","сменить","смесь","сметана","смех","смола","смуглый","смутный","смущать","смысл","снайпер","снаряд","сначала","снег","снизу","сниться","сно��а","снять","собака","соблазн","собрание","событие","совесть","совсем","согласие","создать","сознание","созреть","сойтись","сокол","солдат","соленый","солнце","солома","сомнение","сонный","соперник","соратник","сорвать","сосед","сосиска","состав","сотня","соус","союз","спад","спальня","спасти","спектр","сперва","спешить","спина","спирт","список","спичка","сплав","спонсор","спор","способ","справка","спустя","спутник","сразу","средство","срок","срыв","ссора","ссылка","ставить","стадия","стакан","станция","старый","стая","стебель","стекло","стена","степень","стереть","стиль","стимул","стирать","стихи","стоить","стойка","стол","стонать","стопа","сторона","стоянка","страна","стричь","строгий","струя","студент","стук","ступня","стыдно","суббота","субъект","сувенир","сугроб","сугубо","судить","судно","судьба","суета","суметь","сумма","сумрак","сундук","супруг","суровый","сутки","сухой","суша","существо","сфера","схема","схожий","сценарий","счастье","считать","съезд","сыграть","сырой","сытый","сыщик","сюда","сюжет","сюрприз","тайна","также","такой","такси","тактика","талия","таможня","танец","таракан","тарелка","тариф","тащить","таять","тварь","театр","тезис","текст","текущий","телефон","тема","темнота","теневой","теннис","теория","теперь","тепло","терапия","терзать","термин","терпеть","терраса","терять","тесный","тетрадь","техника","течение","тигр","типовой","тираж","титул","тихий","ткань","товарищ","тоже","толпа","толстый","толчок","толщина","только","тонкий","тонна","топить","топор","торговля","тормоз","торчать","тотчас","точка","точно","тощий","трава","традиция","трактор","трамвай","траншея","трасса","тревога","трезвый","тренер","трепет","треск","третий","трещина","трибуна","тридцать","триста","триумф","трогать","тройка","тронуть","тропа","тротуар","трубка","труд","трюк","тряпка","туго","туловище","туман","тумбочка","тундра","тупик","турист","турнир","тусклый","туфля","туча","тысяча","тяга","тяжело","убежать","убогий","уборка","уважение","увезти","уволить","угадать","угол","угощать","угроза","угрюмый","удар","удачный","уделять","удивить","удобный","удочка","уезжать","ужин","узел","узкий","уйти","указание","уклон","украсть","укусить","улетать","улица","улыбка","умело","умение","умный","умолять","унести","унижать","унылый","упаковка","упасть","упорно","упрек","урна","уровень","урожай","уронить","усадьба","усатый","усвоить","усилие","условие","услуга","усмешка","успеть","устав","устоять","утечка","утешать","утро","уцелеть","участие","ученик","учесть","ущелье","ущерб","уютный","фабрика","фаворит","факел","факт","фамилия","фантазия","фасад","февраль","феномен","фермер","фигура","физика","филиал","философ","фильм","финал","флаг","флот","фойе","фокус","фонарь","фонд","фонтан","форма","форум","фото","фрагмент","фраза","фракция","фронт","фрукт","функция","фуражка","футбол","футляр","халат","хаос","характер","хата","хвалить","хватать","хвойный","хвост","химия","хирург","хитрый","хищник","хлеб","хлынуть","хмурый","ходить","хозяин","хоккей","холм","холст","хорошо","хотеть","храбрый","храм","хранить","хребет","хрен","хрипло","хроника","хрупкий","художник","худший","хулиган","хутор","царь","цветок","целевой","целиком","целое","цель","цензура","ценить","центр","цепной","цикл","цилиндр","цирк","цитата","цифра","чайник","часы","чашка","человек","челюсть","чемодан","чемпион","чепуха","червь","чердак","через","чернила","черта","чеснок","честно","четверть","четыре","число","чистый","читатель","чтение","чтобы","чувство","чудак","чудный","чудо","чужой","чулок","чума","чушь","чуять","шагать","шанс","шапка","шарик","шарф","шахматы","шашлык","шедевр","шептать","шерсть","шестой","шинель","ширина","шишка","шкаф","школа","шкура","шланг","шлем","шнур","шоколад","шорох","шоссе","шпион","шприц","штаб","штамм","штаны","штатный","штора","штраф","штурм","штык","шумно","шуршать","шутить","шутка","щедрый","щека","щенок","экзамен","экипаж","экономия","экран","эксперт","элемент","элитный","эмоция","энергия","эпизод","эпоха","эскиз","эстрада","этап","этика","этот","эфир","эффект","эшелон","юбилей","юбка","южный","юмор","юность","юрист","юстиция","яблоко","явление","ягода","ядро","язык","яйцо","якобы","якорь","январь","яркий","ярмарка","ярость","ясный","яхта","ячейка","ящик"]["ábaco","abdomen","abeja","abierto","abogado","abono","aborto","abrazo","abrir","abuelo","abuso","acabar","academia","acceso","acción","aceite","acelga","acento","aceptar","ácido","aclarar","acné","acoger","acoso","activo","acto","actriz","actuar","acudir","acuerdo","acusar","adicto","admitir","adoptar","adorno","aduana","adulto","aéreo","afectar","afición","afinar","afirmar","ágil","agitar","agonía","agosto","agotar","agregar","agrio","agua","agudo","águila","aguja","ahogo","ahorro","aire","aislar","ajedrez","ajeno","ajuste","alacrán","alambre","alarma","alba","álbum","alcalde","aldea","alegre","alejar","alerta","aleta","alfiler","alga","algodón","aliado","aliento","alivio","alma","almeja","almíbar","altar","alteza","altivo","alto","altura","alumno","alzar","amable","amante","amapola","amargo","amasar","ámbar","ámbito","ameno","amigo","amistad","amor","amparo","amplio","ancho","anciano","ancla","andar","andén","anemia","ángulo","anillo","ánimo","anís","anotar","antena","antiguo","antojo","anual","anular","anuncio","añadir","añejo","año","apagar","aparato","apetito","apio","aplicar","apodo","aporte","apoyo","aprender","aprobar","apuesta","apuro","arado","araña","arar","árbitro","árbol","arbusto","archivo","arco","arder","ardilla","arduo","área","árido","aries","armonía","arnés","aroma","arpa","arpón","arreglo","arroz","arruga","arte","artista","asa","asado","asalto","ascenso","asegurar","aseo","asesor","asiento","asilo","asistir","asno","asombro","áspero","astilla","astro","astuto","asumir","asunto","atajo","ataque","atar","atento","ateo","ático","atleta","átomo","atraer","atroz","atún","audaz","audio","auge","aula","aumento","ausente","autor","aval","avance","avaro","ave","avellana","avena","avestruz","avión","aviso","ayer","ayuda","ayuno","azafrán","azar","azote","azúcar","azufre","azul","baba","babor","bache","bahía","baile","bajar","balanza","balcón","balde","bambú","banco","banda","baño","barba","barco","barniz","barro","báscula","bastón","basura","batalla","batería","batir","batuta","baúl","bazar","bebé","bebida","bello","besar","beso","bestia","bicho","bien","bingo","blanco","bloque","blusa","boa","bobina","bobo","boca","bocina","boda","bodega","boina","bola","bolero","bolsa","bomba","bondad","bonito","bono","bonsái","borde","borrar","bosque","bote","botín","bóveda","bozal","bravo","brazo","brecha","breve","brillo","brinco","brisa","broca","broma","bronce","brote","bruja","brusco","bruto","buceo","bucle","bueno","buey","bufanda","bufón","búho","buitre","bulto","burbuja","burla","burro","buscar","butaca","buzón","caballo","cabeza","cabina","cabra","cacao","cadáver","cadena","caer","café","caída","caimán","caja","cajón","cal","calamar","calcio","caldo","calidad","calle","calma","calor","calvo","cama","cambio","camello","camino","campo","cáncer","candil","canela","canguro","canica","canto","caña","cañón","caoba","caos","capaz","capitán","capote","captar","capucha","cara","carbón","cárcel","careta","carga","cariño","carne","carpeta","carro","carta","casa","casco","casero","caspa","castor","catorce","catre","caudal","causa","cazo","cebolla","ceder","cedro","celda","célebre","celoso","célula","cemento","ceniza","centro","cerca","cerdo","cereza","cero","cerrar","certeza","césped","cetro","chacal","chaleco","champú","chancla","chapa","charla","chico","chiste","chivo","choque","choza","chuleta","chupar","ciclón","ciego","cielo","cien","cierto","cifra","cigarro","cima","cinco","cine","cinta","ciprés","circo","ciruela","cisne","cita","ciudad","clamor","clan","claro","clase","clave","cliente","clima","clínica","cobre","cocción","cochino","cocina","coco","código","codo","cofre","coger","cohete","cojín","cojo","cola","colcha","colegio","colgar","colina","collar","colmo","columna","combate","comer","comida","cómodo","compra","conde","conejo","conga","conocer","consejo","contar","copa","copia","corazón","corbata","corcho","cordón","corona","correr","coser","cosmos","costa","cráneo","cráter","crear","crecer","creído","crema","cría","crimen","cripta","crisis","cromo","crónica","croqueta","crudo","cruz","cuadro","cuarto","cuatro","cubo","cubrir","cuchara","cuello","cuento","cuerda","cuesta","cueva","cuidar","culebra","culpa","culto","cumbre","cumplir","cuna","cuneta","cuota","cupón","cúpula","curar","curioso","curso","curva","cutis","dama","danza","dar","dardo","dátil","deber","débil","década","decir","dedo","defensa","definir","dejar","delfín","delgado","delito","demora","denso","dental","deporte","derecho","derrota","desayuno","deseo","desfile","desnudo","destino","desvío","detalle","detener","deuda","día","diablo","diadema","diamante","diana","diario","dibujo","dictar","diente","dieta","diez","difícil","digno","dilema","diluir","dinero","directo","dirigir","disco","diseño","disfraz","diva","divino","doble","doce","dolor","domingo","don","donar","dorado","dormir","dorso","dos","dosis","dragón","droga","ducha","duda","duelo","dueño","dulce","dúo","duque","durar","dureza","duro","ébano","ebrio","echar","eco","ecuador","edad","edición","edificio","editor","educar","efecto","eficaz","eje","ejemplo","elefante","elegir","elemento","elevar","elipse","élite","elixir","elogio","eludir","embudo","emitir","emoción","empate","empeño","empleo","empresa","enano","encargo","enchufe","encía","enemigo","enero","enfado","enfermo","engaño","enigma","enlace","enorme","enredo","ensayo","enseñar","entero","entrar","envase","envío","época","equipo","erizo","escala","escena","escolar","escribir","escudo","esencia","esfera","esfuerzo","espada","espejo","espía","esposa","espuma","esquí","estar","este","estilo","estufa","etapa","eterno","ética","etnia","evadir","evaluar","evento","evitar","exacto","examen","exceso","excusa","exento","exigir","exilio","existir","éxito","experto","explicar","exponer","extremo","fábrica","fábula","fachada","fácil","factor","faena","faja","falda","fallo","falso","faltar","fama","familia","famoso","faraón","farmacia","farol","farsa","fase","fatiga","fauna","favor","fax","febrero","fecha","feliz","feo","feria","feroz","fértil","fervor","festín","fiable","fianza","fiar","fibra","ficción","ficha","fideo","fiebre","fiel","fiera","fiesta","figura","fijar","fijo","fila","filete","filial","filtro","fin","finca","fingir","finito","firma","flaco","flauta","flecha","flor","flota","fluir","flujo","flúor","fobia","foca","fogata","fogón","folio","folleto","fondo","forma","forro","fortuna","forzar","fosa","foto","fracaso","frágil","franja","frase","fraude","freír","freno","fresa","frío","frito","fruta","fuego","fuente","fuerza","fuga","fumar","función","funda","furgón","furia","fusil","fútbol","futuro","gacela","gafas","gaita","gajo","gala","galería","gallo","gamba","ganar","gancho","ganga","ganso","garaje","garza","gasolina","gastar","gato","gavilán","gemelo","gemir","gen","género","genio","gente","geranio","gerente","germen","gesto","gigante","gimnasio","girar","giro","glaciar","globo","gloria","gol","golfo","goloso","golpe","goma","gordo","gorila","gorra","gota","goteo","gozar","grada","gráfico","grano","grasa","gratis","grave","grieta","grillo","gripe","gris","grito","grosor","grúa","grueso","grumo","grupo","guante","guapo","guardia","guerra","guía","guiño","guion","guiso","guitarra","gusano","gustar","haber","hábil","hablar","hacer","hacha","hada","hallar","hamaca","harina","haz","hazaña","hebilla","hebra","hecho","helado","helio","hembra","herir","hermano","héroe","hervir","hielo","hierro","hígado","higiene","hijo","himno","historia","hocico","hogar","hoguera","hoja","hombre","hongo","honor","honra","hora","hormiga","horno","hostil","hoyo","hueco","huelga","huerta","hueso","huevo","huida","huir","humano","húmedo","humilde","humo","hundir","huracán","hurto","icono","ideal","idioma","ídolo","iglesia","iglú","igual","ilegal","ilusión","imagen","imán","imitar","impar","imperio","imponer","impulso","incapaz","índice","inerte","infiel","informe","ingenio","inicio","inmenso","inmune","innato","insecto","instante","interés","íntimo","intuir","inútil","invierno","ira","iris","ironía","isla","islote","jabalí","jabón","jamón","jarabe","jardín","jarra","jaula","jazmín","jefe","jeringa","jinete","jornada","joroba","joven","joya","juerga","jueves","juez","jugador","jugo","juguete","juicio","junco","jungla","junio","juntar","júpiter","jurar","justo","juvenil","juzgar","kilo","koala","labio","lacio","lacra","lado","ladrón","lagarto","lágrima","laguna","laico","lamer","lámina","lámpara","lana","lancha","langosta","lanza","lápiz","largo","larva","lástima","lata","látex","latir","laurel","lavar","lazo","leal","lección","leche","lector","leer","legión","legumbre","lejano","lengua","lento","leña","león","leopardo","lesión","letal","letra","leve","leyenda","libertad","libro","licor","líder","lidiar","lienzo","liga","ligero","lima","límite","limón","limpio","lince","lindo","línea","lingote","lino","linterna","líquido","liso","lista","litera","litio","litro","llaga","llama","llanto","llave","llegar","llenar","llevar","llorar","llover","lluvia","lobo","loción","loco","locura","lógica","logro","lombriz","lomo","lonja","lote","lucha","lucir","lugar","lujo","luna","lunes","lupa","lustro","luto","luz","maceta","macho","madera","madre","maduro","maestro","mafia","magia","mago","maíz","maldad","maleta","malla","malo","mamá","mambo","mamut","manco","mando","manejar","manga","maniquí","manjar","mano","manso","manta","mañana","mapa","máquina","mar","marco","marea","marfil","margen","marido","mármol","marrón","martes","marzo","masa","máscara","masivo","matar","materia","matiz","matriz","máximo","mayor","mazorca","mecha","medalla","medio","médula","mejilla","mejor","melena","melón","memoria","menor","mensaje","mente","menú","mercado","merengue","mérito","mes","mesón","meta","meter","método","metro","mezcla","miedo","miel","miembro","miga","mil","milagro","militar","millón","mimo","mina","minero","mínimo","minuto","miope","mirar","misa","miseria","misil","mismo","mitad","mito","mochila","moción","moda","modelo","moho","mojar","molde","moler","molino","momento","momia","monarca","moneda","monja","monto","moño","morada","morder","moreno","morir","morro","morsa","mortal","mosca","mostrar","motivo","mover","móvil","mozo","mucho","mudar","mueble","muela","muerte","muestra","mugre","mujer","mula","muleta","multa","mundo","muñeca","mural","muro","músculo","museo","musgo","música","muslo","nácar","nación","nadar","naipe","naranja","nariz","narrar","nasal","natal","nativo","natural","náusea","naval","nave","navidad","necio","néctar","negar","negocio","negro","neón","nervio","neto","neutro","nevar","nevera","nicho","nido","niebla","nieto","niñez","niño","nítido","nivel","nobleza","noche","nómina","noria","norma","norte","nota","noticia","novato","novela","novio","nube","nuca","núcleo","nudillo","nudo","nuera","nueve","nuez","nulo","número","nutria","oasis","obeso","obispo","objeto","obra","obrero","observar","obtener","obvio","oca","ocaso","océano","ochenta","ocho","ocio","ocre","octavo","octubre","oculto","ocupar","ocurrir","odiar","odio","odisea","oeste","ofensa","oferta","oficio","ofrecer","ogro","oído","oír","ojo","ola","oleada","olfato","olivo","olla","olmo","olor","olvido","ombligo","onda","onza","opaco","opción","ópera","opinar","oponer","optar","óptica","opuesto","oración","orador","oral","órbita","orca","orden","oreja","órgano","orgía","orgullo","oriente","origen","orilla","oro","orquesta","oruga","osadía","oscuro","osezno","oso","ostra","otoño","otro","oveja","óvulo","óxido","oxígeno","oyente","ozono","pacto","padre","paella","página","pago","país","pájaro","palabra","palco","paleta","pálido","palma","paloma","palpar","pan","panal","pánico","pantera","pañuelo","papá","papel","papilla","paquete","parar","parcela","pared","parir","paro","párpado","parque","párrafo","parte","pasar","paseo","pasión","paso","pasta","pata","patio","patria","pausa","pauta","pavo","payaso","peatón","pecado","pecera","pecho","pedal","pedir","pegar","peine","pelar","peldaño","pelea","peligro","pellejo","pelo","peluca","pena","pensar","peñón","peón","peor","pepino","pequeño","pera","percha","perder","pereza","perfil","perico","perla","permiso","perro","persona","pesa","pesca","pésimo","pestaña","pétalo","petróleo","pez","pezuña","picar","pichón","pie","piedra","pierna","pieza","pijama","pilar","piloto","pimienta","pino","pintor","pinza","piña","piojo","pipa","pirata","pisar","piscina","piso","pista","pitón","pizca","placa","plan","plata","playa","plaza","pleito","pleno","plomo","pluma","plural","pobre","poco","poder","podio","poema","poesía","poeta","polen","policía","pollo","polvo","pomada","pomelo","pomo","pompa","poner","porción","portal","posada","poseer","posible","poste","potencia","potro","pozo","prado","precoz","pregunta","premio","prensa","preso","previo","primo","príncipe","prisión","privar","proa","probar","proceso","producto","proeza","profesor","programa","prole","promesa","pronto","propio","próximo","prueba","público","puchero","pudor","pueblo","puerta","puesto","pulga","pulir","pulmón","pulpo","pulso","puma","punto","puñal","puño","pupa","pupila","puré","quedar","queja","quemar","querer","queso","quieto","química","quince","quitar","rábano","rabia","rabo","ración","radical","raíz","rama","rampa","rancho","rango","rapaz","rápido","rapto","rasgo","raspa","rato","rayo","raza","razón","reacción","realidad","rebaño","rebote","recaer","receta","rechazo","recoger","recreo","recto","recurso","red","redondo","reducir","reflejo","reforma","refrán","refugio","regalo","regir","regla","regreso","rehén","reino","reír","reja","relato","relevo","relieve","relleno","reloj","remar","remedio","remo","rencor","rendir","renta","reparto","repetir","reposo","reptil","res","rescate","resina","respeto","resto","resumen","retiro","retorno","retrato","reunir","revés","revista","rey","rezar","rico","riego","rienda","riesgo","rifa","rígido","rigor","rincón","riñón","río","riqueza","risa","ritmo","rito","rizo","roble","roce","rociar","rodar","rodeo","rodilla","roer","rojizo","rojo","romero","romper","ron","ronco","ronda","ropa","ropero","rosa","rosca","rostro","rotar","rubí","rubor","rudo","rueda","rugir","ruido","ruina","ruleta","rulo","rumbo","rumor","ruptura","ruta","rutina","sábado","saber","sabio","sable","sacar","sagaz","sagrado","sala","saldo","salero","salir","salmón","salón","salsa","salto","salud","salvar","samba","sanción","sandía","sanear","sangre","sanidad","sano","santo","sapo","saque","sardina","sartén","sastre","satán","sauna","saxofón","sección","seco","secreto","secta","sed","seguir","seis","sello","selva","semana","semilla","senda","sensor","señal","señor","separar","sepia","sequía","ser","serie","sermón","servir","sesenta","sesión","seta","setenta","severo","sexo","sexto","sidra","siesta","siete","siglo","signo","sílaba","silbar","silencio","silla","símbolo","simio","sirena","sistema","sitio","situar","sobre","socio","sodio","sol","solapa","soldado","soledad","sólido","soltar","solución","sombra","sondeo","sonido","sonoro","sonrisa","sopa","soplar","soporte","sordo","sorpresa","sorteo","sostén","sótano","suave","subir","suceso","sudor","suegra","suelo","sueño","suerte","sufrir","sujeto","sultán","sumar","superar","suplir","suponer","supremo","sur","surco","sureño","surgir","susto","sutil","tabaco","tabique","tabla","tabú","taco","tacto","tajo","talar","talco","talento","talla","talón","tamaño","tambor","tango","tanque","tapa","tapete","tapia","tapón","taquilla","tarde","tarea","tarifa","tarjeta","tarot","tarro","tarta","tatuaje","tauro","taza","tazón","teatro","techo","tecla","técnica","tejado","tejer","tejido","tela","teléfono","tema","temor","templo","tenaz","tender","tener","tenis","tenso","teoría","terapia","terco","término","ternura","terror","tesis","tesoro","testigo","tetera","texto","tez","tibio","tiburón","tiempo","tienda","tierra","tieso","tigre","tijera","tilde","timbre","tímido","timo","tinta","tío","típico","tipo","tira","tirón","titán","títere","título","tiza","toalla","tobillo","tocar","tocino","todo","toga","toldo","tomar","tono","tonto","topar","tope","toque","tórax","torero","tormenta","torneo","toro","torpedo","torre","torso","tortuga","tos","tosco","toser","tóxico","trabajo","tractor","traer","tráfico","trago","traje","tramo","trance","trato","trauma","trazar","trébol","tregua","treinta","tren","trepar","tres","tribu","trigo","tripa","triste","triunfo","trofeo","trompa","tronco","tropa","trote","trozo","truco","trueno","trufa","tubería","tubo","tuerto","tumba","tumor","túnel","túnica","turbina","turismo","turno","tutor","ubicar","úlcera","umbral","unidad","unir","universo","uno","untar","uña","urbano","urbe","urgente","urna","usar","usuario","útil","utopía","uva","vaca","vacío","vacuna","vagar","vago","vaina","vajilla","vale","válido","valle","valor","válvula","vampiro","vara","variar","varón","vaso","vecino","vector","vehículo","veinte","vejez","vela","velero","veloz","vena","vencer","venda","veneno","vengar","venir","venta","venus","ver","verano","verbo","verde","vereda","verja","verso","verter","vía","viaje","vibrar","vicio","víctima","vida","vídeo","vidrio","viejo","viernes","vigor","vil","villa","vinagre","vino","viñedo","violín","viral","virgo","virtud","visor","víspera","vista","vitamina","viudo","vivaz","vivero","vivir","vivo","volcán","volumen","volver","voraz","votar","voto","voz","vuelo","vulgar","yacer","yate","yegua","yema","yerno","yeso","yodo","yoga","yogur","zafiro","zanja","zapato","zarza","zona","zorro","zumo","zurdo"]["abajur","abaküs","abartı","abdal","abdest","abiye","abluka","abone","absorbe","absürt","acayip","acele","acemi","açıkgöz","adalet","adam","adezyon","adisyon","adliye","adres","afacan","afili","afiş","afiyet","aforizm","afra","ağaç","ağır","ahbap","ahkam","ahlak","ahtapot","aidat","aile","ajan","akademi","akarsu","akbaş","akciğer","akdeniz","akıbet","akıl","akıntı","akide","akrep","akrobasi","aksiyon","akşam","aktif","aktör","aktris","akustik","alaca","albüm","alçak","aldanma","aleni","alet","alfabe","algılama","alıngan","alkış","alkol","alpay","alperen","altın","altüst","altyapı","alyuvar","amade","amatör","amazon","ambalaj","amblem","ambulans","amca","amel","amigo","amir","amiyane","amorti","ampul","anadolu","anahtar","anakonda","anaokul","anapara","anarşi","anatomi","anayasa","anekdot","anestezi","angaje","anka","anket","anlamlı","anne","anomali","anonim","anten","antlaşma","apse","araba","aracı","araf","arbede","arda","arefe","arena","argo","argüman","arkadaş","armoni","aroma","arsa","arsız","artı","artist","aruz","asansör","asayiş","asfalt","asgari","asil","asker","askı","aslan","asosyal","astsubay","asya","aşçı","aşırı","aşure","atabey","ataman","ateş","atmaca","atmosfer","atom","atölye","avcı","avdet","avize","avlu","avokado","avrupa","avukat","ayaz","ayçiçeği","aydın","aygıt","ayna","ayran","ayrıntı","azim","baca","bagaj","bağlantı","bahadır","bahçe","baki","bakkal","baklava","bakteri","balçık","balina","balo","balta","bant","banyo","bardak","barış","başbuğ","başıboş","başkan","başlık","bavul","bayındır","baykuş","bazlama","bedel","begüm","bekçi","bekle","belge","belki","bencil","benek","bengi","benzer","berjer","berk","bermuda","berrak","beşik","beton","beyin","beyoğlu","bıçak","biberiye","bidon","biftek","bihaber","bikini","bilezik","bilinç","bilye","bina","binbaşı","binyıl","bisiklet","bisküvi","bitki","bizzat","bodrum","boğaz","bohça","bolero","boncuk","bonfile","borsa","boru","bostan","boşboğaz","botanik","boya","boykot","boynuz","bozgun","bozkır","bölüm","börek","buçuk","bugün","buğday","buhar","buhran","bulvar","buram","burçak","burs","burun","butik","buzdağı","buzkıran","bücür","büfe","bülten","bütçe","bütün","büyük","cacık","cadı","cahil","cambaz","canhıraş","casus","cazibe","cehalet","cehennem","ceket","cemre","cenin","cennet","cepken","cerrah","cesur","cetvel","cevher","ceylan","cılız","cıva","cilt","cisim","ciyak","coğrafya","cömert","cumba","cüzdan","çabucak","çadır","çağdaş","çağlayan","çağrı","çakmak","çalışkan","çamaşır","çapa","çaput","çarık","çarpan","çarşaf","çayhane","çekirdek","çelebi","çember","çenet","çengel","çerçeve","çerez","çeşit","çeşme","çete","çevre","çeyiz","çeyrek","çığır","çılgın","çıngırak","çift","çiğdem","çikolata","çilek","çimen","çivi","çoban","çocuk","çokgen","çomak","çorba","çözelti","çubuk","çukur","çuval","çürük","dağbaşı","dağılım","daktilo","daldırış","dalga","dalkavuk","damak","damıtma","damla","dana","dandik","danışman","daniska","dantel","dargeçit","darphane","davet","dayı","defter","değer","değirmen","dehşet","delgeç","demir","deneyim","denge","depo","deprem","derdest","dere","derhal","derman","dernek","derviş","desen","destan","dışarı","dışbükey","dijital","dikbaşlı","dilekçe","dimağ","dinamik","dindar","dinleme","dinozor","dipçik","dipnot","direniş","dirsek","disiplin","disk","divriği","dizüstü","dobra","dodurga","doğalgaz","doktor","doküman","dolap","donanım","dondurma","donör","doruk","dosdoğru","dost","dosya","dozer","döküm","dönence","dörtyol","dövme","dram","dublaj","durum","duvak","duyarga","duyma","duyuru","düğme","düğüm","dükkan","dünür","düpedüz","dürbün","düşünür","düzayak","düzeltme","ebeveyn","ebru","ecel","ecnebi","ecza","edat","edilgen","efendi","efor","efsane","egemen","egzersiz","eğrelti","ekarte","ekip","eklem","ekmek","ekol","ekonomi","ekose","ekran","ekvator","elaman","elastik","elbet","elbise","elçi","eldiven","elebaşı","eleştiri","elma","eloğlu","elveda","emare","emekçi","emisyon","emniyet","empati","emsal","emzik","endüstri","enerji","engebe","engin","enişte","enkaz","entari","entegre","entrika","enzim","erdem","ergen","erguvan","erkek","erozyon","ertesi","erzak","esaret","esenlik","eser","eski","esnek","eşarp","eşofman","eşraf","eşya","eşzaman","etik","etken","etkinlik","etüt","evet","evire","evrak","evrim","eyalet","eyvah","ezber","fabrika","fanatik","fanus","fason","fasulye","fatih","fatura","fauna","favori","fayans","fayton","fazıl","fazilet","federal","felsefe","fener","feribot","fersah","fesih","festival","feveran","feza","fıçı","fıldır","fındık","fırça","fırsat","fırtına","fıtık","fidan","fidye","figür","fihrist","fikir","fildişi","filo","filtre","fincan","firuze","fitil","fiyaka","fizik","flaş","flüt","fosil","fren","fukara","futbol","garabet","gariban","garnitür","gazi","gece","gedik","gelenek","gelin","gemi","genç","geniş","geometri","gerçek","gevrek","gezegen","gezgin","geziyolu","gıcık","gıda","gıybet","girdap","girişim","gitar","giyecek","giysi","gizem","gofret","goril","göbek","göçebe","göğüs","gökdelen","gökmen","gökyüzü","gölge","gömlek","gönül","görenek","görkemli","görsel","gösteri","gövde","gözaltı","gözcü","gözdağı","gözleme","gözyaşı","grup","gurbet","gusül","gübre","güfte","gümüş","günaydın","güncel","gündüz","güneş","günyüzü","gürbüz","güvercin","güzel","haber","hacamat","hacim","hademe","hafız","hafriyat","hafta","hakan","hakem","hakikat","haksever","halı","hançer","hane","hangar","hapis","hapşırık","harf","haseki","hasret","hatun","havuç","haylaz","haysiyet","hayvan","hedef","hektar","hemen","hemfikir","hendek","hepsi","hergele","herhangi","hesap","heyecan","heykel","hezimet","hıçkırık","hızölçer","hicviye","hikaye","hikmet","hile","hisse","hobi","hoca","horlama","hormon","hoşbeş","hoşgörü","hoyrat","hörgüç","höyük","hudut","hukuk","hunhar","hurda","huysuz","huzur","hücum","hükümet","hünkar","hüviyet","ırmak","ısıölçer","ısıtıcı","ıspanak","ısrar","ışıldak","ızdırap","ızgara","ibadet","icat","içbükey","içecek","içgüdü","içsel","idman","iftihar","iğne","ihanet","ihbar","ihdas","ihmal","ihracat","ihsan","ikilem","ikindi","ikircik","iklim","iksir","iktibas","ilaç","ilçe","ileri","iletişim","ilgi","ilhak","ilkbahar","ilkokul","ilmek","imkan","imleç","imsak","imtihan","imza","ince","inkar","inşa","ipek","ipucu","irade","irfan","irmik","isabet","iskele","israf","isyan","işçi","işgal","işgüzar","işlem","itibar","itiraf","ivedi","ivme","iyileşme","iyimser","izbandut","izci","izdiham","izin","jakoben","jandarma","jargon","kabadayı","kablo","kabus","kaçamak","kadeh","kadın","kadraj","kafa","kafkas","kağıt","kağnı","kahkaha","kahraman","kahvaltı","kakül","kaldırım","kale","kalibre","kalkan","kalpak","kamış","kamyon","kanat","kandaş","kanepe","kanser","kanun","kaos","kapı","kaplıca","kaptan","karanlık","kardeş","karga","karınca","karmaşa","karşıt","kasırga","kask","kasvet","katkı","katman","kavram","kaygan","kaynakça","kayyum","kedi","kehanet","kekik","kelebek","kenar","kerkenez","kerpiç","kesirli","kesmece","kestane","keşkek","ketçap","keyfiyet","kıble","kıdemli","kılavuz","kılçık","kılıf","kıraç","kırmızı","kırsal","kısayol","kısım","kıskanç","kısmet","kışla","kıvanç","kıvılcım","kıvrık","kıyafet","kıymetli","kızak","kızılcık","kibar","kinaye","kira","kiremit","kirli","kirpik","kişisel","kitap","koçbaşı","kodaman","koğuş","kokteyl","kolaycı","kolbastı","kolonya","koltuk","kolye","kombine","komedyen","komiser","komposto","komşu","komuta","konak","konfor","koni","konsül","kopya","korkusuz","korna","korse","korunak","korvet","kostüm","koşul","koyu","kozmik","köfte","kökensel","köprücük","köpük","kördüğüm","körfez","köstebek","köşegen","kötü","kravat","kriter","kuantum","kudurma","kuluçka","kulübe","kumanya","kumbara","kumlu","kumpir","kumral","kundura","kupa","kupkuru","kuramsal","kurbağa","kurdele","kurgu","kurmay","kurşun","kurtuluş","kurultay","kurye","kusursuz","kuşak","kuşbaşı","kuşkulu","kutlama","kutsal","kutup","kuver","kuyruk","kuzey","kuzgun","küçük","külçe","külfet","külliye","kültürel","kümes","künefe","küresel","kütle","lahana","lahmacun","lamba","lansman","lavaş","layık","leğen","levent","leziz","lezzet","lider","likide","liman","liste","litre","liyakat","lodos","lokanta","lokman","lokum","lunapark","lütfen","lüzum","nokta","mabet","macera","macun","madalya","madde","madem","mağara","mağdur","mağfiret","mağlup","mahalle","mahcup","mahir","mahkeme","mahlas","mahrum","mahsul","makas","makbuz","makine","makro","maksat","makul","maliye","manav","mangal","manidar","manken","mantık","manzara","mareşal","margarin","marifet","market","marmelat","masaüstü","masmavi","masraf","masum","matah","materyal","matrak","maval","mavra","maydanoz","mayhoş","maytap","mazbata","mazeret","mazlum","mazot","mazur","meblağ","mebus","mecaz","mecbur","meclis","mecmua","mecnun","meçhul","medeni","mehtap","mekanik","melodi","meltem","memur","mendil","menekşe","menteşe","meraklı","mercek","merdiven","merhaba","merinos","merkez","mermi","mert","mesafe","mesele","mesken","meslek","meşale","meşgul","meşhur","metafor","metin","metre","mevcut","mevkidaş","meydan","meyil","meyve","meziyet","mezun","mıknatıs","mısra","mızıka","miğfer","mihrak","mikrofon","miktar","milat","milli","mimar","minare","mineral","minik","minyon","mirliva","misafir","miskin","miting","miyop","mizah","mobilya","model","monitör","morötesi","motive","motor","mozaik","muavin","mucize","muhafız","muhteşem","mukayese","mumya","musluk","muşamba","mutabık","mutfak","mutlu","muzaffer","muzdarip","mübarek","mücadele","müdür","müfredat","müftü","mühendis","mühim","mühlet","mükemmel","mülk","mümkün","mümtaz","müsrif","müstesna","müşahit","müşteri","mütercim","müthiş","müze","müzik","nabız","nadas","nadir","nahoş","nakarat","nakış","nalbur","namlu","namus","nankör","nargile","narkoz","nasıl","nasip","naylon","nazar","nazım","nazik","neden","nefes","negatif","neon","neptün","nerede","nesil","nesnel","neşeli","netice","nevresim","neyse","neyzen","nezaket","nezih","nezle","nicel","nilüfer","nimet","nisan","nispet","nitekim","nizam","nohut","noksan","normal","nostalji","noter","nöbet","numara","numune","nutuk","nüfus","obabaşı","obez","obje","ocak","odun","ofansif","ofis","oğlak","oğuz","okçu","oklava","oksijen","okul","okumuş","okutman","okuyucu","okyanus","olağan","olanak","olası","olay","olgun","olimpik","olumlu","omlet","omurga","onarım","onursal","opera","optik","oral","orantı","ordu","organik","orijin","orkide","orman","orta","oruç","otağ","otantik","otel","otoban","otogar","otomobil","otonom","otopark","otorite","otoyol","oturum","oyuk","oyuncak","ozan","ödeme","ödenek","ödev","ödül","ödünç","öfke","öğlen","öğrenci","öğün","öğütücü","öksürük","ölçme","ölçü","ölümsüz","ömür","önayak","öncü","önder","önem","önerge","öngörü","önlük","önsezi","öpücük","ördek","örgü","örtbas","örtme","örtü","örümcek","örüntü","öteberi","öteki","övünç","öykü","öyleyse","özçekim","özdeyiş","özel","özenti","özerk","özgürlük","özlem","özlü","özne","özsever","özümseme","özür","özveri","pabuç","padişah","palamut","palmiye","palto","palyaço","pamuk","panayır","pancar","panda","panel","panik","panjur","pankart","pano","pansuman","pantolon","panzehir","papatya","papyon","paraşüt","parça","pardösü","parfüm","parıltı","parkur","parmak","parodi","parsel","partner","pasaport","pasif","paskalya","pastırma","paşa","patates","paten","patika","patlıcan","patolog","patron","payanda","paydaş","payidar","paylaşma","paytak","peçete","pedal","peder","pehlivan","pekala","pekmez","pelerin","pelikan","pelüş","pembe","pena","pencere","pense","perçin","perde","pergel","perişan","peron","personel","perşembe","peruk","pervane","pespaye","pestil","peşin","petek","petrol","petunya","peynir","peyzaj","pınar","pırasa","pırlanta","pide","pikap","piknik","pilav","piliç","pilot","pipet","pipo","piramit","pirinç","pirzola","pist","pişik","pişman","piyasa","piyes","plaj","plaket","planlama","platform","plazma","podyum","poğaça","polat","polen","politika","pompa","popüler","porselen","portakal","posa","poster","poşet","poyraz","pozitif","pranga","pratik","prenses","prim","problem","profil","program","proje","protokol","prova","puan","pudra","pusula","püre","pürüz","püstül","püsür","racon","radar","radikal","radyo","rafadan","rafine","rağbet","rahat","rahle","rakam","raket","rakip","rakun","ralli","rampa","randevu","ranza","rapor","rastgele","rasyonel","razı","realite","reçine","refah","referans","refik","reform","rehber","rehin","reis","rekabet","reklam","rekor","rektör","renk","resim","resmen","restoran","retorik","revaç","revize","reyon","rezalet","rezerv","rezil","rıhtım","rıza","ritim","ritüel","rivayet","robot","roman","rota","rozet","röportaj","rötar","ruble","ruhban","ruhsat","rulet","rulo","runik","rutin","rutubet","rüşvet","rütbe","rüya","rüzgar","sabah","sabıka","sabit","sabun","saçma","sade","sadık","safahat","safdil","safkan","sağanak","sağduyu","sağlam","saha","sahiden","sahne","sakal","sakız","sakin","saklama","saksağan","salamura","salça","salgı","salınım","salkım","salon","saltanat","sanatçı","sancak","sandalye","saniye","saplantı","sapsız","saray","sarışın","sarkık","sarmaşık","satır","savaşım","savunma","saydam","sayfa","saygın","sayısal","sebep","seçenek","seçim","seçkin","seçmen","seda","sedir","sedye","sefer","sehpa","sekizgen","selektör","selvi","semavi","sembol","seminer","senaryo","sendika","senkron","sensör","sentez","sepet","seramik","serbest","serdar","seremoni","sergi","serhat","serin","sermaye","serpuş","sersem","serüven","servis","sesli","sesteş","sevap","seviye","seyahat","seyirci","sezon","sıcak","sıfat","sıhhi","sınanma","sınır","sıradan","sırdaş","sırma","sırtüstü","sızgıt","siftah","sigorta","sihirbaz","silah","silecek","silindir","simetri","simge","simit","sincap","sindirim","sinema","sinirli","sipariş","sirke","siroz","sistem","sivilce","siyasi","slogan","soba","sofra","soğuk","sohbet","sokak","solfej","solunum","somut","sonbahar","sonraki","sonsuz","sorunsuz","sosyete","soyağacı","soydaş","soygun","soytarı","söğüş","sömürge","sönük","söylem","sözcük","sözde","spatula","spektrum","spiker","spiral","sponsor","sporcu","sprey","stabil","statü","stok","stopaj","strateji","subay","sucuk","suçüstü","suhulet","sulama","sungur","sunucu","surat","susam","suskun","sükse","sükut","sülale","sünger","süpürge","sürahi","süreç","sürgün","sürüm","süsleme","sütanne","sütlaç","sütun","süvari","şahane","şahbaz","şahit","şahsiyet","şakıma","şaklaban","şakrak","şamar","şampiyon","şanslı","şantiye","şapka","şarkıcı","şartname","şaşırma","şaşkın","şatafat","şayet","şebeke","şefkat","şeftali","şehir","şehvet","şeker","şekil","şelale","şema","şemsiye","şerbet","şeref","şerit","şımarık","şıpıdık","şifre","şimdi","şimşek","şipşak","şirin","şişe","şişirme","şofben","şöhret","şölen","şüphe","tabaka","tabela","tabure","tadilat","taharet","tahıl","tahkim","tahlil","tahmin","tahrifat","tahsilat","tahta","taklit","takoz","taksici","taktik","takvim","talebe","talip","tamamen","tamirci","tampon","tamtakır","tandır","tanecik","tanıtım","tanrı","tansiyon","tapan","tapınak","taptaze","tapu","tarafgir","tarhana","tarım","tarih","tarla","tartak","tarumar","tasarım","tasdik","taslak","tastamam","taşeron","taşınmaz","taşra","tatava","tatbikat","tatil","tatlı","tavsiye","tavşan","tavuk","taze","taziye","tazminat","tebeşir","tebrik","tecrübe","teçhizat","tedarik","tedbir","teftiş","teğet","teğmen","tehdit","tehlike","tekdüze","tekerlek","tekme","teknik","tekrar","telef","telsiz","telve","temas","tembel","temiz","temkin","tempo","temsilci","tendon","teneke","tenha","tenkit","tepegöz","tepki","terazi","terbiye","tercih","tereyağı","terfi","terim","terminal","tersane","tertip","tesadüf","tescil","tesir","teslimat","tespit","testere","teşekkür","teşhir","teşrif","teşvik","teyze","tezahür","tezgah","tıbbi","tıkaç","tıkışık","tıknaz","tılsım","tıpkı","tıraş","tırışka","tırmanış","tırnak","tırpan","tıslama","ticaret","tilki","tiryaki","titreşim","tohum","tokat","tolere","tomar","tombak","tomurcuk","topaç","toplum","toprak","toptan","toraman","torpido","tortu","tosbağa","toynak","tören","trafik","trajedi","tramvay","transfer","tribün","triko","tugay","tuğla","tuğrul","tuhaf","tulumba","tunç","turan","turkuaz","turnusol","turşu","turuncu","tutanak","tutkal","tutsak","tutum","tuyuğ","tuzlu","tüccar","tüfek","tükenmez","tülbent","tümleç","tünel","türbin","türev","türk","tüzük","ucube","ucuz","uçak","uçurtma","ufuk","uğrak","uğur","ukala","ulaşım","ulema","ulus","ulvi","umursama","umut","unutkan","uslu","ustabaşı","ustura","usul","utangaç","uyanık","uyarı","uydu","uygar","uygulama","uykusuz","uysal","uyuşma","uzantı","uzay","uzgören","uzlaşma","uzman","uzun","ücra","ücret","üçbudak","üçgen","üçkağıt","üçleme","üfürük","ülke","ümit","üniforma","ünite","ünlem","üretken","ürün","üslup","üstel","üstün","üşengeç","üşüme","ütopya","üvey","üzengi","üzgün","üzüm","vagon","vaka","vakfiye","vakıf","vakit","vakum","vapur","varil","varlık","varsayım","varyemez","vasıta","vasiyet","vatandaş","vazife","vazo","veciz","vefa","vehim","veliaht","veresiye","verimli","verkaç","vernik","vertigo","vesait","vesika","vestiyer","veznedar","vicdan","vilayet","virane","virgül","vişne","vites","vokal","volkan","vurma","vurucu","vücut","yabancı","yabgu","yağış","yağlı","yağmur","yakamoz","yakın","yaklaşık","yalçın","yalıtım","yaman","yanardağ","yangın","yanıt","yankı","yanlış","yansıma","yapay","yapboz","yapımcı","yaprak","yaratık","yarbay","yardım","yargıç","yarıçap","yasemin","yastık","yaşam","yatak","yatırım","yavru","yaygara","yayıncı","yayla","yazılım","yekpare","yekvücut","yelkovan","yelpaze","yemek","yemiş","yengeç","yeniçeri","yeraltı","yerküre","yerleşke","yeryüzü","yeşil","yetenek","yetkili","yığınak","yıkama","yılbaşı","yıldırım","yılkı","yılmaz","yırtıcı","yiğit","yoğurt","yokuş","yolcu","yoldaş","yolgeçen","yolkesen","yolüstü","yordam","yorgan","yorumcu","yosun","yöndeş","yönetim","yönlü","yöntem","yöresel","yörünge","yufka","yukarı","yumruk","yumurta","yuvarlak","yücelme","yükçeker","yüklem","yüksek","yürek","yürütme","yüzde","yüzeysel","yüzgeç","yüzüstü","yüzyıl","zabıta","zafer","zahmet","zambak","zaptiye","zarafet","zaruret","zeka","zekice","zemberek","zemin","zencefil","zeplin","zeytin","zıbın","zılgıt","zımbırtı","zımpara","zıpkın","zigon","zihinsel","zihniyet","zincir","zindan","zirzop","ziyaret","ziynet","zoraki","zorlu","zorunlu","züğürt","zümre"]const b4a = require('b4a')

function byteLength (size) {
  return Math.ceil(size / 8)
}

function get (buffer, bit) {
  const n = buffer.BYTES_PER_ELEMENT * 8

  const offset = bit & (n - 1)
  const i = (bit - offset) / n

  return (buffer[i] & (1 << offset)) !== 0
}

function set (buffer, bit, value = true) {
  const n = buffer.BYTES_PER_ELEMENT * 8

  const offset = bit & (n - 1)
  const i = (bit - offset) / n
  const mask = 1 << offset

  if (value) {
    if ((buffer[i] & mask) !== 0) return false
  } else {
    if ((buffer[i] & mask) === 0) return false
  }

  buffer[i] ^= mask
  return true
}

function setRange (buffer, start, end, value = true) {
  const n = buffer.BYTES_PER_ELEMENT * 8

  let remaining = end - start
  let offset = start & (n - 1)
  let i = (start - offset) / n

  let changed = false

  while (remaining > 0) {
    const mask = (2 ** Math.min(remaining, n - offset) - 1) << offset

    if (value) {
      if ((buffer[i] & mask) !== mask) {
        buffer[i] |= mask
        changed = true
      }
    } else {
      if ((buffer[i] & mask) !== 0) {
        buffer[i] &= ~mask
        changed = true
      }
    }

    remaining -= n - offset
    offset = 0
    i++
  }

  return changed
}

function fill (buffer, value, start = 0, end = buffer.byteLength * 8) {
  const n = buffer.BYTES_PER_ELEMENT * 8
  let i, j

  {
    const offset = start & (n - 1)
    i = (start - offset) / n

    if (offset !== 0) {
      const mask = (2 ** Math.min(n - offset, end - start) - 1) << offset

      if (value) buffer[i] |= mask
      else buffer[i] &= ~mask

      i++
    }
  }

  {
    const offset = end & (n - 1)
    j = (end - offset) / n

    if (offset !== 0 && j >= i) {
      const mask = (2 ** offset) - 1

      if (value) buffer[j] |= mask
      else buffer[j] &= ~mask
    }
  }

  return buffer.fill(value ? (2 ** n) - 1 : 0, i, j)
}

function toggle (buffer, bit) {
  const n = buffer.BYTES_PER_ELEMENT * 8

  const offset = bit & (n - 1)
  const i = (bit - offset) / n
  const mask = 1 << offset

  buffer[i] ^= mask
  return (buffer[i] & mask) !== 0
}

function remove (buffer, bit) {
  return set(buffer, bit, false)
}

function removeRange (buffer, start, end) {
  return setRange(buffer, start, end, false)
}

function indexOf (buffer, value, position = 0) {
  for (let i = position, n = buffer.byteLength * 8; i < n; i++) {
    if (get(buffer, i) === value) return i
  }

  return -1
}

function lastIndexOf (buffer, value, position = buffer.byteLength * 8 - 1) {
  for (let i = position; i >= 0; i--) {
    if (get(buffer, i) === value) return i
  }

  return -1
}

function of (...bits) {
  return from(bits)
}

function from (bits) {
  const buffer = b4a.alloc(byteLength(bits.length))
  for (let i = 0; i < bits.length; i++) set(buffer, i, bits[i])
  return buffer
}

function * iterator (buffer) {
  for (let i = 0, n = buffer.byteLength * 8; i < n; i++) yield get(buffer, i)
}

module.exports = {
  byteLength,
  get,
  set,
  setRange,
  fill,
  toggle,
  remove,
  removeRange,
  indexOf,
  lastIndexOf,
  of,
  from,
  iterator
}
{
  "name": "bits-to-bytes",
  "version": "1.3.0",
  "description": "Functions for doing bit manipulation of typed arrays",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "scripts": {
    "test": "standard && brittle test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bits-to-bytes.git"
  },
  "author": "Kasper Isager Dalsgarð <kasper@funktionel.co>",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/holepunchto/bits-to-bytes/issues"
  },
  "homepage": "https://github.com/holepunchto/bits-to-bytes#readme",
  "dependencies": {
    "b4a": "^1.5.0"
  },
  "devDependencies": {
    "brittle": "^2.3.1",
    "standard": "^17.0.0"
  }
}
const crypto = require('hypercore-crypto')
const b4a = require('b4a')
const safetyCatch = require('safety-catch')
const ReadyResource = require('ready-resource')
const Xache = require('xache')
const { MemberRequest, CandidateRequest, createInvite, decodeInvite, verifyReceipt, Invite } = require('blind-pairing-core')
const Protomux = require('protomux')
const c = require('compact-encoding')
const debounce = require('debounceify')
const isOptions = require('is-options')

const [NS_EPHEMERAL, NS_REPLY, NS_DISCOVERY] = crypto.namespace('blind-pairing/dht', 3)

const DEFAULT_POLL = 7 * 60 * 1000
const PEER_INTERVAL = 1000

class TimeoutPromise {
  constructor (ms) {
    this.ms = ms
    this.resolve = null
    this.timeout = null
    this.destroyed = false
    this.suspended = false

    this._resolveBound = this._resolve.bind(this)
    this._ontimerBound = this._ontimer.bind(this)
  }

  wait () {
    if (this.destroyed) return Promise.resolve()
    if (this.resolve) this._resolve()
    return new Promise(this._ontimerBound)
  }

  suspend () {
    this.suspended = true
    if (this.timeout !== null) clearTimeout(this.timeout)
    this.timeout = null
  }

  resume () {
    this.suspended = false
    if (this.resolve) this._resolve()
  }

  destroy () {
    this.destroyed = true
    if (this.resolve) this._resolve()
  }

  _ontimer (resolve) {
    this.resolve = resolve
    if (!this.suspended) this.timeout = setTimeout(this._resolveBound, this.ms)
  }

  _resolve () {
    if (this.timeout !== null) clearTimeout(this.timeout)

    const resolve = this.resolve
    this.timeout = null
    this.resolve = null

    resolve()
  }
}

class BlindPairing extends ReadyResource {
  constructor (swarm, { poll = DEFAULT_POLL, onincoming = noop } = {}) {
    super()

    this.swarm = swarm
    this.poll = poll
    this.active = new Map()
    this.suspended = false

    this._onincoming = onincoming
    this._onconnectionBound = this._onconnection.bind(this)
    this._refreshBound = this.refresh.bind(this)
    this._refreshing = null

    this.swarm.on('connection', this._onconnectionBound)
    this.swarm.dht.on('network-change', this._refreshBound)
  }

  static Invite = Invite

  static createInvite (key, opts) {
    return createInvite(key, opts)
  }

  static decodeInvite (invite) {
    return decodeInvite(invite)
  }

  static verifyReceipt (receipt, publicKey) {
    return verifyReceipt(receipt, publicKey)
  }

  static createRequest (invite, userData) {
    return new CandidateRequest(invite, userData)
  }

  async suspend () {
    if (this.suspended) return
    this.suspended = true

    const all = []

    for (const ref of this.active.values()) {
      if (ref.candidate) all.push(ref.candidate._suspend())
      if (ref.member) all.push(ref.member._suspend())
    }

    await Promise.allSettled(all)
  }

  resume () {
    if (!this.suspended) return
    this.suspended = false
    this.refresh().catch(safetyCatch) // no need to wait for the refreshes
  }

  async refresh () {
    if (this._refreshing) {
      await this._refreshing
      return
    }

    if (this.closing || this.suspended) return

    const r = this._refreshing = this._refresh()

    try {
      await r
    } finally {
      if (r === this._refreshing) this._refreshing = null
    }
  }

  async _refresh () {
    if (this.closing || this.suspended) return

    const all = []

    for (const ref of this.active.values()) {
      if (ref.candidate) all.push(ref.candidate.refresh())
      if (ref.member) all.push(ref.member.refresh())
    }

    await Promise.allSettled(all)
  }

  addMember (opts) {
    return new Member(this, opts)
  }

  addCandidate (request, opts) {
    if (isOptions(request)) return this.addCandidate(null, request)
    if (!request) request = new CandidateRequest(opts.invite, opts.userData)
    return new Candidate(this, request, opts)
  }

  async _close () {
    this.swarm.removeListener('connection', this._onconnectionBound)
    this.swarm.dht.removeListener('network-change', this._refreshBound)

    const all = []

    for (const conn of this.swarm.connections) {
      const mux = getMuxer(conn)
      mux.unpair({ protocol: 'blind-pairing' })
      for (const ref of this.active.values()) mux.unpair({ protocol: 'blind-pairing', id: ref.discoveryKey })
    }

    for (const ref of this.active.values()) {
      if (ref.member) all.push(ref.member.close())
      if (ref.candidate) all.push(ref.candidate.close())
      if (ref.discovery) all.push(ref.discovery.destroy())
    }

    await Promise.allSettled(all)
  }

  _randomPoll () {
    return randomInterval(this.poll)
  }

  _add (discoveryKey) {
    const id = b4a.toString(discoveryKey, 'hex')
    const t = this.active.get(id)
    if (t) return t

    const fresh = {
      id,
      discoveryKey,
      member: null,
      candidate: null,
      channels: new Set(),
      alwaysServer: false,
      alwaysClient: false,
      discovery: null
    }

    this.active.set(id, fresh)
    return fresh
  }

  _swarm (ref) {
    const server = ref.alwaysServer || !!ref.member
    const client = ref.alwaysClient || !!ref.candidate

    if (ref.discovery && ref.discovery.isServer === server && ref.discovery.isClient === client) {
      return
    }

    if (ref.discovery) ref.discovery.destroy().catch(safetyCatch)

    // just a sanity check, not needed but doesnt hurt
    if (!server && !client) return

    ref.discovery = this.swarm.join(ref.discoveryKey, { server, client })
    this._attachToSwarm(ref)
  }

  _attachToSwarm (ref) {
    for (const conn of this.swarm.connections) {
      const mux = getMuxer(conn)
      this._attachToMuxer(mux, ref.discoveryKey, ref)
    }
  }

  _gc (ref) {
    if (ref.member || ref.candidate) {
      if (ref.discovery) this._swarm(ref) // in case it needs updating...
      return false
    }
    this.active.delete(ref.id)
    for (const ch of ref.channels) ch.close()
    for (const conn of this.swarm.connections) {
      const mux = getMuxer(conn)
      mux.unpair({ protocol: 'blind-pairing', id: ref.discoveryKey })
    }
    if (ref.discovery) ref.discovery.destroy().catch(safetyCatch)
    return true
  }

  _onconnection (conn) {
    const mux = getMuxer(conn)

    mux.pair({ protocol: 'blind-pairing' }, this._onincoming)

    for (const ref of this.active.values()) {
      this._attachToMuxer(mux, ref.discoveryKey, ref)
    }
  }

  _attachToMuxer (mux, discoveryKey, ref) {
    if (!ref) ref = this._add(discoveryKey)

    const ch = mux.createChannel({
      protocol: 'blind-pairing',
      id: discoveryKey,
      messages: [
        { encoding: c.buffer, onmessage: (req) => this._onpairingrequest(ch, ref, req) },
        { encoding: c.buffer, onmessage: (res) => this._onpairingresponse(ch, ref, res) }
      ],
      onclose: () => {
        ref.channels.delete(ch)
        if (ref.candidate) ref.candidate.visited.delete(ch)
      }
    })

    if (ch === null) return

    ch.open()
    mux.pair({ protocol: 'blind-pairing', id: discoveryKey }, () => this._attachToMuxer(mux, discoveryKey, null))
    ref.channels.add(ch)

    if (ref.candidate) ref.candidate.broadcast()
  }

  async _onpairingrequest (ch, ref, req) {
    if (!ref.member) return

    const request = await ref.member._addRequest(req)
    if (!request) return

    ch.messages[1].send(request.response)
  }

  async _onpairingresponse (ch, ref, res) {
    if (!ref.candidate) return

    await ref.candidate._addResponse(res, false)
  }
}

class Member extends ReadyResource {
  constructor (blind, { announce = true, discoveryKey, onadd = noop } = {}) {
    super()

    if (!discoveryKey) {
      throw new Error('Must provide discoveryKey')
    }

    const ref = blind._add(discoveryKey)

    if (ref.member) {
      throw new Error('Active member already exist')
    }

    ref.member = this

    this._pendingRequests = new Map()

    this.blind = blind
    this.dht = blind.swarm.dht
    this.discoveryKey = discoveryKey
    this.pairingDiscoveryKey = deriveDiscoveryKey(discoveryKey)
    this.timeout = new TimeoutPromise(blind._randomPoll())
    this.pairing = null
    this.skip = new Xache({ maxSize: 512 })
    this.ref = ref
    this.onadd = onadd

    this._activeQuery = null
    this._activePoll = null
    this._closestNodes = null
    this._autoAnnounce = announce

    this.ready()
  }

  announce () {
    if (this.pairing) return this.pairing

    this.blind._swarm(this.ref)
    this.pairing = this._run()
    this.pairing.catch(safetyCatch)

    return this.pairing
  }

  async flushed () {
    if (!this.ref.discovery) return
    return this.ref.discovery.flushed()
  }

  _open () {
    if (this._autoAnnounce) this.announce()
    else this.blind._attachToSwarm(this.ref)
  }

  _suspend () {
    this.timeout.suspend()
    return this._abort()
  }

  async _abort () {
    if (this._activeQuery) this._activeQuery.destroy()
    while (this._activePoll !== null) await this._activePoll
  }

  async refresh () {
    await this._abort()
    this.timeout.resume()
  }

  async _close () {
    this.ref.member = null
    this.blind._gc(this.ref)
    this.timeout.destroy()
    await this._abort()

    try {
      await this.pairing
    } catch {
      // ignore errors since we teardown
    }
  }

  async _run () {
    while (!this.closing) {
      this._activePoll = this._poll()
      await this._activePoll
      this._activePoll = null
      await this.timeout.wait()
    }
  }

  async _poll () {
    const visited = new Set()
    let alwaysClient = false

    if (this._activeQuery) this._activeQuery.destroy()

    const query = this._activeQuery = this.dht.lookup(this.pairingDiscoveryKey, { closestNodes: this._closestNodes })

    try {
      for await (const data of this._activeQuery) {
        if (this.closing || this.blind.suspended) return

        for (const peer of data.peers) {
          const id = b4a.toString(peer.publicKey, 'hex')

          if (visited.has(id) || this.skip.get(id)) continue
          visited.add(id)

          try {
            if (await this._add(peer.publicKey, id)) alwaysClient = true
          } catch (err) {
            safetyCatch(err)
          }

          if (this.closing || this.blind.suspended) return

          if (alwaysClient && !this.ref.alwaysClient) {
            this.ref.alwaysClient = true
            this.blind._swarm(this.ref)
          }
        }
      }
    } catch {
      // do nothing
    } finally {
      const nodes = this._activeQuery.closestNodes
      if (this._activeQuery === query) this._activeQuery = null
      if (nodes && nodes.length > 0) this._closestNodes = nodes
    }

    if (alwaysClient) this._revertClientAfterFlush() // safe to do in bg
  }

  async _revertClientAfterFlush () {
    try {
      await this.blind.swarm.flush()
    } catch {
      return
    }
    if (this.closing || this.blind.suspended) return

    this.ref.alwaysClient = false
    this.blind._swarm(this.ref)
  }

  async _addRequest (value) {
    let request = null
    try {
      request = MemberRequest.from(value)
    } catch {
      return null
    }

    request.discoveryKey = this.discoveryKey

    const session = b4a.toString(request.requestData.session, 'hex')

    if (!this._pendingRequests.has(session)) {
      this._pendingRequests.set(session, {
        request,
        promise: this.onadd(request)
      })
    }

    // laod existing request if it exists
    const pending = this._pendingRequests.get(session)

    try {
      await pending.promise
    } catch (e) {
      safetyCatch(e)
      return null
    }

    this._pendingRequests.delete(session)

    if (!pending.request.response) return null

    return pending.request
  }

  async _add (publicKey, id) {
    const node = await this.dht.mutableGet(publicKey, { latest: false })
    if (!node) return false

    this.skip.set(id, true)

    const request = await this._addRequest(node.value)
    if (!request) return false

    const replyKeyPair = deriveReplyKeyPair(request.token)
    await this.dht.mutablePut(replyKeyPair, request.response)

    return true
  }
}

class Candidate extends ReadyResource {
  constructor (blind, request, { discoveryKey = request.discoveryKey, onadd = noop } = {}) {
    super()

    const ref = blind._add(discoveryKey)
    if (ref.candidate) {
      throw new Error('Active candidate already exist')
    }

    ref.candidate = this

    this.blind = blind
    this.discoveryKey = discoveryKey
    this.pairingDiscoveryKey = deriveDiscoveryKey(discoveryKey)
    this.dht = blind.swarm.dht
    this.request = request
    this.token = request.token
    this.timeout = new TimeoutPromise(blind._randomPoll())
    this.announced = false
    this.gcing = null
    this.ref = ref
    this.paired = null
    this.pairing = null
    this.onadd = onadd

    this.signal = null
    this.visited = new Set()
    this.broadcast = debounce(this._broadcast.bind(this))

    this._activePoll = null

    this.ready()
  }

  _open () {
    this.blind._swarm(this.ref)
    this.pairing = this._run()
    this.broadcast()
  }

  _suspend () {
    this.timeout.suspend()
    // no good way to suspend the mut gets atm unfortunately so we just rely on the polls timing out
  }

  async refresh () {
    while (this._activePoll !== null) await this._activePoll
    this.announced = false
    this.timeout.resume()
  }

  async _close () {
    this.ref.candidate = null
    this.blind._gc(this.ref)
    this.timeout.destroy()
    this.visited.clear()
    await this.pairing
    // gc never throws
    if (this.gcing) await this.gcing
  }

  async _addResponse (value, gc) {
    if (this.paired) return

    const paired = this.request.handleResponse(value)
    if (!paired) return

    this.paired = paired
    if (this.signal) this.signal.destroy()

    if ((gc || this.announced) && !this.gcing) this.gcing = this._gc() // gc in the background
    await this.onadd(paired)
    this.timeout.destroy()
  }

  async _run () {
    while (!this._done()) {
      this._activePoll = this._poll()
      await this._activePoll
      this._activePoll = null
      if (this._done()) break
      await this.timeout.wait()
    }

    this.close().catch(safetyCatch)
    return this.paired
  }

  _done () {
    return !!(this.closing || this.paired)
  }

  async _announce () {
    const eph = deriveEphemeralKeyPair(this.token)

    await this.dht.mutablePut(eph, this.request.encode())
    if (this._done()) return

    await this.dht.announce(this.pairingDiscoveryKey, eph).finished()
    if (this._done()) return

    if (!this.paired) {
      this.ref.alwaysServer = true
      this.blind._swarm(this.ref)
    }

    this.emit('announce')
  }

  async _gc () {
    const eph = deriveEphemeralKeyPair(this.token)

    try {
      await this.dht.unannounce(this.pairingDiscoveryKey, eph)
    } catch (err) {
      safetyCatch(err) // just gc, whatevs
    }
  }

  _sendRequest (ch) {
    ch.messages[0].send(this.request.encode())
    this.visited.add(ch)
  }

  async _broadcast () {
    for (const channel of this.closestPeers()) {
      this.signal = new TimeoutPromise(randomInterval(PEER_INTERVAL))
      if (channel) this._sendRequest(channel)

      await this.signal.wait() // resolves on destroy

      if (this.paired || this.suspended) break
    }
  }

  * closestPeers () {
    while (!this.paired) {
      const closest = Infinity
      let channel = null

      for (const ch of this.ref.channels) {
        if (this.visited.has(ch)) continue

        const { rtt } = ch._mux.stream.rawStream
        if (rtt < closest) channel = ch
      }

      if (!channel) return

      yield channel
    }
  }

  async _poll () {
    try {
      const value = await this._getReply()
      if (this._done() || this.blind.suspended) return

      if (value) {
        await this._addResponse(value, true)
        if (this._done() || this.blind.suspended) return
      }

      if (!this.announced) {
        this.announced = true
        await this._announce()
      }
    } catch {
      // can run in bg, should never crash it
    }
  }

  async _getReply () {
    const { publicKey } = deriveReplyKeyPair(this.token)
    const node = await this.dht.mutableGet(publicKey, { latest: false })
    if (!node) return null
    return node.value
  }
}

module.exports = BlindPairing

function noop () {}

function deriveReplyKeyPair (token) {
  return crypto.keyPair(crypto.hash([NS_REPLY, token]))
}

function deriveEphemeralKeyPair (token) {
  return crypto.keyPair(crypto.hash([NS_EPHEMERAL, token]))
}

function deriveDiscoveryKey (discoveryKey) {
  return crypto.hash([NS_DISCOVERY, discoveryKey])
}

function getMuxer (stream) {
  if (stream.userData) return stream.userData
  const protocol = Protomux.from(stream)
  stream.setKeepAlive(5000)
  stream.userData = protocol
  return protocol
}

function randomInterval (n) {
  return n + (n * 0.5 * Math.random()) | 0
}
{
  "name": "blind-pairing",
  "version": "2.3.1",
  "description": "Blind pairing using Hyperswarm",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "blind-pairing-core": "^2.0.0",
    "b4a": "^1.6.4",
    "debounceify": "^1.1.0",
    "hypercore-crypto": "^3.4.0",
    "is-options": "^1.0.2",
    "ready-resource": "^1.0.0",
    "safety-catch": "^1.0.2",
    "xache": "^1.2.0"
  },
  "devDependencies": {
    "@hyperswarm/testnet": "^3.1.4",
    "brittle": "^3.3.2",
    "hyperdht": "^6.8.9",
    "hyperswarm": "^4.7.3",
    "minimist": "^1.2.8",
    "standard": "^17.1.0",
    "z32": "^1.0.1"
  },
  "scripts": {
    "test": "standard && brittle test/*.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/blind-pairing.git"
  },
  "author": "Holepunch Inc",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/blind-pairing/issues"
  },
  "homepage": "https://github.com/holepunchto/blind-pairing"
}
const EventEmitter = require('events')
const Protomux = require('protomux')
const { Readable } = require('streamx')
const sodium = require('sodium-universal')
const b4a = require('b4a')
const c = require('compact-encoding')
const bitfield = require('compact-encoding-bitfield')
const bits = require('bits-to-bytes')
const errors = require('./lib/errors')

exports.Server = class BlindRelayServer extends EventEmitter {
  constructor(opts = {}) {
    super()

    const { createStream } = opts

    this._createStream = createStream
    this._pairing = new Map()
    this._activePairingRefs = new Map()
    this._sessions = new Set()
    this.stats = createStats()
  }

  get sessions() {
    return this._sessions[Symbol.iterator]()
  }

  accept(stream, opts) {
    const session = new BlindRelaySession(this, stream, opts)

    this._sessions.add(session)
    this.stats.sessions.accepted++

    return session
  }

  async close() {
    const ending = []

    for (const session of this._sessions) {
      ending.push(session.end())
    }

    await Promise.all(ending)

    this._pairing.clear()
  }

  _trackActiveLink(keyString) {
    const refs = this._activePairingRefs.get(keyString) || 0

    if (refs === 0) this.stats.pairings.active++

    this._activePairingRefs.set(keyString, refs + 1)
  }

  _untrackActiveLink(keyString) {
    const refs = this._activePairingRefs.get(keyString)

    if (refs === undefined) return

    if (refs === 1) {
      this._activePairingRefs.delete(keyString)
      this.stats.pairings.active--
    } else {
      this._activePairingRefs.set(keyString, refs - 1)
    }
  }
}

class BlindRelaySession extends EventEmitter {
  constructor(server, stream, opts = {}) {
    super()

    const { id, handshake, handshakeEncoding } = opts

    this._server = server
    this._mux = Protomux.from(stream)

    this._channel = this._mux.createChannel({
      protocol: 'blind-relay',
      id,
      handshake: handshake ? handshakeEncoding || c.raw : null,
      onopen: this._onopen.bind(this),
      onclose: this._onclose.bind(this),
      ondestroy: this._ondestroy.bind(this)
    })

    this._pair = this._channel.addMessage({
      encoding: m.pair,
      onmessage: this._onpair.bind(this)
    })

    this._unpair = this._channel.addMessage({
      encoding: m.unpair,
      onmessage: this._onunpair.bind(this)
    })

    this._ending = null
    this._destroyed = false
    this._error = null
    this._pairing = new Set()
    this._links = new Map()

    this._onerror = (err) => {
      this._server.stats.streams.errors++
      this.emit('error', err)
    }

    this._channel.open(handshake)
  }

  get closed() {
    return this._channel.closed
  }

  get mux() {
    return this._mux
  }

  get stream() {
    return this._mux.stream
  }

  _onopen() {
    this._server.stats.sessions.opened++
    this.emit('open')
  }

  _onclose() {
    this._ending = Promise.resolve()

    const err = this._error || errors.CHANNEL_CLOSED()
    this._server.stats.pairings.cancelled += this._pairing.size

    for (const token of this._pairing) {
      if (this._server._pairing.delete(token.toString('hex'))) {
        this._server.stats.pairings.pending--
      }
    }

    for (const link of this._links.values()) {
      link.destroy(err)
    }

    this._pairing.clear()
    this._links.clear()

    this._server._sessions.delete(this)
    this._server.stats.sessions.closed++

    this.emit('close')
  }

  _ondestroy() {
    this._destroyed = true
    this.emit('destroy')
  }

  _onpair({ isInitiator, token, id: remoteId }) {
    const keyString = token.toString('hex')

    let pair = this._server._pairing.get(keyString)

    if (pair === undefined) {
      pair = new BlindRelayPair(token)
      this._server._pairing.set(keyString, pair)
      this._server.stats.pairings.pending++
    } else if (pair.links[+isInitiator]) return

    this._pairing.add(keyString)
    this._server.stats.pairings.requested++

    pair.links[+isInitiator] = new BlindRelayLink(this, isInitiator, remoteId)

    if (!pair.paired) return

    this._server._pairing.delete(keyString)
    this._server.stats.pairings.pending--
    this._server.stats.pairings.matched++

    // 1st pass: Create the raw streams needed for each end of the link.
    for (const link of pair.links) {
      link.createStream()
    }

    // 2nd pass: Connect the raw streams and set up handlers.
    for (const link of pair.links) {
      link.remote = pair.remote(link.isInitiator)
      link.activate(keyString)
    }

    // 3rd pass: Let either end of the link know the streams were set up.
    for (const { isInitiator, session, remoteId, stream } of pair.links) {
      session._pair.send({
        isInitiator,
        token,
        id: stream.id,
        seq: 0
      })

      session._endMaybe()

      session.emit('pair', isInitiator, token, stream, remoteId)
    }
  }

  _onunpair({ token }) {
    const keyString = token.toString('hex')

    const pair = this._server._pairing.get(keyString)

    if (pair) {
      for (const link of pair.links) {
        if (link) link.session._pairing.delete(keyString)
      }

      this._server._pairing.delete(keyString)
      this._server.stats.pairings.pending--
      this._server.stats.pairings.cancelled++
      return
    }

    const link = this._links.get(keyString)

    if (link) {
      link.destroyPair(errors.PAIRING_CANCELLED())
      this._server.stats.pairings.cancelled++
    }
  }

  cork() {
    this._channel.cork()
  }

  uncork() {
    this._channel.uncork()
  }

  async end() {
    if (this._ending) return this._ending

    this._ending = EventEmitter.once(this, 'close')
    this._endMaybe()

    return this._ending
  }

  _endMaybe() {
    if (this._ending && this._pairing.size === 0) {
      this._channel.close()
    }
  }

  destroy(err) {
    if (this._destroyed) return
    this._destroyed = true

    this._error = err || errors.CHANNEL_DESTROYED()
    this._channel.close()
  }
}

class BlindRelayPair {
  constructor(token) {
    this.token = token
    this.links = [null, null]
  }

  get paired() {
    return this.links[0] !== null && this.links[1] !== null
  }

  remote(isInitiator) {
    return this.links[isInitiator ? 0 : 1]
  }
}

class BlindRelayLink {
  constructor(session, isInitiator, remoteId) {
    this.session = session
    this.isInitiator = isInitiator
    this.remoteId = remoteId
    this.stream = null
    this.remote = null
    this.keyString = null
    this._onclose = null
  }

  createStream() {
    if (this.stream) return

    this.stream = this.session._server._createStream({
      firewall: this._onfirewall.bind(this)
    })
  }

  activate(keyString) {
    const stream = this.stream

    this.keyString = keyString
    this._onclose = () => {
      if (this.stream !== stream) return

      this.stream = null
      unlink(this)
      this.session._links.delete(keyString)
      this.session._server._untrackActiveLink(keyString)
      this.session._server.stats.streams.closed++
    }

    stream.on('error', this.session._onerror).on('close', this._onclose).relayTo(this.remote.stream)

    this.session._pairing.delete(keyString)
    this.session._links.set(keyString, this)
    this.session._server._trackActiveLink(keyString)
    this.session._server.stats.streams.opened++
  }

  destroy(err) {
    const stream = this.stream

    if (!stream) return

    this.stream = null

    stream.off('close', this._onclose)
    this._onclose = null

    stream.off('error', this.session._onerror)
    unlink(this)
    this.session._links.delete(this.keyString)
    this.session._server._untrackActiveLink(this.keyString)
    this.session._server.stats.streams.closed++
    stream.on('error', noop).destroy(err)
  }

  destroyPair(err) {
    const remote = this.remote

    this.destroy(err)
    if (remote) remote.destroy(err)
  }

  _onfirewall(socket, port, host) {
    this.stream.connect(socket, this.remoteId, port, host)

    return false
  }
}

exports.Client = class BlindRelayClient extends EventEmitter {
  static _clients = new WeakMap()

  static from(stream, opts) {
    let client = this._clients.get(stream)
    if (client) return client
    client = new this(stream, opts)
    this._clients.set(stream, client)
    return client
  }

  constructor(stream, opts = {}) {
    super()

    const { id, handshake, handshakeEncoding } = opts

    this._mux = Protomux.from(stream)

    this._channel = this._mux.createChannel({
      protocol: 'blind-relay',
      id,
      handshake: handshake ? handshakeEncoding || c.raw : null,
      onopen: this._onopen.bind(this),
      onclose: this._onclose.bind(this),
      ondestroy: this._ondestroy.bind(this)
    })

    this._pair = this._channel.addMessage({
      encoding: m.pair,
      onmessage: this._onpair.bind(this)
    })

    this._unpair = this._channel.addMessage({
      encoding: m.unpair
    })

    this._ending = false
    this._destroyed = false
    this._error = null
    this._requests = new Map()

    this._channel.open(handshake)
  }

  get closed() {
    return this._channel.closed
  }

  get mux() {
    return this._mux
  }

  get stream() {
    return this._mux.stream
  }

  get requests() {
    return this._requests.values()
  }

  _onopen() {
    this.emit('open')
  }

  _onclose() {
    this._ending = Promise.resolve()

    const err = this._error || errors.CHANNEL_CLOSED()

    for (const request of this._requests.values()) {
      request.destroy(err)
    }

    this._requests.clear()

    this.constructor._clients.delete(this.stream)

    this.emit('close')
  }

  _ondestroy() {
    this._destroyed = true
    this.emit('destroy')
  }

  _onpair({ isInitiator, token, id: remoteId }) {
    const request = this._requests.get(token.toString('hex'))

    if (request === undefined || request.isInitiator !== isInitiator) return

    request.push(remoteId)
    request.push(null)

    this.emit('pair', request.isInitiator, request.token, request.stream, remoteId)
  }

  pair(isInitiator, token, stream) {
    if (this._destroyed) throw errors.CHANNEL_DESTROYED()

    const keyString = token.toString('hex')

    if (this._requests.has(keyString)) throw errors.ALREADY_PAIRING()

    const request = new BlindRelayRequest(this, isInitiator, token, stream)

    this._requests.set(keyString, request)

    return request
  }

  unpair(token) {
    if (this._destroyed) throw errors.CHANNEL_DESTROYED()

    const request = this._requests.get(token.toString('hex'))

    if (request) request.destroy(errors.PAIRING_CANCELLED())

    this._unpair.send({ token })
  }

  cork() {
    this._channel.cork()
  }

  uncork() {
    this._channel.uncork()
  }

  async end() {
    if (this._ending) return this._ending

    this._ending = EventEmitter.once(this, 'close')
    this._endMaybe()

    return this._ending
  }

  _endMaybe() {
    if (this._ending && this._requests.size === 0) {
      this._channel.close()
    }
  }

  destroy(err) {
    if (this._destroyed) return
    this._destroyed = true

    this._error = err || errors.CHANNEL_DESTROYED()
    this._channel.close()
  }
}

class BlindRelayRequest extends Readable {
  constructor(client, isInitiator, token, stream) {
    super()

    this.client = client
    this.isInitiator = isInitiator
    this.token = token
    this.stream = stream
  }

  _open(cb) {
    if (this.client._destroyed) return cb(errors.CHANNEL_DESTROYED())

    this.client._pair.send({
      isInitiator: this.isInitiator,
      token: this.token,
      id: this.stream.id,
      seq: 0
    })

    cb(null)
  }

  _destroy(cb) {
    this.client._requests.delete(this.token.toString('hex'))

    cb(null)

    this.client._endMaybe()
  }
}

exports.token = function token(buf = b4a.allocUnsafe(32)) {
  sodium.randombytes_buf(buf)
  return buf
}

function noop() {}

function unlink(link) {
  const remote = link.remote

  link.remote = null

  if (remote && remote.remote === link) {
    remote.remote = null
  }
}

function createStats() {
  const stats = {
    sessions: {
      accepted: 0,
      opened: 0,
      closed: 0,
      get active() {
        return this.accepted - this.closed
      }
    },
    pairings: {
      requested: 0,
      matched: 0,
      cancelled: 0,
      pending: 0,
      active: 0
    },
    streams: {
      opened: 0,
      closed: 0,
      errors: 0,
      get active() {
        return this.opened - this.closed
      }
    }
  }

  return stats
}

const m = (exports.messages = {})

const flags = bitfield(7)

m.pair = {
  preencode(state, m) {
    flags.preencode(state)
    c.fixed32.preencode(state, m.token)
    c.uint.preencode(state, m.id)
    c.uint.preencode(state, m.seq)
  },
  encode(state, m) {
    flags.encode(state, bits.of(m.isInitiator))
    c.fixed32.encode(state, m.token)
    c.uint.encode(state, m.id)
    c.uint.encode(state, m.seq)
  },
  decode(state) {
    const [isInitiator] = bits.iterator(flags.decode(state))

    return {
      isInitiator,
      token: c.fixed32.decode(state),
      id: c.uint.decode(state),
      seq: c.uint.decode(state)
    }
  }
}

m.unpair = {
  preencode(state, m) {
    flags.preencode(state)
    c.fixed32.preencode(state, m.token)
  },
  encode(state, m) {
    flags.encode(state, bits.of())
    c.fixed32.encode(state, m.token)
  },
  decode(state) {
    flags.decode(state)

    return {
      token: c.fixed32.decode(state)
    }
  }
}
module.exports = class BlindRelayError extends Error {
  constructor(msg, code, fn = BlindRelayError) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'BlindRelayError'
  }

  static DUPLICATE_CHANNEL(msg = 'Duplicate channel') {
    return new BlindRelayError(msg, 'DUPLICATE_CHANNEL', BlindRelayError.DUPLICATE_CHANNEL)
  }

  static CHANNEL_CLOSED(msg = 'Channel closed') {
    return new BlindRelayError(msg, 'CHANNEL_CLOSED', BlindRelayError.CHANNEL_CLOSED)
  }

  static CHANNEL_DESTROYED(msg = 'Channel destroyed') {
    return new BlindRelayError(msg, 'CHANNEL_DESTROYED', BlindRelayError.CHANNEL_DESTROYED)
  }

  static ALREADY_PAIRING(msg = 'Already pairing') {
    return new BlindRelayError(msg, 'ALREADY_PAIRING', BlindRelayError.ALREADY_PAIRING)
  }

  static PAIRING_CANCELLED(msg = 'Pairing cancelled') {
    return new BlindRelayError(msg, 'PAIRING_CANCELLED', BlindRelayError.PAIRING_CANCELLED)
  }
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "blind-relay",
  "version": "1.6.1",
  "description": "Blind relay for UDX over Protomux channels",
  "main": "index.js",
  "files": [
    "index.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:bare",
    "test:bare": "brittle-bare --coverage test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/blind-relay.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/blind-relay/issues"
  },
  "homepage": "https://github.com/holepunchto/blind-relay#readme",
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "dependencies": {
    "b4a": "^1.6.4",
    "bare-events": "^2.2.0",
    "bits-to-bytes": "^1.3.0",
    "compact-encoding": "^3.0.0",
    "compact-encoding-bitfield": "^1.0.0",
    "protomux": "^3.5.1",
    "sodium-universal": "^5.0.0",
    "streamx": "^2.15.1"
  },
  "devDependencies": {
    "brittle": "^3.2.1",
    "hyperdht": "^6.6.1",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "udx-native": "^1.6.1"
  }
}
// https://ipinfo.io/bogon

const b4a = require('b4a')
const c = require('compact-encoding')

module.exports = exports = function isBogon (ip) {
  return isBogonIP(ensureBuffer(ip))
}

exports.isBogon = exports

exports.isPrivate = function isPrivate (ip) {
  return isPrivateIP(ensureBuffer(ip))
}

exports.isReserved = function isReserved (ip) {
  return isReservedIP(ensureBuffer(ip))
}

function isBogonIP (ip) {
  return isPrivateIP(ip) || isReservedIP(ip)
}

function isPrivateIP (ip) {
  return ip.byteLength === 4 ? isPrivateIPv4(ip) : false // IPv6 has no private IPs
}

function isPrivateIPv4 (ip) {
  return (
    // 10.0.0.0/8  Private-use networks
    (ip[0] === 10) ||
    // 100.64.0.0/10 Carrier-grade NAT
    (ip[0] === 100 && ip[1] >= 64 && ip[1] <= 127) ||
    // 127.0.0.0/8 Loopback + Name collision occurrence (127.0.53.53)
    (ip[0] === 127) ||
    // 169.254.0.0/16  Link local
    (ip[0] === 169 && ip[1] === 254) ||
    // 172.16.0.0/12 Private-use networks
    (ip[0] === 172 && ip[1] >= 16 && ip[1] <= 31) ||
    // 192.168.0.0/16  Private-use networks
    (ip[0] === 192 && ip[1] === 168)
  )
}

function isReservedIP (ip) {
  return ip.byteLength === 4 ? isReservedIPv4(ip) : isReservedIPv6(ip)
}

function isReservedIPv4 (ip) {
  return (
    // 0.0.0.0/8 "This" network
    (ip[0] === 0) ||
    // 192.0.0.0/24  IETF protocol assignments
    (ip[0] === 192 && ip[1] === 0 && ip[2] === 0) ||
    // 192.0.2.0/24  TEST-NET-1
    (ip[0] === 192 && ip[1] === 0 && ip[2] === 2) ||
    // 198.18.0.0/15 Network interconnect device benchmark testing
    (ip[0] === 198 && ip[1] >= 18 && ip[1] <= 19) ||
    // 198.51.100.0/24 TEST-NET-2
    (ip[0] === 198 && ip[1] === 51 && ip[2] === 100) ||
    // 203.0.113.0/24  TEST-NET-3
    (ip[0] === 203 && ip[1] === 0 && ip[2] === 113) ||
    // 224.0.0.0/4 Multicast
    (ip[0] >= 224 && ip[0] <= 239) ||
    // 240.0.0.0/4 Reserved for future use
    (ip[0] >= 240) ||
    // 255.255.255.255/32
    (ip[0] === 255 && ip[1] === 255 && ip[2] === 255 && ip[3] === 255)
  )
}

function isReservedIPv6 (ip) {
  return (
    // ::/128 Node-scope unicast unspecified address
    // ::1/128 Node-scope unicast loopback address
    (
      ip[0] === 0 && ip[1] === 0 && ip[2] === 0 && ip[3] === 0 && ip[4] === 0 &&
      ip[5] === 0 && ip[6] === 0 && ip[7] === 0 && ip[8] === 0 && ip[9] === 0 &&
      ip[10] === 0 && ip[11] === 0 && ip[12] === 0 && ip[13] === 0 && ip[14] === 0 &&
      ip[15] <= 1
    ) ||
    // ::ffff:0:0/96 IPv4-mapped addresses
    // ::/96 IPv4-compatible addresses
    (
      ip[0] === 0 && ip[1] === 0 && ip[2] === 0 && ip[3] === 0 && ip[4] === 0 &&
      ip[5] === 0 && ip[6] === 0 && ip[7] === 0 && ip[8] === 0 && ip[9] === 0 &&
      (ip[10] === 0 || ip[10] === 0xff) &&
      (ip[11] === 0 || ip[11] === 0xff)
    ) ||
    // 100::/64 Remotely triggered black hole addresses
    (ip[0] === 0x01 && ip[1] === 0 && ip[2] === 0 && ip[3] === 0 && ip[4] === 0 && ip[5] === 0 && ip[6] === 0 && ip[7] === 0) ||
    // 2001:10::/28 Overlay routable cryptographic hash identifiers (ORCHID)
    (ip[0] === 0x20 && ip[1] === 0x01 && ip[2] === 0 && ip[3] >= 0x10 && ip[3] <= 0x1f) ||
    // 2001:20::/28 Overlay routable cryptographic hash identifiers version 2 (ORCHIDv2)
    (ip[0] === 0x20 && ip[1] === 0x01 && ip[2] === 0 && ip[3] >= 0x20 && ip[3] <= 0x2f) ||
    // 2001:db8::/32 Documentation prefix
    (ip[0] === 0x20 && ip[1] === 0x01 && ip[2] === 0x0d && ip[3] === 0xb8) ||
    // fc00::/7 Unique local addresses (ULA)
    (ip[0] >= 0xfc && ip[0] <= 0xfd) ||
    // fe80::/10 Link-local unicast
    (ip[0] === 0xfe && ip[1] >= 0x80 && ip[1] <= 0xbf) ||
    // ff00::/8 Multicast
    (ip[0] === 0xff)
  )
}

const state = c.state(0, 0, b4a.allocUnsafe(1 /* family */ + 16))

function ensureBuffer (ip) {
  if (b4a.isBuffer(ip)) return ip

  c.ip.preencode(state, ip)
  c.ip.encode(state, ip)

  const buffer = state.buffer.subarray(1 /* family */, state.end)

  state.start = 0
  state.end = 0

  return buffer
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "bogon",
  "version": "1.3.0",
  "description": "Check if an IP is a bogon",
  "main": "index.js",
  "scripts": {
    "test": "standard && brittle test.mjs"
  },
  "dependencies": {
    "compact-encoding": "^3.0.0",
    "compact-encoding-net": "^1.2.0"
  },
  "devDependencies": {
    "brittle": "^3.0.4",
    "nanobench": "^2.1.1",
    "standard": "^17.0.0"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/bogon.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/bogon/issues"
  },
  "homepage": "https://github.com/mafintosh/bogon"
}
import { encode, encodeInto, objectToTokens, rfc8949EncodeOptions } from './lib/encode.js'
import { decode, decodeFirst, Tokeniser, tokensToObject } from './lib/decode.js'
import { Tagged } from './lib/tagged.js'
import { Token, Type } from './lib/token.js'

/**
 * Export the types that were present in the original manual cborg.d.ts
 * @typedef {import('./interface.js').TagDecodeControl} TagDecodeControl
 * @typedef {import('./interface.js').TagDecoder} TagDecoder
 * There was originally just `TypeEncoder` so don't break types by renaming or not exporting
 * @typedef {import('./interface.js').OptionalTypeEncoder} TypeEncoder
 * @typedef {import('./interface.js').DecodeOptions} DecodeOptions
 * @typedef {import('./interface.js').EncodeOptions} EncodeOptions
 */

export {
  decode,
  decodeFirst,
  Tokeniser as Tokenizer,
  tokensToObject,
  encode,
  encodeInto,
  objectToTokens,
  rfc8949EncodeOptions,
  Tagged,
  Token,
  Type
}
/* globals BigInt */

import { Token, Type } from './token.js'
import { decodeErrPrefix, assertEnoughData } from './common.js'

export const uintBoundaries = [24, 256, 65536, 4294967296, BigInt('18446744073709551616')]

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number}
 */
export function readUint8 (data, offset, options) {
  assertEnoughData(data, offset, 1)
  const value = data[offset]
  if (options.strict === true && value < uintBoundaries[0]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  return value
}

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number}
 */
export function readUint16 (data, offset, options) {
  assertEnoughData(data, offset, 2)
  const value = (data[offset] << 8) | data[offset + 1]
  if (options.strict === true && value < uintBoundaries[1]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  return value
}

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number}
 */
export function readUint32 (data, offset, options) {
  assertEnoughData(data, offset, 4)
  const value = (data[offset] * 16777216 /* 2 ** 24 */) + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]
  if (options.strict === true && value < uintBoundaries[2]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  return value
}

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number|bigint}
 */
export function readUint64 (data, offset, options) {
  // assume BigInt, convert back to Number if within safe range
  assertEnoughData(data, offset, 8)
  const hi = (data[offset] * 16777216 /* 2 ** 24 */) + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]
  const lo = (data[offset + 4] * 16777216 /* 2 ** 24 */) + (data[offset + 5] << 16) + (data[offset + 6] << 8) + data[offset + 7]
  const value = (BigInt(hi) << BigInt(32)) + BigInt(lo)
  if (options.strict === true && value < uintBoundaries[3]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  if (value <= Number.MAX_SAFE_INTEGER) {
    return Number(value)
  }
  if (options.allowBigInt === true) {
    return value
  }
  throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`)
}

/* not required thanks to quick[] list
const oneByteTokens = new Array(24).fill(0).map((v, i) => new Token(Type.uint, i, 1))
export function decodeUintCompact (data, pos, minor, options) {
  return oneByteTokens[minor]
}
*/

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint8 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint8(data, pos + 1, options), 2)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint16 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint16(data, pos + 1, options), 3)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint32 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint32(data, pos + 1, options), 5)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint64 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint64(data, pos + 1, options), 9)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeUint (writer, token) {
  return encodeUintValue(writer, 0, token.value)
}

/**
 * @param {ByteWriter} writer
 * @param {number} major
 * @param {number|bigint} uint
 */
export function encodeUintValue (writer, major, uint) {
  if (uint < uintBoundaries[0]) {
    const nuint = Number(uint)
    // pack into one byte, minor=0, additional=value
    writer.push([major | nuint])
  } else if (uint < uintBoundaries[1]) {
    const nuint = Number(uint)
    // pack into two byte, minor=0, additional=24
    writer.push([major | 24, nuint])
  } else if (uint < uintBoundaries[2]) {
    const nuint = Number(uint)
    // pack into three byte, minor=0, additional=25
    writer.push([major | 25, nuint >>> 8, nuint & 0xff])
  } else if (uint < uintBoundaries[3]) {
    const nuint = Number(uint)
    // pack into five byte, minor=0, additional=26
    writer.push([major | 26, (nuint >>> 24) & 0xff, (nuint >>> 16) & 0xff, (nuint >>> 8) & 0xff, nuint & 0xff])
  } else {
    const buint = BigInt(uint)
    if (buint < uintBoundaries[4]) {
      // pack into nine byte, minor=0, additional=27
      const set = [major | 27, 0, 0, 0, 0, 0, 0, 0]
      // simulate bitwise above 32 bits
      let lo = Number(buint & BigInt(0xffffffff))
      let hi = Number(buint >> BigInt(32) & BigInt(0xffffffff))
      set[8] = lo & 0xff
      lo = lo >> 8
      set[7] = lo & 0xff
      lo = lo >> 8
      set[6] = lo & 0xff
      lo = lo >> 8
      set[5] = lo & 0xff
      set[4] = hi & 0xff
      hi = hi >> 8
      set[3] = hi & 0xff
      hi = hi >> 8
      set[2] = hi & 0xff
      hi = hi >> 8
      set[1] = hi & 0xff
      writer.push(set)
    } else {
      throw new Error(`${decodeErrPrefix} encountered BigInt larger than allowable range`)
    }
  }
}

/**
 * @param {Token} token
 * @returns {number}
 */
encodeUint.encodedSize = function encodedSize (token) {
  return encodeUintValue.encodedSize(token.value)
}

/**
 * @param {number} uint
 * @returns {number}
 */
encodeUintValue.encodedSize = function encodedSize (uint) {
  if (uint < uintBoundaries[0]) {
    return 1
  }
  if (uint < uintBoundaries[1]) {
    return 2
  }
  if (uint < uintBoundaries[2]) {
    return 3
  }
  if (uint < uintBoundaries[3]) {
    return 5
  }
  return 9
}

/**
 * @param {Token} tok1
 * @param {Token} tok2
 * @returns {number}
 */
encodeUint.compareTokens = function compareTokens (tok1, tok2) {
  return tok1.value < tok2.value ? -1 : tok1.value > tok2.value ? 1 : 0
}
/* eslint-env es2020 */

import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import { decodeErrPrefix } from './common.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint8 (data, pos, _minor, options) {
  return new Token(Type.negint, -1 - uint.readUint8(data, pos + 1, options), 2)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint16 (data, pos, _minor, options) {
  return new Token(Type.negint, -1 - uint.readUint16(data, pos + 1, options), 3)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint32 (data, pos, _minor, options) {
  return new Token(Type.negint, -1 - uint.readUint32(data, pos + 1, options), 5)
}

const neg1b = BigInt(-1)
const pos1b = BigInt(1)

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint64 (data, pos, _minor, options) {
  const int = uint.readUint64(data, pos + 1, options)
  if (typeof int !== 'bigint') {
    const value = -1 - int
    if (value >= Number.MIN_SAFE_INTEGER) {
      return new Token(Type.negint, value, 9)
    }
  }
  if (options.allowBigInt !== true) {
    throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`)
  }
  return new Token(Type.negint, neg1b - BigInt(int), 9)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeNegint (writer, token) {
  const negint = token.value
  const unsigned = (typeof negint === 'bigint' ? (negint * neg1b - pos1b) : (negint * -1 - 1))
  uint.encodeUintValue(writer, token.type.majorEncoded, unsigned)
}

/**
 * @param {Token} token
 * @returns {number}
 */
encodeNegint.encodedSize = function encodedSize (token) {
  const negint = token.value
  const unsigned = (typeof negint === 'bigint' ? (negint * neg1b - pos1b) : (negint * -1 - 1))
  // handled by quickEncode, we shouldn't get here but it's included for completeness
  if (unsigned < uint.uintBoundaries[0]) {
    return 1
  }
  if (unsigned < uint.uintBoundaries[1]) {
    return 2
  }
  if (unsigned < uint.uintBoundaries[2]) {
    return 3
  }
  if (unsigned < uint.uintBoundaries[3]) {
    return 5
  }
  return 9
}

/**
 * @param {Token} tok1
 * @param {Token} tok2
 * @returns {number}
 */
encodeNegint.compareTokens = function compareTokens (tok1, tok2) {
  // opposite of the uint comparison since we store the uint version in bytes
  return tok1.value < tok2.value ? 1 : tok1.value > tok2.value ? -1 : 0
}
import { Token, Type } from './token.js'
import { assertEnoughData, decodeErrPrefix } from './common.js'
import * as uint from './0uint.js'
import { compare, fromString } from './byte-utils.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} prefix
 * @param {number} length
 * @returns {Token}
 */
function toToken (data, pos, prefix, length) {
  assertEnoughData(data, pos, prefix + length)
  const buf = data.slice(pos + prefix, pos + prefix + length)
  return new Token(Type.bytes, buf, prefix + length)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeBytesCompact (data, pos, minor, _options) {
  return toToken(data, pos, 1, minor)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer bytes lengths not supported`)
  }
  return toToken(data, pos, 9, l)
}

/**
 * `encodedBytes` allows for caching when we do a byte version of a string
 * for key sorting purposes
 * @param {Token} token
 * @returns {Uint8Array}
 */
function tokenBytes (token) {
  if (token.encodedBytes === undefined) {
    token.encodedBytes = Type.equals(token.type, Type.string) ? fromString(token.value) : token.value
  }
  // @ts-ignore c'mon
  return token.encodedBytes
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeBytes (writer, token) {
  const bytes = tokenBytes(token)
  uint.encodeUintValue(writer, token.type.majorEncoded, bytes.length)
  writer.push(bytes)
}

/**
 * @param {Token} token
 * @returns {number}
 */
encodeBytes.encodedSize = function encodedSize (token) {
  const bytes = tokenBytes(token)
  return uint.encodeUintValue.encodedSize(bytes.length) + bytes.length
}

/**
 * @param {Token} tok1
 * @param {Token} tok2
 * @returns {number}
 */
encodeBytes.compareTokens = function compareTokens (tok1, tok2) {
  return compareBytes(tokenBytes(tok1), tokenBytes(tok2))
}

/**
 * @param {Uint8Array} b1
 * @param {Uint8Array} b2
 * @returns {number}
 */
export function compareBytes (b1, b2) {
  return b1.length < b2.length ? -1 : b1.length > b2.length ? 1 : compare(b1, b2)
}
import { Token, Type } from './token.js'
import { assertEnoughData, decodeErrPrefix } from './common.js'
import * as uint from './0uint.js'
import { encodeBytes } from './2bytes.js'

const textDecoder = new TextDecoder()

// Threshold for ASCII fast-path vs TextDecoder. Short ASCII strings (common for
// map keys) are faster to decode with a simple loop than TextDecoder overhead.
const ASCII_THRESHOLD = 32

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * Decode UTF-8 bytes to string. For short ASCII strings (common case for map keys),
 * a simple loop is faster than TextDecoder.
 * @param {Uint8Array} bytes
 * @param {number} start
 * @param {number} end
 * @returns {string}
 */
function toStr (bytes, start, end) {
  const len = end - start
  if (len < ASCII_THRESHOLD) {
    let str = ''
    for (let i = start; i < end; i++) {
      const c = bytes[i]
      if (c & 0x80) { // non-ASCII, fall back to TextDecoder
        return textDecoder.decode(bytes.subarray(start, end))
      }
      str += String.fromCharCode(c)
    }
    return str
  }
  return textDecoder.decode(bytes.subarray(start, end))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} prefix
 * @param {number} length
 * @param {DecodeOptions} options
 * @returns {Token}
 */
function toToken (data, pos, prefix, length, options) {
  const totLength = prefix + length
  assertEnoughData(data, pos, totLength)
  const tok = new Token(Type.string, toStr(data, pos + prefix, pos + totLength), totLength)
  if (options.retainStringBytes === true) {
    tok.byteValue = data.slice(pos + prefix, pos + totLength)
  }
  return tok
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeStringCompact (data, pos, minor, options) {
  return toToken(data, pos, 1, minor, options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options), options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options), options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options), options)
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer string lengths not supported`)
  }
  return toToken(data, pos, 9, l, options)
}

export const encodeString = encodeBytes
import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import { decodeErrPrefix } from './common.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} prefix
 * @param {number} length
 * @returns {Token}
 */
function toToken (_data, _pos, prefix, length) {
  return new Token(Type.array, length, prefix)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeArrayCompact (data, pos, minor, _options) {
  return toToken(data, pos, 1, minor)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer array lengths not supported`)
  }
  return toToken(data, pos, 9, l)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArrayIndefinite (data, pos, _minor, options) {
  if (options.allowIndefinite === false) {
    throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)
  }
  return toToken(data, pos, 1, Infinity)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeArray (writer, token) {
  uint.encodeUintValue(writer, Type.array.majorEncoded, token.value)
}

// using an array as a map key, are you sure about this? we can only sort
// by map length here, it's up to the encoder to decide to look deeper
encodeArray.compareTokens = uint.encodeUint.compareTokens

/**
 * @param {Token} token
 * @returns {number}
 */
encodeArray.encodedSize = function encodedSize (token) {
  return uint.encodeUintValue.encodedSize(token.value)
}
import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import { decodeErrPrefix } from './common.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} prefix
 * @param {number} length
 * @returns {Token}
 */
function toToken (_data, _pos, prefix, length) {
  return new Token(Type.map, length, prefix)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeMapCompact (data, pos, minor, _options) {
  return toToken(data, pos, 1, minor)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer map lengths not supported`)
  }
  return toToken(data, pos, 9, l)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMapIndefinite (data, pos, _minor, options) {
  if (options.allowIndefinite === false) {
    throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)
  }
  return toToken(data, pos, 1, Infinity)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeMap (writer, token) {
  uint.encodeUintValue(writer, Type.map.majorEncoded, token.value)
}

// using a map as a map key, are you sure about this? we can only sort
// by map length here, it's up to the encoder to decide to look deeper
encodeMap.compareTokens = uint.encodeUint.compareTokens

/**
 * @param {Token} token
 * @returns {number}
 */
encodeMap.encodedSize = function encodedSize (token) {
  return uint.encodeUintValue.encodedSize(token.value)
}
import { Token, Type } from './token.js'
import * as uint from './0uint.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeTagCompact (_data, _pos, minor, _options) {
  return new Token(Type.tag, minor, 1)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag8 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint8(data, pos + 1, options), 2)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag16 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint16(data, pos + 1, options), 3)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag32 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint32(data, pos + 1, options), 5)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag64 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint64(data, pos + 1, options), 9)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeTag (writer, token) {
  uint.encodeUintValue(writer, Type.tag.majorEncoded, token.value)
}

encodeTag.compareTokens = uint.encodeUint.compareTokens

/**
 * @param {Token} token
 * @returns {number}
 */
encodeTag.encodedSize = function encodedSize (token) {
  return uint.encodeUintValue.encodedSize(token.value)
}
// TODO: shift some of the bytes logic to bytes-utils so we can use Buffer
// where possible

import { Token, Type } from './token.js'
import { decodeErrPrefix } from './common.js'
import { encodeUint } from './0uint.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 * @typedef {import('../interface.js').EncodeOptions} EncodeOptions
 */

export const MINOR_FALSE = 20
export const MINOR_TRUE = 21
export const MINOR_NULL = 22
export const MINOR_UNDEFINED = 23

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUndefined (_data, _pos, _minor, options) {
  if (options.allowUndefined === false) {
    throw new Error(`${decodeErrPrefix} undefined values are not supported`)
  } else if (options.coerceUndefinedToNull === true) {
    return new Token(Type.null, null, 1)
  }
  return new Token(Type.undefined, undefined, 1)
}

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBreak (_data, _pos, _minor, options) {
  if (options.allowIndefinite === false) {
    throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)
  }
  return new Token(Type.break, undefined, 1)
}

/**
 * @param {number} value
 * @param {number} bytes
 * @param {DecodeOptions} options
 * @returns {Token}
 */
function createToken (value, bytes, options) {
  if (options) {
    if (options.allowNaN === false && Number.isNaN(value)) {
      throw new Error(`${decodeErrPrefix} NaN values are not supported`)
    }
    if (options.allowInfinity === false && (value === Infinity || value === -Infinity)) {
      throw new Error(`${decodeErrPrefix} Infinity values are not supported`)
    }
  }
  return new Token(Type.float, value, bytes)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeFloat16 (data, pos, _minor, options) {
  return createToken(readFloat16(data, pos + 1), 3, options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeFloat32 (data, pos, _minor, options) {
  return createToken(readFloat32(data, pos + 1), 5, options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeFloat64 (data, pos, _minor, options) {
  return createToken(readFloat64(data, pos + 1), 9, options)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 * @param {EncodeOptions} options
 */
export function encodeFloat (writer, token, options) {
  const float = token.value

  if (float === false) {
    writer.push([Type.float.majorEncoded | MINOR_FALSE])
  } else if (float === true) {
    writer.push([Type.float.majorEncoded | MINOR_TRUE])
  } else if (float === null) {
    writer.push([Type.float.majorEncoded | MINOR_NULL])
  } else if (float === undefined) {
    writer.push([Type.float.majorEncoded | MINOR_UNDEFINED])
  } else {
    let decoded
    let success = false
    if (!options || options.float64 !== true) {
      encodeFloat16(float)
      decoded = readFloat16(ui8a, 1)
      if (float === decoded || Number.isNaN(float)) {
        ui8a[0] = 0xf9
        writer.push(ui8a.slice(0, 3))
        success = true
      } else {
        encodeFloat32(float)
        decoded = readFloat32(ui8a, 1)
        if (float === decoded) {
          ui8a[0] = 0xfa
          writer.push(ui8a.slice(0, 5))
          success = true
        }
      }
    }
    if (!success) {
      encodeFloat64(float)
      decoded = readFloat64(ui8a, 1)
      ui8a[0] = 0xfb
      writer.push(ui8a.slice(0, 9))
    }
  }
}

/**
 * @param {Token} token
 * @param {EncodeOptions} options
 * @returns {number}
 */
encodeFloat.encodedSize = function encodedSize (token, options) {
  const float = token.value

  if (float === false || float === true || float === null || float === undefined) {
    return 1
  }

  if (!options || options.float64 !== true) {
    encodeFloat16(float)
    let decoded = readFloat16(ui8a, 1)
    if (float === decoded || Number.isNaN(float)) {
      return 3
    }
    encodeFloat32(float)
    decoded = readFloat32(ui8a, 1)
    if (float === decoded) {
      return 5
    }
  }
  return 9
}

const buffer = new ArrayBuffer(9)
const dataView = new DataView(buffer, 1)
const ui8a = new Uint8Array(buffer, 0)

/**
 * @param {number} inp
 */
function encodeFloat16 (inp) {
  if (inp === Infinity) {
    dataView.setUint16(0, 0x7c00, false)
  } else if (inp === -Infinity) {
    dataView.setUint16(0, 0xfc00, false)
  } else if (Number.isNaN(inp)) {
    dataView.setUint16(0, 0x7e00, false)
  } else {
    dataView.setFloat32(0, inp)
    const valu32 = dataView.getUint32(0)
    const exponent = (valu32 & 0x7f800000) >> 23
    const mantissa = valu32 & 0x7fffff

    if (exponent === 0xff) {
      // too big, Infinity, but this should be hard (impossible?) to trigger
      dataView.setUint16(0, 0x7c00, false)
    } else if (exponent === 0x00) {
      // 0.0, -0.0 and subnormals, shouldn't be possible to get here because 0.0 should be counted as an int
      // Use valu32 for sign bit since bitwise ops on floats lose -0 sign
      dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | (mantissa >> 13), false)
    } else { // standard numbers
      // chunks of logic here borrowed from https://github.com/PJK/libcbor/blob/c78f437182533e3efa8d963ff4b945bb635c2284/src/cbor/encoding.c#L127
      const logicalExponent = exponent - 127
      // Now we know that 2^exponent <= 0 logically
      if (logicalExponent < -24) {
        /* No unambiguous representation exists, this float is not a half float
          and is too small to be represented using a half, round off to zero.
          Consistent with the reference implementation. */
        // should be difficult (impossible?) to get here in JS
        dataView.setUint16(0, 0)
      } else if (logicalExponent < -14) {
        /* Offset the remaining decimal places by shifting the significand, the
          value is lost. This is an implementation decision that works around the
          absence of standard half-float in the language. */
        dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | /* sign bit */ (1 << (24 + logicalExponent)), false)
      } else {
        dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | ((logicalExponent + 15) << 10) | (mantissa >> 13), false)
      }
    }
  }
}

/**
 * @param {Uint8Array} ui8a
 * @param {number} pos
 * @returns {number}
 */
function readFloat16 (ui8a, pos) {
  if (ui8a.length - pos < 2) {
    throw new Error(`${decodeErrPrefix} not enough data for float16`)
  }

  const half = (ui8a[pos] << 8) + ui8a[pos + 1]
  if (half === 0x7c00) {
    return Infinity
  }
  if (half === 0xfc00) {
    return -Infinity
  }
  if (half === 0x7e00) {
    return NaN
  }
  const exp = (half >> 10) & 0x1f
  const mant = half & 0x3ff
  let val
  if (exp === 0) {
    val = mant * (2 ** -24)
  } else if (exp !== 31) {
    val = (mant + 1024) * (2 ** (exp - 25))
  } else {
    // may not be possible to get here
    val = mant === 0 ? Infinity : NaN
  }
  return (half & 0x8000) ? -val : val
}

/**
 * @param {number} inp
 */
function encodeFloat32 (inp) {
  dataView.setFloat32(0, inp, false)
}

/**
 * @param {Uint8Array} ui8a
 * @param {number} pos
 * @returns {number}
 */
function readFloat32 (ui8a, pos) {
  if (ui8a.length - pos < 4) {
    throw new Error(`${decodeErrPrefix} not enough data for float32`)
  }
  const offset = (ui8a.byteOffset || 0) + pos
  return new DataView(ui8a.buffer, offset, 4).getFloat32(0, false)
}

/**
 * @param {number} inp
 */
function encodeFloat64 (inp) {
  dataView.setFloat64(0, inp, false)
}

/**
 * @param {Uint8Array} ui8a
 * @param {number} pos
 * @returns {number}
 */
function readFloat64 (ui8a, pos) {
  if (ui8a.length - pos < 8) {
    throw new Error(`${decodeErrPrefix} not enough data for float64`)
  }
  const offset = (ui8a.byteOffset || 0) + pos
  return new DataView(ui8a.buffer, offset, 8).getFloat64(0, false)
}

/**
 * @param {Token} _tok1
 * @param {Token} _tok2
 * @returns {number}
 */
encodeFloat.compareTokens = encodeUint.compareTokens
/*
encodeFloat.compareTokens = function compareTokens (_tok1, _tok2) {
  return _tok1
  throw new Error(`${encodeErrPrefix} cannot use floats as map keys`)
}
*/
/**
 * Bl is a list of byte chunks, similar to https://github.com/rvagg/bl but for
 * writing rather than reading.
 * A Bl object accepts set() operations for individual bytes and copyTo() for
 * inserting byte arrays. These write operations don't automatically increment
 * the internal cursor so its "length" won't be changed. Instead, increment()
 * must be called to extend its length to cover the inserted data.
 * The toBytes() call will convert all internal memory to a single Uint8Array of
 * the correct length, truncating any data that is stored but hasn't been
 * included by an increment().
 * get() can retrieve a single byte.
 * All operations (except toBytes()) take an "offset" argument that will perform
 * the write at the offset _from the current cursor_. For most operations this
 * will be `0` to write at the current cursor position but it can be ahead of
 * the current cursor. Negative offsets probably work but are untested.
 */

// TODO: ipjs doesn't support this, only for test files: https://github.com/mikeal/ipjs/blob/master/src/package/testFile.js#L39
import { alloc, concat, slice } from './byte-utils.js'

/**
 * @typedef {import('../interface.js').ByteView} ByteView
 * @typedef {import('../interface.js').AllocatedByteView} AllocatedByteView
 */

// the ts-ignores in this file are almost all for the `Uint8Array|number[]` duality that exists
// for perf reasons. Consider better approaches to this or removing it entirely, it is quite
// risky because of some assumptions about small chunks === number[] and everything else === Uint8Array.

const defaultChunkSize = 256

export class Bl {
  /**
   * @param {number} [chunkSize]
   */
  constructor (chunkSize = defaultChunkSize) {
    this.chunkSize = chunkSize
    /** @type {number} */
    this.cursor = 0
    /** @type {number} */
    this.maxCursor = -1
    /** @type {(ByteView|number[])[]} */
    this.chunks = []
    // keep the first chunk around if we can to save allocations for future encodes
    /** @type {ByteView|number[]|null} */
    this._initReuseChunk = null
  }

  reset () {
    this.cursor = 0
    this.maxCursor = -1
    if (this.chunks.length) {
      this.chunks = []
    }
    if (this._initReuseChunk !== null) {
      this.chunks.push(this._initReuseChunk)
      this.maxCursor = this._initReuseChunk.length - 1
    }
  }

  /**
   * @param {ByteView|number[]} bytes
   */
  push (bytes) {
    let topChunk = this.chunks[this.chunks.length - 1]
    const newMax = this.cursor + bytes.length
    if (newMax <= this.maxCursor + 1) {
      // we have at least one chunk and we can fit these bytes into that chunk
      const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1
      // @ts-ignore
      topChunk.set(bytes, chunkPos)
    } else {
      // can't fit it in
      if (topChunk) {
        // trip the last chunk to `cursor` if we need to
        const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1
        if (chunkPos < topChunk.length) {
          // @ts-ignore
          this.chunks[this.chunks.length - 1] = topChunk.subarray(0, chunkPos)
          this.maxCursor = this.cursor - 1
        }
      }
      if (bytes.length < 64 && bytes.length < this.chunkSize) {
        // make a new chunk and copy the new one into it
        topChunk = alloc(this.chunkSize)
        this.chunks.push(topChunk)
        this.maxCursor += topChunk.length
        if (this._initReuseChunk === null) {
          this._initReuseChunk = topChunk
        }
        // @ts-ignore
        topChunk.set(bytes, 0)
      } else {
        // push the new bytes in as its own chunk
        this.chunks.push(bytes)
        this.maxCursor += bytes.length
      }
    }
    this.cursor += bytes.length
  }

  /**
   * @param {boolean} [reset]
   * @returns {AllocatedByteView}
   */
  toBytes (reset = false) {
    let byts
    if (this.chunks.length === 1) {
      const chunk = this.chunks[0]
      if (reset && this.cursor > chunk.length / 2) {
        // @ts-ignore
        byts = this.cursor === chunk.length ? chunk : chunk.subarray(0, this.cursor)
        this._initReuseChunk = null
        this.chunks = []
      } else {
        // @ts-ignore
        byts = slice(chunk, 0, this.cursor)
      }
    } else {
      // @ts-ignore
      byts = concat(this.chunks, this.cursor)
    }
    if (reset) {
      this.reset()
    }
    return byts
  }
}

/**
 * U8Bl is a buffer list that writes directly to a user-provided Uint8Array.
 * It provides the same interface as Bl but writes to a fixed destination.
 * @template {ArrayBufferLike} T
 */
export class U8Bl {
  /**
   * @param {Uint8Array<T>} dest
   */
  constructor (dest) {
    this.dest = dest
    /** @type {number} */
    this.cursor = 0
    // chunks is for interface compatibility with Bl - encode.js checks chunks.length
    // as a sanity check for pre-calculated sizes. For U8Bl this is always [dest].
    /** @type {Array<Uint8Array<T>>} */
    this.chunks = [dest]
  }

  reset () {
    this.cursor = 0
  }

  /**
   * @param {ByteView|number[]} bytes
   */
  push (bytes) {
    if (this.cursor + bytes.length > this.dest.length) {
      throw new Error('write out of bounds, destination buffer is too small')
    }
    this.dest.set(bytes, this.cursor)
    this.cursor += bytes.length
  }

  /**
   * @param {boolean} [reset]
   * @returns {Uint8Array<T>}
   */
  toBytes (reset = false) {
    const byts = this.dest.subarray(0, this.cursor)
    if (reset) {
      this.reset()
    }
    return byts
  }
}
// Use Uint8Array directly in the browser, use Buffer in Node.js but don't
// speak its name directly to avoid bundlers pulling in the `Buffer` polyfill

// @ts-ignore
export const useBuffer = globalThis.process &&
  // @ts-ignore
  !globalThis.process.browser &&
  // @ts-ignore
  globalThis.Buffer &&
  // @ts-ignore
  typeof globalThis.Buffer.isBuffer === 'function'

const textEncoder = new TextEncoder()

/**
 * @typedef {import('../interface.js').ByteView} ByteView
 * @typedef {import('../interface.js').AllocatedByteView} AllocatedByteView
 */

/**
 * @param {Uint8Array} buf
 * @returns {boolean}
 */
function isBuffer (buf) {
  // @ts-ignore
  return useBuffer && globalThis.Buffer.isBuffer(buf)
}

/**
 * @param {ByteView|number[]} buf
 * @returns {ByteView}
 */
export function asU8A (buf) {
  if (!(buf instanceof Uint8Array)) {
    return Uint8Array.from(buf)
  }
  return isBuffer(buf) ? new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength) : buf
}

// Threshold for manual UTF-8 encoding vs native methods.
// Node.js Buffer.from: crossover ~24 chars
// Browser TextEncoder: crossover ~200 chars
const FROM_STRING_THRESHOLD_BUFFER = 24
const FROM_STRING_THRESHOLD_TEXTENCODER = 200

export const fromString = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {string} string
     */
    (string) => {
      return string.length >= FROM_STRING_THRESHOLD_BUFFER
        ? // eslint-disable-line operator-linebreak
      // @ts-ignore
        globalThis.Buffer.from(string)
        : utf8ToBytes(string)
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {string} string
     */
    (string) => {
      return string.length >= FROM_STRING_THRESHOLD_TEXTENCODER ? textEncoder.encode(string) : utf8ToBytes(string)
    }

/**
 * Buffer variant not fast enough for what we need
 * @param {number[]} arr
 * @returns {AllocatedByteView}
 */
export const fromArray = (arr) => {
  return Uint8Array.from(arr)
}

export const slice = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} bytes
     * @param {number} start
     * @param {number} end
     */
    // Buffer.slice() returns a view, not a copy, so we need special handling
    (bytes, start, end) => {
      if (isBuffer(bytes)) {
        return new Uint8Array(bytes.subarray(start, end))
      }
      return bytes.slice(start, end)
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} bytes
     * @param {number} start
     * @param {number} end
     */
    (bytes, start, end) => {
      return bytes.slice(start, end)
    }

export const concat = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {ByteView[]} chunks
     * @param {number} length
     * @returns {AllocatedByteView}
     */
    (chunks, length) => {
      // might get a stray plain Array here
      chunks = chunks.map((c) => c instanceof Uint8Array
        ? c
        : // eslint-disable-line operator-linebreak
        // @ts-ignore
        globalThis.Buffer.from(c))
      // @ts-ignore
      return /** @type {AllocatedByteView} */ (asU8A(globalThis.Buffer.concat(chunks, length)))
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {ByteView[]} chunks
     * @param {number} length
     * @returns {AllocatedByteView}
     */
    (chunks, length) => {
      const out = new Uint8Array(length)
      let off = 0
      for (let b of chunks) {
        if (off + b.length > out.length) {
          // final chunk that's bigger than we need
          b = b.subarray(0, out.length - off)
        }
        out.set(b, off)
        off += b.length
      }
      return out
    }

export const alloc = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {number} size
     * @returns {AllocatedByteView}
     */
    (size) => {
      // we always write over the contents we expose so this should be safe
      // @ts-ignore
      return globalThis.Buffer.allocUnsafe(size)
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {number} size
     * @returns {AllocatedByteView}
     */
    (size) => {
      return new Uint8Array(size)
    }

export const toHex = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} d
     * @returns {string}
     */
    (d) => {
      if (typeof d === 'string') {
        return d
      }
      // @ts-ignore
      return globalThis.Buffer.from(toBytes(d)).toString('hex')
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} d
     * @returns {string}
     */
    (d) => {
      if (typeof d === 'string') {
        return d
      }
      // @ts-ignore not smart enough to figure this out
      return Array.prototype.reduce.call(toBytes(d), (p, c) => `${p}${c.toString(16).padStart(2, '0')}`, '')
    }

export const fromHex = useBuffer
  ? // eslint-disable-line operator-linebreak
  /**
   * @param {string|ByteView} hex
   * @returns {ByteView}
   */
    (hex) => {
      if (hex instanceof Uint8Array) {
        return hex
      }
      // @ts-ignore
      return globalThis.Buffer.from(hex, 'hex')
    }
  : // eslint-disable-line operator-linebreak
  /**
   * @param {string|ByteView} hex
   * @returns {ByteView}
   */
    (hex) => {
      if (hex instanceof Uint8Array) {
        return hex
      }
      if (!hex.length) {
        return new Uint8Array(0)
      }
      return new Uint8Array(hex.split('')
        .map((/** @type {string} */ c, /** @type {number} */ i, /** @type {string[]} */ d) => i % 2 === 0 ? `0x${c}${d[i + 1]}` : '')
        .filter(Boolean)
        .map((/** @type {string} */ e) => parseInt(e, 16)))
    }

/**
 * @param {Uint8Array|ArrayBuffer|ArrayBufferView} obj
 * @returns {Uint8Array}
 */
function toBytes (obj) {
  if (obj instanceof Uint8Array && obj.constructor.name === 'Uint8Array') {
    return obj
  }
  if (obj instanceof ArrayBuffer) {
    return new Uint8Array(obj)
  }
  if (ArrayBuffer.isView(obj)) {
    return new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength)
  }
  throw new Error('Unknown type, must be binary type')
}

/**
 * @param {Uint8Array} b1
 * @param {Uint8Array} b2
 * @returns {number}
 */
export function compare (b1, b2) {
  if (isBuffer(b1) && isBuffer(b2)) {
    // probably not possible to get here in the current API
    // @ts-ignore Buffer
    return b1.compare(b2)
  }
  for (let i = 0; i < b1.length; i++) {
    if (b1[i] === b2[i]) {
      continue
    }
    return b1[i] < b2[i] ? -1 : 1
  }
  return 0
}

// The below code is taken from https://github.com/google/closure-library/blob/8598d87242af59aac233270742c8984e2b2bdbe0/closure/goog/crypt/crypt.js#L117-L143
// Licensed Apache-2.0.

/**
 * @param {string} str
 * @returns {number[]}
 */
function utf8ToBytes (str) {
  const out = []
  let p = 0
  for (let i = 0; i < str.length; i++) {
    let c = str.charCodeAt(i)
    if (c < 128) {
      out[p++] = c
    } else if (c < 2048) {
      out[p++] = (c >> 6) | 192
      out[p++] = (c & 63) | 128
    } else if (
      ((c & 0xFC00) === 0xD800) && (i + 1) < str.length &&
      ((str.charCodeAt(i + 1) & 0xFC00) === 0xDC00)) {
      // Surrogate Pair
      c = 0x10000 + ((c & 0x03FF) << 10) + (str.charCodeAt(++i) & 0x03FF)
      out[p++] = (c >> 18) | 240
      out[p++] = ((c >> 12) & 63) | 128
      out[p++] = ((c >> 6) & 63) | 128
      out[p++] = (c & 63) | 128
    } else {
      if ((c >= 0xD800) && (c <= 0xDFFF)) {
        c = 0xFFFD // Unpaired Surrogate
      }
      out[p++] = (c >> 12) | 224
      out[p++] = ((c >> 6) & 63) | 128
      out[p++] = (c & 63) | 128
    }
  }
  return out
}

// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
const MAX_ARGUMENTS_LENGTH = 0x1000

/**
 * @param {number[]} codePoints
 * @returns {string}
 */
export function decodeCodePointsArray (codePoints) {
  const len = codePoints.length
  if (len <= MAX_ARGUMENTS_LENGTH) {
    return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  }
  // Decode in chunks to avoid "call stack size exceeded".
  let res = ''
  let i = 0
  while (i < len) {
    res += String.fromCharCode.apply(
      String,
      codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
    )
  }
  return res
}
const decodeErrPrefix = 'CBOR decode error:'
const encodeErrPrefix = 'CBOR encode error:'

const uintMinorPrefixBytes = []
uintMinorPrefixBytes[23] = 1
uintMinorPrefixBytes[24] = 2
uintMinorPrefixBytes[25] = 3
uintMinorPrefixBytes[26] = 5
uintMinorPrefixBytes[27] = 9

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} need
 */
function assertEnoughData (data, pos, need) {
  if (data.length - pos < need) {
    throw new Error(`${decodeErrPrefix} not enough data for type`)
  }
}

export {
  decodeErrPrefix,
  encodeErrPrefix,
  uintMinorPrefixBytes,
  assertEnoughData
}
import { decodeErrPrefix } from './common.js'
import { Type } from './token.js'
import { jump, quick } from './jump.js'
import { asU8A } from './byte-utils.js'

/**
 * @typedef {import('./token.js').Token} Token
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 * @typedef {import('../interface.js').DecodeTokenizer} DecodeTokenizer
 * @typedef {import('../interface.js').TagDecodeControl} TagDecodeControl
 */

const defaultDecodeOptions = {
  strict: false,
  allowIndefinite: true,
  allowUndefined: true,
  allowBigInt: true
}

/**
 * @implements {DecodeTokenizer}
 */
class Tokeniser {
  /**
   * @param {Uint8Array} data
   * @param {DecodeOptions} options
   */
  constructor (data, options = {}) {
    this._pos = 0
    this.data = data
    this.options = options
  }

  pos () {
    return this._pos
  }

  done () {
    return this._pos >= this.data.length
  }

  next () {
    const byt = this.data[this._pos]
    let token = quick[byt]
    if (token === undefined) {
      const decoder = jump[byt]
      // if we're here then there's something wrong with our jump or quick lists!
      if (!decoder) {
        throw new Error(`${decodeErrPrefix} no decoder for major type ${byt >>> 5} (byte 0x${byt.toString(16).padStart(2, '0')})`)
      }
      const minor = byt & 31
      token = decoder(this.data, this._pos, minor, this.options)
    }
    // @ts-ignore we get to assume encodedLength is set (crossing fingers slightly)
    this._pos += token.encodedLength
    return token
  }
}

const DONE = Symbol.for('DONE')
const BREAK = Symbol.for('BREAK')

/**
 * @param {Token} token
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {any|BREAK|DONE}
 */
function tokenToArray (token, tokeniser, options) {
  const arr = []
  for (let i = 0; i < token.value; i++) {
    const value = tokensToObject(tokeniser, options)
    if (value === BREAK) {
      if (token.value === Infinity) {
        // normal end to indefinite length array
        break
      }
      throw new Error(`${decodeErrPrefix} got unexpected break to lengthed array`)
    }
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} found array but not enough entries (got ${i}, expected ${token.value})`)
    }
    arr[i] = value
  }
  return arr
}

/**
 * @param {Token} token
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {any|BREAK|DONE}
 */
function tokenToMap (token, tokeniser, options) {
  const useMaps = options.useMaps === true
  const rejectDuplicateMapKeys = options.rejectDuplicateMapKeys === true
  const obj = useMaps ? undefined : {}
  const m = useMaps ? new Map() : undefined
  for (let i = 0; i < token.value; i++) {
    const key = tokensToObject(tokeniser, options)
    if (key === BREAK) {
      if (token.value === Infinity) {
        // normal end to indefinite length map
        break
      }
      throw new Error(`${decodeErrPrefix} got unexpected break to lengthed map`)
    }
    if (key === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no key], expected ${token.value})`)
    }
    if (!useMaps && typeof key !== 'string') {
      throw new Error(`${decodeErrPrefix} non-string keys not supported (got ${typeof key})`)
    }
    if (rejectDuplicateMapKeys) {
      // @ts-ignore
      if ((useMaps && m.has(key)) || (!useMaps && Object.hasOwn(obj, key))) {
        throw new Error(`${decodeErrPrefix} found repeat map key "${key}"`)
      }
    }
    const value = tokensToObject(tokeniser, options)
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no value], expected ${token.value})`)
    }
    if (useMaps) {
      // @ts-ignore TODO reconsider this .. maybe needs to be strict about key types
      m.set(key, value)
    } else {
      // @ts-ignore TODO reconsider this .. maybe needs to be strict about key types
      obj[key] = value
    }
  }
  // @ts-ignore c'mon man
  return useMaps ? m : obj
}

/**
 * Generator that yields [key, value] entries from a CBOR map token.
 * Used by tag decoders that need to preserve key types (e.g., Tag 259 Map).
 * @param {Token} token - The map token
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {Generator<[any, any], void, unknown>}
 */
function * tokenToMapEntries (token, tokeniser, options) {
  for (let i = 0; i < token.value; i++) {
    const key = tokensToObject(tokeniser, options)
    if (key === BREAK) {
      if (token.value === Infinity) {
        // normal end to indefinite length map
        break
      }
      throw new Error(`${decodeErrPrefix} got unexpected break to lengthed map`)
    }
    if (key === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no key], expected ${token.value})`)
    }
    const value = tokensToObject(tokeniser, options)
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no value], expected ${token.value})`)
    }
    yield [key, value]
  }
}

/**
 * Creates a TagDecodeControl object for tag decoders.
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {TagDecodeControl}
 */
function createTagDecodeControl (tokeniser, options) {
  let called = false

  /**
   * @type {TagDecodeControl}
   */
  const decode = function () {
    if (called) {
      throw new Error(`${decodeErrPrefix} tag decode() may only be called once`)
    }
    called = true
    const value = tokensToObject(tokeniser, options)
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} tag content missing`)
    }
    if (value === BREAK) {
      throw new Error(`${decodeErrPrefix} got unexpected break in tag content`)
    }
    return value
  }

  decode.entries = function () {
    if (called) {
      throw new Error(`${decodeErrPrefix} tag decode() may only be called once`)
    }
    called = true

    // Get the next token and ensure it's a map
    const token = tokeniser.next()
    if (!Type.equals(token.type, Type.map)) {
      throw new Error(`${decodeErrPrefix} entries() requires map content, got ${token.type.name}`)
    }

    // Collect all entries into an array (ensures full content consumption)
    const entries = []
    for (const entry of tokenToMapEntries(token, tokeniser, options)) {
      entries.push(entry)
    }
    return entries
  }

  // For internal tracking
  Object.defineProperty(decode, '_called', {
    get () { return called },
    enumerable: false
  })

  return decode
}

/**
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {any|BREAK|DONE}
 */
function tokensToObject (tokeniser, options) {
  // should we support array as an argument?
  // check for tokenIter[Symbol.iterator] and replace tokenIter with what that returns?
  if (tokeniser.done()) {
    return DONE
  }

  const token = tokeniser.next()

  if (Type.equals(token.type, Type.break)) {
    return BREAK
  }

  if (token.type.terminal) {
    return token.value
  }

  if (Type.equals(token.type, Type.array)) {
    return tokenToArray(token, tokeniser, options)
  }

  if (Type.equals(token.type, Type.map)) {
    return tokenToMap(token, tokeniser, options)
  }

  if (Type.equals(token.type, Type.tag)) {
    if (options.tags && typeof options.tags[token.value] === 'function') {
      const decodeControl = createTagDecodeControl(tokeniser, options)
      const result = options.tags[token.value](decodeControl)
      if (!decodeControl._called) {
        throw new Error(`${decodeErrPrefix} tag decoder must call decode() or entries()`)
      }
      return result
    }
    throw new Error(`${decodeErrPrefix} tag not supported (${token.value})`)
  }
  throw new Error('unsupported')
}

/**
 * @param {Uint8Array} data
 * @param {DecodeOptions} [options]
 * @returns {[any, Uint8Array]}
 */
function decodeFirst (data, options) {
  if (!(data instanceof Uint8Array)) {
    throw new Error(`${decodeErrPrefix} data to decode must be a Uint8Array`)
  }
  options = Object.assign({}, defaultDecodeOptions, options)
  // Convert Buffer to plain Uint8Array for faster slicing in decode path
  const u8aData = asU8A(data)
  const tokeniser = options.tokenizer || new Tokeniser(u8aData, options)
  const decoded = tokensToObject(tokeniser, options)
  if (decoded === DONE) {
    throw new Error(`${decodeErrPrefix} did not find any content to decode`)
  }
  if (decoded === BREAK) {
    throw new Error(`${decodeErrPrefix} got unexpected break`)
  }
  return [decoded, data.subarray(tokeniser.pos())]
}

/**
 * @param {Uint8Array} data
 * @param {DecodeOptions} [options]
 * @returns {any}
 */
function decode (data, options) {
  const [decoded, remainder] = decodeFirst(data, options)
  if (remainder.length > 0) {
    throw new Error(`${decodeErrPrefix} too many terminals, data makes no sense`)
  }
  return decoded
}

export { Tokeniser, tokensToObject, decode, decodeFirst }
import { is } from './is.js'
import { Token, Type } from './token.js'
import { Bl, U8Bl } from './bl.js'
import { encodeErrPrefix } from './common.js'
import { quickEncodeToken } from './jump.js'
import { asU8A, compare, fromString } from './byte-utils.js'

import { encodeUint, encodeUintValue } from './0uint.js'
import { encodeNegint } from './1negint.js'
import { encodeBytes } from './2bytes.js'
import { encodeString } from './3string.js'
import { encodeArray } from './4array.js'
import { encodeMap } from './5map.js'
import { encodeTag } from './6tag.js'
import { encodeFloat, MINOR_FALSE, MINOR_TRUE, MINOR_NULL, MINOR_UNDEFINED } from './7float.js'

/**
 * @typedef {import('../interface.js').EncodeOptions} EncodeOptions
 * @typedef {import('../interface.js').OptionalTypeEncoder} OptionalTypeEncoder
 * @typedef {import('../interface.js').Reference} Reference
 * @typedef {import('../interface.js').StrictTypeEncoder} StrictTypeEncoder
 * @typedef {import('../interface.js').TokenTypeEncoder} TokenTypeEncoder
 * @typedef {import('../interface.js').TokenOrNestedTokens} TokenOrNestedTokens
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').ByteView} ByteView
 * @typedef {import('../interface.js').AllocatedByteView} AllocatedByteView
 */

/** @type {EncodeOptions} */
const defaultEncodeOptions = {
  float64: false,
  mapSorter,
  quickEncodeToken
}

/** @type {EncodeOptions} */
export const rfc8949EncodeOptions = Object.freeze({
  mapSorter: rfc8949MapSorter,
  quickEncodeToken
})

/** @returns {TokenTypeEncoder[]} */
export function makeCborEncoders () {
  const encoders = []
  encoders[Type.uint.major] = encodeUint
  encoders[Type.negint.major] = encodeNegint
  encoders[Type.bytes.major] = encodeBytes
  encoders[Type.string.major] = encodeString
  encoders[Type.array.major] = encodeArray
  encoders[Type.map.major] = encodeMap
  encoders[Type.tag.major] = encodeTag
  encoders[Type.float.major] = encodeFloat
  return encoders
}

const cborEncoders = makeCborEncoders()

const defaultWriter = new Bl()

/** @implements {Reference} */
class Ref {
  /**
   * @param {object|any[]} obj
   * @param {Reference|undefined} parent
   */
  constructor (obj, parent) {
    this.obj = obj
    this.parent = parent
  }

  /**
   * @param {object|any[]} obj
   * @returns {boolean}
   */
  includes (obj) {
    /** @type {Reference|undefined} */
    let p = this
    do {
      if (p.obj === obj) {
        return true
      }
    } while (p = p.parent) // eslint-disable-line
    return false
  }

  /**
   * @param {Reference|undefined} stack
   * @param {object|any[]} obj
   * @returns {Reference}
   */
  static createCheck (stack, obj) {
    if (stack && stack.includes(obj)) {
      throw new Error(`${encodeErrPrefix} object contains circular references`)
    }
    return new Ref(obj, stack)
  }
}

const simpleTokens = {
  null: new Token(Type.null, null),
  undefined: new Token(Type.undefined, undefined),
  true: new Token(Type.true, true),
  false: new Token(Type.false, false),
  emptyArray: new Token(Type.array, 0),
  emptyMap: new Token(Type.map, 0)
}

/** @type {{[typeName: string]: StrictTypeEncoder}} */
const typeEncoders = {
  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  number (obj, _typ, _options, _refStack) {
    if (!Number.isInteger(obj) || !Number.isSafeInteger(obj)) {
      return new Token(Type.float, obj)
    } else if (obj >= 0) {
      return new Token(Type.uint, obj)
    } else {
      return new Token(Type.negint, obj)
    }
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  bigint (obj, _typ, _options, _refStack) {
    if (obj >= BigInt(0)) {
      return new Token(Type.uint, obj)
    } else {
      return new Token(Type.negint, obj)
    }
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  Uint8Array (obj, _typ, _options, _refStack) {
    return new Token(Type.bytes, obj)
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  string (obj, _typ, _options, _refStack) {
    return new Token(Type.string, obj)
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  boolean (obj, _typ, _options, _refStack) {
    return obj ? simpleTokens.true : simpleTokens.false
  },

  /**
   * @param {any} _obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  null (_obj, _typ, _options, _refStack) {
    return simpleTokens.null
  },

  /**
   * @param {any} _obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  undefined (_obj, _typ, _options, _refStack) {
    return simpleTokens.undefined
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  ArrayBuffer (obj, _typ, _options, _refStack) {
    return new Token(Type.bytes, new Uint8Array(obj))
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  DataView (obj, _typ, _options, _refStack) {
    return new Token(Type.bytes, new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength))
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} options
   * @param {Reference} [refStack]
   * @returns {TokenOrNestedTokens}
   */
  Array (obj, _typ, options, refStack) {
    if (!obj.length) {
      if (options.addBreakTokens === true) {
        return [simpleTokens.emptyArray, new Token(Type.break)]
      }
      return simpleTokens.emptyArray
    }
    refStack = Ref.createCheck(refStack, obj)
    const entries = []
    let i = 0
    for (const e of obj) {
      entries[i++] = objectToTokens(e, options, refStack)
    }
    if (options.addBreakTokens) {
      return [new Token(Type.array, obj.length), entries, new Token(Type.break)]
    }
    return [new Token(Type.array, obj.length), entries]
  },

  /**
   * @param {any} obj
   * @param {string} typ
   * @param {EncodeOptions} options
   * @param {Reference} [refStack]
   * @returns {TokenOrNestedTokens}
   */
  Object (obj, typ, options, refStack) {
    // could be an Object or a Map
    const isMap = typ !== 'Object'
    // it's slightly quicker to use Object.keys() than Object.entries()
    const keys = isMap ? obj.keys() : Object.keys(obj)
    const maxLength = isMap ? obj.size : keys.length

    /** @type {undefined | [TokenOrNestedTokens, TokenOrNestedTokens][]} */
    let entries

    if (maxLength) {
      // Pre-allocate the array with the expected size
      entries = new Array(maxLength)
      refStack = Ref.createCheck(refStack, obj)
      const skipUndefined = !isMap && options.ignoreUndefinedProperties

      let i = 0
      for (const key of keys) {
        const value = isMap ? obj.get(key) : obj[key]
        if (skipUndefined && value === undefined) {
          continue
        }
        entries[i++] = [
          objectToTokens(key, options, refStack),
          objectToTokens(value, options, refStack)
        ]
      }

      // Truncate only if properties were skipped
      if (i < maxLength) {
        entries.length = i
      }
    }

    if (!entries?.length) {
      if (options.addBreakTokens === true) {
        return [simpleTokens.emptyMap, new Token(Type.break)]
      }
      return simpleTokens.emptyMap
    }

    sortMapEntries(entries, options)
    if (options.addBreakTokens) {
      return [new Token(Type.map, entries.length), entries, new Token(Type.break)]
    }
    return [new Token(Type.map, entries.length), entries]
  },

  /**
   * Encode a `Tagged` wrapper as a CBOR tag header followed by the encoded
   * form of the wrapped value. The value is recursively tokenised through
   * `objectToTokens()` so any registered `typeEncoders` apply to it.
   *
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} options
   * @param {Reference} [refStack]
   * @returns {TokenOrNestedTokens}
   */
  Tagged (obj, _typ, options, refStack) {
    return [
      new Token(Type.tag, obj.tag),
      objectToTokens(obj.value, options, refStack)
    ]
  }
}

typeEncoders.Map = typeEncoders.Object
typeEncoders.Buffer = typeEncoders.Uint8Array
for (const typ of 'Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64'.split(' ')) {
  typeEncoders[`${typ}Array`] = typeEncoders.DataView
}

/**
 * @param {any} obj
 * @param {EncodeOptions} [options]
 * @param {Reference} [refStack]
 * @returns {TokenOrNestedTokens}
 */
function objectToTokens (obj, options = {}, refStack) {
  const typ = is(obj)
  const customTypeEncoder = (options && options.typeEncoders && /** @type {OptionalTypeEncoder} */ options.typeEncoders[typ]) || typeEncoders[typ]
  if (typeof customTypeEncoder === 'function') {
    const tokens = customTypeEncoder(obj, typ, options, refStack)
    if (tokens != null) {
      return tokens
    }
  }
  const typeEncoder = typeEncoders[typ]
  if (!typeEncoder) {
    throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`)
  }
  return typeEncoder(obj, typ, options, refStack)
}

/*
CBOR key sorting is a mess.

The canonicalisation recommendation from https://tools.ietf.org/html/rfc7049#section-3.9
includes the wording:

> The keys in every map must be sorted lowest value to highest.
> Sorting is performed on the bytes of the representation of the key
> data items without paying attention to the 3/5 bit splitting for
> major types.
> ...
>  *  If two keys have different lengths, the shorter one sorts
      earlier;
>  *  If two keys have the same length, the one with the lower value
      in (byte-wise) lexical order sorts earlier.

1. It is not clear what "bytes of the representation of the key" means: is it
   the CBOR representation, or the binary representation of the object itself?
   Consider the int and uint difference here.
2. It is not clear what "without paying attention to" means: do we include it
   and compare on that? Or do we omit the special prefix byte, (mostly) treating
   the key in its plain binary representation form.

The FIDO 2.0: Client To Authenticator Protocol spec takes the original CBOR
wording and clarifies it according to their understanding.
https://fidoalliance.org/specs/fido-v2.0-rd-20170927/fido-client-to-authenticator-protocol-v2.0-rd-20170927.html#message-encoding

> The keys in every map must be sorted lowest value to highest. Sorting is
> performed on the bytes of the representation of the key data items without
> paying attention to the 3/5 bit splitting for major types. The sorting rules
> are:
>  * If the major types are different, the one with the lower value in numerical
>    order sorts earlier.
>  * If two keys have different lengths, the shorter one sorts earlier;
>  * If two keys have the same length, the one with the lower value in
>    (byte-wise) lexical order sorts earlier.

Some other implementations, such as borc, do a full encode then do a
length-first, byte-wise-second comparison:
https://github.com/dignifiedquire/borc/blob/b6bae8b0bcde7c3976b0f0f0957208095c392a36/src/encoder.js#L358
https://github.com/dignifiedquire/borc/blob/b6bae8b0bcde7c3976b0f0f0957208095c392a36/src/utils.js#L143-L151

This has the benefit of being able to easily handle arbitrary keys, including
complex types (maps and arrays).

We'll opt for the FIDO approach, since it affords some efficies since we don't
need a full encode of each key to determine order and can defer to the types
to determine how to most efficiently order their values (i.e. int and uint
ordering can be done on the numbers, no need for byte-wise, for example).

Recommendation: stick to single key types or you'll get into trouble, and prefer
string keys because it's much simpler that way.
*/

/**
 * @param {TokenOrNestedTokens[]} entries
 * @param {EncodeOptions} options
 */
function sortMapEntries (entries, options) {
  if (options.mapSorter) {
    entries.sort(options.mapSorter)
  }
}

/**
 * @param {(Token|Token[])[]} e1
 * @param {(Token|Token[])[]} e2
 * @returns {number}
 */
function mapSorter (e1, e2) {
  // the key position ([0]) could have a single token or an array
  // almost always it'll be a single token but complex key might get involved
  const keyToken1 = Array.isArray(e1[0]) ? e1[0][0] : e1[0]
  const keyToken2 = Array.isArray(e2[0]) ? e2[0][0] : e2[0]

  // different key types
  if (keyToken1.type !== keyToken2.type) {
    return keyToken1.type.compare(keyToken2.type)
  }

  const major = keyToken1.type.major
  // TODO: handle case where cmp === 0 but there are more keyToken e. complex type)
  const tcmp = cborEncoders[major].compareTokens(keyToken1, keyToken2)
  if (tcmp === 0) {
    // duplicate key or complex type where the first token matched,
    // i.e. a map or array and we're only comparing the opening token
    console.warn('WARNING: complex key types used, CBOR key sorting guarantees are gone')
  }
  return tcmp
}

/**
 * @typedef {Token & { _keyBytes?: AllocatedByteView }} TokenEx
 *
 * @param {(Token|Token[])[]} e1
 * @param {(Token|Token[])[]} e2
 * @returns {number}
 */
function rfc8949MapSorter (e1, e2) {
  if (e1[0] instanceof Token && e2[0] instanceof Token) {
    const t1 = /** @type {TokenEx} */ (e1[0])
    const t2 = /** @type {TokenEx} */ (e2[0])

    if (!t1._keyBytes) {
      t1._keyBytes = encodeRfc8949(t1.value)
    }

    if (!t2._keyBytes) {
      t2._keyBytes = encodeRfc8949(t2.value)
    }

    return compare(t1._keyBytes, t2._keyBytes)
  }

  throw new Error('rfc8949MapSorter: complex key types are not supported yet')
}

/**
 * @param {any} data
 * @returns {AllocatedByteView}
 */
function encodeRfc8949 (data) {
  return encodeCustom(data, cborEncoders, rfc8949EncodeOptions)
}

/**
 * @param {ByteWriter} writer
 * @param {TokenOrNestedTokens} tokens
 * @param {TokenTypeEncoder[]} encoders
 * @param {EncodeOptions} options
 */
function tokensToEncoded (writer, tokens, encoders, options) {
  if (Array.isArray(tokens)) {
    for (const token of tokens) {
      tokensToEncoded(writer, token, encoders, options)
    }
  } else {
    encoders[tokens.type.major](writer, tokens, options)
  }
}

// CBOR major type prefixes, cached from Type for hot path performance
const MAJOR_UINT = Type.uint.majorEncoded
const MAJOR_NEGINT = Type.negint.majorEncoded
const MAJOR_BYTES = Type.bytes.majorEncoded
const MAJOR_STRING = Type.string.majorEncoded
const MAJOR_ARRAY = Type.array.majorEncoded

// Simple value bytes (CBOR major type 7 + minor value)
const SIMPLE_FALSE = Type.float.majorEncoded | MINOR_FALSE
const SIMPLE_TRUE = Type.float.majorEncoded | MINOR_TRUE
const SIMPLE_NULL = Type.float.majorEncoded | MINOR_NULL
const SIMPLE_UNDEFINED = Type.float.majorEncoded | MINOR_UNDEFINED

const neg1b = BigInt(-1)
const pos1b = BigInt(1)

/**
 * Check if direct encoding can be used for the given options.
 * Direct encoding bypasses token creation for most values.
 * @param {EncodeOptions} options
 * @returns {boolean}
 */
function canDirectEncode (options) {
  // Cannot use direct encode with addBreakTokens (needs special break token handling).
  // Direct encode checks typeEncoders per-value, falling back to tokens as needed.
  // Maps fall back to token-based encoding for efficient key sorting.
  return options.addBreakTokens !== true
}

/**
 * Direct encode a value to the writer, bypassing token creation for most types.
 * Falls back to token-based encoding for custom type encoders.
 * @param {ByteWriter} writer
 * @param {any} data
 * @param {EncodeOptions} options
 * @param {Reference|undefined} refStack
 */
function directEncode (writer, data, options, refStack) {
  const typ = is(data)

  // Check for custom encoder for THIS specific type
  const customEncoder = options.typeEncoders && options.typeEncoders[typ]
  if (customEncoder) {
    const tokens = customEncoder(data, typ, options, refStack)
    if (tokens != null) {
      // Custom encoder returned tokens, serialize immediately
      tokensToEncoded(writer, tokens, cborEncoders, options)
      return
    }
    // Custom encoder returned null, fall through to default handling
  }

  // Direct encode based on type
  switch (typ) {
    case 'null':
      writer.push([SIMPLE_NULL])
      return

    case 'undefined':
      writer.push([SIMPLE_UNDEFINED])
      return

    case 'boolean':
      writer.push([data ? SIMPLE_TRUE : SIMPLE_FALSE])
      return

    case 'number':
      if (!Number.isInteger(data) || !Number.isSafeInteger(data)) {
        // Float, use token encoder for complex float encoding
        encodeFloat(writer, new Token(Type.float, data), options)
      } else if (data >= 0) {
        encodeUintValue(writer, MAJOR_UINT, data)
      } else {
        // Negative integer
        encodeUintValue(writer, MAJOR_NEGINT, data * -1 - 1)
      }
      return

    case 'bigint':
      if (data >= BigInt(0)) {
        encodeUintValue(writer, MAJOR_UINT, data)
      } else {
        encodeUintValue(writer, MAJOR_NEGINT, data * neg1b - pos1b)
      }
      return

    case 'string': {
      const bytes = fromString(data)
      encodeUintValue(writer, MAJOR_STRING, bytes.length)
      writer.push(bytes)
      return
    }

    case 'Uint8Array':
      encodeUintValue(writer, MAJOR_BYTES, data.length)
      writer.push(data)
      return

    case 'Array':
      if (!data.length) {
        writer.push([MAJOR_ARRAY]) // Empty array: 0x80
        return
      }
      refStack = Ref.createCheck(refStack, data)
      encodeUintValue(writer, MAJOR_ARRAY, data.length)
      for (const elem of data) {
        directEncode(writer, elem, options, refStack)
      }
      return

    case 'Object':
    case 'Map':
      // Maps require key sorting, use token-based encoding for efficiency
      // (pre-encoding all keys for sorting is expensive)
      {
        const tokens = typeEncoders.Object(data, typ, options, refStack)
        tokensToEncoded(writer, tokens, cborEncoders, options)
      }
      return

    default:
    // Fall back to token-based encoding for other types (DataView, TypedArrays, etc.)
    {
      const typeEncoder = typeEncoders[typ]
      if (!typeEncoder) {
        throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`)
      }
      const tokens = typeEncoder(data, typ, options, refStack)
      tokensToEncoded(writer, tokens, cborEncoders, options)
    }
  }
}

/**
 * @template {ArrayBufferLike} T
 * @overload
 * @param {any} data
 * @param {TokenTypeEncoder[]} encoders
 * @param {EncodeOptions} options
 * @param {Uint8Array<T>} destination
 * @returns {Uint8Array<T>}
 */
/**
 * @overload
 * @param {any} data
 * @param {TokenTypeEncoder[]} encoders
 * @param {EncodeOptions} options
 * @returns {AllocatedByteView}
 */
/**
 * @param {any} data
 * @param {TokenTypeEncoder[]} encoders
 * @param {EncodeOptions} options
 * @param {ByteView} [destination]
 * @returns {ByteView}
 */
function encodeCustom (data, encoders, options, destination) {
  // arg ordering is different to encodeInto for backward compatibility
  const hasDest = destination instanceof Uint8Array
  let writeTo = hasDest ? new U8Bl(destination) : defaultWriter

  const tokens = objectToTokens(data, options)
  if (!Array.isArray(tokens) && options.quickEncodeToken) {
    const quickBytes = options.quickEncodeToken(tokens)
    if (quickBytes) {
      if (hasDest) {
        // Copy quick bytes into destination buffer
        writeTo.push(quickBytes)
        return writeTo.toBytes()
      }
      return quickBytes
    }
    const encoder = encoders[tokens.type.major]
    if (encoder.encodedSize) {
      const size = encoder.encodedSize(tokens, options)
      if (!hasDest) {
        writeTo = new Bl(size)
      }
      encoder(writeTo, tokens, options)
      // this would be a problem with encodedSize() functions
      if (writeTo.chunks.length !== 1) {
        throw new Error(`Unexpected error: pre-calculated length for ${tokens} was wrong`)
      }
      return hasDest ? writeTo.toBytes() : asU8A(writeTo.chunks[0])
    }
  }
  writeTo.reset()
  tokensToEncoded(writeTo, tokens, encoders, options)
  return writeTo.toBytes(true)
}

/**
 * @param {any} data
 * @param {EncodeOptions} [options]
 * @returns {AllocatedByteView}
 */
function encode (data, options) {
  options = Object.assign({}, defaultEncodeOptions, options)

  // Use direct encode path when possible
  if (canDirectEncode(options)) {
    defaultWriter.reset()
    directEncode(defaultWriter, data, options, undefined)
    return defaultWriter.toBytes(true)
  }

  return encodeCustom(data, cborEncoders, options)
}

/**
 * @template {ArrayBufferLike} T
 * @param {any} data
 * @param {Uint8Array<T>} destination
 * @param {EncodeOptions} [options]
 * @returns {{ written: number }}
 */
function encodeInto (data, destination, options) {
  options = Object.assign({}, defaultEncodeOptions, options)

  // Use direct encode path when possible
  if (canDirectEncode(options)) {
    const writer = new U8Bl(destination)
    directEncode(writer, data, options, undefined)
    return { written: writer.toBytes().length }
  }

  const result = encodeCustom(data, cborEncoders, options, destination)
  return { written: result.length }
}

export { objectToTokens, encode, encodeCustom, encodeInto, Ref }
// This is an unfortunate replacement for @sindresorhus/is that we need to
// re-implement for performance purposes. In particular the is.observable()
// check is expensive, and unnecessary for our purposes. The values returned
// are compatible with @sindresorhus/is, however.

// Types that reach getObjectType() - excludes types with fast-paths above:
// primitives (typeof), Array (isArray), Uint8Array (instanceof), plain Object (constructor)
const objectTypeNames = [
  'Object', // for Object.create(null) and other non-plain objects
  'RegExp',
  'Date',
  'Error',
  'Map',
  'Set',
  'WeakMap',
  'WeakSet',
  'ArrayBuffer',
  'SharedArrayBuffer',
  'DataView',
  'Promise',
  'URL',
  'HTMLElement',
  'Int8Array',
  'Uint8ClampedArray',
  'Int16Array',
  'Uint16Array',
  'Int32Array',
  'Uint32Array',
  'Float32Array',
  'Float64Array',
  'BigInt64Array',
  'BigUint64Array',
  'Tagged'
]

/**
 * @param {any} value
 * @returns {string}
 */
export function is (value) {
  if (value === null) {
    return 'null'
  }
  if (value === undefined) {
    return 'undefined'
  }
  if (value === true || value === false) {
    return 'boolean'
  }
  const typeOf = typeof value
  if (typeOf === 'string' || typeOf === 'number' || typeOf === 'bigint' || typeOf === 'symbol') {
    return typeOf
  }
  if (typeOf === 'function') {
    return 'Function'
  }
  if (Array.isArray(value)) {
    return 'Array'
  }
  // Also catches Node.js Buffer which extends Uint8Array
  if (value instanceof Uint8Array) {
    return 'Uint8Array'
  }
  // Fast path for plain objects (most common case after primitives/arrays/bytes)
  if (value.constructor === Object) {
    return 'Object'
  }
  const objectType = getObjectType(value)
  if (objectType) {
    return objectType
  }
  return 'Object'
}

/**
 * @param {any} value
 * @returns {string|undefined}
 */
function getObjectType (value) {
  const objectTypeName = Object.prototype.toString.call(value).slice(8, -1)
  if (objectTypeNames.includes(objectTypeName)) {
    return objectTypeName
  }
  return undefined
}
import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import * as negint from './1negint.js'
import * as bytes from './2bytes.js'
import * as string from './3string.js'
import * as array from './4array.js'
import * as map from './5map.js'
import * as tag from './6tag.js'
import * as float from './7float.js'
import { decodeErrPrefix } from './common.js'
import { fromArray } from './byte-utils.js'

/**
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 * @typedef {import('../interface.js').AllocatedByteView} AllocatedByteView
 */

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 */
function invalidMinor (data, pos, minor) {
  throw new Error(`${decodeErrPrefix} encountered invalid minor (${minor}) for major ${data[pos] >>> 5}`)
}

/**
 * @param {string} msg
 * @returns {()=>any}
 */
function errorer (msg) {
  return () => { throw new Error(`${decodeErrPrefix} ${msg}`) }
}

/** @type {((data:Uint8Array, pos:number, minor:number, options?:DecodeOptions) => any)[]} */
export const jump = []

// unsigned integer, 0x00..0x17 (0..23)
for (let i = 0; i <= 0x17; i++) {
  jump[i] = invalidMinor // uint.decodeUintCompact, handled by quick[]
}
jump[0x18] = uint.decodeUint8 // unsigned integer, one-byte uint8_t follows
jump[0x19] = uint.decodeUint16 // unsigned integer, two-byte uint16_t follows
jump[0x1a] = uint.decodeUint32 // unsigned integer, four-byte uint32_t follows
jump[0x1b] = uint.decodeUint64 // unsigned integer, eight-byte uint64_t follows
jump[0x1c] = invalidMinor
jump[0x1d] = invalidMinor
jump[0x1e] = invalidMinor
jump[0x1f] = invalidMinor
// negative integer, -1-0x00..-1-0x17 (-1..-24)
for (let i = 0x20; i <= 0x37; i++) {
  jump[i] = invalidMinor // negintDecode, handled by quick[]
}
jump[0x38] = negint.decodeNegint8 // negative integer, -1-n one-byte uint8_t for n follows
jump[0x39] = negint.decodeNegint16 // negative integer, -1-n two-byte uint16_t for n follows
jump[0x3a] = negint.decodeNegint32 // negative integer, -1-n four-byte uint32_t for follows
jump[0x3b] = negint.decodeNegint64 // negative integer, -1-n eight-byte uint64_t for follows
jump[0x3c] = invalidMinor
jump[0x3d] = invalidMinor
jump[0x3e] = invalidMinor
jump[0x3f] = invalidMinor
// byte string, 0x00..0x17 bytes follow
for (let i = 0x40; i <= 0x57; i++) {
  jump[i] = bytes.decodeBytesCompact
}
jump[0x58] = bytes.decodeBytes8 // byte string, one-byte uint8_t for n, and then n bytes follow
jump[0x59] = bytes.decodeBytes16 // byte string, two-byte uint16_t for n, and then n bytes follow
jump[0x5a] = bytes.decodeBytes32 // byte string, four-byte uint32_t for n, and then n bytes follow
jump[0x5b] = bytes.decodeBytes64 // byte string, eight-byte uint64_t for n, and then n bytes follow
jump[0x5c] = invalidMinor
jump[0x5d] = invalidMinor
jump[0x5e] = invalidMinor
jump[0x5f] = errorer('indefinite length bytes/strings are not supported') // byte string, byte strings follow, terminated by "break"
// UTF-8 string 0x00..0x17 bytes follow
for (let i = 0x60; i <= 0x77; i++) {
  jump[i] = string.decodeStringCompact
}
jump[0x78] = string.decodeString8 // UTF-8 string, one-byte uint8_t for n, and then n bytes follow
jump[0x79] = string.decodeString16 // UTF-8 string, two-byte uint16_t for n, and then n bytes follow
jump[0x7a] = string.decodeString32 // UTF-8 string, four-byte uint32_t for n, and then n bytes follow
jump[0x7b] = string.decodeString64 // UTF-8 string, eight-byte uint64_t for n, and then n bytes follow
jump[0x7c] = invalidMinor
jump[0x7d] = invalidMinor
jump[0x7e] = invalidMinor
jump[0x7f] = errorer('indefinite length bytes/strings are not supported') // UTF-8 strings follow, terminated by "break"
// array, 0x00..0x17 data items follow
for (let i = 0x80; i <= 0x97; i++) {
  jump[i] = array.decodeArrayCompact
}
jump[0x98] = array.decodeArray8 // array, one-byte uint8_t for n, and then n data items follow
jump[0x99] = array.decodeArray16 // array, two-byte uint16_t for n, and then n data items follow
jump[0x9a] = array.decodeArray32 // array, four-byte uint32_t for n, and then n data items follow
jump[0x9b] = array.decodeArray64 // array, eight-byte uint64_t for n, and then n data items follow
jump[0x9c] = invalidMinor
jump[0x9d] = invalidMinor
jump[0x9e] = invalidMinor
jump[0x9f] = array.decodeArrayIndefinite // array, data items follow, terminated by "break"
// map, 0x00..0x17 pairs of data items follow
for (let i = 0xa0; i <= 0xb7; i++) {
  jump[i] = map.decodeMapCompact
}
jump[0xb8] = map.decodeMap8 // map, one-byte uint8_t for n, and then n pairs of data items follow
jump[0xb9] = map.decodeMap16 // map, two-byte uint16_t for n, and then n pairs of data items follow
jump[0xba] = map.decodeMap32 // map, four-byte uint32_t for n, and then n pairs of data items follow
jump[0xbb] = map.decodeMap64 // map, eight-byte uint64_t for n, and then n pairs of data items follow
jump[0xbc] = invalidMinor
jump[0xbd] = invalidMinor
jump[0xbe] = invalidMinor
jump[0xbf] = map.decodeMapIndefinite // map, pairs of data items follow, terminated by "break"
// tags
for (let i = 0xc0; i <= 0xd7; i++) {
  jump[i] = tag.decodeTagCompact
}
jump[0xd8] = tag.decodeTag8
jump[0xd9] = tag.decodeTag16
jump[0xda] = tag.decodeTag32
jump[0xdb] = tag.decodeTag64
jump[0xdc] = invalidMinor
jump[0xdd] = invalidMinor
jump[0xde] = invalidMinor
jump[0xdf] = invalidMinor
// 0xe0..0xf3 simple values, unsupported
for (let i = 0xe0; i <= 0xf3; i++) {
  jump[i] = errorer('simple values are not supported')
}
jump[0xf4] = invalidMinor // false, handled by quick[]
jump[0xf5] = invalidMinor // true, handled by quick[]
jump[0xf6] = invalidMinor // null, handled by quick[]
jump[0xf7] = float.decodeUndefined // undefined
jump[0xf8] = errorer('simple values are not supported') // simple value, one byte follows, unsupported
jump[0xf9] = float.decodeFloat16 // half-precision float (two-byte IEEE 754)
jump[0xfa] = float.decodeFloat32 // single-precision float (four-byte IEEE 754)
jump[0xfb] = float.decodeFloat64 // double-precision float (eight-byte IEEE 754)
jump[0xfc] = invalidMinor
jump[0xfd] = invalidMinor
jump[0xfe] = invalidMinor
jump[0xff] = float.decodeBreak // "break" stop code

/** @type {Token[]} */
export const quick = []
// ints <24
for (let i = 0; i < 24; i++) {
  quick[i] = new Token(Type.uint, i, 1)
}
// negints >= -24
for (let i = -1; i >= -24; i--) {
  quick[31 - i] = new Token(Type.negint, i, 1)
}
// empty bytes
quick[0x40] = new Token(Type.bytes, new Uint8Array(0), 1)
// empty string
quick[0x60] = new Token(Type.string, '', 1)
// empty list
quick[0x80] = new Token(Type.array, 0, 1)
// empty map
quick[0xa0] = new Token(Type.map, 0, 1)
// false
quick[0xf4] = new Token(Type.false, false, 1)
// true
quick[0xf5] = new Token(Type.true, true, 1)
// null
quick[0xf6] = new Token(Type.null, null, 1)

/**
 * @param {Token} token
 * @returns {AllocatedByteView|undefined}
 */
export function quickEncodeToken (token) {
  switch (token.type) {
    case Type.false:
      return fromArray([0xf4])
    case Type.true:
      return fromArray([0xf5])
    case Type.null:
      return fromArray([0xf6])
    case Type.bytes:
      if (!token.value.length) {
        return fromArray([0x40])
      }
      return
    case Type.string:
      if (token.value === '') {
        return fromArray([0x60])
      }
      return
    case Type.array:
      if (token.value === 0) {
        return fromArray([0x80])
      }
      // shouldn't be possible if this were called when there was only one token
      return
    case Type.map:
      if (token.value === 0) {
        return fromArray([0xa0])
      }
      // shouldn't be possible if this were called when there was only one token
      return
    case Type.uint:
      if (token.value < 24) {
        return fromArray([Number(token.value)])
      }
      return
    case Type.negint:
      if (token.value >= -24) {
        return fromArray([31 - Number(token.value)])
      }
  }
}
/**
 * @typedef {import('../interface.js').TagDecodeControl} TagDecodeControl
 * @typedef {(decode: TagDecodeControl) => Tagged} TaggedTagDecoder
 */

/**
 * A wrapper class for representing a CBOR tag with an arbitrary nested value.
 *
 * `Tagged` is a symmetric primitive: it can be passed to `encode()` to emit
 * a CBOR tag header followed by the encoded form of `value`, and it can be
 * returned from a tag decoder (via `Tagged.decoder(tag)` or `Tagged.preserve()`)
 * to round-trip a tag through decode without losing the tag number.
 *
 * Use `Tagged` for one-off tag handling where defining a dedicated
 * `typeEncoders` entry and tag decoder pair would be heavyweight, e.g. when
 * wrapping a structure in a single application-specific tag (COSE, dCBOR
 * envelopes, etc.).
 *
 * For systematic mapping of a JS type to a tag (e.g. CID -> tag 42), prefer
 * a dedicated `typeEncoders` entry instead.
 */
export class Tagged {
  /**
   * @param {number} tag - CBOR tag number, a non-negative integer
   * @param {any} value - The value to be tagged; encoded recursively
   */
  constructor (tag, value) {
    if (typeof tag !== 'number' || !Number.isInteger(tag) || tag < 0) {
      throw new TypeError('Tagged: tag must be a non-negative integer')
    }
    this.tag = tag
    this.value = value
  }

  /**
   * Build a tag decoder for use in `decode()`'s `tags` option that returns the
   * decoded content wrapped in a `Tagged` instance, preserving the tag number
   * for the caller to inspect.
   *
   * @param {number} tag - The CBOR tag number this decoder will be registered for
   * @returns {TaggedTagDecoder}
   *
   * @example
   * import { decode, Tagged } from 'cborg'
   * const value = decode(bytes, { tags: { 16: Tagged.decoder(16) } })
   * // value instanceof Tagged; value.tag === 16
   */
  static decoder (tag) {
    return (decode) => new Tagged(tag, decode())
  }

  /**
   * Build a `tags` option for `decode()` that wraps each listed tag number in
   * a `Tagged` instance, preserving those tags through decode without
   * registering a dedicated decoder per tag.
   *
   * @param {...number} tagNumbers - One or more CBOR tag numbers to preserve
   * @returns {{[tagNumber: number]: TaggedTagDecoder}}
   *
   * @example
   * import { decode, Tagged } from 'cborg'
   * const value = decode(bytes, { tags: Tagged.preserve(16, 96) })
   */
  static preserve (...tagNumbers) {
    /** @type {{[tagNumber: number]: TaggedTagDecoder}} */
    const tags = {}
    for (const tag of tagNumbers) {
      tags[tag] = Tagged.decoder(tag)
    }
    return tags
  }
}

// Symbol.toStringTag so the internal `is()` type detection returns 'Tagged'
// for instances, allowing the default Tagged typeEncoder to match.
Object.defineProperty(Tagged.prototype, Symbol.toStringTag, {
  value: 'Tagged'
})
class Type {
  /**
   * @param {number} major
   * @param {string} name
   * @param {boolean} terminal
   */
  constructor (major, name, terminal) {
    this.major = major
    this.majorEncoded = major << 5
    this.name = name
    this.terminal = terminal
  }

  toString () {
    return `Type[${this.major}].${this.name}`
  }

  /**
   * @param {Type} typ
   * @returns {number}
   */
  compare (typ) {
    return this.major < typ.major ? -1 : this.major > typ.major ? 1 : 0
  }

  /**
   * Check equality between two Type instances. Safe to use across different
   * copies of the Type class (e.g., when bundlers duplicate the module).
   * (major, name) uniquely identifies a Type; terminal is implied by these.
   * @param {Type} a
   * @param {Type} b
   * @returns {boolean}
   */
  static equals (a, b) {
    return a === b || (a.major === b.major && a.name === b.name)
  }
}

// convert to static fields when better supported
Type.uint = new Type(0, 'uint', true)
Type.negint = new Type(1, 'negint', true)
Type.bytes = new Type(2, 'bytes', true)
Type.string = new Type(3, 'string', true)
Type.array = new Type(4, 'array', false)
Type.map = new Type(5, 'map', false)
Type.tag = new Type(6, 'tag', false) // terminal?
Type.float = new Type(7, 'float', true)
Type.false = new Type(7, 'false', true)
Type.true = new Type(7, 'true', true)
Type.null = new Type(7, 'null', true)
Type.undefined = new Type(7, 'undefined', true)
Type.break = new Type(7, 'break', true)
// Type.indefiniteLength = new Type(0, 'indefiniteLength', true)

class Token {
  /**
   * @param {Type} type
   * @param {any} [value]
   * @param {number} [encodedLength]
   */
  constructor (type, value, encodedLength) {
    this.type = type
    this.value = value
    this.encodedLength = encodedLength
    /** @type {Uint8Array|undefined} */
    this.encodedBytes = undefined
    /** @type {Uint8Array|undefined} */
    this.byteValue = undefined
  }

  toString () {
    return `Token[${this.type}].${this.value}`
  }
}

export { Type, Token }
{
  "name": "cborg",
  "version": "5.1.7",
  "description": "Fast CBOR with a focus on strictness",
  "main": "cborg.js",
  "type": "module",
  "bin": {
    "cborg": "lib/bin.js"
  },
  "scripts": {
    "lint": "standard *.js lib/*.js test/*.js",
    "build": "npm run build:types",
    "build:types": "tsc --build",
    "prepublishOnly": "npm run build",
    "test:node": "mocha test/test-*.js",
    "test:node-bin": "mocha test/node-test-bin.js",
    "test:browser": "polendina --cleanup test/test-*.js",
    "test": "npm run lint && npm run build && npm run test:node && npm run test:node-bin && npm run test:browser",
    "test:ci": "npm run test"
  },
  "repository": {
    "type": "git",
    "url": "git@github.com:rvagg/cborg.git"
  },
  "keywords": [
    "cbor"
  ],
  "author": "Rod <rod@vagg.org> (http://r.va.gg/)",
  "license": "Apache-2.0",
  "devDependencies": {
    "@semantic-release/changelog": "^6.0.3",
    "@semantic-release/commit-analyzer": "^13.0.1",
    "@semantic-release/git": "^10.0.1",
    "@semantic-release/github": "^12.0.6",
    "@semantic-release/npm": "^13.1.5",
    "@semantic-release/release-notes-generator": "^14.1.0",
    "@types/chai": "^5.2.3",
    "@types/mocha": "^10.0.10",
    "@types/node": "^26.0.1",
    "chai": "^6.2.2",
    "conventional-changelog-conventionalcommits": "^10.0.0",
    "ipld-garbage": "^5.0.0",
    "mocha": "^11.7.5",
    "polendina": "^3.2.20",
    "semantic-release": "^25.0.3",
    "standard": "^17.1.2",
    "typescript": "^6.0.2"
  },
  "exports": {
    ".": {
      "import": "./cborg.js",
      "types": "./types/cborg.d.ts"
    },
    "./length": {
      "import": "./lib/length.js",
      "types": "./types/lib/length.d.ts"
    },
    "./taglib": {
      "import": "./lib/taglib.js",
      "types": "./types/lib/taglib.d.ts"
    },
    "./json": {
      "import": "./lib/json/json.js",
      "types": "./types/lib/json/json.d.ts"
    },
    "./extended": {
      "import": "./lib/extended/extended.js",
      "types": "./types/lib/extended/extended.d.ts"
    },
    "./interface": {
      "types": "./types/interface.d.ts"
    }
  },
  "types": "cborg.d.ts",
  "typesVersions": {
    "*": {
      "json": [
        "types/lib/json/json.d.ts"
      ],
      "length": [
        "types/lib/length.d.ts"
      ],
      "*": [
        "types/*"
      ],
      "types/*": [
        "types/*"
      ]
    }
  },
  "release": {
    "branches": [
      "master"
    ],
    "plugins": [
      [
        "@semantic-release/commit-analyzer",
        {
          "preset": "conventionalcommits",
          "releaseRules": [
            {
              "breaking": true,
              "release": "major"
            },
            {
              "revert": true,
              "release": "patch"
            },
            {
              "type": "feat",
              "release": "minor"
            },
            {
              "type": "fix",
              "release": "patch"
            },
            {
              "type": "chore",
              "release": "patch"
            },
            {
              "type": "docs",
              "release": "patch"
            },
            {
              "type": "test",
              "release": "patch"
            },
            {
              "scope": "no-release",
              "release": false
            }
          ]
        }
      ],
      [
        "@semantic-release/release-notes-generator",
        {
          "preset": "conventionalcommits",
          "presetConfig": {
            "types": [
              {
                "type": "feat",
                "section": "Features"
              },
              {
                "type": "fix",
                "section": "Bug Fixes"
              },
              {
                "type": "chore",
                "section": "Trivial Changes"
              },
              {
                "type": "docs",
                "section": "Trivial Changes"
              },
              {
                "type": "test",
                "section": "Tests"
              }
            ]
          }
        }
      ],
      "@semantic-release/changelog",
      "@semantic-release/npm",
      "@semantic-release/github",
      "@semantic-release/git"
    ]
  }
}
const b4a = require('b4a')

module.exports = codecs

codecs.ascii = createString('ascii')
codecs.utf8 = createString('utf-8')
codecs.hex = createString('hex')
codecs.base64 = createString('base64')
codecs.ucs2 = createString('ucs2')
codecs.utf16le = createString('utf16le')
codecs.ndjson = createJSON(true)
codecs.json = createJSON(false)
codecs.binary = {
  name: 'binary',
  encode: function encodeBinary (obj) {
    return typeof obj === 'string'
      ? b4a.from(obj, 'utf-8')
      : b4a.toBuffer(obj)
  },
  decode: function decodeBinary (buf) {
    return b4a.toBuffer(buf)
  }
}

function isCompactEncoding (c) {
  return !!(c.encode && c.decode && c.preencode)
}

function fromCompactEncoding (c) {
  return {
    name: 'compact-encoding',
    encode: function encodeWithCompact (value) {
      const state = { start: 0, end: 0, buffer: null, cache: null }
      c.preencode(state, value)
      state.buffer = b4a.allocUnsafe(state.end)
      c.encode(state, value)
      return state.buffer
    },
    decode: function decodeWithCompact (buffer) {
      return c.decode({ start: 0, end: buffer.byteLength, buffer, cache: null })
    }
  }
}

function codecs (fmt, fallback) {
  if (typeof fmt === 'object' && fmt) {
    return isCompactEncoding(fmt) ? fromCompactEncoding(fmt) : fmt
  }

  switch (fmt) {
    case 'ndjson': return codecs.ndjson
    case 'json': return codecs.json
    case 'ascii': return codecs.ascii
    case 'utf-8':
    case 'utf8': return codecs.utf8
    case 'hex': return codecs.hex
    case 'base64': return codecs.base64
    case 'ucs-2':
    case 'ucs2': return codecs.ucs2
    case 'utf16-le':
    case 'utf16le': return codecs.utf16le
  }

  return fallback !== undefined ? fallback : codecs.binary
}

function createJSON (newline) {
  return {
    name: newline ? 'ndjson' : 'json',
    encode: newline ? encodeNDJSON : encodeJSON,
    decode: function decodeJSON (buf) {
      return JSON.parse(b4a.toString(buf))
    }
  }

  function encodeJSON (val) {
    return b4a.from(JSON.stringify(val))
  }

  function encodeNDJSON (val) {
    return b4a.from(JSON.stringify(val) + '\n')
  }
}

function createString (type) {
  return {
    name: type,
    encode: function encodeString (val) {
      if (typeof val !== 'string') val = val.toString()
      return b4a.from(val, type)
    },
    decode: function decodeString (buf) {
      return b4a.toString(buf, type)
    }
  }
}
{
  "name": "codecs",
  "version": "3.1.0",
  "description": "Create an binary encoder/decoder for json, utf-8 or custom types",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.6.3"
  },
  "devDependencies": {
    "brittle": "^3.2.1",
    "compact-encoding": "^2.11.0",
    "standard": "^17.0.0"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/codecs.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/codecs/issues"
  },
  "homepage": "https://github.com/mafintosh/codecs"
}
const c = require('compact-encoding')

module.exports = function bitfield(length) {
  if (length > 64) {
    throw new RangeError('Bitfield cannot be larger than 64 bits')
  }

  let byteLength
  if (length < 8) byteLength = 1
  else if (length <= 16) byteLength = 2
  else if (length <= 32) byteLength = 4
  else byteLength = 8

  return {
    preencode(state) {
      state.end++ // Length byte, used for data when byteLength === 1

      if (byteLength === 1);
      else if (byteLength === 2) c.uint16.preencode(state)
      else if (byteLength === 4) c.uint32.preencode(state)
      else c.uint64.preencode(state)
    },

    encode(state, b) {
      if (byteLength === 1);
      else if (byteLength === 2) c.uint8.encode(state, 0xfd)
      else if (byteLength === 4) c.uint8.encode(state, 0xfe)
      else c.uint8.encode(state, 0xff)

      if (typeof b === 'number') {
        if (byteLength === 1) c.uint8.encode(state, b)
        else if (byteLength === 2) c.uint16.encode(state, b)
        else if (byteLength === 4) c.uint32.encode(state, b)
        else c.uint64.encode(state, b)
      } else {
        state.buffer.set(b, state.start)

        if (b.byteLength < byteLength) {
          // Zero-fill the rest of the byte length.
          state.buffer.fill(
            0,
            state.start + b.byteLength,
            state.start + byteLength
          )
        }

        state.start += byteLength
      }
    },

    decode(state) {
      const byte = state.buffer[state.start]

      let byteLength
      if (byte <= 0xfc) byteLength = 1
      else if (byte === 0xfd) byteLength = 2
      else if (byte === 0xfe) byteLength = 4
      else byteLength = 8

      if (byteLength > 1) state.start++ // Skip the length byte

      if (state.end - state.start < byteLength) throw new Error('Out of bounds')

      const b = state.buffer.subarray(state.start, (state.start += byteLength))

      return length <= 8 ? b.subarray(0, 1) : b
    }
  }
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "compact-encoding-bitfield",
  "version": "1.1.0",
  "description": "Compact codec for bitfields",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node --coverage test.mjs",
    "test:bare": "brittle-bare --coverage test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/compact-encoding/compact-encoding-bitfield.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/compact-encoding/compact-encoding-bitfield/issues"
  },
  "homepage": "https://github.com/compact-encoding/compact-encoding-bitfield#readme",
  "imports": {
    "util": {
      "bare": "bare-utils",
      "default": "util"
    }
  },
  "dependencies": {
    "compact-encoding": "^3.0.0"
  },
  "devDependencies": {
    "bare-utils": "^1.5.1",
    "brittle": "^3.1.0",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  }
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return uint24.decode(state) + 0x1000000 * uint32.decode(state)
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return uint32.decode(state) + 0x100000000 * uint32.decode(state)
  }
})

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "2.19.2",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    if (b.byteLength === 0) return null
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
const safetyCatch = require('safety-catch')

module.exports = class CoreCoupler {
  constructor (target, wakeup) {
    this.target = target
    this.wakeup = wakeup
    this.coupled = new Set()

    this._onpeeraddBound = this._onpeeradd.bind(this)
    this.target.on('peer-add', this._onpeeraddBound)
  }

  add (core) {
    const added = this.coupled.size
    this.coupled.add(core)
    if (added !== this.coupled.size) this._couple(core)
  }

  remove (core) {
    this.coupled.delete(core)
  }

  destroy () {
    this.target.off('peer-add', this._onpeeraddBound)
  }

  async update (stream) {
    const muxer = stream.userData
    if (!muxer) return

    try {
      if (!(await this._hasMuxer(this.target, muxer))) return

      let wakeup = null

      for (const core of this.coupled) {
        if (await this._hasMuxer(core, muxer)) continue
        if (wakeup === null) wakeup = []
        wakeup.push(core)
      }

      if (wakeup !== null) {
        this.wakeup(stream, wakeup)
      }
    } catch (err) {
      safetyCatch(err)
    }
  }

  async _couple (core) {
    try {
      let wakeup = null

      for (const peer of this.target.peers) {
        if (await this._hasPeer(core, peer)) continue
        if (wakeup === null) wakeup = []
        wakeup.push(peer)
      }

      if (wakeup !== null && this.coupled.has(core)) {
        for (const peer of wakeup) this.wakeup(peer.stream, [core])
      }
    } catch (err) {
      safetyCatch(err)
    }
  }

  async _onpeeradd (peer) {
    try {
      let wakeup = null

      for (const core of this.coupled) {
        if (await this._hasPeer(core, peer)) continue
        if (wakeup === null) wakeup = []
        wakeup.push(core)
      }

      if (wakeup !== null) {
        this.wakeup(peer.stream, wakeup)
      }
    } catch (err) {
      safetyCatch(err)
    }
  }

  _hasMuxer (core, muxer) {
    const ch = muxer.getLastChannel({ protocol: 'hypercore', id: core.discoveryKey })
    if (ch) return ch.fullyOpened()

    const cha = muxer.getLastChannel({ protocol: 'hypercore/alpha', id: core.discoveryKey })
    if (cha) return cha.fullyOpened()

    return Promise.resolve(false)
  }

  _hasPeer (core, peer) {
    return this._hasMuxer(core, peer.protomux)
  }
}
{
  "name": "core-coupler",
  "version": "2.0.0",
  "description": "Couple the peers of cores",
  "main": "index.js",
  "scripts": {
    "test": "standard"
  },
  "dependencies": {
    "safety-catch": "^1.0.2"
  },
  "devDependencies": {
    "corestore": "^6.18.2",
    "standard": "^17.1.0"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/core-coupler.git"
  },
  "author": "Holepunch Inc",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/core-coupler/issues"
  },
  "homepage": "https://github.com/holepunchto/core-coupler"
}
const b4a = require('b4a')
const Hypercore = require('hypercore')
const ReadyResource = require('ready-resource')
const sodium = require('sodium-universal')
const crypto = require('hypercore-crypto')
const ID = require('hypercore-id-encoding')
const { isAndroid } = require('which-runtime')
const { STORAGE_EMPTY, ASSERTION } = require('hypercore-errors')

const auditStore = require('./lib/audit.js')
const GroupNotifyHandle = require('./lib/notify.js')

const [NS] = crypto.namespace('corestore', 1)
const DEFAULT_NAMESPACE = b4a.alloc(32) // This is meant to be 32 0-bytes

class StreamTracker {
  constructor() {
    this.records = []
  }

  add(stream, isExternal) {
    const record = { index: 0, stream, isExternal }
    record.index = this.records.push(record) - 1
    return record
  }

  remove(record) {
    const popped = this.records.pop()
    if (popped === record) return
    this.records[(popped.index = record.index)] = popped
  }

  attachAll(core) {
    for (let i = 0; i < this.records.length; i++) {
      const record = this.records[i]
      const muxer = record.stream.noiseStream.userData
      if (!core.replicator.attached(muxer)) core.replicator.attachTo(muxer)
    }
  }

  destroy() {
    // reverse is safer cause we delete mb
    for (let i = this.records.length - 1; i >= 0; i--) {
      const record = this.records[i]
      if (!record.isExternal) record.stream.destroy()
    }
  }
}

class SessionTracker {
  constructor() {
    this.map = new Map()
  }

  get size() {
    return this.map.size
  }

  get(id) {
    const existing = this.map.get(id)
    if (existing !== undefined) return existing
    const fresh = []
    this.map.set(id, fresh)
    return fresh
  }

  gc(id) {
    this.map.delete(id)
  }

  list(id) {
    return id ? this.map.get(id) || [] : [...this]
  }

  *[Symbol.iterator]() {
    for (const sessions of this.map.values()) {
      yield* sessions[Symbol.iterator]()
    }
  }
}

class CoreTracker {
  constructor() {
    this.map = new Map()
    this.watching = []

    this._gcing = new Set()
    this._gcInterval = null
    this._gcCycleBound = this._gcCycle.bind(this)
  }

  get size() {
    return this.map.size
  }

  watch(store) {
    if (store.watchIndex !== -1) return
    store.watchIndex = this.watching.push(store) - 1
  }

  unwatch(store) {
    if (store.watchIndex === -1) return
    const head = this.watching.pop()
    if (head !== store) this.watching[(head.watchIndex = store.watchIndex)] = head
    store.watchIndex = -1
  }

  resume(id) {
    const core = this.map.get(id)

    if (!core) return null

    // signal back that we have a closing one stored
    if (core.closing) return core

    if (core.gc) {
      this._gcing.delete(core)
      if (this._gcing.size === 0) this._stopGC()
      core.gc = 0
    }

    return core
  }

  opened(id) {
    const core = this.map.get(id)
    return !!(core && core.opened && !core.closing)
  }

  get(id) {
    // we allow you do call this from the outside, so support normal buffers also
    if (b4a.isBuffer(id)) id = b4a.toString(id, 'hex')
    const core = this.map.get(id)
    if (!core || core.closing) return null
    return core
  }

  set(id, core) {
    this.map.set(id, core)
    if (this.watching.length > 0) this._emit(core)
  }

  _emit(core) {
    for (let i = this.watching.length - 1; i >= 0; i--) {
      const store = this.watching[i]
      for (const fn of store.watchers) fn(core)
    }
  }

  _gc(core) {
    const id = toHex(core.discoveryKey)
    if (this.map.get(id) === core) this.map.delete(id)
  }

  _gcCycle() {
    for (const core of this._gcing) {
      if (++core.gc < 4) continue
      const gc = this._gc.bind(this, core)
      core.close().then(gc, gc)
      this._gcing.delete(core)
    }

    if (this._gcing.size === 0) this._stopGC()
  }

  gc(core) {
    core.gc = 1 // first strike
    this._gcing.add(core)
    if (this._gcing.size === 1) this._startGC()
  }

  _stopGC() {
    clearInterval(this._gcInterval)
    this._gcInterval = null
  }

  _startGC() {
    if (this._gcInterval) return
    this._gcInterval = setInterval(this._gcCycleBound, 2000)
    if (this._gcInterval.unref) this._gcInterval.unref()
  }

  close() {
    this._stopGC()
    this._gcing.clear()

    const all = []
    for (const core of this.map.values()) {
      core.onidle = noop // no reentry
      all.push(core.close())
    }
    this.map.clear()

    return Promise.all(all)
  }

  *[Symbol.iterator]() {
    for (const core of this.map.values()) {
      if (!core.closing) yield core
    }
  }
}

class FindingPeers {
  constructor() {
    this.count = 0
    this.pending = []
    this.destroyed = false
  }

  add(core) {
    if (this.count === 0) return
    this.pending.push(core.findingPeers())
  }

  inc(sessions) {
    if (this.destroyed || ++this.count !== 1) return

    for (const core of sessions) {
      this.pending.push(core.findingPeers())
    }
  }

  dec(sessions) {
    if (this.destroyed || --this.count !== 0) return
    while (this.pending.length > 0) this.pending.pop()()
  }

  destroy() {
    this.destroyed = true
    while (this.pending.length > 0) this.pending.pop()()
  }
}

class Corestore extends ReadyResource {
  constructor(storage, opts = {}) {
    super()

    this.root = opts.root || null
    this.storage = this.root
      ? this.root.storage
      : Hypercore.defaultStorage(storage, {
          id: opts.id,
          allowBackup: opts.allowBackup,
          readOnly: opts.readOnly,
          wait: opts.wait
        })
    this.streamTracker = this.root ? this.root.streamTracker : new StreamTracker()
    this.cores = this.root ? this.root.cores : new CoreTracker()
    this.sessions = new SessionTracker()
    this.corestores = this.root ? this.root.corestores : new Set()
    this.readOnly = opts.writable === false || !!opts.readOnly
    this.globalCache = this.root ? this.root.globalCache : opts.globalCache || null
    this.primaryKey = this.root ? this.root.primaryKey : opts.primaryKey || null
    this.ns = opts.namespace || DEFAULT_NAMESPACE
    this.manifestVersion = opts.manifestVersion || 1
    this.shouldSuspend = isAndroid ? !!opts.suspend : opts.suspend !== false
    this.active = opts.active !== false

    this.watchers = null
    this.watchIndex = -1

    this._groupNotifiers = new Map() // group notifications
    this._findingPeers = null // here for legacy
    this._ongcBound = this._ongc.bind(this)
    this._onGroupActiveBound = this._onGroupActive.bind(this)

    if (opts.primaryKey && !this.root && !opts.unsafe) {
      throw ASSERTION(
        'Passing the primary key is unsafe unless you know what you are doing. Set unsafe: true to acknowledge that'
      )
    }

    this.ready().catch(noop)
  }

  watch(fn) {
    if (this.watchers === null) {
      this.watchers = new Set()
      this.cores.watch(this)
    }

    this.watchers.add(fn)
  }

  unwatch(fn) {
    if (this.watchers === null) return

    this.watchers.delete(fn)

    if (this.watchers.size === 0) {
      this.watchers = null
      this.cores.unwatch(this)
    }
  }

  _onGroupActive(topic, update) {
    this.emit('group-active', topic, update)

    const topicHex = b4a.toString(topic, 'hex')
    const handles = this._groupNotifiers.get(topicHex)
    if (!handles) return
    for (const handle of handles) handle.emit('update', update)
  }

  notifyGroup(topic) {
    const topicHex = b4a.toString(topic, 'hex')
    let handles = this._groupNotifiers.get(topicHex)

    if (!handles) {
      handles = []
      this._groupNotifiers.set(topicHex, handles)
    }

    const handle = new GroupNotifyHandle(this, topic)
    const length = handles.push(handle)
    handle.index = length - 1

    return handle
  }

  _removeGroupNotify(handle) {
    if (handle.index === -1) return

    const topicHex = b4a.toString(handle._topic, 'hex')
    const handles = this._groupNotifiers.get(topicHex)
    if (!handles) return

    const popped = handles.pop()
    if (popped !== handle) handles[(popped.index = handle.index)] = popped
    if (handles.length === 0) this._groupNotifiers.delete(topicHex)
    handle.index = -1
  }

  findingPeers() {
    if (this._findingPeers === null) this._findingPeers = new FindingPeers()
    this._findingPeers.inc(this.sessions)
    let done = false
    return () => {
      if (done || !this._findingPeers) return
      done = true
      this._findingPeers.dec(this.sessions)
    }
  }

  audit(opts = {}) {
    return auditStore(this, opts)
  }

  async suspend({ log = noop } = {}) {
    await log('Flushing db...')
    // If readOnly we don't need to flush
    if (!this.storage.readOnly) {
      await this.storage.db.flush()
      await log('Flusing db completed')
    }
    if (!this.shouldSuspend) return
    await log('Suspending db...')
    await this.storage.suspend({ log })
    await log('Suspending db completed')
  }

  resume() {
    return this.storage.resume()
  }

  session(opts) {
    this._maybeClosed()
    const root = this.root || this
    return new Corestore(null, {
      manifestVersion: this.manifestVersion,
      ...opts,
      root
    })
  }

  namespace(name, opts) {
    return this.session({
      ...opts,
      namespace: generateNamespace(this.ns, name)
    })
  }

  list(namespace) {
    return this.storage.createDiscoveryKeyStream(namespace)
  }

  getAuth(discoveryKey) {
    return this.storage.getAuth(discoveryKey)
  }

  _ongc(session) {
    if (session.sessions.length === 0) this.sessions.gc(session.id)
  }

  async _getOrSetSeed() {
    const seed = await this.storage.getSeed()
    if (seed !== null) return seed
    return await this.storage.setSeed(this.primaryKey || crypto.randomBytes(32))
  }

  async _open() {
    if (this.root !== null) {
      this.corestores.add(this)
      if (this.root.opened === false) await this.root.ready()
      this.primaryKey = this.root.primaryKey
      return
    }

    const primaryKey = await this._getOrSetSeed()

    if (this.primaryKey === null) {
      this.primaryKey = primaryKey
      return
    }

    if (!b4a.equals(primaryKey, this.primaryKey)) {
      throw new Error('Another corestore is stored here')
    }
  }

  async _close() {
    const closing = []
    const hanging = [...this.sessions]
    for (const sess of hanging) closing.push(sess.close())

    if (this.watchers !== null) {
      this.cores.unwatch(this)
      this.watchers = null
    }

    if (this._findingPeers !== null) {
      this._findingPeers.destroy()
      this._findingPeers = null
    }

    if (this.root !== null) {
      await Promise.all(closing)
      this.corestores.delete(this)
      return
    }

    for (const store of this.corestores) {
      closing.push(store.close())
    }

    await Promise.all(closing)

    await this.cores.close()
    await this.storage.close()
  }

  async _attachMaybe(muxer, discoveryKey) {
    if (this.opened === false) await this.ready()
    if (
      !this.cores.opened(toHex(discoveryKey)) &&
      !(await this.storage.hasCore(discoveryKey, { ifMigrated: true }))
    ) {
      return
    }
    if (this.closing) return

    const core = this._openCore(discoveryKey, { createIfMissing: false })

    if (!core) return
    if (!core.opened) await core.ready()

    if (!core.replicator.attached(muxer)) {
      core.replicator.attachTo(muxer)
    }

    core.checkIfIdle()
  }

  _shouldReplicate(core, muxer) {
    return (
      core.replicator.downloading && !core.replicator.attached(muxer) && core.opened && this.active
    )
  }

  replicate(isInitiator, opts) {
    this._maybeClosed()

    const isExternal = isStream(isInitiator)
    const stream = Hypercore.createProtocolStream(isInitiator, {
      ...opts,
      ondiscoverykey: (discoveryKey) => {
        if (this.closing) return
        const muxer = stream.noiseStream.userData
        return this._attachMaybe(muxer, discoveryKey)
      }
    })

    if (this.cores.size > 0) {
      const muxer = stream.noiseStream.userData
      const uncork = muxer.uncork.bind(muxer)
      muxer.cork()

      for (const core of this.cores) {
        if (!this._shouldReplicate(core, muxer)) {
          continue
        }
        core.replicator.attachTo(muxer)
      }

      stream.noiseStream.opened.then(uncork)
    }

    const record = this.streamTracker.add(stream, isExternal)
    stream.once('close', () => this.streamTracker.remove(record))
    return stream
  }

  _maybeClosed() {
    if (this.closing || (this.root !== null && this.root.closing)) {
      throw new Error('Corestore is closed')
    }
  }

  async staticify(core, opts) {
    if (!this.opened) await this.ready()
    if (!core.opened) await core.ready()

    const rx = core.state.storage.read()

    const headPromise = rx.getHead()
    const authPromise = rx.getAuth()

    rx.tryFlush()

    const [head, auth] = await Promise.all([headPromise, authPromise])
    if (!head || head.length === 0) throw new Error('Core must have data')

    const prologue = {
      length: head.length,
      hash: head.rootHash
    }

    const manifest = {
      version: 1,
      hash: auth.manifest.hash,
      quorum: 0,
      signers: [],
      prologue
    }

    const c = {
      key: null,
      discoveryKey: null,
      manifest,
      core: core.state.storage.core
    }

    c.key = Hypercore.key(c.manifest)
    c.discoveryKey = Hypercore.discoveryKey(c.key)

    await this.storage.createCore(c)

    const staticCore = this.get({ ...opts, key: c.key })
    await staticCore.ready()
    return staticCore
  }

  get(opts) {
    this._maybeClosed()

    if (b4a.isBuffer(opts) || typeof opts === 'string') opts = { key: opts }
    if (!opts) opts = {}

    const conf = {
      preload: null,
      sessions: null,
      ongc: null,
      core: null,
      active: opts.active !== false,
      encryption: opts.encryption || null,
      encryptionKey: opts.encryptionKey || null, // back compat, should remove
      isBlockKey: !!opts.isBlockKey, // back compat, should remove
      valueEncoding: opts.valueEncoding || null,
      exclusive: !!opts.exclusive,
      manifest: opts.manifest || null,
      keyPair: opts.keyPair || null,
      onwait: opts.onwait || null,
      pushOnly: opts.pushOnly === true,
      wait: opts.wait !== false,
      timeout: opts.timeout || 0,
      draft: !!opts.draft,
      writable: opts.writable === undefined && this.readOnly ? false : opts.writable
    }

    // name requires us to rt to storage + ready, so needs preload
    // same goes if user has defined async preload obvs
    if (opts.name || opts.preload) {
      conf.preload = this._preload(opts)
      return this._makeSession(conf)
    }

    if (opts.discoveryKey && !opts.key && !opts.manifest) {
      conf.preload = this._preloadCheckIfExists(opts)
      return this._makeSession(conf)
    }

    // if not not we can sync create it, which just is easier for the
    // upstream user in terms of guarantees (key is there etc etc)
    const core = this._openCore(null, opts)

    conf.core = core
    conf.sessions = this.sessions.get(core.id)
    conf.ongc = this._ongcBound

    return this._makeSession(conf)
  }

  _makeSession(conf) {
    const session = new Hypercore(null, null, conf)

    if (this._findingPeers !== null) this._findingPeers.add(session)
    return session
  }

  async createKeyPair(name, ns = this.ns) {
    if (this.opened === false) await this.ready()
    return createKeyPair(this.primaryKey, ns, name)
  }

  async _preloadCheckIfExists(opts) {
    const has = await this.storage.hasCore(opts.discoveryKey)
    if (!has) throw STORAGE_EMPTY('No Hypercore is stored here')
    return this._preload(opts)
  }

  async _preload(opts) {
    if (opts.preload) opts = { ...opts, ...(await opts.preload) }
    if (this.opened === false) await this.ready()

    const discoveryKey = opts.name
      ? await this.storage.getAlias({ name: opts.name, namespace: this.ns })
      : null
    this._maybeClosed()

    const core = this._openCore(discoveryKey, opts)

    return {
      core,
      sessions: this.sessions.get(core.id),
      ongc: this._ongcBound,
      manifest: opts.manifest || null,
      encryption: opts.encryption || null,
      encryptionKey: opts.encryptionKey || null, // back compat, should remove
      isBlockKey: !!opts.isBlockKey // back compat, should remove
    }
  }

  _auth(discoveryKey, opts) {
    const result = {
      keyPair: null,
      key: null,
      discoveryKey,
      manifest: null,
      group: null
    }

    if (opts.name) {
      result.keyPair = createKeyPair(this.primaryKey, this.ns, opts.name)
    } else if (opts.keyPair) {
      result.keyPair = opts.keyPair
    }

    if (opts.manifest) {
      result.manifest = opts.manifest
    } else if (result.keyPair && !result.discoveryKey) {
      result.manifest = {
        version: this.manifestVersion,
        signers: [{ publicKey: result.keyPair.publicKey }]
      }
    }

    if (opts.group) {
      result.group = opts.group
    }

    if (opts.key) result.key = ID.decode(opts.key)
    else if (result.manifest) result.key = Hypercore.key(result.manifest)

    if (result.discoveryKey) return result

    if (opts.discoveryKey) result.discoveryKey = ID.decode(opts.discoveryKey)
    else if (result.key) result.discoveryKey = crypto.discoveryKey(result.key)
    else throw new Error('Could not derive discovery from input')

    return result
  }

  _openCore(discoveryKey, opts) {
    const auth = this._auth(discoveryKey, opts)

    const id = toHex(auth.discoveryKey)
    const existing = this.cores.resume(id, auth.group)
    if (existing && !existing.closing) return existing

    const core = Hypercore.createCore(this.storage, {
      preopen: existing && existing.opened ? existing.closing : null, // always wait for the prev one to close first in any case...
      eagerUpgrade: true,
      notDownloadingLinger: opts.notDownloadingLinger,
      allowFork: opts.allowFork !== false,
      allowPush: !!opts.allowPush,
      inflightRange: opts.inflightRange,
      compat: false, // no compat for now :)
      force: opts.force,
      createIfMissing: opts.createIfMissing,
      discoveryKey: auth.discoveryKey,
      overwrite: opts.overwrite,
      key: auth.key,
      keyPair: auth.keyPair,
      legacy: opts.legacy,
      manifest: auth.manifest,
      group: auth.group,
      globalCache: opts.globalCache || this.globalCache || null,
      alias: opts.name ? { name: opts.name, namespace: this.ns } : null
    })

    core.onidle = () => {
      this.cores.gc(core)
    }

    core.ongroupupdate = this._onGroupActiveBound

    core.replicator.ondownloading = () => {
      if (this.active) this.streamTracker.attachAll(core)
    }

    this.cores.set(id, core)
    return core
  }
}

module.exports = Corestore

function isStream(s) {
  return typeof s === 'object' && s && typeof s.pipe === 'function'
}

function generateNamespace(namespace, name) {
  if (!b4a.isBuffer(name)) name = b4a.from(name)
  const out = b4a.allocUnsafeSlow(32)
  sodium.crypto_generichash_batch(out, [namespace, name])
  return out
}

function deriveSeed(primaryKey, namespace, name) {
  if (!b4a.isBuffer(name)) name = b4a.from(name)
  const out = b4a.alloc(32)
  sodium.crypto_generichash_batch(out, [NS, namespace, name], primaryKey)
  return out
}

function createKeyPair(primaryKey, namespace, name) {
  const seed = deriveSeed(primaryKey, namespace, name)
  const buf = b4a.alloc(sodium.crypto_sign_PUBLICKEYBYTES + sodium.crypto_sign_SECRETKEYBYTES)
  const keyPair = {
    publicKey: buf.subarray(0, sodium.crypto_sign_PUBLICKEYBYTES),
    secretKey: buf.subarray(sodium.crypto_sign_PUBLICKEYBYTES)
  }
  sodium.crypto_sign_seed_keypair(keyPair.publicKey, keyPair.secretKey, seed)
  return keyPair
}

function noop() {}

function toHex(discoveryKey) {
  return b4a.toString(discoveryKey, 'hex')
}
module.exports = async function* audit(store, { dryRun = false } = {}) {
  for await (const { discoveryKey, core } of store.storage.createCoreStream()) {
    if (core.version < 1) continue // not migrated, ignore

    const c = store.get({ discoveryKey, active: false })
    await c.ready()

    yield { discoveryKey, key: c.key, audit: await c.core.audit({ dryRun }) }

    try {
      await c.close()
    } catch {
      // ignore if failed, we are auditing...
    }
  }
}
const { EventEmitter } = require('events')
const { Readable } = require('streamx')

class GroupNotifyHandle extends EventEmitter {
  constructor(store, topic) {
    super()
    this._store = store
    this._topic = topic
    this.index = -1
  }

  updates(opts) {
    return Readable.deferred(async () => {
      const groupId = await this._store.storage.getGroup(this._topic).catch(noop)
      if (groupId === null) return null
      return this._store.storage.createGroupUpdateStream(groupId, opts)
    })
  }

  destroy() {
    this._store._removeGroupNotify(this)
  }
}

module.exports = GroupNotifyHandle

function noop() {}
{
  "name": "corestore",
  "version": "7.11.0",
  "description": "A Hypercore factory that simplifies managing collections of cores.",
  "main": "index.js",
  "files": [
    "index.js",
    "lib/*"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "dependencies": {
    "b4a": "^1.6.7",
    "bare-events": "^2.8.3",
    "hypercore": "^11.32.0",
    "hypercore-crypto": "^3.4.2",
    "hypercore-errors": "^1.4.0",
    "hypercore-id-encoding": "^1.3.0",
    "ready-resource": "^1.1.1",
    "sodium-universal": "^5.0.1",
    "streamx": "^2.26.0",
    "which-runtime": "^1.2.1"
  },
  "devDependencies": {
    "brittle": "^3.7.0",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "rache": "^1.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "test": "npm run test:node && npm run test:bare",
    "test:bare": "brittle-bare --coverage test/all.js",
    "lint": "prettier --check . && lunte",
    "test:node": "brittle-node --coverage test/all.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/corestore.git"
  },
  "author": "Holepunch Inc",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/corestore/issues"
  },
  "homepage": "https://github.com/holepunchto/corestore"
}
module.exports = function debounce (worker, context = null) {
  debounced.running = null
  return debounced

  async function debounced () {
    if (debounced.running !== null) {
      try {
        await debounced.running
      } catch (_) {
        // ignore - do not fail on old errors
      }
    }

    // another "thread" beat us to it, just piggy pack on that one
    if (debounced.running !== null) return debounced.running

    debounced.running = worker.call(context)

    try {
      return await debounced.running
    } finally {
      debounced.running = null
    }
  }
}
{
  "name": "debounceify",
  "version": "1.1.0",
  "description": "Tiny async debouncer",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^16.0.3",
    "tape": "^5.1.1"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/debounceify.git"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/debounceify/issues"
  },
  "homepage": "https://github.com/mafintosh/debounceify"
}
const fs = require('fs')
const path = require('path')
const fsx = require('fs-native-extensions')
const b4a = require('b4a')
const ReadyResource = require('ready-resource')
const FDLock = require('fd-lock')

const PLATFORM = global.Bare ? global.Bare.platform : global.process.platform
const IS_WIN = PLATFORM === 'win32'
const IS_LINUX = PLATFORM === 'linux'
const MODIFIED_SLACK = 5000
const EMPTY = b4a.alloc(0)
const ATTR = IS_LINUX ? 'user.device-file' : 'device-file'

const nl = IS_WIN ? '\r\n' : '\n'

class DeviceFile extends ReadyResource {
  constructor(filename, { create = true, wait = false, lock = wait, data = {} } = {}) {
    super()

    this.filename = filename
    this.data = data
    this.lock = null

    this._create = create
    this._wait = wait
    this._lock = lock
  }

  async _open() {
    if (await verifyDeviceFile(this)) return
    if (!this._create) throwDeviceFileError('No device file present', false)
    await writeDeviceFile(this)
  }

  static async validate(filename, data) {
    const file = new DeviceFile(filename, { create: false, wait: false, data })
    try {
      await verifyDeviceFile(file)
    } catch (err) {
      if (err.fatal && err.code === 'DEVICE_FILE') return false
      throw err
    }
    return true
  }

  transfer() {
    return this.lock ? this.lock.transfer() : -1
  }

  async _close() {
    if (this.lock) await this.lock.close()
  }

  async suspend() {
    if (!this.opened) await this.ready()
    if (this.lock) await this.lock.suspend()
  }

  async resume() {
    if (!this.opened) await this.ready()
    if (this.lock) await this.lock.resume()
  }
}

module.exports = DeviceFile

async function writeDeviceFile(device) {
  let s = ''

  for (const [key, value] of Object.entries(device.data)) {
    if (value === null) continue
    s += key + '=' + value + nl
  }

  await fs.promises.mkdir(path.dirname(device.filename), { recursive: true })

  const fd = await open(device.filename, 'w')

  device.lock = device._lock ? new FDLock(fd, { wait: device._wait }) : null

  if (device.lock) {
    try {
      await device.lock.ready()
    } catch (err) {
      await device.lock.close()
      throw err
    }
  }

  const st = await fstat(fd)

  const created = Date.now()

  s += 'device/platform=' + PLATFORM + nl
  s += 'device/inode=' + st.ino + nl
  s += 'device/created=' + created + nl

  if (await setAttr(fd, ATTR, b4a.from('original'))) {
    s += 'device/attribute=original' + nl
  }

  await write(fd, b4a.from(s))

  if (!device.lock) await close(fd)
}

async function verifyDeviceFile(device) {
  let fd = 0

  try {
    fd = await open(device.filename, 'r+')
  } catch (e) {
    fd = 0
  }

  if (fd === 0) return false

  device.lock = device._lock ? new FDLock(fd, { wait: device._wait }) : null

  if (device.lock) {
    try {
      await device.lock.ready()
    } catch (err) {
      await device.lock.close()
      throw err
    }
  }

  const buf = await read(fd)
  const result = {}

  const s = b4a.toString(buf).trim().split('\n')

  let inode = 0
  let created = 0
  let attr = ''
  let platform = ''

  for (const ln of s) {
    const i = ln.indexOf('=')
    if (i === -1) continue

    const k = ln.slice(0, i).trim()
    const v = ln.slice(i + 1).trim()

    switch (k) {
      case 'device/platform':
        platform = v
        break
      case 'device/inode':
        inode = Number(v)
        break
      case 'device/created':
        created = Number(v)
        break
      case 'device/attribute':
        attr = v
        break
      default:
        result[k] = v
        break
    }
  }

  for (const [k, v] of Object.entries(device.data)) {
    if (v === null) continue
    if (result[k] === undefined) continue // allow upserts
    if (result[k] !== '' + v) {
      await teardown()
      throwDeviceFileError(`Invalid device file, ${k} has changed. Was ${result[k]}, is ${v}`, true)
    }
  }

  const st = await fstat(fd)
  const at = await getAttr(fd, ATTR)

  const sameAttr = b4a.toString(at || EMPTY) === attr
  const modified = Math.max(st.mtime.getTime(), st.birthtime.getTime())

  if (platform && platform !== PLATFORM) {
    await teardown()
    throwDeviceFileError('Invalid device file, was made on different platform', true)
  }

  if (!sameAttr) {
    await teardown()
    throwDeviceFileError('Invalid device file, was moved unsafely', true)
  }

  if (st.ino !== inode || (created && Math.abs(modified - created) >= MODIFIED_SLACK)) {
    await teardown()
    throwDeviceFileError('Invalid device file, was modified', true)
  }

  if (!device.lock) await close(fd)

  device.data = result
  return true

  async function teardown() {
    if (device.lock) await device.lock.close()
    else await close(fd)
  }
}

async function getAttr(fd, name) {
  try {
    return await fsx.getAttr(fd, name)
  } catch {
    return null
  }
}

async function setAttr(fd, name, value) {
  try {
    await fsx.setAttr(fd, name, value)
    return true
  } catch {
    return false
  }
}

function fstat(fd) {
  return new Promise((resolve, reject) => {
    fs.fstat(fd, (err, st) => {
      if (err) reject(err)
      resolve(st)
    })
  })
}

function close(fd) {
  return new Promise((resolve, reject) => {
    fs.close(fd, (err, st) => {
      if (err) reject(err)
      resolve(st)
    })
  })
}

function write(fd, buf) {
  return new Promise((resolve, reject) => {
    let offset = 0

    onwrite(null, 0)

    function onwrite(err, wrote) {
      if (err) return reject(err)
      if (offset === buf.byteLength) return resolve()
      offset += wrote
      fs.write(fd, buf, offset, buf.byteLength - offset, offset, onwrite)
    }
  })
}

function read(fd) {
  const buf = b4a.allocUnsafe(4096)

  return new Promise((resolve, reject) => {
    let offset = 0

    fs.read(fd, buf, 0, buf.byteLength, 0, onread)

    function onread(err, read) {
      if (err) return reject(err)
      if (read === 0) return resolve(buf.subarray(0, offset))
      offset += read
      fs.read(fd, buf, offset, buf.byteLength - offset, offset, onread)
    }
  })
}

function open(filename, flags) {
  return new Promise((resolve, reject) => {
    fs.open(filename, flags, (err, fd) => {
      if (err) reject(err)
      resolve(fd)
    })
  })
}

function throwDeviceFileError(message, fatal) {
  const err = new Error(message)
  err.code = 'DEVICE_FILE'
  err.fatal = fatal
  throw err
}
{
  "name": "device-file",
  "version": "2.3.1",
  "description": "Device only file",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.6.7",
    "bare-fs": "^4.0.1",
    "bare-path": "^3.0.0",
    "fd-lock": "^2.1.0",
    "fs-native-extensions": "^1.4.0",
    "ready-resource": "^1.2.0"
  },
  "devDependencies": {
    "brittle": "^3.13.1",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node --coverage test.js",
    "test:bare": "brittle-bare --coverage test.js"
  },
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    }
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/device-file.git"
  },
  "author": "Holepunch Inc",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/device-file/issues"
  },
  "homepage": "https://github.com/holepunchto/device-file"
}
const { EventEmitter } = require('events')
const Table = require('kademlia-routing-table')
const TOS = require('time-ordered-set')
const UDX = require('udx-native')
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const NatSampler = require('nat-sampler')
const b4a = require('b4a')
const NetworkHealth = require('./lib/health')
const IO = require('./lib/io')
const Query = require('./lib/query')
const Session = require('./lib/session')
const peer = require('./lib/peer')
const { UNKNOWN_COMMAND, INVALID_TOKEN } = require('./lib/errors')
const { PING, PING_NAT, FIND_NODE, DOWN_HINT, DELAYED_PING } = require('./lib/commands')

const TMP = b4a.allocUnsafe(32)
const TICK_INTERVAL = 5000
const SLEEPING_INTERVAL = 3 * TICK_INTERVAL
const STABLE_TICKS = 240 // if nothing major bad happens in ~20mins we can consider this node stable (if nat is friendly)
const MORE_STABLE_TICKS = 3 * STABLE_TICKS
const REFRESH_TICKS = 60 // refresh every ~5min when idle
const RECENT_NODE = 12 // we've heard from a node less than 1min ago
const OLD_NODE = 360 // if an node has been around more than 30 min we consider it old

const DEFAULTS = {
  concurrency: 10,
  maxWindow: IO.DEFAULT_MAX_WINDOW,
  maxPingDelay: 10_000
}

class DHT extends EventEmitter {
  constructor(opts = {}) {
    super()

    this.bootstrapNodes = opts.bootstrap === false ? [] : (opts.bootstrap || []).map(parseNode)
    this.table = new Table(randomBytes(32))
    this.nodes = new TOS()
    this.udx = opts.udx || new UDX()
    this.io = new IO(this.table, this.udx, {
      ...opts,
      onrequest: this._onrequest.bind(this),
      onresponse: this._onresponse.bind(this),
      ontimeout: this._ontimeout.bind(this)
    })
    this.health = new NetworkHealth(this)

    this.concurrency = opts.concurrency || DEFAULTS.concurrency
    this.maxPingDelay = opts.maxPingDelay || DEFAULTS.maxPingDelay
    this.bootstrapped = false
    this.ephemeral = true
    this.firewalled = this.io.firewalled
    this.adaptive = typeof opts.ephemeral !== 'boolean' && opts.adaptive !== false
    this.destroyed = false
    this.suspended = false
    this.online = true
    this.degraded = false
    this.stats = {
      queries: { active: 0, total: 0 },
      requests: this.io.stats.requests,
      commands: {
        ping: this.io.stats.commands[PING],
        pingNat: this.io.stats.commands[PING_NAT],
        findNode: this.io.stats.commands[FIND_NODE],
        downHint: this.io.stats.commands[DOWN_HINT]
      }
    }

    this._nat = new NatSampler()
    this._quickFirewall = opts.quickFirewall !== false
    this._forcePersistent = opts.ephemeral === false
    this._repinging = 0
    this._checks = 0
    this._tick = randomOffset(100) // make sure to random offset all the network ticks
    this._refreshTicks = randomOffset(REFRESH_TICKS)
    this._stableTicks = this.adaptive ? STABLE_TICKS : 0
    this._tickInterval = setInterval(this._ontick.bind(this), TICK_INTERVAL)
    this._lastTick = Date.now()
    this._lastHost = null
    this._filterNode = opts.filterNode || opts.addNode || null // opts.addNode is deprecating, use opts.filterNode instead
    this._onrow = (row) => row.on('full', (node) => this._onfullrow(node, row))
    this._nonePersistentSamples = []
    this._bootstrapping = this._bootstrap()
    this._bootstrapping.catch(noop)
    this._sendDownHints = opts.sendDownHints !== false
    this._downHintsRateLimit =
      opts.downHintsRateLimit !== undefined ? opts.downHintsRateLimit : 10 * 5
    this._downHintsSentPerTick = 0
    this._pendingTimers = new Set()

    this.table.on('row', this._onrow)

    this.io.networkInterfaces.on('change', (interfaces) => this._onnetworkchange(interfaces))

    if (opts.nodes) {
      for (let i = opts.nodes.length - 1; i >= 0; i--) {
        this.addNode(opts.nodes[i])
      }
    }
  }

  static DEFAULTS = DEFAULTS

  static bootstrapper(port, host, opts) {
    if (!port) throw new Error('Port is required')
    if (!host) throw new Error('Host is required')
    if (host === '0.0.0.0' || host === '::') throw new Error('Invalid host')
    if (!UDX.isIPv4(host)) throw new Error('Host must be a IPv4 address')

    const dht = new this({
      port,
      ephemeral: false,
      firewalled: false,
      anyPort: false,
      bootstrap: [],
      ...opts
    })
    dht._nat.add(host, port)
    return dht
  }

  get id() {
    return this.ephemeral ? null : this.table.id
  }

  get host() {
    return this._nat.host
  }

  get port() {
    return this._nat.port
  }

  get randomized() {
    return this._nat.host !== null && this._nat.port === 0
  }

  get socket() {
    return this.firewalled ? this.io.clientSocket : this.io.serverSocket
  }

  get config() {
    return {
      concurrency: this.concurrency,
      maxWindow: this.io.congestion._maxWindow,
      randomPunchInterval: this._randomPunchInterval,
      connectionKeepAlive: this.connectionKeepAlive,
      sendDownHints: this._sendDownHints,
      downHintsRateLimit: this._downHintsRateLimit
    }
  }

  onmessage(socket, buf, rinfo) {
    if (buf.byteLength > 1) this.io.onmessage(socket, buf, rinfo)
  }

  bind() {
    return this.io.bind()
  }

  async suspend({ log = noop } = {}) {
    log('Suspending waiting for io bind...')
    await this.io.bind()
    log('Done, continuing')
    if (this.suspended || this.destroyed) return
    this.suspended = true
    clearInterval(this._tickInterval)
    log('Done, suspending io')
    await this.io.suspend({ log })
    log('Done, dht suspended')
    this.emit('suspend')
  }

  async resume({ log = noop } = {}) {
    if (!this.suspended || this.destroyed) return
    this.suspended = false
    this._tickInterval = setInterval(this._ontick.bind(this), TICK_INTERVAL)
    this._onwakeup()
    log('Resuming io')
    await this.io.resume()
    log('Done, dht resumed')
    this.io.networkInterfaces.on('change', (interfaces) => this._onnetworkchange(interfaces))
    this.refresh()
    this.emit('resume')
  }

  address() {
    const socket = this.socket
    return socket ? socket.address() : null
  }

  localAddress() {
    if (!this.io.serverSocket) return null

    return {
      host: localIP(this.udx),
      port: this.io.serverSocket.address().port
    }
  }

  remoteAddress() {
    if (!this.host) return null
    if (!this.port) return null
    if (this.firewalled) return null
    if (!this.io.serverSocket) return null

    const port = this.io.serverSocket.address().port
    if (port !== this.port) return null

    return {
      host: this.host,
      port
    }
  }

  addNode({ host, port }) {
    this._addNode({
      id: peer.id(host, port),
      port,
      host,
      token: null,
      to: null,
      sampled: 0,
      added: this._tick,
      pinged: 0,
      seen: 0,
      downHints: 0,
      prev: null,
      next: null
    })
  }

  toArray(opts) {
    const limit = opts && opts.limit
    if (limit === 0) return []
    return this.nodes.toArray({ limit, reverse: true }).map(({ host, port }) => ({ host, port }))
  }

  async fullyBootstrapped() {
    return this._bootstrapping
  }

  ready() {
    // Deprecating, use fullyBootstrapped instead (removed on next major)
    return this.fullyBootstrapped()
  }

  findNode(target, opts) {
    if (this.destroyed) throw new Error('Node destroyed')
    this._refreshTicks = REFRESH_TICKS
    return new Query(this, target, true, FIND_NODE, null, opts)
  }

  query({ target, command, value }, opts) {
    if (this.destroyed) throw new Error('Node destroyed')
    this._refreshTicks = REFRESH_TICKS
    return new Query(this, target, false, command, value || null, opts)
  }

  ping({ host, port }, opts) {
    let value = null

    if (opts && opts.size && opts.size > 0) value = b4a.alloc(opts.size)

    const req = this.io.createRequest(
      { id: null, host, port },
      null,
      true,
      PING,
      null,
      value,
      (opts && opts.session) || null,
      opts && opts.ttl
    )
    return this._requestToPromise(req, opts)
  }

  delayedPing({ host, port }, delayMs, opts) {
    if (delayMs > this.maxPingDelay) {
      throw new Error(`Delay exceeds max delay: ${this.maxPingDelay}ms`)
    }

    const value = b4a.allocUnsafe(4)
    c.uint32.encode({ start: 0, end: 4, buffer: value }, delayMs)

    const req = this.io.createRequest(
      { id: null, host, port },
      null,
      true,
      DELAYED_PING,
      null,
      value,
      (opts && opts.session) || null,
      opts && opts.ttl
    )
    // add 1 second to the timeout to account for network overhead
    req.timeout = delayMs + 1_000
    return this._requestToPromise(req, opts)
  }

  async rttStats() {
    const stats = {
      successes: 0,
      errors: 0,
      responses: {
        avgRtt: 0,
        errors: 0,
        avgCloserNodes: 0
      },
      closestReplies: {
        avgRtt: 0,
        errors: 0,
        avgCloserNodes: 0
      }
    }

    if (this.nodes.latest) {
      const q = this.findNode(this.nodes.latest.id)

      let responseCount = 0
      let closestCount = 0

      for await (const msg of q) {
        stats.responses.avgRtt += msg.rtt
        stats.responses.errors += msg.error
        stats.responses.avgCloserNodes += msg.closerNodes?.length || 0
        responseCount++
      }
      stats.responses.avgRtt /= responseCount
      stats.responses.avgCloserNodes /= responseCount

      for await (const msg of q.closestReplies) {
        stats.closestReplies.avgRtt += msg.rtt
        stats.closestReplies.errors += msg.error
        stats.closestReplies.avgCloserNodes += msg.closerNodes?.length || 0
        closestCount++
      }
      stats.closestReplies.avgRtt /= closestCount
      stats.closestReplies.avgCloserNodes /= closestCount

      stats.successes = q.successes
      stats.errors = q.errors
    }

    return stats
  }

  request({ token = null, command, target = null, value = null }, { host, port }, opts) {
    const req = this.io.createRequest(
      { id: null, host, port },
      token,
      false,
      command,
      target,
      value,
      (opts && opts.session) || null,
      opts && opts.ttl
    )
    return this._requestToPromise(req, opts)
  }

  session() {
    return new Session(this)
  }

  _requestToPromise(req, opts) {
    if (req === null) return Promise.reject(new Error('Node destroyed'))

    if (opts && opts.socket) req.socket = opts.socket
    if (opts && opts.retry === false) req.retries = 0

    return new Promise((resolve, reject) => {
      req.onresponse = resolve
      req.onerror = reject
      req.send()
    })
  }

  async _bootstrap() {
    const self = this

    await Promise.resolve() // wait a tick, so apis can be used from the outside
    await this.io.bind()

    this.emit('listening')

    // TODO: some papers describe more advanced ways of bootstrapping - we should prob look into that

    let first = this.firewalled && this._quickFirewall && !this._forcePersistent
    let testNat = false

    const onlyFirewall = !this._forcePersistent

    for (let i = 0; i < 2; i++) {
      await this._backgroundQuery(this.table.id).on('data', ondata).finished()

      if (this.bootstrapped || (!testNat && !this._forcePersistent)) break
      if (!(await this._updateNetworkState(onlyFirewall))) break
    }

    if (this.bootstrapped) return
    this.bootstrapped = true

    this.emit('ready')

    function ondata(data) {
      // Simple QUICK nat heuristic.
      // If we get ONE positive nat ping before the bootstrap query finishes
      // then we always to a nat test, no matter if we are adaptive...
      // This should be expanded in the future to try more than one node etc, not always hit the first etc
      // If this fails, then nbd, as the onstable hook will pick it up later.

      if (!first) return
      first = false

      const value = b4a.allocUnsafe(2)
      c.uint16.encode({ start: 0, end: 2, buffer: value }, self.io.serverSocket.address().port)

      self._request(
        data.from,
        false,
        true,
        PING_NAT,
        null,
        value,
        null,
        () => {
          testNat = true
        },
        noop
      )
    }
  }

  refresh() {
    const node = this.table.random()
    this._backgroundQuery(node ? node.id : this.table.id).on('error', noop)
  }

  async destroy() {
    const emitClose = !this.destroyed
    this.destroyed = true
    clearInterval(this._tickInterval)
    for (const timer of this._pendingTimers) {
      clearTimeout(timer)
    }
    await this.io.destroy()
    if (emitClose) this.emit('close')
  }

  _request(to, force, internal, command, target, value, session, onresponse, onerror) {
    if (internal && !this._sendDownHints && command === DOWN_HINT) return null
    const req = this.io.createRequest(to, null, internal, command, target, value, session)
    if (req === null) return null

    req.onresponse = onresponse
    req.onerror = onerror
    req.send(force)

    return req
  }

  _natAdd(host, port) {
    const prevHost = this._nat.host
    const prevPort = this._nat.port

    this._nat.add(host, port)

    if (prevHost === this._nat.host && prevPort === this._nat.port) return

    this.emit('nat-update', this._nat.host, this._nat.port)
  }

  // we don't check that this is a bootstrap node but we limit the sample size to very few nodes, so fine
  _sampleBootstrapMaybe(from, to) {
    if (this._nonePersistentSamples.length >= Math.max(1, this.bootstrapNodes.length)) return
    const id = from.host + ':' + from.port
    if (this._nonePersistentSamples.indexOf(id) > -1) return
    this._nonePersistentSamples.push(id)
    this._natAdd(to.host, to.port)
  }

  _addNodeFromNetwork(sample, from, to) {
    if (this._filterNode !== null && !this._filterNode(from)) {
      return
    }

    if (from.id === null) {
      this._sampleBootstrapMaybe(from, to)
      return
    }

    const oldNode = this.table.get(from.id)

    // refresh it, if we've seen this before
    if (oldNode) {
      if (sample && (oldNode.sampled === 0 || this._tick - oldNode.sampled >= OLD_NODE)) {
        oldNode.to = to
        oldNode.sampled = this._tick
        this._natAdd(to.host, to.port)
      }

      oldNode.pinged = oldNode.seen = this._tick
      this.nodes.add(oldNode)
      return
    }

    this._addNode({
      id: from.id,
      port: from.port,
      host: from.host,
      to,
      sampled: 0,
      added: this._tick,
      pinged: this._tick, // last time we interacted with them
      seen: this._tick, // last time we heard from them
      downHints: 0,
      prev: null,
      next: null
    })
  }

  _addNode(node) {
    if (this.nodes.has(node) || b4a.equals(node.id, this.table.id)) return

    node.added = node.pinged = node.seen = this._tick

    if (!this.table.add(node)) return
    this.nodes.add(node)

    if (node.to && node.sampled === 0) {
      node.sampled = this._tick
      this._natAdd(node.to.host, node.to.port)
    }

    this.emit('add-node', node)
  }

  _removeStaleNode(node, lastSeen) {
    if (node.seen <= lastSeen) this._removeNode(node)
  }

  _removeNode(node) {
    if (!this.nodes.has(node)) return

    this.table.remove(node.id)
    this.nodes.remove(node)

    this.emit('remove-node', node)
  }

  _onwakeup() {
    this._tick += 2 * OLD_NODE // bump the tick enough that everything appears old.
    this._tick += 8 - (this._tick & 7) - 2 // triggers a series of pings in two ticks
    this._stableTicks = MORE_STABLE_TICKS
    this._refreshTicks = 1 // triggers a refresh next tick (allow network time to wake up also)
    this._lastHost = null // clear network cache check
    this.health.reset()

    if (this.adaptive) {
      // TODO: re-enable this as soon as we find out why this is over triggering in some edge cases
      // this.firewalled = true
      // this.io.firewalled = true

      if (!this.ephemeral) {
        this.ephemeral = true
        this.io.ephemeral = true
        this.emit('ephemeral')
      }
    }

    this.emit('wakeup')
  }

  _onfullrow(newNode, row) {
    if (!this.bootstrapped || this._repinging >= 3) return

    let oldest = null
    for (const node of row.nodes) {
      if (node.pinged === this._tick) continue
      if (
        oldest === null ||
        oldest.pinged > node.pinged ||
        (oldest.pinged === node.pinged && oldest.added > node.added)
      ) {
        oldest = node
      }
    }

    if (oldest === null) return
    if (this._tick - oldest.pinged < RECENT_NODE && this._tick - oldest.added > OLD_NODE) return

    this._repingAndSwap(newNode, oldest)
  }

  _onnetworkchange(interfaces) {
    this.emit('network-change', interfaces)
    this.emit('network-update')
  }

  _repingAndSwap(newNode, oldNode) {
    const self = this
    const lastSeen = oldNode.seen

    oldNode.pinged = this._tick

    this._repinging++
    this._request(
      { id: null, host: oldNode.host, port: oldNode.port },
      false,
      true,
      PING,
      null,
      null,
      null,
      onsuccess,
      onswap
    )

    function onsuccess(m) {
      if (oldNode.seen <= lastSeen) return onswap()
      self._repinging--
    }

    function onswap(e) {
      self._repinging--
      self._removeNode(oldNode)
      self._addNode(newNode)
    }
  }

  _onrequest(req, external) {
    if (req.from.id !== null) {
      this._addNodeFromNetwork(!external, req.from, req.to)
    }

    if (req.internal) {
      switch (req.command) {
        // standard keep alive call
        case PING: {
          req.sendReply(0, null, false, false)
          return
        }
        case DELAYED_PING: {
          this._ondelayedping(req)
          return
        }
        // check if the other side can receive a message to their other socket
        case PING_NAT: {
          if (req.value === null || req.value.byteLength < 2) return
          const port = c.uint16.decode({ start: 0, end: 2, buffer: req.value })
          if (port === 0) return
          req.from.port = port
          req.sendReply(0, null, false, false)
          return
        }
        // empty dht reply back
        case FIND_NODE: {
          if (!req.target) return
          req.sendReply(0, null, false, true)
          return
        }
        // "this is node you sent me is down" - let's try to ping it
        case DOWN_HINT: {
          if (req.value === null || req.value.byteLength < 6) return
          if (this._checks < 10) {
            sodium.crypto_generichash(TMP, req.value.subarray(0, 6))
            const node = this.table.get(TMP)
            if (node && (node.pinged < this._tick || node.downHints === 0)) {
              node.downHints++
              this._check(node)
            }
          }
          req.sendReply(0, null, false, false)
          return
        }
      }

      req.sendReply(UNKNOWN_COMMAND, null, false, req.target !== null)
      return
    }

    // ask the user to handle it or reply back with a bad command
    if (this.onrequest(req) === false) {
      req.sendReply(UNKNOWN_COMMAND, null, false, req.target !== null)
    }
  }

  onrequest(req) {
    return this.emit('request', req)
  }

  _ondelayedping(req) {
    if (req.value === null || req.value.byteLength < 4) return
    const delayMs = c.uint32.decode({ start: 0, end: 4, buffer: req.value })
    if (delayMs > this.maxPingDelay) return
    const timer = setTimeout(() => {
      if (this.destroyed) return
      this._pendingTimers.delete(timer)
      req.sendReply(0, null, false, false)
    }, delayMs)
    this._pendingTimers.add(timer)
  }

  _onresponse(res, external) {
    this._addNodeFromNetwork(!external, res.from, res.to)
  }

  _ontimeout(req) {
    if (!req.to.id) return
    const node = this.table.get(req.to.id)
    if (node) this._removeNode(node)
  }

  _pingSome() {
    let cnt = this.io.inflight.length > 2 ? 3 : 5
    let oldest = this.nodes.oldest

    // tiny dht, pinged the bootstrap again
    if (!oldest) {
      this.refresh()
      return
    }

    // we've recently pinged the oldest one, so only trigger a couple of repings
    if (this._tick - oldest.pinged < RECENT_NODE) {
      cnt = 2
    }

    while (cnt--) {
      if (!oldest || this._tick === oldest.pinged) continue
      this._check(oldest)
      oldest = oldest.next
    }
  }

  _check(node) {
    node.pinged = this._tick

    const lastSeen = node.seen
    const onresponse = () => {
      this._checks--
      this._removeStaleNode(node, lastSeen)
    }
    const onerror = () => {
      this._checks--
      this._removeNode(node)
    }

    this._checks++
    this._request(
      { id: null, host: node.host, port: node.port },
      false,
      true,
      PING,
      null,
      null,
      null,
      onresponse,
      onerror
    )
  }

  _ontick() {
    const time = Date.now()

    if (time - this._lastTick > SLEEPING_INTERVAL && this.suspended === false) {
      this._onwakeup()
    } else {
      this._tick++
    }

    this._lastTick = time

    if (!this.bootstrapped || this.suspended) return

    if (this.adaptive && this.ephemeral && --this._stableTicks <= 0) {
      if (this._lastHost === this._nat.host) {
        // do not recheck the same network...
        this._stableTicks = MORE_STABLE_TICKS
      } else {
        this._updateNetworkState() // the promise returned here never fails so just ignore it
      }
    }

    if ((this._tick & 7) === 0) {
      this._pingSome()
    }

    if (
      ((this._tick & 63) === 0 && this.nodes.length < this.table.k) ||
      --this._refreshTicks <= 0
    ) {
      this.refresh()
    }

    this._downHintsSentPerTick = 0
    this.health.update()
  }

  async _updateNetworkState(onlyFirewall = false) {
    if (!this.ephemeral) return false
    if (onlyFirewall && !this.firewalled) return false

    const { host, port } = this._nat

    if (!onlyFirewall) {
      // remember what host we checked and reset the counter
      this._stableTicks = MORE_STABLE_TICKS
      this._lastHost = host
    }

    // check if we have a consistent host and port
    if (host === null || port === 0) {
      return false
    }

    const natSampler = this.firewalled ? new NatSampler() : this._nat

    // ask remote nodes to ping us on our server socket to see if we have the port open
    const firewalled = this.firewalled && (await this._checkIfFirewalled(natSampler))
    if (firewalled) return false

    this.firewalled = this.io.firewalled = false

    // incase it's called in parallel for some reason, or if our nat status somehow changed
    if (!this.ephemeral || host !== this._nat.host || port !== this._nat.port) return false
    // if the firewall probe returned a different host / non consistent port, bail as well
    if (natSampler.host !== host || natSampler.port === 0) return false

    const id = peer.id(natSampler.host, natSampler.port)

    if (!onlyFirewall) {
      this.ephemeral = this.io.ephemeral = false
    }

    if (natSampler !== this._nat) {
      const prevHost = this._nat.host
      const prevPort = this._nat.port

      this._nonePersistentSamples = []
      this._nat = natSampler

      if (prevHost !== this._nat.host || prevPort !== this._nat.port) {
        this.emit('nat-update', this._nat.host, this._nat.port)
      }
    }

    // TODO: we should make this a bit more defensive in terms of using more
    // resources to make sure that the new routing table contains as many alive nodes
    // as possible, vs blindly copying them over...

    // all good! copy over the old routing table to the new one
    if (!b4a.equals(this.table.id, id)) {
      const nodes = this.table.toArray()

      this.table = this.io.table = new Table(id)

      for (const node of nodes) {
        if (b4a.equals(node.id, id)) continue
        if (!this.table.add(node)) this.nodes.remove(node)
      }

      this.table.on('row', this._onrow)

      // we need to rebootstrap/refresh since we updated our id
      if (this.bootstrapped) this.refresh()
    }

    if (!this.ephemeral) {
      this.emit('persistent')
    }

    return true
  }

  async *_resolveBootstrapNodes() {
    for (let { host, port } of this.bootstrapNodes) {
      let doLookup = false

      if (host.indexOf('@') === -1) {
        doLookup = true
      } else {
        const [suggestedIP, fallbackHost] = host.split('@')
        try {
          await this.ping({ host: suggestedIP, port })
          host = suggestedIP
        } catch {
          host = fallbackHost
          doLookup = true
        }
      }

      if (doLookup) {
        try {
          host = UDX.isIPv4(host) ? host : (await this.udx.lookup(host, { family: 4 })).host
        } catch {
          continue
        }
      }

      yield {
        id: peer.id(host, port),
        host,
        port
      }
    }
  }

  async _addBootstrapNodes(nodes) {
    for await (const node of this._resolveBootstrapNodes()) {
      nodes.push(node)
    }
  }

  async _checkIfFirewalled(natSampler = new NatSampler()) {
    const nodes = []
    for (let node = this.nodes.latest; node && nodes.length < 5; node = node.prev) {
      nodes.push(node)
    }

    if (nodes.length < 5) await this._addBootstrapNodes(nodes)
    // if no nodes are available, including bootstrappers - bail
    if (nodes.length === 0) return true

    const hosts = new Set()
    const value = b4a.allocUnsafe(2)

    c.uint16.encode({ start: 0, end: 2, buffer: value }, this.io.serverSocket.address().port)

    // double check they actually came on the server socket...
    this.io.serverSocket.on('message', onmessage)

    const pongs = await requestAll(this, true, PING_NAT, value, nodes)

    let count = 0
    for (const res of pongs) {
      if (hosts.has(res.from.host)) {
        count++
        natSampler.add(res.to.host, res.to.port)
      }
    }

    this.io.serverSocket.removeListener('message', onmessage)

    // if we got no or very few replies, consider it a fluke
    if (count < (nodes.length >= 5 ? 3 : 1)) return true

    // check that the server socket has the same ip as the client socket
    if (natSampler.host === null || this._nat.host !== natSampler.host) return true

    // check that the local port of the server socket is the same as the remote port
    // TODO: we might want a flag to opt out of this heuristic for specific remapped port servers
    if (natSampler.port === 0 || natSampler.port !== this.io.serverSocket.address().port) {
      return true
    }

    return false

    function onmessage(_, { host }) {
      hosts.add(host)
    }
  }

  _backgroundQuery(target) {
    this._refreshTicks = REFRESH_TICKS

    const backgroundCon = Math.min(this.concurrency, Math.max(2, (this.concurrency / 8) | 0))
    const q = new Query(this, target, true, FIND_NODE, null, {
      concurrency: backgroundCon
    })

    q.on('data', () => {
      // yield to other traffic
      q.concurrency = this.io.inflight.length < 3 ? this.concurrency : backgroundCon
    })

    return q
  }

  // called by health
  _online() {
    if (this.online && !this.degraded) return
    this.online = true
    this.degraded = false
    this.emit('network-update')
  }

  // called by health
  _degraded() {
    if (this.degraded) return
    this.online = true
    this.degraded = true
    this.emit('network-update')
  }

  // called by health
  _offline() {
    if (!this.online) return
    this.online = false
    this.degraded = false
    this.emit('network-update')
  }
}

DHT.OK = 0
DHT.ERROR_UNKNOWN_COMMAND = UNKNOWN_COMMAND
DHT.ERROR_INVALID_TOKEN = INVALID_TOKEN

module.exports = DHT

function localIP(udx, family = 4) {
  let host = null

  for (const n of udx.networkInterfaces()) {
    if (n.family !== family || n.internal) continue

    // mac really likes en0, mb a better way but this shouldnt be bad anywhere so return now
    if (n.name === 'en0') return n.host

    // otherwise pick the first non internal host (let the loop continue in case we see en0)
    if (host === null) host = n.host
  }

  return host || (family === 4 ? '127.0.0.1' : '::1')
}

function parseNode(s) {
  if (typeof s === 'object') return s
  if (typeof s === 'number') return { host: '127.0.0.1', port: s }
  const [host, port] = s.split(':')
  if (!port) throw new Error('Bootstrap node format is host:port')

  return {
    host,
    port: Number(port)
  }
}

function randomBytes(n) {
  const b = b4a.alloc(n)
  sodium.randombytes_buf(b)
  return b
}

function randomOffset(n) {
  return n - ((Math.random() * 0.5 * n) | 0)
}

function requestAll(dht, internal, command, value, nodes) {
  let missing = nodes.length
  const replies = []

  return new Promise((resolve) => {
    for (const node of nodes) {
      const req = dht._request(
        node,
        false,
        internal,
        command,
        null,
        value,
        null,
        onsuccess,
        onerror
      )
      if (!req) return resolve(replies)
    }

    function onsuccess(res) {
      replies.push(res)
      if (--missing === 0) resolve(replies)
    }

    function onerror() {
      if (--missing === 0) resolve(replies)
    }
  })
}

function noop() {}
exports.PING = 0
exports.PING_NAT = 1
exports.FIND_NODE = 2
exports.DOWN_HINT = 3
exports.DELAYED_PING = 4
module.exports = class DHTError extends Error {
  constructor(msg, code, fn = DHTError) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'DHTError'
  }

  static UNKNOWN_COMMAND = 1
  static INVALID_TOKEN = 2

  static REQUEST_TIMEOUT(msg = 'Request timed out') {
    return new DHTError(msg, 'REQUEST_TIMEOUT', DHTError.REQUEST_TIMEOUT)
  }

  static REQUEST_DESTROYED(msg = 'Request destroyed') {
    return new DHTError(msg, 'REQUEST_DESTROYED', DHTError.REQUEST_DESTROYED)
  }

  static IO_SUSPENDED(msg = 'I/O suspended') {
    return new DHTError(msg, 'IO_SUSPENDED', DHTError.IO_SUSPENDED)
  }
}
const MAX_HEALTH_WINDOW = 4
const OFFLINE_THRESHOLD = 2
const IDLE_THRESHOLD = 4
const DEGRADED_TIMEOUT_RATE_THRESHOLD = 0.5

module.exports = class NetworkHealth {
  constructor(dht) {
    this._dht = dht
    this._window = []
    this._head = -1
    this._offlineTicks = 0
    this._degradedTicks = 0
    this._healthyTicks = 0
    this.online = true
    this.degraded = false
  }

  get oldest() {
    return this._window[this._tail]
  }

  get previous() {
    return this._window[(this._head - 1 + MAX_HEALTH_WINDOW) % MAX_HEALTH_WINDOW]
  }

  get newest() {
    return this._window[this._head]
  }

  get responses() {
    if (!this.newest || !this.previous) return 0
    return this.newest.responses - this.previous.responses
  }

  get timeouts() {
    if (!this.newest || !this.previous) return 0
    return this.newest.timeouts - this.previous.timeouts
  }

  get timeoutsRate() {
    if (this.timeouts === 0) return 0
    return this.timeouts / (this.responses + this.timeouts)
  }

  get cold() {
    return this._window.length < MAX_HEALTH_WINDOW
  }

  get idle() {
    return this.responses + this.timeouts < IDLE_THRESHOLD
  }

  get stats() {
    return {
      online: this.online,
      degraded: this.degraded,
      cold: this.cold,
      idle: this.idle,
      responses: this.responses,
      timeouts: this.timeouts,
      timeoutsRate: this.timeoutsRate
    }
  }

  get _tail() {
    return (this._head + 1) % MAX_HEALTH_WINDOW
  }

  reset() {
    this._window = []
    this._head = -1
    this._offlineTicks = 0
    this._degradedTicks = 0
    this._healthyTicks = 0
    this.online = true
    this.degraded = false
    this._dht._online()
  }

  update() {
    // update counters before dropping oldest
    if (this.oldest?.degraded) this._degradedTicks--
    else if (this.oldest?.degraded === false) this._healthyTicks--

    // move window
    this._head = this._tail
    this._window[this._head] = {
      responses: this._dht.stats.requests.responses,
      timeouts: this._dht.stats.requests.timeouts
    }

    // skip state changes
    if (this.cold || this.idle) return

    // update newest
    this.newest.offline = this.responses === 0
    this.newest.degraded =
      !this.newest.offline && this.timeoutsRate > DEGRADED_TIMEOUT_RATE_THRESHOLD

    // update counters
    if (this.newest.offline) this._offlineTicks++
    else {
      this._offlineTicks = 0
      if (this.newest.degraded) this._degradedTicks++
      else this._healthyTicks++
    }

    // check online/offline
    if (!this.newest.offline) this.online = true
    else if (this._offlineTicks >= OFFLINE_THRESHOLD) this.online = false

    // check degraded
    if (!this.online || this._healthyTicks === MAX_HEALTH_WINDOW) this.degraded = false
    else if (this._degradedTicks === MAX_HEALTH_WINDOW) this.degraded = true

    // fire events
    if (this.online && !this.degraded) this._dht._online()
    else if (this.degraded) this._dht._degraded()
    else this._dht._offline()
  }
}
const FIFO = require('fast-fifo')
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const b4a = require('b4a')
const AdaptiveTimeout = require('adaptive-timeout')
const peer = require('./peer')
const { INVALID_TOKEN, REQUEST_TIMEOUT, REQUEST_DESTROYED, IO_SUSPENDED } = require('./errors')

const VERSION = 0b11
const RESPONSE_ID = (0b0001 << 4) | VERSION
const REQUEST_ID = (0b0000 << 4) | VERSION
const EMPTY_ARRAY = []
const MAX_WINDOW = 80

module.exports = class IO {
  constructor(
    table,
    udx,
    {
      maxWindow = MAX_WINDOW,
      port = 0,
      host = '0.0.0.0',
      anyPort = true,
      firewalled = true,
      onrequest,
      onresponse = noop,
      ontimeout = noop,
      adaptiveTimeout
    } = {}
  ) {
    this.table = table
    this.udx = udx
    this.inflight = []
    this.clientSocket = null
    this.serverSocket = null
    this.firewalled = firewalled !== false
    this.ephemeral = true
    this.congestion = new CongestionWindow(maxWindow)
    this.networkInterfaces = udx.watchNetworkInterfaces()
    this.suspended = false

    this.stats = {
      requests: {
        active: 0,
        total: 0,
        responses: 0,
        timeouts: 0,
        retries: 0
      },
      commands: [
        { tx: 0, rx: 0 }, // tx = transmitted, rx = received
        { tx: 0, rx: 0 },
        { tx: 0, rx: 0 },
        { tx: 0, rx: 0 }
      ]
    }

    this.onrequest = onrequest
    this.onresponse = onresponse
    this.ontimeout = ontimeout

    this._pending = new FIFO()
    this._rotateSecrets = 10
    this._tid = (Math.random() * 65536) | 0
    this._secrets = null
    this._drainInterval = null
    this._destroying = null
    this._binding = null

    // port can be a number or a range [start, to]
    this.portRange = port.length ? port : port === 0 ? [0, 0] : [port, port + 5]

    this._host = host
    this._anyPort = anyPort !== false
    this._boundServerPort = 0
    this._boundClientPort = 0

    this._adt = adaptiveTimeout ? new AdaptiveTimeout(adaptiveTimeout) : null
  }

  static DEFAULT_MAX_WINDOW = MAX_WINDOW

  onmessage(socket, buffer, { host, port }) {
    if (buffer.byteLength < 2 || !(port > 0 && port < 65536) || this.suspended === true) return

    const from = { id: null, host, port }
    const state = { start: 1, end: buffer.byteLength, buffer }
    const expectedSocket = this.firewalled ? this.clientSocket : this.serverSocket
    const external = socket !== expectedSocket

    if (buffer[0] === REQUEST_ID) {
      const req = Request.decode(this, socket, from, state)
      if (req === null) return
      if (
        req.token !== null &&
        !b4a.equals(req.token, this.token(req.from, 1)) &&
        !b4a.equals(req.token, this.token(req.from, 0))
      ) {
        req.error(INVALID_TOKEN, { token: true })
        return
      }
      this.onrequest(req, external)
      return
    }

    if (buffer[0] === RESPONSE_ID) {
      const res = decodeReply(from, state)
      if (res === null) return

      for (let i = 0; i < this.inflight.length; i++) {
        const req = this.inflight[i]
        if (req.tid !== res.tid) continue

        res.rtt = Date.now() - req._timestamp

        if (this._adt && req.sent <= 2) {
          this._adt.put(`${req.to.host}:${req.to.port}`, res.rtt)
        }

        if (i === this.inflight.length - 1) this.inflight.pop()
        else this.inflight[i] = this.inflight.pop()

        if (req.session) req.session._detach(req)

        // TODO: Auto retry here if errors.INVALID_TOKEN is returned?

        if (req._timeout) {
          clearTimeout(req._timeout)
          req._timeout = null
        }

        this.congestion.recv()

        if (req.internal && req.command < this.stats.commands.length) {
          this.stats.commands[req.command].rx++
        }

        this.stats.requests.active--
        this.stats.requests.responses++

        this.onresponse(res, external)
        req.onresponse(res, req)
        break
      }
    }
  }

  token(addr, i) {
    if (this._secrets === null) {
      const buf = b4a.alloc(64)
      this._secrets = [buf.subarray(0, 32), buf.subarray(32, 64)]
      sodium.randombytes_buf(this._secrets[0])
      sodium.randombytes_buf(this._secrets[1])
    }

    const token = b4a.allocUnsafe(32)
    sodium.crypto_generichash(token, b4a.from(addr.host), this._secrets[i])
    return token
  }

  async destroy() {
    if (this._destroying) return this._destroying
    this._destroying = this._destroy()
    return this._destroying
  }

  async _destroy() {
    // simplifies timing to await the bind here also, although it might be unneeded
    await this.bind()
    await this._clear(false)
  }

  async _clear(suspended) {
    if (this._drainInterval) {
      clearInterval(this._drainInterval)
      this._drainInterval = null
    }

    while (this.inflight.length) {
      const req = this.inflight.pop()
      if (req._timeout) clearTimeout(req._timeout)
      req._timeout = null
      req.destroyed = true

      if (req.session) req.session._detach(req)

      this.congestion.recv()
      this.stats.requests.active--

      req.onerror(suspended ? IO_SUSPENDED() : REQUEST_DESTROYED(), req)
    }

    await Promise.allSettled([this.serverSocket.close(), this.clientSocket.close()])

    this.networkInterfaces.destroy()
  }

  async suspend() {
    this.suspended = true
    await this._clear(true)

    this.congestion.clear()

    if (this._drainInterval) {
      clearInterval(this._drainInterval)
      this._drainInterval = null
    }
  }

  async _rebind(binding) {
    if (binding) await binding
    if (this._destroying) return this._destroying
    await this._bindSockets()
    this.networkInterfaces = this.udx.watchNetworkInterfaces()
  }

  resume() {
    this.suspended = false
    const binding = this._binding
    this._binding = this._rebind(binding)
    return this._binding
  }

  bind() {
    if (this._binding) return this._binding
    this._binding = this._bindSockets()
    return this._binding
  }

  async _bindSockets() {
    const serverSocket = this.udx.createSocket()

    const candidatePorts = []

    // Retrying previous port always has precedence
    if (this._boundServerPort) candidatePorts.push(this._boundServerPort)

    for (let i = this.portRange[0]; i < this.portRange[1]; i++) candidatePorts.push(i)

    for (const port of candidatePorts) {
      if (serverSocket.bound) break

      try {
        serverSocket.bind(port, this._host)
      } catch (err) {
        if (!this._anyPort) {
          await serverSocket.close()
          throw err
        }
      }
    }

    if (!serverSocket.bound) {
      try {
        serverSocket.bind(0, this._host)
      } catch (err) {
        await serverSocket.close()
        throw err
      }
    }

    const clientSocket = this.udx.createSocket()

    try {
      clientSocket.bind(this._boundClientPort || 0, this._host)
    } catch {
      try {
        clientSocket.bind(0, this._host)
      } catch (err) {
        await serverSocket.close()
        await clientSocket.close()
        throw err
      }
    }

    this._boundServerPort = serverSocket.address().port
    this._boundClientPort = clientSocket.address().port

    this.clientSocket = clientSocket
    this.serverSocket = serverSocket

    this.serverSocket.on('message', this.onmessage.bind(this, this.serverSocket))
    this.clientSocket.on('message', this.onmessage.bind(this, this.clientSocket))

    if (this._drainInterval === null) {
      this._drainInterval = setInterval(this._drain.bind(this), 750)
      if (this._drainInterval.unref) this._drainInterval.unref()
    }

    for (const req of this.inflight) {
      if (!req.socket) req.socket = this.firewalled ? this.clientSocket : this.serverSocket
      req.sent = 0
      req.send(false)
    }
  }

  _drain() {
    if (this._secrets !== null && --this._rotateSecrets === 0) {
      this._rotateSecrets = 10
      const tmp = this._secrets[0]
      this._secrets[0] = this._secrets[1]
      this._secrets[1] = tmp
      sodium.crypto_generichash(tmp, tmp)
    }

    this.congestion.drain()

    while (!this.congestion.isFull()) {
      const p = this._pending.shift()
      if (p === undefined) return
      p._sendNow()
    }
  }

  createRequest(to, token, internal, command, target, value, session, ttl) {
    if (this._destroying !== null) return null

    if (this._tid === 65536) this._tid = 0

    const tid = this._tid++
    const socket = this.firewalled ? this.clientSocket : this.serverSocket

    const req = new Request(
      this,
      socket,
      tid,
      null,
      to,
      token,
      internal,
      command,
      target,
      value,
      session,
      ttl || 0
    )
    this.inflight.push(req)
    if (session) session._attach(req)

    if (internal && command < this.stats.commands.length) {
      this.stats.commands[command].tx++
    }

    this.stats.requests.active++
    this.stats.requests.total++

    return req
  }
}

class Request {
  constructor(io, socket, tid, from, to, token, internal, command, target, value, session, ttl) {
    this.socket = socket
    this.tid = tid
    this.from = from
    this.to = to
    this.token = token
    this.command = command
    this.target = target
    this.value = value
    this.internal = internal
    this.session = session
    this.ttl = ttl
    this.index = -1
    this.sent = 0
    this.retries = 3
    this.destroyed = false
    this.timeout = 0

    this.oncycle = noop
    this.onerror = noop
    this.onresponse = noop

    this._buffer = null
    this._io = io
    this._timeout = null
    this._timestamp = Date.now()
  }

  static decode(io, socket, from, state) {
    try {
      const flags = c.uint.decode(state)
      const tid = c.uint16.decode(state)
      const to = peer.ipv4.decode(state)
      const id = flags & 1 ? c.fixed32.decode(state) : null
      const token = flags & 2 ? c.fixed32.decode(state) : null
      const internal = (flags & 4) !== 0
      const command = c.uint.decode(state)
      const target = flags & 8 ? c.fixed32.decode(state) : null
      const value = flags & 16 ? c.buffer.decode(state) : null

      if (id !== null) from.id = validateId(id, from)

      return new Request(
        io,
        socket,
        tid,
        from,
        to,
        token,
        internal,
        command,
        target,
        value,
        null,
        0
      )
    } catch {
      return null
    }
  }

  reply(value, opts = {}) {
    const socket = opts.socket || this.socket
    const to = opts.to || this.from
    this._sendReply(0, value || null, opts.token !== false, opts.closerNodes !== false, to, socket)
  }

  error(code, opts = {}) {
    const socket = opts.socket || this.socket
    const to = opts.to || this.from
    this._sendReply(code, null, opts.token === true, opts.closerNodes !== false, to, socket)
  }

  relay(value, to, opts) {
    const socket = (opts && opts.socket) || this.socket
    const buffer = this._encodeRequest(null, value, to, socket)
    socket.trySend(buffer, to.port, to.host, this.ttl)
  }

  send(force = false) {
    if (this.destroyed) return

    if (this.socket === null) return
    if (this._buffer === null) {
      this._buffer = this._encodeRequest(this.token, this.value, this.to, this.socket)
    }

    if (!force && this._io.congestion.isFull()) {
      this._io._pending.push(this)
      return
    }

    this._sendNow()
  }

  sendReply(error, value, token, hasCloserNodes) {
    this._sendReply(error, value, token, hasCloserNodes, this.from, this.socket, null)
  }

  _sendNow() {
    if (this.destroyed) return
    this.sent++
    this._io.congestion.send()
    this.socket.trySend(this._buffer, this.to.port, this.to.host, this.ttl)
    if (this._timeout) clearTimeout(this._timeout)
    const value =
      this.timeout || this._io._adt?.get(`${this.to.host}:${this.to.port}`, this.sent) || 1000
    this._timeout = setTimeout(oncycle, value, this)
  }

  destroy(err) {
    if (this.destroyed) return
    this.destroyed = true

    if (this._timeout) {
      clearTimeout(this._timeout)
      this._timeout = null
    }

    const i = this._io.inflight.indexOf(this)
    if (i === -1) return

    if (i === this._io.inflight.length - 1) this._io.inflight.pop()
    else this._io.inflight[i] = this._io.inflight.pop()

    if (this.session) this.session._detach(this)

    this._io.stats.requests.active--
    this._io.congestion.recv()

    this.onerror(err || REQUEST_DESTROYED(), this)
  }

  _sendReply(error, value, token, hasCloserNodes, from, socket) {
    if (socket === null || this.destroyed) return

    const id = this._io.ephemeral === false && socket === this._io.serverSocket
    const closerNodes =
      this.target !== null && hasCloserNodes ? this._io.table.closest(this.target) : EMPTY_ARRAY
    const state = { start: 0, end: 1 + 1 + 6 + 2, buffer: null } // (type | version) + flags + to + tid

    if (id) state.end += 32
    if (token) state.end += 32
    if (closerNodes.length > 0) peer.ipv4Array.preencode(state, closerNodes)
    if (error > 0) c.uint.preencode(state, error)
    if (value) c.buffer.preencode(state, value)

    state.buffer = b4a.allocUnsafe(state.end)
    state.buffer[state.start++] = RESPONSE_ID
    state.buffer[state.start++] =
      (id ? 1 : 0) |
      (token ? 2 : 0) |
      (closerNodes.length > 0 ? 4 : 0) |
      (error > 0 ? 8 : 0) |
      (value ? 16 : 0)

    c.uint16.encode(state, this.tid)
    peer.ipv4.encode(state, from)

    if (id) c.fixed32.encode(state, this._io.table.id)
    if (token) c.fixed32.encode(state, this._io.token(from, 1))
    if (closerNodes.length > 0) peer.ipv4Array.encode(state, closerNodes)
    if (error > 0) c.uint.encode(state, error)
    if (value) c.buffer.encode(state, value)

    socket.trySend(state.buffer, from.port, from.host, this.ttl)
  }

  _encodeRequest(token, value, to, socket) {
    const id = this._io.ephemeral === false && socket === this._io.serverSocket
    const state = { start: 0, end: 1 + 1 + 6 + 2, buffer: null } // (type | version) + flags + to + tid

    if (id) state.end += 32
    if (token) state.end += 32

    c.uint.preencode(state, this.command)

    if (this.target) state.end += 32
    if (value) c.buffer.preencode(state, value)

    state.buffer = b4a.allocUnsafe(state.end)
    state.buffer[state.start++] = REQUEST_ID
    state.buffer[state.start++] =
      (id ? 1 : 0) |
      (token ? 2 : 0) |
      (this.internal ? 4 : 0) |
      (this.target ? 8 : 0) |
      (value ? 16 : 0)

    c.uint16.encode(state, this.tid)
    peer.ipv4.encode(state, to)

    if (id) c.fixed32.encode(state, this._io.table.id)
    if (token) c.fixed32.encode(state, token)

    c.uint.encode(state, this.command)

    if (this.target) c.fixed32.encode(state, this.target)
    if (value) c.buffer.encode(state, value)

    return state.buffer
  }
}

class CongestionWindow {
  constructor(maxWindow) {
    this._i = 0
    this._total = 0
    this._window = [0, 0, 0, 0]
    this._maxWindow = maxWindow
  }

  clear() {
    this._i = 0
    this._total = 0
    this._window = [0, 0, 0, 0]
  }

  isFull() {
    return this._total >= 2 * this._maxWindow || this._window[this._i] >= this._maxWindow
  }

  recv() {
    if (this._window[this._i] > 0) {
      this._window[this._i]--
      this._total--
    }
  }

  send() {
    this._total++
    this._window[this._i]++
  }

  drain() {
    this._i = (this._i + 1) & 3
    this._total -= this._window[this._i]
    this._window[this._i] = 0 // clear oldest
  }
}

function noop() {}

function oncycle(req) {
  req._timeout = null
  req.oncycle(req)
  if (req.sent > req.retries) {
    req._io.stats.requests.timeouts++
    req.destroy(REQUEST_TIMEOUT())
    req._io.ontimeout(req)
  } else {
    req._io.stats.requests.retries++
    req.send()
  }
}

function decodeReply(from, state) {
  try {
    const flags = c.uint.decode(state)
    const tid = c.uint16.decode(state)
    const to = peer.ipv4.decode(state)
    const id = flags & 1 ? c.fixed32.decode(state) : null
    const token = flags & 2 ? c.fixed32.decode(state) : null
    const closerNodes = flags & 4 ? peer.ipv4Array.decode(state) : null
    const error = flags & 8 ? c.uint.decode(state) : 0
    const value = flags & 16 ? c.buffer.decode(state) : null

    if (id !== null) from.id = validateId(id, from)

    return { tid, rtt: 0, from, to, token, closerNodes, error, value }
  } catch {
    return null
  }
}

function validateId(id, from) {
  const expected = peer.id(from.host, from.port)
  return b4a.equals(expected, id) ? expected : null
}
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const b4a = require('b4a')

const ipv4 = {
  ...c.ipv4Address,
  decode(state) {
    const ip = c.ipv4Address.decode(state)
    return {
      id: null, // populated by the callee
      host: ip.host,
      port: ip.port
    }
  }
}

module.exports = { id, ipv4, ipv4Array: c.array(ipv4) }

function id(host, port, out = b4a.allocUnsafeSlow(32)) {
  const addr = out.subarray(0, 6)
  ipv4.encode({ start: 0, end: 6, buffer: addr }, { host, port })
  sodium.crypto_generichash(out, addr)
  return out
}
const { Readable, getStreamError } = require('streamx')
const b4a = require('b4a')
const peer = require('./peer')
const { DOWN_HINT } = require('./commands')

const DONE = []
const DOWN = []

module.exports = class Query extends Readable {
  constructor(dht, target, internal, command, value, opts = {}) {
    super()

    dht.stats.queries.total++
    dht.stats.queries.active++

    this.force = !!opts.force
    this.dht = dht
    this.k = this.dht.table.k
    this.target = target
    this.internal = internal
    this.command = command
    this.value = value
    this.errors = 0
    this.successes = 0
    this.concurrency = opts.concurrency || this.dht.concurrency
    this.inflight = 0
    this.map = opts.map || defaultMap
    this.retries =
      opts.retries === 0 ? 0 : opts.retries || (this.internal && command === DOWN_HINT ? 3 : 5)
    this.closestReplies = []

    this._slow = 0
    this._slowdown = false
    this._seen = new Map()
    this._pending = []
    this._fromTable = false
    this._commit = opts.commit === true ? autoCommit : opts.commit || null
    this._commiting = false
    this._session = opts.session || dht.session()
    this._autoDestroySession = !opts.session
    this._onlyClosestNodes = false

    this._onvisitbound = this._onvisit.bind(this)
    this._onerrorbound = this._onerror.bind(this)
    this._oncyclebound = this._oncycle.bind(this)

    const nodes = opts.nodes || opts.closestNodes
    const replies = opts.replies || opts.closestReplies

    // add them reverse as we pop below
    if (nodes) {
      for (let i = nodes.length - 1; i >= 0; i--) {
        const node = nodes[i]
        this._addPending(
          {
            id: node.id || peer.id(node.host, node.port),
            host: node.host,
            port: node.port
          },
          null
        )
      }
    } else if (replies) {
      for (let i = replies.length - 1; i >= 0; i--) {
        this._addPending(replies[i].from, null)
      }
    }

    if (opts.onlyClosestNodes) this._onlyClosestNodes = true
  }

  get closestNodes() {
    const nodes = new Array(this.closestReplies.length)

    for (let i = 0; i < nodes.length; i++) {
      nodes[i] = this.closestReplies[i].from
    }

    return nodes
  }

  finished() {
    return new Promise((resolve, reject) => {
      if (this.destroyed) {
        const error = getStreamError(this)
        if (error) reject(error)
        else resolve()
        return
      }

      const self = this
      let error = null

      this.resume()
      this.on('error', onerror)
      this.on('close', onclose)

      function onclose() {
        self.removeListener('error', onerror)
        self.removeListener('close', onclose)
        if (error) reject(error)
        else resolve()
      }

      function onerror(err) {
        error = err
      }
    })
  }

  _addFromTable() {
    if (this._pending.length >= this.k) return
    this._fromTable = true

    const closest = this.dht.table.closest(this.target, this.k - this._pending.length)

    for (const node of closest) {
      this._addPending({ id: node.id, host: node.host, port: node.port }, null)
    }
  }

  async _open(cb) {
    this._addFromTable()
    if (this._pending.length >= this.k) return cb(null)

    for await (const node of this.dht._resolveBootstrapNodes()) {
      this._addPending(node, null)
    }

    cb(null)
  }

  _isCloser(id) {
    return (
      this.closestReplies.length < this.k ||
      this._compare(id, this.closestReplies[this.closestReplies.length - 1].from.id) < 0
    )
  }

  _addPending(node, ref) {
    if (this._onlyClosestNodes) return false

    const addr = node.host + ':' + node.port
    const refs = this._seen.get(addr)
    const isCloser = this._isCloser(node.id)

    if (refs === DONE) {
      return isCloser
    }

    if (refs === DOWN) {
      if (ref) this._downHint(ref, node)
      return isCloser
    }

    if (refs) {
      if (ref !== null) refs.push(ref)
      return isCloser
    }

    if (!isCloser) {
      return false
    }

    this._seen.set(addr, ref === null ? [] : [ref])
    this._pending.push(node)

    return true
  }

  _read(cb) {
    this._readMore()
    cb(null)
  }

  _readMore() {
    if (this.destroying || this._commiting) return

    const concurrency = (this._slowdown ? 3 : this.concurrency) + this._slow

    while (this.inflight < concurrency && this._pending.length > 0) {
      const next = this._pending.pop()
      if (next && next.id && !this._isCloser(next.id)) continue
      this._visit(next)
    }

    // if reusing closest nodes, slow down after the first readMore tick to allow
    // the closest node a chance to reply before going broad to question more
    if (!this._fromTable && this.successes === 0 && this.errors === 0) {
      this._slowdown = true
    }

    if (this._pending.length > 0) return

    // if no inflight OR all the queries we are waiting on are marked as slow and we have a full result.
    if (
      this.inflight === 0 ||
      (this._slow === this.inflight && this.closestReplies.length >= this.k)
    ) {
      // if more than 3/4 failed and we only used cached nodes, try again from the routing table
      if (!this._fromTable && this.successes < this.k / 4) {
        this._addFromTable()
        this._readMore()
        return
      }

      this._flush()
    }
  }

  _flush() {
    if (this._commiting) return
    this._commiting = true

    if (this._commit === null) {
      this.push(null)
      return
    }

    const p = []
    for (const m of this.closestReplies) p.push(this._commit(m, this.dht, this))
    this._endAfterCommit(p)
  }

  _endAfterCommit(ps) {
    if (!ps.length) {
      this.destroy(new Error('Too few nodes responded'))
      return
    }

    const self = this

    let pending = ps.length
    let success = 0

    for (const p of ps) p.then(ondone, onerror)

    function ondone() {
      success++
      if (--pending === 0) self.push(null)
    }

    function onerror(err) {
      if (--pending > 0) return
      if (success) self.push(null)
      else self.destroy(err)
    }
  }

  _dec(req) {
    if (req.oncycle === noop) {
      this._slow--
    } else {
      req.oncycle = noop
    }
    this.inflight--
  }

  _onvisit(m, req) {
    this._dec(req)

    const addr = req.to.host + ':' + req.to.port
    this._seen.set(addr, DONE)

    if (this._commiting) return

    if (m.error === 0) this.successes++
    else this.errors++

    if (m.error === 0 && m.from.id !== null && this._isCloser(m.from.id)) this._pushClosest(m)

    if (m.closerNodes !== null) {
      for (const node of m.closerNodes) {
        node.id = peer.id(node.host, node.port)
        if (this.dht._filterNode !== null && !this.dht._filterNode(node)) continue
        if (b4a.equals(node.id, this.dht.table.id)) continue
        // TODO: we could continue here instead of breaking to ensure that one of the nodes in the closer list
        // is later marked as DOWN that we gossip that back
        if (!this._addPending(node, m.from)) break
      }
    }

    if (!this._fromTable && this.successes + this.errors >= this.concurrency) {
      this._slowdown = false
    }

    if (m.error !== 0) {
      this._readMore()
      return
    }

    const data = this.map(m)
    if (!data || this.push(data) !== false) {
      this._readMore()
    }
  }

  _onerror(err, req) {
    const addr = req.to.host + ':' + req.to.port
    const refs = this._seen.get(addr)

    if (err.code === 'REQUEST_TIMEOUT') {
      this._seen.set(addr, DOWN)
      for (const node of refs) this._downHint(node, req.to)
    }

    this._dec(req)
    this.errors++
    this._readMore()
  }

  _oncycle(req) {
    req.oncycle = noop
    this._slow++
    this._readMore()
  }

  _downHint(node, down) {
    // Check rate limit
    if (
      this.dht._downHintsRateLimit !== -1 &&
      this.dht._downHintsSentPerTick >= this.dht._downHintsRateLimit
    ) {
      return null
    }

    this.dht._downHintsSentPerTick++

    const state = { start: 0, end: 6, buffer: b4a.allocUnsafe(6) }
    peer.ipv4.encode(state, down)
    this.dht._request(node, false, true, DOWN_HINT, null, state.buffer, this._session, noop, noop)
  }

  _pushClosest(m) {
    this.closestReplies.push(m)
    for (let i = this.closestReplies.length - 2; i >= 0; i--) {
      const prev = this.closestReplies[i]
      const cmp = this._compare(prev.from.id, m.from.id)
      // if sorted, done!
      if (cmp < 0) break
      // if dup, splice it out (rare)
      if (cmp === 0) {
        this.closestReplies.splice(i + 1, 1)
        break
      }
      // swap and continue down
      this.closestReplies[i + 1] = prev
      this.closestReplies[i] = m
    }
    if (this.closestReplies.length > this.k) this.closestReplies.pop()
  }

  _compare(a, b) {
    for (let i = 0; i < a.length; i++) {
      if (a[i] === b[i]) continue
      const t = this.target[i]
      return (t ^ a[i]) - (t ^ b[i])
    }
    return 0
  }

  _visit(to) {
    this.inflight++

    const req = this.dht._request(
      to,
      this.force,
      this.internal,
      this.command,
      this.target,
      this.value,
      this._session,
      this._onvisitbound,
      this._onerrorbound
    )
    if (req === null) {
      this.destroy(new Error('Node was destroyed'))
      return
    }
    req.retries = this.retries
    req.oncycle = this._oncyclebound
    if (this.force) req.retries = 0
  }

  _destroy(cb) {
    this.dht.stats.queries.active--
    if (this._autoDestroySession) this._session.destroy()
    cb(null)
  }
}

function autoCommit(reply, dht, query) {
  if (!reply.token) return Promise.reject(new Error('No token received for closest node'))
  return dht.request(
    {
      token: reply.token,
      target: query.target,
      command: query.command,
      value: query.value
    },
    reply.from
  )
}

function defaultMap(m) {
  return m
}

function noop() {}
module.exports = class Session {
  constructor(dht) {
    this.dht = dht
    this.inflight = []
  }

  _attach(req) {
    req.index = this.inflight.push(req) - 1
  }

  _detach(req) {
    const i = req.index
    if (i === -1) return
    req.index = -1

    if (i === this.inflight.length - 1) this.inflight.pop()
    else {
      const req = (this.inflight[i] = this.inflight.pop())
      req.index = i
    }
  }

  query({ target, command, value }, opts = {}) {
    return this.dht.query({ target, command, value }, { ...opts, session: this })
  }

  request({ token, command, target, value }, { host, port }, opts = {}) {
    return this.dht.request(
      { token, command, target, value },
      { host, port },
      { ...opts, session: this }
    )
  }

  ping({ host, port }, opts = {}) {
    return this.dht.ping({ host, port }, { ...opts, session: this })
  }

  destroy(err) {
    while (this.inflight.length) {
      const req = this.inflight[0]
      // prevent destroyed requests from contributing to congestion counts
      this.dht.io.congestion.recv()
      req.destroy(err)
    }
  }
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "dht-rpc",
  "version": "6.27.0",
  "description": "Make RPC calls over a Kademlia based DHT",
  "main": "index.js",
  "files": [
    "index.js",
    "lib/*.js"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "dependencies": {
    "adaptive-timeout": "^1.0.1",
    "b4a": "^1.6.1",
    "bare-events": "^2.2.0",
    "compact-encoding": "^3.0.0",
    "compact-encoding-net": "^1.2.0",
    "fast-fifo": "^1.1.0",
    "kademlia-routing-table": "^1.0.1",
    "nat-sampler": "^1.0.1",
    "sodium-universal": "^5.0.0",
    "streamx": "^2.13.2",
    "time-ordered-set": "^2.0.0",
    "udx-native": "^1.5.3"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "test-suspend": "^1.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "test": "npm run test:node && npm run test:bare",
    "test:bare": "brittle-bare --coverage test.js",
    "lint": "prettier --check . && lunte",
    "test:node": "brittle-node --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/dht-rpc.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/dht-rpc/issues"
  },
  "homepage": "https://github.com/holepunchto/dht-rpc#"
}
const { encode, decode } = require('./spec/hyperschema')

async function encrypt(data, cb) {
  const result = await cb(data)

  return encode('@encryption/encrypted-data', result)
}

async function decrypt(data, cb) {
  const decoded = decode('@encryption/encrypted-data', data)
  const decrypted = await cb(decoded)

  return decrypted
}

module.exports = { encrypt, decrypt }
{
  "name": "encryption-encoding",
  "version": "1.0.3",
  "description": "Compact encoding for versioned encrypted values with automatic string/buffer handling.",
  "main": "index.js",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    }
  },
  "files": [
    "package.json",
    "index.js",
    "index.d.ts",
    "spec"
  ],
  "keywords": [
    "pear",
    "p2p",
    "bare",
    "autobase",
    "encryption",
    "hyperschema"
  ],
  "devDependencies": {
    "b4a": "^1.7.3",
    "brittle": "^3.19.0",
    "lunte": "^1.2.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "sodium-universal": "^5.0.1"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && lunte && brittle-bare test/all.js",
    "lint": "lunte"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/encryption-encoding.git"
  },
  "author": "Holepunch Inc",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/encryption-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/encryption-encoding",
  "dependencies": {
    "hyperschema": "^1.19.0"
  }
}
// This file is autogenerated by the hyperschema compiler
// Schema Version: 1
/* eslint-disable camelcase */
/* eslint-disable quotes */
/* eslint-disable space-before-function-paren */

const { c } = require('hyperschema/runtime')

const VERSION = 1

// eslint-disable-next-line no-unused-vars
let version = VERSION

// @encryption/encrypted-data
const encoding0 = {
  preencode(state, m) {
    c.uint.preencode(state, m.type)
    c.buffer.preencode(state, m.value)
  },
  encode(state, m) {
    c.uint.encode(state, m.type)
    c.buffer.encode(state, m.value)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const r1 = c.buffer.decode(state)

    return {
      type: r0,
      value: r1
    }
  }
}

function setVersion(v) {
  version = v
}

function encode(name, value, v = VERSION) {
  version = v
  return c.encode(getEncoding(name), value)
}

function decode(name, buffer, v = VERSION) {
  version = v
  return c.decode(getEncoding(name), buffer)
}

function getEnum(name) {
  switch (name) {
    default:
      throw new Error('Enum not found ' + name)
  }
}

function getEncoding(name) {
  switch (name) {
    case '@encryption/encrypted-data':
      return encoding0
    default:
      throw new Error('Encoder not found ' + name)
  }
}

function getStruct(name, v = VERSION) {
  const enc = getEncoding(name)
  return {
    preencode(state, m) {
      version = v
      enc.preencode(state, m)
    },
    encode(state, m) {
      version = v
      enc.encode(state, m)
    },
    decode(state) {
      version = v
      return enc.decode(state)
    }
  }
}

const resolveStruct = getStruct // compat

module.exports = {
  resolveStruct,
  getStruct,
  getEnum,
  getEncoding,
  encode,
  decode,
  setVersion,
  version
}
module.exports = require('bare-events')
{
  "name": "events-universal",
  "version": "1.0.1",
  "description": "Universal wrapper for the Node.js events module",
  "exports": {
    "./package": "./package.json",
    ".": {
      "bare": "./bare.js",
      "react-native": "./react-native.js",
      "default": "./default.js"
    }
  },
  "files": [
    "index.js",
    "default.js",
    "bare.js",
    "react-native.js"
  ],
  "scripts": {
    "test": "prettier . --check"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/events-universal.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/events-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/events-universal#readme",
  "dependencies": {
    "bare-events": "^2.7.0"
  },
  "devDependencies": {
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^1.0.0"
  }
}
module.exports = class FixedFIFO {
  constructor (hwm) {
    if (!(hwm > 0) || ((hwm - 1) & hwm) !== 0) throw new Error('Max size for a FixedFIFO should be a power of two')
    this.buffer = new Array(hwm)
    this.mask = hwm - 1
    this.top = 0
    this.btm = 0
    this.next = null
  }

  clear () {
    this.top = this.btm = 0
    this.next = null
    this.buffer.fill(undefined)
  }

  push (data) {
    if (this.buffer[this.top] !== undefined) return false
    this.buffer[this.top] = data
    this.top = (this.top + 1) & this.mask
    return true
  }

  shift () {
    const last = this.buffer[this.btm]
    if (last === undefined) return undefined
    this.buffer[this.btm] = undefined
    this.btm = (this.btm + 1) & this.mask
    return last
  }

  peek () {
    return this.buffer[this.btm]
  }

  isEmpty () {
    return this.buffer[this.btm] === undefined
  }
}
const FixedFIFO = require('./fixed-size')

module.exports = class FastFIFO {
  constructor (hwm) {
    this.hwm = hwm || 16
    this.head = new FixedFIFO(this.hwm)
    this.tail = this.head
    this.length = 0
  }

  clear () {
    this.head = this.tail
    this.head.clear()
    this.length = 0
  }

  push (val) {
    this.length++
    if (!this.head.push(val)) {
      const prev = this.head
      this.head = prev.next = new FixedFIFO(2 * this.head.buffer.length)
      this.head.push(val)
    }
  }

  shift () {
    if (this.length !== 0) this.length--
    const val = this.tail.shift()
    if (val === undefined && this.tail.next) {
      const next = this.tail.next
      this.tail.next = null
      this.tail = next
      return this.tail.shift()
    }

    return val
  }

  peek () {
    const val = this.tail.peek()
    if (val === undefined && this.tail.next) return this.tail.next.peek()
    return val
  }

  isEmpty () {
    return this.length === 0
  }
}
{
  "name": "fast-fifo",
  "version": "1.3.2",
  "description": "A fast fifo implementation similar to the one powering nextTick in Node.js core",
  "main": "index.js",
  "files": [
    "./index.js",
    "./fixed-size.js"
  ],
  "dependencies": {},
  "devDependencies": {
    "standard": "^17.1.0",
    "brittle": "^3.3.2"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/fast-fifo.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/fast-fifo/issues"
  },
  "homepage": "https://github.com/mafintosh/fast-fifo"
}
const fs = require('fs')
const fsx = require('fs-native-extensions')
const onexit = require('resource-on-exit')
const ReadyResource = require('ready-resource')

module.exports = class FDLock extends ReadyResource {
  constructor(fd, opts = {}) {
    const { wait = false } = opts

    super()

    this._fd = fd
    this._wait = wait
    this._locked = false

    onexit.add(this, closeSync)
  }

  get locked() {
    return this._locked
  }

  async _open() {
    try {
      await this._resume()
    } catch (err) {
      onexit.remove(this)
      await close(this)
      throw err
    }
  }

  async _close() {
    onexit.remove(this)
    await close(this)
    this._locked = false
  }

  transfer() {
    const fd = this._fd
    if (fd === -1) throw new Error('Lock has already been transferred')
    this._fd = -1
    onexit.remove(this)
    return fd
  }

  async suspend() {
    if (!this.opened) await this.ready()
    return this._suspend()
  }

  async _suspend() {
    if (this._fd === -1 || this._locked === false) return
    fsx.unlock(this._fd)
    this._locked = false
  }

  async resume() {
    if (!this.opened) await this.ready()
    return this._resume()
  }

  async _resume() {
    if (this._fd === -1 || this._locked === true) return
    if (this._wait) await fsx.waitForLock(this._fd)
    else if (!fsx.tryLock(this._fd)) {
      throw new Error('File descriptor could not be locked')
    }
    this._locked = true
  }
}

function close(lock) {
  const fd = lock._fd
  if (fd === -1) return
  lock._fd = -1
  return new Promise((resolve) => fs.close(fd, () => resolve()))
}

function closeSync(lock) {
  const fd = lock._fd
  if (fd === -1) return
  lock._fd = -1
  lock._locked = false
  try {
    fs.closeSync(fd)
  } catch {}
}
{
  "name": "fd-lock",
  "version": "2.2.0",
  "description": "Stateful file descriptor locks for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": "./index.js"
  },
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    }
  },
  "files": [
    "index.js"
  ],
  "scripts": {
    "test": "npm run lint && npm run test:bare && npm run test:node",
    "test:bare": "bare test.js",
    "test:node": "node test.js",
    "lint": "prettier --check .",
    "format": "prettier --write ."
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/fd-lock.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/fd-lock/issues"
  },
  "homepage": "https://github.com/holepunchto/fd-lock#readme",
  "dependencies": {
    "bare-fs": "^4.5.0",
    "fs-native-extensions": "^1.4.4",
    "ready-resource": "^1.2.0",
    "resource-on-exit": "^1.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
exports.fullRoots = function (index, result) {
  if (index & 1) throw new Error('You can only look up roots for depth(0) blocks')
  if (!result) result = []

  index /= 2

  let offset = 0
  let factor = 1

  while (true) {
    if (!index) return result
    while (factor * 2 <= index) factor *= 2
    result.push(offset + factor - 1)
    offset = offset + 2 * factor
    index -= factor
    factor = 1
  }
}

exports.futureRoots = function (index, result) {
  if (index & 1) throw new Error('You can only look up future roots for depth(0) blocks')
  if (!result) result = []

  let factor = 1

  // make first root
  while (factor * 2 <= index) factor *= 2

  // full factor of 2 - done
  if (factor * 2 - 2 === index) return result

  let pos = factor / 2 - 1

  // while its not a full tree
  while ((pos + factor / 2 - 1) !== index) {
    pos += factor

    // read too far, to to left child
    while ((pos + factor / 2 - 1) > index) {
      factor /= 2
      pos -= factor / 2
    }

    // the "gap" is a future root
    result.push(pos - factor / 2)
  }

  return result
}

exports.patch = function (from, to) {
  if (from === 0 || from >= to) return []

  const roots = exports.fullRoots(from)
  const target = exports.fullRoots(to)

  // first find the first root that is different

  let i = 0
  for (; i < target.length; i++) {
    if (i >= roots.length || roots[i] !== target[i]) break
  }

  const patch = []

  if (i < roots.length) {
    // now we need to grow the newest root until it hits the diff one
    let prev = roots.length - 1

    const ite = exports.iterator(roots[prev--])

    while (ite.index !== target[i]) {
      ite.sibling()

      if (prev >= 0 && ite.index === roots[prev]) {
        prev--
      } else {
        patch.push(ite.index)
      }

      patch.push(ite.parent())
    }

    i++ // patched to next root, so inc
  }

  // include the rest

  for (; i < target.length; i++) patch.push(target[i])

  return patch
}

exports.depth = function (index) {
  let depth = 0

  index += 1
  while (!(index & 1)) {
    depth++
    index = rightShift(index)
  }

  return depth
}

exports.sibling = function (index, depth) {
  if (!depth) depth = exports.depth(index)
  const offset = exports.offset(index, depth)

  return exports.index(depth, offset & 1 ? offset - 1 : offset + 1)
}

exports.parent = function (index, depth) {
  if (!depth) depth = exports.depth(index)
  const offset = exports.offset(index, depth)

  return exports.index(depth + 1, rightShift(offset))
}

exports.leftChild = function (index, depth) {
  if (!(index & 1)) return -1
  if (!depth) depth = exports.depth(index)
  return exports.index(depth - 1, exports.offset(index, depth) * 2)
}

exports.rightChild = function (index, depth) {
  if (!(index & 1)) return -1
  if (!depth) depth = exports.depth(index)
  return exports.index(depth - 1, 1 + (exports.offset(index, depth) * 2))
}

exports.children = function (index, depth) {
  if (!(index & 1)) return null

  if (!depth) depth = exports.depth(index)
  const offset = exports.offset(index, depth) * 2

  return [
    exports.index(depth - 1, offset),
    exports.index(depth - 1, offset + 1)
  ]
}

exports.leftSpan = function (index, depth) {
  if (!(index & 1)) return index
  if (!depth) depth = exports.depth(index)
  return exports.offset(index, depth) * twoPow(depth + 1)
}

exports.rightSpan = function (index, depth) {
  if (!(index & 1)) return index
  if (!depth) depth = exports.depth(index)
  return (exports.offset(index, depth) + 1) * twoPow(depth + 1) - 2
}

exports.nextLeaf = function (index) {
  let factor = 1
  let r = index

  while ((r & 1) === 1) {
    r = (r - 1) / 2
    factor *= 2
  }

  return index + factor + 1
}

exports.count = function (index, depth) {
  if (!(index & 1)) return 1
  if (!depth) depth = exports.depth(index)
  return twoPow(depth + 1) - 1
}

exports.countLeaves = function (index) {
  return (exports.count(index) + 1) / 2
}

exports.spans = function (index, depth) {
  if (!(index & 1)) return [index, index]
  if (!depth) depth = exports.depth(index)

  const offset = exports.offset(index, depth)
  const width = twoPow(depth + 1)

  return [offset * width, (offset + 1) * width - 2]
}

exports.index = function (depth, offset) {
  return (1 + 2 * offset) * twoPow(depth) - 1
}

exports.offset = function (index, depth) {
  if (!(index & 1)) return index / 2
  if (!depth) depth = exports.depth(index)

  return ((index + 1) / twoPow(depth) - 1) / 2
}

exports.iterator = function (index) {
  const ite = new Iterator()
  ite.seek(index || 0)
  return ite
}

function twoPow (n) {
  return n < 31 ? 1 << n : ((1 << 30) * (1 << (n - 30)))
}

function rightShift (n) {
  return (n - (n & 1)) / 2
}

function Iterator () {
  this.index = 0
  this.offset = 0
  this.factor = 0
}

Iterator.prototype.seek = function (index) {
  this.index = index
  if (this.index & 1) {
    this.offset = exports.offset(index)
    this.factor = twoPow(exports.depth(index) + 1)
  } else {
    this.offset = index / 2
    this.factor = 2
  }
}

Iterator.prototype.isLeft = function () {
  return (this.offset & 1) === 0
}

Iterator.prototype.isRight = function () {
  return (this.offset & 1) === 1
}

Iterator.prototype.isRoot = function (length) {
  const currentLength = 1 + (this.index + this.factor / 2 - 1) / 2
  if (length < currentLength) return false

  const factor = this.factor * 2
  const index = (this.offset & 1)
    ? this.index - this.factor / 2
    : this.index + this.factor / 2

  const parentLength = 1 + (index + factor / 2 - 1) / 2
  return parentLength > length
}

Iterator.prototype.contains = function (index) {
  return index > this.index
    ? index < (this.index + this.factor / 2)
    : index < this.index
      ? index > (this.index - this.factor / 2)
      : true
}

Iterator.prototype.prev = function () {
  if (!this.offset) return this.index
  this.offset--
  this.index -= this.factor
  return this.index
}

Iterator.prototype.next = function () {
  this.offset++
  this.index += this.factor
  return this.index
}

Iterator.prototype.count = function () {
  if (!(this.index & 1)) return 1
  return this.factor - 1
}

Iterator.prototype.countLeaves = function () {
  return (this.count() + 1) / 2
}

Iterator.prototype.sibling = function () {
  return this.isLeft() ? this.next() : this.prev()
}

Iterator.prototype.parent = function () {
  if (this.offset & 1) {
    this.index -= this.factor / 2
    this.offset = (this.offset - 1) / 2
  } else {
    this.index += this.factor / 2
    this.offset /= 2
  }
  this.factor *= 2
  return this.index
}

Iterator.prototype.leftSpan = function () {
  this.index = this.index - this.factor / 2 + 1
  this.offset = this.index / 2
  this.factor = 2
  return this.index
}

Iterator.prototype.peekLeftSpan = function () {
  return this.index - this.factor / 2 + 1
}

Iterator.prototype.rightSpan = function () {
  this.index = this.index + this.factor / 2 - 1
  this.offset = this.index / 2
  this.factor = 2
  return this.index
}

Iterator.prototype.peekRightSpan = function () {
  return this.index + this.factor / 2 - 1
}

Iterator.prototype.leftChild = function () {
  if (this.factor === 2) return this.index
  this.factor /= 2
  this.index -= this.factor / 2
  this.offset *= 2
  return this.index
}

Iterator.prototype.rightChild = function () {
  if (this.factor === 2) return this.index
  this.factor /= 2
  this.index += this.factor / 2
  this.offset = 2 * this.offset + 1
  return this.index
}

Iterator.prototype.nextTree = function () {
  this.index = this.index + this.factor / 2 + 1
  this.offset = this.index / 2
  this.factor = 2
  return this.index
}

Iterator.prototype.prevTree = function () {
  if (!this.offset) {
    this.index = 0
    this.factor = 2
  } else {
    this.index = this.index - this.factor / 2 - 1
    this.offset = this.index / 2
    this.factor = 2
  }
  return this.index
}

Iterator.prototype.fullRoot = function (index) {
  if (index <= this.index || (this.index & 1) > 0) return false
  while (index > this.index + this.factor + this.factor / 2) {
    this.index += this.factor / 2
    this.factor *= 2
    this.offset /= 2
  }
  return true
}
{
  "name": "flat-tree",
  "version": "1.13.0",
  "description": "A series of functions to map a binary tree to a list",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {},
  "devDependencies": {
    "brittle": "^3.3.2",
    "standard": "^17.1.0"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/flat-tree.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/flat-tree/issues"
  },
  "homepage": "https://github.com/mafintosh/flat-tree"
}
require.addon = require('require-addon')

module.exports = require.addon('.', __filename)
const { isWindows } = require('which-runtime')
const binding = require('./binding')

function onwork(err, result) {
  if (err) this.reject(err)
  else this.resolve(result)
}

exports.tryLock = function tryLock(fd, offset = 0, length = 0, opts = {}) {
  if (typeof offset === 'object') {
    opts = offset
    offset = 0
  }

  if (typeof length === 'object') {
    opts = length
    length = 0
  }

  if (typeof opts !== 'object' || opts === null) {
    opts = {}
  }

  try {
    binding.tryLock(fd, offset, length, opts.shared !== true)
  } catch (err) {
    if (err.code === 'EAGAIN') return false
    throw err
  }

  return true
}

exports.waitForLock = function waitForLock(fd, offset = 0, length = 0, opts = {}) {
  if (typeof offset === 'object') {
    opts = offset
    offset = 0
  }

  if (typeof length === 'object') {
    opts = length
    length = 0
  }

  if (typeof opts !== 'object' || opts === null) {
    opts = {}
  }

  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.waitForLock(fd, offset, length, opts.shared !== true, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.waitForLockSync = function waitForLockSync(fd, offset = 0, length = 0, opts = {}) {
  if (typeof offset === 'object') {
    opts = offset
    offset = 0
  }

  if (typeof length === 'object') {
    opts = length
    length = 0
  }

  if (typeof opts !== 'object' || opts === null) {
    opts = {}
  }

  binding.waitForLockSync(fd, offset, length, opts.shared !== true)
}

exports.tryDowngradeLock = function tryDowngradeLock(fd, offset = 0, length = 0) {
  try {
    binding.tryDowngradeLock(fd, offset, length)
  } catch (err) {
    if (err.code === 'EAGAIN') return false
    throw err
  }

  return true
}

exports.waitForDowngradeLock = function downgradeLock(fd, offset = 0, length = 0) {
  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.waitForDowngradeLock(fd, offset, length, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.waitForDowngradeLockSync = function waitForDowngradeLockSync(fd, offset = 0, length = 0) {
  binding.waitForDowngradeLockSync(fd, offset, length)
}

exports.tryUpgradeLock = function tryUpgradeLock(fd, offset = 0, length = 0) {
  try {
    binding.tryUpgradeLock(fd, offset, length)
  } catch (err) {
    if (err.code === 'EAGAIN') return false
    throw err
  }

  return true
}

exports.waitForUpgradeLock = function upgradeLock(fd, offset = 0, length = 0) {
  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.waitForUpgradeLock(fd, offset, length, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.waitForUpgradeLockSync = function waitForUpgradeLockSync(fd, offset = 0, length = 0) {
  binding.waitForUpgradeLockSync(fd, offset, length)
}

exports.unlock = function unlock(fd, offset = 0, length = 0) {
  binding.unlock(fd, offset, length)
}

exports.trim = function trim(fd, offset, length) {
  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.trim(fd, offset, length, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.trimSync = function trimSync(fd, offset, length) {
  binding.trimSync(fd, offset, length)
}

exports.sparse = function sparse(fd) {
  // Short circuit on everything but Windows
  if (!isWindows) return Promise.resolve()

  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.sparse(fd, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.sparseSync = function sparseSync(fd) {
  // Short circuit on everything but Windows
  if (!isWindows) return

  binding.sparseSync(fd)
}

exports.swap = function swap(from, to) {
  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.swap(from, to, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.swapSync = function swapSync(from, to) {
  binding.swapSync(from, to)
}

exports.getAttr = function getAttr(fd, name) {
  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.getAttr(fd, name, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise.then((buffer) => (buffer === null ? null : Buffer.from(buffer)))
}

exports.getAttrSync = function getAttrSync(fd, name) {
  const buffer = binding.getAttrSync(fd, name)
  return buffer === null ? null : Buffer.from(buffer)
}

exports.setAttr = function setAttr(fd, name, value, encoding) {
  if (typeof value === 'string') value = Buffer.from(value, encoding)

  const req = {
    value,
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.setAttr(
      fd,
      name,
      value.buffer,
      value.byteOffset,
      value.byteLength,
      req,
      onwork
    )
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.setAttrSync = function setAttrSync(fd, name, value, encoding) {
  if (typeof value === 'string') value = Buffer.from(value, encoding)

  binding.setAttrSync(fd, name, value.buffer, value.byteOffset, value.byteLength)
}

exports.removeAttr = function removeAttr(fd, name) {
  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.removeAttr(fd, name, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.removeAttrSync = function removeAttrSync(fd, name) {
  binding.removeAttrSync(fd, name)
}

exports.listAttrs = function listAttrs(fd) {
  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.listAttrs(fd, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.listAttrsSync = function listAttrsSync(fd) {
  return binding.listAttrsSync(fd)
}
{
  "name": "fs-native-extensions",
  "version": "1.5.0",
  "description": "Native file system extensions for advanced file operations",
  "main": "index.js",
  "files": [
    "index.js",
    "macros.h",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "include",
    "src",
    "prebuilds"
  ],
  "imports": {
    "child_process": {
      "bare": "bare-subprocess",
      "default": "child_process"
    },
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "fs/*": {
      "bare": "bare-fs/*",
      "default": "fs/*"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    }
  },
  "addon": true,
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:bare": "brittle-bare --coverage test.js",
    "test:node": "brittle-node --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/fs-native-extensions.git"
  },
  "author": "Kasper Isager Dalsgarð <kasper@funktionel.co>",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/fs-native-extensions/issues"
  },
  "homepage": "https://github.com/holepunchto/fs-native-extensions#readme",
  "dependencies": {
    "require-addon": "^1.1.0",
    "which-runtime": "^1.2.0"
  },
  "devDependencies": {
    "bare-compat-napi": "^1.3.8",
    "bare-fs": "^4.4.4",
    "bare-path": "^3.0.0",
    "bare-subprocess": "^4.0.5",
    "brittle": "^3.1.1",
    "cmake-bare": "^1.1.10",
    "cmake-fetch": "^1.4.7",
    "cmake-napi": "^1.0.5",
    "cmake-npm": "^1.1.0",
    "lunte": "^1.6.0",
    "minimist": "^1.2.6",
    "prettier": "^3.5.3",
    "prettier-config-holepunch": "^2.0.0",
    "test-tmp": "^1.2.1"
  }
}
const codecs = require('codecs')
const { Readable } = require('streamx')
const mutexify = require('mutexify/promise')
const b4a = require('b4a')
const safetyCatch = require('safety-catch')
const ReadyResource = require('ready-resource')
const debounce = require('debounceify')
const Rache = require('rache')
const rrp = require('resolve-reject-promise')

const { all: unslabAll } = require('unslab')

const RangeIterator = require('./iterators/range')
const HistoryIterator = require('./iterators/history')
const DiffIterator = require('./iterators/diff')
const LocalBlockIterator = require('./iterators/local')
const Extension = require('./lib/extension')
const { YoloIndex, Node, Header } = require('./lib/messages')
const { BLOCK_NOT_AVAILABLE, DECODING_ERROR } = require('hypercore-errors')

const T = 5
const MIN_KEYS = T - 1
const MAX_CHILDREN = MIN_KEYS * 2 + 1

const SEP = b4a.alloc(1)
const EMPTY = b4a.alloc(0)

class Key {
  constructor(seq, value) {
    this.seq = seq
    this.value = value
  }
}

class Child {
  constructor(seq, offset, value) {
    this.seq = seq
    this.offset = offset
    this.value = value
  }
}

class Cache {
  constructor(rache) {
    this.keys = rache
    this.length = 0
  }

  get(seq) {
    return this.keys.get(seq) || null
  }

  set(seq, key) {
    this.keys.set(seq, key)
    if (seq >= this.length) this.length = seq + 1
  }

  gc(length) {
    // if we need to "work" more than 128 ticks, just bust the cache...
    if (this.length - length > 128) {
      this.keys.clear()
    } else {
      for (let i = length; i < this.length; i++) {
        this.keys.delete(i)
      }
    }

    this.length = length
  }

  clear() {
    this.keys.clear()
  }
}

class Pointers {
  constructor(decoded) {
    this.levels = decoded.levels.map((l) => {
      const children = []
      const keys = []

      for (let i = 0; i < l.keys.length; i++) {
        keys.push(new Key(l.keys[i], null))
      }

      for (let i = 0; i < l.children.length; i += 2) {
        children.push(new Child(l.children[i], l.children[i + 1], null))
      }

      return { keys, children }
    })
  }

  get(i) {
    return this.levels[i]
  }

  hasKey(seq) {
    for (const lvl of this.levels) {
      for (const key of lvl.keys) {
        if (key.seq === seq) return true
      }
    }
    return false
  }
}

function inflate(entry) {
  if (entry.inflated === null) {
    entry.inflated = YoloIndex.decode(entry.index)
    entry.index = null
  }
  return new Pointers(entry.inflated)
}

function deflate(index) {
  const levels = index.map((l) => {
    const keys = []
    const children = []

    for (let i = 0; i < l.value.keys.length; i++) {
      keys.push(l.value.keys[i].seq)
    }

    for (let i = 0; i < l.value.children.length; i++) {
      children.push(l.value.children[i].seq, l.value.children[i].offset)
    }

    return { keys, children }
  })

  return YoloIndex.encode({ levels })
}

class TreeNode {
  constructor(block, keys, children, offset) {
    this.block = block
    this.offset = offset
    this.keys = keys
    this.children = children
    this.changed = false

    this.preload()
  }

  preload() {
    if (this.block === null) return

    const core = getBackingCore(this.block.tree.core)
    if (!core) return

    const bitfield = core.core.bitfield
    const blocks = []

    for (let i = 0; i < this.keys.length; i++) {
      const k = this.keys[i]
      if (k.value) continue
      if (k.seq >= core.signedLength || (bitfield && bitfield.get(k.seq))) continue
      blocks.push(k.seq)
    }
    for (let i = 0; i < this.children.length; i++) {
      const c = this.children[i]
      if (c.value) continue
      if (c.seq >= core.signedLength || (bitfield && bitfield.get(c.seq))) continue
      blocks.push(c.seq)
    }

    if (blocks.length) core.download({ blocks })
  }

  async insertKey(key, value, child, node, encoding, cas) {
    let s = 0
    let e = this.keys.length
    let c

    while (s < e) {
      const mid = (s + e) >> 1
      c = b4a.compare(key.value, await this.getKey(mid))

      if (c === 0) {
        if (cas) {
          const prev = await this.getKeyNode(mid)
          if (!(await cas(prev.final(encoding), node))) return true
        }
        if (!this.block.tree.tree.alwaysDuplicate) {
          const prev = await this.getKeyNode(mid)
          if (sameValue(prev.value, value)) return true
        }
        this.changed = true
        this.keys[mid] = key
        return true
      }

      if (c < 0) e = mid
      else s = mid + 1
    }

    const i = c < 0 ? e : s
    this.keys.splice(i, 0, key)
    if (child) this.children.splice(i + 1, 0, new Child(0, 0, child))
    this.changed = true

    return this.keys.length < MAX_CHILDREN
  }

  removeKey(index) {
    this.keys.splice(index, 1)
    if (this.children.length) {
      this.children[index + 1].seq = 0 // mark as freed
      this.children.splice(index + 1, 1)
    }
    this.changed = true
  }

  async siblings(parent) {
    for (let i = 0; i < parent.children.length; i++) {
      if (parent.children[i].value === this) {
        const [left, right] = await Promise.all([
          i ? parent.getChildNode(i - 1) : null,
          i < parent.children.length - 1 ? parent.getChildNode(i + 1) : null
        ])
        return { left, index: i, right }
      }
    }

    throw new Error('Bad parent')
  }

  merge(node, median) {
    this.changed = true
    this.keys.push(median)
    for (let i = 0; i < node.keys.length; i++) this.keys.push(node.keys[i])
    for (let i = 0; i < node.children.length; i++) this.children.push(node.children[i])
  }

  async split() {
    const len = this.keys.length >> 1
    const right = TreeNode.create(this.block)

    while (right.keys.length < len) right.keys.push(this.keys.pop())
    right.keys.reverse()

    await this.getKey(this.keys.length - 1) // make sure the median is loaded
    const median = this.keys.pop()

    if (this.children.length) {
      while (right.children.length < len + 1) right.children.push(this.children.pop())
      right.children.reverse()
    }

    this.changed = true

    return {
      left: this,
      median,
      right
    }
  }

  getKeyNode(index) {
    return this.block.tree.getBlock(this.keys[index].seq)
  }

  async getChildNode(index) {
    const child = this.children[index]
    if (child.value) return child.value
    const block =
      child.seq === this.block.seq ? this.block : await this.block.tree.getBlock(child.seq)
    return (child.value = block.getTreeNode(child.offset))
  }

  setKey(index, key) {
    this.keys[index] = key
    this.changed = true
  }

  async getKey(index) {
    const key = this.keys[index]
    if (key.value) return key.value
    const k = key.seq === this.block.seq ? this.block.key : await this.block.tree.getKey(key.seq)
    return (key.value = k)
  }

  indexChanges(index, seq) {
    const offset = index.push(null) - 1
    this.changed = false

    for (const child of this.children) {
      if (!child.value || !child.value.changed) continue
      child.seq = seq
      child.offset = child.value.indexChanges(index, seq)
      index[child.offset] = child
    }

    return offset
  }

  updateChildren(seq, block) {
    for (const child of this.children) {
      if (!child.value || child.seq !== seq) continue
      child.value.block = block
      child.value.updateChildren(seq, block)
    }
  }

  static create(block) {
    const node = new TreeNode(block, [], [], 0)
    node.changed = true
    return node
  }
}

class BlockEntry {
  constructor(seq, tree, entry) {
    this.seq = seq
    this.tree = tree
    this.index = null
    this.entry = entry
    this.key = entry.key
    this.value = entry.value
  }

  isTarget(key) {
    return b4a.equals(this.key, key)
  }

  inflate() {
    if (this.index === null) {
      this.index = inflate(this.entry)
    }
  }

  isDeletion() {
    if (this.value !== null) return false

    if (this.index === null) {
      this.index = inflate(this.entry)
    }

    return !this.index.hasKey(this.seq)
  }

  final(encoding) {
    return {
      seq: this.seq,
      key: encoding.key ? encoding.key.decode(this.key) : this.key,
      value: this.value && (encoding.value ? encoding.value.decode(this.value) : this.value)
    }
  }

  getTreeNode(offset) {
    if (this.index === null) {
      this.index = inflate(this.entry)
    }
    const entry = this.index.get(offset)
    return new TreeNode(this, entry.keys, entry.children, offset)
  }
}

class CacheLock {
  constructor() {
    this.map = new Map()
  }

  enter(seq) {
    const pending = this.map.get(seq)

    if (!pending) {
      this.map.set(seq, [])
      return Promise.resolve()
    }

    const { resolve, promise } = rrp()
    pending.push(resolve)
    return promise
  }

  exit(seq) {
    const pending = this.map.get(seq)
    if (!pending.length) {
      this.map.delete(seq)
      return
    }

    pending.pop()()
  }
}

class BatchEntry extends BlockEntry {
  constructor(seq, tree, key, value, index) {
    super(seq, tree, { key, value, index: null, inflated: null })
    this.pendingIndex = index
  }

  isTarget(key) {
    return false
  }

  getTreeNode(offset) {
    return this.pendingIndex[offset].value
  }
}

class Hyperbee extends ReadyResource {
  constructor(core, opts = {}) {
    super()
    // this.feed is now deprecated, and will be this.core going forward
    this.feed = core
    this.core = core

    this.keyEncoding = opts.keyEncoding ? codecs(opts.keyEncoding) : null
    this.valueEncoding = opts.valueEncoding ? codecs(opts.valueEncoding) : null
    this.extension = opts.extension !== false ? getExtension(this, opts) : null
    this.metadata = opts.metadata || null
    this.lock = opts.lock || mutexify()
    this.sep = opts.sep || SEP
    this.readonly = !!opts.readonly
    this.prefix = opts.prefix || null

    // In a future version, this should be false by default
    this.alwaysDuplicate = opts.alwaysDuplicate !== false

    this._unprefixedKeyEncoding = this.keyEncoding
    this._sub = !!this.prefix
    this._checkout = opts.checkout || 0
    this._view = !!opts._view

    this._onappendBound = this._view ? null : this._onappend.bind(this)
    this._ontruncateBound = this._view ? null : this._ontruncate.bind(this)
    this._watchers = this._onappendBound ? [] : null
    this._entryWatchers = this._onappendBound ? [] : null
    this._sessions = opts.sessions !== false

    this._keyCache = null
    this._nodeCache = null
    this._cacheLock = new CacheLock()

    this._batches = []

    if (this._watchers) {
      this.core.on('append', this._onappendBound)
      this.core.on('truncate', this._ontruncateBound)
    }

    if (this.prefix && opts._sub) {
      this.keyEncoding = prefixEncoding(this.prefix, this.keyEncoding)
    }

    this.ready().catch(safetyCatch)
  }

  async _open() {
    if (this.core.opened === false) await this.core.ready()
    // bump the internal ranges since the nodes are small
    if (this._watchers && this.core.replicator.setInflightRange) {
      this.core.replicator.setInflightRange(256, 512)
    }

    // snapshot
    if (this._checkout === -1) this._checkout = Math.max(1, this.core.length)

    const baseCache = Rache.from(this.core.globalCache)
    this._keyCache = new Cache(baseCache)
    this._nodeCache = new Cache(Rache.from(baseCache))
  }

  get version() {
    return Math.max(1, this._checkout || this.core.length)
  }

  get id() {
    return this.core.id
  }

  get key() {
    return this.core.key
  }

  get discoveryKey() {
    return this.core.discoveryKey
  }

  get writable() {
    return this.core.writable
  }

  get readable() {
    return this.core.readable
  }

  replicate(isInitiator, opts) {
    return this.core.replicate(isInitiator, opts)
  }

  update(opts) {
    return this.core.update(opts)
  }

  peek(range, opts) {
    return iteratorPeek(this.createRangeIterator(range, { ...opts, limit: 1 }))
  }

  createRangeIterator(range, opts = {}) {
    // backwards compat range arg
    opts = opts ? { ...opts, ...range } : range

    const extension = opts.extension === false && opts.limit !== 0 ? null : this.extension
    const keyEncoding = opts.keyEncoding ? codecs(opts.keyEncoding) : this.keyEncoding

    if (extension) {
      const { onseq, onwait } = opts
      let version = 0
      let next = 0

      opts = encRange(keyEncoding, {
        ...opts,
        sub: this._sub,
        onseq(seq) {
          if (!version) version = seq + 1
          if (next) next--
          if (onseq) onseq(seq)
        },
        onwait(seq) {
          if (!next) {
            next = Extension.BATCH_SIZE
            extension.iterator(ite.snapshot(version))
          }
          if (onwait) onwait(seq)
        }
      })
    } else {
      opts = encRange(keyEncoding, { ...opts, sub: this._sub })
    }

    const ite = new RangeIterator(
      new Batch(this, this._makeSnapshot(), null, false, opts),
      null,
      opts
    )
    return ite
  }

  createReadStream(range, opts) {
    const signal = (opts && opts.signal) || null
    return iteratorToStream(this.createRangeIterator(range, opts), signal)
  }

  createHistoryStream(opts) {
    const session = opts && opts.live ? this.core.session() : this._makeSnapshot()
    const signal = (opts && opts.signal) || null
    return iteratorToStream(
      new HistoryIterator(new Batch(this, session, null, false, opts), opts),
      signal
    )
  }

  createDiffStream(right, range, opts) {
    if (typeof right === 'number') right = this.checkout(Math.max(1, right), { reuseSession: true })

    // backwards compat range arg
    opts = opts ? { ...opts, ...range } : range

    const signal = (opts && opts.signal) || null

    const keyEncoding = opts && opts.keyEncoding ? codecs(opts.keyEncoding) : this.keyEncoding
    if (keyEncoding) opts = encRange(keyEncoding, { ...opts, sub: this._sub })

    let done
    let closing
    let ite

    const left = this

    const rs = new Readable({
      signal,
      eagerOpen: true,
      async open(cb) {
        try {
          if (right.opened === false) await right.ready()
          if (left.opened === false) await left.ready()
        } catch (err) {
          cb(err)
          return
        }

        if (closing) {
          cb(null)
          return
        }

        if (left.core.closing || right.core.closing) {
          cb(new Error('Bee closed'))
          return
        }

        const snapshot = right.version > left.version ? right._makeSnapshot() : left._makeSnapshot()

        done = cb
        ite = new DiffIterator(
          new Batch(left, snapshot, null, false, opts),
          new Batch(right, snapshot, null, false, opts),
          opts
        )
        ite.open().then(fin, fin)
      },
      read(cb) {
        done = cb
        ite.next().then(push, fin)
      },
      predestroy() {
        if (!ite) {
          closing = Promise.resolve()
        } else {
          closing = ite.close()
          closing.catch(noop)
        }
      },
      destroy(cb) {
        done = cb
        if (!closing) closing = ite.close()
        closing.then(fin, fin)
      }
    })

    return rs

    function fin(err) {
      done(err)
    }

    function push(val) {
      rs.push(val)
      done(null)
    }
  }

  get(key, opts) {
    const b = new Batch(this, this._makeSnapshot(), null, true, opts)
    return b.get(key)
  }

  getBySeq(seq, opts) {
    const b = new Batch(this, this._makeSnapshot(), null, true, opts)
    return b.getBySeq(seq)
  }

  put(key, value, opts) {
    const b = new Batch(this, this.core, null, true, opts)
    return b.put(key, value, opts)
  }

  batch(opts) {
    return new Batch(this, this.core, mutexify(), true, opts)
  }

  del(key, opts) {
    const b = new Batch(this, this.core, null, true, opts)
    return b.del(key, opts)
  }

  watch(range, opts) {
    if (!this._watchers) throw new Error('Can only watch the main bee instance')
    return new Watcher(this, range, opts)
  }

  async getAndWatch(key, opts) {
    if (!this._watchers) throw new Error('Can only watch the main bee instance')

    const watcher = new EntryWatcher(this, key, opts)
    await watcher._debouncedUpdate()

    if (this.closing) {
      await watcher.close()
      throw new Error('Bee closed')
    }

    return watcher
  }

  _onappend() {
    for (const watcher of this._watchers) {
      watcher._onappend()
    }

    for (const watcher of this._entryWatchers) {
      watcher._onappend()
    }
  }

  _ontruncate(length) {
    for (const watcher of this._watchers) {
      watcher._ontruncate()
    }

    for (const watcher of this._entryWatchers) {
      watcher._ontruncate()
    }

    this._nodeCache.gc(length)
    this._keyCache.gc(length)
  }

  _makeSnapshot() {
    if (this._sessions === false) return this.core
    // TODO: better if we could encapsulate this in hypercore in the future
    return this._checkout <= this.core.length || this._checkout <= 1
      ? this.core.snapshot()
      : this.core.session({ snapshot: false })
  }

  async clearUnlinked(options = {}) {
    await this.ready()

    const { gte = 0, lt = this.version - 1, batchSize = 4096, wait = true } = options
    const checkout = this.version

    let prev = this.batch({ wait: false, checkout: gte })
    let b = this.batch({ wait, checkout })

    const iteBatch = this.batch({ wait: false, checkout })
    const ite = new LocalBlockIterator(iteBatch, { gte, lt })
    await ite.open()

    let ticks = 0

    while (true) {
      const data = await ite.next()
      if (!data) break

      if (!(await isLinked(b, data))) {
        if (b.core.closing || this.core.closing || this.closing) break
        await this.core.clear(data.seq)
      }

      const prevNode = await prev.get(data.key, { finalize: false }).catch(toNull)

      if (prevNode && !(await isLinked(b, prevNode))) {
        if (b.core.closing || this.core.closing || this.closing) break
        await this.core.clear(prevNode.seq)
      }

      if (ticks++ >= batchSize) {
        ticks = 0
        await prev.close()
        await b.close()

        prev = this.batch({ wait: false, checkout: gte })
        b = this.batch({ wait, checkout })
      }
    }

    if (b.core.closing || this.core.closing || this.closing) throw new Error('Core is closed')

    await b.close()
    await prev.close()
    await ite.close()
    await iteBatch.close()

    return lt
  }

  checkout(version, opts = {}) {
    if (version === 0) version = 1

    // same as above, just checkout isn't set yet...
    const snap =
      opts.reuseSession || this._sessions === false
        ? this.core
        : version <= this.core.length || version <= 1
          ? this.core.snapshot()
          : this.core.session({ snapshot: false })

    return new Hyperbee(snap, {
      _view: true,
      _sub: false,
      prefix: this.prefix,
      sep: this.sep,
      lock: this.lock,
      checkout: version,
      keyEncoding: opts.keyEncoding || this.keyEncoding,
      valueEncoding: opts.valueEncoding || this.valueEncoding,
      extension: this.extension !== null ? this.extension : false
    })
  }

  snapshot(opts) {
    return this.checkout(
      this.core.opened === false || this._checkout <= 0 ? -1 : Math.max(1, this.version),
      opts
    )
  }

  sub(prefix, opts = {}) {
    let sep = opts.sep || this.sep
    if (!b4a.isBuffer(sep)) sep = b4a.from(sep)

    prefix = b4a.concat([this.prefix || EMPTY, b4a.from(prefix), sep])

    const valueEncoding = codecs(opts.valueEncoding || this.valueEncoding)
    const keyEncoding = codecs(opts.keyEncoding || this._unprefixedKeyEncoding)

    return new Hyperbee(this.core, {
      _view: true,
      _sub: true,
      prefix,
      sep: this.sep,
      lock: this.lock,
      checkout: this._checkout,
      valueEncoding,
      keyEncoding,
      extension: this.extension !== null ? this.extension : false,
      metadata: this.metadata
    })
  }

  async getHeader(opts) {
    const blk = await this.core.get(0, opts)
    try {
      return blk && Header.decode(blk)
    } catch {
      throw DECODING_ERROR()
    }
  }

  async _close() {
    if (!this._view) {
      if (this._keyCache) this._keyCache.clear()
      if (this._nodeCache) this._nodeCache.clear()
    }

    if (this._watchers) {
      this.core.off('append', this._onappendBound)
      this.core.off('truncate', this._ontruncateBound)

      while (this._watchers.length) {
        await this._watchers[this._watchers.length - 1].close()
      }
    }

    if (this._entryWatchers) {
      while (this._entryWatchers.length) {
        await this._entryWatchers[this._entryWatchers.length - 1].close()
      }
    }

    while (this._batches.length) {
      await this._batches[this._batches.length - 1].close()
    }

    return this.core.close()
  }

  static async isHyperbee(core, opts) {
    await core.ready()

    const blk0 = await core.get(0, opts)
    if (blk0 === null) throw BLOCK_NOT_AVAILABLE()

    try {
      return Header.decode(blk0).protocol === 'hyperbee'
    } catch (err) {
      // undecodable
      return false
    }
  }
}

class Batch {
  constructor(tree, core, batchLock, cache, options = {}) {
    this.tree = tree
    // this.feed is now deprecated, and will be this.core going forward
    this.feed = core
    this.core = core
    this.index = tree._batches.push(this) - 1
    this.blocks = cache ? new Map() : null
    this.autoFlush = !batchLock
    this.maxBlocksCached = options.maxBlocksCached || 128
    this.rootSeq = 0
    this.root = null
    this.length = 0
    this.checkout = options.checkout === undefined ? -1 : options.checkout
    this.options = options
    this.locked = null
    this.batchLock = batchLock
    this.onseq = this.options.onseq || noop
    this.appending = null
    this.isSnapshot = this.core !== this.tree.core
    this.shouldUpdate = this.options.update !== false
    this.updating = null
    this.encoding = {
      key: options.keyEncoding ? codecs(options.keyEncoding) : tree.keyEncoding,
      value: options.valueEncoding ? codecs(options.valueEncoding) : tree.valueEncoding
    }
  }

  async ready() {
    if (this.core.opened === false) await this.core.ready()
    if (this.tree.opened === false) await this.tree.ready()
  }

  async lock() {
    if (this.tree.readonly) throw new Error('Hyperbee is marked as read-only')
    if (this.locked === null) this.locked = await this.tree.lock()
  }

  get version() {
    if (this.checkout !== -1) return Math.max(1, this.checkout)
    return Math.max(1, this.tree._checkout || this.core.length + this.length)
  }

  async getRoot(ensureHeader) {
    await this.ready()
    if (ensureHeader) {
      if (this.core.length === 0 && this.core.writable && !this.tree.readonly) {
        await this.core.append(
          Header.encode({
            protocol: 'hyperbee',
            metadata: this.tree.metadata
          })
        )
      }
    }
    if (this.tree._checkout === 0 && this.checkout === -1 && this.shouldUpdate) {
      if (this.updating === null) this.updating = this.core.update()
      await this.updating
    }
    if (this.version < 2) return null
    return (await this.getBlock(this.version - 1)).getTreeNode(0)
  }

  async getKey(seq) {
    await this.tree._cacheLock.enter(seq)

    try {
      const k = this.core.fork === this.tree.core.fork ? this.tree._keyCache.get(seq) : null
      if (k !== null) return k
      const key = (await this._getBlock(seq)).key
      if (this.core.fork === this.tree.core.fork) this.tree._keyCache.set(seq, key)
      return key
    } finally {
      this.tree._cacheLock.exit(seq)
    }
  }

  async _getNode(seq) {
    const cached =
      this.tree._nodeCache !== null && this.core.fork === this.tree.core.fork
        ? this.tree._nodeCache.get(seq)
        : null
    if (cached !== null) return cached
    const entry = await this.core.get(seq, {
      ...this.options,
      valueEncoding: Node
    })
    if (entry === null) throw BLOCK_NOT_AVAILABLE()
    const wrap = copyEntry(entry)
    if (this.core.fork === this.tree.core.fork && this.tree._nodeCache !== null) {
      this.tree._nodeCache.set(seq, wrap)
    }
    return wrap
  }

  async getBlock(seq) {
    if (this.rootSeq === 0) this.rootSeq = seq
    await this.tree._cacheLock.enter(seq)

    try {
      return await this._getBlock(seq)
    } finally {
      this.tree._cacheLock.exit(seq)
    }
  }

  async _getBlock(seq) {
    let b = this.blocks && this.blocks.get(seq)
    if (b) return b
    this.onseq(seq)
    const entry = await this._getNode(seq)
    b = this.blocks && this.blocks.get(seq)
    if (b) return b
    b = new BlockEntry(seq, this, entry)
    if (this.blocks && this.blocks.size - this.length < this.maxBlocksCached) {
      this.blocks.set(seq, b)
    }
    return b
  }

  _onwait(key) {
    this.options.onwait = null
    this.tree.extension.get(this.rootSeq + 1, key)
  }

  _getEncoding(opts) {
    if (!opts) return this.encoding
    return {
      key: opts.keyEncoding ? codecs(opts.keyEncoding) : this.encoding.key,
      value: opts.valueEncoding ? codecs(opts.valueEncoding) : this.encoding.value
    }
  }

  peek(range, opts) {
    return iteratorPeek(this.createRangeIterator(range, { ...opts, limit: 1 }))
  }

  createRangeIterator(range, opts = {}) {
    // backwards compat range arg
    opts = opts ? { ...opts, ...range } : range

    const encoding = this._getEncoding(opts)
    return new RangeIterator(
      this,
      encoding,
      encRange(encoding.key, { ...opts, sub: this.tree._sub })
    )
  }

  createReadStream(range, opts) {
    const signal = (opts && opts.signal) || null
    return iteratorToStream(this.createRangeIterator(range, opts), signal)
  }

  async getBySeq(seq, opts) {
    const encoding = this._getEncoding(opts)

    try {
      const block = (await this.getBlock(seq)).final(encoding)
      return { key: block.key, value: block.value }
    } finally {
      await this._closeSnapshot()
    }
  }

  async get(key, opts) {
    const encoding = this._getEncoding(opts)
    const finalize = opts ? opts.finalize !== false : true

    try {
      return await this._get(key, encoding, finalize)
    } finally {
      await this._closeSnapshot()
    }
  }

  async _get(key, encoding, finalize) {
    key = enc(encoding.key, key)

    if (this.tree.extension !== null && this.options.extension !== false) {
      this.options.onwait = this._onwait.bind(this, key)
    }

    let node = await this.getRoot(false)
    if (!node) return null

    while (true) {
      if (node.block.isTarget(key)) {
        return node.block.isDeletion() ? null : finalize ? node.block.final(encoding) : node.block
      }

      let s = 0
      let e = node.keys.length
      let c

      while (s < e) {
        const mid = (s + e) >> 1

        c = b4a.compare(key, await node.getKey(mid))

        if (c === 0) {
          const block = await this.getBlock(node.keys[mid].seq)
          return finalize ? block.final(encoding) : block
        }

        if (c < 0) e = mid
        else s = mid + 1
      }

      if (!node.children.length) return null

      const i = c < 0 ? e : s
      node = await node.getChildNode(i)
    }
  }

  async links(key, seq) {
    let node = await this.getRoot(false)
    if (!node) return false

    if (node.block.seq === seq) return true

    while (true) {
      if (node.block.isTarget(key)) return false

      let s = 0
      let e = node.keys.length
      let c

      while (s < e) {
        const mid = (s + e) >> 1

        if (node.keys[mid].seq === seq) return true
        c = b4a.compare(key, await node.getKey(mid))

        if (c === 0) return false

        if (c < 0) e = mid
        else s = mid + 1
      }

      if (!node.children.length) return false

      const i = c < 0 ? e : s
      node = await node.getChildNode(i)
      if (node.block.seq === seq) return true
    }
  }

  async put(key, value, opts) {
    const release = this.batchLock ? await this.batchLock() : null

    const cas = (opts && opts.cas) || null
    const encoding = this._getEncoding(opts)

    if (!this.locked) await this.lock()
    if (!release) return this._put(key, value, encoding, cas)

    try {
      return await this._put(key, value, encoding, cas)
    } finally {
      release()
    }
  }

  async _put(key, value, encoding, cas) {
    const newNode = {
      seq: 0,
      key,
      value
    }
    key = enc(encoding.key, key)
    value = enc(encoding.value, value)

    const stack = []

    let root
    let node = (root = await this.getRoot(true))
    if (!node) node = root = TreeNode.create(null)

    const seq = (newNode.seq = this.core.length + this.length)
    const target = new Key(seq, key)

    while (node.children.length) {
      stack.push(node)
      node.changed = true // changed, but compressible

      let s = 0
      let e = node.keys.length
      let c

      while (s < e) {
        const mid = (s + e) >> 1
        c = b4a.compare(target.value, await node.getKey(mid))

        if (c === 0) {
          if (cas) {
            const prev = await node.getKeyNode(mid)
            if (!(await cas(prev.final(encoding), newNode))) return this._unlockMaybe()
          }
          if (!this.tree.alwaysDuplicate) {
            const prev = await node.getKeyNode(mid)
            if (sameValue(prev.value, value)) return this._unlockMaybe()
          }
          node.setKey(mid, target)
          return this._append(root, seq, key, value)
        }

        if (c < 0) e = mid
        else s = mid + 1
      }

      const i = c < 0 ? e : s
      node = await node.getChildNode(i)
    }

    let needsSplit = !(await node.insertKey(target, value, null, newNode, encoding, cas))
    if (!node.changed) return this._unlockMaybe()

    while (needsSplit) {
      const parent = stack.pop()
      const { median, right } = await node.split()

      if (parent) {
        needsSplit = !(await parent.insertKey(median, value, right, null, encoding, null))
        node = parent
      } else {
        root = TreeNode.create(node.block)
        root.changed = true
        root.keys.push(median)
        root.children.push(new Child(0, 0, node), new Child(0, 0, right))
        needsSplit = false
      }
    }

    return this._append(root, seq, key, value)
  }

  async del(key, opts) {
    const release = this.batchLock ? await this.batchLock() : null
    const cas = (opts && opts.cas) || null
    const encoding = this._getEncoding(opts)

    if (!this.locked) await this.lock()
    if (!release) return this._del(key, encoding, cas)

    try {
      return await this._del(key, encoding, cas)
    } finally {
      release()
    }
  }

  async _del(key, encoding, cas) {
    const delNode = {
      seq: 0,
      key,
      value: null
    }

    key = enc(encoding.key, key)

    const stack = []

    let node = await this.getRoot(true)
    if (!node) return this._unlockMaybe()

    const seq = (delNode.seq = this.core.length + this.length)

    while (true) {
      stack.push(node)

      let s = 0
      let e = node.keys.length
      let c

      while (s < e) {
        const mid = (s + e) >> 1
        c = b4a.compare(key, await node.getKey(mid))

        if (c === 0) {
          if (cas) {
            const prev = await node.getKeyNode(mid)
            if (!(await cas(prev.final(encoding), delNode))) return this._unlockMaybe()
          }
          if (node.children.length) await setKeyToNearestLeaf(node, mid, stack)
          else node.removeKey(mid)
          // we mark these as changed late, so we don't rewrite them if it is a 404
          for (const node of stack) node.changed = true
          return this._append(await rebalance(stack), seq, key, null)
        }

        if (c < 0) e = mid
        else s = mid + 1
      }

      if (!node.children.length) return this._unlockMaybe()

      const i = c < 0 ? e : s
      node = await node.getChildNode(i)
    }
  }

  async _closeSnapshot() {
    if (this.isSnapshot) {
      await this.core.close()
      this._finalize()
    }
  }

  async close() {
    if (this.isSnapshot) return this._closeSnapshot()

    this.root = null
    if (this.blocks) this.blocks.clear()
    this.length = 0
    this._unlock()
  }

  destroy() {
    // compat, remove later
    this.close().catch(noop)
  }

  toBlocks() {
    if (this.appending) return this.appending

    const batch = new Array(this.length)

    for (let i = 0; i < this.length; i++) {
      const seq = this.core.length + i
      const { pendingIndex, key, value } = this.blocks.get(seq)

      if (i < this.length - 1) {
        pendingIndex[0] = null
        let j = 0

        while (j < pendingIndex.length) {
          const idx = pendingIndex[j]
          if (idx !== null && idx.seq === seq) {
            idx.offset = j++
            continue
          }
          if (j === pendingIndex.length - 1) pendingIndex.pop()
          else pendingIndex[j] = pendingIndex.pop()
        }
      }

      batch[i] = Node.encode({
        key,
        value,
        index: deflate(pendingIndex)
      })
    }

    this.appending = batch
    return batch
  }

  flush() {
    if (!this.length) return this.close()

    const batch = this.toBlocks()

    this.root = null
    this.blocks.clear()
    this.length = 0

    return this._appendBatch(batch)
  }

  _unlockMaybe() {
    if (this.autoFlush) this._unlock()
  }

  _unlock() {
    const locked = this.locked
    this.locked = null
    if (locked !== null) locked()
    this._finalize()
  }

  _finalize() {
    // technically finalize can be called more than once, so here we just check if we already have been removed
    if (this.index >= this.tree._batches.length || this.tree._batches[this.index] !== this) return
    const top = this.tree._batches.pop()
    if (top === this) return
    top.index = this.index
    this.tree._batches[top.index] = top
  }

  _append(root, seq, key, value) {
    const index = []
    root.indexChanges(index, seq)
    index[0] = new Child(seq, 0, root)

    if (!this.autoFlush) {
      const block = new BatchEntry(seq, this, key, value, index)
      root.block = block
      this.root = root
      this.length++
      this.blocks.set(seq, block)

      root.updateChildren(seq, block)
      return
    }

    return this._appendBatch(
      Node.encode({
        key,
        value,
        index: deflate(index)
      })
    )
  }

  async _appendBatch(raw) {
    try {
      await this.core.append(raw)
    } finally {
      this._unlock()
    }
  }
}

class EntryWatcher extends ReadyResource {
  constructor(bee, key, opts = {}) {
    super()

    this.keyEncoding = opts.keyEncoding || bee.keyEncoding
    this.valueEncoding = opts.valueEncoding || bee.valueEncoding

    this.index = bee._entryWatchers.push(this) - 1
    this.bee = bee

    this.key = key
    this.node = null

    this._forceUpdate = false
    this._debouncedUpdate = debounce(this._processUpdate.bind(this))
  }

  _close() {
    const top = this.bee._entryWatchers.pop()
    if (top !== this) {
      top.index = this.index
      this.bee._entryWatchers[top.index] = top
    }
  }

  _onappend() {
    this._debouncedUpdate()
  }

  _ontruncate() {
    this._forceUpdate = true
    this._debouncedUpdate()
  }

  async _processUpdate() {
    const force = this._forceUpdate
    this._forceUpdate = false

    let newNode
    try {
      newNode = await this.bee.get(this.key, {
        keyEncoding: this.keyEncoding,
        valueEncoding: this.valueEncoding
      })
    } catch (e) {
      if (e.code === 'SNAPSHOT_NOT_AVAILABLE') {
        // There was a truncate event before the get resolved
        // So this handler will run again anyway
        return
      } else if (this.bee.closing) {
        this.close().catch(safetyCatch)
        return
      }
      this.emit('error', e)
      return
    }

    if (force || newNode?.seq !== this.node?.seq) {
      this.node = newNode
      this.emit('update')
    }
  }
}

class Watcher extends ReadyResource {
  constructor(bee, range, opts = {}) {
    super()

    this.keyEncoding = opts.keyEncoding || bee.keyEncoding
    this.valueEncoding = opts.valueEncoding || bee.valueEncoding
    this.index = bee._watchers.push(this) - 1
    this.bee = bee
    this.core = bee.core

    this.latestDiff = 0
    this.range = range
    this.map = opts.map || defaultWatchMap

    this.current = null
    this.previous = null
    this.currentMapped = null
    this.previousMapped = null
    this.stream = null

    this._lock = mutexify()
    this._flowing = false
    this._resolveOnChange = null
    this._differ = opts.differ || defaultDiffer
    this._eager = !!opts.eager
    this._onchange = opts.onchange || null

    this.on('newListener', autoFlowOnUpdate)

    this.ready().catch(safetyCatch)
  }

  async _consume() {
    if (this._flowing) return
    try {
      for await (const _ of this) {
      } // eslint-disable-line
    } catch {}
  }

  async _open() {
    await this.bee.ready()

    const opts = {
      keyEncoding: this.keyEncoding,
      valueEncoding: this.valueEncoding
    }

    // Point from which to start watching
    this.current = this._eager ? this.bee.checkout(1, opts) : this.bee.snapshot(opts)
    await this.current.ready()

    if (this._onchange) {
      if (this._eager) await this._onchange()
      this._consume()
    }
  }

  [Symbol.asyncIterator]() {
    this._flowing = true
    return this
  }

  _ontruncate() {
    this._onappend()
  }

  _onappend() {
    const resolve = this._resolveOnChange
    this._resolveOnChange = null
    if (resolve) resolve()
  }

  async _waitForChanges() {
    if (this.current.version < this.bee.version || this.closing) return

    await new Promise((resolve) => {
      this._resolveOnChange = resolve
    })
  }

  async next() {
    try {
      return await this._next()
    } catch (err) {
      if (this.closing) return { value: undefined, done: true }
      await this.close()
      throw err
    }
  }

  async _next() {
    const release = await this._lock()

    try {
      if (this.closing) return { value: undefined, done: true }

      if (!this.opened) await this.ready()

      while (true) {
        await this._waitForChanges()

        if (this.closing) return { value: undefined, done: true }

        await this._closePrevious()
        this.previous = this.current.snapshot()

        await this._closeCurrent()
        this.current = this.bee.snapshot({
          keyEncoding: this.keyEncoding,
          valueEncoding: this.valueEncoding
        })

        await this.current.ready()
        await this.previous.ready()

        if (this.current.core.fork !== this.previous.core.fork) {
          return await this._yield()
        }

        this.stream = this._differ(this.current, this.previous, this.range)

        try {
          for await (const data of this.stream) {
            // eslint-disable-line
            return await this._yield()
          }
        } finally {
          this.stream = null
        }
      }
    } finally {
      release()
    }
  }

  async _yield() {
    this.currentMapped = this.map(this.current)
    this.previousMapped = this.map(this.previous)

    if (this._onchange) {
      try {
        await this._onchange()
      } catch (err) {
        safetyCatch(err)
      }
    }

    this.emit('update')
    return { done: false, value: [this.currentMapped, this.previousMapped] }
  }

  async return() {
    await this.close()
    return { done: true }
  }

  async _close() {
    const top = this.bee._watchers.pop()
    if (top !== this) {
      top.index = this.index
      this.bee._watchers[top.index] = top
    }

    if (this.stream && !this.stream.destroying) {
      this.stream.destroy()
    }

    this._onappend() // Continue execution being closed

    await this._closeCurrent().catch(safetyCatch)
    await this._closePrevious().catch(safetyCatch)

    const release = await this._lock()
    release()
  }

  destroy() {
    return this.close()
  }

  async _closeCurrent() {
    if (this.currentMapped) await this.currentMapped.close()
    if (this.current) await this.current.close()
    this.current = this.currentMapped = null
  }

  async _closePrevious() {
    if (this.previousMapped) await this.previousMapped.close()
    if (this.previous) await this.previous.close()
    this.previous = this.previousMapped = null
  }
}

function autoFlowOnUpdate(name) {
  if (name === 'update') this._consume()
}

function defaultWatchMap(snapshot) {
  return snapshot
}

async function leafSize(node, goLeft) {
  while (node.children.length) node = await node.getChildNode(goLeft ? 0 : node.children.length - 1)
  return node.keys.length
}

async function setKeyToNearestLeaf(node, index, stack) {
  let [left, right] = await Promise.all([node.getChildNode(index), node.getChildNode(index + 1)])
  const [ls, rs] = await Promise.all([leafSize(left, false), leafSize(right, true)])

  if (ls < rs) {
    // if fewer leaves on the left
    stack.push(right)
    while (right.children.length) stack.push((right = right.children[0].value))
    node.keys[index] = right.keys.shift()
  } else {
    // if fewer leaves on the right
    stack.push(left)
    while (left.children.length) stack.push((left = left.children[left.children.length - 1].value))
    node.keys[index] = left.keys.pop()
  }
}

async function rebalance(stack) {
  const root = stack[0]

  while (stack.length > 1) {
    const node = stack.pop()
    const parent = stack[stack.length - 1]

    if (node.keys.length >= MIN_KEYS) return root

    let { left, index, right } = await node.siblings(parent)

    // maybe borrow from left sibling?
    if (left && left.keys.length > MIN_KEYS) {
      left.changed = true
      node.keys.unshift(parent.keys[index - 1])
      if (left.children.length) node.children.unshift(left.children.pop())
      parent.keys[index - 1] = left.keys.pop()
      return root
    }

    // maybe borrow from right sibling?
    if (right && right.keys.length > MIN_KEYS) {
      right.changed = true
      node.keys.push(parent.keys[index])
      if (right.children.length) node.children.push(right.children.shift())
      parent.keys[index] = right.keys.shift()
      return root
    }

    // merge node with another sibling
    if (left) {
      index--
      right = node
    } else {
      left = node
    }

    left.merge(right, parent.keys[index])
    parent.removeKey(index)
  }

  // check if the tree shrunk
  if (!root.keys.length && root.children.length) return root.getChildNode(0)
  return root
}

function iteratorToStream(ite, signal) {
  let done
  let closing

  const rs = new Readable({
    signal,
    open(cb) {
      done = cb
      ite.open().then(fin, fin)
    },
    read(cb) {
      done = cb
      ite.next().then(push, fin)
    },
    predestroy() {
      closing = ite.close()
      closing.catch(noop)
    },
    destroy(cb) {
      done = cb
      if (!closing) closing = ite.close()
      closing.then(fin, fin)
    }
  })

  return rs

  function fin(err) {
    done(err)
  }

  function push(val) {
    rs.push(val)
    done(null)
  }
}

async function iteratorPeek(ite) {
  try {
    await ite.open()
    return await ite.next()
  } finally {
    await ite.close()
  }
}

function encRange(e, opts) {
  if (!e) return opts

  if (e.encodeRange) {
    const r = e.encodeRange({
      gt: opts.gt,
      gte: opts.gte,
      lt: opts.lt,
      lte: opts.lte
    })
    opts.gt = r.gt
    opts.gte = r.gte
    opts.lt = r.lt
    opts.lte = r.lte
    return opts
  }

  if (opts.gt !== undefined) opts.gt = enc(e, opts.gt)
  if (opts.gte !== undefined) opts.gte = enc(e, opts.gte)
  if (opts.lt !== undefined) opts.lt = enc(e, opts.lt)
  if (opts.lte !== undefined) opts.lte = enc(e, opts.lte)
  if (opts.sub && !opts.gt && !opts.gte) opts.gt = enc(e, SEP)
  if (opts.sub && !opts.lt && !opts.lte) opts.lt = bump(enc(e, EMPTY))

  return opts
}

function bump(key) {
  // key should have been copied by enc above before hitting this
  key[key.length - 1]++
  return key
}

function enc(e, v) {
  if (v === undefined || v === null) return null
  if (e !== null) return e.encode(v)
  if (typeof v === 'string') return b4a.from(v)
  return v
}

function prefixEncoding(prefix, keyEncoding) {
  return {
    encode(key) {
      return b4a.concat([prefix, b4a.isBuffer(key) ? key : enc(keyEncoding, key)])
    },
    decode(key) {
      const sliced = key.slice(prefix.length, key.length)
      return keyEncoding ? keyEncoding.decode(sliced) : sliced
    }
  }
}

function copyEntry(entry) {
  let key = entry.key
  let value = entry.value
  let index = entry.index

  // key, value and index all refer to the same buffer (one hypercore block)
  // If together they are larger than half the buffer's byteLength,
  // this means that they got their own private slab (see Buffer.allocUnsafe docs)
  // so no need to unslab
  const size =
    key.byteLength +
    (value === null ? 0 : value.byteLength) +
    (index === null ? 0 : index.byteLength)
  if (2 * size < key.buffer.byteLength) {
    const [newKey, newValue, newIndex] = unslabAll([entry.key, entry.value, entry.index])
    key = newKey
    value = newValue
    index = newIndex
  }

  return {
    key,
    value,
    index,
    inflated: null
  }
}

function defaultDiffer(currentSnap, previousSnap, opts) {
  return currentSnap.createDiffStream(previousSnap, opts)
}

function toNull() {
  return null
}

function getBackingCore(core) {
  if (core.core) return core
  if (core.getBackingCore) return core.getBackingCore().session
  return null
}

function sameValue(a, b) {
  return a === b || (a !== null && b !== null && b4a.equals(a, b))
}

function noop() {}

function getExtension(db, opts) {
  if (opts.extension === false) return null
  if (opts.extension && opts.extension !== true) return opts.extension
  return Extension.register(db)
}

async function isLinked(batch, block) {
  const seq = block.seq
  block.inflate()

  const keys = [block.key]
  const wait = batch.options.wait

  for (const l of block.index.levels) {
    if (!l.keys.length) continue
    batch.options.wait = false
    try {
      keys.push(await batch.getKey(l.keys[0].seq))
    } catch {}
    batch.options.wait = wait
  }

  for (const k of keys) {
    if (await batch.links(k, seq)) return true
  }

  if (batch.core.closing) throw new Error('Core is closed')

  return false
}

module.exports = Hyperbee
const b4a = require('b4a')

class SubTree {
  constructor(node, parent) {
    this.node = node
    this.parent = parent

    this.isKey = node.children.length === 0
    this.i = this.isKey ? 1 : 0
    this.n = 0

    const child = this.isKey ? null : this.node.children[0]
    this.seq = child !== null ? child.seq : this.node.keys[0].seq
    this.offset = child !== null ? child.offset : 0
  }

  next() {
    this.i++
    this.isKey = (this.i & 1) === 1
    if (!this.isKey && !this.node.children.length) this.i++
    return this.update()
  }

  async bisect(key, incl) {
    let s = 0
    let e = this.node.keys.length
    let c

    while (s < e) {
      const mid = (s + e) >> 1
      c = cmp(key, await this.node.getKey(mid))

      if (c === 0) {
        if (incl) this.i = mid * 2 + 1
        else this.i = mid * 2 + (this.node.children.length ? 2 : 3)
        return true
      }

      if (c < 0) e = mid
      else s = mid + 1
    }

    const i = c < 0 ? e : s
    this.i = 2 * i + (this.node.children.length ? 0 : 1)
    return this.node.children.length === 0
  }

  update() {
    this.isKey = (this.i & 1) === 1
    this.n = this.i >> 1
    if (this.n >= (this.isKey ? this.node.keys.length : this.node.children.length)) return false
    const child = this.isKey ? null : this.node.children[this.n]
    this.seq = child !== null ? child.seq : this.node.keys[this.n].seq
    this.offset = child !== null ? child.offset : 0
    return true
  }

  async key() {
    return this.n < this.node.keys.length
      ? this.node.getKey(this.n)
      : this.parent && this.parent.key()
  }

  async compare(tree) {
    const [a, b] = await Promise.all([this.key(), tree.key()])
    return cmp(a, b)
  }
}

class TreeIterator {
  constructor(batch, opts) {
    this.batch = batch
    this.stack = []
    this.lt = opts.lt || opts.lte || null
    this.lte = !!opts.lte
    this.gt = opts.gt || opts.gte || null
    this.gte = !!opts.gte
    this.seeking = !!this.gt
    this.encoding = opts.encoding || batch.encoding
  }

  async open() {
    const node = await this.batch.getRoot(false)
    if (!node || !node.keys.length) return
    const tree = new SubTree(node, null)
    if (this.seeking && !(await this._seek(tree))) return
    this.stack.push(tree)
  }

  async _seek(tree) {
    const done = await tree.bisect(this.gt, this.gte)
    const oob = !tree.update()
    if (done || oob) {
      this.seeking = false
      if (oob) return false
    }
    return true
  }

  peek() {
    if (!this.stack.length) return null
    return this.stack[this.stack.length - 1]
  }

  skip() {
    if (!this.stack.length) return
    if (!this.stack[this.stack.length - 1].next()) this.stack.pop()
  }

  async nextKey() {
    let n = null
    while (this.stack.length && n === null) n = await this.next()
    if (n === null) return null
    if (!this.lt) return n.final(this.encoding)

    const c = cmp(n.key, this.lt)
    if (this.lte ? c <= 0 : c < 0) return n.final(this.encoding)
    this.stack = []
    return null
  }

  async next() {
    if (!this.stack.length) return null

    const top = this.stack[this.stack.length - 1]
    const { isKey, n, seq } = top

    if (!top.next()) {
      this.stack.pop()
    }

    if (isKey) {
      this.seeking = false
      return this.batch.getBlock(seq)
    }

    const child = await top.node.getChildNode(n)
    top.node.children[n] = null // unlink to save memory
    const tree = new SubTree(child, top)
    if (this.seeking && !(await this._seek(tree))) return null
    this.stack.push(tree)

    return null
  }

  close() {
    return this.batch._closeSnapshot()
  }
}

module.exports = class DiffIterator {
  constructor(left, right, opts = {}) {
    this.left = new TreeIterator(left, opts)
    this.right = new TreeIterator(right, opts)
    this.limit = typeof opts.limit === 'number' ? opts.limit : -1
  }

  async open() {
    await Promise.all([this.left.open(), this.right.open()])
  }

  async next() {
    if (this.limit === 0) return null
    const res = await this._next()
    if (!res || (res.left === null && res.right === null)) return null
    this.limit--
    return res
  }

  async _next() {
    const a = this.left
    const b = this.right

    while (true) {
      const [l, r] = await Promise.all([a.peek(), b.peek()])

      if (!l && !r) return null
      if (!l) return { left: null, right: await b.nextKey() }
      if (!r) return { left: await a.nextKey(), right: null }

      if (l.seq === r.seq && l.isKey === r.isKey && l.offset === r.offset) {
        a.skip()
        b.skip()
        continue
      }

      const c = await l.compare(r)

      if (l.isKey && !r.isKey) {
        await b.next()
        continue
      }

      if (!l.isKey && r.isKey) {
        await a.next()
        continue
      }

      if (l.isKey && r.isKey) {
        if (c === 0) return { left: await a.nextKey(), right: await b.nextKey() }
        if (c < 0) return { left: await a.nextKey(), right: null }
        return { left: null, right: await b.nextKey() }
      }

      if (c === 0) await Promise.all([a.next(), b.next()])
      else if (c < 0) await b.next()
      else await a.next()
    }
  }

  async close() {
    await Promise.all([this.left.close(), this.right.close()])
  }
}

function cmp(a, b) {
  if (!a) return b ? 1 : 0
  if (!b) return a ? -1 : 0
  return b4a.compare(a, b)
}
module.exports = class HistoryIterator {
  constructor(batch, opts = {}) {
    this.batch = batch
    this.options = opts
    this.live = !!opts.live
    this.gte = 0
    this.lt = 0
    this.reverse = !!opts.reverse
    this.limit = typeof opts.limit === 'number' ? opts.limit : -1
    this.encoding = opts.encoding || batch.encoding
    if (this.live && this.reverse) {
      throw new Error('Cannot have both live and reverse enabled')
    }
  }

  async open() {
    await this.batch.getRoot(false) // does the update dance
    this.gte = gte(this.options, this.batch.version)
    this.lt = this.live ? Infinity : lt(this.options, this.batch.version)
  }

  async next() {
    if (this.limit === 0) return null
    if (this.limit > 0) this.limit--

    if (this.gte >= this.lt) return null

    if (this.reverse) {
      if (this.lt <= 1) return null
      return final(await this.batch.getBlock(--this.lt), this.encoding)
    }

    return final(await this.batch.getBlock(this.gte++), this.encoding)
  }

  close() {
    return this.batch._closeSnapshot()
  }
}

function final(node, encoding) {
  const type = node.isDeletion() ? 'del' : 'put'
  return { type, ...node.final(encoding) }
}

function gte(opts, version) {
  if (opts.gt) return (opts.gt < 0 ? opts.gt + version : opts.gt) + 1
  const gte = opts.gte || opts.since || 1
  return gte < 0 ? gte + version : gte
}

function lt(opts, version) {
  if (opts.lte === 0 || opts.lt === 0 || opts.end === 0) return 0
  if (opts.lte) return (opts.lte < 0 ? opts.lte + version : opts.lte) + 1
  const lt = opts.lt || opts.end || version
  return lt < 0 ? lt + version : lt
}
module.exports = class LocalBlocksIterator {
  constructor(batch, opts = {}) {
    this.batch = batch
    this.options = opts
    this.gte = 0
    this.lt = 0
    this.limit = typeof opts.limit === 'number' ? opts.limit : -1
  }

  async open() {
    await this.batch.getRoot(false) // does the update dance
    this.gte = gte(this.options, this.batch.version)
    this.lt = lt(this.options, this.batch.version)
  }

  async next() {
    if (this.limit === 0) return null
    if (this.limit > 0) this.limit--

    while (this.gte < this.lt) {
      try {
        return await this.batch.getBlock(this.gte++)
      } catch {
        continue
      }
    }

    return null
  }

  close() {
    return this.batch._closeSnapshot()
  }
}

function gte(opts, version) {
  if (opts.gt) return (opts.gt < 0 ? opts.gt + version : opts.gt) + 1
  const gte = opts.gte || opts.since || 1
  return gte < 0 ? gte + version : gte
}

function lt(opts, version) {
  if (opts.lte === 0 || opts.lt === 0 || opts.end === 0) return 0
  if (opts.lte) return (opts.lte < 0 ? opts.lte + version : opts.lte) + 1
  const lt = opts.lt || opts.end || version
  return lt < 0 ? lt + version : lt
}
const b4a = require('b4a')

module.exports = class RangeIterator {
  constructor(batch, encoding, opts = {}) {
    this.batch = batch
    this.stack = []
    this.opened = false
    this.encoding = encoding || batch.encoding

    this._limit = typeof opts.limit === 'number' ? opts.limit : -1
    this._gIncl = !opts.gt
    this._gKey = opts.gt || opts.gte || null
    this._lIncl = !opts.lt
    this._lKey = opts.lt || opts.lte || null
    this._reverse = !!opts.reverse
    this._version = 0
    this._checkpoint = opts.checkpoint && opts.checkpoint.length ? opts.checkpoint : null
    this._nexting = false
    this._closed = false
  }

  snapshot(version = this.batch.version) {
    const checkpoint = []
    for (const s of this.stack) {
      let { node, i } = s
      if (this._nexting && s === this.stack[this.stack.length - 1]) {
        i = this._reverse ? i + 1 : i - 1
      }
      if (!node.block) continue
      if (i < 0) continue
      checkpoint.push(node.block.seq, node.offset, i)
    }

    return {
      version,
      gte: this._gIncl ? this._gKey : null,
      gt: this._gIncl ? null : this._gKey,
      lte: this._lIncl ? this._lKey : null,
      lt: this._lIncl ? null : this._lKey,
      limit: this._limit,
      reverse: this._reverse,
      ended: this.opened && !checkpoint.length,
      checkpoint: this.opened ? checkpoint : []
    }
  }

  async open() {
    await this._open()
    this.opened = true
  }

  async _open() {
    if (this._checkpoint) {
      for (let j = 0; j < this._checkpoint.length; j += 3) {
        const seq = this._checkpoint[j]
        const offset = this._checkpoint[j + 1]
        const i = this._checkpoint[j + 2]
        this.stack.push({
          node: (await this.batch.getBlock(seq)).getTreeNode(offset),
          i
        })
      }
      return
    }

    this._nexting = true

    let node = await this.batch.getRoot(false)
    if (!node) {
      this._nexting = false
      return
    }

    const incl = this._reverse ? this._lIncl : this._gIncl
    const start = this._reverse ? this._lKey : this._gKey

    if (!start) {
      this.stack.push({ node, i: this._reverse ? node.keys.length << 1 : 0 })
      this._nexting = false
      this._preloadQuery()
      return
    }

    while (true) {
      const entry = { node, i: this._reverse ? node.keys.length << 1 : 0 }

      let s = 0
      let e = node.keys.length
      let c

      while (s < e) {
        const mid = (s + e) >> 1
        c = b4a.compare(start, await node.getKey(mid))

        if (c === 0) {
          if (incl) entry.i = mid * 2 + 1
          else entry.i = mid * 2 + (this._reverse ? 0 : 2)
          this.stack.push(entry)
          this._nexting = false
          this._preloadQuery()
          return
        }

        if (c < 0) e = mid
        else s = mid + 1
      }

      const i = c < 0 ? e : s
      entry.i = 2 * i + (this._reverse ? -1 : 1)

      if (entry.i >= 0 && entry.i <= node.keys.length << 1) this.stack.push(entry)
      if (!node.children.length) {
        this._nexting = false
        this._preloadQuery()
        return
      }

      node = await node.getChildNode(i)
    }
  }

  _preloadQuery() {
    const max = { nodes: 0, max: 2048 }

    if (this._limit === -1 && !this._reverse && this.stack.length) {
      for (const s of this.stack) {
        const k = (s.i - (s.i & 1)) / 2
        this._preload(s.node, k + 1, this._lKey, max).catch(noop)
      }
    }
  }

  async _preload(node, i, end, max) {
    for (; i < node.keys.length; i++) {
      const key = node.keys[i]
      const block = await this.batch.getBlock(key.seq)
      if (this._closed) return
      const c = end ? b4a.compare(block.key, end) : -1
      if (c >= 0 || max.nodes >= max.max || i >= node.children.length) return
      max.nodes++
      const next = await node.getChildNode(i)
      if (this._closed) return
      this._preload(next, 0, end, max).catch(noop)
    }

    if (node.children.length && max.nodes < max.max) {
      const next = await node.getChildNode(node.children.length - 1)
      if (this._closed) return
      this._preload(next, 0, end, max).catch(noop)
    }
  }

  async next() {
    // TODO: this nexting flag is only needed if someone asks for a snapshot during
    // a lookup (ie the extension, pretty important...).
    // A better solution would be to refactor this so top.i is incremented eagerly
    // to get the current block instead of the way it is done now (++i vs i++)
    this._nexting = true

    const end = this._reverse ? this._gKey : this._lKey
    const incl = this._reverse ? this._gIncl : this._lIncl

    while (this.stack.length && (this._limit === -1 || this._limit > 0)) {
      const top = this.stack[this.stack.length - 1]
      const isKey = (top.i & 1) === 1
      const n = this._reverse ? (top.i < 0 ? top.node.keys.length : top.i-- >> 1) : top.i++ >> 1

      if (!isKey) {
        if (!top.node.children.length) continue
        const node = await top.node.getChildNode(n)
        if (top.node.block.seq < this.batch.core.length) {
          top.node.children[n].value = null // unlink it to save memory
        }
        this.stack.push({ i: this._reverse ? node.keys.length << 1 : 0, node })
        continue
      }

      if (n >= top.node.keys.length) {
        this.stack.pop()
        continue
      }

      const key = top.node.keys[n]
      const block = await this.batch.getBlock(key.seq)
      if (end) {
        const c = b4a.compare(block.key, end)
        if (c === 0 ? !incl : this._reverse ? c < 0 : c > 0) {
          this._limit = 0
          break
        }
      }
      if (this._limit > 0) this._limit--
      this._nexting = false
      return block.final(this.encoding)
    }

    this._nexting = false
    return null
  }

  close() {
    this._closed = true
    return this.batch._closeSnapshot()
  }
}

function noop() {}
const { Extension } = require('./messages')

// const MAX_ACTIVE = 32
const FLUSH_BATCH = 128
const MAX_PASSIVE_BATCH = 2048
const MAX_ACTIVE_BATCH = MAX_PASSIVE_BATCH + FLUSH_BATCH

class Batch {
  constructor(outgoing, from) {
    this.blocks = []
    this.start = 0
    this.end = 0
    this.outgoing = outgoing
    this.from = from
  }

  push(seq) {
    const len = this.blocks.push(seq)
    if (len === 1 || seq < this.start) this.start = seq
    if (len === 1 || seq >= this.end) this.end = seq + 1
    if (len >= FLUSH_BATCH) {
      this.send()
      this.clear()
    }
  }

  send() {
    if (!this.blocks.length) return
    this.outgoing.send(
      Extension.encode({
        cache: { blocks: this.blocks, start: this.start, end: this.end }
      }),
      this.from
    )
  }

  clear() {
    this.start = this.end = 0
    this.blocks = []
  }
}

class HyperbeeExtension {
  constructor(db) {
    this.encoding = null
    this.outgoing = null
    this.db = db
    this.active = 0
  }

  get(version, key) {
    this.outgoing.broadcast(Extension.encode({ get: { version, key } }))
  }

  iterator(snapshot) {
    if (snapshot.ended) return
    if (snapshot.limit === 0) return
    if (snapshot.limit === -1) snapshot.limit = 0
    this.outgoing.broadcast(Extension.encode({ iterator: snapshot }))
  }

  onmessage(buf, from) {
    // TODO: handle max active extension messages
    // this.active++

    const message = decode(buf)
    if (!message) return

    if (message.cache) this.oncache(message.cache, from)
    if (message.get) this.onget(message.get, from)
    if (message.iterator) this.oniterator(message.iterator, from)
  }

  oncache(message, from) {
    if (!message.blocks.length) return
    this.db.core.download(message)
  }

  onget(message, from) {
    if (!message.version || message.version > this.db.version) return

    const b = new Batch(this.outgoing, from)
    const db = this.db.checkout(message.version)

    db.get(message.key, {
      extension: false,
      wait: false,
      update: false,
      onseq
    }).then(done, done)

    function done() {
      db.close().catch(noop)
      b.send()
    }

    function onseq(seq) {
      b.push(seq)
    }
  }

  async oniterator(message, from) {
    if (!message.version || message.version > this.db.version) return

    const b = new Batch(this.outgoing, from)
    const seqs = new Set()

    let skip = message.checkpoint.length
    let work = 0

    const db = this.db.checkout(message.version)
    const ite = db.createRangeIterator({
      ...message,
      wait: false,
      extension: false,
      update: false,
      limit: message.limit === 0 ? -1 : message.limit,
      onseq(seq) {
        if (skip && skip--) return
        if (seqs.has(seq)) return
        work++
        seqs.add(seq)
        b.push(seq)
      }
    })

    try {
      await ite.open()
      // eslint-disable-next-line no-unmodified-loop-condition
      while (work < MAX_ACTIVE_BATCH) {
        if (!(await ite.next())) break
      }
    } catch (_) {
      // do nothing
    } finally {
      ite.close().catch(noop)
      db.close().catch(noop)
      b.send()
    }
  }

  static register(db) {
    const e = new this(db)
    e.outgoing = db.core.registerExtension('hyperbee', e)
    return e
  }
}

HyperbeeExtension.BATCH_SIZE = MAX_PASSIVE_BATCH

module.exports = HyperbeeExtension

function decode(buf) {
  try {
    return Extension.decode(buf)
  } catch (err) {
    return null
  }
}

function noop() {}
// This file is auto generated by the protocol-buffers compiler

/* eslint-disable quotes */
/* eslint-disable indent */
/* eslint-disable no-redeclare */
/* eslint-disable camelcase */
/* eslint-disable no-var */

// Remember to `npm install --save protocol-buffers-encodings`
var encodings = require('protocol-buffers-encodings')
var b4a = require('b4a')
var varint = encodings.varint
var skip = encodings.skip

var YoloIndex = exports.YoloIndex = {
  buffer: true,
  encodingLength: null,
  encode: null,
  decode: null
}

var Header = exports.Header = {
  buffer: true,
  encodingLength: null,
  encode: null,
  decode: null
}

var Node = exports.Node = {
  buffer: true,
  encodingLength: null,
  encode: null,
  decode: null
}

var Extension = exports.Extension = {
  buffer: true,
  encodingLength: null,
  encode: null,
  decode: null
}

defineYoloIndex()
defineHeader()
defineNode()
defineExtension()

function defineYoloIndex () {
  var Level = YoloIndex.Level = {
    buffer: true,
    encodingLength: null,
    encode: null,
    decode: null
  }

  defineLevel()

  function defineLevel () {
    Level.encodingLength = encodingLength
    Level.encode = encode
    Level.decode = decode

    function encodingLength (obj) {
      var length = 0
      if (defined(obj.keys)) {
        var packedLen = 0
        for (var i = 0; i < obj.keys.length; i++) {
          if (!defined(obj.keys[i])) continue
          var len = encodings.varint.encodingLength(obj.keys[i])
          packedLen += len
        }
        if (packedLen) {
          length += 1 + packedLen + varint.encodingLength(packedLen)
        }
      }
      if (defined(obj.children)) {
        var packedLen = 0
        for (var i = 0; i < obj.children.length; i++) {
          if (!defined(obj.children[i])) continue
          var len = encodings.varint.encodingLength(obj.children[i])
          packedLen += len
        }
        if (packedLen) {
          length += 1 + packedLen + varint.encodingLength(packedLen)
        }
      }
      return length
    }

    function encode (obj, buf, offset) {
      if (!offset) offset = 0
      if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
      var oldOffset = offset
      if (defined(obj.keys)) {
        var packedLen = 0
        for (var i = 0; i < obj.keys.length; i++) {
          if (!defined(obj.keys[i])) continue
          packedLen += encodings.varint.encodingLength(obj.keys[i])
        }
        if (packedLen) {
          buf[offset++] = 10
          varint.encode(packedLen, buf, offset)
          offset += varint.encode.bytes
        }
        for (var i = 0; i < obj.keys.length; i++) {
          if (!defined(obj.keys[i])) continue
          encodings.varint.encode(obj.keys[i], buf, offset)
          offset += encodings.varint.encode.bytes
        }
      }
      if (defined(obj.children)) {
        var packedLen = 0
        for (var i = 0; i < obj.children.length; i++) {
          if (!defined(obj.children[i])) continue
          packedLen += encodings.varint.encodingLength(obj.children[i])
        }
        if (packedLen) {
          buf[offset++] = 18
          varint.encode(packedLen, buf, offset)
          offset += varint.encode.bytes
        }
        for (var i = 0; i < obj.children.length; i++) {
          if (!defined(obj.children[i])) continue
          encodings.varint.encode(obj.children[i], buf, offset)
          offset += encodings.varint.encode.bytes
        }
      }
      encode.bytes = offset - oldOffset
      return buf
    }

    function decode (buf, offset, end) {
      if (!offset) offset = 0
      if (!end) end = buf.length
      if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
      var oldOffset = offset
      var obj = {
        keys: [],
        children: []
      }
      while (true) {
        if (end <= offset) {
          decode.bytes = offset - oldOffset
          return obj
        }
        var prefix = varint.decode(buf, offset)
        offset += varint.decode.bytes
        var tag = prefix >> 3
        switch (tag) {
          case 1:
          var packedEnd = varint.decode(buf, offset)
          offset += varint.decode.bytes
          packedEnd += offset
          while (offset < packedEnd) {
            obj.keys.push(encodings.varint.decode(buf, offset))
            offset += encodings.varint.decode.bytes
          }
          break
          case 2:
          var packedEnd = varint.decode(buf, offset)
          offset += varint.decode.bytes
          packedEnd += offset
          while (offset < packedEnd) {
            obj.children.push(encodings.varint.decode(buf, offset))
            offset += encodings.varint.decode.bytes
          }
          break
          default:
          offset = skip(prefix & 7, buf, offset)
        }
      }
    }
  }

  YoloIndex.encodingLength = encodingLength
  YoloIndex.encode = encode
  YoloIndex.decode = decode

  function encodingLength (obj) {
    var length = 0
    if (defined(obj.levels)) {
      for (var i = 0; i < obj.levels.length; i++) {
        if (!defined(obj.levels[i])) continue
        var len = Level.encodingLength(obj.levels[i])
        length += varint.encodingLength(len)
        length += 1 + len
      }
    }
    return length
  }

  function encode (obj, buf, offset) {
    if (!offset) offset = 0
    if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
    var oldOffset = offset
    if (defined(obj.levels)) {
      for (var i = 0; i < obj.levels.length; i++) {
        if (!defined(obj.levels[i])) continue
        buf[offset++] = 10
        varint.encode(Level.encodingLength(obj.levels[i]), buf, offset)
        offset += varint.encode.bytes
        Level.encode(obj.levels[i], buf, offset)
        offset += Level.encode.bytes
      }
    }
    encode.bytes = offset - oldOffset
    return buf
  }

  function decode (buf, offset, end) {
    if (!offset) offset = 0
    if (!end) end = buf.length
    if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
    var oldOffset = offset
    var obj = {
      levels: []
    }
    while (true) {
      if (end <= offset) {
        decode.bytes = offset - oldOffset
        return obj
      }
      var prefix = varint.decode(buf, offset)
      offset += varint.decode.bytes
      var tag = prefix >> 3
      switch (tag) {
        case 1:
        var len = varint.decode(buf, offset)
        offset += varint.decode.bytes
        obj.levels.push(Level.decode(buf, offset, offset + len))
        offset += Level.decode.bytes
        break
        default:
        offset = skip(prefix & 7, buf, offset)
      }
    }
  }
}

function defineHeader () {
  var Metadata = Header.Metadata = {
    buffer: true,
    encodingLength: null,
    encode: null,
    decode: null
  }

  defineMetadata()

  function defineMetadata () {
    Metadata.encodingLength = encodingLength
    Metadata.encode = encode
    Metadata.decode = decode

    function encodingLength (obj) {
      var length = 0
      if (defined(obj.contentFeed)) {
        var len = encodings.bytes.encodingLength(obj.contentFeed)
        length += 1 + len
      }
      if (defined(obj.userData)) {
        var len = encodings.bytes.encodingLength(obj.userData)
        length += 1 + len
      }
      return length
    }

    function encode (obj, buf, offset) {
      if (!offset) offset = 0
      if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
      var oldOffset = offset
      if (defined(obj.contentFeed)) {
        buf[offset++] = 10
        encodings.bytes.encode(obj.contentFeed, buf, offset)
        offset += encodings.bytes.encode.bytes
      }
      if (defined(obj.userData)) {
        buf[offset++] = 18
        encodings.bytes.encode(obj.userData, buf, offset)
        offset += encodings.bytes.encode.bytes
      }
      encode.bytes = offset - oldOffset
      return buf
    }

    function decode (buf, offset, end) {
      if (!offset) offset = 0
      if (!end) end = buf.length
      if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
      var oldOffset = offset
      var obj = {
        contentFeed: null,
        userData: null
      }
      while (true) {
        if (end <= offset) {
          decode.bytes = offset - oldOffset
          return obj
        }
        var prefix = varint.decode(buf, offset)
        offset += varint.decode.bytes
        var tag = prefix >> 3
        switch (tag) {
          case 1:
          obj.contentFeed = encodings.bytes.decode(buf, offset)
          offset += encodings.bytes.decode.bytes
          break
          case 2:
          obj.userData = encodings.bytes.decode(buf, offset)
          offset += encodings.bytes.decode.bytes
          break
          default:
          offset = skip(prefix & 7, buf, offset)
        }
      }
    }
  }

  Header.encodingLength = encodingLength
  Header.encode = encode
  Header.decode = decode

  function encodingLength (obj) {
    var length = 0
    if (!defined(obj.protocol)) throw new Error("protocol is required")
    var len = encodings.string.encodingLength(obj.protocol)
    length += 1 + len
    if (defined(obj.metadata)) {
      var len = Metadata.encodingLength(obj.metadata)
      length += varint.encodingLength(len)
      length += 1 + len
    }
    return length
  }

  function encode (obj, buf, offset) {
    if (!offset) offset = 0
    if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
    var oldOffset = offset
    if (!defined(obj.protocol)) throw new Error("protocol is required")
    buf[offset++] = 10
    encodings.string.encode(obj.protocol, buf, offset)
    offset += encodings.string.encode.bytes
    if (defined(obj.metadata)) {
      buf[offset++] = 18
      varint.encode(Metadata.encodingLength(obj.metadata), buf, offset)
      offset += varint.encode.bytes
      Metadata.encode(obj.metadata, buf, offset)
      offset += Metadata.encode.bytes
    }
    encode.bytes = offset - oldOffset
    return buf
  }

  function decode (buf, offset, end) {
    if (!offset) offset = 0
    if (!end) end = buf.length
    if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
    var oldOffset = offset
    var obj = {
      protocol: "",
      metadata: null
    }
    var found0 = false
    while (true) {
      if (end <= offset) {
        if (!found0) throw new Error("Decoded message is not valid")
        decode.bytes = offset - oldOffset
        return obj
      }
      var prefix = varint.decode(buf, offset)
      offset += varint.decode.bytes
      var tag = prefix >> 3
      switch (tag) {
        case 1:
        obj.protocol = encodings.string.decode(buf, offset)
        offset += encodings.string.decode.bytes
        found0 = true
        break
        case 2:
        var len = varint.decode(buf, offset)
        offset += varint.decode.bytes
        obj.metadata = Metadata.decode(buf, offset, offset + len)
        offset += Metadata.decode.bytes
        break
        default:
        offset = skip(prefix & 7, buf, offset)
      }
    }
  }
}

function defineNode () {
  Node.encodingLength = encodingLength
  Node.encode = encode
  Node.decode = decode

  function encodingLength (obj) {
    var length = 0
    if (!defined(obj.index)) throw new Error("index is required")
    var len = encodings.bytes.encodingLength(obj.index)
    length += 1 + len
    if (!defined(obj.key)) throw new Error("key is required")
    var len = encodings.bytes.encodingLength(obj.key)
    length += 1 + len
    if (defined(obj.value)) {
      var len = encodings.bytes.encodingLength(obj.value)
      length += 1 + len
    }
    return length
  }

  function encode (obj, buf, offset) {
    if (!offset) offset = 0
    if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
    var oldOffset = offset
    if (!defined(obj.index)) throw new Error("index is required")
    buf[offset++] = 10
    encodings.bytes.encode(obj.index, buf, offset)
    offset += encodings.bytes.encode.bytes
    if (!defined(obj.key)) throw new Error("key is required")
    buf[offset++] = 18
    encodings.bytes.encode(obj.key, buf, offset)
    offset += encodings.bytes.encode.bytes
    if (defined(obj.value)) {
      buf[offset++] = 26
      encodings.bytes.encode(obj.value, buf, offset)
      offset += encodings.bytes.encode.bytes
    }
    encode.bytes = offset - oldOffset
    return buf
  }

  function decode (buf, offset, end) {
    if (!offset) offset = 0
    if (!end) end = buf.length
    if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
    var oldOffset = offset
    var obj = {
      index: null,
      key: null,
      value: null
    }
    var found0 = false
    var found1 = false
    while (true) {
      if (end <= offset) {
        if (!found0 || !found1) throw new Error("Decoded message is not valid")
        decode.bytes = offset - oldOffset
        return obj
      }
      var prefix = varint.decode(buf, offset)
      offset += varint.decode.bytes
      var tag = prefix >> 3
      switch (tag) {
        case 1:
        obj.index = encodings.bytes.decode(buf, offset)
        offset += encodings.bytes.decode.bytes
        found0 = true
        break
        case 2:
        obj.key = encodings.bytes.decode(buf, offset)
        offset += encodings.bytes.decode.bytes
        found1 = true
        break
        case 3:
        obj.value = encodings.bytes.decode(buf, offset)
        offset += encodings.bytes.decode.bytes
        break
        default:
        offset = skip(prefix & 7, buf, offset)
      }
    }
  }
}

function defineExtension () {
  var Get = Extension.Get = {
    buffer: true,
    encodingLength: null,
    encode: null,
    decode: null
  }

  var Iterator = Extension.Iterator = {
    buffer: true,
    encodingLength: null,
    encode: null,
    decode: null
  }

  var Cache = Extension.Cache = {
    buffer: true,
    encodingLength: null,
    encode: null,
    decode: null
  }

  defineGet()
  defineIterator()
  defineCache()

  function defineGet () {
    Get.encodingLength = encodingLength
    Get.encode = encode
    Get.decode = decode

    function encodingLength (obj) {
      var length = 0
      if (defined(obj.version)) {
        var len = encodings.varint.encodingLength(obj.version)
        length += 1 + len
      }
      if (defined(obj.key)) {
        var len = encodings.bytes.encodingLength(obj.key)
        length += 1 + len
      }
      return length
    }

    function encode (obj, buf, offset) {
      if (!offset) offset = 0
      if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
      var oldOffset = offset
      if (defined(obj.version)) {
        buf[offset++] = 8
        encodings.varint.encode(obj.version, buf, offset)
        offset += encodings.varint.encode.bytes
      }
      if (defined(obj.key)) {
        buf[offset++] = 18
        encodings.bytes.encode(obj.key, buf, offset)
        offset += encodings.bytes.encode.bytes
      }
      encode.bytes = offset - oldOffset
      return buf
    }

    function decode (buf, offset, end) {
      if (!offset) offset = 0
      if (!end) end = buf.length
      if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
      var oldOffset = offset
      var obj = {
        version: 0,
        key: null
      }
      while (true) {
        if (end <= offset) {
          decode.bytes = offset - oldOffset
          return obj
        }
        var prefix = varint.decode(buf, offset)
        offset += varint.decode.bytes
        var tag = prefix >> 3
        switch (tag) {
          case 1:
          obj.version = encodings.varint.decode(buf, offset)
          offset += encodings.varint.decode.bytes
          break
          case 2:
          obj.key = encodings.bytes.decode(buf, offset)
          offset += encodings.bytes.decode.bytes
          break
          default:
          offset = skip(prefix & 7, buf, offset)
        }
      }
    }
  }

  function defineIterator () {
    Iterator.encodingLength = encodingLength
    Iterator.encode = encode
    Iterator.decode = decode

    function encodingLength (obj) {
      var length = 0
      if (defined(obj.version)) {
        var len = encodings.varint.encodingLength(obj.version)
        length += 1 + len
      }
      if (defined(obj.gte)) {
        var len = encodings.bytes.encodingLength(obj.gte)
        length += 1 + len
      }
      if (defined(obj.gt)) {
        var len = encodings.bytes.encodingLength(obj.gt)
        length += 1 + len
      }
      if (defined(obj.lte)) {
        var len = encodings.bytes.encodingLength(obj.lte)
        length += 1 + len
      }
      if (defined(obj.lt)) {
        var len = encodings.bytes.encodingLength(obj.lt)
        length += 1 + len
      }
      if (defined(obj.limit)) {
        var len = encodings.varint.encodingLength(obj.limit)
        length += 1 + len
      }
      if (defined(obj.reverse)) {
        var len = encodings.bool.encodingLength(obj.reverse)
        length += 1 + len
      }
      if (defined(obj.checkpoint)) {
        var packedLen = 0
        for (var i = 0; i < obj.checkpoint.length; i++) {
          if (!defined(obj.checkpoint[i])) continue
          var len = encodings.varint.encodingLength(obj.checkpoint[i])
          packedLen += len
        }
        if (packedLen) {
          length += 1 + packedLen + varint.encodingLength(packedLen)
        }
      }
      return length
    }

    function encode (obj, buf, offset) {
      if (!offset) offset = 0
      if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
      var oldOffset = offset
      if (defined(obj.version)) {
        buf[offset++] = 8
        encodings.varint.encode(obj.version, buf, offset)
        offset += encodings.varint.encode.bytes
      }
      if (defined(obj.gte)) {
        buf[offset++] = 18
        encodings.bytes.encode(obj.gte, buf, offset)
        offset += encodings.bytes.encode.bytes
      }
      if (defined(obj.gt)) {
        buf[offset++] = 26
        encodings.bytes.encode(obj.gt, buf, offset)
        offset += encodings.bytes.encode.bytes
      }
      if (defined(obj.lte)) {
        buf[offset++] = 34
        encodings.bytes.encode(obj.lte, buf, offset)
        offset += encodings.bytes.encode.bytes
      }
      if (defined(obj.lt)) {
        buf[offset++] = 42
        encodings.bytes.encode(obj.lt, buf, offset)
        offset += encodings.bytes.encode.bytes
      }
      if (defined(obj.limit)) {
        buf[offset++] = 48
        encodings.varint.encode(obj.limit, buf, offset)
        offset += encodings.varint.encode.bytes
      }
      if (defined(obj.reverse)) {
        buf[offset++] = 56
        encodings.bool.encode(obj.reverse, buf, offset)
        offset += encodings.bool.encode.bytes
      }
      if (defined(obj.checkpoint)) {
        var packedLen = 0
        for (var i = 0; i < obj.checkpoint.length; i++) {
          if (!defined(obj.checkpoint[i])) continue
          packedLen += encodings.varint.encodingLength(obj.checkpoint[i])
        }
        if (packedLen) {
          buf[offset++] = 66
          varint.encode(packedLen, buf, offset)
          offset += varint.encode.bytes
        }
        for (var i = 0; i < obj.checkpoint.length; i++) {
          if (!defined(obj.checkpoint[i])) continue
          encodings.varint.encode(obj.checkpoint[i], buf, offset)
          offset += encodings.varint.encode.bytes
        }
      }
      encode.bytes = offset - oldOffset
      return buf
    }

    function decode (buf, offset, end) {
      if (!offset) offset = 0
      if (!end) end = buf.length
      if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
      var oldOffset = offset
      var obj = {
        version: 0,
        gte: null,
        gt: null,
        lte: null,
        lt: null,
        limit: 0,
        reverse: false,
        checkpoint: []
      }
      while (true) {
        if (end <= offset) {
          decode.bytes = offset - oldOffset
          return obj
        }
        var prefix = varint.decode(buf, offset)
        offset += varint.decode.bytes
        var tag = prefix >> 3
        switch (tag) {
          case 1:
          obj.version = encodings.varint.decode(buf, offset)
          offset += encodings.varint.decode.bytes
          break
          case 2:
          obj.gte = encodings.bytes.decode(buf, offset)
          offset += encodings.bytes.decode.bytes
          break
          case 3:
          obj.gt = encodings.bytes.decode(buf, offset)
          offset += encodings.bytes.decode.bytes
          break
          case 4:
          obj.lte = encodings.bytes.decode(buf, offset)
          offset += encodings.bytes.decode.bytes
          break
          case 5:
          obj.lt = encodings.bytes.decode(buf, offset)
          offset += encodings.bytes.decode.bytes
          break
          case 6:
          obj.limit = encodings.varint.decode(buf, offset)
          offset += encodings.varint.decode.bytes
          break
          case 7:
          obj.reverse = encodings.bool.decode(buf, offset)
          offset += encodings.bool.decode.bytes
          break
          case 8:
          var packedEnd = varint.decode(buf, offset)
          offset += varint.decode.bytes
          packedEnd += offset
          while (offset < packedEnd) {
            obj.checkpoint.push(encodings.varint.decode(buf, offset))
            offset += encodings.varint.decode.bytes
          }
          break
          default:
          offset = skip(prefix & 7, buf, offset)
        }
      }
    }
  }

  function defineCache () {
    Cache.encodingLength = encodingLength
    Cache.encode = encode
    Cache.decode = decode

    function encodingLength (obj) {
      var length = 0
      if (!defined(obj.start)) throw new Error("start is required")
      var len = encodings.varint.encodingLength(obj.start)
      length += 1 + len
      if (!defined(obj.end)) throw new Error("end is required")
      var len = encodings.varint.encodingLength(obj.end)
      length += 1 + len
      if (defined(obj.blocks)) {
        var packedLen = 0
        for (var i = 0; i < obj.blocks.length; i++) {
          if (!defined(obj.blocks[i])) continue
          var len = encodings.varint.encodingLength(obj.blocks[i])
          packedLen += len
        }
        if (packedLen) {
          length += 1 + packedLen + varint.encodingLength(packedLen)
        }
      }
      return length
    }

    function encode (obj, buf, offset) {
      if (!offset) offset = 0
      if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
      var oldOffset = offset
      if (!defined(obj.start)) throw new Error("start is required")
      buf[offset++] = 8
      encodings.varint.encode(obj.start, buf, offset)
      offset += encodings.varint.encode.bytes
      if (!defined(obj.end)) throw new Error("end is required")
      buf[offset++] = 16
      encodings.varint.encode(obj.end, buf, offset)
      offset += encodings.varint.encode.bytes
      if (defined(obj.blocks)) {
        var packedLen = 0
        for (var i = 0; i < obj.blocks.length; i++) {
          if (!defined(obj.blocks[i])) continue
          packedLen += encodings.varint.encodingLength(obj.blocks[i])
        }
        if (packedLen) {
          buf[offset++] = 26
          varint.encode(packedLen, buf, offset)
          offset += varint.encode.bytes
        }
        for (var i = 0; i < obj.blocks.length; i++) {
          if (!defined(obj.blocks[i])) continue
          encodings.varint.encode(obj.blocks[i], buf, offset)
          offset += encodings.varint.encode.bytes
        }
      }
      encode.bytes = offset - oldOffset
      return buf
    }

    function decode (buf, offset, end) {
      if (!offset) offset = 0
      if (!end) end = buf.length
      if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
      var oldOffset = offset
      var obj = {
        start: 0,
        end: 0,
        blocks: []
      }
      var found0 = false
      var found1 = false
      while (true) {
        if (end <= offset) {
          if (!found0 || !found1) throw new Error("Decoded message is not valid")
          decode.bytes = offset - oldOffset
          return obj
        }
        var prefix = varint.decode(buf, offset)
        offset += varint.decode.bytes
        var tag = prefix >> 3
        switch (tag) {
          case 1:
          obj.start = encodings.varint.decode(buf, offset)
          offset += encodings.varint.decode.bytes
          found0 = true
          break
          case 2:
          obj.end = encodings.varint.decode(buf, offset)
          offset += encodings.varint.decode.bytes
          found1 = true
          break
          case 3:
          var packedEnd = varint.decode(buf, offset)
          offset += varint.decode.bytes
          packedEnd += offset
          while (offset < packedEnd) {
            obj.blocks.push(encodings.varint.decode(buf, offset))
            offset += encodings.varint.decode.bytes
          }
          break
          default:
          offset = skip(prefix & 7, buf, offset)
        }
      }
    }
  }

  Extension.encodingLength = encodingLength
  Extension.encode = encode
  Extension.decode = decode

  function encodingLength (obj) {
    var length = 0
    if (defined(obj.cache)) {
      var len = Cache.encodingLength(obj.cache)
      length += varint.encodingLength(len)
      length += 1 + len
    }
    if (defined(obj.get)) {
      var len = Get.encodingLength(obj.get)
      length += varint.encodingLength(len)
      length += 1 + len
    }
    if (defined(obj.iterator)) {
      var len = Iterator.encodingLength(obj.iterator)
      length += varint.encodingLength(len)
      length += 1 + len
    }
    return length
  }

  function encode (obj, buf, offset) {
    if (!offset) offset = 0
    if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
    var oldOffset = offset
    if (defined(obj.cache)) {
      buf[offset++] = 10
      varint.encode(Cache.encodingLength(obj.cache), buf, offset)
      offset += varint.encode.bytes
      Cache.encode(obj.cache, buf, offset)
      offset += Cache.encode.bytes
    }
    if (defined(obj.get)) {
      buf[offset++] = 18
      varint.encode(Get.encodingLength(obj.get), buf, offset)
      offset += varint.encode.bytes
      Get.encode(obj.get, buf, offset)
      offset += Get.encode.bytes
    }
    if (defined(obj.iterator)) {
      buf[offset++] = 26
      varint.encode(Iterator.encodingLength(obj.iterator), buf, offset)
      offset += varint.encode.bytes
      Iterator.encode(obj.iterator, buf, offset)
      offset += Iterator.encode.bytes
    }
    encode.bytes = offset - oldOffset
    return buf
  }

  function decode (buf, offset, end) {
    if (!offset) offset = 0
    if (!end) end = buf.length
    if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
    var oldOffset = offset
    var obj = {
      cache: null,
      get: null,
      iterator: null
    }
    while (true) {
      if (end <= offset) {
        decode.bytes = offset - oldOffset
        return obj
      }
      var prefix = varint.decode(buf, offset)
      offset += varint.decode.bytes
      var tag = prefix >> 3
      switch (tag) {
        case 1:
        var len = varint.decode(buf, offset)
        offset += varint.decode.bytes
        obj.cache = Cache.decode(buf, offset, offset + len)
        offset += Cache.decode.bytes
        break
        case 2:
        var len = varint.decode(buf, offset)
        offset += varint.decode.bytes
        obj.get = Get.decode(buf, offset, offset + len)
        offset += Get.decode.bytes
        break
        case 3:
        var len = varint.decode(buf, offset)
        offset += varint.decode.bytes
        obj.iterator = Iterator.decode(buf, offset, offset + len)
        offset += Iterator.decode.bytes
        break
        default:
        offset = skip(prefix & 7, buf, offset)
      }
    }
  }
}

function defined (val) {
  return val !== null && val !== undefined && (typeof val !== 'number' || !isNaN(val))
}
{
  "name": "hyperbee",
  "version": "2.27.3",
  "description": "An append-only B-tree running on a Hypercore.",
  "main": "index.js",
  "files": [
    "index.js",
    "lib/**.js",
    "iterators/**.js"
  ],
  "dependencies": {
    "b4a": "^1.6.0",
    "codecs": "^3.0.0",
    "debounceify": "^1.0.0",
    "hypercore-errors": "^1.0.0",
    "mutexify": "^1.4.0",
    "protocol-buffers-encodings": "^1.2.0",
    "rache": "^1.0.0",
    "ready-resource": "^1.0.0",
    "resolve-reject-promise": "^1.1.0",
    "safety-catch": "^1.0.2",
    "streamx": "^2.12.4",
    "unslab": "^1.2.0"
  },
  "devDependencies": {
    "bare-process": "^4.2.2",
    "brittle": "^3.1.0",
    "hypercore": "^11.0.0",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "protocol-buffers": "^4.2.0",
    "sub-encoder": "^1.0.6",
    "tree-to-string": "^1.1.1"
  },
  "imports": {
    "process": {
      "bare": "bare-process",
      "default": "process"
    }
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test/*.js",
    "test:bare": "brittle-bare test/*.js",
    "protobuf": "protocol-buffers schema.proto -o ./lib/messages.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/hyperbee.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/hyperbee/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperbee"
}
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const b4a = require('b4a')

// https://en.wikipedia.org/wiki/Merkle_tree#Second_preimage_attack
const LEAF_TYPE = b4a.from([0])
const PARENT_TYPE = b4a.from([1])
const ROOT_TYPE = b4a.from([2])

const HYPERCORE = b4a.from('hypercore')

exports.keyPair = function (seed) {
  // key pairs might stay around for a while, so better not to use a default slab to avoid retaining it completely
  const slab = b4a.allocUnsafeSlow(
    sodium.crypto_sign_PUBLICKEYBYTES + sodium.crypto_sign_SECRETKEYBYTES
  )
  const publicKey = slab.subarray(0, sodium.crypto_sign_PUBLICKEYBYTES)
  const secretKey = slab.subarray(sodium.crypto_sign_PUBLICKEYBYTES)

  if (seed) sodium.crypto_sign_seed_keypair(publicKey, secretKey, seed)
  else sodium.crypto_sign_keypair(publicKey, secretKey)

  return {
    publicKey,
    secretKey
  }
}

exports.validateKeyPair = function (keyPair) {
  const pk = b4a.allocUnsafe(sodium.crypto_sign_PUBLICKEYBYTES)
  sodium.crypto_sign_ed25519_sk_to_pk(pk, keyPair.secretKey)
  return b4a.equals(pk, keyPair.publicKey)
}

exports.sign = function (message, secretKey) {
  // Dedicated slab for the signature, to avoid retaining unneeded mem and for security
  const signature = b4a.allocUnsafeSlow(sodium.crypto_sign_BYTES)
  sodium.crypto_sign_detached(signature, message, secretKey)
  return signature
}

exports.verify = function (message, signature, publicKey) {
  if (signature.byteLength !== sodium.crypto_sign_BYTES) return false
  if (publicKey.byteLength !== sodium.crypto_sign_PUBLICKEYBYTES) return false
  return sodium.crypto_sign_verify_detached(signature, message, publicKey)
}

exports.encrypt = function (message, publicKey) {
  const ciphertext = b4a.alloc(message.byteLength + sodium.crypto_box_SEALBYTES)
  sodium.crypto_box_seal(ciphertext, message, publicKey)
  return ciphertext
}

exports.decrypt = function (ciphertext, keyPair) {
  if (ciphertext.byteLength < sodium.crypto_box_SEALBYTES) return null

  const plaintext = b4a.alloc(ciphertext.byteLength - sodium.crypto_box_SEALBYTES)

  if (!sodium.crypto_box_seal_open(plaintext, ciphertext, keyPair.publicKey, keyPair.secretKey)) {
    return null
  }

  return plaintext
}

exports.encryptionKeyPair = function (seed) {
  const publicKey = b4a.alloc(sodium.crypto_box_PUBLICKEYBYTES)
  const secretKey = b4a.alloc(sodium.crypto_box_SECRETKEYBYTES)

  if (seed) {
    sodium.crypto_box_seed_keypair(publicKey, secretKey, seed)
  } else {
    sodium.crypto_box_keypair(publicKey, secretKey)
  }

  return {
    publicKey,
    secretKey
  }
}

exports.data = function (data) {
  const out = b4a.allocUnsafe(32)

  sodium.crypto_generichash_batch(out, [LEAF_TYPE, c.encode(c.uint64, data.byteLength), data])

  return out
}

exports.parent = function (a, b) {
  if (a.index > b.index) {
    const tmp = a
    a = b
    b = tmp
  }

  const out = b4a.allocUnsafe(32)

  sodium.crypto_generichash_batch(out, [
    PARENT_TYPE,
    c.encode(c.uint64, a.size + b.size),
    a.hash,
    b.hash
  ])

  return out
}

exports.tree = function (roots, out) {
  const buffers = new Array(3 * roots.length + 1)
  let j = 0

  buffers[j++] = ROOT_TYPE

  for (let i = 0; i < roots.length; i++) {
    const r = roots[i]
    buffers[j++] = r.hash
    buffers[j++] = c.encode(c.uint64, r.index)
    buffers[j++] = c.encode(c.uint64, r.size)
  }

  if (!out) out = b4a.allocUnsafe(32)
  sodium.crypto_generichash_batch(out, buffers)
  return out
}

exports.hash = function (data, out) {
  if (!out) out = b4a.allocUnsafe(32)
  if (!Array.isArray(data)) data = [data]

  sodium.crypto_generichash_batch(out, data)

  return out
}

exports.randomBytes = function (n) {
  const buf = b4a.allocUnsafe(n)
  sodium.randombytes_buf(buf)
  return buf
}

exports.discoveryKey = function (key) {
  if (!key || key.byteLength !== 32) throw new Error('Must pass a 32 byte buffer')
  // Discovery keys might stay around for a while, so better not to use slab memory (for better gc)
  const digest = b4a.allocUnsafeSlow(32)
  sodium.crypto_generichash(digest, HYPERCORE, key)
  return digest
}

if (sodium.sodium_free) {
  exports.free = function (secureBuf) {
    if (secureBuf.secure) sodium.sodium_free(secureBuf)
  }
} else {
  exports.free = function () {}
}

exports.namespace = function (name, count) {
  const ids = typeof count === 'number' ? range(count) : count

  // Namespaces are long-lived, so better to use a dedicated slab
  const buf = b4a.allocUnsafeSlow(32 * ids.length)

  const list = new Array(ids.length)

  // ns is ephemeral, so default slab
  const ns = b4a.allocUnsafe(33)
  sodium.crypto_generichash(ns.subarray(0, 32), typeof name === 'string' ? b4a.from(name) : name)

  for (let i = 0; i < list.length; i++) {
    list[i] = buf.subarray(32 * i, 32 * i + 32)
    ns[32] = ids[i]
    sodium.crypto_generichash(list[i], ns)
  }

  return list
}

function range(count) {
  const arr = new Array(count)
  for (let i = 0; i < count; i++) arr[i] = i
  return arr
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "hypercore-crypto",
  "version": "3.7.0",
  "description": "The crypto primitives used in hypercore, extracted into a separate module",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.6.6",
    "compact-encoding": "^3.0.0",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "brittle": "^3.5.0",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/hypercore-crypto.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/hypercore-crypto/issues"
  },
  "homepage": "https://github.com/mafintosh/hypercore-crypto"
}
const IdEnc = require('hypercore-id-encoding')

module.exports = class HypercoreError extends Error {
  constructor (msg, code, fn = HypercoreError, discoveryKey = null) {
    if (discoveryKey) msg = `${msg} (discovery key: ${IdEnc.normalize(discoveryKey)})`
    super(`${code}: ${msg}`)

    this.code = code
    this.discoveryKey = discoveryKey

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name () {
    return 'HypercoreError'
  }

  static ASSERTION (msg, discoveryKey = null) { // ERR_ASSERTION is picked up by safety-catch also
    return new HypercoreError(msg, 'ERR_ASSERTION', HypercoreError.ASSERT, discoveryKey)
  }

  static BAD_ARGUMENT (msg, discoveryKey = null) {
    return new HypercoreError(msg, 'BAD_ARGUMENT', HypercoreError.BAD_ARGUMENT, discoveryKey)
  }

  static STORAGE_EMPTY (msg, discoveryKey = null) {
    return new HypercoreError(msg, 'STORAGE_EMPTY', HypercoreError.STORAGE_EMPTY, discoveryKey)
  }

  static STORAGE_CONFLICT (msg, discoveryKey = null) {
    return new HypercoreError(msg, 'STORAGE_CONFLICT', HypercoreError.STORAGE_CONFLICT, discoveryKey)
  }

  static INVALID_SIGNATURE (msg, discoveryKey = null) {
    return new HypercoreError(msg, 'INVALID_SIGNATURE', HypercoreError.INVALID_SIGNATURE, discoveryKey)
  }

  static INVALID_CAPABILITY (msg, discoveryKey = null) {
    return new HypercoreError(msg, 'INVALID_CAPABILITY', HypercoreError.INVALID_CAPABILITY, discoveryKey)
  }

  static INVALID_CHECKSUM (msg = 'Invalid checksum', discoveryKey = null) {
    return new HypercoreError(msg, 'INVALID_CHECKSUM', HypercoreError.INVALID_CHECKSUM, discoveryKey)
  }

  static INVALID_OPERATION (msg, discoveryKey = null) {
    return new HypercoreError(msg, 'INVALID_OPERATION', HypercoreError.INVALID_OPERATION, discoveryKey)
  }

  static INVALID_PROOF (msg = 'Proof not verifiable', discoveryKey = null) {
    return new HypercoreError(msg, 'INVALID_PROOF', HypercoreError.INVALID_PROOF, discoveryKey)
  }

  static BLOCK_NOT_AVAILABLE (msg = 'Block is not available', discoveryKey = null) {
    return new HypercoreError(msg, 'BLOCK_NOT_AVAILABLE', HypercoreError.BLOCK_NOT_AVAILABLE, discoveryKey)
  }

  static SNAPSHOT_NOT_AVAILABLE (msg = 'Snapshot is not available', discoveryKey = null) {
    return new HypercoreError(msg, 'SNAPSHOT_NOT_AVAILABLE', HypercoreError.SNAPSHOT_NOT_AVAILABLE, discoveryKey)
  }

  static REQUEST_CANCELLED (msg = 'Request was cancelled', discoveryKey = null) {
    return new HypercoreError(msg, 'REQUEST_CANCELLED', HypercoreError.REQUEST_CANCELLED, discoveryKey)
  }

  static REQUEST_TIMEOUT (msg = 'Request timed out', discoveryKey = null) {
    return new HypercoreError(msg, 'REQUEST_TIMEOUT', HypercoreError.REQUEST_TIMEOUT, discoveryKey)
  }

  static SESSION_NOT_WRITABLE (msg = 'Session is not writable', discoveryKey = null) {
    return new HypercoreError(msg, 'SESSION_NOT_WRITABLE', HypercoreError.SESSION_NOT_WRITABLE, discoveryKey)
  }

  static SESSION_CLOSED (msg = 'Session is closed', discoveryKey = null) {
    return new HypercoreError(msg, 'SESSION_CLOSED', HypercoreError.SESSION_CLOSED, discoveryKey)
  }

  static BATCH_UNFLUSHED (msg = 'Batch not yet flushed', discoveryKey = null) {
    return new HypercoreError(msg, 'BATCH_UNFLUSHED', HypercoreError.BATCH_UNFLUSHED, discoveryKey)
  }

  static BATCH_ALREADY_EXISTS (msg = 'Batch already exists', discoveryKey = null) {
    return new HypercoreError(msg, 'BATCH_ALREADY_EXISTS', HypercoreError.BATCH_ALREADY_EXISTS, discoveryKey)
  }

  static BATCH_ALREADY_FLUSHED (msg = 'Batch has already been flushed', discoveryKey = null) {
    return new HypercoreError(msg, 'BATCH_ALREADY_FLUSHED', HypercoreError.BATCH_ALREADY_FLUSHED, discoveryKey)
  }

  static OPLOG_CORRUPT (msg = 'Oplog file appears corrupt or out of date', discoveryKey = null) {
    return new HypercoreError(msg, 'OPLOG_CORRUPT', HypercoreError.OPLOG_CORRUPT, discoveryKey)
  }

  static OPLOG_HEADER_OVERFLOW (msg = 'Oplog header exceeds page size', discoveryKey = null) {
    return new HypercoreError(msg, 'OPLOG_HEADER_OVERFLOW', HypercoreError.OPLOG_HEADER_OVERFLOW, discoveryKey)
  }

  static INVALID_OPLOG_VERSION (msg = 'Invalid header version', discoveryKey = null) {
    return new HypercoreError(msg, 'INVALID_OPLOG_VERSION', HypercoreError.INVALID_OPLOG_VERSION, discoveryKey)
  }

  static WRITE_FAILED (msg = 'Write to storage failed', discoveryKey = null) {
    return new HypercoreError(msg, 'WRITE_FAILED', HypercoreError.WRITE_FAILED, discoveryKey)
  }

  static DECODING_ERROR (msg = 'Decoding error', discoveryKey = null) {
    return new HypercoreError(msg, 'DECODING_ERROR', HypercoreError.DECODING_ERROR, discoveryKey)
  }

  static SESSION_MOVED (msg = 'Session moved', discoveryKey = null) {
    return new HypercoreError(msg, 'SESSION_MOVED', HypercoreError.SESSION_MOVED, discoveryKey)
  }
}
{
  "name": "hypercore-errors",
  "version": "1.5.0",
  "description": "Hypercore errors",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/hypercore-errors.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/hypercore-errors/issues"
  },
  "homepage": "https://github.com/holepunchto/hypercore-errors#readme",
  "devDependencies": {
    "b4a": "^1.6.7",
    "brittle": "^3.1.3",
    "standard": "^17.0.0"
  },
  "dependencies": {
    "hypercore-id-encoding": "^1.3.0"
  }
}
const z32 = require('z32')
const b4a = require('b4a')

module.exports = {
  encode,
  decode,
  normalize,
  isValid
}

function encode (key) {
  if (!b4a.isBuffer(key)) throw new Error('Key must be a Buffer')
  if (key.byteLength !== 32) throw new Error('Key must be 32-bytes long')
  return z32.encode(key)
}

function decode (id) {
  if (b4a.isBuffer(id)) {
    if (id.byteLength !== 32) throw new Error('ID must be 32-bytes long')
    return id
  }
  if (typeof id === 'string') {
    if (id.startsWith('pear://')) id = id.slice(7).split('/')[0]
    if (id.length === 52) return z32.decode(id)
    if (id.length === 64) {
      const buf = b4a.from(id, 'hex')
      if (buf.byteLength === 32) return buf
    }
  }
  throw new Error('Invalid Hypercore key')
}

function normalize (any) {
  return encode(decode(any))
}

function isValid (any) {
  try {
    decode(any)
    return true
  } catch {
    return false
  }
}
{
  "name": "hypercore-id-encoding",
  "version": "1.3.0",
  "description": "Convert Hypercore keys to/from z-base32 or hex",
  "main": "index.js",
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.5.3",
    "z32": "^1.0.0"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "hypercore": "^10.0.0",
    "random-access-memory": "^6.0.0",
    "standard": "^17.1.0"
  },
  "license": "Apache-2.0",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/hypercore-id-encoding.git"
  },
  "keywords": [],
  "author": "",
  "bugs": {
    "url": "https://github.com/holepunchto/hypercore-id-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/hypercore-id-encoding#readme"
}
function headLegacyMap(m) {
  return {
    version: 2, // version bumped from 1
    cores: m.allocated.cores,
    datas: m.allocated.datas,
    groups: 0,
    seed: m.seed,
    defaultDiscoveryKey: m.defaultDiscoveryKey
  }
}

module.exports = {
  headLegacyMap
}
// This file is autogenerated by the hyperschema compiler
// Schema Version: 2
/* eslint-disable camelcase */
/* eslint-disable quotes */
/* eslint-disable space-before-function-paren */

const { c } = require('hyperschema/runtime')
const external0 = require('../../external.js')

const VERSION = 2

// eslint-disable-next-line no-unused-vars
let version = VERSION

// @corestore/allocated
const encoding0 = {
  preencode(state, m) {
    c.uint.preencode(state, m.cores)
    c.uint.preencode(state, m.datas)
  },
  encode(state, m) {
    c.uint.encode(state, m.cores)
    c.uint.encode(state, m.datas)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const r1 = c.uint.decode(state)

    return {
      cores: r0,
      datas: r1
    }
  }
}

// @corestore/head-v1
const encoding1 = {
  preencode(state, m) {
    state.end++ // max flag is 4 so always one byte

    if (m.allocated) encoding0.preencode(state, m.allocated)
    if (m.seed) c.fixed32.preencode(state, m.seed)
    if (m.defaultDiscoveryKey) c.fixed32.preencode(state, m.defaultDiscoveryKey)
  },
  encode(state, m) {
    const flags = (m.allocated ? 1 : 0) | (m.seed ? 2 : 0) | (m.defaultDiscoveryKey ? 4 : 0)

    c.uint.encode(state, flags)

    if (m.allocated) encoding0.encode(state, m.allocated)
    if (m.seed) c.fixed32.encode(state, m.seed)
    if (m.defaultDiscoveryKey) c.fixed32.encode(state, m.defaultDiscoveryKey)
  },
  decode(state) {
    const v = c.uint.decode(state)
    const flags = c.uint.decode(state)

    return {
      version: v,
      allocated: (flags & 1) !== 0 ? encoding0.decode(state) : null,
      seed: (flags & 2) !== 0 ? c.fixed32.decode(state) : null,
      defaultDiscoveryKey: (flags & 4) !== 0 ? c.fixed32.decode(state) : null
    }
  }
}

// @corestore/head-v2
const encoding2 = {
  preencode(state, m) {
    c.uint.preencode(state, m.cores)
    c.uint.preencode(state, m.datas)
    c.uint.preencode(state, m.groups)
    state.end++ // max flag is 2 so always one byte

    if (m.seed) c.fixed32.preencode(state, m.seed)
    if (m.defaultDiscoveryKey) c.fixed32.preencode(state, m.defaultDiscoveryKey)
  },
  encode(state, m) {
    const flags = (m.seed ? 1 : 0) | (m.defaultDiscoveryKey ? 2 : 0)

    c.uint.encode(state, m.cores)
    c.uint.encode(state, m.datas)
    c.uint.encode(state, m.groups)
    c.uint.encode(state, flags)

    if (m.seed) c.fixed32.encode(state, m.seed)
    if (m.defaultDiscoveryKey) c.fixed32.encode(state, m.defaultDiscoveryKey)
  },
  decode(state) {
    const v = c.uint.decode(state)
    const r0 = c.uint.decode(state)
    const r1 = c.uint.decode(state)
    const r2 = c.uint.decode(state)
    const flags = c.uint.decode(state)

    return {
      version: v,
      cores: r0,
      datas: r1,
      groups: r2,
      seed: (flags & 1) !== 0 ? c.fixed32.decode(state) : null,
      defaultDiscoveryKey: (flags & 2) !== 0 ? c.fixed32.decode(state) : null
    }
  }
}

// @corestore/head
const encoding3 = {
  preencode(state, m) {
    c.uint.preencode(state, m.version)
    switch (m.version) {
      case 0:
      case 1:
        encoding1.preencode(state, m)
        break
      case 2:
        encoding2.preencode(state, m)
        break
      default:
        throw new Error('Unsupported version')
    }
  },
  encode(state, m) {
    c.uint.encode(state, m.version)
    switch (m.version) {
      case 0:
      case 1:
        encoding1.encode(state, m)
        break
      case 2:
        encoding2.encode(state, m)
        break
      default:
        throw new Error('Unsupported version')
    }
  },
  decode(state) {
    const start = state.start
    const v = c.uint.decode(state)
    state.start = start
    switch (v) {
      case 0:
      case 1: {
        const decoded = encoding1.decode(state)
        const map = external0.headLegacyMap
        return map(decoded)
      }
      case 2: {
        const decoded = encoding2.decode(state)
        return decoded
      }
      default:
        throw new Error('Unsupported version')
    }
  }
}

// @corestore/alias
const encoding4 = {
  preencode(state, m) {
    c.string.preencode(state, m.name)
    c.fixed32.preencode(state, m.namespace)
  },
  encode(state, m) {
    c.string.encode(state, m.name)
    c.fixed32.encode(state, m.namespace)
  },
  decode(state) {
    const r0 = c.string.decode(state)
    const r1 = c.fixed32.decode(state)

    return {
      name: r0,
      namespace: r1
    }
  }
}

// @corestore/core
const encoding5 = {
  preencode(state, m) {
    c.uint.preencode(state, m.version)
    c.uint.preencode(state, m.corePointer)
    c.uint.preencode(state, m.dataPointer)
    state.end++ // max flag is 1 so always one byte

    if (m.alias) encoding4.preencode(state, m.alias)
  },
  encode(state, m) {
    const flags = m.alias ? 1 : 0

    c.uint.encode(state, m.version)
    c.uint.encode(state, m.corePointer)
    c.uint.encode(state, m.dataPointer)
    c.uint.encode(state, flags)

    if (m.alias) encoding4.encode(state, m.alias)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const r1 = c.uint.decode(state)
    const r2 = c.uint.decode(state)
    const flags = c.uint.decode(state)

    return {
      version: r0,
      corePointer: r1,
      dataPointer: r2,
      alias: (flags & 1) !== 0 ? encoding4.decode(state) : null
    }
  }
}

const encoding6_enum = {
  blake2b: 'blake2b'
}

// @core/hashes enum
const encoding6 = {
  preencode(state, m) {
    state.end++ // max enum is 0 so always one byte
  },
  encode(state, m) {
    switch (m) {
      case 'blake2b':
        c.uint.encode(state, 0)
        break
      default:
        throw new Error('Unknown enum')
    }
  },
  decode(state) {
    switch (c.uint.decode(state)) {
      case 0:
        return 'blake2b'
      default:
        return null
    }
  }
}

const encoding7_enum = {
  ed25519: 'ed25519'
}

// @core/signatures enum
const encoding7 = {
  preencode(state, m) {
    state.end++ // max enum is 0 so always one byte
  },
  encode(state, m) {
    switch (m) {
      case 'ed25519':
        c.uint.encode(state, 0)
        break
      default:
        throw new Error('Unknown enum')
    }
  },
  decode(state) {
    switch (c.uint.decode(state)) {
      case 0:
        return 'ed25519'
      default:
        return null
    }
  }
}

// @core/tree-node
const encoding8 = {
  preencode(state, m) {
    c.uint.preencode(state, m.index)
    c.uint.preencode(state, m.size)
    c.fixed32.preencode(state, m.hash)
  },
  encode(state, m) {
    c.uint.encode(state, m.index)
    c.uint.encode(state, m.size)
    c.fixed32.encode(state, m.hash)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const r1 = c.uint.decode(state)
    const r2 = c.fixed32.decode(state)

    return {
      index: r0,
      size: r1,
      hash: r2
    }
  }
}

// @core/signer
const encoding9 = {
  preencode(state, m) {
    encoding7.preencode(state, m.signature)
    c.fixed32.preencode(state, m.namespace)
    c.fixed32.preencode(state, m.publicKey)
  },
  encode(state, m) {
    encoding7.encode(state, m.signature)
    c.fixed32.encode(state, m.namespace)
    c.fixed32.encode(state, m.publicKey)
  },
  decode(state) {
    const r0 = encoding7.decode(state)
    const r1 = c.fixed32.decode(state)
    const r2 = c.fixed32.decode(state)

    return {
      signature: r0,
      namespace: r1,
      publicKey: r2
    }
  }
}

// @core/prologue
const encoding10 = {
  preencode(state, m) {
    c.fixed32.preencode(state, m.hash)
    c.uint.preencode(state, m.length)
  },
  encode(state, m) {
    c.fixed32.encode(state, m.hash)
    c.uint.encode(state, m.length)
  },
  decode(state) {
    const r0 = c.fixed32.decode(state)
    const r1 = c.uint.decode(state)

    return {
      hash: r0,
      length: r1
    }
  }
}

// @core/manifest.signers
const encoding11_4 = c.array(encoding9)
// @core/manifest.linked
const encoding11_6 = c.array(c.fixed32)

// @core/manifest
const encoding11 = {
  preencode(state, m) {
    c.uint.preencode(state, m.version)
    state.end++ // max flag is 8 so always one byte
    encoding6.preencode(state, m.hash)
    c.uint.preencode(state, m.quorum)
    encoding11_4.preencode(state, m.signers)

    if (m.prologue) encoding10.preencode(state, m.prologue)
    if (m.linked) encoding11_6.preencode(state, m.linked)
    if (m.userData) c.buffer.preencode(state, m.userData)
  },
  encode(state, m) {
    const flags =
      (m.allowPatch ? 1 : 0) | (m.prologue ? 2 : 0) | (m.linked ? 4 : 0) | (m.userData ? 8 : 0)

    c.uint.encode(state, m.version)
    c.uint.encode(state, flags)
    encoding6.encode(state, m.hash)
    c.uint.encode(state, m.quorum)
    encoding11_4.encode(state, m.signers)

    if (m.prologue) encoding10.encode(state, m.prologue)
    if (m.linked) encoding11_6.encode(state, m.linked)
    if (m.userData) c.buffer.encode(state, m.userData)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const flags = c.uint.decode(state)

    return {
      version: r0,
      hash: encoding6.decode(state),
      quorum: c.uint.decode(state),
      allowPatch: (flags & 1) !== 0,
      signers: encoding11_4.decode(state),
      prologue: (flags & 2) !== 0 ? encoding10.decode(state) : null,
      linked: (flags & 4) !== 0 ? encoding11_6.decode(state) : null,
      userData: (flags & 8) !== 0 ? c.buffer.decode(state) : null
    }
  }
}

// @core/keyPair
const encoding12 = {
  preencode(state, m) {
    c.buffer.preencode(state, m.publicKey)
    c.optionalBuffer.preencode(state, m.secretKey)
  },
  encode(state, m) {
    c.buffer.encode(state, m.publicKey)
    c.optionalBuffer.encode(state, m.secretKey)
  },
  decode(state) {
    const r0 = c.buffer.decode(state)
    const r1 = c.optionalBuffer.decode(state)

    return {
      publicKey: r0,
      secretKey: r1
    }
  }
}

// @core/group
const encoding13 = {
  preencode(state, m) {
    state.end++ // max flag is 2 so always one byte

    if (m.key) c.fixed32.preencode(state, m.key)
    if (m.pointer) c.uint.preencode(state, m.pointer)
  },
  encode(state, m) {
    const flags = (m.key ? 1 : 0) | (m.pointer ? 2 : 0)

    c.uint.encode(state, flags)

    if (m.key) c.fixed32.encode(state, m.key)
    if (m.pointer) c.uint.encode(state, m.pointer)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      key: (flags & 1) !== 0 ? c.fixed32.decode(state) : null,
      pointer: (flags & 2) !== 0 ? c.uint.decode(state) : 0
    }
  }
}

// @core/auth.manifest
const encoding14_2 = c.frame(encoding11)

// @core/auth
const encoding14 = {
  preencode(state, m) {
    c.fixed32.preencode(state, m.key)
    c.fixed32.preencode(state, m.discoveryKey)
    state.end++ // max flag is 4 so always one byte

    if (m.manifest) encoding14_2.preencode(state, m.manifest)
    if (m.keyPair) encoding12.preencode(state, m.keyPair)
    if (m.encryptionKey) c.buffer.preencode(state, m.encryptionKey)
  },
  encode(state, m) {
    const flags = (m.manifest ? 1 : 0) | (m.keyPair ? 2 : 0) | (m.encryptionKey ? 4 : 0)

    c.fixed32.encode(state, m.key)
    c.fixed32.encode(state, m.discoveryKey)
    c.uint.encode(state, flags)

    if (m.manifest) encoding14_2.encode(state, m.manifest)
    if (m.keyPair) encoding12.encode(state, m.keyPair)
    if (m.encryptionKey) c.buffer.encode(state, m.encryptionKey)
  },
  decode(state) {
    const r0 = c.fixed32.decode(state)
    const r1 = c.fixed32.decode(state)
    const flags = c.uint.decode(state)

    return {
      key: r0,
      discoveryKey: r1,
      manifest: (flags & 1) !== 0 ? encoding14_2.decode(state) : null,
      keyPair: (flags & 2) !== 0 ? encoding12.decode(state) : null,
      encryptionKey: (flags & 4) !== 0 ? c.buffer.decode(state) : null
    }
  }
}

// @core/head
const encoding15 = {
  preencode(state, m) {
    c.uint.preencode(state, m.fork)
    c.uint.preencode(state, m.length)
    c.fixed32.preencode(state, m.rootHash)
    c.optionalBuffer.preencode(state, m.signature)
    state.end++ // max flag is 1 so always one byte

    if (version >= 2 && m.timestamp) c.uint64.preencode(state, m.timestamp)
  },
  encode(state, m) {
    const flags = version >= 2 && m.timestamp ? 1 : 0

    c.uint.encode(state, m.fork)
    c.uint.encode(state, m.length)
    c.fixed32.encode(state, m.rootHash)
    c.optionalBuffer.encode(state, m.signature)
    c.uint.encode(state, flags)

    if (version >= 2 && m.timestamp) c.uint64.encode(state, m.timestamp)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const r1 = c.uint.decode(state)
    const r2 = c.fixed32.decode(state)
    const r3 = c.optionalBuffer.decode(state)
    const flags = state.start < state.end ? c.uint.decode(state) : 0

    return {
      fork: r0,
      length: r1,
      rootHash: r2,
      signature: r3,
      timestamp: version >= 2 && (flags & 1) !== 0 ? c.uint64.decode(state) : 0
    }
  }
}

// @core/hints
const encoding16 = {
  preencode(state, m) {
    state.end++ // max flag is 4 so always one byte

    if (m.contiguousLength) c.uint.preencode(state, m.contiguousLength)
    if (m.remoteContiguousLength) c.uint.preencode(state, m.remoteContiguousLength)
    if (m.recovering) c.uint.preencode(state, m.recovering)
  },
  encode(state, m) {
    const flags =
      (m.contiguousLength ? 1 : 0) | (m.remoteContiguousLength ? 2 : 0) | (m.recovering ? 4 : 0)

    c.uint.encode(state, flags)

    if (m.contiguousLength) c.uint.encode(state, m.contiguousLength)
    if (m.remoteContiguousLength) c.uint.encode(state, m.remoteContiguousLength)
    if (m.recovering) c.uint.encode(state, m.recovering)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      contiguousLength: (flags & 1) !== 0 ? c.uint.decode(state) : 0,
      remoteContiguousLength: (flags & 2) !== 0 ? c.uint.decode(state) : 0,
      recovering: (flags & 4) !== 0 ? c.uint.decode(state) : 0
    }
  }
}

// @core/session
const encoding17 = {
  preencode(state, m) {
    c.string.preencode(state, m.name)
    c.uint.preencode(state, m.dataPointer)
  },
  encode(state, m) {
    c.string.encode(state, m.name)
    c.uint.encode(state, m.dataPointer)
  },
  decode(state) {
    const r0 = c.string.decode(state)
    const r1 = c.uint.decode(state)

    return {
      name: r0,
      dataPointer: r1
    }
  }
}

// @core/sessions
const encoding18 = c.array(encoding17)

// @core/dependency
const encoding19 = {
  preencode(state, m) {
    c.uint.preencode(state, m.dataPointer)
    c.uint.preencode(state, m.length)
  },
  encode(state, m) {
    c.uint.encode(state, m.dataPointer)
    c.uint.encode(state, m.length)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const r1 = c.uint.decode(state)

    return {
      dataPointer: r0,
      length: r1
    }
  }
}

function setVersion(v) {
  version = v
}

function encode(name, value, v = VERSION) {
  version = v
  return c.encode(getEncoding(name), value)
}

function decode(name, buffer, v = VERSION) {
  version = v
  return c.decode(getEncoding(name), buffer)
}

function getEnum(name) {
  switch (name) {
    case '@core/hashes':
      return encoding6_enum
    case '@core/signatures':
      return encoding7_enum
    default:
      throw new Error('Enum not found ' + name)
  }
}

function getEncoding(name) {
  switch (name) {
    case '@corestore/allocated':
      return encoding0
    case '@corestore/head-v1':
      return encoding1
    case '@corestore/head-v2':
      return encoding2
    case '@corestore/head':
      return encoding3
    case '@corestore/alias':
      return encoding4
    case '@corestore/core':
      return encoding5
    case '@core/hashes':
      return encoding6
    case '@core/signatures':
      return encoding7
    case '@core/tree-node':
      return encoding8
    case '@core/signer':
      return encoding9
    case '@core/prologue':
      return encoding10
    case '@core/manifest':
      return encoding11
    case '@core/keyPair':
      return encoding12
    case '@core/group':
      return encoding13
    case '@core/auth':
      return encoding14
    case '@core/head':
      return encoding15
    case '@core/hints':
      return encoding16
    case '@core/session':
      return encoding17
    case '@core/sessions':
      return encoding18
    case '@core/dependency':
      return encoding19
    default:
      throw new Error('Encoder not found ' + name)
  }
}

function getStruct(name, v = VERSION) {
  const enc = getEncoding(name)
  return {
    preencode(state, m) {
      version = v
      enc.preencode(state, m)
    },
    encode(state, m) {
      version = v
      enc.encode(state, m)
    },
    decode(state) {
      version = v
      return enc.decode(state)
    }
  }
}

const resolveStruct = getStruct // compat

module.exports = {
  resolveStruct,
  getStruct,
  getEnum,
  getEncoding,
  encode,
  decode,
  setVersion,
  version
}
const RocksDB = require('rocksdb-native')
const rrp = require('resolve-reject-promise')
const ScopeLock = require('scope-lock')
const DeviceFile = require('device-file')
const path = require('path')
const fs = require('fs')
const Xache = require('xache')

const View = require('./lib/view.js')

const VERSION = 2
const COLUMN_FAMILY = 'corestore'

const { store, core } = require('./lib/keys.js')

const { CorestoreRX, CorestoreTX, CoreTX, CoreRX } = require('./lib/tx.js')

const {
  createCoreStream,
  createAliasStream,
  createDiscoveryKeyStream,
  createBlockStream,
  createBitfieldStream,
  createUserDataStream,
  createTreeNodeStream,
  createMarkStream,
  createLocalStream,
  createGroupUpdateStream
} = require('./lib/streams.js')

const EMPTY = new View()

class Atom {
  constructor(db) {
    this.db = db
    this.view = new View()
    this.flushedPromise = null
    this.flushing = false
    this.preflushes = []
    this.flushes = []
  }

  preflush(fn) {
    this.preflushes.push(fn)
  }

  onflush(fn) {
    this.flushes.push(fn)
  }

  flushed() {
    if (!this.flushing) return Promise.resolve()
    if (this.flushedPromise !== null) return this.flushedPromise.promise
    this.flushedPromise = rrp()
    return this.flushedPromise.promise
  }

  _resolve() {
    const f = this.flushedPromise
    this.flushedPromise = null
    f.resolve()
  }

  async flush() {
    if (this.flushing) throw new Error('Atom already flushing')
    this.flushing = true

    try {
      const plen = this.preflushes.length
      for (let i = 0; i < plen; i++) this.preflushes[i]()

      await View.flush(this.view.changes, this.db)

      const promises = []
      const len = this.flushes.length // in case of reentry
      for (let i = 0; i < len; i++) promises.push(this.flushes[i]())

      await Promise.all(promises)
    } finally {
      this.view.reset()
      this.flushing = false
      if (this.flushedPromise !== null) this._resolve()
    }
  }
}

class HypercoreStorage {
  constructor(store, db, treeCache, core, view, atom) {
    this.store = store
    this.db = db
    this.core = core
    this.view = view
    this.atom = atom

    this.view.readStart()
    this.treeCache = treeCache
  }

  get readOnly() {
    return this.store.readOnly
  }

  get dependencies() {
    return this.core.dependencies
  }

  getDependencyLength() {
    return this.core.dependencies.length
      ? this.core.dependencies[this.core.dependencies.length - 1].length
      : -1
  }

  getDependency(length) {
    for (let i = this.core.dependencies.length - 1; i >= 0; i--) {
      const dep = this.core.dependencies[i]
      if (dep.length < length) return dep
    }

    return null
  }

  setDependencyHead(dep) {
    if (dep === null) {
      this.core.dependencies = []
      return
    }

    const deps = this.core.dependencies

    for (let i = deps.length - 1; i >= 0; i--) {
      const d = deps[i]

      if (d.dataPointer !== dep.dataPointer) continue

      // check if nothing changed
      if (d.length === dep.length && i === deps.length - 1) return

      this.core = {
        corePointer: this.core.corePointer,
        dataPointer: this.core.dataPointer,
        dependencies: deps.slice(0, i + 1)
      }

      this.core.dependencies[i] = {
        dataPointer: dep.dataPointer,
        length: dep.length
      }
      return // updated head so done
    }

    this.core.dependencies = [
      {
        dataPointer: dep.dataPointer,
        length: dep.length
      }
    ]
  }

  // TODO: this might have to be async if the dependents have changed, but prop ok for now
  updateDependencyLength(length, truncated) {
    const deps = this.core.dependencies

    const i = this.findDependencyIndex(length, truncated)
    if (i === -1) throw new Error('Dependency not found')

    this.core = {
      corePointer: this.core.corePointer,
      dataPointer: this.core.dataPointer,
      dependencies: deps.slice(0, i + 1)
    }

    if (this.core.dependencies[i].length !== length) {
      this.core.dependencies[i] = {
        dataPointer: deps[i].dataPointer,
        length
      }
    }
  }

  findDependencyIndex(length, truncated) {
    const deps = this.core.dependencies

    if (truncated) {
      for (let i = 0; i < deps.length; i++) {
        if (deps[i].length >= length) return i
      }

      return -1
    }

    for (let i = deps.length - 1; i >= 0; i--) {
      if (deps[i].length <= length) return i
    }

    return -1
  }

  get snapshotted() {
    return this.db._snapshot !== null
  }

  snapshot() {
    return new HypercoreStorage(
      this.store,
      this.db.snapshot(),
      this.treeCache,
      this.core,
      this.view.snapshot(),
      this.atom
    )
  }

  compact() {
    return Promise.all([
      this.db.compactRange(core.core(this.core.corePointer), core.core(this.core.corePointer)),
      this.db.compactRange(core.data(this.core.dataPointer), core.data(this.core.dataPointer))
    ])
  }

  atomize(atom) {
    if (this.atom && this.atom !== atom) {
      throw new Error('Cannot atomize and atomized session with a new atom')
    }

    return new HypercoreStorage(
      this.store,
      this.db.session(),
      this.treeCache,
      this.core,
      atom.view,
      atom
    )
  }

  createAtom() {
    return this.store.createAtom()
  }

  createBlockStream(opts) {
    return createBlockStream(this.core, this.db, this.view, opts)
  }

  createTreeNodeStream(opts) {
    return createTreeNodeStream(this.core, this.db, this.view, opts)
  }

  createBitfieldStream(opts) {
    return createBitfieldStream(this.core, this.db, this.view, opts)
  }

  createUserDataStream(opts) {
    return createUserDataStream(this.core, this.db, this.view, opts)
  }

  createMarkStream(opts) {
    return createMarkStream(this.core, this.db, this.view, opts)
  }

  createLocalStream(opts) {
    return createLocalStream(this.core, this.db, this.view, opts)
  }

  async resumeSession(name) {
    const rx = this.read()
    const existingSessionsPromise = rx.getSessions()

    rx.tryFlush()
    const existingSessions = await existingSessionsPromise

    const sessions = existingSessions || []
    const session = getSession(sessions, name, false)

    if (session === null) return null

    const core = {
      corePointer: this.core.corePointer,
      dataPointer: session.dataPointer,
      dependencies: []
    }

    const coreRx = new CoreRX(core, this.db, this.view, this.treeCache, this.store.stats, -1)

    const dependencyPromise = coreRx.getDependency()
    coreRx.tryFlush()

    const dependency = await dependencyPromise
    if (dependency) core.dependencies = this._addDependency(dependency)

    return new HypercoreStorage(
      this.store,
      this.db.session(),
      this.treeCache,
      core,
      this.atom ? this.view : new View(),
      this.atom
    )
  }

  async createSession(name, head) {
    const rx = this.read()

    const existingSessionsPromise = rx.getSessions()
    const existingHeadPromise = rx.getHead()

    rx.tryFlush()

    const [existingSessions, existingHead] = await Promise.all([
      existingSessionsPromise,
      existingHeadPromise
    ])
    if (head === null) head = existingHead

    if (existingHead !== null && head.length > existingHead.length) {
      throw new Error('Invalid head passed, ahead of core')
    }

    const sessions = existingSessions || []
    const session = getSession(sessions, name, true)
    const fresh = session.dataPointer === -1

    if (fresh) {
      session.dataPointer = await this.store._allocData()
    }

    const tx = this.write()

    tx.setSessions(sessions)

    const length = head === null ? 0 : head.length
    const core = {
      corePointer: this.core.corePointer,
      dataPointer: session.dataPointer,
      dependencies: this._addDependency({
        dataPointer: this.core.dataPointer,
        length
      })
    }

    const coreTx = new CoreTX(core, this.db, tx.view, tx.changes)

    if (length > 0) coreTx.setHead(head)
    coreTx.setDependency(core.dependencies[core.dependencies.length - 1])

    if (!fresh) {
      // nuke all existing state...
      coreTx.deleteBlockRange(0, -1)
      coreTx.deleteTreeNodeRange(0, -1)
      coreTx.deleteBitfieldPageRange(0, -1)
    }

    await tx.flush()

    return new HypercoreStorage(
      this.store,
      this.db.session(),
      this.treeCache,
      core,
      this.atom ? this.view : new View(),
      this.atom
    )
  }

  async createAtomicSession(atom, head) {
    const length = head === null ? 0 : head.length
    const core = {
      corePointer: this.core.corePointer,
      dataPointer: this.core.dataPointer,
      dependencies: this._addDependency(null)
    }

    const coreTx = new CoreTX(core, this.db, atom.view, [])

    if (length > 0) coreTx.setHead(head)

    await coreTx.flush()

    return this.atomize(atom)
  }

  _addDependency(dep) {
    const deps = []

    for (let i = 0; i < this.core.dependencies.length; i++) {
      const d = this.core.dependencies[i]

      if (dep !== null && d.length > dep.length) {
        if (d.dataPointer !== dep.dataPointer) {
          deps.push({ dataPointer: d.dataPointer, length: dep.length })
        }
        return deps
      }

      deps.push(d)
    }

    if (
      dep !== null &&
      (deps.length === 0 || deps[deps.length - 1].dataPointer !== dep.dataPointer)
    ) {
      deps.push(dep)
    }
    return deps
  }

  async deleteSessions() {
    const rx = this.read()
    const existingSessionsPromise = rx.getSessions()
    rx.tryFlush()

    const existingSessions = await existingSessionsPromise

    // Remove batches
    const coreTx = this.write()
    coreTx.setSessions([]) // Clear sessions record
    await coreTx.flush()

    const tx = this.db.write({ autoDestroy: true })

    for (const { dataPointer } of existingSessions) {
      const start = core.data(dataPointer)
      const end = core.data(dataPointer + 1)
      tx.tryDeleteRange(start, end)
    }

    await tx.flush()
  }

  read(fork = -1) {
    let treeCache = null
    if (!this.atom) treeCache = this.treeCache

    return new CoreRX(this.core, this.db, this.view, treeCache, this.store.stats, fork)
  }

  write() {
    return new CoreTX(this.core, this.db, this.atom ? this.view : null, [])
  }

  close() {
    if (this.view !== null) {
      this.view.readStop()
      this.view = null
    }

    return this.db.close()
  }

  static async export(ptr, db, { batches = false } = {}) {
    const rx = new CoreRX(ptr, db, EMPTY, null, null, -1)

    const core = {
      head: null,
      auth: null,
      sessions: [],
      data: null
    }

    const sessionsPromise = rx.getSessions()
    const headPromise = rx.getHead()
    const authPromise = rx.getAuth()

    rx.tryFlush()

    const [sessions, head, auth] = await Promise.all([sessionsPromise, headPromise, authPromise])

    core.head = head
    core.auth = { ...auth, keyPair: null }
    if (sessions) core.sessions = sessions.map((s) => s.name)

    const data = []

    data.push(exportData(ptr, db))

    if (batches) {
      for (const { dataPointer } of sessions) {
        data.push(exportData({ dataPointer, dependencies: [] }, db))
      }
    }

    core.data = await Promise.all(data)

    return core
  }

  static isParentStorage(storage, parent) {
    const last = getLastDependency(storage)
    return !!last && last.dataPointer === parent.core.dataPointer
  }
}

class CorestoreStorage {
  constructor(db, opts = {}) {
    const storage = typeof db === 'string' ? db : null

    this.bootstrap = storage !== null
    this.path = storage !== null ? storage : path.join(db.path, '..')
    this.alwaysRecover = !!opts.alwaysRecover
    this.readOnly = !!opts.readOnly
    this.allowBackup = !!opts.allowBackup
    this.deviceFile = null
    this.wait = !!opts.wait

    // tmp sync fix for simplicty since not super deployed yet
    if (this.bootstrap && !this.readOnly) tmpFixStorage(this.path)

    this.id = opts.id || null
    this.view = null
    this.enters = 0
    this.lock = new ScopeLock()
    this.flushing = null
    this.version = 0
    this.migrating = null

    if ((this.bootstrap && !this.readOnly && !this.allowBackup) || this.wait) {
      const corestoreFile = path.join(this.path, 'CORESTORE')

      this.deviceFile = new DeviceFile(corestoreFile, {
        lock: true,
        wait: this.wait,
        data: { id: this.id }
      })
    }

    const dbPath = path.join(this.path, 'db')

    this.stats = {
      treeCache: {
        hits: 0,
        misses: 0,
        parallel: 0,
        skips: 0
      }
    }
    this.rocks = storage === null ? db : new RocksDB(dbPath, { ...opts, lock: this.deviceFile })
    this.db = createColumnFamily(this.rocks, opts)

    const { treeCache = { maxSize: 8192 } } = opts
    this.treeCache = new Xache(treeCache)
  }

  get opened() {
    return this.db.opened
  }

  get closed() {
    return this.db.closed
  }

  async ready() {
    if (this.version === 0) await this._migrateStore()
    return this.db.ready()
  }

  compact(opts) {
    return this.db.compactRange(opts)
  }

  async audit() {
    for await (const { core } of this.createCoreStream()) {
      const coreRx = new CoreRX(core, this.db, EMPTY, this.treeCache, this.stats, -1)
      const authPromise = coreRx.getAuth()

      coreRx.tryFlush()

      const auth = await authPromise

      if (!auth.manifest || auth.manifest.version > 0) continue
      if (auth.manifest.linked === null) continue

      auth.manifest.linked = null
      const coreTx = new CoreTX(core, this.db, null, [])
      coreTx.setAuth(auth)
      await coreTx.flush()
    }
  }

  async deleteCore(ptr) {
    const rx = new CoreRX(ptr, this.db, EMPTY, this.treeCache, this.stats, -1)

    const authPromise = rx.getAuth()
    const sessionsPromise = rx.getSessions()

    rx.tryFlush()

    const auth = await authPromise
    const sessions = await sessionsPromise

    // no core stored here
    if (!auth) return

    const tx = this.db.write({ autoDestroy: true })

    tx.tryDelete(store.core(auth.discoveryKey))

    // clear core
    const start = core.core(ptr.corePointer)
    const end = core.core(ptr.corePointer + 1)
    tx.tryDeleteRange(start, end)

    if (sessions) {
      for (const { dataPointer } of sessions) {
        const start = core.data(dataPointer)
        const end = core.data(dataPointer + 1)
        tx.tryDeleteRange(start, end)
      }
    }

    return tx.flush()
  }

  static isCoreStorage(db) {
    return isCorestoreStorage(db)
  }

  static from(db) {
    if (isCorestoreStorage(db)) return db
    return new this(db)
  }

  async _flush() {
    while (this.enters > 0) {
      await this.lock.lock()
      await this.lock.unlock()
    }
  }

  async _maybeRecover(view) {
    const r = path.join(this.db.path, 'RECOVERING')
    if (!(await fileExists(r))) return
    await this.setRecovering(view)
    await fs.promises.unlink(r)
  }

  _maybeRecoverLater(err) {
    if (!shouldRecover(err) && !this.alwaysRecover) return
    fs.writeFileSync(path.join(this.db.path, 'RECOVERING'), '')
    for (const file of fs.readdirSync(this.db.path)) {
      if (file.endsWith('.log')) fs.unlinkSync(path.join(this.db.path, file))
    }
  }

  // runs pre any other mutation and read
  async _migrateStore() {
    const view = await this._enter()

    try {
      if (this.version === VERSION) return

      await this._preopen

      try {
        await this.db.ready()
      } catch (err) {
        this._maybeRecoverLater(err)
        throw err
      }

      await this._maybeRecover(view)

      const rx = new CorestoreRX(this.db, view)
      const headPromise = rx.getHead()

      rx.tryFlush()
      const head = await headPromise

      const version = head === null ? 0 : head.version
      if (version === VERSION) {
        this.version = VERSION
        return
      }

      const target = { version: VERSION, dryRun: false }

      switch (version) {
        case 0: {
          await require('./migrations/0').store(this, target)
          break
        }
        case 1: {
          // implicit migration on write
          break
        }
        default: {
          throw new Error(
            'Unsupported version: ' + version + ' - you should probably upgrade your dependencies'
          )
        }
      }

      this.version = VERSION
    } finally {
      await this._exit()
    }
  }

  // runs pre the core is returned to the user
  async _migrateCore(core, discoveryKey, version, locked) {
    const view = locked ? this.view : await this._enter()
    try {
      if (version === VERSION) return

      const target = { version: VERSION, dryRun: false }

      switch (version) {
        case 0: {
          await require('./migrations/0').core(core, target)
          break
        }
        case 1: {
          await require('./migrations/1').core(core, target)
          break
        }
        default: {
          throw new Error(
            'Unsupported version: ' + version + ' - you should probably upgrade your dependencies'
          )
        }
      }

      if (locked === false) return

      // if its locked, then move the core state into the memview
      // in case the core is reopened from the memview, pre flush

      const rx = new CorestoreRX(this.db, EMPTY)
      const tx = new CorestoreTX(view)

      const corePromise = rx.getCore(discoveryKey)
      rx.tryFlush()

      tx.putCore(discoveryKey, await corePromise)
      tx.apply()
    } finally {
      if (!locked) await this._exit()
    }
  }

  async _enter() {
    this.enters++
    await this.lock.lock()
    if (this.view === null) this.view = new View()
    return this.view
  }

  async _exit() {
    this.enters--

    if (this.flushing === null) this.flushing = rrp()
    const flushed = this.flushing.promise

    if (this.enters === 0 || this.view.size() > 128) {
      try {
        await View.flush(this.view.changes, this.db)
        this.flushing.resolve()
      } catch (err) {
        this.flushing.reject(err)
      } finally {
        this.flushing = null
        this.view = null
      }
    }

    this.lock.unlock()
    return flushed
  }

  // when used with core catches this isnt transactional for simplicity, HOWEVER, its just a number
  // so worth the tradeoff
  async _allocData() {
    let dataPointer = 0

    const view = await this._enter()
    const tx = new CorestoreTX(view)

    try {
      const head = await this._getHead(view)

      dataPointer = head.datas++

      tx.setHead(head)
      tx.apply()
    } finally {
      await this._exit()
    }

    return dataPointer
  }

  // exposes here so migrations can easily access the head in an init state
  async _getHead(view) {
    const rx = new CorestoreRX(this.db, view)
    const headPromise = rx.getHead()
    rx.tryFlush()

    const head = await headPromise
    return head === null ? initStoreHead() : head
  }

  createAtom() {
    return new Atom(this.db)
  }

  async flush() {
    await this.rocks.flush()
  }

  async close() {
    if (this.db.closed) return
    await this._flush()
    await this.db.close()
    await this.rocks.close()
    this.treeCache.destroy()
    if (this.deviceFile) await this.deviceFile.close()
  }

  async clear() {
    if (this.version === 0) await this._migrateStore()

    const view = await this._enter()
    const tx = new CorestoreTX(view)

    tx.clear()
    tx.apply()

    await this._exit()
  }

  createCoreStream() {
    // TODO: be nice to run the mgiration here also, but too much plumbing atm
    return createCoreStream(this.db, EMPTY)
  }

  createAliasStream(namespace) {
    // TODO: be nice to run the mgiration here also, but too much plumbing atm
    return createAliasStream(this.db, EMPTY, namespace)
  }

  createDiscoveryKeyStream(namespace) {
    return createDiscoveryKeyStream(this.db, EMPTY, namespace)
  }

  createGroupUpdateStream(group, { since, reverse } = {}) {
    return createGroupUpdateStream(this.db, EMPTY, group, { gte: since, reverse })
  }

  async getAlias(alias) {
    if (this.version === 0) await this._migrateStore()

    const rx = new CorestoreRX(this.db, EMPTY)
    const discoveryKeyPromise = rx.getCoreByAlias(alias)
    rx.tryFlush()
    return discoveryKeyPromise
  }

  async getSeed() {
    if (this.version === 0) await this._migrateStore()

    const rx = new CorestoreRX(this.db, EMPTY)
    const headPromise = rx.getHead()

    rx.tryFlush()

    const head = await headPromise
    return head === null ? null : head.seed
  }

  async getGroup(topic) {
    if (this.version === 0) await this._migrateStore()

    const rx = new CorestoreRX(this.db, EMPTY)
    const groupPromise = rx.getGroup(topic)
    rx.tryFlush()
    return groupPromise
  }

  async setSeed(seed, { overwrite = true } = {}) {
    if (this.version === 0) await this._migrateStore()

    const view = await this._enter()
    const tx = new CorestoreTX(view)

    try {
      const rx = new CorestoreRX(this.db, view)
      const headPromise = rx.getHead()

      rx.tryFlush()

      const head = (await headPromise) || initStoreHead()

      if (head.seed === null || overwrite) head.seed = seed
      tx.setHead(head)
      tx.apply()

      return head.seed
    } finally {
      await this._exit()
    }
  }

  async setRecovering(view = null) {
    const recovering = Date.now()
    let keys = []

    for await (const data of this.createDiscoveryKeyStream()) {
      keys.push(data)
      if (keys.length > 16 * 1024) {
        await this._flushRecovering(recovering, view, keys)
        keys = []
      }
    }

    if (keys.length) await this._flushRecovering(recovering, view, keys)
  }

  async _flushRecovering(recovering, view, keys) {
    const own = !view
    if (own) view = await this._enter()
    const tx = new CorestoreTX(view)

    try {
      const infos = await this._getInfos(keys, { auth: false, head: false, hints: true })
      for (const inf of infos) {
        tx.setCoreHints(inf.core, { ...inf.hints, recovering })
      }
      tx.apply()
    } finally {
      if (own) await this._exit()
    }
  }

  async getDefaultDiscoveryKey() {
    if (this.version === 0) await this._migrateStore()

    const rx = new CorestoreRX(this.db, EMPTY)
    const headPromise = rx.getHead()

    rx.tryFlush()

    const head = await headPromise
    return head === null ? null : head.defaultDiscoveryKey
  }

  async setDefaultDiscoveryKey(discoveryKey, { overwrite = true } = {}) {
    if (this.version === 0) await this._migrateStore()

    const view = await this._enter()
    const tx = new CorestoreTX(view)

    try {
      const rx = new CorestoreRX(this.db, view)
      const headPromise = rx.getHead()

      rx.tryFlush()

      const head = (await headPromise) || initStoreHead()

      if (head.defaultDiscoveryKey === null || overwrite) head.defaultDiscoveryKey = discoveryKey
      tx.setHead(head)
      tx.apply()

      return head.defaultDiscoveryKey
    } finally {
      await this._exit()
    }
  }

  async hasCore(discoveryKey, { ifMigrated = false } = {}) {
    if (this.version === 0) await this._migrateStore()

    const rx = new CorestoreRX(this.db, EMPTY)
    const promise = rx.getCore(discoveryKey)

    rx.tryFlush()

    const core = await promise

    if (core === null) return false
    if (core.version === 0 && ifMigrated) return false

    return true
  }

  async getAuth(discoveryKey) {
    if (this.version === 0) await this._migrateStore()

    const rx = new CorestoreRX(this.db, EMPTY)
    const corePromise = rx.getCore(discoveryKey)

    rx.tryFlush()

    const core = await corePromise
    if (core === null) return null

    const read = this.db.read({ autoDestroy: true })
    const authPromise = CoreRX.getAuth(read, core)

    read.tryFlush()

    return authPromise
  }

  async getInfo(discoveryKey, opts) {
    return (await this.getInfos([discoveryKey], opts))[0]
  }

  async getInfos(discoveryKeys, opts) {
    if (this.version === 0) await this._migrateStore()
    return this._getInfos(discoveryKeys, opts)
  }

  async _getInfos(discoveryKeys, { auth = true, head = true, hints = true } = {}) {
    const rx = new CorestoreRX(this.db, EMPTY)
    const corePromises = new Array(discoveryKeys.length)

    for (let i = 0; i < discoveryKeys.length; i++) {
      corePromises[i] = rx.getCore(discoveryKeys[i])
    }

    rx.tryFlush()

    const cores = await Promise.all(corePromises)
    const read = this.db.read({ autoDestroy: true })

    const resultPromises = new Array(cores.length)

    for (let i = 0; i < cores.length; i++) {
      resultPromises[i] = cores[i]
        ? getInfoFromBatch(read, cores[i], discoveryKeys[i], auth, head, hints)
        : null
    }

    read.tryFlush()

    return Promise.all(resultPromises)
  }

  async suspend({ log = noop } = {}) {
    await log('Suspending hypercore storage...')
    await this.db.suspend()
    await log('db suspended')
    if (this.deviceFile) {
      await log('suspend deviceFile')
      await this.deviceFile.suspend()
      await log('deviceFile suspended')
    }
  }

  async resume() {
    if (this.deviceFile) await this.deviceFile.resume()
    await this.db.resume()
  }

  async resumeCore(discoveryKey) {
    if (this.version === 0) await this._migrateStore()

    if (!discoveryKey) {
      discoveryKey = await this.getDefaultDiscoveryKey()
      if (!discoveryKey) return null
    }

    const rx = new CorestoreRX(this.db, EMPTY)
    const corePromise = rx.getCore(discoveryKey)

    rx.tryFlush()
    const core = await corePromise

    if (core === null) return null
    return this._resumeFromPointers(EMPTY, discoveryKey, false, core)
  }

  async export(discoveryKey, opts) {
    const rx = new CorestoreRX(this.db, EMPTY)
    const corePromise = rx.getCore(discoveryKey)

    rx.tryFlush()
    const core = await corePromise
    if (core === null) return null

    let { dataPointer, corePointer } = core

    const ptr = { corePointer, dataPointer, dependencies: [] }

    while (true) {
      const rx = new CoreRX(
        { dataPointer, corePointer: 0, dependencies: [] },
        this.db,
        EMPTY,
        this.treeCache,
        this.stats,
        -1
      )
      const dependencyPromise = rx.getDependency()
      rx.tryFlush()
      const dependency = await dependencyPromise
      if (!dependency) break
      ptr.dependencies.push(dependency)
      dataPointer = dependency.dataPointer
    }

    const session = this.db.session()
    try {
      return await HypercoreStorage.export(ptr, session, opts)
    } finally {
      await session.close()
    }
  }

  async _resumeFromPointers(view, discoveryKey, create, { version, corePointer, dataPointer }) {
    const core = { corePointer, dataPointer, dependencies: [] }

    while (true) {
      const rx = new CoreRX(
        { dataPointer, corePointer: 0, dependencies: [] },
        this.db,
        view,
        this.treeCache,
        this.stats,
        -1
      )
      const dependencyPromise = rx.getDependency()
      rx.tryFlush()
      const dependency = await dependencyPromise
      if (!dependency) break
      core.dependencies.push(dependency)
      dataPointer = dependency.dataPointer
    }

    const result = new HypercoreStorage(this, this.db.session(), this.treeCache, core, EMPTY, null)

    if (version < VERSION) await this._migrateCore(result, discoveryKey, version, create)
    return result
  }

  // not allowed to throw validation errors as its a shared tx!
  async _create(
    view,
    { key, manifest, keyPair, encryptionKey, discoveryKey, alias, userData, core: ptrs }
  ) {
    const rx = new CorestoreRX(this.db, view)
    const tx = new CorestoreTX(view)

    const corePromise = rx.getCore(discoveryKey)
    const headPromise = rx.getHead()

    rx.tryFlush()

    let [core, head] = await Promise.all([corePromise, headPromise])
    if (core) return this._resumeFromPointers(view, discoveryKey, true, core)

    if (head === null) head = initStoreHead()
    if (head.defaultDiscoveryKey === null) head.defaultDiscoveryKey = discoveryKey

    const corePointer = ptrs ? ptrs.corePointer : head.cores++
    const dataPointer = ptrs ? ptrs.dataPointer : head.datas++

    core = { version: VERSION, corePointer, dataPointer, alias }

    tx.setHead(head)
    tx.putCore(discoveryKey, core)
    if (alias) tx.putCoreByAlias(alias, discoveryKey)

    const ptr = { corePointer, dataPointer, dependencies: [] }
    const ctx = new CoreTX(ptr, this.db, view, tx.changes)

    ctx.setAuth({
      key,
      discoveryKey,
      manifest,
      keyPair,
      encryptionKey
    })

    if (userData) {
      for (const { key, value } of userData) {
        ctx.putUserData(key, value)
      }
    }

    tx.apply()

    return new HypercoreStorage(this, this.db.session(), this.treeCache, ptr, EMPTY, null)
  }

  async createCore(data) {
    if (this.version === 0) await this._migrateStore()

    const view = await this._enter()

    try {
      return await this._create(view, data)
    } finally {
      await this._exit()
    }
  }

  // not allowed to throw validation errors as its a shared tx!
  async _createGroup(view, topic) {
    const rx = new CorestoreRX(this.db, view)
    const tx = new CorestoreTX(view)

    const groupPromise = rx.getGroup(topic)
    const headPromise = rx.getHead()

    rx.tryFlush()

    let group = await groupPromise
    if (group !== null) {
      return {
        key: topic,
        pointer: group
      }
    }

    let head = await headPromise
    if (head === null) head = initStoreHead()

    group = head.groups++

    tx.putGroup(topic, group)
    tx.setHead(head)
    tx.apply()

    return {
      key: topic,
      pointer: group
    }
  }

  async createGroup(topic) {
    if (this.version === 0) await this._migrateStore()

    const view = await this._enter()

    try {
      return await this._createGroup(view, topic)
    } finally {
      await this._exit()
    }
  }

  static isParentStorage(storage, parent) {
    return HypercoreStorage.isParentStorage(storage, parent)
  }
}

module.exports = CorestoreStorage

function initStoreHead() {
  return {
    version: 0, // cause we wanna run the migration
    datas: 0,
    cores: 0,
    groups: 0,
    seed: null,
    defaultDiscoveryKey: null
  }
}

function getSession(sessions, name, alloc) {
  for (let i = 0; i < sessions.length; i++) {
    if (sessions[i].name === name) return sessions[i]
  }

  if (!alloc) return null

  const result = { name, dataPointer: -1 }
  sessions.push(result)
  return result
}

function isCorestoreStorage(s) {
  return typeof s === 'object' && !!s && typeof s.setDefaultDiscoveryKey === 'function'
}

function createColumnFamily(db, opts = {}) {
  const {
    tableCacheIndexAndFilterBlocks = true,
    blockCache = true,
    optimizeFiltersForMemory = false,
    blobFileSize = 256 * 1024 * 1024,
    blobGarbageCollectionAgeCutOff = 0.25,
    blobGarbageCollectionForceThreshold = 1.0
  } = opts

  const col = new RocksDB.ColumnFamily(COLUMN_FAMILY, {
    enableBlobFiles: true,
    minBlobSize: 4096,
    blobFileSize,
    enableBlobGarbageCollection: true,
    tableBlockSize: 8192,
    tableCacheIndexAndFilterBlocks,
    tableFormatVersion: 6,
    optimizeFiltersForMemory,
    blockCache,
    blobGarbageCollectionAgeCutOff,
    blobGarbageCollectionForceThreshold
  })

  return db.columnFamily(col)
}

function getLastDependency(storage) {
  return storage.dependencies.length ? storage.dependencies[storage.dependencies.length - 1] : null
}

// TODO: remove in like 3-6 mo
function tmpFixStorage(p) {
  // if CORESTORE file is written, new format
  if (fs.existsSync(path.join(p, 'CORESTORE'))) return

  let files = []

  try {
    files = fs.readdirSync(p)
  } catch {}

  const notRocks = new Set([
    'CORESTORE',
    'primary-key',
    'cores',
    'app-preferences',
    'cache',
    'preferences.json',
    'db',
    'clone',
    'core',
    'notifications'
  ])

  for (const f of files) {
    if (notRocks.has(f)) continue

    try {
      fs.mkdirSync(path.join(p, 'db'))
    } catch {}

    fs.renameSync(path.join(p, f), path.join(p, 'db', f))
  }
}

async function exportData(ptr, db, opts) {
  // just need dataPointer
  const reads = [
    toArray(createBlockStream(ptr, db, EMPTY, opts)),
    toArray(createTreeNodeStream(ptr, db, EMPTY, opts)),
    toArray(createBitfieldStream(ptr, db, EMPTY, opts))
  ]

  const [blocks, tree, bitfield] = await Promise.all(reads)

  return {
    blocks,
    tree,
    bitfield
  }
}

async function toArray(stream) {
  const all = []
  for await (const e of stream) all.push(e)
  return all
}

async function fileExists(path) {
  try {
    await fs.promises.stat(path)
    return true
  } catch {
    return false
  }
}

function shouldRecover(err) {
  return err.message.toLowerCase().indexOf('sequence number is being set backwards') > -1
}

function noop() {}

async function getInfoFromBatch(db, c, discoveryKey, getAuth, getHead, getHints) {
  const authPromise = getAuth ? CoreRX.getAuth(db, c) : null
  const headPromise = getHead ? CoreRX.getHead(db, c) : null
  const hintsPromise = getHints ? CoreRX.getHints(db, c) : null

  // ensure no uncaughts
  if (authPromise) authPromise.catch(noop)
  if (headPromise) headPromise.catch(noop)
  if (hintsPromise) hintsPromise.catch(noop)

  return {
    discoveryKey,
    core: c,
    auth: await authPromise,
    head: await headPromise,
    hints: await hintsPromise
  }
}
const { Readable, getStreamError } = require('streamx')
const { core } = require('./keys')

module.exports = class BlockStream extends Readable {
  constructor(core, db, updates, start, end, reverse) {
    super()

    this.core = core
    this.db = db
    this.updates = updates
    this.start = start
    this.end = end
    this.reverse = reverse === true

    this._drained = true
    this._consumed = 0
    this._stream = null
    this._oncloseBound = this._onclose.bind(this)
    this._maybeDrainBound = this._maybeDrain.bind(this)

    this._update()
  }

  _update() {
    if (this._consumed > this.core.dependencies.length) return

    const deps = this.core.dependencies
    const index = this._findDependencyIndex(deps)

    const curr = index < deps.length ? deps[index] : null
    const prev = index > 0 && index - 1 < deps.length ? deps[index - 1] : null

    const start = prev && prev.length > this.start ? prev.length : this.start
    const end = curr && (this.end === -1 || curr.length < this.end) ? curr.length : this.end

    const ptr = curr ? curr.dataPointer : this.core.dataPointer

    this._makeStream(core.block(ptr, start), core.block(ptr, end))
  }

  _findDependencyIndex(deps) {
    if (!this.reverse) return this._consumed++

    let i = deps.length - this._consumed++
    while (i > 0) {
      if (deps[i - 1].length <= this.end) return i
      i--
      this._consumed++
    }

    return 0
  }

  _predestroy() {
    if (this._stream !== null) this._stream.destroy()
  }

  _read(cb) {
    this._drained = this._onreadable()
    cb(null)
  }

  _maybeDrain() {
    if (this._drained === true) return
    this._drained = this._onreadable()
  }

  _onreadable() {
    if (this._stream === null) {
      this.push(null)
      return true
    }

    let data = this._stream.read()

    if (data === null) return false

    do {
      this.push(data)
      data = this._stream.read()
    } while (data !== null)

    return true
  }

  _onclose() {
    if (this.destroying) return

    const err = getStreamError(this._stream)

    if (err !== null) {
      this.destroy(err)
      return
    }

    // empty the current stream
    if (this._onreadable() === true) this._drained = true

    this._stream = null

    this._update()
    this._maybeDrain()
  }

  _makeStream(start, end) {
    this._stream = this.updates.iterator(this.db, start, end, this.reverse)
    this._stream.on('readable', this._maybeDrainBound)
    this._stream.on('error', noop)
    this._stream.on('close', this._oncloseBound)
  }
}

function noop() {}
const { Readable } = require('streamx')

// used for returned a stream that just errors (during read during teardown)

module.exports = class CloseErrorStream extends Readable {
  constructor(err) {
    super()
    this.error = err
  }

  _open(cb) {
    cb(this.error)
  }
}
const { UINT, STRING } = require('index-encoder')
const c = require('compact-encoding')
const b4a = require('b4a')

const TL_HEAD = 0
const TL_CORE_BY_DKEY = 1
const TL_CORE_BY_ALIAS = 2
const TL_CORE = 3
const TL_DATA = 4
const TL_GROUP_BY_TOPIC = 5
const TL_GROUP = 6

const TL_END = TL_GROUP + 1

const CORE_AUTH = 0
const CORE_SESSIONS = 1
const CORE_GROUP = 2

const DATA_HEAD = 0
const DATA_DEPENDENCY = 1
const DATA_HINTS = 2
const DATA_BLOCK = 3
const DATA_TREE = 4
const DATA_BITFIELD = 5
const DATA_USER_DATA = 6
const DATA_LOCAL = 7
const DATA_MARK = 8

const slab = { buffer: b4a.allocUnsafe(65536), start: 0, end: 0 }

const store = {}
const core = {}
const group = {}

store.clear = function () {
  const state = alloc()
  let start = state.start
  UINT.encode(state, 0)
  const a = state.buffer.subarray(start, state.start)
  start = state.start
  UINT.encode(state, TL_END)
  const b = state.buffer.subarray(start, state.start)
  return [a, b]
}

store.head = function () {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_HEAD)
  return state.buffer.subarray(start, state.start)
}

store.core = function (discoveryKey) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE_BY_DKEY)
  c.fixed32.encode(state, discoveryKey)
  return state.buffer.subarray(start, state.start)
}

store.coreStart = function () {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE_BY_DKEY)
  return state.buffer.subarray(start, state.start)
}

store.coreEnd = function () {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE_BY_DKEY + 1)
  return state.buffer.subarray(start, state.start)
}

store.coreByAlias = function ({ namespace, name }) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE_BY_ALIAS)
  c.fixed32.encode(state, namespace)
  STRING.encode(state, name)
  return state.buffer.subarray(start, state.start)
}

store.coreByAliasStart = function (namespace) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE_BY_ALIAS)
  if (namespace) c.fixed32.encode(state, namespace)
  return state.buffer.subarray(start, state.start)
}

store.coreByAliasEnd = function (namespace) {
  const state = alloc()
  const start = state.start

  if (namespace) {
    UINT.encode(state, TL_CORE_BY_ALIAS)
    c.fixed32.encode(state, namespace)
    state.buffer[state.start++] = 0xff
  } else {
    UINT.encode(state, TL_CORE_BY_ALIAS + 1)
  }

  return state.buffer.subarray(start, state.start)
}

store.alias = function (buffer) {
  const state = { buffer, start: 0, end: buffer.byteLength }
  UINT.decode(state) // ns
  const namespace = c.fixed32.decode(state)
  const name = STRING.decode(state)
  return { namespace, name }
}

store.discoveryKey = function (buffer) {
  const state = { buffer, start: 0, end: buffer.byteLength }
  UINT.decode(state) // ns
  return c.fixed32.decode(state)
}

core.core = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE)
  UINT.encode(state, ptr)
  return state.buffer.subarray(start, state.start)
}

core.data = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  return state.buffer.subarray(start, state.start)
}

core.auth = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE)
  UINT.encode(state, ptr)
  UINT.encode(state, CORE_AUTH)
  return state.buffer.subarray(start, state.start)
}

core.group = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE)
  UINT.encode(state, ptr)
  UINT.encode(state, CORE_GROUP)
  return state.buffer.subarray(start, state.start)
}

core.sessions = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE)
  UINT.encode(state, ptr)
  UINT.encode(state, CORE_SESSIONS)
  return state.buffer.subarray(start, state.start)
}

core.head = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_HEAD)
  return state.buffer.subarray(start, state.start)
}

core.dependency = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_DEPENDENCY)
  return state.buffer.subarray(start, state.start)
}

core.hints = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_HINTS)
  return state.buffer.subarray(start, state.start)
}

core.block = function (ptr, index) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_BLOCK)
  UINT.encode(state, index)
  return state.buffer.subarray(start, state.start)
}

core.tree = function (ptr, index) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_TREE)
  UINT.encode(state, index)
  return state.buffer.subarray(start, state.start)
}

core.bitfield = function (ptr, index, type) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_BITFIELD)
  UINT.encode(state, index)
  UINT.encode(state, type)
  return state.buffer.subarray(start, state.start)
}

core.userData = function (ptr, key) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_USER_DATA)
  STRING.encode(state, key)
  return state.buffer.subarray(start, state.start)
}

core.userDataEnd = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_USER_DATA + 1)
  return state.buffer.subarray(start, state.start)
}

core.mark = function (ptr, index) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_MARK)
  UINT.encode(state, index)
  return state.buffer.subarray(start, state.start)
}

core.local = function (ptr, key) {
  if (key.byteLength > 2048) {
    throw new Error('local keys has an upper limit of 2048 bytes atm')
  }

  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_LOCAL)

  state.buffer.set(key, state.start)
  state.start += key.byteLength
  return state.buffer.subarray(start, state.start)
}

core.localEnd = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_LOCAL + 1)
  return state.buffer.subarray(start, state.start)
}

core.blockIndex = function (buffer) {
  const state = { buffer, start: 0, end: buffer.byteLength }
  UINT.decode(state) // ns
  UINT.decode(state) // ptr
  UINT.decode(state) // type
  return UINT.decode(state)
}

core.bitfieldIndexAndType = function (buffer) {
  const state = { buffer, start: 0, end: buffer.byteLength }
  UINT.decode(state) // ns
  UINT.decode(state) // ptr
  UINT.decode(state) // type
  return [UINT.decode(state), UINT.decode(state)]
}

core.userDataKey = function (buffer) {
  const state = { buffer, start: 0, end: buffer.byteLength }
  UINT.decode(state) // ns
  UINT.decode(state) // ptr
  UINT.decode(state) // type
  return STRING.decode(state)
}

core.markKey = function (buffer) {
  const state = { buffer, start: 0, end: buffer.byteLength }
  UINT.decode(state) // ns
  UINT.decode(state) // ptr
  UINT.decode(state) // type
  return UINT.decode(state)
}

core.localKey = function (buffer) {
  const state = { buffer, start: 0, end: buffer.byteLength }
  UINT.decode(state) // ns
  UINT.decode(state) // ptr
  UINT.decode(state) // type
  return state.buffer.subarray(state.start, state.end)
}

group.topic = function (topic) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_GROUP_BY_TOPIC)
  c.fixed32.encode(state, topic)
  return state.buffer.subarray(start, state.start)
}

group.entry = function (group, timestamp, ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_GROUP)
  UINT.encode(state, group)
  c.uint64be.encode(state, timestamp)
  UINT.encode(state, ptr)
  return state.buffer.subarray(start, state.start)
}

module.exports = { store, core, group }

function alloc() {
  if (slab.buffer.byteLength - slab.start < 4096) {
    slab.buffer = b4a.allocUnsafe(slab.buffer.byteLength)
    slab.start = 0
  }
  return slab
}
const b4a = require('b4a')
const BlockDependencyStream = require('./block-dependency-stream.js')
const { core, store, group } = require('./keys.js')
const schema = require('../encoding/spec/hyperschema')

const CORESTORE_CORE = schema.getEncoding('@corestore/core')
const CORE_TREE_NODE = schema.getEncoding('@core/tree-node')
const EMPTY = b4a.alloc(0)

module.exports = {
  createBlockStream,
  createBitfieldStream,
  createUserDataStream,
  createCoreStream,
  createAliasStream,
  createDiscoveryKeyStream,
  createTreeNodeStream,
  createMarkStream,
  createLocalStream,
  createGroupUpdateStream
}

function createCoreStream(db, view) {
  const start = store.coreStart()
  const end = store.coreEnd()

  const ite = view.iterator(db, start, end, false)

  ite._readableState.map = mapCore
  return ite
}

function createDiscoveryKeyStream(db, view, namespace) {
  const start = namespace ? store.coreByAliasStart(namespace) : store.coreStart()
  const end = namespace ? store.coreByAliasEnd(namespace) : store.coreEnd()

  const ite = view.iterator(db, start, end, false)

  ite._readableState.map = namespace ? mapNamespaceDiscoveryKeys : mapAllDiscoveryKeys
  return ite
}

function createAliasStream(db, view, namespace) {
  const start = store.coreByAliasStart(namespace)
  const end = store.coreByAliasEnd(namespace)

  const ite = view.iterator(db, start, end, false)

  ite._readableState.map = mapAlias
  return ite
}

function createGroupUpdateStream(db, view, groupID, { gte = 0, reverse = true } = {}) {
  const start = group.entry(groupID, gte, 0)
  const end = group.entry(groupID + 1, 0, 0)

  const ite = view.iterator(db, start, end, reverse)

  ite._readableState.map = mapGroupUpdate
  return ite
}

function createBlockIterator(ptr, db, view, start, end, reverse) {
  if (ptr.dependencies.length > 0) {
    return new BlockDependencyStream(ptr, db, view, start, end, reverse)
  }

  const s = core.block(ptr.dataPointer, start)
  const e = core.block(ptr.dataPointer, end === -1 ? Infinity : end)
  return view.iterator(db, s, e, reverse)
}

function createBlockStream(
  ptr,
  db,
  view,
  { gt = -1, gte = gt + 1, lte = -1, lt = lte === -1 ? -1 : lte + 1, reverse = false } = {}
) {
  const ite = createBlockIterator(ptr, db, view, gte, lt, reverse)

  ite._readableState.map = mapBlock
  return ite
}

function createBitfieldStream(
  ptr,
  db,
  view,
  { gt = -1, gte = gt + 1, lte = -1, lt = lte === -1 ? -1 : lte + 1, reverse = false } = {}
) {
  const s = core.bitfield(ptr.dataPointer, gte, 0)
  const e = core.bitfield(ptr.dataPointer, lt === -1 ? Infinity : lt, 0)
  const ite = view.iterator(db, s, e, false)

  ite._readableState.map = mapBitfield
  return ite
}

// NOTE: this does not do dependency lookups atm
function createTreeNodeStream(
  ptr,
  db,
  view,
  { gt = -1, gte = gt + 1, lte = -1, lt = lte === -1 ? -1 : lte + 1, reverse = false } = {}
) {
  const s = core.tree(ptr.dataPointer, gte, 0)
  const e = core.tree(ptr.dataPointer, lt === -1 ? Infinity : lt, 0)
  const ite = view.iterator(db, s, e, false)

  ite._readableState.map = mapTreeNode
  return ite
}

function createUserDataStream(
  ptr,
  db,
  view,
  { gt = null, gte = '', lte = null, lt = null, reverse = false } = {}
) {
  if (gt !== null || lte !== null) {
    throw new Error('gt and lte not yet supported for user data streams')
  }

  const s = core.userData(ptr.dataPointer, gte)
  const e = lt === null ? core.userDataEnd(ptr.dataPointer) : core.userData(ptr.dataPointer, lt)
  const ite = view.iterator(db, s, e, false)

  ite._readableState.map = mapUserData
  return ite
}

function createMarkStream(
  ptr,
  db,
  view,
  { gt = -1, gte = gt + 1, lte = -1, lt = lte === -1 ? -1 : lte + 1, reverse = false } = {}
) {
  const s = core.mark(ptr.dataPointer, gte)
  const e = core.mark(ptr.dataPointer, lt === -1 ? Infinity : lt)
  const ite = view.iterator(db, s, e, reverse)

  ite._readableState.map = mapMark
  return ite
}

function createLocalStream(
  ptr,
  db,
  view,
  { gt = null, gte = EMPTY, lte = null, lt = null, reverse = false } = {}
) {
  if (gt !== null || lte !== null) throw new Error('gt and lte not yet supported for local streams')

  const s = core.local(ptr.dataPointer, gte)
  const e = lt === null ? core.localEnd(ptr.dataPointer) : core.local(ptr.dataPointer, lt)
  const ite = view.iterator(db, s, e, false)

  ite._readableState.map = mapLocal
  return ite
}

function mapBitfield(data) {
  const [index, type] = core.bitfieldIndexAndType(data.key)
  if (type !== 0) return null // ignore for now
  return { index, page: data.value }
}

function mapMark(data) {
  const index = core.markKey(data.key)
  return { index, page: data.value }
}

function mapLocal(data) {
  const key = core.localKey(data.key)
  return { key, value: data.value }
}

function mapGroupUpdate(data) {
  return data.value
}

function mapUserData(data) {
  const key = core.userDataKey(data.key)
  return { key, value: data.value }
}

function mapCore(data) {
  const discoveryKey = store.discoveryKey(data.key)
  const core = CORESTORE_CORE.decode({
    start: 0,
    end: data.value.byteLength,
    buffer: data.value
  })
  return { discoveryKey, core }
}

function mapAllDiscoveryKeys(data) {
  return store.discoveryKey(data.key)
}

function mapNamespaceDiscoveryKeys(data) {
  return data.value
}

function mapAlias(data) {
  const alias = store.alias(data.key)
  return { alias, discoveryKey: data.value }
}

function mapBlock(data) {
  return { index: core.blockIndex(data.key), value: data.value }
}

function mapTreeNode(data) {
  return CORE_TREE_NODE.decode({
    start: 0,
    end: data.value.byteLength,
    buffer: data.value
  })
}
const b4a = require('b4a')
const c = require('compact-encoding')
const flat = require('flat-tree')

const schema = require('../encoding/spec/hyperschema')
const { store, core, group } = require('./keys.js')
const View = require('./view.js')

const CORESTORE_HEAD = schema.getEncoding('@corestore/head')
const CORESTORE_CORE = schema.getEncoding('@corestore/core')
const CORESTORE_GROUP = c.uint

const CORE_AUTH = schema.getEncoding('@core/auth')
const CORE_GROUP = schema.getEncoding('@core/group')
const CORE_SESSIONS = schema.getEncoding('@core/sessions')
const CORE_HEAD = schema.getEncoding('@core/head')
const CORE_TREE_NODE = schema.getEncoding('@core/tree-node')
const CORE_DEPENDENCY = schema.getEncoding('@core/dependency')
const CORE_HINTS = schema.getEncoding('@core/hints')

class CoreTX {
  constructor(core, db, view, changes) {
    if (db.snapshotted) throw new Error('Cannot open core tx on snapshot')
    this.core = core
    this.db = db
    this.view = view
    this.changes = changes
  }

  setAuth(auth) {
    this.changes.push([core.auth(this.core.corePointer), encode(CORE_AUTH, auth), null])
  }

  setSessions(sessions) {
    this.changes.push([core.sessions(this.core.corePointer), encode(CORE_SESSIONS, sessions), null])
  }

  setHead(head) {
    this.changes.push([core.head(this.core.dataPointer), encode(CORE_HEAD, head), null])
  }

  deleteHead() {
    this.changes.push([core.head(this.core.dataPointer), null, null])
  }

  setDependency(dep) {
    this.changes.push([core.dependency(this.core.dataPointer), encode(CORE_DEPENDENCY, dep), null])
  }

  setGroup(group) {
    this.changes.push([core.group(this.core.dataPointer), encode(CORE_GROUP, group), null])
  }

  deleteGroup() {
    this.changes.push([core.group(this.core.dataPointer), null, null])
  }

  setHints(hints) {
    this.changes.push([core.hints(this.core.dataPointer), encode(CORE_HINTS, hints), null])
  }

  putBlock(index, data) {
    this.changes.push([core.block(this.core.dataPointer, index), data, null])
  }

  deleteBlock(index) {
    this.changes.push([core.block(this.core.dataPointer, index), null, null])
  }

  deleteBlockRange(start, end) {
    this.changes.push([
      core.block(this.core.dataPointer, start),
      null,
      core.block(this.core.dataPointer, end === -1 ? Infinity : end)
    ])
  }

  putBitfieldPage(index, data) {
    this.changes.push([core.bitfield(this.core.dataPointer, index, 0), data, null])
  }

  deleteBitfieldPage(index) {
    this.changes.push([core.bitfield(this.core.dataPointer, index, 0), null, null])
  }

  deleteBitfieldPageRange(start, end) {
    this.changes.push([
      core.bitfield(this.core.dataPointer, start, 0),
      null,
      core.bitfield(this.core.dataPointer, end === -1 ? Infinity : end, 0)
    ])
  }

  putTreeNode(node) {
    this.changes.push([
      core.tree(this.core.dataPointer, node.index),
      encode(CORE_TREE_NODE, node),
      null
    ])
  }

  deleteTreeNode(index) {
    this.changes.push([core.tree(this.core.dataPointer, index), null, null])
  }

  deleteTreeNodeRange(start, end) {
    this.changes.push([
      core.tree(this.core.dataPointer, start),
      null,
      core.tree(this.core.dataPointer, end === -1 ? Infinity : end)
    ])
  }

  putUserData(key, value) {
    const buffer = typeof value === 'string' ? b4a.from(value) : value
    this.changes.push([core.userData(this.core.dataPointer, key), buffer, null])
  }

  deleteUserData(key) {
    this.changes.push([core.userData(this.core.dataPointer, key), null, null])
  }

  putMark(index, data) {
    this.changes.push([core.mark(this.core.dataPointer, index), data, null])
  }

  deleteMark(index) {
    this.changes.push([core.mark(this.core.dataPointer, index), null, null])
  }

  deleteMarkRange(start, end) {
    this.changes.push([
      core.mark(this.core.dataPointer, start),
      null,
      core.mark(this.core.dataPointer, end === -1 ? Infinity : end)
    ])
  }

  putLocal(key, value) {
    this.changes.push([core.local(this.core.dataPointer, key), value, null])
  }

  deleteLocal(key) {
    this.changes.push([core.local(this.core.dataPointer, key), null, null])
  }

  deleteLocalRange(start, end) {
    this.changes.push([
      core.local(this.core.dataPointer, start),
      null,
      end === null ? core.localEnd(this.core.dataPointer) : core.local(this.core.dataPointer, end)
    ])
  }

  putGroupUpdate(groupPtr, timestamp, key) {
    this.changes.push([group.entry(groupPtr, timestamp, this.core.corePointer), key, null])
  }

  deleteGroupUpdate(groupPtr, timestamp) {
    this.changes.push([group.entry(groupPtr, timestamp, this.core.corePointer), null, null])
  }

  flush() {
    const changes = this.changes
    if (changes === null) return Promise.resolve(!this.view)

    this.changes = null

    if (this.view) {
      this.view.apply(changes)
      return Promise.resolve(false)
    }

    return View.flush(changes, this.db)
  }
}

class CoreRX {
  constructor(core, db, view, treeCache, stats, fork) {
    this.core = core
    this.read = db.read({ autoDestroy: true })
    this.view = view
    this.treeCache = treeCache
    this.fork = fork
    this.stats = stats

    view.readStart()
  }

  static async getAuth(db, c) {
    return decode(CORE_AUTH, await db.get(core.auth(c.corePointer)))
  }

  async getAuth() {
    return decode(CORE_AUTH, await this.view.get(this.read, core.auth(this.core.corePointer)))
  }

  async getSessions() {
    return decode(
      CORE_SESSIONS,
      await this.view.get(this.read, core.sessions(this.core.corePointer))
    )
  }

  static async getHead(db, c) {
    return decode(CORE_HEAD, await db.get(core.head(c.dataPointer)))
  }

  async getHead() {
    return decode(CORE_HEAD, await this.view.get(this.read, core.head(this.core.dataPointer)))
  }

  async getDependency() {
    return decode(
      CORE_DEPENDENCY,
      await this.view.get(this.read, core.dependency(this.core.dataPointer))
    )
  }

  async getGroup() {
    return await decode(
      CORE_GROUP,
      await this.view.get(this.read, core.group(this.core.corePointer))
    )
  }

  static async getHints(db, c) {
    return decode(CORE_HINTS, await db.get(core.hints(c.dataPointer)))
  }

  async getHints() {
    return decode(CORE_HINTS, await this.view.get(this.read, core.hints(this.core.dataPointer)))
  }

  getBlock(index) {
    const dep = findBlockDependency(this.core.dependencies, index)
    const data = dep === null ? this.core.dataPointer : dep.dataPointer
    return this.view.get(this.read, core.block(data, index))
  }

  getBitfieldPage(index) {
    return this.view.get(this.read, core.bitfield(this.core.dataPointer, index, 0))
  }

  async _resolveTreeCache(key, promise, entry) {
    try {
      const value = decode(CORE_TREE_NODE, await promise)
      const cached = this.treeCache.get(key)

      // preflight is gone; no-op
      if (cached !== entry) return value

      if (value !== null) {
        // replace cached entry with value
        this.treeCache.set(key, { pending: null, value })
      } else {
        // discard non-existing values
        this.treeCache.delete(key)
      }

      return value
    } catch (err) {
      // cleanup
      const cached = this.treeCache.get(key)
      if (cached === entry) {
        this.treeCache.delete(key)
      }

      throw err
    }
  }

  async getTreeNode(index) {
    const dep = findTreeDependency(this.core.dependencies, index)
    const data = dep === null ? this.core.dataPointer : dep.dataPointer

    if (!this.treeCache || this.fork < 0) {
      if (this.stats !== null) this.stats.treeCache.skips++
      // no-cache
      return decode(CORE_TREE_NODE, await this.view.get(this.read, core.tree(data, index)))
    }

    const key = `${data}:${index}:${this.fork}`
    let entry = this.treeCache.get(key)
    if (entry) {
      if (entry.pending) {
        if (this.stats !== null) this.stats.treeCache.parallel++
        return entry.pending
      }

      if (this.stats !== null) this.stats.treeCache.hits++
      return entry.value
    }

    if (this.stats !== null) this.stats.treeCache.misses++

    const promise = this.view.get(this.read, core.tree(data, index))
    entry = { pending: null, value: null }
    entry.pending = this._resolveTreeCache(key, promise, entry)
    this.treeCache.set(key, entry)

    return entry.pending
  }

  async hasTreeNode(index) {
    return (await this.getTreeNode(index)) !== null
  }

  getUserData(key) {
    return this.view.get(this.read, core.userData(this.core.dataPointer, key))
  }

  getMark(index) {
    return this.view.get(this.read, core.mark(this.core.dataPointer, index))
  }

  getLocal(key) {
    return this.view.get(this.read, core.local(this.core.dataPointer, key))
  }

  tryFlush() {
    this.read.tryFlush()
    this._free()
  }

  destroy() {
    this.read.destroy()
    this._free()
  }

  _free() {
    if (this.view === null) return
    this.view.readStop()
    this.view = null
  }
}

class CorestoreTX {
  constructor(view) {
    this.view = view
    this.changes = []
  }

  setHead(head) {
    this.changes.push([store.head(), encode(CORESTORE_HEAD, head), null])
  }

  setCoreHints(c, hints) {
    this.changes.push([core.hints(c.dataPointer), encode(CORE_HINTS, hints), null])
  }

  putCore(discoveryKey, ptr) {
    this.changes.push([store.core(discoveryKey), encode(CORESTORE_CORE, ptr), null])
  }

  putCoreByAlias(alias, discoveryKey) {
    this.changes.push([store.coreByAlias(alias), discoveryKey, null])
  }

  putGroup(topic, groupPtr) {
    this.changes.push([group.topic(topic), encode(CORESTORE_GROUP, groupPtr), null])
  }

  deleteGroup(topic) {
    this.changes.push([group.topic(topic), null, null])
  }

  clear() {
    const [start, end] = store.clear()
    this.changes.push([start, null, end])
  }

  apply() {
    if (this.changes === null) return
    this.view.apply(this.changes)
    this.changes = null
  }
}

class CorestoreRX {
  constructor(db, view) {
    this.read = db.read({ autoDestroy: true })
    this.view = view

    view.readStart()
  }

  async getHeadRaw(db) {
    return await this.view.get(this.read, store.head())
  }

  async getHead() {
    return decode(CORESTORE_HEAD, await this.view.get(this.read, store.head()))
  }

  async getCore(discoveryKey) {
    return decode(CORESTORE_CORE, await this.view.get(this.read, store.core(discoveryKey)))
  }

  getCoreByAlias(alias) {
    return this.view.get(this.read, store.coreByAlias(alias))
  }

  async getGroup(topic) {
    return decode(CORESTORE_GROUP, await this.view.get(this.read, group.topic(topic)))
  }

  tryFlush() {
    this.read.tryFlush()
    this._free()
  }

  destroy() {
    this.read.destroy()
    this._free()
  }

  _free() {
    if (this.view === null) return
    this.view.readStop()
    this.view = null
  }
}

module.exports = { CorestoreTX, CorestoreRX, CoreTX, CoreRX }

function findBlockDependency(dependencies, index) {
  for (let i = 0; i < dependencies.length; i++) {
    const dep = dependencies[i]
    if (index < dep.length) return dep
  }

  return null
}

function findTreeDependency(dependencies, index) {
  for (let i = 0; i < dependencies.length; i++) {
    const dep = dependencies[i]
    if (flat.rightSpan(index) <= (dep.length - 1) * 2) return dep
  }

  return null
}

function decode(enc, buffer) {
  if (buffer === null) return null
  return enc.decode({ start: 0, end: buffer.byteLength, buffer })
}

function encode(enc, m) {
  // TODO: use fancy slab for small messages
  const state = { start: 0, end: 0, buffer: null }
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}
const { Readable, getStreamError } = require('streamx')
const CloseErrorStream = require('./close-error-stream.js')
const b4a = require('b4a')

class OverlayStream extends Readable {
  constructor(stream, start, end, reverse, changes, cleared) {
    super()

    this.start = start
    this.end = end
    this.reverse = reverse
    this.changes = changes
    this.cleared = cleared
    this.change = 0
    this.range = 0

    this._stream = stream
    this._drained = false

    this._stream.on('readable', this._drainMaybe.bind(this))
    this._stream.on('error', noop)
    this._stream.on('close', this._onclose.bind(this))
  }

  _drainMaybe() {
    if (this._drained === true) return
    this._drained = this._onreadable()
  }

  _onclose() {
    if (this.destroying) return

    const err = getStreamError(this._stream)

    if (err !== null) {
      this.destroy(err)
      return
    }

    while (this.change < this.changes.length) {
      const c = this.changes[this.change++]
      const key = c[0]
      const value = c[1]

      if (value !== null && this._inRange(key)) this.push({ key, value })
    }

    this.push(null)
    this._stream = null
  }

  _onreadable() {
    let data = this._stream.read()
    if (data === null) return false

    let drained = false

    do {
      if (this._push(data) === true) drained = true
      data = this._stream.read()
    } while (data !== null)

    return drained
  }

  _read(cb) {
    this._drained = this._onreadable()
    cb(null)
  }

  _predestroy() {
    this._stream.destroy()
  }

  _push(entry) {
    const key = entry.key

    while (this.range < this.cleared.length) {
      const c = this.cleared[this.range]

      // we moved past the range
      if (this.reverse ? b4a.compare(key, c[0]) < 0 : b4a.compare(c[2], key) <= 0) {
        this.range++
        continue
      }

      // we didnt move past and are in, drop
      if (b4a.compare(c[0], key) <= 0 && b4a.compare(key, c[2]) < 0) {
        return false
      }

      break
    }

    let updated = false

    while (this.change < this.changes.length) {
      const c = this.changes[this.change]
      const key = c[0]
      const value = typeof c[1] === 'string' ? b4a.from(c[1]) : c[1]
      const cmp = b4a.compare(key, entry.key)

      // same value, if not deleted, return new one
      if (cmp === 0) {
        this.change++
        if (value === null || this._inRange(key) === false) return updated
        this.push({ key, value })
        return true
      }

      // we moved past the change, push it
      if (this.reverse ? cmp > 0 : cmp < 0) {
        this.change++
        if (value === null || this._inRange(key) === false) continue
        this.push({ key, value })
        updated = true
        continue
      }

      this.push(entry)
      return true
    }

    this.push(entry)
    return true
  }

  _inRange(key) {
    return b4a.compare(this.start, key) <= 0 && b4a.compare(key, this.end) < 0
  }
}

class Overlay {
  constructor() {
    this.indexed = 0
    this.changes = null
    this.cleared = null
    this.reverse = false
  }

  update(view, reverse) {
    if (view.indexed === this.indexed) return

    const changes = view.map === null ? [] : [...view.map.values()]
    const cleared = view.cleared === null ? [] : view.cleared.slice(0)

    const cmp = reverse ? cmpChangeReverse : cmpChange

    changes.sort(cmp)
    cleared.sort(cmp)

    this.indexed = view.indexed
    this.changes = changes
    this.cleared = cleared
    this.reverse = reverse
  }

  createStream(stream, start, end, reverse) {
    return new OverlayStream(
      stream,
      start,
      end,
      reverse,
      this.reverse === reverse ? this.changes : reverseArray(this.changes),
      this.reverse === reverse ? this.cleared : reverseArray(this.cleared)
    )
  }
}

class View {
  constructor() {
    this.map = null
    this.indexed = 0
    this.changes = null
    this.cleared = null
    this.overlay = null
    this.snap = null
    this.readers = 0
  }

  snapshot() {
    if (this._attached()) return this.snap.snapshot()

    const snap = new View()

    snap.map = this.map
    snap.indexed = this.indexed
    snap.changes = this.changes
    snap.cleared = this.cleared

    if (this._frozen()) return snap

    this.readers++
    snap.snap = this

    return snap
  }

  readStart() {
    if (this.snap !== null) this.readers++
  }

  readStop() {
    if (this.snap !== null && --this.readers === 0) this.snap.readers--
  }

  size() {
    return this.changes === null ? 0 : this.changes.length
  }

  updated() {
    return this.changes === null
  }

  get(read, key) {
    return this.changes === null ? read.get(key) : this._indexAndGet(read, key)
  }

  reset() {
    this.indexed = 0
    this.snap = this.map = this.changes = this.cleared = this.overlay = null
  }

  iterator(db, start, end, reverse) {
    if (dbClosing(db)) return new CloseErrorStream(new Error('RocksDB session is closed'))

    const stream = db.iterator({ gte: start, lt: end, reverse })
    if (this.changes === null) return stream

    this._index()

    if (this.overlay === null) this.overlay = new Overlay()
    this.overlay.update(this, reverse)
    return this.overlay.createStream(stream, start, end, reverse)
  }

  _indexAndGet(read, key) {
    this._index()
    const change = this.map.get(b4a.toString(key, 'hex'))

    if (change === undefined) {
      return this.cleared === null ? read.get(key) : this._readAndMaybeDrop(read, key)
    }

    return Promise.resolve(change[1])
  }

  async _readAndMaybeDrop(read, key) {
    const cleared = this.cleared // in case its cleared
    const value = await read.get(key)
    if (value === null) return null

    for (let i = 0; i < cleared.length; i++) {
      const c = cleared[i]
      // check if in range
      if (b4a.compare(c[0], key) <= 0 && b4a.compare(key, c[2]) < 0) return null
    }

    return value
  }

  _attached() {
    return this.snap !== null && this.changes === this.snap.changes
  }

  _frozen() {
    return this.changes === null || (this.snap !== null && this.changes !== this.snap.changes)
  }

  _index() {
    // if we are a snap and we are still attached (ie no mutations), simply copy the refs
    if (this._attached()) {
      this.snap._index()
      this.map = this.snap.map
      this.cleared = this.snap.cleared
      this.indexed = this.snap.indexed
      return
    }

    if (this.map === null) this.map = new Map()
    if (this.changes.length === this.indexed) return

    while (this.indexed < this.changes.length) {
      const c = this.changes[this.indexed++]

      if (c[2] === null) this.map.set(b4a.toString(c[0], 'hex'), c)
      else this._indexRange(c)
    }
  }

  _indexRange(range) {
    const s = b4a.toString(range[0], 'hex')
    const e = b4a.toString(range[2], 'hex')

    for (const [key, c] of this.map) {
      if (s <= key && key < e) this.map.set(key, [c[0], null, null])
    }

    if (this.cleared === null) this.cleared = []
    this.cleared.push(range)
  }

  apply(changes) {
    if (this.snap !== null) throw new Error('Illegal to push changes to a snapshot')

    if (this.readers !== 0 && this.changes !== null) {
      this.changes = this.changes.slice(0)
      this.cleared = this.cleared === null ? null : this.cleared.slice(0)
      this.map = this.map === null ? null : new Map([...this.map])
    }

    if (this.changes === null) {
      this.changes = changes
      return
    }

    for (let i = 0; i < changes.length; i++) {
      this.changes.push(changes[i])
    }
  }

  static async flush(changes, db) {
    if (changes === null) return true

    const w = db.write({ autoDestroy: true })

    for (const [start, value, end] of changes) {
      if (end !== null) w.tryDeleteRange(start, end)
      else if (value !== null) w.tryPut(start, value)
      else w.tryDelete(start)
    }

    await w.flush()

    return true
  }
}

module.exports = View

function cmpChange(a, b) {
  const c = b4a.compare(a[0], b[0])
  return c === 0 ? b4a.compare(a[2], b[2]) : c
}

function cmpChangeReverse(a, b) {
  return cmpChange(b, a)
}

function noop() {}

function reverseArray(list) {
  const r = new Array(list.length)
  for (let i = 0; i < list.length; i++) r[r.length - 1 - i] = list[i]
  return r
}

// TODO: expose from rocks instead
function dbClosing(db) {
  return db._state.closing || db._index === -1
}
const fs = require('fs')
const path = require('path')
const { Readable } = require('streamx')
const b4a = require('b4a')
const flat = require('flat-tree')
const crypto = require('hypercore-crypto')
const c = require('compact-encoding')
const m = require('./messages.js')
const View = require('../../lib/view.js')
const { CorestoreTX, CoreTX, CorestoreRX } = require('../../lib/tx.js')

const EMPTY_NODE = b4a.alloc(40)
const EMPTY_PAGE = b4a.alloc(4096)

let TREE_01_SKIP = null
let TREE_04_SKIP = null
let TREE_16_SKIP = null

class CoreListStream extends Readable {
  constructor (storage) {
    super()

    this.storage = storage
    this.stack = []
  }

  async _open (cb) {
    for (const a of await readdir(path.join(this.storage, 'cores'))) {
      for (const b of await readdir(path.join(this.storage, 'cores', a))) {
        for (const dkey of await readdir(path.join(this.storage, 'cores', a, b))) {
          this.stack.push(path.join(this.storage, 'cores', a, b, dkey))
        }
      }
    }

    cb(null)
  }

  async _read (cb) {
    while (true) {
      const next = this.stack.pop()
      if (!next) {
        this.push(null)
        break
      }

      const oplog = path.join(next, 'oplog')
      const result = await readOplog(oplog)
      if (!result) continue

      this.push(result)
      break
    }

    cb(null)
  }
}

function decodeOplogHeader (state) {
  c.uint32.decode(state) // cksum, ignore for now

  const l = c.uint32.decode(state)
  const length = l >> 2
  const headerBit = l & 1
  const partialBit = l & 2

  if (state.end - state.start < length) return null

  const end = state.start + length
  const result = { header: headerBit, partial: partialBit !== 0, byteLength: length + 8, message: null }

  try {
    result.message = m.oplog.header.decode({ start: state.start, end, buffer: state.buffer })
  } catch {
    return null
  }

  state.start = end
  return result
}

function decodeOplogEntry (state) {
  if (state.end - state.start < 8) return null

  c.uint32.decode(state) // cksum, ignore for now

  const l = c.uint32.decode(state)
  const length = l >>> 2
  const headerBit = l & 1
  const partialBit = l & 2

  if (state.end - state.start < length) return null

  const end = state.start + length

  const result = { header: headerBit, partial: partialBit !== 0, byteLength: length + 8, message: null }

  try {
    result.message = m.oplog.entry.decode({ start: state.start, end, buffer: state.buffer })
  } catch {
    return null
  }

  state.start = end

  return result
}

module.exports = { store, core }

async function store (storage, { version, dryRun = true, gc = true }) {
  const stream = new CoreListStream(storage.path)
  const view = new View()

  const tx = new CorestoreTX(view)
  const head = await storage._getHead(view)
  const primaryKeyFile = path.join(storage.path, 'primary-key')

  const primaryKey = await readFile(primaryKeyFile)

  if (!head.seed) head.seed = primaryKey

  for await (const data of stream) {
    const key = data.header.key
    const discoveryKey = crypto.discoveryKey(data.header.key)
    const files = getFiles(data.path)

    if (head.defaultDiscoveryKey === null) head.defaultDiscoveryKey = discoveryKey

    const core = {
      version: 0, // need later migration
      corePointer: head.allocated.cores++,
      dataPointer: head.allocated.datas++,
      alias: null
    }

    const ptr = { version: 0, corePointer: core.corePointer, dataPointer: core.dataPointer, dependencies: [] }
    const ctx = new CoreTX(ptr, storage.db, view, [])
    const userData = new Map()
    const treeNodes = new Map()

    const auth = {
      key,
      discoveryKey,
      manifest: data.header.manifest,
      keyPair: data.header.keyPair,
      encryptionKey: null
    }

    const tree = {
      length: 0,
      fork: 0,
      rootHash: null,
      signature: null
    }

    if (data.header.tree && data.header.tree.length) {
      tree.length = data.header.tree.length
      tree.fork = data.header.tree.fork
      tree.rootHash = data.header.tree.rootHash
      tree.signature = data.header.tree.signature
    }

    for (const { key, value } of data.header.userData) {
      userData.set(key, value)
    }

    for (const e of data.entries) {
      if (e.userData) userData.set(e.userData.key, e.userData.value)

      if (e.treeNodes) {
        for (const node of e.treeNodes) {
          treeNodes.set(node.index, node)
          ctx.putTreeNode(node)
        }
      }

      if (e.treeUpgrade) {
        if (e.treeUpgrade.ancestors !== tree.length) {
          throw new Error('Unflushed truncations not migrate-able atm')
        }

        tree.length = e.treeUpgrade.length
        tree.fork = e.treeUpgrade.fork
        tree.rootHash = null
        tree.signature = e.treeUpgrade.signature
      }
    }

    if (userData.has('corestore/name') && userData.has('corestore/namespace')) {
      core.alias = {
        name: b4a.toString(userData.get('corestore/name')),
        namespace: userData.get('corestore/namespace')
      }
      userData.delete('corestore/name')
      userData.delete('corestore/namespace')
    }

    for (const [key, value] of userData) {
      ctx.putUserData(key, value)
    }

    ctx.setAuth(auth)

    const getTreeNode = (index) => (treeNodes.get(index) || getTreeNodeFromFile(files.tree, index))

    if (tree.length) {
      if (tree.rootHash === null) tree.rootHash = crypto.tree(await getRoots(tree.length, getTreeNode))
      ctx.setHead(tree)
    }

    tx.putCore(discoveryKey, core)
    if (core.alias) tx.putCoreByAlias(core.alias, discoveryKey)

    await ctx.flush()
  }

  head.version = version
  tx.setHead(head)
  tx.apply()

  if (dryRun) return

  await View.flush(view.changes, storage.db)

  if (gc) await rm(primaryKeyFile)
}

class BlockSlicer {
  constructor (filename) {
    this.stream = fs.createReadStream(filename)
    this.closed = new Promise(resolve => this.stream.once('close', resolve))
    this.offset = 0
    this.overflow = null
  }

  async take (offset, size) {
    let buffer = null
    if (offset < this.offset) throw new Error('overread')

    while (true) {
      let data = null

      if (this.overflow) {
        data = this.overflow
        this.overflow = null
      } else {
        data = this.stream.read()

        if (!data) {
          await new Promise(resolve => this.stream.once('readable', resolve))
          continue
        }
      }

      let chunk = null

      if (this.offset === offset || buffer) {
        chunk = data
      } else if (this.offset + data.byteLength > offset) {
        chunk = data.subarray(offset - this.offset)
      }

      this.offset += data.byteLength
      if (!chunk) continue

      if (buffer) buffer = b4a.concat([buffer, chunk])
      else buffer = chunk

      if (buffer.byteLength < size) continue

      const result = buffer.subarray(0, size)
      this.overflow = size === buffer.byteLength ? null : buffer.subarray(result.byteLength)
      this.offset -= (this.overflow ? this.overflow.byteLength : 0)
      return result
    }
  }

  close () {
    this.stream.on('error', noop)
    this.stream.destroy()
    return this.closed
  }
}

class TreeSlicer {
  constructor () {
    this.buffer = null
    this.offset = 0
  }

  get size () {
    return this.buffer === null ? 0 : this.buffer.byteLength
  }

  push (data) {
    if (this.buffer === null) this.buffer = data
    else this.buffer = b4a.concat([this.buffer, data])
    this.offset += data.byteLength
  }

  skip () {
    let skipped = 0

    if (TREE_01_SKIP === null) {
      TREE_16_SKIP = b4a.alloc(16 * 40 * 100)
      TREE_04_SKIP = TREE_16_SKIP.subarray(0, 4 * 40 * 100)
      TREE_01_SKIP = TREE_16_SKIP.subarray(0, 1 * 40 * 100)
    }

    while (true) {
      if (this.buffer.byteLength >= TREE_16_SKIP.byteLength) {
        if (b4a.equals(this.buffer.subarray(0, TREE_16_SKIP.byteLength), TREE_16_SKIP)) {
          this.buffer = this.buffer.subarray(TREE_16_SKIP.byteLength)
          skipped += 1600
          continue
        }
      }

      if (this.buffer.byteLength >= TREE_04_SKIP.byteLength) {
        if (b4a.equals(this.buffer.subarray(0, TREE_04_SKIP.byteLength), TREE_04_SKIP)) {
          this.buffer = this.buffer.subarray(TREE_04_SKIP.byteLength)
          skipped += 400
          continue
        }
      }

      if (this.buffer.byteLength >= TREE_01_SKIP.byteLength) {
        if (b4a.equals(this.buffer.subarray(0, TREE_01_SKIP.byteLength), TREE_01_SKIP)) {
          this.buffer = this.buffer.subarray(TREE_01_SKIP.byteLength)
          skipped += 100
          continue
        }
      }
      break
    }

    return skipped
  }

  take () {
    const len = 40

    if (len <= this.size) {
      const chunk = this.buffer.subarray(0, len)
      this.buffer = this.buffer.subarray(len)
      return chunk
    }

    return null
  }
}

async function core (core, { version, dryRun = true, gc = true }) {
  if (dryRun) return // dryRun mode not supported atm

  const rx = core.read()

  const promises = [rx.getAuth(), rx.getHead()]
  rx.tryFlush()

  const [auth, head] = await Promise.all(promises)

  if (!auth) return

  const dk = b4a.toString(auth.discoveryKey, 'hex')
  const files = getFiles(path.join(core.store.path, 'cores', dk.slice(0, 2), dk.slice(2, 4), dk))

  if (head === null || head.length === 0) {
    await commitCoreMigration(auth, core, version)
    if (gc) await runGC()
    return // no data
  }

  const oplog = await readOplog(files.oplog)
  if (!oplog) {
    const writable = !!auth.keyPair

    if (writable) {
      throw new Error('No oplog available writable core for ' + files.oplog + ', length = ' + (head ? head.length : 0))
    }

    // if not writable, just nuke it to recover, some bad state happened here, prop corruption from earlier versions
    const w = core.write()

    w.deleteBlockRange(0, -1)
    w.deleteTreeNodeRange(0, -1)
    w.deleteBitfieldPageRange(0, -1)
    w.deleteHead()

    await w.flush()

    await commitCoreMigration(auth, core, version)
    if (gc) await runGC()
    return // no data
  }

  const treeData = new TreeSlicer()

  let treeIndex = 0

  if (await exists(files.tree)) {
    for await (const data of fs.createReadStream(files.tree)) {
      treeData.push(data)

      let write = null

      while (true) {
        const skip = treeData.skip()
        treeIndex += skip

        const buf = treeData.take()
        if (buf === null) break

        const index = treeIndex++
        if (b4a.equals(buf, EMPTY_NODE)) continue

        if (write === null) write = core.write()
        write.putTreeNode(decodeTreeNode(index, buf))
      }

      if (write !== null) await write.flush()
    }
  }

  const buf = []
  if (await exists(files.bitfield)) {
    for await (const data of fs.createReadStream(files.bitfield)) {
      buf.push(data)
    }
  }

  let bitfield = b4a.concat(buf)
  if (bitfield.byteLength & 4095) bitfield = b4a.concat([bitfield, b4a.alloc(4096 - (bitfield.byteLength & 4095))])

  const pages = new Map()
  const headerBits = new Map()

  const roots = await getRootsFromStorage(core, head.length)

  for (const e of oplog.entries) {
    if (!e.bitfield) continue

    for (let i = 0; i < e.bitfield.length; i++) {
      headerBits.set(i + e.bitfield.start, !e.bitfield.drop)
    }
  }

  let batch = []

  const cache = new Map()
  const blocks = new BlockSlicer(files.data)

  for (const index of allBits(bitfield)) {
    if (headerBits.get(index) === false) continue
    if (index >= head.length) continue

    setBitInPage(index)

    batch.push(index)
    if (batch.length < 1024) continue

    await writeBlocksBatch()
    continue
  }

  if (batch.length) await writeBlocksBatch()

  await blocks.close()

  const w = core.write()

  for (const [index, bit] of headerBits) {
    if (!bit) continue
    if (index >= head.length) continue

    setBitInPage(index)

    const blk = await getBlockFromFile(files.data, core, index, roots, cache)
    w.putBlock(index, blk)
  }

  for (const [index, page] of pages) {
    w.putBitfieldPage(index, b4a.from(page.buffer, page.byteOffset, page.byteLength))
  }

  await w.flush()

  let contiguousLength = 0
  for await (const data of core.createBlockStream()) {
    if (data.index === contiguousLength) contiguousLength++
    else break
  }

  if (contiguousLength) {
    const w = core.write()
    w.setHints({ contiguousLength })
    await w.flush()
  }

  await commitCoreMigration(auth, core, version)

  if (gc) await runGC()

  async function runGC () {
    await rm(files.path)
    await rmdir(path.join(files.path, '..'))
    await rmdir(path.join(files.path, '../..'))
    await rmdir(path.join(core.store.path, 'cores'))
  }

  function setBitInPage (index) {
    const n = index & 32767
    const p = (index - n) / 32768

    let page = pages.get(p)

    if (!page) {
      page = new Uint32Array(1024)
      pages.set(p, page)
    }

    const o = n & 31
    const b = (n - o) / 32
    const v = 1 << o

    page[b] |= v
  }

  async function writeBlocksBatch () {
    const read = core.read()
    const promises = []
    for (const index of batch) promises.push(getByteRangeFromStorage(read, 2 * index, roots, cache))
    read.tryFlush()

    const r = await Promise.all(promises)
    const tx = core.write()

    for (let i = 0; i < r.length; i++) {
      const index = batch[i]
      const [offset, size] = r[i]

      const blk = await blocks.take(offset, size)
      tx.putBlock(index, blk)
    }

    batch = []
    if (cache.size > 16384) cache.clear()

    await tx.flush()
  }
}

async function commitCoreMigration (auth, core, version) {
  const view = new View()
  const rx = new CorestoreRX(core.db, view)

  const storeCorePromise = rx.getCore(auth.discoveryKey)
  rx.tryFlush()

  const storeCore = await storeCorePromise

  storeCore.version = version

  const tx = new CorestoreTX(view)

  tx.putCore(auth.discoveryKey, storeCore)
  tx.apply()

  await View.flush(view.changes, core.db)
}

async function getBlockFromFile (file, core, index, roots, cache) {
  const rx = core.read()
  const promise = getByteRangeFromStorage(rx, 2 * index, roots, cache)
  rx.tryFlush()
  const [offset, size] = await promise

  return new Promise(function (resolve) {
    readAll(file, size, offset, function (err, buf) {
      if (err) return resolve(null)
      resolve(buf)
    })
  })
}

function getFiles (dir) {
  return {
    path: dir,
    oplog: path.join(dir, 'oplog'),
    data: path.join(dir, 'data'),
    tree: path.join(dir, 'tree'),
    bitfield: path.join(dir, 'bitfield')
  }
}

async function getRootsFromStorage (core, length) {
  const all = []
  const rx = core.read()
  for (const index of flat.fullRoots(2 * length)) {
    all.push(rx.getTreeNode(index))
  }
  rx.tryFlush()
  return Promise.all(all)
}

async function getRoots (length, getTreeNode) {
  const all = []
  for (const index of flat.fullRoots(2 * length)) {
    all.push(await getTreeNode(index))
  }
  return all
}

function getCached (read, cache, index) {
  if (cache.has(index)) return cache.get(index)
  const p = read.getTreeNode(index)
  cache.set(index, p)
  return p
}

async function getByteRangeFromStorage (read, index, roots, cache) {
  const promises = [getCached(read, cache, index), getByteOffsetFromStorage(read, index, roots, cache)]
  const [node, offset] = await Promise.all(promises)
  if (!node) throw new Error('Node not found during migration: ' + index)
  return [offset, node.size]
}

async function getByteOffsetFromStorage (rx, index, roots, cache) {
  if (index === 0) return 0
  if ((index & 1) === 1) index = flat.leftSpan(index)

  let head = 0
  let offset = 0

  for (const node of roots) { // all async ticks happen once we find the root so safe
    head += 2 * ((node.index - head) + 1)

    if (index >= head) {
      offset += node.size
      continue
    }

    const ite = flat.iterator(node.index)
    const promises = []

    while (ite.index !== index) {
      if (index < ite.index) {
        ite.leftChild()
      } else {
        promises.push(getCached(rx, cache, ite.leftChild()))
        ite.sibling()
      }
    }

    const nodes = await Promise.all(promises)
    for (const node of nodes) offset += node.size

    return offset
  }

  throw new Error('Failed to find offset')
}

function decodeTreeNode (index, buf) {
  return { index, size: c.decode(c.uint64, buf), hash: buf.subarray(8) }
}

async function getTreeNodeFromFile (file, index) {
  return new Promise(function (resolve) {
    readAll(file, 40, index * 40, function (err, buf) {
      if (err) return resolve(null)
      resolve(decodeTreeNode(index, buf))
    })
  })
}

function readAll (filename, length, pos, cb) {
  const buf = b4a.alloc(length)

  fs.open(filename, 'r', function (err, fd) {
    if (err) return cb(err)

    let offset = 0

    fs.read(fd, buf, offset, buf.byteLength, pos, function loop (err, read) {
      if (err) return done(err)
      if (read === 0) return done(new Error('Partial read'))
      offset += read
      if (offset === buf.byteLength) return done(null, buf)
      fs.read(fd, offset, buf.byteLength - offset, buf, pos + offset, loop)
    })

    function done (err, value) {
      fs.close(fd, () => cb(err, value))
    }
  })
}

async function readdir (dir) {
  try {
    return await fs.promises.readdir(dir)
  } catch {
    return []
  }
}

async function exists (file) {
  try {
    await fs.promises.stat(file)
    return true
  } catch {
    return false
  }
}

async function readFile (file) {
  try {
    return await fs.promises.readFile(file)
  } catch {
    return null
  }
}

async function rm (dir) {
  try {
    await fs.promises.rm(dir, { recursive: true })
  } catch {}
}

async function rmdir (dir) {
  try {
    await fs.promises.rmdir(dir)
  } catch {}
}

function * allBits (buffer) {
  for (let i = 0; i < buffer.byteLength; i += EMPTY_PAGE.byteLength) {
    const page = buffer.subarray(i, i + EMPTY_NODE.byteLength)
    if (b4a.equals(page, EMPTY_PAGE)) continue

    const view = new Uint32Array(page.buffer, page.byteOffset, EMPTY_PAGE.byteLength / 4)

    for (let j = 0; j < view.length; j++) {
      const n = view[j]
      if (n === 0) continue

      for (let k = 0; k < 32; k++) {
        const m = 1 << k
        if (n & m) yield i * 8 + j * 32 + k
      }
    }
  }
}

function readOplog (oplog) {
  return new Promise(function (resolve) {
    fs.readFile(oplog, function (err, buffer) {
      if (err) return resolve(null)

      const state = { start: 0, end: buffer.byteLength, buffer }
      const headers = [1, 0]

      const h1 = decodeOplogHeader(state)
      state.start = 4096

      const h2 = decodeOplogHeader(state)
      state.start = 4096 * 2

      if (!h1 && !h2) return resolve(null)

      if (h1 && !h2) {
        headers[0] = h1.header
        headers[1] = h1.header
      } else if (!h1 && h2) {
        headers[0] = (h2.header + 1) & 1
        headers[1] = h2.header
      } else {
        headers[0] = h1.header
        headers[1] = h2.header
      }

      const header = (headers[0] + headers[1]) & 1
      const result = { path: path.dirname(oplog), header: null, entries: [] }
      const decoded = []

      result.header = header ? h2.message : h1.message

      if (result.header.external) {
        fs.readFile(path.join(oplog, '../header'), function (err, buffer) {
          if (err) return resolve(null)
          const start = result.header.external.start
          const end = start + result.header.external.length
          result.header = m.oplog.header.decode({ buffer, start, end })
          finish()
        })
        return
      }

      finish()

      function finish () {
        while (true) {
          const entry = decodeOplogEntry(state)
          if (!entry) break
          if (entry.header !== header) break

          decoded.push(entry)
        }

        while (decoded.length > 0 && decoded[decoded.length - 1].partial) decoded.pop()

        for (const e of decoded) {
          result.entries.push(e.message)
        }

        resolve(result)
      }
    })
  })
}

function noop () {}
// needed here for compat, copied from old hypercore, do not change this

const c = require('compact-encoding')
const b4a = require('b4a')

const EMPTY = b4a.alloc(0)
const DEFAULT_NAMESPACE = b4a.from('4144eea531e483d54e0c14f4ca68e0644f355343ff6fcb0f005200e12cd747cb', 'hex')

const hashes = {
  preencode (state, m) {
    state.end++ // small uint
  },
  encode (state, m) {
    if (m === 'blake2b') {
      c.uint.encode(state, 0)
      return
    }

    throw new Error('Unknown hash: ' + m)
  },
  decode (state) {
    const n = c.uint.decode(state)
    if (n === 0) return 'blake2b'
    throw new Error('Unknown hash id: ' + n)
  }
}

const signatures = {
  preencode (state, m) {
    state.end++ // small uint
  },
  encode (state, m) {
    if (m === 'ed25519') {
      c.uint.encode(state, 0)
      return
    }

    throw new Error('Unknown signature: ' + m)
  },
  decode (state) {
    const n = c.uint.decode(state)
    if (n === 0) return 'ed25519'
    throw new Error('Unknown signature id: ' + n)
  }
}

const signer = {
  preencode (state, m) {
    signatures.preencode(state, m.signature)
    c.fixed32.preencode(state, m.namespace)
    c.fixed32.preencode(state, m.publicKey)
  },
  encode (state, m) {
    signatures.encode(state, m.signature)
    c.fixed32.encode(state, m.namespace)
    c.fixed32.encode(state, m.publicKey)
  },
  decode (state) {
    return {
      signature: signatures.decode(state),
      namespace: c.fixed32.decode(state),
      publicKey: c.fixed32.decode(state)
    }
  }
}

const signerArray = c.array(signer)

const prologue = {
  preencode (state, p) {
    c.fixed32.preencode(state, p.hash)
    c.uint.preencode(state, p.length)
  },
  encode (state, p) {
    c.fixed32.encode(state, p.hash)
    c.uint.encode(state, p.length)
  },
  decode (state) {
    return {
      hash: c.fixed32.decode(state),
      length: c.uint.decode(state)
    }
  }
}

const manifestv0 = {
  preencode (state, m) {
    hashes.preencode(state, m.hash)
    state.end++ // type

    if (m.prologue && m.signers.length === 0) {
      c.fixed32.preencode(state, m.prologue.hash)
      return
    }

    if (m.quorum === 1 && m.signers.length === 1 && !m.allowPatch) {
      signer.preencode(state, m.signers[0])
    } else {
      state.end++ // flags
      c.uint.preencode(state, m.quorum)
      signerArray.preencode(state, m.signers)
    }
  },
  encode (state, m) {
    hashes.encode(state, m.hash)

    if (m.prologue && m.signers.length === 0) {
      c.uint.encode(state, 0)
      c.fixed32.encode(state, m.prologue.hash)
      return
    }

    if (m.quorum === 1 && m.signers.length === 1 && !m.allowPatch) {
      c.uint.encode(state, 1)
      signer.encode(state, m.signers[0])
    } else {
      c.uint.encode(state, 2)
      c.uint.encode(state, m.allowPatch ? 1 : 0)
      c.uint.encode(state, m.quorum)
      signerArray.encode(state, m.signers)
    }
  },
  decode (state) {
    const hash = hashes.decode(state)
    const type = c.uint.decode(state)

    if (type > 2) throw new Error('Unknown type: ' + type)

    if (type === 0) {
      return {
        version: 0,
        hash,
        allowPatch: false,
        quorum: 0,
        signers: [],
        prologue: {
          hash: c.fixed32.decode(state),
          length: 0
        }
      }
    }

    if (type === 1) {
      return {
        version: 0,
        hash,
        allowPatch: false,
        quorum: 1,
        signers: [signer.decode(state)],
        prologue: null
      }
    }

    const flags = c.uint.decode(state)

    return {
      version: 0,
      hash,
      allowPatch: (flags & 1) !== 0,
      quorum: c.uint.decode(state),
      signers: signerArray.decode(state),
      prologue: null
    }
  }
}

const manifest = exports.manifest = {
  preencode (state, m) {
    state.end++ // version
    if (m.version === 0) return manifestv0.preencode(state, m)

    state.end++ // flags
    hashes.preencode(state, m.hash)

    c.uint.preencode(state, m.quorum)
    signerArray.preencode(state, m.signers)
    if (m.prologue) prologue.preencode(state, m.prologue)
  },
  encode (state, m) {
    c.uint.encode(state, m.version)
    if (m.version === 0) return manifestv0.encode(state, m)

    c.uint.encode(state, (m.allowPatch ? 1 : 0) | (m.prologue ? 2 : 0) | (m.unencrypted ? 4 : 0))
    hashes.encode(state, m.hash)

    c.uint.encode(state, m.quorum)
    signerArray.encode(state, m.signers)
    if (m.prologue) prologue.encode(state, m.prologue)
  },
  decode (state) {
    const v = c.uint.decode(state)
    if (v === 0) return manifestv0.decode(state)
    if (v !== 1) throw new Error('Unknown version: ' + v)

    const flags = c.uint.decode(state)
    const hash = hashes.decode(state)
    const quorum = c.uint.decode(state)
    const signers = signerArray.decode(state)
    const unencrypted = (flags & 4) !== 0

    return {
      version: 1,
      hash,
      allowPatch: (flags & 1) !== 0,
      quorum,
      signers,
      prologue: (flags & 2) === 0 ? null : prologue.decode(state),
      unencrypted
    }
  }
}

const node = {
  preencode (state, n) {
    c.uint.preencode(state, n.index)
    c.uint.preencode(state, n.size)
    c.fixed32.preencode(state, n.hash)
  },
  encode (state, n) {
    c.uint.encode(state, n.index)
    c.uint.encode(state, n.size)
    c.fixed32.encode(state, n.hash)
  },
  decode (state) {
    return {
      index: c.uint.decode(state),
      size: c.uint.decode(state),
      hash: c.fixed32.decode(state)
    }
  }
}

const nodeArray = c.array(node)

const wire = exports.wire = {}

wire.handshake = {
  preencode (state, m) {
    c.uint.preencode(state, 1)
    c.fixed32.preencode(state, m.capability)
  },
  encode (state, m) {
    c.uint.encode(state, m.seeks ? 1 : 0)
    c.fixed32.encode(state, m.capability)
  },
  decode (state) {
    const flags = c.uint.decode(state)
    return {
      seeks: (flags & 1) !== 0,
      capability: c.fixed32.decode(state)
    }
  }
}

const requestBlock = {
  preencode (state, b) {
    c.uint.preencode(state, b.index)
    c.uint.preencode(state, b.nodes)
  },
  encode (state, b) {
    c.uint.encode(state, b.index)
    c.uint.encode(state, b.nodes)
  },
  decode (state) {
    return {
      index: c.uint.decode(state),
      nodes: c.uint.decode(state)
    }
  }
}

const requestSeek = {
  preencode (state, s) {
    c.uint.preencode(state, s.bytes)
    c.uint.preencode(state, s.padding)
  },
  encode (state, s) {
    c.uint.encode(state, s.bytes)
    c.uint.encode(state, s.padding)
  },
  decode (state) {
    return {
      bytes: c.uint.decode(state),
      padding: c.uint.decode(state)
    }
  }
}

const requestUpgrade = {
  preencode (state, u) {
    c.uint.preencode(state, u.start)
    c.uint.preencode(state, u.length)
  },
  encode (state, u) {
    c.uint.encode(state, u.start)
    c.uint.encode(state, u.length)
  },
  decode (state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

wire.request = {
  preencode (state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.id)
    c.uint.preencode(state, m.fork)

    if (m.block) requestBlock.preencode(state, m.block)
    if (m.hash) requestBlock.preencode(state, m.hash)
    if (m.seek) requestSeek.preencode(state, m.seek)
    if (m.upgrade) requestUpgrade.preencode(state, m.upgrade)
    if (m.priority) c.uint.preencode(state, m.priority)
  },
  encode (state, m) {
    const flags = (m.block ? 1 : 0) | (m.hash ? 2 : 0) | (m.seek ? 4 : 0) | (m.upgrade ? 8 : 0) | (m.manifest ? 16 : 0) | (m.priority ? 32 : 0)

    c.uint.encode(state, flags)
    c.uint.encode(state, m.id)
    c.uint.encode(state, m.fork)

    if (m.block) requestBlock.encode(state, m.block)
    if (m.hash) requestBlock.encode(state, m.hash)
    if (m.seek) requestSeek.encode(state, m.seek)
    if (m.upgrade) requestUpgrade.encode(state, m.upgrade)
    if (m.priority) c.uint.encode(state, m.priority)
  },
  decode (state) {
    const flags = c.uint.decode(state)

    return {
      id: c.uint.decode(state),
      fork: c.uint.decode(state),
      block: flags & 1 ? requestBlock.decode(state) : null,
      hash: flags & 2 ? requestBlock.decode(state) : null,
      seek: flags & 4 ? requestSeek.decode(state) : null,
      upgrade: flags & 8 ? requestUpgrade.decode(state) : null,
      manifest: (flags & 16) !== 0,
      priority: flags & 32 ? c.uint.decode(state) : 0
    }
  }
}

wire.cancel = {
  preencode (state, m) {
    c.uint.preencode(state, m.request)
  },
  encode (state, m) {
    c.uint.encode(state, m.request)
  },
  decode (state, m) {
    return {
      request: c.uint.decode(state)
    }
  }
}

const dataUpgrade = {
  preencode (state, u) {
    c.uint.preencode(state, u.start)
    c.uint.preencode(state, u.length)
    nodeArray.preencode(state, u.nodes)
    nodeArray.preencode(state, u.additionalNodes)
    c.optionalBuffer.preencode(state, u.signature)
  },
  encode (state, u) {
    c.uint.encode(state, u.start)
    c.uint.encode(state, u.length)
    nodeArray.encode(state, u.nodes)
    nodeArray.encode(state, u.additionalNodes)
    c.optionalBuffer.encode(state, u.signature)
  },
  decode (state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state),
      nodes: nodeArray.decode(state),
      additionalNodes: nodeArray.decode(state),
      signature: c.optionalBuffer.decode(state)
    }
  }
}

const dataSeek = {
  preencode (state, s) {
    c.uint.preencode(state, s.bytes)
    nodeArray.preencode(state, s.nodes)
  },
  encode (state, s) {
    c.uint.encode(state, s.bytes)
    nodeArray.encode(state, s.nodes)
  },
  decode (state) {
    return {
      bytes: c.uint.decode(state),
      nodes: nodeArray.decode(state)
    }
  }
}

const dataBlock = {
  preencode (state, b) {
    c.uint.preencode(state, b.index)
    c.optionalBuffer.preencode(state, b.value)
    nodeArray.preencode(state, b.nodes)
  },
  encode (state, b) {
    c.uint.encode(state, b.index)
    c.optionalBuffer.encode(state, b.value)
    nodeArray.encode(state, b.nodes)
  },
  decode (state) {
    return {
      index: c.uint.decode(state),
      value: c.optionalBuffer.decode(state) || EMPTY,
      nodes: nodeArray.decode(state)
    }
  }
}

const dataHash = {
  preencode (state, b) {
    c.uint.preencode(state, b.index)
    nodeArray.preencode(state, b.nodes)
  },
  encode (state, b) {
    c.uint.encode(state, b.index)
    nodeArray.encode(state, b.nodes)
  },
  decode (state) {
    return {
      index: c.uint.decode(state),
      nodes: nodeArray.decode(state)
    }
  }
}

wire.data = {
  preencode (state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.request)
    c.uint.preencode(state, m.fork)

    if (m.block) dataBlock.preencode(state, m.block)
    if (m.hash) dataHash.preencode(state, m.hash)
    if (m.seek) dataSeek.preencode(state, m.seek)
    if (m.upgrade) dataUpgrade.preencode(state, m.upgrade)
    if (m.manifest) manifest.preencode(state, m.manifest)
  },
  encode (state, m) {
    const flags = (m.block ? 1 : 0) | (m.hash ? 2 : 0) | (m.seek ? 4 : 0) | (m.upgrade ? 8 : 0) | (m.manifest ? 16 : 0)

    c.uint.encode(state, flags)
    c.uint.encode(state, m.request)
    c.uint.encode(state, m.fork)

    if (m.block) dataBlock.encode(state, m.block)
    if (m.hash) dataHash.encode(state, m.hash)
    if (m.seek) dataSeek.encode(state, m.seek)
    if (m.upgrade) dataUpgrade.encode(state, m.upgrade)
    if (m.manifest) manifest.encode(state, m.manifest)
  },
  decode (state) {
    const flags = c.uint.decode(state)

    return {
      request: c.uint.decode(state),
      fork: c.uint.decode(state),
      block: flags & 1 ? dataBlock.decode(state) : null,
      hash: flags & 2 ? dataHash.decode(state) : null,
      seek: flags & 4 ? dataSeek.decode(state) : null,
      upgrade: flags & 8 ? dataUpgrade.decode(state) : null,
      manifest: flags & 16 ? manifest.decode(state) : null
    }
  }
}

wire.noData = {
  preencode (state, m) {
    c.uint.preencode(state, m.request)
  },
  encode (state, m) {
    c.uint.encode(state, m.request)
  },
  decode (state, m) {
    return {
      request: c.uint.decode(state)
    }
  }
}

wire.want = {
  preencode (state, m) {
    c.uint.preencode(state, m.start)
    c.uint.preencode(state, m.length)
  },
  encode (state, m) {
    c.uint.encode(state, m.start)
    c.uint.encode(state, m.length)
  },
  decode (state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

wire.unwant = {
  preencode (state, m) {
    c.uint.preencode(state, m.start)
    c.uint.preencode(state, m.length)
  },
  encode (state, m) {
    c.uint.encode(state, m.start)
    c.uint.encode(state, m.length)
  },
  decode (state, m) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

wire.range = {
  preencode (state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.start)
    if (m.length !== 1) c.uint.preencode(state, m.length)
  },
  encode (state, m) {
    c.uint.encode(state, (m.drop ? 1 : 0) | (m.length === 1 ? 2 : 0))
    c.uint.encode(state, m.start)
    if (m.length !== 1) c.uint.encode(state, m.length)
  },
  decode (state) {
    const flags = c.uint.decode(state)

    return {
      drop: (flags & 1) !== 0,
      start: c.uint.decode(state),
      length: (flags & 2) !== 0 ? 1 : c.uint.decode(state)
    }
  }
}

wire.bitfield = {
  preencode (state, m) {
    c.uint.preencode(state, m.start)
    c.uint32array.preencode(state, m.bitfield)
  },
  encode (state, m) {
    c.uint.encode(state, m.start)
    c.uint32array.encode(state, m.bitfield)
  },
  decode (state, m) {
    return {
      start: c.uint.decode(state),
      bitfield: c.uint32array.decode(state)
    }
  }
}

wire.sync = {
  preencode (state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.fork)
    c.uint.preencode(state, m.length)
    c.uint.preencode(state, m.remoteLength)
  },
  encode (state, m) {
    c.uint.encode(state, (m.canUpgrade ? 1 : 0) | (m.uploading ? 2 : 0) | (m.downloading ? 4 : 0) | (m.hasManifest ? 8 : 0))
    c.uint.encode(state, m.fork)
    c.uint.encode(state, m.length)
    c.uint.encode(state, m.remoteLength)
  },
  decode (state) {
    const flags = c.uint.decode(state)

    return {
      fork: c.uint.decode(state),
      length: c.uint.decode(state),
      remoteLength: c.uint.decode(state),
      canUpgrade: (flags & 1) !== 0,
      uploading: (flags & 2) !== 0,
      downloading: (flags & 4) !== 0,
      hasManifest: (flags & 8) !== 0
    }
  }
}

wire.reorgHint = {
  preencode (state, m) {
    c.uint.preencode(state, m.from)
    c.uint.preencode(state, m.to)
    c.uint.preencode(state, m.ancestors)
  },
  encode (state, m) {
    c.uint.encode(state, m.from)
    c.uint.encode(state, m.to)
    c.uint.encode(state, m.ancestors)
  },
  decode (state) {
    return {
      from: c.uint.encode(state),
      to: c.uint.encode(state),
      ancestors: c.uint.encode(state)
    }
  }
}

wire.extension = {
  preencode (state, m) {
    c.string.preencode(state, m.name)
    c.raw.preencode(state, m.message)
  },
  encode (state, m) {
    c.string.encode(state, m.name)
    c.raw.encode(state, m.message)
  },
  decode (state) {
    return {
      name: c.string.decode(state),
      message: c.raw.decode(state)
    }
  }
}

const keyValue = {
  preencode (state, p) {
    c.string.preencode(state, p.key)
    c.optionalBuffer.preencode(state, p.value)
  },
  encode (state, p) {
    c.string.encode(state, p.key)
    c.optionalBuffer.encode(state, p.value)
  },
  decode (state) {
    return {
      key: c.string.decode(state),
      value: c.optionalBuffer.decode(state)
    }
  }
}

const treeUpgrade = {
  preencode (state, u) {
    c.uint.preencode(state, u.fork)
    c.uint.preencode(state, u.ancestors)
    c.uint.preencode(state, u.length)
    c.optionalBuffer.preencode(state, u.signature)
  },
  encode (state, u) {
    c.uint.encode(state, u.fork)
    c.uint.encode(state, u.ancestors)
    c.uint.encode(state, u.length)
    c.optionalBuffer.encode(state, u.signature)
  },
  decode (state) {
    return {
      fork: c.uint.decode(state),
      ancestors: c.uint.decode(state),
      length: c.uint.decode(state),
      signature: c.optionalBuffer.decode(state)
    }
  }
}

const bitfieldUpdate = { // TODO: can maybe be folded into a HAVE later on with the most recent spec
  preencode (state, b) {
    state.end++ // flags
    c.uint.preencode(state, b.start)
    c.uint.preencode(state, b.length)
  },
  encode (state, b) {
    state.buffer[state.start++] = b.drop ? 1 : 0
    c.uint.encode(state, b.start)
    c.uint.encode(state, b.length)
  },
  decode (state) {
    const flags = c.uint.decode(state)
    return {
      drop: (flags & 1) !== 0,
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

const oplog = exports.oplog = {}

oplog.entry = {
  preencode (state, m) {
    state.end++ // flags
    if (m.userData) keyValue.preencode(state, m.userData)
    if (m.treeNodes) nodeArray.preencode(state, m.treeNodes)
    if (m.treeUpgrade) treeUpgrade.preencode(state, m.treeUpgrade)
    if (m.bitfield) bitfieldUpdate.preencode(state, m.bitfield)
  },
  encode (state, m) {
    const s = state.start++
    let flags = 0

    if (m.userData) {
      flags |= 1
      keyValue.encode(state, m.userData)
    }
    if (m.treeNodes) {
      flags |= 2
      nodeArray.encode(state, m.treeNodes)
    }
    if (m.treeUpgrade) {
      flags |= 4
      treeUpgrade.encode(state, m.treeUpgrade)
    }
    if (m.bitfield) {
      flags |= 8
      bitfieldUpdate.encode(state, m.bitfield)
    }

    state.buffer[s] = flags
  },
  decode (state) {
    const flags = c.uint.decode(state)
    return {
      userData: (flags & 1) !== 0 ? keyValue.decode(state) : null,
      treeNodes: (flags & 2) !== 0 ? nodeArray.decode(state) : null,
      treeUpgrade: (flags & 4) !== 0 ? treeUpgrade.decode(state) : null,
      bitfield: (flags & 8) !== 0 ? bitfieldUpdate.decode(state) : null
    }
  }
}

const keyPair = {
  preencode (state, kp) {
    c.optionalBuffer.preencode(state, kp.publicKey)
    c.optionalBuffer.preencode(state, kp.secretKey)
  },
  encode (state, kp) {
    c.optionalBuffer.encode(state, kp.publicKey)
    c.optionalBuffer.encode(state, kp.secretKey)
  },
  decode (state) {
    return {
      publicKey: c.optionalBuffer.decode(state),
      secretKey: c.optionalBuffer.decode(state)
    }
  }
}

const reorgHint = {
  preencode (state, r) {
    c.uint.preencode(state, r.from)
    c.uint.preencode(state, r.to)
    c.uint.preencode(state, r.ancestors)
  },
  encode (state, r) {
    c.uint.encode(state, r.from)
    c.uint.encode(state, r.to)
    c.uint.encode(state, r.ancestors)
  },
  decode (state) {
    return {
      from: c.uint.decode(state),
      to: c.uint.decode(state),
      ancestors: c.uint.decode(state)
    }
  }
}

const reorgHintArray = c.array(reorgHint)

const hints = {
  preencode (state, h) {
    reorgHintArray.preencode(state, h.reorgs)
    c.uint.preencode(state, h.contiguousLength)
  },
  encode (state, h) {
    reorgHintArray.encode(state, h.reorgs)
    c.uint.encode(state, h.contiguousLength)
  },
  decode (state) {
    return {
      reorgs: reorgHintArray.decode(state),
      contiguousLength: state.start < state.end ? c.uint.decode(state) : 0
    }
  }
}

const treeHeader = {
  preencode (state, t) {
    c.uint.preencode(state, t.fork)
    c.uint.preencode(state, t.length)
    c.optionalBuffer.preencode(state, t.rootHash)
    c.optionalBuffer.preencode(state, t.signature)
  },
  encode (state, t) {
    c.uint.encode(state, t.fork)
    c.uint.encode(state, t.length)
    c.optionalBuffer.encode(state, t.rootHash)
    c.optionalBuffer.encode(state, t.signature)
  },
  decode (state) {
    return {
      fork: c.uint.decode(state),
      length: c.uint.decode(state),
      rootHash: c.optionalBuffer.decode(state),
      signature: c.optionalBuffer.decode(state)
    }
  }
}

const types = {
  preencode (state, t) {
    c.string.preencode(state, t.tree)
    c.string.preencode(state, t.bitfield)
    c.string.preencode(state, t.signer)
  },
  encode (state, t) {
    c.string.encode(state, t.tree)
    c.string.encode(state, t.bitfield)
    c.string.encode(state, t.signer)
  },
  decode (state) {
    return {
      tree: c.string.decode(state),
      bitfield: c.string.decode(state),
      signer: c.string.decode(state)
    }
  }
}

const externalHeader = {
  preencode (state, m) {
    c.uint.preencode(state, m.start)
    c.uint.preencode(state, m.length)
  },
  encode (state, m) {
    c.uint.encode(state, m.start)
    c.uint.encode(state, m.length)
  },
  decode (state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

const keyValueArray = c.array(keyValue)

oplog.header = {
  preencode (state, h) {
    state.end += 2 // version + flags
    if (h.external) {
      externalHeader.preencode(state, h.external)
      return
    }
    c.fixed32.preencode(state, h.key)
    if (h.manifest) manifest.preencode(state, h.manifest)
    if (h.keyPair) keyPair.preencode(state, h.keyPair)
    keyValueArray.preencode(state, h.userData)
    treeHeader.preencode(state, h.tree)
    hints.preencode(state, h.hints)
  },
  encode (state, h) {
    c.uint.encode(state, 1)
    if (h.external) {
      c.uint.encode(state, 1) // ONLY set the first big for clarity
      externalHeader.encode(state, h.external)
      return
    }
    c.uint.encode(state, (h.manifest ? 2 : 0) | (h.keyPair ? 4 : 0))
    c.fixed32.encode(state, h.key)
    if (h.manifest) manifest.encode(state, h.manifest)
    if (h.keyPair) keyPair.encode(state, h.keyPair)
    keyValueArray.encode(state, h.userData)
    treeHeader.encode(state, h.tree)
    hints.encode(state, h.hints)
  },
  decode (state) {
    const version = c.uint.decode(state)

    if (version > 1) {
      throw new Error('Invalid header version. Expected <= 1, got ' + version)
    }

    if (version === 0) {
      const old = {
        types: types.decode(state),
        userData: keyValueArray.decode(state),
        tree: treeHeader.decode(state),
        signer: keyPair.decode(state),
        hints: hints.decode(state)
      }

      return {
        external: null,
        key: old.signer.publicKey,
        manifest: {
          version: 0,
          hash: old.types.tree,
          allowPatch: false,
          quorum: 1,
          signers: [{
            signature: old.types.signer,
            namespace: DEFAULT_NAMESPACE,
            publicKey: old.signer.publicKey
          }],
          prologue: null
        },
        keyPair: old.signer.secretKey ? old.signer : null,
        userData: old.userData,
        tree: old.tree,
        hints: old.hints
      }
    }

    const flags = c.uint.decode(state)

    if (flags & 1) {
      return {
        external: externalHeader.decode(state),
        key: null,
        manifest: null,
        keyPair: null,
        userData: null,
        tree: null,
        hints: null
      }
    }

    return {
      external: null,
      key: c.fixed32.decode(state),
      manifest: (flags & 2) !== 0 ? manifest.decode(state) : null,
      keyPair: (flags & 4) !== 0 ? keyPair.decode(state) : null,
      userData: keyValueArray.decode(state),
      tree: treeHeader.decode(state),
      hints: hints.decode(state)
    }
  }
}

const uintArray = c.array(c.uint)

const multisigInput = {
  preencode (state, inp) {
    c.uint.preencode(state, inp.signer)
    c.fixed64.preencode(state, inp.signature)
    c.uint.preencode(state, inp.patch)
  },
  encode (state, inp) {
    c.uint.encode(state, inp.signer)
    c.fixed64.encode(state, inp.signature)
    c.uint.encode(state, inp.patch)
  },
  decode (state) {
    return {
      signer: c.uint.decode(state),
      signature: c.fixed64.decode(state),
      patch: c.uint.decode(state)
    }
  }
}

const patchEncodingv0 = {
  preencode (state, n) {
    c.uint.preencode(state, n.start)
    c.uint.preencode(state, n.length)
    uintArray.preencode(state, n.nodes)
  },
  encode (state, n) {
    c.uint.encode(state, n.start)
    c.uint.encode(state, n.length)
    uintArray.encode(state, n.nodes)
  },
  decode (state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state),
      nodes: uintArray.decode(state)
    }
  }
}

const multisigInputv0 = {
  preencode (state, n) {
    state.end++
    c.uint.preencode(state, n.signer)
    c.fixed64.preencode(state, n.signature)
    if (n.patch) patchEncodingv0.preencode(state, n.patch)
  },
  encode (state, n) {
    c.uint.encode(state, n.patch ? 1 : 0)
    c.uint.encode(state, n.signer)
    c.fixed64.encode(state, n.signature)
    if (n.patch) patchEncodingv0.encode(state, n.patch)
  },
  decode (state) {
    const flags = c.uint.decode(state)
    return {
      signer: c.uint.decode(state),
      signature: c.fixed64.decode(state),
      patch: (flags & 1) ? patchEncodingv0.decode(state) : null
    }
  }
}

const multisigInputArrayv0 = c.array(multisigInputv0)
const multisigInputArray = c.array(multisigInput)

const compactNode = {
  preencode (state, n) {
    c.uint.preencode(state, n.index)
    c.uint.preencode(state, n.size)
    c.fixed32.preencode(state, n.hash)
  },
  encode (state, n) {
    c.uint.encode(state, n.index)
    c.uint.encode(state, n.size)
    c.fixed32.encode(state, n.hash)
  },
  decode (state) {
    return {
      index: c.uint.decode(state),
      size: c.uint.decode(state),
      hash: c.fixed32.decode(state)
    }
  }
}

const compactNodeArray = c.array(compactNode)

exports.multiSignaturev0 = {
  preencode (state, s) {
    multisigInputArrayv0.preencode(state, s.proofs)
    compactNodeArray.preencode(state, s.patch)
  },
  encode (state, s) {
    multisigInputArrayv0.encode(state, s.proofs)
    compactNodeArray.encode(state, s.patch)
  },
  decode (state) {
    return {
      proofs: multisigInputArrayv0.decode(state),
      patch: compactNodeArray.decode(state)
    }
  }
}

exports.multiSignature = {
  preencode (state, s) {
    multisigInputArray.preencode(state, s.proofs)
    compactNodeArray.preencode(state, s.patch)
  },
  encode (state, s) {
    multisigInputArray.encode(state, s.proofs)
    compactNodeArray.encode(state, s.patch)
  },
  decode (state) {
    return {
      proofs: multisigInputArray.decode(state),
      patch: compactNodeArray.decode(state)
    }
  }
}
const c = require('compact-encoding')
const schema = require('../../encoding/spec/hyperschema')
const { core: coreKey } = require('../../lib/keys.js')
const View = require('../../lib/view.js')

const CORE_AUTH = schema.getEncoding('@core/auth')

const { CorestoreRX, CorestoreTX } = require('../../lib/tx.js')

async function core (core, { version, dryRun = false } = {}) {
  if (dryRun) return // dryRun mode not supported atm

  const rx = core.db.read({ autoDestroy: true })
  const storedAuthPromise = rx.get(coreKey.auth(core.core.corePointer))

  rx.tryFlush()

  const storedAuth = await storedAuthPromise
  if (!storedAuth) return

  const auth = c.decode(CORE_AUTH, storedAuth)
  await commitCoreMigration(auth, core, version)
}

module.exports = { core }

async function commitCoreMigration (auth, core, version) {
  const view = new View()
  const rx = new CorestoreRX(core.db, view)

  const storeCorePromise = rx.getCore(auth.discoveryKey)
  rx.tryFlush()

  const storeCore = await storeCorePromise

  storeCore.version = version

  const tx = new CorestoreTX(view)
  tx.putCore(auth.discoveryKey, storeCore)
  tx.apply()

  await View.flush(view.changes, core.db)
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "hypercore-storage",
  "version": "3.2.0",
  "main": "index.js",
  "files": [
    "index.js",
    "lib/*.js",
    "encoding/*",
    "migrations/0/*.js",
    "migrations/1/*.js"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:bare": "brittle-bare test/all.js",
    "test:generate": "brittle -r test/all.js test/*.js",
    "test:node": "brittle-node test/all.js"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "description": "Storage engine for Hypercore",
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "fs/*": {
      "bare": "bare-fs/*",
      "default": "fs/*"
    },
    "os": {
      "bare": "bare-os",
      "default": "os"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    }
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/hypercore-storage.git"
  },
  "bugs": {
    "url": "https://github.com/holepunchto/hypercore-storage/issues"
  },
  "homepage": "https://github.com/holepunchto/hypercore-storage#readme",
  "dependencies": {
    "b4a": "^1.6.7",
    "bare-path": "^3.0.0",
    "compact-encoding": "^3.1.0",
    "device-file": "^2.1.2",
    "flat-tree": "^1.12.1",
    "hypercore-crypto": "^3.4.2",
    "hyperschema": "^1.21.0",
    "index-encoder": "^3.3.2",
    "resolve-reject-promise": "^1.0.0",
    "rocksdb-native": "^3.11.0",
    "scope-lock": "^1.2.4",
    "streamx": "^2.21.1",
    "xache": "^1.2.1"
  },
  "devDependencies": {
    "bare-os": "^3.9.1",
    "brittle": "^3.7.0",
    "hypercore-storage-2.9.0": "npm:hypercore-storage@^2.9.0",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "test-tmp": "^1.3.1"
  }
}
const { EventEmitter } = require('events')
const isOptions = require('is-options')
const crypto = require('hypercore-crypto')
const CoreStorage = require('hypercore-storage')
const c = require('compact-encoding')
const b4a = require('b4a')
const NoiseSecretStream = require('@hyperswarm/secret-stream')
const Protomux = require('protomux')
const id = require('hypercore-id-encoding')
const safetyCatch = require('safety-catch')
const unslab = require('unslab')
const flat = require('flat-tree')
const assert = require('nanoassert')

const { SMALL_WANTS } = require('./lib/feature-flags')
const { UPDATE_COMPAT } = require('./lib/wants')
const MarkBitfield = require('./lib/mark-bitfield')

const inspect = require('./lib/inspect')
const Core = require('./lib/core')
const Info = require('./lib/info')
const Download = require('./lib/download')
const DefaultEncryption = require('./lib/default-encryption')
const caps = require('./lib/caps')
const Replicator = require('./lib/replicator')
const { manifestHash, createManifest } = require('./lib/verifier')
const { ReadStream, WriteStream, ByteStream } = require('./lib/streams')
const { MerkleTree } = require('./lib/merkle-tree')
const { proof, verify } = require('./lib/fully-remote-proof')
const {
  ASSERTION,
  BAD_ARGUMENT,
  SESSION_CLOSED,
  SESSION_MOVED,
  SESSION_NOT_WRITABLE,
  SNAPSHOT_NOT_AVAILABLE,
  DECODING_ERROR,
  REQUEST_CANCELLED
} = require('hypercore-errors')

// Hypercore actually does not have any notion of max/min block sizes
// but we enforce 15mb to ensure smooth replication (each block is transmitted atomically)
const MAX_SUGGESTED_BLOCK_SIZE = 15 * 1024 * 1024

class Hypercore extends EventEmitter {
  constructor(storage, key, opts) {
    super()

    if (isOptions(storage) && !storage.db) {
      opts = storage
      storage = null
      key = opts.key || null
    } else if (isOptions(key)) {
      opts = key
      key = opts.key || null
    }

    if (key && typeof key === 'string') key = id.decode(key)
    if (!opts) opts = {}

    if (!storage) storage = opts.storage

    this.core = null
    this.state = null
    this.encryption = null
    this.extensions = new Map()

    this.valueEncoding = null
    this.encodeBatch = null
    this.activeRequests = []
    this.sessions = null
    this.ongc = null

    this.keyPair = opts.keyPair || null
    this.readable = true
    this.writable = false
    this.exclusive = false
    this.opened = false
    this.closed = false
    this.weak = !!opts.weak
    this.snapshotted = !!opts.snapshot
    this.onseq = opts.onseq || null
    this.onwait = opts.onwait || null
    this.wait = opts.wait !== false
    this.timeout = opts.timeout || 0
    this.preload = null
    this.closing = null
    this.opening = null

    this._readonly = opts.writable === false
    this._preappend = preappend.bind(this)
    this._snapshot = null
    this._findingPeers = 0
    this._active = opts.weak ? !!opts.active : opts.active !== false

    this.waits = 0

    // Mark & Sweep GC
    this._marking = false
    this._marks = null

    this._sessionIndex = -1
    this._stateIndex = -1 // maintained by session state
    this._monitorIndex = -1 // maintained by replication state

    this.opening = this._open(storage, key, opts)
    this.opening.catch(safetyCatch)

    this.on('newListener', maybeAddMonitor)
  }

  [Symbol.for('nodejs.util.inspect.custom')](depth, opts) {
    return inspect(this, depth, opts)
  }

  static MAX_SUGGESTED_BLOCK_SIZE = MAX_SUGGESTED_BLOCK_SIZE

  static DefaultEncryption = DefaultEncryption

  static SMALL_WANTS = SMALL_WANTS

  static enable(flag) {
    const enableCompat = (flag & SMALL_WANTS) === 0
    UPDATE_COMPAT(enableCompat)
  }

  static setRecoveryPeers(peers) {
    Core.setRecoveryPeers(peers)
  }

  static key(manifest, { compat, version, namespace } = {}) {
    if (b4a.isBuffer(manifest)) {
      manifest = { version, signers: [{ publicKey: manifest, namespace }] }
    }
    return compat ? manifest.signers[0].publicKey : manifestHash(createManifest(manifest))
  }

  static discoveryKey(key) {
    return crypto.discoveryKey(key)
  }

  static blockEncryptionKey(key, encryptionKey) {
    return DefaultEncryption.blockEncryptionKey(key, encryptionKey)
  }

  static getProtocolMuxer(stream) {
    return stream.noiseStream.userData
  }

  static createCore(storage, opts) {
    return new Core(Hypercore.defaultStorage(storage), { autoClose: false, ...opts })
  }

  static createProtocolStream(isInitiator, opts = {}) {
    let outerStream = Protomux.isProtomux(isInitiator)
      ? isInitiator.stream
      : isStream(isInitiator)
        ? isInitiator
        : opts.stream

    let noiseStream = null

    if (outerStream) {
      noiseStream = outerStream.noiseStream
    } else {
      noiseStream = new NoiseSecretStream(isInitiator, null, opts)
      outerStream = noiseStream.rawStream
    }
    if (!noiseStream) throw BAD_ARGUMENT('Invalid stream', this.discoveryKey)

    if (!noiseStream.userData) {
      const protocol = Protomux.from(noiseStream)

      if (opts.keepAlive !== false && noiseStream.keepAlive === 0) {
        noiseStream.setKeepAlive(5000)
      }
      noiseStream.userData = protocol
    }

    if (opts.ondiscoverykey) {
      const ondiscoverykey = createDiscoveryKeyHandler(opts.ondiscoverykey)
      noiseStream.userData.pair({ protocol: 'hypercore/alpha' }, ondiscoverykey)
    }

    return outerStream
  }

  static defaultStorage(storage, opts = {}) {
    if (CoreStorage.isCoreStorage(storage)) return storage

    const directory = storage
    return new CoreStorage(directory, opts)
  }

  static clearRequests(session, err) {
    Replicator.clearRequests(session, err)
  }

  static destroyRequests(session, err) {
    if (isRequestsDestroyed(session)) return
    Replicator.clearRequests(session, err)
    session.push(null) // mark as dead
  }

  static async treeHashFromStorage(session, length = session.length) {
    const roots = await MerkleTree.getRoots(session.state, length)
    return crypto.tree(roots)
  }

  snapshot(opts) {
    return this.session({ ...opts, snapshot: true })
  }

  compact() {
    return this.core.compact()
  }

  session(opts = {}) {
    if (this.closing) {
      // This makes the closing logic a lot easier. If this turns out to be a problem
      // in practice, open an issue and we'll try to make a solution for it.
      throw SESSION_CLOSED('Cannot make sessions on a closing core', this.discoveryKey)
    }
    if (opts.checkout !== undefined && !opts.name && !opts.atom) {
      throw ASSERTION('Checkouts are only supported on atoms or named sessions', this.discoveryKey)
    }

    const wait = opts.wait === false ? false : this.wait
    const writable = opts.writable === undefined ? !this._readonly : opts.writable === true
    const onwait = opts.onwait === undefined ? this.onwait : opts.onwait
    const onseq = opts.onseq === undefined ? this.onseq : opts.onseq
    const timeout = opts.timeout === undefined ? this.timeout : opts.timeout
    const weak = opts.weak === undefined ? this.weak : opts.weak
    const marking = this._marking
    const marks = this._marks
    const Clz = opts.class || Hypercore
    const s = new Clz(null, this.key, {
      ...opts,
      wait,
      onwait,
      onseq,
      timeout,
      writable,
      weak,
      parent: this
    })
    s._marking = marking
    s._marks = marks

    return s
  }

  async setEncryptionKey(key, opts) {
    if (!this.opened) await this.opening
    const encryption = this._getEncryptionProvider({ key, block: !!(opts && opts.block) })
    return this.setEncryption(encryption)
  }

  async setEncryption(encryption) {
    if (!this.opened) await this.opening

    if (encryption === null) {
      this.encryption = encryption
      return
    }

    if (!isEncryptionProvider(encryption)) {
      throw ASSERTION('Provider does not satisfy HypercoreEncryption interface', this.discoveryKey)
    }

    this.encryption = encryption
  }

  async setGroup(topic) {
    if (!this.opened) await this.opening
    return this.core.setGroup(topic)
  }

  setKeyPair(keyPair) {
    this.keyPair = keyPair
  }

  setActive(bool) {
    const active = !!bool
    if (active === this._active || this.closing) return
    this._active = active
    if (!this.opened) return
    this.core.replicator.updateActivity(this._active ? 1 : -1)
  }

  async _open(storage, key, opts) {
    const preload = opts.preload || (opts.parent && opts.parent.preload)

    if (preload) {
      this.sessions = [] // in case someone looks at it like with peers
      this.preload = preload
      opts = { ...opts, ...(await this.preload) }
      this.preload = null
    }

    const parent = opts.parent || null
    const core = opts.core || (parent && parent.core)
    const sessions = opts.sessions || (parent && parent.sessions)
    const ongc = opts.ongc || (parent && parent.ongc)

    if (core) this.core = core
    if (ongc) this.ongc = ongc
    if (sessions) this.sessions = sessions

    if (this.sessions === null) this.sessions = []
    this._sessionIndex = this.sessions.push(this) - 1

    if (this.core === null) initOnce(this, storage, key, opts)
    if (this._monitorIndex === -2) this.core.addMonitor(this)

    try {
      await this._openSession(opts)
    } catch (err) {
      if (this.core.autoClose && this.core.hasSession() === false) await this.core.close()

      if (this.exclusive) this.core.unlockExclusive()

      this.core.removeMonitor(this)
      this._removeSession()

      if (this.state !== null) this.state.removeSession(this)

      this.closed = true
      this.emit('close')
      throw err
    }

    // Setup automatic recovery if in repair mode
    if (this.core._repairMode) {
      const recoverTreeNodeFromPeersBound = this.recoverTreeNodeFromPeers.bind(this)
      this.once('repaired', () => {
        this.off('peer-add', recoverTreeNodeFromPeersBound)
      })
      this.on('peer-add', recoverTreeNodeFromPeersBound)
    }

    this.emit('ready')

    // if we are a weak session the core might have closed...
    if (this.core.closing) this.close().catch(safetyCatch)
  }

  _removeSession() {
    if (this._sessionIndex === -1) return
    const head = this.sessions.pop()
    if (head !== this) this.sessions[(head._sessionIndex = this._sessionIndex)] = head
    this._sessionIndex = -1
    if (this.ongc !== null) this.ongc(this)
  }

  async _openSession(opts) {
    if (this.core.opened === false) await this.core.ready()

    if (this.keyPair === null) this.keyPair = opts.keyPair || this.core.header.keyPair

    const parent = opts.parent || null
    if (parent && parent.encryption) this.encryption = parent.encryption

    const e = getEncryptionOption(opts)
    if (!this.encryption) this.encryption = this._getEncryptionProvider(e)

    this.writable = this._isWritable()

    if (opts.valueEncoding) {
      this.valueEncoding = c.from(opts.valueEncoding)
    }
    if (opts.encodeBatch) {
      this.encodeBatch = opts.encodeBatch
    }

    // one session sets for pushOnly for all
    if (opts.pushOnly === true) {
      this.core.replicator.setPushOnly(true)
    }

    if (parent) {
      if (parent._stateIndex === -1) await parent.ready()
      if (!this.keyPair) this.keyPair = parent.keyPair

      const ps = parent.state

      if (ps) {
        const shouldSnapshot = this.snapshotted && !ps.isSnapshot()
        this.state = shouldSnapshot ? await ps.snapshot() : ps.ref()
      }

      if (this.snapshotted && this.core && !this._snapshot) {
        this._updateSnapshot()
      }
    }

    if (opts.exclusive && opts.writable !== false) {
      this.exclusive = true
      await this.core.lockExclusive()
    }

    const parentState = parent ? parent.state : this.core.state
    const checkout = opts.checkout === undefined ? -1 : opts.checkout
    const state = this.state

    if (opts.atom) {
      this.state = await parentState.createSession(null, false, opts.atom)
      if (state) state.unref()
    } else if (opts.name) {
      // todo: need to make named sessions safe before ready
      // atm we always copy the state in passCapabilities
      this.state = await parentState.createSession(opts.name, !!opts.overwrite, null)
      if (state) state.unref() // ref'ed above in setup session
    }

    if (this.state && checkout !== -1) {
      if (!opts.name && !opts.atom) {
        throw ASSERTION('Checkouts must be named or atomized', this.discoveryKey)
      }
      if (checkout > this.state.length) {
        throw ASSERTION(
          `Invalid checkout ${checkout} for ${opts.name}, length is ${this.state.length}`,
          this.discoveryKey
        )
      }
      if (this.state.prologue && checkout < this.state.prologue.length) {
        throw ASSERTION(
          `Invalid checkout ${checkout} for ${opts.name}, prologue length is ${this.state.prologue.length}`,
          this.discoveryKey
        )
      }
      if (checkout < this.state.length) await this.state.truncate(checkout, this.fork)
    }

    if (this.state === null) {
      this.state = this.core.state.ref()
    }

    this.writable = this._isWritable()

    if (this.snapshotted && this.core) this._updateSnapshot()

    this.state.addSession(this)
    // TODO: we need to rework the core reference flow, as the state and session do not always agree now due to moveTo
    this.core = this.state.core // in case it was wrong...

    if (opts.userData) {
      const tx = this.state.storage.write()
      for (const [key, value] of Object.entries(opts.userData)) {
        tx.putUserData(key, value)
      }
      await tx.flush()
    }

    if (opts.manifest && !this.core.header.manifest) {
      await this.core.setManifest(createManifest(opts.manifest))
    }

    this.core.replicator.updateActivity(this._active ? 1 : 0)

    this.opened = true
  }

  get replicator() {
    return this.core === null ? null : this.core.replicator
  }

  _getSnapshot() {
    return {
      length: this.state.length,
      byteLength: this.state.byteLength,
      fork: this.state.fork
    }
  }

  _updateSnapshot() {
    const prev = this._snapshot
    const next = (this._snapshot = this._getSnapshot())

    if (!prev) return true
    return prev.length !== next.length || prev.fork !== next.fork
  }

  _isWritable() {
    if (this._readonly) return false
    if (this.state && !this.state.isDefault()) return true
    return !!(this.keyPair && this.keyPair.secretKey)
  }

  close({ error } = {}) {
    if (this.closing) return this.closing

    this.closing = this._close(error || null)
    return this.closing
  }

  clearRequests(activeRequests, error) {
    if (!activeRequests.length) return
    if (this.core) this.core.replicator.clearRequests(activeRequests, error)
  }

  async _close(error) {
    if (this.opened === false) {
      try {
        await this.opening
      } catch (err) {
        if (!this.closed) throw err
      }
    }

    if (this.closed === true) return

    this.core.removeMonitor(this)
    this.state.removeSession(this)
    this._removeSession()

    this.readable = false
    this.writable = false
    this.opened = false

    const gc = []
    for (const ext of this.extensions.values()) {
      if (ext.session === this) gc.push(ext)
    }
    for (const ext of gc) ext.destroy()

    this.core.replicator.findingPeers -= this._findingPeers
    this.core.replicator.clearRequests(this.activeRequests, error)
    this.core.replicator.updateActivity(this._active ? -1 : 0)

    this._findingPeers = 0

    this.state.unref()

    if (this.exclusive) this.core.unlockExclusive()

    if (this.core.hasSession()) {
      // emit "fake" close as this is a session
      this.closed = true
      this.emit('close')
      return
    }

    if (this.core.autoClose) await this.core.close()

    this.closed = true
    this.emit('close')
  }

  async commit(session, opts) {
    await this.ready()
    await session.ready()

    return this.state.commit(session.state, { keyPair: this.keyPair, ...opts })
  }

  replicate(isInitiator, opts = {}) {
    // Only limitation here is that ondiscoverykey doesn't work atm when passing a muxer directly,
    // because it doesn't really make a lot of sense.
    if (Protomux.isProtomux(isInitiator)) return this._attachToMuxer(isInitiator)

    // if same stream is passed twice, ignore the 2nd one before we make sessions etc
    if (isStream(isInitiator) && this._isAttached(isInitiator)) return isInitiator

    const protocolStream = Hypercore.createProtocolStream(isInitiator, opts)
    const noiseStream = protocolStream.noiseStream
    const protocol = noiseStream.userData

    this._attachToMuxer(protocol)

    return protocolStream
  }

  _isAttached(stream) {
    return (
      stream.userData &&
      this.core &&
      this.core.replicator &&
      this.core.replicator.attached(stream.userData)
    )
  }

  _attachToMuxer(mux) {
    if (this.opened) {
      this.core.replicator.attachTo(mux)
    } else {
      this.opening.then(() => this.core.replicator.attachTo(mux), mux.destroy.bind(mux))
    }

    return mux
  }

  get id() {
    return this.core === null ? null : this.core.id
  }

  get key() {
    return this.core === null ? null : this.core.key
  }

  get discoveryKey() {
    return this.core === null ? null : this.core.discoveryKey
  }

  get manifest() {
    return this.core === null ? null : this.core.manifest
  }

  get length() {
    if (this._snapshot) return this._snapshot.length
    return this.opened === false ? 0 : this.state.length
  }

  get signedLength() {
    return this.opened === false ? 0 : this.state.signedLength()
  }

  /**
   * Deprecated. Use `const { byteLength } = await core.info()`.
   */
  get byteLength() {
    if (this.opened === false) return 0
    if (this._snapshot) return this._snapshot.byteLength
    return this.state.byteLength - this.state.length * this.padding
  }

  get remoteContiguousLength() {
    if (this.opened === false) return 0
    return Math.min(this.core.state.length, this.core.header.hints.remoteContiguousLength)
  }

  get contiguousLength() {
    if (this.opened === false) return 0
    return Math.min(this.core.state.length, this.core.header.hints.contiguousLength)
  }

  get contiguousByteLength() {
    return 0
  }

  get fork() {
    if (this.opened === false) return 0
    return this.state.fork
  }

  get padding() {
    if (this.encryption && this.key && this.manifest) {
      return this.encryption.padding(this.core, this.length)
    }

    return 0
  }

  get peers() {
    return this.opened === false ? [] : this.core.replicator.peers
  }

  get globalCache() {
    return this.opened === false ? null : this.core.globalCache
  }

  get recovering() {
    return this.opened === false ? 0 : this.core.header.hints.recovering
  }

  ready() {
    return this.opening
  }

  async recover() {
    if (this.opened === false) await this.opening
    return this.state.waitForRecovery()
  }

  async setUserData(key, value) {
    if (this.opened === false) await this.opening
    const existing = await this.getUserData(key)
    if (existing && b4a.isBuffer(value) && b4a.equals(existing, value)) return
    await this.state.setUserData(key, value)
  }

  async getUserData(key) {
    if (this.opened === false) await this.opening
    const batch = this.state.storage.read()
    const p = batch.getUserData(key)
    batch.tryFlush()
    return p
  }

  transferSession(core) {
    // todo: validate we can move

    if (this.weak === false) {
      this.core.activeSessions--
      core.activeSessions++
    }

    if (this._monitorIndex >= 0) {
      this.core.removeMonitor(this)
      core.addMonitor(this)
    }

    const old = this.core

    this.core = core

    old.replicator.clearRequests(this.activeRequests, SESSION_MOVED())

    this.emit('migrate', this.key)
  }

  findingPeers() {
    this._findingPeers++
    if (this.core !== null && !this.closing) this.core.replicator.findingPeers++

    let once = true

    return () => {
      if (this.closing || !once) return
      once = false
      this._findingPeers--
      if (this.core !== null && --this.core.replicator.findingPeers === 0) {
        this.core.replicator.queueUpdateAll()
      }
    }
  }

  async info(opts) {
    if (this.opened === false) await this.opening

    return Info.from(this, opts)
  }

  async update(opts) {
    if (this.opened === false) await this.opening
    if (this.closing !== null) return false
    if (this.snapshotted) return false

    if (this.writable && (!opts || opts.force !== true)) return false

    const remoteWait = this._shouldWait(opts, this.core.replicator.findingPeers > 0)

    let upgraded = false

    if (await this.core.replicator.applyPendingReorg()) {
      upgraded = true
    }

    if (!upgraded && remoteWait) {
      const activeRequests = (opts && opts.activeRequests) || this.activeRequests
      if (isRequestsDestroyed(activeRequests)) throw REQUEST_CANCELLED()

      const req = this.core.replicator.addUpgrade(activeRequests)

      try {
        upgraded = await req.promise
      } catch (err) {
        if (isSessionMoved(err)) return this.update(opts)
        throw err
      }
    }

    if (!upgraded) return false
    return true
  }

  async seek(bytes, opts) {
    if (this.opened === false) await this.opening
    if (!isValidIndex(bytes)) throw ASSERTION('seek is invalid', this.discoveryKey)

    const activeRequests = (opts && opts.activeRequests) || this.activeRequests
    if (isRequestsDestroyed(activeRequests)) throw REQUEST_CANCELLED()

    if (this.encryption && !this.core.manifest) {
      const req = this.replicator.addUpgrade(activeRequests)
      try {
        await req.promise
      } catch (err) {
        if (isSessionMoved(err)) return this.seek(bytes, opts)
        throw err
      }
    }

    const s = MerkleTree.seek(this.state, bytes, this.padding)

    const offset = await s.update()
    if (offset) return offset

    if (this.closing !== null) {
      throw SESSION_CLOSED('cannot seek on a closed session', this.discoveryKey)
    }

    if (!this._shouldWait(opts, this.wait)) return null

    if (isRequestsDestroyed(activeRequests)) throw REQUEST_CANCELLED()
    const req = this.core.replicator.addSeek(activeRequests, s)

    const timeout = opts && opts.timeout !== undefined ? opts.timeout : this.timeout
    if (timeout) req.context.setTimeout(req, timeout)

    try {
      return await req.promise
    } catch (err) {
      if (isSessionMoved(err)) return this.seek(bytes, opts)
      throw err
    }
  }

  async has(start, end = start + 1) {
    if (this.opened === false) await this.opening
    if (!isValidIndex(start) || !isValidIndex(end)) {
      throw ASSERTION('has range is invalid', this.discoveryKey)
    }

    if (this.state.isDefault()) {
      if (end === start + 1) return this.core.bitfield.get(start)

      const i = this.core.bitfield.firstUnset(start)
      return i === -1 || i >= end
    }

    if (end === start + 1) {
      const rx = this.state.storage.read()
      const block = rx.getBlock(start)
      rx.tryFlush()

      return (await block) !== null
    }

    let count = 0

    const stream = this.state.storage.createBlockStream({ gte: start, lt: end })
    for await (const block of stream) {
      if (block === null) return false
      count++
    }

    return count === end - start
  }

  async get(index, opts) {
    if (this.opened === false) await this.opening
    if (!isValidIndex(index)) throw ASSERTION('block index is invalid', this.discoveryKey)

    if (this.closing !== null) {
      throw SESSION_CLOSED('cannot get on a closed session', this.discoveryKey)
    }

    const encoding =
      (opts && opts.valueEncoding && c.from(opts.valueEncoding)) || this.valueEncoding

    if (this.onseq !== null) this.onseq(index, this)
    if (this._marking) await this.markBlock(index)

    const req = this._get(index, opts)

    let block = await req
    if (!block) return null

    if (opts && opts.raw) return block

    if (this.encryption && (!opts || opts.decrypt !== false)) {
      // Copy the block as it might be shared with other sessions.
      block = b4a.from(block)

      await this.encryption.decrypt(index, block, this.core)
    }

    return this._decode(encoding, block, index)
  }

  async clear(start, end = start + 1, opts) {
    if (this.opened === false) await this.opening
    if (this.closing !== null) {
      throw SESSION_CLOSED('cannot clear on a closed session', this.discoveryKey)
    }

    if (typeof end === 'object') {
      opts = end
      end = start + 1
    }

    if (!isValidIndex(start) || !isValidIndex(end)) {
      throw ASSERTION('clear range is invalid', this.discoveryKey)
    }

    const cleared = opts && opts.diff ? { blocks: 0 } : null

    if (start >= end) return cleared
    if (start >= this.length) return cleared

    await this.state.clear(start, end, cleared)

    return cleared
  }

  async purge() {
    await this._closeAllSessions(null)
    await this.core.purge()
  }

  async _get(index, opts) {
    const block = await readBlock(this.state.storage.read(), index)

    if (block !== null) return block

    if (this.closing !== null) {
      throw SESSION_CLOSED('cannot get on a closed session', this.discoveryKey)
    }

    // snapshot should check if core has block
    if (this._snapshot !== null) {
      checkSnapshot(this, index)
      const coreBlock = await readBlock(this.core.state.storage.read(), index)

      checkSnapshot(this, index)
      if (coreBlock !== null) return coreBlock
    }

    // lets check the bitfield to see if we got it during the above async calls
    // this is the last resort before replication, so always safe.
    if (this.core.bitfield.get(index)) {
      const coreBlock = await readBlock(this.state.storage.read(), index)
      // TODO: this should not be needed, only needed atm in case we are doing a moveTo during this (we should fix)
      if (coreBlock !== null) return coreBlock
    }

    if (!this._shouldWait(opts, this.wait)) return null

    this.waits++
    if (opts && opts.onwait) opts.onwait(index, this)
    if (this.onwait) this.onwait(index, this)

    const activeRequests = (opts && opts.activeRequests) || this.activeRequests
    if (isRequestsDestroyed(activeRequests)) throw REQUEST_CANCELLED()

    const force = opts ? opts.force === true : false
    const req = this.core.replicator.addBlock(activeRequests, index, force)
    req.snapshot = index < this.length

    const timeout = opts && opts.timeout !== undefined ? opts.timeout : this.timeout
    if (timeout) req.context.setTimeout(req, timeout)

    let replicatedBlock = null

    try {
      replicatedBlock = await req.promise
    } catch (err) {
      if (isSessionMoved(err)) return this._get(index, opts)
      throw err
    }

    if (this._snapshot !== null) checkSnapshot(this, index)
    return maybeUnslab(replicatedBlock)
  }

  _shouldWait(opts, defaultValue) {
    if (opts) {
      if (opts.wait === false) return false
      if (opts.wait === true) return true
    }
    return defaultValue
  }

  _setupMarks() {
    if (this._marks === null) {
      const storage = this.snapshotted ? this.core.state.storage : this.state.storage
      this._marks = new MarkBitfield(storage)
    }
  }

  async markBlock(start, end = start + 1) {
    if (this.opened === false) await this.opening

    this._setupMarks()

    // TODO support as single rocks batch
    const setPromises = []
    for (let i = start; i < end; i++) {
      setPromises.push(this._marks.set(i, true))
    }

    return Promise.all(setPromises)
  }

  async clearMarkings() {
    if (this.opened === false) await this.opening

    this._setupMarks()

    await this._marks.clear()
    this._marks = null
  }

  async startMarking() {
    if (this._marking) {
      throw ASSERTION("Hypercore cannot be gc'ed when already in gc mode", this.discoveryKey)
    }
    if (this.state && this.state.name) {
      throw ASSERTION("Hypercore cannot be gc'ed when a named session", this.discoveryKey)
    }
    if (this.state && this.state.storage.atom) {
      throw ASSERTION("Hypercore cannot be gc'ed when an atomic session", this.discoveryKey)
    }
    if (this.opened === false) await this.opening
    await this.clearMarkings()

    this._marking = true
  }

  async sweep({ batchSize = 1000 } = {}) {
    if (this.opened === false) await this.opening

    assert(!this.snapshotted, 'Cannot sweep a snapshot')

    // No marks - load from storage
    this._setupMarks()

    let clearing = []
    let prevIndex = this.length
    for await (const index of this._marks.createMarkStream({ reverse: true })) {
      if (index + 1 === prevIndex) {
        prevIndex = index
        continue
      }
      clearing.push(this.clear(index + 1, prevIndex))
      if (clearing.length >= batchSize) {
        await Promise.all(clearing)
        clearing = []
      }
      prevIndex = index
    }
    // Clear range from the very start if not marked
    if (prevIndex > 0) clearing.push(this.clear(0, prevIndex))
    await Promise.all(clearing)

    this._marking = false
    await this.clearMarkings()
  }

  createReadStream(opts) {
    return new ReadStream(this, opts)
  }

  createWriteStream() {
    return new WriteStream(this)
  }

  createByteStream(opts) {
    return new ByteStream(this, opts)
  }

  download(range) {
    return new Download(this, range)
  }

  // TODO: get rid of this / deprecate it?
  undownload(range) {
    range.destroy(null)
  }

  // TODO: get rid of this / deprecate it?
  cancel(request) {
    // Do nothing for now
  }

  async truncate(newLength = 0, opts = {}) {
    if (this.opened === false) await this.opening
    if (this.closing) throw SESSION_CLOSED('Cannot append to a closed session', this.discoveryKey)

    const {
      fork = this.state.fork + 1,
      keyPair = this.keyPair,
      signature = null
    } = typeof opts === 'number' ? { fork: opts } : opts

    const isDefault = this.state === this.core.state
    const writable = !this._readonly && !!(signature || (keyPair && keyPair.secretKey))
    if (isDefault && writable === false && (newLength > 0 || fork !== this.state.fork)) {
      throw SESSION_NOT_WRITABLE('cannot append to a non-writable core', this.discoveryKey)
    }

    await this.state.truncate(newLength, fork, { keyPair, signature })

    // TODO: Should propagate from an event triggered by the oplog
    if (this.state === this.core.state) this.core.replicator.updateAll()
  }

  async append(blocks, opts = {}) {
    if (this.opened === false) await this.opening
    if (this.closing) throw SESSION_CLOSED('Cannot append to a closed session', this.discoveryKey)

    const isDefault = this.state === this.core.state
    const defaultKeyPair = this.state.name === null ? this.keyPair : null

    const { keyPair = defaultKeyPair, signature = null, maxLength, postappend = null } = opts
    const writable =
      !isDefault || !!signature || !!(keyPair && keyPair.secretKey) || opts.writable === true

    if (this._readonly || writable === false) {
      throw SESSION_NOT_WRITABLE('cannot append to a readonly core', this.discoveryKey)
    }

    blocks = Array.isArray(blocks) ? blocks : [blocks]

    const preappend = this.encryption && this._preappend

    const buffers = this.encodeBatch !== null ? this.encodeBatch(blocks) : new Array(blocks.length)

    if (this.encodeBatch === null) {
      for (let i = 0; i < blocks.length; i++) {
        buffers[i] = this._encode(this.valueEncoding, blocks[i])
      }
    }
    for (const b of buffers) {
      if (b.byteLength > MAX_SUGGESTED_BLOCK_SIZE) {
        throw BAD_ARGUMENT(
          'Appended block exceeds the maximum suggested block size',
          this.discoveryKey
        )
      }
    }

    return this.state.append(buffers, { keyPair, signature, preappend, postappend, maxLength })
  }

  async signable(length = -1, fork = -1) {
    if (this.opened === false) await this.opening
    if (length === -1) length = this.length
    if (fork === -1) fork = this.fork

    return caps.treeSignable(this.key, await this.treeHash(length), length, fork)
  }

  async treeHash(length = -1) {
    if (this.opened === false) await this.opening
    if (length === -1) length = this.length
    if (length > 0 && !(await this.has(length - 1))) await this.get(length - 1)

    const roots = await MerkleTree.getRoots(this.state, length)
    return crypto.tree(roots)
  }

  async missingNodes(index) {
    if (this.opened === false) await this.opening
    return await MerkleTree.missingNodes(this.core.state, 2 * index, this.core.state.length)
  }

  async proof(opts) {
    if (this.opened === false) await this.opening
    const rx = this.state.storage.read()
    const proofPromise = MerkleTree.proof(this.state, rx, opts)
    const blockPromise = opts && opts.block ? rx.getBlock(opts.block.index) : null
    rx.tryFlush()
    const [proof, block] = await Promise.all([proofPromise, blockPromise])
    const settled = await proof.settle()
    if (block) settled.block.value = block
    return settled
  }

  async applyProof(proof, from) {
    if (this.opened === false) await this.opening
    return this.core.verify(proof, from)
  }

  async verifyFullyRemote(proof) {
    if (this.opened === false) await this.opening
    const batch = await MerkleTree.verifyFullyRemote(this.state, proof)
    await this.core._verifyBatchUpgrade(batch, proof.manifest)
    return batch
  }

  generateRemoteProofForTreeNode(treeNodeIndex) {
    const blockProofIndex = flat.rightSpan(treeNodeIndex) / 2
    return proof(this, {
      index: blockProofIndex,
      // + 1 to length so the block is included
      upgrade: { start: 0, length: blockProofIndex + 1 }
    })
  }

  async recoverFromRemoteProof(remoteProof) {
    this.core.replicator.setPushOnly(true)
    this.core._repairMode = true

    await this.core.state.mutex.lock()

    try {
      const p = await verify(this.core.db, remoteProof)
      if (!p) return false

      const tx = this.core.storage.write()
      for (const node of p.proof.upgrade.nodes) {
        tx.putTreeNode(node)
      }
      await tx.flush()

      const succeed = p.proof.upgrade.nodes.length !== 0
      if (succeed) {
        this.core.replicator.setPushOnly(false)
      }
      return succeed
    } finally {
      this.core.state.mutex.unlock()
    }
  }

  recoverTreeNodeFromPeers() {
    this.core.replicator.setPushOnly(true)

    for (const peer of this.core.replicator.peers) {
      const req = {
        id: 0,
        fork: this.fork,
        upgrade: {
          start: 0,
          length: this.length
        }
      }
      peer.wireRequest.send(req)
    }
  }

  registerExtension(name, handlers = {}) {
    if (this.extensions.has(name)) {
      const ext = this.extensions.get(name)
      ext.handlers = handlers
      ext.encoding = c.from(handlers.encoding || c.buffer)
      ext.session = this
      return ext
    }

    const ext = {
      name,
      handlers,
      encoding: c.from(handlers.encoding || c.buffer),
      session: this,
      send(message, peer) {
        const buffer = c.encode(this.encoding, message)
        peer.extension(name, buffer)
      },
      broadcast(message) {
        const buffer = c.encode(this.encoding, message)
        for (const peer of this.session.peers) {
          peer.extension(name, buffer)
        }
      },
      destroy() {
        for (const peer of this.session.peers) {
          if (peer.extensions.get(name) === ext) peer.extensions.delete(name)
        }
        this.session.extensions.delete(name)
      },
      _onmessage(state, peer) {
        const m = this.encoding.decode(state)
        if (this.handlers.onmessage) this.handlers.onmessage(m, peer)
      }
    }

    this.extensions.set(name, ext)

    if (this.core === null) this._monitorIndex = -2
    else this.core.addMonitor(this)

    for (const peer of this.peers) {
      peer.extensions.set(name, ext)
    }

    return ext
  }

  _encode(enc, val) {
    const state = { start: this.padding, end: this.padding, buffer: null }

    if (b4a.isBuffer(val)) {
      if (state.start === 0) return val
      state.end += val.byteLength
    } else if (enc) {
      enc.preencode(state, val)
    } else {
      val = b4a.from(val)
      if (state.start === 0) return val
      state.end += val.byteLength
    }

    state.buffer = b4a.allocUnsafe(state.end)

    if (enc) enc.encode(state, val)
    else state.buffer.set(val, state.start)

    return state.buffer
  }

  _decode(enc, block, index) {
    if (this.encryption) block = block.subarray(this.encryption.padding(this.core, index))
    try {
      if (enc) return c.decode(enc, block)
    } catch (err) {
      throw DECODING_ERROR(err.message, this.discoveryKey)
    }
    return block
  }

  _getEncryptionProvider(e) {
    if (isEncryptionProvider(e)) return e
    if (!e || !e.key) return null
    return new DefaultEncryption(e.key, this.key, { block: e.block, compat: this.core.compat })
  }
}

module.exports = Hypercore

function isStream(s) {
  return typeof s === 'object' && s && typeof s.pipe === 'function'
}

async function preappend(blocks) {
  const offset = this.state.length
  const fork = this.state.encryptionFork

  for (let i = 0; i < blocks.length; i++) {
    await this.encryption.encrypt(offset + i, blocks[i], fork, this.core)
  }
}

function isValidIndex(index) {
  return index === 0 || index > 0
}

function maybeUnslab(block) {
  // Unslab only when it takes up less then half the slab
  return block !== null && 2 * block.byteLength < block.buffer.byteLength ? unslab(block) : block
}

function checkSnapshot(snapshot, index) {
  if (index >= snapshot.state.snapshotCompatLength) {
    throw SNAPSHOT_NOT_AVAILABLE(
      `snapshot at index ${index} not available (max compat length ${snapshot.state.snapshotCompatLength})`,
      snapshot.discoveryKey
    )
  }
}

function readBlock(rx, index) {
  const promise = rx.getBlock(index)
  rx.tryFlush()
  return promise
}

function initOnce(session, storage, key, opts) {
  if (storage === null) storage = opts.storage || null
  if (key === null) key = opts.key || null

  session.core = new Core(Hypercore.defaultStorage(storage), {
    preopen: opts.preopen,
    eagerUpgrade: opts.eagerUpgrade !== false,
    notDownloadingLinger: opts.notDownloadingLinger,
    allowFork: opts.allowFork !== false,
    allowPush: !!opts.allowPush,
    pushOnly: !!opts.pushOnly,
    alwaysLatestBlock: !!opts.allowLatestBlock,
    inflightRange: opts.inflightRange,
    compat: opts.compat === true,
    force: opts.force,
    createIfMissing: opts.createIfMissing,
    discoveryKey: opts.discoveryKey,
    overwrite: opts.overwrite,
    key,
    keyPair: opts.keyPair,
    legacy: opts.legacy,
    manifest: opts.manifest,
    group: opts.group,
    globalCache: opts.globalCache || null // session is a temp option, not to be relied on unless you know what you are doing (no semver guarantees)
  })
}

function maybeAddMonitor(name) {
  if (name === 'append' || name === 'truncate') return
  if (this._monitorIndex >= 0 || this.closing) return

  if (this.core === null) {
    this._monitorIndex = -2
  } else {
    this.core.addMonitor(this)
  }
}

function isSessionMoved(err) {
  return err.code === 'SESSION_MOVED'
}

function getEncryptionOption(opts) {
  // old style, supported for now but will go away
  if (opts.encryptionKey) return { key: opts.encryptionKey, block: !!opts.isBlockKey }
  if (!opts.encryption) return null
  return b4a.isBuffer(opts.encryption) ? { key: opts.encryption } : opts.encryption
}

function isEncryptionProvider(e) {
  return e && isFunction(e.padding) && isFunction(e.encrypt) && isFunction(e.decrypt)
}

function isFunction(fn) {
  return !!fn && typeof fn === 'function'
}

function createDiscoveryKeyHandler(fn) {
  return ondiscoverykey
  function ondiscoverykey(id) {
    if (!id || id.byteLength !== 32) throw BAD_ARGUMENT('Invalid discovery key')
    return fn(id)
  }
}

function isRequestsDestroyed(activeRequests) {
  // TODO: move this to an object instead so we can store a property in next major
  return activeRequests.length > 0 && activeRequests[0] === null
}
const crypto = require('hypercore-crypto')
const flat = require('flat-tree')
const b4a = require('b4a')
const { MerkleTree } = require('./merkle-tree')

module.exports = async function auditCore(
  core,
  { tree = true, blocks = true, bitfield = true, dryRun = false } = {}
) {
  const length = core.state.length
  const stats = {
    treeNodes: 0,
    blocks: 0,
    bits: 0,
    droppedTreeNodes: 0,
    droppedBlocks: 0,
    droppedBits: 0,
    corrupt: false
  }

  // audit the tree
  if (tree) {
    let tx = null

    const roots = await MerkleTree.getRootsFromStorage(core.state.storage, length)
    const stack = []

    for (const r of roots) {
      if (r === null) {
        if (!dryRun) {
          const storage = core.state.storage
          await storage.store.deleteCore(storage.core)
          return null
        }

        stats.corrupt = true
      }

      stack.push(r)
    }

    stats.treeNodes += roots.length

    while (stack.length > 0) {
      const node = stack.pop()

      if ((node.index & 1) === 0) continue

      const [left, right] = flat.children(node.index)

      const rx = core.state.storage.read()
      const leftNodePromise = rx.getTreeNode(left)
      const rightNodePromise = rx.getTreeNode(right)

      rx.tryFlush()

      const [leftNode, rightNode] = await Promise.all([leftNodePromise, rightNodePromise])

      if (isBadTree(node, leftNode, rightNode)) {
        if (!tx && !stats.corrupt) tx = core.state.storage.write()
        const [l, r] = flat.spans(node.index)
        tx.deleteTreeNodeRange(l, r + 1)
        stats.droppedTreeNodes++
        continue
      }

      if (!leftNode) continue

      stats.treeNodes += 2
      stack.push(leftNode, rightNode)
    }

    if (tx && !dryRun) await tx.flush()
  }

  // audit the blocks
  if (blocks) {
    let tx = null

    for await (const block of core.state.storage.createBlockStream()) {
      if (!core.bitfield.get(block.index)) {
        if (!tx && !stats.corrupt) tx = core.state.storage.write()
        tx.deleteBlock(block.index)
        stats.droppedBlocks++
      }

      const rx = core.state.storage.read()
      const treeNodePromise = rx.getTreeNode(2 * block.index)

      rx.tryFlush()

      const treeNode = await treeNodePromise

      if (isBadBlock(treeNode, block.value)) {
        if (!tx && !stats.corrupt) tx = core.state.storage.write()
        tx.deleteBlock(block.index)
        stats.droppedBlocks++
        continue
      }

      stats.blocks++
    }

    if (tx && !dryRun) await tx.flush()
  }

  if (bitfield) {
    let tx = null

    for (const index of allBits(core.bitfield)) {
      const rx = core.state.storage.read()
      const blockPromise = rx.getBlock(index)

      rx.tryFlush()

      const block = await blockPromise
      if (!block) {
        stats.droppedBits++
        if (dryRun) continue

        if (!tx && !stats.corrupt) tx = core.state.storage.write()

        core.bitfield.set(index, false)

        const page = core.bitfield.getBitfield(index)
        if (page.bitfield) tx.putBitfieldPage(page.index, page.bitfield)
        else tx.deleteBitfieldPage(page.index)
        continue
      }

      stats.bits++
    }

    if (tx && !dryRun) await tx.flush()
  }

  return stats
}

function isBadBlock(node, block) {
  if (!node) return true
  const hash = crypto.data(block)
  return !b4a.equals(hash, node.hash) || node.size !== block.byteLength
}

function isBadTree(parent, left, right) {
  if (!left && !right) return false
  if (!left || !right) return true
  const hash = crypto.parent(left, right)
  return !b4a.equals(hash, parent.hash) || parent.size !== left.size + right.size
}

function* allBits(bitfield) {
  let i = 0
  if (bitfield.get(0)) yield 0
  while (true) {
    i = bitfield.findFirst(true, i + 1)
    if (i === -1) break
    yield i
  }
}
const b4a = require('b4a')
const quickbit = require('./compat').quickbit

module.exports = class BitInterlude {
  constructor() {
    this.ranges = []
  }

  contiguousLength(from) {
    for (const r of this.ranges) {
      if (r.start > from) break
      if (!r.value && r.start <= from) return r.start
    }

    // TODO: be smarter
    while (this.get(from) === true) from++
    return from
  }

  get(index) {
    let start = 0
    let end = this.ranges.length

    while (start < end) {
      const mid = (start + end) >> 1
      const r = this.ranges[mid]

      if (index < r.start) {
        end = mid
        continue
      }

      if (index >= r.end) {
        if (mid === start) break
        start = mid
        continue
      }

      return r.value
    }

    return false
  }

  setRange(start, end, value) {
    if (start === end) return

    let r = null

    for (let i = 0; i < this.ranges.length; i++) {
      r = this.ranges[i]

      // if already inside, stop
      if (r.start <= start && end <= r.end) {
        if (value === r.value) return

        const ranges = mergeRanges(r, { start, end, value })
        this.ranges.splice(i, 1, ...ranges)

        return
      }

      // we wanna overun the interval
      if (start > r.end) {
        continue
      }

      // we overran but this interval is ending after us, move it back
      if (end >= r.start && end <= r.end) {
        r.start = r.value === value ? start : end
        if (r.value !== value) this.ranges.splice(i, 0, { start, end, value })
        return
      }

      // we overran but our start is contained in this interval, move start back
      if (start >= r.start && start <= r.end) {
        if (r.value !== value) {
          r.end = start // Crop current comparison

          // If there's a next range
          if (this.ranges.length - 1 > i) {
            const next = this.ranges[i + 1]
            // If the same, go next
            if (next.value === value) continue
            // Else we overlap so update next range
            if (next.start < end) next.start = end
          }

          this.ranges.splice(++i, 0, { start, end, value })
          return
        }

        start = r.start
      }

      let remove = 0

      for (let j = i; j < this.ranges.length; j++) {
        const n = this.ranges[j]
        if (n.start > end || n.value !== value) break
        if (n.start <= end && n.end > end) end = n.end
        remove++
      }

      this.ranges.splice(i, remove, { start, end, value })
      return
    }

    if (r !== null) {
      if (start <= r.end && end > r.end) {
        r.end = end
        return
      }

      // we never
      if (r.end > start) return
    }

    this.ranges.push({ start, end, value })
  }

  flush(tx, bitfield) {
    if (!this.ranges.length) return []

    let index = this.ranges[0].start
    const final = this.ranges[this.ranges.length - 1].end

    let i = 0

    while (index < final) {
      const page = bitfield.getBitfield(index) // read only
      const pageIndex = page ? page.index : bitfield.getPageIndex(index)

      const buf = b4a.allocUnsafe(bitfield.getPageByteLength())

      if (page) {
        const src = page.bitfield // Uint32Array
        buf.set(b4a.from(src.buffer, src.byteOffset, src.byteLength), 0)
      } else {
        b4a.fill(buf, 0)
      }

      const last = (pageIndex + 1) * (buf.byteLength << 3)
      const offset = pageIndex * (buf.byteLength << 3)

      let hasValue = false

      while (i < this.ranges.length) {
        const { start, end, value } = this.ranges[i]

        if (!hasValue && value) hasValue = true

        const from = start < index ? index : start
        const to = end < last ? end : last

        quickbit.fill(buf, value, from - offset, to - offset)

        index = to

        if (to === last) break

        i++
      }

      if (page || hasValue) tx.putBitfieldPage(pageIndex, buf)
    }

    return this.ranges
  }
}

function mergeRanges(a, b) {
  const ranges = []
  if (a.start < b.start) ranges.push({ start: a.start, end: b.start, value: a.value })
  ranges.push({ start: b.start, end: b.end, value: b.value })
  if (b.end < a.end) ranges.push({ start: b.end, end: a.end, value: a.value })

  return ranges
}
const BigSparseArray = require('big-sparse-array')
const b4a = require('b4a')
const quickbit = require('./compat').quickbit

const BITS_PER_PAGE = 32768
const BYTES_PER_PAGE = BITS_PER_PAGE / 8
const WORDS_PER_PAGE = BYTES_PER_PAGE / 4
const BITS_PER_SEGMENT = 2097152
const BYTES_PER_SEGMENT = BITS_PER_SEGMENT / 8
const WORDS_PER_SEGMENT = BYTES_PER_SEGMENT / 4
const INITIAL_WORDS_PER_SEGMENT = 1024
const PAGES_PER_SEGMENT = BITS_PER_SEGMENT / BITS_PER_PAGE
const SEGMENT_GROWTH_FACTOR = 4

class BitfieldPage {
  constructor(index, segment) {
    this.index = index
    this.offset = index * BYTES_PER_PAGE - segment.offset
    this.bitfield = null
    this.segment = segment

    segment.add(this)
  }

  get tree() {
    return this.segment.tree
  }

  get(index, dirty) {
    return quickbit.get(this.bitfield, index)
  }

  set(index, val) {
    if (quickbit.set(this.bitfield, index, val)) {
      this.tree.update(this.offset * 8 + index)
    }
  }

  setRange(start, end, val) {
    quickbit.fill(this.bitfield, val, start, end)

    let i = Math.floor(start / 128)
    const n = i + Math.ceil((end - start) / 128)

    while (i <= n) this.tree.update(this.offset * 8 + i++ * 128)
  }

  findFirst(val, position) {
    return quickbit.findFirst(this.bitfield, val, position)
  }

  findLast(val, position) {
    return quickbit.findLast(this.bitfield, val, position)
  }

  count(start, length, val) {
    const end = start + length

    let i = start
    let c = 0

    while (length > 0) {
      const l = this.findFirst(val, i)
      if (l === -1 || l >= end) return c

      const h = this.findFirst(!val, l + 1)
      if (h === -1 || h >= end) return c + end - l

      c += h - l
      length -= h - i
      i = h
    }

    return c
  }
}

class BitfieldSegment {
  constructor(index, bitfield) {
    this.index = index
    this.offset = index * BYTES_PER_SEGMENT
    this.tree = quickbit.Index.from(bitfield, BYTES_PER_SEGMENT)
    this.pages = new Array(PAGES_PER_SEGMENT)
  }

  get bitfield() {
    return this.tree.field
  }

  add(page) {
    const i = page.index - this.index * PAGES_PER_SEGMENT
    this.pages[i] = page

    const start = i * WORDS_PER_PAGE
    const end = start + WORDS_PER_PAGE

    if (end >= this.bitfield.length) this.reallocate(end)

    page.bitfield = this.bitfield.subarray(start, end)
  }

  reallocate(length) {
    let target = this.bitfield.length
    while (target < length) target *= SEGMENT_GROWTH_FACTOR

    const bitfield = new Uint32Array(target)
    bitfield.set(this.bitfield)

    this.tree = quickbit.Index.from(bitfield, BYTES_PER_SEGMENT)

    for (let i = 0; i < this.pages.length; i++) {
      const page = this.pages[i]
      if (!page) continue

      const start = i * WORDS_PER_PAGE
      const end = start + WORDS_PER_PAGE

      page.bitfield = bitfield.subarray(start, end)
    }
  }

  findFirst(val, position) {
    position = this.tree.skipFirst(!val, position)

    let j = position & (BITS_PER_PAGE - 1)
    let i = (position - j) / BITS_PER_PAGE

    if (i >= PAGES_PER_SEGMENT) return -1

    while (i < this.pages.length) {
      const p = this.pages[i]

      let index = -1

      if (p) index = p.findFirst(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_PAGE + index

      j = 0
      i++
    }

    return -1
  }

  findLast(val, position) {
    position = this.tree.skipLast(!val, position)

    let j = position & (BITS_PER_PAGE - 1)
    let i = (position - j) / BITS_PER_PAGE

    if (i >= PAGES_PER_SEGMENT) return -1

    while (i >= 0) {
      const p = this.pages[i]

      let index = -1

      if (p) index = p.findLast(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_PAGE + index

      j = BITS_PER_PAGE - 1
      i--
    }

    return -1
  }
}

module.exports = class Bitfield {
  static BITS_PER_PAGE = BITS_PER_PAGE
  static BYTES_PER_PAGE = BYTES_PER_PAGE

  constructor(buffer) {
    this.resumed = !!(buffer && buffer.byteLength >= 0)

    this._pages = new BigSparseArray()
    this._segments = new BigSparseArray()

    const view = this.resumed
      ? new Uint32Array(buffer.buffer, buffer.byteOffset, Math.floor(buffer.byteLength / 4))
      : new Uint32Array(INITIAL_WORDS_PER_SEGMENT)

    for (let i = 0; i < view.length; i += WORDS_PER_SEGMENT) {
      let bitfield = view.subarray(i, i + WORDS_PER_SEGMENT)
      let length = WORDS_PER_SEGMENT

      if (i === 0) {
        length = INITIAL_WORDS_PER_SEGMENT
        while (length < bitfield.length) length *= SEGMENT_GROWTH_FACTOR
      }

      if (bitfield.length !== length) {
        const copy = new Uint32Array(length)
        copy.set(bitfield, 0)
        bitfield = copy
      }

      const segment = new BitfieldSegment(i / WORDS_PER_SEGMENT, bitfield)
      this._segments.set(segment.index, segment)

      for (let j = 0; j < bitfield.length; j += WORDS_PER_PAGE) {
        const page = new BitfieldPage((i + j) / WORDS_PER_PAGE, segment)
        this._pages.set(page.index, page)
      }
    }
  }

  static from(bitfield) {
    return new Bitfield(bitfield.toBuffer(bitfield._pages.maxLength * BITS_PER_PAGE))
  }

  toBuffer(length) {
    const pages = Math.ceil(length / BITS_PER_PAGE)
    const buffer = b4a.allocUnsafe(pages * BYTES_PER_PAGE)

    for (let i = 0; i < pages; i++) {
      const page = this._pages.get(i)
      const offset = i * BYTES_PER_PAGE

      if (page) {
        const buf = b4a.from(
          page.bitfield.buffer,
          page.bitfield.byteOffset,
          page.bitfield.byteLength
        )

        buffer.set(buf, offset)
      } else {
        buffer.fill(0, offset, offset + BYTES_PER_PAGE)
      }
    }

    return buffer
  }

  getBitfield(index) {
    const i = this.getPageIndex(index)

    const p = this._pages.get(i)
    return p || null
  }

  merge(bitfield, length) {
    let i = 0

    while (i < length) {
      const start = bitfield.firstSet(i)
      if (start === -1) break

      i = bitfield.firstUnset(start)

      if (i === -1 || i > length) i = length

      this.setRange(start, i, true)

      if (i >= length) break
    }
  }

  get(index) {
    const j = index & (BITS_PER_PAGE - 1)
    const i = (index - j) / BITS_PER_PAGE

    const p = this._pages.get(i)

    return p ? p.get(j) : false
  }

  getPageByteLength() {
    return BYTES_PER_PAGE
  }

  getPageIndex(index) {
    const j = index & (BITS_PER_PAGE - 1)
    return (index - j) / BITS_PER_PAGE
  }

  getPage(index, create) {
    const i = this.getPageIndex(index)

    let p = this._pages.get(i)

    if (p) return p

    if (!create) return null

    const k = Math.floor(i / PAGES_PER_SEGMENT)
    const s =
      this._segments.get(k) ||
      this._segments.set(
        k,
        new BitfieldSegment(
          k,
          new Uint32Array(k === 0 ? INITIAL_WORDS_PER_SEGMENT : WORDS_PER_SEGMENT)
        )
      )

    p = this._pages.set(i, new BitfieldPage(i, s))

    return p
  }

  set(index, val) {
    const j = index & (BITS_PER_PAGE - 1)
    const i = (index - j) / BITS_PER_PAGE

    let p = this._pages.get(i)

    if (!p && val) {
      const k = Math.floor(i / PAGES_PER_SEGMENT)
      const s =
        this._segments.get(k) ||
        this._segments.set(
          k,
          new BitfieldSegment(
            k,
            new Uint32Array(k === 0 ? INITIAL_WORDS_PER_SEGMENT : WORDS_PER_SEGMENT)
          )
        )

      p = this._pages.set(i, new BitfieldPage(i, s))
    }

    if (p) p.set(j, val)
  }

  setRange(start, end, val) {
    let j = start & (BITS_PER_PAGE - 1)
    let i = (start - j) / BITS_PER_PAGE

    while (start < end) {
      let p = this._pages.get(i)

      if (!p && val) {
        const k = Math.floor(i / PAGES_PER_SEGMENT)
        const s =
          this._segments.get(k) ||
          this._segments.set(
            k,
            new BitfieldSegment(
              k,
              new Uint32Array(k === 0 ? INITIAL_WORDS_PER_SEGMENT : WORDS_PER_SEGMENT)
            )
          )

        p = this._pages.set(i, new BitfieldPage(i, s))
      }

      const offset = i * BITS_PER_PAGE
      const last = Math.min(end - offset, BITS_PER_PAGE)
      const range = last - j

      if (p) p.setRange(j, last, val)

      j = 0
      i++
      start += range
    }
  }

  findFirst(val, position) {
    let j = position & (BITS_PER_SEGMENT - 1)
    let i = (position - j) / BITS_PER_SEGMENT

    while (i < this._segments.maxLength) {
      const s = this._segments.get(i)

      let index = -1

      if (s) index = s.findFirst(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_SEGMENT + index

      j = 0
      i++
    }

    return val ? -1 : this._segments.maxLength * BITS_PER_SEGMENT
  }

  firstSet(position) {
    return this.findFirst(true, position)
  }

  firstUnset(position) {
    return this.findFirst(false, position)
  }

  findLast(val, position) {
    let j = position & (BITS_PER_SEGMENT - 1)
    let i = (position - j) / BITS_PER_SEGMENT

    while (i >= 0) {
      const s = this._segments.get(i)

      let index = -1

      if (s) index = s.findLast(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_SEGMENT + index

      j = BITS_PER_SEGMENT - 1
      i--
    }

    return -1
  }

  lastSet(position) {
    return this.findLast(true, position)
  }

  lastUnset(position) {
    return this.findLast(false, position)
  }

  hasUnset(start, length) {
    const end = start + length

    let j = start & (BITS_PER_SEGMENT - 1)
    let i = (start - j) / BITS_PER_SEGMENT

    while (i < this._segments.maxLength) {
      const s = this._segments.get(i)
      const index = s ? s.findFirst(false, j) : j
      if (index !== -1) return i * BITS_PER_SEGMENT + index < end

      j = 0
      i++

      if (i * BITS_PER_SEGMENT >= end) return false
    }

    return true
  }

  hasSet(start, length) {
    const end = start + length

    let j = start & (BITS_PER_SEGMENT - 1)
    let i = (start - j) / BITS_PER_SEGMENT

    while (i < this._segments.maxLength) {
      const s = this._segments.get(i)

      let index = -1

      if (s) index = s.findFirst(true, j)

      if (index !== -1) return i * BITS_PER_SEGMENT + index < end

      j = 0
      i++

      if (i * BITS_PER_SEGMENT >= end) return false
    }

    return false
  }

  count(start, length, val) {
    let j = start & (BITS_PER_PAGE - 1)
    let i = (start - j) / BITS_PER_PAGE
    let c = 0

    while (length > 0) {
      const p = this._pages.get(i)

      const end = Math.min(j + length, BITS_PER_PAGE)
      const range = end - j

      if (p) c += p.count(j, range, val)
      else if (!val) c += range

      j = 0
      i++
      length -= range
    }

    return c
  }

  countSet(start, length) {
    return this.count(start, length, true)
  }

  countUnset(start, length) {
    return this.count(start, length, false)
  }

  *want(start, length) {
    if (start & 31) {
      const d = start & 31
      start -= d
      length += d
    }

    let j = start & (BITS_PER_SEGMENT - 1)
    let i = (start - j) / BITS_PER_SEGMENT

    while (length > 0) {
      const s = this._segments.get(i)

      if (s) {
        let end = Math.min(j + length, BITS_PER_SEGMENT)
        if (end & 31) end += 32 - (end & 31)

        yield {
          start: i * BITS_PER_SEGMENT + j,
          bitfield: s.bitfield.subarray(j / 32, end / 32)
        }
      }

      j = 0
      i++
      length -= BITS_PER_SEGMENT
    }
  }

  clear(tx) {
    return tx.deleteBitfieldPageRange(0, -1)
  }

  onupdate(ranges) {
    for (const { start, end, value } of ranges) {
      this.setRange(start, end, value)
    }
  }

  static async open(storage, length) {
    if (length === 0) return new Bitfield(storage, null)

    const pages = Math.ceil(length / BITS_PER_PAGE)
    const buffer = b4a.alloc(pages * BYTES_PER_PAGE)
    const stream = storage.createBitfieldStream({ lt: pages })

    for await (const { index, page } of stream) {
      buffer.set(page, index * BYTES_PER_PAGE)
    }

    return new Bitfield(buffer)
  }
}
const crypto = require('hypercore-crypto')
const sodium = require('sodium-universal')
const b4a = require('b4a')
const c = require('compact-encoding')

// TODO: rename this to "crypto" and move everything hashing related etc in here
// Also lets move the tree stuff from hypercore-crypto here

const [
  TREE,
  REPLICATE_INITIATOR,
  REPLICATE_RESPONDER,
  MANIFEST,
  DEFAULT_NAMESPACE,
  DEFAULT_ENCRYPTION
] = crypto.namespace('hypercore', 6)

exports.MANIFEST = MANIFEST
exports.DEFAULT_NAMESPACE = DEFAULT_NAMESPACE
exports.DEFAULT_ENCRYPTION = DEFAULT_ENCRYPTION

exports.replicate = function (isInitiator, key, handshakeHash) {
  const out = b4a.allocUnsafe(32)
  sodium.crypto_generichash_batch(
    out,
    [isInitiator ? REPLICATE_INITIATOR : REPLICATE_RESPONDER, key],
    handshakeHash
  )
  return out
}

exports.treeSignable = function (manifestHash, treeHash, length, fork) {
  const state = { start: 0, end: 112, buffer: b4a.allocUnsafe(112) }
  c.fixed32.encode(state, TREE)
  c.fixed32.encode(state, manifestHash)
  c.fixed32.encode(state, treeHash)
  c.uint64.encode(state, length)
  c.uint64.encode(state, fork)
  return state.buffer
}

exports.treeSignableCompat = function (hash, length, fork, noHeader) {
  const end = noHeader ? 48 : 80
  const state = { start: 0, end, buffer: b4a.allocUnsafe(end) }
  if (!noHeader) c.fixed32.encode(state, TREE) // ultra legacy mode, kill in future major
  c.fixed32.encode(state, hash)
  c.uint64.encode(state, length)
  c.uint64.encode(state, fork)
  return state.buffer
}
// Export the appropriate version of `quickbit-universal` as the plain import
// may resolve to an older version in some environments
let quickbit = require('quickbit-universal')
if (
  typeof quickbit.findFirst !== 'function' ||
  typeof quickbit.findLast !== 'function' ||
  typeof quickbit.clear !== 'function'
) {
  // This should always load the fallback from the locally installed version
  quickbit = require('quickbit-universal/fallback')
}
exports.quickbit = quickbit
const crypto = require('hypercore-crypto')
const flat = require('flat-tree')
const b4a = require('b4a')
const quickbit = require('quickbit-universal')
const Bitfield = require('./bitfield')

const MAX_BATCH_USED = 4 * 1024 * 1024
const MIN_BATCH_USED = 512 * 1024

// just in its own file as its a bit involved

module.exports = copyPrologue

async function copyPrologue(src, dst) {
  const prologue = dst.header.manifest.prologue

  if (src.length < prologue.length || prologue.length === 0) return

  const stack = []
  const roots = flat.fullRoots(prologue.length * 2)
  const batch = { roots, first: true, last: false, contig: 0, used: 0, tree: [], blocks: [] }

  for (let i = 0; i < roots.length; i++) {
    const node = roots[i]
    batch.tree.push(node)
    stack.push(node)
  }

  let lastPage = -1
  let lastBlock = -1

  for await (const data of src.storage.createBlockStream({
    gte: 0,
    lt: prologue.length,
    reverse: true
  })) {
    if (walkTree(stack, data.index * 2, batch) === false) {
      throw new Error('Missing block or tree node for ' + data.index)
    }

    batch.contig = data.index + 1 === lastBlock ? batch.contig + 1 : 1
    lastBlock = data.index

    const page = getBitfieldPage(data.index)
    batch.blocks.push(data)

    if (lastPage !== page) batch.used += 4096
    batch.used += Math.max(data.value.byteLength, 128) // 128 is just a sanity number to avoid mega batches

    // always safe to partially flush so we do that ondemand to reduce memory usage...
    if ((batch.used >= MIN_BATCH_USED && page !== lastPage) || batch.used >= MAX_BATCH_USED) {
      await flushBatch(prologue, src, dst, batch)
    }

    lastPage = page
  }

  if (lastBlock !== 0) batch.contig = 0

  batch.last = true
  await flushBatch(prologue, src, dst, batch)
}

async function flushBatch(prologue, src, dst, batch) {
  const nodePromises = []

  const srcReader = src.storage.read()
  for (const index of batch.tree) {
    nodePromises.push(srcReader.getTreeNode(index))
  }
  srcReader.tryFlush()

  const nodes = await Promise.all(nodePromises)

  const pagePromises = []
  const dstReader = dst.storage.read()

  const headPromise = batch.first ? dstReader.getHead() : null
  if (headPromise) headPromise.catch(noop)

  let lastPage = -1
  for (const { index } of batch.blocks) {
    const page = getBitfieldPage(index)
    if (page === lastPage) continue
    lastPage = page
    pagePromises.push(dstReader.getBitfieldPage(page))
  }

  dstReader.tryFlush()

  const pages = await Promise.all(pagePromises)
  const head = headPromise === null ? null : await headPromise
  const userData = []

  // reads done!

  if (batch.first) {
    const roots = nodes.slice(0, batch.roots.length)

    for (const node of roots) {
      if (!node) throw new Error('Missing nodes for prologue hash')
    }

    const treeHash = crypto.tree(roots)
    if (!b4a.equals(treeHash, prologue.hash)) throw new Error('Prologue does not match source')
  }

  if (batch.first) {
    for await (const data of src.storage.createUserDataStream()) userData.push(data)
  }

  for (let i = 0; i < pages.length; i++) {
    if (!pages[i]) pages[i] = b4a.alloc(4096)
  }

  const tx = dst.storage.write()

  for (const node of nodes) tx.putTreeNode(node)

  lastPage = -1
  let pageIndex = -1

  for (const { index, value } of batch.blocks) {
    const page = getBitfieldPage(index)

    if (page !== lastPage) {
      lastPage = page
      pageIndex++
      // queue the page now, we mutate it below but its the same ref
      tx.putBitfieldPage(pageIndex, pages[pageIndex])
    }

    const pageBuffer = pages[pageIndex]
    quickbit.set(pageBuffer, getBitfieldOffset(index), true)
    tx.putBlock(index, value)
  }

  for (const { key, value } of userData) {
    tx.putUserData(key, value)
  }

  let upgraded = batch.first && !head
  if (upgraded) {
    tx.setHead(prologueToTree(prologue))
  }

  await tx.flush()

  if (upgraded) {
    const roots = nodes.slice(0, batch.roots.length)
    dst.state.setRoots(roots)
    dst.header.tree = prologueToTree(prologue)
  }

  if (userData.length > 0) {
    dst.header.userData = userData.concat(dst.header.userData)
  }

  if (batch.contig) {
    // TODO: we need to persist this somehow
    dst.header.hints.contiguousLength = batch.contig
  }

  let start = 0
  let length = 0

  // update in memory bitfield
  for (const { index } of batch.blocks) {
    if (start === 0 || start - 1 === index) {
      length++
    } else {
      if (length > 0) signalReplicator(dst, upgraded, start, length)
      upgraded = false
      length = 1
    }

    start = index
    dst.bitfield.set(index, true)
  }

  if (length > 0) signalReplicator(dst, upgraded, start, length)

  // unlink
  batch.tree = []
  batch.blocks = []
  batch.first = false
  batch.used = 0
}

function signalReplicator(core, upgraded, start, length) {
  if (upgraded) {
    core.replicator.cork()
    core.replicator.onhave(start, length, false)
    core.replicator.onupgrade()
    core.replicator.uncork()
  } else {
    core.replicator.onhave(start, length, false)
  }
}

function prologueToTree(prologue) {
  return {
    fork: 0,
    length: prologue.length,
    rootHash: prologue.hash,
    signature: null
  }
}

function getBitfieldPage(index) {
  return Math.floor(index / Bitfield.BITS_PER_PAGE)
}

function getBitfieldOffset(index) {
  return index & (Bitfield.BITS_PER_PAGE - 1)
}

function walkTree(stack, target, batch) {
  while (stack.length > 0) {
    const node = stack.pop()

    if ((node & 1) === 0) {
      if (node === target) return true
      continue
    }

    const ite = flat.iterator(node)
    if (!ite.contains(target)) continue

    while ((ite.index & 1) !== 0) {
      const left = ite.leftChild()
      const right = ite.sibling() // is right child

      batch.tree.push(left, right)

      if (ite.contains(target)) stack.push(left)
      else ite.sibling()
    }

    if (ite.index === target) return true
  }

  return false
}

function noop() {}
const crypto = require('hypercore-crypto')
const b4a = require('b4a')
const unslab = require('unslab')
const z32 = require('z32')
const Mutex = require('./mutex')
const { MerkleTree, ReorgBatch } = require('./merkle-tree')
const BitInterlude = require('./bit-interlude')
const Bitfield = require('./bitfield')
const RemoteBitfield = require('./remote-bitfield')
const {
  BAD_ARGUMENT,
  STORAGE_EMPTY,
  STORAGE_CONFLICT,
  INVALID_SIGNATURE,
  INVALID_CHECKSUM
} = require('hypercore-errors')
const Verifier = require('./verifier')
const audit = require('./audit')
const copyPrologue = require('./copy-prologue')
const SessionState = require('./session-state')
const Replicator = require('./replicator')

module.exports = class Core {
  constructor(db, opts = {}) {
    this.db = db
    this.storage = null
    this.replicator = new Replicator(this, opts)
    this.sessionStates = []
    this.monitors = []
    this.activeSessions = 0
    this.gc = 0 // corestore uses this to main a gc strike pool

    this.id = opts.key ? z32.encode(opts.key) : null
    this.key = opts.key || null
    this.discoveryKey = opts.discoveryKey || (opts.key && crypto.discoveryKey(opts.key)) || null
    this.manifest = null
    this.opening = null
    this.closing = null
    this.exclusive = null

    this.preupdate = null
    this.header = null
    this.compat = false
    this.bitfield = null
    this.verifier = null
    this.truncating = 0
    this.skipBitfield = null
    this.globalCache = opts.globalCache || null
    this.autoClose = opts.autoClose !== false
    this.onidle = noop
    this.ongroupupdate = noop

    this.state = null
    this.opened = false
    this.destroyed = false
    this.closed = false

    this.hintsChanged = false
    this.remoteContiguousLengthChanged = false

    this._bitfield = null
    this._verifies = null
    this._verifiesFlushed = null
    this._legacy = !!opts.legacy
    this._repairMode = false

    this.opening = this._open(opts)
    this.opening.catch(noop)
  }

  static setRecoveryPeers(peers) {
    SessionState.RECOVERY_PEERS = peers
  }

  ready() {
    return this.opening
  }

  addMonitor(s) {
    if (s._monitorIndex >= 0) return
    s._monitorIndex = this.monitors.push(s) - 1
  }

  removeMonitor(s) {
    if (s._monitorIndex < 0) return
    const head = this.monitors.pop()
    if (head !== s) this.monitors[(head._monitorIndex = s._monitorIndex)] = head
    s._monitorIndex = -1
  }

  emitRemoteContiguousLength() {
    if (!this.remoteContiguousLengthChanged) return
    this.remoteContiguousLengthChanged = false

    const length = this.header.hints.remoteContiguousLength

    for (let i = this.monitors.length - 1; i >= 0; i--) {
      this.monitors[i].emit('remote-contiguous-length', length)
    }
  }

  emitManifest() {
    for (let i = this.monitors.length - 1; i >= 0; i--) {
      this.monitors[i].emit('manifest')
    }
  }

  createUserDataStream(opts, session = this.state) {
    return session.storage.createUserDataStream(opts)
  }

  allSessions() {
    const sessions = []
    for (const state of this.sessionStates) {
      if (state.sessions.length) sessions.push(...state.sessions)
    }
    return sessions
  }

  hasSession() {
    return this.activeSessions !== 0
  }

  compact() {
    const compacting = []
    for (const s of this.sessionStates) {
      compacting.push(s.storage.compact())
    }
    return Promise.all(compacting)
  }

  checkIfIdle() {
    if (!this.opened || this.destroyed === true || this.hasSession() === true) return
    if (this.replicator.idle() === false) return
    if (this.state === null || this.state.mutex.idle() === false) return
    this.onidle()
  }

  async lockExclusive() {
    if (this.exclusive === null) this.exclusive = new Mutex()
    await this.exclusive.lock()
  }

  unlockExclusive() {
    if (this.exclusive !== null) this.exclusive.unlock()
  }

  async _open(opts) {
    try {
      await this._tryOpen(opts)
    } catch (err) {
      this.onidle()
      throw err
    }

    this.opened = true
  }

  async _tryOpen(opts) {
    if (opts.preopen) await opts.preopen // just a hook to allow exclusive access here...

    let storage = await this.db.resumeCore(this.discoveryKey)

    let overwrite = opts.overwrite === true

    const force = opts.force === true
    const createIfMissing = opts.createIfMissing !== false
    // kill this flag soon
    const legacy = !!opts.legacy

    // default to true for now if no manifest is provided
    let compat = opts.compat === true || (opts.compat !== false && !opts.manifest)

    let header = storage ? parseHeader(await getCoreInfo(storage)) : null

    const hadManifest = !!header && !!header.manifest && !!header.key
    const hadKeyPair = !!header && !!header.keyPair

    if (force && opts.key && header && !b4a.equals(header.key, opts.key)) {
      overwrite = true
    }

    if (!header && opts.discoveryKey && !(opts.key || opts.manifest)) {
      throw STORAGE_EMPTY('No Hypercore is stored here', this.discoveryKey)
    }

    if (!header || overwrite) {
      if (!createIfMissing) {
        throw STORAGE_EMPTY('No Hypercore is stored here', this.discoveryKey)
      }

      if (compat) {
        if (opts.key && opts.keyPair && !b4a.equals(opts.key, opts.keyPair.publicKey)) {
          throw BAD_ARGUMENT('Key must match publicKey when in compat mode', this.discoveryKey)
        }
      }

      const keyPair = opts.keyPair || (opts.key ? null : crypto.keyPair())

      const defaultManifest =
        !opts.manifest &&
        (!!opts.compat || !opts.key || !!(keyPair && b4a.equals(opts.key, keyPair.publicKey)))
      const manifest = defaultManifest
        ? Verifier.defaultSignerManifest(opts.key || keyPair.publicKey)
        : Verifier.createManifest(opts.manifest)

      header = {
        key: opts.key || (compat ? manifest.signers[0].publicKey : Verifier.manifestHash(manifest)),
        manifest,
        keyPair: keyPair
          ? { publicKey: keyPair.publicKey, secretKey: keyPair.secretKey || null }
          : null,
        frozen: false,
        tree: {
          fork: 0,
          length: 0,
          rootHash: null,
          signature: null,
          timestamp: 0
        },
        group: null,
        hints: {
          reorgs: [],
          contiguousLength: 0,
          remoteContiguousLength: 0,
          recovering: 0
        }
      }

      const discoveryKey = opts.discoveryKey || crypto.discoveryKey(header.key)

      storage = await this.db.createCore({
        key: header.key,
        manifest,
        keyPair,
        frozen: false,
        discoveryKey,
        userData: opts.userData || [],
        alias: opts.alias || null
      })
    }

    // unslab the long lived buffers to avoid keeping the slab alive
    header.key = unslab(header.key)

    if (header.tree) {
      header.tree.rootHash = unslab(header.tree.rootHash)
      header.tree.signature = unslab(header.tree.signature)
    }

    if (header.keyPair) {
      header.keyPair.publicKey = unslab(header.keyPair.publicKey)
      header.keyPair.secretKey = unslab(header.keyPair.secretKey)
    }

    if (header.keyPair) {
      header.keyPair.publicKey = unslab(header.keyPair.publicKey)
      header.keyPair.secretKey = unslab(header.keyPair.secretKey)
    }

    if (opts.manifest) {
      // if we provide a manifest and no key, verify that the stored key is the same
      if (
        !opts.key &&
        !Verifier.isValidManifest(header.key, Verifier.createManifest(opts.manifest))
      ) {
        throw STORAGE_CONFLICT('Manifest does not hash to provided key', this.discoveryKey)
      }

      if (!header.manifest) header.manifest = opts.manifest
    }

    if (opts.key && !b4a.equals(header.key, opts.key)) {
      throw STORAGE_CONFLICT('Another Hypercore is stored here', this.discoveryKey)
    }

    // if we signalled compat, but already now this core isn't disable it
    if (compat && header.manifest && !Verifier.isCompat(header.key, header.manifest)) {
      compat = false
    } else if (!compat && header.manifest && Verifier.isCompat(header.key, header.manifest)) {
      compat = true
    }

    const prologue = header.manifest ? header.manifest.prologue : null

    const bitfield = await Bitfield.open(storage, header.tree.length)

    const treeInfo = {
      fork: header.tree.fork,
      length: header.tree.length,
      signature: header.tree.signature,
      roots: await maybeGetRootsFromStorage(storage, header.tree.length),
      prologue
    }

    this._repairMode = !treeInfo.roots.length && treeInfo.length && !overwrite
    // Set push only mode if in repair mode
    if (this._repairMode) {
      this.replicator.setPushOnly(true)
    }

    if (opts.group) {
      if (!header.group) header.group = await this.db.createGroup(opts.group)
      else if (!b4a.equals(header.group.key, opts.group)) {
        throw STORAGE_CONFLICT(
          'Core is already register to group: ' + b4a.toString(header.group.key, 'hex')
        )
      }

      const tx = storage.write()
      tx.setGroup(header.group)
      await tx.flush()
    }

    if (overwrite) {
      const tx = storage.write()
      tx.deleteTreeNodeRange(0, -1)
      tx.deleteBlockRange(0, -1)
      bitfield.clear(tx)
      await tx.flush()
    }

    const len = bitfield.findFirst(false, header.hints.contiguousLength)
    if (header.hints.contiguousLength !== len && !storage.readOnly) {
      header.hints.contiguousLength = len
      const tx = storage.write()
      tx.setHints(header.hints)
      await tx.flush()
    }

    // to unslab
    if (header.manifest) {
      header.manifest = Verifier.createManifest(header.manifest)
      if (!hadManifest || (header.keyPair && !hadKeyPair)) {
        const tx = storage.write()
        tx.setAuth({
          key: header.key,
          discoveryKey: crypto.discoveryKey(header.key),
          manifest: header.manifest,
          keyPair: header.keyPair
        })
        await tx.flush()
      }
    }

    const verifier = header.manifest
      ? new Verifier(header.key, header.manifest, { crypto, legacy })
      : null

    this.storage = storage
    this.header = header
    this.compat = compat
    this.bitfield = bitfield
    this.verifier = verifier
    this.state = new SessionState(this, null, storage, treeInfo, null)

    if (this.key === null) this.key = this.header.key
    if (this.discoveryKey === null) this.discoveryKey = crypto.discoveryKey(this.key)
    if (this.id === null) this.id = z32.encode(this.key)
    if (this.manifest === null) this.manifest = this.header.manifest
  }

  async audit(opts) {
    await this.state.mutex.lock()

    try {
      return await audit(this, opts)
    } finally {
      this.state._unlock()
    }
  }

  async setGroup(group) {
    await this.state.mutex.lock()
    try {
      if (!this.header.group) this.header.group = await this.db.createGroup(group)
      else if (!b4a.equals(this.header.group.key, group)) {
        throw STORAGE_CONFLICT(
          'Core is already register to group: ' + b4a.toString(this.header.group.key, 'hex')
        )
      }

      const tx = this.storage.write()
      tx.setGroup(this.header.group)
      await tx.flush()
    } finally {
      this.state.mutex.unlock()
    }
  }

  async setManifest(manifest) {
    await this.state.mutex.lock()

    try {
      if (manifest && this.header.manifest === null) {
        if (!Verifier.isValidManifest(this.header.key, manifest)) {
          throw INVALID_CHECKSUM('Manifest hash does not match', this.discoveryKey)
        }

        const tx = this.state.createWriteBatch()
        this._setManifest(tx, Verifier.createManifest(manifest), null)
        await this.state.flush()
      }
    } finally {
      this.state._unlock()
    }
  }

  _setManifest(tx, manifest, keyPair) {
    if (!manifest && b4a.equals(keyPair.publicKey, this.header.key)) {
      manifest = Verifier.defaultSignerManifest(this.header.key)
    }
    if (!manifest) return

    const verifier = new Verifier(this.header.key, manifest, { legacy: this._legacy })

    if (verifier.prologue) this.state.prologue = Object.assign({}, verifier.prologue)

    this.manifest = this.header.manifest = manifest

    tx.setAuth({
      key: this.header.key,
      discoveryKey: this.discoveryKey,
      manifest,
      keyPair: this.header.keyPair
      // TODO: encryptionKey?
    })

    this.compat = verifier.compat
    this.verifier = verifier

    this.replicator.onupgrade()
    this.emitManifest()
  }

  async copyPrologue(src) {
    await this.state.mutex.lock()

    try {
      await src.mutex.lock()
    } catch (err) {
      this.state.mutex.unlock()
      throw err
    }

    try {
      await copyPrologue(src, this)
    } finally {
      src.mutex.unlock()
      this.state.mutex.unlock()
      this.checkIfIdle()
    }
  }

  flushed() {
    return this.state.flushed()
  }

  async _validateCommit(state, treeLength) {
    if (this.state.length > state.length) {
      return false // TODO: partial commit and truncation possible in the future
    }

    if (this.state.length > treeLength) {
      for (const root of this.state.roots) {
        const batchRoot = await MerkleTree.get(state, root.index)
        if (batchRoot.size !== root.size || !b4a.equals(batchRoot.hash, root.hash)) {
          return false
        }
      }
    }

    if (this.verifier === null) {
      return false // easier to assert than upsert
    }

    return true
  }

  _verifyBatchUpgrade(batch, manifest) {
    if (!this.header.manifest) {
      // compat, drop at some point
      if (!manifest) manifest = Verifier.defaultSignerManifest(this.header.key)

      if (
        !manifest ||
        !(
          Verifier.isValidManifest(this.header.key, manifest) ||
          Verifier.isCompat(this.header.key, manifest)
        )
      ) {
        throw INVALID_SIGNATURE('Proof contains an invalid manifest', this.discoveryKey) // TODO: proper error type
      }
    }

    const verifier =
      this.verifier ||
      new Verifier(this.header.key, Verifier.createManifest(manifest), { legacy: this._legacy })

    if (!verifier.verify(batch, batch.signature)) {
      throw INVALID_SIGNATURE('Proof contains an invalid signature', this.discoveryKey)
    }

    return manifest
  }

  async _verifyExclusive({ batch, bitfield, value, manifest }) {
    manifest = this._verifyBatchUpgrade(batch, manifest)

    if (
      !(await this.state._verifyBlock(
        batch,
        bitfield,
        value,
        this.header.manifest ? null : manifest
      ))
    ) {
      return false
    }

    if (!batch.upgraded && bitfield) {
      this.replicator.onhave(bitfield.start, bitfield.length, bitfield.drop)
    }

    return true
  }

  async _verifyShared() {
    if (!this._verifies.length) return false

    await this.state.mutex.lock()

    const tx = this.state.createWriteBatch()

    const verifies = this._verifies
    this._verifies = null
    this._verified = null

    try {
      for (const { batch, bitfield, value } of verifies) {
        if (!batch.commitable()) continue

        if (bitfield) {
          tx.putBlock(bitfield.start, value)
        }
      }

      const bits = new BitInterlude()

      for (let i = 0; i < verifies.length; i++) {
        const { batch, bitfield, manifest } = verifies[i]

        if (!batch.commitable()) {
          verifies[i] = null // signal that we cannot commit this one
          continue
        }

        if (bitfield) {
          bits.setRange(bitfield.start, bitfield.start + 1, true)
        }

        // if we got a manifest AND its strictly a non compat one, lets store it
        if (manifest && this.header.manifest === null) {
          if (!Verifier.isValidManifest(this.header.key, manifest)) {
            throw INVALID_CHECKSUM('Manifest hash does not match', this.discoveryKey)
          }
          this._setManifest(tx, manifest, null)
        }

        if (batch.commitable()) batch.commit(tx)
      }

      const ranges = bits.flush(tx, this.bitfield)

      await this.state.flush()

      for (const { start, end, value } of ranges) {
        this._setBitfieldRanges(start, end, value)
      }

      for (let i = 0; i < verifies.length; i++) {
        const bitfield = verifies[i] && verifies[i].bitfield
        if (bitfield) {
          this.updateContiguousLength(bitfield)
          this.replicator.onhave(bitfield.start, bitfield.length, bitfield.drop)
        }
      }

      if (this.hintsChanged) await this.flushHints()
    } finally {
      this.state._clearActiveBatch()
      this.state.mutex.unlock()
    }

    return verifies[0] !== null
  }

  async flushHints() {
    if (!this.hintsChanged) return
    this.hintsChanged = false // we unset this immediately as a "debounce"

    const tx = this.state.storage.write()

    tx.setHints({
      contiguousLength: this.header.hints.contiguousLength,
      remoteContiguousLength: this.header.hints.remoteContiguousLength,
      recovering: this.header.hints.recovering
    })

    await tx.flush()
  }

  async checkConflict(proof, from) {
    if (this.state.length < proof.upgrade.length || proof.fork !== this.state.fork) {
      // out of date this proof - ignore for now
      return false
    }

    // sanity check -> no manifest, no way to verify
    if (!this.header.manifest) {
      return false
    }

    const batch = MerkleTree.verifyFullyRemote(this.state, proof)

    try {
      this._verifyBatchUpgrade(batch, proof.manifest)
    } catch {
      return true
    }

    const roots = await maybeGetRootsFromStorage(this.storage, proof.upgrade.length)
    const remoteTreeHash = crypto.tree(proof.upgrade.nodes)
    const localTreeHash = crypto.tree(roots)

    try {
      const rx = this.state.storage.read()
      const treeProofPromise = MerkleTree.proof(this.state, rx, {
        block: null,
        hash: null,
        seek: null,
        upgrade: {
          start: 0,
          length: proof.upgrade.length
        }
      })

      rx.tryFlush()

      const treeProof = await treeProofPromise

      const verifyBatch = MerkleTree.verifyFullyRemote(this.state, await treeProof.settle())
      this._verifyBatchUpgrade(verifyBatch, this.header.manifest)
    } catch (err) {
      if (err.code !== 'INVALID_OPERATION') return true

      return !(await this._repairTreeNodes(proof))
    }

    // both proofs are valid, now check if they forked
    if (b4a.equals(localTreeHash, remoteTreeHash)) return false

    await this.state.mutex.lock()

    try {
      const tx = this.state.createWriteBatch()

      this.header.frozen = true

      tx.setAuth({
        key: this.header.key,
        discoveryKey: this.discoveryKey,
        manifest: this.header.manifest,
        keyPair: this.header.keyPair,
        frozen: true
      })

      await this.state.flush()
    } finally {
      this.state.mutex.unlock()
    }

    // tmp log so we can see these
    const id = b4a.toString(this.discoveryKey, 'hex')
    console.log(
      '[hypercore] conflict detected in ' +
        id +
        ' (writable=' +
        !!this.header.keyPair +
        ',quorum=' +
        this.header.manifest.quorum +
        ')'
    )
    await this._onconflict(proof)
    return true
  }

  async _repairTreeNodes(proof) {
    if (!this._repairMode) return false

    await this.state.mutex.lock()

    for (let i = this.monitors.length - 1; i >= 0; i--) {
      this.monitors[i].emit('repairing', proof)
    }

    try {
      const batch = MerkleTree.verifyFullyRemote(this.state, proof)
      this._verifyBatchUpgrade(batch, proof.manifest)
    } catch {
      this.state.mutex.unlock()
      for (let i = this.monitors.length - 1; i >= 0; i--) {
        this.monitors[i].emit('repair-failed')
      }
      return false
    }

    // Attempt to repair local merkle tree with remote roots
    const atom = this.storage.createAtom()
    const atomized = this.storage.atomize(atom)
    const tx = atomized.write()
    for (const node of proof.upgrade.nodes) {
      tx.putTreeNode(node)
    }
    await tx.flush()

    // Try local proof again
    try {
      const rx = atomized.read()
      const treeProofPromise = MerkleTree.proof(this.state, rx, {
        block: null,
        hash: null,
        seek: null,
        upgrade: {
          start: 0,
          length: proof.upgrade.length
        }
      })

      rx.tryFlush()

      const treeProof = await treeProofPromise

      const verifyBatch = MerkleTree.verifyFullyRemote(this.state, await treeProof.settle())
      this._verifyBatchUpgrade(verifyBatch, this.header.manifest)
    } catch (err) {
      this.state.mutex.unlock()
      for (let i = this.monitors.length - 1; i >= 0; i--) {
        this.monitors[i].emit('repair-failed')
      }
      return false
    }

    await atom.flush()

    for (let i = this.monitors.length - 1; i >= 0; i--) {
      this.monitors[i].emit('repaired', proof)
    }
    this.replicator.setPushOnly(false)
    this.state.mutex.unlock()
    return true
  }

  async verifyReorg(proof) {
    const batch = new ReorgBatch(this.state)
    await MerkleTree.reorg(this.state, proof, batch)
    const manifest = this._verifyBatchUpgrade(batch, proof.manifest)

    if (manifest && !this.header.manifest) {
      await this.state.mutex.lock()
      try {
        if (manifest && this.header.manifest === null) {
          const tx = this.state.createWriteBatch()
          this._setManifest(tx, Verifier.createManifest(manifest), null)
          await this.state.flush()
        }
      } finally {
        this.state._unlock()
      }
    }

    return batch
  }

  async verify(proof, from) {
    // We cannot apply "other forks" atm.
    // We should probably still try and they are likely super similar for non upgrades
    // but this is easy atm (and the above layer will just retry)
    if (proof.fork !== this.state.fork) return false

    const batch = await MerkleTree.verify(this.state, proof)

    if (batch.upgraded && batch.length <= this.state.length) {
      await batch.downgrade()
    }

    if (!batch.commitable()) {
      return false
    }

    const value = (proof.block && proof.block.value) || null
    const op = {
      batch,
      bitfield: value && { drop: false, start: proof.block.index, length: 1 },
      value,
      manifest: proof.manifest,
      from
    }

    if (batch.upgraded) {
      return this._verifyExclusive(op)
    }

    if (this._verifies !== null) {
      const verifies = this._verifies
      const i = verifies.push(op)
      await this._verified
      return verifies[i] !== null
    }

    this._verifies = [op]
    this._verified = this._verifyShared()

    return this._verified
  }

  async reorg(batch) {
    if (!batch.commitable()) return false

    this.truncating++

    try {
      await this.state.reorg(batch)
    } finally {
      this.truncating--
    }

    return true
  }

  openSkipBitfield() {
    if (this.skipBitfield !== null) return this.skipBitfield
    this.skipBitfield = new RemoteBitfield()
    const buf = this.bitfield.toBuffer(this.state.length)
    const bitfield = new Uint32Array(buf.buffer, buf.byteOffset, buf.byteLength / 4)
    this.skipBitfield.insert(0, bitfield)
    return this.skipBitfield
  }

  _setBitfieldRanges(start, end, value) {
    this.bitfield.setRange(start, end, value)
    if (this.skipBitfield !== null) this.skipBitfield.setRange(start, end, value)
  }

  close() {
    if (!this.closing) this.closing = this._close()
    return this.closing
  }

  updateContiguousLength(bitfield) {
    const contig = updateContigBatch(this.header.hints.contiguousLength, bitfield, this.bitfield)

    if (contig.length !== -1 && contig.length !== this.header.hints.contiguousLength) {
      this.header.hints.contiguousLength = contig.length
      this.hintsChanged = true
    }
  }

  updateRemoteContiguousLength(length) {
    this.header.hints.remoteContiguousLength = length
    this.hintsChanged = true
    this.remoteContiguousLengthChanged = true
  }

  onappend(tree, bitfield) {
    this.header.tree = tree

    if (!bitfield) {
      this.replicator.onupgrade()
      return
    }

    this.replicator.cork()

    const { start, length, drop } = bitfield

    this._setBitfieldRanges(start, start + length, true)
    this.updateContiguousLength({ start, length, drop: false })

    this.replicator.onupgrade()
    this.replicator.onhave(start, length, drop)
    this.replicator.uncork()
  }

  ontruncate(tree, { start, length }) {
    if (tree) this.header.tree = tree

    this.replicator.cork()

    this.replicator.ontruncate(start, length)
    this.replicator.onhave(start, length, true)
    this.replicator.onupgrade()
    this.replicator.uncork()

    for (const sessionState of this.sessionStates) {
      if (start < sessionState.snapshotCompatLength) sessionState.snapshotCompatLength = start
    }

    this._setBitfieldRanges(start, start + length, false)
    this.updateContiguousLength({ start, length, drop: true })
  }

  async _onconflict(proof) {
    await this.replicator.onconflict()

    for (let i = this.monitors.length - 1; i >= 0; i--) {
      const s = this.monitors[i]
      s.emit('conflict', proof.upgrade.length, proof.fork, proof)
    }

    const err = new Error('Two conflicting signatures exist for length ' + proof.upgrade.length)
    await this.closeAllSessions(err)
  }

  async closeAllSessions(err) {
    // this.sessions modifies itself when a session closes
    // This way we ensure we indeed iterate over all sessions
    const sessions = this.allSessions()

    const all = []
    for (const s of sessions) all.push(s.close({ error: err, force: false })) // force false or else infinite recursion
    await Promise.allSettled(all)
  }

  async destroy() {
    if (this.destroyed === true) return
    this.destroyed = true

    if (this.hasSession() === true) throw new Error('Cannot destroy while sessions are open')

    const weakSessions = this.allSessions()

    if (this.replicator) this.replicator.destroy()
    if (this.state) await this.state.close()

    // close all pending weak sessions...
    for (const s of weakSessions) s.close().catch(noop)
  }

  async _close() {
    if (this.opened === false) await this.opening
    if (this.hasSession() === true) throw new Error('Cannot close while sessions are open')

    if (this.replicator) await this.replicator.close()

    await this.destroy()
    if (this.autoClose) await this.storage.store.close()

    this.closed = true
  }
}

function updateContigBatch(start, upd, bitfield) {
  const end = upd.start + upd.length

  let c = start

  if (upd.drop) {
    // If we dropped a block in the current contig range, "downgrade" it
    if (c > upd.start) {
      c = upd.start
    }
  } else {
    if (c <= end && c >= upd.start) {
      c = end
      while (bitfield.get(c)) c++
    }
  }

  if (c === start) {
    return {
      length: -1
    }
  }

  if (c > start) {
    return {
      length: c
    }
  }

  return {
    length: c
  }
}

function getDefaultTree() {
  return {
    fork: 0,
    length: 0,
    rootHash: null,
    signature: null,
    timestamp: 0
  }
}

function parseHeader(info) {
  if (!info) return null

  return {
    key: info.key,
    manifest: info.manifest,
    external: null,
    keyPair: info.keyPair,
    tree: info.head || getDefaultTree(),
    group: info.group,
    hints: {
      reorgs: [],
      contiguousLength: info.hints ? info.hints.contiguousLength : 0,
      remoteContiguousLength: info.hints ? info.hints.remoteContiguousLength : 0,
      recovering: info.hints ? info.hints.recovering : 0
    }
  }
}

async function maybeGetRootsFromStorage(storage, length) {
  try {
    return length ? await MerkleTree.getRootsFromStorage(storage, length) : []
  } catch (err) {
    if (err.code !== 'INVALID_OPERATION') throw err
    // If INVALID_OPERATION, a root is likely missing so load empty roots to try to recover
    return []
  }
}

function noop() {}

async function getCoreInfo(storage) {
  const r = storage.read()

  const auth = r.getAuth()
  const head = r.getHead()
  const hints = r.getHints()
  const group = r.getGroup()

  r.tryFlush()

  const [authInfo, headInfo, hintsInfo, groupInfo] = await Promise.all([auth, head, hints, group])
  return {
    ...authInfo,
    head: headInfo,
    hints: hintsInfo,
    group: groupInfo
  }
}
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const b4a = require('b4a')
const { DEFAULT_ENCRYPTION } = require('./caps')

const nonce = b4a.alloc(sodium.crypto_stream_NONCEBYTES)

module.exports = class DefaultEncryption {
  static PADDING = 8

  constructor(encryptionKey, hypercoreKey, opts = {}) {
    this.key = encryptionKey
    this.compat = opts.compat === true

    const keys = DefaultEncryption.deriveKeys(encryptionKey, hypercoreKey, opts)

    this.blockKey = keys.block
    this.blindingKey = keys.blinding
  }

  static deriveKeys(encryptionKey, hypercoreKey, { block = false, compat = false } = {}) {
    const subKeys = b4a.alloc(2 * sodium.crypto_stream_KEYBYTES)

    const blockKey = block ? encryptionKey : subKeys.subarray(0, sodium.crypto_stream_KEYBYTES)
    const blindingKey = subKeys.subarray(sodium.crypto_stream_KEYBYTES)

    if (!block) {
      if (compat) {
        sodium.crypto_generichash_batch(blockKey, [encryptionKey], hypercoreKey)
      } else {
        sodium.crypto_generichash_batch(blockKey, [DEFAULT_ENCRYPTION, hypercoreKey, encryptionKey])
      }
    }

    sodium.crypto_generichash(blindingKey, blockKey)

    return {
      blinding: blindingKey,
      block: blockKey
    }
  }

  static blockEncryptionKey(hypercoreKey, encryptionKey) {
    const blockKey = b4a.alloc(sodium.crypto_stream_KEYBYTES)
    sodium.crypto_generichash_batch(blockKey, [DEFAULT_ENCRYPTION, hypercoreKey, encryptionKey])
    return blockKey
  }

  static encrypt(index, block, fork, blockKey, blindingKey) {
    const padding = block.subarray(0, DefaultEncryption.PADDING)
    block = block.subarray(DefaultEncryption.PADDING)

    c.uint64.encode({ start: 0, end: 8, buffer: padding }, fork)
    c.uint64.encode({ start: 0, end: 8, buffer: nonce }, index)

    // Zero out any previous padding.
    nonce.fill(0, 8, 8 + padding.byteLength)

    // Blind the fork ID, possibly risking reusing the nonce on a reorg of the
    // Hypercore. This is fine as the blinding is best-effort and the latest
    // fork ID shared on replication anyway.
    sodium.crypto_stream_xor(padding, padding, nonce, blindingKey)

    nonce.set(padding, 8)

    // The combination of a (blinded) fork ID and a block index is unique for a
    // given Hypercore and is therefore a valid nonce for encrypting the block.
    sodium.crypto_stream_xor(block, block, nonce, blockKey)
  }

  static decrypt(index, block, blockKey) {
    const padding = block.subarray(0, DefaultEncryption.PADDING)
    block = block.subarray(DefaultEncryption.PADDING)

    c.uint64.encode({ start: 0, end: 8, buffer: nonce }, index)

    nonce.set(padding, 8)

    // Decrypt the block using the blinded fork ID.
    sodium.crypto_stream_xor(block, block, nonce, blockKey)
  }

  encrypt(index, block, fork, core) {
    if (core.compat !== this.compat) this._reload(core)
    return DefaultEncryption.encrypt(index, block, fork, this.blockKey, this.blindingKey)
  }

  decrypt(index, block, core) {
    if (core.compat !== this.compat) this._reload(core)
    return DefaultEncryption.decrypt(index, block, this.blockKey)
  }

  padding() {
    return DefaultEncryption.PADDING
  }

  _reload(core) {
    const block = b4a.equals(this.key, this.blockKey)
    const keys = DefaultEncryption.deriveKeys(this.key, core.key, { block, compat: core.compat })

    this.blockKey = keys.blockKey
    this.blindingKey = keys.blindingKey
  }
}
module.exports = class Download {
  constructor(session, range) {
    this.session = session
    this.range = range
    this.request = null
    this.opened = false
    this.opening = this._open()
    this.opening.catch(noop)
  }

  ready() {
    return this.opening
  }

  async _open() {
    if (this.session.opened === false) await this.session.opening
    this._download()
    this.opened = true
  }

  async done() {
    await this.ready()

    try {
      return await this.request.promise
    } catch (err) {
      if (isSessionMoved(err)) return this._download()
      throw err
    }
  }

  _download() {
    const activeRequests = (this.range && this.range.activeRequests) || this.session.activeRequests
    this.request = this.session.core.replicator.addRange(activeRequests, this.range)
    this.request.promise.catch(noop)
    return this.request.promise
  }

  /**
   * Deprecated. Use `range.done()`.
   */
  downloaded() {
    return this.done()
  }

  destroy() {
    this._destroyBackground().catch(noop)
  }

  async _destroyBackground() {
    if (this.opened === false) await this.ready()
    if (this.request.context) this.request.context.detach(this.request)
  }
}

function noop() {}

function isSessionMoved(err) {
  return err.code === 'SESSION_MOVED'
}
module.exports = {
  SMALL_WANTS: 1
}
// this helper is for fully remote proofs, is like in a push notification where no other context exists

const { MerkleTree } = require('./merkle-tree.js')
const messages = require('./messages.js')
const b4a = require('b4a')
const c = require('compact-encoding')
const crypto = require('hypercore-crypto')
const flat = require('flat-tree')

class SlimSession {
  constructor(storage, auth, head, roots) {
    this.fork = head ? head.fork : 0
    this.roots = roots
    this.length = head ? head.length : 0
    this.signature = head ? head.signature : null
    this.ancestors = this.length
    this.byteLength = 0
    this.prologue = auth.manifest.prologue
    this.storage = storage

    for (let i = 0; i < roots.length; i++) this.byteLength += roots[i].size
  }
}

module.exports = { verify, proof }

async function verify(storage, buffer, { referrer = null } = {}) {
  const state = { buffer, start: 0, end: buffer.byteLength }

  const discoveryKey = c.fixed32.decode(state)
  const proof = messages.wire.data.decode(state)

  const result = {
    key: null,
    discoveryKey,
    newer: true,
    length: 0,
    proof,
    block: null
  }

  const core = await storage.resumeCore(discoveryKey)
  if (core === null) return null

  let rx = core.read()
  const authPromise = rx.getAuth()
  const headPromise = rx.getHead()
  const referrerPromise = rx.getUserData('referrer')

  rx.tryFlush()

  const [auth, head, ref] = await Promise.all([authPromise, headPromise, referrerPromise])

  if (auth === null) return null

  if (referrer && (!ref || !b4a.equals(ref, referrer))) return null

  rx = core.read()

  const rootPromises = []

  for (const index of flat.fullRoots(head ? 2 * head.length : 0)) {
    rootPromises.push(rx.getTreeNode(index))
  }

  rx.tryFlush()

  let roots = await Promise.all(rootPromises)
  if (roots.some(isNull)) roots = []

  const length = head ? head.length : 0

  if (!auth.manifest || !auth.manifest.signers.length) return null

  const batch = await MerkleTree.verifyFullyRemote(new SlimSession(core, auth, head, roots), proof)
  const publicKey = auth.manifest.signers[0].publicKey

  let signable = null
  let signature = null

  if (auth.manifest.version === 0) {
    signable = batch.signable(auth.manifest.signers[0].namespace)
    signature = batch.signature
  } else {
    if (batch.signature[0] !== 1) return null
    if (batch.signature[1] !== 0) return null

    signable = batch.signable(auth.key)
    signature = batch.signature.subarray(2, 66)
  }

  if (!crypto.verify(signable, signature, publicKey)) {
    return null
  }

  result.key = auth.key
  result.discoveryKey = discoveryKey
  result.newer = batch.length > length
  result.length = batch.length
  result.block = proof.block

  return result
}

async function proof(sender, { index, block = null, upgrade = null } = {}) {
  const proof = await sender.proof({
    block: block ? { index, nodes: 0 } : null,
    upgrade: upgrade ? upgrade : { start: 0, length: sender.length }
  })

  if (block) proof.block.value = block
  proof.manifest = sender.core.header.manifest

  const state = { buffer: null, start: 0, end: 0 }
  const data = { request: 0, ...proof }

  c.fixed32.preencode(state, sender.discoveryKey)
  messages.wire.data.preencode(state, data)

  state.buffer = b4a.allocUnsafe(state.end)

  c.fixed32.encode(state, sender.discoveryKey)
  messages.wire.data.encode(state, data)

  return state.buffer
}

function isNull(x) {
  return x === null
}
const TICKS = 16

module.exports = class HotswapQueue {
  constructor() {
    this.priorities = [[], [], []]
  }

  *pick(peer) {
    for (let i = 0; i < this.priorities.length; i++) {
      // try first one more than second one etc etc
      let ticks = (this.priorities.length - i) * TICKS
      const queue = this.priorities[i]

      for (let j = 0; j < queue.length; j++) {
        const r = j + Math.floor(Math.random() * queue.length - j)
        const a = queue[j]
        const b = queue[r]

        if (r !== j) {
          queue[(b.hotswap.index = j)] = b
          queue[(a.hotswap.index = r)] = a
        }

        if (hasInflight(b, peer)) continue

        yield b

        if (--ticks <= 0) break
      }
    }
  }

  add(block) {
    if (block.hotswap !== null) this.remove(block)
    if (block.inflight.length === 0 || block.inflight.length >= 3) return

    // TODO: also use other stuff to determine queue prio
    const queue = this.priorities[block.inflight.length - 1]

    const index = queue.push(block) - 1
    block.hotswap = { ref: this, queue, index }
  }

  remove(block) {
    const hotswap = block.hotswap
    if (hotswap === null) return

    block.hotswap = null
    const head = hotswap.queue.pop()
    if (head === block) return
    hotswap.queue[(head.hotswap.index = hotswap.index)] = head
  }
}

function hasInflight(block, peer) {
  for (let j = 0; j < block.inflight.length; j++) {
    if (block.inflight[j].peer === peer) return true
  }
  return false
}
module.exports = class Info {
  constructor(opts = {}) {
    this.key = opts.key
    this.discoveryKey = opts.discoveryKey
    this.length = opts.length || 0
    this.contiguousLength = opts.contiguousLength || 0
    this.byteLength = opts.byteLength || 0
    this.fork = opts.fork || 0
    this.padding = opts.padding || 0
    this.storage = opts.storage || null
  }

  static async from(session, opts = {}) {
    return new Info({
      key: session.key,
      discoveryKey: session.discoveryKey,
      length: session.length,
      contiguousLength: session.contiguousLength,
      byteLength: session.byteLength,
      fork: session.fork,
      padding: session.padding,
      storage: opts.storage ? await this.storage(session) : null
    })
  }

  static async storage(session) {
    const { oplog, tree, blocks, bitfield } = session.core
    try {
      return {
        oplog: await Info.bytesUsed(oplog.storage),
        tree: await Info.bytesUsed(tree.storage),
        blocks: await Info.bytesUsed(blocks.storage),
        bitfield: await Info.bytesUsed(bitfield.storage)
      }
    } catch {
      return null
    }
  }

  static bytesUsed(file) {
    return new Promise((resolve, reject) => {
      file.stat((err, st) => {
        if (err) {
          resolve(0) // prob just file not found (TODO, improve)
        } else if (typeof st.blocks !== 'number') {
          reject(new Error('cannot determine bytes used'))
        } else {
          resolve(st.blocks * 512)
        }
      })
    })
  }
}
const b4a = require('b4a')

module.exports = function (core, depth, opts) {
  let indent = ''
  if (typeof opts.indentationLvl === 'number') {
    while (indent.length < opts.indentationLvl) indent += ' '
  }

  let peers = ''
  const min = Math.min(core.peers.length, 5)

  for (let i = 0; i < min; i++) {
    const peer = core.peers[i]

    peers += `${indent}    Peer(\n`
    peers += `${indent}      remotePublicKey: ${opts.stylize(toHex(peer.remotePublicKey), 'string')}\n`
    peers += `${indent}      remoteLength: ${opts.stylize(peer.remoteLength, 'number')}\n`
    peers += `${indent}      remoteFork: ${opts.stylize(peer.remoteFork, 'number')}\n`
    peers += `${indent}      remoteCanUpgrade: ${opts.stylize(peer.remoteCanUpgrade, 'boolean')}\n`
    peers += `${indent}    )\n`
  }

  if (core.peers.length > 5) {
    peers += `${indent}  ... and ${core.peers.length - 5} more\n`
  }

  if (peers) peers = `[\n${peers}${indent}  ]`
  else peers = `[ ${opts.stylize(0, 'number')} ]`

  return (
    `${core.constructor.name}(\n` +
    `${indent}  id: ${opts.stylize(core.id, 'string')}\n` +
    `${indent}  key: ${opts.stylize(toHex(core.key), 'string')}\n` +
    `${indent}  discoveryKey: ${opts.stylize(toHex(core.discoveryKey), 'string')}\n` +
    `${indent}  opened: ${opts.stylize(core.opened, 'boolean')}\n` +
    `${indent}  closed: ${opts.stylize(core.closed, 'boolean')}\n` +
    `${indent}  snapshotted: ${opts.stylize(core.snapshotted, 'boolean')}\n` +
    `${indent}  writable: ${opts.stylize(core.writable, 'boolean')}\n` +
    `${indent}  length: ${opts.stylize(core.length, 'number')}\n` +
    `${indent}  fork: ${opts.stylize(core.fork, 'number')}\n` +
    `${indent}  sessions: [ ${opts.stylize(core.sessions.length, 'number')} ]\n` +
    `${indent}  activeRequests: [ ${opts.stylize(core.activeRequests.length, 'number')} ]\n` +
    `${indent}  peers: ${peers}\n` +
    `${indent})`
  )
}

function toHex(buf) {
  return buf && b4a.toString(buf, 'hex')
}
const BigSparseArray = require('big-sparse-array')
const { Transform } = require('streamx')
const quickbit = require('./compat').quickbit
const b4a = require('b4a')

const BITS_PER_PAGE = 32768
const BYTES_PER_PAGE = BITS_PER_PAGE / 8

class MarkPage {
  constructor() {
    this.bitfield = null
    this.loaded = new Promise((resolve) => {
      this.load = resolve
    })
  }

  setBitfield(bitfield) {
    this.bitfield = bitfield
    this.load()
  }

  get(index) {
    return quickbit.get(this.bitfield, index)
  }

  set(index, val) {
    quickbit.set(this.bitfield, index, val)
  }
}

module.exports = class MarkBitfield {
  static BITS_PER_PAGE = BITS_PER_PAGE
  static BYTES_PER_PAGE = BYTES_PER_PAGE

  constructor(storage) {
    this.storage = storage
    this._pages = new BigSparseArray()
  }

  async loadPage(pageIndex) {
    const p = this._pages.set(pageIndex, new MarkPage())
    const rx = this.storage.read()
    const pageBuf = rx.getMark(pageIndex)
    rx.tryFlush()
    const bitfield = (await pageBuf) ?? b4a.alloc(BYTES_PER_PAGE)
    await p.setBitfield(bitfield)
    return p
  }

  async get(index) {
    const j = index & (BITS_PER_PAGE - 1)
    const i = (index - j) / BITS_PER_PAGE

    let p = this._pages.get(i)
    if (!p) p = await this.loadPage(i)

    return p.get(j)
  }

  async set(index, val) {
    const j = index & (BITS_PER_PAGE - 1)
    const i = (index - j) / BITS_PER_PAGE

    let p = this._pages.get(i)

    if (!p && val) p = await this.loadPage(i)

    if (p) {
      await p.loaded
      p.set(j, val)
      const tx = this.storage.write()
      tx.putMark(i, p.bitfield)
      await tx.flush()
    }
  }

  async clear() {
    const tx = this.storage.write()
    tx.deleteMarkRange(0, -1)
    await tx.flush()
    this._pages = new BigSparseArray()
  }

  createMarkStream({ reverse = false } = {}) {
    return this.storage.createMarkStream({ reverse }).pipe(
      new Transform({
        transform({ index, page }, cb) {
          let bitIndex = reverse
            ? quickbit.findLast(page, true, BITS_PER_PAGE)
            : quickbit.findFirst(page, true, 0)
          while (bitIndex !== -1) {
            const blockIndex = index * BITS_PER_PAGE + bitIndex
            this.push(blockIndex)

            // Account for `bitIndex` being either causing infinite loop
            if (bitIndex === 0 && reverse) break

            bitIndex = reverse
              ? quickbit.findLast(page, true, bitIndex - 1)
              : quickbit.findFirst(page, true, bitIndex + 1)
          }

          cb(null)
        }
      })
    )
  }
}
const flat = require('flat-tree')
const crypto = require('hypercore-crypto')
const b4a = require('b4a')
const unslab = require('unslab')
const caps = require('./caps')
const {
  INVALID_PROOF,
  INVALID_CHECKSUM,
  INVALID_OPERATION,
  BAD_ARGUMENT,
  ASSERTION
} = require('hypercore-errors')

class NodeQueue {
  constructor(nodes, extra = null) {
    this.i = 0
    this.nodes = nodes
    this.extra = extra
    this.length = nodes.length + (this.extra === null ? 0 : 1)
  }

  shift(index) {
    if (this.extra !== null && this.extra.index === index) {
      const node = this.extra
      this.extra = null
      this.length--
      return node
    }

    if (this.i >= this.nodes.length) {
      throw INVALID_OPERATION('Expected node ' + index + ', got (nil)')
    }

    const node = this.nodes[this.i++]
    if (node.index !== index) {
      throw INVALID_OPERATION('Expected node ' + index + ', got node ' + node.index)
    }

    this.length--
    return node
  }
}

class MerkleTreeBatch {
  constructor(session) {
    this.fork = session.fork
    this.roots = [...session.roots]
    this.length = session.length
    this.signature = session.signature
    this.ancestors = session.length
    this.byteLength = session.byteLength
    this.prologue = session.prologue
    this.hashCached = null

    this.committed = false
    this.truncated = false
    this.treeLength = session.length
    this.treeFork = session.fork
    this.storage = session.storage
    this.session = session
    this.nodes = []
    this.upgraded = false
  }

  checkout(length, additionalRoots) {
    const roots = []
    let r = 0

    const head = 2 * length - 2
    const gaps = new Set()
    const all = new Map()

    // additional roots is so the original roots can be passed (we mutate the array in appendRoot)
    if (additionalRoots) {
      for (const node of additionalRoots) all.set(node.index, node)
    }

    for (const node of this.nodes) all.set(node.index, node)

    for (const index of flat.fullRoots(head + 2)) {
      const left = flat.leftSpan(index)
      if (left !== 0) gaps.add(left - 1)

      if (r < this.roots.length && this.roots[r].index === index) {
        roots.push(this.roots[r++])
        continue
      }
      const node = all.get(index)
      if (!node) throw new BAD_ARGUMENT('root missing for given length')
      roots.push(node)
    }

    this.roots = roots
    this.length = length
    this.byteLength = totalSize(roots)
    this.hashCached = null
    this.signature = null

    for (let i = 0; i < this.nodes.length; i++) {
      const index = this.nodes[i].index
      if (index <= head && !gaps.has(index)) continue
      const last = this.nodes.pop()
      if (i < this.nodes.length) this.nodes[i--] = last
    }
  }

  prune(length) {
    if (length === 0) return

    const head = 2 * length - 2
    const gaps = new Set()

    // TODO: make a function for this in flat-tree
    for (const index of flat.fullRoots(head + 2)) {
      const left = flat.leftSpan(index)
      if (left !== 0) gaps.add(left - 1)
    }

    for (let i = 0; i < this.nodes.length; i++) {
      const index = this.nodes[i].index
      if (index > head || gaps.has(index)) continue
      const last = this.nodes.pop()
      if (i < this.nodes.length) this.nodes[i--] = last
    }
  }

  clone() {
    const b = new MerkleTreeBatch(this.session)

    b.fork = this.fork
    b.roots = [...this.roots]
    b.length = this.length
    b.byteLength = this.byteLength
    b.signature = this.signature
    b.treeLength = this.treeLength
    b.treeFork = this.treeFork
    b.tree = this.tree
    b.nodes = [...this.nodes]
    b.upgraded = this.upgraded

    return b
  }

  hash() {
    if (this.hashCached === null) this.hashCached = unslab(crypto.tree(this.roots))
    return this.hashCached
  }

  signable(manifestHash) {
    return caps.treeSignable(manifestHash, this.hash(), this.length, this.fork)
  }

  signableCompat(noHeader) {
    return caps.treeSignableCompat(this.hash(), this.length, this.fork, noHeader)
  }

  get(index) {
    if (index >= this.length * 2) {
      return null
    }

    for (const n of this.nodes) {
      if (n.index === index) return n
    }

    return getTreeNodeFromStorage(this.session.storage, index)
  }

  // deprecated, use sssion proof instead
  proof(batch, { block, hash, seek, upgrade }) {
    return generateProof(this.session, batch, block, hash, seek, upgrade)
  }

  verifyUpgrade(proof) {
    const unverified = verifyTree(proof, this.nodes)

    if (!proof.upgrade) throw INVALID_OPERATION('Expected upgrade proof')

    return verifyUpgrade(proof, unverified, this)
  }

  addNodesUnsafe(nodes) {
    for (let i = 0; i < nodes.length; i++) {
      this.nodes.push(nodes[i])
    }
  }

  append(buf) {
    const head = this.length * 2
    const ite = flat.iterator(head)
    const node = blockNode(head, buf)

    this.appendRoot(node, ite)
  }

  appendRoot(node, ite) {
    node = unslabNode(node)
    this.hashCached = null
    this.upgraded = true
    this.length += ite.factor / 2
    this.byteLength += node.size
    this.roots.push(node)
    this.nodes.push(node)

    while (this.roots.length > 1) {
      const a = this.roots[this.roots.length - 1]
      const b = this.roots[this.roots.length - 2]

      // TODO: just have a peek sibling instead? (pretty sure it's always the left sib as well)
      if (ite.sibling() !== b.index) {
        ite.sibling() // unset so it always points to last root
        break
      }

      const node = unslabNode(parentNode(ite.parent(), a, b))
      this.nodes.push(node)
      this.roots.pop()
      this.roots.pop()
      this.roots.push(node)
    }
  }

  commitable() {
    return (
      this.treeFork === this.session.fork &&
      (this.upgraded
        ? this.treeLength === this.session.length
        : this.treeLength <= this.session.length)
    )
  }

  commit(tx) {
    if (tx === undefined) throw INVALID_OPERATION('No database batch was passed')

    if (this.session.core._repairMode) {
      throw ASSERTION('Cannot commit while repair mode is on')
    }

    if (!this.commitable()) {
      throw INVALID_OPERATION('Tree was modified during batch, refusing to commit')
    }

    if (this.upgraded) this._commitUpgrade(tx)

    for (let i = 0; i < this.nodes.length; i++) {
      const node = this.nodes[i]
      tx.putTreeNode(node)
    }

    this.committed = true

    return this
  }

  _commitUpgrade(tx) {
    // TODO: If easy to detect, we should refuse an trunc+append here without a fork id
    // change. Will only happen on user error so mostly to prevent that.

    if (this.ancestors < this.treeLength) {
      tx.deleteTreeNodeRange(this.ancestors * 2, this.treeLength * 2)

      if (this.ancestors > 0) {
        const head = this.ancestors * 2
        const ite = flat.iterator(head - 2)

        while (true) {
          if (ite.contains(head) && ite.index < head) {
            tx.deleteTreeNode(ite.index)
          }
          if (ite.offset === 0) break
          ite.parent()
        }

        this.truncated = true
      }
    }
  }

  seek(bytes, padding) {
    return new ByteSeeker(this, this, bytes, padding)
  }

  byteRange(index) {
    const rx = this.storage.read()
    const range = getByteRange(this, index, rx)
    rx.tryFlush()

    return range
  }

  byteOffset(index) {
    if (index === 2 * this.length) return this.byteLength

    const rx = this.storage.read()
    const offset = getByteOffset(this, index, rx)
    rx.tryFlush()

    return offset
  }

  async downgrade() {
    if (!this.upgraded) return true

    const rx = this.storage.read()
    const nodePromises = []

    for (const r of this.roots) {
      nodePromises.push(rx.getTreeNode(r.index))
    }

    rx.tryFlush()

    const nodes = await Promise.all(nodePromises)

    for (let i = 0; i < this.roots.length; i++) {
      const root = this.roots[i]
      const node = nodes[i]

      if (!node) return false
      if (!b4a.equals(node.hash, root.hash)) return false
    }

    this.upgraded = false
    return true
  }

  async restore(length) {
    if (length === this.length) return this

    const roots = unslabNodes(await MerkleTree.getRootsFromStorage(this.storage, length))

    this.roots = roots
    this.length = length
    this.byteLength = totalSize(roots)
    this.ancestors = length

    for (const node of roots) this.byteLength += node.size

    return this
  }
}

class ReorgBatch extends MerkleTreeBatch {
  constructor(session) {
    super(session)

    this.roots = []
    this.length = 0
    this.byteLength = 0
    this.diff = null
    this.ancestors = 0
    // We set upgraded because reorgs are signed so hit will
    // hit the same code paths (like the treeLength check in commit)
    this.upgraded = true
    this.want = {
      nodes: 0,
      start: 0,
      end: 0
    }
  }

  get finished() {
    return this.want === null
  }

  update(proof) {
    if (this.want === null) return true

    const nodes = []
    const root = verifyTree(proof, nodes)

    if (root === null || !b4a.equals(root.hash, this.diff.hash)) return false

    this.nodes.push(...nodes)
    return this._update(nodes)
  }

  async _update(nodes) {
    const n = new Map()
    for (const node of nodes) n.set(node.index, node)

    let diff = null
    const ite = flat.iterator(this.diff.index)
    const startingDiff = this.diff

    while ((ite.index & 1) !== 0) {
      const left = n.get(ite.leftChild())
      if (!left) break

      const existing = await getTreeNodeFromStorage(this.session.storage, left.index)
      if (!existing || !b4a.equals(existing.hash, left.hash)) {
        diff = left
      } else {
        diff = n.get(ite.sibling())
      }
    }

    if ((this.diff.index & 1) === 0) return true
    if (diff === null) return false
    if (startingDiff !== this.diff) return false

    return this._updateDiffRoot(diff)
  }

  _updateDiffRoot(diff) {
    if (this.want === null) return true

    const spans = flat.spans(diff.index)
    const start = spans[0] / 2
    const end = Math.min(this.treeLength, spans[1] / 2 + 1)
    const len = end - start

    this.ancestors = start
    this.diff = diff

    if ((diff.index & 1) === 0 || this.want.start >= this.treeLength || len <= 0) {
      this.want = null
      return true
    }

    this.want.start = start
    this.want.end = end
    this.want.nodes = log2(spans[1] - spans[0] + 2) - 1

    return false
  }
}

class ByteSeeker {
  constructor(session, bytes, padding = 0) {
    this.session = session
    this.bytes = bytes
    this.padding = padding

    const size = session.byteLength - session.length * padding

    this.start = bytes >= size ? session.length : 0
    this.end = bytes < size ? session.length : 0
  }

  async _seek(bytes) {
    if (!bytes) return [0, 0]

    for (const node of this.session.roots) {
      // all async ticks happen once we find the root so safe
      const size = getUnpaddedSize(node, this.padding, null)

      if (bytes === size) return [flat.rightSpan(node.index) + 2, 0]
      if (bytes > size) {
        bytes -= size
        continue
      }

      const ite = flat.iterator(node.index)

      while ((ite.index & 1) !== 0) {
        const l = await getTreeNodeFromStorage(this.session.storage, ite.leftChild())

        if (l) {
          const size = getUnpaddedSize(l, this.padding, ite)

          if (size === bytes) return [ite.rightSpan() + 2, 0]
          if (size > bytes) continue
          bytes -= size
          ite.sibling()
        } else {
          ite.parent()
          return [ite.index, bytes]
        }
      }

      return [ite.index, bytes]
    }

    return null
  }

  async update() {
    // TODO: combine _seek and this, much simpler
    const res = await this._seek(this.bytes)
    if (!res) return null
    if ((res[0] & 1) === 0) return [res[0] / 2, res[1]]

    const span = flat.spans(res[0])
    this.start = span[0] / 2
    this.end = span[1] / 2 + 1

    return null
  }
}

class TreeProof {
  constructor(session, block, hash, seek, upgrade) {
    this.fork = session.fork
    this.signature = session.signature

    this.block = block
    this.hash = hash
    this.seek = seek
    this.upgrade = upgrade

    this.pending = {
      node: null,
      seek: null,
      upgrade: null,
      additionalUpgrade: null
    }
  }

  async settle() {
    const result = {
      fork: this.fork,
      block: null,
      hash: null,
      seek: null,
      upgrade: null,
      manifest: null
    }

    const [pNode, pSeek, pUpgrade, pAdditional] = await settleProof(this.pending)

    if (this.block) {
      if (pNode === null) throw INVALID_OPERATION('Invalid block request')
      result.block = {
        index: this.block.index,
        value: null, // populated upstream, alloc it here for simplicity
        nodes: pNode
      }
    } else if (this.hash) {
      if (pNode === null) throw INVALID_OPERATION('Invalid block request')
      result.hash = {
        index: this.hash.index,
        nodes: pNode
      }
    }

    if (this.seek && pSeek !== null) {
      result.seek = {
        bytes: this.seek.bytes,
        nodes: pSeek
      }
    }

    if (this.upgrade) {
      result.upgrade = {
        start: this.upgrade.start,
        length: this.upgrade.length,
        nodes: pUpgrade,
        additionalNodes: pAdditional || [],
        signature: this.signature
      }
    }

    return result
  }
}

class MerkleTree {
  static hash(s) {
    return unslab(crypto.tree(s.roots))
  }

  static signable(s, namespace) {
    return caps.treeSignable(namespace, MerkleTree.hash(s), s.length, s.fork)
  }

  static size(roots) {
    return totalSize(roots)
  }

  static span(roots) {
    return totalSpan(roots)
  }

  static getRoots(session, length) {
    return MerkleTree.getRootsFromStorage(session.storage, length)
  }

  static getRootsFromStorage(storage, length) {
    const indexes = flat.fullRoots(2 * length)
    const roots = new Array(indexes.length)
    const rx = storage.read()

    for (let i = 0; i < indexes.length; i++) {
      roots[i] = getTreeNodeOrError(rx, indexes[i])
    }

    rx.tryFlush()

    return Promise.all(roots)
  }

  static async upgradeable(session, length) {
    const indexes = flat.fullRoots(2 * length)
    const roots = new Array(indexes.length)
    const rx = session.storage.read()

    for (let i = 0; i < indexes.length; i++) {
      roots[i] = rx.getTreeNode(indexes[i])
    }

    rx.tryFlush()

    for (const node of await Promise.all(roots)) {
      if (node === null) return false
    }

    return true
  }

  static seek(session, bytes, padding) {
    return new ByteSeeker(session, bytes, padding)
  }

  static get(session, index) {
    return getTreeNodeFromStorage(session.storage, index)
  }

  static async truncate(session, length, batch, fork = batch.fork) {
    const head = length * 2
    const fullRoots = flat.fullRoots(head)

    for (let i = 0; i < fullRoots.length; i++) {
      const root = fullRoots[i]
      if (i < batch.roots.length && batch.roots[i].index === root) continue

      while (batch.roots.length > i) batch.roots.pop()
      batch.roots.push(unslabNode(await getTreeNodeFromStorageOrError(session.storage, root)))
    }

    while (batch.roots.length > fullRoots.length) {
      batch.roots.pop()
    }

    batch.fork = fork
    batch.length = length
    batch.ancestors = length
    batch.byteLength = totalSize(batch.roots)
    batch.upgraded = true

    return batch
  }

  static async reorg(session, proof, batch) {
    let unverified = null

    if (proof.block || proof.hash || proof.seek) {
      unverified = verifyTree(proof, batch.nodes)
    }

    if (!verifyUpgrade(proof, unverified, batch)) {
      throw INVALID_PROOF('Fork proof not verifiable')
    }

    for (const root of batch.roots) {
      const existing = await getTreeNodeFromStorage(session.storage, root.index)
      if (existing && b4a.equals(existing.hash, root.hash)) continue
      batch._updateDiffRoot(root)
      break
    }

    if (batch.diff !== null) {
      await batch._update(batch.nodes)
    } else {
      batch.want = null
      batch.ancestors = batch.length
    }

    return batch
  }

  static verifyFullyRemote(session, proof) {
    // TODO: impl this less hackishly
    const batch = new MerkleTreeBatch(session)

    batch.fork = proof.fork
    batch.roots = []
    batch.length = 0
    batch.ancestors = 0
    batch.byteLength = 0

    let unverified = verifyTree(proof, batch.nodes)

    if (proof.upgrade) {
      if (verifyUpgrade(proof, unverified, batch)) {
        unverified = null
      }
    }

    return batch
  }

  static async verify(session, proof) {
    const batch = new MerkleTreeBatch(session)

    let unverified = verifyTree(proof, batch.nodes)

    if (proof.upgrade) {
      if (verifyUpgrade(proof, unverified, batch)) {
        unverified = null
      }
    }

    if (unverified) {
      const verified = await getTreeNodeFromStorageOrError(session.storage, unverified.index)
      if (!b4a.equals(verified.hash, unverified.hash)) {
        throw INVALID_CHECKSUM('Invalid checksum at node ' + unverified.index)
      }
    }

    return batch
  }

  static proof(session, rx, { block, hash, seek, upgrade }) {
    return generateProof(session, rx, block, hash, seek, upgrade)
  }

  static maxMissingNodes(index, length) {
    const head = 2 * length
    const ite = flat.iterator(index)

    // See iterator.rightSpan()
    const iteRightSpan = ite.index + ite.factor / 2 - 1
    // If the index is not in the current tree, we do not know how many missing nodes there are...
    if (iteRightSpan >= head) return 0

    for (const r of flat.fullRoots(head)) {
      if (r === index) return 0
    }

    // need missing nodes not inclusive of index
    ite.parent()

    let cnt = 0
    while (!ite.contains(head)) {
      cnt++
      ite.parent()
    }

    return cnt
  }

  static async missingNodes(session, index, length) {
    const head = 2 * length
    const ite = flat.iterator(index)

    // See iterator.rightSpan()
    const iteRightSpan = ite.index + ite.factor / 2 - 1
    // If the index is not in the current tree, we do not know how many missing nodes there are...
    if (iteRightSpan >= head) return 0

    let cnt = 0
    // TODO: we could prop use a read batch here and do this in blocks of X for perf
    while (!ite.contains(head) && !(await hasTreeNode(session.storage, ite.index))) {
      cnt++
      if (cnt >= 1024) {
        throw ASSERTION('Bad arguments to missingNodes index=' + index + ' at length=' + length)
      }
      ite.parent()
    }

    return cnt
  }

  static byteOffset(session, index) {
    return getByteOffsetSession(session, index, null)
  }

  static byteRange(session, index) {
    const rx = session.storage.read()
    const offset = getByteOffsetSession(session, index, rx)
    const size = getNodeSize(index, rx)
    rx.tryFlush()
    return Promise.all([offset, size])
  }

  static upgradeLength(proof) {
    const extra = proof.additionalNodes

    if (extra.length) {
      const last = extra[extra.length - 1]
      const index = flat.rightSpan(last.index)
      return index / 2 + 1
    }

    return proof.start + proof.length
  }
}

module.exports = {
  MerkleTreeBatch,
  ReorgBatch,
  MerkleTree
}

async function getNodeSize(index, rx) {
  return (await getTreeNodeOrError(rx, index)).size
}

async function getByteOffsetSession(session, index, rx) {
  if (index === 2 * session.length) return session.byteLength

  const treeNodes =
    rx === null
      ? await getByteOffsetBatchFlush(session.roots, index, session.storage.read())
      : await getByteOffsetBatch(session.roots, index, rx)

  let offset = 0
  for (const node of treeNodes) offset += node.size

  return offset
}

async function getByteOffset(tree, index, rx) {
  if (index === 2 * tree.length) return tree.byteLength

  const treeNodes = await getByteOffsetBatch(tree.roots, index, rx)

  let offset = 0
  for (const node of treeNodes) offset += node.size

  return offset
}

function getByteOffsetBatchFlush(roots, index, rx) {
  const treeNodes = getByteOffsetBatch(roots, index, rx)
  rx.tryFlush()
  return treeNodes
}

function getByteOffsetBatch(roots, index, rx) {
  if ((index & 1) === 1) index = flat.leftSpan(index)

  let head = 0
  let cnt = 0

  const promises = []

  for (const node of roots) {
    // all async ticks happen once we find the root so safe
    head += 2 * (node.index - head + 1)

    if (index >= head) {
      promises.push(node.size)
      continue
    }

    const ite = flat.iterator(node.index)

    while (ite.index !== index) {
      if (++cnt >= 1024) throw ASSERTION('Bad getByteOffsetSession index=' + index)

      if (index < ite.index) {
        ite.leftChild()
      } else {
        promises.push(getTreeNodeOrError(rx, ite.leftChild()))
        ite.sibling()
      }
    }

    return Promise.all(promises)
  }

  throw ASSERTION('Failed to find offset')
}

function getByteRange(tree, index, rx) {
  const head = 2 * tree.length
  if (((index & 1) === 0 ? index : flat.rightSpan(index)) >= head) {
    throw BAD_ARGUMENT('Index is out of bounds')
  }

  const offset = getByteOffset(tree, index, rx)
  const size = getNodeSize(index, rx)

  return Promise.all([offset, size])
}

// All the methods needed for proof verification

function verifyTree({ block, hash, seek }, nodes) {
  const untrustedNode = block
    ? { index: 2 * block.index, value: block.value, nodes: block.nodes }
    : hash
      ? { index: hash.index, value: null, nodes: hash.nodes }
      : null

  if (untrustedNode === null && (!seek || !seek.nodes.length)) return null

  let root = null

  if (seek && seek.nodes.length) {
    const ite = flat.iterator(seek.nodes[0].index)
    const q = new NodeQueue(seek.nodes)

    root = q.shift(ite.index)
    nodes.push(root)

    while (q.length > 0) {
      const node = q.shift(ite.sibling())

      root = parentNode(ite.parent(), root, node)
      nodes.push(node)
      nodes.push(root)
    }
  }

  if (untrustedNode === null) return root

  const ite = flat.iterator(untrustedNode.index)
  const blockHash = untrustedNode.value && blockNode(ite.index, untrustedNode.value)

  const q = new NodeQueue(untrustedNode.nodes, root)

  root = blockHash || q.shift(ite.index)
  nodes.push(root)

  while (q.length > 0) {
    const node = q.shift(ite.sibling())

    root = parentNode(ite.parent(), root, node)
    nodes.push(node)
    nodes.push(root)
  }

  return root
}

function verifyUpgrade({ fork, upgrade }, blockRoot, batch) {
  const prologue = batch.prologue

  if (prologue) {
    const { start, length } = upgrade
    if (start < prologue.length && (start !== 0 || length < prologue.length)) {
      throw INVALID_PROOF('Upgrade does not satisfy prologue')
    }
  }

  const q = new NodeQueue(upgrade.nodes, blockRoot)

  let grow = batch.roots.length > 0
  let i = 0

  const to = 2 * (upgrade.start + upgrade.length)
  const ite = flat.iterator(0)

  for (; ite.fullRoot(to); ite.nextTree()) {
    if (i < batch.roots.length && batch.roots[i].index === ite.index) {
      i++
      continue
    }

    if (grow) {
      grow = false
      const root = ite.index
      if (i < batch.roots.length) {
        ite.seek(batch.roots[batch.roots.length - 1].index)
        while (ite.index !== root) {
          batch.appendRoot(q.shift(ite.sibling()), ite)
        }
        continue
      }
    }

    batch.appendRoot(q.shift(ite.index), ite)
  }

  if (prologue && batch.length === prologue.length) {
    if (!b4a.equals(prologue.hash, batch.hash())) {
      throw INVALID_PROOF('Invalid hash')
    }
  }

  const extra = upgrade.additionalNodes

  ite.seek(batch.roots[batch.roots.length - 1].index)
  i = 0

  while (i < extra.length && extra[i].index === ite.sibling()) {
    batch.appendRoot(extra[i++], ite)
  }

  while (i < extra.length) {
    const node = extra[i++]

    while (node.index !== ite.index) {
      if (ite.factor === 2) throw INVALID_OPERATION('Unexpected node: ' + node.index)
      ite.leftChild()
    }

    batch.appendRoot(node, ite)
    ite.sibling()
  }

  batch.signature = unslab(upgrade.signature)
  batch.fork = fork

  return q.extra === null
}

async function seekFromHead(session, head, bytes, padding) {
  const roots = flat.fullRoots(head)

  for (let i = 0; i < roots.length; i++) {
    const root = roots[i]
    const node = await getTreeNodeFromStorage(session.storage, root)
    const size = getUnpaddedSize(node, padding, null)

    if (bytes === size) return root
    if (bytes > size) {
      bytes -= size
      continue
    }

    return seekTrustedTree(session, root, bytes, padding)
  }

  return head
}

// trust that bytes are within the root tree and find the block at bytes

async function seekTrustedTree(session, root, bytes, padding) {
  if (!bytes) return root

  const ite = flat.iterator(root)
  let cnt = 0

  while ((ite.index & 1) !== 0) {
    if (++cnt >= 1024) throw ASSERTION('Bad seekTrusted bytes=' + bytes + ', paddding=' + padding)
    const l = await getTreeNodeFromStorage(session.storage, ite.leftChild())

    if (l) {
      const size = getUnpaddedSize(l, padding, ite)
      if (size === bytes) return ite.index
      if (size > bytes) continue
      bytes -= size
      ite.sibling()
    } else {
      ite.parent()
      return ite.index
    }
  }

  return ite.index
}

// try to find the block at bytes without trusting that is *is* within the root passed

async function seekUntrustedTree(session, root, bytes, padding) {
  const offset =
    (await getByteOffsetSession(session, root, null)) -
    (padding ? (padding * flat.leftSpan(root)) / 2 : 0)

  if (offset > bytes) throw INVALID_OPERATION('Invalid seek')
  if (offset === bytes) return root

  bytes -= offset

  const node = await getTreeNodeFromStorageOrError(session.storage, root)

  if (getUnpaddedSize(node, padding, null) <= bytes) throw INVALID_OPERATION('Invalid seek')

  return seekTrustedTree(session, root, bytes, padding)
}

// Below is proof production, ie, construct proofs to verify a request
// Note, that all these methods are sync as we can statically infer which nodes
// are needed for the remote to verify given they arguments they passed us

function seekProof(session, rx, seekRoot, root, p) {
  const ite = flat.iterator(seekRoot)
  let cnt = 0

  p.seek = []
  p.seek.push(getTreeNodeOrError(rx, ite.index))

  while (ite.index !== root) {
    if (++cnt >= 1024) throw ASSERTION('Bad seekProof seekRoot=' + seekRoot + ', root=' + root)
    ite.sibling()
    p.seek.push(getTreeNodeOrError(rx, ite.index))
    ite.parent()
  }
}

function blockAndSeekProof(session, rx, node, seek, seekRoot, root, p) {
  if (!node) return seekProof(session, rx, seekRoot, root, p)

  const ite = flat.iterator(node.index)
  let cnt = 0

  p.node = []
  if (!node.value) p.node.push(getTreeNodeOrError(rx, ite.index))

  while (ite.index !== root) {
    if (++cnt >= 1024) {
      throw ASSERTION('Bad blockAndSeekProof seekRoot=' + seekRoot + ', root=' + root)
    }
    ite.sibling()

    if (seek && ite.contains(seekRoot) && ite.index !== seekRoot) {
      seekProof(session, rx, seekRoot, ite.index, p)
    } else {
      p.node.push(getTreeNodeOrError(rx, ite.index))
    }

    ite.parent()
  }
}

function upgradeProof(session, rx, node, seek, from, to, subTree, p) {
  if (from === 0) p.upgrade = []

  for (const ite = flat.iterator(0); ite.fullRoot(to); ite.nextTree()) {
    // check if they already have the node
    if (ite.index + ite.factor / 2 < from) continue

    // connect existing tree
    if (p.upgrade === null && ite.contains(from - 2)) {
      p.upgrade = []

      const root = ite.index
      const target = from - 2
      let cnt = 0

      ite.seek(target)

      while (ite.index !== root) {
        if (++cnt >= 1024) throw ASSERTION('Bad upgradeProof target=' + target + ', root=' + root)

        ite.sibling()
        if (ite.index > target) {
          if (p.node === null && p.seek === null && ite.contains(subTree)) {
            blockAndSeekProof(session, rx, node, seek, subTree, ite.index, p)
          } else {
            p.upgrade.push(getTreeNodeOrError(rx, ite.index))
          }
        }
        ite.parent()
      }

      continue
    }

    if (p.upgrade === null) {
      p.upgrade = []
    }

    // if the subtree included is a child of this tree, include that one
    // instead of a dup node
    if (p.node === null && p.seek === null && ite.contains(subTree)) {
      blockAndSeekProof(session, rx, node, seek, subTree, ite.index, p)
      continue
    }

    // add root (can be optimised since the root might be in tree.roots)
    p.upgrade.push(getTreeNodeOrError(rx, ite.index))
  }
}

function additionalUpgradeProof(session, rx, from, to, p) {
  if (from === 0) p.additionalUpgrade = []

  for (const ite = flat.iterator(0); ite.fullRoot(to); ite.nextTree()) {
    // check if they already have the node
    if (ite.index + ite.factor / 2 < from) continue

    // connect existing tree
    if (p.additionalUpgrade === null && ite.contains(from - 2)) {
      p.additionalUpgrade = []

      const root = ite.index
      const target = from - 2
      let cnt = 0

      ite.seek(target)

      while (ite.index !== root) {
        if (++cnt >= 1024) {
          throw ASSERTION(
            'Bad arguments to additionalUpgradeProof root=' + root + ' target=' + target
          )
        }
        ite.sibling()
        if (ite.index > target) {
          p.additionalUpgrade.push(getTreeNodeOrError(rx, ite.index))
        }
        ite.parent()
      }

      continue
    }

    if (p.additionalUpgrade === null) {
      p.additionalUpgrade = []
    }

    // add root (can be optimised since the root is in tree.roots)
    p.additionalUpgrade.push(getTreeNodeOrError(rx, ite.index))
  }
}

function nodesToRoot(index, nodes, head) {
  const ite = flat.iterator(index)

  for (let i = 0; i < nodes; i++) {
    ite.parent()
    if (ite.contains(head)) throw INVALID_OPERATION('Nodes is out of bounds')
  }

  return ite.index
}

function totalSize(nodes) {
  let s = 0
  for (const node of nodes) s += node.size
  return s
}

function totalSpan(nodes) {
  let s = 0
  for (const node of nodes) s += 2 * (node.index - s + 1)
  return s
}

function blockNode(index, value) {
  return { index, size: value.byteLength, hash: crypto.data(value) }
}

function parentNode(index, a, b) {
  return { index, size: a.size + b.size, hash: crypto.parent(a, b) }
}

function log2(n) {
  let res = 1

  while (n > 2) {
    n /= 2
    res++
  }

  return res
}

function normalizeIndexed(block, hash) {
  if (block) {
    return {
      value: true,
      index: block.index * 2,
      nodes: block.nodes,
      lastIndex: block.index
    }
  }
  if (hash) {
    return {
      value: false,
      index: hash.index,
      nodes: hash.nodes,
      lastIndex: flat.rightSpan(hash.index) / 2
    }
  }
  return null
}

async function getTreeNodeOrError(rx, index) {
  const node = await rx.getTreeNode(index)
  if (node === null) {
    throw INVALID_OPERATION('Expected tree node ' + index + ' from storage, got (nil)')
  }
  return node
}

function getTreeNodeFromStorageOrError(storage, index) {
  const rx = storage.read()
  const p = getTreeNodeOrError(rx, index)
  rx.tryFlush()
  return p
}

function getTreeNodeFromStorage(storage, index) {
  const rx = storage.read()
  const node = rx.getTreeNode(index)
  rx.tryFlush()
  return node
}

function hasTreeNode(storage, index) {
  const rx = storage.read()
  const has = rx.hasTreeNode(index)
  rx.tryFlush()
  return has
}

async function settleProof(p) {
  const result = [
    p.node && Promise.all(p.node),
    p.seek && Promise.all(p.seek),
    p.upgrade && Promise.all(p.upgrade),
    p.additionalUpgrade && Promise.all(p.additionalUpgrade)
  ]

  try {
    return await Promise.all(result)
  } catch (err) {
    if (p.node) await Promise.allSettled(p.node)
    if (p.seek) await Promise.allSettled(p.seek)
    if (p.upgrade) await Promise.allSettled(p.upgrade)
    if (p.additionalUpgrade) await Promise.allSettled(p.additionalUpgrade)
    throw err
  }
}

// tree can be either the merkle tree or a merkle tree batch
async function generateProof(session, rx, block, hash, seek, upgrade) {
  // Important that this does not throw inbetween making the promise arrays
  // and finalise being called, otherwise there will be lingering promises in the background

  if (session.prologue && upgrade) {
    upgrade.start = upgrade.start < session.prologue.length ? 0 : upgrade.start
    upgrade.length =
      upgrade.start < session.prologue.length ? session.prologue.length : upgrade.length
  }

  const head = 2 * session.length
  const from = upgrade ? upgrade.start * 2 : 0
  const to = upgrade ? from + upgrade.length * 2 : head
  const node = normalizeIndexed(block, hash)

  // can't do anything as we have no data...
  if (head === 0) return new TreeProof(session, null, null, null, null)

  if (from >= to || to > head) {
    throw INVALID_OPERATION('Invalid upgrade')
  }
  if (seek && upgrade && node !== null && node.index >= from) {
    throw INVALID_OPERATION('Cannot both do a seek and block/hash request when upgrading')
  }

  let subTree = head

  const p = new TreeProof(session, block, hash, seek, upgrade)

  if (node !== null && (!upgrade || node.lastIndex < upgrade.start)) {
    subTree = nodesToRoot(node.index, node.nodes, to)
    const seekRoot = seek
      ? await seekUntrustedTree(session, subTree, seek.bytes, seek.padding)
      : head
    blockAndSeekProof(session, rx, node, seek, seekRoot, subTree, p.pending)
  } else if ((node || seek) && upgrade) {
    subTree = seek ? await seekFromHead(session, to, seek.bytes, seek.padding) : node.index
  }

  if (upgrade) {
    upgradeProof(session, rx, node, seek, from, to, subTree, p.pending)
    if (head > to) additionalUpgradeProof(session, rx, to, head, p.pending)
  }

  return p
}

function getUnpaddedSize(node, padding, ite) {
  return padding === 0
    ? node.size
    : node.size - padding * (ite ? ite.countLeaves() : flat.countLeaves(node.index))
}

function unslabNodes(nodes) {
  for (const node of nodes) unslabNode(node)
  return nodes
}

function unslabNode(node) {
  if (node === null) return node
  node.hash = unslab(node.hash)
  return node
}
const c = require('compact-encoding')
const { DEFAULT_NAMESPACE } = require('./caps')
const { INVALID_OPLOG_VERSION } = require('hypercore-errors')
const unslab = require('unslab')

const MANIFEST_PATCH = 0b00000001
const MANIFEST_PROLOGUE = 0b00000010
const MANIFEST_LINKED = 0b00000100
const MANIFEST_USER_DATA = 0b00001000

const hashes = {
  preencode(state, m) {
    state.end++ // small uint
  },
  encode(state, m) {
    if (m === 'blake2b') {
      c.uint.encode(state, 0)
      return
    }

    throw new Error('Unknown hash: ' + m)
  },
  decode(state) {
    const n = c.uint.decode(state)
    if (n === 0) return 'blake2b'
    throw new Error('Unknown hash id: ' + n)
  }
}

const signatures = {
  preencode(state, m) {
    state.end++ // small uint
  },
  encode(state, m) {
    if (m === 'ed25519') {
      c.uint.encode(state, 0)
      return
    }

    throw new Error('Unknown signature: ' + m)
  },
  decode(state) {
    const n = c.uint.decode(state)
    if (n === 0) return 'ed25519'
    throw new Error('Unknown signature id: ' + n)
  }
}

const signer = {
  preencode(state, m) {
    signatures.preencode(state, m.signature)
    c.fixed32.preencode(state, m.namespace)
    c.fixed32.preencode(state, m.publicKey)
  },
  encode(state, m) {
    signatures.encode(state, m.signature)
    c.fixed32.encode(state, m.namespace)
    c.fixed32.encode(state, m.publicKey)
  },
  decode(state) {
    return {
      signature: signatures.decode(state),
      namespace: c.fixed32.decode(state),
      publicKey: c.fixed32.decode(state)
    }
  }
}

const signerArray = c.array(signer)

const prologue = {
  preencode(state, p) {
    c.fixed32.preencode(state, p.hash)
    c.uint.preencode(state, p.length)
  },
  encode(state, p) {
    c.fixed32.encode(state, p.hash)
    c.uint.encode(state, p.length)
  },
  decode(state) {
    return {
      hash: c.fixed32.decode(state),
      length: c.uint.decode(state)
    }
  }
}

const manifestv0 = {
  preencode(state, m) {
    hashes.preencode(state, m.hash)
    state.end++ // type

    if (m.prologue && m.signers.length === 0) {
      c.fixed32.preencode(state, m.prologue.hash)
      return
    }

    if (m.quorum === 1 && m.signers.length === 1 && !m.allowPatch) {
      signer.preencode(state, m.signers[0])
    } else {
      state.end++ // flags
      c.uint.preencode(state, m.quorum)
      signerArray.preencode(state, m.signers)
    }
  },
  encode(state, m) {
    hashes.encode(state, m.hash)

    if (m.prologue && m.signers.length === 0) {
      c.uint.encode(state, 0)
      c.fixed32.encode(state, m.prologue.hash)
      return
    }

    if (m.quorum === 1 && m.signers.length === 1 && !m.allowPatch) {
      c.uint.encode(state, 1)
      signer.encode(state, m.signers[0])
    } else {
      c.uint.encode(state, 2)
      c.uint.encode(state, m.allowPatch ? 1 : 0)
      c.uint.encode(state, m.quorum)
      signerArray.encode(state, m.signers)
    }
  },
  decode(state) {
    const hash = hashes.decode(state)
    const type = c.uint.decode(state)

    if (type > 2) throw new Error('Unknown type: ' + type)

    if (type === 0) {
      return {
        version: 0,
        hash,
        allowPatch: false,
        quorum: 0,
        signers: [],
        prologue: {
          hash: c.fixed32.decode(state),
          length: 0
        },
        linked: null,
        userData: null
      }
    }

    if (type === 1) {
      return {
        version: 0,
        hash,
        allowPatch: false,
        quorum: 1,
        signers: [signer.decode(state)],
        prologue: null,
        linked: null,
        userData: null
      }
    }

    const flags = c.uint.decode(state)

    return {
      version: 0,
      hash,
      allowPatch: (flags & 1) !== 0,
      quorum: c.uint.decode(state),
      signers: signerArray.decode(state),
      prologue: null,
      linked: null,
      userData: null
    }
  }
}

const fixed32Array = c.array(c.fixed32)

const manifest = (exports.manifest = {
  preencode(state, m) {
    state.end++ // version

    if (m.version === 0) return manifestv0.preencode(state, m)

    state.end++ // flags
    hashes.preencode(state, m.hash)

    c.uint.preencode(state, m.quorum)
    signerArray.preencode(state, m.signers)

    if (m.prologue) prologue.preencode(state, m.prologue)
    if (m.linked) fixed32Array.preencode(state, m.linked)
    if (m.userData) c.buffer.preencode(state, m.userData)
  },
  encode(state, m) {
    c.uint.encode(state, m.version)

    if (m.version === 0) return manifestv0.encode(state, m)

    let flags = 0
    if (m.allowPatch) flags |= MANIFEST_PATCH
    if (m.prologue) flags |= MANIFEST_PROLOGUE
    if (m.linked) flags |= MANIFEST_LINKED
    if (m.userData) flags |= MANIFEST_USER_DATA

    c.uint.encode(state, flags)
    hashes.encode(state, m.hash)

    c.uint.encode(state, m.quorum)
    signerArray.encode(state, m.signers)

    if (m.prologue) prologue.encode(state, m.prologue)
    if (m.linked) fixed32Array.encode(state, m.linked)
    if (m.userData) c.buffer.encode(state, m.userData)
  },
  decode(state) {
    const version = c.uint.decode(state)

    if (version === 0) return manifestv0.decode(state)
    if (version > 2) throw new Error('Unknown version: ' + version)

    const flags = c.uint.decode(state)
    const hash = hashes.decode(state)
    const quorum = c.uint.decode(state)
    const signers = signerArray.decode(state)

    const hasPatch = (flags & MANIFEST_PATCH) !== 0
    const hasPrologue = (flags & MANIFEST_PROLOGUE) !== 0
    const hasLinked = (flags & MANIFEST_LINKED) !== 0
    const hasUserData = (flags & MANIFEST_USER_DATA) !== 0

    return {
      version,
      hash,
      allowPatch: hasPatch,
      quorum,
      signers,
      prologue: hasPrologue ? prologue.decode(state) : null,
      linked: hasLinked ? fixed32Array.decode(state) : null,
      userData: hasUserData ? c.buffer.decode(state) : null
    }
  }
})

const node = {
  preencode(state, n) {
    c.uint.preencode(state, n.index)
    c.uint.preencode(state, n.size)
    c.fixed32.preencode(state, n.hash)
  },
  encode(state, n) {
    c.uint.encode(state, n.index)
    c.uint.encode(state, n.size)
    c.fixed32.encode(state, n.hash)
  },
  decode(state) {
    return {
      index: c.uint.decode(state),
      size: c.uint.decode(state),
      hash: c.fixed32.decode(state)
    }
  }
}

const nodeArray = c.array(node)

const wire = (exports.wire = {})

wire.handshake = {
  preencode(state, m) {
    c.uint.preencode(state, 1)
    c.fixed32.preencode(state, m.capability)
  },
  encode(state, m) {
    c.uint.encode(state, m.seeks ? 1 : 0)
    c.fixed32.encode(state, m.capability)
  },
  decode(state) {
    const flags = c.uint.decode(state)
    return {
      seeks: (flags & 1) !== 0,
      capability: unslab(c.fixed32.decode(state))
    }
  }
}

const requestBlock = {
  preencode(state, b) {
    c.uint.preencode(state, b.index)
    c.uint.preencode(state, b.nodes)
  },
  encode(state, b) {
    c.uint.encode(state, b.index)
    c.uint.encode(state, b.nodes)
  },
  decode(state) {
    return {
      index: c.uint.decode(state),
      nodes: c.uint.decode(state)
    }
  }
}

const requestSeek = {
  preencode(state, s) {
    c.uint.preencode(state, s.bytes)
    c.uint.preencode(state, s.padding)
  },
  encode(state, s) {
    c.uint.encode(state, s.bytes)
    c.uint.encode(state, s.padding)
  },
  decode(state) {
    return {
      bytes: c.uint.decode(state),
      padding: c.uint.decode(state)
    }
  }
}

const requestUpgrade = {
  preencode(state, u) {
    c.uint.preencode(state, u.start)
    c.uint.preencode(state, u.length)
  },
  encode(state, u) {
    c.uint.encode(state, u.start)
    c.uint.encode(state, u.length)
  },
  decode(state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

wire.request = {
  preencode(state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.id)
    c.uint.preencode(state, m.fork)

    if (m.block) requestBlock.preencode(state, m.block)
    if (m.hash) requestBlock.preencode(state, m.hash)
    if (m.seek) requestSeek.preencode(state, m.seek)
    if (m.upgrade) requestUpgrade.preencode(state, m.upgrade)
    if (m.priority) c.uint.preencode(state, m.priority)
  },
  encode(state, m) {
    const flags =
      (m.block ? 1 : 0) |
      (m.hash ? 2 : 0) |
      (m.seek ? 4 : 0) |
      (m.upgrade ? 8 : 0) |
      (m.manifest ? 16 : 0) |
      (m.priority ? 32 : 0)

    c.uint.encode(state, flags)
    c.uint.encode(state, m.id)
    c.uint.encode(state, m.fork)

    if (m.block) requestBlock.encode(state, m.block)
    if (m.hash) requestBlock.encode(state, m.hash)
    if (m.seek) requestSeek.encode(state, m.seek)
    if (m.upgrade) requestUpgrade.encode(state, m.upgrade)
    if (m.priority) c.uint.encode(state, m.priority)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      id: c.uint.decode(state),
      fork: c.uint.decode(state),
      block: flags & 1 ? requestBlock.decode(state) : null,
      hash: flags & 2 ? requestBlock.decode(state) : null,
      seek: flags & 4 ? requestSeek.decode(state) : null,
      upgrade: flags & 8 ? requestUpgrade.decode(state) : null,
      manifest: (flags & 16) !== 0,
      priority: flags & 32 ? c.uint.decode(state) : 0
    }
  }
}

wire.cancel = {
  preencode(state, m) {
    c.uint.preencode(state, m.request)
  },
  encode(state, m) {
    c.uint.encode(state, m.request)
  },
  decode(state, m) {
    return {
      request: c.uint.decode(state)
    }
  }
}

const dataUpgrade = {
  preencode(state, u) {
    c.uint.preencode(state, u.start)
    c.uint.preencode(state, u.length)
    nodeArray.preencode(state, u.nodes)
    nodeArray.preencode(state, u.additionalNodes)
    c.optionalBuffer.preencode(state, u.signature)
  },
  encode(state, u) {
    c.uint.encode(state, u.start)
    c.uint.encode(state, u.length)
    nodeArray.encode(state, u.nodes)
    nodeArray.encode(state, u.additionalNodes)
    c.optionalBuffer.encode(state, u.signature)
  },
  decode(state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state),
      nodes: nodeArray.decode(state),
      additionalNodes: nodeArray.decode(state),
      signature: c.optionalBuffer.decode(state)
    }
  }
}

const dataSeek = {
  preencode(state, s) {
    c.uint.preencode(state, s.bytes)
    nodeArray.preencode(state, s.nodes)
  },
  encode(state, s) {
    c.uint.encode(state, s.bytes)
    nodeArray.encode(state, s.nodes)
  },
  decode(state) {
    return {
      bytes: c.uint.decode(state),
      nodes: nodeArray.decode(state)
    }
  }
}

const dataBlock = {
  preencode(state, b) {
    c.uint.preencode(state, b.index)
    c.buffer.preencode(state, b.value)
    nodeArray.preencode(state, b.nodes)
  },
  encode(state, b) {
    c.uint.encode(state, b.index)
    c.buffer.encode(state, b.value)
    nodeArray.encode(state, b.nodes)
  },
  decode(state) {
    return {
      index: c.uint.decode(state),
      value: c.buffer.decode(state),
      nodes: nodeArray.decode(state)
    }
  }
}

const dataHash = {
  preencode(state, b) {
    c.uint.preencode(state, b.index)
    nodeArray.preencode(state, b.nodes)
  },
  encode(state, b) {
    c.uint.encode(state, b.index)
    nodeArray.encode(state, b.nodes)
  },
  decode(state) {
    return {
      index: c.uint.decode(state),
      nodes: nodeArray.decode(state)
    }
  }
}

wire.data = {
  preencode(state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.request)
    c.uint.preencode(state, m.fork)

    if (m.block) dataBlock.preencode(state, m.block)
    if (m.hash) dataHash.preencode(state, m.hash)
    if (m.seek) dataSeek.preencode(state, m.seek)
    if (m.upgrade) dataUpgrade.preencode(state, m.upgrade)
    if (m.manifest) manifest.preencode(state, m.manifest)
  },
  encode(state, m) {
    const flags =
      (m.block ? 1 : 0) |
      (m.hash ? 2 : 0) |
      (m.seek ? 4 : 0) |
      (m.upgrade ? 8 : 0) |
      (m.manifest ? 16 : 0)

    c.uint.encode(state, flags)
    c.uint.encode(state, m.request)
    c.uint.encode(state, m.fork)

    if (m.block) dataBlock.encode(state, m.block)
    if (m.hash) dataHash.encode(state, m.hash)
    if (m.seek) dataSeek.encode(state, m.seek)
    if (m.upgrade) dataUpgrade.encode(state, m.upgrade)
    if (m.manifest) manifest.encode(state, m.manifest)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      request: c.uint.decode(state),
      fork: c.uint.decode(state),
      block: flags & 1 ? dataBlock.decode(state) : null,
      hash: flags & 2 ? dataHash.decode(state) : null,
      seek: flags & 4 ? dataSeek.decode(state) : null,
      upgrade: flags & 8 ? dataUpgrade.decode(state) : null,
      manifest: flags & 16 ? manifest.decode(state) : null
    }
  }
}

wire.noData = {
  preencode(state, m) {
    c.uint.preencode(state, m.request)
    c.uint.preencode(state, m.reason ? 1 : 0)
    if (m.reason) c.uint.preencode(state, m.reason)
  },
  encode(state, m) {
    c.uint.encode(state, m.request)
    c.uint.encode(state, m.reason ? 1 : 0)
    if (m.reason) c.uint.encode(state, m.reason)
  },
  decode(state, m) {
    const request = c.uint.decode(state)
    const flags = state.start < state.end ? c.uint.decode(state) : 0
    return {
      request,
      reason: flags & 1 ? c.uint.decode(state) : 0
    }
  }
}

// TODO: we should move to having these have a handle like in data, easier since they
// allocate state in practice
wire.want = {
  preencode(state, m) {
    c.uint.preencode(state, m.start)
    c.uint.preencode(state, m.length)

    const flags = m.any ? 1 : 0
    if (flags !== 0) c.uint.preencode(state, flags)
  },
  encode(state, m) {
    c.uint.encode(state, m.start)
    c.uint.encode(state, m.length)

    const flags = m.any ? 1 : 0
    if (flags !== 0) c.uint.encode(state, flags)
  },
  decode(state) {
    const start = c.uint.decode(state)
    const length = c.uint.decode(state)
    const flags = state.start < state.end ? c.uint.decode(state) : 0

    return {
      start,
      length,
      any: (flags & 1) !== 0
    }
  }
}

wire.unwant = {
  preencode(state, m) {
    c.uint.preencode(state, m.start)
    c.uint.preencode(state, m.length)

    const flags = m.any ? 1 : 0
    if (flags !== 0) c.uint.preencode(state, flags)
  },
  encode(state, m) {
    c.uint.encode(state, m.start)
    c.uint.encode(state, m.length)

    const flags = m.any ? 1 : 0
    if (flags !== 0) c.uint.encode(state, flags)
  },
  decode(state, m) {
    const start = c.uint.decode(state)
    const length = c.uint.decode(state)
    const flags = state.start < state.end ? c.uint.decode(state) : 0

    return {
      start,
      length,
      any: (flags & 1) !== 0
    }
  }
}

wire.range = {
  preencode(state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.start)
    if (m.length !== 1) c.uint.preencode(state, m.length)
  },
  encode(state, m) {
    c.uint.encode(state, (m.drop ? 1 : 0) | (m.length === 1 ? 2 : 0))
    c.uint.encode(state, m.start)
    if (m.length !== 1) c.uint.encode(state, m.length)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      drop: (flags & 1) !== 0,
      start: c.uint.decode(state),
      length: (flags & 2) !== 0 ? 1 : c.uint.decode(state)
    }
  }
}

wire.bitfield = {
  preencode(state, m) {
    c.uint.preencode(state, m.start)
    c.uint32array.preencode(state, m.bitfield)
  },
  encode(state, m) {
    c.uint.encode(state, m.start)
    c.uint32array.encode(state, m.bitfield)
  },
  decode(state, m) {
    return {
      start: c.uint.decode(state),
      bitfield: c.uint32array.decode(state)
    }
  }
}

wire.sync = {
  preencode(state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.fork)
    c.uint.preencode(state, m.length)
    c.uint.preencode(state, m.remoteLength)
  },
  encode(state, m) {
    c.uint.encode(
      state,
      (m.canUpgrade ? 1 : 0) |
        (m.uploading ? 2 : 0) |
        (m.downloading ? 4 : 0) |
        (m.hasManifest ? 8 : 0) |
        (m.allowPush ? 16 : 0)
    )
    c.uint.encode(state, m.fork)
    c.uint.encode(state, m.length)
    c.uint.encode(state, m.remoteLength)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      fork: c.uint.decode(state),
      length: c.uint.decode(state),
      remoteLength: c.uint.decode(state),
      canUpgrade: (flags & 1) !== 0,
      uploading: (flags & 2) !== 0,
      downloading: (flags & 4) !== 0,
      hasManifest: (flags & 8) !== 0,
      allowPush: (flags & 16) !== 0
    }
  }
}

wire.reorgHint = {
  preencode(state, m) {
    c.uint.preencode(state, m.from)
    c.uint.preencode(state, m.to)
    c.uint.preencode(state, m.ancestors)
  },
  encode(state, m) {
    c.uint.encode(state, m.from)
    c.uint.encode(state, m.to)
    c.uint.encode(state, m.ancestors)
  },
  decode(state) {
    return {
      from: c.uint.decode(state),
      to: c.uint.decode(state),
      ancestors: c.uint.decode(state)
    }
  }
}

wire.extension = {
  preencode(state, m) {
    c.string.preencode(state, m.name)
    c.raw.preencode(state, m.message)
  },
  encode(state, m) {
    c.string.encode(state, m.name)
    c.raw.encode(state, m.message)
  },
  decode(state) {
    return {
      name: c.string.decode(state),
      message: c.raw.decode(state)
    }
  }
}

const keyValue = {
  preencode(state, p) {
    c.string.preencode(state, p.key)
    c.buffer.preencode(state, p.value)
  },
  encode(state, p) {
    c.string.encode(state, p.key)
    c.buffer.encode(state, p.value)
  },
  decode(state) {
    return {
      key: c.string.decode(state),
      value: c.buffer.decode(state)
    }
  }
}

const treeUpgrade = {
  preencode(state, u) {
    c.uint.preencode(state, u.fork)
    c.uint.preencode(state, u.ancestors)
    c.uint.preencode(state, u.length)
    c.buffer.preencode(state, u.signature)
  },
  encode(state, u) {
    c.uint.encode(state, u.fork)
    c.uint.encode(state, u.ancestors)
    c.uint.encode(state, u.length)
    c.buffer.encode(state, u.signature)
  },
  decode(state) {
    return {
      fork: c.uint.decode(state),
      ancestors: c.uint.decode(state),
      length: c.uint.decode(state),
      signature: c.buffer.decode(state)
    }
  }
}

const bitfieldUpdate = {
  // TODO: can maybe be folded into a HAVE later on with the most recent spec
  preencode(state, b) {
    state.end++ // flags
    c.uint.preencode(state, b.start)
    c.uint.preencode(state, b.length)
  },
  encode(state, b) {
    state.buffer[state.start++] = b.drop ? 1 : 0
    c.uint.encode(state, b.start)
    c.uint.encode(state, b.length)
  },
  decode(state) {
    const flags = c.uint.decode(state)
    return {
      drop: (flags & 1) !== 0,
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

const oplog = (exports.oplog = {})

oplog.entry = {
  preencode(state, m) {
    state.end++ // flags
    if (m.userData) keyValue.preencode(state, m.userData)
    if (m.treeNodes) nodeArray.preencode(state, m.treeNodes)
    if (m.treeUpgrade) treeUpgrade.preencode(state, m.treeUpgrade)
    if (m.bitfield) bitfieldUpdate.preencode(state, m.bitfield)
  },
  encode(state, m) {
    const s = state.start++
    let flags = 0

    if (m.userData) {
      flags |= 1
      keyValue.encode(state, m.userData)
    }
    if (m.treeNodes) {
      flags |= 2
      nodeArray.encode(state, m.treeNodes)
    }
    if (m.treeUpgrade) {
      flags |= 4
      treeUpgrade.encode(state, m.treeUpgrade)
    }
    if (m.bitfield) {
      flags |= 8
      bitfieldUpdate.encode(state, m.bitfield)
    }

    state.buffer[s] = flags
  },
  decode(state) {
    const flags = c.uint.decode(state)
    return {
      userData: (flags & 1) !== 0 ? keyValue.decode(state) : null,
      treeNodes: (flags & 2) !== 0 ? nodeArray.decode(state) : null,
      treeUpgrade: (flags & 4) !== 0 ? treeUpgrade.decode(state) : null,
      bitfield: (flags & 8) !== 0 ? bitfieldUpdate.decode(state) : null
    }
  }
}

const keyPair = {
  preencode(state, kp) {
    c.buffer.preencode(state, kp.publicKey)
    c.buffer.preencode(state, kp.secretKey)
  },
  encode(state, kp) {
    c.buffer.encode(state, kp.publicKey)
    c.buffer.encode(state, kp.secretKey)
  },
  decode(state) {
    return {
      publicKey: c.buffer.decode(state),
      secretKey: c.buffer.decode(state)
    }
  }
}

const reorgHint = {
  preencode(state, r) {
    c.uint.preencode(state, r.from)
    c.uint.preencode(state, r.to)
    c.uint.preencode(state, r.ancestors)
  },
  encode(state, r) {
    c.uint.encode(state, r.from)
    c.uint.encode(state, r.to)
    c.uint.encode(state, r.ancestors)
  },
  decode(state) {
    return {
      from: c.uint.decode(state),
      to: c.uint.decode(state),
      ancestors: c.uint.decode(state)
    }
  }
}

const reorgHintArray = c.array(reorgHint)

const hints = {
  preencode(state, h) {
    reorgHintArray.preencode(state, h.reorgs)
    c.uint.preencode(state, h.contiguousLength)
  },
  encode(state, h) {
    reorgHintArray.encode(state, h.reorgs)
    c.uint.encode(state, h.contiguousLength)
  },
  decode(state) {
    return {
      reorgs: reorgHintArray.decode(state),
      contiguousLength: state.start < state.end ? c.uint.decode(state) : 0
    }
  }
}

const treeHeader = {
  preencode(state, t) {
    c.uint.preencode(state, t.fork)
    c.uint.preencode(state, t.length)
    c.buffer.preencode(state, t.rootHash)
    c.buffer.preencode(state, t.signature)
  },
  encode(state, t) {
    c.uint.encode(state, t.fork)
    c.uint.encode(state, t.length)
    c.buffer.encode(state, t.rootHash)
    c.buffer.encode(state, t.signature)
  },
  decode(state) {
    return {
      fork: c.uint.decode(state),
      length: c.uint.decode(state),
      rootHash: c.buffer.decode(state),
      signature: c.buffer.decode(state)
    }
  }
}

const types = {
  preencode(state, t) {
    c.string.preencode(state, t.tree)
    c.string.preencode(state, t.bitfield)
    c.string.preencode(state, t.signer)
  },
  encode(state, t) {
    c.string.encode(state, t.tree)
    c.string.encode(state, t.bitfield)
    c.string.encode(state, t.signer)
  },
  decode(state) {
    return {
      tree: c.string.decode(state),
      bitfield: c.string.decode(state),
      signer: c.string.decode(state)
    }
  }
}

const externalHeader = {
  preencode(state, m) {
    c.uint.preencode(state, m.start)
    c.uint.preencode(state, m.length)
  },
  encode(state, m) {
    c.uint.encode(state, m.start)
    c.uint.encode(state, m.length)
  },
  decode(state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

const keyValueArray = c.array(keyValue)

oplog.header = {
  preencode(state, h) {
    state.end += 2 // version + flags
    if (h.external) {
      externalHeader.preencode(state, h.external)
      return
    }
    c.fixed32.preencode(state, h.key)
    if (h.manifest) manifest.preencode(state, h.manifest)
    if (h.keyPair) keyPair.preencode(state, h.keyPair)
    keyValueArray.preencode(state, h.userData)
    treeHeader.preencode(state, h.tree)
    hints.preencode(state, h.hints)
  },
  encode(state, h) {
    c.uint.encode(state, 1)
    if (h.external) {
      c.uint.encode(state, 1) // ONLY set the first big for clarity
      externalHeader.encode(state, h.external)
      return
    }
    c.uint.encode(state, (h.manifest ? 2 : 0) | (h.keyPair ? 4 : 0))
    c.fixed32.encode(state, h.key)
    if (h.manifest) manifest.encode(state, h.manifest)
    if (h.keyPair) keyPair.encode(state, h.keyPair)
    keyValueArray.encode(state, h.userData)
    treeHeader.encode(state, h.tree)
    hints.encode(state, h.hints)
  },
  decode(state) {
    const version = c.uint.decode(state)

    if (version > 1) {
      throw INVALID_OPLOG_VERSION('Invalid header version. Expected <= 1, got ' + version)
    }

    if (version === 0) {
      const old = {
        types: types.decode(state),
        userData: keyValueArray.decode(state),
        tree: treeHeader.decode(state),
        signer: keyPair.decode(state),
        hints: hints.decode(state)
      }

      return {
        external: null,
        key: old.signer.publicKey,
        manifest: {
          version: 0,
          hash: old.types.tree,
          allowPatch: false,
          quorum: 1,
          signers: [
            {
              signature: old.types.signer,
              namespace: DEFAULT_NAMESPACE,
              publicKey: old.signer.publicKey
            }
          ],
          prologue: null,
          linked: null,
          userData: null
        },
        keyPair: old.signer.secretKey ? old.signer : null,
        userData: old.userData,
        tree: old.tree,
        hints: old.hints
      }
    }

    const flags = c.uint.decode(state)

    if (flags & 1) {
      return {
        external: externalHeader.decode(state),
        key: null,
        manifest: null,
        keyPair: null,
        userData: null,
        tree: null,
        hints: null
      }
    }

    return {
      external: null,
      key: c.fixed32.decode(state),
      manifest: (flags & 2) !== 0 ? manifest.decode(state) : null,
      keyPair: (flags & 4) !== 0 ? keyPair.decode(state) : null,
      userData: keyValueArray.decode(state),
      tree: treeHeader.decode(state),
      hints: hints.decode(state)
    }
  }
}

const uintArray = c.array(c.uint)

const multisigInput = {
  preencode(state, inp) {
    c.uint.preencode(state, inp.signer)
    c.fixed64.preencode(state, inp.signature)
    c.uint.preencode(state, inp.patch)
  },
  encode(state, inp) {
    c.uint.encode(state, inp.signer)
    c.fixed64.encode(state, inp.signature)
    c.uint.encode(state, inp.patch)
  },
  decode(state) {
    return {
      signer: c.uint.decode(state),
      signature: c.fixed64.decode(state),
      patch: c.uint.decode(state)
    }
  }
}

const patchEncodingv0 = {
  preencode(state, n) {
    c.uint.preencode(state, n.start)
    c.uint.preencode(state, n.length)
    uintArray.preencode(state, n.nodes)
  },
  encode(state, n) {
    c.uint.encode(state, n.start)
    c.uint.encode(state, n.length)
    uintArray.encode(state, n.nodes)
  },
  decode(state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state),
      nodes: uintArray.decode(state)
    }
  }
}

const multisigInputv0 = {
  preencode(state, n) {
    state.end++
    c.uint.preencode(state, n.signer)
    c.fixed64.preencode(state, n.signature)
    if (n.patch) patchEncodingv0.preencode(state, n.patch)
  },
  encode(state, n) {
    c.uint.encode(state, n.patch ? 1 : 0)
    c.uint.encode(state, n.signer)
    c.fixed64.encode(state, n.signature)
    if (n.patch) patchEncodingv0.encode(state, n.patch)
  },
  decode(state) {
    const flags = c.uint.decode(state)
    return {
      signer: c.uint.decode(state),
      signature: c.fixed64.decode(state),
      patch: flags & 1 ? patchEncodingv0.decode(state) : null
    }
  }
}

const multisigInputArrayv0 = c.array(multisigInputv0)
const multisigInputArray = c.array(multisigInput)

const compactNode = {
  preencode(state, n) {
    c.uint.preencode(state, n.index)
    c.uint.preencode(state, n.size)
    c.fixed32.preencode(state, n.hash)
  },
  encode(state, n) {
    c.uint.encode(state, n.index)
    c.uint.encode(state, n.size)
    c.fixed32.encode(state, n.hash)
  },
  decode(state) {
    return {
      index: c.uint.decode(state),
      size: c.uint.decode(state),
      hash: c.fixed32.decode(state)
    }
  }
}

const compactNodeArray = c.array(compactNode)

exports.multiSignaturev0 = {
  preencode(state, s) {
    multisigInputArrayv0.preencode(state, s.proofs)
    compactNodeArray.preencode(state, s.patch)
  },
  encode(state, s) {
    multisigInputArrayv0.encode(state, s.proofs)
    compactNodeArray.encode(state, s.patch)
  },
  decode(state) {
    return {
      proofs: multisigInputArrayv0.decode(state),
      patch: compactNodeArray.decode(state)
    }
  }
}

exports.multiSignature = {
  preencode(state, s) {
    multisigInputArray.preencode(state, s.proofs)
    compactNodeArray.preencode(state, s.patch)
  },
  encode(state, s) {
    multisigInputArray.encode(state, s.proofs)
    compactNodeArray.encode(state, s.patch)
  },
  decode(state) {
    return {
      proofs: multisigInputArray.decode(state),
      patch: compactNodeArray.decode(state)
    }
  }
}
const c = require('compact-encoding')
const b4a = require('b4a')
const flat = require('flat-tree')
const { MerkleTree } = require('./merkle-tree')
const { multiSignature, multiSignaturev0 } = require('./messages')

module.exports = {
  assemblev0,
  assemble,
  inflatev0,
  inflate,
  partialSignature,
  signableLength
}

function inflatev0(data) {
  return c.decode(multiSignaturev0, data)
}

function inflate(data) {
  return c.decode(multiSignature, data)
}

async function partialSignature(
  core,
  signer,
  from,
  to = core.state.length,
  signature = core.state.signature
) {
  if (from > core.state.length) return null
  const nodes = to <= from ? null : await upgradeNodes(core, from, to)

  if (signature.byteLength !== 64) {
    signature = c.decode(multiSignature, signature).proofs[0].signature
  }

  return {
    signer,
    signature,
    patch: nodes ? to - from : 0,
    nodes
  }
}

async function upgradeNodes(core, from, to) {
  const rx = core.state.storage.read()
  let p = null
  try {
    p = await MerkleTree.proof(core.state, rx, { upgrade: { start: from, length: to - from } })
  } catch (err) {
    rx.destroy()
    throw err
  }
  rx.tryFlush()
  return (await p.settle()).upgrade.nodes
}

function signableLength(lengths, quorum) {
  if (quorum <= 0) quorum = 1
  if (quorum > lengths.length) return 0

  return lengths.sort(cmp)[quorum - 1]
}

function cmp(a, b) {
  return b - a
}

function assemblev0(inputs) {
  const proofs = []
  const patch = []

  for (const u of inputs) {
    proofs.push(compressProof(u, patch))
  }

  return c.encode(multiSignaturev0, { proofs, patch })
}

function assemble(inputs) {
  const proofs = []
  const patch = []
  const seen = new Set()

  for (const u of inputs) {
    if (u.nodes) {
      for (const node of u.nodes) {
        if (seen.has(node.index)) continue
        seen.add(node.index)
        patch.push(node)
      }
    }

    proofs.push({
      signer: u.signer,
      signature: u.signature,
      patch: u.patch
    })
  }

  return c.encode(multiSignature, { proofs, patch })
}

function compareNode(a, b) {
  if (a.index !== b.index) return false
  if (a.size !== b.size) return false
  return b4a.equals(a.hash, b.hash)
}

function compressProof(proof, nodes) {
  return {
    signer: proof.signer,
    signature: proof.signature,
    patch: proof.patch ? compressUpgrade(proof, nodes) : null
  }
}

function compressUpgrade(p, nodes) {
  const u = {
    start: flat.rightSpan(p.nodes[p.nodes.length - 1].index) / 2 + 1,
    length: p.patch,
    nodes: []
  }

  for (const node of p.nodes) {
    let present = false
    for (let i = 0; i < nodes.length; i++) {
      if (!compareNode(nodes[i], node)) continue

      u.nodes.push(i)
      present = true
      break
    }

    if (present) continue
    u.nodes.push(nodes.push(node) - 1)
  }

  return u
}
module.exports = class Mutex {
  constructor() {
    this.locked = false
    this.destroyed = false

    this._destroying = null
    this._destroyError = null
    this._queue = []
    this._enqueue = (resolve, reject) => this._queue.push([resolve, reject])
  }

  idle() {
    return this._queue.length === 0 && this.locked === false
  }

  lock() {
    if (this.destroyed) {
      return Promise.reject(this._destroyError || new Error('Mutex has been destroyed'))
    }
    if (this.locked) return new Promise(this._enqueue)
    this.locked = true
    return Promise.resolve()
  }

  unlock() {
    if (!this._queue.length) {
      this.locked = false
      return
    }
    this._queue.shift()[0]()
  }

  destroy(err) {
    if (!this._destroying) {
      this._destroying = this.locked ? this.lock().catch(() => {}) : Promise.resolve()
    }

    this.destroyed = true
    if (err) this._destroyError = err

    if (err) {
      while (this._queue.length) this._queue.shift()[1](err)
    }

    return this._destroying
  }
}
const FIFO = require('fast-fifo')

module.exports = class ReceiverQueue {
  constructor() {
    this.queue = new FIFO()
    this.priority = []
    this.requests = new Map()
    this.length = 0
  }

  push(req) {
    // TODO: use a heap at some point if we wanna support multiple prios
    if (req.priority > 0) this.priority.push(req)
    else this.queue.push(req)

    this.requests.set(req.id, req)
    this.length++
  }

  shift() {
    while (this.priority.length > 0) {
      const msg = this.priority.pop()
      const req = this._processRequest(msg)
      if (req !== null) return req
    }

    while (this.queue.length > 0) {
      const msg = this.queue.shift()
      const req = this._processRequest(msg)
      if (req !== null) return req
    }

    return null
  }

  _processRequest(req) {
    if (req.block || req.hash || req.seek || req.upgrade || req.manifest) {
      this.requests.delete(req.id)
      this.length--
      return req
    }

    return null
  }

  clear() {
    this.queue.clear()
    this.priority = []
    this.length = 0
    this.requests.clear()
  }

  delete(id) {
    const req = this.requests.get(id)
    if (!req) return

    req.block = null
    req.hash = null
    req.seek = null
    req.upgrade = null
    req.manifest = false

    this.requests.delete(id)
    this.length--

    if (this.length === 0) {
      this.queue.clear()
      this.priority = []
    }
  }
}
const BigSparseArray = require('big-sparse-array')
const quickbit = require('./compat').quickbit

const BITS_PER_PAGE = 32768
const BYTES_PER_PAGE = BITS_PER_PAGE / 8
const WORDS_PER_PAGE = BYTES_PER_PAGE / 4
const BITS_PER_SEGMENT = 2097152
const BYTES_PER_SEGMENT = BITS_PER_SEGMENT / 8
const PAGES_PER_SEGMENT = BITS_PER_SEGMENT / BITS_PER_PAGE

class RemoteBitfieldPage {
  constructor(index, bitfield, segment) {
    this.index = index
    this.offset = index * BYTES_PER_PAGE - segment.offset
    this.bitfield = bitfield
    this.segment = segment

    segment.add(this)
  }

  get tree() {
    return this.segment.tree
  }

  get(index) {
    return quickbit.get(this.bitfield, index)
  }

  set(index, val) {
    if (quickbit.set(this.bitfield, index, val)) {
      this.tree.update(this.offset * 8 + index)
    }
  }

  setRange(start, end, val) {
    quickbit.fill(this.bitfield, val, start, end)

    let i = Math.floor(start / 128)
    const n = i + Math.ceil((end - start) / 128)

    while (i <= n) this.tree.update(this.offset * 8 + i++ * 128)
  }

  findFirst(val, position) {
    return quickbit.findFirst(this.bitfield, val, position)
  }

  findLast(val, position) {
    return quickbit.findLast(this.bitfield, val, position)
  }

  insert(start, bitfield) {
    this.bitfield.set(bitfield, start / 32)
    this.segment.refresh()
  }

  clear(start, bitfield) {
    quickbit.clear(this.bitfield, { field: bitfield, offset: start })
  }
}

class RemoteBitfieldSegment {
  constructor(index) {
    this.index = index
    this.offset = index * BYTES_PER_SEGMENT
    this.tree = quickbit.Index.from([], BYTES_PER_SEGMENT)
    this.pages = new Array(PAGES_PER_SEGMENT)
    this.pagesLength = 0
  }

  get chunks() {
    return this.tree.chunks
  }

  refresh() {
    this.tree = quickbit.Index.from(this.tree.chunks, BYTES_PER_SEGMENT)
  }

  add(page) {
    const pageIndex = page.index - this.index * PAGES_PER_SEGMENT
    if (pageIndex >= this.pagesLength) this.pagesLength = pageIndex + 1

    this.pages[pageIndex] = page

    const chunk = { field: page.bitfield, offset: page.offset }

    this.chunks.push(chunk)

    for (let i = this.chunks.length - 2; i >= 0; i--) {
      const prev = this.chunks[i]
      if (prev.offset <= chunk.offset) break
      this.chunks[i] = chunk
      this.chunks[i + 1] = prev
    }
  }

  findFirst(val, position) {
    position = this.tree.skipFirst(!val, position)

    let j = position & (BITS_PER_PAGE - 1)
    let i = (position - j) / BITS_PER_PAGE

    if (i >= PAGES_PER_SEGMENT) return -1

    while (i < this.pagesLength) {
      const p = this.pages[i]

      let index = -1

      if (p) index = p.findFirst(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_PAGE + index

      j = 0
      i++
    }

    return val || this.pagesLength === PAGES_PER_SEGMENT ? -1 : this.pagesLength * BITS_PER_PAGE
  }

  findLast(val, position) {
    position = this.tree.skipLast(!val, position)

    let j = position & (BITS_PER_PAGE - 1)
    let i = (position - j) / BITS_PER_PAGE

    if (i >= PAGES_PER_SEGMENT) return -1

    while (i >= 0) {
      const p = this.pages[i]

      let index = -1

      if (p) index = p.findLast(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_PAGE + index

      j = BITS_PER_PAGE - 1
      i--
    }

    return -1
  }
}

module.exports = class RemoteBitfield {
  static BITS_PER_PAGE = BITS_PER_PAGE
  static BITS_PER_SEGMENT = BITS_PER_SEGMENT

  constructor() {
    this._pages = new BigSparseArray()
    this._segments = new BigSparseArray()
    this._maxSegments = 0
  }

  getBitfield(index) {
    const j = index & (BITS_PER_PAGE - 1)
    const i = (index - j) / BITS_PER_PAGE

    const p = this._pages.get(i)
    return p || null
  }

  get(index) {
    const j = index & (BITS_PER_PAGE - 1)
    const i = (index - j) / BITS_PER_PAGE

    const p = this._pages.get(i)

    return p ? p.get(j) : false
  }

  set(index, val) {
    const j = index & (BITS_PER_PAGE - 1)
    const i = (index - j) / BITS_PER_PAGE

    let p = this._pages.get(i)

    if (!p && val) {
      const k = Math.floor(i / PAGES_PER_SEGMENT)
      const s = this._segments.get(k) || this._segments.set(k, new RemoteBitfieldSegment(k))
      if (this._maxSegments <= k) this._maxSegments = k + 1

      p = this._pages.set(i, new RemoteBitfieldPage(i, new Uint32Array(WORDS_PER_PAGE), s))
    }

    if (p) p.set(j, val)
  }

  setRange(start, end, val) {
    let j = start & (BITS_PER_PAGE - 1)
    let i = (start - j) / BITS_PER_PAGE

    while (start < end) {
      let p = this._pages.get(i)

      if (!p && val) {
        const k = Math.floor(i / PAGES_PER_SEGMENT)
        const s = this._segments.get(k) || this._segments.set(k, new RemoteBitfieldSegment(k))
        if (this._maxSegments <= k) this._maxSegments = k + 1

        p = this._pages.set(i, new RemoteBitfieldPage(i, new Uint32Array(WORDS_PER_PAGE), s))
      }

      const offset = i * BITS_PER_PAGE
      const last = Math.min(end - offset, BITS_PER_PAGE)
      const range = last - j

      if (p) p.setRange(j, last, val)

      j = 0
      i++
      start += range
    }
  }

  findFirst(val, position) {
    let j = position & (BITS_PER_SEGMENT - 1)
    let i = (position - j) / BITS_PER_SEGMENT

    while (i < this._maxSegments) {
      const s = this._segments.get(i)

      let index = -1

      if (s) index = s.findFirst(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_SEGMENT + index

      j = 0
      i++
    }

    // For the val === false case, we always return at least
    // the 'position', also if nothing was found
    return val ? -1 : Math.max(position, this._maxSegments * BITS_PER_SEGMENT)
  }

  firstSet(position) {
    return this.findFirst(true, position)
  }

  firstUnset(position) {
    return this.findFirst(false, position)
  }

  findLast(val, position) {
    let j = position & (BITS_PER_SEGMENT - 1)
    let i = (position - j) / BITS_PER_SEGMENT

    while (i >= 0) {
      const s = this._segments.get(i)

      let index = -1

      if (s) index = s.findLast(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_SEGMENT + index

      j = BITS_PER_SEGMENT - 1
      i--
    }

    return -1
  }

  lastSet(position) {
    return this.findLast(true, position)
  }

  lastUnset(position) {
    return this.findLast(false, position)
  }

  insert(start, bitfield) {
    if (start % 32 !== 0) return false

    let length = bitfield.byteLength * 8

    let j = start & (BITS_PER_PAGE - 1)
    let i = (start - j) / BITS_PER_PAGE

    while (length > 0) {
      let p = this._pages.get(i)

      if (!p) {
        const k = Math.floor(i / PAGES_PER_SEGMENT)
        const s = this._segments.get(k) || this._segments.set(k, new RemoteBitfieldSegment(k))
        if (this._maxSegments <= k) this._maxSegments = k + 1

        p = this._pages.set(i, new RemoteBitfieldPage(i, new Uint32Array(WORDS_PER_PAGE), s))
      }

      const end = Math.min(j + length, BITS_PER_PAGE)
      const range = end - j

      p.insert(j, bitfield.subarray(0, range / 32))

      bitfield = bitfield.subarray(range / 32)

      j = 0
      i++
      length -= range
    }

    return true
  }

  clear(start, bitfield) {
    if (start % 32 !== 0) return false

    let length = bitfield.byteLength * 8

    let j = start & (BITS_PER_PAGE - 1)
    let i = (start - j) / BITS_PER_PAGE

    while (length > 0) {
      let p = this._pages.get(i)

      if (!p) {
        const k = Math.floor(i / PAGES_PER_SEGMENT)
        const s = this._segments.get(k) || this._segments.set(k, new RemoteBitfieldSegment(k))
        if (this._maxSegments <= k) this._maxSegments = k + 1

        p = this._pages.set(i, new RemoteBitfieldPage(i, new Uint32Array(WORDS_PER_PAGE), s))
      }

      const end = Math.min(j + length, BITS_PER_PAGE)
      const range = end - j

      p.clear(j, bitfield.subarray(0, range / 32))

      bitfield = bitfield.subarray(range / 32)

      j = 0
      i++
      length -= range
    }

    return true
  }
}
/* DEV DOCS
  Every hypercore has one Replicator object managing its connections to other peers.
  There is one Peer object per peer connected to the Hypercore.
  Hypercores do not know about other hypercores, so when a peer is connected to multiple cores, there exists one Peer object per core.

  Hypercore indicates block should be downloaded through methods like Replicator.addRange or Replicator.addBlock
  Hypercore calls Replicator.updateActivity every time a hypercore session opens/closes
  Replicator.updateActivity ensures the Hypercore is downloading blocks as expected
  Replicator keeps track of:
    - Which blocks need to be downloaded (Replicator._blocks)
    - Which blocks currently have inflight requests (Replicator._inflight)

  Blocks are requested from remote peers by Peer objects. The flow is:
    - The replicator's updatePeer method gets called
    - The replicator detects whether the Peer can accept more requests (for example by checking if it's maxed out on inflight blocks)
    - The replicator then tells the Peer what to request (e.g. Peer_requestRange or Peer._requestBlock methods)

  The Peer object is responsible for tracking
    - Which blocks does the Peer have available (tracked in remoteBitfield)
    - Which blocks are you actively looking for from this peer (tracked in missingBlocks)
    - How many blocks are currently inflight (tracked in inflight)
  The Peer uses this information to decide which blocks to request from the peer in response to _requestRange requests and the like.
*/

const b4a = require('b4a')
const safetyCatch = require('safety-catch')
const RandomIterator = require('random-array-iterator')
const flatTree = require('flat-tree')
const Mutex = require('./mutex')
const ReceiverQueue = require('./receiver-queue')
const HotswapQueue = require('./hotswap-queue')
const RemoteBitfield = require('./remote-bitfield')
const { MerkleTree } = require('./merkle-tree')
const w = require('./wants')
const { LocalWants, RemoteWants } = w
const {
  REQUEST_CANCELLED,
  REQUEST_TIMEOUT,
  INVALID_CAPABILITY,
  SNAPSHOT_NOT_AVAILABLE,
  ASSERTION
} = require('hypercore-errors')
const m = require('./messages')
const caps = require('./caps')

const DEFAULT_MAX_INFLIGHT = [16, 512]
const SCALE_LATENCY = 50
const NOT_DOWNLOADING_SLACK = (20000 + Math.random() * 20000) | 0
const MAX_PEERS_UPGRADE = 3
const LAST_BLOCKS = 256
const MAX_RANGES = 64
const MIN_PEER_UPDATE_ALL = 40

const NOT_AVAILABLE = 1
const INVALID_REQUEST = 2
const MAX_INVALID_REQUESTS = 64
const MAX_BACKOFFS = MAX_INVALID_REQUESTS / 2

const PRIORITY = {
  NORMAL: 0,
  HIGH: 1,
  VERY_HIGH: 2,
  CANCELLED: 255 // reserved to mark cancellation
}

class Attachable {
  constructor(replicator) {
    this.replicator = replicator
    this.resolved = false
    this.processing = false
    this.refs = []
    this.wants = null
  }

  addWant(w) {
    if (this.wants === null) this.wants = new Set()
    this.wants.add(w)
  }

  removeWant(w) {
    if (this.wants === null) return
    this.wants.delete(w)
  }

  attach(session) {
    const r = {
      context: this,
      session,
      sindex: 0,
      rindex: 0,
      snapshot: true,
      resolve: null,
      reject: null,
      promise: null,
      timeout: null
    }

    r.sindex = session.push(r) - 1
    r.rindex = this.refs.push(r) - 1
    r.promise = new Promise((resolve, reject) => {
      r.resolve = resolve
      r.reject = reject
    })

    return r
  }

  detach(r, err = null) {
    if (r.context !== this) return false

    this._detach(r)
    this._cancel(r, err)
    this.gc()

    return true
  }

  _detach(r) {
    const rh = this.refs.pop()
    const sh = r.session.pop()

    if (r.rindex < this.refs.length) this.refs[(rh.rindex = r.rindex)] = rh
    if (r.sindex < r.session.length) r.session[(sh.sindex = r.sindex)] = sh

    destroyRequestTimeout(r)
    r.context = null

    return r
  }

  gc() {
    if (this.refs.length > 0 || this.processing) return
    this._unref()

    if (this.wants === null) return

    const wants = this.wants
    this.wants = null

    let update = null

    for (const w of wants) {
      if (w.any) {
        const removed = w.wants.removeAnyRange(w.start, w.length, this)
        if (!removed) continue
        if (update === null) update = new Set()
        update.add(w.wants.peer)
        // TODO: should also use a free list for simplicity
        w.wants.peer.wireUnwant.send(removed)
        continue
      }

      if (w.wants.removeBatch(w.start, this)) {
        if (update === null) update = new Set()
        update.add(w.wants.peer)
      }
    }

    if (update === null) return
    for (const peer of update) {
      this.replicator.updatePeer(peer)
    }
  }

  processed() {
    this.processing = false
    this.gc()
  }

  _cancel(r, err) {
    r.reject(err || REQUEST_CANCELLED())
  }

  _unref() {
    // overwrite me
  }

  resolve(val) {
    this.resolved = true
    while (this.refs.length > 0) {
      this._detach(this.refs[this.refs.length - 1]).resolve(val)
    }
    this.gc()
  }

  reject(err) {
    this.resolved = true
    while (this.refs.length > 0) {
      this._detach(this.refs[this.refs.length - 1]).reject(err)
    }
    this.gc()
  }

  setTimeout(r, ms) {
    destroyRequestTimeout(r)
    r.timeout = setTimeout(onrequesttimeout, ms, r)
  }
}

class BlockRequest extends Attachable {
  constructor(replicator, tracker, index, priority, force) {
    super(replicator)

    this.index = index
    this.priority = priority
    this.inflight = []
    this.queued = false
    this.hotswap = null
    this.tracker = tracker
    this.force = force
  }

  _unref() {
    if (this.resolved) return
    this.queued = false

    for (const req of this.inflight) {
      req.peer._cancelRequest(req)
    }

    this.tracker.remove(this.index)
    removeHotswap(this)
  }
}

class RangeBatchRequest extends Attachable {
  constructor(replicator, batch) {
    super(replicator)

    this.batch = batch
    this.index = 0
  }
}

class RangeRequest extends Attachable {
  constructor(replicator, ranges, start, end, linear, blocks) {
    super(replicator)

    this.start = start
    this.end = end
    this.linear = linear
    this.blocks = blocks
    this.ranges = ranges
    this.batches = []

    ranges.push(this)

    if (this.end === -1) {
      this.replicator._alwaysLatestBlock++
    }

    // As passed by the user, immut
    this.userStart = start
    this.userEnd = end
  }

  addBatch(batch) {
    for (let i = 0; i < this.batches.length; i++) {
      const b = this.batches[i]
      if (b.batch === batch) return false
    }
    const b = new RangeBatchRequest(this.replicator, batch)
    b.index = this.batches.length
    this.batches.push(b)
    return true
  }

  removeBatch(batch) {
    const head = this.batches.pop()

    if (head !== batch) {
      head.index = batch.index
      this.batches[head.index] = head
    }

    batch.gc()
  }

  _unref() {
    const rangeIndex = this.ranges.indexOf(this)
    if (rangeIndex === -1) return

    const h = this.ranges.pop()
    if (h !== this) {
      this.ranges[rangeIndex] = h
    }

    if (this.end === -1) {
      this.replicator._alwaysLatestBlock--
    }

    while (this.batches.length) {
      this.batches.pop().gc()
    }
  }

  _cancel(r) {
    r.resolve(false)
  }
}

class UpgradeRequest extends Attachable {
  constructor(replicator, fork, length) {
    super(replicator)

    this.fork = fork
    this.length = length
    this.inflight = []
  }

  _unref() {
    if (this.resolved) return
    if (this.replicator.eagerUpgrade === true || this.inflight.length > 0) return
    this.replicator._upgrade = null
  }

  _cancel(r) {
    r.resolve(false)
  }
}

class SeekRequest extends Attachable {
  constructor(replicator, seeks, seeker) {
    super(replicator)

    this.seeker = seeker
    this.inflight = []
    this.seeks = seeks
  }

  _unref() {
    if (this.resolved) return
    if (this.inflight.length > 0) return
    const i = this.seeks.indexOf(this)
    if (i === -1) return
    const h = this.seeks.pop()
    if (i < this.seeks.length) this.seeks[i] = h
  }
}

class ForkRequest extends Attachable {
  constructor(replicator, fork) {
    super(replicator)
    this.fork = fork
    this.inflight = []
    this.batch = null
  }
}

class InflightTracker {
  constructor() {
    this._requests = []
    this._free = []
    this._active = 0
  }

  get idle() {
    return this._active === 0
  }

  *[Symbol.iterator]() {
    for (const req of this._requests) {
      if (req !== null) yield req
    }
  }

  add(req) {
    const id = this._free.length ? this._free.pop() : this._requests.push(null)
    req.id = id
    this._requests[id - 1] = req
    this._active++
    return req
  }

  get(id) {
    return id <= this._requests.length ? this._requests[id - 1] : null
  }

  remove(id, roundtrip) {
    if (id > this._requests.length) return
    if (this._requests[id - 1]) this._active--
    this._requests[id - 1] = null
    if (roundtrip === true) this._free.push(id)
  }

  reusable(id) {
    this._free.push(id)
  }
}

class BlockTracker {
  constructor(replicator) {
    this._replicator = replicator
    this._map = new Map()
  }

  [Symbol.iterator]() {
    return this._map.values()
  }

  isEmpty() {
    return this._map.size === 0
  }

  has(index) {
    return this._map.has(index)
  }

  get(index) {
    return this._map.get(index) || null
  }

  add(index, priority, force) {
    let b = this._map.get(index)
    if (b) return b

    b = new BlockRequest(this._replicator, this, index, priority, force)
    this._map.set(index, b)

    return b
  }

  remove(index) {
    const b = this.get(index)
    this._map.delete(index)
    return b
  }
}

class RoundtripQueue {
  constructor() {
    this.queue = []
    this.tick = 0
  }

  clear() {
    const ids = new Array(this.queue.length)
    for (let i = 0; i < ids.length; i++) {
      ids[i] = this.queue[i][1]
    }

    this.queue = []

    return ids
  }

  add(id) {
    this.queue.push([++this.tick, id])
  }

  flush(tick) {
    let flushed = null

    for (let i = 0; i < this.queue.length; i++) {
      if (this.queue[i][0] > tick) break
      if (flushed === null) flushed = []
      flushed.push(this.queue[i][1])
    }

    if (flushed !== null) this.queue.splice(0, flushed.length)
    return flushed
  }
}

class ProofRequest {
  constructor(msg, proof, block, manifest) {
    this.msg = msg
    this.proof = proof
    this.block = block
    this.manifest = manifest
  }

  async fulfill() {
    if (this.proof === null) return null

    const [proof, block] = await Promise.all([this.proof.settle(), this.block])

    if (this.manifest) proof.manifest = this.manifest
    if (!block && proof.block) return null

    if (block) proof.block.value = block
    return proof
  }
}

class Peer {
  constructor(replicator, protomux, channel, inflightRange) {
    this.core = replicator.core
    this.replicator = replicator
    this.stream = protomux.stream
    this.protomux = protomux
    this.remotePublicKey = this.stream.remotePublicKey
    this.remoteSupportsSeeks = false
    this.inflightRange = inflightRange
    this.fullyDownloadedSignaled = 0

    this.paused = false
    this.removed = false

    this.channel = channel
    this.channel.userData = this

    this.wireSync = this.channel.messages[0]
    this.wireRequest = this.channel.messages[1]
    this.wireCancel = this.channel.messages[2]
    this.wireData = this.channel.messages[3]
    this.wireNoData = this.channel.messages[4]
    this.wireWant = this.channel.messages[5]
    this.wireUnwant = this.channel.messages[6]
    this.wireBitfield = this.channel.messages[7]
    this.wireRange = this.channel.messages[8]
    this.wireExtension = this.channel.messages[9]

    // Same stats as replicator, but for this specific peer
    this.stats = {
      wireSync: { tx: 0, rx: 0 },
      wireRequest: { tx: 0, rx: 0 },
      wireCancel: { tx: 0, rx: 0 },
      wireData: { tx: 0, rx: 0 },
      wireWant: { tx: 0, rx: 0 },
      wireUnwant: { tx: 0, rx: 0 },
      wireBitfield: { tx: 0, rx: 0 },
      wireRange: { tx: 0, rx: 0 },
      wireExtension: { tx: 0, rx: 0 },
      hotswaps: 0,
      invalidData: 0,
      invalidRequests: 0,
      backoffs: 0,
      notAvailableBackoffs: 0
    }

    this.receiverQueue = new ReceiverQueue()
    this.receiverBusy = false

    // most often not used, so made on demand
    this.roundtripQueue = null

    this.inflight = 0
    this.dataProcessing = 0

    this.canUpgrade = true

    this.needsSync = false
    this.syncsProcessing = 0
    this.lastUpgradableLength = 0
    this.lastUpgradableFork = 0

    this._remoteContiguousLength = 0

    // TODO: tweak pipelining so that data sent BEFORE remoteOpened is not cap verified!
    // we might wanna tweak that with some crypto, ie use the cap to encrypt it...
    // or just be aware of that, to only push non leaky data

    this.remoteOpened = false
    this.remoteBitfield = new RemoteBitfield()
    this.missingBlocks = new RemoteBitfield()

    this.pushedLength = 0

    this.remoteFork = 0
    this.remoteLength = 0
    this.remoteCanUpgrade = false
    this.remoteUploading = true
    this.remoteDownloading = true
    this.remoteSynced = false
    this.remoteHasManifest = false
    this.remoteAllowPush = false
    this.remoteRequests = new Map()

    this.segmentsWanted = new Set()
    this.broadcastedNonSparse = false

    this.wants = new LocalWants(this)
    this.remoteWants = new RemoteWants(this)

    this.lengthAcked = 0

    this.extensions = new Map()
    this.lastExtensionSent = ''
    this.lastExtensionRecv = ''

    replicator._ifAvailable++
    replicator._active++
  }

  get remoteContiguousLength() {
    return this.remoteBitfield.findFirst(false, this._remoteContiguousLength)
  }

  getMaxInflight() {
    const stream = this.stream.rawStream
    if (!stream.udx) return Math.min(this.inflightRange[1], this.inflightRange[0] * 3)

    const scale =
      stream.rtt <= SCALE_LATENCY
        ? 1
        : (stream.rtt / SCALE_LATENCY) * Math.min(1, 2 / this.replicator.peers.length)
    return Math.max(
      this.inflightRange[0],
      Math.round(Math.min(this.inflightRange[1], this.inflightRange[0] * scale))
    )
  }

  getMaxHotswapInflight() {
    const inf = this.getMaxInflight()
    return Math.max(16, inf / 2)
  }

  signalUpgrade() {
    if (this._shouldUpdateCanUpgrade() === true) this._updateCanUpgradeAndSync()
    else this.sendSync()
  }

  _markInflight(index) {
    this.missingBlocks.set(index, false)
  }

  broadcastRange(start, length, drop) {
    if (!this.isActive()) return

    if (drop) this._unclearLocalRange(start, length)
    else this._clearLocalRange(start, length)

    const fullyContig = this.core.header.hints.contiguousLength === this.core.state.length

    if (start + LAST_BLOCKS < this.core.state.length && !drop && !fullyContig) {
      if (!this.remoteWants.hasRange(start, length)) return
    }

    let force = false
    if (fullyContig && !drop) {
      start = 0
      length = this.core.state.length

      // Always send the broadcast when we switch from sparse to fully contiguous, so remote knows too
      if (this.fullyDownloadedSignaled < length) {
        this.fullyDownloadedSignaled = length
        force = true
      }
    }

    // TODO: consider also adding early-returns on the drop===true case
    if (!force && !drop) {
      // No need to broadcast if the remote already has this range

      if (this._remoteContiguousLength >= start + length) return

      if (length === 1) {
        if (this.remoteBitfield.get(start)) return
      } else {
        if (this.remoteBitfield.firstUnset(start) >= start + length) return
      }
    }

    this.wireRange.send({
      drop,
      start,
      length
    })
    incrementTx(this.stats.wireRange, this.replicator.stats.wireRange)
  }

  extension(name, message) {
    this.wireExtension.send({ name: name === this.lastExtensionSent ? '' : name, message })
    incrementTx(this.stats.wireExtension, this.replicator.stats.wireExtension)
    this.lastExtensionSent = name
  }

  onextension(message) {
    const name = message.name || this.lastExtensionRecv
    this.lastExtensionRecv = name
    const ext = this.extensions.get(name)
    if (ext) {
      ext._onmessage({ start: 0, end: message.message.byteLength, buffer: message.message }, this)
    }
  }

  sendSync() {
    // Skip syncs if in repair mode
    if (this.core._repairMode) return

    if (this.syncsProcessing !== 0) {
      this.needsSync = true
      return
    }

    if (this.core.state.fork !== this.remoteFork) {
      this.canUpgrade = false
    }

    this.needsSync = false

    this.wireSync.send({
      fork: this.core.state.fork,
      length: this.core.state.length,
      remoteLength: this.core.state.fork === this.remoteFork ? this.remoteLength : 0,
      canUpgrade: this.canUpgrade,
      uploading: true,
      downloading: this.replicator.isDownloading(),
      hasManifest: !!this.core.header.manifest && this.core.compat === false,
      allowPush: this.replicator.isAllowingPush()
    })
    incrementTx(this.stats.wireSync, this.replicator.stats.wireSync)
  }

  onopen({ seeks, capability }) {
    const expected = caps.replicate(
      this.stream.isInitiator === false,
      this.core.key,
      this.stream.handshakeHash
    )

    if (b4a.equals(capability, expected) !== true) {
      // TODO: change this to a rejection instead, less leakage
      throw INVALID_CAPABILITY('Remote sent an invalid replication capability')
    }

    if (this.remoteOpened === true) return
    this.remoteOpened = true
    this.remoteSupportsSeeks = seeks

    this.protomux.cork()

    this.sendSync()

    const contig = Math.min(this.core.state.length, this.core.header.hints.contiguousLength)
    if (contig > 0) {
      this.broadcastRange(0, contig, false)

      if (contig === this.core.state.length) {
        this.broadcastedNonSparse = true
      }
    }

    this.replicator._ifAvailable--
    this.replicator._addPeer(this)

    this.protomux.uncork()

    this.core.checkIfIdle()
  }

  onclose(isRemote) {
    // we might have signalled to the remote that we are done (ie not downloading) and the remote might agree on that
    // if that happens, the channel might be closed by the remote. if so just renegotiate it.
    // TODO: add a CLOSE_REASON to mux to we can make this cleaner...
    const reopen =
      isRemote === true &&
      this.remoteOpened === true &&
      this.remoteDownloading === false &&
      this.remoteUploading === true &&
      this.replicator.downloading === true

    if (this.remoteOpened === false) {
      this.replicator._ifAvailable--
      this.replicator.queueUpdateAll()
      return
    }

    this.remoteOpened = false
    this.removed = true
    this.remoteRequests.clear() // cancel all
    this.receiverQueue.clear()

    if (this.roundtripQueue !== null) {
      for (const id of this.roundtripQueue.clear()) this.replicator._inflight.reusable(id)
    }

    this.replicator._removePeer(this)

    if (reopen) {
      this.replicator._makePeer(this.protomux)
    }
  }

  closeIfIdle() {
    if (this.remoteDownloading === false && this.replicator.isDownloading() === false) {
      // idling, shut it down...
      this.channel.close()
      return true
    }

    return false
  }

  async onsync(msg) {
    const {
      fork,
      length,
      remoteLength,
      canUpgrade,
      uploading,
      downloading,
      hasManifest,
      allowPush
    } = msg

    const lengthChanged = length !== this.remoteLength
    const sameFork = fork === this.core.state.fork

    this.remoteSynced = true
    this.remoteFork = fork
    this.remoteLength = length
    this.remoteCanUpgrade = canUpgrade
    this.remoteUploading = uploading
    this.remoteDownloading = downloading
    this.remoteHasManifest = hasManifest
    this.remoteAllowPush = allowPush

    if (this.closeIfIdle()) return

    this.lengthAcked = sameFork ? remoteLength : 0
    this.syncsProcessing++

    this.replicator._updateFork(this)

    if (this.remoteLength > this.core.state.length && this.lengthAcked === this.core.state.length) {
      if (this.replicator._addUpgradeMaybe() !== null) this._update()
    }

    const upgrade =
      lengthChanged === false || sameFork === false
        ? this.canUpgrade && sameFork
        : await this._canUpgrade(length, fork)

    if (length === this.remoteLength && fork === this.core.state.fork) {
      this.canUpgrade = upgrade
      if (upgrade) {
        this.lastUpgradableFork = fork
        this.lastUpgradableLength = length
      }
    }

    if (--this.syncsProcessing !== 0) return // ie not latest

    if (
      this.needsSync === true ||
      (this.core.state.fork === this.remoteFork && this.core.state.length > this.remoteLength)
    ) {
      this.signalUpgrade()
    }

    this._update()
  }

  _shouldUpdateCanUpgrade() {
    return (
      this.core.state.fork === this.remoteFork &&
      this.core.state.length > this.remoteLength &&
      this.canUpgrade === false &&
      this.syncsProcessing === 0
    )
  }

  async _updateCanUpgradeAndSync() {
    const { length, fork } = this.core.state

    const remoteLength = this.remoteLength
    const remoteFork = this.remoteFork
    const canUpgrade = await this._canUpgrade(this.remoteLength, this.remoteFork)

    if (
      this.syncsProcessing > 0 ||
      length !== this.core.state.length ||
      fork !== this.core.state.fork
    ) {
      return
    }
    if (remoteLength !== this.remoteLength || remoteFork !== this.remoteFork) {
      return
    }
    if (canUpgrade === this.canUpgrade) {
      return
    }

    this.canUpgrade = canUpgrade
    if (canUpgrade) {
      this.lastUpgradableLength = this.remoteLength
      this.lastUpgradableFork = this.remoteFork
    }

    this.sendSync()
  }

  // Safe to call in the background - never fails
  async _canUpgrade(remoteLength, remoteFork) {
    if (remoteFork !== this.core.state.fork) return false

    if (remoteLength === 0) return true
    if (remoteLength >= this.core.state.length) return false

    try {
      // Rely on caching to make sure this is cheap...
      const canUpgrade = await MerkleTree.upgradeable(this.core.state, remoteLength)

      if (remoteFork !== this.core.state.fork) return false

      return canUpgrade
    } catch {
      return false
    }
  }

  async _getProof(batch, msg, pushing) {
    let block = null

    if (msg.block) {
      const index = msg.block.index

      if (!pushing && (msg.fork !== this.core.state.fork || !this.core.bitfield.get(index))) {
        return new ProofRequest(msg, null, null, null)
      }

      block = batch.getBlock(index)
      block.catch(noop)
    }

    const manifest = msg.manifest && !this.core.compat ? this.core.header.manifest : null

    try {
      const proof = await MerkleTree.proof(this.core.state, batch, msg)
      return new ProofRequest(msg, proof, block, manifest)
    } catch (err) {
      batch.destroy()

      this.replicator._oninvalidrequest(err, msg, this)

      if (this.stats.invalidRequests >= MAX_INVALID_REQUESTS) throw err

      await backoff(this.stats.invalidRequests)
      return null
    }
  }

  async onrequest(msg) {
    const size = this.remoteRequests.size
    this.remoteRequests.set(msg.id, msg)

    // if size didnt change -> id overwrite -> old one is deleted, cancel current and re-add
    if (size === this.remoteRequests.size) {
      this._cancel(msg.id)
      this.remoteRequests.set(msg.id, msg)
    }

    if (!this.protomux.drained || this.receiverQueue.length) {
      this.receiverQueue.push(msg)
      return
    }

    if (this.replicator.destroyed) return

    await this._handleRequest(msg)
  }

  oncancel(msg) {
    this._cancel(msg.request)
  }

  _cancel(id) {
    this.remoteRequests.delete(id)
    this.receiverQueue.delete(id)
  }

  ondrain() {
    return this._handleRequests()
  }

  async _handleRequests() {
    if (this.receiverBusy || this.replicator.destroyed) return
    this.receiverBusy = true
    this.protomux.cork()

    while (
      this.remoteOpened &&
      this.protomux.drained &&
      this.receiverQueue.length > 0 &&
      !this.removed
    ) {
      const msg = this.receiverQueue.shift()
      await this._handleRequest(msg)
    }

    this.protomux.uncork()
    this.receiverBusy = false
  }

  async push(index) {
    if (!this.remoteAllowPush) return
    if (!this.remoteDownloading) return
    if (this.core.state.length <= index) return
    if (this.core.state.fork !== this.remoteFork) return
    if (this.remoteBitfield.get(index)) return

    const msg = {
      id: 0,
      fork: this.core.state.fork,
      block: null,
      hash: null,
      seek: null,
      upgrade: null,
      manifest: this.remoteLength === 0,
      priority: 0
    }

    await this.replicator._txLock.lock()
    try {
      const remoteLength = Math.max(this.remoteLength, this.pushedLength)

      msg.block = {
        index,
        nodes: MerkleTree.maxMissingNodes(2 * index, remoteLength)
      }

      if (index >= remoteLength) {
        msg.upgrade = {
          start: remoteLength,
          length: this.core.state.length - remoteLength
        }
      }

      let req = null
      const batch = this.core.storage.read(this.core.state.fork)
      try {
        req = await this._getProof(batch, msg, true)
      } catch (err) {
        this.replicator._oninvalidrequest(err, msg, this)
        return
      }

      if (req === null) return
      batch.tryFlush()

      await this._fulfillRequest(req, true)
    } finally {
      this.replicator._txLock.unlock()
    }
  }

  async _handleRequest(msg) {
    const locked = !!msg.upgrade && this.remoteAllowPush

    if (locked) {
      // ensure contig push proofs
      await this.replicator._txLock.lock()
      const end = msg.upgrade.start + msg.upgrade.length

      if (this.pushedLength < end) {
        msg.upgrade.start = this.pushedLength
        msg.upgrade.length = end - this.pushedLength
      }
    }

    try {
      const batch = this.core.storage.read(this.core.state.fork)

      // TODO: could still be answerable if (index, fork) is an ancestor of the current fork
      const req =
        msg.fork === this.core.state.fork
          ? await this._getProof(batch, msg, false)
          : new ProofRequest(msg, null, null, null)

      if (req === null) {
        this.wireNoData.send({ request: msg.id, reason: INVALID_REQUEST })
        return
      }

      batch.tryFlush()

      await this._fulfillRequest(req, false)
    } finally {
      if (locked) this.replicator._txLock.unlock()
    }
  }

  async _fulfillRequest(req, pushing) {
    if (this.core._repairMode) {
      // if cancelled do not reply
      if (this.remoteRequests.get(req.msg.id) !== req.msg) {
        return
      }

      // sync from now on, so safe to delete from the map
      this.remoteRequests.delete(req.msg.id)

      // If cutting off the fulfillment, ensure promise is caught.
      // While repairing merkle tree nodes can be `nil` so can throw.
      req.fulfill().catch(safetyCatch)
      return
    }

    const proof = await req.fulfill()

    if (!pushing) {
      // if cancelled do not reply
      if (this.remoteRequests.get(req.msg.id) !== req.msg) {
        return
      }

      // sync from now on, so safe to delete from the map
      this.remoteRequests.delete(req.msg.id)
    } else if (!this.remoteAllowPush) {
      // if pushing but remote disabled it, just drop it
      return
    }

    if (!this.isActive() && proof.block !== null) {
      return
    }

    if (proof === null) {
      if (req.msg.manifest && this.core.header.manifest) {
        const manifest = this.core.header.manifest
        this.wireData.send({
          request: req.msg.id,
          fork: this.core.state.fork,
          block: null,
          hash: null,
          seek: null,
          upgrade: null,
          manifest
        })
        incrementTx(this.stats.wireData, this.replicator.stats.wireData)
        return
      }

      this.wireNoData.send({ request: req.msg.id, reason: NOT_AVAILABLE })
      return
    }

    if (proof.block !== null) {
      this.replicator._onupload(proof.block.index, proof.block.value.byteLength, this)
    }

    if (proof.upgrade) {
      const remoteLength = MerkleTree.upgradeLength(proof.upgrade)
      if (remoteLength > this.pushedLength) this.pushedLength = remoteLength
    }

    this.wireData.send({
      request: req.msg.id,
      fork: req.msg.fork,
      block: proof.block,
      hash: proof.hash,
      seek: proof.seek,
      upgrade: proof.upgrade,
      manifest: proof.manifest
    })
    incrementTx(this.stats.wireData, this.replicator.stats.wireData)
  }

  _cancelRequest(req) {
    if (req.priority === PRIORITY.CANCELLED) return
    // mark as cancelled also and avoid re-entry
    req.priority = PRIORITY.CANCELLED

    this.inflight--
    this.replicator._requestDone(req.id, false)

    // clear inflight state
    if (isBlockRequest(req)) this.replicator._unmarkInflight(req.block.index)
    if (isUpgradeRequest(req)) this.replicator._clearInflightUpgrade(req)

    if (this.roundtripQueue === null) this.roundtripQueue = new RoundtripQueue()
    this.roundtripQueue.add(req.id)
    this.wireCancel.send({ request: req.id })
    incrementTx(this.stats.wireCancel, this.replicator.stats.wireCancel)
  }

  _checkIfConflict() {
    this.paused = true

    const length = Math.min(this.core.state.length, this.remoteLength)
    if (length === 0) return // pause and ignore

    this.wireRequest.send({
      id: 0, // TODO: use an more explicit id for this eventually...
      fork: this.remoteFork,
      block: null,
      hash: null,
      seek: null,
      upgrade: {
        start: 0,
        length
      }
    })

    incrementTx(this.stats.wireRequest, this.replicator.stats.wireRequest)
  }

  _unmarkInflightBlockRequest(req, data) {
    if (isBlockRequest(req)) this.replicator._unmarkInflight(req.block.index)
    else if (data.block && !req) this.replicator._unmarkInflight(data.block.index)
  }

  async ondata(data) {
    if (data.request !== 0 && !data.upgrade) return this._handleData(data)

    await this.replicator._rxLock.lock()
    try {
      await this._handleData(data)
    } finally {
      this.replicator._rxLock.unlock()
    }
  }

  async _handleData(data) {
    // always allow a fork conflict proof to be sent
    if (data.request === 0 && data.upgrade && data.upgrade.start === 0) {
      if (await this.core.checkConflict(data, this)) return
      this.paused = false
    }

    const req = data.request > 0 ? this.replicator._inflight.get(data.request) : null
    const reorg = data.fork > this.core.state.fork

    // no push atm, TODO: check if this satisfies another pending request
    // allow reorg pushes tho as those are not written to storage so we'll take all the help we can get
    if (req === null && reorg === false && !this.replicator.allowPush) {
      return
    }

    // Skip accepting data if in repair mode to avoid corruption
    if (this.core._repairMode) {
      this.replicator._onnodata(this, req, NOT_AVAILABLE)
      return
    }

    if (req === null && reorg === false && data.block) {
      // mark this as inflight to avoid parallel requests
      this.replicator._markInflight(data.block.index)
    }

    if (req !== null) {
      if (req.peer !== this) return
      this._onrequestroundtrip(req)
    }

    try {
      if (reorg === true) return await this.replicator._onreorgdata(this, req, data)
    } catch (err) {
      safetyCatch(err)
      this._unmarkInflightBlockRequest(req, data)

      this.paused = true
      this.replicator._oninvaliddata(err, req, data, this)
      return
    }

    this.dataProcessing++
    if (isBlockRequest(req)) this.replicator._markProcessing(req.block.index)

    try {
      if (!this.replicator._matchingRequest(req, data) || !(await this.core.verify(data, this))) {
        this.replicator._onnodata(this, req, 0)
        return
      }
    } catch (err) {
      safetyCatch(err)
      this._unmarkInflightBlockRequest(req, data)

      if (err.code === 'WRITE_FAILED') {
        // For example, we don't want to keep pulling data when storage is full
        // TODO: notify the user somehow
        this.paused = true
        return
      }

      if (this.core.closed && !isCriticalError(err)) return

      if (err.code !== 'INVALID_OPERATION') {
        // might be a fork, verify
        this._checkIfConflict()
      }

      // if push mode, we MIGHT get an occasional bad message
      // no need to mega bail for that. TODO: rate limit instead as a general thing
      if (!this.replicator.allowPush) {
        this.paused = true
      }

      this.replicator._onnodata(this, req, 0)
      this.replicator._oninvaliddata(err, req, data, this)
      return
    } finally {
      if (isBlockRequest(req)) this.replicator._markProcessed(req.block.index)
      this.dataProcessing--
    }

    this.replicator._ondata(this, req, data)

    if (this._shouldUpdateCanUpgrade() === true) {
      this._updateCanUpgradeAndSync()
    }
  }

  onnodata({ request, reason }) {
    const req = request > 0 ? this.replicator._inflight.get(request) : null

    if (req === null || req.peer !== this) {
      this.replicator.queueUpdateAll()
      return
    }

    this._onrequestroundtrip(req)
    this.replicator._onnodata(this, req, reason)
  }

  _onrequestroundtrip(req) {
    if (req.priority === PRIORITY.CANCELLED) return
    // to avoid re-entry we also just mark it as cancelled
    req.priority = PRIORITY.CANCELLED

    this.inflight--
    this.replicator._requestDone(req.id, true)
    if (this.roundtripQueue === null) return
    const flushed = this.roundtripQueue.flush(req.rt)
    if (flushed === null) return
    for (const id of flushed) this.replicator._inflight.reusable(id)
  }

  onwant(range) {
    if (!this.remoteWants.add(range)) return
    this.replicator._onwant(this, range.start, range.length, range.any)
  }

  onunwant(range) {
    this.remoteWants.remove(range)
  }

  onbitfield({ start, bitfield }) {
    if (start < this._remoteContiguousLength) this._remoteContiguousLength = start // bitfield is always the truth
    this.remoteBitfield.insert(start, bitfield)
    this.missingBlocks.insert(start, bitfield)
    this._clearLocalRange(start, bitfield.byteLength * 8)
    this._update()
  }

  _clearLocalRange(start, length) {
    const bitfield = this.core.skipBitfield === null ? this.core.bitfield : this.core.skipBitfield

    if (length === 1) {
      this.missingBlocks.set(start, this._remoteHasBlock(start) && !bitfield.get(start))
      return
    }

    const contig = Math.min(this.core.state.length, this.core.header.hints.contiguousLength)

    if (start + length < contig) {
      this.missingBlocks.setRange(start, contig, false)
      return
    }

    const rem = start & 32767
    if (rem > 0) {
      start -= rem
      length += rem
    }

    const end = start + Math.min(length, this.core.state.length)
    while (start < end) {
      const local = bitfield.getBitfield(start)

      if (local && local.bitfield) {
        this.missingBlocks.clear(start, local.bitfield)
      }

      start += 32768
    }
  }

  _resetMissingBlock(index) {
    const bitfield = this.core.skipBitfield === null ? this.core.bitfield : this.core.skipBitfield
    this.missingBlocks.set(index, this._remoteHasBlock(index) && !bitfield.get(index))
  }

  _unclearLocalRange(start, length) {
    if (length === 1) {
      this._resetMissingBlock(start)
      return
    }

    const rem = start & (RemoteBitfield.BITS_PER_SEGMENT - 1)
    if (rem > 0) {
      start -= rem
      length += rem
    }

    const fixedStart = start

    const end = start + Math.min(length, this.remoteLength)
    while (start < end) {
      const remote = this.remoteBitfield.getBitfield(start)
      if (remote && remote.bitfield) {
        this.missingBlocks.insert(start, remote.bitfield)
      }

      start += RemoteBitfield.BITS_PER_SEGMENT
    }

    this._clearLocalRange(fixedStart, length)
  }

  async onrange({ drop, start, length }) {
    const has = drop === false

    if (drop === true && start < this._remoteContiguousLength) {
      this._remoteContiguousLength = start
    }

    if (start === 0 && drop === false) {
      if (length > this._remoteContiguousLength) {
        this._remoteContiguousLength = length
        if (
          this.remoteFork === this.core.state.fork &&
          length > this.core.header.hints.remoteContiguousLength
        ) {
          this.core.updateRemoteContiguousLength(length)
        }
      }
    } else if (length === 1) {
      const bitfield = this.core.skipBitfield === null ? this.core.bitfield : this.core.skipBitfield
      this.remoteBitfield.set(start, has)
      this.missingBlocks.set(start, has && !bitfield.get(start))
    } else {
      const rangeStart = this.remoteBitfield.findFirst(!has, start)
      const rangeEnd = length + start

      if (rangeStart !== -1 && rangeStart < rangeEnd) {
        this.remoteBitfield.setRange(rangeStart, rangeEnd, has)
        this.missingBlocks.setRange(rangeStart, rangeEnd, has)
        if (has) this._clearLocalRange(rangeStart, rangeEnd - rangeStart)
      }
    }

    if (this.core.hintsChanged) await this.core.flushHints()
    if (drop === false) this._update()

    this.core.emitRemoteContiguousLength()
  }

  onreorghint() {
    // TODO
  }

  _update() {
    // TODO: if this is in a batch or similar it would be better to defer it
    // we could do that with nextTick/microtick mb? (combined with a property on the session to signal read buffer mb)
    this.replicator.updatePeer(this)
  }

  async _onconflict() {
    this.protomux.cork()
    if (this.remoteLength > 0 && this.core.state.fork === this.remoteFork) {
      await this.onrequest({
        id: 0,
        fork: this.core.state.fork,
        block: null,
        hash: null,
        seek: null,
        upgrade: {
          start: 0,
          length: Math.min(this.core.state.length, this.remoteLength)
        }
      })
    }
    this.channel.close()
    this.protomux.uncork()
  }

  _makeRequest(needsUpgrade, priority, minLength) {
    if (needsUpgrade === true && this.replicator._shouldUpgrade(this) === false) {
      return null
    }

    // ensure that the remote has signalled they have the length we request
    if (this.remoteLength < minLength) {
      return null
    }

    if (needsUpgrade === false && this.replicator._autoUpgrade(this) === true) {
      needsUpgrade = true
    }

    return {
      peer: this,
      rt: this.roundtripQueue === null ? 0 : this.roundtripQueue.tick,
      id: 0,
      fork: this.remoteFork,
      block: null,
      hash: null,
      seek: null,
      upgrade:
        needsUpgrade === false
          ? null
          : { start: this.core.state.length, length: this.remoteLength - this.core.state.length },
      // remote manifest check can be removed eventually...
      manifest: this.core.header.manifest === null && this.remoteHasManifest === true,
      priority,
      timestamp: Date.now(),
      elapsed: 0
    }
  }

  _requestManifest() {
    const req = this._makeRequest(false, 0, 0)
    if (req === null) return

    this._send(req)
  }

  _includeLastBlock() {
    if (this.replicator._alwaysLatestBlock === 0) return null

    const index = this.remoteLength - 1

    // only valid if its an OOB get
    if (index < this.core.state.length) return null

    // do the normal checks
    if (!this._remoteHasBlock(index)) return null
    if (!this._canRequest(index, false)) return null

    // atm we only ever do one upgrade request in parallel, if that changes
    // then we should add some check here for inflights to avoid over requesting
    const b = this.replicator._blocks.add(index, PRIORITY.NORMAL, false)
    return b
  }

  _requestUpgrade(u) {
    if (this.replicator.pushOnly) return false

    const req = this._makeRequest(true, 0, 0)
    if (req === null) return false

    const b = this._includeLastBlock()

    if (b) this._sendBlockRequest(req, b)
    else this._send(req)

    return true
  }

  _requestSeek(s) {
    // if replicator is updating the seeks etc, bail and wait for it to drain
    if (this.replicator._updatesPending > 0) return false
    if (this.replicator.pushOnly) return false

    const { length, fork } = this.core.state

    if (fork !== this.remoteFork) return false

    if (s.seeker.start >= length) {
      const req = this._makeRequest(true, 0, 0)

      // We need an upgrade for the seek, if non can be provided, skip
      if (req === null) return false

      req.seek = this.remoteSupportsSeeks
        ? { bytes: s.seeker.bytes, padding: s.seeker.padding }
        : null

      s.inflight.push(req)
      this._send(req)

      return true
    }

    const len = s.seeker.end - s.seeker.start
    const off = s.seeker.start + Math.floor(Math.random() * len)

    for (let i = 0; i < len; i++) {
      let index = off + i
      if (index > s.seeker.end) index -= len

      if (this._remoteHasBlock(index) === false) continue
      if (this.core.bitfield.get(index) === true) continue
      if (!this._canRequest(index, false)) continue

      // Check if this block is currently inflight - if so pick another
      const b = this.replicator._blocks.get(index)
      if (b !== null && b.inflight.length > 0) continue

      // Block is not inflight, but we only want the hash, check if that is inflight
      const h = this.replicator._hashes.add(index, PRIORITY.NORMAL, false)
      if (h.inflight.length > 0) continue

      const req = this._makeRequest(false, h.priority, index + 1)
      if (req === null) continue

      const nodes = flatTree.depth(s.seeker.start + s.seeker.end - 1)

      req.hash = { index: 2 * index, nodes }
      req.seek = this.remoteSupportsSeeks
        ? { bytes: s.seeker.bytes, padding: s.seeker.padding }
        : null

      s.inflight.push(req)
      h.inflight.push(req)
      this._send(req)

      return true
    }

    this._maybeWantAnyRange(s.seeker.start, len, s)
    return false
  }

  _canRequest(index, force) {
    if (!(index >= 0)) throw ASSERTION('bad index to _canRequest: ' + index)

    if (!force && this.replicator.pushOnly) {
      return false
    }

    if (this.remoteLength >= this.core.state.length) {
      return true
    }

    if (index < this.lastUpgradableLength && this.lastUpgradableFork === this.core.state.fork) {
      return true
    }

    if (this.canUpgrade && this.syncsProcessing === 0) {
      return true
    }

    return false
  }

  _remoteHasBlock(index) {
    return index < this._remoteContiguousLength || this.remoteBitfield.get(index) === true
  }

  _sendBlockRequest(req, b) {
    if (this.core._repairMode) return

    req.block = { index: b.index, nodes: 0 }
    this.replicator._markInflight(b.index)

    b.inflight.push(req)
    this.replicator.hotswaps.add(b)
    this._send(req)
  }

  _requestBlock(b) {
    const { length, fork } = this.core.state

    if (this._remoteHasBlock(b.index) === false || fork !== this.remoteFork) {
      if (!this.core.bitfield.get(b.index)) this._maybeWant(b.index, b)
      return false
    }

    if (!this._canRequest(b.index, b.force)) return false

    const req = this._makeRequest(b.index >= length, b.priority, b.index + 1)
    if (req === null) return false

    this._sendBlockRequest(req, b)

    return true
  }

  _maybeWant(index, handle) {
    if (index < this.remoteContiguousLength) return

    const res = this.wants.add(index, handle)
    if (!res) return

    const batch = res.want && res.unwant
    if (batch) this.protomux.cork()

    if (res.unwant) {
      this.wireUnwant.send(res.unwant)
      incrementTx(this.stats.wireUnwant, this.replicator.stats.wireUnwant)
    }
    if (res.want) {
      this.wireWant.send(res.want)
      incrementTx(this.stats.wireWant, this.replicator.stats.wireWant)
    }

    if (batch) this.protomux.uncork()
  }

  _maybeWantAnyRange(start, length, handle) {
    if (handle.wants) {
      for (const w of handle.wants) {
        if ((w.start !== start || w.length !== length) && w.any) {
          const req = this.wants.removeAnyRange(w.start, w.length, handle)
          if (req) this.wireUnwant.send(req)
        }
      }
    }

    if (start + length <= this.remoteContiguousLength) return

    const req = this.wants.addAnyRange(start, length, handle)
    if (req) this.wireWant.send(req)
  }

  _requestRangeBlock(index, length) {
    if (this.core.bitfield.get(index) === true || !this._canRequest(index, false)) return false

    const b = this.replicator._blocks.add(index, PRIORITY.NORMAL, false)
    if (b.inflight.length > 0) {
      this.missingBlocks.set(index, false) // in case we missed some states just set them ondemand, nbd
      return false
    }

    const req = this._makeRequest(index >= length, b.priority, index + 1)

    // If the request cannot be satisfied, dealloc the block request if no one is subscribed to it
    if (req === null) {
      b.gc()
      return false
    }

    this._sendBlockRequest(req, b)

    // Don't think this will ever happen, as the pending queue is drained before the range queue
    // but doesn't hurt to check this explicitly here also.
    if (b.queued) b.queued = false
    return true
  }

  _findNext(i) {
    if (i < this._remoteContiguousLength) {
      if (this.core.skipBitfield === null) this.replicator._openSkipBitfield()
      i = this.core.skipBitfield.findFirst(false, i)
      if (i < this._remoteContiguousLength && i > -1) return i
      i = this._remoteContiguousLength
    }

    return this.missingBlocks.findFirst(true, i)
  }

  _addRangeBatch(r, offset, end) {
    const { WANT_BATCH } = w
    while (offset < end) {
      const next = this.core.bitfield.findFirst(false, offset)
      if (next === -1 || next >= end) return false

      const b = (next - (next & (WANT_BATCH - 1))) / WANT_BATCH

      if (r.addBatch(b)) return true

      offset = (b + 1) * WANT_BATCH
    }

    return false
  }

  _populateRangeBatches(r) {
    const { WANT_BATCH } = w
    for (let i = r.batches.length - 1; i >= 0; i--) {
      const b = r.batches[i]
      const minStart = b.batch * WANT_BATCH
      const maxEnd = minStart + WANT_BATCH

      const start = Math.max(r.start, minStart)
      const end = Math.min(r.end === -1 ? maxEnd : r.end, maxEnd)

      if (start < end && this.core.bitfield.hasUnset(start, end - start)) continue

      r.removeBatch(b)
    }

    while (r.batches.length < 3) {
      const end = r.end === -1 ? this.core.state.length : r.end
      if (end <= r.start) return

      const len = end - r.start
      const off = r.start + (r.linear ? 0 : Math.floor(Math.random() * len))

      if (!this._addRangeBatch(r, off, end) && !this._addRangeBatch(r, r.start, end)) break
    }
  }

  _requestRangeBatch(start, end, length) {
    let tries = this.inflight

    do {
      start = this._findNext(start)
      if (start === -1 || start >= end) break

      if (this._requestRangeBlock(start, length)) return true
      start++
    } while (tries-- > 0)

    return false
  }

  _getValidEnd(maxEnd) {
    // if we can upgrade the remote, or the remote is ahead, then all the remotes blocks are valid
    // otherwise truncate to the last length the remote has acked for us
    const maxLocalLength =
      this.canUpgrade || this.remoteLength >= this.core.state.length
        ? this.core.state.length
        : this.core.state.fork === this.lastUpgradableFork
          ? Math.min(this.lastUpgradableLength, this.core.state.length)
          : 0

    return Math.min(
      maxLocalLength,
      Math.min(maxEnd === -1 ? this.remoteLength : maxEnd, this.remoteLength)
    )
  }

  _requestRange(r) {
    const { WANT_BATCH } = w
    if (this.syncsProcessing > 0) return false

    const { length, fork } = this.core.state

    if (r.blocks) {
      for (let i = r.start; i < r.end; i++) {
        const index = r.blocks[i]
        const has = index < this._remoteContiguousLength || this.missingBlocks.get(index) === true
        if (has === true && this._requestRangeBlock(index, length)) return true
        this._maybeWant(index, r)
      }

      return false
    }

    this._populateRangeBatches(r)

    const end = this._getValidEnd(r.end)

    if (end <= r.start || fork !== this.remoteFork) return false

    for (let i = 0; i < r.batches.length; i++) {
      const b = r.batches[i]

      const batchStart = Math.max(b.batch * WANT_BATCH, r.start)
      const batchEnd = Math.min((b.batch + 1) * WANT_BATCH, end)
      const len = batchEnd - batchStart
      const off = batchStart + (r.linear ? 0 : Math.floor(Math.random() * len))

      if (
        this._requestRangeBatch(off, end, length) ||
        this._requestRangeBatch(batchStart, off, length)
      ) {
        return true
      }

      this._maybeWant(batchStart, b)
    }

    // Here we should consider making an OOB request (ie if the remote says they have a newer block)
    // but the upgrade code already does that, so no big deal for now

    return false
  }

  _requestForkProof(f) {
    if (!this.remoteLength) return
    if (this.replicator.pushOnly) return

    const req = this._makeRequest(false, 0, 0)
    if (req === null) return

    req.upgrade = { start: 0, length: this.remoteLength }
    req.manifest = !this.core.header.manifest

    f.inflight.push(req)
    this._send(req)
  }

  _requestForkRange(f) {
    if (f.fork !== this.remoteFork || f.batch.want === null) return false
    if (this.replicator.pushOnly) return false

    const end = Math.min(f.batch.want.end, this.remoteLength)
    if (end < f.batch.want.start) return false

    const len = end - f.batch.want.start
    const off = f.batch.want.start + Math.floor(Math.random() * len)

    for (let i = 0; i < len; i++) {
      let index = off + i
      if (index >= end) index -= len

      if (this._remoteHasBlock(index) === false) continue

      const req = this._makeRequest(false, 0, 0)
      if (req === null) return false

      req.hash = { index: 2 * index, nodes: f.batch.want.nodes }

      f.inflight.push(req)
      this._send(req)

      return true
    }

    this._maybeWantAnyRange(f.batch.want.start, len, f)
    return false
  }

  isActive() {
    if (this.paused || this.removed || this.core.header.frozen) return false
    return true
  }

  async _send(req) {
    const fork = this.core.state.fork

    this.inflight++
    this.replicator._inflight.add(req)

    if (req.upgrade !== null && req.fork === fork) {
      const u = this.replicator._addUpgrade()
      u.inflight.push(req)
    }

    try {
      if (req.block !== null && req.fork === fork) {
        req.block.nodes = await MerkleTree.missingNodes(
          this.core.state,
          2 * req.block.index,
          this.core.state.length
        )
        if (req.priority === PRIORITY.CANCELLED) return
      }
      if (req.hash !== null && req.fork === fork && req.hash.nodes === 0) {
        req.hash.nodes = await MerkleTree.missingNodes(
          this.core.state,
          req.hash.index,
          this.core.state.length
        )
        if (req.priority === PRIORITY.CANCELLED) return

        // nodes === 0, we already have it, bail
        if (req.hash.nodes === 0 && (req.hash.index & 1) === 0) {
          this.inflight--
          this.replicator._resolveHashLocally(this, req)
          return
        }
      }
    } catch (err) {
      this.stream.destroy(err)
      return
    }

    this.wireRequest.send(req)
    incrementTx(this.stats.wireRequest, this.replicator.stats.wireRequest)
  }
}

module.exports = class Replicator {
  static Peer = Peer // hack to be able to access Peer from outside this module

  constructor(
    core,
    {
      notDownloadingLinger = NOT_DOWNLOADING_SLACK,
      eagerUpgrade = true,
      allowFork = true,
      allowPush = false,
      alwaysLatestBlock = false,
      inflightRange = null
    } = {}
  ) {
    this.core = core
    this.eagerUpgrade = eagerUpgrade
    this.allowFork = allowFork
    this.allowPush = allowPush
    this.ondownloading = null // optional external hook for monitoring downloading status
    this.peers = []
    this.findingPeers = 0 // updatable from the outside
    this.destroyed = false
    this.downloading = false
    this.pushOnly = false
    this.activeSessions = 0

    this.hotswaps = new HotswapQueue()
    this.inflightRange = inflightRange || DEFAULT_MAX_INFLIGHT

    // Note: nodata and unwant not currently tracked
    // tx = transmitted, rx = received
    this.stats = {
      wireSync: { tx: 0, rx: 0 },
      wireRequest: { tx: 0, rx: 0 },
      wireCancel: { tx: 0, rx: 0 },
      wireData: { tx: 0, rx: 0 },
      wireWant: { tx: 0, rx: 0 },
      wireUnwant: { tx: 0, rx: 0 },
      wireBitfield: { tx: 0, rx: 0 },
      wireRange: { tx: 0, rx: 0 },
      wireExtension: { tx: 0, rx: 0 },
      hotswaps: 0,
      invalidData: 0,
      invalidRequests: 0,
      backoffs: 0,
      notAvailableBackoffs: 0
    }

    this._attached = new Set()
    this._inflight = new InflightTracker()
    this._blocks = new BlockTracker(this)
    this._hashes = new BlockTracker(this)

    this._alwaysLatestBlock = alwaysLatestBlock ? 1 : 0
    this._queued = []

    this._seeks = []
    this._upgrade = null
    this._reorgs = []
    this._ranges = []

    this._rxLock = new Mutex()
    this._txLock = new Mutex()

    this._hadPeers = false
    this._active = 0
    this._ifAvailable = 0
    this._updatesPending = 0
    this._applyingReorg = null
    this._manifestPeer = null
    this._notDownloadingLinger = notDownloadingLinger
    this._notDownloadingTimer = null

    this._updateAllBump = null
    this._updateAllBound = this.updateAll.bind(this)

    const self = this
    this._onstreamclose = onstreamclose

    function onstreamclose() {
      self.detachFrom(this.userData)
    }
  }

  setInflightRange(min, max) {
    const def = this.inflightRange
    this.inflightRange = [min, max]
    for (const peer of this.peers) {
      if (peer.inflightRange !== def) continue
      peer.inflightRange = this.inflightRange
    }
  }

  updateActivity(inc, session) {
    this.activeSessions += inc
    this.setDownloading(this.activeSessions !== 0, session)
  }

  isDownloading() {
    return this.downloading || !this._inflight.idle
  }

  async push(index) {
    const all = []
    for (const peer of this.peers) {
      all.push(peer.push(index))
    }
    await Promise.all(all)
  }

  setAllowPush(allowPush) {
    if (allowPush === this.allowPush) return
    this.allowPush = allowPush
    for (const peer of this.peers) peer.sendSync()
  }

  isAllowingPush() {
    if (!this.allowPush) return false
    if (this._notDownloadingTimer) return false
    return this.downloading
  }

  setPushOnly(pushOnly) {
    if (pushOnly === this.pushOnly) return
    this.pushOnly = pushOnly
  }

  setDownloading(downloading) {
    const allowPush = this.isAllowingPush()
    const linger = this._notDownloadingLinger

    if (this._notDownloadingTimer) {
      clearTimeout(this._notDownloadingTimer)
      this._notDownloadingTimer = null
    }

    if (this.destroyed) return

    if (downloading || linger === 0) {
      if (!this._setDownloadingNow(downloading)) this.signalAllowPush(allowPush)
      return
    }

    this._notDownloadingTimer = setTimeout(setNotDownloadingLater, linger, this)
    if (this._notDownloadingTimer.unref) this._notDownloadingTimer.unref()
    this.signalAllowPush(allowPush)
  }

  signalAllowPush(allowPush) {
    if (allowPush === this.isAllowingPush()) return
    for (const peer of this.peers) peer.signalUpgrade()
  }

  _setDownloadingNow(downloading) {
    this._notDownloadingTimer = null

    if (this.downloading === downloading) return false
    this.downloading = downloading

    if (!downloading && this.isDownloading()) return false

    for (const peer of this.peers) peer.signalUpgrade()

    if (downloading) {
      // restart channel if needed...
      for (const protomux of this._attached) {
        if (!protomux.stream.handshakeHash) continue
        if (protomux.opened({ protocol: 'hypercore/alpha', id: this.core.discoveryKey })) continue
        this._makePeer(protomux, true)
      }
    } else {
      for (const peer of this.peers) peer.closeIfIdle()
    }

    if (this.ondownloading !== null && downloading) this.ondownloading()
    return true
  }

  cork() {
    for (const peer of this.peers) peer.protomux.cork()
  }

  uncork() {
    for (const peer of this.peers) peer.protomux.uncork()
  }

  // Called externally when a range of new blocks has been processed/removed
  onhave(start, length, drop = false) {
    for (const peer of this.peers) peer.broadcastRange(start, length, drop)
  }

  // Called externally when a truncation upgrade has been processed
  ontruncate(newLength, truncated) {
    const notify = []

    for (const blk of this._blocks) {
      if (blk.index < newLength) continue
      notify.push(blk)
    }

    for (const blk of notify) {
      for (const r of blk.refs) {
        if (r.snapshot === false) continue
        blk.detach(r, SNAPSHOT_NOT_AVAILABLE())
      }
    }

    for (const peer of this.peers) {
      peer.fullyDownloadedSignaled = Math.min(newLength, peer.fullyDownloadedSignaled)
      peer._unclearLocalRange(newLength, truncated)
    }
  }

  // Called externally when a upgrade has been processed
  onupgrade() {
    for (const peer of this.peers) peer.signalUpgrade()
    if (this._blocks.isEmpty() === false) this._resolveBlocksLocally()
    if (this._upgrade !== null) this._resolveUpgradeRequest(null)
    if (!this._blocks.isEmpty() || this._ranges.length !== 0 || this._seeks.length !== 0) {
      this._updateNonPrimary(true)
    }
  }

  // Called externally when a conflict has been detected and verified
  async onconflict() {
    const all = []
    for (const peer of this.peers) {
      all.push(peer._onconflict())
    }
    await Promise.allSettled(all)
  }

  async applyPendingReorg() {
    if (this._applyingReorg !== null) {
      await this._applyingReorg
      return true
    }

    for (let i = this._reorgs.length - 1; i >= 0; i--) {
      const f = this._reorgs[i]
      if (f.batch !== null && f.batch.finished) {
        await this._applyReorg(f)
        return true
      }
    }

    return false
  }

  addUpgrade(session) {
    if (this._upgrade !== null) {
      const ref = this._upgrade.attach(session)
      this._checkUpgradeIfAvailable()
      return ref
    }

    const ref = this._addUpgrade().attach(session)

    this.queueUpdateAll()

    return ref
  }

  addBlock(session, index, force) {
    const b = this._blocks.add(index, PRIORITY.HIGH, force)
    const ref = b.attach(session)

    this._queueBlock(b)
    this.queueUpdateAll()

    return ref
  }

  addSeek(session, seeker) {
    const s = new SeekRequest(this, this._seeks, seeker)
    const ref = s.attach(session)

    this._seeks.push(s)
    this.queueUpdateAll()

    return ref
  }

  addRange(
    session,
    { start = 0, end = -1, length = toLength(start, end), blocks = null, linear = false } = {}
  ) {
    if (blocks !== null) {
      // if using blocks, start, end just acts as frames around the blocks array
      start = 0
      end = length = blocks.length
    }

    const r = new RangeRequest(
      this,
      this._ranges,
      start,
      length === -1 ? -1 : start + length,
      linear,
      blocks
    )

    const ref = r.attach(session)

    // Trigger this to see if this is already resolved...
    // Also auto compresses the range based on local bitfield
    clampRange(this.core, r)

    if (r.end !== -1 && r.start >= r.end) {
      this._resolveRangeRequest(r)
      return ref
    }

    this.queueUpdateAll()

    return ref
  }

  cancel(ref) {
    ref.context.detach(ref, null)
  }

  static clearRequests(session, err) {
    if (session.length === 0) return
    if (session.length === 1 && session[0] === null) return

    const updated = new Set()

    while (session.length > 0) {
      const ref = session[session.length - 1]
      updated.add(ref.context.replicator)
      ref.context.detach(ref, err)
    }

    for (const replicator of updated) {
      replicator.queueUpdateAll()
    }
  }

  clearRequests(session, err = null) {
    let cleared = false
    while (session.length > 0) {
      const ref = session[session.length - 1]
      ref.context.detach(ref, err)
      cleared = true
    }

    if (cleared) this.queueUpdateAll()
  }

  _matchingRequest(req, data) {
    if (this.allowPush) {
      return true
    }
    if (data.block !== null && (req.block === null || req.block.index !== data.block.index)) {
      return false
    }
    if (data.hash !== null && (req.hash === null || req.hash.index !== data.hash.index)) {
      return false
    }
    if (data.seek !== null && (req.seek === null || req.seek.bytes !== data.seek.bytes)) {
      return false
    }
    if (data.upgrade !== null && req.upgrade === null) {
      return false
    }
    return req.fork === data.fork
  }

  _addUpgradeMaybe() {
    return this.eagerUpgrade === true ? this._addUpgrade() : this._upgrade
  }

  // TODO: this function is OVER called atm, at each updatePeer/updateAll
  // instead its more efficient to only call it when the conditions in here change - ie on sync/add/remove peer
  // Do this when we have more tests.
  _checkUpgradeIfAvailable() {
    if (this._ifAvailable > 0 && this.peers.length < MAX_PEERS_UPGRADE) return
    if (this._upgrade === null || this._upgrade.refs.length === 0) return
    if (this._hadPeers === false && this.findingPeers > 0) return

    const maxPeers = Math.min(this.peers.length, MAX_PEERS_UPGRADE)

    // check if a peer can upgrade us

    for (let i = 0; i < maxPeers; i++) {
      const peer = this.peers[i]

      if (peer.remoteSynced === false) return

      if (this.core.state.length === 0 && peer.remoteLength > 0) return

      if (peer.remoteLength <= this._upgrade.length || peer.remoteFork !== this._upgrade.fork) {
        continue
      }

      if (peer.syncsProcessing > 0) return

      if (peer.lengthAcked !== this.core.state.length && peer.remoteFork === this.core.state.fork) {
        return
      }

      if (peer.remoteCanUpgrade === true) return
    }

    // check if reorgs in progress...

    if (this._applyingReorg !== null) return

    // TODO: we prob should NOT wait for inflight reorgs here, seems better to just resolve the upgrade
    // and then apply the reorg on the next call in case it's slow - needs some testing in practice

    for (let i = 0; i < this._reorgs.length; i++) {
      const r = this._reorgs[i]
      if (r.inflight.length > 0) return
    }

    // if something is inflight, wait for that first
    if (this._upgrade.inflight.length > 0) return

    // nothing to do, indicate no update avail

    const u = this._upgrade
    this._upgrade = null
    u.resolve(false)
  }

  _addUpgrade() {
    if (this._upgrade !== null) return this._upgrade

    // TODO: needs a reorg: true/false flag to indicate if the user requested a reorg
    this._upgrade = new UpgradeRequest(this, this.core.state.fork, this.core.state.length)

    return this._upgrade
  }

  _addReorg(fork, peer) {
    if (this.allowFork === false) return null

    // TODO: eager gc old reorgs from the same peer
    // not super important because they'll get gc'ed when the request finishes
    // but just spam the remote can do ...

    for (const f of this._reorgs) {
      if (f.fork > fork && f.batch !== null) return null
      if (f.fork === fork) return f
    }

    const f = new ForkRequest(this, fork)

    this._reorgs.push(f)

    // maintain sorted by fork
    let i = this._reorgs.length - 1
    while (i > 0 && this._reorgs[i - 1].fork > fork) {
      this._reorgs[i] = this._reorgs[i - 1]
      this._reorgs[--i] = f
    }

    return f
  }

  _shouldUpgrade(peer) {
    if (this._upgrade !== null && this._upgrade.inflight.length > 0) return false
    return (
      peer.remoteCanUpgrade === true &&
      peer.remoteLength > this.core.state.length &&
      peer.lengthAcked === this.core.state.length
    )
  }

  _autoUpgrade(peer) {
    return (
      this._upgrade !== null &&
      peer.remoteFork === this.core.state.fork &&
      this._shouldUpgrade(peer)
    )
  }

  _addPeer(peer) {
    this._hadPeers = true
    this.peers.push(peer)
    this.updatePeer(peer)
    this._onpeerupdate(true, peer)
  }

  _requestDone(id, roundtrip) {
    this._inflight.remove(id, roundtrip)
    if (this.isDownloading() === true) return
    for (const peer of this.peers) peer.signalUpgrade()
  }

  _removePeer(peer) {
    this.peers.splice(this.peers.indexOf(peer), 1)
    peer.wants.destroy()

    if (this._manifestPeer === peer) this._manifestPeer = null

    let inflight = false
    for (const req of this._inflight) {
      if (req.peer !== peer) continue
      inflight = true
      this._inflight.remove(req.id, true)
      this._clearRequest(peer, req)
    }

    this._onpeerupdate(false, peer)
    if (inflight) {
      this.queueUpdateAll()
    } else {
      this._checkUpgradeIfAvailable()
    }
  }

  _queueBlock(b) {
    if (b.inflight.length > 0 || b.queued === true) return
    b.queued = true
    this._queued.push(b)
  }

  _resolveHashLocally(peer, req) {
    this._requestDone(req.id, false)
    this._resolveBlockRequest(this._hashes, req.hash.index / 2, null, req)
    this.updatePeer(peer)
  }

  // Runs in the background - not allowed to throw
  async _resolveBlocksLocally() {
    // TODO: check if fork compat etc. Requires that we pass down truncation info

    const clear = []
    const blocks = []

    const reader = this.core.storage.read()
    for (const b of this._blocks) {
      if (this.core.bitfield.get(b.index) === false) continue
      blocks.push(this._resolveLocalBlock(b, reader, clear))
    }
    reader.tryFlush()

    await Promise.all(blocks)

    if (!clear.length) return

    // Currently the block tracker does not support deletes during iteration, so we make
    // sure to clear them afterwards.
    for (const b of clear) {
      this._blocks.remove(b.index)
      removeHotswap(b)
    }
  }

  async _resolveLocalBlock(b, reader, resolved) {
    try {
      b.resolve(await reader.getBlock(b.index))
    } catch (err) {
      b.reject(err)
      return
    }

    resolved.push(b)
  }

  _resolveBlockRequest(tracker, index, value, req) {
    const b = tracker.remove(index)
    if (b === null) return false

    removeInflight(b.inflight, req)
    removeHotswap(b)
    b.queued = false

    b.resolve(value)

    if (b.inflight.length > 0) {
      // if anything is still inflight, cancel it
      for (let i = b.inflight.length - 1; i >= 0; i--) {
        const req = b.inflight[i]
        req.peer._cancelRequest(req)
      }
    }

    return true
  }

  _resolveUpgradeRequest(req) {
    if (req !== null) removeInflight(this._upgrade.inflight, req)

    if (
      this.core.state.length === this._upgrade.length &&
      this.core.state.fork === this._upgrade.fork
    ) {
      return false
    }

    const u = this._upgrade
    this._upgrade = null
    u.resolve(true)

    return true
  }

  _resolveRangeRequest(req) {
    req.resolve(true)
    req.gc()
  }

  _clearInflightBlock(tracker, req) {
    const isBlock = tracker === this._blocks
    const index = isBlock === true ? req.block.index : req.hash.index / 2
    const b = tracker.get(index)

    if (b === null || removeInflight(b.inflight, req) === false) return

    if (removeHotswap(b) === true && b.inflight.length > 0) {
      this.hotswaps.add(b)
    }

    if (b.refs.length > 0 && isBlock === true) {
      this._queueBlock(b)
      return
    }

    b.gc()
  }

  _clearInflightUpgrade(req) {
    if (this._upgrade === null || removeInflight(this._upgrade.inflight, req) === false) return
    this._upgrade.gc()
  }

  _clearInflightSeeks(req) {
    for (const s of this._seeks) {
      if (removeInflight(s.inflight, req) === false) continue
      s.gc()
    }
  }

  _clearInflightReorgs(req) {
    for (const r of this._reorgs) {
      removeInflight(r.inflight, req)
    }
  }

  _clearOldReorgs(fork) {
    for (let i = 0; i < this._reorgs.length; i++) {
      const f = this._reorgs[i]
      if (f.fork >= fork) continue
      if (i === this._reorgs.length - 1) this._reorgs.pop()
      else this._reorgs[i] = this._reorgs.pop()
      i--
    }
  }

  // "slow" updates here - async but not allowed to ever throw
  async _updateNonPrimary(updateAll) {
    // Check if running, if so skip it and the running one will issue another update for us (debounce)
    while (++this._updatesPending === 1) {
      let len = Math.min(MAX_RANGES, this._ranges.length)

      for (let i = 0; i < len; i++) {
        const r = this._ranges[i]

        clampRange(this.core, r)

        if (r.end !== -1 && r.start >= r.end) {
          this._resolveRangeRequest(r)
          i--
          if (len > this._ranges.length) len--
          if (this._ranges.length === MAX_RANGES) updateAll = true
        }
      }

      for (let i = 0; i < this._seeks.length; i++) {
        const s = this._seeks[i]

        let err = null
        let res = null

        try {
          res = await s.seeker.update()
        } catch (error) {
          err = error
        }

        if (!res && !err) continue

        if (i < this._seeks.length - 1) this._seeks[i] = this._seeks.pop()
        else this._seeks.pop()

        i--

        if (err) s.reject(err)
        else s.resolve(res)
      }

      // No additional updates scheduled - break
      if (--this._updatesPending === 0) break
      // Debounce the additional updates - continue
      this._updatesPending = 0
    }

    if (this._inflight.idle || updateAll) this.queueUpdateAll()
  }

  _clearRequest(peer, req) {
    if (req.block !== null) {
      this._clearInflightBlock(this._blocks, req)
      this._unmarkInflight(req.block.index)
    }

    if (req.hash !== null) {
      this._clearInflightBlock(this._hashes, req)
    }

    if (req.upgrade !== null && this._upgrade !== null) {
      this._clearInflightUpgrade(req)
    }

    if (this._seeks.length > 0) {
      this._clearInflightSeeks(req)
    }

    if (this._reorgs.length > 0) {
      this._clearInflightReorgs(req)
    }
  }

  _onnodata(peer, req, reason) {
    if (reason === NOT_AVAILABLE) {
      peer.stats.notAvailableBackoffs++
      this.stats.notAvailableBackoffs++

      if (peer.stats.notAvailableBackoffs >= MAX_BACKOFFS) {
        peer.paused = true
      }
    }

    if (reason === INVALID_REQUEST) {
      peer.stats.backoffs++
      this.stats.backoffs++

      if (peer.stats.backoffs >= MAX_BACKOFFS) {
        peer.paused = true
      }
    }

    if (req) {
      this._clearRequest(peer, req)
    }

    this.queueUpdateAll()
  }

  _openSkipBitfield() {
    // technically the skip bitfield gets bits cleared if .clear() is called
    // also which might be in inflight also, but that just results in that section being overcalled shortly
    // worst case, so ok for now

    const bitfield = this.core.openSkipBitfield()

    for (const req of this._inflight) {
      if (req.block) bitfield.set(req.block.index, true) // skip
    }
  }

  _markProcessing(index) {
    const b = this._blocks.get(index)
    if (b) {
      b.processing = true
      return
    }

    const h = this._hashes.get(index)
    if (h) h.processing = true
  }

  _markProcessed(index) {
    const b = this._blocks.get(index)
    if (b) return b.processed()

    const h = this._hashes.get(index)
    if (h) h.processed()
  }

  _markInflight(index) {
    if (this.core.skipBitfield !== null) this.core.skipBitfield.set(index, true)
    for (const peer of this.peers) peer._markInflight(index)
  }

  _unmarkInflight(index) {
    if (this.core.skipBitfield !== null) {
      this.core.skipBitfield.set(index, this.core.bitfield.get(index))
    }
    for (const peer of this.peers) peer._resetMissingBlock(index)
  }

  _ondata(peer, req, data) {
    if (req) {
      req.elapsed = Date.now() - req.timestamp
    }

    if (data.block !== null) {
      this._resolveBlockRequest(this._blocks, data.block.index, data.block.value, req)
      this._ondownload(data.block.index, data.block.value.byteLength, peer, req)
    }

    if (data.hash !== null && (data.hash.index & 1) === 0) {
      this._resolveBlockRequest(this._hashes, data.hash.index / 2, null, req)
    }

    if (this._upgrade !== null) {
      this._resolveUpgradeRequest(req)
    }

    if (this._seeks.length > 0) {
      this._clearInflightSeeks(req)
    }

    if (this._reorgs.length > 0) {
      this._clearInflightReorgs(req)
    }

    if (this._manifestPeer === peer && this.core.header.manifest !== null) {
      this._manifestPeer = null
    }

    if (this._seeks.length > 0 || this._ranges.length > 0) {
      this._updateNonPrimary(this._seeks.length > 0)
    }

    this.updatePeer(peer)
  }

  _onwant(peer, start, length, any) {
    if (!peer.isActive()) return

    const contig = Math.min(this.core.state.length, this.core.header.hints.contiguousLength)

    if (start + length < contig || this.core.state.length === contig || (any && start < contig)) {
      peer.wireRange.send({
        drop: false,
        start: 0,
        length: contig
      })
      incrementTx(peer.stats.wireRange, this.stats.wireRange)
      return
    }

    length = Math.min(length, this.core.state.length - start)

    if (any) {
      const bit = this.core.bitfield.firstSet(start)
      if (bit > -1 && bit < start + length) {
        peer.wireRange.send({
          drop: false,
          start: bit,
          length: 1
        })
      }
      return
    }

    for (const msg of this.core.bitfield.want(start, length)) {
      peer.wireBitfield.send(msg)
      incrementTx(peer.stats.wireBitfield, this.stats.wireBitfield)
    }
  }

  async _onreorgdata(peer, req, data) {
    const newBatch = data.upgrade && (await this.core.verifyReorg(data))
    const f = this._addReorg(data.fork, peer)

    if (f === null) {
      this.queueUpdateAll()
      return
    }

    removeInflight(f.inflight, req)

    if (f.batch) {
      await f.batch.update(data)
    } else if (data.upgrade) {
      f.batch = newBatch

      // Remove "older" reorgs in progress as we just verified this one.
      this._clearOldReorgs(f.fork)
    }

    if (f.batch && f.batch.finished) {
      if (this._addUpgradeMaybe() !== null) {
        await this._applyReorg(f)
      }
    }

    this.queueUpdateAll()
  }

  // Never throws, allowed to run in the background
  async _applyReorg(f) {
    // TODO: more optimal here to check if potentially a better reorg
    // is available, ie higher fork, and request that one first.
    // This will request that one after this finishes, which is fine, but we
    // should investigate the complexity in going the other way

    const u = this._upgrade
    const old = this._reorgs

    this._reorgs = [] // clear all as the nodes are against the old tree - easier
    this._applyingReorg = this.core.reorg(f.batch, null) // TODO: null should be the first/last peer?

    try {
      await this._applyingReorg
    } catch (err) {
      this._upgrade = null
      u.reject(err)
    }

    this._applyingReorg = null

    if (this._upgrade !== null) {
      this._resolveUpgradeRequest(null)
    }

    for (const peer of this.peers) this._updateFork(peer)

    // TODO: all the remaining is a tmp workaround until we have a flag/way for ANY_FORK
    for (const r of this._ranges) {
      r.start = r.userStart
      r.end = r.userEnd
    }

    for (const f of old) f.resolve()
    f.resolve()

    this.queueUpdateAll()
  }

  _maybeUpdate() {
    return this._upgrade !== null && this._upgrade.inflight.length === 0
  }

  _maybeRequestManifest() {
    return this.core.header.manifest === null && this._manifestPeer === null
  }

  _updateFork(peer) {
    if (
      this._applyingReorg !== null ||
      this.allowFork === false ||
      peer.remoteFork <= this.core.state.fork
    ) {
      return false
    }

    const f = this._addReorg(peer.remoteFork, peer)

    // TODO: one per peer is better
    if (f !== null && f.batch === null && f.inflight.length === 0) {
      return peer._requestForkProof(f)
    }

    return false
  }

  _updateHotswap(peer) {
    const maxHotswaps = peer.getMaxHotswapInflight()
    if (!peer.isActive() || peer.inflight >= maxHotswaps) return

    for (const b of this.hotswaps.pick(peer)) {
      if (peer._requestBlock(b) === false) continue
      peer.stats.hotswaps++
      peer.replicator.stats.hotswaps++
      if (peer.inflight >= maxHotswaps) break
    }
  }

  _updatePeer(peer) {
    if (!peer.isActive() || peer.inflight >= peer.getMaxInflight() || !peer.remoteUploading) {
      return false
    }

    // Eagerly request the manifest even if the remote length is 0. If not 0 we'll get as part of the upgrade request...
    if (
      this._maybeRequestManifest() === true &&
      peer.remoteLength === 0 &&
      peer.remoteHasManifest === true
    ) {
      this._manifestPeer = peer
      peer._requestManifest()
    }

    for (const s of this._seeks) {
      if (s.inflight.length > 0) continue // TODO: one per peer is better
      if (peer._requestSeek(s) === true) {
        return true
      }
    }

    // Implied that any block in the queue should be requested, no matter how many inflights
    const blks = new RandomIterator(this._queued)

    for (const b of blks) {
      if (b.queued === false || peer._requestBlock(b) === true) {
        b.queued = false
        blks.dequeue()
        return true
      }
    }

    return false
  }

  _updatePeerNonPrimary(peer) {
    if (!peer.isActive() || peer.inflight >= peer.getMaxInflight() || !peer.remoteUploading) {
      return false
    }

    const ranges = new RandomIterator(this._ranges)
    let tried = 0

    for (const r of ranges) {
      if (peer._requestRange(r) === true) {
        return true
      }
      if (++tried >= MAX_RANGES) break
    }

    // Iterate from newest fork to oldest fork...
    for (let i = this._reorgs.length - 1; i >= 0; i--) {
      const f = this._reorgs[i]
      if (f.batch !== null && f.inflight.length === 0 && peer._requestForkRange(f) === true) {
        return true
      }
    }

    if (this._maybeUpdate() === true && peer._requestUpgrade(this._upgrade) === true) {
      return true
    }

    return false
  }

  updatePeer(peer) {
    // Quick shortcut to wait for flushing reorgs - not needed but less waisted requests
    if (this._applyingReorg !== null) return

    while (this._updatePeer(peer) === true);
    while (this._updatePeerNonPrimary(peer) === true);

    if (this.peers.length > 1 && this._blocks.isEmpty() === false) {
      this._updateHotswap(peer)
    }

    this._checkUpgradeIfAvailable()
  }

  updateSubset() {
    return this.updateAll(false)
  }

  updateAll(all = true) {
    // Clear queued scan if a full scan
    if (this._updateAllBump !== null && all) {
      clearTimeout(this._updateAllBump)
      this._updateAllBump = null
    }

    // Quick shortcut to wait for flushing reorgs - not needed but less waisted requests
    if (this._applyingReorg !== null) return

    const peers = new RandomIterator(this.peers)

    const limit = all ? peers.length : MIN_PEER_UPDATE_ALL
    let tried = 0
    for (const peer of peers) {
      tried++
      if (this._updatePeer(peer) === true) {
        peers.requeue()
      }
      if (tried >= limit) break
    }

    // Check if we can skip the non primary check fully
    if (this._maybeUpdate() === false && this._ranges.length === 0 && this._reorgs.length === 0) {
      this._checkUpgradeIfAvailable()
      return
    }

    tried = 0
    for (const peer of peers.restart()) {
      tried++
      if (this._updatePeerNonPrimary(peer) === true) {
        peers.requeue()
      }
      if (tried >= limit) break
    }

    this._checkUpgradeIfAvailable()
  }

  getUpdateAllDelay(peers) {
    return Math.min(3000, Math.max(100, (peers.length - MIN_PEER_UPDATE_ALL) * 5))
  }

  queueUpdateAll() {
    if (this.peers.length < MIN_PEER_UPDATE_ALL) return this.updateAll()

    // Immediately scan subset
    this.updateSubset()

    // Schedule full scan
    if (this._updateAllBump !== null) return //skip if already scheduled
    this._updateAllBump = setTimeout(this._updateAllBound, this.getUpdateAllDelay(this.peers))
  }

  onpeerdestroy() {
    if (--this._active === 0) this.core.checkIfIdle()
  }

  attached(protomux) {
    return this._attached.has(protomux)
  }

  attachTo(protomux) {
    if (this.core.closed) return

    const makePeer = this._makePeer.bind(this, protomux)

    this._attached.add(protomux)
    protomux.pair({ protocol: 'hypercore/alpha', id: this.core.discoveryKey }, makePeer)
    protomux.stream.setMaxListeners(0)
    protomux.stream.on('close', this._onstreamclose)

    this._ifAvailable++
    this._active++

    protomux.stream.opened.then((opened) => {
      this._ifAvailable--
      this._active--

      if (opened && !this.destroyed) makePeer()
      this._checkUpgradeIfAvailable()

      this.core.checkIfIdle()
    })
  }

  detachFrom(protomux) {
    if (this._attached.delete(protomux)) {
      protomux.stream.removeListener('close', this._onstreamclose)
      protomux.unpair({ protocol: 'hypercore/alpha', id: this.core.discoveryKey })
    }
  }

  idle() {
    return this.peers.length === 0 && this._active === 0
  }

  close() {
    const waiting = []

    for (const peer of this.peers) {
      waiting.push(peer.channel.fullyClosed())
    }

    this.destroy()
    return Promise.all(waiting)
  }

  destroy() {
    if (this.destroyed) return
    this.destroyed = true

    if (this._notDownloadingTimer) {
      clearTimeout(this._notDownloadingTimer)
      this._notDownloadingTimer = null
    }

    if (this._updateAllBump) {
      clearTimeout(this._updateAllBump)
      this._updateAllBump = null
    }

    while (this.peers.length) {
      const peer = this.peers[this.peers.length - 1]
      this.detachFrom(peer.protomux)
      peer.channel.close() // peer is removed from array in onclose
    }

    for (const protomux of this._attached) {
      this.detachFrom(protomux)
    }
  }

  _makePeer(protomux) {
    const replicator = this
    if (protomux.opened({ protocol: 'hypercore/alpha', id: this.core.discoveryKey })) {
      return onnochannel()
    }

    const channel = protomux.createChannel({
      userData: null,
      protocol: 'hypercore/alpha',
      aliases: ['hypercore'],
      id: this.core.discoveryKey,
      handshake: m.wire.handshake,
      messages: [
        { encoding: m.wire.sync, onmessage: onwiresync },
        { encoding: m.wire.request, onmessage: onwirerequest },
        { encoding: m.wire.cancel, onmessage: onwirecancel },
        { encoding: m.wire.data, onmessage: onwiredata },
        { encoding: m.wire.noData, onmessage: onwirenodata },
        { encoding: m.wire.want, onmessage: onwirewant },
        { encoding: m.wire.unwant, onmessage: onwireunwant },
        { encoding: m.wire.bitfield, onmessage: onwirebitfield },
        { encoding: m.wire.range, onmessage: onwirerange },
        { encoding: m.wire.extension, onmessage: onwireextension }
      ],
      onopen: onwireopen,
      onclose: onwireclose,
      ondrain: onwiredrain,
      ondestroy: onwiredestroy
    })

    if (channel === null) return onnochannel()

    const peer = new Peer(replicator, protomux, channel, this.inflightRange)
    const stream = protomux.stream

    peer.channel.open({
      seeks: true,
      capability: caps.replicate(stream.isInitiator, this.core.key, stream.handshakeHash)
    })

    return true

    function onnochannel() {
      return false
    }
  }

  _onpeerupdate(added, peer) {
    const name = added ? 'peer-add' : 'peer-remove'
    const sessions = this.core.monitors

    for (let i = sessions.length - 1; i >= 0; i--) {
      sessions[i].emit(name, peer)

      if (added) {
        for (const ext of sessions[i].extensions.values()) {
          peer.extensions.set(ext.name, ext)
        }
      }
    }
  }

  _ondownload(index, byteLength, from, req) {
    const sessions = this.core.monitors

    for (let i = sessions.length - 1; i >= 0; i--) {
      const s = sessions[i]
      s.emit('download', index, byteLength - s.padding, from, req)
    }
  }

  _onupload(index, byteLength, from) {
    const sessions = this.core.monitors

    for (let i = sessions.length - 1; i >= 0; i--) {
      const s = sessions[i]
      s.emit('upload', index, byteLength - s.padding, from)
    }
  }

  _oninvaliddata(err, req, res, from) {
    const sessions = this.core.monitors

    this.stats.invalidData++
    from.stats.invalidData++
    for (let i = 0; i < sessions.length; i++) {
      sessions[i].emit('verification-error', err, req, res, from)
    }
  }

  _oninvalidrequest(err, req, from) {
    const sessions = this.core.monitors

    from.stats.invalidRequests++
    this.stats.invalidRequests++
    for (let i = 0; i < sessions.length; i++) {
      sessions[i].emit('invalid-request', err, req, from)
    }
  }
}

function removeHotswap(block) {
  if (block.hotswap === null) return false
  block.hotswap.ref.remove(block)
  return true
}

function removeInflight(inf, req) {
  const i = inf.indexOf(req)
  if (i === -1) return false
  if (i < inf.length - 1) inf[i] = inf.pop()
  else inf.pop()
  return true
}

function toLength(start, end) {
  return end === -1 ? -1 : end < start ? 0 : end - start
}

function clampRange(core, r) {
  if (r.blocks === null) {
    const start = core.bitfield.firstUnset(r.start)

    if (r.end === -1) r.start = start === -1 ? core.state.length : start
    else if (start === -1 || start >= r.end) r.start = r.end
    else {
      r.start = start

      const end = core.bitfield.lastUnset(r.end - 1)

      if (end === -1 || start >= end + 1) r.end = r.start
      else r.end = end + 1
    }
  } else {
    while (r.start < r.end && core.bitfield.get(r.blocks[r.start])) r.start++
    while (r.start < r.end && core.bitfield.get(r.blocks[r.end - 1])) r.end--
  }
}

function onrequesttimeout(req) {
  if (req.context) req.context.detach(req, REQUEST_TIMEOUT())
}

function destroyRequestTimeout(req) {
  if (req.timeout !== null) {
    clearTimeout(req.timeout)
    req.timeout = null
  }
}

function isCriticalError(err) {
  // TODO: expose .critical or similar on the hypercore errors that are critical (if all not are)
  return err.name === 'HypercoreError'
}

function onwireopen(m, c) {
  return c.userData.onopen(m)
}

function onwireclose(isRemote, c) {
  return c.userData.onclose(isRemote)
}

function onwiredestroy(c) {
  c.userData.replicator.onpeerdestroy()
}

function onwiredrain(c) {
  return c.userData.ondrain()
}

function onwiresync(m, c) {
  incrementRx(c.userData.stats.wireSync, c.userData.replicator.stats.wireSync)
  return c.userData.onsync(m)
}

function onwirerequest(m, c) {
  incrementRx(c.userData.stats.wireRequest, c.userData.replicator.stats.wireRequest)
  return c.userData.onrequest(m)
}

function onwirecancel(m, c) {
  incrementRx(c.userData.stats.wireCancel, c.userData.replicator.stats.wireCancel)
  return c.userData.oncancel(m)
}

function onwiredata(m, c) {
  incrementRx(c.userData.stats.wireData, c.userData.replicator.stats.wireData)
  return c.userData.ondata(m)
}

function onwirenodata(m, c) {
  return c.userData.onnodata(m)
}

function onwirewant(m, c) {
  incrementRx(c.userData.stats.wireWant, c.userData.replicator.stats.wireWant)
  return c.userData.onwant(m)
}

function onwireunwant(m, c) {
  return c.userData.onunwant(m)
}

function onwirebitfield(m, c) {
  incrementRx(c.userData.stats.wireBitfield, c.userData.replicator.stats.wireBitfield)
  return c.userData.onbitfield(m)
}

function onwirerange(m, c) {
  incrementRx(c.userData.stats.wireRange, c.userData.replicator.stats.wireRange)
  return c.userData.onrange(m)
}

function onwireextension(m, c) {
  incrementRx(c.userData.stats.wireExtension, c.userData.replicator.stats.wireExtension)
  return c.userData.onextension(m)
}

function setNotDownloadingLater(repl, session) {
  repl._setDownloadingNow(false, session)
}

function isBlockRequest(req) {
  return req !== null && req.block !== null
}

function isUpgradeRequest(req) {
  return req !== null && req.upgrade !== null
}

function incrementTx(stats1, stats2) {
  stats1.tx++
  stats2.tx++
}

function incrementRx(stats1, stats2) {
  stats1.rx++
  stats2.rx++
}

function noop() {}

function backoff(times) {
  const sleep = times < 2 ? 200 : times < 5 ? 500 : times < 40 ? 1000 : 5000
  return new Promise((resolve) => setTimeout(resolve, sleep))
}
const crypto = require('hypercore-crypto')
const b4a = require('b4a')
const assert = require('nanoassert')
const flat = require('flat-tree')
const quickbit = require('quickbit-universal')
const HypercoreStorage = require('hypercore-storage')

const {
  INVALID_OPERATION,
  INVALID_SIGNATURE,
  ASSERTION,
  SESSION_CLOSED,
  SESSION_NOT_WRITABLE
} = require('hypercore-errors')

const Mutex = require('./mutex')
const Bitfield = require('./bitfield')
const { MerkleTree, MerkleTreeBatch } = require('./merkle-tree')

class SessionState {
  constructor(core, parent, storage, treeInfo, name) {
    this.core = core
    this.index = this.core.sessionStates.push(this) - 1

    this.storage = storage
    this.name = name
    this.sessions = []

    // small hack to close old storages as late as possible.
    // TODO: add a read lock so we can avoid that
    this.lingers = null

    this.parent = parent
    this.atomized = null
    this.mutex = new Mutex()

    // merkle state
    this.roots = treeInfo.roots.length ? treeInfo.roots : []
    this.fork = treeInfo.fork || 0
    this.length = this.roots.length ? MerkleTree.span(this.roots) / 2 : treeInfo.length
    this.byteLength = MerkleTree.size(this.roots)
    this.prologue = treeInfo.prologue || null
    this.signature = treeInfo.signature || null

    this.snapshotCompatLength = this.isSnapshot()
      ? Math.min(this.length, this.core.state.length)
      : -1
    this.lastTruncation = null
    this.groupUpdated = false

    this.active = 0

    this._activeTx = null
    this._pendingBitfield = null

    this.ref()
  }

  static RECOVERY_PEERS = null

  isSnapshot() {
    return this.storage.snapshotted
  }

  isDefault() {
    return this.core.state === this || this.isAtomicDefault()
  }

  isAtomicDefault() {
    return !!this.storage.atom && !!this.parent && this.parent.isDefault()
  }

  createTreeBatch() {
    return new MerkleTreeBatch(this)
  }

  addSession(s) {
    if (s._stateIndex !== -1) return
    s._stateIndex = this.sessions.push(s) - 1
    if (s.weak === false) this.core.activeSessions++
  }

  removeSession(s) {
    if (s._stateIndex === -1) return
    const head = this.sessions.pop()
    if (head !== s) this.sessions[(head._stateIndex = s._stateIndex)] = head
    s._stateIndex = -1
    if (s.weak === false) this.core.activeSessions--
    this.core.checkIfIdle()
  }

  flushedLength() {
    if (this.isDefault() || this.isSnapshot()) return this.length
    const deps = this.storage.dependencies
    if (deps.length) return deps[deps.length - 1].length
    return 0
  }

  signedLength() {
    const l = Math.min(this.flushedLength(), this.core.state.length)
    return this.isSnapshot() && l > this.snapshotCompatLength ? this.snapshotCompatLength : l
  }

  unref() {
    if (--this.active > 0) return
    this.close().catch(noop) // technically async, but only for the last db session
  }

  ref() {
    this.active++
    return this
  }

  hash() {
    return MerkleTree.hash(this)
  }

  setRoots(roots) {
    this.roots = roots
    this.length = MerkleTree.span(roots) / 2
    this.byteLength = MerkleTree.size(roots)
  }

  get encryptionFork() {
    return this.core.header.tree.fork
  }

  async _updateSnapshotStorage(storage) {
    if (!this.atomized || !this.atomized.flushing) return this.treeInfo()
    while (this.atomized.flushing) await this.atomized.flushed()

    let rx = storage.read()
    const headPromise = rx.getHead()
    const authPromise = rx.getAuth()
    const depPromise = rx.getDependency()

    rx.tryFlush()
    const [head, auth, dep] = await Promise.all([headPromise, authPromise, depPromise])

    storage.setDependencyHead(dep)

    const fork = head ? head.fork : 0
    const length = head ? head.length : 0

    rx = storage.read()
    const rootPromises = []
    for (const r of flat.fullRoots(length * 2)) {
      rootPromises.push(rx.getTreeNode(r))
    }

    rx.tryFlush()

    const roots = await Promise.all(rootPromises)

    // dbl check if we are hitting an regression from earler
    for (const root of roots) {
      if (root === null) {
        throw new Error(
          'Bad snapshot from atomized session, id = ' +
            this.core.id +
            ' length = ' +
            length +
            ' fork = ' +
            fork
        )
      }
    }

    return {
      fork,
      roots,
      length,
      prologue: auth.manifest && auth.manifest.prologue,
      signature: head && head.signature
    }
  }

  treeInfo() {
    return {
      fork: this.fork,
      roots: this.roots.slice(),
      length: this.length,
      prologue: this.prologue,
      signature: this.signature
    }
  }

  async close() {
    if (this.index === -1) return

    this.active = 0
    this.mutex.destroy(new Error('Closed')).catch(noop)
    if (this.parent && this.parent.atomized) this.parent.atomized = null

    const closing = this.storage.close()

    const head = this.core.sessionStates.pop()
    if (head !== this) this.core.sessionStates[(head.index = this.index)] = head

    this.index = -1
    this.core.checkIfIdle()

    if (this.lingers !== null) {
      for (const storage of this.lingers) await storage.close()
    }

    return closing
  }

  async snapshot() {
    const storage = this.storage.snapshot()
    const treeInfo = await this._updateSnapshotStorage(storage)

    return new SessionState(this.core, null, storage, treeInfo, this.name)
  }

  updateDependency(tx, length) {
    const dependency = updateDependency(this, length, false)
    if (dependency) tx.setDependency(dependency)
    return dependency
  }

  updateGroupIndex(tx, tree) {
    const { pointer } = this.core.header.group

    tx.deleteGroupUpdate(pointer, this.core.header.tree.timestamp)
    tx.putGroupUpdate(pointer, tree.timestamp, this.core.header.key)

    this.groupUpdated = true
  }

  _clearActiveBatch() {
    this._activeTx = null
  }

  createWriteBatch() {
    assert(!this._activeTx && !this.storage.snapshotted)

    this._activeTx = this.storage.write()
    return this._activeTx
  }

  _unlock() {
    this._clearActiveBatch()
    this.mutex.unlock()
    this.core.checkIfIdle()
  }

  _flushHooks() {
    if (!this.groupUpdated) return
    this.groupUpdated = false
    this.core.ongroupupdate(this.core.header.group.key, {
      key: this.core.key,
      length: this.length,
      fork: this.fork
    })
  }

  async flush() {
    const tx = this._activeTx
    this._activeTx = null

    try {
      if (!(await tx.flush())) return false
    } finally {
      this._clearActiveBatch()
    }

    this.lastTruncation = null
    return true
  }

  _precommit(state) {
    assert(
      state.parent === this && state.storage.core.dataPointer === this.storage.core.dataPointer,
      'Atomic state must flush to parent'
    )
  }

  async _commit() {
    await this.mutex.lock()

    try {
      const bitfield = this._pendingBitfield
      this._pendingBitfield = null
      this.lastTruncation = null
      await this.parent._oncommit(this, bitfield)
    } finally {
      this.mutex.unlock()
    }
  }

  async _oncommit(src, bitfield) {
    await this.mutex.lock()

    try {
      const currLength = this.length

      // load dependency into memory
      const rx = this.storage.read()
      const dependencyPromise = rx.getDependency()

      rx.tryFlush()

      const dependency = await dependencyPromise

      this.fork = src.fork
      this.length = src.length
      this.byteLength = src.byteLength
      this.roots = src.roots.slice()
      this.signature = src.signature

      const tree = {
        fork: this.fork,
        length: this.length,
        rootHash: this.hash(),
        signature: this.signature,
        timestamp: Date.now()
      }

      if (this.isDefault() && this.core.header.group) {
        const tx = this.createWriteBatch()
        this.updateGroupIndex(tx, tree)
        await this.flush()
        this._flushHooks()
      }

      if (dependency) this.storage.setDependencyHead(dependency)

      const b = bitfield

      if (b && b.truncated && b.start < currLength) {
        this.ontruncate(tree, b.start, currLength, true)
        if (!b || b.appends === 0) return
      }

      const append = b ? { start: b.start, length: b.appends, drop: false } : null

      this.onappend(tree, append, true)

      if (this.core.hintsChanged && this.isDefault()) await this.core.flushHints()
    } finally {
      this._unlock()
    }
  }

  async setUserData(key, value) {
    await this.mutex.lock()

    try {
      const tx = this.createWriteBatch()
      tx.putUserData(key, value)

      return await this.flush()
    } finally {
      this._unlock()
    }
  }

  async _verifyBlock(batch, bitfield, value, manifest, from) {
    await this.mutex.lock()

    try {
      if (batch.upgraded && batch.length <= this.length) {
        await batch.downgrade()
      }

      if (!batch.commitable()) {
        return false
      }

      if (this.core.preupdate !== null) {
        await this.core.preupdate(batch, this.core.header.key)
      }

      const tx = this.createWriteBatch()

      if (bitfield) {
        tx.putBlock(bitfield.start, value)
      }

      if (bitfield && this.isDefault()) {
        await storeBitfieldRange(this.storage, tx, bitfield.start, bitfield.start + 1, true)
      }

      if (manifest) this.core._setManifest(tx, manifest, null)

      assert(batch.commitable(), 'Should still be commitable')
      batch.commit(tx)

      const head = {
        fork: batch.fork,
        length: batch.length,
        rootHash: batch.hash(),
        signature: batch.signature,
        timestamp: Date.now()
      }

      if (batch.upgraded) {
        tx.setHead(head)

        if (this.core.header.group) {
          this.updateGroupIndex(tx, head)
        }
      }

      const flushed = await this.flush()

      if (batch.upgraded) {
        this.roots = batch.roots
        this.length = batch.length
        this.byteLength = batch.byteLength
        this.fork = batch.fork
        this.signature = batch.signature

        this.onappend(head, bitfield, flushed)
      }

      if (this.core.hintsChanged && this.isDefault()) await this.core.flushHints()
    } finally {
      this._unlock()
    }

    return true
  }

  async truncate(length, fork, { signature, keyPair } = {}) {
    if (!keyPair && this.isDefault()) keyPair = this.core.header.keyPair

    await this.mutex.lock()

    try {
      if (this.prologue && length < this.prologue.length) {
        throw INVALID_OPERATION('Truncation breaks prologue', this.core.discoveryKey)
      }
      if (length > this.length) {
        throw INVALID_OPERATION(
          'Not a truncation, ' + length + ' must be less or equal to ' + this.length,
          this.core.discoveryKey
        )
      }

      const batch = this.createTreeBatch()
      await MerkleTree.truncate(this, length, batch, fork)

      if (signature) {
        batch.signature = signature
        this.core._verifyBatchUpgrade(batch)
      } else if (keyPair) {
        batch.signature = this.core.verifier.sign(batch, keyPair)
      }

      const tx = this.createWriteBatch()

      // upsert compat manifest
      if (this.core.verifier === null && keyPair) this.core._setManifest(tx, null, keyPair)

      const { dependency, tree, roots } = await this._truncate(tx, batch)

      for (const sessionState of this.core.sessionStates) {
        if (
          sessionState.isSnapshot() &&
          sessionState.name === this.name &&
          length < sessionState.snapshotCompatLength
        ) {
          sessionState.snapshotCompatLength = length
        }
      }

      const flushed = await this.flush()

      this.fork = tree.fork
      this.length = tree.length
      this.byteLength = MerkleTree.size(roots)
      this.roots = roots
      this.signature = tree.signature

      if (dependency) this.storage.setDependencyHead(dependency)

      this.ontruncate(tree, tree.length, batch.treeLength, flushed)

      if (this.core.hintsChanged && this.isDefault()) await this.core.flushHints()
    } finally {
      this._unlock()
    }
  }

  async reorg(batch) {
    await this.mutex.lock()

    const storage = this.createWriteBatch()

    try {
      if (!batch.commitable()) return false

      const { dependency, tree } = await this._truncate(storage, batch)

      const flushed = await this.flush()

      this.fork = batch.fork
      this.length = batch.length
      this.byteLength = batch.byteLength
      this.roots = batch.roots
      this.signature = batch.signature

      if (dependency) this.storage.setDependencyHead(dependency)

      this.ontruncate(tree, batch.ancestors, batch.treeLength, flushed)

      if (this.core.hintsChanged && this.isDefault()) await this.core.flushHints()
    } finally {
      this._unlock()
    }
  }

  async _truncate(storage, batch) {
    storage.deleteBlockRange(batch.ancestors, batch.treeLength)

    assert(batch.commitable(), 'Batch must be commitable')

    const tree = {
      fork: batch.fork,
      length: batch.length,
      rootHash: batch.hash(),
      signature: batch.signature,
      timestamp: Date.now()
    }

    if (this.isDefault() && this.core.header.group) {
      this.updateGroupIndex(storage, tree)
    }

    storage.setHead(tree)
    batch.commit(storage)

    const truncated = batch.length < this.flushedLength()
    const dependency = truncated ? updateDependency(this, batch.length, true) : null

    if (dependency) storage.setDependency(dependency)

    if (this.isDefault()) {
      await storeBitfieldRange(this.storage, storage, batch.ancestors, batch.treeLength, false)
      if (batch.ancestors < this.core.header.hints.contiguousLength) {
        this.core.header.hints.remoteContiguousLength = Math.min(
          batch.length,
          this.core.header.hints.remoteContiguousLength
        )
        storage.setHints({
          contiguousLength: batch.ancestors,
          remoteContiguousLength: this.core.header.hints.remoteContiguousLength
        })
      }
    }

    return { dependency, tree, roots: batch.roots }
  }

  async clear(start, end, cleared) {
    await this.mutex.lock()

    try {
      const tx = this.createWriteBatch()

      const ite = flat.iterator(start * 2)
      while (!isRootIndex(ite.index, this.roots)) {
        const a = ite.index
        const b = ite.sibling()
        ite.parent()

        const [left, right] = flat.spans(b)
        const s = left / 2
        const e = right / 2 + 1
        const has = s <= start && e <= end ? false : this.core.bitfield.hasSet(s, e - s)
        if (has) break

        tx.deleteTreeNode(a)
        tx.deleteTreeNode(b)
      }

      if (this.isDefault()) {
        await storeBitfieldRange(this.storage, tx, start, end, false)
        if (start < this.core.header.hints.contiguousLength) {
          tx.setHints({
            contiguousLength: start,
            remoteContiguousLength: this.core.header.hints.remoteContiguousLength
          })
        }
      }

      if (end - start === 1) tx.deleteBlock(start)
      else tx.deleteBlockRange(start, end)

      const dependency = start < this.flushedLength() ? updateDependency(this, start, true) : null

      const flushed = await this.flush()

      if (dependency) this.storage.setDependencyHead(dependency)

      // todo: atomic event handle
      if (this.isDefault() && flushed) {
        const length = end - start

        this.core.updateContiguousLength({ start, length, drop: true })
        this.core._setBitfieldRanges(start, end, false)
        this.core.replicator.onhave(start, length, true)

        if (this.core.hintsChanged) await this.core.flushHints()
      }
    } finally {
      this._unlock()
    }
  }

  // simple tool to wait for other peers to catch us up
  async waitForRecovery() {
    const length = this.length
    const replicator = this.core.replicator

    while (!this.closing) {
      let peers = getRecoveryPeers(replicator.peers)

      if (peers.length < 1) {
        await new Promise((resolve) => setTimeout(resolve, 5000))
        continue
      }

      let restart = false

      for (let i = 0; i < 32; i++) {
        await new Promise((resolve) => setTimeout(resolve, 250))

        peers = getRecoveryPeers(replicator.peers)

        if (this.closing || !validateRecoveryPeers(peers, this.length)) {
          restart = true
          break
        }
      }

      if (restart) continue

      if (this.length !== length) {
        throw SESSION_NOT_WRITABLE('core recovered during append')
      }

      this.core.header.hints.recovering = 0
      this.core.hintsChanged = true

      await this.mutex.lock()
      try {
        await this.core.flushHints()
        return
      } finally {
        this.mutex.unlock()
      }
    }

    throw SESSION_CLOSED('Cannot recover a closed session', this.discoveryKey)
  }

  async append(values, { signature, keyPair, preappend, postappend, maxLength = -1 } = {}) {
    if (!keyPair && this.isDefault()) keyPair = this.core.header.keyPair

    if (this.isDefault() && this.core.header.hints.recovering) await this.waitForRecovery()

    await this.mutex.lock()

    try {
      if (maxLength >= 0 && this.length + values.length > maxLength) {
        return { length: this.length, byteLength: this.byteLength }
      }

      const tx = this.createWriteBatch()

      // upsert compat manifest
      if (this.core.verifier === null && keyPair) this.core._setManifest(tx, null, keyPair)

      if (preappend) await preappend(values)

      if (!values.length) {
        await this.flush()
        return { length: this.length, byteLength: this.byteLength }
      }

      const batch = this.createTreeBatch()
      for (const val of values) batch.append(val)

      // only multisig can have prologue so signature is always present
      if (this.prologue && batch.length < this.prologue.length) {
        throw INVALID_OPERATION('Append is not consistent with prologue', this.core.discoveryKey)
      }

      if (signature) {
        batch.signature = signature
        this.core._verifyBatchUpgrade(batch)
      } else if (keyPair) {
        batch.signature = this.core.verifier.sign(batch, keyPair)
      }

      batch.commit(tx)

      const tree = {
        fork: batch.fork,
        length: batch.length,
        rootHash: batch.hash(),
        signature: batch.signature,
        timestamp: Date.now()
      }

      tx.setHead(tree)

      if (this.isDefault()) {
        await storeBitfieldRange(this.storage, tx, batch.ancestors, batch.length, true)
        if (this.length === this.core.header.hints.contiguousLength) {
          tx.setHints({
            contiguousLength: this.length + values.length,
            remoteContiguousLength: this.core.header.hints.remoteContiguousLength
          })
        }

        if (this.core.header.group) {
          this.updateGroupIndex(tx, tree)
        }
      }

      for (let i = 0; i < values.length; i++) {
        tx.putBlock(this.length + i, values[i])
      }

      const bitfield = {
        drop: false,
        start: batch.ancestors,
        length: values.length
      }

      const flushed = await this.flush()

      this.fork = batch.fork
      this.roots = batch.roots
      this.length = batch.length
      this.byteLength = batch.byteLength
      this.signature = batch.signature

      if (postappend) await postappend(values)

      this.onappend(tree, bitfield, flushed)

      if (this.core.hintsChanged && this.isDefault()) await this.core.flushHints()

      return { length: this.length, byteLength: this.byteLength }
    } finally {
      this._unlock()
    }
  }

  onappend(tree, bitfield, flushed) {
    if (!flushed) this._updateBitfield(bitfield)
    else if (this.isDefault()) this.core.onappend(tree, bitfield)

    for (let i = this.sessions.length - 1; i >= 0; i--) {
      this.sessions[i].emit('append')
    }

    this._flushHooks()
  }

  ontruncate(tree, to, from, flushed) {
    const bitfield = { start: to, length: from - to, drop: true }

    this.lastTruncation = { from, to }

    if (!flushed) this._updateBitfield(bitfield)
    else if (this.isDefault()) this.core.ontruncate(tree, bitfield)

    for (const sessionState of this.core.sessionStates) {
      if (
        sessionState.isSnapshot() &&
        sessionState.name === this.name &&
        to < sessionState.snapshotCompatLength
      ) {
        sessionState.snapshotCompatLength = to
      }
    }

    for (let i = this.sessions.length - 1; i >= 0; i--) {
      this.sessions[i].emit('truncate', to, tree.fork)
    }

    this._flushHooks()
  }

  _updateBitfield(bitfield, flushed) {
    if (!bitfield) return

    const p = this._pendingBitfield
    const b = bitfield

    if (b.drop) {
      // truncation must be from end
      if (p && b.start + b.length !== p.start + p.appends) {
        throw INVALID_OPERATION('Atomic truncations must be contiguous', this.core.discoveryKey)
      }

      // actual truncation
      if (p === null || b.start < p.start) {
        this._pendingBitfield = { truncated: true, start: b.start, appends: 0 }
        return
      }

      // just clearing batch data
      p.appends = b.start - p.start

      // we cleared the current batch
      if (p.appends === 0) this._pendingBitfield = null

      return
    }

    if (p === null) {
      this._pendingBitfield = { truncated: false, start: b.start, appends: b.length }
      return
    }

    if (b.start !== p.start + p.appends) {
      throw INVALID_OPERATION('Atomic operations must be contiguous', this.core.discoveryKey)
    }

    p.appends += b.length
  }

  async catchup(length) {
    assert(!this.isDefault(), 'Cannot catchup signed state') // TODO: make this check better

    await this.mutex.lock()

    try {
      const origLength = this.length

      let sharedLength = 0
      for (let i = this.storage.dependencies.length - 1; i >= 0; i--) {
        const dep = this.storage.dependencies[i]
        if (dep.dataPointer === this.core.state.storage.core.dataPointer) {
          sharedLength = dep.length
          break
        }
      }

      const tx = this.createWriteBatch()
      const rx = this.core.state.storage.read()
      const rootPromises = []

      for (const root of flat.fullRoots(length * 2)) {
        rootPromises.push(rx.getTreeNode(root))
      }

      rx.tryFlush()

      const roots = await Promise.all(rootPromises)
      const truncating = sharedLength < origLength

      for (const node of roots) {
        if (node === null) {
          throw INVALID_OPERATION(
            'Invalid catchup length, tree nodes not available',
            this.core.discoveryKey
          )
        }
      }

      const fork = truncating ? this.fork + 1 : this.fork

      // overwrite it atm, TODO: keep what we can connect to the tree
      tx.deleteBlockRange(0, -1)
      tx.deleteTreeNodeRange(0, -1)
      tx.deleteBitfieldPageRange(0, -1)

      const tree = {
        fork,
        length,
        rootHash: crypto.tree(roots),
        signature: null,
        timestamp: Date.now()
      }

      // never default state so do not update group index
      tx.setHead(tree)

      // prop a better way to do this
      const dep = updateDependency(this, sharedLength, true)
      dep.length = length

      tx.setDependency(dep)

      const flushed = await this.flush()

      this.storage.setDependencyHead(dep)

      this.fork = tree.fork
      this.roots = roots
      this.length = tree.length
      this.byteLength = MerkleTree.size(roots)

      if (truncating) this.ontruncate(tree, sharedLength, origLength, flushed)
      if (sharedLength < length) this.onappend(tree, null, flushed)

      if (this.core.hintsChanged && this.isDefault()) await this.core.flushHints()
    } finally {
      this._unlock()
    }
  }

  async _overwrite(source, fork, length, treeLength, signature) {
    const blockPromises = []
    const treePromises = []
    const rootPromises = []

    const rx = source.storage.read()

    for (const root of flat.fullRoots(length * 2)) {
      rootPromises.push(rx.getTreeNode(root))
    }

    for (const index of flat.patch(treeLength * 2, length * 2)) {
      treePromises.push(rx.getTreeNode(index))
    }

    for (let i = treeLength; i < length; i++) {
      treePromises.push(rx.getTreeNode(i * 2))
      treePromises.push(rx.getTreeNode(i * 2 + 1))
      blockPromises.push(rx.getBlock(i))
    }

    rx.tryFlush()

    const [blocks, nodes, roots] = await Promise.all([
      Promise.all(blockPromises),
      Promise.all(treePromises),
      Promise.all(rootPromises)
    ])

    if (this.core.destroyed) throw new Error('Core destroyed')

    if (signature) {
      const batch = this.createTreeBatch()
      batch.roots = roots
      batch.length = length

      if (!this.core.verifier.verify(batch, signature)) {
        throw INVALID_SIGNATURE(
          'Signature is not valid over committed tree',
          this.core.discoveryKey
        )
      }
    }

    const tx = this.createWriteBatch()

    // truncate existing tree
    if (treeLength < this.length) {
      tx.deleteBlockRange(treeLength, this.length)
    }

    for (const root of roots) tx.putTreeNode(root)

    // no nodes will be copied in shallow mode
    for (const node of nodes) {
      if (node !== null) tx.putTreeNode(node)
    }

    for (let i = 0; i < blocks.length; i++) {
      assert(blocks[i] !== null, 'has block')
      tx.putBlock(i + treeLength, blocks[i])
    }

    const totalLength = Math.max(length, this.length)

    if (totalLength > treeLength) {
      const firstPage = getBitfieldPage(treeLength)
      const lastPage = getBitfieldPage(totalLength - 1)

      const srx = this.storage.read()
      const bitfieldPagePromise = srx.getBitfieldPage(firstPage)
      srx.tryFlush()

      const bitfieldPage = await bitfieldPagePromise

      let index = treeLength

      for (let i = firstPage; i <= lastPage; i++) {
        const page = b4a.alloc(Bitfield.BYTES_PER_PAGE)
        tx.putBitfieldPage(i, page)

        // copy existing bits in
        if (i === firstPage && bitfieldPage) page.set(bitfieldPage)

        if (index < length) {
          index = fillBitfieldPage(page, index, length, i, true)
          if (index < length) continue
        }

        if (index < this.length) {
          index = fillBitfieldPage(page, index, this.length, i, false)
        }
      }
    }

    const tree = {
      fork,
      length,
      rootHash: crypto.tree(roots),
      signature,
      timestamp: Date.now()
    }

    if (this.isDefault() && this.core.header.group) {
      this.updateGroupIndex(tx, tree)
    }

    const upgraded = treeLength < this.length || this.length < length || tree.fork !== this.fork

    if (upgraded) tx.setHead(tree)

    const flushed = await this.flush()

    this.fork = tree.fork
    this.roots = roots
    this.length = length
    this.byteLength = MerkleTree.size(roots)
    this.signature = signature

    return { tree, flushed }
  }

  static isParent(state, parent) {
    // atomic batches have parent set
    if (state.parent && state.parent === parent) return true

    return HypercoreStorage.isParentStorage(state.storage, parent.storage)
  }

  async commit(state, { signature, keyPair, length = state.length, treeLength = -1 } = {}) {
    assert(
      this.isDefault() || (this.parent && this.parent.isDefault()),
      'Can only commit into default state'
    )

    assert(SessionState.isParent(state, this), 'Cannot commit across cores')

    if (this.core._repairMode) {
      throw ASSERTION('Cannot commit while repair mode is on')
    }

    if (this.core.header.hints.recovering) await this.waitForRecovery()

    let srcLocked = false
    await this.mutex.lock()

    try {
      await state.mutex.lock()
      srcLocked = true

      if (treeLength === -1) treeLength = state.flushedLength()

      if (!(await this.core._validateCommit(state, treeLength))) return null
      if (this.length > length) return null

      if (this.length < length && !signature) {
        if (!keyPair) keyPair = this.core.header.keyPair
        const batch = state.createTreeBatch()
        if (length !== batch.length) await batch.restore(length)
        signature = this.core.verifier.sign(batch, keyPair)
      }

      const { tree, flushed } = await this._overwrite(
        state,
        this.fork,
        length,
        treeLength,
        signature
      )

      // gc blocks from source
      if (treeLength < length) {
        const tx = state.createWriteBatch()

        tx.deleteBlockRange(treeLength, length)
        const dependency = state.updateDependency(tx, length)

        await state.flush(tx)

        if (dependency) state.storage.setDependencyHead(dependency)
      }

      const bitfield = { start: treeLength, length: length - treeLength, drop: false }
      this.onappend(tree, bitfield, flushed)

      return {
        length: this.length,
        byteLength: this.byteLength
      }
    } finally {
      if (srcLocked) state._unlock()
      this._unlock()
    }
  }

  async _getTreeHeadAt(length) {
    if (length === null) return this.treeInfo()

    const head = getDefaultTree()

    head.length = length

    const roots = await MerkleTree.getRootsFromStorage(this.storage, length)
    const rootHash = crypto.tree(roots)

    head.fork = this.fork
    head.rootHash = rootHash

    if (length === this.length) head.signature = this.signature

    return head
  }

  _moveToCore(core, truncated, appended) {
    const head = this.core.sessionStates.pop()
    if (head !== this) this.core.sessionStates[(head.index = this.index)] = head

    this.core = core
    this.index = this.core.sessionStates.push(this) - 1

    for (let i = this.sessions.length - 1; i >= 0; i--) {
      const s = this.sessions[i]
      const manifest = s.manifest
      s.transferSession(this.core)
      if (!manifest && s.manifest) s.emit('manifest')
      if (truncated) s.emit('truncate', truncated.to, truncated.fork)
      if (appended) s.emit('append')
    }
  }

  async moveTo(core, length) {
    const state = core.state

    await this.mutex.lock()

    try {
      // if (state.storage && (await state.storage.resumeSession(this.name)) !== null) {
      //   throw STORAGE_CONFLICT('Batch has already been created')
      // }

      const treeLength = this.length

      let truncated = null
      let appended = false

      if (!this.isSnapshot()) {
        if (this.lingers === null) this.lingers = []
        this.lingers.push(this.storage)

        const resumed = await state.storage.resumeSession(this.name)

        const truncation = length < this.length ? await truncateAndFlush(this, length) : null
        const treeInfo = truncation
          ? truncation.tree
          : resumed
            ? null
            : await state._getTreeHeadAt(this.length)

        const fork = truncation ? this.fork + 1 : this.fork

        // todo: validate treeInfo

        let storage = null

        if (resumed) {
          storage = resumed
        } else {
          treeInfo.fork = fork
          storage = await state.storage.createSession(this.name, treeInfo)
        }

        const roots = await MerkleTree.getRootsFromStorage(storage, length)

        this.storage = storage
        this.prologue = state.prologue
        this.fork = fork
        this.length = length
        this.byteLength = MerkleTree.size(roots)
        this.roots = roots

        if (truncation) {
          const { dependency } = truncation

          if (dependency) this.storage.setDependencyHead(dependency)
          truncated = { to: treeLength, fork }
        }

        if (this.length > treeLength) {
          appended = true
        }
      }

      for (let i = this.core.sessionStates.length - 1; i >= 0; i--) {
        const state = this.core.sessionStates[i]
        if (state === this) continue
        if (state.name === this.name) state._moveToCore(core.core)
      }

      this._moveToCore(core.core, truncated, appended)
    } finally {
      this._unlock()
    }
  }

  async createSession(name, overwrite, atom) {
    await this.mutex.lock()

    try {
      let storage = null
      let treeInfo = null

      if (!atom && !overwrite && this.storage) {
        storage = await this.storage.resumeSession(name)

        if (storage !== null) treeInfo = (await getCoreHead(storage)) || getDefaultTree()
      }

      const length = treeInfo ? treeInfo.length : this.length

      if (storage === null) {
        treeInfo = await this._getTreeHeadAt(length)

        if (atom) {
          storage = await this.storage.createAtomicSession(atom, treeInfo)
        } else {
          storage = await this.storage.createSession(name, treeInfo)
        }
      }

      if (this.atomized && atom) {
        throw new Error('Session already atomized')
      }

      const head = {
        fork: this.fork,
        roots:
          length === this.length
            ? this.roots.slice()
            : await MerkleTree.getRootsFromStorage(storage, length),
        length,
        prologue: this.prologue,
        signature: length === this.length ? this.signature : null
      }

      const state = new SessionState(
        this.core,
        atom ? this : null,
        storage,
        head,
        atom ? this.name : name
      )

      if (atom) {
        this.atomized = atom
        atom.preflush(this._precommit.bind(this, state))
        atom.onflush(state._commit.bind(state))
      }

      return state
    } finally {
      this._unlock()
    }
  }
}

module.exports = SessionState

function noop() {}

function getBitfieldPage(index) {
  return Math.floor(index / Bitfield.BITS_PER_PAGE)
}

function fillBitfieldPage(page, start, end, pageIndex, value) {
  const offset = pageIndex * Bitfield.BITS_PER_PAGE
  const max = offset + Bitfield.BITS_PER_PAGE

  const index = max < end ? max : end

  const from = start - offset
  const to = index - offset

  quickbit.fill(page, value, from, to)

  return index
}

async function storeBitfieldRange(storage, tx, from, to, value) {
  if (from >= to) return

  const firstPage = getBitfieldPage(from)
  const lastPage = getBitfieldPage(to - 1)

  let index = from

  const rx = storage.read()

  const promises = []
  for (let i = firstPage; i <= lastPage; i++) {
    promises.push(rx.getBitfieldPage(i))
  }

  rx.tryFlush()

  const pages = await Promise.all(promises)
  const cnt = lastPage - firstPage + 1

  for (let i = 0; i < cnt; i++) {
    const pageIndex = i + firstPage
    if (!pages[i]) pages[i] = b4a.alloc(Bitfield.BYTES_PER_PAGE)

    index = fillBitfieldPage(pages[i], index, to, pageIndex, value)
    tx.putBitfieldPage(pageIndex, pages[i])
  }
}

async function truncateAndFlush(s, length) {
  const batch = s.createTreeBatch()
  await MerkleTree.truncate(s, length, batch, s.fork)
  const tx = s.createWriteBatch()

  const info = await s._truncate(tx, batch)
  const flushed = await s.flush()

  return {
    tree: info.tree,
    roots: info.roots,
    dependency: info.dependency,
    flushed
  }
}

function updateDependency(state, length, truncated) {
  const i = state.storage.findDependencyIndex(length, truncated)
  if (i === -1) return null // skip default state and overlays of default

  return {
    dataPointer: state.storage.dependencies[i].dataPointer,
    length
  }
}

function getDefaultTree() {
  return {
    fork: 0,
    length: 0,
    rootHash: null,
    signature: null
  }
}

function getCoreHead(storage) {
  const b = storage.read()
  const p = b.getHead()
  b.tryFlush()
  return p
}

function isRootIndex(index, roots) {
  for (const node of roots) {
    if (node.index === index) return true
  }

  return false
}

function getRecoveryPeers(peers) {
  if (!SessionState.RECOVERY_PEERS) return peers

  const actual = []

  for (const p of peers) {
    for (const r of SessionState.RECOVERY_PEERS) {
      if (b4a.equals(p.remotePublicKey, r)) {
        actual.push(p)
        break
      }
    }
  }

  return actual
}

function validateRecoveryPeers(peers, length) {
  if (peers.length < 1) return false

  for (const p of peers) {
    if (p.remoteLength > length) return false
    if (p.remoteLength === 0 && !p.remoteSynced) return false
  }

  return true
}
const { Writable, Readable } = require('streamx')

class ReadStream extends Readable {
  constructor(core, opts = {}) {
    super()

    this.core = core
    this.start = opts.start || 0
    this.end = typeof opts.end === 'number' ? opts.end : -1
    this.snapshot = !opts.live && opts.snapshot !== false
    this.live = this.end === -1 ? !!opts.live : false
    this.wait = typeof opts.wait === 'boolean' ? opts.wait : this.core.wait
    this.timeout = opts.timeout || core.timeout
  }

  _open(cb) {
    this._openP().then(cb, cb)
  }

  _read(cb) {
    this._readP().then(cb, cb)
  }

  async _openP() {
    if (this.end === -1) await this.core.update()
    else await this.core.ready()
    if (this.snapshot && this.end === -1) this.end = this.core.length
  }

  async _readP() {
    const end = this.live ? -1 : this.end === -1 ? this.core.length : this.end
    if (end >= 0 && this.start >= end) {
      this.push(null)
      return
    }

    this.push(await this.core.get(this.start++, { wait: this.wait, timeout: this.timeout }))
  }
}

exports.ReadStream = ReadStream

class WriteStream extends Writable {
  constructor(core) {
    super()
    this.core = core
  }

  _writev(batch, cb) {
    this._writevP(batch).then(cb, cb)
  }

  async _writevP(batch) {
    await this.core.append(batch)
  }
}

exports.WriteStream = WriteStream

class ByteStream extends Readable {
  constructor(core, opts = {}) {
    super()

    this._core = core
    this._index = 0
    this._range = null

    this._byteOffset = opts.byteOffset || 0
    this._byteLength = typeof opts.byteLength === 'number' ? opts.byteLength : -1
    this._prefetch = typeof opts.prefetch === 'number' ? opts.prefetch : 32

    this._applyOffset = this._byteOffset > 0
  }

  _open(cb) {
    this._openp().then(cb, cb)
  }

  _read(cb) {
    this._readp().then(cb, cb)
  }

  async _openp() {
    if (this._byteLength === -1) {
      await this._core.update()
      this._byteLength = Math.max(this._core.byteLength - this._byteOffset, 0)
    }
  }

  async _readp() {
    let data = null

    if (this._byteLength === 0) {
      this.push(null)
      return
    }

    let relativeOffset = 0

    if (this._applyOffset) {
      this._applyOffset = false

      const [block, byteOffset] = await this._core.seek(this._byteOffset)

      this._index = block
      relativeOffset = byteOffset
    }

    this._predownload(this._index + 1)
    data = await this._core.get(this._index++, { valueEncoding: 'binary' })

    if (relativeOffset > 0) data = data.subarray(relativeOffset)

    if (data.byteLength > this._byteLength) data = data.subarray(0, this._byteLength)
    this._byteLength -= data.byteLength

    this.push(data)
    if (this._byteLength === 0) this.push(null)
  }

  _predownload(index) {
    if (this._range) this._range.destroy()
    this._range = this._core.download({ start: index, end: index + this._prefetch, linear: true })
  }

  _destroy(cb) {
    if (this._range) this._range.destroy()
    cb(null)
  }
}

exports.ByteStream = ByteStream
const crypto = require('hypercore-crypto')
const b4a = require('b4a')
const c = require('compact-encoding')
const flat = require('flat-tree')
const { BAD_ARGUMENT } = require('hypercore-errors')
const unslab = require('unslab')

const m = require('./messages')
const multisig = require('./multisig')
const caps = require('./caps')

class Signer {
  constructor(
    manifestHash,
    version,
    index,
    { signature = 'ed25519', publicKey, namespace = caps.DEFAULT_NAMESPACE } = {}
  ) {
    if (!publicKey) throw BAD_ARGUMENT('public key is required for a signer')
    if (signature !== 'ed25519') throw BAD_ARGUMENT('Only Ed25519 signatures are supported')

    this.manifestHash = manifestHash
    this.version = version
    this.signer = index
    this.signature = signature
    this.publicKey = publicKey
    this.namespace = namespace
  }

  _ctx() {
    return this.version === 0 ? this.namespace : this.manifestHash
  }

  verify(batch, signature) {
    return crypto.verify(batch.signable(this._ctx()), signature, this.publicKey)
  }

  sign(batch, keyPair) {
    return crypto.sign(batch.signable(this._ctx()), keyPair.secretKey)
  }
}

class CompatSigner extends Signer {
  constructor(index, signer, legacy) {
    super(null, 0, index, signer)
    this.legacy = legacy
  }

  verify(batch, signature) {
    return crypto.verify(batch.signableCompat(this.legacy), signature, this.publicKey)
  }

  sign(batch, keyPair) {
    return crypto.sign(batch.signableCompat(this.legacy), keyPair.secretKey)
  }
}

module.exports = class Verifier {
  constructor(
    manifestHash,
    manifest,
    { compat = isCompat(manifestHash, manifest), legacy = false } = {}
  ) {
    const self = this

    this.manifestHash = manifestHash
    this.compat = compat || manifest === null
    this.version = this.compat ? 0 : typeof manifest.version === 'number' ? manifest.version : 1
    this.hash = manifest.hash || 'blake2b'
    this.allowPatch = !this.compat && !!manifest.allowPatch
    this.quorum = this.compat ? 1 : defaultQuorum(manifest)

    this.signers = manifest.signers ? manifest.signers.map(createSigner) : []
    this.prologue = this.compat ? null : manifest.prologue || null

    function createSigner(signer, index) {
      return self.compat
        ? new CompatSigner(index, signer, legacy)
        : new Signer(manifestHash, self.version, index, signer)
    }
  }

  _verifyCompat(batch, signature) {
    if (!signature) return false

    if (this.compat || (!this.allowPatch && this.signers.length === 1)) {
      return !!signature && this.signers[0].verify(batch, signature)
    }

    return this._verifyMulti(batch, signature)
  }

  _inflate(signature) {
    if (this.version >= 1) return multisig.inflate(signature)
    const { proofs, patch } = multisig.inflatev0(signature)

    return {
      proofs: proofs.map(proofToVersion1),
      patch
    }
  }

  _verifyMulti(batch, signature) {
    if (!signature || this.quorum === 0) return false

    const { proofs, patch } = this._inflate(signature)
    if (proofs.length < this.quorum) return false

    const tried = new Uint8Array(this.signers.length)
    const nodes = this.allowPatch && patch.length ? toMap(patch) : null

    for (let i = 0; i < this.quorum; i++) {
      const inp = proofs[i]

      let tree = batch

      if (inp.patch && this.allowPatch) {
        tree = batch.clone()

        const upgrade = generateUpgrade(nodes, batch.length, inp.patch)
        const proof = {
          fork: tree.fork,
          block: null,
          hash: null,
          seek: null,
          upgrade,
          manifest: null
        }

        try {
          if (!tree.verifyUpgrade(proof)) return false
        } catch {
          return false
        }
      }

      if (inp.signer >= this.signers.length || tried[inp.signer]) return false
      tried[inp.signer] = 1

      const s = this.signers[inp.signer]
      if (!s.verify(tree, inp.signature)) return false
    }

    return true
  }

  verify(batch, signature) {
    if (this.version === 0) {
      return this._verifyCompat(batch, signature)
    }

    if (this.prologue !== null && batch.length <= this.prologue.length) {
      return batch.length === this.prologue.length && b4a.equals(batch.hash(), this.prologue.hash)
    }

    return this._verifyMulti(batch, signature)
  }

  // TODO: better api for this that is more ... multisig-ey
  sign(batch, keyPair) {
    if (!keyPair || !keyPair.secretKey) throw BAD_ARGUMENT('No key pair was passed')

    for (const s of this.signers) {
      if (b4a.equals(s.publicKey, keyPair.publicKey)) {
        const signature = s.sign(batch, keyPair)
        if (this.signers.length !== 1 || this.version === 0) return signature
        return this.assemble([{ signer: 0, signature, patch: 0, nodes: null }])
      }
    }

    throw BAD_ARGUMENT('Public key is not a declared signer')
  }

  assemble(inputs) {
    return this.version === 0 ? multisig.assemblev0(inputs) : multisig.assemble(inputs)
  }

  static manifestHash(manifest) {
    return manifestHash(manifest)
  }

  static encodeManifest(manifest) {
    return c.encode(m.manifest, manifest)
  }

  static decodeManifest(manifest) {
    return c.decode(m.manifest, manifest)
  }

  static defaultSignerManifest(publicKey) {
    return {
      version: 1,
      hash: 'blake2b',
      allowPatch: false,
      quorum: 1,
      signers: [
        {
          signature: 'ed25519',
          namespace: caps.DEFAULT_NAMESPACE,
          publicKey
        }
      ],
      prologue: null,
      linked: null,
      userData: null
    }
  }

  static fromManifest(manifest, opts) {
    const m = this.createManifest(manifest)
    return new this(manifestHash(m), m, opts)
  }

  static createManifest(inp) {
    if (!inp) return null

    if (inp.quorum && inp.quorum < 0) throw BAD_ARGUMENT('Quorum cannot be negative')
    if (inp.quorum && inp.signers && inp.quorum > inp.signers.length) {
      throw BAD_ARGUMENT('Quorum should not be higher than the number of signers')
    }

    const manifest = {
      version: getManifestVersion(inp), // defaults to v1
      hash: 'blake2b',
      allowPatch: !!inp.allowPatch,
      quorum: defaultQuorum(inp),
      signers: inp.signers ? inp.signers.map(parseSigner) : [],
      prologue: null,
      linked: null,
      userData: inp.userData || null
    }

    if (inp.hash && inp.hash !== 'blake2b') throw BAD_ARGUMENT('Only Blake2b hashes are supported')

    if (inp.prologue) {
      if (
        !(b4a.isBuffer(inp.prologue.hash) && inp.prologue.hash.byteLength === 32) ||
        !(inp.prologue.length >= 0)
      ) {
        throw BAD_ARGUMENT('Invalid prologue')
      }

      manifest.prologue = inp.prologue
      manifest.prologue.hash = unslab(manifest.prologue.hash)
    }

    if (manifest.userData !== null && manifest.version < 2) {
      throw BAD_ARGUMENT('Invalid field: userData')
    }

    if (inp.linked && inp.linked.length) {
      if (manifest.version < 2) throw BAD_ARGUMENT('Invalid field: linked')

      for (const key of inp.linked) {
        if (!(b4a.isBuffer(key) && key.byteLength === 32)) {
          throw BAD_ARGUMENT('Invalid key')
        }
      }

      manifest.linked = inp.linked
    }

    return manifest
  }

  static isValidManifest(key, manifest) {
    return b4a.equals(key, manifestHash(manifest))
  }

  static isCompat(key, manifest) {
    return isCompat(key, manifest)
  }

  static sign(manifest, batch, keyPair, opts) {
    return Verifier.fromManifest(manifest, opts).sign(batch, keyPair)
  }
}

function toMap(nodes) {
  const m = new Map()
  for (const node of nodes) m.set(node.index, node)
  return m
}

function isCompat(key, manifest) {
  return !!(
    manifest &&
    manifest.signers.length === 1 &&
    b4a.equals(key, manifest.signers[0].publicKey)
  )
}

function defaultQuorum(man) {
  if (typeof man.quorum === 'number') return man.quorum
  if (!man.signers || !man.signers.length) return 0
  return (man.signers.length >> 1) + 1
}

function generateUpgrade(patch, start, length) {
  const upgrade = { start, length, nodes: null, additionalNodes: [], signature: null }

  const from = start * 2
  const to = from + length * 2

  for (const ite = flat.iterator(0); ite.fullRoot(to); ite.nextTree()) {
    if (ite.index + ite.factor / 2 < from) continue

    if (upgrade.nodes === null && ite.contains(from - 2)) {
      upgrade.nodes = []

      const root = ite.index
      const target = from - 2

      ite.seek(target)

      while (ite.index !== root) {
        ite.sibling()
        if (ite.index > target) upgrade.nodes.push(patch.get(ite.index))
        ite.parent()
      }

      continue
    }

    if (upgrade.nodes === null) upgrade.nodes = []
    upgrade.nodes.push(patch.get(ite.index))
  }

  if (upgrade.nodes === null) upgrade.nodes = []
  return upgrade
}

function parseSigner(signer) {
  validateSigner(signer)
  return {
    signature: 'ed25519',
    namespace: unslab(signer.namespace || caps.DEFAULT_NAMESPACE),
    publicKey: unslab(signer.publicKey)
  }
}

function validateSigner(signer) {
  if (!signer || !signer.publicKey) throw BAD_ARGUMENT('Signer missing public key')
  if (signer.signature && signer.signature !== 'ed25519') {
    throw BAD_ARGUMENT('Only Ed25519 signatures are supported')
  }
}

function manifestHash(manifest) {
  const state = { start: 0, end: 32, buffer: null }
  m.manifest.preencode(state, manifest)
  state.buffer = b4a.allocUnsafe(state.end)
  c.raw.encode(state, caps.MANIFEST)
  m.manifest.encode(state, manifest)
  return crypto.hash(state.buffer)
}

function proofToVersion1(proof) {
  return {
    signer: proof.signer,
    signature: proof.signature,
    patch: proof.patch ? proof.patch.length : 0
  }
}

function getManifestVersion(inp) {
  if (typeof inp.version === 'number') return inp.version
  if (inp.linked && inp.linked.length) return 2
  if (inp.userData) return 2
  return 1
}
let COMPAT = true
let BATCH_UINTS = COMPAT ? 65536 : 128
let BATCH_BYTES = BATCH_UINTS * 4
let BATCH = BATCH_BYTES * 8 // in bits
const MAX_REMOTE_BATCHES = 4
const MAX_RANGE = 8 * 256 * 1024
const MIN_RANGE = 32 // 4bit ints
const MAX = 512
const MAX_ANY = 16

class LocalWants {
  constructor(peer) {
    this.destroyed = false
    this.peer = peer
    this.wants = new Map()
    this.free = new Set()
    this.any = null
  }

  add(index, handle) {
    const b = (index - (index & (BATCH - 1))) / BATCH
    return this.addBatch(b, handle)
  }

  addAnyRange(start, length, handle) {
    if (this.destroyed) return null
    if (this.any === null) this.any = []

    if (COMPAT) {
      let r = start & (BATCH - 1)
      start -= r
      length += r
      r = length & (BATCH - 1)
      if (r) length = length - r + BATCH
    }

    for (let i = 0; i < this.any.length; i++) {
      const w = this.any[i]
      if (w.start === start && w.length === length) {
        w.handles.add(handle)
        handle.addWant(w)
        return null
      }
    }

    const w = { wants: this, start, length, any: true, handles: new Set([handle]) }
    this.any.push(w)
    handle.addWant(w)

    return { start, length, any: !COMPAT }
  }

  removeAnyRange(start, length, handle) {
    if (this.any === null) return null

    for (let i = 0; i < this.any.length; i++) {
      const w = this.any[i]
      if (w.start !== start || w.length !== length) continue

      w.handles.delete(handle)
      handle.removeWant(w)
      if (w.handles.size > 0) return null

      const head = this.any.pop()
      if (head !== w) this.any[i] = head
      return { start, length, any: !COMPAT }
    }

    return null
  }

  addBatch(index, handle) {
    if (this.destroyed) return null
    let w = this.wants.get(index)

    if (w) {
      const size = w.handles.size
      w.handles.add(handle)
      if (w.handles.size !== size) {
        handle.addWant(w)
      }
      return null
    }

    // start here is the batch number for simplicity....
    w = { wants: this, start: index, length: 0, any: false, handles: new Set([handle]) }

    if (this.free.has(index)) {
      this.free.delete(index)
      this.wants.set(index, w)
      handle.addWant(w)
      return null
    }

    let unwant = null
    if (this.wants.size + this.free.size === MAX) {
      if (this.free.size === 0) {
        return null
      }
      unwant = this._unwant()
    }

    this.wants.set(index, w)
    handle.addWant(w)

    return {
      want: { start: index * BATCH, length: BATCH, any: false },
      unwant
    }
  }

  remove(index, handle) {
    const b = (index - (index & (BATCH - 1))) / BATCH
    return this.removeBatch(b, handle)
  }

  removeBatch(index, handle) {
    if (this.destroyed) return false

    const w = this.wants.get(index)
    if (!w) {
      return false
    }

    w.handles.delete(handle)
    handle.removeWant(w)

    if (w.handles.size === 0) {
      this.free.add(index)
      this.wants.delete(index)
      return this.free.size === 1 && this.wants.size === MAX - 1
    }

    return false
  }

  destroy() {
    if (this.destroyed) return
    this.destroyed = true

    for (const w of this.wants.values()) {
      for (const handle of w.handles) {
        handle.removeWant(w)
      }
    }

    this.wants.clear()
  }

  _unwant() {
    for (const index of this.free) {
      this.free.delete(index)
      return { start: index * BATCH, length: BATCH, any: false }
    }
    return null
  }
}

class RemoteWants {
  constructor() {
    this.any = null
    this.all = false
    this.size = 0
    this.batches = []
  }

  hasAny(start, length) {
    for (let i = 0; i < this.any.length; i++) {
      const a = this.any[i]
      const e = start + length
      const end = a.start + a.length

      if (a.start <= start && start < end) return true
      if (a.start < e && e <= end) return true
    }

    return this.all
  }

  hasRange(start, length) {
    if (this.any !== null && this.hasAny(start, length)) return true
    if (length === 1) return this.has(start)

    let smallest = -1

    for (let i = 0; i < this.batches.length; i++) {
      const b = this.batches[i]
      if (b.length < smallest || smallest === -1) smallest = b.length
    }

    if (smallest === -1) return this.all

    const r = start & (smallest - 1)
    const end = start + length

    let max = 3

    for (let i = start - r; i < end; i += smallest) {
      if (max-- === 0) return true // just to save work
      if (this.has(i)) return true
    }

    return this.all
  }

  has(index) {
    for (let i = 0; i < this.batches.length; i++) {
      const b = this.batches[i]
      const block = (index - (index & (b.length - 1))) / b.length
      if (b.ranges.has(block)) return true
    }

    return this.all
  }

  add(range) {
    if (range.any) {
      if (this.any === null) this.any = []
      if (this.any.length < MAX_ANY) this.any.push(range)
      else this.all = true
      return true
    }

    if (range.length > MAX_RANGE) return false

    if (!validateBatchRange(range)) {
      this.all = true
      return true
    }

    if (this.size >= MAX) {
      this.all = true
      return true
    }

    for (let i = 0; i < this.batches.length; i++) {
      const b = this.batches[i]
      if (b.length === range.length) {
        b.ranges.add(range.start / range.length)
        this.size++
        return true
      }
    }

    if (this.batches.length >= MAX_REMOTE_BATCHES) {
      this.all = true
      return true
    }

    this.batches.push({
      length: range.length,
      ranges: new Set([range.start / range.length])
    })
    this.size++

    return true
  }

  remove(range) {
    if (range.any) {
      if (this.any === null) return false

      for (let i = 0; i < this.any.length; i++) {
        const a = this.any[i]

        if (a.start === range.start && a.length === range.length) {
          const head = this.any.pop()
          if (head !== a) this.any[i] = head
          return true
        }
      }

      return false
    }

    if (!validateBatchRange(range)) return false

    for (let i = 0; i < this.batches.length; i++) {
      const b = this.batches[i]
      if (b.length !== range.length) continue

      const size = b.ranges.size
      b.ranges.delete(range.start / range.length)
      if (b.ranges.size !== size) this.size--

      if (b.ranges.size === 0) {
        const head = this.batches.pop()
        if (head !== b) this.batches[i] = head
      }

      return true
    }

    return false
  }
}

function UPDATE_COMPAT(isCompat) {
  COMPAT = isCompat
  BATCH_UINTS = COMPAT ? 65536 : 128
  BATCH_BYTES = BATCH_UINTS * 4
  BATCH = BATCH_BYTES * 8 // in bits
  exports.WANT_BATCH = BATCH
}

exports.LocalWants = LocalWants
exports.RemoteWants = RemoteWants
exports.WANT_BATCH = BATCH
exports.UPDATE_COMPAT = UPDATE_COMPAT

function validateBatchRange(range) {
  if (range.length > MAX_RANGE || range.length < MIN_RANGE) {
    return false
  }
  // check if power of two
  if ((range.length & (range.length - 1)) !== 0) {
    return false
  }
  // start must be a multiple of the length
  if (range.start & (range.length - 1)) {
    return false
  }

  return true
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "hypercore",
  "version": "11.34.0",
  "description": "Hypercore is a secure, distributed append-only log",
  "main": "index.js",
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "brittle test/all.js",
    "test:bare": "bare test/all.js",
    "test:generate": "brittle -r test/all.js test/*.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/hypercore.git"
  },
  "contributors": [
    {
      "name": "Mathias Buus",
      "email": "mathiasbuus@gmail.com",
      "url": "https://mafinto.sh"
    },
    {
      "name": "Andrew Osheroff",
      "email": "andrewosh@gmail.com",
      "url": "https://andrewosh.com"
    }
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/hypercore/issues"
  },
  "homepage": "https://github.com/holepunchto/hypercore#readme",
  "files": [
    "index.js",
    "errors.js",
    "messages.js",
    "lib/**.js"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "dependencies": {
    "@hyperswarm/secret-stream": "^6.0.0",
    "b4a": "^1.1.0",
    "bare-events": "^2.2.0",
    "big-sparse-array": "^1.0.3",
    "compact-encoding": "^3.0.0",
    "fast-fifo": "^1.3.0",
    "flat-tree": "^1.9.0",
    "hypercore-crypto": "^3.2.1",
    "hypercore-errors": "^1.5.0",
    "hypercore-id-encoding": "^1.2.0",
    "hypercore-storage": "^3.2.0",
    "is-options": "^1.0.1",
    "nanoassert": "^2.0.0",
    "protomux": "^3.5.0",
    "quickbit-universal": "^2.2.0",
    "random-array-iterator": "^1.0.0",
    "safety-catch": "^1.0.1",
    "sodium-universal": "^5.0.1",
    "streamx": "^2.12.4",
    "unslab": "^1.3.0",
    "z32": "^1.0.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "debugging-stream": "^3.1.0",
    "hyperswarm": "^4.3.6",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "rache": "^1.0.0",
    "range-parser": "^1.2.1",
    "resolve-reject-promise": "^1.1.0",
    "speedometer": "^1.1.0",
    "test-tmp": "^1.0.2",
    "tiny-byte-size": "^1.1.0",
    "udx-native": "^1.6.1",
    "uncaughts": "^1.1.0"
  }
}
const IndexStream = require('./lib/stream.js')
const def = require('./lib/definition.js')
const b4a = require('b4a')

// engines
const RocksEngine = require('./lib/engine/rocks.js')
const BeeEngine = require('./lib/engine/bee.js')
const Bee2Engine = require('./lib/engine/bee2.js')

let compareHasDups = false

class Updates {
  constructor(tick, entries) {
    this.refs = 1
    this.mutating = 0
    this.tick = tick // internal tie breaker clock for same key updates
    this.map = new Map(entries)
    this.locks = new Map()
  }

  get size() {
    return this.map.size
  }

  nextTick() {
    const tick = this.tick
    this.tick += 256 // 256 is how many trigger inserts can fire, deprecated anyway
    return tick
  }

  enter(collection) {
    if (collection.trigger !== null) {
      if (this.locks.has(collection.id)) return false
      this.locks.set(collection.id, { resolve: null, promise: null })
    }

    this.mutating++
    return true
  }

  exit(collection) {
    this.mutating--
    if (collection.trigger === null) return
    const { resolve } = this.locks.get(collection.id)
    this.locks.delete(collection.id)
    if (resolve) resolve()
  }

  wait(collection) {
    const state = this.locks.get(collection.id)
    if (state.promise) return state.promise
    state.promise = new Promise((resolve) => {
      state.resolve = resolve
    })
    return state.promise
  }

  ref() {
    this.refs++
    return this
  }

  unref() {
    this.refs--
  }

  detach() {
    const entries = new Array(this.map.size)

    if (entries.length > 0) {
      let i = 0
      for (const [key, u] of this.map) {
        const clone = {
          created: u.created,
          tick: u.tick,
          collection: u.collection,
          key: u.key,
          value: u.value,
          indexes: u.indexes.slice(0)
        }
        entries[i++] = [key, clone]
      }
    }

    this.refs--
    return new Updates(this.tick, entries)
  }

  get(key) {
    const u = this.map.get(b4a.toString(key, 'hex'))
    return u === undefined ? null : u
  }

  getIndex(index, key) {
    // 99% of all reads
    if (this.map.size === 0 || index.offset === -1) return null

    const matches = []

    for (const u of this.map.values()) {
      if (u.collection.id !== index.collection.id) continue

      const ups = u.indexes[index.offset]

      for (let i = 0; i < ups.length; i++) {
        if (b4a.equals(key, ups[i].key)) matches.push(u)
      }
    }

    if (!matches.length) return null

    let latest = matches[0]

    for (let i = 1; i < matches.length; i++) {
      const m = matches[i]
      if (m.tick > latest.tick) latest = m
    }

    return latest
  }

  flush() {
    this.map.clear()
  }

  update(collection, tick, key, value) {
    const u = {
      created: false,
      tick,
      collection,
      key,
      value,
      indexes: []
    }
    this.map.set(b4a.toString(key, 'hex'), u)
    return u
  }

  delete(key) {
    this.map.delete(b4a.toString(key, 'hex'))
  }

  batch() {
    const ordered = new Array(this.map.size)

    let sort = false
    let i = 0

    for (const u of this.map.values()) {
      if (i > 0 && u.tick < ordered[i - 1].tick) sort = true
      ordered[i++] = u
    }

    if (sort) ordered.sort(sortUpdates)

    const dedup = ordered.length > 1 ? new Set() : null
    const batch = []

    for (let i = ordered.length - 1; i >= 0; i--) {
      const u = ordered[i]

      for (let j = 0; j < u.indexes.length; j++) {
        const idx = u.indexes[j]

        // TODO: we can be more fancy here with only deduping non-unique indexes
        for (let k = 0; k < idx.length; k++) {
          const { key, value } = idx[k]
          if (dedup !== null) {
            const id = b4a.toString(key, 'hex')
            if (dedup.has(id)) continue
            dedup.add(id)
          }

          batch.push([key, value])
        }
      }

      // these keys are guaranteed unique so no dedup is needed
      batch.push([u.key, u.value])
    }

    return batch
  }

  collectionOverlay(collection, range, reverse) {
    const overlay = []

    // 99% of all reads
    if (this.map.size === 0) return overlay

    for (const u of this.map.values()) {
      if (u.collection.id !== collection.id) continue
      if (withinRange(range, u.key)) {
        overlay.push({
          tick: u.tick,
          key: u.key,
          value: u.value === null ? null : [u.key, u.value]
        })
      }
    }

    return sortOverlay(overlay, reverse)
  }

  indexOverlay(index, range, reverse) {
    const overlay = []

    // 99% of all reads
    if (this.map.size === 0 || index.offset === -1) return overlay

    const collection = index.collection

    for (const u of this.map.values()) {
      if (u.collection.id !== collection.id) continue
      for (const { key, value } of u.indexes[index.offset]) {
        if (withinRange(range, key)) {
          overlay.push({
            tick: u.tick,
            key,
            value: value === null ? null : [u.key, u.value]
          })
        }
      }
    }

    return sortOverlay(overlay, reverse)
  }
}

class TriggeredHyperDB {
  constructor(db, tick) {
    this.db = db

    this.tick = tick
    this.maxTick = tick + 256
  }

  _nextTick() {
    const tick = ++this.tick
    if (tick >= this.maxTick) throw new Error('Too many inserts in the trigger')
    return tick
  }

  getAll(...args) {
    return this.db.getAll(...args)
  }

  get(...args) {
    return this.db.get(...args)
  }

  find(...args) {
    return this.db.find(...args)
  }

  findOne(...args) {
    return this.db.findOne(...args)
  }

  async insert(collection, record) {
    const tick = this._nextTick()
    return this.db.insert(collection, record, { tick })
  }

  async delete(collection, record) {
    const tick = this._nextTick()
    return this.db.delete(collection, record, { tick })
  }
}

class HyperDB {
  constructor(
    engine,
    definition,
    {
      versions = definition.versions,
      snapshot = engine.snapshot(),
      updates = new Updates(1, []),
      rootInstance = null,
      writable = true,
      context = null
    } = {}
  ) {
    this.versions = versions
    this.context = context
    this.index = 0 // for the session
    this.engine = engine
    this.engineSnapshot = snapshot
    this.definition = definition
    this.updates = updates
    this.rootInstance = writable === true ? rootInstance || this : null
    this.watchers = null
    this.closing = null
    this.activeRequests = []

    this.engine.sessions.add(this)
  }

  static isDefinition(definition) {
    return def.isDefinition(definition)
  }

  static rocks(storage, definition, options = {}) {
    const readOnly = options.readOnly === true || options.readonly === true
    const trace = options.trace || null
    const engine = new RocksEngine(storage, { readOnly, trace })

    return new HyperDB(engine, def.compat(definition), options)
  }

  static bee(core, definition, options = {}) {
    const extension = options.extension
    const autoUpdate = !!options.autoUpdate
    const trace = options.trace || null
    const engine = new BeeEngine(core, { extension, trace })

    const db = new HyperDB(engine, def.compat(definition), options)

    if (autoUpdate) {
      const update = db.update.bind(db)
      core.on('append', update)
      core.on('truncate', update)
    }

    return db
  }

  static bee2(bee, definition, options = {}) {
    const { autoUpdate = false, trace = null, key = null, length = -1 } = options

    const engine = new Bee2Engine(bee, { trace, key, length })
    const db = new HyperDB(engine, def.compat(definition), options)

    if (autoUpdate) {
      bee.on('update', db.update.bind(db))
    }

    return db
  }

  get core() {
    return this.engine.core
  }

  get db() {
    return this.engine.db
  }

  get closed() {
    return this.engine === null
  }

  get writable() {
    return this.rootInstance !== null
  }

  get traceable() {
    // basically, are we not a write tx
    return this.rootInstance === this || this.rootInstance === null
  }

  get readable() {
    return this.closing !== null
  }

  get autoClose() {
    return this.rootInstance !== null && this.rootInstance !== this
  }

  setVersions(versions) {
    this.versions = versions
  }

  setDefinition(definition) {
    definition = def.compat(definition)

    this.versions = definition.versions
    this.definition = definition
  }

  cork() {
    if (this.engineSnapshot !== null) this.engineSnapshot.cork()
  }

  uncork() {
    if (this.engineSnapshot !== null) this.engineSnapshot.uncork()
  }

  ready() {
    return this.engineSnapshot === null ? Promise.resolve() : this.engineSnapshot.ready()
  }

  close() {
    if (this.closing === null) this.closing = this._close()
    return this.closing
  }

  changes(range = {}) {
    maybeClosed(this)
    const snap = range.live ? null : this.engineSnapshot
    return this.engine.changes(snap, this.versions, this.definition, range)
  }

  watch(fn) {
    if (this.watchers === null) this.watchers = new Set()
    this.watchers.add(fn)
  }

  unwatch(fn) {
    if (this.watchers === null) return
    this.watchers.delete(fn)
  }

  async _close() {
    this.engine.clearRequests(this.activeRequests)

    this.updates.unref()
    this.updates = null

    this.engineSnapshot.unref()
    this.engineSnapshot = null

    // if root, close all
    if (this.rootInstance === this) {
      await this.engine.sessions.close(this)
    }

    this.engine.sessions.remove(this)

    if (this.engine.tx === this) this.engine.exit()
    if (this.engine.sessions.size === 0) await this.engine.close()

    this.engine = null
  }

  _createSnapshot(rootInstance, writable, context) {
    const snapshot = this.engineSnapshot.ref()

    return new HyperDB(this.engine, this.definition, {
      versions: this.versions,
      snapshot,
      updates: this.updates.ref(),
      rootInstance,
      writable,
      context
    })
  }

  snapshot(options) {
    maybeClosed(this)

    const context = (options && options.context) || this.context
    return this._createSnapshot(this, false, context)
  }

  // in future major, lets move transaction to be exclusive (aka sync) always
  async exclusiveTransaction(options) {
    await this.engine.enter()

    if (this.closing) {
      this.engine.exit()
      maybeClosed(this)
    }

    this.engine.tx = this.transaction(options)
    return this.engine.tx
  }

  transaction(options) {
    maybeClosed(this)

    if (this.rootInstance !== this) {
      throw new Error('Can only make transactions on main instance')
    }

    const context = (options && options.context) || this.context
    const tx = this._createSnapshot(this, true, context)

    tx.update()

    return tx
  }

  find(indexName, query = {}, options) {
    if (options) query = { ...query, ...options }

    maybeClosed(this)

    const index = this.definition.resolveIndex(indexName)
    const collection =
      index === null ? this.definition.resolveCollection(indexName) : index.collection

    if (collection === null) throw new Error('Unknown index: ' + indexName)

    const { checkout = -1, limit, reverse = false } = query

    const range = index === null ? collection.encodeKeyRange(query) : index.encodeKeyRange(query)

    const overlay =
      checkout !== -1
        ? []
        : index === null
          ? this.updates.collectionOverlay(collection, range, reverse)
          : this.updates.indexOverlay(index, range, reverse)

    return new IndexStream(this, range, {
      index,
      collection,
      reverse,
      limit,
      overlay,
      checkout
    })
  }

  async findOne(indexName, query, options) {
    return this.find(indexName, query, { ...options, limit: 1 }).one()
  }

  updated(collectionName, record) {
    if (this.updates === null) return false
    if (!collectionName) return this.updates.size > 0

    const collection = this.definition.resolveCollection(collectionName)
    if (collection === null) return false

    const key = b4a.isBuffer(record) ? record : collection.encodeKey(record)
    const u = this.updates.get(key)
    return u !== null
  }

  getAll(batch) {
    const promises = []
    for (const b of batch) {
      if (Array.isArray(b)) promises.push(this.get(...b))
      else promises.push(b)
    }
    return Promise.all(promises)
  }

  async get(collectionName, record, { checkout = -1 } = {}) {
    maybeClosed(this)

    const snap = this.engineSnapshot.ref()

    try {
      const collection = this.definition.resolveCollection(collectionName)
      if (collection !== null) return await this._getCollection(collection, snap, record, checkout)

      const index = this.definition.resolveIndex(collectionName)
      if (index === null) throw new Error('Unknown index or collection: ' + collectionName)

      const key = index.encodeKey(record, this.context)
      if (key === null) return null

      const u = this.updates.getIndex(index, key)
      if (u !== null && checkout === -1) {
        return u.value === null
          ? null
          : index.collection.reconstruct(this.versions.schema, u.key, u.value)
      }

      const value = await snap.get(key, checkout, this.activeRequests)
      if (value === null) return null

      return this._getCollection(index.collection, snap, index.reconstruct(key, value), checkout)
    } finally {
      if (snap !== null) snap.unref()
    }
  }

  async _getCollection(collection, snap, record, checkout) {
    maybeClosed(this)

    // we allow passing the raw primary key here cause thats what the trigger passes for simplicity
    // you shouldnt rely on that.
    const key = b4a.isBuffer(record) ? record : collection.encodeKey(record)

    const u = this.updates.get(key)
    const value =
      u !== null && checkout === -1 ? u.value : await snap.get(key, checkout, this.activeRequests)

    // check again now cause we did async work above to engine might be nulled out
    maybeClosed(this)

    return this.engine.finalize(collection, this.versions, checkout, this.traceable, key, value)
  }

  async _runTrigger(tick, collection, key, record) {
    const db = new TriggeredHyperDB(this, tick)
    await collection.trigger(db, key, record, this.context)
    return db.tick
  }

  async delete(collectionName, record, { tick = 0 } = {}) {
    maybeClosed(this)

    if (this.updates.refs > 1) this.updates = this.updates.detach()

    const collection = this.definition.resolveCollection(collectionName)
    if (collection === null) return

    if (tick === 0) tick = this.updates.nextTick()

    while (this.updates.enter(collection) === false) await this.updates.wait(collection)

    const snap = this.engineSnapshot.ref()
    const key = collection.encodeKey(record)

    let prevValue = null

    try {
      prevValue = await this.engineSnapshot.get(key, -1, this.activeRequests)
      if (collection.trigger !== null) {
        tick = await this._runTrigger(tick, collection, record, null)
      }

      if (prevValue === null) {
        this.updates.delete(key)
        return
      }

      const prevDoc = collection.reconstruct(this.versions.schema, key, prevValue)
      const prevVersion = collection.decodedVersion

      const u = this.updates.update(collection, tick, key, null)

      for (let i = 0; i < collection.indexes.length; i++) {
        const idx = collection.indexes[i]
        if (idx.version > prevVersion) continue

        const del = idx.encodeIndexKeys(prevDoc, this.context)
        const ups = []

        u.indexes.push(ups)

        for (let j = 0; j < del.length; j++) ups.push({ key: del[j], value: null })
      }
    } finally {
      snap.unref()
      this.updates.exit(collection)
    }
  }

  async insert(collectionName, record, { tick = 0 } = {}) {
    maybeClosed(this)

    if (this.updates.refs > 1) this.updates = this.updates.detach()

    const collection = this.definition.resolveCollection(collectionName)
    if (collection === null) throw new Error('Unknown collection: ' + collectionName)

    if (tick === 0) tick = this.updates.nextTick()
    while (this.updates.enter(collection) === false) await this.updates.wait(collection)

    const snap = this.engineSnapshot.ref()
    const key = collection.encodeKey(record)
    const collectionVersion = Math.min(this.versions.db, collection.version)
    const value = collection.encodeValue(this.versions.schema, collectionVersion, record)

    let prevValue = null

    try {
      prevValue = await this.engineSnapshot.get(key, -1, this.activeRequests)
      if (collection.trigger !== null) {
        tick = await this._runTrigger(tick, collection, record, record)
      }

      const prevDoc =
        prevValue === null ? null : collection.reconstruct(this.versions.schema, key, prevValue)

      const prevVersion = prevDoc ? collection.decodedVersion : -1

      if (prevValue !== null && prevVersion === collectionVersion && b4a.equals(value, prevValue)) {
        this.updates.delete(key)
        return
      }

      const u = this.updates.update(collection, tick, key, value)

      u.created = prevValue === null

      for (let i = 0; i < collection.indexes.length; i++) {
        const idx = collection.indexes[i]
        const prevKeys =
          idx.version <= prevVersion ? idx.encodeIndexKeys(prevDoc, this.context) : []
        const nextKeys = idx.encodeIndexKeys(record, this.context)
        const ups = []

        u.indexes.push(ups)

        const [del, put] = diffKeys(prevKeys, nextKeys)
        const value = put.length === 0 ? null : idx.encodeValue(record)

        for (let j = 0; j < del.length; j++) ups.push({ key: del[j], value: null })
        for (let j = 0; j < put.length; j++) ups.push({ key: put[j], value })
      }
    } finally {
      snap.unref()
      this.updates.exit(collection)
    }
  }

  async insertAll(batch) {
    const promises = []

    for (const [collection, record, opts] of batch) {
      if (opts && opts.type === 'delete') {
        promises.push(this.delete(collection, record))
      } else {
        promises.push(this.insert(collection, record))
      }
    }

    await Promise.all(promises)
  }

  update() {
    maybeClosed(this)

    if (!this.engine.outdated(this.engineSnapshot)) return

    if (this.updates.refs > 1) this.updates = this.updates.detach()
    this.updates.flush()

    this.engineSnapshot.unref()
    this.engineSnapshot = this.engine.snapshot()

    if (this.watchers !== null) {
      for (const fn of this.watchers) fn()
    }
  }

  async _flush() {
    if (this.engine.outdated(this.engineSnapshot)) {
      throw new Error('Database has changed, refusing to commit')
    }

    if (this.updates.refs > 1) this.updates = this.updates.detach()

    await this.engine.commit(this.updates)

    this.update()

    if (this.rootInstance !== this && this.rootInstance.updates.size === 0) {
      this.rootInstance.update()
    }
  }

  async flush() {
    maybeClosed(this)

    if (this.engineSnapshot.opened === false) await this.engineSnapshot.ready()

    if (this.updates.mutating > 0) throw new Error('Insert/delete in progress, refusing to commit')
    if (this.rootInstance === null) throw new Error('Instance is not writable, refusing to commit')
    if (this.updates.size > 0) await this._flush()
    if (this.autoClose === true) await this.close()
  }
}

function maybeClosed(db) {
  if (db.closing !== null) throw new Error('Hyperdb is closed')
}

function withinRange(range, key) {
  if (range.gte && b4a.compare(range.gte, key) > 0) return false
  if (range.gt && b4a.compare(range.gt, key) >= 0) return false
  if (range.lte && b4a.compare(range.lte, key) < 0) return false
  if (range.lt && b4a.compare(range.lt, key) <= 0) return false
  return true
}

function sortKeys(a, b) {
  return b4a.compare(a, b)
}

function sortUpdates(a, b) {
  return a.tick - b.tick // oldest to newest
}

function compareOverlay(a, b) {
  const c = b4a.compare(a.key, b.key)
  if (c !== 0) return c
  compareHasDups = true
  return b.tick - a.tick
}

function reverseCompareOverlay(a, b) {
  const c = b4a.compare(b.key, a.key)
  if (c !== 0) return c
  compareHasDups = true
  return b.tick - a.tick
}

function diffKeys(a, b) {
  if (a.length === 0 || b.length === 0) return [a, b]

  // 90% of all indexes
  if (a.length === 1 && b.length === 1) {
    return b4a.equals(a[0], b[0]) ? [[], []] : [a, b]
  }

  a.sort(sortKeys)
  b.sort(sortKeys)

  const res = [[], []]
  let ai = 0
  let bi = 0

  while (true) {
    if (ai < a.length && bi < b.length) {
      const cmp = b4a.compare(a[ai], b[bi])

      if (cmp === 0) {
        ai++
        bi++
      } else if (cmp < 0) {
        res[0].push(a[ai++])
      } else {
        res[1].push(b[bi++])
      }

      continue
    }

    if (ai < a.length) res[0].push(a[ai++])
    else if (bi < b.length) res[1].push(b[bi++])
    else break
  }

  return res
}

function stripDups(overlay) {
  let j = 0

  for (let i = 0; i < overlay.length; i++) {
    const a = overlay[i]
    overlay[j++] = a
    while (i + 1 < overlay.length && b4a.equals(a.key, overlay[i + 1].key)) i++
  }

  overlay.length = j
}

function sortOverlay(overlay, reverse) {
  compareHasDups = false
  overlay.sort(reverse ? reverseCompareOverlay : compareOverlay)
  if (compareHasDups === true) stripDups(overlay)
  return overlay
}

module.exports = HyperDB
function toChangesStream(stream, map) {
  const existingMap = stream._readableState.map
  stream._readableState.map = function (data) {
    let entry = data
    if (existingMap) {
      entry = existingMap(data)
      if (!entry) return null
    }

    return map(entry)
  }
  return stream
}

module.exports = toChangesStream
exports.isDefinition = isDefinition
exports.compat = makeCompat

function makeCompat(definition) {
  if (definition.versions) return definition

  for (const c of definition.collections) {
    if (typeof c.version === 'number') continue
    const { encodeValue } = c
    c.encodeValue = function (schemaVersion, collectionVersion, record) {
      return encodeValue(schemaVersion, record)
    }
    c.version = 0
    c.decodedVersion = 0
  }

  for (const i of definition.indexes) {
    if (typeof i.version === 'number') continue
    i.version = 0
  }

  return {
    versions: { schema: definition.version, db: 0 },
    collections: definition.collections,
    indexes: definition.indexes,
    resolveCollection: definition.resolveCollection,
    resolveIndex: definition.resolveIndex
  }
}

function isDefinition(definition) {
  return !!(definition && typeof definition.resolveCollection === 'function')
}
const HyperBee = require('hyperbee')
const ScopeLock = require('scope-lock')
const c = require('compact-encoding')
const RefCounter = require('refcounter')
const Hypercore = require('hypercore')
const Sessions = require('../sessions.js')
const toChangesStream = require('../changes-stream.js')

class BeeSnapshot {
  constructor(snap, onfree) {
    this.refs = 1
    this.snapshot = snap
    this.opened = false
    this.onfree = onfree
  }

  async ready() {
    await this.snapshot.ready()
    this.opened = true
  }

  ref() {
    this.refs++
    return this
  }

  unref() {
    if (--this.refs === 0) {
      this.snapshot.close().then(this.onfree, this.onfree)
      this.snapshot = null
    }
  }

  cork() {}

  uncork() {}

  getIndirectRange(reconstruct, entries, checkout, reqs) {
    const promises = new Array(entries.length)

    for (let i = 0; i < promises.length; i++) {
      const { key, value } = entries[i]
      promises[i] = getWrapped(this.snapshot, key, reconstruct(key, value), checkout, reqs)
    }

    return promises
  }

  getBatch(keys, checkout, reqs) {
    const promises = new Array(keys.length)

    for (let i = 0; i < keys.length; i++) {
      promises[i] = getValue(this.snapshot, keys[i], checkout, reqs)
    }

    return Promise.all(promises)
  }

  get(key, checkout, reqs) {
    return getValue(this.snapshot, key, checkout, reqs)
  }

  createReadStream(range, options) {
    return this.snapshot.createReadStream(range, options)
  }
}

module.exports = class BeeEngine {
  constructor(core, { extension, trace } = {}) {
    this.asap = true
    this.clock = 0
    this.core = core
    this.sessions = new Sessions()
    this.trace = trace
    this.snaps = new RefCounter()
    this.db = new HyperBee(core, {
      extension,
      keyEncoding: 'binary',
      valueEncoding: 'binary'
    })

    this.tx = null
    this.lock = new ScopeLock()

    this._freeSnapBound = this.snaps.dec.bind(this.snaps)
  }

  get closed() {
    return this.db.closed
  }

  ready() {
    return this.db.ready()
  }

  async close() {
    while (!this.snaps.isIdle()) await this.snaps.idle()
    await this.db.close()
  }

  enter() {
    return this.lock.lock()
  }

  exit() {
    this.tx = null
    this.lock.unlock()
  }

  finalize(collection, versions, checkout, tracing, key, value) {
    if (value === null) return null

    const reconstructed = collection.reconstruct(versions.schema, key, value)
    if (this.trace && tracing) this.trace(collection.name, reconstructed, checkout)

    return reconstructed
  }

  changes(snapshot, versions, definition, range) {
    const db = snapshot === null ? this.db : snapshot.snapshot
    const collectionsById = new Map()
    for (const c of definition.collections) collectionsById.set(c.id, c)

    return toChangesStream(
      db.createHistoryStream(range),
      mapChange.bind(null, versions, collectionsById)
    )
  }

  checkout(opts) {
    return null // not supported
  }

  snapshot() {
    this.snaps.inc()
    return new BeeSnapshot(this.db.snapshot(), this._freeSnapBound)
  }

  outdated(snap) {
    return (
      snap === null ||
      this.core.length !== snap.snapshot.core.length ||
      this.core.fork !== snap.snapshot.core.fork
    )
  }

  async commit(updates) {
    this.clock++

    let i = 0

    const entries = updates.batch()
    const batch = this.db.batch({ maxBlocksCached: entries.length * 2 })

    for (; i < entries.length; i++) {
      const [key, value] = entries[i]

      if (value !== null) await batch.put(key, value)
      else await batch.del(key)
    }

    await batch.flush()
  }

  clearRequests(reqs) {
    Hypercore.destroyRequests(reqs, null)
  }
}

async function getWrapped(db, key, value, checkout, reqs) {
  return { key, value: [value, await getValue(db, value, checkout, reqs)] }
}

async function getValue(db, key, checkout, activeRequests) {
  const node = await db.get(key, { checkout, activeRequests })
  return node === null ? null : node.value
}

function mapChange(versions, collectionsById, data) {
  const id = c.uint.decode({ start: 0, end: data.key.byteLength, buffer: data.key })
  const coll = collectionsById.get(id)
  if (coll === undefined) return null

  if (data.type === 'put') {
    const doc = coll.reconstruct(versions.schema, data.key, data.value)
    return { type: 'insert', seq: data.seq, collection: coll.name, value: doc }
  }

  const key = coll.reconstructKey(data.key)
  return { type: 'delete', seq: data.seq, collection: coll.name, value: key }
}
const Hypercore = require('hypercore')
const ScopeLock = require('scope-lock')
const b4a = require('b4a')
const RefCounter = require('refcounter')
const c = require('compact-encoding')

const toChangesStream = require('../changes-stream.js')
const Sessions = require('../sessions.js')

class BeeSnapshot {
  constructor(snap, onfree) {
    this.refs = 1
    this.snapshot = snap
    this.opened = false
    this.onfree = onfree
  }

  async ready() {
    await this.snapshot.ready()
    this.opened = true
  }

  ref() {
    this.refs++
    return this
  }

  unref() {
    if (--this.refs === 0) {
      this.snapshot.close().then(this.onfree, this.onfree)
      this.snapshot = null
    }
  }

  cork() {}

  uncork() {}

  getIndirectRange(reconstruct, entries, checkout, reqs) {
    const promises = new Array(entries.length)

    for (let i = 0; i < promises.length; i++) {
      const { key, value } = entries[i]
      promises[i] = getWrapped(this.snapshot, key, reconstruct(key, value), checkout, reqs)
    }

    return promises
  }

  getBatch(keys, checkout, reqs) {
    const promises = new Array(keys.length)

    for (let i = 0; i < keys.length; i++) {
      promises[i] = getValue(this.snapshot, keys[i], checkout, reqs)
    }

    return Promise.all(promises)
  }

  get(key, checkout, reqs) {
    return getValue(this.snapshot, key, checkout, reqs)
  }

  createReadStream(range, options) {
    return this.snapshot.createReadStream({ ...range, ...options })
  }
}

module.exports = class Bee2Engine {
  constructor(bee, { trace, key, length = -1 } = {}) {
    this.asap = true
    this.clock = 0
    this.sessions = new Sessions()
    this.trace = trace
    this.snaps = new RefCounter()
    this.db = bee

    if (length > -1) this.db.move({ key, length })

    this.tx = null
    this.lock = new ScopeLock()

    this._freeSnapBound = this.snaps.dec.bind(this.snaps)
  }

  head() {
    return this.db.head()
  }

  get core() {
    return this.db.core
  }

  get closed() {
    return this.db.closed
  }

  ready() {
    return this.db.ready()
  }

  async close() {
    while (!this.snaps.isIdle()) await this.snaps.idle()
    await this.db.close()
  }

  enter() {
    return this.lock.lock()
  }

  exit() {
    this.tx = null
    this.lock.unlock()
  }

  finalize(collection, versions, checkout, tracing, key, value) {
    if (value === null) return null

    const reconstructed = collection.reconstruct(versions.schema, key, value)
    if (this.trace && tracing) this.trace(collection.name, reconstructed, checkout)

    return reconstructed
  }

  changes(snapshot, versions, definition, range) {
    const db = snapshot === null ? this.db : snapshot.snapshot

    const from = db.checkout(range.from)

    const collectionsById = new Map()
    for (const c of definition.collections) collectionsById.set(c.id, c)

    const stream = toChangesStream(
      from.createDiffStream(db, range),
      mapChange.bind(null, versions, collectionsById)
    )
    stream.on('close', () => from.close().catch(noop))
    return stream
  }

  snapshot() {
    this.snaps.inc()
    return new BeeSnapshot(this.db.snapshot(), this._freeSnapBound)
  }

  checkout(opts) {
    if (opts === -1) return null
    this.snaps.inc()
    return new BeeSnapshot(this.db.checkout(opts), this._freeSnapBound)
  }

  outdated(snap) {
    if (snap === null) return true

    const a = snap.snapshot.head()
    const b = this.db.head()
    if (!a || !b) return true

    if (a.length !== b.length) return true
    return !b4a.equals(a.key, b.key)
  }

  async commit(updates) {
    this.clock++

    let i = 0

    const entries = updates.batch()
    const batch = this.db.write()

    for (; i < entries.length; i++) {
      const [key, value] = entries[i]

      if (value !== null) batch.tryPut(key, value)
      else batch.tryDelete(key)
    }

    await batch.flush()
  }

  clearRequests(reqs) {
    Hypercore.destroyRequests(reqs, null)
  }
}

async function getWrapped(db, key, value, checkout, reqs) {
  return { key, value: [value, await getValue(db, value, checkout, reqs)] }
}

async function getValue(db, key, checkout, activeRequests) {
  const source = checkout === -1 || !checkout ? db : db.checkout(checkout)
  try {
    const node = await source.get(key, { checkout, activeRequests })
    return node === null ? null : node.value
  } finally {
    if (source !== db) source.close().catch(noop)
  }
}

function mapChange(versions, collectionsById, { left, right }) {
  const insert = !!right
  const data = insert ? right : left
  const id = c.uint.decode({ start: 0, end: data.key.byteLength, buffer: data.key })

  const coll = collectionsById.get(id)
  if (coll === undefined) return null
  const head = { length: data.core.length, key: b4a.from(data.core.key) }

  if (insert) {
    const doc = coll.reconstruct(versions.schema, data.key, data.value)
    return { type: 'insert', head, collection: coll.name, value: doc }
  }

  const key = coll.reconstructKey(data.key)
  return { type: 'delete', head, collection: coll.name, value: key }
}

function noop() {}
const RocksDB = require('rocksdb-native')
const ScopeLock = require('scope-lock')
const Sessions = require('../sessions.js')

class RocksSnapshot {
  constructor(snap, clock) {
    this.clock = clock
    this.corks = 0
    this.refs = 1
    this.snapshot = snap
    this.opened = true
    this.closed = false
    this.batch = null
    this.batches = []
  }

  ready() {
    return this.snapshot.ready()
  }

  ref() {
    this.refs++
    return this
  }

  unref() {
    if (--this.refs === 0) {
      this.closed = true
      this.snapshot.close().catch(noop)
      for (const b of this.batches) b.destroy()
    }
  }

  cork() {
    this.corks++
    if (this.batch === null) this.batch = this.snapshot.read()
  }

  uncork() {
    if (--this.corks !== 0) return
    if (this.batch !== null) this._flushBackground(this.batch)
    this.batch = null
  }

  // checkout, reqs is just here for completeness, not supported in rocks
  getIndirectRange(reconstruct, entries, checkout, reqs) {
    // TODO: add prop api for this in rocks, ie snapshot.closing
    if (this.snapshot._state.closing) return rejectAll(entries)

    const read = this.batches.length > 0 ? this.batches.pop() : this.snapshot.read()
    const promises = new Array(entries.length)

    for (let i = 0; i < promises.length; i++) {
      const { key, value } = entries[i]
      promises[i] = getWrapped(read, key, reconstruct(key, value))
    }

    this._flushBackground(read)
    return promises
  }

  // checkout is just here for completeness, not supported in rocks
  getBatch(keys, checkout, reqs) {
    const read = this.batches.length > 0 ? this.batches.pop() : this.snapshot.read()
    const promises = new Array(keys.length)

    for (let i = 0; i < promises.length; i++) {
      promises[i] = read.get(keys[i])
    }

    this._flushBackground(read)
    return Promise.all(promises)
  }

  // checkout is just here for completeness, not supported in rocks
  get(key, checkout, reqs) {
    return this.batch === null ? this.snapshot.get(key) : this.batch.get(key)
  }

  createReadStream(range, options) {
    return this.snapshot.iterator({ ...range, ...options })
  }

  async _flushBackground(batch) {
    try {
      await batch.flush()
      if (this.closed) batch.destroy()
      else this.batches.push(batch)
    } catch (err) {
      batch.destroy()
    }
  }
}

module.exports = class RocksEngine {
  constructor(storage, options = {}) {
    this.asap = false
    this.clock = 0
    this.sessions = new Sessions()
    this.trace = options.trace || null
    this.core = null
    this.db = typeof storage === 'object' ? storage : new RocksDB(storage, options)
    this.db.ready().catch(noop)
    this.write = null
    this.tx = null
    this.lock = new ScopeLock()
  }

  get closed() {
    return this.db.closed
  }

  enter() {
    return this.lock.lock()
  }

  exit() {
    this.tx = null
    this.lock.unlock()
  }

  ready() {
    return this.db.ready()
  }

  close() {
    if (this.write !== null) this.write.destroy()
    return this.db.close()
  }

  finalize(collection, versions, checkout, tracing, key, value) {
    if (value === null) return null

    const reconstructed = collection.reconstruct(versions.schema, key, value)
    if (this.trace && tracing) this.trace(collection.name, reconstructed, checkout)

    return reconstructed
  }

  changes() {
    throw new Error('Not supported in Rocks engine')
  }

  checkout(opts) {
    return null // not supported
  }

  snapshot() {
    return new RocksSnapshot(this.db.snapshot(), this.clock)
  }

  outdated(snap) {
    return snap === null || snap.clock !== this.clock
  }

  async commit(updates) {
    this.clock++

    if (this.write === null) this.write = this.db.write()

    const entries = updates.batch()

    for (let i = 0; i < entries.length; i++) {
      const [key, value] = entries[i]

      if (value !== null) this.write.tryPut(key, value)
      else this.write.tryDelete(key)
    }

    await this.write.flush()
  }

  clearRequests(reqs) {
    // api parity
  }
}

async function getWrapped(read, key, value) {
  return { key, value: [value, await read.get(value)] }
}

function noop() {}

function rejectAll(entries) {
  const promises = new Array(entries.length)
  for (let i = 0; i < entries.length; i++) {
    promises[i] = Promise.reject(new Error('Database is closed'))
  }
  return promises
}
module.exports = class SessionTracker {
  constructor() {
    this.sessions = []
  }

  get size() {
    return this.sessions.length
  }

  has(s) {
    return s.index < this.sessions.length && this.sessions[s.index] === s
  }

  add(s) {
    if (this.has(s)) return
    s.index = this.sessions.push(s) - 1
  }

  remove(s) {
    if (!this.has(s)) return

    const head = this.sessions.pop()
    if (head === s) return
    this.sessions[(head.index = s.index)] = head
  }

  close(skip) {
    const closing = []

    for (let i = this.sessions.length - 1; i >= 0; i--) {
      const s = this.sessions[i]
      if (s === skip) continue
      closing.push(s.close())
    }

    return Promise.all(closing)
  }
}
const { Readable, isEnded, getStreamError } = require('streamx')
const b4a = require('b4a')

module.exports = class IndexStream extends Readable {
  constructor(
    db,
    range,
    {
      index = null,
      collection = index.collection,
      reverse = false,
      limit = -1,
      overlay = [],
      checkout = 0
    }
  ) {
    super()

    this.versions = db.versions
    this.engine = db.engine
    this.checkout = checkout
    this.engineSnapshot = db.engineSnapshot
    this.snapshot = db.engine.checkout(checkout) || this.engineSnapshot
    this.activeRequests = db.activeRequests
    this.traceable = db.traceable
    this.collection = collection
    this.index = index

    this.stream = this.snapshot.createReadStream(range, {
      reverse,
      limit,
      checkout,
      activeRequests: this.activeRequests
    })
    this.streamClosed = false
    this.overlay = overlay
    this.overlayIndex = 0
    this.continueDestroy = null
    this.limit = limit
    this.reverse = reverse
    this.mapping = false
    this.ending = false

    this.snapshot.ref()
  }

  _open(cb) {
    const destroy = this.destroy.bind(this)
    const drain = this._drain.bind(this)
    const onclose = this._onclose.bind(this)

    this.stream.on('readable', drain)
    this.stream.on('end', drain)

    this.stream.on('error', destroy)
    this.stream.on('close', onclose)

    cb(null)
  }

  _onclose() {
    this.streamClosed = true
    if (isEnded(this.stream) === false) this.destroy()
    this._continueDestroyMaybe()
  }

  _continueDestroyMaybe() {
    if (this.mapping === true) return
    if (this.streamClosed === false) return
    if (this.continueDestroy === null) return

    const cb = this.continueDestroy
    this.continueDestroy = null
    this.snapshot.unref()

    // we own the bee snapshot
    if (this.engineSnapshot !== this.snapshot) this.snapshot.unref()

    cb(null)
  }

  _push(value) {
    if (value === null) return
    if (this.limit > 0) this.limit--
    this.push(
      this.engine.finalize(
        this.collection,
        this.versions,
        this.checkout,
        this.traceable,
        value[0],
        value[1]
      )
    )
  }

  _process(batch, ended) {
    for (let i = 0; i < batch.length && this.limit !== 0; i++) {
      const data = batch[i]

      while (this.limit !== 0) {
        if (this.overlayIndex >= this.overlay.length) {
          this._push(data.value)
          break
        }

        const cmp = b4a.compare(data.key, this.overlay[this.overlayIndex].key)
        if (this.reverse === true ? cmp > 0 : cmp < 0) {
          this._push(data.value)
          break
        }

        this._push(this.overlay[this.overlayIndex++].value)
        if (cmp === 0) break
      }
    }

    if (ended === true) {
      while (this.overlayIndex < this.overlay.length && this.limit !== 0) {
        this._push(this.overlay[this.overlayIndex++].value)
      }

      this.push(null)
      this.ending = true
    }
  }

  async _processAsap(promises, ended) {
    for (let i = 1; i < promises.length; i++) promises[i].catch(noop) // promises are handled

    for (let i = 0; i < promises.length; i++) {
      const batch = [await promises[i]]
      if (this.destroying === true) return
      this._process(batch, i === promises.length - 1 && ended)
    }
  }

  async _mapAndProcess() {
    this.mapping = true

    while (!Readable.isBackpressured(this) && this.destroying === false) {
      const entries = fullyDrain(this.stream)

      const promises =
        entries.length === 0
          ? entries
          : this.snapshot.getIndirectRange(
              this.index.reconstruct,
              entries,
              this.checkout,
              this.activeRequests
            )
      const ended = isEnded(this.stream)

      if (promises.length === 0 && ended === false) break

      try {
        if (this.engine.asap === true && promises.length > 1) {
          await this._processAsap(promises, ended)
        } else {
          const batch = await Promise.all(promises)
          if (this.destroying === false) this._process(batch, ended)
        }
      } catch (err) {
        await Promise.allSettled(promises)
        this.destroy(err)
      }
    }

    this.mapping = false
    this._continueDestroyMaybe()
  }

  _drain() {
    if (Readable.isBackpressured(this)) return

    if (this.index === null) {
      this._process(fullyDrainMapped(this.stream), isEnded(this.stream))
    } else if (this.mapping === false) {
      this._mapAndProcess()
    }
  }

  _read(cb) {
    this._drain()
    cb(null)
  }

  _predestroy() {
    this.stream.destroy()
  }

  _destroy(cb) {
    this.stream.destroy()
    this.continueDestroy = cb
    this._continueDestroyMaybe()
  }

  one() {
    const stream = this
    let last = null

    return new Promise(function (resolve, reject) {
      stream.on('error', noop)
      stream.on('readable', onreadable)
      stream.on('close', onclose)

      function onreadable() {
        while (true) {
          const data = stream.read()
          if (data === null) return
          last = data
        }
      }

      function onclose() {
        if (isEnded(stream)) resolve(last)
        else reject(getStreamError(stream, { all: true }))
      }
    })
  }

  async toArray() {
    const stream = this
    const list = []

    return new Promise(function (resolve, reject) {
      stream.on('error', noop)
      stream.on('readable', onreadable)
      stream.on('close', onclose)

      function onreadable() {
        while (true) {
          const data = stream.read()
          if (data === null) return
          list.push(data)
        }
      }

      function onclose() {
        if (isEnded(stream)) resolve(list)
        else reject(getStreamError(stream, { all: true }))
      }
    })
  }
}

function fullyDrainMapped(stream) {
  const batch = []

  while (true) {
    const data = stream.read()
    if (data === null) return batch
    batch.push({ key: data.key, value: [data.key, data.value] })
  }
}

function fullyDrain(stream) {
  const batch = []

  while (true) {
    const data = stream.read()
    if (data === null) return batch
    batch.push(data)
  }
}

function noop() {}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "hyperdb",
  "version": "6.7.0",
  "description": "P2P Indexable Database",
  "files": [
    "index.js",
    "runtime.js",
    "runtime.mjs",
    "builder/*.js",
    "builder/*.mjs",
    "lib/**"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "brittle-node test/*.js",
    "generate": "rm -rf test/fixtures/generated && node test/fixtures/generate.js"
  },
  "exports": {
    ".": "./index.js",
    "./package": "./package.json",
    "./builder": {
      "import": "./builder/index.mjs",
      "default": "./builder/index.js"
    },
    "./runtime": {
      "import": "./runtime.mjs",
      "default": "./runtime.js"
    }
  },
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    }
  },
  "dependencies": {
    "b4a": "^1.6.6",
    "compact-encoding": "^3.0.0",
    "generate-object-property": "^2.0.0",
    "generate-string": "^1.0.1",
    "hyperbee": "^2.24.2",
    "hypercore": "^11.29.0",
    "hyperschema": "^1.9.2",
    "index-encoder": "^3.4.0",
    "refcounter": "^1.0.0",
    "rocksdb-native": "^3.0.0",
    "scope-lock": "^1.2.4",
    "streamx": "^2.20.0"
  },
  "devDependencies": {
    "brittle": "^3.7.0",
    "corestore": "^7.8.0",
    "hyperbee2": "^2.7.1",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "test-tmp": "^1.2.1"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/hyperdb.git"
  },
  "author": "Holepunch Inc",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/hyperdb/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperdb"
}
module.exports = {
  c: require('compact-encoding'),
  b4a: require('b4a'),
  IndexEncoder: require('index-encoder')
}
const c = require('compact-encoding')
const { getEncoding } = require('./spec/hyperschema')

const HyperdhtAddress = getEncoding('@hyperdht/address')

function decode(buf) {
  const addr = c.decode(HyperdhtAddress, buf)
  return addr
}

function encode(key, nodes) {
  return c.encode(HyperdhtAddress, { key, nodes })
}

module.exports = { decode, encode }
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "hyperdht-address",
  "version": "1.1.1",
  "description": "hyperdht-address",
  "main": "index.js",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    }
  },
  "files": [
    "package.json",
    "index.js",
    "index.d.ts",
    "spec"
  ],
  "devDependencies": {
    "b4a": "^1.8.0",
    "brittle": "^3.19.0",
    "lunte": "^1.2.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && lunte && brittle-bare test/index.js",
    "lint": "lunte"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/hyperdht-address.git"
  },
  "author": "Holepunch Inc",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/hyperdht-address/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperdht-address",
  "dependencies": {
    "compact-encoding": "^3.0.0",
    "hyperschema": "^1.20.1"
  }
}
// This file is autogenerated by the hyperschema compiler
// Schema Version: 2
/* eslint-disable camelcase */
/* eslint-disable quotes */
/* eslint-disable space-before-function-paren */

const { c } = require('hyperschema/runtime')

const VERSION = 2

// eslint-disable-next-line no-unused-vars
let version = VERSION

// @hyperdht/address.nodes
const encoding0_1 = c.array(c.ipv4Address)

// @hyperdht/address
const encoding0 = {
  preencode(state, m) {
    c.fixed32.preencode(state, m.key)
    state.end++ // max flag is 1 so always one byte

    if (version >= 2 && m.nodes) encoding0_1.preencode(state, m.nodes)
  },
  encode(state, m) {
    const flags = version >= 2 && m.nodes ? 1 : 0

    c.fixed32.encode(state, m.key)
    c.uint.encode(state, flags)

    if (version >= 2 && m.nodes) encoding0_1.encode(state, m.nodes)
  },
  decode(state) {
    const r0 = c.fixed32.decode(state)
    const flags = state.start < state.end ? c.uint.decode(state) : 0

    return {
      key: r0,
      nodes: version >= 2 && (flags & 1) !== 0 ? encoding0_1.decode(state) : null
    }
  }
}

function setVersion(v) {
  version = v
}

function encode(name, value, v = VERSION) {
  version = v
  return c.encode(getEncoding(name), value)
}

function decode(name, buffer, v = VERSION) {
  version = v
  return c.decode(getEncoding(name), buffer)
}

function getEnum(name) {
  switch (name) {
    default:
      throw new Error('Enum not found ' + name)
  }
}

function getEncoding(name) {
  switch (name) {
    case '@hyperdht/address':
      return encoding0
    default:
      throw new Error('Encoder not found ' + name)
  }
}

function getStruct(name, v = VERSION) {
  const enc = getEncoding(name)
  return {
    preencode(state, m) {
      version = v
      enc.preencode(state, m)
    },
    encode(state, m) {
      version = v
      enc.encode(state, m)
    },
    decode(state) {
      version = v
      return enc.decode(state)
    }
  }
}

const resolveStruct = getStruct // compat

module.exports = {
  resolveStruct,
  getStruct,
  getEnum,
  getEncoding,
  encode,
  decode,
  setVersion,
  version
}
const DHT = require('dht-rpc')
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const b4a = require('b4a')
const safetyCatch = require('safety-catch')
const m = require('./lib/messages')
const SocketPool = require('./lib/socket-pool')
const Persistent = require('./lib/persistent')
const Router = require('./lib/router')
const Cache = require('xache')
const Server = require('./lib/server')
const connect = require('./lib/connect')
const { FIREWALL, BOOTSTRAP_NODES, COMMANDS } = require('./lib/constants')
const { hash, createKeyPair } = require('./lib/crypto')
const RawStreamSet = require('./lib/raw-stream-set')
const ConnectionPool = require('./lib/connection-pool')
const { STREAM_NOT_CONNECTED } = require('./lib/errors')

const DEFAULTS = {
  ...DHT.DEFAULTS,
  connectionKeepAlive: 5000,
  randomPunchInterval: 20000
}

class HyperDHT extends DHT {
  constructor(opts = {}) {
    const port = opts.port || 49737
    const bootstrap = opts.bootstrap || BOOTSTRAP_NODES
    const nodes = opts.nodes || []

    super({ ...opts, port, bootstrap, nodes, filterNode })

    const { router, relayAddresses, persistent } = defaultCacheOpts(opts)

    this.defaultKeyPair = opts.keyPair || createKeyPair(opts.seed)
    this.listening = new Set()
    this.connectionKeepAlive =
      opts.connectionKeepAlive === false
        ? 0
        : opts.connectionKeepAlive || DEFAULTS.connectionKeepAlive

    // stats is inherited from dht-rpc so fwd the ones from there
    this.stats = {
      punches: { consistent: 0, random: 0, open: 0 },
      relaying: { attempts: 0, successes: 0, aborts: 0 },
      ...this.stats
    }
    this.rawStreams = new RawStreamSet(this)
    this.plugins = new Map()

    this._router = new Router(this, router)
    this._socketPool = new SocketPool(this, opts.host || '0.0.0.0')
    this._persistent = null
    this._validatedLocalAddresses = new Map()
    this._relayAddressesCache = new Cache(relayAddresses)

    this._deferRandomPunch = !!opts.deferRandomPunch
    this._lastRandomPunch = this._deferRandomPunch ? Date.now() : 0
    this._connectable = true
    this._randomPunchInterval = opts.randomPunchInterval || DEFAULTS.randomPunchInterval // min 20s between random punches...
    this._randomPunches = 0
    this._randomPunchLimit = 1 // set to one for extra safety for now

    this.once('persistent', () => {
      this._persistent = new Persistent(this, persistent)
      for (const plugin of this.plugins.values()) plugin.onpersistent()
    })

    this.on('network-change', () => {
      for (const server of this.listening) server.refresh()
    })

    this.on('network-update', () => {
      if (!this.online) return
      for (const server of this.listening) server.notifyOnline()
    })
  }

  static DEFAULTS = DEFAULTS

  connect(remotePublicKey, opts) {
    return connect(this, remotePublicKey, opts)
  }

  createServer(opts, onconnection) {
    if (typeof opts === 'function') return this.createServer({}, opts)
    if (opts && opts.onconnection) onconnection = opts.onconnection
    const s = new Server(this, opts)
    if (onconnection) s.on('connection', onconnection)
    return s
  }

  pool() {
    return new ConnectionPool(this)
  }

  async resume({ log = noop } = {}) {
    if (this._deferRandomPunch) this._lastRandomPunch = Date.now()
    await super.resume({ log })
    const resuming = []
    for (const server of this.listening) resuming.push(server.resume())
    log('Resuming hyperdht servers')
    await Promise.allSettled(resuming)
    log('Done, hyperdht fully resumed')
  }

  async suspend({ log = noop } = {}) {
    this._connectable = false // just so nothing gets connected during suspension
    const suspending = []
    for (const server of this.listening) suspending.push(server.suspend())
    log('Suspending all hyperdht servers')
    await Promise.allSettled(suspending)
    log('Done, clearing all raw streams')
    await this.rawStreams.clear()
    log('Done, suspending dht-rpc')
    await super.suspend({ log })
    log('Done, clearing raw streams again')
    await this.rawStreams.clear()
    log('Done, hyperdht fully suspended')
    this._connectable = true
  }

  async destroy({ force = false } = {}) {
    if (!force) {
      const closing = []
      for (const server of this.listening) closing.push(server.close())
      await Promise.allSettled(closing)
    }
    this._router.destroy()
    if (this._persistent) this._persistent.destroy()
    for (const plugin of this.plugins.values()) plugin.destroy()
    await this.rawStreams.clear()
    await this._socketPool.destroy()
    await super.destroy()
  }

  async validateLocalAddresses(addresses) {
    const list = []
    const socks = []
    const waiting = []

    for (const addr of addresses) {
      const { host } = addr

      if (this._validatedLocalAddresses.has(host)) {
        if (await this._validatedLocalAddresses.get(host)) {
          list.push(addr)
        }
        continue
      }

      const sock = this.udx.createSocket()
      try {
        sock.bind(0, host)
      } catch {
        this._validatedLocalAddresses.set(host, Promise.resolve(false))
        continue
      }

      socks.push(sock)

      // semi terrible heuristic until we proper fix local connections by racing them to the remote...
      const promise = new Promise((resolve) => {
        sock.on('message', () => resolve(true))
        setTimeout(() => resolve(false), 500)
        sock.trySend(b4a.alloc(1), sock.address().port, addr.host)
      })

      this._validatedLocalAddresses.set(host, promise)
      waiting.push(addr)
    }

    for (const addr of waiting) {
      const { host } = addr
      if (this._validatedLocalAddresses.has(host)) {
        if (await this._validatedLocalAddresses.get(host)) {
          list.push(addr)
        }
        continue
      }
    }

    for (const sock of socks) await sock.close()

    return list
  }

  findPeer(publicKey, opts = {}) {
    const target = opts.hash === false ? publicKey : hash(publicKey)
    opts = { ...opts, map: mapFindPeer }
    return this.query({ target, command: COMMANDS.FIND_PEER, value: null }, opts)
  }

  lookup(target, opts = {}) {
    opts = { ...opts, map: mapLookup }
    return this.query({ target, command: COMMANDS.LOOKUP, value: null }, opts)
  }

  lookupAndUnannounce(target, keyPair, opts = {}) {
    const unannounces = []
    const dht = this
    const userCommit = opts.commit || noop
    const signUnannounce = opts.signUnannounce || Persistent.signUnannounce

    if (this._persistent !== null) {
      // unlink self
      this._persistent.unannounce(target, keyPair.publicKey)
    }

    opts = { ...opts, map, commit }
    return this.query({ target, command: COMMANDS.LOOKUP, value: null }, opts)

    async function commit(reply, dht, query) {
      await Promise.all(unannounces) // can never fail, caught below
      return userCommit(reply, dht, query)
    }

    function map(reply) {
      const data = mapLookup(reply)

      if (!data || !data.token) return data

      let found = data.peers.length >= 20
      for (let i = 0; !found && i < data.peers.length; i++) {
        found = b4a.equals(data.peers[i].publicKey, keyPair.publicKey)
      }

      if (!found) return data

      if (!data.from.id) return data

      unannounces.push(
        dht
          ._requestUnannounce(keyPair, dht, target, data.token, data.from, signUnannounce)
          .catch(safetyCatch)
      )

      return data
    }
  }

  unannounce(target, keyPair, opts = {}) {
    return this.lookupAndUnannounce(target, keyPair, opts).finished()
  }

  announce(target, keyPair, relayAddresses, opts = {}) {
    const signAnnounce = opts.signAnnounce || Persistent.signAnnounce
    const bump = opts.bump || 0

    opts = { ...opts, commit }

    return opts.clear ? this.lookupAndUnannounce(target, keyPair, opts) : this.lookup(target, opts)

    function commit(reply, dht) {
      return dht._requestAnnounce(
        keyPair,
        dht,
        target,
        reply.token,
        reply.from,
        relayAddresses,
        signAnnounce,
        bump
      )
    }
  }

  async immutableGet(target, opts = {}) {
    opts = { ...opts, map: mapImmutable }

    const query = this.query({ target, command: COMMANDS.IMMUTABLE_GET, value: null }, opts)
    const check = b4a.allocUnsafe(32)

    for await (const node of query) {
      const { value } = node
      sodium.crypto_generichash(check, value)
      if (b4a.equals(check, target)) return node
    }

    return null
  }

  async immutablePut(value, opts = {}) {
    const target = b4a.allocUnsafe(32)
    sodium.crypto_generichash(target, value)

    opts = {
      ...opts,
      map: mapImmutable,
      commit(reply, dht) {
        return dht.request(
          { token: reply.token, target, command: COMMANDS.IMMUTABLE_PUT, value },
          reply.from
        )
      }
    }

    const query = this.query({ target, command: COMMANDS.IMMUTABLE_GET, value: null }, opts)
    await query.finished()

    return { hash: target, closestNodes: query.closestNodes }
  }

  async mutableGet(publicKey, opts = {}) {
    let refresh = opts.refresh || null
    let signed = null
    let result = null

    opts = { ...opts, map: mapMutable, commit: refresh ? commit : null }

    const target = b4a.allocUnsafe(32)
    sodium.crypto_generichash(target, publicKey)

    const userSeq = opts.seq || 0
    const query = this.query(
      { target, command: COMMANDS.MUTABLE_GET, value: c.encode(c.uint, userSeq) },
      opts
    )
    const latest = opts.latest !== false

    for await (const node of query) {
      if (result && node.seq <= result.seq) continue
      if (
        node.seq < userSeq ||
        !Persistent.verifyMutable(node.signature, node.seq, node.value, publicKey)
      )
        continue
      if (!latest) return node
      if (!result || node.seq > result.seq) result = node
    }

    return result

    function commit(reply, dht) {
      if (!signed && result && refresh) {
        if (refresh(result)) {
          signed = c.encode(m.mutablePutRequest, {
            publicKey,
            seq: result.seq,
            value: result.value,
            signature: result.signature
          })
        } else {
          refresh = null
        }
      }

      return signed
        ? dht.request(
            { token: reply.token, target, command: COMMANDS.MUTABLE_PUT, value: signed },
            reply.from
          )
        : Promise.resolve(null)
    }
  }

  async mutablePut(keyPair, value, opts = {}) {
    const signMutable = opts.signMutable || Persistent.signMutable

    const target = b4a.allocUnsafe(32)
    sodium.crypto_generichash(target, keyPair.publicKey)

    const seq = opts.seq || 0
    const signature = await signMutable(seq, value, keyPair)

    const signed = c.encode(m.mutablePutRequest, {
      publicKey: keyPair.publicKey,
      seq,
      value,
      signature
    })

    opts = {
      ...opts,
      map: mapMutable,
      commit(reply, dht) {
        return dht.request(
          { token: reply.token, target, command: COMMANDS.MUTABLE_PUT, value: signed },
          reply.from
        )
      }
    }

    // use seq = 0, for the query part here, as we don't care about the actual values
    const query = this.query(
      { target, command: COMMANDS.MUTABLE_GET, value: c.encode(c.uint, 0) },
      opts
    )
    await query.finished()

    return { publicKey: keyPair.publicKey, closestNodes: query.closestNodes, seq, signature }
  }

  onrequest(req) {
    switch (req.command) {
      case COMMANDS.PEER_HANDSHAKE: {
        this._router.onpeerhandshake(req)
        return true
      }
      case COMMANDS.PEER_HOLEPUNCH: {
        this._router.onpeerholepunch(req)
        return true
      }
    }

    if (this._persistent === null || this.id === null) return false

    switch (req.command) {
      case COMMANDS.FIND_PEER: {
        this._persistent.onfindpeer(req)
        return true
      }
      case COMMANDS.LOOKUP: {
        this._persistent.onlookup(req)
        return true
      }
      case COMMANDS.ANNOUNCE: {
        this._persistent.onannounce(req)
        return true
      }
      case COMMANDS.UNANNOUNCE: {
        this._persistent.onunannounce(req)
        return true
      }
      case COMMANDS.MUTABLE_PUT: {
        this._persistent.onmutableput(req)
        return true
      }
      case COMMANDS.MUTABLE_GET: {
        this._persistent.onmutableget(req)
        return true
      }
      case COMMANDS.IMMUTABLE_PUT: {
        this._persistent.onimmutableput(req)
        return true
      }
      case COMMANDS.IMMUTABLE_GET: {
        this._persistent.onimmutableget(req)
        return true
      }
      case COMMANDS.PLUGIN: {
        this._persistent.onplugin(req)
        return true
      }
    }

    return false
  }

  static keyPair(seed) {
    return createKeyPair(seed)
  }

  static hash(data) {
    return hash(data)
  }

  static connectRawStream(encryptedStream, rawStream, remoteId) {
    const stream = encryptedStream.rawStream

    if (!stream.connected) throw STREAM_NOT_CONNECTED()

    rawStream.connect(stream.socket, remoteId, stream.remotePort, stream.remoteHost)
  }

  createRawStream(opts) {
    return this.rawStreams.add(opts)
  }

  async _requestAnnounce(keyPair, dht, target, token, from, relayAddresses, sign, bump) {
    const ann = {
      peer: {
        publicKey: keyPair.publicKey,
        relayAddresses: relayAddresses || []
      },
      refresh: null,
      signature: null,
      bump
    }

    ann.signature = await sign(target, token, from.id, ann, keyPair)

    const value = c.encode(m.announce, ann)

    return dht.request(
      {
        token,
        target,
        command: COMMANDS.ANNOUNCE,
        value
      },
      from
    )
  }

  async _requestUnannounce(keyPair, dht, target, token, from, sign) {
    const unann = {
      peer: {
        publicKey: keyPair.publicKey,
        relayAddresses: []
      },
      signature: null
    }

    unann.signature = await sign(target, token, from.id, unann, keyPair)

    const value = c.encode(m.announce, unann)

    return dht.request(
      {
        token,
        target,
        command: COMMANDS.UNANNOUNCE,
        value
      },
      from
    )
  }

  register(name, plugin) {
    this.plugins.set(name, plugin)
    plugin.onregister(this)
  }
}

HyperDHT.BOOTSTRAP = BOOTSTRAP_NODES
HyperDHT.FIREWALL = FIREWALL

module.exports = HyperDHT

function mapLookup(node) {
  if (!node.value) return null

  try {
    const l = c.decode(m.lookupRawReply, node.value)

    return {
      token: node.token,
      from: node.from,
      to: node.to,
      peers: l.peers,
      bump: l.bump
    }
  } catch {
    return null
  }
}

function mapFindPeer(node) {
  if (!node.value) return null

  try {
    return {
      token: node.token,
      from: node.from,
      to: node.to,
      peer: c.decode(m.peer, node.value)
    }
  } catch {
    return null
  }
}

function mapImmutable(node) {
  if (!node.value) return null

  return {
    token: node.token,
    from: node.from,
    to: node.to,
    value: node.value
  }
}

function mapMutable(node) {
  if (!node.value) return null

  try {
    const { seq, value, signature } = c.decode(m.mutableGetResponse, node.value)

    return {
      token: node.token,
      from: node.from,
      to: node.to,
      seq,
      value,
      signature
    }
  } catch {
    return null
  }
}

function noop() {}

function filterNode(node) {
  // always skip these testnet nodes that got mixed in by accident, until they get updated
  return (
    !(node.port === 49738 && (node.host === '134.209.28.98' || node.host === '167.99.142.185')) &&
    !(node.port === 9400 && node.host === '35.233.47.252') &&
    !(node.host === '150.136.142.116')
  )
}

const defaultMaxSize = 65536
const defaultMaxAge = 20 * 60 * 1000 // 20 minutes

function defaultCacheOpts(opts) {
  const maxSize = opts.maxSize || defaultMaxSize
  const maxAge = opts.maxAge || defaultMaxAge

  return {
    router: {
      forwards: { maxSize, maxAge }
    },
    relayAddresses: { maxSize: Math.min(maxSize, 512), maxAge: 0 },
    persistent: {
      records: { maxSize, maxAge },
      refreshes: { maxSize, maxAge },
      mutables: {
        maxSize: (maxSize / 2) | 0,
        maxAge: opts.maxAge || 48 * 60 * 60 * 1000 // 48 hours
      },
      immutables: {
        maxSize: (maxSize / 2) | 0,
        maxAge: opts.maxAge || 48 * 60 * 60 * 1000 // 48 hours
      },
      bumps: { maxSize, maxAge }
    }
  }
}
const safetyCatch = require('safety-catch')
const c = require('compact-encoding')
const Signal = require('signal-promise')
const { encodeUnslab } = require('./encode')
const Sleeper = require('./sleeper')
const m = require('./messages')
const Persistent = require('./persistent')
const { COMMANDS } = require('./constants')

const MIN_ACTIVE = 3

module.exports = class Announcer {
  constructor(dht, keyPair, target, opts = {}) {
    this.dht = dht
    this.keyPair = keyPair
    this.target = target
    this.relays = []
    this.relayAddresses = []
    this.stopped = false
    this.suspended = false
    this.record = encodeUnslab(m.peer, { publicKey: keyPair.publicKey, relayAddresses: [] })
    this.online = new Signal()

    this._refreshing = false
    this._closestNodes = null
    this._active = null
    this._sleeper = new Sleeper()
    this._resumed = new Signal()
    this._signAnnounce = opts.signAnnounce || Persistent.signAnnounce
    this._signUnannounce = opts.signUnannounce || Persistent.signUnannounce
    this._updating = null
    this._activeQuery = null
    this._unannouncing = null

    this._serverRelays = [new Map(), new Map(), new Map()]
  }

  isRelay(addr) {
    const id = addr.host + ':' + addr.port
    const [a, b, c] = this._serverRelays
    return a.has(id) || b.has(id) || c.has(id)
  }

  async suspend({ log = noop } = {}) {
    if (this.suspended) return
    this.suspended = true

    log('Suspending announcer')

    // Suspend has its own sleep logic
    // so we don't want to hang on this one
    this.online.notify()

    if (this._activeQuery) this._activeQuery.destroy()

    this._sleeper.resume()
    if (this._updating) await this._updating
    log('Suspending announcer (post update)')

    if (this.suspended === false || this.stopped) return

    log('Suspending announcer (pre unannounce)')
    await this._unannounceCurrent()
    log('Suspending announcer (post unannounce)')
  }

  resume() {
    if (!this.suspended) return
    this.suspended = false

    this.refresh()
    this._sleeper.resume()
    this._resumed.notify()
  }

  refresh() {
    if (this.stopped) return
    this._refreshing = true
  }

  async start() {
    if (this.stopped) return
    this._active = this._runUpdate()
    await this._active
    if (this.stopped) return
    this._active = this._background()
  }

  async stop() {
    this.stopped = true
    this.online.notify() // Break out of the _background loop if we're offline
    this._sleeper.resume()
    this._resumed.notify()
    await this._active
    await this._unannounceCurrent()
  }

  async _unannounceCurrent() {
    while (this._unannouncing !== null) await this._unannouncing
    const un = (this._unannouncing = this._unannounceAll(this._serverRelays[2].values()))
    await this._unannouncing
    if (un === this._unannouncing) this._unannouncing = null
  }

  async _background() {
    while (!this.dht.destroyed && !this.stopped) {
      try {
        this._refreshing = false

        // ~5min +-
        for (let i = 0; i < 100 && !this.stopped && !this._refreshing && !this.suspended; i++) {
          const pings = []

          for (const node of this._serverRelays[2].values()) {
            pings.push(this.dht.ping(node))
          }

          const active = await resolved(pings)
          if (active < Math.min(pings.length, MIN_ACTIVE)) {
            this.refresh() // we lost too many relay nodes, retry all
          }

          if (this.stopped) return

          if (!this.suspended && !this._refreshing) await this._sleeper.pause(3000)
        }

        while (!this.stopped && this.suspended) await this._resumed.wait()

        if (!this.stopped) await this._runUpdate()

        while (!this.dht.online && !this.stopped && !this.suspended) {
          // Being offline can make _background repeat very quickly
          // So wait until we're back online
          await this.online.wait()
        }
      } catch (err) {
        safetyCatch(err)
      }
    }
  }

  async _runUpdate() {
    this._updating = this._update()
    await this._updating
    this._updating = null
  }

  async _update() {
    while (this._unannouncing) await this._unannouncing

    this._cycle()

    const q = (this._activeQuery = this.dht.findPeer(this.target, {
      hash: false,
      nodes: this._closestNodes
    }))

    try {
      await q.finished()
    } catch {
      // ignore failures...
    }

    this._activeQuery = null

    if (this.stopped || this.suspended) return

    const ann = []
    const replies = pickBest(q.closestReplies)

    const relays = []
    const relayAddresses = []

    if (!this.dht.firewalled) {
      const addr = this.dht.remoteAddress()
      if (addr) relayAddresses.push(addr)
    }

    for (const msg of replies) {
      ann.push(this._commit(msg, relays, relayAddresses))
    }

    await Promise.allSettled(ann)
    if (this.stopped || this.suspended) return

    this._closestNodes = q.closestNodes
    this.relays = relays
    this.relayAddresses = relayAddresses

    const removed = []
    for (const [key, value] of this._serverRelays[1]) {
      if (!this._serverRelays[2].has(key)) removed.push(value)
    }

    await this._unannounceAll(removed)
  }

  _unannounceAll(relays) {
    const unann = []
    for (const r of relays) unann.push(this._unannounce(r))
    return Promise.allSettled(unann)
  }

  async _unannounce(to) {
    const unann = {
      peer: {
        publicKey: this.keyPair.publicKey,
        relayAddresses: []
      },
      refresh: null,
      signature: null
    }

    const { from, token, value } = await this.dht.request(
      {
        token: null,
        command: COMMANDS.FIND_PEER,
        target: this.target,
        value: null
      },
      to
    )

    if (!token || !from.id || !value) return

    unann.signature = await this._signUnannounce(this.target, token, from.id, unann, this.keyPair)

    await this.dht.request(
      {
        token,
        command: COMMANDS.UNANNOUNCE,
        target: this.target,
        value: c.encode(m.announce, unann)
      },
      to
    )
  }

  async _commit(msg, relays, relayAddresses) {
    const ann = {
      peer: {
        publicKey: this.keyPair.publicKey,
        relayAddresses: []
      },
      refresh: null,
      signature: null
    }

    ann.signature = await this._signAnnounce(this.target, msg.token, msg.from.id, ann, this.keyPair)

    const res = await this.dht.request(
      {
        token: msg.token,
        command: COMMANDS.ANNOUNCE,
        target: this.target,
        value: c.encode(m.announce, ann)
      },
      msg.from
    )

    if (res.error !== 0) return

    if (relayAddresses.length < 3) relayAddresses.push({ host: msg.from.host, port: msg.from.port })
    relays.push({ relayAddress: msg.from, peerAddress: msg.to })

    this._serverRelays[2].set(msg.from.host + ':' + msg.from.port, msg.from)
  }

  _cycle() {
    const tmp = this._serverRelays[0]
    this._serverRelays[0] = this._serverRelays[1]
    this._serverRelays[1] = this._serverRelays[2]
    this._serverRelays[2] = tmp
    tmp.clear()
  }
}

function resolved(ps) {
  let replied = 0
  let ticks = ps.length + 1

  return new Promise((resolve) => {
    for (const p of ps) p.then(push, tick)
    tick()

    function push(v) {
      replied++
      tick()
    }

    function tick() {
      if (--ticks === 0) resolve(replied)
    }
  })
}

function pickBest(replies) {
  // TODO: pick the ones closest to us RTT wise
  return replies.slice(0, 3)
}

function noop() {}
const NoiseSecretStream = require('@hyperswarm/secret-stream')
const b4a = require('b4a')
const relay = require('blind-relay')
const { isReserved, isBogon } = require('bogon')
const safetyCatch = require('safety-catch')
const unslab = require('unslab')
const Semaphore = require('./semaphore')
const NoiseWrap = require('./noise-wrap')
const SecurePayload = require('./secure-payload')
const Holepuncher = require('./holepuncher')
const Sleeper = require('./sleeper')
const {
  clearRelayTimeout,
  confirmDirectUpgrade,
  destroyRelayConnection
} = require('./relay-connection')
const { FIREWALL, ERROR } = require('./constants')
const { unslabbedHash } = require('./crypto')
const {
  CANNOT_HOLEPUNCH,
  HANDSHAKE_INVALID,
  HOLEPUNCH_ABORTED,
  HOLEPUNCH_INVALID,
  HOLEPUNCH_PROBE_TIMEOUT,
  HOLEPUNCH_DOUBLE_RANDOMIZED_NATS,
  PEER_CONNECTION_FAILED,
  PEER_NOT_FOUND,
  REMOTE_ABORTED,
  REMOTE_NOT_HOLEPUNCHABLE,
  REMOTE_NOT_HOLEPUNCHING,
  SERVER_ERROR,
  SERVER_INCOMPATIBLE,
  RELAY_ABORTED,
  SUSPENDED
} = require('./errors')
const { decode } = require('hypercore-id-encoding')
const HyperDHTAddress = require('hyperdht-address')

module.exports = function connect(dht, publicKey, opts = {}) {
  const pool = opts.pool || null

  const { key, nodes: providedNodes } = HyperDHTAddress.decode(
    b4a.isBuffer(publicKey) ? publicKey : decode(publicKey)
  )
  publicKey = key

  if (pool && pool.has(publicKey)) return pool.get(publicKey)

  publicKey = unslab(publicKey)

  opts.relayAddresses = opts.relayAddresses || providedNodes || []
  const keyPair = opts.keyPair || dht.defaultKeyPair
  const relayThrough = selectRelay(opts.relayThrough || null)
  const encryptedSocket = (opts.createSecretStream || defaultCreateSecretStream)(true, null, {
    publicKey: keyPair.publicKey,
    remotePublicKey: publicKey,
    autoStart: false,
    keepAlive: dht.connectionKeepAlive
  })

  // in case a socket is made during suspended state, destroy it immediately
  if (dht.suspended || !dht._connectable) {
    encryptedSocket.destroy(SUSPENDED())
    return encryptedSocket
  }

  if (pool) pool._attachStream(encryptedSocket, false)

  const id = b4a.toString(publicKey, 'hex')
  const c = {
    id,
    dht,
    session: dht.session(),
    relayAddresses: opts.relayAddresses,
    remoteRelayAddresses: [],
    pool,
    round: 0,
    target: unslabbedHash(publicKey),
    remotePublicKey: publicKey,
    reusableSocket: !!opts.reusableSocket,
    handshake: (opts.createHandshake || defaultCreateHandshake)(keyPair, publicKey),
    request: null,
    requesting: false,
    lan: opts.localConnection !== false,
    firewall: FIREWALL.UNKNOWN,
    rawStream: dht.createRawStream({ framed: true, firewall }),
    connect: null,
    query: null,
    puncher: null,
    payload: null,
    passiveConnectTimeout: null,
    serverSocket: null,
    serverAddress: null,
    onsocket: null,
    sleeper: new Sleeper(),
    encryptedSocket,

    // Relay state
    relayTimeout: null,
    relayThrough,
    relayToken: relayThrough ? relay.token() : null,
    relaySocket: null,
    relayClient: null,
    relayPaired: false,
    validUpgrade: true,
    relayKeepAlive: opts.relayKeepAlive || 5000
  }

  // If the raw stream receives an error signal pre connect (ie from the firewall hook), make sure
  // to forward that to the encrypted socket for proper teardown
  c.rawStream.on('error', autoDestroy)
  c.rawStream.once('connect', () => {
    c.rawStream.removeListener('error', autoDestroy)
  })

  encryptedSocket.on('close', function () {
    if (c.passiveConnectTimeout) clearPassiveConnectTimeout(c)
    if (c.query) c.query.destroy()
    if (c.puncher) c.puncher.destroy()
    if (c.rawStream) c.rawStream.destroy()
    c.session.destroy()
    c.sleeper.resume()
  })

  // Safe to run in the background - never throws
  if (dht.suspended) encryptedSocket.destroy(SUSPENDED())
  else connectAndHolepunch(c, opts)

  return encryptedSocket

  function autoDestroy(err) {
    maybeDestroyEncryptedSocket(c, err)
  }

  function firewall(socket, port, host) {
    // Check if the traffic originated from the socket on which we're expecting relay traffic. If so,
    // we haven't hole punched yet and the other side is just sending us traffic through the relay.
    if (c.relaySocket && isRelay(c.relaySocket, socket, port, host)) {
      c.validUpgrade = false
      return false
    }

    c.validUpgrade = true
    if (c.onsocket) {
      c.onsocket(socket, port, host)
    } else {
      c.serverSocket = socket
      c.serverAddress = { port, host }
    }
    return false
  }
}

function isDone(c) {
  // we are destroying or the puncher is connected - done
  if (c.encryptedSocket.destroying || !!(c.puncher && c.puncher.connected)) {
    return true
  }
  // not destroying, but no raw stream - def not done
  if (c.encryptedSocket.rawStream === null) {
    return false
  }
  // we are relayed, but the puncher is not done yet
  if (c.relaySocket && !!(c.puncher && !c.puncher.connected && !c.puncher.destroyed)) {
    return false
  }
  // we are done
  return true
}

async function retryRoute(c, route) {
  const ref = c.dht._socketPool.lookup(route.socket)

  if (!ref) {
    if (route.socket === c.dht.socket) {
      await connectThroughNode(c, route.address, c.dht.socket)
    }
    return
  }

  ref.active()

  try {
    await connectThroughNode(c, route.address, route.socket)
  } catch {
    // if error, just ignore, and continue through the existing strat
  }

  ref.inactive()
}

async function connectAndHolepunch(c, opts) {
  const route = c.reusableSocket ? c.dht._socketPool.routes.get(c.remotePublicKey) : null

  if (route) {
    await retryRoute(c, route)
    if (isDone(c)) return
  }

  await findAndConnect(c, opts)
  if (isDone(c)) return

  if (!c.connect) {
    // TODO: just a quick fix for now, should retry prob
    maybeDestroyEncryptedSocket(c, HANDSHAKE_INVALID())
    return
  }

  await holepunch(c, opts)
}

function getFirstRemoteAddress(addrs, serverAddress) {
  for (const addr of addrs) {
    if (isBogon(addr.host)) continue
    return addr
  }

  return serverAddress
}

async function holepunch(c, opts) {
  let { relayAddress, serverAddress, clientAddress, payload } = c.connect

  const remoteHolepunchable = !!(payload.holepunch && payload.holepunch.relays.length)
  const relayed = diffAddress(serverAddress, relayAddress)

  if (payload.firewall === FIREWALL.OPEN || (relayed && !remoteHolepunchable)) {
    const addr = getFirstRemoteAddress(payload.addresses4, serverAddress)
    if (addr) {
      const socket = c.dht.socket
      c.dht.stats.punches.open++
      c.onsocket(socket, addr.port, addr.host)
      return
    }
    // TODO: check all addresses also obvs
  }

  const onabort = () => {
    c.session.destroy()
    maybeDestroyEncryptedSocket(c, HOLEPUNCH_ABORTED())
  }

  if (c.firewall === FIREWALL.OPEN) {
    c.passiveConnectTimeout = setTimeout(onabort, 10000)
    return
  }

  // Race the LAN shortcut with normal holepunch when possible. A blocked LAN ping
  // should not abort a connection that can still holepunch. If the remote is not
  // holepunchable, the LAN ping is the only remaining path.
  if (c.lan && relayed && clientAddress.host === serverAddress.host) {
    const serverAddresses = payload.addresses4.filter(onlyNonReserved)

    if (serverAddresses.length > 0) {
      const myAddresses = Holepuncher.localAddresses(c.dht.io.serverSocket)
      const addr = Holepuncher.matchAddress(myAddresses, serverAddresses) || serverAddresses[0]

      const socket = c.dht.io.serverSocket
      c.dht.ping(addr).then(onlanconnect, onlanerror)
      if (!remoteHolepunchable) return

      function onlanconnect() {
        // LAN and holepunch completions both converge through onsocket,
        // which claims c.rawStream once and ignores later winners.
        if (isDone(c)) return
        c.onsocket(socket, addr.port, addr.host)
      }

      function onlanerror() {
        if (!remoteHolepunchable) {
          maybeDestroyEncryptedSocket(c, HOLEPUNCH_ABORTED())
        }
      }
    }
  }

  if (!remoteHolepunchable) {
    maybeDestroyEncryptedSocket(c, CANNOT_HOLEPUNCH())
    return
  }

  c.puncher = new Holepuncher(c.dht, c.session, true, payload.firewall)

  c.puncher.onconnect = c.onsocket
  c.puncher.onabort = onabort

  const serverRelay = pickServerRelay(payload.holepunch.relays, relayAddress)

  // Begin holepunching!

  let probe
  try {
    probe = await probeRound(c, opts.fastOpen === false ? null : serverAddress, serverRelay, true)
  } catch (err) {
    destroyPuncher(c)
    // TODO: we should retry here with some of the other relays, bail for now
    maybeDestroyEncryptedSocket(c, err)
    return
  }

  if (isDone(c) || !probe) return
  const { token, peerAddress } = probe

  // If the relay the server picked is the same as the relay the client picked,
  // then we can use the peerAddress that round one indicates the server wants to use.
  // This shaves off a roundtrip if the server chose to reroll its socket due to some NAT
  // issue with the first one it picked (ie mobile nat inconsistencies...).
  // If the relays were different, then the server would not have a UDP session open on this address
  // to the client relay, which round2 uses.
  if (
    !diffAddress(serverRelay.relayAddress, relayAddress) &&
    diffAddress(serverAddress, peerAddress)
  ) {
    serverAddress = peerAddress
    await c.puncher.openSession(serverAddress)
    if (isDone(c)) return
  }

  // TODO: still continue here if a local connection might work, but then do not holepunch...
  if (
    opts.holepunch &&
    !opts.holepunch(
      c.puncher.remoteFirewall,
      c.puncher.nat.firewall,
      c.puncher.remoteAddresses,
      c.puncher.nat.addresses
    )
  ) {
    await abort(c, serverRelay, HOLEPUNCH_ABORTED('Client aborted holepunch'))
    return
  }

  try {
    await roundPunch(c, serverAddress, token, relayAddress, serverRelay, false)
  } catch (err) {
    destroyPuncher(c)
    // TODO: retry with another relay?
    maybeDestroyEncryptedSocket(c, err)
  }
}

async function connectThroughNodes(c, addresses, socket) {
  for (const address of addresses) {
    if (isDone(c) || c.connect) return

    c.remoteRelayAddresses.push(address)
    await connectThroughNode(c, address, socket)
  }
}

async function findAndConnect(c, opts) {
  let attempts = 0
  let relayAddresses =
    opts.relayAddresses && opts.relayAddresses.length ? opts.relayAddresses : null

  if (!relayAddresses) {
    const cachedRelayAddresses = c.dht._relayAddressesCache.get(c.id)
    if (cachedRelayAddresses) relayAddresses = cachedRelayAddresses
  }

  if (c.dht._persistent) {
    // check if we know the route ourself...
    const route = c.dht._router.get(c.target)
    if (route && route.relay !== null) {
      relayAddresses = [{ host: route.relay.host, port: route.relay.port }]
    }
  }

  // 2 is how many parallel connect attempts we want to do, we can make this configurable
  const preConnect = relayAddresses !== null && relayAddresses.length > 0
  const sem = new Semaphore(preConnect ? 3 : 2)
  const signal = sem.signal.bind(sem)
  const tries = relayAddresses !== null ? 2 : 1

  if (preConnect) {
    await sem.wait()
    connectThroughNodes(c, relayAddresses, null).then(signal, signal)
  }

  try {
    for (let i = 0; i < tries && !isDone(c) && !c.connect; i++) {
      c.query = c.dht.findPeer(c.target, {
        hash: false,
        session: c.session,
        nodes: relayAddresses,
        retries: 3
      })

      for await (const data of c.query) {
        await sem.wait()
        if (isDone(c)) return

        if (c.connect) {
          sem.signal()
          break
        }

        // Skip node already run via preConnect
        if (preConnect && relayAddresses && isRelayAddress(relayAddresses, data)) {
          sem.signal()
          continue
        }

        c.remoteRelayAddresses.push(data.from)
        attempts++
        connectThroughNode(c, data.from, null).then(signal, signal)
      }

      relayAddresses = null

      if (attempts > 0) await sem.flush()
    }

    c.query = null
    if (isDone(c)) return

    // flush the semaphore
    await sem.flush()
    if (isDone(c)) return
  } catch (err) {
    c.query = null
    maybeDestroyEncryptedSocket(c, err)
    return
  }

  if (!c.connect) {
    maybeDestroyEncryptedSocket(c, attempts ? PEER_CONNECTION_FAILED() : PEER_NOT_FOUND())
  }
}

async function connectThroughNode(c, address, socket) {
  if (!c.requesting) {
    // If we have a stable server address, send it over now
    const addr = c.dht.remoteAddress()
    const localAddrs = c.lan ? Holepuncher.localAddresses(c.dht.io.serverSocket) : null
    const addresses4 = []

    if (addr) addresses4.push(addr)
    if (localAddrs) addresses4.push(...localAddrs)

    c.firewall = addr ? FIREWALL.OPEN : FIREWALL.UNKNOWN
    c.requesting = true
    c.request = await c.handshake.send({
      error: ERROR.NONE,
      firewall: c.firewall,
      holepunch: null,
      addresses4,
      addresses6: [],
      udx: {
        reusableSocket: c.reusableSocket,
        id: c.rawStream.id,
        seq: 0
      },
      secretStream: {},
      relayThrough: c.relayThrough ? { publicKey: c.relayThrough, token: c.relayToken } : null
    })
    if (isDone(c)) return
  }

  const { serverAddress, clientAddress, relayed, noise } = await c.dht._router.peerHandshake(
    c.target,
    { noise: c.request, socket, session: c.session },
    address
  )
  if (isDone(c) || c.connect) return

  const payload = await c.handshake.recv(noise)
  if (isDone(c) || !payload) return

  if (payload.version !== 1) {
    maybeDestroyEncryptedSocket(c, SERVER_INCOMPATIBLE())
    return
  }
  if (payload.error !== ERROR.NONE) {
    maybeDestroyEncryptedSocket(c, SERVER_ERROR())
    return
  }
  if (!payload.udx) {
    maybeDestroyEncryptedSocket(c, SERVER_ERROR('Server did not send UDX data'))
    return
  }

  const hs = c.handshake.final()

  c.handshake = null
  c.request = null
  c.requesting = false
  c.connect = {
    relayed,
    relayAddress: address,
    clientAddress,
    serverAddress,
    payload
  }

  c.payload = new SecurePayload(hs.holepunchSecret)

  c.onsocket = function (socket, port, host) {
    if (c.rawStream === null) return // Already hole punched

    if (c.rawStream.connected) {
      const rawStream = c.rawStream
      const remoteChanging = rawStream.changeRemote(socket, c.connect.payload.udx.id, port, host)
      confirmDirectUpgrade(c, rawStream, remoteChanging)
    } else {
      // cache the relay addrs for a future reconnect, we prefer the remote one so they
      // can give us the correct ones from their pov
      if (payload.relayAddresses && payload.relayAddresses.length) {
        c.dht._relayAddressesCache.set(c.id, payload.relayAddresses)
      } else if (c.remoteRelayAddresses.length) {
        c.dht._relayAddressesCache.set(c.id, c.remoteRelayAddresses)
      }

      c.rawStream.connect(socket, c.connect.payload.udx.id, port, host)
      c.encryptedSocket.start(c.rawStream, { handshake: hs })
    }

    if (c.reusableSocket && payload.udx.reusableSocket) {
      c.dht._socketPool.routes.add(c.remotePublicKey, c.rawStream)
    }

    if (c.puncher) {
      c.puncher.onabort = noop
      c.puncher.destroy()
    }

    if (c.passiveConnectTimeout) {
      clearPassiveConnectTimeout(c)
    }

    c.rawStream = null
  }

  if (payload.relayThrough || c.relayThrough) {
    relayConnection(c, c.relayThrough, payload, hs)
  }

  if (c.serverSocket) {
    c.onsocket(c.serverSocket, c.serverAddress.port, c.serverAddress.host)
    return
  }

  if (!relayed) {
    c.onsocket(socket || c.dht.socket, address.port, address.host)
  }

  c.session.destroy()
}

async function updateHolepunch(c, peerAddress, relayAddr, payload) {
  const holepunch = await c.dht._router.peerHolepunch(
    c.target,
    {
      id: c.connect.payload.holepunch.id,
      payload: c.payload.encrypt(payload),
      peerAddress,
      socket: c.puncher.socket,
      session: c.session
    },
    relayAddr
  )

  if (isDone(c)) return null

  const remotePayload = c.payload.decrypt(holepunch.payload)
  if (!remotePayload) {
    throw HOLEPUNCH_INVALID()
  }

  const { error, firewall, punching, addresses, remoteToken } = remotePayload

  if (error === ERROR.TRY_LATER && c.relayToken && payload.punching) {
    return {
      tryLater: true,
      ...holepunch,
      payload: remotePayload
    }
  }

  if (error !== ERROR.NONE) {
    throw REMOTE_ABORTED('Remote aborted with error code ' + error)
  }

  const echoed = !!(remoteToken && payload.token && b4a.equals(remoteToken, payload.token))

  c.puncher.updateRemote({
    punching,
    firewall,
    addresses,
    verified: echoed ? peerAddress.host : null
  })

  return {
    tryLater: false,
    ...holepunch,
    payload: remotePayload
  }
}

async function probeRound(c, serverAddress, serverRelay, retry) {
  // Open a quick low ttl session against what we think is the server
  if (serverAddress) await c.puncher.openSession(serverAddress)

  if (isDone(c)) return null

  const reply = await updateHolepunch(c, serverRelay.peerAddress, serverRelay.relayAddress, {
    error: ERROR.NONE,
    firewall: c.puncher.nat.firewall,
    round: c.round++,
    connected: false,
    punching: false,
    addresses: c.puncher.nat.addresses,
    remoteAddress: serverAddress,
    token: null,
    remoteToken: null
  })

  if (isDone(c) || !reply) return null

  const { peerAddress } = reply
  const { address, token } = reply.payload

  c.puncher.nat.add(reply.to, reply.from)

  // Open another quick low ttl session against what the server says their address is,
  // if they haven't said they are random yet
  if (
    c.puncher.remoteFirewall < FIREWALL.RANDOM &&
    address &&
    address.host &&
    address.port &&
    diffAddress(address, serverAddress)
  ) {
    await c.puncher.openSession(address)
    if (isDone(c)) return null
  }

  // If the remote told us they didn't know their nat firewall yet, give them a chance to figure it out
  // They might say this to see if the "fast mode" punch comes through first.
  if (c.puncher.remoteFirewall === FIREWALL.UNKNOWN) {
    await c.sleeper.pause(1000)
    if (isDone(c)) return null
  }

  let stable = await c.puncher.analyze(false)
  if (isDone(c)) return null

  // If the socket seems unstable, try to make it stable by setting the "allowReopen" flag
  // Mostly relevant for mobile networks
  if (!stable) {
    stable = await c.puncher.analyze(true)
    if (isDone(c)) return null
    if (stable) return probeRound(c, serverAddress, serverRelay, false)
  }

  if ((c.puncher.remoteFirewall === FIREWALL.UNKNOWN || !token) && retry) {
    return probeRound(c, serverAddress, serverRelay, false)
  }

  if (
    c.puncher.remoteFirewall === FIREWALL.UNKNOWN ||
    c.puncher.nat.firewall === FIREWALL.UNKNOWN
  ) {
    await abort(c, serverRelay, HOLEPUNCH_PROBE_TIMEOUT())
    return null
  }

  if (c.puncher.remoteFirewall >= FIREWALL.RANDOM && c.puncher.nat.firewall >= FIREWALL.RANDOM) {
    await abort(c, serverRelay, HOLEPUNCH_DOUBLE_RANDOMIZED_NATS())
    return null
  }

  return { token, peerAddress }
}

async function roundPunch(c, serverAddress, remoteToken, clientRelay, serverRelay, delayed) {
  // We are gossiping our final NAT status to the other peer now
  // so make sure we don't update our local view for now as that can make things weird
  c.puncher.nat.freeze()

  const isRandom =
    c.puncher.remoteFirewall >= FIREWALL.RANDOM || c.puncher.nat.firewall >= FIREWALL.RANDOM
  if (isRandom) {
    while (
      c.dht._randomPunches >= c.dht._randomPunchLimit ||
      Date.now() - c.dht._lastRandomPunch < c.dht._randomPunchInterval
    ) {
      // if no relay can help, bail
      if (!c.relayToken) throw HOLEPUNCH_ABORTED()

      if (!delayed) {
        delayed = true
        await updateHolepunch(c, serverAddress, clientRelay, {
          error: ERROR.NONE,
          firewall: c.puncher.nat.firewall,
          round: c.round++,
          connected: false,
          punching: false,
          addresses: c.puncher.nat.addresses,
          remoteAddress: null,
          token: c.payload.token(serverAddress),
          remoteToken
        })
        if (isDone(c)) return
      }

      await tryLater(c)
      if (isDone(c)) return
    }
  }

  // increment now, so we can commit to punching
  if (isRandom) c.dht._randomPunches++

  let reply

  try {
    // if delayed switch to the servers chosen relay - we validated anyway
    reply = await updateHolepunch(
      c,
      delayed ? serverRelay.peerAddress : serverAddress,
      delayed ? serverRelay.relayAddress : clientRelay,
      {
        error: ERROR.NONE,
        firewall: c.puncher.nat.firewall,
        round: c.round++,
        connected: false,
        punching: true,
        addresses: c.puncher.nat.addresses,
        remoteAddress: null,
        token: delayed ? null : c.payload.token(serverAddress),
        remoteToken
      }
    )
  } finally {
    // decrement as punch increments for us
    if (isRandom) c.dht._randomPunches--
  }

  if (isDone(c)) return
  if (!reply) return

  if (reply.tryLater) {
    await tryLater(c)
    if (isDone(c)) return
    return roundPunch(c, serverAddress, remoteToken, clientRelay, serverRelay, true)
  }

  if (!c.puncher.remoteHolepunching) {
    throw REMOTE_NOT_HOLEPUNCHING()
  }

  if (!(await c.puncher.punch())) {
    throw REMOTE_NOT_HOLEPUNCHABLE()
  }
}

async function tryLater(c) {
  if (!c.relayToken) throw HOLEPUNCH_ABORTED()
  await c.sleeper.pause(10000 + Math.round(Math.random() * 10000))
}

function maybeDestroyEncryptedSocket(c, err) {
  if (isDone(c)) return
  if (c.encryptedSocket.rawStream) return
  if (c.relaySocket) return // waiting for the relay
  if (c.puncher && !c.puncher.destroyed) return // waiting for the puncher
  c.session.destroy()
  c.encryptedSocket.destroy(err)
}

async function abort(c, { peerAddress, relayAddress }, err) {
  try {
    await updateHolepunch(c, peerAddress, relayAddress, {
      error: ERROR.ABORTED,
      firewall: FIREWALL.UNKNOWN,
      round: c.round++,
      connected: false,
      punching: false,
      addresses: null,
      remoteAddress: null,
      token: null,
      remoteToken: null
    })
  } catch (err) {
    safetyCatch(err)
  }

  destroyPuncher(c)
  maybeDestroyEncryptedSocket(c, err)
}

function relayConnection(c, relayThrough, payload, hs) {
  let isInitiator
  let publicKey
  let token

  if (payload.relayThrough) {
    isInitiator = false
    publicKey = payload.relayThrough.publicKey
    token = payload.relayThrough.token
  } else {
    isInitiator = true
    publicKey = relayThrough
    token = c.relayToken
  }

  c.relayToken = token
  c.relaySocket = c.dht.connect(publicKey)
  c.relaySocket.setKeepAlive(c.relayKeepAlive)
  c.relayClient = relay.Client.from(c.relaySocket, { id: c.relaySocket.publicKey })
  c.relayTimeout = setTimeout(onabort, 15000, null)

  c.relayClient.pair(isInitiator, token, c.rawStream).on('error', onabort).on('data', ondata)

  function ondata(remoteId) {
    if (c.relayTimeout) clearRelayTimeout(c)
    if (c.rawStream === null) {
      onabort(null)
      return
    }

    c.relayPaired = true

    const { remotePort, remoteHost, socket } = c.relaySocket.rawStream

    c.rawStream
      .on('close', () => destroyRelayConnection(c))
      .connect(socket, remoteId, remotePort, remoteHost)

    c.encryptedSocket.start(c.rawStream, { handshake: hs })
  }

  function onabort(err) {
    destroyRelayConnection(c)
    maybeDestroyEncryptedSocket(c, err || RELAY_ABORTED())
  }
}

function clearPassiveConnectTimeout(c) {
  clearTimeout(c.passiveConnectTimeout)
  c.passiveConnectTimeout = null
}

function destroyPuncher(c) {
  if (c.puncher) c.puncher.destroy()
  c.session.destroy()
}

function pickServerRelay(relays, clientRelay) {
  for (const r of relays) {
    if (!diffAddress(r.relayAddress, clientRelay)) return r
  }
  return relays[0]
}

function diffAddress(a, b) {
  return a.host !== b.host || a.port !== b.port
}

function defaultCreateHandshake(keyPair, remotePublicKey) {
  return new NoiseWrap(keyPair, remotePublicKey)
}

function defaultCreateSecretStream(isInitiator, rawStream, opts) {
  return new NoiseSecretStream(isInitiator, rawStream, opts)
}

function onlyNonReserved(addr) {
  return !isReserved(addr.host)
}

function isRelay(relaySocket, socket, port, host) {
  const stream = relaySocket.rawStream
  if (!stream) return false
  if (stream.socket !== socket) return false
  return port === stream.remotePort && host === stream.remoteHost
}

function selectRelay(relayThrough) {
  if (typeof relayThrough === 'function') relayThrough = relayThrough()
  if (relayThrough === null) return null
  if (Array.isArray(relayThrough))
    return relayThrough[Math.floor(Math.random() * relayThrough.length)]
  return relayThrough
}

function isRelayAddress(relayAddresses, data) {
  for (const node of relayAddresses) {
    if (node.host === data.from.host && node.port === data.from.port) return true
  }

  return false
}

function noop() {}
const EventEmitter = require('events')
const b4a = require('b4a')
const errors = require('./errors')

module.exports = class ConnectionPool extends EventEmitter {
  constructor(dht) {
    super()

    this._dht = dht
    this._servers = new Map()
    this._connecting = new Map()
    this._connections = new Map()
  }

  _attachServer(server) {
    const keyString = b4a.toString(server.publicKey, 'hex')

    this._servers.set(keyString, server)

    server
      .on('close', () => {
        this._servers.delete(keyString)
      })
      .on('connection', (socket) => {
        this._attachStream(socket, true)
      })
  }

  _attachStream(stream, opened) {
    const existing = this.get(stream.remotePublicKey)

    if (existing) {
      const keepNew =
        stream.isInitiator === existing.isInitiator ||
        b4a.compare(stream.publicKey, stream.remotePublicKey) > 0

      if (keepNew) {
        let closed = false

        const onclose = () => {
          closed = true
        }

        existing
          .on('error', noop)
          .on('close', () => {
            if (closed) return

            stream.off('error', noop).off('close', onclose)

            this._attachStream(stream, opened)
          })
          .destroy(errors.DUPLICATE_CONNECTION())

        stream.on('error', noop).on('close', onclose)
      } else {
        stream.on('error', noop).destroy(errors.DUPLICATE_CONNECTION())
      }

      return
    }

    const session = new ConnectionRef(this, stream)

    const keyString = b4a.toString(stream.remotePublicKey, 'hex')

    if (opened) {
      this._connections.set(keyString, session)

      stream.on('close', () => {
        this._connections.delete(keyString)
      })

      this.emit('connection', stream, session)
    } else {
      this._connecting.set(keyString, session)

      stream
        .on('error', noop)
        .on('close', () => {
          if (opened) this._connections.delete(keyString)
          else this._connecting.delete(keyString)
        })
        .on('open', () => {
          opened = true

          this._connecting.delete(keyString)
          this._connections.set(keyString, session)

          stream.off('error', noop)

          this.emit('connection', stream, session)
        })
    }

    return session
  }

  get connecting() {
    return this._connecting.size
  }

  get connections() {
    return this._connections.values()
  }

  has(publicKey) {
    const keyString = b4a.toString(publicKey, 'hex')

    return this._connections.has(keyString) || this._connecting.has(keyString)
  }

  get(publicKey) {
    const keyString = b4a.toString(publicKey, 'hex')

    const existing = this._connections.get(keyString) || this._connecting.get(keyString)

    return existing?._stream || null
  }
}

class ConnectionRef {
  constructor(pool, stream) {
    this._pool = pool
    this._stream = stream
    this._refs = 0
  }

  active() {
    this._refs++
  }

  inactive() {
    this._refs--
  }

  release() {
    this._stream.destroy()
  }
}

function noop() {}
const crypto = require('hypercore-crypto')

const COMMANDS = (exports.COMMANDS = {
  PEER_HANDSHAKE: 0,
  PEER_HOLEPUNCH: 1,
  FIND_PEER: 2,
  LOOKUP: 3,
  ANNOUNCE: 4,
  UNANNOUNCE: 5,
  MUTABLE_PUT: 6,
  MUTABLE_GET: 7,
  IMMUTABLE_PUT: 8,
  IMMUTABLE_GET: 9,
  PLUGIN: 10
})

exports.BOOTSTRAP_NODES = [
  '88.99.3.86@node1.hyperdht.org:49737',
  '142.93.90.113@node2.hyperdht.org:49737',
  '138.68.147.8@node3.hyperdht.org:49737'
]

exports.FIREWALL = {
  UNKNOWN: 0,
  OPEN: 1,
  CONSISTENT: 2,
  RANDOM: 3
}

exports.ERROR = {
  // noise / connection related
  NONE: 0,
  ABORTED: 1,
  VERSION_MISMATCH: 2,
  TRY_LATER: 3,
  // dht related
  SEQ_REUSED: 16,
  SEQ_TOO_LOW: 17
}

const [
  NS_ANNOUNCE,
  NS_UNANNOUNCE,
  NS_MUTABLE_PUT,
  NS_PEER_HANDSHAKE,
  NS_PEER_HOLEPUNCH,
  NS_PLUGIN
] = crypto.namespace('hyperswarm/dht', [
  COMMANDS.ANNOUNCE,
  COMMANDS.UNANNOUNCE,
  COMMANDS.MUTABLE_PUT,
  COMMANDS.PEER_HANDSHAKE,
  COMMANDS.PEER_HOLEPUNCH,
  COMMANDS.PLUGIN
])

exports.NS = {
  ANNOUNCE: NS_ANNOUNCE,
  UNANNOUNCE: NS_UNANNOUNCE,
  MUTABLE_PUT: NS_MUTABLE_PUT,
  PEER_HANDSHAKE: NS_PEER_HANDSHAKE,
  PEER_HOLEPUNCH: NS_PEER_HOLEPUNCH,
  PLUGIN: NS_PLUGIN
}
const sodium = require('sodium-universal')
const b4a = require('b4a')

function hash(data) {
  const out = b4a.allocUnsafe(32)
  sodium.crypto_generichash(out, data)
  return out
}

function unslabbedHash(data) {
  const out = b4a.allocUnsafeSlow(32)
  sodium.crypto_generichash(out, data)
  return out
}

function createKeyPair(seed) {
  const publicKey = b4a.alloc(32)
  const secretKey = b4a.alloc(64)
  if (seed) sodium.crypto_sign_seed_keypair(publicKey, secretKey, seed)
  else sodium.crypto_sign_keypair(publicKey, secretKey)
  return { publicKey, secretKey }
}

module.exports = {
  hash,
  unslabbedHash,
  createKeyPair
}
const b4a = require('b4a')
const cenc = require('compact-encoding')

function encodeUnslab(enc, m) {
  // Faster than unslab(c.encode(enc, data)) because it avoids the mem copy.
  // Makes sense to put in compact-encoding when we need it in other modules too
  const state = cenc.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafeSlow(state.end)
  enc.encode(state, m)
  return state.buffer
}

module.exports = {
  encodeUnslab
}
module.exports = class DHTError extends Error {
  constructor(msg, code, fn = DHTError) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'DHTError'
  }

  static BAD_HANDSHAKE_REPLY(msg = 'Bad handshake reply') {
    return new DHTError(msg, 'BAD_HANDSHAKE_REPLY', DHTError.BAD_HANDSHAKE_REPLY)
  }

  static BAD_HOLEPUNCH_REPLY(msg = 'Bad holepunch reply') {
    return new DHTError(msg, 'BAD_HOLEPUNCH_REPLY', DHTError.BAD_HOLEPUNCH_REPLY)
  }

  static HOLEPUNCH_ABORTED(msg = 'Holepunch aborted') {
    return new DHTError(msg, 'HOLEPUNCH_ABORTED', DHTError.HOLEPUNCH_ABORTED)
  }

  static HOLEPUNCH_INVALID(msg = 'Invalid holepunch payload') {
    return new DHTError(msg, 'HOLEPUNCH_INVALID', DHTError.HOLEPUNCH_INVALID)
  }

  static HOLEPUNCH_PROBE_TIMEOUT(msg = 'Holepunching probe did not finish in time') {
    return new DHTError(msg, 'HOLEPUNCH_PROBE_TIMEOUT', DHTError.HOLEPUNCH_PROBE_TIMEOUT)
  }

  static HOLEPUNCH_DOUBLE_RANDOMIZED_NATS(msg = 'Both remote and local NATs are randomized') {
    return new DHTError(
      msg,
      'HOLEPUNCH_DOUBLE_RANDOMIZED_NATS',
      DHTError.HOLEPUNCH_DOUBLE_RANDOMIZED_NATS
    )
  }

  static CANNOT_HOLEPUNCH(msg = 'Cannot holepunch to remote') {
    return new DHTError(msg, 'CANNOT_HOLEPUNCH', DHTError.CANNOT_HOLEPUNCH)
  }

  static REMOTE_NOT_HOLEPUNCHING(msg = 'Remote is not holepunching') {
    return new DHTError(msg, 'REMOTE_NOT_HOLEPUNCHING', DHTError.REMOTE_NOT_HOLEPUNCHING)
  }

  static REMOTE_NOT_HOLEPUNCHABLE(msg = 'Remote is not holepunchable') {
    return new DHTError(msg, 'REMOTE_NOT_HOLEPUNCHABLE', DHTError.REMOTE_NOT_HOLEPUNCHABLE)
  }

  static REMOTE_ABORTED(msg = 'Remote aborted') {
    return new DHTError(msg, 'REMOTE_ABORTED', DHTError.REMOTE_ABORTED)
  }

  static HANDSHAKE_UNFINISHED(msg = 'Handshake did not finish') {
    return new DHTError(msg, 'HANDSHAKE_UNFINISHED', DHTError.HANDSHAKE_UNFINISHED)
  }

  static HANDSHAKE_INVALID(msg = 'Received invalid handshake') {
    return new DHTError(msg, 'HANDSHAKE_INVALID', DHTError.HANDSHAKE_INVALID)
  }

  static ALREADY_LISTENING(msg = 'Already listening') {
    return new DHTError(msg, 'ALREADY_LISTENING', DHTError.ALREADY_LISTENING)
  }

  static KEYPAIR_ALREADY_USED(msg = 'Keypair already used') {
    return new DHTError(msg, 'KEYPAIR_ALREADY_USED', DHTError.KEYPAIR_ALREADY_USED)
  }

  static NODE_DESTROYED(msg = 'Node destroyed') {
    return new DHTError(msg, 'NODE_DESTROYED', DHTError.NODE_DESTROYED)
  }

  static PEER_CONNECTION_FAILED(msg = 'Could not connect to peer') {
    return new DHTError(msg, 'PEER_CONNECTION_FAILED', DHTError.PEER_CONNECTION_FAILED)
  }

  static PEER_NOT_FOUND(msg = 'Peer not found') {
    return new DHTError(msg, 'PEER_NOT_FOUND', DHTError.PEER_NOT_FOUND)
  }

  static STREAM_NOT_CONNECTED(msg = 'Stream is not connected') {
    return new DHTError(msg, 'STREAM_NOT_CONNECTED', DHTError.STREAM_NOT_CONNECTED)
  }

  static SERVER_INCOMPATIBLE(msg = 'Server is using an incompatible version') {
    return new DHTError(msg, 'SERVER_INCOMPATIBLE', DHTError.SERVER_INCOMPATIBLE)
  }

  static SERVER_ERROR(msg = 'Server returned an error') {
    return new DHTError(msg, 'SERVER_ERROR', DHTError.SERVER_ERROR)
  }

  static DUPLICATE_CONNECTION(msg = 'Duplicate connection') {
    return new DHTError(msg, 'DUPLICATE_CONNECTION', DHTError.DUPLICATE_CONNECTION)
  }

  static RELAY_ABORTED(msg = 'Relay aborted') {
    return new DHTError(msg, 'RELAY_ABORTED', DHTError.RELAY_ABORTED)
  }

  static SUSPENDED(msg = 'Suspended') {
    return new DHTError(msg, 'SUSPENDED', DHTError.SUSPENDED)
  }
}
const b4a = require('b4a')
const Nat = require('./nat')
const Sleeper = require('./sleeper')
const { FIREWALL } = require('./constants')

const BIRTHDAY_SOCKETS = 256
const HOLEPUNCH = b4a.from([0])
const HOLEPUNCH_TTL = 5
const DEFAULT_TTL = 64
const MAX_REOPENS = 3

module.exports = class Holepuncher {
  constructor(dht, session, isInitiator, remoteFirewall = FIREWALL.UNKNOWN) {
    const holder = dht._socketPool.acquire()

    this.dht = dht
    this.session = session

    this.nat = new Nat(dht, session, holder.socket)
    this.nat.autoSample()

    this.isInitiator = isInitiator

    // events
    this.onconnect = noop
    this.onabort = noop

    this.punching = false
    this.connected = false
    this.destroyed = false
    this.randomized = false

    // track remote state
    this.remoteFirewall = remoteFirewall
    this.remoteAddresses = []
    this.remoteHolepunching = false

    this._sleeper = new Sleeper()
    this._reopening = null
    this._timeout = null
    this._punching = null
    this._allHolders = []
    this._holder = this._addRef(holder)
  }

  get socket() {
    return this._holder.socket
  }

  updateRemote({ punching, firewall, addresses, verified }) {
    const remoteAddresses = []

    if (addresses) {
      for (const addr of addresses) {
        remoteAddresses.push({
          host: addr.host,
          port: addr.port,
          verified: verified === addr.host || this._isVerified(addr.host)
        })
      }
    }

    this.remoteFirewall = firewall
    this.remoteAddresses = remoteAddresses
    this.remoteHolepunching = punching
  }

  _isVerified(host) {
    for (const addr of this.remoteAddresses) {
      if (addr.verified && addr.host === host) {
        return true
      }
    }
    return false
  }

  ping(addr, socket = this._holder.socket) {
    return holepunch(socket, addr, false)
  }

  openSession(addr, socket = this._holder.socket) {
    return holepunch(socket, addr, true)
  }

  async analyze(allowReopen) {
    await this.nat.analyzing
    if (this._unstable()) {
      if (!allowReopen) return false
      if (!this._reopening) this._reopening = this._reopen()
      return this._reopening
    }
    return true
  }

  _unstable() {
    // TODO!!: We need an additional heuristic here... If we were NOT random in the past we should also do this.
    const firewall = this.nat.firewall
    return (
      (this.remoteFirewall >= FIREWALL.RANDOM && firewall >= FIREWALL.RANDOM) ||
      firewall === FIREWALL.UNKNOWN
    )
  }

  _reset() {
    const prev = this._holder

    this._allHolders.pop()
    this._holder = this._addRef(this.dht._socketPool.acquire())

    prev.release()
    this.nat.destroy()

    this.nat = new Nat(this.dht, this.session, this._holder.socket)
    // TODO: maybe make auto sampling configurable somehow?
    this.nat.autoSample()
  }

  _addRef(ref) {
    this._allHolders.push(ref)
    ref.onholepunchmessage = (msg, rinfo) => this._onholepunchmessage(msg, rinfo, ref)
    return ref
  }

  _onholepunchmessage(_, addr, ref) {
    if (!this.isInitiator) {
      // TODO: we don't need this if we had a way to connect a socket to many hosts
      holepunch(ref.socket, addr, false) // never fails
      return
    }

    if (this.connected) return

    this.connected = true
    this.punching = false

    for (const r of this._allHolders) {
      if (r === ref) continue
      r.release()
    }

    this._allHolders[0] = ref
    while (this._allHolders.length > 1) this._allHolders.pop()

    this._decrementRandomized()
    this.onconnect(ref.socket, addr.port, addr.host)
  }

  _done() {
    return this.destroyed || this.connected
  }

  async _reopen() {
    for (let i = 0; this._unstable() && i < MAX_REOPENS && !this._done() && !this.punching; i++) {
      this._reset()
      await this.nat.analyzing
    }

    return coerceFirewall(this.nat.firewall) === FIREWALL.CONSISTENT
  }

  punch() {
    if (!this._punching) this._punching = this._punch()
    return this._punching
  }

  async _punch() {
    if (this._done() || !this.remoteAddresses.length) return false

    this.punching = true

    // Coerce into consistency for now. Obvs we could make this this more efficient if we use that info
    // but that's seldomly used since those will just use tcp most of the time.

    const local = coerceFirewall(this.nat.firewall)
    const remote = coerceFirewall(this.remoteFirewall)

    // Note that most of these async functions are meant to run in the background
    // which is why we don't await them here and why they are not allowed to throw

    let remoteVerifiedAddress = null
    for (const addr of this.remoteAddresses) {
      if (addr.verified) {
        remoteVerifiedAddress = addr
        break
      }
    }

    if (local === FIREWALL.CONSISTENT && remote === FIREWALL.CONSISTENT) {
      this.dht.stats.punches.consistent++
      this._consistentProbe()
      return true
    }

    if (!remoteVerifiedAddress) return false

    if (local === FIREWALL.CONSISTENT && remote >= FIREWALL.RANDOM) {
      this.dht.stats.punches.random++
      this._incrementRandomized()
      this._randomProbes(remoteVerifiedAddress)
      return true
    }

    if (local >= FIREWALL.RANDOM && remote === FIREWALL.CONSISTENT) {
      this.dht.stats.punches.random++
      this._incrementRandomized()
      await this._openBirthdaySockets(remoteVerifiedAddress)
      if (this.punching) this._keepAliveRandomNat(remoteVerifiedAddress)
      return true
    }

    return false
  }

  // Note that this never throws so it is safe to run in the background
  async _consistentProbe() {
    // Here we do the sleep first because the "fast open" mode in the server just fired a ping
    if (!this.isInitiator) await this._sleeper.pause(1000)

    let tries = 0

    while (this.punching && tries++ < 10) {
      for (const addr of this.remoteAddresses) {
        // only try unverified addresses every 4 ticks
        if (!addr.verified && (tries & 3) !== 0) continue
        await holepunch(this._holder.socket, addr, false)
      }
      if (this.punching) await this._sleeper.pause(1000)
    }

    this._autoDestroy()
  }

  // Note that this never throws so it is safe to run in the background
  async _randomProbes(remoteAddr) {
    let tries = 1750 // ~35s

    while (this.punching && tries-- > 0) {
      const addr = { host: remoteAddr.host, port: randomPort() }
      await holepunch(this._holder.socket, addr, false)
      if (this.punching) await this._sleeper.pause(20)
    }

    this._autoDestroy()
  }

  // Note that this never throws so it is safe to run in the background
  async _keepAliveRandomNat(remoteAddr) {
    let i = 0
    let lowTTLRounds = 1

    // TODO: experiment with this here. We just bursted all the messages in
    // openOtherSockets to ensure the sockets are open, so it's potentially
    // a good idea to slow down for a bit.
    await this._sleeper.pause(100)

    let tries = 1750 // ~35s

    while (this.punching && tries-- > 0) {
      if (i === this._allHolders.length) {
        i = 0
        if (lowTTLRounds > 0) lowTTLRounds--
      }

      await holepunch(this._allHolders[i++].socket, remoteAddr, lowTTLRounds > 0)
      if (this.punching) await this._sleeper.pause(20)
    }

    this._autoDestroy()
  }

  async _openBirthdaySockets(remoteAddr) {
    while (this.punching && this._allHolders.length < BIRTHDAY_SOCKETS) {
      const ref = this._addRef(this.dht._socketPool.acquire())
      await holepunch(ref.socket, remoteAddr, HOLEPUNCH_TTL)
    }
  }

  _autoDestroy() {
    if (!this.connected) this.destroy()
  }

  _incrementRandomized() {
    if (!this.randomized) {
      this.randomized = true
      this.dht._randomPunches++
    }
  }

  _decrementRandomized() {
    if (this.randomized) {
      this.dht._lastRandomPunch = Date.now()
      this.randomized = false
      this.dht._randomPunches--
    }
  }

  destroy() {
    if (this.destroyed) return
    this.destroyed = true
    this.punching = false

    for (const ref of this._allHolders) ref.release()
    this._allHolders = []
    this.nat.destroy()

    if (!this.connected) {
      this._decrementRandomized()
      this.onabort()
    }
  }

  static ping(socket, addr) {
    return holepunch(socket, addr, false)
  }

  static localAddresses(socket) {
    return localAddresses(socket)
  }

  static matchAddress(myAddresses, externalAddresses) {
    return matchAddress(myAddresses, externalAddresses)
  }
}

function holepunch(socket, addr, lowTTL) {
  return socket.send(HOLEPUNCH, addr.port, addr.host, lowTTL ? HOLEPUNCH_TTL : DEFAULT_TTL)
}

function randomPort() {
  return (1000 + Math.random() * 64536) | 0
}

function coerceFirewall(fw) {
  return fw === FIREWALL.OPEN ? FIREWALL.CONSISTENT : fw
}

function localAddresses(socket) {
  const addrs = []
  const { host, port } = socket.address()

  if (host === '127.0.0.1') return [{ host, port }]

  for (const n of socket.udx.networkInterfaces()) {
    if (n.family !== 4 || n.internal) continue

    addrs.push({ host: n.host, port })
  }

  if (addrs.length === 0) {
    addrs.push({ host: '127.0.0.1', port })
  }

  return addrs
}

function matchAddress(localAddresses, remoteLocalAddresses) {
  if (remoteLocalAddresses.length === 0) return null

  let best = { segment: 1, addr: null }

  for (const localAddress of localAddresses) {
    // => 192.168.122.238
    const a = localAddress.host.split('.')

    for (const remoteAddress of remoteLocalAddresses) {
      // => 192.168.0.23
      // => 192.168.122.1
      const b = remoteAddress.host.split('.')

      // Matches 192.*.*.*
      if (a[0] === b[0]) {
        if (best.segment === 1) best = { segment: 2, addr: remoteAddress }

        // Matches 192.168.*.*
        if (a[1] === b[1]) {
          if (best.segment === 2) best = { segment: 3, addr: remoteAddress }

          // Matches 192.168.122.*
          if (a[2] === b[2]) return remoteAddress
        }
      }
    }
  }

  return best.addr
}

function noop() {}
const c = require('compact-encoding')

const ipv4 = {
  ...c.ipv4Address,
  decode(state) {
    const ip = c.ipv4Address.decode(state)
    return {
      host: ip.host,
      port: ip.port
    }
  }
}

const ipv4Array = c.array(ipv4)

const ipv6 = {
  ...c.ipv6Address,
  decode(state) {
    const ip = c.ipv6Address.decode(state)
    return {
      host: ip.host,
      port: ip.port
    }
  }
}

const ipv6Array = c.array(ipv6)

exports.handshake = {
  preencode(state, m) {
    state.end += 1 + 1 + (m.peerAddress ? 6 : 0) + (m.relayAddress ? 6 : 0)
    c.buffer.preencode(state, m.noise)
  },
  encode(state, m) {
    const flags = (m.peerAddress ? 1 : 0) | (m.relayAddress ? 2 : 0)

    c.uint.encode(state, flags)
    c.uint.encode(state, m.mode)
    c.buffer.encode(state, m.noise)

    if (m.peerAddress) ipv4.encode(state, m.peerAddress)
    if (m.relayAddress) ipv4.encode(state, m.relayAddress)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      mode: c.uint.decode(state),
      noise: c.buffer.decode(state),
      peerAddress: flags & 1 ? ipv4.decode(state) : null,
      relayAddress: flags & 2 ? ipv4.decode(state) : null
    }
  }
}

const relayInfo = {
  preencode(state, m) {
    state.end += 12
  },
  encode(state, m) {
    ipv4.encode(state, m.relayAddress)
    ipv4.encode(state, m.peerAddress)
  },
  decode(state) {
    return {
      relayAddress: ipv4.decode(state),
      peerAddress: ipv4.decode(state)
    }
  }
}

const relayInfoArray = c.array(relayInfo)

const holepunchInfo = {
  preencode(state, m) {
    c.uint.preencode(state, m.id)
    relayInfoArray.preencode(state, m.relays)
  },
  encode(state, m) {
    c.uint.encode(state, m.id)
    relayInfoArray.encode(state, m.relays)
  },
  decode(state) {
    return {
      id: c.uint.decode(state),
      relays: relayInfoArray.decode(state)
    }
  }
}

const udxInfo = {
  preencode(state, m) {
    state.end += 2 // version + features
    c.uint.preencode(state, m.id)
    c.uint.preencode(state, m.seq)
  },
  encode(state, m) {
    c.uint.encode(state, 1)
    c.uint.encode(state, m.reusableSocket ? 1 : 0)
    c.uint.encode(state, m.id)
    c.uint.encode(state, m.seq)
  },
  decode(state) {
    const version = c.uint.decode(state)
    const features = c.uint.decode(state)

    return {
      version,
      reusableSocket: (features & 1) !== 0,
      id: c.uint.decode(state),
      seq: c.uint.decode(state)
    }
  }
}

const secretStreamInfo = {
  preencode(state, m) {
    c.uint.preencode(state, 1)
  },
  encode(state, m) {
    c.uint.encode(state, 1)
  },
  decode(state) {
    return {
      version: c.uint.decode(state)
    }
  }
}

const relayThroughInfo = {
  preencode(state, m) {
    c.uint.preencode(state, 1) // version
    c.uint.preencode(state, 0) // flags
    c.fixed32.preencode(state, m.publicKey)
    c.fixed32.preencode(state, m.token)
  },
  encode(state, m) {
    c.uint.encode(state, 1)
    c.uint.encode(state, 0)
    c.fixed32.encode(state, m.publicKey)
    c.fixed32.encode(state, m.token)
  },
  decode(state) {
    const version = c.uint.decode(state)
    c.uint.decode(state)

    return {
      version,
      publicKey: c.fixed32.decode(state),
      token: c.fixed32.decode(state)
    }
  }
}

exports.noisePayload = {
  preencode(state, m) {
    state.end += 4 // version + flags + error + firewall
    if (m.holepunch) holepunchInfo.preencode(state, m.holepunch)
    if (m.addresses4 && m.addresses4.length) ipv4Array.preencode(state, m.addresses4)
    if (m.addresses6 && m.addresses6.length) ipv6Array.preencode(state, m.addresses6)
    if (m.udx) udxInfo.preencode(state, m.udx)
    if (m.secretStream) secretStreamInfo.preencode(state, m.secretStream)
    if (m.relayThrough) relayThroughInfo.preencode(state, m.relayThrough)
    if (m.relayAddresses) ipv4Array.preencode(state, m.relayAddresses)
  },
  encode(state, m) {
    let flags = 0

    if (m.holepunch) flags |= 1
    if (m.addresses4 && m.addresses4.length) flags |= 2
    if (m.addresses6 && m.addresses6.length) flags |= 4
    if (m.udx) flags |= 8
    if (m.secretStream) flags |= 16
    if (m.relayThrough) flags |= 32
    if (m.relayAddresses) flags |= 64

    c.uint.encode(state, 1) // version
    c.uint.encode(state, flags)
    c.uint.encode(state, m.error)
    c.uint.encode(state, m.firewall)

    if (m.holepunch) holepunchInfo.encode(state, m.holepunch)
    if (m.addresses4 && m.addresses4.length) ipv4Array.encode(state, m.addresses4)
    if (m.addresses6 && m.addresses6.length) ipv6Array.encode(state, m.addresses6)
    if (m.udx) udxInfo.encode(state, m.udx)
    if (m.secretStream) secretStreamInfo.encode(state, m.secretStream)
    if (m.relayThrough) relayThroughInfo.encode(state, m.relayThrough)
    if (m.relayAddresses) ipv4Array.encode(state, m.relayAddresses)
  },
  decode(state) {
    const version = c.uint.decode(state)

    if (version !== 1) {
      // Do not attempt to decode but return this back to the user so they can
      // actually handle it
      return {
        version,
        error: 0,
        firewall: 0,
        holepunch: null,
        addresses4: [],
        addresses6: [],
        udx: null,
        secretStream: null,
        relayThrough: null,
        relayAddresses: null
      }
    }

    const flags = c.uint.decode(state)

    return {
      version,
      error: c.uint.decode(state),
      firewall: c.uint.decode(state),
      holepunch: (flags & 1) !== 0 ? holepunchInfo.decode(state) : null,
      addresses4: (flags & 2) !== 0 ? ipv4Array.decode(state) : [],
      addresses6: (flags & 4) !== 0 ? ipv6Array.decode(state) : [],
      udx: (flags & 8) !== 0 ? udxInfo.decode(state) : null,
      secretStream: (flags & 16) !== 0 ? secretStreamInfo.decode(state) : null,
      relayThrough: (flags & 32) !== 0 ? relayThroughInfo.decode(state) : null,
      relayAddresses: (flags & 64) !== 0 ? ipv4Array.decode(state) : null
    }
  }
}

exports.holepunch = {
  preencode(state, m) {
    state.end += 2
    c.uint.preencode(state, m.id)
    c.buffer.preencode(state, m.payload)
    if (m.peerAddress) ipv4.preencode(state, m.peerAddress)
  },
  encode(state, m) {
    const flags = m.peerAddress ? 1 : 0
    c.uint.encode(state, flags)
    c.uint.encode(state, m.mode)
    c.uint.encode(state, m.id)
    c.buffer.encode(state, m.payload)
    if (m.peerAddress) ipv4.encode(state, m.peerAddress)
  },
  decode(state) {
    const flags = c.uint.decode(state)
    return {
      mode: c.uint.decode(state),
      id: c.uint.decode(state),
      payload: c.buffer.decode(state),
      peerAddress: flags & 1 ? ipv4.decode(state) : null
    }
  }
}

exports.holepunchPayload = {
  preencode(state, m) {
    state.end += 4 // flags + error + firewall + round
    if (m.addresses) ipv4Array.preencode(state, m.addresses)
    if (m.remoteAddress) state.end += 6
    if (m.token) state.end += 32
    if (m.remoteToken) state.end += 32
  },
  encode(state, m) {
    const flags =
      (m.connected ? 1 : 0) |
      (m.punching ? 2 : 0) |
      (m.addresses ? 4 : 0) |
      (m.remoteAddress ? 8 : 0) |
      (m.token ? 16 : 0) |
      (m.remoteToken ? 32 : 0)

    c.uint.encode(state, flags)
    c.uint.encode(state, m.error)
    c.uint.encode(state, m.firewall)
    c.uint.encode(state, m.round)

    if (m.addresses) ipv4Array.encode(state, m.addresses)
    if (m.remoteAddress) ipv4.encode(state, m.remoteAddress)
    if (m.token) c.fixed32.encode(state, m.token)
    if (m.remoteToken) c.fixed32.encode(state, m.remoteToken)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      error: c.uint.decode(state),
      firewall: c.uint.decode(state),
      round: c.uint.decode(state),
      connected: (flags & 1) !== 0,
      punching: (flags & 2) !== 0,
      addresses: (flags & 4) !== 0 ? ipv4Array.decode(state) : null,
      remoteAddress: (flags & 8) !== 0 ? ipv4.decode(state) : null,
      token: (flags & 16) !== 0 ? c.fixed32.decode(state) : null,
      remoteToken: (flags & 32) !== 0 ? c.fixed32.decode(state) : null
    }
  }
}

const peer = (exports.peer = {
  preencode(state, m) {
    state.end += 32
    ipv4Array.preencode(state, m.relayAddresses)
  },
  encode(state, m) {
    c.fixed32.encode(state, m.publicKey)
    ipv4Array.encode(state, m.relayAddresses)
  },
  decode(state) {
    return {
      publicKey: c.fixed32.decode(state),
      relayAddresses: ipv4Array.decode(state)
    }
  }
})

const peers = (exports.peers = c.array(peer))

const rawPeers = c.array(c.raw)

exports.lookupRawReply = {
  preencode(state, m) {
    rawPeers.preencode(state, m.peers)
    c.uint.preencode(state, m.bump)
  },
  encode(state, m) {
    rawPeers.encode(state, m.peers)
    c.uint.encode(state, m.bump)
  },
  decode(state) {
    return {
      peers: peers.decode(state),
      bump: state.start < state.end ? c.uint.decode(state) : 0
    }
  }
}

exports.announce = {
  preencode(state, m) {
    state.end++ // flags
    if (m.peer) peer.preencode(state, m.peer)
    if (m.refresh) state.end += 32
    if (m.signature) state.end += 64
    if (m.bump) c.uint.preencode(state, m.bump)
  },
  encode(state, m) {
    const flags = (m.peer ? 1 : 0) | (m.refresh ? 2 : 0) | (m.signature ? 4 : 0) | (m.bump ? 8 : 0)
    c.uint.encode(state, flags)
    if (m.peer) peer.encode(state, m.peer)
    if (m.refresh) c.fixed32.encode(state, m.refresh)
    if (m.signature) c.fixed64.encode(state, m.signature)
    if (m.bump) c.uint.encode(state, m.bump)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      peer: (flags & 1) !== 0 ? peer.decode(state) : null,
      refresh: (flags & 2) !== 0 ? c.fixed32.decode(state) : null,
      signature: (flags & 4) !== 0 ? c.fixed64.decode(state) : null,
      bump: (flags & 8) !== 0 ? c.uint.decode(state) : 0
    }
  }
}

exports.mutableSignable = {
  preencode(state, m) {
    c.uint.preencode(state, m.seq)
    c.buffer.preencode(state, m.value)
  },
  encode(state, m) {
    c.uint.encode(state, m.seq)
    c.buffer.encode(state, m.value)
  },
  decode(state) {
    return {
      seq: c.uint.decode(state),
      value: c.buffer.decode(state)
    }
  }
}

exports.mutablePutRequest = {
  preencode(state, m) {
    c.fixed32.preencode(state, m.publicKey)
    c.uint.preencode(state, m.seq)
    c.buffer.preencode(state, m.value)
    c.fixed64.preencode(state, m.signature)
  },
  encode(state, m) {
    c.fixed32.encode(state, m.publicKey)
    c.uint.encode(state, m.seq)
    c.buffer.encode(state, m.value)
    c.fixed64.encode(state, m.signature)
  },
  decode(state) {
    return {
      publicKey: c.fixed32.decode(state),
      seq: c.uint.decode(state),
      value: c.buffer.decode(state),
      signature: c.fixed64.decode(state)
    }
  }
}

exports.mutableGetResponse = {
  preencode(state, m) {
    c.uint.preencode(state, m.seq)
    c.buffer.preencode(state, m.value)
    c.fixed64.preencode(state, m.signature)
  },
  encode(state, m) {
    c.uint.encode(state, m.seq)
    c.buffer.encode(state, m.value)
    c.fixed64.encode(state, m.signature)
  },
  decode(state) {
    return {
      seq: c.uint.decode(state),
      value: c.buffer.decode(state),
      signature: c.fixed64.decode(state)
    }
  }
}

exports.pluginRequest = {
  preencode(state, m) {
    c.string.preencode(state, m.plugin)
    c.uint.preencode(state, m.version)
    c.uint.preencode(state, m.command)
    state.end++ // max flag is 1 so always one byte

    if (m.value) c.buffer.preencode(state, m.value)
  },
  encode(state, m) {
    const flags = m.value ? 1 : 0

    c.string.encode(state, m.plugin)
    c.uint.encode(state, m.version)
    c.uint.encode(state, m.command)
    c.uint.encode(state, flags)

    if (m.value) c.buffer.encode(state, m.value)
  },
  decode(state) {
    const r0 = c.string.decode(state)
    const r1 = c.uint.decode(state)
    const r2 = c.uint.decode(state)
    const flags = c.uint.decode(state)

    return {
      plugin: r0,
      version: r1,
      command: r2,
      value: (flags & 1) !== 0 ? c.buffer.decode(state) : null
    }
  }
}
const { FIREWALL } = require('../lib/constants')

module.exports = class Nat {
  constructor(dht, session, socket) {
    this._samplesHost = []
    this._samplesFull = []
    this._visited = new Map()
    this._resolve = null
    this._minSamples = 4
    this._autoSampling = false

    this.dht = dht
    this.session = session
    this.socket = socket

    this.sampled = 0
    this.firewall = dht.firewalled ? FIREWALL.UNKNOWN : FIREWALL.OPEN
    this.addresses = null

    this.analyzing = new Promise((resolve) => {
      this._resolve = resolve
    })
  }

  autoSample(retry = true) {
    if (this._autoSampling) return
    this._autoSampling = true

    const self = this
    const socket = this.socket
    const maxPings = this._minSamples

    let skip = this.dht.nodes.length >= 8 ? 5 : 0
    let pending = 0

    // TODO: it would be best to pick the nodes to help us based on latency to us
    // That should reduce connect latency in general. We should investigate tracking that later on.

    // TODO 2: try to pick nodes with different IPs as well, as that'll help multi IP cell connections...
    // If we expose this from the nat sampler then the DHT should be able to help us filter out scams as well...

    for (
      let node = this.dht.nodes.latest;
      node && this.sampled + pending < maxPings;
      node = node.prev
    ) {
      if (skip > 0) {
        skip--
        continue
      }

      const ref = node.host + ':' + node.port

      if (this._visited.has(ref)) continue
      this._visited.set(ref, 1)

      pending++
      this.session.ping(node, { socket, retry: false }).then(onpong, onskip)
    }

    pending++
    onskip()

    function onpong(res) {
      self.add(res.to, res.from)
      onskip()
    }

    function onskip() {
      if (--pending === 0 && self.sampled < self._minSamples) {
        if (retry) {
          self._autoSampling = false
          self.autoSample(false)
          return
        }
        self._resolve()
      }
    }
  }

  destroy() {
    this._autoSampling = true
    this._minSamples = 0
    this._resolve()
  }

  unfreeze() {
    this.frozen = false
    this._updateFirewall()
    this._updateAddresses()
  }

  freeze() {
    this.frozen = true
  }

  _updateFirewall() {
    if (!this.dht.firewalled) {
      this.firewall = FIREWALL.OPEN
      return
    }

    if (this.sampled < 3) return

    const max = this._samplesFull[0].hits

    if (max >= 3) {
      this.firewall = FIREWALL.CONSISTENT
      return
    }

    if (max === 1) {
      this.firewall = FIREWALL.RANDOM
      return
    }

    // else max === 2

    // 1 host, >= 4 total samples ie, 2 bad ones -> random
    if (this._samplesHost.length === 1 && this.sampled > 3) {
      this.firewall = FIREWALL.RANDOM
      return
    }

    // double hit on two different ips -> assume consistent
    if (this._samplesHost.length > 1 && this._samplesFull[1].hits > 1) {
      this.firewall = FIREWALL.CONSISTENT
      return
    }

    // (4 is just means - all the samples we expect) - no decision - assume random
    if (this.sampled > 4) {
      this.firewall = FIREWALL.RANDOM
    }
  }

  _updateAddresses() {
    if (this.firewall === FIREWALL.UNKNOWN) {
      this.addresses = null
      return
    }

    if (this.firewall === FIREWALL.RANDOM) {
      this.addresses = [this._samplesHost[0]]
      return
    }

    if (this.firewall === FIREWALL.CONSISTENT) {
      this.addresses = []
      for (const addr of this._samplesFull) {
        if (addr.hits >= 2 || this.addresses.length < 2) this.addresses.push(addr)
      }
    }
  }

  update() {
    if (this.dht.firewalled && this.firewall === FIREWALL.OPEN) {
      this.firewall = FIREWALL.UNKNOWN
    }
    this._updateFirewall()
    this._updateAddresses()
  }

  add(addr, from) {
    const ref = from.host + ':' + from.port

    if (this._visited.get(ref) === 2) return
    this._visited.set(ref, 2)

    addSample(this._samplesHost, addr.host, 0)
    addSample(this._samplesFull, addr.host, addr.port)

    if ((++this.sampled >= 3 || !this.dht.firewalled) && !this.frozen) {
      this.update()
    }

    if (this.firewall === FIREWALL.CONSISTENT || this.firewall === FIREWALL.OPEN) {
      this._resolve()
    } else if (this.sampled >= this._minSamples) {
      this._resolve()
    }
  }
}

function addSample(samples, host, port) {
  for (let i = 0; i < samples.length; i++) {
    const s = samples[i]

    if (s.port !== port || s.host !== host) continue
    s.hits++

    for (; i > 0; i--) {
      const prev = samples[i - 1]
      if (prev.hits >= s.hits) return
      samples[i - 1] = s
      samples[i] = prev
    }

    return
  }

  samples.push({
    host,
    port,
    hits: 1
  })
}
const NoiseSecretStream = require('@hyperswarm/secret-stream')
const NoiseHandshake = require('noise-handshake')
const curve = require('noise-curve-ed')
const c = require('compact-encoding')
const b4a = require('b4a')
const sodium = require('sodium-universal')
const m = require('./messages')
const { NS } = require('./constants')
const { HANDSHAKE_UNFINISHED } = require('./errors')

const NOISE_PROLOUGE = NS.PEER_HANDSHAKE

module.exports = class NoiseWrap {
  constructor(keyPair, remotePublicKey) {
    this.isInitiator = !!remotePublicKey
    this.remotePublicKey = remotePublicKey
    this.keyPair = keyPair
    this.handshake = new NoiseHandshake('IK', this.isInitiator, keyPair, { curve })
    this.handshake.initialise(NOISE_PROLOUGE, remotePublicKey)
  }

  send(payload) {
    const buf = c.encode(m.noisePayload, payload)
    return this.handshake.send(buf)
  }

  recv(buf) {
    const payload = c.decode(m.noisePayload, this.handshake.recv(buf))
    this.remotePublicKey = b4a.toBuffer(this.handshake.rs)
    return payload
  }

  final() {
    if (!this.handshake.complete) throw HANDSHAKE_UNFINISHED()

    const holepunchSecret = b4a.allocUnsafe(32)

    sodium.crypto_generichash(holepunchSecret, NS.PEER_HOLEPUNCH, this.handshake.hash)

    return {
      isInitiator: this.isInitiator,
      publicKey: this.keyPair.publicKey,
      streamId: this.streamId,
      remotePublicKey: this.remotePublicKey,
      remoteId: NoiseSecretStream.id(this.handshake.hash, !this.isInitiator),
      holepunchSecret,
      hash: b4a.toBuffer(this.handshake.hash),
      rx: b4a.toBuffer(this.handshake.rx),
      tx: b4a.toBuffer(this.handshake.tx)
    }
  }
}
const c = require('compact-encoding')
const sodium = require('sodium-universal')
const RecordCache = require('record-cache')
const Cache = require('xache')
const b4a = require('b4a')
const unslab = require('unslab')

const { encodeUnslab } = require('./encode')
const m = require('./messages')
const { NS, ERROR } = require('./constants')

const EMPTY = b4a.alloc(0)
const TMP = b4a.allocUnsafe(32)
const MAX_BUMP_DRIFT = 60_000

module.exports = class Persistent {
  constructor(dht, opts) {
    this.dht = dht
    this.records = new RecordCache(opts.records)
    this.bumps = new Cache(opts.bumps)
    this.refreshes = new Cache(opts.refreshes)
    this.mutables = new Cache(opts.mutables)
    this.immutables = new Cache(opts.immutables)
  }

  onlookup(req) {
    if (!req.target) return

    const k = b4a.toString(req.target, 'hex')
    const records = this.records.get(k, 20)
    const bump = this.bumps.get(k) || 0
    const fwd = this.dht._router.get(k)

    if (fwd && records.length < 20) records.push(fwd.record)

    req.reply(records.length ? c.encode(m.lookupRawReply, { peers: records, bump }) : null)
  }

  onfindpeer(req) {
    if (!req.target) return
    const fwd = this.dht._router.get(req.target)
    req.reply(fwd ? fwd.record : null)
  }

  unannounce(target, publicKey) {
    const k = b4a.toString(target, 'hex')
    sodium.crypto_generichash(TMP, publicKey)

    if (b4a.equals(TMP, target)) this.dht._router.delete(k)
    this.records.remove(k, publicKey)
  }

  onunannounce(req) {
    if (!req.target || !req.token) return

    const unann = decode(m.announce, req.value)
    if (unann === null) return

    const { peer, signature } = unann
    if (!peer || !signature) return

    const signable = annSignable(req.target, req.token, this.dht.id, unann, NS.UNANNOUNCE)

    if (!sodium.crypto_sign_verify_detached(signature, signable, peer.publicKey)) {
      return
    }

    this.unannounce(req.target, peer.publicKey)
    req.reply(null, { token: false, closerNodes: false })
  }

  _onrefresh(token, req) {
    sodium.crypto_generichash(TMP, token)
    const activeRefresh = b4a.toString(TMP, 'hex')

    const r = this.refreshes.get(activeRefresh)
    if (!r) return

    const { announceSelf, k, record } = r
    const publicKey = record.subarray(0, 32)

    if (announceSelf) {
      this.dht._router.set(k, {
        relay: req.from,
        record,
        onconnect: null,
        onholepunch: null
      })
      this.records.remove(k, publicKey)
    } else {
      this.records.add(k, publicKey, record)
    }

    this.refreshes.delete(activeRefresh)
    this.refreshes.set(b4a.toString(token, 'hex'), r)

    req.reply(null, { token: false, closerNodes: false })
  }

  onannounce(req) {
    if (!req.target || !req.token || !this.dht.id) return

    const ann = decode(m.announce, req.value)
    if (ann === null) return

    const { peer, refresh, signature, bump } = ann

    if (!peer) {
      if (!refresh) return
      this._onrefresh(refresh, req)
      return
    }

    const signable = annSignable(req.target, req.token, this.dht.id, ann, NS.ANNOUNCE)

    if (!signature || !sodium.crypto_sign_verify_detached(signature, signable, peer.publicKey)) {
      return
    }

    // TODO: it would be potentially be more optimal to allow more than 3 addresses here for a findPeer response
    // and only use max 3 for a lookup reply
    if (peer.relayAddresses.length > 3) {
      peer.relayAddresses = peer.relayAddresses.slice(0, 3)
    }

    sodium.crypto_generichash(TMP, peer.publicKey)

    const k = b4a.toString(req.target, 'hex')
    const announceSelf = b4a.equals(TMP, req.target)
    const record = encodeUnslab(m.peer, peer)

    if (announceSelf) {
      this.dht._router.set(k, {
        relay: req.from,
        record,
        onconnect: null,
        onholepunch: null
      })
      this.records.remove(k, peer.publicKey)
    } else {
      const currentBump = this.bumps.get(k) || 0
      if (bump > currentBump && bump <= Date.now() + MAX_BUMP_DRIFT) this.bumps.set(k, bump)
      this.records.add(k, peer.publicKey, record)
    }

    if (refresh) {
      this.refreshes.set(b4a.toString(refresh, 'hex'), { k, record, announceSelf })
    }

    req.reply(null, { token: false, closerNodes: false })
  }

  onmutableget(req) {
    if (!req.target || !req.value) return

    let seq = 0
    try {
      seq = c.decode(c.uint, req.value)
    } catch {
      return
    }

    const k = b4a.toString(req.target, 'hex')
    const value = this.mutables.get(k)

    if (!value) {
      req.reply(null)
      return
    }

    const localSeq = c.decode(c.uint, value)
    req.reply(localSeq < seq ? null : value)
  }

  onmutableput(req) {
    if (!req.target || !req.token || !req.value) return

    const p = decode(m.mutablePutRequest, req.value)
    if (!p) return

    const { publicKey, seq, value, signature } = p

    const hash = b4a.allocUnsafe(32)
    sodium.crypto_generichash(hash, publicKey)
    if (!b4a.equals(hash, req.target)) return

    if (!value || !verifyMutable(signature, seq, value, publicKey)) return

    const k = b4a.toString(hash, 'hex')
    const local = this.mutables.get(k)

    if (local) {
      const existing = c.decode(m.mutableGetResponse, local)
      if (existing.value && existing.seq === seq && b4a.compare(value, existing.value) !== 0) {
        req.error(ERROR.SEQ_REUSED)
        return
      }
      if (seq < existing.seq) {
        req.error(ERROR.SEQ_TOO_LOW)
        return
      }
    }

    this.mutables.set(k, encodeUnslab(m.mutableGetResponse, { seq, value, signature }))
    req.reply(null)
  }

  onimmutableget(req) {
    if (!req.target) return

    const k = b4a.toString(req.target, 'hex')
    const value = this.immutables.get(k)

    req.reply(value || null)
  }

  onimmutableput(req) {
    if (!req.target || !req.token || !req.value) return

    const hash = b4a.alloc(32)
    sodium.crypto_generichash(hash, req.value)
    if (!b4a.equals(hash, req.target)) return

    const k = b4a.toString(hash, 'hex')
    this.immutables.set(k, unslab(req.value))

    req.reply(null)
  }

  onplugin(req) {
    if (!req.value) return

    const plugreq = decode(m.pluginRequest, req.value)
    if (plugreq === null) return

    const p = this.dht.plugins.get(plugreq.plugin)
    if (!p || p.version !== plugreq.version) return

    p.onrequest(plugreq, req)
  }

  destroy() {
    this.records.destroy()
    this.refreshes.destroy()
    this.mutables.destroy()
    this.immutables.destroy()
  }

  static signMutable(seq, value, keyPair) {
    const signable = b4a.allocUnsafe(32 + 32)
    const hash = signable.subarray(32)

    signable.set(NS.MUTABLE_PUT, 0)

    sodium.crypto_generichash(hash, c.encode(m.mutableSignable, { seq, value }))
    return sign(signable, keyPair)
  }

  static verifyMutable(signature, seq, value, publicKey) {
    return verifyMutable(signature, seq, value, publicKey)
  }

  static signAnnounce(target, token, id, ann, keyPair) {
    return sign(annSignable(target, token, id, ann, NS.ANNOUNCE), keyPair)
  }

  static signUnannounce(target, token, id, ann, keyPair) {
    return sign(annSignable(target, token, id, ann, NS.UNANNOUNCE), keyPair)
  }
}

function verifyMutable(signature, seq, value, publicKey) {
  const signable = b4a.allocUnsafe(32 + 32)
  const hash = signable.subarray(32)

  signable.set(NS.MUTABLE_PUT, 0)

  sodium.crypto_generichash(hash, c.encode(m.mutableSignable, { seq, value }))
  return sodium.crypto_sign_verify_detached(signature, signable, publicKey)
}

function annSignable(target, token, id, ann, ns) {
  const signable = b4a.allocUnsafe(32 + 32)
  const hash = signable.subarray(32)

  signable.set(ns, 0)

  sodium.crypto_generichash_batch(hash, [
    target,
    id,
    token,
    c.encode(m.peer, ann.peer), // note that this is the partial encoding of the announce message so we could just use that for perf
    ann.refresh || EMPTY
  ])

  return signable
}

function sign(signable, keyPair) {
  if (keyPair.sign) {
    return keyPair.sign(signable)
  }
  const secretKey = keyPair.secretKey ? keyPair.secretKey : keyPair
  const signature = b4a.allocUnsafe(64)
  sodium.crypto_sign_detached(signature, signable, secretKey)
  return signature
}

function decode(enc, val) {
  try {
    return val && c.decode(enc, val)
  } catch (err) {
    return null
  }
}
module.exports = class RawStreamSet {
  constructor(dht) {
    this._dht = dht

    this._prefix = 16 - 1 // 16 is the default stream-set side in udx
    this._streams = new Map()
  }

  get size() {
    return this._streams.size
  }

  [Symbol.iterator]() {
    return this._streams.values()
  }

  add(opts) {
    const self = this

    // TODO: we should prob have a udx helper for id generation, given the slight complexity
    // of the below. requires a PRNG in udx tho.

    let id = 0

    while (true) {
      id = (Math.random() * 0x100000000) >>> 0

      if (this._streams.has(id & this._prefix)) continue
      break
    }

    // always have ~50% change of rolling a free one
    if (2 * this._streams.size >= this._prefix) {
      // ie 0b11111 = 0b1111 + 1 + 0b1111
      this._prefix = 2 * this._prefix + 1

      // move the prefixes over
      const next = new Map()
      for (const stream of this._streams.values()) {
        next.set(stream.id & this._prefix, stream)
      }
      this._streams = next
    }

    const stream = this._dht.udx.createStream(id, opts)
    this._streams.set(id & this._prefix, stream)

    stream.on('close', onclose)

    return stream

    function onclose() {
      self._streams.delete(id & self._prefix)
    }
  }

  async clear() {
    const destroying = []

    for (const stream of this._streams.values()) {
      destroying.push(new Promise((resolve) => stream.once('close', resolve).destroy()))
    }

    await Promise.allSettled(destroying)
  }
}
const b4a = require('b4a')
const safetyCatch = require('safety-catch')

exports.clearRelayTimeout = clearRelayTimeout
exports.closeRelayConnection = closeRelayConnection
exports.confirmDirectUpgrade = confirmDirectUpgrade
exports.destroyRelayConnection = destroyRelayConnection

function clearRelayTimeout(connectionOrHandshake) {
  clearTimeout(connectionOrHandshake.relayTimeout)
  connectionOrHandshake.relayTimeout = null
}

function closeRelayConnection(connectionOrHandshake) {
  const socket = resetRelayConnection(connectionOrHandshake)

  if (socket) socket.end()
}

function confirmDirectUpgrade(connectionOrHandshake, rawStream, remoteChanging) {
  const cleanup = () => {
    rawStream.off('data', ondirect)
    rawStream.off('message', ondirect)
    rawStream.off('close', cleanup)
  }

  function ondirect() {
    if (!connectionOrHandshake.validUpgrade) {
      // reset, aka assume from direct
      connectionOrHandshake.validUpgrade = true
      return
    }

    cleanup()
    closeRelayConnection(connectionOrHandshake)
  }

  const confirm = () => {
    rawStream.on('data', ondirect)
    rawStream.on('message', ondirect)
    rawStream.once('close', cleanup)

    // Use a raw UDX message to make the peer observe the direct path without
    // writing application data into the secret stream.
    if (rawStream.trySend) rawStream.trySend(b4a.alloc(0))
  }

  if (!remoteChanging) {
    confirm()
    return
  }

  remoteChanging.then(confirm).catch(safetyCatch)
}

function destroyRelayConnection(connectionOrHandshake) {
  const socket = resetRelayConnection(connectionOrHandshake)

  if (socket) socket.destroy()
}

function resetRelayConnection(connectionOrHandshake) {
  if (connectionOrHandshake.relayTimeout) clearRelayTimeout(connectionOrHandshake)

  const socket = connectionOrHandshake.relaySocket
  // Drop relay references so the app connection no longer keeps relay state alive.
  connectionOrHandshake.relayToken = null
  connectionOrHandshake.relaySocket = null
  connectionOrHandshake.relayClient = null

  return socket
}
const c = require('compact-encoding')
const Cache = require('xache')
const safetyCatch = require('safety-catch')
const b4a = require('b4a')
const { handshake, holepunch } = require('./messages')
const { COMMANDS } = require('./constants')
const { BAD_HANDSHAKE_REPLY, BAD_HOLEPUNCH_REPLY } = require('./errors')

const FROM_CLIENT = 0
const FROM_SERVER = 1
const FROM_RELAY = 2
const FROM_SECOND_RELAY = 3
const REPLY = 4

// TODO: While the current design is very trustless in regards to clients/servers trusting the DHT,
// we should add a bunch of rate limits everywhere, especially including here to avoid bad users
// using a DHT node to relay traffic indiscriminately using the connect/holepunch messages.
// That's mostly from an abuse POV as none of the messsages do amplication.

module.exports = class Router {
  constructor(dht, opts) {
    this.dht = dht
    this.forwards = new Cache(opts.forwards)
  }

  set(target, state) {
    if (state.onpeerhandshake) {
      this.forwards.retain(toString(target), state)
    } else {
      this.forwards.set(toString(target), state)
    }
  }

  get(target) {
    return this.forwards.get(toString(target))
  }

  delete(target) {
    this.forwards.delete(toString(target))
  }

  destroy() {
    this.forwards.destroy()
  }

  async peerHandshake(target, { noise, peerAddress, relayAddress, socket, session }, to) {
    const dht = this.dht

    const requestValue = c.encode(handshake, {
      mode: FROM_CLIENT,
      noise,
      peerAddress,
      relayAddress
    })

    const res = await dht.request(
      { command: COMMANDS.PEER_HANDSHAKE, target, value: requestValue },
      to,
      { socket, session }
    )

    const hs = decode(handshake, res.value)
    if (
      !hs ||
      hs.mode !== REPLY ||
      to.host !== res.from.host ||
      to.port !== res.from.port ||
      !hs.noise
    ) {
      throw BAD_HANDSHAKE_REPLY()
    }

    return {
      noise: hs.noise,
      relayed: !!hs.peerAddress,
      serverAddress: hs.peerAddress || to,
      clientAddress: res.to
    }
  }

  async onpeerhandshake(req) {
    const hs = req.value && decode(handshake, req.value)
    if (!hs) return

    const { mode, noise, peerAddress, relayAddress } = hs

    const state = req.target && this.get(req.target)
    const isServer = !!(state && state.onpeerhandshake)
    const relay = state && state.relay

    if (isServer) {
      let reply = null
      try {
        reply = noise && (await state.onpeerhandshake({ noise, peerAddress }, req))
      } catch (e) {
        safetyCatch(e)
        return
      }
      if (!reply || !reply.noise) return
      const opts = { socket: reply.socket, closerNodes: false, token: false }

      switch (mode) {
        case FROM_CLIENT: {
          req.reply(
            c.encode(handshake, { mode: REPLY, noise: reply.noise, peerAddress: null }),
            opts
          )
          return
        }
        case FROM_RELAY: {
          req.relay(
            c.encode(handshake, { mode: FROM_SERVER, noise: reply.noise, peerAddress }),
            req.from,
            opts
          )
          return
        }
        case FROM_SECOND_RELAY: {
          if (!relayAddress) return
          req.relay(
            c.encode(handshake, { mode: FROM_SERVER, noise: reply.noise, peerAddress }),
            relayAddress,
            opts
          )
          return // eslint-disable-line
        }
      }
    } else {
      switch (mode) {
        case FROM_CLIENT: {
          // TODO: if no relay is known route closer to the target instead of timing out
          if (!noise) return
          if (!relay && !relayAddress) {
            // help the user route
            req.reply(null, { token: false, closerNodes: true })
            return
          }
          req.relay(
            c.encode(handshake, {
              mode: FROM_RELAY,
              noise,
              peerAddress: req.from,
              relayAddress: null
            }),
            relayAddress || relay
          )
          return
        }
        case FROM_RELAY: {
          if (!relay || !noise) return
          req.relay(
            c.encode(handshake, {
              mode: FROM_SECOND_RELAY,
              noise,
              peerAddress,
              relayAddress: req.from
            }),
            relay
          )
          return
        }
        case FROM_SERVER: {
          if (!peerAddress || !noise) return
          req.reply(
            c.encode(handshake, { mode: REPLY, noise, peerAddress: req.from, relayAddress: null }),
            { to: peerAddress, closerNodes: false, token: false }
          )
          return // eslint-disable-line
        }
      }
    }
  }

  async peerHolepunch(target, { id, payload, peerAddress, socket, session }, to) {
    const dht = this.dht
    const requestValue = c.encode(holepunch, {
      mode: FROM_CLIENT,
      id,
      payload,
      peerAddress
    })

    const res = await dht.request(
      { command: COMMANDS.PEER_HOLEPUNCH, target, value: requestValue },
      to,
      { socket, session }
    )

    const hp = decode(holepunch, res.value)
    if (!hp || hp.mode !== REPLY || to.host !== res.from.host || to.port !== res.from.port) {
      throw BAD_HOLEPUNCH_REPLY()
    }

    return {
      from: res.from,
      to: res.to,
      payload: hp.payload,
      peerAddress: hp.peerAddress || to
    }
  }

  async onpeerholepunch(req) {
    const hp = req.value && decode(holepunch, req.value)
    if (!hp) return

    const { mode, id, payload, peerAddress } = hp

    const state = req.target && this.get(req.target)
    const isServer = !!(state && state.onpeerholepunch)
    const relay = state && state.relay

    switch (mode) {
      case FROM_CLIENT: {
        if (!peerAddress && !relay) return
        req.relay(
          c.encode(holepunch, { mode: FROM_RELAY, id, payload, peerAddress: req.from }),
          peerAddress || relay
        )
        return
      }
      case FROM_RELAY: {
        if (!isServer || !peerAddress) return
        let reply = null
        try {
          reply = await state.onpeerholepunch({ id, payload, peerAddress }, req)
        } catch (e) {
          safetyCatch(e)
          return
        }
        if (!reply) return
        const opts = { socket: reply.socket, closerNodes: false, token: false }
        req.relay(
          c.encode(holepunch, { mode: FROM_SERVER, id: 0, payload: reply.payload, peerAddress }),
          req.from,
          opts
        )
        return
      }
      case FROM_SERVER: {
        req.reply(c.encode(holepunch, { mode: REPLY, id, payload, peerAddress: req.from }), {
          to: peerAddress,
          closerNodes: false,
          token: false
        })
        return // eslint-disable-line
      }
    }
  }
}

function decode(enc, val) {
  try {
    return c.decode(enc, val)
  } catch {
    return null
  }
}

function toString(t) {
  return typeof t === 'string' ? t : b4a.toString(t, 'hex')
}
const sodium = require('sodium-universal')
const b4a = require('b4a')
const { holepunchPayload } = require('./messages')

module.exports = class HolepunchPayload {
  constructor(holepunchSecret) {
    this._sharedSecret = holepunchSecret
    this._localSecret = b4a.allocUnsafe(32)

    sodium.randombytes_buf(this._localSecret)
  }

  decrypt(buffer) {
    const state = { start: 24, end: buffer.byteLength - 16, buffer }

    if (state.end <= state.start) return null

    const nonce = buffer.subarray(0, 24)
    const msg = state.buffer.subarray(state.start, state.end)
    const cipher = state.buffer.subarray(state.start)

    if (!sodium.crypto_secretbox_open_easy(msg, cipher, nonce, this._sharedSecret)) return null

    try {
      return holepunchPayload.decode(state)
    } catch {
      return null
    }
  }

  encrypt(payload) {
    const state = { start: 24, end: 24, buffer: null }
    holepunchPayload.preencode(state, payload)
    state.buffer = b4a.allocUnsafe(state.end + 16)

    const nonce = state.buffer.subarray(0, 24)
    const msg = state.buffer.subarray(state.start, state.end)
    const cipher = state.buffer.subarray(state.start)

    holepunchPayload.encode(state, payload)
    sodium.randombytes_buf(nonce)
    sodium.crypto_secretbox_easy(cipher, msg, nonce, this._sharedSecret)

    return state.buffer
  }

  token(addr) {
    const out = b4a.allocUnsafe(32)
    sodium.crypto_generichash(out, b4a.from(addr.host), this._localSecret)
    return out
  }
}
const DONE = Promise.resolve(true)
const DESTROYED = Promise.resolve(false)

module.exports = class Semaphore {
  constructor(limit = 1) {
    this.limit = limit
    this.active = 0
    this.waiting = []

    this.flushedPromise = null
    this.flushedResolve = null

    this.destroyed = false

    this._onwait = this._queueWaiting.bind(this)
    this._onflush = this._queueFlushed.bind(this)
  }

  _queueWaiting(resolve) {
    this.waiting.push(resolve)
  }

  _queueFlushed(resolve) {
    this.flushedResolve = resolve
  }

  wait() {
    if (this.destroyed === true) return DESTROYED

    if (this.active < this.limit && this.waiting.length === 0) {
      this.active++
      return DONE
    }

    return new Promise(this._onwait)
  }

  signal() {
    if (this.destroyed === true) return

    this.active--
    while (this.active < this.limit && this.waiting.length > 0 && this.destroyed === false) {
      this.active++
      this.waiting.shift()(true)
    }

    if (this.active === 0 && this.flushedResolve) {
      const resolve = this.flushedResolve
      this.flushedResolve = null
      this.flushedPromise = null
      resolve(true)
    }
  }

  async flush() {
    if (this.destroyed === true) return
    if (this.active === 0) return
    if (this.flushedPromise) return this.flushedPromise
    this.flushedPromise = new Promise(this._onflush)
    return this.flushedPromise
  }

  destroy() {
    this.destroyed = true
    this.active = 0
    while (this.waiting.length) this.waiting.pop()(false)
    if (this.flushedResolve) this.flushedResolve(false)
  }
}
const { EventEmitter } = require('events')
const safetyCatch = require('safety-catch')
const NoiseSecretStream = require('@hyperswarm/secret-stream')
const b4a = require('b4a')
const relay = require('blind-relay')
const NoiseWrap = require('./noise-wrap')
const Announcer = require('./announcer')
const { FIREWALL, ERROR } = require('./constants')
const { unslabbedHash } = require('./crypto')
const SecurePayload = require('./secure-payload')
const Holepuncher = require('./holepuncher')
const {
  clearRelayTimeout,
  confirmDirectUpgrade,
  destroyRelayConnection
} = require('./relay-connection')
const { isPrivate } = require('bogon')
const { ALREADY_LISTENING, NODE_DESTROYED, KEYPAIR_ALREADY_USED } = require('./errors')

const HANDSHAKE_CLEAR_WAIT = 10000
const HANDSHAKE_INITIAL_TIMEOUT = 10000

module.exports = class Server extends EventEmitter {
  constructor(dht, opts = {}) {
    super()

    this.dht = dht
    this.target = null

    this.closed = false
    this.firewall = opts.firewall || (() => false)
    this.holepunch = opts.holepunch || (() => true)
    this.relayThrough = opts.relayThrough || null
    this.relayKeepAlive = opts.relayKeepAlive || 5000
    this.pool = opts.pool || null
    this.createHandshake = opts.createHandshake || defaultCreateHandshake
    this.createSecretStream = opts.createSecretStream || defaultCreateSecretStream
    this.suspended = false
    this.handshakeClearWait = opts.handshakeClearWait || HANDSHAKE_CLEAR_WAIT

    this._shareLocalAddress = opts.shareLocalAddress !== false
    this._reusableSocket = !!opts.reusableSocket
    this._neverPunch = opts.holepunch === false // useful for fully disabling punching
    this._keyPair = null
    this._announcer = null
    this._connects = new Map()
    this._holepunches = []
    this._listening = null
    this._closing = null
  }

  get listening() {
    return this._listening !== null
  }

  get publicKey() {
    return this._keyPair && this._keyPair.publicKey
  }

  get relayAddresses() {
    return this._announcer ? this._announcer.relayAddresses : []
  }

  onconnection(encryptedSocket) {
    this.emit('connection', encryptedSocket)
  }

  async suspend({ log = noop } = {}) {
    log('Suspending hyperdht server')
    if (this._listening !== null) await this._listening
    log('Suspending hyperdht server (post listening)')
    this.suspended = true
    this._clearAll()
    return this._announcer ? this._announcer.suspend({ log }) : Promise.resolve()
  }

  async resume() {
    if (this._listening !== null) await this._listening
    this.suspended = false
    return this._announcer ? this._announcer.resume() : Promise.resolve()
  }

  address() {
    if (!this._keyPair) return null

    return {
      publicKey: this._keyPair.publicKey,
      host: this.dht.host,
      port: this.dht.port
    }
  }

  close() {
    if (this._closing) return this._closing
    this._closing = this._close()
    return this._closing
  }

  _gc() {
    this.dht.listening.delete(this)
    if (this.target) this.dht._router.delete(this.target)
  }

  async _stopListening() {
    try {
      if (this._announcer) await this._announcer.stop()
    } catch {
      // ignore
    }

    this._announcer = null
    this._listening = null
    this._keyPair = null
  }

  async _close() {
    if (this._listening === null) {
      this.closed = true
      this.emit('close')
      return
    }

    try {
      await this._listening
    } catch (err) {
      safetyCatch(err)
    }

    this._gc()
    this._clearAll()

    await this._stopListening()

    this.closed = true
    this.emit('close')
  }

  _clearAll() {
    while (this._holepunches.length > 0) {
      const h = this._holepunches.pop()
      if (h && h.puncher) h.puncher.destroy()
      if (h && h.clearing) clearTimeout(h.clearing)
      if (h && h.prepunching) clearTimeout(h.prepunching)
      if (h && h.rawStream) h.rawStream.destroy()
    }

    this._connects.clear()
  }

  async listen(keyPair = this.dht.defaultKeyPair, opts = {}) {
    if (this._listening !== null) throw ALREADY_LISTENING()
    if (this.dht.destroyed) throw NODE_DESTROYED()

    this._listening = this._listen(keyPair, opts)
    await this._listening
    return this
  }

  async _listen(keyPair, opts) {
    // From now on, the DHT object which created me is responsible for closing me
    this.dht.listening.add(this)

    try {
      await this.dht.bind()
      if (this._closing) return

      for (const s of this.dht.listening) {
        if (s._keyPair && b4a.equals(s._keyPair.publicKey, keyPair.publicKey)) {
          throw KEYPAIR_ALREADY_USED()
        }
      }

      this.target = unslabbedHash(keyPair.publicKey)
      this._keyPair = keyPair
      this._announcer = new Announcer(this.dht, keyPair, this.target, opts)

      this.dht._router.set(this.target, {
        relay: null,
        record: this._announcer.record,
        onpeerhandshake: this._onpeerhandshake.bind(this),
        onpeerholepunch: this._onpeerholepunch.bind(this)
      })

      // warm it up for now
      this._localAddresses().catch(safetyCatch)

      await this._announcer.start()
    } catch (err) {
      await this._stopListening()
      this._gc()
      throw err
    }

    if (this._closing) return
    if (this.suspended) await this._announcer.suspend()

    if (this._closing) return
    if (this.dht.destroyed) throw NODE_DESTROYED()

    if (this.pool) this.pool._attachServer(this)

    this.emit('listening')
  }

  refresh() {
    if (this._announcer && !this.suspended) this._announcer.refresh()
  }

  notifyOnline() {
    if (this._announcer) this._announcer.online.notify()
  }

  _localAddresses() {
    return this.dht.validateLocalAddresses(Holepuncher.localAddresses(this.dht.io.serverSocket))
  }

  async _addHandshake(k, noise, clientAddress, { to: serverAddress, socket }, direct) {
    let id = this._holepunches.indexOf(null)
    if (id === -1) id = this._holepunches.push(null) - 1

    const hs = {
      round: 0,
      reply: null,
      puncher: null,
      payload: null,
      rawStream: null,
      encryptedSocket: null,
      prepunching: null,
      firewalled: true,
      clearing: null,
      replyFromPuncher: false,
      onsocket: null,
      aborted: false,

      // Relay state
      relayTimeout: null,
      relayToken: null,
      relaySocket: null,
      relayClient: null,
      relayPaired: false,
      validUpgrade: true
    }

    this._holepunches[id] = hs

    const handshake = this.createHandshake(this._keyPair, null)

    let remotePayload
    try {
      remotePayload = await handshake.recv(noise)
    } catch (err) {
      safetyCatch(err)
      this._clearLater(hs, id, k)
      return null
    }

    if (this._closing || this.suspended) return null

    try {
      hs.firewalled = await this.firewall(handshake.remotePublicKey, remotePayload, clientAddress)
    } catch (err) {
      safetyCatch(err)
    }

    if (this._closing || this.suspended) return null

    if (hs.firewalled) {
      this._clearLater(hs, id, k)
      return null
    }

    const error =
      remotePayload.version === 1
        ? remotePayload.udx
          ? ERROR.NONE
          : ERROR.ABORTED
        : ERROR.VERSION_MISMATCH

    const addresses = []
    const ourRemoteAddr = this.dht.remoteAddress()
    const ourLocalAddrs = this._shareLocalAddress ? await this._localAddresses() : null

    if (this._closing || this.suspended) return null

    if (ourRemoteAddr) addresses.push(ourRemoteAddr)
    if (ourLocalAddrs) addresses.push(...ourLocalAddrs)

    if (error === ERROR.NONE) {
      hs.rawStream = this.dht.createRawStream({
        framed: true,
        firewall(socket, port, host) {
          if (!(port > 0 && port < 65536)) return true

          // Check if the traffic originated from the socket on which we're expecting relay traffic. If so,
          // we haven't hole punched yet and the other side is just sending us traffic through the relay.
          if (hs.relaySocket && isRelay(hs.relaySocket, socket, port, host)) {
            hs.validUpgrade = false
            return false
          }

          hs.onsocket(socket, port, host)
          hs.validUpgrade = true
          return false
        }
      })

      hs.rawStream.on('error', autoDestroy)

      // Handles the case where onsocket is never called, but the stream got setup
      // This can happen on a relayed connection which never connects directly
      // (onsocket is called there only when the direct connection is established)
      const onrawstreamclose = () => {
        if (this._closing) return
        this._clearLater(hs, id, k)
      }
      hs.rawStream.on('close', onrawstreamclose)

      hs.onsocket = (socket, port, host) => {
        if (hs.rawStream === null) return // Already hole punched

        this._clearLater(hs, id, k)

        if (hs.prepunching) {
          clearTimeout(hs.prepunching)
          hs.prepunching = null
        }

        if (this._reusableSocket && remotePayload.udx.reusableSocket) {
          this.dht._socketPool.routes.add(handshake.remotePublicKey, hs.rawStream)
        }

        hs.rawStream.removeListener('error', autoDestroy)
        hs.rawStream.removeListener('close', onrawstreamclose)

        if (hs.rawStream.connected) {
          const rawStream = hs.rawStream
          const remoteChanging = rawStream.changeRemote(socket, remotePayload.udx.id, port, host)
          confirmDirectUpgrade(hs, rawStream, remoteChanging)
        } else {
          hs.rawStream.connect(socket, remotePayload.udx.id, port, host)
          hs.encryptedSocket = this.createSecretStream(false, hs.rawStream, {
            handshake: h,
            keepAlive: this.dht.connectionKeepAlive
          })

          this.onconnection(hs.encryptedSocket)
        }

        if (hs.puncher) {
          hs.puncher.onabort = noop
          hs.puncher.destroy()
        }

        hs.rawStream = null
      }

      function autoDestroy() {
        if (hs.puncher) hs.puncher.destroy()
      }
    }

    const relayAddresses = this.relayAddresses
    const relayThrough = selectRelay(this.relayThrough)

    if (relayThrough) hs.relayToken = relay.token()

    try {
      hs.reply = await handshake.send({
        error,
        firewall: ourRemoteAddr ? FIREWALL.OPEN : FIREWALL.UNKNOWN,
        holepunch: ourRemoteAddr ? null : { id, relays: this._announcer.relays },
        addresses4: addresses,
        addresses6: null,
        udx: {
          reusableSocket: this._reusableSocket,
          id: hs.rawStream ? hs.rawStream.id : 0,
          seq: 0
        },
        secretStream: {},
        relayThrough: relayThrough ? { publicKey: relayThrough, token: hs.relayToken } : null,
        relayAddresses: relayAddresses.length ? relayAddresses : null
      })
    } catch (err) {
      safetyCatch(err)
      if (hs.rawStream) hs.rawStream.destroy()
      this._clearLater(hs, id, k)
      return null
    }

    if (this._closing || this.suspended) {
      if (hs.rawStream) hs.rawStream.destroy()
      return null
    }

    const h = handshake.final()

    if (error !== ERROR.NONE) {
      if (hs.rawStream) hs.rawStream.destroy()
      this._clearLater(hs, id, k)
      return hs
    }

    if (remotePayload.firewall === FIREWALL.OPEN || direct) {
      const sock = direct ? socket : this.dht.socket
      this.dht.stats.punches.open++
      hs.onsocket(sock, clientAddress.port, clientAddress.host)
      return hs
    }

    if (relayThrough || remotePayload.relayThrough) {
      this._relayConnection(hs, relayThrough, remotePayload, h)
    }

    const onabort = () => {
      hs.aborted = true
      if (hs.prepunching) clearTimeout(hs.prepunching)
      hs.prepunching = null
      if (hs.puncher) {
        hs.puncher.onabort = noop
        hs.puncher.destroy()
      }
      if (hs.rawStream.destroyed) {
        this._clearLater(hs, id, k)
        return
      }

      hs.rawStream.on('close', () => this._clearLater(hs, id, k))
      if (hs.relayToken === null) hs.rawStream.destroy()
    }

    if (!direct && clientAddress.host === serverAddress.host) {
      const clientAddresses = remotePayload.addresses4.filter((addr) => isPrivate(addr.host))

      if (clientAddresses.length > 0 && this._shareLocalAddress) {
        const myAddresses = await this._localAddresses()
        const addr = Holepuncher.matchAddress(myAddresses, clientAddresses)

        if (addr) {
          hs.payload = new SecurePayload(h.holepunchSecret)
          setupHolepuncher(this.dht, hs, remotePayload.firewall, onabort)
          hs.prepunching = setTimeout(onabort, HANDSHAKE_INITIAL_TIMEOUT)
          return hs
        }
      }
    }

    if (this._closing || this.suspended) return null

    if (ourRemoteAddr || this._neverPunch) {
      hs.prepunching = setTimeout(onabort, HANDSHAKE_INITIAL_TIMEOUT)
      return hs
    }

    hs.payload = new SecurePayload(h.holepunchSecret)
    setupHolepuncher(this.dht, hs, remotePayload.firewall, onabort)
    hs.replyFromPuncher = true
    hs.prepunching = setTimeout(hs.puncher.destroy.bind(hs.puncher), HANDSHAKE_INITIAL_TIMEOUT)

    return hs
  }

  _clearLater(hs, id, k) {
    if (hs.clearing) return
    hs.clearing = setTimeout(() => this._clear(hs, id, k), this.handshakeClearWait)
  }

  _clear(hs, id, k) {
    if (id >= this._holepunches.length || this._holepunches[id] !== hs) return
    if (hs.clearing) clearTimeout(hs.clearing)

    this._holepunches[id] = null
    while (
      this._holepunches.length > 0 &&
      this._holepunches[this._holepunches.length - 1] === null
    ) {
      this._holepunches.pop()
    }
    this._connects.delete(k)
  }

  async _onpeerhandshake({ noise, peerAddress }, req) {
    const k = b4a.toString(noise, 'hex')

    // The next couple of statements MUST run within the same tick to prevent
    // a malicious peer from flooding us with handshakes.
    let p = this._connects.get(k)
    if (!p) {
      p = this._addHandshake(k, noise, peerAddress || req.from, req, !peerAddress)
      this._connects.set(k, p)
    }

    const h = await p
    if (!h) return null

    if (this._closing !== null || this.suspended) return null

    // Routed handshake replies advertise the socket they are sent from as the
    // server address. Same-LAN prepunch also creates a puncher, but it must
    // keep advertising the normal server socket so the LAN shortcut can open.
    return { socket: h.replyFromPuncher ? h.puncher.socket : null, noise: h.reply }
  }

  async _onpeerholepunch({ id, peerAddress, payload }, req) {
    const h = id < this._holepunches.length ? this._holepunches[id] : null
    if (!h) return null

    if (!peerAddress || this._closing !== null || this.suspended) return null
    if (!h.payload) return this._abort(h) // not opened

    const remotePayload = h.payload.decrypt(payload)
    if (!remotePayload) return null

    const p = h.puncher
    if (!p || !p.socket) return this._abort(h) // not opened

    const isServerRelay = this._announcer.isRelay(req.from)
    const { error, firewall, round, punching, addresses, remoteAddress, remoteToken } =
      remotePayload

    if (error !== ERROR.NONE) {
      // We actually do not need to set the round here, but just do it for consistency.
      if (round >= h.round) h.round = round
      return this._abort(h)
    }

    const token = h.payload.token(peerAddress)
    const echoed = isServerRelay && !!remoteToken && b4a.equals(token, remoteToken)

    // Update our heuristics here
    if (req.socket === p.socket) {
      p.nat.add(req.to, req.from)
    }

    if (round >= h.round) {
      h.round = round
      p.updateRemote({ punching, firewall, addresses, verified: echoed ? peerAddress.host : null })
    }

    // Wait for the analyzer to reach a conclusion...
    let stable = await p.analyze(false)
    if (p.destroyed) return null

    if (!p.remoteHolepunching && !stable) {
      stable = await p.analyze(true)
      if (p.destroyed) return null
      if (!stable) return this._abort(h)
    }

    // Fast mode! If we are consistent and the remote has opened a session to us (remoteAddress)
    // then fire a quick punch back. Note the await here just waits for the udp socket to flush.
    if (
      isConsistent(p.nat.firewall) &&
      remoteAddress &&
      hasSameAddr(p.nat.addresses, remoteAddress)
    ) {
      await p.ping(peerAddress)
      if (p.destroyed) return null
    }

    // Remote said they are punching (or willing to), so we will punch as well.
    // Note that this returns when the punching has STARTED, so no guarantee
    // we will have a connection after this promise etc.
    if (p.remoteHolepunching) {
      // TODO: still continue here if a local connection might work, but then do not holepunch...
      if (!this.holepunch(p.remoteFirewall, p.nat.firewall, p.remoteAddresses, p.nat.addresses)) {
        return p.destroyed ? null : this._abort(h)
      }

      if (h.prepunching) {
        clearTimeout(h.prepunching)
        h.prepunching = null
      }

      if (p.remoteFirewall >= FIREWALL.RANDOM || p.nat.firewall >= FIREWALL.RANDOM) {
        if (
          this.dht._randomPunches >= this.dht._randomPunchLimit ||
          Date.now() - this.dht._lastRandomPunch < this.dht._randomPunchInterval
        ) {
          if (!h.relayToken) return this._abort(h, ERROR.TRY_LATER)
          return {
            socket: p.socket,
            payload: h.payload.encrypt({
              error: ERROR.TRY_LATER,
              firewall: p.nat.firewall,
              round: h.round,
              connected: p.connected,
              punching: p.punching,
              addresses: p.nat.addresses,
              remoteAddress: null,
              token: isServerRelay ? token : null,
              remoteToken: remotePayload.token
            })
          }
        }
      }

      const punching = await p.punch()
      if (p.destroyed) return null
      if (!punching) return this._abort(h)
    }

    // Freeze that analysis as soon as we have a result we are giving to the other peer
    if (p.nat.firewall !== FIREWALL.UNKNOWN) {
      p.nat.freeze()
    }

    return {
      socket: p.socket,
      payload: h.payload.encrypt({
        error: ERROR.NONE,
        firewall: p.nat.firewall,
        round: h.round,
        connected: p.connected,
        punching: p.punching,
        addresses: p.nat.addresses,
        remoteAddress: null,
        token: isServerRelay ? token : null,
        remoteToken: remotePayload.token
      })
    }
  }

  _abort(h, error = ERROR.ABORTED) {
    if (!h.payload) {
      if (h.puncher) h.puncher.destroy()
      return null
    }

    const payload = h.payload.encrypt({
      error,
      firewall: FIREWALL.UNKNOWN,
      round: h.round,
      connected: false,
      punching: false,
      addresses: null,
      remoteAddress: null,
      token: null,
      remoteToken: null
    })

    if (h.puncher) h.puncher.destroy()

    return { socket: this.dht.socket, payload }
  }

  _relayConnection(hs, relayThrough, remotePayload, h) {
    this.dht.stats.relaying.attempts++

    let isInitiator
    let publicKey
    let token

    if (relayThrough) {
      isInitiator = true
      publicKey = relayThrough
      token = hs.relayToken
    } else {
      isInitiator = false
      publicKey = remotePayload.relayThrough.publicKey
      token = remotePayload.relayThrough.token
    }

    hs.relayToken = token
    hs.relaySocket = this.dht.connect(publicKey)
    hs.relaySocket.setKeepAlive(this.relayKeepAlive)
    hs.relayClient = relay.Client.from(hs.relaySocket, { id: hs.relaySocket.publicKey })
    hs.relayTimeout = setTimeout(onabort, 15000)

    hs.relayClient
      .pair(isInitiator, token, hs.rawStream)
      .on('error', onabort)
      .on('data', (remoteId) => {
        if (hs.relayTimeout) clearRelayTimeout(hs)
        if (hs.rawStream === null) {
          onabort(null)
          return
        }

        hs.relayPaired = true
        this.dht.stats.relaying.successes++

        if (hs.prepunching) clearTimeout(hs.prepunching)
        hs.prepunching = null

        const { remotePort, remoteHost, socket } = hs.relaySocket.rawStream

        hs.rawStream
          .on('close', () => destroyRelayConnection(hs))
          .connect(socket, remoteId, remotePort, remoteHost)

        hs.encryptedSocket = this.createSecretStream(false, hs.rawStream, {
          handshake: h,
          keepAlive: this.dht.connectionKeepAlive
        })

        this.onconnection(hs.encryptedSocket)
      })

    const dht = this.dht
    function onabort() {
      if (!hs.relayPaired) dht.stats.relaying.aborts++
      destroyRelayConnection(hs)
      if (hs.aborted && hs.rawStream) hs.rawStream.destroy()
    }
  }
}

function isConsistent(fw) {
  return fw === FIREWALL.OPEN || fw === FIREWALL.CONSISTENT
}

function hasSameAddr(addrs, other) {
  if (addrs === null) return false

  for (const addr of addrs) {
    if (addr.port === other.port && addr.host === other.host) return true
  }
  return false
}

function defaultCreateHandshake(keyPair, remotePublicKey) {
  return new NoiseWrap(keyPair, remotePublicKey)
}

function defaultCreateSecretStream(isInitiator, rawStream, opts) {
  return new NoiseSecretStream(isInitiator, rawStream, opts)
}

function setupHolepuncher(dht, hs, remoteFirewall, onabort) {
  if (hs.puncher) return

  hs.puncher = new Holepuncher(dht, dht.session(), false, remoteFirewall)
  hs.puncher.onconnect = hs.onsocket
  hs.puncher.onabort = onabort
}

function isRelay(relaySocket, socket, port, host) {
  const stream = relaySocket.rawStream
  if (!stream) return false
  if (stream.socket !== socket) return false
  return port === stream.remotePort && host === stream.remoteHost
}

function selectRelay(relayThrough) {
  if (typeof relayThrough === 'function') relayThrough = relayThrough()
  if (relayThrough === null) return null
  if (Array.isArray(relayThrough)) {
    return relayThrough[Math.floor(Math.random() * relayThrough.length)]
  }
  return relayThrough
}

function noop() {}
module.exports = class Sleeper {
  constructor() {
    this._timeout = null
    this._resolve = null

    this._start = (resolve) => {
      this._resolve = resolve
    }

    this._trigger = () => {
      if (this._resolve === null) return
      const resolve = this._resolve
      this._timeout = null
      this._resolve = null
      resolve()
    }
  }

  pause(ms) {
    const p = new Promise(this._start)
    if (this._timeout !== null) {
      clearTimeout(this._timeout)
      this._trigger()
    }
    this._timeout = setTimeout(this._trigger, ms)
    return p
  }

  resume() {
    if (this._timeout !== null) {
      clearTimeout(this._timeout)
      this._trigger()
    }
  }
}
const b4a = require('b4a')

const LINGER_TIME = 3000

module.exports = class SocketPool {
  constructor(dht, host) {
    this._dht = dht
    this._sockets = new Map()
    this._lingering = new Set() // updated by the ref
    this._host = host

    this.routes = new SocketRoutes(this)
  }

  _onmessage(ref, data, address) {
    this._dht.onmessage(ref.socket, data, address)
  }

  _add(ref) {
    this._sockets.set(ref.socket, ref)
  }

  _remove(ref) {
    this._sockets.delete(ref.socket)
    this._lingering.delete(ref)
  }

  lookup(socket) {
    return this._sockets.get(socket) || null
  }

  setReusable(socket, bool) {
    const ref = this.lookup(socket)
    if (ref) ref.reusable = bool
  }

  acquire() {
    // TODO: Enable socket reuse
    return new SocketRef(this)
  }

  async destroy() {
    const closing = []

    for (const ref of this._sockets.values()) {
      ref._unlinger()
      closing.push(ref.socket.close())
    }

    await Promise.allSettled(closing)
  }
}

class SocketRoutes {
  constructor(pool) {
    this._pool = pool
    this._routes = new Map()
  }

  add(publicKey, rawStream) {
    if (rawStream.socket) this._onconnect(publicKey, rawStream)
    else rawStream.on('connect', this._onconnect.bind(this, publicKey, rawStream))
  }

  get(publicKey) {
    const id = b4a.toString(publicKey, 'hex')
    const route = this._routes.get(id)
    if (!route) return null
    return route
  }

  _onconnect(publicKey, rawStream) {
    const id = b4a.toString(publicKey, 'hex')
    const socket = rawStream.socket

    let route = this._routes.get(id)

    if (!route) {
      const gc = () => {
        if (this._routes.get(id) === route) this._routes.delete(id)
        socket.removeListener('close', gc)
      }

      route = {
        socket,
        address: { host: rawStream.remoteHost, port: rawStream.remotePort },
        gc
      }

      this._routes.set(id, route)
      socket.on('close', gc)
    }

    this._pool.setReusable(socket, true)

    rawStream.on('error', () => {
      this._pool.setReusable(socket, false)
      if (!route) route = this._routes.get(id)
      if (route && route.socket === socket) route.gc()
    })
  }
}

// TODO: we should just make some "user data" object on udx to allow to attach this info
class SocketRef {
  constructor(pool) {
    this._pool = pool

    // Events
    this.onholepunchmessage = noop

    // Whether it should teardown immediately or wait a bit
    this.reusable = false

    this.socket = pool._dht.udx.createSocket()
    this.socket
      .on('close', this._onclose.bind(this))
      .on('message', this._onmessage.bind(this))
      .on('idle', this._onidle.bind(this))
      .on('busy', this._onbusy.bind(this))
      .bind(0, this._pool._host)

    this._refs = 1
    this._released = false
    this._closed = false

    this._timeout = null
    this._wasBusy = false

    this._pool._add(this)
  }

  _onclose() {
    this._pool._remove(this)
  }

  _onmessage(data, address) {
    if (data.byteLength > 1) {
      this._pool._onmessage(this, data, address)
    } else {
      this.onholepunchmessage(data, address, this)
    }
  }

  _onidle() {
    this._closeMaybe()
  }

  _onbusy() {
    this._wasBusy = true
    this._unlinger()
  }

  _reset() {
    this.onholepunchmessage = noop
  }

  _closeMaybe() {
    if (this._refs === 0 && this.socket.idle && !this._timeout) this._close()
  }

  _lingeringClose() {
    this._pool._lingering.delete(this)
    this._timeout = null
    this._closeMaybe()
  }

  _close() {
    this._unlinger()

    if (this.reusable && this._wasBusy) {
      this._wasBusy = false
      this._pool._lingering.add(this)
      this._timeout = setTimeout(this._lingeringClose.bind(this), LINGER_TIME)
      return
    }

    this._closed = true
    this.socket.close()
  }

  _unlinger() {
    if (this._timeout !== null) {
      clearTimeout(this._timeout)
      this._pool._lingering.delete(this)
      this._timeout = null
    }
  }

  get free() {
    return this._refs === 0
  }

  active() {
    this._refs++
    this._unlinger()
  }

  inactive() {
    this._refs--
    this._closeMaybe()
  }

  address() {
    return this.socket.address()
  }

  release() {
    if (this._released) return

    this._released = true
    this._reset()

    this._refs--
    this._closeMaybe()
  }
}

function noop() {}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "hyperdht",
  "version": "6.33.0",
  "description": "The DHT powering Hyperswarm",
  "main": "index.js",
  "browser": "browser.js",
  "bin": {
    "hyperdht": "./bin.js"
  },
  "files": [
    "index.js",
    "browser.js",
    "testnet.js",
    "bin.js",
    "lib/**.js"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    },
    "child_process": {
      "bare": "bare-node-child-process",
      "default": "child_process"
    }
  },
  "dependencies": {
    "@hyperswarm/secret-stream": "^6.6.2",
    "b4a": "^1.3.1",
    "bare-events": "^2.2.0",
    "blind-relay": "^1.3.0",
    "bogon": "^1.0.0",
    "compact-encoding": "^3.0.0",
    "dht-rpc": "^6.15.1",
    "hypercore-crypto": "^3.3.0",
    "hypercore-id-encoding": "^1.2.0",
    "hyperdht-address": "^1.0.1",
    "noise-curve-ed": "^2.0.0",
    "noise-handshake": "^4.0.0",
    "record-cache": "^1.1.1",
    "safety-catch": "^1.0.1",
    "signal-promise": "^1.0.3",
    "sodium-universal": "^5.0.1",
    "streamx": "^2.16.1",
    "unslab": "^1.3.0",
    "xache": "^1.1.0"
  },
  "devDependencies": {
    "bare-node-child-process": "^1.0.1",
    "brittle": "^3.0.0",
    "graceful-goodbye": "^1.3.0",
    "newline-decoder": "^1.0.2",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "test": "prettier --check . && node test/all.js",
    "test:bare": "bare test/all.js",
    "test:generate": "brittle -r test/all.js test/*.js",
    "integration": "brittle test/integration/*.js",
    "end-to-end": "brittle test/end-to-end/*.js"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "directories": {
    "lib": "lib",
    "test": "test"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/hyperdht.git"
  },
  "keywords": [],
  "bugs": {
    "url": "https://github.com/holepunchto/hyperdht/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperdht#readme"
}
const ERRORS = {
  NONEXISTENT_ROUTE: 'NONEXISTENT_ROUTE',
  HANDLER_NOT_FOUND_BY_ID: 'HANDLER_NOT_FOUND_BY_ID',
  ROUTE_NOT_FOUND_BY_NAME: 'ROUTE_NOT_FOUND_BY_NAME'
}

class DispatchError extends Error {
  constructor(code, message, fn = DispatchError) {
    super(message ? `${code}: ${message}` : code)
    this.code = code
    this.isDispatchError = true

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  static isDispatchError(err) {
    return err?.isDispatchError === true
  }

  static NONEXISTENT_ROUTE(name) {
    return new DispatchError(ERRORS.NONEXISTENT_ROUTE, name, DispatchError.NONEXISTENT_ROUTE)
  }

  static HANDLER_NOT_FOUND_BY_ID(id) {
    return new DispatchError(
      ERRORS.HANDLER_NOT_FOUND_BY_ID,
      id,
      DispatchError.HANDLER_NOT_FOUND_BY_ID
    )
  }

  static ROUTE_NOT_FOUND_BY_NAME(name) {
    return new DispatchError(
      ERRORS.ROUTE_NOT_FOUND_BY_NAME,
      name,
      DispatchError.ROUTE_NOT_FOUND_BY_NAME
    )
  }
}

module.exports = {
  DispatchError,
  ERRORS
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "hyperdispatch",
  "version": "1.6.0",
  "description": "Generate operations/endpoints using Hyperschema",
  "main": "index.js",
  "files": [
    "lib/*.js",
    "builder.mjs",
    "builder.cjs",
    "runtime.mjs",
    "runtime.cjs"
  ],
  "imports": {
    "path": {
      "bare": "bare-path",
      "default": "path"
    },
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "fs/*": {
      "bare": "bare-fs/*",
      "default": "fs/*"
    }
  },
  "exports": {
    "./package": "./package.json",
    ".": {
      "import": "./builder.mjs",
      "require": "./builder.cjs"
    },
    "./runtime": {
      "import": "./runtime.mjs",
      "require": "./runtime.cjs"
    }
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test/index.js && npm run example:rebuild",
    "example:rebuild": "node example.js && node example.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/hyperdispatch.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/hyperdispatch/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperdispatch#readme",
  "devDependencies": {
    "brittle": "^3.7.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "test-tmp": "^1.3.0",
    "which-runtime": "^1.3.0"
  },
  "dependencies": {
    "b4a": "^1.6.7",
    "bare-fs": "^4.2.3",
    "bare-path": "^3.0.0",
    "compact-encoding": "^3.0.0",
    "generate-string": "^1.0.1",
    "hyperschema": "^1.3.2",
    "nanoassert": "^2.0.0"
  }
}
const { DispatchError, ERRORS } = require('./lib/errors.js')

module.exports = {
  c: require('compact-encoding'),
  b4a: require('b4a'),
  assert: require('nanoassert'),
  DispatchError,
  ERRORS
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "hyperschema",
  "version": "1.21.0",
  "description": "Create registries of declarative compact-encoding schemas",
  "files": [
    "lib/*.js",
    "builder.mjs",
    "builder.cjs",
    "runtime.mjs",
    "runtime.cjs",
    "primitives.mjs",
    "primitives.cjs"
  ],
  "exports": {
    "./package": "./package.json",
    ".": {
      "import": "./builder.mjs",
      "default": "./builder.cjs"
    },
    "./runtime": {
      "import": "./runtime.mjs",
      "default": "./runtime.cjs"
    },
    "./primitives": {
      "import": "./primitives.mjs",
      "default": "./primitives.cjs"
    }
  },
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    }
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test/index.js",
    "test:bare": "prettier . --check && bare test/index.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/hyperschema.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/hyperschema/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperschema#readme",
  "dependencies": {
    "bare-fs": "^4.0.1",
    "compact-encoding": "^3.0.0",
    "generate-object-property": "^2.0.0",
    "generate-string": "^1.0.1"
  },
  "devDependencies": {
    "brittle": "^3.7.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "test-tmp": "^1.3.0"
  }
}
module.exports = {
  c: require('compact-encoding')
}
const { EventEmitter } = require('events')
const { getStreamError } = require('streamx')
const DHT = require('hyperdht')
const spq = require('shuffled-priority-queue')
const b4a = require('b4a')
const unslab = require('unslab')

const PeerInfo = require('./lib/peer-info')
const RetryTimer = require('./lib/retry-timer')
const ConnectionSet = require('./lib/connection-set')
const PeerDiscovery = require('./lib/peer-discovery')

const MAX_PEERS = 64
const MAX_PARALLEL = 3
const MAX_CLIENT_CONNECTIONS = Infinity // TODO: Change
const MAX_SERVER_CONNECTIONS = Infinity

const ERR_MISSING_TOPIC = 'Topic is required and must be a 32-byte buffer'
const ERR_DESTROYED = 'Swarm has been destroyed'
const ERR_DUPLICATE = 'Duplicate connection'
const ERR_FIREWALL = 'Peer is firewalled'

module.exports = class Hyperswarm extends EventEmitter {
  constructor(opts = {}) {
    super()
    const {
      seed,
      relayThrough,
      keyPair = DHT.keyPair(seed),
      maxPeers = MAX_PEERS,
      maxClientConnections = MAX_CLIENT_CONNECTIONS,
      maxServerConnections = MAX_SERVER_CONNECTIONS,
      maxParallel = MAX_PARALLEL,
      firewall = allowAll
    } = opts
    this.keyPair = keyPair

    this.dht =
      opts.dht ||
      new DHT({
        bootstrap: opts.bootstrap,
        nodes: opts.nodes,
        port: opts.port,
        deferRandomPunch: opts.deferRandomPunch,
        randomPunchInterval: opts.randomPunchInterval
      })
    this.server = this.dht.createServer(
      {
        firewall: this._handleFirewall.bind(this),
        relayThrough: this._maybeRelayConnection.bind(this),
        handshakeClearWait: opts.handshakeClearWait
      },
      this._handleServerConnection.bind(this)
    )

    this.destroyed = false
    this.suspended = false
    this.maxPeers = maxPeers
    this.maxClientConnections = maxClientConnections
    this.maxServerConnections = maxServerConnections
    this.maxParallel = maxParallel
    this.relayThrough = relayThrough ? toRelayFunction(relayThrough) : null

    this.connecting = 0
    this.connections = new Set()
    this.peers = new Map()
    this.explicitPeers = new Set()
    this.listening = null
    this.stats = {
      updates: 0,
      connects: {
        client: {
          opened: 0,
          closed: 0,
          attempted: 0
        },
        server: {
          // Note: there is no notion of 'attempts' for server connections
          opened: 0,
          closed: 0
        }
      },
      bannedPeers: 0
    }

    this._discovery = new Map()
    this._timer = new RetryTimer(this._requeue.bind(this), {
      backoffs: opts.backoffs,
      jitter: opts.jitter
    })
    this._queue = spq()

    this._allConnections = new ConnectionSet()
    this._pendingFlushes = []
    this._flushTick = 0

    this._drainingQueue = false
    this._clientConnections = 0
    this._serverConnections = 0
    this._firewall = firewall

    this.dht.on('network-change', this._handleNetworkChange.bind(this))
    this.dht.on('network-update', this._handleNetworkUpdate.bind(this))
    this.on('update', this._handleUpdate)
  }

  _maybeRelayConnection(force) {
    if (!this.relayThrough) return null
    return this.relayThrough(force, this)
  }

  _enqueue(peerInfo) {
    if (peerInfo.queued) return
    peerInfo.queued = true
    peerInfo._flushTick = this._flushTick
    this._queue.add(peerInfo)

    this._attemptClientConnections()
  }

  _requeue(batch) {
    if (this.suspended) return
    for (const peerInfo of batch) {
      peerInfo.waiting = false

      if (
        peerInfo._updatePriority() === false ||
        this._allConnections.has(peerInfo.publicKey) ||
        peerInfo.queued
      ) {
        continue
      }
      peerInfo.queued = true
      peerInfo._flushTick = this._flushTick
      this._queue.add(peerInfo)
    }

    this._attemptClientConnections()
  }

  _flushMaybe(peerInfo) {
    for (let i = 0; i < this._pendingFlushes.length; i++) {
      const flush = this._pendingFlushes[i]
      if (peerInfo._flushTick > flush.tick) continue
      if (--flush.missing > 0) continue
      flush.onflush(true)
      this._pendingFlushes.splice(i--, 1)
    }
  }

  _withinMaxPeers() {
    const e = this.explicitPeers.size
    const factor = e === 0 ? 1 : e < 2 ? 2 : e < 4 ? 3 : 4
    return factor * this._allConnections.size < this.maxPeers
  }

  _flushAllMaybe() {
    if (
      this.connecting > 0 ||
      (this._withinMaxPeers() && this._clientConnections < this.maxClientConnections)
    ) {
      return false
    }

    while (this._pendingFlushes.length) {
      const flush = this._pendingFlushes.pop()
      flush.onflush(true)
    }

    return true
  }

  _shouldConnectExplicit() {
    return !this.destroyed && !this.suspended && this.connecting < this.maxParallel
  }

  _shouldConnect() {
    return (
      !this.destroyed &&
      !this.suspended &&
      this.connecting < this.maxParallel &&
      this._withinMaxPeers() &&
      this._clientConnections < this.maxClientConnections
    )
  }

  _shouldRequeue(peerInfo) {
    if (this.suspended) return false
    if (peerInfo.explicit) return true
    for (const topic of peerInfo.topics) {
      if (this._discovery.has(b4a.toString(topic, 'hex')) && !this.destroyed) {
        return true
      }
    }
    return false
  }

  _connect(peerInfo, queued) {
    if (peerInfo.banned || this._allConnections.has(peerInfo.publicKey)) {
      if (queued) this._flushMaybe(peerInfo)
      return
    }

    // TODO: Support async firewalling at some point.
    if (this._handleFirewall(peerInfo.publicKey, null)) {
      if (queued) this._flushMaybe(peerInfo)
      return
    }

    const relayThrough = this._maybeRelayConnection(peerInfo.forceRelaying)
    const conn = this.dht.connect(peerInfo.publicKey, {
      relayAddresses: peerInfo.relayAddresses,
      keyPair: this.keyPair,
      relayThrough
    })
    this._allConnections.add(conn)

    this.stats.connects.client.attempted++

    this.connecting++
    this._clientConnections++
    let opened = false

    const onerror = (err) => {
      if (this.relayThrough && shouldForceRelaying(err.code)) {
        peerInfo.forceRelaying = true
        // Reset the attempts in order to fast connect to relay
        peerInfo.attempts = 0
      }
    }

    // Removed once a connection is opened
    conn.on('error', onerror)

    conn.on('open', () => {
      opened = true
      this.stats.connects.client.opened++

      this._connectDone()
      this.connections.add(conn)
      conn.removeListener('error', onerror)
      peerInfo._connected()
      peerInfo.client = true
      this.emit('connection', conn, peerInfo)
      if (queued) this._flushMaybe(peerInfo)

      this.emit('update')
    })
    conn.on('close', () => {
      if (!opened) this._connectDone()
      this.stats.connects.client.closed++

      const err = getStreamError(conn)
      if (shouldBan(err)) {
        this._banPeer(peerInfo, true, err)
      }

      this.connections.delete(conn)
      this._allConnections.delete(conn)
      this._clientConnections--
      peerInfo._disconnected()

      peerInfo.waiting = this._shouldRequeue(peerInfo) && this._timer.add(peerInfo)
      this._maybeDeletePeer(peerInfo)

      if (!opened && queued) this._flushMaybe(peerInfo)

      this._attemptClientConnections()

      this.emit('update')
    })

    this.emit('update')
  }

  _connectDone() {
    this.connecting--

    if (this.connecting < this.maxParallel) this._attemptClientConnections()
    if (this.connecting === 0) this._flushAllMaybe()
  }

  // Called when the PeerQueue indicates a connection should be attempted.
  _attemptClientConnections() {
    // Guard against re-entries - unsure if it still needed but doesn't hurt
    if (this._drainingQueue || this.suspended) return
    this._drainingQueue = true

    for (const peerInfo of this.explicitPeers) {
      if (!this._shouldConnectExplicit()) break
      if (
        peerInfo.attempts >= 5 ||
        Date.now() - peerInfo.disconnectedTime < peerInfo.attempts * 1000
      ) {
        continue
      }
      this._connect(peerInfo, false)
    }

    while (this._queue.length && this._shouldConnect()) {
      const peerInfo = this._queue.shift()
      peerInfo.queued = false
      this._connect(peerInfo, true)
    }
    this._drainingQueue = false
    if (this.connecting === 0) this._flushAllMaybe()
  }

  _handleFirewall(remotePublicKey, payload) {
    if (b4a.equals(remotePublicKey, this.keyPair.publicKey)) return true

    let peerInfo = this.peers.get(b4a.toString(remotePublicKey, 'hex'))
    if (peerInfo && peerInfo.banned) return true

    const firewalled = this._firewall(remotePublicKey, payload)
    if (firewalled) {
      if (!peerInfo) peerInfo = this._upsertPeer(remotePublicKey)
      this._banPeer(peerInfo, true, new Error(ERR_FIREWALL))
    }

    return firewalled
  }

  _handleServerConnectionSwap(existing, conn) {
    let closed = false

    existing.on('close', () => {
      if (closed) return

      conn.removeListener('error', noop)
      conn.removeListener('close', onclose)

      this._handleServerConnection(conn)
    })

    conn.on('error', noop)
    conn.on('close', onclose)

    function onclose() {
      closed = true
    }
  }

  // Called when the DHT receives a new server connection.
  _handleServerConnection(conn) {
    if (this.destroyed || this.suspended) {
      // TODO: Investigate why a final server connection can be received after close
      conn.on('error', noop)
      return conn.destroy(ERR_DESTROYED)
    }

    const existing = this._allConnections.get(conn.remotePublicKey)

    if (existing) {
      // If both connections are from the same peer,
      // - pick the new one if the existing stream is already established (has sent and received bytes),
      //   because the other client must have lost that connection and be reconnecting
      // - otherwise, pick the one thats expected to initiate in a tie break
      const existingIsOutdated = existing.rawBytesRead > 0 && existing.rawBytesWritten > 0
      const expectedInitiator = b4a.compare(conn.publicKey, conn.remotePublicKey) > 0
      const keepNew = existingIsOutdated || expectedInitiator === conn.isInitiator

      if (keepNew === false) {
        existing.sendKeepAlive()
        conn.on('error', noop)
        conn.destroy(new Error(ERR_DUPLICATE))
        return
      }

      existing.on('error', noop)
      existing.destroy(new Error(ERR_DUPLICATE))
      this._handleServerConnectionSwap(existing, conn)
      return
    }

    // When reaching here, the connection will always be 'opened' next tick
    this.stats.connects.server.opened++

    const peerInfo = this._upsertPeer(conn.remotePublicKey, null)

    this.connections.add(conn)
    this._allConnections.add(conn)
    this._serverConnections++

    conn.on('close', () => {
      const err = getStreamError(conn)
      if (shouldBan(err)) {
        this._banPeer(peerInfo, true, err)
      }

      this.connections.delete(conn)
      this._allConnections.delete(conn)
      this._serverConnections--
      this.stats.connects.server.closed++

      this._maybeDeletePeer(peerInfo)

      this._attemptClientConnections()

      this.emit('update')
    })
    peerInfo.client = false
    this.emit('connection', conn, peerInfo)

    this.emit('update')
  }

  _upsertPeer(publicKey, relayAddresses) {
    if (b4a.equals(publicKey, this.keyPair.publicKey)) return null
    const keyString = b4a.toString(publicKey, 'hex')
    let peerInfo = this.peers.get(keyString)

    if (peerInfo) {
      peerInfo.relayAddresses = relayAddresses // new is always better
      return peerInfo
    }

    peerInfo = new PeerInfo({
      publicKey,
      relayAddresses
    })

    this.peers.set(keyString, peerInfo)
    return peerInfo
  }

  _handleUpdate() {
    this.stats.updates++
  }

  _maybeDeletePeer(peerInfo) {
    if (!peerInfo.shouldGC()) return

    const hasActiveConn = this._allConnections.has(peerInfo.publicKey)
    if (hasActiveConn) return

    const keyString = b4a.toString(peerInfo.publicKey, 'hex')
    this.peers.delete(keyString)
  }

  /*
   * Called when a peer is actively discovered during a lookup.
   *
   * Three conditions:
   *  1. Not a known peer -- insert into queue
   *  2. A known peer with normal priority -- do nothing
   *  3. A known peer with low priority -- bump priority, because it's been rediscovered
   */
  _handlePeer(peer, topic) {
    const peerInfo = this._upsertPeer(peer.publicKey, peer.relayAddresses)
    if (peerInfo) peerInfo._topic(topic)
    if (!peerInfo || this._allConnections.has(peer.publicKey)) return
    if (!peerInfo.prioritized || peerInfo.server) peerInfo._reset()
    if (peerInfo._updatePriority()) {
      this._enqueue(peerInfo)
    }
  }

  async _handleNetworkUpdate() {
    if (!this.online) return
    this._handleNetworkChange()
  }

  async _handleNetworkChange() {
    if (this.suspended) return

    // prioritize figuring out if existing connections are dead
    for (const conn of this._allConnections) {
      conn.sendKeepAlive()
    }

    const refreshes = []

    for (const discovery of this._discovery.values()) {
      refreshes.push(discovery.refresh())
    }

    await Promise.allSettled(refreshes)
  }

  _banPeer(peerInfo, banned, err) {
    peerInfo.ban(banned)
    this.stats.bannedPeers++
    this.emit('ban', peerInfo, err)
  }

  status(key) {
    return this._discovery.get(b4a.toString(key, 'hex')) || null
  }

  listen() {
    if (!this.listening) {
      if (this.destroyed) throw new Error('Swarm destroyed')
      this.listening = this.server.listen(this.keyPair)
    }
    return this.listening
  }

  // Object that exposes a cancellation method (destroy)
  // TODO: When you rejoin, it should reannounce + bump lookup priority
  join(topic, opts = {}) {
    if (this.destroyed) throw new Error('Swarm destroyed')
    if (!topic) throw new Error(ERR_MISSING_TOPIC)
    topic = unslab(topic)

    const topicString = b4a.toString(topic, 'hex')

    let discovery = this._discovery.get(topicString)

    if (discovery && !discovery.destroyed) {
      return discovery.session(opts)
    }

    discovery = new PeerDiscovery(this, topic, {
      limit: opts.limit,
      wait: discovery ? discovery.destroy() : null,
      suspended: this.suspended,
      onpeer: (peer) => this._handlePeer(peer, topic)
    })
    this._discovery.set(topicString, discovery)
    return discovery.session(opts)
  }

  // Returns a promise
  async leave(topic) {
    if (!topic) throw new Error(ERR_MISSING_TOPIC)
    const topicString = b4a.toString(topic, 'hex')
    if (!this._discovery.has(topicString)) return Promise.resolve()

    const discovery = this._discovery.get(topicString)

    try {
      await discovery.destroy()
    } catch {
      // ignore, prop network
    }

    if (this._discovery.get(topicString) === discovery) {
      this._discovery.delete(topicString)
    }
  }

  joinPeer(publicKey) {
    const peerInfo = this._upsertPeer(publicKey, null)
    if (!peerInfo) return
    if (!this.explicitPeers.has(peerInfo)) {
      peerInfo.explicit = true
      this.explicitPeers.add(peerInfo)
    }
    if (this._allConnections.has(publicKey)) return
    if (peerInfo._updatePriority()) {
      this._enqueue(peerInfo)
    }
  }

  leavePeer(publicKey) {
    const keyString = b4a.toString(publicKey, 'hex')
    if (!this.peers.has(keyString)) return

    const peerInfo = this.peers.get(keyString)
    peerInfo.explicit = false
    this.explicitPeers.delete(peerInfo)
    this._maybeDeletePeer(peerInfo)
  }

  // Returns a promise
  async flush() {
    const allFlushed = [...this._discovery.values()].map((v) => v.flushed())
    await Promise.all(allFlushed)
    if (this._flushAllMaybe()) return true
    const pendingSize = this._allConnections.size - this.connections.size
    if (!this._queue.length && !pendingSize) return true
    return new Promise((resolve) => {
      this._pendingFlushes.push({
        onflush: resolve,
        missing: this._queue.length + pendingSize,
        tick: this._flushTick++
      })
    })
  }

  async clear() {
    const cleared = Promise.allSettled([...this._discovery.values()].map((d) => d.destroy()))
    this._discovery.clear()
    return cleared
  }

  async destroy({ force } = {}) {
    if (this.destroyed && !force) return
    this.destroyed = true

    this._timer.destroy()

    if (!force) await this.clear()

    await this.server.close()

    while (this._pendingFlushes.length) {
      const flush = this._pendingFlushes.pop()
      flush.onflush(false)
    }

    await this.dht.destroy({ force })
  }

  async suspend({ log = noop } = {}) {
    if (this.suspended) return

    const promises = []

    promises.push(this.server.suspend({ log }))

    for (const discovery of this._discovery.values()) {
      promises.push(discovery.suspend({ log }))
    }

    const pending = []
    for (const connection of this._allConnections) {
      connection.destroy()
      pending.push(new Promise((resolve) => connection.on('close', resolve)))
    }

    this.suspended = true

    log('Suspending server and discovery... (' + promises.length + ')')
    await Promise.allSettled(promises)
    log('Done, suspending the dht...')
    await this.dht.suspend({ log })
    log('Done, swarm fully suspended')

    await Promise.all(pending)

    // reset queue
    this._timer.destroy()
    this._timer = new RetryTimer(this._requeue.bind(this), {
      backoffs: this._timer.backoffs,
      jitter: this._timer.jitter
    })
    this._queue = spq()
  }

  async resume({ log = noop } = {}) {
    if (!this.suspended) return

    log('Resuming the dht')
    await this.dht.resume()
    log('Done, resuming the server')
    await this.server.resume()
    log('Done, all discovery')

    for (const discovery of this._discovery.values()) {
      discovery.resume()
    }

    this.suspended = false
    this._attemptClientConnections()
  }

  topics() {
    return this._discovery.values()
  }
}

function noop() {}

function allowAll() {
  return false
}

function shouldForceRelaying(code) {
  return (
    code === 'HOLEPUNCH_ABORTED' ||
    code === 'HOLEPUNCH_DOUBLE_RANDOMIZED_NATS' ||
    code === 'REMOTE_NOT_HOLEPUNCHABLE'
  )
}

function shouldBan() {
  // return !!err && err.name === 'HypercoreError' && err.code === 'INVALID_OPERATION'
  return false
}

function toRelayFunction(relayThrough) {
  return typeof relayThrough === 'function'
    ? relayThrough
    : (force, swarm) => (force || swarm.dht.randomized ? relayThrough : null)
}
module.exports = class BulkTimer {
  constructor(time, fn) {
    this._time = time
    this._fn = fn
    this._interval = null
    this._next = []
    this._pending = []
    this._destroyed = false
  }

  destroy() {
    if (this._destroyed) return
    this._destroyed = true
    clearInterval(this._interval)
    this._interval = null
  }

  _ontick() {
    if (!this._next.length && !this._pending.length) return
    if (this._next.length) this._fn(this._next)
    this._next = this._pending
    this._pending = []
  }

  add(info) {
    if (this._destroyed) return
    if (!this._interval) {
      this._interval = setInterval(this._ontick.bind(this), Math.floor(this._time * 0.66))
    }

    this._pending.push(info)
  }
}
const b4a = require('b4a')

module.exports = class ConnectionSet {
  constructor() {
    this._byPublicKey = new Map()
  }

  [Symbol.iterator]() {
    return this._byPublicKey.values()
  }

  get size() {
    return this._byPublicKey.size
  }

  has(publicKey) {
    return this._byPublicKey.has(toHex(publicKey))
  }

  get(publicKey) {
    return this._byPublicKey.get(toHex(publicKey))
  }

  add(connection) {
    this._byPublicKey.set(b4a.toString(connection.remotePublicKey, 'hex'), connection)
  }

  delete(connection) {
    const keyString = b4a.toString(connection.remotePublicKey, 'hex')
    const existing = this._byPublicKey.get(keyString)
    if (existing !== connection) return
    this._byPublicKey.delete(keyString)
  }
}

function toHex(b) {
  return typeof b === 'string' ? b : b4a.toString(b, 'hex')
}
const safetyCatch = require('safety-catch')
const b4a = require('b4a')

const REFRESH_INTERVAL = 1000 * 60 * 10 // 10 min
const RANDOM_JITTER = 1000 * 60 * 2 // 2 min
const DELAY_GRACE_PERIOD = 1000 * 30 // 30s

const MAX_DISCOVERY_CACHE = 64

module.exports = class PeerDiscovery {
  constructor(
    swarm,
    topic,
    { limit = Infinity, wait = null, suspended = false, onpeer = noop, onerror = safetyCatch }
  ) {
    this.limit = limit
    this.swarm = swarm
    this.topic = topic
    this.isClient = false
    this.isServer = false
    this.destroyed = false
    this.destroying = null
    this.suspended = suspended

    this._sessions = []
    this._clientSessions = 0
    this._serverSessions = 0

    this._onpeer = onpeer
    this._onerror = onerror

    this._discovered = new Set()
    this._activeQuery = null
    this._timer = null
    this._currentRefresh = null
    this._closestNodes = null
    this._firstAnnounce = true
    this._needsUnannounce = false
    this._refreshes = 0
    this._wait = wait
  }

  session({ server = true, client = true, limit = Infinity, onerror = safetyCatch }) {
    if (this.destroyed) throw new Error('PeerDiscovery is destroyed')
    const session = new PeerDiscoverySession(this)
    session.refresh({ server, client, limit }).catch(onerror)
    this._sessions.push(session)
    return session
  }

  _refreshLater(eager) {
    const jitter = Math.round(Math.random() * RANDOM_JITTER)
    const delay = !eager ? REFRESH_INTERVAL + jitter : jitter

    if (this._timer) clearTimeout(this._timer)

    const startTime = Date.now()
    this._timer = setTimeout(() => {
      // If your laptop went to sleep, and is coming back online...
      const overdue = Date.now() - startTime > delay + DELAY_GRACE_PERIOD
      if (overdue) this._refreshLater(true)
      else this.refresh().catch(this._onerror)
    }, delay)
  }

  _isActive() {
    return !this.destroyed && !this.suspended
  }

  // TODO: Allow announce to be an argument to this
  // TODO: Maybe announce should be a setter?
  async _refresh() {
    if (this.suspended) return
    const clock = ++this._refreshes

    if (this._wait) {
      await this._wait
      this._wait = null
      if (clock !== this._refreshes || !this._isActive()) return
    }

    const clear = this.isServer && this._firstAnnounce
    if (clear) this._firstAnnounce = false

    const opts = {
      clear,
      closestNodes: this._closestNodes
    }

    if (this.isServer) {
      await this.swarm.listen()
      // if a parallel refresh is happening, yield to the new one
      if (clock !== this._refreshes || !this._isActive()) return
      this._needsUnannounce = true
    }

    let limit = this.limit

    if (limit < Infinity && limit > 0) {
      for (const id of this._discovered) {
        if (!this.swarm.connections.has(id)) continue
        if (--limit === 0) break
      }
    }

    this._discovered.clear()

    const announcing = this.isServer
    const query = (this._activeQuery = announcing
      ? this.swarm.dht.announce(
          this.topic,
          this.swarm.keyPair,
          this.swarm.server.relayAddresses,
          opts
        )
      : this._needsUnannounce
        ? this.swarm.dht.lookupAndUnannounce(this.topic, this.swarm.keyPair, opts)
        : this.swarm.dht.lookup(this.topic, opts))

    try {
      for await (const data of this._activeQuery) {
        if (!this.isClient || !this._isActive()) continue
        for (const peer of data.peers) {
          if (limit < Infinity) {
            const id = b4a.toString(peer.publicKey, 'hex')

            if (this._discovered.size < MAX_DISCOVERY_CACHE) {
              this._discovered.add(id)
            }

            if (limit === 0) continue

            // there is a chance it has updated a connection during discovery and we go over
            // the limit - thats acceptable to avoid a complexity spiral here.
            if (!this.swarm.connections.has(id)) limit--
          }

          this._onpeer(peer, data)
        }
      }
    } catch (err) {
      if (this._isActive()) throw err
    } finally {
      if (this._activeQuery === query) {
        this._activeQuery = null
        if (!this.destroyed && !this.suspended) this._refreshLater(false)
      }
    }

    // This is set at the very end, when the query completes successfully.
    this._closestNodes = query.closestNodes

    if (clock !== this._refreshes) return

    // In this is the latest query, unannounce has been fulfilled as well
    if (!announcing) this._needsUnannounce = false
  }

  async refresh() {
    if (this.destroyed) throw new Error('PeerDiscovery is destroyed')

    const server = this._serverSessions > 0
    const client = this._clientSessions > 0

    if (this.suspended) return

    if (server === this.isServer && client === this.isClient) {
      if (this._currentRefresh) return this._currentRefresh
      this._currentRefresh = this._refresh()
    } else {
      if (this._activeQuery) this._activeQuery.destroy()
      this.isServer = server
      this.isClient = client
      this._currentRefresh = this._refresh()
    }

    const refresh = this._currentRefresh
    try {
      await refresh
    } catch {
      return false
    } finally {
      if (refresh === this._currentRefresh) {
        this._currentRefresh = null
      }
    }

    return true
  }

  async flushed() {
    if (this.swarm.listening) await this.swarm.listening

    try {
      await this._currentRefresh
      return true
    } catch {
      return false
    }
  }

  async _destroyMaybe() {
    if (this.destroyed) return

    try {
      if (this._sessions.length === 0) await this.swarm.leave(this.topic)
      else if (this._serverSessions === 0 && this._needsUnannounce) await this.refresh()
    } catch (err) {
      // ignore network failures here, as we are tearing down
      safetyCatch(err)
    }
  }

  destroy() {
    if (this.destroying) return this.destroying
    this.destroying = this._destroy()
    return this.destroying
  }

  async _abort(log) {
    const id = log === noop ? '' : b4a.toString(this.topic, 'hex')

    log('Aborting discovery', id)
    if (this._wait) await this._wait
    log('Aborting discovery (post wait)', id)

    if (this._activeQuery) {
      this._activeQuery.destroy()
      this._activeQuery = null
    }
    if (this._timer) {
      clearTimeout(this._timer)
      this._timer = null
    }

    let nodes = this._closestNodes

    if (this._currentRefresh) {
      try {
        await this._currentRefresh
      } catch {
        // If the destroy causes the refresh to fail, suppress it.
      }
    }

    log('Aborting discovery (post refresh)', id)
    if (this._isActive()) return

    if (!nodes) nodes = this._closestNodes
    else if (this._closestNodes !== nodes) {
      const len = nodes.length
      for (const newer of this._closestNodes) {
        if (newer.id && !hasNode(nodes, len, newer)) nodes.push(newer)
      }
    }

    if (this._needsUnannounce) {
      log('Unannouncing discovery', id)
      if (nodes && nodes.length) {
        await this.swarm.dht.unannounce(this.topic, this.swarm.keyPair, {
          closestNodes: nodes,
          onlyClosestNodes: true,
          force: true
        })
      }
      this._needsUnannounce = false
      log('Unannouncing discovery (done)', id)
    }
  }

  _destroy() {
    if (this.destroyed) return
    this.destroyed = true
    return this._abort(noop)
  }

  async suspend({ log = noop } = {}) {
    if (this.suspended) return
    this.suspended = true
    try {
      await this._abort(log)
    } catch {
      // ignore
    }
  }

  resume() {
    if (!this.suspended) return
    this.suspended = false
    this.refresh().catch(noop)
  }
}

class PeerDiscoverySession {
  constructor(discovery) {
    this.discovery = discovery
    this.isClient = false
    this.isServer = false
    this.destroyed = false
  }

  get swarm() {
    return this.discovery.swarm
  }

  get topic() {
    return this.discovery.topic
  }

  async refresh({ client = this.isClient, server = this.isServer, limit = Infinity } = {}) {
    if (this.destroyed) throw new Error('PeerDiscovery is destroyed')
    if (!client && !server) throw new Error('Cannot refresh with neither client nor server option')

    if (client !== this.isClient) {
      this.isClient = client
      this.discovery._clientSessions += client ? 1 : -1
    }

    if (server !== this.isServer) {
      this.isServer = server
      this.discovery._serverSessions += server ? 1 : -1
    }

    this.discovery.limit = limit

    return this.discovery.refresh()
  }

  async flushed() {
    return this.discovery.flushed()
  }

  async destroy() {
    if (this.destroyed) return
    this.destroyed = true

    if (this.isClient) this.discovery._clientSessions--
    if (this.isServer) this.discovery._serverSessions--

    const index = this.discovery._sessions.indexOf(this)
    const head = this.discovery._sessions.pop()

    if (head !== this) this.discovery._sessions[index] = head

    return this.discovery._destroyMaybe()
  }
}

function hasNode(nodes, len, node) {
  for (let i = 0; i < len; i++) {
    const existing = nodes[i]
    if (existing.id && b4a.equals(existing.id, node.id)) return true
  }

  return false
}

function noop() {}
const { EventEmitter } = require('events')
const b4a = require('b4a')
const unslab = require('unslab')

const MIN_CONNECTION_TIME = 15000

const VERY_LOW_PRIORITY = 0
const LOW_PRIORITY = 1
const NORMAL_PRIORITY = 2
const HIGH_PRIORITY = 3
const VERY_HIGH_PRIORITY = 4

module.exports = class PeerInfo extends EventEmitter {
  constructor({ publicKey, relayAddresses }) {
    super()

    this.publicKey = unslab(publicKey)
    this.relayAddresses = relayAddresses

    this.reconnecting = true
    this.proven = false
    this.connectedTime = -1
    this.disconnectedTime = 0
    this.banned = false
    this.tried = false
    this.explicit = false
    this.waiting = false
    this.forceRelaying = false

    // Set by the Swarm
    this.queued = false
    this.client = false
    this.topics = [] // TODO: remove on next major (check with mafintosh for context)

    this.attempts = 0
    this.priority = NORMAL_PRIORITY

    // Used by shuffled-priority-queue
    this._index = 0

    // Used for flush management
    this._flushTick = 0

    // Used for topic multiplexing
    this._seenTopics = new Set()
  }

  get server() {
    return !this.client
  }

  get prioritized() {
    return this.priority >= NORMAL_PRIORITY
  }

  _getPriority() {
    const peerIsStale = this.tried && !this.proven
    if (peerIsStale || this.attempts > 3) return VERY_LOW_PRIORITY
    if (this.attempts === 3) return LOW_PRIORITY
    if (this.attempts === 2) return HIGH_PRIORITY
    if (this.attempts === 1) return VERY_HIGH_PRIORITY
    return NORMAL_PRIORITY
  }

  _connected() {
    this.proven = true
    this.connectedTime = Date.now()
  }

  _disconnected() {
    this.disconnectedTime = Date.now()
    if (this.connectedTime > -1) {
      if (this.disconnectedTime - this.connectedTime >= MIN_CONNECTION_TIME) this.attempts = 0 // fast retry
      this.connectedTime = -1
    }
    this.attempts++
  }

  _deprioritize() {
    this.attempts = 3
  }

  _reset() {
    this.client = false
    this.proven = false
    this.tried = false
    this.attempts = 0
  }

  _updatePriority() {
    if (this.explicit && this.attempts > 3) this._deprioritize()
    if (this.banned || this.queued || this.attempts > 3) return false
    this.priority = this._getPriority()
    return true
  }

  _topic(topic) {
    const topicString = b4a.toString(topic, 'hex')
    if (this._seenTopics.has(topicString)) return
    this._seenTopics.add(topicString)
    this.topics.push(topic)
    this.emit('topic', topic)
  }

  reconnect(val) {
    this.reconnecting = !!val
  }

  ban(val) {
    this.banned = !!val
  }

  shouldGC() {
    return !(this.banned || this.queued || this.explicit || this.waiting)
  }
}
const BulkTimer = require('./bulk-timer')

const BACKOFF_JITTER = 500
const BACKOFF_S = 1000 + Math.round(BACKOFF_JITTER * Math.random())
const BACKOFF_M = 5000 + Math.round(2 * BACKOFF_JITTER * Math.random())
const BACKOFF_L = 15000 + Math.round(4 * BACKOFF_JITTER * Math.random())
const BACKOFF_X = 1000 * 60 * 10 + Math.round(240 * BACKOFF_JITTER * Math.random())

module.exports = class RetryTimer {
  constructor(
    push,
    { backoffs = [BACKOFF_S, BACKOFF_M, BACKOFF_L, BACKOFF_X], jitter = BACKOFF_JITTER } = {}
  ) {
    this.jitter = jitter
    this.backoffs = backoffs

    this._sTimer = new BulkTimer(backoffs[0] + Math.round(jitter * Math.random()), push)
    this._mTimer = new BulkTimer(backoffs[1] + Math.round(jitter * Math.random()), push)
    this._lTimer = new BulkTimer(backoffs[2] + Math.round(jitter * Math.random()), push)
    this._xTimer = new BulkTimer(backoffs[3] + Math.round(jitter * Math.random()), push)
  }

  _selectRetryTimer(peerInfo) {
    if (peerInfo.banned || !peerInfo.reconnecting) return null

    if (peerInfo.attempts > 3) {
      return peerInfo.explicit ? this._xTimer : null
    }

    if (peerInfo.attempts === 0) return this._sTimer
    if (peerInfo.proven) {
      switch (peerInfo.attempts) {
        case 1:
          return this._sTimer
        case 2:
          return this._mTimer
        case 3:
          return this._lTimer
      }
    } else {
      switch (peerInfo.attempts) {
        case 1:
          return this._mTimer
        case 2:
          return this._lTimer
        case 3:
          return this._lTimer
      }
    }

    return null
  }

  add(peerInfo) {
    const timer = this._selectRetryTimer(peerInfo)
    if (!timer) return false

    timer.add(peerInfo)
    return true
  }

  destroy() {
    this._sTimer.destroy()
    this._mTimer.destroy()
    this._lTimer.destroy()
    this._xTimer.destroy()
  }
}
{
  "name": "hyperswarm",
  "version": "4.17.0",
  "description": "A distributed networking stack for connecting peers",
  "files": [
    "index.js",
    "lib/**.js"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    },
    "process": {
      "bare": "bare-process",
      "default": "process"
    }
  },
  "dependencies": {
    "b4a": "^1.3.1",
    "bare-events": "^2.2.0",
    "hyperdht": "^6.21.0",
    "safety-catch": "^1.0.2",
    "shuffled-priority-queue": "^2.1.0",
    "streamx": "^2.22.1",
    "unslab": "^1.3.0"
  },
  "devDependencies": {
    "bare-process": "^4.2.2",
    "brittle": "^3.0.2",
    "hypercore-crypto": "^3.4.0",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "which-runtime": "^1.3.2"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:generate": "brittle -r test/all.js test/*.js",
    "test:node": "brittle-node --coverage test/*.js",
    "test:bare": "bare test/all.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/hyperswarm.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "contributors": [
    "David Mark Clements (@davidmarkclem)",
    "Andrew Osheroff (@andrewosh)"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/hyperswarm/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperswarm"
}
const b4a = require('b4a')

const EMPTY = b4a.alloc(0)
const MAX = b4a.from([0xff])
const BUFFER = {}

BUFFER.preencode = function (state, buf) {
  if (buf === null) buf = EMPTY

  let i = 0
  let extra = 3

  while ((i = b4a.indexOf(buf, 0x00, i)) > -1) {
    i++
    extra++
  }

  state.end += buf.byteLength + extra
}

BUFFER.encode = function (state, buf) {
  if (buf === null) buf = EMPTY

  state.buffer[state.start++] = 0x00

  let prev = 0
  let i = 0

  while ((i = b4a.indexOf(buf, 0x00, i)) > -1) {
    const slice = buf.subarray(prev, ++i)

    state.buffer.set(slice, state.start)
    state.start += slice.byteLength
    state.buffer[state.start++] = 0x02
    prev = i
  }

  const slice = buf.subarray(prev)

  state.buffer.set(slice, state.start)
  state.start += slice.byteLength

  state.buffer[state.start++] = 0x00
  state.buffer[state.start++] = 0x01
}

BUFFER.decode = function (state) {
  if (state.start >= state.end) throw new Error('Out of bounds')
  if (state.buffer[state.start++] !== 0x00) {
    throw new Error('Invalid start of string')
  }

  let escaped = null

  let prev = state.start
  let i = state.start

  while ((i = b4a.indexOf(state.buffer, 0x00, i)) > -1) {
    const next = ++i < state.end ? state.buffer[i] : 0x00

    i++

    if (next === 0x01) {
      break
    }

    if (next === 0x02) {
      if (escaped === null) escaped = []
      escaped.push(state.buffer.subarray(prev, i - 1))
      prev = i
      continue
    }

    throw new Error('Unknown value in terminator')
  }

  if (i === -1) {
    throw new Error('No terminator found')
  }

  state.start = i
  const last = state.buffer.subarray(prev, i - 2)
  if (escaped === null) return last

  escaped.push(last)
  return b4a.concat(escaped)
}

// TODO: can be optimised a lot

const STRING = {}

STRING.preencode = function (state, str) {
  BUFFER.preencode(state, b4a.from(str || ''))
}

STRING.encode = function (state, str) {
  BUFFER.encode(state, b4a.from(str || ''))
}

STRING.decode = function (state, str) {
  return b4a.toString(BUFFER.decode(state))
}

const UINT = {}

UINT.preencode = function (state, n) {
  state.end += n <= 0xfb ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : n === Infinity ? 1 : 9
}

UINT.encode = function (state, n) {
  if (n === Infinity) {
    state.buffer[state.start++] = 0xff
    return
  }

  if (n <= 0xfb) {
    state.buffer[state.start++] = n
    return
  }

  if (n <= 0xffff) {
    state.buffer[state.start++] = 0xfc
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
    return
  }

  if (n <= 0xffffffff) {
    state.buffer[state.start++] = 0xfd
    encodeUint32(state, n)
    return
  }

  if (Number.isSafeInteger(n)) {
    state.buffer[state.start++] = 0xfe

    const r = Math.floor(n / 0x100000000)
    encodeUint32(state, r)
    encodeUint32(state, n)
    return
  }

  throw new Error('Invalid number ' + n)
}

UINT.decode = function (state) {
  if (state.start >= state.end) throw new Error('Out of bounds')

  const a = state.buffer[state.start++]

  if (a <= 0xfb) return a

  if (a === 0xfc) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] * 0x100 + state.buffer[state.start++]
  }

  if (a === 0xfd) {
    return decodeUint32(state)
  }

  if (a === 0xfe) {
    return decodeUint32(state) * 0x100000000 + decodeUint32(state)
  }

  return Infinity
}

const INT = {}

INT.preencode = function (state, n) {
  // One asymmetric condition
  if (n >= -0xff && n < 0) {
    state.end += 2
    return
  }
  n = Math.abs(n)
  state.end += n <= 0xf6 ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : n === Infinity ? 1 : 9
}

INT.encode = function (state, n) {
  if (n === Infinity) {
    state.buffer[state.start++] = 0xff
    return
  }

  if (n === -Infinity) {
    state.buffer[state.start++] = 0x00
    return
  }

  // Negative 64 bit
  if (n < -0xffffffff) {
    if (!Number.isSafeInteger(n)) throw new Error('Invalid number ' + n)
    state.buffer[state.start++] = 0x01

    const r = Math.floor(-n / 0x100000000)
    encodeUint32(state, -r + 0xffffffff)
    encodeUint32(state, -(-n % 0x100000000) + 0xffffffff)
    return
  }

  // Negative 32 bit
  if (n < -0xffff) {
    state.buffer[state.start++] = 0x02

    n += 0xffffffff
    encodeUint32(state, n)
    return
  }

  // Negative 16bit
  if (n < -0xff) {
    state.buffer[state.start++] = 0x03

    n += 0xffff
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
    return
  }

  // Negative 8bit
  if (n < 0) {
    state.buffer[state.start++] = 0x04

    n += 0xff
    state.buffer[state.start++] = n
    return
  }

  // Remainder of 8bit space for positive int
  if (n <= 0xf6) {
    state.buffer[state.start++] = n + 0x05
    return
  }

  // Positive 16bit
  if (n <= 0xffff) {
    state.buffer[state.start++] = 0xfc
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
    return
  }

  // Positive 32bit
  if (n <= 0xffffffff) {
    state.buffer[state.start++] = 0xfd
    encodeUint32(state, n)
    return
  }

  // Positive 64bit
  if (Number.isSafeInteger(n)) {
    state.buffer[state.start++] = 0xfe

    const r = Math.floor(n / 0x100000000)
    encodeUint32(state, r)
    encodeUint32(state, n)
    return
  }

  throw new Error('Invalid number ' + n)
}

INT.decode = function (state) {
  if (state.start >= state.end) throw new Error('Out of bounds')

  const a = state.buffer[state.start++]

  if (a === 0x00) return -Infinity

  if (a === 0x01) {
    // Split (2^64 - 1) into its 32 bit components
    // r * 0x100000000 + n - (2^64 - 1)
    // r * 0x100000000 + n - (0xffffffff * 0x100000000) - 0xffffffff
    // (r - 0xffffffff) * 0x100000000 + n - 0xffffffff
    return (decodeUint32(state) - 0xffffffff) * 0x100000000 + decodeUint32(state) - 0xffffffff
  }

  if (a === 0x02) {
    return decodeUint32(state) - 0xffffffff
  }

  if (a === 0x03) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] * 0x100 + state.buffer[state.start++] - 0xffff
  }

  if (a === 0x04) return state.buffer[state.start++] - 0xff

  if (a <= 0xfb) return a - 0x05

  if (a === 0xfc) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] * 0x100 + state.buffer[state.start++]
  }

  if (a === 0xfd) {
    return decodeUint32(state)
  }

  if (a === 0xfe) {
    return decodeUint32(state) * 0x100000000 + decodeUint32(state)
  }

  return Infinity
}

const DATE = {}

DATE.preencode = (state, d) => INT.preencode(state, d.getTime())
DATE.encode = (state, d) => INT.encode(state, d.getTime())
DATE.decode = (state) => new Date(INT.decode(state))

const BOOL = {}

BOOL.preencode = (state, b) => UINT.preencode(state, b ? 1 : 0)
BOOL.encode = (state, b) => UINT.encode(state, b ? 1 : 0)
BOOL.decode = (state) => !!UINT.decode(state)

module.exports = class IndexEncoder {
  constructor(encodings, { prefix = -1 } = {}) {
    this.encodings = encodings
    this.prefix = prefix
  }

  static BUFFER = BUFFER
  static STRING = STRING
  static UINT = UINT
  static INT = INT
  static DATE = DATE
  static BOOL = BOOL

  static lookup(c) {
    switch (c) {
      case 'uint':
        return UINT
      case 'uint8':
        return UINT
      case 'uint16':
        return UINT
      case 'uint24':
        return UINT
      case 'uint32':
        return UINT
      case 'uint40':
        return UINT
      case 'uint48':
        return UINT
      case 'uint56':
        return UINT
      case 'uint64':
        return UINT
      case 'int':
        return INT
      case 'int8':
        return INT
      case 'int16':
        return INT
      case 'int24':
        return INT
      case 'int32':
        return INT
      case 'int40':
        return INT
      case 'int48':
        return INT
      case 'int56':
        return INT
      case 'int64':
        return INT
      case 'string':
        return STRING
      case 'utf8':
        return STRING
      case 'ascii':
        return STRING
      case 'hex':
        return STRING
      case 'base64':
        return STRING
      case 'fixed32':
        return BUFFER
      case 'fixed64':
        return BUFFER
      case 'buffer':
        return BUFFER
      case 'date':
        return DATE
      case 'bool':
        return BOOL
    }

    throw new Error('Unknown type')
  }

  encode(keys) {
    return this._encode(keys, false)
  }

  _encode(keys, terminate) {
    if (b4a.isBuffer(keys)) return keys

    const state = { start: 0, end: 0, buffer: null }

    if (this.prefix !== -1) UINT.preencode(state, this.prefix)
    for (let i = 0; i < keys.length; i++) {
      this.encodings[i].preencode(state, keys[i])
    }

    if (terminate && keys.length < this.encodings.length) {
      state.end++
    }

    state.buffer = b4a.allocUnsafe(state.end)

    if (this.prefix !== -1) UINT.encode(state, this.prefix)
    for (let i = 0; i < keys.length; i++) {
      this.encodings[i].encode(state, keys[i])
    }

    if (terminate && keys.length < this.encodings.length) {
      state.buffer[state.start++] = MAX[0]
    }

    return state.buffer
  }

  decode(buffer) {
    const state = { start: 0, end: buffer.byteLength, buffer }
    const result = []

    if (this.prefix !== -1) UINT.decode(state)
    for (const enc of this.encodings) {
      const key = state.start < state.end ? enc.decode(state) : enc === UINT ? 0 : null
      result.push(key)
    }

    return result
  }

  encodeRange({ gt, gte, lt, lte }) {
    const range = {
      gt: gt && this._encode(gt, true),
      gte: gte && this._encode(gte, false),
      lt: lt && this._encode(lt, false),
      lte: lte && this._encode(lte, true)
    }

    if (this.prefix !== -1) {
      if (!gt && !gte) range.gte = encodeUint(this.prefix)
      if (!lt && !lte) range.lt = encodeUint(this.prefix + 1)
    }

    return range
  }
}

function encodeUint(n) {
  const state = { start: 0, end: 0, buffer: null }
  UINT.preencode(state, n)
  state.buffer = b4a.allocUnsafe(state.end)
  UINT.encode(state, n)
  return state.buffer
}

function encodeUint32(state, n) {
  state.buffer[state.start++] = n >>> 24
  state.buffer[state.start++] = n >>> 16
  state.buffer[state.start++] = n >>> 8
  state.buffer[state.start++] = n
}

function decodeUint32(state) {
  if (state.end - state.start < 4) throw new Error('Out of bounds')
  return (
    state.buffer[state.start++] * 0x1000000 +
    state.buffer[state.start++] * 0x10000 +
    state.buffer[state.start++] * 0x100 +
    state.buffer[state.start++]
  )
}
{
  "name": "index-encoder",
  "version": "3.5.0",
  "description": "Encode multiple values into sorted keys",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.6.4"
  },
  "devDependencies": {
    "brittle": "^3.2.1",
    "hyperbee": "^2.10.5",
    "hypercore": "^11.0.0",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/index-encoder.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/index-encoder/issues"
  },
  "homepage": "https://github.com/holepunchto/index-encoder"
}
const b4a = require('b4a')

module.exports = function isOptions (opts) {
  return typeof opts === 'object' && opts && !b4a.isBuffer(opts)
}
{
  "name": "is-options",
  "version": "1.0.2",
  "description": "Easily check if input is an options map",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.1.1"
  },
  "devDependencies": {
    "standard": "^11.0.1",
    "tape": "^4.9.0"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/is-options.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/is-options/issues"
  },
  "homepage": "https://github.com/mafintosh/is-options"
}
const { EventEmitter } = require('events')

module.exports = class RoutingTable extends EventEmitter {
  constructor (id, opts) {
    if (!opts) opts = {}

    super()

    this.id = id
    this.k = opts.k || 20
    this.size = 0
    this.rows = new Array(id.length * 8)
  }

  add (node) {
    const i = this._diff(node.id)

    let row = this.rows[i]

    if (!row) {
      row = this.rows[i] = new Row(this, i)
      this.emit('row', row)
    }

    const len = row.nodes.length
    if (!row.add(node, this.k)) return false

    this.size += row.nodes.length - len
    return true
  }

  remove (id) {
    const i = this._diff(id)
    const row = this.rows[i]
    if (!row) return false
    if (!row.remove(id)) return false
    this.size--
    return true
  }

  get (id) {
    const i = this._diff(id)
    const row = this.rows[i]
    if (!row) return null
    return row.get(id)
  }

  has (id) {
    return this.get(id) !== null
  }

  random () {
    let n = (Math.random() * this.size) | 0

    for (let i = 0; i < this.rows.length; i++) {
      const r = this.rows[i]
      if (!r) continue
      if (n < r.nodes.length) return r.nodes[n]
      n -= r.nodes.length
    }

    return null
  }

  closest (id, k) {
    if (!k) k = this.k

    const result = []
    const d = this._diff(id)

    // push close nodes
    for (let i = d; i >= 0 && result.length < k; i--) this._pushNodes(i, k, result)

    // if we don't have enough close nodes, populate from other rows, re the paper
    for (let i = d + 1; i < this.rows.length && result.length < k; i++) this._pushNodes(i, k, result)

    return result
  }

  _pushNodes (i, k, result) {
    const row = this.rows[i]
    if (!row) return

    const missing = Math.min(k - result.length, row.nodes.length)
    for (let j = 0; j < missing; j++) result.push(row.nodes[j])
  }

  toArray () {
    return this.closest(this.id, Infinity)
  }

  _diff (id) {
    for (let i = 0; i < id.length; i++) {
      const a = id[i]
      const b = this.id[i]

      if (a !== b) return i * 8 + Math.clz32(a ^ b) - 24
    }

    return this.rows.length - 1
  }
}

class Row extends EventEmitter {
  constructor (table, index) {
    super()

    this.data = null // can be used be upstream for whatevs
    this.byteOffset = index >> 3
    this.index = index
    this.table = table
    this.nodes = []
  }

  add (node) {
    const id = node.id

    let l = 0
    let r = this.nodes.length - 1

    while (l <= r) {
      const m = (l + r) >> 1
      const c = this.compare(id, this.nodes[m].id)

      if (c === 0) {
        this.nodes[m] = node
        return true
      }

      if (c < 0) r = m - 1
      else l = m + 1
    }

    if (this.nodes.length >= this.table.k) {
      this.emit('full', node)
      return false
    }

    this.insert(l, node)
    return true
  }

  remove (id) {
    let l = 0
    let r = this.nodes.length - 1

    while (l <= r) {
      const m = (l + r) >> 1
      const c = this.compare(id, this.nodes[m].id)

      if (c === 0) {
        this.splice(m)
        return true
      }

      if (c < 0) r = m - 1
      else l = m + 1
    }

    return false
  }

  get (id) {
    let l = 0
    let r = this.nodes.length - 1

    while (l <= r) {
      const m = (l + r) >> 1
      const node = this.nodes[m]
      const c = this.compare(id, node.id)

      if (c === 0) return node
      if (c < 0) r = m - 1
      else l = m + 1
    }

    return null
  }

  insert (i, node) {
    this.nodes.push(node) // push node or null or whatevs, just trying to not be polymorphic
    for (let j = this.nodes.length - 1; j > i; j--) this.nodes[j] = this.nodes[j - 1]
    this.nodes[i] = node
    this.emit('add', node)
  }

  splice (i) {
    for (; i < this.nodes.length - 1; i++) this.nodes[i] = this.nodes[i + 1]
    this.emit('remove', this.nodes.pop())
  }

  // very likely they diverge after a couple of bytes so a simple impl, like this is prop fastest vs Buffer.compare
  compare (a, b) {
    for (let i = this.byteOffset; i < a.length; i++) {
      const ai = a[i]
      const bi = b[i]
      if (ai === bi) continue
      return ai < bi ? -1 : 1
    }
    return 0
  }
}
{
  "name": "kademlia-routing-table",
  "version": "1.0.6",
  "description": "XOR based routing table used for P2P networks such as a Kademlia DHT.",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "dependencies": {
    "bare-events": "^2.2.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "standard": "^17.1.0"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "keywords": [
    "kademlia",
    "p2p",
    "k-bucket",
    "k-buckets",
    "xor",
    "routing",
    "distributed",
    "systems"
  ],
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/kademlia-routing-table.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/kademlia-routing-table/issues"
  },
  "homepage": "https://github.com/mafintosh/kademlia-routing-table"
}
const c = require('compact-encoding')
const b4a = require('b4a')

const KeyChain = require('./lib/keychain')
const { sign, verify, hash } = require('./lib/crypto')

const {
  ProofEncoding,
  AttestedData,
  AttestedDevice,
  ReceiptEncoding
} = require('./lib/encoding')

const PROOF_VERSION = 1
const KEET_TYPE = 5338

const NS_PROFILE_DISC_ENC = hash(b4a.from('profile discovery'))

module.exports = class IdentityKey {
  constructor (keyChain) {
    this.keyChain = keyChain

    this.identityKeyPair = this.keyChain.get(identityKeyPath(0))
    this.profileDiscoveryKeyPair = this.keyChain.get(discoveryCorePath(0))
  }

  static generateMnemonic () {
    return KeyChain.generateMnemonic()
  }

  static deriveSeed (mnemonic) {
    return KeyChain.deriveSeed(mnemonic)
  }

  get identityPublicKey () {
    return this.identityKeyPair.publicKey
  }

  get profileDiscoveryPublicKey () {
    return this.profileDiscoveryKeyPair.publicKey
  }

  getProfileDiscoveryEncryptionKey () {
    return this.keyChain.getSymmetricKey(encryptionKeyPath(NS_PROFILE_DISC_ENC))
  }

  getEncryptionKey (profileKey) {
    return this.keyChain.getSymmetricKey(encryptionKeyPath(profileKey))
  }

  bootstrap (device) {
    return IdentityKey.bootstrap({ identity: this.identityKeyPair }, device)
  }

  clear () {
    this.keyChain.clear()
    this.identityKeyPair.secretKey.fill(0)
    this.profileDiscoveryKeyPair.secretKey.fill(0)
  }

  static async bootstrap ({ identity, seed, mnemonic }, device) {
    if (!identity) {
      const identityPath = identityKeyPath(0) // accountIndex unused for now
      identity = await KeyChain.from({ seed, mnemonic }, identityPath)
    }

    const proof = {
      version: PROOF_VERSION,
      epoch: Date.now(),
      identity: identity.publicKey,
      chain: []
    }

    return IdentityKey.attestDevice(device, identity, proof)
  }

  static attestDevice (publicKey, parent, proof) {
    if (!proof) return IdentityKey.bootstrap({ identity: parent }, publicKey)

    if (b4a.isBuffer(proof)) {
      proof = c.decode(ProofEncoding, proof)
    }

    if (proof.version === 0) {
      throw new Error('Version 0 proofs are not supported')
    }

    const signable = c.encode(AttestedDevice, {
      epoch: proof.epoch,
      identity: proof.identity,
      device: publicKey
    })

    const signature = sign(signable, parent)

    proof.chain.push({ publicKey, signature })

    return c.encode(ProofEncoding, proof)
  }

  static attestData (attestedData, keyPair, proof) {
    if (attestedData === null) throw new Error('Data is not attestable')

    if (b4a.isBuffer(proof)) {
      proof = c.decode(ProofEncoding, proof)
    }

    if (proof && proof.version === 0) {
      throw new Error('Version 0 proofs are not supported')
    }

    if (!proof) {
      proof = {
        version: PROOF_VERSION,
        epoch: Date.now(),
        identity: keyPair.publicKey,
        chain: []
      }
    }

    const signable = c.encode(AttestedData, {
      epoch: proof.epoch,
      identity: proof.identity,
      data: hash(attestedData)
    })

    proof.data = { signature: sign(signable, keyPair) }

    return c.encode(ProofEncoding, proof)
  }

  static async from ({ seed, mnemonic }) {
    const keyChain = await KeyChain.from({ seed, mnemonic })

    return new IdentityKey(keyChain)
  }

  static verify (proof, attestedData, opts = {}) {
    if (b4a.isBuffer(proof)) {
      proof = c.decode(ProofEncoding, proof)
    }

    if (!validateProof(proof, attestedData, opts)) {
      return null
    }

    const { epoch, identity, chain } = proof

    const candidate = getLastKey(chain) || identity

    if (opts.expectedDevice) {
      if (!b4a.equals(candidate, opts.expectedDevice)) return null
    }

    let parent = identity

    // verify chain
    for (let i = 0; i < chain.length; i++) {
      const { publicKey, signature } = chain[i]

      const signable = c.encode(AttestedDevice, {
        epoch,
        identity,
        device: publicKey
      })

      if (!verify(signable, signature, parent)) {
        return null
      }

      parent = publicKey
    }

    if (proof.data) {
      const signable = c.encode(AttestedData, {
        epoch,
        identity,
        data: hash(attestedData)
      })

      if (!verify(signable, proof.data.signature, parent)) {
        return null
      }
    }

    const receipt = c.encode(ReceiptEncoding, { epoch })

    return {
      receipt,
      identityPublicKey: identity,
      devicePublicKey: candidate
    }
  }
}

function validateProof (proof, attestedData, opts = {}) {
  // version 0 is ignored
  if (proof.version === 0) return false

  // validate version
  if (proof.version > PROOF_VERSION) return false

  // verify epoch
  if (opts.receipt) {
    const { epoch } = c.decode(ReceiptEncoding, opts.receipt)
    if (proof.epoch < epoch) return false
  }

  // verify identity
  if (opts.expectedIdentity) {
    if (!b4a.equals(proof.identity, opts.expectedIdentity)) return false
  }

  return validateAttestedData(proof.data, attestedData)
}

function validateAttestedData (data, attestedData) {
  if (!data && attestedData) return false
  return true
}

function getLastKey (chain) {
  if (!chain.length) return null

  const last = chain[chain.length - 1]
  return last.publicKey
}

// slip48 derivations:
// https://github.com/satoshilabs/slips/blob/master/slip-0048.md

function keyPath (accountIndex, index) {
  // https://github.com/bitcoin/bips/blob/master/bip-0043.mediawiki
  const purpose = 48 // SLIP-48 wallet
  const role = 0 // owner

  return [purpose, KEET_TYPE, role, accountIndex, index]
}

// identityKey -> m/48'/keet'/0'/0'

function identityKeyPath (accountIndex) {
  return keyPath(accountIndex, 0)
}

// identityKey -> m/48'/keet'/0'/1'

function discoveryCorePath (accountIndex) {
  return keyPath(accountIndex, 1)
}

// slip21 derivations
// https://github.com/satoshilabs/slips/blob/master/slip-0021.md

function symmetricPath (...path) {
  const purpose = 'SLIP-0021' // SLIP-21 wallet
  const namespace = 'keet-identity-key' // keet

  return [purpose, namespace, ...path]
}

// encryptionKey  -> m/SLIP-10/keet-identity-key/account/"encryption key"

function encryptionKeyPath (profileKey) {
  return symmetricPath(b4a.toString(profileKey, 'hex'), 'encryption key')
}
const sodium = require('sodium-universal')
const b4a = require('b4a')

module.exports = {
  sign,
  verify,
  hash: blake2b
}

function sign (signable, keyPair) {
  const signature = b4a.alloc(sodium.crypto_sign_BYTES)
  sodium.crypto_sign_detached(signature, signable, keyPair.secretKey)

  return signature
}

function verify (signable, signature, publicKey) {
  return sodium.crypto_sign_verify_detached(signature, signable, publicKey)
}

function blake2b (data, output = b4a.alloc(32)) {
  sodium.crypto_generichash(output, data)
  return output
}
const c = require('compact-encoding')

const ATTESTED_DEVICE = 0
const ATTESTED_DATA = 1

const Epoch = {
  preencode (state, e) {
    c.uint64.preencode(state, Math.floor(e / 1000))
  },
  encode (state, e) {
    c.uint64.encode(state, Math.floor(e / 1000))
  },
  decode (state) {
    return c.uint64.decode(state) * 1000
  }
}

const AttestedDevice = {
  preencode (state, a) {
    c.uint8.preencode(state, ATTESTED_DEVICE)
    Epoch.preencode(state, a.epoch)
    c.fixed32.preencode(state, a.identity)
    c.fixed32.preencode(state, a.device)
  },
  encode (state, a) {
    c.uint8.encode(state, ATTESTED_DEVICE)
    Epoch.encode(state, a.epoch)
    c.fixed32.encode(state, a.identity)
    c.fixed32.encode(state, a.device)
  },
  decode (state) {
    throw new Error('Signed data should only be encoded')
  }
}

const AttestedData = {
  preencode (state, a) {
    c.uint8.preencode(state, ATTESTED_DATA)
    Epoch.preencode(state, a.epoch)
    c.fixed32.preencode(state, a.identity)
    c.fixed32.preencode(state, a.data)
  },
  encode (state, a) {
    c.uint8.encode(state, ATTESTED_DATA)
    Epoch.encode(state, a.epoch)
    c.fixed32.encode(state, a.identity)
    c.fixed32.encode(state, a.data)
  },
  decode (state) {
    throw new Error('Signed data should only be encoded')
  }
}

const DeviceAttestation = {
  preencode (state, a) {
    c.fixed32.preencode(state, a.publicKey)
    c.fixed64.preencode(state, a.signature)
  },
  encode (state, a) {
    c.fixed32.encode(state, a.publicKey)
    c.fixed64.encode(state, a.signature)
  },
  decode (state) {
    return {
      publicKey: c.fixed32.decode(state),
      signature: c.fixed64.decode(state)
    }
  }
}

const DeviceAttestationArray = c.array(DeviceAttestation)

const DataAttestation = {
  preencode (state, a) {
    c.fixed64.preencode(state, a.signature)
  },
  encode (state, a) {
    c.fixed64.encode(state, a.signature)
  },
  decode (state) {
    return {
      signature: c.fixed64.decode(state)
    }
  }
}

const ProofEncoding = {
  preencode (state, proof) {
    c.uint.preencode(state, proof.version)
    Epoch.preencode(state, proof.epoch)
    c.fixed32.preencode(state, proof.identity)
    DeviceAttestationArray.preencode(state, proof.chain)

    let flags = 0
    if (proof.data) flags |= 1
    c.uint.preencode(state, flags)

    if (proof.data) DataAttestation.preencode(state, proof.data)
  },
  encode (state, proof) {
    c.uint.encode(state, proof.version)
    Epoch.encode(state, proof.epoch)
    c.fixed32.encode(state, proof.identity)
    DeviceAttestationArray.encode(state, proof.chain)

    let flags = 0
    if (proof.data) flags |= 1
    c.uint.encode(state, flags)

    if (proof.data) DataAttestation.encode(state, proof.data)
  },
  decode (state) {
    const version = c.uint.decode(state)

    // ignore v0 proofs
    if (version === 0) {
      return {
        version: 0,
        epoch: 0,
        identity: null,
        chain: [],
        data: null
      }
    }

    const epoch = Epoch.decode(state)
    const identity = c.fixed32.decode(state)
    const chain = DeviceAttestationArray.decode(state)

    const flags = c.uint.decode(state)
    const data = flags & 1 ? DataAttestation.decode(state) : null

    return {
      version,
      epoch,
      identity,
      chain,
      data
    }
  }
}

const ReceiptEncoding = {
  preencode (state, receipt) {
    Epoch.preencode(state, receipt.epoch)
  },
  encode (state, receipt) {
    Epoch.encode(state, receipt.epoch)
  },
  decode (state) {
    return {
      epoch: Epoch.decode(state)
    }
  }
}

module.exports = {
  ATTESTED_DEVICE,
  ATTESTED_DATA,
  AttestedDevice,
  AttestedData,
  ProofEncoding,
  ReceiptEncoding
}
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const assert = require('nanoassert')
const b4a = require('b4a')
const { HMAC } = require('sodium-hmac')
const bip39 = require('bip39-mnemonic')

const { sign } = require('./crypto')

const MASTER_CHAIN_CODE = b4a.from('ed25519 seed')
const MASTER_SYMMETRIC_CODE = b4a.from('Symmetric key seed')

const HARDENED_OFFSET = 0x80000000

class KeyChain {
  constructor (seed) {
    this.seed = seed

    this._buffer = b4a.alloc(64)

    this.chainKey = this._buffer.subarray(0, 32)
    this.chainCode = this._buffer.subarray(32)

    this.publicKey = b4a.alloc(sodium.crypto_sign_PUBLICKEYBYTES)
    this.secretKey = b4a.alloc(sodium.crypto_sign_SECRETKEYBYTES)

    this._initialise()
  }

  static generateMnemonic () {
    return bip39.generateMnemonic()
  }

  static deriveSeed (mnemonic) {
    return bip39.mnemonicToSeed(mnemonic)
  }

  static async from ({ mnemonic, seed }, path) {
    assert(mnemonic || seed, 'No mnemonic or seed was passed.')

    if (!seed) seed = await KeyChain.deriveSeed(mnemonic)

    const key = new KeyChain(seed)

    if (!path) return key

    return key.get(path)
  }

  getSymmetricKey (path) {
    const buffer = b4a.alloc(64)

    const chainKey = buffer.subarray(0, 32)
    const key = buffer.subarray(32)

    HMAC.sha512(this.seed, MASTER_SYMMETRIC_CODE, buffer)

    for (const step of path) {
      const label = b4a.alloc(step.length + 1)
      b4a.write(label, step, 1, 'utf8')

      HMAC.sha512(label, chainKey, buffer)
    }

    return key
  }

  get isKeychain () {
    return true
  }

  _initialise () {
    HMAC.sha512(this.seed, MASTER_CHAIN_CODE, this._buffer)
    sodium.crypto_sign_seed_keypair(this.publicKey, this.secretKey, this.chainKey)
  }

  clear () {
    this.secretKey.fill(0)
    this.chainKey.fill(0)
    this.chainCode.fill(0)
  }

  get (path) {
    return this.derive(path)
  }

  sign (signable) {
    return sign(signable, this)
  }

  derive (path) {
    const buffer = b4a.from(this._buffer)

    const chainKey = buffer.subarray(0, 32)
    const chainCode = buffer.subarray(32)

    for (const step of path) {
      const index = ensureHardened(step) // hardened indices are >= 2^31
      HMAC.sha512(encodeDerivationData(chainKey, index), chainCode, buffer)
    }

    return createKeyPair(chainKey)
  }
}

module.exports = KeyChain

function createKeyPair (seed) {
  if (!seed) throw new Error('No seed provided')

  const publicKey = b4a.alloc(sodium.crypto_sign_PUBLICKEYBYTES)
  const secretKey = b4a.alloc(sodium.crypto_sign_SECRETKEYBYTES)

  sodium.crypto_sign_seed_keypair(publicKey, secretKey, seed)

  return {
    publicKey,
    secretKey
  }
}

function encodeDerivationData (key, step) {
  const state = { buffer: b4a.alloc(37), start: 0, end: 37 }

  c.uint8.encode(state, 0)
  c.fixed32.encode(state, key)
  state.buffer.writeUInt32BE(step, state.start)

  state.buffer[33] |= 0x80

  return state.buffer
}

function ensureHardened (n) {
  if (n >= HARDENED_OFFSET) return n
  return n + HARDENED_OFFSET
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "keet-identity-key",
  "version": "3.2.0",
  "description": "Hierarchical Deterministic Keys for Keet Identities",
  "main": "index.js",
  "scripts": {
    "test": "standard && brittle test/*.js"
  },
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "devDependencies": {
    "brittle": "^3.3.2",
    "hypercore-crypto": "^3.4.0",
    "standard": "^17.1.0"
  },
  "dependencies": {
    "b4a": "^1.6.4",
    "bip39-mnemonic": "^2.2.0",
    "compact-encoding": "^3.0.0",
    "nanoassert": "^2.0.0",
    "sodium-hmac": "^2.0.1",
    "sodium-universal": "^5.0.1"
  },
  "files": [
    "lib/*"
  ],
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/keet-identity-key.git"
  },
  "bugs": {
    "url": "https://github.com/holepunchto/keet-identity-key/issues"
  },
  "homepage": "https://github.com/holepunchto/keet-identity-key#readme"
}
import { coerce } from '../bytes.js';
import basex from '../vendor/base-x.js';
/**
 * Class represents both BaseEncoder and MultibaseEncoder meaning it
 * can be used to encode to multibase or base encode without multibase
 * prefix.
 */
class Encoder {
    name;
    prefix;
    baseEncode;
    constructor(name, prefix, baseEncode) {
        this.name = name;
        this.prefix = prefix;
        this.baseEncode = baseEncode;
    }
    encode(bytes) {
        if (bytes instanceof Uint8Array) {
            return `${this.prefix}${this.baseEncode(bytes)}`;
        }
        else {
            throw Error('Unknown type, must be binary type');
        }
    }
}
/**
 * Class represents both BaseDecoder and MultibaseDecoder so it could be used
 * to decode multibases (with matching prefix) or just base decode strings
 * with corresponding base encoding.
 */
class Decoder {
    name;
    prefix;
    baseDecode;
    prefixCodePoint;
    constructor(name, prefix, baseDecode) {
        this.name = name;
        this.prefix = prefix;
        const prefixCodePoint = prefix.codePointAt(0);
        /* c8 ignore next 3 */
        if (prefixCodePoint === undefined) {
            throw new Error('Invalid prefix character');
        }
        this.prefixCodePoint = prefixCodePoint;
        this.baseDecode = baseDecode;
    }
    decode(text) {
        if (typeof text === 'string') {
            if (text.codePointAt(0) !== this.prefixCodePoint) {
                throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);
            }
            return this.baseDecode(text.slice(this.prefix.length));
        }
        else {
            throw Error('Can only multibase decode strings');
        }
    }
    or(decoder) {
        return or(this, decoder);
    }
}
class ComposedDecoder {
    decoders;
    constructor(decoders) {
        this.decoders = decoders;
    }
    or(decoder) {
        return or(this, decoder);
    }
    decode(input) {
        const prefix = input[0];
        const decoder = this.decoders[prefix];
        if (decoder != null) {
            return decoder.decode(input);
        }
        else {
            throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);
        }
    }
}
export function or(left, right) {
    return new ComposedDecoder({
        ...(left.decoders ?? { [left.prefix]: left }),
        ...(right.decoders ?? { [right.prefix]: right })
    });
}
export class Codec {
    name;
    prefix;
    baseEncode;
    baseDecode;
    encoder;
    decoder;
    constructor(name, prefix, baseEncode, baseDecode) {
        this.name = name;
        this.prefix = prefix;
        this.baseEncode = baseEncode;
        this.baseDecode = baseDecode;
        this.encoder = new Encoder(name, prefix, baseEncode);
        this.decoder = new Decoder(name, prefix, baseDecode);
    }
    encode(input) {
        return this.encoder.encode(input);
    }
    decode(input) {
        return this.decoder.decode(input);
    }
}
export function from({ name, prefix, encode, decode }) {
    return new Codec(name, prefix, encode, decode);
}
export function baseX({ name, prefix, alphabet }) {
    const { encode, decode } = basex(alphabet, name);
    return from({
        prefix,
        name,
        encode,
        decode: (text) => coerce(decode(text))
    });
}
function decode(string, alphabetIdx, bitsPerChar, name) {
    // Count the padding bytes:
    let end = string.length;
    while (string[end - 1] === '=') {
        --end;
    }
    // Allocate the output:
    const out = new Uint8Array((end * bitsPerChar / 8) | 0);
    // Parse the data:
    let bits = 0; // Number of bits currently in the buffer
    let buffer = 0; // Bits waiting to be written out, MSB first
    let written = 0; // Next byte to write
    for (let i = 0; i < end; ++i) {
        // Read one character from the string:
        const value = alphabetIdx[string[i]];
        if (value === undefined) {
            throw new SyntaxError(`Non-${name} character`);
        }
        // Append the bits to the buffer:
        buffer = (buffer << bitsPerChar) | value;
        bits += bitsPerChar;
        // Write out some bits if the buffer has a byte's worth:
        if (bits >= 8) {
            bits -= 8;
            out[written++] = 0xff & (buffer >> bits);
        }
    }
    // Verify that we have received just enough bits:
    if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {
        throw new SyntaxError('Unexpected end of data');
    }
    return out;
}
function encode(data, alphabet, bitsPerChar) {
    const pad = alphabet[alphabet.length - 1] === '=';
    const mask = (1 << bitsPerChar) - 1;
    let out = '';
    let bits = 0; // Number of bits currently in the buffer
    let buffer = 0; // Bits waiting to be written out, MSB first
    for (let i = 0; i < data.length; ++i) {
        // Slurp data into the buffer:
        buffer = (buffer << 8) | data[i];
        bits += 8;
        // Write out as much as we can:
        while (bits > bitsPerChar) {
            bits -= bitsPerChar;
            out += alphabet[mask & (buffer >> bits)];
        }
    }
    // Partial character:
    if (bits !== 0) {
        out += alphabet[mask & (buffer << (bitsPerChar - bits))];
    }
    // Add padding characters until we hit a byte boundary:
    if (pad) {
        while (((out.length * bitsPerChar) & 7) !== 0) {
            out += '=';
        }
    }
    return out;
}
function createAlphabetIdx(alphabet) {
    // Build the character lookup table:
    const alphabetIdx = {};
    for (let i = 0; i < alphabet.length; ++i) {
        alphabetIdx[alphabet[i]] = i;
    }
    return alphabetIdx;
}
/**
 * RFC4648 Factory
 */
export function rfc4648({ name, prefix, bitsPerChar, alphabet }) {
    const alphabetIdx = createAlphabetIdx(alphabet);
    return from({
        prefix,
        name,
        encode(input) {
            return encode(input, alphabet, bitsPerChar);
        },
        decode(input) {
            return decode(input, alphabetIdx, bitsPerChar, name);
        }
    });
}
//# sourceMappingURL=base.js.mapimport { rfc4648 } from './base.js';
export const base32 = rfc4648({
    prefix: 'b',
    name: 'base32',
    alphabet: 'abcdefghijklmnopqrstuvwxyz234567',
    bitsPerChar: 5
});
export const base32upper = rfc4648({
    prefix: 'B',
    name: 'base32upper',
    alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',
    bitsPerChar: 5
});
export const base32pad = rfc4648({
    prefix: 'c',
    name: 'base32pad',
    alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',
    bitsPerChar: 5
});
export const base32padupper = rfc4648({
    prefix: 'C',
    name: 'base32padupper',
    alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',
    bitsPerChar: 5
});
export const base32hex = rfc4648({
    prefix: 'v',
    name: 'base32hex',
    alphabet: '0123456789abcdefghijklmnopqrstuv',
    bitsPerChar: 5
});
export const base32hexupper = rfc4648({
    prefix: 'V',
    name: 'base32hexupper',
    alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',
    bitsPerChar: 5
});
export const base32hexpad = rfc4648({
    prefix: 't',
    name: 'base32hexpad',
    alphabet: '0123456789abcdefghijklmnopqrstuv=',
    bitsPerChar: 5
});
export const base32hexpadupper = rfc4648({
    prefix: 'T',
    name: 'base32hexpadupper',
    alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',
    bitsPerChar: 5
});
export const base32z = rfc4648({
    prefix: 'h',
    name: 'base32z',
    alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',
    bitsPerChar: 5
});
//# sourceMappingURL=base32.js.mapimport { baseX } from './base.js';
export const base36 = baseX({
    prefix: 'k',
    name: 'base36',
    alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'
});
export const base36upper = baseX({
    prefix: 'K',
    name: 'base36upper',
    alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
});
//# sourceMappingURL=base36.js.mapimport { baseX } from './base.js';
export const base58btc = baseX({
    name: 'base58btc',
    prefix: 'z',
    alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
});
export const base58flickr = baseX({
    name: 'base58flickr',
    prefix: 'Z',
    alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'
});
//# sourceMappingURL=base58.js.mapexport const empty = new Uint8Array(0);
export function toHex(d) {
    return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '');
}
export function fromHex(hex) {
    const hexes = hex.match(/../g);
    return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty;
}
export function equals(aa, bb) {
    if (aa === bb) {
        return true;
    }
    if (aa.byteLength !== bb.byteLength) {
        return false;
    }
    for (let ii = 0; ii < aa.byteLength; ii++) {
        if (aa[ii] !== bb[ii]) {
            return false;
        }
    }
    return true;
}
export function coerce(o) {
    if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') {
        return o;
    }
    if (o instanceof ArrayBuffer) {
        return new Uint8Array(o);
    }
    if (ArrayBuffer.isView(o)) {
        return new Uint8Array(o.buffer, o.byteOffset, o.byteLength);
    }
    throw new Error('Unknown type, must be binary type');
}
export function isBinary(o) {
    return o instanceof ArrayBuffer || ArrayBuffer.isView(o);
}
export function fromString(str) {
    return new TextEncoder().encode(str);
}
export function toString(b) {
    return new TextDecoder().decode(b);
}
//# sourceMappingURL=bytes.js.mapimport { base32 } from './bases/base32.js';
import { base36 } from './bases/base36.js';
import { base58btc } from './bases/base58.js';
import { coerce } from './bytes.js';
import * as Digest from './hashes/digest.js';
import * as varint from './varint.js';
// This way TS will also expose all the types from module
export * from './link/interface.js';
export function format(link, base) {
    const { bytes, version } = link;
    switch (version) {
        case 0:
            return toStringV0(bytes, baseCache(link), base ?? base58btc.encoder);
        default:
            return toStringV1(bytes, baseCache(link), (base ?? base32.encoder));
    }
}
export function toJSON(link) {
    return {
        '/': format(link)
    };
}
export function fromJSON(json) {
    return CID.parse(json['/']);
}
const cache = new WeakMap();
function baseCache(cid) {
    const baseCache = cache.get(cid);
    if (baseCache == null) {
        const baseCache = new Map();
        cache.set(cid, baseCache);
        return baseCache;
    }
    return baseCache;
}
export class CID {
    code;
    version;
    multihash;
    bytes;
    '/';
    /**
     * @param version - Version of the CID
     * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
     * @param multihash - (Multi)hash of the of the content.
     */
    constructor(version, code, multihash, bytes) {
        this.code = code;
        this.version = version;
        this.multihash = multihash;
        this.bytes = bytes;
        // flag to serializers that this is a CID and
        // should be treated specially
        this['/'] = bytes;
    }
    /**
     * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`
     * please either use `CID.asCID(cid)` or switch to new signalling mechanism
     *
     * @deprecated
     */
    get asCID() {
        return this;
    }
    // ArrayBufferView
    get byteOffset() {
        return this.bytes.byteOffset;
    }
    // ArrayBufferView
    get byteLength() {
        return this.bytes.byteLength;
    }
    toV0() {
        switch (this.version) {
            case 0: {
                return this;
            }
            case 1: {
                const { code, multihash } = this;
                if (code !== DAG_PB_CODE) {
                    throw new Error('Cannot convert a non dag-pb CID to CIDv0');
                }
                // sha2-256
                if (multihash.code !== SHA_256_CODE) {
                    throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0');
                }
                return (CID.createV0(multihash));
            }
            default: {
                throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);
            }
        }
    }
    toV1() {
        switch (this.version) {
            case 0: {
                const { code, digest } = this.multihash;
                const multihash = Digest.create(code, digest);
                return (CID.createV1(this.code, multihash));
            }
            case 1: {
                return this;
            }
            default: {
                throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);
            }
        }
    }
    equals(other) {
        return CID.equals(this, other);
    }
    static equals(self, other) {
        const unknown = other;
        return (unknown != null &&
            self.code === unknown.code &&
            self.version === unknown.version &&
            Digest.equals(self.multihash, unknown.multihash));
    }
    toString(base) {
        return format(this, base);
    }
    toJSON() {
        return { '/': format(this) };
    }
    link() {
        return this;
    }
    [Symbol.toStringTag] = 'CID';
    // Legacy
    [Symbol.for('nodejs.util.inspect.custom')]() {
        return `CID(${this.toString()})`;
    }
    /**
     * Takes any input `value` and returns a `CID` instance if it was
     * a `CID` otherwise returns `null`. If `value` is instanceof `CID`
     * it will return value back. If `value` is not instance of this CID
     * class, but is compatible CID it will return new instance of this
     * `CID` class. Otherwise returns null.
     *
     * This allows two different incompatible versions of CID library to
     * co-exist and interop as long as binary interface is compatible.
     */
    static asCID(input) {
        if (input == null) {
            return null;
        }
        const value = input;
        if (value instanceof CID) {
            // If value is instance of CID then we're all set.
            return value;
        }
        else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {
            // If value isn't instance of this CID class but `this.asCID === this` or
            // `value['/'] === value.bytes` is true it is CID instance coming from a
            // different implementation (diff version or duplicate). In that case we
            // rebase it to this `CID` implementation so caller is guaranteed to get
            // instance with expected API.
            const { version, code, multihash, bytes } = value;
            return new CID(version, code, multihash, bytes ?? encodeCID(version, code, multihash.bytes));
        }
        else if (value[cidSymbol] === true) {
            // If value is a CID from older implementation that used to be tagged via
            // symbol we still rebase it to the this `CID` implementation by
            // delegating that to a constructor.
            const { version, multihash, code } = value;
            const digest = Digest.decode(multihash);
            return CID.create(version, code, digest);
        }
        else {
            // Otherwise value is not a CID (or an incompatible version of it) in
            // which case we return `null`.
            return null;
        }
    }
    /**
     * @param version - Version of the CID
     * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
     * @param digest - (Multi)hash of the of the content.
     */
    static create(version, code, digest) {
        if (typeof code !== 'number') {
            throw new Error('String codecs are no longer supported');
        }
        if (!(digest.bytes instanceof Uint8Array)) {
            throw new Error('Invalid digest');
        }
        switch (version) {
            case 0: {
                if (code !== DAG_PB_CODE) {
                    throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);
                }
                else {
                    return new CID(version, code, digest, digest.bytes);
                }
            }
            case 1: {
                const bytes = encodeCID(version, code, digest.bytes);
                return new CID(version, code, digest, bytes);
            }
            default: {
                throw new Error('Invalid version');
            }
        }
    }
    /**
     * Simplified version of `create` for CIDv0.
     */
    static createV0(digest) {
        return CID.create(0, DAG_PB_CODE, digest);
    }
    /**
     * Simplified version of `create` for CIDv1.
     *
     * @param code - Content encoding format code.
     * @param digest - Multihash of the content.
     */
    static createV1(code, digest) {
        return CID.create(1, code, digest);
    }
    /**
     * Decoded a CID from its binary representation. The byte array must contain
     * only the CID with no additional bytes.
     *
     * An error will be thrown if the bytes provided do not contain a valid
     * binary representation of a CID.
     */
    static decode(bytes) {
        const [cid, remainder] = CID.decodeFirst(bytes);
        if (remainder.length !== 0) {
            throw new Error('Incorrect length');
        }
        return cid;
    }
    /**
     * Decoded a CID from its binary representation at the beginning of a byte
     * array.
     *
     * Returns an array with the first element containing the CID and the second
     * element containing the remainder of the original byte array. The remainder
     * will be a zero-length byte array if the provided bytes only contained a
     * binary CID representation.
     */
    static decodeFirst(bytes) {
        const specs = CID.inspectBytes(bytes);
        const prefixSize = specs.size - specs.multihashSize;
        const multihashBytes = coerce(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));
        if (multihashBytes.byteLength !== specs.multihashSize) {
            throw new Error('Incorrect length');
        }
        const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);
        const digest = new Digest.Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);
        const cid = specs.version === 0
            ? CID.createV0(digest)
            : CID.createV1(specs.codec, digest);
        return [cid, bytes.subarray(specs.size)];
    }
    /**
     * Inspect the initial bytes of a CID to determine its properties.
     *
     * Involves decoding up to 4 varints. Typically this will require only 4 to 6
     * bytes but for larger multicodec code values and larger multihash digest
     * lengths these varints can be quite large. It is recommended that at least
     * 10 bytes be made available in the `initialBytes` argument for a complete
     * inspection.
     */
    static inspectBytes(initialBytes) {
        let offset = 0;
        const next = () => {
            const [i, length] = varint.decode(initialBytes.subarray(offset));
            offset += length;
            return i;
        };
        let version = next();
        let codec = DAG_PB_CODE;
        if (version === 18) {
            // CIDv0
            version = 0;
            offset = 0;
        }
        else {
            codec = next();
        }
        if (version !== 0 && version !== 1) {
            throw new RangeError(`Invalid CID version ${version}`);
        }
        const prefixSize = offset;
        const multihashCode = next(); // multihash code
        const digestSize = next(); // multihash length
        const size = offset + digestSize;
        const multihashSize = size - prefixSize;
        return { version, codec, multihashCode, digestSize, multihashSize, size };
    }
    /**
     * Takes cid in a string representation and creates an instance. If `base`
     * decoder is not provided will use a default from the configuration. It will
     * throw an error if encoding of the CID is not compatible with supplied (or
     * a default decoder).
     */
    static parse(source, base) {
        const [prefix, bytes] = parseCIDtoBytes(source, base);
        const cid = CID.decode(bytes);
        if (cid.version === 0 && source[0] !== 'Q') {
            throw Error('Version 0 CID string must not include multibase prefix');
        }
        // Cache string representation to avoid computing it on `this.toString()`
        baseCache(cid).set(prefix, source);
        return cid;
    }
}
function parseCIDtoBytes(source, base) {
    switch (source[0]) {
        // CIDv0 is parsed differently
        case 'Q': {
            const decoder = base ?? base58btc;
            return [
                base58btc.prefix,
                decoder.decode(`${base58btc.prefix}${source}`)
            ];
        }
        case base58btc.prefix: {
            const decoder = base ?? base58btc;
            return [base58btc.prefix, decoder.decode(source)];
        }
        case base32.prefix: {
            const decoder = base ?? base32;
            return [base32.prefix, decoder.decode(source)];
        }
        case base36.prefix: {
            const decoder = base ?? base36;
            return [base36.prefix, decoder.decode(source)];
        }
        default: {
            if (base == null) {
                throw Error('To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided');
            }
            return [source[0], base.decode(source)];
        }
    }
}
function toStringV0(bytes, cache, base) {
    const { prefix } = base;
    if (prefix !== base58btc.prefix) {
        throw Error(`Cannot string encode V0 in ${base.name} encoding`);
    }
    const cid = cache.get(prefix);
    if (cid == null) {
        const cid = base.encode(bytes).slice(1);
        cache.set(prefix, cid);
        return cid;
    }
    else {
        return cid;
    }
}
function toStringV1(bytes, cache, base) {
    const { prefix } = base;
    const cid = cache.get(prefix);
    if (cid == null) {
        const cid = base.encode(bytes);
        cache.set(prefix, cid);
        return cid;
    }
    else {
        return cid;
    }
}
const DAG_PB_CODE = 0x70;
const SHA_256_CODE = 0x12;
function encodeCID(version, code, multihash) {
    const codeOffset = varint.encodingLength(version);
    const hashOffset = codeOffset + varint.encodingLength(code);
    const bytes = new Uint8Array(hashOffset + multihash.byteLength);
    varint.encodeTo(version, bytes, 0);
    varint.encodeTo(code, bytes, codeOffset);
    bytes.set(multihash, hashOffset);
    return bytes;
}
const cidSymbol = Symbol.for('@ipld/js-cid/CID');
//# sourceMappingURL=cid.js.mapimport { coerce, equals as equalBytes } from '../bytes.js';
import * as varint from '../varint.js';
/**
 * Creates a multihash digest.
 */
export function create(code, digest) {
    const size = digest.byteLength;
    const sizeOffset = varint.encodingLength(code);
    const digestOffset = sizeOffset + varint.encodingLength(size);
    const bytes = new Uint8Array(digestOffset + size);
    varint.encodeTo(code, bytes, 0);
    varint.encodeTo(size, bytes, sizeOffset);
    bytes.set(digest, digestOffset);
    return new Digest(code, size, digest, bytes);
}
/**
 * Turns bytes representation of multihash digest into an instance.
 */
export function decode(multihash) {
    const bytes = coerce(multihash);
    const [code, sizeOffset] = varint.decode(bytes);
    const [size, digestOffset] = varint.decode(bytes.subarray(sizeOffset));
    const digest = bytes.subarray(sizeOffset + digestOffset);
    if (digest.byteLength !== size) {
        throw new Error('Incorrect length');
    }
    return new Digest(code, size, digest, bytes);
}
export function equals(a, b) {
    if (a === b) {
        return true;
    }
    else {
        const data = b;
        return (a.code === data.code &&
            a.size === data.size &&
            data.bytes instanceof Uint8Array &&
            equalBytes(a.bytes, data.bytes));
    }
}
/**
 * Represents a multihash digest which carries information about the
 * hashing algorithm and an actual hash digest.
 */
export class Digest {
    code;
    size;
    digest;
    bytes;
    /**
     * Creates a multihash digest.
     */
    constructor(code, size, digest, bytes) {
        this.code = code;
        this.size = size;
        this.digest = digest;
        this.bytes = bytes;
    }
}
/**
 * Used to check that the passed multihash has the passed code
 */
export function hasCode(digest, code) {
    return digest.code === code;
}
//# sourceMappingURL=digest.js.mapexport {};
//# sourceMappingURL=interface.js.mapimport varint from './vendor/varint.js';
export function decode(data, offset = 0) {
    const code = varint.decode(data, offset);
    return [code, varint.decode.bytes];
}
export function encodeTo(int, target, offset = 0) {
    varint.encode(int, target, offset);
    return target;
}
export function encodingLength(int) {
    return varint.encodingLength(int);
}
//# sourceMappingURL=varint.js.map/* eslint-disable */
// base-x encoding / decoding
// Copyright (c) 2018 base-x contributors
// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)
// Distributed under the MIT software license, see the accompanying
// file LICENSE or http://www.opensource.org/licenses/mit-license.php.
/**
 * @param {string} ALPHABET
 * @param {any} name
 */
function base(ALPHABET, name) {
    if (ALPHABET.length >= 255) {
        throw new TypeError('Alphabet too long');
    }
    var BASE_MAP = new Uint8Array(256);
    for (var j = 0; j < BASE_MAP.length; j++) {
        BASE_MAP[j] = 255;
    }
    for (var i = 0; i < ALPHABET.length; i++) {
        var x = ALPHABET.charAt(i);
        var xc = x.charCodeAt(0);
        if (BASE_MAP[xc] !== 255) {
            throw new TypeError(x + ' is ambiguous');
        }
        BASE_MAP[xc] = i;
    }
    var BASE = ALPHABET.length;
    var LEADER = ALPHABET.charAt(0);
    var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up
    var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up
    /**
     * @param {any[] | Iterable<number>} source
     */
    function encode(source) {
        // @ts-ignore
        if (source instanceof Uint8Array)
            ;
        else if (ArrayBuffer.isView(source)) {
            source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
        }
        else if (Array.isArray(source)) {
            source = Uint8Array.from(source);
        }
        if (!(source instanceof Uint8Array)) {
            throw new TypeError('Expected Uint8Array');
        }
        if (source.length === 0) {
            return '';
        }
        // Skip & count leading zeroes.
        var zeroes = 0;
        var length = 0;
        var pbegin = 0;
        var pend = source.length;
        while (pbegin !== pend && source[pbegin] === 0) {
            pbegin++;
            zeroes++;
        }
        // Allocate enough space in big-endian base58 representation.
        var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;
        var b58 = new Uint8Array(size);
        // Process the bytes.
        while (pbegin !== pend) {
            var carry = source[pbegin];
            // Apply "b58 = b58 * 256 + ch".
            var i = 0;
            for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {
                carry += (256 * b58[it1]) >>> 0;
                b58[it1] = (carry % BASE) >>> 0;
                carry = (carry / BASE) >>> 0;
            }
            if (carry !== 0) {
                throw new Error('Non-zero carry');
            }
            length = i;
            pbegin++;
        }
        // Skip leading zeroes in base58 result.
        var it2 = size - length;
        while (it2 !== size && b58[it2] === 0) {
            it2++;
        }
        // Translate the result into a string.
        var str = LEADER.repeat(zeroes);
        for (; it2 < size; ++it2) {
            str += ALPHABET.charAt(b58[it2]);
        }
        return str;
    }
    /**
     * @param {string | string[]} source
     */
    function decodeUnsafe(source) {
        if (typeof source !== 'string') {
            throw new TypeError('Expected String');
        }
        if (source.length === 0) {
            return new Uint8Array();
        }
        var psz = 0;
        // Skip leading spaces.
        if (source[psz] === ' ') {
            return;
        }
        // Skip and count leading '1's.
        var zeroes = 0;
        var length = 0;
        while (source[psz] === LEADER) {
            zeroes++;
            psz++;
        }
        // Allocate enough space in big-endian base256 representation.
        var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.
        var b256 = new Uint8Array(size);
        // Process the characters.
        while (source[psz]) {
            // Decode character
            var carry = BASE_MAP[source.charCodeAt(psz)];
            // Invalid character
            if (carry === 255) {
                return;
            }
            var i = 0;
            for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {
                carry += (BASE * b256[it3]) >>> 0;
                b256[it3] = (carry % 256) >>> 0;
                carry = (carry / 256) >>> 0;
            }
            if (carry !== 0) {
                throw new Error('Non-zero carry');
            }
            length = i;
            psz++;
        }
        // Skip trailing spaces.
        if (source[psz] === ' ') {
            return;
        }
        // Skip leading zeroes in b256.
        var it4 = size - length;
        while (it4 !== size && b256[it4] === 0) {
            it4++;
        }
        var vch = new Uint8Array(zeroes + (size - it4));
        var j = zeroes;
        while (it4 !== size) {
            vch[j++] = b256[it4++];
        }
        return vch;
    }
    /**
     * @param {string | string[]} string
     */
    function decode(string) {
        var buffer = decodeUnsafe(string);
        if (buffer) {
            return buffer;
        }
        throw new Error(`Non-${name} character`);
    }
    return {
        encode: encode,
        decodeUnsafe: decodeUnsafe,
        decode: decode
    };
}
var src = base;
var _brrp__multiformats_scope_baseX = src;
export default _brrp__multiformats_scope_baseX;
//# sourceMappingURL=base-x.js.map/* eslint-disable */
var encode_1 = encode;
var MSB = 0x80, REST = 0x7F, MSBALL = ~REST, INT = Math.pow(2, 31);
/**
 * @param {number} num
 * @param {number[]} out
 * @param {number} offset
 */
function encode(num, out, offset) {
    out = out || [];
    offset = offset || 0;
    var oldOffset = offset;
    while (num >= INT) {
        out[offset++] = (num & 0xFF) | MSB;
        num /= 128;
    }
    while (num & MSBALL) {
        out[offset++] = (num & 0xFF) | MSB;
        num >>>= 7;
    }
    out[offset] = num | 0;
    // @ts-ignore
    encode.bytes = offset - oldOffset + 1;
    return out;
}
var decode = read;
var MSB$1 = 0x80, REST$1 = 0x7F;
/**
 * @param {string | any[]} buf
 * @param {number} offset
 */
function read(buf, offset) {
    var res = 0, offset = offset || 0, shift = 0, counter = offset, b, l = buf.length;
    do {
        if (counter >= l) {
            // @ts-ignore
            read.bytes = 0;
            throw new RangeError('Could not decode varint');
        }
        b = buf[counter++];
        res += shift < 28
            ? (b & REST$1) << shift
            : (b & REST$1) * Math.pow(2, shift);
        shift += 7;
    } while (b >= MSB$1);
    // @ts-ignore
    read.bytes = counter - offset;
    return res;
}
var N1 = Math.pow(2, 7);
var N2 = Math.pow(2, 14);
var N3 = Math.pow(2, 21);
var N4 = Math.pow(2, 28);
var N5 = Math.pow(2, 35);
var N6 = Math.pow(2, 42);
var N7 = Math.pow(2, 49);
var N8 = Math.pow(2, 56);
var N9 = Math.pow(2, 63);
var length = function (/** @type {number} */ value) {
    return (value < N1 ? 1
        : value < N2 ? 2
            : value < N3 ? 3
                : value < N4 ? 4
                    : value < N5 ? 5
                        : value < N6 ? 6
                            : value < N7 ? 7
                                : value < N8 ? 8
                                    : value < N9 ? 9
                                        : 10);
};
var varint = {
    encode: encode_1,
    decode: decode,
    encodingLength: length
};
var _brrp_varint = varint;
export default _brrp_varint;
//# sourceMappingURL=varint.js.map{
  "name": "multiformats",
  "version": "13.4.2",
  "description": "Interface for multihash, multicodec, multibase and CID",
  "author": "Mikeal Rogers <mikeal.rogers@gmail.com> (https://www.mikealrogers.com/)",
  "license": "Apache-2.0 OR MIT",
  "homepage": "https://github.com/multiformats/js-multiformats#readme",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/multiformats/js-multiformats.git"
  },
  "bugs": {
    "url": "https://github.com/multiformats/js-multiformats/issues"
  },
  "publishConfig": {
    "access": "public",
    "provenance": true
  },
  "keywords": [
    "ipfs",
    "ipld",
    "multiformats"
  ],
  "type": "module",
  "types": "./dist/src/index.d.ts",
  "typesVersions": {
    "*": {
      "*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ],
      "src/*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ]
    }
  },
  "files": [
    "src",
    "dist",
    "!dist/test",
    "!**/*.tsbuildinfo"
  ],
  "exports": {
    ".": {
      "types": "./dist/src/index.d.ts",
      "import": "./dist/src/index.js"
    },
    "./bases/base10": {
      "types": "./dist/src/bases/base10.d.ts",
      "import": "./dist/src/bases/base10.js"
    },
    "./bases/base16": {
      "types": "./dist/src/bases/base16.d.ts",
      "import": "./dist/src/bases/base16.js"
    },
    "./bases/base2": {
      "types": "./dist/src/bases/base2.d.ts",
      "import": "./dist/src/bases/base2.js"
    },
    "./bases/base256emoji": {
      "types": "./dist/src/bases/base256emoji.d.ts",
      "import": "./dist/src/bases/base256emoji.js"
    },
    "./bases/base32": {
      "types": "./dist/src/bases/base32.d.ts",
      "import": "./dist/src/bases/base32.js"
    },
    "./bases/base36": {
      "types": "./dist/src/bases/base36.d.ts",
      "import": "./dist/src/bases/base36.js"
    },
    "./bases/base58": {
      "types": "./dist/src/bases/base58.d.ts",
      "import": "./dist/src/bases/base58.js"
    },
    "./bases/base64": {
      "types": "./dist/src/bases/base64.d.ts",
      "import": "./dist/src/bases/base64.js"
    },
    "./bases/base8": {
      "types": "./dist/src/bases/base8.d.ts",
      "import": "./dist/src/bases/base8.js"
    },
    "./bases/identity": {
      "types": "./dist/src/bases/identity.d.ts",
      "import": "./dist/src/bases/identity.js"
    },
    "./bases/interface": {
      "types": "./dist/src/bases/interface.d.ts",
      "import": "./dist/src/bases/interface.js"
    },
    "./basics": {
      "types": "./dist/src/basics.d.ts",
      "import": "./dist/src/basics.js"
    },
    "./block": {
      "types": "./dist/src/block.d.ts",
      "import": "./dist/src/block.js"
    },
    "./block/interface": {
      "types": "./dist/src/block/interface.d.ts",
      "import": "./dist/src/block/interface.js"
    },
    "./bytes": {
      "types": "./dist/src/bytes.d.ts",
      "import": "./dist/src/bytes.js"
    },
    "./cid": {
      "types": "./dist/src/cid.d.ts",
      "import": "./dist/src/cid.js"
    },
    "./codecs/interface": {
      "types": "./dist/src/codecs/interface.d.ts",
      "import": "./dist/src/codecs/interface.js"
    },
    "./codecs/json": {
      "types": "./dist/src/codecs/json.d.ts",
      "import": "./dist/src/codecs/json.js"
    },
    "./codecs/raw": {
      "types": "./dist/src/codecs/raw.d.ts",
      "import": "./dist/src/codecs/raw.js"
    },
    "./hashes/digest": {
      "types": "./dist/src/hashes/digest.d.ts",
      "import": "./dist/src/hashes/digest.js"
    },
    "./hashes/hasher": {
      "types": "./dist/src/hashes/hasher.d.ts",
      "import": "./dist/src/hashes/hasher.js"
    },
    "./hashes/identity": {
      "types": "./dist/src/hashes/identity.d.ts",
      "import": "./dist/src/hashes/identity.js"
    },
    "./hashes/interface": {
      "types": "./dist/src/hashes/interface.d.ts",
      "import": "./dist/src/hashes/interface.js"
    },
    "./hashes/sha1": {
      "types": "./dist/types/src/hashes/sha1.d.ts",
      "browser": "./dist/src/hashes/sha1-browser.js",
      "import": "./dist/src/hashes/sha1.js"
    },
    "./hashes/sha2": {
      "types": "./dist/src/hashes/sha2.d.ts",
      "browser": "./dist/src/hashes/sha2-browser.js",
      "import": "./dist/src/hashes/sha2.js"
    },
    "./interface": {
      "types": "./dist/src/interface.d.ts",
      "import": "./dist/src/interface.js"
    },
    "./link": {
      "types": "./dist/src/link.d.ts",
      "import": "./dist/src/link.js"
    },
    "./link/interface": {
      "types": "./dist/src/link/interface.d.ts",
      "import": "./dist/src/link/interface.js"
    },
    "./traversal": {
      "types": "./dist/src/traversal.d.ts",
      "import": "./dist/src/traversal.js"
    }
  },
  "eslintConfig": {
    "extends": "ipfs",
    "parserOptions": {
      "project": true,
      "sourceType": "module"
    }
  },
  "release": {
    "branches": [
      "master"
    ],
    "plugins": [
      [
        "@semantic-release/commit-analyzer",
        {
          "preset": "conventionalcommits",
          "releaseRules": [
            {
              "breaking": true,
              "release": "major"
            },
            {
              "revert": true,
              "release": "patch"
            },
            {
              "type": "feat",
              "release": "minor"
            },
            {
              "type": "fix",
              "release": "patch"
            },
            {
              "type": "docs",
              "release": "patch"
            },
            {
              "type": "test",
              "release": "patch"
            },
            {
              "type": "deps",
              "release": "patch"
            },
            {
              "scope": "no-release",
              "release": false
            }
          ]
        }
      ],
      [
        "@semantic-release/release-notes-generator",
        {
          "preset": "conventionalcommits",
          "presetConfig": {
            "types": [
              {
                "type": "feat",
                "section": "Features"
              },
              {
                "type": "fix",
                "section": "Bug Fixes"
              },
              {
                "type": "chore",
                "section": "Trivial Changes"
              },
              {
                "type": "docs",
                "section": "Documentation"
              },
              {
                "type": "deps",
                "section": "Dependencies"
              },
              {
                "type": "test",
                "section": "Tests"
              }
            ]
          }
        }
      ],
      "@semantic-release/changelog",
      "@semantic-release/npm",
      "@semantic-release/github",
      [
        "@semantic-release/git",
        {
          "assets": [
            "CHANGELOG.md",
            "package.json"
          ]
        }
      ]
    ]
  },
  "scripts": {
    "clean": "aegir clean",
    "lint": "aegir lint",
    "build": "aegir build",
    "release": "aegir release",
    "docs": "aegir docs",
    "test": "npm run lint && npm run test:node && npm run test:chrome",
    "test:node": "aegir test -t node --cov",
    "test:chrome": "aegir test -t browser --cov",
    "test:chrome-webworker": "aegir test -t webworker",
    "test:firefox": "aegir test -t browser -- --browser firefox",
    "test:firefox-webworker": "aegir test -t webworker -- --browser firefox",
    "test:electron-main": "aegir test -t electron-main"
  },
  "devDependencies": {
    "@stablelib/sha256": "^2.0.0",
    "@stablelib/sha512": "^2.0.0",
    "@types/node": "^25.0.0",
    "aegir": "^47.0.7",
    "buffer": "^6.0.3",
    "cids": "^1.1.9",
    "crypto-hash": "^4.0.0"
  },
  "aegir": {
    "test": {
      "target": [
        "node",
        "browser"
      ]
    }
  },
  "browser": {
    "./hashes/sha1": "./dist/src/hashes/sha1-browser.js",
    "./dist/src/hashes/sha1.js": "./dist/src/hashes/sha1-browser.js",
    "./hashes/sha2": "./dist/src/hashes/sha2-browser.js",
    "./dist/src/hashes/sha2.js": "./dist/src/hashes/sha2-browser.js"
  }
}
var queueTick = require('queue-tick')

var mutexify = function () {
  var queue = []
  var used = null

  var call = function () {
    used(release)
  }

  var acquire = function (fn) {
    if (used) return queue.push(fn)
    used = fn
    acquire.locked = true
    queueTick(call)
    return 0
  }

  acquire.locked = false

  var release = function (fn, err, value) {
    used = null
    acquire.locked = false
    if (queue.length) acquire(queue.shift())
    if (fn) fn(err, value)
  }

  return acquire
}

module.exports = mutexify
{
  "name": "mutexify",
  "version": "1.4.0",
  "description": "mutex lock for javascript",
  "main": "index.js",
  "dependencies": {
    "queue-tick": "^1.0.0"
  },
  "devDependencies": {
    "standard": "^14.3.3",
    "tape": "^3.0.2"
  },
  "scripts": {
    "test": "tape test.js",
    "posttest": "npm run lint",
    "lint": "standard"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/mutexify.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/mutexify/issues"
  },
  "keywords": [
    "mutex",
    "lock"
  ],
  "homepage": "https://github.com/mafintosh/mutexify"
}
var mutexify = require('.')

var mutexifyPromise = function () {
  var lock = mutexify()

  var acquire = function () {
    return new Promise(lock)
  }

  Object.defineProperty(acquire, 'locked', {
    get: function () { return lock.locked },
    enumerable: true
  })

  return acquire
}

module.exports = mutexifyPromise
module.exports = assert

class AssertionError extends Error {}
AssertionError.prototype.name = 'AssertionError'

/**
 * Minimal assert function
 * @param  {any} t Value to check if falsy
 * @param  {string=} m Optional assertion error message
 * @throws {AssertionError}
 */
function assert (t, m) {
  if (!t) {
    var err = new AssertionError(m)
    if (Error.captureStackTrace) Error.captureStackTrace(err, assert)
    throw err
  }
}
{
  "name": "nanoassert",
  "version": "2.0.0",
  "description": "Nanoscale assertion module",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "tape": "^4.9.1"
  },
  "scripts": {
    "test": "tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/emilbayes/nanoassert.git"
  },
  "keywords": [
    "assert",
    "unassert",
    "power-assert",
    "tiny",
    "nano",
    "pico"
  ],
  "author": "Emil Bay <github@tixz.dk>",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/emilbayes/nanoassert/issues"
  },
  "homepage": "https://github.com/emilbayes/nanoassert#readme"
}
module.exports = class NatSampler {
  constructor () {
    this.host = null
    this.port = 0
    this.size = 0

    this._a = null
    this._b = null
    this._threshold = 0
    this._top = 0
    this._samples = []
  }

  add (host, port) {
    const a = this._bump(host, port, 2)
    const b = this._bump(host, 0, 1)

    if (this._samples.length < 32) {
      this.size++
      this._threshold = this.size - (this.size < 4 ? 0 : this.size < 8 ? 1 : this.size < 12 ? 2 : 3)
      this._samples.push(a, b)
      this._top += 2
    } else {
      if (this._top === 32) this._top = 0

      const oa = this._samples[this._top]
      this._samples[this._top++] = a
      oa.hits--

      const ob = this._samples[this._top]
      this._samples[this._top++] = b
      ob.hits--
    }

    if (this._a === null || this._a.hits < a.hits) this._a = a
    if (this._b === null || this._b.hits < b.hits) this._b = b

    if (this._a.hits >= this._threshold) {
      this.host = this._a.host
      this.port = this._a.port
    } else if (this._b.hits >= this._threshold) {
      this.host = this._b.host
      this.port = 0
    } else {
      this.host = null
      this.port = 0
    }

    return a.hits
  }

  _bump (host, port, inc) {
    for (let i = 0; i < 4; i++) {
      const j = (this._top - inc - (2 * i)) & 31
      if (j >= this._samples.length) return { host, port, hits: 1 }
      const s = this._samples[j]
      if (s.port === port && s.host === host) {
        s.hits++
        return s
      }
    }
    return { host, port, hits: 1 }
  }
}
{
  "name": "nat-sampler",
  "version": "1.0.1",
  "description": "Sample addresses to figure out if a host + port is consistent",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^16.0.3",
    "tape": "^5.2.2"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/nat-sampler.git"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/nat-sampler/issues"
  },
  "homepage": "https://github.com/mafintosh/nat-sampler"
}
/* eslint-disable camelcase */
const sodium = require('sodium-universal')
const assert = require('nanoassert')
const b4a = require('b4a')

const DHLEN = sodium.crypto_scalarmult_ed25519_BYTES
const PKLEN = sodium.crypto_scalarmult_ed25519_BYTES
const SCALARLEN = sodium.crypto_scalarmult_ed25519_BYTES
const SKLEN = sodium.crypto_sign_SECRETKEYBYTES
const ALG = 'Ed25519'

module.exports = {
  DHLEN,
  PKLEN,
  SCALARLEN,
  SKLEN,
  ALG,
  name: ALG,
  generateKeyPair,
  dh
}

function generateKeyPair (privKey) {
  if (privKey) return generateSeedKeyPair(privKey.subarray(0, 32))

  const keyPair = {}
  keyPair.secretKey = b4a.alloc(SKLEN)
  keyPair.publicKey = b4a.alloc(PKLEN)

  sodium.crypto_sign_keypair(keyPair.publicKey, keyPair.secretKey)
  return keyPair
}

function generateSeedKeyPair (seed) {
  const keyPair = {}
  keyPair.secretKey = b4a.alloc(SKLEN)
  keyPair.publicKey = b4a.alloc(PKLEN)

  sodium.crypto_sign_seed_keypair(keyPair.publicKey, keyPair.secretKey, seed)
  return keyPair
}

function dh (publicKey, { scalar, secretKey }) {
  // tweaked keys expose scalar directly
  if (!scalar) {
    assert(secretKey.byteLength === SKLEN)

    // libsodium stores seed not actual scalar
    const sk = b4a.alloc(64)
    sodium.crypto_hash_sha512(sk, secretKey.subarray(0, 32))
    sk[0] &= 248
    sk[31] &= 127
    sk[31] |= 64

    scalar = sk.subarray(0, 32)
  }

  assert(scalar.byteLength === SCALARLEN)
  assert(publicKey.byteLength === PKLEN)

  const output = b4a.alloc(DHLEN)

  // we clamp if necessary above
  sodium.crypto_scalarmult_ed25519_noclamp(
    output,
    scalar,
    publicKey
  )

  return output
}
{
  "name": "noise-curve-ed",
  "version": "2.1.0",
  "description": "Ed25519 elliptic curve operations for [`noise-handshake`](https://github.com/chm-diederichs/noise-handshake)",
  "main": "index.js",
  "scripts": {
    "test": "npx standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/chm-diederichs/noise-curve-ed.git"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/chm-diederichs/noise-curve-ed/issues"
  },
  "homepage": "https://github.com/chm-diederichs/noise-curve-ed#readme",
  "dependencies": {
    "b4a": "^1.1.0",
    "nanoassert": "^2.0.0",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "noise-handshake": "^3.0.0",
    "standard": "^16.0.3",
    "tape": "^5.2.2"
  }
}
const sodium = require('sodium-universal')
const b4a = require('b4a')

module.exports = class CipherState {
  constructor (key) {
    this.key = key || null
    this.nonce = 0
    this.CIPHER_ALG = 'ChaChaPoly'
  }

  initialiseKey (key) {
    this.key = key
    this.nonce = 0
  }

  setNonce (nonce) {
    this.nonce = nonce
  }

  encrypt (plaintext, ad) {
    if (!this.hasKey) return plaintext
    if (!ad) ad = b4a.alloc(0)

    const ciphertext = encryptWithAD(this.key, this.nonce, ad, plaintext)
    if (ciphertext.length > 65535) throw new Error(`ciphertext length of ${ciphertext.length} exceeds maximum Noise message length of 65535`)
    this.nonce++

    return ciphertext
  }

  decrypt (ciphertext, ad) {
    if (!this.hasKey) return ciphertext
    if (!ad) ad = b4a.alloc(0)
    if (ciphertext.length > 65535) throw new Error(`ciphertext length of ${ciphertext.length} exceeds maximum Noise message length of 65535`)

    const plaintext = decryptWithAD(this.key, this.nonce, ad, ciphertext)
    this.nonce++

    return plaintext
  }

  get hasKey () {
    return this.key !== null
  }

  _clear () {
    sodium.sodium_memzero(this.key)
    this.key = null
    this.nonce = null
  }

  static get MACBYTES () {
    return 16
  }

  static get NONCEBYTES () {
    return 8
  }

  static get KEYBYTES () {
    return 32
  }
}

function encryptWithAD (key, counter, additionalData, plaintext) {
  // for our purposes, additionalData will always be a pubkey so we encode from hex
  if (!b4a.isBuffer(additionalData)) additionalData = b4a.from(additionalData, 'hex')
  if (!b4a.isBuffer(plaintext)) plaintext = b4a.from(plaintext, 'hex')

  const nonce = b4a.alloc(sodium.crypto_aead_chacha20poly1305_ietf_NPUBBYTES)
  const view = new DataView(nonce.buffer, nonce.byteOffset, nonce.byteLength)
  view.setUint32(4, counter, true)

  const ciphertext = b4a.alloc(plaintext.byteLength + sodium.crypto_aead_chacha20poly1305_ietf_ABYTES)

  sodium.crypto_aead_chacha20poly1305_ietf_encrypt(ciphertext, plaintext, additionalData, null, nonce, key)
  return ciphertext
}

function decryptWithAD (key, counter, additionalData, ciphertext) {
  // for our purposes, additionalData will always be a pubkey so we encode from hex
  if (!b4a.isBuffer(additionalData)) additionalData = b4a.from(additionalData, 'hex')
  if (!b4a.isBuffer(ciphertext)) ciphertext = b4a.from(ciphertext, 'hex')

  const nonce = b4a.alloc(sodium.crypto_aead_chacha20poly1305_ietf_NPUBBYTES)
  const view = new DataView(nonce.buffer, nonce.byteOffset, nonce.byteLength)
  view.setUint32(4, counter, true)

  const plaintext = b4a.alloc(ciphertext.byteLength - sodium.crypto_aead_chacha20poly1305_ietf_ABYTES)

  sodium.crypto_aead_chacha20poly1305_ietf_decrypt(plaintext, null, ciphertext, additionalData, nonce, key)
  return plaintext
}
/* eslint-disable camelcase */
const {
  crypto_kx_SEEDBYTES,
  crypto_kx_keypair,
  crypto_kx_seed_keypair,
  crypto_scalarmult_BYTES,
  crypto_scalarmult_SCALARBYTES,
  crypto_scalarmult,
  crypto_scalarmult_base
} = require('sodium-universal')

const assert = require('nanoassert')
const b4a = require('b4a')

const DHLEN = crypto_scalarmult_BYTES
const PKLEN = crypto_scalarmult_BYTES
const SKLEN = crypto_scalarmult_SCALARBYTES
const SEEDLEN = crypto_kx_SEEDBYTES
const ALG = '25519'

module.exports = {
  DHLEN,
  PKLEN,
  SKLEN,
  SEEDLEN,
  ALG,
  generateKeyPair,
  generateSeedKeyPair,
  dh
}

function generateKeyPair (privKey) {
  const keyPair = {}

  keyPair.secretKey = privKey || b4a.alloc(SKLEN)
  keyPair.publicKey = b4a.alloc(PKLEN)

  if (privKey) {
    crypto_scalarmult_base(keyPair.publicKey, keyPair.secretKey)
  } else {
    crypto_kx_keypair(keyPair.publicKey, keyPair.secretKey)
  }

  return keyPair
}

function generateSeedKeyPair (seed) {
  assert(seed.byteLength === SKLEN)

  const keyPair = {}
  keyPair.secretKey = b4a.alloc(SKLEN)
  keyPair.publicKey = b4a.alloc(PKLEN)

  crypto_kx_seed_keypair(keyPair.publicKey, keyPair.secretKey, seed)
  return keyPair
}

function dh (publicKey, { secretKey }) {
  assert(secretKey.byteLength === SKLEN)
  assert(publicKey.byteLength === PKLEN)

  const output = b4a.alloc(DHLEN)

  crypto_scalarmult(
    output,
    secretKey,
    publicKey
  )

  return output
}
const hmacBlake2b = require('./hmac')
const b4a = require('b4a')

const HASHLEN = 64

module.exports = {
  hkdf,
  HASHLEN
}

// HMAC-based Extract-and-Expand KDF
// https://www.ietf.org/rfc/rfc5869.txt

function hkdf (salt, inputKeyMaterial, info = '', length = 2 * HASHLEN) {
  const pseudoRandomKey = hkdfExtract(salt, inputKeyMaterial)
  return hkdfExpand(pseudoRandomKey, info, length)
}

function hkdfExtract (salt, inputKeyMaterial) {
  const hmac = b4a.alloc(HASHLEN)
  return hmacDigest(hmac, salt, inputKeyMaterial)
}

function hkdfExpand (key, info, length) {
  // Put in dedicated slab to avoid keeping shared slab from being gc'ed
  const buffer = b4a.allocUnsafeSlow(length)

  const infoBuf = b4a.from(info)
  let prev = infoBuf

  const result = []
  for (let i = 0; i < length; i += HASHLEN) {
    const pos = b4a.from([(i / HASHLEN) + 1])

    const out = buffer.subarray(i, i + HASHLEN)
    result.push(out)

    prev = hmacDigest(out, key, [prev, infoBuf, pos])
  }

  return result
}

function hmacDigest (out, key, input) {
  hmacBlake2b(out, input, key)
  return out
}
/* eslint-disable camelcase */
const b4a = require('b4a')
const { sodium_memzero, crypto_generichash, crypto_generichash_batch } = require('sodium-universal')

const HASHLEN = 64
const BLOCKLEN = 128
const scratch = b4a.alloc(BLOCKLEN * 3)
const HMACKey = scratch.subarray(BLOCKLEN * 0, BLOCKLEN * 1)
const OuterKeyPad = scratch.subarray(BLOCKLEN * 1, BLOCKLEN * 2)
const InnerKeyPad = scratch.subarray(BLOCKLEN * 2, BLOCKLEN * 3)

// Post-fill is done in the cases where someone caught an exception that
// happened before we were able to clear data at the end

module.exports = function hmac (out, batch, key) {
  if (key.byteLength > BLOCKLEN) {
    crypto_generichash(HMACKey.subarray(0, HASHLEN), key)
    sodium_memzero(HMACKey.subarray(HASHLEN))
  } else {
    // Covers key <= BLOCKLEN
    HMACKey.set(key)
    sodium_memzero(HMACKey.subarray(key.byteLength))
  }

  for (let i = 0; i < HMACKey.byteLength; i++) {
    OuterKeyPad[i] = 0x5c ^ HMACKey[i]
    InnerKeyPad[i] = 0x36 ^ HMACKey[i]
  }
  sodium_memzero(HMACKey)

  crypto_generichash_batch(out, [InnerKeyPad].concat(batch))
  sodium_memzero(InnerKeyPad)
  crypto_generichash_batch(out, [OuterKeyPad, out])
  sodium_memzero(OuterKeyPad)
}

module.exports.BYTES = HASHLEN
module.exports.KEYBYTES = BLOCKLEN
const assert = require('nanoassert')
const b4a = require('b4a')

const SymmetricState = require('./symmetric-state')
const { HASHLEN } = require('./hkdf')

const PRESHARE_IS = Symbol('initiator static key preshared')
const PRESHARE_RS = Symbol('responder static key preshared')

const TOK_PSK = Symbol('psk')

const TOK_S = Symbol('s')
const TOK_E = Symbol('e')

const TOK_ES = Symbol('es')
const TOK_SE = Symbol('se')
const TOK_EE = Symbol('ee')
const TOK_SS = Symbol('ss')

const HANDSHAKES = Object.freeze({
  NN: [
    [TOK_E],
    [TOK_E, TOK_EE]
  ],
  NNpsk0: [
    [TOK_PSK, TOK_E],
    [TOK_E, TOK_EE]
  ],
  XX: [
    [TOK_E],
    [TOK_E, TOK_EE, TOK_S, TOK_ES],
    [TOK_S, TOK_SE]
  ],
  XXpsk0: [
    [TOK_PSK, TOK_E],
    [TOK_E, TOK_EE, TOK_S, TOK_ES],
    [TOK_S, TOK_SE]
  ],
  IK: [
    PRESHARE_RS,
    [TOK_E, TOK_ES, TOK_S, TOK_SS],
    [TOK_E, TOK_EE, TOK_SE]
  ],
  XK: [
    PRESHARE_RS,
    [TOK_E, TOK_ES],
    [TOK_E, TOK_EE],
    [TOK_S, TOK_SE]
  ]
})

class Writer {
  constructor () {
    this.size = 0
    this.buffers = []
  }

  push (b) {
    this.size += b.byteLength
    this.buffers.push(b)
  }

  end () {
    const all = b4a.alloc(this.size)
    let offset = 0
    for (const b of this.buffers) {
      all.set(b, offset)
      offset += b.byteLength
    }
    return all
  }
}

class Reader {
  constructor (buf) {
    this.offset = 0
    this.buffer = buf
  }

  shift (n) {
    const start = this.offset
    const end = this.offset += n
    if (end > this.buffer.byteLength) throw new Error('Insufficient bytes')
    return this.buffer.subarray(start, end)
  }

  end () {
    return this.shift(this.buffer.byteLength - this.offset)
  }
}

module.exports = class NoiseState extends SymmetricState {
  constructor (pattern, initiator, staticKeypair, opts = {}) {
    super(opts)

    this.s = staticKeypair || this.curve.generateKeyPair()
    this.e = null

    this.psk = null
    if (opts && opts.psk) this.psk = opts.psk

    this.re = null
    this.rs = null

    this.pattern = pattern
    this.handshake = HANDSHAKES[this.pattern].slice()

    this.isPskHandshake = !!this.psk && hasPskToken(this.handshake)

    this.protocol = b4a.from([
      'Noise',
      this.pattern,
      this.DH_ALG,
      this.CIPHER_ALG,
      'BLAKE2b'
    ].join('_'))

    this.initiator = initiator
    this.complete = false

    this.rx = null
    this.tx = null
    this.hash = null
  }

  initialise (prologue, remoteStatic) {
    if (this.protocol.byteLength <= HASHLEN) this.digest.set(this.protocol)
    else this.mixHash(this.protocol)

    this.chainingKey = b4a.from(this.digest)

    this.mixHash(prologue)

    while (!Array.isArray(this.handshake[0])) {
      const message = this.handshake.shift()

      // handshake steps should be as arrays, only
      // preshare tokens are provided otherwise
      assert(message === PRESHARE_RS || message === PRESHARE_IS,
        'Unexpected pattern')

      const takeRemoteKey = this.initiator
        ? message === PRESHARE_RS
        : message === PRESHARE_IS

      if (takeRemoteKey) this.rs = remoteStatic

      const key = takeRemoteKey ? this.rs : this.s.publicKey
      assert(key != null, 'Remote pubkey required')

      this.mixHash(key)
    }
  }

  final () {
    const [k1, k2] = this.split()

    this.tx = this.initiator ? k1 : k2
    this.rx = this.initiator ? k2 : k1

    this.complete = true
    this.hash = this.getHandshakeHash()

    this._clear()
  }

  recv (buf) {
    const r = new Reader(buf)

    for (const pattern of this.handshake.shift()) {
      switch (pattern) {
        case TOK_PSK :
          this.mixKeyAndHash(this.psk)
          break

        case TOK_E :
          this.re = r.shift(this.curve.PKLEN)
          this.mixHash(this.re)
          if (this.isPskHandshake) this.mixKeyNormal(this.re)
          break

        case TOK_S : {
          const klen = this.hasKey ? this.curve.PKLEN + 16 : this.curve.PKLEN
          this.rs = this.decryptAndHash(r.shift(klen))
          break
        }

        case TOK_EE :
        case TOK_ES :
        case TOK_SE :
        case TOK_SS : {
          const useStatic = keyPattern(pattern, this.initiator)

          const localKey = useStatic.local ? this.s : this.e
          const remoteKey = useStatic.remote ? this.rs : this.re

          this.mixKey(remoteKey, localKey)
          break
        }

        default :
          throw new Error('Unexpected message')
      }
    }

    const payload = this.decryptAndHash(r.end())

    if (!this.handshake.length) this.final()
    return payload
  }

  send (payload = b4a.alloc(0)) {
    const w = new Writer()

    for (const pattern of this.handshake.shift()) {
      switch (pattern) {
        case TOK_PSK :
          this.mixKeyAndHash(this.psk)
          break

        case TOK_E :
          if (this.e === null) this.e = this.curve.generateKeyPair()
          this.mixHash(this.e.publicKey)
          if (this.isPskHandshake) this.mixKeyNormal(this.e.publicKey)
          w.push(this.e.publicKey)
          break

        case TOK_S :
          w.push(this.encryptAndHash(this.s.publicKey))
          break

        case TOK_ES :
        case TOK_SE :
        case TOK_EE :
        case TOK_SS : {
          const useStatic = keyPattern(pattern, this.initiator)

          const localKey = useStatic.local ? this.s : this.e
          const remoteKey = useStatic.remote ? this.rs : this.re

          this.mixKey(remoteKey, localKey)
          break
        }

        default :
          throw new Error('Unexpected message')
      }
    }

    w.push(this.encryptAndHash(payload))
    const response = w.end()

    if (!this.handshake.length) this.final()
    return response
  }

  _clear () {
    super._clear()

    this.e.secretKey.fill(0)
    this.e.publicKey.fill(0)

    this.re.fill(0)

    this.e = null
    this.re = null
  }
}

function keyPattern (pattern, initiator) {
  const ret = {
    local: false,
    remote: false
  }

  switch (pattern) {
    case TOK_EE:
      return ret

    case TOK_ES:
      ret.local ^= !initiator
      ret.remote ^= initiator
      return ret

    case TOK_SE:
      ret.local ^= initiator
      ret.remote ^= !initiator
      return ret

    case TOK_SS:
      ret.local ^= 1
      ret.remote ^= 1
      return ret
  }
}

function hasPskToken (handshake) {
  return handshake.some(x => {
    return Array.isArray(x) && x.indexOf(TOK_PSK) !== -1
  })
}
{
  "name": "noise-handshake",
  "version": "4.2.0",
  "description": "Noise protocol handshake",
  "main": "noise.js",
  "files": [
    "*.js"
  ],
  "scripts": {
    "test": "standard && brittle test/*.js"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/noise-handshake.git"
  },
  "dependencies": {
    "b4a": "^1.1.0",
    "nanoassert": "^2.0.0",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "noise-protocol": "chm-diederichs/noise-protocol.git#xx-ephemeral-key",
    "standard": "^16.0.3"
  }
}
const sodium = require('sodium-universal')
const assert = require('nanoassert')
const b4a = require('b4a')
const CipherState = require('./cipher')
const curve = require('./dh')
const { HASHLEN, hkdf } = require('./hkdf')

module.exports = class SymmetricState extends CipherState {
  constructor (opts = {}) {
    super()

    this.curve = opts.curve || curve
    this.digest = b4a.alloc(HASHLEN)
    this.chainingKey = null
    this.offset = 0

    this.DH_ALG = this.curve.ALG
  }

  mixHash (data) {
    accumulateDigest(this.digest, data)
  }

  mixKeyAndHash (key) {
    const [ck, tempH, tempK] = hkdf(this.chainingKey, key, '', 3 * HASHLEN)
    this.chainingKey = ck
    this.mixHash(tempH)
    this.initialiseKey(tempK.subarray(0, 32))
  }

  mixKeyNormal (key) {
    const [ck, tempK] = hkdf(this.chainingKey, key)
    this.chainingKey = ck
    this.initialiseKey(tempK.subarray(0, 32))
  }

  mixKey (remoteKey, localKey) {
    const dh = this.curve.dh(remoteKey, localKey)
    const hkdfResult = hkdf(this.chainingKey, dh)
    this.chainingKey = hkdfResult[0]
    this.initialiseKey(hkdfResult[1].subarray(0, 32))
  }

  encryptAndHash (plaintext) {
    const ciphertext = this.encrypt(plaintext, this.digest)
    accumulateDigest(this.digest, ciphertext)
    return ciphertext
  }

  decryptAndHash (ciphertext) {
    const plaintext = this.decrypt(ciphertext, this.digest)
    accumulateDigest(this.digest, ciphertext)
    return plaintext
  }

  getHandshakeHash (out) {
    if (!out) return this.getHandshakeHash(b4a.alloc(HASHLEN))
    assert(out.byteLength === HASHLEN, `output must be ${HASHLEN} bytes`)

    out.set(this.digest)
    return out
  }

  split () {
    const res = hkdf(this.chainingKey, b4a.alloc(0))
    return res.map(k => k.subarray(0, 32))
  }

  _clear () {
    super._clear()

    sodium.sodium_memzero(this.digest)
    sodium.sodium_memzero(this.chainingKey)

    this.digest = null
    this.chainingKey = null
    this.offset = null

    this.curve = null
  }

  static get alg () {
    return CipherState.alg + '_BLAKE2b'
  }
}

function accumulateDigest (digest, input) {
  const toHash = b4a.concat([digest, input])
  sodium.crypto_generichash(digest, toHash)
}
var varint = require('varint')
var svarint = require('signed-varint')
var b4a = require('b4a')

exports.make = encoder

exports.name = function (enc) {
  var keys = Object.keys(exports)
  for (var i = 0; i < keys.length; i++) {
    if (exports[keys[i]] === enc) return keys[i]
  }
  return null
}

exports.skip = function (type, buffer, offset) {
  switch (type) {
    case 0:
      varint.decode(buffer, offset)
      return offset + varint.decode.bytes

    case 1:
      return offset + 8

    case 2:
      var len = varint.decode(buffer, offset)
      return offset + varint.decode.bytes + len

    case 3:
    case 4:
      throw new Error('Groups are not supported')

    case 5:
      return offset + 4
  }

  throw new Error('Unknown wire type: ' + type)
}

exports.bytes = encoder(2,
  function encode (val, buffer, offset) {
    var oldOffset = offset
    var len = bufferLength(val)

    varint.encode(len, buffer, offset)
    offset += varint.encode.bytes

    if (b4a.isBuffer(val)) b4a.copy(val, buffer, offset)
    else b4a.write(buffer, val, offset, len)
    offset += len

    encode.bytes = offset - oldOffset
    return buffer
  },
  function decode (buffer, offset) {
    var oldOffset = offset

    var len = varint.decode(buffer, offset)
    offset += varint.decode.bytes

    var val = buffer.subarray(offset, offset + len)
    offset += val.length

    decode.bytes = offset - oldOffset
    return val
  },
  function encodingLength (val) {
    var len = bufferLength(val)
    return varint.encodingLength(len) + len
  }
)

exports.string = encoder(2,
  function encode (val, buffer, offset) {
    var oldOffset = offset
    var len = b4a.byteLength(val)

    varint.encode(len, buffer, offset, 'utf-8')
    offset += varint.encode.bytes

    b4a.write(buffer, val, offset, len)
    offset += len

    encode.bytes = offset - oldOffset
    return buffer
  },
  function decode (buffer, offset) {
    var oldOffset = offset

    var len = varint.decode(buffer, offset)
    offset += varint.decode.bytes

    var val = b4a.toString(buffer, 'utf-8', offset, offset + len)
    offset += len

    decode.bytes = offset - oldOffset
    return val
  },
  function encodingLength (val) {
    var len = b4a.byteLength(val)
    return varint.encodingLength(len) + len
  }
)

exports.bool = encoder(0,
  function encode (val, buffer, offset) {
    buffer[offset] = val ? 1 : 0
    encode.bytes = 1
    return buffer
  },
  function decode (buffer, offset) {
    var bool = buffer[offset] > 0
    decode.bytes = 1
    return bool
  },
  function encodingLength () {
    return 1
  }
)

exports.int32 = encoder(0,
  function encode (val, buffer, offset) {
    varint.encode(val < 0 ? val + 4294967296 : val, buffer, offset)
    encode.bytes = varint.encode.bytes
    return buffer
  },
  function decode (buffer, offset) {
    var val = varint.decode(buffer, offset)
    decode.bytes = varint.decode.bytes
    return val > 2147483647 ? val - 4294967296 : val
  },
  function encodingLength (val) {
    return varint.encodingLength(val < 0 ? val + 4294967296 : val)
  }
)

exports.int64 = encoder(0,
  function encode (val, buffer, offset) {
    if (val < 0) {
      var last = offset + 9
      varint.encode(val * -1, buffer, offset)
      offset += varint.encode.bytes - 1
      buffer[offset] = buffer[offset] | 0x80
      while (offset < last - 1) {
        offset++
        buffer[offset] = 0xff
      }
      buffer[last] = 0x01
      encode.bytes = 10
    } else {
      varint.encode(val, buffer, offset)
      encode.bytes = varint.encode.bytes
    }
    return buffer
  },
  function decode (buffer, offset) {
    var val = varint.decode(buffer, offset)
    if (val >= Math.pow(2, 63)) {
      var limit = 9
      while (buffer[offset + limit - 1] === 0xff) limit--
      limit = limit || 9
      var subset = b4a.allocUnsafe(limit)
      b4a.copy(buffer, subset, 0, offset, offset + limit)
      subset[limit - 1] = subset[limit - 1] & 0x7f
      val = -1 * varint.decode(subset, 0)
      decode.bytes = 10
    } else {
      decode.bytes = varint.decode.bytes
    }
    return val
  },
  function encodingLength (val) {
    return val < 0 ? 10 : varint.encodingLength(val)
  }
)

exports.sint32 =
exports.sint64 = encoder(0,
  svarint.encode,
  svarint.decode,
  svarint.encodingLength
)

exports.uint32 =
exports.uint64 =
exports.enum =
exports.varint = encoder(0,
  varint.encode,
  varint.decode,
  varint.encodingLength
)

// we cannot represent these in javascript so we just use buffers
exports.fixed64 =
exports.sfixed64 = encoder(1,
  function encode (val, buffer, offset) {
    b4a.copy(val, buffer, offset)
    encode.bytes = 8
    return buffer
  },
  function decode (buffer, offset) {
    var val = buffer.subarray(offset, offset + 8)
    decode.bytes = 8
    return val
  },
  function encodingLength () {
    return 8
  }
)

exports.double = encoder(1,
  function encode (val, buffer, offset) {
    b4a.writeDoubleLE(buffer, val, offset)
    encode.bytes = 8
    return buffer
  },
  function decode (buffer, offset) {
    var val = b4a.readDoubleLE(buffer, offset)
    decode.bytes = 8
    return val
  },
  function encodingLength () {
    return 8
  }
)

exports.fixed32 = encoder(5,
  function encode (val, buffer, offset) {
    b4a.writeUInt32LE(buffer, val, offset)
    encode.bytes = 4
    return buffer
  },
  function decode (buffer, offset) {
    var val = b4a.readUInt32LE(buffer, offset)
    decode.bytes = 4
    return val
  },
  function encodingLength () {
    return 4
  }
)

exports.sfixed32 = encoder(5,
  function encode (val, buffer, offset) {
    b4a.writeInt32LE(buffer, val, offset)
    encode.bytes = 4
    return buffer
  },
  function decode (buffer, offset) {
    var val = b4a.readInt32LE(buffer, offset)
    decode.bytes = 4
    return val
  },
  function encodingLength () {
    return 4
  }
)

exports.float = encoder(5,
  function encode (val, buffer, offset) {
    b4a.writeFloatLE(buffer, val, offset)
    encode.bytes = 4
    return buffer
  },
  function decode (buffer, offset) {
    var val = b4a.readFloatLE(buffer, offset)
    decode.bytes = 4
    return val
  },
  function encodingLength () {
    return 4
  }
)

function encoder (type, encode, decode, encodingLength) {
  encode.bytes = decode.bytes = 0

  return {
    type: type,
    encode: encode,
    decode: decode,
    encodingLength: encodingLength
  }
}

function bufferLength (val) {
  return b4a.isBuffer(val) ? val.length : b4a.byteLength(val)
}
{
  "name": "protocol-buffers-encodings",
  "version": "1.2.0",
  "description": "Base encodings for protocol-buffers",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.6.0",
    "signed-varint": "^2.0.1",
    "varint": "5.0.0"
  },
  "devDependencies": {
    "standard": "^14.3.4",
    "tape": "^5.0.1"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/protocol-buffers-encodings.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/protocol-buffers-encodings/issues"
  },
  "homepage": "https://github.com/mafintosh/protocol-buffers-encodings"
}
const EventEmitter = require('events')
const Protomux = require('protomux')
const c = require('compact-encoding')
const bitfield = require('compact-encoding-bitfield')
const bits = require('bits-to-bytes')
const safetyCatch = require('safety-catch')
const errors = require('./lib/errors')

module.exports = class ProtomuxRPC extends EventEmitter {
  constructor(stream, options = {}) {
    super()

    const {
      id,
      protocol = 'protomux-rpc',
      valueEncoding = c.optionalBuffer,
      handshake = null,
      handshakeEncoding
    } = options

    this._mux = Protomux.from(stream)
    this._defaultValueEncoding = valueEncoding

    this._id = 1
    this._ending = null
    this._destroyed = false
    this._error = null
    this._responding = 0

    this._requests = new Map()
    this._responders = new Map()

    this._channel = this._mux.createChannel({
      protocol,
      id,
      handshake: handshake === null ? null : handshakeEncoding || c.raw,
      onopen: this._onopen.bind(this),
      onclose: this._onclose.bind(this),
      ondestroy: this._ondestroy.bind(this)
    })

    if (this._channel === null) throw errors.DUPLICATE_CHANNEL()

    this._request = this._channel.addMessage({
      encoding: request,
      onmessage: this._onrequest.bind(this)
    })

    this._response = this._channel.addMessage({
      encoding: response,
      onmessage: this._onresponse.bind(this)
    })

    this._channel.open(handshake)
  }

  _onopen(handshake) {
    this.emit('open', handshake)
  }

  _onclose() {
    this._ending = Promise.resolve()

    const err = this._error || errors.CHANNEL_CLOSED()

    for (const request of this._requests.values()) {
      request.reject(err)
      if (request.timeout) clearTimeout(request.timeout)
    }

    this._requests.clear()
    this._responders.clear()

    this.emit('close')
  }

  _ondestroy() {
    this._destroyed = true
    this.emit('destroy')
  }

  async _onrequest({ id, method, value }) {
    let error = null

    const responder = this._responders.get(method)

    if (responder === undefined) error = errors.UNKNOWN_METHOD(`Unknown method '${method}'`)
    else {
      const {
        valueEncoding = this._defaultValueEncoding,
        requestEncoding = valueEncoding,
        responseEncoding = valueEncoding
      } = responder.options

      this._responding++

      try {
        if (requestEncoding) value = c.decode(requestEncoding, value)

        try {
          value = await responder.handler(value)
        } catch (err) {
          safetyCatch(err)

          error = errors.REQUEST_ERROR('Request failed', err)
        }
      } catch (err) {
        safetyCatch(err)

        error = errors.DECODE_ERROR('Could not decode request', err)
      }

      this._responding--

      if (!error && responseEncoding && id) {
        try {
          value = c.encode(responseEncoding, value)
        } catch (err) {
          safetyCatch(err)

          error = errors.ENCODE_ERROR('Could not encode response', err)
        }
      }
    }

    if (id) this._response.send({ id, error, value })

    this._endMaybe()
  }

  _onresponse({ id, error, value }) {
    if (id === 0) return

    const request = this._requests.get(id)

    if (request === undefined) return

    this._requests.delete(id)

    if (request.timeout) clearTimeout(request.timeout)

    if (error) request.reject(error)
    else {
      const { valueEncoding = this._defaultValueEncoding, responseEncoding = valueEncoding } =
        request.options

      try {
        if (responseEncoding) value = c.decode(responseEncoding, value)

        request.resolve(value)
      } catch (err) {
        safetyCatch(err)

        request.reject(errors.DECODE_ERROR('Could not decode response', err))
      }
    }

    this._endMaybe()
  }

  _ontimeout(id, timeout) {
    const request = this._requests.get(id)

    if (request === undefined) return

    this._requests.delete(id)

    request.reject(errors.TIMEOUT_EXCEEDED(`timeout of ${timeout}ms exceeded`))

    this._endMaybe()
  }

  get opened() {
    return this._channel.opened
  }

  get closed() {
    return this._channel.closed
  }

  get mux() {
    return this._mux
  }

  get stream() {
    return this._mux.stream
  }

  async fullyOpened() {
    await this._channel.fullyOpened()
  }

  respond(method, options, handler) {
    if (typeof options === 'function') {
      handler = options
      options = {}
    }

    this._responders.set(method, { options, handler })

    return this
  }

  unrespond(method) {
    this._responders.delete(method)

    return this
  }

  async request(method, value, options = {}) {
    if (this.closed) throw errors.CHANNEL_CLOSED()

    const {
      valueEncoding = this._defaultValueEncoding,
      requestEncoding = valueEncoding,
      timeout = -1
    } = options

    if (requestEncoding) value = c.encode(requestEncoding, value)

    const id = this._id++

    this._request.send({ id, method, value })

    return new Promise((resolve, reject) =>
      this._requests.set(id, {
        options,
        resolve,
        reject,
        timeout: timeout > 0 && setTimeout(this._ontimeout.bind(this, id, timeout), timeout)
      })
    )
  }

  event(method, value, options = {}) {
    if (this.closed) throw errors.CHANNEL_CLOSED()

    const { valueEncoding = this._defaultValueEncoding, requestEncoding = valueEncoding } = options

    if (requestEncoding) value = c.encode(requestEncoding, value)

    this._request.send({ id: 0, method, value })
  }

  cork() {
    this._channel.cork()
  }

  uncork() {
    this._channel.uncork()
  }

  async end() {
    if (this._ending) return this._ending

    this._ending = EventEmitter.once(this, 'close')
    this._endMaybe()

    return this._ending
  }

  _endMaybe() {
    if (this._ending && this._responding === 0 && this._requests.size === 0) {
      this._channel.close()
    }
  }

  destroy(err) {
    if (this._destroyed) return
    this._destroyed = true

    this._error = err || errors.CHANNEL_DESTROYED()
    this._channel.close()
  }
}

const request = {
  preencode(state, m) {
    c.uint.preencode(state, m.id)
    c.string.preencode(state, m.method)
    c.raw.preencode(state, m.value)
  },
  encode(state, m) {
    c.uint.encode(state, m.id)
    c.string.encode(state, m.method)
    c.raw.encode(state, m.value)
  },
  decode(state) {
    return {
      id: c.uint.decode(state),
      method: c.string.decode(state),
      value: c.raw.decode(state)
    }
  }
}

const flags = bitfield(1)

const response = {
  preencode(state, m) {
    flags.preencode(state)

    c.uint.preencode(state, m.id)

    if (m.error) {
      c.string.preencode(state, m.error.message.replace(m.error.code + ': ', ''))

      if (m.error.code) c.string.preencode(state, m.error.code)

      if (m.error.cause) {
        const cause = m.error.cause

        c.string.preencode(state, cause.message)
        c.string.preencode(state, cause.code || '')

        if (cause.context) c.string.preencode(state, cause.context)
      }
    } else {
      c.raw.preencode(state, m.value)
    }
  },
  encode(state, m) {
    flags.encode(
      state,
      bits.of(
        !!m.error,
        !!(m.error && m.error.code),
        !!(m.error && m.error.cause),
        !!(m.error && m.error.cause && m.error.cause.context)
      )
    )

    c.uint.encode(state, m.id)

    if (m.error) {
      c.string.encode(state, m.error.message.replace(m.error.code + ': ', ''))

      if (m.error.code) c.string.encode(state, m.error.code)

      if (m.error.cause) {
        const cause = m.error.cause

        c.string.encode(state, cause.message)
        c.string.encode(state, cause.code || '')

        if (cause.context) c.string.encode(state, cause.context)
      }
    } else {
      c.raw.encode(state, m.value)
    }
  },
  decode(state) {
    const [hasError, hasErrorCode, hasErrorCause, hasErrorContext] = bits.iterator(
      flags.decode(state)
    )

    const id = c.uint.decode(state)

    let error = null
    let value = null

    if (hasError) {
      const message = c.string.decode(state)
      const code = hasErrorCode ? c.string.decode(state) : null

      let cause
      if (hasErrorCause) {
        cause = new Error(c.string.decode(state))

        const code = c.string.decode(state)
        if (code) cause.code = code

        const context = hasErrorContext ? c.string.decode(state) : null
        if (context) cause.context = context
      }

      switch (code) {
        case 'UNKNOWN_METHOD':
          error = errors.UNKNOWN_METHOD(message)
          break
        case 'REQUEST_ERROR':
          error = errors.REQUEST_ERROR(message, cause)
          break
        case 'DECODE_ERROR':
          error = errors.DECODE_ERROR(message, cause)
          break
        case 'ENCODE_ERROR':
          error = errors.ENCODE_ERROR(message, cause)
          break
        default:
          error = new Error(message, { cause })
      }
    } else {
      value = c.raw.decode(state)
    }

    return {
      id,
      error,
      value
    }
  }
}
module.exports = class RPCError extends Error {
  constructor(msg, code, fn = RPCError, { cause } = {}) {
    super(`${code}: ${msg}`, { cause })
    this.code = code

    if (Error.captureStackTrace) Error.captureStackTrace(this, fn)
  }

  get name() {
    return 'RPCError'
  }

  static DUPLICATE_CHANNEL(msg = 'duplicate channel') {
    return new RPCError(msg, 'DUPLICATE_CHANNEL', RPCError.DUPLICATE_CHANNEL)
  }

  static CHANNEL_CLOSED(msg = 'channel closed') {
    return new RPCError(msg, 'CHANNEL_CLOSED', RPCError.CHANNEL_CLOSED)
  }

  static CHANNEL_DESTROYED(msg = 'channel destroyed') {
    return new RPCError(msg, 'CHANNEL_DESTROYED', RPCError.CHANNEL_DESTROYED)
  }

  static REQUEST_ERROR(msg, cause) {
    return new RPCError(msg, 'REQUEST_ERROR', RPCError.REQUEST_ERROR, { cause })
  }

  static TIMEOUT_EXCEEDED(msg) {
    return new RPCError(msg, 'TIMEOUT_EXCEEDED', RPCError.TIMEOUT_EXCEEDED)
  }

  static UNKNOWN_METHOD(msg) {
    return new RPCError(msg, 'UNKNOWN_METHOD', RPCError.UNKNOWN_METHOD)
  }

  static DECODE_ERROR(msg, cause) {
    return new RPCError(msg, 'DECODE_ERROR', RPCError.DECODE_ERROR, { cause })
  }

  static ENCODE_ERROR(msg, cause) {
    return new RPCError(msg, 'ENCODE_ERROR', RPCError.ENCODE_ERROR, { cause })
  }
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "protomux-rpc",
  "version": "1.10.0",
  "description": "RPC over Protomux channels",
  "main": "index.js",
  "files": [
    "index.js",
    "lib"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "exports": {
    "./package": "./package.json",
    ".": "./index.js",
    "./errors": "./lib/errors.js"
  },
  "scripts": {
    "test": "prettier . --check && brittle test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/protomux-rpc.git"
  },
  "author": "Kasper Isager Dalsgarð <kasper@funktionel.co>",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/protomux-rpc/issues"
  },
  "homepage": "https://github.com/holepunchto/protomux-rpc#readme",
  "dependencies": {
    "bits-to-bytes": "^1.0.0",
    "compact-encoding": "^3.0.0",
    "compact-encoding-bitfield": "^1.0.0",
    "protomux": "^3.7.0",
    "safety-catch": "^1.0.2"
  },
  "optionalDependencies": {
    "bare-events": "^2.2.0"
  },
  "devDependencies": {
    "brittle": "^3.3.0",
    "prettier": "^3.7.4",
    "prettier-config-holepunch": "^2.0.0",
    "streamx": "^2.12.4"
  }
}
const crypto = require('hypercore-crypto')
const Protomux = require('protomux')
const b4a = require('b4a')
const schema = require('./spec/hyperschema')

const [NS_INITATOR, NS_RESPONDER] = crypto.namespace('wakeup', 2)

const Handshake = schema.getEncoding('@wakeup/handshake')
const Announce = schema.getEncoding('@wakeup/announce')
const Lookup = schema.getEncoding('@wakeup/lookup')
const Info = schema.getEncoding('@wakeup/info')

module.exports = class WakeupSwarm {
  constructor(onwakeup = noop, { gcTickTime = 2000 } = {}) {
    this.gcTickTime = gcTickTime

    this.topics = new Map()
    this.topicsGC = new Set()
    this.muxers = new Set()
    this.stats = {
      sessionsOpened: 0,
      sessionsClosed: 0,
      topicsAdded: 0,
      topicsGcd: 0,
      peersAdded: 0,
      peersRemoved: 0,
      wireAnnounce: { rx: 0, tx: 0 },
      wireLookup: { rx: 0, tx: 0 },
      wireInfo: { rx: 0, tx: 0 }
    }

    this.onwakeup = onwakeup

    this._gcInterval = null
    this._gcBound = this._gc.bind(this)
  }

  session(capability, handlers = {}) {
    const id = handlers.discoveryKey || crypto.discoveryKey(capability)
    const active = handlers.active !== false
    const hex = b4a.toString(id, 'hex')

    let w = this.topics.get(hex)

    if (w) return w.addSession(handlers)

    w = new WakeupTopic(this, id, capability, active)

    this.topics.set(hex, w)

    for (const muxer of this.muxers) {
      w._onopen(muxer, true)
    }

    return w.addSession(handlers)
  }

  getSessions(capability, handlers = {}) {
    const id = handlers.discoveryKey || crypto.discoveryKey(capability)
    const hex = b4a.toString(id, 'hex')
    const w = this.topics.get(hex)
    return w ? w.sessions : []
  }

  hasStream(stream, capability, handlers = {}) {
    if (!capability) {
      const noiseStream = stream.noiseStream || stream
      return this.muxers.has(getMuxer(noiseStream))
    }

    const id = handlers.discoveryKey || crypto.discoveryKey(capability)
    const hex = b4a.toString(id, 'hex')
    const t = this.topics.get(hex)

    return t ? t.peersByStream.has(stream) : false
  }

  addStream(stream) {
    const noiseStream = stream.noiseStream || stream

    if (!noiseStream.connected) {
      noiseStream.once('open', this.addStream.bind(this, noiseStream))
      return
    }

    const muxer = getMuxer(noiseStream)
    muxer.pair({ protocol: 'wakeup' }, (id) => this._onpair(id, muxer))

    this.muxers.add(muxer)
    noiseStream.on('close', () => this.muxers.delete(muxer))

    for (const w of this.topics.values()) {
      if (!w.isActive) continue
      w._onopen(muxer, true)
    }
  }

  _onActive(w) {
    for (const m of this.muxers) {
      w._onopen(m, false)
    }
  }

  _addGC(topic) {
    if (topic.destroyed) return
    this.topicsGC.add(topic)
    if (this._gcInterval === null) {
      this._gcInterval = setInterval(this._gcBound, this.gcTickTime)
    }
  }

  _removeGC(topic) {
    this.topicsGC.delete(topic)
    if (this.topicsGC.size === 0 && this._gcInterval) {
      clearInterval(this._gcInterval)
      this._gcInterval = null
    }
  }

  _gc() {
    const destroy = []
    for (const w of this.topicsGC) {
      w.idleTicks++
      if (w.idleTicks >= 5) destroy.push(w)
    }
    for (const w of destroy) w.teardown()
  }

  destroy() {
    if (this._gcInterval) clearInterval(this._gcInterval)
    this._gcInterval = null

    for (const w of this.topics.values()) w.teardown()
  }

  async _onpair(id, stream) {
    const hex = b4a.toString(id, 'hex')
    const w = this.topics.get(hex)
    if (!w || !w.sessions.length) return this.onwakeup(id, stream)
    w._onopen(getMuxer(stream), false)
  }

  registerMetrics(promClient) {
    const self = this
    new promClient.Gauge({
      // eslint-disable-line no-new
      name: 'protomux_wakeup_sessions_opened',
      help: 'The amount of sessions opened by protomux wakeup',
      collect() {
        this.set(self.stats.sessionsOpened)
      }
    })

    new promClient.Gauge({
      // eslint-disable-line no-new
      name: 'protomux_wakeup_sessions_closed',
      help: 'The amount of sessions closed by protomux wakeup',
      collect() {
        this.set(self.stats.sessionsClosed)
      }
    })

    new promClient.Gauge({
      // eslint-disable-line no-new
      name: 'protomux_wakeup_topics_added',
      help: 'The amount of topics added to protomux wakeup',
      collect() {
        this.set(self.stats.topicsAdded)
      }
    })

    new promClient.Gauge({
      // eslint-disable-line no-new
      name: 'protomux_wakeup_topics_gcd',
      help: 'The amount of topics that got garbage collected by protomux wakeup',
      collect() {
        this.set(self.stats.topicsGcd)
      }
    })

    new promClient.Gauge({
      // eslint-disable-line no-new
      name: 'protomux_wakeup_peers_added',
      help: 'The amount of peers added by protomux wakeup, across all topics',
      collect() {
        this.set(self.stats.peersAdded)
      }
    })

    new promClient.Gauge({
      // eslint-disable-line no-new
      name: 'protomux_wakeup_peers_removed',
      help: 'The amount of peers removed by protomux wakeup, across all topics',
      collect() {
        this.set(self.stats.peersRemoved)
      }
    })

    new promClient.Gauge({
      // eslint-disable-line no-new
      name: 'protomux_wakeup_wire_announce_rx',
      help: 'The amount of wire announce messages received by protomux wakeup',
      collect() {
        this.set(self.stats.wireAnnounce.rx)
      }
    })
    new promClient.Gauge({
      // eslint-disable-line no-new
      name: 'protomux_wakeup_wire_announce_tx',
      help: 'The amount of wire announce messages transmitted by protomux wakeup',
      collect() {
        this.set(self.stats.wireAnnounce.tx)
      }
    })
    new promClient.Gauge({
      // eslint-disable-line no-new
      name: 'protomux_wakeup_wire_lookup_rx',
      help: 'The amount of wire lookup messages received by protomux wakeup',
      collect() {
        this.set(self.stats.wireLookup.rx)
      }
    })
    new promClient.Gauge({
      // eslint-disable-line no-new
      name: 'protomux_wakeup_wire_lookup_tx',
      help: 'The amount of wire lookup messages transmitted by protomux wakeup',
      collect() {
        this.set(self.stats.wireLookup.tx)
      }
    })
    new promClient.Gauge({
      // eslint-disable-line no-new
      name: 'protomux_wakeup_wire_info_rx',
      help: 'The amount of wire info messages received by protomux wakeup',
      collect() {
        this.set(self.stats.wireInfo.rx)
      }
    })
    new promClient.Gauge({
      // eslint-disable-line no-new
      name: 'protomux_wakeup_wire_info_tx',
      help: 'The amount of wire info messages transmitted by protomux wakeup',
      collect() {
        this.set(self.stats.wireInfo.rx)
      }
    })
  }
}

class WakeupPeer {
  constructor(topic) {
    this.index = 0
    this.userData = null // for the user
    this.clock = 0 // for the user, v useful to reduce traffic
    this.pending = true
    this.removed = false
    this.topic = topic
    this.channel = null
    this.stream = null
    this.wireLookup = null
    this.wireAnnounce = null
    this.wireInfo = null
    this.active = false
  }

  unlink(list) {
    // note that since we pop here we can iterate in reverse safely in case a peer is removed in the same tick
    const head = list.pop()
    if (head === this) return
    head.index = this.index
    list[head.index] = head
  }
}

class WakeupSession {
  constructor(topic, handlers) {
    this.index = 0
    this.topic = topic
    this.handlers = handlers
    this.isActive = handlers.active !== false
    this.destroyed = false
  }

  get peers() {
    return this.topic.peers
  }

  hasStream(stream) {
    return !!this.getPeer(stream)
  }

  addStream(stream) {
    this.topic.addStream(stream)
  }

  getPeer(stream) {
    return this.topic.peersByStream.get(stream) || null
  }

  broadcastLookup(req) {
    for (const peer of this.topic.pendingPeers) {
      this.lookup(peer, req)
    }
    for (const peer of this.topic.peers) {
      this.lookup(peer, req)
    }
  }

  lookupByStream(stream, req) {
    const peer = this.topic.peersByStream.get(stream)
    if (peer) this.lookup(peer, req)
  }

  lookup(peer, req) {
    peer.topic.state.stats.wireLookup.tx++
    peer.wireLookup.send(req || { hash: null })
  }

  announceByStream(stream, wakeup) {
    const peer = this.topic.peersByStream.get(stream)
    if (peer && !peer.pending) this.announce(peer, wakeup)
  }

  announce(peer, wakeup) {
    peer.topic.state.stats.wireAnnounce.tx++
    peer.wireAnnounce.send(wakeup)
  }

  active() {
    this.isActive = true
    this.topic._bumpActivity()
  }

  inactive() {
    this.isActive = false
    this.topic._bumpActivity()
  }

  destroy() {
    if (this.destroyed) return
    this.destroyed = true
    this.topic.removeSession(this)
  }
}

class WakeupTopic {
  constructor(state, id, capability, active) {
    this.state = state
    this.sessions = []
    this.id = id
    this.capability = capability
    this.peers = []
    this.pendingPeers = []
    this.peersByStream = new Map()
    this.activePeers = 0
    this.isActive = active
    this.idleTicks = 0
    this.gcing = false
    this.destroyed = false

    this.state.stats.topicsAdded++
  }

  addSession(handlers) {
    this.state.stats.sessionsOpened++
    const session = new WakeupSession(this, handlers)
    session.index = this.sessions.length
    this.sessions.push(session)
    this._bumpActivity()
    this._checkGC()
    return session
  }

  removeSession(session) {
    if (this.sessions.length <= session.index) return
    if (this.sessions[session.index] !== session) return

    this.state.stats.sessionsClosed++

    // same as with the peer, this allows us to iterate while removing if iterating backwards
    const head = this.sessions.pop()
    if (head !== session) {
      head.index = session.index
      this.sessions[head.index] = head
    }

    this._bumpActivity()
    this._checkGC()
  }

  _bumpActivity() {
    let isActive = false

    for (let i = this.sessions.length - 1; i >= 0; i--) {
      if (this.sessions[i].isActive) {
        isActive = true
        break
      }
    }

    if (isActive) this.active()
    else this.inactive()
  }

  active() {
    if (this.isActive) return
    this.idleTicks = 0
    this.isActive = true
    this._updateActive(true)
  }

  inactive() {
    if (!this.isActive) return
    this.isActive = false
    this._updateActive(false)
  }

  _updateActive(active) {
    const info = { active }

    for (const peer of this.pendingPeers) {
      peer.topic.state.stats.wireInfo.tx++
      peer.wireInfo.send(info)
    }
    for (const peer of this.peers) {
      peer.topic.state.stats.wireInfo.tx++
      peer.wireInfo.send(info)
    }

    this._checkGC()

    if (active) this.state._onActive(this)
  }

  teardown() {
    if (this.destroyed) return
    this.destroyed = true

    this.state.stats.topicsGcd++

    for (let i = this.peers.length - 1; i >= 0; i--) {
      this.peers[i].channel.close()
    }

    for (let i = this.pendingPeers.length - 1; i >= 0; i--) {
      this.pendingPeers[i].channel.close()
    }

    const hex = b4a.toString(this.id, 'hex')

    this.gcing = false
    this.state.topics.delete(hex)
    this.state._removeGC(this)

    for (let i = this.sessions.length - 1; i >= 0; i--) {
      this.state.stats.sessionsClosed++
      const session = this.sessions[i]
      if (session.handlers.ondestroy) session.handlers.ondestroy(session)
    }
  }

  addStream(stream) {
    this._onopen(getMuxer(stream), false)
  }

  _proveCapabilityTo(stream) {
    return this._makeCapability(stream.isInitiator, stream.handshakeHash)
  }

  _makeCapability(isInitiator, handshakeHash) {
    return crypto.hash([isInitiator ? NS_INITATOR : NS_RESPONDER, this.capability, handshakeHash])
  }

  _addPeer(peer, open) {
    if (
      !b4a.equals(
        open.capability,
        this._makeCapability(!peer.stream.isInitiator, peer.stream.handshakeHash)
      )
    ) {
      peer.channel.close()
      return
    }

    if (peer.pending) {
      peer.unlink(this.pendingPeers)
    }

    peer.active = open.active
    peer.pending = false
    peer.index = this.peers.push(peer) - 1

    if (peer.active) {
      this.activePeers++
      this._checkGC()
    }

    for (let i = this.sessions.length - 1; i >= 0; i--) {
      const session = this.sessions[i]
      const handlers = session.handlers

      if (handlers.onpeeradd) handlers.onpeeradd(peer, session)
      if (peer.active && handlers.onpeeractive) handlers.onpeeractive(peer, session)
    }
  }

  _checkGC() {
    const shouldGC = this.activePeers === 0 && this.sessions.length === 0

    if (shouldGC) {
      if (!this.gcing) {
        this.gcing = true
        this.state._addGC(this)
      }
    } else {
      if (this.gcing) {
        this.gcing = false
        this.state._removeGC(this)
      }
    }
  }

  _removePeer(peer) {
    this.state.stats.peersRemoved++
    peer.removed = true
    this.peersByStream.delete(peer.stream)

    if (peer.pending) {
      peer.unlink(this.pendingPeers)
      return
    }

    const active = peer.active

    if (active) {
      peer.active = false
      this.activePeers--
      this._checkGC()
    }

    peer.unlink(this.peers)

    for (let i = this.sessions.length - 1; i >= 0; i--) {
      const session = this.sessions[i]
      const handlers = session.handlers

      if (active && handlers.onpeerinactive) handlers.onpeerinactive(peer, session)
      if (handlers.onpeerremove) handlers.onpeerremove(peer, session)
    }
  }

  _onannounce(wakeup, peer) {
    for (let i = this.sessions.length - 1; i >= 0; i--) {
      const session = this.sessions[i]
      const handlers = session.handlers

      if (handlers.onannounce) handlers.onannounce(wakeup, peer, session)
    }
  }

  _onlookup(req, peer) {
    for (let i = this.sessions.length - 1; i >= 0; i--) {
      const session = this.sessions[i]
      const handlers = session.handlers

      if (handlers.onlookup) handlers.onlookup(req, peer, session)
    }
  }

  _oninfo(info, peer) {
    if (info.active) {
      if (!peer.active) {
        peer.active = true
        this.activePeers++
        this._checkGC()

        for (let i = this.sessions.length - 1; i >= 0; i--) {
          const session = this.sessions[i]
          const handlers = session.handlers

          if (handlers.onpeeractive) handlers.onpeeractive(peer, session)
        }
      }
    } else {
      if (peer.active) {
        peer.active = false
        this.activePeers--
        this._checkGC()

        for (let i = this.sessions.length - 1; i >= 0; i--) {
          const session = this.sessions[i]
          const handlers = session.handlers

          if (handlers.onpeerinactive) handlers.onpeerinactive(peer, session)
        }
      }
    }
  }

  _onopen(muxer, unique) {
    if (!unique && this.peersByStream.has(muxer.stream)) return

    const peer = new WakeupPeer(this)
    const ch = muxer.createChannel({
      userData: peer,
      protocol: 'wakeup',
      id: this.id,
      handshake: Handshake,
      messages: [
        { encoding: Lookup, onmessage: onlookup },
        { encoding: Announce, onmessage: onannounce },
        { encoding: Info, onmessage: onchannelinfo }
      ],
      onopen: onchannelopen,
      onclose: onchannelclose
    })

    if (!ch) return

    this.state.stats.peersAdded++

    peer.channel = ch
    peer.stream = muxer.stream

    peer.wireLookup = ch.messages[0]
    peer.wireAnnounce = ch.messages[1]
    peer.wireInfo = ch.messages[2]

    peer.index = this.pendingPeers.push(peer) - 1
    this.peersByStream.set(muxer.stream, peer)

    ch.open({
      version: 0,
      capability: this._proveCapabilityTo(muxer.stream),
      active: this.isActive
    })
  }
}

function onchannelopen(open, channel) {
  const peer = channel.userData
  peer.topic._addPeer(peer, open)
}

function onchannelclose(close, channel) {
  const peer = channel.userData
  peer.topic._removePeer(peer)
}

function onlookup(req, channel) {
  const peer = channel.userData
  peer.topic.state.stats.wireLookup.rx++
  peer.topic._onlookup(req, peer)
}

function onannounce(wakeup, channel) {
  const peer = channel.userData
  peer.topic.state.stats.wireAnnounce.rx++
  peer.topic._onannounce(wakeup, peer)
}

function onchannelinfo(info, channel) {
  const peer = channel.userData
  peer.topic.state.stats.wireInfo.rx++
  peer.topic._oninfo(info, peer)
}

function getMuxer(stream) {
  if (Protomux.isProtomux(stream)) return stream
  if (stream.noiseStream.userData) return stream.noiseStream.userData
  const mux = Protomux.from(stream.noiseStream)
  stream.noiseStream.userData = mux
  return mux
}

function noop() {}
{
  "name": "protomux-wakeup",
  "version": "2.9.0",
  "description": "Wakeup protocol over protomux",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.6.7",
    "hypercore-crypto": "^3.5.0",
    "hyperschema": "^1.10.4",
    "protomux": "^3.10.1"
  },
  "devDependencies": {
    "@hyperswarm/secret-stream": "^6.8.1",
    "brittle": "^3.17.1",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "prom-client": "^15.1.3"
  },
  "files": [
    "index.js",
    "spec/hyperschema/*.js"
  ],
  "scripts": {
    "format": "prettier --write .",
    "test": "prettier --check . && lunte && brittle test/*.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/protomux-wakeup.git"
  },
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/protomux-wakeup/issues"
  },
  "homepage": "https://github.com/holepunchto/protomux-wakeup"
}
// This file is autogenerated by the hyperschema compiler
// Schema Version: 1
/* eslint-disable camelcase */
/* eslint-disable quotes */

const VERSION = 1
const { c } = require('hyperschema/runtime')

// eslint-disable-next-line no-unused-vars
let version = VERSION

// @wakeup/info
const encoding0 = {
  preencode(state, m) {
    state.end++ // max flag is 1 so always one byte
  },
  encode(state, m) {
    const flags = m.active ? 1 : 0

    c.uint.encode(state, flags)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      active: (flags & 1) !== 0
    }
  }
}

// @wakeup/handshake
const encoding1 = {
  preencode(state, m) {
    c.uint.preencode(state, m.version)
    c.fixed32.preencode(state, m.capability)
    state.end++ // max flag is 1 so always one byte
  },
  encode(state, m) {
    const flags = m.active ? 1 : 0

    c.uint.encode(state, m.version)
    c.fixed32.encode(state, m.capability)
    c.uint.encode(state, flags)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const r1 = c.fixed32.decode(state)
    const flags = c.uint.decode(state)

    return {
      version: r0,
      capability: r1,
      active: (flags & 1) !== 0
    }
  }
}

// @wakeup/writer
const encoding2 = {
  preencode(state, m) {
    c.fixed32.preencode(state, m.key)
    c.uint.preencode(state, m.length)
  },
  encode(state, m) {
    c.fixed32.encode(state, m.key)
    c.uint.encode(state, m.length)
  },
  decode(state) {
    const r0 = c.fixed32.decode(state)
    const r1 = c.uint.decode(state)

    return {
      key: r0,
      length: r1
    }
  }
}

// @wakeup/announce
const encoding3 = c.array(encoding2)

// @wakeup/lookup
const encoding4 = {
  preencode(state, m) {
    state.end++ // max flag is 1 so always one byte

    if (m.hash) c.fixed32.preencode(state, m.hash)
  },
  encode(state, m) {
    const flags = m.hash ? 1 : 0

    c.uint.encode(state, flags)

    if (m.hash) c.fixed32.encode(state, m.hash)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      hash: (flags & 1) !== 0 ? c.fixed32.decode(state) : null
    }
  }
}

function setVersion(v) {
  version = v
}

function encode(name, value, v = VERSION) {
  version = v
  return c.encode(getEncoding(name), value)
}

function decode(name, buffer, v = VERSION) {
  version = v
  return c.decode(getEncoding(name), buffer)
}

function getEnum(name) {
  switch (name) {
    default:
      throw new Error('Enum not found ' + name)
  }
}

function getEncoding(name) {
  switch (name) {
    case '@wakeup/info':
      return encoding0
    case '@wakeup/handshake':
      return encoding1
    case '@wakeup/writer':
      return encoding2
    case '@wakeup/announce':
      return encoding3
    case '@wakeup/lookup':
      return encoding4
    default:
      throw new Error('Encoder not found ' + name)
  }
}

function getStruct(name, v = VERSION) {
  const enc = getEncoding(name)
  return {
    preencode(state, m) {
      version = v
      enc.preencode(state, m)
    },
    encode(state, m) {
      version = v
      enc.encode(state, m)
    },
    decode(state) {
      version = v
      return enc.decode(state)
    }
  }
}

const resolveStruct = getStruct // compat

module.exports = {
  resolveStruct,
  getStruct,
  getEnum,
  getEncoding,
  encode,
  decode,
  setVersion,
  version
}
const b4a = require('b4a')
const c = require('compact-encoding')
const queueTick = require('queue-tick')
const safetyCatch = require('safety-catch')
const unslab = require('unslab')

const MAX_BUFFERED = 32768
const MAX_BACKLOG = Infinity // TODO: impl "open" backpressure
const MAX_BATCH = 8 * 1024 * 1024

class Channel {
  constructor(
    mux,
    info,
    userData,
    protocol,
    aliases,
    id,
    handshake,
    messages,
    onopen,
    onclose,
    ondestroy,
    ondrain
  ) {
    this.userData = userData
    this.protocol = protocol
    this.aliases = aliases
    this.id = id
    this.handshake = null
    this.messages = []

    this.opened = false
    this.closed = false
    this.destroyed = false

    this.onopen = onopen
    this.onclose = onclose
    this.ondestroy = ondestroy
    this.ondrain = ondrain

    this._handshake = handshake
    this._mux = mux
    this._info = info
    this._localId = 0
    this._remoteId = 0
    this._active = 0
    this._extensions = null

    this._decBound = this._dec.bind(this)
    this._decAndDestroyBound = this._decAndDestroy.bind(this)

    this._openedPromise = null
    this._openedResolve = null

    this._destroyedPromise = null
    this._destroyedResolve = null

    for (const m of messages) this.addMessage(m)
  }

  get drained() {
    return this._mux.drained
  }

  fullyOpened() {
    if (this.opened) return Promise.resolve(true)
    if (this.closed) return Promise.resolve(false)
    if (this._openedPromise) return this._openedPromise

    this._openedPromise = new Promise((resolve) => {
      this._openedResolve = resolve
    })
    return this._openedPromise
  }

  fullyClosed() {
    if (this.destroyed) return Promise.resolve()
    if (this._destroyedPromise) return this._destroyedPromise

    this._destroyedPromise = new Promise((resolve) => {
      this._destroyedResolve = resolve
    })
    return this._destroyedPromise
  }

  open(handshake) {
    const id = this._mux._free.length > 0 ? this._mux._free.pop() : this._mux._local.push(null) - 1

    this._info.opened++
    this._info.lastChannel = this
    this._localId = id + 1
    this._mux._local[id] = this

    if (this._remoteId === 0) {
      this._info.outgoing.push(this._localId)
    }

    const state = { buffer: null, start: 2, end: 2 }

    c.uint.preencode(state, this._localId)
    c.string.preencode(state, this.protocol)
    c.optionalBuffer.preencode(state, this.id)
    if (this._handshake) this._handshake.preencode(state, handshake)

    state.buffer = this._mux._alloc(state.end)

    state.buffer[0] = 0
    state.buffer[1] = 1
    c.uint.encode(state, this._localId)
    c.string.encode(state, this.protocol)
    c.optionalBuffer.encode(state, this.id)
    if (this._handshake) this._handshake.encode(state, handshake)

    this._mux._write0(state.buffer)
  }

  _dec() {
    if (--this._active === 0 && this.closed === true) this._destroy()
  }

  _decAndDestroy(err) {
    this._dec()
    this._mux._safeDestroy(err)
  }

  _fullyOpenSoon() {
    this._mux._remote[this._remoteId - 1].session = this
    queueTick(this._fullyOpenOrDestroy.bind(this))
  }

  _fullyOpenOrDestroy() {
    try {
      this._fullyOpen()
    } catch (err) {
      this._mux._safeDestroyBound(err)
    }
  }

  _fullyOpen() {
    if (this.opened === true || this.closed === true) return

    const remote = this._mux._remote[this._remoteId - 1]

    this.handshake = this._handshake ? this._handshake.decode(remote.state) : null
    this._track(this.onopen(this.handshake, this))

    remote.session = this
    remote.state = null
    if (remote.pending !== null) this._drain(remote)
    if (this._mux._destroying === true) return

    this.opened = true
    this._resolveOpen(true)
  }

  _resolveOpen(opened) {
    if (this._openedResolve !== null) {
      this._openedResolve(opened)
      this._openedResolve = this._openedPromise = null
    }
  }

  _resolveDestroyed() {
    if (this._destroyedResolve !== null) {
      this._destroyedResolve()
      this._destroyedResolve = this._destroyedPromise = null
    }
  }

  _drain(remote) {
    for (let i = 0; i < remote.pending.length; i++) {
      const p = remote.pending[i]
      this._mux._buffered -= byteSize(p.state)
      this._recv(p.type, p.state)
      if (this._mux._destroying === true) return
    }

    remote.pending = null
    this._mux._resumeMaybe()
  }

  _track(p) {
    if (isPromise(p) === true) {
      this._active++
      return p.then(this._decBound, this._decAndDestroyBound)
    }

    return null
  }

  _close(isRemote) {
    if (this.closed === true) return
    this.closed = true

    this._info.opened--
    if (this._info.lastChannel === this) this._info.lastChannel = null

    if (this._remoteId > 0) {
      this._mux._remote[this._remoteId - 1] = null
      this._remoteId = 0
      // If remote has acked, we can reuse the local id now
      // otherwise, we need to wait for the "ack" to arrive
      this._mux._free.push(this._localId - 1)
    }

    this._mux._local[this._localId - 1] = null
    this._localId = 0

    this._mux._gc(this._info)
    this._track(this.onclose(isRemote, this))

    if (this._active === 0) this._destroy()

    this._resolveOpen(false)
  }

  _destroy() {
    if (this.destroyed === true) return
    this.destroyed = true
    this._track(this.ondestroy(this))
    this._resolveDestroyed()
  }

  _recv(type, state) {
    if (type < this.messages.length) {
      const m = this.messages[type]
      const p = m.recv(state, this)
      if (m.autoBatch === true) return p
    }
    return null
  }

  cork() {
    this._mux.cork()
  }

  uncork() {
    this._mux.uncork()
  }

  close() {
    if (this.closed === true) return

    const state = { buffer: null, start: 2, end: 2 }

    c.uint.preencode(state, this._localId)

    state.buffer = this._mux._alloc(state.end)

    state.buffer[0] = 0
    state.buffer[1] = 3
    c.uint.encode(state, this._localId)

    this._close(false)
    this._mux._write0(state.buffer)
  }

  addMessage(opts) {
    if (!opts) return this._skipMessage()

    const type = this.messages.length
    const autoBatch = opts.autoBatch !== false
    const encoding = opts.encoding || c.raw
    const onmessage = opts.onmessage || noop

    const s = this
    const typeLen = encodingLength(c.uint, type)

    const m = {
      type,
      autoBatch,
      encoding,
      onmessage,
      recv(state, session) {
        return session._track(m.onmessage(encoding.decode(state), session))
      },
      send(m, session = s) {
        if (session.closed === true) return false

        const mux = session._mux
        const state = { buffer: null, start: 0, end: typeLen }

        if (mux._batch !== null) {
          encoding.preencode(state, m)
          state.buffer = mux._alloc(state.end)

          c.uint.encode(state, type)
          encoding.encode(state, m)

          mux._pushBatch(session._localId, state.buffer)
          return true
        }

        c.uint.preencode(state, session._localId)
        encoding.preencode(state, m)

        state.buffer = mux._alloc(state.end)

        c.uint.encode(state, session._localId)
        c.uint.encode(state, type)
        encoding.encode(state, m)

        mux.drained = mux.stream.write(state.buffer)

        return mux.drained
      }
    }

    this.messages.push(m)

    return m
  }

  _skipMessage() {
    const type = this.messages.length
    const m = {
      type,
      encoding: c.raw,
      onmessage: noop,
      recv(state, session) {},
      send(m, session) {}
    }

    this.messages.push(m)
    return m
  }
}

module.exports = class Protomux {
  constructor(stream, { alloc } = {}) {
    if (stream.userData === null) stream.userData = this

    this.isProtomux = true
    this.stream = stream
    this.corked = 0
    this.drained = true

    this._alloc =
      alloc || (typeof stream.alloc === 'function' ? stream.alloc.bind(stream) : b4a.allocUnsafe)
    this._safeDestroyBound = this._safeDestroy.bind(this)
    this._uncorkBound = this.uncork.bind(this)

    this._remoteBacklog = 0
    this._buffered = 0
    this._paused = false
    this._remote = []
    this._local = []
    this._free = []
    this._batch = null
    this._batchState = null

    this._infos = new Map()
    this._notify = new Map()
    // stream.destroyed flips asynchronously on streamx-based transports.
    this._destroying = false

    this.stream.on('data', this._ondata.bind(this))
    this.stream.on('drain', this._ondrain.bind(this))
    this.stream.on('end', this._onend.bind(this))
    this.stream.on('error', noop) // we handle this in "close"
    this.stream.on('close', this._shutdown.bind(this))
  }

  static from(stream, opts) {
    if (stream.userData && stream.userData.isProtomux) return stream.userData
    if (stream.isProtomux) return stream
    return new this(stream, opts)
  }

  static isProtomux(mux) {
    return typeof mux === 'object' && mux.isProtomux === true
  }

  *[Symbol.iterator]() {
    for (const session of this._local) {
      if (session !== null) yield session
    }
  }

  isIdle() {
    return this._local.length === this._free.length
  }

  cork() {
    if (++this.corked === 1) {
      this._batch = []
      this._batchState = { buffer: null, start: 0, end: 1 }
    }
  }

  uncork() {
    if (--this.corked === 0) {
      this._sendBatch(this._batch, this._batchState)
      this._batch = null
      this._batchState = null
    }
  }

  getLastChannel({ protocol, id = null }) {
    const key = toKey(protocol, id)
    const info = this._infos.get(key)
    if (info) return info.lastChannel
    return null
  }

  pair({ protocol, id = null }, notify) {
    this._notify.set(toKey(protocol, id), notify)
  }

  unpair({ protocol, id = null }) {
    this._notify.delete(toKey(protocol, id))
  }

  opened({ protocol, id = null }) {
    const key = toKey(protocol, id)
    const info = this._infos.get(key)
    return info ? info.opened > 0 : false
  }

  createChannel({
    userData = null,
    protocol,
    aliases = [],
    id = null,
    unique = true,
    handshake = null,
    messages = [],
    onopen = noop,
    onclose = noop,
    ondestroy = noop,
    ondrain = noop
  }) {
    if (this.stream.destroyed) return null

    const info = this._get(protocol, id, aliases)
    if (unique && info.opened > 0) return null

    if (info.incoming.length === 0) {
      return new Channel(
        this,
        info,
        userData,
        protocol,
        aliases,
        id,
        handshake,
        messages,
        onopen,
        onclose,
        ondestroy,
        ondrain
      )
    }

    this._remoteBacklog--

    const remoteId = info.incoming.shift()
    const r = this._remote[remoteId - 1]
    if (r === null) return null

    const session = new Channel(
      this,
      info,
      userData,
      protocol,
      aliases,
      id,
      handshake,
      messages,
      onopen,
      onclose,
      ondestroy,
      ondrain
    )

    session._remoteId = remoteId
    session._fullyOpenSoon()

    return session
  }

  _pushBatch(localId, buffer) {
    if (this._batchState.end >= MAX_BATCH) {
      this._sendBatch(this._batch, this._batchState)
      this._batch = []
      this._batchState = { buffer: null, start: 0, end: 1 }
    }

    if (this._batch.length === 0 || this._batch[this._batch.length - 1].localId !== localId) {
      this._batchState.end++
      c.uint.preencode(this._batchState, localId)
    }
    c.buffer.preencode(this._batchState, buffer)
    this._batch.push({ localId, buffer })
  }

  _sendBatch(batch, state) {
    if (batch.length === 0) return

    let prev = batch[0].localId

    state.buffer = this._alloc(state.end)
    state.buffer[state.start++] = 0
    state.buffer[state.start++] = 0

    c.uint.encode(state, prev)

    for (let i = 0; i < batch.length; i++) {
      const b = batch[i]
      if (prev !== b.localId) {
        state.buffer[state.start++] = 0
        c.uint.encode(state, (prev = b.localId))
      }
      c.buffer.encode(state, b.buffer)
    }

    this.drained = this.stream.write(state.buffer)
  }

  _get(protocol, id, aliases = []) {
    const key = toKey(protocol, id)

    let info = this._infos.get(key)
    if (info) return info

    info = {
      key,
      protocol,
      aliases: [],
      id,
      pairing: 0,
      opened: 0,
      incoming: [],
      outgoing: [],
      lastChannel: null
    }
    this._infos.set(key, info)

    for (const alias of aliases) {
      const key = toKey(alias, id)
      info.aliases.push(key)

      this._infos.set(key, info)
    }

    return info
  }

  _gc(info) {
    if (info.opened === 0 && info.outgoing.length === 0 && info.incoming.length === 0) {
      this._infos.delete(info.key)

      for (const alias of info.aliases) this._infos.delete(alias)
    }
  }

  _ondata(buffer) {
    if (buffer.byteLength === 0) return // ignore empty frames...
    try {
      const state = { buffer, start: 0, end: buffer.byteLength }
      this._decode(c.uint.decode(state), state)
    } catch (err) {
      this._safeDestroy(err)
    }
  }

  _ondrain() {
    this.drained = true

    for (const s of this._local) {
      if (s !== null) s._track(s.ondrain(s))
    }
  }

  _onend() {
    // TODO: support half open mode for the users who wants that here
    this.stream.end()
  }

  _decode(remoteId, state) {
    const type = c.uint.decode(state)

    if (remoteId === 0) {
      return this._oncontrolsession(type, state)
    }

    const r = remoteId <= this._remote.length ? this._remote[remoteId - 1] : null

    // if the channel is closed ignore - could just be a pipeline message...
    if (r === null) return null

    if (r.pending !== null) {
      this._bufferMessage(r, type, state)
      return null
    }

    return r.session._recv(type, state)
  }

  _oncontrolsession(type, state) {
    switch (type) {
      case 0:
        this._onbatch(state)
        break

      case 1:
        // return the promise back up as this has sideeffects so we can batch reply
        return this._onopensession(state)

      case 2:
        this._onrejectsession(state)
        break

      case 3:
        this._onclosesession(state)
        break
    }

    return null
  }

  _bufferMessage(r, type, { buffer, start, end }) {
    const state = { buffer, start, end } // copy
    r.pending.push({ type, state })
    this._buffered += byteSize(state)
    this._pauseMaybe()
  }

  _pauseMaybe() {
    if (this._paused === true || this._buffered <= MAX_BUFFERED) return
    this._paused = true
    this.stream.pause()
  }

  _resumeMaybe() {
    if (this._paused === false || this._buffered > MAX_BUFFERED) return
    this._paused = false
    this.stream.resume()
  }

  _onbatch(state) {
    const end = state.end
    let remoteId = c.uint.decode(state)

    let waiting = null

    while (state.end > state.start) {
      const len = c.uint.decode(state)
      if (len === 0) {
        remoteId = c.uint.decode(state)
        continue
      }
      state.end = state.start + len
      // if batch contains more than one message, cork it so we reply back with a batch
      if (end !== state.end && waiting === null) {
        waiting = []
        this.cork()
      }
      const p = this._decode(remoteId, state)
      if (waiting !== null && p !== null) waiting.push(p)
      state.start = state.end
      state.end = end
    }

    if (waiting !== null) {
      // the waiting promises are not allowed to throw but we destroy the stream in case we are wrong
      Promise.all(waiting).then(this._uncorkBound, this._safeDestroyBound)
    }
  }

  _onopensession(state) {
    const remoteId = c.uint.decode(state)
    const protocol = c.string.decode(state)
    const id = unslab(c.optionalBuffer.decode(state))

    // remote tried to open the control session - auto reject for now
    // as we can use as an explicit control protocol declaration if we need to
    if (remoteId === 0) {
      this._rejectSession(0)
      return null
    }

    const rid = remoteId - 1
    const info = this._get(protocol, id)

    // allow the remote to grow the ids by one
    if (this._remote.length === rid) {
      this._remote.push(null)
    }

    if (rid >= this._remote.length || this._remote[rid] !== null) {
      throw new Error('Invalid open message')
    }

    if (info.outgoing.length > 0) {
      const localId = info.outgoing.shift()
      const session = this._local[localId - 1]

      if (session === null) {
        // we already closed the channel - ignore
        this._free.push(localId - 1)
        return null
      }

      this._remote[rid] = { state, pending: null, session: null }

      session._remoteId = remoteId
      session._fullyOpen()
      return null
    }

    const copyState = { buffer: state.buffer, start: state.start, end: state.end }
    this._remote[rid] = { state: copyState, pending: [], session: null }

    if (++this._remoteBacklog > MAX_BACKLOG) {
      throw new Error('Remote exceeded backlog')
    }

    info.pairing++
    info.incoming.push(remoteId)

    return this._requestSession(protocol, id, info).catch(this._safeDestroyBound)
  }

  _onrejectsession(state) {
    const localId = c.uint.decode(state)

    // TODO: can be done smarter...
    for (const info of this._infos.values()) {
      const i = info.outgoing.indexOf(localId)
      if (i === -1) continue

      info.outgoing.splice(i, 1)

      const session = this._local[localId - 1]

      this._free.push(localId - 1)
      if (session !== null) session._close(true)

      this._gc(info)
      return
    }

    throw new Error('Invalid reject message')
  }

  _onclosesession(state) {
    const remoteId = c.uint.decode(state)

    if (remoteId === 0) return // ignore

    const rid = remoteId - 1
    const r = rid < this._remote.length ? this._remote[rid] : null

    if (r === null) return

    if (r.session !== null) r.session._close(true)
  }

  async _requestSession(protocol, id, info) {
    const notify = this._notify.get(toKey(protocol, id)) || this._notify.get(toKey(protocol, null))

    if (notify) await notify(id)

    if (--info.pairing > 0) return

    while (info.incoming.length > 0) {
      this._rejectSession(info, info.incoming.shift())
    }

    this._gc(info)
  }

  _rejectSession(info, remoteId) {
    if (remoteId > 0) {
      const r = this._remote[remoteId - 1]

      if (r.pending !== null) {
        for (let i = 0; i < r.pending.length; i++) {
          this._buffered -= byteSize(r.pending[i].state)
        }
      }

      this._remote[remoteId - 1] = null
      this._resumeMaybe()
    }

    const state = { buffer: null, start: 2, end: 2 }

    c.uint.preencode(state, remoteId)

    state.buffer = this._alloc(state.end)

    state.buffer[0] = 0
    state.buffer[1] = 2
    c.uint.encode(state, remoteId)

    this._write0(state.buffer)
  }

  _write0(buffer) {
    if (this._batch !== null) {
      this._pushBatch(0, buffer.subarray(1))
      return
    }

    this.drained = this.stream.write(buffer)
  }

  destroy(err) {
    this._destroying = true
    this.stream.destroy(err)
  }

  _safeDestroy(err) {
    safetyCatch(err)
    this._destroying = true
    this.stream.destroy(err)
  }

  _shutdown() {
    this._destroying = true
    for (const s of this._local) {
      if (s !== null) s._close(true)
    }
  }
}

function noop() {}

function toKey(protocol, id) {
  return protocol + '##' + (id ? b4a.toString(id, 'hex') : '')
}

function byteSize(state) {
  return 512 + (state.end - state.start)
}

function isPromise(p) {
  return !!(p && typeof p.then === 'function')
}

function encodingLength(enc, val) {
  const state = { buffer: null, start: 0, end: 0 }
  enc.preencode(state, val)
  return state.end
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "protomux",
  "version": "3.11.0",
  "description": "Multiplex multiple message oriented protocols over a stream",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.3.1",
    "compact-encoding": "^3.0.0",
    "queue-tick": "^1.0.0",
    "safety-catch": "^1.0.1",
    "unslab": "^1.3.0"
  },
  "devDependencies": {
    "@hyperswarm/secret-stream": "^6.0.0",
    "brittle": "^3.0.0",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/protomux.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/protomux/issues"
  },
  "homepage": "https://github.com/holepunchto/protomux"
}
{
  "name": "queue-tick",
  "version": "1.0.1",
  "description": "Next tick shim that prefers process.nextTick over queueMicrotask for compat",
  "main": "./process-next-tick.js",
  "browser": "./queue-microtask.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^16.0.3",
    "tape": "^5.3.1"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/queue-tick.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/queue-tick/issues"
  },
  "homepage": "https://github.com/mafintosh/queue-tick"
}
module.exports = (typeof process !== 'undefined' && typeof process.nextTick === 'function')
  ? process.nextTick.bind(process)
  : require('./queue-microtask')
module.exports = typeof queueMicrotask === 'function' ? queueMicrotask : (fn) => Promise.resolve().then(fn)
require.addon = require('require-addon')

module.exports = require.addon('.', __filename)
const binding = require('./binding')

exports.get = function get(field, bit) {
  const n = field.byteLength * 8

  if (bit < 0) bit += n
  if (bit < 0 || bit >= n) return false

  return binding.quickbit_napi_get(toBuffer(field), bit) !== 0
}

exports.set = function set(field, bit, value = true) {
  const n = field.byteLength * 8

  if (bit < 0) bit += n
  if (bit < 0 || bit >= n) return false

  return binding.quickbit_napi_set(toBuffer(field), bit, value ? 1 : 0) !== 0
}

exports.fill = function fill(
  field,
  value,
  start = 0,
  end = field.byteLength * 8
) {
  const n = field.byteLength * 8

  if (start < 0) start += n
  if (end < 0) end += n
  if (start < 0 || start >= field.byteLength * 8 || start >= end) return field

  binding.quickbit_napi_fill(toBuffer(field), value ? 1 : 0, start, end)
  return field
}

exports.clear = function clear(field, ...chunks) {
  binding.quickbit_napi_clear(toBuffer(field), chunks.map(toBufferChunk))
}

exports.findFirst = function findFirst(field, value, position = 0) {
  const n = field.byteLength * 8

  if (position < 0) position += n
  if (position < 0) position = 0
  if (position >= n) return -1

  return binding.quickbit_napi_find_first(
    toBuffer(field),
    value ? 1 : 0,
    position
  )
}

exports.findLast = function findLast(
  field,
  value,
  position = field.byteLength * 8 - 1
) {
  const n = field.byteLength * 8

  if (position < 0) position += n
  if (position < 0) return -1
  if (position >= n) position = n - 1

  return binding.quickbit_napi_find_last(
    toBuffer(field),
    value ? 1 : 0,
    position
  )
}

function toBuffer(field) {
  if (field.BYTES_PER_ELEMENT === 1) return field
  return new Uint8Array(field.buffer, field.byteOffset, field.byteLength)
}

function toBufferChunk(chunk) {
  return { field: toBuffer(chunk.field), offset: chunk.offset }
}

class Index {
  static from(fieldOrChunks, byteLength = -1) {
    if (Array.isArray(fieldOrChunks)) {
      return new SparseIndex(fieldOrChunks, byteLength)
    } else {
      return new DenseIndex(fieldOrChunks, byteLength)
    }
  }

  constructor(byteLength) {
    this._byteLength = byteLength
    this.handle = Buffer.allocUnsafe(binding.sizeof_quickbit_index_t)
  }

  get byteLength() {
    return this._byteLength
  }

  skipFirst(value, position = 0) {
    const n = this.byteLength * 8

    if (position < 0) position += n
    if (position < 0) position = 0
    if (position >= n) return n - 1

    return binding.quickbit_napi_skip_first(
      this.handle,
      this.byteLength,
      value ? 1 : 0,
      position
    )
  }

  skipLast(value, position = this.byteLength * 8 - 1) {
    const n = this.byteLength * 8

    if (position < 0) position += n
    if (position < 0) return 0
    if (position >= n) position = n - 1

    return binding.quickbit_napi_skip_last(
      this.handle,
      this.byteLength,
      value ? 1 : 0,
      position
    )
  }
}

exports.Index = Index

class DenseIndex extends Index {
  constructor(field, byteLength) {
    super(byteLength)
    this.field = field

    binding.quickbit_napi_index_init(this.handle, toBuffer(this.field))
  }

  get byteLength() {
    if (this._byteLength !== -1) return this._byteLength
    return this.field.byteLength
  }

  update(bit) {
    const n = this.byteLength * 8

    if (bit < 0) bit += n
    if (bit < 0 || bit >= n) return false

    return (
      binding.quickbit_napi_index_update(
        this.handle,
        toBuffer(this.field),
        bit
      ) !== 0
    )
  }
}

function selectChunk(chunks, offset) {
  for (let i = 0; i < chunks.length; i++) {
    const next = chunks[i]

    const start = next.offset
    const end = next.offset + next.field.byteLength

    if (offset >= start && offset + 16 <= end) {
      return next
    }
  }

  return null
}

class SparseIndex extends Index {
  constructor(chunks, byteLength) {
    super(byteLength)
    this.chunks = chunks

    binding.quickbit_napi_index_init_sparse(
      this.handle,
      this.chunks.map(toBufferChunk)
    )
  }

  get byteLength() {
    if (this._byteLength !== -1) return this._byteLength
    const last = this.chunks[this.chunks.length - 1]
    return last ? last.offset + last.field.byteLength : 0
  }

  update(bit) {
    const n = this.byteLength * 8

    if (bit < 0) bit += n
    if (bit < 0 || bit >= n) return false

    const j = Math.floor(bit / 128)

    const offset = j * 16

    const chunk = selectChunk(this.chunks, offset)

    if (chunk === null) return false

    return (
      binding.quickbit_napi_index_update_sparse(
        this.handle,
        toBuffer(chunk.field),
        chunk.offset,
        bit
      ) !== 0
    )
  }
}
{
  "name": "quickbit-native",
  "version": "2.4.8",
  "description": "libquickbit JavaScript bindings for Node.js",
  "main": "index.js",
  "files": [
    "index.js",
    "macros.h",
    "binding.cc",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "npm run lint && npm run test:bare && npm run test:node",
    "test:bare": "bare test.mjs",
    "test:node": "node test.mjs",
    "lint": "prettier . --check"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/quickbit-native.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/quickbit-native/issues"
  },
  "homepage": "https://github.com/holepunchto/quickbit-native#readme",
  "dependencies": {
    "require-addon": "^1.1.0"
  },
  "devDependencies": {
    "b4a": "^1.6.7",
    "bare-compat-napi": "^1.3.2",
    "brittle": "^3.1.0",
    "cmake-bare": "^1.1.7",
    "cmake-fetch": "^1.1.0",
    "cmake-napi": "^1.0.2",
    "prettier": "^3.5.3",
    "prettier-config-standard": "^7.0.0"
  }
}
const simdle = require('simdle-universal')

const INDEX_LEN = (16 /* root */ + 128 * 16 /* children */) * 2

const get = exports.get = function get (field, bit) {
  const n = field.byteLength * 8

  if (bit < 0) bit += n
  if (bit < 0 || bit >= n) return false

  const m = field.BYTES_PER_ELEMENT * 8

  const offset = bit & (m - 1)
  const i = (bit - offset) / m

  return (field[i] & (1 << offset)) !== 0
}

const set = exports.set = function set (field, bit, value = true) {
  const n = field.byteLength * 8

  if (bit < 0) bit += n
  if (bit < 0 || bit >= n) return false

  const m = field.BYTES_PER_ELEMENT * 8

  const offset = bit & (m - 1)
  const i = (bit - offset) / m
  const mask = 1 << offset

  if (value) {
    if ((field[i] & mask) !== 0) return false
  } else {
    if ((field[i] & mask) === 0) return false
  }

  field[i] ^= mask

  return true
}

exports.fill = function fill (field, value, start = 0, end = field.byteLength * 8) {
  const n = field.byteLength * 8

  if (start < 0) start += n
  if (end < 0) end += n
  if (start < 0 || start >= field.byteLength * 8 || start >= end) return field

  const m = field.BYTES_PER_ELEMENT * 8

  let i, j

  {
    const offset = start & (m - 1)
    i = (start - offset) / m

    if (offset !== 0) {
      let shift = m - offset
      if (end - start < shift) shift = end - start

      const mask = ((1 << shift) - 1) << offset

      if (value) field[i] |= mask
      else field[i] &= ~mask

      i++
    }
  }

  {
    const offset = end & (m - 1)
    j = (end - offset) / m

    if (offset !== 0 && j >= i) {
      const mask = (1 << offset) - 1

      if (value) field[j] |= mask
      else field[j] &= ~mask
    }
  }

  if (i < j) field.fill(value ? (2 ** m) - 1 : 0, i, j)

  return field
}

exports.clear = function clear (field, ...chunks) {
  const n = field.byteLength

  for (const chunk of chunks) {
    if (chunk.offset >= n) continue

    const m = chunk.field.byteLength

    let i = chunk.offset
    let j = 0

    while (((i & 15) !== 0 || (j & 15) !== 0) && i < n && j < m) {
      field[i] = field[i] & ~chunk.field[j]
      i++
      j++
    }

    if (i + 15 < n && j + 15 < m) {
      const len = Math.min(n - (n & 15) - i, m - (m & 15) - j)

      simdle.clear(field.subarray(i, i + len), chunk.field.subarray(j, j + len), field.subarray(i, i + len))
    }

    while (i < n && j < m) {
      field[i] = field[i] & ~chunk.field[j]
      i++
      j++
    }
  }
}

function bitOffset (bit, offset) {
  return !bit ? offset : (INDEX_LEN * 8 / 2) + offset
}

function byteOffset (bit, offset) {
  return !bit ? offset : (INDEX_LEN / 2) + offset
}

exports.findFirst = function findFirst (field, value, position = 0) {
  const n = field.byteLength * 8

  if (position < 0) position += n
  if (position < 0) position = 0
  if (position >= n) return -1

  value = !!value

  for (let i = position; i < n; i++) {
    if (get(field, i) === value) return i
  }

  return -1
}

exports.findLast = function findLast (field, value, position = field.byteLength * 8 - 1) {
  const n = field.byteLength * 8

  if (position < 0) position += n
  if (position < 0) return -1
  if (position >= n) position = n - 1

  value = !!value

  for (let i = position; i >= 0; i--) {
    if (get(field, i) === value) return i
  }

  return -1
}

const Index = exports.Index = class Index {
  static from (fieldOrChunks, byteLength = -1) {
    if (Array.isArray(fieldOrChunks)) {
      return new SparseIndex(fieldOrChunks, byteLength)
    } else {
      return new DenseIndex(fieldOrChunks, byteLength)
    }
  }

  constructor (byteLength) {
    this._byteLength = byteLength
    this.handle = new Uint32Array(INDEX_LEN / 4)
  }

  get byteLength () {
    return this._byteLength
  }

  skipFirst (value, position = 0) {
    const n = this.byteLength * 8

    if (position < 0) position += n
    if (position < 0) position = 0
    if (position >= n) return n - 1

    let i = Math.floor(position / 16384)

    if (i > 127) return position

    while (i <= 127 && get(this.handle, bitOffset(value, i))) {
      i++
    }

    if (i === 128) return n - 1

    let k = i * 16384
    let j = 0

    if (position > k) j = Math.floor((position - k) / 128)

    while (j <= 127 && get(this.handle, bitOffset(value, i * 128 + j + 128))) {
      j++
      k += 128
    }

    if (j === 128 && i !== 127) return this.skipFirst(value, (i + 1) * 16384)

    if (k > position) position = k

    return position < n ? position : n - 1
  }

  skipLast (value, position = this.byteLength * 8 - 1) {
    const n = this.byteLength * 8

    if (position < 0) position += n
    if (position < 0) return 0
    if (position >= n) position = n - 1

    let i = Math.floor(position / 16384)

    if (i > 127) return position

    while (i >= 0 && get(this.handle, bitOffset(value, i))) {
      i--
    }

    if (i === -1) return 0

    let k = ((i + 1) * 16384) - 1
    let j = 127

    if (position < k) j = 128 - Math.ceil((k - position) / 128)

    while (j >= 0 && get(this.handle, bitOffset(value, i * 128 + j + 128))) {
      j--
      k -= 128
    }

    if (j === -1 && i !== 0) return this.skipLast(value, i * 16384 - 1)

    if (k < position) position = k

    return position
  }
}

class DenseIndex extends Index {
  constructor (field, byteLength) {
    super(byteLength)
    this.field = field

    const m = field.BYTES_PER_ELEMENT

    for (let i = 0; i < 128; i++) {
      for (let j = 0; j < 128; j++) {
        const offset = (i * 128 + j) * 16
        let allz = true
        let allo = false

        if (offset + 16 <= this.field.byteLength) {
          const vec = this.field.subarray(offset / m, (offset + 16) / m)

          allz = simdle.allz(vec)
          allo = simdle.allo(vec)
        }

        const k = i * 128 + 128 + j

        set(this.handle, bitOffset(false, k), allz)
        set(this.handle, bitOffset(true, k), allo)
      }

      {
        const offset = byteOffset(false, i * 16 + 16) / 4
        const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

        set(this.handle, bitOffset(false, i), allo)
      }

      {
        const offset = byteOffset(true, i * 16 + 16) / 4
        const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

        set(this.handle, bitOffset(true, i), allo)
      }
    }
  }

  get byteLength () {
    if (this._byteLength !== -1) return this._byteLength
    return this.field.byteLength
  }

  update (bit) {
    const n = this.byteLength * 8

    if (bit < 0) bit += n
    if (bit < 0 || bit >= n) return false

    const m = this.field.BYTES_PER_ELEMENT

    const i = Math.floor(bit / 16384)
    const j = Math.floor(bit / 128)

    const offset = (j * 16) / m
    const vec = this.field.subarray(offset, offset + (16 / m))

    const allz = simdle.allz(vec)
    const allo = simdle.allo(vec)

    let changed = false

    if (set(this.handle, bitOffset(false, 128 + j), allz)) {
      changed = true

      const offset = byteOffset(false, i * 16 + 16) / 4
      const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

      set(this.handle, bitOffset(false, i), allo)
    }

    if (set(this.handle, bitOffset(true, 128 + j), allo)) {
      changed = true

      const offset = byteOffset(true, i * 16 + 16) / 4
      const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

      set(this.handle, bitOffset(true, i), allo)
    }

    return changed
  }
}

function selectChunk (chunks, offset) {
  for (let i = 0; i < chunks.length; i++) {
    const next = chunks[i]

    const start = next.offset
    const end = next.offset + next.field.byteLength

    if (offset >= start && offset + 16 <= end) {
      return next
    }
  }

  return null
}

class SparseIndex extends Index {
  constructor (chunks, byteLength) {
    super(byteLength)
    this.chunks = chunks

    for (let i = 0; i < 128; i++) {
      for (let j = 0; j < 128; j++) {
        const offset = (i * 128 + j) * 16
        let allz = true
        let allo = false

        const chunk = selectChunk(this.chunks, offset)

        if (chunk !== null) {
          const m = chunk.field.BYTES_PER_ELEMENT

          const vec = chunk.field.subarray((offset - chunk.offset) / m, (offset - chunk.offset + 16) / m)

          allz = simdle.allz(vec)
          allo = simdle.allo(vec)
        }

        const k = i * 128 + 128 + j

        set(this.handle, bitOffset(false, k), allz)
        set(this.handle, bitOffset(true, k), allo)
      }

      {
        const offset = byteOffset(false, i * 16 + 16) / 4
        const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

        set(this.handle, bitOffset(false, i), allo)
      }

      {
        const offset = byteOffset(true, i * 16 + 16) / 4
        const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

        set(this.handle, bitOffset(true, i), allo)
      }
    }
  }

  get byteLength () {
    if (this._byteLength !== -1) return this._byteLength
    const last = this.chunks[this.chunks.length - 1]
    return last ? last.offset + last.field.byteLength : 0
  }

  update (bit) {
    const n = this.byteLength * 8

    if (bit < 0) bit += n
    if (bit < 0 || bit >= n) return false

    const i = Math.floor(bit / 16384)
    const j = Math.floor(bit / 128)

    const offset = j * 16

    const chunk = selectChunk(this.chunks, offset)

    if (chunk === null) return false

    const m = chunk.field.BYTES_PER_ELEMENT

    const vec = chunk.field.subarray((offset - chunk.offset) / m, (offset - chunk.offset + 16) / m)

    const allz = simdle.allz(vec)
    const allo = simdle.allo(vec)

    let changed = false

    if (set(this.handle, bitOffset(false, 128 + j), allz)) {
      changed = true

      const offset = byteOffset(false, i * 16 + 16) / 4
      const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

      set(this.handle, bitOffset(false, i), allo)
    }

    if (set(this.handle, bitOffset(true, 128 + j), allo)) {
      changed = true

      const offset = byteOffset(true, i * 16 + 16) / 4
      const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

      set(this.handle, bitOffset(true, i), allo)
    }

    return changed
  }
}
const fallback = require('./fallback')

try {
  const native = require('quickbit-native')

  // These functions are faster in JavaScript
  exports.get = fallback.get
  exports.set = fallback.set
  exports.fill = fallback.fill

  // These functions are faster in C
  exports.clear = native.clear
  exports.findFirst = native.findFirst
  exports.findLast = native.findLast
  exports.Index = native.Index
} catch {
  module.exports = fallback
}
{
  "name": "quickbit-universal",
  "version": "2.2.0",
  "description": "Universal wrapper for libquickbit with a JavaScript fallback",
  "main": "index.js",
  "files": [
    "fallback.js",
    "index.js"
  ],
  "browser": {
    "./index.js": "./fallback.js"
  },
  "scripts": {
    "test": "standard && brittle test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/quickbit-universal.git"
  },
  "author": "Kasper Isager Dalsgarð <kasper@funktionel.co>",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/holepunchto/quickbit-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/quickbit-universal#readme",
  "dependencies": {
    "b4a": "^1.6.0",
    "simdle-universal": "^1.1.0"
  },
  "optionalDependencies": {
    "quickbit-native": "^2.2.0"
  },
  "devDependencies": {
    "brittle": "^3.1.0",
    "standard": "^17.0.0"
  }
}
class CacheEntry {
  constructor (key, index, map) {
    this.key = key
    this.index = index
    this.map = map
  }
}

class CacheValue {
  constructor (entry, value) {
    this.entry = entry
    this.value = value
  }
}

class Rache {
  constructor ({ maxSize = 65536, parent = null } = {}) {
    this.maxSize = parent?.maxSize || maxSize

    this._array = parent?._array || []
    this._map = new Map()
  }

  static from (cache) {
    return cache ? new this({ parent: cache }) : new this()
  }

  get globalSize () {
    return this._array.length
  }

  get size () {
    return this._map.size
  }

  sub () {
    return new Rache({ parent: this })
  }

  set (key, value) { // ~constant time
    const existing = this._map.get(key)
    if (existing !== undefined) {
      existing.value = value
      return
    }

    if (this._array.length >= this.maxSize) this._gc()

    const entry = new CacheEntry(key, this._array.length, this._map)
    this._array.push(entry)
    const cacheValue = new CacheValue(entry, value)
    this._map.set(key, cacheValue)
  }

  delete (key) {
    const existing = this._map.get(key)
    if (existing === undefined) return false

    this._delete(existing.entry.index)
    return true
  }

  get (key) {
    const existing = this._map.get(key)
    return existing === undefined ? undefined : existing.value
  }

  * [Symbol.iterator] () {
    for (const [key, { value }] of this._map) {
      yield [key, value]
    }
  }

  keys () {
    return this._map.keys()
  }

  * values () {
    for (const { value } of this._map.values()) {
      yield value
    }
  }

  clear () {
    // The entries in map linger on in _array,
    // so on top of clearing the map, we also kill the ref,
    // so that any gc running later on the old map won't interfere
    // (in case a new entry was added with the same key as a cleared entry)

    this._map.clear()
    this._map = new Map()
  }

  destroy () {
    this._map = null
    this._array = null
  }

  _gc () {
    this._delete(Math.floor(Math.random() * this._array.length))
  }

  _delete (index) { // ~constant time
    if (index >= this._array.length) throw new Error('Cannot delete unused index (logic bug?)')

    const head = this._array.pop()
    let removed = head

    if (index < this._array.length) {
      removed = this._array[index]
      head.index = index
      this._array[index] = head
    }

    removed.map.delete(removed.key)
  }
}

module.exports = Rache
{
  "name": "rache",
  "version": "1.0.0",
  "description": "Random-eviction cache",
  "main": "index.js",
  "scripts": {
    "test": "standard && brittle test.js --coverage"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/rache.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/rache/issues"
  },
  "homepage": "https://github.com/holepunchto/rache#readme",
  "files": [
    "index.js"
  ],
  "dependencies": {},
  "devDependencies": {
    "brittle": "^3.5.2",
    "standard": "^17.1.0"
  }
}
module.exports = class RandomArrayIterator {
  constructor (values) {
    this.values = values
    this.start = 0
    this.length = this.values.length
  }

  next () {
    if (this.length === 0) {
      if (this.start === 0) return { done: true, value: undefined }
      this.length = this.start
      this.start = 0
    }

    const i = this.start + ((Math.random() * this.length) | 0)
    const j = this.start + --this.length
    const value = this.values[i]

    this.values[i] = this.values[j]
    this.values[j] = value

    return { done: false, value }
  }

  dequeue () {
    this.values[this.start + this.length] = this.values[this.values.length - 1]
    this.values.pop()
  }

  requeue () {
    const i = this.start + this.length
    const value = this.values[i]
    this.values[i] = this.values[this.start]
    this.values[this.start++] = value
  }

  restart () {
    this.start = 0
    this.length = this.values.length
    return this
  }

  [Symbol.iterator] () {
    return this
  }
}
{
  "name": "random-array-iterator",
  "version": "1.0.0",
  "description": "An iterator to iterate an array in random order with controls to requeue or dequeue elements during the iteration",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^16.0.3",
    "tape": "^5.0.1"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/random-array-iterator.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/random-array-iterator/issues"
  },
  "homepage": "https://github.com/mafintosh/random-array-iterator"
}
const EventEmitter = require('events')

module.exports = class ReadyResource extends EventEmitter {
  constructor () {
    super()

    this.opening = null
    this.closing = null

    this.opened = false
    this.closed = false
  }

  ready () {
    if (this.opening !== null) return this.opening
    this.opening = open(this)
    return this.opening
  }

  close () {
    if (this.closing !== null) return this.closing
    this.closing = close(this)
    return this.closing
  }

  async _open () {
    // add impl here
  }

  async _close () {
    // add impl here
  }
}

async function open (self) {
  // open after close
  if (self.closing !== null) return

  try {
    await self._open()
  } catch (err) {
    self.close() // safe to run in bg
    throw err
  }

  self.opened = true
  self.emit('ready')
}

async function close (self) {
  try {
    if (self.opened === false && self.opening !== null) await self.opening
  } catch {
    // ignore errors on closing
  }
  if (self.opened === true || self.opening === null) await self._close()
  self.closed = true
  self.emit('close')
}
{
  "name": "ready-resource",
  "version": "1.2.0",
  "description": "Modern single resource management",
  "main": "index.js",
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "types": "index.d.ts",
  "files": [
    "index.js",
    "index.d.ts"
  ],
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "devDependencies": {
    "brittle": "^3.1.0",
    "standard": "^17.0.0"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/ready-resource.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/ready-resource/issues"
  },
  "homepage": "https://github.com/holepunchto/ready-resource",
  "dependencies": {
    "bare-events": "^2.2.0"
  }
}
const b4a = require('b4a')

var EMPTY = []

module.exports = RecordCache

function RecordSet () {
  this.list = []
  this.map = new Map()
}

RecordSet.prototype.add = function (record, value) {
  var k = toString(record)
  var r = this.map.get(k)
  if (r) return false

  r = {index: this.list.length, record: value || record}
  this.list.push(r)
  this.map.set(k, r)
  return true
}

RecordSet.prototype.remove = function (record) {
  var k = toString(record)
  var r = this.map.get(k)
  if (!r) return false

  swap(this.list, r.index, this.list.length - 1)
  this.list.pop()
  this.map.delete(k)
  return true
}

function RecordStore () {
  this.records = new Map()
  this.size = 0
}

RecordStore.prototype.add = function (name, record, value) {
  var r = this.records.get(name)

  if (!r) {
    r = new RecordSet()
    this.records.set(name, r)
  }

  if (r.add(record, value)) {
    this.size++
    return true
  }

  return false
}

RecordStore.prototype.remove = function (name, record, value) {
  var r = this.records.get(name)
  if (!r) return false

  if (r.remove(record, value)) {
    this.size--
    if (!r.map.size) this.records.delete(name)
    return true
  }

  return false
}

RecordStore.prototype.get = function (name) {
  var r = this.records.get(name)
  return r ? r.list : EMPTY
}

function RecordCache (opts) {
  if (!(this instanceof RecordCache)) return new RecordCache(opts)
  if (!opts) opts = {}

  this.maxSize = opts.maxSize || Infinity
  this.maxAge = opts.maxAge || 0

  this._onstale = opts.onStale || opts.onstale || null
  this._fresh = new RecordStore()
  this._stale = new RecordStore()
  this._interval = null
  this._gced = false

  if (this.maxAge && this.maxAge < Infinity) {
    // 2/3 gives us a span of 0.66-1.33 maxAge or avg maxAge
    var tick = Math.ceil(2 / 3 * this.maxAge)
    this._interval = setInterval(this._gcAuto.bind(this), tick)
    if (this._interval.unref) this._interval.unref()
  }
}

Object.defineProperty(RecordCache.prototype, 'size', {
  get: function () {
    return this._fresh.size + this._stale.size
  }
})

RecordCache.prototype.add = function (name, record, value) {
  this._stale.remove(name, record, value)
  if (this._fresh.add(name, record, value) && this._fresh.size > this.maxSize) {
    this._gc()
  }
}

RecordCache.prototype.remove = function (name, record, value) {
  this._fresh.remove(name, record, value)
  this._stale.remove(name, record, value)
}

RecordCache.prototype.get = function (name, n) {
  var a = this._fresh.get(name)
  var b = this._stale.get(name)
  var aLen = a.length
  var bLen = b.length
  var len = aLen + bLen

  if (n > len || !n) n = len
  var result = new Array(n)

  for (var i = 0; i < n; i++) {
    var j = Math.floor(Math.random() * (aLen + bLen))
    if (j < aLen) {
      result[i] = a[j].record
      swap(a, j, --aLen)
    } else {
      j -= aLen
      result[i] = b[j].record
      swap(b, j, --bLen)
    }
  }

  return result
}

RecordCache.prototype._gcAuto = function () {
  if (!this._gced) this._gc()
  this._gced = false
}

RecordCache.prototype._gc = function () {
  if (this._onstale && this._stale.size > 0) this._onstale(this._stale)
  this._stale = this._fresh
  this._fresh = new RecordStore()
  this._gced = true
}

RecordCache.prototype.clear = function () {
  this._gc()
  this._gc()
}

RecordCache.prototype.destroy = function () {
  this.clear()
  clearInterval(this._interval)
  this._interval = null
}

function toString (record) {
  return b4a.isBuffer(record) ? b4a.toString(record, 'hex') : record
}

function swap (list, a, b) {
  var tmp = list[a]
  tmp.index = b
  list[b].index = a
  list[a] = list[b]
  list[b] = tmp
}
{
  "name": "record-cache",
  "version": "1.2.0",
  "description": "Cache optimised for record like things",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.3.1"
  },
  "devDependencies": {
    "standard": "^10.0.3",
    "tape": "^4.8.0"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/record-cache.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/record-cache/issues"
  },
  "homepage": "https://github.com/mafintosh/record-cache"
}
module.exports = class RefCounter {
  constructor() {
    this.count = 0

    this._onidle = null
    this._idle = null
  }

  isIdle() {
    return this.count === 0
  }

  idle() {
    if (this.count === 0) return Promise.resolve()
    if (this._idle !== null) return this._idle

    this._idle = new Promise((resolve) => {
      this._onidle = resolve
    })

    return this._idle
  }

  inc() {
    this.count++
  }

  dec() {
    if (--this.count > 0) return

    if (this._onidle !== null) {
      const resolve = this._onidle
      this._idle = null
      this._onidle = null
      resolve()
    }
  }
}
{
  "name": "refcounter",
  "version": "1.0.0",
  "description": "Simple refcounter",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {},
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/refcounter.git"
  },
  "author": "Holepunch Inc",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/refcounter/issues"
  },
  "homepage": "https://github.com/holepunchto/refcounter"
}
module.exports = require.addon.bind(require)
{
  "name": "require-addon",
  "version": "1.2.0",
  "description": "Import native addons across JavaScript runtimes",
  "exports": {
    "./package": "./package.json",
    ".": {
      "bare": "./lib/bare.js",
      "node": "./lib/node.js",
      "default": "./lib/default.js"
    }
  },
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    },
    "url": {
      "bare": "bare-url",
      "default": "url"
    }
  },
  "files": [
    "lib"
  ],
  "scripts": {
    "test": "npm run lint && npm run test:bare && npm run test:node",
    "test:bare": "bare test.js",
    "test:node": "node test.js",
    "lint": "prettier --check .",
    "format": "prettier --write ."
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/require-addon.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/require-addon/issues"
  },
  "homepage": "https://github.com/holepunchto/require-addon#readme",
  "engines": {
    "bare": ">=1.10.0"
  },
  "dependencies": {
    "bare-addon-resolve": "^1.3.0"
  },
  "devDependencies": {
    "bare-bundle": "^1.8.1",
    "bare-bundle-evaluate": "^1.1.0",
    "bare-fs": "^4.0.0",
    "bare-path": "^3.0.0",
    "bare-url": "^2.1.0",
    "brittle": "^3.7.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
let tmpResolve = null
let tmpReject = null

if (Promise.withResolvers) {
  module.exports = Promise.withResolvers.bind(Promise)
} else {
  module.exports = function resolveRejectPromise () {
    const promise = new Promise(setTmp)
    const result = { promise, resolve: tmpResolve, reject: tmpReject }
    tmpResolve = tmpReject = null
    return result
  }
}

function setTmp (resolve, reject) {
  tmpResolve = resolve
  tmpReject = reject
}
{
  "name": "resolve-reject-promise",
  "version": "1.1.0",
  "description": "Create an inverted promise with no function allocs",
  "main": "index.js",
  "scripts": {
    "test": "standard"
  },
  "devDependencies": {
    "standard": "^17.1.2"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/resolve-reject-promise.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/resolve-reject-promise/issues"
  },
  "homepage": "https://github.com/mafintosh/resolve-reject-promise"
}
const resources = new Map()

exports.add = function(resource, teardown) {
  resources.set(resource, teardown)
}

exports.remove = function(resource) {
  resources.delete(resource)
}

if (global.Bare) global.Bare.on('exit', run)
else global.process.on('exit', run)

function run() {
  for (const [resource, teardown] of resources) {
    teardown(resource)
  }
}
{
  "name": "resource-on-exit",
  "version": "1.0.0",
  "description": "Register sync teardown handlers for a resource",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {},
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/bare-teardown.git"
  },
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-teardown/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-teardown"
}
require.addon = require('require-addon')

module.exports = require.addon('.', __filename)
const ColumnFamily = require('./lib/column-family')
const Iterator = require('./lib/iterator')
const Snapshot = require('./lib/snapshot')
const State = require('./lib/state')
const { BloomFilterPolicy, RibbonFilterPolicy } = require('./lib/filter-policy')
const constants = require('./lib/constants')

class RocksDB {
  constructor(path, opts = {}) {
    const {
      columnFamily,
      state = new State(this, path, opts),
      snapshot = null,
      keyEncoding = null,
      valueEncoding = null
    } = opts

    this._state = state
    this._snapshot = snapshot
    this._columnFamily = state.getColumnFamily(columnFamily)
    this._keyEncoding = keyEncoding
    this._valueEncoding = valueEncoding
    this._index = -1

    this._state.addSession(this)
  }

  get opened() {
    return this._state.opened
  }

  get closed() {
    return this.isRoot() ? this._state.closed : this._index === -1
  }

  get path() {
    return this._state.path
  }

  get stats() {
    return this._state.stats
  }

  get snapshotted() {
    return this._snapshot !== null
  }

  get defaultColumnFamily() {
    return this._columnFamily
  }

  session({
    columnFamily = this._columnFamily,
    snapshot = this._snapshot !== null,
    keyEncoding = this._keyEncoding,
    valueEncoding = this._valueEncoding
  } = {}) {
    maybeClosed(this)

    return new RocksDB(null, {
      state: this._state,
      columnFamily,
      snapshot: snapshot ? this._snapshot || new Snapshot(this._state) : null,
      keyEncoding,
      valueEncoding
    })
  }

  columnFamily(name, opts) {
    return this.session({ ...opts, columnFamily: name })
  }

  snapshot() {
    return this.session({ snapshot: true })
  }

  isRoot() {
    return this === this._state.db
  }

  ready() {
    return this._state.ready()
  }

  async close({ force } = {}) {
    if (!this._state.opened) await this._state.ready()

    if (this._index !== -1) this._state.removeSession(this)

    if (force) {
      while (this._state.sessions.length > 0) {
        await this._state.sessions[this._state.sessions.length - 1].close()
      }
    }

    return this.isRoot() ? this._state.close() : Promise.resolve()
  }

  suspend() {
    maybeClosed(this)

    return this._state.suspend()
  }

  resume() {
    maybeClosed(this)

    return this._state.resume()
  }

  isIdle() {
    return this._state.handles.isIdle()
  }

  idle() {
    return this._state.handles.idle()
  }

  iterator(range, opts) {
    maybeClosed(this)

    return new Iterator(this, { ...range, ...opts })
  }

  async *keys(range, opts) {
    for await (const { key } of this.iterator(range, {
      ...opts,
      values: false
    })) {
      yield key
    }
  }

  async peek(range, opts) {
    for await (const value of this.iterator({ ...range, ...opts, limit: 1 })) {
      return value
    }

    return null
  }

  read(opts) {
    maybeClosed(this)

    return this._state.createReadBatch(this, opts)
  }

  write(opts) {
    maybeClosed(this)

    return this._state.createWriteBatch(this, opts)
  }

  flush(opts) {
    maybeClosed(this)

    return this._state.flush(this, opts)
  }

  async get(key, opts) {
    const batch = this.read({ ...opts, capacity: 1, autoDestroy: true })
    const value = batch.get(key)
    batch.tryFlush()
    return value
  }

  async put(key, value, opts) {
    const batch = this.write({ ...opts, capacity: 1, autoDestroy: true })
    batch.tryPut(key, value)
    await batch.flush()
  }

  async delete(key, opts) {
    const batch = this.write({ ...opts, capacity: 1, autoDestroy: true })
    batch.tryDelete(key)
    await batch.flush()
  }

  async deleteRange(start, end, opts) {
    const batch = this.write({ ...opts, capacity: 1, autoDestroy: true })
    batch.tryDeleteRange(start, end)
    await batch.flush()
  }

  async compact(opts = {}) {
    maybeClosed(this)

    await this._state.compact(this, opts)
  }

  async compactRange(start = null, end = null, opts = {}) {
    if (typeof end === 'object' && end !== null) {
      opts = end
      end = null
    } else if (typeof start === 'object' && start !== null) {
      opts = start
      start = null
      end = null
    }

    await this._state.compactRange(this, start, end, opts)
  }

  async approximateSize(start, end, opts = {}) {
    return this._state.approximateSize(this, start, end, opts)
  }

  async currentWalFile() {
    maybeClosed(this)

    return this._state.currentWalFile()
  }

  async getStatsLevel() {
    maybeClosed(this)

    return this._state.getStatsLevel()
  }

  async setStatsLevel(level) {
    maybeClosed(this)

    await this._state.setStatsLevel(level)
  }

  async getProperty(name) {
    maybeClosed(this)

    return this._state.getProperty(name)
  }

  _ref() {
    if (this._snapshot) this._snapshot.ref()
    this._state.handles.inc()
  }

  _unref() {
    if (this._snapshot) this._snapshot.unref()
    this._state.handles.dec()
  }

  diagnostics() {
    return this._state.diagnostics()
  }
}

module.exports = exports = RocksDB

exports.constants = constants

exports.ColumnFamily = ColumnFamily
exports.BloomFilterPolicy = BloomFilterPolicy
exports.RibbonFilterPolicy = RibbonFilterPolicy

function maybeClosed(db) {
  if (db._state.closing || db._index === -1) throw new Error('RocksDB session is closed')
}
const c = require('compact-encoding')
const binding = require('../binding')

const empty = Buffer.alloc(0)
const resolved = Promise.resolve()

class RocksDBBatch {
  constructor(db, opts = {}) {
    const { capacity = 8, autoDestroy = false } = opts

    db._ref()

    this._db = db
    this._destroyed = false
    this._capacity = capacity
    this._operations = []
    this._promises = []

    this._enqueuePromise = this._enqueuePromise.bind(this)

    this._request = null
    this._resolve = null
    this._reject = null

    this._handle = null
    this._buffer = null
    this._autoDestroy = autoDestroy
    this._stats = null

    this._resetStats()

    if (db._state.opened === true) this.ready()
  }

  _reuse(db, opts = {}) {
    const { autoDestroy = false } = opts

    db._ref()

    this._db = db
    this._destroyed = false
    this._autoDestroy = autoDestroy
  }

  _onfinished(err) {
    const resolve = this._resolve
    const reject = this._reject

    if (this._request) this._db._state.io.dec()

    this._operations = []
    this._promises = []
    this._request = null
    this._resolve = null
    this._reject = null

    this._resetStats()

    if (this._autoDestroy === true) this.destroy()

    if (reject !== null && err) reject(err)
    else if (resolve !== null) resolve()
  }

  _resize() {
    if (this._operations.length <= this._capacity) return false

    while (this._operations.length > this._capacity) {
      this._capacity *= 2
    }

    return true
  }

  async ready() {
    if (this._handle !== null) return

    if (this._db._state.opened === false) await this._db._state.ready()

    this._init()
  }

  destroy() {
    if (this._request) throw new Error('Request in progress')
    if (this._destroyed) return

    this._destroyed = true

    if (this._promises.length) this._abort()

    this._db._unref()
    this._onfree()
  }

  _onfree() {
    this._resetStats()
    this._db._state.freeBatch(this, false)
    this._db = null
  }

  _abort() {
    for (let i = 0; i < this._promises.length; i++) {
      const promise = this._promises[i]
      if (promise !== null) promise.reject(new Error('Batch is destroyed'))
    }

    this._onfinished(new Error('Batch is destroyed'))
  }

  _resetStats() {}

  async flush() {
    if (this._request) throw new Error('Request in progress')
    if (this._destroyed) throw new Error('Batch is destroyed')

    this._request = new Promise((resolve, reject) => {
      this._resolve = resolve
      this._reject = reject
    })

    this._flush()

    return this._request
  }

  tryFlush() {
    if (this._request) throw new Error('Request in progress')
    if (this._destroyed) throw new Error('Batch is destroyed')

    this._request = resolved

    this._flush()
  }

  async _flush() {
    if (this._handle === null) await this.ready()

    this._db._state.io.inc()

    if (this._db._state.resumed !== null) {
      const resumed = await this._db._state.resumed.promise

      if (!resumed) {
        if (this._destroyed) {
          this._db._state.io.dec()
        } else {
          this._destroyed = true
          this._abort()
          this._db._unref()
        }
      }
    }
  }

  _enqueuePromise(resolve, reject) {
    this._promises.push({ resolve, reject })
  }

  _encodeKey(k) {
    if (this._db._keyEncoding) return c.encode(this._db._keyEncoding, k)
    if (typeof k === 'string') return Buffer.from(k)
    return k
  }

  _encodeValue(v) {
    if (this._db._valueEncoding) return c.encode(this._db._valueEncoding, v)
    if (v === null) return empty
    if (typeof v === 'string') return Buffer.from(v)
    return v
  }

  _decodeValue(b) {
    if (this._db._valueEncoding) return c.decode(this._db._valueEncoding, b)
    return b
  }
}

exports.ReadBatch = class RocksDBReadBatch extends RocksDBBatch {
  constructor(db, opts = {}) {
    super(db, opts)

    const { asyncIO = false, fillCache = true } = opts

    this._asyncIO = asyncIO
    this._fillCache = fillCache
  }

  _init() {
    this._handle = binding.readInit()
    this._buffer = binding.readBuffer(this._handle, this._capacity)
  }

  _resize() {
    if (super._resize() && this._handle !== null) {
      this._buffer = binding.readBuffer(this._handle, this._capacity)
    }
  }

  async _flush() {
    await super._flush()

    if (this._destroyed) return

    try {
      binding.read(
        this._db._state._handle,
        this._handle,
        this._operations,
        this._db._snapshot ? this._db._snapshot._handle : undefined,
        this._asyncIO,
        this._fillCache,
        this,
        this._onread
      )
    } catch (err) {
      this._db._state.io.dec()
      throw err
    }

    this._db._state.stats.gets += this._stats.gets
    this._db._state.stats.readBatches++
  }

  _onread(errs, values) {
    let applied = true

    for (let i = 0, n = this._promises.length; i < n; i++) {
      const err = errs[i]
      if (err) applied = false

      const promise = this._promises[i]
      if (promise === null) continue

      if (err) promise.reject(err)
      else promise.resolve(values[i] ? this._decodeValue(Buffer.from(values[i])) : null)
    }

    this._onfinished(applied ? null : new AggregateError(errs, 'Batch was not applied'))
  }

  _resetStats() {
    this._stats = { gets: 0 }
  }

  get(key) {
    if (this._request) throw new Error('Request already in progress')
    this._stats.gets++

    const promise = new Promise(this._enqueuePromise)

    this._operations.push(new RocksDBGet(this._encodeKey(key), this._db._columnFamily))

    this._resize()

    return promise
  }
}

exports.WriteBatch = class RocksDBWriteBatch extends RocksDBBatch {
  _init() {
    this._handle = binding.writeInit()
    this._buffer = binding.writeBuffer(this._handle, this._capacity)
  }

  _resize() {
    if (super._resize() && this._handle !== null) {
      this._buffer = binding.writeBuffer(this._handle, this._capacity)
    }
  }

  _onfree() {
    this._resetStats()
    this._db._state.freeBatch(this, true)
    this._db = null
  }

  async _flush() {
    await super._flush()

    if (this._destroyed) return

    try {
      binding.write(this._db._state._handle, this._handle, this._operations, this, this._onwrite)
    } catch (err) {
      this._db._state.io.dec()
      throw err
    }

    this._db._state.stats.puts += this._stats.puts
    this._db._state.stats.deletes += this._stats.deletes
    this._db._state.stats.rangeDeletes += this._stats.rangeDeletes
    this._db._state.stats.writeBatches++
  }

  _onwrite(err) {
    const applied = !err

    for (let i = 0, n = this._promises.length; i < n; i++) {
      const promise = this._promises[i]
      if (promise === null) continue

      if (err) promise.reject(err)
      else promise.resolve()
    }

    this._onfinished(applied ? null : new Error('Batch was not applied', { cause: err }))
  }

  _resetStats() {
    this._stats = { puts: 0, deletes: 0, rangeDeletes: 0 }
  }

  put(key, value) {
    if (this._request) throw new Error('Request already in progress')
    this._stats.puts++

    const promise = new Promise(this._enqueuePromise)

    this._operations.push(
      new RocksDBPut(this._encodeKey(key), this._encodeValue(value), this._db._columnFamily)
    )

    this._resize()

    return promise
  }

  tryPut(key, value) {
    if (this._request) throw new Error('Request already in progress')
    this._stats.puts++

    this._operations.push(
      new RocksDBPut(this._encodeKey(key), this._encodeValue(value), this._db._columnFamily)
    )

    this._promises.push(null)

    this._resize()
  }

  delete(key) {
    if (this._request) throw new Error('Request already in progress')
    this._stats.deletes++

    const promise = new Promise(this._enqueuePromise)

    this._operations.push(new RocksDBDelete(this._encodeKey(key), this._db._columnFamily))

    this._resize()

    return promise
  }

  tryDelete(key) {
    if (this._request) throw new Error('Request already in progress')
    this._stats.deletes++

    this._operations.push(new RocksDBDelete(this._encodeKey(key), this._db._columnFamily))

    this._promises.push(null)

    this._resize()
  }

  deleteRange(start, end) {
    if (this._request) throw new Error('Request already in progress')
    this._stats.rangeDeletes++

    const promise = new Promise(this._enqueuePromise)

    this._operations.push(
      new RocksDBDeleteRange(this._encodeKey(start), this._encodeKey(end), this._db._columnFamily)
    )

    this._resize()

    return promise
  }

  tryDeleteRange(start, end) {
    if (this._request) throw new Error('Request already in progress')
    this._stats.rangeDeletes++

    this._operations.push(
      new RocksDBDeleteRange(this._encodeKey(start), this._encodeKey(end), this._db._columnFamily)
    )

    this._promises.push(null)

    this._resize()
  }
}

class RocksDBGet {
  constructor(key, columnFamily) {
    this.key = key
    this.columnFamily = columnFamily._handle
  }

  get type() {
    return binding.GET
  }
}

class RocksDBPut {
  constructor(key, value, columnFamily) {
    this.key = key
    this.value = value
    this.columnFamily = columnFamily._handle
  }

  get type() {
    return binding.PUT
  }
}

class RocksDBDelete {
  constructor(key, columnFamily) {
    this.key = key
    this.columnFamily = columnFamily._handle
  }

  get type() {
    return binding.DELETE
  }
}

class RocksDBDeleteRange {
  constructor(start, end, columnFamily) {
    this.start = start
    this.end = end
    this.columnFamily = columnFamily._handle
  }

  get type() {
    return binding.DELETE_RANGE
  }
}
const binding = require('../binding')
const constants = require('./constants')
const { BloomFilterPolicy } = require('./filter-policy')

class RocksDBColumnFamily {
  constructor(name, opts = {}) {
    const {
      // Blob options
      enableBlobFiles = false,
      minBlobSize = 0,
      blobFileSize = 0,
      enableBlobGarbageCollection = true,
      // Block table options
      tableBlockSize = 8192,
      tableCacheIndexAndFilterBlocks = true,
      tableFormatVersion = 6,
      optimizeFiltersForMemory = false,
      blockCache = true,
      filterPolicy = new BloomFilterPolicy(10),
      topLevelIndexPinningTier = constants.pinningTier.ALL,
      partitionPinningTier = constants.pinningTier.ALL,
      unpartitionedPinningTier = constants.pinningTier.ALL,
      optimizeFiltersForHits = false,
      numLevels = 7,
      maxWriteBufferNumber = 2,
      blobGarbageCollectionAgeCutOff = 0.25,
      blobGarbageCollectionForceThreshold = 1.0
    } = opts

    this._name = name
    this._flushing = null
    this._options = {
      enableBlobFiles,
      minBlobSize,
      blobFileSize,
      enableBlobGarbageCollection,
      tableBlockSize,
      tableCacheIndexAndFilterBlocks,
      tableFormatVersion,
      optimizeFiltersForMemory,
      blockCache,
      filterPolicy,
      topLevelIndexPinningTier,
      partitionPinningTier,
      unpartitionedPinningTier,
      optimizeFiltersForHits,
      numLevels,
      maxWriteBufferNumber,
      blobGarbageCollectionAgeCutOff,
      blobGarbageCollectionForceThreshold
    }

    const filterPolicyArguments = [0, 0, 0]

    if (filterPolicy !== null) {
      filterPolicyArguments[0] = filterPolicy.type

      switch (filterPolicy.type) {
        case 1: // Bloom filter policy
          filterPolicyArguments[1] = filterPolicy.bitsPerKey
          break
        case 2: // Ribbon filter policy
          filterPolicyArguments[1] = filterPolicy.bloomEquivalentBitsPerKey
          filterPolicyArguments[2] = filterPolicy.bloomBeforeLevel

          break
      }
    }

    this._handle = binding.columnFamilyInit(
      name,
      enableBlobFiles,
      minBlobSize,
      blobFileSize,
      enableBlobGarbageCollection,
      tableBlockSize,
      tableCacheIndexAndFilterBlocks,
      tableFormatVersion,
      optimizeFiltersForMemory,
      blockCache === false,
      ...filterPolicyArguments,
      topLevelIndexPinningTier,
      partitionPinningTier,
      unpartitionedPinningTier,
      optimizeFiltersForHits,
      numLevels,
      maxWriteBufferNumber,
      blobGarbageCollectionAgeCutOff,
      blobGarbageCollectionForceThreshold
    )
  }

  cloneSettings(name) {
    return new RocksDBColumnFamily(name, this._options)
  }

  get name() {
    return this._name
  }

  destroy() {
    if (this._handle === null) return

    binding.columnFamilyDestroy(this._handle)

    this._handle = null
  }
}

module.exports = RocksDBColumnFamily
module.exports = {
  pinningTier: {
    NONE: 0,
    FLUSHED_AND_SIMILAR: 1,
    ALL: 2
  },
  garbageCollectionPolicy: {
    DEFAULT: 0,
    FORCE: 1,
    DISABLE: 2
  },
  bottommostLevelCompaction: {
    NONE: 0,
    SKIP: 1,
    FORCE: 2
  },
  walRecoveryMode: {
    TOLERATE_CORRUPTED_TAIL_RECORDS: 0,
    ABSOLUTE_CONSISTENCY: 1,
    POINT_IN_TIME: 2,
    SKIP_ANY_CORRUPTED_RECORDS: 3
  },
  statsLevel: {
    DISABLE_ALL: 0,
    EXCEPT_HISTOGRAM_OR_TIMERS: 1,
    EXCEPT_TIMERS: 2,
    EXCEPT_DETAILED_TIMERS: 3,
    EXCEPT_TIME_FOR_MUTEX: 4,
    ALL: 5
  },
  walFileType: {
    ARCHIVED: 0,
    ALIVE: 1
  }
}
exports.BloomFilterPolicy = class RocksDBBloomFilterPolicy {
  get type() {
    return 1
  }

  constructor(bitsPerKey) {
    this.bitsPerKey = bitsPerKey
  }
}

exports.RibbonFilterPolicy = class RocksDBRibbonFilterPolicy {
  get type() {
    return 2
  }

  constructor(bloomEquivalentBitsPerKey, bloomBeforeLevel = 0) {
    this.bloomEquivalentBitsPerKey = bloomEquivalentBitsPerKey
    this.bloomBeforeLevel = bloomBeforeLevel
  }
}
const { Readable } = require('streamx')
const c = require('compact-encoding')
const binding = require('../binding')

const empty = Buffer.alloc(0)

module.exports = class RocksDBIterator extends Readable {
  constructor(db, opts = {}) {
    const {
      gt = null,
      gte = null,
      lt = null,
      lte = null,
      reverse = false,
      values = true,
      limit = Infinity,
      capacity = 8
    } = opts

    super()

    db._ref()

    this._db = db

    this._gt = gt ? this._encodeKey(gt) : empty
    this._gte = gte ? this._encodeKey(gte) : empty
    this._lt = lt ? this._encodeKey(lt) : empty
    this._lte = lte ? this._encodeKey(lte) : empty

    this._reverse = reverse
    this._values = values
    this._limit = limit < 0 ? Infinity : limit
    this._capacity = capacity
    this._opened = false

    this._pendingOpen = null
    this._pendingRead = null
    this._pendingDestroy = null

    this._buffer = null
    this._handle = null

    if (this._db._state.opened === true) this.ready()
  }

  _onopen(err) {
    const cb = this._pendingOpen
    this._pendingOpen = null
    this._opened = true
    this._db._state.io.dec()
    cb(err)
  }

  _onread(err, keys, values) {
    const cb = this._pendingRead
    this._pendingRead = null
    this._db._state.io.dec()
    if (err) return cb(err)

    const n = keys.length

    this._limit -= n

    for (let i = 0; i < n; i++) {
      this.push({
        key: this._decodeKey(Buffer.from(keys[i])),
        value: this._values ? this._decodeValue(Buffer.from(values[i])) : null
      })
    }

    if (n < this._capacity) this.push(null)

    cb(null)
  }

  _onclose(err) {
    const cb = this._pendingDestroy
    this._pendingDestroy = null
    this._db._state.io.dec()
    this._db._unref()
    cb(err)
  }

  _resize() {
    if (this._handle !== null) {
      this._buffer = binding.iteratorBuffer(this._handle, this._capacity)
    }
  }

  async ready() {
    if (this._handle !== null) return

    if (this._db._state.opened === false) await this._db._state.ready()

    this._init()
  }

  _init() {
    this._handle = binding.iteratorInit()
    this._buffer = binding.iteratorBuffer(this._handle, this._capacity)
  }

  async _open(cb) {
    await this.ready()

    this._db._state.io.inc()

    if (this._db._state.resumed !== null) {
      const resumed = await this._db._state.resumed.promise

      if (!resumed) {
        this._db._state.io.dec()

        return cb(new Error('RocksDB session is closed'))
      }
    }

    this._pendingOpen = cb

    try {
      binding.iteratorOpen(
        this._db._state._handle,
        this._handle,
        this._db._columnFamily._handle,
        this._gt,
        this._gte,
        this._lt,
        this._lte,
        this._reverse,
        !this._values, // Keys only
        this._db._snapshot ? this._db._snapshot._handle : undefined,
        this,
        this._onopen,
        this._onclose,
        this._onread
      )
    } catch (err) {
      this._db._state.io.dec()

      cb(err)
    }
  }

  async _read(cb) {
    this._db._state.io.inc()

    if (this._db._state.resumed !== null) {
      const resumed = await this._db._state.resumed.promise

      if (!resumed) {
        this._db._state.io.dec()

        return cb(new Error('RocksDB session is closed'))
      }
    }

    this._pendingRead = cb

    try {
      binding.iteratorRead(this._handle, Math.min(this._capacity, this._limit))
    } catch (err) {
      this._db._state.io.dec()

      cb(err)
    }
  }

  async _destroy(cb) {
    await this.ready()

    this._db._state.io.inc()

    if (this._opened === false) {
      this._db._state.io.dec()
      this._db._unref()

      return cb(null)
    }

    this._pendingDestroy = cb

    try {
      binding.iteratorClose(this._handle)
    } catch (err) {
      this._db._state.io.dec()
      this._db._unref()

      cb(err)
    }
  }

  _encodeKey(k) {
    if (this._db._keyEncoding !== null) return c.encode(this._db._keyEncoding, k)
    if (typeof k === 'string') return Buffer.from(k)
    return k
  }

  _decodeKey(b) {
    if (this._db._keyEncoding !== null) return c.decode(this._db._keyEncoding, b)
    return b
  }

  _decodeValue(b) {
    if (this._db._valueEncoding !== null) return c.decode(this._db._valueEncoding, b)
    return b
  }
}
const binding = require('../binding')

module.exports = class RocksDBSnapshot {
  constructor(state) {
    this._state = state

    this._handle = null
    this._refs = 0

    if (state.deferSnapshotInit === false) this._init()
  }

  _init() {
    this._handle = binding.snapshotCreate(this._state._handle)
  }

  ref() {
    this._refs++
  }

  unref() {
    if (--this._refs > 0) return

    if (this._handle === null) return

    binding.snapshotDestroy(this._handle)

    this._handle = null
  }
}
const ReadyResource = require('ready-resource')
const RefCounter = require('refcounter')
const rrp = require('resolve-reject-promise')
const SignalPromise = require('signal-promise')
const c = require('compact-encoding')
const { ReadBatch, WriteBatch } = require('./batch')
const ColumnFamily = require('./column-family')
const binding = require('../binding')
const constants = require('./constants')

const MAX_BATCH_REUSE = 64
const empty = Buffer.alloc(0)

module.exports = class RocksDBState extends ReadyResource {
  constructor(db, path, opts) {
    super()

    const {
      columnFamily = new ColumnFamily('default', opts),
      columnFamilies = [],
      readOnly = false,
      createIfMissing = true,
      createMissingColumnFamilies = true,
      maxBackgroundJobs = 6,
      bytesPerSync = 1048576,
      maxOpenFiles = -1,
      useDirectReads = false,
      avoidUnnecessaryBlockingIO = false,
      skipStatsUpdateOnOpen = false,
      useDirectIOForFlushAndCompaction = false,
      maxFileOpeningThreads = 16,
      lock = null,
      walRecoveryMode = constants.walRecoveryMode.POINT_IN_TIME,
      bestEffortsRecovery = false,
      enableStatistics = false,
      statsLevel = constants.statsLevel.EXCEPT_HISTOGRAM_OR_TIMERS,
      walTtlSeconds = 0,
      walSizeLimitMegabytes = 0,
      avoidFlushDuringShutdown = false,
      walFilterPrefixes = []
    } = opts

    this.path = path
    this.db = db
    this.handles = new RefCounter()
    this.io = new RefCounter()
    this.sessions = []
    this.columnFamilies = [columnFamily]
    this.deferSnapshotInit = true
    this.resumed = null
    this.stats = {
      gets: 0,
      puts: 0,
      deletes: 0,
      rangeDeletes: 0,
      readBatches: 0,
      writeBatches: 0
    }

    this._suspended = false
    this._suspending = false
    this._updating = false
    this._updatingSignal = new SignalPromise()
    this._columnsFlushed = false
    this._lock = lock
    this._readBatches = []
    this._writeBatches = []

    for (const columnFamily of columnFamilies) {
      this.columnFamilies.push(
        typeof columnFamily === 'string' ? new ColumnFamily(columnFamily, opts) : columnFamily
      )
    }

    this._handle = binding.init(
      readOnly,
      createIfMissing,
      createMissingColumnFamilies,
      maxBackgroundJobs,
      bytesPerSync,
      maxOpenFiles,
      useDirectReads,
      avoidUnnecessaryBlockingIO,
      skipStatsUpdateOnOpen,
      useDirectIOForFlushAndCompaction,
      maxFileOpeningThreads,
      walRecoveryMode,
      bestEffortsRecovery,
      enableStatistics,
      statsLevel,
      walTtlSeconds,
      walSizeLimitMegabytes,
      avoidFlushDuringShutdown,
      walFilterPrefixes.map(encodePrefix)
    )
  }

  createReadBatch(db, opts) {
    if (this._readBatches.length === 0) return new ReadBatch(db, opts)
    const batch = this._readBatches.pop()
    batch._reuse(db, opts)
    return batch
  }

  createWriteBatch(db, opts) {
    if (this._writeBatches.length === 0) return new WriteBatch(db, opts)
    const batch = this._writeBatches.pop()
    batch._reuse(db, opts)
    return batch
  }

  freeBatch(batch, writable) {
    if (batch._capacity > 16) return
    const queue = writable ? this._writeBatches : this._readBatches
    if (queue.length >= MAX_BATCH_REUSE) return
    queue.push(batch)
  }

  addSession(db) {
    db._index = this.sessions.push(db) - 1
    if (db._snapshot) db._snapshot.ref()
  }

  removeSession(db) {
    const head = this.sessions.pop()
    if (head !== db) this.sessions[(head._index = db._index)] = head
    db._index = -1
    if (db._snapshot) db._snapshot.unref()
  }

  upsertColumnFamily(c) {
    if (typeof c === 'string') {
      let col = this.getColumnFamilyByName(c)
      if (col) return col
      col = this.columnFamilies[0].cloneSettings(c)
      this.columnFamilies.push(col)
      return col
    }

    if (this.columnFamilies.includes(c)) return c
    this.columnFamilies.push(c)
    return c
  }

  getColumnFamily(c) {
    if (!c) return this.columnFamilies[0]
    if (!this._columnsFlushed) return this.upsertColumnFamily(c)

    if (typeof c !== 'string') return c

    const col = this.getColumnFamilyByName(c)
    if (col === null) throw new Error('Unknown column family')
    return col
  }

  getColumnFamilyByName(name) {
    for (const col of this.columnFamilies) {
      if (col.name === name) return col
    }
    return null
  }

  async _open() {
    await Promise.resolve() // Allow column families to populate if on-demand

    if (this._lock) await this._lock.ready()

    const req = { resolve: null, reject: null, handle: null }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    this._columnsFlushed = true

    const lock = this._lock === null ? -1 : this._lock.transfer()

    req.handle = binding.open(
      this._handle,
      this,
      this.path,
      this.columnFamilies.map((c) => c._handle),
      lock,
      req,
      onopen
    )

    await promise

    this.deferSnapshotInit = false

    for (const session of this.sessions) {
      if (session._snapshot) session._snapshot._init()
    }

    function onopen(err) {
      if (err) req.reject(err)
      else req.resolve()
    }
  }

  async _close() {
    while (this._updating) await this._updatingSignal.wait()
    if (this.resumed) this.resumed.resolve(false)

    while (!this.io.isIdle()) await this.io.idle()
    while (!this.handles.isIdle()) await this.handles.idle()

    while (this.sessions.length > 0) {
      await this.sessions[this.sessions.length - 1].close()
    }

    for (const columnFamily of this.columnFamilies) columnFamily.destroy()

    const req = { resolve: null, reject: null, handle: null }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    req.handle = binding.close(this._handle, req, onclose)

    try {
      await promise
    } finally {
      if (this._lock) await this._lock.close()
    }

    function onclose(err) {
      if (err) req.reject(err)
      else req.resolve()
    }
  }

  async flush(db, opts) {
    if (this.opened === false) await this.ready()

    this.io.inc()

    if (this.resumed !== null) {
      const resumed = await this.resumed.promise

      if (!resumed) {
        this.io.dec()

        throw new Error('RocksDB session is closed')
      }
    }

    const req = { resolve: null, reject: null, handle: null }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    try {
      req.handle = binding.flush(this._handle, db._columnFamily._handle, req, onflush)

      await promise
    } finally {
      this.io.dec()
    }

    function onflush(err) {
      if (err) req.reject(err)
      else req.resolve()
    }
  }

  suspend() {
    this._suspending = true
    return this.update()
  }

  resume() {
    this._suspending = false
    return this.update()
  }

  async update() {
    while (this._updating) await this._updatingSignal.wait()
    if (this._suspending === this._suspended || this.closing) return
    this._updating = true
    try {
      if (this._suspending) await this._suspend()
      else await this._resume()
    } finally {
      this._updating = false
      this._updatingSignal.notify()
    }
  }

  async _suspend() {
    if (this._suspended === true) return

    while (!this.io.isIdle()) await this.io.idle()

    this.io.inc()
    this.resumed = rrp()

    const req = { resolve: null, reject: null, handle: null }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    try {
      req.handle = binding.suspend(this._handle, req, onsuspend)

      await promise

      this._suspended = true
    } finally {
      this.io.dec()
    }

    function onsuspend(err) {
      if (err) req.reject(err)
      else req.resolve()
    }
  }

  async _resume() {
    if (this._suspended === false) return

    const req = { resolve: null, reject: null, handle: null }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    req.handle = binding.resume(this._handle, req, onresume)

    await promise

    this._suspended = false

    const resumed = this.resumed
    this.resumed = null
    resumed.resolve(true)

    function onresume(err) {
      if (err) req.reject(err)
      else req.resolve()
    }
  }

  async compact(db, opts) {
    if (this.opened === false) await this.ready()

    this.io.inc()

    const {
      exclusive = false,
      blobGarbageCollectionPolicy = constants.garbageCollectionPolicy.DEFAULT,
      blobGarbageCollectionAgeCutoff = 0.25,
      bottommostLevelCompaction = constants.bottommostLevelCompaction.NONE
    } = opts

    const req = { resolve: null, reject: null, handle: null }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    try {
      req.handle = binding.compact(
        this._handle,
        db._columnFamily._handle,
        exclusive,
        blobGarbageCollectionPolicy,
        blobGarbageCollectionAgeCutoff,
        bottommostLevelCompaction,
        req,
        oncompact
      )

      await promise
    } finally {
      this.io.dec()
    }

    function oncompact(err) {
      if (err) req.reject(err)
      else req.resolve()
    }
  }

  async compactRange(db, start, end, opts) {
    if (this.opened === false) await this.ready()

    this.io.inc()

    const {
      exclusive = false,
      blobGarbageCollectionPolicy = constants.garbageCollectionPolicy.DEFAULT,
      blobGarbageCollectionAgeCutoff = 0.25,
      bottommostLevelCompaction = constants.bottommostLevelCompaction.NONE
    } = opts

    start = this._encodeKey(start)
    end = this._encodeKey(end)

    const req = { resolve: null, reject: null, handle: null, start, end }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    try {
      req.handle = binding.compactRange(
        this._handle,
        db._columnFamily._handle,
        start,
        end,
        exclusive,
        blobGarbageCollectionPolicy,
        blobGarbageCollectionAgeCutoff,
        bottommostLevelCompaction,
        req,
        oncompactrange
      )

      await promise
    } finally {
      this.io.dec()
    }

    function oncompactrange(err) {
      if (err) req.reject(err)
      else req.resolve()
    }
  }

  async approximateSize(db, start, end, opts) {
    if (this.opened === false) await this.ready()

    this.io.inc()

    const { includeMemtables = false, includeFiles = true, filesSizeErrorMargin = -1 } = opts

    start = this._encodeKey(start)
    end = this._encodeKey(end)

    const req = { resolve: null, reject: null, handle: null, start, end }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    try {
      req.handle = binding.approximateSize(
        this._handle,
        db._columnFamily._handle,
        start,
        end,
        includeMemtables,
        includeFiles,
        filesSizeErrorMargin,
        req,
        onapproximatesize
      )

      return await promise
    } finally {
      this.io.dec()
    }

    function onapproximatesize(err, result) {
      if (err) req.reject(err)
      else req.resolve(result)
    }
  }

  async currentWalFile() {
    if (this.opened === false) await this.ready()

    this.io.inc()

    const req = { resolve: null, reject: null, handle: null }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    try {
      req.handle = binding.currentWalFile(this._handle, req, oncurrentwalfile)

      return await promise
    } finally {
      this.io.dec()
    }

    function oncurrentwalfile(err, path, number, type, startSequence, size) {
      if (err) req.reject(err)
      else req.resolve({ path, number, type, startSequence, size })
    }
  }

  async getStatsLevel() {
    if (this.opened === false) await this.ready()

    return binding.statsLevelGet(this._handle)
  }

  async setStatsLevel(level) {
    if (this.opened === false) await this.ready()

    binding.statsLevelSet(this._handle, level)
  }

  async getProperty(name) {
    if (this.opened === false) await this.ready()

    return binding.propertyGet(this._handle, name)
  }

  _encodeKey(k) {
    if (this.db._keyEncoding) return c.encode(this.db._keyEncoding, k)
    if (typeof k === 'string') return Buffer.from(k)
    if (k === null) return empty
    return k
  }

  diagnostics() {
    return {
      suspended: this._suspended,
      suspending: this._suspending,
      updating: this._updating,
      resumedPending: this.resumed !== null,
      io: this.io.count,
      handles: this.handles.count,
      sessions: this.sessions.length
    }
  }
}

function encodePrefix(prefix) {
  if (typeof prefix === 'string') return Buffer.from(prefix)
  return prefix
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "rocksdb-native",
  "version": "3.17.2",
  "description": "librocksdb bindings for JavaScript",
  "exports": {
    ".": "./index.js",
    "./package": "./package.json"
  },
  "imports": {
    "crypto": {
      "bare": "bare-crypto",
      "default": "crypto"
    },
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    }
  },
  "files": [
    "index.js",
    "binding.cc",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds",
    "!prebuilds/android-*/**/*.node"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:bare && npm run test:node",
    "test:bare": "brittle-bare --coverage test.js",
    "test:node": "brittle-node --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/rocksdb-native.git"
  },
  "author": "Holepunch Inc",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/rocksdb-native/issues"
  },
  "homepage": "https://github.com/holepunchto/rocksdb-native",
  "engines": {
    "bare": ">=1.16.0"
  },
  "dependencies": {
    "compact-encoding": "^3.0.0",
    "ready-resource": "^1.0.0",
    "refcounter": "^1.0.0",
    "require-addon": "^1.0.2",
    "resolve-reject-promise": "^1.1.0",
    "signal-promise": "^1.0.3",
    "streamx": "^2.16.1"
  },
  "devDependencies": {
    "bare-compat-napi": "^1.3.0",
    "bare-crypto": "^1.12.0",
    "bare-fs": "^4.5.0",
    "bare-path": "^3.0.0",
    "brittle": "^3.5.0",
    "cmake-bare": "^1.1.14",
    "cmake-fetch": "^1.0.1",
    "cmake-napi": "^1.0.6",
    "fd-lock": "^2.0.0",
    "lunte": "^1.8.0",
    "paparam": "^1.9.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = safetyCatch

function isActuallyUncaught (err) {
  if (!err) return false
  return err instanceof TypeError ||
    err instanceof SyntaxError ||
    err instanceof ReferenceError ||
    err instanceof EvalError ||
    err instanceof RangeError ||
    err instanceof URIError ||
    err.code === 'ERR_ASSERTION' ||
    err.name === 'AssertionError'
}

function throwErrorNT (err) {
  queueMicrotask(() => { throw err })
}

function safetyCatch (err) {
  if (isActuallyUncaught(err)) {
    throwErrorNT(err)
    throw err
  }
}
{
  "name": "safety-catch",
  "version": "1.0.3",
  "description": "Small module that makes sure your catch, caught an actual error and not a programming mistake or assertion",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {},
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/safety-catch.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/safety-catch/issues"
  },
  "homepage": "https://github.com/mafintosh/safety-catch"
}
let tmpResolve = null

module.exports = class ScopeLock {
  constructor ({ debounce = false } = {}) {
    this.debounce = debounce
    this.waiting = []
    this.locked = false
    this.skip = 0
    this.destroyed = false
  }

  flush () {
    if (this.locked === false && this.waiting.length === 0) return Promise.resolve(this.destroyed === false)

    const promise = new Promise(setTmpResolve)
    const resolve = tmpResolve

    tmpResolve = null
    this.waiting.push({ lock: false, resolve })

    return promise
  }

  destroy () {
    this.destroyed = true
  }

  lock () {
    const promise = new Promise(setTmpResolve)
    const resolve = tmpResolve

    tmpResolve = null

    if (this.locked === true) {
      this.waiting.push({ lock: true, resolve })
      return promise
    }

    if (this.destroyed === true) {
      resolve(false)
      return promise
    }

    this.locked = true
    resolve(true)

    return promise
  }

  unlock () {
    if (this.destroyed === true) {
      for (let i = 0; i < this.waiting.length; i++) {
        this.waiting[i].resolve(false)
      }
      this.waiting = []
      this.skip = 0
      this.locked = false
      return
    }

    if (this.skip !== 0) {
      for (let i = 0; i < this.skip; i++) {
        const { lock, resolve } = this.waiting[i]
        resolve(lock === false)
      }

      this.waiting = this.waiting.slice(this.skip)
      this.skip = 0
    }

    while (this.waiting.length > 0 && this.waiting[0].lock === false) {
      this.waiting.shift().resolve(true)
    }

    if (this.waiting.length === 0) {
      this.locked = false
      return
    }

    const { resolve } = this.waiting.shift()
    if (this.debounce === true) this.skip = this.waiting.length

    resolve(true)
  }
}

function setTmpResolve (resolve) {
  tmpResolve = resolve
}
{
  "name": "scope-lock",
  "version": "1.2.4",
  "description": "Some concurrency semantics around entering scopes",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "devDependencies": {
    "brittle": "^3.7.0",
    "standard": "^17.1.2"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/scope-lock.git"
  },
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/scope-lock/issues"
  },
  "homepage": "https://github.com/holepunchto/scope-lock"
}
const set = require('unordered-set')

module.exports = opts => new ShuffledPriorityQueue(opts)

class ShuffledPriorityQueue {
  constructor (opts) {
    this.priorities = []
    this.equals = (opts && opts.equals) || null
  }

  get length () {
    return this.priorities.reduce(add, 0)
  }

  [Symbol.iterator] () {
    return new Iterator(this)
  }

  head () {
    for (let i = this.priorities.length - 1; i >= 0; i--) {
      const q = this.priorities[i]
      if (q.length) return shuffle(q, 0)
    }
    return null
  }

  tail () {
    for (let i = 0; i < this.priorities.length; i++) {
      const q = this.priorities[i]
      if (q.length) return shuffle(q, 0)
    }
    return null
  }

  prev (prev) {
    if (!prev) return this.tail()
    return next(this.priorities, prev, 1)
  }

  next (prev) {
    if (!prev) return this.head()
    return next(this.priorities, prev, -1)
  }

  shift () {
    return this.remove(this.head())
  }

  pop () {
    return this.remove(this.tail())
  }

  add (val) {
    const prio = val.priority || 0
    while (prio >= this.priorities.length) this.priorities.push([])
    set.add(this.priorities[prio], val)
    return val
  }

  remove (val) {
    if (!val) return null

    if (val._index === undefined) {
      val = this.find(val)
      if (!val) return null
    }

    return set.remove(this.priorities[val.priority || 0], val)
  }

  has (val) {
    if (val._index === undefined) return this.find(val)
    const priority = val.priority || 0
    if (priority >= this.priorities.length) return false
    return set.has(this.priorities[priority], val)
  }

  find (val) {
    if (val._index !== undefined) return val

    const prio = val.priority || 0
    const qs = this.priorities
    if (prio >= qs.length) return null

    const q = qs[prio]

    for (let i = 0; i < q.length; i++) {
      if (this.equals(q[i], val)) return q[i]
    }

    return null
  }
}

class Iterator {
  constructor (queue) {
    this.prev = null
    this.queue = queue
  }

  next () {
    const next = this.queue.next(this.prev)
    this.prev = next
    return { done: !next, value: next }
  }
}

function shuffle (q, i) {
  const ran = i + Math.floor(Math.random() * (q.length - i))
  set.swap(q, q[ran], q[i])
  return q[i]
}

function next (queues, prev, inc) {
  let i = prev.priority || 0
  let j = (prev._index || 0) + 1

  while (true) {
    if (i < 0 || i >= queues.length) return null
    const q = queues[i]

    if (j >= q.length) {
      i += inc
      j = 0
      continue
    }

    return shuffle(q, j)
  }
}

function add (len, b) {
  return len + b.length
}
{
  "name": "shuffled-priority-queue",
  "version": "2.1.0",
  "description": "A priority queue that shuffles elements with the same priority.",
  "main": "index.js",
  "scripts": {
    "test": "standard && tape test.js"
  },
  "dependencies": {
    "unordered-set": "^2.0.1"
  },
  "devDependencies": {
    "standard": "^12.0.1",
    "tape": "^4.9.1"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/shuffled-priority-queue.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/shuffled-priority-queue/issues"
  },
  "homepage": "https://github.com/mafintosh/shuffled-priority-queue"
}
module.exports = class Signal {
  constructor () {
    this._resolve = null
    this._reject = null
    this._promise = null
    this._bind = bind.bind(this)
    this._onerror = clear.bind(this)
    this._onsuccess = clear.bind(this, null)
    this._timers = new Set()
  }

  wait (max) {
    if (!this._promise) {
      this._promise = new Promise(this._bind)
      this._promise.then(this._onsuccess).catch(this._onerror)
    }
    if (max) return this._sleep(max)
    return this._promise
  }

  _sleep (max) {
    const s = new Promise((resolve, reject) => {
      const done = () => {
        this._timers.delete(state)
        resolve(true)
      }
      const id = setTimeout(done, max)
      const state = { id, resolve, reject }
      this._timers.add(state)
    })

    return s
  }

  notify (err) {
    if (!this._promise) return
    const resolve = this._resolve
    const reject = this._reject
    this._promise = null
    if (err) reject(err)
    else resolve(true)
  }
}

function clear (err) {
  for (const { id, resolve, reject } of this._timers) {
    clearTimeout(id)
    if (err) reject(err)
    else resolve(true)
  }
  this._timers.clear()
}

function bind (resolve, reject) {
  this._resolve = resolve
  this._reject = reject
}
{
  "name": "signal-promise",
  "version": "1.0.3",
  "description": "Simple wait/notify promise with optional max wait time",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {},
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/signal-promise.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/signal-promise/issues"
  },
  "homepage": "https://github.com/mafintosh/signal-promise"
}
var varint = require('varint')
exports.encode = function encode (v, b, o) {
  v = v >= 0 ? v*2 : v*-2 - 1
  var r = varint.encode(v, b, o)
  encode.bytes = varint.encode.bytes
  return r
}
exports.decode = function decode (b, o) {
  var v = varint.decode(b, o)
  decode.bytes = varint.decode.bytes
  return v & 1 ? (v+1) / -2 : v / 2
}

exports.encodingLength = function (v) {
  return varint.encodingLength(v >= 0 ? v*2 : v*-2 - 1)
}
{
  "name": "signed-varint",
  "description": "efficiently store signed integers in varint",
  "version": "2.0.1",
  "homepage": "https://github.com/dominictarr/signed-varint",
  "repository": {
    "type": "git",
    "url": "git://github.com/dominictarr/signed-varint.git"
  },
  "dependencies": {
    "varint": "~5.0.0"
  },
  "devDependencies": {
    "tape": "~2.12.3"
  },
  "scripts": {
    "test": "node test.js"
  },
  "author": "Dominic Tarr <dominic.tarr@gmail.com> (http://dominictarr.com)",
  "license": "MIT"
}
require.addon = require('require-addon')

module.exports = require.addon('.', __filename)
const binding = require('./binding')
const b4a = require('b4a')

function predicate(u8, u16, u32) {
  return function predicate(buf) {
    if (buf.byteLength % 16 !== 0) {
      throw new Error('Buffer length must be a multiple of 16')
    }

    const n = buf.BYTES_PER_ELEMENT

    if (n === 1) return u8(buf)
    if (n === 2) return u16(buf)
    return u32(buf)
  }
}

function unary(u8, u16, u32) {
  return function unary(buf, result = b4a.allocUnsafe(buf.byteLength)) {
    if (buf.byteLength % 16 !== 0) {
      throw new Error('Buffer length must be a multiple of 16')
    }

    if (buf.byteLength !== result.byteLength) {
      throw new Error('Length of result buffer is insufficient')
    }

    const n = buf.BYTES_PER_ELEMENT

    if (n === 1) u8(buf, result)
    else if (n === 2) u16(buf, result)
    else u32(buf, result)

    return result
  }
}

function binary(u8, u16, u32) {
  return function binary(a, b, result = b4a.allocUnsafe(a.byteLength)) {
    if (a.byteLength % 16 !== 0) {
      throw new Error('Buffer length must be a multiple of 16')
    }

    if (a.byteLength !== b.byteLength || a.byteLength !== result.byteLength) {
      throw new Error('Buffers must be the same length')
    }

    const n = a.BYTES_PER_ELEMENT

    if (n === 1) u8(a, b, result)
    else if (n === 2) u16(a, b, result)
    else u32(a, b, result)

    return result
  }
}

function reduce(u8, u16, u32) {
  return function reduce(buf) {
    if (buf.byteLength % 16 !== 0) {
      throw new Error('Buffer length must be a multiple of 16')
    }

    const n = buf.BYTES_PER_ELEMENT

    if (n === 1) return u8(buf)
    if (n === 2) return u16(buf)
    return u32(buf)
  }
}

exports.allo = predicate(
  binding.simdle_native_allo_v128_u8,
  binding.simdle_native_allo_v128_u16,
  binding.simdle_native_allo_v128_u32
)

exports.allz = predicate(
  binding.simdle_native_allz_v128_u8,
  binding.simdle_native_allz_v128_u16,
  binding.simdle_native_allz_v128_u32
)

exports.and = binary(
  binding.simdle_native_and_v128_u8,
  binding.simdle_native_and_v128_u16,
  binding.simdle_native_and_v128_u32
)

exports.clear = binary(
  binding.simdle_native_clear_v128_u8,
  binding.simdle_native_clear_v128_u16,
  binding.simdle_native_clear_v128_u32
)

exports.clo = unary(
  binding.simdle_native_clo_v128_u8,
  binding.simdle_native_clo_v128_u16,
  binding.simdle_native_clo_v128_u32
)

exports.clz = unary(
  binding.simdle_native_clz_v128_u8,
  binding.simdle_native_clz_v128_u16,
  binding.simdle_native_clz_v128_u32
)

exports.cnt = unary(
  binding.simdle_native_cnt_v128_u8,
  binding.simdle_native_cnt_v128_u16,
  binding.simdle_native_cnt_v128_u32
)

exports.cto = unary(
  binding.simdle_native_cto_v128_u8,
  binding.simdle_native_cto_v128_u16,
  binding.simdle_native_cto_v128_u32
)

exports.ctz = unary(
  binding.simdle_native_ctz_v128_u8,
  binding.simdle_native_ctz_v128_u16,
  binding.simdle_native_ctz_v128_u32
)

exports.not = unary(
  binding.simdle_native_not_v128_u8,
  binding.simdle_native_not_v128_u16,
  binding.simdle_native_not_v128_u32
)

exports.or = binary(
  binding.simdle_native_or_v128_u8,
  binding.simdle_native_or_v128_u16,
  binding.simdle_native_or_v128_u32
)

exports.sum = reduce(
  binding.simdle_native_sum_v128_u8,
  binding.simdle_native_sum_v128_u16,
  binding.simdle_native_sum_v128_u32
)

exports.xor = binary(
  binding.simdle_native_xor_v128_u8,
  binding.simdle_native_xor_v128_u16,
  binding.simdle_native_xor_v128_u32
)
{
  "name": "simdle-native",
  "version": "1.3.9",
  "description": "libsimdle JavaScript bindings for Node.js",
  "main": "index.js",
  "files": [
    "index.js",
    "binding.cc",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check .",
    "test": "npm run lint && npm run test:bare && npm run test:node",
    "test:bare": "bare test.mjs",
    "test:node": "node test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/simdle-native.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/simdle-native/issues"
  },
  "homepage": "https://github.com/holepunchto/simdle-native#readme",
  "dependencies": {
    "b4a": "^1.6.0",
    "require-addon": "^1.1.0"
  },
  "devDependencies": {
    "bare-compat-napi": "^1.3.2",
    "brittle": "^3.1.0",
    "cmake-bare": "^1.1.7",
    "cmake-fetch": "^1.1.0",
    "cmake-napi": "^1.0.2",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  }
}
const b4a = require('b4a')
const scalar = require('./scalar')

function view (buf, n) {
  if (n === buf.BYTES_PER_ELEMENT) return buf

  let TypedArray

  if (n === 1) TypedArray = Uint8Array
  else if (n === 2) TypedArray = Uint16Array
  else TypedArray = Uint32Array

  return new TypedArray(buf.buffer, buf.byteOffset, buf.byteLength / n)
}

function unary (u8, u16 = u8, u32 = u16) {
  return function unary (buf, result = b4a.allocUnsafe(buf.byteLength)) {
    if (buf.byteLength % 16 !== 0) {
      throw new Error('Buffer length must be a multiple of 16')
    }

    if (buf.byteLength !== result.byteLength) {
      throw new Error('Length of result buffer is insufficient')
    }

    const n = buf.BYTES_PER_ELEMENT

    if (n === 1) u8(buf, view(result, n))
    else if (n === 2) u16(buf, view(result, n))
    else u32(buf, view(result, n))

    return result
  }
}

function binary (u8, u16 = u8, u32 = u16) {
  return function binary (a, b, result = b4a.allocUnsafe(a.byteLength)) {
    if (a.byteLength % 16 !== 0) {
      throw new Error('Buffer length must be a multiple of 16')
    }

    if (a.byteLength !== b.byteLength || a.byteLength !== result.byteLength) {
      throw new Error('Buffers must be the same length')
    }

    const n = a.BYTES_PER_ELEMENT

    if (n === 1) u8(a, b, view(result, n))
    else if (n === 2) u16(a, b, view(result, n))
    else u32(a, b, view(result, n))

    return result
  }
}

function reduce (u8, u16 = u8, u32 = u16) {
  return function reduce (buf) {
    if (buf.byteLength % 16 !== 0) {
      throw new Error('Buffer length must be a multiple of 16')
    }

    const n = buf.BYTES_PER_ELEMENT

    if (n === 1) return u8(buf)
    if (n === 2) return u16(buf)
    return u32(buf)
  }
}

exports.allo = function allo (buf) {
  if (buf.byteLength % 16 !== 0) {
    throw new Error('Buffer length must be a multiple of 16')
  }

  const m = 2 ** (buf.BYTES_PER_ELEMENT * 8) - 1

  for (let i = 0, n = buf.length; i < n; i++) {
    if (buf[i] !== m) return false
  }

  return true
}

exports.allz = function allz (buf) {
  if (buf.byteLength % 16 !== 0) {
    throw new Error('Buffer length must be a multiple of 16')
  }

  for (let i = 0, n = buf.length; i < n; i++) {
    if (buf[i] !== 0) return false
  }

  return true
}

exports.and = binary(
  (a, b, result) => {
    for (let i = 0, n = result.length; i < n; i++) {
      result[i] = a[i] & b[i]
    }
  }
)

exports.clear = binary(
  (a, b, result) => {
    for (let i = 0, n = result.length; i < n; i++) {
      result[i] = a[i] & ~b[i]
    }
  }
)

exports.clo = unary(
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = 24 - scalar.clo(buf[i])
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = 16 - scalar.clo(buf[i])
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = scalar.clo(buf[i])
    }
  }
)

exports.clz = unary(
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = 24 - scalar.clz(buf[i])
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = 16 - scalar.clz(buf[i])
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = scalar.clz(buf[i])
    }
  }
)

exports.cnt = unary(
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = scalar.cnt(buf[i]) & 0xff
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = scalar.cnt(buf[i]) & 0xffff
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = scalar.cnt(buf[i])
    }
  }
)

exports.cto = unary(
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = Math.min(scalar.cto(buf[i]), 8)
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = Math.min(scalar.cto(buf[i]), 16)
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = scalar.cto(buf[i])
    }
  }
)

exports.ctz = unary(
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = Math.min(scalar.ctz(buf[i]), 8)
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = Math.min(scalar.ctz(buf[i]), 16)
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = scalar.ctz(buf[i])
    }
  }
)

exports.not = unary(
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = ~buf[i]
    }
  }
)

exports.or = binary(
  (a, b, result) => {
    for (let i = 0, n = result.length; i < n; i++) {
      result[i] = a[i] | b[i]
    }
  }
)

exports.sum = reduce(
  (buf) => {
    let result = 0n

    for (let i = 0, n = buf.length; i < n; i++) {
      result += BigInt(buf[i])
    }

    return result
  }
)

exports.xor = binary(
  (a, b, result) => {
    for (let i = 0, n = result.length; i < n; i++) {
      result[i] = a[i] ^ b[i]
    }
  }
)
try {
  module.exports = require('simdle-native')
} catch {
  module.exports = require('./fallback')
}
{
  "name": "simdle-universal",
  "version": "1.1.2",
  "description": "Universal wrapper for libsimdle with a JavaScript fallback",
  "main": "index.js",
  "files": [
    "fallback.js",
    "index.js",
    "scalar.js"
  ],
  "browser": {
    "./index.js": "./fallback.js"
  },
  "scripts": {
    "test": "standard && brittle test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/simdle-universal.git"
  },
  "author": "Kasper Isager Dalsgarð <kasper@funktionel.co>",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/holepunchto/simdle-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/simdle-universal#readme",
  "dependencies": {
    "b4a": "^1.6.0"
  },
  "optionalDependencies": {
    "simdle-native": "^1.1.1"
  },
  "devDependencies": {
    "brittle": "^3.1.0",
    "standard": "^17.0.0"
  }
}
const clz = exports.clz = function clz (n) {
  return Math.clz32(n)
}

exports.clo = function clo (n) {
  return clz(~n)
}

const ctz = exports.ctz = function ctz (n) {
  return 32 - (n === 0 ? 0 : (clz(n & -n) + 1))
}

exports.cto = function cto (n) {
  return ctz(~n)
}

exports.cnt = function cnt (n) {
  n = n - ((n >>> 1) & 0x55555555)
  n = (n & 0x33333333) + ((n >>> 2) & 0x33333333)
  n = (n + (n >>> 4)) & 0x0f0f0f0f
  n = (n * 0x01010101) >>> 24
  return n
}
const sodium = require('sodium-universal')

module.exports = {
  init: sodium.crypto_hash_sha256_init,
  update: sodium.crypto_hash_sha256_update,
  final: sodium.crypto_hash_sha256_final,
  BYTES: sodium.crypto_hash_sha256_BYTES,
  STATEBYTES: sodium.crypto_hash_sha256_STATEBYTES
}
const sodium = require('sodium-universal')

module.exports = {
  init: sodium.crypto_hash_sha512_init,
  update: sodium.crypto_hash_sha512_update,
  final: sodium.crypto_hash_sha512_final,
  BYTES: sodium.crypto_hash_sha512_BYTES,
  STATEBYTES: sodium.crypto_hash_sha512_STATEBYTES
}
const b4a = require('b4a')

const sha256 = require('./hash/sha256')
const sha512 = require('./hash/sha512')

class HMAC {
  constructor (hash, key) {
    this.hash = hash
    this.length = hash.BYTES

    this._blocksize = 2 * hash.BYTES

    this._initialised = false

    this.state = b4a.alloc(hash.STATEBYTES)
    this.pad = b4a.alloc(this._blocksize)

    if (key) this.init(key)
  }

  init (key) {
    if (this._initialised) {
      throw new Error('Already initialised, call final first')
    }

    if (key.length > this._blocksize) {
      this.hash.init(this.state)
      this.hash.update(this.state, key)
      this.hash.final(this.state, this.pad.subarray(0, this.length))
    } else {
      this.pad.set(key)
    }

    bufferByteXor(this.pad, 0x36)

    this.hash.init(this.state)
    this.hash.update(this.state, this.pad)

    bufferByteXor(this.pad, 0x5c ^ 0x36)

    this._initialised = true

    return this
  }

  update (data) {
    if (!this._initialised) {
      throw new Error('First initialise with a key')
    }

    this.hash.update(this.state, data)
    return this
  }

  final (output = b4a.alloc(this.length)) {
    if (!this._initialised) {
      throw new Error('First initialise with a key')
    }

    const out = output.byteLength === this.length
      ? output
      : output.subarray(0, this.hash.BYTES)

    this.hash.final(this.state, out)

    this.hash.init(this.state)
    this.hash.update(this.state, this.pad)
    this.hash.update(this.state, out)
    this.hash.final(this.state, out)

    this.pad.fill(0)
    this.state.fill(0)

    this._initialised = false

    return out
  }

  static sha256 (data, key, output) {
    const hmac = new HMAC(sha256, key)
    return hmac.update(data).final(output)
  }

  static sha512 (data, key, output) {
    const hmac = new HMAC(sha512, key)
    return hmac.update(data).final(output)
  }
}

module.exports = {
  HMAC,
  sha256,
  sha512
}

function bufferByteXor (output, byte) {
  for (let i = 0; i < output.byteLength; i++) {
    output[i] ^= byte
  }

  return output
}
{
  "name": "sodium-hmac",
  "version": "2.1.0",
  "description": "HMAC utility",
  "main": "index.js",
  "scripts": {
    "test": "standard && brittle test/*.js"
  },
  "author": "",
  "license": "Apache-2.0",
  "dependencies": {
    "b4a": "^1.6.6",
    "sodium-universal": "^5.0.1"
  },
  "devDependencies": {
    "brittle": "^3.4.0",
    "standard": "^17.1.0"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sodium-hmac.git"
  },
  "files": [
    "index.js",
    "hash/*"
  ],
  "bugs": {
    "url": "https://github.com/holepunchto/sodium-hmac/issues"
  },
  "homepage": "https://github.com/holepunchto/sodium-hmac#readme"
}
require.addon = require('require-addon')
module.exports = require.addon('.', __filename)
const assert = require('assert')
const binding = require('./binding')
const { isNode } = require('which-runtime')

const OPTIONAL = Buffer.from(new ArrayBuffer(0))

module.exports = exports = { ...binding }

// memory

exports.sodium_memzero = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  binding.sodium_memzero(buf)
}

exports.sodium_mlock = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  const res = binding.sodium_mlock(buf)

  if (res !== 0) throw new Error('memory lock failed')
}

exports.sodium_munlock = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  const res = binding.sodium_munlock(buf)

  if (res !== 0) throw new Error('memory unlock failed')
}

exports.sodium_malloc = function (size) {
  assert(size >= 0, 'invalid size')

  const buf = Buffer.from(binding.sodium_malloc(size))
  buf.secure = true
  return buf
}

exports.sodium_free = function (buf) {
  if (!buf || !buf.secure) return

  binding.sodium_free(buf.buffer)
}

exports.sodium_mprotect_noaccess = function (buf) {
  const res = binding.sodium_mprotect_noaccess(buf.buffer)

  if (res !== 0) throw new Error('failed to lock buffer')
}

exports.sodium_mprotect_readonly = function (buf) {
  const res = binding.sodium_mprotect_readonly(buf.buffer)

  if (res !== 0) throw new Error('failed to unlock buffer')
}

exports.sodium_mprotect_readwrite = function (buf) {
  const res = binding.sodium_mprotect_readwrite(buf.buffer)

  if (res !== 0) throw new Error('failed to unlock buffer')
}

// crypto_randombytes

exports.randombytes_buf = function (buffer) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')

  binding.randombytes_buf(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

exports.randombytes_buf_deterministic = function (buffer, seed) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    seed.byteLength === binding.randombytes_SEEDBYTES,
    "seed must be 'randombytes_SEEDBYTES' bytes"
  )

  binding.randombytes_buf_deterministic(
    buffer.buffer,
    buffer.byteOffset,
    buffer.byteLength,

    seed.buffer,
    seed.byteOffset,
    seed.byteLength
  )
}

// sodium_helpers

exports.sodium_memcmp = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  return binding.sodium_memcmp(a, b)
}

exports.sodium_add = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  binding.sodium_add(a, b)
}

exports.sodium_sub = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  binding.sodium_sub(a, b)
}

exports.sodium_compare = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  return binding.sodium_compare(a, b)
}

exports.sodium_is_zero = function (buffer, length) {
  if (length === undefined) length = buffer.byteLength

  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(length >= 0 && length <= buffer.byteLength, 'invalid length')

  return binding.sodium_is_zero(buffer, length)
}

exports.sodium_pad = function (buffer, unpaddedBuflen, blockSize) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(unpaddedBuflen <= buffer.byteLength, 'unpadded length cannot exceed buffer length')
  assert(blockSize <= buffer.byteLength, 'block size cannot exceed buffer length')
  assert(blockSize >= 1, 'block size must be at least 1 byte')
  assert(
    buffer.byteLength >= unpaddedBuflen + (blockSize - (unpaddedBuflen % blockSize)),
    'buf not long enough'
  )

  return binding.sodium_pad(buffer, unpaddedBuflen, blockSize)
}

exports.sodium_unpad = function (buffer, paddedBuflen, blockSize) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(paddedBuflen <= buffer.byteLength, 'unpadded length cannot exceed buffer length')
  assert(blockSize <= buffer.byteLength, 'block size cannot exceed buffer length')
  assert(blockSize >= 1, 'block size must be at least 1 byte')

  return binding.sodium_unpad(buffer, paddedBuflen, blockSize)
}

// crypto_sign

exports.crypto_sign_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )
  assert(
    seed.byteLength === binding.crypto_sign_SEEDBYTES,
    "seed must be 'crypto_sign_SEEDBYTES' bytes"
  )

  const res = binding.crypto_sign_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign = function (sm, m, sk) {
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sm.byteLength === binding.crypto_sign_BYTES + m.byteLength,
    "sm must be 'm.byteLength + crypto_sign_BYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign(sm, m, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_open = function (m, sm, pk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sm.byteLength >= binding.crypto_sign_BYTES,
    "sm must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    m.byteLength === sm.byteLength - binding.crypto_sign_BYTES,
    "m must be 'sm.byteLength - crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_open(m, sm, pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_open = function (m, sm, pk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sm.byteLength >= binding.crypto_sign_BYTES,
    "sm must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    m.byteLength === sm.byteLength - binding.crypto_sign_BYTES,
    "m must be 'sm.byteLength - crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  return binding.crypto_sign_open(m, sm, pk)
}

exports.crypto_sign_detached = function (sig, m, sk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(sig.byteLength === binding.crypto_sign_BYTES, "sig must be 'crypto_sign_BYTES' bytes")
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_detached(sig, m, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_verify_detached = function (sig, m, pk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sig.byteLength >= binding.crypto_sign_BYTES,
    "sig must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  return binding.crypto_sign_verify_detached(
    sig.buffer,
    sig.byteOffset,
    sig.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    pk.buffer,
    pk.byteOffset,
    pk.byteLength
  )
}

exports.crypto_sign_ed25519_sk_to_pk = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_sk_to_pk(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_ed25519_pk_to_curve25519 = function (x25519pk, ed25519pk) {
  assert(ArrayBuffer.isView(x25519pk), 'x25519pk must be a typed array')
  assert(ArrayBuffer.isView(ed25519pk), 'ed25519pk must be a typed array')
  assert(
    x25519pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "x25519pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    ed25519pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "ed25519pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_pk_to_curve25519(x25519pk, ed25519pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_ed25519_sk_to_curve25519 = function (x25519sk, ed25519sk) {
  assert(ArrayBuffer.isView(x25519sk), 'x25519sk must be a typed array')
  assert(ArrayBuffer.isView(ed25519sk), 'ed25519sk must be a typed array')
  assert(
    x25519sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "x25519sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const edLen = ed25519sk.byteLength

  assert(
    edLen === binding.crypto_sign_SECRETKEYBYTES || edLen === binding.crypto_box_SECRETKEYBYTES,
    "ed25519sk must be 'crypto_sign_SECRETKEYBYTES' or 'crypto_sign_SECRETKEYBYTES - crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_sk_to_curve25519(x25519sk, ed25519sk)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_box

exports.crypto_box_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    seed.byteLength === binding.crypto_box_SEEDBYTES,
    "seed must be 'crypto_box_SEEDBYTES' bytes"
  )

  const res = binding.crypto_box_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_easy = function (c, m, n, pk, sk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength === m.byteLength + exports.crypto_box_MACBYTES,
    "c must be 'm.byteLength + crypto_box_MACBYTES' bytes"
  )
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_easy(c, m, n, pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_detached = function (c, mac, m, n, pk, sk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(mac.byteLength === exports.crypto_box_MACBYTES, "mac must be 'crypto_box_MACBYTES' bytes")
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_detached(c, mac, m, n, pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_open_easy = function (m, c, n, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength >= exports.crypto_box_MACBYTES,
    "c must be at least 'crypto_box_MACBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - exports.crypto_box_MACBYTES,
    "m must be 'c.byteLength - crypto_box_MACBYTES' bytes"
  )
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_open_easy(m, c, n, pk, sk)
}

exports.crypto_box_open_detached = function (m, c, mac, n, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(mac.byteLength === exports.crypto_box_MACBYTES, "mac must be 'crypto_box_MACBYTES' bytes")
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_open_detached(m, c, mac, n, pk, sk)
}

exports.crypto_box_seal = function (c, m, pk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    c.byteLength === m.byteLength + exports.crypto_box_SEALBYTES,
    "c must be 'm.byteLength + crypto_box_SEALBYTES' bytes"
  )
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_box_seal(c, m, pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_seal_open = function (m, c, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength >= exports.crypto_box_SEALBYTES,
    "c must be at least 'crypto_box_SEALBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - exports.crypto_box_SEALBYTES,
    "m must be 'c.byteLength - crypto_box_SEALBYTES' bytes"
  )
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_seal_open(
    m.buffer,
    m.byteOffset,
    m.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    pk.buffer,
    pk.byteOffset,
    pk.byteLength,

    sk.buffer,
    sk.byteOffset,
    sk.byteLength
  )
}

// crypto_secretbox

exports.crypto_secretbox_easy = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_secretbox_MACBYTES,
    "c must be 'm.byteLength + crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretbox_easy(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretbox_open_easy = function (m, c, n, k) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    c.byteLength >= binding.crypto_secretbox_MACBYTES,
    "c must be at least 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - binding.crypto_secretbox_MACBYTES,
    "m must be 'c.byteLength - crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  return binding.crypto_secretbox_open_easy(m, c, n, k)
}

exports.crypto_secretbox_detached = function (c, mac, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    mac.byteLength === binding.crypto_secretbox_MACBYTES,
    "mac must be 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretbox_detached(c, mac, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretbox_open_detached = function (m, c, mac, n, k) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(
    mac.byteLength === binding.crypto_secretbox_MACBYTES,
    "mac must be 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  return binding.crypto_secretbox_open_detached(m, c, mac, n, k)
}

// crypto_generichash

exports.crypto_generichash = function (output, input, key) {
  if (!key) key = OPTIONAL

  assert(ArrayBuffer.isView(output), 'output must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    output.byteLength >= binding.crypto_generichash_BYTES_MIN &&
      output.byteLength <= binding.crypto_generichash_BYTES_MAX,
    'output must be between crypto_generichash_BYTES_MIN and crypto_generichash_BYTES_MAX bytes'
  )

  if (key !== OPTIONAL) {
    assert(ArrayBuffer.isView(key), 'key must be a typed array')
    assert(
      key.byteLength >= binding.crypto_generichash_KEYBYTES_MIN &&
        key.byteLength <= binding.crypto_generichash_KEYBYTES_MAX,
      'key must be between crypto_generichash_KEYBYTES_MIN and crypto_generichash_KEYBYTES_MAX bytes'
    )
  }

  const res = binding.crypto_generichash(
    output.buffer,
    output.byteOffset,
    output.byteLength,

    input.buffer,
    input.byteOffset,
    input.byteLength,

    key.buffer,
    key.byteOffset,
    key.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_batch = function (output, batch, key) {
  assert(ArrayBuffer.isView(output), 'output must be a typed array')

  if (isNode || batch.length < 4) {
    const res = binding.crypto_generichash_batch(output, batch, !!key, key || OPTIONAL)
    if (res !== 0) throw new Error('status: ' + res)
  } else {
    const state = Buffer.alloc(binding.crypto_generichash_STATEBYTES)

    exports.crypto_generichash_init(state, key, output.byteLength)

    for (const buf of batch) {
      exports.crypto_generichash_update(state, buf)
    }

    exports.crypto_generichash_final(state, output)
  }
}

exports.crypto_generichash_keygen = function (key) {
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(
    key.byteLength === binding.crypto_generichash_KEYBYTES,
    "key must be 'crypto_generichash_KEYBYTES' bytes"
  )

  const res = binding.crypto_generichash_keygen(key.buffer, key.byteOffset, key.byteLength)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_init = function (state, key, outputLength) {
  if (!key) key = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_init(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    key.buffer,
    key.byteOffset,
    key.byteLength,

    outputLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_update(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    input.buffer,
    input.byteOffset,
    input.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_final = function (state, output) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(output), 'output must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_final(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    output.buffer,
    output.byteOffset,
    output.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

// secretstream

exports.crypto_secretstream_xchacha20poly1305_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  binding.crypto_secretstream_xchacha20poly1305_keygen(k.buffer, k.byteOffset, k.byteLength)
}

exports.crypto_secretstream_xchacha20poly1305_init_push = function (state, header, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(header), 'header must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    header.byteLength === binding.crypto_secretstream_xchacha20poly1305_HEADERBYTES,
    "header must be 'crypto_secretstream_xchacha20poly1305_HEADERBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_init_push(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    header.buffer,
    header.byteOffset,
    header.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretstream_xchacha20poly1305_init_pull = function (state, header, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(header), 'header must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    header.byteLength === binding.crypto_secretstream_xchacha20poly1305_HEADERBYTES,
    "header must be 'crypto_secretstream_xchacha20poly1305_HEADERBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_init_pull(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    header.buffer,
    header.byteOffset,
    header.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretstream_xchacha20poly1305_push = function (state, c, m, ad, tag) {
  if (!ad) ad = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    c.byteLength === m.byteLength + binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "c must be 'm.byteLength + crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_push(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    ad.buffer,
    ad.byteOffset,
    ad.byteLength,

    tag
  )

  if (res < 0) throw new Error('push failed')

  return res
}

exports.crypto_secretstream_xchacha20poly1305_pull = function (state, m, tag, c, ad) {
  if (!ad) ad = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(tag), 'tag must be a typed array')
  assert(tag.byteLength === 1, 'tag must be 1 byte')

  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    c.byteLength >= binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "c must be at least 'crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "m must be 'c.byteLength - crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_pull(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    tag.buffer,
    tag.byteOffset,
    tag.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    ad.buffer,
    ad.byteOffset,
    ad.byteLength
  )

  if (res < 0) throw new Error('pull failed')

  return res
}

exports.crypto_secretstream_xchacha20poly1305_rekey = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )

  binding.crypto_secretstream_xchacha20poly1305_rekey(
    state.buffer,
    state.byteOffset,
    state.byteLength
  )
}

// crypto_stream

exports.crypto_stream = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xor(
    c.buffer,
    c.byteOffset,
    c.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    n.buffer,
    n.byteOffset,
    n.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_auth

exports.crypto_auth = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(out.byteLength === binding.crypto_auth_BYTES, "out must be 'crypto_auth_BYTES' bytes")
  assert(k.byteLength === binding.crypto_auth_KEYBYTES, "k must be 'crypto_auth_KEYBYTES' bytes")

  const res = binding.crypto_auth(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_auth_verify = function (h, input, k) {
  assert(ArrayBuffer.isView(h), 'h must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(h.byteLength === binding.crypto_auth_BYTES, "h must be 'crypto_auth_BYTES' bytes")
  assert(k.byteLength === binding.crypto_auth_KEYBYTES, "k must be 'crypto_auth_KEYBYTES' bytes")

  return binding.crypto_auth_verify(h, input, k)
}

// crypto_onetimeauth

exports.crypto_onetimeauth = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    out.byteLength === binding.crypto_onetimeauth_BYTES,
    "out must be 'crypto_onetimeauth_BYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_init = function (state, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_init(state, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )
  assert(
    out.byteLength === binding.crypto_onetimeauth_BYTES,
    "out must be 'crypto_onetimeauth_BYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_verify = function (h, input, k) {
  assert(ArrayBuffer.isView(h), 'h must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    h.byteLength === binding.crypto_onetimeauth_BYTES,
    "h must be 'crypto_onetimeauth_BYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  return binding.crypto_onetimeauth_verify(h, input, k)
}

// crypto_pwhash

exports.crypto_pwhash = function (out, passwd, salt, opslimit, memlimit, alg) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_BYTES_MIN,
    "out must be at least 'crypto_pwhash_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_BYTES_MAX,
    "out must be at most 'crypto_pwhash_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_SALTBYTES,
    "salt must be 'crypto_pwhash_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )
  assert(alg >= 1 && alg <= 2, 'alg must be either Argon2i 1.3 or Argon2id 1.3')

  const res = binding.crypto_pwhash(out, passwd, salt, opslimit, memlimit, alg)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_async = function (
  out,
  passwd,
  salt,
  opslimit,
  memlimit,
  alg,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_BYTES_MIN,
    "out must be at least 'crypto_pwhash_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_BYTES_MAX,
    "out must be at most 'crypto_pwhash_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_SALTBYTES,
    "salt must be 'crypto_pwhash_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )
  assert(alg >= 1 && alg <= 2, 'alg must be either Argon2i 1.3 or Argon2id 1.3')

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    opslimit,
    memlimit,
    alg,

    done
  )

  return promise
}

exports.crypto_pwhash_str = function (out, passwd, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_STRBYTES,
    "out must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(typeof opslimit === 'number', 'opslimit must be a number')
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(typeof memlimit === 'number', 'memlimit must be a number')
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_str(out, passwd, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_str_async = function (out, passwd, opslimit, memlimit, callback = undefined) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_STRBYTES,
    "out must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(typeof opslimit === 'number', 'opslimit must be a number')
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(typeof memlimit === 'number', 'memlimit must be a number')
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_str_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_str_verify = function (str, passwd) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )

  return binding.crypto_pwhash_str_verify(str, passwd)
}

exports.crypto_pwhash_str_verify_async = function (str, passwd, callback = undefined) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  const [done, promise] = checkStatus(callback, true)

  binding.crypto_pwhash_str_verify_async(
    str.buffer,
    str.byteOffset,
    str.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    done
  )

  return promise
}

exports.crypto_pwhash_str_needs_rehash = function (str, opslimit, memlimit) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  return binding.crypto_pwhash_str_needs_rehash(str, opslimit, memlimit)
}

exports.crypto_pwhash_scryptsalsa208sha256 = function (out, passwd, salt, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MIN,
    "out must be at least 'crypto_pwhash_scryptsalsa208sha256_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MAX,
    "out must be at most 'crypto_pwhash_scryptsalsa208sha256_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_SALTBYTES,
    "salt must be 'crypto_pwhash_scryptsalsa208sha256_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_scryptsalsa208sha256(out, passwd, salt, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_scryptsalsa208sha256_async = function (
  out,
  passwd,
  salt,
  opslimit,
  memlimit,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MIN,
    "out must be at least 'crypto_pwhash_scryptsalsa208sha256_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MAX,
    "out must be at most 'crypto_pwhash_scryptsalsa208sha256_BYTES_MAX' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    salt.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_SALTBYTES,
    "salt must be 'crypto_pwhash_scryptsalsa208sha256_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_scryptsalsa208sha256_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str_async = function (
  out,
  passwd,
  opslimit,
  memlimit,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "out must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_scryptsalsa208sha256_str_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str = function (out, passwd, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "out must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_scryptsalsa208sha256_str(out, passwd, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_scryptsalsa208sha256_str_verify_async = function (
  str,
  passwd,
  callback = undefined
) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  const [done, promise] = checkStatus(callback, true)

  binding.crypto_pwhash_scryptsalsa208sha256_str_verify_async(
    str.buffer,
    str.byteOffset,
    str.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str_verify = function (str, passwd) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  return binding.crypto_pwhash_scryptsalsa208sha256_str_verify(str, passwd)
}

exports.crypto_pwhash_scryptsalsa208sha256_str_needs_rehash = function (str, opslimit, memlimit) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  return binding.crypto_pwhash_scryptsalsa208sha256_str_needs_rehash(str, opslimit, memlimit)
}

// crypto_kx

exports.crypto_kx_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "pk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "sk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    pk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "pk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "sk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    seed.byteLength === binding.crypto_kx_SEEDBYTES,
    "seed must be 'crypto_kx_SEEDBYTES' bytes"
  )

  const res = binding.crypto_kx_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_client_session_keys = function (rx, tx, clientPk, clientSk, serverPk) {
  if (!rx) rx = undefined
  if (!tx) tx = undefined

  assert(rx || tx, 'at least one session key must be specified')

  if (rx) {
    assert(ArrayBuffer.isView(rx), 'rx must be a typed array')
    assert(
      rx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "rx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  if (tx) {
    assert(ArrayBuffer.isView(tx), 'tx must be a typed array')
    assert(
      tx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "tx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  assert(ArrayBuffer.isView(clientPk), 'clientPk must be a typed array')
  assert(ArrayBuffer.isView(clientSk), 'clientSk must be a typed array')
  assert(ArrayBuffer.isView(serverPk), 'serverPk must be a typed array')
  assert(
    clientPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "clientPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    clientSk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "clientSk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    serverPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "serverPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_client_session_keys(rx, tx, clientPk, clientSk, serverPk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_server_session_keys = function (rx, tx, serverPk, serverSk, clientPk) {
  if (!rx) rx = undefined
  if (!tx) tx = undefined

  assert(rx || tx, 'at least one session key must be specified')

  if (rx) {
    assert(ArrayBuffer.isView(rx), 'rx must be a typed array')
    assert(
      rx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "rx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  if (tx) {
    assert(ArrayBuffer.isView(tx), 'tx must be a typed array')
    assert(
      tx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "tx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  assert(ArrayBuffer.isView(serverPk), 'serverPk must be a typed array')
  assert(ArrayBuffer.isView(serverSk), 'serverSk must be a typed array')
  assert(ArrayBuffer.isView(clientPk), 'clientPk must be a typed array')
  assert(
    serverPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "serverPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    serverSk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "serverSk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    clientPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "clientPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_server_session_keys(rx, tx, serverPk, serverSk, clientPk)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_scalarmult

exports.crypto_scalarmult_base = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_BYTES,
    "q must be 'crypto_scalarmult_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_SCALARBYTES,
    "n must be 'crypto_scalarmult_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_base(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_BYTES,
    "q must be 'crypto_scalarmult_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_SCALARBYTES,
    "n must be 'crypto_scalarmult_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_BYTES,
    "p must be 'crypto_scalarmult_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_base = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_base(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519 = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "p must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_is_valid_point = function (p) {
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )

  return binding.crypto_core_ed25519_is_valid_point(p)
}

exports.crypto_core_ed25519_from_uniform = function (p, r) {
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_UNIFORMBYTES,
    "r must be 'crypto_core_ed25519_UNIFORMBYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_from_uniform(p, r)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_base_noclamp = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_base_noclamp(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_noclamp = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "p must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_noclamp(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_core

exports.crypto_core_ed25519_add = function (r, p, q) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_BYTES,
    "r must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_core_ed25519_BYTES,
    "q must be 'crypto_core_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_add(r, p, q)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_sub = function (r, p, q) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_BYTES,
    "r must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_core_ed25519_BYTES,
    "q must be 'crypto_core_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_sub(r, p, q)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_scalar_random = function (r) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "r must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_random(r)
}

exports.crypto_core_ed25519_scalar_reduce = function (r, s) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "r must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_NONREDUCEDSCALARBYTES,
    "s must be 'crypto_core_ed25519_NONREDUCEDSCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_reduce(r, s)
}

exports.crypto_core_ed25519_scalar_invert = function (recip, s) {
  assert(ArrayBuffer.isView(recip), 'recip must be a typed array')
  assert(
    recip.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "recip must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_invert(recip, s)
}

exports.crypto_core_ed25519_scalar_negate = function (neg, s) {
  assert(ArrayBuffer.isView(neg), 'neg must be a typed array')
  assert(
    neg.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "neg must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_negate(neg, s)
}

exports.crypto_core_ed25519_scalar_complement = function (comp, s) {
  assert(ArrayBuffer.isView(comp), 'comp must be a typed array')
  assert(
    comp.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "comp must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_complement(comp, s)
}

exports.crypto_core_ed25519_scalar_add = function (z, x, y) {
  assert(ArrayBuffer.isView(z), 'z must be a typed array')
  assert(
    z.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "z must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(x), 'x must be a typed array')
  assert(
    x.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "x must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(y), 'y must be a typed array')
  assert(
    y.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "y must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_add(z, x, y)
}

exports.crypto_core_ed25519_scalar_sub = function (z, x, y) {
  assert(ArrayBuffer.isView(z), 'z must be a typed array')
  assert(
    z.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "z must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(x), 'x must be a typed array')
  assert(
    x.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "x must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(y), 'y must be a typed array')
  assert(
    y.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "y must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_sub(z, x, y)
}

// crypto_shorthash

exports.crypto_shorthash = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_shorthash_BYTES,
    "out must be 'crypto_shorthash_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_shorthash_KEYBYTES,
    "k must be 'crypto_shorthash_KEYBYTES' bytes"
  )

  const res = binding.crypto_shorthash(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_kdf

exports.crypto_kdf_keygen = function (key) {
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(key.byteLength === binding.crypto_kdf_KEYBYTES, "key must be 'crypto_kdf_KEYBYTES' bytes")

  binding.crypto_kdf_keygen(key)
}

exports.crypto_kdf_derive_from_key = function (subkey, subkeyId, ctx, key) {
  assert(ArrayBuffer.isView(subkey), 'subkey must be a typed array')
  assert(
    subkey.byteLength >= binding.crypto_kdf_BYTES_MIN,
    "subkey must be at least 'crypto_kdf_BYTES_MIN' bytes"
  )
  assert(
    subkey.byteLength <= binding.crypto_kdf_BYTES_MAX,
    "subkey must be at most 'crypto_kdf_BYTES_MAX' bytes"
  )
  assert(ArrayBuffer.isView(ctx), 'ctx must be a typed array')
  assert(
    ctx.byteLength === binding.crypto_kdf_CONTEXTBYTES,
    "ctx must be 'crypto_kdf_CONTEXTBYTES' bytes"
  )
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(key.byteLength === binding.crypto_kdf_KEYBYTES, "key must be 'crypto_kdf_KEYBYTES' bytes")

  const res = binding.crypto_kdf_derive_from_key(subkey, subkeyId, ctx, key)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_hash

exports.crypto_hash = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(out.byteLength === binding.crypto_hash_BYTES, "out must be 'crypto_hash_BYTES' bytes")

  const res = binding.crypto_hash(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256 = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha256_BYTES,
    "out must be 'crypto_hash_sha256_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha256(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_init = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_init(state)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha256_BYTES,
    "out must be 'crypto_hash_sha256_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512 = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha512_BYTES,
    "out must be 'crypto_hash_sha512_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha512(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_init = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_init(state)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha512_BYTES,
    "out must be 'crypto_hash_sha512_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_aead

exports.crypto_aead_xchacha20poly1305_ietf_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  binding.crypto_aead_xchacha20poly1305_ietf_keygen(k)
}

exports.crypto_aead_xchacha20poly1305_ietf_encrypt = function (c, m, ad, nsec, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "c must be 'm.byteLength + crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(c.byteLength <= 0xffffffff, 'c.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_encrypt(c, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_decrypt = function (m, nsec, c, ad, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "m must be 'c.byteLength - crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(m.byteLength <= 0xffffffff, 'm.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_decrypt(m, c, ad, npub, k)

  if (res < 0) throw new Error('could not verify data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_encrypt_detached = function (
  c,
  mac,
  m,
  ad,
  nsec,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_encrypt_detached(c, mac, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_decrypt_detached = function (
  m,
  nsec,
  c,
  mac,
  ad,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_decrypt_detached(m, c, mac, ad, npub, k)

  if (res !== 0) throw new Error('could not verify data')
}

exports.crypto_aead_chacha20poly1305_ietf_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  binding.crypto_aead_chacha20poly1305_ietf_keygen(k)
}

exports.crypto_aead_chacha20poly1305_ietf_encrypt = function (c, m, ad, nsec, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "c must be 'm.byteLength + crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(c.byteLength <= 0xffffffff, 'c.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_encrypt(c, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_decrypt = function (m, nsec, c, ad, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "m must be 'c.byteLength - crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(m.byteLength <= 0xffffffff, 'm.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_decrypt(m, c, ad, npub, k)

  if (res < 0) throw new Error('could not verify data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_encrypt_detached = function (
  c,
  mac,
  m,
  ad,
  nsec,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_encrypt_detached(c, mac, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_decrypt_detached = function (
  m,
  nsec,
  c,
  mac,
  ad,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_decrypt_detached(m, c, mac, ad, npub, k)

  if (res !== 0) throw new Error('could not verify data')
}

// crypto_stream

exports.crypto_stream_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  binding.crypto_stream_xor_wrap_init(state, n, k)
}

exports.crypto_stream_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_xor_wrap_update(state, c, m)
}

exports.crypto_stream_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_xor_wrap_final(state)
}

exports.crypto_stream_chacha20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  binding.crypto_stream_chacha20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_chacha20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_chacha20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_chacha20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_chacha20_xor_wrap_final(state)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  binding.crypto_stream_chacha20_ietf_xor_wrap_init(state, n, k)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_chacha20_ietf_xor_wrap_update(state, c, m)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_chacha20_ietf_xor_wrap_final(state)
}

exports.crypto_stream_xchacha20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  binding.crypto_stream_xchacha20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_xchacha20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_xchacha20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_xchacha20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_xchacha20_xor_wrap_final(state)
}

exports.crypto_stream_salsa20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  binding.crypto_stream_salsa20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_salsa20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_salsa20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_salsa20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_salsa20_xor_wrap_final(state)
}

// experimental

exports.extension_tweak_ed25519_base = function (n, p, ns) {
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.extension_tweak_ed25519_BYTES,
    "p must be 'extension_tweak_ed25519_BYTES' bytes"
  )

  binding.extension_tweak_ed25519_base(n, p, ns)
}

exports.extension_tweak_ed25519_sign_detached = function (sig, m, scalar, pk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(sig.byteLength === binding.crypto_sign_BYTES, "sig must be 'crypto_sign_BYTES' bytes")
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  if (pk) {
    assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
    assert(
      pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
      "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
    )
  }

  const res = binding.extension_tweak_ed25519_sign_detached(sig, m, scalar, pk)

  if (res !== 0) throw new Error('failed to compute signature')
}

exports.extension_tweak_ed25519_sk_to_scalar = function (n, sk) {
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  binding.extension_tweak_ed25519_sk_to_scalar(n, sk)
}

exports.extension_tweak_ed25519_scalar = function (scalarOut, scalar, ns) {
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_scalar(scalarOut, scalar, ns)
}

exports.extension_tweak_ed25519_pk = function (tpk, pk, ns) {
  assert(ArrayBuffer.isView(tpk), 'tpk must be a typed array')
  assert(
    tpk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "tpk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_pk(tpk, pk, ns)

  if (res !== 0) throw new Error('failed to tweak public key')
}

exports.extension_tweak_ed25519_keypair = function (pk, scalarOut, scalarIn, ns) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.extension_tweak_ed25519_BYTES,
    "pk must be 'extension_tweak_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarIn), 'scalarIn must be a typed array')
  assert(
    scalarIn.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarIn must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_keypair(pk, scalarOut, scalarIn, ns)
}

exports.extension_tweak_ed25519_scalar_add = function (scalarOut, scalar, n) {
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_scalar_add(scalarOut, scalar, n)
}

exports.extension_tweak_ed25519_pk_add = function (tpk, pk, p) {
  assert(ArrayBuffer.isView(tpk), 'tpk must be a typed array')
  assert(
    tpk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "tpk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "p must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_pk_add(tpk, pk, p)

  if (res !== 0) throw new Error('failed to add tweak to public key')
}

exports.extension_tweak_ed25519_keypair_add = function (pk, scalarOut, scalarIn, tweak) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.extension_tweak_ed25519_BYTES,
    "pk must be 'extension_tweak_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarIn), 'scalarIn must be a typed array')
  assert(
    scalarIn.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarIn must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(tweak), 'tweak must be a typed array')
  assert(
    tweak.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "tweak must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_keypair_add(pk, scalarOut, scalarIn, tweak)

  if (res !== 0) throw new Error('failed to add tweak to keypair')
}

exports.extension_pbkdf2_sha512_async = function (out, passwd, salt, iter, outlen, callback) {
  assert(
    iter >= binding.extension_pbkdf2_sha512_ITERATIONS_MIN,
    "iter must be at least 'extension_pbkdf2_sha512_ITERATIONS_MIN'"
  )
  assert(
    outlen <= binding.extension_pbkdf2_sha512_BYTES_MAX,
    "outlen must be at most 'extension_pbkdf2_sha512_BYTES_MAX'"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(out.byteLength >= outlen, "out must be at least 'outlen' bytes")
  assert(out.byteLength > 0, 'out must not be empty')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(salt.byteLength > 0, 'salt must not be empty')

  const [done, promise] = checkStatus(callback)

  binding.extension_pbkdf2_sha512_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    iter,
    outlen,

    done
  )

  return promise
}

exports.extension_pbkdf2_sha512 = function (out, passwd, salt, iter, outlen) {
  assert(
    iter >= binding.extension_pbkdf2_sha512_ITERATIONS_MIN,
    "iter must be at least 'extension_pbkdf2_sha512_ITERATIONS_MIN'"
  )
  assert(
    outlen <= binding.extension_pbkdf2_sha512_BYTES_MAX,
    "outlen must be at most 'extension_pbkdf2_sha512_BYTES_MAX'"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(out.byteLength >= outlen, "out must be at least 'outlen' bytes")
  assert(out.byteLength > 0, 'out must not be empty')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(salt.byteLength > 0, 'salt must not be empty')

  const res = binding.extension_pbkdf2_sha512(out, passwd, salt, iter, outlen)

  if (res !== 0) throw new Error('failed to add tweak to public key')
}

function checkStatus(callback, booleanResult = false) {
  let done, promise

  if (typeof callback === 'function') {
    done = function (status) {
      if (booleanResult) callback(null, status === 0)
      else if (status === 0) callback(null)
      else callback(new Error('status: ' + status))
    }
  } else {
    promise = new Promise(function (resolve, reject) {
      done = function (status) {
        if (booleanResult) resolve(status === 0)
        else if (status === 0) resolve()
        else reject(new Error('status: ' + status))
      }
    })
  }

  return [done, promise]
}
{
  "name": "sodium-native",
  "version": "5.1.0",
  "description": "Low level bindings for libsodium",
  "main": "index.js",
  "files": [
    "index.js",
    "binding.cc",
    "binding.js",
    "extensions",
    "prebuilds",
    "CMakeLists.txt"
  ],
  "imports": {
    "assert": {
      "bare": "bare-assert",
      "node": "assert"
    }
  },
  "addon": true,
  "dependencies": {
    "bare-assert": "^1.2.0",
    "require-addon": "^1.1.0",
    "which-runtime": "^1.2.1"
  },
  "devDependencies": {
    "bare-compat-napi": "^1.3.5",
    "brittle": "^3.16.2",
    "cmake-bare": "^1.6.1",
    "cmake-fetch": "^1.4.3",
    "cmake-napi": "^1.2.1",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "test": "prettier . --check && npm run test:node && npm run test:bare",
    "test:node": "node test/all.js",
    "test:bare": "bare test/all.js"
  },
  "standard": {
    "ignore": [
      "/test/fixtures/*.js"
    ]
  },
  "engines": {
    "bare": ">=1.16.0"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sodium-native.git"
  },
  "contributors": [
    "Emil Bay <github@tixz.dk> (http://bayes.dk)",
    "Mathias Buus <mathiasbuus@gmail.com> (https://mafinto.sh)",
    "Christophe Diederichs <chm-diederichs@hyperdivision.dk>"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/sodium-native/issues"
  },
  "homepage": "https://github.com/holepunchto/sodium-native"
}
const sodium = require('sodium-universal')
const b4a = require('b4a')

const ABYTES = sodium.crypto_secretstream_xchacha20poly1305_ABYTES
const TAG_MESSAGE = sodium.crypto_secretstream_xchacha20poly1305_TAG_MESSAGE
const TAG_FINAL = sodium.crypto_secretstream_xchacha20poly1305_TAG_FINAL
const STATEBYTES = sodium.crypto_secretstream_xchacha20poly1305_STATEBYTES
const HEADERBYTES = sodium.crypto_secretstream_xchacha20poly1305_HEADERBYTES
const KEYBYTES = sodium.crypto_secretstream_xchacha20poly1305_KEYBYTES
const TAG_FINAL_BYTE = b4a.isBuffer(TAG_FINAL) ? TAG_FINAL[0] : TAG_FINAL

const EMPTY = b4a.alloc(0)
const TAG = b4a.alloc(1)

class Push {
  constructor (key, state = b4a.allocUnsafeSlow(STATEBYTES), header = b4a.allocUnsafeSlow(HEADERBYTES)) {
    if (!TAG_FINAL) throw new Error('JavaScript sodium version needs to support crypto_secretstream_xchacha20poly')

    this.key = key
    this.state = state
    this.header = header

    sodium.crypto_secretstream_xchacha20poly1305_init_push(this.state, this.header, this.key)
  }

  next (message, cipher = b4a.allocUnsafe(message.byteLength + ABYTES)) {
    sodium.crypto_secretstream_xchacha20poly1305_push(this.state, cipher, message, null, TAG_MESSAGE)
    return cipher
  }

  final (message = EMPTY, cipher = b4a.allocUnsafe(ABYTES)) {
    sodium.crypto_secretstream_xchacha20poly1305_push(this.state, cipher, message, null, TAG_FINAL)
    return cipher
  }
}

class Pull {
  constructor (key, state = b4a.allocUnsafeSlow(STATEBYTES)) {
    if (!TAG_FINAL) throw new Error('JavaScript sodium version needs to support crypto_secretstream_xchacha20poly')

    this.key = key
    this.state = state
    this.final = false
  }

  init (header) {
    sodium.crypto_secretstream_xchacha20poly1305_init_pull(this.state, header, this.key)
  }

  next (cipher, message = b4a.allocUnsafe(cipher.byteLength - ABYTES)) {
    sodium.crypto_secretstream_xchacha20poly1305_pull(this.state, message, TAG, cipher, null)
    this.final = TAG[0] === TAG_FINAL_BYTE
    return message
  }
}

function keygen (buf = b4a.alloc(KEYBYTES)) {
  sodium.crypto_secretstream_xchacha20poly1305_keygen(buf)
  return buf
}

module.exports = {
  keygen,
  KEYBYTES,
  ABYTES,
  STATEBYTES,
  HEADERBYTES,
  Push,
  Pull
}
{
  "name": "sodium-secretstream",
  "version": "1.2.0",
  "description": "Wraps libsodiums secretstream in a higher level abstraction",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.1.1",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "standard": "^17.0.0"
  },
  "scripts": {
    "test": "standard"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/sodium-secretstream.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/sodium-secretstream/issues"
  },
  "homepage": "https://github.com/mafintosh/sodium-secretstream"
}
module.exports = require('sodium-native')
{
  "name": "sodium-universal",
  "version": "5.0.1",
  "description": "Universal wrapper for sodium-javascript and sodium-native working in Node.js and the Browser",
  "main": "index.js",
  "dependencies": {
    "sodium-native": "^5.0.1"
  },
  "peerDependencies": {
    "sodium-javascript": "~0.8.0"
  },
  "peerDependenciesMeta": {
    "sodium-javascript": {
      "optional": true
    }
  },
  "scripts": {
    "prepublish": "./build-scripts/generate.js"
  },
  "browser": {
    "sodium-native": "sodium-javascript"
  },
  "browserify": {
    "transform": [
      "./build-scripts/transform.js"
    ]
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sodium-universal.git"
  },
  "keywords": [
    "libsodium",
    "sodium",
    "sodium-native",
    "sodium-javascript",
    "browserify"
  ],
  "contributors": [
    "Emil Bay <github@tixz.dk> (http://bayes.dk)",
    "Mathias Buus <mathiasbuus@gmail.com> (https://mafinto.sh)",
    "Christophe Diederichs <chm-diederichs@hyperdivision.dk>"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/sodium-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/sodium-universal#readme"
}
const { EventEmitter } = require('events-universal')
const FIFO = require('fast-fifo')
const TextDecoder = require('text-decoder')

const StreamError = require('./lib/errors.js')

// if we do a future major, expect queue microtask to be there always, for now a bit defensive
const qmt =
  typeof queueMicrotask === 'undefined' ? (fn) => global.process.nextTick(fn) : queueMicrotask

// 29 bits used total (4 from shared, 14 from read, and 11 from write)
const MAX = (1 << 29) - 1

// Shared state
const OPENING = 0b0001
const PREDESTROYING = 0b0010
const DESTROYING = 0b0100
const DESTROYED = 0b1000

const NOT_OPENING = MAX ^ OPENING
const NOT_PREDESTROYING = MAX ^ PREDESTROYING

// Read state (4 bit offset from shared state)
const READ_ACTIVE = 0b00000000000001 << 4
const READ_UPDATING = 0b00000000000010 << 4
const READ_PRIMARY = 0b00000000000100 << 4
const READ_QUEUED = 0b00000000001000 << 4
const READ_RESUMED = 0b00000000010000 << 4
const READ_PIPE_DRAINED = 0b00000000100000 << 4
const READ_ENDING = 0b00000001000000 << 4
const READ_EMIT_DATA = 0b00000010000000 << 4
const READ_EMIT_READABLE = 0b00000100000000 << 4
const READ_EMITTED_READABLE = 0b00001000000000 << 4
const READ_DONE = 0b00010000000000 << 4
const READ_NEXT_TICK = 0b00100000000000 << 4
const READ_NEEDS_PUSH = 0b01000000000000 << 4
const READ_READ_AHEAD = 0b10000000000000 << 4

// Combined read state
const READ_FLOWING = READ_RESUMED | READ_PIPE_DRAINED
const READ_ACTIVE_AND_NEEDS_PUSH = READ_ACTIVE | READ_NEEDS_PUSH
const READ_PRIMARY_AND_ACTIVE = READ_PRIMARY | READ_ACTIVE
const READ_EMIT_READABLE_AND_QUEUED = READ_EMIT_READABLE | READ_QUEUED
const READ_RESUMED_READ_AHEAD = READ_RESUMED | READ_READ_AHEAD

const READ_NOT_ACTIVE = MAX ^ READ_ACTIVE
const READ_NON_PRIMARY = MAX ^ READ_PRIMARY
const READ_NON_PRIMARY_AND_PUSHED = MAX ^ (READ_PRIMARY | READ_NEEDS_PUSH)
const READ_PUSHED = MAX ^ READ_NEEDS_PUSH
const READ_PAUSED = MAX ^ READ_RESUMED
const READ_NOT_QUEUED = MAX ^ (READ_QUEUED | READ_EMITTED_READABLE)
const READ_NOT_ENDING = MAX ^ READ_ENDING
const READ_PIPE_NOT_DRAINED = MAX ^ READ_FLOWING
const READ_NOT_NEXT_TICK = MAX ^ READ_NEXT_TICK
const READ_NOT_UPDATING = MAX ^ READ_UPDATING
const READ_NO_READ_AHEAD = MAX ^ READ_READ_AHEAD
const READ_PAUSED_NO_READ_AHEAD = MAX ^ READ_RESUMED_READ_AHEAD

// Write state (18 bit offset, 4 bit offset from shared state and 14 from read state)
const WRITE_ACTIVE = 0b00000000001 << 18
const WRITE_UPDATING = 0b00000000010 << 18
const WRITE_PRIMARY = 0b00000000100 << 18
const WRITE_QUEUED = 0b00000001000 << 18
const WRITE_UNDRAINED = 0b00000010000 << 18
const WRITE_DONE = 0b00000100000 << 18
const WRITE_EMIT_DRAIN = 0b00001000000 << 18
const WRITE_NEXT_TICK = 0b00010000000 << 18
const WRITE_WRITING = 0b00100000000 << 18
const WRITE_FINISHING = 0b01000000000 << 18
const WRITE_CORKED = 0b10000000000 << 18

const WRITE_NOT_ACTIVE = MAX ^ (WRITE_ACTIVE | WRITE_WRITING)
const WRITE_NON_PRIMARY = MAX ^ WRITE_PRIMARY
const WRITE_NOT_FINISHING = MAX ^ (WRITE_ACTIVE | WRITE_FINISHING)
const WRITE_DRAINED = MAX ^ WRITE_UNDRAINED
const WRITE_NOT_QUEUED = MAX ^ WRITE_QUEUED
const WRITE_NOT_NEXT_TICK = MAX ^ WRITE_NEXT_TICK
const WRITE_NOT_UPDATING = MAX ^ WRITE_UPDATING
const WRITE_NOT_CORKED = MAX ^ WRITE_CORKED

// Combined shared state
const ACTIVE = READ_ACTIVE | WRITE_ACTIVE
const NOT_ACTIVE = MAX ^ ACTIVE
const DONE = READ_DONE | WRITE_DONE
const DESTROY_STATUS = DESTROYING | DESTROYED | PREDESTROYING
const OPEN_STATUS = DESTROY_STATUS | OPENING
const AUTO_DESTROY = DESTROY_STATUS | DONE
const NON_PRIMARY = WRITE_NON_PRIMARY & READ_NON_PRIMARY
const ACTIVE_OR_TICKING = WRITE_NEXT_TICK | READ_NEXT_TICK
const TICKING = ACTIVE_OR_TICKING & NOT_ACTIVE
const IS_OPENING = OPEN_STATUS | TICKING

// Combined shared state and read state
const READ_PRIMARY_STATUS = OPEN_STATUS | READ_ENDING | READ_DONE
const READ_STATUS = OPEN_STATUS | READ_DONE | READ_QUEUED
const READ_ENDING_STATUS = OPEN_STATUS | READ_ENDING | READ_QUEUED
const READ_READABLE_STATUS = OPEN_STATUS | READ_EMIT_READABLE | READ_QUEUED | READ_EMITTED_READABLE
const SHOULD_NOT_READ =
  OPEN_STATUS | READ_ACTIVE | READ_ENDING | READ_DONE | READ_NEEDS_PUSH | READ_READ_AHEAD
const READ_BACKPRESSURE_STATUS = DESTROY_STATUS | READ_ENDING | READ_DONE
const READ_UPDATE_SYNC_STATUS = READ_UPDATING | OPEN_STATUS | READ_NEXT_TICK | READ_PRIMARY
const READ_NEXT_TICK_OR_OPENING = READ_NEXT_TICK | OPENING

// Combined write state
const WRITE_PRIMARY_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_DONE
const WRITE_QUEUED_AND_UNDRAINED = WRITE_QUEUED | WRITE_UNDRAINED
const WRITE_QUEUED_AND_ACTIVE = WRITE_QUEUED | WRITE_ACTIVE
const WRITE_DRAIN_STATUS = WRITE_QUEUED | WRITE_UNDRAINED | OPEN_STATUS | WRITE_ACTIVE
const WRITE_STATUS = OPEN_STATUS | WRITE_ACTIVE | WRITE_QUEUED | WRITE_CORKED
const WRITE_PRIMARY_AND_ACTIVE = WRITE_PRIMARY | WRITE_ACTIVE
const WRITE_ACTIVE_AND_WRITING = WRITE_ACTIVE | WRITE_WRITING
const WRITE_FINISHING_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_QUEUED_AND_ACTIVE | WRITE_DONE
const WRITE_BACKPRESSURE_STATUS = WRITE_UNDRAINED | DESTROY_STATUS | WRITE_FINISHING | WRITE_DONE
const WRITE_UPDATE_SYNC_STATUS = WRITE_UPDATING | OPEN_STATUS | WRITE_NEXT_TICK | WRITE_PRIMARY
const WRITE_DROP_DATA = WRITE_FINISHING | WRITE_DONE | DESTROY_STATUS

const asyncIterator = Symbol.asyncIterator || Symbol('asyncIterator')

class WritableState {
  constructor(
    stream,
    { highWaterMark = 16384, map = null, mapWritable, byteLength, byteLengthWritable } = {}
  ) {
    this.stream = stream
    this.queue = new FIFO()
    this.highWaterMark = highWaterMark
    this.buffered = 0
    this.error = null
    this.pipeline = null
    this.drains = null // if we add more seldomly used helpers we might them into a subobject so its a single ptr
    this.byteLength = byteLengthWritable || byteLength || defaultByteLength
    this.map = mapWritable || map
    this.afterWrite = afterWrite.bind(this)
    this.afterUpdateNextTick = updateWriteNT.bind(this)
  }

  get ending() {
    return (this.stream._duplexState & WRITE_FINISHING) !== 0
  }

  get ended() {
    return (this.stream._duplexState & WRITE_DONE) !== 0
  }

  push(data) {
    if ((this.stream._duplexState & WRITE_DROP_DATA) !== 0) return false
    if (this.map !== null) data = this.map(data)

    this.buffered += this.byteLength(data)
    this.queue.push(data)

    if (this.buffered < this.highWaterMark) {
      this.stream._duplexState |= WRITE_QUEUED
      return true
    }

    this.stream._duplexState |= WRITE_QUEUED_AND_UNDRAINED
    return false
  }

  shift() {
    const data = this.queue.shift()

    this.buffered -= this.byteLength(data)
    if (this.buffered === 0) this.stream._duplexState &= WRITE_NOT_QUEUED

    return data
  }

  end(data) {
    if (typeof data === 'function') {
      this.stream.once('finish', data)
    } else if (data !== undefined && data !== null) {
      this.push(data)
    }

    this.stream._duplexState = (this.stream._duplexState | WRITE_FINISHING) & WRITE_NON_PRIMARY
  }

  autoBatch(data, cb) {
    const buffer = []
    const stream = this.stream

    buffer.push(data)
    while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED_AND_ACTIVE) {
      buffer.push(stream._writableState.shift())
    }

    if ((stream._duplexState & OPEN_STATUS) !== 0) return cb(null)
    stream._writev(buffer, cb)
  }

  update() {
    const stream = this.stream

    stream._duplexState |= WRITE_UPDATING

    do {
      while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED) {
        const data = this.shift()
        stream._duplexState |= WRITE_ACTIVE_AND_WRITING
        stream._write(data, this.afterWrite)
      }

      if ((stream._duplexState & WRITE_PRIMARY_AND_ACTIVE) === 0) this.updateNonPrimary()
    } while (this.continueUpdate() === true)

    stream._duplexState &= WRITE_NOT_UPDATING
  }

  updateNonPrimary() {
    const stream = this.stream

    if ((stream._duplexState & WRITE_FINISHING_STATUS) === WRITE_FINISHING) {
      stream._duplexState = stream._duplexState | WRITE_ACTIVE
      stream._final(afterFinal.bind(this))
      return
    }

    if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
      if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
        stream._duplexState |= ACTIVE
        stream._destroy(afterDestroy.bind(this))
      }
      return
    }

    if ((stream._duplexState & IS_OPENING) === OPENING) {
      stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING
      stream._open(afterOpen.bind(this))
    }
  }

  continueUpdate() {
    if ((this.stream._duplexState & WRITE_NEXT_TICK) === 0) return false
    this.stream._duplexState &= WRITE_NOT_NEXT_TICK
    return true
  }

  updateCallback() {
    if ((this.stream._duplexState & WRITE_UPDATE_SYNC_STATUS) === WRITE_PRIMARY) {
      this.update()
    } else {
      this.updateNextTick()
    }
  }

  updateNextTick() {
    if ((this.stream._duplexState & WRITE_NEXT_TICK) !== 0) return
    this.stream._duplexState |= WRITE_NEXT_TICK
    if ((this.stream._duplexState & WRITE_UPDATING) === 0) qmt(this.afterUpdateNextTick)
  }
}

class ReadableState {
  constructor(
    stream,
    { highWaterMark = 16384, map = null, mapReadable, byteLength, byteLengthReadable } = {}
  ) {
    this.stream = stream
    this.queue = new FIFO()
    this.highWaterMark = highWaterMark === 0 ? 1 : highWaterMark
    this.buffered = 0
    this.readAhead = highWaterMark > 0
    this.error = null
    this.pipeline = null
    this.byteLength = byteLengthReadable || byteLength || defaultByteLength
    this.map = mapReadable || map
    this.pipeTo = null
    this.afterRead = afterRead.bind(this)
    this.afterUpdateNextTick = updateReadNT.bind(this)
  }

  get ending() {
    return (this.stream._duplexState & READ_ENDING) !== 0
  }

  get ended() {
    return (this.stream._duplexState & READ_DONE) !== 0
  }

  pipe(pipeTo, cb) {
    if (this.pipeTo !== null) throw StreamError.BAD_ARGUMENT('Can only pipe to one destination')
    if (typeof cb !== 'function') cb = null

    this.stream._duplexState |= READ_PIPE_DRAINED
    this.pipeTo = pipeTo
    this.pipeline = new Pipeline(this.stream, pipeTo, cb)

    if (cb) this.stream.on('error', noop) // We already error handle this so supress crashes

    if (isStreamx(pipeTo)) {
      pipeTo._writableState.pipeline = this.pipeline
      if (cb) pipeTo.on('error', noop) // We already error handle this so supress crashes
      pipeTo.on('finish', this.pipeline.finished.bind(this.pipeline)) // TODO: just call finished from pipeTo itself
    } else {
      const onerror = this.pipeline.done.bind(this.pipeline, pipeTo)
      const onclose = this.pipeline.done.bind(this.pipeline, pipeTo, null) // onclose has a weird bool arg
      pipeTo.on('error', onerror)
      pipeTo.on('close', onclose)
      pipeTo.on('finish', this.pipeline.finished.bind(this.pipeline))
    }

    pipeTo.on('drain', afterDrain.bind(this))
    this.stream.emit('piping', pipeTo)
    pipeTo.emit('pipe', this.stream)
  }

  push(data) {
    const stream = this.stream

    if (data === null) {
      this.highWaterMark = 0
      stream._duplexState = (stream._duplexState | READ_ENDING) & READ_NON_PRIMARY_AND_PUSHED
      return false
    }

    if (this.map !== null) {
      data = this.map(data)
      if (data === null) {
        stream._duplexState &= READ_PUSHED
        return this.buffered < this.highWaterMark
      }
    }

    this.buffered += this.byteLength(data)
    this.queue.push(data)

    stream._duplexState = (stream._duplexState | READ_QUEUED) & READ_PUSHED

    return this.buffered < this.highWaterMark
  }

  shift() {
    const data = this.queue.shift()

    this.buffered -= this.byteLength(data)
    if (this.buffered === 0) {
      this.stream._duplexState &= READ_NOT_QUEUED
    }

    return data
  }

  unshift(data) {
    const pending = [this.map !== null ? this.map(data) : data]
    while (this.buffered > 0) pending.push(this.shift())

    for (let i = 0; i < pending.length - 1; i++) {
      const data = pending[i]
      this.buffered += this.byteLength(data)
      this.queue.push(data)
    }

    this.push(pending[pending.length - 1])
  }

  read() {
    const stream = this.stream

    if ((stream._duplexState & READ_STATUS) === READ_QUEUED) {
      const data = this.shift()

      if (this.pipeTo !== null && this.pipeTo.write(data) === false) {
        stream._duplexState &= READ_PIPE_NOT_DRAINED
      }

      if ((stream._duplexState & READ_EMIT_DATA) !== 0) {
        stream.emit('data', data)
      }

      return data
    }

    if (this.readAhead === false) {
      stream._duplexState |= READ_READ_AHEAD
      this.updateNextTick()
    }

    return null
  }

  drain() {
    const stream = this.stream

    while (
      (stream._duplexState & READ_STATUS) === READ_QUEUED &&
      (stream._duplexState & READ_FLOWING) !== 0
    ) {
      const data = this.shift()

      if (this.pipeTo !== null && this.pipeTo.write(data) === false) {
        stream._duplexState &= READ_PIPE_NOT_DRAINED
      }

      if ((stream._duplexState & READ_EMIT_DATA) !== 0) {
        stream.emit('data', data)
      }
    }
  }

  update() {
    const stream = this.stream

    stream._duplexState |= READ_UPDATING

    do {
      this.drain()

      while (
        this.buffered < this.highWaterMark &&
        (stream._duplexState & SHOULD_NOT_READ) === READ_READ_AHEAD
      ) {
        stream._duplexState |= READ_ACTIVE_AND_NEEDS_PUSH
        stream._read(this.afterRead)
        this.drain()
      }

      if ((stream._duplexState & READ_READABLE_STATUS) === READ_EMIT_READABLE_AND_QUEUED) {
        stream._duplexState |= READ_EMITTED_READABLE
        stream.emit('readable')
      }

      if ((stream._duplexState & READ_PRIMARY_AND_ACTIVE) === 0) {
        this.updateNonPrimary()
      }
    } while (this.continueUpdate() === true)

    stream._duplexState &= READ_NOT_UPDATING
  }

  updateNonPrimary() {
    const stream = this.stream

    if ((stream._duplexState & READ_ENDING_STATUS) === READ_ENDING) {
      stream._duplexState = (stream._duplexState | READ_DONE) & READ_NOT_ENDING
      stream.emit('end')

      if ((stream._duplexState & AUTO_DESTROY) === DONE) {
        stream._duplexState |= DESTROYING
      }

      if (this.pipeTo !== null) {
        this.pipeTo.end()
      }
    }

    if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
      if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
        stream._duplexState |= ACTIVE
        stream._destroy(afterDestroy.bind(this))
      }
      return
    }

    if ((stream._duplexState & IS_OPENING) === OPENING) {
      stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING
      stream._open(afterOpen.bind(this))
    }
  }

  continueUpdate() {
    if ((this.stream._duplexState & READ_NEXT_TICK) === 0) return false
    this.stream._duplexState &= READ_NOT_NEXT_TICK
    return true
  }

  updateCallback() {
    if ((this.stream._duplexState & READ_UPDATE_SYNC_STATUS) === READ_PRIMARY) {
      this.update()
    } else {
      this.updateNextTick()
    }
  }

  updateNextTickIfOpen() {
    if ((this.stream._duplexState & READ_NEXT_TICK_OR_OPENING) !== 0) return
    this.stream._duplexState |= READ_NEXT_TICK
    if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick)
  }

  updateNextTick() {
    if ((this.stream._duplexState & READ_NEXT_TICK) !== 0) return
    this.stream._duplexState |= READ_NEXT_TICK
    if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick)
  }
}

class TransformState {
  constructor(stream) {
    this.data = null
    this.afterTransform = afterTransform.bind(stream)
    this.afterFinal = null
  }
}

class Pipeline {
  constructor(src, dst, cb) {
    this.from = src
    this.to = dst
    this.afterPipe = cb
    this.error = null
    this.pipeToFinished = false
  }

  finished() {
    this.pipeToFinished = true
  }

  done(stream, err) {
    if (err) this.error = err

    if (stream === this.to) {
      this.to = null

      if (this.from !== null) {
        if ((this.from._duplexState & READ_DONE) === 0 || !this.pipeToFinished) {
          this.from.destroy(this.error || StreamError.PREMATURE_CLOSE('Writable stream closed'))
        }
        return
      }
    }

    if (stream === this.from) {
      this.from = null

      if (this.to !== null) {
        if ((stream._duplexState & READ_DONE) === 0) {
          this.to.destroy(this.error || StreamError.PREMATURE_CLOSE('Readable stream closed'))
        }
        return
      }
    }

    if (this.afterPipe !== null) this.afterPipe(this.error)
    this.to = this.from = this.afterPipe = null
  }
}

function afterDrain() {
  this.stream._duplexState |= READ_PIPE_DRAINED
  this.updateCallback()
}

function afterFinal(err) {
  const stream = this.stream
  if (err) stream.destroy(err)

  if ((stream._duplexState & DESTROY_STATUS) === 0) {
    stream._duplexState |= WRITE_DONE
    stream.emit('finish')
  }

  if ((stream._duplexState & AUTO_DESTROY) === DONE) {
    stream._duplexState |= DESTROYING
  }

  stream._duplexState &= WRITE_NOT_FINISHING

  // no need to wait the extra tick here, so we short circuit that
  if ((stream._duplexState & WRITE_UPDATING) === 0) {
    this.update()
  } else {
    this.updateNextTick()
  }
}

function afterDestroy(err) {
  const stream = this.stream

  if (!err && !StreamError.isStreamDestroyed(this.error)) err = this.error
  if (err) stream.emit('error', err)

  stream._duplexState |= DESTROYED
  stream.emit('close')

  const rs = stream._readableState
  const ws = stream._writableState

  if (rs !== null && rs.pipeline !== null) {
    rs.pipeline.done(stream, err)
  }

  if (ws !== null) {
    while (ws.drains !== null && ws.drains.length > 0) {
      ws.drains.shift().resolve(false)
    }

    if (ws.pipeline !== null) {
      ws.pipeline.done(stream, err)
    }
  }
}

function afterWrite(err) {
  const stream = this.stream

  if (err) stream.destroy(err)
  stream._duplexState &= WRITE_NOT_ACTIVE

  if (this.drains !== null) tickDrains(this.drains)

  if ((stream._duplexState & WRITE_DRAIN_STATUS) === WRITE_UNDRAINED) {
    stream._duplexState &= WRITE_DRAINED

    if ((stream._duplexState & WRITE_EMIT_DRAIN) === WRITE_EMIT_DRAIN) {
      stream.emit('drain')
    }
  }

  this.updateCallback()
}

function afterRead(err) {
  if (err) this.stream.destroy(err)
  this.stream._duplexState &= READ_NOT_ACTIVE

  if (this.readAhead === false && (this.stream._duplexState & READ_RESUMED) === 0) {
    this.stream._duplexState &= READ_NO_READ_AHEAD
  }

  this.updateCallback()
}

function updateReadNT() {
  if ((this.stream._duplexState & READ_UPDATING) === 0) {
    this.stream._duplexState &= READ_NOT_NEXT_TICK
    this.update()
  }
}

function updateWriteNT() {
  if ((this.stream._duplexState & WRITE_UPDATING) === 0) {
    this.stream._duplexState &= WRITE_NOT_NEXT_TICK
    this.update()
  }
}

function tickDrains(drains) {
  for (let i = 0; i < drains.length; i++) {
    // drains.writes are monotonic, so if one is 0 its always the first one
    if (--drains[i].writes === 0) {
      drains.shift().resolve(true)
      i--
    }
  }
}

function afterOpen(err) {
  const stream = this.stream

  if (err) stream.destroy(err)

  if ((stream._duplexState & DESTROYING) === 0) {
    if ((stream._duplexState & READ_PRIMARY_STATUS) === 0) {
      stream._duplexState |= READ_PRIMARY
    }

    if ((stream._duplexState & WRITE_PRIMARY_STATUS) === 0) {
      stream._duplexState |= WRITE_PRIMARY
    }

    stream.emit('open')
  }

  stream._duplexState &= NOT_ACTIVE

  if (stream._writableState !== null) {
    stream._writableState.updateCallback()
  }

  if (stream._readableState !== null) {
    stream._readableState.updateCallback()
  }
}

function afterTransform(err, data) {
  if (data !== undefined && data !== null) this.push(data)
  this._writableState.afterWrite(err)
}

function newListener(name) {
  if (this._readableState !== null) {
    if (name === 'data') {
      this._duplexState |= READ_EMIT_DATA | READ_RESUMED_READ_AHEAD
      this._readableState.updateNextTick()
    }
    if (name === 'readable') {
      this._duplexState |= READ_EMIT_READABLE
      this._readableState.updateNextTick()
    }
  }

  if (this._writableState !== null) {
    if (name === 'drain') {
      this._duplexState |= WRITE_EMIT_DRAIN
      this._writableState.updateNextTick()
    }
  }
}

class Stream extends EventEmitter {
  constructor(opts) {
    super()

    this._duplexState = 0
    this._readableState = null
    this._writableState = null

    if (opts) {
      if (opts.open) this._open = opts.open
      if (opts.destroy) this._destroy = opts.destroy
      if (opts.predestroy) this._predestroy = opts.predestroy
      if (opts.signal) opts.signal.addEventListener('abort', abort.bind(this))
    }

    this.on('newListener', newListener)
  }

  _open(cb) {
    cb(null)
  }

  _destroy(cb) {
    cb(null)
  }

  _predestroy() {
    // does nothing
  }

  get readable() {
    return this._readableState !== null ? true : undefined
  }

  get writable() {
    return this._writableState !== null ? true : undefined
  }

  get destroyed() {
    return (this._duplexState & DESTROYED) !== 0
  }

  get destroying() {
    return (this._duplexState & DESTROY_STATUS) !== 0
  }

  destroy(err) {
    if ((this._duplexState & DESTROY_STATUS) === 0) {
      if (!err) err = StreamError.STREAM_DESTROYED()
      this._duplexState = (this._duplexState | DESTROYING) & NON_PRIMARY

      if (this._readableState !== null) {
        this._readableState.highWaterMark = 0
        this._readableState.error = err
      }

      if (this._writableState !== null) {
        this._writableState.highWaterMark = 0
        this._writableState.error = err
      }

      this._duplexState |= PREDESTROYING
      this._predestroy()
      this._duplexState &= NOT_PREDESTROYING

      if (this._readableState !== null) {
        this._readableState.updateNextTick()
      }

      if (this._writableState !== null) {
        this._writableState.updateNextTick()
      }
    }
  }
}

class Readable extends Stream {
  constructor(opts) {
    super(opts)

    this._duplexState |= OPENING | WRITE_DONE | READ_READ_AHEAD
    this._readableState = new ReadableState(this, opts)

    if (opts) {
      if (this._readableState.readAhead === false) this._duplexState &= READ_NO_READ_AHEAD
      if (opts.read) this._read = opts.read
      if (opts.eagerOpen) this._readableState.updateNextTick()
      if (opts.encoding) this.setEncoding(opts.encoding)
    }
  }

  static deferred(fn, opts) {
    const out = new PassThrough(opts)

    fn()
      .then((src) => {
        if (src === null) return out.end()
        if (out.destroying) return
        pipeline(src, out, noop)
      })
      .catch((err) => out.destroy(err))

    return out
  }

  setEncoding(encoding) {
    const dec = new TextDecoder(encoding)
    const map = this._readableState.map || echo
    this._readableState.map = mapOrSkip
    return this

    function mapOrSkip(data) {
      const next = dec.push(data)
      return next === '' && (data.byteLength !== 0 || dec.remaining > 0) ? null : map(next)
    }
  }

  _read(cb) {
    cb(null)
  }

  pipe(dest, cb) {
    this._readableState.updateNextTick()
    this._readableState.pipe(dest, cb)
    return dest
  }

  read() {
    this._readableState.updateNextTick()
    return this._readableState.read()
  }

  push(data) {
    this._readableState.updateNextTickIfOpen()
    return this._readableState.push(data)
  }

  unshift(data) {
    this._readableState.updateNextTickIfOpen()
    return this._readableState.unshift(data)
  }

  resume() {
    this._duplexState |= READ_RESUMED_READ_AHEAD
    this._readableState.updateNextTick()
    return this
  }

  pause() {
    this._duplexState &=
      this._readableState.readAhead === false ? READ_PAUSED_NO_READ_AHEAD : READ_PAUSED
    return this
  }

  static _fromAsyncIterator(ite, opts) {
    let destroy

    const rs = new Readable({
      ...opts,
      read(cb) {
        ite.next().then(push).then(cb.bind(null, null)).catch(cb)
      },
      predestroy() {
        destroy = ite.return()
      },
      destroy(cb) {
        if (!destroy) return cb(null)
        destroy.then(cb.bind(null, null)).catch(cb)
      }
    })

    return rs

    function push(data) {
      if (data.done) rs.push(null)
      else rs.push(data.value)
    }
  }

  static from(data, opts) {
    if (isReadStreamx(data)) return data
    if (data[asyncIterator]) return this._fromAsyncIterator(data[asyncIterator](), opts)
    if (!Array.isArray(data)) data = data === undefined ? [] : [data]

    let i = 0
    return new Readable({
      ...opts,
      read(cb) {
        this.push(i === data.length ? null : data[i++])
        cb(null)
      }
    })
  }

  static isBackpressured(rs) {
    return (
      (rs._duplexState & READ_BACKPRESSURE_STATUS) !== 0 ||
      rs._readableState.buffered >= rs._readableState.highWaterMark
    )
  }

  static isPaused(rs) {
    return (rs._duplexState & READ_RESUMED) === 0
  }

  [asyncIterator]() {
    const stream = this

    let error = null
    let promiseResolve = null
    let promiseReject = null

    this.on('error', (err) => {
      error = err
    })
    this.on('readable', onreadable)
    this.on('close', onclose)

    return {
      [asyncIterator]() {
        return this
      },
      next() {
        return new Promise(function (resolve, reject) {
          promiseResolve = resolve
          promiseReject = reject
          const data = stream.read()
          if (data !== null) ondata(data)
          else if ((stream._duplexState & DESTROYED) !== 0) ondata(null)
        })
      },
      return() {
        return destroy(null)
      },
      throw(err) {
        return destroy(err)
      }
    }

    function onreadable() {
      if (promiseResolve !== null) ondata(stream.read())
    }

    function onclose() {
      if (promiseResolve !== null) ondata(null)
    }

    function ondata(data) {
      if (promiseReject === null) return
      if (error) {
        promiseReject(error)
      } else if (data === null && (stream._duplexState & READ_DONE) === 0) {
        promiseReject(StreamError.STREAM_DESTROYED())
      } else {
        promiseResolve({ value: data, done: data === null })
      }
      promiseReject = promiseResolve = null
    }

    function destroy(err) {
      stream.destroy(err)
      return new Promise((resolve, reject) => {
        if (stream._duplexState & DESTROYED) return resolve({ value: undefined, done: true })
        stream.once('close', function () {
          if (err) reject(err)
          else resolve({ value: undefined, done: true })
        })
      })
    }
  }
}

class Writable extends Stream {
  constructor(opts) {
    super(opts)

    this._duplexState |= OPENING | READ_DONE
    this._writableState = new WritableState(this, opts)

    if (opts) {
      if (opts.writev) this._writev = opts.writev
      if (opts.write) this._write = opts.write
      if (opts.final) this._final = opts.final
      if (opts.eagerOpen) this._writableState.updateNextTick()
    }
  }

  cork() {
    this._duplexState |= WRITE_CORKED
  }

  uncork() {
    this._duplexState &= WRITE_NOT_CORKED
    this._writableState.updateNextTick()
  }

  _writev(batch, cb) {
    cb(null)
  }

  _write(data, cb) {
    this._writableState.autoBatch(data, cb)
  }

  _final(cb) {
    cb(null)
  }

  static isBackpressured(ws) {
    return (ws._duplexState & WRITE_BACKPRESSURE_STATUS) !== 0
  }

  static drained(ws) {
    if (ws.destroyed) return Promise.resolve(false)

    const state = ws._writableState
    const pending = isWritev(ws) ? Math.min(1, state.queue.length) : state.queue.length
    const writes = pending + (ws._duplexState & WRITE_WRITING ? 1 : 0)
    if (writes === 0) return Promise.resolve(true)

    if (state.drains === null) state.drains = []
    return new Promise((resolve) => {
      state.drains.push({ writes, resolve })
    })
  }

  write(data) {
    this._writableState.updateNextTick()
    return this._writableState.push(data)
  }

  end(data) {
    this._writableState.updateNextTick()
    this._writableState.end(data)
    return this
  }
}

class Duplex extends Readable {
  // and Writable
  constructor(opts) {
    super(opts)

    this._duplexState = OPENING | (this._duplexState & READ_READ_AHEAD)
    this._writableState = new WritableState(this, opts)

    if (opts) {
      if (opts.writev) this._writev = opts.writev
      if (opts.write) this._write = opts.write
      if (opts.final) this._final = opts.final
    }
  }

  cork() {
    this._duplexState |= WRITE_CORKED
  }

  uncork() {
    this._duplexState &= WRITE_NOT_CORKED
    this._writableState.updateNextTick()
  }

  _writev(batch, cb) {
    cb(null)
  }

  _write(data, cb) {
    this._writableState.autoBatch(data, cb)
  }

  _final(cb) {
    cb(null)
  }

  write(data) {
    this._writableState.updateNextTick()
    return this._writableState.push(data)
  }

  end(data) {
    this._writableState.updateNextTick()
    this._writableState.end(data)
    return this
  }
}

class Transform extends Duplex {
  constructor(opts) {
    super(opts)
    this._transformState = new TransformState(this)

    if (opts) {
      if (opts.transform) this._transform = opts.transform
      if (opts.flush) this._flush = opts.flush
    }
  }

  _write(data, cb) {
    if (this._readableState.buffered >= this._readableState.highWaterMark) {
      this._transformState.data = data
    } else {
      this._transform(data, this._transformState.afterTransform)
    }
  }

  _read(cb) {
    if (this._transformState.data !== null) {
      const data = this._transformState.data
      this._transformState.data = null
      cb(null)
      this._transform(data, this._transformState.afterTransform)
    } else {
      cb(null)
    }
  }

  destroy(err) {
    super.destroy(err)
    if (this._transformState.data !== null) {
      this._transformState.data = null
      this._transformState.afterTransform()
    }
  }

  _transform(data, cb) {
    cb(null, data)
  }

  _flush(cb) {
    cb(null)
  }

  _final(cb) {
    this._transformState.afterFinal = cb
    this._flush(transformAfterFlush.bind(this))
  }
}

class PassThrough extends Transform {}

function transformAfterFlush(err, data) {
  const cb = this._transformState.afterFinal
  if (err) return cb(err)

  if (data !== null && data !== undefined) this.push(data)
  this.push(null)
  cb(null)
}

function pipelinePromise(...streams) {
  return new Promise((resolve, reject) => {
    return pipeline(...streams, (err) => {
      if (err) return reject(err)
      resolve()
    })
  })
}

function pipeline(stream, ...streams) {
  const all = Array.isArray(stream) ? [...stream, ...streams] : [stream, ...streams]
  const done = all.length && typeof all[all.length - 1] === 'function' ? all.pop() : null

  if (all.length < 2) throw StreamError.BAD_ARGUMENT('Pipeline requires at least 2 streams')

  let src = all[0]
  let dest = null
  let error = null

  for (let i = 1; i < all.length; i++) {
    dest = all[i]

    if (isStreamx(src)) {
      src.pipe(dest, onerror)
    } else {
      errorHandle(src, true, i > 1, onerror)
      src.pipe(dest)
    }

    src = dest
  }

  if (done) {
    let fin = false

    const autoDestroy =
      isStreamx(dest) || !!(dest._writableState && dest._writableState.autoDestroy)

    dest.on('error', (err) => {
      if (error === null) error = err
    })

    dest.on('finish', () => {
      fin = true
      if (!autoDestroy) done(error)
    })

    if (autoDestroy) {
      dest.on('close', () => done(error || (fin ? null : StreamError.PREMATURE_CLOSE())))
    }
  }

  return dest

  function errorHandle(s, rd, wr, onerror) {
    s.on('error', onerror)
    s.on('close', onclose)

    function onclose() {
      if (rd && s._readableState && !s._readableState.ended) {
        return onerror(StreamError.PREMATURE_CLOSE())
      }
      if (wr && s._writableState && !s._writableState.ended) {
        return onerror(StreamError.PREMATURE_CLOSE())
      }
    }
  }

  function onerror(err) {
    if (!err || error) return
    error = err

    for (const s of all) {
      s.destroy(err)
    }
  }
}

function echo(s) {
  return s
}

function isStream(stream) {
  return !!stream._readableState || !!stream._writableState
}

function isStreamx(stream) {
  return typeof stream._duplexState === 'number' && isStream(stream)
}

function isEnding(stream) {
  return !!stream._readableState && stream._readableState.ending
}

function isEnded(stream) {
  return !!stream._readableState && stream._readableState.ended
}

function isFinishing(stream) {
  return !!stream._writableState && stream._writableState.ending
}

function isFinished(stream) {
  return !!stream._writableState && stream._writableState.ended
}

function getStreamError(stream, opts = {}) {
  const err =
    (stream._readableState && stream._readableState.error) ||
    (stream._writableState && stream._writableState.error)

  // avoid implicit errors by default
  return !opts.all && StreamError.isStreamDestroyed(err) ? null : err
}

function isReadStreamx(stream) {
  return isStreamx(stream) && stream.readable
}

function isDisturbed(stream) {
  return (
    (stream._duplexState & OPENING) !== OPENING ||
    (stream._duplexState & DESTROYING) === DESTROYING ||
    (stream._duplexState & ACTIVE_OR_TICKING) !== 0
  )
}

function isTypedArray(data) {
  return typeof data === 'object' && data !== null && typeof data.byteLength === 'number'
}

function defaultByteLength(data) {
  return isTypedArray(data) ? data.byteLength : 1024
}

function noop() {}

function abort() {
  this.destroy(StreamError.ABORTED())
}

function isWritev(s) {
  return s._writev !== Writable.prototype._writev && s._writev !== Duplex.prototype._writev
}

module.exports = {
  pipeline,
  pipelinePromise,
  isStream,
  isStreamx,
  isEnding,
  isEnded,
  isFinishing,
  isFinished,
  isDisturbed,
  getStreamError,
  Stream,
  Writable,
  Readable,
  Duplex,
  Transform,
  // Export PassThrough for compatibility with Node.js core's stream module
  PassThrough
}
module.exports = class StreamError extends Error {
  constructor(msg, code, fn = StreamError) {
    super(msg)

    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  static isStreamDestroyed(err) {
    return err && err.code === 'STREAM_DESTROYED'
  }

  static isPrematureClose(err) {
    return err && err.code === 'PREMATURE_CLOSE'
  }

  static isAborted(err) {
    return err && err.code === 'ABORTED'
  }

  static isBadArgument(err) {
    return err && err.code === 'BAD_ARGUMENT'
  }

  get name() {
    return 'StreamError'
  }

  static STREAM_DESTROYED() {
    return new StreamError('Stream was destroyed', 'STREAM_DESTROYED', StreamError.STREAM_DESTROYED)
  }

  static PREMATURE_CLOSE(msg = 'Premature close') {
    return new StreamError(msg, 'PREMATURE_CLOSE', StreamError.PREMATURE_CLOSE)
  }

  static ABORTED() {
    return new StreamError('Stream aborted', 'ABORTED', StreamError.ABORTED)
  }

  static BAD_ARGUMENT(msg = 'Bad argument') {
    return new StreamError(msg, 'BAD_ARGUMENT', StreamError.BAD_ARGUMENT)
  }
}
{
  "name": "streamx",
  "version": "2.28.0",
  "description": "An iteration of the Node.js core streams with a series of improvements",
  "main": "index.js",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./errors": {
      "types": "./lib/errors.d.ts",
      "default": "./lib/errors"
    }
  },
  "dependencies": {
    "events-universal": "^1.0.0",
    "fast-fifo": "^1.3.2",
    "text-decoder": "^1.1.0"
  },
  "devDependencies": {
    "b4a": "^1.6.6",
    "brittle": "^3.1.1",
    "end-of-stream": "^1.4.4",
    "lunte": "^1.8.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "runtime.d.ts",
    "lib"
  ],
  "scripts": {
    "format": "prettier . --write",
    "test": "brittle test/all.js && brittle-bare test/all.js",
    "lint": "prettier . --check && lunte"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/streamx.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/streamx/issues"
  },
  "homepage": "https://github.com/mafintosh/streamx"
}
const codecs = require('codecs')
const b = require('b4a')

const SEP = b.alloc(1)
const SEP_BUMPED = b.from([0x1])
const EMPTY = b.alloc(0)

module.exports = class SubEncoder {
  constructor (prefix, encoding, parent = null) {
    this.userEncoding = codecs(encoding)
    this.prefix = prefix != null ? createPrefix(prefix, parent) : null
    this.lt = this.prefix && b.concat([this.prefix.subarray(0, this.prefix.byteLength - 1), SEP_BUMPED])
  }

  _encodeRangeUser (r) {
    if (this.userEncoding.encodeRange) return this.userEncoding.encodeRange(r)

    const res = {}
    if (r.gt != null) res.gt = this.userEncoding.encode(r.gt)
    if (r.gte != null) res.gte = this.userEncoding.encode(r.gte)
    if (r.lte != null) res.lte = this.userEncoding.encode(r.lte)
    if (r.lt != null) res.lt = this.userEncoding.encode(r.lt)

    return res
  }

  _addPrefix (key) {
    return this.prefix ? b.concat([this.prefix, key]) : key
  }

  encode (key) {
    return this._addPrefix(this.userEncoding.encode(key))
  }

  encodeRange (range) {
    const r = this._encodeRangeUser(range)

    if (r.gt) r.gt = this._addPrefix(r.gt)
    else if (r.gte) r.gte = this._addPrefix(r.gte)
    else if (this.prefix) r.gte = this.prefix

    if (r.lt) r.lt = this._addPrefix(r.lt)
    else if (r.lte) r.lte = this._addPrefix(r.lte)
    else if (this.prefix) r.lt = this.lt

    return r
  }

  decode (key) {
    return this.userEncoding.decode(this.prefix ? key.subarray(this.prefix.byteLength) : key)
  }

  sub (prefix, encoding) {
    return new SubEncoder(prefix || EMPTY, compat(encoding), this.prefix)
  }
}

function createPrefix (prefix, parent) {
  prefix = typeof prefix === 'string' ? b.from(prefix) : prefix

  if (prefix && parent) return b.concat([parent, prefix, SEP])
  if (prefix) return b.concat([prefix, SEP])
  if (parent) return b.concat([parent, SEP])
  return SEP
}

function compat (enc) {
  if (enc && enc.keyEncoding) return enc.keyEncoding
  return enc
}
{
  "name": "sub-encoder",
  "version": "2.1.3",
  "description": "Generate sub encodings for key/value stores",
  "main": "index.js",
  "scripts": {
    "test": "standard && brittle test/*.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sub-encoder.git"
  },
  "keywords": [
    "kv-store",
    "encoding",
    "hyperbee"
  ],
  "author": "Andrew Osheroff <andrewosh@gmail.com>",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/sub-encoder/issues"
  },
  "homepage": "https://github.com/holepunchto/sub-encoder#readme",
  "devDependencies": {
    "brittle": "^3.1.1",
    "compact-encoding": "^2.12.0",
    "hyperbee": "^2.11.0",
    "hypercore": "^10.3.2",
    "index-encoder": "^3.0.0",
    "random-access-memory": "^6.0.0",
    "standard": "^17.0.0"
  },
  "dependencies": {
    "b4a": "^1.6.0",
    "codecs": "^3.1.0"
  }
}
const { Readable } = require('streamx')

module.exports = function (s, forks = 2) {
  const streams = new Array(forks)
  const status = new Array(forks).fill(true)

  let ended = false

  for (let i = 0; i < forks; i++) {
    streams[i] = new Readable({
      read (cb) {
        const check = !status[i]
        status[i] = true
        if (check && allReadable()) s.resume()
        cb(null)
      }
    })
  }

  s.on('end', function () {
    ended = true
    for (const stream of streams) stream.push(null)
  })

  s.on('error', function (err) {
    for (const stream of streams) stream.destroy(err)
  })

  s.on('close', function () {
    if (ended) return
    for (const stream of streams) stream.destroy()
  })

  s.on('data', function (data) {
    let needsPause = false
    for (let i = 0; i < streams.length; i++) {
      if (!(status[i] = streams[i].push(data))) {
        needsPause = true
      }
    }
    if (needsPause) s.pause()
  })

  return streams

  function allReadable () {
    for (let j = 0; j < status.length; j++) {
      if (!status[j]) return false
    }
    return true
  }
}
{
  "name": "teex",
  "version": "1.0.1",
  "description": "Turn a readable stream into multiple readable streamx streams",
  "main": "index.js",
  "dependencies": {
    "streamx": "^2.12.5"
  },
  "devDependencies": {
    "standard": "^14.3.4",
    "tape": "^5.0.1"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/teex.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/teex/issues"
  },
  "homepage": "https://github.com/mafintosh/teex"
}
const PassThroughDecoder = require('./lib/pass-through-decoder')
const UTF8Decoder = require('./lib/utf8-decoder')

module.exports = class TextDecoder {
  constructor(encoding = 'utf8') {
    this.encoding = normalizeEncoding(encoding)

    switch (this.encoding) {
      case 'utf8':
        this.decoder = new UTF8Decoder()
        break
      case 'utf16le':
      case 'base64':
        throw new Error('Unsupported encoding: ' + this.encoding)
      default:
        this.decoder = new PassThroughDecoder(this.encoding)
    }
  }

  get remaining() {
    return this.decoder.remaining
  }

  push(data) {
    if (typeof data === 'string') return data
    return this.decoder.decode(data)
  }

  // For Node.js compatibility
  write(data) {
    return this.push(data)
  }

  end(data) {
    let result = ''
    if (data) result = this.push(data)
    result += this.decoder.flush()
    return result
  }
}

function normalizeEncoding(encoding) {
  encoding = encoding.toLowerCase()

  switch (encoding) {
    case 'utf8':
    case 'utf-8':
      return 'utf8'
    case 'ucs2':
    case 'ucs-2':
    case 'utf16le':
    case 'utf-16le':
      return 'utf16le'
    case 'latin1':
    case 'binary':
      return 'latin1'
    case 'base64':
    case 'ascii':
    case 'hex':
      return encoding
    default:
      throw new Error('Unknown encoding: ' + encoding)
  }
}
const b4a = require('b4a')

module.exports = class PassThroughDecoder {
  constructor(encoding) {
    this.encoding = encoding
  }

  get remaining() {
    return 0
  }

  decode(data) {
    return b4a.toString(data, this.encoding)
  }

  flush() {
    return ''
  }
}
const b4a = require('b4a')

/**
 * https://encoding.spec.whatwg.org/#utf-8-decoder
 */
module.exports = class UTF8Decoder {
  constructor() {
    this._reset()
  }

  get remaining() {
    return this.bytesSeen
  }

  decode(data) {
    if (data.byteLength === 0) return ''

    if (this.bytesNeeded === 0 && trailingIncomplete(data, 0) === 0) {
      this.bytesSeen = trailingBytesSeen(data)
      return b4a.toString(data, 'utf8')
    }

    let result = ''
    let start = 0

    if (this.bytesNeeded > 0) {
      while (start < data.byteLength) {
        const byte = data[start]

        if (byte < this.lowerBoundary || byte > this.upperBoundary) {
          result += '\ufffd'
          this._reset()
          break
        }

        this.lowerBoundary = 0x80
        this.upperBoundary = 0xbf
        this.codePoint = (this.codePoint << 6) | (byte & 0x3f)
        this.bytesSeen++
        start++

        if (this.bytesSeen === this.bytesNeeded) {
          result += String.fromCodePoint(this.codePoint)
          this._reset()
          break
        }
      }

      if (this.bytesNeeded > 0) return result
    }

    const trailing = trailingIncomplete(data, start)
    const end = data.byteLength - trailing

    if (end > start) result += b4a.toString(data, 'utf8', start, end)

    for (let i = end; i < data.byteLength; i++) {
      const byte = data[i]

      if (this.bytesNeeded === 0) {
        if (byte <= 0x7f) {
          this.bytesSeen = 0
          result += String.fromCharCode(byte)
        } else if (byte >= 0xc2 && byte <= 0xdf) {
          this.bytesNeeded = 2
          this.bytesSeen = 1
          this.codePoint = byte & 0x1f
        } else if (byte >= 0xe0 && byte <= 0xef) {
          if (byte === 0xe0) this.lowerBoundary = 0xa0
          else if (byte === 0xed) this.upperBoundary = 0x9f
          this.bytesNeeded = 3
          this.bytesSeen = 1
          this.codePoint = byte & 0xf
        } else if (byte >= 0xf0 && byte <= 0xf4) {
          if (byte === 0xf0) this.lowerBoundary = 0x90
          else if (byte === 0xf4) this.upperBoundary = 0x8f
          this.bytesNeeded = 4
          this.bytesSeen = 1
          this.codePoint = byte & 0x7
        } else {
          this.bytesSeen = 1
          result += '\ufffd'
        }

        continue
      }

      if (byte < this.lowerBoundary || byte > this.upperBoundary) {
        result += '\ufffd'
        i--
        this._reset()

        continue
      }

      this.lowerBoundary = 0x80
      this.upperBoundary = 0xbf

      this.codePoint = (this.codePoint << 6) | (byte & 0x3f)
      this.bytesSeen++

      if (this.bytesSeen === this.bytesNeeded) {
        result += String.fromCodePoint(this.codePoint)
        this._reset()
      }
    }

    return result
  }

  flush() {
    const result = this.bytesNeeded > 0 ? '\ufffd' : ''
    this._reset()
    return result
  }

  _reset() {
    this.codePoint = 0
    this.bytesNeeded = 0
    this.bytesSeen = 0
    this.lowerBoundary = 0x80
    this.upperBoundary = 0xbf
  }
}

function trailingIncomplete(data, start) {
  const len = data.byteLength
  if (len <= start) return 0

  const limit = Math.max(start, len - 4)

  let i = len - 1
  while (i > limit && (data[i] & 0xc0) === 0x80) i--

  if (i < start) return 0

  const byte = data[i]

  let needed
  if (byte <= 0x7f) return 0
  if (byte >= 0xc2 && byte <= 0xdf) needed = 2
  else if (byte >= 0xe0 && byte <= 0xef) needed = 3
  else if (byte >= 0xf0 && byte <= 0xf4) needed = 4
  else return 0

  const available = len - i
  return available < needed ? available : 0
}

function trailingBytesSeen(data) {
  const len = data.byteLength
  if (len === 0) return 0

  const last = data[len - 1]

  if (last <= 0x7f) return 0
  if ((last & 0xc0) !== 0x80) return 1

  const limit = Math.max(0, len - 4)

  let i = len - 2
  while (i >= limit && (data[i] & 0xc0) === 0x80) i--

  if (i < 0) return 1

  const first = data[i]

  let needed
  if (first >= 0xc2 && first <= 0xdf) needed = 2
  else if (first >= 0xe0 && first <= 0xef) needed = 3
  else if (first >= 0xf0 && first <= 0xf4) needed = 4
  else return 1

  if (len - i !== needed) return 1

  if (needed >= 3) {
    const second = data[i + 1]
    if (first === 0xe0 && second < 0xa0) return 1
    if (first === 0xed && second > 0x9f) return 1
    if (first === 0xf0 && second < 0x90) return 1
    if (first === 0xf4 && second > 0x8f) return 1
  }

  return 0
}
{
  "name": "text-decoder",
  "version": "1.2.7",
  "description": "Streaming text decoder that preserves multibyte Unicode characters",
  "exports": {
    "./package": "./package.json",
    ".": "./index.js"
  },
  "files": [
    "index.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/text-decoder.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/text-decoder/issues"
  },
  "homepage": "https://github.com/holepunchto/text-decoder#readme",
  "dependencies": {
    "b4a": "^1.6.4"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  }
}
module.exports = class TimeOrderedSet {
  constructor () {
    this.oldest = null
    this.latest = null
    this.length = 0
  }

  has (node) {
    return !!(node.next || node.prev) || node === this.oldest
  }

  add (node) {
    if (this.has(node)) this.remove(node)

    if (!this.latest && !this.oldest) {
      this.latest = this.oldest = node
      node.prev = node.next = null
    } else {
      this.latest.next = node
      node.prev = this.latest
      node.next = null
      this.latest = node
    }

    this.length++

    return node
  }

  remove (node) {
    if (!this.has(node)) return node

    if (this.oldest !== node && this.latest !== node) {
      node.prev.next = node.next
      node.next.prev = node.prev
    } else {
      if (this.oldest === node) {
        this.oldest = node.next
        if (this.oldest) this.oldest.prev = null
      }
      if (this.latest === node) {
        this.latest = node.prev
        if (this.latest) this.latest.next = null
      }
    }

    node.next = node.prev = null
    this.length--

    return node
  }

  toArray ({ limit = Infinity, reverse = false } = {}) {
    const list = []

    if (reverse) {
      let node = this.latest
      while (node && limit--) {
        list.push(node)
        node = node.prev
      }
    } else {
      let node = this.oldest
      while (node && limit--) {
        list.push(node)
        node = node.next
      }
    }

    return list
  }
}
{
  "name": "time-ordered-set",
  "version": "2.0.1",
  "description": "Efficiently maintain a set of nodes ordered by the time they were added to the set",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "devDependencies": {
    "brittle": "^3.0.0",
    "standard": "^17.1.2"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/time-ordered-set.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/time-ordered-set/issues"
  },
  "homepage": "https://github.com/mafintosh/time-ordered-set"
}
module.exports = class TimerBrowser {
  constructor (ms, fn, ctx = null, interval = false) {
    this.ms = ms
    this.ontimeout = fn
    this.context = ctx || null
    this.interval = interval
    this.done = false

    this._timer = interval
      ? setInterval(callInterval, ms, this)
      : setTimeout(callTimeout, ms, this)
  }

  unref () {}

  ref () {}

  refresh () {
    if (this.done) return

    if (this.interval) {
      clearInterval(this._timer)
      this._timer = setInterval(callInterval, this.ms, this)
    } else {
      clearTimeout(this._timer)
      this._timer = setTimeout(callTimeout, this.ms, this)
    }
  }

  destroy () {
    this.done = true
    this.ontimeout = null

    if (this.interval) clearInterval(this._timer)
    else clearTimeout(this._timer)
  }

  static once (ms, fn, ctx) {
    return new this(ms, fn, ctx, false)
  }

  static on (ms, fn, ctx) {
    return new this(ms, fn, ctx, true)
  }
}

function callTimeout (self) {
  self.done = true
  self.ontimeout.call(self.context)
}

function callInterval (self) {
  self.ontimeout.call(self.context)
}
module.exports = isNode()
  ? require('./node')
  : require('./browser')

function isNode () {
  const to = setTimeout(function () {}, 1000)
  clearTimeout(to)
  return !!to.refresh
}
module.exports = class Timer {
  constructor (ms, fn, ctx = null, interval = false) {
    this.ms = ms
    this.ontimeout = fn
    this.context = ctx
    this.interval = interval
    this.done = false

    this._timer = interval
      ? setInterval(callInterval, ms, this)
      : setTimeout(callTimeout, ms, this)
  }

  unref () {
    this._timer.unref()
  }

  ref () {
    this._timer.ref()
  }

  refresh () {
    if (this.done !== true) this._timer.refresh()
  }

  destroy () {
    this.done = true
    this.ontimeout = null
    if (this.interval) clearInterval(this._timer)
    else clearTimeout(this._timer)
  }

  static once (ms, fn, ctx) {
    return new this(ms, fn, ctx, false)
  }

  static on (ms, fn, ctx) {
    return new this(ms, fn, ctx, true)
  }
}

function callTimeout (self) {
  self.done = true
  self.ontimeout.call(self.context)
}

function callInterval (self) {
  self.ontimeout.call(self.context)
}
{
  "name": "timeout-refresh",
  "version": "2.0.1",
  "description": "Efficiently refresh a timer",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^16.0.4",
    "tape": "^5.5.2"
  },
  "browser": "./browser.js",
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/timeout-refresh.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/timeout-refresh/issues"
  },
  "homepage": "https://github.com/mafintosh/timeout-refresh"
}
const b4a = require('b4a')

module.exports = class BufferMap {
  constructor (other) {
    this.m = other ? new Map([...other.m]) : new Map()
  }

  get size () {
    return this.m.size
  }

  get (key) {
    if (b4a.isBuffer(key)) key = b4a.toString(key, 'hex')
    return this.m.get(key)
  }

  set (key, value) {
    if (b4a.isBuffer(key)) key = b4a.toString(key, 'hex')
    return this.m.set(key, value)
  }

  delete (key) {
    if (b4a.isBuffer(key)) key = b4a.toString(key, 'hex')
    return this.m.delete(key)
  }

  has (key) {
    if (b4a.isBuffer(key)) key = b4a.toString(key, 'hex')
    return this.m.has(key)
  }

  * [Symbol.iterator] () {
    for (const [key, value] of this.m) {
      yield [b4a.from(key, 'hex'), value]
    }
  }

  * keys () {
    for (const key of this.m.keys()) {
      yield b4a.from(key, 'hex')
    }
  }

  values () {
    return this.m.values()
  }

  clear () {
    return this.m.clear()
  }
}
{
  "name": "tiny-buffer-map",
  "version": "1.1.1",
  "description": "A very simple map for Buffers",
  "main": "index.js",
  "scripts": {
    "test": "brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/andrewosh/tiny-buffer-map.git"
  },
  "keywords": [
    "buffer",
    "map"
  ],
  "author": "Andrew Osheroff <andrewosh@gmail.com>",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/andrewosh/tiny-buffer-map/issues"
  },
  "homepage": "https://github.com/andrewosh/tiny-buffer-map#readme",
  "dependencies": {
    "b4a": "^1.6.0"
  },
  "devDependencies": {
    "brittle": "^3.0.4"
  }
}
require.addon = require('require-addon')

module.exports = require.addon('.', __filename)
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

const v4Seg = '(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])'
const v4Str = `(${v4Seg}[.]){3}${v4Seg}`
const IPv4Pattern = new RegExp(`^${v4Str}$`)

const v6Seg = '(?:[0-9a-fA-F]{1,4})'
const IPv6Pattern = new RegExp(
  '^(' +
    `(?:${v6Seg}:){7}(?:${v6Seg}|:)|` +
    `(?:${v6Seg}:){6}(?:${v4Str}|:${v6Seg}|:)|` +
    `(?:${v6Seg}:){5}(?::${v4Str}|(:${v6Seg}){1,2}|:)|` +
    `(?:${v6Seg}:){4}(?:(:${v6Seg}){0,1}:${v4Str}|(:${v6Seg}){1,3}|:)|` +
    `(?:${v6Seg}:){3}(?:(:${v6Seg}){0,2}:${v4Str}|(:${v6Seg}){1,4}|:)|` +
    `(?:${v6Seg}:){2}(?:(:${v6Seg}){0,3}:${v4Str}|(:${v6Seg}){1,5}|:)|` +
    `(?:${v6Seg}:){1}(?:(:${v6Seg}){0,4}:${v4Str}|(:${v6Seg}){1,6}|:)|` +
    `(?::((?::${v6Seg}){0,5}:${v4Str}|(?::${v6Seg}){1,7}|:))` +
    ')(%[0-9a-zA-Z-.:]{1,})?$'
)

const isIPv4 = (exports.isIPv4 = function isIPv4(host) {
  return IPv4Pattern.test(host)
})

const isIPv6 = (exports.isIPv6 = function isIPv6(host) {
  return IPv6Pattern.test(host)
})

exports.isIP = function isIP(host) {
  if (isIPv4(host)) return 4
  if (isIPv6(host)) return 6
  return 0
}
const events = require('events')
const b4a = require('b4a')
const binding = require('../binding')

module.exports = class NetworkInterfaces extends events.EventEmitter {
  constructor(udx) {
    super()

    this._handle = b4a.alloc(binding.sizeof_udx_napi_interface_event_t)
    this._watching = false
    this._destroying = null

    binding.udx_napi_interface_event_init(
      udx._handle,
      this._handle,
      this,
      this._onevent,
      this._onclose
    )

    this.interfaces = binding.udx_napi_interface_event_get_addrs(this._handle)
  }

  _onclose() {
    this.emit('close')
  }

  _onevent() {
    this.interfaces = binding.udx_napi_interface_event_get_addrs(this._handle)

    this.emit('change', this.interfaces)
  }

  watch() {
    if (this._watching) return this
    this._watching = true

    binding.udx_napi_interface_event_start(this._handle)

    return this
  }

  unwatch() {
    if (!this._watching) return this
    this._watching = false

    binding.udx_napi_interface_event_stop(this._handle)

    return this
  }

  async destroy() {
    if (this._destroying) return this._destroying
    this._destroying = events.once(this, 'close')

    binding.udx_napi_interface_event_close(this._handle)

    return this._destroying
  }

  [Symbol.iterator]() {
    return this.interfaces[Symbol.iterator]()
  }
}
const events = require('events')
const b4a = require('b4a')
const binding = require('../binding')
const ip = require('./ip')

module.exports = class UDXSocket extends events.EventEmitter {
  constructor(udx, opts = {}) {
    super()

    this.udx = udx

    this._handle = b4a.alloc(binding.sizeof_udx_napi_socket_t)
    this._inited = false
    this._host = null
    this._family = 0
    this._ipv6Only = opts.ipv6Only === true
    this._reuseAddress = opts.reuseAddress === true
    this._port = 0
    this._reqs = []
    this._free = []
    this._closing = null
    this._closed = false

    this._view64 = new BigUint64Array(
      this._handle.buffer,
      this._handle.byteOffset,
      this._handle.byteLength >> 3
    )

    this.streams = new Set()

    this.userData = null
  }

  get bound() {
    return this._port !== 0
  }

  get closing() {
    return this._closing !== null
  }

  get idle() {
    return this.streams.size === 0
  }

  get busy() {
    return this.streams.size > 0
  }

  get bytesTransmitted() {
    if (this._inited !== true) return 0
    return Number(this._view64[binding.offsetof_udx_socket_t_bytes_tx >> 3])
  }

  get packetsTransmitted() {
    if (this._inited !== true) return 0
    return Number(this._view64[binding.offsetof_udx_socket_t_packets_tx >> 3])
  }

  get bytesReceived() {
    if (this._inited !== true) return 0
    return Number(this._view64[binding.offsetof_udx_socket_t_bytes_rx >> 3])
  }

  get packetsReceived() {
    if (this._inited !== true) return 0
    return Number(this._view64[binding.offsetof_udx_socket_t_packets_rx >> 3])
  }

  get packetsDroppedByKernel() {
    if (this._inited !== true) return 0
    return Number(this._view64[binding.offsetof_udx_socket_t_packets_dropped_by_kernel >> 3])
  }

  toJSON() {
    return {
      bound: this.bound,
      closing: this.closing,
      streams: this.streams.size,
      address: this.address(),
      ipv6Only: this._ipv6Only,
      reuseAddress: this._reuseAddress,
      idle: this.idle,
      busy: this.busy
    }
  }

  _init() {
    if (this._inited) return

    binding.udx_napi_socket_init(
      this.udx._handle,
      this._handle,
      this,
      this._onsend,
      this._onmessage,
      this._onclose,
      this._reallocMessage
    )

    this._inited = true
  }

  _onsend(id, err) {
    const req = this._reqs[id]

    const onflush = req.onflush

    req.buffer = null
    req.onflush = null

    this._free.push(id)

    onflush(err >= 0)

    // gc the free list
    if (this._free.length >= 16 && this._free.length === this._reqs.length) {
      this._free = []
      this._reqs = []
    }
  }

  _onmessage(len, port, host, family) {
    this.emit('message', this.udx._consumeMessage(len), { host, family, port })
    return this.udx._buffer
  }

  _onclose() {
    this.emit('close')
  }

  _reallocMessage() {
    return this.udx._reallocMessage()
  }

  _onidle() {
    this.emit('idle')
  }

  _onbusy() {
    this.emit('busy')
  }

  _addStream(stream) {
    if (this.streams.has(stream)) return false
    this.streams.add(stream)
    if (this.streams.size === 1) this._onbusy()
    return true
  }

  _removeStream(stream) {
    if (!this.streams.has(stream)) return false
    this.streams.delete(stream)
    const closed = this._closeMaybe()
    if (this.idle && !closed) this._onidle()
    return true
  }

  address() {
    if (!this.bound) return null
    return { host: this._host, family: this._family, port: this._port }
  }

  bind(port, host) {
    if (this.bound) throw new Error('Already bound')
    if (this.closing) throw new Error('Socket is closed')

    if (!port) port = 0

    let flags = 0
    if (this._ipv6Only) flags |= binding.UV_UDP_IPV6ONLY
    if (this._reuseAddress) flags |= binding.UV_UDP_REUSEADDR

    let family

    if (host) {
      family = ip.isIP(host)
      if (!family) throw new Error(`${host} is not a valid IP address`)

      if (!this._inited) this._init()

      this._port = binding.udx_napi_socket_bind(this._handle, port, host, family, flags)
    } else {
      if (!this._inited) this._init()

      try {
        host = '::'
        family = 6
        this._port = binding.udx_napi_socket_bind(this._handle, port, host, family, flags)
      } catch {
        host = '0.0.0.0'
        family = 4
        this._port = binding.udx_napi_socket_bind(this._handle, port, host, family, flags)
      }
    }

    this._host = host
    this._family = family

    this.emit('listening')
  }

  async close() {
    if (this._closing) return this._closing
    this._closing = new Promise((resolve) => this.once('close', resolve))
    this._closeMaybe()
    return this._closing
  }

  _closeMaybe() {
    if (this._closed || this._closing === null) return this._closed

    if (!this._inited) {
      this._closed = true
      this.emit('close')
      return true
    }

    if (this.idle) {
      binding.udx_napi_socket_close(this._handle)
      this._closed = true
    }

    return this._closed
  }

  setTTL(ttl) {
    if (!this._inited) throw new Error('Socket not active')
    binding.udx_napi_socket_set_ttl(this._handle, ttl)
  }

  getRecvBufferSize() {
    if (!this._inited) throw new Error('Socket not active')
    return binding.udx_napi_socket_get_recv_buffer_size(this._handle)
  }

  setRecvBufferSize(size) {
    if (!this._inited) throw new Error('Socket not active')
    return binding.udx_napi_socket_set_recv_buffer_size(this._handle, size)
  }

  getSendBufferSize() {
    if (!this._inited) throw new Error('Socket not active')
    return binding.udx_napi_socket_get_send_buffer_size(this._handle)
  }

  setSendBufferSize(size) {
    if (!this._inited) throw new Error('Socket not active')
    return binding.udx_napi_socket_set_send_buffer_size(this._handle, size)
  }

  addMembership(group, ifaceAddress) {
    if (!this._inited) throw new Error('Socket not active')
    return binding.udx_napi_socket_set_membership(this._handle, group, ifaceAddress || '', true)
  }

  dropMembership(group, ifaceAddress) {
    if (!this._inited) throw new Error('Socket not active')
    return binding.udx_napi_socket_set_membership(this._handle, group, ifaceAddress || '', false)
  }

  async send(buffer, port, host, ttl) {
    if (this.closing) return false

    if (!host) host = '127.0.0.1'

    const family = ip.isIP(host)
    if (!family) throw new Error(`${host} is not a valid IP address`)

    if (!this.bound) this.bind(0)

    const id = this._allocSend()
    const req = this._reqs[id]

    req.buffer = buffer

    const promise = new Promise((resolve) => {
      req.onflush = resolve
    })

    binding.udx_napi_socket_send_ttl(
      this._handle,
      req.handle,
      id,
      buffer,
      port,
      host,
      family,
      ttl || 0
    )

    return promise
  }

  trySend(buffer, port, host, ttl) {
    if (this.closing) return

    if (!host) host = '127.0.0.1'

    const family = ip.isIP(host)
    if (!family) throw new Error(`${host} is not a valid IP address`)

    if (!this.bound) this.bind(0)

    const id = this._allocSend()
    const req = this._reqs[id]

    req.buffer = buffer
    req.onflush = noop

    binding.udx_napi_socket_send_ttl(
      this._handle,
      req.handle,
      id,
      buffer,
      port,
      host,
      family,
      ttl || 0
    )
  }

  _allocSend() {
    if (this._free.length > 0) return this._free.pop()
    const handle = b4a.allocUnsafe(binding.sizeof_udx_socket_send_t)
    return this._reqs.push({ handle, buffer: null, onflush: null }) - 1
  }
}

function noop() {}
const streamx = require('streamx')
const b4a = require('b4a')
const binding = require('../binding')
const ip = require('./ip')

const MAX_PACKET = 2048
const BUFFER_SIZE = 65536 + MAX_PACKET

module.exports = class UDXStream extends streamx.Duplex {
  constructor(udx, id, opts = {}) {
    super({ mapWritable: toBuffer, eagerOpen: true })

    this.udx = udx
    this.socket = null

    this._handle = b4a.alloc(binding.sizeof_udx_napi_stream_t)
    this._view = new Uint32Array(
      this._handle.buffer,
      this._handle.byteOffset,
      this._handle.byteLength >> 2
    )
    this._view16 = new Uint16Array(
      this._handle.buffer,
      this._handle.byteOffset,
      this._handle.byteLength >> 1
    )
    this._view64 = new BigUint64Array(
      this._handle.buffer,
      this._handle.byteOffset,
      this._handle.byteLength >> 3
    )

    this._wreqs = []
    this._wfree = []

    this._sreqs = []
    this._sfree = []
    this._closed = false

    this._flushing = 0
    this._flushes = []

    this._buffer = null
    this._reallocData()

    this._onwrite = null
    this._ondestroy = null
    this._firewall = opts.firewall || firewallAll

    this._remoteChanging = null
    this._previousSocket = null

    this.id = id
    this.remoteId = 0
    this.remoteHost = null
    this.remoteFamily = 0
    this.remotePort = 0

    this.userData = null

    binding.udx_napi_stream_init(
      this.udx._handle,
      this._handle,
      id,
      opts.framed ? 1 : 0,
      this,
      this._ondata,
      this._onend,
      this._ondrain,
      this._onack,
      this._onsend,
      this._onmessage,
      this._onclose,
      this._onfirewall,
      this._onremotechanged,
      this._reallocData,
      this._reallocMessage
    )

    if (opts.seq) binding.udx_napi_stream_set_seq(this._handle, opts.seq)

    binding.udx_napi_stream_recv_start(this._handle, this._buffer)
  }

  get connected() {
    return this.socket !== null
  }

  get mtu() {
    return this._view16[binding.offsetof_udx_stream_t_mtu >> 1]
  }

  get rtt() {
    return this._view[binding.offsetof_udx_stream_t_srtt >> 2]
  }

  get cwnd() {
    return this._view[binding.offsetof_udx_stream_t_cwnd >> 2]
  }

  get rtoCount() {
    return this._view16[binding.offsetof_udx_stream_t_rto_count >> 1]
  }

  get retransmits() {
    return this._view16[binding.offsetof_udx_stream_t_retransmit_count >> 1]
  }

  get bbrState() {
    const view = new Uint8Array(
      this._handle.buffer,
      this._handle.byteOffset,
      this._handle.byteLength
    )
    return view[binding.offsetof_udx_stream_t_bbr_state]
  }

  get bbrBandwidth() {
    return binding.udx_napi_stream_get_bw(this._handle)
  }

  get fastRecoveries() {
    return this._view16[binding.offsetof_udx_stream_t_fast_recovery_count >> 1]
  }

  get inflight() {
    return this._view[binding.offsetof_udx_stream_t_inflight >> 2]
  }

  get bytesTransmitted() {
    return Number(this._view64[binding.offsetof_udx_stream_t_bytes_tx >> 3])
  }

  get packetsTransmitted() {
    return Number(this._view64[binding.offsetof_udx_stream_t_packets_tx >> 3])
  }

  get bytesReceived() {
    return Number(this._view64[binding.offsetof_udx_stream_t_bytes_rx >> 3])
  }

  get packetsReceived() {
    return Number(this._view64[binding.offsetof_udx_stream_t_packets_rx >> 3])
  }

  get localHost() {
    return this.socket ? this.socket.address().host : null
  }

  get localFamily() {
    return this.socket ? this.socket.address().family : 0
  }

  get localPort() {
    return this.socket ? this.socket.address().port : 0
  }

  setInteractive(bool) {
    if (!this._closed) return
    binding.udx_napi_stream_set_mode(this._handle, bool ? 0 : 1)
  }

  connect(socket, remoteId, port, host, opts = {}) {
    if (this._closed) return

    if (this.connected) throw new Error('Already connected')
    if (socket.closing) throw new Error('Socket is closed')

    if (typeof host === 'object') {
      opts = host
      host = null
    }

    if (!host) host = '127.0.0.1'

    const family = ip.isIP(host)
    if (!family) throw new Error(`${host} is not a valid IP address`)
    if (!(port > 0 && port < 65536)) throw new Error(`${port} is not a valid port`)

    if (!socket.bound) socket.bind(0)

    this.remoteId = remoteId
    this.remotePort = port
    this.remoteHost = host
    this.remoteFamily = family
    this.socket = socket

    if (opts.ack) binding.udx_napi_stream_set_ack(this._handle, opts.ack)

    binding.udx_napi_stream_connect(this._handle, socket._handle, remoteId, port, host, family)

    this.socket._addStream(this)

    this.emit('connect')
  }

  changeRemote(socket, remoteId, port, host) {
    if (this._remoteChanging) throw new Error('Remote already changing')

    if (!this.connected) throw new Error('Not yet connected')
    if (socket.closing) throw new Error('Socket is closed')

    if (this.socket.udx !== socket.udx) {
      throw new Error('Cannot change to a socket on another UDX instance')
    }

    if (!host) host = '127.0.0.1'

    const family = ip.isIP(host)
    if (!family) throw new Error(`${host} is not a valid IP address`)
    if (!(port > 0 && port < 65536)) throw new Error(`${port} is not a valid port`)

    if (this.socket !== socket) this._previousSocket = this.socket

    this.remoteId = remoteId
    this.remotePort = port
    this.remoteHost = host
    this.remoteFamily = family
    this.socket = socket

    this._remoteChanging = new Promise((resolve, reject) => {
      const onchanged = () => {
        this.off('close', onclose)
        resolve()
      }

      const onclose = () => {
        this.off('remote-changed', onchanged)
        reject(new Error('Stream is closed'))
      }

      this.once('remote-changed', onchanged).once('close', onclose)
    })

    binding.udx_napi_stream_change_remote(
      this._handle,
      socket._handle,
      remoteId,
      port,
      host,
      family
    )

    this.socket._addStream(this)

    return this._remoteChanging
  }

  relayTo(destination) {
    if (this._closed) return

    binding.udx_napi_stream_relay_to(this._handle, destination._handle)
  }

  async send(buffer) {
    if (!this.connected || this._closed) return false

    const id = this._allocSend()
    const req = this._sreqs[id]

    req.buffer = buffer

    const promise = new Promise((resolve) => {
      req.onflush = resolve
    })

    binding.udx_napi_stream_send(this._handle, req.handle, id, buffer)

    return promise
  }

  trySend(buffer) {
    if (!this.connected || this._closed) return

    const id = this._allocSend()
    const req = this._sreqs[id]

    req.buffer = buffer
    req.onflush = noop

    binding.udx_napi_stream_send(this._handle, req.handle, id, buffer)
  }

  async flush() {
    if ((await streamx.Writable.drained(this)) === false) return false
    if (this.destroying) return false

    const missing = this._wreqs.length - this._wfree.length
    if (missing === 0) return true

    return new Promise((resolve) => {
      this._flushes.push({ flush: this._flushing++, missing, resolve })
    })
  }

  toJSON() {
    return {
      id: this.id,
      connected: this.connected,
      destroying: this.destroying,
      destroyed: this.destroyed,
      remoteId: this.remoteId,
      remoteHost: this.remoteHost,
      remoteFamily: this.remoteFamily,
      remotePort: this.remotePort,
      mtu: this.mtu,
      rtt: this.rtt,
      cwnd: this.cwnd,
      inflight: this.inflight,
      socket: this.socket ? this.socket.toJSON() : null
    }
  }

  _read(cb) {
    cb(null)
  }

  _writeContinue(err) {
    if (this._onwrite === null) return
    const cb = this._onwrite
    this._onwrite = null
    cb(err)
  }

  _destroyContinue(err) {
    if (this._ondestroy === null) return
    const cb = this._ondestroy
    this._ondestroy = null
    cb(err)
  }

  _writev(buffers, cb) {
    if (!this.connected) {
      throw customError('Writing while not connected not currently supported', 'ERR_ASSERTION')
    }

    let drained = true

    if (buffers.length === 1) {
      const id = this._allocWrite(1)
      const req = this._wreqs[id]

      req.flush = this._flushing
      req.buffer = buffers[0]

      drained = binding.udx_napi_stream_write(this._handle, req.handle, id, req.buffer) !== 0
    } else {
      const id = this._allocWrite(nextBatchSize(buffers.length))
      const req = this._wreqs[id]

      req.flush = this._flushing
      req.buffers = buffers

      drained = binding.udx_napi_stream_writev(this._handle, req.handle, id, req.buffers) !== 0
    }

    if (drained) cb(null)
    else this._onwrite = cb
  }

  _final(cb) {
    const id = this._allocWrite(1)
    const req = this._wreqs[id]

    req.flush = this._flushes
    req.buffer = b4a.allocUnsafe(0)

    const drained =
      binding.udx_napi_stream_write_end(this._handle, req.handle, id, req.buffer) !== 0

    if (drained) cb(null)
    else this._onwrite = cb
  }

  _predestroy() {
    if (!this._closed) binding.udx_napi_stream_destroy(this._handle)
    this._closed = true
    this._writeContinue(null)
  }

  _destroy(cb) {
    if (this.connected) this._ondestroy = cb
    else cb(null)
  }

  _ondata(read) {
    this.push(this._consumeData(read))
    return this._buffer
  }

  _onend(read) {
    if (read > 0) this.push(this._consumeData(read))
    this.push(null)
  }

  _ondrain() {
    this._writeContinue(null)
  }

  _flushAck(flush) {
    for (let i = this._flushes.length - 1; i >= 0; i--) {
      const f = this._flushes[i]
      if (f.flush < flush) break
      f.missing--
    }

    while (this._flushes.length > 0 && this._flushes[0].missing === 0) {
      this._flushes.shift().resolve(true)
    }
  }

  _onack(id) {
    const req = this._wreqs[id]

    req.buffers = req.buffer = null
    this._wfree.push(id)

    if (this._flushes.length > 0) this._flushAck(req.flush)

    // gc the free list
    if (this._wfree.length >= 64 && this._wfree.length === this._wreqs.length) {
      this._wfree = []
      this._wreqs = []
    }
  }

  _onsend(id, err) {
    const req = this._sreqs[id]

    const onflush = req.onflush

    req.buffer = null
    req.onflush = null

    this._sfree.push(id)

    onflush(err >= 0)

    // gc the free list
    if (this._sfree.length >= 16 && this._sfree.length === this._sreqs.length) {
      this._sfree = []
      this._sreqs = []
    }
  }

  _onmessage(len) {
    this.emit('message', this.udx._consumeMessage(len))
    return this.udx._buffer
  }

  _onclose(err) {
    this._closed = true

    if (this.socket) {
      this.socket._removeStream(this)
      this.socket = null
    }

    if (this._previousSocket) {
      this._previousSocket._removeStream(this)
      this._previousSocket = null
    }

    // no error, we don't need to do anything
    if (!err) return this._destroyContinue(null)

    if (this._ondestroy === null) this.destroy(err)
    else this._destroyContinue(err)
  }

  _onfirewall(socket, port, host, family) {
    if (port <= 0 || port > 65535) return 1
    return this._firewall(socket, port, host, family) ? 1 : 0
  }

  _onremotechanged() {
    if (this._previousSocket) {
      this._previousSocket._removeStream(this)
      this._previousSocket = null
    }

    this._remoteChanging = null
    this.emit('remote-changed')
  }

  _consumeData(len) {
    const next = this._buffer.subarray(0, len)
    this._buffer = this._buffer.subarray(len)
    if (this._buffer.byteLength < MAX_PACKET) this._reallocData()
    return next
  }

  _reallocData() {
    this._buffer = b4a.allocUnsafe(BUFFER_SIZE)
    return this._buffer
  }

  _reallocMessage() {
    return this.udx._reallocMessage()
  }

  _allocWrite(size) {
    if (this._wfree.length === 0) {
      const handle = b4a.allocUnsafe(binding.udx_napi_stream_write_sizeof(size))
      return (
        this._wreqs.push({
          handle,
          size,
          buffers: null,
          buffer: null,
          flush: 0
        }) - 1
      )
    }

    const free = this._wfree.pop()
    if (size === 1) return free

    const next = this._wreqs[free]
    if (next.size < size) {
      next.handle = b4a.allocUnsafe(binding.udx_napi_stream_write_sizeof(size))
      next.size = size
    }

    return free
  }

  _allocSend() {
    if (this._sfree.length > 0) return this._sfree.pop()
    const handle = b4a.allocUnsafe(binding.sizeof_udx_stream_send_t)
    return this._sreqs.push({ handle, buffer: null, resolve: null, reject: null }) - 1
  }
}

function noop() {}

function toBuffer(data) {
  return typeof data === 'string' ? b4a.from(data) : data
}

function firewallAll(socket, port, host) {
  return true
}

function customError(message, code) {
  const error = new Error(message)
  error.code = code
  return error
}

function nextBatchSize(n) {
  // try to coerce the the writevs into sameish size
  if (n === 1) return 1
  // group all < 8 to the same size, low mem overhead but save some small allocs
  if (n < 8) return 8
  if (n < 16) return 16
  if (n < 32) return 32
  if (n < 64) return 64
  return n
}
const b4a = require('b4a')
const binding = require('../binding')
const ip = require('./ip')
const Socket = require('./socket')
const Stream = require('./stream')
const NetworkInterfaces = require('./network-interfaces')

const MAX_MESSAGE = 4096
const BUFFER_SIZE = 65536 + MAX_MESSAGE

module.exports = class UDX {
  constructor() {
    this._handle = b4a.alloc(binding.sizeof_udx_napi_t)
    this._watchers = new Set()
    this._view64 = new BigUint64Array(
      this._handle.buffer,
      this._handle.byteOffset,
      this._handle.byteLength >> 3
    )

    this._buffer = null
    this._reallocMessage()

    binding.udx_napi_init(this._handle, this._buffer)
  }

  static isIPv4(host) {
    return ip.isIPv4(host)
  }

  static isIPv6(host) {
    return ip.isIPv6(host)
  }

  static isIP(host) {
    return ip.isIP(host)
  }

  get bytesTransmitted() {
    return Number(this._view64[binding.offsetof_udx_t_bytes_tx >> 3])
  }

  get packetsTransmitted() {
    return Number(this._view64[binding.offsetof_udx_t_packets_tx >> 3])
  }

  get bytesReceived() {
    return Number(this._view64[binding.offsetof_udx_t_bytes_rx >> 3])
  }

  get packetsReceived() {
    return Number(this._view64[binding.offsetof_udx_t_packets_rx >> 3])
  }

  get packetsDroppedByKernel() {
    return Number(this._view64[binding.offsetof_udx_t_packets_dropped_by_kernel >> 3])
  }

  _consumeMessage(len) {
    const next = this._buffer.subarray(0, len)
    this._buffer = this._buffer.subarray(len)
    if (this._buffer.byteLength < MAX_MESSAGE) this._reallocMessage()
    return next
  }

  _reallocMessage() {
    // TODO: move reallocation to native
    this._buffer = b4a.allocUnsafe(BUFFER_SIZE)
    return this._buffer
  }

  createSocket(opts) {
    return new Socket(this, opts)
  }

  createStream(id, opts) {
    return new Stream(this, id, opts)
  }

  networkInterfaces() {
    let [watcher = null] = this._watchers
    if (watcher) return watcher.interfaces

    watcher = new NetworkInterfaces(this)
    watcher.destroy()

    return watcher.interfaces
  }

  watchNetworkInterfaces(onchange) {
    const watcher = new NetworkInterfaces(this)

    this._watchers.add(watcher)
    watcher.on('close', () => {
      this._watchers.delete(watcher)
    })

    if (onchange) watcher.on('change', onchange)

    return watcher.watch()
  }

  async lookup(host, opts = {}) {
    const { family = 0 } = opts

    const req = b4a.alloc(binding.sizeof_udx_napi_lookup_t)
    const ctx = {
      req,
      resolve: null,
      reject: null
    }

    const promise = new Promise((resolve, reject) => {
      ctx.resolve = resolve
      ctx.reject = reject
    })

    binding.udx_napi_lookup(this._handle, req, host, family, ctx, onlookup)

    return promise
  }
}

function onlookup(err, host, family) {
  if (err) this.reject(err)
  else this.resolve({ host, family })
}
{
  "name": "udx-native",
  "version": "1.20.7",
  "description": "udx is reliable, multiplexed, and congestion-controlled streams over udp",
  "main": "lib/udx.js",
  "files": [
    "lib",
    "prebuilds",
    "binding.cc",
    "binding.js",
    "CMakeLists.txt"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "addon": true,
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node --coverage test/*.js",
    "test:bare": "brittle-bare --coverage test/*.js",
    "test:all": "brittle test/*.js test/slow/*.js",
    "test:generate": "brittle -r test/all.js test/*.js",
    "bench": "brittle test/bench/*.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/udx-native.git"
  },
  "keywords": [
    "tcp",
    "udp",
    "stream",
    "reliable"
  ],
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/udx-native/issues"
  },
  "homepage": "https://github.com/holepunchto/udx-native#readme",
  "engines": {
    "bare": ">=1.17.4"
  },
  "dependencies": {
    "b4a": "^1.5.0",
    "bare-events": "^2.2.0",
    "require-addon": "^1.1.0",
    "streamx": "^2.22.0"
  },
  "devDependencies": {
    "bare-compat-napi": "^1.3.0",
    "brittle": "^3.1.0",
    "cmake-bare": "^1.1.10",
    "cmake-fetch": "^1.0.1",
    "cmake-napi": "^1.0.5",
    "is-ci": "^3.0.1",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "tiny-byte-size": "^1.1.0"
  }
}
exports.add = add
exports.has = has
exports.remove = remove
exports.swap = swap

function add (list, item) {
  if (has(list, item)) return item
  item._index = list.length
  list.push(item)
  return item
}

function has (list, item) {
  return item._index < list.length && list[item._index] === item
}

function remove (list, item) {
  if (!has(list, item)) return null

  var last = list.pop()
  if (last !== item) {
    list[item._index] = last
    last._index = item._index
  }

  return item
}

function swap (list, a, b) {
  if (!has(list, a) || !has(list, b)) return
  var tmp = a._index
  a._index = b._index
  list[a._index] = a
  b._index = tmp
  list[b._index] = b
}
{
  "name": "unordered-set",
  "version": "2.0.1",
  "description": "A couple of functions that make it easy to maintain an unordered set as an array in an efficient way",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^6.0.4",
    "tape": "^4.4.0"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/unordered-set.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/unordered-set/issues"
  },
  "homepage": "https://github.com/mafintosh/unordered-set"
}
const b4a = require('b4a')

unslab.all = all
unslab.is = is

module.exports = unslab

function unslab (buf) {
  if (buf === null || buf.buffer.byteLength === buf.byteLength) return buf
  const copy = b4a.allocUnsafeSlow(buf.byteLength)
  copy.set(buf, 0)
  return copy
}

function is (buf) {
  return buf.buffer.byteLength !== buf.byteLength
}

function all (list) {
  let size = 0
  for (let i = 0; i < list.length; i++) {
    const buf = list[i]
    size += buf === null || buf.buffer.byteLength === buf.byteLength ? 0 : buf.byteLength
  }

  const copy = b4a.allocUnsafeSlow(size)
  const result = new Array(list.length)

  let offset = 0
  for (let i = 0; i < list.length; i++) {
    let buf = list[i]

    if (buf !== null && buf.buffer.byteLength !== buf.byteLength) {
      copy.set(buf, offset)
      buf = copy.subarray(offset, offset += buf.byteLength)
    }

    result[i] = buf
  }

  return result
}
{
  "name": "unslab",
  "version": "1.3.0",
  "description": "Unslab some slab'ed buffers",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.6.6"
  },
  "devDependencies": {
    "brittle": "^3.5.2",
    "standard": "^17.1.0"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/unslab.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/unslab/issues"
  },
  "homepage": "https://github.com/holepunchto/unslab"
}
module.exports = read

var MSB = 0x80
  , REST = 0x7F

function read(buf, offset) {
  var res    = 0
    , offset = offset || 0
    , shift  = 0
    , counter = offset
    , b
    , l = buf.length

  do {
    if (counter >= l) {
      read.bytes = 0
      throw new RangeError('Could not decode varint')
    }
    b = buf[counter++]
    res += shift < 28
      ? (b & REST) << shift
      : (b & REST) * Math.pow(2, shift)
    shift += 7
  } while (b >= MSB)

  read.bytes = counter - offset

  return res
}
module.exports = encode

var MSB = 0x80
  , REST = 0x7F
  , MSBALL = ~REST
  , INT = Math.pow(2, 31)

function encode(num, out, offset) {
  out = out || []
  offset = offset || 0
  var oldOffset = offset

  while(num >= INT) {
    out[offset++] = (num & 0xFF) | MSB
    num /= 128
  }
  while(num & MSBALL) {
    out[offset++] = (num & 0xFF) | MSB
    num >>>= 7
  }
  out[offset] = num | 0
  
  encode.bytes = offset - oldOffset + 1
  
  return out
}
module.exports = {
    encode: require('./encode.js')
  , decode: require('./decode.js')
  , encodingLength: require('./length.js')
}

var N1 = Math.pow(2,  7)
var N2 = Math.pow(2, 14)
var N3 = Math.pow(2, 21)
var N4 = Math.pow(2, 28)
var N5 = Math.pow(2, 35)
var N6 = Math.pow(2, 42)
var N7 = Math.pow(2, 49)
var N8 = Math.pow(2, 56)
var N9 = Math.pow(2, 63)

module.exports = function (value) {
  return (
    value < N1 ? 1
  : value < N2 ? 2
  : value < N3 ? 3
  : value < N4 ? 4
  : value < N5 ? 5
  : value < N6 ? 6
  : value < N7 ? 7
  : value < N8 ? 8
  : value < N9 ? 9
  :              10
  )
}
{
  "name": "varint",
  "version": "5.0.0",
  "description": "protobuf-style varint bytes - use msb to create integer values of varying sizes",
  "main": "index.js",
  "scripts": {
    "test": "node test.js"
  },
  "repository": {
    "type": "git",
    "url": "git://github.com/chrisdickinson/varint.git"
  },
  "keywords": [
    "varint",
    "protobuf",
    "encode",
    "decode"
  ],
  "author": "Chris Dickinson <chris@neversaw.us>",
  "license": "MIT",
  "devDependencies": {
    "tape": "~2.12.3"
  }
}
const { runtime, platform, arch, version } =
  typeof Bare !== 'undefined'
    ? {
        runtime: 'bare',
        platform: global.Bare.platform,
        arch: global.Bare.arch,
        version: global.Bare.version
      }
    : typeof process !== 'undefined'
      ? {
          runtime: 'node',
          platform: global.process.platform,
          arch: global.process.arch,
          version: global.process.version
        }
      : typeof Window !== 'undefined'
        ? { runtime: 'browser', platform: 'unknown', arch: 'unknown', version: 'unknown' }
        : { runtime: 'unknown', platform: 'unknown', arch: 'unknown', version: 'unknown' }

exports.runtime = runtime
exports.version = version
exports.platform = platform
exports.arch = arch
exports.isBare = runtime === 'bare'
exports.isBareKit = exports.isBare && typeof BareKit !== 'undefined'
exports.isPear = typeof Pear !== 'undefined'
exports.isNode = runtime === 'node'
exports.isBrowser = runtime === 'browser'
exports.isWindows = platform === 'win32'
exports.isLinux = platform === 'linux'
exports.isMac = platform === 'darwin'
exports.isIOS = platform === 'ios' || platform === 'ios-simulator'
exports.isAndroid = platform === 'android'
exports.isElectron = typeof process !== 'undefined' && !!global.process.versions?.electron
exports.isElectronRenderer = exports.isElectron && global.process.type === 'renderer'
exports.isElectronWorker = exports.isElectron && global.process.type === 'worker'
{
  "name": "which-runtime",
  "version": "1.4.0",
  "description": "Detect if you are in Bare or Node and which os etc",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte .",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/which-runtime.git"
  },
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/which-runtime/issues"
  },
  "homepage": "https://github.com/holepunchto/which-runtime",
  "devDependencies": {
    "brittle": "^3.0.0",
    "lunte": "^1.4.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = class MaxCache {
  constructor ({ maxSize, maxAge, createMap, ongc }) {
    this.maxSize = maxSize
    this.maxAge = maxAge
    this.ongc = ongc || null

    this._createMap = createMap || defaultCreateMap
    this._latest = this._createMap()
    this._oldest = this._createMap()
    this._retained = this._createMap()
    this._gced = false
    this._interval = null

    if (this.maxAge > 0 && this.maxAge < Infinity) {
      const tick = Math.ceil(2 / 3 * this.maxAge)
      this._interval = setInterval(this._gcAuto.bind(this), tick)
      if (this._interval.unref) this._interval.unref()
    }
  }

  * [Symbol.iterator] () {
    for (const it of [this._latest, this._oldest, this._retained]) {
      yield * it
    }
  }

  * keys () {
    for (const it of [this._latest, this._oldest, this._retained]) {
      yield * it.keys()
    }
  }

  * values () {
    for (const it of [this._latest, this._oldest, this._retained]) {
      yield * it.values()
    }
  }

  destroy () {
    this.clear()
    clearInterval(this._interval)
    this._interval = null
  }

  clear () {
    this._gced = true
    this._latest.clear()
    this._oldest.clear()
    this._retained.clear()
  }

  set (k, v) {
    if (this._retained.has(k)) return this
    this._latest.set(k, v)
    this._oldest.delete(k) || this._retained.delete(k)
    if (this._latest.size >= this.maxSize) this._gc()
    return this
  }

  retain (k, v) {
    this._retained.set(k, v)
    this._latest.delete(k) || this._oldest.delete(k)
    return this
  }

  delete (k) {
    return this._latest.delete(k) || this._oldest.delete(k) || this._retained.delete(k)
  }

  has (k) {
    return this._latest.has(k) || this._oldest.has(k) || this._retained.has(k)
  }

  get (k) {
    if (this._latest.has(k)) {
      return this._latest.get(k)
    }

    if (this._oldest.has(k)) {
      const v = this._oldest.get(k)
      this._latest.set(k, v)
      this._oldest.delete(k)
      return v
    }

    if (this._retained.has(k)) {
      return this._retained.get(k)
    }

    return null
  }

  _gcAuto () {
    if (!this._gced) this._gc()
    this._gced = false
  }

  _gc () {
    this._gced = true
    if (this.ongc !== null && this._oldest.size > 0) this.ongc(this._oldest)
    this._oldest = this._latest
    this._latest = this._createMap()
  }
}

function defaultCreateMap () {
  return new Map()
}
{
  "name": "xache",
  "version": "1.2.1",
  "description": "Yet another auto expiring, max sizable cache",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "devDependencies": {
    "brittle": "^3.3.2",
    "standard": "^17.1.0"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/xache.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/xache/issues"
  },
  "homepage": "https://github.com/mafintosh/xache"
}
const b4a = require('b4a')

const ALPHABET = 'ybndrfg8ejkmcpqxot1uwisza345h769'
const MIN = 0x31 // 1
const MAX = 0x7a // z
const REVERSE = new Int8Array(1 + MAX - MIN)

REVERSE.fill(-1)

for (let i = 0; i < ALPHABET.length; i++) {
  const v = ALPHABET.charCodeAt(i) - MIN
  REVERSE[v] = i
}

exports.encode = encode
exports.decode = decode
exports.ALPHABET = ALPHABET

function decode (s, out) {
  let pb = 0
  let ps = 0

  const r = s.length & 7
  const q = (s.length - r) / 8

  if (!out) out = b4a.allocUnsafe(Math.ceil(s.length * 5 / 8))

  // 0 5 2 7 4 1 6 3 (+5 mod 8)
  for (let i = 0; i < q; i++) {
    const a = quintet(s, ps++)
    const b = quintet(s, ps++)
    const c = quintet(s, ps++)
    const d = quintet(s, ps++)
    const e = quintet(s, ps++)
    const f = quintet(s, ps++)
    const g = quintet(s, ps++)
    const h = quintet(s, ps++)

    out[pb++] = (a << 3) | (b >>> 2)
    out[pb++] = ((b & 0b11) << 6) | (c << 1) | (d >>> 4)
    out[pb++] = ((d & 0b1111) << 4) | (e >>> 1)
    out[pb++] = ((e & 0b1) << 7) | (f << 2) | (g >>> 3)
    out[pb++] = ((g & 0b111) << 5) | h
  }

  if (r === 0) return out.subarray(0, pb)

  const a = quintet(s, ps++)
  const b = quintet(s, ps++)

  out[pb++] = (a << 3) | (b >>> 2)

  if (r <= 2) return out.subarray(0, pb)

  const c = quintet(s, ps++)
  const d = quintet(s, ps++)

  out[pb++] = ((b & 0b11) << 6) | (c << 1) | (d >>> 4)

  if (r <= 4) return out.subarray(0, pb)

  const e = quintet(s, ps++)

  out[pb++] = ((d & 0b1111) << 4) | (e >>> 1)

  if (r <= 5) return out.subarray(0, pb)

  const f = quintet(s, ps++)
  const g = quintet(s, ps++)

  out[pb++] = ((e & 0b1) << 7) | (f << 2) | (g >>> 3)

  if (r <= 7) return out.subarray(0, pb)

  const h = quintet(s, ps++)

  out[pb++] = ((g & 0b111) << 5) | h

  return out.subarray(0, pb)
}

function encode (buf) {
  if (typeof buf === 'string') buf = b4a.from(buf)

  const max = buf.byteLength * 8

  let s = ''

  for (let p = 0; p < max; p += 5) {
    const i = p >>> 3
    const j = p & 7

    if (j <= 3) {
      s += ALPHABET[(buf[i] >>> (3 - j)) & 0b11111]
      continue
    }

    const of = j - 3
    const h = (buf[i] << of) & 0b11111
    const l = (i >= buf.byteLength ? 0 : buf[i + 1]) >>> (8 - of)

    s += ALPHABET[h | l]
  }

  return s
}

function quintet (s, i) {
  if (i > s.length) {
    return 0
  }

  const v = s.charCodeAt(i)

  if (v < MIN || v > MAX) {
    throw Error('Invalid character in base32 input: "' + s[i] + '" at position ' + i)
  }

  const bits = REVERSE[v - MIN]

  if (bits === -1) {
    throw Error('Invalid character in base32 input: "' + s[i] + '" at position ' + i)
  }

  return bits
}
{
  "name": "z32",
  "version": "1.1.0",
  "description": "Encode & decode z-base32",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.5.3"
  },
  "devDependencies": {
    "base-x": "^4.0.0",
    "base32": "0.0.7",
    "brittle": "^3.1.3",
    "nanobench": "^3.0.0",
    "rfc4648": "^1.5.2",
    "standard": "^17.0.0"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/z32.git"
  },
  "scripts": {
    "test": "standard && brittle test.js",
    "bench": "node benchmark.js"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/z32/issues"
  },
  "homepage": "https://github.com/mafintosh/z32"
}
{
  "name": "atproto-room",
  "version": "0.2.22",
  "description": "Attestation-gated, encrypted multi-writer room engine — StateBase (keet-model admission) + Lease + signer + RepoBase + LabelBase/LabelRoom + serve-membrane. Extracted from hyper-proto-peer; consumed by the atproto peer (repo devices) and the co-authored labeler.",
  "type": "module",
  "main": "index.js",
  "scripts": {
    "test": "bare test/all.js",
    "test:units": "node test/label-base.test.mjs && node test/label-signer.test.mjs && node test/label-room.test.mjs",
    "postinstall": "node scripts/bare-deps.mjs"
  },
  "dependencies": {
    "@ipld/dag-cbor": "^9.2.1",
    "atproto-identity": "file:../atproto-identity",
    "atproto-repo": "file:../atproto-repo",
    "atproto-store": "file:../atproto-store",
    "autobase": "7.28.1",
    "b4a": "^1.6.0",
    "bare-fs": "^4.7.1",
    "bare-path": "^3.0.1",
    "bare-process": "^4.2.1",
    "blind-pairing": "^2.3.1",
    "compact-encoding": "^2.16.0",
    "corestore": "^7.10.0",
    "hypercore": "^11.33.1",
    "hypercore-crypto": "^3.0.0",
    "hyperdb": "^6.7.0",
    "hyperdispatch": "^1.6.0",
    "hyperschema": "^1.21.0",
    "hyperswarm": "^4.17.0",
    "keet-identity-key": "^3.2.0",
    "multiformats": "^13.4.2",
    "protomux": "^3.11.0",
    "protomux-rpc": "^1.10.0"
  },
  "devDependencies": {
    "@hyperswarm/testnet": "^3.1.4",
    "@noble/curves": "^1.6.0",
    "brittle": "^4.0.2"
  }
}
// This file is autogenerated by the hyperdb compiler
/* eslint-disable camelcase */

const { IndexEncoder, c, b4a } = require('hyperdb/runtime')
const { version, getEncoding, setVersion } = require('./messages.js')

const versions = { schema: version, db: 1 }

// '@state/entries' collection key
const collection0_key = new IndexEncoder([
  IndexEncoder.STRING
], { prefix: 0 })

function collection0_indexify (record) {
  const a = record.key
  return a === undefined ? [] : [a]
}

// '@state/entries' value encoding
const collection0_enc = getEncoding('@state/entry/hyperdb#0')

// '@state/entries' reconstruction function
function collection0_reconstruct (schemaVersion, keyBuf, valueBuf) {
  const key = collection0_key.decode(keyBuf)
  setVersion(schemaVersion)
  const state = { start: 0, end: valueBuf.byteLength, buffer: valueBuf }
  const type = c.uint.decode(state)
  if (type !== 0) throw new Error('Unknown collection type: ' + type)
  collection0.decodedVersion = c.uint.decode(state)
  const record = collection0_enc.decode(state)
  record.key = key[0]
  return record
}
// '@state/entries' key reconstruction function
function collection0_reconstruct_key (keyBuf) {
  const key = collection0_key.decode(keyBuf)
  return {
    key: key[0]
  }
}

// '@state/entries'
const collection0 = {
  name: '@state/entries',
  id: 0,
  version: 1,
  encodeKey (record) {
    const key = [record.key]
    return collection0_key.encode(key)
  },
  encodeKeyRange ({ gt, lt, gte, lte } = {}) {
    return collection0_key.encodeRange({
      gt: gt ? collection0_indexify(gt) : null,
      lt: lt ? collection0_indexify(lt) : null,
      gte: gte ? collection0_indexify(gte) : null,
      lte: lte ? collection0_indexify(lte) : null
    })
  },
  encodeValue (schemaVersion, collectionVersion, record) {
    setVersion(schemaVersion)
    const state = { start: 0, end: 2, buffer: null }
    collection0_enc.preencode(state, record)
    state.buffer = b4a.allocUnsafe(state.end)
    state.buffer[state.start++] = 0
    state.buffer[state.start++] = collectionVersion
    collection0_enc.encode(state, record)
    return state.buffer
  },
  trigger: null,
  reconstruct: collection0_reconstruct,
  reconstructKey: collection0_reconstruct_key,
  indexes: [],
  decodedVersion: 0
}

const collections = [
  collection0
]

const indexes = [
]

module.exports = { versions, collections, indexes, resolveCollection, resolveIndex }

function resolveCollection (name) {
  switch (name) {
    case '@state/entries': return collection0
    default: return null
  }
}

function resolveIndex (name) {
  switch (name) {
    default: return null
  }
}
// This file is autogenerated by the hyperschema compiler
// Schema Version: 1
/* eslint-disable camelcase */
/* eslint-disable quotes */
/* eslint-disable space-before-function-paren */

const { c } = require('hyperschema/runtime')

const VERSION = 1

// eslint-disable-next-line no-unused-vars
let version = VERSION

// @state/entry
const encoding0 = {
  preencode(state, m) {
    c.string.preencode(state, m.key)
    state.end++ // max flag is 4 so always one byte

    if (m.value) c.string.preencode(state, m.value)
    if (m.ts) c.uint.preencode(state, m.ts)
    if (m.admit) c.string.preencode(state, m.admit)
  },
  encode(state, m) {
    const flags = (m.value ? 1 : 0) | (m.ts ? 2 : 0) | (m.admit ? 4 : 0)

    c.string.encode(state, m.key)
    c.uint.encode(state, flags)

    if (m.value) c.string.encode(state, m.value)
    if (m.ts) c.uint.encode(state, m.ts)
    if (m.admit) c.string.encode(state, m.admit)
  },
  decode(state) {
    const r0 = c.string.decode(state)
    const flags = c.uint.decode(state)

    return {
      key: r0,
      value: (flags & 1) !== 0 ? c.string.decode(state) : null,
      ts: (flags & 2) !== 0 ? c.uint.decode(state) : 0,
      admit: (flags & 4) !== 0 ? c.string.decode(state) : null
    }
  }
}

// @state/entry-key
const encoding1 = {
  preencode(state, m) {
    c.string.preencode(state, m.key)
    state.end++ // max flag is 1 so always one byte

    if (m.ts) c.uint.preencode(state, m.ts)
  },
  encode(state, m) {
    const flags = m.ts ? 1 : 0

    c.string.encode(state, m.key)
    c.uint.encode(state, flags)

    if (m.ts) c.uint.encode(state, m.ts)
  },
  decode(state) {
    const r0 = c.string.decode(state)
    const flags = c.uint.decode(state)

    return {
      key: r0,
      ts: (flags & 1) !== 0 ? c.uint.decode(state) : 0
    }
  }
}

// @state/entry/hyperdb#0
const encoding2 = {
  preencode(state, m) {
    state.end++ // max flag is 4 so always one byte

    if (m.value) c.string.preencode(state, m.value)
    if (m.ts) c.uint.preencode(state, m.ts)
    if (m.admit) c.string.preencode(state, m.admit)
  },
  encode(state, m) {
    const flags = (m.value ? 1 : 0) | (m.ts ? 2 : 0) | (m.admit ? 4 : 0)

    c.uint.encode(state, flags)

    if (m.value) c.string.encode(state, m.value)
    if (m.ts) c.uint.encode(state, m.ts)
    if (m.admit) c.string.encode(state, m.admit)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      key: null,
      value: (flags & 1) !== 0 ? c.string.decode(state) : null,
      ts: (flags & 2) !== 0 ? c.uint.decode(state) : 0,
      admit: (flags & 4) !== 0 ? c.string.decode(state) : null
    }
  }
}

function setVersion(v) {
  version = v
}

function encode(name, value, v = VERSION) {
  version = v
  return c.encode(getEncoding(name), value)
}

function decode(name, buffer, v = VERSION) {
  version = v
  return c.decode(getEncoding(name), buffer)
}

function getEnum(name) {
  switch (name) {
    default:
      throw new Error('Enum not found ' + name)
  }
}

function getEncoding(name) {
  switch (name) {
    case '@state/entry':
      return encoding0
    case '@state/entry-key':
      return encoding1
    case '@state/entry/hyperdb#0':
      return encoding2
    default:
      throw new Error('Encoder not found ' + name)
  }
}

function getStruct(name, v = VERSION) {
  const enc = getEncoding(name)
  return {
    preencode(state, m) {
      version = v
      enc.preencode(state, m)
    },
    encode(state, m) {
      version = v
      enc.encode(state, m)
    },
    decode(state) {
      version = v
      return enc.decode(state)
    }
  }
}

const resolveStruct = getStruct // compat

module.exports = {
  resolveStruct,
  getStruct,
  getEnum,
  getEncoding,
  encode,
  decode,
  setVersion,
  version
}
// This file is autogenerated by the hyperdispatch compiler
/* eslint-disable camelcase */

const { c, b4a, assert, DispatchError, ERRORS } = require('hyperdispatch/runtime')
const { version, getEncoding, setVersion } = require('./messages.js')

const defaultVersion = version

class Router {
  constructor () {
    this._handler0 = null
    this._handler1 = null

    this._missing = 2
  }

  add (name, handler) {
    switch (name) {
      case '@state/set-entry':
        this._handler0 = handler
        break
      case '@state/del-entry':
        this._handler1 = handler
        break
      default:
        throw DispatchError.NONEXISTENT_ROUTE(name)
    }
    this._missing--
  }

  _checkAll () {
    assert(this._handler0 !== null, 'Missing handler for "@state/set-entry"')
    assert(this._handler1 !== null, 'Missing handler for "@state/del-entry"')
  }

  async dispatch (message, context) {
    if (this._missing > 0) {
      this._checkAll()
    }

    setVersion(defaultVersion)

    const op = b4a.isBuffer(message) ? decode(message) : message

    switch (op.id) {
      case 0:
        return this._handler0(op.value, context)
      case 1:
        return this._handler1(op.value, context)
      default:
        throw DispatchError.HANDLER_NOT_FOUND_BY_ID(op.id)
    }
  }
}

function encode (name, message, { version = defaultVersion } = {}) {
  const state = { buffer: null, start: 0, end: 0 }

  const route = getRouteByName(name)
  setVersion(version)

  c.uint.preencode(state, route.id)
  route.enc.preencode(state, message)

  state.buffer = b4a.allocUnsafe(state.end)
  c.uint.encode(state, route.id)
  route.enc.encode(state, message)

  return state.buffer
}

function decode (buffer, { version = defaultVersion } = {}) {
  const state = { buffer, start: 0, end: buffer.length }

  const id = c.uint.decode(state)
  const route = getRouteById(id)
  setVersion(version)

  const value = route.enc.decode(state)
  return { id, name: route.name, value }
}

const route0 = {
  name: '@state/set-entry',
  id: 0,
  enc: getEncoding('@state/entry')
}

const route1 = {
  name: '@state/del-entry',
  id: 1,
  enc: getEncoding('@state/entry-key')
}

function getRouteByName (name) {
  switch (name) {
    case '@state/set-entry':
      return route0
    case '@state/del-entry':
      return route1
    default:
      throw DispatchError.ROUTE_NOT_FOUND_BY_NAME(name)
  }
}

function getRouteById (id) {
  switch (id) {
    case 0:
      return route0
    case 1:
      return route1
    default:
      throw DispatchError.HANDLER_NOT_FOUND_BY_ID(id)
  }
}

module.exports = {
  version,
  encode,
  decode,
  Router,
  DispatchError,
  ERRORS
}
// This file is autogenerated by the hyperschema compiler
// Schema Version: 1
/* eslint-disable camelcase */
/* eslint-disable quotes */
/* eslint-disable space-before-function-paren */

const { c } = require('hyperschema/runtime')

const VERSION = 1

// eslint-disable-next-line no-unused-vars
let version = VERSION

// @state/entry
const encoding0 = {
  preencode(state, m) {
    c.string.preencode(state, m.key)
    state.end++ // max flag is 4 so always one byte

    if (m.value) c.string.preencode(state, m.value)
    if (m.ts) c.uint.preencode(state, m.ts)
    if (m.admit) c.string.preencode(state, m.admit)
  },
  encode(state, m) {
    const flags = (m.value ? 1 : 0) | (m.ts ? 2 : 0) | (m.admit ? 4 : 0)

    c.string.encode(state, m.key)
    c.uint.encode(state, flags)

    if (m.value) c.string.encode(state, m.value)
    if (m.ts) c.uint.encode(state, m.ts)
    if (m.admit) c.string.encode(state, m.admit)
  },
  decode(state) {
    const r0 = c.string.decode(state)
    const flags = c.uint.decode(state)

    return {
      key: r0,
      value: (flags & 1) !== 0 ? c.string.decode(state) : null,
      ts: (flags & 2) !== 0 ? c.uint.decode(state) : 0,
      admit: (flags & 4) !== 0 ? c.string.decode(state) : null
    }
  }
}

// @state/entry-key
const encoding1 = {
  preencode(state, m) {
    c.string.preencode(state, m.key)
    state.end++ // max flag is 1 so always one byte

    if (m.ts) c.uint.preencode(state, m.ts)
  },
  encode(state, m) {
    const flags = m.ts ? 1 : 0

    c.string.encode(state, m.key)
    c.uint.encode(state, flags)

    if (m.ts) c.uint.encode(state, m.ts)
  },
  decode(state) {
    const r0 = c.string.decode(state)
    const flags = c.uint.decode(state)

    return {
      key: r0,
      ts: (flags & 1) !== 0 ? c.uint.decode(state) : 0
    }
  }
}

function setVersion(v) {
  version = v
}

function encode(name, value, v = VERSION) {
  version = v
  return c.encode(getEncoding(name), value)
}

function decode(name, buffer, v = VERSION) {
  version = v
  return c.decode(getEncoding(name), buffer)
}

function getEnum(name) {
  switch (name) {
    default:
      throw new Error('Enum not found ' + name)
  }
}

function getEncoding(name) {
  switch (name) {
    case '@state/entry':
      return encoding0
    case '@state/entry-key':
      return encoding1
    default:
      throw new Error('Encoder not found ' + name)
  }
}

function getStruct(name, v = VERSION) {
  const enc = getEncoding(name)
  return {
    preencode(state, m) {
      version = v
      enc.preencode(state, m)
    },
    encode(state, m) {
      version = v
      enc.encode(state, m)
    },
    decode(state) {
      version = v
      return enc.decode(state)
    }
  }
}

const resolveStruct = getStruct // compat

module.exports = {
  resolveStruct,
  getStruct,
  getEnum,
  getEncoding,
  encode,
  decode,
  setVersion,
  version
}
{ "type": "commonjs" }
// AccountRegistry — the multi-tenant PDS's durable roster of hosted repos.
//
// One classic Hyperbee (same substrate as RepoStore) on a reserved core of the SHARED
// corestore: key = did, value = the account record (handle, storeName, signing key,
// genesis op, active flag). This is what lets a restarted PDS re-open every account it
// hosts instead of forgetting them. The signing key lives here in the PDS custody model
// (the bsky PDS holds account keys); hardening the at-rest storage is a tracked loose
// end (see the hyperident plaintext-seed note in the handoff).

import Hyperbee from 'hyperbee'

export class AccountRegistry {
  constructor (corestore, opts = {}) {
    this._store = corestore
    this._name = opts.name || 'pds-accounts'
    this.bee = null
  }

  async ready () {
    const core = this._store.get({ name: this._name })
    await core.ready()
    // alwaysDuplicate:false → re-putting an unchanged account record is a no-op, not an append. See repo-store.js.
    this.bee = new Hyperbee(core, { keyEncoding: 'utf-8', valueEncoding: 'json', alwaysDuplicate: false })
    await this.bee.ready()
    return this
  }

  async put (did, record) { await this.bee.put(did, record) }

  async get (did) {
    const node = await this.bee.get(did)
    return node ? node.value : null
  }

  // Every persisted account record, in did (key) order.
  async * list () {
    for await (const node of this.bee.createReadStream()) yield node.value
  }

  async close () { if (this.bee) await this.bee.close() }
}
// BlobPointerStore — the blob half of the "pointers in the autobase, bytes in the overlay" design.
// This is to blobs exactly what PointerSubstrate is to records, and it exists because the records
// side got this right and the blobs side did not.
//
// THE GAP IT CLOSES. OverlayBlobStore keeps a per-blob metadata record { mimeType, size, oid } in a
// Hyperbee, and that bee is NODE-LOCAL — in the live daemon it lives in the membrane corestore
// (device-node.js: `overlay-blobs:<did>` on membraneStore), which does not replicate. Its get() reads
// that bee FIRST and returns null when the entry is missing, BEFORE it ever looks at the file or the
// overlay. So a blob uploaded on node A produces two artifacts with very different fates:
//
//   the FILE + overlay registration  -> content-addressed, fetchable by `oid` from any peer
//   the bee entry { mimeType,size,oid } -> stays on node A, forever
//
// Node B therefore cannot serve the blob even when the bytes are reachable, because the one thing it
// is missing is the cid -> oid mapping needed to ask for them. Since the atproto blob CID (raw codec,
// cidForBlobSync) and the overlay oid (blake2b) are DIFFERENT hashes, B cannot derive one from the
// other — the mapping has to be replicated, not recomputed. Symptom in production: an avatar that
// serves or 404s depending on which co-owner the bridge happens to front.
//
// THE FIX is the pattern PointerSubstrate already proves for records: put a tiny pointer in the SHARED
// autobase so every co-owner converges on which blobs exist and the oid to fetch each one by, while the
// bytes stay out of the append-only log. Pointer key is `__blob__/<cid>`, in the RESERVED "__"
// namespace — RepoBase.splitKey and PointerSubstrate both return null for a collection starting with
// "__", so these entries can never be mistaken for records or materialized into a signed commit.
//
// Drop-in: same public surface as BlobStore / OverlayBlobStore (ready / put / get / has / close), so it
// composes under DualBlobStore unchanged.

const BLOB_PREFIX = '__blob__/'

export class BlobPointerStore {
  // statebase: the shared StateBase (set/get). blobs: an OverlayBlobStore (the local bytes + bee).
  constructor (statebase, blobs, { did = null } = {}) {
    if (!statebase || typeof statebase.set !== 'function' || typeof statebase.get !== 'function') {
      throw new Error('BlobPointerStore: a StateBase (set/get) is required for the shared pointer set')
    }
    if (!blobs || typeof blobs.put !== 'function' || typeof blobs.adoptMeta !== 'function') {
      throw new Error('BlobPointerStore: an OverlayBlobStore (put/get/adoptMeta) is required for the bytes')
    }
    this.sb = statebase
    this.blobs = blobs
    this._did = did
  }

  static key (cidStr) { return BLOB_PREFIX + cidStr }

  async ready () { return this } // the caller readies the underlying OverlayBlobStore

  // Write the bytes locally (file + overlay registration + local bee), then publish the SHARED pointer
  // so any co-owner can resolve this blob by oid.
  //
  // A failed pointer write does NOT fail the upload. The blob is already durably stored and servable
  // from this node, so throwing here would turn a cross-node limitation into a total upload failure —
  // strictly worse than today. But it is logged LOUDLY rather than swallowed, because the resulting
  // state (blob local-only) is exactly the silent condition this module exists to end. The common
  // cause is a non-writable device: sb.set appends to the autobase, so only an admitted writer can
  // publish a pointer.
  async put (bytes, mimeType) {
    const r = await this.blobs.put(bytes, mimeType)
    const cidStr = r.cid.toString()
    if (r.oid) {
      try {
        await this.sb.set(BlobPointerStore.key(cidStr), { $oid: r.oid, size: r.size, mimeType: r.mimeType })
      } catch (err) {
        this._warn(cidStr, 'pointer write failed — blob is stored LOCAL-ONLY and will not serve from other co-owners', err && err.message)
      }
    } else {
      this._warn(cidStr, 'no overlay oid — blob cannot be published as a shared pointer (is the overlay attached?)', null)
    }
    return r
  }

  // Local first (bee hit -> file, or fetch-by-oid). On a miss, consult the SHARED pointer: adopt its
  // metadata into the local bee, then re-enter the ordinary get() path, which now finds the mapping and
  // fetches the bytes by oid. Reusing get() rather than fetching here keeps ONE byte-resolution path.
  async get (cidStr) {
    const cid = String(cidStr)
    const local = await this.blobs.get(cid)
    if (local) return local
    const ptr = await this._pointer(cid)
    if (!ptr || !ptr.$oid) return null
    await this.blobs.adoptMeta(cid, { mimeType: ptr.mimeType, size: ptr.size, oid: ptr.$oid })
    return this.blobs.get(cid)
  }

  // Known here OR known to the swarm. A shared pointer means the bytes are fetchable even if this node
  // has never seen them, so reporting only the local bee would understate availability.
  async has (cidStr) {
    const cid = String(cidStr)
    if (await this.blobs.has(cid)) return true
    return !!(await this._pointer(cid))
  }

  // MIGRATION: publish a shared pointer for every blob this node already holds but has never announced.
  // The counterpart of PointerSubstrate.backfill for records, and the reason blobs uploaded BEFORE this
  // module existed are not stranded: their bytes and metadata are already here, only the announcement is
  // missing. Idempotent and convergence-safe — SKIPS any cid that already has a pointer (a co-owner may
  // have published a newer one; never clobber it) and never deletes.
  //
  // WRITABLE-ONLY: sb.set appends to the autobase, so the caller must gate on base.writable.
  // `unpublishable` counts blobs with no local oid — nothing to point at; those need reindexOverlay()
  // first to re-register the file and recover an oid.
  async backfill () {
    if (typeof this.blobs.entries !== 'function') {
      throw new Error('BlobPointerStore.backfill: the blob store must enumerate entries() to migrate blobs → pointers')
    }
    let written = 0
    let skipped = 0
    let unpublishable = 0
    let total = 0
    for await (const e of this.blobs.entries()) {
      total++
      if (!e.oid) { unpublishable++; continue }
      const key = BlobPointerStore.key(e.cid)
      if ((await this.sb.get(key)) != null) { skipped++; continue }
      await this.sb.set(key, { $oid: e.oid, size: e.size, mimeType: e.mimeType })
      written++
    }
    return { written, skipped, unpublishable, total }
  }

  // PROACTIVE blob convergence — the half that was missing.
  //
  // Publishing `__blob__/<cid>` makes a blob FETCHABLE by any co-owner, but nothing was walking those
  // pointers, so blobs only ever moved LAZILY: when something happened to call get(). Two peers that
  // never request each other's blobs therefore never exchanged them — images resolved to bsky (the
  // bridge relays get-blob by RPC to whoever holds the bytes) while silently never replicating between
  // nodes. This is the blob counterpart of SwarmDevice.reconcileBytes, which deliberately skips
  // `__`-prefixed keys and so could never cover them.
  //
  // PULL-ONLY: it never writes a pointer, so it is safe on a NON-WRITABLE replica — exactly the peer
  // that needs to catch up. Presence is tested with hasLocalFile (a stat), not get(), so a converged
  // node does no reads at all. Bounded per pass with `more`, so a large backlog cannot stall the caller.
  // Every blob CID this DID has PUBLISHED a pointer for — the inventory behind com.atproto.sync.listBlobs.
  //
  // ⛔ THIS IS THE ONLY WAY TO SEE AN ORPHAN. A blob referenced by some record can be found by walking
  // records (favela-web/lib/blob-refs.js does exactly that, and needs no server support). A blob that is
  // uploaded and referenced by NOTHING is invisible to any such walk, by construction — and that is the
  // class that permanently lost the 2026-07-03 image. The pointer set is the authority's own inventory,
  // so it is the only place the difference shows up.
  //
  // Reads the SHARED state, so it lists what the DID has published across all its co-owners, not merely
  // what this node happens to hold bytes for. Sorted for a stable cursor; `since` is deliberately NOT
  // supported (pointers carry no rev, so a rev-filter would silently return the wrong set — better to
  // not offer it than to answer wrongly).
  async list ({ limit = 500, cursor = null } = {}) {
    let map
    try {
      map = await ((typeof this.sb.listNow === 'function') ? this.sb.listNow(BLOB_PREFIX) : this.sb.list(BLOB_PREFIX))
    } catch (e) {
      return { cids: [], cursor: null, error: e.message }
    }
    const all = Object.keys(map || {})
      .filter((k) => k.startsWith(BLOB_PREFIX))
      .map((k) => k.slice(BLOB_PREFIX.length))
      .filter(Boolean)
      .sort()
    const start = cursor ? all.findIndex((c) => c > String(cursor)) : 0
    const from = start < 0 ? all.length : start
    const n = Math.max(1, Math.min(Number(limit) || 500, 1000))
    const page = all.slice(from, from + n)
    const next = (from + n) < all.length ? page[page.length - 1] : null
    return { cids: page, cursor: next, total: all.length }
  }

  async reconcile ({ limit = 8 } = {}) {
    if (typeof this.blobs.hasLocalFile !== 'function') return { skipped: 'not-supported' }
    let map
    try {
      map = await ((typeof this.sb.listNow === 'function') ? this.sb.listNow(BLOB_PREFIX) : this.sb.list(BLOB_PREFIX))
    } catch (e) { return { skipped: 'list-failed', error: e.message } }
    let checked = 0; let missing = 0; let fetched = 0; let failed = 0; let more = false
    for (const key of Object.keys(map)) {
      if (!key.startsWith(BLOB_PREFIX)) continue
      const cid = key.slice(BLOB_PREFIX.length)
      if (!cid) continue
      checked++
      if (this.blobs.hasLocalFile(cid)) continue // bytes already here — a stat, not a read
      missing++
      if (fetched + failed >= limit) { more = true; continue }
      let got = null
      try { got = await this.get(cid) } catch {}
      if (got) fetched++; else failed++
    }
    const sig = checked + ':' + missing + ':' + fetched + ':' + failed
    if ((fetched || missing) && sig !== this._lastReconcileSig) {
      try { console.log(JSON.stringify({ msg: 'blob reconcile: pulling shared-pointer blobs', did: this._did, checked, missing, fetched, failed, more })) } catch {}
    }
    this._lastReconcileSig = sig
    return { checked, missing, fetched, failed, more }
  }

  // Pass through to the byte layer's repair (re-register blob files so peers can fetch them by oid).
  async reindexOverlay () {
    if (typeof this.blobs.reindexOverlay !== 'function') return { skipped: 'not-supported' }
    return this.blobs.reindexOverlay()
  }

  async _pointer (cidStr) {
    try { return await this.sb.get(BlobPointerStore.key(cidStr)) } catch { return null }
  }

  _warn (cid, msg, error) {
    try { console.error(JSON.stringify({ msg: 'blob pointer: ' + msg, did: this._did, cid, error })) } catch {}
  }

  async close () { try { await this.blobs.close() } catch {} }
}

export { BLOB_PREFIX }
// BlobStore — content-addressed blob storage for the PDS (images, avatars).
//
// atproto blobs are opaque bytes addressed by a CIDv1/raw/sha256 CID; a record references
// one via a blob ref ({$type:'blob', ref:{$link:<cid>}, mimeType, size}), and
// com.atproto.sync.getBlob serves it back by CID. Content-addressed, so it's shared across
// accounts on this PDS (the same bytes upload once). Backed by ONE classic Hyperbee on the
// shared corestore — same substrate as RepoStore — value framed as [4-byte headerLen] +
// JSON{mimeType,size} + raw bytes, so a single binary bee holds bytes + their mime type.
//
// (hyperblobs would be the heavier "right" tool for very large blobs; a Hyperbee is ample
// for avatars/images and adds no dependency. Revisit if blob sizes grow.)

import Corestore from 'corestore'
import { isCorestore } from './corestore.js'
import Hyperbee from 'hyperbee'
import b4a from 'b4a'
import { cidForBlobSync } from 'atproto-repo/lib/cid.js'

export class BlobStore {
  constructor (storage, opts = {}) {
    // Behavioural check, NOT `instanceof` — a second copy of corestore in a bundled tree makes a real
    // store look like a path and Corestore then path.join()s an object. See lib/corestore.js.
    this._ownStore = !isCorestore(storage)
    this._store = this._ownStore ? new Corestore(storage) : storage
    this._name = opts.name || 'pds-blobs'
    this.bee = null
  }

  async ready () {
    const core = this._store.get({ name: this._name })
    await core.ready()
    // alwaysDuplicate:false → re-uploading identical bytes at the same CID is a no-op, not a re-append of
    // the full blob value (content-addressed key is stable, so the value is byte-identical). See repo-store.js.
    this.bee = new Hyperbee(core, { keyEncoding: 'utf-8', valueEncoding: 'binary', alwaysDuplicate: false })
    await this.bee.ready()
    return this
  }

  // Store bytes; returns { cid (CID), mimeType, size }. Idempotent (content-addressed).
  async put (bytes, mimeType = 'application/octet-stream') {
    const buf = b4a.isBuffer(bytes) ? bytes : b4a.from(bytes)
    const cid = cidForBlobSync(buf)
    const header = b4a.from(JSON.stringify({ mimeType, size: buf.length }), 'utf-8')
    const len = b4a.allocUnsafe(4)
    len.writeUInt32BE(header.length, 0)
    await this.bee.put(cid.toString(), b4a.concat([len, header, buf]))
    return { cid, mimeType, size: buf.length }
  }

  // Fetch by CID string; returns { mimeType, size, bytes } or null.
  async get (cidStr) {
    const node = await this.bee.get(cidStr)
    if (!node) return null
    const frame = node.value
    const headerLen = frame.readUInt32BE(0)
    const header = JSON.parse(b4a.toString(frame.subarray(4, 4 + headerLen), 'utf-8'))
    return { mimeType: header.mimeType, size: header.size, bytes: frame.subarray(4 + headerLen) }
  }

  async has (cidStr) { return !!(await this.bee.get(cidStr)) }

  async close () { if (this.bee) await this.bee.close() }
}
// The store package owns the Holepunch substrate — so the corestore dependency resolves
// here (store/node_modules), and higher layers (pds) compose store abstractions without
// reaching for corestore directly.

import Corestore from 'corestore'

// A dir path (or an existing Corestore) -> a Corestore. Idempotent on an instance.
export function openCorestore (storage) {
  return isCorestore(storage) ? storage : new Corestore(storage)
}

// ⛔ NOT `instanceof`. That compares against ONE module instance's class object, and a nested
// node_modules tree routinely yields two copies of corestore — which is what bare-pack ships to the
// phone (…/hyper-proto-peer/node_modules/atproto-room/node_modules/atproto-store/node_modules/corestore
// alongside the daemon's own). A store built by copy A then fails `instanceof` against copy B, and every
// discriminator here reads that as "not a store, therefore a PATH", so Corestore tried to path.join an
// OBJECT and the node died with `Cannot read properties of undefined (reading 'length')` — a message
// that names a JS idiom and no cause (hyper-social #40).
//
// It cannot reproduce on a workstation, where the tree is deduped to one copy. The environments differ
// in their module graph, not their code, so identity is the wrong question: a store is what it DOES.
// `get` + `namespace` + `replicate` are the surface every caller here uses and nothing else implements.
// The instanceof check stays as a fast path for the common single-copy case.
export function isCorestore (x) {
  if (!x || typeof x !== 'object') return false
  if (x instanceof Corestore) return true
  return typeof x.get === 'function' && typeof x.namespace === 'function' && typeof x.replicate === 'function'
}

export { Corestore }
// OverlayBlobStore — atproto blobs (avatars/images) stored as REAL content-addressed FILES on disk,
// deduped + distributed by hyper-overlay. The drop-in replacement for BlobStore's Hyperbee-of-bytes
// (which stored [len][header][BYTES] as bee values → an append-only balloon, the exact model the
// records redesign fled). Here the BYTES are files (FastCDC dedup, no corestore balloon); the bee
// holds only a TINY per-blob record { mimeType, size, oid } — metadata + the overlay content hash
// (oid) so a peer that has the metadata can fetch the bytes by hash cross-node.
//
// Same public API as BlobStore (drop-in): ready / put(bytes,mime)->{cid,mimeType,size} /
// get(cidStr)->{mimeType,size,bytes}|null / has / close. `cid` is the atproto blob CID
// (cidForBlobSync — raw codec); the overlay `oid` is blake2b (hypercore-crypto data()) — distinct,
// hence the mapping in the bee.
//
// overlay = a HyperOverlay (injected — this module never imports hyper-overlay, so it stays
// dual-runtime like OverlayRepoStore). blobRoot = dir for the canonical blob files. indexStore = a
// Corestore for the tiny metadata bee.

import Corestore from 'corestore'
import { isCorestore } from './corestore.js'
import Hyperbee from 'hyperbee'
import b4a from 'b4a'
import fs from '#node:fs' // dual-runtime: bare-fs under Bare (the daemon), builtin fs under Node (tests)
import { join } from '#node:path'
import { cidForBlobSync } from 'atproto-repo/lib/cid.js'

export class OverlayBlobStore {
  constructor (blobRoot, { overlay = null, indexStore, name = 'blob-index' } = {}) {
    if (typeof blobRoot !== 'string') throw new Error('OverlayBlobStore: blobRoot dir required')
    if (!indexStore) throw new Error('OverlayBlobStore: indexStore (Corestore) required')
    this._blobRoot = blobRoot
    this._overlay = overlay
    // Behavioural check, NOT `instanceof` — a second copy of corestore in a bundled tree makes a real
    // store look like a path and Corestore then path.join()s an object. See lib/corestore.js.
    this._ownStore = !isCorestore(indexStore)
    this._store = this._ownStore ? new Corestore(indexStore) : indexStore
    this._name = name
    this.bee = null
  }

  async ready () {
    fs.mkdirSync(this._blobRoot, { recursive: true })
    const core = this._store.get({ name: this._name })
    await core.ready()
    // metadata only (tiny JSON) — NOT the blob bytes. root bee, alwaysDuplicate:false is safe here.
    this.bee = new Hyperbee(core, { keyEncoding: 'utf-8', valueEncoding: 'binary', alwaysDuplicate: false })
    await this.bee.ready()
    return this
  }

  _pathFor (cidStr) { return join(this._blobRoot, cidStr) }

  // Store bytes as a content-addressed file + register with the overlay (dedup + servable by oid).
  // Idempotent (content-addressed): the same bytes always map to the same cid/file.
  async put (bytes, mimeType = 'application/octet-stream') {
    const buf = b4a.isBuffer(bytes) ? bytes : b4a.from(bytes)
    const cid = cidForBlobSync(buf)
    const cidStr = cid.toString()
    const path = this._pathFor(cidStr)
    fs.writeFileSync(path, buf)
    let oid = null
    if (this._overlay) {
      const r = await this._overlay.registerFile('/blobs/' + cidStr, path, { size: buf.length })
      oid = r ? r.contentHash : null
    }
    await this.bee.put(cidStr, b4a.from(JSON.stringify({ mimeType, size: buf.length, oid }), 'utf-8'))
    // `oid` is returned so a caller can publish it as a SHARED pointer (see BlobPointerStore). The bee
    // here is node-local and never replicates, so without propagating the oid a co-owner that receives
    // the blob FILE still cannot serve it — get() below returns null on a missing bee entry.
    return { cid, mimeType, size: buf.length, oid }
  }

  // Record metadata for a blob this node did NOT upload — learned from a replicated source (the shared
  // pointer set). Writing the bee entry is what makes get() able to resolve the blob at all: get() reads
  // the bee FIRST and returns null when it is absent, even if the bytes are already on disk. After this,
  // the ordinary get() path applies unchanged (local file hit, else fetchFile by oid).
  async adoptMeta (cidStr, { mimeType = 'application/octet-stream', size = 0, oid = null } = {}) {
    const existing = await this.bee.get(cidStr)
    if (existing) return false // never clobber locally-known metadata
    await this.bee.put(cidStr, b4a.from(JSON.stringify({ mimeType, size, oid }), 'utf-8'))
    return true
  }

  // Fetch by CID string; returns { mimeType, size, bytes } or null. Serves the local file if present;
  // otherwise pulls the bytes from a connected peer by the overlay oid (content-hash verified).
  async get (cidStr) {
    const node = await this.bee.get(cidStr)
    if (!node) return null
    const meta = JSON.parse(b4a.toString(node.value, 'utf-8'))
    const path = this._pathFor(cidStr)
    let bytes = null
    try {
      bytes = fs.readFileSync(path)
    } catch (e) {
      if (!e || e.code !== 'ENOENT') throw e
      if (this._overlay && meta.oid) {
        const r = await this._overlay.fetchFile(meta.oid, { destPath: path })
        if (r) { try { bytes = fs.readFileSync(path) } catch { bytes = null } }
      }
    }
    if (!bytes) return null
    return { mimeType: meta.mimeType, size: meta.size, bytes }
  }

  async has (cidStr) { return !!(await this.bee.get(cidStr)) }

  // Do we hold the BYTES on disk? Distinct from has(), which only reports that the local metadata bee
  // knows this cid — a blob can have an ADOPTED bee entry (learned from a shared pointer) with no file
  // yet. Reconciliation needs the byte-level answer, and needs it CHEAP: a stat, not a read, so a pass
  // over hundreds of blobs does not pull every one into memory just to discover it is already present.
  hasLocalFile (cidStr) {
    try { return fs.statSync(this._pathFor(String(cidStr))).isFile() } catch { return false }
  }

  // Everything this node knows locally: { cid, mimeType, size, oid }. The input to pointer backfill.
  async * entries () {
    for await (const node of this.bee.createReadStream()) {
      const cid = typeof node.key === 'string' ? node.key : b4a.toString(node.key, 'utf-8')
      let meta
      try { meta = JSON.parse(b4a.toString(node.value, 'utf-8')) } catch { continue }
      yield { cid, mimeType: meta.mimeType, size: meta.size, oid: meta.oid || null }
    }
  }

  // EXPLICIT REPAIR — the blob counterpart of OverlayRepoStore.reindexOverlay, for a store whose overlay
  // INDEX is missing or stale. That method walks records/ ONLY and never touches blobs, so a repaired
  // node would resume serving records by oid while silently still failing every blob.
  //
  // Walks the blob FILES (the canonical bytes; each filename IS its atproto CID) rather than the bee,
  // because the bee is exactly what may be impoverished. Deliberately never INVENTS metadata: a file
  // with no bee entry is registered — so its bytes become fetchable by oid — but is reported as
  // `unknownMeta` rather than given a guessed mimeType, which would be served to clients as fact. Such a
  // blob is recoverable once its shared pointer replicates (BlobPointerStore.get adopts mime from there).
  // `prepare:false` matches the record path: the serve path chunks lazily on first request.
  async reindexOverlay () {
    if (!this._overlay) return { skipped: 'no-overlay' }
    let names
    try { names = fs.readdirSync(this._blobRoot) } catch (e) { if (e && e.code === 'ENOENT') return { registered: 0, failed: 0, metaUpdated: 0, unknownMeta: 0, total: 0 }; throw e }
    let registered = 0
    let failed = 0
    let metaUpdated = 0
    let unknownMeta = 0
    for (const cidStr of names) {
      const path = this._pathFor(cidStr)
      let size = 0
      try { const st = fs.statSync(path); if (!st.isFile()) continue; size = st.size } catch { continue }
      let oid = null
      try {
        const r = await this._overlay.registerFile('/blobs/' + cidStr, path, { size, prepare: false })
        oid = r ? r.contentHash : null
      } catch { failed++; continue }
      if (!oid) { failed++; continue }
      registered++
      const node = await this.bee.get(cidStr)
      if (!node) { unknownMeta++; continue }
      try {
        const meta = JSON.parse(b4a.toString(node.value, 'utf-8'))
        if (meta.oid !== oid) {
          meta.oid = oid
          await this.bee.put(cidStr, b4a.from(JSON.stringify(meta), 'utf-8'))
          metaUpdated++
        }
      } catch {}
    }
    return { registered, failed, metaUpdated, unknownMeta, total: names.length }
  }

  async close () {
    try { if (this.bee) await this.bee.close() } catch {}
    if (this._ownStore) { try { await this._store.close() } catch {} }
  }
}
// OverlayRepoStore — a RepoStore backend that keeps records as canonical DAG-CBOR FILES
// on disk (one file per record at records/<collection>/<rkey>.dagcbor) instead of in an
// append-only Hyperbee. Overwrite-in-place on edit, unlink on delete → the on-disk size is
// O(CURRENT records), not O(operations-ever). MST/commit/CAR are DERIVED on read by the
// atproto-repo codec (read-view.js / repo-manager.js consume only this interface), so nothing
// atproto-specific is stored beyond the record bytes + a tiny head.json.
//
// Byte-exactness (the determinism contract): `put` stores dagCbor.encode(record) VERBATIM —
// byte-identical to the Hyperbee RepoStore — so cidForBytesSync(bytes) and the derived MST +
// commit are identical. records() returns records in Hyperbee key order (utf-8 byte order via
// b4a.compare) so the derivation is order-stable.
//
// The canonical bytes ARE the files on disk. An optional hyper-overlay instance (opts.overlay)
// indexes + replicates them (bytes stay on disk — no corestore balloon; hyper-overlay/index.js).
// Without it the store is a fully-functional local file tree (used by the determinism tests).
// Drop-in for atproto-store/lib/repo-store.js's RepoStore (same method surface).

import * as dagCbor from '@ipld/dag-cbor'
import b4a from 'b4a'
import fs from '#node:fs' // dual-runtime: bare-fs under Bare (the daemon), builtin fs under Node (tests)
import { join } from '#node:path'
import { tidNow } from './tid.js'

const EXT = '.dagcbor'
const byteOrder = (a, b) => b4a.compare(b4a.from(a), b4a.from(b)) // match Hyperbee's key comparison exactly
// atproto collection NSIDs + rkeys are single path segments (no '/'); reject anything else so a
// record key can never escape the records/ dir or collide with a parent path.
const isSafeSeg = (s) => typeof s === 'string' && s.length > 0 && !s.includes('/') && s !== '.' && s !== '..'

export class OverlayRepoStore {
  // root: the per-DID dir (<storage>/dids/<did>). opts.overlay: optional HyperOverlay to
  // register files with (bytes-on-disk indexing/replication). opts.did: for logging/namespacing.
  constructor (root, opts = {}) {
    if (typeof root !== 'string') throw new Error('OverlayRepoStore: root dir path required')
    this._root = root
    this._recordsDir = join(root, 'records')
    this._headFile = join(root, 'head.json')
    this._overlay = opts.overlay || null
    this._did = opts.did || null
  }

  static key (collection, rkey) { return `${collection}/${rkey}` }

  async ready () {
    fs.mkdirSync(this._recordsDir, { recursive: true })
    // Restore servability across restart. The overlay's path maps are in-memory and only registerFile
    // fills them, so without this a restarted node serves ONLY records written since boot — every file
    // still on disk, yet peers get "no connected peer served this oid" (75+ hours of it on wj62), which
    // blocks signing. Seeding from the PERSISTED index costs one scan with no hashing and no file
    // reads, and it avoids the protocol's tier-3 full-index re-scan on every content request.
    // Our overlay paths are disk paths relative to root, so the resolver is a plain join.
    if (this._overlay && typeof this._overlay.seedFilePathsFromIndex === 'function') {
      try {
        const n = await this._overlay.seedFilePathsFromIndex((overlayPath) => join(this._root, overlayPath))
        if (n) console.log(JSON.stringify({ msg: 'overlay: seeded record paths from the persisted index (servable-by-oid after restart)', did: this._did, seeded: n }))
      } catch (err) { console.error(JSON.stringify({ msg: 'overlay path seed FAILED — this node may not serve its records by oid until re-registered', did: this._did, error: err.message })) }
    }
    return this
  }

  // EXPLICIT REPAIR — not a boot step. ready() seeds the path maps from the persisted index, which is
  // the cheap normal path. This is the heavier fallback for a store whose INDEX itself is missing or
  // stale (records written before overlay indexing existed, or an index rebuilt/lost): it re-hashes
  // every record file and re-registers it. Needed once on nodes whose indexes predate the seed fix;
  // deliberately NOT wired into ready(), because re-hashing every file at every boot is the cold-start
  // cost that made pgh-sidecar take ~190s to bind its socket.
  //
  // Re-register every record file with the overlay so peers can fetch it BY OID.
  //
  // hyper-overlay's serve path resolves contentHash -> disk path through an IN-MEMORY map
  // (overlay.js `_contentHashPaths`, populated only by registerFile and handed to protocol.js by
  // reference). Nothing rebuilds it at boot, and the persisted FileIndex stores { contentHash, size,
  // mtime } WITHOUT the disk path — so the overlay cannot repair itself; only the consumer knows the
  // layout. Net effect before this: after a restart a node could serve ONLY the records it had
  // written since boot ("registering a file makes it servable", overlay.js:15), even though every
  // file was still on disk.
  //
  // That silently breaks cross-node byte resolution, which GATES SIGNING: the forward-only sign gate
  // skips while a converged pointer's bytes are unresolved. Measured on the live fleet — wj62's
  // app.bsky.feed.post/3mr6v6r2ofs22 sat unresolvable for 75+ hours while the peer holding it had the
  // exact bytes on disk (hash verified equal to the pointer's oid), reporting only "no connected peer
  // served this oid"; both co-owners held different incomplete subsets for the same reason.
  //
  // Idempotent and safe to run every boot: registerFile re-asserts an identical entry. Deliberately
  // passes NO `rev` (a fresh TID would make a re-registration look like a newer write to rev-wins
  // conflict resolution) and `prepare: false` (the serve path chunks lazily on first request, so we
  // avoid a second full read of every file at boot).
  async reindexOverlay () {
    if (!this._overlay) return { skipped: 'no-overlay' }
    let registered = 0
    let failed = 0
    const files = await this.records()
    for (const { key, bytes } of files) {
      const i = key.indexOf('/')
      const collection = key.slice(0, i)
      const rkey = key.slice(i + 1)
      try {
        const r = await this._overlay.registerFile(this._overlayPath(collection, rkey), this._pathFor(collection, rkey), { size: bytes.length, prepare: false })
        if (r) registered++; else failed++
      } catch { failed++ }
    }
    if (files.length) {
      try { console.log(JSON.stringify({ msg: 'overlay reindex: record files re-registered as servable-by-oid', did: this._did, registered, failed, total: files.length })) } catch {}
    }
    return { registered, failed, total: files.length }
  }

  _pathFor (collection, rkey) {
    if (!isSafeSeg(collection) || !isSafeSeg(rkey)) throw new Error(`OverlayRepoStore: unsafe record key "${collection}/${rkey}"`)
    return join(this._recordsDir, collection, rkey + EXT)
  }

  // READ-ONLY: the overlay oid the record file CURRENTLY on disk hashes to, or null when absent.
  // Writes nothing (no registration, no index entry) — safe against a live store.
  //
  // This is the missing half of the pointer design's integrity story. PointerSubstrate stores
  // { $oid, size } in the shared autobase and resolves it through ensureLocal, which returns a local
  // file hit WITHOUT comparing it to $oid — so a node holding a superseded copy of a record serves it
  // forever and never re-fetches, while its pointer set looks perfectly converged. Nothing in the
  // stack could even ask "does my file match the pointer?", which is why the wj62 profile divergence
  // (two co-owners, identical 139 pointers, different avatar blob refs) was only visible by diffing
  // two signed CARs against each other. Compare this against the pointer's $oid to answer it directly.
  async localOid (collection, rkey) {
    if (!this._overlay || typeof this._overlay.hashFile !== 'function') return null
    let p
    try { p = this._pathFor(collection, rkey) } catch { return null }
    const r = await this._overlay.hashFile(p)
    return r ? { oid: r.contentHash, size: r.size } : null
  }

  // Returns { oid, size }: oid = the overlay content hash (blake2b) that a PEER fetches the bytes by
  // (PointerSubstrate stores {oid,size} as the symmetric autobase pointer). null oid when no overlay.
  async put (collection, rkey, record) {
    const bytes = b4a.from(dagCbor.encode(record))
    const p = this._pathFor(collection, rkey)
    fs.mkdirSync(join(this._recordsDir, collection), { recursive: true })
    fs.writeFileSync(p, bytes)
    // Stamp a monotonic per-write version (TID) so cross-device conflict resolution is atproto-native
    // (rev-wins: the later write wins). Records carry no rev at put time — the commit rev comes at sign.
    // Only affects the overlay change feed, never the canonical record file → determinism is preserved.
    let oid = null
    if (this._overlay) { try { const r = await this._overlay.registerFile(this._overlayPath(collection, rkey), p, { size: bytes.length, rev: tidNow() }); oid = r ? r.contentHash : null } catch {} }
    return { oid, size: bytes.length }
  }

  // Ensure the record BYTES are present locally, fetching from a connected peer by overlay oid if this
  // node holds only the pointer (a follower resolving the converged autobase set). Returns the decoded
  // record or null. Local-hit is the common path; the fetch is the cross-node byte-resolution.
  async ensureLocal (collection, rkey, oid) {
    const local = await this.get(collection, rkey)
    if (local != null) {
      // A local hit used to return here UNCONDITIONALLY, without ever comparing the bytes to the oid
      // the caller asked for. That made the pointer design's central promise unenforced: the autobase
      // converges { $oid, size }, but a node holding a SUPERSEDED copy resolved it happily, never
      // re-fetched, and signed it as truth. Live on wj62 — two co-owners, identical 139 converged
      // pointers, both resolving all 139, different signed repos, differing on exactly one record
      // (app.bsky.actor.profile/self, two avatar blob refs) — so the published profile flipped avatar
      // on every signer change. Content-addressing was being used to FETCH but never to VERIFY.
      if (!oid || !this._overlay || typeof this._overlay.hashFile !== 'function') return local
      const h = await this.localOid(collection, rkey)
      // Only a POSITIVE mismatch is staleness. If the bytes cannot be hashed at all we cannot judge
      // them, and inventing a verdict would re-resolve every record on every pass — behaviour must be
      // unchanged wherever verification is impossible.
      if (!h || h.oid === oid) return local // verified against the converged pointer — the common path
      this._logStaleLocal(collection, rkey, oid, h ? h.oid : null)
      const fetched = await this._refetchOver(collection, rkey, oid)
      // Deliberately null, NOT the stale record, when the authoritative bytes cannot be obtained.
      // Returning the superseded copy is what published wrong content: this record then reads as
      // UNRESOLVED, which is precisely the state the forward-only sign gate is built to handle
      // ("pointer present, bytes unreplicated -> behind -> SKIP"). A node that cannot prove its bytes
      // match the group's pointer must not sign them. Note the trade: if NO peer holds the
      // authoritative bytes, the record stays unresolved and the chain stalls rather than advancing
      // with content nobody agreed on — loudly (see _logStaleLocal) instead of silently.
      return fetched
    }
    if (!this._overlay || !oid) return null
    const disk = this._pathFor(collection, rkey)
    try {
      fs.mkdirSync(join(this._recordsDir, collection), { recursive: true })
      const r = await this._overlay.fetchFile(oid, { destPath: disk })
      if (!r) { this._logFetchMiss(collection, rkey, oid, 'fetchFile returned null'); return null }
    } catch (err) { this._logFetchMiss(collection, rkey, oid, (err && err.message) || String(err)); return null }
    return this.get(collection, rkey)
  }

  // Replace a SUPERSEDED local record file with the authoritative bytes for `oid`, without destroying
  // what we hold until the replacement is verified. Fetches to a sibling temp path (reSeed:false so the
  // overlay never indexes the temp), re-asserts the hash, then renames into place atomically and
  // registers the FINAL path so this node serves the correct bytes afterwards. On any failure the
  // existing file is left exactly as it was and null is returned. Returns the decoded record or null.
  async _refetchOver (collection, rkey, oid) {
    const disk = this._pathFor(collection, rkey)
    const tmp = disk + '.incoming-' + String(oid).slice(0, 12)
    try {
      const r = await this._overlay.fetchFile(oid, { destPath: tmp, reSeed: false })
      if (!r) { this._logFetchMiss(collection, rkey, oid, 'no peer served the authoritative bytes for a superseded local file'); return null }
      // fetchFile verifies incrementally during transfer; re-assert before overwriting persistent state.
      const h = await this._overlay.hashFile(tmp)
      if (!h || h.contentHash !== oid) {
        try { fs.unlinkSync(tmp) } catch {}
        this._logFetchMiss(collection, rkey, oid, 'fetched bytes did not hash to the requested oid')
        return null
      }
      fs.renameSync(tmp, disk)
      try { await this._overlay.registerFile(this._overlayPath(collection, rkey), disk, { size: h.size }) } catch {}
      try {
        console.log(JSON.stringify({ msg: 'ensureLocal: replaced superseded record bytes with the authoritative copy', did: this._did, key: collection + '/' + rkey, oid: String(oid).slice(0, 16) }))
      } catch {}
      return this.get(collection, rkey)
    } catch (err) {
      try { fs.unlinkSync(tmp) } catch {}
      this._logFetchMiss(collection, rkey, oid, (err && err.message) || String(err))
      return null
    }
  }

  // A local file that does not match the converged pointer is an ANOMALY, not routine lag — it means
  // this node has been resolving (and possibly signing) content the group did not agree on. Reported
  // once per key+oid so a persistent case is visible without spamming the resolve loop.
  _logStaleLocal (collection, rkey, oid, localOid) {
    if (!this._staleSeen) this._staleSeen = new Set()
    const k = collection + '/' + rkey + ':' + oid
    if (this._staleSeen.has(k)) return
    this._staleSeen.add(k)
    try {
      console.error(JSON.stringify({
        msg: 'ensureLocal: LOCAL BYTES DO NOT MATCH THE CONVERGED POINTER — this node held a superseded copy; re-fetching the authoritative bytes. Until it succeeds this record reads as unresolved and will not be signed.',
        did: this._did, key: collection + '/' + rkey, pointerOid: String(oid).slice(0, 16), localOid: localOid ? String(localOid).slice(0, 16) : null
      }))
    } catch {}
  }

  // Byte-resolution failures used to be swallowed entirely (`catch { return null }`), which made a
  // record whose bytes never replicated indistinguishable from any ordinary miss. That matters because
  // this path GATES SIGNING: the forward-only sign gate skips while a converged pointer's bytes are
  // unresolved, so a permanent miss silently stops a co-owner signing at all, with no diagnosable
  // cause. Observed on wj62 — one record unresolved for 75+ hours with nothing logged anywhere.
  // Deduped per oid, because the resolve loop calls this once per record on every list().
  // `fetchFile` returns null for two ROOT-DISTINCT reasons and the old message asserted only one of
  // them ("no connected peer served this oid"), which is why a transport-level fault read as a content
  // fault for days. overlay.js:307-315 waits peerWaitMs for a peer and bails if none ever attaches;
  // otherwise it asks the attached peers and they may simply not hold it. Reporting `overlayPeers`
  // separates those: 0 => the overlay channel never attached (a WIRING fault — look at attachProtocol);
  // >0 => genuinely nobody serving that content (a DISTRIBUTION fault — look at the holder's index).
  //
  // Dedup is keyed on oid + peerCount, not oid alone. Deduping per-oid-per-process meant the line was
  // emitted once at boot and never again, so a stale line was indistinguishable from a live failure and
  // could not be used to judge whether a repair had worked. Keying on the peer count keeps the log quiet
  // while still re-emitting the moment connectivity changes — which is exactly when the answer changes.
  _logFetchMiss (collection, rkey, oid, reason) {
    if (!this._fetchMisses) this._fetchMisses = new Set()
    const peers = (this._overlay && typeof this._overlay.peerCount === 'number') ? this._overlay.peerCount : null
    const k = String(oid)
    const dedupKey = k + ':' + peers
    if (this._fetchMisses.has(dedupKey)) return
    this._fetchMisses.add(dedupKey)
    try {
      console.error(JSON.stringify({
        msg: peers === 0
          ? 'overlay byte-resolution FAILED — NO overlay peers attached (transport/wiring fault, not content)'
          : 'overlay byte-resolution FAILED — peers attached but none served this oid (distribution fault)',
        did: this._did, key: `${collection}/${rkey}`, oid: k.slice(0, 16), overlayPeers: peers, reason
      }))
    } catch {}
  }

  async get (collection, rkey) {
    const raw = await this.getRaw(collection, rkey)
    return raw ? raw.record : null
  }

  // Raw stored bytes + decoded record. The bridge CIDs the EXACT bytes (never a re-encode) —
  // so these must be the same bytes `put` wrote.
  async getRaw (collection, rkey) {
    let bytes
    try { bytes = fs.readFileSync(this._pathFor(collection, rkey)) } catch (e) { if (e && e.code === 'ENOENT') return null; throw e }
    return { bytes, record: dagCbor.decode(bytes) }
  }

  async del (collection, rkey) {
    try { fs.unlinkSync(this._pathFor(collection, rkey)) } catch (e) { if (!e || e.code !== 'ENOENT') throw e }
    // Record the deletion in the overlay's change feed so it propagates to peers (attachReplication).
    if (this._overlay) { try { await this._overlay.unregisterFile(this._overlayPath(collection, rkey)) } catch {} }
    try { fs.rmdirSync(join(this._recordsDir, collection)) } catch {} // best-effort: drop an empty collection dir
  }

  // Yield { rkey, record } for one collection, in key (byte) order.
  async * list (collection) {
    const dir = join(this._recordsDir, collection)
    let names
    try { names = fs.readdirSync(dir) } catch (e) { if (e && e.code === 'ENOENT') return; throw e }
    for (const n of names.filter((x) => x.endsWith(EXT)).sort(byteOrder)) {
      const bytes = fs.readFileSync(join(dir, n))
      yield { rkey: n.slice(0, -EXT.length), record: dagCbor.decode(bytes) }
    }
  }

  // All records as { key, bytes, record } in key (byte) order — the sole input to the MST build.
  async records () {
    const out = []
    let collections
    try { collections = fs.readdirSync(this._recordsDir) } catch (e) { if (e && e.code === 'ENOENT') return out; throw e }
    for (const collection of collections) {
      const dir = join(this._recordsDir, collection)
      let st
      try { st = fs.statSync(dir) } catch { continue }
      if (!st.isDirectory()) continue
      for (const n of fs.readdirSync(dir)) {
        if (!n.endsWith(EXT)) continue
        const bytes = fs.readFileSync(join(dir, n))
        out.push({ key: `${collection}/${n.slice(0, -EXT.length)}`, bytes, record: dagCbor.decode(bytes) })
      }
    }
    out.sort((a, b) => byteOrder(a.key, b.key))
    return out
  }

  // Persist the commit head ({ rev, commitCid, dataCid }) — a tiny file, NOT a record, so it never
  // appears in records()/the MST. This is what keeps the head stable across restart: the rev is
  // RESTORED, not re-minted (re-minting forges a phantom commit — see RepoManager.init).
  async saveHead (head) {
    fs.mkdirSync(this._root, { recursive: true })
    fs.writeFileSync(this._headFile, JSON.stringify(head))
  }

  async loadHead () {
    try { return JSON.parse(fs.readFileSync(this._headFile, 'utf8')) } catch (e) { if (e && e.code === 'ENOENT') return null; throw e }
  }

  async close () {}

  _overlayPath (collection, rkey) { return `/records/${collection}/${rkey}${EXT}` }
}
// PointerSubstrate — the RepoBase KV that restores SYMMETRIC multi-writer convergence to the record
// set while keeping the bytes off the append-only log. A tiny { $oid, size } POINTER per record lives
// in the shared StateBase autobase (so every attested device converges on WHICH records exist, exactly
// like the default statebase path), and the record BYTES live as deduped files in the overlay,
// content-addressed + served by `oid` (blake2b). This is the "pointers in the autobase + bytes in the
// overlay" design: the autobase carries ~50 bytes/record instead of the full record (+ the firehose's
// inline copy), and cross-device convergence is the autobase — no bespoke overlay-to-overlay sync
// (RepoMirror is retired).
//
// RepoBase sees the SAME interface + shape as any substrate: set(key,record) / del(key) /
// get(key)->record|null / list(prefix)->{key:record} / listNow. The pointer indirection is internal:
// list/get RESOLVE each pointer to its record bytes via the overlay store (a local file hit, or a
// fetch-by-oid from a connected peer when this node — e.g. a just-promoted signer — holds only the
// converged pointer). Reserved "__" keys (firehose/admission) never reach here (swarm-device writes
// those to the StateBase directly); we defensively skip any that appear in a raw list.

const SEP = '/'

// The record-layer DELETE TOMBSTONE convention (owned by atproto-room's RepoBase; duplicated as a
// predicate here because the dependency direction is atproto-room -> atproto-store, never back).
// A deleted record keeps a pointer-shaped { $deleted:true } entry instead of vanishing, so a peer
// can tell "deleted" from "not replicated to me yet" — see RepoBase.deleteRecord.
const isTombstone = (v) => !!(v && typeof v === 'object' && v.$deleted === true)

function split (key) {
  const k = String(key)
  const i = k.indexOf(SEP)
  if (i < 0) throw new Error('PointerSubstrate: expected a "collection/rkey" record key, got ' + JSON.stringify(key))
  return { collection: k.slice(0, i), rkey: k.slice(i + 1) }
}

// Like RepoBase.splitKey: null for a reserved/non-record key (single-segment, or a "__"-prefixed
// collection such as __commit__/<rev>), so a raw statebase.list('') never resolves control data.
function recSplit (key) {
  const i = key.indexOf(SEP)
  if (i < 0) return null
  const collection = key.slice(0, i)
  if (collection.startsWith('__')) return null
  return { collection, rkey: key.slice(i + 1) }
}

export class PointerSubstrate {
  constructor (statebase, store) {
    if (!statebase || typeof statebase.set !== 'function' || typeof statebase.list !== 'function') {
      throw new Error('PointerSubstrate: a StateBase (set/get/del/list) is required for the pointer set')
    }
    if (!store || typeof store.put !== 'function' || typeof store.ensureLocal !== 'function') {
      throw new Error('PointerSubstrate: an OverlayRepoStore (put/ensureLocal) is required for the bytes')
    }
    this.statebase = statebase
    this.store = store
  }

  // Write the bytes to the overlay (dedup + servable by oid), then the tiny pointer to the autobase.
  // A TOMBSTONE value is not a record: it carries no bytes, so it is stored as the pointer itself and
  // the record's bytes are dropped. (RepoBase.deleteRecord routes deletes through set(), so this is
  // the delete path for the pointer design.)
  async set (key, record) {
    const { collection, rkey } = split(key)
    if (isTombstone(record)) {
      await this.statebase.set(key, { $deleted: true }) // converges symmetrically, like any pointer
      try { await this.store.del(collection, rkey) } catch {}
      return
    }
    const { oid, size } = await this.store.put(collection, rkey, record)
    await this.statebase.set(key, { $oid: oid, size })
  }

  // Legacy hard-delete. Retained for callers that genuinely want the key GONE; record deletion now
  // goes through set(TOMBSTONE) so absence stays unambiguous.
  async del (key) {
    const { collection, rkey } = split(key)
    await this.statebase.del(key)
    try { await this.store.del(collection, rkey) } catch {}
  }

  // Resolve the pointer to the record bytes (local file, or fetch-by-oid from a peer).
  async get (key) {
    const ptr = await this.statebase.get(key)
    if (!ptr || isTombstone(ptr)) return null // deleted reads as absent
    const { collection, rkey } = split(key)
    return this.store.ensureLocal(collection, rkey, ptr && ptr.$oid)
  }

  // The converged pointer set (authoritative) resolved to { key: record }. Skips reserved keys.
  async list (prefix = '') { return this._resolve(await this.statebase.list(prefix)) }
  async listNow (prefix = '') {
    const raw = (typeof this.statebase.listNow === 'function') ? await this.statebase.listNow(prefix) : await this.statebase.list(prefix)
    return this._resolve(raw)
  }

  async _resolve (ptrMap) {
    const out = {}
    for (const key of Object.keys(ptrMap)) {
      const s = recSplit(key)
      if (!s) continue // reserved/control key — not a record
      const ptr = ptrMap[key]
      if (isTombstone(ptr)) continue // deleted — never resolve bytes for a tombstone
      const rec = await this.store.ensureLocal(s.collection, s.rkey, ptr && ptr.$oid)
      if (rec != null) out[key] = rec
    }
    return out
  }

  // ── Step 2a MIGRATION: files-only → pointers (idempotent) ──────────────────────────────────────
  // A repo previously written by OverlayRepoSubstrate has its record BYTES on disk as overlay files
  // but NO pointers in the shared autobase. Under this substrate, listRecords() reads the pointer set
  // → ZERO, so the first sign() would materialize an EMPTY repo and wipe every record off the relay
  // (the wj62-wipe hazard). backfill() closes that gap: for every record file that has no pointer yet,
  // it writes the tiny {$oid,size} pointer into the autobase — so the converged pointer set reflects
  // the real record set before any sign runs.
  //
  // Idempotent + convergence-safe: SKIPS any key that already has a pointer (a peer may have converged
  // a newer put OR a delete tombstone — never resurrect/clobber it), and never deletes. Re-registering
  // the byte-identical file via store.put is harmless (the determinism contract: same bytes → same oid)
  // and yields the oid without trusting stale overlay index state. WRITABLE-ONLY: statebase.set appends
  // to the autobase, so only an admitted writer (the creator) may run this — the caller gates on
  // base.writable. Returns { written, skipped, total }.
  // ── MIGRATION: INLINE RECORD → POINTER (idempotent) ────────────────────────────────────────────
  // The inverse gap to backfill(). backfill covers "bytes on disk, no entry in the autobase"; this
  // covers "an entry in the autobase that is a full RECORD instead of a { $oid, size } pointer" —
  // written through the LEGACY substrate against a DID that now runs the pointer design.
  //
  // Such a repo reads perfectly on the node that holds it and is UNFETCHABLE BY EVERY OTHER NODE:
  // _resolve passes ptr.$oid (undefined) to ensureLocal, which falls back to the local file, so the
  // records resolve locally and no peer has an oid to fetch by. A co-owner would converge N keys it can
  // never turn into bytes. Live on loser-club: three records, all inline, so that DID cannot be
  // co-owned at all — the config and roster work is wasted until this is fixed.
  //
  // backfill() cannot do it: it SKIPS any key that already has a value (`if (existing != null)`), which
  // is correct for its job — never clobber a converged pointer or tombstone — but an inline record IS
  // such a value.
  //
  // CONTENT IS PRESERVED, NOT CHOSEN. What the repo currently publishes is the LOCAL FILE (that is what
  // ensureLocal returns today), not the inline copy in the log — so the pointer must address the file's
  // bytes or the signed repo would change underneath us. We therefore re-put the record read back from
  // disk, which registers it with the overlay (making it fetchable, the whole point) and returns its
  // oid; DAG-CBOR is canonical so the rewrite is byte-identical. That is ASSERTED, not assumed: if the
  // resulting oid differs from what the file already hashed to, the key is skipped and counted rather
  // than silently republishing different content. Only when there is no local file at all do we fall
  // back to the inline record — then it is the only copy in existence.
  //
  // Nothing is deleted (statebase.set appends; the old value stays in oplog history) and files are
  // never modified beyond a byte-identical rewrite. WRITABLE-ONLY: the caller gates on base.writable.
  // Returns { converted, alreadyPointer, tombstones, fromInline, mismatched, failed, total }.
  // TWO PASSES, and the order is a SAFETY property, not tidiness.
  //
  // PASS 1 MATERIALIZES every inline record to a file. PASS 2 publishes the pointers. Interleaving them
  // (put/set per record, as this did originally) leaves the set only partly protected while it runs.
  //
  // Why that matters: a legacy repo being flipped to this substrate reads as an EMPTY record set (_resolve
  // has no $oid and no file to fall back to), and sign()'s anti-wipe guard aborts only when record FILES
  // exist. With no files it does not fire, and the first sign publishes a delete-every-record commit.
  // Materializing the whole set FIRST arms that guard before a single autobase entry is touched — so if
  // pass 2 never runs (crash, lost writability, autobase error), the repo is protected rather than wiped.
  //
  // Pass 1 is also purely local: content-addressed files, nothing published, no writability needed, and
  // nothing to roll back. Pass 2 is the only part that appends.
  async migrateInline () {
    const raw = await this.statebase.list('')
    let converted = 0; let alreadyPointer = 0; let tombstones = 0; let fromInline = 0; let mismatched = 0; let failed = 0; let total = 0
    const staged = []
    for (const key of Object.keys(raw)) {
      const s = recSplit(key)
      if (!s) continue // reserved/control key — never part of the record pointer set
      total++
      const v = raw[key]
      if (isTombstone(v)) { tombstones++; continue }
      if (v && v.$oid) { alreadyPointer++; continue } // already the right shape — idempotent
      if (!v || typeof v !== 'object') { failed++; continue }
      try {
        const before = (typeof this.store.localOid === 'function') ? await this.store.localOid(s.collection, s.rkey) : null
        const onDisk = await this.store.get(s.collection, s.rkey)
        const record = onDisk != null ? onDisk : v // the file is what resolves today; the inline copy is the fallback
        if (onDisk == null) fromInline++
        const { oid, size } = await this.store.put(s.collection, s.rkey, record)
        if (!oid) { failed++; continue } // no overlay → no oid to publish; leave the entry alone
        if (before && oid !== before.oid) { mismatched++; continue } // would change published content — refuse
        staged.push({ key, oid, size })
      } catch { failed++ }
    }
    const materialized = staged.length
    for (const { key, oid, size } of staged) {
      try { await this.statebase.set(key, { $oid: oid, size }); converted++ } catch { failed++ }
    }
    return { converted, materialized, alreadyPointer, tombstones, fromInline, mismatched, failed, total }
  }

  async backfill () {
    if (typeof this.store.records !== 'function') {
      throw new Error('PointerSubstrate.backfill: the store must enumerate records() to migrate files → pointers')
    }
    let written = 0
    let skipped = 0
    const files = await this.store.records() // [{ key, bytes, record }] — the on-disk record files
    for (const { key, record } of files) {
      const s = recSplit(key)
      if (!s) continue // never migrate a reserved/control key into the record pointer set
      const existing = await this.statebase.get(key)
      if (existing != null) { skipped++; continue } // pointer already converged (put or tombstone) — leave it
      const { oid, size } = await this.store.put(s.collection, s.rkey, record)
      await this.statebase.set(key, { $oid: oid, size })
      written++
    }
    return { written, skipped, total: files.length }
  }
}
// Bridge READ-view — pure functions turning RepoStore (Hyperbee) state into atproto
// wire responses (com.atproto.sync.* / repo.*). No HTTP here (that's the thin face,
// later); no storage-specific atproto state in the store. rev/prev are INPUTS — commit
// head-state (monotonic rev, prev-linking) advances on writes, which is the next slice.
//
// Curve note: the commit block carries our secp256k1 sig (millipds uses P-256), so the
// commit CID differs from millipds — but the MST + record blocks are curve-independent
// and byte-identical to millipds output (verified against the golden CAR).

import * as dagCbor from '@ipld/dag-cbor'
import { buildMst, reachableBlocks } from 'atproto-repo/lib/mst.js'
import { unsignedCommit, signCommit, commitCid } from 'atproto-repo/lib/commit.js'
import { cidForBytesSync } from 'atproto-repo/lib/cid.js'
import { writeCar } from 'atproto-repo/lib/repo.js'

// Build every block of the repo from the store's exact bytes (no re-encode).
async function assembleRepo (store, { did, rev, prev = null, privateKey }) {
  const recs = await store.records() // [{ key, bytes, record }]
  const recordBlocks = []
  const mstRecords = []
  for (const r of recs) {
    const cid = cidForBytesSync(r.bytes)
    recordBlocks.push({ cid, bytes: r.bytes })
    mstRecords.push({ key: r.key, value: cid })
  }
  const { root: dataCid, ns } = buildMst(mstRecords)
  const mstBlocks = [...reachableBlocks(ns, dataCid).values()]
  const signed = signCommit(unsignedCommit({ did, rev, data: dataCid, prev }), privateKey)
  const cCid = commitCid(signed)
  const commitBlock = { cid: cCid, bytes: dagCbor.encode(signed) }
  return { commitCid: cCid, dataCid, signedCommit: signed, commitBlock, mstBlocks, recordBlocks }
}

// com.atproto.sync.getRepo -> full CAR (commit + MST + records).
export async function getRepo (store, meta) {
  const r = await assembleRepo(store, meta)
  const carBytes = await writeCar(r.commitCid, [r.commitBlock, ...r.mstBlocks, ...r.recordBlocks])
  return { carBytes, commitCid: r.commitCid, dataCid: r.dataCid, signedCommit: r.signedCommit }
}

// KEYLESS getRepo (peer/bridge split): assemble the full CAR from the store's records + a
// PROVIDED signed commit — e.g. one a bridge read from a peer's replicated firehose. The
// MST/records are curve-independent so they rebuild without the key; the signature travels
// IN the commit, never re-derived. Integrity: the provided commit must commit to exactly
// these records (its data CID == the rebuilt MST root), else we refuse to serve a mismatched
// repo. Signature verification (vs the peer's did:key) is the caller's concern.
export async function getRepoFromCommit (store, signedCommit) {
  const recs = await store.records()
  const recordBlocks = []
  const mstRecords = []
  for (const r of recs) {
    const cid = cidForBytesSync(r.bytes)
    recordBlocks.push({ cid, bytes: r.bytes })
    mstRecords.push({ key: r.key, value: cid })
  }
  const { root: dataCid, ns } = buildMst(mstRecords)
  if (!dataCid.equals(signedCommit.data)) {
    throw new Error('getRepoFromCommit: signed commit data CID != rebuilt MST root (repo/commit mismatch)')
  }
  const cCid = commitCid(signedCommit)
  const commitBlock = { cid: cCid, bytes: dagCbor.encode(signedCommit) }
  const mstBlocks = [...reachableBlocks(ns, dataCid).values()]
  const carBytes = await writeCar(cCid, [commitBlock, ...mstBlocks, ...recordBlocks])
  return { carBytes, commitCid: cCid, dataCid }
}

// com.atproto.sync.getLatestCommit -> { cid, rev }.
export async function getLatestCommit (store, meta) {
  const r = await assembleRepo(store, meta)
  return { cid: r.commitCid.toString(), rev: r.signedCommit.rev }
}

// com.atproto.repo.getRecord -> { uri, cid, value }.
export async function getRecord (store, collection, rkey, { did }) {
  const raw = await store.getRaw(collection, rkey)
  if (!raw) return null
  return {
    uri: `at://${did}/${collection}/${rkey}`,
    cid: cidForBytesSync(raw.bytes).toString(),
    value: raw.record
  }
}

// com.atproto.repo.listRecords -> [{ uri, cid, value }] for a collection.
// com.atproto.repo.listRecords. `limit`, `reverse` and `cursor` were ACCEPTED AND IGNORED, so every
// caller silently got the whole collection in ascending order no matter what it asked for — a client
// paging our repo would loop forever on a cursor that never advanced, and one asking for the newest 10
// would get the oldest N thousand. Non-conformance that looks like success is the worst kind.
//
// The lexicon's contract, implemented here:
//   limit    1..100, default 50
//   reverse  true = DESCENDING rkey order (newest first for TID rkeys)
//   cursor   opaque; here it is the last rkey returned, and paging resumes STRICTLY after it
//   returns  { records, cursor } — cursor ABSENT when the page is the last one, which is how a client
//            knows to stop. Returning a cursor at the end is what makes a pager loop.
export async function listRecords (store, collection, { did, limit = 50, reverse = false, cursor = null } = {}) {
  const n = Math.min(100, Math.max(1, Number(limit) || 50))
  // store.list yields in ascending key (byte) order — the same order the MST uses.
  const all = []
  for await (const { rkey, record } of store.list(collection)) all.push({ rkey, record })
  if (reverse) all.reverse()
  let start = 0
  if (cursor) {
    // Resume strictly AFTER the cursor. `>` not `>=`, or the cursor row is returned twice and a pager
    // that dedupes by uri silently stalls instead of advancing.
    const i = all.findIndex((r) => r.rkey === cursor)
    start = i >= 0 ? i + 1 : all.length
  }
  const page = all.slice(start, start + n)
  const records = page.map(({ rkey, record }) => ({
    uri: `at://${did}/${collection}/${rkey}`,
    // NOTE: this CIDs a re-encode of the decoded record, not the stored bytes. A canonical DAG-CBOR
    // round-trip is byte-identical so this is correct today, but getRaw would be strictly safer — the
    // 2026-07-31 incidents were all re-encode-vs-canonical mismatches. Left as-is rather than widened
    // here; worth revisiting with a raw-bytes list().
    cid: cidForBytesSync(dagCbor.encode(record)).toString(),
    value: record
  }))
  const last = page.length ? page[page.length - 1].rkey : null
  // No cursor on the final page — its ABSENCE is the stop signal.
  const more = start + page.length < all.length
  return { records, cursor: more && last ? last : undefined }
}
// atproto TID — the 13-char, lexicographically-sortable timestamp id used for `rev`
// (and default rkeys). value = (unixMicros << 10) | clockId(10 bits), top bit 0,
// encoded in the sortable base32 alphabet. Monotonic within a process.

const S32 = '234567abcdefghijklmnopqrstuvwxyz' // atproto sortable base32

function s32encode (n) {
  let s = ''
  for (let i = 0; i < 13; i++) { s = S32[Number(n % 32n)] + s; n /= 32n }
  return s
}

let _last = 0n

// clock() returns micros; injectable for deterministic tests.
export function tidNow (clockId = 0, clock = () => BigInt(Date.now()) * 1000n) {
  let micros = clock()
  const val = (micros << 10n) | (BigInt(clockId) & 0x3ffn)
  const t = val > _last ? val : _last + 1n // strictly monotonic
  _last = t
  return s32encode(t)
}

export function isValidTid (s) {
  return typeof s === 'string' && s.length === 13 && [...s].every(c => S32.includes(c))
}

// The micros component of a TID (drops the 10-bit clock id).
export function tidMicros (tid) {
  let n = 0n
  for (const ch of String(tid)) n = (n << 5n) | BigInt(S32.indexOf(ch))
  return n >> 10n
}

// The DETERMINISTIC next rev after `prevRev` — a pure function of the previous rev, never the
// wall clock. This is what makes the atproto chain indexer-agnostic: two co-owners continuing
// from the SAME head over the SAME finalized record set produce byte-identical commits (RFC6979
// signing is deterministic), so concurrent signers are idempotent rather than forking. Mirrors
// atproto-base/lib/rev.js byte-for-byte (clockId 0) so both implementations agree exactly.
export function nextRev (prevRev) {
  return s32encode((tidMicros(prevRev) + 1n) << 10n)
}
const { Pull, Push, HEADERBYTES, KEYBYTES, ABYTES } = require('sodium-secretstream')
const sodium = require('sodium-universal')
const crypto = require('hypercore-crypto')
const { Duplex, Writable, getStreamError } = require('streamx')
const b4a = require('b4a')
const Timeout = require('timeout-refresh')
const unslab = require('unslab')
const Bridge = require('./lib/bridge')
const Handshake = require('./lib/handshake')

const IDHEADERBYTES = HEADERBYTES + 32
const [NS_INITIATOR, NS_RESPONDER, NS_SEND] = crypto.namespace('hyperswarm/secret-stream', 3)
const MAX_ATOMIC_WRITE = 256 * 256 * 256 - 1

module.exports = class NoiseSecretStream extends Duplex {
  constructor(isInitiator, rawStream, opts = {}) {
    super({ mapWritable: toBuffer })

    if (typeof isInitiator !== 'boolean') {
      throw new Error('isInitiator should be a boolean')
    }

    this.noiseStream = this
    this.isInitiator = isInitiator
    this.rawStream = null

    this.publicKey = opts.publicKey || null
    this.remotePublicKey = opts.remotePublicKey || null
    this.handshakeHash = null
    this.connected = false
    this.keepAlive = opts.keepAlive || 0
    this.timeout = 0
    this.enableSend = opts.enableSend !== false

    // pointer for upstream to set data here if they want
    this.userData = null

    let openedDone = null
    this.opened = new Promise((resolve) => {
      openedDone = resolve
    })

    this.rawBytesWritten = 0
    this.rawBytesRead = 0

    // metadata used by 'hyperdht'
    this.relay = null
    this.puncher = null

    // unwrapped raw stream
    this._rawStream = null

    // handshake state
    this._handshake = null
    this._handshakePattern = opts.pattern || null
    this._handshakeDone = null

    // message parsing state
    this._state = 0
    this._len = 0
    this._tmp = 1
    this._message = null

    this._openedDone = openedDone
    this._startDone = null
    this._drainDone = null
    this._outgoingPlain = null
    this._outgoingWrapped = null
    this._utp = null
    this._setup = true
    this._ended = 2
    this._encrypt = null
    this._decrypt = null
    this._timeoutTimer = null
    this._keepAliveTimer = null
    this._sendState = null

    if (opts.autoStart !== false) this.start(rawStream, opts)

    // wiggle it to trigger open immediately (TODO add streamx option for this)
    this.resume()
    this.pause()
  }

  static keyPair(seed) {
    return Handshake.keyPair(seed)
  }

  static id(handshakeHash, isInitiator, id) {
    return streamId(handshakeHash, isInitiator, id)
  }

  setTimeout(ms) {
    if (!ms) ms = 0

    this._clearTimeout()
    this.timeout = ms

    if (!ms || this.rawStream === null) return

    this._timeoutTimer = Timeout.once(ms, destroyTimeout, this)
    this._timeoutTimer.unref()
  }

  setKeepAlive(ms) {
    if (!ms) ms = 0

    this._clearKeepAlive()

    this.keepAlive = ms

    if (!ms || this.rawStream === null) return

    this._keepAliveTimer = Timeout.on(ms, sendKeepAlive, this)
    this._keepAliveTimer.unref()
  }

  sendKeepAlive() {
    const empty = this.alloc(0)
    this.write(empty)
  }

  start(rawStream, opts = {}) {
    if (rawStream) {
      this.rawStream = rawStream
      this._rawStream = rawStream
      if (typeof this.rawStream.setContentSize === 'function') {
        this._utp = rawStream
      }
    } else {
      this.rawStream = new Bridge(this)
      this._rawStream = this.rawStream.reverse
    }

    this.rawStream.on('error', this._onrawerror.bind(this))
    this.rawStream.on('close', this._onrawclose.bind(this))

    this._startHandshake(opts.handshake, opts.keyPair || null)
    this._continueOpen(null)

    if (this.destroying) return

    if (opts.data) this._onrawdata(opts.data)
    if (opts.ended) this._onrawend()

    if (this.keepAlive > 0 && this._keepAliveTimer === null) {
      this.setKeepAlive(this.keepAlive)
    }

    if (this.timeout > 0 && this._timeoutTimer === null) {
      this.setTimeout(this.timeout)
    }
  }

  async flush() {
    if ((await this.opened) === false) return false
    if ((await Writable.drained(this)) === false) return false
    if (this.destroying) return false

    if (this.rawStream !== null && this.rawStream.flush) {
      return await this.rawStream.flush()
    }

    return true
  }

  _continueOpen(err) {
    if (err) this.destroy(err)
    if (this._startDone === null) return
    const done = this._startDone
    this._startDone = null
    this._open(done)
  }

  _onkeypairpromise(p) {
    const self = this
    const cont = this._continueOpen.bind(this)

    p.then(onkeypair, cont)

    function onkeypair(kp) {
      self._onkeypair(kp)
      cont(null)
    }
  }

  _onkeypair(keyPair) {
    const pattern = this._handshakePattern || 'XX'
    const remotePublicKey = this.remotePublicKey

    this._handshake = new Handshake(this.isInitiator, keyPair, remotePublicKey, pattern)
    this.publicKey = this._handshake.keyPair.publicKey
  }

  _startHandshake(handshake, keyPair) {
    if (handshake) {
      const { tx, rx, hash, publicKey, remotePublicKey } = handshake
      this._setupSecretStream(tx, rx, hash, publicKey, remotePublicKey)
      return
    }

    if (!keyPair) keyPair = Handshake.keyPair()

    if (typeof keyPair.then === 'function') {
      this._onkeypairpromise(keyPair)
    } else {
      this._onkeypair(keyPair)
    }
  }

  _onrawerror(err) {
    this.destroy(err)
  }

  _onrawclose() {
    if (this._ended !== 0) this.destroy()
  }

  _onrawdata(data) {
    let offset = 0

    if (this._timeoutTimer !== null) {
      this._timeoutTimer.refresh()
    }

    do {
      switch (this._state) {
        case 0: {
          while (this._tmp !== 0x1000000 && offset < data.byteLength) {
            const v = data[offset++]
            this._len += this._tmp * v
            this._tmp *= 256
          }

          if (this._tmp === 0x1000000) {
            this._tmp = 0
            this._state = 1
            const unprocessed = data.byteLength - offset
            if (unprocessed < this._len && this._utp !== null)
              this._utp.setContentSize(this._len - unprocessed)
          }

          break
        }

        case 1: {
          const missing = this._len - this._tmp
          const end = missing + offset

          if (this._message === null && end <= data.byteLength) {
            this._message = data.subarray(offset, end)
            offset += missing
            this._incoming()
            break
          }

          const unprocessed = data.byteLength - offset

          if (this._message === null) {
            this._message = b4a.allocUnsafe(this._len)
          }

          b4a.copy(data, this._message, this._tmp, offset)
          this._tmp += unprocessed

          if (end <= data.byteLength) {
            offset += missing
            this._incoming()
          } else {
            offset += unprocessed
          }

          break
        }
      }
    } while (offset < data.byteLength && !this.destroying)
  }

  _onrawend() {
    this._ended--
    this.push(null)
  }

  _onrawdrain() {
    const drain = this._drainDone
    if (drain === null) return
    this._drainDone = null
    drain()
  }

  _read(cb) {
    this.rawStream.resume()
    cb(null)
  }

  _incoming() {
    const message = this._message

    this._state = 0
    this._len = 0
    this._tmp = 1
    this._message = null

    if (this._setup === true) {
      if (this._handshake) {
        this._onhandshakert(this._handshake.recv(message))
      } else {
        if (message.byteLength !== IDHEADERBYTES) {
          this.destroy(new Error('Invalid header message received'))
          return
        }

        const remoteId = message.subarray(0, 32)
        const expectedId = streamId(this.handshakeHash, !this.isInitiator)
        const header = message.subarray(32)

        if (!b4a.equals(expectedId, remoteId)) {
          this.destroy(new Error('Invalid header received'))
          return
        }

        this._decrypt.init(header)
        this._setup = false // setup is now done
      }
      return
    }

    if (message.byteLength < ABYTES) {
      this.destroy(new Error('Invalid message received'))
      return
    }

    this.rawBytesRead += message.byteLength

    const plain = message.subarray(1, message.byteLength - ABYTES + 1)

    try {
      this._decrypt.next(message, plain)
    } catch (err) {
      this.destroy(err)
      return
    }

    // If keep alive is selective, eat the empty buffers (ie assume the other side has it enabled also)
    if (plain.byteLength === 0 && this.keepAlive !== 0) return

    if (this.push(plain) === false) {
      this.rawStream.pause()
    }
  }

  _onhandshakert(h) {
    if (this._handshakeDone === null) return

    if (h !== null) {
      if (h.data) this._rawStream.write(h.data)
      if (!h.tx) return
    }

    const done = this._handshakeDone
    const publicKey = this._handshake.keyPair.publicKey

    this._handshakeDone = null
    this._handshake = null

    if (h === null) return done(new Error('Noise handshake failed'))

    this._setupSecretStream(h.tx, h.rx, h.hash, publicKey, h.remotePublicKey)
    this._resolveOpened(true)
    done(null)
  }

  _setupSecretStream(tx, rx, handshakeHash, publicKey, remotePublicKey) {
    const buf = b4a.allocUnsafeSlow(3 + IDHEADERBYTES)
    writeUint24le(IDHEADERBYTES, buf)

    this._encrypt = new Push(unslab(tx.subarray(0, KEYBYTES)), undefined, buf.subarray(3 + 32))
    this._decrypt = new Pull(unslab(rx.subarray(0, KEYBYTES)))

    this.publicKey = publicKey
    this.remotePublicKey = remotePublicKey
    this.handshakeHash = handshakeHash

    const id = buf.subarray(3, 3 + 32)
    streamId(handshakeHash, this.isInitiator, id)

    // initialize secretbox state for unordered messages
    this._setupSecretSend(handshakeHash)

    this.emit('handshake')
    // if rawStream is a bridge, also emit it there
    if (this.rawStream !== this._rawStream) this.rawStream.emit('handshake')

    if (this.destroying) return

    this._rawStream.write(buf)
  }

  _setupSecretSend(handshakeHash) {
    this._sendState = b4a.allocUnsafeSlow(32 + 32 + 8 + 8)
    const encrypt = this._sendState.subarray(0, 32) // secrets
    const decrypt = this._sendState.subarray(32, 64)
    const counter = this._sendState.subarray(64, 72) // nonce
    const initial = this._sendState.subarray(72)

    const inputs = this.isInitiator
      ? [
          [NS_INITIATOR, NS_SEND],
          [NS_RESPONDER, NS_SEND]
        ]
      : [
          [NS_RESPONDER, NS_SEND],
          [NS_INITIATOR, NS_SEND]
        ]

    sodium.crypto_generichash_batch(encrypt, inputs[0], handshakeHash)
    sodium.crypto_generichash_batch(decrypt, inputs[1], handshakeHash)

    sodium.randombytes_buf(initial)
    counter.set(initial)
  }

  _open(cb) {
    // no autostart or no handshake yet
    if (this._rawStream === null || (this._handshake === null && this._encrypt === null)) {
      this._startDone = cb
      return
    }

    this._rawStream.on('data', this._onrawdata.bind(this))
    this._rawStream.on('end', this._onrawend.bind(this))
    this._rawStream.on('drain', this._onrawdrain.bind(this))

    if (this.enableSend) this._rawStream.on('message', this._onmessage.bind(this))

    if (this._encrypt !== null) {
      this._resolveOpened(true)
      return cb(null)
    }

    this._handshakeDone = cb

    if (this.isInitiator) this._onhandshakert(this._handshake.send())
  }

  _predestroy() {
    if (this.rawStream) {
      const error = getStreamError(this)
      this.rawStream.destroy(error)
    }

    if (this._startDone !== null) {
      const done = this._startDone
      this._startDone = null
      done(new Error('Stream destroyed'))
    }

    if (this._handshakeDone !== null) {
      const done = this._handshakeDone
      this._handshakeDone = null
      done(new Error('Stream destroyed'))
    }

    if (this._drainDone !== null) {
      const done = this._drainDone
      this._drainDone = null
      done(new Error('Stream destroyed'))
    }
  }

  _write(data, cb) {
    let wrapped = this._outgoingWrapped

    if (data !== this._outgoingPlain) {
      wrapped = b4a.allocUnsafe(data.byteLength + 3 + ABYTES)
      wrapped.set(data, 4)
    } else {
      this._outgoingWrapped = this._outgoingPlain = null
    }

    if (wrapped.byteLength - 3 > MAX_ATOMIC_WRITE) {
      return cb(
        new Error(
          'Message is too large for an atomic write. Max size is ' + MAX_ATOMIC_WRITE + ' bytes.'
        )
      )
    }
    this.rawBytesWritten += wrapped.byteLength

    writeUint24le(wrapped.byteLength - 3, wrapped)
    // offset 4 so we can do it in-place
    this._encrypt.next(wrapped.subarray(4, 4 + data.byteLength), wrapped.subarray(3))

    if (this._keepAliveTimer !== null) this._keepAliveTimer.refresh()

    if (this._rawStream.write(wrapped) === false) {
      this._drainDone = cb
    } else {
      cb(null)
    }
  }

  _final(cb) {
    this._clearKeepAlive()
    this._ended--
    this._rawStream.end()
    cb(null)
  }

  _resolveOpened(val) {
    if (this._openedDone === null) return
    const opened = this._openedDone
    this._openedDone = null
    opened(val)
    if (!val) return
    this.connected = true
    this.emit('connect')
  }

  _clearTimeout() {
    if (this._timeoutTimer === null) return
    this._timeoutTimer.destroy()
    this._timeoutTimer = null
    this.timeout = 0
  }

  _clearKeepAlive() {
    if (this._keepAliveTimer === null) return
    this._keepAliveTimer.destroy()
    this._keepAliveTimer = null
    this.keepAlive = 0
  }

  _destroy(cb) {
    this._clearKeepAlive()
    this._clearTimeout()
    this._resolveOpened(false)
    cb(null)
  }

  _boxMessage(buffer) {
    const MB = sodium.crypto_secretbox_MACBYTES // 16
    const NB = sodium.crypto_secretbox_NONCEBYTES // 24

    const counter = this._sendState.subarray(64, 72)
    sodium.sodium_increment(counter)
    if (b4a.equals(counter, this._sendState.subarray(72))) {
      this.destroy(new Error('udp send nonce exchausted'))
      return
    }

    const secret = this._sendState.subarray(0, 32)
    const envelope = b4a.allocUnsafe(8 + MB + buffer.byteLength)
    const nonce = envelope.subarray(0, NB)
    const ciphertext = envelope.subarray(8)

    b4a.fill(nonce, 0) // pad suffix
    nonce.set(counter)

    sodium.crypto_secretbox_easy(ciphertext, buffer, nonce, secret)
    return envelope
  }

  send(buffer) {
    if (!this._sendState) return
    if (!this.rawStream?.send) return // udx-stream expected

    const message = this._boxMessage(buffer)
    return this.rawStream.send(message)
  }

  trySend(buffer) {
    if (!this._sendState) return
    if (!this.rawStream?.trySend) return // udx-stream expected

    const message = this._boxMessage(buffer)
    this.rawStream.trySend(message)
  }

  _onmessage(buffer) {
    if (!this._sendState) return // messages before handshake are dropped

    const MB = sodium.crypto_secretbox_MACBYTES // 16
    const NB = sodium.crypto_secretbox_NONCEBYTES // 24

    if (buffer.byteLength < NB) return // Invalid message

    const nonce = b4a.allocUnsafe(NB)
    b4a.fill(nonce, 0)
    nonce.set(buffer.subarray(0, 8))

    const secret = this._sendState.subarray(32, 64)
    const ciphertext = buffer.subarray(8)
    const plain = buffer.subarray(8, buffer.byteLength - MB)

    if (ciphertext.byteLength < MB) return // invalid message

    const success = sodium.crypto_secretbox_open_easy(plain, ciphertext, nonce, secret)

    if (success) this.emit('message', plain)
  }

  alloc(len) {
    const buf = b4a.allocUnsafe(len + 3 + ABYTES)
    this._outgoingWrapped = buf
    this._outgoingPlain = buf.subarray(4, buf.byteLength - ABYTES + 1)
    return this._outgoingPlain
  }

  toJSON() {
    return {
      isInitiator: this.isInitiator,
      publicKey: this.publicKey && b4a.toString(this.publicKey, 'hex'),
      remotePublicKey: this.remotePublicKey && b4a.toString(this.remotePublicKey, 'hex'),
      connected: this.connected,
      destroying: this.destroying,
      destroyed: this.destroyed,
      rawStream: this.rawStream && this.rawStream.toJSON ? this.rawStream.toJSON() : null
    }
  }
}

function writeUint24le(n, buf) {
  buf[0] = n & 255
  buf[1] = (n >>> 8) & 255
  buf[2] = (n >>> 16) & 255
}

function streamId(handshakeHash, isInitiator, out = b4a.allocUnsafe(32)) {
  sodium.crypto_generichash(out, isInitiator ? NS_INITIATOR : NS_RESPONDER, handshakeHash)
  return out
}

function toBuffer(data) {
  return typeof data === 'string' ? b4a.from(data) : data
}

function destroyTimeout() {
  this.destroy(new Error('Stream timed out'))
}

function sendKeepAlive() {
  const empty = this.alloc(0)
  this.write(empty)
}
const { Duplex, Writable } = require('streamx')

class ReversePassThrough extends Duplex {
  constructor(s) {
    super()
    this._stream = s
    this._ondrain = null
  }

  _write(data, cb) {
    if (this._stream.push(data) === false) {
      this._stream._ondrain = cb
    } else {
      cb(null)
    }
  }

  _final(cb) {
    this._stream.push(null)
    cb(null)
  }

  _read(cb) {
    const ondrain = this._ondrain
    this._ondrain = null
    if (ondrain) ondrain()
    cb(null)
  }
}

module.exports = class Bridge extends Duplex {
  constructor(noiseStream) {
    super()

    this.noiseStream = noiseStream

    this._ondrain = null
    this.reverse = new ReversePassThrough(this)
  }

  get publicKey() {
    return this.noiseStream.publicKey
  }

  get remotePublicKey() {
    return this.noiseStream.remotePublicKey
  }

  get handshakeHash() {
    return this.noiseStream.handshakeHash
  }

  flush() {
    return Writable.drained(this)
  }

  _read(cb) {
    const ondrain = this._ondrain
    this._ondrain = null
    if (ondrain) ondrain()
    cb(null)
  }

  _write(data, cb) {
    if (this.reverse.push(data) === false) {
      this.reverse._ondrain = cb
    } else {
      cb(null)
    }
  }

  _final(cb) {
    this.reverse.push(null)
    cb(null)
  }
}
const sodium = require('sodium-universal')
const curve = require('noise-curve-ed')
const Noise = require('noise-handshake')
const b4a = require('b4a')

const EMPTY = b4a.alloc(0)

module.exports = class Handshake {
  constructor(isInitiator, keyPair, remotePublicKey, pattern) {
    this.isInitiator = isInitiator
    this.keyPair = keyPair
    this.noise = new Noise(pattern, isInitiator, keyPair, { curve })
    this.noise.initialise(EMPTY, remotePublicKey)
    this.destroyed = false
  }

  static keyPair(seed) {
    const publicKey = b4a.alloc(32)
    const secretKey = b4a.alloc(64)
    if (seed) sodium.crypto_sign_seed_keypair(publicKey, secretKey, seed)
    else sodium.crypto_sign_keypair(publicKey, secretKey)
    return { publicKey, secretKey }
  }

  recv(data) {
    try {
      this.noise.recv(data)
      if (this.noise.complete) return this._return(null)
      return this.send()
    } catch {
      this.destroy()
      return null
    }
  }

  // note that the data returned here is framed so we don't have to do an extra copy
  // when sending it...
  send() {
    try {
      const data = this.noise.send()
      const wrap = b4a.allocUnsafe(data.byteLength + 3)

      writeUint24le(data.byteLength, wrap)
      wrap.set(data, 3)

      return this._return(wrap)
    } catch {
      this.destroy()
      return null
    }
  }

  destroy() {
    if (this.destroyed) return
    this.destroyed = true
  }

  _return(data) {
    const tx = this.noise.complete ? b4a.toBuffer(this.noise.tx) : null
    const rx = this.noise.complete ? b4a.toBuffer(this.noise.rx) : null
    const hash = this.noise.complete ? b4a.toBuffer(this.noise.hash) : null
    const remotePublicKey = this.noise.complete ? b4a.toBuffer(this.noise.rs) : null

    return {
      data,
      remotePublicKey,
      hash,
      tx,
      rx
    }
  }
}

function writeUint24le(n, buf) {
  buf[0] = n & 255
  buf[1] = (n >>> 8) & 255
  buf[2] = (n >>> 16) & 255
}
{
  "name": "@hyperswarm/secret-stream",
  "version": "6.9.1",
  "description": "Secret stream backed by Noise and libsodium's secretstream",
  "main": "index.js",
  "files": [
    "index.js",
    "lib/**.js"
  ],
  "dependencies": {
    "b4a": "^1.1.0",
    "hypercore-crypto": "^3.3.1",
    "noise-curve-ed": "^2.0.1",
    "noise-handshake": "^4.0.0",
    "sodium-secretstream": "^1.1.0",
    "sodium-universal": "^5.0.0",
    "streamx": "^2.14.0",
    "timeout-refresh": "^2.0.0",
    "unslab": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "udx-native": "^1.13.2"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check .",
    "test": "brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/hyperswarm-secret-stream.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/hyperswarm-secret-stream/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperswarm-secret-stream"
}
{
  "name": "@ipld/dag-cbor",
  "version": "9.2.7",
  "description": "JS implementation of DAG-CBOR",
  "author": "Rod <rod@vagg.org> (http://r.va.gg/)",
  "license": "Apache-2.0 OR MIT",
  "homepage": "https://github.com/ipld/js-dag-cbor#readme",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/ipld/js-dag-cbor.git"
  },
  "bugs": {
    "url": "https://github.com/ipld/js-dag-cbor/issues"
  },
  "publishConfig": {
    "access": "public",
    "provenance": true
  },
  "keywords": [
    "ipfs",
    "ipld",
    "multiformats"
  ],
  "type": "module",
  "types": "./dist/src/index.d.ts",
  "typesVersions": {
    "*": {
      "*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ],
      "src/*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ]
    }
  },
  "files": [
    "src",
    "dist",
    "!dist/test",
    "!**/*.tsbuildinfo"
  ],
  "exports": {
    ".": {
      "types": "./dist/src/index.d.ts",
      "import": "./src/index.js",
      "module-sync": "./src/index.js"
    }
  },
  "release": {
    "branches": [
      "master"
    ],
    "plugins": [
      [
        "@semantic-release/commit-analyzer",
        {
          "preset": "conventionalcommits",
          "releaseRules": [
            {
              "breaking": true,
              "release": "major"
            },
            {
              "revert": true,
              "release": "patch"
            },
            {
              "type": "feat",
              "release": "minor"
            },
            {
              "type": "fix",
              "release": "patch"
            },
            {
              "type": "docs",
              "release": "patch"
            },
            {
              "type": "test",
              "release": "patch"
            },
            {
              "type": "deps",
              "release": "patch"
            },
            {
              "scope": "no-release",
              "release": false
            }
          ]
        }
      ],
      [
        "@semantic-release/release-notes-generator",
        {
          "preset": "conventionalcommits",
          "presetConfig": {
            "types": [
              {
                "type": "feat",
                "section": "Features"
              },
              {
                "type": "fix",
                "section": "Bug Fixes"
              },
              {
                "type": "chore",
                "section": "Trivial Changes"
              },
              {
                "type": "docs",
                "section": "Documentation"
              },
              {
                "type": "deps",
                "section": "Dependencies"
              },
              {
                "type": "test",
                "section": "Tests"
              }
            ]
          }
        }
      ],
      "@semantic-release/changelog",
      "@semantic-release/npm",
      "@semantic-release/github",
      [
        "@semantic-release/git",
        {
          "assets": [
            "CHANGELOG.md",
            "package.json"
          ]
        }
      ]
    ]
  },
  "scripts": {
    "clean": "aegir clean",
    "lint": "aegir lint",
    "build": "aegir build",
    "release": "aegir release",
    "test": "npm run lint && aegir test",
    "test:ts": "npm run test --prefix test/ts-use",
    "test:node": "aegir test -t node --cov",
    "test:chrome": "aegir test -t browser --cov",
    "test:chrome-webworker": "aegir test -t webworker",
    "test:firefox": "aegir test -t browser -- --browser firefox",
    "test:firefox-webworker": "aegir test -t webworker -- --browser firefox",
    "test:electron-main": "aegir test -t electron-main",
    "dep-check": "aegir dep-check"
  },
  "dependencies": {
    "cborg": "^5.0.1",
    "multiformats": "^13.1.0"
  },
  "devDependencies": {
    "@ipld/garbage": "^6.0.0",
    "aegir": "^48.0.1"
  }
}
import * as cborg from 'cborg'
import { CID } from 'multiformats/cid'

// https://github.com/ipfs/go-ipfs/issues/3570#issuecomment-273931692
const CID_CBOR_TAG = 42

/**
 * @template T
 * @typedef {import('multiformats/codecs/interface').ByteView<T>} ByteView
 */

/**
 * @template T
 * @typedef {import('multiformats/codecs/interface').ArrayBufferView<T>} ArrayBufferView
 */

/**
 * @template T
 * @param {ByteView<T> | ArrayBufferView<T>} buf
 * @returns {ByteView<T>}
 */
export function toByteView (buf) {
  if (buf instanceof ArrayBuffer) {
    return new Uint8Array(buf, 0, buf.byteLength)
  }

  return buf
}

/**
 * cidEncoder will receive all Objects during encode, it needs to filter out
 * anything that's not a CID and return `null` for that so it's encoded as
 * normal.
 *
 * @param {any} obj
 * @returns {cborg.Token[]|null}
 */
function cidEncoder (obj) {
  if (obj.asCID !== obj && obj['/'] !== obj.bytes) {
    return null // any other kind of object
  }
  const cid = CID.asCID(obj)
  /* c8 ignore next 4 */
  // very unlikely case, and it'll probably throw a recursion error in cborg
  if (!cid) {
    return null
  }
  const bytes = new Uint8Array(cid.bytes.byteLength + 1)
  bytes.set(cid.bytes, 1) // prefix is 0x00, for historical reasons
  return [
    new cborg.Token(cborg.Type.tag, CID_CBOR_TAG),
    new cborg.Token(cborg.Type.bytes, bytes)
  ]
}

// eslint-disable-next-line jsdoc/require-returns-check
/**
 * Intercept all `undefined` values from an object walk and reject the entire
 * object if we find one.
 *
 * @returns {null}
 */
function undefinedEncoder () {
  throw new Error('`undefined` is not supported by the IPLD Data Model and cannot be encoded')
}

/**
 * Intercept all `number` values from an object walk and reject the entire
 * object if we find something that doesn't fit the IPLD data model (NaN &
 * Infinity).
 *
 * @param {number} num
 * @returns {null}
 */
function numberEncoder (num) {
  if (Number.isNaN(num)) {
    throw new Error('`NaN` is not supported by the IPLD Data Model and cannot be encoded')
  }
  if (num === Infinity || num === -Infinity) {
    throw new Error('`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded')
  }
  return null
}

/**
 * @param {Map<any, any>} map
 * @returns {null}
 */
function mapEncoder (map) {
  for (const key of map.keys()) {
    if (typeof key !== 'string' || key.length === 0) {
      throw new Error('Non-string Map keys are not supported by the IPLD Data Model and cannot be encoded')
    }
  }
  return null
}

const _encodeOptions = {
  float64: true,
  typeEncoders: {
    Map: mapEncoder,
    Object: cidEncoder,
    undefined: undefinedEncoder,
    number: numberEncoder
  }
}

export const encodeOptions = {
  ..._encodeOptions,
  typeEncoders: {
    ..._encodeOptions.typeEncoders
  }
}

/**
 * @param {import('cborg').TagDecodeControl} decode
 * @returns {CID}
 */
function cidDecoder (decode) {
  const bytes = /** @type {Uint8Array} */ (decode())
  if (bytes[0] !== 0) {
    throw new Error('Invalid CID for CBOR tag 42; expected leading 0x00')
  }
  return CID.decode(bytes.subarray(1)) // ignore leading 0x00
}

const _decodeOptions = {
  allowIndefinite: false,
  coerceUndefinedToNull: true,
  allowNaN: false,
  allowInfinity: false,
  allowBigInt: true, // this will lead to BigInt for ints outside of
  // safe-integer range, which may surprise users
  strict: true,
  useMaps: false,
  rejectDuplicateMapKeys: true,
  /** @type {{ [tagNumber: number]: import('cborg').TagDecoder }} */
  tags: { [CID_CBOR_TAG]: cidDecoder }
}

export const decodeOptions = {
  ..._decodeOptions,
  tags: { ..._decodeOptions.tags }
}

export const name = 'dag-cbor'
export const code = 0x71

/**
 * @template T
 * @param {T} node
 * @returns {ByteView<T>}
 */
export const encode = (node) => cborg.encode(node, _encodeOptions)

/**
 * @template T
 * @param {ByteView<T> | ArrayBufferView<T>} data
 * @returns {T}
 */
export const decode = (data) => cborg.decode(toByteView(data), _decodeOptions)
// Minimal CAR v1 codec — bare-safe, dependency-light replacement for @ipld/car.
//
// CAR v1 is a trivial container: varint(headerLen) ++ dag-cbor({version:1, roots:[…]})
// then, per block, varint(len) ++ CIDbytes ++ blockBytes. We only need whole-buffer
// read/write (no streaming, no file I/O), so this is ~40 lines of pure JS over
// multiformats' CID (byte-exact with @ipld/car — verified by the repo tests + the
// @atproto/repo conformance reader). Drops @ipld/car (which imports `fs`/streams and
// won't load under Bare).
//
// ⚠️ LIMITATIONS vs @ipld/car (tracked in memory: bare-car-limitations). Fine for our
// current use (whole-buffer, CARv1, OUR-OWN trusted output); add the feature before the
// gate it guards:
//   - No streaming — whole CAR is buffered in memory. GATE: large repos (getRepo of a
//     big repo could be GBs). Add an async-iterator read/write path.
//   - No untrusted-input hardening — readCar trusts varints/lengths/CIDs. GATE: reading
//     UNTRUSTED CARs (com.atproto.repo.importRepo, ingress bridge). Add bounds/overflow/
//     truncation checks + duplicate-CID handling before then.
//   - CARv1 only (no CARv2/index). atproto is CARv1, so no gate today.
// Fully-featured path: grow this file at each gate, OR extract a standalone bare-native
// `bare-car` package (the holepunch ecosystem lacks one — a real contribution).

import { CID } from 'multiformats/cid'
import * as dagCbor from '@ipld/dag-cbor'

function varintEncode (n) {
  const out = []
  while (n >= 0x80) { out.push((n & 0x7f) | 0x80); n >>>= 7 }
  out.push(n)
  return Uint8Array.from(out)
}

function varintDecode (bytes, offset) {
  let n = 0; let shift = 0; let i = offset
  for (;;) {
    const b = bytes[i++]
    n |= (b & 0x7f) << shift
    if ((b & 0x80) === 0) break
    shift += 7
  }
  return [n >>> 0, i]
}

// Serialise { root, blocks } to CAR bytes. `blocks` is an iterable of { cid, bytes }.
export async function writeCar (rootCid, blocks) {
  const header = dagCbor.encode({ version: 1, roots: [rootCid] })
  const parts = [Buffer.from(varintEncode(header.length)), Buffer.from(header)]
  for (const { cid, bytes } of blocks) {
    const cidBytes = cid.bytes
    const body = new Uint8Array(cidBytes.length + bytes.length)
    body.set(cidBytes, 0)
    body.set(bytes, cidBytes.length)
    parts.push(Buffer.from(varintEncode(body.length)), Buffer.from(body))
  }
  return Buffer.concat(parts)
}

// Read a CAR into { roots, blocks } where blocks maps cid-string -> { cid, bytes }.
export async function readCar (carBytes) {
  const bytes = carBytes instanceof Uint8Array ? carBytes : new Uint8Array(carBytes)
  let [hlen, off] = varintDecode(bytes, 0)
  const header = dagCbor.decode(bytes.subarray(off, off + hlen))
  off += hlen
  const blocks = new Map()
  while (off < bytes.length) {
    const [blen, bodyStart] = varintDecode(bytes, off)
    const end = bodyStart + blen
    const [cid, rest] = CID.decodeFirst(bytes.subarray(bodyStart, end))
    blocks.set(cid.toString(), { cid, bytes: rest })
    off = end
  }
  return { roots: header.roots, blocks }
}
// atproto block CIDs — CIDv1, dag-cbor codec (0x71), sha2-256 multihash (0x12).
// Every block in a repo (commit, MST node, record) is content-addressed this way,
// so computeCid(dag-cbor(block)) IS the block's identity. This is the anchor for
// byte-exact fidelity: if our re-encoded bytes hash to the same CID the reference
// produced, our encoding is byte-identical.

import { CID } from 'multiformats/cid'
import * as Digest from 'multiformats/hashes/digest'
import { sha256 as nobleSha256 } from '@noble/hashes/sha2'
import * as dagCbor from '@ipld/dag-cbor'
import * as raw from 'multiformats/codecs/raw'

// raw block bytes -> CID. Uses noble's pure-JS sha256 (same as the sync path) rather
// than multiformats' `crypto.subtle` path — identical CID, and no WebCrypto dependency
// (so it loads + runs under Bare, which has no crypto.subtle).
export async function cidForBytes (bytes) {
  return cidForBytesSync(bytes)
}

// Synchronous variant — needed by the recursive MST build. Same result as
// cidForBytes (CIDv1 / dag-cbor 0x71 / sha2-256 0x12), just without the async
// WebCrypto digest.
export function cidForBytesSync (bytes) {
  const digest = Digest.create(0x12, nobleSha256(bytes)) // 0x12 = sha2-256 multihash code
  return CID.createV1(dagCbor.code, digest)
}

// BLOB CID — CIDv1, RAW codec (0x55), sha2-256. atproto blobs (images/avatars) are
// content-addressed with the raw codec (opaque bytes), NOT dag-cbor. This is the CID that
// goes in a blob ref ({$type:'blob', ref:{$link:<this>}, mimeType, size}) and the key
// com.atproto.sync.getBlob serves by.
export function cidForBlobSync (bytes) {
  const digest = Digest.create(0x12, nobleSha256(bytes))
  return CID.createV1(raw.code, digest)
}

// a JS value -> its canonical dag-cbor bytes + CID
export async function cidForValue (value) {
  const bytes = dagCbor.encode(value)
  return { bytes, cid: await cidForBytes(bytes) }
}
// atproto repo commit — sign + verify.
//
// A commit is { did, version: 3, data: <MST root CID>, rev, prev, sig }. The
// signature is ECDSA-secp256k1 (low-S) over sha256(dag-cbor(unsignedCommit)), stored
// as a raw 64-byte CBOR byte string (NOT base64url — that's the did:plc genesis).
// The relay validates this sig against the DID doc's verificationMethod.

import * as dagCbor from '@ipld/dag-cbor'
import { sha256 as nobleSha256 } from '@noble/hashes/sha2'
import { secp256k1 } from '@noble/curves/secp256k1'
import { cidForBytesSync } from './cid.js'

export const REPO_VERSION = 3

// The unsigned commit (everything the signature covers).
export function unsignedCommit ({ did, rev, data, prev = null }) {
  return { did, version: REPO_VERSION, data, rev, prev }
}

// Sign an unsigned commit -> signed commit with `sig` (64 raw bytes).
export function signCommit (unsigned, privateKey) {
  const hash = nobleSha256(dagCbor.encode(unsigned))
  const sig = secp256k1.sign(hash, privateKey, { lowS: true }).toCompactRawBytes()
  return { ...unsigned, sig }
}

export function commitCid (signedCommit) {
  return cidForBytesSync(dagCbor.encode(signedCommit))
}

// Verify a signed commit against a compressed secp256k1 pubkey (33 bytes).
export function verifyCommit (signedCommit, publicKey) {
  const { sig, ...unsigned } = signedCommit
  const hash = nobleSha256(dagCbor.encode(unsigned))
  return secp256k1.verify(sig, hash, publicKey, { lowS: true })
}
// atproto MST — WRITE path (slice 2).
//
// A faithful port of millipds's `atmst` (mst/node.py + node_wrangler.py) — the exact
// code that produced our golden CAR. Byte-exactness is verified two ways: rebuilding
// the golden repo's MST, and matching atmst's own root CIDs for a multi-height tree
// (build + delete oracles). See test/mst-write.test.js.
//
// Node shape (interleaved): subtrees[0], (keys[0],vals[0]), subtrees[1], … ,subtrees[n].
// key layer = leading-zero BITS of sha256(key), // 2 (fanout 4).

import * as dagCbor from '@ipld/dag-cbor'
import { sha256 as nobleSha256 } from '@noble/hashes/sha2'
import { cidForBytesSync } from './cid.js'

const cidEq = (a, b) => (a === null || b === null) ? a === b : a.equals(b)
const replaceAt = (arr, i, v) => { const c = arr.slice(); c[i] = v; return c }
const insertAt = (arr, i, v) => arr.slice(0, i).concat([v], arr.slice(i))
const removeAt = (arr, i) => arr.slice(0, i).concat(arr.slice(i + 1))

export function keyHeight (key) {
  const h = nobleSha256(Buffer.from(key, 'utf8')) // 32 bytes
  let zeros = 0
  for (const byte of h) {
    if (byte === 0) { zeros += 8; continue }
    zeros += Math.clz32(byte) - 24 // leading zero bits within this byte
    break
  }
  return zeros >> 1 // // 2
}

export class MSTNode {
  constructor (keys, vals, subtrees) {
    this.keys = keys // [string]
    this.vals = vals // [CID]
    this.subtrees = subtrees // [CID|null], length keys.length + 1
  }

  static empty () { return new MSTNode([], [], [null]) }

  isEmpty () { return this.keys.length === 0 && this.subtrees.length === 1 && this.subtrees[0] === null }

  serialise () {
    const e = []
    let prevKey = Buffer.alloc(0)
    for (let i = 0; i < this.keys.length; i++) {
      const keyBytes = Buffer.from(this.keys[i], 'utf8')
      const max = Math.min(prevKey.length, keyBytes.length)
      let p = 0
      while (p < max && prevKey[p] === keyBytes[p]) p++
      e.push({ k: keyBytes.subarray(p), p, t: this.subtrees[i + 1], v: this.vals[i] })
      prevKey = keyBytes
    }
    return dagCbor.encode({ e, l: this.subtrees[0] }) // dag-cbor canonicalises map key order
  }

  cid () { return cidForBytesSync(this.serialise()) }

  toOptional () { return this.isEmpty() ? null : this.cid() }

  gteIndex (key) { let i = 0; while (i < this.keys.length && key > this.keys[i]) i++; return i }

  height () {
    if (this.keys.length) return keyHeight(this.keys[0])
    if (this.subtrees[0] === null) return 0
    return null // indeterminate (empty intermediate node)
  }

  static deserialise (bytes) {
    const cbor = dagCbor.decode(bytes)
    const subtrees = [cbor.l]
    const keys = []
    const vals = []
    let prevKey = Buffer.alloc(0)
    for (const e of cbor.e) {
      const suffix = Buffer.from(e.k)
      const thisKey = Buffer.concat([prevKey.subarray(0, e.p), suffix])
      keys.push(thisKey.toString('utf8'))
      vals.push(e.v)
      subtrees.push(e.t)
      prevKey = thisKey
    }
    return new MSTNode(keys, vals, subtrees)
  }
}

// In-memory node store — maps CID string -> { cid, bytes }. get(null) returns the
// (stored) empty node, matching atmst NodeStore.get_node(None).
export class NodeStore {
  constructor () { this.blocks = new Map() }

  storedNode (node) {
    const bytes = node.serialise()
    const cid = cidForBytesSync(bytes)
    this.blocks.set(cid.toString(), { cid, bytes })
    return node
  }

  getNode (cid) {
    if (cid === null || cid === undefined) return this.storedNode(MSTNode.empty())
    const b = this.blocks.get(cid.toString())
    if (!b) throw new Error(`missing MST node ${cid}`)
    return MSTNode.deserialise(b.bytes)
  }
}

export class NodeWrangler {
  constructor (ns) { this.ns = ns }

  putRecord (rootCid, key, val) {
    const root = this.ns.getNode(rootCid)
    if (root.isEmpty()) return this._putHere(root, key, val).cid()
    return this._putRecursive(root, key, val, keyHeight(key), root.height()).cid()
  }

  delRecord (rootCid, key) {
    const root = this.ns.getNode(rootCid)
    const afterDel = this._deleteRecursive(root, key, keyHeight(key), root.height())
    return this.ns.getNode(this._squashTop(afterDel)).cid()
  }

  _putHere (node, key, val) {
    const i = node.gteIndex(key)
    if (i < node.keys.length && node.keys[i] === key) {
      if (cidEq(node.vals[i], val)) return node
      return this.ns.storedNode(new MSTNode(node.keys.slice(), replaceAt(node.vals, i, val), node.subtrees.slice()))
    }
    const [lsub, rsub] = this._splitOnKey(node.subtrees[i], key)
    return this.ns.storedNode(new MSTNode(
      insertAt(node.keys, i, key),
      insertAt(node.vals, i, val),
      node.subtrees.slice(0, i).concat([lsub, rsub], node.subtrees.slice(i + 1))
    ))
  }

  _putRecursive (node, key, val, keyH, treeH) {
    if (keyH > treeH) { // grow the tree upward
      return this.ns.storedNode(this._putRecursive(
        this.ns.storedNode(new MSTNode([], [], [node.cid()])),
        key, val, keyH, treeH + 1
      ))
    }
    if (keyH < treeH) { // descend
      const i = node.gteIndex(key)
      return this.ns.storedNode(new MSTNode(
        node.keys.slice(), node.vals.slice(),
        replaceAt(node.subtrees, i, this._putRecursive(this.ns.getNode(node.subtrees[i]), key, val, keyH, treeH - 1).cid())
      ))
    }
    return this._putHere(node, key, val) // keyH === treeH
  }

  _splitOnKey (nodeCid, key) {
    if (nodeCid === null || nodeCid === undefined) return [null, null]
    const node = this.ns.getNode(nodeCid)
    const i = node.gteIndex(key)
    const [lsub, rsub] = this._splitOnKey(node.subtrees[i], key)
    const left = this.ns.storedNode(new MSTNode(node.keys.slice(0, i), node.vals.slice(0, i), node.subtrees.slice(0, i).concat([lsub]))).toOptional()
    const right = this.ns.storedNode(new MSTNode(node.keys.slice(i), node.vals.slice(i), [rsub].concat(node.subtrees.slice(i + 1)))).toOptional()
    return [left, right]
  }

  _squashTop (nodeCid) {
    const node = this.ns.getNode(nodeCid)
    if (node.keys.length) return nodeCid
    if (node.subtrees[0] === null) return nodeCid
    return this._squashTop(node.subtrees[0])
  }

  _deleteRecursive (node, key, keyH, treeH) {
    if (keyH > treeH) return node.toOptional()
    let i = node.gteIndex(key)
    if (keyH < treeH) {
      if (node.subtrees[i] === null) return node.toOptional()
      return this.ns.storedNode(new MSTNode(
        node.keys.slice(), node.vals.slice(),
        replaceAt(node.subtrees, i, this._deleteRecursive(this.ns.getNode(node.subtrees[i]), key, keyH, treeH - 1))
      )).toOptional()
    }
    i = node.gteIndex(key)
    if (i === node.keys.length || node.keys[i] !== key) return node.toOptional()
    return this.ns.storedNode(new MSTNode(
      removeAt(node.keys, i), removeAt(node.vals, i),
      node.subtrees.slice(0, i).concat([this._merge(node.subtrees[i], node.subtrees[i + 1])], node.subtrees.slice(i + 2))
    )).toOptional()
  }

  _merge (leftCid, rightCid) {
    if (leftCid === null) return rightCid
    if (rightCid === null) return leftCid
    const left = this.ns.getNode(leftCid)
    const right = this.ns.getNode(rightCid)
    return this.ns.storedNode(new MSTNode(
      left.keys.concat(right.keys), left.vals.concat(right.vals),
      left.subtrees.slice(0, -1).concat([this._merge(left.subtrees[left.subtrees.length - 1], right.subtrees[0])], right.subtrees.slice(1))
    )).toOptional()
  }
}

// Build an MST from records [{ key, value: CID }] (any order). Returns
// { root: CID, ns: NodeStore }. ns.blocks holds every node created; use
// reachableBlocks(ns, root) for just the live set (CAR output).
export function buildMst (records) {
  const ns = new NodeStore()
  const w = new NodeWrangler(ns)
  let root = ns.storedNode(MSTNode.empty()).cid()
  for (const { key, value } of records) root = w.putRecord(root, key, value)
  return { root, ns, wrangler: w }
}

// BFS the live MST nodes reachable from root (for CAR block sets).
export function reachableBlocks (ns, rootCid) {
  const out = new Map()
  const stack = [rootCid]
  while (stack.length) {
    const cid = stack.pop()
    if (cid === null || cid === undefined) continue
    const key = cid.toString()
    if (out.has(key)) continue
    const b = ns.blocks.get(key)
    if (!b) throw new Error(`missing node ${key}`)
    out.set(key, b)
    const node = MSTNode.deserialise(b.bytes)
    for (const t of node.subtrees) if (t) stack.push(t)
  }
  return out
}

// ---- Firehose MST-inversion proof (slice 3b) ----
//
// A #commit's `blocks` CAR must be a MINIMAL, self-contained proof of the
// old→new transition — not the whole tree (that would trip a relay's `tooBig`).
// This ports millipds `repo_ops.py:apply_writes` step 2b + `atmst` proof.py:
//   blocks = created | deletion_proof_cids | inductive_proof_nodes  (+ new records)
// where `inductive_proof_nodes` = every MST node READ while replaying the ops
// backward from the new root, which must reproduce the old (prevData) root.
// The prior record CIDs travel in each op's `prev` (like millipds), so a cold
// relay can invert with no old-tree state of its own.

// A NodeStore overlay: writes land in an in-memory upper layer (NOT logged);
// reads that fall through to `lower` are recorded in `.gets`. Mirrors millipds's
// OverlayBlockStore(MemoryBlockStore, LoggingBlockStoreWrapper(bs)).
export class OverlayNodeStore {
  constructor (lower) { this.lower = lower; this.upper = new Map(); this.gets = new Set() }

  storedNode (node) {
    const bytes = node.serialise()
    const cid = cidForBytesSync(bytes)
    this.upper.set(cid.toString(), { cid, bytes })
    return node
  }

  getNode (cid) {
    if (cid === null || cid === undefined) return MSTNode.empty()
    const k = cid.toString()
    const u = this.upper.get(k)
    if (u) return MSTNode.deserialise(u.bytes)
    this.gets.add(k) // a read of a pre-existing node — part of the inductive proof
    return this.lower.getNode(cid)
  }
}

// Follow the search path for `key` from `rootCid`, collecting every node visited.
// Returns { value: CID|null, proof: Set<cidStr> }. value===null ⇒ exclusion proof;
// value!==null ⇒ inclusion proof. Port of atmst find_rpath_and_build_proof.
export function findRpathProof (ns, rootCid, key) {
  const proof = new Set()
  let cid = rootCid
  while (cid !== null && cid !== undefined) {
    const node = ns.getNode(cid)
    proof.add(cid.toString())
    const i = node.gteIndex(key)
    if (i < node.keys.length && node.keys[i] === key) return { value: node.vals[i], proof }
    cid = node.subtrees[i] // descend the subtree left of the first key >= target
  }
  return { value: null, proof }
}

// Build a NodeStore holding exactly the given blocks (cid-string -> { cid, bytes }).
export function nodeStoreFromBlocks (blocks) {
  const ns = new NodeStore()
  for (const [k, v] of blocks) ns.blocks.set(k, v)
  return ns
}

// Compute the minimal firehose block set for a single commit's ops.
//   oldRecords / newRecords : [{ key, value: CID }] — the record sets BEFORE/AFTER.
//   ops : [{ action:'create'|'update'|'delete', path, cid: CID|null, prev: CID|null }]
// Returns { blocks: Map<cidStr,{cid,bytes}>, dataCid, oldRoot } — MST nodes only
// (record + commit blocks are added by the caller). Throws if the backward replay
// does not reproduce the old root (i.e. the proof would be invalid).
export function firehoseProofBlocks ({ oldRecords, newRecords, ops }) {
  const oldB = buildMst(oldRecords)
  const newB = buildMst(newRecords)
  const oldRoot = oldB.root
  const newRoot = newB.root

  const oldSet = reachableBlocks(oldB.ns, oldRoot)
  const newSet = reachableBlocks(newB.ns, newRoot)

  // combined store holds every node of BOTH trees (proof reads span both)
  const combined = new NodeStore()
  for (const [k, v] of oldSet) combined.blocks.set(k, v)
  for (const [k, v] of newSet) combined.blocks.set(k, v)

  const proofCids = new Set()

  // created: new-tree nodes not present in the old tree
  for (const k of newSet.keys()) if (!oldSet.has(k)) proofCids.add(k)

  // deletion proofs: for each delete, the exclusion-proof path in the NEW tree
  for (const op of ops) {
    if (op.action !== 'delete') continue
    const { value, proof } = findRpathProof(combined, newRoot, op.path)
    if (value !== null) throw new Error(`delete proof: ${op.path} still present in new tree`)
    for (const c of proof) proofCids.add(c)
  }

  // inductive proof: replay ops backward from newRoot; every node read is required.
  const overlay = new OverlayNodeStore(combined)
  const w = new NodeWrangler(overlay)
  let inv = newRoot
  for (let i = ops.length - 1; i >= 0; i--) {
    const op = ops[i]
    if (op.action === 'create') {
      inv = w.delRecord(inv, op.path)
    } else { // update | delete → restore the prior value
      if (op.prev === null || op.prev === undefined) throw new Error(`inversion: ${op.action} ${op.path} missing prev`)
      inv = w.putRecord(inv, op.path, op.prev)
    }
  }
  if (!inv.equals(oldRoot)) throw new Error('inversion proof failed: backward replay did not reproduce prevData root')
  for (const k of overlay.gets) proofCids.add(k)

  const blocks = new Map()
  for (const k of proofCids) blocks.set(k, combined.blocks.get(k))
  return { blocks, dataCid: newRoot, oldRoot }
}
// atproto repo — READ path (slice 1).
//
// A repo is a CAR whose root is a signed commit; the commit's `data` CID points at
// the root of a Merkle Search Tree (MST) of records. This module reads a CAR, walks
// the MST, and — most importantly — VERIFIES byte-exact fidelity by re-encoding every
// block and checking its CID. Writing/mutating the MST is slice 2.

import * as dagCbor from '@ipld/dag-cbor'
import { cidForBytes, cidForBytesSync } from './cid.js'
import { buildMst, reachableBlocks } from './mst.js'
import { unsignedCommit, signCommit, commitCid } from './commit.js'
import { readCar, writeCar } from './car.js'

// CAR read/write moved to the bare-safe minimal codec in ./car.js (was @ipld/car).
export { readCar, writeCar }

export function getBlock (car, cid) {
  const b = car.blocks.get(cid.toString())
  if (!b) throw new Error(`missing block ${cid}`)
  return b
}

export function decodeBlock (car, cid) {
  return dagCbor.decode(getBlock(car, cid).bytes)
}

// The signed commit at the CAR root.
export function loadCommit (car) {
  if (car.roots.length !== 1) throw new Error(`expected 1 root, got ${car.roots.length}`)
  const commit = decodeBlock(car, car.roots[0])
  if (!commit || !commit.did || commit.data === undefined) throw new Error('root is not a commit')
  return { cid: car.roots[0], value: commit }
}

// Walk the MST in key order, yielding { key, value: recordCid }. MST node shape:
//   { l: CID|null, e: [ { p: int, k: bytes, v: CID, t: CID|null } ] }
// keys are prefix-compressed against the previous key in the SAME node.
export function * walkMst (car, rootCid, _prevKey = '') {
  const node = decodeBlock(car, rootCid)
  if (!node || !Array.isArray(node.e)) throw new Error(`not an MST node: ${rootCid}`)
  if (node.l) yield * walkMst(car, node.l)
  let prev = ''
  for (const e of node.e) {
    const suffix = Buffer.from(e.k).toString('utf8')
    const key = prev.slice(0, e.p) + suffix
    prev = key
    yield { key, value: e.v }
    if (e.t) yield * walkMst(car, e.t)
  }
}

// All records as { key, cid, value } in key order.
export function listRecords (car) {
  const commit = loadCommit(car)
  const out = []
  for (const { key, value } of walkMst(car, commit.value.data)) {
    out.push({ key, cid: value, value: decodeBlock(car, value) })
  }
  return out
}

// Byte-exact fidelity check: re-encode every block and confirm its CID is unchanged.
// Also confirms the commit's data CID and every MST value CID resolve to a present
// block. Returns { blocks, records, ok, mismatches }.
export async function verifyRepo (car) {
  const mismatches = []
  for (const [cidStr, { cid, bytes }] of car.blocks) {
    // re-encode: decode then canonical-encode; must reproduce the exact bytes + CID
    const reencoded = dagCbor.encode(dagCbor.decode(bytes))
    const sameBytes = Buffer.from(reencoded).equals(Buffer.from(bytes))
    const recomputed = await cidForBytes(reencoded)
    if (!sameBytes || !recomputed.equals(cid)) {
      mismatches.push({ cid: cidStr, sameBytes, recomputed: recomputed.toString() })
    }
  }
  const commit = loadCommit(car)
  getBlock(car, commit.value.data) // MST root must be present
  const records = listRecords(car)
  for (const r of records) getBlock(car, r.cid) // each record block present
  return { blocks: car.blocks.size, records: records.length, ok: mismatches.length === 0, mismatches }
}

// ---- WRITE path (slice 3) ----

// Originate a full atproto repo from records. Each record is
// { collection, rkey, record } (or { key, value }). Returns the CAR bytes plus the
// commit/data CIDs. `privateKey` is the atproto secp256k1 signing key.
export async function createRepo ({ records, did, rev, privateKey }) {
  const recordBlocks = new Map()
  const mstRecords = []
  for (const r of records) {
    const key = r.key !== undefined ? r.key : `${r.collection}/${r.rkey}`
    const value = r.record !== undefined ? r.record : r.value
    const bytes = dagCbor.encode(value)
    const cid = cidForBytesSync(bytes)
    recordBlocks.set(cid.toString(), { cid, bytes })
    mstRecords.push({ key, value: cid })
  }
  const { root: dataCid, ns } = buildMst(mstRecords)
  const mstBlocks = reachableBlocks(ns, dataCid)

  const signed = signCommit(unsignedCommit({ did, rev, data: dataCid }), privateKey)
  const cCid = commitCid(signed)
  const commitBytes = dagCbor.encode(signed)

  const blocks = [{ cid: cCid, bytes: commitBytes }, ...mstBlocks.values(), ...recordBlocks.values()]
  const carBytes = await writeCar(cCid, blocks)
  return { carBytes, commitCid: cCid, dataCid, signedCommit: signed }
}
{
  "name": "@ipld/dag-cbor",
  "version": "9.2.7",
  "description": "JS implementation of DAG-CBOR",
  "author": "Rod <rod@vagg.org> (http://r.va.gg/)",
  "license": "Apache-2.0 OR MIT",
  "homepage": "https://github.com/ipld/js-dag-cbor#readme",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/ipld/js-dag-cbor.git"
  },
  "bugs": {
    "url": "https://github.com/ipld/js-dag-cbor/issues"
  },
  "publishConfig": {
    "access": "public",
    "provenance": true
  },
  "keywords": [
    "ipfs",
    "ipld",
    "multiformats"
  ],
  "type": "module",
  "types": "./dist/src/index.d.ts",
  "typesVersions": {
    "*": {
      "*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ],
      "src/*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ]
    }
  },
  "files": [
    "src",
    "dist",
    "!dist/test",
    "!**/*.tsbuildinfo"
  ],
  "exports": {
    ".": {
      "types": "./dist/src/index.d.ts",
      "import": "./src/index.js",
      "module-sync": "./src/index.js"
    }
  },
  "release": {
    "branches": [
      "master"
    ],
    "plugins": [
      [
        "@semantic-release/commit-analyzer",
        {
          "preset": "conventionalcommits",
          "releaseRules": [
            {
              "breaking": true,
              "release": "major"
            },
            {
              "revert": true,
              "release": "patch"
            },
            {
              "type": "feat",
              "release": "minor"
            },
            {
              "type": "fix",
              "release": "patch"
            },
            {
              "type": "docs",
              "release": "patch"
            },
            {
              "type": "test",
              "release": "patch"
            },
            {
              "type": "deps",
              "release": "patch"
            },
            {
              "scope": "no-release",
              "release": false
            }
          ]
        }
      ],
      [
        "@semantic-release/release-notes-generator",
        {
          "preset": "conventionalcommits",
          "presetConfig": {
            "types": [
              {
                "type": "feat",
                "section": "Features"
              },
              {
                "type": "fix",
                "section": "Bug Fixes"
              },
              {
                "type": "chore",
                "section": "Trivial Changes"
              },
              {
                "type": "docs",
                "section": "Documentation"
              },
              {
                "type": "deps",
                "section": "Dependencies"
              },
              {
                "type": "test",
                "section": "Tests"
              }
            ]
          }
        }
      ],
      "@semantic-release/changelog",
      "@semantic-release/npm",
      "@semantic-release/github",
      [
        "@semantic-release/git",
        {
          "assets": [
            "CHANGELOG.md",
            "package.json"
          ]
        }
      ]
    ]
  },
  "scripts": {
    "clean": "aegir clean",
    "lint": "aegir lint",
    "build": "aegir build",
    "release": "aegir release",
    "test": "npm run lint && aegir test",
    "test:ts": "npm run test --prefix test/ts-use",
    "test:node": "aegir test -t node --cov",
    "test:chrome": "aegir test -t browser --cov",
    "test:chrome-webworker": "aegir test -t webworker",
    "test:firefox": "aegir test -t browser -- --browser firefox",
    "test:firefox-webworker": "aegir test -t webworker -- --browser firefox",
    "test:electron-main": "aegir test -t electron-main",
    "dep-check": "aegir dep-check"
  },
  "dependencies": {
    "cborg": "^5.0.1",
    "multiformats": "^13.1.0"
  },
  "devDependencies": {
    "@ipld/garbage": "^6.0.0",
    "aegir": "^48.0.1"
  }
}
import * as cborg from 'cborg'
import { CID } from 'multiformats/cid'

// https://github.com/ipfs/go-ipfs/issues/3570#issuecomment-273931692
const CID_CBOR_TAG = 42

/**
 * @template T
 * @typedef {import('multiformats/codecs/interface').ByteView<T>} ByteView
 */

/**
 * @template T
 * @typedef {import('multiformats/codecs/interface').ArrayBufferView<T>} ArrayBufferView
 */

/**
 * @template T
 * @param {ByteView<T> | ArrayBufferView<T>} buf
 * @returns {ByteView<T>}
 */
export function toByteView (buf) {
  if (buf instanceof ArrayBuffer) {
    return new Uint8Array(buf, 0, buf.byteLength)
  }

  return buf
}

/**
 * cidEncoder will receive all Objects during encode, it needs to filter out
 * anything that's not a CID and return `null` for that so it's encoded as
 * normal.
 *
 * @param {any} obj
 * @returns {cborg.Token[]|null}
 */
function cidEncoder (obj) {
  if (obj.asCID !== obj && obj['/'] !== obj.bytes) {
    return null // any other kind of object
  }
  const cid = CID.asCID(obj)
  /* c8 ignore next 4 */
  // very unlikely case, and it'll probably throw a recursion error in cborg
  if (!cid) {
    return null
  }
  const bytes = new Uint8Array(cid.bytes.byteLength + 1)
  bytes.set(cid.bytes, 1) // prefix is 0x00, for historical reasons
  return [
    new cborg.Token(cborg.Type.tag, CID_CBOR_TAG),
    new cborg.Token(cborg.Type.bytes, bytes)
  ]
}

// eslint-disable-next-line jsdoc/require-returns-check
/**
 * Intercept all `undefined` values from an object walk and reject the entire
 * object if we find one.
 *
 * @returns {null}
 */
function undefinedEncoder () {
  throw new Error('`undefined` is not supported by the IPLD Data Model and cannot be encoded')
}

/**
 * Intercept all `number` values from an object walk and reject the entire
 * object if we find something that doesn't fit the IPLD data model (NaN &
 * Infinity).
 *
 * @param {number} num
 * @returns {null}
 */
function numberEncoder (num) {
  if (Number.isNaN(num)) {
    throw new Error('`NaN` is not supported by the IPLD Data Model and cannot be encoded')
  }
  if (num === Infinity || num === -Infinity) {
    throw new Error('`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded')
  }
  return null
}

/**
 * @param {Map<any, any>} map
 * @returns {null}
 */
function mapEncoder (map) {
  for (const key of map.keys()) {
    if (typeof key !== 'string' || key.length === 0) {
      throw new Error('Non-string Map keys are not supported by the IPLD Data Model and cannot be encoded')
    }
  }
  return null
}

const _encodeOptions = {
  float64: true,
  typeEncoders: {
    Map: mapEncoder,
    Object: cidEncoder,
    undefined: undefinedEncoder,
    number: numberEncoder
  }
}

export const encodeOptions = {
  ..._encodeOptions,
  typeEncoders: {
    ..._encodeOptions.typeEncoders
  }
}

/**
 * @param {import('cborg').TagDecodeControl} decode
 * @returns {CID}
 */
function cidDecoder (decode) {
  const bytes = /** @type {Uint8Array} */ (decode())
  if (bytes[0] !== 0) {
    throw new Error('Invalid CID for CBOR tag 42; expected leading 0x00')
  }
  return CID.decode(bytes.subarray(1)) // ignore leading 0x00
}

const _decodeOptions = {
  allowIndefinite: false,
  coerceUndefinedToNull: true,
  allowNaN: false,
  allowInfinity: false,
  allowBigInt: true, // this will lead to BigInt for ints outside of
  // safe-integer range, which may surprise users
  strict: true,
  useMaps: false,
  rejectDuplicateMapKeys: true,
  /** @type {{ [tagNumber: number]: import('cborg').TagDecoder }} */
  tags: { [CID_CBOR_TAG]: cidDecoder }
}

export const decodeOptions = {
  ..._decodeOptions,
  tags: { ..._decodeOptions.tags }
}

export const name = 'dag-cbor'
export const code = 0x71

/**
 * @template T
 * @param {T} node
 * @returns {ByteView<T>}
 */
export const encode = (node) => cborg.encode(node, _encodeOptions)

/**
 * @template T
 * @param {ByteView<T> | ArrayBufferView<T>} data
 * @returns {T}
 */
export const decode = (data) => cborg.decode(toByteView(data), _decodeOptions)
/**
 * Utilities for short weierstrass curves, combined with noble-hashes.
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { weierstrass } from "./abstract/weierstrass.js";
/** connects noble-curves to noble-hashes */
export function getHash(hash) {
    return { hash };
}
/** @deprecated use new `weierstrass()` and `ecdsa()` methods */
export function createCurve(curveDef, defHash) {
    const create = (hash) => weierstrass({ ...curveDef, hash: hash });
    return { ...create(defHash), create };
}
//# sourceMappingURL=_shortw_utils.js.map/**
 * Methods for elliptic curve multiplication by scalars.
 * Contains wNAF, pippenger.
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { bitLen, bitMask, validateObject } from "../utils.js";
import { Field, FpInvertBatch, nLength, validateField } from "./modular.js";
const _0n = BigInt(0);
const _1n = BigInt(1);
export function negateCt(condition, item) {
    const neg = item.negate();
    return condition ? neg : item;
}
/**
 * Takes a bunch of Projective Points but executes only one
 * inversion on all of them. Inversion is very slow operation,
 * so this improves performance massively.
 * Optimization: converts a list of projective points to a list of identical points with Z=1.
 */
export function normalizeZ(c, points) {
    const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
    return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
}
function validateW(W, bits) {
    if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
        throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);
}
function calcWOpts(W, scalarBits) {
    validateW(W, scalarBits);
    const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero
    const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero
    const maxNumber = 2 ** W; // W=8 256
    const mask = bitMask(W); // W=8 255 == mask 0b11111111
    const shiftBy = BigInt(W); // W=8 8
    return { windows, windowSize, mask, maxNumber, shiftBy };
}
function calcOffsets(n, window, wOpts) {
    const { windowSize, mask, maxNumber, shiftBy } = wOpts;
    let wbits = Number(n & mask); // extract W bits.
    let nextN = n >> shiftBy; // shift number by W bits.
    // What actually happens here:
    // const highestBit = Number(mask ^ (mask >> 1n));
    // let wbits2 = wbits - 1; // skip zero
    // if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);
    // split if bits > max: +224 => 256-32
    if (wbits > windowSize) {
        // we skip zero, which means instead of `>= size-1`, we do `> size`
        wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.
        nextN += _1n; // +256 (carry)
    }
    const offsetStart = window * windowSize;
    const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero
    const isZero = wbits === 0; // is current window slice a 0?
    const isNeg = wbits < 0; // is current window slice negative?
    const isNegF = window % 2 !== 0; // fake random statement for noise
    const offsetF = offsetStart; // fake offset for noise
    return { nextN, offset, isZero, isNeg, isNegF, offsetF };
}
function validateMSMPoints(points, c) {
    if (!Array.isArray(points))
        throw new Error('array expected');
    points.forEach((p, i) => {
        if (!(p instanceof c))
            throw new Error('invalid point at index ' + i);
    });
}
function validateMSMScalars(scalars, field) {
    if (!Array.isArray(scalars))
        throw new Error('array of scalars expected');
    scalars.forEach((s, i) => {
        if (!field.isValid(s))
            throw new Error('invalid scalar at index ' + i);
    });
}
// Since points in different groups cannot be equal (different object constructor),
// we can have single place to store precomputes.
// Allows to make points frozen / immutable.
const pointPrecomputes = new WeakMap();
const pointWindowSizes = new WeakMap();
function getW(P) {
    // To disable precomputes:
    // return 1;
    return pointWindowSizes.get(P) || 1;
}
function assert0(n) {
    if (n !== _0n)
        throw new Error('invalid wNAF');
}
/**
 * Elliptic curve multiplication of Point by scalar. Fragile.
 * Table generation takes **30MB of ram and 10ms on high-end CPU**,
 * but may take much longer on slow devices. Actual generation will happen on
 * first call of `multiply()`. By default, `BASE` point is precomputed.
 *
 * Scalars should always be less than curve order: this should be checked inside of a curve itself.
 * Creates precomputation tables for fast multiplication:
 * - private scalar is split by fixed size windows of W bits
 * - every window point is collected from window's table & added to accumulator
 * - since windows are different, same point inside tables won't be accessed more than once per calc
 * - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)
 * - +1 window is neccessary for wNAF
 * - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication
 *
 * @todo Research returning 2d JS array of windows, instead of a single window.
 * This would allow windows to be in different memory locations
 */
export class wNAF {
    // Parametrized with a given Point class (not individual point)
    constructor(Point, bits) {
        this.BASE = Point.BASE;
        this.ZERO = Point.ZERO;
        this.Fn = Point.Fn;
        this.bits = bits;
    }
    // non-const time multiplication ladder
    _unsafeLadder(elm, n, p = this.ZERO) {
        let d = elm;
        while (n > _0n) {
            if (n & _1n)
                p = p.add(d);
            d = d.double();
            n >>= _1n;
        }
        return p;
    }
    /**
     * Creates a wNAF precomputation window. Used for caching.
     * Default window size is set by `utils.precompute()` and is equal to 8.
     * Number of precomputed points depends on the curve size:
     * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
     * - 𝑊 is the window size
     * - 𝑛 is the bitlength of the curve order.
     * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
     * @param point Point instance
     * @param W window size
     * @returns precomputed point tables flattened to a single array
     */
    precomputeWindow(point, W) {
        const { windows, windowSize } = calcWOpts(W, this.bits);
        const points = [];
        let p = point;
        let base = p;
        for (let window = 0; window < windows; window++) {
            base = p;
            points.push(base);
            // i=1, bc we skip 0
            for (let i = 1; i < windowSize; i++) {
                base = base.add(p);
                points.push(base);
            }
            p = base.double();
        }
        return points;
    }
    /**
     * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
     * More compact implementation:
     * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
     * @returns real and fake (for const-time) points
     */
    wNAF(W, precomputes, n) {
        // Scalar should be smaller than field order
        if (!this.Fn.isValid(n))
            throw new Error('invalid scalar');
        // Accumulators
        let p = this.ZERO;
        let f = this.BASE;
        // This code was first written with assumption that 'f' and 'p' will never be infinity point:
        // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,
        // there is negate now: it is possible that negated element from low value
        // would be the same as high element, which will create carry into next window.
        // It's not obvious how this can fail, but still worth investigating later.
        const wo = calcWOpts(W, this.bits);
        for (let window = 0; window < wo.windows; window++) {
            // (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise
            const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
            n = nextN;
            if (isZero) {
                // bits are 0: add garbage to fake point
                // Important part for const-time getPublicKey: add random "noise" point to f.
                f = f.add(negateCt(isNegF, precomputes[offsetF]));
            }
            else {
                // bits are 1: add to result point
                p = p.add(negateCt(isNeg, precomputes[offset]));
            }
        }
        assert0(n);
        // Return both real and fake points: JIT won't eliminate f.
        // At this point there is a way to F be infinity-point even if p is not,
        // which makes it less const-time: around 1 bigint multiply.
        return { p, f };
    }
    /**
     * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
     * @param acc accumulator point to add result of multiplication
     * @returns point
     */
    wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
        const wo = calcWOpts(W, this.bits);
        for (let window = 0; window < wo.windows; window++) {
            if (n === _0n)
                break; // Early-exit, skip 0 value
            const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
            n = nextN;
            if (isZero) {
                // Window bits are 0: skip processing.
                // Move to next window.
                continue;
            }
            else {
                const item = precomputes[offset];
                acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM
            }
        }
        assert0(n);
        return acc;
    }
    getPrecomputes(W, point, transform) {
        // Calculate precomputes on a first run, reuse them after
        let comp = pointPrecomputes.get(point);
        if (!comp) {
            comp = this.precomputeWindow(point, W);
            if (W !== 1) {
                // Doing transform outside of if brings 15% perf hit
                if (typeof transform === 'function')
                    comp = transform(comp);
                pointPrecomputes.set(point, comp);
            }
        }
        return comp;
    }
    cached(point, scalar, transform) {
        const W = getW(point);
        return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
    }
    unsafe(point, scalar, transform, prev) {
        const W = getW(point);
        if (W === 1)
            return this._unsafeLadder(point, scalar, prev); // For W=1 ladder is ~x2 faster
        return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
    }
    // We calculate precomputes for elliptic curve point multiplication
    // using windowed method. This specifies window size and
    // stores precomputed values. Usually only base point would be precomputed.
    createCache(P, W) {
        validateW(W, this.bits);
        pointWindowSizes.set(P, W);
        pointPrecomputes.delete(P);
    }
    hasCache(elm) {
        return getW(elm) !== 1;
    }
}
/**
 * Endomorphism-specific multiplication for Koblitz curves.
 * Cost: 128 dbl, 0-256 adds.
 */
export function mulEndoUnsafe(Point, point, k1, k2) {
    let acc = point;
    let p1 = Point.ZERO;
    let p2 = Point.ZERO;
    while (k1 > _0n || k2 > _0n) {
        if (k1 & _1n)
            p1 = p1.add(acc);
        if (k2 & _1n)
            p2 = p2.add(acc);
        acc = acc.double();
        k1 >>= _1n;
        k2 >>= _1n;
    }
    return { p1, p2 };
}
/**
 * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).
 * 30x faster vs naive addition on L=4096, 10x faster than precomputes.
 * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.
 * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.
 * @param c Curve Point constructor
 * @param fieldN field over CURVE.N - important that it's not over CURVE.P
 * @param points array of L curve points
 * @param scalars array of L scalars (aka secret keys / bigints)
 */
export function pippenger(c, fieldN, points, scalars) {
    // If we split scalars by some window (let's say 8 bits), every chunk will only
    // take 256 buckets even if there are 4096 scalars, also re-uses double.
    // TODO:
    // - https://eprint.iacr.org/2024/750.pdf
    // - https://tches.iacr.org/index.php/TCHES/article/view/10287
    // 0 is accepted in scalars
    validateMSMPoints(points, c);
    validateMSMScalars(scalars, fieldN);
    const plength = points.length;
    const slength = scalars.length;
    if (plength !== slength)
        throw new Error('arrays of points and scalars must have equal length');
    // if (plength === 0) throw new Error('array must be of length >= 2');
    const zero = c.ZERO;
    const wbits = bitLen(BigInt(plength));
    let windowSize = 1; // bits
    if (wbits > 12)
        windowSize = wbits - 3;
    else if (wbits > 4)
        windowSize = wbits - 2;
    else if (wbits > 0)
        windowSize = 2;
    const MASK = bitMask(windowSize);
    const buckets = new Array(Number(MASK) + 1).fill(zero); // +1 for zero array
    const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;
    let sum = zero;
    for (let i = lastBits; i >= 0; i -= windowSize) {
        buckets.fill(zero);
        for (let j = 0; j < slength; j++) {
            const scalar = scalars[j];
            const wbits = Number((scalar >> BigInt(i)) & MASK);
            buckets[wbits] = buckets[wbits].add(points[j]);
        }
        let resI = zero; // not using this will do small speed-up, but will lose ct
        // Skip first bucket, because it is zero
        for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {
            sumI = sumI.add(buckets[j]);
            resI = resI.add(sumI);
        }
        sum = sum.add(resI);
        if (i !== 0)
            for (let j = 0; j < windowSize; j++)
                sum = sum.double();
    }
    return sum;
}
/**
 * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).
 * @param c Curve Point constructor
 * @param fieldN field over CURVE.N - important that it's not over CURVE.P
 * @param points array of L curve points
 * @returns function which multiplies points with scaars
 */
export function precomputeMSMUnsafe(c, fieldN, points, windowSize) {
    /**
     * Performance Analysis of Window-based Precomputation
     *
     * Base Case (256-bit scalar, 8-bit window):
     * - Standard precomputation requires:
     *   - 31 additions per scalar × 256 scalars = 7,936 ops
     *   - Plus 255 summary additions = 8,191 total ops
     *   Note: Summary additions can be optimized via accumulator
     *
     * Chunked Precomputation Analysis:
     * - Using 32 chunks requires:
     *   - 255 additions per chunk
     *   - 256 doublings
     *   - Total: (255 × 32) + 256 = 8,416 ops
     *
     * Memory Usage Comparison:
     * Window Size | Standard Points | Chunked Points
     * ------------|-----------------|---------------
     *     4-bit   |     520         |      15
     *     8-bit   |    4,224        |     255
     *    10-bit   |   13,824        |   1,023
     *    16-bit   |  557,056        |  65,535
     *
     * Key Advantages:
     * 1. Enables larger window sizes due to reduced memory overhead
     * 2. More efficient for smaller scalar counts:
     *    - 16 chunks: (16 × 255) + 256 = 4,336 ops
     *    - ~2x faster than standard 8,191 ops
     *
     * Limitations:
     * - Not suitable for plain precomputes (requires 256 constant doublings)
     * - Performance degrades with larger scalar counts:
     *   - Optimal for ~256 scalars
     *   - Less efficient for 4096+ scalars (Pippenger preferred)
     */
    validateW(windowSize, fieldN.BITS);
    validateMSMPoints(points, c);
    const zero = c.ZERO;
    const tableSize = 2 ** windowSize - 1; // table size (without zero)
    const chunks = Math.ceil(fieldN.BITS / windowSize); // chunks of item
    const MASK = bitMask(windowSize);
    const tables = points.map((p) => {
        const res = [];
        for (let i = 0, acc = p; i < tableSize; i++) {
            res.push(acc);
            acc = acc.add(p);
        }
        return res;
    });
    return (scalars) => {
        validateMSMScalars(scalars, fieldN);
        if (scalars.length > points.length)
            throw new Error('array of scalars must be smaller than array of points');
        let res = zero;
        for (let i = 0; i < chunks; i++) {
            // No need to double if accumulator is still zero.
            if (res !== zero)
                for (let j = 0; j < windowSize; j++)
                    res = res.double();
            const shiftBy = BigInt(chunks * windowSize - (i + 1) * windowSize);
            for (let j = 0; j < scalars.length; j++) {
                const n = scalars[j];
                const curr = Number((n >> shiftBy) & MASK);
                if (!curr)
                    continue; // skip zero scalars chunks
                res = res.add(tables[j][curr - 1]);
            }
        }
        return res;
    };
}
// TODO: remove
/** @deprecated */
export function validateBasic(curve) {
    validateField(curve.Fp);
    validateObject(curve, {
        n: 'bigint',
        h: 'bigint',
        Gx: 'field',
        Gy: 'field',
    }, {
        nBitLength: 'isSafeInteger',
        nByteLength: 'isSafeInteger',
    });
    // Set defaults
    return Object.freeze({
        ...nLength(curve.n, curve.nBitLength),
        ...curve,
        ...{ p: curve.Fp.ORDER },
    });
}
function createField(order, field, isLE) {
    if (field) {
        if (field.ORDER !== order)
            throw new Error('Field.ORDER must match order: Fp == p, Fn == n');
        validateField(field);
        return field;
    }
    else {
        return Field(order, { isLE });
    }
}
/** Validates CURVE opts and creates fields */
export function _createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
    if (FpFnLE === undefined)
        FpFnLE = type === 'edwards';
    if (!CURVE || typeof CURVE !== 'object')
        throw new Error(`expected valid ${type} CURVE object`);
    for (const p of ['p', 'n', 'h']) {
        const val = CURVE[p];
        if (!(typeof val === 'bigint' && val > _0n))
            throw new Error(`CURVE.${p} must be positive bigint`);
    }
    const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);
    const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
    const _b = type === 'weierstrass' ? 'b' : 'd';
    const params = ['Gx', 'Gy', 'a', _b];
    for (const p of params) {
        // @ts-ignore
        if (!Fp.isValid(CURVE[p]))
            throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
    }
    CURVE = Object.freeze(Object.assign({}, CURVE));
    return { CURVE, Fp, Fn };
}
//# sourceMappingURL=curve.js.mapimport { _validateObject, abytes, bytesToNumberBE, concatBytes, isBytes, isHash, utf8ToBytes, } from "../utils.js";
import { FpInvertBatch, mod } from "./modular.js";
// Octet Stream to Integer. "spec" implementation of os2ip is 2.5x slower vs bytesToNumberBE.
const os2ip = bytesToNumberBE;
// Integer to Octet Stream (numberToBytesBE)
function i2osp(value, length) {
    anum(value);
    anum(length);
    if (value < 0 || value >= 1 << (8 * length))
        throw new Error('invalid I2OSP input: ' + value);
    const res = Array.from({ length }).fill(0);
    for (let i = length - 1; i >= 0; i--) {
        res[i] = value & 0xff;
        value >>>= 8;
    }
    return new Uint8Array(res);
}
function strxor(a, b) {
    const arr = new Uint8Array(a.length);
    for (let i = 0; i < a.length; i++) {
        arr[i] = a[i] ^ b[i];
    }
    return arr;
}
function anum(item) {
    if (!Number.isSafeInteger(item))
        throw new Error('number expected');
}
function normDST(DST) {
    if (!isBytes(DST) && typeof DST !== 'string')
        throw new Error('DST must be Uint8Array or string');
    return typeof DST === 'string' ? utf8ToBytes(DST) : DST;
}
/**
 * Produces a uniformly random byte string using a cryptographic hash function H that outputs b bits.
 * [RFC 9380 5.3.1](https://www.rfc-editor.org/rfc/rfc9380#section-5.3.1).
 */
export function expand_message_xmd(msg, DST, lenInBytes, H) {
    abytes(msg);
    anum(lenInBytes);
    DST = normDST(DST);
    // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3
    if (DST.length > 255)
        DST = H(concatBytes(utf8ToBytes('H2C-OVERSIZE-DST-'), DST));
    const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H;
    const ell = Math.ceil(lenInBytes / b_in_bytes);
    if (lenInBytes > 65535 || ell > 255)
        throw new Error('expand_message_xmd: invalid lenInBytes');
    const DST_prime = concatBytes(DST, i2osp(DST.length, 1));
    const Z_pad = i2osp(0, r_in_bytes);
    const l_i_b_str = i2osp(lenInBytes, 2); // len_in_bytes_str
    const b = new Array(ell);
    const b_0 = H(concatBytes(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));
    b[0] = H(concatBytes(b_0, i2osp(1, 1), DST_prime));
    for (let i = 1; i <= ell; i++) {
        const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime];
        b[i] = H(concatBytes(...args));
    }
    const pseudo_random_bytes = concatBytes(...b);
    return pseudo_random_bytes.slice(0, lenInBytes);
}
/**
 * Produces a uniformly random byte string using an extendable-output function (XOF) H.
 * 1. The collision resistance of H MUST be at least k bits.
 * 2. H MUST be an XOF that has been proved indifferentiable from
 *    a random oracle under a reasonable cryptographic assumption.
 * [RFC 9380 5.3.2](https://www.rfc-editor.org/rfc/rfc9380#section-5.3.2).
 */
export function expand_message_xof(msg, DST, lenInBytes, k, H) {
    abytes(msg);
    anum(lenInBytes);
    DST = normDST(DST);
    // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3
    // DST = H('H2C-OVERSIZE-DST-' || a_very_long_DST, Math.ceil((lenInBytes * k) / 8));
    if (DST.length > 255) {
        const dkLen = Math.ceil((2 * k) / 8);
        DST = H.create({ dkLen }).update(utf8ToBytes('H2C-OVERSIZE-DST-')).update(DST).digest();
    }
    if (lenInBytes > 65535 || DST.length > 255)
        throw new Error('expand_message_xof: invalid lenInBytes');
    return (H.create({ dkLen: lenInBytes })
        .update(msg)
        .update(i2osp(lenInBytes, 2))
        // 2. DST_prime = DST || I2OSP(len(DST), 1)
        .update(DST)
        .update(i2osp(DST.length, 1))
        .digest());
}
/**
 * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F.
 * [RFC 9380 5.2](https://www.rfc-editor.org/rfc/rfc9380#section-5.2).
 * @param msg a byte string containing the message to hash
 * @param count the number of elements of F to output
 * @param options `{DST: string, p: bigint, m: number, k: number, expand: 'xmd' | 'xof', hash: H}`, see above
 * @returns [u_0, ..., u_(count - 1)], a list of field elements.
 */
export function hash_to_field(msg, count, options) {
    _validateObject(options, {
        p: 'bigint',
        m: 'number',
        k: 'number',
        hash: 'function',
    });
    const { p, k, m, hash, expand, DST } = options;
    if (!isHash(options.hash))
        throw new Error('expected valid hash');
    abytes(msg);
    anum(count);
    const log2p = p.toString(2).length;
    const L = Math.ceil((log2p + k) / 8); // section 5.1 of ietf draft link above
    const len_in_bytes = count * m * L;
    let prb; // pseudo_random_bytes
    if (expand === 'xmd') {
        prb = expand_message_xmd(msg, DST, len_in_bytes, hash);
    }
    else if (expand === 'xof') {
        prb = expand_message_xof(msg, DST, len_in_bytes, k, hash);
    }
    else if (expand === '_internal_pass') {
        // for internal tests only
        prb = msg;
    }
    else {
        throw new Error('expand must be "xmd" or "xof"');
    }
    const u = new Array(count);
    for (let i = 0; i < count; i++) {
        const e = new Array(m);
        for (let j = 0; j < m; j++) {
            const elm_offset = L * (j + i * m);
            const tv = prb.subarray(elm_offset, elm_offset + L);
            e[j] = mod(os2ip(tv), p);
        }
        u[i] = e;
    }
    return u;
}
export function isogenyMap(field, map) {
    // Make same order as in spec
    const coeff = map.map((i) => Array.from(i).reverse());
    return (x, y) => {
        const [xn, xd, yn, yd] = coeff.map((val) => val.reduce((acc, i) => field.add(field.mul(acc, x), i)));
        // 6.6.3
        // Exceptional cases of iso_map are inputs that cause the denominator of
        // either rational function to evaluate to zero; such cases MUST return
        // the identity point on E.
        const [xd_inv, yd_inv] = FpInvertBatch(field, [xd, yd], true);
        x = field.mul(xn, xd_inv); // xNum / xDen
        y = field.mul(y, field.mul(yn, yd_inv)); // y * (yNum / yDev)
        return { x, y };
    };
}
export const _DST_scalar = utf8ToBytes('HashToScalar-');
/** Creates hash-to-curve methods from EC Point and mapToCurve function. See {@link H2CHasher}. */
export function createHasher(Point, mapToCurve, defaults) {
    if (typeof mapToCurve !== 'function')
        throw new Error('mapToCurve() must be defined');
    function map(num) {
        return Point.fromAffine(mapToCurve(num));
    }
    function clear(initial) {
        const P = initial.clearCofactor();
        if (P.equals(Point.ZERO))
            return Point.ZERO; // zero will throw in assert
        P.assertValidity();
        return P;
    }
    return {
        defaults,
        hashToCurve(msg, options) {
            const opts = Object.assign({}, defaults, options);
            const u = hash_to_field(msg, 2, opts);
            const u0 = map(u[0]);
            const u1 = map(u[1]);
            return clear(u0.add(u1));
        },
        encodeToCurve(msg, options) {
            const optsDst = defaults.encodeDST ? { DST: defaults.encodeDST } : {};
            const opts = Object.assign({}, defaults, optsDst, options);
            const u = hash_to_field(msg, 1, opts);
            const u0 = map(u[0]);
            return clear(u0);
        },
        /** See {@link H2CHasher} */
        mapToCurve(scalars) {
            if (!Array.isArray(scalars))
                throw new Error('expected array of bigints');
            for (const i of scalars)
                if (typeof i !== 'bigint')
                    throw new Error('expected array of bigints');
            return clear(map(scalars));
        },
        // hash_to_scalar can produce 0: https://www.rfc-editor.org/errata/eid8393
        // RFC 9380, draft-irtf-cfrg-bbs-signatures-08
        hashToScalar(msg, options) {
            // @ts-ignore
            const N = Point.Fn.ORDER;
            const opts = Object.assign({}, defaults, { p: N, m: 1, DST: _DST_scalar }, options);
            return hash_to_field(msg, 1, opts)[0][0];
        },
    };
}
//# sourceMappingURL=hash-to-curve.js.map/**
 * Utils for modular division and fields.
 * Field over 11 is a finite (Galois) field is integer number operations `mod 11`.
 * There is no division: it is replaced by modular multiplicative inverse.
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { _validateObject, anumber, bitMask, bytesToNumberBE, bytesToNumberLE, ensureBytes, numberToBytesBE, numberToBytesLE, } from "../utils.js";
// prettier-ignore
const _0n = BigInt(0), _1n = BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3);
// prettier-ignore
const _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5), _7n = /* @__PURE__ */ BigInt(7);
// prettier-ignore
const _8n = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9), _16n = /* @__PURE__ */ BigInt(16);
// Calculates a modulo b
export function mod(a, b) {
    const result = a % b;
    return result >= _0n ? result : b + result;
}
/**
 * Efficiently raise num to power and do modular division.
 * Unsafe in some contexts: uses ladder, so can expose bigint bits.
 * @example
 * pow(2n, 6n, 11n) // 64n % 11n == 9n
 */
export function pow(num, power, modulo) {
    return FpPow(Field(modulo), num, power);
}
/** Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)` */
export function pow2(x, power, modulo) {
    let res = x;
    while (power-- > _0n) {
        res *= res;
        res %= modulo;
    }
    return res;
}
/**
 * Inverses number over modulo.
 * Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).
 */
export function invert(number, modulo) {
    if (number === _0n)
        throw new Error('invert: expected non-zero number');
    if (modulo <= _0n)
        throw new Error('invert: expected positive modulus, got ' + modulo);
    // Fermat's little theorem "CT-like" version inv(n) = n^(m-2) mod m is 30x slower.
    let a = mod(number, modulo);
    let b = modulo;
    // prettier-ignore
    let x = _0n, y = _1n, u = _1n, v = _0n;
    while (a !== _0n) {
        // JIT applies optimization if those two lines follow each other
        const q = b / a;
        const r = b % a;
        const m = x - u * q;
        const n = y - v * q;
        // prettier-ignore
        b = a, a = r, x = u, y = v, u = m, v = n;
    }
    const gcd = b;
    if (gcd !== _1n)
        throw new Error('invert: does not exist');
    return mod(x, modulo);
}
function assertIsSquare(Fp, root, n) {
    if (!Fp.eql(Fp.sqr(root), n))
        throw new Error('Cannot find square root');
}
// Not all roots are possible! Example which will throw:
// const NUM =
// n = 72057594037927816n;
// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));
function sqrt3mod4(Fp, n) {
    const p1div4 = (Fp.ORDER + _1n) / _4n;
    const root = Fp.pow(n, p1div4);
    assertIsSquare(Fp, root, n);
    return root;
}
function sqrt5mod8(Fp, n) {
    const p5div8 = (Fp.ORDER - _5n) / _8n;
    const n2 = Fp.mul(n, _2n);
    const v = Fp.pow(n2, p5div8);
    const nv = Fp.mul(n, v);
    const i = Fp.mul(Fp.mul(nv, _2n), v);
    const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
    assertIsSquare(Fp, root, n);
    return root;
}
// Based on RFC9380, Kong algorithm
// prettier-ignore
function sqrt9mod16(P) {
    const Fp_ = Field(P);
    const tn = tonelliShanks(P);
    const c1 = tn(Fp_, Fp_.neg(Fp_.ONE)); //  1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F
    const c2 = tn(Fp_, c1); //  2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F
    const c3 = tn(Fp_, Fp_.neg(c1)); //  3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F
    const c4 = (P + _7n) / _16n; //  4. c4 = (q + 7) / 16        # Integer arithmetic
    return (Fp, n) => {
        let tv1 = Fp.pow(n, c4); //  1. tv1 = x^c4
        let tv2 = Fp.mul(tv1, c1); //  2. tv2 = c1 * tv1
        const tv3 = Fp.mul(tv1, c2); //  3. tv3 = c2 * tv1
        const tv4 = Fp.mul(tv1, c3); //  4. tv4 = c3 * tv1
        const e1 = Fp.eql(Fp.sqr(tv2), n); //  5.  e1 = (tv2^2) == x
        const e2 = Fp.eql(Fp.sqr(tv3), n); //  6.  e2 = (tv3^2) == x
        tv1 = Fp.cmov(tv1, tv2, e1); //  7. tv1 = CMOV(tv1, tv2, e1)  # Select tv2 if (tv2^2) == x
        tv2 = Fp.cmov(tv4, tv3, e2); //  8. tv2 = CMOV(tv4, tv3, e2)  # Select tv3 if (tv3^2) == x
        const e3 = Fp.eql(Fp.sqr(tv2), n); //  9.  e3 = (tv2^2) == x
        const root = Fp.cmov(tv1, tv2, e3); // 10.  z = CMOV(tv1, tv2, e3)   # Select sqrt from tv1 & tv2
        assertIsSquare(Fp, root, n);
        return root;
    };
}
/**
 * Tonelli-Shanks square root search algorithm.
 * 1. https://eprint.iacr.org/2012/685.pdf (page 12)
 * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks
 * @param P field order
 * @returns function that takes field Fp (created from P) and number n
 */
export function tonelliShanks(P) {
    // Initialization (precomputation).
    // Caching initialization could boost perf by 7%.
    if (P < _3n)
        throw new Error('sqrt is not defined for small field');
    // Factor P - 1 = Q * 2^S, where Q is odd
    let Q = P - _1n;
    let S = 0;
    while (Q % _2n === _0n) {
        Q /= _2n;
        S++;
    }
    // Find the first quadratic non-residue Z >= 2
    let Z = _2n;
    const _Fp = Field(P);
    while (FpLegendre(_Fp, Z) === 1) {
        // Basic primality test for P. After x iterations, chance of
        // not finding quadratic non-residue is 2^x, so 2^1000.
        if (Z++ > 1000)
            throw new Error('Cannot find square root: probably non-prime P');
    }
    // Fast-path; usually done before Z, but we do "primality test".
    if (S === 1)
        return sqrt3mod4;
    // Slow-path
    // TODO: test on Fp2 and others
    let cc = _Fp.pow(Z, Q); // c = z^Q
    const Q1div2 = (Q + _1n) / _2n;
    return function tonelliSlow(Fp, n) {
        if (Fp.is0(n))
            return n;
        // Check if n is a quadratic residue using Legendre symbol
        if (FpLegendre(Fp, n) !== 1)
            throw new Error('Cannot find square root');
        // Initialize variables for the main loop
        let M = S;
        let c = Fp.mul(Fp.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp
        let t = Fp.pow(n, Q); // t = n^Q, first guess at the fudge factor
        let R = Fp.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root
        // Main loop
        // while t != 1
        while (!Fp.eql(t, Fp.ONE)) {
            if (Fp.is0(t))
                return Fp.ZERO; // if t=0 return R=0
            let i = 1;
            // Find the smallest i >= 1 such that t^(2^i) ≡ 1 (mod P)
            let t_tmp = Fp.sqr(t); // t^(2^1)
            while (!Fp.eql(t_tmp, Fp.ONE)) {
                i++;
                t_tmp = Fp.sqr(t_tmp); // t^(2^2)...
                if (i === M)
                    throw new Error('Cannot find square root');
            }
            // Calculate the exponent for b: 2^(M - i - 1)
            const exponent = _1n << BigInt(M - i - 1); // bigint is important
            const b = Fp.pow(c, exponent); // b = 2^(M - i - 1)
            // Update variables
            M = i;
            c = Fp.sqr(b); // c = b^2
            t = Fp.mul(t, c); // t = (t * b^2)
            R = Fp.mul(R, b); // R = R*b
        }
        return R;
    };
}
/**
 * Square root for a finite field. Will try optimized versions first:
 *
 * 1. P ≡ 3 (mod 4)
 * 2. P ≡ 5 (mod 8)
 * 3. P ≡ 9 (mod 16)
 * 4. Tonelli-Shanks algorithm
 *
 * Different algorithms can give different roots, it is up to user to decide which one they want.
 * For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).
 */
export function FpSqrt(P) {
    // P ≡ 3 (mod 4) => √n = n^((P+1)/4)
    if (P % _4n === _3n)
        return sqrt3mod4;
    // P ≡ 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf
    if (P % _8n === _5n)
        return sqrt5mod8;
    // P ≡ 9 (mod 16) => Kong algorithm, page 11 of https://eprint.iacr.org/2012/685.pdf (algorithm 4)
    if (P % _16n === _9n)
        return sqrt9mod16(P);
    // Tonelli-Shanks algorithm
    return tonelliShanks(P);
}
// Little-endian check for first LE bit (last BE bit);
export const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n;
// prettier-ignore
const FIELD_FIELDS = [
    'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',
    'eql', 'add', 'sub', 'mul', 'pow', 'div',
    'addN', 'subN', 'mulN', 'sqrN'
];
export function validateField(field) {
    const initial = {
        ORDER: 'bigint',
        MASK: 'bigint',
        BYTES: 'number',
        BITS: 'number',
    };
    const opts = FIELD_FIELDS.reduce((map, val) => {
        map[val] = 'function';
        return map;
    }, initial);
    _validateObject(field, opts);
    // const max = 16384;
    // if (field.BYTES < 1 || field.BYTES > max) throw new Error('invalid field');
    // if (field.BITS < 1 || field.BITS > 8 * max) throw new Error('invalid field');
    return field;
}
// Generic field functions
/**
 * Same as `pow` but for Fp: non-constant-time.
 * Unsafe in some contexts: uses ladder, so can expose bigint bits.
 */
export function FpPow(Fp, num, power) {
    if (power < _0n)
        throw new Error('invalid exponent, negatives unsupported');
    if (power === _0n)
        return Fp.ONE;
    if (power === _1n)
        return num;
    let p = Fp.ONE;
    let d = num;
    while (power > _0n) {
        if (power & _1n)
            p = Fp.mul(p, d);
        d = Fp.sqr(d);
        power >>= _1n;
    }
    return p;
}
/**
 * Efficiently invert an array of Field elements.
 * Exception-free. Will return `undefined` for 0 elements.
 * @param passZero map 0 to 0 (instead of undefined)
 */
export function FpInvertBatch(Fp, nums, passZero = false) {
    const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : undefined);
    // Walk from first to last, multiply them by each other MOD p
    const multipliedAcc = nums.reduce((acc, num, i) => {
        if (Fp.is0(num))
            return acc;
        inverted[i] = acc;
        return Fp.mul(acc, num);
    }, Fp.ONE);
    // Invert last element
    const invertedAcc = Fp.inv(multipliedAcc);
    // Walk from last to first, multiply them by inverted each other MOD p
    nums.reduceRight((acc, num, i) => {
        if (Fp.is0(num))
            return acc;
        inverted[i] = Fp.mul(acc, inverted[i]);
        return Fp.mul(acc, num);
    }, invertedAcc);
    return inverted;
}
// TODO: remove
export function FpDiv(Fp, lhs, rhs) {
    return Fp.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, Fp.ORDER) : Fp.inv(rhs));
}
/**
 * Legendre symbol.
 * Legendre constant is used to calculate Legendre symbol (a | p)
 * which denotes the value of a^((p-1)/2) (mod p).
 *
 * * (a | p) ≡ 1    if a is a square (mod p), quadratic residue
 * * (a | p) ≡ -1   if a is not a square (mod p), quadratic non residue
 * * (a | p) ≡ 0    if a ≡ 0 (mod p)
 */
export function FpLegendre(Fp, n) {
    // We can use 3rd argument as optional cache of this value
    // but seems unneeded for now. The operation is very fast.
    const p1mod2 = (Fp.ORDER - _1n) / _2n;
    const powered = Fp.pow(n, p1mod2);
    const yes = Fp.eql(powered, Fp.ONE);
    const zero = Fp.eql(powered, Fp.ZERO);
    const no = Fp.eql(powered, Fp.neg(Fp.ONE));
    if (!yes && !zero && !no)
        throw new Error('invalid Legendre symbol result');
    return yes ? 1 : zero ? 0 : -1;
}
// This function returns True whenever the value x is a square in the field F.
export function FpIsSquare(Fp, n) {
    const l = FpLegendre(Fp, n);
    return l === 1;
}
// CURVE.n lengths
export function nLength(n, nBitLength) {
    // Bit size, byte size of CURVE.n
    if (nBitLength !== undefined)
        anumber(nBitLength);
    const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;
    const nByteLength = Math.ceil(_nBitLength / 8);
    return { nBitLength: _nBitLength, nByteLength };
}
/**
 * Creates a finite field. Major performance optimizations:
 * * 1. Denormalized operations like mulN instead of mul.
 * * 2. Identical object shape: never add or remove keys.
 * * 3. `Object.freeze`.
 * Fragile: always run a benchmark on a change.
 * Security note: operations don't check 'isValid' for all elements for performance reasons,
 * it is caller responsibility to check this.
 * This is low-level code, please make sure you know what you're doing.
 *
 * Note about field properties:
 * * CHARACTERISTIC p = prime number, number of elements in main subgroup.
 * * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.
 *
 * @param ORDER field order, probably prime, or could be composite
 * @param bitLen how many bits the field consumes
 * @param isLE (default: false) if encoding / decoding should be in little-endian
 * @param redef optional faster redefinitions of sqrt and other methods
 */
export function Field(ORDER, bitLenOrOpts, // TODO: use opts only in v2?
isLE = false, opts = {}) {
    if (ORDER <= _0n)
        throw new Error('invalid field: expected ORDER > 0, got ' + ORDER);
    let _nbitLength = undefined;
    let _sqrt = undefined;
    let modFromBytes = false;
    let allowedLengths = undefined;
    if (typeof bitLenOrOpts === 'object' && bitLenOrOpts != null) {
        if (opts.sqrt || isLE)
            throw new Error('cannot specify opts in two arguments');
        const _opts = bitLenOrOpts;
        if (_opts.BITS)
            _nbitLength = _opts.BITS;
        if (_opts.sqrt)
            _sqrt = _opts.sqrt;
        if (typeof _opts.isLE === 'boolean')
            isLE = _opts.isLE;
        if (typeof _opts.modFromBytes === 'boolean')
            modFromBytes = _opts.modFromBytes;
        allowedLengths = _opts.allowedLengths;
    }
    else {
        if (typeof bitLenOrOpts === 'number')
            _nbitLength = bitLenOrOpts;
        if (opts.sqrt)
            _sqrt = opts.sqrt;
    }
    const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, _nbitLength);
    if (BYTES > 2048)
        throw new Error('invalid field: expected ORDER of <= 2048 bytes');
    let sqrtP; // cached sqrtP
    const f = Object.freeze({
        ORDER,
        isLE,
        BITS,
        BYTES,
        MASK: bitMask(BITS),
        ZERO: _0n,
        ONE: _1n,
        allowedLengths: allowedLengths,
        create: (num) => mod(num, ORDER),
        isValid: (num) => {
            if (typeof num !== 'bigint')
                throw new Error('invalid field element: expected bigint, got ' + typeof num);
            return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible
        },
        is0: (num) => num === _0n,
        // is valid and invertible
        isValidNot0: (num) => !f.is0(num) && f.isValid(num),
        isOdd: (num) => (num & _1n) === _1n,
        neg: (num) => mod(-num, ORDER),
        eql: (lhs, rhs) => lhs === rhs,
        sqr: (num) => mod(num * num, ORDER),
        add: (lhs, rhs) => mod(lhs + rhs, ORDER),
        sub: (lhs, rhs) => mod(lhs - rhs, ORDER),
        mul: (lhs, rhs) => mod(lhs * rhs, ORDER),
        pow: (num, power) => FpPow(f, num, power),
        div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),
        // Same as above, but doesn't normalize
        sqrN: (num) => num * num,
        addN: (lhs, rhs) => lhs + rhs,
        subN: (lhs, rhs) => lhs - rhs,
        mulN: (lhs, rhs) => lhs * rhs,
        inv: (num) => invert(num, ORDER),
        sqrt: _sqrt ||
            ((n) => {
                if (!sqrtP)
                    sqrtP = FpSqrt(ORDER);
                return sqrtP(f, n);
            }),
        toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),
        fromBytes: (bytes, skipValidation = true) => {
            if (allowedLengths) {
                if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
                    throw new Error('Field.fromBytes: expected ' + allowedLengths + ' bytes, got ' + bytes.length);
                }
                const padded = new Uint8Array(BYTES);
                // isLE add 0 to right, !isLE to the left.
                padded.set(bytes, isLE ? 0 : padded.length - bytes.length);
                bytes = padded;
            }
            if (bytes.length !== BYTES)
                throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);
            let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
            if (modFromBytes)
                scalar = mod(scalar, ORDER);
            if (!skipValidation)
                if (!f.isValid(scalar))
                    throw new Error('invalid field element: outside of range 0..ORDER');
            // NOTE: we don't validate scalar here, please use isValid. This done such way because some
            // protocol may allow non-reduced scalar that reduced later or changed some other way.
            return scalar;
        },
        // TODO: we don't need it here, move out to separate fn
        invertBatch: (lst) => FpInvertBatch(f, lst),
        // We can't move this out because Fp6, Fp12 implement it
        // and it's unclear what to return in there.
        cmov: (a, b, c) => (c ? b : a),
    });
    return Object.freeze(f);
}
// Generic random scalar, we can do same for other fields if via Fp2.mul(Fp2.ONE, Fp2.random)?
// This allows unsafe methods like ignore bias or zero. These unsafe, but often used in different protocols (if deterministic RNG).
// which mean we cannot force this via opts.
// Not sure what to do with randomBytes, we can accept it inside opts if wanted.
// Probably need to export getMinHashLength somewhere?
// random(bytes?: Uint8Array, unsafeAllowZero = false, unsafeAllowBias = false) {
//   const LEN = !unsafeAllowBias ? getMinHashLength(ORDER) : BYTES;
//   if (bytes === undefined) bytes = randomBytes(LEN); // _opts.randomBytes?
//   const num = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
//   // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0
//   const reduced = unsafeAllowZero ? mod(num, ORDER) : mod(num, ORDER - _1n) + _1n;
//   return reduced;
// },
export function FpSqrtOdd(Fp, elm) {
    if (!Fp.isOdd)
        throw new Error("Field doesn't have isOdd");
    const root = Fp.sqrt(elm);
    return Fp.isOdd(root) ? root : Fp.neg(root);
}
export function FpSqrtEven(Fp, elm) {
    if (!Fp.isOdd)
        throw new Error("Field doesn't have isOdd");
    const root = Fp.sqrt(elm);
    return Fp.isOdd(root) ? Fp.neg(root) : root;
}
/**
 * "Constant-time" private key generation utility.
 * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field).
 * Which makes it slightly more biased, less secure.
 * @deprecated use `mapKeyToField` instead
 */
export function hashToPrivateScalar(hash, groupOrder, isLE = false) {
    hash = ensureBytes('privateHash', hash);
    const hashLen = hash.length;
    const minLen = nLength(groupOrder).nByteLength + 8;
    if (minLen < 24 || hashLen < minLen || hashLen > 1024)
        throw new Error('hashToPrivateScalar: expected ' + minLen + '-1024 bytes of input, got ' + hashLen);
    const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash);
    return mod(num, groupOrder - _1n) + _1n;
}
/**
 * Returns total number of bytes consumed by the field element.
 * For example, 32 bytes for usual 256-bit weierstrass curve.
 * @param fieldOrder number of field elements, usually CURVE.n
 * @returns byte length of field
 */
export function getFieldBytesLength(fieldOrder) {
    if (typeof fieldOrder !== 'bigint')
        throw new Error('field order must be bigint');
    const bitLength = fieldOrder.toString(2).length;
    return Math.ceil(bitLength / 8);
}
/**
 * Returns minimal amount of bytes that can be safely reduced
 * by field order.
 * Should be 2^-128 for 128-bit curve such as P256.
 * @param fieldOrder number of field elements, usually CURVE.n
 * @returns byte length of target hash
 */
export function getMinHashLength(fieldOrder) {
    const length = getFieldBytesLength(fieldOrder);
    return length + Math.ceil(length / 2);
}
/**
 * "Constant-time" private key generation utility.
 * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF
 * and convert them into private scalar, with the modulo bias being negligible.
 * Needs at least 48 bytes of input for 32-byte private key.
 * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/
 * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final
 * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5
 * @param hash hash output from SHA3 or a similar function
 * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)
 * @param isLE interpret hash bytes as LE num
 * @returns valid private scalar
 */
export function mapHashToField(key, fieldOrder, isLE = false) {
    const len = key.length;
    const fieldLen = getFieldBytesLength(fieldOrder);
    const minLen = getMinHashLength(fieldOrder);
    // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.
    if (len < 16 || len < minLen || len > 1024)
        throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);
    const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);
    // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0
    const reduced = mod(num, fieldOrder - _1n) + _1n;
    return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
}
//# sourceMappingURL=modular.js.map/**
 * Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.
 *
 * ### Design rationale for types
 *
 * * Interaction between classes from different curves should fail:
 *   `k256.Point.BASE.add(p256.Point.BASE)`
 * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime
 * * Different calls of `curve()` would return different classes -
 *   `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,
 *   it won't affect others
 *
 * TypeScript can't infer types for classes created inside a function. Classes is one instance
 * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create
 * unique type for every function call.
 *
 * We can use generic types via some param, like curve opts, but that would:
 *     1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)
 *     which is hard to debug.
 *     2. Params can be generic and we can't enforce them to be constant value:
 *     if somebody creates curve from non-constant params,
 *     it would be allowed to interact with other curves with non-constant params
 *
 * @todo https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { hmac as nobleHmac } from '@noble/hashes/hmac.js';
import { ahash } from '@noble/hashes/utils';
import { _validateObject, _abool2 as abool, _abytes2 as abytes, aInRange, bitLen, bitMask, bytesToHex, bytesToNumberBE, concatBytes, createHmacDrbg, ensureBytes, hexToBytes, inRange, isBytes, memoized, numberToHexUnpadded, randomBytes as randomBytesWeb, } from "../utils.js";
import { _createCurveFields, mulEndoUnsafe, negateCt, normalizeZ, pippenger, wNAF, } from "./curve.js";
import { Field, FpInvertBatch, getMinHashLength, mapHashToField, nLength, validateField, } from "./modular.js";
// We construct basis in such way that den is always positive and equals n, but num sign depends on basis (not on secret value)
const divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n) / den;
/**
 * Splits scalar for GLV endomorphism.
 */
export function _splitEndoScalar(k, basis, n) {
    // Split scalar into two such that part is ~half bits: `abs(part) < sqrt(N)`
    // Since part can be negative, we need to do this on point.
    // TODO: verifyScalar function which consumes lambda
    const [[a1, b1], [a2, b2]] = basis;
    const c1 = divNearest(b2 * k, n);
    const c2 = divNearest(-b1 * k, n);
    // |k1|/|k2| is < sqrt(N), but can be negative.
    // If we do `k1 mod N`, we'll get big scalar (`> sqrt(N)`): so, we do cheaper negation instead.
    let k1 = k - c1 * a1 - c2 * a2;
    let k2 = -c1 * b1 - c2 * b2;
    const k1neg = k1 < _0n;
    const k2neg = k2 < _0n;
    if (k1neg)
        k1 = -k1;
    if (k2neg)
        k2 = -k2;
    // Double check that resulting scalar less than half bits of N: otherwise wNAF will fail.
    // This should only happen on wrong basises. Also, math inside is too complex and I don't trust it.
    const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n; // Half bits of N
    if (k1 < _0n || k1 >= MAX_NUM || k2 < _0n || k2 >= MAX_NUM) {
        throw new Error('splitScalar (endomorphism): failed, k=' + k);
    }
    return { k1neg, k1, k2neg, k2 };
}
function validateSigFormat(format) {
    if (!['compact', 'recovered', 'der'].includes(format))
        throw new Error('Signature format must be "compact", "recovered", or "der"');
    return format;
}
function validateSigOpts(opts, def) {
    const optsn = {};
    for (let optName of Object.keys(def)) {
        // @ts-ignore
        optsn[optName] = opts[optName] === undefined ? def[optName] : opts[optName];
    }
    abool(optsn.lowS, 'lowS');
    abool(optsn.prehash, 'prehash');
    if (optsn.format !== undefined)
        validateSigFormat(optsn.format);
    return optsn;
}
export class DERErr extends Error {
    constructor(m = '') {
        super(m);
    }
}
/**
 * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:
 *
 *     [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]
 *
 * Docs: https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/, https://luca.ntop.org/Teaching/Appunti/asn1.html
 */
export const DER = {
    // asn.1 DER encoding utils
    Err: DERErr,
    // Basic building block is TLV (Tag-Length-Value)
    _tlv: {
        encode: (tag, data) => {
            const { Err: E } = DER;
            if (tag < 0 || tag > 256)
                throw new E('tlv.encode: wrong tag');
            if (data.length & 1)
                throw new E('tlv.encode: unpadded data');
            const dataLen = data.length / 2;
            const len = numberToHexUnpadded(dataLen);
            if ((len.length / 2) & 128)
                throw new E('tlv.encode: long form length too big');
            // length of length with long form flag
            const lenLen = dataLen > 127 ? numberToHexUnpadded((len.length / 2) | 128) : '';
            const t = numberToHexUnpadded(tag);
            return t + lenLen + len + data;
        },
        // v - value, l - left bytes (unparsed)
        decode(tag, data) {
            const { Err: E } = DER;
            let pos = 0;
            if (tag < 0 || tag > 256)
                throw new E('tlv.encode: wrong tag');
            if (data.length < 2 || data[pos++] !== tag)
                throw new E('tlv.decode: wrong tlv');
            const first = data[pos++];
            const isLong = !!(first & 128); // First bit of first length byte is flag for short/long form
            let length = 0;
            if (!isLong)
                length = first;
            else {
                // Long form: [longFlag(1bit), lengthLength(7bit), length (BE)]
                const lenLen = first & 127;
                if (!lenLen)
                    throw new E('tlv.decode(long): indefinite length not supported');
                if (lenLen > 4)
                    throw new E('tlv.decode(long): byte length is too big'); // this will overflow u32 in js
                const lengthBytes = data.subarray(pos, pos + lenLen);
                if (lengthBytes.length !== lenLen)
                    throw new E('tlv.decode: length bytes not complete');
                if (lengthBytes[0] === 0)
                    throw new E('tlv.decode(long): zero leftmost byte');
                for (const b of lengthBytes)
                    length = (length << 8) | b;
                pos += lenLen;
                if (length < 128)
                    throw new E('tlv.decode(long): not minimal encoding');
            }
            const v = data.subarray(pos, pos + length);
            if (v.length !== length)
                throw new E('tlv.decode: wrong value length');
            return { v, l: data.subarray(pos + length) };
        },
    },
    // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
    // since we always use positive integers here. It must always be empty:
    // - add zero byte if exists
    // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
    _int: {
        encode(num) {
            const { Err: E } = DER;
            if (num < _0n)
                throw new E('integer: negative integers are not allowed');
            let hex = numberToHexUnpadded(num);
            // Pad with zero byte if negative flag is present
            if (Number.parseInt(hex[0], 16) & 0b1000)
                hex = '00' + hex;
            if (hex.length & 1)
                throw new E('unexpected DER parsing assertion: unpadded hex');
            return hex;
        },
        decode(data) {
            const { Err: E } = DER;
            if (data[0] & 128)
                throw new E('invalid signature integer: negative');
            if (data[0] === 0x00 && !(data[1] & 128))
                throw new E('invalid signature integer: unnecessary leading zero');
            return bytesToNumberBE(data);
        },
    },
    toSig(hex) {
        // parse DER signature
        const { Err: E, _int: int, _tlv: tlv } = DER;
        const data = ensureBytes('signature', hex);
        const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);
        if (seqLeftBytes.length)
            throw new E('invalid signature: left bytes after parsing');
        const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);
        const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);
        if (sLeftBytes.length)
            throw new E('invalid signature: left bytes after parsing');
        return { r: int.decode(rBytes), s: int.decode(sBytes) };
    },
    hexFromSig(sig) {
        const { _tlv: tlv, _int: int } = DER;
        const rs = tlv.encode(0x02, int.encode(sig.r));
        const ss = tlv.encode(0x02, int.encode(sig.s));
        const seq = rs + ss;
        return tlv.encode(0x30, seq);
    },
};
// Be friendly to bad ECMAScript parsers by not using bigint literals
// prettier-ignore
const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4);
export function _normFnElement(Fn, key) {
    const { BYTES: expected } = Fn;
    let num;
    if (typeof key === 'bigint') {
        num = key;
    }
    else {
        let bytes = ensureBytes('private key', key);
        try {
            num = Fn.fromBytes(bytes);
        }
        catch (error) {
            throw new Error(`invalid private key: expected ui8a of size ${expected}, got ${typeof key}`);
        }
    }
    if (!Fn.isValidNot0(num))
        throw new Error('invalid private key: out of range [1..N-1]');
    return num;
}
/**
 * Creates weierstrass Point constructor, based on specified curve options.
 *
 * @example
```js
const opts = {
  p: BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff'),
  n: BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551'),
  h: BigInt(1),
  a: BigInt('0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc'),
  b: BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b'),
  Gx: BigInt('0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296'),
  Gy: BigInt('0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5'),
};
const p256_Point = weierstrass(opts);
```
 */
export function weierstrassN(params, extraOpts = {}) {
    const validated = _createCurveFields('weierstrass', params, extraOpts);
    const { Fp, Fn } = validated;
    let CURVE = validated.CURVE;
    const { h: cofactor, n: CURVE_ORDER } = CURVE;
    _validateObject(extraOpts, {}, {
        allowInfinityPoint: 'boolean',
        clearCofactor: 'function',
        isTorsionFree: 'function',
        fromBytes: 'function',
        toBytes: 'function',
        endo: 'object',
        wrapPrivateKey: 'boolean',
    });
    const { endo } = extraOpts;
    if (endo) {
        // validateObject(endo, { beta: 'bigint', splitScalar: 'function' });
        if (!Fp.is0(CURVE.a) || typeof endo.beta !== 'bigint' || !Array.isArray(endo.basises)) {
            throw new Error('invalid endo: expected "beta": bigint and "basises": array');
        }
    }
    const lengths = getWLengths(Fp, Fn);
    function assertCompressionIsSupported() {
        if (!Fp.isOdd)
            throw new Error('compression is not supported: Field does not have .isOdd()');
    }
    // Implements IEEE P1363 point encoding
    function pointToBytes(_c, point, isCompressed) {
        const { x, y } = point.toAffine();
        const bx = Fp.toBytes(x);
        abool(isCompressed, 'isCompressed');
        if (isCompressed) {
            assertCompressionIsSupported();
            const hasEvenY = !Fp.isOdd(y);
            return concatBytes(pprefix(hasEvenY), bx);
        }
        else {
            return concatBytes(Uint8Array.of(0x04), bx, Fp.toBytes(y));
        }
    }
    function pointFromBytes(bytes) {
        abytes(bytes, undefined, 'Point');
        const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths; // e.g. for 32-byte: 33, 65
        const length = bytes.length;
        const head = bytes[0];
        const tail = bytes.subarray(1);
        // No actual validation is done here: use .assertValidity()
        if (length === comp && (head === 0x02 || head === 0x03)) {
            const x = Fp.fromBytes(tail);
            if (!Fp.isValid(x))
                throw new Error('bad point: is not on curve, wrong x');
            const y2 = weierstrassEquation(x); // y² = x³ + ax + b
            let y;
            try {
                y = Fp.sqrt(y2); // y = y² ^ (p+1)/4
            }
            catch (sqrtError) {
                const err = sqrtError instanceof Error ? ': ' + sqrtError.message : '';
                throw new Error('bad point: is not on curve, sqrt error' + err);
            }
            assertCompressionIsSupported();
            const isYOdd = Fp.isOdd(y); // (y & _1n) === _1n;
            const isHeadOdd = (head & 1) === 1; // ECDSA-specific
            if (isHeadOdd !== isYOdd)
                y = Fp.neg(y);
            return { x, y };
        }
        else if (length === uncomp && head === 0x04) {
            // TODO: more checks
            const L = Fp.BYTES;
            const x = Fp.fromBytes(tail.subarray(0, L));
            const y = Fp.fromBytes(tail.subarray(L, L * 2));
            if (!isValidXY(x, y))
                throw new Error('bad point: is not on curve');
            return { x, y };
        }
        else {
            throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);
        }
    }
    const encodePoint = extraOpts.toBytes || pointToBytes;
    const decodePoint = extraOpts.fromBytes || pointFromBytes;
    function weierstrassEquation(x) {
        const x2 = Fp.sqr(x); // x * x
        const x3 = Fp.mul(x2, x); // x² * x
        return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b); // x³ + a * x + b
    }
    // TODO: move top-level
    /** Checks whether equation holds for given x, y: y² == x³ + ax + b */
    function isValidXY(x, y) {
        const left = Fp.sqr(y); // y²
        const right = weierstrassEquation(x); // x³ + ax + b
        return Fp.eql(left, right);
    }
    // Validate whether the passed curve params are valid.
    // Test 1: equation y² = x³ + ax + b should work for generator point.
    if (!isValidXY(CURVE.Gx, CURVE.Gy))
        throw new Error('bad curve params: generator point');
    // Test 2: discriminant Δ part should be non-zero: 4a³ + 27b² != 0.
    // Guarantees curve is genus-1, smooth (non-singular).
    const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n), _4n);
    const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));
    if (Fp.is0(Fp.add(_4a3, _27b2)))
        throw new Error('bad curve params: a or b');
    /** Asserts coordinate is valid: 0 <= n < Fp.ORDER. */
    function acoord(title, n, banZero = false) {
        if (!Fp.isValid(n) || (banZero && Fp.is0(n)))
            throw new Error(`bad point coordinate ${title}`);
        return n;
    }
    function aprjpoint(other) {
        if (!(other instanceof Point))
            throw new Error('ProjectivePoint expected');
    }
    function splitEndoScalarN(k) {
        if (!endo || !endo.basises)
            throw new Error('no endo');
        return _splitEndoScalar(k, endo.basises, Fn.ORDER);
    }
    // Memoized toAffine / validity check. They are heavy. Points are immutable.
    // Converts Projective point to affine (x, y) coordinates.
    // Can accept precomputed Z^-1 - for example, from invertBatch.
    // (X, Y, Z) ∋ (x=X/Z, y=Y/Z)
    const toAffineMemo = memoized((p, iz) => {
        const { X, Y, Z } = p;
        // Fast-path for normalized points
        if (Fp.eql(Z, Fp.ONE))
            return { x: X, y: Y };
        const is0 = p.is0();
        // If invZ was 0, we return zero point. However we still want to execute
        // all operations, so we replace invZ with a random number, 1.
        if (iz == null)
            iz = is0 ? Fp.ONE : Fp.inv(Z);
        const x = Fp.mul(X, iz);
        const y = Fp.mul(Y, iz);
        const zz = Fp.mul(Z, iz);
        if (is0)
            return { x: Fp.ZERO, y: Fp.ZERO };
        if (!Fp.eql(zz, Fp.ONE))
            throw new Error('invZ was invalid');
        return { x, y };
    });
    // NOTE: on exception this will crash 'cached' and no value will be set.
    // Otherwise true will be return
    const assertValidMemo = memoized((p) => {
        if (p.is0()) {
            // (0, 1, 0) aka ZERO is invalid in most contexts.
            // In BLS, ZERO can be serialized, so we allow it.
            // (0, 0, 0) is invalid representation of ZERO.
            if (extraOpts.allowInfinityPoint && !Fp.is0(p.Y))
                return;
            throw new Error('bad point: ZERO');
        }
        // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`
        const { x, y } = p.toAffine();
        if (!Fp.isValid(x) || !Fp.isValid(y))
            throw new Error('bad point: x or y not field elements');
        if (!isValidXY(x, y))
            throw new Error('bad point: equation left != right');
        if (!p.isTorsionFree())
            throw new Error('bad point: not in prime-order subgroup');
        return true;
    });
    function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) {
        k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);
        k1p = negateCt(k1neg, k1p);
        k2p = negateCt(k2neg, k2p);
        return k1p.add(k2p);
    }
    /**
     * Projective Point works in 3d / projective (homogeneous) coordinates:(X, Y, Z) ∋ (x=X/Z, y=Y/Z).
     * Default Point works in 2d / affine coordinates: (x, y).
     * We're doing calculations in projective, because its operations don't require costly inversion.
     */
    class Point {
        /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
        constructor(X, Y, Z) {
            this.X = acoord('x', X);
            this.Y = acoord('y', Y, true);
            this.Z = acoord('z', Z);
            Object.freeze(this);
        }
        static CURVE() {
            return CURVE;
        }
        /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
        static fromAffine(p) {
            const { x, y } = p || {};
            if (!p || !Fp.isValid(x) || !Fp.isValid(y))
                throw new Error('invalid affine point');
            if (p instanceof Point)
                throw new Error('projective point not allowed');
            // (0, 0) would've produced (0, 0, 1) - instead, we need (0, 1, 0)
            if (Fp.is0(x) && Fp.is0(y))
                return Point.ZERO;
            return new Point(x, y, Fp.ONE);
        }
        static fromBytes(bytes) {
            const P = Point.fromAffine(decodePoint(abytes(bytes, undefined, 'point')));
            P.assertValidity();
            return P;
        }
        static fromHex(hex) {
            return Point.fromBytes(ensureBytes('pointHex', hex));
        }
        get x() {
            return this.toAffine().x;
        }
        get y() {
            return this.toAffine().y;
        }
        /**
         *
         * @param windowSize
         * @param isLazy true will defer table computation until the first multiplication
         * @returns
         */
        precompute(windowSize = 8, isLazy = true) {
            wnaf.createCache(this, windowSize);
            if (!isLazy)
                this.multiply(_3n); // random number
            return this;
        }
        // TODO: return `this`
        /** A point on curve is valid if it conforms to equation. */
        assertValidity() {
            assertValidMemo(this);
        }
        hasEvenY() {
            const { y } = this.toAffine();
            if (!Fp.isOdd)
                throw new Error("Field doesn't support isOdd");
            return !Fp.isOdd(y);
        }
        /** Compare one point to another. */
        equals(other) {
            aprjpoint(other);
            const { X: X1, Y: Y1, Z: Z1 } = this;
            const { X: X2, Y: Y2, Z: Z2 } = other;
            const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
            const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
            return U1 && U2;
        }
        /** Flips point to one corresponding to (x, -y) in Affine coordinates. */
        negate() {
            return new Point(this.X, Fp.neg(this.Y), this.Z);
        }
        // Renes-Costello-Batina exception-free doubling formula.
        // There is 30% faster Jacobian formula, but it is not complete.
        // https://eprint.iacr.org/2015/1060, algorithm 3
        // Cost: 8M + 3S + 3*a + 2*b3 + 15add.
        double() {
            const { a, b } = CURVE;
            const b3 = Fp.mul(b, _3n);
            const { X: X1, Y: Y1, Z: Z1 } = this;
            let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore
            let t0 = Fp.mul(X1, X1); // step 1
            let t1 = Fp.mul(Y1, Y1);
            let t2 = Fp.mul(Z1, Z1);
            let t3 = Fp.mul(X1, Y1);
            t3 = Fp.add(t3, t3); // step 5
            Z3 = Fp.mul(X1, Z1);
            Z3 = Fp.add(Z3, Z3);
            X3 = Fp.mul(a, Z3);
            Y3 = Fp.mul(b3, t2);
            Y3 = Fp.add(X3, Y3); // step 10
            X3 = Fp.sub(t1, Y3);
            Y3 = Fp.add(t1, Y3);
            Y3 = Fp.mul(X3, Y3);
            X3 = Fp.mul(t3, X3);
            Z3 = Fp.mul(b3, Z3); // step 15
            t2 = Fp.mul(a, t2);
            t3 = Fp.sub(t0, t2);
            t3 = Fp.mul(a, t3);
            t3 = Fp.add(t3, Z3);
            Z3 = Fp.add(t0, t0); // step 20
            t0 = Fp.add(Z3, t0);
            t0 = Fp.add(t0, t2);
            t0 = Fp.mul(t0, t3);
            Y3 = Fp.add(Y3, t0);
            t2 = Fp.mul(Y1, Z1); // step 25
            t2 = Fp.add(t2, t2);
            t0 = Fp.mul(t2, t3);
            X3 = Fp.sub(X3, t0);
            Z3 = Fp.mul(t2, t1);
            Z3 = Fp.add(Z3, Z3); // step 30
            Z3 = Fp.add(Z3, Z3);
            return new Point(X3, Y3, Z3);
        }
        // Renes-Costello-Batina exception-free addition formula.
        // There is 30% faster Jacobian formula, but it is not complete.
        // https://eprint.iacr.org/2015/1060, algorithm 1
        // Cost: 12M + 0S + 3*a + 3*b3 + 23add.
        add(other) {
            aprjpoint(other);
            const { X: X1, Y: Y1, Z: Z1 } = this;
            const { X: X2, Y: Y2, Z: Z2 } = other;
            let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore
            const a = CURVE.a;
            const b3 = Fp.mul(CURVE.b, _3n);
            let t0 = Fp.mul(X1, X2); // step 1
            let t1 = Fp.mul(Y1, Y2);
            let t2 = Fp.mul(Z1, Z2);
            let t3 = Fp.add(X1, Y1);
            let t4 = Fp.add(X2, Y2); // step 5
            t3 = Fp.mul(t3, t4);
            t4 = Fp.add(t0, t1);
            t3 = Fp.sub(t3, t4);
            t4 = Fp.add(X1, Z1);
            let t5 = Fp.add(X2, Z2); // step 10
            t4 = Fp.mul(t4, t5);
            t5 = Fp.add(t0, t2);
            t4 = Fp.sub(t4, t5);
            t5 = Fp.add(Y1, Z1);
            X3 = Fp.add(Y2, Z2); // step 15
            t5 = Fp.mul(t5, X3);
            X3 = Fp.add(t1, t2);
            t5 = Fp.sub(t5, X3);
            Z3 = Fp.mul(a, t4);
            X3 = Fp.mul(b3, t2); // step 20
            Z3 = Fp.add(X3, Z3);
            X3 = Fp.sub(t1, Z3);
            Z3 = Fp.add(t1, Z3);
            Y3 = Fp.mul(X3, Z3);
            t1 = Fp.add(t0, t0); // step 25
            t1 = Fp.add(t1, t0);
            t2 = Fp.mul(a, t2);
            t4 = Fp.mul(b3, t4);
            t1 = Fp.add(t1, t2);
            t2 = Fp.sub(t0, t2); // step 30
            t2 = Fp.mul(a, t2);
            t4 = Fp.add(t4, t2);
            t0 = Fp.mul(t1, t4);
            Y3 = Fp.add(Y3, t0);
            t0 = Fp.mul(t5, t4); // step 35
            X3 = Fp.mul(t3, X3);
            X3 = Fp.sub(X3, t0);
            t0 = Fp.mul(t3, t1);
            Z3 = Fp.mul(t5, Z3);
            Z3 = Fp.add(Z3, t0); // step 40
            return new Point(X3, Y3, Z3);
        }
        subtract(other) {
            return this.add(other.negate());
        }
        is0() {
            return this.equals(Point.ZERO);
        }
        /**
         * Constant time multiplication.
         * Uses wNAF method. Windowed method may be 10% faster,
         * but takes 2x longer to generate and consumes 2x memory.
         * Uses precomputes when available.
         * Uses endomorphism for Koblitz curves.
         * @param scalar by which the point would be multiplied
         * @returns New point
         */
        multiply(scalar) {
            const { endo } = extraOpts;
            if (!Fn.isValidNot0(scalar))
                throw new Error('invalid scalar: out of range'); // 0 is invalid
            let point, fake; // Fake point is used to const-time mult
            const mul = (n) => wnaf.cached(this, n, (p) => normalizeZ(Point, p));
            /** See docs for {@link EndomorphismOpts} */
            if (endo) {
                const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);
                const { p: k1p, f: k1f } = mul(k1);
                const { p: k2p, f: k2f } = mul(k2);
                fake = k1f.add(k2f);
                point = finishEndo(endo.beta, k1p, k2p, k1neg, k2neg);
            }
            else {
                const { p, f } = mul(scalar);
                point = p;
                fake = f;
            }
            // Normalize `z` for both points, but return only real one
            return normalizeZ(Point, [point, fake])[0];
        }
        /**
         * Non-constant-time multiplication. Uses double-and-add algorithm.
         * It's faster, but should only be used when you don't care about
         * an exposed secret key e.g. sig verification, which works over *public* keys.
         */
        multiplyUnsafe(sc) {
            const { endo } = extraOpts;
            const p = this;
            if (!Fn.isValid(sc))
                throw new Error('invalid scalar: out of range'); // 0 is valid
            if (sc === _0n || p.is0())
                return Point.ZERO;
            if (sc === _1n)
                return p; // fast-path
            if (wnaf.hasCache(this))
                return this.multiply(sc);
            if (endo) {
                const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);
                const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2); // 30% faster vs wnaf.unsafe
                return finishEndo(endo.beta, p1, p2, k1neg, k2neg);
            }
            else {
                return wnaf.unsafe(p, sc);
            }
        }
        multiplyAndAddUnsafe(Q, a, b) {
            const sum = this.multiplyUnsafe(a).add(Q.multiplyUnsafe(b));
            return sum.is0() ? undefined : sum;
        }
        /**
         * Converts Projective point to affine (x, y) coordinates.
         * @param invertedZ Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch
         */
        toAffine(invertedZ) {
            return toAffineMemo(this, invertedZ);
        }
        /**
         * Checks whether Point is free of torsion elements (is in prime subgroup).
         * Always torsion-free for cofactor=1 curves.
         */
        isTorsionFree() {
            const { isTorsionFree } = extraOpts;
            if (cofactor === _1n)
                return true;
            if (isTorsionFree)
                return isTorsionFree(Point, this);
            return wnaf.unsafe(this, CURVE_ORDER).is0();
        }
        clearCofactor() {
            const { clearCofactor } = extraOpts;
            if (cofactor === _1n)
                return this; // Fast-path
            if (clearCofactor)
                return clearCofactor(Point, this);
            return this.multiplyUnsafe(cofactor);
        }
        isSmallOrder() {
            // can we use this.clearCofactor()?
            return this.multiplyUnsafe(cofactor).is0();
        }
        toBytes(isCompressed = true) {
            abool(isCompressed, 'isCompressed');
            this.assertValidity();
            return encodePoint(Point, this, isCompressed);
        }
        toHex(isCompressed = true) {
            return bytesToHex(this.toBytes(isCompressed));
        }
        toString() {
            return `<Point ${this.is0() ? 'ZERO' : this.toHex()}>`;
        }
        // TODO: remove
        get px() {
            return this.X;
        }
        get py() {
            return this.X;
        }
        get pz() {
            return this.Z;
        }
        toRawBytes(isCompressed = true) {
            return this.toBytes(isCompressed);
        }
        _setWindowSize(windowSize) {
            this.precompute(windowSize);
        }
        static normalizeZ(points) {
            return normalizeZ(Point, points);
        }
        static msm(points, scalars) {
            return pippenger(Point, Fn, points, scalars);
        }
        static fromPrivateKey(privateKey) {
            return Point.BASE.multiply(_normFnElement(Fn, privateKey));
        }
    }
    // base / generator point
    Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
    // zero / infinity / identity point
    Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); // 0, 1, 0
    // math field
    Point.Fp = Fp;
    // scalar field
    Point.Fn = Fn;
    const bits = Fn.BITS;
    const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);
    Point.BASE.precompute(8); // Enable precomputes. Slows down first publicKey computation by 20ms.
    return Point;
}
// Points start with byte 0x02 when y is even; otherwise 0x03
function pprefix(hasEvenY) {
    return Uint8Array.of(hasEvenY ? 0x02 : 0x03);
}
/**
 * Implementation of the Shallue and van de Woestijne method for any weierstrass curve.
 * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular.
 * b = True and y = sqrt(u / v) if (u / v) is square in F, and
 * b = False and y = sqrt(Z * (u / v)) otherwise.
 * @param Fp
 * @param Z
 * @returns
 */
export function SWUFpSqrtRatio(Fp, Z) {
    // Generic implementation
    const q = Fp.ORDER;
    let l = _0n;
    for (let o = q - _1n; o % _2n === _0n; o /= _2n)
        l += _1n;
    const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1.
    // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<.
    // 2n ** c1 == 2n << (c1-1)
    const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n);
    const _2n_pow_c1 = _2n_pow_c1_1 * _2n;
    const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1)  # Integer arithmetic
    const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2            # Integer arithmetic
    const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1                # Integer arithmetic
    const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1)                  # Integer arithmetic
    const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2
    const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2)
    let sqrtRatio = (u, v) => {
        let tv1 = c6; // 1. tv1 = c6
        let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4
        let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2
        tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v
        let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3
        tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3
        tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2
        tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v
        tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u
        let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2
        tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5
        let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1
        tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7
        tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1
        tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR)
        tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR)
        // 17. for i in (c1, c1 - 1, ..., 2):
        for (let i = c1; i > _1n; i--) {
            let tv5 = i - _2n; // 18.    tv5 = i - 2
            tv5 = _2n << (tv5 - _1n); // 19.    tv5 = 2^tv5
            let tvv5 = Fp.pow(tv4, tv5); // 20.    tv5 = tv4^tv5
            const e1 = Fp.eql(tvv5, Fp.ONE); // 21.    e1 = tv5 == 1
            tv2 = Fp.mul(tv3, tv1); // 22.    tv2 = tv3 * tv1
            tv1 = Fp.mul(tv1, tv1); // 23.    tv1 = tv1 * tv1
            tvv5 = Fp.mul(tv4, tv1); // 24.    tv5 = tv4 * tv1
            tv3 = Fp.cmov(tv2, tv3, e1); // 25.    tv3 = CMOV(tv2, tv3, e1)
            tv4 = Fp.cmov(tvv5, tv4, e1); // 26.    tv4 = CMOV(tv5, tv4, e1)
        }
        return { isValid: isQR, value: tv3 };
    };
    if (Fp.ORDER % _4n === _3n) {
        // sqrt_ratio_3mod4(u, v)
        const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4     # Integer arithmetic
        const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z)
        sqrtRatio = (u, v) => {
            let tv1 = Fp.sqr(v); // 1. tv1 = v^2
            const tv2 = Fp.mul(u, v); // 2. tv2 = u * v
            tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2
            let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1
            y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2
            const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2
            const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v
            const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u
            let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR)
            return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2
        };
    }
    // No curves uses that
    // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8
    return sqrtRatio;
}
/**
 * Simplified Shallue-van de Woestijne-Ulas Method
 * https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2
 */
export function mapToCurveSimpleSWU(Fp, opts) {
    validateField(Fp);
    const { A, B, Z } = opts;
    if (!Fp.isValid(A) || !Fp.isValid(B) || !Fp.isValid(Z))
        throw new Error('mapToCurveSimpleSWU: invalid opts');
    const sqrtRatio = SWUFpSqrtRatio(Fp, Z);
    if (!Fp.isOdd)
        throw new Error('Field does not have .isOdd()');
    // Input: u, an element of F.
    // Output: (x, y), a point on E.
    return (u) => {
        // prettier-ignore
        let tv1, tv2, tv3, tv4, tv5, tv6, x, y;
        tv1 = Fp.sqr(u); // 1.  tv1 = u^2
        tv1 = Fp.mul(tv1, Z); // 2.  tv1 = Z * tv1
        tv2 = Fp.sqr(tv1); // 3.  tv2 = tv1^2
        tv2 = Fp.add(tv2, tv1); // 4.  tv2 = tv2 + tv1
        tv3 = Fp.add(tv2, Fp.ONE); // 5.  tv3 = tv2 + 1
        tv3 = Fp.mul(tv3, B); // 6.  tv3 = B * tv3
        tv4 = Fp.cmov(Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7.  tv4 = CMOV(Z, -tv2, tv2 != 0)
        tv4 = Fp.mul(tv4, A); // 8.  tv4 = A * tv4
        tv2 = Fp.sqr(tv3); // 9.  tv2 = tv3^2
        tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2
        tv5 = Fp.mul(tv6, A); // 11. tv5 = A * tv6
        tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5
        tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3
        tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4
        tv5 = Fp.mul(tv6, B); // 15. tv5 = B * tv6
        tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5
        x = Fp.mul(tv1, tv3); // 17.   x = tv1 * tv3
        const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6)
        y = Fp.mul(tv1, u); // 19.   y = tv1 * u  -> Z * u^3 * y1
        y = Fp.mul(y, value); // 20.   y = y * y1
        x = Fp.cmov(x, tv3, isValid); // 21.   x = CMOV(x, tv3, is_gx1_square)
        y = Fp.cmov(y, value, isValid); // 22.   y = CMOV(y, y1, is_gx1_square)
        const e1 = Fp.isOdd(u) === Fp.isOdd(y); // 23.  e1 = sgn0(u) == sgn0(y)
        y = Fp.cmov(Fp.neg(y), y, e1); // 24.   y = CMOV(-y, y, e1)
        const tv4_inv = FpInvertBatch(Fp, [tv4], true)[0];
        x = Fp.mul(x, tv4_inv); // 25.   x = x / tv4
        return { x, y };
    };
}
function getWLengths(Fp, Fn) {
    return {
        secretKey: Fn.BYTES,
        publicKey: 1 + Fp.BYTES,
        publicKeyUncompressed: 1 + 2 * Fp.BYTES,
        publicKeyHasPrefix: true,
        signature: 2 * Fn.BYTES,
    };
}
/**
 * Sometimes users only need getPublicKey, getSharedSecret, and secret key handling.
 * This helper ensures no signature functionality is present. Less code, smaller bundle size.
 */
export function ecdh(Point, ecdhOpts = {}) {
    const { Fn } = Point;
    const randomBytes_ = ecdhOpts.randomBytes || randomBytesWeb;
    const lengths = Object.assign(getWLengths(Point.Fp, Fn), { seed: getMinHashLength(Fn.ORDER) });
    function isValidSecretKey(secretKey) {
        try {
            return !!_normFnElement(Fn, secretKey);
        }
        catch (error) {
            return false;
        }
    }
    function isValidPublicKey(publicKey, isCompressed) {
        const { publicKey: comp, publicKeyUncompressed } = lengths;
        try {
            const l = publicKey.length;
            if (isCompressed === true && l !== comp)
                return false;
            if (isCompressed === false && l !== publicKeyUncompressed)
                return false;
            return !!Point.fromBytes(publicKey);
        }
        catch (error) {
            return false;
        }
    }
    /**
     * Produces cryptographically secure secret key from random of size
     * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.
     */
    function randomSecretKey(seed = randomBytes_(lengths.seed)) {
        return mapHashToField(abytes(seed, lengths.seed, 'seed'), Fn.ORDER);
    }
    /**
     * Computes public key for a secret key. Checks for validity of the secret key.
     * @param isCompressed whether to return compact (default), or full key
     * @returns Public key, full when isCompressed=false; short when isCompressed=true
     */
    function getPublicKey(secretKey, isCompressed = true) {
        return Point.BASE.multiply(_normFnElement(Fn, secretKey)).toBytes(isCompressed);
    }
    function keygen(seed) {
        const secretKey = randomSecretKey(seed);
        return { secretKey, publicKey: getPublicKey(secretKey) };
    }
    /**
     * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.
     */
    function isProbPub(item) {
        if (typeof item === 'bigint')
            return false;
        if (item instanceof Point)
            return true;
        const { secretKey, publicKey, publicKeyUncompressed } = lengths;
        if (Fn.allowedLengths || secretKey === publicKey)
            return undefined;
        const l = ensureBytes('key', item).length;
        return l === publicKey || l === publicKeyUncompressed;
    }
    /**
     * ECDH (Elliptic Curve Diffie Hellman).
     * Computes shared public key from secret key A and public key B.
     * Checks: 1) secret key validity 2) shared key is on-curve.
     * Does NOT hash the result.
     * @param isCompressed whether to return compact (default), or full key
     * @returns shared public key
     */
    function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {
        if (isProbPub(secretKeyA) === true)
            throw new Error('first arg must be private key');
        if (isProbPub(publicKeyB) === false)
            throw new Error('second arg must be public key');
        const s = _normFnElement(Fn, secretKeyA);
        const b = Point.fromHex(publicKeyB); // checks for being on-curve
        return b.multiply(s).toBytes(isCompressed);
    }
    const utils = {
        isValidSecretKey,
        isValidPublicKey,
        randomSecretKey,
        // TODO: remove
        isValidPrivateKey: isValidSecretKey,
        randomPrivateKey: randomSecretKey,
        normPrivateKeyToScalar: (key) => _normFnElement(Fn, key),
        precompute(windowSize = 8, point = Point.BASE) {
            return point.precompute(windowSize, false);
        },
    };
    return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point, utils, lengths });
}
/**
 * Creates ECDSA signing interface for given elliptic curve `Point` and `hash` function.
 * We need `hash` for 2 features:
 * 1. Message prehash-ing. NOT used if `sign` / `verify` are called with `prehash: false`
 * 2. k generation in `sign`, using HMAC-drbg(hash)
 *
 * ECDSAOpts are only rarely needed.
 *
 * @example
 * ```js
 * const p256_Point = weierstrass(...);
 * const p256_sha256 = ecdsa(p256_Point, sha256);
 * const p256_sha224 = ecdsa(p256_Point, sha224);
 * const p256_sha224_r = ecdsa(p256_Point, sha224, { randomBytes: (length) => { ... } });
 * ```
 */
export function ecdsa(Point, hash, ecdsaOpts = {}) {
    ahash(hash);
    _validateObject(ecdsaOpts, {}, {
        hmac: 'function',
        lowS: 'boolean',
        randomBytes: 'function',
        bits2int: 'function',
        bits2int_modN: 'function',
    });
    const randomBytes = ecdsaOpts.randomBytes || randomBytesWeb;
    const hmac = ecdsaOpts.hmac ||
        ((key, ...msgs) => nobleHmac(hash, key, concatBytes(...msgs)));
    const { Fp, Fn } = Point;
    const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;
    const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);
    const defaultSigOpts = {
        prehash: false,
        lowS: typeof ecdsaOpts.lowS === 'boolean' ? ecdsaOpts.lowS : false,
        format: undefined, //'compact' as ECDSASigFormat,
        extraEntropy: false,
    };
    const defaultSigOpts_format = 'compact';
    function isBiggerThanHalfOrder(number) {
        const HALF = CURVE_ORDER >> _1n;
        return number > HALF;
    }
    function validateRS(title, num) {
        if (!Fn.isValidNot0(num))
            throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);
        return num;
    }
    function validateSigLength(bytes, format) {
        validateSigFormat(format);
        const size = lengths.signature;
        const sizer = format === 'compact' ? size : format === 'recovered' ? size + 1 : undefined;
        return abytes(bytes, sizer, `${format} signature`);
    }
    /**
     * ECDSA signature with its (r, s) properties. Supports compact, recovered & DER representations.
     */
    class Signature {
        constructor(r, s, recovery) {
            this.r = validateRS('r', r); // r in [1..N-1];
            this.s = validateRS('s', s); // s in [1..N-1];
            if (recovery != null)
                this.recovery = recovery;
            Object.freeze(this);
        }
        static fromBytes(bytes, format = defaultSigOpts_format) {
            validateSigLength(bytes, format);
            let recid;
            if (format === 'der') {
                const { r, s } = DER.toSig(abytes(bytes));
                return new Signature(r, s);
            }
            if (format === 'recovered') {
                recid = bytes[0];
                format = 'compact';
                bytes = bytes.subarray(1);
            }
            const L = Fn.BYTES;
            const r = bytes.subarray(0, L);
            const s = bytes.subarray(L, L * 2);
            return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);
        }
        static fromHex(hex, format) {
            return this.fromBytes(hexToBytes(hex), format);
        }
        addRecoveryBit(recovery) {
            return new Signature(this.r, this.s, recovery);
        }
        recoverPublicKey(messageHash) {
            const FIELD_ORDER = Fp.ORDER;
            const { r, s, recovery: rec } = this;
            if (rec == null || ![0, 1, 2, 3].includes(rec))
                throw new Error('recovery id invalid');
            // ECDSA recovery is hard for cofactor > 1 curves.
            // In sign, `r = q.x mod n`, and here we recover q.x from r.
            // While recovering q.x >= n, we need to add r+n for cofactor=1 curves.
            // However, for cofactor>1, r+n may not get q.x:
            // r+n*i would need to be done instead where i is unknown.
            // To easily get i, we either need to:
            // a. increase amount of valid recid values (4, 5...); OR
            // b. prohibit non-prime-order signatures (recid > 1).
            const hasCofactor = CURVE_ORDER * _2n < FIELD_ORDER;
            if (hasCofactor && rec > 1)
                throw new Error('recovery id is ambiguous for h>1 curve');
            const radj = rec === 2 || rec === 3 ? r + CURVE_ORDER : r;
            if (!Fp.isValid(radj))
                throw new Error('recovery id 2 or 3 invalid');
            const x = Fp.toBytes(radj);
            const R = Point.fromBytes(concatBytes(pprefix((rec & 1) === 0), x));
            const ir = Fn.inv(radj); // r^-1
            const h = bits2int_modN(ensureBytes('msgHash', messageHash)); // Truncate hash
            const u1 = Fn.create(-h * ir); // -hr^-1
            const u2 = Fn.create(s * ir); // sr^-1
            // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1). unsafe is fine: there is no private data.
            const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));
            if (Q.is0())
                throw new Error('point at infinify');
            Q.assertValidity();
            return Q;
        }
        // Signatures should be low-s, to prevent malleability.
        hasHighS() {
            return isBiggerThanHalfOrder(this.s);
        }
        toBytes(format = defaultSigOpts_format) {
            validateSigFormat(format);
            if (format === 'der')
                return hexToBytes(DER.hexFromSig(this));
            const r = Fn.toBytes(this.r);
            const s = Fn.toBytes(this.s);
            if (format === 'recovered') {
                if (this.recovery == null)
                    throw new Error('recovery bit must be present');
                return concatBytes(Uint8Array.of(this.recovery), r, s);
            }
            return concatBytes(r, s);
        }
        toHex(format) {
            return bytesToHex(this.toBytes(format));
        }
        // TODO: remove
        assertValidity() { }
        static fromCompact(hex) {
            return Signature.fromBytes(ensureBytes('sig', hex), 'compact');
        }
        static fromDER(hex) {
            return Signature.fromBytes(ensureBytes('sig', hex), 'der');
        }
        normalizeS() {
            return this.hasHighS() ? new Signature(this.r, Fn.neg(this.s), this.recovery) : this;
        }
        toDERRawBytes() {
            return this.toBytes('der');
        }
        toDERHex() {
            return bytesToHex(this.toBytes('der'));
        }
        toCompactRawBytes() {
            return this.toBytes('compact');
        }
        toCompactHex() {
            return bytesToHex(this.toBytes('compact'));
        }
    }
    // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.
    // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.
    // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.
    // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors
    const bits2int = ecdsaOpts.bits2int ||
        function bits2int_def(bytes) {
            // Our custom check "just in case", for protection against DoS
            if (bytes.length > 8192)
                throw new Error('input is too large');
            // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)
            // for some cases, since bytes.length * 8 is not actual bitLength.
            const num = bytesToNumberBE(bytes); // check for == u8 done here
            const delta = bytes.length * 8 - fnBits; // truncate to nBitLength leftmost bits
            return delta > 0 ? num >> BigInt(delta) : num;
        };
    const bits2int_modN = ecdsaOpts.bits2int_modN ||
        function bits2int_modN_def(bytes) {
            return Fn.create(bits2int(bytes)); // can't use bytesToNumberBE here
        };
    // Pads output with zero as per spec
    const ORDER_MASK = bitMask(fnBits);
    /** Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. */
    function int2octets(num) {
        // IMPORTANT: the check ensures working for case `Fn.BYTES != Fn.BITS * 8`
        aInRange('num < 2^' + fnBits, num, _0n, ORDER_MASK);
        return Fn.toBytes(num);
    }
    function validateMsgAndHash(message, prehash) {
        abytes(message, undefined, 'message');
        return prehash ? abytes(hash(message), undefined, 'prehashed message') : message;
    }
    /**
     * Steps A, D of RFC6979 3.2.
     * Creates RFC6979 seed; converts msg/privKey to numbers.
     * Used only in sign, not in verify.
     *
     * Warning: we cannot assume here that message has same amount of bytes as curve order,
     * this will be invalid at least for P521. Also it can be bigger for P224 + SHA256.
     */
    function prepSig(message, privateKey, opts) {
        if (['recovered', 'canonical'].some((k) => k in opts))
            throw new Error('sign() legacy options not supported');
        const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);
        message = validateMsgAndHash(message, prehash); // RFC6979 3.2 A: h1 = H(m)
        // We can't later call bits2octets, since nested bits2int is broken for curves
        // with fnBits % 8 !== 0. Because of that, we unwrap it here as int2octets call.
        // const bits2octets = (bits) => int2octets(bits2int_modN(bits))
        const h1int = bits2int_modN(message);
        const d = _normFnElement(Fn, privateKey); // validate secret key, convert to bigint
        const seedArgs = [int2octets(d), int2octets(h1int)];
        // extraEntropy. RFC6979 3.6: additional k' (optional).
        if (extraEntropy != null && extraEntropy !== false) {
            // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')
            // gen random bytes OR pass as-is
            const e = extraEntropy === true ? randomBytes(lengths.secretKey) : extraEntropy;
            seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes
        }
        const seed = concatBytes(...seedArgs); // Step D of RFC6979 3.2
        const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash!
        // Converts signature params into point w r/s, checks result for validity.
        // To transform k => Signature:
        // q = k⋅G
        // r = q.x mod n
        // s = k^-1(m + rd) mod n
        // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to
        // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:
        // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT
        function k2sig(kBytes) {
            // RFC 6979 Section 3.2, step 3: k = bits2int(T)
            // Important: all mod() calls here must be done over N
            const k = bits2int(kBytes); // mod n, not mod p
            if (!Fn.isValidNot0(k))
                return; // Valid scalars (including k) must be in 1..N-1
            const ik = Fn.inv(k); // k^-1 mod n
            const q = Point.BASE.multiply(k).toAffine(); // q = k⋅G
            const r = Fn.create(q.x); // r = q.x mod n
            if (r === _0n)
                return;
            const s = Fn.create(ik * Fn.create(m + r * d)); // Not using blinding here, see comment above
            if (s === _0n)
                return;
            let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n)
            let normS = s;
            if (lowS && isBiggerThanHalfOrder(s)) {
                normS = Fn.neg(s); // if lowS was passed, ensure s is always
                recovery ^= 1; // // in the bottom half of N
            }
            return new Signature(r, normS, recovery); // use normS, not s
        }
        return { seed, k2sig };
    }
    /**
     * Signs message hash with a secret key.
     *
     * ```
     * sign(m, d) where
     *   k = rfc6979_hmac_drbg(m, d)
     *   (x, y) = G × k
     *   r = x mod n
     *   s = (m + dr) / k mod n
     * ```
     */
    function sign(message, secretKey, opts = {}) {
        message = ensureBytes('message', message);
        const { seed, k2sig } = prepSig(message, secretKey, opts); // Steps A, D of RFC6979 3.2.
        const drbg = createHmacDrbg(hash.outputLen, Fn.BYTES, hmac);
        const sig = drbg(seed, k2sig); // Steps B, C, D, E, F, G
        return sig;
    }
    function tryParsingSig(sg) {
        // Try to deduce format
        let sig = undefined;
        const isHex = typeof sg === 'string' || isBytes(sg);
        const isObj = !isHex &&
            sg !== null &&
            typeof sg === 'object' &&
            typeof sg.r === 'bigint' &&
            typeof sg.s === 'bigint';
        if (!isHex && !isObj)
            throw new Error('invalid signature, expected Uint8Array, hex string or Signature instance');
        if (isObj) {
            sig = new Signature(sg.r, sg.s);
        }
        else if (isHex) {
            try {
                sig = Signature.fromBytes(ensureBytes('sig', sg), 'der');
            }
            catch (derError) {
                if (!(derError instanceof DER.Err))
                    throw derError;
            }
            if (!sig) {
                try {
                    sig = Signature.fromBytes(ensureBytes('sig', sg), 'compact');
                }
                catch (error) {
                    return false;
                }
            }
        }
        if (!sig)
            return false;
        return sig;
    }
    /**
     * Verifies a signature against message and public key.
     * Rejects lowS signatures by default: see {@link ECDSAVerifyOpts}.
     * Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:
     *
     * ```
     * verify(r, s, h, P) where
     *   u1 = hs^-1 mod n
     *   u2 = rs^-1 mod n
     *   R = u1⋅G + u2⋅P
     *   mod(R.x, n) == r
     * ```
     */
    function verify(signature, message, publicKey, opts = {}) {
        const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);
        publicKey = ensureBytes('publicKey', publicKey);
        message = validateMsgAndHash(ensureBytes('message', message), prehash);
        if ('strict' in opts)
            throw new Error('options.strict was renamed to lowS');
        const sig = format === undefined
            ? tryParsingSig(signature)
            : Signature.fromBytes(ensureBytes('sig', signature), format);
        if (sig === false)
            return false;
        try {
            const P = Point.fromBytes(publicKey);
            if (lowS && sig.hasHighS())
                return false;
            const { r, s } = sig;
            const h = bits2int_modN(message); // mod n, not mod p
            const is = Fn.inv(s); // s^-1 mod n
            const u1 = Fn.create(h * is); // u1 = hs^-1 mod n
            const u2 = Fn.create(r * is); // u2 = rs^-1 mod n
            const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2)); // u1⋅G + u2⋅P
            if (R.is0())
                return false;
            const v = Fn.create(R.x); // v = r.x mod n
            return v === r;
        }
        catch (e) {
            return false;
        }
    }
    function recoverPublicKey(signature, message, opts = {}) {
        const { prehash } = validateSigOpts(opts, defaultSigOpts);
        message = validateMsgAndHash(message, prehash);
        return Signature.fromBytes(signature, 'recovered').recoverPublicKey(message).toBytes();
    }
    return Object.freeze({
        keygen,
        getPublicKey,
        getSharedSecret,
        utils,
        lengths,
        Point,
        sign,
        verify,
        recoverPublicKey,
        Signature,
        hash,
    });
}
/** @deprecated use `weierstrass` in newer releases */
export function weierstrassPoints(c) {
    const { CURVE, curveOpts } = _weierstrass_legacy_opts_to_new(c);
    const Point = weierstrassN(CURVE, curveOpts);
    return _weierstrass_new_output_to_legacy(c, Point);
}
function _weierstrass_legacy_opts_to_new(c) {
    const CURVE = {
        a: c.a,
        b: c.b,
        p: c.Fp.ORDER,
        n: c.n,
        h: c.h,
        Gx: c.Gx,
        Gy: c.Gy,
    };
    const Fp = c.Fp;
    let allowedLengths = c.allowedPrivateKeyLengths
        ? Array.from(new Set(c.allowedPrivateKeyLengths.map((l) => Math.ceil(l / 2))))
        : undefined;
    const Fn = Field(CURVE.n, {
        BITS: c.nBitLength,
        allowedLengths: allowedLengths,
        modFromBytes: c.wrapPrivateKey,
    });
    const curveOpts = {
        Fp,
        Fn,
        allowInfinityPoint: c.allowInfinityPoint,
        endo: c.endo,
        isTorsionFree: c.isTorsionFree,
        clearCofactor: c.clearCofactor,
        fromBytes: c.fromBytes,
        toBytes: c.toBytes,
    };
    return { CURVE, curveOpts };
}
function _ecdsa_legacy_opts_to_new(c) {
    const { CURVE, curveOpts } = _weierstrass_legacy_opts_to_new(c);
    const ecdsaOpts = {
        hmac: c.hmac,
        randomBytes: c.randomBytes,
        lowS: c.lowS,
        bits2int: c.bits2int,
        bits2int_modN: c.bits2int_modN,
    };
    return { CURVE, curveOpts, hash: c.hash, ecdsaOpts };
}
export function _legacyHelperEquat(Fp, a, b) {
    /**
     * y² = x³ + ax + b: Short weierstrass curve formula. Takes x, returns y².
     * @returns y²
     */
    function weierstrassEquation(x) {
        const x2 = Fp.sqr(x); // x * x
        const x3 = Fp.mul(x2, x); // x² * x
        return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x³ + a * x + b
    }
    return weierstrassEquation;
}
function _weierstrass_new_output_to_legacy(c, Point) {
    const { Fp, Fn } = Point;
    function isWithinCurveOrder(num) {
        return inRange(num, _1n, Fn.ORDER);
    }
    const weierstrassEquation = _legacyHelperEquat(Fp, c.a, c.b);
    return Object.assign({}, {
        CURVE: c,
        Point: Point,
        ProjectivePoint: Point,
        normPrivateKeyToScalar: (key) => _normFnElement(Fn, key),
        weierstrassEquation,
        isWithinCurveOrder,
    });
}
function _ecdsa_new_output_to_legacy(c, _ecdsa) {
    const Point = _ecdsa.Point;
    return Object.assign({}, _ecdsa, {
        ProjectivePoint: Point,
        CURVE: Object.assign({}, c, nLength(Point.Fn.ORDER, Point.Fn.BITS)),
    });
}
// _ecdsa_legacy
export function weierstrass(c) {
    const { CURVE, curveOpts, hash, ecdsaOpts } = _ecdsa_legacy_opts_to_new(c);
    const Point = weierstrassN(CURVE, curveOpts);
    const signs = ecdsa(Point, hash, ecdsaOpts);
    return _ecdsa_new_output_to_legacy(c, signs);
}
//# sourceMappingURL=weierstrass.js.map{
  "type": "module",
  "sideEffects": false
}
/**
 * SECG secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).
 *
 * Belongs to Koblitz curves: it has efficiently-computable GLV endomorphism ψ,
 * check out {@link EndomorphismOpts}. Seems to be rigid (not backdoored).
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { sha256 } from '@noble/hashes/sha2.js';
import { randomBytes } from '@noble/hashes/utils.js';
import { createCurve } from "./_shortw_utils.js";
import { createHasher, isogenyMap, } from "./abstract/hash-to-curve.js";
import { Field, mapHashToField, mod, pow2 } from "./abstract/modular.js";
import { _normFnElement, mapToCurveSimpleSWU, } from "./abstract/weierstrass.js";
import { bytesToNumberBE, concatBytes, ensureBytes, inRange, numberToBytesBE, utf8ToBytes, } from "./utils.js";
// Seems like generator was produced from some seed:
// `Point.BASE.multiply(Point.Fn.inv(2n, N)).toAffine().x`
// // gives short x 0x3b78ce563f89a0ed9414f5aa28ad0d96d6795f9c63n
const secp256k1_CURVE = {
    p: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'),
    n: BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'),
    h: BigInt(1),
    a: BigInt(0),
    b: BigInt(7),
    Gx: BigInt('0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'),
    Gy: BigInt('0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8'),
};
const secp256k1_ENDO = {
    beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),
    basises: [
        [BigInt('0x3086d221a7d46bcde86c90e49284eb15'), -BigInt('0xe4437ed6010e88286f547fa90abfe4c3')],
        [BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'), BigInt('0x3086d221a7d46bcde86c90e49284eb15')],
    ],
};
const _0n = /* @__PURE__ */ BigInt(0);
const _1n = /* @__PURE__ */ BigInt(1);
const _2n = /* @__PURE__ */ BigInt(2);
/**
 * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.
 * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]
 */
function sqrtMod(y) {
    const P = secp256k1_CURVE.p;
    // prettier-ignore
    const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
    // prettier-ignore
    const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
    const b2 = (y * y * y) % P; // x^3, 11
    const b3 = (b2 * b2 * y) % P; // x^7
    const b6 = (pow2(b3, _3n, P) * b3) % P;
    const b9 = (pow2(b6, _3n, P) * b3) % P;
    const b11 = (pow2(b9, _2n, P) * b2) % P;
    const b22 = (pow2(b11, _11n, P) * b11) % P;
    const b44 = (pow2(b22, _22n, P) * b22) % P;
    const b88 = (pow2(b44, _44n, P) * b44) % P;
    const b176 = (pow2(b88, _88n, P) * b88) % P;
    const b220 = (pow2(b176, _44n, P) * b44) % P;
    const b223 = (pow2(b220, _3n, P) * b3) % P;
    const t1 = (pow2(b223, _23n, P) * b22) % P;
    const t2 = (pow2(t1, _6n, P) * b2) % P;
    const root = pow2(t2, _2n, P);
    if (!Fpk1.eql(Fpk1.sqr(root), y))
        throw new Error('Cannot find square root');
    return root;
}
const Fpk1 = Field(secp256k1_CURVE.p, { sqrt: sqrtMod });
/**
 * secp256k1 curve, ECDSA and ECDH methods.
 *
 * Field: `2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n`
 *
 * @example
 * ```js
 * import { secp256k1 } from '@noble/curves/secp256k1';
 * const { secretKey, publicKey } = secp256k1.keygen();
 * const msg = new TextEncoder().encode('hello');
 * const sig = secp256k1.sign(msg, secretKey);
 * const isValid = secp256k1.verify(sig, msg, publicKey) === true;
 * ```
 */
export const secp256k1 = createCurve({ ...secp256k1_CURVE, Fp: Fpk1, lowS: true, endo: secp256k1_ENDO }, sha256);
// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.
// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki
/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */
const TAGGED_HASH_PREFIXES = {};
function taggedHash(tag, ...messages) {
    let tagP = TAGGED_HASH_PREFIXES[tag];
    if (tagP === undefined) {
        const tagH = sha256(utf8ToBytes(tag));
        tagP = concatBytes(tagH, tagH);
        TAGGED_HASH_PREFIXES[tag] = tagP;
    }
    return sha256(concatBytes(tagP, ...messages));
}
// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03
const pointToBytes = (point) => point.toBytes(true).slice(1);
const Pointk1 = /* @__PURE__ */ (() => secp256k1.Point)();
const hasEven = (y) => y % _2n === _0n;
// Calculate point, scalar and bytes
function schnorrGetExtPubKey(priv) {
    const { Fn, BASE } = Pointk1;
    const d_ = _normFnElement(Fn, priv);
    const p = BASE.multiply(d_); // P = d'⋅G; 0 < d' < n check is done inside
    const scalar = hasEven(p.y) ? d_ : Fn.neg(d_);
    return { scalar, bytes: pointToBytes(p) };
}
/**
 * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.
 * @returns valid point checked for being on-curve
 */
function lift_x(x) {
    const Fp = Fpk1;
    if (!Fp.isValidNot0(x))
        throw new Error('invalid x: Fail if x ≥ p');
    const xx = Fp.create(x * x);
    const c = Fp.create(xx * x + BigInt(7)); // Let c = x³ + 7 mod p.
    let y = Fp.sqrt(c); // Let y = c^(p+1)/4 mod p. Same as sqrt().
    // Return the unique point P such that x(P) = x and
    // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.
    if (!hasEven(y))
        y = Fp.neg(y);
    const p = Pointk1.fromAffine({ x, y });
    p.assertValidity();
    return p;
}
const num = bytesToNumberBE;
/**
 * Create tagged hash, convert it to bigint, reduce modulo-n.
 */
function challenge(...args) {
    return Pointk1.Fn.create(num(taggedHash('BIP0340/challenge', ...args)));
}
/**
 * Schnorr public key is just `x` coordinate of Point as per BIP340.
 */
function schnorrGetPublicKey(secretKey) {
    return schnorrGetExtPubKey(secretKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G)
}
/**
 * Creates Schnorr signature as per BIP340. Verifies itself before returning anything.
 * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous.
 */
function schnorrSign(message, secretKey, auxRand = randomBytes(32)) {
    const { Fn } = Pointk1;
    const m = ensureBytes('message', message);
    const { bytes: px, scalar: d } = schnorrGetExtPubKey(secretKey); // checks for isWithinCurveOrder
    const a = ensureBytes('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array
    const t = Fn.toBytes(d ^ num(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a)
    const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m)
    // Let k' = int(rand) mod n. Fail if k' = 0. Let R = k'⋅G
    const { bytes: rx, scalar: k } = schnorrGetExtPubKey(rand);
    const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.
    const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n).
    sig.set(rx, 0);
    sig.set(Fn.toBytes(Fn.create(k + e * d)), 32);
    // If Verify(bytes(P), m, sig) (see below) returns failure, abort
    if (!schnorrVerify(sig, m, px))
        throw new Error('sign: Invalid signature produced');
    return sig;
}
/**
 * Verifies Schnorr signature.
 * Will swallow errors & return false except for initial type validation of arguments.
 */
function schnorrVerify(signature, message, publicKey) {
    const { Fn, BASE } = Pointk1;
    const sig = ensureBytes('signature', signature, 64);
    const m = ensureBytes('message', message);
    const pub = ensureBytes('publicKey', publicKey, 32);
    try {
        const P = lift_x(num(pub)); // P = lift_x(int(pk)); fail if that fails
        const r = num(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r ≥ p.
        if (!inRange(r, _1n, secp256k1_CURVE.p))
            return false;
        const s = num(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n.
        if (!inRange(s, _1n, secp256k1_CURVE.n))
            return false;
        // int(challenge(bytes(r)||bytes(P)||m))%n
        const e = challenge(Fn.toBytes(r), pointToBytes(P), m);
        // R = s⋅G - e⋅P, where -eP == (n-e)P
        const R = BASE.multiplyUnsafe(s).add(P.multiplyUnsafe(Fn.neg(e)));
        const { x, y } = R.toAffine();
        // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r.
        if (R.is0() || !hasEven(y) || x !== r)
            return false;
        return true;
    }
    catch (error) {
        return false;
    }
}
/**
 * Schnorr signatures over secp256k1.
 * https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki
 * @example
 * ```js
 * import { schnorr } from '@noble/curves/secp256k1';
 * const { secretKey, publicKey } = schnorr.keygen();
 * // const publicKey = schnorr.getPublicKey(secretKey);
 * const msg = new TextEncoder().encode('hello');
 * const sig = schnorr.sign(msg, secretKey);
 * const isValid = schnorr.verify(sig, msg, publicKey);
 * ```
 */
export const schnorr = /* @__PURE__ */ (() => {
    const size = 32;
    const seedLength = 48;
    const randomSecretKey = (seed = randomBytes(seedLength)) => {
        return mapHashToField(seed, secp256k1_CURVE.n);
    };
    // TODO: remove
    secp256k1.utils.randomSecretKey;
    function keygen(seed) {
        const secretKey = randomSecretKey(seed);
        return { secretKey, publicKey: schnorrGetPublicKey(secretKey) };
    }
    return {
        keygen,
        getPublicKey: schnorrGetPublicKey,
        sign: schnorrSign,
        verify: schnorrVerify,
        Point: Pointk1,
        utils: {
            randomSecretKey: randomSecretKey,
            randomPrivateKey: randomSecretKey,
            taggedHash,
            // TODO: remove
            lift_x,
            pointToBytes,
            numberToBytesBE,
            bytesToNumberBE,
            mod,
        },
        lengths: {
            secretKey: size,
            publicKey: size,
            publicKeyHasPrefix: false,
            signature: size * 2,
            seed: seedLength,
        },
    };
})();
const isoMap = /* @__PURE__ */ (() => isogenyMap(Fpk1, [
    // xNum
    [
        '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7',
        '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581',
        '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262',
        '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c',
    ],
    // xDen
    [
        '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b',
        '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14',
        '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1
    ],
    // yNum
    [
        '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c',
        '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3',
        '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931',
        '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84',
    ],
    // yDen
    [
        '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b',
        '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573',
        '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f',
        '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1
    ],
].map((i) => i.map((j) => BigInt(j)))))();
const mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fpk1, {
    A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),
    B: BigInt('1771'),
    Z: Fpk1.create(BigInt('-11')),
}))();
/** Hashing / encoding to secp256k1 points / field. RFC 9380 methods. */
export const secp256k1_hasher = /* @__PURE__ */ (() => createHasher(secp256k1.Point, (scalars) => {
    const { x, y } = mapSWU(Fpk1.create(scalars[0]));
    return isoMap(x, y);
}, {
    DST: 'secp256k1_XMD:SHA-256_SSWU_RO_',
    encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_',
    p: Fpk1.ORDER,
    m: 1,
    k: 128,
    expand: 'xmd',
    hash: sha256,
}))();
/** @deprecated use `import { secp256k1_hasher } from '@noble/curves/secp256k1.js';` */
export const hashToCurve = /* @__PURE__ */ (() => secp256k1_hasher.hashToCurve)();
/** @deprecated use `import { secp256k1_hasher } from '@noble/curves/secp256k1.js';` */
export const encodeToCurve = /* @__PURE__ */ (() => secp256k1_hasher.encodeToCurve)();
//# sourceMappingURL=secp256k1.js.map/**
 * Hex, bytes and number utilities.
 * @module
 */
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { abytes as abytes_, bytesToHex as bytesToHex_, concatBytes as concatBytes_, hexToBytes as hexToBytes_, isBytes as isBytes_, } from '@noble/hashes/utils.js';
export { abytes, anumber, bytesToHex, bytesToUtf8, concatBytes, hexToBytes, isBytes, randomBytes, utf8ToBytes, } from '@noble/hashes/utils.js';
const _0n = /* @__PURE__ */ BigInt(0);
const _1n = /* @__PURE__ */ BigInt(1);
export function abool(title, value) {
    if (typeof value !== 'boolean')
        throw new Error(title + ' boolean expected, got ' + value);
}
// tmp name until v2
export function _abool2(value, title = '') {
    if (typeof value !== 'boolean') {
        const prefix = title && `"${title}"`;
        throw new Error(prefix + 'expected boolean, got type=' + typeof value);
    }
    return value;
}
// tmp name until v2
/** Asserts something is Uint8Array. */
export function _abytes2(value, length, title = '') {
    const bytes = isBytes_(value);
    const len = value?.length;
    const needsLen = length !== undefined;
    if (!bytes || (needsLen && len !== length)) {
        const prefix = title && `"${title}" `;
        const ofLen = needsLen ? ` of length ${length}` : '';
        const got = bytes ? `length=${len}` : `type=${typeof value}`;
        throw new Error(prefix + 'expected Uint8Array' + ofLen + ', got ' + got);
    }
    return value;
}
// Used in weierstrass, der
export function numberToHexUnpadded(num) {
    const hex = num.toString(16);
    return hex.length & 1 ? '0' + hex : hex;
}
export function hexToNumber(hex) {
    if (typeof hex !== 'string')
        throw new Error('hex string expected, got ' + typeof hex);
    return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian
}
// BE: Big Endian, LE: Little Endian
export function bytesToNumberBE(bytes) {
    return hexToNumber(bytesToHex_(bytes));
}
export function bytesToNumberLE(bytes) {
    abytes_(bytes);
    return hexToNumber(bytesToHex_(Uint8Array.from(bytes).reverse()));
}
export function numberToBytesBE(n, len) {
    return hexToBytes_(n.toString(16).padStart(len * 2, '0'));
}
export function numberToBytesLE(n, len) {
    return numberToBytesBE(n, len).reverse();
}
// Unpadded, rarely used
export function numberToVarBytesBE(n) {
    return hexToBytes_(numberToHexUnpadded(n));
}
/**
 * Takes hex string or Uint8Array, converts to Uint8Array.
 * Validates output length.
 * Will throw error for other types.
 * @param title descriptive title for an error e.g. 'secret key'
 * @param hex hex string or Uint8Array
 * @param expectedLength optional, will compare to result array's length
 * @returns
 */
export function ensureBytes(title, hex, expectedLength) {
    let res;
    if (typeof hex === 'string') {
        try {
            res = hexToBytes_(hex);
        }
        catch (e) {
            throw new Error(title + ' must be hex string or Uint8Array, cause: ' + e);
        }
    }
    else if (isBytes_(hex)) {
        // Uint8Array.from() instead of hash.slice() because node.js Buffer
        // is instance of Uint8Array, and its slice() creates **mutable** copy
        res = Uint8Array.from(hex);
    }
    else {
        throw new Error(title + ' must be hex string or Uint8Array');
    }
    const len = res.length;
    if (typeof expectedLength === 'number' && len !== expectedLength)
        throw new Error(title + ' of length ' + expectedLength + ' expected, got ' + len);
    return res;
}
// Compares 2 u8a-s in kinda constant time
export function equalBytes(a, b) {
    if (a.length !== b.length)
        return false;
    let diff = 0;
    for (let i = 0; i < a.length; i++)
        diff |= a[i] ^ b[i];
    return diff === 0;
}
/**
 * Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,
 * and Buffer#slice creates mutable copy. Never use Buffers!
 */
export function copyBytes(bytes) {
    return Uint8Array.from(bytes);
}
/**
 * Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols
 * Should be safe to use for things expected to be ASCII.
 * Returns exact same result as utf8ToBytes for ASCII or throws.
 */
export function asciiToBytes(ascii) {
    return Uint8Array.from(ascii, (c, i) => {
        const charCode = c.charCodeAt(0);
        if (c.length !== 1 || charCode > 127) {
            throw new Error(`string contains non-ASCII character "${ascii[i]}" with code ${charCode} at position ${i}`);
        }
        return charCode;
    });
}
/**
 * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
 */
// export const utf8ToBytes: typeof utf8ToBytes_ = utf8ToBytes_;
/**
 * Converts bytes to string using UTF8 encoding.
 * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'
 */
// export const bytesToUtf8: typeof bytesToUtf8_ = bytesToUtf8_;
// Is positive bigint
const isPosBig = (n) => typeof n === 'bigint' && _0n <= n;
export function inRange(n, min, max) {
    return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
}
/**
 * Asserts min <= n < max. NOTE: It's < max and not <= max.
 * @example
 * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)
 */
export function aInRange(title, n, min, max) {
    // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?
    // consider P=256n, min=0n, max=P
    // - a for min=0 would require -1:          `inRange('x', x, -1n, P)`
    // - b would commonly require subtraction:  `inRange('x', x, 0n, P - 1n)`
    // - our way is the cleanest:               `inRange('x', x, 0n, P)
    if (!inRange(n, min, max))
        throw new Error('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);
}
// Bit operations
/**
 * Calculates amount of bits in a bigint.
 * Same as `n.toString(2).length`
 * TODO: merge with nLength in modular
 */
export function bitLen(n) {
    let len;
    for (len = 0; n > _0n; n >>= _1n, len += 1)
        ;
    return len;
}
/**
 * Gets single bit at position.
 * NOTE: first bit position is 0 (same as arrays)
 * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`
 */
export function bitGet(n, pos) {
    return (n >> BigInt(pos)) & _1n;
}
/**
 * Sets single bit at position.
 */
export function bitSet(n, pos, value) {
    return n | ((value ? _1n : _0n) << BigInt(pos));
}
/**
 * Calculate mask for N bits. Not using ** operator with bigints because of old engines.
 * Same as BigInt(`0b${Array(i).fill('1').join('')}`)
 */
export const bitMask = (n) => (_1n << BigInt(n)) - _1n;
/**
 * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
 * @returns function that will call DRBG until 2nd arg returns something meaningful
 * @example
 *   const drbg = createHmacDRBG<Key>(32, 32, hmac);
 *   drbg(seed, bytesToKey); // bytesToKey must return Key or undefined
 */
export function createHmacDrbg(hashLen, qByteLen, hmacFn) {
    if (typeof hashLen !== 'number' || hashLen < 2)
        throw new Error('hashLen must be a number');
    if (typeof qByteLen !== 'number' || qByteLen < 2)
        throw new Error('qByteLen must be a number');
    if (typeof hmacFn !== 'function')
        throw new Error('hmacFn must be a function');
    // Step B, Step C: set hashLen to 8*ceil(hlen/8)
    const u8n = (len) => new Uint8Array(len); // creates Uint8Array
    const u8of = (byte) => Uint8Array.of(byte); // another shortcut
    let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
    let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same
    let i = 0; // Iterations counter, will throw when over 1000
    const reset = () => {
        v.fill(1);
        k.fill(0);
        i = 0;
    };
    const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)
    const reseed = (seed = u8n(0)) => {
        // HMAC-DRBG reseed() function. Steps D-G
        k = h(u8of(0x00), seed); // k = hmac(k || v || 0x00 || seed)
        v = h(); // v = hmac(k || v)
        if (seed.length === 0)
            return;
        k = h(u8of(0x01), seed); // k = hmac(k || v || 0x01 || seed)
        v = h(); // v = hmac(k || v)
    };
    const gen = () => {
        // HMAC-DRBG generate() function
        if (i++ >= 1000)
            throw new Error('drbg: tried 1000 values');
        let len = 0;
        const out = [];
        while (len < qByteLen) {
            v = h();
            const sl = v.slice();
            out.push(sl);
            len += v.length;
        }
        return concatBytes_(...out);
    };
    const genUntil = (seed, pred) => {
        reset();
        reseed(seed); // Steps D-G
        let res = undefined; // Step H: grind until k is in [1..n-1]
        while (!(res = pred(gen())))
            reseed();
        reset();
        return res;
    };
    return genUntil;
}
// Validating curves and fields
const validatorFns = {
    bigint: (val) => typeof val === 'bigint',
    function: (val) => typeof val === 'function',
    boolean: (val) => typeof val === 'boolean',
    string: (val) => typeof val === 'string',
    stringOrUint8Array: (val) => typeof val === 'string' || isBytes_(val),
    isSafeInteger: (val) => Number.isSafeInteger(val),
    array: (val) => Array.isArray(val),
    field: (val, object) => object.Fp.isValid(val),
    hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),
};
// type Record<K extends string | number | symbol, T> = { [P in K]: T; }
export function validateObject(object, validators, optValidators = {}) {
    const checkField = (fieldName, type, isOptional) => {
        const checkVal = validatorFns[type];
        if (typeof checkVal !== 'function')
            throw new Error('invalid validator function');
        const val = object[fieldName];
        if (isOptional && val === undefined)
            return;
        if (!checkVal(val, object)) {
            throw new Error('param ' + String(fieldName) + ' is invalid. Expected ' + type + ', got ' + val);
        }
    };
    for (const [fieldName, type] of Object.entries(validators))
        checkField(fieldName, type, false);
    for (const [fieldName, type] of Object.entries(optValidators))
        checkField(fieldName, type, true);
    return object;
}
// validate type tests
// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };
// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!
// // Should fail type-check
// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });
// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });
// const z3 = validateObject(o, { test: 'boolean', z: 'bug' });
// const z4 = validateObject(o, { a: 'boolean', z: 'bug' });
export function isHash(val) {
    return typeof val === 'function' && Number.isSafeInteger(val.outputLen);
}
export function _validateObject(object, fields, optFields = {}) {
    if (!object || typeof object !== 'object')
        throw new Error('expected valid options object');
    function checkField(fieldName, expectedType, isOpt) {
        const val = object[fieldName];
        if (isOpt && val === undefined)
            return;
        const current = typeof val;
        if (current !== expectedType || val === null)
            throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
    }
    Object.entries(fields).forEach(([k, v]) => checkField(k, v, false));
    Object.entries(optFields).forEach(([k, v]) => checkField(k, v, true));
}
/**
 * throws not implemented error
 */
export const notImplemented = () => {
    throw new Error('not implemented');
};
/**
 * Memoizes (caches) computation result.
 * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.
 */
export function memoized(fn) {
    const map = new WeakMap();
    return (arg, ...args) => {
        const val = map.get(arg);
        if (val !== undefined)
            return val;
        const computed = fn(arg, ...args);
        map.set(arg, computed);
        return computed;
    };
}
//# sourceMappingURL=utils.js.map/**
 * Internal Merkle-Damgard hash utils.
 * @module
 */
import { Hash, abytes, aexists, aoutput, clean, createView, toBytes } from "./utils.js";
/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */
export function setBigUint64(view, byteOffset, value, isLE) {
    if (typeof view.setBigUint64 === 'function')
        return view.setBigUint64(byteOffset, value, isLE);
    const _32n = BigInt(32);
    const _u32_max = BigInt(0xffffffff);
    const wh = Number((value >> _32n) & _u32_max);
    const wl = Number(value & _u32_max);
    const h = isLE ? 4 : 0;
    const l = isLE ? 0 : 4;
    view.setUint32(byteOffset + h, wh, isLE);
    view.setUint32(byteOffset + l, wl, isLE);
}
/** Choice: a ? b : c */
export function Chi(a, b, c) {
    return (a & b) ^ (~a & c);
}
/** Majority function, true if any two inputs is true. */
export function Maj(a, b, c) {
    return (a & b) ^ (a & c) ^ (b & c);
}
/**
 * Merkle-Damgard hash construction base class.
 * Could be used to create MD5, RIPEMD, SHA1, SHA2.
 */
export class HashMD extends Hash {
    constructor(blockLen, outputLen, padOffset, isLE) {
        super();
        this.finished = false;
        this.length = 0;
        this.pos = 0;
        this.destroyed = false;
        this.blockLen = blockLen;
        this.outputLen = outputLen;
        this.padOffset = padOffset;
        this.isLE = isLE;
        this.buffer = new Uint8Array(blockLen);
        this.view = createView(this.buffer);
    }
    update(data) {
        aexists(this);
        data = toBytes(data);
        abytes(data);
        const { view, buffer, blockLen } = this;
        const len = data.length;
        for (let pos = 0; pos < len;) {
            const take = Math.min(blockLen - this.pos, len - pos);
            // Fast path: we have at least one block in input, cast it to view and process
            if (take === blockLen) {
                const dataView = createView(data);
                for (; blockLen <= len - pos; pos += blockLen)
                    this.process(dataView, pos);
                continue;
            }
            buffer.set(data.subarray(pos, pos + take), this.pos);
            this.pos += take;
            pos += take;
            if (this.pos === blockLen) {
                this.process(view, 0);
                this.pos = 0;
            }
        }
        this.length += data.length;
        this.roundClean();
        return this;
    }
    digestInto(out) {
        aexists(this);
        aoutput(out, this);
        this.finished = true;
        // Padding
        // We can avoid allocation of buffer for padding completely if it
        // was previously not allocated here. But it won't change performance.
        const { buffer, view, blockLen, isLE } = this;
        let { pos } = this;
        // append the bit '1' to the message
        buffer[pos++] = 0b10000000;
        clean(this.buffer.subarray(pos));
        // we have less than padOffset left in buffer, so we cannot put length in
        // current block, need process it and pad again
        if (this.padOffset > blockLen - pos) {
            this.process(view, 0);
            pos = 0;
        }
        // Pad until full block byte with zeros
        for (let i = pos; i < blockLen; i++)
            buffer[i] = 0;
        // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that
        // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.
        // So we just write lowest 64 bits of that value.
        setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
        this.process(view, 0);
        const oview = createView(out);
        const len = this.outputLen;
        // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT
        if (len % 4)
            throw new Error('_sha2: outputLen should be aligned to 32bit');
        const outLen = len / 4;
        const state = this.get();
        if (outLen > state.length)
            throw new Error('_sha2: outputLen bigger than state');
        for (let i = 0; i < outLen; i++)
            oview.setUint32(4 * i, state[i], isLE);
    }
    digest() {
        const { buffer, outputLen } = this;
        this.digestInto(buffer);
        const res = buffer.slice(0, outputLen);
        this.destroy();
        return res;
    }
    _cloneInto(to) {
        to || (to = new this.constructor());
        to.set(...this.get());
        const { blockLen, buffer, length, finished, destroyed, pos } = this;
        to.destroyed = destroyed;
        to.finished = finished;
        to.length = length;
        to.pos = pos;
        if (length % blockLen)
            to.buffer.set(buffer);
        return to;
    }
    clone() {
        return this._cloneInto();
    }
}
/**
 * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.
 * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.
 */
/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */
export const SHA256_IV = /* @__PURE__ */ Uint32Array.from([
    0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
]);
/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */
export const SHA224_IV = /* @__PURE__ */ Uint32Array.from([
    0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,
]);
/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */
export const SHA384_IV = /* @__PURE__ */ Uint32Array.from([
    0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,
    0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,
]);
/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */
export const SHA512_IV = /* @__PURE__ */ Uint32Array.from([
    0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,
    0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,
]);
//# sourceMappingURL=_md.js.map/**
 * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.
 * @todo re-check https://issues.chromium.org/issues/42212588
 * @module
 */
const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
const _32n = /* @__PURE__ */ BigInt(32);
function fromBig(n, le = false) {
    if (le)
        return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };
    return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
}
function split(lst, le = false) {
    const len = lst.length;
    let Ah = new Uint32Array(len);
    let Al = new Uint32Array(len);
    for (let i = 0; i < len; i++) {
        const { h, l } = fromBig(lst[i], le);
        [Ah[i], Al[i]] = [h, l];
    }
    return [Ah, Al];
}
const toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);
// for Shift in [0, 32)
const shrSH = (h, _l, s) => h >>> s;
const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
// Right rotate for Shift in [1, 32)
const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));
const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
// Right rotate for Shift in (32, 64), NOTE: 32 is special case.
const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));
const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));
// Right rotate for shift===32 (just swaps l&h)
const rotr32H = (_h, l) => l;
const rotr32L = (h, _l) => h;
// Left rotate for Shift in [1, 32)
const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));
const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));
// Left rotate for Shift in (32, 64), NOTE: 32 is special case.
const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));
const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));
// JS uses 32-bit signed integers for bitwise operations which means we cannot
// simple take carry out of low bit sum by shift, we need to use division.
function add(Ah, Al, Bh, Bl) {
    const l = (Al >>> 0) + (Bl >>> 0);
    return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };
}
// Addition with more than 2 elements
const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;
const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;
const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;
// prettier-ignore
export { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig };
// prettier-ignore
const u64 = {
    fromBig, split, toBig,
    shrSH, shrSL,
    rotrSH, rotrSL, rotrBH, rotrBL,
    rotr32H, rotr32L,
    rotlSH, rotlSL, rotlBH, rotlBL,
    add, add3L, add3H, add4L, add4H, add5H, add5L,
};
export default u64;
//# sourceMappingURL=_u64.js.mapexport const crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;
//# sourceMappingURL=crypto.js.map/**
 * HMAC: RFC2104 message authentication code.
 * @module
 */
import { abytes, aexists, ahash, clean, Hash, toBytes } from "./utils.js";
export class HMAC extends Hash {
    constructor(hash, _key) {
        super();
        this.finished = false;
        this.destroyed = false;
        ahash(hash);
        const key = toBytes(_key);
        this.iHash = hash.create();
        if (typeof this.iHash.update !== 'function')
            throw new Error('Expected instance of class which extends utils.Hash');
        this.blockLen = this.iHash.blockLen;
        this.outputLen = this.iHash.outputLen;
        const blockLen = this.blockLen;
        const pad = new Uint8Array(blockLen);
        // blockLen can be bigger than outputLen
        pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
        for (let i = 0; i < pad.length; i++)
            pad[i] ^= 0x36;
        this.iHash.update(pad);
        // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone
        this.oHash = hash.create();
        // Undo internal XOR && apply outer XOR
        for (let i = 0; i < pad.length; i++)
            pad[i] ^= 0x36 ^ 0x5c;
        this.oHash.update(pad);
        clean(pad);
    }
    update(buf) {
        aexists(this);
        this.iHash.update(buf);
        return this;
    }
    digestInto(out) {
        aexists(this);
        abytes(out, this.outputLen);
        this.finished = true;
        this.iHash.digestInto(out);
        this.oHash.update(out);
        this.oHash.digestInto(out);
        this.destroy();
    }
    digest() {
        const out = new Uint8Array(this.oHash.outputLen);
        this.digestInto(out);
        return out;
    }
    _cloneInto(to) {
        // Create new instance without calling constructor since key already in state and we don't know it.
        to || (to = Object.create(Object.getPrototypeOf(this), {}));
        const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
        to = to;
        to.finished = finished;
        to.destroyed = destroyed;
        to.blockLen = blockLen;
        to.outputLen = outputLen;
        to.oHash = oHash._cloneInto(to.oHash);
        to.iHash = iHash._cloneInto(to.iHash);
        return to;
    }
    clone() {
        return this._cloneInto();
    }
    destroy() {
        this.destroyed = true;
        this.oHash.destroy();
        this.iHash.destroy();
    }
}
/**
 * HMAC: RFC2104 message authentication code.
 * @param hash - function that would be used e.g. sha256
 * @param key - message key
 * @param message - message data
 * @example
 * import { hmac } from '@noble/hashes/hmac';
 * import { sha256 } from '@noble/hashes/sha2';
 * const mac1 = hmac(sha256, 'key', 'message');
 */
export const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
hmac.create = (hash, key) => new HMAC(hash, key);
//# sourceMappingURL=hmac.js.map{
  "type": "module",
  "sideEffects": false,
  "browser": {
    "node:crypto": false
  },
  "node": {
    "./crypto": "./esm/cryptoNode.js"
  }
}
/**
 * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.
 * SHA256 is the fastest hash implementable in JS, even faster than Blake3.
 * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and
 * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).
 * @module
 */
import { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from "./_md.js";
import * as u64 from "./_u64.js";
import { clean, createHasher, rotr } from "./utils.js";
/**
 * Round constants:
 * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)
 */
// prettier-ignore
const SHA256_K = /* @__PURE__ */ Uint32Array.from([
    0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
    0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
    0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
    0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
    0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
    0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
    0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
    0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
]);
/** Reusable temporary buffer. "W" comes straight from spec. */
const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
export class SHA256 extends HashMD {
    constructor(outputLen = 32) {
        super(64, outputLen, 8, false);
        // We cannot use array here since array allows indexing by variable
        // which means optimizer/compiler cannot use registers.
        this.A = SHA256_IV[0] | 0;
        this.B = SHA256_IV[1] | 0;
        this.C = SHA256_IV[2] | 0;
        this.D = SHA256_IV[3] | 0;
        this.E = SHA256_IV[4] | 0;
        this.F = SHA256_IV[5] | 0;
        this.G = SHA256_IV[6] | 0;
        this.H = SHA256_IV[7] | 0;
    }
    get() {
        const { A, B, C, D, E, F, G, H } = this;
        return [A, B, C, D, E, F, G, H];
    }
    // prettier-ignore
    set(A, B, C, D, E, F, G, H) {
        this.A = A | 0;
        this.B = B | 0;
        this.C = C | 0;
        this.D = D | 0;
        this.E = E | 0;
        this.F = F | 0;
        this.G = G | 0;
        this.H = H | 0;
    }
    process(view, offset) {
        // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array
        for (let i = 0; i < 16; i++, offset += 4)
            SHA256_W[i] = view.getUint32(offset, false);
        for (let i = 16; i < 64; i++) {
            const W15 = SHA256_W[i - 15];
            const W2 = SHA256_W[i - 2];
            const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);
            const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);
            SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;
        }
        // Compression function main loop, 64 rounds
        let { A, B, C, D, E, F, G, H } = this;
        for (let i = 0; i < 64; i++) {
            const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
            const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
            const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
            const T2 = (sigma0 + Maj(A, B, C)) | 0;
            H = G;
            G = F;
            F = E;
            E = (D + T1) | 0;
            D = C;
            C = B;
            B = A;
            A = (T1 + T2) | 0;
        }
        // Add the compressed chunk to the current hash value
        A = (A + this.A) | 0;
        B = (B + this.B) | 0;
        C = (C + this.C) | 0;
        D = (D + this.D) | 0;
        E = (E + this.E) | 0;
        F = (F + this.F) | 0;
        G = (G + this.G) | 0;
        H = (H + this.H) | 0;
        this.set(A, B, C, D, E, F, G, H);
    }
    roundClean() {
        clean(SHA256_W);
    }
    destroy() {
        this.set(0, 0, 0, 0, 0, 0, 0, 0);
        clean(this.buffer);
    }
}
export class SHA224 extends SHA256 {
    constructor() {
        super(28);
        this.A = SHA224_IV[0] | 0;
        this.B = SHA224_IV[1] | 0;
        this.C = SHA224_IV[2] | 0;
        this.D = SHA224_IV[3] | 0;
        this.E = SHA224_IV[4] | 0;
        this.F = SHA224_IV[5] | 0;
        this.G = SHA224_IV[6] | 0;
        this.H = SHA224_IV[7] | 0;
    }
}
// SHA2-512 is slower than sha256 in js because u64 operations are slow.
// Round contants
// First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409
// prettier-ignore
const K512 = /* @__PURE__ */ (() => u64.split([
    '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',
    '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',
    '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',
    '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',
    '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',
    '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',
    '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',
    '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',
    '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',
    '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',
    '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',
    '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',
    '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',
    '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',
    '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',
    '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',
    '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',
    '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',
    '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',
    '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'
].map(n => BigInt(n))))();
const SHA512_Kh = /* @__PURE__ */ (() => K512[0])();
const SHA512_Kl = /* @__PURE__ */ (() => K512[1])();
// Reusable temporary buffers
const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
export class SHA512 extends HashMD {
    constructor(outputLen = 64) {
        super(128, outputLen, 16, false);
        // We cannot use array here since array allows indexing by variable
        // which means optimizer/compiler cannot use registers.
        // h -- high 32 bits, l -- low 32 bits
        this.Ah = SHA512_IV[0] | 0;
        this.Al = SHA512_IV[1] | 0;
        this.Bh = SHA512_IV[2] | 0;
        this.Bl = SHA512_IV[3] | 0;
        this.Ch = SHA512_IV[4] | 0;
        this.Cl = SHA512_IV[5] | 0;
        this.Dh = SHA512_IV[6] | 0;
        this.Dl = SHA512_IV[7] | 0;
        this.Eh = SHA512_IV[8] | 0;
        this.El = SHA512_IV[9] | 0;
        this.Fh = SHA512_IV[10] | 0;
        this.Fl = SHA512_IV[11] | 0;
        this.Gh = SHA512_IV[12] | 0;
        this.Gl = SHA512_IV[13] | 0;
        this.Hh = SHA512_IV[14] | 0;
        this.Hl = SHA512_IV[15] | 0;
    }
    // prettier-ignore
    get() {
        const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
        return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
    }
    // prettier-ignore
    set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
        this.Ah = Ah | 0;
        this.Al = Al | 0;
        this.Bh = Bh | 0;
        this.Bl = Bl | 0;
        this.Ch = Ch | 0;
        this.Cl = Cl | 0;
        this.Dh = Dh | 0;
        this.Dl = Dl | 0;
        this.Eh = Eh | 0;
        this.El = El | 0;
        this.Fh = Fh | 0;
        this.Fl = Fl | 0;
        this.Gh = Gh | 0;
        this.Gl = Gl | 0;
        this.Hh = Hh | 0;
        this.Hl = Hl | 0;
    }
    process(view, offset) {
        // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array
        for (let i = 0; i < 16; i++, offset += 4) {
            SHA512_W_H[i] = view.getUint32(offset);
            SHA512_W_L[i] = view.getUint32((offset += 4));
        }
        for (let i = 16; i < 80; i++) {
            // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)
            const W15h = SHA512_W_H[i - 15] | 0;
            const W15l = SHA512_W_L[i - 15] | 0;
            const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);
            const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);
            // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)
            const W2h = SHA512_W_H[i - 2] | 0;
            const W2l = SHA512_W_L[i - 2] | 0;
            const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);
            const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);
            // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];
            const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
            const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
            SHA512_W_H[i] = SUMh | 0;
            SHA512_W_L[i] = SUMl | 0;
        }
        let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
        // Compression function main loop, 80 rounds
        for (let i = 0; i < 80; i++) {
            // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)
            const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);
            const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);
            //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
            const CHIh = (Eh & Fh) ^ (~Eh & Gh);
            const CHIl = (El & Fl) ^ (~El & Gl);
            // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]
            // prettier-ignore
            const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
            const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
            const T1l = T1ll | 0;
            // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)
            const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);
            const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);
            const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);
            const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);
            Hh = Gh | 0;
            Hl = Gl | 0;
            Gh = Fh | 0;
            Gl = Fl | 0;
            Fh = Eh | 0;
            Fl = El | 0;
            ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
            Dh = Ch | 0;
            Dl = Cl | 0;
            Ch = Bh | 0;
            Cl = Bl | 0;
            Bh = Ah | 0;
            Bl = Al | 0;
            const All = u64.add3L(T1l, sigma0l, MAJl);
            Ah = u64.add3H(All, T1h, sigma0h, MAJh);
            Al = All | 0;
        }
        // Add the compressed chunk to the current hash value
        ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
        ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
        ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
        ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
        ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
        ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
        ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
        ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
        this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
    }
    roundClean() {
        clean(SHA512_W_H, SHA512_W_L);
    }
    destroy() {
        clean(this.buffer);
        this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
    }
}
export class SHA384 extends SHA512 {
    constructor() {
        super(48);
        this.Ah = SHA384_IV[0] | 0;
        this.Al = SHA384_IV[1] | 0;
        this.Bh = SHA384_IV[2] | 0;
        this.Bl = SHA384_IV[3] | 0;
        this.Ch = SHA384_IV[4] | 0;
        this.Cl = SHA384_IV[5] | 0;
        this.Dh = SHA384_IV[6] | 0;
        this.Dl = SHA384_IV[7] | 0;
        this.Eh = SHA384_IV[8] | 0;
        this.El = SHA384_IV[9] | 0;
        this.Fh = SHA384_IV[10] | 0;
        this.Fl = SHA384_IV[11] | 0;
        this.Gh = SHA384_IV[12] | 0;
        this.Gl = SHA384_IV[13] | 0;
        this.Hh = SHA384_IV[14] | 0;
        this.Hl = SHA384_IV[15] | 0;
    }
}
/**
 * Truncated SHA512/256 and SHA512/224.
 * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as "intermediary" IV of SHA512/t.
 * Then t hashes string to produce result IV.
 * See `test/misc/sha2-gen-iv.js`.
 */
/** SHA512/224 IV */
const T224_IV = /* @__PURE__ */ Uint32Array.from([
    0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,
    0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,
]);
/** SHA512/256 IV */
const T256_IV = /* @__PURE__ */ Uint32Array.from([
    0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,
    0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,
]);
export class SHA512_224 extends SHA512 {
    constructor() {
        super(28);
        this.Ah = T224_IV[0] | 0;
        this.Al = T224_IV[1] | 0;
        this.Bh = T224_IV[2] | 0;
        this.Bl = T224_IV[3] | 0;
        this.Ch = T224_IV[4] | 0;
        this.Cl = T224_IV[5] | 0;
        this.Dh = T224_IV[6] | 0;
        this.Dl = T224_IV[7] | 0;
        this.Eh = T224_IV[8] | 0;
        this.El = T224_IV[9] | 0;
        this.Fh = T224_IV[10] | 0;
        this.Fl = T224_IV[11] | 0;
        this.Gh = T224_IV[12] | 0;
        this.Gl = T224_IV[13] | 0;
        this.Hh = T224_IV[14] | 0;
        this.Hl = T224_IV[15] | 0;
    }
}
export class SHA512_256 extends SHA512 {
    constructor() {
        super(32);
        this.Ah = T256_IV[0] | 0;
        this.Al = T256_IV[1] | 0;
        this.Bh = T256_IV[2] | 0;
        this.Bl = T256_IV[3] | 0;
        this.Ch = T256_IV[4] | 0;
        this.Cl = T256_IV[5] | 0;
        this.Dh = T256_IV[6] | 0;
        this.Dl = T256_IV[7] | 0;
        this.Eh = T256_IV[8] | 0;
        this.El = T256_IV[9] | 0;
        this.Fh = T256_IV[10] | 0;
        this.Fl = T256_IV[11] | 0;
        this.Gh = T256_IV[12] | 0;
        this.Gl = T256_IV[13] | 0;
        this.Hh = T256_IV[14] | 0;
        this.Hl = T256_IV[15] | 0;
    }
}
/**
 * SHA2-256 hash function from RFC 4634.
 *
 * It is the fastest JS hash, even faster than Blake3.
 * To break sha256 using birthday attack, attackers need to try 2^128 hashes.
 * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
 */
export const sha256 = /* @__PURE__ */ createHasher(() => new SHA256());
/** SHA2-224 hash function from RFC 4634 */
export const sha224 = /* @__PURE__ */ createHasher(() => new SHA224());
/** SHA2-512 hash function from RFC 4634. */
export const sha512 = /* @__PURE__ */ createHasher(() => new SHA512());
/** SHA2-384 hash function from RFC 4634. */
export const sha384 = /* @__PURE__ */ createHasher(() => new SHA384());
/**
 * SHA2-512/256 "truncated" hash function, with improved resistance to length extension attacks.
 * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).
 */
export const sha512_256 = /* @__PURE__ */ createHasher(() => new SHA512_256());
/**
 * SHA2-512/224 "truncated" hash function, with improved resistance to length extension attacks.
 * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).
 */
export const sha512_224 = /* @__PURE__ */ createHasher(() => new SHA512_224());
//# sourceMappingURL=sha2.js.map/**
 * Utilities for hex, bytes, CSPRNG.
 * @module
 */
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
// node.js versions earlier than v19 don't declare it in global scope.
// For node.js, package.json#exports field mapping rewrites import
// from `crypto` to `cryptoNode`, which imports native module.
// Makes the utils un-importable in browsers without a bundler.
// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.
import { crypto } from '@noble/hashes/crypto';
/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */
export function isBytes(a) {
    return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
}
/** Asserts something is positive integer. */
export function anumber(n) {
    if (!Number.isSafeInteger(n) || n < 0)
        throw new Error('positive integer expected, got ' + n);
}
/** Asserts something is Uint8Array. */
export function abytes(b, ...lengths) {
    if (!isBytes(b))
        throw new Error('Uint8Array expected');
    if (lengths.length > 0 && !lengths.includes(b.length))
        throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);
}
/** Asserts something is hash */
export function ahash(h) {
    if (typeof h !== 'function' || typeof h.create !== 'function')
        throw new Error('Hash should be wrapped by utils.createHasher');
    anumber(h.outputLen);
    anumber(h.blockLen);
}
/** Asserts a hash instance has not been destroyed / finished */
export function aexists(instance, checkFinished = true) {
    if (instance.destroyed)
        throw new Error('Hash instance has been destroyed');
    if (checkFinished && instance.finished)
        throw new Error('Hash#digest() has already been called');
}
/** Asserts output is properly-sized byte array */
export function aoutput(out, instance) {
    abytes(out);
    const min = instance.outputLen;
    if (out.length < min) {
        throw new Error('digestInto() expects output buffer of length at least ' + min);
    }
}
/** Cast u8 / u16 / u32 to u8. */
export function u8(arr) {
    return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
}
/** Cast u8 / u16 / u32 to u32. */
export function u32(arr) {
    return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
}
/** Zeroize a byte array. Warning: JS provides no guarantees. */
export function clean(...arrays) {
    for (let i = 0; i < arrays.length; i++) {
        arrays[i].fill(0);
    }
}
/** Create DataView of an array for easy byte-level manipulation. */
export function createView(arr) {
    return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
}
/** The rotate right (circular right shift) operation for uint32 */
export function rotr(word, shift) {
    return (word << (32 - shift)) | (word >>> shift);
}
/** The rotate left (circular left shift) operation for uint32 */
export function rotl(word, shift) {
    return (word << shift) | ((word >>> (32 - shift)) >>> 0);
}
/** Is current platform little-endian? Most are. Big-Endian platform: IBM */
export const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();
/** The byte swap operation for uint32 */
export function byteSwap(word) {
    return (((word << 24) & 0xff000000) |
        ((word << 8) & 0xff0000) |
        ((word >>> 8) & 0xff00) |
        ((word >>> 24) & 0xff));
}
/** Conditionally byte swap if on a big-endian platform */
export const swap8IfBE = isLE
    ? (n) => n
    : (n) => byteSwap(n);
/** @deprecated */
export const byteSwapIfBE = swap8IfBE;
/** In place byte swap for Uint32Array */
export function byteSwap32(arr) {
    for (let i = 0; i < arr.length; i++) {
        arr[i] = byteSwap(arr[i]);
    }
    return arr;
}
export const swap32IfBE = isLE
    ? (u) => u
    : byteSwap32;
// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex
const hasHexBuiltin = /* @__PURE__ */ (() => 
// @ts-ignore
typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();
// Array where index 0xf0 (240) is mapped to string 'f0'
const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
/**
 * Convert byte array to hex string. Uses built-in function, when available.
 * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
 */
export function bytesToHex(bytes) {
    abytes(bytes);
    // @ts-ignore
    if (hasHexBuiltin)
        return bytes.toHex();
    // pre-caching improves the speed 6x
    let hex = '';
    for (let i = 0; i < bytes.length; i++) {
        hex += hexes[bytes[i]];
    }
    return hex;
}
// We use optimized technique to convert hex string to byte array
const asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
function asciiToBase16(ch) {
    if (ch >= asciis._0 && ch <= asciis._9)
        return ch - asciis._0; // '2' => 50-48
    if (ch >= asciis.A && ch <= asciis.F)
        return ch - (asciis.A - 10); // 'B' => 66-(65-10)
    if (ch >= asciis.a && ch <= asciis.f)
        return ch - (asciis.a - 10); // 'b' => 98-(97-10)
    return;
}
/**
 * Convert hex string to byte array. Uses built-in function, when available.
 * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
 */
export function hexToBytes(hex) {
    if (typeof hex !== 'string')
        throw new Error('hex string expected, got ' + typeof hex);
    // @ts-ignore
    if (hasHexBuiltin)
        return Uint8Array.fromHex(hex);
    const hl = hex.length;
    const al = hl / 2;
    if (hl % 2)
        throw new Error('hex string expected, got unpadded hex of length ' + hl);
    const array = new Uint8Array(al);
    for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
        const n1 = asciiToBase16(hex.charCodeAt(hi));
        const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
        if (n1 === undefined || n2 === undefined) {
            const char = hex[hi] + hex[hi + 1];
            throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
        }
        array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163
    }
    return array;
}
/**
 * There is no setImmediate in browser and setTimeout is slow.
 * Call of async fn will return Promise, which will be fullfiled only on
 * next scheduler queue processing step and this is exactly what we need.
 */
export const nextTick = async () => { };
/** Returns control to thread each 'tick' ms to avoid blocking. */
export async function asyncLoop(iters, tick, cb) {
    let ts = Date.now();
    for (let i = 0; i < iters; i++) {
        cb(i);
        // Date.now() is not monotonic, so in case if clock goes backwards we return return control too
        const diff = Date.now() - ts;
        if (diff >= 0 && diff < tick)
            continue;
        await nextTick();
        ts += diff;
    }
}
/**
 * Converts string to bytes using UTF8 encoding.
 * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])
 */
export function utf8ToBytes(str) {
    if (typeof str !== 'string')
        throw new Error('string expected');
    return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
}
/**
 * Converts bytes to string using UTF8 encoding.
 * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'
 */
export function bytesToUtf8(bytes) {
    return new TextDecoder().decode(bytes);
}
/**
 * Normalizes (non-hex) string or Uint8Array to Uint8Array.
 * Warning: when Uint8Array is passed, it would NOT get copied.
 * Keep in mind for future mutable operations.
 */
export function toBytes(data) {
    if (typeof data === 'string')
        data = utf8ToBytes(data);
    abytes(data);
    return data;
}
/**
 * Helper for KDFs: consumes uint8array or string.
 * When string is passed, does utf8 decoding, using TextDecoder.
 */
export function kdfInputToBytes(data) {
    if (typeof data === 'string')
        data = utf8ToBytes(data);
    abytes(data);
    return data;
}
/** Copies several Uint8Arrays into one. */
export function concatBytes(...arrays) {
    let sum = 0;
    for (let i = 0; i < arrays.length; i++) {
        const a = arrays[i];
        abytes(a);
        sum += a.length;
    }
    const res = new Uint8Array(sum);
    for (let i = 0, pad = 0; i < arrays.length; i++) {
        const a = arrays[i];
        res.set(a, pad);
        pad += a.length;
    }
    return res;
}
export function checkOpts(defaults, opts) {
    if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')
        throw new Error('options should be object or undefined');
    const merged = Object.assign(defaults, opts);
    return merged;
}
/** For runtime check if class implements interface */
export class Hash {
}
/** Wraps hash function, creating an interface on top of it */
export function createHasher(hashCons) {
    const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
    const tmp = hashCons();
    hashC.outputLen = tmp.outputLen;
    hashC.blockLen = tmp.blockLen;
    hashC.create = () => hashCons();
    return hashC;
}
export function createOptHasher(hashCons) {
    const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();
    const tmp = hashCons({});
    hashC.outputLen = tmp.outputLen;
    hashC.blockLen = tmp.blockLen;
    hashC.create = (opts) => hashCons(opts);
    return hashC;
}
export function createXOFer(hashCons) {
    const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();
    const tmp = hashCons({});
    hashC.outputLen = tmp.outputLen;
    hashC.blockLen = tmp.blockLen;
    hashC.create = (opts) => hashCons(opts);
    return hashC;
}
export const wrapConstructor = createHasher;
export const wrapConstructorWithOpts = createOptHasher;
export const wrapXOFConstructorWithOpts = createXOFer;
/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */
export function randomBytes(bytesLength = 32) {
    if (crypto && typeof crypto.getRandomValues === 'function') {
        return crypto.getRandomValues(new Uint8Array(bytesLength));
    }
    // Legacy Node.js compatibility
    if (crypto && typeof crypto.randomBytes === 'function') {
        return Uint8Array.from(crypto.randomBytes(bytesLength));
    }
    throw new Error('crypto.getRandomValues must be defined');
}
//# sourceMappingURL=utils.js.mapimport { encode, encodeInto, objectToTokens, rfc8949EncodeOptions } from './lib/encode.js'
import { decode, decodeFirst, Tokeniser, tokensToObject } from './lib/decode.js'
import { Tagged } from './lib/tagged.js'
import { Token, Type } from './lib/token.js'

/**
 * Export the types that were present in the original manual cborg.d.ts
 * @typedef {import('./interface.js').TagDecodeControl} TagDecodeControl
 * @typedef {import('./interface.js').TagDecoder} TagDecoder
 * There was originally just `TypeEncoder` so don't break types by renaming or not exporting
 * @typedef {import('./interface.js').OptionalTypeEncoder} TypeEncoder
 * @typedef {import('./interface.js').DecodeOptions} DecodeOptions
 * @typedef {import('./interface.js').EncodeOptions} EncodeOptions
 */

export {
  decode,
  decodeFirst,
  Tokeniser as Tokenizer,
  tokensToObject,
  encode,
  encodeInto,
  objectToTokens,
  rfc8949EncodeOptions,
  Tagged,
  Token,
  Type
}
/* globals BigInt */

import { Token, Type } from './token.js'
import { decodeErrPrefix, assertEnoughData } from './common.js'

export const uintBoundaries = [24, 256, 65536, 4294967296, BigInt('18446744073709551616')]

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number}
 */
export function readUint8 (data, offset, options) {
  assertEnoughData(data, offset, 1)
  const value = data[offset]
  if (options.strict === true && value < uintBoundaries[0]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  return value
}

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number}
 */
export function readUint16 (data, offset, options) {
  assertEnoughData(data, offset, 2)
  const value = (data[offset] << 8) | data[offset + 1]
  if (options.strict === true && value < uintBoundaries[1]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  return value
}

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number}
 */
export function readUint32 (data, offset, options) {
  assertEnoughData(data, offset, 4)
  const value = (data[offset] * 16777216 /* 2 ** 24 */) + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]
  if (options.strict === true && value < uintBoundaries[2]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  return value
}

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number|bigint}
 */
export function readUint64 (data, offset, options) {
  // assume BigInt, convert back to Number if within safe range
  assertEnoughData(data, offset, 8)
  const hi = (data[offset] * 16777216 /* 2 ** 24 */) + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]
  const lo = (data[offset + 4] * 16777216 /* 2 ** 24 */) + (data[offset + 5] << 16) + (data[offset + 6] << 8) + data[offset + 7]
  const value = (BigInt(hi) << BigInt(32)) + BigInt(lo)
  if (options.strict === true && value < uintBoundaries[3]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  if (value <= Number.MAX_SAFE_INTEGER) {
    return Number(value)
  }
  if (options.allowBigInt === true) {
    return value
  }
  throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`)
}

/* not required thanks to quick[] list
const oneByteTokens = new Array(24).fill(0).map((v, i) => new Token(Type.uint, i, 1))
export function decodeUintCompact (data, pos, minor, options) {
  return oneByteTokens[minor]
}
*/

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint8 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint8(data, pos + 1, options), 2)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint16 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint16(data, pos + 1, options), 3)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint32 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint32(data, pos + 1, options), 5)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint64 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint64(data, pos + 1, options), 9)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeUint (writer, token) {
  return encodeUintValue(writer, 0, token.value)
}

/**
 * @param {ByteWriter} writer
 * @param {number} major
 * @param {number|bigint} uint
 */
export function encodeUintValue (writer, major, uint) {
  if (uint < uintBoundaries[0]) {
    const nuint = Number(uint)
    // pack into one byte, minor=0, additional=value
    writer.push([major | nuint])
  } else if (uint < uintBoundaries[1]) {
    const nuint = Number(uint)
    // pack into two byte, minor=0, additional=24
    writer.push([major | 24, nuint])
  } else if (uint < uintBoundaries[2]) {
    const nuint = Number(uint)
    // pack into three byte, minor=0, additional=25
    writer.push([major | 25, nuint >>> 8, nuint & 0xff])
  } else if (uint < uintBoundaries[3]) {
    const nuint = Number(uint)
    // pack into five byte, minor=0, additional=26
    writer.push([major | 26, (nuint >>> 24) & 0xff, (nuint >>> 16) & 0xff, (nuint >>> 8) & 0xff, nuint & 0xff])
  } else {
    const buint = BigInt(uint)
    if (buint < uintBoundaries[4]) {
      // pack into nine byte, minor=0, additional=27
      const set = [major | 27, 0, 0, 0, 0, 0, 0, 0]
      // simulate bitwise above 32 bits
      let lo = Number(buint & BigInt(0xffffffff))
      let hi = Number(buint >> BigInt(32) & BigInt(0xffffffff))
      set[8] = lo & 0xff
      lo = lo >> 8
      set[7] = lo & 0xff
      lo = lo >> 8
      set[6] = lo & 0xff
      lo = lo >> 8
      set[5] = lo & 0xff
      set[4] = hi & 0xff
      hi = hi >> 8
      set[3] = hi & 0xff
      hi = hi >> 8
      set[2] = hi & 0xff
      hi = hi >> 8
      set[1] = hi & 0xff
      writer.push(set)
    } else {
      throw new Error(`${decodeErrPrefix} encountered BigInt larger than allowable range`)
    }
  }
}

/**
 * @param {Token} token
 * @returns {number}
 */
encodeUint.encodedSize = function encodedSize (token) {
  return encodeUintValue.encodedSize(token.value)
}

/**
 * @param {number} uint
 * @returns {number}
 */
encodeUintValue.encodedSize = function encodedSize (uint) {
  if (uint < uintBoundaries[0]) {
    return 1
  }
  if (uint < uintBoundaries[1]) {
    return 2
  }
  if (uint < uintBoundaries[2]) {
    return 3
  }
  if (uint < uintBoundaries[3]) {
    return 5
  }
  return 9
}

/**
 * @param {Token} tok1
 * @param {Token} tok2
 * @returns {number}
 */
encodeUint.compareTokens = function compareTokens (tok1, tok2) {
  return tok1.value < tok2.value ? -1 : tok1.value > tok2.value ? 1 : 0
}
/* eslint-env es2020 */

import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import { decodeErrPrefix } from './common.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint8 (data, pos, _minor, options) {
  return new Token(Type.negint, -1 - uint.readUint8(data, pos + 1, options), 2)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint16 (data, pos, _minor, options) {
  return new Token(Type.negint, -1 - uint.readUint16(data, pos + 1, options), 3)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint32 (data, pos, _minor, options) {
  return new Token(Type.negint, -1 - uint.readUint32(data, pos + 1, options), 5)
}

const neg1b = BigInt(-1)
const pos1b = BigInt(1)

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint64 (data, pos, _minor, options) {
  const int = uint.readUint64(data, pos + 1, options)
  if (typeof int !== 'bigint') {
    const value = -1 - int
    if (value >= Number.MIN_SAFE_INTEGER) {
      return new Token(Type.negint, value, 9)
    }
  }
  if (options.allowBigInt !== true) {
    throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`)
  }
  return new Token(Type.negint, neg1b - BigInt(int), 9)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeNegint (writer, token) {
  const negint = token.value
  const unsigned = (typeof negint === 'bigint' ? (negint * neg1b - pos1b) : (negint * -1 - 1))
  uint.encodeUintValue(writer, token.type.majorEncoded, unsigned)
}

/**
 * @param {Token} token
 * @returns {number}
 */
encodeNegint.encodedSize = function encodedSize (token) {
  const negint = token.value
  const unsigned = (typeof negint === 'bigint' ? (negint * neg1b - pos1b) : (negint * -1 - 1))
  // handled by quickEncode, we shouldn't get here but it's included for completeness
  if (unsigned < uint.uintBoundaries[0]) {
    return 1
  }
  if (unsigned < uint.uintBoundaries[1]) {
    return 2
  }
  if (unsigned < uint.uintBoundaries[2]) {
    return 3
  }
  if (unsigned < uint.uintBoundaries[3]) {
    return 5
  }
  return 9
}

/**
 * @param {Token} tok1
 * @param {Token} tok2
 * @returns {number}
 */
encodeNegint.compareTokens = function compareTokens (tok1, tok2) {
  // opposite of the uint comparison since we store the uint version in bytes
  return tok1.value < tok2.value ? 1 : tok1.value > tok2.value ? -1 : 0
}
import { Token, Type } from './token.js'
import { assertEnoughData, decodeErrPrefix } from './common.js'
import * as uint from './0uint.js'
import { compare, fromString } from './byte-utils.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} prefix
 * @param {number} length
 * @returns {Token}
 */
function toToken (data, pos, prefix, length) {
  assertEnoughData(data, pos, prefix + length)
  const buf = data.slice(pos + prefix, pos + prefix + length)
  return new Token(Type.bytes, buf, prefix + length)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeBytesCompact (data, pos, minor, _options) {
  return toToken(data, pos, 1, minor)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer bytes lengths not supported`)
  }
  return toToken(data, pos, 9, l)
}

/**
 * `encodedBytes` allows for caching when we do a byte version of a string
 * for key sorting purposes
 * @param {Token} token
 * @returns {Uint8Array}
 */
function tokenBytes (token) {
  if (token.encodedBytes === undefined) {
    token.encodedBytes = Type.equals(token.type, Type.string) ? fromString(token.value) : token.value
  }
  // @ts-ignore c'mon
  return token.encodedBytes
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeBytes (writer, token) {
  const bytes = tokenBytes(token)
  uint.encodeUintValue(writer, token.type.majorEncoded, bytes.length)
  writer.push(bytes)
}

/**
 * @param {Token} token
 * @returns {number}
 */
encodeBytes.encodedSize = function encodedSize (token) {
  const bytes = tokenBytes(token)
  return uint.encodeUintValue.encodedSize(bytes.length) + bytes.length
}

/**
 * @param {Token} tok1
 * @param {Token} tok2
 * @returns {number}
 */
encodeBytes.compareTokens = function compareTokens (tok1, tok2) {
  return compareBytes(tokenBytes(tok1), tokenBytes(tok2))
}

/**
 * @param {Uint8Array} b1
 * @param {Uint8Array} b2
 * @returns {number}
 */
export function compareBytes (b1, b2) {
  return b1.length < b2.length ? -1 : b1.length > b2.length ? 1 : compare(b1, b2)
}
import { Token, Type } from './token.js'
import { assertEnoughData, decodeErrPrefix } from './common.js'
import * as uint from './0uint.js'
import { encodeBytes } from './2bytes.js'

const textDecoder = new TextDecoder()

// Threshold for ASCII fast-path vs TextDecoder. Short ASCII strings (common for
// map keys) are faster to decode with a simple loop than TextDecoder overhead.
const ASCII_THRESHOLD = 32

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * Decode UTF-8 bytes to string. For short ASCII strings (common case for map keys),
 * a simple loop is faster than TextDecoder.
 * @param {Uint8Array} bytes
 * @param {number} start
 * @param {number} end
 * @returns {string}
 */
function toStr (bytes, start, end) {
  const len = end - start
  if (len < ASCII_THRESHOLD) {
    let str = ''
    for (let i = start; i < end; i++) {
      const c = bytes[i]
      if (c & 0x80) { // non-ASCII, fall back to TextDecoder
        return textDecoder.decode(bytes.subarray(start, end))
      }
      str += String.fromCharCode(c)
    }
    return str
  }
  return textDecoder.decode(bytes.subarray(start, end))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} prefix
 * @param {number} length
 * @param {DecodeOptions} options
 * @returns {Token}
 */
function toToken (data, pos, prefix, length, options) {
  const totLength = prefix + length
  assertEnoughData(data, pos, totLength)
  const tok = new Token(Type.string, toStr(data, pos + prefix, pos + totLength), totLength)
  if (options.retainStringBytes === true) {
    tok.byteValue = data.slice(pos + prefix, pos + totLength)
  }
  return tok
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeStringCompact (data, pos, minor, options) {
  return toToken(data, pos, 1, minor, options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options), options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options), options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options), options)
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer string lengths not supported`)
  }
  return toToken(data, pos, 9, l, options)
}

export const encodeString = encodeBytes
import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import { decodeErrPrefix } from './common.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} prefix
 * @param {number} length
 * @returns {Token}
 */
function toToken (_data, _pos, prefix, length) {
  return new Token(Type.array, length, prefix)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeArrayCompact (data, pos, minor, _options) {
  return toToken(data, pos, 1, minor)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer array lengths not supported`)
  }
  return toToken(data, pos, 9, l)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArrayIndefinite (data, pos, _minor, options) {
  if (options.allowIndefinite === false) {
    throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)
  }
  return toToken(data, pos, 1, Infinity)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeArray (writer, token) {
  uint.encodeUintValue(writer, Type.array.majorEncoded, token.value)
}

// using an array as a map key, are you sure about this? we can only sort
// by map length here, it's up to the encoder to decide to look deeper
encodeArray.compareTokens = uint.encodeUint.compareTokens

/**
 * @param {Token} token
 * @returns {number}
 */
encodeArray.encodedSize = function encodedSize (token) {
  return uint.encodeUintValue.encodedSize(token.value)
}
import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import { decodeErrPrefix } from './common.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} prefix
 * @param {number} length
 * @returns {Token}
 */
function toToken (_data, _pos, prefix, length) {
  return new Token(Type.map, length, prefix)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeMapCompact (data, pos, minor, _options) {
  return toToken(data, pos, 1, minor)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer map lengths not supported`)
  }
  return toToken(data, pos, 9, l)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMapIndefinite (data, pos, _minor, options) {
  if (options.allowIndefinite === false) {
    throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)
  }
  return toToken(data, pos, 1, Infinity)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeMap (writer, token) {
  uint.encodeUintValue(writer, Type.map.majorEncoded, token.value)
}

// using a map as a map key, are you sure about this? we can only sort
// by map length here, it's up to the encoder to decide to look deeper
encodeMap.compareTokens = uint.encodeUint.compareTokens

/**
 * @param {Token} token
 * @returns {number}
 */
encodeMap.encodedSize = function encodedSize (token) {
  return uint.encodeUintValue.encodedSize(token.value)
}
import { Token, Type } from './token.js'
import * as uint from './0uint.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeTagCompact (_data, _pos, minor, _options) {
  return new Token(Type.tag, minor, 1)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag8 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint8(data, pos + 1, options), 2)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag16 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint16(data, pos + 1, options), 3)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag32 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint32(data, pos + 1, options), 5)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag64 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint64(data, pos + 1, options), 9)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeTag (writer, token) {
  uint.encodeUintValue(writer, Type.tag.majorEncoded, token.value)
}

encodeTag.compareTokens = uint.encodeUint.compareTokens

/**
 * @param {Token} token
 * @returns {number}
 */
encodeTag.encodedSize = function encodedSize (token) {
  return uint.encodeUintValue.encodedSize(token.value)
}
// TODO: shift some of the bytes logic to bytes-utils so we can use Buffer
// where possible

import { Token, Type } from './token.js'
import { decodeErrPrefix } from './common.js'
import { encodeUint } from './0uint.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 * @typedef {import('../interface.js').EncodeOptions} EncodeOptions
 */

export const MINOR_FALSE = 20
export const MINOR_TRUE = 21
export const MINOR_NULL = 22
export const MINOR_UNDEFINED = 23

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUndefined (_data, _pos, _minor, options) {
  if (options.allowUndefined === false) {
    throw new Error(`${decodeErrPrefix} undefined values are not supported`)
  } else if (options.coerceUndefinedToNull === true) {
    return new Token(Type.null, null, 1)
  }
  return new Token(Type.undefined, undefined, 1)
}

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBreak (_data, _pos, _minor, options) {
  if (options.allowIndefinite === false) {
    throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)
  }
  return new Token(Type.break, undefined, 1)
}

/**
 * @param {number} value
 * @param {number} bytes
 * @param {DecodeOptions} options
 * @returns {Token}
 */
function createToken (value, bytes, options) {
  if (options) {
    if (options.allowNaN === false && Number.isNaN(value)) {
      throw new Error(`${decodeErrPrefix} NaN values are not supported`)
    }
    if (options.allowInfinity === false && (value === Infinity || value === -Infinity)) {
      throw new Error(`${decodeErrPrefix} Infinity values are not supported`)
    }
  }
  return new Token(Type.float, value, bytes)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeFloat16 (data, pos, _minor, options) {
  return createToken(readFloat16(data, pos + 1), 3, options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeFloat32 (data, pos, _minor, options) {
  return createToken(readFloat32(data, pos + 1), 5, options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeFloat64 (data, pos, _minor, options) {
  return createToken(readFloat64(data, pos + 1), 9, options)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 * @param {EncodeOptions} options
 */
export function encodeFloat (writer, token, options) {
  const float = token.value

  if (float === false) {
    writer.push([Type.float.majorEncoded | MINOR_FALSE])
  } else if (float === true) {
    writer.push([Type.float.majorEncoded | MINOR_TRUE])
  } else if (float === null) {
    writer.push([Type.float.majorEncoded | MINOR_NULL])
  } else if (float === undefined) {
    writer.push([Type.float.majorEncoded | MINOR_UNDEFINED])
  } else {
    let decoded
    let success = false
    if (!options || options.float64 !== true) {
      encodeFloat16(float)
      decoded = readFloat16(ui8a, 1)
      if (float === decoded || Number.isNaN(float)) {
        ui8a[0] = 0xf9
        writer.push(ui8a.slice(0, 3))
        success = true
      } else {
        encodeFloat32(float)
        decoded = readFloat32(ui8a, 1)
        if (float === decoded) {
          ui8a[0] = 0xfa
          writer.push(ui8a.slice(0, 5))
          success = true
        }
      }
    }
    if (!success) {
      encodeFloat64(float)
      decoded = readFloat64(ui8a, 1)
      ui8a[0] = 0xfb
      writer.push(ui8a.slice(0, 9))
    }
  }
}

/**
 * @param {Token} token
 * @param {EncodeOptions} options
 * @returns {number}
 */
encodeFloat.encodedSize = function encodedSize (token, options) {
  const float = token.value

  if (float === false || float === true || float === null || float === undefined) {
    return 1
  }

  if (!options || options.float64 !== true) {
    encodeFloat16(float)
    let decoded = readFloat16(ui8a, 1)
    if (float === decoded || Number.isNaN(float)) {
      return 3
    }
    encodeFloat32(float)
    decoded = readFloat32(ui8a, 1)
    if (float === decoded) {
      return 5
    }
  }
  return 9
}

const buffer = new ArrayBuffer(9)
const dataView = new DataView(buffer, 1)
const ui8a = new Uint8Array(buffer, 0)

/**
 * @param {number} inp
 */
function encodeFloat16 (inp) {
  if (inp === Infinity) {
    dataView.setUint16(0, 0x7c00, false)
  } else if (inp === -Infinity) {
    dataView.setUint16(0, 0xfc00, false)
  } else if (Number.isNaN(inp)) {
    dataView.setUint16(0, 0x7e00, false)
  } else {
    dataView.setFloat32(0, inp)
    const valu32 = dataView.getUint32(0)
    const exponent = (valu32 & 0x7f800000) >> 23
    const mantissa = valu32 & 0x7fffff

    if (exponent === 0xff) {
      // too big, Infinity, but this should be hard (impossible?) to trigger
      dataView.setUint16(0, 0x7c00, false)
    } else if (exponent === 0x00) {
      // 0.0, -0.0 and subnormals, shouldn't be possible to get here because 0.0 should be counted as an int
      // Use valu32 for sign bit since bitwise ops on floats lose -0 sign
      dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | (mantissa >> 13), false)
    } else { // standard numbers
      // chunks of logic here borrowed from https://github.com/PJK/libcbor/blob/c78f437182533e3efa8d963ff4b945bb635c2284/src/cbor/encoding.c#L127
      const logicalExponent = exponent - 127
      // Now we know that 2^exponent <= 0 logically
      if (logicalExponent < -24) {
        /* No unambiguous representation exists, this float is not a half float
          and is too small to be represented using a half, round off to zero.
          Consistent with the reference implementation. */
        // should be difficult (impossible?) to get here in JS
        dataView.setUint16(0, 0)
      } else if (logicalExponent < -14) {
        /* Offset the remaining decimal places by shifting the significand, the
          value is lost. This is an implementation decision that works around the
          absence of standard half-float in the language. */
        dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | /* sign bit */ (1 << (24 + logicalExponent)), false)
      } else {
        dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | ((logicalExponent + 15) << 10) | (mantissa >> 13), false)
      }
    }
  }
}

/**
 * @param {Uint8Array} ui8a
 * @param {number} pos
 * @returns {number}
 */
function readFloat16 (ui8a, pos) {
  if (ui8a.length - pos < 2) {
    throw new Error(`${decodeErrPrefix} not enough data for float16`)
  }

  const half = (ui8a[pos] << 8) + ui8a[pos + 1]
  if (half === 0x7c00) {
    return Infinity
  }
  if (half === 0xfc00) {
    return -Infinity
  }
  if (half === 0x7e00) {
    return NaN
  }
  const exp = (half >> 10) & 0x1f
  const mant = half & 0x3ff
  let val
  if (exp === 0) {
    val = mant * (2 ** -24)
  } else if (exp !== 31) {
    val = (mant + 1024) * (2 ** (exp - 25))
  } else {
    // may not be possible to get here
    val = mant === 0 ? Infinity : NaN
  }
  return (half & 0x8000) ? -val : val
}

/**
 * @param {number} inp
 */
function encodeFloat32 (inp) {
  dataView.setFloat32(0, inp, false)
}

/**
 * @param {Uint8Array} ui8a
 * @param {number} pos
 * @returns {number}
 */
function readFloat32 (ui8a, pos) {
  if (ui8a.length - pos < 4) {
    throw new Error(`${decodeErrPrefix} not enough data for float32`)
  }
  const offset = (ui8a.byteOffset || 0) + pos
  return new DataView(ui8a.buffer, offset, 4).getFloat32(0, false)
}

/**
 * @param {number} inp
 */
function encodeFloat64 (inp) {
  dataView.setFloat64(0, inp, false)
}

/**
 * @param {Uint8Array} ui8a
 * @param {number} pos
 * @returns {number}
 */
function readFloat64 (ui8a, pos) {
  if (ui8a.length - pos < 8) {
    throw new Error(`${decodeErrPrefix} not enough data for float64`)
  }
  const offset = (ui8a.byteOffset || 0) + pos
  return new DataView(ui8a.buffer, offset, 8).getFloat64(0, false)
}

/**
 * @param {Token} _tok1
 * @param {Token} _tok2
 * @returns {number}
 */
encodeFloat.compareTokens = encodeUint.compareTokens
/*
encodeFloat.compareTokens = function compareTokens (_tok1, _tok2) {
  return _tok1
  throw new Error(`${encodeErrPrefix} cannot use floats as map keys`)
}
*/
/**
 * Bl is a list of byte chunks, similar to https://github.com/rvagg/bl but for
 * writing rather than reading.
 * A Bl object accepts set() operations for individual bytes and copyTo() for
 * inserting byte arrays. These write operations don't automatically increment
 * the internal cursor so its "length" won't be changed. Instead, increment()
 * must be called to extend its length to cover the inserted data.
 * The toBytes() call will convert all internal memory to a single Uint8Array of
 * the correct length, truncating any data that is stored but hasn't been
 * included by an increment().
 * get() can retrieve a single byte.
 * All operations (except toBytes()) take an "offset" argument that will perform
 * the write at the offset _from the current cursor_. For most operations this
 * will be `0` to write at the current cursor position but it can be ahead of
 * the current cursor. Negative offsets probably work but are untested.
 */

// TODO: ipjs doesn't support this, only for test files: https://github.com/mikeal/ipjs/blob/master/src/package/testFile.js#L39
import { alloc, concat, slice } from './byte-utils.js'

// the ts-ignores in this file are almost all for the `Uint8Array|number[]` duality that exists
// for perf reasons. Consider better approaches to this or removing it entirely, it is quite
// risky because of some assumptions about small chunks === number[] and everything else === Uint8Array.

const defaultChunkSize = 256

export class Bl {
  /**
   * @param {number} [chunkSize]
   */
  constructor (chunkSize = defaultChunkSize) {
    this.chunkSize = chunkSize
    /** @type {number} */
    this.cursor = 0
    /** @type {number} */
    this.maxCursor = -1
    /** @type {(Uint8Array|number[])[]} */
    this.chunks = []
    // keep the first chunk around if we can to save allocations for future encodes
    /** @type {Uint8Array|number[]|null} */
    this._initReuseChunk = null
  }

  reset () {
    this.cursor = 0
    this.maxCursor = -1
    if (this.chunks.length) {
      this.chunks = []
    }
    if (this._initReuseChunk !== null) {
      this.chunks.push(this._initReuseChunk)
      this.maxCursor = this._initReuseChunk.length - 1
    }
  }

  /**
   * @param {Uint8Array|number[]} bytes
   */
  push (bytes) {
    let topChunk = this.chunks[this.chunks.length - 1]
    const newMax = this.cursor + bytes.length
    if (newMax <= this.maxCursor + 1) {
      // we have at least one chunk and we can fit these bytes into that chunk
      const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1
      // @ts-ignore
      topChunk.set(bytes, chunkPos)
    } else {
      // can't fit it in
      if (topChunk) {
        // trip the last chunk to `cursor` if we need to
        const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1
        if (chunkPos < topChunk.length) {
          // @ts-ignore
          this.chunks[this.chunks.length - 1] = topChunk.subarray(0, chunkPos)
          this.maxCursor = this.cursor - 1
        }
      }
      if (bytes.length < 64 && bytes.length < this.chunkSize) {
        // make a new chunk and copy the new one into it
        topChunk = alloc(this.chunkSize)
        this.chunks.push(topChunk)
        this.maxCursor += topChunk.length
        if (this._initReuseChunk === null) {
          this._initReuseChunk = topChunk
        }
        // @ts-ignore
        topChunk.set(bytes, 0)
      } else {
        // push the new bytes in as its own chunk
        this.chunks.push(bytes)
        this.maxCursor += bytes.length
      }
    }
    this.cursor += bytes.length
  }

  /**
   * @param {boolean} [reset]
   * @returns {Uint8Array}
   */
  toBytes (reset = false) {
    let byts
    if (this.chunks.length === 1) {
      const chunk = this.chunks[0]
      if (reset && this.cursor > chunk.length / 2) {
        // @ts-ignore
        byts = this.cursor === chunk.length ? chunk : chunk.subarray(0, this.cursor)
        this._initReuseChunk = null
        this.chunks = []
      } else {
        // @ts-ignore
        byts = slice(chunk, 0, this.cursor)
      }
    } else {
      // @ts-ignore
      byts = concat(this.chunks, this.cursor)
    }
    if (reset) {
      this.reset()
    }
    return byts
  }
}

/**
 * U8Bl is a buffer list that writes directly to a user-provided Uint8Array.
 * It provides the same interface as Bl but writes to a fixed destination.
 */
export class U8Bl {
  /**
   * @param {Uint8Array} dest
   */
  constructor (dest) {
    this.dest = dest
    /** @type {number} */
    this.cursor = 0
    // chunks is for interface compatibility with Bl - encode.js checks chunks.length
    // as a sanity check for pre-calculated sizes. For U8Bl this is always [dest].
    /** @type {Uint8Array[]} */
    this.chunks = [dest]
  }

  reset () {
    this.cursor = 0
  }

  /**
   * @param {Uint8Array|number[]} bytes
   */
  push (bytes) {
    if (this.cursor + bytes.length > this.dest.length) {
      throw new Error('write out of bounds, destination buffer is too small')
    }
    this.dest.set(bytes, this.cursor)
    this.cursor += bytes.length
  }

  /**
   * @param {boolean} [reset]
   * @returns {Uint8Array}
   */
  toBytes (reset = false) {
    const byts = this.dest.subarray(0, this.cursor)
    if (reset) {
      this.reset()
    }
    return byts
  }
}
// Use Uint8Array directly in the browser, use Buffer in Node.js but don't
// speak its name directly to avoid bundlers pulling in the `Buffer` polyfill

// @ts-ignore
export const useBuffer = globalThis.process &&
  // @ts-ignore
  !globalThis.process.browser &&
  // @ts-ignore
  globalThis.Buffer &&
  // @ts-ignore
  typeof globalThis.Buffer.isBuffer === 'function'

const textEncoder = new TextEncoder()

/**
 * @param {Uint8Array} buf
 * @returns {boolean}
 */
function isBuffer (buf) {
  // @ts-ignore
  return useBuffer && globalThis.Buffer.isBuffer(buf)
}

/**
 * @param {Uint8Array|number[]} buf
 * @returns {Uint8Array}
 */
export function asU8A (buf) {
  if (!(buf instanceof Uint8Array)) {
    return Uint8Array.from(buf)
  }
  return isBuffer(buf) ? new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength) : buf
}

// Threshold for manual UTF-8 encoding vs native methods.
// Node.js Buffer.from: crossover ~24 chars
// Browser TextEncoder: crossover ~200 chars
const FROM_STRING_THRESHOLD_BUFFER = 24
const FROM_STRING_THRESHOLD_TEXTENCODER = 200

export const fromString = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {string} string
     */
    (string) => {
      return string.length >= FROM_STRING_THRESHOLD_BUFFER
        ? // eslint-disable-line operator-linebreak
      // @ts-ignore
        globalThis.Buffer.from(string)
        : utf8ToBytes(string)
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {string} string
     */
    (string) => {
      return string.length >= FROM_STRING_THRESHOLD_TEXTENCODER ? textEncoder.encode(string) : utf8ToBytes(string)
    }

/**
 * Buffer variant not fast enough for what we need
 * @param {number[]} arr
 * @returns {Uint8Array}
 */
export const fromArray = (arr) => {
  return Uint8Array.from(arr)
}

export const slice = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} bytes
     * @param {number} start
     * @param {number} end
     */
    // Buffer.slice() returns a view, not a copy, so we need special handling
    (bytes, start, end) => {
      if (isBuffer(bytes)) {
        return new Uint8Array(bytes.subarray(start, end))
      }
      return bytes.slice(start, end)
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} bytes
     * @param {number} start
     * @param {number} end
     */
    (bytes, start, end) => {
      return bytes.slice(start, end)
    }

export const concat = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array[]} chunks
     * @param {number} length
     * @returns {Uint8Array}
     */
    (chunks, length) => {
      // might get a stray plain Array here
      chunks = chunks.map((c) => c instanceof Uint8Array
        ? c
        : // eslint-disable-line operator-linebreak
        // @ts-ignore
        globalThis.Buffer.from(c))
      // @ts-ignore
      return asU8A(globalThis.Buffer.concat(chunks, length))
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array[]} chunks
     * @param {number} length
     * @returns {Uint8Array}
     */
    (chunks, length) => {
      const out = new Uint8Array(length)
      let off = 0
      for (let b of chunks) {
        if (off + b.length > out.length) {
          // final chunk that's bigger than we need
          b = b.subarray(0, out.length - off)
        }
        out.set(b, off)
        off += b.length
      }
      return out
    }

export const alloc = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {number} size
     * @returns {Uint8Array}
     */
    (size) => {
      // we always write over the contents we expose so this should be safe
      // @ts-ignore
      return globalThis.Buffer.allocUnsafe(size)
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {number} size
     * @returns {Uint8Array}
     */
    (size) => {
      return new Uint8Array(size)
    }

export const toHex = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} d
     * @returns {string}
     */
    (d) => {
      if (typeof d === 'string') {
        return d
      }
      // @ts-ignore
      return globalThis.Buffer.from(toBytes(d)).toString('hex')
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} d
     * @returns {string}
     */
    (d) => {
      if (typeof d === 'string') {
        return d
      }
      // @ts-ignore not smart enough to figure this out
      return Array.prototype.reduce.call(toBytes(d), (p, c) => `${p}${c.toString(16).padStart(2, '0')}`, '')
    }

export const fromHex = useBuffer
  ? // eslint-disable-line operator-linebreak
  /**
   * @param {string|Uint8Array} hex
   * @returns {Uint8Array}
   */
    (hex) => {
      if (hex instanceof Uint8Array) {
        return hex
      }
      // @ts-ignore
      return globalThis.Buffer.from(hex, 'hex')
    }
  : // eslint-disable-line operator-linebreak
  /**
   * @param {string|Uint8Array} hex
   * @returns {Uint8Array}
   */
    (hex) => {
      if (hex instanceof Uint8Array) {
        return hex
      }
      if (!hex.length) {
        return new Uint8Array(0)
      }
      return new Uint8Array(hex.split('')
        .map((/** @type {string} */ c, /** @type {number} */ i, /** @type {string[]} */ d) => i % 2 === 0 ? `0x${c}${d[i + 1]}` : '')
        .filter(Boolean)
        .map((/** @type {string} */ e) => parseInt(e, 16)))
    }

/**
 * @param {Uint8Array|ArrayBuffer|ArrayBufferView} obj
 * @returns {Uint8Array}
 */
function toBytes (obj) {
  if (obj instanceof Uint8Array && obj.constructor.name === 'Uint8Array') {
    return obj
  }
  if (obj instanceof ArrayBuffer) {
    return new Uint8Array(obj)
  }
  if (ArrayBuffer.isView(obj)) {
    return new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength)
  }
  throw new Error('Unknown type, must be binary type')
}

/**
 * @param {Uint8Array} b1
 * @param {Uint8Array} b2
 * @returns {number}
 */
export function compare (b1, b2) {
  if (isBuffer(b1) && isBuffer(b2)) {
    // probably not possible to get here in the current API
    // @ts-ignore Buffer
    return b1.compare(b2)
  }
  for (let i = 0; i < b1.length; i++) {
    if (b1[i] === b2[i]) {
      continue
    }
    return b1[i] < b2[i] ? -1 : 1
  }
  return 0
}

// The below code is taken from https://github.com/google/closure-library/blob/8598d87242af59aac233270742c8984e2b2bdbe0/closure/goog/crypt/crypt.js#L117-L143
// Licensed Apache-2.0.

/**
 * @param {string} str
 * @returns {number[]}
 */
function utf8ToBytes (str) {
  const out = []
  let p = 0
  for (let i = 0; i < str.length; i++) {
    let c = str.charCodeAt(i)
    if (c < 128) {
      out[p++] = c
    } else if (c < 2048) {
      out[p++] = (c >> 6) | 192
      out[p++] = (c & 63) | 128
    } else if (
      ((c & 0xFC00) === 0xD800) && (i + 1) < str.length &&
      ((str.charCodeAt(i + 1) & 0xFC00) === 0xDC00)) {
      // Surrogate Pair
      c = 0x10000 + ((c & 0x03FF) << 10) + (str.charCodeAt(++i) & 0x03FF)
      out[p++] = (c >> 18) | 240
      out[p++] = ((c >> 12) & 63) | 128
      out[p++] = ((c >> 6) & 63) | 128
      out[p++] = (c & 63) | 128
    } else {
      if ((c >= 0xD800) && (c <= 0xDFFF)) {
        c = 0xFFFD // Unpaired Surrogate
      }
      out[p++] = (c >> 12) | 224
      out[p++] = ((c >> 6) & 63) | 128
      out[p++] = (c & 63) | 128
    }
  }
  return out
}

// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
const MAX_ARGUMENTS_LENGTH = 0x1000

/**
 * @param {number[]} codePoints
 * @returns {string}
 */
export function decodeCodePointsArray (codePoints) {
  const len = codePoints.length
  if (len <= MAX_ARGUMENTS_LENGTH) {
    return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  }
  // Decode in chunks to avoid "call stack size exceeded".
  let res = ''
  let i = 0
  while (i < len) {
    res += String.fromCharCode.apply(
      String,
      codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
    )
  }
  return res
}
const decodeErrPrefix = 'CBOR decode error:'
const encodeErrPrefix = 'CBOR encode error:'

const uintMinorPrefixBytes = []
uintMinorPrefixBytes[23] = 1
uintMinorPrefixBytes[24] = 2
uintMinorPrefixBytes[25] = 3
uintMinorPrefixBytes[26] = 5
uintMinorPrefixBytes[27] = 9

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} need
 */
function assertEnoughData (data, pos, need) {
  if (data.length - pos < need) {
    throw new Error(`${decodeErrPrefix} not enough data for type`)
  }
}

export {
  decodeErrPrefix,
  encodeErrPrefix,
  uintMinorPrefixBytes,
  assertEnoughData
}
import { decodeErrPrefix } from './common.js'
import { Type } from './token.js'
import { jump, quick } from './jump.js'
import { asU8A } from './byte-utils.js'

/**
 * @typedef {import('./token.js').Token} Token
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 * @typedef {import('../interface.js').DecodeTokenizer} DecodeTokenizer
 * @typedef {import('../interface.js').TagDecodeControl} TagDecodeControl
 */

const defaultDecodeOptions = {
  strict: false,
  allowIndefinite: true,
  allowUndefined: true,
  allowBigInt: true
}

/**
 * @implements {DecodeTokenizer}
 */
class Tokeniser {
  /**
   * @param {Uint8Array} data
   * @param {DecodeOptions} options
   */
  constructor (data, options = {}) {
    this._pos = 0
    this.data = data
    this.options = options
  }

  pos () {
    return this._pos
  }

  done () {
    return this._pos >= this.data.length
  }

  next () {
    const byt = this.data[this._pos]
    let token = quick[byt]
    if (token === undefined) {
      const decoder = jump[byt]
      // if we're here then there's something wrong with our jump or quick lists!
      if (!decoder) {
        throw new Error(`${decodeErrPrefix} no decoder for major type ${byt >>> 5} (byte 0x${byt.toString(16).padStart(2, '0')})`)
      }
      const minor = byt & 31
      token = decoder(this.data, this._pos, minor, this.options)
    }
    // @ts-ignore we get to assume encodedLength is set (crossing fingers slightly)
    this._pos += token.encodedLength
    return token
  }
}

const DONE = Symbol.for('DONE')
const BREAK = Symbol.for('BREAK')

/**
 * @param {Token} token
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {any|BREAK|DONE}
 */
function tokenToArray (token, tokeniser, options) {
  const arr = []
  for (let i = 0; i < token.value; i++) {
    const value = tokensToObject(tokeniser, options)
    if (value === BREAK) {
      if (token.value === Infinity) {
        // normal end to indefinite length array
        break
      }
      throw new Error(`${decodeErrPrefix} got unexpected break to lengthed array`)
    }
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} found array but not enough entries (got ${i}, expected ${token.value})`)
    }
    arr[i] = value
  }
  return arr
}

/**
 * @param {Token} token
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {any|BREAK|DONE}
 */
function tokenToMap (token, tokeniser, options) {
  const useMaps = options.useMaps === true
  const rejectDuplicateMapKeys = options.rejectDuplicateMapKeys === true
  const obj = useMaps ? undefined : {}
  const m = useMaps ? new Map() : undefined
  for (let i = 0; i < token.value; i++) {
    const key = tokensToObject(tokeniser, options)
    if (key === BREAK) {
      if (token.value === Infinity) {
        // normal end to indefinite length map
        break
      }
      throw new Error(`${decodeErrPrefix} got unexpected break to lengthed map`)
    }
    if (key === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no key], expected ${token.value})`)
    }
    if (!useMaps && typeof key !== 'string') {
      throw new Error(`${decodeErrPrefix} non-string keys not supported (got ${typeof key})`)
    }
    if (rejectDuplicateMapKeys) {
      // @ts-ignore
      if ((useMaps && m.has(key)) || (!useMaps && Object.hasOwn(obj, key))) {
        throw new Error(`${decodeErrPrefix} found repeat map key "${key}"`)
      }
    }
    const value = tokensToObject(tokeniser, options)
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no value], expected ${token.value})`)
    }
    if (useMaps) {
      // @ts-ignore TODO reconsider this .. maybe needs to be strict about key types
      m.set(key, value)
    } else {
      // @ts-ignore TODO reconsider this .. maybe needs to be strict about key types
      obj[key] = value
    }
  }
  // @ts-ignore c'mon man
  return useMaps ? m : obj
}

/**
 * Generator that yields [key, value] entries from a CBOR map token.
 * Used by tag decoders that need to preserve key types (e.g., Tag 259 Map).
 * @param {Token} token - The map token
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {Generator<[any, any], void, unknown>}
 */
function * tokenToMapEntries (token, tokeniser, options) {
  for (let i = 0; i < token.value; i++) {
    const key = tokensToObject(tokeniser, options)
    if (key === BREAK) {
      if (token.value === Infinity) {
        // normal end to indefinite length map
        break
      }
      throw new Error(`${decodeErrPrefix} got unexpected break to lengthed map`)
    }
    if (key === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no key], expected ${token.value})`)
    }
    const value = tokensToObject(tokeniser, options)
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no value], expected ${token.value})`)
    }
    yield [key, value]
  }
}

/**
 * Creates a TagDecodeControl object for tag decoders.
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {TagDecodeControl}
 */
function createTagDecodeControl (tokeniser, options) {
  let called = false

  /**
   * @type {TagDecodeControl}
   */
  const decode = function () {
    if (called) {
      throw new Error(`${decodeErrPrefix} tag decode() may only be called once`)
    }
    called = true
    const value = tokensToObject(tokeniser, options)
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} tag content missing`)
    }
    if (value === BREAK) {
      throw new Error(`${decodeErrPrefix} got unexpected break in tag content`)
    }
    return value
  }

  decode.entries = function () {
    if (called) {
      throw new Error(`${decodeErrPrefix} tag decode() may only be called once`)
    }
    called = true

    // Get the next token and ensure it's a map
    const token = tokeniser.next()
    if (!Type.equals(token.type, Type.map)) {
      throw new Error(`${decodeErrPrefix} entries() requires map content, got ${token.type.name}`)
    }

    // Collect all entries into an array (ensures full content consumption)
    const entries = []
    for (const entry of tokenToMapEntries(token, tokeniser, options)) {
      entries.push(entry)
    }
    return entries
  }

  // For internal tracking
  Object.defineProperty(decode, '_called', {
    get () { return called },
    enumerable: false
  })

  return decode
}

/**
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {any|BREAK|DONE}
 */
function tokensToObject (tokeniser, options) {
  // should we support array as an argument?
  // check for tokenIter[Symbol.iterator] and replace tokenIter with what that returns?
  if (tokeniser.done()) {
    return DONE
  }

  const token = tokeniser.next()

  if (Type.equals(token.type, Type.break)) {
    return BREAK
  }

  if (token.type.terminal) {
    return token.value
  }

  if (Type.equals(token.type, Type.array)) {
    return tokenToArray(token, tokeniser, options)
  }

  if (Type.equals(token.type, Type.map)) {
    return tokenToMap(token, tokeniser, options)
  }

  if (Type.equals(token.type, Type.tag)) {
    if (options.tags && typeof options.tags[token.value] === 'function') {
      const decodeControl = createTagDecodeControl(tokeniser, options)
      const result = options.tags[token.value](decodeControl)
      if (!decodeControl._called) {
        throw new Error(`${decodeErrPrefix} tag decoder must call decode() or entries()`)
      }
      return result
    }
    throw new Error(`${decodeErrPrefix} tag not supported (${token.value})`)
  }
  throw new Error('unsupported')
}

/**
 * @param {Uint8Array} data
 * @param {DecodeOptions} [options]
 * @returns {[any, Uint8Array]}
 */
function decodeFirst (data, options) {
  if (!(data instanceof Uint8Array)) {
    throw new Error(`${decodeErrPrefix} data to decode must be a Uint8Array`)
  }
  options = Object.assign({}, defaultDecodeOptions, options)
  // Convert Buffer to plain Uint8Array for faster slicing in decode path
  const u8aData = asU8A(data)
  const tokeniser = options.tokenizer || new Tokeniser(u8aData, options)
  const decoded = tokensToObject(tokeniser, options)
  if (decoded === DONE) {
    throw new Error(`${decodeErrPrefix} did not find any content to decode`)
  }
  if (decoded === BREAK) {
    throw new Error(`${decodeErrPrefix} got unexpected break`)
  }
  return [decoded, data.subarray(tokeniser.pos())]
}

/**
 * @param {Uint8Array} data
 * @param {DecodeOptions} [options]
 * @returns {any}
 */
function decode (data, options) {
  const [decoded, remainder] = decodeFirst(data, options)
  if (remainder.length > 0) {
    throw new Error(`${decodeErrPrefix} too many terminals, data makes no sense`)
  }
  return decoded
}

export { Tokeniser, tokensToObject, decode, decodeFirst }
import { is } from './is.js'
import { Token, Type } from './token.js'
import { Bl, U8Bl } from './bl.js'
import { encodeErrPrefix } from './common.js'
import { quickEncodeToken } from './jump.js'
import { asU8A, compare, fromString } from './byte-utils.js'

import { encodeUint, encodeUintValue } from './0uint.js'
import { encodeNegint } from './1negint.js'
import { encodeBytes } from './2bytes.js'
import { encodeString } from './3string.js'
import { encodeArray } from './4array.js'
import { encodeMap } from './5map.js'
import { encodeTag } from './6tag.js'
import { encodeFloat, MINOR_FALSE, MINOR_TRUE, MINOR_NULL, MINOR_UNDEFINED } from './7float.js'

/**
 * @typedef {import('../interface.js').EncodeOptions} EncodeOptions
 * @typedef {import('../interface.js').OptionalTypeEncoder} OptionalTypeEncoder
 * @typedef {import('../interface.js').Reference} Reference
 * @typedef {import('../interface.js').StrictTypeEncoder} StrictTypeEncoder
 * @typedef {import('../interface.js').TokenTypeEncoder} TokenTypeEncoder
 * @typedef {import('../interface.js').TokenOrNestedTokens} TokenOrNestedTokens
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 */

/** @type {EncodeOptions} */
const defaultEncodeOptions = {
  float64: false,
  mapSorter,
  quickEncodeToken
}

/** @type {EncodeOptions} */
export const rfc8949EncodeOptions = Object.freeze({
  mapSorter: rfc8949MapSorter,
  quickEncodeToken
})

/** @returns {TokenTypeEncoder[]} */
export function makeCborEncoders () {
  const encoders = []
  encoders[Type.uint.major] = encodeUint
  encoders[Type.negint.major] = encodeNegint
  encoders[Type.bytes.major] = encodeBytes
  encoders[Type.string.major] = encodeString
  encoders[Type.array.major] = encodeArray
  encoders[Type.map.major] = encodeMap
  encoders[Type.tag.major] = encodeTag
  encoders[Type.float.major] = encodeFloat
  return encoders
}

const cborEncoders = makeCborEncoders()

const defaultWriter = new Bl()

/** @implements {Reference} */
class Ref {
  /**
   * @param {object|any[]} obj
   * @param {Reference|undefined} parent
   */
  constructor (obj, parent) {
    this.obj = obj
    this.parent = parent
  }

  /**
   * @param {object|any[]} obj
   * @returns {boolean}
   */
  includes (obj) {
    /** @type {Reference|undefined} */
    let p = this
    do {
      if (p.obj === obj) {
        return true
      }
    } while (p = p.parent) // eslint-disable-line
    return false
  }

  /**
   * @param {Reference|undefined} stack
   * @param {object|any[]} obj
   * @returns {Reference}
   */
  static createCheck (stack, obj) {
    if (stack && stack.includes(obj)) {
      throw new Error(`${encodeErrPrefix} object contains circular references`)
    }
    return new Ref(obj, stack)
  }
}

const simpleTokens = {
  null: new Token(Type.null, null),
  undefined: new Token(Type.undefined, undefined),
  true: new Token(Type.true, true),
  false: new Token(Type.false, false),
  emptyArray: new Token(Type.array, 0),
  emptyMap: new Token(Type.map, 0)
}

/** @type {{[typeName: string]: StrictTypeEncoder}} */
const typeEncoders = {
  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  number (obj, _typ, _options, _refStack) {
    if (!Number.isInteger(obj) || !Number.isSafeInteger(obj)) {
      return new Token(Type.float, obj)
    } else if (obj >= 0) {
      return new Token(Type.uint, obj)
    } else {
      return new Token(Type.negint, obj)
    }
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  bigint (obj, _typ, _options, _refStack) {
    if (obj >= BigInt(0)) {
      return new Token(Type.uint, obj)
    } else {
      return new Token(Type.negint, obj)
    }
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  Uint8Array (obj, _typ, _options, _refStack) {
    return new Token(Type.bytes, obj)
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  string (obj, _typ, _options, _refStack) {
    return new Token(Type.string, obj)
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  boolean (obj, _typ, _options, _refStack) {
    return obj ? simpleTokens.true : simpleTokens.false
  },

  /**
   * @param {any} _obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  null (_obj, _typ, _options, _refStack) {
    return simpleTokens.null
  },

  /**
   * @param {any} _obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  undefined (_obj, _typ, _options, _refStack) {
    return simpleTokens.undefined
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  ArrayBuffer (obj, _typ, _options, _refStack) {
    return new Token(Type.bytes, new Uint8Array(obj))
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  DataView (obj, _typ, _options, _refStack) {
    return new Token(Type.bytes, new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength))
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} options
   * @param {Reference} [refStack]
   * @returns {TokenOrNestedTokens}
   */
  Array (obj, _typ, options, refStack) {
    if (!obj.length) {
      if (options.addBreakTokens === true) {
        return [simpleTokens.emptyArray, new Token(Type.break)]
      }
      return simpleTokens.emptyArray
    }
    refStack = Ref.createCheck(refStack, obj)
    const entries = []
    let i = 0
    for (const e of obj) {
      entries[i++] = objectToTokens(e, options, refStack)
    }
    if (options.addBreakTokens) {
      return [new Token(Type.array, obj.length), entries, new Token(Type.break)]
    }
    return [new Token(Type.array, obj.length), entries]
  },

  /**
   * @param {any} obj
   * @param {string} typ
   * @param {EncodeOptions} options
   * @param {Reference} [refStack]
   * @returns {TokenOrNestedTokens}
   */
  Object (obj, typ, options, refStack) {
    // could be an Object or a Map
    const isMap = typ !== 'Object'
    // it's slightly quicker to use Object.keys() than Object.entries()
    const keys = isMap ? obj.keys() : Object.keys(obj)
    const maxLength = isMap ? obj.size : keys.length

    /** @type {undefined | [TokenOrNestedTokens, TokenOrNestedTokens][]} */
    let entries

    if (maxLength) {
      // Pre-allocate the array with the expected size
      entries = new Array(maxLength)
      refStack = Ref.createCheck(refStack, obj)
      const skipUndefined = !isMap && options.ignoreUndefinedProperties

      let i = 0
      for (const key of keys) {
        const value = isMap ? obj.get(key) : obj[key]
        if (skipUndefined && value === undefined) {
          continue
        }
        entries[i++] = [
          objectToTokens(key, options, refStack),
          objectToTokens(value, options, refStack)
        ]
      }

      // Truncate only if properties were skipped
      if (i < maxLength) {
        entries.length = i
      }
    }

    if (!entries?.length) {
      if (options.addBreakTokens === true) {
        return [simpleTokens.emptyMap, new Token(Type.break)]
      }
      return simpleTokens.emptyMap
    }

    sortMapEntries(entries, options)
    if (options.addBreakTokens) {
      return [new Token(Type.map, entries.length), entries, new Token(Type.break)]
    }
    return [new Token(Type.map, entries.length), entries]
  },

  /**
   * Encode a `Tagged` wrapper as a CBOR tag header followed by the encoded
   * form of the wrapped value. The value is recursively tokenised through
   * `objectToTokens()` so any registered `typeEncoders` apply to it.
   *
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} options
   * @param {Reference} [refStack]
   * @returns {TokenOrNestedTokens}
   */
  Tagged (obj, _typ, options, refStack) {
    return [
      new Token(Type.tag, obj.tag),
      objectToTokens(obj.value, options, refStack)
    ]
  }
}

typeEncoders.Map = typeEncoders.Object
typeEncoders.Buffer = typeEncoders.Uint8Array
for (const typ of 'Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64'.split(' ')) {
  typeEncoders[`${typ}Array`] = typeEncoders.DataView
}

/**
 * @param {any} obj
 * @param {EncodeOptions} [options]
 * @param {Reference} [refStack]
 * @returns {TokenOrNestedTokens}
 */
function objectToTokens (obj, options = {}, refStack) {
  const typ = is(obj)
  const customTypeEncoder = (options && options.typeEncoders && /** @type {OptionalTypeEncoder} */ options.typeEncoders[typ]) || typeEncoders[typ]
  if (typeof customTypeEncoder === 'function') {
    const tokens = customTypeEncoder(obj, typ, options, refStack)
    if (tokens != null) {
      return tokens
    }
  }
  const typeEncoder = typeEncoders[typ]
  if (!typeEncoder) {
    throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`)
  }
  return typeEncoder(obj, typ, options, refStack)
}

/*
CBOR key sorting is a mess.

The canonicalisation recommendation from https://tools.ietf.org/html/rfc7049#section-3.9
includes the wording:

> The keys in every map must be sorted lowest value to highest.
> Sorting is performed on the bytes of the representation of the key
> data items without paying attention to the 3/5 bit splitting for
> major types.
> ...
>  *  If two keys have different lengths, the shorter one sorts
      earlier;
>  *  If two keys have the same length, the one with the lower value
      in (byte-wise) lexical order sorts earlier.

1. It is not clear what "bytes of the representation of the key" means: is it
   the CBOR representation, or the binary representation of the object itself?
   Consider the int and uint difference here.
2. It is not clear what "without paying attention to" means: do we include it
   and compare on that? Or do we omit the special prefix byte, (mostly) treating
   the key in its plain binary representation form.

The FIDO 2.0: Client To Authenticator Protocol spec takes the original CBOR
wording and clarifies it according to their understanding.
https://fidoalliance.org/specs/fido-v2.0-rd-20170927/fido-client-to-authenticator-protocol-v2.0-rd-20170927.html#message-encoding

> The keys in every map must be sorted lowest value to highest. Sorting is
> performed on the bytes of the representation of the key data items without
> paying attention to the 3/5 bit splitting for major types. The sorting rules
> are:
>  * If the major types are different, the one with the lower value in numerical
>    order sorts earlier.
>  * If two keys have different lengths, the shorter one sorts earlier;
>  * If two keys have the same length, the one with the lower value in
>    (byte-wise) lexical order sorts earlier.

Some other implementations, such as borc, do a full encode then do a
length-first, byte-wise-second comparison:
https://github.com/dignifiedquire/borc/blob/b6bae8b0bcde7c3976b0f0f0957208095c392a36/src/encoder.js#L358
https://github.com/dignifiedquire/borc/blob/b6bae8b0bcde7c3976b0f0f0957208095c392a36/src/utils.js#L143-L151

This has the benefit of being able to easily handle arbitrary keys, including
complex types (maps and arrays).

We'll opt for the FIDO approach, since it affords some efficies since we don't
need a full encode of each key to determine order and can defer to the types
to determine how to most efficiently order their values (i.e. int and uint
ordering can be done on the numbers, no need for byte-wise, for example).

Recommendation: stick to single key types or you'll get into trouble, and prefer
string keys because it's much simpler that way.
*/

/**
 * @param {TokenOrNestedTokens[]} entries
 * @param {EncodeOptions} options
 */
function sortMapEntries (entries, options) {
  if (options.mapSorter) {
    entries.sort(options.mapSorter)
  }
}

/**
 * @param {(Token|Token[])[]} e1
 * @param {(Token|Token[])[]} e2
 * @returns {number}
 */
function mapSorter (e1, e2) {
  // the key position ([0]) could have a single token or an array
  // almost always it'll be a single token but complex key might get involved
  const keyToken1 = Array.isArray(e1[0]) ? e1[0][0] : e1[0]
  const keyToken2 = Array.isArray(e2[0]) ? e2[0][0] : e2[0]

  // different key types
  if (keyToken1.type !== keyToken2.type) {
    return keyToken1.type.compare(keyToken2.type)
  }

  const major = keyToken1.type.major
  // TODO: handle case where cmp === 0 but there are more keyToken e. complex type)
  const tcmp = cborEncoders[major].compareTokens(keyToken1, keyToken2)
  if (tcmp === 0) {
    // duplicate key or complex type where the first token matched,
    // i.e. a map or array and we're only comparing the opening token
    console.warn('WARNING: complex key types used, CBOR key sorting guarantees are gone')
  }
  return tcmp
}

/**
 * @typedef {Token & { _keyBytes?: Uint8Array }} TokenEx
 *
 * @param {(Token|Token[])[]} e1
 * @param {(Token|Token[])[]} e2
 * @returns {number}
 */
function rfc8949MapSorter (e1, e2) {
  if (e1[0] instanceof Token && e2[0] instanceof Token) {
    const t1 = /** @type {TokenEx} */ (e1[0])
    const t2 = /** @type {TokenEx} */ (e2[0])

    if (!t1._keyBytes) {
      t1._keyBytes = encodeRfc8949(t1.value)
    }

    if (!t2._keyBytes) {
      t2._keyBytes = encodeRfc8949(t2.value)
    }

    return compare(t1._keyBytes, t2._keyBytes)
  }

  throw new Error('rfc8949MapSorter: complex key types are not supported yet')
}

/**
 * @param {any} data
 * @returns {Uint8Array}
 */
function encodeRfc8949 (data) {
  return encodeCustom(data, cborEncoders, rfc8949EncodeOptions)
}

/**
 * @param {ByteWriter} writer
 * @param {TokenOrNestedTokens} tokens
 * @param {TokenTypeEncoder[]} encoders
 * @param {EncodeOptions} options
 */
function tokensToEncoded (writer, tokens, encoders, options) {
  if (Array.isArray(tokens)) {
    for (const token of tokens) {
      tokensToEncoded(writer, token, encoders, options)
    }
  } else {
    encoders[tokens.type.major](writer, tokens, options)
  }
}

// CBOR major type prefixes, cached from Type for hot path performance
const MAJOR_UINT = Type.uint.majorEncoded
const MAJOR_NEGINT = Type.negint.majorEncoded
const MAJOR_BYTES = Type.bytes.majorEncoded
const MAJOR_STRING = Type.string.majorEncoded
const MAJOR_ARRAY = Type.array.majorEncoded

// Simple value bytes (CBOR major type 7 + minor value)
const SIMPLE_FALSE = Type.float.majorEncoded | MINOR_FALSE
const SIMPLE_TRUE = Type.float.majorEncoded | MINOR_TRUE
const SIMPLE_NULL = Type.float.majorEncoded | MINOR_NULL
const SIMPLE_UNDEFINED = Type.float.majorEncoded | MINOR_UNDEFINED

const neg1b = BigInt(-1)
const pos1b = BigInt(1)

/**
 * Check if direct encoding can be used for the given options.
 * Direct encoding bypasses token creation for most values.
 * @param {EncodeOptions} options
 * @returns {boolean}
 */
function canDirectEncode (options) {
  // Cannot use direct encode with addBreakTokens (needs special break token handling).
  // Direct encode checks typeEncoders per-value, falling back to tokens as needed.
  // Maps fall back to token-based encoding for efficient key sorting.
  return options.addBreakTokens !== true
}

/**
 * Direct encode a value to the writer, bypassing token creation for most types.
 * Falls back to token-based encoding for custom type encoders.
 * @param {ByteWriter} writer
 * @param {any} data
 * @param {EncodeOptions} options
 * @param {Reference|undefined} refStack
 */
function directEncode (writer, data, options, refStack) {
  const typ = is(data)

  // Check for custom encoder for THIS specific type
  const customEncoder = options.typeEncoders && options.typeEncoders[typ]
  if (customEncoder) {
    const tokens = customEncoder(data, typ, options, refStack)
    if (tokens != null) {
      // Custom encoder returned tokens, serialize immediately
      tokensToEncoded(writer, tokens, cborEncoders, options)
      return
    }
    // Custom encoder returned null, fall through to default handling
  }

  // Direct encode based on type
  switch (typ) {
    case 'null':
      writer.push([SIMPLE_NULL])
      return

    case 'undefined':
      writer.push([SIMPLE_UNDEFINED])
      return

    case 'boolean':
      writer.push([data ? SIMPLE_TRUE : SIMPLE_FALSE])
      return

    case 'number':
      if (!Number.isInteger(data) || !Number.isSafeInteger(data)) {
        // Float, use token encoder for complex float encoding
        encodeFloat(writer, new Token(Type.float, data), options)
      } else if (data >= 0) {
        encodeUintValue(writer, MAJOR_UINT, data)
      } else {
        // Negative integer
        encodeUintValue(writer, MAJOR_NEGINT, data * -1 - 1)
      }
      return

    case 'bigint':
      if (data >= BigInt(0)) {
        encodeUintValue(writer, MAJOR_UINT, data)
      } else {
        encodeUintValue(writer, MAJOR_NEGINT, data * neg1b - pos1b)
      }
      return

    case 'string': {
      const bytes = fromString(data)
      encodeUintValue(writer, MAJOR_STRING, bytes.length)
      writer.push(bytes)
      return
    }

    case 'Uint8Array':
      encodeUintValue(writer, MAJOR_BYTES, data.length)
      writer.push(data)
      return

    case 'Array':
      if (!data.length) {
        writer.push([MAJOR_ARRAY]) // Empty array: 0x80
        return
      }
      refStack = Ref.createCheck(refStack, data)
      encodeUintValue(writer, MAJOR_ARRAY, data.length)
      for (const elem of data) {
        directEncode(writer, elem, options, refStack)
      }
      return

    case 'Object':
    case 'Map':
      // Maps require key sorting, use token-based encoding for efficiency
      // (pre-encoding all keys for sorting is expensive)
      {
        const tokens = typeEncoders.Object(data, typ, options, refStack)
        tokensToEncoded(writer, tokens, cborEncoders, options)
      }
      return

    default:
    // Fall back to token-based encoding for other types (DataView, TypedArrays, etc.)
    {
      const typeEncoder = typeEncoders[typ]
      if (!typeEncoder) {
        throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`)
      }
      const tokens = typeEncoder(data, typ, options, refStack)
      tokensToEncoded(writer, tokens, cborEncoders, options)
    }
  }
}

/**
 * @param {any} data
 * @param {TokenTypeEncoder[]} encoders
 * @param {EncodeOptions} options
 * @param {Uint8Array} [destination]
 * @returns {Uint8Array}
 */
function encodeCustom (data, encoders, options, destination) {
  // arg ordering is different to encodeInto for backward compatibility
  const hasDest = destination instanceof Uint8Array
  let writeTo = hasDest ? new U8Bl(destination) : defaultWriter

  const tokens = objectToTokens(data, options)
  if (!Array.isArray(tokens) && options.quickEncodeToken) {
    const quickBytes = options.quickEncodeToken(tokens)
    if (quickBytes) {
      if (hasDest) {
        // Copy quick bytes into destination buffer
        writeTo.push(quickBytes)
        return writeTo.toBytes()
      }
      return quickBytes
    }
    const encoder = encoders[tokens.type.major]
    if (encoder.encodedSize) {
      const size = encoder.encodedSize(tokens, options)
      if (!hasDest) {
        writeTo = new Bl(size)
      }
      encoder(writeTo, tokens, options)
      // this would be a problem with encodedSize() functions
      if (writeTo.chunks.length !== 1) {
        throw new Error(`Unexpected error: pre-calculated length for ${tokens} was wrong`)
      }
      return hasDest ? writeTo.toBytes() : asU8A(writeTo.chunks[0])
    }
  }
  writeTo.reset()
  tokensToEncoded(writeTo, tokens, encoders, options)
  return writeTo.toBytes(true)
}

/**
 * @param {any} data
 * @param {EncodeOptions} [options]
 * @returns {Uint8Array}
 */
function encode (data, options) {
  options = Object.assign({}, defaultEncodeOptions, options)

  // Use direct encode path when possible
  if (canDirectEncode(options)) {
    defaultWriter.reset()
    directEncode(defaultWriter, data, options, undefined)
    return defaultWriter.toBytes(true)
  }

  return encodeCustom(data, cborEncoders, options)
}

/**
 * @param {any} data
 * @param {Uint8Array} destination
 * @param {EncodeOptions} [options]
 * @returns {{ written: number }}
 */
function encodeInto (data, destination, options) {
  options = Object.assign({}, defaultEncodeOptions, options)

  // Use direct encode path when possible
  if (canDirectEncode(options)) {
    const writer = new U8Bl(destination)
    directEncode(writer, data, options, undefined)
    return { written: writer.toBytes().length }
  }

  const result = encodeCustom(data, cborEncoders, options, destination)
  return { written: result.length }
}

export { objectToTokens, encode, encodeCustom, encodeInto, Ref }
// This is an unfortunate replacement for @sindresorhus/is that we need to
// re-implement for performance purposes. In particular the is.observable()
// check is expensive, and unnecessary for our purposes. The values returned
// are compatible with @sindresorhus/is, however.

// Types that reach getObjectType() - excludes types with fast-paths above:
// primitives (typeof), Array (isArray), Uint8Array (instanceof), plain Object (constructor)
const objectTypeNames = [
  'Object', // for Object.create(null) and other non-plain objects
  'RegExp',
  'Date',
  'Error',
  'Map',
  'Set',
  'WeakMap',
  'WeakSet',
  'ArrayBuffer',
  'SharedArrayBuffer',
  'DataView',
  'Promise',
  'URL',
  'HTMLElement',
  'Int8Array',
  'Uint8ClampedArray',
  'Int16Array',
  'Uint16Array',
  'Int32Array',
  'Uint32Array',
  'Float32Array',
  'Float64Array',
  'BigInt64Array',
  'BigUint64Array',
  'Tagged'
]

/**
 * @param {any} value
 * @returns {string}
 */
export function is (value) {
  if (value === null) {
    return 'null'
  }
  if (value === undefined) {
    return 'undefined'
  }
  if (value === true || value === false) {
    return 'boolean'
  }
  const typeOf = typeof value
  if (typeOf === 'string' || typeOf === 'number' || typeOf === 'bigint' || typeOf === 'symbol') {
    return typeOf
  }
  if (typeOf === 'function') {
    return 'Function'
  }
  if (Array.isArray(value)) {
    return 'Array'
  }
  // Also catches Node.js Buffer which extends Uint8Array
  if (value instanceof Uint8Array) {
    return 'Uint8Array'
  }
  // Fast path for plain objects (most common case after primitives/arrays/bytes)
  if (value.constructor === Object) {
    return 'Object'
  }
  const objectType = getObjectType(value)
  if (objectType) {
    return objectType
  }
  return 'Object'
}

/**
 * @param {any} value
 * @returns {string|undefined}
 */
function getObjectType (value) {
  const objectTypeName = Object.prototype.toString.call(value).slice(8, -1)
  if (objectTypeNames.includes(objectTypeName)) {
    return objectTypeName
  }
  return undefined
}
import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import * as negint from './1negint.js'
import * as bytes from './2bytes.js'
import * as string from './3string.js'
import * as array from './4array.js'
import * as map from './5map.js'
import * as tag from './6tag.js'
import * as float from './7float.js'
import { decodeErrPrefix } from './common.js'
import { fromArray } from './byte-utils.js'

/**
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 */
function invalidMinor (data, pos, minor) {
  throw new Error(`${decodeErrPrefix} encountered invalid minor (${minor}) for major ${data[pos] >>> 5}`)
}

/**
 * @param {string} msg
 * @returns {()=>any}
 */
function errorer (msg) {
  return () => { throw new Error(`${decodeErrPrefix} ${msg}`) }
}

/** @type {((data:Uint8Array, pos:number, minor:number, options?:DecodeOptions) => any)[]} */
export const jump = []

// unsigned integer, 0x00..0x17 (0..23)
for (let i = 0; i <= 0x17; i++) {
  jump[i] = invalidMinor // uint.decodeUintCompact, handled by quick[]
}
jump[0x18] = uint.decodeUint8 // unsigned integer, one-byte uint8_t follows
jump[0x19] = uint.decodeUint16 // unsigned integer, two-byte uint16_t follows
jump[0x1a] = uint.decodeUint32 // unsigned integer, four-byte uint32_t follows
jump[0x1b] = uint.decodeUint64 // unsigned integer, eight-byte uint64_t follows
jump[0x1c] = invalidMinor
jump[0x1d] = invalidMinor
jump[0x1e] = invalidMinor
jump[0x1f] = invalidMinor
// negative integer, -1-0x00..-1-0x17 (-1..-24)
for (let i = 0x20; i <= 0x37; i++) {
  jump[i] = invalidMinor // negintDecode, handled by quick[]
}
jump[0x38] = negint.decodeNegint8 // negative integer, -1-n one-byte uint8_t for n follows
jump[0x39] = negint.decodeNegint16 // negative integer, -1-n two-byte uint16_t for n follows
jump[0x3a] = negint.decodeNegint32 // negative integer, -1-n four-byte uint32_t for follows
jump[0x3b] = negint.decodeNegint64 // negative integer, -1-n eight-byte uint64_t for follows
jump[0x3c] = invalidMinor
jump[0x3d] = invalidMinor
jump[0x3e] = invalidMinor
jump[0x3f] = invalidMinor
// byte string, 0x00..0x17 bytes follow
for (let i = 0x40; i <= 0x57; i++) {
  jump[i] = bytes.decodeBytesCompact
}
jump[0x58] = bytes.decodeBytes8 // byte string, one-byte uint8_t for n, and then n bytes follow
jump[0x59] = bytes.decodeBytes16 // byte string, two-byte uint16_t for n, and then n bytes follow
jump[0x5a] = bytes.decodeBytes32 // byte string, four-byte uint32_t for n, and then n bytes follow
jump[0x5b] = bytes.decodeBytes64 // byte string, eight-byte uint64_t for n, and then n bytes follow
jump[0x5c] = invalidMinor
jump[0x5d] = invalidMinor
jump[0x5e] = invalidMinor
jump[0x5f] = errorer('indefinite length bytes/strings are not supported') // byte string, byte strings follow, terminated by "break"
// UTF-8 string 0x00..0x17 bytes follow
for (let i = 0x60; i <= 0x77; i++) {
  jump[i] = string.decodeStringCompact
}
jump[0x78] = string.decodeString8 // UTF-8 string, one-byte uint8_t for n, and then n bytes follow
jump[0x79] = string.decodeString16 // UTF-8 string, two-byte uint16_t for n, and then n bytes follow
jump[0x7a] = string.decodeString32 // UTF-8 string, four-byte uint32_t for n, and then n bytes follow
jump[0x7b] = string.decodeString64 // UTF-8 string, eight-byte uint64_t for n, and then n bytes follow
jump[0x7c] = invalidMinor
jump[0x7d] = invalidMinor
jump[0x7e] = invalidMinor
jump[0x7f] = errorer('indefinite length bytes/strings are not supported') // UTF-8 strings follow, terminated by "break"
// array, 0x00..0x17 data items follow
for (let i = 0x80; i <= 0x97; i++) {
  jump[i] = array.decodeArrayCompact
}
jump[0x98] = array.decodeArray8 // array, one-byte uint8_t for n, and then n data items follow
jump[0x99] = array.decodeArray16 // array, two-byte uint16_t for n, and then n data items follow
jump[0x9a] = array.decodeArray32 // array, four-byte uint32_t for n, and then n data items follow
jump[0x9b] = array.decodeArray64 // array, eight-byte uint64_t for n, and then n data items follow
jump[0x9c] = invalidMinor
jump[0x9d] = invalidMinor
jump[0x9e] = invalidMinor
jump[0x9f] = array.decodeArrayIndefinite // array, data items follow, terminated by "break"
// map, 0x00..0x17 pairs of data items follow
for (let i = 0xa0; i <= 0xb7; i++) {
  jump[i] = map.decodeMapCompact
}
jump[0xb8] = map.decodeMap8 // map, one-byte uint8_t for n, and then n pairs of data items follow
jump[0xb9] = map.decodeMap16 // map, two-byte uint16_t for n, and then n pairs of data items follow
jump[0xba] = map.decodeMap32 // map, four-byte uint32_t for n, and then n pairs of data items follow
jump[0xbb] = map.decodeMap64 // map, eight-byte uint64_t for n, and then n pairs of data items follow
jump[0xbc] = invalidMinor
jump[0xbd] = invalidMinor
jump[0xbe] = invalidMinor
jump[0xbf] = map.decodeMapIndefinite // map, pairs of data items follow, terminated by "break"
// tags
for (let i = 0xc0; i <= 0xd7; i++) {
  jump[i] = tag.decodeTagCompact
}
jump[0xd8] = tag.decodeTag8
jump[0xd9] = tag.decodeTag16
jump[0xda] = tag.decodeTag32
jump[0xdb] = tag.decodeTag64
jump[0xdc] = invalidMinor
jump[0xdd] = invalidMinor
jump[0xde] = invalidMinor
jump[0xdf] = invalidMinor
// 0xe0..0xf3 simple values, unsupported
for (let i = 0xe0; i <= 0xf3; i++) {
  jump[i] = errorer('simple values are not supported')
}
jump[0xf4] = invalidMinor // false, handled by quick[]
jump[0xf5] = invalidMinor // true, handled by quick[]
jump[0xf6] = invalidMinor // null, handled by quick[]
jump[0xf7] = float.decodeUndefined // undefined
jump[0xf8] = errorer('simple values are not supported') // simple value, one byte follows, unsupported
jump[0xf9] = float.decodeFloat16 // half-precision float (two-byte IEEE 754)
jump[0xfa] = float.decodeFloat32 // single-precision float (four-byte IEEE 754)
jump[0xfb] = float.decodeFloat64 // double-precision float (eight-byte IEEE 754)
jump[0xfc] = invalidMinor
jump[0xfd] = invalidMinor
jump[0xfe] = invalidMinor
jump[0xff] = float.decodeBreak // "break" stop code

/** @type {Token[]} */
export const quick = []
// ints <24
for (let i = 0; i < 24; i++) {
  quick[i] = new Token(Type.uint, i, 1)
}
// negints >= -24
for (let i = -1; i >= -24; i--) {
  quick[31 - i] = new Token(Type.negint, i, 1)
}
// empty bytes
quick[0x40] = new Token(Type.bytes, new Uint8Array(0), 1)
// empty string
quick[0x60] = new Token(Type.string, '', 1)
// empty list
quick[0x80] = new Token(Type.array, 0, 1)
// empty map
quick[0xa0] = new Token(Type.map, 0, 1)
// false
quick[0xf4] = new Token(Type.false, false, 1)
// true
quick[0xf5] = new Token(Type.true, true, 1)
// null
quick[0xf6] = new Token(Type.null, null, 1)

/**
 * @param {Token} token
 * @returns {Uint8Array|undefined}
 */
export function quickEncodeToken (token) {
  switch (token.type) {
    case Type.false:
      return fromArray([0xf4])
    case Type.true:
      return fromArray([0xf5])
    case Type.null:
      return fromArray([0xf6])
    case Type.bytes:
      if (!token.value.length) {
        return fromArray([0x40])
      }
      return
    case Type.string:
      if (token.value === '') {
        return fromArray([0x60])
      }
      return
    case Type.array:
      if (token.value === 0) {
        return fromArray([0x80])
      }
      // shouldn't be possible if this were called when there was only one token
      return
    case Type.map:
      if (token.value === 0) {
        return fromArray([0xa0])
      }
      // shouldn't be possible if this were called when there was only one token
      return
    case Type.uint:
      if (token.value < 24) {
        return fromArray([Number(token.value)])
      }
      return
    case Type.negint:
      if (token.value >= -24) {
        return fromArray([31 - Number(token.value)])
      }
  }
}
/**
 * @typedef {import('../interface.js').TagDecodeControl} TagDecodeControl
 * @typedef {(decode: TagDecodeControl) => Tagged} TaggedTagDecoder
 */

/**
 * A wrapper class for representing a CBOR tag with an arbitrary nested value.
 *
 * `Tagged` is a symmetric primitive: it can be passed to `encode()` to emit
 * a CBOR tag header followed by the encoded form of `value`, and it can be
 * returned from a tag decoder (via `Tagged.decoder(tag)` or `Tagged.preserve()`)
 * to round-trip a tag through decode without losing the tag number.
 *
 * Use `Tagged` for one-off tag handling where defining a dedicated
 * `typeEncoders` entry and tag decoder pair would be heavyweight, e.g. when
 * wrapping a structure in a single application-specific tag (COSE, dCBOR
 * envelopes, etc.).
 *
 * For systematic mapping of a JS type to a tag (e.g. CID -> tag 42), prefer
 * a dedicated `typeEncoders` entry instead.
 */
export class Tagged {
  /**
   * @param {number} tag - CBOR tag number, a non-negative integer
   * @param {any} value - The value to be tagged; encoded recursively
   */
  constructor (tag, value) {
    if (typeof tag !== 'number' || !Number.isInteger(tag) || tag < 0) {
      throw new TypeError('Tagged: tag must be a non-negative integer')
    }
    this.tag = tag
    this.value = value
  }

  /**
   * Build a tag decoder for use in `decode()`'s `tags` option that returns the
   * decoded content wrapped in a `Tagged` instance, preserving the tag number
   * for the caller to inspect.
   *
   * @param {number} tag - The CBOR tag number this decoder will be registered for
   * @returns {TaggedTagDecoder}
   *
   * @example
   * import { decode, Tagged } from 'cborg'
   * const value = decode(bytes, { tags: { 16: Tagged.decoder(16) } })
   * // value instanceof Tagged; value.tag === 16
   */
  static decoder (tag) {
    return (decode) => new Tagged(tag, decode())
  }

  /**
   * Build a `tags` option for `decode()` that wraps each listed tag number in
   * a `Tagged` instance, preserving those tags through decode without
   * registering a dedicated decoder per tag.
   *
   * @param {...number} tagNumbers - One or more CBOR tag numbers to preserve
   * @returns {{[tagNumber: number]: TaggedTagDecoder}}
   *
   * @example
   * import { decode, Tagged } from 'cborg'
   * const value = decode(bytes, { tags: Tagged.preserve(16, 96) })
   */
  static preserve (...tagNumbers) {
    /** @type {{[tagNumber: number]: TaggedTagDecoder}} */
    const tags = {}
    for (const tag of tagNumbers) {
      tags[tag] = Tagged.decoder(tag)
    }
    return tags
  }
}

// Symbol.toStringTag so the internal `is()` type detection returns 'Tagged'
// for instances, allowing the default Tagged typeEncoder to match.
Object.defineProperty(Tagged.prototype, Symbol.toStringTag, {
  value: 'Tagged'
})
class Type {
  /**
   * @param {number} major
   * @param {string} name
   * @param {boolean} terminal
   */
  constructor (major, name, terminal) {
    this.major = major
    this.majorEncoded = major << 5
    this.name = name
    this.terminal = terminal
  }

  toString () {
    return `Type[${this.major}].${this.name}`
  }

  /**
   * @param {Type} typ
   * @returns {number}
   */
  compare (typ) {
    return this.major < typ.major ? -1 : this.major > typ.major ? 1 : 0
  }

  /**
   * Check equality between two Type instances. Safe to use across different
   * copies of the Type class (e.g., when bundlers duplicate the module).
   * (major, name) uniquely identifies a Type; terminal is implied by these.
   * @param {Type} a
   * @param {Type} b
   * @returns {boolean}
   */
  static equals (a, b) {
    return a === b || (a.major === b.major && a.name === b.name)
  }
}

// convert to static fields when better supported
Type.uint = new Type(0, 'uint', true)
Type.negint = new Type(1, 'negint', true)
Type.bytes = new Type(2, 'bytes', true)
Type.string = new Type(3, 'string', true)
Type.array = new Type(4, 'array', false)
Type.map = new Type(5, 'map', false)
Type.tag = new Type(6, 'tag', false) // terminal?
Type.float = new Type(7, 'float', true)
Type.false = new Type(7, 'false', true)
Type.true = new Type(7, 'true', true)
Type.null = new Type(7, 'null', true)
Type.undefined = new Type(7, 'undefined', true)
Type.break = new Type(7, 'break', true)
// Type.indefiniteLength = new Type(0, 'indefiniteLength', true)

class Token {
  /**
   * @param {Type} type
   * @param {any} [value]
   * @param {number} [encodedLength]
   */
  constructor (type, value, encodedLength) {
    this.type = type
    this.value = value
    this.encodedLength = encodedLength
    /** @type {Uint8Array|undefined} */
    this.encodedBytes = undefined
    /** @type {Uint8Array|undefined} */
    this.byteValue = undefined
  }

  toString () {
    return `Token[${this.type}].${this.value}`
  }
}

export { Type, Token }
{
  "name": "cborg",
  "version": "5.1.6",
  "description": "Fast CBOR with a focus on strictness",
  "main": "cborg.js",
  "type": "module",
  "bin": {
    "cborg": "lib/bin.js"
  },
  "scripts": {
    "lint": "standard *.js lib/*.js test/*.js",
    "build": "npm run build:types",
    "build:types": "tsc --build",
    "prepublishOnly": "npm run build",
    "test:node": "mocha test/test-*.js",
    "test:node-bin": "mocha test/node-test-bin.js",
    "test:browser": "polendina --cleanup test/test-*.js",
    "test": "npm run lint && npm run build && npm run test:node && npm run test:node-bin && npm run test:browser",
    "test:ci": "npm run test"
  },
  "repository": {
    "type": "git",
    "url": "git@github.com:rvagg/cborg.git"
  },
  "keywords": [
    "cbor"
  ],
  "author": "Rod <rod@vagg.org> (http://r.va.gg/)",
  "license": "Apache-2.0",
  "devDependencies": {
    "@semantic-release/changelog": "^6.0.3",
    "@semantic-release/commit-analyzer": "^13.0.1",
    "@semantic-release/git": "^10.0.1",
    "@semantic-release/github": "^12.0.6",
    "@semantic-release/npm": "^13.1.5",
    "@semantic-release/release-notes-generator": "^14.1.0",
    "@types/chai": "^5.2.3",
    "@types/mocha": "^10.0.10",
    "@types/node": "^26.0.1",
    "chai": "^6.2.2",
    "conventional-changelog-conventionalcommits": "^10.0.0",
    "ipld-garbage": "^5.0.0",
    "mocha": "^11.7.5",
    "polendina": "^3.2.20",
    "semantic-release": "^25.0.3",
    "standard": "^17.1.2",
    "typescript": "^6.0.2"
  },
  "exports": {
    ".": {
      "import": "./cborg.js",
      "types": "./types/cborg.d.ts"
    },
    "./length": {
      "import": "./lib/length.js",
      "types": "./types/lib/length.d.ts"
    },
    "./taglib": {
      "import": "./lib/taglib.js",
      "types": "./types/lib/taglib.d.ts"
    },
    "./json": {
      "import": "./lib/json/json.js",
      "types": "./types/lib/json/json.d.ts"
    },
    "./extended": {
      "import": "./lib/extended/extended.js",
      "types": "./types/lib/extended/extended.d.ts"
    },
    "./interface": {
      "types": "./types/interface.d.ts"
    }
  },
  "types": "cborg.d.ts",
  "typesVersions": {
    "*": {
      "json": [
        "types/lib/json/json.d.ts"
      ],
      "length": [
        "types/lib/length.d.ts"
      ],
      "*": [
        "types/*"
      ],
      "types/*": [
        "types/*"
      ]
    }
  },
  "release": {
    "branches": [
      "master"
    ],
    "plugins": [
      [
        "@semantic-release/commit-analyzer",
        {
          "preset": "conventionalcommits",
          "releaseRules": [
            {
              "breaking": true,
              "release": "major"
            },
            {
              "revert": true,
              "release": "patch"
            },
            {
              "type": "feat",
              "release": "minor"
            },
            {
              "type": "fix",
              "release": "patch"
            },
            {
              "type": "chore",
              "release": "patch"
            },
            {
              "type": "docs",
              "release": "patch"
            },
            {
              "type": "test",
              "release": "patch"
            },
            {
              "scope": "no-release",
              "release": false
            }
          ]
        }
      ],
      [
        "@semantic-release/release-notes-generator",
        {
          "preset": "conventionalcommits",
          "presetConfig": {
            "types": [
              {
                "type": "feat",
                "section": "Features"
              },
              {
                "type": "fix",
                "section": "Bug Fixes"
              },
              {
                "type": "chore",
                "section": "Trivial Changes"
              },
              {
                "type": "docs",
                "section": "Trivial Changes"
              },
              {
                "type": "test",
                "section": "Tests"
              }
            ]
          }
        }
      ],
      "@semantic-release/changelog",
      "@semantic-release/npm",
      "@semantic-release/github",
      "@semantic-release/git"
    ]
  }
}
import { coerce } from '../bytes.js';
import basex from '../vendor/base-x.js';
/**
 * Class represents both BaseEncoder and MultibaseEncoder meaning it
 * can be used to encode to multibase or base encode without multibase
 * prefix.
 */
class Encoder {
    name;
    prefix;
    baseEncode;
    constructor(name, prefix, baseEncode) {
        this.name = name;
        this.prefix = prefix;
        this.baseEncode = baseEncode;
    }
    encode(bytes) {
        if (bytes instanceof Uint8Array) {
            return `${this.prefix}${this.baseEncode(bytes)}`;
        }
        else {
            throw Error('Unknown type, must be binary type');
        }
    }
}
/**
 * Class represents both BaseDecoder and MultibaseDecoder so it could be used
 * to decode multibases (with matching prefix) or just base decode strings
 * with corresponding base encoding.
 */
class Decoder {
    name;
    prefix;
    baseDecode;
    prefixCodePoint;
    constructor(name, prefix, baseDecode) {
        this.name = name;
        this.prefix = prefix;
        const prefixCodePoint = prefix.codePointAt(0);
        /* c8 ignore next 3 */
        if (prefixCodePoint === undefined) {
            throw new Error('Invalid prefix character');
        }
        this.prefixCodePoint = prefixCodePoint;
        this.baseDecode = baseDecode;
    }
    decode(text) {
        if (typeof text === 'string') {
            if (text.codePointAt(0) !== this.prefixCodePoint) {
                throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);
            }
            return this.baseDecode(text.slice(this.prefix.length));
        }
        else {
            throw Error('Can only multibase decode strings');
        }
    }
    or(decoder) {
        return or(this, decoder);
    }
}
class ComposedDecoder {
    decoders;
    constructor(decoders) {
        this.decoders = decoders;
    }
    or(decoder) {
        return or(this, decoder);
    }
    decode(input) {
        const prefix = input[0];
        const decoder = this.decoders[prefix];
        if (decoder != null) {
            return decoder.decode(input);
        }
        else {
            throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);
        }
    }
}
export function or(left, right) {
    return new ComposedDecoder({
        ...(left.decoders ?? { [left.prefix]: left }),
        ...(right.decoders ?? { [right.prefix]: right })
    });
}
export class Codec {
    name;
    prefix;
    baseEncode;
    baseDecode;
    encoder;
    decoder;
    constructor(name, prefix, baseEncode, baseDecode) {
        this.name = name;
        this.prefix = prefix;
        this.baseEncode = baseEncode;
        this.baseDecode = baseDecode;
        this.encoder = new Encoder(name, prefix, baseEncode);
        this.decoder = new Decoder(name, prefix, baseDecode);
    }
    encode(input) {
        return this.encoder.encode(input);
    }
    decode(input) {
        return this.decoder.decode(input);
    }
}
export function from({ name, prefix, encode, decode }) {
    return new Codec(name, prefix, encode, decode);
}
export function baseX({ name, prefix, alphabet }) {
    const { encode, decode } = basex(alphabet, name);
    return from({
        prefix,
        name,
        encode,
        decode: (text) => coerce(decode(text))
    });
}
function decode(string, alphabetIdx, bitsPerChar, name) {
    // Count the padding bytes:
    let end = string.length;
    while (string[end - 1] === '=') {
        --end;
    }
    // Allocate the output:
    const out = new Uint8Array((end * bitsPerChar / 8) | 0);
    // Parse the data:
    let bits = 0; // Number of bits currently in the buffer
    let buffer = 0; // Bits waiting to be written out, MSB first
    let written = 0; // Next byte to write
    for (let i = 0; i < end; ++i) {
        // Read one character from the string:
        const value = alphabetIdx[string[i]];
        if (value === undefined) {
            throw new SyntaxError(`Non-${name} character`);
        }
        // Append the bits to the buffer:
        buffer = (buffer << bitsPerChar) | value;
        bits += bitsPerChar;
        // Write out some bits if the buffer has a byte's worth:
        if (bits >= 8) {
            bits -= 8;
            out[written++] = 0xff & (buffer >> bits);
        }
    }
    // Verify that we have received just enough bits:
    if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {
        throw new SyntaxError('Unexpected end of data');
    }
    return out;
}
function encode(data, alphabet, bitsPerChar) {
    const pad = alphabet[alphabet.length - 1] === '=';
    const mask = (1 << bitsPerChar) - 1;
    let out = '';
    let bits = 0; // Number of bits currently in the buffer
    let buffer = 0; // Bits waiting to be written out, MSB first
    for (let i = 0; i < data.length; ++i) {
        // Slurp data into the buffer:
        buffer = (buffer << 8) | data[i];
        bits += 8;
        // Write out as much as we can:
        while (bits > bitsPerChar) {
            bits -= bitsPerChar;
            out += alphabet[mask & (buffer >> bits)];
        }
    }
    // Partial character:
    if (bits !== 0) {
        out += alphabet[mask & (buffer << (bitsPerChar - bits))];
    }
    // Add padding characters until we hit a byte boundary:
    if (pad) {
        while (((out.length * bitsPerChar) & 7) !== 0) {
            out += '=';
        }
    }
    return out;
}
function createAlphabetIdx(alphabet) {
    // Build the character lookup table:
    const alphabetIdx = {};
    for (let i = 0; i < alphabet.length; ++i) {
        alphabetIdx[alphabet[i]] = i;
    }
    return alphabetIdx;
}
/**
 * RFC4648 Factory
 */
export function rfc4648({ name, prefix, bitsPerChar, alphabet }) {
    const alphabetIdx = createAlphabetIdx(alphabet);
    return from({
        prefix,
        name,
        encode(input) {
            return encode(input, alphabet, bitsPerChar);
        },
        decode(input) {
            return decode(input, alphabetIdx, bitsPerChar, name);
        }
    });
}
//# sourceMappingURL=base.js.mapimport { rfc4648 } from './base.js';
export const base32 = rfc4648({
    prefix: 'b',
    name: 'base32',
    alphabet: 'abcdefghijklmnopqrstuvwxyz234567',
    bitsPerChar: 5
});
export const base32upper = rfc4648({
    prefix: 'B',
    name: 'base32upper',
    alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',
    bitsPerChar: 5
});
export const base32pad = rfc4648({
    prefix: 'c',
    name: 'base32pad',
    alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',
    bitsPerChar: 5
});
export const base32padupper = rfc4648({
    prefix: 'C',
    name: 'base32padupper',
    alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',
    bitsPerChar: 5
});
export const base32hex = rfc4648({
    prefix: 'v',
    name: 'base32hex',
    alphabet: '0123456789abcdefghijklmnopqrstuv',
    bitsPerChar: 5
});
export const base32hexupper = rfc4648({
    prefix: 'V',
    name: 'base32hexupper',
    alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',
    bitsPerChar: 5
});
export const base32hexpad = rfc4648({
    prefix: 't',
    name: 'base32hexpad',
    alphabet: '0123456789abcdefghijklmnopqrstuv=',
    bitsPerChar: 5
});
export const base32hexpadupper = rfc4648({
    prefix: 'T',
    name: 'base32hexpadupper',
    alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',
    bitsPerChar: 5
});
export const base32z = rfc4648({
    prefix: 'h',
    name: 'base32z',
    alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',
    bitsPerChar: 5
});
//# sourceMappingURL=base32.js.mapimport { baseX } from './base.js';
export const base36 = baseX({
    prefix: 'k',
    name: 'base36',
    alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'
});
export const base36upper = baseX({
    prefix: 'K',
    name: 'base36upper',
    alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
});
//# sourceMappingURL=base36.js.mapimport { baseX } from './base.js';
export const base58btc = baseX({
    name: 'base58btc',
    prefix: 'z',
    alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
});
export const base58flickr = baseX({
    name: 'base58flickr',
    prefix: 'Z',
    alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'
});
//# sourceMappingURL=base58.js.mapexport const empty = new Uint8Array(0);
export function toHex(d) {
    return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '');
}
export function fromHex(hex) {
    const hexes = hex.match(/../g);
    return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty;
}
export function equals(aa, bb) {
    if (aa === bb) {
        return true;
    }
    if (aa.byteLength !== bb.byteLength) {
        return false;
    }
    for (let ii = 0; ii < aa.byteLength; ii++) {
        if (aa[ii] !== bb[ii]) {
            return false;
        }
    }
    return true;
}
export function coerce(o) {
    if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') {
        return o;
    }
    if (o instanceof ArrayBuffer) {
        return new Uint8Array(o);
    }
    if (ArrayBuffer.isView(o)) {
        return new Uint8Array(o.buffer, o.byteOffset, o.byteLength);
    }
    throw new Error('Unknown type, must be binary type');
}
export function isBinary(o) {
    return o instanceof ArrayBuffer || ArrayBuffer.isView(o);
}
export function fromString(str) {
    return new TextEncoder().encode(str);
}
export function toString(b) {
    return new TextDecoder().decode(b);
}
//# sourceMappingURL=bytes.js.mapimport { base32 } from './bases/base32.js';
import { base36 } from './bases/base36.js';
import { base58btc } from './bases/base58.js';
import { coerce } from './bytes.js';
import * as Digest from './hashes/digest.js';
import * as varint from './varint.js';
// This way TS will also expose all the types from module
export * from './link/interface.js';
export function format(link, base) {
    const { bytes, version } = link;
    switch (version) {
        case 0:
            return toStringV0(bytes, baseCache(link), base ?? base58btc.encoder);
        default:
            return toStringV1(bytes, baseCache(link), (base ?? base32.encoder));
    }
}
export function toJSON(link) {
    return {
        '/': format(link)
    };
}
export function fromJSON(json) {
    return CID.parse(json['/']);
}
const cache = new WeakMap();
function baseCache(cid) {
    const baseCache = cache.get(cid);
    if (baseCache == null) {
        const baseCache = new Map();
        cache.set(cid, baseCache);
        return baseCache;
    }
    return baseCache;
}
export class CID {
    code;
    version;
    multihash;
    bytes;
    '/';
    /**
     * @param version - Version of the CID
     * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
     * @param multihash - (Multi)hash of the of the content.
     */
    constructor(version, code, multihash, bytes) {
        this.code = code;
        this.version = version;
        this.multihash = multihash;
        this.bytes = bytes;
        // flag to serializers that this is a CID and
        // should be treated specially
        this['/'] = bytes;
    }
    /**
     * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`
     * please either use `CID.asCID(cid)` or switch to new signalling mechanism
     *
     * @deprecated
     */
    get asCID() {
        return this;
    }
    // ArrayBufferView
    get byteOffset() {
        return this.bytes.byteOffset;
    }
    // ArrayBufferView
    get byteLength() {
        return this.bytes.byteLength;
    }
    toV0() {
        switch (this.version) {
            case 0: {
                return this;
            }
            case 1: {
                const { code, multihash } = this;
                if (code !== DAG_PB_CODE) {
                    throw new Error('Cannot convert a non dag-pb CID to CIDv0');
                }
                // sha2-256
                if (multihash.code !== SHA_256_CODE) {
                    throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0');
                }
                return (CID.createV0(multihash));
            }
            default: {
                throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);
            }
        }
    }
    toV1() {
        switch (this.version) {
            case 0: {
                const { code, digest } = this.multihash;
                const multihash = Digest.create(code, digest);
                return (CID.createV1(this.code, multihash));
            }
            case 1: {
                return this;
            }
            default: {
                throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);
            }
        }
    }
    equals(other) {
        return CID.equals(this, other);
    }
    static equals(self, other) {
        const unknown = other;
        return (unknown != null &&
            self.code === unknown.code &&
            self.version === unknown.version &&
            Digest.equals(self.multihash, unknown.multihash));
    }
    toString(base) {
        return format(this, base);
    }
    toJSON() {
        return { '/': format(this) };
    }
    link() {
        return this;
    }
    [Symbol.toStringTag] = 'CID';
    // Legacy
    [Symbol.for('nodejs.util.inspect.custom')]() {
        return `CID(${this.toString()})`;
    }
    /**
     * Takes any input `value` and returns a `CID` instance if it was
     * a `CID` otherwise returns `null`. If `value` is instanceof `CID`
     * it will return value back. If `value` is not instance of this CID
     * class, but is compatible CID it will return new instance of this
     * `CID` class. Otherwise returns null.
     *
     * This allows two different incompatible versions of CID library to
     * co-exist and interop as long as binary interface is compatible.
     */
    static asCID(input) {
        if (input == null) {
            return null;
        }
        const value = input;
        if (value instanceof CID) {
            // If value is instance of CID then we're all set.
            return value;
        }
        else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {
            // If value isn't instance of this CID class but `this.asCID === this` or
            // `value['/'] === value.bytes` is true it is CID instance coming from a
            // different implementation (diff version or duplicate). In that case we
            // rebase it to this `CID` implementation so caller is guaranteed to get
            // instance with expected API.
            const { version, code, multihash, bytes } = value;
            return new CID(version, code, multihash, bytes ?? encodeCID(version, code, multihash.bytes));
        }
        else if (value[cidSymbol] === true) {
            // If value is a CID from older implementation that used to be tagged via
            // symbol we still rebase it to the this `CID` implementation by
            // delegating that to a constructor.
            const { version, multihash, code } = value;
            const digest = Digest.decode(multihash);
            return CID.create(version, code, digest);
        }
        else {
            // Otherwise value is not a CID (or an incompatible version of it) in
            // which case we return `null`.
            return null;
        }
    }
    /**
     * @param version - Version of the CID
     * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
     * @param digest - (Multi)hash of the of the content.
     */
    static create(version, code, digest) {
        if (typeof code !== 'number') {
            throw new Error('String codecs are no longer supported');
        }
        if (!(digest.bytes instanceof Uint8Array)) {
            throw new Error('Invalid digest');
        }
        switch (version) {
            case 0: {
                if (code !== DAG_PB_CODE) {
                    throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);
                }
                else {
                    return new CID(version, code, digest, digest.bytes);
                }
            }
            case 1: {
                const bytes = encodeCID(version, code, digest.bytes);
                return new CID(version, code, digest, bytes);
            }
            default: {
                throw new Error('Invalid version');
            }
        }
    }
    /**
     * Simplified version of `create` for CIDv0.
     */
    static createV0(digest) {
        return CID.create(0, DAG_PB_CODE, digest);
    }
    /**
     * Simplified version of `create` for CIDv1.
     *
     * @param code - Content encoding format code.
     * @param digest - Multihash of the content.
     */
    static createV1(code, digest) {
        return CID.create(1, code, digest);
    }
    /**
     * Decoded a CID from its binary representation. The byte array must contain
     * only the CID with no additional bytes.
     *
     * An error will be thrown if the bytes provided do not contain a valid
     * binary representation of a CID.
     */
    static decode(bytes) {
        const [cid, remainder] = CID.decodeFirst(bytes);
        if (remainder.length !== 0) {
            throw new Error('Incorrect length');
        }
        return cid;
    }
    /**
     * Decoded a CID from its binary representation at the beginning of a byte
     * array.
     *
     * Returns an array with the first element containing the CID and the second
     * element containing the remainder of the original byte array. The remainder
     * will be a zero-length byte array if the provided bytes only contained a
     * binary CID representation.
     */
    static decodeFirst(bytes) {
        const specs = CID.inspectBytes(bytes);
        const prefixSize = specs.size - specs.multihashSize;
        const multihashBytes = coerce(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));
        if (multihashBytes.byteLength !== specs.multihashSize) {
            throw new Error('Incorrect length');
        }
        const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);
        const digest = new Digest.Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);
        const cid = specs.version === 0
            ? CID.createV0(digest)
            : CID.createV1(specs.codec, digest);
        return [cid, bytes.subarray(specs.size)];
    }
    /**
     * Inspect the initial bytes of a CID to determine its properties.
     *
     * Involves decoding up to 4 varints. Typically this will require only 4 to 6
     * bytes but for larger multicodec code values and larger multihash digest
     * lengths these varints can be quite large. It is recommended that at least
     * 10 bytes be made available in the `initialBytes` argument for a complete
     * inspection.
     */
    static inspectBytes(initialBytes) {
        let offset = 0;
        const next = () => {
            const [i, length] = varint.decode(initialBytes.subarray(offset));
            offset += length;
            return i;
        };
        let version = next();
        let codec = DAG_PB_CODE;
        if (version === 18) {
            // CIDv0
            version = 0;
            offset = 0;
        }
        else {
            codec = next();
        }
        if (version !== 0 && version !== 1) {
            throw new RangeError(`Invalid CID version ${version}`);
        }
        const prefixSize = offset;
        const multihashCode = next(); // multihash code
        const digestSize = next(); // multihash length
        const size = offset + digestSize;
        const multihashSize = size - prefixSize;
        return { version, codec, multihashCode, digestSize, multihashSize, size };
    }
    /**
     * Takes cid in a string representation and creates an instance. If `base`
     * decoder is not provided will use a default from the configuration. It will
     * throw an error if encoding of the CID is not compatible with supplied (or
     * a default decoder).
     */
    static parse(source, base) {
        const [prefix, bytes] = parseCIDtoBytes(source, base);
        const cid = CID.decode(bytes);
        if (cid.version === 0 && source[0] !== 'Q') {
            throw Error('Version 0 CID string must not include multibase prefix');
        }
        // Cache string representation to avoid computing it on `this.toString()`
        baseCache(cid).set(prefix, source);
        return cid;
    }
}
function parseCIDtoBytes(source, base) {
    switch (source[0]) {
        // CIDv0 is parsed differently
        case 'Q': {
            const decoder = base ?? base58btc;
            return [
                base58btc.prefix,
                decoder.decode(`${base58btc.prefix}${source}`)
            ];
        }
        case base58btc.prefix: {
            const decoder = base ?? base58btc;
            return [base58btc.prefix, decoder.decode(source)];
        }
        case base32.prefix: {
            const decoder = base ?? base32;
            return [base32.prefix, decoder.decode(source)];
        }
        case base36.prefix: {
            const decoder = base ?? base36;
            return [base36.prefix, decoder.decode(source)];
        }
        default: {
            if (base == null) {
                throw Error('To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided');
            }
            return [source[0], base.decode(source)];
        }
    }
}
function toStringV0(bytes, cache, base) {
    const { prefix } = base;
    if (prefix !== base58btc.prefix) {
        throw Error(`Cannot string encode V0 in ${base.name} encoding`);
    }
    const cid = cache.get(prefix);
    if (cid == null) {
        const cid = base.encode(bytes).slice(1);
        cache.set(prefix, cid);
        return cid;
    }
    else {
        return cid;
    }
}
function toStringV1(bytes, cache, base) {
    const { prefix } = base;
    const cid = cache.get(prefix);
    if (cid == null) {
        const cid = base.encode(bytes);
        cache.set(prefix, cid);
        return cid;
    }
    else {
        return cid;
    }
}
const DAG_PB_CODE = 0x70;
const SHA_256_CODE = 0x12;
function encodeCID(version, code, multihash) {
    const codeOffset = varint.encodingLength(version);
    const hashOffset = codeOffset + varint.encodingLength(code);
    const bytes = new Uint8Array(hashOffset + multihash.byteLength);
    varint.encodeTo(version, bytes, 0);
    varint.encodeTo(code, bytes, codeOffset);
    bytes.set(multihash, hashOffset);
    return bytes;
}
const cidSymbol = Symbol.for('@ipld/js-cid/CID');
//# sourceMappingURL=cid.js.mapimport { coerce } from '../bytes.js';
export const name = 'raw';
export const code = 0x55;
export function encode(node) {
    return coerce(node);
}
export function decode(data) {
    return coerce(data);
}
//# sourceMappingURL=raw.js.mapimport { coerce, equals as equalBytes } from '../bytes.js';
import * as varint from '../varint.js';
/**
 * Creates a multihash digest.
 */
export function create(code, digest) {
    const size = digest.byteLength;
    const sizeOffset = varint.encodingLength(code);
    const digestOffset = sizeOffset + varint.encodingLength(size);
    const bytes = new Uint8Array(digestOffset + size);
    varint.encodeTo(code, bytes, 0);
    varint.encodeTo(size, bytes, sizeOffset);
    bytes.set(digest, digestOffset);
    return new Digest(code, size, digest, bytes);
}
/**
 * Turns bytes representation of multihash digest into an instance.
 */
export function decode(multihash) {
    const bytes = coerce(multihash);
    const [code, sizeOffset] = varint.decode(bytes);
    const [size, digestOffset] = varint.decode(bytes.subarray(sizeOffset));
    const digest = bytes.subarray(sizeOffset + digestOffset);
    if (digest.byteLength !== size) {
        throw new Error('Incorrect length');
    }
    return new Digest(code, size, digest, bytes);
}
export function equals(a, b) {
    if (a === b) {
        return true;
    }
    else {
        const data = b;
        return (a.code === data.code &&
            a.size === data.size &&
            data.bytes instanceof Uint8Array &&
            equalBytes(a.bytes, data.bytes));
    }
}
/**
 * Represents a multihash digest which carries information about the
 * hashing algorithm and an actual hash digest.
 */
export class Digest {
    code;
    size;
    digest;
    bytes;
    /**
     * Creates a multihash digest.
     */
    constructor(code, size, digest, bytes) {
        this.code = code;
        this.size = size;
        this.digest = digest;
        this.bytes = bytes;
    }
}
/**
 * Used to check that the passed multihash has the passed code
 */
export function hasCode(digest, code) {
    return digest.code === code;
}
//# sourceMappingURL=digest.js.mapexport {};
//# sourceMappingURL=interface.js.mapimport varint from './vendor/varint.js';
export function decode(data, offset = 0) {
    const code = varint.decode(data, offset);
    return [code, varint.decode.bytes];
}
export function encodeTo(int, target, offset = 0) {
    varint.encode(int, target, offset);
    return target;
}
export function encodingLength(int) {
    return varint.encodingLength(int);
}
//# sourceMappingURL=varint.js.map/* eslint-disable */
// base-x encoding / decoding
// Copyright (c) 2018 base-x contributors
// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)
// Distributed under the MIT software license, see the accompanying
// file LICENSE or http://www.opensource.org/licenses/mit-license.php.
/**
 * @param {string} ALPHABET
 * @param {any} name
 */
function base(ALPHABET, name) {
    if (ALPHABET.length >= 255) {
        throw new TypeError('Alphabet too long');
    }
    var BASE_MAP = new Uint8Array(256);
    for (var j = 0; j < BASE_MAP.length; j++) {
        BASE_MAP[j] = 255;
    }
    for (var i = 0; i < ALPHABET.length; i++) {
        var x = ALPHABET.charAt(i);
        var xc = x.charCodeAt(0);
        if (BASE_MAP[xc] !== 255) {
            throw new TypeError(x + ' is ambiguous');
        }
        BASE_MAP[xc] = i;
    }
    var BASE = ALPHABET.length;
    var LEADER = ALPHABET.charAt(0);
    var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up
    var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up
    /**
     * @param {any[] | Iterable<number>} source
     */
    function encode(source) {
        // @ts-ignore
        if (source instanceof Uint8Array)
            ;
        else if (ArrayBuffer.isView(source)) {
            source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
        }
        else if (Array.isArray(source)) {
            source = Uint8Array.from(source);
        }
        if (!(source instanceof Uint8Array)) {
            throw new TypeError('Expected Uint8Array');
        }
        if (source.length === 0) {
            return '';
        }
        // Skip & count leading zeroes.
        var zeroes = 0;
        var length = 0;
        var pbegin = 0;
        var pend = source.length;
        while (pbegin !== pend && source[pbegin] === 0) {
            pbegin++;
            zeroes++;
        }
        // Allocate enough space in big-endian base58 representation.
        var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;
        var b58 = new Uint8Array(size);
        // Process the bytes.
        while (pbegin !== pend) {
            var carry = source[pbegin];
            // Apply "b58 = b58 * 256 + ch".
            var i = 0;
            for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {
                carry += (256 * b58[it1]) >>> 0;
                b58[it1] = (carry % BASE) >>> 0;
                carry = (carry / BASE) >>> 0;
            }
            if (carry !== 0) {
                throw new Error('Non-zero carry');
            }
            length = i;
            pbegin++;
        }
        // Skip leading zeroes in base58 result.
        var it2 = size - length;
        while (it2 !== size && b58[it2] === 0) {
            it2++;
        }
        // Translate the result into a string.
        var str = LEADER.repeat(zeroes);
        for (; it2 < size; ++it2) {
            str += ALPHABET.charAt(b58[it2]);
        }
        return str;
    }
    /**
     * @param {string | string[]} source
     */
    function decodeUnsafe(source) {
        if (typeof source !== 'string') {
            throw new TypeError('Expected String');
        }
        if (source.length === 0) {
            return new Uint8Array();
        }
        var psz = 0;
        // Skip leading spaces.
        if (source[psz] === ' ') {
            return;
        }
        // Skip and count leading '1's.
        var zeroes = 0;
        var length = 0;
        while (source[psz] === LEADER) {
            zeroes++;
            psz++;
        }
        // Allocate enough space in big-endian base256 representation.
        var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.
        var b256 = new Uint8Array(size);
        // Process the characters.
        while (source[psz]) {
            // Decode character
            var carry = BASE_MAP[source.charCodeAt(psz)];
            // Invalid character
            if (carry === 255) {
                return;
            }
            var i = 0;
            for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {
                carry += (BASE * b256[it3]) >>> 0;
                b256[it3] = (carry % 256) >>> 0;
                carry = (carry / 256) >>> 0;
            }
            if (carry !== 0) {
                throw new Error('Non-zero carry');
            }
            length = i;
            psz++;
        }
        // Skip trailing spaces.
        if (source[psz] === ' ') {
            return;
        }
        // Skip leading zeroes in b256.
        var it4 = size - length;
        while (it4 !== size && b256[it4] === 0) {
            it4++;
        }
        var vch = new Uint8Array(zeroes + (size - it4));
        var j = zeroes;
        while (it4 !== size) {
            vch[j++] = b256[it4++];
        }
        return vch;
    }
    /**
     * @param {string | string[]} string
     */
    function decode(string) {
        var buffer = decodeUnsafe(string);
        if (buffer) {
            return buffer;
        }
        throw new Error(`Non-${name} character`);
    }
    return {
        encode: encode,
        decodeUnsafe: decodeUnsafe,
        decode: decode
    };
}
var src = base;
var _brrp__multiformats_scope_baseX = src;
export default _brrp__multiformats_scope_baseX;
//# sourceMappingURL=base-x.js.map/* eslint-disable */
var encode_1 = encode;
var MSB = 0x80, REST = 0x7F, MSBALL = ~REST, INT = Math.pow(2, 31);
/**
 * @param {number} num
 * @param {number[]} out
 * @param {number} offset
 */
function encode(num, out, offset) {
    out = out || [];
    offset = offset || 0;
    var oldOffset = offset;
    while (num >= INT) {
        out[offset++] = (num & 0xFF) | MSB;
        num /= 128;
    }
    while (num & MSBALL) {
        out[offset++] = (num & 0xFF) | MSB;
        num >>>= 7;
    }
    out[offset] = num | 0;
    // @ts-ignore
    encode.bytes = offset - oldOffset + 1;
    return out;
}
var decode = read;
var MSB$1 = 0x80, REST$1 = 0x7F;
/**
 * @param {string | any[]} buf
 * @param {number} offset
 */
function read(buf, offset) {
    var res = 0, offset = offset || 0, shift = 0, counter = offset, b, l = buf.length;
    do {
        if (counter >= l) {
            // @ts-ignore
            read.bytes = 0;
            throw new RangeError('Could not decode varint');
        }
        b = buf[counter++];
        res += shift < 28
            ? (b & REST$1) << shift
            : (b & REST$1) * Math.pow(2, shift);
        shift += 7;
    } while (b >= MSB$1);
    // @ts-ignore
    read.bytes = counter - offset;
    return res;
}
var N1 = Math.pow(2, 7);
var N2 = Math.pow(2, 14);
var N3 = Math.pow(2, 21);
var N4 = Math.pow(2, 28);
var N5 = Math.pow(2, 35);
var N6 = Math.pow(2, 42);
var N7 = Math.pow(2, 49);
var N8 = Math.pow(2, 56);
var N9 = Math.pow(2, 63);
var length = function (/** @type {number} */ value) {
    return (value < N1 ? 1
        : value < N2 ? 2
            : value < N3 ? 3
                : value < N4 ? 4
                    : value < N5 ? 5
                        : value < N6 ? 6
                            : value < N7 ? 7
                                : value < N8 ? 8
                                    : value < N9 ? 9
                                        : 10);
};
var varint = {
    encode: encode_1,
    decode: decode,
    encodingLength: length
};
var _brrp_varint = varint;
export default _brrp_varint;
//# sourceMappingURL=varint.js.map{
  "name": "multiformats",
  "version": "13.4.2",
  "description": "Interface for multihash, multicodec, multibase and CID",
  "author": "Mikeal Rogers <mikeal.rogers@gmail.com> (https://www.mikealrogers.com/)",
  "license": "Apache-2.0 OR MIT",
  "homepage": "https://github.com/multiformats/js-multiformats#readme",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/multiformats/js-multiformats.git"
  },
  "bugs": {
    "url": "https://github.com/multiformats/js-multiformats/issues"
  },
  "publishConfig": {
    "access": "public",
    "provenance": true
  },
  "keywords": [
    "ipfs",
    "ipld",
    "multiformats"
  ],
  "type": "module",
  "types": "./dist/src/index.d.ts",
  "typesVersions": {
    "*": {
      "*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ],
      "src/*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ]
    }
  },
  "files": [
    "src",
    "dist",
    "!dist/test",
    "!**/*.tsbuildinfo"
  ],
  "exports": {
    ".": {
      "types": "./dist/src/index.d.ts",
      "import": "./dist/src/index.js"
    },
    "./bases/base10": {
      "types": "./dist/src/bases/base10.d.ts",
      "import": "./dist/src/bases/base10.js"
    },
    "./bases/base16": {
      "types": "./dist/src/bases/base16.d.ts",
      "import": "./dist/src/bases/base16.js"
    },
    "./bases/base2": {
      "types": "./dist/src/bases/base2.d.ts",
      "import": "./dist/src/bases/base2.js"
    },
    "./bases/base256emoji": {
      "types": "./dist/src/bases/base256emoji.d.ts",
      "import": "./dist/src/bases/base256emoji.js"
    },
    "./bases/base32": {
      "types": "./dist/src/bases/base32.d.ts",
      "import": "./dist/src/bases/base32.js"
    },
    "./bases/base36": {
      "types": "./dist/src/bases/base36.d.ts",
      "import": "./dist/src/bases/base36.js"
    },
    "./bases/base58": {
      "types": "./dist/src/bases/base58.d.ts",
      "import": "./dist/src/bases/base58.js"
    },
    "./bases/base64": {
      "types": "./dist/src/bases/base64.d.ts",
      "import": "./dist/src/bases/base64.js"
    },
    "./bases/base8": {
      "types": "./dist/src/bases/base8.d.ts",
      "import": "./dist/src/bases/base8.js"
    },
    "./bases/identity": {
      "types": "./dist/src/bases/identity.d.ts",
      "import": "./dist/src/bases/identity.js"
    },
    "./bases/interface": {
      "types": "./dist/src/bases/interface.d.ts",
      "import": "./dist/src/bases/interface.js"
    },
    "./basics": {
      "types": "./dist/src/basics.d.ts",
      "import": "./dist/src/basics.js"
    },
    "./block": {
      "types": "./dist/src/block.d.ts",
      "import": "./dist/src/block.js"
    },
    "./block/interface": {
      "types": "./dist/src/block/interface.d.ts",
      "import": "./dist/src/block/interface.js"
    },
    "./bytes": {
      "types": "./dist/src/bytes.d.ts",
      "import": "./dist/src/bytes.js"
    },
    "./cid": {
      "types": "./dist/src/cid.d.ts",
      "import": "./dist/src/cid.js"
    },
    "./codecs/interface": {
      "types": "./dist/src/codecs/interface.d.ts",
      "import": "./dist/src/codecs/interface.js"
    },
    "./codecs/json": {
      "types": "./dist/src/codecs/json.d.ts",
      "import": "./dist/src/codecs/json.js"
    },
    "./codecs/raw": {
      "types": "./dist/src/codecs/raw.d.ts",
      "import": "./dist/src/codecs/raw.js"
    },
    "./hashes/digest": {
      "types": "./dist/src/hashes/digest.d.ts",
      "import": "./dist/src/hashes/digest.js"
    },
    "./hashes/hasher": {
      "types": "./dist/src/hashes/hasher.d.ts",
      "import": "./dist/src/hashes/hasher.js"
    },
    "./hashes/identity": {
      "types": "./dist/src/hashes/identity.d.ts",
      "import": "./dist/src/hashes/identity.js"
    },
    "./hashes/interface": {
      "types": "./dist/src/hashes/interface.d.ts",
      "import": "./dist/src/hashes/interface.js"
    },
    "./hashes/sha1": {
      "types": "./dist/types/src/hashes/sha1.d.ts",
      "browser": "./dist/src/hashes/sha1-browser.js",
      "import": "./dist/src/hashes/sha1.js"
    },
    "./hashes/sha2": {
      "types": "./dist/src/hashes/sha2.d.ts",
      "browser": "./dist/src/hashes/sha2-browser.js",
      "import": "./dist/src/hashes/sha2.js"
    },
    "./interface": {
      "types": "./dist/src/interface.d.ts",
      "import": "./dist/src/interface.js"
    },
    "./link": {
      "types": "./dist/src/link.d.ts",
      "import": "./dist/src/link.js"
    },
    "./link/interface": {
      "types": "./dist/src/link/interface.d.ts",
      "import": "./dist/src/link/interface.js"
    },
    "./traversal": {
      "types": "./dist/src/traversal.d.ts",
      "import": "./dist/src/traversal.js"
    }
  },
  "eslintConfig": {
    "extends": "ipfs",
    "parserOptions": {
      "project": true,
      "sourceType": "module"
    }
  },
  "release": {
    "branches": [
      "master"
    ],
    "plugins": [
      [
        "@semantic-release/commit-analyzer",
        {
          "preset": "conventionalcommits",
          "releaseRules": [
            {
              "breaking": true,
              "release": "major"
            },
            {
              "revert": true,
              "release": "patch"
            },
            {
              "type": "feat",
              "release": "minor"
            },
            {
              "type": "fix",
              "release": "patch"
            },
            {
              "type": "docs",
              "release": "patch"
            },
            {
              "type": "test",
              "release": "patch"
            },
            {
              "type": "deps",
              "release": "patch"
            },
            {
              "scope": "no-release",
              "release": false
            }
          ]
        }
      ],
      [
        "@semantic-release/release-notes-generator",
        {
          "preset": "conventionalcommits",
          "presetConfig": {
            "types": [
              {
                "type": "feat",
                "section": "Features"
              },
              {
                "type": "fix",
                "section": "Bug Fixes"
              },
              {
                "type": "chore",
                "section": "Trivial Changes"
              },
              {
                "type": "docs",
                "section": "Documentation"
              },
              {
                "type": "deps",
                "section": "Dependencies"
              },
              {
                "type": "test",
                "section": "Tests"
              }
            ]
          }
        }
      ],
      "@semantic-release/changelog",
      "@semantic-release/npm",
      "@semantic-release/github",
      [
        "@semantic-release/git",
        {
          "assets": [
            "CHANGELOG.md",
            "package.json"
          ]
        }
      ]
    ]
  },
  "scripts": {
    "clean": "aegir clean",
    "lint": "aegir lint",
    "build": "aegir build",
    "release": "aegir release",
    "docs": "aegir docs",
    "test": "npm run lint && npm run test:node && npm run test:chrome",
    "test:node": "aegir test -t node --cov",
    "test:chrome": "aegir test -t browser --cov",
    "test:chrome-webworker": "aegir test -t webworker",
    "test:firefox": "aegir test -t browser -- --browser firefox",
    "test:firefox-webworker": "aegir test -t webworker -- --browser firefox",
    "test:electron-main": "aegir test -t electron-main"
  },
  "devDependencies": {
    "@stablelib/sha256": "^2.0.0",
    "@stablelib/sha512": "^2.0.0",
    "@types/node": "^25.0.0",
    "aegir": "^47.0.7",
    "buffer": "^6.0.3",
    "cids": "^1.1.9",
    "crypto-hash": "^4.0.0"
  },
  "aegir": {
    "test": {
      "target": [
        "node",
        "browser"
      ]
    }
  },
  "browser": {
    "./hashes/sha1": "./dist/src/hashes/sha1-browser.js",
    "./dist/src/hashes/sha1.js": "./dist/src/hashes/sha1-browser.js",
    "./hashes/sha2": "./dist/src/hashes/sha2-browser.js",
    "./dist/src/hashes/sha2.js": "./dist/src/hashes/sha2-browser.js"
  }
}
{
  "name": "atproto-repo",
  "version": "0.0.1",
  "description": "Byte-exact atproto repo layer — CAR + DAG-CBOR + CID + MST — over Hypercore-friendly primitives. Verified against real relay-accepted repos.",
  "type": "module",
  "main": "lib/repo.js",
  "scripts": {
    "test": "brittle-node test/*.test.js",
    "postinstall": "node scripts/bare-deps.mjs"
  },
  "dependencies": {
    "@ipld/car": "^5.4.0",
    "@ipld/dag-cbor": "^9.2.1",
    "@noble/curves": "^1.9.7",
    "@noble/hashes": "^1.5.0",
    "multiformats": "^13.3.0"
  },
  "devDependencies": {
    "atproto-identity": "file:../atproto-identity",
    "brittle": "^4.0.2"
  }
}
function isBuffer(value) {
  return Buffer.isBuffer(value) || value instanceof Uint8Array
}

function isEncoding(encoding) {
  return Buffer.isEncoding(encoding)
}

function alloc(size, fill, encoding) {
  return Buffer.alloc(size, fill, encoding)
}

function allocUnsafe(size) {
  return Buffer.allocUnsafe(size)
}

function allocUnsafeSlow(size) {
  return Buffer.allocUnsafeSlow(size)
}

function byteLength(string, encoding) {
  return Buffer.byteLength(string, encoding)
}

function compare(a, b) {
  return Buffer.compare(a, b)
}

function concat(buffers, totalLength) {
  return Buffer.concat(buffers, totalLength)
}

function copy(source, target, targetStart, start, end) {
  return toBuffer(source).copy(target, targetStart, start, end)
}

function equals(a, b) {
  return toBuffer(a).equals(b)
}

function fill(buffer, value, offset, end, encoding) {
  return toBuffer(buffer).fill(value, offset, end, encoding)
}

function from(value, encodingOrOffset, length) {
  return Buffer.from(value, encodingOrOffset, length)
}

function includes(buffer, value, byteOffset, encoding) {
  return toBuffer(buffer).includes(value, byteOffset, encoding)
}

function indexOf(buffer, value, byfeOffset, encoding) {
  return toBuffer(buffer).indexOf(value, byfeOffset, encoding)
}

function lastIndexOf(buffer, value, byteOffset, encoding) {
  return toBuffer(buffer).lastIndexOf(value, byteOffset, encoding)
}

function swap16(buffer) {
  return toBuffer(buffer).swap16()
}

function swap32(buffer) {
  return toBuffer(buffer).swap32()
}

function swap64(buffer) {
  return toBuffer(buffer).swap64()
}

function toBuffer(buffer) {
  if (Buffer.isBuffer(buffer)) return buffer
  return Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

function toString(buffer, encoding, start, end) {
  return toBuffer(buffer).toString(encoding, start, end)
}

function write(buffer, string, offset, length, encoding) {
  return toBuffer(buffer).write(string, offset, length, encoding)
}

function readDoubleBE(buffer, offset) {
  return toBuffer(buffer).readDoubleBE(offset)
}

function readDoubleLE(buffer, offset) {
  return toBuffer(buffer).readDoubleLE(offset)
}

function readFloatBE(buffer, offset) {
  return toBuffer(buffer).readFloatBE(offset)
}

function readFloatLE(buffer, offset) {
  return toBuffer(buffer).readFloatLE(offset)
}

function readInt32BE(buffer, offset) {
  return toBuffer(buffer).readInt32BE(offset)
}

function readInt32LE(buffer, offset) {
  return toBuffer(buffer).readInt32LE(offset)
}

function readUInt32BE(buffer, offset) {
  return toBuffer(buffer).readUInt32BE(offset)
}

function readUInt32LE(buffer, offset) {
  return toBuffer(buffer).readUInt32LE(offset)
}

function writeDoubleBE(buffer, value, offset) {
  return toBuffer(buffer).writeDoubleBE(value, offset)
}

function writeDoubleLE(buffer, value, offset) {
  return toBuffer(buffer).writeDoubleLE(value, offset)
}

function writeFloatBE(buffer, value, offset) {
  return toBuffer(buffer).writeFloatBE(value, offset)
}

function writeFloatLE(buffer, value, offset) {
  return toBuffer(buffer).writeFloatLE(value, offset)
}

function writeInt32BE(buffer, value, offset) {
  return toBuffer(buffer).writeInt32BE(value, offset)
}

function writeInt32LE(buffer, value, offset) {
  return toBuffer(buffer).writeInt32LE(value, offset)
}

function writeUInt32BE(buffer, value, offset) {
  return toBuffer(buffer).writeUInt32BE(value, offset)
}

function writeUInt32LE(buffer, value, offset) {
  return toBuffer(buffer).writeUInt32LE(value, offset)
}

module.exports = {
  isBuffer,
  isEncoding,
  alloc,
  allocUnsafe,
  allocUnsafeSlow,
  byteLength,
  compare,
  concat,
  copy,
  equals,
  fill,
  from,
  includes,
  indexOf,
  lastIndexOf,
  swap16,
  swap32,
  swap64,
  toBuffer,
  toString,
  write,
  readDoubleBE,
  readDoubleLE,
  readFloatBE,
  readFloatLE,
  readInt32BE,
  readInt32LE,
  readUInt32BE,
  readUInt32LE,
  writeDoubleBE,
  writeDoubleLE,
  writeFloatBE,
  writeFloatLE,
  writeInt32BE,
  writeInt32LE,
  writeUInt32BE,
  writeUInt32LE
}
{
  "name": "b4a",
  "version": "1.8.1",
  "description": "Bridging the gap between buffers and typed arrays",
  "exports": {
    "./package": "./package.json",
    ".": {
      "react-native": "./react-native.js",
      "browser": "./browser.js",
      "default": "./index.js"
    }
  },
  "files": [
    "browser.js",
    "index.js",
    "react-native.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:bare && npm run test:node",
    "test:bare": "brittle-bare --coverage test.mjs",
    "test:node": "brittle-node --coverage test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/b4a.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/b4a/issues"
  },
  "homepage": "https://github.com/holepunchto/b4a#readme",
  "devDependencies": {
    "brittle": "^3.5.2",
    "lunte": "^1.7.0",
    "nanobench": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "react-native-b4a": "*"
  },
  "peerDependenciesMeta": {
    "react-native-b4a": {
      "optional": true
    }
  }
}
const ESC = '\x1b'
const CSI = ESC + '['
const SGR = (n) => CSI + n + 'm'

exports.constants = {
  ESC,
  CSI,
  SGR
}

// https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_(Control_Sequence_Introducer)_sequences

exports.cursorHide = CSI + '?25l'
exports.cursorShow = CSI + '?25h'

exports.cursorUp = function cursorUp(n = 1) {
  return CSI + n + 'A'
}

exports.cursorDown = function cursorDown(n = 1) {
  return CSI + n + 'B'
}

exports.cursorForward = function cursorForward(n = 1) {
  return CSI + n + 'C'
}

exports.cursorBack = function cursorBack(n = 1) {
  return CSI + n + 'D'
}

exports.cursorNextLine = function cursorNextLine(n = 1) {
  return CSI + n + 'E'
}

exports.cursorPreviousLine = function cursorPreviousLine(n = 1) {
  return CSI + n + 'F'
}

exports.cursorPosition = function cursorPosition(column, row = 0) {
  if (row === 0) return CSI + (column + 1) + 'G'

  return CSI + (row + 1) + ';' + (column + 1) + 'H'
}

exports.eraseDisplayEnd = CSI + 'J'
exports.eraseDisplayStart = CSI + '1J'
exports.eraseDisplay = CSI + '2J'
exports.eraseLineEnd = CSI + 'K'
exports.eraseLineStart = CSI + '1K'
exports.eraseLine = CSI + '2K'

exports.scrollUp = function scrollUp(n = 1) {
  return CSI + n + 'S'
}

exports.scrollDown = function scrollDown(n = 1) {
  return CSI + n + 'T'
}

// https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_(Select_Graphic_Rendition)_parameters

exports.modifierReset = SGR(0)
exports.modifierBold = SGR(1)
exports.modifierDim = SGR(2)
exports.modifierItalic = SGR(3)
exports.modifierUnderline = SGR(4)
exports.modifierNormal = SGR(22)
exports.modifierNotItalic = SGR(23)
exports.modifierNotUnderline = SGR(24)

// https://en.wikipedia.org/wiki/ANSI_escape_code#Colors

exports.colorBlack = SGR(30)
exports.colorRed = SGR(31)
exports.colorGreen = SGR(32)
exports.colorYellow = SGR(33)
exports.colorBlue = SGR(34)
exports.colorMagenta = SGR(35)
exports.colorCyan = SGR(36)
exports.colorWhite = SGR(37)
exports.colorDefault = SGR(39)
exports.colorBrightBlack = SGR(90)
exports.colorBrightRed = SGR(91)
exports.colorBrightGreen = SGR(92)
exports.colorBrightYellow = SGR(93)
exports.colorBrightBlue = SGR(94)
exports.colorBrightMagenta = SGR(95)
exports.colorBrightCyan = SGR(96)
exports.colorBrightWhite = SGR(97)
{
  "name": "bare-ansi-escapes",
  "version": "2.2.3",
  "description": "Parse and produce ANSI escape sequences",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./key-decoder": {
      "types": "./key-decoder.d.ts",
      "default": "./key-decoder.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "key-decoder.js",
    "key-decoder.d.ts"
  ],
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-ansi-escapes.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-ansi-escapes/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-ansi-escapes#readme",
  "dependencies": {
    "bare-stream": "^2.6.5"
  },
  "devDependencies": {
    "bare-buffer": "^3.0.2",
    "brittle": "^3.3.2",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  },
  "peerDependencies": {
    "bare-buffer": "*"
  },
  "peerDependenciesMeta": {
    "bare-buffer": {
      "optional": true
    }
  }
}
const inspect = require('bare-inspect')

class AssertionError extends Error {
  constructor(opts = {}) {
    let { message = null, actual, expected, operator } = opts

    if (message === null) {
      message = `${inspect(actual)} ${operator} ${inspect(expected)}`
    }

    super(message)

    this.actual = actual
    this.expected = expected
    this.operator = operator
  }

  get name() {
    return 'AssertionError'
  }

  get code() {
    'ASSERTION'
  }
}

function assertFail(opts, fn) {
  if (opts.message instanceof Error) throw opts.message

  const err = new AssertionError(opts)

  if (Error.captureStackTrace) Error.captureStackTrace(err, fn)

  throw err
}

module.exports = exports = function assert(actual, message) {
  if (actual) return

  assertFail({ message, actual, expected: true, operator: '==' }, assert)
}

exports.AssertionError = AssertionError

exports.fail = function fail(message) {
  if (message === undefined) message = 'Failed'

  assertFail({ message, operator: 'fail' }, fail)
}

exports.ok = function ok(actual, message) {
  if (actual) return

  assertFail({ message, actual, expected: true, operator: '==' }, ok)
}

exports.notOk = function ok(actual, message) {
  if (!actual) return

  assertFail({ message, actual, expected: false, operator: '==' }, ok)
}

exports.equal = function equal(actual, expected, message) {
  if (actual == expected || (actual !== actual && expected !== expected)) {
    return
  }

  assertFail({ message, actual, expected, operator: '==' }, equal)
}

exports.notEqual = function notEqual(actual, expected, message) {
  if (actual != expected && (actual === actual || expected === expected)) {
    return
  }

  assertFail({ message, actual, expected, operator: '!=' }, notEqual)
}

exports.strictEqual = function strictEqual(actual, expected, message) {
  if (Object.is(actual, expected)) return

  assertFail(
    { message, actual, expected, operator: 'strictEqual' },
    strictEqual
  )
}

exports.notStrictEqual = function notStrictEqual(actual, expected, message) {
  if (!Object.is(actual, expected)) return

  assertFail(
    { message, actual, expected, operator: 'notStrictEqual' },
    notStrictEqual
  )
}
{
  "name": "bare-assert",
  "version": "1.2.0",
  "description": "Assertion library for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts"
  ],
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-assert.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-assert/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-assert#readme",
  "dependencies": {
    "bare-inspect": "^3.1.2"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  }
}
const errors = require('./lib/errors')

class EventListener {
  constructor() {
    this.list = []
    this.count = 0
  }

  append(ctx, name, fn, once) {
    this.count++
    ctx.emit('newListener', name, fn) // Emit BEFORE adding
    this.list.push([fn, once])
  }

  prepend(ctx, name, fn, once) {
    this.count++
    ctx.emit('newListener', name, fn) // Emit BEFORE adding
    this.list.unshift([fn, once])
  }

  remove(ctx, name, fn) {
    for (let i = 0, n = this.list.length; i < n; i++) {
      const l = this.list[i]

      if (l[0] === fn) {
        this.list.splice(i, 1)

        if (this.count === 1) delete ctx._events[name]

        ctx.emit('removeListener', name, fn) // Emit AFTER removing

        this.count--
        return
      }
    }
  }

  removeAll(ctx, name) {
    const list = [...this.list]
    this.list = []

    if (this.count === list.length) delete ctx._events[name]

    for (let i = list.length - 1; i >= 0; i--) {
      ctx.emit('removeListener', name, list[i][0]) // Emit AFTER removing
    }

    this.count -= list.length
  }

  emit(ctx, name, ...args) {
    const list = [...this.list]

    for (let i = 0, n = list.length; i < n; i++) {
      const l = list[i]

      if (l[1] === true) this.remove(ctx, name, l[0])

      Reflect.apply(l[0], ctx, args)
    }

    return list.length > 0
  }
}

function appendListener(ctx, name, fn, once) {
  if (ctx._events === undefined) ctx._events = Object.create(null)
  const e = ctx._events[name] || (ctx._events[name] = new EventListener())
  e.append(ctx, name, fn, once)
  return ctx
}

function prependListener(ctx, name, fn, once) {
  if (ctx._events === undefined) ctx._events = Object.create(null)
  const e = ctx._events[name] || (ctx._events[name] = new EventListener())
  e.prepend(ctx, name, fn, once)
  return ctx
}

function removeListener(ctx, name, fn) {
  if (ctx._events === undefined) return ctx
  const e = ctx._events[name]
  if (e !== undefined) e.remove(ctx, name, fn)
  return ctx
}

function throwUnhandledError(...args) {
  let err

  if (args.length > 0) err = args[0]

  if (err instanceof Error === false) err = errors.UNHANDLED_ERROR(err)

  if (Error.captureStackTrace) {
    Error.captureStackTrace(err, exports.prototype.emit)
  }

  queueMicrotask(() => {
    throw err
  })
}

module.exports = exports = class EventEmitter {
  constructor() {
    this._events = Object.create(null)
  }

  addListener(name, fn) {
    return appendListener(this, name, fn, false)
  }

  addOnceListener(name, fn) {
    return appendListener(this, name, fn, true)
  }

  prependListener(name, fn) {
    return prependListener(this, name, fn, false)
  }

  prependOnceListener(name, fn) {
    return prependListener(this, name, fn, true)
  }

  removeListener(name, fn) {
    return removeListener(this, name, fn)
  }

  on(name, fn) {
    return appendListener(this, name, fn, false)
  }

  once(name, fn) {
    return appendListener(this, name, fn, true)
  }

  off(name, fn) {
    return removeListener(this, name, fn)
  }

  emit(name, ...args) {
    if (name === 'error' && this._events !== undefined && this._events.error === undefined) {
      throwUnhandledError(...args)
    }

    if (this._events === undefined) return false
    const e = this._events[name]
    return e === undefined ? false : e.emit(this, name, ...args)
  }

  listeners(name) {
    if (this._events === undefined) return []
    const e = this._events[name]
    return e === undefined ? [] : [...e.list]
  }

  rawListeners(name) {
    if (this._events === undefined) return []
    const e = this._events[name]
    return e === undefined ? [] : e.list.map((l) => l[0])
  }

  eventNames() {
    if (this._events === undefined) return []
    return Reflect.ownKeys(this._events)
  }

  listenerCount(name) {
    if (this._events === undefined) return 0
    const e = this._events[name]
    return e === undefined ? 0 : e.list.length
  }

  getMaxListeners() {
    return EventEmitter.defaultMaxListeners
  }

  setMaxListeners(n) {}

  removeAllListeners(name) {
    if (arguments.length === 0) {
      for (const key of Reflect.ownKeys(this._events)) {
        if (key === 'removeListener') continue
        this.removeAllListeners(key)
      }
      this.removeAllListeners('removeListener')
    } else {
      const e = this._events[name]
      if (e !== undefined) e.removeAll(this, name)
    }
    return this
  }
}

exports.EventEmitter = exports

exports.errors = errors

exports.defaultMaxListeners = 10

exports.on = function on(emitter, name, opts = {}) {
  const { signal } = opts

  if (signal && signal.aborted) {
    throw errors.OPERATION_ABORTED(signal.reason)
  }

  let error = null
  let done = false

  const events = []
  const promises = []

  if (name !== 'error') emitter.on('error', onerror)

  if (signal) signal.addEventListener('abort', onabort)

  emitter.on(name, onevent)

  return {
    next() {
      if (events.length) {
        return Promise.resolve({ value: events.shift(), done: false })
      }

      if (error) {
        const err = error

        error = null

        return Promise.reject(err)
      }

      if (done) return onclose()

      return new Promise((resolve, reject) => promises.push({ resolve, reject }))
    },

    return() {
      return onclose()
    },

    throw(err) {
      return onerror(err)
    },

    [Symbol.asyncIterator]() {
      return this
    }
  }

  function onevent(...args) {
    if (promises.length) {
      promises.shift().resolve({ value: args, done: false })
    } else {
      events.push(args)
    }
  }

  function onerror(err) {
    emitter.off(name, onevent).off('error', onerror)

    if (promises.length) {
      promises.shift().reject(err)
    } else {
      error = err
    }

    return Promise.resolve({ done: true })
  }

  function onabort() {
    signal.removeEventListener('abort', onabort)

    onerror(errors.OPERATION_ABORTED(signal.reason))
  }

  function onclose() {
    emitter.off(name, onevent)

    if (name !== 'error') emitter.off('error', onerror)

    if (signal) signal.removeEventListener('abort', onabort)

    done = true

    if (promises.length) promises.shift().resolve({ done: true })

    return Promise.resolve({ done: true })
  }
}

exports.once = function once(emitter, name, opts = {}) {
  const { signal } = opts

  if (signal && signal.aborted) {
    return Promise.reject(errors.OPERATION_ABORTED(signal.reason))
  }

  return new Promise((resolve, reject) => {
    if (name !== 'error') emitter.on('error', onerror)

    if (signal) signal.addEventListener('abort', onabort)

    emitter.once(name, onevent)

    function onevent(...args) {
      if (name !== 'error') emitter.off('error', onerror)

      if (signal) signal.removeEventListener('abort', onabort)

      resolve(args)
    }

    function onerror(err) {
      emitter.off(name, onevent)

      if (name !== 'error') emitter.off('error', onerror)

      reject(err)
    }

    function onabort() {
      signal.removeEventListener('abort', onabort)

      onerror(errors.OPERATION_ABORTED(signal.reason))
    }
  })
}

exports.forward = function forward(from, to, names, opts = {}) {
  if (typeof names === 'string') names = [names]

  const { emit = to.emit.bind(to) } = opts

  const listeners = names.map(
    (name) =>
      function onevent(...args) {
        emit(name, ...args)
      }
  )

  to.on('newListener', (name) => {
    const i = names.indexOf(name)

    if (i !== -1 && to.listenerCount(name) === 0) {
      from.on(name, listeners[i])
    }
  }).on('removeListener', (name) => {
    const i = names.indexOf(name)

    if (i !== -1 && to.listenerCount(name) === 0) {
      from.off(name, listeners[i])
    }
  })
}

exports.listenerCount = function listenerCount(emitter, name) {
  return emitter.listenerCount(name)
}

exports.getMaxListeners = function getMaxListeners(emitter) {
  if (typeof emitter.getMaxListeners === 'function') {
    return emitter.getMaxListeners()
  }

  return exports.defaultMaxListeners
}

exports.setMaxListeners = function setMaxListeners(n, ...emitters) {
  if (emitters.length === 0) exports.defaultMaxListeners = n
  else {
    for (const emitter of emitters) {
      if (typeof emitter.setMaxListeners === 'function') {
        emitter.setMaxListeners(n)
      }
    }
  }
}
module.exports = class EventEmitterError extends Error {
  constructor(msg, code, fn = EventEmitterError, opts) {
    super(`${code}: ${msg}`, opts)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'EventEmitterError'
  }

  static OPERATION_ABORTED(cause, msg = 'Operation aborted') {
    return new EventEmitterError(msg, 'OPERATION_ABORTED', EventEmitterError.OPERATION_ABORTED, {
      cause
    })
  }

  static UNHANDLED_ERROR(cause, msg = 'Unhandled error') {
    return new EventEmitterError(msg, 'UNHANDLED_ERROR', EventEmitterError.UNHANDLED_ERROR, {
      cause
    })
  }
}
{
  "name": "bare-events",
  "version": "2.9.1",
  "description": "Event emitters for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    },
    "./web": {
      "types": "./web.d.ts",
      "default": "./web.js"
    },
    "./errors": "./lib/errors.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "global.js",
    "global.d.ts",
    "web.js",
    "web.d.ts",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:bare && npm run test:node",
    "test:bare": "brittle-bare --coverage test.js",
    "test:node": "brittle-node --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-events.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-events/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-events#readme",
  "devDependencies": {
    "bare-abort-controller": "^1.0.0",
    "brittle": "^3.3.2",
    "lunte": "^1.8.0",
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^2.0.0",
    "uncaughts": "^1.1.1"
  },
  "peerDependencies": {
    "bare-abort-controller": "*"
  },
  "peerDependenciesMeta": {
    "bare-abort-controller": {
      "optional": true
    }
  }
}
module.exports = require.addon()
const FIFO = require('fast-fifo')
const EventEmitter = require('bare-events')
const path = require('bare-path')
const { isURL, fileURLToPath } = require('bare-url')
const { Readable, Writable } = require('bare-stream')
const binding = require('./binding')
const constants = require('./lib/constants')
const FileError = require('./lib/errors')

const isWindows = Bare.platform === 'win32'

exports.constants = constants

class FileRequest {
  static borrow() {
    if (this._free.length > 0) return this._free.pop()
    return new FileRequest()
  }

  static return(req) {
    if (this._free.length < 32) this._free.push(req.reset())
    else req.destroy()
  }

  constructor() {
    this._reset()
    this._handle = binding.requestInit(this, this._onresult)
  }

  get handle() {
    return this._handle
  }

  retain(value) {
    this._retain = value // Tie the lifetime of `value` to the lifetime of `this`
  }

  reset() {
    if (this._handle === null) return this

    binding.requestReset(this._handle)

    this._reset()

    return this
  }

  destroy() {
    if (this._handle === null) return this

    binding.requestDestroy(this._handle)

    this._reset()
    this._handle = null

    return this
  }

  then(resolve, reject) {
    return this._promise.then(resolve, reject)
  }

  return() {
    if (this._handle === null) return this

    FileRequest.return(this)

    return this
  }

  _reset() {
    this._promise = new Promise((resolve, reject) => {
      this._resolve = resolve
      this._reject = reject
    })
    this._retain = null
  }

  _onresult(err, status) {
    if (err) this._reject(err)
    else this._resolve(status)
  }
}

FileRequest._free = []

function ok(result, cb) {
  if (typeof result === 'function') {
    cb = result
    result = undefined
  }

  if (cb) cb(null, result)
  else return result
}

function fail(err, cb) {
  if (cb) cb(err)
  else throw err
}

function done(err, result, cb) {
  if (typeof result === 'function') {
    cb = result
    result = undefined
  }

  if (err) fail(err, cb)
  else return ok(result, cb)
}

async function open(filepath, flags = 'r', mode = 0o666, cb) {
  if (typeof flags === 'function') {
    cb = flags
    flags = 'r'
    mode = 0o666
  } else if (typeof mode === 'function') {
    cb = mode
    mode = 0o666
  }

  if (typeof flags === 'string') flags = toFlags(flags)
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let fd
  let err = null
  try {
    binding.open(req.handle, filepath, flags, mode)

    fd = await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'open',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, fd, cb)
}

function openSync(filepath, flags = 'r', mode = 0o666) {
  if (typeof flags === 'string') flags = toFlags(flags)
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    return binding.openSync(req.handle, filepath, flags, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'open',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function close(fd, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.close(req.handle, fd)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'close', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function closeSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.closeSync(req.handle, fd)
  } catch (e) {
    throw new FileError(e.message, { operation: 'close', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function access(filepath, mode = constants.F_OK, cb) {
  if (typeof mode === 'function') {
    cb = mode
    mode = constants.F_OK
  }

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.access(req.handle, filepath, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'access',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function accessSync(filepath, mode = constants.F_OK) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.accessSync(req.handle, filepath, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'access',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function exists(filepath, cb) {
  let ok = true
  try {
    await access(filepath)
  } catch {
    ok = false
  }

  return done(null, ok, cb)
}

function existsSync(filepath) {
  try {
    accessSync(filepath)
  } catch {
    return false
  }

  return true
}

async function read(fd, buffer, offset = 0, len = buffer.byteLength - offset, pos = -1, cb) {
  if (typeof offset === 'function') {
    cb = offset
    offset = 0
    len = buffer.byteLength
    pos = -1
  } else if (typeof len === 'function') {
    cb = len
    len = buffer.byteLength - offset
    pos = -1
  } else if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.read(req.handle, fd, buffer, offset, len, pos)

    req.retain(buffer)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'read', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function readSync(fd, buffer, offset = 0, len = buffer.byteLength - offset, pos = -1) {
  const req = FileRequest.borrow()

  try {
    return binding.readSync(req.handle, fd, buffer, offset, len, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'read', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function readv(fd, buffers, pos = -1, cb) {
  if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.readv(req.handle, fd, buffers, pos)

    req.retain(buffers)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'readv', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function readvSync(fd, buffers, pos = -1) {
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  try {
    return binding.readvSync(req.handle, fd, buffers, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'readv', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function write(fd, data, offset, len, pos = -1, cb) {
  if (typeof data === 'string') {
    let encoding = len
    cb = pos
    pos = offset

    if (typeof pos === 'function') {
      cb = pos
      pos = -1
      encoding = 'utf8'
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = 'utf8'
    }

    if (typeof pos === 'string') {
      encoding = pos
      pos = -1
    }

    data = Buffer.from(data, encoding)
    offset = 0
    len = data.byteLength
  } else if (typeof offset === 'function') {
    cb = offset
    offset = 0
    len = data.byteLength
    pos = -1
  } else if (typeof len === 'function') {
    cb = len
    len = data.byteLength - offset
    pos = -1
  } else if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof offset !== 'number') offset = 0
  if (typeof len !== 'number') len = data.byteLength - offset
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.write(req.handle, fd, data, offset, len, pos)

    req.retain(data)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'write', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function writeSync(fd, data, offset, len, pos = -1) {
  if (typeof data === 'string') {
    let encoding = len
    pos = offset

    if (typeof pos === 'string') {
      encoding = pos
      pos = -1
    }

    data = Buffer.from(data, encoding)
    offset = 0
    len = data.byteLength
  }

  if (typeof offset !== 'number') offset = 0
  if (typeof len !== 'number') len = data.byteLength - offset
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  try {
    return binding.writeSync(req.handle, fd, data, offset, len, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'write', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function writev(fd, buffers, pos = -1, cb) {
  if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.writev(req.handle, fd, buffers, pos)

    req.retain(buffers)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'writev', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function writevSync(fd, buffers, pos = -1) {
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  try {
    return binding.writevSync(req.handle, fd, buffers, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'writev', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function stat(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.stat(req.handle, filepath)

    await req

    st = new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'stat', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function statSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.statSync(req.handle, filepath)

    return new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'stat', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function lstat(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.lstat(req.handle, filepath)

    await req

    st = new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'lstat', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function lstatSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.lstatSync(req.handle, filepath)

    return new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'lstat', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function fstat(fd, cb) {
  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.fstat(req.handle, fd)

    await req

    st = new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'fstat', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function fstatSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.fstatSync(req.handle, fd)

    return new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'fstat', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function statfs(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.statfs(req.handle, filepath)

    await req

    st = new StatFs(...binding.requestResultStatfs(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'statfs', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function statfsSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.statfsSync(req.handle, filepath)

    return new StatFs(...binding.requestResultStatfs(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'statfs', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function ftruncate(fd, len = 0, cb) {
  if (typeof len === 'function') {
    cb = len
    len = 0
  }

  if (typeof len !== 'number') len = 0

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.ftruncate(req.handle, fd, len)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'ftruncate', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function ftruncateSync(fd, len = 0) {
  if (typeof len !== 'number') len = 0

  const req = FileRequest.borrow()

  try {
    binding.ftruncateSync(req.handle, fd, len)
  } catch (e) {
    throw new FileError(e.message, { operation: 'ftruncate', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function truncate(filepath, len, cb) {
  let fd = -1
  let err

  try {
    fd = await open(filepath, 'r+')

    await ftruncate(fd, len)
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) await close(fd)
  }

  return done(err, cb)
}

function truncateSync(filepath, len) {
  let fd = -1
  let err

  try {
    fd = openSync(filepath, 'r+')

    ftruncateSync(fd, len)
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) closeSync(fd)
  }
}

async function chmod(filepath, mode, cb) {
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.chmod(req.handle, filepath, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'chmod',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function chmodSync(filepath, mode) {
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.chmodSync(req.handle, filepath, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'chmod',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function fchmod(fd, mode, cb) {
  if (typeof mode === 'string') mode = toMode(mode)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fchmod(req.handle, fd, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fchmod', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fchmodSync(fd, mode) {
  if (typeof mode === 'string') mode = toMode(mode)

  const req = FileRequest.borrow()

  try {
    binding.fchmodSync(req.handle, fd, mode)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fchmod', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function chown(filepath, uid, gid, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.chown(req.handle, filepath, uid, gid)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'chown', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function chownSync(filepath, uid, gid) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.chownSync(req.handle, filepath, uid, gid)
  } catch (e) {
    throw new FileError(e.message, { operation: 'chownSync', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function lchown(filepath, uid, gid, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.lchown(req.handle, filepath, uid, gid)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'lchown', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function lchownSync(filepath, uid, gid) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.lchownSync(req.handle, filepath, uid, gid)
  } catch (e) {
    throw new FileError(e.message, { operation: 'lchownSync', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function fchown(fd, uid, gid, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fchown(req.handle, fd, uid, gid)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fchown', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fchownSync(fd, uid, gid) {
  const req = FileRequest.borrow()

  try {
    binding.fchownSync(req.handle, fd, uid, gid)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fchownSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function utimes(filepath, atime, mtime, cb) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.utimes(req.handle, filepath, atime, mtime)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'utimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function utimesSync(filepath, atime, mtime) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.utimesSync(req.handle, filepath, atime, mtime)
  } catch (e) {
    throw new FileError(e.message, { operation: 'utimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function lutimes(filepath, atime, mtime, cb) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.lutimes(req.handle, filepath, atime, mtime)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'lutimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function lutimesSync(filepath, atime, mtime) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.lutimesSync(req.handle, filepath, atime, mtime)
  } catch (e) {
    throw new FileError(e.message, { operation: 'lutimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function futimes(fd, atime, mtime, cb) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.futimes(req.handle, fd, atime, mtime)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'futimes', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function futimesSync(fd, atime, mtime) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  const req = FileRequest.borrow()

  try {
    binding.futimesSync(req.handle, fd, atime, mtime)
  } catch (e) {
    throw new FileError(e.message, { operation: 'futimesSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function link(src, dst, cb) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.link(req.handle, src, dst)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'link', code: e.code, path: src, destination: dst })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function linkSync(src, dst) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  try {
    binding.linkSync(req.handle, src, dst)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'linkSync',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }
}

async function mkdir(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = { mode: 0o777 }
  }

  if (typeof opts === 'number') opts = { mode: opts }
  else if (!opts) opts = {}

  const mode = typeof opts.mode === 'number' ? opts.mode : 0o777

  filepath = toNamespacedPath(filepath)

  if (opts.recursive) {
    let err = null
    try {
      try {
        await mkdir(filepath, { mode })
      } catch (err) {
        if (err.code !== 'ENOENT') {
          if (!(await stat(filepath)).isDirectory()) throw err
        } else {
          while (filepath.endsWith(path.sep)) filepath = filepath.slice(0, -1)
          const i = filepath.lastIndexOf(path.sep)
          if (i <= 0) throw err

          await mkdir(filepath.slice(0, i), { mode, recursive: true })

          try {
            await mkdir(filepath, { mode })
          } catch (err) {
            if (!(await stat(filepath)).isDirectory()) throw err
          }
        }
      }
    } catch (e) {
      err = e
    }

    return done(err, cb)
  }

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.mkdir(req.handle, filepath, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'mkdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function mkdirSync(filepath, opts) {
  if (typeof opts === 'number') opts = { mode: opts }
  else if (!opts) opts = {}

  const mode = typeof opts.mode === 'number' ? opts.mode : 0o777

  filepath = toNamespacedPath(filepath)

  if (opts.recursive) {
    try {
      mkdirSync(filepath, { mode })
    } catch (err) {
      if (err.code !== 'ENOENT') {
        if (!statSync(filepath).isDirectory()) throw err
      } else {
        while (filepath.endsWith(path.sep)) filepath = filepath.slice(0, -1)
        const i = filepath.lastIndexOf(path.sep)
        if (i <= 0) throw err

        mkdirSync(filepath.slice(0, i), { mode, recursive: true })

        try {
          mkdirSync(filepath, { mode })
        } catch (err) {
          if (!statSync(filepath).isDirectory()) throw err
        }
      }
    }

    return
  }

  const req = FileRequest.borrow()

  try {
    binding.mkdirSync(req.handle, filepath, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'mkdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function mkdtemp(prefix, cb) {
  prefix = toNamespacedPath(prefix)

  const req = FileRequest.borrow()

  let res
  let err = null
  try {
    binding.mkdtemp(req.handle, prefix + 'XXXXXX')

    await req

    res = binding.requestResultPath(req.handle)
  } catch (e) {
    err = new FileError(e.message, { operation: 'mkdtemp', code: e.code, path: prefix })
  } finally {
    req.return()
  }

  return done(err, res, cb)
}

function mkdtempSync(prefix) {
  prefix = toNamespacedPath(prefix)

  const req = FileRequest.borrow()

  try {
    binding.mkdtempSync(req.handle, prefix + 'XXXXXX')

    return binding.requestResultPath(req.handle)
  } catch (e) {
    throw new FileError(e.message, { operation: 'mkdtempSync', code: e.code, path: prefix })
  } finally {
    req.return()
  }
}

async function rmdir(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.rmdir(req.handle, filepath)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'rmdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function rmdirSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.rmdirSync(req.handle, filepath)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'rmdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function rm(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  let err = null
  try {
    const st = await lstat(filepath)

    if (st.isDirectory()) {
      if (opts.recursive) {
        try {
          await rmdir(filepath)
        } catch (err) {
          if (err.code !== 'ENOTEMPTY') throw err

          const files = await readdir(filepath)

          for (const file of files) {
            await rm(filepath + path.sep + file, opts)
          }

          await rmdir(filepath)
        }
      } else {
        throw new FileError('is a directory', {
          operation: 'rm',
          code: 'EISDIR',
          path: filepath
        })
      }
    } else {
      await unlink(filepath)
    }
  } catch (e) {
    if (e.code !== 'ENOENT' || !opts.force) err = e
  }

  return done(err, cb)
}

function rmSync(filepath, opts) {
  if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  try {
    const st = lstatSync(filepath)

    if (st.isDirectory()) {
      if (opts.recursive) {
        try {
          rmdirSync(filepath)
        } catch (err) {
          if (err.code !== 'ENOTEMPTY') throw err

          const files = readdirSync(filepath)

          for (const file of files) {
            rmSync(filepath + path.sep + file, opts)
          }

          rmdirSync(filepath)
        }
      } else {
        throw new FileError('is a directory', {
          operation: 'rm',
          code: 'EISDIR',
          path: filepath
        })
      }
    } else {
      unlinkSync(filepath)
    }
  } catch (err) {
    if (err.code !== 'ENOENT' || !opts.force) throw err
  }
}

async function unlink(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.unlink(req.handle, filepath)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'unlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function unlinkSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.unlinkSync(req.handle, filepath)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'unlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function rename(src, dst, cb) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.rename(req.handle, src, dst)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'rename',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function renameSync(src, dst) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  try {
    binding.renameSync(req.handle, src, dst)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'rename',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }
}

async function copyFile(src, dst, mode = 0, cb) {
  if (typeof mode === 'function') {
    cb = mode
    mode = 0
  }

  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.copyfile(req.handle, src, dst, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'copyfile',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function copyFileSync(src, dst, mode = 0) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  try {
    binding.copyfileSync(req.handle, src, dst, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'copyfile',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }
}

async function cp(src, dst, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (!opts) opts = {}

  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  let err = null
  try {
    const st = await lstat(src)

    if (st.isDirectory()) {
      if (opts.recursive !== true) {
        throw new FileError('is a directory', { operation: 'cp', code: 'EISDIR', path: src })
      }

      try {
        await lstat(dst)
      } catch (e) {
        if (e.code !== 'ENOENT') throw e

        await mkdir(dst, { mode: st.mode, recursive: true })
      }

      const dir = await opendir(src)
      for await (const { name } of dir) {
        await cp(path.join(src, name), path.join(dst, name), opts)
      }
    } else if (st.isFile()) {
      await copyFile(src, dst)
      await chmod(dst, st.mode)
    }
  } catch (e) {
    err = e
  }

  return done(err, cb)
}

function cpSync(src, dst, opts = {}) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const st = lstatSync(src)

  if (st.isDirectory()) {
    if (opts.recursive !== true) {
      throw new FileError('is a directory', { operation: 'cp', code: 'EISDIR', path: src })
    }

    try {
      lstatSync(dst)
    } catch (e) {
      if (e.code !== 'ENOENT') throw e

      mkdirSync(dst, { mode: st.mode, recursive: true })
    }

    const dir = opendirSync(src)
    for (const { name } of dir) {
      cpSync(path.join(src, name), path.join(dst, name), opts)
    }
  } else if (st.isFile()) {
    copyFileSync(src, dst)
    chmodSync(dst, st.mode)
  }
}

async function realpath(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let res
  let err = null
  try {
    binding.realpath(req.handle, filepath)

    await req

    res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'realpath',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, res, cb)
}

function realpathSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.realpathSync(req.handle, filepath)

    let res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)

    return res
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'realpath',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function readlink(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let res
  let err = null
  try {
    binding.readlink(req.handle, filepath)

    await req

    res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'readlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, res, cb)
}

function readlinkSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.readlinkSync(req.handle, filepath)

    let res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)

    return res
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'readlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function fsync(fd, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fsync(req.handle, fd)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fsync', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fsyncSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.fsyncSync(req.handle, fd)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fsyncSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function fdatasync(fd, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fdatasync(req.handle, fd)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fdatasync', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fdatasyncSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.fdatasyncSync(req.handle, fd)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fdatasyncSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

function normalizeSymlinkTarget(target, type, filepath) {
  if (isWindows) {
    if (type === constants.UV_FS_SYMLINK_JUNCTION) target = path.resolve(filepath, '..', target)

    if (path.isAbsolute(target)) return path.toNamespacedPath(target)

    return target.replace(/\//g, path.sep)
  }

  return target
}

async function symlink(target, filepath, type, cb) {
  if (typeof type === 'function') {
    cb = type
    type = null
  }

  filepath = toNamespacedPath(filepath)

  if (typeof type === 'string') {
    switch (type) {
      case 'dir':
        type = constants.UV_FS_SYMLINK_DIR
        break
      case 'junction':
        type = constants.UV_FS_SYMLINK_JUNCTION
        break
      case 'file':
      default:
        type = 0
        break
    }
  } else if (typeof type !== 'number') {
    if (isWindows) {
      target = path.resolve(filepath, '..', target)

      try {
        type = (await stat(target)).isDirectory()
          ? constants.UV_FS_SYMLINK_DIR
          : constants.UV_FS_SYMLINK_JUNCTION
      } catch {
        type = 0
      }
    } else {
      type = 0
    }
  }

  target = normalizeSymlinkTarget(target, type, filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.symlink(req.handle, target, filepath, type)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'symlink',
      code: e.code,
      path: target,
      destination: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function symlinkSync(target, filepath, type) {
  filepath = toNamespacedPath(filepath)

  if (typeof type === 'string') {
    switch (type) {
      case 'dir':
        type = constants.UV_FS_SYMLINK_DIR
        break
      case 'junction':
        type = constants.UV_FS_SYMLINK_JUNCTION
        break
      case 'file':
      default:
        type = 0
        break
    }
  } else if (typeof type !== 'number') {
    if (isWindows) {
      target = path.resolve(filepath, '..', target)

      try {
        type = statSync(target).isDirectory()
          ? constants.UV_FS_SYMLINK_DIR
          : constants.UV_FS_SYMLINK_JUNCTION
      } catch {
        type = 0
      }
    } else {
      type = 0
    }
  }

  target = normalizeSymlinkTarget(target, type, filepath)

  const req = FileRequest.borrow()

  try {
    binding.symlinkSync(req.handle, target, filepath, type)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'symlink',
      code: e.code,
      path: target,
      destination: filepath
    })
  } finally {
    req.return()
  }
}

async function opendir(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let dir
  let err = null
  try {
    binding.opendir(req.handle, filepath)

    await req

    dir = new Dir(filepath, binding.requestResultDir(req.handle), opts)
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'opendir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, dir, cb)
}

function opendirSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.opendirSync(req.handle, filepath)

    return new Dir(filepath, binding.requestResultDir(req.handle), opts)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'opendir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function readdir(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { withFileTypes = false, recursive = false } = opts

  filepath = toNamespacedPath(filepath)

  const queue = [filepath]
  let result = []
  let err = null
  try {
    while (queue.length !== 0) {
      const dir = await opendir(queue.pop())

      for await (const entry of dir) {
        const entryPath = path.join(entry.parentPath, entry.name)

        if (withFileTypes) {
          result.push(entry)
        } else {
          result.push(path.relative(filepath, entryPath))
        }

        if (recursive && entry.isDirectory()) queue.push(entryPath)
      }
    }
  } catch (e) {
    result = []
    err = e
  }

  return done(err, result, cb)
}

function readdirSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { withFileTypes = false, recursive = false } = opts

  filepath = toNamespacedPath(filepath)

  const queue = [filepath]
  const result = []

  while (queue.length !== 0) {
    const dir = opendirSync(queue.pop(), opts)

    for (const entry of dir) {
      const entryPath = path.join(entry.parentPath, entry.name)

      if (withFileTypes) {
        result.push(entry)
      } else {
        result.push(path.relative(filepath, entryPath))
      }

      if (recursive && entry.isDirectory()) queue.push(entryPath)
    }
  }

  return result
}

async function readFile(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'buffer' } = opts

  let fd = -1
  let buffer = null
  let err = null
  try {
    fd = await open(filepath, opts.flag || 'r')

    const st = await fstat(fd)

    let len = 0

    if (st.size === 0) {
      const buffers = []

      while (true) {
        buffer = Buffer.allocUnsafe(8192)
        const r = await read(fd, buffer)
        len += r
        if (r === 0) break
        buffers.push(buffer.subarray(0, r))
      }

      buffer = Buffer.concat(buffers)
    } else {
      buffer = Buffer.allocUnsafe(st.size)

      while (true) {
        const r = await read(fd, len ? buffer.subarray(len) : buffer)
        len += r
        if (r === 0 || len === buffer.byteLength) break
      }

      if (len !== buffer.byteLength) buffer = buffer.subarray(0, len)
    }

    if (encoding !== 'buffer') buffer = buffer.toString(encoding)
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) await close(fd)
  }

  return done(err, buffer, cb)
}

function readFileSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'buffer' } = opts

  let fd = -1
  try {
    fd = openSync(filepath, opts.flag || 'r')

    const st = fstatSync(fd)

    let buffer
    let len = 0

    if (st.size === 0) {
      const buffers = []

      while (true) {
        buffer = Buffer.allocUnsafe(8192)
        const r = readSync(fd, buffer)
        len += r
        if (r === 0) break
        buffers.push(buffer.subarray(0, r))
      }

      buffer = Buffer.concat(buffers)
    } else {
      buffer = Buffer.allocUnsafe(st.size)

      while (true) {
        const r = readSync(fd, len ? buffer.subarray(len) : buffer)
        len += r
        if (r === 0 || len === buffer.byteLength) break
      }

      if (len !== buffer.byteLength) buffer = buffer.subarray(0, len)
    }

    if (encoding !== 'buffer') buffer = buffer.toString(encoding)

    return buffer
  } finally {
    if (fd !== -1) closeSync(fd)
  }
}

async function writeFile(filepath, data, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (typeof data === 'string') data = Buffer.from(data, opts.encoding)

  let fd = -1
  let len = 0
  let err = null
  try {
    fd = await open(filepath, opts.flag || 'w', opts.mode || 0o666)

    while (true) {
      len += await write(fd, len ? data.subarray(len) : data)
      if (len === data.byteLength) break
    }
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) await close(fd)
  }

  return done(err, len, cb)
}

function writeFileSync(filepath, data, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (typeof data === 'string') data = Buffer.from(data, opts.encoding)

  let fd = -1
  try {
    fd = openSync(filepath, opts.flag || 'w', opts.mode || 0o666)

    let len = 0

    while (true) {
      len += writeSync(fd, len ? data.subarray(len) : data)
      if (len === data.byteLength) break
    }
  } finally {
    if (fd !== -1) closeSync(fd)
  }
}

function appendFile(filepath, data, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (!opts.flag) opts = { ...opts, flag: 'a' }

  return writeFile(filepath, data, opts, cb)
}

function appendFileSync(filepath, data, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (!opts.flag) opts = { ...opts, flag: 'a' }

  return writeFileSync(filepath, data, opts)
}

function watch(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  return new Watcher(filepath, opts, cb)
}

class Stats {
  constructor(
    dev,
    mode,
    nlink,
    uid,
    gid,
    rdev,
    blksize,
    ino,
    size,
    blocks,
    atimeMs,
    mtimeMs,
    ctimeMs,
    birthtimeMs
  ) {
    this.dev = dev
    this.mode = mode
    this.nlink = nlink
    this.uid = uid
    this.gid = gid
    this.rdev = rdev
    this.blksize = blksize
    this.ino = ino
    this.size = size
    this.blocks = blocks
    this.atimeMs = atimeMs
    this.mtimeMs = mtimeMs
    this.ctimeMs = ctimeMs
    this.birthtimeMs = birthtimeMs
    this.atime = new Date(atimeMs)
    this.mtime = new Date(mtimeMs)
    this.ctime = new Date(ctimeMs)
    this.birthtime = new Date(birthtimeMs)
  }

  isDirectory() {
    return (this.mode & constants.S_IFMT) === constants.S_IFDIR
  }

  isFile() {
    return (this.mode & constants.S_IFMT) === constants.S_IFREG
  }

  isBlockDevice() {
    return (this.mode & constants.S_IFMT) === constants.S_IFBLK
  }

  isCharacterDevice() {
    return (this.mode & constants.S_IFMT) === constants.S_IFCHR
  }

  isFIFO() {
    return (this.mode & constants.S_IFMT) === constants.S_IFIFO
  }

  isSymbolicLink() {
    return (this.mode & constants.S_IFMT) === constants.S_IFLNK
  }

  isSocket() {
    return (this.mode & constants.S_IFMT) === constants.S_IFSOCK
  }
}

class StatFs {
  constructor(type, bsize, blocks, bfree, bavail, files, ffree) {
    this.type = type
    this.bsize = bsize
    this.blocks = blocks
    this.bfree = bfree
    this.bavail = bavail
    this.files = files
    this.ffree = ffree
  }
}

class Dir {
  constructor(path, handle, opts = {}) {
    const { encoding = 'utf8', bufferSize = 32 } = opts

    this.path = path

    this._encoding = encoding
    this._capacity = bufferSize
    this._buffer = new FIFO()
    this._ended = false
    this._handle = handle
  }

  async read(cb) {
    if (this._buffer.length) return ok(this._buffer.shift(), cb)
    if (this._ended) return ok(null, cb)

    const req = FileRequest.borrow()

    let entries
    let err = null
    try {
      req.retain(binding.readdir(req.handle, this._handle, this._capacity))

      await req

      entries = binding.requestResultDirents(req.handle)
    } catch (e) {
      err = new FileError(e.message, {
        operation: 'readdir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    if (err) return fail(err, cb)

    if (entries.length === 0) {
      this._ended = true

      return ok(null, cb)
    }

    for (const entry of entries) {
      let name = Buffer.from(entry.name)

      if (this._encoding !== 'buffer') name = name.toString(this._encoding)

      this._buffer.push(new Dirent(this.path, name, entry.type))
    }

    return ok(this._buffer.shift(), cb)
  }

  readSync() {
    if (this._buffer.length) return this._buffer.shift()
    if (this._ended) return null

    const req = FileRequest.borrow()

    let entries
    try {
      req.retain(binding.readdirSync(req.handle, this._handle, this._capacity))

      entries = binding.requestResultDirents(req.handle)
    } catch (e) {
      throw new FileError(e.message, {
        operation: 'readdir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    if (entries.length === 0) {
      this._ended = true

      return null
    }

    for (const entry of entries) {
      let name = Buffer.from(entry.name)

      if (this._encoding !== 'buffer') name = name.toString(this._encoding)

      this._buffer.push(new Dirent(this.path, name, entry.type))
    }

    return this._buffer.shift()
  }

  async close(cb) {
    const req = FileRequest.borrow()

    let err = null
    try {
      binding.closedir(req.handle, this._handle)

      await req
    } catch (e) {
      err = new FileError(e.message, {
        operation: 'closedir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    this._handle = null

    return done(err, cb)
  }

  closeSync() {
    const req = FileRequest.borrow()

    try {
      binding.closedirSync(req.handle, this._handle)
    } catch (e) {
      throw new FileError(e.message, {
        operation: 'closedir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    this._handle = null
  }

  [Symbol.dispose]() {
    this.closeSync()
  }

  async [Symbol.asyncDispose]() {
    await this.close()
  }

  *[Symbol.iterator]() {
    while (true) {
      const entry = this.readSync()
      if (entry === null) break
      yield entry
    }

    this.closeSync()
  }

  async *[Symbol.asyncIterator]() {
    while (true) {
      const entry = await this.read()
      if (entry === null) break
      yield entry
    }

    await this.close()
  }
}

class Dirent {
  constructor(parentPath, name, type) {
    this.parentPath = parentPath
    this.name = name
    this.type = type
  }

  isFile() {
    return this.type === constants.UV_DIRENT_FILE
  }

  isDirectory() {
    return this.type === constants.UV_DIRENT_DIR
  }

  isSymbolicLink() {
    return this.type === constants.UV_DIRENT_LINK
  }

  isFIFO() {
    return this.type === constants.UV_DIRENT_FIFO
  }

  isSocket() {
    return this.type === constants.UV_DIRENT_SOCKET
  }

  isCharacterDevice() {
    return this.type === constants.UV_DIRENT_CHAR
  }

  isBlockDevice() {
    return this.type === constants.UV_DIRENT_BLOCK
  }
}

class FileReadStream extends Readable {
  constructor(path, opts = {}) {
    const { eagerOpen = true } = opts

    super({ eagerOpen, ...opts })

    this.path = path
    this.fd = typeof opts.fd === 'number' ? opts.fd : -1
    this.flags = opts.flags || 'r'
    this.mode = opts.mode || 0o666

    this._offset = opts.start || 0
    this._missing = 0

    if (opts.length) {
      this._missing = opts.length
    } else if (typeof opts.end === 'number') {
      this._missing = opts.end - this._offset + 1
    } else {
      this._missing = -1
    }
  }

  async _open(cb) {
    let err

    if (this.fd === -1) {
      err = null
      try {
        this.fd = await open(this.path, this.flags, this.mode)
      } catch (e) {
        err = e
      }

      if (err) return cb(err)
    }

    let st
    err = null
    try {
      st = await fstat(this.fd)
    } catch (e) {
      err = e
    }

    if (err) return cb(err)

    if (this._missing === -1) this._missing = st.size

    if (st.size < this._offset) {
      this._offset = st.size
      this._missing = 0
    } else if (st.size < this._offset + this._missing) {
      this._missing = st.size - this._offset
    }

    cb(null)
  }

  async _read(size) {
    if (this._missing <= 0) return this.push(null)

    const data = Buffer.allocUnsafe(Math.min(this._missing, size))

    let len
    let err = null
    try {
      len = await read(this.fd, data, 0, data.byteLength, this._offset)
    } catch (e) {
      err = e
    }

    if (err) return this.destroy(err)

    if (len === 0) return this.push(null)

    if (this._missing < len) len = this._missing

    this._missing -= len
    this._offset += len

    this.push(data.subarray(0, len))
  }

  async _destroy(err, cb) {
    if (this.fd === -1) return cb(err)

    try {
      await close(this.fd)
    } catch (e) {
      err = err || e
    }

    cb(err)
  }
}

class FileWriteStream extends Writable {
  constructor(path, opts = {}) {
    const { eagerOpen = true } = opts

    super({ eagerOpen, ...opts })

    this.path = path
    this.fd = typeof opts.fd === 'number' ? opts.fd : -1
    this.flags = opts.flags || 'w'
    this.mode = opts.mode || 0o666
  }

  async _open(cb) {
    if (this.fd !== -1) return cb(null)

    let err = null
    try {
      this.fd = await open(this.path, this.flags, this.mode)
    } catch (e) {
      err = e
    }

    cb(err)
  }

  async _writev(batch, cb) {
    let err = null
    try {
      await writev(
        this.fd,
        batch.map(({ chunk }) => chunk)
      )
    } catch (e) {
      err = e
    }

    cb(err)
  }

  async _destroy(err, cb) {
    if (this.fd === -1) return cb(err)

    try {
      await close(this.fd)
    } catch (e) {
      err = err || e
    }

    cb(err)
  }
}

class Watcher extends EventEmitter {
  constructor(path, opts, onchange) {
    if (typeof opts === 'function') {
      onchange = opts
      opts = {}
    }

    if (!opts) opts = {}

    const { persistent = true, recursive = false, encoding = 'utf8' } = opts

    super()

    this._closed = false
    this._encoding = encoding
    this._handle = binding.watcherInit(path, recursive, this, this._onevent, this._onclose)

    if (!persistent) this.unref()

    if (onchange) this.on('change', onchange)
  }

  close() {
    if (this._closed) return
    this._closed = true

    binding.watcherClose(this._handle)
  }

  ref() {
    if (this._handle) binding.watcherRef(this._handle)
    return this
  }

  unref() {
    if (this._handle) binding.watcherUnref(this._handle)
    return this
  }

  [Symbol.asyncIterator]() {
    const buffer = []
    let done = false
    let error = null
    let next = null

    this.on('change', (eventType, filename) => {
      if (next) {
        next.resolve({ done: false, value: { eventType, filename } })
        next = null
      } else {
        buffer.push({ eventType, filename })
      }
    })
      .on('error', (err) => {
        done = true
        error = err

        if (next) {
          next.reject(error)
          next = null
        }
      })
      .on('close', () => {
        done = true

        if (next) {
          next.resolve({ done })
          next = null
        }
      })

    return {
      next: () =>
        new Promise((resolve, reject) => {
          if (error) return reject(error)

          if (buffer.length) return resolve({ done: false, value: buffer.shift() })

          if (done) return resolve({ done })

          next = { resolve, reject }
        })
    }
  }

  _onevent(err, events, filename) {
    if (err) {
      this.close()
      this.emit('error', err)
    } else {
      const path =
        this._encoding === 'buffer'
          ? Buffer.from(filename)
          : Buffer.from(filename).toString(this._encoding)

      if (events & binding.UV_RENAME) {
        this.emit('change', 'rename', path)
      }

      if (events & binding.UV_CHANGE) {
        this.emit('change', 'change', path)
      }
    }
  }

  _onclose() {
    this._handle = null

    this.emit('close')
  }
}

exports.access = access
exports.appendFile = appendFile
exports.chmod = chmod
exports.chown = chown
exports.close = close
exports.copyFile = copyFile
exports.cp = cp
exports.exists = exists
exports.fchmod = fchmod
exports.fchown = fchown
exports.fdatasync = fdatasync
exports.fstat = fstat
exports.fsync = fsync
exports.ftruncate = ftruncate
exports.futimes = futimes
exports.lchown = lchown
exports.lutimes = lutimes
exports.link = link
exports.lstat = lstat
exports.mkdir = mkdir
exports.mkdtemp = mkdtemp
exports.open = open
exports.opendir = opendir
exports.read = read
exports.readFile = readFile
exports.readdir = readdir
exports.readlink = readlink
exports.readv = readv
exports.realpath = realpath
exports.rename = rename
exports.rm = rm
exports.rmdir = rmdir
exports.stat = stat
exports.statfs = statfs
exports.symlink = symlink
exports.truncate = truncate
exports.unlink = unlink
exports.utimes = utimes
exports.watch = watch
exports.write = write
exports.writeFile = writeFile
exports.writev = writev

exports.accessSync = accessSync
exports.appendFileSync = appendFileSync
exports.chmodSync = chmodSync
exports.chownSync = chownSync
exports.closeSync = closeSync
exports.copyFileSync = copyFileSync
exports.cpSync = cpSync
exports.existsSync = existsSync
exports.fchmodSync = fchmodSync
exports.fchownSync = fchownSync
exports.fdatasyncSync = fdatasyncSync
exports.fstatSync = fstatSync
exports.fsyncSync = fsyncSync
exports.ftruncateSync = ftruncateSync
exports.futimesSync = futimesSync
exports.lchownSync = lchownSync
exports.lutimesSync = lutimesSync
exports.linkSync = linkSync
exports.lstatSync = lstatSync
exports.mkdirSync = mkdirSync
exports.mkdtempSync = mkdtempSync
exports.openSync = openSync
exports.opendirSync = opendirSync
exports.readFileSync = readFileSync
exports.readSync = readSync
exports.readdirSync = readdirSync
exports.readlinkSync = readlinkSync
exports.readvSync = readvSync
exports.realpathSync = realpathSync
exports.renameSync = renameSync
exports.rmSync = rmSync
exports.rmdirSync = rmdirSync
exports.statSync = statSync
exports.statfsSync = statfsSync
exports.symlinkSync = symlinkSync
exports.truncateSync = truncateSync
exports.unlinkSync = unlinkSync
exports.utimesSync = utimesSync
exports.writeFileSync = writeFileSync
exports.writeSync = writeSync
exports.writevSync = writevSync

exports.promises = require('./promises')

exports.Stats = Stats
exports.StatFs = StatFs
exports.Dir = Dir
exports.Dirent = Dirent
exports.Watcher = Watcher

exports.ReadStream = FileReadStream

exports.createReadStream = function createReadStream(path, opts) {
  return new FileReadStream(path, opts)
}

exports.WriteStream = FileWriteStream

exports.createWriteStream = function createWriteStream(path, opts) {
  return new FileWriteStream(path, opts)
}

function toNamespacedPath(filepath) {
  if (typeof filepath !== 'string') {
    if (isURL(filepath)) filepath = fileURLToPath(filepath)
    else filepath = filepath.toString()
  }

  return path.toNamespacedPath(filepath)
}

function toFlags(flags) {
  switch (flags) {
    case 'r':
      return constants.O_RDONLY
    case 'rs': // Fall through.
    case 'sr':
      return constants.O_RDONLY | constants.O_SYNC
    case 'r+':
      return constants.O_RDWR
    case 'rs+': // Fall through.
    case 'sr+':
      return constants.O_RDWR | constants.O_SYNC

    case 'w':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_WRONLY
    case 'wx': // Fall through.
    case 'xw':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_WRONLY | constants.O_EXCL

    case 'w+':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_RDWR
    case 'wx+': // Fall through.
    case 'xw+':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_RDWR | constants.O_EXCL

    case 'a':
      return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY
    case 'ax': // Fall through.
    case 'xa':
      return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY | constants.O_EXCL
    case 'as': // Fall through.
    case 'sa':
      return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY | constants.O_SYNC

    case 'a+':
      return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR
    case 'ax+': // Fall through.
    case 'xa+':
      return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR | constants.O_EXCL
    case 'as+': // Fall through.
    case 'sa+':
      return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR | constants.O_SYNC
    default:
      return 0
  }
}

function toMode(mode) {
  return parseInt(mode, 8)
}
const binding = require('../binding')

module.exports = {
  O_RDWR: binding.O_RDWR,
  O_RDONLY: binding.O_RDONLY,
  O_WRONLY: binding.O_WRONLY,
  O_CREAT: binding.O_CREAT,
  O_TRUNC: binding.O_TRUNC,
  O_APPEND: binding.O_APPEND,

  F_OK: binding.F_OK || 0,
  R_OK: binding.R_OK || 0,
  W_OK: binding.W_OK || 0,
  X_OK: binding.X_OK || 0,

  S_IFMT: binding.S_IFMT,
  S_IFREG: binding.S_IFREG,
  S_IFDIR: binding.S_IFDIR,
  S_IFCHR: binding.S_IFCHR,
  S_IFLNK: binding.S_IFLNK,
  S_IFBLK: binding.S_IFBLK || 0,
  S_IFIFO: binding.S_IFIFO || 0,
  S_IFSOCK: binding.S_IFSOCK || 0,

  S_IRUSR: binding.S_IRUSR || 0,
  S_IWUSR: binding.S_IWUSR || 0,
  S_IXUSR: binding.S_IXUSR || 0,
  S_IRGRP: binding.S_IRGRP || 0,
  S_IWGRP: binding.S_IWGRP || 0,
  S_IXGRP: binding.S_IXGRP || 0,
  S_IROTH: binding.S_IROTH || 0,
  S_IWOTH: binding.S_IWOTH || 0,
  S_IXOTH: binding.S_IXOTH || 0,

  UV_DIRENT_UNKNOWN: binding.UV_DIRENT_UNKNOWN,
  UV_DIRENT_FILE: binding.UV_DIRENT_FILE,
  UV_DIRENT_DIR: binding.UV_DIRENT_DIR,
  UV_DIRENT_LINK: binding.UV_DIRENT_LINK,
  UV_DIRENT_FIFO: binding.UV_DIRENT_FIFO,
  UV_DIRENT_SOCKET: binding.UV_DIRENT_SOCKET,
  UV_DIRENT_CHAR: binding.UV_DIRENT_CHAR,
  UV_DIRENT_BLOCK: binding.UV_DIRENT_BLOCK,

  COPYFILE_EXCL: binding.UV_FS_COPYFILE_EXCL,
  COPYFILE_FICLONE: binding.UV_FS_COPYFILE_FICLONE,
  COPYFILE_FICLONE_FORCE: binding.UV_FS_COPYFILE_FICLONE_FORCE,
  UV_FS_SYMLINK_DIR: binding.UV_FS_SYMLINK_DIR,
  UV_FS_SYMLINK_JUNCTION: binding.UV_FS_SYMLINK_JUNCTION
}
const os = require('bare-os')

module.exports = class FileError extends Error {
  constructor(msg, opts = {}) {
    const { code, operation = null, path = null, destination = null, fd = -1 } = opts

    if (operation !== null) msg += describe(operation, opts)

    super(`${code}: ${msg}`)

    this.code = code

    if (operation !== null) this.operation = operation
    if (path !== null) this.path = path
    if (destination !== null) this.destination = destination
    if (fd !== -1) this.fd = fd
  }

  get name() {
    return 'FileError'
  }

  // For Node.js compatibility
  get errno() {
    return os.constants.errnos[this.code]
  }

  // For Node.js compatibility
  get syscall() {
    return this.operation
  }

  // For Node.js compatibility
  get dest() {
    return this.destination
  }
}

function describe(operation, opts) {
  const { path = null, destination = null, fd = -1 } = opts

  let result = `, ${operation}`

  if (path !== null) {
    result += ` ${JSON.stringify(path)}`

    if (destination !== null) {
      result += ` -> ${JSON.stringify(destination)}`
    }
  } else if (fd !== -1) {
    result += ` ${fd}`
  }

  return result
}
{
  "name": "bare-fs",
  "version": "4.7.3",
  "description": "Native file system operations for Bare",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./promises": {
      "types": "./promises.d.ts",
      "default": "./promises.js"
    },
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "promises.js",
    "promises.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-fs.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-fs/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-fs#readme",
  "engines": {
    "bare": ">=1.16.0"
  },
  "dependencies": {
    "bare-events": "^2.5.4",
    "bare-path": "^3.0.0",
    "bare-stream": "^2.6.4",
    "bare-url": "^2.2.2",
    "fast-fifo": "^1.3.2"
  },
  "devDependencies": {
    "bare-buffer": "^3.0.2",
    "bare-crypto": "^1.11.2",
    "brittle": "^3.1.1",
    "cmake-bare": "^1.1.7",
    "lunte": "^1.6.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "bare-buffer": "*"
  },
  "peerDependenciesMeta": {
    "bare-buffer": {
      "optional": true
    }
  }
}
const EventEmitter = require('bare-events')
const fs = require('.')

class FileHandle extends EventEmitter {
  constructor(fd) {
    super()

    this.fd = fd
  }

  async close() {
    await fs.close(this.fd)

    this.fd = -1
    this.emit('close')
  }

  async read(buffer, ...args) {
    return {
      bytesRead: await fs.read(this.fd, buffer, ...args),
      buffer
    }
  }

  async readv(buffers, ...args) {
    return {
      bytesRead: await fs.readv(this.fd, buffers, ...args),
      buffers
    }
  }

  async write(buffer, ...args) {
    return {
      bytesWritten: await fs.write(this.fd, buffer, ...args),
      buffer
    }
  }

  async writev(buffers, ...args) {
    return {
      bytesWritten: await fs.writev(this.fd, buffers, ...args),
      buffers
    }
  }

  async stat() {
    return fs.fstat(this.fd)
  }

  async chmod(mode) {
    await fs.fchmod(this.fd, mode)
  }

  async chown(uid, gid) {
    await fs.fchown(this.fd, uid, gid)
  }

  async datasync() {
    return fs.fdatasync(this.fd)
  }

  async sync() {
    return fs.fsync(this.fd)
  }

  async truncate(len) {
    await fs.ftruncate(this.fd, len)
  }

  async utimes(atime, mtime) {
    await fs.futimes(this.fd, atime, mtime)
  }

  createReadStream(opts) {
    return fs.createReadStream(null, { ...opts, fd: this.fd })
  }

  createWriteStream(opts) {
    return fs.createWriteStream(null, { ...opts, fd: this.fd })
  }

  async [Symbol.asyncDispose]() {
    await this.close()
  }
}

exports.open = async function open(filepath, flags, mode) {
  return new FileHandle(await fs.open(filepath, flags, mode))
}

exports.access = fs.access
exports.appendFile = fs.appendFile
exports.chmod = fs.chmod
exports.chown = fs.chown
exports.constants = fs.constants
exports.copyFile = fs.copyFile
exports.cp = fs.cp
exports.lchown = fs.lchown
exports.lutimes = fs.lutimes
exports.link = fs.link
exports.lstat = fs.lstat
exports.mkdir = fs.mkdir
exports.mkdtemp = fs.mkdtemp
exports.opendir = fs.opendir
exports.readFile = fs.readFile
exports.readdir = fs.readdir
exports.readlink = fs.readlink
exports.realpath = fs.realpath
exports.rename = fs.rename
exports.rm = fs.rm
exports.rmdir = fs.rmdir
exports.stat = fs.stat
exports.statfs = fs.statfs
exports.truncate = fs.truncate
exports.symlink = fs.symlink
exports.unlink = fs.unlink
exports.utimes = fs.utimes
exports.watch = fs.watch
exports.writeFile = fs.writeFile
module.exports = require.addon()
const ansiEscapes = require('bare-ansi-escapes')
const getType = require('bare-type')
const binding = require('./binding')

const PLAIN_KEY = /^[a-zA-Z_][a-zA-Z_0-9]*$/

const defaultDepth = 2
const defaultBreakLength = 80
const defaultMaxArrayLength = 40

module.exports = exports = function inspect(value, opts = {}) {
  const {
    colors = false,
    depth = defaultDepth,
    breakLength = defaultBreakLength,
    stylize = defaultStylize(colors)
  } = opts

  const references = new InspectRefMap()

  const tree = inspectValue(value, 0, {
    colors,
    depth,
    breakLength,
    stylize,
    references
  })

  return tree.toString()
}

exports.styles = {
  bigint: ansiEscapes.colorYellow,
  boolean: ansiEscapes.colorYellow,
  date: ansiEscapes.colorMagenta,
  module: ansiEscapes.modifierUnderline,
  name: ansiEscapes.modifierReset,
  null: ansiEscapes.modifierBold,
  number: ansiEscapes.colorYellow,
  regexp: ansiEscapes.colorRed,
  special: ansiEscapes.colorCyan,
  string: ansiEscapes.colorGreen,
  symbol: ansiEscapes.colorGreen,
  undefined: ansiEscapes.colorBrightBlack
}

const styles = exports.styles

function defaultStylize(colors) {
  return function stylize(value, style) {
    const color = colors && styles[style]

    if (color) return color + value + ansiEscapes.modifierReset

    return value
  }
}

class InspectRefMap {
  constructor() {
    this.refs = new WeakMap()
    this.ids = new WeakMap()
    this.nextId = 1
  }

  has(object) {
    return this.refs.has(object)
  }

  get(object) {
    return this.refs.get(object) || null
  }

  set(object, ref) {
    this.refs.set(object, ref)
  }

  id(object) {
    let id = this.ids.get(object)
    if (id) return id

    id = this.nextId++
    this.ids.set(object, id)

    return id
  }
}

class InspectNode {
  constructor(depth, length, opts) {
    const { breakLength = defaultBreakLength, breakAlways = false } = opts

    this.depth = depth
    this.length = length
    this.breakLength = breakLength
    this.breakAlways = breakAlways
  }

  pad(n, string) {
    return string.padStart(n, ' ')
  }

  indent(n, string) {
    return '  '.repeat(n) + string
  }
}

class InspectRef extends InspectNode {
  constructor(depth, opts) {
    super(depth, '[circular *]'.length, opts)

    this.refs = opts.references
    this.count = 0
    this.circular = false
    this.color = opts.colors && styles.special
  }

  get id() {
    return this.refs.id(this)
  }

  increment() {
    return ++this.count
  }

  decrement() {
    return --this.count
  }

  toString(opts = {}) {
    const { offset = 0, pad = 0, indent = 0 } = opts

    let value = this.pad(pad, '[circular *' + this.id + ']')

    if (this.color) value = this.color + value + ansiEscapes.modifierReset

    return offset ? value : this.indent(indent, value)
  }
}

class InspectLeaf extends InspectNode {
  constructor(value, color, depth, opts) {
    const length = value.length

    if (value.includes('\n')) {
      value = value.replaceAll('\n', '\n' + '  '.repeat(depth))

      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.value = value
    this.color = opts.colors && color
  }

  toString(opts = {}) {
    const { offset = 0, pad = 0, indent = 0 } = opts

    let value = this.pad(pad, this.value)

    if (this.color) value = this.color + value + ansiEscapes.modifierReset

    return offset ? value : this.indent(indent, value)
  }
}

class InspectPair extends InspectNode {
  constructor(delim, left, right, depth, opts) {
    const length = left.length + delim.length + right.length

    if (left.breakAlways || right.breakAlways) {
      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.delim = delim
    this.left = left
    this.right = right
  }

  toString(opts = {}) {
    const { indent = 0 } = opts

    return this.indent(
      indent,
      this.left +
        this.delim +
        this.right.toString({
          indent,
          offset: this.left.length + this.delim.length
        })
    )
  }
}

class InspectSuspension extends InspectNode {
  constructor(overflow, depth, opts) {
    const label = `... ${overflow} more`

    super(depth, label.length, opts)

    this.label = label
  }

  toString(opts = {}) {
    const { indent = 0 } = opts

    return this.indent(indent, this.label)
  }
}

class InspectSequence extends InspectNode {
  constructor(header, footer, delim, values, ref, depth, opts) {
    const { tabulate = false } = opts

    const length =
      (ref.circular ? '<ref *>'.length + 1 : 0) +
      header.length +
      values.reduce(
        (length, value, i) =>
          length + value.length + (i === 0 ? 0 : delim.length),
        0
      ) +
      footer.length

    if (values.some((value) => value.breakAlways)) {
      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.header = header
    this.footer = footer
    this.delim = delim
    this.values = values
    this.ref = ref
    this.tabulate = tabulate
  }

  toString(opts = {}) {
    const { offset = 0, indent = 0 } = opts

    const split =
      this.breakAlways ||
      (this.values.length &&
        (offset + this.length > this.breakLength ||
          indent * 2 + this.length > this.breakLength))

    let header = this.header

    if (this.ref.circular) {
      header = '<ref *' + this.ref.id + '> ' + header
    }

    if (this.values.length === 0) {
      header = header.trimEnd()
    }

    if (offset === 0) {
      header = this.indent(indent, header)
    }

    if (split) {
      header = header.trimEnd() + '\n'
    }

    let string = header

    let columns = 1
    let pad = 0

    if (this.tabulate) {
      const widest = this.values.reduce(
        (length, value) =>
          value.breakAlways ? length : Math.max(length, value.length),
        0
      )

      if (widest) {
        columns = Math.max(
          columns,
          Math.floor(
            (this.breakLength - indent * 2) / (widest + this.delim.length)
          )
        )

        if (columns > 1) pad = widest
      }
    }

    for (let i = 0, n = this.values.length, offset = 0; i < n; i++) {
      const value = this.values[i]

      if (split) {
        let part

        if (i % columns === 0 || value.breakAlways) {
          part = value.toString({ indent: indent + 1, pad })
        } else {
          part = value.toString({ pad })
        }

        string += part

        if (i < n - 1) {
          if (i % columns === columns - 1 || this.values[i + 1].breakAlways) {
            string += this.delim.trimEnd() + '\n'
          } else {
            string += this.delim
          }
        }
      } else {
        if (i > 0) string += this.delim

        string += value.toString({ offset })

        offset += value.length
      }
    }

    let footer = this.footer

    if (this.values.length === 0) {
      footer = footer.trimStart()
    }

    if (split) {
      string += '\n' + this.indent(indent, footer.trimStart())
    } else {
      string += footer
    }

    return string
  }
}

function inspectValue(value, depth, opts) {
  const type = getType(value)

  if (type.isUndefined()) return inspectUndefined(depth, opts)
  if (type.isNull()) return inspectNull(depth, opts)
  if (type.isBoolean()) return inspectBoolean(value, depth, opts)
  if (type.isNumber()) return inspectNumber(value, depth, opts)
  if (type.isBigInt()) return inspectBigInt(value, depth, opts)
  if (type.isString()) return inspectString(value, depth, opts)
  if (type.isSymbol()) return inspectSymbol(value, depth, opts)
  if (type.isObject()) return inspectObject(type, value, depth, opts)
  if (type.isFunction()) return inspectFunction(type, value, depth, opts)
  if (type.isExternal()) return inspectExternal(value, opts, opts)
}

function inspectUndefined(depth, opts) {
  return new InspectLeaf('undefined', styles.undefined, depth, opts)
}

function inspectNull(depth, opts) {
  return new InspectLeaf('null', styles.null, depth, opts)
}

function inspectBoolean(value, depth, opts) {
  return new InspectLeaf(value.toString(), styles.boolean, depth, opts)
}

function inspectNumber(value, depth, opts) {
  let string

  if (Object.is(value, -0)) {
    string = '-0'
  } else {
    string = value.toString(10)
  }

  return new InspectLeaf(string, styles.number, depth, opts)
}

function inspectBigInt(value, depth, opts) {
  return new InspectLeaf(value.toString(10) + 'n', styles.bigint, depth, opts)
}

const STRING_ESCAPES =
  /[\ud800-\udbff][\udc00-\udfff]|[\u0000-\u001f'\\\ud800-\udfff]/g

function inspectString(value, depth, opts) {
  // https://tc39.es/ecma262/multipage/structured-data.html#sec-quotejsonstring
  const string = value.replace(STRING_ESCAPES, (match) => {
    if (match.length === 2) return match

    switch (match) {
      case "'":
        return "\\'"
      case '\\':
        return '\\\\'
      case '\b':
        return '\\b'
      case '\t':
        return '\\t'
      case '\n':
        return '\\n'
      case '\f':
        return '\\f'
      case '\r':
        return '\\r'
      default:
        return '\\u' + match.charCodeAt(0).toString(16).padStart(4, '0')
    }
  })

  return new InspectLeaf("'" + string + "'", styles.string, depth, opts)
}

function inspectSymbol(value, depth, opts) {
  return new InspectLeaf(value.toString(), styles.symbol, depth, opts)
}

function inspectKey(value, depth, opts) {
  if (PLAIN_KEY.test(value)) {
    return new InspectLeaf(value, null, depth, opts)
  } else {
    return inspectValue(value, depth, opts)
  }
}

function inspectObject(type, object, depth, opts) {
  const refs = opts.references

  let ref = refs.get(object)
  if (ref === null) {
    ref = new InspectRef(depth, opts)
    refs.set(object, ref)
  } else if (ref.count) {
    ref.circular = true
    return ref
  }

  const maxDepth = typeof opts.depth === 'number' ? opts.depth : Infinity

  if (maxDepth < depth) {
    const constructor = object.constructor

    return new InspectLeaf(
      '[' +
        (constructor && constructor.name ? constructor.name : 'Object') +
        ']',
      styles.special,
      depth,
      opts
    )
  }

  const inspect =
    object[Symbol.for('bare.inspect')] ||
    object[Symbol.for('nodejs.util.inspect.custom')]

  if (typeof inspect === 'function') {
    const value = inspect.call(
      object,
      typeof opts.depth === 'number' ? opts.depth - depth : null,
      {
        colors: opts.colors,
        breakLength: opts.breakLength,
        stylize: opts.stylize
      },
      exports
    )

    if (typeof value === 'object' && value !== null) {
      refs.set(value, ref)
    }

    if (typeof value !== 'string') {
      return inspectValue(value, depth, opts)
    }

    return new InspectLeaf(value, null, depth, opts)
  }

  if (type.isArray()) return inspectArray(object, ref, depth, opts)
  if (type.isDate()) return inspectDate(object, ref, depth, opts)
  if (type.isRegExp()) return inspectRegExp(object, ref, depth, opts)
  if (type.isError()) return inspectError(object, ref, depth, opts)
  if (type.isPromise()) return inspectPromise(object, ref, depth, opts)
  if (type.isMap()) return inspectMap(object, ref, depth, opts)
  if (type.isSet()) return inspectSet(object, ref, depth, opts)
  if (type.isWeakMap()) return inspectWeakMap(object, ref, depth, opts)
  if (type.isWeakSet()) return inspectWeakSet(object, ref, depth, opts)
  if (type.isWeakRef()) return inspectWeakRef(object, ref, depth, opts)
  if (type.isArrayBuffer()) return inspectArrayBuffer(object, ref, depth, opts)
  if (type.isSharedArrayBuffer())
    return inspectSharedArrayBuffer(object, ref, depth, opts)
  if (type.isTypedArray()) return inspectTypedArray(object, ref, depth, opts)
  if (type.isDataView()) return inspectDataView(object, ref, depth, opts)

  ref.increment()

  const values = []

  for (const key in object) {
    if (key === 'constructor') continue

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(object[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  let header = '{ '

  const tag = object[Symbol.toStringTag]

  if (tag) header = '[' + tag + '] ' + header

  if (object.constructor) {
    const name = object.constructor.name

    if (name && name !== 'Object') {
      header = object.constructor.name + ' ' + header
    }
  }

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectArray(array, ref, depth, opts) {
  const { maxArrayLength = defaultMaxArrayLength } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxArrayLength, 0)

  for (let i = 0, n = array.length; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(array.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(inspectValue(array[i], depth + 1, opts))
  }

  for (const key of binding.getOwnNonIndexPropertyNames(array)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(array[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  let header = '[ '

  if (array.constructor.name !== 'Array') {
    header = array.constructor.name + '(' + array.length + ') ' + header
  }

  return new InspectSequence(header, ' ]', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectDate(date, ref, depth, opts) {
  return new InspectLeaf(date.toISOString(), styles.date, depth, opts)
}

function inspectRegExp(regExp, ref, depth, opts) {
  return new InspectLeaf(regExp.toString(), styles.regexp, depth, opts)
}

function inspectError(error, ref, depth, opts) {
  let header

  if ('stack' in error) {
    header = error.stack

    if (depth > 0) {
      header = header.replaceAll('\n', '\n' + '  '.repeat(depth))
    }
  } else {
    header = error.toString()
  }

  const builtins = ['cause']

  if (error.name === 'AggregateError') {
    builtins.push('errors')
  } else if (error.name === 'SuppressedError') {
    builtins.push('error', 'suppressed')
  }

  const values = []

  for (const key of builtins) {
    if (key in error === false) continue

    values.push(
      new InspectPair(
        ': ',
        new InspectLeaf('[' + key + ']', null, depth + 1, opts),
        inspectValue(error[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key in error) {
    if (key === 'constructor' || builtins.includes(key)) continue

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(error[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  if (values.length === 0) return new InspectLeaf(header, null, depth, opts)

  return new InspectSequence(
    header + ' {',
    ' }',
    ', ',
    values,
    ref,
    depth,
    opts
  )
}

function inspectPromise(promise, ref, depth, opts) {
  ref.increment()

  const state = binding.getPromiseState(promise)

  const values = []

  switch (state) {
    case 0: // Pending
      values.push(new InspectLeaf('<pending>', styles.special, depth, opts))
      break

    case 1: // Fulfilled
      values.push(inspectValue(binding.getPromiseResult(promise), depth, opts))
      break

    case 2: // Rejected
      values.push(
        new InspectLeaf('<rejected>', styles.special, depth, opts),
        inspectValue(binding.getPromiseResult(promise), depth, opts)
      )
  }

  ref.decrement()

  const header = promise.constructor.name + ' { '

  return new InspectSequence(header, ' }', ' ', values, ref, depth, opts)
}

function inspectMap(map, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxMapLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = maxMapLength

  for (const entry of map) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(map.size - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )
      break
    }

    values.push(
      new InspectPair(
        ' => ',
        inspectValue(entry[0], depth + 1, opts),
        inspectValue(entry[1], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key in map) {
    if (key === 'constructor') continue

    const value = inspectValue(map[key], depth + 1, opts)

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        value,
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = map.constructor.name + '(' + map.size + ') { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectSet(set, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxSetLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = maxSetLength

  for (const entry of set) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(set.size - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )
      break
    }

    values.push(inspectValue(entry, depth + 1, opts))
  }

  for (const key in set) {
    if (key === 'constructor') continue

    const value = inspectValue(set[key], depth + 1, opts)

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        value,
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = set.constructor.name + '(' + set.size + ') { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectWeakMap(weakMap, ref, depth, opts) {
  const header = weakMap.constructor.name + ' { '

  return new InspectSequence(
    header,
    ' }',
    ' ',
    [new InspectLeaf('<items unknown>', styles.special, depth + 1, opts)],
    ref,
    depth,
    opts
  )
}

function inspectWeakSet(weakSet, ref, depth, opts) {
  const header = weakSet.constructor.name + ' { '

  return new InspectSequence(
    header,
    ' }',
    ' ',
    [new InspectLeaf('<items unknown>', styles.special, depth + 1, opts)],
    ref,
    depth,
    opts
  )
}

function inspectWeakRef(weakRef, ref, depth, opts) {
  const target = weakRef.deref()

  let value

  if (target === undefined) {
    value = new InspectLeaf('<cleared>', styles.special, depth + 1, opts)
  } else {
    value = inspectValue(target, depth + 1, opts)
  }

  const header = weakRef.constructor.name + ' { '

  return new InspectSequence(header, ' }', ' ', [value], ref, depth, opts)
}

function inspectArrayBuffer(arrayBuffer, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(arrayBuffer[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = arrayBuffer.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectSharedArrayBuffer(sharedArrayBuffer, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(sharedArrayBuffer[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = sharedArrayBuffer.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectTypedArray(typedArray, ref, depth, opts) {
  if (Buffer.isBuffer(typedArray)) {
    return inspectBuffer(typedArray, ref, depth, opts)
  }

  const {
    maxArrayLength = defaultMaxArrayLength,
    maxTypedArrayLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxTypedArrayLength, 0)

  for (let i = 0, n = typedArray.length; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(typedArray.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(inspectValue(typedArray[i], depth + 1, opts))
  }

  for (const key of binding.getOwnNonIndexPropertyNames(typedArray)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(typedArray[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = typedArray.constructor.name + '(' + typedArray.length + ') [ '

  return new InspectSequence(header, ' ]', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectBuffer(buffer, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxBufferLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxBufferLength, 0)

  for (let i = 0, n = buffer.byteLength; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(buffer.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(
      new InspectLeaf(
        buffer[i].toString(16).padStart(2, '0'),
        null,
        depth + 1,
        opts
      )
    )
  }

  for (const key of binding.getOwnNonIndexPropertyNames(buffer)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(buffer[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  return new InspectSequence('<Buffer ', '>', ' ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectDataView(dataView, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength', 'byteOffset', 'buffer']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(dataView[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key of binding.getOwnNonIndexPropertyNames(dataView)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(dataView[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = dataView.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectFunction(type, fn, depth, opts) {
  if (fn.toString().startsWith('class')) return inspectClass(fn, depth, opts)

  let tag = 'function'

  if (type.isGeneratorFunction()) tag = 'generator ' + tag
  if (type.isAsyncFunction()) tag = 'async ' + tag

  return new InspectLeaf(
    '[' + tag + ' ' + (fn.name ? fn.name : '(anonymous)') + ']',
    styles.special,
    depth,
    opts
  )
}

function inspectClass(ctor, depth, opts) {
  return new InspectLeaf(
    '[class ' + (ctor.name ? ctor.name : '(anonymous)') + ']',
    styles.special,
    depth,
    opts
  )
}

function inspectExternal(external, depth, opts) {
  return new InspectLeaf(
    '[external 0x' + binding.getExternal(external).toString(16) + ']',
    styles.special,
    depth,
    opts
  )
}
{
  "name": "bare-inspect",
  "version": "3.1.4",
  "description": "Inspect objects as strings for debugging",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-inspect.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-inspect/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-inspect#readme",
  "engines": {
    "bare": ">=1.18.0"
  },
  "dependencies": {
    "bare-ansi-escapes": "^2.1.0",
    "bare-type": "^1.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
module.exports = require.addon()
const binding = require('./binding')
const errors = require('./lib/errors')
const constants = require('./lib/constants')

exports.constants = constants
exports.errors = errors

exports.EOL = binding.platform === 'win32' ? '\r\n' : '\n'

exports.devNull = binding.platform === 'win32' ? '\\\\.\\nul' : '/dev/null'

exports.platform = function platform() {
  return binding.platform
}

exports.arch = function arch() {
  return binding.arch
}

exports.type = function type() {
  return binding.type()
}

exports.version = function version() {
  return binding.version()
}

exports.release = function release() {
  return binding.release()
}

exports.machine = function machine() {
  return binding.machine()
}

exports.execPath = function execPath() {
  return binding.execPath()
}

exports.pid = function pid() {
  return binding.pid()
}

exports.ppid = function ppid() {
  return binding.ppid()
}

exports.cwd = function cwd() {
  return binding.cwd()
}

exports.chdir = function chdir(dir) {
  validateString(dir, 'Directory')

  binding.chdir(dir)
}

exports.tmpdir = function tmpdir() {
  return binding.tmpdir()
}

exports.homedir = function homedir() {
  return binding.homedir()
}

exports.hostname = function hostname() {
  return binding.hostname()
}

exports.userInfo = function userInfo(uid) {
  if (uid !== undefined) validateInteger(uid, 'User ID')

  return binding.userInfo(uid)
}

exports.groupInfo = function groupInfo(gid) {
  if (gid !== undefined) validateInteger(gid, 'Group ID')

  return binding.groupInfo(gid)
}

exports.networkInterfaces = function networkInterfaces() {
  const result = {}

  for (const entry of binding.networkInterfaces()) {
    const { name, ...properties } = entry

    if (result[name]) result[name].push(properties)
    else result[name] = [properties]
  }

  return result
}

exports.kill = function kill(pid, signal = constants.signals.SIGTERM) {
  validateInteger(pid, 'Process ID')

  if (typeof signal === 'string') {
    if (signal in constants.signals === false) {
      throw errors.UNKNOWN_SIGNAL('Unknown signal: ' + signal)
    }

    signal = constants.signals[signal]
  } else {
    validateInteger(signal, 'Signal')
  }

  binding.kill(pid, signal)
}

exports.endianness = function endianness() {
  return binding.isLittleEndian ? 'LE' : 'BE'
}

exports.availableParallelism = function availableParallelism() {
  return binding.availableParallelism()
}

exports.cpuUsage = function cpuUsage(previous) {
  const current = binding.cpuUsage()

  if (previous) {
    return {
      user: current.user - previous.user,
      system: current.system - previous.system
    }
  }

  return current
}

exports.threadCpuUsage = function threadCpuUsage(previous) {
  const current = binding.threadCpuUsage()

  if (previous) {
    return {
      user: current.user - previous.user,
      system: current.system - previous.system
    }
  }

  return current
}

exports.resourceUsage = function resourceUsage() {
  return binding.resourceUsage()
}

exports.memoryUsage = function memoryUsage() {
  return binding.memoryUsage()
}

exports.freemem = function freemem() {
  return binding.freemem()
}

exports.totalmem = function totalmem() {
  return binding.totalmem()
}

exports.availableMemory = function availableMemory() {
  return binding.availableMemory()
}

exports.constrainedMemory = function constrainedMemory() {
  return binding.constrainedMemory()
}

exports.uptime = function uptime() {
  return binding.uptime()
}

exports.loadavg = function loadavg() {
  return binding.loadavg()
}

exports.cpus = function cpus() {
  return binding.cpus()
}

exports.getProcessTitle = function getProcessTitle() {
  return binding.getProcessTitle()
}

exports.setProcessTitle = function setProcessTitle(title) {
  if (typeof title !== 'string') title = title.toString()

  if (title.length >= 256) {
    throw errors.TITLE_OVERFLOW('Process title is too long')
  }

  binding.setProcessTitle(title)
}

exports.getPriority = function getPriority(pid = 0) {
  validateInteger(pid, 'Process ID')

  return binding.getPriority(pid)
}

exports.setPriority = function setPriority(pid, priority) {
  if (priority === undefined) {
    priority = pid
    pid = 0
  }

  validateInteger(pid, 'Process ID')
  validateInteger(priority, 'Priority')

  binding.setPriority(pid, priority)
}

exports.getEnvKeys = function getEnvKeys() {
  return binding.getEnvKeys()
}

exports.getEnv = function getEnv(name) {
  validateString(name, 'Name')

  return binding.getEnv(name)
}

exports.hasEnv = function hasEnv(name) {
  validateString(name, 'Name')

  return binding.hasEnv(name)
}

exports.setEnv = function setEnv(name, value) {
  validateString(name, 'Name')
  validateString(value, 'Value')

  binding.setEnv(name, value)
}

exports.unsetEnv = function unsetEnv(name) {
  validateString(name, 'Name')

  binding.unsetEnv(name)
}

function validateString(value, name) {
  if (typeof value !== 'string') {
    throw new TypeError(`${name} must be a string. Received type ${typeof value} (${value})`)
  }
}

function validateInteger(value, name) {
  if (!Number.isInteger(value)) {
    throw new TypeError(`${name} must be an integer. Received type ${typeof value} (${value})`)
  }
}
const binding = require('../binding')

module.exports = {
  signals: binding.signals,
  errnos: binding.errnos,
  priority: binding.priority
}
module.exports = class OSError extends Error {
  constructor(msg, fn = OSError, code = fn.name) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'OSError'
  }

  static UNKNOWN_SIGNAL(msg) {
    return new OSError(msg, OSError.UNKNOWN_SIGNAL)
  }

  static TITLE_OVERFLOW(msg) {
    return new OSError(msg, OSError.TITLE_OVERFLOW)
  }
}
{
  "name": "bare-os",
  "version": "3.9.3",
  "description": "Operating system utilities for Bare",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    },
    "./errors": {
      "types": "./lib/errors.d.ts",
      "default": "./lib/errors.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-os.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-os/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-os#readme",
  "engines": {
    "bare": ">=1.14.0"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "cmake-bare": "^1.1.6",
    "lunte": "^1.6.0",
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
// This export SHOULD NOT be shortened in any way as having the full
// `module.exports = require(...)` statement is crucial for synthesizing
// ESM exports.

if (Bare.platform === 'win32') {
  module.exports = require('./lib/win32')
} else {
  module.exports = require('./lib/posix')
}
module.exports = {
  CHAR_UPPERCASE_A: 0x41,
  CHAR_LOWERCASE_A: 0x61,
  CHAR_UPPERCASE_Z: 0x5a,
  CHAR_LOWERCASE_Z: 0x7a,
  CHAR_DOT: 0x2e,
  CHAR_FORWARD_SLASH: 0x2f,
  CHAR_BACKWARD_SLASH: 0x5c,
  CHAR_COLON: 0x3a,
  CHAR_QUESTION_MARK: 0x3f
}
const os = require('bare-os')

const { normalizeString } = require('./shared')
const { CHAR_DOT, CHAR_FORWARD_SLASH } = require('./constants')

function isPosixPathSeparator(code) {
  return code === CHAR_FORWARD_SLASH
}

exports.win32 = require('./win32')
exports.posix = exports

exports.sep = '/'
exports.delimiter = ':'

exports.resolve = function resolve(...args) {
  let resolvedPath = ''
  let resolvedAbsolute = false

  for (let i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) {
    const path = i >= 0 ? args[i] : os.cwd()

    if (path.length === 0) {
      continue
    }

    resolvedPath = `${path}/${resolvedPath}`
    resolvedAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH
  }

  resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute, '/', isPosixPathSeparator)

  if (resolvedAbsolute) {
    return `/${resolvedPath}`
  }

  return resolvedPath.length > 0 ? resolvedPath : '.'
}

exports.normalize = function normalize(path) {
  if (path.length === 0) return '.'

  const isAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH
  const trailingSeparator = path.charCodeAt(path.length - 1) === CHAR_FORWARD_SLASH

  path = normalizeString(path, !isAbsolute, '/', isPosixPathSeparator)

  if (path.length === 0) {
    if (isAbsolute) return '/'
    return trailingSeparator ? './' : '.'
  }

  if (trailingSeparator) path += '/'

  return isAbsolute ? `/${path}` : path
}

exports.isAbsolute = function isAbsolute(path) {
  return path.length > 0 && path.charCodeAt(0) === CHAR_FORWARD_SLASH
}

exports.join = function join(...args) {
  if (args.length === 0) return '.'
  let joined
  for (let i = 0; i < args.length; ++i) {
    const arg = args[i]
    if (arg.length > 0) {
      if (joined === undefined) joined = arg
      else joined += `/${arg}`
    }
  }
  if (joined === undefined) return '.'
  return exports.normalize(joined)
}

exports.relative = function relative(from, to) {
  if (from === to) return ''

  from = exports.resolve(from)
  to = exports.resolve(to)

  if (from === to) return ''

  const fromStart = 1
  const fromEnd = from.length
  const fromLen = fromEnd - fromStart
  const toStart = 1
  const toLen = to.length - toStart

  const length = fromLen < toLen ? fromLen : toLen
  let lastCommonSep = -1
  let i = 0
  for (; i < length; i++) {
    const fromCode = from.charCodeAt(fromStart + i)
    if (fromCode !== to.charCodeAt(toStart + i)) {
      break
    } else if (fromCode === CHAR_FORWARD_SLASH) {
      lastCommonSep = i
    }
  }
  if (i === length) {
    if (toLen > length) {
      if (to.charCodeAt(toStart + i) === CHAR_FORWARD_SLASH) {
        return to.substring(toStart + i + 1)
      }
      if (i === 0) {
        return to.substring(toStart + i)
      }
    } else if (fromLen > length) {
      if (from.charCodeAt(fromStart + i) === CHAR_FORWARD_SLASH) {
        lastCommonSep = i
      } else if (i === 0) {
        lastCommonSep = 0
      }
    }
  }

  let out = ''
  for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
    if (i === fromEnd || from.charCodeAt(i) === CHAR_FORWARD_SLASH) {
      out += out.length === 0 ? '..' : '/..'
    }
  }

  return `${out}${to.substring(toStart + lastCommonSep)}`
}

exports.toNamespacedPath = function toNamespacedPath(path) {
  return path
}

exports.dirname = function dirname(path) {
  if (path.length === 0) return '.'
  const hasRoot = path.charCodeAt(0) === CHAR_FORWARD_SLASH
  let end = -1
  let matchedSlash = true
  for (let i = path.length - 1; i >= 1; --i) {
    if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) {
      if (!matchedSlash) {
        end = i
        break
      }
    } else {
      matchedSlash = false
    }
  }

  if (end === -1) return hasRoot ? '/' : '.'
  if (hasRoot && end === 1) return '//'
  return path.substring(0, end)
}

exports.basename = function basename(path, suffix) {
  let start = 0
  let end = -1
  let matchedSlash = true

  if (suffix !== undefined && suffix.length > 0 && suffix.length <= path.length) {
    if (suffix === path) {
      return ''
    }
    let extIdx = suffix.length - 1
    let firstNonSlashEnd = -1
    for (let i = path.length - 1; i >= 0; --i) {
      const code = path.charCodeAt(i)
      if (code === CHAR_FORWARD_SLASH) {
        if (!matchedSlash) {
          start = i + 1
          break
        }
      } else {
        if (firstNonSlashEnd === -1) {
          matchedSlash = false
          firstNonSlashEnd = i + 1
        }
        if (extIdx >= 0) {
          if (code === suffix.charCodeAt(extIdx)) {
            if (--extIdx === -1) {
              end = i
            }
          } else {
            extIdx = -1
            end = firstNonSlashEnd
          }
        }
      }
    }

    if (start === end) end = firstNonSlashEnd
    else if (end === -1) end = path.length
    return path.substring(start, end)
  }

  for (let i = path.length - 1; i >= 0; --i) {
    if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) {
      if (!matchedSlash) {
        start = i + 1
        break
      }
    } else if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
  }

  if (end === -1) return ''
  return path.substring(start, end)
}

exports.extname = function extname(path) {
  let startDot = -1
  let startPart = 0
  let end = -1
  let matchedSlash = true
  let preDotState = 0
  for (let i = path.length - 1; i >= 0; --i) {
    const code = path.charCodeAt(i)
    if (code === CHAR_FORWARD_SLASH) {
      if (!matchedSlash) {
        startPart = i + 1
        break
      }
      continue
    }
    if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
    if (code === CHAR_DOT) {
      if (startDot === -1) startDot = i
      else if (preDotState !== 1) preDotState = 1
    } else if (startDot !== -1) {
      preDotState = -1
    }
  }

  if (
    startDot === -1 ||
    end === -1 ||
    preDotState === 0 ||
    (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1)
  ) {
    return ''
  }
  return path.substring(startDot, end)
}
const { CHAR_DOT, CHAR_FORWARD_SLASH } = require('./constants')

exports.normalizeString = function normalizeString(
  path,
  allowAboveRoot,
  separator,
  isPathSeparator
) {
  let res = ''
  let lastSegmentLength = 0
  let lastSlash = -1
  let dots = 0
  let code = 0
  for (let i = 0; i <= path.length; ++i) {
    if (i < path.length) {
      code = path.charCodeAt(i)
    } else if (isPathSeparator(code)) {
      break
    } else {
      code = CHAR_FORWARD_SLASH
    }

    if (isPathSeparator(code)) {
      if (lastSlash === i - 1 || dots === 1);
      else if (dots === 2) {
        if (
          res.length < 2 ||
          lastSegmentLength !== 2 ||
          res.charCodeAt(res.length - 1) !== CHAR_DOT ||
          res.charCodeAt(res.length - 2) !== CHAR_DOT
        ) {
          if (res.length > 2) {
            const lastSlashIndex = res.lastIndexOf(separator)
            if (lastSlashIndex === -1) {
              res = ''
              lastSegmentLength = 0
            } else {
              res = res.substring(0, lastSlashIndex)
              lastSegmentLength = res.length - 1 - res.lastIndexOf(separator)
            }
            lastSlash = i
            dots = 0
            continue
          } else if (res.length !== 0) {
            res = ''
            lastSegmentLength = 0
            lastSlash = i
            dots = 0
            continue
          }
        }
        if (allowAboveRoot) {
          res += res.length > 0 ? `${separator}..` : '..'
          lastSegmentLength = 2
        }
      } else {
        if (res.length > 0) {
          res += `${separator}${path.substring(lastSlash + 1, i)}`
        } else {
          res = path.substring(lastSlash + 1, i)
        }
        lastSegmentLength = i - lastSlash - 1
      }
      lastSlash = i
      dots = 0
    } else if (code === CHAR_DOT && dots !== -1) {
      ++dots
    } else {
      dots = -1
    }
  }
  return res
}
const os = require('bare-os')

const { normalizeString } = require('./shared')
const {
  CHAR_UPPERCASE_A,
  CHAR_LOWERCASE_A,
  CHAR_UPPERCASE_Z,
  CHAR_LOWERCASE_Z,
  CHAR_DOT,
  CHAR_FORWARD_SLASH,
  CHAR_BACKWARD_SLASH,
  CHAR_COLON,
  CHAR_QUESTION_MARK
} = require('./constants')

function isWindowsPathSeparator(code) {
  return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH
}

function isWindowsDeviceRoot(code) {
  return (
    (code >= CHAR_UPPERCASE_A && code <= CHAR_UPPERCASE_Z) ||
    (code >= CHAR_LOWERCASE_A && code <= CHAR_LOWERCASE_Z)
  )
}

exports.posix = require('./posix')
exports.win32 = exports

exports.sep = '\\'
exports.delimiter = ';'

exports.resolve = function resolve(...args) {
  let resolvedDevice = ''
  let resolvedTail = ''
  let resolvedAbsolute = false

  for (let i = args.length - 1; i >= -1; i--) {
    let path
    if (i >= 0) {
      path = args[i]

      if (path.length === 0) continue
    } else if (resolvedDevice.length === 0) {
      path = os.cwd()
    } else {
      path = os.getEnv(`=${resolvedDevice}`) || os.cwd()

      if (
        path === undefined ||
        (path.substring(0, 2).toLowerCase() !== resolvedDevice.toLowerCase() &&
          path.charCodeAt(2) === CHAR_BACKWARD_SLASH)
      ) {
        path = `${resolvedDevice}\\`
      }
    }

    const len = path.length
    let rootEnd = 0
    let device = ''
    let isAbsolute = false
    const code = path.charCodeAt(0)

    if (len === 1) {
      if (isWindowsPathSeparator(code)) {
        rootEnd = 1
        isAbsolute = true
      }
    } else if (isWindowsPathSeparator(code)) {
      isAbsolute = true

      if (isWindowsPathSeparator(path.charCodeAt(1))) {
        let j = 2
        let last = j
        while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
          j++
        }
        if (j < len && j !== last) {
          const firstPart = path.substring(last, j)
          last = j
          while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
            j++
          }
          if (j < len && j !== last) {
            last = j
            while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
              j++
            }
            if (j === len || j !== last) {
              device = `\\\\${firstPart}\\${path.substring(last, j)}`
              rootEnd = j
            }
          }
        }
      } else {
        rootEnd = 1
      }
    } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
      device = path.substring(0, 2)
      rootEnd = 2
      if (len > 2 && isWindowsPathSeparator(path.charCodeAt(2))) {
        isAbsolute = true
        rootEnd = 3
      }
    }

    if (device.length > 0) {
      if (resolvedDevice.length > 0) {
        if (device.toLowerCase() !== resolvedDevice.toLowerCase()) {
          continue
        }
      } else {
        resolvedDevice = device
      }
    }

    if (resolvedAbsolute) {
      if (resolvedDevice.length > 0) {
        break
      }
    } else {
      resolvedTail = `${path.substring(rootEnd)}\\${resolvedTail}`
      resolvedAbsolute = isAbsolute
      if (isAbsolute && resolvedDevice.length > 0) {
        break
      }
    }
  }

  resolvedTail = normalizeString(resolvedTail, !resolvedAbsolute, '\\', isWindowsPathSeparator)

  return resolvedAbsolute
    ? `${resolvedDevice}\\${resolvedTail}`
    : `${resolvedDevice}${resolvedTail}` || '.'
}

exports.normalize = function normalize(path) {
  const len = path.length
  if (len === 0) return '.'
  let rootEnd = 0
  let device
  let isAbsolute = false
  const code = path.charCodeAt(0)

  if (len === 1) {
    return code === CHAR_FORWARD_SLASH ? '\\' : path
  }

  if (isWindowsPathSeparator(code)) {
    isAbsolute = true

    if (isWindowsPathSeparator(path.charCodeAt(1))) {
      let j = 2
      let last = j
      while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
        j++
      }
      if (j < len && j !== last) {
        const firstPart = path.substring(last, j)
        last = j
        while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
          j++
        }
        if (j < len && j !== last) {
          last = j
          while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
            j++
          }
          if (j === len) {
            return `\\\\${firstPart}\\${path.substring(last)}\\`
          }
          if (j !== last) {
            device = `\\\\${firstPart}\\${path.substring(last, j)}`
            rootEnd = j
          }
        }
      }
    } else {
      rootEnd = 1
    }
  } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
    device = path.substring(0, 2)
    rootEnd = 2
    if (len > 2 && isWindowsPathSeparator(path.charCodeAt(2))) {
      isAbsolute = true
      rootEnd = 3
    }
  }

  let tail =
    rootEnd < len
      ? normalizeString(path.substring(rootEnd), !isAbsolute, '\\', isWindowsPathSeparator)
      : ''
  if (tail.length === 0 && !isAbsolute) {
    tail = '.'
  }
  if (tail.length > 0 && isWindowsPathSeparator(path.charCodeAt(len - 1))) {
    tail += '\\'
  }
  if (device === undefined) {
    return isAbsolute ? `\\${tail}` : tail
  }
  return isAbsolute ? `${device}\\${tail}` : `${device}${tail}`
}

exports.isAbsolute = function isAbsolute(path) {
  const len = path.length
  if (len === 0) return false

  const code = path.charCodeAt(0)

  return (
    isWindowsPathSeparator(code) ||
    (len > 2 &&
      isWindowsDeviceRoot(code) &&
      path.charCodeAt(1) === CHAR_COLON &&
      isWindowsPathSeparator(path.charCodeAt(2)))
  )
}

exports.join = function join(...args) {
  if (args.length === 0) return '.'

  let joined
  let firstPart
  for (let i = 0; i < args.length; ++i) {
    const arg = args[i]
    if (arg.length > 0) {
      if (joined === undefined) joined = firstPart = arg
      else joined += `\\${arg}`
    }
  }

  if (joined === undefined) return '.'

  let needsReplace = true
  let slashCount = 0
  if (isWindowsPathSeparator(firstPart.charCodeAt(0))) {
    ++slashCount
    const firstLen = firstPart.length
    if (firstLen > 1 && isWindowsPathSeparator(firstPart.charCodeAt(1))) {
      ++slashCount
      if (firstLen > 2) {
        if (isWindowsPathSeparator(firstPart.charCodeAt(2))) {
          ++slashCount
        } else {
          needsReplace = false
        }
      }
    }
  }
  if (needsReplace) {
    while (slashCount < joined.length && isWindowsPathSeparator(joined.charCodeAt(slashCount))) {
      slashCount++
    }

    if (slashCount >= 2) {
      joined = `\\${joined.substring(slashCount)}`
    }
  }

  return exports.normalize(joined)
}

exports.relative = function relative(from, to) {
  if (from === to) return ''

  const fromOrig = exports.resolve(from)
  const toOrig = exports.resolve(to)

  if (fromOrig === toOrig) return ''

  from = fromOrig.toLowerCase()
  to = toOrig.toLowerCase()

  if (from === to) return ''

  let fromStart = 0
  while (fromStart < from.length && from.charCodeAt(fromStart) === CHAR_BACKWARD_SLASH) {
    fromStart++
  }
  let fromEnd = from.length
  while (fromEnd - 1 > fromStart && from.charCodeAt(fromEnd - 1) === CHAR_BACKWARD_SLASH) {
    fromEnd--
  }
  const fromLen = fromEnd - fromStart

  let toStart = 0
  while (toStart < to.length && to.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) {
    toStart++
  }
  let toEnd = to.length
  while (toEnd - 1 > toStart && to.charCodeAt(toEnd - 1) === CHAR_BACKWARD_SLASH) {
    toEnd--
  }
  const toLen = toEnd - toStart

  const length = fromLen < toLen ? fromLen : toLen
  let lastCommonSep = -1
  let i = 0
  for (; i < length; i++) {
    const fromCode = from.charCodeAt(fromStart + i)
    if (fromCode !== to.charCodeAt(toStart + i)) {
      break
    } else if (fromCode === CHAR_BACKWARD_SLASH) {
      lastCommonSep = i
    }
  }

  if (i !== length) {
    if (lastCommonSep === -1) return toOrig
  } else {
    if (toLen > length) {
      if (to.charCodeAt(toStart + i) === CHAR_BACKWARD_SLASH) {
        return toOrig.substring(toStart + i + 1)
      }
      if (i === 2) {
        return toOrig.substring(toStart + i)
      }
    }
    if (fromLen > length) {
      if (from.charCodeAt(fromStart + i) === CHAR_BACKWARD_SLASH) {
        lastCommonSep = i
      } else if (i === 2) {
        lastCommonSep = 3
      }
    }
    if (lastCommonSep === -1) lastCommonSep = 0
  }

  let out = ''
  for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
    if (i === fromEnd || from.charCodeAt(i) === CHAR_BACKWARD_SLASH) {
      out += out.length === 0 ? '..' : '\\..'
    }
  }

  toStart += lastCommonSep

  if (out.length > 0) {
    return `${out}${toOrig.substring(toStart, toEnd)}`
  }
  if (toOrig.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) {
    ++toStart
  }
  return toOrig.substring(toStart, toEnd)
}

exports.toNamespacedPath = function toNamespacedPath(path) {
  if (path.length === 0) return path

  const resolvedPath = exports.resolve(path)

  if (resolvedPath.length <= 2) return path

  if (resolvedPath.charCodeAt(0) === CHAR_BACKWARD_SLASH) {
    if (resolvedPath.charCodeAt(1) === CHAR_BACKWARD_SLASH) {
      const code = resolvedPath.charCodeAt(2)
      if (code !== CHAR_QUESTION_MARK && code !== CHAR_DOT) {
        return `\\\\?\\UNC\\${resolvedPath.substring(2)}`
      }
    }
  } else if (
    isWindowsDeviceRoot(resolvedPath.charCodeAt(0)) &&
    resolvedPath.charCodeAt(1) === CHAR_COLON &&
    resolvedPath.charCodeAt(2) === CHAR_BACKWARD_SLASH
  ) {
    return `\\\\?\\${resolvedPath}`
  }

  return path
}

exports.dirname = function dirname(path) {
  const len = path.length
  if (len === 0) return '.'
  let rootEnd = -1
  let offset = 0
  const code = path.charCodeAt(0)

  if (len === 1) {
    return isWindowsPathSeparator(code) ? path : '.'
  }

  if (isWindowsPathSeparator(code)) {
    rootEnd = offset = 1

    if (isWindowsPathSeparator(path.charCodeAt(1))) {
      let j = 2
      let last = j
      while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
        j++
      }
      if (j < len && j !== last) {
        last = j
        while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
          j++
        }
        if (j < len && j !== last) {
          last = j
          while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
            j++
          }
          if (j === len) {
            return path
          }
          if (j !== last) {
            rootEnd = offset = j + 1
          }
        }
      }
    }
  } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
    rootEnd = len > 2 && isWindowsPathSeparator(path.charCodeAt(2)) ? 3 : 2
    offset = rootEnd
  }

  let end = -1
  let matchedSlash = true
  for (let i = len - 1; i >= offset; --i) {
    if (isWindowsPathSeparator(path.charCodeAt(i))) {
      if (!matchedSlash) {
        end = i
        break
      }
    } else {
      matchedSlash = false
    }
  }

  if (end === -1) {
    if (rootEnd === -1) return '.'

    end = rootEnd
  }
  return path.substring(0, end)
}

exports.basename = function basename(path, suffix) {
  let start = 0
  let end = -1
  let matchedSlash = true

  if (
    path.length >= 2 &&
    isWindowsDeviceRoot(path.charCodeAt(0)) &&
    path.charCodeAt(1) === CHAR_COLON
  ) {
    start = 2
  }

  if (suffix !== undefined && suffix.length > 0 && suffix.length <= path.length) {
    if (suffix === path) return ''
    let extIdx = suffix.length - 1
    let firstNonSlashEnd = -1
    for (let i = path.length - 1; i >= start; --i) {
      const code = path.charCodeAt(i)
      if (isWindowsPathSeparator(code)) {
        if (!matchedSlash) {
          start = i + 1
          break
        }
      } else {
        if (firstNonSlashEnd === -1) {
          matchedSlash = false
          firstNonSlashEnd = i + 1
        }
        if (extIdx >= 0) {
          if (code === suffix.charCodeAt(extIdx)) {
            if (--extIdx === -1) {
              end = i
            }
          } else {
            extIdx = -1
            end = firstNonSlashEnd
          }
        }
      }
    }

    if (start === end) end = firstNonSlashEnd
    else if (end === -1) end = path.length
    return path.substring(start, end)
  }
  for (let i = path.length - 1; i >= start; --i) {
    if (isWindowsPathSeparator(path.charCodeAt(i))) {
      if (!matchedSlash) {
        start = i + 1
        break
      }
    } else if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
  }

  if (end === -1) return ''
  return path.substring(start, end)
}

exports.extname = function extname(path) {
  let start = 0
  let startDot = -1
  let startPart = 0
  let end = -1
  let matchedSlash = true
  let preDotState = 0

  if (
    path.length >= 2 &&
    path.charCodeAt(1) === CHAR_COLON &&
    isWindowsDeviceRoot(path.charCodeAt(0))
  ) {
    start = startPart = 2
  }

  for (let i = path.length - 1; i >= start; --i) {
    const code = path.charCodeAt(i)
    if (isWindowsPathSeparator(code)) {
      if (!matchedSlash) {
        startPart = i + 1
        break
      }
      continue
    }
    if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
    if (code === CHAR_DOT) {
      if (startDot === -1) startDot = i
      else if (preDotState !== 1) preDotState = 1
    } else if (startDot !== -1) {
      preDotState = -1
    }
  }

  if (
    startDot === -1 ||
    end === -1 ||
    preDotState === 0 ||
    (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1)
  ) {
    return ''
  }
  return path.substring(startDot, end)
}
{
  "name": "bare-path",
  "version": "3.0.1",
  "description": "Path manipulation library for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./posix": "./lib/posix.js",
    "./win32": "./lib/win32.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "lib",
    "NOTICE"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-path.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-path/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-path#readme",
  "dependencies": {
    "bare-os": "^3.0.1"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "lunte": "^1.8.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
const b4a = require('b4a')
const stream = require('streamx')
const { ReadableStream, WritableStream } = require('./web')

const defaultEncoding = 'utf8'

module.exports = exports = stream.Stream

exports.pipeline = stream.pipeline

exports.isStream = stream.isStream
exports.isEnding = stream.isEnding
exports.isEnded = stream.isEnded
exports.isFinishing = stream.isFinishing
exports.isFinished = stream.isFinished
exports.isDisturbed = stream.isDisturbed

exports.isErrored = function isErrored(stream) {
  return exports.getStreamError(stream) !== null
}

exports.isReadable = function isReadable(stream) {
  return stream.readable && !stream.destroying && !exports.isEnded(stream)
}

exports.isWritable = function isWritable(stream) {
  return stream.writable && !stream.destroying && !exports.isFinishing(stream)
}

exports.getStreamError = stream.getStreamError

exports.addAbortSignal = function addAbortSignal(signal, stream) {
  function onAbort() {
    stream.destroy(signal.reason)
  }

  if (signal.aborted) onAbort()
  else signal.addEventListener('abort', onAbort)

  return stream
}

exports.Stream = exports

exports.Readable = class Readable extends stream.Readable {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthReadable: null,
      map: null,
      mapReadable: null
    })

    if (this._construct) this._open = this._construct

    if (this._read !== stream.Readable.prototype._read) {
      this._read = read.bind(this, this._read)
    }

    if (this._destroy !== stream.Stream.prototype._destroy) {
      this._destroy = destroy.bind(this, this._destroy)
    }
  }

  get closed() {
    return !exports.isReadable(this)
  }

  get errored() {
    return stream.getStreamError(this)
  }

  push(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    return super.push(chunk)
  }

  unshift(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    super.unshift(chunk)
  }

  static fromWeb(readableStream, opts = {}) {
    const stream = readableStream._stream

    if (opts.encoding) stream.setEncoding(opts.encoding)
    if (opts.signal) exports.addAbortSignal(opts.signal, stream)

    return stream
  }

  static toWeb(readable, opts = {}) {
    return new ReadableStream(readable, opts.strategy)
  }

  async [Symbol.asyncDispose]() {
    if (!this.destroyed) this.destroy()

    await new Promise((resolve) => exports.finished(this, resolve))
  }
}

exports.Writable = class Writable extends stream.Writable {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthWritable,
      map: null,
      mapWritable: null
    })

    if (this._construct) this._open = this._construct

    if (this._write !== stream.Writable.prototype._write) {
      this._write = write.bind(this, this._write)
    }

    if (this._destroy !== stream.Stream.prototype._destroy) {
      this._destroy = destroy.bind(this, this._destroy)
    }
  }

  get closed() {
    return !exports.isWritable(this)
  }

  get errored() {
    return stream.getStreamError(this)
  }

  write(chunk, encoding, cb) {
    if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result = super.write({ chunk, encoding })

    if (cb) stream.Writable.drained(this).then(() => cb(null), cb)

    return result
  }

  end(chunk, encoding, cb) {
    if (typeof chunk === 'function') {
      cb = chunk
      chunk = null
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    } else {
      encoding = 'buffer'
    }

    const result =
      chunk !== undefined && chunk !== null ? super.end({ chunk, encoding }) : super.end()

    if (cb) this.once('finish', () => cb(null))

    return result
  }

  static fromWeb(writableStream, opts = {}) {
    const stream = writableStream._stream

    if (opts.signal) exports.addAbortSignal(opts.signal, stream)

    return stream
  }

  static toWeb(writable) {
    return new WritableStream(writable)
  }

  async [Symbol.asyncDispose]() {
    if (!this.destroyed) this.destroy()

    await new Promise((resolve) => exports.finished(this, resolve))
  }
}

exports.Duplex = class Duplex extends stream.Duplex {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthReadable: null,
      byteLengthWritable,
      map: null,
      mapReadable: null,
      mapWritable: null
    })

    if (this._construct) this._open = this._construct

    if (this._read !== stream.Readable.prototype._read) {
      this._read = read.bind(this, this._read)
    }

    if (this._write !== stream.Duplex.prototype._write) {
      this._write = write.bind(this, this._write)
    }

    if (this._destroy !== stream.Stream.prototype._destroy) {
      this._destroy = destroy.bind(this, this._destroy)
    }
  }

  push(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    return super.push(chunk)
  }

  unshift(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    super.unshift(chunk)
  }

  write(chunk, encoding, cb) {
    if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result = super.write({ chunk, encoding })

    if (cb) stream.Writable.drained(this).then(() => cb(null), cb)

    return result
  }

  end(chunk, encoding, cb) {
    if (typeof chunk === 'function') {
      cb = chunk
      chunk = null
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result =
      chunk !== undefined && chunk !== null ? super.end({ chunk, encoding }) : super.end()

    if (cb) this.once('finish', () => cb(null))

    return result
  }

  static fromWeb({ readable: readableStream, writable: writableStream }, opts) {
    const readable = exports.Readable.fromWeb(readableStream, opts)
    const writable = exports.Writable.fromWeb(writableStream, opts)

    const duplex = new exports.Duplex({
      write(data, encoding, cb) {
        writable.write(data, encoding, cb)
      }
    })

    readable
      .on('data', (data) => duplex.push(data))
      .on('end', () => duplex.push(null))
      .on('error', (err) => duplex.destroy(err))

    writable.on('finish', () => duplex.end()).on('error', (err) => duplex.destroy(err))

    return duplex
  }

  static toWeb(duplex) {
    const readableStream = exports.Readable.toWeb(duplex)
    const writableStream = exports.Writable.toWeb(duplex)

    return { readable: readableStream, writable: writableStream }
  }
}

class DuplexSide extends exports.Duplex {
  constructor(opts) {
    super(opts)

    this._otherSide = null
    this._cb = null
  }

  _read() {
    const cb = this._cb
    if (!cb) return

    this._cb = null
    cb()
  }

  _write(chunk, encoding, cb) {
    this._otherSide.push(chunk, encoding)
    this._otherSide._cb = cb
  }

  _final(cb) {
    this._otherSide.on('end', cb)
    this._otherSide.push(null)
  }
}

exports.duplexPair = function duplexPair(opts) {
  const sideA = new DuplexSide(opts)
  const sideB = new DuplexSide(opts)

  sideA._otherSide = sideB
  sideB._otherSide = sideA

  return [sideA, sideB]
}

exports.Transform = class Transform extends stream.Transform {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthReadable: null,
      byteLengthWritable,
      map: null,
      mapReadable: null,
      mapWritable: null
    })

    if (this._transform !== stream.Transform.prototype._transform) {
      this._transform = transform.bind(this, this._transform)
    } else {
      this._transform = passthrough
    }
  }

  push(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    return super.push(chunk)
  }

  unshift(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    super.unshift(chunk)
  }

  write(chunk, encoding, cb) {
    if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result = super.write({ chunk, encoding })

    if (cb) stream.Writable.drained(this).then(() => cb(null), cb)

    return result
  }

  end(chunk, encoding, cb) {
    if (typeof chunk === 'function') {
      cb = chunk
      chunk = null
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result =
      chunk !== undefined && chunk !== null ? super.end({ chunk, encoding }) : super.end()

    if (cb) this.once('finish', () => cb(null))

    return result
  }
}

exports.PassThrough = class PassThrough extends exports.Transform {}

exports.finished = function finished(stream, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (!opts) opts = {}

  const { cleanup = false } = opts

  const done = () => {
    cb(exports.getStreamError(stream, { all: true }))

    if (cleanup) detach()
  }

  const detach = () => {
    stream.off('close', done)
    stream.off('error', noop)
  }

  if (stream.destroyed) {
    done()
  } else {
    stream.on('close', done)
    stream.on('error', noop)
  }

  return detach
}

function read(read, cb) {
  read.call(this, 65536)

  cb(null)
}

function write(write, data, cb) {
  write.call(this, data.chunk, data.encoding, cb)
}

function transform(transform, data, cb) {
  transform.call(this, data.chunk, data.encoding, cb)
}

function destroy(destroy, cb) {
  destroy.call(this, exports.getStreamError(this), cb)
}

function passthrough(data, cb) {
  cb(null, data.chunk)
}

function byteLengthWritable(data) {
  return data.chunk.byteLength
}

function noop() {}
{
  "name": "bare-stream",
  "version": "2.13.3",
  "description": "Streaming data for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./promises": "./promises.js",
    "./web": {
      "types": "./web.d.ts",
      "default": "./web.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "promises.js",
    "web.js",
    "web.d.ts",
    "global.js",
    "global.d.ts"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-stream.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-stream/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-stream#readme",
  "dependencies": {
    "b4a": "^1.8.1",
    "streamx": "^2.25.0",
    "teex": "^1.0.1"
  },
  "devDependencies": {
    "bare-abort-controller": "^1.1.0",
    "bare-buffer": "^3.0.0",
    "bare-events": "^2.5.4",
    "brittle": "^3.5.2",
    "lunte": "^1.6.0",
    "prettier": "^3.3.3",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "bare-abort-controller": "*",
    "bare-buffer": "*",
    "bare-events": "*"
  },
  "peerDependenciesMeta": {
    "bare-abort-controller": {
      "optional": true
    },
    "bare-buffer": {
      "optional": true
    },
    "bare-events": {
      "optional": true
    }
  }
}
const { Readable, Writable, Transform, getStreamError, isStreamx, isDisturbed } = require('streamx')
const tee = require('teex')

const readableKind = Symbol.for('bare.stream.readable.kind')
const writableKind = Symbol.for('bare.stream.writable.kind')
const transformKind = Symbol.for('bare.stream.transform.kind')

// https://streams.spec.whatwg.org/#readablestreamdefaultreader
exports.ReadableStreamDefaultReader = class ReadableStreamDefaultReader {
  constructor(stream) {
    this._stream = stream
    this._stream._stream.once('close', onclose).once('error', onerror)

    const closed = Promise.withResolvers()

    // Avoid unhandled exceptions
    closed.promise.catch(noop)

    this._closed = closed

    function onclose() {
      closed.resolve()
    }

    function onerror(err) {
      closed.reject(err)
    }
  }

  get closed() {
    return this._closed.promise
  }

  read() {
    const stream = this._stream._stream

    return new Promise((resolve, reject) => {
      const err = getStreamError(stream)

      if (err) return reject(err)

      if (stream.destroyed) {
        return resolve({ value: undefined, done: true })
      }

      const value = stream.read()

      if (value !== null) {
        return resolve({ value, done: false })
      }

      stream.once('readable', onreadable).once('close', onclose).once('error', onerror)

      function onreadable() {
        const value = stream.read()

        ondone(null, value === null ? { value: undefined, done: true } : { value, done: false })
      }

      function onclose() {
        ondone(null, { value: undefined, done: true })
      }

      function onerror(err) {
        ondone(err, null)
      }

      function ondone(err, value) {
        stream.off('readable', onreadable).off('close', onclose).off('error', onerror)

        if (err) reject(err)
        else resolve(value)
      }
    })
  }

  releaseLock() {
    this._closed.reject(new TypeError('Reader was released'))
    this._stream._releaseLock()
    this._stream = null
  }

  cancel(reason = new TypeError('Stream was cancelled')) {
    const stream = this._stream._stream

    if (stream.destroyed) return Promise.resolve()

    return new Promise((resolve) =>
      stream.once('close', resolve).once('error', noop).destroy(reason)
    )
  }
}

// https://streams.spec.whatwg.org/#readablestreamdefaultcontroller
exports.ReadableStreamDefaultController = class ReadableStreamDefaultController {
  constructor(stream) {
    this._stream = stream
  }

  get desiredSize() {
    const stream = this._stream._stream

    return stream._readableState.highWaterMark - stream._readableState.buffered
  }

  enqueue(data) {
    this._stream._stream.push(data)
  }

  close() {
    this._stream._stream.push(null)
  }

  error(err) {
    this._stream._stream.destroy(err)
  }
}

// https://streams.spec.whatwg.org/#readablestream
class ReadableStream {
  static get [readableKind]() {
    return 0 // Compatibility version
  }

  static from(iterable) {
    return new ReadableStream(Readable.from(iterable))
  }

  constructor(underlyingSource = {}, queuingStrategy) {
    if (isStreamx(underlyingSource)) {
      this._stream = underlyingSource
    } else {
      if (queuingStrategy === undefined) {
        queuingStrategy = new exports.CountQueuingStrategy()
      }

      const { start, pull, cancel } = underlyingSource
      const { highWaterMark = 1, size = defaultSize } = queuingStrategy

      this._stream = new Readable({ highWaterMark, byteLength: size })

      const controller = new exports.ReadableStreamDefaultController(this)

      try {
        let starting = Promise.resolve()

        if (start) starting = forwardError(start.call(this, controller), controller)

        if (pull) {
          this._stream._read = this._read.bind(this, starting, pull.bind(this, controller))
        }

        if (cancel) {
          this._stream.once('error', cancel.bind(this))
        }
      } catch (err) {
        controller.error(err)
      }
    }

    this._reader = null
  }

  get [readableKind]() {
    return ReadableStream[readableKind]
  }

  get locked() {
    return this._reader !== null
  }

  getReader() {
    if (this.locked) throw new TypeError('Stream is locked')

    this._reader = new exports.ReadableStreamDefaultReader(this)

    return this._reader
  }

  cancel(reason = new TypeError('Stream was cancelled')) {
    const stream = this._stream

    if (stream.destroyed) return Promise.resolve()

    if (this.locked) return Promise.reject(new TypeError('Stream is locked'))

    return new Promise((resolve) =>
      stream.once('close', resolve).once('error', noop).destroy(reason)
    )
  }

  tee() {
    const [a, b] = tee(this._stream)

    return [new ReadableStream(a), new ReadableStream(b)]
  }

  pipeTo(destination) {
    return new Promise((resolve, reject) =>
      this._stream.pipe(destination._stream, (err) => {
        err ? reject(err) : resolve()
      })
    )
  }

  [Symbol.asyncIterator]() {
    return this._stream[Symbol.asyncIterator]()
  }

  _releaseLock() {
    this._reader = null
  }

  async _read(starting, pull, cb) {
    await starting

    let err = null
    try {
      await pull()
    } catch (e) {
      err = e
    }
    cb(err)
  }
}

function defaultSize() {
  return 1
}

exports.ReadableStream = ReadableStream

// https://streams.spec.whatwg.org/#countqueuingstrategy
exports.CountQueuingStrategy = class CountQueuingStrategy {
  constructor(opts = {}) {
    const { highWaterMark = 1 } = opts

    this.highWaterMark = highWaterMark
  }

  size(chunk) {
    return 1
  }
}

// https://streams.spec.whatwg.org/#bytelengthqueuingstrategy
exports.ByteLengthQueuingStrategy = class ByteLengthQueuingStrategy {
  constructor(opts = {}) {
    const { highWaterMark = 16384 } = opts

    this.highWaterMark = highWaterMark
  }

  size(chunk) {
    return chunk.byteLength
  }
}

exports.isReadableStream = function isReadableStream(value) {
  if (value instanceof ReadableStream) return true

  return (
    typeof value === 'object' &&
    value !== null &&
    value[readableKind] === ReadableStream[readableKind]
  )
}

// https://streams.spec.whatwg.org/#readablestream-errored
exports.isReadableStreamErrored = function isReadableStreamErrored(stream) {
  return getStreamError(stream._stream) !== null
}

// https://streams.spec.whatwg.org/#is-readable-stream-disturbed
exports.isReadableStreamDisturbed = function isReadableStreamDisturbed(stream) {
  return isDisturbed(stream._stream)
}

// https://streams.spec.whatwg.org/#writablestreamdefaultwriter
exports.WritableStreamDefaultWriter = class WritableStreamDefaultWriter {
  constructor(stream) {
    this._stream = stream
    this._stream._stream.once('close', onclose).once('error', onerror)

    const closed = Promise.withResolvers()

    // Avoid unhandled exceptions
    closed.promise.catch(noop)

    this._closed = closed

    function onclose() {
      closed.resolve()
    }

    function onerror(err) {
      closed.reject(err)
    }
  }

  get desiredSize() {
    const stream = this._stream._stream

    return stream._writableState.highWaterMark - stream._writableState.buffered
  }

  get closed() {
    return this._closed.promise
  }

  get ready() {
    const stream = this._stream._stream

    if (getStreamError(stream)) return Promise.reject()

    return Writable.drained(stream).then()
  }

  async write(chunk) {
    const stream = this._stream._stream

    let err = getStreamError(stream)
    if (err) return Promise.reject(err)

    stream.write(chunk)

    await Writable.drained(stream)

    err = getStreamError(stream)
    if (err) return Promise.reject(err)
  }

  releaseLock() {
    this._closed.reject(new TypeError('Writer was released'))
    this._stream._releaseLock()
    this._stream = null
  }

  close() {
    const stream = this._stream._stream

    if (stream.destroyed) return Promise.resolve()

    return new Promise((resolve) => stream.once('close', resolve).end())
  }

  abort(reason = new TypeError('Stream was aborted')) {
    const stream = this._stream._stream

    if (stream.destroyed) return Promise.resolve()

    return new Promise((resolve) => stream.once('close', resolve).destroy(reason))
  }
}

// https://streams.spec.whatwg.org/#writablestreamdefaultcontroller
exports.WritableStreamDefaultController = class WritableStreamDefaultController {
  constructor(stream) {
    this._stream = stream
  }

  error(err) {
    this._stream._stream.destroy(err)
  }
}

// https://streams.spec.whatwg.org/#writablestream
class WritableStream {
  static get [writableKind]() {
    return 0 // Compatibility version
  }

  constructor(underlyingSink = {}, queuingStrategy = {}) {
    if (isStreamx(underlyingSink)) {
      this._stream = underlyingSink
    } else {
      if (queuingStrategy === undefined) {
        queuingStrategy = new exports.CountQueuingStrategy()
      }

      const { start, write, close, abort } = underlyingSink
      const { highWaterMark = 1, size = defaultSize } = queuingStrategy

      this._stream = new Writable({ highWaterMark, byteLength: size })

      const controller = new exports.WritableStreamDefaultController(this)

      this._controller = controller

      try {
        let starting = Promise.resolve()

        if (start) starting = forwardError(start.call(this, controller), controller)

        if (write) {
          this._stream._write = this._write.bind(this, starting, write.bind(this))
        }

        if (close) {
          this._stream._destroy = this._destroy.bind(this, close.call(this))
        }

        if (abort) {
          this._stream.once('error', abort.bind(this))
        }
      } catch (err) {
        controller.error(err)
      }
    }

    this._writer = null
  }

  get [writableKind]() {
    return WritableStream[writableKind]
  }

  get locked() {
    return this._writer !== null
  }

  getWriter() {
    if (this.locked) throw new TypeError('Stream is locked')

    this._writer = new exports.WritableStreamDefaultWriter(this)

    return this._writer
  }

  abort(reason = new TypeError('Stream was aborted')) {
    if (this._stream.destroyed) return Promise.resolve()

    if (this.locked) return Promise.reject(new TypeError('Stream is locked'))

    return new Promise((resolve) => this._stream.once('close', resolve).destroy(reason))
  }

  close() {
    if (this._stream.destroyed) return Promise.resolve()

    if (this.locked) return Promise.reject(new TypeError('Stream is locked'))

    return new Promise((resolve) => this._stream.once('close', resolve).end())
  }

  _releaseLock() {
    this._writer = null
  }

  async _write(starting, write, data, cb) {
    await starting

    let err = null
    try {
      await write(data, this._controller)
    } catch (e) {
      err = e
    }
    cb(err)
  }

  async _destroy(closing, cb) {
    let err = null
    try {
      await closing
    } catch (e) {
      err = e
    }
    cb(err)
  }
}

exports.WritableStream = WritableStream

exports.isWritableStream = function isWritableStream(value) {
  if (value instanceof WritableStream) return true

  return (
    typeof value === 'object' &&
    value !== null &&
    value[writableKind] === WritableStream[writableKind]
  )
}

// https://streams.spec.whatwg.org/#transformstreamdefaultcontroller
exports.TransformStreamDefaultController = class TransformStreamDefaultController {
  constructor(stream) {
    this._stream = stream
  }

  get desiredSize() {
    const stream = this._stream._stream

    return stream._readableState.highWaterMark - stream._readableState.buffered
  }

  enqueue(data) {
    this._stream._stream.push(data)
  }

  error(err) {
    this._stream._stream.destroy(err)
  }

  terminate() {
    const stream = this._stream._stream

    stream.push(null)
    stream.destroy(new TypeError('Stream has been terminated'))
  }
}

// https://streams.spec.whatwg.org/#transformstream
class TransformStream {
  static get [transformKind]() {
    return 0 // Compatibility version
  }

  constructor(transformer = {}, writableStrategy = {}, readableStrategy = {}) {
    if (isStreamx(transformer)) {
      this._stream = transformer
    } else {
      const { start, transform, flush } = transformer

      this._stream = new Transform({ ...writableStrategy, ...readableStrategy })

      const controller = new exports.TransformStreamDefaultController(this)

      this._controller = controller

      try {
        let starting = Promise.resolve()

        if (start) starting = forwardError(start.call(this, controller), controller)

        if (transform) {
          this._stream._transform = this._transform.bind(this, starting, transform.bind(this))
        }

        if (flush) {
          this._stream._flush = this._flush.bind(this, flush.call(this, this._controller))
        }
      } catch (err) {
        controller.error(err)
      }
    }

    this._writable = new WritableStream(this._stream)
    this._readable = new ReadableStream(this._stream)
  }

  get [transformKind]() {
    return TransformStream[transformKind]
  }

  get writable() {
    return this._writable
  }

  get readable() {
    return this._readable
  }

  async _transform(starting, transform, data, cb) {
    await starting

    let err = null
    try {
      await transform(data, this._controller)
    } catch (e) {
      err = e
    }
    cb(err)
  }

  async _flush(flush, cb) {
    let err = null
    try {
      await flush
    } catch (e) {
      err = e
    }
    cb(err)
  }
}

exports.TransformStream = TransformStream

exports.isTransformStream = function isTransformStream(value) {
  if (value instanceof TransformStream) return true

  return (
    typeof value === 'object' &&
    value !== null &&
    value[transformKind] === TransformStream[transformKind]
  )
}

async function forwardError(promise, controller) {
  try {
    await promise
  } catch (err) {
    controller.error(err)
  }
}

function noop() {}
module.exports = require.addon()
const binding = require('./binding')

const t = binding.constants

class Type {
  constructor(type) {
    this._type = type
  }

  isUndefined() {
    return this._type === t.UNDEFINED
  }

  isNull() {
    return this._type === t.NULL
  }

  isBoolean() {
    return this._type === t.BOOLEAN
  }

  isNumber() {
    return (this._type & 0xff) === t.NUMBER
  }

  isInt32() {
    return (this._type & (0xff | t.INT32)) === (t.NUMBER | t.INT32)
  }

  isUint32() {
    return (this._type & (0xff | t.UINT32)) === (t.NUMBER | t.UINT32)
  }

  isString() {
    return this._type === t.STRING
  }

  isSymbol() {
    return this._type === t.SYMBOL
  }

  isObject() {
    return (this._type & 0xff) === t.OBJECT
  }

  isArray() {
    return this._type === (t.OBJECT | t.ARRAY)
  }

  isArguments() {
    return this._type === (t.OBJECT | t.ARGUMENTS)
  }

  isDate() {
    return this._type === (t.OBJECT | t.DATE)
  }

  isRegExp() {
    return this._type === (t.OBJECT | t.REGEXP)
  }

  isError() {
    return this._type === (t.OBJECT | t.ERROR)
  }

  isPromise() {
    return this._type === (t.OBJECT | t.PROMISE)
  }

  isProxy() {
    return this._type === (t.OBJECT | t.PROXY)
  }

  isGenerator() {
    return this._type === (t.OBJECT | t.GENERATOR)
  }

  isMap() {
    return this._type === (t.OBJECT | t.MAP)
  }

  isSet() {
    return this._type === (t.OBJECT | t.SET)
  }

  isWeakMap() {
    return this._type === (t.OBJECT | t.WEAK_MAP)
  }

  isWeakSet() {
    return this._type === (t.OBJECT | t.WEAK_SET)
  }

  isWeakRef() {
    return this._type === (t.OBJECT | t.WEAK_REF)
  }

  isArrayBuffer() {
    return this._type === (t.OBJECT | t.ARRAYBUFFER)
  }

  isSharedArrayBuffer() {
    return this._type === (t.OBJECT | t.SHAREDARRAYBUFFER)
  }

  isTypedArray() {
    return (this._type & 0xffff) === (t.OBJECT | t.TYPEDARRAY)
  }

  isInt8Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT8ARRAY)
  }

  isUint8Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT8ARRAY)
  }

  isUint8ClampedArray() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT8CLAMPEDARRAY)
  }

  isInt16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT16ARRAY)
  }

  isUint16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT16ARRAY)
  }

  isInt32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT32ARRAY)
  }

  isUint32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT32ARRAY)
  }

  isFloat16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT16ARRAY)
  }

  isFloat32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT32ARRAY)
  }

  isFloat64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT64ARRAY)
  }

  isBigInt64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.BIGINT64ARRAY)
  }

  isBigUint64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.BIGUINT64ARRAY)
  }

  isDataView() {
    return this._type === (t.OBJECT | t.DATAVIEW)
  }

  isModuleNamespace() {
    return this._type === (t.OBJECT | t.MODULE_NAMESPACE)
  }

  isFunction() {
    return (this._type & 0xff) === t.FUNCTION
  }

  isAsyncFunction() {
    return (
      (this._type & (0xff | t.ASYNC_FUNCTION)) ===
      (t.FUNCTION | t.ASYNC_FUNCTION)
    )
  }

  isGeneratorFunction() {
    return (
      (this._type & (0xff | t.GENERATOR_FUNCTION)) ===
      (t.FUNCTION | t.GENERATOR_FUNCTION)
    )
  }

  isExternal() {
    return this._type === t.EXTERNAL
  }

  isBigInt() {
    return this._type === t.BIGINT
  }
}

module.exports = exports = function type(value) {
  switch (typeof value) {
    case 'undefined':
      return new Type(t.UNDEFINED)
    case 'boolean':
      return new Type(t.BOOLEAN)
    case 'number':
      return new Type(
        Number.isSafeInteger(value) ? binding.type(value) : t.NUMBER
      )
    case 'string':
      return new Type(t.STRING)
    case 'symbol':
      return new Type(t.SYMBOL)
    case 'object':
      return new Type(value === null ? t.NULL : binding.type(value))
    case 'function':
      return new Type(binding.type(value))
    case 'bigint':
      return new Type(t.BIGINT)
  }
}

exports.createTag = function createTag(...components) {
  const tag = new Uint32Array(4)
  for (let i = 0; i < 4; i++) tag[i] = components[i] || 0
  return tag
}

exports.addTag = function addTag(object, tag) {
  binding.addTag(object, tag)
}

exports.checkTag = function checkTag(object, tag) {
  return binding.checkTag(object, tag)
}
{
  "name": "bare-type",
  "version": "1.1.0",
  "description": "Cross-realm type predicates for Bare",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-type.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-type/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-type#readme",
  "engines": {
    "bare": ">=1.2.0"
  },
  "devDependencies": {
    "brittle": "^3.4.0",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
module.exports = require.addon()
const path = require('bare-path')
const binding = require('./binding')
const errors = require('./lib/errors')
const URLSearchParams = require('./lib/url-search-params')

const kind = Symbol.for('bare.url.kind')

const isWindows = Bare.platform === 'win32'

class URL {
  static get [kind]() {
    return 0 // Compatibility version
  }

  constructor(input, base, opts = {}) {
    if (arguments.length === 0) throw errors.INVALID_URL()

    input = String(input)

    if (base !== undefined) base = String(base)

    this._components = new Uint32Array(8)

    this._parse(input, base, opts.throw !== false)

    if (this._href) this._params = new URLSearchParams(this.search, this)
  }

  get [kind]() {
    return URL[kind]
  }

  // https://url.spec.whatwg.org/#dom-url-href

  get href() {
    return this._href
  }

  set href(value) {
    this._update(value)

    this._params._parse(this.search)
  }

  // https://url.spec.whatwg.org/#dom-url-protocol

  get protocol() {
    return this._slice(0, this._components[0]) + ':'
  }

  set protocol(value) {
    this._update(this._replace(value.replace(/:+$/, ''), 0, this._components[0]))
  }

  // https://url.spec.whatwg.org/#dom-url-username

  get username() {
    return this._slice(this._components[0] + 3 /* :// */, this._components[1])
  }

  set username(value) {
    if (cannotHaveCredentialsOrPort(this)) {
      return
    }

    if (this.username === '') value += '@'

    this._update(this._replace(value, this._components[0] + 3 /* :// */, this._components[1]))
  }

  // https://url.spec.whatwg.org/#dom-url-password

  get password() {
    return this._href.slice(this._components[1] + 1 /* : */, this._components[2] - 1 /* @ */)
  }

  set password(value) {
    if (cannotHaveCredentialsOrPort(this)) {
      return
    }

    let start = this._components[1] + 1 /* : */
    let end = this._components[2] - 1 /* @ */

    if (this.password === '') {
      value = ':' + value
      start--
    }

    if (this.username === '') {
      value += '@'
      end++
    }

    this._update(this._replace(value, start, end))
  }

  // https://url.spec.whatwg.org/#dom-url-host

  get host() {
    return this._slice(this._components[2], this._components[5])
  }

  set host(value) {
    if (hasOpaquePath(this)) {
      return
    }

    this._update(
      this._replace(value, this._components[2], this._components[value.includes(':') ? 5 : 3])
    )
  }

  // https://url.spec.whatwg.org/#dom-url-hostname

  get hostname() {
    return this._slice(this._components[2], this._components[3])
  }

  set hostname(value) {
    if (hasOpaquePath(this)) {
      return
    }

    this._update(this._replace(value, this._components[2], this._components[3]))
  }

  // https://url.spec.whatwg.org/#dom-url-port

  get port() {
    return this._slice(this._components[3] + 1 /* : */, this._components[5])
  }

  set port(value) {
    if (cannotHaveCredentialsOrPort(this)) {
      return
    }

    let start = this._components[3] + 1 /* : */

    if (this.port === '') {
      value = ':' + value
      start--
    }

    this._update(this._replace(value, start, this._components[5]))
  }

  // https://url.spec.whatwg.org/#dom-url-pathname

  get pathname() {
    return this._slice(this._components[5], this._components[6] - 1 /* ? */)
  }

  set pathname(value) {
    if (hasOpaquePath(this)) {
      return
    }

    if (value[0] !== '/' && value[0] !== '\\') {
      value = '/' + value
    }

    this._update(this._replace(value, this._components[5], this._components[6] - 1 /* ? */))
  }

  // https://url.spec.whatwg.org/#dom-url-search

  get search() {
    return this._slice(this._components[6] - 1 /* ? */, this._components[7] - 1 /* # */)
  }

  set search(value) {
    if (value && value[0] !== '?') value = '?' + value

    this._update(
      this._replace(value, this._components[6] - 1 /* ? */, this._components[7] - 1 /* # */)
    )

    this._params._parse(this.search)
  }

  // https://url.spec.whatwg.org/#dom-url-searchparams

  get searchParams() {
    return this._params
  }

  // https://url.spec.whatwg.org/#dom-url-hash

  get hash() {
    return this._slice(this._components[7] - 1 /* # */)
  }

  set hash(value) {
    if (value && value[0] !== '#') value = '#' + value

    this._update(this._replace(value, this._components[7] - 1 /* # */))
  }

  toString() {
    return this._href
  }

  toJSON() {
    return this._href
  }

  [Symbol.for('bare.inspect')]() {
    return {
      __proto__: { constructor: URL },

      href: this.href,
      protocol: this.protocol,
      username: this.username,
      password: this.password,
      host: this.host,
      hostname: this.hostname,
      port: this.port,
      pathname: this.pathname,
      search: this.search,
      searchParams: this.searchParams,
      hash: this.hash
    }
  }

  _slice(start, end = this._href.length) {
    return this._href.slice(start, end)
  }

  _replace(replacement, start, end = this._href.length) {
    return this._slice(0, start) + replacement + this._slice(end)
  }

  _parse(input, base, shouldThrow) {
    try {
      this._href = binding.parse(
        String(input),
        base ? String(base) : null,
        this._components,
        shouldThrow
      )
    } catch (err) {
      if (err instanceof TypeError) throw err

      throw errors.INVALID_URL(`Invalid URL '${input}'`, input)
    }
  }

  _update(input) {
    try {
      this._parse(input, null, true)
    } catch (err) {
      if (err instanceof TypeError) throw err
    }
  }
}

module.exports = exports = URL

// https://url.spec.whatwg.org/#url-opaque-path
function hasOpaquePath(url) {
  return url.pathname[0] !== '/'
}

// https://url.spec.whatwg.org/#cannot-have-a-username-password-port
function cannotHaveCredentialsOrPort(url) {
  return url.hostname === '' || url.protocol === 'file:'
}

exports.URL = URL
exports.URLSearchParams = URLSearchParams

exports.errors = errors

exports.isURL = function isURL(value) {
  if (value instanceof URL) return true

  return typeof value === 'object' && value !== null && value[kind] === URL[kind]
}

exports.isURLSearchParams = URLSearchParams.isURLSearchParams

// https://url.spec.whatwg.org/#dom-url-parse
exports.parse = function parse(input, base) {
  const url = new URL(input, base, { throw: false })
  return url._href ? url : null
}

// https://url.spec.whatwg.org/#dom-url-canparse
exports.canParse = function canParse(input, base) {
  return binding.canParse(String(input), base ? String(base) : null)
}

exports.fileURLToPath = function fileURLToPath(url) {
  if (typeof url === 'string') {
    url = new URL(url)
  }

  if (url.protocol !== 'file:') {
    throw errors.INVALID_URL_SCHEME('The URL must use the file: protocol')
  }

  if (isWindows) {
    if (/%2f|%5c/i.test(url.pathname)) {
      throw errors.INVALID_FILE_URL_PATH(
        'The file: URL path must not include encoded \\ or / characters'
      )
    }
  } else {
    if (url.hostname) {
      throw errors.INVALID_FILE_URL_HOST("The file: URL host must be 'localhost' or empty")
    }

    if (/%2f/i.test(url.pathname)) {
      throw errors.INVALID_FILE_URL_PATH('The file: URL path must not include encoded / characters')
    }
  }

  if (/%00/i.test(url.pathname)) {
    throw errors.INVALID_FILE_URL_PATH('The file: URL path must not include encoded NUL characters')
  }

  const pathname = path.normalize(decodeURIComponent(url.pathname))

  if (isWindows) {
    if (url.hostname) return '\\\\' + url.hostname + pathname

    const letter = pathname.charCodeAt(1) | 0x20

    if (letter < 0x61 /* a */ || letter > 0x7a /* z */ || pathname.charCodeAt(2) !== 0x3a /* : */) {
      throw errors.INVALID_FILE_URL_PATH('The file: URL path must be absolute')
    }

    return pathname.slice(1)
  }

  return pathname
}

exports.pathToFileURL = function pathToFileURL(pathname) {
  let resolved = path.resolve(pathname)

  if (pathname[pathname.length - 1] === '/') {
    resolved += '/'
  } else if (isWindows && pathname[pathname.length - 1] === '\\') {
    resolved += '\\'
  }

  resolved = resolved
    .replaceAll('%', '%25') // Must be first
    .replaceAll('#', '%23')
    .replaceAll('?', '%3f')
    .replaceAll('\n', '%0a')
    .replaceAll('\r', '%0d')
    .replaceAll('\t', '%09')

  if (!isWindows) {
    resolved = resolved.replaceAll('\\', '%5c')
  }

  return new URL('file:' + resolved)
}

exports.format = function format(parts) {
  const { protocol, auth, host, hostname, port, pathname, search, query, hash, slashes } = parts

  let result = ''

  if (typeof protocol === 'string') {
    result += protocol

    if (protocol[protocol.length - 1] !== ':') {
      result += ':'
    }

    if (slashes === true || /https?|ftp|gopher|file/.test(protocol)) {
      result += '//'
    }
  }

  if (typeof auth === 'string') {
    if (host || hostname) result += auth + '@'
  }

  if (typeof host === 'string') result += host
  else {
    result += hostname

    if (port) result += ':' + port
  }

  if (typeof pathname === 'string' && pathname !== '') {
    if (pathname[0] !== '/') result += '/'
    result += pathname
  }

  if (typeof search === 'string') {
    if (search[0] !== '?') result += '?'
    result += search
  } else if (typeof query === 'object' && query !== null) {
    result += '?' + new URLSearchParams(query)
  }

  if (typeof hash === 'string') {
    if (hash[0] !== '#') result += '#'
    result += hash
  }

  return result
}
module.exports = class URLError extends Error {
  constructor(msg, fn = URLError, code = fn.name) {
    super(`${code}: ${msg}`)

    this.code = code

    if (Error.captureStackTrace) Error.captureStackTrace(this, fn)
  }

  get name() {
    return 'URLError'
  }

  static INVALID_URL(msg, input) {
    const err = new URLError(msg, URLError.INVALID_URL)

    err.input = input

    return err
  }

  static INVALID_URL_SCHEME(msg = 'Invalid URL') {
    return new URLError(msg, URLError.INVALID_URL_SCHEME)
  }

  static INVALID_FILE_URL_HOST(msg = 'Invalid file: URL host') {
    return new URLError(msg, URLError.INVALID_FILE_URL_HOST)
  }

  static INVALID_FILE_URL_PATH(msg = 'Invalid file: URL path') {
    return new URLError(msg, URLError.INVALID_FILE_URL_PATH)
  }
}
const kind = Symbol.for('bare.url.search-params.kind')

class URLSearchParams {
  static _urls = new WeakMap()

  static get [kind]() {
    return 0 // Compatibility version
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-urlsearchparams
  constructor(init, url = null) {
    this._params = new Map()

    if (url) URLSearchParams._urls.set(this, url)

    if (typeof init === 'string') {
      this._parse(init)
    } else if (init) {
      for (const [name, value] of typeof init[Symbol.iterator] === 'function'
        ? init
        : Object.entries(init)) {
        this.append(name, value)
      }
    }
  }

  get [kind]() {
    return URLSearchParams[kind]
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-size
  get size() {
    return this._params.length
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-append
  append(name, value = null) {
    if (value === null) return

    let list = this._params.get(name)

    if (list === undefined) {
      list = []
      this._params.set(name, list)
    }

    list.push(value)

    this._update()
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-delete
  delete(name, value = null) {
    if (value === null) this._params.delete(name)
    else {
      let list = this._params.get(name)

      if (list === undefined) return

      list = list.filter((found) => found !== value)

      if (list.length === 0) this._params.delete(name)
      else this._params.set(name, list)
    }

    this._update()
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-get
  get(name) {
    const list = this._params.get(name)

    if (list === undefined) return null

    return list[0]
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-getall
  getAll(name) {
    const list = this._params.get(name)

    if (list === undefined) return []

    return Array.from(list)
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-has
  has(name, value = null) {
    const list = this._params.get(name)

    if (list === undefined) return false

    if (value === null) return true

    return list.includes(value)
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-set
  set(name, value = null) {
    if (value === null) this._params.delete(name)
    else this._params.set(name, [value])

    this._update()
  }

  toString() {
    return this._serialize()
  }

  toJSON() {
    return [...this]
  }

  *[Symbol.iterator]() {
    for (const [name, values] of this._params) {
      for (const value of values) yield [name, value]
    }
  }

  [Symbol.for('bare.inspect')]() {
    const object = {
      __proto__: { constructor: URLSearchParams }
    }

    for (const [name, values] of this._params) {
      if (values.length === 1) object[name] = values[0]
      else object[name] = values
    }

    return object
  }

  // https://url.spec.whatwg.org/#concept-urlsearchparams-update
  _update() {
    const url = URLSearchParams._urls.get(this)

    if (url === undefined) return

    url.search = this._serialize()
  }

  // https://url.spec.whatwg.org/#concept-urlencoded-parser
  _parse(input) {
    if (input[0] === '?') input = input.substring(1)

    this._params = new Map()

    for (let sequence of input.split('&')) {
      if (sequence.length === 0) continue

      sequence = sequence.replace(/\+/g, ' ')

      let i = sequence.indexOf('=')
      if (i === -1) i = sequence.length

      const name = decodeURIComponent(sequence.substring(0, i))
      const value = decodeURIComponent(sequence.substring(i + 1, sequence.length))

      let list = this._params.get(name)

      if (list === undefined) {
        list = []
        this._params.set(name, list)
      }

      list.push(value)
    }
  }

  // https://url.spec.whatwg.org/#concept-urlencoded-serializer
  _serialize() {
    let output = ''

    for (let [name, values] of this._params) {
      name = encodeURIComponent(name)

      for (const value of values) {
        if (output) output += '&'

        output += name + '=' + encodeURIComponent(value)
      }
    }

    return output
  }
}

module.exports = exports = URLSearchParams

exports.isURLSearchParams = function isURLSearchParams(value) {
  if (value instanceof URLSearchParams) return true

  return typeof value === 'object' && value !== null && value[kind] === URLSearchParams[kind]
}
{
  "name": "bare-url",
  "version": "2.4.5",
  "description": "WHATWG URL implementation for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "global.js",
    "global.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-url.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-url/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-url",
  "dependencies": {
    "bare-path": "^3.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "cmake-bare": "^1.1.6",
    "cmake-fetch": "^1.0.0",
    "lunte": "^1.6.0",
    "prettier": "^3.3.3",
    "prettier-config-holepunch": "^2.0.0"
  }
}
const FACTOR = new Uint16Array(8)

function factor4096 (i, n) {
  while (n > 0) {
    const f = i & 4095
    FACTOR[--n] = f
    i = (i - f) / 4096
  }
  return FACTOR
}

module.exports = class BigSparseArray {
  constructor () {
    this.tiny = new TinyArray()
    this.maxLength = 4096
    this.factor = 1
  }

  set (index, val) {
    if (val !== undefined) {
      while (index >= this.maxLength) {
        this.maxLength *= 4096
        this.factor++
        if (!this.tiny.isEmptyish()) {
          const t = new TinyArray()
          t.set(0, this.tiny)
          this.tiny = t
        }
      }
    }

    const f = factor4096(index, this.factor)
    const last = this.factor - 1

    let tiny = this.tiny
    for (let i = 0; i < last; i++) {
      const next = tiny.get(f[i])
      if (next === undefined) {
        if (val === undefined) return
        tiny = tiny.set(f[i], new TinyArray())
      } else {
        tiny = next
      }
    }

    return tiny.set(f[last], val)
  }

  get (index) {
    if (index >= this.maxLength) return

    const f = factor4096(index, this.factor)
    const last = this.factor - 1

    let tiny = this.tiny
    for (let i = 0; i < last; i++) {
      tiny = tiny.get(f[i])
      if (tiny === undefined) return
    }

    return tiny.get(f[last])
  }
}

class TinyArray {
  constructor () {
    this.s = 0
    this.b = new Array(1)
    this.f = new Uint16Array(1)
  }

  isEmptyish () {
    return this.b.length === 1 && this.b[0] === undefined
  }

  get (i) {
    if (this.s === 12) return this.b[i]
    const f = i >>> this.s
    const r = i & (this.b.length - 1)
    return this.f[r] === f ? this.b[r] : undefined
  }

  set (i, v) {
    while (this.s !== 12) {
      const f = i >>> this.s
      const r = i & (this.b.length - 1)
      const o = this.b[r]

      if (o === undefined || f === this.f[r]) {
        this.b[r] = v
        this.f[r] = f
        return v
      }

      this.grow()
    }

    this.b[i] = v
    return v
  }

  grow () {
    const os = this.s
    const ob = this.b
    const of = this.f

    this.s += 4
    this.b = new Array(this.b.length << 4)
    this.f = this.s === 12 ? null : new Uint8Array(this.b.length)

    const m = this.b.length - 1

    for (let or = 0; or < ob.length; or++) {
      if (ob[or] === undefined) continue

      const i = of[or] << os | or
      const f = i >>> this.s
      const r = i & m

      this.b[r] = ob[or]
      if (this.s !== 12) this.f[r] = f
    }
  }
}
{
  "name": "big-sparse-array",
  "version": "1.0.3",
  "description": "A sparse array optimised for low memory whilst still being fast",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "brittle": "^3.1.1",
    "standard": "^16.0.3"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/big-sparse-array.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/big-sparse-array/issues"
  },
  "homepage": "https://github.com/mafintosh/big-sparse-array"
}
import { encode, encodeInto, objectToTokens, rfc8949EncodeOptions } from './lib/encode.js'
import { decode, decodeFirst, Tokeniser, tokensToObject } from './lib/decode.js'
import { Tagged } from './lib/tagged.js'
import { Token, Type } from './lib/token.js'

/**
 * Export the types that were present in the original manual cborg.d.ts
 * @typedef {import('./interface.js').TagDecodeControl} TagDecodeControl
 * @typedef {import('./interface.js').TagDecoder} TagDecoder
 * There was originally just `TypeEncoder` so don't break types by renaming or not exporting
 * @typedef {import('./interface.js').OptionalTypeEncoder} TypeEncoder
 * @typedef {import('./interface.js').DecodeOptions} DecodeOptions
 * @typedef {import('./interface.js').EncodeOptions} EncodeOptions
 */

export {
  decode,
  decodeFirst,
  Tokeniser as Tokenizer,
  tokensToObject,
  encode,
  encodeInto,
  objectToTokens,
  rfc8949EncodeOptions,
  Tagged,
  Token,
  Type
}
/* globals BigInt */

import { Token, Type } from './token.js'
import { decodeErrPrefix, assertEnoughData } from './common.js'

export const uintBoundaries = [24, 256, 65536, 4294967296, BigInt('18446744073709551616')]

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number}
 */
export function readUint8 (data, offset, options) {
  assertEnoughData(data, offset, 1)
  const value = data[offset]
  if (options.strict === true && value < uintBoundaries[0]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  return value
}

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number}
 */
export function readUint16 (data, offset, options) {
  assertEnoughData(data, offset, 2)
  const value = (data[offset] << 8) | data[offset + 1]
  if (options.strict === true && value < uintBoundaries[1]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  return value
}

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number}
 */
export function readUint32 (data, offset, options) {
  assertEnoughData(data, offset, 4)
  const value = (data[offset] * 16777216 /* 2 ** 24 */) + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]
  if (options.strict === true && value < uintBoundaries[2]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  return value
}

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number|bigint}
 */
export function readUint64 (data, offset, options) {
  // assume BigInt, convert back to Number if within safe range
  assertEnoughData(data, offset, 8)
  const hi = (data[offset] * 16777216 /* 2 ** 24 */) + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]
  const lo = (data[offset + 4] * 16777216 /* 2 ** 24 */) + (data[offset + 5] << 16) + (data[offset + 6] << 8) + data[offset + 7]
  const value = (BigInt(hi) << BigInt(32)) + BigInt(lo)
  if (options.strict === true && value < uintBoundaries[3]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  if (value <= Number.MAX_SAFE_INTEGER) {
    return Number(value)
  }
  if (options.allowBigInt === true) {
    return value
  }
  throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`)
}

/* not required thanks to quick[] list
const oneByteTokens = new Array(24).fill(0).map((v, i) => new Token(Type.uint, i, 1))
export function decodeUintCompact (data, pos, minor, options) {
  return oneByteTokens[minor]
}
*/

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint8 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint8(data, pos + 1, options), 2)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint16 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint16(data, pos + 1, options), 3)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint32 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint32(data, pos + 1, options), 5)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint64 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint64(data, pos + 1, options), 9)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeUint (writer, token) {
  return encodeUintValue(writer, 0, token.value)
}

/**
 * @param {ByteWriter} writer
 * @param {number} major
 * @param {number|bigint} uint
 */
export function encodeUintValue (writer, major, uint) {
  if (uint < uintBoundaries[0]) {
    const nuint = Number(uint)
    // pack into one byte, minor=0, additional=value
    writer.push([major | nuint])
  } else if (uint < uintBoundaries[1]) {
    const nuint = Number(uint)
    // pack into two byte, minor=0, additional=24
    writer.push([major | 24, nuint])
  } else if (uint < uintBoundaries[2]) {
    const nuint = Number(uint)
    // pack into three byte, minor=0, additional=25
    writer.push([major | 25, nuint >>> 8, nuint & 0xff])
  } else if (uint < uintBoundaries[3]) {
    const nuint = Number(uint)
    // pack into five byte, minor=0, additional=26
    writer.push([major | 26, (nuint >>> 24) & 0xff, (nuint >>> 16) & 0xff, (nuint >>> 8) & 0xff, nuint & 0xff])
  } else {
    const buint = BigInt(uint)
    if (buint < uintBoundaries[4]) {
      // pack into nine byte, minor=0, additional=27
      const set = [major | 27, 0, 0, 0, 0, 0, 0, 0]
      // simulate bitwise above 32 bits
      let lo = Number(buint & BigInt(0xffffffff))
      let hi = Number(buint >> BigInt(32) & BigInt(0xffffffff))
      set[8] = lo & 0xff
      lo = lo >> 8
      set[7] = lo & 0xff
      lo = lo >> 8
      set[6] = lo & 0xff
      lo = lo >> 8
      set[5] = lo & 0xff
      set[4] = hi & 0xff
      hi = hi >> 8
      set[3] = hi & 0xff
      hi = hi >> 8
      set[2] = hi & 0xff
      hi = hi >> 8
      set[1] = hi & 0xff
      writer.push(set)
    } else {
      throw new Error(`${decodeErrPrefix} encountered BigInt larger than allowable range`)
    }
  }
}

/**
 * @param {Token} token
 * @returns {number}
 */
encodeUint.encodedSize = function encodedSize (token) {
  return encodeUintValue.encodedSize(token.value)
}

/**
 * @param {number} uint
 * @returns {number}
 */
encodeUintValue.encodedSize = function encodedSize (uint) {
  if (uint < uintBoundaries[0]) {
    return 1
  }
  if (uint < uintBoundaries[1]) {
    return 2
  }
  if (uint < uintBoundaries[2]) {
    return 3
  }
  if (uint < uintBoundaries[3]) {
    return 5
  }
  return 9
}

/**
 * @param {Token} tok1
 * @param {Token} tok2
 * @returns {number}
 */
encodeUint.compareTokens = function compareTokens (tok1, tok2) {
  return tok1.value < tok2.value ? -1 : tok1.value > tok2.value ? 1 : 0
}
/* eslint-env es2020 */

import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import { decodeErrPrefix } from './common.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint8 (data, pos, _minor, options) {
  return new Token(Type.negint, -1 - uint.readUint8(data, pos + 1, options), 2)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint16 (data, pos, _minor, options) {
  return new Token(Type.negint, -1 - uint.readUint16(data, pos + 1, options), 3)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint32 (data, pos, _minor, options) {
  return new Token(Type.negint, -1 - uint.readUint32(data, pos + 1, options), 5)
}

const neg1b = BigInt(-1)
const pos1b = BigInt(1)

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint64 (data, pos, _minor, options) {
  const int = uint.readUint64(data, pos + 1, options)
  if (typeof int !== 'bigint') {
    const value = -1 - int
    if (value >= Number.MIN_SAFE_INTEGER) {
      return new Token(Type.negint, value, 9)
    }
  }
  if (options.allowBigInt !== true) {
    throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`)
  }
  return new Token(Type.negint, neg1b - BigInt(int), 9)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeNegint (writer, token) {
  const negint = token.value
  const unsigned = (typeof negint === 'bigint' ? (negint * neg1b - pos1b) : (negint * -1 - 1))
  uint.encodeUintValue(writer, token.type.majorEncoded, unsigned)
}

/**
 * @param {Token} token
 * @returns {number}
 */
encodeNegint.encodedSize = function encodedSize (token) {
  const negint = token.value
  const unsigned = (typeof negint === 'bigint' ? (negint * neg1b - pos1b) : (negint * -1 - 1))
  // handled by quickEncode, we shouldn't get here but it's included for completeness
  if (unsigned < uint.uintBoundaries[0]) {
    return 1
  }
  if (unsigned < uint.uintBoundaries[1]) {
    return 2
  }
  if (unsigned < uint.uintBoundaries[2]) {
    return 3
  }
  if (unsigned < uint.uintBoundaries[3]) {
    return 5
  }
  return 9
}

/**
 * @param {Token} tok1
 * @param {Token} tok2
 * @returns {number}
 */
encodeNegint.compareTokens = function compareTokens (tok1, tok2) {
  // opposite of the uint comparison since we store the uint version in bytes
  return tok1.value < tok2.value ? 1 : tok1.value > tok2.value ? -1 : 0
}
import { Token, Type } from './token.js'
import { assertEnoughData, decodeErrPrefix } from './common.js'
import * as uint from './0uint.js'
import { compare, fromString } from './byte-utils.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} prefix
 * @param {number} length
 * @returns {Token}
 */
function toToken (data, pos, prefix, length) {
  assertEnoughData(data, pos, prefix + length)
  const buf = data.slice(pos + prefix, pos + prefix + length)
  return new Token(Type.bytes, buf, prefix + length)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeBytesCompact (data, pos, minor, _options) {
  return toToken(data, pos, 1, minor)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer bytes lengths not supported`)
  }
  return toToken(data, pos, 9, l)
}

/**
 * `encodedBytes` allows for caching when we do a byte version of a string
 * for key sorting purposes
 * @param {Token} token
 * @returns {Uint8Array}
 */
function tokenBytes (token) {
  if (token.encodedBytes === undefined) {
    token.encodedBytes = Type.equals(token.type, Type.string) ? fromString(token.value) : token.value
  }
  // @ts-ignore c'mon
  return token.encodedBytes
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeBytes (writer, token) {
  const bytes = tokenBytes(token)
  uint.encodeUintValue(writer, token.type.majorEncoded, bytes.length)
  writer.push(bytes)
}

/**
 * @param {Token} token
 * @returns {number}
 */
encodeBytes.encodedSize = function encodedSize (token) {
  const bytes = tokenBytes(token)
  return uint.encodeUintValue.encodedSize(bytes.length) + bytes.length
}

/**
 * @param {Token} tok1
 * @param {Token} tok2
 * @returns {number}
 */
encodeBytes.compareTokens = function compareTokens (tok1, tok2) {
  return compareBytes(tokenBytes(tok1), tokenBytes(tok2))
}

/**
 * @param {Uint8Array} b1
 * @param {Uint8Array} b2
 * @returns {number}
 */
export function compareBytes (b1, b2) {
  return b1.length < b2.length ? -1 : b1.length > b2.length ? 1 : compare(b1, b2)
}
import { Token, Type } from './token.js'
import { assertEnoughData, decodeErrPrefix } from './common.js'
import * as uint from './0uint.js'
import { encodeBytes } from './2bytes.js'

const textDecoder = new TextDecoder()

// Threshold for ASCII fast-path vs TextDecoder. Short ASCII strings (common for
// map keys) are faster to decode with a simple loop than TextDecoder overhead.
const ASCII_THRESHOLD = 32

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * Decode UTF-8 bytes to string. For short ASCII strings (common case for map keys),
 * a simple loop is faster than TextDecoder.
 * @param {Uint8Array} bytes
 * @param {number} start
 * @param {number} end
 * @returns {string}
 */
function toStr (bytes, start, end) {
  const len = end - start
  if (len < ASCII_THRESHOLD) {
    let str = ''
    for (let i = start; i < end; i++) {
      const c = bytes[i]
      if (c & 0x80) { // non-ASCII, fall back to TextDecoder
        return textDecoder.decode(bytes.subarray(start, end))
      }
      str += String.fromCharCode(c)
    }
    return str
  }
  return textDecoder.decode(bytes.subarray(start, end))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} prefix
 * @param {number} length
 * @param {DecodeOptions} options
 * @returns {Token}
 */
function toToken (data, pos, prefix, length, options) {
  const totLength = prefix + length
  assertEnoughData(data, pos, totLength)
  const tok = new Token(Type.string, toStr(data, pos + prefix, pos + totLength), totLength)
  if (options.retainStringBytes === true) {
    tok.byteValue = data.slice(pos + prefix, pos + totLength)
  }
  return tok
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeStringCompact (data, pos, minor, options) {
  return toToken(data, pos, 1, minor, options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options), options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options), options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options), options)
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer string lengths not supported`)
  }
  return toToken(data, pos, 9, l, options)
}

export const encodeString = encodeBytes
import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import { decodeErrPrefix } from './common.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} prefix
 * @param {number} length
 * @returns {Token}
 */
function toToken (_data, _pos, prefix, length) {
  return new Token(Type.array, length, prefix)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeArrayCompact (data, pos, minor, _options) {
  return toToken(data, pos, 1, minor)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer array lengths not supported`)
  }
  return toToken(data, pos, 9, l)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArrayIndefinite (data, pos, _minor, options) {
  if (options.allowIndefinite === false) {
    throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)
  }
  return toToken(data, pos, 1, Infinity)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeArray (writer, token) {
  uint.encodeUintValue(writer, Type.array.majorEncoded, token.value)
}

// using an array as a map key, are you sure about this? we can only sort
// by map length here, it's up to the encoder to decide to look deeper
encodeArray.compareTokens = uint.encodeUint.compareTokens

/**
 * @param {Token} token
 * @returns {number}
 */
encodeArray.encodedSize = function encodedSize (token) {
  return uint.encodeUintValue.encodedSize(token.value)
}
import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import { decodeErrPrefix } from './common.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} prefix
 * @param {number} length
 * @returns {Token}
 */
function toToken (_data, _pos, prefix, length) {
  return new Token(Type.map, length, prefix)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeMapCompact (data, pos, minor, _options) {
  return toToken(data, pos, 1, minor)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer map lengths not supported`)
  }
  return toToken(data, pos, 9, l)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMapIndefinite (data, pos, _minor, options) {
  if (options.allowIndefinite === false) {
    throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)
  }
  return toToken(data, pos, 1, Infinity)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeMap (writer, token) {
  uint.encodeUintValue(writer, Type.map.majorEncoded, token.value)
}

// using a map as a map key, are you sure about this? we can only sort
// by map length here, it's up to the encoder to decide to look deeper
encodeMap.compareTokens = uint.encodeUint.compareTokens

/**
 * @param {Token} token
 * @returns {number}
 */
encodeMap.encodedSize = function encodedSize (token) {
  return uint.encodeUintValue.encodedSize(token.value)
}
import { Token, Type } from './token.js'
import * as uint from './0uint.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeTagCompact (_data, _pos, minor, _options) {
  return new Token(Type.tag, minor, 1)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag8 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint8(data, pos + 1, options), 2)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag16 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint16(data, pos + 1, options), 3)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag32 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint32(data, pos + 1, options), 5)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag64 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint64(data, pos + 1, options), 9)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeTag (writer, token) {
  uint.encodeUintValue(writer, Type.tag.majorEncoded, token.value)
}

encodeTag.compareTokens = uint.encodeUint.compareTokens

/**
 * @param {Token} token
 * @returns {number}
 */
encodeTag.encodedSize = function encodedSize (token) {
  return uint.encodeUintValue.encodedSize(token.value)
}
// TODO: shift some of the bytes logic to bytes-utils so we can use Buffer
// where possible

import { Token, Type } from './token.js'
import { decodeErrPrefix } from './common.js'
import { encodeUint } from './0uint.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 * @typedef {import('../interface.js').EncodeOptions} EncodeOptions
 */

export const MINOR_FALSE = 20
export const MINOR_TRUE = 21
export const MINOR_NULL = 22
export const MINOR_UNDEFINED = 23

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUndefined (_data, _pos, _minor, options) {
  if (options.allowUndefined === false) {
    throw new Error(`${decodeErrPrefix} undefined values are not supported`)
  } else if (options.coerceUndefinedToNull === true) {
    return new Token(Type.null, null, 1)
  }
  return new Token(Type.undefined, undefined, 1)
}

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBreak (_data, _pos, _minor, options) {
  if (options.allowIndefinite === false) {
    throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)
  }
  return new Token(Type.break, undefined, 1)
}

/**
 * @param {number} value
 * @param {number} bytes
 * @param {DecodeOptions} options
 * @returns {Token}
 */
function createToken (value, bytes, options) {
  if (options) {
    if (options.allowNaN === false && Number.isNaN(value)) {
      throw new Error(`${decodeErrPrefix} NaN values are not supported`)
    }
    if (options.allowInfinity === false && (value === Infinity || value === -Infinity)) {
      throw new Error(`${decodeErrPrefix} Infinity values are not supported`)
    }
  }
  return new Token(Type.float, value, bytes)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeFloat16 (data, pos, _minor, options) {
  return createToken(readFloat16(data, pos + 1), 3, options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeFloat32 (data, pos, _minor, options) {
  return createToken(readFloat32(data, pos + 1), 5, options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeFloat64 (data, pos, _minor, options) {
  return createToken(readFloat64(data, pos + 1), 9, options)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 * @param {EncodeOptions} options
 */
export function encodeFloat (writer, token, options) {
  const float = token.value

  if (float === false) {
    writer.push([Type.float.majorEncoded | MINOR_FALSE])
  } else if (float === true) {
    writer.push([Type.float.majorEncoded | MINOR_TRUE])
  } else if (float === null) {
    writer.push([Type.float.majorEncoded | MINOR_NULL])
  } else if (float === undefined) {
    writer.push([Type.float.majorEncoded | MINOR_UNDEFINED])
  } else {
    let decoded
    let success = false
    if (!options || options.float64 !== true) {
      encodeFloat16(float)
      decoded = readFloat16(ui8a, 1)
      if (float === decoded || Number.isNaN(float)) {
        ui8a[0] = 0xf9
        writer.push(ui8a.slice(0, 3))
        success = true
      } else {
        encodeFloat32(float)
        decoded = readFloat32(ui8a, 1)
        if (float === decoded) {
          ui8a[0] = 0xfa
          writer.push(ui8a.slice(0, 5))
          success = true
        }
      }
    }
    if (!success) {
      encodeFloat64(float)
      decoded = readFloat64(ui8a, 1)
      ui8a[0] = 0xfb
      writer.push(ui8a.slice(0, 9))
    }
  }
}

/**
 * @param {Token} token
 * @param {EncodeOptions} options
 * @returns {number}
 */
encodeFloat.encodedSize = function encodedSize (token, options) {
  const float = token.value

  if (float === false || float === true || float === null || float === undefined) {
    return 1
  }

  if (!options || options.float64 !== true) {
    encodeFloat16(float)
    let decoded = readFloat16(ui8a, 1)
    if (float === decoded || Number.isNaN(float)) {
      return 3
    }
    encodeFloat32(float)
    decoded = readFloat32(ui8a, 1)
    if (float === decoded) {
      return 5
    }
  }
  return 9
}

const buffer = new ArrayBuffer(9)
const dataView = new DataView(buffer, 1)
const ui8a = new Uint8Array(buffer, 0)

/**
 * @param {number} inp
 */
function encodeFloat16 (inp) {
  if (inp === Infinity) {
    dataView.setUint16(0, 0x7c00, false)
  } else if (inp === -Infinity) {
    dataView.setUint16(0, 0xfc00, false)
  } else if (Number.isNaN(inp)) {
    dataView.setUint16(0, 0x7e00, false)
  } else {
    dataView.setFloat32(0, inp)
    const valu32 = dataView.getUint32(0)
    const exponent = (valu32 & 0x7f800000) >> 23
    const mantissa = valu32 & 0x7fffff

    if (exponent === 0xff) {
      // too big, Infinity, but this should be hard (impossible?) to trigger
      dataView.setUint16(0, 0x7c00, false)
    } else if (exponent === 0x00) {
      // 0.0, -0.0 and subnormals, shouldn't be possible to get here because 0.0 should be counted as an int
      // Use valu32 for sign bit since bitwise ops on floats lose -0 sign
      dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | (mantissa >> 13), false)
    } else { // standard numbers
      // chunks of logic here borrowed from https://github.com/PJK/libcbor/blob/c78f437182533e3efa8d963ff4b945bb635c2284/src/cbor/encoding.c#L127
      const logicalExponent = exponent - 127
      // Now we know that 2^exponent <= 0 logically
      if (logicalExponent < -24) {
        /* No unambiguous representation exists, this float is not a half float
          and is too small to be represented using a half, round off to zero.
          Consistent with the reference implementation. */
        // should be difficult (impossible?) to get here in JS
        dataView.setUint16(0, 0)
      } else if (logicalExponent < -14) {
        /* Offset the remaining decimal places by shifting the significand, the
          value is lost. This is an implementation decision that works around the
          absence of standard half-float in the language. */
        dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | /* sign bit */ (1 << (24 + logicalExponent)), false)
      } else {
        dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | ((logicalExponent + 15) << 10) | (mantissa >> 13), false)
      }
    }
  }
}

/**
 * @param {Uint8Array} ui8a
 * @param {number} pos
 * @returns {number}
 */
function readFloat16 (ui8a, pos) {
  if (ui8a.length - pos < 2) {
    throw new Error(`${decodeErrPrefix} not enough data for float16`)
  }

  const half = (ui8a[pos] << 8) + ui8a[pos + 1]
  if (half === 0x7c00) {
    return Infinity
  }
  if (half === 0xfc00) {
    return -Infinity
  }
  if (half === 0x7e00) {
    return NaN
  }
  const exp = (half >> 10) & 0x1f
  const mant = half & 0x3ff
  let val
  if (exp === 0) {
    val = mant * (2 ** -24)
  } else if (exp !== 31) {
    val = (mant + 1024) * (2 ** (exp - 25))
  } else {
    // may not be possible to get here
    val = mant === 0 ? Infinity : NaN
  }
  return (half & 0x8000) ? -val : val
}

/**
 * @param {number} inp
 */
function encodeFloat32 (inp) {
  dataView.setFloat32(0, inp, false)
}

/**
 * @param {Uint8Array} ui8a
 * @param {number} pos
 * @returns {number}
 */
function readFloat32 (ui8a, pos) {
  if (ui8a.length - pos < 4) {
    throw new Error(`${decodeErrPrefix} not enough data for float32`)
  }
  const offset = (ui8a.byteOffset || 0) + pos
  return new DataView(ui8a.buffer, offset, 4).getFloat32(0, false)
}

/**
 * @param {number} inp
 */
function encodeFloat64 (inp) {
  dataView.setFloat64(0, inp, false)
}

/**
 * @param {Uint8Array} ui8a
 * @param {number} pos
 * @returns {number}
 */
function readFloat64 (ui8a, pos) {
  if (ui8a.length - pos < 8) {
    throw new Error(`${decodeErrPrefix} not enough data for float64`)
  }
  const offset = (ui8a.byteOffset || 0) + pos
  return new DataView(ui8a.buffer, offset, 8).getFloat64(0, false)
}

/**
 * @param {Token} _tok1
 * @param {Token} _tok2
 * @returns {number}
 */
encodeFloat.compareTokens = encodeUint.compareTokens
/*
encodeFloat.compareTokens = function compareTokens (_tok1, _tok2) {
  return _tok1
  throw new Error(`${encodeErrPrefix} cannot use floats as map keys`)
}
*/
/**
 * Bl is a list of byte chunks, similar to https://github.com/rvagg/bl but for
 * writing rather than reading.
 * A Bl object accepts set() operations for individual bytes and copyTo() for
 * inserting byte arrays. These write operations don't automatically increment
 * the internal cursor so its "length" won't be changed. Instead, increment()
 * must be called to extend its length to cover the inserted data.
 * The toBytes() call will convert all internal memory to a single Uint8Array of
 * the correct length, truncating any data that is stored but hasn't been
 * included by an increment().
 * get() can retrieve a single byte.
 * All operations (except toBytes()) take an "offset" argument that will perform
 * the write at the offset _from the current cursor_. For most operations this
 * will be `0` to write at the current cursor position but it can be ahead of
 * the current cursor. Negative offsets probably work but are untested.
 */

// TODO: ipjs doesn't support this, only for test files: https://github.com/mikeal/ipjs/blob/master/src/package/testFile.js#L39
import { alloc, concat, slice } from './byte-utils.js'

// the ts-ignores in this file are almost all for the `Uint8Array|number[]` duality that exists
// for perf reasons. Consider better approaches to this or removing it entirely, it is quite
// risky because of some assumptions about small chunks === number[] and everything else === Uint8Array.

const defaultChunkSize = 256

export class Bl {
  /**
   * @param {number} [chunkSize]
   */
  constructor (chunkSize = defaultChunkSize) {
    this.chunkSize = chunkSize
    /** @type {number} */
    this.cursor = 0
    /** @type {number} */
    this.maxCursor = -1
    /** @type {(Uint8Array|number[])[]} */
    this.chunks = []
    // keep the first chunk around if we can to save allocations for future encodes
    /** @type {Uint8Array|number[]|null} */
    this._initReuseChunk = null
  }

  reset () {
    this.cursor = 0
    this.maxCursor = -1
    if (this.chunks.length) {
      this.chunks = []
    }
    if (this._initReuseChunk !== null) {
      this.chunks.push(this._initReuseChunk)
      this.maxCursor = this._initReuseChunk.length - 1
    }
  }

  /**
   * @param {Uint8Array|number[]} bytes
   */
  push (bytes) {
    let topChunk = this.chunks[this.chunks.length - 1]
    const newMax = this.cursor + bytes.length
    if (newMax <= this.maxCursor + 1) {
      // we have at least one chunk and we can fit these bytes into that chunk
      const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1
      // @ts-ignore
      topChunk.set(bytes, chunkPos)
    } else {
      // can't fit it in
      if (topChunk) {
        // trip the last chunk to `cursor` if we need to
        const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1
        if (chunkPos < topChunk.length) {
          // @ts-ignore
          this.chunks[this.chunks.length - 1] = topChunk.subarray(0, chunkPos)
          this.maxCursor = this.cursor - 1
        }
      }
      if (bytes.length < 64 && bytes.length < this.chunkSize) {
        // make a new chunk and copy the new one into it
        topChunk = alloc(this.chunkSize)
        this.chunks.push(topChunk)
        this.maxCursor += topChunk.length
        if (this._initReuseChunk === null) {
          this._initReuseChunk = topChunk
        }
        // @ts-ignore
        topChunk.set(bytes, 0)
      } else {
        // push the new bytes in as its own chunk
        this.chunks.push(bytes)
        this.maxCursor += bytes.length
      }
    }
    this.cursor += bytes.length
  }

  /**
   * @param {boolean} [reset]
   * @returns {Uint8Array}
   */
  toBytes (reset = false) {
    let byts
    if (this.chunks.length === 1) {
      const chunk = this.chunks[0]
      if (reset && this.cursor > chunk.length / 2) {
        // @ts-ignore
        byts = this.cursor === chunk.length ? chunk : chunk.subarray(0, this.cursor)
        this._initReuseChunk = null
        this.chunks = []
      } else {
        // @ts-ignore
        byts = slice(chunk, 0, this.cursor)
      }
    } else {
      // @ts-ignore
      byts = concat(this.chunks, this.cursor)
    }
    if (reset) {
      this.reset()
    }
    return byts
  }
}

/**
 * U8Bl is a buffer list that writes directly to a user-provided Uint8Array.
 * It provides the same interface as Bl but writes to a fixed destination.
 */
export class U8Bl {
  /**
   * @param {Uint8Array} dest
   */
  constructor (dest) {
    this.dest = dest
    /** @type {number} */
    this.cursor = 0
    // chunks is for interface compatibility with Bl - encode.js checks chunks.length
    // as a sanity check for pre-calculated sizes. For U8Bl this is always [dest].
    /** @type {Uint8Array[]} */
    this.chunks = [dest]
  }

  reset () {
    this.cursor = 0
  }

  /**
   * @param {Uint8Array|number[]} bytes
   */
  push (bytes) {
    if (this.cursor + bytes.length > this.dest.length) {
      throw new Error('write out of bounds, destination buffer is too small')
    }
    this.dest.set(bytes, this.cursor)
    this.cursor += bytes.length
  }

  /**
   * @param {boolean} [reset]
   * @returns {Uint8Array}
   */
  toBytes (reset = false) {
    const byts = this.dest.subarray(0, this.cursor)
    if (reset) {
      this.reset()
    }
    return byts
  }
}
// Use Uint8Array directly in the browser, use Buffer in Node.js but don't
// speak its name directly to avoid bundlers pulling in the `Buffer` polyfill

// @ts-ignore
export const useBuffer = globalThis.process &&
  // @ts-ignore
  !globalThis.process.browser &&
  // @ts-ignore
  globalThis.Buffer &&
  // @ts-ignore
  typeof globalThis.Buffer.isBuffer === 'function'

const textEncoder = new TextEncoder()

/**
 * @param {Uint8Array} buf
 * @returns {boolean}
 */
function isBuffer (buf) {
  // @ts-ignore
  return useBuffer && globalThis.Buffer.isBuffer(buf)
}

/**
 * @param {Uint8Array|number[]} buf
 * @returns {Uint8Array}
 */
export function asU8A (buf) {
  if (!(buf instanceof Uint8Array)) {
    return Uint8Array.from(buf)
  }
  return isBuffer(buf) ? new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength) : buf
}

// Threshold for manual UTF-8 encoding vs native methods.
// Node.js Buffer.from: crossover ~24 chars
// Browser TextEncoder: crossover ~200 chars
const FROM_STRING_THRESHOLD_BUFFER = 24
const FROM_STRING_THRESHOLD_TEXTENCODER = 200

export const fromString = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {string} string
     */
    (string) => {
      return string.length >= FROM_STRING_THRESHOLD_BUFFER
        ? // eslint-disable-line operator-linebreak
      // @ts-ignore
        globalThis.Buffer.from(string)
        : utf8ToBytes(string)
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {string} string
     */
    (string) => {
      return string.length >= FROM_STRING_THRESHOLD_TEXTENCODER ? textEncoder.encode(string) : utf8ToBytes(string)
    }

/**
 * Buffer variant not fast enough for what we need
 * @param {number[]} arr
 * @returns {Uint8Array}
 */
export const fromArray = (arr) => {
  return Uint8Array.from(arr)
}

export const slice = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} bytes
     * @param {number} start
     * @param {number} end
     */
    // Buffer.slice() returns a view, not a copy, so we need special handling
    (bytes, start, end) => {
      if (isBuffer(bytes)) {
        return new Uint8Array(bytes.subarray(start, end))
      }
      return bytes.slice(start, end)
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} bytes
     * @param {number} start
     * @param {number} end
     */
    (bytes, start, end) => {
      return bytes.slice(start, end)
    }

export const concat = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array[]} chunks
     * @param {number} length
     * @returns {Uint8Array}
     */
    (chunks, length) => {
      // might get a stray plain Array here
      chunks = chunks.map((c) => c instanceof Uint8Array
        ? c
        : // eslint-disable-line operator-linebreak
        // @ts-ignore
        globalThis.Buffer.from(c))
      // @ts-ignore
      return asU8A(globalThis.Buffer.concat(chunks, length))
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array[]} chunks
     * @param {number} length
     * @returns {Uint8Array}
     */
    (chunks, length) => {
      const out = new Uint8Array(length)
      let off = 0
      for (let b of chunks) {
        if (off + b.length > out.length) {
          // final chunk that's bigger than we need
          b = b.subarray(0, out.length - off)
        }
        out.set(b, off)
        off += b.length
      }
      return out
    }

export const alloc = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {number} size
     * @returns {Uint8Array}
     */
    (size) => {
      // we always write over the contents we expose so this should be safe
      // @ts-ignore
      return globalThis.Buffer.allocUnsafe(size)
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {number} size
     * @returns {Uint8Array}
     */
    (size) => {
      return new Uint8Array(size)
    }

export const toHex = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} d
     * @returns {string}
     */
    (d) => {
      if (typeof d === 'string') {
        return d
      }
      // @ts-ignore
      return globalThis.Buffer.from(toBytes(d)).toString('hex')
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} d
     * @returns {string}
     */
    (d) => {
      if (typeof d === 'string') {
        return d
      }
      // @ts-ignore not smart enough to figure this out
      return Array.prototype.reduce.call(toBytes(d), (p, c) => `${p}${c.toString(16).padStart(2, '0')}`, '')
    }

export const fromHex = useBuffer
  ? // eslint-disable-line operator-linebreak
  /**
   * @param {string|Uint8Array} hex
   * @returns {Uint8Array}
   */
    (hex) => {
      if (hex instanceof Uint8Array) {
        return hex
      }
      // @ts-ignore
      return globalThis.Buffer.from(hex, 'hex')
    }
  : // eslint-disable-line operator-linebreak
  /**
   * @param {string|Uint8Array} hex
   * @returns {Uint8Array}
   */
    (hex) => {
      if (hex instanceof Uint8Array) {
        return hex
      }
      if (!hex.length) {
        return new Uint8Array(0)
      }
      return new Uint8Array(hex.split('')
        .map((/** @type {string} */ c, /** @type {number} */ i, /** @type {string[]} */ d) => i % 2 === 0 ? `0x${c}${d[i + 1]}` : '')
        .filter(Boolean)
        .map((/** @type {string} */ e) => parseInt(e, 16)))
    }

/**
 * @param {Uint8Array|ArrayBuffer|ArrayBufferView} obj
 * @returns {Uint8Array}
 */
function toBytes (obj) {
  if (obj instanceof Uint8Array && obj.constructor.name === 'Uint8Array') {
    return obj
  }
  if (obj instanceof ArrayBuffer) {
    return new Uint8Array(obj)
  }
  if (ArrayBuffer.isView(obj)) {
    return new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength)
  }
  throw new Error('Unknown type, must be binary type')
}

/**
 * @param {Uint8Array} b1
 * @param {Uint8Array} b2
 * @returns {number}
 */
export function compare (b1, b2) {
  if (isBuffer(b1) && isBuffer(b2)) {
    // probably not possible to get here in the current API
    // @ts-ignore Buffer
    return b1.compare(b2)
  }
  for (let i = 0; i < b1.length; i++) {
    if (b1[i] === b2[i]) {
      continue
    }
    return b1[i] < b2[i] ? -1 : 1
  }
  return 0
}

// The below code is taken from https://github.com/google/closure-library/blob/8598d87242af59aac233270742c8984e2b2bdbe0/closure/goog/crypt/crypt.js#L117-L143
// Licensed Apache-2.0.

/**
 * @param {string} str
 * @returns {number[]}
 */
function utf8ToBytes (str) {
  const out = []
  let p = 0
  for (let i = 0; i < str.length; i++) {
    let c = str.charCodeAt(i)
    if (c < 128) {
      out[p++] = c
    } else if (c < 2048) {
      out[p++] = (c >> 6) | 192
      out[p++] = (c & 63) | 128
    } else if (
      ((c & 0xFC00) === 0xD800) && (i + 1) < str.length &&
      ((str.charCodeAt(i + 1) & 0xFC00) === 0xDC00)) {
      // Surrogate Pair
      c = 0x10000 + ((c & 0x03FF) << 10) + (str.charCodeAt(++i) & 0x03FF)
      out[p++] = (c >> 18) | 240
      out[p++] = ((c >> 12) & 63) | 128
      out[p++] = ((c >> 6) & 63) | 128
      out[p++] = (c & 63) | 128
    } else {
      if ((c >= 0xD800) && (c <= 0xDFFF)) {
        c = 0xFFFD // Unpaired Surrogate
      }
      out[p++] = (c >> 12) | 224
      out[p++] = ((c >> 6) & 63) | 128
      out[p++] = (c & 63) | 128
    }
  }
  return out
}

// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
const MAX_ARGUMENTS_LENGTH = 0x1000

/**
 * @param {number[]} codePoints
 * @returns {string}
 */
export function decodeCodePointsArray (codePoints) {
  const len = codePoints.length
  if (len <= MAX_ARGUMENTS_LENGTH) {
    return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  }
  // Decode in chunks to avoid "call stack size exceeded".
  let res = ''
  let i = 0
  while (i < len) {
    res += String.fromCharCode.apply(
      String,
      codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
    )
  }
  return res
}
const decodeErrPrefix = 'CBOR decode error:'
const encodeErrPrefix = 'CBOR encode error:'

const uintMinorPrefixBytes = []
uintMinorPrefixBytes[23] = 1
uintMinorPrefixBytes[24] = 2
uintMinorPrefixBytes[25] = 3
uintMinorPrefixBytes[26] = 5
uintMinorPrefixBytes[27] = 9

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} need
 */
function assertEnoughData (data, pos, need) {
  if (data.length - pos < need) {
    throw new Error(`${decodeErrPrefix} not enough data for type`)
  }
}

export {
  decodeErrPrefix,
  encodeErrPrefix,
  uintMinorPrefixBytes,
  assertEnoughData
}
import { decodeErrPrefix } from './common.js'
import { Type } from './token.js'
import { jump, quick } from './jump.js'
import { asU8A } from './byte-utils.js'

/**
 * @typedef {import('./token.js').Token} Token
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 * @typedef {import('../interface.js').DecodeTokenizer} DecodeTokenizer
 * @typedef {import('../interface.js').TagDecodeControl} TagDecodeControl
 */

const defaultDecodeOptions = {
  strict: false,
  allowIndefinite: true,
  allowUndefined: true,
  allowBigInt: true
}

/**
 * @implements {DecodeTokenizer}
 */
class Tokeniser {
  /**
   * @param {Uint8Array} data
   * @param {DecodeOptions} options
   */
  constructor (data, options = {}) {
    this._pos = 0
    this.data = data
    this.options = options
  }

  pos () {
    return this._pos
  }

  done () {
    return this._pos >= this.data.length
  }

  next () {
    const byt = this.data[this._pos]
    let token = quick[byt]
    if (token === undefined) {
      const decoder = jump[byt]
      // if we're here then there's something wrong with our jump or quick lists!
      if (!decoder) {
        throw new Error(`${decodeErrPrefix} no decoder for major type ${byt >>> 5} (byte 0x${byt.toString(16).padStart(2, '0')})`)
      }
      const minor = byt & 31
      token = decoder(this.data, this._pos, minor, this.options)
    }
    // @ts-ignore we get to assume encodedLength is set (crossing fingers slightly)
    this._pos += token.encodedLength
    return token
  }
}

const DONE = Symbol.for('DONE')
const BREAK = Symbol.for('BREAK')

/**
 * @param {Token} token
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {any|BREAK|DONE}
 */
function tokenToArray (token, tokeniser, options) {
  const arr = []
  for (let i = 0; i < token.value; i++) {
    const value = tokensToObject(tokeniser, options)
    if (value === BREAK) {
      if (token.value === Infinity) {
        // normal end to indefinite length array
        break
      }
      throw new Error(`${decodeErrPrefix} got unexpected break to lengthed array`)
    }
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} found array but not enough entries (got ${i}, expected ${token.value})`)
    }
    arr[i] = value
  }
  return arr
}

/**
 * @param {Token} token
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {any|BREAK|DONE}
 */
function tokenToMap (token, tokeniser, options) {
  const useMaps = options.useMaps === true
  const rejectDuplicateMapKeys = options.rejectDuplicateMapKeys === true
  const obj = useMaps ? undefined : {}
  const m = useMaps ? new Map() : undefined
  for (let i = 0; i < token.value; i++) {
    const key = tokensToObject(tokeniser, options)
    if (key === BREAK) {
      if (token.value === Infinity) {
        // normal end to indefinite length map
        break
      }
      throw new Error(`${decodeErrPrefix} got unexpected break to lengthed map`)
    }
    if (key === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no key], expected ${token.value})`)
    }
    if (!useMaps && typeof key !== 'string') {
      throw new Error(`${decodeErrPrefix} non-string keys not supported (got ${typeof key})`)
    }
    if (rejectDuplicateMapKeys) {
      // @ts-ignore
      if ((useMaps && m.has(key)) || (!useMaps && Object.hasOwn(obj, key))) {
        throw new Error(`${decodeErrPrefix} found repeat map key "${key}"`)
      }
    }
    const value = tokensToObject(tokeniser, options)
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no value], expected ${token.value})`)
    }
    if (useMaps) {
      // @ts-ignore TODO reconsider this .. maybe needs to be strict about key types
      m.set(key, value)
    } else {
      // @ts-ignore TODO reconsider this .. maybe needs to be strict about key types
      obj[key] = value
    }
  }
  // @ts-ignore c'mon man
  return useMaps ? m : obj
}

/**
 * Generator that yields [key, value] entries from a CBOR map token.
 * Used by tag decoders that need to preserve key types (e.g., Tag 259 Map).
 * @param {Token} token - The map token
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {Generator<[any, any], void, unknown>}
 */
function * tokenToMapEntries (token, tokeniser, options) {
  for (let i = 0; i < token.value; i++) {
    const key = tokensToObject(tokeniser, options)
    if (key === BREAK) {
      if (token.value === Infinity) {
        // normal end to indefinite length map
        break
      }
      throw new Error(`${decodeErrPrefix} got unexpected break to lengthed map`)
    }
    if (key === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no key], expected ${token.value})`)
    }
    const value = tokensToObject(tokeniser, options)
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no value], expected ${token.value})`)
    }
    yield [key, value]
  }
}

/**
 * Creates a TagDecodeControl object for tag decoders.
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {TagDecodeControl}
 */
function createTagDecodeControl (tokeniser, options) {
  let called = false

  /**
   * @type {TagDecodeControl}
   */
  const decode = function () {
    if (called) {
      throw new Error(`${decodeErrPrefix} tag decode() may only be called once`)
    }
    called = true
    const value = tokensToObject(tokeniser, options)
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} tag content missing`)
    }
    if (value === BREAK) {
      throw new Error(`${decodeErrPrefix} got unexpected break in tag content`)
    }
    return value
  }

  decode.entries = function () {
    if (called) {
      throw new Error(`${decodeErrPrefix} tag decode() may only be called once`)
    }
    called = true

    // Get the next token and ensure it's a map
    const token = tokeniser.next()
    if (!Type.equals(token.type, Type.map)) {
      throw new Error(`${decodeErrPrefix} entries() requires map content, got ${token.type.name}`)
    }

    // Collect all entries into an array (ensures full content consumption)
    const entries = []
    for (const entry of tokenToMapEntries(token, tokeniser, options)) {
      entries.push(entry)
    }
    return entries
  }

  // For internal tracking
  Object.defineProperty(decode, '_called', {
    get () { return called },
    enumerable: false
  })

  return decode
}

/**
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {any|BREAK|DONE}
 */
function tokensToObject (tokeniser, options) {
  // should we support array as an argument?
  // check for tokenIter[Symbol.iterator] and replace tokenIter with what that returns?
  if (tokeniser.done()) {
    return DONE
  }

  const token = tokeniser.next()

  if (Type.equals(token.type, Type.break)) {
    return BREAK
  }

  if (token.type.terminal) {
    return token.value
  }

  if (Type.equals(token.type, Type.array)) {
    return tokenToArray(token, tokeniser, options)
  }

  if (Type.equals(token.type, Type.map)) {
    return tokenToMap(token, tokeniser, options)
  }

  if (Type.equals(token.type, Type.tag)) {
    if (options.tags && typeof options.tags[token.value] === 'function') {
      const decodeControl = createTagDecodeControl(tokeniser, options)
      const result = options.tags[token.value](decodeControl)
      if (!decodeControl._called) {
        throw new Error(`${decodeErrPrefix} tag decoder must call decode() or entries()`)
      }
      return result
    }
    throw new Error(`${decodeErrPrefix} tag not supported (${token.value})`)
  }
  throw new Error('unsupported')
}

/**
 * @param {Uint8Array} data
 * @param {DecodeOptions} [options]
 * @returns {[any, Uint8Array]}
 */
function decodeFirst (data, options) {
  if (!(data instanceof Uint8Array)) {
    throw new Error(`${decodeErrPrefix} data to decode must be a Uint8Array`)
  }
  options = Object.assign({}, defaultDecodeOptions, options)
  // Convert Buffer to plain Uint8Array for faster slicing in decode path
  const u8aData = asU8A(data)
  const tokeniser = options.tokenizer || new Tokeniser(u8aData, options)
  const decoded = tokensToObject(tokeniser, options)
  if (decoded === DONE) {
    throw new Error(`${decodeErrPrefix} did not find any content to decode`)
  }
  if (decoded === BREAK) {
    throw new Error(`${decodeErrPrefix} got unexpected break`)
  }
  return [decoded, data.subarray(tokeniser.pos())]
}

/**
 * @param {Uint8Array} data
 * @param {DecodeOptions} [options]
 * @returns {any}
 */
function decode (data, options) {
  const [decoded, remainder] = decodeFirst(data, options)
  if (remainder.length > 0) {
    throw new Error(`${decodeErrPrefix} too many terminals, data makes no sense`)
  }
  return decoded
}

export { Tokeniser, tokensToObject, decode, decodeFirst }
import { is } from './is.js'
import { Token, Type } from './token.js'
import { Bl, U8Bl } from './bl.js'
import { encodeErrPrefix } from './common.js'
import { quickEncodeToken } from './jump.js'
import { asU8A, compare, fromString } from './byte-utils.js'

import { encodeUint, encodeUintValue } from './0uint.js'
import { encodeNegint } from './1negint.js'
import { encodeBytes } from './2bytes.js'
import { encodeString } from './3string.js'
import { encodeArray } from './4array.js'
import { encodeMap } from './5map.js'
import { encodeTag } from './6tag.js'
import { encodeFloat, MINOR_FALSE, MINOR_TRUE, MINOR_NULL, MINOR_UNDEFINED } from './7float.js'

/**
 * @typedef {import('../interface.js').EncodeOptions} EncodeOptions
 * @typedef {import('../interface.js').OptionalTypeEncoder} OptionalTypeEncoder
 * @typedef {import('../interface.js').Reference} Reference
 * @typedef {import('../interface.js').StrictTypeEncoder} StrictTypeEncoder
 * @typedef {import('../interface.js').TokenTypeEncoder} TokenTypeEncoder
 * @typedef {import('../interface.js').TokenOrNestedTokens} TokenOrNestedTokens
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 */

/** @type {EncodeOptions} */
const defaultEncodeOptions = {
  float64: false,
  mapSorter,
  quickEncodeToken
}

/** @type {EncodeOptions} */
export const rfc8949EncodeOptions = Object.freeze({
  mapSorter: rfc8949MapSorter,
  quickEncodeToken
})

/** @returns {TokenTypeEncoder[]} */
export function makeCborEncoders () {
  const encoders = []
  encoders[Type.uint.major] = encodeUint
  encoders[Type.negint.major] = encodeNegint
  encoders[Type.bytes.major] = encodeBytes
  encoders[Type.string.major] = encodeString
  encoders[Type.array.major] = encodeArray
  encoders[Type.map.major] = encodeMap
  encoders[Type.tag.major] = encodeTag
  encoders[Type.float.major] = encodeFloat
  return encoders
}

const cborEncoders = makeCborEncoders()

const defaultWriter = new Bl()

/** @implements {Reference} */
class Ref {
  /**
   * @param {object|any[]} obj
   * @param {Reference|undefined} parent
   */
  constructor (obj, parent) {
    this.obj = obj
    this.parent = parent
  }

  /**
   * @param {object|any[]} obj
   * @returns {boolean}
   */
  includes (obj) {
    /** @type {Reference|undefined} */
    let p = this
    do {
      if (p.obj === obj) {
        return true
      }
    } while (p = p.parent) // eslint-disable-line
    return false
  }

  /**
   * @param {Reference|undefined} stack
   * @param {object|any[]} obj
   * @returns {Reference}
   */
  static createCheck (stack, obj) {
    if (stack && stack.includes(obj)) {
      throw new Error(`${encodeErrPrefix} object contains circular references`)
    }
    return new Ref(obj, stack)
  }
}

const simpleTokens = {
  null: new Token(Type.null, null),
  undefined: new Token(Type.undefined, undefined),
  true: new Token(Type.true, true),
  false: new Token(Type.false, false),
  emptyArray: new Token(Type.array, 0),
  emptyMap: new Token(Type.map, 0)
}

/** @type {{[typeName: string]: StrictTypeEncoder}} */
const typeEncoders = {
  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  number (obj, _typ, _options, _refStack) {
    if (!Number.isInteger(obj) || !Number.isSafeInteger(obj)) {
      return new Token(Type.float, obj)
    } else if (obj >= 0) {
      return new Token(Type.uint, obj)
    } else {
      return new Token(Type.negint, obj)
    }
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  bigint (obj, _typ, _options, _refStack) {
    if (obj >= BigInt(0)) {
      return new Token(Type.uint, obj)
    } else {
      return new Token(Type.negint, obj)
    }
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  Uint8Array (obj, _typ, _options, _refStack) {
    return new Token(Type.bytes, obj)
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  string (obj, _typ, _options, _refStack) {
    return new Token(Type.string, obj)
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  boolean (obj, _typ, _options, _refStack) {
    return obj ? simpleTokens.true : simpleTokens.false
  },

  /**
   * @param {any} _obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  null (_obj, _typ, _options, _refStack) {
    return simpleTokens.null
  },

  /**
   * @param {any} _obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  undefined (_obj, _typ, _options, _refStack) {
    return simpleTokens.undefined
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  ArrayBuffer (obj, _typ, _options, _refStack) {
    return new Token(Type.bytes, new Uint8Array(obj))
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  DataView (obj, _typ, _options, _refStack) {
    return new Token(Type.bytes, new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength))
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} options
   * @param {Reference} [refStack]
   * @returns {TokenOrNestedTokens}
   */
  Array (obj, _typ, options, refStack) {
    if (!obj.length) {
      if (options.addBreakTokens === true) {
        return [simpleTokens.emptyArray, new Token(Type.break)]
      }
      return simpleTokens.emptyArray
    }
    refStack = Ref.createCheck(refStack, obj)
    const entries = []
    let i = 0
    for (const e of obj) {
      entries[i++] = objectToTokens(e, options, refStack)
    }
    if (options.addBreakTokens) {
      return [new Token(Type.array, obj.length), entries, new Token(Type.break)]
    }
    return [new Token(Type.array, obj.length), entries]
  },

  /**
   * @param {any} obj
   * @param {string} typ
   * @param {EncodeOptions} options
   * @param {Reference} [refStack]
   * @returns {TokenOrNestedTokens}
   */
  Object (obj, typ, options, refStack) {
    // could be an Object or a Map
    const isMap = typ !== 'Object'
    // it's slightly quicker to use Object.keys() than Object.entries()
    const keys = isMap ? obj.keys() : Object.keys(obj)
    const maxLength = isMap ? obj.size : keys.length

    /** @type {undefined | [TokenOrNestedTokens, TokenOrNestedTokens][]} */
    let entries

    if (maxLength) {
      // Pre-allocate the array with the expected size
      entries = new Array(maxLength)
      refStack = Ref.createCheck(refStack, obj)
      const skipUndefined = !isMap && options.ignoreUndefinedProperties

      let i = 0
      for (const key of keys) {
        const value = isMap ? obj.get(key) : obj[key]
        if (skipUndefined && value === undefined) {
          continue
        }
        entries[i++] = [
          objectToTokens(key, options, refStack),
          objectToTokens(value, options, refStack)
        ]
      }

      // Truncate only if properties were skipped
      if (i < maxLength) {
        entries.length = i
      }
    }

    if (!entries?.length) {
      if (options.addBreakTokens === true) {
        return [simpleTokens.emptyMap, new Token(Type.break)]
      }
      return simpleTokens.emptyMap
    }

    sortMapEntries(entries, options)
    if (options.addBreakTokens) {
      return [new Token(Type.map, entries.length), entries, new Token(Type.break)]
    }
    return [new Token(Type.map, entries.length), entries]
  },

  /**
   * Encode a `Tagged` wrapper as a CBOR tag header followed by the encoded
   * form of the wrapped value. The value is recursively tokenised through
   * `objectToTokens()` so any registered `typeEncoders` apply to it.
   *
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} options
   * @param {Reference} [refStack]
   * @returns {TokenOrNestedTokens}
   */
  Tagged (obj, _typ, options, refStack) {
    return [
      new Token(Type.tag, obj.tag),
      objectToTokens(obj.value, options, refStack)
    ]
  }
}

typeEncoders.Map = typeEncoders.Object
typeEncoders.Buffer = typeEncoders.Uint8Array
for (const typ of 'Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64'.split(' ')) {
  typeEncoders[`${typ}Array`] = typeEncoders.DataView
}

/**
 * @param {any} obj
 * @param {EncodeOptions} [options]
 * @param {Reference} [refStack]
 * @returns {TokenOrNestedTokens}
 */
function objectToTokens (obj, options = {}, refStack) {
  const typ = is(obj)
  const customTypeEncoder = (options && options.typeEncoders && /** @type {OptionalTypeEncoder} */ options.typeEncoders[typ]) || typeEncoders[typ]
  if (typeof customTypeEncoder === 'function') {
    const tokens = customTypeEncoder(obj, typ, options, refStack)
    if (tokens != null) {
      return tokens
    }
  }
  const typeEncoder = typeEncoders[typ]
  if (!typeEncoder) {
    throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`)
  }
  return typeEncoder(obj, typ, options, refStack)
}

/*
CBOR key sorting is a mess.

The canonicalisation recommendation from https://tools.ietf.org/html/rfc7049#section-3.9
includes the wording:

> The keys in every map must be sorted lowest value to highest.
> Sorting is performed on the bytes of the representation of the key
> data items without paying attention to the 3/5 bit splitting for
> major types.
> ...
>  *  If two keys have different lengths, the shorter one sorts
      earlier;
>  *  If two keys have the same length, the one with the lower value
      in (byte-wise) lexical order sorts earlier.

1. It is not clear what "bytes of the representation of the key" means: is it
   the CBOR representation, or the binary representation of the object itself?
   Consider the int and uint difference here.
2. It is not clear what "without paying attention to" means: do we include it
   and compare on that? Or do we omit the special prefix byte, (mostly) treating
   the key in its plain binary representation form.

The FIDO 2.0: Client To Authenticator Protocol spec takes the original CBOR
wording and clarifies it according to their understanding.
https://fidoalliance.org/specs/fido-v2.0-rd-20170927/fido-client-to-authenticator-protocol-v2.0-rd-20170927.html#message-encoding

> The keys in every map must be sorted lowest value to highest. Sorting is
> performed on the bytes of the representation of the key data items without
> paying attention to the 3/5 bit splitting for major types. The sorting rules
> are:
>  * If the major types are different, the one with the lower value in numerical
>    order sorts earlier.
>  * If two keys have different lengths, the shorter one sorts earlier;
>  * If two keys have the same length, the one with the lower value in
>    (byte-wise) lexical order sorts earlier.

Some other implementations, such as borc, do a full encode then do a
length-first, byte-wise-second comparison:
https://github.com/dignifiedquire/borc/blob/b6bae8b0bcde7c3976b0f0f0957208095c392a36/src/encoder.js#L358
https://github.com/dignifiedquire/borc/blob/b6bae8b0bcde7c3976b0f0f0957208095c392a36/src/utils.js#L143-L151

This has the benefit of being able to easily handle arbitrary keys, including
complex types (maps and arrays).

We'll opt for the FIDO approach, since it affords some efficies since we don't
need a full encode of each key to determine order and can defer to the types
to determine how to most efficiently order their values (i.e. int and uint
ordering can be done on the numbers, no need for byte-wise, for example).

Recommendation: stick to single key types or you'll get into trouble, and prefer
string keys because it's much simpler that way.
*/

/**
 * @param {TokenOrNestedTokens[]} entries
 * @param {EncodeOptions} options
 */
function sortMapEntries (entries, options) {
  if (options.mapSorter) {
    entries.sort(options.mapSorter)
  }
}

/**
 * @param {(Token|Token[])[]} e1
 * @param {(Token|Token[])[]} e2
 * @returns {number}
 */
function mapSorter (e1, e2) {
  // the key position ([0]) could have a single token or an array
  // almost always it'll be a single token but complex key might get involved
  const keyToken1 = Array.isArray(e1[0]) ? e1[0][0] : e1[0]
  const keyToken2 = Array.isArray(e2[0]) ? e2[0][0] : e2[0]

  // different key types
  if (keyToken1.type !== keyToken2.type) {
    return keyToken1.type.compare(keyToken2.type)
  }

  const major = keyToken1.type.major
  // TODO: handle case where cmp === 0 but there are more keyToken e. complex type)
  const tcmp = cborEncoders[major].compareTokens(keyToken1, keyToken2)
  if (tcmp === 0) {
    // duplicate key or complex type where the first token matched,
    // i.e. a map or array and we're only comparing the opening token
    console.warn('WARNING: complex key types used, CBOR key sorting guarantees are gone')
  }
  return tcmp
}

/**
 * @typedef {Token & { _keyBytes?: Uint8Array }} TokenEx
 *
 * @param {(Token|Token[])[]} e1
 * @param {(Token|Token[])[]} e2
 * @returns {number}
 */
function rfc8949MapSorter (e1, e2) {
  if (e1[0] instanceof Token && e2[0] instanceof Token) {
    const t1 = /** @type {TokenEx} */ (e1[0])
    const t2 = /** @type {TokenEx} */ (e2[0])

    if (!t1._keyBytes) {
      t1._keyBytes = encodeRfc8949(t1.value)
    }

    if (!t2._keyBytes) {
      t2._keyBytes = encodeRfc8949(t2.value)
    }

    return compare(t1._keyBytes, t2._keyBytes)
  }

  throw new Error('rfc8949MapSorter: complex key types are not supported yet')
}

/**
 * @param {any} data
 * @returns {Uint8Array}
 */
function encodeRfc8949 (data) {
  return encodeCustom(data, cborEncoders, rfc8949EncodeOptions)
}

/**
 * @param {ByteWriter} writer
 * @param {TokenOrNestedTokens} tokens
 * @param {TokenTypeEncoder[]} encoders
 * @param {EncodeOptions} options
 */
function tokensToEncoded (writer, tokens, encoders, options) {
  if (Array.isArray(tokens)) {
    for (const token of tokens) {
      tokensToEncoded(writer, token, encoders, options)
    }
  } else {
    encoders[tokens.type.major](writer, tokens, options)
  }
}

// CBOR major type prefixes, cached from Type for hot path performance
const MAJOR_UINT = Type.uint.majorEncoded
const MAJOR_NEGINT = Type.negint.majorEncoded
const MAJOR_BYTES = Type.bytes.majorEncoded
const MAJOR_STRING = Type.string.majorEncoded
const MAJOR_ARRAY = Type.array.majorEncoded

// Simple value bytes (CBOR major type 7 + minor value)
const SIMPLE_FALSE = Type.float.majorEncoded | MINOR_FALSE
const SIMPLE_TRUE = Type.float.majorEncoded | MINOR_TRUE
const SIMPLE_NULL = Type.float.majorEncoded | MINOR_NULL
const SIMPLE_UNDEFINED = Type.float.majorEncoded | MINOR_UNDEFINED

const neg1b = BigInt(-1)
const pos1b = BigInt(1)

/**
 * Check if direct encoding can be used for the given options.
 * Direct encoding bypasses token creation for most values.
 * @param {EncodeOptions} options
 * @returns {boolean}
 */
function canDirectEncode (options) {
  // Cannot use direct encode with addBreakTokens (needs special break token handling).
  // Direct encode checks typeEncoders per-value, falling back to tokens as needed.
  // Maps fall back to token-based encoding for efficient key sorting.
  return options.addBreakTokens !== true
}

/**
 * Direct encode a value to the writer, bypassing token creation for most types.
 * Falls back to token-based encoding for custom type encoders.
 * @param {ByteWriter} writer
 * @param {any} data
 * @param {EncodeOptions} options
 * @param {Reference|undefined} refStack
 */
function directEncode (writer, data, options, refStack) {
  const typ = is(data)

  // Check for custom encoder for THIS specific type
  const customEncoder = options.typeEncoders && options.typeEncoders[typ]
  if (customEncoder) {
    const tokens = customEncoder(data, typ, options, refStack)
    if (tokens != null) {
      // Custom encoder returned tokens, serialize immediately
      tokensToEncoded(writer, tokens, cborEncoders, options)
      return
    }
    // Custom encoder returned null, fall through to default handling
  }

  // Direct encode based on type
  switch (typ) {
    case 'null':
      writer.push([SIMPLE_NULL])
      return

    case 'undefined':
      writer.push([SIMPLE_UNDEFINED])
      return

    case 'boolean':
      writer.push([data ? SIMPLE_TRUE : SIMPLE_FALSE])
      return

    case 'number':
      if (!Number.isInteger(data) || !Number.isSafeInteger(data)) {
        // Float, use token encoder for complex float encoding
        encodeFloat(writer, new Token(Type.float, data), options)
      } else if (data >= 0) {
        encodeUintValue(writer, MAJOR_UINT, data)
      } else {
        // Negative integer
        encodeUintValue(writer, MAJOR_NEGINT, data * -1 - 1)
      }
      return

    case 'bigint':
      if (data >= BigInt(0)) {
        encodeUintValue(writer, MAJOR_UINT, data)
      } else {
        encodeUintValue(writer, MAJOR_NEGINT, data * neg1b - pos1b)
      }
      return

    case 'string': {
      const bytes = fromString(data)
      encodeUintValue(writer, MAJOR_STRING, bytes.length)
      writer.push(bytes)
      return
    }

    case 'Uint8Array':
      encodeUintValue(writer, MAJOR_BYTES, data.length)
      writer.push(data)
      return

    case 'Array':
      if (!data.length) {
        writer.push([MAJOR_ARRAY]) // Empty array: 0x80
        return
      }
      refStack = Ref.createCheck(refStack, data)
      encodeUintValue(writer, MAJOR_ARRAY, data.length)
      for (const elem of data) {
        directEncode(writer, elem, options, refStack)
      }
      return

    case 'Object':
    case 'Map':
      // Maps require key sorting, use token-based encoding for efficiency
      // (pre-encoding all keys for sorting is expensive)
      {
        const tokens = typeEncoders.Object(data, typ, options, refStack)
        tokensToEncoded(writer, tokens, cborEncoders, options)
      }
      return

    default:
    // Fall back to token-based encoding for other types (DataView, TypedArrays, etc.)
    {
      const typeEncoder = typeEncoders[typ]
      if (!typeEncoder) {
        throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`)
      }
      const tokens = typeEncoder(data, typ, options, refStack)
      tokensToEncoded(writer, tokens, cborEncoders, options)
    }
  }
}

/**
 * @param {any} data
 * @param {TokenTypeEncoder[]} encoders
 * @param {EncodeOptions} options
 * @param {Uint8Array} [destination]
 * @returns {Uint8Array}
 */
function encodeCustom (data, encoders, options, destination) {
  // arg ordering is different to encodeInto for backward compatibility
  const hasDest = destination instanceof Uint8Array
  let writeTo = hasDest ? new U8Bl(destination) : defaultWriter

  const tokens = objectToTokens(data, options)
  if (!Array.isArray(tokens) && options.quickEncodeToken) {
    const quickBytes = options.quickEncodeToken(tokens)
    if (quickBytes) {
      if (hasDest) {
        // Copy quick bytes into destination buffer
        writeTo.push(quickBytes)
        return writeTo.toBytes()
      }
      return quickBytes
    }
    const encoder = encoders[tokens.type.major]
    if (encoder.encodedSize) {
      const size = encoder.encodedSize(tokens, options)
      if (!hasDest) {
        writeTo = new Bl(size)
      }
      encoder(writeTo, tokens, options)
      // this would be a problem with encodedSize() functions
      if (writeTo.chunks.length !== 1) {
        throw new Error(`Unexpected error: pre-calculated length for ${tokens} was wrong`)
      }
      return hasDest ? writeTo.toBytes() : asU8A(writeTo.chunks[0])
    }
  }
  writeTo.reset()
  tokensToEncoded(writeTo, tokens, encoders, options)
  return writeTo.toBytes(true)
}

/**
 * @param {any} data
 * @param {EncodeOptions} [options]
 * @returns {Uint8Array}
 */
function encode (data, options) {
  options = Object.assign({}, defaultEncodeOptions, options)

  // Use direct encode path when possible
  if (canDirectEncode(options)) {
    defaultWriter.reset()
    directEncode(defaultWriter, data, options, undefined)
    return defaultWriter.toBytes(true)
  }

  return encodeCustom(data, cborEncoders, options)
}

/**
 * @param {any} data
 * @param {Uint8Array} destination
 * @param {EncodeOptions} [options]
 * @returns {{ written: number }}
 */
function encodeInto (data, destination, options) {
  options = Object.assign({}, defaultEncodeOptions, options)

  // Use direct encode path when possible
  if (canDirectEncode(options)) {
    const writer = new U8Bl(destination)
    directEncode(writer, data, options, undefined)
    return { written: writer.toBytes().length }
  }

  const result = encodeCustom(data, cborEncoders, options, destination)
  return { written: result.length }
}

export { objectToTokens, encode, encodeCustom, encodeInto, Ref }
// This is an unfortunate replacement for @sindresorhus/is that we need to
// re-implement for performance purposes. In particular the is.observable()
// check is expensive, and unnecessary for our purposes. The values returned
// are compatible with @sindresorhus/is, however.

// Types that reach getObjectType() - excludes types with fast-paths above:
// primitives (typeof), Array (isArray), Uint8Array (instanceof), plain Object (constructor)
const objectTypeNames = [
  'Object', // for Object.create(null) and other non-plain objects
  'RegExp',
  'Date',
  'Error',
  'Map',
  'Set',
  'WeakMap',
  'WeakSet',
  'ArrayBuffer',
  'SharedArrayBuffer',
  'DataView',
  'Promise',
  'URL',
  'HTMLElement',
  'Int8Array',
  'Uint8ClampedArray',
  'Int16Array',
  'Uint16Array',
  'Int32Array',
  'Uint32Array',
  'Float32Array',
  'Float64Array',
  'BigInt64Array',
  'BigUint64Array',
  'Tagged'
]

/**
 * @param {any} value
 * @returns {string}
 */
export function is (value) {
  if (value === null) {
    return 'null'
  }
  if (value === undefined) {
    return 'undefined'
  }
  if (value === true || value === false) {
    return 'boolean'
  }
  const typeOf = typeof value
  if (typeOf === 'string' || typeOf === 'number' || typeOf === 'bigint' || typeOf === 'symbol') {
    return typeOf
  }
  if (typeOf === 'function') {
    return 'Function'
  }
  if (Array.isArray(value)) {
    return 'Array'
  }
  // Also catches Node.js Buffer which extends Uint8Array
  if (value instanceof Uint8Array) {
    return 'Uint8Array'
  }
  // Fast path for plain objects (most common case after primitives/arrays/bytes)
  if (value.constructor === Object) {
    return 'Object'
  }
  const objectType = getObjectType(value)
  if (objectType) {
    return objectType
  }
  return 'Object'
}

/**
 * @param {any} value
 * @returns {string|undefined}
 */
function getObjectType (value) {
  const objectTypeName = Object.prototype.toString.call(value).slice(8, -1)
  if (objectTypeNames.includes(objectTypeName)) {
    return objectTypeName
  }
  return undefined
}
import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import * as negint from './1negint.js'
import * as bytes from './2bytes.js'
import * as string from './3string.js'
import * as array from './4array.js'
import * as map from './5map.js'
import * as tag from './6tag.js'
import * as float from './7float.js'
import { decodeErrPrefix } from './common.js'
import { fromArray } from './byte-utils.js'

/**
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 */
function invalidMinor (data, pos, minor) {
  throw new Error(`${decodeErrPrefix} encountered invalid minor (${minor}) for major ${data[pos] >>> 5}`)
}

/**
 * @param {string} msg
 * @returns {()=>any}
 */
function errorer (msg) {
  return () => { throw new Error(`${decodeErrPrefix} ${msg}`) }
}

/** @type {((data:Uint8Array, pos:number, minor:number, options?:DecodeOptions) => any)[]} */
export const jump = []

// unsigned integer, 0x00..0x17 (0..23)
for (let i = 0; i <= 0x17; i++) {
  jump[i] = invalidMinor // uint.decodeUintCompact, handled by quick[]
}
jump[0x18] = uint.decodeUint8 // unsigned integer, one-byte uint8_t follows
jump[0x19] = uint.decodeUint16 // unsigned integer, two-byte uint16_t follows
jump[0x1a] = uint.decodeUint32 // unsigned integer, four-byte uint32_t follows
jump[0x1b] = uint.decodeUint64 // unsigned integer, eight-byte uint64_t follows
jump[0x1c] = invalidMinor
jump[0x1d] = invalidMinor
jump[0x1e] = invalidMinor
jump[0x1f] = invalidMinor
// negative integer, -1-0x00..-1-0x17 (-1..-24)
for (let i = 0x20; i <= 0x37; i++) {
  jump[i] = invalidMinor // negintDecode, handled by quick[]
}
jump[0x38] = negint.decodeNegint8 // negative integer, -1-n one-byte uint8_t for n follows
jump[0x39] = negint.decodeNegint16 // negative integer, -1-n two-byte uint16_t for n follows
jump[0x3a] = negint.decodeNegint32 // negative integer, -1-n four-byte uint32_t for follows
jump[0x3b] = negint.decodeNegint64 // negative integer, -1-n eight-byte uint64_t for follows
jump[0x3c] = invalidMinor
jump[0x3d] = invalidMinor
jump[0x3e] = invalidMinor
jump[0x3f] = invalidMinor
// byte string, 0x00..0x17 bytes follow
for (let i = 0x40; i <= 0x57; i++) {
  jump[i] = bytes.decodeBytesCompact
}
jump[0x58] = bytes.decodeBytes8 // byte string, one-byte uint8_t for n, and then n bytes follow
jump[0x59] = bytes.decodeBytes16 // byte string, two-byte uint16_t for n, and then n bytes follow
jump[0x5a] = bytes.decodeBytes32 // byte string, four-byte uint32_t for n, and then n bytes follow
jump[0x5b] = bytes.decodeBytes64 // byte string, eight-byte uint64_t for n, and then n bytes follow
jump[0x5c] = invalidMinor
jump[0x5d] = invalidMinor
jump[0x5e] = invalidMinor
jump[0x5f] = errorer('indefinite length bytes/strings are not supported') // byte string, byte strings follow, terminated by "break"
// UTF-8 string 0x00..0x17 bytes follow
for (let i = 0x60; i <= 0x77; i++) {
  jump[i] = string.decodeStringCompact
}
jump[0x78] = string.decodeString8 // UTF-8 string, one-byte uint8_t for n, and then n bytes follow
jump[0x79] = string.decodeString16 // UTF-8 string, two-byte uint16_t for n, and then n bytes follow
jump[0x7a] = string.decodeString32 // UTF-8 string, four-byte uint32_t for n, and then n bytes follow
jump[0x7b] = string.decodeString64 // UTF-8 string, eight-byte uint64_t for n, and then n bytes follow
jump[0x7c] = invalidMinor
jump[0x7d] = invalidMinor
jump[0x7e] = invalidMinor
jump[0x7f] = errorer('indefinite length bytes/strings are not supported') // UTF-8 strings follow, terminated by "break"
// array, 0x00..0x17 data items follow
for (let i = 0x80; i <= 0x97; i++) {
  jump[i] = array.decodeArrayCompact
}
jump[0x98] = array.decodeArray8 // array, one-byte uint8_t for n, and then n data items follow
jump[0x99] = array.decodeArray16 // array, two-byte uint16_t for n, and then n data items follow
jump[0x9a] = array.decodeArray32 // array, four-byte uint32_t for n, and then n data items follow
jump[0x9b] = array.decodeArray64 // array, eight-byte uint64_t for n, and then n data items follow
jump[0x9c] = invalidMinor
jump[0x9d] = invalidMinor
jump[0x9e] = invalidMinor
jump[0x9f] = array.decodeArrayIndefinite // array, data items follow, terminated by "break"
// map, 0x00..0x17 pairs of data items follow
for (let i = 0xa0; i <= 0xb7; i++) {
  jump[i] = map.decodeMapCompact
}
jump[0xb8] = map.decodeMap8 // map, one-byte uint8_t for n, and then n pairs of data items follow
jump[0xb9] = map.decodeMap16 // map, two-byte uint16_t for n, and then n pairs of data items follow
jump[0xba] = map.decodeMap32 // map, four-byte uint32_t for n, and then n pairs of data items follow
jump[0xbb] = map.decodeMap64 // map, eight-byte uint64_t for n, and then n pairs of data items follow
jump[0xbc] = invalidMinor
jump[0xbd] = invalidMinor
jump[0xbe] = invalidMinor
jump[0xbf] = map.decodeMapIndefinite // map, pairs of data items follow, terminated by "break"
// tags
for (let i = 0xc0; i <= 0xd7; i++) {
  jump[i] = tag.decodeTagCompact
}
jump[0xd8] = tag.decodeTag8
jump[0xd9] = tag.decodeTag16
jump[0xda] = tag.decodeTag32
jump[0xdb] = tag.decodeTag64
jump[0xdc] = invalidMinor
jump[0xdd] = invalidMinor
jump[0xde] = invalidMinor
jump[0xdf] = invalidMinor
// 0xe0..0xf3 simple values, unsupported
for (let i = 0xe0; i <= 0xf3; i++) {
  jump[i] = errorer('simple values are not supported')
}
jump[0xf4] = invalidMinor // false, handled by quick[]
jump[0xf5] = invalidMinor // true, handled by quick[]
jump[0xf6] = invalidMinor // null, handled by quick[]
jump[0xf7] = float.decodeUndefined // undefined
jump[0xf8] = errorer('simple values are not supported') // simple value, one byte follows, unsupported
jump[0xf9] = float.decodeFloat16 // half-precision float (two-byte IEEE 754)
jump[0xfa] = float.decodeFloat32 // single-precision float (four-byte IEEE 754)
jump[0xfb] = float.decodeFloat64 // double-precision float (eight-byte IEEE 754)
jump[0xfc] = invalidMinor
jump[0xfd] = invalidMinor
jump[0xfe] = invalidMinor
jump[0xff] = float.decodeBreak // "break" stop code

/** @type {Token[]} */
export const quick = []
// ints <24
for (let i = 0; i < 24; i++) {
  quick[i] = new Token(Type.uint, i, 1)
}
// negints >= -24
for (let i = -1; i >= -24; i--) {
  quick[31 - i] = new Token(Type.negint, i, 1)
}
// empty bytes
quick[0x40] = new Token(Type.bytes, new Uint8Array(0), 1)
// empty string
quick[0x60] = new Token(Type.string, '', 1)
// empty list
quick[0x80] = new Token(Type.array, 0, 1)
// empty map
quick[0xa0] = new Token(Type.map, 0, 1)
// false
quick[0xf4] = new Token(Type.false, false, 1)
// true
quick[0xf5] = new Token(Type.true, true, 1)
// null
quick[0xf6] = new Token(Type.null, null, 1)

/**
 * @param {Token} token
 * @returns {Uint8Array|undefined}
 */
export function quickEncodeToken (token) {
  switch (token.type) {
    case Type.false:
      return fromArray([0xf4])
    case Type.true:
      return fromArray([0xf5])
    case Type.null:
      return fromArray([0xf6])
    case Type.bytes:
      if (!token.value.length) {
        return fromArray([0x40])
      }
      return
    case Type.string:
      if (token.value === '') {
        return fromArray([0x60])
      }
      return
    case Type.array:
      if (token.value === 0) {
        return fromArray([0x80])
      }
      // shouldn't be possible if this were called when there was only one token
      return
    case Type.map:
      if (token.value === 0) {
        return fromArray([0xa0])
      }
      // shouldn't be possible if this were called when there was only one token
      return
    case Type.uint:
      if (token.value < 24) {
        return fromArray([Number(token.value)])
      }
      return
    case Type.negint:
      if (token.value >= -24) {
        return fromArray([31 - Number(token.value)])
      }
  }
}
/**
 * @typedef {import('../interface.js').TagDecodeControl} TagDecodeControl
 * @typedef {(decode: TagDecodeControl) => Tagged} TaggedTagDecoder
 */

/**
 * A wrapper class for representing a CBOR tag with an arbitrary nested value.
 *
 * `Tagged` is a symmetric primitive: it can be passed to `encode()` to emit
 * a CBOR tag header followed by the encoded form of `value`, and it can be
 * returned from a tag decoder (via `Tagged.decoder(tag)` or `Tagged.preserve()`)
 * to round-trip a tag through decode without losing the tag number.
 *
 * Use `Tagged` for one-off tag handling where defining a dedicated
 * `typeEncoders` entry and tag decoder pair would be heavyweight, e.g. when
 * wrapping a structure in a single application-specific tag (COSE, dCBOR
 * envelopes, etc.).
 *
 * For systematic mapping of a JS type to a tag (e.g. CID -> tag 42), prefer
 * a dedicated `typeEncoders` entry instead.
 */
export class Tagged {
  /**
   * @param {number} tag - CBOR tag number, a non-negative integer
   * @param {any} value - The value to be tagged; encoded recursively
   */
  constructor (tag, value) {
    if (typeof tag !== 'number' || !Number.isInteger(tag) || tag < 0) {
      throw new TypeError('Tagged: tag must be a non-negative integer')
    }
    this.tag = tag
    this.value = value
  }

  /**
   * Build a tag decoder for use in `decode()`'s `tags` option that returns the
   * decoded content wrapped in a `Tagged` instance, preserving the tag number
   * for the caller to inspect.
   *
   * @param {number} tag - The CBOR tag number this decoder will be registered for
   * @returns {TaggedTagDecoder}
   *
   * @example
   * import { decode, Tagged } from 'cborg'
   * const value = decode(bytes, { tags: { 16: Tagged.decoder(16) } })
   * // value instanceof Tagged; value.tag === 16
   */
  static decoder (tag) {
    return (decode) => new Tagged(tag, decode())
  }

  /**
   * Build a `tags` option for `decode()` that wraps each listed tag number in
   * a `Tagged` instance, preserving those tags through decode without
   * registering a dedicated decoder per tag.
   *
   * @param {...number} tagNumbers - One or more CBOR tag numbers to preserve
   * @returns {{[tagNumber: number]: TaggedTagDecoder}}
   *
   * @example
   * import { decode, Tagged } from 'cborg'
   * const value = decode(bytes, { tags: Tagged.preserve(16, 96) })
   */
  static preserve (...tagNumbers) {
    /** @type {{[tagNumber: number]: TaggedTagDecoder}} */
    const tags = {}
    for (const tag of tagNumbers) {
      tags[tag] = Tagged.decoder(tag)
    }
    return tags
  }
}

// Symbol.toStringTag so the internal `is()` type detection returns 'Tagged'
// for instances, allowing the default Tagged typeEncoder to match.
Object.defineProperty(Tagged.prototype, Symbol.toStringTag, {
  value: 'Tagged'
})
class Type {
  /**
   * @param {number} major
   * @param {string} name
   * @param {boolean} terminal
   */
  constructor (major, name, terminal) {
    this.major = major
    this.majorEncoded = major << 5
    this.name = name
    this.terminal = terminal
  }

  toString () {
    return `Type[${this.major}].${this.name}`
  }

  /**
   * @param {Type} typ
   * @returns {number}
   */
  compare (typ) {
    return this.major < typ.major ? -1 : this.major > typ.major ? 1 : 0
  }

  /**
   * Check equality between two Type instances. Safe to use across different
   * copies of the Type class (e.g., when bundlers duplicate the module).
   * (major, name) uniquely identifies a Type; terminal is implied by these.
   * @param {Type} a
   * @param {Type} b
   * @returns {boolean}
   */
  static equals (a, b) {
    return a === b || (a.major === b.major && a.name === b.name)
  }
}

// convert to static fields when better supported
Type.uint = new Type(0, 'uint', true)
Type.negint = new Type(1, 'negint', true)
Type.bytes = new Type(2, 'bytes', true)
Type.string = new Type(3, 'string', true)
Type.array = new Type(4, 'array', false)
Type.map = new Type(5, 'map', false)
Type.tag = new Type(6, 'tag', false) // terminal?
Type.float = new Type(7, 'float', true)
Type.false = new Type(7, 'false', true)
Type.true = new Type(7, 'true', true)
Type.null = new Type(7, 'null', true)
Type.undefined = new Type(7, 'undefined', true)
Type.break = new Type(7, 'break', true)
// Type.indefiniteLength = new Type(0, 'indefiniteLength', true)

class Token {
  /**
   * @param {Type} type
   * @param {any} [value]
   * @param {number} [encodedLength]
   */
  constructor (type, value, encodedLength) {
    this.type = type
    this.value = value
    this.encodedLength = encodedLength
    /** @type {Uint8Array|undefined} */
    this.encodedBytes = undefined
    /** @type {Uint8Array|undefined} */
    this.byteValue = undefined
  }

  toString () {
    return `Token[${this.type}].${this.value}`
  }
}

export { Type, Token }
{
  "name": "cborg",
  "version": "5.1.6",
  "description": "Fast CBOR with a focus on strictness",
  "main": "cborg.js",
  "type": "module",
  "bin": {
    "cborg": "lib/bin.js"
  },
  "scripts": {
    "lint": "standard *.js lib/*.js test/*.js",
    "build": "npm run build:types",
    "build:types": "tsc --build",
    "prepublishOnly": "npm run build",
    "test:node": "mocha test/test-*.js",
    "test:node-bin": "mocha test/node-test-bin.js",
    "test:browser": "polendina --cleanup test/test-*.js",
    "test": "npm run lint && npm run build && npm run test:node && npm run test:node-bin && npm run test:browser",
    "test:ci": "npm run test"
  },
  "repository": {
    "type": "git",
    "url": "git@github.com:rvagg/cborg.git"
  },
  "keywords": [
    "cbor"
  ],
  "author": "Rod <rod@vagg.org> (http://r.va.gg/)",
  "license": "Apache-2.0",
  "devDependencies": {
    "@semantic-release/changelog": "^6.0.3",
    "@semantic-release/commit-analyzer": "^13.0.1",
    "@semantic-release/git": "^10.0.1",
    "@semantic-release/github": "^12.0.6",
    "@semantic-release/npm": "^13.1.5",
    "@semantic-release/release-notes-generator": "^14.1.0",
    "@types/chai": "^5.2.3",
    "@types/mocha": "^10.0.10",
    "@types/node": "^26.0.1",
    "chai": "^6.2.2",
    "conventional-changelog-conventionalcommits": "^10.0.0",
    "ipld-garbage": "^5.0.0",
    "mocha": "^11.7.5",
    "polendina": "^3.2.20",
    "semantic-release": "^25.0.3",
    "standard": "^17.1.2",
    "typescript": "^6.0.2"
  },
  "exports": {
    ".": {
      "import": "./cborg.js",
      "types": "./types/cborg.d.ts"
    },
    "./length": {
      "import": "./lib/length.js",
      "types": "./types/lib/length.d.ts"
    },
    "./taglib": {
      "import": "./lib/taglib.js",
      "types": "./types/lib/taglib.d.ts"
    },
    "./json": {
      "import": "./lib/json/json.js",
      "types": "./types/lib/json/json.d.ts"
    },
    "./extended": {
      "import": "./lib/extended/extended.js",
      "types": "./types/lib/extended/extended.d.ts"
    },
    "./interface": {
      "types": "./types/interface.d.ts"
    }
  },
  "types": "cborg.d.ts",
  "typesVersions": {
    "*": {
      "json": [
        "types/lib/json/json.d.ts"
      ],
      "length": [
        "types/lib/length.d.ts"
      ],
      "*": [
        "types/*"
      ],
      "types/*": [
        "types/*"
      ]
    }
  },
  "release": {
    "branches": [
      "master"
    ],
    "plugins": [
      [
        "@semantic-release/commit-analyzer",
        {
          "preset": "conventionalcommits",
          "releaseRules": [
            {
              "breaking": true,
              "release": "major"
            },
            {
              "revert": true,
              "release": "patch"
            },
            {
              "type": "feat",
              "release": "minor"
            },
            {
              "type": "fix",
              "release": "patch"
            },
            {
              "type": "chore",
              "release": "patch"
            },
            {
              "type": "docs",
              "release": "patch"
            },
            {
              "type": "test",
              "release": "patch"
            },
            {
              "scope": "no-release",
              "release": false
            }
          ]
        }
      ],
      [
        "@semantic-release/release-notes-generator",
        {
          "preset": "conventionalcommits",
          "presetConfig": {
            "types": [
              {
                "type": "feat",
                "section": "Features"
              },
              {
                "type": "fix",
                "section": "Bug Fixes"
              },
              {
                "type": "chore",
                "section": "Trivial Changes"
              },
              {
                "type": "docs",
                "section": "Trivial Changes"
              },
              {
                "type": "test",
                "section": "Tests"
              }
            ]
          }
        }
      ],
      "@semantic-release/changelog",
      "@semantic-release/npm",
      "@semantic-release/github",
      "@semantic-release/git"
    ]
  }
}
const b4a = require('b4a')

module.exports = codecs

codecs.ascii = createString('ascii')
codecs.utf8 = createString('utf-8')
codecs.hex = createString('hex')
codecs.base64 = createString('base64')
codecs.ucs2 = createString('ucs2')
codecs.utf16le = createString('utf16le')
codecs.ndjson = createJSON(true)
codecs.json = createJSON(false)
codecs.binary = {
  name: 'binary',
  encode: function encodeBinary (obj) {
    return typeof obj === 'string'
      ? b4a.from(obj, 'utf-8')
      : b4a.toBuffer(obj)
  },
  decode: function decodeBinary (buf) {
    return b4a.toBuffer(buf)
  }
}

function isCompactEncoding (c) {
  return !!(c.encode && c.decode && c.preencode)
}

function fromCompactEncoding (c) {
  return {
    name: 'compact-encoding',
    encode: function encodeWithCompact (value) {
      const state = { start: 0, end: 0, buffer: null, cache: null }
      c.preencode(state, value)
      state.buffer = b4a.allocUnsafe(state.end)
      c.encode(state, value)
      return state.buffer
    },
    decode: function decodeWithCompact (buffer) {
      return c.decode({ start: 0, end: buffer.byteLength, buffer, cache: null })
    }
  }
}

function codecs (fmt, fallback) {
  if (typeof fmt === 'object' && fmt) {
    return isCompactEncoding(fmt) ? fromCompactEncoding(fmt) : fmt
  }

  switch (fmt) {
    case 'ndjson': return codecs.ndjson
    case 'json': return codecs.json
    case 'ascii': return codecs.ascii
    case 'utf-8':
    case 'utf8': return codecs.utf8
    case 'hex': return codecs.hex
    case 'base64': return codecs.base64
    case 'ucs-2':
    case 'ucs2': return codecs.ucs2
    case 'utf16-le':
    case 'utf16le': return codecs.utf16le
  }

  return fallback !== undefined ? fallback : codecs.binary
}

function createJSON (newline) {
  return {
    name: newline ? 'ndjson' : 'json',
    encode: newline ? encodeNDJSON : encodeJSON,
    decode: function decodeJSON (buf) {
      return JSON.parse(b4a.toString(buf))
    }
  }

  function encodeJSON (val) {
    return b4a.from(JSON.stringify(val))
  }

  function encodeNDJSON (val) {
    return b4a.from(JSON.stringify(val) + '\n')
  }
}

function createString (type) {
  return {
    name: type,
    encode: function encodeString (val) {
      if (typeof val !== 'string') val = val.toString()
      return b4a.from(val, type)
    },
    decode: function decodeString (buf) {
      return b4a.toString(buf, type)
    }
  }
}
{
  "name": "codecs",
  "version": "3.1.0",
  "description": "Create an binary encoder/decoder for json, utf-8 or custom types",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.6.3"
  },
  "devDependencies": {
    "brittle": "^3.2.1",
    "compact-encoding": "^2.11.0",
    "standard": "^17.0.0"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/codecs.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/codecs/issues"
  },
  "homepage": "https://github.com/mafintosh/codecs"
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
const b4a = require('b4a')
const Hypercore = require('hypercore')
const ReadyResource = require('ready-resource')
const sodium = require('sodium-universal')
const crypto = require('hypercore-crypto')
const ID = require('hypercore-id-encoding')
const { isAndroid } = require('which-runtime')
const { STORAGE_EMPTY, ASSERTION } = require('hypercore-errors')

const auditStore = require('./lib/audit.js')
const GroupNotifyHandle = require('./lib/notify.js')

const [NS] = crypto.namespace('corestore', 1)
const DEFAULT_NAMESPACE = b4a.alloc(32) // This is meant to be 32 0-bytes

class StreamTracker {
  constructor() {
    this.records = []
  }

  add(stream, isExternal) {
    const record = { index: 0, stream, isExternal }
    record.index = this.records.push(record) - 1
    return record
  }

  remove(record) {
    const popped = this.records.pop()
    if (popped === record) return
    this.records[(popped.index = record.index)] = popped
  }

  attachAll(core) {
    for (let i = 0; i < this.records.length; i++) {
      const record = this.records[i]
      const muxer = record.stream.noiseStream.userData
      if (!core.replicator.attached(muxer)) core.replicator.attachTo(muxer)
    }
  }

  destroy() {
    // reverse is safer cause we delete mb
    for (let i = this.records.length - 1; i >= 0; i--) {
      const record = this.records[i]
      if (!record.isExternal) record.stream.destroy()
    }
  }
}

class SessionTracker {
  constructor() {
    this.map = new Map()
  }

  get size() {
    return this.map.size
  }

  get(id) {
    const existing = this.map.get(id)
    if (existing !== undefined) return existing
    const fresh = []
    this.map.set(id, fresh)
    return fresh
  }

  gc(id) {
    this.map.delete(id)
  }

  list(id) {
    return id ? this.map.get(id) || [] : [...this]
  }

  *[Symbol.iterator]() {
    for (const sessions of this.map.values()) {
      yield* sessions[Symbol.iterator]()
    }
  }
}

class CoreTracker {
  constructor() {
    this.map = new Map()
    this.watching = []

    this._gcing = new Set()
    this._gcInterval = null
    this._gcCycleBound = this._gcCycle.bind(this)
  }

  get size() {
    return this.map.size
  }

  watch(store) {
    if (store.watchIndex !== -1) return
    store.watchIndex = this.watching.push(store) - 1
  }

  unwatch(store) {
    if (store.watchIndex === -1) return
    const head = this.watching.pop()
    if (head !== store) this.watching[(head.watchIndex = store.watchIndex)] = head
    store.watchIndex = -1
  }

  resume(id) {
    const core = this.map.get(id)

    if (!core) return null

    // signal back that we have a closing one stored
    if (core.closing) return core

    if (core.gc) {
      this._gcing.delete(core)
      if (this._gcing.size === 0) this._stopGC()
      core.gc = 0
    }

    return core
  }

  opened(id) {
    const core = this.map.get(id)
    return !!(core && core.opened && !core.closing)
  }

  get(id) {
    // we allow you do call this from the outside, so support normal buffers also
    if (b4a.isBuffer(id)) id = b4a.toString(id, 'hex')
    const core = this.map.get(id)
    if (!core || core.closing) return null
    return core
  }

  set(id, core) {
    this.map.set(id, core)
    if (this.watching.length > 0) this._emit(core)
  }

  _emit(core) {
    for (let i = this.watching.length - 1; i >= 0; i--) {
      const store = this.watching[i]
      for (const fn of store.watchers) fn(core)
    }
  }

  _gc(core) {
    const id = toHex(core.discoveryKey)
    if (this.map.get(id) === core) this.map.delete(id)
  }

  _gcCycle() {
    for (const core of this._gcing) {
      if (++core.gc < 4) continue
      const gc = this._gc.bind(this, core)
      core.close().then(gc, gc)
      this._gcing.delete(core)
    }

    if (this._gcing.size === 0) this._stopGC()
  }

  gc(core) {
    core.gc = 1 // first strike
    this._gcing.add(core)
    if (this._gcing.size === 1) this._startGC()
  }

  _stopGC() {
    clearInterval(this._gcInterval)
    this._gcInterval = null
  }

  _startGC() {
    if (this._gcInterval) return
    this._gcInterval = setInterval(this._gcCycleBound, 2000)
    if (this._gcInterval.unref) this._gcInterval.unref()
  }

  close() {
    this._stopGC()
    this._gcing.clear()

    const all = []
    for (const core of this.map.values()) {
      core.onidle = noop // no reentry
      all.push(core.close())
    }
    this.map.clear()

    return Promise.all(all)
  }

  *[Symbol.iterator]() {
    for (const core of this.map.values()) {
      if (!core.closing) yield core
    }
  }
}

class FindingPeers {
  constructor() {
    this.count = 0
    this.pending = []
    this.destroyed = false
  }

  add(core) {
    if (this.count === 0) return
    this.pending.push(core.findingPeers())
  }

  inc(sessions) {
    if (this.destroyed || ++this.count !== 1) return

    for (const core of sessions) {
      this.pending.push(core.findingPeers())
    }
  }

  dec(sessions) {
    if (this.destroyed || --this.count !== 0) return
    while (this.pending.length > 0) this.pending.pop()()
  }

  destroy() {
    this.destroyed = true
    while (this.pending.length > 0) this.pending.pop()()
  }
}

class Corestore extends ReadyResource {
  constructor(storage, opts = {}) {
    super()

    this.root = opts.root || null
    this.storage = this.root
      ? this.root.storage
      : Hypercore.defaultStorage(storage, {
          id: opts.id,
          allowBackup: opts.allowBackup,
          readOnly: opts.readOnly,
          wait: opts.wait
        })
    this.streamTracker = this.root ? this.root.streamTracker : new StreamTracker()
    this.cores = this.root ? this.root.cores : new CoreTracker()
    this.sessions = new SessionTracker()
    this.corestores = this.root ? this.root.corestores : new Set()
    this.readOnly = opts.writable === false || !!opts.readOnly
    this.globalCache = this.root ? this.root.globalCache : opts.globalCache || null
    this.primaryKey = this.root ? this.root.primaryKey : opts.primaryKey || null
    this.ns = opts.namespace || DEFAULT_NAMESPACE
    this.manifestVersion = opts.manifestVersion || 1
    this.shouldSuspend = isAndroid ? !!opts.suspend : opts.suspend !== false
    this.active = opts.active !== false

    this.watchers = null
    this.watchIndex = -1

    this._groupNotifiers = new Map() // group notifications
    this._findingPeers = null // here for legacy
    this._ongcBound = this._ongc.bind(this)
    this._onGroupActiveBound = this._onGroupActive.bind(this)

    if (opts.primaryKey && !this.root && !opts.unsafe) {
      throw ASSERTION(
        'Passing the primary key is unsafe unless you know what you are doing. Set unsafe: true to acknowledge that'
      )
    }

    this.ready().catch(noop)
  }

  watch(fn) {
    if (this.watchers === null) {
      this.watchers = new Set()
      this.cores.watch(this)
    }

    this.watchers.add(fn)
  }

  unwatch(fn) {
    if (this.watchers === null) return

    this.watchers.delete(fn)

    if (this.watchers.size === 0) {
      this.watchers = null
      this.cores.unwatch(this)
    }
  }

  _onGroupActive(topic, update) {
    this.emit('group-active', topic, update)

    const topicHex = b4a.toString(topic, 'hex')
    const handles = this._groupNotifiers.get(topicHex)
    if (!handles) return
    for (const handle of handles) handle.emit('update', update)
  }

  notifyGroup(topic) {
    const topicHex = b4a.toString(topic, 'hex')
    let handles = this._groupNotifiers.get(topicHex)

    if (!handles) {
      handles = []
      this._groupNotifiers.set(topicHex, handles)
    }

    const handle = new GroupNotifyHandle(this, topic)
    const length = handles.push(handle)
    handle.index = length - 1

    return handle
  }

  _removeGroupNotify(handle) {
    if (handle.index === -1) return

    const topicHex = b4a.toString(handle._topic, 'hex')
    const handles = this._groupNotifiers.get(topicHex)
    if (!handles) return

    const popped = handles.pop()
    if (popped !== handle) handles[(popped.index = handle.index)] = popped
    if (handles.length === 0) this._groupNotifiers.delete(topicHex)
    handle.index = -1
  }

  findingPeers() {
    if (this._findingPeers === null) this._findingPeers = new FindingPeers()
    this._findingPeers.inc(this.sessions)
    let done = false
    return () => {
      if (done || !this._findingPeers) return
      done = true
      this._findingPeers.dec(this.sessions)
    }
  }

  audit(opts = {}) {
    return auditStore(this, opts)
  }

  async suspend({ log = noop } = {}) {
    await log('Flushing db...')
    // If readOnly we don't need to flush
    if (!this.storage.readOnly) {
      await this.storage.db.flush()
      await log('Flusing db completed')
    }
    if (!this.shouldSuspend) return
    await log('Suspending db...')
    await this.storage.suspend({ log })
    await log('Suspending db completed')
  }

  resume() {
    return this.storage.resume()
  }

  session(opts) {
    this._maybeClosed()
    const root = this.root || this
    return new Corestore(null, {
      manifestVersion: this.manifestVersion,
      ...opts,
      root
    })
  }

  namespace(name, opts) {
    return this.session({
      ...opts,
      namespace: generateNamespace(this.ns, name)
    })
  }

  list(namespace) {
    return this.storage.createDiscoveryKeyStream(namespace)
  }

  getAuth(discoveryKey) {
    return this.storage.getAuth(discoveryKey)
  }

  _ongc(session) {
    if (session.sessions.length === 0) this.sessions.gc(session.id)
  }

  async _getOrSetSeed() {
    const seed = await this.storage.getSeed()
    if (seed !== null) return seed
    return await this.storage.setSeed(this.primaryKey || crypto.randomBytes(32))
  }

  async _open() {
    if (this.root !== null) {
      this.corestores.add(this)
      if (this.root.opened === false) await this.root.ready()
      this.primaryKey = this.root.primaryKey
      return
    }

    const primaryKey = await this._getOrSetSeed()

    if (this.primaryKey === null) {
      this.primaryKey = primaryKey
      return
    }

    if (!b4a.equals(primaryKey, this.primaryKey)) {
      throw new Error('Another corestore is stored here')
    }
  }

  async _close() {
    const closing = []
    const hanging = [...this.sessions]
    for (const sess of hanging) closing.push(sess.close())

    if (this.watchers !== null) {
      this.cores.unwatch(this)
      this.watchers = null
    }

    if (this._findingPeers !== null) {
      this._findingPeers.destroy()
      this._findingPeers = null
    }

    if (this.root !== null) {
      await Promise.all(closing)
      this.corestores.delete(this)
      return
    }

    for (const store of this.corestores) {
      closing.push(store.close())
    }

    await Promise.all(closing)

    await this.cores.close()
    await this.storage.close()
  }

  async _attachMaybe(muxer, discoveryKey) {
    if (this.opened === false) await this.ready()
    if (
      !this.cores.opened(toHex(discoveryKey)) &&
      !(await this.storage.hasCore(discoveryKey, { ifMigrated: true }))
    ) {
      return
    }
    if (this.closing) return

    const core = this._openCore(discoveryKey, { createIfMissing: false })

    if (!core) return
    if (!core.opened) await core.ready()

    if (!core.replicator.attached(muxer)) {
      core.replicator.attachTo(muxer)
    }

    core.checkIfIdle()
  }

  _shouldReplicate(core, muxer) {
    return (
      core.replicator.downloading && !core.replicator.attached(muxer) && core.opened && this.active
    )
  }

  replicate(isInitiator, opts) {
    this._maybeClosed()

    const isExternal = isStream(isInitiator)
    const stream = Hypercore.createProtocolStream(isInitiator, {
      ...opts,
      ondiscoverykey: (discoveryKey) => {
        if (this.closing) return
        const muxer = stream.noiseStream.userData
        return this._attachMaybe(muxer, discoveryKey)
      }
    })

    if (this.cores.size > 0) {
      const muxer = stream.noiseStream.userData
      const uncork = muxer.uncork.bind(muxer)
      muxer.cork()

      for (const core of this.cores) {
        if (!this._shouldReplicate(core, muxer)) {
          continue
        }
        core.replicator.attachTo(muxer)
      }

      stream.noiseStream.opened.then(uncork)
    }

    const record = this.streamTracker.add(stream, isExternal)
    stream.once('close', () => this.streamTracker.remove(record))
    return stream
  }

  _maybeClosed() {
    if (this.closing || (this.root !== null && this.root.closing)) {
      throw new Error('Corestore is closed')
    }
  }

  async staticify(core, opts) {
    if (!this.opened) await this.ready()
    if (!core.opened) await core.ready()

    const rx = core.state.storage.read()

    const headPromise = rx.getHead()
    const authPromise = rx.getAuth()

    rx.tryFlush()

    const [head, auth] = await Promise.all([headPromise, authPromise])
    if (!head || head.length === 0) throw new Error('Core must have data')

    const prologue = {
      length: head.length,
      hash: head.rootHash
    }

    const manifest = {
      version: 1,
      hash: auth.manifest.hash,
      quorum: 0,
      signers: [],
      prologue
    }

    const c = {
      key: null,
      discoveryKey: null,
      manifest,
      core: core.state.storage.core
    }

    c.key = Hypercore.key(c.manifest)
    c.discoveryKey = Hypercore.discoveryKey(c.key)

    await this.storage.createCore(c)

    const staticCore = this.get({ ...opts, key: c.key })
    await staticCore.ready()
    return staticCore
  }

  get(opts) {
    this._maybeClosed()

    if (b4a.isBuffer(opts) || typeof opts === 'string') opts = { key: opts }
    if (!opts) opts = {}

    const conf = {
      preload: null,
      sessions: null,
      ongc: null,
      core: null,
      active: opts.active !== false,
      encryption: opts.encryption || null,
      encryptionKey: opts.encryptionKey || null, // back compat, should remove
      isBlockKey: !!opts.isBlockKey, // back compat, should remove
      valueEncoding: opts.valueEncoding || null,
      exclusive: !!opts.exclusive,
      manifest: opts.manifest || null,
      keyPair: opts.keyPair || null,
      onwait: opts.onwait || null,
      pushOnly: opts.pushOnly === true,
      wait: opts.wait !== false,
      timeout: opts.timeout || 0,
      draft: !!opts.draft,
      writable: opts.writable === undefined && this.readOnly ? false : opts.writable
    }

    // name requires us to rt to storage + ready, so needs preload
    // same goes if user has defined async preload obvs
    if (opts.name || opts.preload) {
      conf.preload = this._preload(opts)
      return this._makeSession(conf)
    }

    if (opts.discoveryKey && !opts.key && !opts.manifest) {
      conf.preload = this._preloadCheckIfExists(opts)
      return this._makeSession(conf)
    }

    // if not not we can sync create it, which just is easier for the
    // upstream user in terms of guarantees (key is there etc etc)
    const core = this._openCore(null, opts)

    conf.core = core
    conf.sessions = this.sessions.get(core.id)
    conf.ongc = this._ongcBound

    return this._makeSession(conf)
  }

  _makeSession(conf) {
    const session = new Hypercore(null, null, conf)

    if (this._findingPeers !== null) this._findingPeers.add(session)
    return session
  }

  async createKeyPair(name, ns = this.ns) {
    if (this.opened === false) await this.ready()
    return createKeyPair(this.primaryKey, ns, name)
  }

  async _preloadCheckIfExists(opts) {
    const has = await this.storage.hasCore(opts.discoveryKey)
    if (!has) throw STORAGE_EMPTY('No Hypercore is stored here')
    return this._preload(opts)
  }

  async _preload(opts) {
    if (opts.preload) opts = { ...opts, ...(await opts.preload) }
    if (this.opened === false) await this.ready()

    const discoveryKey = opts.name
      ? await this.storage.getAlias({ name: opts.name, namespace: this.ns })
      : null
    this._maybeClosed()

    const core = this._openCore(discoveryKey, opts)

    return {
      core,
      sessions: this.sessions.get(core.id),
      ongc: this._ongcBound,
      manifest: opts.manifest || null,
      encryption: opts.encryption || null,
      encryptionKey: opts.encryptionKey || null, // back compat, should remove
      isBlockKey: !!opts.isBlockKey // back compat, should remove
    }
  }

  _auth(discoveryKey, opts) {
    const result = {
      keyPair: null,
      key: null,
      discoveryKey,
      manifest: null,
      group: null
    }

    if (opts.name) {
      result.keyPair = createKeyPair(this.primaryKey, this.ns, opts.name)
    } else if (opts.keyPair) {
      result.keyPair = opts.keyPair
    }

    if (opts.manifest) {
      result.manifest = opts.manifest
    } else if (result.keyPair && !result.discoveryKey) {
      result.manifest = {
        version: this.manifestVersion,
        signers: [{ publicKey: result.keyPair.publicKey }]
      }
    }

    if (opts.group) {
      result.group = opts.group
    }

    if (opts.key) result.key = ID.decode(opts.key)
    else if (result.manifest) result.key = Hypercore.key(result.manifest)

    if (result.discoveryKey) return result

    if (opts.discoveryKey) result.discoveryKey = ID.decode(opts.discoveryKey)
    else if (result.key) result.discoveryKey = crypto.discoveryKey(result.key)
    else throw new Error('Could not derive discovery from input')

    return result
  }

  _openCore(discoveryKey, opts) {
    const auth = this._auth(discoveryKey, opts)

    const id = toHex(auth.discoveryKey)
    const existing = this.cores.resume(id, auth.group)
    if (existing && !existing.closing) return existing

    const core = Hypercore.createCore(this.storage, {
      preopen: existing && existing.opened ? existing.closing : null, // always wait for the prev one to close first in any case...
      eagerUpgrade: true,
      notDownloadingLinger: opts.notDownloadingLinger,
      allowFork: opts.allowFork !== false,
      allowPush: !!opts.allowPush,
      inflightRange: opts.inflightRange,
      compat: false, // no compat for now :)
      force: opts.force,
      createIfMissing: opts.createIfMissing,
      discoveryKey: auth.discoveryKey,
      overwrite: opts.overwrite,
      key: auth.key,
      keyPair: auth.keyPair,
      legacy: opts.legacy,
      manifest: auth.manifest,
      group: auth.group,
      globalCache: opts.globalCache || this.globalCache || null,
      alias: opts.name ? { name: opts.name, namespace: this.ns } : null
    })

    core.onidle = () => {
      this.cores.gc(core)
    }

    core.ongroupupdate = this._onGroupActiveBound

    core.replicator.ondownloading = () => {
      if (this.active) this.streamTracker.attachAll(core)
    }

    this.cores.set(id, core)
    return core
  }
}

module.exports = Corestore

function isStream(s) {
  return typeof s === 'object' && s && typeof s.pipe === 'function'
}

function generateNamespace(namespace, name) {
  if (!b4a.isBuffer(name)) name = b4a.from(name)
  const out = b4a.allocUnsafeSlow(32)
  sodium.crypto_generichash_batch(out, [namespace, name])
  return out
}

function deriveSeed(primaryKey, namespace, name) {
  if (!b4a.isBuffer(name)) name = b4a.from(name)
  const out = b4a.alloc(32)
  sodium.crypto_generichash_batch(out, [NS, namespace, name], primaryKey)
  return out
}

function createKeyPair(primaryKey, namespace, name) {
  const seed = deriveSeed(primaryKey, namespace, name)
  const buf = b4a.alloc(sodium.crypto_sign_PUBLICKEYBYTES + sodium.crypto_sign_SECRETKEYBYTES)
  const keyPair = {
    publicKey: buf.subarray(0, sodium.crypto_sign_PUBLICKEYBYTES),
    secretKey: buf.subarray(sodium.crypto_sign_PUBLICKEYBYTES)
  }
  sodium.crypto_sign_seed_keypair(keyPair.publicKey, keyPair.secretKey, seed)
  return keyPair
}

function noop() {}

function toHex(discoveryKey) {
  return b4a.toString(discoveryKey, 'hex')
}
module.exports = async function* audit(store, { dryRun = false } = {}) {
  for await (const { discoveryKey, core } of store.storage.createCoreStream()) {
    if (core.version < 1) continue // not migrated, ignore

    const c = store.get({ discoveryKey, active: false })
    await c.ready()

    yield { discoveryKey, key: c.key, audit: await c.core.audit({ dryRun }) }

    try {
      await c.close()
    } catch {
      // ignore if failed, we are auditing...
    }
  }
}
const { EventEmitter } = require('events')
const { Readable } = require('streamx')

class GroupNotifyHandle extends EventEmitter {
  constructor(store, topic) {
    super()
    this._store = store
    this._topic = topic
    this.index = -1
  }

  updates(opts) {
    return Readable.deferred(async () => {
      const groupId = await this._store.storage.getGroup(this._topic).catch(noop)
      if (groupId === null) return null
      return this._store.storage.createGroupUpdateStream(groupId, opts)
    })
  }

  destroy() {
    this._store._removeGroupNotify(this)
  }
}

module.exports = GroupNotifyHandle

function noop() {}
{
  "name": "corestore",
  "version": "7.11.0",
  "description": "A Hypercore factory that simplifies managing collections of cores.",
  "main": "index.js",
  "files": [
    "index.js",
    "lib/*"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "dependencies": {
    "b4a": "^1.6.7",
    "bare-events": "^2.8.3",
    "hypercore": "^11.32.0",
    "hypercore-crypto": "^3.4.2",
    "hypercore-errors": "^1.4.0",
    "hypercore-id-encoding": "^1.3.0",
    "ready-resource": "^1.1.1",
    "sodium-universal": "^5.0.1",
    "streamx": "^2.26.0",
    "which-runtime": "^1.2.1"
  },
  "devDependencies": {
    "brittle": "^3.7.0",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "rache": "^1.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "test": "npm run test:node && npm run test:bare",
    "test:bare": "brittle-bare --coverage test/all.js",
    "lint": "prettier --check . && lunte",
    "test:node": "brittle-node --coverage test/all.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/corestore.git"
  },
  "author": "Holepunch Inc",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/corestore/issues"
  },
  "homepage": "https://github.com/holepunchto/corestore"
}
module.exports = function debounce (worker, context = null) {
  debounced.running = null
  return debounced

  async function debounced () {
    if (debounced.running !== null) {
      try {
        await debounced.running
      } catch (_) {
        // ignore - do not fail on old errors
      }
    }

    // another "thread" beat us to it, just piggy pack on that one
    if (debounced.running !== null) return debounced.running

    debounced.running = worker.call(context)

    try {
      return await debounced.running
    } finally {
      debounced.running = null
    }
  }
}
{
  "name": "debounceify",
  "version": "1.1.0",
  "description": "Tiny async debouncer",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^16.0.3",
    "tape": "^5.1.1"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/debounceify.git"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/debounceify/issues"
  },
  "homepage": "https://github.com/mafintosh/debounceify"
}
const fs = require('fs')
const path = require('path')
const fsx = require('fs-native-extensions')
const b4a = require('b4a')
const ReadyResource = require('ready-resource')
const FDLock = require('fd-lock')

const PLATFORM = global.Bare ? global.Bare.platform : global.process.platform
const IS_WIN = PLATFORM === 'win32'
const IS_LINUX = PLATFORM === 'linux'
const MODIFIED_SLACK = 5000
const EMPTY = b4a.alloc(0)
const ATTR = IS_LINUX ? 'user.device-file' : 'device-file'

const nl = IS_WIN ? '\r\n' : '\n'

class DeviceFile extends ReadyResource {
  constructor(filename, { create = true, wait = false, lock = wait, data = {} } = {}) {
    super()

    this.filename = filename
    this.data = data
    this.lock = null

    this._create = create
    this._wait = wait
    this._lock = lock
  }

  async _open() {
    if (await verifyDeviceFile(this)) return
    if (!this._create) throwDeviceFileError('No device file present', false)
    await writeDeviceFile(this)
  }

  static async validate(filename, data) {
    const file = new DeviceFile(filename, { create: false, wait: false, data })
    try {
      await verifyDeviceFile(file)
    } catch (err) {
      if (err.fatal && err.code === 'DEVICE_FILE') return false
      throw err
    }
    return true
  }

  transfer() {
    return this.lock ? this.lock.transfer() : -1
  }

  async _close() {
    if (this.lock) await this.lock.close()
  }

  async suspend() {
    if (!this.opened) await this.ready()
    if (this.lock) await this.lock.suspend()
  }

  async resume() {
    if (!this.opened) await this.ready()
    if (this.lock) await this.lock.resume()
  }
}

module.exports = DeviceFile

async function writeDeviceFile(device) {
  let s = ''

  for (const [key, value] of Object.entries(device.data)) {
    if (value === null) continue
    s += key + '=' + value + nl
  }

  await fs.promises.mkdir(path.dirname(device.filename), { recursive: true })

  const fd = await open(device.filename, 'w')

  device.lock = device._lock ? new FDLock(fd, { wait: device._wait }) : null

  if (device.lock) {
    try {
      await device.lock.ready()
    } catch (err) {
      await device.lock.close()
      throw err
    }
  }

  const st = await fstat(fd)

  const created = Date.now()

  s += 'device/platform=' + PLATFORM + nl
  s += 'device/inode=' + st.ino + nl
  s += 'device/created=' + created + nl

  if (await setAttr(fd, ATTR, b4a.from('original'))) {
    s += 'device/attribute=original' + nl
  }

  await write(fd, b4a.from(s))

  if (!device.lock) await close(fd)
}

async function verifyDeviceFile(device) {
  let fd = 0

  try {
    fd = await open(device.filename, 'r+')
  } catch (e) {
    fd = 0
  }

  if (fd === 0) return false

  device.lock = device._lock ? new FDLock(fd, { wait: device._wait }) : null

  if (device.lock) {
    try {
      await device.lock.ready()
    } catch (err) {
      await device.lock.close()
      throw err
    }
  }

  const buf = await read(fd)
  const result = {}

  const s = b4a.toString(buf).trim().split('\n')

  let inode = 0
  let created = 0
  let attr = ''
  let platform = ''

  for (const ln of s) {
    const i = ln.indexOf('=')
    if (i === -1) continue

    const k = ln.slice(0, i).trim()
    const v = ln.slice(i + 1).trim()

    switch (k) {
      case 'device/platform':
        platform = v
        break
      case 'device/inode':
        inode = Number(v)
        break
      case 'device/created':
        created = Number(v)
        break
      case 'device/attribute':
        attr = v
        break
      default:
        result[k] = v
        break
    }
  }

  for (const [k, v] of Object.entries(device.data)) {
    if (v === null) continue
    if (result[k] === undefined) continue // allow upserts
    if (result[k] !== '' + v) {
      await teardown()
      throwDeviceFileError(`Invalid device file, ${k} has changed. Was ${result[k]}, is ${v}`, true)
    }
  }

  const st = await fstat(fd)
  const at = await getAttr(fd, ATTR)

  const sameAttr = b4a.toString(at || EMPTY) === attr
  const modified = Math.max(st.mtime.getTime(), st.birthtime.getTime())

  if (platform && platform !== PLATFORM) {
    await teardown()
    throwDeviceFileError('Invalid device file, was made on different platform', true)
  }

  if (!sameAttr) {
    await teardown()
    throwDeviceFileError('Invalid device file, was moved unsafely', true)
  }

  if (st.ino !== inode || (created && Math.abs(modified - created) >= MODIFIED_SLACK)) {
    await teardown()
    throwDeviceFileError('Invalid device file, was modified', true)
  }

  if (!device.lock) await close(fd)

  device.data = result
  return true

  async function teardown() {
    if (device.lock) await device.lock.close()
    else await close(fd)
  }
}

async function getAttr(fd, name) {
  try {
    return await fsx.getAttr(fd, name)
  } catch {
    return null
  }
}

async function setAttr(fd, name, value) {
  try {
    await fsx.setAttr(fd, name, value)
    return true
  } catch {
    return false
  }
}

function fstat(fd) {
  return new Promise((resolve, reject) => {
    fs.fstat(fd, (err, st) => {
      if (err) reject(err)
      resolve(st)
    })
  })
}

function close(fd) {
  return new Promise((resolve, reject) => {
    fs.close(fd, (err, st) => {
      if (err) reject(err)
      resolve(st)
    })
  })
}

function write(fd, buf) {
  return new Promise((resolve, reject) => {
    let offset = 0

    onwrite(null, 0)

    function onwrite(err, wrote) {
      if (err) return reject(err)
      if (offset === buf.byteLength) return resolve()
      offset += wrote
      fs.write(fd, buf, offset, buf.byteLength - offset, offset, onwrite)
    }
  })
}

function read(fd) {
  const buf = b4a.allocUnsafe(4096)

  return new Promise((resolve, reject) => {
    let offset = 0

    fs.read(fd, buf, 0, buf.byteLength, 0, onread)

    function onread(err, read) {
      if (err) return reject(err)
      if (read === 0) return resolve(buf.subarray(0, offset))
      offset += read
      fs.read(fd, buf, offset, buf.byteLength - offset, offset, onread)
    }
  })
}

function open(filename, flags) {
  return new Promise((resolve, reject) => {
    fs.open(filename, flags, (err, fd) => {
      if (err) reject(err)
      resolve(fd)
    })
  })
}

function throwDeviceFileError(message, fatal) {
  const err = new Error(message)
  err.code = 'DEVICE_FILE'
  err.fatal = fatal
  throw err
}
{
  "name": "device-file",
  "version": "2.3.1",
  "description": "Device only file",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.6.7",
    "bare-fs": "^4.0.1",
    "bare-path": "^3.0.0",
    "fd-lock": "^2.1.0",
    "fs-native-extensions": "^1.4.0",
    "ready-resource": "^1.2.0"
  },
  "devDependencies": {
    "brittle": "^3.13.1",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node --coverage test.js",
    "test:bare": "brittle-bare --coverage test.js"
  },
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    }
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/device-file.git"
  },
  "author": "Holepunch Inc",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/device-file/issues"
  },
  "homepage": "https://github.com/holepunchto/device-file"
}
module.exports = require('bare-events')
{
  "name": "events-universal",
  "version": "1.0.1",
  "description": "Universal wrapper for the Node.js events module",
  "exports": {
    "./package": "./package.json",
    ".": {
      "bare": "./bare.js",
      "react-native": "./react-native.js",
      "default": "./default.js"
    }
  },
  "files": [
    "index.js",
    "default.js",
    "bare.js",
    "react-native.js"
  ],
  "scripts": {
    "test": "prettier . --check"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/events-universal.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/events-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/events-universal#readme",
  "dependencies": {
    "bare-events": "^2.7.0"
  },
  "devDependencies": {
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^1.0.0"
  }
}
module.exports = class FixedFIFO {
  constructor (hwm) {
    if (!(hwm > 0) || ((hwm - 1) & hwm) !== 0) throw new Error('Max size for a FixedFIFO should be a power of two')
    this.buffer = new Array(hwm)
    this.mask = hwm - 1
    this.top = 0
    this.btm = 0
    this.next = null
  }

  clear () {
    this.top = this.btm = 0
    this.next = null
    this.buffer.fill(undefined)
  }

  push (data) {
    if (this.buffer[this.top] !== undefined) return false
    this.buffer[this.top] = data
    this.top = (this.top + 1) & this.mask
    return true
  }

  shift () {
    const last = this.buffer[this.btm]
    if (last === undefined) return undefined
    this.buffer[this.btm] = undefined
    this.btm = (this.btm + 1) & this.mask
    return last
  }

  peek () {
    return this.buffer[this.btm]
  }

  isEmpty () {
    return this.buffer[this.btm] === undefined
  }
}
const FixedFIFO = require('./fixed-size')

module.exports = class FastFIFO {
  constructor (hwm) {
    this.hwm = hwm || 16
    this.head = new FixedFIFO(this.hwm)
    this.tail = this.head
    this.length = 0
  }

  clear () {
    this.head = this.tail
    this.head.clear()
    this.length = 0
  }

  push (val) {
    this.length++
    if (!this.head.push(val)) {
      const prev = this.head
      this.head = prev.next = new FixedFIFO(2 * this.head.buffer.length)
      this.head.push(val)
    }
  }

  shift () {
    if (this.length !== 0) this.length--
    const val = this.tail.shift()
    if (val === undefined && this.tail.next) {
      const next = this.tail.next
      this.tail.next = null
      this.tail = next
      return this.tail.shift()
    }

    return val
  }

  peek () {
    const val = this.tail.peek()
    if (val === undefined && this.tail.next) return this.tail.next.peek()
    return val
  }

  isEmpty () {
    return this.length === 0
  }
}
{
  "name": "fast-fifo",
  "version": "1.3.2",
  "description": "A fast fifo implementation similar to the one powering nextTick in Node.js core",
  "main": "index.js",
  "files": [
    "./index.js",
    "./fixed-size.js"
  ],
  "dependencies": {},
  "devDependencies": {
    "standard": "^17.1.0",
    "brittle": "^3.3.2"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/fast-fifo.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/fast-fifo/issues"
  },
  "homepage": "https://github.com/mafintosh/fast-fifo"
}
const fs = require('fs')
const fsx = require('fs-native-extensions')
const onexit = require('resource-on-exit')
const ReadyResource = require('ready-resource')

module.exports = class FDLock extends ReadyResource {
  constructor(fd, opts = {}) {
    const { wait = false } = opts

    super()

    this._fd = fd
    this._wait = wait
    this._locked = false

    onexit.add(this, closeSync)
  }

  get locked() {
    return this._locked
  }

  async _open() {
    try {
      await this._resume()
    } catch (err) {
      onexit.remove(this)
      await close(this)
      throw err
    }
  }

  async _close() {
    onexit.remove(this)
    await close(this)
    this._locked = false
  }

  transfer() {
    const fd = this._fd
    if (fd === -1) throw new Error('Lock has already been transferred')
    this._fd = -1
    onexit.remove(this)
    return fd
  }

  async suspend() {
    if (!this.opened) await this.ready()
    return this._suspend()
  }

  async _suspend() {
    if (this._fd === -1 || this._locked === false) return
    fsx.unlock(this._fd)
    this._locked = false
  }

  async resume() {
    if (!this.opened) await this.ready()
    return this._resume()
  }

  async _resume() {
    if (this._fd === -1 || this._locked === true) return
    if (this._wait) await fsx.waitForLock(this._fd)
    else if (!fsx.tryLock(this._fd)) {
      throw new Error('File descriptor could not be locked')
    }
    this._locked = true
  }
}

function close(lock) {
  const fd = lock._fd
  if (fd === -1) return
  lock._fd = -1
  return new Promise((resolve) => fs.close(fd, () => resolve()))
}

function closeSync(lock) {
  const fd = lock._fd
  if (fd === -1) return
  lock._fd = -1
  lock._locked = false
  try {
    fs.closeSync(fd)
  } catch {}
}
{
  "name": "fd-lock",
  "version": "2.2.0",
  "description": "Stateful file descriptor locks for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": "./index.js"
  },
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    }
  },
  "files": [
    "index.js"
  ],
  "scripts": {
    "test": "npm run lint && npm run test:bare && npm run test:node",
    "test:bare": "bare test.js",
    "test:node": "node test.js",
    "lint": "prettier --check .",
    "format": "prettier --write ."
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/fd-lock.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/fd-lock/issues"
  },
  "homepage": "https://github.com/holepunchto/fd-lock#readme",
  "dependencies": {
    "bare-fs": "^4.5.0",
    "fs-native-extensions": "^1.4.4",
    "ready-resource": "^1.2.0",
    "resource-on-exit": "^1.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
exports.fullRoots = function (index, result) {
  if (index & 1) throw new Error('You can only look up roots for depth(0) blocks')
  if (!result) result = []

  index /= 2

  let offset = 0
  let factor = 1

  while (true) {
    if (!index) return result
    while (factor * 2 <= index) factor *= 2
    result.push(offset + factor - 1)
    offset = offset + 2 * factor
    index -= factor
    factor = 1
  }
}

exports.futureRoots = function (index, result) {
  if (index & 1) throw new Error('You can only look up future roots for depth(0) blocks')
  if (!result) result = []

  let factor = 1

  // make first root
  while (factor * 2 <= index) factor *= 2

  // full factor of 2 - done
  if (factor * 2 - 2 === index) return result

  let pos = factor / 2 - 1

  // while its not a full tree
  while ((pos + factor / 2 - 1) !== index) {
    pos += factor

    // read too far, to to left child
    while ((pos + factor / 2 - 1) > index) {
      factor /= 2
      pos -= factor / 2
    }

    // the "gap" is a future root
    result.push(pos - factor / 2)
  }

  return result
}

exports.patch = function (from, to) {
  if (from === 0 || from >= to) return []

  const roots = exports.fullRoots(from)
  const target = exports.fullRoots(to)

  // first find the first root that is different

  let i = 0
  for (; i < target.length; i++) {
    if (i >= roots.length || roots[i] !== target[i]) break
  }

  const patch = []

  if (i < roots.length) {
    // now we need to grow the newest root until it hits the diff one
    let prev = roots.length - 1

    const ite = exports.iterator(roots[prev--])

    while (ite.index !== target[i]) {
      ite.sibling()

      if (prev >= 0 && ite.index === roots[prev]) {
        prev--
      } else {
        patch.push(ite.index)
      }

      patch.push(ite.parent())
    }

    i++ // patched to next root, so inc
  }

  // include the rest

  for (; i < target.length; i++) patch.push(target[i])

  return patch
}

exports.depth = function (index) {
  let depth = 0

  index += 1
  while (!(index & 1)) {
    depth++
    index = rightShift(index)
  }

  return depth
}

exports.sibling = function (index, depth) {
  if (!depth) depth = exports.depth(index)
  const offset = exports.offset(index, depth)

  return exports.index(depth, offset & 1 ? offset - 1 : offset + 1)
}

exports.parent = function (index, depth) {
  if (!depth) depth = exports.depth(index)
  const offset = exports.offset(index, depth)

  return exports.index(depth + 1, rightShift(offset))
}

exports.leftChild = function (index, depth) {
  if (!(index & 1)) return -1
  if (!depth) depth = exports.depth(index)
  return exports.index(depth - 1, exports.offset(index, depth) * 2)
}

exports.rightChild = function (index, depth) {
  if (!(index & 1)) return -1
  if (!depth) depth = exports.depth(index)
  return exports.index(depth - 1, 1 + (exports.offset(index, depth) * 2))
}

exports.children = function (index, depth) {
  if (!(index & 1)) return null

  if (!depth) depth = exports.depth(index)
  const offset = exports.offset(index, depth) * 2

  return [
    exports.index(depth - 1, offset),
    exports.index(depth - 1, offset + 1)
  ]
}

exports.leftSpan = function (index, depth) {
  if (!(index & 1)) return index
  if (!depth) depth = exports.depth(index)
  return exports.offset(index, depth) * twoPow(depth + 1)
}

exports.rightSpan = function (index, depth) {
  if (!(index & 1)) return index
  if (!depth) depth = exports.depth(index)
  return (exports.offset(index, depth) + 1) * twoPow(depth + 1) - 2
}

exports.nextLeaf = function (index) {
  let factor = 1
  let r = index

  while ((r & 1) === 1) {
    r = (r - 1) / 2
    factor *= 2
  }

  return index + factor + 1
}

exports.count = function (index, depth) {
  if (!(index & 1)) return 1
  if (!depth) depth = exports.depth(index)
  return twoPow(depth + 1) - 1
}

exports.countLeaves = function (index) {
  return (exports.count(index) + 1) / 2
}

exports.spans = function (index, depth) {
  if (!(index & 1)) return [index, index]
  if (!depth) depth = exports.depth(index)

  const offset = exports.offset(index, depth)
  const width = twoPow(depth + 1)

  return [offset * width, (offset + 1) * width - 2]
}

exports.index = function (depth, offset) {
  return (1 + 2 * offset) * twoPow(depth) - 1
}

exports.offset = function (index, depth) {
  if (!(index & 1)) return index / 2
  if (!depth) depth = exports.depth(index)

  return ((index + 1) / twoPow(depth) - 1) / 2
}

exports.iterator = function (index) {
  const ite = new Iterator()
  ite.seek(index || 0)
  return ite
}

function twoPow (n) {
  return n < 31 ? 1 << n : ((1 << 30) * (1 << (n - 30)))
}

function rightShift (n) {
  return (n - (n & 1)) / 2
}

function Iterator () {
  this.index = 0
  this.offset = 0
  this.factor = 0
}

Iterator.prototype.seek = function (index) {
  this.index = index
  if (this.index & 1) {
    this.offset = exports.offset(index)
    this.factor = twoPow(exports.depth(index) + 1)
  } else {
    this.offset = index / 2
    this.factor = 2
  }
}

Iterator.prototype.isLeft = function () {
  return (this.offset & 1) === 0
}

Iterator.prototype.isRight = function () {
  return (this.offset & 1) === 1
}

Iterator.prototype.isRoot = function (length) {
  const currentLength = 1 + (this.index + this.factor / 2 - 1) / 2
  if (length < currentLength) return false

  const factor = this.factor * 2
  const index = (this.offset & 1)
    ? this.index - this.factor / 2
    : this.index + this.factor / 2

  const parentLength = 1 + (index + factor / 2 - 1) / 2
  return parentLength > length
}

Iterator.prototype.contains = function (index) {
  return index > this.index
    ? index < (this.index + this.factor / 2)
    : index < this.index
      ? index > (this.index - this.factor / 2)
      : true
}

Iterator.prototype.prev = function () {
  if (!this.offset) return this.index
  this.offset--
  this.index -= this.factor
  return this.index
}

Iterator.prototype.next = function () {
  this.offset++
  this.index += this.factor
  return this.index
}

Iterator.prototype.count = function () {
  if (!(this.index & 1)) return 1
  return this.factor - 1
}

Iterator.prototype.countLeaves = function () {
  return (this.count() + 1) / 2
}

Iterator.prototype.sibling = function () {
  return this.isLeft() ? this.next() : this.prev()
}

Iterator.prototype.parent = function () {
  if (this.offset & 1) {
    this.index -= this.factor / 2
    this.offset = (this.offset - 1) / 2
  } else {
    this.index += this.factor / 2
    this.offset /= 2
  }
  this.factor *= 2
  return this.index
}

Iterator.prototype.leftSpan = function () {
  this.index = this.index - this.factor / 2 + 1
  this.offset = this.index / 2
  this.factor = 2
  return this.index
}

Iterator.prototype.peekLeftSpan = function () {
  return this.index - this.factor / 2 + 1
}

Iterator.prototype.rightSpan = function () {
  this.index = this.index + this.factor / 2 - 1
  this.offset = this.index / 2
  this.factor = 2
  return this.index
}

Iterator.prototype.peekRightSpan = function () {
  return this.index + this.factor / 2 - 1
}

Iterator.prototype.leftChild = function () {
  if (this.factor === 2) return this.index
  this.factor /= 2
  this.index -= this.factor / 2
  this.offset *= 2
  return this.index
}

Iterator.prototype.rightChild = function () {
  if (this.factor === 2) return this.index
  this.factor /= 2
  this.index += this.factor / 2
  this.offset = 2 * this.offset + 1
  return this.index
}

Iterator.prototype.nextTree = function () {
  this.index = this.index + this.factor / 2 + 1
  this.offset = this.index / 2
  this.factor = 2
  return this.index
}

Iterator.prototype.prevTree = function () {
  if (!this.offset) {
    this.index = 0
    this.factor = 2
  } else {
    this.index = this.index - this.factor / 2 - 1
    this.offset = this.index / 2
    this.factor = 2
  }
  return this.index
}

Iterator.prototype.fullRoot = function (index) {
  if (index <= this.index || (this.index & 1) > 0) return false
  while (index > this.index + this.factor + this.factor / 2) {
    this.index += this.factor / 2
    this.factor *= 2
    this.offset /= 2
  }
  return true
}
{
  "name": "flat-tree",
  "version": "1.13.0",
  "description": "A series of functions to map a binary tree to a list",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {},
  "devDependencies": {
    "brittle": "^3.3.2",
    "standard": "^17.1.0"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/flat-tree.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/flat-tree/issues"
  },
  "homepage": "https://github.com/mafintosh/flat-tree"
}
require.addon = require('require-addon')

module.exports = require.addon('.', __filename)
const { isWindows } = require('which-runtime')
const binding = require('./binding')

function onwork(err, result) {
  if (err) this.reject(err)
  else this.resolve(result)
}

exports.tryLock = function tryLock(fd, offset = 0, length = 0, opts = {}) {
  if (typeof offset === 'object') {
    opts = offset
    offset = 0
  }

  if (typeof length === 'object') {
    opts = length
    length = 0
  }

  if (typeof opts !== 'object' || opts === null) {
    opts = {}
  }

  try {
    binding.tryLock(fd, offset, length, opts.shared !== true)
  } catch (err) {
    if (err.code === 'EAGAIN') return false
    throw err
  }

  return true
}

exports.waitForLock = function waitForLock(fd, offset = 0, length = 0, opts = {}) {
  if (typeof offset === 'object') {
    opts = offset
    offset = 0
  }

  if (typeof length === 'object') {
    opts = length
    length = 0
  }

  if (typeof opts !== 'object' || opts === null) {
    opts = {}
  }

  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.waitForLock(fd, offset, length, opts.shared !== true, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.waitForLockSync = function waitForLockSync(fd, offset = 0, length = 0, opts = {}) {
  if (typeof offset === 'object') {
    opts = offset
    offset = 0
  }

  if (typeof length === 'object') {
    opts = length
    length = 0
  }

  if (typeof opts !== 'object' || opts === null) {
    opts = {}
  }

  binding.waitForLockSync(fd, offset, length, opts.shared !== true)
}

exports.tryDowngradeLock = function tryDowngradeLock(fd, offset = 0, length = 0) {
  try {
    binding.tryDowngradeLock(fd, offset, length)
  } catch (err) {
    if (err.code === 'EAGAIN') return false
    throw err
  }

  return true
}

exports.waitForDowngradeLock = function downgradeLock(fd, offset = 0, length = 0) {
  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.waitForDowngradeLock(fd, offset, length, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.waitForDowngradeLockSync = function waitForDowngradeLockSync(fd, offset = 0, length = 0) {
  binding.waitForDowngradeLockSync(fd, offset, length)
}

exports.tryUpgradeLock = function tryUpgradeLock(fd, offset = 0, length = 0) {
  try {
    binding.tryUpgradeLock(fd, offset, length)
  } catch (err) {
    if (err.code === 'EAGAIN') return false
    throw err
  }

  return true
}

exports.waitForUpgradeLock = function upgradeLock(fd, offset = 0, length = 0) {
  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.waitForUpgradeLock(fd, offset, length, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.waitForUpgradeLockSync = function waitForUpgradeLockSync(fd, offset = 0, length = 0) {
  binding.waitForUpgradeLockSync(fd, offset, length)
}

exports.unlock = function unlock(fd, offset = 0, length = 0) {
  binding.unlock(fd, offset, length)
}

exports.trim = function trim(fd, offset, length) {
  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.trim(fd, offset, length, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.trimSync = function trimSync(fd, offset, length) {
  binding.trimSync(fd, offset, length)
}

exports.sparse = function sparse(fd) {
  // Short circuit on everything but Windows
  if (!isWindows) return Promise.resolve()

  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.sparse(fd, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.sparseSync = function sparseSync(fd) {
  // Short circuit on everything but Windows
  if (!isWindows) return

  binding.sparseSync(fd)
}

exports.swap = function swap(from, to) {
  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.swap(from, to, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.swapSync = function swapSync(from, to) {
  binding.swapSync(from, to)
}

exports.getAttr = function getAttr(fd, name) {
  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.getAttr(fd, name, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise.then((buffer) => (buffer === null ? null : Buffer.from(buffer)))
}

exports.getAttrSync = function getAttrSync(fd, name) {
  const buffer = binding.getAttrSync(fd, name)
  return buffer === null ? null : Buffer.from(buffer)
}

exports.setAttr = function setAttr(fd, name, value, encoding) {
  if (typeof value === 'string') value = Buffer.from(value, encoding)

  const req = {
    value,
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.setAttr(
      fd,
      name,
      value.buffer,
      value.byteOffset,
      value.byteLength,
      req,
      onwork
    )
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.setAttrSync = function setAttrSync(fd, name, value, encoding) {
  if (typeof value === 'string') value = Buffer.from(value, encoding)

  binding.setAttrSync(fd, name, value.buffer, value.byteOffset, value.byteLength)
}

exports.removeAttr = function removeAttr(fd, name) {
  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.removeAttr(fd, name, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.removeAttrSync = function removeAttrSync(fd, name) {
  binding.removeAttrSync(fd, name)
}

exports.listAttrs = function listAttrs(fd) {
  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.listAttrs(fd, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.listAttrsSync = function listAttrsSync(fd) {
  return binding.listAttrsSync(fd)
}
{
  "name": "fs-native-extensions",
  "version": "1.5.0",
  "description": "Native file system extensions for advanced file operations",
  "main": "index.js",
  "files": [
    "index.js",
    "macros.h",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "include",
    "src",
    "prebuilds"
  ],
  "imports": {
    "child_process": {
      "bare": "bare-subprocess",
      "default": "child_process"
    },
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "fs/*": {
      "bare": "bare-fs/*",
      "default": "fs/*"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    }
  },
  "addon": true,
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:bare": "brittle-bare --coverage test.js",
    "test:node": "brittle-node --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/fs-native-extensions.git"
  },
  "author": "Kasper Isager Dalsgarð <kasper@funktionel.co>",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/fs-native-extensions/issues"
  },
  "homepage": "https://github.com/holepunchto/fs-native-extensions#readme",
  "dependencies": {
    "require-addon": "^1.1.0",
    "which-runtime": "^1.2.0"
  },
  "devDependencies": {
    "bare-compat-napi": "^1.3.8",
    "bare-fs": "^4.4.4",
    "bare-path": "^3.0.0",
    "bare-subprocess": "^4.0.5",
    "brittle": "^3.1.1",
    "cmake-bare": "^1.1.10",
    "cmake-fetch": "^1.4.7",
    "cmake-napi": "^1.0.5",
    "cmake-npm": "^1.1.0",
    "lunte": "^1.6.0",
    "minimist": "^1.2.6",
    "prettier": "^3.5.3",
    "prettier-config-holepunch": "^2.0.0",
    "test-tmp": "^1.2.1"
  }
}
const codecs = require('codecs')
const { Readable } = require('streamx')
const mutexify = require('mutexify/promise')
const b4a = require('b4a')
const safetyCatch = require('safety-catch')
const ReadyResource = require('ready-resource')
const debounce = require('debounceify')
const Rache = require('rache')
const rrp = require('resolve-reject-promise')

const { all: unslabAll } = require('unslab')

const RangeIterator = require('./iterators/range')
const HistoryIterator = require('./iterators/history')
const DiffIterator = require('./iterators/diff')
const LocalBlockIterator = require('./iterators/local')
const Extension = require('./lib/extension')
const { YoloIndex, Node, Header } = require('./lib/messages')
const { BLOCK_NOT_AVAILABLE, DECODING_ERROR } = require('hypercore-errors')

const T = 5
const MIN_KEYS = T - 1
const MAX_CHILDREN = MIN_KEYS * 2 + 1

const SEP = b4a.alloc(1)
const EMPTY = b4a.alloc(0)

class Key {
  constructor(seq, value) {
    this.seq = seq
    this.value = value
  }
}

class Child {
  constructor(seq, offset, value) {
    this.seq = seq
    this.offset = offset
    this.value = value
  }
}

class Cache {
  constructor(rache) {
    this.keys = rache
    this.length = 0
  }

  get(seq) {
    return this.keys.get(seq) || null
  }

  set(seq, key) {
    this.keys.set(seq, key)
    if (seq >= this.length) this.length = seq + 1
  }

  gc(length) {
    // if we need to "work" more than 128 ticks, just bust the cache...
    if (this.length - length > 128) {
      this.keys.clear()
    } else {
      for (let i = length; i < this.length; i++) {
        this.keys.delete(i)
      }
    }

    this.length = length
  }

  clear() {
    this.keys.clear()
  }
}

class Pointers {
  constructor(decoded) {
    this.levels = decoded.levels.map((l) => {
      const children = []
      const keys = []

      for (let i = 0; i < l.keys.length; i++) {
        keys.push(new Key(l.keys[i], null))
      }

      for (let i = 0; i < l.children.length; i += 2) {
        children.push(new Child(l.children[i], l.children[i + 1], null))
      }

      return { keys, children }
    })
  }

  get(i) {
    return this.levels[i]
  }

  hasKey(seq) {
    for (const lvl of this.levels) {
      for (const key of lvl.keys) {
        if (key.seq === seq) return true
      }
    }
    return false
  }
}

function inflate(entry) {
  if (entry.inflated === null) {
    entry.inflated = YoloIndex.decode(entry.index)
    entry.index = null
  }
  return new Pointers(entry.inflated)
}

function deflate(index) {
  const levels = index.map((l) => {
    const keys = []
    const children = []

    for (let i = 0; i < l.value.keys.length; i++) {
      keys.push(l.value.keys[i].seq)
    }

    for (let i = 0; i < l.value.children.length; i++) {
      children.push(l.value.children[i].seq, l.value.children[i].offset)
    }

    return { keys, children }
  })

  return YoloIndex.encode({ levels })
}

class TreeNode {
  constructor(block, keys, children, offset) {
    this.block = block
    this.offset = offset
    this.keys = keys
    this.children = children
    this.changed = false

    this.preload()
  }

  preload() {
    if (this.block === null) return

    const core = getBackingCore(this.block.tree.core)
    if (!core) return

    const bitfield = core.core.bitfield
    const blocks = []

    for (let i = 0; i < this.keys.length; i++) {
      const k = this.keys[i]
      if (k.value) continue
      if (k.seq >= core.signedLength || (bitfield && bitfield.get(k.seq))) continue
      blocks.push(k.seq)
    }
    for (let i = 0; i < this.children.length; i++) {
      const c = this.children[i]
      if (c.value) continue
      if (c.seq >= core.signedLength || (bitfield && bitfield.get(c.seq))) continue
      blocks.push(c.seq)
    }

    if (blocks.length) core.download({ blocks })
  }

  async insertKey(key, value, child, node, encoding, cas) {
    let s = 0
    let e = this.keys.length
    let c

    while (s < e) {
      const mid = (s + e) >> 1
      c = b4a.compare(key.value, await this.getKey(mid))

      if (c === 0) {
        if (cas) {
          const prev = await this.getKeyNode(mid)
          if (!(await cas(prev.final(encoding), node))) return true
        }
        if (!this.block.tree.tree.alwaysDuplicate) {
          const prev = await this.getKeyNode(mid)
          if (sameValue(prev.value, value)) return true
        }
        this.changed = true
        this.keys[mid] = key
        return true
      }

      if (c < 0) e = mid
      else s = mid + 1
    }

    const i = c < 0 ? e : s
    this.keys.splice(i, 0, key)
    if (child) this.children.splice(i + 1, 0, new Child(0, 0, child))
    this.changed = true

    return this.keys.length < MAX_CHILDREN
  }

  removeKey(index) {
    this.keys.splice(index, 1)
    if (this.children.length) {
      this.children[index + 1].seq = 0 // mark as freed
      this.children.splice(index + 1, 1)
    }
    this.changed = true
  }

  async siblings(parent) {
    for (let i = 0; i < parent.children.length; i++) {
      if (parent.children[i].value === this) {
        const [left, right] = await Promise.all([
          i ? parent.getChildNode(i - 1) : null,
          i < parent.children.length - 1 ? parent.getChildNode(i + 1) : null
        ])
        return { left, index: i, right }
      }
    }

    throw new Error('Bad parent')
  }

  merge(node, median) {
    this.changed = true
    this.keys.push(median)
    for (let i = 0; i < node.keys.length; i++) this.keys.push(node.keys[i])
    for (let i = 0; i < node.children.length; i++) this.children.push(node.children[i])
  }

  async split() {
    const len = this.keys.length >> 1
    const right = TreeNode.create(this.block)

    while (right.keys.length < len) right.keys.push(this.keys.pop())
    right.keys.reverse()

    await this.getKey(this.keys.length - 1) // make sure the median is loaded
    const median = this.keys.pop()

    if (this.children.length) {
      while (right.children.length < len + 1) right.children.push(this.children.pop())
      right.children.reverse()
    }

    this.changed = true

    return {
      left: this,
      median,
      right
    }
  }

  getKeyNode(index) {
    return this.block.tree.getBlock(this.keys[index].seq)
  }

  async getChildNode(index) {
    const child = this.children[index]
    if (child.value) return child.value
    const block =
      child.seq === this.block.seq ? this.block : await this.block.tree.getBlock(child.seq)
    return (child.value = block.getTreeNode(child.offset))
  }

  setKey(index, key) {
    this.keys[index] = key
    this.changed = true
  }

  async getKey(index) {
    const key = this.keys[index]
    if (key.value) return key.value
    const k = key.seq === this.block.seq ? this.block.key : await this.block.tree.getKey(key.seq)
    return (key.value = k)
  }

  indexChanges(index, seq) {
    const offset = index.push(null) - 1
    this.changed = false

    for (const child of this.children) {
      if (!child.value || !child.value.changed) continue
      child.seq = seq
      child.offset = child.value.indexChanges(index, seq)
      index[child.offset] = child
    }

    return offset
  }

  updateChildren(seq, block) {
    for (const child of this.children) {
      if (!child.value || child.seq !== seq) continue
      child.value.block = block
      child.value.updateChildren(seq, block)
    }
  }

  static create(block) {
    const node = new TreeNode(block, [], [], 0)
    node.changed = true
    return node
  }
}

class BlockEntry {
  constructor(seq, tree, entry) {
    this.seq = seq
    this.tree = tree
    this.index = null
    this.entry = entry
    this.key = entry.key
    this.value = entry.value
  }

  isTarget(key) {
    return b4a.equals(this.key, key)
  }

  inflate() {
    if (this.index === null) {
      this.index = inflate(this.entry)
    }
  }

  isDeletion() {
    if (this.value !== null) return false

    if (this.index === null) {
      this.index = inflate(this.entry)
    }

    return !this.index.hasKey(this.seq)
  }

  final(encoding) {
    return {
      seq: this.seq,
      key: encoding.key ? encoding.key.decode(this.key) : this.key,
      value: this.value && (encoding.value ? encoding.value.decode(this.value) : this.value)
    }
  }

  getTreeNode(offset) {
    if (this.index === null) {
      this.index = inflate(this.entry)
    }
    const entry = this.index.get(offset)
    return new TreeNode(this, entry.keys, entry.children, offset)
  }
}

class CacheLock {
  constructor() {
    this.map = new Map()
  }

  enter(seq) {
    const pending = this.map.get(seq)

    if (!pending) {
      this.map.set(seq, [])
      return Promise.resolve()
    }

    const { resolve, promise } = rrp()
    pending.push(resolve)
    return promise
  }

  exit(seq) {
    const pending = this.map.get(seq)
    if (!pending.length) {
      this.map.delete(seq)
      return
    }

    pending.pop()()
  }
}

class BatchEntry extends BlockEntry {
  constructor(seq, tree, key, value, index) {
    super(seq, tree, { key, value, index: null, inflated: null })
    this.pendingIndex = index
  }

  isTarget(key) {
    return false
  }

  getTreeNode(offset) {
    return this.pendingIndex[offset].value
  }
}

class Hyperbee extends ReadyResource {
  constructor(core, opts = {}) {
    super()
    // this.feed is now deprecated, and will be this.core going forward
    this.feed = core
    this.core = core

    this.keyEncoding = opts.keyEncoding ? codecs(opts.keyEncoding) : null
    this.valueEncoding = opts.valueEncoding ? codecs(opts.valueEncoding) : null
    this.extension = opts.extension !== false ? getExtension(this, opts) : null
    this.metadata = opts.metadata || null
    this.lock = opts.lock || mutexify()
    this.sep = opts.sep || SEP
    this.readonly = !!opts.readonly
    this.prefix = opts.prefix || null

    // In a future version, this should be false by default
    this.alwaysDuplicate = opts.alwaysDuplicate !== false

    this._unprefixedKeyEncoding = this.keyEncoding
    this._sub = !!this.prefix
    this._checkout = opts.checkout || 0
    this._view = !!opts._view

    this._onappendBound = this._view ? null : this._onappend.bind(this)
    this._ontruncateBound = this._view ? null : this._ontruncate.bind(this)
    this._watchers = this._onappendBound ? [] : null
    this._entryWatchers = this._onappendBound ? [] : null
    this._sessions = opts.sessions !== false

    this._keyCache = null
    this._nodeCache = null
    this._cacheLock = new CacheLock()

    this._batches = []

    if (this._watchers) {
      this.core.on('append', this._onappendBound)
      this.core.on('truncate', this._ontruncateBound)
    }

    if (this.prefix && opts._sub) {
      this.keyEncoding = prefixEncoding(this.prefix, this.keyEncoding)
    }

    this.ready().catch(safetyCatch)
  }

  async _open() {
    if (this.core.opened === false) await this.core.ready()
    // bump the internal ranges since the nodes are small
    if (this._watchers && this.core.replicator.setInflightRange) {
      this.core.replicator.setInflightRange(256, 512)
    }

    // snapshot
    if (this._checkout === -1) this._checkout = Math.max(1, this.core.length)

    const baseCache = Rache.from(this.core.globalCache)
    this._keyCache = new Cache(baseCache)
    this._nodeCache = new Cache(Rache.from(baseCache))
  }

  get version() {
    return Math.max(1, this._checkout || this.core.length)
  }

  get id() {
    return this.core.id
  }

  get key() {
    return this.core.key
  }

  get discoveryKey() {
    return this.core.discoveryKey
  }

  get writable() {
    return this.core.writable
  }

  get readable() {
    return this.core.readable
  }

  replicate(isInitiator, opts) {
    return this.core.replicate(isInitiator, opts)
  }

  update(opts) {
    return this.core.update(opts)
  }

  peek(range, opts) {
    return iteratorPeek(this.createRangeIterator(range, { ...opts, limit: 1 }))
  }

  createRangeIterator(range, opts = {}) {
    // backwards compat range arg
    opts = opts ? { ...opts, ...range } : range

    const extension = opts.extension === false && opts.limit !== 0 ? null : this.extension
    const keyEncoding = opts.keyEncoding ? codecs(opts.keyEncoding) : this.keyEncoding

    if (extension) {
      const { onseq, onwait } = opts
      let version = 0
      let next = 0

      opts = encRange(keyEncoding, {
        ...opts,
        sub: this._sub,
        onseq(seq) {
          if (!version) version = seq + 1
          if (next) next--
          if (onseq) onseq(seq)
        },
        onwait(seq) {
          if (!next) {
            next = Extension.BATCH_SIZE
            extension.iterator(ite.snapshot(version))
          }
          if (onwait) onwait(seq)
        }
      })
    } else {
      opts = encRange(keyEncoding, { ...opts, sub: this._sub })
    }

    const ite = new RangeIterator(
      new Batch(this, this._makeSnapshot(), null, false, opts),
      null,
      opts
    )
    return ite
  }

  createReadStream(range, opts) {
    const signal = (opts && opts.signal) || null
    return iteratorToStream(this.createRangeIterator(range, opts), signal)
  }

  createHistoryStream(opts) {
    const session = opts && opts.live ? this.core.session() : this._makeSnapshot()
    const signal = (opts && opts.signal) || null
    return iteratorToStream(
      new HistoryIterator(new Batch(this, session, null, false, opts), opts),
      signal
    )
  }

  createDiffStream(right, range, opts) {
    if (typeof right === 'number') right = this.checkout(Math.max(1, right), { reuseSession: true })

    // backwards compat range arg
    opts = opts ? { ...opts, ...range } : range

    const signal = (opts && opts.signal) || null

    const keyEncoding = opts && opts.keyEncoding ? codecs(opts.keyEncoding) : this.keyEncoding
    if (keyEncoding) opts = encRange(keyEncoding, { ...opts, sub: this._sub })

    let done
    let closing
    let ite

    const left = this

    const rs = new Readable({
      signal,
      eagerOpen: true,
      async open(cb) {
        try {
          if (right.opened === false) await right.ready()
          if (left.opened === false) await left.ready()
        } catch (err) {
          cb(err)
          return
        }

        if (closing) {
          cb(null)
          return
        }

        if (left.core.closing || right.core.closing) {
          cb(new Error('Bee closed'))
          return
        }

        const snapshot = right.version > left.version ? right._makeSnapshot() : left._makeSnapshot()

        done = cb
        ite = new DiffIterator(
          new Batch(left, snapshot, null, false, opts),
          new Batch(right, snapshot, null, false, opts),
          opts
        )
        ite.open().then(fin, fin)
      },
      read(cb) {
        done = cb
        ite.next().then(push, fin)
      },
      predestroy() {
        if (!ite) {
          closing = Promise.resolve()
        } else {
          closing = ite.close()
          closing.catch(noop)
        }
      },
      destroy(cb) {
        done = cb
        if (!closing) closing = ite.close()
        closing.then(fin, fin)
      }
    })

    return rs

    function fin(err) {
      done(err)
    }

    function push(val) {
      rs.push(val)
      done(null)
    }
  }

  get(key, opts) {
    const b = new Batch(this, this._makeSnapshot(), null, true, opts)
    return b.get(key)
  }

  getBySeq(seq, opts) {
    const b = new Batch(this, this._makeSnapshot(), null, true, opts)
    return b.getBySeq(seq)
  }

  put(key, value, opts) {
    const b = new Batch(this, this.core, null, true, opts)
    return b.put(key, value, opts)
  }

  batch(opts) {
    return new Batch(this, this.core, mutexify(), true, opts)
  }

  del(key, opts) {
    const b = new Batch(this, this.core, null, true, opts)
    return b.del(key, opts)
  }

  watch(range, opts) {
    if (!this._watchers) throw new Error('Can only watch the main bee instance')
    return new Watcher(this, range, opts)
  }

  async getAndWatch(key, opts) {
    if (!this._watchers) throw new Error('Can only watch the main bee instance')

    const watcher = new EntryWatcher(this, key, opts)
    await watcher._debouncedUpdate()

    if (this.closing) {
      await watcher.close()
      throw new Error('Bee closed')
    }

    return watcher
  }

  _onappend() {
    for (const watcher of this._watchers) {
      watcher._onappend()
    }

    for (const watcher of this._entryWatchers) {
      watcher._onappend()
    }
  }

  _ontruncate(length) {
    for (const watcher of this._watchers) {
      watcher._ontruncate()
    }

    for (const watcher of this._entryWatchers) {
      watcher._ontruncate()
    }

    this._nodeCache.gc(length)
    this._keyCache.gc(length)
  }

  _makeSnapshot() {
    if (this._sessions === false) return this.core
    // TODO: better if we could encapsulate this in hypercore in the future
    return this._checkout <= this.core.length || this._checkout <= 1
      ? this.core.snapshot()
      : this.core.session({ snapshot: false })
  }

  async clearUnlinked(options = {}) {
    await this.ready()

    const { gte = 0, lt = this.version - 1, batchSize = 4096, wait = true } = options
    const checkout = this.version

    let prev = this.batch({ wait: false, checkout: gte })
    let b = this.batch({ wait, checkout })

    const iteBatch = this.batch({ wait: false, checkout })
    const ite = new LocalBlockIterator(iteBatch, { gte, lt })
    await ite.open()

    let ticks = 0

    while (true) {
      const data = await ite.next()
      if (!data) break

      if (!(await isLinked(b, data))) {
        if (b.core.closing || this.core.closing || this.closing) break
        await this.core.clear(data.seq)
      }

      const prevNode = await prev.get(data.key, { finalize: false }).catch(toNull)

      if (prevNode && !(await isLinked(b, prevNode))) {
        if (b.core.closing || this.core.closing || this.closing) break
        await this.core.clear(prevNode.seq)
      }

      if (ticks++ >= batchSize) {
        ticks = 0
        await prev.close()
        await b.close()

        prev = this.batch({ wait: false, checkout: gte })
        b = this.batch({ wait, checkout })
      }
    }

    if (b.core.closing || this.core.closing || this.closing) throw new Error('Core is closed')

    await b.close()
    await prev.close()
    await ite.close()
    await iteBatch.close()

    return lt
  }

  checkout(version, opts = {}) {
    if (version === 0) version = 1

    // same as above, just checkout isn't set yet...
    const snap =
      opts.reuseSession || this._sessions === false
        ? this.core
        : version <= this.core.length || version <= 1
          ? this.core.snapshot()
          : this.core.session({ snapshot: false })

    return new Hyperbee(snap, {
      _view: true,
      _sub: false,
      prefix: this.prefix,
      sep: this.sep,
      lock: this.lock,
      checkout: version,
      keyEncoding: opts.keyEncoding || this.keyEncoding,
      valueEncoding: opts.valueEncoding || this.valueEncoding,
      extension: this.extension !== null ? this.extension : false
    })
  }

  snapshot(opts) {
    return this.checkout(
      this.core.opened === false || this._checkout <= 0 ? -1 : Math.max(1, this.version),
      opts
    )
  }

  sub(prefix, opts = {}) {
    let sep = opts.sep || this.sep
    if (!b4a.isBuffer(sep)) sep = b4a.from(sep)

    prefix = b4a.concat([this.prefix || EMPTY, b4a.from(prefix), sep])

    const valueEncoding = codecs(opts.valueEncoding || this.valueEncoding)
    const keyEncoding = codecs(opts.keyEncoding || this._unprefixedKeyEncoding)

    return new Hyperbee(this.core, {
      _view: true,
      _sub: true,
      prefix,
      sep: this.sep,
      lock: this.lock,
      checkout: this._checkout,
      valueEncoding,
      keyEncoding,
      extension: this.extension !== null ? this.extension : false,
      metadata: this.metadata
    })
  }

  async getHeader(opts) {
    const blk = await this.core.get(0, opts)
    try {
      return blk && Header.decode(blk)
    } catch {
      throw DECODING_ERROR()
    }
  }

  async _close() {
    if (!this._view) {
      if (this._keyCache) this._keyCache.clear()
      if (this._nodeCache) this._nodeCache.clear()
    }

    if (this._watchers) {
      this.core.off('append', this._onappendBound)
      this.core.off('truncate', this._ontruncateBound)

      while (this._watchers.length) {
        await this._watchers[this._watchers.length - 1].close()
      }
    }

    if (this._entryWatchers) {
      while (this._entryWatchers.length) {
        await this._entryWatchers[this._entryWatchers.length - 1].close()
      }
    }

    while (this._batches.length) {
      await this._batches[this._batches.length - 1].close()
    }

    return this.core.close()
  }

  static async isHyperbee(core, opts) {
    await core.ready()

    const blk0 = await core.get(0, opts)
    if (blk0 === null) throw BLOCK_NOT_AVAILABLE()

    try {
      return Header.decode(blk0).protocol === 'hyperbee'
    } catch (err) {
      // undecodable
      return false
    }
  }
}

class Batch {
  constructor(tree, core, batchLock, cache, options = {}) {
    this.tree = tree
    // this.feed is now deprecated, and will be this.core going forward
    this.feed = core
    this.core = core
    this.index = tree._batches.push(this) - 1
    this.blocks = cache ? new Map() : null
    this.autoFlush = !batchLock
    this.maxBlocksCached = options.maxBlocksCached || 128
    this.rootSeq = 0
    this.root = null
    this.length = 0
    this.checkout = options.checkout === undefined ? -1 : options.checkout
    this.options = options
    this.locked = null
    this.batchLock = batchLock
    this.onseq = this.options.onseq || noop
    this.appending = null
    this.isSnapshot = this.core !== this.tree.core
    this.shouldUpdate = this.options.update !== false
    this.updating = null
    this.encoding = {
      key: options.keyEncoding ? codecs(options.keyEncoding) : tree.keyEncoding,
      value: options.valueEncoding ? codecs(options.valueEncoding) : tree.valueEncoding
    }
  }

  async ready() {
    if (this.core.opened === false) await this.core.ready()
    if (this.tree.opened === false) await this.tree.ready()
  }

  async lock() {
    if (this.tree.readonly) throw new Error('Hyperbee is marked as read-only')
    if (this.locked === null) this.locked = await this.tree.lock()
  }

  get version() {
    if (this.checkout !== -1) return Math.max(1, this.checkout)
    return Math.max(1, this.tree._checkout || this.core.length + this.length)
  }

  async getRoot(ensureHeader) {
    await this.ready()
    if (ensureHeader) {
      if (this.core.length === 0 && this.core.writable && !this.tree.readonly) {
        await this.core.append(
          Header.encode({
            protocol: 'hyperbee',
            metadata: this.tree.metadata
          })
        )
      }
    }
    if (this.tree._checkout === 0 && this.checkout === -1 && this.shouldUpdate) {
      if (this.updating === null) this.updating = this.core.update()
      await this.updating
    }
    if (this.version < 2) return null
    return (await this.getBlock(this.version - 1)).getTreeNode(0)
  }

  async getKey(seq) {
    await this.tree._cacheLock.enter(seq)

    try {
      const k = this.core.fork === this.tree.core.fork ? this.tree._keyCache.get(seq) : null
      if (k !== null) return k
      const key = (await this._getBlock(seq)).key
      if (this.core.fork === this.tree.core.fork) this.tree._keyCache.set(seq, key)
      return key
    } finally {
      this.tree._cacheLock.exit(seq)
    }
  }

  async _getNode(seq) {
    const cached =
      this.tree._nodeCache !== null && this.core.fork === this.tree.core.fork
        ? this.tree._nodeCache.get(seq)
        : null
    if (cached !== null) return cached
    const entry = await this.core.get(seq, {
      ...this.options,
      valueEncoding: Node
    })
    if (entry === null) throw BLOCK_NOT_AVAILABLE()
    const wrap = copyEntry(entry)
    if (this.core.fork === this.tree.core.fork && this.tree._nodeCache !== null) {
      this.tree._nodeCache.set(seq, wrap)
    }
    return wrap
  }

  async getBlock(seq) {
    if (this.rootSeq === 0) this.rootSeq = seq
    await this.tree._cacheLock.enter(seq)

    try {
      return await this._getBlock(seq)
    } finally {
      this.tree._cacheLock.exit(seq)
    }
  }

  async _getBlock(seq) {
    let b = this.blocks && this.blocks.get(seq)
    if (b) return b
    this.onseq(seq)
    const entry = await this._getNode(seq)
    b = this.blocks && this.blocks.get(seq)
    if (b) return b
    b = new BlockEntry(seq, this, entry)
    if (this.blocks && this.blocks.size - this.length < this.maxBlocksCached) {
      this.blocks.set(seq, b)
    }
    return b
  }

  _onwait(key) {
    this.options.onwait = null
    this.tree.extension.get(this.rootSeq + 1, key)
  }

  _getEncoding(opts) {
    if (!opts) return this.encoding
    return {
      key: opts.keyEncoding ? codecs(opts.keyEncoding) : this.encoding.key,
      value: opts.valueEncoding ? codecs(opts.valueEncoding) : this.encoding.value
    }
  }

  peek(range, opts) {
    return iteratorPeek(this.createRangeIterator(range, { ...opts, limit: 1 }))
  }

  createRangeIterator(range, opts = {}) {
    // backwards compat range arg
    opts = opts ? { ...opts, ...range } : range

    const encoding = this._getEncoding(opts)
    return new RangeIterator(
      this,
      encoding,
      encRange(encoding.key, { ...opts, sub: this.tree._sub })
    )
  }

  createReadStream(range, opts) {
    const signal = (opts && opts.signal) || null
    return iteratorToStream(this.createRangeIterator(range, opts), signal)
  }

  async getBySeq(seq, opts) {
    const encoding = this._getEncoding(opts)

    try {
      const block = (await this.getBlock(seq)).final(encoding)
      return { key: block.key, value: block.value }
    } finally {
      await this._closeSnapshot()
    }
  }

  async get(key, opts) {
    const encoding = this._getEncoding(opts)
    const finalize = opts ? opts.finalize !== false : true

    try {
      return await this._get(key, encoding, finalize)
    } finally {
      await this._closeSnapshot()
    }
  }

  async _get(key, encoding, finalize) {
    key = enc(encoding.key, key)

    if (this.tree.extension !== null && this.options.extension !== false) {
      this.options.onwait = this._onwait.bind(this, key)
    }

    let node = await this.getRoot(false)
    if (!node) return null

    while (true) {
      if (node.block.isTarget(key)) {
        return node.block.isDeletion() ? null : finalize ? node.block.final(encoding) : node.block
      }

      let s = 0
      let e = node.keys.length
      let c

      while (s < e) {
        const mid = (s + e) >> 1

        c = b4a.compare(key, await node.getKey(mid))

        if (c === 0) {
          const block = await this.getBlock(node.keys[mid].seq)
          return finalize ? block.final(encoding) : block
        }

        if (c < 0) e = mid
        else s = mid + 1
      }

      if (!node.children.length) return null

      const i = c < 0 ? e : s
      node = await node.getChildNode(i)
    }
  }

  async links(key, seq) {
    let node = await this.getRoot(false)
    if (!node) return false

    if (node.block.seq === seq) return true

    while (true) {
      if (node.block.isTarget(key)) return false

      let s = 0
      let e = node.keys.length
      let c

      while (s < e) {
        const mid = (s + e) >> 1

        if (node.keys[mid].seq === seq) return true
        c = b4a.compare(key, await node.getKey(mid))

        if (c === 0) return false

        if (c < 0) e = mid
        else s = mid + 1
      }

      if (!node.children.length) return false

      const i = c < 0 ? e : s
      node = await node.getChildNode(i)
      if (node.block.seq === seq) return true
    }
  }

  async put(key, value, opts) {
    const release = this.batchLock ? await this.batchLock() : null

    const cas = (opts && opts.cas) || null
    const encoding = this._getEncoding(opts)

    if (!this.locked) await this.lock()
    if (!release) return this._put(key, value, encoding, cas)

    try {
      return await this._put(key, value, encoding, cas)
    } finally {
      release()
    }
  }

  async _put(key, value, encoding, cas) {
    const newNode = {
      seq: 0,
      key,
      value
    }
    key = enc(encoding.key, key)
    value = enc(encoding.value, value)

    const stack = []

    let root
    let node = (root = await this.getRoot(true))
    if (!node) node = root = TreeNode.create(null)

    const seq = (newNode.seq = this.core.length + this.length)
    const target = new Key(seq, key)

    while (node.children.length) {
      stack.push(node)
      node.changed = true // changed, but compressible

      let s = 0
      let e = node.keys.length
      let c

      while (s < e) {
        const mid = (s + e) >> 1
        c = b4a.compare(target.value, await node.getKey(mid))

        if (c === 0) {
          if (cas) {
            const prev = await node.getKeyNode(mid)
            if (!(await cas(prev.final(encoding), newNode))) return this._unlockMaybe()
          }
          if (!this.tree.alwaysDuplicate) {
            const prev = await node.getKeyNode(mid)
            if (sameValue(prev.value, value)) return this._unlockMaybe()
          }
          node.setKey(mid, target)
          return this._append(root, seq, key, value)
        }

        if (c < 0) e = mid
        else s = mid + 1
      }

      const i = c < 0 ? e : s
      node = await node.getChildNode(i)
    }

    let needsSplit = !(await node.insertKey(target, value, null, newNode, encoding, cas))
    if (!node.changed) return this._unlockMaybe()

    while (needsSplit) {
      const parent = stack.pop()
      const { median, right } = await node.split()

      if (parent) {
        needsSplit = !(await parent.insertKey(median, value, right, null, encoding, null))
        node = parent
      } else {
        root = TreeNode.create(node.block)
        root.changed = true
        root.keys.push(median)
        root.children.push(new Child(0, 0, node), new Child(0, 0, right))
        needsSplit = false
      }
    }

    return this._append(root, seq, key, value)
  }

  async del(key, opts) {
    const release = this.batchLock ? await this.batchLock() : null
    const cas = (opts && opts.cas) || null
    const encoding = this._getEncoding(opts)

    if (!this.locked) await this.lock()
    if (!release) return this._del(key, encoding, cas)

    try {
      return await this._del(key, encoding, cas)
    } finally {
      release()
    }
  }

  async _del(key, encoding, cas) {
    const delNode = {
      seq: 0,
      key,
      value: null
    }

    key = enc(encoding.key, key)

    const stack = []

    let node = await this.getRoot(true)
    if (!node) return this._unlockMaybe()

    const seq = (delNode.seq = this.core.length + this.length)

    while (true) {
      stack.push(node)

      let s = 0
      let e = node.keys.length
      let c

      while (s < e) {
        const mid = (s + e) >> 1
        c = b4a.compare(key, await node.getKey(mid))

        if (c === 0) {
          if (cas) {
            const prev = await node.getKeyNode(mid)
            if (!(await cas(prev.final(encoding), delNode))) return this._unlockMaybe()
          }
          if (node.children.length) await setKeyToNearestLeaf(node, mid, stack)
          else node.removeKey(mid)
          // we mark these as changed late, so we don't rewrite them if it is a 404
          for (const node of stack) node.changed = true
          return this._append(await rebalance(stack), seq, key, null)
        }

        if (c < 0) e = mid
        else s = mid + 1
      }

      if (!node.children.length) return this._unlockMaybe()

      const i = c < 0 ? e : s
      node = await node.getChildNode(i)
    }
  }

  async _closeSnapshot() {
    if (this.isSnapshot) {
      await this.core.close()
      this._finalize()
    }
  }

  async close() {
    if (this.isSnapshot) return this._closeSnapshot()

    this.root = null
    if (this.blocks) this.blocks.clear()
    this.length = 0
    this._unlock()
  }

  destroy() {
    // compat, remove later
    this.close().catch(noop)
  }

  toBlocks() {
    if (this.appending) return this.appending

    const batch = new Array(this.length)

    for (let i = 0; i < this.length; i++) {
      const seq = this.core.length + i
      const { pendingIndex, key, value } = this.blocks.get(seq)

      if (i < this.length - 1) {
        pendingIndex[0] = null
        let j = 0

        while (j < pendingIndex.length) {
          const idx = pendingIndex[j]
          if (idx !== null && idx.seq === seq) {
            idx.offset = j++
            continue
          }
          if (j === pendingIndex.length - 1) pendingIndex.pop()
          else pendingIndex[j] = pendingIndex.pop()
        }
      }

      batch[i] = Node.encode({
        key,
        value,
        index: deflate(pendingIndex)
      })
    }

    this.appending = batch
    return batch
  }

  flush() {
    if (!this.length) return this.close()

    const batch = this.toBlocks()

    this.root = null
    this.blocks.clear()
    this.length = 0

    return this._appendBatch(batch)
  }

  _unlockMaybe() {
    if (this.autoFlush) this._unlock()
  }

  _unlock() {
    const locked = this.locked
    this.locked = null
    if (locked !== null) locked()
    this._finalize()
  }

  _finalize() {
    // technically finalize can be called more than once, so here we just check if we already have been removed
    if (this.index >= this.tree._batches.length || this.tree._batches[this.index] !== this) return
    const top = this.tree._batches.pop()
    if (top === this) return
    top.index = this.index
    this.tree._batches[top.index] = top
  }

  _append(root, seq, key, value) {
    const index = []
    root.indexChanges(index, seq)
    index[0] = new Child(seq, 0, root)

    if (!this.autoFlush) {
      const block = new BatchEntry(seq, this, key, value, index)
      root.block = block
      this.root = root
      this.length++
      this.blocks.set(seq, block)

      root.updateChildren(seq, block)
      return
    }

    return this._appendBatch(
      Node.encode({
        key,
        value,
        index: deflate(index)
      })
    )
  }

  async _appendBatch(raw) {
    try {
      await this.core.append(raw)
    } finally {
      this._unlock()
    }
  }
}

class EntryWatcher extends ReadyResource {
  constructor(bee, key, opts = {}) {
    super()

    this.keyEncoding = opts.keyEncoding || bee.keyEncoding
    this.valueEncoding = opts.valueEncoding || bee.valueEncoding

    this.index = bee._entryWatchers.push(this) - 1
    this.bee = bee

    this.key = key
    this.node = null

    this._forceUpdate = false
    this._debouncedUpdate = debounce(this._processUpdate.bind(this))
  }

  _close() {
    const top = this.bee._entryWatchers.pop()
    if (top !== this) {
      top.index = this.index
      this.bee._entryWatchers[top.index] = top
    }
  }

  _onappend() {
    this._debouncedUpdate()
  }

  _ontruncate() {
    this._forceUpdate = true
    this._debouncedUpdate()
  }

  async _processUpdate() {
    const force = this._forceUpdate
    this._forceUpdate = false

    let newNode
    try {
      newNode = await this.bee.get(this.key, {
        keyEncoding: this.keyEncoding,
        valueEncoding: this.valueEncoding
      })
    } catch (e) {
      if (e.code === 'SNAPSHOT_NOT_AVAILABLE') {
        // There was a truncate event before the get resolved
        // So this handler will run again anyway
        return
      } else if (this.bee.closing) {
        this.close().catch(safetyCatch)
        return
      }
      this.emit('error', e)
      return
    }

    if (force || newNode?.seq !== this.node?.seq) {
      this.node = newNode
      this.emit('update')
    }
  }
}

class Watcher extends ReadyResource {
  constructor(bee, range, opts = {}) {
    super()

    this.keyEncoding = opts.keyEncoding || bee.keyEncoding
    this.valueEncoding = opts.valueEncoding || bee.valueEncoding
    this.index = bee._watchers.push(this) - 1
    this.bee = bee
    this.core = bee.core

    this.latestDiff = 0
    this.range = range
    this.map = opts.map || defaultWatchMap

    this.current = null
    this.previous = null
    this.currentMapped = null
    this.previousMapped = null
    this.stream = null

    this._lock = mutexify()
    this._flowing = false
    this._resolveOnChange = null
    this._differ = opts.differ || defaultDiffer
    this._eager = !!opts.eager
    this._onchange = opts.onchange || null

    this.on('newListener', autoFlowOnUpdate)

    this.ready().catch(safetyCatch)
  }

  async _consume() {
    if (this._flowing) return
    try {
      for await (const _ of this) {
      } // eslint-disable-line
    } catch {}
  }

  async _open() {
    await this.bee.ready()

    const opts = {
      keyEncoding: this.keyEncoding,
      valueEncoding: this.valueEncoding
    }

    // Point from which to start watching
    this.current = this._eager ? this.bee.checkout(1, opts) : this.bee.snapshot(opts)
    await this.current.ready()

    if (this._onchange) {
      if (this._eager) await this._onchange()
      this._consume()
    }
  }

  [Symbol.asyncIterator]() {
    this._flowing = true
    return this
  }

  _ontruncate() {
    this._onappend()
  }

  _onappend() {
    const resolve = this._resolveOnChange
    this._resolveOnChange = null
    if (resolve) resolve()
  }

  async _waitForChanges() {
    if (this.current.version < this.bee.version || this.closing) return

    await new Promise((resolve) => {
      this._resolveOnChange = resolve
    })
  }

  async next() {
    try {
      return await this._next()
    } catch (err) {
      if (this.closing) return { value: undefined, done: true }
      await this.close()
      throw err
    }
  }

  async _next() {
    const release = await this._lock()

    try {
      if (this.closing) return { value: undefined, done: true }

      if (!this.opened) await this.ready()

      while (true) {
        await this._waitForChanges()

        if (this.closing) return { value: undefined, done: true }

        await this._closePrevious()
        this.previous = this.current.snapshot()

        await this._closeCurrent()
        this.current = this.bee.snapshot({
          keyEncoding: this.keyEncoding,
          valueEncoding: this.valueEncoding
        })

        await this.current.ready()
        await this.previous.ready()

        if (this.current.core.fork !== this.previous.core.fork) {
          return await this._yield()
        }

        this.stream = this._differ(this.current, this.previous, this.range)

        try {
          for await (const data of this.stream) {
            // eslint-disable-line
            return await this._yield()
          }
        } finally {
          this.stream = null
        }
      }
    } finally {
      release()
    }
  }

  async _yield() {
    this.currentMapped = this.map(this.current)
    this.previousMapped = this.map(this.previous)

    if (this._onchange) {
      try {
        await this._onchange()
      } catch (err) {
        safetyCatch(err)
      }
    }

    this.emit('update')
    return { done: false, value: [this.currentMapped, this.previousMapped] }
  }

  async return() {
    await this.close()
    return { done: true }
  }

  async _close() {
    const top = this.bee._watchers.pop()
    if (top !== this) {
      top.index = this.index
      this.bee._watchers[top.index] = top
    }

    if (this.stream && !this.stream.destroying) {
      this.stream.destroy()
    }

    this._onappend() // Continue execution being closed

    await this._closeCurrent().catch(safetyCatch)
    await this._closePrevious().catch(safetyCatch)

    const release = await this._lock()
    release()
  }

  destroy() {
    return this.close()
  }

  async _closeCurrent() {
    if (this.currentMapped) await this.currentMapped.close()
    if (this.current) await this.current.close()
    this.current = this.currentMapped = null
  }

  async _closePrevious() {
    if (this.previousMapped) await this.previousMapped.close()
    if (this.previous) await this.previous.close()
    this.previous = this.previousMapped = null
  }
}

function autoFlowOnUpdate(name) {
  if (name === 'update') this._consume()
}

function defaultWatchMap(snapshot) {
  return snapshot
}

async function leafSize(node, goLeft) {
  while (node.children.length) node = await node.getChildNode(goLeft ? 0 : node.children.length - 1)
  return node.keys.length
}

async function setKeyToNearestLeaf(node, index, stack) {
  let [left, right] = await Promise.all([node.getChildNode(index), node.getChildNode(index + 1)])
  const [ls, rs] = await Promise.all([leafSize(left, false), leafSize(right, true)])

  if (ls < rs) {
    // if fewer leaves on the left
    stack.push(right)
    while (right.children.length) stack.push((right = right.children[0].value))
    node.keys[index] = right.keys.shift()
  } else {
    // if fewer leaves on the right
    stack.push(left)
    while (left.children.length) stack.push((left = left.children[left.children.length - 1].value))
    node.keys[index] = left.keys.pop()
  }
}

async function rebalance(stack) {
  const root = stack[0]

  while (stack.length > 1) {
    const node = stack.pop()
    const parent = stack[stack.length - 1]

    if (node.keys.length >= MIN_KEYS) return root

    let { left, index, right } = await node.siblings(parent)

    // maybe borrow from left sibling?
    if (left && left.keys.length > MIN_KEYS) {
      left.changed = true
      node.keys.unshift(parent.keys[index - 1])
      if (left.children.length) node.children.unshift(left.children.pop())
      parent.keys[index - 1] = left.keys.pop()
      return root
    }

    // maybe borrow from right sibling?
    if (right && right.keys.length > MIN_KEYS) {
      right.changed = true
      node.keys.push(parent.keys[index])
      if (right.children.length) node.children.push(right.children.shift())
      parent.keys[index] = right.keys.shift()
      return root
    }

    // merge node with another sibling
    if (left) {
      index--
      right = node
    } else {
      left = node
    }

    left.merge(right, parent.keys[index])
    parent.removeKey(index)
  }

  // check if the tree shrunk
  if (!root.keys.length && root.children.length) return root.getChildNode(0)
  return root
}

function iteratorToStream(ite, signal) {
  let done
  let closing

  const rs = new Readable({
    signal,
    open(cb) {
      done = cb
      ite.open().then(fin, fin)
    },
    read(cb) {
      done = cb
      ite.next().then(push, fin)
    },
    predestroy() {
      closing = ite.close()
      closing.catch(noop)
    },
    destroy(cb) {
      done = cb
      if (!closing) closing = ite.close()
      closing.then(fin, fin)
    }
  })

  return rs

  function fin(err) {
    done(err)
  }

  function push(val) {
    rs.push(val)
    done(null)
  }
}

async function iteratorPeek(ite) {
  try {
    await ite.open()
    return await ite.next()
  } finally {
    await ite.close()
  }
}

function encRange(e, opts) {
  if (!e) return opts

  if (e.encodeRange) {
    const r = e.encodeRange({
      gt: opts.gt,
      gte: opts.gte,
      lt: opts.lt,
      lte: opts.lte
    })
    opts.gt = r.gt
    opts.gte = r.gte
    opts.lt = r.lt
    opts.lte = r.lte
    return opts
  }

  if (opts.gt !== undefined) opts.gt = enc(e, opts.gt)
  if (opts.gte !== undefined) opts.gte = enc(e, opts.gte)
  if (opts.lt !== undefined) opts.lt = enc(e, opts.lt)
  if (opts.lte !== undefined) opts.lte = enc(e, opts.lte)
  if (opts.sub && !opts.gt && !opts.gte) opts.gt = enc(e, SEP)
  if (opts.sub && !opts.lt && !opts.lte) opts.lt = bump(enc(e, EMPTY))

  return opts
}

function bump(key) {
  // key should have been copied by enc above before hitting this
  key[key.length - 1]++
  return key
}

function enc(e, v) {
  if (v === undefined || v === null) return null
  if (e !== null) return e.encode(v)
  if (typeof v === 'string') return b4a.from(v)
  return v
}

function prefixEncoding(prefix, keyEncoding) {
  return {
    encode(key) {
      return b4a.concat([prefix, b4a.isBuffer(key) ? key : enc(keyEncoding, key)])
    },
    decode(key) {
      const sliced = key.slice(prefix.length, key.length)
      return keyEncoding ? keyEncoding.decode(sliced) : sliced
    }
  }
}

function copyEntry(entry) {
  let key = entry.key
  let value = entry.value
  let index = entry.index

  // key, value and index all refer to the same buffer (one hypercore block)
  // If together they are larger than half the buffer's byteLength,
  // this means that they got their own private slab (see Buffer.allocUnsafe docs)
  // so no need to unslab
  const size =
    key.byteLength +
    (value === null ? 0 : value.byteLength) +
    (index === null ? 0 : index.byteLength)
  if (2 * size < key.buffer.byteLength) {
    const [newKey, newValue, newIndex] = unslabAll([entry.key, entry.value, entry.index])
    key = newKey
    value = newValue
    index = newIndex
  }

  return {
    key,
    value,
    index,
    inflated: null
  }
}

function defaultDiffer(currentSnap, previousSnap, opts) {
  return currentSnap.createDiffStream(previousSnap, opts)
}

function toNull() {
  return null
}

function getBackingCore(core) {
  if (core.core) return core
  if (core.getBackingCore) return core.getBackingCore().session
  return null
}

function sameValue(a, b) {
  return a === b || (a !== null && b !== null && b4a.equals(a, b))
}

function noop() {}

function getExtension(db, opts) {
  if (opts.extension === false) return null
  if (opts.extension && opts.extension !== true) return opts.extension
  return Extension.register(db)
}

async function isLinked(batch, block) {
  const seq = block.seq
  block.inflate()

  const keys = [block.key]
  const wait = batch.options.wait

  for (const l of block.index.levels) {
    if (!l.keys.length) continue
    batch.options.wait = false
    try {
      keys.push(await batch.getKey(l.keys[0].seq))
    } catch {}
    batch.options.wait = wait
  }

  for (const k of keys) {
    if (await batch.links(k, seq)) return true
  }

  if (batch.core.closing) throw new Error('Core is closed')

  return false
}

module.exports = Hyperbee
const b4a = require('b4a')

class SubTree {
  constructor(node, parent) {
    this.node = node
    this.parent = parent

    this.isKey = node.children.length === 0
    this.i = this.isKey ? 1 : 0
    this.n = 0

    const child = this.isKey ? null : this.node.children[0]
    this.seq = child !== null ? child.seq : this.node.keys[0].seq
    this.offset = child !== null ? child.offset : 0
  }

  next() {
    this.i++
    this.isKey = (this.i & 1) === 1
    if (!this.isKey && !this.node.children.length) this.i++
    return this.update()
  }

  async bisect(key, incl) {
    let s = 0
    let e = this.node.keys.length
    let c

    while (s < e) {
      const mid = (s + e) >> 1
      c = cmp(key, await this.node.getKey(mid))

      if (c === 0) {
        if (incl) this.i = mid * 2 + 1
        else this.i = mid * 2 + (this.node.children.length ? 2 : 3)
        return true
      }

      if (c < 0) e = mid
      else s = mid + 1
    }

    const i = c < 0 ? e : s
    this.i = 2 * i + (this.node.children.length ? 0 : 1)
    return this.node.children.length === 0
  }

  update() {
    this.isKey = (this.i & 1) === 1
    this.n = this.i >> 1
    if (this.n >= (this.isKey ? this.node.keys.length : this.node.children.length)) return false
    const child = this.isKey ? null : this.node.children[this.n]
    this.seq = child !== null ? child.seq : this.node.keys[this.n].seq
    this.offset = child !== null ? child.offset : 0
    return true
  }

  async key() {
    return this.n < this.node.keys.length
      ? this.node.getKey(this.n)
      : this.parent && this.parent.key()
  }

  async compare(tree) {
    const [a, b] = await Promise.all([this.key(), tree.key()])
    return cmp(a, b)
  }
}

class TreeIterator {
  constructor(batch, opts) {
    this.batch = batch
    this.stack = []
    this.lt = opts.lt || opts.lte || null
    this.lte = !!opts.lte
    this.gt = opts.gt || opts.gte || null
    this.gte = !!opts.gte
    this.seeking = !!this.gt
    this.encoding = opts.encoding || batch.encoding
  }

  async open() {
    const node = await this.batch.getRoot(false)
    if (!node || !node.keys.length) return
    const tree = new SubTree(node, null)
    if (this.seeking && !(await this._seek(tree))) return
    this.stack.push(tree)
  }

  async _seek(tree) {
    const done = await tree.bisect(this.gt, this.gte)
    const oob = !tree.update()
    if (done || oob) {
      this.seeking = false
      if (oob) return false
    }
    return true
  }

  peek() {
    if (!this.stack.length) return null
    return this.stack[this.stack.length - 1]
  }

  skip() {
    if (!this.stack.length) return
    if (!this.stack[this.stack.length - 1].next()) this.stack.pop()
  }

  async nextKey() {
    let n = null
    while (this.stack.length && n === null) n = await this.next()
    if (n === null) return null
    if (!this.lt) return n.final(this.encoding)

    const c = cmp(n.key, this.lt)
    if (this.lte ? c <= 0 : c < 0) return n.final(this.encoding)
    this.stack = []
    return null
  }

  async next() {
    if (!this.stack.length) return null

    const top = this.stack[this.stack.length - 1]
    const { isKey, n, seq } = top

    if (!top.next()) {
      this.stack.pop()
    }

    if (isKey) {
      this.seeking = false
      return this.batch.getBlock(seq)
    }

    const child = await top.node.getChildNode(n)
    top.node.children[n] = null // unlink to save memory
    const tree = new SubTree(child, top)
    if (this.seeking && !(await this._seek(tree))) return null
    this.stack.push(tree)

    return null
  }

  close() {
    return this.batch._closeSnapshot()
  }
}

module.exports = class DiffIterator {
  constructor(left, right, opts = {}) {
    this.left = new TreeIterator(left, opts)
    this.right = new TreeIterator(right, opts)
    this.limit = typeof opts.limit === 'number' ? opts.limit : -1
  }

  async open() {
    await Promise.all([this.left.open(), this.right.open()])
  }

  async next() {
    if (this.limit === 0) return null
    const res = await this._next()
    if (!res || (res.left === null && res.right === null)) return null
    this.limit--
    return res
  }

  async _next() {
    const a = this.left
    const b = this.right

    while (true) {
      const [l, r] = await Promise.all([a.peek(), b.peek()])

      if (!l && !r) return null
      if (!l) return { left: null, right: await b.nextKey() }
      if (!r) return { left: await a.nextKey(), right: null }

      if (l.seq === r.seq && l.isKey === r.isKey && l.offset === r.offset) {
        a.skip()
        b.skip()
        continue
      }

      const c = await l.compare(r)

      if (l.isKey && !r.isKey) {
        await b.next()
        continue
      }

      if (!l.isKey && r.isKey) {
        await a.next()
        continue
      }

      if (l.isKey && r.isKey) {
        if (c === 0) return { left: await a.nextKey(), right: await b.nextKey() }
        if (c < 0) return { left: await a.nextKey(), right: null }
        return { left: null, right: await b.nextKey() }
      }

      if (c === 0) await Promise.all([a.next(), b.next()])
      else if (c < 0) await b.next()
      else await a.next()
    }
  }

  async close() {
    await Promise.all([this.left.close(), this.right.close()])
  }
}

function cmp(a, b) {
  if (!a) return b ? 1 : 0
  if (!b) return a ? -1 : 0
  return b4a.compare(a, b)
}
module.exports = class HistoryIterator {
  constructor(batch, opts = {}) {
    this.batch = batch
    this.options = opts
    this.live = !!opts.live
    this.gte = 0
    this.lt = 0
    this.reverse = !!opts.reverse
    this.limit = typeof opts.limit === 'number' ? opts.limit : -1
    this.encoding = opts.encoding || batch.encoding
    if (this.live && this.reverse) {
      throw new Error('Cannot have both live and reverse enabled')
    }
  }

  async open() {
    await this.batch.getRoot(false) // does the update dance
    this.gte = gte(this.options, this.batch.version)
    this.lt = this.live ? Infinity : lt(this.options, this.batch.version)
  }

  async next() {
    if (this.limit === 0) return null
    if (this.limit > 0) this.limit--

    if (this.gte >= this.lt) return null

    if (this.reverse) {
      if (this.lt <= 1) return null
      return final(await this.batch.getBlock(--this.lt), this.encoding)
    }

    return final(await this.batch.getBlock(this.gte++), this.encoding)
  }

  close() {
    return this.batch._closeSnapshot()
  }
}

function final(node, encoding) {
  const type = node.isDeletion() ? 'del' : 'put'
  return { type, ...node.final(encoding) }
}

function gte(opts, version) {
  if (opts.gt) return (opts.gt < 0 ? opts.gt + version : opts.gt) + 1
  const gte = opts.gte || opts.since || 1
  return gte < 0 ? gte + version : gte
}

function lt(opts, version) {
  if (opts.lte === 0 || opts.lt === 0 || opts.end === 0) return 0
  if (opts.lte) return (opts.lte < 0 ? opts.lte + version : opts.lte) + 1
  const lt = opts.lt || opts.end || version
  return lt < 0 ? lt + version : lt
}
module.exports = class LocalBlocksIterator {
  constructor(batch, opts = {}) {
    this.batch = batch
    this.options = opts
    this.gte = 0
    this.lt = 0
    this.limit = typeof opts.limit === 'number' ? opts.limit : -1
  }

  async open() {
    await this.batch.getRoot(false) // does the update dance
    this.gte = gte(this.options, this.batch.version)
    this.lt = lt(this.options, this.batch.version)
  }

  async next() {
    if (this.limit === 0) return null
    if (this.limit > 0) this.limit--

    while (this.gte < this.lt) {
      try {
        return await this.batch.getBlock(this.gte++)
      } catch {
        continue
      }
    }

    return null
  }

  close() {
    return this.batch._closeSnapshot()
  }
}

function gte(opts, version) {
  if (opts.gt) return (opts.gt < 0 ? opts.gt + version : opts.gt) + 1
  const gte = opts.gte || opts.since || 1
  return gte < 0 ? gte + version : gte
}

function lt(opts, version) {
  if (opts.lte === 0 || opts.lt === 0 || opts.end === 0) return 0
  if (opts.lte) return (opts.lte < 0 ? opts.lte + version : opts.lte) + 1
  const lt = opts.lt || opts.end || version
  return lt < 0 ? lt + version : lt
}
const b4a = require('b4a')

module.exports = class RangeIterator {
  constructor(batch, encoding, opts = {}) {
    this.batch = batch
    this.stack = []
    this.opened = false
    this.encoding = encoding || batch.encoding

    this._limit = typeof opts.limit === 'number' ? opts.limit : -1
    this._gIncl = !opts.gt
    this._gKey = opts.gt || opts.gte || null
    this._lIncl = !opts.lt
    this._lKey = opts.lt || opts.lte || null
    this._reverse = !!opts.reverse
    this._version = 0
    this._checkpoint = opts.checkpoint && opts.checkpoint.length ? opts.checkpoint : null
    this._nexting = false
    this._closed = false
  }

  snapshot(version = this.batch.version) {
    const checkpoint = []
    for (const s of this.stack) {
      let { node, i } = s
      if (this._nexting && s === this.stack[this.stack.length - 1]) {
        i = this._reverse ? i + 1 : i - 1
      }
      if (!node.block) continue
      if (i < 0) continue
      checkpoint.push(node.block.seq, node.offset, i)
    }

    return {
      version,
      gte: this._gIncl ? this._gKey : null,
      gt: this._gIncl ? null : this._gKey,
      lte: this._lIncl ? this._lKey : null,
      lt: this._lIncl ? null : this._lKey,
      limit: this._limit,
      reverse: this._reverse,
      ended: this.opened && !checkpoint.length,
      checkpoint: this.opened ? checkpoint : []
    }
  }

  async open() {
    await this._open()
    this.opened = true
  }

  async _open() {
    if (this._checkpoint) {
      for (let j = 0; j < this._checkpoint.length; j += 3) {
        const seq = this._checkpoint[j]
        const offset = this._checkpoint[j + 1]
        const i = this._checkpoint[j + 2]
        this.stack.push({
          node: (await this.batch.getBlock(seq)).getTreeNode(offset),
          i
        })
      }
      return
    }

    this._nexting = true

    let node = await this.batch.getRoot(false)
    if (!node) {
      this._nexting = false
      return
    }

    const incl = this._reverse ? this._lIncl : this._gIncl
    const start = this._reverse ? this._lKey : this._gKey

    if (!start) {
      this.stack.push({ node, i: this._reverse ? node.keys.length << 1 : 0 })
      this._nexting = false
      this._preloadQuery()
      return
    }

    while (true) {
      const entry = { node, i: this._reverse ? node.keys.length << 1 : 0 }

      let s = 0
      let e = node.keys.length
      let c

      while (s < e) {
        const mid = (s + e) >> 1
        c = b4a.compare(start, await node.getKey(mid))

        if (c === 0) {
          if (incl) entry.i = mid * 2 + 1
          else entry.i = mid * 2 + (this._reverse ? 0 : 2)
          this.stack.push(entry)
          this._nexting = false
          this._preloadQuery()
          return
        }

        if (c < 0) e = mid
        else s = mid + 1
      }

      const i = c < 0 ? e : s
      entry.i = 2 * i + (this._reverse ? -1 : 1)

      if (entry.i >= 0 && entry.i <= node.keys.length << 1) this.stack.push(entry)
      if (!node.children.length) {
        this._nexting = false
        this._preloadQuery()
        return
      }

      node = await node.getChildNode(i)
    }
  }

  _preloadQuery() {
    const max = { nodes: 0, max: 2048 }

    if (this._limit === -1 && !this._reverse && this.stack.length) {
      for (const s of this.stack) {
        const k = (s.i - (s.i & 1)) / 2
        this._preload(s.node, k + 1, this._lKey, max).catch(noop)
      }
    }
  }

  async _preload(node, i, end, max) {
    for (; i < node.keys.length; i++) {
      const key = node.keys[i]
      const block = await this.batch.getBlock(key.seq)
      if (this._closed) return
      const c = end ? b4a.compare(block.key, end) : -1
      if (c >= 0 || max.nodes >= max.max || i >= node.children.length) return
      max.nodes++
      const next = await node.getChildNode(i)
      if (this._closed) return
      this._preload(next, 0, end, max).catch(noop)
    }

    if (node.children.length && max.nodes < max.max) {
      const next = await node.getChildNode(node.children.length - 1)
      if (this._closed) return
      this._preload(next, 0, end, max).catch(noop)
    }
  }

  async next() {
    // TODO: this nexting flag is only needed if someone asks for a snapshot during
    // a lookup (ie the extension, pretty important...).
    // A better solution would be to refactor this so top.i is incremented eagerly
    // to get the current block instead of the way it is done now (++i vs i++)
    this._nexting = true

    const end = this._reverse ? this._gKey : this._lKey
    const incl = this._reverse ? this._gIncl : this._lIncl

    while (this.stack.length && (this._limit === -1 || this._limit > 0)) {
      const top = this.stack[this.stack.length - 1]
      const isKey = (top.i & 1) === 1
      const n = this._reverse ? (top.i < 0 ? top.node.keys.length : top.i-- >> 1) : top.i++ >> 1

      if (!isKey) {
        if (!top.node.children.length) continue
        const node = await top.node.getChildNode(n)
        if (top.node.block.seq < this.batch.core.length) {
          top.node.children[n].value = null // unlink it to save memory
        }
        this.stack.push({ i: this._reverse ? node.keys.length << 1 : 0, node })
        continue
      }

      if (n >= top.node.keys.length) {
        this.stack.pop()
        continue
      }

      const key = top.node.keys[n]
      const block = await this.batch.getBlock(key.seq)
      if (end) {
        const c = b4a.compare(block.key, end)
        if (c === 0 ? !incl : this._reverse ? c < 0 : c > 0) {
          this._limit = 0
          break
        }
      }
      if (this._limit > 0) this._limit--
      this._nexting = false
      return block.final(this.encoding)
    }

    this._nexting = false
    return null
  }

  close() {
    this._closed = true
    return this.batch._closeSnapshot()
  }
}

function noop() {}
const { Extension } = require('./messages')

// const MAX_ACTIVE = 32
const FLUSH_BATCH = 128
const MAX_PASSIVE_BATCH = 2048
const MAX_ACTIVE_BATCH = MAX_PASSIVE_BATCH + FLUSH_BATCH

class Batch {
  constructor(outgoing, from) {
    this.blocks = []
    this.start = 0
    this.end = 0
    this.outgoing = outgoing
    this.from = from
  }

  push(seq) {
    const len = this.blocks.push(seq)
    if (len === 1 || seq < this.start) this.start = seq
    if (len === 1 || seq >= this.end) this.end = seq + 1
    if (len >= FLUSH_BATCH) {
      this.send()
      this.clear()
    }
  }

  send() {
    if (!this.blocks.length) return
    this.outgoing.send(
      Extension.encode({
        cache: { blocks: this.blocks, start: this.start, end: this.end }
      }),
      this.from
    )
  }

  clear() {
    this.start = this.end = 0
    this.blocks = []
  }
}

class HyperbeeExtension {
  constructor(db) {
    this.encoding = null
    this.outgoing = null
    this.db = db
    this.active = 0
  }

  get(version, key) {
    this.outgoing.broadcast(Extension.encode({ get: { version, key } }))
  }

  iterator(snapshot) {
    if (snapshot.ended) return
    if (snapshot.limit === 0) return
    if (snapshot.limit === -1) snapshot.limit = 0
    this.outgoing.broadcast(Extension.encode({ iterator: snapshot }))
  }

  onmessage(buf, from) {
    // TODO: handle max active extension messages
    // this.active++

    const message = decode(buf)
    if (!message) return

    if (message.cache) this.oncache(message.cache, from)
    if (message.get) this.onget(message.get, from)
    if (message.iterator) this.oniterator(message.iterator, from)
  }

  oncache(message, from) {
    if (!message.blocks.length) return
    this.db.core.download(message)
  }

  onget(message, from) {
    if (!message.version || message.version > this.db.version) return

    const b = new Batch(this.outgoing, from)
    const db = this.db.checkout(message.version)

    db.get(message.key, {
      extension: false,
      wait: false,
      update: false,
      onseq
    }).then(done, done)

    function done() {
      db.close().catch(noop)
      b.send()
    }

    function onseq(seq) {
      b.push(seq)
    }
  }

  async oniterator(message, from) {
    if (!message.version || message.version > this.db.version) return

    const b = new Batch(this.outgoing, from)
    const seqs = new Set()

    let skip = message.checkpoint.length
    let work = 0

    const db = this.db.checkout(message.version)
    const ite = db.createRangeIterator({
      ...message,
      wait: false,
      extension: false,
      update: false,
      limit: message.limit === 0 ? -1 : message.limit,
      onseq(seq) {
        if (skip && skip--) return
        if (seqs.has(seq)) return
        work++
        seqs.add(seq)
        b.push(seq)
      }
    })

    try {
      await ite.open()
      // eslint-disable-next-line no-unmodified-loop-condition
      while (work < MAX_ACTIVE_BATCH) {
        if (!(await ite.next())) break
      }
    } catch (_) {
      // do nothing
    } finally {
      ite.close().catch(noop)
      db.close().catch(noop)
      b.send()
    }
  }

  static register(db) {
    const e = new this(db)
    e.outgoing = db.core.registerExtension('hyperbee', e)
    return e
  }
}

HyperbeeExtension.BATCH_SIZE = MAX_PASSIVE_BATCH

module.exports = HyperbeeExtension

function decode(buf) {
  try {
    return Extension.decode(buf)
  } catch (err) {
    return null
  }
}

function noop() {}
// This file is auto generated by the protocol-buffers compiler

/* eslint-disable quotes */
/* eslint-disable indent */
/* eslint-disable no-redeclare */
/* eslint-disable camelcase */
/* eslint-disable no-var */

// Remember to `npm install --save protocol-buffers-encodings`
var encodings = require('protocol-buffers-encodings')
var b4a = require('b4a')
var varint = encodings.varint
var skip = encodings.skip

var YoloIndex = exports.YoloIndex = {
  buffer: true,
  encodingLength: null,
  encode: null,
  decode: null
}

var Header = exports.Header = {
  buffer: true,
  encodingLength: null,
  encode: null,
  decode: null
}

var Node = exports.Node = {
  buffer: true,
  encodingLength: null,
  encode: null,
  decode: null
}

var Extension = exports.Extension = {
  buffer: true,
  encodingLength: null,
  encode: null,
  decode: null
}

defineYoloIndex()
defineHeader()
defineNode()
defineExtension()

function defineYoloIndex () {
  var Level = YoloIndex.Level = {
    buffer: true,
    encodingLength: null,
    encode: null,
    decode: null
  }

  defineLevel()

  function defineLevel () {
    Level.encodingLength = encodingLength
    Level.encode = encode
    Level.decode = decode

    function encodingLength (obj) {
      var length = 0
      if (defined(obj.keys)) {
        var packedLen = 0
        for (var i = 0; i < obj.keys.length; i++) {
          if (!defined(obj.keys[i])) continue
          var len = encodings.varint.encodingLength(obj.keys[i])
          packedLen += len
        }
        if (packedLen) {
          length += 1 + packedLen + varint.encodingLength(packedLen)
        }
      }
      if (defined(obj.children)) {
        var packedLen = 0
        for (var i = 0; i < obj.children.length; i++) {
          if (!defined(obj.children[i])) continue
          var len = encodings.varint.encodingLength(obj.children[i])
          packedLen += len
        }
        if (packedLen) {
          length += 1 + packedLen + varint.encodingLength(packedLen)
        }
      }
      return length
    }

    function encode (obj, buf, offset) {
      if (!offset) offset = 0
      if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
      var oldOffset = offset
      if (defined(obj.keys)) {
        var packedLen = 0
        for (var i = 0; i < obj.keys.length; i++) {
          if (!defined(obj.keys[i])) continue
          packedLen += encodings.varint.encodingLength(obj.keys[i])
        }
        if (packedLen) {
          buf[offset++] = 10
          varint.encode(packedLen, buf, offset)
          offset += varint.encode.bytes
        }
        for (var i = 0; i < obj.keys.length; i++) {
          if (!defined(obj.keys[i])) continue
          encodings.varint.encode(obj.keys[i], buf, offset)
          offset += encodings.varint.encode.bytes
        }
      }
      if (defined(obj.children)) {
        var packedLen = 0
        for (var i = 0; i < obj.children.length; i++) {
          if (!defined(obj.children[i])) continue
          packedLen += encodings.varint.encodingLength(obj.children[i])
        }
        if (packedLen) {
          buf[offset++] = 18
          varint.encode(packedLen, buf, offset)
          offset += varint.encode.bytes
        }
        for (var i = 0; i < obj.children.length; i++) {
          if (!defined(obj.children[i])) continue
          encodings.varint.encode(obj.children[i], buf, offset)
          offset += encodings.varint.encode.bytes
        }
      }
      encode.bytes = offset - oldOffset
      return buf
    }

    function decode (buf, offset, end) {
      if (!offset) offset = 0
      if (!end) end = buf.length
      if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
      var oldOffset = offset
      var obj = {
        keys: [],
        children: []
      }
      while (true) {
        if (end <= offset) {
          decode.bytes = offset - oldOffset
          return obj
        }
        var prefix = varint.decode(buf, offset)
        offset += varint.decode.bytes
        var tag = prefix >> 3
        switch (tag) {
          case 1:
          var packedEnd = varint.decode(buf, offset)
          offset += varint.decode.bytes
          packedEnd += offset
          while (offset < packedEnd) {
            obj.keys.push(encodings.varint.decode(buf, offset))
            offset += encodings.varint.decode.bytes
          }
          break
          case 2:
          var packedEnd = varint.decode(buf, offset)
          offset += varint.decode.bytes
          packedEnd += offset
          while (offset < packedEnd) {
            obj.children.push(encodings.varint.decode(buf, offset))
            offset += encodings.varint.decode.bytes
          }
          break
          default:
          offset = skip(prefix & 7, buf, offset)
        }
      }
    }
  }

  YoloIndex.encodingLength = encodingLength
  YoloIndex.encode = encode
  YoloIndex.decode = decode

  function encodingLength (obj) {
    var length = 0
    if (defined(obj.levels)) {
      for (var i = 0; i < obj.levels.length; i++) {
        if (!defined(obj.levels[i])) continue
        var len = Level.encodingLength(obj.levels[i])
        length += varint.encodingLength(len)
        length += 1 + len
      }
    }
    return length
  }

  function encode (obj, buf, offset) {
    if (!offset) offset = 0
    if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
    var oldOffset = offset
    if (defined(obj.levels)) {
      for (var i = 0; i < obj.levels.length; i++) {
        if (!defined(obj.levels[i])) continue
        buf[offset++] = 10
        varint.encode(Level.encodingLength(obj.levels[i]), buf, offset)
        offset += varint.encode.bytes
        Level.encode(obj.levels[i], buf, offset)
        offset += Level.encode.bytes
      }
    }
    encode.bytes = offset - oldOffset
    return buf
  }

  function decode (buf, offset, end) {
    if (!offset) offset = 0
    if (!end) end = buf.length
    if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
    var oldOffset = offset
    var obj = {
      levels: []
    }
    while (true) {
      if (end <= offset) {
        decode.bytes = offset - oldOffset
        return obj
      }
      var prefix = varint.decode(buf, offset)
      offset += varint.decode.bytes
      var tag = prefix >> 3
      switch (tag) {
        case 1:
        var len = varint.decode(buf, offset)
        offset += varint.decode.bytes
        obj.levels.push(Level.decode(buf, offset, offset + len))
        offset += Level.decode.bytes
        break
        default:
        offset = skip(prefix & 7, buf, offset)
      }
    }
  }
}

function defineHeader () {
  var Metadata = Header.Metadata = {
    buffer: true,
    encodingLength: null,
    encode: null,
    decode: null
  }

  defineMetadata()

  function defineMetadata () {
    Metadata.encodingLength = encodingLength
    Metadata.encode = encode
    Metadata.decode = decode

    function encodingLength (obj) {
      var length = 0
      if (defined(obj.contentFeed)) {
        var len = encodings.bytes.encodingLength(obj.contentFeed)
        length += 1 + len
      }
      if (defined(obj.userData)) {
        var len = encodings.bytes.encodingLength(obj.userData)
        length += 1 + len
      }
      return length
    }

    function encode (obj, buf, offset) {
      if (!offset) offset = 0
      if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
      var oldOffset = offset
      if (defined(obj.contentFeed)) {
        buf[offset++] = 10
        encodings.bytes.encode(obj.contentFeed, buf, offset)
        offset += encodings.bytes.encode.bytes
      }
      if (defined(obj.userData)) {
        buf[offset++] = 18
        encodings.bytes.encode(obj.userData, buf, offset)
        offset += encodings.bytes.encode.bytes
      }
      encode.bytes = offset - oldOffset
      return buf
    }

    function decode (buf, offset, end) {
      if (!offset) offset = 0
      if (!end) end = buf.length
      if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
      var oldOffset = offset
      var obj = {
        contentFeed: null,
        userData: null
      }
      while (true) {
        if (end <= offset) {
          decode.bytes = offset - oldOffset
          return obj
        }
        var prefix = varint.decode(buf, offset)
        offset += varint.decode.bytes
        var tag = prefix >> 3
        switch (tag) {
          case 1:
          obj.contentFeed = encodings.bytes.decode(buf, offset)
          offset += encodings.bytes.decode.bytes
          break
          case 2:
          obj.userData = encodings.bytes.decode(buf, offset)
          offset += encodings.bytes.decode.bytes
          break
          default:
          offset = skip(prefix & 7, buf, offset)
        }
      }
    }
  }

  Header.encodingLength = encodingLength
  Header.encode = encode
  Header.decode = decode

  function encodingLength (obj) {
    var length = 0
    if (!defined(obj.protocol)) throw new Error("protocol is required")
    var len = encodings.string.encodingLength(obj.protocol)
    length += 1 + len
    if (defined(obj.metadata)) {
      var len = Metadata.encodingLength(obj.metadata)
      length += varint.encodingLength(len)
      length += 1 + len
    }
    return length
  }

  function encode (obj, buf, offset) {
    if (!offset) offset = 0
    if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
    var oldOffset = offset
    if (!defined(obj.protocol)) throw new Error("protocol is required")
    buf[offset++] = 10
    encodings.string.encode(obj.protocol, buf, offset)
    offset += encodings.string.encode.bytes
    if (defined(obj.metadata)) {
      buf[offset++] = 18
      varint.encode(Metadata.encodingLength(obj.metadata), buf, offset)
      offset += varint.encode.bytes
      Metadata.encode(obj.metadata, buf, offset)
      offset += Metadata.encode.bytes
    }
    encode.bytes = offset - oldOffset
    return buf
  }

  function decode (buf, offset, end) {
    if (!offset) offset = 0
    if (!end) end = buf.length
    if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
    var oldOffset = offset
    var obj = {
      protocol: "",
      metadata: null
    }
    var found0 = false
    while (true) {
      if (end <= offset) {
        if (!found0) throw new Error("Decoded message is not valid")
        decode.bytes = offset - oldOffset
        return obj
      }
      var prefix = varint.decode(buf, offset)
      offset += varint.decode.bytes
      var tag = prefix >> 3
      switch (tag) {
        case 1:
        obj.protocol = encodings.string.decode(buf, offset)
        offset += encodings.string.decode.bytes
        found0 = true
        break
        case 2:
        var len = varint.decode(buf, offset)
        offset += varint.decode.bytes
        obj.metadata = Metadata.decode(buf, offset, offset + len)
        offset += Metadata.decode.bytes
        break
        default:
        offset = skip(prefix & 7, buf, offset)
      }
    }
  }
}

function defineNode () {
  Node.encodingLength = encodingLength
  Node.encode = encode
  Node.decode = decode

  function encodingLength (obj) {
    var length = 0
    if (!defined(obj.index)) throw new Error("index is required")
    var len = encodings.bytes.encodingLength(obj.index)
    length += 1 + len
    if (!defined(obj.key)) throw new Error("key is required")
    var len = encodings.bytes.encodingLength(obj.key)
    length += 1 + len
    if (defined(obj.value)) {
      var len = encodings.bytes.encodingLength(obj.value)
      length += 1 + len
    }
    return length
  }

  function encode (obj, buf, offset) {
    if (!offset) offset = 0
    if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
    var oldOffset = offset
    if (!defined(obj.index)) throw new Error("index is required")
    buf[offset++] = 10
    encodings.bytes.encode(obj.index, buf, offset)
    offset += encodings.bytes.encode.bytes
    if (!defined(obj.key)) throw new Error("key is required")
    buf[offset++] = 18
    encodings.bytes.encode(obj.key, buf, offset)
    offset += encodings.bytes.encode.bytes
    if (defined(obj.value)) {
      buf[offset++] = 26
      encodings.bytes.encode(obj.value, buf, offset)
      offset += encodings.bytes.encode.bytes
    }
    encode.bytes = offset - oldOffset
    return buf
  }

  function decode (buf, offset, end) {
    if (!offset) offset = 0
    if (!end) end = buf.length
    if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
    var oldOffset = offset
    var obj = {
      index: null,
      key: null,
      value: null
    }
    var found0 = false
    var found1 = false
    while (true) {
      if (end <= offset) {
        if (!found0 || !found1) throw new Error("Decoded message is not valid")
        decode.bytes = offset - oldOffset
        return obj
      }
      var prefix = varint.decode(buf, offset)
      offset += varint.decode.bytes
      var tag = prefix >> 3
      switch (tag) {
        case 1:
        obj.index = encodings.bytes.decode(buf, offset)
        offset += encodings.bytes.decode.bytes
        found0 = true
        break
        case 2:
        obj.key = encodings.bytes.decode(buf, offset)
        offset += encodings.bytes.decode.bytes
        found1 = true
        break
        case 3:
        obj.value = encodings.bytes.decode(buf, offset)
        offset += encodings.bytes.decode.bytes
        break
        default:
        offset = skip(prefix & 7, buf, offset)
      }
    }
  }
}

function defineExtension () {
  var Get = Extension.Get = {
    buffer: true,
    encodingLength: null,
    encode: null,
    decode: null
  }

  var Iterator = Extension.Iterator = {
    buffer: true,
    encodingLength: null,
    encode: null,
    decode: null
  }

  var Cache = Extension.Cache = {
    buffer: true,
    encodingLength: null,
    encode: null,
    decode: null
  }

  defineGet()
  defineIterator()
  defineCache()

  function defineGet () {
    Get.encodingLength = encodingLength
    Get.encode = encode
    Get.decode = decode

    function encodingLength (obj) {
      var length = 0
      if (defined(obj.version)) {
        var len = encodings.varint.encodingLength(obj.version)
        length += 1 + len
      }
      if (defined(obj.key)) {
        var len = encodings.bytes.encodingLength(obj.key)
        length += 1 + len
      }
      return length
    }

    function encode (obj, buf, offset) {
      if (!offset) offset = 0
      if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
      var oldOffset = offset
      if (defined(obj.version)) {
        buf[offset++] = 8
        encodings.varint.encode(obj.version, buf, offset)
        offset += encodings.varint.encode.bytes
      }
      if (defined(obj.key)) {
        buf[offset++] = 18
        encodings.bytes.encode(obj.key, buf, offset)
        offset += encodings.bytes.encode.bytes
      }
      encode.bytes = offset - oldOffset
      return buf
    }

    function decode (buf, offset, end) {
      if (!offset) offset = 0
      if (!end) end = buf.length
      if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
      var oldOffset = offset
      var obj = {
        version: 0,
        key: null
      }
      while (true) {
        if (end <= offset) {
          decode.bytes = offset - oldOffset
          return obj
        }
        var prefix = varint.decode(buf, offset)
        offset += varint.decode.bytes
        var tag = prefix >> 3
        switch (tag) {
          case 1:
          obj.version = encodings.varint.decode(buf, offset)
          offset += encodings.varint.decode.bytes
          break
          case 2:
          obj.key = encodings.bytes.decode(buf, offset)
          offset += encodings.bytes.decode.bytes
          break
          default:
          offset = skip(prefix & 7, buf, offset)
        }
      }
    }
  }

  function defineIterator () {
    Iterator.encodingLength = encodingLength
    Iterator.encode = encode
    Iterator.decode = decode

    function encodingLength (obj) {
      var length = 0
      if (defined(obj.version)) {
        var len = encodings.varint.encodingLength(obj.version)
        length += 1 + len
      }
      if (defined(obj.gte)) {
        var len = encodings.bytes.encodingLength(obj.gte)
        length += 1 + len
      }
      if (defined(obj.gt)) {
        var len = encodings.bytes.encodingLength(obj.gt)
        length += 1 + len
      }
      if (defined(obj.lte)) {
        var len = encodings.bytes.encodingLength(obj.lte)
        length += 1 + len
      }
      if (defined(obj.lt)) {
        var len = encodings.bytes.encodingLength(obj.lt)
        length += 1 + len
      }
      if (defined(obj.limit)) {
        var len = encodings.varint.encodingLength(obj.limit)
        length += 1 + len
      }
      if (defined(obj.reverse)) {
        var len = encodings.bool.encodingLength(obj.reverse)
        length += 1 + len
      }
      if (defined(obj.checkpoint)) {
        var packedLen = 0
        for (var i = 0; i < obj.checkpoint.length; i++) {
          if (!defined(obj.checkpoint[i])) continue
          var len = encodings.varint.encodingLength(obj.checkpoint[i])
          packedLen += len
        }
        if (packedLen) {
          length += 1 + packedLen + varint.encodingLength(packedLen)
        }
      }
      return length
    }

    function encode (obj, buf, offset) {
      if (!offset) offset = 0
      if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
      var oldOffset = offset
      if (defined(obj.version)) {
        buf[offset++] = 8
        encodings.varint.encode(obj.version, buf, offset)
        offset += encodings.varint.encode.bytes
      }
      if (defined(obj.gte)) {
        buf[offset++] = 18
        encodings.bytes.encode(obj.gte, buf, offset)
        offset += encodings.bytes.encode.bytes
      }
      if (defined(obj.gt)) {
        buf[offset++] = 26
        encodings.bytes.encode(obj.gt, buf, offset)
        offset += encodings.bytes.encode.bytes
      }
      if (defined(obj.lte)) {
        buf[offset++] = 34
        encodings.bytes.encode(obj.lte, buf, offset)
        offset += encodings.bytes.encode.bytes
      }
      if (defined(obj.lt)) {
        buf[offset++] = 42
        encodings.bytes.encode(obj.lt, buf, offset)
        offset += encodings.bytes.encode.bytes
      }
      if (defined(obj.limit)) {
        buf[offset++] = 48
        encodings.varint.encode(obj.limit, buf, offset)
        offset += encodings.varint.encode.bytes
      }
      if (defined(obj.reverse)) {
        buf[offset++] = 56
        encodings.bool.encode(obj.reverse, buf, offset)
        offset += encodings.bool.encode.bytes
      }
      if (defined(obj.checkpoint)) {
        var packedLen = 0
        for (var i = 0; i < obj.checkpoint.length; i++) {
          if (!defined(obj.checkpoint[i])) continue
          packedLen += encodings.varint.encodingLength(obj.checkpoint[i])
        }
        if (packedLen) {
          buf[offset++] = 66
          varint.encode(packedLen, buf, offset)
          offset += varint.encode.bytes
        }
        for (var i = 0; i < obj.checkpoint.length; i++) {
          if (!defined(obj.checkpoint[i])) continue
          encodings.varint.encode(obj.checkpoint[i], buf, offset)
          offset += encodings.varint.encode.bytes
        }
      }
      encode.bytes = offset - oldOffset
      return buf
    }

    function decode (buf, offset, end) {
      if (!offset) offset = 0
      if (!end) end = buf.length
      if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
      var oldOffset = offset
      var obj = {
        version: 0,
        gte: null,
        gt: null,
        lte: null,
        lt: null,
        limit: 0,
        reverse: false,
        checkpoint: []
      }
      while (true) {
        if (end <= offset) {
          decode.bytes = offset - oldOffset
          return obj
        }
        var prefix = varint.decode(buf, offset)
        offset += varint.decode.bytes
        var tag = prefix >> 3
        switch (tag) {
          case 1:
          obj.version = encodings.varint.decode(buf, offset)
          offset += encodings.varint.decode.bytes
          break
          case 2:
          obj.gte = encodings.bytes.decode(buf, offset)
          offset += encodings.bytes.decode.bytes
          break
          case 3:
          obj.gt = encodings.bytes.decode(buf, offset)
          offset += encodings.bytes.decode.bytes
          break
          case 4:
          obj.lte = encodings.bytes.decode(buf, offset)
          offset += encodings.bytes.decode.bytes
          break
          case 5:
          obj.lt = encodings.bytes.decode(buf, offset)
          offset += encodings.bytes.decode.bytes
          break
          case 6:
          obj.limit = encodings.varint.decode(buf, offset)
          offset += encodings.varint.decode.bytes
          break
          case 7:
          obj.reverse = encodings.bool.decode(buf, offset)
          offset += encodings.bool.decode.bytes
          break
          case 8:
          var packedEnd = varint.decode(buf, offset)
          offset += varint.decode.bytes
          packedEnd += offset
          while (offset < packedEnd) {
            obj.checkpoint.push(encodings.varint.decode(buf, offset))
            offset += encodings.varint.decode.bytes
          }
          break
          default:
          offset = skip(prefix & 7, buf, offset)
        }
      }
    }
  }

  function defineCache () {
    Cache.encodingLength = encodingLength
    Cache.encode = encode
    Cache.decode = decode

    function encodingLength (obj) {
      var length = 0
      if (!defined(obj.start)) throw new Error("start is required")
      var len = encodings.varint.encodingLength(obj.start)
      length += 1 + len
      if (!defined(obj.end)) throw new Error("end is required")
      var len = encodings.varint.encodingLength(obj.end)
      length += 1 + len
      if (defined(obj.blocks)) {
        var packedLen = 0
        for (var i = 0; i < obj.blocks.length; i++) {
          if (!defined(obj.blocks[i])) continue
          var len = encodings.varint.encodingLength(obj.blocks[i])
          packedLen += len
        }
        if (packedLen) {
          length += 1 + packedLen + varint.encodingLength(packedLen)
        }
      }
      return length
    }

    function encode (obj, buf, offset) {
      if (!offset) offset = 0
      if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
      var oldOffset = offset
      if (!defined(obj.start)) throw new Error("start is required")
      buf[offset++] = 8
      encodings.varint.encode(obj.start, buf, offset)
      offset += encodings.varint.encode.bytes
      if (!defined(obj.end)) throw new Error("end is required")
      buf[offset++] = 16
      encodings.varint.encode(obj.end, buf, offset)
      offset += encodings.varint.encode.bytes
      if (defined(obj.blocks)) {
        var packedLen = 0
        for (var i = 0; i < obj.blocks.length; i++) {
          if (!defined(obj.blocks[i])) continue
          packedLen += encodings.varint.encodingLength(obj.blocks[i])
        }
        if (packedLen) {
          buf[offset++] = 26
          varint.encode(packedLen, buf, offset)
          offset += varint.encode.bytes
        }
        for (var i = 0; i < obj.blocks.length; i++) {
          if (!defined(obj.blocks[i])) continue
          encodings.varint.encode(obj.blocks[i], buf, offset)
          offset += encodings.varint.encode.bytes
        }
      }
      encode.bytes = offset - oldOffset
      return buf
    }

    function decode (buf, offset, end) {
      if (!offset) offset = 0
      if (!end) end = buf.length
      if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
      var oldOffset = offset
      var obj = {
        start: 0,
        end: 0,
        blocks: []
      }
      var found0 = false
      var found1 = false
      while (true) {
        if (end <= offset) {
          if (!found0 || !found1) throw new Error("Decoded message is not valid")
          decode.bytes = offset - oldOffset
          return obj
        }
        var prefix = varint.decode(buf, offset)
        offset += varint.decode.bytes
        var tag = prefix >> 3
        switch (tag) {
          case 1:
          obj.start = encodings.varint.decode(buf, offset)
          offset += encodings.varint.decode.bytes
          found0 = true
          break
          case 2:
          obj.end = encodings.varint.decode(buf, offset)
          offset += encodings.varint.decode.bytes
          found1 = true
          break
          case 3:
          var packedEnd = varint.decode(buf, offset)
          offset += varint.decode.bytes
          packedEnd += offset
          while (offset < packedEnd) {
            obj.blocks.push(encodings.varint.decode(buf, offset))
            offset += encodings.varint.decode.bytes
          }
          break
          default:
          offset = skip(prefix & 7, buf, offset)
        }
      }
    }
  }

  Extension.encodingLength = encodingLength
  Extension.encode = encode
  Extension.decode = decode

  function encodingLength (obj) {
    var length = 0
    if (defined(obj.cache)) {
      var len = Cache.encodingLength(obj.cache)
      length += varint.encodingLength(len)
      length += 1 + len
    }
    if (defined(obj.get)) {
      var len = Get.encodingLength(obj.get)
      length += varint.encodingLength(len)
      length += 1 + len
    }
    if (defined(obj.iterator)) {
      var len = Iterator.encodingLength(obj.iterator)
      length += varint.encodingLength(len)
      length += 1 + len
    }
    return length
  }

  function encode (obj, buf, offset) {
    if (!offset) offset = 0
    if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
    var oldOffset = offset
    if (defined(obj.cache)) {
      buf[offset++] = 10
      varint.encode(Cache.encodingLength(obj.cache), buf, offset)
      offset += varint.encode.bytes
      Cache.encode(obj.cache, buf, offset)
      offset += Cache.encode.bytes
    }
    if (defined(obj.get)) {
      buf[offset++] = 18
      varint.encode(Get.encodingLength(obj.get), buf, offset)
      offset += varint.encode.bytes
      Get.encode(obj.get, buf, offset)
      offset += Get.encode.bytes
    }
    if (defined(obj.iterator)) {
      buf[offset++] = 26
      varint.encode(Iterator.encodingLength(obj.iterator), buf, offset)
      offset += varint.encode.bytes
      Iterator.encode(obj.iterator, buf, offset)
      offset += Iterator.encode.bytes
    }
    encode.bytes = offset - oldOffset
    return buf
  }

  function decode (buf, offset, end) {
    if (!offset) offset = 0
    if (!end) end = buf.length
    if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
    var oldOffset = offset
    var obj = {
      cache: null,
      get: null,
      iterator: null
    }
    while (true) {
      if (end <= offset) {
        decode.bytes = offset - oldOffset
        return obj
      }
      var prefix = varint.decode(buf, offset)
      offset += varint.decode.bytes
      var tag = prefix >> 3
      switch (tag) {
        case 1:
        var len = varint.decode(buf, offset)
        offset += varint.decode.bytes
        obj.cache = Cache.decode(buf, offset, offset + len)
        offset += Cache.decode.bytes
        break
        case 2:
        var len = varint.decode(buf, offset)
        offset += varint.decode.bytes
        obj.get = Get.decode(buf, offset, offset + len)
        offset += Get.decode.bytes
        break
        case 3:
        var len = varint.decode(buf, offset)
        offset += varint.decode.bytes
        obj.iterator = Iterator.decode(buf, offset, offset + len)
        offset += Iterator.decode.bytes
        break
        default:
        offset = skip(prefix & 7, buf, offset)
      }
    }
  }
}

function defined (val) {
  return val !== null && val !== undefined && (typeof val !== 'number' || !isNaN(val))
}
{
  "name": "hyperbee",
  "version": "2.27.3",
  "description": "An append-only B-tree running on a Hypercore.",
  "main": "index.js",
  "files": [
    "index.js",
    "lib/**.js",
    "iterators/**.js"
  ],
  "dependencies": {
    "b4a": "^1.6.0",
    "codecs": "^3.0.0",
    "debounceify": "^1.0.0",
    "hypercore-errors": "^1.0.0",
    "mutexify": "^1.4.0",
    "protocol-buffers-encodings": "^1.2.0",
    "rache": "^1.0.0",
    "ready-resource": "^1.0.0",
    "resolve-reject-promise": "^1.1.0",
    "safety-catch": "^1.0.2",
    "streamx": "^2.12.4",
    "unslab": "^1.2.0"
  },
  "devDependencies": {
    "bare-process": "^4.2.2",
    "brittle": "^3.1.0",
    "hypercore": "^11.0.0",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "protocol-buffers": "^4.2.0",
    "sub-encoder": "^1.0.6",
    "tree-to-string": "^1.1.1"
  },
  "imports": {
    "process": {
      "bare": "bare-process",
      "default": "process"
    }
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test/*.js",
    "test:bare": "brittle-bare test/*.js",
    "protobuf": "protocol-buffers schema.proto -o ./lib/messages.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/hyperbee.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/hyperbee/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperbee"
}
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const b4a = require('b4a')

// https://en.wikipedia.org/wiki/Merkle_tree#Second_preimage_attack
const LEAF_TYPE = b4a.from([0])
const PARENT_TYPE = b4a.from([1])
const ROOT_TYPE = b4a.from([2])

const HYPERCORE = b4a.from('hypercore')

exports.keyPair = function (seed) {
  // key pairs might stay around for a while, so better not to use a default slab to avoid retaining it completely
  const slab = b4a.allocUnsafeSlow(
    sodium.crypto_sign_PUBLICKEYBYTES + sodium.crypto_sign_SECRETKEYBYTES
  )
  const publicKey = slab.subarray(0, sodium.crypto_sign_PUBLICKEYBYTES)
  const secretKey = slab.subarray(sodium.crypto_sign_PUBLICKEYBYTES)

  if (seed) sodium.crypto_sign_seed_keypair(publicKey, secretKey, seed)
  else sodium.crypto_sign_keypair(publicKey, secretKey)

  return {
    publicKey,
    secretKey
  }
}

exports.validateKeyPair = function (keyPair) {
  const pk = b4a.allocUnsafe(sodium.crypto_sign_PUBLICKEYBYTES)
  sodium.crypto_sign_ed25519_sk_to_pk(pk, keyPair.secretKey)
  return b4a.equals(pk, keyPair.publicKey)
}

exports.sign = function (message, secretKey) {
  // Dedicated slab for the signature, to avoid retaining unneeded mem and for security
  const signature = b4a.allocUnsafeSlow(sodium.crypto_sign_BYTES)
  sodium.crypto_sign_detached(signature, message, secretKey)
  return signature
}

exports.verify = function (message, signature, publicKey) {
  if (signature.byteLength !== sodium.crypto_sign_BYTES) return false
  if (publicKey.byteLength !== sodium.crypto_sign_PUBLICKEYBYTES) return false
  return sodium.crypto_sign_verify_detached(signature, message, publicKey)
}

exports.encrypt = function (message, publicKey) {
  const ciphertext = b4a.alloc(message.byteLength + sodium.crypto_box_SEALBYTES)
  sodium.crypto_box_seal(ciphertext, message, publicKey)
  return ciphertext
}

exports.decrypt = function (ciphertext, keyPair) {
  if (ciphertext.byteLength < sodium.crypto_box_SEALBYTES) return null

  const plaintext = b4a.alloc(ciphertext.byteLength - sodium.crypto_box_SEALBYTES)

  if (!sodium.crypto_box_seal_open(plaintext, ciphertext, keyPair.publicKey, keyPair.secretKey)) {
    return null
  }

  return plaintext
}

exports.encryptionKeyPair = function (seed) {
  const publicKey = b4a.alloc(sodium.crypto_box_PUBLICKEYBYTES)
  const secretKey = b4a.alloc(sodium.crypto_box_SECRETKEYBYTES)

  if (seed) {
    sodium.crypto_box_seed_keypair(publicKey, secretKey, seed)
  } else {
    sodium.crypto_box_keypair(publicKey, secretKey)
  }

  return {
    publicKey,
    secretKey
  }
}

exports.data = function (data) {
  const out = b4a.allocUnsafe(32)

  sodium.crypto_generichash_batch(out, [LEAF_TYPE, c.encode(c.uint64, data.byteLength), data])

  return out
}

exports.parent = function (a, b) {
  if (a.index > b.index) {
    const tmp = a
    a = b
    b = tmp
  }

  const out = b4a.allocUnsafe(32)

  sodium.crypto_generichash_batch(out, [
    PARENT_TYPE,
    c.encode(c.uint64, a.size + b.size),
    a.hash,
    b.hash
  ])

  return out
}

exports.tree = function (roots, out) {
  const buffers = new Array(3 * roots.length + 1)
  let j = 0

  buffers[j++] = ROOT_TYPE

  for (let i = 0; i < roots.length; i++) {
    const r = roots[i]
    buffers[j++] = r.hash
    buffers[j++] = c.encode(c.uint64, r.index)
    buffers[j++] = c.encode(c.uint64, r.size)
  }

  if (!out) out = b4a.allocUnsafe(32)
  sodium.crypto_generichash_batch(out, buffers)
  return out
}

exports.hash = function (data, out) {
  if (!out) out = b4a.allocUnsafe(32)
  if (!Array.isArray(data)) data = [data]

  sodium.crypto_generichash_batch(out, data)

  return out
}

exports.randomBytes = function (n) {
  const buf = b4a.allocUnsafe(n)
  sodium.randombytes_buf(buf)
  return buf
}

exports.discoveryKey = function (key) {
  if (!key || key.byteLength !== 32) throw new Error('Must pass a 32 byte buffer')
  // Discovery keys might stay around for a while, so better not to use slab memory (for better gc)
  const digest = b4a.allocUnsafeSlow(32)
  sodium.crypto_generichash(digest, HYPERCORE, key)
  return digest
}

if (sodium.sodium_free) {
  exports.free = function (secureBuf) {
    if (secureBuf.secure) sodium.sodium_free(secureBuf)
  }
} else {
  exports.free = function () {}
}

exports.namespace = function (name, count) {
  const ids = typeof count === 'number' ? range(count) : count

  // Namespaces are long-lived, so better to use a dedicated slab
  const buf = b4a.allocUnsafeSlow(32 * ids.length)

  const list = new Array(ids.length)

  // ns is ephemeral, so default slab
  const ns = b4a.allocUnsafe(33)
  sodium.crypto_generichash(ns.subarray(0, 32), typeof name === 'string' ? b4a.from(name) : name)

  for (let i = 0; i < list.length; i++) {
    list[i] = buf.subarray(32 * i, 32 * i + 32)
    ns[32] = ids[i]
    sodium.crypto_generichash(list[i], ns)
  }

  return list
}

function range(count) {
  const arr = new Array(count)
  for (let i = 0; i < count; i++) arr[i] = i
  return arr
}
{
  "name": "hypercore-crypto",
  "version": "3.7.0",
  "description": "The crypto primitives used in hypercore, extracted into a separate module",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.6.6",
    "compact-encoding": "^3.0.0",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "brittle": "^3.5.0",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/hypercore-crypto.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/hypercore-crypto/issues"
  },
  "homepage": "https://github.com/mafintosh/hypercore-crypto"
}
const IdEnc = require('hypercore-id-encoding')

module.exports = class HypercoreError extends Error {
  constructor (msg, code, fn = HypercoreError, discoveryKey = null) {
    if (discoveryKey) msg = `${msg} (discovery key: ${IdEnc.normalize(discoveryKey)})`
    super(`${code}: ${msg}`)

    this.code = code
    this.discoveryKey = discoveryKey

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name () {
    return 'HypercoreError'
  }

  static ASSERTION (msg, discoveryKey = null) { // ERR_ASSERTION is picked up by safety-catch also
    return new HypercoreError(msg, 'ERR_ASSERTION', HypercoreError.ASSERT, discoveryKey)
  }

  static BAD_ARGUMENT (msg, discoveryKey = null) {
    return new HypercoreError(msg, 'BAD_ARGUMENT', HypercoreError.BAD_ARGUMENT, discoveryKey)
  }

  static STORAGE_EMPTY (msg, discoveryKey = null) {
    return new HypercoreError(msg, 'STORAGE_EMPTY', HypercoreError.STORAGE_EMPTY, discoveryKey)
  }

  static STORAGE_CONFLICT (msg, discoveryKey = null) {
    return new HypercoreError(msg, 'STORAGE_CONFLICT', HypercoreError.STORAGE_CONFLICT, discoveryKey)
  }

  static INVALID_SIGNATURE (msg, discoveryKey = null) {
    return new HypercoreError(msg, 'INVALID_SIGNATURE', HypercoreError.INVALID_SIGNATURE, discoveryKey)
  }

  static INVALID_CAPABILITY (msg, discoveryKey = null) {
    return new HypercoreError(msg, 'INVALID_CAPABILITY', HypercoreError.INVALID_CAPABILITY, discoveryKey)
  }

  static INVALID_CHECKSUM (msg = 'Invalid checksum', discoveryKey = null) {
    return new HypercoreError(msg, 'INVALID_CHECKSUM', HypercoreError.INVALID_CHECKSUM, discoveryKey)
  }

  static INVALID_OPERATION (msg, discoveryKey = null) {
    return new HypercoreError(msg, 'INVALID_OPERATION', HypercoreError.INVALID_OPERATION, discoveryKey)
  }

  static INVALID_PROOF (msg = 'Proof not verifiable', discoveryKey = null) {
    return new HypercoreError(msg, 'INVALID_PROOF', HypercoreError.INVALID_PROOF, discoveryKey)
  }

  static BLOCK_NOT_AVAILABLE (msg = 'Block is not available', discoveryKey = null) {
    return new HypercoreError(msg, 'BLOCK_NOT_AVAILABLE', HypercoreError.BLOCK_NOT_AVAILABLE, discoveryKey)
  }

  static SNAPSHOT_NOT_AVAILABLE (msg = 'Snapshot is not available', discoveryKey = null) {
    return new HypercoreError(msg, 'SNAPSHOT_NOT_AVAILABLE', HypercoreError.SNAPSHOT_NOT_AVAILABLE, discoveryKey)
  }

  static REQUEST_CANCELLED (msg = 'Request was cancelled', discoveryKey = null) {
    return new HypercoreError(msg, 'REQUEST_CANCELLED', HypercoreError.REQUEST_CANCELLED, discoveryKey)
  }

  static REQUEST_TIMEOUT (msg = 'Request timed out', discoveryKey = null) {
    return new HypercoreError(msg, 'REQUEST_TIMEOUT', HypercoreError.REQUEST_TIMEOUT, discoveryKey)
  }

  static SESSION_NOT_WRITABLE (msg = 'Session is not writable', discoveryKey = null) {
    return new HypercoreError(msg, 'SESSION_NOT_WRITABLE', HypercoreError.SESSION_NOT_WRITABLE, discoveryKey)
  }

  static SESSION_CLOSED (msg = 'Session is closed', discoveryKey = null) {
    return new HypercoreError(msg, 'SESSION_CLOSED', HypercoreError.SESSION_CLOSED, discoveryKey)
  }

  static BATCH_UNFLUSHED (msg = 'Batch not yet flushed', discoveryKey = null) {
    return new HypercoreError(msg, 'BATCH_UNFLUSHED', HypercoreError.BATCH_UNFLUSHED, discoveryKey)
  }

  static BATCH_ALREADY_EXISTS (msg = 'Batch already exists', discoveryKey = null) {
    return new HypercoreError(msg, 'BATCH_ALREADY_EXISTS', HypercoreError.BATCH_ALREADY_EXISTS, discoveryKey)
  }

  static BATCH_ALREADY_FLUSHED (msg = 'Batch has already been flushed', discoveryKey = null) {
    return new HypercoreError(msg, 'BATCH_ALREADY_FLUSHED', HypercoreError.BATCH_ALREADY_FLUSHED, discoveryKey)
  }

  static OPLOG_CORRUPT (msg = 'Oplog file appears corrupt or out of date', discoveryKey = null) {
    return new HypercoreError(msg, 'OPLOG_CORRUPT', HypercoreError.OPLOG_CORRUPT, discoveryKey)
  }

  static OPLOG_HEADER_OVERFLOW (msg = 'Oplog header exceeds page size', discoveryKey = null) {
    return new HypercoreError(msg, 'OPLOG_HEADER_OVERFLOW', HypercoreError.OPLOG_HEADER_OVERFLOW, discoveryKey)
  }

  static INVALID_OPLOG_VERSION (msg = 'Invalid header version', discoveryKey = null) {
    return new HypercoreError(msg, 'INVALID_OPLOG_VERSION', HypercoreError.INVALID_OPLOG_VERSION, discoveryKey)
  }

  static WRITE_FAILED (msg = 'Write to storage failed', discoveryKey = null) {
    return new HypercoreError(msg, 'WRITE_FAILED', HypercoreError.WRITE_FAILED, discoveryKey)
  }

  static DECODING_ERROR (msg = 'Decoding error', discoveryKey = null) {
    return new HypercoreError(msg, 'DECODING_ERROR', HypercoreError.DECODING_ERROR, discoveryKey)
  }

  static SESSION_MOVED (msg = 'Session moved', discoveryKey = null) {
    return new HypercoreError(msg, 'SESSION_MOVED', HypercoreError.SESSION_MOVED, discoveryKey)
  }
}
{
  "name": "hypercore-errors",
  "version": "1.5.0",
  "description": "Hypercore errors",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/hypercore-errors.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/hypercore-errors/issues"
  },
  "homepage": "https://github.com/holepunchto/hypercore-errors#readme",
  "devDependencies": {
    "b4a": "^1.6.7",
    "brittle": "^3.1.3",
    "standard": "^17.0.0"
  },
  "dependencies": {
    "hypercore-id-encoding": "^1.3.0"
  }
}
const z32 = require('z32')
const b4a = require('b4a')

module.exports = {
  encode,
  decode,
  normalize,
  isValid
}

function encode (key) {
  if (!b4a.isBuffer(key)) throw new Error('Key must be a Buffer')
  if (key.byteLength !== 32) throw new Error('Key must be 32-bytes long')
  return z32.encode(key)
}

function decode (id) {
  if (b4a.isBuffer(id)) {
    if (id.byteLength !== 32) throw new Error('ID must be 32-bytes long')
    return id
  }
  if (typeof id === 'string') {
    if (id.startsWith('pear://')) id = id.slice(7).split('/')[0]
    if (id.length === 52) return z32.decode(id)
    if (id.length === 64) {
      const buf = b4a.from(id, 'hex')
      if (buf.byteLength === 32) return buf
    }
  }
  throw new Error('Invalid Hypercore key')
}

function normalize (any) {
  return encode(decode(any))
}

function isValid (any) {
  try {
    decode(any)
    return true
  } catch {
    return false
  }
}
{
  "name": "hypercore-id-encoding",
  "version": "1.3.0",
  "description": "Convert Hypercore keys to/from z-base32 or hex",
  "main": "index.js",
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.5.3",
    "z32": "^1.0.0"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "hypercore": "^10.0.0",
    "random-access-memory": "^6.0.0",
    "standard": "^17.1.0"
  },
  "license": "Apache-2.0",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/hypercore-id-encoding.git"
  },
  "keywords": [],
  "author": "",
  "bugs": {
    "url": "https://github.com/holepunchto/hypercore-id-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/hypercore-id-encoding#readme"
}
function headLegacyMap(m) {
  return {
    version: 2, // version bumped from 1
    cores: m.allocated.cores,
    datas: m.allocated.datas,
    groups: 0,
    seed: m.seed,
    defaultDiscoveryKey: m.defaultDiscoveryKey
  }
}

module.exports = {
  headLegacyMap
}
// This file is autogenerated by the hyperschema compiler
// Schema Version: 2
/* eslint-disable camelcase */
/* eslint-disable quotes */
/* eslint-disable space-before-function-paren */

const { c } = require('hyperschema/runtime')
const external0 = require('../../external.js')

const VERSION = 2

// eslint-disable-next-line no-unused-vars
let version = VERSION

// @corestore/allocated
const encoding0 = {
  preencode(state, m) {
    c.uint.preencode(state, m.cores)
    c.uint.preencode(state, m.datas)
  },
  encode(state, m) {
    c.uint.encode(state, m.cores)
    c.uint.encode(state, m.datas)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const r1 = c.uint.decode(state)

    return {
      cores: r0,
      datas: r1
    }
  }
}

// @corestore/head-v1
const encoding1 = {
  preencode(state, m) {
    state.end++ // max flag is 4 so always one byte

    if (m.allocated) encoding0.preencode(state, m.allocated)
    if (m.seed) c.fixed32.preencode(state, m.seed)
    if (m.defaultDiscoveryKey) c.fixed32.preencode(state, m.defaultDiscoveryKey)
  },
  encode(state, m) {
    const flags = (m.allocated ? 1 : 0) | (m.seed ? 2 : 0) | (m.defaultDiscoveryKey ? 4 : 0)

    c.uint.encode(state, flags)

    if (m.allocated) encoding0.encode(state, m.allocated)
    if (m.seed) c.fixed32.encode(state, m.seed)
    if (m.defaultDiscoveryKey) c.fixed32.encode(state, m.defaultDiscoveryKey)
  },
  decode(state) {
    const v = c.uint.decode(state)
    const flags = c.uint.decode(state)

    return {
      version: v,
      allocated: (flags & 1) !== 0 ? encoding0.decode(state) : null,
      seed: (flags & 2) !== 0 ? c.fixed32.decode(state) : null,
      defaultDiscoveryKey: (flags & 4) !== 0 ? c.fixed32.decode(state) : null
    }
  }
}

// @corestore/head-v2
const encoding2 = {
  preencode(state, m) {
    c.uint.preencode(state, m.cores)
    c.uint.preencode(state, m.datas)
    c.uint.preencode(state, m.groups)
    state.end++ // max flag is 2 so always one byte

    if (m.seed) c.fixed32.preencode(state, m.seed)
    if (m.defaultDiscoveryKey) c.fixed32.preencode(state, m.defaultDiscoveryKey)
  },
  encode(state, m) {
    const flags = (m.seed ? 1 : 0) | (m.defaultDiscoveryKey ? 2 : 0)

    c.uint.encode(state, m.cores)
    c.uint.encode(state, m.datas)
    c.uint.encode(state, m.groups)
    c.uint.encode(state, flags)

    if (m.seed) c.fixed32.encode(state, m.seed)
    if (m.defaultDiscoveryKey) c.fixed32.encode(state, m.defaultDiscoveryKey)
  },
  decode(state) {
    const v = c.uint.decode(state)
    const r0 = c.uint.decode(state)
    const r1 = c.uint.decode(state)
    const r2 = c.uint.decode(state)
    const flags = c.uint.decode(state)

    return {
      version: v,
      cores: r0,
      datas: r1,
      groups: r2,
      seed: (flags & 1) !== 0 ? c.fixed32.decode(state) : null,
      defaultDiscoveryKey: (flags & 2) !== 0 ? c.fixed32.decode(state) : null
    }
  }
}

// @corestore/head
const encoding3 = {
  preencode(state, m) {
    c.uint.preencode(state, m.version)
    switch (m.version) {
      case 0:
      case 1:
        encoding1.preencode(state, m)
        break
      case 2:
        encoding2.preencode(state, m)
        break
      default:
        throw new Error('Unsupported version')
    }
  },
  encode(state, m) {
    c.uint.encode(state, m.version)
    switch (m.version) {
      case 0:
      case 1:
        encoding1.encode(state, m)
        break
      case 2:
        encoding2.encode(state, m)
        break
      default:
        throw new Error('Unsupported version')
    }
  },
  decode(state) {
    const start = state.start
    const v = c.uint.decode(state)
    state.start = start
    switch (v) {
      case 0:
      case 1: {
        const decoded = encoding1.decode(state)
        const map = external0.headLegacyMap
        return map(decoded)
      }
      case 2: {
        const decoded = encoding2.decode(state)
        return decoded
      }
      default:
        throw new Error('Unsupported version')
    }
  }
}

// @corestore/alias
const encoding4 = {
  preencode(state, m) {
    c.string.preencode(state, m.name)
    c.fixed32.preencode(state, m.namespace)
  },
  encode(state, m) {
    c.string.encode(state, m.name)
    c.fixed32.encode(state, m.namespace)
  },
  decode(state) {
    const r0 = c.string.decode(state)
    const r1 = c.fixed32.decode(state)

    return {
      name: r0,
      namespace: r1
    }
  }
}

// @corestore/core
const encoding5 = {
  preencode(state, m) {
    c.uint.preencode(state, m.version)
    c.uint.preencode(state, m.corePointer)
    c.uint.preencode(state, m.dataPointer)
    state.end++ // max flag is 1 so always one byte

    if (m.alias) encoding4.preencode(state, m.alias)
  },
  encode(state, m) {
    const flags = m.alias ? 1 : 0

    c.uint.encode(state, m.version)
    c.uint.encode(state, m.corePointer)
    c.uint.encode(state, m.dataPointer)
    c.uint.encode(state, flags)

    if (m.alias) encoding4.encode(state, m.alias)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const r1 = c.uint.decode(state)
    const r2 = c.uint.decode(state)
    const flags = c.uint.decode(state)

    return {
      version: r0,
      corePointer: r1,
      dataPointer: r2,
      alias: (flags & 1) !== 0 ? encoding4.decode(state) : null
    }
  }
}

const encoding6_enum = {
  blake2b: 'blake2b'
}

// @core/hashes enum
const encoding6 = {
  preencode(state, m) {
    state.end++ // max enum is 0 so always one byte
  },
  encode(state, m) {
    switch (m) {
      case 'blake2b':
        c.uint.encode(state, 0)
        break
      default:
        throw new Error('Unknown enum')
    }
  },
  decode(state) {
    switch (c.uint.decode(state)) {
      case 0:
        return 'blake2b'
      default:
        return null
    }
  }
}

const encoding7_enum = {
  ed25519: 'ed25519'
}

// @core/signatures enum
const encoding7 = {
  preencode(state, m) {
    state.end++ // max enum is 0 so always one byte
  },
  encode(state, m) {
    switch (m) {
      case 'ed25519':
        c.uint.encode(state, 0)
        break
      default:
        throw new Error('Unknown enum')
    }
  },
  decode(state) {
    switch (c.uint.decode(state)) {
      case 0:
        return 'ed25519'
      default:
        return null
    }
  }
}

// @core/tree-node
const encoding8 = {
  preencode(state, m) {
    c.uint.preencode(state, m.index)
    c.uint.preencode(state, m.size)
    c.fixed32.preencode(state, m.hash)
  },
  encode(state, m) {
    c.uint.encode(state, m.index)
    c.uint.encode(state, m.size)
    c.fixed32.encode(state, m.hash)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const r1 = c.uint.decode(state)
    const r2 = c.fixed32.decode(state)

    return {
      index: r0,
      size: r1,
      hash: r2
    }
  }
}

// @core/signer
const encoding9 = {
  preencode(state, m) {
    encoding7.preencode(state, m.signature)
    c.fixed32.preencode(state, m.namespace)
    c.fixed32.preencode(state, m.publicKey)
  },
  encode(state, m) {
    encoding7.encode(state, m.signature)
    c.fixed32.encode(state, m.namespace)
    c.fixed32.encode(state, m.publicKey)
  },
  decode(state) {
    const r0 = encoding7.decode(state)
    const r1 = c.fixed32.decode(state)
    const r2 = c.fixed32.decode(state)

    return {
      signature: r0,
      namespace: r1,
      publicKey: r2
    }
  }
}

// @core/prologue
const encoding10 = {
  preencode(state, m) {
    c.fixed32.preencode(state, m.hash)
    c.uint.preencode(state, m.length)
  },
  encode(state, m) {
    c.fixed32.encode(state, m.hash)
    c.uint.encode(state, m.length)
  },
  decode(state) {
    const r0 = c.fixed32.decode(state)
    const r1 = c.uint.decode(state)

    return {
      hash: r0,
      length: r1
    }
  }
}

// @core/manifest.signers
const encoding11_4 = c.array(encoding9)
// @core/manifest.linked
const encoding11_6 = c.array(c.fixed32)

// @core/manifest
const encoding11 = {
  preencode(state, m) {
    c.uint.preencode(state, m.version)
    state.end++ // max flag is 8 so always one byte
    encoding6.preencode(state, m.hash)
    c.uint.preencode(state, m.quorum)
    encoding11_4.preencode(state, m.signers)

    if (m.prologue) encoding10.preencode(state, m.prologue)
    if (m.linked) encoding11_6.preencode(state, m.linked)
    if (m.userData) c.buffer.preencode(state, m.userData)
  },
  encode(state, m) {
    const flags =
      (m.allowPatch ? 1 : 0) | (m.prologue ? 2 : 0) | (m.linked ? 4 : 0) | (m.userData ? 8 : 0)

    c.uint.encode(state, m.version)
    c.uint.encode(state, flags)
    encoding6.encode(state, m.hash)
    c.uint.encode(state, m.quorum)
    encoding11_4.encode(state, m.signers)

    if (m.prologue) encoding10.encode(state, m.prologue)
    if (m.linked) encoding11_6.encode(state, m.linked)
    if (m.userData) c.buffer.encode(state, m.userData)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const flags = c.uint.decode(state)

    return {
      version: r0,
      hash: encoding6.decode(state),
      quorum: c.uint.decode(state),
      allowPatch: (flags & 1) !== 0,
      signers: encoding11_4.decode(state),
      prologue: (flags & 2) !== 0 ? encoding10.decode(state) : null,
      linked: (flags & 4) !== 0 ? encoding11_6.decode(state) : null,
      userData: (flags & 8) !== 0 ? c.buffer.decode(state) : null
    }
  }
}

// @core/keyPair
const encoding12 = {
  preencode(state, m) {
    c.buffer.preencode(state, m.publicKey)
    c.optionalBuffer.preencode(state, m.secretKey)
  },
  encode(state, m) {
    c.buffer.encode(state, m.publicKey)
    c.optionalBuffer.encode(state, m.secretKey)
  },
  decode(state) {
    const r0 = c.buffer.decode(state)
    const r1 = c.optionalBuffer.decode(state)

    return {
      publicKey: r0,
      secretKey: r1
    }
  }
}

// @core/group
const encoding13 = {
  preencode(state, m) {
    state.end++ // max flag is 2 so always one byte

    if (m.key) c.fixed32.preencode(state, m.key)
    if (m.pointer) c.uint.preencode(state, m.pointer)
  },
  encode(state, m) {
    const flags = (m.key ? 1 : 0) | (m.pointer ? 2 : 0)

    c.uint.encode(state, flags)

    if (m.key) c.fixed32.encode(state, m.key)
    if (m.pointer) c.uint.encode(state, m.pointer)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      key: (flags & 1) !== 0 ? c.fixed32.decode(state) : null,
      pointer: (flags & 2) !== 0 ? c.uint.decode(state) : 0
    }
  }
}

// @core/auth.manifest
const encoding14_2 = c.frame(encoding11)

// @core/auth
const encoding14 = {
  preencode(state, m) {
    c.fixed32.preencode(state, m.key)
    c.fixed32.preencode(state, m.discoveryKey)
    state.end++ // max flag is 4 so always one byte

    if (m.manifest) encoding14_2.preencode(state, m.manifest)
    if (m.keyPair) encoding12.preencode(state, m.keyPair)
    if (m.encryptionKey) c.buffer.preencode(state, m.encryptionKey)
  },
  encode(state, m) {
    const flags = (m.manifest ? 1 : 0) | (m.keyPair ? 2 : 0) | (m.encryptionKey ? 4 : 0)

    c.fixed32.encode(state, m.key)
    c.fixed32.encode(state, m.discoveryKey)
    c.uint.encode(state, flags)

    if (m.manifest) encoding14_2.encode(state, m.manifest)
    if (m.keyPair) encoding12.encode(state, m.keyPair)
    if (m.encryptionKey) c.buffer.encode(state, m.encryptionKey)
  },
  decode(state) {
    const r0 = c.fixed32.decode(state)
    const r1 = c.fixed32.decode(state)
    const flags = c.uint.decode(state)

    return {
      key: r0,
      discoveryKey: r1,
      manifest: (flags & 1) !== 0 ? encoding14_2.decode(state) : null,
      keyPair: (flags & 2) !== 0 ? encoding12.decode(state) : null,
      encryptionKey: (flags & 4) !== 0 ? c.buffer.decode(state) : null
    }
  }
}

// @core/head
const encoding15 = {
  preencode(state, m) {
    c.uint.preencode(state, m.fork)
    c.uint.preencode(state, m.length)
    c.fixed32.preencode(state, m.rootHash)
    c.optionalBuffer.preencode(state, m.signature)
    state.end++ // max flag is 1 so always one byte

    if (version >= 2 && m.timestamp) c.uint64.preencode(state, m.timestamp)
  },
  encode(state, m) {
    const flags = version >= 2 && m.timestamp ? 1 : 0

    c.uint.encode(state, m.fork)
    c.uint.encode(state, m.length)
    c.fixed32.encode(state, m.rootHash)
    c.optionalBuffer.encode(state, m.signature)
    c.uint.encode(state, flags)

    if (version >= 2 && m.timestamp) c.uint64.encode(state, m.timestamp)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const r1 = c.uint.decode(state)
    const r2 = c.fixed32.decode(state)
    const r3 = c.optionalBuffer.decode(state)
    const flags = state.start < state.end ? c.uint.decode(state) : 0

    return {
      fork: r0,
      length: r1,
      rootHash: r2,
      signature: r3,
      timestamp: version >= 2 && (flags & 1) !== 0 ? c.uint64.decode(state) : 0
    }
  }
}

// @core/hints
const encoding16 = {
  preencode(state, m) {
    state.end++ // max flag is 4 so always one byte

    if (m.contiguousLength) c.uint.preencode(state, m.contiguousLength)
    if (m.remoteContiguousLength) c.uint.preencode(state, m.remoteContiguousLength)
    if (m.recovering) c.uint.preencode(state, m.recovering)
  },
  encode(state, m) {
    const flags =
      (m.contiguousLength ? 1 : 0) | (m.remoteContiguousLength ? 2 : 0) | (m.recovering ? 4 : 0)

    c.uint.encode(state, flags)

    if (m.contiguousLength) c.uint.encode(state, m.contiguousLength)
    if (m.remoteContiguousLength) c.uint.encode(state, m.remoteContiguousLength)
    if (m.recovering) c.uint.encode(state, m.recovering)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      contiguousLength: (flags & 1) !== 0 ? c.uint.decode(state) : 0,
      remoteContiguousLength: (flags & 2) !== 0 ? c.uint.decode(state) : 0,
      recovering: (flags & 4) !== 0 ? c.uint.decode(state) : 0
    }
  }
}

// @core/session
const encoding17 = {
  preencode(state, m) {
    c.string.preencode(state, m.name)
    c.uint.preencode(state, m.dataPointer)
  },
  encode(state, m) {
    c.string.encode(state, m.name)
    c.uint.encode(state, m.dataPointer)
  },
  decode(state) {
    const r0 = c.string.decode(state)
    const r1 = c.uint.decode(state)

    return {
      name: r0,
      dataPointer: r1
    }
  }
}

// @core/sessions
const encoding18 = c.array(encoding17)

// @core/dependency
const encoding19 = {
  preencode(state, m) {
    c.uint.preencode(state, m.dataPointer)
    c.uint.preencode(state, m.length)
  },
  encode(state, m) {
    c.uint.encode(state, m.dataPointer)
    c.uint.encode(state, m.length)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const r1 = c.uint.decode(state)

    return {
      dataPointer: r0,
      length: r1
    }
  }
}

function setVersion(v) {
  version = v
}

function encode(name, value, v = VERSION) {
  version = v
  return c.encode(getEncoding(name), value)
}

function decode(name, buffer, v = VERSION) {
  version = v
  return c.decode(getEncoding(name), buffer)
}

function getEnum(name) {
  switch (name) {
    case '@core/hashes':
      return encoding6_enum
    case '@core/signatures':
      return encoding7_enum
    default:
      throw new Error('Enum not found ' + name)
  }
}

function getEncoding(name) {
  switch (name) {
    case '@corestore/allocated':
      return encoding0
    case '@corestore/head-v1':
      return encoding1
    case '@corestore/head-v2':
      return encoding2
    case '@corestore/head':
      return encoding3
    case '@corestore/alias':
      return encoding4
    case '@corestore/core':
      return encoding5
    case '@core/hashes':
      return encoding6
    case '@core/signatures':
      return encoding7
    case '@core/tree-node':
      return encoding8
    case '@core/signer':
      return encoding9
    case '@core/prologue':
      return encoding10
    case '@core/manifest':
      return encoding11
    case '@core/keyPair':
      return encoding12
    case '@core/group':
      return encoding13
    case '@core/auth':
      return encoding14
    case '@core/head':
      return encoding15
    case '@core/hints':
      return encoding16
    case '@core/session':
      return encoding17
    case '@core/sessions':
      return encoding18
    case '@core/dependency':
      return encoding19
    default:
      throw new Error('Encoder not found ' + name)
  }
}

function getStruct(name, v = VERSION) {
  const enc = getEncoding(name)
  return {
    preencode(state, m) {
      version = v
      enc.preencode(state, m)
    },
    encode(state, m) {
      version = v
      enc.encode(state, m)
    },
    decode(state) {
      version = v
      return enc.decode(state)
    }
  }
}

const resolveStruct = getStruct // compat

module.exports = {
  resolveStruct,
  getStruct,
  getEnum,
  getEncoding,
  encode,
  decode,
  setVersion,
  version
}
const RocksDB = require('rocksdb-native')
const rrp = require('resolve-reject-promise')
const ScopeLock = require('scope-lock')
const DeviceFile = require('device-file')
const path = require('path')
const fs = require('fs')
const Xache = require('xache')

const View = require('./lib/view.js')

const VERSION = 2
const COLUMN_FAMILY = 'corestore'

const { store, core } = require('./lib/keys.js')

const { CorestoreRX, CorestoreTX, CoreTX, CoreRX } = require('./lib/tx.js')

const {
  createCoreStream,
  createAliasStream,
  createDiscoveryKeyStream,
  createBlockStream,
  createBitfieldStream,
  createUserDataStream,
  createTreeNodeStream,
  createMarkStream,
  createLocalStream,
  createGroupUpdateStream
} = require('./lib/streams.js')

const EMPTY = new View()

class Atom {
  constructor(db) {
    this.db = db
    this.view = new View()
    this.flushedPromise = null
    this.flushing = false
    this.preflushes = []
    this.flushes = []
  }

  preflush(fn) {
    this.preflushes.push(fn)
  }

  onflush(fn) {
    this.flushes.push(fn)
  }

  flushed() {
    if (!this.flushing) return Promise.resolve()
    if (this.flushedPromise !== null) return this.flushedPromise.promise
    this.flushedPromise = rrp()
    return this.flushedPromise.promise
  }

  _resolve() {
    const f = this.flushedPromise
    this.flushedPromise = null
    f.resolve()
  }

  async flush() {
    if (this.flushing) throw new Error('Atom already flushing')
    this.flushing = true

    try {
      const plen = this.preflushes.length
      for (let i = 0; i < plen; i++) this.preflushes[i]()

      await View.flush(this.view.changes, this.db)

      const promises = []
      const len = this.flushes.length // in case of reentry
      for (let i = 0; i < len; i++) promises.push(this.flushes[i]())

      await Promise.all(promises)
    } finally {
      this.view.reset()
      this.flushing = false
      if (this.flushedPromise !== null) this._resolve()
    }
  }
}

class HypercoreStorage {
  constructor(store, db, treeCache, core, view, atom) {
    this.store = store
    this.db = db
    this.core = core
    this.view = view
    this.atom = atom

    this.view.readStart()
    this.treeCache = treeCache
  }

  get readOnly() {
    return this.store.readOnly
  }

  get dependencies() {
    return this.core.dependencies
  }

  getDependencyLength() {
    return this.core.dependencies.length
      ? this.core.dependencies[this.core.dependencies.length - 1].length
      : -1
  }

  getDependency(length) {
    for (let i = this.core.dependencies.length - 1; i >= 0; i--) {
      const dep = this.core.dependencies[i]
      if (dep.length < length) return dep
    }

    return null
  }

  setDependencyHead(dep) {
    if (dep === null) {
      this.core.dependencies = []
      return
    }

    const deps = this.core.dependencies

    for (let i = deps.length - 1; i >= 0; i--) {
      const d = deps[i]

      if (d.dataPointer !== dep.dataPointer) continue

      // check if nothing changed
      if (d.length === dep.length && i === deps.length - 1) return

      this.core = {
        corePointer: this.core.corePointer,
        dataPointer: this.core.dataPointer,
        dependencies: deps.slice(0, i + 1)
      }

      this.core.dependencies[i] = {
        dataPointer: dep.dataPointer,
        length: dep.length
      }
      return // updated head so done
    }

    this.core.dependencies = [
      {
        dataPointer: dep.dataPointer,
        length: dep.length
      }
    ]
  }

  // TODO: this might have to be async if the dependents have changed, but prop ok for now
  updateDependencyLength(length, truncated) {
    const deps = this.core.dependencies

    const i = this.findDependencyIndex(length, truncated)
    if (i === -1) throw new Error('Dependency not found')

    this.core = {
      corePointer: this.core.corePointer,
      dataPointer: this.core.dataPointer,
      dependencies: deps.slice(0, i + 1)
    }

    if (this.core.dependencies[i].length !== length) {
      this.core.dependencies[i] = {
        dataPointer: deps[i].dataPointer,
        length
      }
    }
  }

  findDependencyIndex(length, truncated) {
    const deps = this.core.dependencies

    if (truncated) {
      for (let i = 0; i < deps.length; i++) {
        if (deps[i].length >= length) return i
      }

      return -1
    }

    for (let i = deps.length - 1; i >= 0; i--) {
      if (deps[i].length <= length) return i
    }

    return -1
  }

  get snapshotted() {
    return this.db._snapshot !== null
  }

  snapshot() {
    return new HypercoreStorage(
      this.store,
      this.db.snapshot(),
      this.treeCache,
      this.core,
      this.view.snapshot(),
      this.atom
    )
  }

  compact() {
    return Promise.all([
      this.db.compactRange(core.core(this.core.corePointer), core.core(this.core.corePointer)),
      this.db.compactRange(core.data(this.core.dataPointer), core.data(this.core.dataPointer))
    ])
  }

  atomize(atom) {
    if (this.atom && this.atom !== atom) {
      throw new Error('Cannot atomize and atomized session with a new atom')
    }

    return new HypercoreStorage(
      this.store,
      this.db.session(),
      this.treeCache,
      this.core,
      atom.view,
      atom
    )
  }

  createAtom() {
    return this.store.createAtom()
  }

  createBlockStream(opts) {
    return createBlockStream(this.core, this.db, this.view, opts)
  }

  createTreeNodeStream(opts) {
    return createTreeNodeStream(this.core, this.db, this.view, opts)
  }

  createBitfieldStream(opts) {
    return createBitfieldStream(this.core, this.db, this.view, opts)
  }

  createUserDataStream(opts) {
    return createUserDataStream(this.core, this.db, this.view, opts)
  }

  createMarkStream(opts) {
    return createMarkStream(this.core, this.db, this.view, opts)
  }

  createLocalStream(opts) {
    return createLocalStream(this.core, this.db, this.view, opts)
  }

  async resumeSession(name) {
    const rx = this.read()
    const existingSessionsPromise = rx.getSessions()

    rx.tryFlush()
    const existingSessions = await existingSessionsPromise

    const sessions = existingSessions || []
    const session = getSession(sessions, name, false)

    if (session === null) return null

    const core = {
      corePointer: this.core.corePointer,
      dataPointer: session.dataPointer,
      dependencies: []
    }

    const coreRx = new CoreRX(core, this.db, this.view, this.treeCache, this.store.stats, -1)

    const dependencyPromise = coreRx.getDependency()
    coreRx.tryFlush()

    const dependency = await dependencyPromise
    if (dependency) core.dependencies = this._addDependency(dependency)

    return new HypercoreStorage(
      this.store,
      this.db.session(),
      this.treeCache,
      core,
      this.atom ? this.view : new View(),
      this.atom
    )
  }

  async createSession(name, head) {
    const rx = this.read()

    const existingSessionsPromise = rx.getSessions()
    const existingHeadPromise = rx.getHead()

    rx.tryFlush()

    const [existingSessions, existingHead] = await Promise.all([
      existingSessionsPromise,
      existingHeadPromise
    ])
    if (head === null) head = existingHead

    if (existingHead !== null && head.length > existingHead.length) {
      throw new Error('Invalid head passed, ahead of core')
    }

    const sessions = existingSessions || []
    const session = getSession(sessions, name, true)
    const fresh = session.dataPointer === -1

    if (fresh) {
      session.dataPointer = await this.store._allocData()
    }

    const tx = this.write()

    tx.setSessions(sessions)

    const length = head === null ? 0 : head.length
    const core = {
      corePointer: this.core.corePointer,
      dataPointer: session.dataPointer,
      dependencies: this._addDependency({
        dataPointer: this.core.dataPointer,
        length
      })
    }

    const coreTx = new CoreTX(core, this.db, tx.view, tx.changes)

    if (length > 0) coreTx.setHead(head)
    coreTx.setDependency(core.dependencies[core.dependencies.length - 1])

    if (!fresh) {
      // nuke all existing state...
      coreTx.deleteBlockRange(0, -1)
      coreTx.deleteTreeNodeRange(0, -1)
      coreTx.deleteBitfieldPageRange(0, -1)
    }

    await tx.flush()

    return new HypercoreStorage(
      this.store,
      this.db.session(),
      this.treeCache,
      core,
      this.atom ? this.view : new View(),
      this.atom
    )
  }

  async createAtomicSession(atom, head) {
    const length = head === null ? 0 : head.length
    const core = {
      corePointer: this.core.corePointer,
      dataPointer: this.core.dataPointer,
      dependencies: this._addDependency(null)
    }

    const coreTx = new CoreTX(core, this.db, atom.view, [])

    if (length > 0) coreTx.setHead(head)

    await coreTx.flush()

    return this.atomize(atom)
  }

  _addDependency(dep) {
    const deps = []

    for (let i = 0; i < this.core.dependencies.length; i++) {
      const d = this.core.dependencies[i]

      if (dep !== null && d.length > dep.length) {
        if (d.dataPointer !== dep.dataPointer) {
          deps.push({ dataPointer: d.dataPointer, length: dep.length })
        }
        return deps
      }

      deps.push(d)
    }

    if (
      dep !== null &&
      (deps.length === 0 || deps[deps.length - 1].dataPointer !== dep.dataPointer)
    ) {
      deps.push(dep)
    }
    return deps
  }

  async deleteSessions() {
    const rx = this.read()
    const existingSessionsPromise = rx.getSessions()
    rx.tryFlush()

    const existingSessions = await existingSessionsPromise

    // Remove batches
    const coreTx = this.write()
    coreTx.setSessions([]) // Clear sessions record
    await coreTx.flush()

    const tx = this.db.write({ autoDestroy: true })

    for (const { dataPointer } of existingSessions) {
      const start = core.data(dataPointer)
      const end = core.data(dataPointer + 1)
      tx.tryDeleteRange(start, end)
    }

    await tx.flush()
  }

  read(fork = -1) {
    let treeCache = null
    if (!this.atom) treeCache = this.treeCache

    return new CoreRX(this.core, this.db, this.view, treeCache, this.store.stats, fork)
  }

  write() {
    return new CoreTX(this.core, this.db, this.atom ? this.view : null, [])
  }

  close() {
    if (this.view !== null) {
      this.view.readStop()
      this.view = null
    }

    return this.db.close()
  }

  static async export(ptr, db, { batches = false } = {}) {
    const rx = new CoreRX(ptr, db, EMPTY, null, null, -1)

    const core = {
      head: null,
      auth: null,
      sessions: [],
      data: null
    }

    const sessionsPromise = rx.getSessions()
    const headPromise = rx.getHead()
    const authPromise = rx.getAuth()

    rx.tryFlush()

    const [sessions, head, auth] = await Promise.all([sessionsPromise, headPromise, authPromise])

    core.head = head
    core.auth = { ...auth, keyPair: null }
    if (sessions) core.sessions = sessions.map((s) => s.name)

    const data = []

    data.push(exportData(ptr, db))

    if (batches) {
      for (const { dataPointer } of sessions) {
        data.push(exportData({ dataPointer, dependencies: [] }, db))
      }
    }

    core.data = await Promise.all(data)

    return core
  }

  static isParentStorage(storage, parent) {
    const last = getLastDependency(storage)
    return !!last && last.dataPointer === parent.core.dataPointer
  }
}

class CorestoreStorage {
  constructor(db, opts = {}) {
    const storage = typeof db === 'string' ? db : null

    this.bootstrap = storage !== null
    this.path = storage !== null ? storage : path.join(db.path, '..')
    this.alwaysRecover = !!opts.alwaysRecover
    this.readOnly = !!opts.readOnly
    this.allowBackup = !!opts.allowBackup
    this.deviceFile = null
    this.wait = !!opts.wait

    // tmp sync fix for simplicty since not super deployed yet
    if (this.bootstrap && !this.readOnly) tmpFixStorage(this.path)

    this.id = opts.id || null
    this.view = null
    this.enters = 0
    this.lock = new ScopeLock()
    this.flushing = null
    this.version = 0
    this.migrating = null

    if ((this.bootstrap && !this.readOnly && !this.allowBackup) || this.wait) {
      const corestoreFile = path.join(this.path, 'CORESTORE')

      this.deviceFile = new DeviceFile(corestoreFile, {
        lock: true,
        wait: this.wait,
        data: { id: this.id }
      })
    }

    const dbPath = path.join(this.path, 'db')

    this.stats = {
      treeCache: {
        hits: 0,
        misses: 0,
        parallel: 0,
        skips: 0
      }
    }
    this.rocks = storage === null ? db : new RocksDB(dbPath, { ...opts, lock: this.deviceFile })
    this.db = createColumnFamily(this.rocks, opts)

    const { treeCache = { maxSize: 8192 } } = opts
    this.treeCache = new Xache(treeCache)
  }

  get opened() {
    return this.db.opened
  }

  get closed() {
    return this.db.closed
  }

  async ready() {
    if (this.version === 0) await this._migrateStore()
    return this.db.ready()
  }

  compact(opts) {
    return this.db.compactRange(opts)
  }

  async audit() {
    for await (const { core } of this.createCoreStream()) {
      const coreRx = new CoreRX(core, this.db, EMPTY, this.treeCache, this.stats, -1)
      const authPromise = coreRx.getAuth()

      coreRx.tryFlush()

      const auth = await authPromise

      if (!auth.manifest || auth.manifest.version > 0) continue
      if (auth.manifest.linked === null) continue

      auth.manifest.linked = null
      const coreTx = new CoreTX(core, this.db, null, [])
      coreTx.setAuth(auth)
      await coreTx.flush()
    }
  }

  async deleteCore(ptr) {
    const rx = new CoreRX(ptr, this.db, EMPTY, this.treeCache, this.stats, -1)

    const authPromise = rx.getAuth()
    const sessionsPromise = rx.getSessions()

    rx.tryFlush()

    const auth = await authPromise
    const sessions = await sessionsPromise

    // no core stored here
    if (!auth) return

    const tx = this.db.write({ autoDestroy: true })

    tx.tryDelete(store.core(auth.discoveryKey))

    // clear core
    const start = core.core(ptr.corePointer)
    const end = core.core(ptr.corePointer + 1)
    tx.tryDeleteRange(start, end)

    if (sessions) {
      for (const { dataPointer } of sessions) {
        const start = core.data(dataPointer)
        const end = core.data(dataPointer + 1)
        tx.tryDeleteRange(start, end)
      }
    }

    return tx.flush()
  }

  static isCoreStorage(db) {
    return isCorestoreStorage(db)
  }

  static from(db) {
    if (isCorestoreStorage(db)) return db
    return new this(db)
  }

  async _flush() {
    while (this.enters > 0) {
      await this.lock.lock()
      await this.lock.unlock()
    }
  }

  async _maybeRecover(view) {
    const r = path.join(this.db.path, 'RECOVERING')
    if (!(await fileExists(r))) return
    await this.setRecovering(view)
    await fs.promises.unlink(r)
  }

  _maybeRecoverLater(err) {
    if (!shouldRecover(err) && !this.alwaysRecover) return
    fs.writeFileSync(path.join(this.db.path, 'RECOVERING'), '')
    for (const file of fs.readdirSync(this.db.path)) {
      if (file.endsWith('.log')) fs.unlinkSync(path.join(this.db.path, file))
    }
  }

  // runs pre any other mutation and read
  async _migrateStore() {
    const view = await this._enter()

    try {
      if (this.version === VERSION) return

      await this._preopen

      try {
        await this.db.ready()
      } catch (err) {
        this._maybeRecoverLater(err)
        throw err
      }

      await this._maybeRecover(view)

      const rx = new CorestoreRX(this.db, view)
      const headPromise = rx.getHead()

      rx.tryFlush()
      const head = await headPromise

      const version = head === null ? 0 : head.version
      if (version === VERSION) {
        this.version = VERSION
        return
      }

      const target = { version: VERSION, dryRun: false }

      switch (version) {
        case 0: {
          await require('./migrations/0').store(this, target)
          break
        }
        case 1: {
          // implicit migration on write
          break
        }
        default: {
          throw new Error(
            'Unsupported version: ' + version + ' - you should probably upgrade your dependencies'
          )
        }
      }

      this.version = VERSION
    } finally {
      await this._exit()
    }
  }

  // runs pre the core is returned to the user
  async _migrateCore(core, discoveryKey, version, locked) {
    const view = locked ? this.view : await this._enter()
    try {
      if (version === VERSION) return

      const target = { version: VERSION, dryRun: false }

      switch (version) {
        case 0: {
          await require('./migrations/0').core(core, target)
          break
        }
        case 1: {
          await require('./migrations/1').core(core, target)
          break
        }
        default: {
          throw new Error(
            'Unsupported version: ' + version + ' - you should probably upgrade your dependencies'
          )
        }
      }

      if (locked === false) return

      // if its locked, then move the core state into the memview
      // in case the core is reopened from the memview, pre flush

      const rx = new CorestoreRX(this.db, EMPTY)
      const tx = new CorestoreTX(view)

      const corePromise = rx.getCore(discoveryKey)
      rx.tryFlush()

      tx.putCore(discoveryKey, await corePromise)
      tx.apply()
    } finally {
      if (!locked) await this._exit()
    }
  }

  async _enter() {
    this.enters++
    await this.lock.lock()
    if (this.view === null) this.view = new View()
    return this.view
  }

  async _exit() {
    this.enters--

    if (this.flushing === null) this.flushing = rrp()
    const flushed = this.flushing.promise

    if (this.enters === 0 || this.view.size() > 128) {
      try {
        await View.flush(this.view.changes, this.db)
        this.flushing.resolve()
      } catch (err) {
        this.flushing.reject(err)
      } finally {
        this.flushing = null
        this.view = null
      }
    }

    this.lock.unlock()
    return flushed
  }

  // when used with core catches this isnt transactional for simplicity, HOWEVER, its just a number
  // so worth the tradeoff
  async _allocData() {
    let dataPointer = 0

    const view = await this._enter()
    const tx = new CorestoreTX(view)

    try {
      const head = await this._getHead(view)

      dataPointer = head.datas++

      tx.setHead(head)
      tx.apply()
    } finally {
      await this._exit()
    }

    return dataPointer
  }

  // exposes here so migrations can easily access the head in an init state
  async _getHead(view) {
    const rx = new CorestoreRX(this.db, view)
    const headPromise = rx.getHead()
    rx.tryFlush()

    const head = await headPromise
    return head === null ? initStoreHead() : head
  }

  createAtom() {
    return new Atom(this.db)
  }

  async flush() {
    await this.rocks.flush()
  }

  async close() {
    if (this.db.closed) return
    await this._flush()
    await this.db.close()
    await this.rocks.close()
    this.treeCache.destroy()
    if (this.deviceFile) await this.deviceFile.close()
  }

  async clear() {
    if (this.version === 0) await this._migrateStore()

    const view = await this._enter()
    const tx = new CorestoreTX(view)

    tx.clear()
    tx.apply()

    await this._exit()
  }

  createCoreStream() {
    // TODO: be nice to run the mgiration here also, but too much plumbing atm
    return createCoreStream(this.db, EMPTY)
  }

  createAliasStream(namespace) {
    // TODO: be nice to run the mgiration here also, but too much plumbing atm
    return createAliasStream(this.db, EMPTY, namespace)
  }

  createDiscoveryKeyStream(namespace) {
    return createDiscoveryKeyStream(this.db, EMPTY, namespace)
  }

  createGroupUpdateStream(group, { since, reverse } = {}) {
    return createGroupUpdateStream(this.db, EMPTY, group, { gte: since, reverse })
  }

  async getAlias(alias) {
    if (this.version === 0) await this._migrateStore()

    const rx = new CorestoreRX(this.db, EMPTY)
    const discoveryKeyPromise = rx.getCoreByAlias(alias)
    rx.tryFlush()
    return discoveryKeyPromise
  }

  async getSeed() {
    if (this.version === 0) await this._migrateStore()

    const rx = new CorestoreRX(this.db, EMPTY)
    const headPromise = rx.getHead()

    rx.tryFlush()

    const head = await headPromise
    return head === null ? null : head.seed
  }

  async getGroup(topic) {
    if (this.version === 0) await this._migrateStore()

    const rx = new CorestoreRX(this.db, EMPTY)
    const groupPromise = rx.getGroup(topic)
    rx.tryFlush()
    return groupPromise
  }

  async setSeed(seed, { overwrite = true } = {}) {
    if (this.version === 0) await this._migrateStore()

    const view = await this._enter()
    const tx = new CorestoreTX(view)

    try {
      const rx = new CorestoreRX(this.db, view)
      const headPromise = rx.getHead()

      rx.tryFlush()

      const head = (await headPromise) || initStoreHead()

      if (head.seed === null || overwrite) head.seed = seed
      tx.setHead(head)
      tx.apply()

      return head.seed
    } finally {
      await this._exit()
    }
  }

  async setRecovering(view = null) {
    const recovering = Date.now()
    let keys = []

    for await (const data of this.createDiscoveryKeyStream()) {
      keys.push(data)
      if (keys.length > 16 * 1024) {
        await this._flushRecovering(recovering, view, keys)
        keys = []
      }
    }

    if (keys.length) await this._flushRecovering(recovering, view, keys)
  }

  async _flushRecovering(recovering, view, keys) {
    const own = !view
    if (own) view = await this._enter()
    const tx = new CorestoreTX(view)

    try {
      const infos = await this._getInfos(keys, { auth: false, head: false, hints: true })
      for (const inf of infos) {
        tx.setCoreHints(inf.core, { ...inf.hints, recovering })
      }
      tx.apply()
    } finally {
      if (own) await this._exit()
    }
  }

  async getDefaultDiscoveryKey() {
    if (this.version === 0) await this._migrateStore()

    const rx = new CorestoreRX(this.db, EMPTY)
    const headPromise = rx.getHead()

    rx.tryFlush()

    const head = await headPromise
    return head === null ? null : head.defaultDiscoveryKey
  }

  async setDefaultDiscoveryKey(discoveryKey, { overwrite = true } = {}) {
    if (this.version === 0) await this._migrateStore()

    const view = await this._enter()
    const tx = new CorestoreTX(view)

    try {
      const rx = new CorestoreRX(this.db, view)
      const headPromise = rx.getHead()

      rx.tryFlush()

      const head = (await headPromise) || initStoreHead()

      if (head.defaultDiscoveryKey === null || overwrite) head.defaultDiscoveryKey = discoveryKey
      tx.setHead(head)
      tx.apply()

      return head.defaultDiscoveryKey
    } finally {
      await this._exit()
    }
  }

  async hasCore(discoveryKey, { ifMigrated = false } = {}) {
    if (this.version === 0) await this._migrateStore()

    const rx = new CorestoreRX(this.db, EMPTY)
    const promise = rx.getCore(discoveryKey)

    rx.tryFlush()

    const core = await promise

    if (core === null) return false
    if (core.version === 0 && ifMigrated) return false

    return true
  }

  async getAuth(discoveryKey) {
    if (this.version === 0) await this._migrateStore()

    const rx = new CorestoreRX(this.db, EMPTY)
    const corePromise = rx.getCore(discoveryKey)

    rx.tryFlush()

    const core = await corePromise
    if (core === null) return null

    const read = this.db.read({ autoDestroy: true })
    const authPromise = CoreRX.getAuth(read, core)

    read.tryFlush()

    return authPromise
  }

  async getInfo(discoveryKey, opts) {
    return (await this.getInfos([discoveryKey], opts))[0]
  }

  async getInfos(discoveryKeys, opts) {
    if (this.version === 0) await this._migrateStore()
    return this._getInfos(discoveryKeys, opts)
  }

  async _getInfos(discoveryKeys, { auth = true, head = true, hints = true } = {}) {
    const rx = new CorestoreRX(this.db, EMPTY)
    const corePromises = new Array(discoveryKeys.length)

    for (let i = 0; i < discoveryKeys.length; i++) {
      corePromises[i] = rx.getCore(discoveryKeys[i])
    }

    rx.tryFlush()

    const cores = await Promise.all(corePromises)
    const read = this.db.read({ autoDestroy: true })

    const resultPromises = new Array(cores.length)

    for (let i = 0; i < cores.length; i++) {
      resultPromises[i] = cores[i]
        ? getInfoFromBatch(read, cores[i], discoveryKeys[i], auth, head, hints)
        : null
    }

    read.tryFlush()

    return Promise.all(resultPromises)
  }

  async suspend({ log = noop } = {}) {
    await log('Suspending hypercore storage...')
    await this.db.suspend()
    await log('db suspended')
    if (this.deviceFile) {
      await log('suspend deviceFile')
      await this.deviceFile.suspend()
      await log('deviceFile suspended')
    }
  }

  async resume() {
    if (this.deviceFile) await this.deviceFile.resume()
    await this.db.resume()
  }

  async resumeCore(discoveryKey) {
    if (this.version === 0) await this._migrateStore()

    if (!discoveryKey) {
      discoveryKey = await this.getDefaultDiscoveryKey()
      if (!discoveryKey) return null
    }

    const rx = new CorestoreRX(this.db, EMPTY)
    const corePromise = rx.getCore(discoveryKey)

    rx.tryFlush()
    const core = await corePromise

    if (core === null) return null
    return this._resumeFromPointers(EMPTY, discoveryKey, false, core)
  }

  async export(discoveryKey, opts) {
    const rx = new CorestoreRX(this.db, EMPTY)
    const corePromise = rx.getCore(discoveryKey)

    rx.tryFlush()
    const core = await corePromise
    if (core === null) return null

    let { dataPointer, corePointer } = core

    const ptr = { corePointer, dataPointer, dependencies: [] }

    while (true) {
      const rx = new CoreRX(
        { dataPointer, corePointer: 0, dependencies: [] },
        this.db,
        EMPTY,
        this.treeCache,
        this.stats,
        -1
      )
      const dependencyPromise = rx.getDependency()
      rx.tryFlush()
      const dependency = await dependencyPromise
      if (!dependency) break
      ptr.dependencies.push(dependency)
      dataPointer = dependency.dataPointer
    }

    const session = this.db.session()
    try {
      return await HypercoreStorage.export(ptr, session, opts)
    } finally {
      await session.close()
    }
  }

  async _resumeFromPointers(view, discoveryKey, create, { version, corePointer, dataPointer }) {
    const core = { corePointer, dataPointer, dependencies: [] }

    while (true) {
      const rx = new CoreRX(
        { dataPointer, corePointer: 0, dependencies: [] },
        this.db,
        view,
        this.treeCache,
        this.stats,
        -1
      )
      const dependencyPromise = rx.getDependency()
      rx.tryFlush()
      const dependency = await dependencyPromise
      if (!dependency) break
      core.dependencies.push(dependency)
      dataPointer = dependency.dataPointer
    }

    const result = new HypercoreStorage(this, this.db.session(), this.treeCache, core, EMPTY, null)

    if (version < VERSION) await this._migrateCore(result, discoveryKey, version, create)
    return result
  }

  // not allowed to throw validation errors as its a shared tx!
  async _create(
    view,
    { key, manifest, keyPair, encryptionKey, discoveryKey, alias, userData, core: ptrs }
  ) {
    const rx = new CorestoreRX(this.db, view)
    const tx = new CorestoreTX(view)

    const corePromise = rx.getCore(discoveryKey)
    const headPromise = rx.getHead()

    rx.tryFlush()

    let [core, head] = await Promise.all([corePromise, headPromise])
    if (core) return this._resumeFromPointers(view, discoveryKey, true, core)

    if (head === null) head = initStoreHead()
    if (head.defaultDiscoveryKey === null) head.defaultDiscoveryKey = discoveryKey

    const corePointer = ptrs ? ptrs.corePointer : head.cores++
    const dataPointer = ptrs ? ptrs.dataPointer : head.datas++

    core = { version: VERSION, corePointer, dataPointer, alias }

    tx.setHead(head)
    tx.putCore(discoveryKey, core)
    if (alias) tx.putCoreByAlias(alias, discoveryKey)

    const ptr = { corePointer, dataPointer, dependencies: [] }
    const ctx = new CoreTX(ptr, this.db, view, tx.changes)

    ctx.setAuth({
      key,
      discoveryKey,
      manifest,
      keyPair,
      encryptionKey
    })

    if (userData) {
      for (const { key, value } of userData) {
        ctx.putUserData(key, value)
      }
    }

    tx.apply()

    return new HypercoreStorage(this, this.db.session(), this.treeCache, ptr, EMPTY, null)
  }

  async createCore(data) {
    if (this.version === 0) await this._migrateStore()

    const view = await this._enter()

    try {
      return await this._create(view, data)
    } finally {
      await this._exit()
    }
  }

  // not allowed to throw validation errors as its a shared tx!
  async _createGroup(view, topic) {
    const rx = new CorestoreRX(this.db, view)
    const tx = new CorestoreTX(view)

    const groupPromise = rx.getGroup(topic)
    const headPromise = rx.getHead()

    rx.tryFlush()

    let group = await groupPromise
    if (group !== null) {
      return {
        key: topic,
        pointer: group
      }
    }

    let head = await headPromise
    if (head === null) head = initStoreHead()

    group = head.groups++

    tx.putGroup(topic, group)
    tx.setHead(head)
    tx.apply()

    return {
      key: topic,
      pointer: group
    }
  }

  async createGroup(topic) {
    if (this.version === 0) await this._migrateStore()

    const view = await this._enter()

    try {
      return await this._createGroup(view, topic)
    } finally {
      await this._exit()
    }
  }

  static isParentStorage(storage, parent) {
    return HypercoreStorage.isParentStorage(storage, parent)
  }
}

module.exports = CorestoreStorage

function initStoreHead() {
  return {
    version: 0, // cause we wanna run the migration
    datas: 0,
    cores: 0,
    groups: 0,
    seed: null,
    defaultDiscoveryKey: null
  }
}

function getSession(sessions, name, alloc) {
  for (let i = 0; i < sessions.length; i++) {
    if (sessions[i].name === name) return sessions[i]
  }

  if (!alloc) return null

  const result = { name, dataPointer: -1 }
  sessions.push(result)
  return result
}

function isCorestoreStorage(s) {
  return typeof s === 'object' && !!s && typeof s.setDefaultDiscoveryKey === 'function'
}

function createColumnFamily(db, opts = {}) {
  const {
    tableCacheIndexAndFilterBlocks = true,
    blockCache = true,
    optimizeFiltersForMemory = false,
    blobFileSize = 256 * 1024 * 1024,
    blobGarbageCollectionAgeCutOff = 0.25,
    blobGarbageCollectionForceThreshold = 1.0
  } = opts

  const col = new RocksDB.ColumnFamily(COLUMN_FAMILY, {
    enableBlobFiles: true,
    minBlobSize: 4096,
    blobFileSize,
    enableBlobGarbageCollection: true,
    tableBlockSize: 8192,
    tableCacheIndexAndFilterBlocks,
    tableFormatVersion: 6,
    optimizeFiltersForMemory,
    blockCache,
    blobGarbageCollectionAgeCutOff,
    blobGarbageCollectionForceThreshold
  })

  return db.columnFamily(col)
}

function getLastDependency(storage) {
  return storage.dependencies.length ? storage.dependencies[storage.dependencies.length - 1] : null
}

// TODO: remove in like 3-6 mo
function tmpFixStorage(p) {
  // if CORESTORE file is written, new format
  if (fs.existsSync(path.join(p, 'CORESTORE'))) return

  let files = []

  try {
    files = fs.readdirSync(p)
  } catch {}

  const notRocks = new Set([
    'CORESTORE',
    'primary-key',
    'cores',
    'app-preferences',
    'cache',
    'preferences.json',
    'db',
    'clone',
    'core',
    'notifications'
  ])

  for (const f of files) {
    if (notRocks.has(f)) continue

    try {
      fs.mkdirSync(path.join(p, 'db'))
    } catch {}

    fs.renameSync(path.join(p, f), path.join(p, 'db', f))
  }
}

async function exportData(ptr, db, opts) {
  // just need dataPointer
  const reads = [
    toArray(createBlockStream(ptr, db, EMPTY, opts)),
    toArray(createTreeNodeStream(ptr, db, EMPTY, opts)),
    toArray(createBitfieldStream(ptr, db, EMPTY, opts))
  ]

  const [blocks, tree, bitfield] = await Promise.all(reads)

  return {
    blocks,
    tree,
    bitfield
  }
}

async function toArray(stream) {
  const all = []
  for await (const e of stream) all.push(e)
  return all
}

async function fileExists(path) {
  try {
    await fs.promises.stat(path)
    return true
  } catch {
    return false
  }
}

function shouldRecover(err) {
  return err.message.toLowerCase().indexOf('sequence number is being set backwards') > -1
}

function noop() {}

async function getInfoFromBatch(db, c, discoveryKey, getAuth, getHead, getHints) {
  const authPromise = getAuth ? CoreRX.getAuth(db, c) : null
  const headPromise = getHead ? CoreRX.getHead(db, c) : null
  const hintsPromise = getHints ? CoreRX.getHints(db, c) : null

  // ensure no uncaughts
  if (authPromise) authPromise.catch(noop)
  if (headPromise) headPromise.catch(noop)
  if (hintsPromise) hintsPromise.catch(noop)

  return {
    discoveryKey,
    core: c,
    auth: await authPromise,
    head: await headPromise,
    hints: await hintsPromise
  }
}
const { Readable, getStreamError } = require('streamx')
const { core } = require('./keys')

module.exports = class BlockStream extends Readable {
  constructor(core, db, updates, start, end, reverse) {
    super()

    this.core = core
    this.db = db
    this.updates = updates
    this.start = start
    this.end = end
    this.reverse = reverse === true

    this._drained = true
    this._consumed = 0
    this._stream = null
    this._oncloseBound = this._onclose.bind(this)
    this._maybeDrainBound = this._maybeDrain.bind(this)

    this._update()
  }

  _update() {
    if (this._consumed > this.core.dependencies.length) return

    const deps = this.core.dependencies
    const index = this._findDependencyIndex(deps)

    const curr = index < deps.length ? deps[index] : null
    const prev = index > 0 && index - 1 < deps.length ? deps[index - 1] : null

    const start = prev && prev.length > this.start ? prev.length : this.start
    const end = curr && (this.end === -1 || curr.length < this.end) ? curr.length : this.end

    const ptr = curr ? curr.dataPointer : this.core.dataPointer

    this._makeStream(core.block(ptr, start), core.block(ptr, end))
  }

  _findDependencyIndex(deps) {
    if (!this.reverse) return this._consumed++

    let i = deps.length - this._consumed++
    while (i > 0) {
      if (deps[i - 1].length <= this.end) return i
      i--
      this._consumed++
    }

    return 0
  }

  _predestroy() {
    if (this._stream !== null) this._stream.destroy()
  }

  _read(cb) {
    this._drained = this._onreadable()
    cb(null)
  }

  _maybeDrain() {
    if (this._drained === true) return
    this._drained = this._onreadable()
  }

  _onreadable() {
    if (this._stream === null) {
      this.push(null)
      return true
    }

    let data = this._stream.read()

    if (data === null) return false

    do {
      this.push(data)
      data = this._stream.read()
    } while (data !== null)

    return true
  }

  _onclose() {
    if (this.destroying) return

    const err = getStreamError(this._stream)

    if (err !== null) {
      this.destroy(err)
      return
    }

    // empty the current stream
    if (this._onreadable() === true) this._drained = true

    this._stream = null

    this._update()
    this._maybeDrain()
  }

  _makeStream(start, end) {
    this._stream = this.updates.iterator(this.db, start, end, this.reverse)
    this._stream.on('readable', this._maybeDrainBound)
    this._stream.on('error', noop)
    this._stream.on('close', this._oncloseBound)
  }
}

function noop() {}
const { Readable } = require('streamx')

// used for returned a stream that just errors (during read during teardown)

module.exports = class CloseErrorStream extends Readable {
  constructor(err) {
    super()
    this.error = err
  }

  _open(cb) {
    cb(this.error)
  }
}
const { UINT, STRING } = require('index-encoder')
const c = require('compact-encoding')
const b4a = require('b4a')

const TL_HEAD = 0
const TL_CORE_BY_DKEY = 1
const TL_CORE_BY_ALIAS = 2
const TL_CORE = 3
const TL_DATA = 4
const TL_GROUP_BY_TOPIC = 5
const TL_GROUP = 6

const TL_END = TL_GROUP + 1

const CORE_AUTH = 0
const CORE_SESSIONS = 1
const CORE_GROUP = 2

const DATA_HEAD = 0
const DATA_DEPENDENCY = 1
const DATA_HINTS = 2
const DATA_BLOCK = 3
const DATA_TREE = 4
const DATA_BITFIELD = 5
const DATA_USER_DATA = 6
const DATA_LOCAL = 7
const DATA_MARK = 8

const slab = { buffer: b4a.allocUnsafe(65536), start: 0, end: 0 }

const store = {}
const core = {}
const group = {}

store.clear = function () {
  const state = alloc()
  let start = state.start
  UINT.encode(state, 0)
  const a = state.buffer.subarray(start, state.start)
  start = state.start
  UINT.encode(state, TL_END)
  const b = state.buffer.subarray(start, state.start)
  return [a, b]
}

store.head = function () {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_HEAD)
  return state.buffer.subarray(start, state.start)
}

store.core = function (discoveryKey) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE_BY_DKEY)
  c.fixed32.encode(state, discoveryKey)
  return state.buffer.subarray(start, state.start)
}

store.coreStart = function () {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE_BY_DKEY)
  return state.buffer.subarray(start, state.start)
}

store.coreEnd = function () {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE_BY_DKEY + 1)
  return state.buffer.subarray(start, state.start)
}

store.coreByAlias = function ({ namespace, name }) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE_BY_ALIAS)
  c.fixed32.encode(state, namespace)
  STRING.encode(state, name)
  return state.buffer.subarray(start, state.start)
}

store.coreByAliasStart = function (namespace) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE_BY_ALIAS)
  if (namespace) c.fixed32.encode(state, namespace)
  return state.buffer.subarray(start, state.start)
}

store.coreByAliasEnd = function (namespace) {
  const state = alloc()
  const start = state.start

  if (namespace) {
    UINT.encode(state, TL_CORE_BY_ALIAS)
    c.fixed32.encode(state, namespace)
    state.buffer[state.start++] = 0xff
  } else {
    UINT.encode(state, TL_CORE_BY_ALIAS + 1)
  }

  return state.buffer.subarray(start, state.start)
}

store.alias = function (buffer) {
  const state = { buffer, start: 0, end: buffer.byteLength }
  UINT.decode(state) // ns
  const namespace = c.fixed32.decode(state)
  const name = STRING.decode(state)
  return { namespace, name }
}

store.discoveryKey = function (buffer) {
  const state = { buffer, start: 0, end: buffer.byteLength }
  UINT.decode(state) // ns
  return c.fixed32.decode(state)
}

core.core = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE)
  UINT.encode(state, ptr)
  return state.buffer.subarray(start, state.start)
}

core.data = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  return state.buffer.subarray(start, state.start)
}

core.auth = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE)
  UINT.encode(state, ptr)
  UINT.encode(state, CORE_AUTH)
  return state.buffer.subarray(start, state.start)
}

core.group = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE)
  UINT.encode(state, ptr)
  UINT.encode(state, CORE_GROUP)
  return state.buffer.subarray(start, state.start)
}

core.sessions = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE)
  UINT.encode(state, ptr)
  UINT.encode(state, CORE_SESSIONS)
  return state.buffer.subarray(start, state.start)
}

core.head = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_HEAD)
  return state.buffer.subarray(start, state.start)
}

core.dependency = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_DEPENDENCY)
  return state.buffer.subarray(start, state.start)
}

core.hints = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_HINTS)
  return state.buffer.subarray(start, state.start)
}

core.block = function (ptr, index) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_BLOCK)
  UINT.encode(state, index)
  return state.buffer.subarray(start, state.start)
}

core.tree = function (ptr, index) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_TREE)
  UINT.encode(state, index)
  return state.buffer.subarray(start, state.start)
}

core.bitfield = function (ptr, index, type) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_BITFIELD)
  UINT.encode(state, index)
  UINT.encode(state, type)
  return state.buffer.subarray(start, state.start)
}

core.userData = function (ptr, key) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_USER_DATA)
  STRING.encode(state, key)
  return state.buffer.subarray(start, state.start)
}

core.userDataEnd = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_USER_DATA + 1)
  return state.buffer.subarray(start, state.start)
}

core.mark = function (ptr, index) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_MARK)
  UINT.encode(state, index)
  return state.buffer.subarray(start, state.start)
}

core.local = function (ptr, key) {
  if (key.byteLength > 2048) {
    throw new Error('local keys has an upper limit of 2048 bytes atm')
  }

  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_LOCAL)

  state.buffer.set(key, state.start)
  state.start += key.byteLength
  return state.buffer.subarray(start, state.start)
}

core.localEnd = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_LOCAL + 1)
  return state.buffer.subarray(start, state.start)
}

core.blockIndex = function (buffer) {
  const state = { buffer, start: 0, end: buffer.byteLength }
  UINT.decode(state) // ns
  UINT.decode(state) // ptr
  UINT.decode(state) // type
  return UINT.decode(state)
}

core.bitfieldIndexAndType = function (buffer) {
  const state = { buffer, start: 0, end: buffer.byteLength }
  UINT.decode(state) // ns
  UINT.decode(state) // ptr
  UINT.decode(state) // type
  return [UINT.decode(state), UINT.decode(state)]
}

core.userDataKey = function (buffer) {
  const state = { buffer, start: 0, end: buffer.byteLength }
  UINT.decode(state) // ns
  UINT.decode(state) // ptr
  UINT.decode(state) // type
  return STRING.decode(state)
}

core.markKey = function (buffer) {
  const state = { buffer, start: 0, end: buffer.byteLength }
  UINT.decode(state) // ns
  UINT.decode(state) // ptr
  UINT.decode(state) // type
  return UINT.decode(state)
}

core.localKey = function (buffer) {
  const state = { buffer, start: 0, end: buffer.byteLength }
  UINT.decode(state) // ns
  UINT.decode(state) // ptr
  UINT.decode(state) // type
  return state.buffer.subarray(state.start, state.end)
}

group.topic = function (topic) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_GROUP_BY_TOPIC)
  c.fixed32.encode(state, topic)
  return state.buffer.subarray(start, state.start)
}

group.entry = function (group, timestamp, ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_GROUP)
  UINT.encode(state, group)
  c.uint64be.encode(state, timestamp)
  UINT.encode(state, ptr)
  return state.buffer.subarray(start, state.start)
}

module.exports = { store, core, group }

function alloc() {
  if (slab.buffer.byteLength - slab.start < 4096) {
    slab.buffer = b4a.allocUnsafe(slab.buffer.byteLength)
    slab.start = 0
  }
  return slab
}
const b4a = require('b4a')
const BlockDependencyStream = require('./block-dependency-stream.js')
const { core, store, group } = require('./keys.js')
const schema = require('../encoding/spec/hyperschema')

const CORESTORE_CORE = schema.getEncoding('@corestore/core')
const CORE_TREE_NODE = schema.getEncoding('@core/tree-node')
const EMPTY = b4a.alloc(0)

module.exports = {
  createBlockStream,
  createBitfieldStream,
  createUserDataStream,
  createCoreStream,
  createAliasStream,
  createDiscoveryKeyStream,
  createTreeNodeStream,
  createMarkStream,
  createLocalStream,
  createGroupUpdateStream
}

function createCoreStream(db, view) {
  const start = store.coreStart()
  const end = store.coreEnd()

  const ite = view.iterator(db, start, end, false)

  ite._readableState.map = mapCore
  return ite
}

function createDiscoveryKeyStream(db, view, namespace) {
  const start = namespace ? store.coreByAliasStart(namespace) : store.coreStart()
  const end = namespace ? store.coreByAliasEnd(namespace) : store.coreEnd()

  const ite = view.iterator(db, start, end, false)

  ite._readableState.map = namespace ? mapNamespaceDiscoveryKeys : mapAllDiscoveryKeys
  return ite
}

function createAliasStream(db, view, namespace) {
  const start = store.coreByAliasStart(namespace)
  const end = store.coreByAliasEnd(namespace)

  const ite = view.iterator(db, start, end, false)

  ite._readableState.map = mapAlias
  return ite
}

function createGroupUpdateStream(db, view, groupID, { gte = 0, reverse = true } = {}) {
  const start = group.entry(groupID, gte, 0)
  const end = group.entry(groupID + 1, 0, 0)

  const ite = view.iterator(db, start, end, reverse)

  ite._readableState.map = mapGroupUpdate
  return ite
}

function createBlockIterator(ptr, db, view, start, end, reverse) {
  if (ptr.dependencies.length > 0) {
    return new BlockDependencyStream(ptr, db, view, start, end, reverse)
  }

  const s = core.block(ptr.dataPointer, start)
  const e = core.block(ptr.dataPointer, end === -1 ? Infinity : end)
  return view.iterator(db, s, e, reverse)
}

function createBlockStream(
  ptr,
  db,
  view,
  { gt = -1, gte = gt + 1, lte = -1, lt = lte === -1 ? -1 : lte + 1, reverse = false } = {}
) {
  const ite = createBlockIterator(ptr, db, view, gte, lt, reverse)

  ite._readableState.map = mapBlock
  return ite
}

function createBitfieldStream(
  ptr,
  db,
  view,
  { gt = -1, gte = gt + 1, lte = -1, lt = lte === -1 ? -1 : lte + 1, reverse = false } = {}
) {
  const s = core.bitfield(ptr.dataPointer, gte, 0)
  const e = core.bitfield(ptr.dataPointer, lt === -1 ? Infinity : lt, 0)
  const ite = view.iterator(db, s, e, false)

  ite._readableState.map = mapBitfield
  return ite
}

// NOTE: this does not do dependency lookups atm
function createTreeNodeStream(
  ptr,
  db,
  view,
  { gt = -1, gte = gt + 1, lte = -1, lt = lte === -1 ? -1 : lte + 1, reverse = false } = {}
) {
  const s = core.tree(ptr.dataPointer, gte, 0)
  const e = core.tree(ptr.dataPointer, lt === -1 ? Infinity : lt, 0)
  const ite = view.iterator(db, s, e, false)

  ite._readableState.map = mapTreeNode
  return ite
}

function createUserDataStream(
  ptr,
  db,
  view,
  { gt = null, gte = '', lte = null, lt = null, reverse = false } = {}
) {
  if (gt !== null || lte !== null) {
    throw new Error('gt and lte not yet supported for user data streams')
  }

  const s = core.userData(ptr.dataPointer, gte)
  const e = lt === null ? core.userDataEnd(ptr.dataPointer) : core.userData(ptr.dataPointer, lt)
  const ite = view.iterator(db, s, e, false)

  ite._readableState.map = mapUserData
  return ite
}

function createMarkStream(
  ptr,
  db,
  view,
  { gt = -1, gte = gt + 1, lte = -1, lt = lte === -1 ? -1 : lte + 1, reverse = false } = {}
) {
  const s = core.mark(ptr.dataPointer, gte)
  const e = core.mark(ptr.dataPointer, lt === -1 ? Infinity : lt)
  const ite = view.iterator(db, s, e, reverse)

  ite._readableState.map = mapMark
  return ite
}

function createLocalStream(
  ptr,
  db,
  view,
  { gt = null, gte = EMPTY, lte = null, lt = null, reverse = false } = {}
) {
  if (gt !== null || lte !== null) throw new Error('gt and lte not yet supported for local streams')

  const s = core.local(ptr.dataPointer, gte)
  const e = lt === null ? core.localEnd(ptr.dataPointer) : core.local(ptr.dataPointer, lt)
  const ite = view.iterator(db, s, e, false)

  ite._readableState.map = mapLocal
  return ite
}

function mapBitfield(data) {
  const [index, type] = core.bitfieldIndexAndType(data.key)
  if (type !== 0) return null // ignore for now
  return { index, page: data.value }
}

function mapMark(data) {
  const index = core.markKey(data.key)
  return { index, page: data.value }
}

function mapLocal(data) {
  const key = core.localKey(data.key)
  return { key, value: data.value }
}

function mapGroupUpdate(data) {
  return data.value
}

function mapUserData(data) {
  const key = core.userDataKey(data.key)
  return { key, value: data.value }
}

function mapCore(data) {
  const discoveryKey = store.discoveryKey(data.key)
  const core = CORESTORE_CORE.decode({
    start: 0,
    end: data.value.byteLength,
    buffer: data.value
  })
  return { discoveryKey, core }
}

function mapAllDiscoveryKeys(data) {
  return store.discoveryKey(data.key)
}

function mapNamespaceDiscoveryKeys(data) {
  return data.value
}

function mapAlias(data) {
  const alias = store.alias(data.key)
  return { alias, discoveryKey: data.value }
}

function mapBlock(data) {
  return { index: core.blockIndex(data.key), value: data.value }
}

function mapTreeNode(data) {
  return CORE_TREE_NODE.decode({
    start: 0,
    end: data.value.byteLength,
    buffer: data.value
  })
}
const b4a = require('b4a')
const c = require('compact-encoding')
const flat = require('flat-tree')

const schema = require('../encoding/spec/hyperschema')
const { store, core, group } = require('./keys.js')
const View = require('./view.js')

const CORESTORE_HEAD = schema.getEncoding('@corestore/head')
const CORESTORE_CORE = schema.getEncoding('@corestore/core')
const CORESTORE_GROUP = c.uint

const CORE_AUTH = schema.getEncoding('@core/auth')
const CORE_GROUP = schema.getEncoding('@core/group')
const CORE_SESSIONS = schema.getEncoding('@core/sessions')
const CORE_HEAD = schema.getEncoding('@core/head')
const CORE_TREE_NODE = schema.getEncoding('@core/tree-node')
const CORE_DEPENDENCY = schema.getEncoding('@core/dependency')
const CORE_HINTS = schema.getEncoding('@core/hints')

class CoreTX {
  constructor(core, db, view, changes) {
    if (db.snapshotted) throw new Error('Cannot open core tx on snapshot')
    this.core = core
    this.db = db
    this.view = view
    this.changes = changes
  }

  setAuth(auth) {
    this.changes.push([core.auth(this.core.corePointer), encode(CORE_AUTH, auth), null])
  }

  setSessions(sessions) {
    this.changes.push([core.sessions(this.core.corePointer), encode(CORE_SESSIONS, sessions), null])
  }

  setHead(head) {
    this.changes.push([core.head(this.core.dataPointer), encode(CORE_HEAD, head), null])
  }

  deleteHead() {
    this.changes.push([core.head(this.core.dataPointer), null, null])
  }

  setDependency(dep) {
    this.changes.push([core.dependency(this.core.dataPointer), encode(CORE_DEPENDENCY, dep), null])
  }

  setGroup(group) {
    this.changes.push([core.group(this.core.dataPointer), encode(CORE_GROUP, group), null])
  }

  deleteGroup() {
    this.changes.push([core.group(this.core.dataPointer), null, null])
  }

  setHints(hints) {
    this.changes.push([core.hints(this.core.dataPointer), encode(CORE_HINTS, hints), null])
  }

  putBlock(index, data) {
    this.changes.push([core.block(this.core.dataPointer, index), data, null])
  }

  deleteBlock(index) {
    this.changes.push([core.block(this.core.dataPointer, index), null, null])
  }

  deleteBlockRange(start, end) {
    this.changes.push([
      core.block(this.core.dataPointer, start),
      null,
      core.block(this.core.dataPointer, end === -1 ? Infinity : end)
    ])
  }

  putBitfieldPage(index, data) {
    this.changes.push([core.bitfield(this.core.dataPointer, index, 0), data, null])
  }

  deleteBitfieldPage(index) {
    this.changes.push([core.bitfield(this.core.dataPointer, index, 0), null, null])
  }

  deleteBitfieldPageRange(start, end) {
    this.changes.push([
      core.bitfield(this.core.dataPointer, start, 0),
      null,
      core.bitfield(this.core.dataPointer, end === -1 ? Infinity : end, 0)
    ])
  }

  putTreeNode(node) {
    this.changes.push([
      core.tree(this.core.dataPointer, node.index),
      encode(CORE_TREE_NODE, node),
      null
    ])
  }

  deleteTreeNode(index) {
    this.changes.push([core.tree(this.core.dataPointer, index), null, null])
  }

  deleteTreeNodeRange(start, end) {
    this.changes.push([
      core.tree(this.core.dataPointer, start),
      null,
      core.tree(this.core.dataPointer, end === -1 ? Infinity : end)
    ])
  }

  putUserData(key, value) {
    const buffer = typeof value === 'string' ? b4a.from(value) : value
    this.changes.push([core.userData(this.core.dataPointer, key), buffer, null])
  }

  deleteUserData(key) {
    this.changes.push([core.userData(this.core.dataPointer, key), null, null])
  }

  putMark(index, data) {
    this.changes.push([core.mark(this.core.dataPointer, index), data, null])
  }

  deleteMark(index) {
    this.changes.push([core.mark(this.core.dataPointer, index), null, null])
  }

  deleteMarkRange(start, end) {
    this.changes.push([
      core.mark(this.core.dataPointer, start),
      null,
      core.mark(this.core.dataPointer, end === -1 ? Infinity : end)
    ])
  }

  putLocal(key, value) {
    this.changes.push([core.local(this.core.dataPointer, key), value, null])
  }

  deleteLocal(key) {
    this.changes.push([core.local(this.core.dataPointer, key), null, null])
  }

  deleteLocalRange(start, end) {
    this.changes.push([
      core.local(this.core.dataPointer, start),
      null,
      end === null ? core.localEnd(this.core.dataPointer) : core.local(this.core.dataPointer, end)
    ])
  }

  putGroupUpdate(groupPtr, timestamp, key) {
    this.changes.push([group.entry(groupPtr, timestamp, this.core.corePointer), key, null])
  }

  deleteGroupUpdate(groupPtr, timestamp) {
    this.changes.push([group.entry(groupPtr, timestamp, this.core.corePointer), null, null])
  }

  flush() {
    const changes = this.changes
    if (changes === null) return Promise.resolve(!this.view)

    this.changes = null

    if (this.view) {
      this.view.apply(changes)
      return Promise.resolve(false)
    }

    return View.flush(changes, this.db)
  }
}

class CoreRX {
  constructor(core, db, view, treeCache, stats, fork) {
    this.core = core
    this.read = db.read({ autoDestroy: true })
    this.view = view
    this.treeCache = treeCache
    this.fork = fork
    this.stats = stats

    view.readStart()
  }

  static async getAuth(db, c) {
    return decode(CORE_AUTH, await db.get(core.auth(c.corePointer)))
  }

  async getAuth() {
    return decode(CORE_AUTH, await this.view.get(this.read, core.auth(this.core.corePointer)))
  }

  async getSessions() {
    return decode(
      CORE_SESSIONS,
      await this.view.get(this.read, core.sessions(this.core.corePointer))
    )
  }

  static async getHead(db, c) {
    return decode(CORE_HEAD, await db.get(core.head(c.dataPointer)))
  }

  async getHead() {
    return decode(CORE_HEAD, await this.view.get(this.read, core.head(this.core.dataPointer)))
  }

  async getDependency() {
    return decode(
      CORE_DEPENDENCY,
      await this.view.get(this.read, core.dependency(this.core.dataPointer))
    )
  }

  async getGroup() {
    return await decode(
      CORE_GROUP,
      await this.view.get(this.read, core.group(this.core.corePointer))
    )
  }

  static async getHints(db, c) {
    return decode(CORE_HINTS, await db.get(core.hints(c.dataPointer)))
  }

  async getHints() {
    return decode(CORE_HINTS, await this.view.get(this.read, core.hints(this.core.dataPointer)))
  }

  getBlock(index) {
    const dep = findBlockDependency(this.core.dependencies, index)
    const data = dep === null ? this.core.dataPointer : dep.dataPointer
    return this.view.get(this.read, core.block(data, index))
  }

  getBitfieldPage(index) {
    return this.view.get(this.read, core.bitfield(this.core.dataPointer, index, 0))
  }

  async _resolveTreeCache(key, promise, entry) {
    try {
      const value = decode(CORE_TREE_NODE, await promise)
      const cached = this.treeCache.get(key)

      // preflight is gone; no-op
      if (cached !== entry) return value

      if (value !== null) {
        // replace cached entry with value
        this.treeCache.set(key, { pending: null, value })
      } else {
        // discard non-existing values
        this.treeCache.delete(key)
      }

      return value
    } catch (err) {
      // cleanup
      const cached = this.treeCache.get(key)
      if (cached === entry) {
        this.treeCache.delete(key)
      }

      throw err
    }
  }

  async getTreeNode(index) {
    const dep = findTreeDependency(this.core.dependencies, index)
    const data = dep === null ? this.core.dataPointer : dep.dataPointer

    if (!this.treeCache || this.fork < 0) {
      if (this.stats !== null) this.stats.treeCache.skips++
      // no-cache
      return decode(CORE_TREE_NODE, await this.view.get(this.read, core.tree(data, index)))
    }

    const key = `${data}:${index}:${this.fork}`
    let entry = this.treeCache.get(key)
    if (entry) {
      if (entry.pending) {
        if (this.stats !== null) this.stats.treeCache.parallel++
        return entry.pending
      }

      if (this.stats !== null) this.stats.treeCache.hits++
      return entry.value
    }

    if (this.stats !== null) this.stats.treeCache.misses++

    const promise = this.view.get(this.read, core.tree(data, index))
    entry = { pending: null, value: null }
    entry.pending = this._resolveTreeCache(key, promise, entry)
    this.treeCache.set(key, entry)

    return entry.pending
  }

  async hasTreeNode(index) {
    return (await this.getTreeNode(index)) !== null
  }

  getUserData(key) {
    return this.view.get(this.read, core.userData(this.core.dataPointer, key))
  }

  getMark(index) {
    return this.view.get(this.read, core.mark(this.core.dataPointer, index))
  }

  getLocal(key) {
    return this.view.get(this.read, core.local(this.core.dataPointer, key))
  }

  tryFlush() {
    this.read.tryFlush()
    this._free()
  }

  destroy() {
    this.read.destroy()
    this._free()
  }

  _free() {
    if (this.view === null) return
    this.view.readStop()
    this.view = null
  }
}

class CorestoreTX {
  constructor(view) {
    this.view = view
    this.changes = []
  }

  setHead(head) {
    this.changes.push([store.head(), encode(CORESTORE_HEAD, head), null])
  }

  setCoreHints(c, hints) {
    this.changes.push([core.hints(c.dataPointer), encode(CORE_HINTS, hints), null])
  }

  putCore(discoveryKey, ptr) {
    this.changes.push([store.core(discoveryKey), encode(CORESTORE_CORE, ptr), null])
  }

  putCoreByAlias(alias, discoveryKey) {
    this.changes.push([store.coreByAlias(alias), discoveryKey, null])
  }

  putGroup(topic, groupPtr) {
    this.changes.push([group.topic(topic), encode(CORESTORE_GROUP, groupPtr), null])
  }

  deleteGroup(topic) {
    this.changes.push([group.topic(topic), null, null])
  }

  clear() {
    const [start, end] = store.clear()
    this.changes.push([start, null, end])
  }

  apply() {
    if (this.changes === null) return
    this.view.apply(this.changes)
    this.changes = null
  }
}

class CorestoreRX {
  constructor(db, view) {
    this.read = db.read({ autoDestroy: true })
    this.view = view

    view.readStart()
  }

  async getHeadRaw(db) {
    return await this.view.get(this.read, store.head())
  }

  async getHead() {
    return decode(CORESTORE_HEAD, await this.view.get(this.read, store.head()))
  }

  async getCore(discoveryKey) {
    return decode(CORESTORE_CORE, await this.view.get(this.read, store.core(discoveryKey)))
  }

  getCoreByAlias(alias) {
    return this.view.get(this.read, store.coreByAlias(alias))
  }

  async getGroup(topic) {
    return decode(CORESTORE_GROUP, await this.view.get(this.read, group.topic(topic)))
  }

  tryFlush() {
    this.read.tryFlush()
    this._free()
  }

  destroy() {
    this.read.destroy()
    this._free()
  }

  _free() {
    if (this.view === null) return
    this.view.readStop()
    this.view = null
  }
}

module.exports = { CorestoreTX, CorestoreRX, CoreTX, CoreRX }

function findBlockDependency(dependencies, index) {
  for (let i = 0; i < dependencies.length; i++) {
    const dep = dependencies[i]
    if (index < dep.length) return dep
  }

  return null
}

function findTreeDependency(dependencies, index) {
  for (let i = 0; i < dependencies.length; i++) {
    const dep = dependencies[i]
    if (flat.rightSpan(index) <= (dep.length - 1) * 2) return dep
  }

  return null
}

function decode(enc, buffer) {
  if (buffer === null) return null
  return enc.decode({ start: 0, end: buffer.byteLength, buffer })
}

function encode(enc, m) {
  // TODO: use fancy slab for small messages
  const state = { start: 0, end: 0, buffer: null }
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}
const { Readable, getStreamError } = require('streamx')
const CloseErrorStream = require('./close-error-stream.js')
const b4a = require('b4a')

class OverlayStream extends Readable {
  constructor(stream, start, end, reverse, changes, cleared) {
    super()

    this.start = start
    this.end = end
    this.reverse = reverse
    this.changes = changes
    this.cleared = cleared
    this.change = 0
    this.range = 0

    this._stream = stream
    this._drained = false

    this._stream.on('readable', this._drainMaybe.bind(this))
    this._stream.on('error', noop)
    this._stream.on('close', this._onclose.bind(this))
  }

  _drainMaybe() {
    if (this._drained === true) return
    this._drained = this._onreadable()
  }

  _onclose() {
    if (this.destroying) return

    const err = getStreamError(this._stream)

    if (err !== null) {
      this.destroy(err)
      return
    }

    while (this.change < this.changes.length) {
      const c = this.changes[this.change++]
      const key = c[0]
      const value = c[1]

      if (value !== null && this._inRange(key)) this.push({ key, value })
    }

    this.push(null)
    this._stream = null
  }

  _onreadable() {
    let data = this._stream.read()
    if (data === null) return false

    let drained = false

    do {
      if (this._push(data) === true) drained = true
      data = this._stream.read()
    } while (data !== null)

    return drained
  }

  _read(cb) {
    this._drained = this._onreadable()
    cb(null)
  }

  _predestroy() {
    this._stream.destroy()
  }

  _push(entry) {
    const key = entry.key

    while (this.range < this.cleared.length) {
      const c = this.cleared[this.range]

      // we moved past the range
      if (this.reverse ? b4a.compare(key, c[0]) < 0 : b4a.compare(c[2], key) <= 0) {
        this.range++
        continue
      }

      // we didnt move past and are in, drop
      if (b4a.compare(c[0], key) <= 0 && b4a.compare(key, c[2]) < 0) {
        return false
      }

      break
    }

    let updated = false

    while (this.change < this.changes.length) {
      const c = this.changes[this.change]
      const key = c[0]
      const value = typeof c[1] === 'string' ? b4a.from(c[1]) : c[1]
      const cmp = b4a.compare(key, entry.key)

      // same value, if not deleted, return new one
      if (cmp === 0) {
        this.change++
        if (value === null || this._inRange(key) === false) return updated
        this.push({ key, value })
        return true
      }

      // we moved past the change, push it
      if (this.reverse ? cmp > 0 : cmp < 0) {
        this.change++
        if (value === null || this._inRange(key) === false) continue
        this.push({ key, value })
        updated = true
        continue
      }

      this.push(entry)
      return true
    }

    this.push(entry)
    return true
  }

  _inRange(key) {
    return b4a.compare(this.start, key) <= 0 && b4a.compare(key, this.end) < 0
  }
}

class Overlay {
  constructor() {
    this.indexed = 0
    this.changes = null
    this.cleared = null
    this.reverse = false
  }

  update(view, reverse) {
    if (view.indexed === this.indexed) return

    const changes = view.map === null ? [] : [...view.map.values()]
    const cleared = view.cleared === null ? [] : view.cleared.slice(0)

    const cmp = reverse ? cmpChangeReverse : cmpChange

    changes.sort(cmp)
    cleared.sort(cmp)

    this.indexed = view.indexed
    this.changes = changes
    this.cleared = cleared
    this.reverse = reverse
  }

  createStream(stream, start, end, reverse) {
    return new OverlayStream(
      stream,
      start,
      end,
      reverse,
      this.reverse === reverse ? this.changes : reverseArray(this.changes),
      this.reverse === reverse ? this.cleared : reverseArray(this.cleared)
    )
  }
}

class View {
  constructor() {
    this.map = null
    this.indexed = 0
    this.changes = null
    this.cleared = null
    this.overlay = null
    this.snap = null
    this.readers = 0
  }

  snapshot() {
    if (this._attached()) return this.snap.snapshot()

    const snap = new View()

    snap.map = this.map
    snap.indexed = this.indexed
    snap.changes = this.changes
    snap.cleared = this.cleared

    if (this._frozen()) return snap

    this.readers++
    snap.snap = this

    return snap
  }

  readStart() {
    if (this.snap !== null) this.readers++
  }

  readStop() {
    if (this.snap !== null && --this.readers === 0) this.snap.readers--
  }

  size() {
    return this.changes === null ? 0 : this.changes.length
  }

  updated() {
    return this.changes === null
  }

  get(read, key) {
    return this.changes === null ? read.get(key) : this._indexAndGet(read, key)
  }

  reset() {
    this.indexed = 0
    this.snap = this.map = this.changes = this.cleared = this.overlay = null
  }

  iterator(db, start, end, reverse) {
    if (dbClosing(db)) return new CloseErrorStream(new Error('RocksDB session is closed'))

    const stream = db.iterator({ gte: start, lt: end, reverse })
    if (this.changes === null) return stream

    this._index()

    if (this.overlay === null) this.overlay = new Overlay()
    this.overlay.update(this, reverse)
    return this.overlay.createStream(stream, start, end, reverse)
  }

  _indexAndGet(read, key) {
    this._index()
    const change = this.map.get(b4a.toString(key, 'hex'))

    if (change === undefined) {
      return this.cleared === null ? read.get(key) : this._readAndMaybeDrop(read, key)
    }

    return Promise.resolve(change[1])
  }

  async _readAndMaybeDrop(read, key) {
    const cleared = this.cleared // in case its cleared
    const value = await read.get(key)
    if (value === null) return null

    for (let i = 0; i < cleared.length; i++) {
      const c = cleared[i]
      // check if in range
      if (b4a.compare(c[0], key) <= 0 && b4a.compare(key, c[2]) < 0) return null
    }

    return value
  }

  _attached() {
    return this.snap !== null && this.changes === this.snap.changes
  }

  _frozen() {
    return this.changes === null || (this.snap !== null && this.changes !== this.snap.changes)
  }

  _index() {
    // if we are a snap and we are still attached (ie no mutations), simply copy the refs
    if (this._attached()) {
      this.snap._index()
      this.map = this.snap.map
      this.cleared = this.snap.cleared
      this.indexed = this.snap.indexed
      return
    }

    if (this.map === null) this.map = new Map()
    if (this.changes.length === this.indexed) return

    while (this.indexed < this.changes.length) {
      const c = this.changes[this.indexed++]

      if (c[2] === null) this.map.set(b4a.toString(c[0], 'hex'), c)
      else this._indexRange(c)
    }
  }

  _indexRange(range) {
    const s = b4a.toString(range[0], 'hex')
    const e = b4a.toString(range[2], 'hex')

    for (const [key, c] of this.map) {
      if (s <= key && key < e) this.map.set(key, [c[0], null, null])
    }

    if (this.cleared === null) this.cleared = []
    this.cleared.push(range)
  }

  apply(changes) {
    if (this.snap !== null) throw new Error('Illegal to push changes to a snapshot')

    if (this.readers !== 0 && this.changes !== null) {
      this.changes = this.changes.slice(0)
      this.cleared = this.cleared === null ? null : this.cleared.slice(0)
      this.map = this.map === null ? null : new Map([...this.map])
    }

    if (this.changes === null) {
      this.changes = changes
      return
    }

    for (let i = 0; i < changes.length; i++) {
      this.changes.push(changes[i])
    }
  }

  static async flush(changes, db) {
    if (changes === null) return true

    const w = db.write({ autoDestroy: true })

    for (const [start, value, end] of changes) {
      if (end !== null) w.tryDeleteRange(start, end)
      else if (value !== null) w.tryPut(start, value)
      else w.tryDelete(start)
    }

    await w.flush()

    return true
  }
}

module.exports = View

function cmpChange(a, b) {
  const c = b4a.compare(a[0], b[0])
  return c === 0 ? b4a.compare(a[2], b[2]) : c
}

function cmpChangeReverse(a, b) {
  return cmpChange(b, a)
}

function noop() {}

function reverseArray(list) {
  const r = new Array(list.length)
  for (let i = 0; i < list.length; i++) r[r.length - 1 - i] = list[i]
  return r
}

// TODO: expose from rocks instead
function dbClosing(db) {
  return db._state.closing || db._index === -1
}
const fs = require('fs')
const path = require('path')
const { Readable } = require('streamx')
const b4a = require('b4a')
const flat = require('flat-tree')
const crypto = require('hypercore-crypto')
const c = require('compact-encoding')
const m = require('./messages.js')
const View = require('../../lib/view.js')
const { CorestoreTX, CoreTX, CorestoreRX } = require('../../lib/tx.js')

const EMPTY_NODE = b4a.alloc(40)
const EMPTY_PAGE = b4a.alloc(4096)

let TREE_01_SKIP = null
let TREE_04_SKIP = null
let TREE_16_SKIP = null

class CoreListStream extends Readable {
  constructor (storage) {
    super()

    this.storage = storage
    this.stack = []
  }

  async _open (cb) {
    for (const a of await readdir(path.join(this.storage, 'cores'))) {
      for (const b of await readdir(path.join(this.storage, 'cores', a))) {
        for (const dkey of await readdir(path.join(this.storage, 'cores', a, b))) {
          this.stack.push(path.join(this.storage, 'cores', a, b, dkey))
        }
      }
    }

    cb(null)
  }

  async _read (cb) {
    while (true) {
      const next = this.stack.pop()
      if (!next) {
        this.push(null)
        break
      }

      const oplog = path.join(next, 'oplog')
      const result = await readOplog(oplog)
      if (!result) continue

      this.push(result)
      break
    }

    cb(null)
  }
}

function decodeOplogHeader (state) {
  c.uint32.decode(state) // cksum, ignore for now

  const l = c.uint32.decode(state)
  const length = l >> 2
  const headerBit = l & 1
  const partialBit = l & 2

  if (state.end - state.start < length) return null

  const end = state.start + length
  const result = { header: headerBit, partial: partialBit !== 0, byteLength: length + 8, message: null }

  try {
    result.message = m.oplog.header.decode({ start: state.start, end, buffer: state.buffer })
  } catch {
    return null
  }

  state.start = end
  return result
}

function decodeOplogEntry (state) {
  if (state.end - state.start < 8) return null

  c.uint32.decode(state) // cksum, ignore for now

  const l = c.uint32.decode(state)
  const length = l >>> 2
  const headerBit = l & 1
  const partialBit = l & 2

  if (state.end - state.start < length) return null

  const end = state.start + length

  const result = { header: headerBit, partial: partialBit !== 0, byteLength: length + 8, message: null }

  try {
    result.message = m.oplog.entry.decode({ start: state.start, end, buffer: state.buffer })
  } catch {
    return null
  }

  state.start = end

  return result
}

module.exports = { store, core }

async function store (storage, { version, dryRun = true, gc = true }) {
  const stream = new CoreListStream(storage.path)
  const view = new View()

  const tx = new CorestoreTX(view)
  const head = await storage._getHead(view)
  const primaryKeyFile = path.join(storage.path, 'primary-key')

  const primaryKey = await readFile(primaryKeyFile)

  if (!head.seed) head.seed = primaryKey

  for await (const data of stream) {
    const key = data.header.key
    const discoveryKey = crypto.discoveryKey(data.header.key)
    const files = getFiles(data.path)

    if (head.defaultDiscoveryKey === null) head.defaultDiscoveryKey = discoveryKey

    const core = {
      version: 0, // need later migration
      corePointer: head.allocated.cores++,
      dataPointer: head.allocated.datas++,
      alias: null
    }

    const ptr = { version: 0, corePointer: core.corePointer, dataPointer: core.dataPointer, dependencies: [] }
    const ctx = new CoreTX(ptr, storage.db, view, [])
    const userData = new Map()
    const treeNodes = new Map()

    const auth = {
      key,
      discoveryKey,
      manifest: data.header.manifest,
      keyPair: data.header.keyPair,
      encryptionKey: null
    }

    const tree = {
      length: 0,
      fork: 0,
      rootHash: null,
      signature: null
    }

    if (data.header.tree && data.header.tree.length) {
      tree.length = data.header.tree.length
      tree.fork = data.header.tree.fork
      tree.rootHash = data.header.tree.rootHash
      tree.signature = data.header.tree.signature
    }

    for (const { key, value } of data.header.userData) {
      userData.set(key, value)
    }

    for (const e of data.entries) {
      if (e.userData) userData.set(e.userData.key, e.userData.value)

      if (e.treeNodes) {
        for (const node of e.treeNodes) {
          treeNodes.set(node.index, node)
          ctx.putTreeNode(node)
        }
      }

      if (e.treeUpgrade) {
        if (e.treeUpgrade.ancestors !== tree.length) {
          throw new Error('Unflushed truncations not migrate-able atm')
        }

        tree.length = e.treeUpgrade.length
        tree.fork = e.treeUpgrade.fork
        tree.rootHash = null
        tree.signature = e.treeUpgrade.signature
      }
    }

    if (userData.has('corestore/name') && userData.has('corestore/namespace')) {
      core.alias = {
        name: b4a.toString(userData.get('corestore/name')),
        namespace: userData.get('corestore/namespace')
      }
      userData.delete('corestore/name')
      userData.delete('corestore/namespace')
    }

    for (const [key, value] of userData) {
      ctx.putUserData(key, value)
    }

    ctx.setAuth(auth)

    const getTreeNode = (index) => (treeNodes.get(index) || getTreeNodeFromFile(files.tree, index))

    if (tree.length) {
      if (tree.rootHash === null) tree.rootHash = crypto.tree(await getRoots(tree.length, getTreeNode))
      ctx.setHead(tree)
    }

    tx.putCore(discoveryKey, core)
    if (core.alias) tx.putCoreByAlias(core.alias, discoveryKey)

    await ctx.flush()
  }

  head.version = version
  tx.setHead(head)
  tx.apply()

  if (dryRun) return

  await View.flush(view.changes, storage.db)

  if (gc) await rm(primaryKeyFile)
}

class BlockSlicer {
  constructor (filename) {
    this.stream = fs.createReadStream(filename)
    this.closed = new Promise(resolve => this.stream.once('close', resolve))
    this.offset = 0
    this.overflow = null
  }

  async take (offset, size) {
    let buffer = null
    if (offset < this.offset) throw new Error('overread')

    while (true) {
      let data = null

      if (this.overflow) {
        data = this.overflow
        this.overflow = null
      } else {
        data = this.stream.read()

        if (!data) {
          await new Promise(resolve => this.stream.once('readable', resolve))
          continue
        }
      }

      let chunk = null

      if (this.offset === offset || buffer) {
        chunk = data
      } else if (this.offset + data.byteLength > offset) {
        chunk = data.subarray(offset - this.offset)
      }

      this.offset += data.byteLength
      if (!chunk) continue

      if (buffer) buffer = b4a.concat([buffer, chunk])
      else buffer = chunk

      if (buffer.byteLength < size) continue

      const result = buffer.subarray(0, size)
      this.overflow = size === buffer.byteLength ? null : buffer.subarray(result.byteLength)
      this.offset -= (this.overflow ? this.overflow.byteLength : 0)
      return result
    }
  }

  close () {
    this.stream.on('error', noop)
    this.stream.destroy()
    return this.closed
  }
}

class TreeSlicer {
  constructor () {
    this.buffer = null
    this.offset = 0
  }

  get size () {
    return this.buffer === null ? 0 : this.buffer.byteLength
  }

  push (data) {
    if (this.buffer === null) this.buffer = data
    else this.buffer = b4a.concat([this.buffer, data])
    this.offset += data.byteLength
  }

  skip () {
    let skipped = 0

    if (TREE_01_SKIP === null) {
      TREE_16_SKIP = b4a.alloc(16 * 40 * 100)
      TREE_04_SKIP = TREE_16_SKIP.subarray(0, 4 * 40 * 100)
      TREE_01_SKIP = TREE_16_SKIP.subarray(0, 1 * 40 * 100)
    }

    while (true) {
      if (this.buffer.byteLength >= TREE_16_SKIP.byteLength) {
        if (b4a.equals(this.buffer.subarray(0, TREE_16_SKIP.byteLength), TREE_16_SKIP)) {
          this.buffer = this.buffer.subarray(TREE_16_SKIP.byteLength)
          skipped += 1600
          continue
        }
      }

      if (this.buffer.byteLength >= TREE_04_SKIP.byteLength) {
        if (b4a.equals(this.buffer.subarray(0, TREE_04_SKIP.byteLength), TREE_04_SKIP)) {
          this.buffer = this.buffer.subarray(TREE_04_SKIP.byteLength)
          skipped += 400
          continue
        }
      }

      if (this.buffer.byteLength >= TREE_01_SKIP.byteLength) {
        if (b4a.equals(this.buffer.subarray(0, TREE_01_SKIP.byteLength), TREE_01_SKIP)) {
          this.buffer = this.buffer.subarray(TREE_01_SKIP.byteLength)
          skipped += 100
          continue
        }
      }
      break
    }

    return skipped
  }

  take () {
    const len = 40

    if (len <= this.size) {
      const chunk = this.buffer.subarray(0, len)
      this.buffer = this.buffer.subarray(len)
      return chunk
    }

    return null
  }
}

async function core (core, { version, dryRun = true, gc = true }) {
  if (dryRun) return // dryRun mode not supported atm

  const rx = core.read()

  const promises = [rx.getAuth(), rx.getHead()]
  rx.tryFlush()

  const [auth, head] = await Promise.all(promises)

  if (!auth) return

  const dk = b4a.toString(auth.discoveryKey, 'hex')
  const files = getFiles(path.join(core.store.path, 'cores', dk.slice(0, 2), dk.slice(2, 4), dk))

  if (head === null || head.length === 0) {
    await commitCoreMigration(auth, core, version)
    if (gc) await runGC()
    return // no data
  }

  const oplog = await readOplog(files.oplog)
  if (!oplog) {
    const writable = !!auth.keyPair

    if (writable) {
      throw new Error('No oplog available writable core for ' + files.oplog + ', length = ' + (head ? head.length : 0))
    }

    // if not writable, just nuke it to recover, some bad state happened here, prop corruption from earlier versions
    const w = core.write()

    w.deleteBlockRange(0, -1)
    w.deleteTreeNodeRange(0, -1)
    w.deleteBitfieldPageRange(0, -1)
    w.deleteHead()

    await w.flush()

    await commitCoreMigration(auth, core, version)
    if (gc) await runGC()
    return // no data
  }

  const treeData = new TreeSlicer()

  let treeIndex = 0

  if (await exists(files.tree)) {
    for await (const data of fs.createReadStream(files.tree)) {
      treeData.push(data)

      let write = null

      while (true) {
        const skip = treeData.skip()
        treeIndex += skip

        const buf = treeData.take()
        if (buf === null) break

        const index = treeIndex++
        if (b4a.equals(buf, EMPTY_NODE)) continue

        if (write === null) write = core.write()
        write.putTreeNode(decodeTreeNode(index, buf))
      }

      if (write !== null) await write.flush()
    }
  }

  const buf = []
  if (await exists(files.bitfield)) {
    for await (const data of fs.createReadStream(files.bitfield)) {
      buf.push(data)
    }
  }

  let bitfield = b4a.concat(buf)
  if (bitfield.byteLength & 4095) bitfield = b4a.concat([bitfield, b4a.alloc(4096 - (bitfield.byteLength & 4095))])

  const pages = new Map()
  const headerBits = new Map()

  const roots = await getRootsFromStorage(core, head.length)

  for (const e of oplog.entries) {
    if (!e.bitfield) continue

    for (let i = 0; i < e.bitfield.length; i++) {
      headerBits.set(i + e.bitfield.start, !e.bitfield.drop)
    }
  }

  let batch = []

  const cache = new Map()
  const blocks = new BlockSlicer(files.data)

  for (const index of allBits(bitfield)) {
    if (headerBits.get(index) === false) continue
    if (index >= head.length) continue

    setBitInPage(index)

    batch.push(index)
    if (batch.length < 1024) continue

    await writeBlocksBatch()
    continue
  }

  if (batch.length) await writeBlocksBatch()

  await blocks.close()

  const w = core.write()

  for (const [index, bit] of headerBits) {
    if (!bit) continue
    if (index >= head.length) continue

    setBitInPage(index)

    const blk = await getBlockFromFile(files.data, core, index, roots, cache)
    w.putBlock(index, blk)
  }

  for (const [index, page] of pages) {
    w.putBitfieldPage(index, b4a.from(page.buffer, page.byteOffset, page.byteLength))
  }

  await w.flush()

  let contiguousLength = 0
  for await (const data of core.createBlockStream()) {
    if (data.index === contiguousLength) contiguousLength++
    else break
  }

  if (contiguousLength) {
    const w = core.write()
    w.setHints({ contiguousLength })
    await w.flush()
  }

  await commitCoreMigration(auth, core, version)

  if (gc) await runGC()

  async function runGC () {
    await rm(files.path)
    await rmdir(path.join(files.path, '..'))
    await rmdir(path.join(files.path, '../..'))
    await rmdir(path.join(core.store.path, 'cores'))
  }

  function setBitInPage (index) {
    const n = index & 32767
    const p = (index - n) / 32768

    let page = pages.get(p)

    if (!page) {
      page = new Uint32Array(1024)
      pages.set(p, page)
    }

    const o = n & 31
    const b = (n - o) / 32
    const v = 1 << o

    page[b] |= v
  }

  async function writeBlocksBatch () {
    const read = core.read()
    const promises = []
    for (const index of batch) promises.push(getByteRangeFromStorage(read, 2 * index, roots, cache))
    read.tryFlush()

    const r = await Promise.all(promises)
    const tx = core.write()

    for (let i = 0; i < r.length; i++) {
      const index = batch[i]
      const [offset, size] = r[i]

      const blk = await blocks.take(offset, size)
      tx.putBlock(index, blk)
    }

    batch = []
    if (cache.size > 16384) cache.clear()

    await tx.flush()
  }
}

async function commitCoreMigration (auth, core, version) {
  const view = new View()
  const rx = new CorestoreRX(core.db, view)

  const storeCorePromise = rx.getCore(auth.discoveryKey)
  rx.tryFlush()

  const storeCore = await storeCorePromise

  storeCore.version = version

  const tx = new CorestoreTX(view)

  tx.putCore(auth.discoveryKey, storeCore)
  tx.apply()

  await View.flush(view.changes, core.db)
}

async function getBlockFromFile (file, core, index, roots, cache) {
  const rx = core.read()
  const promise = getByteRangeFromStorage(rx, 2 * index, roots, cache)
  rx.tryFlush()
  const [offset, size] = await promise

  return new Promise(function (resolve) {
    readAll(file, size, offset, function (err, buf) {
      if (err) return resolve(null)
      resolve(buf)
    })
  })
}

function getFiles (dir) {
  return {
    path: dir,
    oplog: path.join(dir, 'oplog'),
    data: path.join(dir, 'data'),
    tree: path.join(dir, 'tree'),
    bitfield: path.join(dir, 'bitfield')
  }
}

async function getRootsFromStorage (core, length) {
  const all = []
  const rx = core.read()
  for (const index of flat.fullRoots(2 * length)) {
    all.push(rx.getTreeNode(index))
  }
  rx.tryFlush()
  return Promise.all(all)
}

async function getRoots (length, getTreeNode) {
  const all = []
  for (const index of flat.fullRoots(2 * length)) {
    all.push(await getTreeNode(index))
  }
  return all
}

function getCached (read, cache, index) {
  if (cache.has(index)) return cache.get(index)
  const p = read.getTreeNode(index)
  cache.set(index, p)
  return p
}

async function getByteRangeFromStorage (read, index, roots, cache) {
  const promises = [getCached(read, cache, index), getByteOffsetFromStorage(read, index, roots, cache)]
  const [node, offset] = await Promise.all(promises)
  if (!node) throw new Error('Node not found during migration: ' + index)
  return [offset, node.size]
}

async function getByteOffsetFromStorage (rx, index, roots, cache) {
  if (index === 0) return 0
  if ((index & 1) === 1) index = flat.leftSpan(index)

  let head = 0
  let offset = 0

  for (const node of roots) { // all async ticks happen once we find the root so safe
    head += 2 * ((node.index - head) + 1)

    if (index >= head) {
      offset += node.size
      continue
    }

    const ite = flat.iterator(node.index)
    const promises = []

    while (ite.index !== index) {
      if (index < ite.index) {
        ite.leftChild()
      } else {
        promises.push(getCached(rx, cache, ite.leftChild()))
        ite.sibling()
      }
    }

    const nodes = await Promise.all(promises)
    for (const node of nodes) offset += node.size

    return offset
  }

  throw new Error('Failed to find offset')
}

function decodeTreeNode (index, buf) {
  return { index, size: c.decode(c.uint64, buf), hash: buf.subarray(8) }
}

async function getTreeNodeFromFile (file, index) {
  return new Promise(function (resolve) {
    readAll(file, 40, index * 40, function (err, buf) {
      if (err) return resolve(null)
      resolve(decodeTreeNode(index, buf))
    })
  })
}

function readAll (filename, length, pos, cb) {
  const buf = b4a.alloc(length)

  fs.open(filename, 'r', function (err, fd) {
    if (err) return cb(err)

    let offset = 0

    fs.read(fd, buf, offset, buf.byteLength, pos, function loop (err, read) {
      if (err) return done(err)
      if (read === 0) return done(new Error('Partial read'))
      offset += read
      if (offset === buf.byteLength) return done(null, buf)
      fs.read(fd, offset, buf.byteLength - offset, buf, pos + offset, loop)
    })

    function done (err, value) {
      fs.close(fd, () => cb(err, value))
    }
  })
}

async function readdir (dir) {
  try {
    return await fs.promises.readdir(dir)
  } catch {
    return []
  }
}

async function exists (file) {
  try {
    await fs.promises.stat(file)
    return true
  } catch {
    return false
  }
}

async function readFile (file) {
  try {
    return await fs.promises.readFile(file)
  } catch {
    return null
  }
}

async function rm (dir) {
  try {
    await fs.promises.rm(dir, { recursive: true })
  } catch {}
}

async function rmdir (dir) {
  try {
    await fs.promises.rmdir(dir)
  } catch {}
}

function * allBits (buffer) {
  for (let i = 0; i < buffer.byteLength; i += EMPTY_PAGE.byteLength) {
    const page = buffer.subarray(i, i + EMPTY_NODE.byteLength)
    if (b4a.equals(page, EMPTY_PAGE)) continue

    const view = new Uint32Array(page.buffer, page.byteOffset, EMPTY_PAGE.byteLength / 4)

    for (let j = 0; j < view.length; j++) {
      const n = view[j]
      if (n === 0) continue

      for (let k = 0; k < 32; k++) {
        const m = 1 << k
        if (n & m) yield i * 8 + j * 32 + k
      }
    }
  }
}

function readOplog (oplog) {
  return new Promise(function (resolve) {
    fs.readFile(oplog, function (err, buffer) {
      if (err) return resolve(null)

      const state = { start: 0, end: buffer.byteLength, buffer }
      const headers = [1, 0]

      const h1 = decodeOplogHeader(state)
      state.start = 4096

      const h2 = decodeOplogHeader(state)
      state.start = 4096 * 2

      if (!h1 && !h2) return resolve(null)

      if (h1 && !h2) {
        headers[0] = h1.header
        headers[1] = h1.header
      } else if (!h1 && h2) {
        headers[0] = (h2.header + 1) & 1
        headers[1] = h2.header
      } else {
        headers[0] = h1.header
        headers[1] = h2.header
      }

      const header = (headers[0] + headers[1]) & 1
      const result = { path: path.dirname(oplog), header: null, entries: [] }
      const decoded = []

      result.header = header ? h2.message : h1.message

      if (result.header.external) {
        fs.readFile(path.join(oplog, '../header'), function (err, buffer) {
          if (err) return resolve(null)
          const start = result.header.external.start
          const end = start + result.header.external.length
          result.header = m.oplog.header.decode({ buffer, start, end })
          finish()
        })
        return
      }

      finish()

      function finish () {
        while (true) {
          const entry = decodeOplogEntry(state)
          if (!entry) break
          if (entry.header !== header) break

          decoded.push(entry)
        }

        while (decoded.length > 0 && decoded[decoded.length - 1].partial) decoded.pop()

        for (const e of decoded) {
          result.entries.push(e.message)
        }

        resolve(result)
      }
    })
  })
}

function noop () {}
// needed here for compat, copied from old hypercore, do not change this

const c = require('compact-encoding')
const b4a = require('b4a')

const EMPTY = b4a.alloc(0)
const DEFAULT_NAMESPACE = b4a.from('4144eea531e483d54e0c14f4ca68e0644f355343ff6fcb0f005200e12cd747cb', 'hex')

const hashes = {
  preencode (state, m) {
    state.end++ // small uint
  },
  encode (state, m) {
    if (m === 'blake2b') {
      c.uint.encode(state, 0)
      return
    }

    throw new Error('Unknown hash: ' + m)
  },
  decode (state) {
    const n = c.uint.decode(state)
    if (n === 0) return 'blake2b'
    throw new Error('Unknown hash id: ' + n)
  }
}

const signatures = {
  preencode (state, m) {
    state.end++ // small uint
  },
  encode (state, m) {
    if (m === 'ed25519') {
      c.uint.encode(state, 0)
      return
    }

    throw new Error('Unknown signature: ' + m)
  },
  decode (state) {
    const n = c.uint.decode(state)
    if (n === 0) return 'ed25519'
    throw new Error('Unknown signature id: ' + n)
  }
}

const signer = {
  preencode (state, m) {
    signatures.preencode(state, m.signature)
    c.fixed32.preencode(state, m.namespace)
    c.fixed32.preencode(state, m.publicKey)
  },
  encode (state, m) {
    signatures.encode(state, m.signature)
    c.fixed32.encode(state, m.namespace)
    c.fixed32.encode(state, m.publicKey)
  },
  decode (state) {
    return {
      signature: signatures.decode(state),
      namespace: c.fixed32.decode(state),
      publicKey: c.fixed32.decode(state)
    }
  }
}

const signerArray = c.array(signer)

const prologue = {
  preencode (state, p) {
    c.fixed32.preencode(state, p.hash)
    c.uint.preencode(state, p.length)
  },
  encode (state, p) {
    c.fixed32.encode(state, p.hash)
    c.uint.encode(state, p.length)
  },
  decode (state) {
    return {
      hash: c.fixed32.decode(state),
      length: c.uint.decode(state)
    }
  }
}

const manifestv0 = {
  preencode (state, m) {
    hashes.preencode(state, m.hash)
    state.end++ // type

    if (m.prologue && m.signers.length === 0) {
      c.fixed32.preencode(state, m.prologue.hash)
      return
    }

    if (m.quorum === 1 && m.signers.length === 1 && !m.allowPatch) {
      signer.preencode(state, m.signers[0])
    } else {
      state.end++ // flags
      c.uint.preencode(state, m.quorum)
      signerArray.preencode(state, m.signers)
    }
  },
  encode (state, m) {
    hashes.encode(state, m.hash)

    if (m.prologue && m.signers.length === 0) {
      c.uint.encode(state, 0)
      c.fixed32.encode(state, m.prologue.hash)
      return
    }

    if (m.quorum === 1 && m.signers.length === 1 && !m.allowPatch) {
      c.uint.encode(state, 1)
      signer.encode(state, m.signers[0])
    } else {
      c.uint.encode(state, 2)
      c.uint.encode(state, m.allowPatch ? 1 : 0)
      c.uint.encode(state, m.quorum)
      signerArray.encode(state, m.signers)
    }
  },
  decode (state) {
    const hash = hashes.decode(state)
    const type = c.uint.decode(state)

    if (type > 2) throw new Error('Unknown type: ' + type)

    if (type === 0) {
      return {
        version: 0,
        hash,
        allowPatch: false,
        quorum: 0,
        signers: [],
        prologue: {
          hash: c.fixed32.decode(state),
          length: 0
        }
      }
    }

    if (type === 1) {
      return {
        version: 0,
        hash,
        allowPatch: false,
        quorum: 1,
        signers: [signer.decode(state)],
        prologue: null
      }
    }

    const flags = c.uint.decode(state)

    return {
      version: 0,
      hash,
      allowPatch: (flags & 1) !== 0,
      quorum: c.uint.decode(state),
      signers: signerArray.decode(state),
      prologue: null
    }
  }
}

const manifest = exports.manifest = {
  preencode (state, m) {
    state.end++ // version
    if (m.version === 0) return manifestv0.preencode(state, m)

    state.end++ // flags
    hashes.preencode(state, m.hash)

    c.uint.preencode(state, m.quorum)
    signerArray.preencode(state, m.signers)
    if (m.prologue) prologue.preencode(state, m.prologue)
  },
  encode (state, m) {
    c.uint.encode(state, m.version)
    if (m.version === 0) return manifestv0.encode(state, m)

    c.uint.encode(state, (m.allowPatch ? 1 : 0) | (m.prologue ? 2 : 0) | (m.unencrypted ? 4 : 0))
    hashes.encode(state, m.hash)

    c.uint.encode(state, m.quorum)
    signerArray.encode(state, m.signers)
    if (m.prologue) prologue.encode(state, m.prologue)
  },
  decode (state) {
    const v = c.uint.decode(state)
    if (v === 0) return manifestv0.decode(state)
    if (v !== 1) throw new Error('Unknown version: ' + v)

    const flags = c.uint.decode(state)
    const hash = hashes.decode(state)
    const quorum = c.uint.decode(state)
    const signers = signerArray.decode(state)
    const unencrypted = (flags & 4) !== 0

    return {
      version: 1,
      hash,
      allowPatch: (flags & 1) !== 0,
      quorum,
      signers,
      prologue: (flags & 2) === 0 ? null : prologue.decode(state),
      unencrypted
    }
  }
}

const node = {
  preencode (state, n) {
    c.uint.preencode(state, n.index)
    c.uint.preencode(state, n.size)
    c.fixed32.preencode(state, n.hash)
  },
  encode (state, n) {
    c.uint.encode(state, n.index)
    c.uint.encode(state, n.size)
    c.fixed32.encode(state, n.hash)
  },
  decode (state) {
    return {
      index: c.uint.decode(state),
      size: c.uint.decode(state),
      hash: c.fixed32.decode(state)
    }
  }
}

const nodeArray = c.array(node)

const wire = exports.wire = {}

wire.handshake = {
  preencode (state, m) {
    c.uint.preencode(state, 1)
    c.fixed32.preencode(state, m.capability)
  },
  encode (state, m) {
    c.uint.encode(state, m.seeks ? 1 : 0)
    c.fixed32.encode(state, m.capability)
  },
  decode (state) {
    const flags = c.uint.decode(state)
    return {
      seeks: (flags & 1) !== 0,
      capability: c.fixed32.decode(state)
    }
  }
}

const requestBlock = {
  preencode (state, b) {
    c.uint.preencode(state, b.index)
    c.uint.preencode(state, b.nodes)
  },
  encode (state, b) {
    c.uint.encode(state, b.index)
    c.uint.encode(state, b.nodes)
  },
  decode (state) {
    return {
      index: c.uint.decode(state),
      nodes: c.uint.decode(state)
    }
  }
}

const requestSeek = {
  preencode (state, s) {
    c.uint.preencode(state, s.bytes)
    c.uint.preencode(state, s.padding)
  },
  encode (state, s) {
    c.uint.encode(state, s.bytes)
    c.uint.encode(state, s.padding)
  },
  decode (state) {
    return {
      bytes: c.uint.decode(state),
      padding: c.uint.decode(state)
    }
  }
}

const requestUpgrade = {
  preencode (state, u) {
    c.uint.preencode(state, u.start)
    c.uint.preencode(state, u.length)
  },
  encode (state, u) {
    c.uint.encode(state, u.start)
    c.uint.encode(state, u.length)
  },
  decode (state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

wire.request = {
  preencode (state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.id)
    c.uint.preencode(state, m.fork)

    if (m.block) requestBlock.preencode(state, m.block)
    if (m.hash) requestBlock.preencode(state, m.hash)
    if (m.seek) requestSeek.preencode(state, m.seek)
    if (m.upgrade) requestUpgrade.preencode(state, m.upgrade)
    if (m.priority) c.uint.preencode(state, m.priority)
  },
  encode (state, m) {
    const flags = (m.block ? 1 : 0) | (m.hash ? 2 : 0) | (m.seek ? 4 : 0) | (m.upgrade ? 8 : 0) | (m.manifest ? 16 : 0) | (m.priority ? 32 : 0)

    c.uint.encode(state, flags)
    c.uint.encode(state, m.id)
    c.uint.encode(state, m.fork)

    if (m.block) requestBlock.encode(state, m.block)
    if (m.hash) requestBlock.encode(state, m.hash)
    if (m.seek) requestSeek.encode(state, m.seek)
    if (m.upgrade) requestUpgrade.encode(state, m.upgrade)
    if (m.priority) c.uint.encode(state, m.priority)
  },
  decode (state) {
    const flags = c.uint.decode(state)

    return {
      id: c.uint.decode(state),
      fork: c.uint.decode(state),
      block: flags & 1 ? requestBlock.decode(state) : null,
      hash: flags & 2 ? requestBlock.decode(state) : null,
      seek: flags & 4 ? requestSeek.decode(state) : null,
      upgrade: flags & 8 ? requestUpgrade.decode(state) : null,
      manifest: (flags & 16) !== 0,
      priority: flags & 32 ? c.uint.decode(state) : 0
    }
  }
}

wire.cancel = {
  preencode (state, m) {
    c.uint.preencode(state, m.request)
  },
  encode (state, m) {
    c.uint.encode(state, m.request)
  },
  decode (state, m) {
    return {
      request: c.uint.decode(state)
    }
  }
}

const dataUpgrade = {
  preencode (state, u) {
    c.uint.preencode(state, u.start)
    c.uint.preencode(state, u.length)
    nodeArray.preencode(state, u.nodes)
    nodeArray.preencode(state, u.additionalNodes)
    c.optionalBuffer.preencode(state, u.signature)
  },
  encode (state, u) {
    c.uint.encode(state, u.start)
    c.uint.encode(state, u.length)
    nodeArray.encode(state, u.nodes)
    nodeArray.encode(state, u.additionalNodes)
    c.optionalBuffer.encode(state, u.signature)
  },
  decode (state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state),
      nodes: nodeArray.decode(state),
      additionalNodes: nodeArray.decode(state),
      signature: c.optionalBuffer.decode(state)
    }
  }
}

const dataSeek = {
  preencode (state, s) {
    c.uint.preencode(state, s.bytes)
    nodeArray.preencode(state, s.nodes)
  },
  encode (state, s) {
    c.uint.encode(state, s.bytes)
    nodeArray.encode(state, s.nodes)
  },
  decode (state) {
    return {
      bytes: c.uint.decode(state),
      nodes: nodeArray.decode(state)
    }
  }
}

const dataBlock = {
  preencode (state, b) {
    c.uint.preencode(state, b.index)
    c.optionalBuffer.preencode(state, b.value)
    nodeArray.preencode(state, b.nodes)
  },
  encode (state, b) {
    c.uint.encode(state, b.index)
    c.optionalBuffer.encode(state, b.value)
    nodeArray.encode(state, b.nodes)
  },
  decode (state) {
    return {
      index: c.uint.decode(state),
      value: c.optionalBuffer.decode(state) || EMPTY,
      nodes: nodeArray.decode(state)
    }
  }
}

const dataHash = {
  preencode (state, b) {
    c.uint.preencode(state, b.index)
    nodeArray.preencode(state, b.nodes)
  },
  encode (state, b) {
    c.uint.encode(state, b.index)
    nodeArray.encode(state, b.nodes)
  },
  decode (state) {
    return {
      index: c.uint.decode(state),
      nodes: nodeArray.decode(state)
    }
  }
}

wire.data = {
  preencode (state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.request)
    c.uint.preencode(state, m.fork)

    if (m.block) dataBlock.preencode(state, m.block)
    if (m.hash) dataHash.preencode(state, m.hash)
    if (m.seek) dataSeek.preencode(state, m.seek)
    if (m.upgrade) dataUpgrade.preencode(state, m.upgrade)
    if (m.manifest) manifest.preencode(state, m.manifest)
  },
  encode (state, m) {
    const flags = (m.block ? 1 : 0) | (m.hash ? 2 : 0) | (m.seek ? 4 : 0) | (m.upgrade ? 8 : 0) | (m.manifest ? 16 : 0)

    c.uint.encode(state, flags)
    c.uint.encode(state, m.request)
    c.uint.encode(state, m.fork)

    if (m.block) dataBlock.encode(state, m.block)
    if (m.hash) dataHash.encode(state, m.hash)
    if (m.seek) dataSeek.encode(state, m.seek)
    if (m.upgrade) dataUpgrade.encode(state, m.upgrade)
    if (m.manifest) manifest.encode(state, m.manifest)
  },
  decode (state) {
    const flags = c.uint.decode(state)

    return {
      request: c.uint.decode(state),
      fork: c.uint.decode(state),
      block: flags & 1 ? dataBlock.decode(state) : null,
      hash: flags & 2 ? dataHash.decode(state) : null,
      seek: flags & 4 ? dataSeek.decode(state) : null,
      upgrade: flags & 8 ? dataUpgrade.decode(state) : null,
      manifest: flags & 16 ? manifest.decode(state) : null
    }
  }
}

wire.noData = {
  preencode (state, m) {
    c.uint.preencode(state, m.request)
  },
  encode (state, m) {
    c.uint.encode(state, m.request)
  },
  decode (state, m) {
    return {
      request: c.uint.decode(state)
    }
  }
}

wire.want = {
  preencode (state, m) {
    c.uint.preencode(state, m.start)
    c.uint.preencode(state, m.length)
  },
  encode (state, m) {
    c.uint.encode(state, m.start)
    c.uint.encode(state, m.length)
  },
  decode (state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

wire.unwant = {
  preencode (state, m) {
    c.uint.preencode(state, m.start)
    c.uint.preencode(state, m.length)
  },
  encode (state, m) {
    c.uint.encode(state, m.start)
    c.uint.encode(state, m.length)
  },
  decode (state, m) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

wire.range = {
  preencode (state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.start)
    if (m.length !== 1) c.uint.preencode(state, m.length)
  },
  encode (state, m) {
    c.uint.encode(state, (m.drop ? 1 : 0) | (m.length === 1 ? 2 : 0))
    c.uint.encode(state, m.start)
    if (m.length !== 1) c.uint.encode(state, m.length)
  },
  decode (state) {
    const flags = c.uint.decode(state)

    return {
      drop: (flags & 1) !== 0,
      start: c.uint.decode(state),
      length: (flags & 2) !== 0 ? 1 : c.uint.decode(state)
    }
  }
}

wire.bitfield = {
  preencode (state, m) {
    c.uint.preencode(state, m.start)
    c.uint32array.preencode(state, m.bitfield)
  },
  encode (state, m) {
    c.uint.encode(state, m.start)
    c.uint32array.encode(state, m.bitfield)
  },
  decode (state, m) {
    return {
      start: c.uint.decode(state),
      bitfield: c.uint32array.decode(state)
    }
  }
}

wire.sync = {
  preencode (state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.fork)
    c.uint.preencode(state, m.length)
    c.uint.preencode(state, m.remoteLength)
  },
  encode (state, m) {
    c.uint.encode(state, (m.canUpgrade ? 1 : 0) | (m.uploading ? 2 : 0) | (m.downloading ? 4 : 0) | (m.hasManifest ? 8 : 0))
    c.uint.encode(state, m.fork)
    c.uint.encode(state, m.length)
    c.uint.encode(state, m.remoteLength)
  },
  decode (state) {
    const flags = c.uint.decode(state)

    return {
      fork: c.uint.decode(state),
      length: c.uint.decode(state),
      remoteLength: c.uint.decode(state),
      canUpgrade: (flags & 1) !== 0,
      uploading: (flags & 2) !== 0,
      downloading: (flags & 4) !== 0,
      hasManifest: (flags & 8) !== 0
    }
  }
}

wire.reorgHint = {
  preencode (state, m) {
    c.uint.preencode(state, m.from)
    c.uint.preencode(state, m.to)
    c.uint.preencode(state, m.ancestors)
  },
  encode (state, m) {
    c.uint.encode(state, m.from)
    c.uint.encode(state, m.to)
    c.uint.encode(state, m.ancestors)
  },
  decode (state) {
    return {
      from: c.uint.encode(state),
      to: c.uint.encode(state),
      ancestors: c.uint.encode(state)
    }
  }
}

wire.extension = {
  preencode (state, m) {
    c.string.preencode(state, m.name)
    c.raw.preencode(state, m.message)
  },
  encode (state, m) {
    c.string.encode(state, m.name)
    c.raw.encode(state, m.message)
  },
  decode (state) {
    return {
      name: c.string.decode(state),
      message: c.raw.decode(state)
    }
  }
}

const keyValue = {
  preencode (state, p) {
    c.string.preencode(state, p.key)
    c.optionalBuffer.preencode(state, p.value)
  },
  encode (state, p) {
    c.string.encode(state, p.key)
    c.optionalBuffer.encode(state, p.value)
  },
  decode (state) {
    return {
      key: c.string.decode(state),
      value: c.optionalBuffer.decode(state)
    }
  }
}

const treeUpgrade = {
  preencode (state, u) {
    c.uint.preencode(state, u.fork)
    c.uint.preencode(state, u.ancestors)
    c.uint.preencode(state, u.length)
    c.optionalBuffer.preencode(state, u.signature)
  },
  encode (state, u) {
    c.uint.encode(state, u.fork)
    c.uint.encode(state, u.ancestors)
    c.uint.encode(state, u.length)
    c.optionalBuffer.encode(state, u.signature)
  },
  decode (state) {
    return {
      fork: c.uint.decode(state),
      ancestors: c.uint.decode(state),
      length: c.uint.decode(state),
      signature: c.optionalBuffer.decode(state)
    }
  }
}

const bitfieldUpdate = { // TODO: can maybe be folded into a HAVE later on with the most recent spec
  preencode (state, b) {
    state.end++ // flags
    c.uint.preencode(state, b.start)
    c.uint.preencode(state, b.length)
  },
  encode (state, b) {
    state.buffer[state.start++] = b.drop ? 1 : 0
    c.uint.encode(state, b.start)
    c.uint.encode(state, b.length)
  },
  decode (state) {
    const flags = c.uint.decode(state)
    return {
      drop: (flags & 1) !== 0,
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

const oplog = exports.oplog = {}

oplog.entry = {
  preencode (state, m) {
    state.end++ // flags
    if (m.userData) keyValue.preencode(state, m.userData)
    if (m.treeNodes) nodeArray.preencode(state, m.treeNodes)
    if (m.treeUpgrade) treeUpgrade.preencode(state, m.treeUpgrade)
    if (m.bitfield) bitfieldUpdate.preencode(state, m.bitfield)
  },
  encode (state, m) {
    const s = state.start++
    let flags = 0

    if (m.userData) {
      flags |= 1
      keyValue.encode(state, m.userData)
    }
    if (m.treeNodes) {
      flags |= 2
      nodeArray.encode(state, m.treeNodes)
    }
    if (m.treeUpgrade) {
      flags |= 4
      treeUpgrade.encode(state, m.treeUpgrade)
    }
    if (m.bitfield) {
      flags |= 8
      bitfieldUpdate.encode(state, m.bitfield)
    }

    state.buffer[s] = flags
  },
  decode (state) {
    const flags = c.uint.decode(state)
    return {
      userData: (flags & 1) !== 0 ? keyValue.decode(state) : null,
      treeNodes: (flags & 2) !== 0 ? nodeArray.decode(state) : null,
      treeUpgrade: (flags & 4) !== 0 ? treeUpgrade.decode(state) : null,
      bitfield: (flags & 8) !== 0 ? bitfieldUpdate.decode(state) : null
    }
  }
}

const keyPair = {
  preencode (state, kp) {
    c.optionalBuffer.preencode(state, kp.publicKey)
    c.optionalBuffer.preencode(state, kp.secretKey)
  },
  encode (state, kp) {
    c.optionalBuffer.encode(state, kp.publicKey)
    c.optionalBuffer.encode(state, kp.secretKey)
  },
  decode (state) {
    return {
      publicKey: c.optionalBuffer.decode(state),
      secretKey: c.optionalBuffer.decode(state)
    }
  }
}

const reorgHint = {
  preencode (state, r) {
    c.uint.preencode(state, r.from)
    c.uint.preencode(state, r.to)
    c.uint.preencode(state, r.ancestors)
  },
  encode (state, r) {
    c.uint.encode(state, r.from)
    c.uint.encode(state, r.to)
    c.uint.encode(state, r.ancestors)
  },
  decode (state) {
    return {
      from: c.uint.decode(state),
      to: c.uint.decode(state),
      ancestors: c.uint.decode(state)
    }
  }
}

const reorgHintArray = c.array(reorgHint)

const hints = {
  preencode (state, h) {
    reorgHintArray.preencode(state, h.reorgs)
    c.uint.preencode(state, h.contiguousLength)
  },
  encode (state, h) {
    reorgHintArray.encode(state, h.reorgs)
    c.uint.encode(state, h.contiguousLength)
  },
  decode (state) {
    return {
      reorgs: reorgHintArray.decode(state),
      contiguousLength: state.start < state.end ? c.uint.decode(state) : 0
    }
  }
}

const treeHeader = {
  preencode (state, t) {
    c.uint.preencode(state, t.fork)
    c.uint.preencode(state, t.length)
    c.optionalBuffer.preencode(state, t.rootHash)
    c.optionalBuffer.preencode(state, t.signature)
  },
  encode (state, t) {
    c.uint.encode(state, t.fork)
    c.uint.encode(state, t.length)
    c.optionalBuffer.encode(state, t.rootHash)
    c.optionalBuffer.encode(state, t.signature)
  },
  decode (state) {
    return {
      fork: c.uint.decode(state),
      length: c.uint.decode(state),
      rootHash: c.optionalBuffer.decode(state),
      signature: c.optionalBuffer.decode(state)
    }
  }
}

const types = {
  preencode (state, t) {
    c.string.preencode(state, t.tree)
    c.string.preencode(state, t.bitfield)
    c.string.preencode(state, t.signer)
  },
  encode (state, t) {
    c.string.encode(state, t.tree)
    c.string.encode(state, t.bitfield)
    c.string.encode(state, t.signer)
  },
  decode (state) {
    return {
      tree: c.string.decode(state),
      bitfield: c.string.decode(state),
      signer: c.string.decode(state)
    }
  }
}

const externalHeader = {
  preencode (state, m) {
    c.uint.preencode(state, m.start)
    c.uint.preencode(state, m.length)
  },
  encode (state, m) {
    c.uint.encode(state, m.start)
    c.uint.encode(state, m.length)
  },
  decode (state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

const keyValueArray = c.array(keyValue)

oplog.header = {
  preencode (state, h) {
    state.end += 2 // version + flags
    if (h.external) {
      externalHeader.preencode(state, h.external)
      return
    }
    c.fixed32.preencode(state, h.key)
    if (h.manifest) manifest.preencode(state, h.manifest)
    if (h.keyPair) keyPair.preencode(state, h.keyPair)
    keyValueArray.preencode(state, h.userData)
    treeHeader.preencode(state, h.tree)
    hints.preencode(state, h.hints)
  },
  encode (state, h) {
    c.uint.encode(state, 1)
    if (h.external) {
      c.uint.encode(state, 1) // ONLY set the first big for clarity
      externalHeader.encode(state, h.external)
      return
    }
    c.uint.encode(state, (h.manifest ? 2 : 0) | (h.keyPair ? 4 : 0))
    c.fixed32.encode(state, h.key)
    if (h.manifest) manifest.encode(state, h.manifest)
    if (h.keyPair) keyPair.encode(state, h.keyPair)
    keyValueArray.encode(state, h.userData)
    treeHeader.encode(state, h.tree)
    hints.encode(state, h.hints)
  },
  decode (state) {
    const version = c.uint.decode(state)

    if (version > 1) {
      throw new Error('Invalid header version. Expected <= 1, got ' + version)
    }

    if (version === 0) {
      const old = {
        types: types.decode(state),
        userData: keyValueArray.decode(state),
        tree: treeHeader.decode(state),
        signer: keyPair.decode(state),
        hints: hints.decode(state)
      }

      return {
        external: null,
        key: old.signer.publicKey,
        manifest: {
          version: 0,
          hash: old.types.tree,
          allowPatch: false,
          quorum: 1,
          signers: [{
            signature: old.types.signer,
            namespace: DEFAULT_NAMESPACE,
            publicKey: old.signer.publicKey
          }],
          prologue: null
        },
        keyPair: old.signer.secretKey ? old.signer : null,
        userData: old.userData,
        tree: old.tree,
        hints: old.hints
      }
    }

    const flags = c.uint.decode(state)

    if (flags & 1) {
      return {
        external: externalHeader.decode(state),
        key: null,
        manifest: null,
        keyPair: null,
        userData: null,
        tree: null,
        hints: null
      }
    }

    return {
      external: null,
      key: c.fixed32.decode(state),
      manifest: (flags & 2) !== 0 ? manifest.decode(state) : null,
      keyPair: (flags & 4) !== 0 ? keyPair.decode(state) : null,
      userData: keyValueArray.decode(state),
      tree: treeHeader.decode(state),
      hints: hints.decode(state)
    }
  }
}

const uintArray = c.array(c.uint)

const multisigInput = {
  preencode (state, inp) {
    c.uint.preencode(state, inp.signer)
    c.fixed64.preencode(state, inp.signature)
    c.uint.preencode(state, inp.patch)
  },
  encode (state, inp) {
    c.uint.encode(state, inp.signer)
    c.fixed64.encode(state, inp.signature)
    c.uint.encode(state, inp.patch)
  },
  decode (state) {
    return {
      signer: c.uint.decode(state),
      signature: c.fixed64.decode(state),
      patch: c.uint.decode(state)
    }
  }
}

const patchEncodingv0 = {
  preencode (state, n) {
    c.uint.preencode(state, n.start)
    c.uint.preencode(state, n.length)
    uintArray.preencode(state, n.nodes)
  },
  encode (state, n) {
    c.uint.encode(state, n.start)
    c.uint.encode(state, n.length)
    uintArray.encode(state, n.nodes)
  },
  decode (state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state),
      nodes: uintArray.decode(state)
    }
  }
}

const multisigInputv0 = {
  preencode (state, n) {
    state.end++
    c.uint.preencode(state, n.signer)
    c.fixed64.preencode(state, n.signature)
    if (n.patch) patchEncodingv0.preencode(state, n.patch)
  },
  encode (state, n) {
    c.uint.encode(state, n.patch ? 1 : 0)
    c.uint.encode(state, n.signer)
    c.fixed64.encode(state, n.signature)
    if (n.patch) patchEncodingv0.encode(state, n.patch)
  },
  decode (state) {
    const flags = c.uint.decode(state)
    return {
      signer: c.uint.decode(state),
      signature: c.fixed64.decode(state),
      patch: (flags & 1) ? patchEncodingv0.decode(state) : null
    }
  }
}

const multisigInputArrayv0 = c.array(multisigInputv0)
const multisigInputArray = c.array(multisigInput)

const compactNode = {
  preencode (state, n) {
    c.uint.preencode(state, n.index)
    c.uint.preencode(state, n.size)
    c.fixed32.preencode(state, n.hash)
  },
  encode (state, n) {
    c.uint.encode(state, n.index)
    c.uint.encode(state, n.size)
    c.fixed32.encode(state, n.hash)
  },
  decode (state) {
    return {
      index: c.uint.decode(state),
      size: c.uint.decode(state),
      hash: c.fixed32.decode(state)
    }
  }
}

const compactNodeArray = c.array(compactNode)

exports.multiSignaturev0 = {
  preencode (state, s) {
    multisigInputArrayv0.preencode(state, s.proofs)
    compactNodeArray.preencode(state, s.patch)
  },
  encode (state, s) {
    multisigInputArrayv0.encode(state, s.proofs)
    compactNodeArray.encode(state, s.patch)
  },
  decode (state) {
    return {
      proofs: multisigInputArrayv0.decode(state),
      patch: compactNodeArray.decode(state)
    }
  }
}

exports.multiSignature = {
  preencode (state, s) {
    multisigInputArray.preencode(state, s.proofs)
    compactNodeArray.preencode(state, s.patch)
  },
  encode (state, s) {
    multisigInputArray.encode(state, s.proofs)
    compactNodeArray.encode(state, s.patch)
  },
  decode (state) {
    return {
      proofs: multisigInputArray.decode(state),
      patch: compactNodeArray.decode(state)
    }
  }
}
const c = require('compact-encoding')
const schema = require('../../encoding/spec/hyperschema')
const { core: coreKey } = require('../../lib/keys.js')
const View = require('../../lib/view.js')

const CORE_AUTH = schema.getEncoding('@core/auth')

const { CorestoreRX, CorestoreTX } = require('../../lib/tx.js')

async function core (core, { version, dryRun = false } = {}) {
  if (dryRun) return // dryRun mode not supported atm

  const rx = core.db.read({ autoDestroy: true })
  const storedAuthPromise = rx.get(coreKey.auth(core.core.corePointer))

  rx.tryFlush()

  const storedAuth = await storedAuthPromise
  if (!storedAuth) return

  const auth = c.decode(CORE_AUTH, storedAuth)
  await commitCoreMigration(auth, core, version)
}

module.exports = { core }

async function commitCoreMigration (auth, core, version) {
  const view = new View()
  const rx = new CorestoreRX(core.db, view)

  const storeCorePromise = rx.getCore(auth.discoveryKey)
  rx.tryFlush()

  const storeCore = await storeCorePromise

  storeCore.version = version

  const tx = new CorestoreTX(view)
  tx.putCore(auth.discoveryKey, storeCore)
  tx.apply()

  await View.flush(view.changes, core.db)
}
{
  "name": "hypercore-storage",
  "version": "3.2.0",
  "main": "index.js",
  "files": [
    "index.js",
    "lib/*.js",
    "encoding/*",
    "migrations/0/*.js",
    "migrations/1/*.js"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:bare": "brittle-bare test/all.js",
    "test:generate": "brittle -r test/all.js test/*.js",
    "test:node": "brittle-node test/all.js"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "description": "Storage engine for Hypercore",
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "fs/*": {
      "bare": "bare-fs/*",
      "default": "fs/*"
    },
    "os": {
      "bare": "bare-os",
      "default": "os"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    }
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/hypercore-storage.git"
  },
  "bugs": {
    "url": "https://github.com/holepunchto/hypercore-storage/issues"
  },
  "homepage": "https://github.com/holepunchto/hypercore-storage#readme",
  "dependencies": {
    "b4a": "^1.6.7",
    "bare-path": "^3.0.0",
    "compact-encoding": "^3.1.0",
    "device-file": "^2.1.2",
    "flat-tree": "^1.12.1",
    "hypercore-crypto": "^3.4.2",
    "hyperschema": "^1.21.0",
    "index-encoder": "^3.3.2",
    "resolve-reject-promise": "^1.0.0",
    "rocksdb-native": "^3.11.0",
    "scope-lock": "^1.2.4",
    "streamx": "^2.21.1",
    "xache": "^1.2.1"
  },
  "devDependencies": {
    "bare-os": "^3.9.1",
    "brittle": "^3.7.0",
    "hypercore-storage-2.9.0": "npm:hypercore-storage@^2.9.0",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "test-tmp": "^1.3.1"
  }
}
const { EventEmitter } = require('events')
const isOptions = require('is-options')
const crypto = require('hypercore-crypto')
const CoreStorage = require('hypercore-storage')
const c = require('compact-encoding')
const b4a = require('b4a')
const NoiseSecretStream = require('@hyperswarm/secret-stream')
const Protomux = require('protomux')
const id = require('hypercore-id-encoding')
const safetyCatch = require('safety-catch')
const unslab = require('unslab')
const flat = require('flat-tree')
const assert = require('nanoassert')

const { SMALL_WANTS } = require('./lib/feature-flags')
const { UPDATE_COMPAT } = require('./lib/wants')
const MarkBitfield = require('./lib/mark-bitfield')

const inspect = require('./lib/inspect')
const Core = require('./lib/core')
const Info = require('./lib/info')
const Download = require('./lib/download')
const DefaultEncryption = require('./lib/default-encryption')
const caps = require('./lib/caps')
const Replicator = require('./lib/replicator')
const { manifestHash, createManifest } = require('./lib/verifier')
const { ReadStream, WriteStream, ByteStream } = require('./lib/streams')
const { MerkleTree } = require('./lib/merkle-tree')
const { proof, verify } = require('./lib/fully-remote-proof')
const {
  ASSERTION,
  BAD_ARGUMENT,
  SESSION_CLOSED,
  SESSION_MOVED,
  SESSION_NOT_WRITABLE,
  SNAPSHOT_NOT_AVAILABLE,
  DECODING_ERROR,
  REQUEST_CANCELLED
} = require('hypercore-errors')

// Hypercore actually does not have any notion of max/min block sizes
// but we enforce 15mb to ensure smooth replication (each block is transmitted atomically)
const MAX_SUGGESTED_BLOCK_SIZE = 15 * 1024 * 1024

class Hypercore extends EventEmitter {
  constructor(storage, key, opts) {
    super()

    if (isOptions(storage) && !storage.db) {
      opts = storage
      storage = null
      key = opts.key || null
    } else if (isOptions(key)) {
      opts = key
      key = opts.key || null
    }

    if (key && typeof key === 'string') key = id.decode(key)
    if (!opts) opts = {}

    if (!storage) storage = opts.storage

    this.core = null
    this.state = null
    this.encryption = null
    this.extensions = new Map()

    this.valueEncoding = null
    this.encodeBatch = null
    this.activeRequests = []
    this.sessions = null
    this.ongc = null

    this.keyPair = opts.keyPair || null
    this.readable = true
    this.writable = false
    this.exclusive = false
    this.opened = false
    this.closed = false
    this.weak = !!opts.weak
    this.snapshotted = !!opts.snapshot
    this.onseq = opts.onseq || null
    this.onwait = opts.onwait || null
    this.wait = opts.wait !== false
    this.timeout = opts.timeout || 0
    this.preload = null
    this.closing = null
    this.opening = null

    this._readonly = opts.writable === false
    this._preappend = preappend.bind(this)
    this._snapshot = null
    this._findingPeers = 0
    this._active = opts.weak ? !!opts.active : opts.active !== false

    this.waits = 0

    // Mark & Sweep GC
    this._marking = false
    this._marks = null

    this._sessionIndex = -1
    this._stateIndex = -1 // maintained by session state
    this._monitorIndex = -1 // maintained by replication state

    this.opening = this._open(storage, key, opts)
    this.opening.catch(safetyCatch)

    this.on('newListener', maybeAddMonitor)
  }

  [Symbol.for('nodejs.util.inspect.custom')](depth, opts) {
    return inspect(this, depth, opts)
  }

  static MAX_SUGGESTED_BLOCK_SIZE = MAX_SUGGESTED_BLOCK_SIZE

  static DefaultEncryption = DefaultEncryption

  static SMALL_WANTS = SMALL_WANTS

  static enable(flag) {
    const enableCompat = (flag & SMALL_WANTS) === 0
    UPDATE_COMPAT(enableCompat)
  }

  static setRecoveryPeers(peers) {
    Core.setRecoveryPeers(peers)
  }

  static key(manifest, { compat, version, namespace } = {}) {
    if (b4a.isBuffer(manifest)) {
      manifest = { version, signers: [{ publicKey: manifest, namespace }] }
    }
    return compat ? manifest.signers[0].publicKey : manifestHash(createManifest(manifest))
  }

  static discoveryKey(key) {
    return crypto.discoveryKey(key)
  }

  static blockEncryptionKey(key, encryptionKey) {
    return DefaultEncryption.blockEncryptionKey(key, encryptionKey)
  }

  static getProtocolMuxer(stream) {
    return stream.noiseStream.userData
  }

  static createCore(storage, opts) {
    return new Core(Hypercore.defaultStorage(storage), { autoClose: false, ...opts })
  }

  static createProtocolStream(isInitiator, opts = {}) {
    let outerStream = Protomux.isProtomux(isInitiator)
      ? isInitiator.stream
      : isStream(isInitiator)
        ? isInitiator
        : opts.stream

    let noiseStream = null

    if (outerStream) {
      noiseStream = outerStream.noiseStream
    } else {
      noiseStream = new NoiseSecretStream(isInitiator, null, opts)
      outerStream = noiseStream.rawStream
    }
    if (!noiseStream) throw BAD_ARGUMENT('Invalid stream', this.discoveryKey)

    if (!noiseStream.userData) {
      const protocol = Protomux.from(noiseStream)

      if (opts.keepAlive !== false && noiseStream.keepAlive === 0) {
        noiseStream.setKeepAlive(5000)
      }
      noiseStream.userData = protocol
    }

    if (opts.ondiscoverykey) {
      const ondiscoverykey = createDiscoveryKeyHandler(opts.ondiscoverykey)
      noiseStream.userData.pair({ protocol: 'hypercore/alpha' }, ondiscoverykey)
    }

    return outerStream
  }

  static defaultStorage(storage, opts = {}) {
    if (CoreStorage.isCoreStorage(storage)) return storage

    const directory = storage
    return new CoreStorage(directory, opts)
  }

  static clearRequests(session, err) {
    Replicator.clearRequests(session, err)
  }

  static destroyRequests(session, err) {
    if (isRequestsDestroyed(session)) return
    Replicator.clearRequests(session, err)
    session.push(null) // mark as dead
  }

  static async treeHashFromStorage(session, length = session.length) {
    const roots = await MerkleTree.getRoots(session.state, length)
    return crypto.tree(roots)
  }

  snapshot(opts) {
    return this.session({ ...opts, snapshot: true })
  }

  compact() {
    return this.core.compact()
  }

  session(opts = {}) {
    if (this.closing) {
      // This makes the closing logic a lot easier. If this turns out to be a problem
      // in practice, open an issue and we'll try to make a solution for it.
      throw SESSION_CLOSED('Cannot make sessions on a closing core', this.discoveryKey)
    }
    if (opts.checkout !== undefined && !opts.name && !opts.atom) {
      throw ASSERTION('Checkouts are only supported on atoms or named sessions', this.discoveryKey)
    }

    const wait = opts.wait === false ? false : this.wait
    const writable = opts.writable === undefined ? !this._readonly : opts.writable === true
    const onwait = opts.onwait === undefined ? this.onwait : opts.onwait
    const onseq = opts.onseq === undefined ? this.onseq : opts.onseq
    const timeout = opts.timeout === undefined ? this.timeout : opts.timeout
    const weak = opts.weak === undefined ? this.weak : opts.weak
    const marking = this._marking
    const marks = this._marks
    const Clz = opts.class || Hypercore
    const s = new Clz(null, this.key, {
      ...opts,
      wait,
      onwait,
      onseq,
      timeout,
      writable,
      weak,
      parent: this
    })
    s._marking = marking
    s._marks = marks

    return s
  }

  async setEncryptionKey(key, opts) {
    if (!this.opened) await this.opening
    const encryption = this._getEncryptionProvider({ key, block: !!(opts && opts.block) })
    return this.setEncryption(encryption)
  }

  async setEncryption(encryption) {
    if (!this.opened) await this.opening

    if (encryption === null) {
      this.encryption = encryption
      return
    }

    if (!isEncryptionProvider(encryption)) {
      throw ASSERTION('Provider does not satisfy HypercoreEncryption interface', this.discoveryKey)
    }

    this.encryption = encryption
  }

  async setGroup(topic) {
    if (!this.opened) await this.opening
    return this.core.setGroup(topic)
  }

  setKeyPair(keyPair) {
    this.keyPair = keyPair
  }

  setActive(bool) {
    const active = !!bool
    if (active === this._active || this.closing) return
    this._active = active
    if (!this.opened) return
    this.core.replicator.updateActivity(this._active ? 1 : -1)
  }

  async _open(storage, key, opts) {
    const preload = opts.preload || (opts.parent && opts.parent.preload)

    if (preload) {
      this.sessions = [] // in case someone looks at it like with peers
      this.preload = preload
      opts = { ...opts, ...(await this.preload) }
      this.preload = null
    }

    const parent = opts.parent || null
    const core = opts.core || (parent && parent.core)
    const sessions = opts.sessions || (parent && parent.sessions)
    const ongc = opts.ongc || (parent && parent.ongc)

    if (core) this.core = core
    if (ongc) this.ongc = ongc
    if (sessions) this.sessions = sessions

    if (this.sessions === null) this.sessions = []
    this._sessionIndex = this.sessions.push(this) - 1

    if (this.core === null) initOnce(this, storage, key, opts)
    if (this._monitorIndex === -2) this.core.addMonitor(this)

    try {
      await this._openSession(opts)
    } catch (err) {
      if (this.core.autoClose && this.core.hasSession() === false) await this.core.close()

      if (this.exclusive) this.core.unlockExclusive()

      this.core.removeMonitor(this)
      this._removeSession()

      if (this.state !== null) this.state.removeSession(this)

      this.closed = true
      this.emit('close')
      throw err
    }

    // Setup automatic recovery if in repair mode
    if (this.core._repairMode) {
      const recoverTreeNodeFromPeersBound = this.recoverTreeNodeFromPeers.bind(this)
      this.once('repaired', () => {
        this.off('peer-add', recoverTreeNodeFromPeersBound)
      })
      this.on('peer-add', recoverTreeNodeFromPeersBound)
    }

    this.emit('ready')

    // if we are a weak session the core might have closed...
    if (this.core.closing) this.close().catch(safetyCatch)
  }

  _removeSession() {
    if (this._sessionIndex === -1) return
    const head = this.sessions.pop()
    if (head !== this) this.sessions[(head._sessionIndex = this._sessionIndex)] = head
    this._sessionIndex = -1
    if (this.ongc !== null) this.ongc(this)
  }

  async _openSession(opts) {
    if (this.core.opened === false) await this.core.ready()

    if (this.keyPair === null) this.keyPair = opts.keyPair || this.core.header.keyPair

    const parent = opts.parent || null
    if (parent && parent.encryption) this.encryption = parent.encryption

    const e = getEncryptionOption(opts)
    if (!this.encryption) this.encryption = this._getEncryptionProvider(e)

    this.writable = this._isWritable()

    if (opts.valueEncoding) {
      this.valueEncoding = c.from(opts.valueEncoding)
    }
    if (opts.encodeBatch) {
      this.encodeBatch = opts.encodeBatch
    }

    // one session sets for pushOnly for all
    if (opts.pushOnly === true) {
      this.core.replicator.setPushOnly(true)
    }

    if (parent) {
      if (parent._stateIndex === -1) await parent.ready()
      if (!this.keyPair) this.keyPair = parent.keyPair

      const ps = parent.state

      if (ps) {
        const shouldSnapshot = this.snapshotted && !ps.isSnapshot()
        this.state = shouldSnapshot ? await ps.snapshot() : ps.ref()
      }

      if (this.snapshotted && this.core && !this._snapshot) {
        this._updateSnapshot()
      }
    }

    if (opts.exclusive && opts.writable !== false) {
      this.exclusive = true
      await this.core.lockExclusive()
    }

    const parentState = parent ? parent.state : this.core.state
    const checkout = opts.checkout === undefined ? -1 : opts.checkout
    const state = this.state

    if (opts.atom) {
      this.state = await parentState.createSession(null, false, opts.atom)
      if (state) state.unref()
    } else if (opts.name) {
      // todo: need to make named sessions safe before ready
      // atm we always copy the state in passCapabilities
      this.state = await parentState.createSession(opts.name, !!opts.overwrite, null)
      if (state) state.unref() // ref'ed above in setup session
    }

    if (this.state && checkout !== -1) {
      if (!opts.name && !opts.atom) {
        throw ASSERTION('Checkouts must be named or atomized', this.discoveryKey)
      }
      if (checkout > this.state.length) {
        throw ASSERTION(
          `Invalid checkout ${checkout} for ${opts.name}, length is ${this.state.length}`,
          this.discoveryKey
        )
      }
      if (this.state.prologue && checkout < this.state.prologue.length) {
        throw ASSERTION(
          `Invalid checkout ${checkout} for ${opts.name}, prologue length is ${this.state.prologue.length}`,
          this.discoveryKey
        )
      }
      if (checkout < this.state.length) await this.state.truncate(checkout, this.fork)
    }

    if (this.state === null) {
      this.state = this.core.state.ref()
    }

    this.writable = this._isWritable()

    if (this.snapshotted && this.core) this._updateSnapshot()

    this.state.addSession(this)
    // TODO: we need to rework the core reference flow, as the state and session do not always agree now due to moveTo
    this.core = this.state.core // in case it was wrong...

    if (opts.userData) {
      const tx = this.state.storage.write()
      for (const [key, value] of Object.entries(opts.userData)) {
        tx.putUserData(key, value)
      }
      await tx.flush()
    }

    if (opts.manifest && !this.core.header.manifest) {
      await this.core.setManifest(createManifest(opts.manifest))
    }

    this.core.replicator.updateActivity(this._active ? 1 : 0)

    this.opened = true
  }

  get replicator() {
    return this.core === null ? null : this.core.replicator
  }

  _getSnapshot() {
    return {
      length: this.state.length,
      byteLength: this.state.byteLength,
      fork: this.state.fork
    }
  }

  _updateSnapshot() {
    const prev = this._snapshot
    const next = (this._snapshot = this._getSnapshot())

    if (!prev) return true
    return prev.length !== next.length || prev.fork !== next.fork
  }

  _isWritable() {
    if (this._readonly) return false
    if (this.state && !this.state.isDefault()) return true
    return !!(this.keyPair && this.keyPair.secretKey)
  }

  close({ error } = {}) {
    if (this.closing) return this.closing

    this.closing = this._close(error || null)
    return this.closing
  }

  clearRequests(activeRequests, error) {
    if (!activeRequests.length) return
    if (this.core) this.core.replicator.clearRequests(activeRequests, error)
  }

  async _close(error) {
    if (this.opened === false) {
      try {
        await this.opening
      } catch (err) {
        if (!this.closed) throw err
      }
    }

    if (this.closed === true) return

    this.core.removeMonitor(this)
    this.state.removeSession(this)
    this._removeSession()

    this.readable = false
    this.writable = false
    this.opened = false

    const gc = []
    for (const ext of this.extensions.values()) {
      if (ext.session === this) gc.push(ext)
    }
    for (const ext of gc) ext.destroy()

    this.core.replicator.findingPeers -= this._findingPeers
    this.core.replicator.clearRequests(this.activeRequests, error)
    this.core.replicator.updateActivity(this._active ? -1 : 0)

    this._findingPeers = 0

    this.state.unref()

    if (this.exclusive) this.core.unlockExclusive()

    if (this.core.hasSession()) {
      // emit "fake" close as this is a session
      this.closed = true
      this.emit('close')
      return
    }

    if (this.core.autoClose) await this.core.close()

    this.closed = true
    this.emit('close')
  }

  async commit(session, opts) {
    await this.ready()
    await session.ready()

    return this.state.commit(session.state, { keyPair: this.keyPair, ...opts })
  }

  replicate(isInitiator, opts = {}) {
    // Only limitation here is that ondiscoverykey doesn't work atm when passing a muxer directly,
    // because it doesn't really make a lot of sense.
    if (Protomux.isProtomux(isInitiator)) return this._attachToMuxer(isInitiator)

    // if same stream is passed twice, ignore the 2nd one before we make sessions etc
    if (isStream(isInitiator) && this._isAttached(isInitiator)) return isInitiator

    const protocolStream = Hypercore.createProtocolStream(isInitiator, opts)
    const noiseStream = protocolStream.noiseStream
    const protocol = noiseStream.userData

    this._attachToMuxer(protocol)

    return protocolStream
  }

  _isAttached(stream) {
    return (
      stream.userData &&
      this.core &&
      this.core.replicator &&
      this.core.replicator.attached(stream.userData)
    )
  }

  _attachToMuxer(mux) {
    if (this.opened) {
      this.core.replicator.attachTo(mux)
    } else {
      this.opening.then(() => this.core.replicator.attachTo(mux), mux.destroy.bind(mux))
    }

    return mux
  }

  get id() {
    return this.core === null ? null : this.core.id
  }

  get key() {
    return this.core === null ? null : this.core.key
  }

  get discoveryKey() {
    return this.core === null ? null : this.core.discoveryKey
  }

  get manifest() {
    return this.core === null ? null : this.core.manifest
  }

  get length() {
    if (this._snapshot) return this._snapshot.length
    return this.opened === false ? 0 : this.state.length
  }

  get signedLength() {
    return this.opened === false ? 0 : this.state.signedLength()
  }

  /**
   * Deprecated. Use `const { byteLength } = await core.info()`.
   */
  get byteLength() {
    if (this.opened === false) return 0
    if (this._snapshot) return this._snapshot.byteLength
    return this.state.byteLength - this.state.length * this.padding
  }

  get remoteContiguousLength() {
    if (this.opened === false) return 0
    return Math.min(this.core.state.length, this.core.header.hints.remoteContiguousLength)
  }

  get contiguousLength() {
    if (this.opened === false) return 0
    return Math.min(this.core.state.length, this.core.header.hints.contiguousLength)
  }

  get contiguousByteLength() {
    return 0
  }

  get fork() {
    if (this.opened === false) return 0
    return this.state.fork
  }

  get padding() {
    if (this.encryption && this.key && this.manifest) {
      return this.encryption.padding(this.core, this.length)
    }

    return 0
  }

  get peers() {
    return this.opened === false ? [] : this.core.replicator.peers
  }

  get globalCache() {
    return this.opened === false ? null : this.core.globalCache
  }

  get recovering() {
    return this.opened === false ? 0 : this.core.header.hints.recovering
  }

  ready() {
    return this.opening
  }

  async recover() {
    if (this.opened === false) await this.opening
    return this.state.waitForRecovery()
  }

  async setUserData(key, value) {
    if (this.opened === false) await this.opening
    const existing = await this.getUserData(key)
    if (existing && b4a.isBuffer(value) && b4a.equals(existing, value)) return
    await this.state.setUserData(key, value)
  }

  async getUserData(key) {
    if (this.opened === false) await this.opening
    const batch = this.state.storage.read()
    const p = batch.getUserData(key)
    batch.tryFlush()
    return p
  }

  transferSession(core) {
    // todo: validate we can move

    if (this.weak === false) {
      this.core.activeSessions--
      core.activeSessions++
    }

    if (this._monitorIndex >= 0) {
      this.core.removeMonitor(this)
      core.addMonitor(this)
    }

    const old = this.core

    this.core = core

    old.replicator.clearRequests(this.activeRequests, SESSION_MOVED())

    this.emit('migrate', this.key)
  }

  findingPeers() {
    this._findingPeers++
    if (this.core !== null && !this.closing) this.core.replicator.findingPeers++

    let once = true

    return () => {
      if (this.closing || !once) return
      once = false
      this._findingPeers--
      if (this.core !== null && --this.core.replicator.findingPeers === 0) {
        this.core.replicator.queueUpdateAll()
      }
    }
  }

  async info(opts) {
    if (this.opened === false) await this.opening

    return Info.from(this, opts)
  }

  async update(opts) {
    if (this.opened === false) await this.opening
    if (this.closing !== null) return false
    if (this.snapshotted) return false

    if (this.writable && (!opts || opts.force !== true)) return false

    const remoteWait = this._shouldWait(opts, this.core.replicator.findingPeers > 0)

    let upgraded = false

    if (await this.core.replicator.applyPendingReorg()) {
      upgraded = true
    }

    if (!upgraded && remoteWait) {
      const activeRequests = (opts && opts.activeRequests) || this.activeRequests
      if (isRequestsDestroyed(activeRequests)) throw REQUEST_CANCELLED()

      const req = this.core.replicator.addUpgrade(activeRequests)

      try {
        upgraded = await req.promise
      } catch (err) {
        if (isSessionMoved(err)) return this.update(opts)
        throw err
      }
    }

    if (!upgraded) return false
    return true
  }

  async seek(bytes, opts) {
    if (this.opened === false) await this.opening
    if (!isValidIndex(bytes)) throw ASSERTION('seek is invalid', this.discoveryKey)

    const activeRequests = (opts && opts.activeRequests) || this.activeRequests
    if (isRequestsDestroyed(activeRequests)) throw REQUEST_CANCELLED()

    if (this.encryption && !this.core.manifest) {
      const req = this.replicator.addUpgrade(activeRequests)
      try {
        await req.promise
      } catch (err) {
        if (isSessionMoved(err)) return this.seek(bytes, opts)
        throw err
      }
    }

    const s = MerkleTree.seek(this.state, bytes, this.padding)

    const offset = await s.update()
    if (offset) return offset

    if (this.closing !== null) {
      throw SESSION_CLOSED('cannot seek on a closed session', this.discoveryKey)
    }

    if (!this._shouldWait(opts, this.wait)) return null

    if (isRequestsDestroyed(activeRequests)) throw REQUEST_CANCELLED()
    const req = this.core.replicator.addSeek(activeRequests, s)

    const timeout = opts && opts.timeout !== undefined ? opts.timeout : this.timeout
    if (timeout) req.context.setTimeout(req, timeout)

    try {
      return await req.promise
    } catch (err) {
      if (isSessionMoved(err)) return this.seek(bytes, opts)
      throw err
    }
  }

  async has(start, end = start + 1) {
    if (this.opened === false) await this.opening
    if (!isValidIndex(start) || !isValidIndex(end)) {
      throw ASSERTION('has range is invalid', this.discoveryKey)
    }

    if (this.state.isDefault()) {
      if (end === start + 1) return this.core.bitfield.get(start)

      const i = this.core.bitfield.firstUnset(start)
      return i === -1 || i >= end
    }

    if (end === start + 1) {
      const rx = this.state.storage.read()
      const block = rx.getBlock(start)
      rx.tryFlush()

      return (await block) !== null
    }

    let count = 0

    const stream = this.state.storage.createBlockStream({ gte: start, lt: end })
    for await (const block of stream) {
      if (block === null) return false
      count++
    }

    return count === end - start
  }

  async get(index, opts) {
    if (this.opened === false) await this.opening
    if (!isValidIndex(index)) throw ASSERTION('block index is invalid', this.discoveryKey)

    if (this.closing !== null) {
      throw SESSION_CLOSED('cannot get on a closed session', this.discoveryKey)
    }

    const encoding =
      (opts && opts.valueEncoding && c.from(opts.valueEncoding)) || this.valueEncoding

    if (this.onseq !== null) this.onseq(index, this)
    if (this._marking) await this.markBlock(index)

    const req = this._get(index, opts)

    let block = await req
    if (!block) return null

    if (opts && opts.raw) return block

    if (this.encryption && (!opts || opts.decrypt !== false)) {
      // Copy the block as it might be shared with other sessions.
      block = b4a.from(block)

      await this.encryption.decrypt(index, block, this.core)
    }

    return this._decode(encoding, block, index)
  }

  async clear(start, end = start + 1, opts) {
    if (this.opened === false) await this.opening
    if (this.closing !== null) {
      throw SESSION_CLOSED('cannot clear on a closed session', this.discoveryKey)
    }

    if (typeof end === 'object') {
      opts = end
      end = start + 1
    }

    if (!isValidIndex(start) || !isValidIndex(end)) {
      throw ASSERTION('clear range is invalid', this.discoveryKey)
    }

    const cleared = opts && opts.diff ? { blocks: 0 } : null

    if (start >= end) return cleared
    if (start >= this.length) return cleared

    await this.state.clear(start, end, cleared)

    return cleared
  }

  async purge() {
    await this._closeAllSessions(null)
    await this.core.purge()
  }

  async _get(index, opts) {
    const block = await readBlock(this.state.storage.read(), index)

    if (block !== null) return block

    if (this.closing !== null) {
      throw SESSION_CLOSED('cannot get on a closed session', this.discoveryKey)
    }

    // snapshot should check if core has block
    if (this._snapshot !== null) {
      checkSnapshot(this, index)
      const coreBlock = await readBlock(this.core.state.storage.read(), index)

      checkSnapshot(this, index)
      if (coreBlock !== null) return coreBlock
    }

    // lets check the bitfield to see if we got it during the above async calls
    // this is the last resort before replication, so always safe.
    if (this.core.bitfield.get(index)) {
      const coreBlock = await readBlock(this.state.storage.read(), index)
      // TODO: this should not be needed, only needed atm in case we are doing a moveTo during this (we should fix)
      if (coreBlock !== null) return coreBlock
    }

    if (!this._shouldWait(opts, this.wait)) return null

    this.waits++
    if (opts && opts.onwait) opts.onwait(index, this)
    if (this.onwait) this.onwait(index, this)

    const activeRequests = (opts && opts.activeRequests) || this.activeRequests
    if (isRequestsDestroyed(activeRequests)) throw REQUEST_CANCELLED()

    const force = opts ? opts.force === true : false
    const req = this.core.replicator.addBlock(activeRequests, index, force)
    req.snapshot = index < this.length

    const timeout = opts && opts.timeout !== undefined ? opts.timeout : this.timeout
    if (timeout) req.context.setTimeout(req, timeout)

    let replicatedBlock = null

    try {
      replicatedBlock = await req.promise
    } catch (err) {
      if (isSessionMoved(err)) return this._get(index, opts)
      throw err
    }

    if (this._snapshot !== null) checkSnapshot(this, index)
    return maybeUnslab(replicatedBlock)
  }

  _shouldWait(opts, defaultValue) {
    if (opts) {
      if (opts.wait === false) return false
      if (opts.wait === true) return true
    }
    return defaultValue
  }

  _setupMarks() {
    if (this._marks === null) {
      const storage = this.snapshotted ? this.core.state.storage : this.state.storage
      this._marks = new MarkBitfield(storage)
    }
  }

  async markBlock(start, end = start + 1) {
    if (this.opened === false) await this.opening

    this._setupMarks()

    // TODO support as single rocks batch
    const setPromises = []
    for (let i = start; i < end; i++) {
      setPromises.push(this._marks.set(i, true))
    }

    return Promise.all(setPromises)
  }

  async clearMarkings() {
    if (this.opened === false) await this.opening

    this._setupMarks()

    await this._marks.clear()
    this._marks = null
  }

  async startMarking() {
    if (this._marking) {
      throw ASSERTION("Hypercore cannot be gc'ed when already in gc mode", this.discoveryKey)
    }
    if (this.state && this.state.name) {
      throw ASSERTION("Hypercore cannot be gc'ed when a named session", this.discoveryKey)
    }
    if (this.state && this.state.storage.atom) {
      throw ASSERTION("Hypercore cannot be gc'ed when an atomic session", this.discoveryKey)
    }
    if (this.opened === false) await this.opening
    await this.clearMarkings()

    this._marking = true
  }

  async sweep({ batchSize = 1000 } = {}) {
    if (this.opened === false) await this.opening

    assert(!this.snapshotted, 'Cannot sweep a snapshot')

    // No marks - load from storage
    this._setupMarks()

    let clearing = []
    let prevIndex = this.length
    for await (const index of this._marks.createMarkStream({ reverse: true })) {
      if (index + 1 === prevIndex) {
        prevIndex = index
        continue
      }
      clearing.push(this.clear(index + 1, prevIndex))
      if (clearing.length >= batchSize) {
        await Promise.all(clearing)
        clearing = []
      }
      prevIndex = index
    }
    // Clear range from the very start if not marked
    if (prevIndex > 0) clearing.push(this.clear(0, prevIndex))
    await Promise.all(clearing)

    this._marking = false
    await this.clearMarkings()
  }

  createReadStream(opts) {
    return new ReadStream(this, opts)
  }

  createWriteStream() {
    return new WriteStream(this)
  }

  createByteStream(opts) {
    return new ByteStream(this, opts)
  }

  download(range) {
    return new Download(this, range)
  }

  // TODO: get rid of this / deprecate it?
  undownload(range) {
    range.destroy(null)
  }

  // TODO: get rid of this / deprecate it?
  cancel(request) {
    // Do nothing for now
  }

  async truncate(newLength = 0, opts = {}) {
    if (this.opened === false) await this.opening
    if (this.closing) throw SESSION_CLOSED('Cannot append to a closed session', this.discoveryKey)

    const {
      fork = this.state.fork + 1,
      keyPair = this.keyPair,
      signature = null
    } = typeof opts === 'number' ? { fork: opts } : opts

    const isDefault = this.state === this.core.state
    const writable = !this._readonly && !!(signature || (keyPair && keyPair.secretKey))
    if (isDefault && writable === false && (newLength > 0 || fork !== this.state.fork)) {
      throw SESSION_NOT_WRITABLE('cannot append to a non-writable core', this.discoveryKey)
    }

    await this.state.truncate(newLength, fork, { keyPair, signature })

    // TODO: Should propagate from an event triggered by the oplog
    if (this.state === this.core.state) this.core.replicator.updateAll()
  }

  async append(blocks, opts = {}) {
    if (this.opened === false) await this.opening
    if (this.closing) throw SESSION_CLOSED('Cannot append to a closed session', this.discoveryKey)

    const isDefault = this.state === this.core.state
    const defaultKeyPair = this.state.name === null ? this.keyPair : null

    const { keyPair = defaultKeyPair, signature = null, maxLength, postappend = null } = opts
    const writable =
      !isDefault || !!signature || !!(keyPair && keyPair.secretKey) || opts.writable === true

    if (this._readonly || writable === false) {
      throw SESSION_NOT_WRITABLE('cannot append to a readonly core', this.discoveryKey)
    }

    blocks = Array.isArray(blocks) ? blocks : [blocks]

    const preappend = this.encryption && this._preappend

    const buffers = this.encodeBatch !== null ? this.encodeBatch(blocks) : new Array(blocks.length)

    if (this.encodeBatch === null) {
      for (let i = 0; i < blocks.length; i++) {
        buffers[i] = this._encode(this.valueEncoding, blocks[i])
      }
    }
    for (const b of buffers) {
      if (b.byteLength > MAX_SUGGESTED_BLOCK_SIZE) {
        throw BAD_ARGUMENT(
          'Appended block exceeds the maximum suggested block size',
          this.discoveryKey
        )
      }
    }

    return this.state.append(buffers, { keyPair, signature, preappend, postappend, maxLength })
  }

  async signable(length = -1, fork = -1) {
    if (this.opened === false) await this.opening
    if (length === -1) length = this.length
    if (fork === -1) fork = this.fork

    return caps.treeSignable(this.key, await this.treeHash(length), length, fork)
  }

  async treeHash(length = -1) {
    if (this.opened === false) await this.opening
    if (length === -1) length = this.length
    if (length > 0 && !(await this.has(length - 1))) await this.get(length - 1)

    const roots = await MerkleTree.getRoots(this.state, length)
    return crypto.tree(roots)
  }

  async missingNodes(index) {
    if (this.opened === false) await this.opening
    return await MerkleTree.missingNodes(this.core.state, 2 * index, this.core.state.length)
  }

  async proof(opts) {
    if (this.opened === false) await this.opening
    const rx = this.state.storage.read()
    const proofPromise = MerkleTree.proof(this.state, rx, opts)
    const blockPromise = opts && opts.block ? rx.getBlock(opts.block.index) : null
    rx.tryFlush()
    const [proof, block] = await Promise.all([proofPromise, blockPromise])
    const settled = await proof.settle()
    if (block) settled.block.value = block
    return settled
  }

  async applyProof(proof, from) {
    if (this.opened === false) await this.opening
    return this.core.verify(proof, from)
  }

  async verifyFullyRemote(proof) {
    if (this.opened === false) await this.opening
    const batch = await MerkleTree.verifyFullyRemote(this.state, proof)
    await this.core._verifyBatchUpgrade(batch, proof.manifest)
    return batch
  }

  generateRemoteProofForTreeNode(treeNodeIndex) {
    const blockProofIndex = flat.rightSpan(treeNodeIndex) / 2
    return proof(this, {
      index: blockProofIndex,
      // + 1 to length so the block is included
      upgrade: { start: 0, length: blockProofIndex + 1 }
    })
  }

  async recoverFromRemoteProof(remoteProof) {
    this.core.replicator.setPushOnly(true)
    this.core._repairMode = true

    await this.core.state.mutex.lock()

    try {
      const p = await verify(this.core.db, remoteProof)
      if (!p) return false

      const tx = this.core.storage.write()
      for (const node of p.proof.upgrade.nodes) {
        tx.putTreeNode(node)
      }
      await tx.flush()

      const succeed = p.proof.upgrade.nodes.length !== 0
      if (succeed) {
        this.core.replicator.setPushOnly(false)
      }
      return succeed
    } finally {
      this.core.state.mutex.unlock()
    }
  }

  recoverTreeNodeFromPeers() {
    this.core.replicator.setPushOnly(true)

    for (const peer of this.core.replicator.peers) {
      const req = {
        id: 0,
        fork: this.fork,
        upgrade: {
          start: 0,
          length: this.length
        }
      }
      peer.wireRequest.send(req)
    }
  }

  registerExtension(name, handlers = {}) {
    if (this.extensions.has(name)) {
      const ext = this.extensions.get(name)
      ext.handlers = handlers
      ext.encoding = c.from(handlers.encoding || c.buffer)
      ext.session = this
      return ext
    }

    const ext = {
      name,
      handlers,
      encoding: c.from(handlers.encoding || c.buffer),
      session: this,
      send(message, peer) {
        const buffer = c.encode(this.encoding, message)
        peer.extension(name, buffer)
      },
      broadcast(message) {
        const buffer = c.encode(this.encoding, message)
        for (const peer of this.session.peers) {
          peer.extension(name, buffer)
        }
      },
      destroy() {
        for (const peer of this.session.peers) {
          if (peer.extensions.get(name) === ext) peer.extensions.delete(name)
        }
        this.session.extensions.delete(name)
      },
      _onmessage(state, peer) {
        const m = this.encoding.decode(state)
        if (this.handlers.onmessage) this.handlers.onmessage(m, peer)
      }
    }

    this.extensions.set(name, ext)

    if (this.core === null) this._monitorIndex = -2
    else this.core.addMonitor(this)

    for (const peer of this.peers) {
      peer.extensions.set(name, ext)
    }

    return ext
  }

  _encode(enc, val) {
    const state = { start: this.padding, end: this.padding, buffer: null }

    if (b4a.isBuffer(val)) {
      if (state.start === 0) return val
      state.end += val.byteLength
    } else if (enc) {
      enc.preencode(state, val)
    } else {
      val = b4a.from(val)
      if (state.start === 0) return val
      state.end += val.byteLength
    }

    state.buffer = b4a.allocUnsafe(state.end)

    if (enc) enc.encode(state, val)
    else state.buffer.set(val, state.start)

    return state.buffer
  }

  _decode(enc, block, index) {
    if (this.encryption) block = block.subarray(this.encryption.padding(this.core, index))
    try {
      if (enc) return c.decode(enc, block)
    } catch (err) {
      throw DECODING_ERROR(err.message, this.discoveryKey)
    }
    return block
  }

  _getEncryptionProvider(e) {
    if (isEncryptionProvider(e)) return e
    if (!e || !e.key) return null
    return new DefaultEncryption(e.key, this.key, { block: e.block, compat: this.core.compat })
  }
}

module.exports = Hypercore

function isStream(s) {
  return typeof s === 'object' && s && typeof s.pipe === 'function'
}

async function preappend(blocks) {
  const offset = this.state.length
  const fork = this.state.encryptionFork

  for (let i = 0; i < blocks.length; i++) {
    await this.encryption.encrypt(offset + i, blocks[i], fork, this.core)
  }
}

function isValidIndex(index) {
  return index === 0 || index > 0
}

function maybeUnslab(block) {
  // Unslab only when it takes up less then half the slab
  return block !== null && 2 * block.byteLength < block.buffer.byteLength ? unslab(block) : block
}

function checkSnapshot(snapshot, index) {
  if (index >= snapshot.state.snapshotCompatLength) {
    throw SNAPSHOT_NOT_AVAILABLE(
      `snapshot at index ${index} not available (max compat length ${snapshot.state.snapshotCompatLength})`,
      snapshot.discoveryKey
    )
  }
}

function readBlock(rx, index) {
  const promise = rx.getBlock(index)
  rx.tryFlush()
  return promise
}

function initOnce(session, storage, key, opts) {
  if (storage === null) storage = opts.storage || null
  if (key === null) key = opts.key || null

  session.core = new Core(Hypercore.defaultStorage(storage), {
    preopen: opts.preopen,
    eagerUpgrade: opts.eagerUpgrade !== false,
    notDownloadingLinger: opts.notDownloadingLinger,
    allowFork: opts.allowFork !== false,
    allowPush: !!opts.allowPush,
    pushOnly: !!opts.pushOnly,
    alwaysLatestBlock: !!opts.allowLatestBlock,
    inflightRange: opts.inflightRange,
    compat: opts.compat === true,
    force: opts.force,
    createIfMissing: opts.createIfMissing,
    discoveryKey: opts.discoveryKey,
    overwrite: opts.overwrite,
    key,
    keyPair: opts.keyPair,
    legacy: opts.legacy,
    manifest: opts.manifest,
    group: opts.group,
    globalCache: opts.globalCache || null // session is a temp option, not to be relied on unless you know what you are doing (no semver guarantees)
  })
}

function maybeAddMonitor(name) {
  if (name === 'append' || name === 'truncate') return
  if (this._monitorIndex >= 0 || this.closing) return

  if (this.core === null) {
    this._monitorIndex = -2
  } else {
    this.core.addMonitor(this)
  }
}

function isSessionMoved(err) {
  return err.code === 'SESSION_MOVED'
}

function getEncryptionOption(opts) {
  // old style, supported for now but will go away
  if (opts.encryptionKey) return { key: opts.encryptionKey, block: !!opts.isBlockKey }
  if (!opts.encryption) return null
  return b4a.isBuffer(opts.encryption) ? { key: opts.encryption } : opts.encryption
}

function isEncryptionProvider(e) {
  return e && isFunction(e.padding) && isFunction(e.encrypt) && isFunction(e.decrypt)
}

function isFunction(fn) {
  return !!fn && typeof fn === 'function'
}

function createDiscoveryKeyHandler(fn) {
  return ondiscoverykey
  function ondiscoverykey(id) {
    if (!id || id.byteLength !== 32) throw BAD_ARGUMENT('Invalid discovery key')
    return fn(id)
  }
}

function isRequestsDestroyed(activeRequests) {
  // TODO: move this to an object instead so we can store a property in next major
  return activeRequests.length > 0 && activeRequests[0] === null
}
const crypto = require('hypercore-crypto')
const flat = require('flat-tree')
const b4a = require('b4a')
const { MerkleTree } = require('./merkle-tree')

module.exports = async function auditCore(
  core,
  { tree = true, blocks = true, bitfield = true, dryRun = false } = {}
) {
  const length = core.state.length
  const stats = {
    treeNodes: 0,
    blocks: 0,
    bits: 0,
    droppedTreeNodes: 0,
    droppedBlocks: 0,
    droppedBits: 0,
    corrupt: false
  }

  // audit the tree
  if (tree) {
    let tx = null

    const roots = await MerkleTree.getRootsFromStorage(core.state.storage, length)
    const stack = []

    for (const r of roots) {
      if (r === null) {
        if (!dryRun) {
          const storage = core.state.storage
          await storage.store.deleteCore(storage.core)
          return null
        }

        stats.corrupt = true
      }

      stack.push(r)
    }

    stats.treeNodes += roots.length

    while (stack.length > 0) {
      const node = stack.pop()

      if ((node.index & 1) === 0) continue

      const [left, right] = flat.children(node.index)

      const rx = core.state.storage.read()
      const leftNodePromise = rx.getTreeNode(left)
      const rightNodePromise = rx.getTreeNode(right)

      rx.tryFlush()

      const [leftNode, rightNode] = await Promise.all([leftNodePromise, rightNodePromise])

      if (isBadTree(node, leftNode, rightNode)) {
        if (!tx && !stats.corrupt) tx = core.state.storage.write()
        const [l, r] = flat.spans(node.index)
        tx.deleteTreeNodeRange(l, r + 1)
        stats.droppedTreeNodes++
        continue
      }

      if (!leftNode) continue

      stats.treeNodes += 2
      stack.push(leftNode, rightNode)
    }

    if (tx && !dryRun) await tx.flush()
  }

  // audit the blocks
  if (blocks) {
    let tx = null

    for await (const block of core.state.storage.createBlockStream()) {
      if (!core.bitfield.get(block.index)) {
        if (!tx && !stats.corrupt) tx = core.state.storage.write()
        tx.deleteBlock(block.index)
        stats.droppedBlocks++
      }

      const rx = core.state.storage.read()
      const treeNodePromise = rx.getTreeNode(2 * block.index)

      rx.tryFlush()

      const treeNode = await treeNodePromise

      if (isBadBlock(treeNode, block.value)) {
        if (!tx && !stats.corrupt) tx = core.state.storage.write()
        tx.deleteBlock(block.index)
        stats.droppedBlocks++
        continue
      }

      stats.blocks++
    }

    if (tx && !dryRun) await tx.flush()
  }

  if (bitfield) {
    let tx = null

    for (const index of allBits(core.bitfield)) {
      const rx = core.state.storage.read()
      const blockPromise = rx.getBlock(index)

      rx.tryFlush()

      const block = await blockPromise
      if (!block) {
        stats.droppedBits++
        if (dryRun) continue

        if (!tx && !stats.corrupt) tx = core.state.storage.write()

        core.bitfield.set(index, false)

        const page = core.bitfield.getBitfield(index)
        if (page.bitfield) tx.putBitfieldPage(page.index, page.bitfield)
        else tx.deleteBitfieldPage(page.index)
        continue
      }

      stats.bits++
    }

    if (tx && !dryRun) await tx.flush()
  }

  return stats
}

function isBadBlock(node, block) {
  if (!node) return true
  const hash = crypto.data(block)
  return !b4a.equals(hash, node.hash) || node.size !== block.byteLength
}

function isBadTree(parent, left, right) {
  if (!left && !right) return false
  if (!left || !right) return true
  const hash = crypto.parent(left, right)
  return !b4a.equals(hash, parent.hash) || parent.size !== left.size + right.size
}

function* allBits(bitfield) {
  let i = 0
  if (bitfield.get(0)) yield 0
  while (true) {
    i = bitfield.findFirst(true, i + 1)
    if (i === -1) break
    yield i
  }
}
const b4a = require('b4a')
const quickbit = require('./compat').quickbit

module.exports = class BitInterlude {
  constructor() {
    this.ranges = []
  }

  contiguousLength(from) {
    for (const r of this.ranges) {
      if (r.start > from) break
      if (!r.value && r.start <= from) return r.start
    }

    // TODO: be smarter
    while (this.get(from) === true) from++
    return from
  }

  get(index) {
    let start = 0
    let end = this.ranges.length

    while (start < end) {
      const mid = (start + end) >> 1
      const r = this.ranges[mid]

      if (index < r.start) {
        end = mid
        continue
      }

      if (index >= r.end) {
        if (mid === start) break
        start = mid
        continue
      }

      return r.value
    }

    return false
  }

  setRange(start, end, value) {
    if (start === end) return

    let r = null

    for (let i = 0; i < this.ranges.length; i++) {
      r = this.ranges[i]

      // if already inside, stop
      if (r.start <= start && end <= r.end) {
        if (value === r.value) return

        const ranges = mergeRanges(r, { start, end, value })
        this.ranges.splice(i, 1, ...ranges)

        return
      }

      // we wanna overun the interval
      if (start > r.end) {
        continue
      }

      // we overran but this interval is ending after us, move it back
      if (end >= r.start && end <= r.end) {
        r.start = r.value === value ? start : end
        if (r.value !== value) this.ranges.splice(i, 0, { start, end, value })
        return
      }

      // we overran but our start is contained in this interval, move start back
      if (start >= r.start && start <= r.end) {
        if (r.value !== value) {
          r.end = start // Crop current comparison

          // If there's a next range
          if (this.ranges.length - 1 > i) {
            const next = this.ranges[i + 1]
            // If the same, go next
            if (next.value === value) continue
            // Else we overlap so update next range
            if (next.start < end) next.start = end
          }

          this.ranges.splice(++i, 0, { start, end, value })
          return
        }

        start = r.start
      }

      let remove = 0

      for (let j = i; j < this.ranges.length; j++) {
        const n = this.ranges[j]
        if (n.start > end || n.value !== value) break
        if (n.start <= end && n.end > end) end = n.end
        remove++
      }

      this.ranges.splice(i, remove, { start, end, value })
      return
    }

    if (r !== null) {
      if (start <= r.end && end > r.end) {
        r.end = end
        return
      }

      // we never
      if (r.end > start) return
    }

    this.ranges.push({ start, end, value })
  }

  flush(tx, bitfield) {
    if (!this.ranges.length) return []

    let index = this.ranges[0].start
    const final = this.ranges[this.ranges.length - 1].end

    let i = 0

    while (index < final) {
      const page = bitfield.getBitfield(index) // read only
      const pageIndex = page ? page.index : bitfield.getPageIndex(index)

      const buf = b4a.allocUnsafe(bitfield.getPageByteLength())

      if (page) {
        const src = page.bitfield // Uint32Array
        buf.set(b4a.from(src.buffer, src.byteOffset, src.byteLength), 0)
      } else {
        b4a.fill(buf, 0)
      }

      const last = (pageIndex + 1) * (buf.byteLength << 3)
      const offset = pageIndex * (buf.byteLength << 3)

      let hasValue = false

      while (i < this.ranges.length) {
        const { start, end, value } = this.ranges[i]

        if (!hasValue && value) hasValue = true

        const from = start < index ? index : start
        const to = end < last ? end : last

        quickbit.fill(buf, value, from - offset, to - offset)

        index = to

        if (to === last) break

        i++
      }

      if (page || hasValue) tx.putBitfieldPage(pageIndex, buf)
    }

    return this.ranges
  }
}

function mergeRanges(a, b) {
  const ranges = []
  if (a.start < b.start) ranges.push({ start: a.start, end: b.start, value: a.value })
  ranges.push({ start: b.start, end: b.end, value: b.value })
  if (b.end < a.end) ranges.push({ start: b.end, end: a.end, value: a.value })

  return ranges
}
const BigSparseArray = require('big-sparse-array')
const b4a = require('b4a')
const quickbit = require('./compat').quickbit

const BITS_PER_PAGE = 32768
const BYTES_PER_PAGE = BITS_PER_PAGE / 8
const WORDS_PER_PAGE = BYTES_PER_PAGE / 4
const BITS_PER_SEGMENT = 2097152
const BYTES_PER_SEGMENT = BITS_PER_SEGMENT / 8
const WORDS_PER_SEGMENT = BYTES_PER_SEGMENT / 4
const INITIAL_WORDS_PER_SEGMENT = 1024
const PAGES_PER_SEGMENT = BITS_PER_SEGMENT / BITS_PER_PAGE
const SEGMENT_GROWTH_FACTOR = 4

class BitfieldPage {
  constructor(index, segment) {
    this.index = index
    this.offset = index * BYTES_PER_PAGE - segment.offset
    this.bitfield = null
    this.segment = segment

    segment.add(this)
  }

  get tree() {
    return this.segment.tree
  }

  get(index, dirty) {
    return quickbit.get(this.bitfield, index)
  }

  set(index, val) {
    if (quickbit.set(this.bitfield, index, val)) {
      this.tree.update(this.offset * 8 + index)
    }
  }

  setRange(start, end, val) {
    quickbit.fill(this.bitfield, val, start, end)

    let i = Math.floor(start / 128)
    const n = i + Math.ceil((end - start) / 128)

    while (i <= n) this.tree.update(this.offset * 8 + i++ * 128)
  }

  findFirst(val, position) {
    return quickbit.findFirst(this.bitfield, val, position)
  }

  findLast(val, position) {
    return quickbit.findLast(this.bitfield, val, position)
  }

  count(start, length, val) {
    const end = start + length

    let i = start
    let c = 0

    while (length > 0) {
      const l = this.findFirst(val, i)
      if (l === -1 || l >= end) return c

      const h = this.findFirst(!val, l + 1)
      if (h === -1 || h >= end) return c + end - l

      c += h - l
      length -= h - i
      i = h
    }

    return c
  }
}

class BitfieldSegment {
  constructor(index, bitfield) {
    this.index = index
    this.offset = index * BYTES_PER_SEGMENT
    this.tree = quickbit.Index.from(bitfield, BYTES_PER_SEGMENT)
    this.pages = new Array(PAGES_PER_SEGMENT)
  }

  get bitfield() {
    return this.tree.field
  }

  add(page) {
    const i = page.index - this.index * PAGES_PER_SEGMENT
    this.pages[i] = page

    const start = i * WORDS_PER_PAGE
    const end = start + WORDS_PER_PAGE

    if (end >= this.bitfield.length) this.reallocate(end)

    page.bitfield = this.bitfield.subarray(start, end)
  }

  reallocate(length) {
    let target = this.bitfield.length
    while (target < length) target *= SEGMENT_GROWTH_FACTOR

    const bitfield = new Uint32Array(target)
    bitfield.set(this.bitfield)

    this.tree = quickbit.Index.from(bitfield, BYTES_PER_SEGMENT)

    for (let i = 0; i < this.pages.length; i++) {
      const page = this.pages[i]
      if (!page) continue

      const start = i * WORDS_PER_PAGE
      const end = start + WORDS_PER_PAGE

      page.bitfield = bitfield.subarray(start, end)
    }
  }

  findFirst(val, position) {
    position = this.tree.skipFirst(!val, position)

    let j = position & (BITS_PER_PAGE - 1)
    let i = (position - j) / BITS_PER_PAGE

    if (i >= PAGES_PER_SEGMENT) return -1

    while (i < this.pages.length) {
      const p = this.pages[i]

      let index = -1

      if (p) index = p.findFirst(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_PAGE + index

      j = 0
      i++
    }

    return -1
  }

  findLast(val, position) {
    position = this.tree.skipLast(!val, position)

    let j = position & (BITS_PER_PAGE - 1)
    let i = (position - j) / BITS_PER_PAGE

    if (i >= PAGES_PER_SEGMENT) return -1

    while (i >= 0) {
      const p = this.pages[i]

      let index = -1

      if (p) index = p.findLast(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_PAGE + index

      j = BITS_PER_PAGE - 1
      i--
    }

    return -1
  }
}

module.exports = class Bitfield {
  static BITS_PER_PAGE = BITS_PER_PAGE
  static BYTES_PER_PAGE = BYTES_PER_PAGE

  constructor(buffer) {
    this.resumed = !!(buffer && buffer.byteLength >= 0)

    this._pages = new BigSparseArray()
    this._segments = new BigSparseArray()

    const view = this.resumed
      ? new Uint32Array(buffer.buffer, buffer.byteOffset, Math.floor(buffer.byteLength / 4))
      : new Uint32Array(INITIAL_WORDS_PER_SEGMENT)

    for (let i = 0; i < view.length; i += WORDS_PER_SEGMENT) {
      let bitfield = view.subarray(i, i + WORDS_PER_SEGMENT)
      let length = WORDS_PER_SEGMENT

      if (i === 0) {
        length = INITIAL_WORDS_PER_SEGMENT
        while (length < bitfield.length) length *= SEGMENT_GROWTH_FACTOR
      }

      if (bitfield.length !== length) {
        const copy = new Uint32Array(length)
        copy.set(bitfield, 0)
        bitfield = copy
      }

      const segment = new BitfieldSegment(i / WORDS_PER_SEGMENT, bitfield)
      this._segments.set(segment.index, segment)

      for (let j = 0; j < bitfield.length; j += WORDS_PER_PAGE) {
        const page = new BitfieldPage((i + j) / WORDS_PER_PAGE, segment)
        this._pages.set(page.index, page)
      }
    }
  }

  static from(bitfield) {
    return new Bitfield(bitfield.toBuffer(bitfield._pages.maxLength * BITS_PER_PAGE))
  }

  toBuffer(length) {
    const pages = Math.ceil(length / BITS_PER_PAGE)
    const buffer = b4a.allocUnsafe(pages * BYTES_PER_PAGE)

    for (let i = 0; i < pages; i++) {
      const page = this._pages.get(i)
      const offset = i * BYTES_PER_PAGE

      if (page) {
        const buf = b4a.from(
          page.bitfield.buffer,
          page.bitfield.byteOffset,
          page.bitfield.byteLength
        )

        buffer.set(buf, offset)
      } else {
        buffer.fill(0, offset, offset + BYTES_PER_PAGE)
      }
    }

    return buffer
  }

  getBitfield(index) {
    const i = this.getPageIndex(index)

    const p = this._pages.get(i)
    return p || null
  }

  merge(bitfield, length) {
    let i = 0

    while (i < length) {
      const start = bitfield.firstSet(i)
      if (start === -1) break

      i = bitfield.firstUnset(start)

      if (i === -1 || i > length) i = length

      this.setRange(start, i, true)

      if (i >= length) break
    }
  }

  get(index) {
    const j = index & (BITS_PER_PAGE - 1)
    const i = (index - j) / BITS_PER_PAGE

    const p = this._pages.get(i)

    return p ? p.get(j) : false
  }

  getPageByteLength() {
    return BYTES_PER_PAGE
  }

  getPageIndex(index) {
    const j = index & (BITS_PER_PAGE - 1)
    return (index - j) / BITS_PER_PAGE
  }

  getPage(index, create) {
    const i = this.getPageIndex(index)

    let p = this._pages.get(i)

    if (p) return p

    if (!create) return null

    const k = Math.floor(i / PAGES_PER_SEGMENT)
    const s =
      this._segments.get(k) ||
      this._segments.set(
        k,
        new BitfieldSegment(
          k,
          new Uint32Array(k === 0 ? INITIAL_WORDS_PER_SEGMENT : WORDS_PER_SEGMENT)
        )
      )

    p = this._pages.set(i, new BitfieldPage(i, s))

    return p
  }

  set(index, val) {
    const j = index & (BITS_PER_PAGE - 1)
    const i = (index - j) / BITS_PER_PAGE

    let p = this._pages.get(i)

    if (!p && val) {
      const k = Math.floor(i / PAGES_PER_SEGMENT)
      const s =
        this._segments.get(k) ||
        this._segments.set(
          k,
          new BitfieldSegment(
            k,
            new Uint32Array(k === 0 ? INITIAL_WORDS_PER_SEGMENT : WORDS_PER_SEGMENT)
          )
        )

      p = this._pages.set(i, new BitfieldPage(i, s))
    }

    if (p) p.set(j, val)
  }

  setRange(start, end, val) {
    let j = start & (BITS_PER_PAGE - 1)
    let i = (start - j) / BITS_PER_PAGE

    while (start < end) {
      let p = this._pages.get(i)

      if (!p && val) {
        const k = Math.floor(i / PAGES_PER_SEGMENT)
        const s =
          this._segments.get(k) ||
          this._segments.set(
            k,
            new BitfieldSegment(
              k,
              new Uint32Array(k === 0 ? INITIAL_WORDS_PER_SEGMENT : WORDS_PER_SEGMENT)
            )
          )

        p = this._pages.set(i, new BitfieldPage(i, s))
      }

      const offset = i * BITS_PER_PAGE
      const last = Math.min(end - offset, BITS_PER_PAGE)
      const range = last - j

      if (p) p.setRange(j, last, val)

      j = 0
      i++
      start += range
    }
  }

  findFirst(val, position) {
    let j = position & (BITS_PER_SEGMENT - 1)
    let i = (position - j) / BITS_PER_SEGMENT

    while (i < this._segments.maxLength) {
      const s = this._segments.get(i)

      let index = -1

      if (s) index = s.findFirst(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_SEGMENT + index

      j = 0
      i++
    }

    return val ? -1 : this._segments.maxLength * BITS_PER_SEGMENT
  }

  firstSet(position) {
    return this.findFirst(true, position)
  }

  firstUnset(position) {
    return this.findFirst(false, position)
  }

  findLast(val, position) {
    let j = position & (BITS_PER_SEGMENT - 1)
    let i = (position - j) / BITS_PER_SEGMENT

    while (i >= 0) {
      const s = this._segments.get(i)

      let index = -1

      if (s) index = s.findLast(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_SEGMENT + index

      j = BITS_PER_SEGMENT - 1
      i--
    }

    return -1
  }

  lastSet(position) {
    return this.findLast(true, position)
  }

  lastUnset(position) {
    return this.findLast(false, position)
  }

  hasUnset(start, length) {
    const end = start + length

    let j = start & (BITS_PER_SEGMENT - 1)
    let i = (start - j) / BITS_PER_SEGMENT

    while (i < this._segments.maxLength) {
      const s = this._segments.get(i)
      const index = s ? s.findFirst(false, j) : j
      if (index !== -1) return i * BITS_PER_SEGMENT + index < end

      j = 0
      i++

      if (i * BITS_PER_SEGMENT >= end) return false
    }

    return true
  }

  hasSet(start, length) {
    const end = start + length

    let j = start & (BITS_PER_SEGMENT - 1)
    let i = (start - j) / BITS_PER_SEGMENT

    while (i < this._segments.maxLength) {
      const s = this._segments.get(i)

      let index = -1

      if (s) index = s.findFirst(true, j)

      if (index !== -1) return i * BITS_PER_SEGMENT + index < end

      j = 0
      i++

      if (i * BITS_PER_SEGMENT >= end) return false
    }

    return false
  }

  count(start, length, val) {
    let j = start & (BITS_PER_PAGE - 1)
    let i = (start - j) / BITS_PER_PAGE
    let c = 0

    while (length > 0) {
      const p = this._pages.get(i)

      const end = Math.min(j + length, BITS_PER_PAGE)
      const range = end - j

      if (p) c += p.count(j, range, val)
      else if (!val) c += range

      j = 0
      i++
      length -= range
    }

    return c
  }

  countSet(start, length) {
    return this.count(start, length, true)
  }

  countUnset(start, length) {
    return this.count(start, length, false)
  }

  *want(start, length) {
    if (start & 31) {
      const d = start & 31
      start -= d
      length += d
    }

    let j = start & (BITS_PER_SEGMENT - 1)
    let i = (start - j) / BITS_PER_SEGMENT

    while (length > 0) {
      const s = this._segments.get(i)

      if (s) {
        let end = Math.min(j + length, BITS_PER_SEGMENT)
        if (end & 31) end += 32 - (end & 31)

        yield {
          start: i * BITS_PER_SEGMENT + j,
          bitfield: s.bitfield.subarray(j / 32, end / 32)
        }
      }

      j = 0
      i++
      length -= BITS_PER_SEGMENT
    }
  }

  clear(tx) {
    return tx.deleteBitfieldPageRange(0, -1)
  }

  onupdate(ranges) {
    for (const { start, end, value } of ranges) {
      this.setRange(start, end, value)
    }
  }

  static async open(storage, length) {
    if (length === 0) return new Bitfield(storage, null)

    const pages = Math.ceil(length / BITS_PER_PAGE)
    const buffer = b4a.alloc(pages * BYTES_PER_PAGE)
    const stream = storage.createBitfieldStream({ lt: pages })

    for await (const { index, page } of stream) {
      buffer.set(page, index * BYTES_PER_PAGE)
    }

    return new Bitfield(buffer)
  }
}
const crypto = require('hypercore-crypto')
const sodium = require('sodium-universal')
const b4a = require('b4a')
const c = require('compact-encoding')

// TODO: rename this to "crypto" and move everything hashing related etc in here
// Also lets move the tree stuff from hypercore-crypto here

const [
  TREE,
  REPLICATE_INITIATOR,
  REPLICATE_RESPONDER,
  MANIFEST,
  DEFAULT_NAMESPACE,
  DEFAULT_ENCRYPTION
] = crypto.namespace('hypercore', 6)

exports.MANIFEST = MANIFEST
exports.DEFAULT_NAMESPACE = DEFAULT_NAMESPACE
exports.DEFAULT_ENCRYPTION = DEFAULT_ENCRYPTION

exports.replicate = function (isInitiator, key, handshakeHash) {
  const out = b4a.allocUnsafe(32)
  sodium.crypto_generichash_batch(
    out,
    [isInitiator ? REPLICATE_INITIATOR : REPLICATE_RESPONDER, key],
    handshakeHash
  )
  return out
}

exports.treeSignable = function (manifestHash, treeHash, length, fork) {
  const state = { start: 0, end: 112, buffer: b4a.allocUnsafe(112) }
  c.fixed32.encode(state, TREE)
  c.fixed32.encode(state, manifestHash)
  c.fixed32.encode(state, treeHash)
  c.uint64.encode(state, length)
  c.uint64.encode(state, fork)
  return state.buffer
}

exports.treeSignableCompat = function (hash, length, fork, noHeader) {
  const end = noHeader ? 48 : 80
  const state = { start: 0, end, buffer: b4a.allocUnsafe(end) }
  if (!noHeader) c.fixed32.encode(state, TREE) // ultra legacy mode, kill in future major
  c.fixed32.encode(state, hash)
  c.uint64.encode(state, length)
  c.uint64.encode(state, fork)
  return state.buffer
}
// Export the appropriate version of `quickbit-universal` as the plain import
// may resolve to an older version in some environments
let quickbit = require('quickbit-universal')
if (
  typeof quickbit.findFirst !== 'function' ||
  typeof quickbit.findLast !== 'function' ||
  typeof quickbit.clear !== 'function'
) {
  // This should always load the fallback from the locally installed version
  quickbit = require('quickbit-universal/fallback')
}
exports.quickbit = quickbit
const crypto = require('hypercore-crypto')
const flat = require('flat-tree')
const b4a = require('b4a')
const quickbit = require('quickbit-universal')
const Bitfield = require('./bitfield')

const MAX_BATCH_USED = 4 * 1024 * 1024
const MIN_BATCH_USED = 512 * 1024

// just in its own file as its a bit involved

module.exports = copyPrologue

async function copyPrologue(src, dst) {
  const prologue = dst.header.manifest.prologue

  if (src.length < prologue.length || prologue.length === 0) return

  const stack = []
  const roots = flat.fullRoots(prologue.length * 2)
  const batch = { roots, first: true, last: false, contig: 0, used: 0, tree: [], blocks: [] }

  for (let i = 0; i < roots.length; i++) {
    const node = roots[i]
    batch.tree.push(node)
    stack.push(node)
  }

  let lastPage = -1
  let lastBlock = -1

  for await (const data of src.storage.createBlockStream({
    gte: 0,
    lt: prologue.length,
    reverse: true
  })) {
    if (walkTree(stack, data.index * 2, batch) === false) {
      throw new Error('Missing block or tree node for ' + data.index)
    }

    batch.contig = data.index + 1 === lastBlock ? batch.contig + 1 : 1
    lastBlock = data.index

    const page = getBitfieldPage(data.index)
    batch.blocks.push(data)

    if (lastPage !== page) batch.used += 4096
    batch.used += Math.max(data.value.byteLength, 128) // 128 is just a sanity number to avoid mega batches

    // always safe to partially flush so we do that ondemand to reduce memory usage...
    if ((batch.used >= MIN_BATCH_USED && page !== lastPage) || batch.used >= MAX_BATCH_USED) {
      await flushBatch(prologue, src, dst, batch)
    }

    lastPage = page
  }

  if (lastBlock !== 0) batch.contig = 0

  batch.last = true
  await flushBatch(prologue, src, dst, batch)
}

async function flushBatch(prologue, src, dst, batch) {
  const nodePromises = []

  const srcReader = src.storage.read()
  for (const index of batch.tree) {
    nodePromises.push(srcReader.getTreeNode(index))
  }
  srcReader.tryFlush()

  const nodes = await Promise.all(nodePromises)

  const pagePromises = []
  const dstReader = dst.storage.read()

  const headPromise = batch.first ? dstReader.getHead() : null
  if (headPromise) headPromise.catch(noop)

  let lastPage = -1
  for (const { index } of batch.blocks) {
    const page = getBitfieldPage(index)
    if (page === lastPage) continue
    lastPage = page
    pagePromises.push(dstReader.getBitfieldPage(page))
  }

  dstReader.tryFlush()

  const pages = await Promise.all(pagePromises)
  const head = headPromise === null ? null : await headPromise
  const userData = []

  // reads done!

  if (batch.first) {
    const roots = nodes.slice(0, batch.roots.length)

    for (const node of roots) {
      if (!node) throw new Error('Missing nodes for prologue hash')
    }

    const treeHash = crypto.tree(roots)
    if (!b4a.equals(treeHash, prologue.hash)) throw new Error('Prologue does not match source')
  }

  if (batch.first) {
    for await (const data of src.storage.createUserDataStream()) userData.push(data)
  }

  for (let i = 0; i < pages.length; i++) {
    if (!pages[i]) pages[i] = b4a.alloc(4096)
  }

  const tx = dst.storage.write()

  for (const node of nodes) tx.putTreeNode(node)

  lastPage = -1
  let pageIndex = -1

  for (const { index, value } of batch.blocks) {
    const page = getBitfieldPage(index)

    if (page !== lastPage) {
      lastPage = page
      pageIndex++
      // queue the page now, we mutate it below but its the same ref
      tx.putBitfieldPage(pageIndex, pages[pageIndex])
    }

    const pageBuffer = pages[pageIndex]
    quickbit.set(pageBuffer, getBitfieldOffset(index), true)
    tx.putBlock(index, value)
  }

  for (const { key, value } of userData) {
    tx.putUserData(key, value)
  }

  let upgraded = batch.first && !head
  if (upgraded) {
    tx.setHead(prologueToTree(prologue))
  }

  await tx.flush()

  if (upgraded) {
    const roots = nodes.slice(0, batch.roots.length)
    dst.state.setRoots(roots)
    dst.header.tree = prologueToTree(prologue)
  }

  if (userData.length > 0) {
    dst.header.userData = userData.concat(dst.header.userData)
  }

  if (batch.contig) {
    // TODO: we need to persist this somehow
    dst.header.hints.contiguousLength = batch.contig
  }

  let start = 0
  let length = 0

  // update in memory bitfield
  for (const { index } of batch.blocks) {
    if (start === 0 || start - 1 === index) {
      length++
    } else {
      if (length > 0) signalReplicator(dst, upgraded, start, length)
      upgraded = false
      length = 1
    }

    start = index
    dst.bitfield.set(index, true)
  }

  if (length > 0) signalReplicator(dst, upgraded, start, length)

  // unlink
  batch.tree = []
  batch.blocks = []
  batch.first = false
  batch.used = 0
}

function signalReplicator(core, upgraded, start, length) {
  if (upgraded) {
    core.replicator.cork()
    core.replicator.onhave(start, length, false)
    core.replicator.onupgrade()
    core.replicator.uncork()
  } else {
    core.replicator.onhave(start, length, false)
  }
}

function prologueToTree(prologue) {
  return {
    fork: 0,
    length: prologue.length,
    rootHash: prologue.hash,
    signature: null
  }
}

function getBitfieldPage(index) {
  return Math.floor(index / Bitfield.BITS_PER_PAGE)
}

function getBitfieldOffset(index) {
  return index & (Bitfield.BITS_PER_PAGE - 1)
}

function walkTree(stack, target, batch) {
  while (stack.length > 0) {
    const node = stack.pop()

    if ((node & 1) === 0) {
      if (node === target) return true
      continue
    }

    const ite = flat.iterator(node)
    if (!ite.contains(target)) continue

    while ((ite.index & 1) !== 0) {
      const left = ite.leftChild()
      const right = ite.sibling() // is right child

      batch.tree.push(left, right)

      if (ite.contains(target)) stack.push(left)
      else ite.sibling()
    }

    if (ite.index === target) return true
  }

  return false
}

function noop() {}
const crypto = require('hypercore-crypto')
const b4a = require('b4a')
const unslab = require('unslab')
const z32 = require('z32')
const Mutex = require('./mutex')
const { MerkleTree, ReorgBatch } = require('./merkle-tree')
const BitInterlude = require('./bit-interlude')
const Bitfield = require('./bitfield')
const RemoteBitfield = require('./remote-bitfield')
const {
  BAD_ARGUMENT,
  STORAGE_EMPTY,
  STORAGE_CONFLICT,
  INVALID_SIGNATURE,
  INVALID_CHECKSUM
} = require('hypercore-errors')
const Verifier = require('./verifier')
const audit = require('./audit')
const copyPrologue = require('./copy-prologue')
const SessionState = require('./session-state')
const Replicator = require('./replicator')

module.exports = class Core {
  constructor(db, opts = {}) {
    this.db = db
    this.storage = null
    this.replicator = new Replicator(this, opts)
    this.sessionStates = []
    this.monitors = []
    this.activeSessions = 0
    this.gc = 0 // corestore uses this to main a gc strike pool

    this.id = opts.key ? z32.encode(opts.key) : null
    this.key = opts.key || null
    this.discoveryKey = opts.discoveryKey || (opts.key && crypto.discoveryKey(opts.key)) || null
    this.manifest = null
    this.opening = null
    this.closing = null
    this.exclusive = null

    this.preupdate = null
    this.header = null
    this.compat = false
    this.bitfield = null
    this.verifier = null
    this.truncating = 0
    this.skipBitfield = null
    this.globalCache = opts.globalCache || null
    this.autoClose = opts.autoClose !== false
    this.onidle = noop
    this.ongroupupdate = noop

    this.state = null
    this.opened = false
    this.destroyed = false
    this.closed = false

    this.hintsChanged = false
    this.remoteContiguousLengthChanged = false

    this._bitfield = null
    this._verifies = null
    this._verifiesFlushed = null
    this._legacy = !!opts.legacy
    this._repairMode = false

    this.opening = this._open(opts)
    this.opening.catch(noop)
  }

  static setRecoveryPeers(peers) {
    SessionState.RECOVERY_PEERS = peers
  }

  ready() {
    return this.opening
  }

  addMonitor(s) {
    if (s._monitorIndex >= 0) return
    s._monitorIndex = this.monitors.push(s) - 1
  }

  removeMonitor(s) {
    if (s._monitorIndex < 0) return
    const head = this.monitors.pop()
    if (head !== s) this.monitors[(head._monitorIndex = s._monitorIndex)] = head
    s._monitorIndex = -1
  }

  emitRemoteContiguousLength() {
    if (!this.remoteContiguousLengthChanged) return
    this.remoteContiguousLengthChanged = false

    const length = this.header.hints.remoteContiguousLength

    for (let i = this.monitors.length - 1; i >= 0; i--) {
      this.monitors[i].emit('remote-contiguous-length', length)
    }
  }

  emitManifest() {
    for (let i = this.monitors.length - 1; i >= 0; i--) {
      this.monitors[i].emit('manifest')
    }
  }

  createUserDataStream(opts, session = this.state) {
    return session.storage.createUserDataStream(opts)
  }

  allSessions() {
    const sessions = []
    for (const state of this.sessionStates) {
      if (state.sessions.length) sessions.push(...state.sessions)
    }
    return sessions
  }

  hasSession() {
    return this.activeSessions !== 0
  }

  compact() {
    const compacting = []
    for (const s of this.sessionStates) {
      compacting.push(s.storage.compact())
    }
    return Promise.all(compacting)
  }

  checkIfIdle() {
    if (!this.opened || this.destroyed === true || this.hasSession() === true) return
    if (this.replicator.idle() === false) return
    if (this.state === null || this.state.mutex.idle() === false) return
    this.onidle()
  }

  async lockExclusive() {
    if (this.exclusive === null) this.exclusive = new Mutex()
    await this.exclusive.lock()
  }

  unlockExclusive() {
    if (this.exclusive !== null) this.exclusive.unlock()
  }

  async _open(opts) {
    try {
      await this._tryOpen(opts)
    } catch (err) {
      this.onidle()
      throw err
    }

    this.opened = true
  }

  async _tryOpen(opts) {
    if (opts.preopen) await opts.preopen // just a hook to allow exclusive access here...

    let storage = await this.db.resumeCore(this.discoveryKey)

    let overwrite = opts.overwrite === true

    const force = opts.force === true
    const createIfMissing = opts.createIfMissing !== false
    // kill this flag soon
    const legacy = !!opts.legacy

    // default to true for now if no manifest is provided
    let compat = opts.compat === true || (opts.compat !== false && !opts.manifest)

    let header = storage ? parseHeader(await getCoreInfo(storage)) : null

    const hadManifest = !!header && !!header.manifest && !!header.key
    const hadKeyPair = !!header && !!header.keyPair

    if (force && opts.key && header && !b4a.equals(header.key, opts.key)) {
      overwrite = true
    }

    if (!header && opts.discoveryKey && !(opts.key || opts.manifest)) {
      throw STORAGE_EMPTY('No Hypercore is stored here', this.discoveryKey)
    }

    if (!header || overwrite) {
      if (!createIfMissing) {
        throw STORAGE_EMPTY('No Hypercore is stored here', this.discoveryKey)
      }

      if (compat) {
        if (opts.key && opts.keyPair && !b4a.equals(opts.key, opts.keyPair.publicKey)) {
          throw BAD_ARGUMENT('Key must match publicKey when in compat mode', this.discoveryKey)
        }
      }

      const keyPair = opts.keyPair || (opts.key ? null : crypto.keyPair())

      const defaultManifest =
        !opts.manifest &&
        (!!opts.compat || !opts.key || !!(keyPair && b4a.equals(opts.key, keyPair.publicKey)))
      const manifest = defaultManifest
        ? Verifier.defaultSignerManifest(opts.key || keyPair.publicKey)
        : Verifier.createManifest(opts.manifest)

      header = {
        key: opts.key || (compat ? manifest.signers[0].publicKey : Verifier.manifestHash(manifest)),
        manifest,
        keyPair: keyPair
          ? { publicKey: keyPair.publicKey, secretKey: keyPair.secretKey || null }
          : null,
        frozen: false,
        tree: {
          fork: 0,
          length: 0,
          rootHash: null,
          signature: null,
          timestamp: 0
        },
        group: null,
        hints: {
          reorgs: [],
          contiguousLength: 0,
          remoteContiguousLength: 0,
          recovering: 0
        }
      }

      const discoveryKey = opts.discoveryKey || crypto.discoveryKey(header.key)

      storage = await this.db.createCore({
        key: header.key,
        manifest,
        keyPair,
        frozen: false,
        discoveryKey,
        userData: opts.userData || [],
        alias: opts.alias || null
      })
    }

    // unslab the long lived buffers to avoid keeping the slab alive
    header.key = unslab(header.key)

    if (header.tree) {
      header.tree.rootHash = unslab(header.tree.rootHash)
      header.tree.signature = unslab(header.tree.signature)
    }

    if (header.keyPair) {
      header.keyPair.publicKey = unslab(header.keyPair.publicKey)
      header.keyPair.secretKey = unslab(header.keyPair.secretKey)
    }

    if (header.keyPair) {
      header.keyPair.publicKey = unslab(header.keyPair.publicKey)
      header.keyPair.secretKey = unslab(header.keyPair.secretKey)
    }

    if (opts.manifest) {
      // if we provide a manifest and no key, verify that the stored key is the same
      if (
        !opts.key &&
        !Verifier.isValidManifest(header.key, Verifier.createManifest(opts.manifest))
      ) {
        throw STORAGE_CONFLICT('Manifest does not hash to provided key', this.discoveryKey)
      }

      if (!header.manifest) header.manifest = opts.manifest
    }

    if (opts.key && !b4a.equals(header.key, opts.key)) {
      throw STORAGE_CONFLICT('Another Hypercore is stored here', this.discoveryKey)
    }

    // if we signalled compat, but already now this core isn't disable it
    if (compat && header.manifest && !Verifier.isCompat(header.key, header.manifest)) {
      compat = false
    } else if (!compat && header.manifest && Verifier.isCompat(header.key, header.manifest)) {
      compat = true
    }

    const prologue = header.manifest ? header.manifest.prologue : null

    const bitfield = await Bitfield.open(storage, header.tree.length)

    const treeInfo = {
      fork: header.tree.fork,
      length: header.tree.length,
      signature: header.tree.signature,
      roots: await maybeGetRootsFromStorage(storage, header.tree.length),
      prologue
    }

    this._repairMode = !treeInfo.roots.length && treeInfo.length && !overwrite
    // Set push only mode if in repair mode
    if (this._repairMode) {
      this.replicator.setPushOnly(true)
    }

    if (opts.group) {
      if (!header.group) header.group = await this.db.createGroup(opts.group)
      else if (!b4a.equals(header.group.key, opts.group)) {
        throw STORAGE_CONFLICT(
          'Core is already register to group: ' + b4a.toString(header.group.key, 'hex')
        )
      }

      const tx = storage.write()
      tx.setGroup(header.group)
      await tx.flush()
    }

    if (overwrite) {
      const tx = storage.write()
      tx.deleteTreeNodeRange(0, -1)
      tx.deleteBlockRange(0, -1)
      bitfield.clear(tx)
      await tx.flush()
    }

    const len = bitfield.findFirst(false, header.hints.contiguousLength)
    if (header.hints.contiguousLength !== len && !storage.readOnly) {
      header.hints.contiguousLength = len
      const tx = storage.write()
      tx.setHints(header.hints)
      await tx.flush()
    }

    // to unslab
    if (header.manifest) {
      header.manifest = Verifier.createManifest(header.manifest)
      if (!hadManifest || (header.keyPair && !hadKeyPair)) {
        const tx = storage.write()
        tx.setAuth({
          key: header.key,
          discoveryKey: crypto.discoveryKey(header.key),
          manifest: header.manifest,
          keyPair: header.keyPair
        })
        await tx.flush()
      }
    }

    const verifier = header.manifest
      ? new Verifier(header.key, header.manifest, { crypto, legacy })
      : null

    this.storage = storage
    this.header = header
    this.compat = compat
    this.bitfield = bitfield
    this.verifier = verifier
    this.state = new SessionState(this, null, storage, treeInfo, null)

    if (this.key === null) this.key = this.header.key
    if (this.discoveryKey === null) this.discoveryKey = crypto.discoveryKey(this.key)
    if (this.id === null) this.id = z32.encode(this.key)
    if (this.manifest === null) this.manifest = this.header.manifest
  }

  async audit(opts) {
    await this.state.mutex.lock()

    try {
      return await audit(this, opts)
    } finally {
      this.state._unlock()
    }
  }

  async setGroup(group) {
    await this.state.mutex.lock()
    try {
      if (!this.header.group) this.header.group = await this.db.createGroup(group)
      else if (!b4a.equals(this.header.group.key, group)) {
        throw STORAGE_CONFLICT(
          'Core is already register to group: ' + b4a.toString(this.header.group.key, 'hex')
        )
      }

      const tx = this.storage.write()
      tx.setGroup(this.header.group)
      await tx.flush()
    } finally {
      this.state.mutex.unlock()
    }
  }

  async setManifest(manifest) {
    await this.state.mutex.lock()

    try {
      if (manifest && this.header.manifest === null) {
        if (!Verifier.isValidManifest(this.header.key, manifest)) {
          throw INVALID_CHECKSUM('Manifest hash does not match', this.discoveryKey)
        }

        const tx = this.state.createWriteBatch()
        this._setManifest(tx, Verifier.createManifest(manifest), null)
        await this.state.flush()
      }
    } finally {
      this.state._unlock()
    }
  }

  _setManifest(tx, manifest, keyPair) {
    if (!manifest && b4a.equals(keyPair.publicKey, this.header.key)) {
      manifest = Verifier.defaultSignerManifest(this.header.key)
    }
    if (!manifest) return

    const verifier = new Verifier(this.header.key, manifest, { legacy: this._legacy })

    if (verifier.prologue) this.state.prologue = Object.assign({}, verifier.prologue)

    this.manifest = this.header.manifest = manifest

    tx.setAuth({
      key: this.header.key,
      discoveryKey: this.discoveryKey,
      manifest,
      keyPair: this.header.keyPair
      // TODO: encryptionKey?
    })

    this.compat = verifier.compat
    this.verifier = verifier

    this.replicator.onupgrade()
    this.emitManifest()
  }

  async copyPrologue(src) {
    await this.state.mutex.lock()

    try {
      await src.mutex.lock()
    } catch (err) {
      this.state.mutex.unlock()
      throw err
    }

    try {
      await copyPrologue(src, this)
    } finally {
      src.mutex.unlock()
      this.state.mutex.unlock()
      this.checkIfIdle()
    }
  }

  flushed() {
    return this.state.flushed()
  }

  async _validateCommit(state, treeLength) {
    if (this.state.length > state.length) {
      return false // TODO: partial commit and truncation possible in the future
    }

    if (this.state.length > treeLength) {
      for (const root of this.state.roots) {
        const batchRoot = await MerkleTree.get(state, root.index)
        if (batchRoot.size !== root.size || !b4a.equals(batchRoot.hash, root.hash)) {
          return false
        }
      }
    }

    if (this.verifier === null) {
      return false // easier to assert than upsert
    }

    return true
  }

  _verifyBatchUpgrade(batch, manifest) {
    if (!this.header.manifest) {
      // compat, drop at some point
      if (!manifest) manifest = Verifier.defaultSignerManifest(this.header.key)

      if (
        !manifest ||
        !(
          Verifier.isValidManifest(this.header.key, manifest) ||
          Verifier.isCompat(this.header.key, manifest)
        )
      ) {
        throw INVALID_SIGNATURE('Proof contains an invalid manifest', this.discoveryKey) // TODO: proper error type
      }
    }

    const verifier =
      this.verifier ||
      new Verifier(this.header.key, Verifier.createManifest(manifest), { legacy: this._legacy })

    if (!verifier.verify(batch, batch.signature)) {
      throw INVALID_SIGNATURE('Proof contains an invalid signature', this.discoveryKey)
    }

    return manifest
  }

  async _verifyExclusive({ batch, bitfield, value, manifest }) {
    manifest = this._verifyBatchUpgrade(batch, manifest)

    if (
      !(await this.state._verifyBlock(
        batch,
        bitfield,
        value,
        this.header.manifest ? null : manifest
      ))
    ) {
      return false
    }

    if (!batch.upgraded && bitfield) {
      this.replicator.onhave(bitfield.start, bitfield.length, bitfield.drop)
    }

    return true
  }

  async _verifyShared() {
    if (!this._verifies.length) return false

    await this.state.mutex.lock()

    const tx = this.state.createWriteBatch()

    const verifies = this._verifies
    this._verifies = null
    this._verified = null

    try {
      for (const { batch, bitfield, value } of verifies) {
        if (!batch.commitable()) continue

        if (bitfield) {
          tx.putBlock(bitfield.start, value)
        }
      }

      const bits = new BitInterlude()

      for (let i = 0; i < verifies.length; i++) {
        const { batch, bitfield, manifest } = verifies[i]

        if (!batch.commitable()) {
          verifies[i] = null // signal that we cannot commit this one
          continue
        }

        if (bitfield) {
          bits.setRange(bitfield.start, bitfield.start + 1, true)
        }

        // if we got a manifest AND its strictly a non compat one, lets store it
        if (manifest && this.header.manifest === null) {
          if (!Verifier.isValidManifest(this.header.key, manifest)) {
            throw INVALID_CHECKSUM('Manifest hash does not match', this.discoveryKey)
          }
          this._setManifest(tx, manifest, null)
        }

        if (batch.commitable()) batch.commit(tx)
      }

      const ranges = bits.flush(tx, this.bitfield)

      await this.state.flush()

      for (const { start, end, value } of ranges) {
        this._setBitfieldRanges(start, end, value)
      }

      for (let i = 0; i < verifies.length; i++) {
        const bitfield = verifies[i] && verifies[i].bitfield
        if (bitfield) {
          this.updateContiguousLength(bitfield)
          this.replicator.onhave(bitfield.start, bitfield.length, bitfield.drop)
        }
      }

      if (this.hintsChanged) await this.flushHints()
    } finally {
      this.state._clearActiveBatch()
      this.state.mutex.unlock()
    }

    return verifies[0] !== null
  }

  async flushHints() {
    if (!this.hintsChanged) return
    this.hintsChanged = false // we unset this immediately as a "debounce"

    const tx = this.state.storage.write()

    tx.setHints({
      contiguousLength: this.header.hints.contiguousLength,
      remoteContiguousLength: this.header.hints.remoteContiguousLength,
      recovering: this.header.hints.recovering
    })

    await tx.flush()
  }

  async checkConflict(proof, from) {
    if (this.state.length < proof.upgrade.length || proof.fork !== this.state.fork) {
      // out of date this proof - ignore for now
      return false
    }

    // sanity check -> no manifest, no way to verify
    if (!this.header.manifest) {
      return false
    }

    const batch = MerkleTree.verifyFullyRemote(this.state, proof)

    try {
      this._verifyBatchUpgrade(batch, proof.manifest)
    } catch {
      return true
    }

    const roots = await maybeGetRootsFromStorage(this.storage, proof.upgrade.length)
    const remoteTreeHash = crypto.tree(proof.upgrade.nodes)
    const localTreeHash = crypto.tree(roots)

    try {
      const rx = this.state.storage.read()
      const treeProofPromise = MerkleTree.proof(this.state, rx, {
        block: null,
        hash: null,
        seek: null,
        upgrade: {
          start: 0,
          length: proof.upgrade.length
        }
      })

      rx.tryFlush()

      const treeProof = await treeProofPromise

      const verifyBatch = MerkleTree.verifyFullyRemote(this.state, await treeProof.settle())
      this._verifyBatchUpgrade(verifyBatch, this.header.manifest)
    } catch (err) {
      if (err.code !== 'INVALID_OPERATION') return true

      return !(await this._repairTreeNodes(proof))
    }

    // both proofs are valid, now check if they forked
    if (b4a.equals(localTreeHash, remoteTreeHash)) return false

    await this.state.mutex.lock()

    try {
      const tx = this.state.createWriteBatch()

      this.header.frozen = true

      tx.setAuth({
        key: this.header.key,
        discoveryKey: this.discoveryKey,
        manifest: this.header.manifest,
        keyPair: this.header.keyPair,
        frozen: true
      })

      await this.state.flush()
    } finally {
      this.state.mutex.unlock()
    }

    // tmp log so we can see these
    const id = b4a.toString(this.discoveryKey, 'hex')
    console.log(
      '[hypercore] conflict detected in ' +
        id +
        ' (writable=' +
        !!this.header.keyPair +
        ',quorum=' +
        this.header.manifest.quorum +
        ')'
    )
    await this._onconflict(proof)
    return true
  }

  async _repairTreeNodes(proof) {
    if (!this._repairMode) return false

    await this.state.mutex.lock()

    for (let i = this.monitors.length - 1; i >= 0; i--) {
      this.monitors[i].emit('repairing', proof)
    }

    try {
      const batch = MerkleTree.verifyFullyRemote(this.state, proof)
      this._verifyBatchUpgrade(batch, proof.manifest)
    } catch {
      this.state.mutex.unlock()
      for (let i = this.monitors.length - 1; i >= 0; i--) {
        this.monitors[i].emit('repair-failed')
      }
      return false
    }

    // Attempt to repair local merkle tree with remote roots
    const atom = this.storage.createAtom()
    const atomized = this.storage.atomize(atom)
    const tx = atomized.write()
    for (const node of proof.upgrade.nodes) {
      tx.putTreeNode(node)
    }
    await tx.flush()

    // Try local proof again
    try {
      const rx = atomized.read()
      const treeProofPromise = MerkleTree.proof(this.state, rx, {
        block: null,
        hash: null,
        seek: null,
        upgrade: {
          start: 0,
          length: proof.upgrade.length
        }
      })

      rx.tryFlush()

      const treeProof = await treeProofPromise

      const verifyBatch = MerkleTree.verifyFullyRemote(this.state, await treeProof.settle())
      this._verifyBatchUpgrade(verifyBatch, this.header.manifest)
    } catch (err) {
      this.state.mutex.unlock()
      for (let i = this.monitors.length - 1; i >= 0; i--) {
        this.monitors[i].emit('repair-failed')
      }
      return false
    }

    await atom.flush()

    for (let i = this.monitors.length - 1; i >= 0; i--) {
      this.monitors[i].emit('repaired', proof)
    }
    this.replicator.setPushOnly(false)
    this.state.mutex.unlock()
    return true
  }

  async verifyReorg(proof) {
    const batch = new ReorgBatch(this.state)
    await MerkleTree.reorg(this.state, proof, batch)
    const manifest = this._verifyBatchUpgrade(batch, proof.manifest)

    if (manifest && !this.header.manifest) {
      await this.state.mutex.lock()
      try {
        if (manifest && this.header.manifest === null) {
          const tx = this.state.createWriteBatch()
          this._setManifest(tx, Verifier.createManifest(manifest), null)
          await this.state.flush()
        }
      } finally {
        this.state._unlock()
      }
    }

    return batch
  }

  async verify(proof, from) {
    // We cannot apply "other forks" atm.
    // We should probably still try and they are likely super similar for non upgrades
    // but this is easy atm (and the above layer will just retry)
    if (proof.fork !== this.state.fork) return false

    const batch = await MerkleTree.verify(this.state, proof)

    if (batch.upgraded && batch.length <= this.state.length) {
      await batch.downgrade()
    }

    if (!batch.commitable()) {
      return false
    }

    const value = (proof.block && proof.block.value) || null
    const op = {
      batch,
      bitfield: value && { drop: false, start: proof.block.index, length: 1 },
      value,
      manifest: proof.manifest,
      from
    }

    if (batch.upgraded) {
      return this._verifyExclusive(op)
    }

    if (this._verifies !== null) {
      const verifies = this._verifies
      const i = verifies.push(op)
      await this._verified
      return verifies[i] !== null
    }

    this._verifies = [op]
    this._verified = this._verifyShared()

    return this._verified
  }

  async reorg(batch) {
    if (!batch.commitable()) return false

    this.truncating++

    try {
      await this.state.reorg(batch)
    } finally {
      this.truncating--
    }

    return true
  }

  openSkipBitfield() {
    if (this.skipBitfield !== null) return this.skipBitfield
    this.skipBitfield = new RemoteBitfield()
    const buf = this.bitfield.toBuffer(this.state.length)
    const bitfield = new Uint32Array(buf.buffer, buf.byteOffset, buf.byteLength / 4)
    this.skipBitfield.insert(0, bitfield)
    return this.skipBitfield
  }

  _setBitfieldRanges(start, end, value) {
    this.bitfield.setRange(start, end, value)
    if (this.skipBitfield !== null) this.skipBitfield.setRange(start, end, value)
  }

  close() {
    if (!this.closing) this.closing = this._close()
    return this.closing
  }

  updateContiguousLength(bitfield) {
    const contig = updateContigBatch(this.header.hints.contiguousLength, bitfield, this.bitfield)

    if (contig.length !== -1 && contig.length !== this.header.hints.contiguousLength) {
      this.header.hints.contiguousLength = contig.length
      this.hintsChanged = true
    }
  }

  updateRemoteContiguousLength(length) {
    this.header.hints.remoteContiguousLength = length
    this.hintsChanged = true
    this.remoteContiguousLengthChanged = true
  }

  onappend(tree, bitfield) {
    this.header.tree = tree

    if (!bitfield) {
      this.replicator.onupgrade()
      return
    }

    this.replicator.cork()

    const { start, length, drop } = bitfield

    this._setBitfieldRanges(start, start + length, true)
    this.updateContiguousLength({ start, length, drop: false })

    this.replicator.onupgrade()
    this.replicator.onhave(start, length, drop)
    this.replicator.uncork()
  }

  ontruncate(tree, { start, length }) {
    if (tree) this.header.tree = tree

    this.replicator.cork()

    this.replicator.ontruncate(start, length)
    this.replicator.onhave(start, length, true)
    this.replicator.onupgrade()
    this.replicator.uncork()

    for (const sessionState of this.sessionStates) {
      if (start < sessionState.snapshotCompatLength) sessionState.snapshotCompatLength = start
    }

    this._setBitfieldRanges(start, start + length, false)
    this.updateContiguousLength({ start, length, drop: true })
  }

  async _onconflict(proof) {
    await this.replicator.onconflict()

    for (let i = this.monitors.length - 1; i >= 0; i--) {
      const s = this.monitors[i]
      s.emit('conflict', proof.upgrade.length, proof.fork, proof)
    }

    const err = new Error('Two conflicting signatures exist for length ' + proof.upgrade.length)
    await this.closeAllSessions(err)
  }

  async closeAllSessions(err) {
    // this.sessions modifies itself when a session closes
    // This way we ensure we indeed iterate over all sessions
    const sessions = this.allSessions()

    const all = []
    for (const s of sessions) all.push(s.close({ error: err, force: false })) // force false or else infinite recursion
    await Promise.allSettled(all)
  }

  async destroy() {
    if (this.destroyed === true) return
    this.destroyed = true

    if (this.hasSession() === true) throw new Error('Cannot destroy while sessions are open')

    const weakSessions = this.allSessions()

    if (this.replicator) this.replicator.destroy()
    if (this.state) await this.state.close()

    // close all pending weak sessions...
    for (const s of weakSessions) s.close().catch(noop)
  }

  async _close() {
    if (this.opened === false) await this.opening
    if (this.hasSession() === true) throw new Error('Cannot close while sessions are open')

    if (this.replicator) await this.replicator.close()

    await this.destroy()
    if (this.autoClose) await this.storage.store.close()

    this.closed = true
  }
}

function updateContigBatch(start, upd, bitfield) {
  const end = upd.start + upd.length

  let c = start

  if (upd.drop) {
    // If we dropped a block in the current contig range, "downgrade" it
    if (c > upd.start) {
      c = upd.start
    }
  } else {
    if (c <= end && c >= upd.start) {
      c = end
      while (bitfield.get(c)) c++
    }
  }

  if (c === start) {
    return {
      length: -1
    }
  }

  if (c > start) {
    return {
      length: c
    }
  }

  return {
    length: c
  }
}

function getDefaultTree() {
  return {
    fork: 0,
    length: 0,
    rootHash: null,
    signature: null,
    timestamp: 0
  }
}

function parseHeader(info) {
  if (!info) return null

  return {
    key: info.key,
    manifest: info.manifest,
    external: null,
    keyPair: info.keyPair,
    tree: info.head || getDefaultTree(),
    group: info.group,
    hints: {
      reorgs: [],
      contiguousLength: info.hints ? info.hints.contiguousLength : 0,
      remoteContiguousLength: info.hints ? info.hints.remoteContiguousLength : 0,
      recovering: info.hints ? info.hints.recovering : 0
    }
  }
}

async function maybeGetRootsFromStorage(storage, length) {
  try {
    return length ? await MerkleTree.getRootsFromStorage(storage, length) : []
  } catch (err) {
    if (err.code !== 'INVALID_OPERATION') throw err
    // If INVALID_OPERATION, a root is likely missing so load empty roots to try to recover
    return []
  }
}

function noop() {}

async function getCoreInfo(storage) {
  const r = storage.read()

  const auth = r.getAuth()
  const head = r.getHead()
  const hints = r.getHints()
  const group = r.getGroup()

  r.tryFlush()

  const [authInfo, headInfo, hintsInfo, groupInfo] = await Promise.all([auth, head, hints, group])
  return {
    ...authInfo,
    head: headInfo,
    hints: hintsInfo,
    group: groupInfo
  }
}
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const b4a = require('b4a')
const { DEFAULT_ENCRYPTION } = require('./caps')

const nonce = b4a.alloc(sodium.crypto_stream_NONCEBYTES)

module.exports = class DefaultEncryption {
  static PADDING = 8

  constructor(encryptionKey, hypercoreKey, opts = {}) {
    this.key = encryptionKey
    this.compat = opts.compat === true

    const keys = DefaultEncryption.deriveKeys(encryptionKey, hypercoreKey, opts)

    this.blockKey = keys.block
    this.blindingKey = keys.blinding
  }

  static deriveKeys(encryptionKey, hypercoreKey, { block = false, compat = false } = {}) {
    const subKeys = b4a.alloc(2 * sodium.crypto_stream_KEYBYTES)

    const blockKey = block ? encryptionKey : subKeys.subarray(0, sodium.crypto_stream_KEYBYTES)
    const blindingKey = subKeys.subarray(sodium.crypto_stream_KEYBYTES)

    if (!block) {
      if (compat) {
        sodium.crypto_generichash_batch(blockKey, [encryptionKey], hypercoreKey)
      } else {
        sodium.crypto_generichash_batch(blockKey, [DEFAULT_ENCRYPTION, hypercoreKey, encryptionKey])
      }
    }

    sodium.crypto_generichash(blindingKey, blockKey)

    return {
      blinding: blindingKey,
      block: blockKey
    }
  }

  static blockEncryptionKey(hypercoreKey, encryptionKey) {
    const blockKey = b4a.alloc(sodium.crypto_stream_KEYBYTES)
    sodium.crypto_generichash_batch(blockKey, [DEFAULT_ENCRYPTION, hypercoreKey, encryptionKey])
    return blockKey
  }

  static encrypt(index, block, fork, blockKey, blindingKey) {
    const padding = block.subarray(0, DefaultEncryption.PADDING)
    block = block.subarray(DefaultEncryption.PADDING)

    c.uint64.encode({ start: 0, end: 8, buffer: padding }, fork)
    c.uint64.encode({ start: 0, end: 8, buffer: nonce }, index)

    // Zero out any previous padding.
    nonce.fill(0, 8, 8 + padding.byteLength)

    // Blind the fork ID, possibly risking reusing the nonce on a reorg of the
    // Hypercore. This is fine as the blinding is best-effort and the latest
    // fork ID shared on replication anyway.
    sodium.crypto_stream_xor(padding, padding, nonce, blindingKey)

    nonce.set(padding, 8)

    // The combination of a (blinded) fork ID and a block index is unique for a
    // given Hypercore and is therefore a valid nonce for encrypting the block.
    sodium.crypto_stream_xor(block, block, nonce, blockKey)
  }

  static decrypt(index, block, blockKey) {
    const padding = block.subarray(0, DefaultEncryption.PADDING)
    block = block.subarray(DefaultEncryption.PADDING)

    c.uint64.encode({ start: 0, end: 8, buffer: nonce }, index)

    nonce.set(padding, 8)

    // Decrypt the block using the blinded fork ID.
    sodium.crypto_stream_xor(block, block, nonce, blockKey)
  }

  encrypt(index, block, fork, core) {
    if (core.compat !== this.compat) this._reload(core)
    return DefaultEncryption.encrypt(index, block, fork, this.blockKey, this.blindingKey)
  }

  decrypt(index, block, core) {
    if (core.compat !== this.compat) this._reload(core)
    return DefaultEncryption.decrypt(index, block, this.blockKey)
  }

  padding() {
    return DefaultEncryption.PADDING
  }

  _reload(core) {
    const block = b4a.equals(this.key, this.blockKey)
    const keys = DefaultEncryption.deriveKeys(this.key, core.key, { block, compat: core.compat })

    this.blockKey = keys.blockKey
    this.blindingKey = keys.blindingKey
  }
}
module.exports = class Download {
  constructor(session, range) {
    this.session = session
    this.range = range
    this.request = null
    this.opened = false
    this.opening = this._open()
    this.opening.catch(noop)
  }

  ready() {
    return this.opening
  }

  async _open() {
    if (this.session.opened === false) await this.session.opening
    this._download()
    this.opened = true
  }

  async done() {
    await this.ready()

    try {
      return await this.request.promise
    } catch (err) {
      if (isSessionMoved(err)) return this._download()
      throw err
    }
  }

  _download() {
    const activeRequests = (this.range && this.range.activeRequests) || this.session.activeRequests
    this.request = this.session.core.replicator.addRange(activeRequests, this.range)
    this.request.promise.catch(noop)
    return this.request.promise
  }

  /**
   * Deprecated. Use `range.done()`.
   */
  downloaded() {
    return this.done()
  }

  destroy() {
    this._destroyBackground().catch(noop)
  }

  async _destroyBackground() {
    if (this.opened === false) await this.ready()
    if (this.request.context) this.request.context.detach(this.request)
  }
}

function noop() {}

function isSessionMoved(err) {
  return err.code === 'SESSION_MOVED'
}
module.exports = {
  SMALL_WANTS: 1
}
// this helper is for fully remote proofs, is like in a push notification where no other context exists

const { MerkleTree } = require('./merkle-tree.js')
const messages = require('./messages.js')
const b4a = require('b4a')
const c = require('compact-encoding')
const crypto = require('hypercore-crypto')
const flat = require('flat-tree')

class SlimSession {
  constructor(storage, auth, head, roots) {
    this.fork = head ? head.fork : 0
    this.roots = roots
    this.length = head ? head.length : 0
    this.signature = head ? head.signature : null
    this.ancestors = this.length
    this.byteLength = 0
    this.prologue = auth.manifest.prologue
    this.storage = storage

    for (let i = 0; i < roots.length; i++) this.byteLength += roots[i].size
  }
}

module.exports = { verify, proof }

async function verify(storage, buffer, { referrer = null } = {}) {
  const state = { buffer, start: 0, end: buffer.byteLength }

  const discoveryKey = c.fixed32.decode(state)
  const proof = messages.wire.data.decode(state)

  const result = {
    key: null,
    discoveryKey,
    newer: true,
    length: 0,
    proof,
    block: null
  }

  const core = await storage.resumeCore(discoveryKey)
  if (core === null) return null

  let rx = core.read()
  const authPromise = rx.getAuth()
  const headPromise = rx.getHead()
  const referrerPromise = rx.getUserData('referrer')

  rx.tryFlush()

  const [auth, head, ref] = await Promise.all([authPromise, headPromise, referrerPromise])

  if (auth === null) return null

  if (referrer && (!ref || !b4a.equals(ref, referrer))) return null

  rx = core.read()

  const rootPromises = []

  for (const index of flat.fullRoots(head ? 2 * head.length : 0)) {
    rootPromises.push(rx.getTreeNode(index))
  }

  rx.tryFlush()

  let roots = await Promise.all(rootPromises)
  if (roots.some(isNull)) roots = []

  const length = head ? head.length : 0

  if (!auth.manifest || !auth.manifest.signers.length) return null

  const batch = await MerkleTree.verifyFullyRemote(new SlimSession(core, auth, head, roots), proof)
  const publicKey = auth.manifest.signers[0].publicKey

  let signable = null
  let signature = null

  if (auth.manifest.version === 0) {
    signable = batch.signable(auth.manifest.signers[0].namespace)
    signature = batch.signature
  } else {
    if (batch.signature[0] !== 1) return null
    if (batch.signature[1] !== 0) return null

    signable = batch.signable(auth.key)
    signature = batch.signature.subarray(2, 66)
  }

  if (!crypto.verify(signable, signature, publicKey)) {
    return null
  }

  result.key = auth.key
  result.discoveryKey = discoveryKey
  result.newer = batch.length > length
  result.length = batch.length
  result.block = proof.block

  return result
}

async function proof(sender, { index, block = null, upgrade = null } = {}) {
  const proof = await sender.proof({
    block: block ? { index, nodes: 0 } : null,
    upgrade: upgrade ? upgrade : { start: 0, length: sender.length }
  })

  if (block) proof.block.value = block
  proof.manifest = sender.core.header.manifest

  const state = { buffer: null, start: 0, end: 0 }
  const data = { request: 0, ...proof }

  c.fixed32.preencode(state, sender.discoveryKey)
  messages.wire.data.preencode(state, data)

  state.buffer = b4a.allocUnsafe(state.end)

  c.fixed32.encode(state, sender.discoveryKey)
  messages.wire.data.encode(state, data)

  return state.buffer
}

function isNull(x) {
  return x === null
}
const TICKS = 16

module.exports = class HotswapQueue {
  constructor() {
    this.priorities = [[], [], []]
  }

  *pick(peer) {
    for (let i = 0; i < this.priorities.length; i++) {
      // try first one more than second one etc etc
      let ticks = (this.priorities.length - i) * TICKS
      const queue = this.priorities[i]

      for (let j = 0; j < queue.length; j++) {
        const r = j + Math.floor(Math.random() * queue.length - j)
        const a = queue[j]
        const b = queue[r]

        if (r !== j) {
          queue[(b.hotswap.index = j)] = b
          queue[(a.hotswap.index = r)] = a
        }

        if (hasInflight(b, peer)) continue

        yield b

        if (--ticks <= 0) break
      }
    }
  }

  add(block) {
    if (block.hotswap !== null) this.remove(block)
    if (block.inflight.length === 0 || block.inflight.length >= 3) return

    // TODO: also use other stuff to determine queue prio
    const queue = this.priorities[block.inflight.length - 1]

    const index = queue.push(block) - 1
    block.hotswap = { ref: this, queue, index }
  }

  remove(block) {
    const hotswap = block.hotswap
    if (hotswap === null) return

    block.hotswap = null
    const head = hotswap.queue.pop()
    if (head === block) return
    hotswap.queue[(head.hotswap.index = hotswap.index)] = head
  }
}

function hasInflight(block, peer) {
  for (let j = 0; j < block.inflight.length; j++) {
    if (block.inflight[j].peer === peer) return true
  }
  return false
}
module.exports = class Info {
  constructor(opts = {}) {
    this.key = opts.key
    this.discoveryKey = opts.discoveryKey
    this.length = opts.length || 0
    this.contiguousLength = opts.contiguousLength || 0
    this.byteLength = opts.byteLength || 0
    this.fork = opts.fork || 0
    this.padding = opts.padding || 0
    this.storage = opts.storage || null
  }

  static async from(session, opts = {}) {
    return new Info({
      key: session.key,
      discoveryKey: session.discoveryKey,
      length: session.length,
      contiguousLength: session.contiguousLength,
      byteLength: session.byteLength,
      fork: session.fork,
      padding: session.padding,
      storage: opts.storage ? await this.storage(session) : null
    })
  }

  static async storage(session) {
    const { oplog, tree, blocks, bitfield } = session.core
    try {
      return {
        oplog: await Info.bytesUsed(oplog.storage),
        tree: await Info.bytesUsed(tree.storage),
        blocks: await Info.bytesUsed(blocks.storage),
        bitfield: await Info.bytesUsed(bitfield.storage)
      }
    } catch {
      return null
    }
  }

  static bytesUsed(file) {
    return new Promise((resolve, reject) => {
      file.stat((err, st) => {
        if (err) {
          resolve(0) // prob just file not found (TODO, improve)
        } else if (typeof st.blocks !== 'number') {
          reject(new Error('cannot determine bytes used'))
        } else {
          resolve(st.blocks * 512)
        }
      })
    })
  }
}
const b4a = require('b4a')

module.exports = function (core, depth, opts) {
  let indent = ''
  if (typeof opts.indentationLvl === 'number') {
    while (indent.length < opts.indentationLvl) indent += ' '
  }

  let peers = ''
  const min = Math.min(core.peers.length, 5)

  for (let i = 0; i < min; i++) {
    const peer = core.peers[i]

    peers += `${indent}    Peer(\n`
    peers += `${indent}      remotePublicKey: ${opts.stylize(toHex(peer.remotePublicKey), 'string')}\n`
    peers += `${indent}      remoteLength: ${opts.stylize(peer.remoteLength, 'number')}\n`
    peers += `${indent}      remoteFork: ${opts.stylize(peer.remoteFork, 'number')}\n`
    peers += `${indent}      remoteCanUpgrade: ${opts.stylize(peer.remoteCanUpgrade, 'boolean')}\n`
    peers += `${indent}    )\n`
  }

  if (core.peers.length > 5) {
    peers += `${indent}  ... and ${core.peers.length - 5} more\n`
  }

  if (peers) peers = `[\n${peers}${indent}  ]`
  else peers = `[ ${opts.stylize(0, 'number')} ]`

  return (
    `${core.constructor.name}(\n` +
    `${indent}  id: ${opts.stylize(core.id, 'string')}\n` +
    `${indent}  key: ${opts.stylize(toHex(core.key), 'string')}\n` +
    `${indent}  discoveryKey: ${opts.stylize(toHex(core.discoveryKey), 'string')}\n` +
    `${indent}  opened: ${opts.stylize(core.opened, 'boolean')}\n` +
    `${indent}  closed: ${opts.stylize(core.closed, 'boolean')}\n` +
    `${indent}  snapshotted: ${opts.stylize(core.snapshotted, 'boolean')}\n` +
    `${indent}  writable: ${opts.stylize(core.writable, 'boolean')}\n` +
    `${indent}  length: ${opts.stylize(core.length, 'number')}\n` +
    `${indent}  fork: ${opts.stylize(core.fork, 'number')}\n` +
    `${indent}  sessions: [ ${opts.stylize(core.sessions.length, 'number')} ]\n` +
    `${indent}  activeRequests: [ ${opts.stylize(core.activeRequests.length, 'number')} ]\n` +
    `${indent}  peers: ${peers}\n` +
    `${indent})`
  )
}

function toHex(buf) {
  return buf && b4a.toString(buf, 'hex')
}
const BigSparseArray = require('big-sparse-array')
const { Transform } = require('streamx')
const quickbit = require('./compat').quickbit
const b4a = require('b4a')

const BITS_PER_PAGE = 32768
const BYTES_PER_PAGE = BITS_PER_PAGE / 8

class MarkPage {
  constructor() {
    this.bitfield = null
    this.loaded = new Promise((resolve) => {
      this.load = resolve
    })
  }

  setBitfield(bitfield) {
    this.bitfield = bitfield
    this.load()
  }

  get(index) {
    return quickbit.get(this.bitfield, index)
  }

  set(index, val) {
    quickbit.set(this.bitfield, index, val)
  }
}

module.exports = class MarkBitfield {
  static BITS_PER_PAGE = BITS_PER_PAGE
  static BYTES_PER_PAGE = BYTES_PER_PAGE

  constructor(storage) {
    this.storage = storage
    this._pages = new BigSparseArray()
  }

  async loadPage(pageIndex) {
    const p = this._pages.set(pageIndex, new MarkPage())
    const rx = this.storage.read()
    const pageBuf = rx.getMark(pageIndex)
    rx.tryFlush()
    const bitfield = (await pageBuf) ?? b4a.alloc(BYTES_PER_PAGE)
    await p.setBitfield(bitfield)
    return p
  }

  async get(index) {
    const j = index & (BITS_PER_PAGE - 1)
    const i = (index - j) / BITS_PER_PAGE

    let p = this._pages.get(i)
    if (!p) p = await this.loadPage(i)

    return p.get(j)
  }

  async set(index, val) {
    const j = index & (BITS_PER_PAGE - 1)
    const i = (index - j) / BITS_PER_PAGE

    let p = this._pages.get(i)

    if (!p && val) p = await this.loadPage(i)

    if (p) {
      await p.loaded
      p.set(j, val)
      const tx = this.storage.write()
      tx.putMark(i, p.bitfield)
      await tx.flush()
    }
  }

  async clear() {
    const tx = this.storage.write()
    tx.deleteMarkRange(0, -1)
    await tx.flush()
    this._pages = new BigSparseArray()
  }

  createMarkStream({ reverse = false } = {}) {
    return this.storage.createMarkStream({ reverse }).pipe(
      new Transform({
        transform({ index, page }, cb) {
          let bitIndex = reverse
            ? quickbit.findLast(page, true, BITS_PER_PAGE)
            : quickbit.findFirst(page, true, 0)
          while (bitIndex !== -1) {
            const blockIndex = index * BITS_PER_PAGE + bitIndex
            this.push(blockIndex)

            // Account for `bitIndex` being either causing infinite loop
            if (bitIndex === 0 && reverse) break

            bitIndex = reverse
              ? quickbit.findLast(page, true, bitIndex - 1)
              : quickbit.findFirst(page, true, bitIndex + 1)
          }

          cb(null)
        }
      })
    )
  }
}
const flat = require('flat-tree')
const crypto = require('hypercore-crypto')
const b4a = require('b4a')
const unslab = require('unslab')
const caps = require('./caps')
const {
  INVALID_PROOF,
  INVALID_CHECKSUM,
  INVALID_OPERATION,
  BAD_ARGUMENT,
  ASSERTION
} = require('hypercore-errors')

class NodeQueue {
  constructor(nodes, extra = null) {
    this.i = 0
    this.nodes = nodes
    this.extra = extra
    this.length = nodes.length + (this.extra === null ? 0 : 1)
  }

  shift(index) {
    if (this.extra !== null && this.extra.index === index) {
      const node = this.extra
      this.extra = null
      this.length--
      return node
    }

    if (this.i >= this.nodes.length) {
      throw INVALID_OPERATION('Expected node ' + index + ', got (nil)')
    }

    const node = this.nodes[this.i++]
    if (node.index !== index) {
      throw INVALID_OPERATION('Expected node ' + index + ', got node ' + node.index)
    }

    this.length--
    return node
  }
}

class MerkleTreeBatch {
  constructor(session) {
    this.fork = session.fork
    this.roots = [...session.roots]
    this.length = session.length
    this.signature = session.signature
    this.ancestors = session.length
    this.byteLength = session.byteLength
    this.prologue = session.prologue
    this.hashCached = null

    this.committed = false
    this.truncated = false
    this.treeLength = session.length
    this.treeFork = session.fork
    this.storage = session.storage
    this.session = session
    this.nodes = []
    this.upgraded = false
  }

  checkout(length, additionalRoots) {
    const roots = []
    let r = 0

    const head = 2 * length - 2
    const gaps = new Set()
    const all = new Map()

    // additional roots is so the original roots can be passed (we mutate the array in appendRoot)
    if (additionalRoots) {
      for (const node of additionalRoots) all.set(node.index, node)
    }

    for (const node of this.nodes) all.set(node.index, node)

    for (const index of flat.fullRoots(head + 2)) {
      const left = flat.leftSpan(index)
      if (left !== 0) gaps.add(left - 1)

      if (r < this.roots.length && this.roots[r].index === index) {
        roots.push(this.roots[r++])
        continue
      }
      const node = all.get(index)
      if (!node) throw new BAD_ARGUMENT('root missing for given length')
      roots.push(node)
    }

    this.roots = roots
    this.length = length
    this.byteLength = totalSize(roots)
    this.hashCached = null
    this.signature = null

    for (let i = 0; i < this.nodes.length; i++) {
      const index = this.nodes[i].index
      if (index <= head && !gaps.has(index)) continue
      const last = this.nodes.pop()
      if (i < this.nodes.length) this.nodes[i--] = last
    }
  }

  prune(length) {
    if (length === 0) return

    const head = 2 * length - 2
    const gaps = new Set()

    // TODO: make a function for this in flat-tree
    for (const index of flat.fullRoots(head + 2)) {
      const left = flat.leftSpan(index)
      if (left !== 0) gaps.add(left - 1)
    }

    for (let i = 0; i < this.nodes.length; i++) {
      const index = this.nodes[i].index
      if (index > head || gaps.has(index)) continue
      const last = this.nodes.pop()
      if (i < this.nodes.length) this.nodes[i--] = last
    }
  }

  clone() {
    const b = new MerkleTreeBatch(this.session)

    b.fork = this.fork
    b.roots = [...this.roots]
    b.length = this.length
    b.byteLength = this.byteLength
    b.signature = this.signature
    b.treeLength = this.treeLength
    b.treeFork = this.treeFork
    b.tree = this.tree
    b.nodes = [...this.nodes]
    b.upgraded = this.upgraded

    return b
  }

  hash() {
    if (this.hashCached === null) this.hashCached = unslab(crypto.tree(this.roots))
    return this.hashCached
  }

  signable(manifestHash) {
    return caps.treeSignable(manifestHash, this.hash(), this.length, this.fork)
  }

  signableCompat(noHeader) {
    return caps.treeSignableCompat(this.hash(), this.length, this.fork, noHeader)
  }

  get(index) {
    if (index >= this.length * 2) {
      return null
    }

    for (const n of this.nodes) {
      if (n.index === index) return n
    }

    return getTreeNodeFromStorage(this.session.storage, index)
  }

  // deprecated, use sssion proof instead
  proof(batch, { block, hash, seek, upgrade }) {
    return generateProof(this.session, batch, block, hash, seek, upgrade)
  }

  verifyUpgrade(proof) {
    const unverified = verifyTree(proof, this.nodes)

    if (!proof.upgrade) throw INVALID_OPERATION('Expected upgrade proof')

    return verifyUpgrade(proof, unverified, this)
  }

  addNodesUnsafe(nodes) {
    for (let i = 0; i < nodes.length; i++) {
      this.nodes.push(nodes[i])
    }
  }

  append(buf) {
    const head = this.length * 2
    const ite = flat.iterator(head)
    const node = blockNode(head, buf)

    this.appendRoot(node, ite)
  }

  appendRoot(node, ite) {
    node = unslabNode(node)
    this.hashCached = null
    this.upgraded = true
    this.length += ite.factor / 2
    this.byteLength += node.size
    this.roots.push(node)
    this.nodes.push(node)

    while (this.roots.length > 1) {
      const a = this.roots[this.roots.length - 1]
      const b = this.roots[this.roots.length - 2]

      // TODO: just have a peek sibling instead? (pretty sure it's always the left sib as well)
      if (ite.sibling() !== b.index) {
        ite.sibling() // unset so it always points to last root
        break
      }

      const node = unslabNode(parentNode(ite.parent(), a, b))
      this.nodes.push(node)
      this.roots.pop()
      this.roots.pop()
      this.roots.push(node)
    }
  }

  commitable() {
    return (
      this.treeFork === this.session.fork &&
      (this.upgraded
        ? this.treeLength === this.session.length
        : this.treeLength <= this.session.length)
    )
  }

  commit(tx) {
    if (tx === undefined) throw INVALID_OPERATION('No database batch was passed')

    if (this.session.core._repairMode) {
      throw ASSERTION('Cannot commit while repair mode is on')
    }

    if (!this.commitable()) {
      throw INVALID_OPERATION('Tree was modified during batch, refusing to commit')
    }

    if (this.upgraded) this._commitUpgrade(tx)

    for (let i = 0; i < this.nodes.length; i++) {
      const node = this.nodes[i]
      tx.putTreeNode(node)
    }

    this.committed = true

    return this
  }

  _commitUpgrade(tx) {
    // TODO: If easy to detect, we should refuse an trunc+append here without a fork id
    // change. Will only happen on user error so mostly to prevent that.

    if (this.ancestors < this.treeLength) {
      tx.deleteTreeNodeRange(this.ancestors * 2, this.treeLength * 2)

      if (this.ancestors > 0) {
        const head = this.ancestors * 2
        const ite = flat.iterator(head - 2)

        while (true) {
          if (ite.contains(head) && ite.index < head) {
            tx.deleteTreeNode(ite.index)
          }
          if (ite.offset === 0) break
          ite.parent()
        }

        this.truncated = true
      }
    }
  }

  seek(bytes, padding) {
    return new ByteSeeker(this, this, bytes, padding)
  }

  byteRange(index) {
    const rx = this.storage.read()
    const range = getByteRange(this, index, rx)
    rx.tryFlush()

    return range
  }

  byteOffset(index) {
    if (index === 2 * this.length) return this.byteLength

    const rx = this.storage.read()
    const offset = getByteOffset(this, index, rx)
    rx.tryFlush()

    return offset
  }

  async downgrade() {
    if (!this.upgraded) return true

    const rx = this.storage.read()
    const nodePromises = []

    for (const r of this.roots) {
      nodePromises.push(rx.getTreeNode(r.index))
    }

    rx.tryFlush()

    const nodes = await Promise.all(nodePromises)

    for (let i = 0; i < this.roots.length; i++) {
      const root = this.roots[i]
      const node = nodes[i]

      if (!node) return false
      if (!b4a.equals(node.hash, root.hash)) return false
    }

    this.upgraded = false
    return true
  }

  async restore(length) {
    if (length === this.length) return this

    const roots = unslabNodes(await MerkleTree.getRootsFromStorage(this.storage, length))

    this.roots = roots
    this.length = length
    this.byteLength = totalSize(roots)
    this.ancestors = length

    for (const node of roots) this.byteLength += node.size

    return this
  }
}

class ReorgBatch extends MerkleTreeBatch {
  constructor(session) {
    super(session)

    this.roots = []
    this.length = 0
    this.byteLength = 0
    this.diff = null
    this.ancestors = 0
    // We set upgraded because reorgs are signed so hit will
    // hit the same code paths (like the treeLength check in commit)
    this.upgraded = true
    this.want = {
      nodes: 0,
      start: 0,
      end: 0
    }
  }

  get finished() {
    return this.want === null
  }

  update(proof) {
    if (this.want === null) return true

    const nodes = []
    const root = verifyTree(proof, nodes)

    if (root === null || !b4a.equals(root.hash, this.diff.hash)) return false

    this.nodes.push(...nodes)
    return this._update(nodes)
  }

  async _update(nodes) {
    const n = new Map()
    for (const node of nodes) n.set(node.index, node)

    let diff = null
    const ite = flat.iterator(this.diff.index)
    const startingDiff = this.diff

    while ((ite.index & 1) !== 0) {
      const left = n.get(ite.leftChild())
      if (!left) break

      const existing = await getTreeNodeFromStorage(this.session.storage, left.index)
      if (!existing || !b4a.equals(existing.hash, left.hash)) {
        diff = left
      } else {
        diff = n.get(ite.sibling())
      }
    }

    if ((this.diff.index & 1) === 0) return true
    if (diff === null) return false
    if (startingDiff !== this.diff) return false

    return this._updateDiffRoot(diff)
  }

  _updateDiffRoot(diff) {
    if (this.want === null) return true

    const spans = flat.spans(diff.index)
    const start = spans[0] / 2
    const end = Math.min(this.treeLength, spans[1] / 2 + 1)
    const len = end - start

    this.ancestors = start
    this.diff = diff

    if ((diff.index & 1) === 0 || this.want.start >= this.treeLength || len <= 0) {
      this.want = null
      return true
    }

    this.want.start = start
    this.want.end = end
    this.want.nodes = log2(spans[1] - spans[0] + 2) - 1

    return false
  }
}

class ByteSeeker {
  constructor(session, bytes, padding = 0) {
    this.session = session
    this.bytes = bytes
    this.padding = padding

    const size = session.byteLength - session.length * padding

    this.start = bytes >= size ? session.length : 0
    this.end = bytes < size ? session.length : 0
  }

  async _seek(bytes) {
    if (!bytes) return [0, 0]

    for (const node of this.session.roots) {
      // all async ticks happen once we find the root so safe
      const size = getUnpaddedSize(node, this.padding, null)

      if (bytes === size) return [flat.rightSpan(node.index) + 2, 0]
      if (bytes > size) {
        bytes -= size
        continue
      }

      const ite = flat.iterator(node.index)

      while ((ite.index & 1) !== 0) {
        const l = await getTreeNodeFromStorage(this.session.storage, ite.leftChild())

        if (l) {
          const size = getUnpaddedSize(l, this.padding, ite)

          if (size === bytes) return [ite.rightSpan() + 2, 0]
          if (size > bytes) continue
          bytes -= size
          ite.sibling()
        } else {
          ite.parent()
          return [ite.index, bytes]
        }
      }

      return [ite.index, bytes]
    }

    return null
  }

  async update() {
    // TODO: combine _seek and this, much simpler
    const res = await this._seek(this.bytes)
    if (!res) return null
    if ((res[0] & 1) === 0) return [res[0] / 2, res[1]]

    const span = flat.spans(res[0])
    this.start = span[0] / 2
    this.end = span[1] / 2 + 1

    return null
  }
}

class TreeProof {
  constructor(session, block, hash, seek, upgrade) {
    this.fork = session.fork
    this.signature = session.signature

    this.block = block
    this.hash = hash
    this.seek = seek
    this.upgrade = upgrade

    this.pending = {
      node: null,
      seek: null,
      upgrade: null,
      additionalUpgrade: null
    }
  }

  async settle() {
    const result = {
      fork: this.fork,
      block: null,
      hash: null,
      seek: null,
      upgrade: null,
      manifest: null
    }

    const [pNode, pSeek, pUpgrade, pAdditional] = await settleProof(this.pending)

    if (this.block) {
      if (pNode === null) throw INVALID_OPERATION('Invalid block request')
      result.block = {
        index: this.block.index,
        value: null, // populated upstream, alloc it here for simplicity
        nodes: pNode
      }
    } else if (this.hash) {
      if (pNode === null) throw INVALID_OPERATION('Invalid block request')
      result.hash = {
        index: this.hash.index,
        nodes: pNode
      }
    }

    if (this.seek && pSeek !== null) {
      result.seek = {
        bytes: this.seek.bytes,
        nodes: pSeek
      }
    }

    if (this.upgrade) {
      result.upgrade = {
        start: this.upgrade.start,
        length: this.upgrade.length,
        nodes: pUpgrade,
        additionalNodes: pAdditional || [],
        signature: this.signature
      }
    }

    return result
  }
}

class MerkleTree {
  static hash(s) {
    return unslab(crypto.tree(s.roots))
  }

  static signable(s, namespace) {
    return caps.treeSignable(namespace, MerkleTree.hash(s), s.length, s.fork)
  }

  static size(roots) {
    return totalSize(roots)
  }

  static span(roots) {
    return totalSpan(roots)
  }

  static getRoots(session, length) {
    return MerkleTree.getRootsFromStorage(session.storage, length)
  }

  static getRootsFromStorage(storage, length) {
    const indexes = flat.fullRoots(2 * length)
    const roots = new Array(indexes.length)
    const rx = storage.read()

    for (let i = 0; i < indexes.length; i++) {
      roots[i] = getTreeNodeOrError(rx, indexes[i])
    }

    rx.tryFlush()

    return Promise.all(roots)
  }

  static async upgradeable(session, length) {
    const indexes = flat.fullRoots(2 * length)
    const roots = new Array(indexes.length)
    const rx = session.storage.read()

    for (let i = 0; i < indexes.length; i++) {
      roots[i] = rx.getTreeNode(indexes[i])
    }

    rx.tryFlush()

    for (const node of await Promise.all(roots)) {
      if (node === null) return false
    }

    return true
  }

  static seek(session, bytes, padding) {
    return new ByteSeeker(session, bytes, padding)
  }

  static get(session, index) {
    return getTreeNodeFromStorage(session.storage, index)
  }

  static async truncate(session, length, batch, fork = batch.fork) {
    const head = length * 2
    const fullRoots = flat.fullRoots(head)

    for (let i = 0; i < fullRoots.length; i++) {
      const root = fullRoots[i]
      if (i < batch.roots.length && batch.roots[i].index === root) continue

      while (batch.roots.length > i) batch.roots.pop()
      batch.roots.push(unslabNode(await getTreeNodeFromStorageOrError(session.storage, root)))
    }

    while (batch.roots.length > fullRoots.length) {
      batch.roots.pop()
    }

    batch.fork = fork
    batch.length = length
    batch.ancestors = length
    batch.byteLength = totalSize(batch.roots)
    batch.upgraded = true

    return batch
  }

  static async reorg(session, proof, batch) {
    let unverified = null

    if (proof.block || proof.hash || proof.seek) {
      unverified = verifyTree(proof, batch.nodes)
    }

    if (!verifyUpgrade(proof, unverified, batch)) {
      throw INVALID_PROOF('Fork proof not verifiable')
    }

    for (const root of batch.roots) {
      const existing = await getTreeNodeFromStorage(session.storage, root.index)
      if (existing && b4a.equals(existing.hash, root.hash)) continue
      batch._updateDiffRoot(root)
      break
    }

    if (batch.diff !== null) {
      await batch._update(batch.nodes)
    } else {
      batch.want = null
      batch.ancestors = batch.length
    }

    return batch
  }

  static verifyFullyRemote(session, proof) {
    // TODO: impl this less hackishly
    const batch = new MerkleTreeBatch(session)

    batch.fork = proof.fork
    batch.roots = []
    batch.length = 0
    batch.ancestors = 0
    batch.byteLength = 0

    let unverified = verifyTree(proof, batch.nodes)

    if (proof.upgrade) {
      if (verifyUpgrade(proof, unverified, batch)) {
        unverified = null
      }
    }

    return batch
  }

  static async verify(session, proof) {
    const batch = new MerkleTreeBatch(session)

    let unverified = verifyTree(proof, batch.nodes)

    if (proof.upgrade) {
      if (verifyUpgrade(proof, unverified, batch)) {
        unverified = null
      }
    }

    if (unverified) {
      const verified = await getTreeNodeFromStorageOrError(session.storage, unverified.index)
      if (!b4a.equals(verified.hash, unverified.hash)) {
        throw INVALID_CHECKSUM('Invalid checksum at node ' + unverified.index)
      }
    }

    return batch
  }

  static proof(session, rx, { block, hash, seek, upgrade }) {
    return generateProof(session, rx, block, hash, seek, upgrade)
  }

  static maxMissingNodes(index, length) {
    const head = 2 * length
    const ite = flat.iterator(index)

    // See iterator.rightSpan()
    const iteRightSpan = ite.index + ite.factor / 2 - 1
    // If the index is not in the current tree, we do not know how many missing nodes there are...
    if (iteRightSpan >= head) return 0

    for (const r of flat.fullRoots(head)) {
      if (r === index) return 0
    }

    // need missing nodes not inclusive of index
    ite.parent()

    let cnt = 0
    while (!ite.contains(head)) {
      cnt++
      ite.parent()
    }

    return cnt
  }

  static async missingNodes(session, index, length) {
    const head = 2 * length
    const ite = flat.iterator(index)

    // See iterator.rightSpan()
    const iteRightSpan = ite.index + ite.factor / 2 - 1
    // If the index is not in the current tree, we do not know how many missing nodes there are...
    if (iteRightSpan >= head) return 0

    let cnt = 0
    // TODO: we could prop use a read batch here and do this in blocks of X for perf
    while (!ite.contains(head) && !(await hasTreeNode(session.storage, ite.index))) {
      cnt++
      if (cnt >= 1024) {
        throw ASSERTION('Bad arguments to missingNodes index=' + index + ' at length=' + length)
      }
      ite.parent()
    }

    return cnt
  }

  static byteOffset(session, index) {
    return getByteOffsetSession(session, index, null)
  }

  static byteRange(session, index) {
    const rx = session.storage.read()
    const offset = getByteOffsetSession(session, index, rx)
    const size = getNodeSize(index, rx)
    rx.tryFlush()
    return Promise.all([offset, size])
  }

  static upgradeLength(proof) {
    const extra = proof.additionalNodes

    if (extra.length) {
      const last = extra[extra.length - 1]
      const index = flat.rightSpan(last.index)
      return index / 2 + 1
    }

    return proof.start + proof.length
  }
}

module.exports = {
  MerkleTreeBatch,
  ReorgBatch,
  MerkleTree
}

async function getNodeSize(index, rx) {
  return (await getTreeNodeOrError(rx, index)).size
}

async function getByteOffsetSession(session, index, rx) {
  if (index === 2 * session.length) return session.byteLength

  const treeNodes =
    rx === null
      ? await getByteOffsetBatchFlush(session.roots, index, session.storage.read())
      : await getByteOffsetBatch(session.roots, index, rx)

  let offset = 0
  for (const node of treeNodes) offset += node.size

  return offset
}

async function getByteOffset(tree, index, rx) {
  if (index === 2 * tree.length) return tree.byteLength

  const treeNodes = await getByteOffsetBatch(tree.roots, index, rx)

  let offset = 0
  for (const node of treeNodes) offset += node.size

  return offset
}

function getByteOffsetBatchFlush(roots, index, rx) {
  const treeNodes = getByteOffsetBatch(roots, index, rx)
  rx.tryFlush()
  return treeNodes
}

function getByteOffsetBatch(roots, index, rx) {
  if ((index & 1) === 1) index = flat.leftSpan(index)

  let head = 0
  let cnt = 0

  const promises = []

  for (const node of roots) {
    // all async ticks happen once we find the root so safe
    head += 2 * (node.index - head + 1)

    if (index >= head) {
      promises.push(node.size)
      continue
    }

    const ite = flat.iterator(node.index)

    while (ite.index !== index) {
      if (++cnt >= 1024) throw ASSERTION('Bad getByteOffsetSession index=' + index)

      if (index < ite.index) {
        ite.leftChild()
      } else {
        promises.push(getTreeNodeOrError(rx, ite.leftChild()))
        ite.sibling()
      }
    }

    return Promise.all(promises)
  }

  throw ASSERTION('Failed to find offset')
}

function getByteRange(tree, index, rx) {
  const head = 2 * tree.length
  if (((index & 1) === 0 ? index : flat.rightSpan(index)) >= head) {
    throw BAD_ARGUMENT('Index is out of bounds')
  }

  const offset = getByteOffset(tree, index, rx)
  const size = getNodeSize(index, rx)

  return Promise.all([offset, size])
}

// All the methods needed for proof verification

function verifyTree({ block, hash, seek }, nodes) {
  const untrustedNode = block
    ? { index: 2 * block.index, value: block.value, nodes: block.nodes }
    : hash
      ? { index: hash.index, value: null, nodes: hash.nodes }
      : null

  if (untrustedNode === null && (!seek || !seek.nodes.length)) return null

  let root = null

  if (seek && seek.nodes.length) {
    const ite = flat.iterator(seek.nodes[0].index)
    const q = new NodeQueue(seek.nodes)

    root = q.shift(ite.index)
    nodes.push(root)

    while (q.length > 0) {
      const node = q.shift(ite.sibling())

      root = parentNode(ite.parent(), root, node)
      nodes.push(node)
      nodes.push(root)
    }
  }

  if (untrustedNode === null) return root

  const ite = flat.iterator(untrustedNode.index)
  const blockHash = untrustedNode.value && blockNode(ite.index, untrustedNode.value)

  const q = new NodeQueue(untrustedNode.nodes, root)

  root = blockHash || q.shift(ite.index)
  nodes.push(root)

  while (q.length > 0) {
    const node = q.shift(ite.sibling())

    root = parentNode(ite.parent(), root, node)
    nodes.push(node)
    nodes.push(root)
  }

  return root
}

function verifyUpgrade({ fork, upgrade }, blockRoot, batch) {
  const prologue = batch.prologue

  if (prologue) {
    const { start, length } = upgrade
    if (start < prologue.length && (start !== 0 || length < prologue.length)) {
      throw INVALID_PROOF('Upgrade does not satisfy prologue')
    }
  }

  const q = new NodeQueue(upgrade.nodes, blockRoot)

  let grow = batch.roots.length > 0
  let i = 0

  const to = 2 * (upgrade.start + upgrade.length)
  const ite = flat.iterator(0)

  for (; ite.fullRoot(to); ite.nextTree()) {
    if (i < batch.roots.length && batch.roots[i].index === ite.index) {
      i++
      continue
    }

    if (grow) {
      grow = false
      const root = ite.index
      if (i < batch.roots.length) {
        ite.seek(batch.roots[batch.roots.length - 1].index)
        while (ite.index !== root) {
          batch.appendRoot(q.shift(ite.sibling()), ite)
        }
        continue
      }
    }

    batch.appendRoot(q.shift(ite.index), ite)
  }

  if (prologue && batch.length === prologue.length) {
    if (!b4a.equals(prologue.hash, batch.hash())) {
      throw INVALID_PROOF('Invalid hash')
    }
  }

  const extra = upgrade.additionalNodes

  ite.seek(batch.roots[batch.roots.length - 1].index)
  i = 0

  while (i < extra.length && extra[i].index === ite.sibling()) {
    batch.appendRoot(extra[i++], ite)
  }

  while (i < extra.length) {
    const node = extra[i++]

    while (node.index !== ite.index) {
      if (ite.factor === 2) throw INVALID_OPERATION('Unexpected node: ' + node.index)
      ite.leftChild()
    }

    batch.appendRoot(node, ite)
    ite.sibling()
  }

  batch.signature = unslab(upgrade.signature)
  batch.fork = fork

  return q.extra === null
}

async function seekFromHead(session, head, bytes, padding) {
  const roots = flat.fullRoots(head)

  for (let i = 0; i < roots.length; i++) {
    const root = roots[i]
    const node = await getTreeNodeFromStorage(session.storage, root)
    const size = getUnpaddedSize(node, padding, null)

    if (bytes === size) return root
    if (bytes > size) {
      bytes -= size
      continue
    }

    return seekTrustedTree(session, root, bytes, padding)
  }

  return head
}

// trust that bytes are within the root tree and find the block at bytes

async function seekTrustedTree(session, root, bytes, padding) {
  if (!bytes) return root

  const ite = flat.iterator(root)
  let cnt = 0

  while ((ite.index & 1) !== 0) {
    if (++cnt >= 1024) throw ASSERTION('Bad seekTrusted bytes=' + bytes + ', paddding=' + padding)
    const l = await getTreeNodeFromStorage(session.storage, ite.leftChild())

    if (l) {
      const size = getUnpaddedSize(l, padding, ite)
      if (size === bytes) return ite.index
      if (size > bytes) continue
      bytes -= size
      ite.sibling()
    } else {
      ite.parent()
      return ite.index
    }
  }

  return ite.index
}

// try to find the block at bytes without trusting that is *is* within the root passed

async function seekUntrustedTree(session, root, bytes, padding) {
  const offset =
    (await getByteOffsetSession(session, root, null)) -
    (padding ? (padding * flat.leftSpan(root)) / 2 : 0)

  if (offset > bytes) throw INVALID_OPERATION('Invalid seek')
  if (offset === bytes) return root

  bytes -= offset

  const node = await getTreeNodeFromStorageOrError(session.storage, root)

  if (getUnpaddedSize(node, padding, null) <= bytes) throw INVALID_OPERATION('Invalid seek')

  return seekTrustedTree(session, root, bytes, padding)
}

// Below is proof production, ie, construct proofs to verify a request
// Note, that all these methods are sync as we can statically infer which nodes
// are needed for the remote to verify given they arguments they passed us

function seekProof(session, rx, seekRoot, root, p) {
  const ite = flat.iterator(seekRoot)
  let cnt = 0

  p.seek = []
  p.seek.push(getTreeNodeOrError(rx, ite.index))

  while (ite.index !== root) {
    if (++cnt >= 1024) throw ASSERTION('Bad seekProof seekRoot=' + seekRoot + ', root=' + root)
    ite.sibling()
    p.seek.push(getTreeNodeOrError(rx, ite.index))
    ite.parent()
  }
}

function blockAndSeekProof(session, rx, node, seek, seekRoot, root, p) {
  if (!node) return seekProof(session, rx, seekRoot, root, p)

  const ite = flat.iterator(node.index)
  let cnt = 0

  p.node = []
  if (!node.value) p.node.push(getTreeNodeOrError(rx, ite.index))

  while (ite.index !== root) {
    if (++cnt >= 1024) {
      throw ASSERTION('Bad blockAndSeekProof seekRoot=' + seekRoot + ', root=' + root)
    }
    ite.sibling()

    if (seek && ite.contains(seekRoot) && ite.index !== seekRoot) {
      seekProof(session, rx, seekRoot, ite.index, p)
    } else {
      p.node.push(getTreeNodeOrError(rx, ite.index))
    }

    ite.parent()
  }
}

function upgradeProof(session, rx, node, seek, from, to, subTree, p) {
  if (from === 0) p.upgrade = []

  for (const ite = flat.iterator(0); ite.fullRoot(to); ite.nextTree()) {
    // check if they already have the node
    if (ite.index + ite.factor / 2 < from) continue

    // connect existing tree
    if (p.upgrade === null && ite.contains(from - 2)) {
      p.upgrade = []

      const root = ite.index
      const target = from - 2
      let cnt = 0

      ite.seek(target)

      while (ite.index !== root) {
        if (++cnt >= 1024) throw ASSERTION('Bad upgradeProof target=' + target + ', root=' + root)

        ite.sibling()
        if (ite.index > target) {
          if (p.node === null && p.seek === null && ite.contains(subTree)) {
            blockAndSeekProof(session, rx, node, seek, subTree, ite.index, p)
          } else {
            p.upgrade.push(getTreeNodeOrError(rx, ite.index))
          }
        }
        ite.parent()
      }

      continue
    }

    if (p.upgrade === null) {
      p.upgrade = []
    }

    // if the subtree included is a child of this tree, include that one
    // instead of a dup node
    if (p.node === null && p.seek === null && ite.contains(subTree)) {
      blockAndSeekProof(session, rx, node, seek, subTree, ite.index, p)
      continue
    }

    // add root (can be optimised since the root might be in tree.roots)
    p.upgrade.push(getTreeNodeOrError(rx, ite.index))
  }
}

function additionalUpgradeProof(session, rx, from, to, p) {
  if (from === 0) p.additionalUpgrade = []

  for (const ite = flat.iterator(0); ite.fullRoot(to); ite.nextTree()) {
    // check if they already have the node
    if (ite.index + ite.factor / 2 < from) continue

    // connect existing tree
    if (p.additionalUpgrade === null && ite.contains(from - 2)) {
      p.additionalUpgrade = []

      const root = ite.index
      const target = from - 2
      let cnt = 0

      ite.seek(target)

      while (ite.index !== root) {
        if (++cnt >= 1024) {
          throw ASSERTION(
            'Bad arguments to additionalUpgradeProof root=' + root + ' target=' + target
          )
        }
        ite.sibling()
        if (ite.index > target) {
          p.additionalUpgrade.push(getTreeNodeOrError(rx, ite.index))
        }
        ite.parent()
      }

      continue
    }

    if (p.additionalUpgrade === null) {
      p.additionalUpgrade = []
    }

    // add root (can be optimised since the root is in tree.roots)
    p.additionalUpgrade.push(getTreeNodeOrError(rx, ite.index))
  }
}

function nodesToRoot(index, nodes, head) {
  const ite = flat.iterator(index)

  for (let i = 0; i < nodes; i++) {
    ite.parent()
    if (ite.contains(head)) throw INVALID_OPERATION('Nodes is out of bounds')
  }

  return ite.index
}

function totalSize(nodes) {
  let s = 0
  for (const node of nodes) s += node.size
  return s
}

function totalSpan(nodes) {
  let s = 0
  for (const node of nodes) s += 2 * (node.index - s + 1)
  return s
}

function blockNode(index, value) {
  return { index, size: value.byteLength, hash: crypto.data(value) }
}

function parentNode(index, a, b) {
  return { index, size: a.size + b.size, hash: crypto.parent(a, b) }
}

function log2(n) {
  let res = 1

  while (n > 2) {
    n /= 2
    res++
  }

  return res
}

function normalizeIndexed(block, hash) {
  if (block) {
    return {
      value: true,
      index: block.index * 2,
      nodes: block.nodes,
      lastIndex: block.index
    }
  }
  if (hash) {
    return {
      value: false,
      index: hash.index,
      nodes: hash.nodes,
      lastIndex: flat.rightSpan(hash.index) / 2
    }
  }
  return null
}

async function getTreeNodeOrError(rx, index) {
  const node = await rx.getTreeNode(index)
  if (node === null) {
    throw INVALID_OPERATION('Expected tree node ' + index + ' from storage, got (nil)')
  }
  return node
}

function getTreeNodeFromStorageOrError(storage, index) {
  const rx = storage.read()
  const p = getTreeNodeOrError(rx, index)
  rx.tryFlush()
  return p
}

function getTreeNodeFromStorage(storage, index) {
  const rx = storage.read()
  const node = rx.getTreeNode(index)
  rx.tryFlush()
  return node
}

function hasTreeNode(storage, index) {
  const rx = storage.read()
  const has = rx.hasTreeNode(index)
  rx.tryFlush()
  return has
}

async function settleProof(p) {
  const result = [
    p.node && Promise.all(p.node),
    p.seek && Promise.all(p.seek),
    p.upgrade && Promise.all(p.upgrade),
    p.additionalUpgrade && Promise.all(p.additionalUpgrade)
  ]

  try {
    return await Promise.all(result)
  } catch (err) {
    if (p.node) await Promise.allSettled(p.node)
    if (p.seek) await Promise.allSettled(p.seek)
    if (p.upgrade) await Promise.allSettled(p.upgrade)
    if (p.additionalUpgrade) await Promise.allSettled(p.additionalUpgrade)
    throw err
  }
}

// tree can be either the merkle tree or a merkle tree batch
async function generateProof(session, rx, block, hash, seek, upgrade) {
  // Important that this does not throw inbetween making the promise arrays
  // and finalise being called, otherwise there will be lingering promises in the background

  if (session.prologue && upgrade) {
    upgrade.start = upgrade.start < session.prologue.length ? 0 : upgrade.start
    upgrade.length =
      upgrade.start < session.prologue.length ? session.prologue.length : upgrade.length
  }

  const head = 2 * session.length
  const from = upgrade ? upgrade.start * 2 : 0
  const to = upgrade ? from + upgrade.length * 2 : head
  const node = normalizeIndexed(block, hash)

  // can't do anything as we have no data...
  if (head === 0) return new TreeProof(session, null, null, null, null)

  if (from >= to || to > head) {
    throw INVALID_OPERATION('Invalid upgrade')
  }
  if (seek && upgrade && node !== null && node.index >= from) {
    throw INVALID_OPERATION('Cannot both do a seek and block/hash request when upgrading')
  }

  let subTree = head

  const p = new TreeProof(session, block, hash, seek, upgrade)

  if (node !== null && (!upgrade || node.lastIndex < upgrade.start)) {
    subTree = nodesToRoot(node.index, node.nodes, to)
    const seekRoot = seek
      ? await seekUntrustedTree(session, subTree, seek.bytes, seek.padding)
      : head
    blockAndSeekProof(session, rx, node, seek, seekRoot, subTree, p.pending)
  } else if ((node || seek) && upgrade) {
    subTree = seek ? await seekFromHead(session, to, seek.bytes, seek.padding) : node.index
  }

  if (upgrade) {
    upgradeProof(session, rx, node, seek, from, to, subTree, p.pending)
    if (head > to) additionalUpgradeProof(session, rx, to, head, p.pending)
  }

  return p
}

function getUnpaddedSize(node, padding, ite) {
  return padding === 0
    ? node.size
    : node.size - padding * (ite ? ite.countLeaves() : flat.countLeaves(node.index))
}

function unslabNodes(nodes) {
  for (const node of nodes) unslabNode(node)
  return nodes
}

function unslabNode(node) {
  if (node === null) return node
  node.hash = unslab(node.hash)
  return node
}
const c = require('compact-encoding')
const { DEFAULT_NAMESPACE } = require('./caps')
const { INVALID_OPLOG_VERSION } = require('hypercore-errors')
const unslab = require('unslab')

const MANIFEST_PATCH = 0b00000001
const MANIFEST_PROLOGUE = 0b00000010
const MANIFEST_LINKED = 0b00000100
const MANIFEST_USER_DATA = 0b00001000

const hashes = {
  preencode(state, m) {
    state.end++ // small uint
  },
  encode(state, m) {
    if (m === 'blake2b') {
      c.uint.encode(state, 0)
      return
    }

    throw new Error('Unknown hash: ' + m)
  },
  decode(state) {
    const n = c.uint.decode(state)
    if (n === 0) return 'blake2b'
    throw new Error('Unknown hash id: ' + n)
  }
}

const signatures = {
  preencode(state, m) {
    state.end++ // small uint
  },
  encode(state, m) {
    if (m === 'ed25519') {
      c.uint.encode(state, 0)
      return
    }

    throw new Error('Unknown signature: ' + m)
  },
  decode(state) {
    const n = c.uint.decode(state)
    if (n === 0) return 'ed25519'
    throw new Error('Unknown signature id: ' + n)
  }
}

const signer = {
  preencode(state, m) {
    signatures.preencode(state, m.signature)
    c.fixed32.preencode(state, m.namespace)
    c.fixed32.preencode(state, m.publicKey)
  },
  encode(state, m) {
    signatures.encode(state, m.signature)
    c.fixed32.encode(state, m.namespace)
    c.fixed32.encode(state, m.publicKey)
  },
  decode(state) {
    return {
      signature: signatures.decode(state),
      namespace: c.fixed32.decode(state),
      publicKey: c.fixed32.decode(state)
    }
  }
}

const signerArray = c.array(signer)

const prologue = {
  preencode(state, p) {
    c.fixed32.preencode(state, p.hash)
    c.uint.preencode(state, p.length)
  },
  encode(state, p) {
    c.fixed32.encode(state, p.hash)
    c.uint.encode(state, p.length)
  },
  decode(state) {
    return {
      hash: c.fixed32.decode(state),
      length: c.uint.decode(state)
    }
  }
}

const manifestv0 = {
  preencode(state, m) {
    hashes.preencode(state, m.hash)
    state.end++ // type

    if (m.prologue && m.signers.length === 0) {
      c.fixed32.preencode(state, m.prologue.hash)
      return
    }

    if (m.quorum === 1 && m.signers.length === 1 && !m.allowPatch) {
      signer.preencode(state, m.signers[0])
    } else {
      state.end++ // flags
      c.uint.preencode(state, m.quorum)
      signerArray.preencode(state, m.signers)
    }
  },
  encode(state, m) {
    hashes.encode(state, m.hash)

    if (m.prologue && m.signers.length === 0) {
      c.uint.encode(state, 0)
      c.fixed32.encode(state, m.prologue.hash)
      return
    }

    if (m.quorum === 1 && m.signers.length === 1 && !m.allowPatch) {
      c.uint.encode(state, 1)
      signer.encode(state, m.signers[0])
    } else {
      c.uint.encode(state, 2)
      c.uint.encode(state, m.allowPatch ? 1 : 0)
      c.uint.encode(state, m.quorum)
      signerArray.encode(state, m.signers)
    }
  },
  decode(state) {
    const hash = hashes.decode(state)
    const type = c.uint.decode(state)

    if (type > 2) throw new Error('Unknown type: ' + type)

    if (type === 0) {
      return {
        version: 0,
        hash,
        allowPatch: false,
        quorum: 0,
        signers: [],
        prologue: {
          hash: c.fixed32.decode(state),
          length: 0
        },
        linked: null,
        userData: null
      }
    }

    if (type === 1) {
      return {
        version: 0,
        hash,
        allowPatch: false,
        quorum: 1,
        signers: [signer.decode(state)],
        prologue: null,
        linked: null,
        userData: null
      }
    }

    const flags = c.uint.decode(state)

    return {
      version: 0,
      hash,
      allowPatch: (flags & 1) !== 0,
      quorum: c.uint.decode(state),
      signers: signerArray.decode(state),
      prologue: null,
      linked: null,
      userData: null
    }
  }
}

const fixed32Array = c.array(c.fixed32)

const manifest = (exports.manifest = {
  preencode(state, m) {
    state.end++ // version

    if (m.version === 0) return manifestv0.preencode(state, m)

    state.end++ // flags
    hashes.preencode(state, m.hash)

    c.uint.preencode(state, m.quorum)
    signerArray.preencode(state, m.signers)

    if (m.prologue) prologue.preencode(state, m.prologue)
    if (m.linked) fixed32Array.preencode(state, m.linked)
    if (m.userData) c.buffer.preencode(state, m.userData)
  },
  encode(state, m) {
    c.uint.encode(state, m.version)

    if (m.version === 0) return manifestv0.encode(state, m)

    let flags = 0
    if (m.allowPatch) flags |= MANIFEST_PATCH
    if (m.prologue) flags |= MANIFEST_PROLOGUE
    if (m.linked) flags |= MANIFEST_LINKED
    if (m.userData) flags |= MANIFEST_USER_DATA

    c.uint.encode(state, flags)
    hashes.encode(state, m.hash)

    c.uint.encode(state, m.quorum)
    signerArray.encode(state, m.signers)

    if (m.prologue) prologue.encode(state, m.prologue)
    if (m.linked) fixed32Array.encode(state, m.linked)
    if (m.userData) c.buffer.encode(state, m.userData)
  },
  decode(state) {
    const version = c.uint.decode(state)

    if (version === 0) return manifestv0.decode(state)
    if (version > 2) throw new Error('Unknown version: ' + version)

    const flags = c.uint.decode(state)
    const hash = hashes.decode(state)
    const quorum = c.uint.decode(state)
    const signers = signerArray.decode(state)

    const hasPatch = (flags & MANIFEST_PATCH) !== 0
    const hasPrologue = (flags & MANIFEST_PROLOGUE) !== 0
    const hasLinked = (flags & MANIFEST_LINKED) !== 0
    const hasUserData = (flags & MANIFEST_USER_DATA) !== 0

    return {
      version,
      hash,
      allowPatch: hasPatch,
      quorum,
      signers,
      prologue: hasPrologue ? prologue.decode(state) : null,
      linked: hasLinked ? fixed32Array.decode(state) : null,
      userData: hasUserData ? c.buffer.decode(state) : null
    }
  }
})

const node = {
  preencode(state, n) {
    c.uint.preencode(state, n.index)
    c.uint.preencode(state, n.size)
    c.fixed32.preencode(state, n.hash)
  },
  encode(state, n) {
    c.uint.encode(state, n.index)
    c.uint.encode(state, n.size)
    c.fixed32.encode(state, n.hash)
  },
  decode(state) {
    return {
      index: c.uint.decode(state),
      size: c.uint.decode(state),
      hash: c.fixed32.decode(state)
    }
  }
}

const nodeArray = c.array(node)

const wire = (exports.wire = {})

wire.handshake = {
  preencode(state, m) {
    c.uint.preencode(state, 1)
    c.fixed32.preencode(state, m.capability)
  },
  encode(state, m) {
    c.uint.encode(state, m.seeks ? 1 : 0)
    c.fixed32.encode(state, m.capability)
  },
  decode(state) {
    const flags = c.uint.decode(state)
    return {
      seeks: (flags & 1) !== 0,
      capability: unslab(c.fixed32.decode(state))
    }
  }
}

const requestBlock = {
  preencode(state, b) {
    c.uint.preencode(state, b.index)
    c.uint.preencode(state, b.nodes)
  },
  encode(state, b) {
    c.uint.encode(state, b.index)
    c.uint.encode(state, b.nodes)
  },
  decode(state) {
    return {
      index: c.uint.decode(state),
      nodes: c.uint.decode(state)
    }
  }
}

const requestSeek = {
  preencode(state, s) {
    c.uint.preencode(state, s.bytes)
    c.uint.preencode(state, s.padding)
  },
  encode(state, s) {
    c.uint.encode(state, s.bytes)
    c.uint.encode(state, s.padding)
  },
  decode(state) {
    return {
      bytes: c.uint.decode(state),
      padding: c.uint.decode(state)
    }
  }
}

const requestUpgrade = {
  preencode(state, u) {
    c.uint.preencode(state, u.start)
    c.uint.preencode(state, u.length)
  },
  encode(state, u) {
    c.uint.encode(state, u.start)
    c.uint.encode(state, u.length)
  },
  decode(state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

wire.request = {
  preencode(state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.id)
    c.uint.preencode(state, m.fork)

    if (m.block) requestBlock.preencode(state, m.block)
    if (m.hash) requestBlock.preencode(state, m.hash)
    if (m.seek) requestSeek.preencode(state, m.seek)
    if (m.upgrade) requestUpgrade.preencode(state, m.upgrade)
    if (m.priority) c.uint.preencode(state, m.priority)
  },
  encode(state, m) {
    const flags =
      (m.block ? 1 : 0) |
      (m.hash ? 2 : 0) |
      (m.seek ? 4 : 0) |
      (m.upgrade ? 8 : 0) |
      (m.manifest ? 16 : 0) |
      (m.priority ? 32 : 0)

    c.uint.encode(state, flags)
    c.uint.encode(state, m.id)
    c.uint.encode(state, m.fork)

    if (m.block) requestBlock.encode(state, m.block)
    if (m.hash) requestBlock.encode(state, m.hash)
    if (m.seek) requestSeek.encode(state, m.seek)
    if (m.upgrade) requestUpgrade.encode(state, m.upgrade)
    if (m.priority) c.uint.encode(state, m.priority)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      id: c.uint.decode(state),
      fork: c.uint.decode(state),
      block: flags & 1 ? requestBlock.decode(state) : null,
      hash: flags & 2 ? requestBlock.decode(state) : null,
      seek: flags & 4 ? requestSeek.decode(state) : null,
      upgrade: flags & 8 ? requestUpgrade.decode(state) : null,
      manifest: (flags & 16) !== 0,
      priority: flags & 32 ? c.uint.decode(state) : 0
    }
  }
}

wire.cancel = {
  preencode(state, m) {
    c.uint.preencode(state, m.request)
  },
  encode(state, m) {
    c.uint.encode(state, m.request)
  },
  decode(state, m) {
    return {
      request: c.uint.decode(state)
    }
  }
}

const dataUpgrade = {
  preencode(state, u) {
    c.uint.preencode(state, u.start)
    c.uint.preencode(state, u.length)
    nodeArray.preencode(state, u.nodes)
    nodeArray.preencode(state, u.additionalNodes)
    c.optionalBuffer.preencode(state, u.signature)
  },
  encode(state, u) {
    c.uint.encode(state, u.start)
    c.uint.encode(state, u.length)
    nodeArray.encode(state, u.nodes)
    nodeArray.encode(state, u.additionalNodes)
    c.optionalBuffer.encode(state, u.signature)
  },
  decode(state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state),
      nodes: nodeArray.decode(state),
      additionalNodes: nodeArray.decode(state),
      signature: c.optionalBuffer.decode(state)
    }
  }
}

const dataSeek = {
  preencode(state, s) {
    c.uint.preencode(state, s.bytes)
    nodeArray.preencode(state, s.nodes)
  },
  encode(state, s) {
    c.uint.encode(state, s.bytes)
    nodeArray.encode(state, s.nodes)
  },
  decode(state) {
    return {
      bytes: c.uint.decode(state),
      nodes: nodeArray.decode(state)
    }
  }
}

const dataBlock = {
  preencode(state, b) {
    c.uint.preencode(state, b.index)
    c.buffer.preencode(state, b.value)
    nodeArray.preencode(state, b.nodes)
  },
  encode(state, b) {
    c.uint.encode(state, b.index)
    c.buffer.encode(state, b.value)
    nodeArray.encode(state, b.nodes)
  },
  decode(state) {
    return {
      index: c.uint.decode(state),
      value: c.buffer.decode(state),
      nodes: nodeArray.decode(state)
    }
  }
}

const dataHash = {
  preencode(state, b) {
    c.uint.preencode(state, b.index)
    nodeArray.preencode(state, b.nodes)
  },
  encode(state, b) {
    c.uint.encode(state, b.index)
    nodeArray.encode(state, b.nodes)
  },
  decode(state) {
    return {
      index: c.uint.decode(state),
      nodes: nodeArray.decode(state)
    }
  }
}

wire.data = {
  preencode(state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.request)
    c.uint.preencode(state, m.fork)

    if (m.block) dataBlock.preencode(state, m.block)
    if (m.hash) dataHash.preencode(state, m.hash)
    if (m.seek) dataSeek.preencode(state, m.seek)
    if (m.upgrade) dataUpgrade.preencode(state, m.upgrade)
    if (m.manifest) manifest.preencode(state, m.manifest)
  },
  encode(state, m) {
    const flags =
      (m.block ? 1 : 0) |
      (m.hash ? 2 : 0) |
      (m.seek ? 4 : 0) |
      (m.upgrade ? 8 : 0) |
      (m.manifest ? 16 : 0)

    c.uint.encode(state, flags)
    c.uint.encode(state, m.request)
    c.uint.encode(state, m.fork)

    if (m.block) dataBlock.encode(state, m.block)
    if (m.hash) dataHash.encode(state, m.hash)
    if (m.seek) dataSeek.encode(state, m.seek)
    if (m.upgrade) dataUpgrade.encode(state, m.upgrade)
    if (m.manifest) manifest.encode(state, m.manifest)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      request: c.uint.decode(state),
      fork: c.uint.decode(state),
      block: flags & 1 ? dataBlock.decode(state) : null,
      hash: flags & 2 ? dataHash.decode(state) : null,
      seek: flags & 4 ? dataSeek.decode(state) : null,
      upgrade: flags & 8 ? dataUpgrade.decode(state) : null,
      manifest: flags & 16 ? manifest.decode(state) : null
    }
  }
}

wire.noData = {
  preencode(state, m) {
    c.uint.preencode(state, m.request)
    c.uint.preencode(state, m.reason ? 1 : 0)
    if (m.reason) c.uint.preencode(state, m.reason)
  },
  encode(state, m) {
    c.uint.encode(state, m.request)
    c.uint.encode(state, m.reason ? 1 : 0)
    if (m.reason) c.uint.encode(state, m.reason)
  },
  decode(state, m) {
    const request = c.uint.decode(state)
    const flags = state.start < state.end ? c.uint.decode(state) : 0
    return {
      request,
      reason: flags & 1 ? c.uint.decode(state) : 0
    }
  }
}

// TODO: we should move to having these have a handle like in data, easier since they
// allocate state in practice
wire.want = {
  preencode(state, m) {
    c.uint.preencode(state, m.start)
    c.uint.preencode(state, m.length)

    const flags = m.any ? 1 : 0
    if (flags !== 0) c.uint.preencode(state, flags)
  },
  encode(state, m) {
    c.uint.encode(state, m.start)
    c.uint.encode(state, m.length)

    const flags = m.any ? 1 : 0
    if (flags !== 0) c.uint.encode(state, flags)
  },
  decode(state) {
    const start = c.uint.decode(state)
    const length = c.uint.decode(state)
    const flags = state.start < state.end ? c.uint.decode(state) : 0

    return {
      start,
      length,
      any: (flags & 1) !== 0
    }
  }
}

wire.unwant = {
  preencode(state, m) {
    c.uint.preencode(state, m.start)
    c.uint.preencode(state, m.length)

    const flags = m.any ? 1 : 0
    if (flags !== 0) c.uint.preencode(state, flags)
  },
  encode(state, m) {
    c.uint.encode(state, m.start)
    c.uint.encode(state, m.length)

    const flags = m.any ? 1 : 0
    if (flags !== 0) c.uint.encode(state, flags)
  },
  decode(state, m) {
    const start = c.uint.decode(state)
    const length = c.uint.decode(state)
    const flags = state.start < state.end ? c.uint.decode(state) : 0

    return {
      start,
      length,
      any: (flags & 1) !== 0
    }
  }
}

wire.range = {
  preencode(state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.start)
    if (m.length !== 1) c.uint.preencode(state, m.length)
  },
  encode(state, m) {
    c.uint.encode(state, (m.drop ? 1 : 0) | (m.length === 1 ? 2 : 0))
    c.uint.encode(state, m.start)
    if (m.length !== 1) c.uint.encode(state, m.length)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      drop: (flags & 1) !== 0,
      start: c.uint.decode(state),
      length: (flags & 2) !== 0 ? 1 : c.uint.decode(state)
    }
  }
}

wire.bitfield = {
  preencode(state, m) {
    c.uint.preencode(state, m.start)
    c.uint32array.preencode(state, m.bitfield)
  },
  encode(state, m) {
    c.uint.encode(state, m.start)
    c.uint32array.encode(state, m.bitfield)
  },
  decode(state, m) {
    return {
      start: c.uint.decode(state),
      bitfield: c.uint32array.decode(state)
    }
  }
}

wire.sync = {
  preencode(state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.fork)
    c.uint.preencode(state, m.length)
    c.uint.preencode(state, m.remoteLength)
  },
  encode(state, m) {
    c.uint.encode(
      state,
      (m.canUpgrade ? 1 : 0) |
        (m.uploading ? 2 : 0) |
        (m.downloading ? 4 : 0) |
        (m.hasManifest ? 8 : 0) |
        (m.allowPush ? 16 : 0)
    )
    c.uint.encode(state, m.fork)
    c.uint.encode(state, m.length)
    c.uint.encode(state, m.remoteLength)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      fork: c.uint.decode(state),
      length: c.uint.decode(state),
      remoteLength: c.uint.decode(state),
      canUpgrade: (flags & 1) !== 0,
      uploading: (flags & 2) !== 0,
      downloading: (flags & 4) !== 0,
      hasManifest: (flags & 8) !== 0,
      allowPush: (flags & 16) !== 0
    }
  }
}

wire.reorgHint = {
  preencode(state, m) {
    c.uint.preencode(state, m.from)
    c.uint.preencode(state, m.to)
    c.uint.preencode(state, m.ancestors)
  },
  encode(state, m) {
    c.uint.encode(state, m.from)
    c.uint.encode(state, m.to)
    c.uint.encode(state, m.ancestors)
  },
  decode(state) {
    return {
      from: c.uint.decode(state),
      to: c.uint.decode(state),
      ancestors: c.uint.decode(state)
    }
  }
}

wire.extension = {
  preencode(state, m) {
    c.string.preencode(state, m.name)
    c.raw.preencode(state, m.message)
  },
  encode(state, m) {
    c.string.encode(state, m.name)
    c.raw.encode(state, m.message)
  },
  decode(state) {
    return {
      name: c.string.decode(state),
      message: c.raw.decode(state)
    }
  }
}

const keyValue = {
  preencode(state, p) {
    c.string.preencode(state, p.key)
    c.buffer.preencode(state, p.value)
  },
  encode(state, p) {
    c.string.encode(state, p.key)
    c.buffer.encode(state, p.value)
  },
  decode(state) {
    return {
      key: c.string.decode(state),
      value: c.buffer.decode(state)
    }
  }
}

const treeUpgrade = {
  preencode(state, u) {
    c.uint.preencode(state, u.fork)
    c.uint.preencode(state, u.ancestors)
    c.uint.preencode(state, u.length)
    c.buffer.preencode(state, u.signature)
  },
  encode(state, u) {
    c.uint.encode(state, u.fork)
    c.uint.encode(state, u.ancestors)
    c.uint.encode(state, u.length)
    c.buffer.encode(state, u.signature)
  },
  decode(state) {
    return {
      fork: c.uint.decode(state),
      ancestors: c.uint.decode(state),
      length: c.uint.decode(state),
      signature: c.buffer.decode(state)
    }
  }
}

const bitfieldUpdate = {
  // TODO: can maybe be folded into a HAVE later on with the most recent spec
  preencode(state, b) {
    state.end++ // flags
    c.uint.preencode(state, b.start)
    c.uint.preencode(state, b.length)
  },
  encode(state, b) {
    state.buffer[state.start++] = b.drop ? 1 : 0
    c.uint.encode(state, b.start)
    c.uint.encode(state, b.length)
  },
  decode(state) {
    const flags = c.uint.decode(state)
    return {
      drop: (flags & 1) !== 0,
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

const oplog = (exports.oplog = {})

oplog.entry = {
  preencode(state, m) {
    state.end++ // flags
    if (m.userData) keyValue.preencode(state, m.userData)
    if (m.treeNodes) nodeArray.preencode(state, m.treeNodes)
    if (m.treeUpgrade) treeUpgrade.preencode(state, m.treeUpgrade)
    if (m.bitfield) bitfieldUpdate.preencode(state, m.bitfield)
  },
  encode(state, m) {
    const s = state.start++
    let flags = 0

    if (m.userData) {
      flags |= 1
      keyValue.encode(state, m.userData)
    }
    if (m.treeNodes) {
      flags |= 2
      nodeArray.encode(state, m.treeNodes)
    }
    if (m.treeUpgrade) {
      flags |= 4
      treeUpgrade.encode(state, m.treeUpgrade)
    }
    if (m.bitfield) {
      flags |= 8
      bitfieldUpdate.encode(state, m.bitfield)
    }

    state.buffer[s] = flags
  },
  decode(state) {
    const flags = c.uint.decode(state)
    return {
      userData: (flags & 1) !== 0 ? keyValue.decode(state) : null,
      treeNodes: (flags & 2) !== 0 ? nodeArray.decode(state) : null,
      treeUpgrade: (flags & 4) !== 0 ? treeUpgrade.decode(state) : null,
      bitfield: (flags & 8) !== 0 ? bitfieldUpdate.decode(state) : null
    }
  }
}

const keyPair = {
  preencode(state, kp) {
    c.buffer.preencode(state, kp.publicKey)
    c.buffer.preencode(state, kp.secretKey)
  },
  encode(state, kp) {
    c.buffer.encode(state, kp.publicKey)
    c.buffer.encode(state, kp.secretKey)
  },
  decode(state) {
    return {
      publicKey: c.buffer.decode(state),
      secretKey: c.buffer.decode(state)
    }
  }
}

const reorgHint = {
  preencode(state, r) {
    c.uint.preencode(state, r.from)
    c.uint.preencode(state, r.to)
    c.uint.preencode(state, r.ancestors)
  },
  encode(state, r) {
    c.uint.encode(state, r.from)
    c.uint.encode(state, r.to)
    c.uint.encode(state, r.ancestors)
  },
  decode(state) {
    return {
      from: c.uint.decode(state),
      to: c.uint.decode(state),
      ancestors: c.uint.decode(state)
    }
  }
}

const reorgHintArray = c.array(reorgHint)

const hints = {
  preencode(state, h) {
    reorgHintArray.preencode(state, h.reorgs)
    c.uint.preencode(state, h.contiguousLength)
  },
  encode(state, h) {
    reorgHintArray.encode(state, h.reorgs)
    c.uint.encode(state, h.contiguousLength)
  },
  decode(state) {
    return {
      reorgs: reorgHintArray.decode(state),
      contiguousLength: state.start < state.end ? c.uint.decode(state) : 0
    }
  }
}

const treeHeader = {
  preencode(state, t) {
    c.uint.preencode(state, t.fork)
    c.uint.preencode(state, t.length)
    c.buffer.preencode(state, t.rootHash)
    c.buffer.preencode(state, t.signature)
  },
  encode(state, t) {
    c.uint.encode(state, t.fork)
    c.uint.encode(state, t.length)
    c.buffer.encode(state, t.rootHash)
    c.buffer.encode(state, t.signature)
  },
  decode(state) {
    return {
      fork: c.uint.decode(state),
      length: c.uint.decode(state),
      rootHash: c.buffer.decode(state),
      signature: c.buffer.decode(state)
    }
  }
}

const types = {
  preencode(state, t) {
    c.string.preencode(state, t.tree)
    c.string.preencode(state, t.bitfield)
    c.string.preencode(state, t.signer)
  },
  encode(state, t) {
    c.string.encode(state, t.tree)
    c.string.encode(state, t.bitfield)
    c.string.encode(state, t.signer)
  },
  decode(state) {
    return {
      tree: c.string.decode(state),
      bitfield: c.string.decode(state),
      signer: c.string.decode(state)
    }
  }
}

const externalHeader = {
  preencode(state, m) {
    c.uint.preencode(state, m.start)
    c.uint.preencode(state, m.length)
  },
  encode(state, m) {
    c.uint.encode(state, m.start)
    c.uint.encode(state, m.length)
  },
  decode(state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

const keyValueArray = c.array(keyValue)

oplog.header = {
  preencode(state, h) {
    state.end += 2 // version + flags
    if (h.external) {
      externalHeader.preencode(state, h.external)
      return
    }
    c.fixed32.preencode(state, h.key)
    if (h.manifest) manifest.preencode(state, h.manifest)
    if (h.keyPair) keyPair.preencode(state, h.keyPair)
    keyValueArray.preencode(state, h.userData)
    treeHeader.preencode(state, h.tree)
    hints.preencode(state, h.hints)
  },
  encode(state, h) {
    c.uint.encode(state, 1)
    if (h.external) {
      c.uint.encode(state, 1) // ONLY set the first big for clarity
      externalHeader.encode(state, h.external)
      return
    }
    c.uint.encode(state, (h.manifest ? 2 : 0) | (h.keyPair ? 4 : 0))
    c.fixed32.encode(state, h.key)
    if (h.manifest) manifest.encode(state, h.manifest)
    if (h.keyPair) keyPair.encode(state, h.keyPair)
    keyValueArray.encode(state, h.userData)
    treeHeader.encode(state, h.tree)
    hints.encode(state, h.hints)
  },
  decode(state) {
    const version = c.uint.decode(state)

    if (version > 1) {
      throw INVALID_OPLOG_VERSION('Invalid header version. Expected <= 1, got ' + version)
    }

    if (version === 0) {
      const old = {
        types: types.decode(state),
        userData: keyValueArray.decode(state),
        tree: treeHeader.decode(state),
        signer: keyPair.decode(state),
        hints: hints.decode(state)
      }

      return {
        external: null,
        key: old.signer.publicKey,
        manifest: {
          version: 0,
          hash: old.types.tree,
          allowPatch: false,
          quorum: 1,
          signers: [
            {
              signature: old.types.signer,
              namespace: DEFAULT_NAMESPACE,
              publicKey: old.signer.publicKey
            }
          ],
          prologue: null,
          linked: null,
          userData: null
        },
        keyPair: old.signer.secretKey ? old.signer : null,
        userData: old.userData,
        tree: old.tree,
        hints: old.hints
      }
    }

    const flags = c.uint.decode(state)

    if (flags & 1) {
      return {
        external: externalHeader.decode(state),
        key: null,
        manifest: null,
        keyPair: null,
        userData: null,
        tree: null,
        hints: null
      }
    }

    return {
      external: null,
      key: c.fixed32.decode(state),
      manifest: (flags & 2) !== 0 ? manifest.decode(state) : null,
      keyPair: (flags & 4) !== 0 ? keyPair.decode(state) : null,
      userData: keyValueArray.decode(state),
      tree: treeHeader.decode(state),
      hints: hints.decode(state)
    }
  }
}

const uintArray = c.array(c.uint)

const multisigInput = {
  preencode(state, inp) {
    c.uint.preencode(state, inp.signer)
    c.fixed64.preencode(state, inp.signature)
    c.uint.preencode(state, inp.patch)
  },
  encode(state, inp) {
    c.uint.encode(state, inp.signer)
    c.fixed64.encode(state, inp.signature)
    c.uint.encode(state, inp.patch)
  },
  decode(state) {
    return {
      signer: c.uint.decode(state),
      signature: c.fixed64.decode(state),
      patch: c.uint.decode(state)
    }
  }
}

const patchEncodingv0 = {
  preencode(state, n) {
    c.uint.preencode(state, n.start)
    c.uint.preencode(state, n.length)
    uintArray.preencode(state, n.nodes)
  },
  encode(state, n) {
    c.uint.encode(state, n.start)
    c.uint.encode(state, n.length)
    uintArray.encode(state, n.nodes)
  },
  decode(state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state),
      nodes: uintArray.decode(state)
    }
  }
}

const multisigInputv0 = {
  preencode(state, n) {
    state.end++
    c.uint.preencode(state, n.signer)
    c.fixed64.preencode(state, n.signature)
    if (n.patch) patchEncodingv0.preencode(state, n.patch)
  },
  encode(state, n) {
    c.uint.encode(state, n.patch ? 1 : 0)
    c.uint.encode(state, n.signer)
    c.fixed64.encode(state, n.signature)
    if (n.patch) patchEncodingv0.encode(state, n.patch)
  },
  decode(state) {
    const flags = c.uint.decode(state)
    return {
      signer: c.uint.decode(state),
      signature: c.fixed64.decode(state),
      patch: flags & 1 ? patchEncodingv0.decode(state) : null
    }
  }
}

const multisigInputArrayv0 = c.array(multisigInputv0)
const multisigInputArray = c.array(multisigInput)

const compactNode = {
  preencode(state, n) {
    c.uint.preencode(state, n.index)
    c.uint.preencode(state, n.size)
    c.fixed32.preencode(state, n.hash)
  },
  encode(state, n) {
    c.uint.encode(state, n.index)
    c.uint.encode(state, n.size)
    c.fixed32.encode(state, n.hash)
  },
  decode(state) {
    return {
      index: c.uint.decode(state),
      size: c.uint.decode(state),
      hash: c.fixed32.decode(state)
    }
  }
}

const compactNodeArray = c.array(compactNode)

exports.multiSignaturev0 = {
  preencode(state, s) {
    multisigInputArrayv0.preencode(state, s.proofs)
    compactNodeArray.preencode(state, s.patch)
  },
  encode(state, s) {
    multisigInputArrayv0.encode(state, s.proofs)
    compactNodeArray.encode(state, s.patch)
  },
  decode(state) {
    return {
      proofs: multisigInputArrayv0.decode(state),
      patch: compactNodeArray.decode(state)
    }
  }
}

exports.multiSignature = {
  preencode(state, s) {
    multisigInputArray.preencode(state, s.proofs)
    compactNodeArray.preencode(state, s.patch)
  },
  encode(state, s) {
    multisigInputArray.encode(state, s.proofs)
    compactNodeArray.encode(state, s.patch)
  },
  decode(state) {
    return {
      proofs: multisigInputArray.decode(state),
      patch: compactNodeArray.decode(state)
    }
  }
}
const c = require('compact-encoding')
const b4a = require('b4a')
const flat = require('flat-tree')
const { MerkleTree } = require('./merkle-tree')
const { multiSignature, multiSignaturev0 } = require('./messages')

module.exports = {
  assemblev0,
  assemble,
  inflatev0,
  inflate,
  partialSignature,
  signableLength
}

function inflatev0(data) {
  return c.decode(multiSignaturev0, data)
}

function inflate(data) {
  return c.decode(multiSignature, data)
}

async function partialSignature(
  core,
  signer,
  from,
  to = core.state.length,
  signature = core.state.signature
) {
  if (from > core.state.length) return null
  const nodes = to <= from ? null : await upgradeNodes(core, from, to)

  if (signature.byteLength !== 64) {
    signature = c.decode(multiSignature, signature).proofs[0].signature
  }

  return {
    signer,
    signature,
    patch: nodes ? to - from : 0,
    nodes
  }
}

async function upgradeNodes(core, from, to) {
  const rx = core.state.storage.read()
  let p = null
  try {
    p = await MerkleTree.proof(core.state, rx, { upgrade: { start: from, length: to - from } })
  } catch (err) {
    rx.destroy()
    throw err
  }
  rx.tryFlush()
  return (await p.settle()).upgrade.nodes
}

function signableLength(lengths, quorum) {
  if (quorum <= 0) quorum = 1
  if (quorum > lengths.length) return 0

  return lengths.sort(cmp)[quorum - 1]
}

function cmp(a, b) {
  return b - a
}

function assemblev0(inputs) {
  const proofs = []
  const patch = []

  for (const u of inputs) {
    proofs.push(compressProof(u, patch))
  }

  return c.encode(multiSignaturev0, { proofs, patch })
}

function assemble(inputs) {
  const proofs = []
  const patch = []
  const seen = new Set()

  for (const u of inputs) {
    if (u.nodes) {
      for (const node of u.nodes) {
        if (seen.has(node.index)) continue
        seen.add(node.index)
        patch.push(node)
      }
    }

    proofs.push({
      signer: u.signer,
      signature: u.signature,
      patch: u.patch
    })
  }

  return c.encode(multiSignature, { proofs, patch })
}

function compareNode(a, b) {
  if (a.index !== b.index) return false
  if (a.size !== b.size) return false
  return b4a.equals(a.hash, b.hash)
}

function compressProof(proof, nodes) {
  return {
    signer: proof.signer,
    signature: proof.signature,
    patch: proof.patch ? compressUpgrade(proof, nodes) : null
  }
}

function compressUpgrade(p, nodes) {
  const u = {
    start: flat.rightSpan(p.nodes[p.nodes.length - 1].index) / 2 + 1,
    length: p.patch,
    nodes: []
  }

  for (const node of p.nodes) {
    let present = false
    for (let i = 0; i < nodes.length; i++) {
      if (!compareNode(nodes[i], node)) continue

      u.nodes.push(i)
      present = true
      break
    }

    if (present) continue
    u.nodes.push(nodes.push(node) - 1)
  }

  return u
}
module.exports = class Mutex {
  constructor() {
    this.locked = false
    this.destroyed = false

    this._destroying = null
    this._destroyError = null
    this._queue = []
    this._enqueue = (resolve, reject) => this._queue.push([resolve, reject])
  }

  idle() {
    return this._queue.length === 0 && this.locked === false
  }

  lock() {
    if (this.destroyed) {
      return Promise.reject(this._destroyError || new Error('Mutex has been destroyed'))
    }
    if (this.locked) return new Promise(this._enqueue)
    this.locked = true
    return Promise.resolve()
  }

  unlock() {
    if (!this._queue.length) {
      this.locked = false
      return
    }
    this._queue.shift()[0]()
  }

  destroy(err) {
    if (!this._destroying) {
      this._destroying = this.locked ? this.lock().catch(() => {}) : Promise.resolve()
    }

    this.destroyed = true
    if (err) this._destroyError = err

    if (err) {
      while (this._queue.length) this._queue.shift()[1](err)
    }

    return this._destroying
  }
}
const FIFO = require('fast-fifo')

module.exports = class ReceiverQueue {
  constructor() {
    this.queue = new FIFO()
    this.priority = []
    this.requests = new Map()
    this.length = 0
  }

  push(req) {
    // TODO: use a heap at some point if we wanna support multiple prios
    if (req.priority > 0) this.priority.push(req)
    else this.queue.push(req)

    this.requests.set(req.id, req)
    this.length++
  }

  shift() {
    while (this.priority.length > 0) {
      const msg = this.priority.pop()
      const req = this._processRequest(msg)
      if (req !== null) return req
    }

    while (this.queue.length > 0) {
      const msg = this.queue.shift()
      const req = this._processRequest(msg)
      if (req !== null) return req
    }

    return null
  }

  _processRequest(req) {
    if (req.block || req.hash || req.seek || req.upgrade || req.manifest) {
      this.requests.delete(req.id)
      this.length--
      return req
    }

    return null
  }

  clear() {
    this.queue.clear()
    this.priority = []
    this.length = 0
    this.requests.clear()
  }

  delete(id) {
    const req = this.requests.get(id)
    if (!req) return

    req.block = null
    req.hash = null
    req.seek = null
    req.upgrade = null
    req.manifest = false

    this.requests.delete(id)
    this.length--

    if (this.length === 0) {
      this.queue.clear()
      this.priority = []
    }
  }
}
const BigSparseArray = require('big-sparse-array')
const quickbit = require('./compat').quickbit

const BITS_PER_PAGE = 32768
const BYTES_PER_PAGE = BITS_PER_PAGE / 8
const WORDS_PER_PAGE = BYTES_PER_PAGE / 4
const BITS_PER_SEGMENT = 2097152
const BYTES_PER_SEGMENT = BITS_PER_SEGMENT / 8
const PAGES_PER_SEGMENT = BITS_PER_SEGMENT / BITS_PER_PAGE

class RemoteBitfieldPage {
  constructor(index, bitfield, segment) {
    this.index = index
    this.offset = index * BYTES_PER_PAGE - segment.offset
    this.bitfield = bitfield
    this.segment = segment

    segment.add(this)
  }

  get tree() {
    return this.segment.tree
  }

  get(index) {
    return quickbit.get(this.bitfield, index)
  }

  set(index, val) {
    if (quickbit.set(this.bitfield, index, val)) {
      this.tree.update(this.offset * 8 + index)
    }
  }

  setRange(start, end, val) {
    quickbit.fill(this.bitfield, val, start, end)

    let i = Math.floor(start / 128)
    const n = i + Math.ceil((end - start) / 128)

    while (i <= n) this.tree.update(this.offset * 8 + i++ * 128)
  }

  findFirst(val, position) {
    return quickbit.findFirst(this.bitfield, val, position)
  }

  findLast(val, position) {
    return quickbit.findLast(this.bitfield, val, position)
  }

  insert(start, bitfield) {
    this.bitfield.set(bitfield, start / 32)
    this.segment.refresh()
  }

  clear(start, bitfield) {
    quickbit.clear(this.bitfield, { field: bitfield, offset: start })
  }
}

class RemoteBitfieldSegment {
  constructor(index) {
    this.index = index
    this.offset = index * BYTES_PER_SEGMENT
    this.tree = quickbit.Index.from([], BYTES_PER_SEGMENT)
    this.pages = new Array(PAGES_PER_SEGMENT)
    this.pagesLength = 0
  }

  get chunks() {
    return this.tree.chunks
  }

  refresh() {
    this.tree = quickbit.Index.from(this.tree.chunks, BYTES_PER_SEGMENT)
  }

  add(page) {
    const pageIndex = page.index - this.index * PAGES_PER_SEGMENT
    if (pageIndex >= this.pagesLength) this.pagesLength = pageIndex + 1

    this.pages[pageIndex] = page

    const chunk = { field: page.bitfield, offset: page.offset }

    this.chunks.push(chunk)

    for (let i = this.chunks.length - 2; i >= 0; i--) {
      const prev = this.chunks[i]
      if (prev.offset <= chunk.offset) break
      this.chunks[i] = chunk
      this.chunks[i + 1] = prev
    }
  }

  findFirst(val, position) {
    position = this.tree.skipFirst(!val, position)

    let j = position & (BITS_PER_PAGE - 1)
    let i = (position - j) / BITS_PER_PAGE

    if (i >= PAGES_PER_SEGMENT) return -1

    while (i < this.pagesLength) {
      const p = this.pages[i]

      let index = -1

      if (p) index = p.findFirst(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_PAGE + index

      j = 0
      i++
    }

    return val || this.pagesLength === PAGES_PER_SEGMENT ? -1 : this.pagesLength * BITS_PER_PAGE
  }

  findLast(val, position) {
    position = this.tree.skipLast(!val, position)

    let j = position & (BITS_PER_PAGE - 1)
    let i = (position - j) / BITS_PER_PAGE

    if (i >= PAGES_PER_SEGMENT) return -1

    while (i >= 0) {
      const p = this.pages[i]

      let index = -1

      if (p) index = p.findLast(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_PAGE + index

      j = BITS_PER_PAGE - 1
      i--
    }

    return -1
  }
}

module.exports = class RemoteBitfield {
  static BITS_PER_PAGE = BITS_PER_PAGE
  static BITS_PER_SEGMENT = BITS_PER_SEGMENT

  constructor() {
    this._pages = new BigSparseArray()
    this._segments = new BigSparseArray()
    this._maxSegments = 0
  }

  getBitfield(index) {
    const j = index & (BITS_PER_PAGE - 1)
    const i = (index - j) / BITS_PER_PAGE

    const p = this._pages.get(i)
    return p || null
  }

  get(index) {
    const j = index & (BITS_PER_PAGE - 1)
    const i = (index - j) / BITS_PER_PAGE

    const p = this._pages.get(i)

    return p ? p.get(j) : false
  }

  set(index, val) {
    const j = index & (BITS_PER_PAGE - 1)
    const i = (index - j) / BITS_PER_PAGE

    let p = this._pages.get(i)

    if (!p && val) {
      const k = Math.floor(i / PAGES_PER_SEGMENT)
      const s = this._segments.get(k) || this._segments.set(k, new RemoteBitfieldSegment(k))
      if (this._maxSegments <= k) this._maxSegments = k + 1

      p = this._pages.set(i, new RemoteBitfieldPage(i, new Uint32Array(WORDS_PER_PAGE), s))
    }

    if (p) p.set(j, val)
  }

  setRange(start, end, val) {
    let j = start & (BITS_PER_PAGE - 1)
    let i = (start - j) / BITS_PER_PAGE

    while (start < end) {
      let p = this._pages.get(i)

      if (!p && val) {
        const k = Math.floor(i / PAGES_PER_SEGMENT)
        const s = this._segments.get(k) || this._segments.set(k, new RemoteBitfieldSegment(k))
        if (this._maxSegments <= k) this._maxSegments = k + 1

        p = this._pages.set(i, new RemoteBitfieldPage(i, new Uint32Array(WORDS_PER_PAGE), s))
      }

      const offset = i * BITS_PER_PAGE
      const last = Math.min(end - offset, BITS_PER_PAGE)
      const range = last - j

      if (p) p.setRange(j, last, val)

      j = 0
      i++
      start += range
    }
  }

  findFirst(val, position) {
    let j = position & (BITS_PER_SEGMENT - 1)
    let i = (position - j) / BITS_PER_SEGMENT

    while (i < this._maxSegments) {
      const s = this._segments.get(i)

      let index = -1

      if (s) index = s.findFirst(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_SEGMENT + index

      j = 0
      i++
    }

    // For the val === false case, we always return at least
    // the 'position', also if nothing was found
    return val ? -1 : Math.max(position, this._maxSegments * BITS_PER_SEGMENT)
  }

  firstSet(position) {
    return this.findFirst(true, position)
  }

  firstUnset(position) {
    return this.findFirst(false, position)
  }

  findLast(val, position) {
    let j = position & (BITS_PER_SEGMENT - 1)
    let i = (position - j) / BITS_PER_SEGMENT

    while (i >= 0) {
      const s = this._segments.get(i)

      let index = -1

      if (s) index = s.findLast(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_SEGMENT + index

      j = BITS_PER_SEGMENT - 1
      i--
    }

    return -1
  }

  lastSet(position) {
    return this.findLast(true, position)
  }

  lastUnset(position) {
    return this.findLast(false, position)
  }

  insert(start, bitfield) {
    if (start % 32 !== 0) return false

    let length = bitfield.byteLength * 8

    let j = start & (BITS_PER_PAGE - 1)
    let i = (start - j) / BITS_PER_PAGE

    while (length > 0) {
      let p = this._pages.get(i)

      if (!p) {
        const k = Math.floor(i / PAGES_PER_SEGMENT)
        const s = this._segments.get(k) || this._segments.set(k, new RemoteBitfieldSegment(k))
        if (this._maxSegments <= k) this._maxSegments = k + 1

        p = this._pages.set(i, new RemoteBitfieldPage(i, new Uint32Array(WORDS_PER_PAGE), s))
      }

      const end = Math.min(j + length, BITS_PER_PAGE)
      const range = end - j

      p.insert(j, bitfield.subarray(0, range / 32))

      bitfield = bitfield.subarray(range / 32)

      j = 0
      i++
      length -= range
    }

    return true
  }

  clear(start, bitfield) {
    if (start % 32 !== 0) return false

    let length = bitfield.byteLength * 8

    let j = start & (BITS_PER_PAGE - 1)
    let i = (start - j) / BITS_PER_PAGE

    while (length > 0) {
      let p = this._pages.get(i)

      if (!p) {
        const k = Math.floor(i / PAGES_PER_SEGMENT)
        const s = this._segments.get(k) || this._segments.set(k, new RemoteBitfieldSegment(k))
        if (this._maxSegments <= k) this._maxSegments = k + 1

        p = this._pages.set(i, new RemoteBitfieldPage(i, new Uint32Array(WORDS_PER_PAGE), s))
      }

      const end = Math.min(j + length, BITS_PER_PAGE)
      const range = end - j

      p.clear(j, bitfield.subarray(0, range / 32))

      bitfield = bitfield.subarray(range / 32)

      j = 0
      i++
      length -= range
    }

    return true
  }
}
/* DEV DOCS
  Every hypercore has one Replicator object managing its connections to other peers.
  There is one Peer object per peer connected to the Hypercore.
  Hypercores do not know about other hypercores, so when a peer is connected to multiple cores, there exists one Peer object per core.

  Hypercore indicates block should be downloaded through methods like Replicator.addRange or Replicator.addBlock
  Hypercore calls Replicator.updateActivity every time a hypercore session opens/closes
  Replicator.updateActivity ensures the Hypercore is downloading blocks as expected
  Replicator keeps track of:
    - Which blocks need to be downloaded (Replicator._blocks)
    - Which blocks currently have inflight requests (Replicator._inflight)

  Blocks are requested from remote peers by Peer objects. The flow is:
    - The replicator's updatePeer method gets called
    - The replicator detects whether the Peer can accept more requests (for example by checking if it's maxed out on inflight blocks)
    - The replicator then tells the Peer what to request (e.g. Peer_requestRange or Peer._requestBlock methods)

  The Peer object is responsible for tracking
    - Which blocks does the Peer have available (tracked in remoteBitfield)
    - Which blocks are you actively looking for from this peer (tracked in missingBlocks)
    - How many blocks are currently inflight (tracked in inflight)
  The Peer uses this information to decide which blocks to request from the peer in response to _requestRange requests and the like.
*/

const b4a = require('b4a')
const safetyCatch = require('safety-catch')
const RandomIterator = require('random-array-iterator')
const flatTree = require('flat-tree')
const Mutex = require('./mutex')
const ReceiverQueue = require('./receiver-queue')
const HotswapQueue = require('./hotswap-queue')
const RemoteBitfield = require('./remote-bitfield')
const { MerkleTree } = require('./merkle-tree')
const w = require('./wants')
const { LocalWants, RemoteWants } = w
const {
  REQUEST_CANCELLED,
  REQUEST_TIMEOUT,
  INVALID_CAPABILITY,
  SNAPSHOT_NOT_AVAILABLE,
  ASSERTION
} = require('hypercore-errors')
const m = require('./messages')
const caps = require('./caps')

const DEFAULT_MAX_INFLIGHT = [16, 512]
const SCALE_LATENCY = 50
const NOT_DOWNLOADING_SLACK = (20000 + Math.random() * 20000) | 0
const MAX_PEERS_UPGRADE = 3
const LAST_BLOCKS = 256
const MAX_RANGES = 64
const MIN_PEER_UPDATE_ALL = 40

const NOT_AVAILABLE = 1
const INVALID_REQUEST = 2
const MAX_INVALID_REQUESTS = 64
const MAX_BACKOFFS = MAX_INVALID_REQUESTS / 2

const PRIORITY = {
  NORMAL: 0,
  HIGH: 1,
  VERY_HIGH: 2,
  CANCELLED: 255 // reserved to mark cancellation
}

class Attachable {
  constructor(replicator) {
    this.replicator = replicator
    this.resolved = false
    this.processing = false
    this.refs = []
    this.wants = null
  }

  addWant(w) {
    if (this.wants === null) this.wants = new Set()
    this.wants.add(w)
  }

  removeWant(w) {
    if (this.wants === null) return
    this.wants.delete(w)
  }

  attach(session) {
    const r = {
      context: this,
      session,
      sindex: 0,
      rindex: 0,
      snapshot: true,
      resolve: null,
      reject: null,
      promise: null,
      timeout: null
    }

    r.sindex = session.push(r) - 1
    r.rindex = this.refs.push(r) - 1
    r.promise = new Promise((resolve, reject) => {
      r.resolve = resolve
      r.reject = reject
    })

    return r
  }

  detach(r, err = null) {
    if (r.context !== this) return false

    this._detach(r)
    this._cancel(r, err)
    this.gc()

    return true
  }

  _detach(r) {
    const rh = this.refs.pop()
    const sh = r.session.pop()

    if (r.rindex < this.refs.length) this.refs[(rh.rindex = r.rindex)] = rh
    if (r.sindex < r.session.length) r.session[(sh.sindex = r.sindex)] = sh

    destroyRequestTimeout(r)
    r.context = null

    return r
  }

  gc() {
    if (this.refs.length > 0 || this.processing) return
    this._unref()

    if (this.wants === null) return

    const wants = this.wants
    this.wants = null

    let update = null

    for (const w of wants) {
      if (w.any) {
        const removed = w.wants.removeAnyRange(w.start, w.length, this)
        if (!removed) continue
        if (update === null) update = new Set()
        update.add(w.wants.peer)
        // TODO: should also use a free list for simplicity
        w.wants.peer.wireUnwant.send(removed)
        continue
      }

      if (w.wants.removeBatch(w.start, this)) {
        if (update === null) update = new Set()
        update.add(w.wants.peer)
      }
    }

    if (update === null) return
    for (const peer of update) {
      this.replicator.updatePeer(peer)
    }
  }

  processed() {
    this.processing = false
    this.gc()
  }

  _cancel(r, err) {
    r.reject(err || REQUEST_CANCELLED())
  }

  _unref() {
    // overwrite me
  }

  resolve(val) {
    this.resolved = true
    while (this.refs.length > 0) {
      this._detach(this.refs[this.refs.length - 1]).resolve(val)
    }
    this.gc()
  }

  reject(err) {
    this.resolved = true
    while (this.refs.length > 0) {
      this._detach(this.refs[this.refs.length - 1]).reject(err)
    }
    this.gc()
  }

  setTimeout(r, ms) {
    destroyRequestTimeout(r)
    r.timeout = setTimeout(onrequesttimeout, ms, r)
  }
}

class BlockRequest extends Attachable {
  constructor(replicator, tracker, index, priority, force) {
    super(replicator)

    this.index = index
    this.priority = priority
    this.inflight = []
    this.queued = false
    this.hotswap = null
    this.tracker = tracker
    this.force = force
  }

  _unref() {
    if (this.resolved) return
    this.queued = false

    for (const req of this.inflight) {
      req.peer._cancelRequest(req)
    }

    this.tracker.remove(this.index)
    removeHotswap(this)
  }
}

class RangeBatchRequest extends Attachable {
  constructor(replicator, batch) {
    super(replicator)

    this.batch = batch
    this.index = 0
  }
}

class RangeRequest extends Attachable {
  constructor(replicator, ranges, start, end, linear, blocks) {
    super(replicator)

    this.start = start
    this.end = end
    this.linear = linear
    this.blocks = blocks
    this.ranges = ranges
    this.batches = []

    ranges.push(this)

    if (this.end === -1) {
      this.replicator._alwaysLatestBlock++
    }

    // As passed by the user, immut
    this.userStart = start
    this.userEnd = end
  }

  addBatch(batch) {
    for (let i = 0; i < this.batches.length; i++) {
      const b = this.batches[i]
      if (b.batch === batch) return false
    }
    const b = new RangeBatchRequest(this.replicator, batch)
    b.index = this.batches.length
    this.batches.push(b)
    return true
  }

  removeBatch(batch) {
    const head = this.batches.pop()

    if (head !== batch) {
      head.index = batch.index
      this.batches[head.index] = head
    }

    batch.gc()
  }

  _unref() {
    const rangeIndex = this.ranges.indexOf(this)
    if (rangeIndex === -1) return

    const h = this.ranges.pop()
    if (h !== this) {
      this.ranges[rangeIndex] = h
    }

    if (this.end === -1) {
      this.replicator._alwaysLatestBlock--
    }

    while (this.batches.length) {
      this.batches.pop().gc()
    }
  }

  _cancel(r) {
    r.resolve(false)
  }
}

class UpgradeRequest extends Attachable {
  constructor(replicator, fork, length) {
    super(replicator)

    this.fork = fork
    this.length = length
    this.inflight = []
  }

  _unref() {
    if (this.resolved) return
    if (this.replicator.eagerUpgrade === true || this.inflight.length > 0) return
    this.replicator._upgrade = null
  }

  _cancel(r) {
    r.resolve(false)
  }
}

class SeekRequest extends Attachable {
  constructor(replicator, seeks, seeker) {
    super(replicator)

    this.seeker = seeker
    this.inflight = []
    this.seeks = seeks
  }

  _unref() {
    if (this.resolved) return
    if (this.inflight.length > 0) return
    const i = this.seeks.indexOf(this)
    if (i === -1) return
    const h = this.seeks.pop()
    if (i < this.seeks.length) this.seeks[i] = h
  }
}

class ForkRequest extends Attachable {
  constructor(replicator, fork) {
    super(replicator)
    this.fork = fork
    this.inflight = []
    this.batch = null
  }
}

class InflightTracker {
  constructor() {
    this._requests = []
    this._free = []
    this._active = 0
  }

  get idle() {
    return this._active === 0
  }

  *[Symbol.iterator]() {
    for (const req of this._requests) {
      if (req !== null) yield req
    }
  }

  add(req) {
    const id = this._free.length ? this._free.pop() : this._requests.push(null)
    req.id = id
    this._requests[id - 1] = req
    this._active++
    return req
  }

  get(id) {
    return id <= this._requests.length ? this._requests[id - 1] : null
  }

  remove(id, roundtrip) {
    if (id > this._requests.length) return
    if (this._requests[id - 1]) this._active--
    this._requests[id - 1] = null
    if (roundtrip === true) this._free.push(id)
  }

  reusable(id) {
    this._free.push(id)
  }
}

class BlockTracker {
  constructor(replicator) {
    this._replicator = replicator
    this._map = new Map()
  }

  [Symbol.iterator]() {
    return this._map.values()
  }

  isEmpty() {
    return this._map.size === 0
  }

  has(index) {
    return this._map.has(index)
  }

  get(index) {
    return this._map.get(index) || null
  }

  add(index, priority, force) {
    let b = this._map.get(index)
    if (b) return b

    b = new BlockRequest(this._replicator, this, index, priority, force)
    this._map.set(index, b)

    return b
  }

  remove(index) {
    const b = this.get(index)
    this._map.delete(index)
    return b
  }
}

class RoundtripQueue {
  constructor() {
    this.queue = []
    this.tick = 0
  }

  clear() {
    const ids = new Array(this.queue.length)
    for (let i = 0; i < ids.length; i++) {
      ids[i] = this.queue[i][1]
    }

    this.queue = []

    return ids
  }

  add(id) {
    this.queue.push([++this.tick, id])
  }

  flush(tick) {
    let flushed = null

    for (let i = 0; i < this.queue.length; i++) {
      if (this.queue[i][0] > tick) break
      if (flushed === null) flushed = []
      flushed.push(this.queue[i][1])
    }

    if (flushed !== null) this.queue.splice(0, flushed.length)
    return flushed
  }
}

class ProofRequest {
  constructor(msg, proof, block, manifest) {
    this.msg = msg
    this.proof = proof
    this.block = block
    this.manifest = manifest
  }

  async fulfill() {
    if (this.proof === null) return null

    const [proof, block] = await Promise.all([this.proof.settle(), this.block])

    if (this.manifest) proof.manifest = this.manifest
    if (!block && proof.block) return null

    if (block) proof.block.value = block
    return proof
  }
}

class Peer {
  constructor(replicator, protomux, channel, inflightRange) {
    this.core = replicator.core
    this.replicator = replicator
    this.stream = protomux.stream
    this.protomux = protomux
    this.remotePublicKey = this.stream.remotePublicKey
    this.remoteSupportsSeeks = false
    this.inflightRange = inflightRange
    this.fullyDownloadedSignaled = 0

    this.paused = false
    this.removed = false

    this.channel = channel
    this.channel.userData = this

    this.wireSync = this.channel.messages[0]
    this.wireRequest = this.channel.messages[1]
    this.wireCancel = this.channel.messages[2]
    this.wireData = this.channel.messages[3]
    this.wireNoData = this.channel.messages[4]
    this.wireWant = this.channel.messages[5]
    this.wireUnwant = this.channel.messages[6]
    this.wireBitfield = this.channel.messages[7]
    this.wireRange = this.channel.messages[8]
    this.wireExtension = this.channel.messages[9]

    // Same stats as replicator, but for this specific peer
    this.stats = {
      wireSync: { tx: 0, rx: 0 },
      wireRequest: { tx: 0, rx: 0 },
      wireCancel: { tx: 0, rx: 0 },
      wireData: { tx: 0, rx: 0 },
      wireWant: { tx: 0, rx: 0 },
      wireUnwant: { tx: 0, rx: 0 },
      wireBitfield: { tx: 0, rx: 0 },
      wireRange: { tx: 0, rx: 0 },
      wireExtension: { tx: 0, rx: 0 },
      hotswaps: 0,
      invalidData: 0,
      invalidRequests: 0,
      backoffs: 0,
      notAvailableBackoffs: 0
    }

    this.receiverQueue = new ReceiverQueue()
    this.receiverBusy = false

    // most often not used, so made on demand
    this.roundtripQueue = null

    this.inflight = 0
    this.dataProcessing = 0

    this.canUpgrade = true

    this.needsSync = false
    this.syncsProcessing = 0
    this.lastUpgradableLength = 0
    this.lastUpgradableFork = 0

    this._remoteContiguousLength = 0

    // TODO: tweak pipelining so that data sent BEFORE remoteOpened is not cap verified!
    // we might wanna tweak that with some crypto, ie use the cap to encrypt it...
    // or just be aware of that, to only push non leaky data

    this.remoteOpened = false
    this.remoteBitfield = new RemoteBitfield()
    this.missingBlocks = new RemoteBitfield()

    this.pushedLength = 0

    this.remoteFork = 0
    this.remoteLength = 0
    this.remoteCanUpgrade = false
    this.remoteUploading = true
    this.remoteDownloading = true
    this.remoteSynced = false
    this.remoteHasManifest = false
    this.remoteAllowPush = false
    this.remoteRequests = new Map()

    this.segmentsWanted = new Set()
    this.broadcastedNonSparse = false

    this.wants = new LocalWants(this)
    this.remoteWants = new RemoteWants(this)

    this.lengthAcked = 0

    this.extensions = new Map()
    this.lastExtensionSent = ''
    this.lastExtensionRecv = ''

    replicator._ifAvailable++
    replicator._active++
  }

  get remoteContiguousLength() {
    return this.remoteBitfield.findFirst(false, this._remoteContiguousLength)
  }

  getMaxInflight() {
    const stream = this.stream.rawStream
    if (!stream.udx) return Math.min(this.inflightRange[1], this.inflightRange[0] * 3)

    const scale =
      stream.rtt <= SCALE_LATENCY
        ? 1
        : (stream.rtt / SCALE_LATENCY) * Math.min(1, 2 / this.replicator.peers.length)
    return Math.max(
      this.inflightRange[0],
      Math.round(Math.min(this.inflightRange[1], this.inflightRange[0] * scale))
    )
  }

  getMaxHotswapInflight() {
    const inf = this.getMaxInflight()
    return Math.max(16, inf / 2)
  }

  signalUpgrade() {
    if (this._shouldUpdateCanUpgrade() === true) this._updateCanUpgradeAndSync()
    else this.sendSync()
  }

  _markInflight(index) {
    this.missingBlocks.set(index, false)
  }

  broadcastRange(start, length, drop) {
    if (!this.isActive()) return

    if (drop) this._unclearLocalRange(start, length)
    else this._clearLocalRange(start, length)

    const fullyContig = this.core.header.hints.contiguousLength === this.core.state.length

    if (start + LAST_BLOCKS < this.core.state.length && !drop && !fullyContig) {
      if (!this.remoteWants.hasRange(start, length)) return
    }

    let force = false
    if (fullyContig && !drop) {
      start = 0
      length = this.core.state.length

      // Always send the broadcast when we switch from sparse to fully contiguous, so remote knows too
      if (this.fullyDownloadedSignaled < length) {
        this.fullyDownloadedSignaled = length
        force = true
      }
    }

    // TODO: consider also adding early-returns on the drop===true case
    if (!force && !drop) {
      // No need to broadcast if the remote already has this range

      if (this._remoteContiguousLength >= start + length) return

      if (length === 1) {
        if (this.remoteBitfield.get(start)) return
      } else {
        if (this.remoteBitfield.firstUnset(start) >= start + length) return
      }
    }

    this.wireRange.send({
      drop,
      start,
      length
    })
    incrementTx(this.stats.wireRange, this.replicator.stats.wireRange)
  }

  extension(name, message) {
    this.wireExtension.send({ name: name === this.lastExtensionSent ? '' : name, message })
    incrementTx(this.stats.wireExtension, this.replicator.stats.wireExtension)
    this.lastExtensionSent = name
  }

  onextension(message) {
    const name = message.name || this.lastExtensionRecv
    this.lastExtensionRecv = name
    const ext = this.extensions.get(name)
    if (ext) {
      ext._onmessage({ start: 0, end: message.message.byteLength, buffer: message.message }, this)
    }
  }

  sendSync() {
    // Skip syncs if in repair mode
    if (this.core._repairMode) return

    if (this.syncsProcessing !== 0) {
      this.needsSync = true
      return
    }

    if (this.core.state.fork !== this.remoteFork) {
      this.canUpgrade = false
    }

    this.needsSync = false

    this.wireSync.send({
      fork: this.core.state.fork,
      length: this.core.state.length,
      remoteLength: this.core.state.fork === this.remoteFork ? this.remoteLength : 0,
      canUpgrade: this.canUpgrade,
      uploading: true,
      downloading: this.replicator.isDownloading(),
      hasManifest: !!this.core.header.manifest && this.core.compat === false,
      allowPush: this.replicator.isAllowingPush()
    })
    incrementTx(this.stats.wireSync, this.replicator.stats.wireSync)
  }

  onopen({ seeks, capability }) {
    const expected = caps.replicate(
      this.stream.isInitiator === false,
      this.core.key,
      this.stream.handshakeHash
    )

    if (b4a.equals(capability, expected) !== true) {
      // TODO: change this to a rejection instead, less leakage
      throw INVALID_CAPABILITY('Remote sent an invalid replication capability')
    }

    if (this.remoteOpened === true) return
    this.remoteOpened = true
    this.remoteSupportsSeeks = seeks

    this.protomux.cork()

    this.sendSync()

    const contig = Math.min(this.core.state.length, this.core.header.hints.contiguousLength)
    if (contig > 0) {
      this.broadcastRange(0, contig, false)

      if (contig === this.core.state.length) {
        this.broadcastedNonSparse = true
      }
    }

    this.replicator._ifAvailable--
    this.replicator._addPeer(this)

    this.protomux.uncork()

    this.core.checkIfIdle()
  }

  onclose(isRemote) {
    // we might have signalled to the remote that we are done (ie not downloading) and the remote might agree on that
    // if that happens, the channel might be closed by the remote. if so just renegotiate it.
    // TODO: add a CLOSE_REASON to mux to we can make this cleaner...
    const reopen =
      isRemote === true &&
      this.remoteOpened === true &&
      this.remoteDownloading === false &&
      this.remoteUploading === true &&
      this.replicator.downloading === true

    if (this.remoteOpened === false) {
      this.replicator._ifAvailable--
      this.replicator.queueUpdateAll()
      return
    }

    this.remoteOpened = false
    this.removed = true
    this.remoteRequests.clear() // cancel all
    this.receiverQueue.clear()

    if (this.roundtripQueue !== null) {
      for (const id of this.roundtripQueue.clear()) this.replicator._inflight.reusable(id)
    }

    this.replicator._removePeer(this)

    if (reopen) {
      this.replicator._makePeer(this.protomux)
    }
  }

  closeIfIdle() {
    if (this.remoteDownloading === false && this.replicator.isDownloading() === false) {
      // idling, shut it down...
      this.channel.close()
      return true
    }

    return false
  }

  async onsync(msg) {
    const {
      fork,
      length,
      remoteLength,
      canUpgrade,
      uploading,
      downloading,
      hasManifest,
      allowPush
    } = msg

    const lengthChanged = length !== this.remoteLength
    const sameFork = fork === this.core.state.fork

    this.remoteSynced = true
    this.remoteFork = fork
    this.remoteLength = length
    this.remoteCanUpgrade = canUpgrade
    this.remoteUploading = uploading
    this.remoteDownloading = downloading
    this.remoteHasManifest = hasManifest
    this.remoteAllowPush = allowPush

    if (this.closeIfIdle()) return

    this.lengthAcked = sameFork ? remoteLength : 0
    this.syncsProcessing++

    this.replicator._updateFork(this)

    if (this.remoteLength > this.core.state.length && this.lengthAcked === this.core.state.length) {
      if (this.replicator._addUpgradeMaybe() !== null) this._update()
    }

    const upgrade =
      lengthChanged === false || sameFork === false
        ? this.canUpgrade && sameFork
        : await this._canUpgrade(length, fork)

    if (length === this.remoteLength && fork === this.core.state.fork) {
      this.canUpgrade = upgrade
      if (upgrade) {
        this.lastUpgradableFork = fork
        this.lastUpgradableLength = length
      }
    }

    if (--this.syncsProcessing !== 0) return // ie not latest

    if (
      this.needsSync === true ||
      (this.core.state.fork === this.remoteFork && this.core.state.length > this.remoteLength)
    ) {
      this.signalUpgrade()
    }

    this._update()
  }

  _shouldUpdateCanUpgrade() {
    return (
      this.core.state.fork === this.remoteFork &&
      this.core.state.length > this.remoteLength &&
      this.canUpgrade === false &&
      this.syncsProcessing === 0
    )
  }

  async _updateCanUpgradeAndSync() {
    const { length, fork } = this.core.state

    const remoteLength = this.remoteLength
    const remoteFork = this.remoteFork
    const canUpgrade = await this._canUpgrade(this.remoteLength, this.remoteFork)

    if (
      this.syncsProcessing > 0 ||
      length !== this.core.state.length ||
      fork !== this.core.state.fork
    ) {
      return
    }
    if (remoteLength !== this.remoteLength || remoteFork !== this.remoteFork) {
      return
    }
    if (canUpgrade === this.canUpgrade) {
      return
    }

    this.canUpgrade = canUpgrade
    if (canUpgrade) {
      this.lastUpgradableLength = this.remoteLength
      this.lastUpgradableFork = this.remoteFork
    }

    this.sendSync()
  }

  // Safe to call in the background - never fails
  async _canUpgrade(remoteLength, remoteFork) {
    if (remoteFork !== this.core.state.fork) return false

    if (remoteLength === 0) return true
    if (remoteLength >= this.core.state.length) return false

    try {
      // Rely on caching to make sure this is cheap...
      const canUpgrade = await MerkleTree.upgradeable(this.core.state, remoteLength)

      if (remoteFork !== this.core.state.fork) return false

      return canUpgrade
    } catch {
      return false
    }
  }

  async _getProof(batch, msg, pushing) {
    let block = null

    if (msg.block) {
      const index = msg.block.index

      if (!pushing && (msg.fork !== this.core.state.fork || !this.core.bitfield.get(index))) {
        return new ProofRequest(msg, null, null, null)
      }

      block = batch.getBlock(index)
      block.catch(noop)
    }

    const manifest = msg.manifest && !this.core.compat ? this.core.header.manifest : null

    try {
      const proof = await MerkleTree.proof(this.core.state, batch, msg)
      return new ProofRequest(msg, proof, block, manifest)
    } catch (err) {
      batch.destroy()

      this.replicator._oninvalidrequest(err, msg, this)

      if (this.stats.invalidRequests >= MAX_INVALID_REQUESTS) throw err

      await backoff(this.stats.invalidRequests)
      return null
    }
  }

  async onrequest(msg) {
    const size = this.remoteRequests.size
    this.remoteRequests.set(msg.id, msg)

    // if size didnt change -> id overwrite -> old one is deleted, cancel current and re-add
    if (size === this.remoteRequests.size) {
      this._cancel(msg.id)
      this.remoteRequests.set(msg.id, msg)
    }

    if (!this.protomux.drained || this.receiverQueue.length) {
      this.receiverQueue.push(msg)
      return
    }

    if (this.replicator.destroyed) return

    await this._handleRequest(msg)
  }

  oncancel(msg) {
    this._cancel(msg.request)
  }

  _cancel(id) {
    this.remoteRequests.delete(id)
    this.receiverQueue.delete(id)
  }

  ondrain() {
    return this._handleRequests()
  }

  async _handleRequests() {
    if (this.receiverBusy || this.replicator.destroyed) return
    this.receiverBusy = true
    this.protomux.cork()

    while (
      this.remoteOpened &&
      this.protomux.drained &&
      this.receiverQueue.length > 0 &&
      !this.removed
    ) {
      const msg = this.receiverQueue.shift()
      await this._handleRequest(msg)
    }

    this.protomux.uncork()
    this.receiverBusy = false
  }

  async push(index) {
    if (!this.remoteAllowPush) return
    if (!this.remoteDownloading) return
    if (this.core.state.length <= index) return
    if (this.core.state.fork !== this.remoteFork) return
    if (this.remoteBitfield.get(index)) return

    const msg = {
      id: 0,
      fork: this.core.state.fork,
      block: null,
      hash: null,
      seek: null,
      upgrade: null,
      manifest: this.remoteLength === 0,
      priority: 0
    }

    await this.replicator._txLock.lock()
    try {
      const remoteLength = Math.max(this.remoteLength, this.pushedLength)

      msg.block = {
        index,
        nodes: MerkleTree.maxMissingNodes(2 * index, remoteLength)
      }

      if (index >= remoteLength) {
        msg.upgrade = {
          start: remoteLength,
          length: this.core.state.length - remoteLength
        }
      }

      let req = null
      const batch = this.core.storage.read()
      try {
        req = await this._getProof(batch, msg, true)
      } catch (err) {
        this.replicator._oninvalidrequest(err, msg, this)
        return
      }

      if (req === null) return
      batch.tryFlush()

      await this._fulfillRequest(req, true)
    } finally {
      this.replicator._txLock.unlock()
    }
  }

  async _handleRequest(msg) {
    const locked = !!msg.upgrade && this.remoteAllowPush

    if (locked) {
      // ensure contig push proofs
      await this.replicator._txLock.lock()
      const end = msg.upgrade.start + msg.upgrade.length

      if (this.pushedLength < end) {
        msg.upgrade.start = this.pushedLength
        msg.upgrade.length = end - this.pushedLength
      }
    }

    try {
      const batch = this.core.storage.read()

      // TODO: could still be answerable if (index, fork) is an ancestor of the current fork
      const req =
        msg.fork === this.core.state.fork
          ? await this._getProof(batch, msg, false)
          : new ProofRequest(msg, null, null, null)

      if (req === null) {
        this.wireNoData.send({ request: msg.id, reason: INVALID_REQUEST })
        return
      }

      batch.tryFlush()

      await this._fulfillRequest(req, false)
    } finally {
      if (locked) this.replicator._txLock.unlock()
    }
  }

  async _fulfillRequest(req, pushing) {
    if (this.core._repairMode) {
      // if cancelled do not reply
      if (this.remoteRequests.get(req.msg.id) !== req.msg) {
        return
      }

      // sync from now on, so safe to delete from the map
      this.remoteRequests.delete(req.msg.id)

      // If cutting off the fulfillment, ensure promise is caught.
      // While repairing merkle tree nodes can be `nil` so can throw.
      req.fulfill().catch(safetyCatch)
      return
    }

    const proof = await req.fulfill()

    if (!pushing) {
      // if cancelled do not reply
      if (this.remoteRequests.get(req.msg.id) !== req.msg) {
        return
      }

      // sync from now on, so safe to delete from the map
      this.remoteRequests.delete(req.msg.id)
    } else if (!this.remoteAllowPush) {
      // if pushing but remote disabled it, just drop it
      return
    }

    if (!this.isActive() && proof.block !== null) {
      return
    }

    if (proof === null) {
      if (req.msg.manifest && this.core.header.manifest) {
        const manifest = this.core.header.manifest
        this.wireData.send({
          request: req.msg.id,
          fork: this.core.state.fork,
          block: null,
          hash: null,
          seek: null,
          upgrade: null,
          manifest
        })
        incrementTx(this.stats.wireData, this.replicator.stats.wireData)
        return
      }

      this.wireNoData.send({ request: req.msg.id, reason: NOT_AVAILABLE })
      return
    }

    if (proof.block !== null) {
      this.replicator._onupload(proof.block.index, proof.block.value.byteLength, this)
    }

    if (proof.upgrade) {
      const remoteLength = MerkleTree.upgradeLength(proof.upgrade)
      if (remoteLength > this.pushedLength) this.pushedLength = remoteLength
    }

    this.wireData.send({
      request: req.msg.id,
      fork: req.msg.fork,
      block: proof.block,
      hash: proof.hash,
      seek: proof.seek,
      upgrade: proof.upgrade,
      manifest: proof.manifest
    })
    incrementTx(this.stats.wireData, this.replicator.stats.wireData)
  }

  _cancelRequest(req) {
    if (req.priority === PRIORITY.CANCELLED) return
    // mark as cancelled also and avoid re-entry
    req.priority = PRIORITY.CANCELLED

    this.inflight--
    this.replicator._requestDone(req.id, false)

    // clear inflight state
    if (isBlockRequest(req)) this.replicator._unmarkInflight(req.block.index)
    if (isUpgradeRequest(req)) this.replicator._clearInflightUpgrade(req)

    if (this.roundtripQueue === null) this.roundtripQueue = new RoundtripQueue()
    this.roundtripQueue.add(req.id)
    this.wireCancel.send({ request: req.id })
    incrementTx(this.stats.wireCancel, this.replicator.stats.wireCancel)
  }

  _checkIfConflict() {
    this.paused = true

    const length = Math.min(this.core.state.length, this.remoteLength)
    if (length === 0) return // pause and ignore

    this.wireRequest.send({
      id: 0, // TODO: use an more explicit id for this eventually...
      fork: this.remoteFork,
      block: null,
      hash: null,
      seek: null,
      upgrade: {
        start: 0,
        length
      }
    })

    incrementTx(this.stats.wireRequest, this.replicator.stats.wireRequest)
  }

  _unmarkInflightBlockRequest(req, data) {
    if (isBlockRequest(req)) this.replicator._unmarkInflight(req.block.index)
    else if (data.block && !req) this.replicator._unmarkInflight(data.block.index)
  }

  async ondata(data) {
    if (data.request !== 0 && !data.upgrade) return this._handleData(data)

    await this.replicator._rxLock.lock()
    try {
      await this._handleData(data)
    } finally {
      this.replicator._rxLock.unlock()
    }
  }

  async _handleData(data) {
    // always allow a fork conflict proof to be sent
    if (data.request === 0 && data.upgrade && data.upgrade.start === 0) {
      if (await this.core.checkConflict(data, this)) return
      this.paused = false
    }

    const req = data.request > 0 ? this.replicator._inflight.get(data.request) : null
    const reorg = data.fork > this.core.state.fork

    // no push atm, TODO: check if this satisfies another pending request
    // allow reorg pushes tho as those are not written to storage so we'll take all the help we can get
    if (req === null && reorg === false && !this.replicator.allowPush) {
      return
    }

    // Skip accepting data if in repair mode to avoid corruption
    if (this.core._repairMode) {
      this.replicator._onnodata(this, req, NOT_AVAILABLE)
      return
    }

    if (req === null && reorg === false && data.block) {
      // mark this as inflight to avoid parallel requests
      this.replicator._markInflight(data.block.index)
    }

    if (req !== null) {
      if (req.peer !== this) return
      this._onrequestroundtrip(req)
    }

    try {
      if (reorg === true) return await this.replicator._onreorgdata(this, req, data)
    } catch (err) {
      safetyCatch(err)
      this._unmarkInflightBlockRequest(req, data)

      this.paused = true
      this.replicator._oninvaliddata(err, req, data, this)
      return
    }

    this.dataProcessing++
    if (isBlockRequest(req)) this.replicator._markProcessing(req.block.index)

    try {
      if (!this.replicator._matchingRequest(req, data) || !(await this.core.verify(data, this))) {
        this.replicator._onnodata(this, req, 0)
        return
      }
    } catch (err) {
      safetyCatch(err)
      this._unmarkInflightBlockRequest(req, data)

      if (err.code === 'WRITE_FAILED') {
        // For example, we don't want to keep pulling data when storage is full
        // TODO: notify the user somehow
        this.paused = true
        return
      }

      if (this.core.closed && !isCriticalError(err)) return

      if (err.code !== 'INVALID_OPERATION') {
        // might be a fork, verify
        this._checkIfConflict()
      }

      // if push mode, we MIGHT get an occasional bad message
      // no need to mega bail for that. TODO: rate limit instead as a general thing
      if (!this.replicator.allowPush) {
        this.paused = true
      }

      this.replicator._onnodata(this, req, 0)
      this.replicator._oninvaliddata(err, req, data, this)
      return
    } finally {
      if (isBlockRequest(req)) this.replicator._markProcessed(req.block.index)
      this.dataProcessing--
    }

    this.replicator._ondata(this, req, data)

    if (this._shouldUpdateCanUpgrade() === true) {
      this._updateCanUpgradeAndSync()
    }
  }

  onnodata({ request, reason }) {
    const req = request > 0 ? this.replicator._inflight.get(request) : null

    if (req === null || req.peer !== this) {
      this.replicator.queueUpdateAll()
      return
    }

    this._onrequestroundtrip(req)
    this.replicator._onnodata(this, req, reason)
  }

  _onrequestroundtrip(req) {
    if (req.priority === PRIORITY.CANCELLED) return
    // to avoid re-entry we also just mark it as cancelled
    req.priority = PRIORITY.CANCELLED

    this.inflight--
    this.replicator._requestDone(req.id, true)
    if (this.roundtripQueue === null) return
    const flushed = this.roundtripQueue.flush(req.rt)
    if (flushed === null) return
    for (const id of flushed) this.replicator._inflight.reusable(id)
  }

  onwant(range) {
    if (!this.remoteWants.add(range)) return
    this.replicator._onwant(this, range.start, range.length, range.any)
  }

  onunwant(range) {
    this.remoteWants.remove(range)
  }

  onbitfield({ start, bitfield }) {
    if (start < this._remoteContiguousLength) this._remoteContiguousLength = start // bitfield is always the truth
    this.remoteBitfield.insert(start, bitfield)
    this.missingBlocks.insert(start, bitfield)
    this._clearLocalRange(start, bitfield.byteLength * 8)
    this._update()
  }

  _clearLocalRange(start, length) {
    const bitfield = this.core.skipBitfield === null ? this.core.bitfield : this.core.skipBitfield

    if (length === 1) {
      this.missingBlocks.set(start, this._remoteHasBlock(start) && !bitfield.get(start))
      return
    }

    const contig = Math.min(this.core.state.length, this.core.header.hints.contiguousLength)

    if (start + length < contig) {
      this.missingBlocks.setRange(start, contig, false)
      return
    }

    const rem = start & 32767
    if (rem > 0) {
      start -= rem
      length += rem
    }

    const end = start + Math.min(length, this.core.state.length)
    while (start < end) {
      const local = bitfield.getBitfield(start)

      if (local && local.bitfield) {
        this.missingBlocks.clear(start, local.bitfield)
      }

      start += 32768
    }
  }

  _resetMissingBlock(index) {
    const bitfield = this.core.skipBitfield === null ? this.core.bitfield : this.core.skipBitfield
    this.missingBlocks.set(index, this._remoteHasBlock(index) && !bitfield.get(index))
  }

  _unclearLocalRange(start, length) {
    if (length === 1) {
      this._resetMissingBlock(start)
      return
    }

    const rem = start & (RemoteBitfield.BITS_PER_SEGMENT - 1)
    if (rem > 0) {
      start -= rem
      length += rem
    }

    const fixedStart = start

    const end = start + Math.min(length, this.remoteLength)
    while (start < end) {
      const remote = this.remoteBitfield.getBitfield(start)
      if (remote && remote.bitfield) {
        this.missingBlocks.insert(start, remote.bitfield)
      }

      start += RemoteBitfield.BITS_PER_SEGMENT
    }

    this._clearLocalRange(fixedStart, length)
  }

  async onrange({ drop, start, length }) {
    const has = drop === false

    if (drop === true && start < this._remoteContiguousLength) {
      this._remoteContiguousLength = start
    }

    if (start === 0 && drop === false) {
      if (length > this._remoteContiguousLength) {
        this._remoteContiguousLength = length
        if (
          this.remoteFork === this.core.state.fork &&
          length > this.core.header.hints.remoteContiguousLength
        ) {
          this.core.updateRemoteContiguousLength(length)
        }
      }
    } else if (length === 1) {
      const bitfield = this.core.skipBitfield === null ? this.core.bitfield : this.core.skipBitfield
      this.remoteBitfield.set(start, has)
      this.missingBlocks.set(start, has && !bitfield.get(start))
    } else {
      const rangeStart = this.remoteBitfield.findFirst(!has, start)
      const rangeEnd = length + start

      if (rangeStart !== -1 && rangeStart < rangeEnd) {
        this.remoteBitfield.setRange(rangeStart, rangeEnd, has)
        this.missingBlocks.setRange(rangeStart, rangeEnd, has)
        if (has) this._clearLocalRange(rangeStart, rangeEnd - rangeStart)
      }
    }

    if (this.core.hintsChanged) await this.core.flushHints()
    if (drop === false) this._update()

    this.core.emitRemoteContiguousLength()
  }

  onreorghint() {
    // TODO
  }

  _update() {
    // TODO: if this is in a batch or similar it would be better to defer it
    // we could do that with nextTick/microtick mb? (combined with a property on the session to signal read buffer mb)
    this.replicator.updatePeer(this)
  }

  async _onconflict() {
    this.protomux.cork()
    if (this.remoteLength > 0 && this.core.state.fork === this.remoteFork) {
      await this.onrequest({
        id: 0,
        fork: this.core.state.fork,
        block: null,
        hash: null,
        seek: null,
        upgrade: {
          start: 0,
          length: Math.min(this.core.state.length, this.remoteLength)
        }
      })
    }
    this.channel.close()
    this.protomux.uncork()
  }

  _makeRequest(needsUpgrade, priority, minLength) {
    if (needsUpgrade === true && this.replicator._shouldUpgrade(this) === false) {
      return null
    }

    // ensure that the remote has signalled they have the length we request
    if (this.remoteLength < minLength) {
      return null
    }

    if (needsUpgrade === false && this.replicator._autoUpgrade(this) === true) {
      needsUpgrade = true
    }

    return {
      peer: this,
      rt: this.roundtripQueue === null ? 0 : this.roundtripQueue.tick,
      id: 0,
      fork: this.remoteFork,
      block: null,
      hash: null,
      seek: null,
      upgrade:
        needsUpgrade === false
          ? null
          : { start: this.core.state.length, length: this.remoteLength - this.core.state.length },
      // remote manifest check can be removed eventually...
      manifest: this.core.header.manifest === null && this.remoteHasManifest === true,
      priority,
      timestamp: Date.now(),
      elapsed: 0
    }
  }

  _requestManifest() {
    const req = this._makeRequest(false, 0, 0)
    if (req === null) return

    this._send(req)
  }

  _includeLastBlock() {
    if (this.replicator._alwaysLatestBlock === 0) return null

    const index = this.remoteLength - 1

    // only valid if its an OOB get
    if (index < this.core.state.length) return null

    // do the normal checks
    if (!this._remoteHasBlock(index)) return null
    if (!this._canRequest(index, false)) return null

    // atm we only ever do one upgrade request in parallel, if that changes
    // then we should add some check here for inflights to avoid over requesting
    const b = this.replicator._blocks.add(index, PRIORITY.NORMAL, false)
    return b
  }

  _requestUpgrade(u) {
    if (this.replicator.pushOnly) return false

    const req = this._makeRequest(true, 0, 0)
    if (req === null) return false

    const b = this._includeLastBlock()

    if (b) this._sendBlockRequest(req, b)
    else this._send(req)

    return true
  }

  _requestSeek(s) {
    // if replicator is updating the seeks etc, bail and wait for it to drain
    if (this.replicator._updatesPending > 0) return false
    if (this.replicator.pushOnly) return false

    const { length, fork } = this.core.state

    if (fork !== this.remoteFork) return false

    if (s.seeker.start >= length) {
      const req = this._makeRequest(true, 0, 0)

      // We need an upgrade for the seek, if non can be provided, skip
      if (req === null) return false

      req.seek = this.remoteSupportsSeeks
        ? { bytes: s.seeker.bytes, padding: s.seeker.padding }
        : null

      s.inflight.push(req)
      this._send(req)

      return true
    }

    const len = s.seeker.end - s.seeker.start
    const off = s.seeker.start + Math.floor(Math.random() * len)

    for (let i = 0; i < len; i++) {
      let index = off + i
      if (index > s.seeker.end) index -= len

      if (this._remoteHasBlock(index) === false) continue
      if (this.core.bitfield.get(index) === true) continue
      if (!this._canRequest(index, false)) continue

      // Check if this block is currently inflight - if so pick another
      const b = this.replicator._blocks.get(index)
      if (b !== null && b.inflight.length > 0) continue

      // Block is not inflight, but we only want the hash, check if that is inflight
      const h = this.replicator._hashes.add(index, PRIORITY.NORMAL, false)
      if (h.inflight.length > 0) continue

      const req = this._makeRequest(false, h.priority, index + 1)
      if (req === null) continue

      const nodes = flatTree.depth(s.seeker.start + s.seeker.end - 1)

      req.hash = { index: 2 * index, nodes }
      req.seek = this.remoteSupportsSeeks
        ? { bytes: s.seeker.bytes, padding: s.seeker.padding }
        : null

      s.inflight.push(req)
      h.inflight.push(req)
      this._send(req)

      return true
    }

    this._maybeWantAnyRange(s.seeker.start, len, s)
    return false
  }

  _canRequest(index, force) {
    if (!(index >= 0)) throw ASSERTION('bad index to _canRequest: ' + index)

    if (!force && this.replicator.pushOnly) {
      return false
    }

    if (this.remoteLength >= this.core.state.length) {
      return true
    }

    if (index < this.lastUpgradableLength && this.lastUpgradableFork === this.core.state.fork) {
      return true
    }

    if (this.canUpgrade && this.syncsProcessing === 0) {
      return true
    }

    return false
  }

  _remoteHasBlock(index) {
    return index < this._remoteContiguousLength || this.remoteBitfield.get(index) === true
  }

  _sendBlockRequest(req, b) {
    if (this.core._repairMode) return

    req.block = { index: b.index, nodes: 0 }
    this.replicator._markInflight(b.index)

    b.inflight.push(req)
    this.replicator.hotswaps.add(b)
    this._send(req)
  }

  _requestBlock(b) {
    const { length, fork } = this.core.state

    if (this._remoteHasBlock(b.index) === false || fork !== this.remoteFork) {
      if (!this.core.bitfield.get(b.index)) this._maybeWant(b.index, b)
      return false
    }

    if (!this._canRequest(b.index, b.force)) return false

    const req = this._makeRequest(b.index >= length, b.priority, b.index + 1)
    if (req === null) return false

    this._sendBlockRequest(req, b)

    return true
  }

  _maybeWant(index, handle) {
    if (index < this.remoteContiguousLength) return

    const res = this.wants.add(index, handle)
    if (!res) return

    const batch = res.want && res.unwant
    if (batch) this.protomux.cork()

    if (res.unwant) {
      this.wireUnwant.send(res.unwant)
      incrementTx(this.stats.wireUnwant, this.replicator.stats.wireUnwant)
    }
    if (res.want) {
      this.wireWant.send(res.want)
      incrementTx(this.stats.wireWant, this.replicator.stats.wireWant)
    }

    if (batch) this.protomux.uncork()
  }

  _maybeWantAnyRange(start, length, handle) {
    if (handle.wants) {
      for (const w of handle.wants) {
        if ((w.start !== start || w.length !== length) && w.any) {
          const req = this.wants.removeAnyRange(w.start, w.length, handle)
          if (req) this.wireUnwant.send(req)
        }
      }
    }

    if (start + length <= this.remoteContiguousLength) return

    const req = this.wants.addAnyRange(start, length, handle)
    if (req) this.wireWant.send(req)
  }

  _requestRangeBlock(index, length) {
    if (this.core.bitfield.get(index) === true || !this._canRequest(index, false)) return false

    const b = this.replicator._blocks.add(index, PRIORITY.NORMAL, false)
    if (b.inflight.length > 0) {
      this.missingBlocks.set(index, false) // in case we missed some states just set them ondemand, nbd
      return false
    }

    const req = this._makeRequest(index >= length, b.priority, index + 1)

    // If the request cannot be satisfied, dealloc the block request if no one is subscribed to it
    if (req === null) {
      b.gc()
      return false
    }

    this._sendBlockRequest(req, b)

    // Don't think this will ever happen, as the pending queue is drained before the range queue
    // but doesn't hurt to check this explicitly here also.
    if (b.queued) b.queued = false
    return true
  }

  _findNext(i) {
    if (i < this._remoteContiguousLength) {
      if (this.core.skipBitfield === null) this.replicator._openSkipBitfield()
      i = this.core.skipBitfield.findFirst(false, i)
      if (i < this._remoteContiguousLength && i > -1) return i
      i = this._remoteContiguousLength
    }

    return this.missingBlocks.findFirst(true, i)
  }

  _addRangeBatch(r, offset, end) {
    const { WANT_BATCH } = w
    while (offset < end) {
      const next = this.core.bitfield.findFirst(false, offset)
      if (next === -1 || next >= end) return false

      const b = (next - (next & (WANT_BATCH - 1))) / WANT_BATCH

      if (r.addBatch(b)) return true

      offset = (b + 1) * WANT_BATCH
    }

    return false
  }

  _populateRangeBatches(r) {
    const { WANT_BATCH } = w
    for (let i = r.batches.length - 1; i >= 0; i--) {
      const b = r.batches[i]
      const minStart = b.batch * WANT_BATCH
      const maxEnd = minStart + WANT_BATCH

      const start = Math.max(r.start, minStart)
      const end = Math.min(r.end === -1 ? maxEnd : r.end, maxEnd)

      if (start < end && this.core.bitfield.hasUnset(start, end - start)) continue

      r.removeBatch(b)
    }

    while (r.batches.length < 3) {
      const end = r.end === -1 ? this.core.state.length : r.end
      if (end <= r.start) return

      const len = end - r.start
      const off = r.start + (r.linear ? 0 : Math.floor(Math.random() * len))

      if (!this._addRangeBatch(r, off, end) && !this._addRangeBatch(r, r.start, end)) break
    }
  }

  _requestRangeBatch(start, end, length) {
    let tries = this.inflight

    do {
      start = this._findNext(start)
      if (start === -1 || start >= end) break

      if (this._requestRangeBlock(start, length)) return true
      start++
    } while (tries-- > 0)

    return false
  }

  _getValidEnd(maxEnd) {
    // if we can upgrade the remote, or the remote is ahead, then all the remotes blocks are valid
    // otherwise truncate to the last length the remote has acked for us
    const maxLocalLength =
      this.canUpgrade || this.remoteLength >= this.core.state.length
        ? this.core.state.length
        : this.core.state.fork === this.lastUpgradableFork
          ? Math.min(this.lastUpgradableLength, this.core.state.length)
          : 0

    return Math.min(
      maxLocalLength,
      Math.min(maxEnd === -1 ? this.remoteLength : maxEnd, this.remoteLength)
    )
  }

  _requestRange(r) {
    const { WANT_BATCH } = w
    if (this.syncsProcessing > 0) return false

    const { length, fork } = this.core.state

    if (r.blocks) {
      for (let i = r.start; i < r.end; i++) {
        const index = r.blocks[i]
        const has = index < this._remoteContiguousLength || this.missingBlocks.get(index) === true
        if (has === true && this._requestRangeBlock(index, length)) return true
        this._maybeWant(index, r)
      }

      return false
    }

    this._populateRangeBatches(r)

    const end = this._getValidEnd(r.end)

    if (end <= r.start || fork !== this.remoteFork) return false

    for (let i = 0; i < r.batches.length; i++) {
      const b = r.batches[i]

      const batchStart = Math.max(b.batch * WANT_BATCH, r.start)
      const batchEnd = Math.min((b.batch + 1) * WANT_BATCH, end)
      const len = batchEnd - batchStart
      const off = batchStart + (r.linear ? 0 : Math.floor(Math.random() * len))

      if (
        this._requestRangeBatch(off, end, length) ||
        this._requestRangeBatch(batchStart, off, length)
      ) {
        return true
      }

      this._maybeWant(batchStart, b)
    }

    // Here we should consider making an OOB request (ie if the remote says they have a newer block)
    // but the upgrade code already does that, so no big deal for now

    return false
  }

  _requestForkProof(f) {
    if (!this.remoteLength) return
    if (this.replicator.pushOnly) return

    const req = this._makeRequest(false, 0, 0)
    if (req === null) return

    req.upgrade = { start: 0, length: this.remoteLength }
    req.manifest = !this.core.header.manifest

    f.inflight.push(req)
    this._send(req)
  }

  _requestForkRange(f) {
    if (f.fork !== this.remoteFork || f.batch.want === null) return false
    if (this.replicator.pushOnly) return false

    const end = Math.min(f.batch.want.end, this.remoteLength)
    if (end < f.batch.want.start) return false

    const len = end - f.batch.want.start
    const off = f.batch.want.start + Math.floor(Math.random() * len)

    for (let i = 0; i < len; i++) {
      let index = off + i
      if (index >= end) index -= len

      if (this._remoteHasBlock(index) === false) continue

      const req = this._makeRequest(false, 0, 0)
      if (req === null) return false

      req.hash = { index: 2 * index, nodes: f.batch.want.nodes }

      f.inflight.push(req)
      this._send(req)

      return true
    }

    this._maybeWantAnyRange(f.batch.want.start, len, f)
    return false
  }

  isActive() {
    if (this.paused || this.removed || this.core.header.frozen) return false
    return true
  }

  async _send(req) {
    const fork = this.core.state.fork

    this.inflight++
    this.replicator._inflight.add(req)

    if (req.upgrade !== null && req.fork === fork) {
      const u = this.replicator._addUpgrade()
      u.inflight.push(req)
    }

    try {
      if (req.block !== null && req.fork === fork) {
        req.block.nodes = await MerkleTree.missingNodes(
          this.core.state,
          2 * req.block.index,
          this.core.state.length
        )
        if (req.priority === PRIORITY.CANCELLED) return
      }
      if (req.hash !== null && req.fork === fork && req.hash.nodes === 0) {
        req.hash.nodes = await MerkleTree.missingNodes(
          this.core.state,
          req.hash.index,
          this.core.state.length
        )
        if (req.priority === PRIORITY.CANCELLED) return

        // nodes === 0, we already have it, bail
        if (req.hash.nodes === 0 && (req.hash.index & 1) === 0) {
          this.inflight--
          this.replicator._resolveHashLocally(this, req)
          return
        }
      }
    } catch (err) {
      this.stream.destroy(err)
      return
    }

    this.wireRequest.send(req)
    incrementTx(this.stats.wireRequest, this.replicator.stats.wireRequest)
  }
}

module.exports = class Replicator {
  static Peer = Peer // hack to be able to access Peer from outside this module

  constructor(
    core,
    {
      notDownloadingLinger = NOT_DOWNLOADING_SLACK,
      eagerUpgrade = true,
      allowFork = true,
      allowPush = false,
      alwaysLatestBlock = false,
      inflightRange = null
    } = {}
  ) {
    this.core = core
    this.eagerUpgrade = eagerUpgrade
    this.allowFork = allowFork
    this.allowPush = allowPush
    this.ondownloading = null // optional external hook for monitoring downloading status
    this.peers = []
    this.findingPeers = 0 // updatable from the outside
    this.destroyed = false
    this.downloading = false
    this.pushOnly = false
    this.activeSessions = 0

    this.hotswaps = new HotswapQueue()
    this.inflightRange = inflightRange || DEFAULT_MAX_INFLIGHT

    // Note: nodata and unwant not currently tracked
    // tx = transmitted, rx = received
    this.stats = {
      wireSync: { tx: 0, rx: 0 },
      wireRequest: { tx: 0, rx: 0 },
      wireCancel: { tx: 0, rx: 0 },
      wireData: { tx: 0, rx: 0 },
      wireWant: { tx: 0, rx: 0 },
      wireUnwant: { tx: 0, rx: 0 },
      wireBitfield: { tx: 0, rx: 0 },
      wireRange: { tx: 0, rx: 0 },
      wireExtension: { tx: 0, rx: 0 },
      hotswaps: 0,
      invalidData: 0,
      invalidRequests: 0,
      backoffs: 0,
      notAvailableBackoffs: 0
    }

    this._attached = new Set()
    this._inflight = new InflightTracker()
    this._blocks = new BlockTracker(this)
    this._hashes = new BlockTracker(this)

    this._alwaysLatestBlock = alwaysLatestBlock ? 1 : 0
    this._queued = []

    this._seeks = []
    this._upgrade = null
    this._reorgs = []
    this._ranges = []

    this._rxLock = new Mutex()
    this._txLock = new Mutex()

    this._hadPeers = false
    this._active = 0
    this._ifAvailable = 0
    this._updatesPending = 0
    this._applyingReorg = null
    this._manifestPeer = null
    this._notDownloadingLinger = notDownloadingLinger
    this._notDownloadingTimer = null

    this._updateAllBump = null
    this._updateAllBound = this.updateAll.bind(this)

    const self = this
    this._onstreamclose = onstreamclose

    function onstreamclose() {
      self.detachFrom(this.userData)
    }
  }

  setInflightRange(min, max) {
    const def = this.inflightRange
    this.inflightRange = [min, max]
    for (const peer of this.peers) {
      if (peer.inflightRange !== def) continue
      peer.inflightRange = this.inflightRange
    }
  }

  updateActivity(inc, session) {
    this.activeSessions += inc
    this.setDownloading(this.activeSessions !== 0, session)
  }

  isDownloading() {
    return this.downloading || !this._inflight.idle
  }

  async push(index) {
    const all = []
    for (const peer of this.peers) {
      all.push(peer.push(index))
    }
    await Promise.all(all)
  }

  setAllowPush(allowPush) {
    if (allowPush === this.allowPush) return
    this.allowPush = allowPush
    for (const peer of this.peers) peer.sendSync()
  }

  isAllowingPush() {
    if (!this.allowPush) return false
    if (this._notDownloadingTimer) return false
    return this.downloading
  }

  setPushOnly(pushOnly) {
    if (pushOnly === this.pushOnly) return
    this.pushOnly = pushOnly
  }

  setDownloading(downloading) {
    const allowPush = this.isAllowingPush()
    const linger = this._notDownloadingLinger

    if (this._notDownloadingTimer) {
      clearTimeout(this._notDownloadingTimer)
      this._notDownloadingTimer = null
    }

    if (this.destroyed) return

    if (downloading || linger === 0) {
      if (!this._setDownloadingNow(downloading)) this.signalAllowPush(allowPush)
      return
    }

    this._notDownloadingTimer = setTimeout(setNotDownloadingLater, linger, this)
    if (this._notDownloadingTimer.unref) this._notDownloadingTimer.unref()
    this.signalAllowPush(allowPush)
  }

  signalAllowPush(allowPush) {
    if (allowPush === this.isAllowingPush()) return
    for (const peer of this.peers) peer.signalUpgrade()
  }

  _setDownloadingNow(downloading) {
    this._notDownloadingTimer = null

    if (this.downloading === downloading) return false
    this.downloading = downloading

    if (!downloading && this.isDownloading()) return false

    for (const peer of this.peers) peer.signalUpgrade()

    if (downloading) {
      // restart channel if needed...
      for (const protomux of this._attached) {
        if (!protomux.stream.handshakeHash) continue
        if (protomux.opened({ protocol: 'hypercore/alpha', id: this.core.discoveryKey })) continue
        this._makePeer(protomux, true)
      }
    } else {
      for (const peer of this.peers) peer.closeIfIdle()
    }

    if (this.ondownloading !== null && downloading) this.ondownloading()
    return true
  }

  cork() {
    for (const peer of this.peers) peer.protomux.cork()
  }

  uncork() {
    for (const peer of this.peers) peer.protomux.uncork()
  }

  // Called externally when a range of new blocks has been processed/removed
  onhave(start, length, drop = false) {
    for (const peer of this.peers) peer.broadcastRange(start, length, drop)
  }

  // Called externally when a truncation upgrade has been processed
  ontruncate(newLength, truncated) {
    const notify = []

    for (const blk of this._blocks) {
      if (blk.index < newLength) continue
      notify.push(blk)
    }

    for (const blk of notify) {
      for (const r of blk.refs) {
        if (r.snapshot === false) continue
        blk.detach(r, SNAPSHOT_NOT_AVAILABLE())
      }
    }

    for (const peer of this.peers) {
      peer.fullyDownloadedSignaled = Math.min(newLength, peer.fullyDownloadedSignaled)
      peer._unclearLocalRange(newLength, truncated)
    }
  }

  // Called externally when a upgrade has been processed
  onupgrade() {
    for (const peer of this.peers) peer.signalUpgrade()
    if (this._blocks.isEmpty() === false) this._resolveBlocksLocally()
    if (this._upgrade !== null) this._resolveUpgradeRequest(null)
    if (!this._blocks.isEmpty() || this._ranges.length !== 0 || this._seeks.length !== 0) {
      this._updateNonPrimary(true)
    }
  }

  // Called externally when a conflict has been detected and verified
  async onconflict() {
    const all = []
    for (const peer of this.peers) {
      all.push(peer._onconflict())
    }
    await Promise.allSettled(all)
  }

  async applyPendingReorg() {
    if (this._applyingReorg !== null) {
      await this._applyingReorg
      return true
    }

    for (let i = this._reorgs.length - 1; i >= 0; i--) {
      const f = this._reorgs[i]
      if (f.batch !== null && f.batch.finished) {
        await this._applyReorg(f)
        return true
      }
    }

    return false
  }

  addUpgrade(session) {
    if (this._upgrade !== null) {
      const ref = this._upgrade.attach(session)
      this._checkUpgradeIfAvailable()
      return ref
    }

    const ref = this._addUpgrade().attach(session)

    this.queueUpdateAll()

    return ref
  }

  addBlock(session, index, force) {
    const b = this._blocks.add(index, PRIORITY.HIGH, force)
    const ref = b.attach(session)

    this._queueBlock(b)
    this.queueUpdateAll()

    return ref
  }

  addSeek(session, seeker) {
    const s = new SeekRequest(this, this._seeks, seeker)
    const ref = s.attach(session)

    this._seeks.push(s)
    this.queueUpdateAll()

    return ref
  }

  addRange(
    session,
    { start = 0, end = -1, length = toLength(start, end), blocks = null, linear = false } = {}
  ) {
    if (blocks !== null) {
      // if using blocks, start, end just acts as frames around the blocks array
      start = 0
      end = length = blocks.length
    }

    const r = new RangeRequest(
      this,
      this._ranges,
      start,
      length === -1 ? -1 : start + length,
      linear,
      blocks
    )

    const ref = r.attach(session)

    // Trigger this to see if this is already resolved...
    // Also auto compresses the range based on local bitfield
    clampRange(this.core, r)

    if (r.end !== -1 && r.start >= r.end) {
      this._resolveRangeRequest(r)
      return ref
    }

    this.queueUpdateAll()

    return ref
  }

  cancel(ref) {
    ref.context.detach(ref, null)
  }

  static clearRequests(session, err) {
    if (session.length === 0) return
    if (session.length === 1 && session[0] === null) return

    const updated = new Set()

    while (session.length > 0) {
      const ref = session[session.length - 1]
      updated.add(ref.context.replicator)
      ref.context.detach(ref, err)
    }

    for (const replicator of updated) {
      replicator.queueUpdateAll()
    }
  }

  clearRequests(session, err = null) {
    let cleared = false
    while (session.length > 0) {
      const ref = session[session.length - 1]
      ref.context.detach(ref, err)
      cleared = true
    }

    if (cleared) this.queueUpdateAll()
  }

  _matchingRequest(req, data) {
    if (this.allowPush) {
      return true
    }
    if (data.block !== null && (req.block === null || req.block.index !== data.block.index)) {
      return false
    }
    if (data.hash !== null && (req.hash === null || req.hash.index !== data.hash.index)) {
      return false
    }
    if (data.seek !== null && (req.seek === null || req.seek.bytes !== data.seek.bytes)) {
      return false
    }
    if (data.upgrade !== null && req.upgrade === null) {
      return false
    }
    return req.fork === data.fork
  }

  _addUpgradeMaybe() {
    return this.eagerUpgrade === true ? this._addUpgrade() : this._upgrade
  }

  // TODO: this function is OVER called atm, at each updatePeer/updateAll
  // instead its more efficient to only call it when the conditions in here change - ie on sync/add/remove peer
  // Do this when we have more tests.
  _checkUpgradeIfAvailable() {
    if (this._ifAvailable > 0 && this.peers.length < MAX_PEERS_UPGRADE) return
    if (this._upgrade === null || this._upgrade.refs.length === 0) return
    if (this._hadPeers === false && this.findingPeers > 0) return

    const maxPeers = Math.min(this.peers.length, MAX_PEERS_UPGRADE)

    // check if a peer can upgrade us

    for (let i = 0; i < maxPeers; i++) {
      const peer = this.peers[i]

      if (peer.remoteSynced === false) return

      if (this.core.state.length === 0 && peer.remoteLength > 0) return

      if (peer.remoteLength <= this._upgrade.length || peer.remoteFork !== this._upgrade.fork) {
        continue
      }

      if (peer.syncsProcessing > 0) return

      if (peer.lengthAcked !== this.core.state.length && peer.remoteFork === this.core.state.fork) {
        return
      }

      if (peer.remoteCanUpgrade === true) return
    }

    // check if reorgs in progress...

    if (this._applyingReorg !== null) return

    // TODO: we prob should NOT wait for inflight reorgs here, seems better to just resolve the upgrade
    // and then apply the reorg on the next call in case it's slow - needs some testing in practice

    for (let i = 0; i < this._reorgs.length; i++) {
      const r = this._reorgs[i]
      if (r.inflight.length > 0) return
    }

    // if something is inflight, wait for that first
    if (this._upgrade.inflight.length > 0) return

    // nothing to do, indicate no update avail

    const u = this._upgrade
    this._upgrade = null
    u.resolve(false)
  }

  _addUpgrade() {
    if (this._upgrade !== null) return this._upgrade

    // TODO: needs a reorg: true/false flag to indicate if the user requested a reorg
    this._upgrade = new UpgradeRequest(this, this.core.state.fork, this.core.state.length)

    return this._upgrade
  }

  _addReorg(fork, peer) {
    if (this.allowFork === false) return null

    // TODO: eager gc old reorgs from the same peer
    // not super important because they'll get gc'ed when the request finishes
    // but just spam the remote can do ...

    for (const f of this._reorgs) {
      if (f.fork > fork && f.batch !== null) return null
      if (f.fork === fork) return f
    }

    const f = new ForkRequest(this, fork)

    this._reorgs.push(f)

    // maintain sorted by fork
    let i = this._reorgs.length - 1
    while (i > 0 && this._reorgs[i - 1].fork > fork) {
      this._reorgs[i] = this._reorgs[i - 1]
      this._reorgs[--i] = f
    }

    return f
  }

  _shouldUpgrade(peer) {
    if (this._upgrade !== null && this._upgrade.inflight.length > 0) return false
    return (
      peer.remoteCanUpgrade === true &&
      peer.remoteLength > this.core.state.length &&
      peer.lengthAcked === this.core.state.length
    )
  }

  _autoUpgrade(peer) {
    return (
      this._upgrade !== null &&
      peer.remoteFork === this.core.state.fork &&
      this._shouldUpgrade(peer)
    )
  }

  _addPeer(peer) {
    this._hadPeers = true
    this.peers.push(peer)
    this.updatePeer(peer)
    this._onpeerupdate(true, peer)
  }

  _requestDone(id, roundtrip) {
    this._inflight.remove(id, roundtrip)
    if (this.isDownloading() === true) return
    for (const peer of this.peers) peer.signalUpgrade()
  }

  _removePeer(peer) {
    this.peers.splice(this.peers.indexOf(peer), 1)
    peer.wants.destroy()

    if (this._manifestPeer === peer) this._manifestPeer = null

    let inflight = false
    for (const req of this._inflight) {
      if (req.peer !== peer) continue
      inflight = true
      this._inflight.remove(req.id, true)
      this._clearRequest(peer, req)
    }

    this._onpeerupdate(false, peer)
    if (inflight) {
      this.queueUpdateAll()
    } else {
      this._checkUpgradeIfAvailable()
    }
  }

  _queueBlock(b) {
    if (b.inflight.length > 0 || b.queued === true) return
    b.queued = true
    this._queued.push(b)
  }

  _resolveHashLocally(peer, req) {
    this._requestDone(req.id, false)
    this._resolveBlockRequest(this._hashes, req.hash.index / 2, null, req)
    this.updatePeer(peer)
  }

  // Runs in the background - not allowed to throw
  async _resolveBlocksLocally() {
    // TODO: check if fork compat etc. Requires that we pass down truncation info

    const clear = []
    const blocks = []

    const reader = this.core.storage.read()
    for (const b of this._blocks) {
      if (this.core.bitfield.get(b.index) === false) continue
      blocks.push(this._resolveLocalBlock(b, reader, clear))
    }
    reader.tryFlush()

    await Promise.all(blocks)

    if (!clear.length) return

    // Currently the block tracker does not support deletes during iteration, so we make
    // sure to clear them afterwards.
    for (const b of clear) {
      this._blocks.remove(b.index)
      removeHotswap(b)
    }
  }

  async _resolveLocalBlock(b, reader, resolved) {
    try {
      b.resolve(await reader.getBlock(b.index))
    } catch (err) {
      b.reject(err)
      return
    }

    resolved.push(b)
  }

  _resolveBlockRequest(tracker, index, value, req) {
    const b = tracker.remove(index)
    if (b === null) return false

    removeInflight(b.inflight, req)
    removeHotswap(b)
    b.queued = false

    b.resolve(value)

    if (b.inflight.length > 0) {
      // if anything is still inflight, cancel it
      for (let i = b.inflight.length - 1; i >= 0; i--) {
        const req = b.inflight[i]
        req.peer._cancelRequest(req)
      }
    }

    return true
  }

  _resolveUpgradeRequest(req) {
    if (req !== null) removeInflight(this._upgrade.inflight, req)

    if (
      this.core.state.length === this._upgrade.length &&
      this.core.state.fork === this._upgrade.fork
    ) {
      return false
    }

    const u = this._upgrade
    this._upgrade = null
    u.resolve(true)

    return true
  }

  _resolveRangeRequest(req) {
    req.resolve(true)
    req.gc()
  }

  _clearInflightBlock(tracker, req) {
    const isBlock = tracker === this._blocks
    const index = isBlock === true ? req.block.index : req.hash.index / 2
    const b = tracker.get(index)

    if (b === null || removeInflight(b.inflight, req) === false) return

    if (removeHotswap(b) === true && b.inflight.length > 0) {
      this.hotswaps.add(b)
    }

    if (b.refs.length > 0 && isBlock === true) {
      this._queueBlock(b)
      return
    }

    b.gc()
  }

  _clearInflightUpgrade(req) {
    if (this._upgrade === null || removeInflight(this._upgrade.inflight, req) === false) return
    this._upgrade.gc()
  }

  _clearInflightSeeks(req) {
    for (const s of this._seeks) {
      if (removeInflight(s.inflight, req) === false) continue
      s.gc()
    }
  }

  _clearInflightReorgs(req) {
    for (const r of this._reorgs) {
      removeInflight(r.inflight, req)
    }
  }

  _clearOldReorgs(fork) {
    for (let i = 0; i < this._reorgs.length; i++) {
      const f = this._reorgs[i]
      if (f.fork >= fork) continue
      if (i === this._reorgs.length - 1) this._reorgs.pop()
      else this._reorgs[i] = this._reorgs.pop()
      i--
    }
  }

  // "slow" updates here - async but not allowed to ever throw
  async _updateNonPrimary(updateAll) {
    // Check if running, if so skip it and the running one will issue another update for us (debounce)
    while (++this._updatesPending === 1) {
      let len = Math.min(MAX_RANGES, this._ranges.length)

      for (let i = 0; i < len; i++) {
        const r = this._ranges[i]

        clampRange(this.core, r)

        if (r.end !== -1 && r.start >= r.end) {
          this._resolveRangeRequest(r)
          i--
          if (len > this._ranges.length) len--
          if (this._ranges.length === MAX_RANGES) updateAll = true
        }
      }

      for (let i = 0; i < this._seeks.length; i++) {
        const s = this._seeks[i]

        let err = null
        let res = null

        try {
          res = await s.seeker.update()
        } catch (error) {
          err = error
        }

        if (!res && !err) continue

        if (i < this._seeks.length - 1) this._seeks[i] = this._seeks.pop()
        else this._seeks.pop()

        i--

        if (err) s.reject(err)
        else s.resolve(res)
      }

      // No additional updates scheduled - break
      if (--this._updatesPending === 0) break
      // Debounce the additional updates - continue
      this._updatesPending = 0
    }

    if (this._inflight.idle || updateAll) this.queueUpdateAll()
  }

  _clearRequest(peer, req) {
    if (req.block !== null) {
      this._clearInflightBlock(this._blocks, req)
      this._unmarkInflight(req.block.index)
    }

    if (req.hash !== null) {
      this._clearInflightBlock(this._hashes, req)
    }

    if (req.upgrade !== null && this._upgrade !== null) {
      this._clearInflightUpgrade(req)
    }

    if (this._seeks.length > 0) {
      this._clearInflightSeeks(req)
    }

    if (this._reorgs.length > 0) {
      this._clearInflightReorgs(req)
    }
  }

  _onnodata(peer, req, reason) {
    if (reason === NOT_AVAILABLE) {
      peer.stats.notAvailableBackoffs++
      this.stats.notAvailableBackoffs++

      if (peer.stats.notAvailableBackoffs >= MAX_BACKOFFS) {
        peer.paused = true
      }
    }

    if (reason === INVALID_REQUEST) {
      peer.stats.backoffs++
      this.stats.backoffs++

      if (peer.stats.backoffs >= MAX_BACKOFFS) {
        peer.paused = true
      }
    }

    if (req) {
      this._clearRequest(peer, req)
    }

    this.queueUpdateAll()
  }

  _openSkipBitfield() {
    // technically the skip bitfield gets bits cleared if .clear() is called
    // also which might be in inflight also, but that just results in that section being overcalled shortly
    // worst case, so ok for now

    const bitfield = this.core.openSkipBitfield()

    for (const req of this._inflight) {
      if (req.block) bitfield.set(req.block.index, true) // skip
    }
  }

  _markProcessing(index) {
    const b = this._blocks.get(index)
    if (b) {
      b.processing = true
      return
    }

    const h = this._hashes.get(index)
    if (h) h.processing = true
  }

  _markProcessed(index) {
    const b = this._blocks.get(index)
    if (b) return b.processed()

    const h = this._hashes.get(index)
    if (h) h.processed()
  }

  _markInflight(index) {
    if (this.core.skipBitfield !== null) this.core.skipBitfield.set(index, true)
    for (const peer of this.peers) peer._markInflight(index)
  }

  _unmarkInflight(index) {
    if (this.core.skipBitfield !== null) {
      this.core.skipBitfield.set(index, this.core.bitfield.get(index))
    }
    for (const peer of this.peers) peer._resetMissingBlock(index)
  }

  _ondata(peer, req, data) {
    if (req) {
      req.elapsed = Date.now() - req.timestamp
    }

    if (data.block !== null) {
      this._resolveBlockRequest(this._blocks, data.block.index, data.block.value, req)
      this._ondownload(data.block.index, data.block.value.byteLength, peer, req)
    }

    if (data.hash !== null && (data.hash.index & 1) === 0) {
      this._resolveBlockRequest(this._hashes, data.hash.index / 2, null, req)
    }

    if (this._upgrade !== null) {
      this._resolveUpgradeRequest(req)
    }

    if (this._seeks.length > 0) {
      this._clearInflightSeeks(req)
    }

    if (this._reorgs.length > 0) {
      this._clearInflightReorgs(req)
    }

    if (this._manifestPeer === peer && this.core.header.manifest !== null) {
      this._manifestPeer = null
    }

    if (this._seeks.length > 0 || this._ranges.length > 0) {
      this._updateNonPrimary(this._seeks.length > 0)
    }

    this.updatePeer(peer)
  }

  _onwant(peer, start, length, any) {
    if (!peer.isActive()) return

    const contig = Math.min(this.core.state.length, this.core.header.hints.contiguousLength)

    if (start + length < contig || this.core.state.length === contig || (any && start < contig)) {
      peer.wireRange.send({
        drop: false,
        start: 0,
        length: contig
      })
      incrementTx(peer.stats.wireRange, this.stats.wireRange)
      return
    }

    length = Math.min(length, this.core.state.length - start)

    if (any) {
      const bit = this.core.bitfield.firstSet(start)
      if (bit > -1 && bit < start + length) {
        peer.wireRange.send({
          drop: false,
          start: bit,
          length: 1
        })
      }
      return
    }

    for (const msg of this.core.bitfield.want(start, length)) {
      peer.wireBitfield.send(msg)
      incrementTx(peer.stats.wireBitfield, this.stats.wireBitfield)
    }
  }

  async _onreorgdata(peer, req, data) {
    const newBatch = data.upgrade && (await this.core.verifyReorg(data))
    const f = this._addReorg(data.fork, peer)

    if (f === null) {
      this.queueUpdateAll()
      return
    }

    removeInflight(f.inflight, req)

    if (f.batch) {
      await f.batch.update(data)
    } else if (data.upgrade) {
      f.batch = newBatch

      // Remove "older" reorgs in progress as we just verified this one.
      this._clearOldReorgs(f.fork)
    }

    if (f.batch && f.batch.finished) {
      if (this._addUpgradeMaybe() !== null) {
        await this._applyReorg(f)
      }
    }

    this.queueUpdateAll()
  }

  // Never throws, allowed to run in the background
  async _applyReorg(f) {
    // TODO: more optimal here to check if potentially a better reorg
    // is available, ie higher fork, and request that one first.
    // This will request that one after this finishes, which is fine, but we
    // should investigate the complexity in going the other way

    const u = this._upgrade
    const old = this._reorgs

    this._reorgs = [] // clear all as the nodes are against the old tree - easier
    this._applyingReorg = this.core.reorg(f.batch, null) // TODO: null should be the first/last peer?

    try {
      await this._applyingReorg
    } catch (err) {
      this._upgrade = null
      u.reject(err)
    }

    this._applyingReorg = null

    if (this._upgrade !== null) {
      this._resolveUpgradeRequest(null)
    }

    for (const peer of this.peers) this._updateFork(peer)

    // TODO: all the remaining is a tmp workaround until we have a flag/way for ANY_FORK
    for (const r of this._ranges) {
      r.start = r.userStart
      r.end = r.userEnd
    }

    for (const f of old) f.resolve()
    f.resolve()

    this.queueUpdateAll()
  }

  _maybeUpdate() {
    return this._upgrade !== null && this._upgrade.inflight.length === 0
  }

  _maybeRequestManifest() {
    return this.core.header.manifest === null && this._manifestPeer === null
  }

  _updateFork(peer) {
    if (
      this._applyingReorg !== null ||
      this.allowFork === false ||
      peer.remoteFork <= this.core.state.fork
    ) {
      return false
    }

    const f = this._addReorg(peer.remoteFork, peer)

    // TODO: one per peer is better
    if (f !== null && f.batch === null && f.inflight.length === 0) {
      return peer._requestForkProof(f)
    }

    return false
  }

  _updateHotswap(peer) {
    const maxHotswaps = peer.getMaxHotswapInflight()
    if (!peer.isActive() || peer.inflight >= maxHotswaps) return

    for (const b of this.hotswaps.pick(peer)) {
      if (peer._requestBlock(b) === false) continue
      peer.stats.hotswaps++
      peer.replicator.stats.hotswaps++
      if (peer.inflight >= maxHotswaps) break
    }
  }

  _updatePeer(peer) {
    if (!peer.isActive() || peer.inflight >= peer.getMaxInflight() || !peer.remoteUploading) {
      return false
    }

    // Eagerly request the manifest even if the remote length is 0. If not 0 we'll get as part of the upgrade request...
    if (
      this._maybeRequestManifest() === true &&
      peer.remoteLength === 0 &&
      peer.remoteHasManifest === true
    ) {
      this._manifestPeer = peer
      peer._requestManifest()
    }

    for (const s of this._seeks) {
      if (s.inflight.length > 0) continue // TODO: one per peer is better
      if (peer._requestSeek(s) === true) {
        return true
      }
    }

    // Implied that any block in the queue should be requested, no matter how many inflights
    const blks = new RandomIterator(this._queued)

    for (const b of blks) {
      if (b.queued === false || peer._requestBlock(b) === true) {
        b.queued = false
        blks.dequeue()
        return true
      }
    }

    return false
  }

  _updatePeerNonPrimary(peer) {
    if (!peer.isActive() || peer.inflight >= peer.getMaxInflight() || !peer.remoteUploading) {
      return false
    }

    const ranges = new RandomIterator(this._ranges)
    let tried = 0

    for (const r of ranges) {
      if (peer._requestRange(r) === true) {
        return true
      }
      if (++tried >= MAX_RANGES) break
    }

    // Iterate from newest fork to oldest fork...
    for (let i = this._reorgs.length - 1; i >= 0; i--) {
      const f = this._reorgs[i]
      if (f.batch !== null && f.inflight.length === 0 && peer._requestForkRange(f) === true) {
        return true
      }
    }

    if (this._maybeUpdate() === true && peer._requestUpgrade(this._upgrade) === true) {
      return true
    }

    return false
  }

  updatePeer(peer) {
    // Quick shortcut to wait for flushing reorgs - not needed but less waisted requests
    if (this._applyingReorg !== null) return

    while (this._updatePeer(peer) === true);
    while (this._updatePeerNonPrimary(peer) === true);

    if (this.peers.length > 1 && this._blocks.isEmpty() === false) {
      this._updateHotswap(peer)
    }

    this._checkUpgradeIfAvailable()
  }

  updateSubset() {
    return this.updateAll(false)
  }

  updateAll(all = true) {
    // Clear queued scan if a full scan
    if (this._updateAllBump !== null && all) {
      clearTimeout(this._updateAllBump)
      this._updateAllBump = null
    }

    // Quick shortcut to wait for flushing reorgs - not needed but less waisted requests
    if (this._applyingReorg !== null) return

    const peers = new RandomIterator(this.peers)

    const limit = all ? peers.length : MIN_PEER_UPDATE_ALL
    let tried = 0
    for (const peer of peers) {
      tried++
      if (this._updatePeer(peer) === true) {
        peers.requeue()
      }
      if (tried >= limit) break
    }

    // Check if we can skip the non primary check fully
    if (this._maybeUpdate() === false && this._ranges.length === 0 && this._reorgs.length === 0) {
      this._checkUpgradeIfAvailable()
      return
    }

    tried = 0
    for (const peer of peers.restart()) {
      tried++
      if (this._updatePeerNonPrimary(peer) === true) {
        peers.requeue()
      }
      if (tried >= limit) break
    }

    this._checkUpgradeIfAvailable()
  }

  getUpdateAllDelay(peers) {
    return Math.min(3000, Math.max(100, (peers.length - MIN_PEER_UPDATE_ALL) * 5))
  }

  queueUpdateAll() {
    if (this.peers.length < MIN_PEER_UPDATE_ALL) return this.updateAll()

    // Immediately scan subset
    this.updateSubset()

    // Schedule full scan
    if (this._updateAllBump !== null) return //skip if already scheduled
    this._updateAllBump = setTimeout(this._updateAllBound, this.getUpdateAllDelay(this.peers))
  }

  onpeerdestroy() {
    if (--this._active === 0) this.core.checkIfIdle()
  }

  attached(protomux) {
    return this._attached.has(protomux)
  }

  attachTo(protomux) {
    if (this.core.closed) return

    const makePeer = this._makePeer.bind(this, protomux)

    this._attached.add(protomux)
    protomux.pair({ protocol: 'hypercore/alpha', id: this.core.discoveryKey }, makePeer)
    protomux.stream.setMaxListeners(0)
    protomux.stream.on('close', this._onstreamclose)

    this._ifAvailable++
    this._active++

    protomux.stream.opened.then((opened) => {
      this._ifAvailable--
      this._active--

      if (opened && !this.destroyed) makePeer()
      this._checkUpgradeIfAvailable()

      this.core.checkIfIdle()
    })
  }

  detachFrom(protomux) {
    if (this._attached.delete(protomux)) {
      protomux.stream.removeListener('close', this._onstreamclose)
      protomux.unpair({ protocol: 'hypercore/alpha', id: this.core.discoveryKey })
    }
  }

  idle() {
    return this.peers.length === 0 && this._active === 0
  }

  close() {
    const waiting = []

    for (const peer of this.peers) {
      waiting.push(peer.channel.fullyClosed())
    }

    this.destroy()
    return Promise.all(waiting)
  }

  destroy() {
    if (this.destroyed) return
    this.destroyed = true

    if (this._notDownloadingTimer) {
      clearTimeout(this._notDownloadingTimer)
      this._notDownloadingTimer = null
    }

    if (this._updateAllBump) {
      clearTimeout(this._updateAllBump)
      this._updateAllBump = null
    }

    while (this.peers.length) {
      const peer = this.peers[this.peers.length - 1]
      this.detachFrom(peer.protomux)
      peer.channel.close() // peer is removed from array in onclose
    }

    for (const protomux of this._attached) {
      this.detachFrom(protomux)
    }
  }

  _makePeer(protomux) {
    const replicator = this
    if (protomux.opened({ protocol: 'hypercore/alpha', id: this.core.discoveryKey })) {
      return onnochannel()
    }

    const channel = protomux.createChannel({
      userData: null,
      protocol: 'hypercore/alpha',
      aliases: ['hypercore'],
      id: this.core.discoveryKey,
      handshake: m.wire.handshake,
      messages: [
        { encoding: m.wire.sync, onmessage: onwiresync },
        { encoding: m.wire.request, onmessage: onwirerequest },
        { encoding: m.wire.cancel, onmessage: onwirecancel },
        { encoding: m.wire.data, onmessage: onwiredata },
        { encoding: m.wire.noData, onmessage: onwirenodata },
        { encoding: m.wire.want, onmessage: onwirewant },
        { encoding: m.wire.unwant, onmessage: onwireunwant },
        { encoding: m.wire.bitfield, onmessage: onwirebitfield },
        { encoding: m.wire.range, onmessage: onwirerange },
        { encoding: m.wire.extension, onmessage: onwireextension }
      ],
      onopen: onwireopen,
      onclose: onwireclose,
      ondrain: onwiredrain,
      ondestroy: onwiredestroy
    })

    if (channel === null) return onnochannel()

    const peer = new Peer(replicator, protomux, channel, this.inflightRange)
    const stream = protomux.stream

    peer.channel.open({
      seeks: true,
      capability: caps.replicate(stream.isInitiator, this.core.key, stream.handshakeHash)
    })

    return true

    function onnochannel() {
      return false
    }
  }

  _onpeerupdate(added, peer) {
    const name = added ? 'peer-add' : 'peer-remove'
    const sessions = this.core.monitors

    for (let i = sessions.length - 1; i >= 0; i--) {
      sessions[i].emit(name, peer)

      if (added) {
        for (const ext of sessions[i].extensions.values()) {
          peer.extensions.set(ext.name, ext)
        }
      }
    }
  }

  _ondownload(index, byteLength, from, req) {
    const sessions = this.core.monitors

    for (let i = sessions.length - 1; i >= 0; i--) {
      const s = sessions[i]
      s.emit('download', index, byteLength - s.padding, from, req)
    }
  }

  _onupload(index, byteLength, from) {
    const sessions = this.core.monitors

    for (let i = sessions.length - 1; i >= 0; i--) {
      const s = sessions[i]
      s.emit('upload', index, byteLength - s.padding, from)
    }
  }

  _oninvaliddata(err, req, res, from) {
    const sessions = this.core.monitors

    this.stats.invalidData++
    from.stats.invalidData++
    for (let i = 0; i < sessions.length; i++) {
      sessions[i].emit('verification-error', err, req, res, from)
    }
  }

  _oninvalidrequest(err, req, from) {
    const sessions = this.core.monitors

    from.stats.invalidRequests++
    this.stats.invalidRequests++
    for (let i = 0; i < sessions.length; i++) {
      sessions[i].emit('invalid-request', err, req, from)
    }
  }
}

function removeHotswap(block) {
  if (block.hotswap === null) return false
  block.hotswap.ref.remove(block)
  return true
}

function removeInflight(inf, req) {
  const i = inf.indexOf(req)
  if (i === -1) return false
  if (i < inf.length - 1) inf[i] = inf.pop()
  else inf.pop()
  return true
}

function toLength(start, end) {
  return end === -1 ? -1 : end < start ? 0 : end - start
}

function clampRange(core, r) {
  if (r.blocks === null) {
    const start = core.bitfield.firstUnset(r.start)

    if (r.end === -1) r.start = start === -1 ? core.state.length : start
    else if (start === -1 || start >= r.end) r.start = r.end
    else {
      r.start = start

      const end = core.bitfield.lastUnset(r.end - 1)

      if (end === -1 || start >= end + 1) r.end = r.start
      else r.end = end + 1
    }
  } else {
    while (r.start < r.end && core.bitfield.get(r.blocks[r.start])) r.start++
    while (r.start < r.end && core.bitfield.get(r.blocks[r.end - 1])) r.end--
  }
}

function onrequesttimeout(req) {
  if (req.context) req.context.detach(req, REQUEST_TIMEOUT())
}

function destroyRequestTimeout(req) {
  if (req.timeout !== null) {
    clearTimeout(req.timeout)
    req.timeout = null
  }
}

function isCriticalError(err) {
  // TODO: expose .critical or similar on the hypercore errors that are critical (if all not are)
  return err.name === 'HypercoreError'
}

function onwireopen(m, c) {
  return c.userData.onopen(m)
}

function onwireclose(isRemote, c) {
  return c.userData.onclose(isRemote)
}

function onwiredestroy(c) {
  c.userData.replicator.onpeerdestroy()
}

function onwiredrain(c) {
  return c.userData.ondrain()
}

function onwiresync(m, c) {
  incrementRx(c.userData.stats.wireSync, c.userData.replicator.stats.wireSync)
  return c.userData.onsync(m)
}

function onwirerequest(m, c) {
  incrementRx(c.userData.stats.wireRequest, c.userData.replicator.stats.wireRequest)
  return c.userData.onrequest(m)
}

function onwirecancel(m, c) {
  incrementRx(c.userData.stats.wireCancel, c.userData.replicator.stats.wireCancel)
  return c.userData.oncancel(m)
}

function onwiredata(m, c) {
  incrementRx(c.userData.stats.wireData, c.userData.replicator.stats.wireData)
  return c.userData.ondata(m)
}

function onwirenodata(m, c) {
  return c.userData.onnodata(m)
}

function onwirewant(m, c) {
  incrementRx(c.userData.stats.wireWant, c.userData.replicator.stats.wireWant)
  return c.userData.onwant(m)
}

function onwireunwant(m, c) {
  return c.userData.onunwant(m)
}

function onwirebitfield(m, c) {
  incrementRx(c.userData.stats.wireBitfield, c.userData.replicator.stats.wireBitfield)
  return c.userData.onbitfield(m)
}

function onwirerange(m, c) {
  incrementRx(c.userData.stats.wireRange, c.userData.replicator.stats.wireRange)
  return c.userData.onrange(m)
}

function onwireextension(m, c) {
  incrementRx(c.userData.stats.wireExtension, c.userData.replicator.stats.wireExtension)
  return c.userData.onextension(m)
}

function setNotDownloadingLater(repl, session) {
  repl._setDownloadingNow(false, session)
}

function isBlockRequest(req) {
  return req !== null && req.block !== null
}

function isUpgradeRequest(req) {
  return req !== null && req.upgrade !== null
}

function incrementTx(stats1, stats2) {
  stats1.tx++
  stats2.tx++
}

function incrementRx(stats1, stats2) {
  stats1.rx++
  stats2.rx++
}

function noop() {}

function backoff(times) {
  const sleep = times < 2 ? 200 : times < 5 ? 500 : times < 40 ? 1000 : 5000
  return new Promise((resolve) => setTimeout(resolve, sleep))
}
const crypto = require('hypercore-crypto')
const b4a = require('b4a')
const assert = require('nanoassert')
const flat = require('flat-tree')
const quickbit = require('quickbit-universal')
const HypercoreStorage = require('hypercore-storage')

const {
  INVALID_OPERATION,
  INVALID_SIGNATURE,
  ASSERTION,
  SESSION_CLOSED,
  SESSION_NOT_WRITABLE
} = require('hypercore-errors')

const Mutex = require('./mutex')
const Bitfield = require('./bitfield')
const { MerkleTree, MerkleTreeBatch } = require('./merkle-tree')

class SessionState {
  constructor(core, parent, storage, treeInfo, name) {
    this.core = core
    this.index = this.core.sessionStates.push(this) - 1

    this.storage = storage
    this.name = name
    this.sessions = []

    // small hack to close old storages as late as possible.
    // TODO: add a read lock so we can avoid that
    this.lingers = null

    this.parent = parent
    this.atomized = null
    this.mutex = new Mutex()

    // merkle state
    this.roots = treeInfo.roots.length ? treeInfo.roots : []
    this.fork = treeInfo.fork || 0
    this.length = this.roots.length ? MerkleTree.span(this.roots) / 2 : treeInfo.length
    this.byteLength = MerkleTree.size(this.roots)
    this.prologue = treeInfo.prologue || null
    this.signature = treeInfo.signature || null

    this.snapshotCompatLength = this.isSnapshot()
      ? Math.min(this.length, this.core.state.length)
      : -1
    this.lastTruncation = null
    this.groupUpdated = false

    this.active = 0

    this._activeTx = null
    this._pendingBitfield = null

    this.ref()
  }

  static RECOVERY_PEERS = null

  isSnapshot() {
    return this.storage.snapshotted
  }

  isDefault() {
    return this.core.state === this || this.isAtomicDefault()
  }

  isAtomicDefault() {
    return !!this.storage.atom && !!this.parent && this.parent.isDefault()
  }

  createTreeBatch() {
    return new MerkleTreeBatch(this)
  }

  addSession(s) {
    if (s._stateIndex !== -1) return
    s._stateIndex = this.sessions.push(s) - 1
    if (s.weak === false) this.core.activeSessions++
  }

  removeSession(s) {
    if (s._stateIndex === -1) return
    const head = this.sessions.pop()
    if (head !== s) this.sessions[(head._stateIndex = s._stateIndex)] = head
    s._stateIndex = -1
    if (s.weak === false) this.core.activeSessions--
    this.core.checkIfIdle()
  }

  flushedLength() {
    if (this.isDefault() || this.isSnapshot()) return this.length
    const deps = this.storage.dependencies
    if (deps.length) return deps[deps.length - 1].length
    return 0
  }

  signedLength() {
    const l = Math.min(this.flushedLength(), this.core.state.length)
    return this.isSnapshot() && l > this.snapshotCompatLength ? this.snapshotCompatLength : l
  }

  unref() {
    if (--this.active > 0) return
    this.close().catch(noop) // technically async, but only for the last db session
  }

  ref() {
    this.active++
    return this
  }

  hash() {
    return MerkleTree.hash(this)
  }

  setRoots(roots) {
    this.roots = roots
    this.length = MerkleTree.span(roots) / 2
    this.byteLength = MerkleTree.size(roots)
  }

  get encryptionFork() {
    return this.core.header.tree.fork
  }

  async _updateSnapshotStorage(storage) {
    if (!this.atomized || !this.atomized.flushing) return this.treeInfo()
    while (this.atomized.flushing) await this.atomized.flushed()

    let rx = storage.read()
    const headPromise = rx.getHead()
    const authPromise = rx.getAuth()
    const depPromise = rx.getDependency()

    rx.tryFlush()
    const [head, auth, dep] = await Promise.all([headPromise, authPromise, depPromise])

    storage.setDependencyHead(dep)

    const fork = head ? head.fork : 0
    const length = head ? head.length : 0

    rx = storage.read()
    const rootPromises = []
    for (const r of flat.fullRoots(length * 2)) {
      rootPromises.push(rx.getTreeNode(r))
    }

    rx.tryFlush()

    const roots = await Promise.all(rootPromises)

    // dbl check if we are hitting an regression from earler
    for (const root of roots) {
      if (root === null) {
        throw new Error(
          'Bad snapshot from atomized session, id = ' +
            this.core.id +
            ' length = ' +
            length +
            ' fork = ' +
            fork
        )
      }
    }

    return {
      fork,
      roots,
      length,
      prologue: auth.manifest && auth.manifest.prologue,
      signature: head && head.signature
    }
  }

  treeInfo() {
    return {
      fork: this.fork,
      roots: this.roots.slice(),
      length: this.length,
      prologue: this.prologue,
      signature: this.signature
    }
  }

  async close() {
    if (this.index === -1) return

    this.active = 0
    this.mutex.destroy(new Error('Closed')).catch(noop)
    if (this.parent && this.parent.atomized) this.parent.atomized = null

    const closing = this.storage.close()

    const head = this.core.sessionStates.pop()
    if (head !== this) this.core.sessionStates[(head.index = this.index)] = head

    this.index = -1
    this.core.checkIfIdle()

    if (this.lingers !== null) {
      for (const storage of this.lingers) await storage.close()
    }

    return closing
  }

  async snapshot() {
    const storage = this.storage.snapshot()
    const treeInfo = await this._updateSnapshotStorage(storage)

    return new SessionState(this.core, null, storage, treeInfo, this.name)
  }

  updateDependency(tx, length) {
    const dependency = updateDependency(this, length, false)
    if (dependency) tx.setDependency(dependency)
    return dependency
  }

  updateGroupIndex(tx, tree) {
    const { pointer } = this.core.header.group

    tx.deleteGroupUpdate(pointer, this.core.header.tree.timestamp)
    tx.putGroupUpdate(pointer, tree.timestamp, this.core.header.key)

    this.groupUpdated = true
  }

  _clearActiveBatch() {
    this._activeTx = null
  }

  createWriteBatch() {
    assert(!this._activeTx && !this.storage.snapshotted)

    this._activeTx = this.storage.write()
    return this._activeTx
  }

  _unlock() {
    this._clearActiveBatch()
    this.mutex.unlock()
    this.core.checkIfIdle()
  }

  _flushHooks() {
    if (!this.groupUpdated) return
    this.groupUpdated = false
    this.core.ongroupupdate(this.core.header.group.key, {
      key: this.core.key,
      length: this.length,
      fork: this.fork
    })
  }

  async flush() {
    const tx = this._activeTx
    this._activeTx = null

    try {
      if (!(await tx.flush())) return false
    } finally {
      this._clearActiveBatch()
    }

    this.lastTruncation = null
    return true
  }

  _precommit(state) {
    assert(
      state.parent === this && state.storage.core.dataPointer === this.storage.core.dataPointer,
      'Atomic state must flush to parent'
    )
  }

  async _commit() {
    await this.mutex.lock()

    try {
      const bitfield = this._pendingBitfield
      this._pendingBitfield = null
      this.lastTruncation = null
      await this.parent._oncommit(this, bitfield)
    } finally {
      this.mutex.unlock()
    }
  }

  async _oncommit(src, bitfield) {
    await this.mutex.lock()

    try {
      const currLength = this.length

      // load dependency into memory
      const rx = this.storage.read()
      const dependencyPromise = rx.getDependency()

      rx.tryFlush()

      const dependency = await dependencyPromise

      this.fork = src.fork
      this.length = src.length
      this.byteLength = src.byteLength
      this.roots = src.roots.slice()
      this.signature = src.signature

      const tree = {
        fork: this.fork,
        length: this.length,
        rootHash: this.hash(),
        signature: this.signature,
        timestamp: Date.now()
      }

      if (this.isDefault() && this.core.header.group) {
        const tx = this.createWriteBatch()
        this.updateGroupIndex(tx, tree)
        await this.flush()
        this._flushHooks()
      }

      if (dependency) this.storage.setDependencyHead(dependency)

      const b = bitfield

      if (b && b.truncated && b.start < currLength) {
        this.ontruncate(tree, b.start, currLength, true)
        if (!b || b.appends === 0) return
      }

      const append = b ? { start: b.start, length: b.appends, drop: false } : null

      this.onappend(tree, append, true)

      if (this.core.hintsChanged && this.isDefault()) await this.core.flushHints()
    } finally {
      this._unlock()
    }
  }

  async setUserData(key, value) {
    await this.mutex.lock()

    try {
      const tx = this.createWriteBatch()
      tx.putUserData(key, value)

      return await this.flush()
    } finally {
      this._unlock()
    }
  }

  async _verifyBlock(batch, bitfield, value, manifest, from) {
    await this.mutex.lock()

    try {
      if (batch.upgraded && batch.length <= this.length) {
        await batch.downgrade()
      }

      if (!batch.commitable()) {
        return false
      }

      if (this.core.preupdate !== null) {
        await this.core.preupdate(batch, this.core.header.key)
      }

      const tx = this.createWriteBatch()

      if (bitfield) {
        tx.putBlock(bitfield.start, value)
      }

      if (bitfield && this.isDefault()) {
        await storeBitfieldRange(this.storage, tx, bitfield.start, bitfield.start + 1, true)
      }

      if (manifest) this.core._setManifest(tx, manifest, null)

      assert(batch.commitable(), 'Should still be commitable')
      batch.commit(tx)

      const head = {
        fork: batch.fork,
        length: batch.length,
        rootHash: batch.hash(),
        signature: batch.signature,
        timestamp: Date.now()
      }

      if (batch.upgraded) {
        tx.setHead(head)

        if (this.core.header.group) {
          this.updateGroupIndex(tx, head)
        }
      }

      const flushed = await this.flush()

      if (batch.upgraded) {
        this.roots = batch.roots
        this.length = batch.length
        this.byteLength = batch.byteLength
        this.fork = batch.fork
        this.signature = batch.signature

        this.onappend(head, bitfield, flushed)
      }

      if (this.core.hintsChanged && this.isDefault()) await this.core.flushHints()
    } finally {
      this._unlock()
    }

    return true
  }

  async truncate(length, fork, { signature, keyPair } = {}) {
    if (!keyPair && this.isDefault()) keyPair = this.core.header.keyPair

    await this.mutex.lock()

    try {
      if (this.prologue && length < this.prologue.length) {
        throw INVALID_OPERATION('Truncation breaks prologue', this.core.discoveryKey)
      }
      if (length > this.length) {
        throw INVALID_OPERATION(
          'Not a truncation, ' + length + ' must be less or equal to ' + this.length,
          this.core.discoveryKey
        )
      }

      const batch = this.createTreeBatch()
      await MerkleTree.truncate(this, length, batch, fork)

      if (signature) {
        batch.signature = signature
        this.core._verifyBatchUpgrade(batch)
      } else if (keyPair) {
        batch.signature = this.core.verifier.sign(batch, keyPair)
      }

      const tx = this.createWriteBatch()

      // upsert compat manifest
      if (this.core.verifier === null && keyPair) this.core._setManifest(tx, null, keyPair)

      const { dependency, tree, roots } = await this._truncate(tx, batch)

      for (const sessionState of this.core.sessionStates) {
        if (
          sessionState.isSnapshot() &&
          sessionState.name === this.name &&
          length < sessionState.snapshotCompatLength
        ) {
          sessionState.snapshotCompatLength = length
        }
      }

      const flushed = await this.flush()

      this.fork = tree.fork
      this.length = tree.length
      this.byteLength = MerkleTree.size(roots)
      this.roots = roots
      this.signature = tree.signature

      if (dependency) this.storage.setDependencyHead(dependency)

      this.ontruncate(tree, tree.length, batch.treeLength, flushed)

      if (this.core.hintsChanged && this.isDefault()) await this.core.flushHints()
    } finally {
      this._unlock()
    }
  }

  async reorg(batch) {
    await this.mutex.lock()

    const storage = this.createWriteBatch()

    try {
      if (!batch.commitable()) return false

      const { dependency, tree } = await this._truncate(storage, batch)

      const flushed = await this.flush()

      this.fork = batch.fork
      this.length = batch.length
      this.byteLength = batch.byteLength
      this.roots = batch.roots
      this.signature = batch.signature

      if (dependency) this.storage.setDependencyHead(dependency)

      this.ontruncate(tree, batch.ancestors, batch.treeLength, flushed)

      if (this.core.hintsChanged && this.isDefault()) await this.core.flushHints()
    } finally {
      this._unlock()
    }
  }

  async _truncate(storage, batch) {
    storage.deleteBlockRange(batch.ancestors, batch.treeLength)

    assert(batch.commitable(), 'Batch must be commitable')

    const tree = {
      fork: batch.fork,
      length: batch.length,
      rootHash: batch.hash(),
      signature: batch.signature,
      timestamp: Date.now()
    }

    if (this.isDefault() && this.core.header.group) {
      this.updateGroupIndex(storage, tree)
    }

    storage.setHead(tree)
    batch.commit(storage)

    const truncated = batch.length < this.flushedLength()
    const dependency = truncated ? updateDependency(this, batch.length, true) : null

    if (dependency) storage.setDependency(dependency)

    if (this.isDefault()) {
      await storeBitfieldRange(this.storage, storage, batch.ancestors, batch.treeLength, false)
      if (batch.ancestors < this.core.header.hints.contiguousLength) {
        this.core.header.hints.remoteContiguousLength = Math.min(
          batch.length,
          this.core.header.hints.remoteContiguousLength
        )
        storage.setHints({
          contiguousLength: batch.ancestors,
          remoteContiguousLength: this.core.header.hints.remoteContiguousLength
        })
      }
    }

    return { dependency, tree, roots: batch.roots }
  }

  async clear(start, end, cleared) {
    await this.mutex.lock()

    try {
      const tx = this.createWriteBatch()

      const ite = flat.iterator(start * 2)
      while (!isRootIndex(ite.index, this.roots)) {
        const a = ite.index
        const b = ite.sibling()
        ite.parent()

        const [left, right] = flat.spans(b)
        const s = left / 2
        const e = right / 2 + 1
        const has = s <= start && e <= end ? false : this.core.bitfield.hasSet(s, e - s)
        if (has) break

        tx.deleteTreeNode(a)
        tx.deleteTreeNode(b)
      }

      if (this.isDefault()) {
        await storeBitfieldRange(this.storage, tx, start, end, false)
        if (start < this.core.header.hints.contiguousLength) {
          tx.setHints({
            contiguousLength: start,
            remoteContiguousLength: this.core.header.hints.remoteContiguousLength
          })
        }
      }

      if (end - start === 1) tx.deleteBlock(start)
      else tx.deleteBlockRange(start, end)

      const dependency = start < this.flushedLength() ? updateDependency(this, start, true) : null

      const flushed = await this.flush()

      if (dependency) this.storage.setDependencyHead(dependency)

      // todo: atomic event handle
      if (this.isDefault() && flushed) {
        const length = end - start

        this.core.updateContiguousLength({ start, length, drop: true })
        this.core._setBitfieldRanges(start, end, false)
        this.core.replicator.onhave(start, length, true)

        if (this.core.hintsChanged) await this.core.flushHints()
      }
    } finally {
      this._unlock()
    }
  }

  // simple tool to wait for other peers to catch us up
  async waitForRecovery() {
    const length = this.length
    const replicator = this.core.replicator

    while (!this.closing) {
      let peers = getRecoveryPeers(replicator.peers)

      if (peers.length < 1) {
        await new Promise((resolve) => setTimeout(resolve, 5000))
        continue
      }

      let restart = false

      for (let i = 0; i < 32; i++) {
        await new Promise((resolve) => setTimeout(resolve, 250))

        peers = getRecoveryPeers(replicator.peers)

        if (this.closing || !validateRecoveryPeers(peers, this.length)) {
          restart = true
          break
        }
      }

      if (restart) continue

      if (this.length !== length) {
        throw SESSION_NOT_WRITABLE('core recovered during append')
      }

      this.core.header.hints.recovering = 0
      this.core.hintsChanged = true

      await this.mutex.lock()
      try {
        await this.core.flushHints()
        return
      } finally {
        this.mutex.unlock()
      }
    }

    throw SESSION_CLOSED('Cannot recover a closed session', this.discoveryKey)
  }

  async append(values, { signature, keyPair, preappend, postappend, maxLength = -1 } = {}) {
    if (!keyPair && this.isDefault()) keyPair = this.core.header.keyPair

    if (this.isDefault() && this.core.header.hints.recovering) await this.waitForRecovery()

    await this.mutex.lock()

    try {
      if (maxLength >= 0 && this.length + values.length > maxLength) {
        return { length: this.length, byteLength: this.byteLength }
      }

      const tx = this.createWriteBatch()

      // upsert compat manifest
      if (this.core.verifier === null && keyPair) this.core._setManifest(tx, null, keyPair)

      if (preappend) await preappend(values)

      if (!values.length) {
        await this.flush()
        return { length: this.length, byteLength: this.byteLength }
      }

      const batch = this.createTreeBatch()
      for (const val of values) batch.append(val)

      // only multisig can have prologue so signature is always present
      if (this.prologue && batch.length < this.prologue.length) {
        throw INVALID_OPERATION('Append is not consistent with prologue', this.core.discoveryKey)
      }

      if (signature) {
        batch.signature = signature
        this.core._verifyBatchUpgrade(batch)
      } else if (keyPair) {
        batch.signature = this.core.verifier.sign(batch, keyPair)
      }

      batch.commit(tx)

      const tree = {
        fork: batch.fork,
        length: batch.length,
        rootHash: batch.hash(),
        signature: batch.signature,
        timestamp: Date.now()
      }

      tx.setHead(tree)

      if (this.isDefault()) {
        await storeBitfieldRange(this.storage, tx, batch.ancestors, batch.length, true)
        if (this.length === this.core.header.hints.contiguousLength) {
          tx.setHints({
            contiguousLength: this.length + values.length,
            remoteContiguousLength: this.core.header.hints.remoteContiguousLength
          })
        }

        if (this.core.header.group) {
          this.updateGroupIndex(tx, tree)
        }
      }

      for (let i = 0; i < values.length; i++) {
        tx.putBlock(this.length + i, values[i])
      }

      const bitfield = {
        drop: false,
        start: batch.ancestors,
        length: values.length
      }

      const flushed = await this.flush()

      this.fork = batch.fork
      this.roots = batch.roots
      this.length = batch.length
      this.byteLength = batch.byteLength
      this.signature = batch.signature

      if (postappend) await postappend(values)

      this.onappend(tree, bitfield, flushed)

      if (this.core.hintsChanged && this.isDefault()) await this.core.flushHints()

      return { length: this.length, byteLength: this.byteLength }
    } finally {
      this._unlock()
    }
  }

  onappend(tree, bitfield, flushed) {
    if (!flushed) this._updateBitfield(bitfield)
    else if (this.isDefault()) this.core.onappend(tree, bitfield)

    for (let i = this.sessions.length - 1; i >= 0; i--) {
      this.sessions[i].emit('append')
    }

    this._flushHooks()
  }

  ontruncate(tree, to, from, flushed) {
    const bitfield = { start: to, length: from - to, drop: true }

    this.lastTruncation = { from, to }

    if (!flushed) this._updateBitfield(bitfield)
    else if (this.isDefault()) this.core.ontruncate(tree, bitfield)

    for (const sessionState of this.core.sessionStates) {
      if (
        sessionState.isSnapshot() &&
        sessionState.name === this.name &&
        to < sessionState.snapshotCompatLength
      ) {
        sessionState.snapshotCompatLength = to
      }
    }

    for (let i = this.sessions.length - 1; i >= 0; i--) {
      this.sessions[i].emit('truncate', to, tree.fork)
    }

    this._flushHooks()
  }

  _updateBitfield(bitfield, flushed) {
    if (!bitfield) return

    const p = this._pendingBitfield
    const b = bitfield

    if (b.drop) {
      // truncation must be from end
      if (p && b.start + b.length !== p.start + p.appends) {
        throw INVALID_OPERATION('Atomic truncations must be contiguous', this.core.discoveryKey)
      }

      // actual truncation
      if (p === null || b.start < p.start) {
        this._pendingBitfield = { truncated: true, start: b.start, appends: 0 }
        return
      }

      // just clearing batch data
      p.appends = b.start - p.start

      // we cleared the current batch
      if (p.appends === 0) this._pendingBitfield = null

      return
    }

    if (p === null) {
      this._pendingBitfield = { truncated: false, start: b.start, appends: b.length }
      return
    }

    if (b.start !== p.start + p.appends) {
      throw INVALID_OPERATION('Atomic operations must be contiguous', this.core.discoveryKey)
    }

    p.appends += b.length
  }

  async catchup(length) {
    assert(!this.isDefault(), 'Cannot catchup signed state') // TODO: make this check better

    await this.mutex.lock()

    try {
      const origLength = this.length

      let sharedLength = 0
      for (let i = this.storage.dependencies.length - 1; i >= 0; i--) {
        const dep = this.storage.dependencies[i]
        if (dep.dataPointer === this.core.state.storage.core.dataPointer) {
          sharedLength = dep.length
          break
        }
      }

      const tx = this.createWriteBatch()
      const rx = this.core.state.storage.read()
      const rootPromises = []

      for (const root of flat.fullRoots(length * 2)) {
        rootPromises.push(rx.getTreeNode(root))
      }

      rx.tryFlush()

      const roots = await Promise.all(rootPromises)
      const truncating = sharedLength < origLength

      for (const node of roots) {
        if (node === null) {
          throw INVALID_OPERATION(
            'Invalid catchup length, tree nodes not available',
            this.core.discoveryKey
          )
        }
      }

      const fork = truncating ? this.fork + 1 : this.fork

      // overwrite it atm, TODO: keep what we can connect to the tree
      tx.deleteBlockRange(0, -1)
      tx.deleteTreeNodeRange(0, -1)
      tx.deleteBitfieldPageRange(0, -1)

      const tree = {
        fork,
        length,
        rootHash: crypto.tree(roots),
        signature: null,
        timestamp: Date.now()
      }

      // never default state so do not update group index
      tx.setHead(tree)

      // prop a better way to do this
      const dep = updateDependency(this, sharedLength, true)
      dep.length = length

      tx.setDependency(dep)

      const flushed = await this.flush()

      this.storage.setDependencyHead(dep)

      this.fork = tree.fork
      this.roots = roots
      this.length = tree.length
      this.byteLength = MerkleTree.size(roots)

      if (truncating) this.ontruncate(tree, sharedLength, origLength, flushed)
      if (sharedLength < length) this.onappend(tree, null, flushed)

      if (this.core.hintsChanged && this.isDefault()) await this.core.flushHints()
    } finally {
      this._unlock()
    }
  }

  async _overwrite(source, fork, length, treeLength, signature) {
    const blockPromises = []
    const treePromises = []
    const rootPromises = []

    const rx = source.storage.read()

    for (const root of flat.fullRoots(length * 2)) {
      rootPromises.push(rx.getTreeNode(root))
    }

    for (const index of flat.patch(treeLength * 2, length * 2)) {
      treePromises.push(rx.getTreeNode(index))
    }

    for (let i = treeLength; i < length; i++) {
      treePromises.push(rx.getTreeNode(i * 2))
      treePromises.push(rx.getTreeNode(i * 2 + 1))
      blockPromises.push(rx.getBlock(i))
    }

    rx.tryFlush()

    const [blocks, nodes, roots] = await Promise.all([
      Promise.all(blockPromises),
      Promise.all(treePromises),
      Promise.all(rootPromises)
    ])

    if (this.core.destroyed) throw new Error('Core destroyed')

    if (signature) {
      const batch = this.createTreeBatch()
      batch.roots = roots
      batch.length = length

      if (!this.core.verifier.verify(batch, signature)) {
        throw INVALID_SIGNATURE(
          'Signature is not valid over committed tree',
          this.core.discoveryKey
        )
      }
    }

    const tx = this.createWriteBatch()

    // truncate existing tree
    if (treeLength < this.length) {
      tx.deleteBlockRange(treeLength, this.length)
    }

    for (const root of roots) tx.putTreeNode(root)

    // no nodes will be copied in shallow mode
    for (const node of nodes) {
      if (node !== null) tx.putTreeNode(node)
    }

    for (let i = 0; i < blocks.length; i++) {
      assert(blocks[i] !== null, 'has block')
      tx.putBlock(i + treeLength, blocks[i])
    }

    const totalLength = Math.max(length, this.length)

    if (totalLength > treeLength) {
      const firstPage = getBitfieldPage(treeLength)
      const lastPage = getBitfieldPage(totalLength - 1)

      const srx = this.storage.read()
      const bitfieldPagePromise = srx.getBitfieldPage(firstPage)
      srx.tryFlush()

      const bitfieldPage = await bitfieldPagePromise

      let index = treeLength

      for (let i = firstPage; i <= lastPage; i++) {
        const page = b4a.alloc(Bitfield.BYTES_PER_PAGE)
        tx.putBitfieldPage(i, page)

        // copy existing bits in
        if (i === firstPage && bitfieldPage) page.set(bitfieldPage)

        if (index < length) {
          index = fillBitfieldPage(page, index, length, i, true)
          if (index < length) continue
        }

        if (index < this.length) {
          index = fillBitfieldPage(page, index, this.length, i, false)
        }
      }
    }

    const tree = {
      fork,
      length,
      rootHash: crypto.tree(roots),
      signature,
      timestamp: Date.now()
    }

    if (this.isDefault() && this.core.header.group) {
      this.updateGroupIndex(tx, tree)
    }

    const upgraded = treeLength < this.length || this.length < length || tree.fork !== this.fork

    if (upgraded) tx.setHead(tree)

    const flushed = await this.flush()

    this.fork = tree.fork
    this.roots = roots
    this.length = length
    this.byteLength = MerkleTree.size(roots)
    this.signature = signature

    return { tree, flushed }
  }

  static isParent(state, parent) {
    // atomic batches have parent set
    if (state.parent && state.parent === parent) return true

    return HypercoreStorage.isParentStorage(state.storage, parent.storage)
  }

  async commit(state, { signature, keyPair, length = state.length, treeLength = -1 } = {}) {
    assert(
      this.isDefault() || (this.parent && this.parent.isDefault()),
      'Can only commit into default state'
    )

    assert(SessionState.isParent(state, this), 'Cannot commit across cores')

    if (this.core._repairMode) {
      throw ASSERTION('Cannot commit while repair mode is on')
    }

    if (this.core.header.hints.recovering) await this.waitForRecovery()

    let srcLocked = false
    await this.mutex.lock()

    try {
      await state.mutex.lock()
      srcLocked = true

      if (treeLength === -1) treeLength = state.flushedLength()

      if (!(await this.core._validateCommit(state, treeLength))) return null
      if (this.length > length) return null

      if (this.length < length && !signature) {
        if (!keyPair) keyPair = this.core.header.keyPair
        const batch = state.createTreeBatch()
        if (length !== batch.length) await batch.restore(length)
        signature = this.core.verifier.sign(batch, keyPair)
      }

      const { tree, flushed } = await this._overwrite(
        state,
        this.fork,
        length,
        treeLength,
        signature
      )

      // gc blocks from source
      if (treeLength < length) {
        const tx = state.createWriteBatch()

        tx.deleteBlockRange(treeLength, length)
        const dependency = state.updateDependency(tx, length)

        await state.flush(tx)

        if (dependency) state.storage.setDependencyHead(dependency)
      }

      const bitfield = { start: treeLength, length: length - treeLength, drop: false }
      this.onappend(tree, bitfield, flushed)

      return {
        length: this.length,
        byteLength: this.byteLength
      }
    } finally {
      if (srcLocked) state._unlock()
      this._unlock()
    }
  }

  async _getTreeHeadAt(length) {
    if (length === null) return this.treeInfo()

    const head = getDefaultTree()

    head.length = length

    const roots = await MerkleTree.getRootsFromStorage(this.storage, length)
    const rootHash = crypto.tree(roots)

    head.fork = this.fork
    head.rootHash = rootHash

    if (length === this.length) head.signature = this.signature

    return head
  }

  _moveToCore(core, truncated, appended) {
    const head = this.core.sessionStates.pop()
    if (head !== this) this.core.sessionStates[(head.index = this.index)] = head

    this.core = core
    this.index = this.core.sessionStates.push(this) - 1

    for (let i = this.sessions.length - 1; i >= 0; i--) {
      const s = this.sessions[i]
      const manifest = s.manifest
      s.transferSession(this.core)
      if (!manifest && s.manifest) s.emit('manifest')
      if (truncated) s.emit('truncate', truncated.to, truncated.fork)
      if (appended) s.emit('append')
    }
  }

  async moveTo(core, length) {
    const state = core.state

    await this.mutex.lock()

    try {
      // if (state.storage && (await state.storage.resumeSession(this.name)) !== null) {
      //   throw STORAGE_CONFLICT('Batch has already been created')
      // }

      const treeLength = this.length

      let truncated = null
      let appended = false

      if (!this.isSnapshot()) {
        if (this.lingers === null) this.lingers = []
        this.lingers.push(this.storage)

        const resumed = await state.storage.resumeSession(this.name)

        const truncation = length < this.length ? await truncateAndFlush(this, length) : null
        const treeInfo = truncation
          ? truncation.tree
          : resumed
            ? null
            : await state._getTreeHeadAt(this.length)

        const fork = truncation ? this.fork + 1 : this.fork

        // todo: validate treeInfo

        let storage = null

        if (resumed) {
          storage = resumed
        } else {
          treeInfo.fork = fork
          storage = await state.storage.createSession(this.name, treeInfo)
        }

        const roots = await MerkleTree.getRootsFromStorage(storage, length)

        this.storage = storage
        this.prologue = state.prologue
        this.fork = fork
        this.length = length
        this.byteLength = MerkleTree.size(roots)
        this.roots = roots

        if (truncation) {
          const { dependency } = truncation

          if (dependency) this.storage.setDependencyHead(dependency)
          truncated = { to: treeLength, fork }
        }

        if (this.length > treeLength) {
          appended = true
        }
      }

      for (let i = this.core.sessionStates.length - 1; i >= 0; i--) {
        const state = this.core.sessionStates[i]
        if (state === this) continue
        if (state.name === this.name) state._moveToCore(core.core)
      }

      this._moveToCore(core.core, truncated, appended)
    } finally {
      this._unlock()
    }
  }

  async createSession(name, overwrite, atom) {
    await this.mutex.lock()

    try {
      let storage = null
      let treeInfo = null

      if (!atom && !overwrite && this.storage) {
        storage = await this.storage.resumeSession(name)

        if (storage !== null) treeInfo = (await getCoreHead(storage)) || getDefaultTree()
      }

      const length = treeInfo ? treeInfo.length : this.length

      if (storage === null) {
        treeInfo = await this._getTreeHeadAt(length)

        if (atom) {
          storage = await this.storage.createAtomicSession(atom, treeInfo)
        } else {
          storage = await this.storage.createSession(name, treeInfo)
        }
      }

      if (this.atomized && atom) {
        throw new Error('Session already atomized')
      }

      const head = {
        fork: this.fork,
        roots:
          length === this.length
            ? this.roots.slice()
            : await MerkleTree.getRootsFromStorage(storage, length),
        length,
        prologue: this.prologue,
        signature: length === this.length ? this.signature : null
      }

      const state = new SessionState(
        this.core,
        atom ? this : null,
        storage,
        head,
        atom ? this.name : name
      )

      if (atom) {
        this.atomized = atom
        atom.preflush(this._precommit.bind(this, state))
        atom.onflush(state._commit.bind(state))
      }

      return state
    } finally {
      this._unlock()
    }
  }
}

module.exports = SessionState

function noop() {}

function getBitfieldPage(index) {
  return Math.floor(index / Bitfield.BITS_PER_PAGE)
}

function fillBitfieldPage(page, start, end, pageIndex, value) {
  const offset = pageIndex * Bitfield.BITS_PER_PAGE
  const max = offset + Bitfield.BITS_PER_PAGE

  const index = max < end ? max : end

  const from = start - offset
  const to = index - offset

  quickbit.fill(page, value, from, to)

  return index
}

async function storeBitfieldRange(storage, tx, from, to, value) {
  if (from >= to) return

  const firstPage = getBitfieldPage(from)
  const lastPage = getBitfieldPage(to - 1)

  let index = from

  const rx = storage.read()

  const promises = []
  for (let i = firstPage; i <= lastPage; i++) {
    promises.push(rx.getBitfieldPage(i))
  }

  rx.tryFlush()

  const pages = await Promise.all(promises)
  const cnt = lastPage - firstPage + 1

  for (let i = 0; i < cnt; i++) {
    const pageIndex = i + firstPage
    if (!pages[i]) pages[i] = b4a.alloc(Bitfield.BYTES_PER_PAGE)

    index = fillBitfieldPage(pages[i], index, to, pageIndex, value)
    tx.putBitfieldPage(pageIndex, pages[i])
  }
}

async function truncateAndFlush(s, length) {
  const batch = s.createTreeBatch()
  await MerkleTree.truncate(s, length, batch, s.fork)
  const tx = s.createWriteBatch()

  const info = await s._truncate(tx, batch)
  const flushed = await s.flush()

  return {
    tree: info.tree,
    roots: info.roots,
    dependency: info.dependency,
    flushed
  }
}

function updateDependency(state, length, truncated) {
  const i = state.storage.findDependencyIndex(length, truncated)
  if (i === -1) return null // skip default state and overlays of default

  return {
    dataPointer: state.storage.dependencies[i].dataPointer,
    length
  }
}

function getDefaultTree() {
  return {
    fork: 0,
    length: 0,
    rootHash: null,
    signature: null
  }
}

function getCoreHead(storage) {
  const b = storage.read()
  const p = b.getHead()
  b.tryFlush()
  return p
}

function isRootIndex(index, roots) {
  for (const node of roots) {
    if (node.index === index) return true
  }

  return false
}

function getRecoveryPeers(peers) {
  if (!SessionState.RECOVERY_PEERS) return peers

  const actual = []

  for (const p of peers) {
    for (const r of SessionState.RECOVERY_PEERS) {
      if (b4a.equals(p.remotePublicKey, r)) {
        actual.push(p)
        break
      }
    }
  }

  return actual
}

function validateRecoveryPeers(peers, length) {
  if (peers.length < 1) return false

  for (const p of peers) {
    if (p.remoteLength > length) return false
    if (p.remoteLength === 0 && !p.remoteSynced) return false
  }

  return true
}
const { Writable, Readable } = require('streamx')

class ReadStream extends Readable {
  constructor(core, opts = {}) {
    super()

    this.core = core
    this.start = opts.start || 0
    this.end = typeof opts.end === 'number' ? opts.end : -1
    this.snapshot = !opts.live && opts.snapshot !== false
    this.live = this.end === -1 ? !!opts.live : false
    this.wait = typeof opts.wait === 'boolean' ? opts.wait : this.core.wait
    this.timeout = opts.timeout || core.timeout
  }

  _open(cb) {
    this._openP().then(cb, cb)
  }

  _read(cb) {
    this._readP().then(cb, cb)
  }

  async _openP() {
    if (this.end === -1) await this.core.update()
    else await this.core.ready()
    if (this.snapshot && this.end === -1) this.end = this.core.length
  }

  async _readP() {
    const end = this.live ? -1 : this.end === -1 ? this.core.length : this.end
    if (end >= 0 && this.start >= end) {
      this.push(null)
      return
    }

    this.push(await this.core.get(this.start++, { wait: this.wait, timeout: this.timeout }))
  }
}

exports.ReadStream = ReadStream

class WriteStream extends Writable {
  constructor(core) {
    super()
    this.core = core
  }

  _writev(batch, cb) {
    this._writevP(batch).then(cb, cb)
  }

  async _writevP(batch) {
    await this.core.append(batch)
  }
}

exports.WriteStream = WriteStream

class ByteStream extends Readable {
  constructor(core, opts = {}) {
    super()

    this._core = core
    this._index = 0
    this._range = null

    this._byteOffset = opts.byteOffset || 0
    this._byteLength = typeof opts.byteLength === 'number' ? opts.byteLength : -1
    this._prefetch = typeof opts.prefetch === 'number' ? opts.prefetch : 32

    this._applyOffset = this._byteOffset > 0
  }

  _open(cb) {
    this._openp().then(cb, cb)
  }

  _read(cb) {
    this._readp().then(cb, cb)
  }

  async _openp() {
    if (this._byteLength === -1) {
      await this._core.update()
      this._byteLength = Math.max(this._core.byteLength - this._byteOffset, 0)
    }
  }

  async _readp() {
    let data = null

    if (this._byteLength === 0) {
      this.push(null)
      return
    }

    let relativeOffset = 0

    if (this._applyOffset) {
      this._applyOffset = false

      const [block, byteOffset] = await this._core.seek(this._byteOffset)

      this._index = block
      relativeOffset = byteOffset
    }

    this._predownload(this._index + 1)
    data = await this._core.get(this._index++, { valueEncoding: 'binary' })

    if (relativeOffset > 0) data = data.subarray(relativeOffset)

    if (data.byteLength > this._byteLength) data = data.subarray(0, this._byteLength)
    this._byteLength -= data.byteLength

    this.push(data)
    if (this._byteLength === 0) this.push(null)
  }

  _predownload(index) {
    if (this._range) this._range.destroy()
    this._range = this._core.download({ start: index, end: index + this._prefetch, linear: true })
  }

  _destroy(cb) {
    if (this._range) this._range.destroy()
    cb(null)
  }
}

exports.ByteStream = ByteStream
const crypto = require('hypercore-crypto')
const b4a = require('b4a')
const c = require('compact-encoding')
const flat = require('flat-tree')
const { BAD_ARGUMENT } = require('hypercore-errors')
const unslab = require('unslab')

const m = require('./messages')
const multisig = require('./multisig')
const caps = require('./caps')

class Signer {
  constructor(
    manifestHash,
    version,
    index,
    { signature = 'ed25519', publicKey, namespace = caps.DEFAULT_NAMESPACE } = {}
  ) {
    if (!publicKey) throw BAD_ARGUMENT('public key is required for a signer')
    if (signature !== 'ed25519') throw BAD_ARGUMENT('Only Ed25519 signatures are supported')

    this.manifestHash = manifestHash
    this.version = version
    this.signer = index
    this.signature = signature
    this.publicKey = publicKey
    this.namespace = namespace
  }

  _ctx() {
    return this.version === 0 ? this.namespace : this.manifestHash
  }

  verify(batch, signature) {
    return crypto.verify(batch.signable(this._ctx()), signature, this.publicKey)
  }

  sign(batch, keyPair) {
    return crypto.sign(batch.signable(this._ctx()), keyPair.secretKey)
  }
}

class CompatSigner extends Signer {
  constructor(index, signer, legacy) {
    super(null, 0, index, signer)
    this.legacy = legacy
  }

  verify(batch, signature) {
    return crypto.verify(batch.signableCompat(this.legacy), signature, this.publicKey)
  }

  sign(batch, keyPair) {
    return crypto.sign(batch.signableCompat(this.legacy), keyPair.secretKey)
  }
}

module.exports = class Verifier {
  constructor(
    manifestHash,
    manifest,
    { compat = isCompat(manifestHash, manifest), legacy = false } = {}
  ) {
    const self = this

    this.manifestHash = manifestHash
    this.compat = compat || manifest === null
    this.version = this.compat ? 0 : typeof manifest.version === 'number' ? manifest.version : 1
    this.hash = manifest.hash || 'blake2b'
    this.allowPatch = !this.compat && !!manifest.allowPatch
    this.quorum = this.compat ? 1 : defaultQuorum(manifest)

    this.signers = manifest.signers ? manifest.signers.map(createSigner) : []
    this.prologue = this.compat ? null : manifest.prologue || null

    function createSigner(signer, index) {
      return self.compat
        ? new CompatSigner(index, signer, legacy)
        : new Signer(manifestHash, self.version, index, signer)
    }
  }

  _verifyCompat(batch, signature) {
    if (!signature) return false

    if (this.compat || (!this.allowPatch && this.signers.length === 1)) {
      return !!signature && this.signers[0].verify(batch, signature)
    }

    return this._verifyMulti(batch, signature)
  }

  _inflate(signature) {
    if (this.version >= 1) return multisig.inflate(signature)
    const { proofs, patch } = multisig.inflatev0(signature)

    return {
      proofs: proofs.map(proofToVersion1),
      patch
    }
  }

  _verifyMulti(batch, signature) {
    if (!signature || this.quorum === 0) return false

    const { proofs, patch } = this._inflate(signature)
    if (proofs.length < this.quorum) return false

    const tried = new Uint8Array(this.signers.length)
    const nodes = this.allowPatch && patch.length ? toMap(patch) : null

    for (let i = 0; i < this.quorum; i++) {
      const inp = proofs[i]

      let tree = batch

      if (inp.patch && this.allowPatch) {
        tree = batch.clone()

        const upgrade = generateUpgrade(nodes, batch.length, inp.patch)
        const proof = {
          fork: tree.fork,
          block: null,
          hash: null,
          seek: null,
          upgrade,
          manifest: null
        }

        try {
          if (!tree.verifyUpgrade(proof)) return false
        } catch {
          return false
        }
      }

      if (inp.signer >= this.signers.length || tried[inp.signer]) return false
      tried[inp.signer] = 1

      const s = this.signers[inp.signer]
      if (!s.verify(tree, inp.signature)) return false
    }

    return true
  }

  verify(batch, signature) {
    if (this.version === 0) {
      return this._verifyCompat(batch, signature)
    }

    if (this.prologue !== null && batch.length <= this.prologue.length) {
      return batch.length === this.prologue.length && b4a.equals(batch.hash(), this.prologue.hash)
    }

    return this._verifyMulti(batch, signature)
  }

  // TODO: better api for this that is more ... multisig-ey
  sign(batch, keyPair) {
    if (!keyPair || !keyPair.secretKey) throw BAD_ARGUMENT('No key pair was passed')

    for (const s of this.signers) {
      if (b4a.equals(s.publicKey, keyPair.publicKey)) {
        const signature = s.sign(batch, keyPair)
        if (this.signers.length !== 1 || this.version === 0) return signature
        return this.assemble([{ signer: 0, signature, patch: 0, nodes: null }])
      }
    }

    throw BAD_ARGUMENT('Public key is not a declared signer')
  }

  assemble(inputs) {
    return this.version === 0 ? multisig.assemblev0(inputs) : multisig.assemble(inputs)
  }

  static manifestHash(manifest) {
    return manifestHash(manifest)
  }

  static encodeManifest(manifest) {
    return c.encode(m.manifest, manifest)
  }

  static decodeManifest(manifest) {
    return c.decode(m.manifest, manifest)
  }

  static defaultSignerManifest(publicKey) {
    return {
      version: 1,
      hash: 'blake2b',
      allowPatch: false,
      quorum: 1,
      signers: [
        {
          signature: 'ed25519',
          namespace: caps.DEFAULT_NAMESPACE,
          publicKey
        }
      ],
      prologue: null,
      linked: null,
      userData: null
    }
  }

  static fromManifest(manifest, opts) {
    const m = this.createManifest(manifest)
    return new this(manifestHash(m), m, opts)
  }

  static createManifest(inp) {
    if (!inp) return null

    if (inp.quorum && inp.quorum < 0) throw BAD_ARGUMENT('Quorum cannot be negative')
    if (inp.quorum && inp.signers && inp.quorum > inp.signers.length) {
      throw BAD_ARGUMENT('Quorum should not be higher than the number of signers')
    }

    const manifest = {
      version: getManifestVersion(inp), // defaults to v1
      hash: 'blake2b',
      allowPatch: !!inp.allowPatch,
      quorum: defaultQuorum(inp),
      signers: inp.signers ? inp.signers.map(parseSigner) : [],
      prologue: null,
      linked: null,
      userData: inp.userData || null
    }

    if (inp.hash && inp.hash !== 'blake2b') throw BAD_ARGUMENT('Only Blake2b hashes are supported')

    if (inp.prologue) {
      if (
        !(b4a.isBuffer(inp.prologue.hash) && inp.prologue.hash.byteLength === 32) ||
        !(inp.prologue.length >= 0)
      ) {
        throw BAD_ARGUMENT('Invalid prologue')
      }

      manifest.prologue = inp.prologue
      manifest.prologue.hash = unslab(manifest.prologue.hash)
    }

    if (manifest.userData !== null && manifest.version < 2) {
      throw BAD_ARGUMENT('Invalid field: userData')
    }

    if (inp.linked && inp.linked.length) {
      if (manifest.version < 2) throw BAD_ARGUMENT('Invalid field: linked')

      for (const key of inp.linked) {
        if (!(b4a.isBuffer(key) && key.byteLength === 32)) {
          throw BAD_ARGUMENT('Invalid key')
        }
      }

      manifest.linked = inp.linked
    }

    return manifest
  }

  static isValidManifest(key, manifest) {
    return b4a.equals(key, manifestHash(manifest))
  }

  static isCompat(key, manifest) {
    return isCompat(key, manifest)
  }

  static sign(manifest, batch, keyPair, opts) {
    return Verifier.fromManifest(manifest, opts).sign(batch, keyPair)
  }
}

function toMap(nodes) {
  const m = new Map()
  for (const node of nodes) m.set(node.index, node)
  return m
}

function isCompat(key, manifest) {
  return !!(
    manifest &&
    manifest.signers.length === 1 &&
    b4a.equals(key, manifest.signers[0].publicKey)
  )
}

function defaultQuorum(man) {
  if (typeof man.quorum === 'number') return man.quorum
  if (!man.signers || !man.signers.length) return 0
  return (man.signers.length >> 1) + 1
}

function generateUpgrade(patch, start, length) {
  const upgrade = { start, length, nodes: null, additionalNodes: [], signature: null }

  const from = start * 2
  const to = from + length * 2

  for (const ite = flat.iterator(0); ite.fullRoot(to); ite.nextTree()) {
    if (ite.index + ite.factor / 2 < from) continue

    if (upgrade.nodes === null && ite.contains(from - 2)) {
      upgrade.nodes = []

      const root = ite.index
      const target = from - 2

      ite.seek(target)

      while (ite.index !== root) {
        ite.sibling()
        if (ite.index > target) upgrade.nodes.push(patch.get(ite.index))
        ite.parent()
      }

      continue
    }

    if (upgrade.nodes === null) upgrade.nodes = []
    upgrade.nodes.push(patch.get(ite.index))
  }

  if (upgrade.nodes === null) upgrade.nodes = []
  return upgrade
}

function parseSigner(signer) {
  validateSigner(signer)
  return {
    signature: 'ed25519',
    namespace: unslab(signer.namespace || caps.DEFAULT_NAMESPACE),
    publicKey: unslab(signer.publicKey)
  }
}

function validateSigner(signer) {
  if (!signer || !signer.publicKey) throw BAD_ARGUMENT('Signer missing public key')
  if (signer.signature && signer.signature !== 'ed25519') {
    throw BAD_ARGUMENT('Only Ed25519 signatures are supported')
  }
}

function manifestHash(manifest) {
  const state = { start: 0, end: 32, buffer: null }
  m.manifest.preencode(state, manifest)
  state.buffer = b4a.allocUnsafe(state.end)
  c.raw.encode(state, caps.MANIFEST)
  m.manifest.encode(state, manifest)
  return crypto.hash(state.buffer)
}

function proofToVersion1(proof) {
  return {
    signer: proof.signer,
    signature: proof.signature,
    patch: proof.patch ? proof.patch.length : 0
  }
}

function getManifestVersion(inp) {
  if (typeof inp.version === 'number') return inp.version
  if (inp.linked && inp.linked.length) return 2
  if (inp.userData) return 2
  return 1
}
let COMPAT = true
let BATCH_UINTS = COMPAT ? 65536 : 128
let BATCH_BYTES = BATCH_UINTS * 4
let BATCH = BATCH_BYTES * 8 // in bits
const MAX_REMOTE_BATCHES = 4
const MAX_RANGE = 8 * 256 * 1024
const MIN_RANGE = 32 // 4bit ints
const MAX = 512
const MAX_ANY = 16

class LocalWants {
  constructor(peer) {
    this.destroyed = false
    this.peer = peer
    this.wants = new Map()
    this.free = new Set()
    this.any = null
  }

  add(index, handle) {
    const b = (index - (index & (BATCH - 1))) / BATCH
    return this.addBatch(b, handle)
  }

  addAnyRange(start, length, handle) {
    if (this.destroyed) return null
    if (this.any === null) this.any = []

    if (COMPAT) {
      let r = start & (BATCH - 1)
      start -= r
      length += r
      r = length & (BATCH - 1)
      if (r) length = length - r + BATCH
    }

    for (let i = 0; i < this.any.length; i++) {
      const w = this.any[i]
      if (w.start === start && w.length === length) {
        w.handles.add(handle)
        handle.addWant(w)
        return null
      }
    }

    const w = { wants: this, start, length, any: true, handles: new Set([handle]) }
    this.any.push(w)
    handle.addWant(w)

    return { start, length, any: !COMPAT }
  }

  removeAnyRange(start, length, handle) {
    if (this.any === null) return null

    for (let i = 0; i < this.any.length; i++) {
      const w = this.any[i]
      if (w.start !== start || w.length !== length) continue

      w.handles.delete(handle)
      handle.removeWant(w)
      if (w.handles.size > 0) return null

      const head = this.any.pop()
      if (head !== w) this.any[i] = head
      return { start, length, any: !COMPAT }
    }

    return null
  }

  addBatch(index, handle) {
    if (this.destroyed) return null
    let w = this.wants.get(index)

    if (w) {
      const size = w.handles.size
      w.handles.add(handle)
      if (w.handles.size !== size) {
        handle.addWant(w)
      }
      return null
    }

    // start here is the batch number for simplicity....
    w = { wants: this, start: index, length: 0, any: false, handles: new Set([handle]) }

    if (this.free.has(index)) {
      this.free.delete(index)
      this.wants.set(index, w)
      handle.addWant(w)
      return null
    }

    let unwant = null
    if (this.wants.size + this.free.size === MAX) {
      if (this.free.size === 0) {
        return null
      }
      unwant = this._unwant()
    }

    this.wants.set(index, w)
    handle.addWant(w)

    return {
      want: { start: index * BATCH, length: BATCH, any: false },
      unwant
    }
  }

  remove(index, handle) {
    const b = (index - (index & (BATCH - 1))) / BATCH
    return this.removeBatch(b, handle)
  }

  removeBatch(index, handle) {
    if (this.destroyed) return false

    const w = this.wants.get(index)
    if (!w) {
      return false
    }

    w.handles.delete(handle)
    handle.removeWant(w)

    if (w.handles.size === 0) {
      this.free.add(index)
      this.wants.delete(index)
      return this.free.size === 1 && this.wants.size === MAX - 1
    }

    return false
  }

  destroy() {
    if (this.destroyed) return
    this.destroyed = true

    for (const w of this.wants.values()) {
      for (const handle of w.handles) {
        handle.removeWant(w)
      }
    }

    this.wants.clear()
  }

  _unwant() {
    for (const index of this.free) {
      this.free.delete(index)
      return { start: index * BATCH, length: BATCH, any: false }
    }
    return null
  }
}

class RemoteWants {
  constructor() {
    this.any = null
    this.all = false
    this.size = 0
    this.batches = []
  }

  hasAny(start, length) {
    for (let i = 0; i < this.any.length; i++) {
      const a = this.any[i]
      const e = start + length
      const end = a.start + a.length

      if (a.start <= start && start < end) return true
      if (a.start < e && e <= end) return true
    }

    return this.all
  }

  hasRange(start, length) {
    if (this.any !== null && this.hasAny(start, length)) return true
    if (length === 1) return this.has(start)

    let smallest = -1

    for (let i = 0; i < this.batches.length; i++) {
      const b = this.batches[i]
      if (b.length < smallest || smallest === -1) smallest = b.length
    }

    if (smallest === -1) return this.all

    const r = start & (smallest - 1)
    const end = start + length

    let max = 3

    for (let i = start - r; i < end; i += smallest) {
      if (max-- === 0) return true // just to save work
      if (this.has(i)) return true
    }

    return this.all
  }

  has(index) {
    for (let i = 0; i < this.batches.length; i++) {
      const b = this.batches[i]
      const block = (index - (index & (b.length - 1))) / b.length
      if (b.ranges.has(block)) return true
    }

    return this.all
  }

  add(range) {
    if (range.any) {
      if (this.any === null) this.any = []
      if (this.any.length < MAX_ANY) this.any.push(range)
      else this.all = true
      return true
    }

    if (range.length > MAX_RANGE) return false

    if (!validateBatchRange(range)) {
      this.all = true
      return true
    }

    if (this.size >= MAX) {
      this.all = true
      return true
    }

    for (let i = 0; i < this.batches.length; i++) {
      const b = this.batches[i]
      if (b.length === range.length) {
        b.ranges.add(range.start / range.length)
        this.size++
        return true
      }
    }

    if (this.batches.length >= MAX_REMOTE_BATCHES) {
      this.all = true
      return true
    }

    this.batches.push({
      length: range.length,
      ranges: new Set([range.start / range.length])
    })
    this.size++

    return true
  }

  remove(range) {
    if (range.any) {
      if (this.any === null) return false

      for (let i = 0; i < this.any.length; i++) {
        const a = this.any[i]

        if (a.start === range.start && a.length === range.length) {
          const head = this.any.pop()
          if (head !== a) this.any[i] = head
          return true
        }
      }

      return false
    }

    if (!validateBatchRange(range)) return false

    for (let i = 0; i < this.batches.length; i++) {
      const b = this.batches[i]
      if (b.length !== range.length) continue

      const size = b.ranges.size
      b.ranges.delete(range.start / range.length)
      if (b.ranges.size !== size) this.size--

      if (b.ranges.size === 0) {
        const head = this.batches.pop()
        if (head !== b) this.batches[i] = head
      }

      return true
    }

    return false
  }
}

function UPDATE_COMPAT(isCompat) {
  COMPAT = isCompat
  BATCH_UINTS = COMPAT ? 65536 : 128
  BATCH_BYTES = BATCH_UINTS * 4
  BATCH = BATCH_BYTES * 8 // in bits
  exports.WANT_BATCH = BATCH
}

exports.LocalWants = LocalWants
exports.RemoteWants = RemoteWants
exports.WANT_BATCH = BATCH
exports.UPDATE_COMPAT = UPDATE_COMPAT

function validateBatchRange(range) {
  if (range.length > MAX_RANGE || range.length < MIN_RANGE) {
    return false
  }
  // check if power of two
  if ((range.length & (range.length - 1)) !== 0) {
    return false
  }
  // start must be a multiple of the length
  if (range.start & (range.length - 1)) {
    return false
  }

  return true
}
{
  "name": "hypercore",
  "version": "11.33.5",
  "description": "Hypercore is a secure, distributed append-only log",
  "main": "index.js",
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "brittle test/all.js",
    "test:bare": "bare test/all.js",
    "test:generate": "brittle -r test/all.js test/*.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/hypercore.git"
  },
  "contributors": [
    {
      "name": "Mathias Buus",
      "email": "mathiasbuus@gmail.com",
      "url": "https://mafinto.sh"
    },
    {
      "name": "Andrew Osheroff",
      "email": "andrewosh@gmail.com",
      "url": "https://andrewosh.com"
    }
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/hypercore/issues"
  },
  "homepage": "https://github.com/holepunchto/hypercore#readme",
  "files": [
    "index.js",
    "errors.js",
    "messages.js",
    "lib/**.js"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "dependencies": {
    "@hyperswarm/secret-stream": "^6.0.0",
    "b4a": "^1.1.0",
    "bare-events": "^2.2.0",
    "big-sparse-array": "^1.0.3",
    "compact-encoding": "^3.0.0",
    "fast-fifo": "^1.3.0",
    "flat-tree": "^1.9.0",
    "hypercore-crypto": "^3.2.1",
    "hypercore-errors": "^1.5.0",
    "hypercore-id-encoding": "^1.2.0",
    "hypercore-storage": "^3.0.0",
    "is-options": "^1.0.1",
    "nanoassert": "^2.0.0",
    "protomux": "^3.5.0",
    "quickbit-universal": "^2.2.0",
    "random-array-iterator": "^1.0.0",
    "safety-catch": "^1.0.1",
    "sodium-universal": "^5.0.1",
    "streamx": "^2.12.4",
    "unslab": "^1.3.0",
    "z32": "^1.0.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "debugging-stream": "^3.1.0",
    "hyperswarm": "^4.3.6",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "rache": "^1.0.0",
    "range-parser": "^1.2.1",
    "resolve-reject-promise": "^1.1.0",
    "speedometer": "^1.1.0",
    "test-tmp": "^1.0.2",
    "tiny-byte-size": "^1.1.0",
    "udx-native": "^1.6.1",
    "uncaughts": "^1.1.0"
  }
}
{
  "name": "hyperschema",
  "version": "1.21.0",
  "description": "Create registries of declarative compact-encoding schemas",
  "files": [
    "lib/*.js",
    "builder.mjs",
    "builder.cjs",
    "runtime.mjs",
    "runtime.cjs",
    "primitives.mjs",
    "primitives.cjs"
  ],
  "exports": {
    "./package": "./package.json",
    ".": {
      "import": "./builder.mjs",
      "default": "./builder.cjs"
    },
    "./runtime": {
      "import": "./runtime.mjs",
      "default": "./runtime.cjs"
    },
    "./primitives": {
      "import": "./primitives.mjs",
      "default": "./primitives.cjs"
    }
  },
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    }
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test/index.js",
    "test:bare": "prettier . --check && bare test/index.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/hyperschema.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/hyperschema/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperschema#readme",
  "dependencies": {
    "bare-fs": "^4.0.1",
    "compact-encoding": "^3.0.0",
    "generate-object-property": "^2.0.0",
    "generate-string": "^1.0.1"
  },
  "devDependencies": {
    "brittle": "^3.7.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "test-tmp": "^1.3.0"
  }
}
module.exports = {
  c: require('compact-encoding')
}
const b4a = require('b4a')

const EMPTY = b4a.alloc(0)
const MAX = b4a.from([0xff])
const BUFFER = {}

BUFFER.preencode = function (state, buf) {
  if (buf === null) buf = EMPTY

  let i = 0
  let extra = 3

  while ((i = b4a.indexOf(buf, 0x00, i)) > -1) {
    i++
    extra++
  }

  state.end += buf.byteLength + extra
}

BUFFER.encode = function (state, buf) {
  if (buf === null) buf = EMPTY

  state.buffer[state.start++] = 0x00

  let prev = 0
  let i = 0

  while ((i = b4a.indexOf(buf, 0x00, i)) > -1) {
    const slice = buf.subarray(prev, ++i)

    state.buffer.set(slice, state.start)
    state.start += slice.byteLength
    state.buffer[state.start++] = 0x02
    prev = i
  }

  const slice = buf.subarray(prev)

  state.buffer.set(slice, state.start)
  state.start += slice.byteLength

  state.buffer[state.start++] = 0x00
  state.buffer[state.start++] = 0x01
}

BUFFER.decode = function (state) {
  if (state.start >= state.end) throw new Error('Out of bounds')
  if (state.buffer[state.start++] !== 0x00) {
    throw new Error('Invalid start of string')
  }

  let escaped = null

  let prev = state.start
  let i = state.start

  while ((i = b4a.indexOf(state.buffer, 0x00, i)) > -1) {
    const next = ++i < state.end ? state.buffer[i] : 0x00

    i++

    if (next === 0x01) {
      break
    }

    if (next === 0x02) {
      if (escaped === null) escaped = []
      escaped.push(state.buffer.subarray(prev, i - 1))
      prev = i
      continue
    }

    throw new Error('Unknown value in terminator')
  }

  if (i === -1) {
    throw new Error('No terminator found')
  }

  state.start = i
  const last = state.buffer.subarray(prev, i - 2)
  if (escaped === null) return last

  escaped.push(last)
  return b4a.concat(escaped)
}

// TODO: can be optimised a lot

const STRING = {}

STRING.preencode = function (state, str) {
  BUFFER.preencode(state, b4a.from(str || ''))
}

STRING.encode = function (state, str) {
  BUFFER.encode(state, b4a.from(str || ''))
}

STRING.decode = function (state, str) {
  return b4a.toString(BUFFER.decode(state))
}

const UINT = {}

UINT.preencode = function (state, n) {
  state.end += n <= 0xfb ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : n === Infinity ? 1 : 9
}

UINT.encode = function (state, n) {
  if (n === Infinity) {
    state.buffer[state.start++] = 0xff
    return
  }

  if (n <= 0xfb) {
    state.buffer[state.start++] = n
    return
  }

  if (n <= 0xffff) {
    state.buffer[state.start++] = 0xfc
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
    return
  }

  if (n <= 0xffffffff) {
    state.buffer[state.start++] = 0xfd
    encodeUint32(state, n)
    return
  }

  if (Number.isSafeInteger(n)) {
    state.buffer[state.start++] = 0xfe

    const r = Math.floor(n / 0x100000000)
    encodeUint32(state, r)
    encodeUint32(state, n)
    return
  }

  throw new Error('Invalid number ' + n)
}

UINT.decode = function (state) {
  if (state.start >= state.end) throw new Error('Out of bounds')

  const a = state.buffer[state.start++]

  if (a <= 0xfb) return a

  if (a === 0xfc) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] * 0x100 + state.buffer[state.start++]
  }

  if (a === 0xfd) {
    return decodeUint32(state)
  }

  if (a === 0xfe) {
    return decodeUint32(state) * 0x100000000 + decodeUint32(state)
  }

  return Infinity
}

const INT = {}

INT.preencode = function (state, n) {
  // One asymmetric condition
  if (n >= -0xff && n < 0) {
    state.end += 2
    return
  }
  n = Math.abs(n)
  state.end += n <= 0xf6 ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : n === Infinity ? 1 : 9
}

INT.encode = function (state, n) {
  if (n === Infinity) {
    state.buffer[state.start++] = 0xff
    return
  }

  if (n === -Infinity) {
    state.buffer[state.start++] = 0x00
    return
  }

  // Negative 64 bit
  if (n < -0xffffffff) {
    if (!Number.isSafeInteger(n)) throw new Error('Invalid number ' + n)
    state.buffer[state.start++] = 0x01

    const r = Math.floor(-n / 0x100000000)
    encodeUint32(state, -r + 0xffffffff)
    encodeUint32(state, -(-n % 0x100000000) + 0xffffffff)
    return
  }

  // Negative 32 bit
  if (n < -0xffff) {
    state.buffer[state.start++] = 0x02

    n += 0xffffffff
    encodeUint32(state, n)
    return
  }

  // Negative 16bit
  if (n < -0xff) {
    state.buffer[state.start++] = 0x03

    n += 0xffff
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
    return
  }

  // Negative 8bit
  if (n < 0) {
    state.buffer[state.start++] = 0x04

    n += 0xff
    state.buffer[state.start++] = n
    return
  }

  // Remainder of 8bit space for positive int
  if (n <= 0xf6) {
    state.buffer[state.start++] = n + 0x05
    return
  }

  // Positive 16bit
  if (n <= 0xffff) {
    state.buffer[state.start++] = 0xfc
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
    return
  }

  // Positive 32bit
  if (n <= 0xffffffff) {
    state.buffer[state.start++] = 0xfd
    encodeUint32(state, n)
    return
  }

  // Positive 64bit
  if (Number.isSafeInteger(n)) {
    state.buffer[state.start++] = 0xfe

    const r = Math.floor(n / 0x100000000)
    encodeUint32(state, r)
    encodeUint32(state, n)
    return
  }

  throw new Error('Invalid number ' + n)
}

INT.decode = function (state) {
  if (state.start >= state.end) throw new Error('Out of bounds')

  const a = state.buffer[state.start++]

  if (a === 0x00) return -Infinity

  if (a === 0x01) {
    // Split (2^64 - 1) into its 32 bit components
    // r * 0x100000000 + n - (2^64 - 1)
    // r * 0x100000000 + n - (0xffffffff * 0x100000000) - 0xffffffff
    // (r - 0xffffffff) * 0x100000000 + n - 0xffffffff
    return (decodeUint32(state) - 0xffffffff) * 0x100000000 + decodeUint32(state) - 0xffffffff
  }

  if (a === 0x02) {
    return decodeUint32(state) - 0xffffffff
  }

  if (a === 0x03) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] * 0x100 + state.buffer[state.start++] - 0xffff
  }

  if (a === 0x04) return state.buffer[state.start++] - 0xff

  if (a <= 0xfb) return a - 0x05

  if (a === 0xfc) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] * 0x100 + state.buffer[state.start++]
  }

  if (a === 0xfd) {
    return decodeUint32(state)
  }

  if (a === 0xfe) {
    return decodeUint32(state) * 0x100000000 + decodeUint32(state)
  }

  return Infinity
}

const DATE = {}

DATE.preencode = (state, d) => INT.preencode(state, d.getTime())
DATE.encode = (state, d) => INT.encode(state, d.getTime())
DATE.decode = (state) => new Date(INT.decode(state))

const BOOL = {}

BOOL.preencode = (state, b) => UINT.preencode(state, b ? 1 : 0)
BOOL.encode = (state, b) => UINT.encode(state, b ? 1 : 0)
BOOL.decode = (state) => !!UINT.decode(state)

module.exports = class IndexEncoder {
  constructor(encodings, { prefix = -1 } = {}) {
    this.encodings = encodings
    this.prefix = prefix
  }

  static BUFFER = BUFFER
  static STRING = STRING
  static UINT = UINT
  static INT = INT
  static DATE = DATE
  static BOOL = BOOL

  static lookup(c) {
    switch (c) {
      case 'uint':
        return UINT
      case 'uint8':
        return UINT
      case 'uint16':
        return UINT
      case 'uint24':
        return UINT
      case 'uint32':
        return UINT
      case 'uint40':
        return UINT
      case 'uint48':
        return UINT
      case 'uint56':
        return UINT
      case 'uint64':
        return UINT
      case 'int':
        return INT
      case 'int8':
        return INT
      case 'int16':
        return INT
      case 'int24':
        return INT
      case 'int32':
        return INT
      case 'int40':
        return INT
      case 'int48':
        return INT
      case 'int56':
        return INT
      case 'int64':
        return INT
      case 'string':
        return STRING
      case 'utf8':
        return STRING
      case 'ascii':
        return STRING
      case 'hex':
        return STRING
      case 'base64':
        return STRING
      case 'fixed32':
        return BUFFER
      case 'fixed64':
        return BUFFER
      case 'buffer':
        return BUFFER
      case 'date':
        return DATE
      case 'bool':
        return BOOL
    }

    throw new Error('Unknown type')
  }

  encode(keys) {
    return this._encode(keys, false)
  }

  _encode(keys, terminate) {
    if (b4a.isBuffer(keys)) return keys

    const state = { start: 0, end: 0, buffer: null }

    if (this.prefix !== -1) UINT.preencode(state, this.prefix)
    for (let i = 0; i < keys.length; i++) {
      this.encodings[i].preencode(state, keys[i])
    }

    if (terminate && keys.length < this.encodings.length) {
      state.end++
    }

    state.buffer = b4a.allocUnsafe(state.end)

    if (this.prefix !== -1) UINT.encode(state, this.prefix)
    for (let i = 0; i < keys.length; i++) {
      this.encodings[i].encode(state, keys[i])
    }

    if (terminate && keys.length < this.encodings.length) {
      state.buffer[state.start++] = MAX[0]
    }

    return state.buffer
  }

  decode(buffer) {
    const state = { start: 0, end: buffer.byteLength, buffer }
    const result = []

    if (this.prefix !== -1) UINT.decode(state)
    for (const enc of this.encodings) {
      const key = state.start < state.end ? enc.decode(state) : enc === UINT ? 0 : null
      result.push(key)
    }

    return result
  }

  encodeRange({ gt, gte, lt, lte }) {
    const range = {
      gt: gt && this._encode(gt, true),
      gte: gte && this._encode(gte, false),
      lt: lt && this._encode(lt, false),
      lte: lte && this._encode(lte, true)
    }

    if (this.prefix !== -1) {
      if (!gt && !gte) range.gte = encodeUint(this.prefix)
      if (!lt && !lte) range.lt = encodeUint(this.prefix + 1)
    }

    return range
  }
}

function encodeUint(n) {
  const state = { start: 0, end: 0, buffer: null }
  UINT.preencode(state, n)
  state.buffer = b4a.allocUnsafe(state.end)
  UINT.encode(state, n)
  return state.buffer
}

function encodeUint32(state, n) {
  state.buffer[state.start++] = n >>> 24
  state.buffer[state.start++] = n >>> 16
  state.buffer[state.start++] = n >>> 8
  state.buffer[state.start++] = n
}

function decodeUint32(state) {
  if (state.end - state.start < 4) throw new Error('Out of bounds')
  return (
    state.buffer[state.start++] * 0x1000000 +
    state.buffer[state.start++] * 0x10000 +
    state.buffer[state.start++] * 0x100 +
    state.buffer[state.start++]
  )
}
{
  "name": "index-encoder",
  "version": "3.5.0",
  "description": "Encode multiple values into sorted keys",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.6.4"
  },
  "devDependencies": {
    "brittle": "^3.2.1",
    "hyperbee": "^2.10.5",
    "hypercore": "^11.0.0",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/index-encoder.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/index-encoder/issues"
  },
  "homepage": "https://github.com/holepunchto/index-encoder"
}
const b4a = require('b4a')

module.exports = function isOptions (opts) {
  return typeof opts === 'object' && opts && !b4a.isBuffer(opts)
}
{
  "name": "is-options",
  "version": "1.0.2",
  "description": "Easily check if input is an options map",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.1.1"
  },
  "devDependencies": {
    "standard": "^11.0.1",
    "tape": "^4.9.0"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/is-options.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/is-options/issues"
  },
  "homepage": "https://github.com/mafintosh/is-options"
}
import { coerce } from '../bytes.js';
import basex from '../vendor/base-x.js';
/**
 * Class represents both BaseEncoder and MultibaseEncoder meaning it
 * can be used to encode to multibase or base encode without multibase
 * prefix.
 */
class Encoder {
    name;
    prefix;
    baseEncode;
    constructor(name, prefix, baseEncode) {
        this.name = name;
        this.prefix = prefix;
        this.baseEncode = baseEncode;
    }
    encode(bytes) {
        if (bytes instanceof Uint8Array) {
            return `${this.prefix}${this.baseEncode(bytes)}`;
        }
        else {
            throw Error('Unknown type, must be binary type');
        }
    }
}
/**
 * Class represents both BaseDecoder and MultibaseDecoder so it could be used
 * to decode multibases (with matching prefix) or just base decode strings
 * with corresponding base encoding.
 */
class Decoder {
    name;
    prefix;
    baseDecode;
    prefixCodePoint;
    constructor(name, prefix, baseDecode) {
        this.name = name;
        this.prefix = prefix;
        const prefixCodePoint = prefix.codePointAt(0);
        /* c8 ignore next 3 */
        if (prefixCodePoint === undefined) {
            throw new Error('Invalid prefix character');
        }
        this.prefixCodePoint = prefixCodePoint;
        this.baseDecode = baseDecode;
    }
    decode(text) {
        if (typeof text === 'string') {
            if (text.codePointAt(0) !== this.prefixCodePoint) {
                throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);
            }
            return this.baseDecode(text.slice(this.prefix.length));
        }
        else {
            throw Error('Can only multibase decode strings');
        }
    }
    or(decoder) {
        return or(this, decoder);
    }
}
class ComposedDecoder {
    decoders;
    constructor(decoders) {
        this.decoders = decoders;
    }
    or(decoder) {
        return or(this, decoder);
    }
    decode(input) {
        const prefix = input[0];
        const decoder = this.decoders[prefix];
        if (decoder != null) {
            return decoder.decode(input);
        }
        else {
            throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);
        }
    }
}
export function or(left, right) {
    return new ComposedDecoder({
        ...(left.decoders ?? { [left.prefix]: left }),
        ...(right.decoders ?? { [right.prefix]: right })
    });
}
export class Codec {
    name;
    prefix;
    baseEncode;
    baseDecode;
    encoder;
    decoder;
    constructor(name, prefix, baseEncode, baseDecode) {
        this.name = name;
        this.prefix = prefix;
        this.baseEncode = baseEncode;
        this.baseDecode = baseDecode;
        this.encoder = new Encoder(name, prefix, baseEncode);
        this.decoder = new Decoder(name, prefix, baseDecode);
    }
    encode(input) {
        return this.encoder.encode(input);
    }
    decode(input) {
        return this.decoder.decode(input);
    }
}
export function from({ name, prefix, encode, decode }) {
    return new Codec(name, prefix, encode, decode);
}
export function baseX({ name, prefix, alphabet }) {
    const { encode, decode } = basex(alphabet, name);
    return from({
        prefix,
        name,
        encode,
        decode: (text) => coerce(decode(text))
    });
}
function decode(string, alphabetIdx, bitsPerChar, name) {
    // Count the padding bytes:
    let end = string.length;
    while (string[end - 1] === '=') {
        --end;
    }
    // Allocate the output:
    const out = new Uint8Array((end * bitsPerChar / 8) | 0);
    // Parse the data:
    let bits = 0; // Number of bits currently in the buffer
    let buffer = 0; // Bits waiting to be written out, MSB first
    let written = 0; // Next byte to write
    for (let i = 0; i < end; ++i) {
        // Read one character from the string:
        const value = alphabetIdx[string[i]];
        if (value === undefined) {
            throw new SyntaxError(`Non-${name} character`);
        }
        // Append the bits to the buffer:
        buffer = (buffer << bitsPerChar) | value;
        bits += bitsPerChar;
        // Write out some bits if the buffer has a byte's worth:
        if (bits >= 8) {
            bits -= 8;
            out[written++] = 0xff & (buffer >> bits);
        }
    }
    // Verify that we have received just enough bits:
    if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {
        throw new SyntaxError('Unexpected end of data');
    }
    return out;
}
function encode(data, alphabet, bitsPerChar) {
    const pad = alphabet[alphabet.length - 1] === '=';
    const mask = (1 << bitsPerChar) - 1;
    let out = '';
    let bits = 0; // Number of bits currently in the buffer
    let buffer = 0; // Bits waiting to be written out, MSB first
    for (let i = 0; i < data.length; ++i) {
        // Slurp data into the buffer:
        buffer = (buffer << 8) | data[i];
        bits += 8;
        // Write out as much as we can:
        while (bits > bitsPerChar) {
            bits -= bitsPerChar;
            out += alphabet[mask & (buffer >> bits)];
        }
    }
    // Partial character:
    if (bits !== 0) {
        out += alphabet[mask & (buffer << (bitsPerChar - bits))];
    }
    // Add padding characters until we hit a byte boundary:
    if (pad) {
        while (((out.length * bitsPerChar) & 7) !== 0) {
            out += '=';
        }
    }
    return out;
}
function createAlphabetIdx(alphabet) {
    // Build the character lookup table:
    const alphabetIdx = {};
    for (let i = 0; i < alphabet.length; ++i) {
        alphabetIdx[alphabet[i]] = i;
    }
    return alphabetIdx;
}
/**
 * RFC4648 Factory
 */
export function rfc4648({ name, prefix, bitsPerChar, alphabet }) {
    const alphabetIdx = createAlphabetIdx(alphabet);
    return from({
        prefix,
        name,
        encode(input) {
            return encode(input, alphabet, bitsPerChar);
        },
        decode(input) {
            return decode(input, alphabetIdx, bitsPerChar, name);
        }
    });
}
//# sourceMappingURL=base.js.mapimport { rfc4648 } from './base.js';
export const base32 = rfc4648({
    prefix: 'b',
    name: 'base32',
    alphabet: 'abcdefghijklmnopqrstuvwxyz234567',
    bitsPerChar: 5
});
export const base32upper = rfc4648({
    prefix: 'B',
    name: 'base32upper',
    alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',
    bitsPerChar: 5
});
export const base32pad = rfc4648({
    prefix: 'c',
    name: 'base32pad',
    alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',
    bitsPerChar: 5
});
export const base32padupper = rfc4648({
    prefix: 'C',
    name: 'base32padupper',
    alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',
    bitsPerChar: 5
});
export const base32hex = rfc4648({
    prefix: 'v',
    name: 'base32hex',
    alphabet: '0123456789abcdefghijklmnopqrstuv',
    bitsPerChar: 5
});
export const base32hexupper = rfc4648({
    prefix: 'V',
    name: 'base32hexupper',
    alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',
    bitsPerChar: 5
});
export const base32hexpad = rfc4648({
    prefix: 't',
    name: 'base32hexpad',
    alphabet: '0123456789abcdefghijklmnopqrstuv=',
    bitsPerChar: 5
});
export const base32hexpadupper = rfc4648({
    prefix: 'T',
    name: 'base32hexpadupper',
    alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',
    bitsPerChar: 5
});
export const base32z = rfc4648({
    prefix: 'h',
    name: 'base32z',
    alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',
    bitsPerChar: 5
});
//# sourceMappingURL=base32.js.mapimport { baseX } from './base.js';
export const base36 = baseX({
    prefix: 'k',
    name: 'base36',
    alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'
});
export const base36upper = baseX({
    prefix: 'K',
    name: 'base36upper',
    alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
});
//# sourceMappingURL=base36.js.mapimport { baseX } from './base.js';
export const base58btc = baseX({
    name: 'base58btc',
    prefix: 'z',
    alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
});
export const base58flickr = baseX({
    name: 'base58flickr',
    prefix: 'Z',
    alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'
});
//# sourceMappingURL=base58.js.mapexport const empty = new Uint8Array(0);
export function toHex(d) {
    return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '');
}
export function fromHex(hex) {
    const hexes = hex.match(/../g);
    return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty;
}
export function equals(aa, bb) {
    if (aa === bb) {
        return true;
    }
    if (aa.byteLength !== bb.byteLength) {
        return false;
    }
    for (let ii = 0; ii < aa.byteLength; ii++) {
        if (aa[ii] !== bb[ii]) {
            return false;
        }
    }
    return true;
}
export function coerce(o) {
    if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') {
        return o;
    }
    if (o instanceof ArrayBuffer) {
        return new Uint8Array(o);
    }
    if (ArrayBuffer.isView(o)) {
        return new Uint8Array(o.buffer, o.byteOffset, o.byteLength);
    }
    throw new Error('Unknown type, must be binary type');
}
export function isBinary(o) {
    return o instanceof ArrayBuffer || ArrayBuffer.isView(o);
}
export function fromString(str) {
    return new TextEncoder().encode(str);
}
export function toString(b) {
    return new TextDecoder().decode(b);
}
//# sourceMappingURL=bytes.js.mapimport { base32 } from './bases/base32.js';
import { base36 } from './bases/base36.js';
import { base58btc } from './bases/base58.js';
import { coerce } from './bytes.js';
import * as Digest from './hashes/digest.js';
import * as varint from './varint.js';
// This way TS will also expose all the types from module
export * from './link/interface.js';
export function format(link, base) {
    const { bytes, version } = link;
    switch (version) {
        case 0:
            return toStringV0(bytes, baseCache(link), base ?? base58btc.encoder);
        default:
            return toStringV1(bytes, baseCache(link), (base ?? base32.encoder));
    }
}
export function toJSON(link) {
    return {
        '/': format(link)
    };
}
export function fromJSON(json) {
    return CID.parse(json['/']);
}
const cache = new WeakMap();
function baseCache(cid) {
    const baseCache = cache.get(cid);
    if (baseCache == null) {
        const baseCache = new Map();
        cache.set(cid, baseCache);
        return baseCache;
    }
    return baseCache;
}
export class CID {
    code;
    version;
    multihash;
    bytes;
    '/';
    /**
     * @param version - Version of the CID
     * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
     * @param multihash - (Multi)hash of the of the content.
     */
    constructor(version, code, multihash, bytes) {
        this.code = code;
        this.version = version;
        this.multihash = multihash;
        this.bytes = bytes;
        // flag to serializers that this is a CID and
        // should be treated specially
        this['/'] = bytes;
    }
    /**
     * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`
     * please either use `CID.asCID(cid)` or switch to new signalling mechanism
     *
     * @deprecated
     */
    get asCID() {
        return this;
    }
    // ArrayBufferView
    get byteOffset() {
        return this.bytes.byteOffset;
    }
    // ArrayBufferView
    get byteLength() {
        return this.bytes.byteLength;
    }
    toV0() {
        switch (this.version) {
            case 0: {
                return this;
            }
            case 1: {
                const { code, multihash } = this;
                if (code !== DAG_PB_CODE) {
                    throw new Error('Cannot convert a non dag-pb CID to CIDv0');
                }
                // sha2-256
                if (multihash.code !== SHA_256_CODE) {
                    throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0');
                }
                return (CID.createV0(multihash));
            }
            default: {
                throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);
            }
        }
    }
    toV1() {
        switch (this.version) {
            case 0: {
                const { code, digest } = this.multihash;
                const multihash = Digest.create(code, digest);
                return (CID.createV1(this.code, multihash));
            }
            case 1: {
                return this;
            }
            default: {
                throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);
            }
        }
    }
    equals(other) {
        return CID.equals(this, other);
    }
    static equals(self, other) {
        const unknown = other;
        return (unknown != null &&
            self.code === unknown.code &&
            self.version === unknown.version &&
            Digest.equals(self.multihash, unknown.multihash));
    }
    toString(base) {
        return format(this, base);
    }
    toJSON() {
        return { '/': format(this) };
    }
    link() {
        return this;
    }
    [Symbol.toStringTag] = 'CID';
    // Legacy
    [Symbol.for('nodejs.util.inspect.custom')]() {
        return `CID(${this.toString()})`;
    }
    /**
     * Takes any input `value` and returns a `CID` instance if it was
     * a `CID` otherwise returns `null`. If `value` is instanceof `CID`
     * it will return value back. If `value` is not instance of this CID
     * class, but is compatible CID it will return new instance of this
     * `CID` class. Otherwise returns null.
     *
     * This allows two different incompatible versions of CID library to
     * co-exist and interop as long as binary interface is compatible.
     */
    static asCID(input) {
        if (input == null) {
            return null;
        }
        const value = input;
        if (value instanceof CID) {
            // If value is instance of CID then we're all set.
            return value;
        }
        else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {
            // If value isn't instance of this CID class but `this.asCID === this` or
            // `value['/'] === value.bytes` is true it is CID instance coming from a
            // different implementation (diff version or duplicate). In that case we
            // rebase it to this `CID` implementation so caller is guaranteed to get
            // instance with expected API.
            const { version, code, multihash, bytes } = value;
            return new CID(version, code, multihash, bytes ?? encodeCID(version, code, multihash.bytes));
        }
        else if (value[cidSymbol] === true) {
            // If value is a CID from older implementation that used to be tagged via
            // symbol we still rebase it to the this `CID` implementation by
            // delegating that to a constructor.
            const { version, multihash, code } = value;
            const digest = Digest.decode(multihash);
            return CID.create(version, code, digest);
        }
        else {
            // Otherwise value is not a CID (or an incompatible version of it) in
            // which case we return `null`.
            return null;
        }
    }
    /**
     * @param version - Version of the CID
     * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
     * @param digest - (Multi)hash of the of the content.
     */
    static create(version, code, digest) {
        if (typeof code !== 'number') {
            throw new Error('String codecs are no longer supported');
        }
        if (!(digest.bytes instanceof Uint8Array)) {
            throw new Error('Invalid digest');
        }
        switch (version) {
            case 0: {
                if (code !== DAG_PB_CODE) {
                    throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);
                }
                else {
                    return new CID(version, code, digest, digest.bytes);
                }
            }
            case 1: {
                const bytes = encodeCID(version, code, digest.bytes);
                return new CID(version, code, digest, bytes);
            }
            default: {
                throw new Error('Invalid version');
            }
        }
    }
    /**
     * Simplified version of `create` for CIDv0.
     */
    static createV0(digest) {
        return CID.create(0, DAG_PB_CODE, digest);
    }
    /**
     * Simplified version of `create` for CIDv1.
     *
     * @param code - Content encoding format code.
     * @param digest - Multihash of the content.
     */
    static createV1(code, digest) {
        return CID.create(1, code, digest);
    }
    /**
     * Decoded a CID from its binary representation. The byte array must contain
     * only the CID with no additional bytes.
     *
     * An error will be thrown if the bytes provided do not contain a valid
     * binary representation of a CID.
     */
    static decode(bytes) {
        const [cid, remainder] = CID.decodeFirst(bytes);
        if (remainder.length !== 0) {
            throw new Error('Incorrect length');
        }
        return cid;
    }
    /**
     * Decoded a CID from its binary representation at the beginning of a byte
     * array.
     *
     * Returns an array with the first element containing the CID and the second
     * element containing the remainder of the original byte array. The remainder
     * will be a zero-length byte array if the provided bytes only contained a
     * binary CID representation.
     */
    static decodeFirst(bytes) {
        const specs = CID.inspectBytes(bytes);
        const prefixSize = specs.size - specs.multihashSize;
        const multihashBytes = coerce(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));
        if (multihashBytes.byteLength !== specs.multihashSize) {
            throw new Error('Incorrect length');
        }
        const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);
        const digest = new Digest.Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);
        const cid = specs.version === 0
            ? CID.createV0(digest)
            : CID.createV1(specs.codec, digest);
        return [cid, bytes.subarray(specs.size)];
    }
    /**
     * Inspect the initial bytes of a CID to determine its properties.
     *
     * Involves decoding up to 4 varints. Typically this will require only 4 to 6
     * bytes but for larger multicodec code values and larger multihash digest
     * lengths these varints can be quite large. It is recommended that at least
     * 10 bytes be made available in the `initialBytes` argument for a complete
     * inspection.
     */
    static inspectBytes(initialBytes) {
        let offset = 0;
        const next = () => {
            const [i, length] = varint.decode(initialBytes.subarray(offset));
            offset += length;
            return i;
        };
        let version = next();
        let codec = DAG_PB_CODE;
        if (version === 18) {
            // CIDv0
            version = 0;
            offset = 0;
        }
        else {
            codec = next();
        }
        if (version !== 0 && version !== 1) {
            throw new RangeError(`Invalid CID version ${version}`);
        }
        const prefixSize = offset;
        const multihashCode = next(); // multihash code
        const digestSize = next(); // multihash length
        const size = offset + digestSize;
        const multihashSize = size - prefixSize;
        return { version, codec, multihashCode, digestSize, multihashSize, size };
    }
    /**
     * Takes cid in a string representation and creates an instance. If `base`
     * decoder is not provided will use a default from the configuration. It will
     * throw an error if encoding of the CID is not compatible with supplied (or
     * a default decoder).
     */
    static parse(source, base) {
        const [prefix, bytes] = parseCIDtoBytes(source, base);
        const cid = CID.decode(bytes);
        if (cid.version === 0 && source[0] !== 'Q') {
            throw Error('Version 0 CID string must not include multibase prefix');
        }
        // Cache string representation to avoid computing it on `this.toString()`
        baseCache(cid).set(prefix, source);
        return cid;
    }
}
function parseCIDtoBytes(source, base) {
    switch (source[0]) {
        // CIDv0 is parsed differently
        case 'Q': {
            const decoder = base ?? base58btc;
            return [
                base58btc.prefix,
                decoder.decode(`${base58btc.prefix}${source}`)
            ];
        }
        case base58btc.prefix: {
            const decoder = base ?? base58btc;
            return [base58btc.prefix, decoder.decode(source)];
        }
        case base32.prefix: {
            const decoder = base ?? base32;
            return [base32.prefix, decoder.decode(source)];
        }
        case base36.prefix: {
            const decoder = base ?? base36;
            return [base36.prefix, decoder.decode(source)];
        }
        default: {
            if (base == null) {
                throw Error('To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided');
            }
            return [source[0], base.decode(source)];
        }
    }
}
function toStringV0(bytes, cache, base) {
    const { prefix } = base;
    if (prefix !== base58btc.prefix) {
        throw Error(`Cannot string encode V0 in ${base.name} encoding`);
    }
    const cid = cache.get(prefix);
    if (cid == null) {
        const cid = base.encode(bytes).slice(1);
        cache.set(prefix, cid);
        return cid;
    }
    else {
        return cid;
    }
}
function toStringV1(bytes, cache, base) {
    const { prefix } = base;
    const cid = cache.get(prefix);
    if (cid == null) {
        const cid = base.encode(bytes);
        cache.set(prefix, cid);
        return cid;
    }
    else {
        return cid;
    }
}
const DAG_PB_CODE = 0x70;
const SHA_256_CODE = 0x12;
function encodeCID(version, code, multihash) {
    const codeOffset = varint.encodingLength(version);
    const hashOffset = codeOffset + varint.encodingLength(code);
    const bytes = new Uint8Array(hashOffset + multihash.byteLength);
    varint.encodeTo(version, bytes, 0);
    varint.encodeTo(code, bytes, codeOffset);
    bytes.set(multihash, hashOffset);
    return bytes;
}
const cidSymbol = Symbol.for('@ipld/js-cid/CID');
//# sourceMappingURL=cid.js.mapimport { coerce, equals as equalBytes } from '../bytes.js';
import * as varint from '../varint.js';
/**
 * Creates a multihash digest.
 */
export function create(code, digest) {
    const size = digest.byteLength;
    const sizeOffset = varint.encodingLength(code);
    const digestOffset = sizeOffset + varint.encodingLength(size);
    const bytes = new Uint8Array(digestOffset + size);
    varint.encodeTo(code, bytes, 0);
    varint.encodeTo(size, bytes, sizeOffset);
    bytes.set(digest, digestOffset);
    return new Digest(code, size, digest, bytes);
}
/**
 * Turns bytes representation of multihash digest into an instance.
 */
export function decode(multihash) {
    const bytes = coerce(multihash);
    const [code, sizeOffset] = varint.decode(bytes);
    const [size, digestOffset] = varint.decode(bytes.subarray(sizeOffset));
    const digest = bytes.subarray(sizeOffset + digestOffset);
    if (digest.byteLength !== size) {
        throw new Error('Incorrect length');
    }
    return new Digest(code, size, digest, bytes);
}
export function equals(a, b) {
    if (a === b) {
        return true;
    }
    else {
        const data = b;
        return (a.code === data.code &&
            a.size === data.size &&
            data.bytes instanceof Uint8Array &&
            equalBytes(a.bytes, data.bytes));
    }
}
/**
 * Represents a multihash digest which carries information about the
 * hashing algorithm and an actual hash digest.
 */
export class Digest {
    code;
    size;
    digest;
    bytes;
    /**
     * Creates a multihash digest.
     */
    constructor(code, size, digest, bytes) {
        this.code = code;
        this.size = size;
        this.digest = digest;
        this.bytes = bytes;
    }
}
/**
 * Used to check that the passed multihash has the passed code
 */
export function hasCode(digest, code) {
    return digest.code === code;
}
//# sourceMappingURL=digest.js.mapexport {};
//# sourceMappingURL=interface.js.mapimport varint from './vendor/varint.js';
export function decode(data, offset = 0) {
    const code = varint.decode(data, offset);
    return [code, varint.decode.bytes];
}
export function encodeTo(int, target, offset = 0) {
    varint.encode(int, target, offset);
    return target;
}
export function encodingLength(int) {
    return varint.encodingLength(int);
}
//# sourceMappingURL=varint.js.map/* eslint-disable */
// base-x encoding / decoding
// Copyright (c) 2018 base-x contributors
// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)
// Distributed under the MIT software license, see the accompanying
// file LICENSE or http://www.opensource.org/licenses/mit-license.php.
/**
 * @param {string} ALPHABET
 * @param {any} name
 */
function base(ALPHABET, name) {
    if (ALPHABET.length >= 255) {
        throw new TypeError('Alphabet too long');
    }
    var BASE_MAP = new Uint8Array(256);
    for (var j = 0; j < BASE_MAP.length; j++) {
        BASE_MAP[j] = 255;
    }
    for (var i = 0; i < ALPHABET.length; i++) {
        var x = ALPHABET.charAt(i);
        var xc = x.charCodeAt(0);
        if (BASE_MAP[xc] !== 255) {
            throw new TypeError(x + ' is ambiguous');
        }
        BASE_MAP[xc] = i;
    }
    var BASE = ALPHABET.length;
    var LEADER = ALPHABET.charAt(0);
    var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up
    var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up
    /**
     * @param {any[] | Iterable<number>} source
     */
    function encode(source) {
        // @ts-ignore
        if (source instanceof Uint8Array)
            ;
        else if (ArrayBuffer.isView(source)) {
            source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
        }
        else if (Array.isArray(source)) {
            source = Uint8Array.from(source);
        }
        if (!(source instanceof Uint8Array)) {
            throw new TypeError('Expected Uint8Array');
        }
        if (source.length === 0) {
            return '';
        }
        // Skip & count leading zeroes.
        var zeroes = 0;
        var length = 0;
        var pbegin = 0;
        var pend = source.length;
        while (pbegin !== pend && source[pbegin] === 0) {
            pbegin++;
            zeroes++;
        }
        // Allocate enough space in big-endian base58 representation.
        var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;
        var b58 = new Uint8Array(size);
        // Process the bytes.
        while (pbegin !== pend) {
            var carry = source[pbegin];
            // Apply "b58 = b58 * 256 + ch".
            var i = 0;
            for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {
                carry += (256 * b58[it1]) >>> 0;
                b58[it1] = (carry % BASE) >>> 0;
                carry = (carry / BASE) >>> 0;
            }
            if (carry !== 0) {
                throw new Error('Non-zero carry');
            }
            length = i;
            pbegin++;
        }
        // Skip leading zeroes in base58 result.
        var it2 = size - length;
        while (it2 !== size && b58[it2] === 0) {
            it2++;
        }
        // Translate the result into a string.
        var str = LEADER.repeat(zeroes);
        for (; it2 < size; ++it2) {
            str += ALPHABET.charAt(b58[it2]);
        }
        return str;
    }
    /**
     * @param {string | string[]} source
     */
    function decodeUnsafe(source) {
        if (typeof source !== 'string') {
            throw new TypeError('Expected String');
        }
        if (source.length === 0) {
            return new Uint8Array();
        }
        var psz = 0;
        // Skip leading spaces.
        if (source[psz] === ' ') {
            return;
        }
        // Skip and count leading '1's.
        var zeroes = 0;
        var length = 0;
        while (source[psz] === LEADER) {
            zeroes++;
            psz++;
        }
        // Allocate enough space in big-endian base256 representation.
        var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.
        var b256 = new Uint8Array(size);
        // Process the characters.
        while (source[psz]) {
            // Decode character
            var carry = BASE_MAP[source.charCodeAt(psz)];
            // Invalid character
            if (carry === 255) {
                return;
            }
            var i = 0;
            for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {
                carry += (BASE * b256[it3]) >>> 0;
                b256[it3] = (carry % 256) >>> 0;
                carry = (carry / 256) >>> 0;
            }
            if (carry !== 0) {
                throw new Error('Non-zero carry');
            }
            length = i;
            psz++;
        }
        // Skip trailing spaces.
        if (source[psz] === ' ') {
            return;
        }
        // Skip leading zeroes in b256.
        var it4 = size - length;
        while (it4 !== size && b256[it4] === 0) {
            it4++;
        }
        var vch = new Uint8Array(zeroes + (size - it4));
        var j = zeroes;
        while (it4 !== size) {
            vch[j++] = b256[it4++];
        }
        return vch;
    }
    /**
     * @param {string | string[]} string
     */
    function decode(string) {
        var buffer = decodeUnsafe(string);
        if (buffer) {
            return buffer;
        }
        throw new Error(`Non-${name} character`);
    }
    return {
        encode: encode,
        decodeUnsafe: decodeUnsafe,
        decode: decode
    };
}
var src = base;
var _brrp__multiformats_scope_baseX = src;
export default _brrp__multiformats_scope_baseX;
//# sourceMappingURL=base-x.js.map/* eslint-disable */
var encode_1 = encode;
var MSB = 0x80, REST = 0x7F, MSBALL = ~REST, INT = Math.pow(2, 31);
/**
 * @param {number} num
 * @param {number[]} out
 * @param {number} offset
 */
function encode(num, out, offset) {
    out = out || [];
    offset = offset || 0;
    var oldOffset = offset;
    while (num >= INT) {
        out[offset++] = (num & 0xFF) | MSB;
        num /= 128;
    }
    while (num & MSBALL) {
        out[offset++] = (num & 0xFF) | MSB;
        num >>>= 7;
    }
    out[offset] = num | 0;
    // @ts-ignore
    encode.bytes = offset - oldOffset + 1;
    return out;
}
var decode = read;
var MSB$1 = 0x80, REST$1 = 0x7F;
/**
 * @param {string | any[]} buf
 * @param {number} offset
 */
function read(buf, offset) {
    var res = 0, offset = offset || 0, shift = 0, counter = offset, b, l = buf.length;
    do {
        if (counter >= l) {
            // @ts-ignore
            read.bytes = 0;
            throw new RangeError('Could not decode varint');
        }
        b = buf[counter++];
        res += shift < 28
            ? (b & REST$1) << shift
            : (b & REST$1) * Math.pow(2, shift);
        shift += 7;
    } while (b >= MSB$1);
    // @ts-ignore
    read.bytes = counter - offset;
    return res;
}
var N1 = Math.pow(2, 7);
var N2 = Math.pow(2, 14);
var N3 = Math.pow(2, 21);
var N4 = Math.pow(2, 28);
var N5 = Math.pow(2, 35);
var N6 = Math.pow(2, 42);
var N7 = Math.pow(2, 49);
var N8 = Math.pow(2, 56);
var N9 = Math.pow(2, 63);
var length = function (/** @type {number} */ value) {
    return (value < N1 ? 1
        : value < N2 ? 2
            : value < N3 ? 3
                : value < N4 ? 4
                    : value < N5 ? 5
                        : value < N6 ? 6
                            : value < N7 ? 7
                                : value < N8 ? 8
                                    : value < N9 ? 9
                                        : 10);
};
var varint = {
    encode: encode_1,
    decode: decode,
    encodingLength: length
};
var _brrp_varint = varint;
export default _brrp_varint;
//# sourceMappingURL=varint.js.map{
  "name": "multiformats",
  "version": "13.4.2",
  "description": "Interface for multihash, multicodec, multibase and CID",
  "author": "Mikeal Rogers <mikeal.rogers@gmail.com> (https://www.mikealrogers.com/)",
  "license": "Apache-2.0 OR MIT",
  "homepage": "https://github.com/multiformats/js-multiformats#readme",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/multiformats/js-multiformats.git"
  },
  "bugs": {
    "url": "https://github.com/multiformats/js-multiformats/issues"
  },
  "publishConfig": {
    "access": "public",
    "provenance": true
  },
  "keywords": [
    "ipfs",
    "ipld",
    "multiformats"
  ],
  "type": "module",
  "types": "./dist/src/index.d.ts",
  "typesVersions": {
    "*": {
      "*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ],
      "src/*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ]
    }
  },
  "files": [
    "src",
    "dist",
    "!dist/test",
    "!**/*.tsbuildinfo"
  ],
  "exports": {
    ".": {
      "types": "./dist/src/index.d.ts",
      "import": "./dist/src/index.js"
    },
    "./bases/base10": {
      "types": "./dist/src/bases/base10.d.ts",
      "import": "./dist/src/bases/base10.js"
    },
    "./bases/base16": {
      "types": "./dist/src/bases/base16.d.ts",
      "import": "./dist/src/bases/base16.js"
    },
    "./bases/base2": {
      "types": "./dist/src/bases/base2.d.ts",
      "import": "./dist/src/bases/base2.js"
    },
    "./bases/base256emoji": {
      "types": "./dist/src/bases/base256emoji.d.ts",
      "import": "./dist/src/bases/base256emoji.js"
    },
    "./bases/base32": {
      "types": "./dist/src/bases/base32.d.ts",
      "import": "./dist/src/bases/base32.js"
    },
    "./bases/base36": {
      "types": "./dist/src/bases/base36.d.ts",
      "import": "./dist/src/bases/base36.js"
    },
    "./bases/base58": {
      "types": "./dist/src/bases/base58.d.ts",
      "import": "./dist/src/bases/base58.js"
    },
    "./bases/base64": {
      "types": "./dist/src/bases/base64.d.ts",
      "import": "./dist/src/bases/base64.js"
    },
    "./bases/base8": {
      "types": "./dist/src/bases/base8.d.ts",
      "import": "./dist/src/bases/base8.js"
    },
    "./bases/identity": {
      "types": "./dist/src/bases/identity.d.ts",
      "import": "./dist/src/bases/identity.js"
    },
    "./bases/interface": {
      "types": "./dist/src/bases/interface.d.ts",
      "import": "./dist/src/bases/interface.js"
    },
    "./basics": {
      "types": "./dist/src/basics.d.ts",
      "import": "./dist/src/basics.js"
    },
    "./block": {
      "types": "./dist/src/block.d.ts",
      "import": "./dist/src/block.js"
    },
    "./block/interface": {
      "types": "./dist/src/block/interface.d.ts",
      "import": "./dist/src/block/interface.js"
    },
    "./bytes": {
      "types": "./dist/src/bytes.d.ts",
      "import": "./dist/src/bytes.js"
    },
    "./cid": {
      "types": "./dist/src/cid.d.ts",
      "import": "./dist/src/cid.js"
    },
    "./codecs/interface": {
      "types": "./dist/src/codecs/interface.d.ts",
      "import": "./dist/src/codecs/interface.js"
    },
    "./codecs/json": {
      "types": "./dist/src/codecs/json.d.ts",
      "import": "./dist/src/codecs/json.js"
    },
    "./codecs/raw": {
      "types": "./dist/src/codecs/raw.d.ts",
      "import": "./dist/src/codecs/raw.js"
    },
    "./hashes/digest": {
      "types": "./dist/src/hashes/digest.d.ts",
      "import": "./dist/src/hashes/digest.js"
    },
    "./hashes/hasher": {
      "types": "./dist/src/hashes/hasher.d.ts",
      "import": "./dist/src/hashes/hasher.js"
    },
    "./hashes/identity": {
      "types": "./dist/src/hashes/identity.d.ts",
      "import": "./dist/src/hashes/identity.js"
    },
    "./hashes/interface": {
      "types": "./dist/src/hashes/interface.d.ts",
      "import": "./dist/src/hashes/interface.js"
    },
    "./hashes/sha1": {
      "types": "./dist/types/src/hashes/sha1.d.ts",
      "browser": "./dist/src/hashes/sha1-browser.js",
      "import": "./dist/src/hashes/sha1.js"
    },
    "./hashes/sha2": {
      "types": "./dist/src/hashes/sha2.d.ts",
      "browser": "./dist/src/hashes/sha2-browser.js",
      "import": "./dist/src/hashes/sha2.js"
    },
    "./interface": {
      "types": "./dist/src/interface.d.ts",
      "import": "./dist/src/interface.js"
    },
    "./link": {
      "types": "./dist/src/link.d.ts",
      "import": "./dist/src/link.js"
    },
    "./link/interface": {
      "types": "./dist/src/link/interface.d.ts",
      "import": "./dist/src/link/interface.js"
    },
    "./traversal": {
      "types": "./dist/src/traversal.d.ts",
      "import": "./dist/src/traversal.js"
    }
  },
  "eslintConfig": {
    "extends": "ipfs",
    "parserOptions": {
      "project": true,
      "sourceType": "module"
    }
  },
  "release": {
    "branches": [
      "master"
    ],
    "plugins": [
      [
        "@semantic-release/commit-analyzer",
        {
          "preset": "conventionalcommits",
          "releaseRules": [
            {
              "breaking": true,
              "release": "major"
            },
            {
              "revert": true,
              "release": "patch"
            },
            {
              "type": "feat",
              "release": "minor"
            },
            {
              "type": "fix",
              "release": "patch"
            },
            {
              "type": "docs",
              "release": "patch"
            },
            {
              "type": "test",
              "release": "patch"
            },
            {
              "type": "deps",
              "release": "patch"
            },
            {
              "scope": "no-release",
              "release": false
            }
          ]
        }
      ],
      [
        "@semantic-release/release-notes-generator",
        {
          "preset": "conventionalcommits",
          "presetConfig": {
            "types": [
              {
                "type": "feat",
                "section": "Features"
              },
              {
                "type": "fix",
                "section": "Bug Fixes"
              },
              {
                "type": "chore",
                "section": "Trivial Changes"
              },
              {
                "type": "docs",
                "section": "Documentation"
              },
              {
                "type": "deps",
                "section": "Dependencies"
              },
              {
                "type": "test",
                "section": "Tests"
              }
            ]
          }
        }
      ],
      "@semantic-release/changelog",
      "@semantic-release/npm",
      "@semantic-release/github",
      [
        "@semantic-release/git",
        {
          "assets": [
            "CHANGELOG.md",
            "package.json"
          ]
        }
      ]
    ]
  },
  "scripts": {
    "clean": "aegir clean",
    "lint": "aegir lint",
    "build": "aegir build",
    "release": "aegir release",
    "docs": "aegir docs",
    "test": "npm run lint && npm run test:node && npm run test:chrome",
    "test:node": "aegir test -t node --cov",
    "test:chrome": "aegir test -t browser --cov",
    "test:chrome-webworker": "aegir test -t webworker",
    "test:firefox": "aegir test -t browser -- --browser firefox",
    "test:firefox-webworker": "aegir test -t webworker -- --browser firefox",
    "test:electron-main": "aegir test -t electron-main"
  },
  "devDependencies": {
    "@stablelib/sha256": "^2.0.0",
    "@stablelib/sha512": "^2.0.0",
    "@types/node": "^25.0.0",
    "aegir": "^47.0.7",
    "buffer": "^6.0.3",
    "cids": "^1.1.9",
    "crypto-hash": "^4.0.0"
  },
  "aegir": {
    "test": {
      "target": [
        "node",
        "browser"
      ]
    }
  },
  "browser": {
    "./hashes/sha1": "./dist/src/hashes/sha1-browser.js",
    "./dist/src/hashes/sha1.js": "./dist/src/hashes/sha1-browser.js",
    "./hashes/sha2": "./dist/src/hashes/sha2-browser.js",
    "./dist/src/hashes/sha2.js": "./dist/src/hashes/sha2-browser.js"
  }
}
var queueTick = require('queue-tick')

var mutexify = function () {
  var queue = []
  var used = null

  var call = function () {
    used(release)
  }

  var acquire = function (fn) {
    if (used) return queue.push(fn)
    used = fn
    acquire.locked = true
    queueTick(call)
    return 0
  }

  acquire.locked = false

  var release = function (fn, err, value) {
    used = null
    acquire.locked = false
    if (queue.length) acquire(queue.shift())
    if (fn) fn(err, value)
  }

  return acquire
}

module.exports = mutexify
{
  "name": "mutexify",
  "version": "1.4.0",
  "description": "mutex lock for javascript",
  "main": "index.js",
  "dependencies": {
    "queue-tick": "^1.0.0"
  },
  "devDependencies": {
    "standard": "^14.3.3",
    "tape": "^3.0.2"
  },
  "scripts": {
    "test": "tape test.js",
    "posttest": "npm run lint",
    "lint": "standard"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/mutexify.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/mutexify/issues"
  },
  "keywords": [
    "mutex",
    "lock"
  ],
  "homepage": "https://github.com/mafintosh/mutexify"
}
var mutexify = require('.')

var mutexifyPromise = function () {
  var lock = mutexify()

  var acquire = function () {
    return new Promise(lock)
  }

  Object.defineProperty(acquire, 'locked', {
    get: function () { return lock.locked },
    enumerable: true
  })

  return acquire
}

module.exports = mutexifyPromise
module.exports = assert

class AssertionError extends Error {}
AssertionError.prototype.name = 'AssertionError'

/**
 * Minimal assert function
 * @param  {any} t Value to check if falsy
 * @param  {string=} m Optional assertion error message
 * @throws {AssertionError}
 */
function assert (t, m) {
  if (!t) {
    var err = new AssertionError(m)
    if (Error.captureStackTrace) Error.captureStackTrace(err, assert)
    throw err
  }
}
{
  "name": "nanoassert",
  "version": "2.0.0",
  "description": "Nanoscale assertion module",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "tape": "^4.9.1"
  },
  "scripts": {
    "test": "tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/emilbayes/nanoassert.git"
  },
  "keywords": [
    "assert",
    "unassert",
    "power-assert",
    "tiny",
    "nano",
    "pico"
  ],
  "author": "Emil Bay <github@tixz.dk>",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/emilbayes/nanoassert/issues"
  },
  "homepage": "https://github.com/emilbayes/nanoassert#readme"
}
/* eslint-disable camelcase */
const sodium = require('sodium-universal')
const assert = require('nanoassert')
const b4a = require('b4a')

const DHLEN = sodium.crypto_scalarmult_ed25519_BYTES
const PKLEN = sodium.crypto_scalarmult_ed25519_BYTES
const SCALARLEN = sodium.crypto_scalarmult_ed25519_BYTES
const SKLEN = sodium.crypto_sign_SECRETKEYBYTES
const ALG = 'Ed25519'

module.exports = {
  DHLEN,
  PKLEN,
  SCALARLEN,
  SKLEN,
  ALG,
  name: ALG,
  generateKeyPair,
  dh
}

function generateKeyPair (privKey) {
  if (privKey) return generateSeedKeyPair(privKey.subarray(0, 32))

  const keyPair = {}
  keyPair.secretKey = b4a.alloc(SKLEN)
  keyPair.publicKey = b4a.alloc(PKLEN)

  sodium.crypto_sign_keypair(keyPair.publicKey, keyPair.secretKey)
  return keyPair
}

function generateSeedKeyPair (seed) {
  const keyPair = {}
  keyPair.secretKey = b4a.alloc(SKLEN)
  keyPair.publicKey = b4a.alloc(PKLEN)

  sodium.crypto_sign_seed_keypair(keyPair.publicKey, keyPair.secretKey, seed)
  return keyPair
}

function dh (publicKey, { scalar, secretKey }) {
  // tweaked keys expose scalar directly
  if (!scalar) {
    assert(secretKey.byteLength === SKLEN)

    // libsodium stores seed not actual scalar
    const sk = b4a.alloc(64)
    sodium.crypto_hash_sha512(sk, secretKey.subarray(0, 32))
    sk[0] &= 248
    sk[31] &= 127
    sk[31] |= 64

    scalar = sk.subarray(0, 32)
  }

  assert(scalar.byteLength === SCALARLEN)
  assert(publicKey.byteLength === PKLEN)

  const output = b4a.alloc(DHLEN)

  // we clamp if necessary above
  sodium.crypto_scalarmult_ed25519_noclamp(
    output,
    scalar,
    publicKey
  )

  return output
}
{
  "name": "noise-curve-ed",
  "version": "2.1.0",
  "description": "Ed25519 elliptic curve operations for [`noise-handshake`](https://github.com/chm-diederichs/noise-handshake)",
  "main": "index.js",
  "scripts": {
    "test": "npx standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/chm-diederichs/noise-curve-ed.git"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/chm-diederichs/noise-curve-ed/issues"
  },
  "homepage": "https://github.com/chm-diederichs/noise-curve-ed#readme",
  "dependencies": {
    "b4a": "^1.1.0",
    "nanoassert": "^2.0.0",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "noise-handshake": "^3.0.0",
    "standard": "^16.0.3",
    "tape": "^5.2.2"
  }
}
const sodium = require('sodium-universal')
const b4a = require('b4a')

module.exports = class CipherState {
  constructor (key) {
    this.key = key || null
    this.nonce = 0
    this.CIPHER_ALG = 'ChaChaPoly'
  }

  initialiseKey (key) {
    this.key = key
    this.nonce = 0
  }

  setNonce (nonce) {
    this.nonce = nonce
  }

  encrypt (plaintext, ad) {
    if (!this.hasKey) return plaintext
    if (!ad) ad = b4a.alloc(0)

    const ciphertext = encryptWithAD(this.key, this.nonce, ad, plaintext)
    if (ciphertext.length > 65535) throw new Error(`ciphertext length of ${ciphertext.length} exceeds maximum Noise message length of 65535`)
    this.nonce++

    return ciphertext
  }

  decrypt (ciphertext, ad) {
    if (!this.hasKey) return ciphertext
    if (!ad) ad = b4a.alloc(0)
    if (ciphertext.length > 65535) throw new Error(`ciphertext length of ${ciphertext.length} exceeds maximum Noise message length of 65535`)

    const plaintext = decryptWithAD(this.key, this.nonce, ad, ciphertext)
    this.nonce++

    return plaintext
  }

  get hasKey () {
    return this.key !== null
  }

  _clear () {
    sodium.sodium_memzero(this.key)
    this.key = null
    this.nonce = null
  }

  static get MACBYTES () {
    return 16
  }

  static get NONCEBYTES () {
    return 8
  }

  static get KEYBYTES () {
    return 32
  }
}

function encryptWithAD (key, counter, additionalData, plaintext) {
  // for our purposes, additionalData will always be a pubkey so we encode from hex
  if (!b4a.isBuffer(additionalData)) additionalData = b4a.from(additionalData, 'hex')
  if (!b4a.isBuffer(plaintext)) plaintext = b4a.from(plaintext, 'hex')

  const nonce = b4a.alloc(sodium.crypto_aead_chacha20poly1305_ietf_NPUBBYTES)
  const view = new DataView(nonce.buffer, nonce.byteOffset, nonce.byteLength)
  view.setUint32(4, counter, true)

  const ciphertext = b4a.alloc(plaintext.byteLength + sodium.crypto_aead_chacha20poly1305_ietf_ABYTES)

  sodium.crypto_aead_chacha20poly1305_ietf_encrypt(ciphertext, plaintext, additionalData, null, nonce, key)
  return ciphertext
}

function decryptWithAD (key, counter, additionalData, ciphertext) {
  // for our purposes, additionalData will always be a pubkey so we encode from hex
  if (!b4a.isBuffer(additionalData)) additionalData = b4a.from(additionalData, 'hex')
  if (!b4a.isBuffer(ciphertext)) ciphertext = b4a.from(ciphertext, 'hex')

  const nonce = b4a.alloc(sodium.crypto_aead_chacha20poly1305_ietf_NPUBBYTES)
  const view = new DataView(nonce.buffer, nonce.byteOffset, nonce.byteLength)
  view.setUint32(4, counter, true)

  const plaintext = b4a.alloc(ciphertext.byteLength - sodium.crypto_aead_chacha20poly1305_ietf_ABYTES)

  sodium.crypto_aead_chacha20poly1305_ietf_decrypt(plaintext, null, ciphertext, additionalData, nonce, key)
  return plaintext
}
/* eslint-disable camelcase */
const {
  crypto_kx_SEEDBYTES,
  crypto_kx_keypair,
  crypto_kx_seed_keypair,
  crypto_scalarmult_BYTES,
  crypto_scalarmult_SCALARBYTES,
  crypto_scalarmult,
  crypto_scalarmult_base
} = require('sodium-universal')

const assert = require('nanoassert')
const b4a = require('b4a')

const DHLEN = crypto_scalarmult_BYTES
const PKLEN = crypto_scalarmult_BYTES
const SKLEN = crypto_scalarmult_SCALARBYTES
const SEEDLEN = crypto_kx_SEEDBYTES
const ALG = '25519'

module.exports = {
  DHLEN,
  PKLEN,
  SKLEN,
  SEEDLEN,
  ALG,
  generateKeyPair,
  generateSeedKeyPair,
  dh
}

function generateKeyPair (privKey) {
  const keyPair = {}

  keyPair.secretKey = privKey || b4a.alloc(SKLEN)
  keyPair.publicKey = b4a.alloc(PKLEN)

  if (privKey) {
    crypto_scalarmult_base(keyPair.publicKey, keyPair.secretKey)
  } else {
    crypto_kx_keypair(keyPair.publicKey, keyPair.secretKey)
  }

  return keyPair
}

function generateSeedKeyPair (seed) {
  assert(seed.byteLength === SKLEN)

  const keyPair = {}
  keyPair.secretKey = b4a.alloc(SKLEN)
  keyPair.publicKey = b4a.alloc(PKLEN)

  crypto_kx_seed_keypair(keyPair.publicKey, keyPair.secretKey, seed)
  return keyPair
}

function dh (publicKey, { secretKey }) {
  assert(secretKey.byteLength === SKLEN)
  assert(publicKey.byteLength === PKLEN)

  const output = b4a.alloc(DHLEN)

  crypto_scalarmult(
    output,
    secretKey,
    publicKey
  )

  return output
}
const hmacBlake2b = require('./hmac')
const b4a = require('b4a')

const HASHLEN = 64

module.exports = {
  hkdf,
  HASHLEN
}

// HMAC-based Extract-and-Expand KDF
// https://www.ietf.org/rfc/rfc5869.txt

function hkdf (salt, inputKeyMaterial, info = '', length = 2 * HASHLEN) {
  const pseudoRandomKey = hkdfExtract(salt, inputKeyMaterial)
  return hkdfExpand(pseudoRandomKey, info, length)
}

function hkdfExtract (salt, inputKeyMaterial) {
  const hmac = b4a.alloc(HASHLEN)
  return hmacDigest(hmac, salt, inputKeyMaterial)
}

function hkdfExpand (key, info, length) {
  // Put in dedicated slab to avoid keeping shared slab from being gc'ed
  const buffer = b4a.allocUnsafeSlow(length)

  const infoBuf = b4a.from(info)
  let prev = infoBuf

  const result = []
  for (let i = 0; i < length; i += HASHLEN) {
    const pos = b4a.from([(i / HASHLEN) + 1])

    const out = buffer.subarray(i, i + HASHLEN)
    result.push(out)

    prev = hmacDigest(out, key, [prev, infoBuf, pos])
  }

  return result
}

function hmacDigest (out, key, input) {
  hmacBlake2b(out, input, key)
  return out
}
/* eslint-disable camelcase */
const b4a = require('b4a')
const { sodium_memzero, crypto_generichash, crypto_generichash_batch } = require('sodium-universal')

const HASHLEN = 64
const BLOCKLEN = 128
const scratch = b4a.alloc(BLOCKLEN * 3)
const HMACKey = scratch.subarray(BLOCKLEN * 0, BLOCKLEN * 1)
const OuterKeyPad = scratch.subarray(BLOCKLEN * 1, BLOCKLEN * 2)
const InnerKeyPad = scratch.subarray(BLOCKLEN * 2, BLOCKLEN * 3)

// Post-fill is done in the cases where someone caught an exception that
// happened before we were able to clear data at the end

module.exports = function hmac (out, batch, key) {
  if (key.byteLength > BLOCKLEN) {
    crypto_generichash(HMACKey.subarray(0, HASHLEN), key)
    sodium_memzero(HMACKey.subarray(HASHLEN))
  } else {
    // Covers key <= BLOCKLEN
    HMACKey.set(key)
    sodium_memzero(HMACKey.subarray(key.byteLength))
  }

  for (let i = 0; i < HMACKey.byteLength; i++) {
    OuterKeyPad[i] = 0x5c ^ HMACKey[i]
    InnerKeyPad[i] = 0x36 ^ HMACKey[i]
  }
  sodium_memzero(HMACKey)

  crypto_generichash_batch(out, [InnerKeyPad].concat(batch))
  sodium_memzero(InnerKeyPad)
  crypto_generichash_batch(out, [OuterKeyPad, out])
  sodium_memzero(OuterKeyPad)
}

module.exports.BYTES = HASHLEN
module.exports.KEYBYTES = BLOCKLEN
const assert = require('nanoassert')
const b4a = require('b4a')

const SymmetricState = require('./symmetric-state')
const { HASHLEN } = require('./hkdf')

const PRESHARE_IS = Symbol('initiator static key preshared')
const PRESHARE_RS = Symbol('responder static key preshared')

const TOK_PSK = Symbol('psk')

const TOK_S = Symbol('s')
const TOK_E = Symbol('e')

const TOK_ES = Symbol('es')
const TOK_SE = Symbol('se')
const TOK_EE = Symbol('ee')
const TOK_SS = Symbol('ss')

const HANDSHAKES = Object.freeze({
  NN: [
    [TOK_E],
    [TOK_E, TOK_EE]
  ],
  NNpsk0: [
    [TOK_PSK, TOK_E],
    [TOK_E, TOK_EE]
  ],
  XX: [
    [TOK_E],
    [TOK_E, TOK_EE, TOK_S, TOK_ES],
    [TOK_S, TOK_SE]
  ],
  XXpsk0: [
    [TOK_PSK, TOK_E],
    [TOK_E, TOK_EE, TOK_S, TOK_ES],
    [TOK_S, TOK_SE]
  ],
  IK: [
    PRESHARE_RS,
    [TOK_E, TOK_ES, TOK_S, TOK_SS],
    [TOK_E, TOK_EE, TOK_SE]
  ],
  XK: [
    PRESHARE_RS,
    [TOK_E, TOK_ES],
    [TOK_E, TOK_EE],
    [TOK_S, TOK_SE]
  ]
})

class Writer {
  constructor () {
    this.size = 0
    this.buffers = []
  }

  push (b) {
    this.size += b.byteLength
    this.buffers.push(b)
  }

  end () {
    const all = b4a.alloc(this.size)
    let offset = 0
    for (const b of this.buffers) {
      all.set(b, offset)
      offset += b.byteLength
    }
    return all
  }
}

class Reader {
  constructor (buf) {
    this.offset = 0
    this.buffer = buf
  }

  shift (n) {
    const start = this.offset
    const end = this.offset += n
    if (end > this.buffer.byteLength) throw new Error('Insufficient bytes')
    return this.buffer.subarray(start, end)
  }

  end () {
    return this.shift(this.buffer.byteLength - this.offset)
  }
}

module.exports = class NoiseState extends SymmetricState {
  constructor (pattern, initiator, staticKeypair, opts = {}) {
    super(opts)

    this.s = staticKeypair || this.curve.generateKeyPair()
    this.e = null

    this.psk = null
    if (opts && opts.psk) this.psk = opts.psk

    this.re = null
    this.rs = null

    this.pattern = pattern
    this.handshake = HANDSHAKES[this.pattern].slice()

    this.isPskHandshake = !!this.psk && hasPskToken(this.handshake)

    this.protocol = b4a.from([
      'Noise',
      this.pattern,
      this.DH_ALG,
      this.CIPHER_ALG,
      'BLAKE2b'
    ].join('_'))

    this.initiator = initiator
    this.complete = false

    this.rx = null
    this.tx = null
    this.hash = null
  }

  initialise (prologue, remoteStatic) {
    if (this.protocol.byteLength <= HASHLEN) this.digest.set(this.protocol)
    else this.mixHash(this.protocol)

    this.chainingKey = b4a.from(this.digest)

    this.mixHash(prologue)

    while (!Array.isArray(this.handshake[0])) {
      const message = this.handshake.shift()

      // handshake steps should be as arrays, only
      // preshare tokens are provided otherwise
      assert(message === PRESHARE_RS || message === PRESHARE_IS,
        'Unexpected pattern')

      const takeRemoteKey = this.initiator
        ? message === PRESHARE_RS
        : message === PRESHARE_IS

      if (takeRemoteKey) this.rs = remoteStatic

      const key = takeRemoteKey ? this.rs : this.s.publicKey
      assert(key != null, 'Remote pubkey required')

      this.mixHash(key)
    }
  }

  final () {
    const [k1, k2] = this.split()

    this.tx = this.initiator ? k1 : k2
    this.rx = this.initiator ? k2 : k1

    this.complete = true
    this.hash = this.getHandshakeHash()

    this._clear()
  }

  recv (buf) {
    const r = new Reader(buf)

    for (const pattern of this.handshake.shift()) {
      switch (pattern) {
        case TOK_PSK :
          this.mixKeyAndHash(this.psk)
          break

        case TOK_E :
          this.re = r.shift(this.curve.PKLEN)
          this.mixHash(this.re)
          if (this.isPskHandshake) this.mixKeyNormal(this.re)
          break

        case TOK_S : {
          const klen = this.hasKey ? this.curve.PKLEN + 16 : this.curve.PKLEN
          this.rs = this.decryptAndHash(r.shift(klen))
          break
        }

        case TOK_EE :
        case TOK_ES :
        case TOK_SE :
        case TOK_SS : {
          const useStatic = keyPattern(pattern, this.initiator)

          const localKey = useStatic.local ? this.s : this.e
          const remoteKey = useStatic.remote ? this.rs : this.re

          this.mixKey(remoteKey, localKey)
          break
        }

        default :
          throw new Error('Unexpected message')
      }
    }

    const payload = this.decryptAndHash(r.end())

    if (!this.handshake.length) this.final()
    return payload
  }

  send (payload = b4a.alloc(0)) {
    const w = new Writer()

    for (const pattern of this.handshake.shift()) {
      switch (pattern) {
        case TOK_PSK :
          this.mixKeyAndHash(this.psk)
          break

        case TOK_E :
          if (this.e === null) this.e = this.curve.generateKeyPair()
          this.mixHash(this.e.publicKey)
          if (this.isPskHandshake) this.mixKeyNormal(this.e.publicKey)
          w.push(this.e.publicKey)
          break

        case TOK_S :
          w.push(this.encryptAndHash(this.s.publicKey))
          break

        case TOK_ES :
        case TOK_SE :
        case TOK_EE :
        case TOK_SS : {
          const useStatic = keyPattern(pattern, this.initiator)

          const localKey = useStatic.local ? this.s : this.e
          const remoteKey = useStatic.remote ? this.rs : this.re

          this.mixKey(remoteKey, localKey)
          break
        }

        default :
          throw new Error('Unexpected message')
      }
    }

    w.push(this.encryptAndHash(payload))
    const response = w.end()

    if (!this.handshake.length) this.final()
    return response
  }

  _clear () {
    super._clear()

    this.e.secretKey.fill(0)
    this.e.publicKey.fill(0)

    this.re.fill(0)

    this.e = null
    this.re = null
  }
}

function keyPattern (pattern, initiator) {
  const ret = {
    local: false,
    remote: false
  }

  switch (pattern) {
    case TOK_EE:
      return ret

    case TOK_ES:
      ret.local ^= !initiator
      ret.remote ^= initiator
      return ret

    case TOK_SE:
      ret.local ^= initiator
      ret.remote ^= !initiator
      return ret

    case TOK_SS:
      ret.local ^= 1
      ret.remote ^= 1
      return ret
  }
}

function hasPskToken (handshake) {
  return handshake.some(x => {
    return Array.isArray(x) && x.indexOf(TOK_PSK) !== -1
  })
}
{
  "name": "noise-handshake",
  "version": "4.2.0",
  "description": "Noise protocol handshake",
  "main": "noise.js",
  "files": [
    "*.js"
  ],
  "scripts": {
    "test": "standard && brittle test/*.js"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/noise-handshake.git"
  },
  "dependencies": {
    "b4a": "^1.1.0",
    "nanoassert": "^2.0.0",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "noise-protocol": "chm-diederichs/noise-protocol.git#xx-ephemeral-key",
    "standard": "^16.0.3"
  }
}
const sodium = require('sodium-universal')
const assert = require('nanoassert')
const b4a = require('b4a')
const CipherState = require('./cipher')
const curve = require('./dh')
const { HASHLEN, hkdf } = require('./hkdf')

module.exports = class SymmetricState extends CipherState {
  constructor (opts = {}) {
    super()

    this.curve = opts.curve || curve
    this.digest = b4a.alloc(HASHLEN)
    this.chainingKey = null
    this.offset = 0

    this.DH_ALG = this.curve.ALG
  }

  mixHash (data) {
    accumulateDigest(this.digest, data)
  }

  mixKeyAndHash (key) {
    const [ck, tempH, tempK] = hkdf(this.chainingKey, key, '', 3 * HASHLEN)
    this.chainingKey = ck
    this.mixHash(tempH)
    this.initialiseKey(tempK.subarray(0, 32))
  }

  mixKeyNormal (key) {
    const [ck, tempK] = hkdf(this.chainingKey, key)
    this.chainingKey = ck
    this.initialiseKey(tempK.subarray(0, 32))
  }

  mixKey (remoteKey, localKey) {
    const dh = this.curve.dh(remoteKey, localKey)
    const hkdfResult = hkdf(this.chainingKey, dh)
    this.chainingKey = hkdfResult[0]
    this.initialiseKey(hkdfResult[1].subarray(0, 32))
  }

  encryptAndHash (plaintext) {
    const ciphertext = this.encrypt(plaintext, this.digest)
    accumulateDigest(this.digest, ciphertext)
    return ciphertext
  }

  decryptAndHash (ciphertext) {
    const plaintext = this.decrypt(ciphertext, this.digest)
    accumulateDigest(this.digest, ciphertext)
    return plaintext
  }

  getHandshakeHash (out) {
    if (!out) return this.getHandshakeHash(b4a.alloc(HASHLEN))
    assert(out.byteLength === HASHLEN, `output must be ${HASHLEN} bytes`)

    out.set(this.digest)
    return out
  }

  split () {
    const res = hkdf(this.chainingKey, b4a.alloc(0))
    return res.map(k => k.subarray(0, 32))
  }

  _clear () {
    super._clear()

    sodium.sodium_memzero(this.digest)
    sodium.sodium_memzero(this.chainingKey)

    this.digest = null
    this.chainingKey = null
    this.offset = null

    this.curve = null
  }

  static get alg () {
    return CipherState.alg + '_BLAKE2b'
  }
}

function accumulateDigest (digest, input) {
  const toHash = b4a.concat([digest, input])
  sodium.crypto_generichash(digest, toHash)
}
var varint = require('varint')
var svarint = require('signed-varint')
var b4a = require('b4a')

exports.make = encoder

exports.name = function (enc) {
  var keys = Object.keys(exports)
  for (var i = 0; i < keys.length; i++) {
    if (exports[keys[i]] === enc) return keys[i]
  }
  return null
}

exports.skip = function (type, buffer, offset) {
  switch (type) {
    case 0:
      varint.decode(buffer, offset)
      return offset + varint.decode.bytes

    case 1:
      return offset + 8

    case 2:
      var len = varint.decode(buffer, offset)
      return offset + varint.decode.bytes + len

    case 3:
    case 4:
      throw new Error('Groups are not supported')

    case 5:
      return offset + 4
  }

  throw new Error('Unknown wire type: ' + type)
}

exports.bytes = encoder(2,
  function encode (val, buffer, offset) {
    var oldOffset = offset
    var len = bufferLength(val)

    varint.encode(len, buffer, offset)
    offset += varint.encode.bytes

    if (b4a.isBuffer(val)) b4a.copy(val, buffer, offset)
    else b4a.write(buffer, val, offset, len)
    offset += len

    encode.bytes = offset - oldOffset
    return buffer
  },
  function decode (buffer, offset) {
    var oldOffset = offset

    var len = varint.decode(buffer, offset)
    offset += varint.decode.bytes

    var val = buffer.subarray(offset, offset + len)
    offset += val.length

    decode.bytes = offset - oldOffset
    return val
  },
  function encodingLength (val) {
    var len = bufferLength(val)
    return varint.encodingLength(len) + len
  }
)

exports.string = encoder(2,
  function encode (val, buffer, offset) {
    var oldOffset = offset
    var len = b4a.byteLength(val)

    varint.encode(len, buffer, offset, 'utf-8')
    offset += varint.encode.bytes

    b4a.write(buffer, val, offset, len)
    offset += len

    encode.bytes = offset - oldOffset
    return buffer
  },
  function decode (buffer, offset) {
    var oldOffset = offset

    var len = varint.decode(buffer, offset)
    offset += varint.decode.bytes

    var val = b4a.toString(buffer, 'utf-8', offset, offset + len)
    offset += len

    decode.bytes = offset - oldOffset
    return val
  },
  function encodingLength (val) {
    var len = b4a.byteLength(val)
    return varint.encodingLength(len) + len
  }
)

exports.bool = encoder(0,
  function encode (val, buffer, offset) {
    buffer[offset] = val ? 1 : 0
    encode.bytes = 1
    return buffer
  },
  function decode (buffer, offset) {
    var bool = buffer[offset] > 0
    decode.bytes = 1
    return bool
  },
  function encodingLength () {
    return 1
  }
)

exports.int32 = encoder(0,
  function encode (val, buffer, offset) {
    varint.encode(val < 0 ? val + 4294967296 : val, buffer, offset)
    encode.bytes = varint.encode.bytes
    return buffer
  },
  function decode (buffer, offset) {
    var val = varint.decode(buffer, offset)
    decode.bytes = varint.decode.bytes
    return val > 2147483647 ? val - 4294967296 : val
  },
  function encodingLength (val) {
    return varint.encodingLength(val < 0 ? val + 4294967296 : val)
  }
)

exports.int64 = encoder(0,
  function encode (val, buffer, offset) {
    if (val < 0) {
      var last = offset + 9
      varint.encode(val * -1, buffer, offset)
      offset += varint.encode.bytes - 1
      buffer[offset] = buffer[offset] | 0x80
      while (offset < last - 1) {
        offset++
        buffer[offset] = 0xff
      }
      buffer[last] = 0x01
      encode.bytes = 10
    } else {
      varint.encode(val, buffer, offset)
      encode.bytes = varint.encode.bytes
    }
    return buffer
  },
  function decode (buffer, offset) {
    var val = varint.decode(buffer, offset)
    if (val >= Math.pow(2, 63)) {
      var limit = 9
      while (buffer[offset + limit - 1] === 0xff) limit--
      limit = limit || 9
      var subset = b4a.allocUnsafe(limit)
      b4a.copy(buffer, subset, 0, offset, offset + limit)
      subset[limit - 1] = subset[limit - 1] & 0x7f
      val = -1 * varint.decode(subset, 0)
      decode.bytes = 10
    } else {
      decode.bytes = varint.decode.bytes
    }
    return val
  },
  function encodingLength (val) {
    return val < 0 ? 10 : varint.encodingLength(val)
  }
)

exports.sint32 =
exports.sint64 = encoder(0,
  svarint.encode,
  svarint.decode,
  svarint.encodingLength
)

exports.uint32 =
exports.uint64 =
exports.enum =
exports.varint = encoder(0,
  varint.encode,
  varint.decode,
  varint.encodingLength
)

// we cannot represent these in javascript so we just use buffers
exports.fixed64 =
exports.sfixed64 = encoder(1,
  function encode (val, buffer, offset) {
    b4a.copy(val, buffer, offset)
    encode.bytes = 8
    return buffer
  },
  function decode (buffer, offset) {
    var val = buffer.subarray(offset, offset + 8)
    decode.bytes = 8
    return val
  },
  function encodingLength () {
    return 8
  }
)

exports.double = encoder(1,
  function encode (val, buffer, offset) {
    b4a.writeDoubleLE(buffer, val, offset)
    encode.bytes = 8
    return buffer
  },
  function decode (buffer, offset) {
    var val = b4a.readDoubleLE(buffer, offset)
    decode.bytes = 8
    return val
  },
  function encodingLength () {
    return 8
  }
)

exports.fixed32 = encoder(5,
  function encode (val, buffer, offset) {
    b4a.writeUInt32LE(buffer, val, offset)
    encode.bytes = 4
    return buffer
  },
  function decode (buffer, offset) {
    var val = b4a.readUInt32LE(buffer, offset)
    decode.bytes = 4
    return val
  },
  function encodingLength () {
    return 4
  }
)

exports.sfixed32 = encoder(5,
  function encode (val, buffer, offset) {
    b4a.writeInt32LE(buffer, val, offset)
    encode.bytes = 4
    return buffer
  },
  function decode (buffer, offset) {
    var val = b4a.readInt32LE(buffer, offset)
    decode.bytes = 4
    return val
  },
  function encodingLength () {
    return 4
  }
)

exports.float = encoder(5,
  function encode (val, buffer, offset) {
    b4a.writeFloatLE(buffer, val, offset)
    encode.bytes = 4
    return buffer
  },
  function decode (buffer, offset) {
    var val = b4a.readFloatLE(buffer, offset)
    decode.bytes = 4
    return val
  },
  function encodingLength () {
    return 4
  }
)

function encoder (type, encode, decode, encodingLength) {
  encode.bytes = decode.bytes = 0

  return {
    type: type,
    encode: encode,
    decode: decode,
    encodingLength: encodingLength
  }
}

function bufferLength (val) {
  return b4a.isBuffer(val) ? val.length : b4a.byteLength(val)
}
{
  "name": "protocol-buffers-encodings",
  "version": "1.2.0",
  "description": "Base encodings for protocol-buffers",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.6.0",
    "signed-varint": "^2.0.1",
    "varint": "5.0.0"
  },
  "devDependencies": {
    "standard": "^14.3.4",
    "tape": "^5.0.1"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/protocol-buffers-encodings.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/protocol-buffers-encodings/issues"
  },
  "homepage": "https://github.com/mafintosh/protocol-buffers-encodings"
}
const b4a = require('b4a')
const c = require('compact-encoding')
const queueTick = require('queue-tick')
const safetyCatch = require('safety-catch')
const unslab = require('unslab')

const MAX_BUFFERED = 32768
const MAX_BACKLOG = Infinity // TODO: impl "open" backpressure
const MAX_BATCH = 8 * 1024 * 1024

class Channel {
  constructor(
    mux,
    info,
    userData,
    protocol,
    aliases,
    id,
    handshake,
    messages,
    onopen,
    onclose,
    ondestroy,
    ondrain
  ) {
    this.userData = userData
    this.protocol = protocol
    this.aliases = aliases
    this.id = id
    this.handshake = null
    this.messages = []

    this.opened = false
    this.closed = false
    this.destroyed = false

    this.onopen = onopen
    this.onclose = onclose
    this.ondestroy = ondestroy
    this.ondrain = ondrain

    this._handshake = handshake
    this._mux = mux
    this._info = info
    this._localId = 0
    this._remoteId = 0
    this._active = 0
    this._extensions = null

    this._decBound = this._dec.bind(this)
    this._decAndDestroyBound = this._decAndDestroy.bind(this)

    this._openedPromise = null
    this._openedResolve = null

    this._destroyedPromise = null
    this._destroyedResolve = null

    for (const m of messages) this.addMessage(m)
  }

  get drained() {
    return this._mux.drained
  }

  fullyOpened() {
    if (this.opened) return Promise.resolve(true)
    if (this.closed) return Promise.resolve(false)
    if (this._openedPromise) return this._openedPromise

    this._openedPromise = new Promise((resolve) => {
      this._openedResolve = resolve
    })
    return this._openedPromise
  }

  fullyClosed() {
    if (this.destroyed) return Promise.resolve()
    if (this._destroyedPromise) return this._destroyedPromise

    this._destroyedPromise = new Promise((resolve) => {
      this._destroyedResolve = resolve
    })
    return this._destroyedPromise
  }

  open(handshake) {
    const id = this._mux._free.length > 0 ? this._mux._free.pop() : this._mux._local.push(null) - 1

    this._info.opened++
    this._info.lastChannel = this
    this._localId = id + 1
    this._mux._local[id] = this

    if (this._remoteId === 0) {
      this._info.outgoing.push(this._localId)
    }

    const state = { buffer: null, start: 2, end: 2 }

    c.uint.preencode(state, this._localId)
    c.string.preencode(state, this.protocol)
    c.optionalBuffer.preencode(state, this.id)
    if (this._handshake) this._handshake.preencode(state, handshake)

    state.buffer = this._mux._alloc(state.end)

    state.buffer[0] = 0
    state.buffer[1] = 1
    c.uint.encode(state, this._localId)
    c.string.encode(state, this.protocol)
    c.optionalBuffer.encode(state, this.id)
    if (this._handshake) this._handshake.encode(state, handshake)

    this._mux._write0(state.buffer)
  }

  _dec() {
    if (--this._active === 0 && this.closed === true) this._destroy()
  }

  _decAndDestroy(err) {
    this._dec()
    this._mux._safeDestroy(err)
  }

  _fullyOpenSoon() {
    this._mux._remote[this._remoteId - 1].session = this
    queueTick(this._fullyOpenOrDestroy.bind(this))
  }

  _fullyOpenOrDestroy() {
    try {
      this._fullyOpen()
    } catch (err) {
      this._mux._safeDestroyBound(err)
    }
  }

  _fullyOpen() {
    if (this.opened === true || this.closed === true) return

    const remote = this._mux._remote[this._remoteId - 1]

    this.handshake = this._handshake ? this._handshake.decode(remote.state) : null
    this._track(this.onopen(this.handshake, this))

    remote.session = this
    remote.state = null
    if (remote.pending !== null) this._drain(remote)
    if (this._mux._destroying === true) return

    this.opened = true
    this._resolveOpen(true)
  }

  _resolveOpen(opened) {
    if (this._openedResolve !== null) {
      this._openedResolve(opened)
      this._openedResolve = this._openedPromise = null
    }
  }

  _resolveDestroyed() {
    if (this._destroyedResolve !== null) {
      this._destroyedResolve()
      this._destroyedResolve = this._destroyedPromise = null
    }
  }

  _drain(remote) {
    for (let i = 0; i < remote.pending.length; i++) {
      const p = remote.pending[i]
      this._mux._buffered -= byteSize(p.state)
      this._recv(p.type, p.state)
      if (this._mux._destroying === true) return
    }

    remote.pending = null
    this._mux._resumeMaybe()
  }

  _track(p) {
    if (isPromise(p) === true) {
      this._active++
      return p.then(this._decBound, this._decAndDestroyBound)
    }

    return null
  }

  _close(isRemote) {
    if (this.closed === true) return
    this.closed = true

    this._info.opened--
    if (this._info.lastChannel === this) this._info.lastChannel = null

    if (this._remoteId > 0) {
      this._mux._remote[this._remoteId - 1] = null
      this._remoteId = 0
      // If remote has acked, we can reuse the local id now
      // otherwise, we need to wait for the "ack" to arrive
      this._mux._free.push(this._localId - 1)
    }

    this._mux._local[this._localId - 1] = null
    this._localId = 0

    this._mux._gc(this._info)
    this._track(this.onclose(isRemote, this))

    if (this._active === 0) this._destroy()

    this._resolveOpen(false)
  }

  _destroy() {
    if (this.destroyed === true) return
    this.destroyed = true
    this._track(this.ondestroy(this))
    this._resolveDestroyed()
  }

  _recv(type, state) {
    if (type < this.messages.length) {
      const m = this.messages[type]
      const p = m.recv(state, this)
      if (m.autoBatch === true) return p
    }
    return null
  }

  cork() {
    this._mux.cork()
  }

  uncork() {
    this._mux.uncork()
  }

  close() {
    if (this.closed === true) return

    const state = { buffer: null, start: 2, end: 2 }

    c.uint.preencode(state, this._localId)

    state.buffer = this._mux._alloc(state.end)

    state.buffer[0] = 0
    state.buffer[1] = 3
    c.uint.encode(state, this._localId)

    this._close(false)
    this._mux._write0(state.buffer)
  }

  addMessage(opts) {
    if (!opts) return this._skipMessage()

    const type = this.messages.length
    const autoBatch = opts.autoBatch !== false
    const encoding = opts.encoding || c.raw
    const onmessage = opts.onmessage || noop

    const s = this
    const typeLen = encodingLength(c.uint, type)

    const m = {
      type,
      autoBatch,
      encoding,
      onmessage,
      recv(state, session) {
        return session._track(m.onmessage(encoding.decode(state), session))
      },
      send(m, session = s) {
        if (session.closed === true) return false

        const mux = session._mux
        const state = { buffer: null, start: 0, end: typeLen }

        if (mux._batch !== null) {
          encoding.preencode(state, m)
          state.buffer = mux._alloc(state.end)

          c.uint.encode(state, type)
          encoding.encode(state, m)

          mux._pushBatch(session._localId, state.buffer)
          return true
        }

        c.uint.preencode(state, session._localId)
        encoding.preencode(state, m)

        state.buffer = mux._alloc(state.end)

        c.uint.encode(state, session._localId)
        c.uint.encode(state, type)
        encoding.encode(state, m)

        mux.drained = mux.stream.write(state.buffer)

        return mux.drained
      }
    }

    this.messages.push(m)

    return m
  }

  _skipMessage() {
    const type = this.messages.length
    const m = {
      type,
      encoding: c.raw,
      onmessage: noop,
      recv(state, session) {},
      send(m, session) {}
    }

    this.messages.push(m)
    return m
  }
}

module.exports = class Protomux {
  constructor(stream, { alloc } = {}) {
    if (stream.userData === null) stream.userData = this

    this.isProtomux = true
    this.stream = stream
    this.corked = 0
    this.drained = true

    this._alloc =
      alloc || (typeof stream.alloc === 'function' ? stream.alloc.bind(stream) : b4a.allocUnsafe)
    this._safeDestroyBound = this._safeDestroy.bind(this)
    this._uncorkBound = this.uncork.bind(this)

    this._remoteBacklog = 0
    this._buffered = 0
    this._paused = false
    this._remote = []
    this._local = []
    this._free = []
    this._batch = null
    this._batchState = null

    this._infos = new Map()
    this._notify = new Map()
    // stream.destroyed flips asynchronously on streamx-based transports.
    this._destroying = false

    this.stream.on('data', this._ondata.bind(this))
    this.stream.on('drain', this._ondrain.bind(this))
    this.stream.on('end', this._onend.bind(this))
    this.stream.on('error', noop) // we handle this in "close"
    this.stream.on('close', this._shutdown.bind(this))
  }

  static from(stream, opts) {
    if (stream.userData && stream.userData.isProtomux) return stream.userData
    if (stream.isProtomux) return stream
    return new this(stream, opts)
  }

  static isProtomux(mux) {
    return typeof mux === 'object' && mux.isProtomux === true
  }

  *[Symbol.iterator]() {
    for (const session of this._local) {
      if (session !== null) yield session
    }
  }

  isIdle() {
    return this._local.length === this._free.length
  }

  cork() {
    if (++this.corked === 1) {
      this._batch = []
      this._batchState = { buffer: null, start: 0, end: 1 }
    }
  }

  uncork() {
    if (--this.corked === 0) {
      this._sendBatch(this._batch, this._batchState)
      this._batch = null
      this._batchState = null
    }
  }

  getLastChannel({ protocol, id = null }) {
    const key = toKey(protocol, id)
    const info = this._infos.get(key)
    if (info) return info.lastChannel
    return null
  }

  pair({ protocol, id = null }, notify) {
    this._notify.set(toKey(protocol, id), notify)
  }

  unpair({ protocol, id = null }) {
    this._notify.delete(toKey(protocol, id))
  }

  opened({ protocol, id = null }) {
    const key = toKey(protocol, id)
    const info = this._infos.get(key)
    return info ? info.opened > 0 : false
  }

  createChannel({
    userData = null,
    protocol,
    aliases = [],
    id = null,
    unique = true,
    handshake = null,
    messages = [],
    onopen = noop,
    onclose = noop,
    ondestroy = noop,
    ondrain = noop
  }) {
    if (this.stream.destroyed) return null

    const info = this._get(protocol, id, aliases)
    if (unique && info.opened > 0) return null

    if (info.incoming.length === 0) {
      return new Channel(
        this,
        info,
        userData,
        protocol,
        aliases,
        id,
        handshake,
        messages,
        onopen,
        onclose,
        ondestroy,
        ondrain
      )
    }

    this._remoteBacklog--

    const remoteId = info.incoming.shift()
    const r = this._remote[remoteId - 1]
    if (r === null) return null

    const session = new Channel(
      this,
      info,
      userData,
      protocol,
      aliases,
      id,
      handshake,
      messages,
      onopen,
      onclose,
      ondestroy,
      ondrain
    )

    session._remoteId = remoteId
    session._fullyOpenSoon()

    return session
  }

  _pushBatch(localId, buffer) {
    if (this._batchState.end >= MAX_BATCH) {
      this._sendBatch(this._batch, this._batchState)
      this._batch = []
      this._batchState = { buffer: null, start: 0, end: 1 }
    }

    if (this._batch.length === 0 || this._batch[this._batch.length - 1].localId !== localId) {
      this._batchState.end++
      c.uint.preencode(this._batchState, localId)
    }
    c.buffer.preencode(this._batchState, buffer)
    this._batch.push({ localId, buffer })
  }

  _sendBatch(batch, state) {
    if (batch.length === 0) return

    let prev = batch[0].localId

    state.buffer = this._alloc(state.end)
    state.buffer[state.start++] = 0
    state.buffer[state.start++] = 0

    c.uint.encode(state, prev)

    for (let i = 0; i < batch.length; i++) {
      const b = batch[i]
      if (prev !== b.localId) {
        state.buffer[state.start++] = 0
        c.uint.encode(state, (prev = b.localId))
      }
      c.buffer.encode(state, b.buffer)
    }

    this.drained = this.stream.write(state.buffer)
  }

  _get(protocol, id, aliases = []) {
    const key = toKey(protocol, id)

    let info = this._infos.get(key)
    if (info) return info

    info = {
      key,
      protocol,
      aliases: [],
      id,
      pairing: 0,
      opened: 0,
      incoming: [],
      outgoing: [],
      lastChannel: null
    }
    this._infos.set(key, info)

    for (const alias of aliases) {
      const key = toKey(alias, id)
      info.aliases.push(key)

      this._infos.set(key, info)
    }

    return info
  }

  _gc(info) {
    if (info.opened === 0 && info.outgoing.length === 0 && info.incoming.length === 0) {
      this._infos.delete(info.key)

      for (const alias of info.aliases) this._infos.delete(alias)
    }
  }

  _ondata(buffer) {
    if (buffer.byteLength === 0) return // ignore empty frames...
    try {
      const state = { buffer, start: 0, end: buffer.byteLength }
      this._decode(c.uint.decode(state), state)
    } catch (err) {
      this._safeDestroy(err)
    }
  }

  _ondrain() {
    this.drained = true

    for (const s of this._local) {
      if (s !== null) s._track(s.ondrain(s))
    }
  }

  _onend() {
    // TODO: support half open mode for the users who wants that here
    this.stream.end()
  }

  _decode(remoteId, state) {
    const type = c.uint.decode(state)

    if (remoteId === 0) {
      return this._oncontrolsession(type, state)
    }

    const r = remoteId <= this._remote.length ? this._remote[remoteId - 1] : null

    // if the channel is closed ignore - could just be a pipeline message...
    if (r === null) return null

    if (r.pending !== null) {
      this._bufferMessage(r, type, state)
      return null
    }

    return r.session._recv(type, state)
  }

  _oncontrolsession(type, state) {
    switch (type) {
      case 0:
        this._onbatch(state)
        break

      case 1:
        // return the promise back up as this has sideeffects so we can batch reply
        return this._onopensession(state)

      case 2:
        this._onrejectsession(state)
        break

      case 3:
        this._onclosesession(state)
        break
    }

    return null
  }

  _bufferMessage(r, type, { buffer, start, end }) {
    const state = { buffer, start, end } // copy
    r.pending.push({ type, state })
    this._buffered += byteSize(state)
    this._pauseMaybe()
  }

  _pauseMaybe() {
    if (this._paused === true || this._buffered <= MAX_BUFFERED) return
    this._paused = true
    this.stream.pause()
  }

  _resumeMaybe() {
    if (this._paused === false || this._buffered > MAX_BUFFERED) return
    this._paused = false
    this.stream.resume()
  }

  _onbatch(state) {
    const end = state.end
    let remoteId = c.uint.decode(state)

    let waiting = null

    while (state.end > state.start) {
      const len = c.uint.decode(state)
      if (len === 0) {
        remoteId = c.uint.decode(state)
        continue
      }
      state.end = state.start + len
      // if batch contains more than one message, cork it so we reply back with a batch
      if (end !== state.end && waiting === null) {
        waiting = []
        this.cork()
      }
      const p = this._decode(remoteId, state)
      if (waiting !== null && p !== null) waiting.push(p)
      state.start = state.end
      state.end = end
    }

    if (waiting !== null) {
      // the waiting promises are not allowed to throw but we destroy the stream in case we are wrong
      Promise.all(waiting).then(this._uncorkBound, this._safeDestroyBound)
    }
  }

  _onopensession(state) {
    const remoteId = c.uint.decode(state)
    const protocol = c.string.decode(state)
    const id = unslab(c.optionalBuffer.decode(state))

    // remote tried to open the control session - auto reject for now
    // as we can use as an explicit control protocol declaration if we need to
    if (remoteId === 0) {
      this._rejectSession(0)
      return null
    }

    const rid = remoteId - 1
    const info = this._get(protocol, id)

    // allow the remote to grow the ids by one
    if (this._remote.length === rid) {
      this._remote.push(null)
    }

    if (rid >= this._remote.length || this._remote[rid] !== null) {
      throw new Error('Invalid open message')
    }

    if (info.outgoing.length > 0) {
      const localId = info.outgoing.shift()
      const session = this._local[localId - 1]

      if (session === null) {
        // we already closed the channel - ignore
        this._free.push(localId - 1)
        return null
      }

      this._remote[rid] = { state, pending: null, session: null }

      session._remoteId = remoteId
      session._fullyOpen()
      return null
    }

    const copyState = { buffer: state.buffer, start: state.start, end: state.end }
    this._remote[rid] = { state: copyState, pending: [], session: null }

    if (++this._remoteBacklog > MAX_BACKLOG) {
      throw new Error('Remote exceeded backlog')
    }

    info.pairing++
    info.incoming.push(remoteId)

    return this._requestSession(protocol, id, info).catch(this._safeDestroyBound)
  }

  _onrejectsession(state) {
    const localId = c.uint.decode(state)

    // TODO: can be done smarter...
    for (const info of this._infos.values()) {
      const i = info.outgoing.indexOf(localId)
      if (i === -1) continue

      info.outgoing.splice(i, 1)

      const session = this._local[localId - 1]

      this._free.push(localId - 1)
      if (session !== null) session._close(true)

      this._gc(info)
      return
    }

    throw new Error('Invalid reject message')
  }

  _onclosesession(state) {
    const remoteId = c.uint.decode(state)

    if (remoteId === 0) return // ignore

    const rid = remoteId - 1
    const r = rid < this._remote.length ? this._remote[rid] : null

    if (r === null) return

    if (r.session !== null) r.session._close(true)
  }

  async _requestSession(protocol, id, info) {
    const notify = this._notify.get(toKey(protocol, id)) || this._notify.get(toKey(protocol, null))

    if (notify) await notify(id)

    if (--info.pairing > 0) return

    while (info.incoming.length > 0) {
      this._rejectSession(info, info.incoming.shift())
    }

    this._gc(info)
  }

  _rejectSession(info, remoteId) {
    if (remoteId > 0) {
      const r = this._remote[remoteId - 1]

      if (r.pending !== null) {
        for (let i = 0; i < r.pending.length; i++) {
          this._buffered -= byteSize(r.pending[i].state)
        }
      }

      this._remote[remoteId - 1] = null
      this._resumeMaybe()
    }

    const state = { buffer: null, start: 2, end: 2 }

    c.uint.preencode(state, remoteId)

    state.buffer = this._alloc(state.end)

    state.buffer[0] = 0
    state.buffer[1] = 2
    c.uint.encode(state, remoteId)

    this._write0(state.buffer)
  }

  _write0(buffer) {
    if (this._batch !== null) {
      this._pushBatch(0, buffer.subarray(1))
      return
    }

    this.drained = this.stream.write(buffer)
  }

  destroy(err) {
    this._destroying = true
    this.stream.destroy(err)
  }

  _safeDestroy(err) {
    safetyCatch(err)
    this._destroying = true
    this.stream.destroy(err)
  }

  _shutdown() {
    this._destroying = true
    for (const s of this._local) {
      if (s !== null) s._close(true)
    }
  }
}

function noop() {}

function toKey(protocol, id) {
  return protocol + '##' + (id ? b4a.toString(id, 'hex') : '')
}

function byteSize(state) {
  return 512 + (state.end - state.start)
}

function isPromise(p) {
  return !!(p && typeof p.then === 'function')
}

function encodingLength(enc, val) {
  const state = { buffer: null, start: 0, end: 0 }
  enc.preencode(state, val)
  return state.end
}
{
  "name": "protomux",
  "version": "3.11.0",
  "description": "Multiplex multiple message oriented protocols over a stream",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.3.1",
    "compact-encoding": "^3.0.0",
    "queue-tick": "^1.0.0",
    "safety-catch": "^1.0.1",
    "unslab": "^1.3.0"
  },
  "devDependencies": {
    "@hyperswarm/secret-stream": "^6.0.0",
    "brittle": "^3.0.0",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/protomux.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/protomux/issues"
  },
  "homepage": "https://github.com/holepunchto/protomux"
}
{
  "name": "queue-tick",
  "version": "1.0.1",
  "description": "Next tick shim that prefers process.nextTick over queueMicrotask for compat",
  "main": "./process-next-tick.js",
  "browser": "./queue-microtask.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^16.0.3",
    "tape": "^5.3.1"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/queue-tick.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/queue-tick/issues"
  },
  "homepage": "https://github.com/mafintosh/queue-tick"
}
module.exports = (typeof process !== 'undefined' && typeof process.nextTick === 'function')
  ? process.nextTick.bind(process)
  : require('./queue-microtask')
module.exports = typeof queueMicrotask === 'function' ? queueMicrotask : (fn) => Promise.resolve().then(fn)
require.addon = require('require-addon')

module.exports = require.addon('.', __filename)
const binding = require('./binding')

exports.get = function get(field, bit) {
  const n = field.byteLength * 8

  if (bit < 0) bit += n
  if (bit < 0 || bit >= n) return false

  return binding.quickbit_napi_get(toBuffer(field), bit) !== 0
}

exports.set = function set(field, bit, value = true) {
  const n = field.byteLength * 8

  if (bit < 0) bit += n
  if (bit < 0 || bit >= n) return false

  return binding.quickbit_napi_set(toBuffer(field), bit, value ? 1 : 0) !== 0
}

exports.fill = function fill(
  field,
  value,
  start = 0,
  end = field.byteLength * 8
) {
  const n = field.byteLength * 8

  if (start < 0) start += n
  if (end < 0) end += n
  if (start < 0 || start >= field.byteLength * 8 || start >= end) return field

  binding.quickbit_napi_fill(toBuffer(field), value ? 1 : 0, start, end)
  return field
}

exports.clear = function clear(field, ...chunks) {
  binding.quickbit_napi_clear(toBuffer(field), chunks.map(toBufferChunk))
}

exports.findFirst = function findFirst(field, value, position = 0) {
  const n = field.byteLength * 8

  if (position < 0) position += n
  if (position < 0) position = 0
  if (position >= n) return -1

  return binding.quickbit_napi_find_first(
    toBuffer(field),
    value ? 1 : 0,
    position
  )
}

exports.findLast = function findLast(
  field,
  value,
  position = field.byteLength * 8 - 1
) {
  const n = field.byteLength * 8

  if (position < 0) position += n
  if (position < 0) return -1
  if (position >= n) position = n - 1

  return binding.quickbit_napi_find_last(
    toBuffer(field),
    value ? 1 : 0,
    position
  )
}

function toBuffer(field) {
  if (field.BYTES_PER_ELEMENT === 1) return field
  return new Uint8Array(field.buffer, field.byteOffset, field.byteLength)
}

function toBufferChunk(chunk) {
  return { field: toBuffer(chunk.field), offset: chunk.offset }
}

class Index {
  static from(fieldOrChunks, byteLength = -1) {
    if (Array.isArray(fieldOrChunks)) {
      return new SparseIndex(fieldOrChunks, byteLength)
    } else {
      return new DenseIndex(fieldOrChunks, byteLength)
    }
  }

  constructor(byteLength) {
    this._byteLength = byteLength
    this.handle = Buffer.allocUnsafe(binding.sizeof_quickbit_index_t)
  }

  get byteLength() {
    return this._byteLength
  }

  skipFirst(value, position = 0) {
    const n = this.byteLength * 8

    if (position < 0) position += n
    if (position < 0) position = 0
    if (position >= n) return n - 1

    return binding.quickbit_napi_skip_first(
      this.handle,
      this.byteLength,
      value ? 1 : 0,
      position
    )
  }

  skipLast(value, position = this.byteLength * 8 - 1) {
    const n = this.byteLength * 8

    if (position < 0) position += n
    if (position < 0) return 0
    if (position >= n) position = n - 1

    return binding.quickbit_napi_skip_last(
      this.handle,
      this.byteLength,
      value ? 1 : 0,
      position
    )
  }
}

exports.Index = Index

class DenseIndex extends Index {
  constructor(field, byteLength) {
    super(byteLength)
    this.field = field

    binding.quickbit_napi_index_init(this.handle, toBuffer(this.field))
  }

  get byteLength() {
    if (this._byteLength !== -1) return this._byteLength
    return this.field.byteLength
  }

  update(bit) {
    const n = this.byteLength * 8

    if (bit < 0) bit += n
    if (bit < 0 || bit >= n) return false

    return (
      binding.quickbit_napi_index_update(
        this.handle,
        toBuffer(this.field),
        bit
      ) !== 0
    )
  }
}

function selectChunk(chunks, offset) {
  for (let i = 0; i < chunks.length; i++) {
    const next = chunks[i]

    const start = next.offset
    const end = next.offset + next.field.byteLength

    if (offset >= start && offset + 16 <= end) {
      return next
    }
  }

  return null
}

class SparseIndex extends Index {
  constructor(chunks, byteLength) {
    super(byteLength)
    this.chunks = chunks

    binding.quickbit_napi_index_init_sparse(
      this.handle,
      this.chunks.map(toBufferChunk)
    )
  }

  get byteLength() {
    if (this._byteLength !== -1) return this._byteLength
    const last = this.chunks[this.chunks.length - 1]
    return last ? last.offset + last.field.byteLength : 0
  }

  update(bit) {
    const n = this.byteLength * 8

    if (bit < 0) bit += n
    if (bit < 0 || bit >= n) return false

    const j = Math.floor(bit / 128)

    const offset = j * 16

    const chunk = selectChunk(this.chunks, offset)

    if (chunk === null) return false

    return (
      binding.quickbit_napi_index_update_sparse(
        this.handle,
        toBuffer(chunk.field),
        chunk.offset,
        bit
      ) !== 0
    )
  }
}
{
  "name": "quickbit-native",
  "version": "2.4.8",
  "description": "libquickbit JavaScript bindings for Node.js",
  "main": "index.js",
  "files": [
    "index.js",
    "macros.h",
    "binding.cc",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "npm run lint && npm run test:bare && npm run test:node",
    "test:bare": "bare test.mjs",
    "test:node": "node test.mjs",
    "lint": "prettier . --check"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/quickbit-native.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/quickbit-native/issues"
  },
  "homepage": "https://github.com/holepunchto/quickbit-native#readme",
  "dependencies": {
    "require-addon": "^1.1.0"
  },
  "devDependencies": {
    "b4a": "^1.6.7",
    "bare-compat-napi": "^1.3.2",
    "brittle": "^3.1.0",
    "cmake-bare": "^1.1.7",
    "cmake-fetch": "^1.1.0",
    "cmake-napi": "^1.0.2",
    "prettier": "^3.5.3",
    "prettier-config-standard": "^7.0.0"
  }
}
const simdle = require('simdle-universal')

const INDEX_LEN = (16 /* root */ + 128 * 16 /* children */) * 2

const get = exports.get = function get (field, bit) {
  const n = field.byteLength * 8

  if (bit < 0) bit += n
  if (bit < 0 || bit >= n) return false

  const m = field.BYTES_PER_ELEMENT * 8

  const offset = bit & (m - 1)
  const i = (bit - offset) / m

  return (field[i] & (1 << offset)) !== 0
}

const set = exports.set = function set (field, bit, value = true) {
  const n = field.byteLength * 8

  if (bit < 0) bit += n
  if (bit < 0 || bit >= n) return false

  const m = field.BYTES_PER_ELEMENT * 8

  const offset = bit & (m - 1)
  const i = (bit - offset) / m
  const mask = 1 << offset

  if (value) {
    if ((field[i] & mask) !== 0) return false
  } else {
    if ((field[i] & mask) === 0) return false
  }

  field[i] ^= mask

  return true
}

exports.fill = function fill (field, value, start = 0, end = field.byteLength * 8) {
  const n = field.byteLength * 8

  if (start < 0) start += n
  if (end < 0) end += n
  if (start < 0 || start >= field.byteLength * 8 || start >= end) return field

  const m = field.BYTES_PER_ELEMENT * 8

  let i, j

  {
    const offset = start & (m - 1)
    i = (start - offset) / m

    if (offset !== 0) {
      let shift = m - offset
      if (end - start < shift) shift = end - start

      const mask = ((1 << shift) - 1) << offset

      if (value) field[i] |= mask
      else field[i] &= ~mask

      i++
    }
  }

  {
    const offset = end & (m - 1)
    j = (end - offset) / m

    if (offset !== 0 && j >= i) {
      const mask = (1 << offset) - 1

      if (value) field[j] |= mask
      else field[j] &= ~mask
    }
  }

  if (i < j) field.fill(value ? (2 ** m) - 1 : 0, i, j)

  return field
}

exports.clear = function clear (field, ...chunks) {
  const n = field.byteLength

  for (const chunk of chunks) {
    if (chunk.offset >= n) continue

    const m = chunk.field.byteLength

    let i = chunk.offset
    let j = 0

    while (((i & 15) !== 0 || (j & 15) !== 0) && i < n && j < m) {
      field[i] = field[i] & ~chunk.field[j]
      i++
      j++
    }

    if (i + 15 < n && j + 15 < m) {
      const len = Math.min(n - (n & 15) - i, m - (m & 15) - j)

      simdle.clear(field.subarray(i, i + len), chunk.field.subarray(j, j + len), field.subarray(i, i + len))
    }

    while (i < n && j < m) {
      field[i] = field[i] & ~chunk.field[j]
      i++
      j++
    }
  }
}

function bitOffset (bit, offset) {
  return !bit ? offset : (INDEX_LEN * 8 / 2) + offset
}

function byteOffset (bit, offset) {
  return !bit ? offset : (INDEX_LEN / 2) + offset
}

exports.findFirst = function findFirst (field, value, position = 0) {
  const n = field.byteLength * 8

  if (position < 0) position += n
  if (position < 0) position = 0
  if (position >= n) return -1

  value = !!value

  for (let i = position; i < n; i++) {
    if (get(field, i) === value) return i
  }

  return -1
}

exports.findLast = function findLast (field, value, position = field.byteLength * 8 - 1) {
  const n = field.byteLength * 8

  if (position < 0) position += n
  if (position < 0) return -1
  if (position >= n) position = n - 1

  value = !!value

  for (let i = position; i >= 0; i--) {
    if (get(field, i) === value) return i
  }

  return -1
}

const Index = exports.Index = class Index {
  static from (fieldOrChunks, byteLength = -1) {
    if (Array.isArray(fieldOrChunks)) {
      return new SparseIndex(fieldOrChunks, byteLength)
    } else {
      return new DenseIndex(fieldOrChunks, byteLength)
    }
  }

  constructor (byteLength) {
    this._byteLength = byteLength
    this.handle = new Uint32Array(INDEX_LEN / 4)
  }

  get byteLength () {
    return this._byteLength
  }

  skipFirst (value, position = 0) {
    const n = this.byteLength * 8

    if (position < 0) position += n
    if (position < 0) position = 0
    if (position >= n) return n - 1

    let i = Math.floor(position / 16384)

    if (i > 127) return position

    while (i <= 127 && get(this.handle, bitOffset(value, i))) {
      i++
    }

    if (i === 128) return n - 1

    let k = i * 16384
    let j = 0

    if (position > k) j = Math.floor((position - k) / 128)

    while (j <= 127 && get(this.handle, bitOffset(value, i * 128 + j + 128))) {
      j++
      k += 128
    }

    if (j === 128 && i !== 127) return this.skipFirst(value, (i + 1) * 16384)

    if (k > position) position = k

    return position < n ? position : n - 1
  }

  skipLast (value, position = this.byteLength * 8 - 1) {
    const n = this.byteLength * 8

    if (position < 0) position += n
    if (position < 0) return 0
    if (position >= n) position = n - 1

    let i = Math.floor(position / 16384)

    if (i > 127) return position

    while (i >= 0 && get(this.handle, bitOffset(value, i))) {
      i--
    }

    if (i === -1) return 0

    let k = ((i + 1) * 16384) - 1
    let j = 127

    if (position < k) j = 128 - Math.ceil((k - position) / 128)

    while (j >= 0 && get(this.handle, bitOffset(value, i * 128 + j + 128))) {
      j--
      k -= 128
    }

    if (j === -1 && i !== 0) return this.skipLast(value, i * 16384 - 1)

    if (k < position) position = k

    return position
  }
}

class DenseIndex extends Index {
  constructor (field, byteLength) {
    super(byteLength)
    this.field = field

    const m = field.BYTES_PER_ELEMENT

    for (let i = 0; i < 128; i++) {
      for (let j = 0; j < 128; j++) {
        const offset = (i * 128 + j) * 16
        let allz = true
        let allo = false

        if (offset + 16 <= this.field.byteLength) {
          const vec = this.field.subarray(offset / m, (offset + 16) / m)

          allz = simdle.allz(vec)
          allo = simdle.allo(vec)
        }

        const k = i * 128 + 128 + j

        set(this.handle, bitOffset(false, k), allz)
        set(this.handle, bitOffset(true, k), allo)
      }

      {
        const offset = byteOffset(false, i * 16 + 16) / 4
        const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

        set(this.handle, bitOffset(false, i), allo)
      }

      {
        const offset = byteOffset(true, i * 16 + 16) / 4
        const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

        set(this.handle, bitOffset(true, i), allo)
      }
    }
  }

  get byteLength () {
    if (this._byteLength !== -1) return this._byteLength
    return this.field.byteLength
  }

  update (bit) {
    const n = this.byteLength * 8

    if (bit < 0) bit += n
    if (bit < 0 || bit >= n) return false

    const m = this.field.BYTES_PER_ELEMENT

    const i = Math.floor(bit / 16384)
    const j = Math.floor(bit / 128)

    const offset = (j * 16) / m
    const vec = this.field.subarray(offset, offset + (16 / m))

    const allz = simdle.allz(vec)
    const allo = simdle.allo(vec)

    let changed = false

    if (set(this.handle, bitOffset(false, 128 + j), allz)) {
      changed = true

      const offset = byteOffset(false, i * 16 + 16) / 4
      const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

      set(this.handle, bitOffset(false, i), allo)
    }

    if (set(this.handle, bitOffset(true, 128 + j), allo)) {
      changed = true

      const offset = byteOffset(true, i * 16 + 16) / 4
      const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

      set(this.handle, bitOffset(true, i), allo)
    }

    return changed
  }
}

function selectChunk (chunks, offset) {
  for (let i = 0; i < chunks.length; i++) {
    const next = chunks[i]

    const start = next.offset
    const end = next.offset + next.field.byteLength

    if (offset >= start && offset + 16 <= end) {
      return next
    }
  }

  return null
}

class SparseIndex extends Index {
  constructor (chunks, byteLength) {
    super(byteLength)
    this.chunks = chunks

    for (let i = 0; i < 128; i++) {
      for (let j = 0; j < 128; j++) {
        const offset = (i * 128 + j) * 16
        let allz = true
        let allo = false

        const chunk = selectChunk(this.chunks, offset)

        if (chunk !== null) {
          const m = chunk.field.BYTES_PER_ELEMENT

          const vec = chunk.field.subarray((offset - chunk.offset) / m, (offset - chunk.offset + 16) / m)

          allz = simdle.allz(vec)
          allo = simdle.allo(vec)
        }

        const k = i * 128 + 128 + j

        set(this.handle, bitOffset(false, k), allz)
        set(this.handle, bitOffset(true, k), allo)
      }

      {
        const offset = byteOffset(false, i * 16 + 16) / 4
        const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

        set(this.handle, bitOffset(false, i), allo)
      }

      {
        const offset = byteOffset(true, i * 16 + 16) / 4
        const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

        set(this.handle, bitOffset(true, i), allo)
      }
    }
  }

  get byteLength () {
    if (this._byteLength !== -1) return this._byteLength
    const last = this.chunks[this.chunks.length - 1]
    return last ? last.offset + last.field.byteLength : 0
  }

  update (bit) {
    const n = this.byteLength * 8

    if (bit < 0) bit += n
    if (bit < 0 || bit >= n) return false

    const i = Math.floor(bit / 16384)
    const j = Math.floor(bit / 128)

    const offset = j * 16

    const chunk = selectChunk(this.chunks, offset)

    if (chunk === null) return false

    const m = chunk.field.BYTES_PER_ELEMENT

    const vec = chunk.field.subarray((offset - chunk.offset) / m, (offset - chunk.offset + 16) / m)

    const allz = simdle.allz(vec)
    const allo = simdle.allo(vec)

    let changed = false

    if (set(this.handle, bitOffset(false, 128 + j), allz)) {
      changed = true

      const offset = byteOffset(false, i * 16 + 16) / 4
      const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

      set(this.handle, bitOffset(false, i), allo)
    }

    if (set(this.handle, bitOffset(true, 128 + j), allo)) {
      changed = true

      const offset = byteOffset(true, i * 16 + 16) / 4
      const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

      set(this.handle, bitOffset(true, i), allo)
    }

    return changed
  }
}
const fallback = require('./fallback')

try {
  const native = require('quickbit-native')

  // These functions are faster in JavaScript
  exports.get = fallback.get
  exports.set = fallback.set
  exports.fill = fallback.fill

  // These functions are faster in C
  exports.clear = native.clear
  exports.findFirst = native.findFirst
  exports.findLast = native.findLast
  exports.Index = native.Index
} catch {
  module.exports = fallback
}
{
  "name": "quickbit-universal",
  "version": "2.2.0",
  "description": "Universal wrapper for libquickbit with a JavaScript fallback",
  "main": "index.js",
  "files": [
    "fallback.js",
    "index.js"
  ],
  "browser": {
    "./index.js": "./fallback.js"
  },
  "scripts": {
    "test": "standard && brittle test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/quickbit-universal.git"
  },
  "author": "Kasper Isager Dalsgarð <kasper@funktionel.co>",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/holepunchto/quickbit-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/quickbit-universal#readme",
  "dependencies": {
    "b4a": "^1.6.0",
    "simdle-universal": "^1.1.0"
  },
  "optionalDependencies": {
    "quickbit-native": "^2.2.0"
  },
  "devDependencies": {
    "brittle": "^3.1.0",
    "standard": "^17.0.0"
  }
}
class CacheEntry {
  constructor (key, index, map) {
    this.key = key
    this.index = index
    this.map = map
  }
}

class CacheValue {
  constructor (entry, value) {
    this.entry = entry
    this.value = value
  }
}

class Rache {
  constructor ({ maxSize = 65536, parent = null } = {}) {
    this.maxSize = parent?.maxSize || maxSize

    this._array = parent?._array || []
    this._map = new Map()
  }

  static from (cache) {
    return cache ? new this({ parent: cache }) : new this()
  }

  get globalSize () {
    return this._array.length
  }

  get size () {
    return this._map.size
  }

  sub () {
    return new Rache({ parent: this })
  }

  set (key, value) { // ~constant time
    const existing = this._map.get(key)
    if (existing !== undefined) {
      existing.value = value
      return
    }

    if (this._array.length >= this.maxSize) this._gc()

    const entry = new CacheEntry(key, this._array.length, this._map)
    this._array.push(entry)
    const cacheValue = new CacheValue(entry, value)
    this._map.set(key, cacheValue)
  }

  delete (key) {
    const existing = this._map.get(key)
    if (existing === undefined) return false

    this._delete(existing.entry.index)
    return true
  }

  get (key) {
    const existing = this._map.get(key)
    return existing === undefined ? undefined : existing.value
  }

  * [Symbol.iterator] () {
    for (const [key, { value }] of this._map) {
      yield [key, value]
    }
  }

  keys () {
    return this._map.keys()
  }

  * values () {
    for (const { value } of this._map.values()) {
      yield value
    }
  }

  clear () {
    // The entries in map linger on in _array,
    // so on top of clearing the map, we also kill the ref,
    // so that any gc running later on the old map won't interfere
    // (in case a new entry was added with the same key as a cleared entry)

    this._map.clear()
    this._map = new Map()
  }

  destroy () {
    this._map = null
    this._array = null
  }

  _gc () {
    this._delete(Math.floor(Math.random() * this._array.length))
  }

  _delete (index) { // ~constant time
    if (index >= this._array.length) throw new Error('Cannot delete unused index (logic bug?)')

    const head = this._array.pop()
    let removed = head

    if (index < this._array.length) {
      removed = this._array[index]
      head.index = index
      this._array[index] = head
    }

    removed.map.delete(removed.key)
  }
}

module.exports = Rache
{
  "name": "rache",
  "version": "1.0.0",
  "description": "Random-eviction cache",
  "main": "index.js",
  "scripts": {
    "test": "standard && brittle test.js --coverage"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/rache.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/rache/issues"
  },
  "homepage": "https://github.com/holepunchto/rache#readme",
  "files": [
    "index.js"
  ],
  "dependencies": {},
  "devDependencies": {
    "brittle": "^3.5.2",
    "standard": "^17.1.0"
  }
}
module.exports = class RandomArrayIterator {
  constructor (values) {
    this.values = values
    this.start = 0
    this.length = this.values.length
  }

  next () {
    if (this.length === 0) {
      if (this.start === 0) return { done: true, value: undefined }
      this.length = this.start
      this.start = 0
    }

    const i = this.start + ((Math.random() * this.length) | 0)
    const j = this.start + --this.length
    const value = this.values[i]

    this.values[i] = this.values[j]
    this.values[j] = value

    return { done: false, value }
  }

  dequeue () {
    this.values[this.start + this.length] = this.values[this.values.length - 1]
    this.values.pop()
  }

  requeue () {
    const i = this.start + this.length
    const value = this.values[i]
    this.values[i] = this.values[this.start]
    this.values[this.start++] = value
  }

  restart () {
    this.start = 0
    this.length = this.values.length
    return this
  }

  [Symbol.iterator] () {
    return this
  }
}
{
  "name": "random-array-iterator",
  "version": "1.0.0",
  "description": "An iterator to iterate an array in random order with controls to requeue or dequeue elements during the iteration",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^16.0.3",
    "tape": "^5.0.1"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/random-array-iterator.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/random-array-iterator/issues"
  },
  "homepage": "https://github.com/mafintosh/random-array-iterator"
}
const EventEmitter = require('events')

module.exports = class ReadyResource extends EventEmitter {
  constructor () {
    super()

    this.opening = null
    this.closing = null

    this.opened = false
    this.closed = false
  }

  ready () {
    if (this.opening !== null) return this.opening
    this.opening = open(this)
    return this.opening
  }

  close () {
    if (this.closing !== null) return this.closing
    this.closing = close(this)
    return this.closing
  }

  async _open () {
    // add impl here
  }

  async _close () {
    // add impl here
  }
}

async function open (self) {
  // open after close
  if (self.closing !== null) return

  try {
    await self._open()
  } catch (err) {
    self.close() // safe to run in bg
    throw err
  }

  self.opened = true
  self.emit('ready')
}

async function close (self) {
  try {
    if (self.opened === false && self.opening !== null) await self.opening
  } catch {
    // ignore errors on closing
  }
  if (self.opened === true || self.opening === null) await self._close()
  self.closed = true
  self.emit('close')
}
{
  "name": "ready-resource",
  "version": "1.2.0",
  "description": "Modern single resource management",
  "main": "index.js",
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "types": "index.d.ts",
  "files": [
    "index.js",
    "index.d.ts"
  ],
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "devDependencies": {
    "brittle": "^3.1.0",
    "standard": "^17.0.0"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/ready-resource.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/ready-resource/issues"
  },
  "homepage": "https://github.com/holepunchto/ready-resource",
  "dependencies": {
    "bare-events": "^2.2.0"
  }
}
module.exports = class RefCounter {
  constructor() {
    this.count = 0

    this._onidle = null
    this._idle = null
  }

  isIdle() {
    return this.count === 0
  }

  idle() {
    if (this.count === 0) return Promise.resolve()
    if (this._idle !== null) return this._idle

    this._idle = new Promise((resolve) => {
      this._onidle = resolve
    })

    return this._idle
  }

  inc() {
    this.count++
  }

  dec() {
    if (--this.count > 0) return

    if (this._onidle !== null) {
      const resolve = this._onidle
      this._idle = null
      this._onidle = null
      resolve()
    }
  }
}
{
  "name": "refcounter",
  "version": "1.0.0",
  "description": "Simple refcounter",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {},
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/refcounter.git"
  },
  "author": "Holepunch Inc",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/refcounter/issues"
  },
  "homepage": "https://github.com/holepunchto/refcounter"
}
module.exports = require.addon.bind(require)
{
  "name": "require-addon",
  "version": "1.2.0",
  "description": "Import native addons across JavaScript runtimes",
  "exports": {
    "./package": "./package.json",
    ".": {
      "bare": "./lib/bare.js",
      "node": "./lib/node.js",
      "default": "./lib/default.js"
    }
  },
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    },
    "url": {
      "bare": "bare-url",
      "default": "url"
    }
  },
  "files": [
    "lib"
  ],
  "scripts": {
    "test": "npm run lint && npm run test:bare && npm run test:node",
    "test:bare": "bare test.js",
    "test:node": "node test.js",
    "lint": "prettier --check .",
    "format": "prettier --write ."
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/require-addon.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/require-addon/issues"
  },
  "homepage": "https://github.com/holepunchto/require-addon#readme",
  "engines": {
    "bare": ">=1.10.0"
  },
  "dependencies": {
    "bare-addon-resolve": "^1.3.0"
  },
  "devDependencies": {
    "bare-bundle": "^1.8.1",
    "bare-bundle-evaluate": "^1.1.0",
    "bare-fs": "^4.0.0",
    "bare-path": "^3.0.0",
    "bare-url": "^2.1.0",
    "brittle": "^3.7.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
let tmpResolve = null
let tmpReject = null

if (Promise.withResolvers) {
  module.exports = Promise.withResolvers.bind(Promise)
} else {
  module.exports = function resolveRejectPromise () {
    const promise = new Promise(setTmp)
    const result = { promise, resolve: tmpResolve, reject: tmpReject }
    tmpResolve = tmpReject = null
    return result
  }
}

function setTmp (resolve, reject) {
  tmpResolve = resolve
  tmpReject = reject
}
{
  "name": "resolve-reject-promise",
  "version": "1.1.0",
  "description": "Create an inverted promise with no function allocs",
  "main": "index.js",
  "scripts": {
    "test": "standard"
  },
  "devDependencies": {
    "standard": "^17.1.2"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/resolve-reject-promise.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/resolve-reject-promise/issues"
  },
  "homepage": "https://github.com/mafintosh/resolve-reject-promise"
}
const resources = new Map()

exports.add = function(resource, teardown) {
  resources.set(resource, teardown)
}

exports.remove = function(resource) {
  resources.delete(resource)
}

if (global.Bare) global.Bare.on('exit', run)
else global.process.on('exit', run)

function run() {
  for (const [resource, teardown] of resources) {
    teardown(resource)
  }
}
{
  "name": "resource-on-exit",
  "version": "1.0.0",
  "description": "Register sync teardown handlers for a resource",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {},
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/bare-teardown.git"
  },
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-teardown/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-teardown"
}
require.addon = require('require-addon')

module.exports = require.addon('.', __filename)
const ColumnFamily = require('./lib/column-family')
const Iterator = require('./lib/iterator')
const Snapshot = require('./lib/snapshot')
const State = require('./lib/state')
const { BloomFilterPolicy, RibbonFilterPolicy } = require('./lib/filter-policy')
const constants = require('./lib/constants')

class RocksDB {
  constructor(path, opts = {}) {
    const {
      columnFamily,
      state = new State(this, path, opts),
      snapshot = null,
      keyEncoding = null,
      valueEncoding = null
    } = opts

    this._state = state
    this._snapshot = snapshot
    this._columnFamily = state.getColumnFamily(columnFamily)
    this._keyEncoding = keyEncoding
    this._valueEncoding = valueEncoding
    this._index = -1

    this._state.addSession(this)
  }

  get opened() {
    return this._state.opened
  }

  get closed() {
    return this.isRoot() ? this._state.closed : this._index === -1
  }

  get path() {
    return this._state.path
  }

  get stats() {
    return this._state.stats
  }

  get snapshotted() {
    return this._snapshot !== null
  }

  get defaultColumnFamily() {
    return this._columnFamily
  }

  session({
    columnFamily = this._columnFamily,
    snapshot = this._snapshot !== null,
    keyEncoding = this._keyEncoding,
    valueEncoding = this._valueEncoding
  } = {}) {
    maybeClosed(this)

    return new RocksDB(null, {
      state: this._state,
      columnFamily,
      snapshot: snapshot ? this._snapshot || new Snapshot(this._state) : null,
      keyEncoding,
      valueEncoding
    })
  }

  columnFamily(name, opts) {
    return this.session({ ...opts, columnFamily: name })
  }

  snapshot() {
    return this.session({ snapshot: true })
  }

  isRoot() {
    return this === this._state.db
  }

  ready() {
    return this._state.ready()
  }

  async close({ force } = {}) {
    if (!this._state.opened) await this._state.ready()

    if (this._index !== -1) this._state.removeSession(this)

    if (force) {
      while (this._state.sessions.length > 0) {
        await this._state.sessions[this._state.sessions.length - 1].close()
      }
    }

    return this.isRoot() ? this._state.close() : Promise.resolve()
  }

  suspend() {
    maybeClosed(this)

    return this._state.suspend()
  }

  resume() {
    maybeClosed(this)

    return this._state.resume()
  }

  isIdle() {
    return this._state.handles.isIdle()
  }

  idle() {
    return this._state.handles.idle()
  }

  iterator(range, opts) {
    maybeClosed(this)

    return new Iterator(this, { ...range, ...opts })
  }

  async *keys(range, opts) {
    for await (const { key } of this.iterator(range, {
      ...opts,
      values: false
    })) {
      yield key
    }
  }

  async peek(range, opts) {
    for await (const value of this.iterator({ ...range, ...opts, limit: 1 })) {
      return value
    }

    return null
  }

  read(opts) {
    maybeClosed(this)

    return this._state.createReadBatch(this, opts)
  }

  write(opts) {
    maybeClosed(this)

    return this._state.createWriteBatch(this, opts)
  }

  flush(opts) {
    maybeClosed(this)

    return this._state.flush(this, opts)
  }

  async get(key, opts) {
    const batch = this.read({ ...opts, capacity: 1, autoDestroy: true })
    const value = batch.get(key)
    batch.tryFlush()
    return value
  }

  async put(key, value, opts) {
    const batch = this.write({ ...opts, capacity: 1, autoDestroy: true })
    batch.tryPut(key, value)
    await batch.flush()
  }

  async delete(key, opts) {
    const batch = this.write({ ...opts, capacity: 1, autoDestroy: true })
    batch.tryDelete(key)
    await batch.flush()
  }

  async deleteRange(start, end, opts) {
    const batch = this.write({ ...opts, capacity: 1, autoDestroy: true })
    batch.tryDeleteRange(start, end)
    await batch.flush()
  }

  async compact(opts = {}) {
    maybeClosed(this)

    await this._state.compact(this, opts)
  }

  async compactRange(start = null, end = null, opts = {}) {
    if (typeof end === 'object' && end !== null) {
      opts = end
      end = null
    } else if (typeof start === 'object' && start !== null) {
      opts = start
      start = null
      end = null
    }

    await this._state.compactRange(this, start, end, opts)
  }

  async approximateSize(start, end, opts = {}) {
    return this._state.approximateSize(this, start, end, opts)
  }

  async currentWalFile() {
    maybeClosed(this)

    return this._state.currentWalFile()
  }

  async getStatsLevel() {
    maybeClosed(this)

    return this._state.getStatsLevel()
  }

  async setStatsLevel(level) {
    maybeClosed(this)

    await this._state.setStatsLevel(level)
  }

  async getProperty(name) {
    maybeClosed(this)

    return this._state.getProperty(name)
  }

  _ref() {
    if (this._snapshot) this._snapshot.ref()
    this._state.handles.inc()
  }

  _unref() {
    if (this._snapshot) this._snapshot.unref()
    this._state.handles.dec()
  }

  diagnostics() {
    return this._state.diagnostics()
  }
}

module.exports = exports = RocksDB

exports.constants = constants

exports.ColumnFamily = ColumnFamily
exports.BloomFilterPolicy = BloomFilterPolicy
exports.RibbonFilterPolicy = RibbonFilterPolicy

function maybeClosed(db) {
  if (db._state.closing || db._index === -1) throw new Error('RocksDB session is closed')
}
const c = require('compact-encoding')
const binding = require('../binding')

const empty = Buffer.alloc(0)
const resolved = Promise.resolve()

class RocksDBBatch {
  constructor(db, opts = {}) {
    const { capacity = 8, autoDestroy = false } = opts

    db._ref()

    this._db = db
    this._destroyed = false
    this._capacity = capacity
    this._operations = []
    this._promises = []

    this._enqueuePromise = this._enqueuePromise.bind(this)

    this._request = null
    this._resolve = null
    this._reject = null

    this._handle = null
    this._buffer = null
    this._autoDestroy = autoDestroy
    this._stats = null

    this._resetStats()

    if (db._state.opened === true) this.ready()
  }

  _reuse(db, opts = {}) {
    const { autoDestroy = false } = opts

    db._ref()

    this._db = db
    this._destroyed = false
    this._autoDestroy = autoDestroy
  }

  _onfinished(err) {
    const resolve = this._resolve
    const reject = this._reject

    if (this._request) this._db._state.io.dec()

    this._operations = []
    this._promises = []
    this._request = null
    this._resolve = null
    this._reject = null

    this._resetStats()

    if (this._autoDestroy === true) this.destroy()

    if (reject !== null && err) reject(err)
    else if (resolve !== null) resolve()
  }

  _resize() {
    if (this._operations.length <= this._capacity) return false

    while (this._operations.length > this._capacity) {
      this._capacity *= 2
    }

    return true
  }

  async ready() {
    if (this._handle !== null) return

    if (this._db._state.opened === false) await this._db._state.ready()

    this._init()
  }

  destroy() {
    if (this._request) throw new Error('Request in progress')
    if (this._destroyed) return

    this._destroyed = true

    if (this._promises.length) this._abort()

    this._db._unref()
    this._onfree()
  }

  _onfree() {
    this._resetStats()
    this._db._state.freeBatch(this, false)
    this._db = null
  }

  _abort() {
    for (let i = 0; i < this._promises.length; i++) {
      const promise = this._promises[i]
      if (promise !== null) promise.reject(new Error('Batch is destroyed'))
    }

    this._onfinished(new Error('Batch is destroyed'))
  }

  _resetStats() {}

  async flush() {
    if (this._request) throw new Error('Request in progress')
    if (this._destroyed) throw new Error('Batch is destroyed')

    this._request = new Promise((resolve, reject) => {
      this._resolve = resolve
      this._reject = reject
    })

    this._flush()

    return this._request
  }

  tryFlush() {
    if (this._request) throw new Error('Request in progress')
    if (this._destroyed) throw new Error('Batch is destroyed')

    this._request = resolved

    this._flush()
  }

  async _flush() {
    if (this._handle === null) await this.ready()

    this._db._state.io.inc()

    if (this._db._state.resumed !== null) {
      const resumed = await this._db._state.resumed.promise

      if (!resumed) {
        if (this._destroyed) {
          this._db._state.io.dec()
        } else {
          this._destroyed = true
          this._abort()
          this._db._unref()
        }
      }
    }
  }

  _enqueuePromise(resolve, reject) {
    this._promises.push({ resolve, reject })
  }

  _encodeKey(k) {
    if (this._db._keyEncoding) return c.encode(this._db._keyEncoding, k)
    if (typeof k === 'string') return Buffer.from(k)
    return k
  }

  _encodeValue(v) {
    if (this._db._valueEncoding) return c.encode(this._db._valueEncoding, v)
    if (v === null) return empty
    if (typeof v === 'string') return Buffer.from(v)
    return v
  }

  _decodeValue(b) {
    if (this._db._valueEncoding) return c.decode(this._db._valueEncoding, b)
    return b
  }
}

exports.ReadBatch = class RocksDBReadBatch extends RocksDBBatch {
  constructor(db, opts = {}) {
    super(db, opts)

    const { asyncIO = false, fillCache = true } = opts

    this._asyncIO = asyncIO
    this._fillCache = fillCache
  }

  _init() {
    this._handle = binding.readInit()
    this._buffer = binding.readBuffer(this._handle, this._capacity)
  }

  _resize() {
    if (super._resize() && this._handle !== null) {
      this._buffer = binding.readBuffer(this._handle, this._capacity)
    }
  }

  async _flush() {
    await super._flush()

    if (this._destroyed) return

    try {
      binding.read(
        this._db._state._handle,
        this._handle,
        this._operations,
        this._db._snapshot ? this._db._snapshot._handle : undefined,
        this._asyncIO,
        this._fillCache,
        this,
        this._onread
      )
    } catch (err) {
      this._db._state.io.dec()
      throw err
    }

    this._db._state.stats.gets += this._stats.gets
    this._db._state.stats.readBatches++
  }

  _onread(errs, values) {
    let applied = true

    for (let i = 0, n = this._promises.length; i < n; i++) {
      const err = errs[i]
      if (err) applied = false

      const promise = this._promises[i]
      if (promise === null) continue

      if (err) promise.reject(err)
      else promise.resolve(values[i] ? this._decodeValue(Buffer.from(values[i])) : null)
    }

    this._onfinished(applied ? null : new AggregateError(errs, 'Batch was not applied'))
  }

  _resetStats() {
    this._stats = { gets: 0 }
  }

  get(key) {
    if (this._request) throw new Error('Request already in progress')
    this._stats.gets++

    const promise = new Promise(this._enqueuePromise)

    this._operations.push(new RocksDBGet(this._encodeKey(key), this._db._columnFamily))

    this._resize()

    return promise
  }
}

exports.WriteBatch = class RocksDBWriteBatch extends RocksDBBatch {
  _init() {
    this._handle = binding.writeInit()
    this._buffer = binding.writeBuffer(this._handle, this._capacity)
  }

  _resize() {
    if (super._resize() && this._handle !== null) {
      this._buffer = binding.writeBuffer(this._handle, this._capacity)
    }
  }

  _onfree() {
    this._resetStats()
    this._db._state.freeBatch(this, true)
    this._db = null
  }

  async _flush() {
    await super._flush()

    if (this._destroyed) return

    try {
      binding.write(this._db._state._handle, this._handle, this._operations, this, this._onwrite)
    } catch (err) {
      this._db._state.io.dec()
      throw err
    }

    this._db._state.stats.puts += this._stats.puts
    this._db._state.stats.deletes += this._stats.deletes
    this._db._state.stats.rangeDeletes += this._stats.rangeDeletes
    this._db._state.stats.writeBatches++
  }

  _onwrite(err) {
    const applied = !err

    for (let i = 0, n = this._promises.length; i < n; i++) {
      const promise = this._promises[i]
      if (promise === null) continue

      if (err) promise.reject(err)
      else promise.resolve()
    }

    this._onfinished(applied ? null : new Error('Batch was not applied', { cause: err }))
  }

  _resetStats() {
    this._stats = { puts: 0, deletes: 0, rangeDeletes: 0 }
  }

  put(key, value) {
    if (this._request) throw new Error('Request already in progress')
    this._stats.puts++

    const promise = new Promise(this._enqueuePromise)

    this._operations.push(
      new RocksDBPut(this._encodeKey(key), this._encodeValue(value), this._db._columnFamily)
    )

    this._resize()

    return promise
  }

  tryPut(key, value) {
    if (this._request) throw new Error('Request already in progress')
    this._stats.puts++

    this._operations.push(
      new RocksDBPut(this._encodeKey(key), this._encodeValue(value), this._db._columnFamily)
    )

    this._promises.push(null)

    this._resize()
  }

  delete(key) {
    if (this._request) throw new Error('Request already in progress')
    this._stats.deletes++

    const promise = new Promise(this._enqueuePromise)

    this._operations.push(new RocksDBDelete(this._encodeKey(key), this._db._columnFamily))

    this._resize()

    return promise
  }

  tryDelete(key) {
    if (this._request) throw new Error('Request already in progress')
    this._stats.deletes++

    this._operations.push(new RocksDBDelete(this._encodeKey(key), this._db._columnFamily))

    this._promises.push(null)

    this._resize()
  }

  deleteRange(start, end) {
    if (this._request) throw new Error('Request already in progress')
    this._stats.rangeDeletes++

    const promise = new Promise(this._enqueuePromise)

    this._operations.push(
      new RocksDBDeleteRange(this._encodeKey(start), this._encodeKey(end), this._db._columnFamily)
    )

    this._resize()

    return promise
  }

  tryDeleteRange(start, end) {
    if (this._request) throw new Error('Request already in progress')
    this._stats.rangeDeletes++

    this._operations.push(
      new RocksDBDeleteRange(this._encodeKey(start), this._encodeKey(end), this._db._columnFamily)
    )

    this._promises.push(null)

    this._resize()
  }
}

class RocksDBGet {
  constructor(key, columnFamily) {
    this.key = key
    this.columnFamily = columnFamily._handle
  }

  get type() {
    return binding.GET
  }
}

class RocksDBPut {
  constructor(key, value, columnFamily) {
    this.key = key
    this.value = value
    this.columnFamily = columnFamily._handle
  }

  get type() {
    return binding.PUT
  }
}

class RocksDBDelete {
  constructor(key, columnFamily) {
    this.key = key
    this.columnFamily = columnFamily._handle
  }

  get type() {
    return binding.DELETE
  }
}

class RocksDBDeleteRange {
  constructor(start, end, columnFamily) {
    this.start = start
    this.end = end
    this.columnFamily = columnFamily._handle
  }

  get type() {
    return binding.DELETE_RANGE
  }
}
const binding = require('../binding')
const constants = require('./constants')
const { BloomFilterPolicy } = require('./filter-policy')

class RocksDBColumnFamily {
  constructor(name, opts = {}) {
    const {
      // Blob options
      enableBlobFiles = false,
      minBlobSize = 0,
      blobFileSize = 0,
      enableBlobGarbageCollection = true,
      // Block table options
      tableBlockSize = 8192,
      tableCacheIndexAndFilterBlocks = true,
      tableFormatVersion = 6,
      optimizeFiltersForMemory = false,
      blockCache = true,
      filterPolicy = new BloomFilterPolicy(10),
      topLevelIndexPinningTier = constants.pinningTier.ALL,
      partitionPinningTier = constants.pinningTier.ALL,
      unpartitionedPinningTier = constants.pinningTier.ALL,
      optimizeFiltersForHits = false,
      numLevels = 7,
      maxWriteBufferNumber = 2,
      blobGarbageCollectionAgeCutOff = 0.25,
      blobGarbageCollectionForceThreshold = 1.0
    } = opts

    this._name = name
    this._flushing = null
    this._options = {
      enableBlobFiles,
      minBlobSize,
      blobFileSize,
      enableBlobGarbageCollection,
      tableBlockSize,
      tableCacheIndexAndFilterBlocks,
      tableFormatVersion,
      optimizeFiltersForMemory,
      blockCache,
      filterPolicy,
      topLevelIndexPinningTier,
      partitionPinningTier,
      unpartitionedPinningTier,
      optimizeFiltersForHits,
      numLevels,
      maxWriteBufferNumber,
      blobGarbageCollectionAgeCutOff,
      blobGarbageCollectionForceThreshold
    }

    const filterPolicyArguments = [0, 0, 0]

    if (filterPolicy !== null) {
      filterPolicyArguments[0] = filterPolicy.type

      switch (filterPolicy.type) {
        case 1: // Bloom filter policy
          filterPolicyArguments[1] = filterPolicy.bitsPerKey
          break
        case 2: // Ribbon filter policy
          filterPolicyArguments[1] = filterPolicy.bloomEquivalentBitsPerKey
          filterPolicyArguments[2] = filterPolicy.bloomBeforeLevel

          break
      }
    }

    this._handle = binding.columnFamilyInit(
      name,
      enableBlobFiles,
      minBlobSize,
      blobFileSize,
      enableBlobGarbageCollection,
      tableBlockSize,
      tableCacheIndexAndFilterBlocks,
      tableFormatVersion,
      optimizeFiltersForMemory,
      blockCache === false,
      ...filterPolicyArguments,
      topLevelIndexPinningTier,
      partitionPinningTier,
      unpartitionedPinningTier,
      optimizeFiltersForHits,
      numLevels,
      maxWriteBufferNumber,
      blobGarbageCollectionAgeCutOff,
      blobGarbageCollectionForceThreshold
    )
  }

  cloneSettings(name) {
    return new RocksDBColumnFamily(name, this._options)
  }

  get name() {
    return this._name
  }

  destroy() {
    if (this._handle === null) return

    binding.columnFamilyDestroy(this._handle)

    this._handle = null
  }
}

module.exports = RocksDBColumnFamily
module.exports = {
  pinningTier: {
    NONE: 0,
    FLUSHED_AND_SIMILAR: 1,
    ALL: 2
  },
  garbageCollectionPolicy: {
    DEFAULT: 0,
    FORCE: 1,
    DISABLE: 2
  },
  bottommostLevelCompaction: {
    NONE: 0,
    SKIP: 1,
    FORCE: 2
  },
  walRecoveryMode: {
    TOLERATE_CORRUPTED_TAIL_RECORDS: 0,
    ABSOLUTE_CONSISTENCY: 1,
    POINT_IN_TIME: 2,
    SKIP_ANY_CORRUPTED_RECORDS: 3
  },
  statsLevel: {
    DISABLE_ALL: 0,
    EXCEPT_HISTOGRAM_OR_TIMERS: 1,
    EXCEPT_TIMERS: 2,
    EXCEPT_DETAILED_TIMERS: 3,
    EXCEPT_TIME_FOR_MUTEX: 4,
    ALL: 5
  },
  walFileType: {
    ARCHIVED: 0,
    ALIVE: 1
  }
}
exports.BloomFilterPolicy = class RocksDBBloomFilterPolicy {
  get type() {
    return 1
  }

  constructor(bitsPerKey) {
    this.bitsPerKey = bitsPerKey
  }
}

exports.RibbonFilterPolicy = class RocksDBRibbonFilterPolicy {
  get type() {
    return 2
  }

  constructor(bloomEquivalentBitsPerKey, bloomBeforeLevel = 0) {
    this.bloomEquivalentBitsPerKey = bloomEquivalentBitsPerKey
    this.bloomBeforeLevel = bloomBeforeLevel
  }
}
const { Readable } = require('streamx')
const c = require('compact-encoding')
const binding = require('../binding')

const empty = Buffer.alloc(0)

module.exports = class RocksDBIterator extends Readable {
  constructor(db, opts = {}) {
    const {
      gt = null,
      gte = null,
      lt = null,
      lte = null,
      reverse = false,
      values = true,
      limit = Infinity,
      capacity = 8
    } = opts

    super()

    db._ref()

    this._db = db

    this._gt = gt ? this._encodeKey(gt) : empty
    this._gte = gte ? this._encodeKey(gte) : empty
    this._lt = lt ? this._encodeKey(lt) : empty
    this._lte = lte ? this._encodeKey(lte) : empty

    this._reverse = reverse
    this._values = values
    this._limit = limit < 0 ? Infinity : limit
    this._capacity = capacity
    this._opened = false

    this._pendingOpen = null
    this._pendingRead = null
    this._pendingDestroy = null

    this._buffer = null
    this._handle = null

    if (this._db._state.opened === true) this.ready()
  }

  _onopen(err) {
    const cb = this._pendingOpen
    this._pendingOpen = null
    this._opened = true
    this._db._state.io.dec()
    cb(err)
  }

  _onread(err, keys, values) {
    const cb = this._pendingRead
    this._pendingRead = null
    this._db._state.io.dec()
    if (err) return cb(err)

    const n = keys.length

    this._limit -= n

    for (let i = 0; i < n; i++) {
      this.push({
        key: this._decodeKey(Buffer.from(keys[i])),
        value: this._values ? this._decodeValue(Buffer.from(values[i])) : null
      })
    }

    if (n < this._capacity) this.push(null)

    cb(null)
  }

  _onclose(err) {
    const cb = this._pendingDestroy
    this._pendingDestroy = null
    this._db._state.io.dec()
    this._db._unref()
    cb(err)
  }

  _resize() {
    if (this._handle !== null) {
      this._buffer = binding.iteratorBuffer(this._handle, this._capacity)
    }
  }

  async ready() {
    if (this._handle !== null) return

    if (this._db._state.opened === false) await this._db._state.ready()

    this._init()
  }

  _init() {
    this._handle = binding.iteratorInit()
    this._buffer = binding.iteratorBuffer(this._handle, this._capacity)
  }

  async _open(cb) {
    await this.ready()

    this._db._state.io.inc()

    if (this._db._state.resumed !== null) {
      const resumed = await this._db._state.resumed.promise

      if (!resumed) {
        this._db._state.io.dec()

        return cb(new Error('RocksDB session is closed'))
      }
    }

    this._pendingOpen = cb

    try {
      binding.iteratorOpen(
        this._db._state._handle,
        this._handle,
        this._db._columnFamily._handle,
        this._gt,
        this._gte,
        this._lt,
        this._lte,
        this._reverse,
        !this._values, // Keys only
        this._db._snapshot ? this._db._snapshot._handle : undefined,
        this,
        this._onopen,
        this._onclose,
        this._onread
      )
    } catch (err) {
      this._db._state.io.dec()

      cb(err)
    }
  }

  async _read(cb) {
    this._db._state.io.inc()

    if (this._db._state.resumed !== null) {
      const resumed = await this._db._state.resumed.promise

      if (!resumed) {
        this._db._state.io.dec()

        return cb(new Error('RocksDB session is closed'))
      }
    }

    this._pendingRead = cb

    try {
      binding.iteratorRead(this._handle, Math.min(this._capacity, this._limit))
    } catch (err) {
      this._db._state.io.dec()

      cb(err)
    }
  }

  async _destroy(cb) {
    await this.ready()

    this._db._state.io.inc()

    if (this._opened === false) {
      this._db._state.io.dec()
      this._db._unref()

      return cb(null)
    }

    this._pendingDestroy = cb

    try {
      binding.iteratorClose(this._handle)
    } catch (err) {
      this._db._state.io.dec()
      this._db._unref()

      cb(err)
    }
  }

  _encodeKey(k) {
    if (this._db._keyEncoding !== null) return c.encode(this._db._keyEncoding, k)
    if (typeof k === 'string') return Buffer.from(k)
    return k
  }

  _decodeKey(b) {
    if (this._db._keyEncoding !== null) return c.decode(this._db._keyEncoding, b)
    return b
  }

  _decodeValue(b) {
    if (this._db._valueEncoding !== null) return c.decode(this._db._valueEncoding, b)
    return b
  }
}
const binding = require('../binding')

module.exports = class RocksDBSnapshot {
  constructor(state) {
    this._state = state

    this._handle = null
    this._refs = 0

    if (state.deferSnapshotInit === false) this._init()
  }

  _init() {
    this._handle = binding.snapshotCreate(this._state._handle)
  }

  ref() {
    this._refs++
  }

  unref() {
    if (--this._refs > 0) return

    if (this._handle === null) return

    binding.snapshotDestroy(this._handle)

    this._handle = null
  }
}
const ReadyResource = require('ready-resource')
const RefCounter = require('refcounter')
const rrp = require('resolve-reject-promise')
const SignalPromise = require('signal-promise')
const c = require('compact-encoding')
const { ReadBatch, WriteBatch } = require('./batch')
const ColumnFamily = require('./column-family')
const binding = require('../binding')
const constants = require('./constants')

const MAX_BATCH_REUSE = 64
const empty = Buffer.alloc(0)

module.exports = class RocksDBState extends ReadyResource {
  constructor(db, path, opts) {
    super()

    const {
      columnFamily = new ColumnFamily('default', opts),
      columnFamilies = [],
      readOnly = false,
      createIfMissing = true,
      createMissingColumnFamilies = true,
      maxBackgroundJobs = 6,
      bytesPerSync = 1048576,
      maxOpenFiles = -1,
      useDirectReads = false,
      avoidUnnecessaryBlockingIO = false,
      skipStatsUpdateOnOpen = false,
      useDirectIOForFlushAndCompaction = false,
      maxFileOpeningThreads = 16,
      lock = null,
      walRecoveryMode = constants.walRecoveryMode.POINT_IN_TIME,
      bestEffortsRecovery = false,
      enableStatistics = false,
      statsLevel = constants.statsLevel.EXCEPT_HISTOGRAM_OR_TIMERS,
      walTtlSeconds = 0,
      walSizeLimitMegabytes = 0,
      avoidFlushDuringShutdown = false,
      walFilterPrefixes = []
    } = opts

    this.path = path
    this.db = db
    this.handles = new RefCounter()
    this.io = new RefCounter()
    this.sessions = []
    this.columnFamilies = [columnFamily]
    this.deferSnapshotInit = true
    this.resumed = null
    this.stats = {
      gets: 0,
      puts: 0,
      deletes: 0,
      rangeDeletes: 0,
      readBatches: 0,
      writeBatches: 0
    }

    this._suspended = false
    this._suspending = false
    this._updating = false
    this._updatingSignal = new SignalPromise()
    this._columnsFlushed = false
    this._lock = lock
    this._readBatches = []
    this._writeBatches = []

    for (const columnFamily of columnFamilies) {
      this.columnFamilies.push(
        typeof columnFamily === 'string' ? new ColumnFamily(columnFamily, opts) : columnFamily
      )
    }

    this._handle = binding.init(
      readOnly,
      createIfMissing,
      createMissingColumnFamilies,
      maxBackgroundJobs,
      bytesPerSync,
      maxOpenFiles,
      useDirectReads,
      avoidUnnecessaryBlockingIO,
      skipStatsUpdateOnOpen,
      useDirectIOForFlushAndCompaction,
      maxFileOpeningThreads,
      walRecoveryMode,
      bestEffortsRecovery,
      enableStatistics,
      statsLevel,
      walTtlSeconds,
      walSizeLimitMegabytes,
      avoidFlushDuringShutdown,
      walFilterPrefixes.map(encodePrefix)
    )
  }

  createReadBatch(db, opts) {
    if (this._readBatches.length === 0) return new ReadBatch(db, opts)
    const batch = this._readBatches.pop()
    batch._reuse(db, opts)
    return batch
  }

  createWriteBatch(db, opts) {
    if (this._writeBatches.length === 0) return new WriteBatch(db, opts)
    const batch = this._writeBatches.pop()
    batch._reuse(db, opts)
    return batch
  }

  freeBatch(batch, writable) {
    if (batch._capacity > 16) return
    const queue = writable ? this._writeBatches : this._readBatches
    if (queue.length >= MAX_BATCH_REUSE) return
    queue.push(batch)
  }

  addSession(db) {
    db._index = this.sessions.push(db) - 1
    if (db._snapshot) db._snapshot.ref()
  }

  removeSession(db) {
    const head = this.sessions.pop()
    if (head !== db) this.sessions[(head._index = db._index)] = head
    db._index = -1
    if (db._snapshot) db._snapshot.unref()
  }

  upsertColumnFamily(c) {
    if (typeof c === 'string') {
      let col = this.getColumnFamilyByName(c)
      if (col) return col
      col = this.columnFamilies[0].cloneSettings(c)
      this.columnFamilies.push(col)
      return col
    }

    if (this.columnFamilies.includes(c)) return c
    this.columnFamilies.push(c)
    return c
  }

  getColumnFamily(c) {
    if (!c) return this.columnFamilies[0]
    if (!this._columnsFlushed) return this.upsertColumnFamily(c)

    if (typeof c !== 'string') return c

    const col = this.getColumnFamilyByName(c)
    if (col === null) throw new Error('Unknown column family')
    return col
  }

  getColumnFamilyByName(name) {
    for (const col of this.columnFamilies) {
      if (col.name === name) return col
    }
    return null
  }

  async _open() {
    await Promise.resolve() // Allow column families to populate if on-demand

    if (this._lock) await this._lock.ready()

    const req = { resolve: null, reject: null, handle: null }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    this._columnsFlushed = true

    const lock = this._lock === null ? -1 : this._lock.transfer()

    req.handle = binding.open(
      this._handle,
      this,
      this.path,
      this.columnFamilies.map((c) => c._handle),
      lock,
      req,
      onopen
    )

    await promise

    this.deferSnapshotInit = false

    for (const session of this.sessions) {
      if (session._snapshot) session._snapshot._init()
    }

    function onopen(err) {
      if (err) req.reject(err)
      else req.resolve()
    }
  }

  async _close() {
    while (this._updating) await this._updatingSignal.wait()
    if (this.resumed) this.resumed.resolve(false)

    while (!this.io.isIdle()) await this.io.idle()
    while (!this.handles.isIdle()) await this.handles.idle()

    while (this.sessions.length > 0) {
      await this.sessions[this.sessions.length - 1].close()
    }

    for (const columnFamily of this.columnFamilies) columnFamily.destroy()

    const req = { resolve: null, reject: null, handle: null }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    req.handle = binding.close(this._handle, req, onclose)

    try {
      await promise
    } finally {
      if (this._lock) await this._lock.close()
    }

    function onclose(err) {
      if (err) req.reject(err)
      else req.resolve()
    }
  }

  async flush(db, opts) {
    if (this.opened === false) await this.ready()

    this.io.inc()

    if (this.resumed !== null) {
      const resumed = await this.resumed.promise

      if (!resumed) {
        this.io.dec()

        throw new Error('RocksDB session is closed')
      }
    }

    const req = { resolve: null, reject: null, handle: null }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    try {
      req.handle = binding.flush(this._handle, db._columnFamily._handle, req, onflush)

      await promise
    } finally {
      this.io.dec()
    }

    function onflush(err) {
      if (err) req.reject(err)
      else req.resolve()
    }
  }

  suspend() {
    this._suspending = true
    return this.update()
  }

  resume() {
    this._suspending = false
    return this.update()
  }

  async update() {
    while (this._updating) await this._updatingSignal.wait()
    if (this._suspending === this._suspended || this.closing) return
    this._updating = true
    try {
      if (this._suspending) await this._suspend()
      else await this._resume()
    } finally {
      this._updating = false
      this._updatingSignal.notify()
    }
  }

  async _suspend() {
    if (this._suspended === true) return

    while (!this.io.isIdle()) await this.io.idle()

    this.io.inc()
    this.resumed = rrp()

    const req = { resolve: null, reject: null, handle: null }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    try {
      req.handle = binding.suspend(this._handle, req, onsuspend)

      await promise

      this._suspended = true
    } finally {
      this.io.dec()
    }

    function onsuspend(err) {
      if (err) req.reject(err)
      else req.resolve()
    }
  }

  async _resume() {
    if (this._suspended === false) return

    const req = { resolve: null, reject: null, handle: null }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    req.handle = binding.resume(this._handle, req, onresume)

    await promise

    this._suspended = false

    const resumed = this.resumed
    this.resumed = null
    resumed.resolve(true)

    function onresume(err) {
      if (err) req.reject(err)
      else req.resolve()
    }
  }

  async compact(db, opts) {
    if (this.opened === false) await this.ready()

    this.io.inc()

    const {
      exclusive = false,
      blobGarbageCollectionPolicy = constants.garbageCollectionPolicy.DEFAULT,
      blobGarbageCollectionAgeCutoff = 0.25,
      bottommostLevelCompaction = constants.bottommostLevelCompaction.NONE
    } = opts

    const req = { resolve: null, reject: null, handle: null }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    try {
      req.handle = binding.compact(
        this._handle,
        db._columnFamily._handle,
        exclusive,
        blobGarbageCollectionPolicy,
        blobGarbageCollectionAgeCutoff,
        bottommostLevelCompaction,
        req,
        oncompact
      )

      await promise
    } finally {
      this.io.dec()
    }

    function oncompact(err) {
      if (err) req.reject(err)
      else req.resolve()
    }
  }

  async compactRange(db, start, end, opts) {
    if (this.opened === false) await this.ready()

    this.io.inc()

    const {
      exclusive = false,
      blobGarbageCollectionPolicy = constants.garbageCollectionPolicy.DEFAULT,
      blobGarbageCollectionAgeCutoff = 0.25,
      bottommostLevelCompaction = constants.bottommostLevelCompaction.NONE
    } = opts

    start = this._encodeKey(start)
    end = this._encodeKey(end)

    const req = { resolve: null, reject: null, handle: null, start, end }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    try {
      req.handle = binding.compactRange(
        this._handle,
        db._columnFamily._handle,
        start,
        end,
        exclusive,
        blobGarbageCollectionPolicy,
        blobGarbageCollectionAgeCutoff,
        bottommostLevelCompaction,
        req,
        oncompactrange
      )

      await promise
    } finally {
      this.io.dec()
    }

    function oncompactrange(err) {
      if (err) req.reject(err)
      else req.resolve()
    }
  }

  async approximateSize(db, start, end, opts) {
    if (this.opened === false) await this.ready()

    this.io.inc()

    const { includeMemtables = false, includeFiles = true, filesSizeErrorMargin = -1 } = opts

    start = this._encodeKey(start)
    end = this._encodeKey(end)

    const req = { resolve: null, reject: null, handle: null, start, end }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    try {
      req.handle = binding.approximateSize(
        this._handle,
        db._columnFamily._handle,
        start,
        end,
        includeMemtables,
        includeFiles,
        filesSizeErrorMargin,
        req,
        onapproximatesize
      )

      return await promise
    } finally {
      this.io.dec()
    }

    function onapproximatesize(err, result) {
      if (err) req.reject(err)
      else req.resolve(result)
    }
  }

  async currentWalFile() {
    if (this.opened === false) await this.ready()

    this.io.inc()

    const req = { resolve: null, reject: null, handle: null }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    try {
      req.handle = binding.currentWalFile(this._handle, req, oncurrentwalfile)

      return await promise
    } finally {
      this.io.dec()
    }

    function oncurrentwalfile(err, path, number, type, startSequence, size) {
      if (err) req.reject(err)
      else req.resolve({ path, number, type, startSequence, size })
    }
  }

  async getStatsLevel() {
    if (this.opened === false) await this.ready()

    return binding.statsLevelGet(this._handle)
  }

  async setStatsLevel(level) {
    if (this.opened === false) await this.ready()

    binding.statsLevelSet(this._handle, level)
  }

  async getProperty(name) {
    if (this.opened === false) await this.ready()

    return binding.propertyGet(this._handle, name)
  }

  _encodeKey(k) {
    if (this.db._keyEncoding) return c.encode(this.db._keyEncoding, k)
    if (typeof k === 'string') return Buffer.from(k)
    if (k === null) return empty
    return k
  }

  diagnostics() {
    return {
      suspended: this._suspended,
      suspending: this._suspending,
      updating: this._updating,
      resumedPending: this.resumed !== null,
      io: this.io.count,
      handles: this.handles.count,
      sessions: this.sessions.length
    }
  }
}

function encodePrefix(prefix) {
  if (typeof prefix === 'string') return Buffer.from(prefix)
  return prefix
}
{
  "name": "rocksdb-native",
  "version": "3.17.2",
  "description": "librocksdb bindings for JavaScript",
  "exports": {
    ".": "./index.js",
    "./package": "./package.json"
  },
  "imports": {
    "crypto": {
      "bare": "bare-crypto",
      "default": "crypto"
    },
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    }
  },
  "files": [
    "index.js",
    "binding.cc",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds",
    "!prebuilds/android-*/**/*.node"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:bare && npm run test:node",
    "test:bare": "brittle-bare --coverage test.js",
    "test:node": "brittle-node --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/rocksdb-native.git"
  },
  "author": "Holepunch Inc",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/rocksdb-native/issues"
  },
  "homepage": "https://github.com/holepunchto/rocksdb-native",
  "engines": {
    "bare": ">=1.16.0"
  },
  "dependencies": {
    "compact-encoding": "^3.0.0",
    "ready-resource": "^1.0.0",
    "refcounter": "^1.0.0",
    "require-addon": "^1.0.2",
    "resolve-reject-promise": "^1.1.0",
    "signal-promise": "^1.0.3",
    "streamx": "^2.16.1"
  },
  "devDependencies": {
    "bare-compat-napi": "^1.3.0",
    "bare-crypto": "^1.12.0",
    "bare-fs": "^4.5.0",
    "bare-path": "^3.0.0",
    "brittle": "^3.5.0",
    "cmake-bare": "^1.1.14",
    "cmake-fetch": "^1.0.1",
    "cmake-napi": "^1.0.6",
    "fd-lock": "^2.0.0",
    "lunte": "^1.8.0",
    "paparam": "^1.9.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = safetyCatch

function isActuallyUncaught (err) {
  if (!err) return false
  return err instanceof TypeError ||
    err instanceof SyntaxError ||
    err instanceof ReferenceError ||
    err instanceof EvalError ||
    err instanceof RangeError ||
    err instanceof URIError ||
    err.code === 'ERR_ASSERTION' ||
    err.name === 'AssertionError'
}

function throwErrorNT (err) {
  queueMicrotask(() => { throw err })
}

function safetyCatch (err) {
  if (isActuallyUncaught(err)) {
    throwErrorNT(err)
    throw err
  }
}
{
  "name": "safety-catch",
  "version": "1.0.3",
  "description": "Small module that makes sure your catch, caught an actual error and not a programming mistake or assertion",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {},
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/safety-catch.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/safety-catch/issues"
  },
  "homepage": "https://github.com/mafintosh/safety-catch"
}
let tmpResolve = null

module.exports = class ScopeLock {
  constructor ({ debounce = false } = {}) {
    this.debounce = debounce
    this.waiting = []
    this.locked = false
    this.skip = 0
    this.destroyed = false
  }

  flush () {
    if (this.locked === false && this.waiting.length === 0) return Promise.resolve(this.destroyed === false)

    const promise = new Promise(setTmpResolve)
    const resolve = tmpResolve

    tmpResolve = null
    this.waiting.push({ lock: false, resolve })

    return promise
  }

  destroy () {
    this.destroyed = true
  }

  lock () {
    const promise = new Promise(setTmpResolve)
    const resolve = tmpResolve

    tmpResolve = null

    if (this.locked === true) {
      this.waiting.push({ lock: true, resolve })
      return promise
    }

    if (this.destroyed === true) {
      resolve(false)
      return promise
    }

    this.locked = true
    resolve(true)

    return promise
  }

  unlock () {
    if (this.destroyed === true) {
      for (let i = 0; i < this.waiting.length; i++) {
        this.waiting[i].resolve(false)
      }
      this.waiting = []
      this.skip = 0
      this.locked = false
      return
    }

    if (this.skip !== 0) {
      for (let i = 0; i < this.skip; i++) {
        const { lock, resolve } = this.waiting[i]
        resolve(lock === false)
      }

      this.waiting = this.waiting.slice(this.skip)
      this.skip = 0
    }

    while (this.waiting.length > 0 && this.waiting[0].lock === false) {
      this.waiting.shift().resolve(true)
    }

    if (this.waiting.length === 0) {
      this.locked = false
      return
    }

    const { resolve } = this.waiting.shift()
    if (this.debounce === true) this.skip = this.waiting.length

    resolve(true)
  }
}

function setTmpResolve (resolve) {
  tmpResolve = resolve
}
{
  "name": "scope-lock",
  "version": "1.2.4",
  "description": "Some concurrency semantics around entering scopes",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "devDependencies": {
    "brittle": "^3.7.0",
    "standard": "^17.1.2"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/scope-lock.git"
  },
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/scope-lock/issues"
  },
  "homepage": "https://github.com/holepunchto/scope-lock"
}
module.exports = class Signal {
  constructor () {
    this._resolve = null
    this._reject = null
    this._promise = null
    this._bind = bind.bind(this)
    this._onerror = clear.bind(this)
    this._onsuccess = clear.bind(this, null)
    this._timers = new Set()
  }

  wait (max) {
    if (!this._promise) {
      this._promise = new Promise(this._bind)
      this._promise.then(this._onsuccess).catch(this._onerror)
    }
    if (max) return this._sleep(max)
    return this._promise
  }

  _sleep (max) {
    const s = new Promise((resolve, reject) => {
      const done = () => {
        this._timers.delete(state)
        resolve(true)
      }
      const id = setTimeout(done, max)
      const state = { id, resolve, reject }
      this._timers.add(state)
    })

    return s
  }

  notify (err) {
    if (!this._promise) return
    const resolve = this._resolve
    const reject = this._reject
    this._promise = null
    if (err) reject(err)
    else resolve(true)
  }
}

function clear (err) {
  for (const { id, resolve, reject } of this._timers) {
    clearTimeout(id)
    if (err) reject(err)
    else resolve(true)
  }
  this._timers.clear()
}

function bind (resolve, reject) {
  this._resolve = resolve
  this._reject = reject
}
{
  "name": "signal-promise",
  "version": "1.0.3",
  "description": "Simple wait/notify promise with optional max wait time",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {},
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/signal-promise.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/signal-promise/issues"
  },
  "homepage": "https://github.com/mafintosh/signal-promise"
}
var varint = require('varint')
exports.encode = function encode (v, b, o) {
  v = v >= 0 ? v*2 : v*-2 - 1
  var r = varint.encode(v, b, o)
  encode.bytes = varint.encode.bytes
  return r
}
exports.decode = function decode (b, o) {
  var v = varint.decode(b, o)
  decode.bytes = varint.decode.bytes
  return v & 1 ? (v+1) / -2 : v / 2
}

exports.encodingLength = function (v) {
  return varint.encodingLength(v >= 0 ? v*2 : v*-2 - 1)
}
{
  "name": "signed-varint",
  "description": "efficiently store signed integers in varint",
  "version": "2.0.1",
  "homepage": "https://github.com/dominictarr/signed-varint",
  "repository": {
    "type": "git",
    "url": "git://github.com/dominictarr/signed-varint.git"
  },
  "dependencies": {
    "varint": "~5.0.0"
  },
  "devDependencies": {
    "tape": "~2.12.3"
  },
  "scripts": {
    "test": "node test.js"
  },
  "author": "Dominic Tarr <dominic.tarr@gmail.com> (http://dominictarr.com)",
  "license": "MIT"
}
require.addon = require('require-addon')

module.exports = require.addon('.', __filename)
const binding = require('./binding')
const b4a = require('b4a')

function predicate(u8, u16, u32) {
  return function predicate(buf) {
    if (buf.byteLength % 16 !== 0) {
      throw new Error('Buffer length must be a multiple of 16')
    }

    const n = buf.BYTES_PER_ELEMENT

    if (n === 1) return u8(buf)
    if (n === 2) return u16(buf)
    return u32(buf)
  }
}

function unary(u8, u16, u32) {
  return function unary(buf, result = b4a.allocUnsafe(buf.byteLength)) {
    if (buf.byteLength % 16 !== 0) {
      throw new Error('Buffer length must be a multiple of 16')
    }

    if (buf.byteLength !== result.byteLength) {
      throw new Error('Length of result buffer is insufficient')
    }

    const n = buf.BYTES_PER_ELEMENT

    if (n === 1) u8(buf, result)
    else if (n === 2) u16(buf, result)
    else u32(buf, result)

    return result
  }
}

function binary(u8, u16, u32) {
  return function binary(a, b, result = b4a.allocUnsafe(a.byteLength)) {
    if (a.byteLength % 16 !== 0) {
      throw new Error('Buffer length must be a multiple of 16')
    }

    if (a.byteLength !== b.byteLength || a.byteLength !== result.byteLength) {
      throw new Error('Buffers must be the same length')
    }

    const n = a.BYTES_PER_ELEMENT

    if (n === 1) u8(a, b, result)
    else if (n === 2) u16(a, b, result)
    else u32(a, b, result)

    return result
  }
}

function reduce(u8, u16, u32) {
  return function reduce(buf) {
    if (buf.byteLength % 16 !== 0) {
      throw new Error('Buffer length must be a multiple of 16')
    }

    const n = buf.BYTES_PER_ELEMENT

    if (n === 1) return u8(buf)
    if (n === 2) return u16(buf)
    return u32(buf)
  }
}

exports.allo = predicate(
  binding.simdle_native_allo_v128_u8,
  binding.simdle_native_allo_v128_u16,
  binding.simdle_native_allo_v128_u32
)

exports.allz = predicate(
  binding.simdle_native_allz_v128_u8,
  binding.simdle_native_allz_v128_u16,
  binding.simdle_native_allz_v128_u32
)

exports.and = binary(
  binding.simdle_native_and_v128_u8,
  binding.simdle_native_and_v128_u16,
  binding.simdle_native_and_v128_u32
)

exports.clear = binary(
  binding.simdle_native_clear_v128_u8,
  binding.simdle_native_clear_v128_u16,
  binding.simdle_native_clear_v128_u32
)

exports.clo = unary(
  binding.simdle_native_clo_v128_u8,
  binding.simdle_native_clo_v128_u16,
  binding.simdle_native_clo_v128_u32
)

exports.clz = unary(
  binding.simdle_native_clz_v128_u8,
  binding.simdle_native_clz_v128_u16,
  binding.simdle_native_clz_v128_u32
)

exports.cnt = unary(
  binding.simdle_native_cnt_v128_u8,
  binding.simdle_native_cnt_v128_u16,
  binding.simdle_native_cnt_v128_u32
)

exports.cto = unary(
  binding.simdle_native_cto_v128_u8,
  binding.simdle_native_cto_v128_u16,
  binding.simdle_native_cto_v128_u32
)

exports.ctz = unary(
  binding.simdle_native_ctz_v128_u8,
  binding.simdle_native_ctz_v128_u16,
  binding.simdle_native_ctz_v128_u32
)

exports.not = unary(
  binding.simdle_native_not_v128_u8,
  binding.simdle_native_not_v128_u16,
  binding.simdle_native_not_v128_u32
)

exports.or = binary(
  binding.simdle_native_or_v128_u8,
  binding.simdle_native_or_v128_u16,
  binding.simdle_native_or_v128_u32
)

exports.sum = reduce(
  binding.simdle_native_sum_v128_u8,
  binding.simdle_native_sum_v128_u16,
  binding.simdle_native_sum_v128_u32
)

exports.xor = binary(
  binding.simdle_native_xor_v128_u8,
  binding.simdle_native_xor_v128_u16,
  binding.simdle_native_xor_v128_u32
)
{
  "name": "simdle-native",
  "version": "1.3.9",
  "description": "libsimdle JavaScript bindings for Node.js",
  "main": "index.js",
  "files": [
    "index.js",
    "binding.cc",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check .",
    "test": "npm run lint && npm run test:bare && npm run test:node",
    "test:bare": "bare test.mjs",
    "test:node": "node test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/simdle-native.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/simdle-native/issues"
  },
  "homepage": "https://github.com/holepunchto/simdle-native#readme",
  "dependencies": {
    "b4a": "^1.6.0",
    "require-addon": "^1.1.0"
  },
  "devDependencies": {
    "bare-compat-napi": "^1.3.2",
    "brittle": "^3.1.0",
    "cmake-bare": "^1.1.7",
    "cmake-fetch": "^1.1.0",
    "cmake-napi": "^1.0.2",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  }
}
const b4a = require('b4a')
const scalar = require('./scalar')

function view (buf, n) {
  if (n === buf.BYTES_PER_ELEMENT) return buf

  let TypedArray

  if (n === 1) TypedArray = Uint8Array
  else if (n === 2) TypedArray = Uint16Array
  else TypedArray = Uint32Array

  return new TypedArray(buf.buffer, buf.byteOffset, buf.byteLength / n)
}

function unary (u8, u16 = u8, u32 = u16) {
  return function unary (buf, result = b4a.allocUnsafe(buf.byteLength)) {
    if (buf.byteLength % 16 !== 0) {
      throw new Error('Buffer length must be a multiple of 16')
    }

    if (buf.byteLength !== result.byteLength) {
      throw new Error('Length of result buffer is insufficient')
    }

    const n = buf.BYTES_PER_ELEMENT

    if (n === 1) u8(buf, view(result, n))
    else if (n === 2) u16(buf, view(result, n))
    else u32(buf, view(result, n))

    return result
  }
}

function binary (u8, u16 = u8, u32 = u16) {
  return function binary (a, b, result = b4a.allocUnsafe(a.byteLength)) {
    if (a.byteLength % 16 !== 0) {
      throw new Error('Buffer length must be a multiple of 16')
    }

    if (a.byteLength !== b.byteLength || a.byteLength !== result.byteLength) {
      throw new Error('Buffers must be the same length')
    }

    const n = a.BYTES_PER_ELEMENT

    if (n === 1) u8(a, b, view(result, n))
    else if (n === 2) u16(a, b, view(result, n))
    else u32(a, b, view(result, n))

    return result
  }
}

function reduce (u8, u16 = u8, u32 = u16) {
  return function reduce (buf) {
    if (buf.byteLength % 16 !== 0) {
      throw new Error('Buffer length must be a multiple of 16')
    }

    const n = buf.BYTES_PER_ELEMENT

    if (n === 1) return u8(buf)
    if (n === 2) return u16(buf)
    return u32(buf)
  }
}

exports.allo = function allo (buf) {
  if (buf.byteLength % 16 !== 0) {
    throw new Error('Buffer length must be a multiple of 16')
  }

  const m = 2 ** (buf.BYTES_PER_ELEMENT * 8) - 1

  for (let i = 0, n = buf.length; i < n; i++) {
    if (buf[i] !== m) return false
  }

  return true
}

exports.allz = function allz (buf) {
  if (buf.byteLength % 16 !== 0) {
    throw new Error('Buffer length must be a multiple of 16')
  }

  for (let i = 0, n = buf.length; i < n; i++) {
    if (buf[i] !== 0) return false
  }

  return true
}

exports.and = binary(
  (a, b, result) => {
    for (let i = 0, n = result.length; i < n; i++) {
      result[i] = a[i] & b[i]
    }
  }
)

exports.clear = binary(
  (a, b, result) => {
    for (let i = 0, n = result.length; i < n; i++) {
      result[i] = a[i] & ~b[i]
    }
  }
)

exports.clo = unary(
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = 24 - scalar.clo(buf[i])
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = 16 - scalar.clo(buf[i])
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = scalar.clo(buf[i])
    }
  }
)

exports.clz = unary(
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = 24 - scalar.clz(buf[i])
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = 16 - scalar.clz(buf[i])
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = scalar.clz(buf[i])
    }
  }
)

exports.cnt = unary(
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = scalar.cnt(buf[i]) & 0xff
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = scalar.cnt(buf[i]) & 0xffff
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = scalar.cnt(buf[i])
    }
  }
)

exports.cto = unary(
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = Math.min(scalar.cto(buf[i]), 8)
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = Math.min(scalar.cto(buf[i]), 16)
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = scalar.cto(buf[i])
    }
  }
)

exports.ctz = unary(
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = Math.min(scalar.ctz(buf[i]), 8)
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = Math.min(scalar.ctz(buf[i]), 16)
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = scalar.ctz(buf[i])
    }
  }
)

exports.not = unary(
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = ~buf[i]
    }
  }
)

exports.or = binary(
  (a, b, result) => {
    for (let i = 0, n = result.length; i < n; i++) {
      result[i] = a[i] | b[i]
    }
  }
)

exports.sum = reduce(
  (buf) => {
    let result = 0n

    for (let i = 0, n = buf.length; i < n; i++) {
      result += BigInt(buf[i])
    }

    return result
  }
)

exports.xor = binary(
  (a, b, result) => {
    for (let i = 0, n = result.length; i < n; i++) {
      result[i] = a[i] ^ b[i]
    }
  }
)
try {
  module.exports = require('simdle-native')
} catch {
  module.exports = require('./fallback')
}
{
  "name": "simdle-universal",
  "version": "1.1.2",
  "description": "Universal wrapper for libsimdle with a JavaScript fallback",
  "main": "index.js",
  "files": [
    "fallback.js",
    "index.js",
    "scalar.js"
  ],
  "browser": {
    "./index.js": "./fallback.js"
  },
  "scripts": {
    "test": "standard && brittle test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/simdle-universal.git"
  },
  "author": "Kasper Isager Dalsgarð <kasper@funktionel.co>",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/holepunchto/simdle-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/simdle-universal#readme",
  "dependencies": {
    "b4a": "^1.6.0"
  },
  "optionalDependencies": {
    "simdle-native": "^1.1.1"
  },
  "devDependencies": {
    "brittle": "^3.1.0",
    "standard": "^17.0.0"
  }
}
const clz = exports.clz = function clz (n) {
  return Math.clz32(n)
}

exports.clo = function clo (n) {
  return clz(~n)
}

const ctz = exports.ctz = function ctz (n) {
  return 32 - (n === 0 ? 0 : (clz(n & -n) + 1))
}

exports.cto = function cto (n) {
  return ctz(~n)
}

exports.cnt = function cnt (n) {
  n = n - ((n >>> 1) & 0x55555555)
  n = (n & 0x33333333) + ((n >>> 2) & 0x33333333)
  n = (n + (n >>> 4)) & 0x0f0f0f0f
  n = (n * 0x01010101) >>> 24
  return n
}
require.addon = require('require-addon')
module.exports = require.addon('.', __filename)
const assert = require('assert')
const binding = require('./binding')
const { isNode } = require('which-runtime')

const OPTIONAL = Buffer.from(new ArrayBuffer(0))

module.exports = exports = { ...binding }

// memory

exports.sodium_memzero = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  binding.sodium_memzero(buf)
}

exports.sodium_mlock = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  const res = binding.sodium_mlock(buf)

  if (res !== 0) throw new Error('memory lock failed')
}

exports.sodium_munlock = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  const res = binding.sodium_munlock(buf)

  if (res !== 0) throw new Error('memory unlock failed')
}

exports.sodium_malloc = function (size) {
  assert(size >= 0, 'invalid size')

  const buf = Buffer.from(binding.sodium_malloc(size))
  buf.secure = true
  return buf
}

exports.sodium_free = function (buf) {
  if (!buf || !buf.secure) return

  binding.sodium_free(buf.buffer)
}

exports.sodium_mprotect_noaccess = function (buf) {
  const res = binding.sodium_mprotect_noaccess(buf.buffer)

  if (res !== 0) throw new Error('failed to lock buffer')
}

exports.sodium_mprotect_readonly = function (buf) {
  const res = binding.sodium_mprotect_readonly(buf.buffer)

  if (res !== 0) throw new Error('failed to unlock buffer')
}

exports.sodium_mprotect_readwrite = function (buf) {
  const res = binding.sodium_mprotect_readwrite(buf.buffer)

  if (res !== 0) throw new Error('failed to unlock buffer')
}

// crypto_randombytes

exports.randombytes_buf = function (buffer) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')

  binding.randombytes_buf(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

exports.randombytes_buf_deterministic = function (buffer, seed) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    seed.byteLength === binding.randombytes_SEEDBYTES,
    "seed must be 'randombytes_SEEDBYTES' bytes"
  )

  binding.randombytes_buf_deterministic(
    buffer.buffer,
    buffer.byteOffset,
    buffer.byteLength,

    seed.buffer,
    seed.byteOffset,
    seed.byteLength
  )
}

// sodium_helpers

exports.sodium_memcmp = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  return binding.sodium_memcmp(a, b)
}

exports.sodium_add = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  binding.sodium_add(a, b)
}

exports.sodium_sub = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  binding.sodium_sub(a, b)
}

exports.sodium_compare = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  return binding.sodium_compare(a, b)
}

exports.sodium_is_zero = function (buffer, length) {
  if (length === undefined) length = buffer.byteLength

  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(length >= 0 && length <= buffer.byteLength, 'invalid length')

  return binding.sodium_is_zero(buffer, length)
}

exports.sodium_pad = function (buffer, unpaddedBuflen, blockSize) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(unpaddedBuflen <= buffer.byteLength, 'unpadded length cannot exceed buffer length')
  assert(blockSize <= buffer.byteLength, 'block size cannot exceed buffer length')
  assert(blockSize >= 1, 'block size must be at least 1 byte')
  assert(
    buffer.byteLength >= unpaddedBuflen + (blockSize - (unpaddedBuflen % blockSize)),
    'buf not long enough'
  )

  return binding.sodium_pad(buffer, unpaddedBuflen, blockSize)
}

exports.sodium_unpad = function (buffer, paddedBuflen, blockSize) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(paddedBuflen <= buffer.byteLength, 'unpadded length cannot exceed buffer length')
  assert(blockSize <= buffer.byteLength, 'block size cannot exceed buffer length')
  assert(blockSize >= 1, 'block size must be at least 1 byte')

  return binding.sodium_unpad(buffer, paddedBuflen, blockSize)
}

// crypto_sign

exports.crypto_sign_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )
  assert(
    seed.byteLength === binding.crypto_sign_SEEDBYTES,
    "seed must be 'crypto_sign_SEEDBYTES' bytes"
  )

  const res = binding.crypto_sign_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign = function (sm, m, sk) {
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sm.byteLength === binding.crypto_sign_BYTES + m.byteLength,
    "sm must be 'm.byteLength + crypto_sign_BYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign(sm, m, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_open = function (m, sm, pk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sm.byteLength >= binding.crypto_sign_BYTES,
    "sm must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    m.byteLength === sm.byteLength - binding.crypto_sign_BYTES,
    "m must be 'sm.byteLength - crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_open(m, sm, pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_open = function (m, sm, pk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sm.byteLength >= binding.crypto_sign_BYTES,
    "sm must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    m.byteLength === sm.byteLength - binding.crypto_sign_BYTES,
    "m must be 'sm.byteLength - crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  return binding.crypto_sign_open(m, sm, pk)
}

exports.crypto_sign_detached = function (sig, m, sk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(sig.byteLength === binding.crypto_sign_BYTES, "sig must be 'crypto_sign_BYTES' bytes")
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_detached(sig, m, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_verify_detached = function (sig, m, pk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sig.byteLength >= binding.crypto_sign_BYTES,
    "sig must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  return binding.crypto_sign_verify_detached(
    sig.buffer,
    sig.byteOffset,
    sig.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    pk.buffer,
    pk.byteOffset,
    pk.byteLength
  )
}

exports.crypto_sign_ed25519_sk_to_pk = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_sk_to_pk(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_ed25519_pk_to_curve25519 = function (x25519pk, ed25519pk) {
  assert(ArrayBuffer.isView(x25519pk), 'x25519pk must be a typed array')
  assert(ArrayBuffer.isView(ed25519pk), 'ed25519pk must be a typed array')
  assert(
    x25519pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "x25519pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    ed25519pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "ed25519pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_pk_to_curve25519(x25519pk, ed25519pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_ed25519_sk_to_curve25519 = function (x25519sk, ed25519sk) {
  assert(ArrayBuffer.isView(x25519sk), 'x25519sk must be a typed array')
  assert(ArrayBuffer.isView(ed25519sk), 'ed25519sk must be a typed array')
  assert(
    x25519sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "x25519sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const edLen = ed25519sk.byteLength

  assert(
    edLen === binding.crypto_sign_SECRETKEYBYTES || edLen === binding.crypto_box_SECRETKEYBYTES,
    "ed25519sk must be 'crypto_sign_SECRETKEYBYTES' or 'crypto_sign_SECRETKEYBYTES - crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_sk_to_curve25519(x25519sk, ed25519sk)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_box

exports.crypto_box_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    seed.byteLength === binding.crypto_box_SEEDBYTES,
    "seed must be 'crypto_box_SEEDBYTES' bytes"
  )

  const res = binding.crypto_box_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_easy = function (c, m, n, pk, sk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength === m.byteLength + exports.crypto_box_MACBYTES,
    "c must be 'm.byteLength + crypto_box_MACBYTES' bytes"
  )
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_easy(c, m, n, pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_detached = function (c, mac, m, n, pk, sk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(mac.byteLength === exports.crypto_box_MACBYTES, "mac must be 'crypto_box_MACBYTES' bytes")
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_detached(c, mac, m, n, pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_open_easy = function (m, c, n, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength >= exports.crypto_box_MACBYTES,
    "c must be at least 'crypto_box_MACBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - exports.crypto_box_MACBYTES,
    "m must be 'c.byteLength - crypto_box_MACBYTES' bytes"
  )
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_open_easy(m, c, n, pk, sk)
}

exports.crypto_box_open_detached = function (m, c, mac, n, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(mac.byteLength === exports.crypto_box_MACBYTES, "mac must be 'crypto_box_MACBYTES' bytes")
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_open_detached(m, c, mac, n, pk, sk)
}

exports.crypto_box_seal = function (c, m, pk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    c.byteLength === m.byteLength + exports.crypto_box_SEALBYTES,
    "c must be 'm.byteLength + crypto_box_SEALBYTES' bytes"
  )
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_box_seal(c, m, pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_seal_open = function (m, c, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength >= exports.crypto_box_SEALBYTES,
    "c must be at least 'crypto_box_SEALBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - exports.crypto_box_SEALBYTES,
    "m must be 'c.byteLength - crypto_box_SEALBYTES' bytes"
  )
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_seal_open(
    m.buffer,
    m.byteOffset,
    m.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    pk.buffer,
    pk.byteOffset,
    pk.byteLength,

    sk.buffer,
    sk.byteOffset,
    sk.byteLength
  )
}

// crypto_secretbox

exports.crypto_secretbox_easy = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_secretbox_MACBYTES,
    "c must be 'm.byteLength + crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretbox_easy(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretbox_open_easy = function (m, c, n, k) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    c.byteLength >= binding.crypto_secretbox_MACBYTES,
    "c must be at least 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - binding.crypto_secretbox_MACBYTES,
    "m must be 'c.byteLength - crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  return binding.crypto_secretbox_open_easy(m, c, n, k)
}

exports.crypto_secretbox_detached = function (c, mac, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    mac.byteLength === binding.crypto_secretbox_MACBYTES,
    "mac must be 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretbox_detached(c, mac, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretbox_open_detached = function (m, c, mac, n, k) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(
    mac.byteLength === binding.crypto_secretbox_MACBYTES,
    "mac must be 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  return binding.crypto_secretbox_open_detached(m, c, mac, n, k)
}

// crypto_generichash

exports.crypto_generichash = function (output, input, key) {
  if (!key) key = OPTIONAL

  assert(ArrayBuffer.isView(output), 'output must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    output.byteLength >= binding.crypto_generichash_BYTES_MIN &&
      output.byteLength <= binding.crypto_generichash_BYTES_MAX,
    'output must be between crypto_generichash_BYTES_MIN and crypto_generichash_BYTES_MAX bytes'
  )

  if (key !== OPTIONAL) {
    assert(ArrayBuffer.isView(key), 'key must be a typed array')
    assert(
      key.byteLength >= binding.crypto_generichash_KEYBYTES_MIN &&
        key.byteLength <= binding.crypto_generichash_KEYBYTES_MAX,
      'key must be between crypto_generichash_KEYBYTES_MIN and crypto_generichash_KEYBYTES_MAX bytes'
    )
  }

  const res = binding.crypto_generichash(
    output.buffer,
    output.byteOffset,
    output.byteLength,

    input.buffer,
    input.byteOffset,
    input.byteLength,

    key.buffer,
    key.byteOffset,
    key.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_batch = function (output, batch, key) {
  assert(ArrayBuffer.isView(output), 'output must be a typed array')

  if (isNode || batch.length < 4) {
    const res = binding.crypto_generichash_batch(output, batch, !!key, key || OPTIONAL)
    if (res !== 0) throw new Error('status: ' + res)
  } else {
    const state = Buffer.alloc(binding.crypto_generichash_STATEBYTES)

    exports.crypto_generichash_init(state, key, output.byteLength)

    for (const buf of batch) {
      exports.crypto_generichash_update(state, buf)
    }

    exports.crypto_generichash_final(state, output)
  }
}

exports.crypto_generichash_keygen = function (key) {
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(
    key.byteLength === binding.crypto_generichash_KEYBYTES,
    "key must be 'crypto_generichash_KEYBYTES' bytes"
  )

  const res = binding.crypto_generichash_keygen(key.buffer, key.byteOffset, key.byteLength)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_init = function (state, key, outputLength) {
  if (!key) key = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_init(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    key.buffer,
    key.byteOffset,
    key.byteLength,

    outputLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_update(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    input.buffer,
    input.byteOffset,
    input.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_final = function (state, output) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(output), 'output must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_final(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    output.buffer,
    output.byteOffset,
    output.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

// secretstream

exports.crypto_secretstream_xchacha20poly1305_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  binding.crypto_secretstream_xchacha20poly1305_keygen(k.buffer, k.byteOffset, k.byteLength)
}

exports.crypto_secretstream_xchacha20poly1305_init_push = function (state, header, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(header), 'header must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    header.byteLength === binding.crypto_secretstream_xchacha20poly1305_HEADERBYTES,
    "header must be 'crypto_secretstream_xchacha20poly1305_HEADERBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_init_push(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    header.buffer,
    header.byteOffset,
    header.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretstream_xchacha20poly1305_init_pull = function (state, header, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(header), 'header must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    header.byteLength === binding.crypto_secretstream_xchacha20poly1305_HEADERBYTES,
    "header must be 'crypto_secretstream_xchacha20poly1305_HEADERBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_init_pull(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    header.buffer,
    header.byteOffset,
    header.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretstream_xchacha20poly1305_push = function (state, c, m, ad, tag) {
  if (!ad) ad = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    c.byteLength === m.byteLength + binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "c must be 'm.byteLength + crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_push(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    ad.buffer,
    ad.byteOffset,
    ad.byteLength,

    tag
  )

  if (res < 0) throw new Error('push failed')

  return res
}

exports.crypto_secretstream_xchacha20poly1305_pull = function (state, m, tag, c, ad) {
  if (!ad) ad = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(tag), 'tag must be a typed array')
  assert(tag.byteLength === 1, 'tag must be 1 byte')

  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    c.byteLength >= binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "c must be at least 'crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "m must be 'c.byteLength - crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_pull(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    tag.buffer,
    tag.byteOffset,
    tag.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    ad.buffer,
    ad.byteOffset,
    ad.byteLength
  )

  if (res < 0) throw new Error('pull failed')

  return res
}

exports.crypto_secretstream_xchacha20poly1305_rekey = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )

  binding.crypto_secretstream_xchacha20poly1305_rekey(
    state.buffer,
    state.byteOffset,
    state.byteLength
  )
}

// crypto_stream

exports.crypto_stream = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xor(
    c.buffer,
    c.byteOffset,
    c.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    n.buffer,
    n.byteOffset,
    n.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_auth

exports.crypto_auth = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(out.byteLength === binding.crypto_auth_BYTES, "out must be 'crypto_auth_BYTES' bytes")
  assert(k.byteLength === binding.crypto_auth_KEYBYTES, "k must be 'crypto_auth_KEYBYTES' bytes")

  const res = binding.crypto_auth(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_auth_verify = function (h, input, k) {
  assert(ArrayBuffer.isView(h), 'h must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(h.byteLength === binding.crypto_auth_BYTES, "h must be 'crypto_auth_BYTES' bytes")
  assert(k.byteLength === binding.crypto_auth_KEYBYTES, "k must be 'crypto_auth_KEYBYTES' bytes")

  return binding.crypto_auth_verify(h, input, k)
}

// crypto_onetimeauth

exports.crypto_onetimeauth = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    out.byteLength === binding.crypto_onetimeauth_BYTES,
    "out must be 'crypto_onetimeauth_BYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_init = function (state, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_init(state, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )
  assert(
    out.byteLength === binding.crypto_onetimeauth_BYTES,
    "out must be 'crypto_onetimeauth_BYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_verify = function (h, input, k) {
  assert(ArrayBuffer.isView(h), 'h must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    h.byteLength === binding.crypto_onetimeauth_BYTES,
    "h must be 'crypto_onetimeauth_BYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  return binding.crypto_onetimeauth_verify(h, input, k)
}

// crypto_pwhash

exports.crypto_pwhash = function (out, passwd, salt, opslimit, memlimit, alg) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_BYTES_MIN,
    "out must be at least 'crypto_pwhash_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_BYTES_MAX,
    "out must be at most 'crypto_pwhash_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_SALTBYTES,
    "salt must be 'crypto_pwhash_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )
  assert(alg >= 1 && alg <= 2, 'alg must be either Argon2i 1.3 or Argon2id 1.3')

  const res = binding.crypto_pwhash(out, passwd, salt, opslimit, memlimit, alg)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_async = function (
  out,
  passwd,
  salt,
  opslimit,
  memlimit,
  alg,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_BYTES_MIN,
    "out must be at least 'crypto_pwhash_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_BYTES_MAX,
    "out must be at most 'crypto_pwhash_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_SALTBYTES,
    "salt must be 'crypto_pwhash_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )
  assert(alg >= 1 && alg <= 2, 'alg must be either Argon2i 1.3 or Argon2id 1.3')

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    opslimit,
    memlimit,
    alg,

    done
  )

  return promise
}

exports.crypto_pwhash_str = function (out, passwd, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_STRBYTES,
    "out must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(typeof opslimit === 'number', 'opslimit must be a number')
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(typeof memlimit === 'number', 'memlimit must be a number')
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_str(out, passwd, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_str_async = function (out, passwd, opslimit, memlimit, callback = undefined) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_STRBYTES,
    "out must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(typeof opslimit === 'number', 'opslimit must be a number')
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(typeof memlimit === 'number', 'memlimit must be a number')
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_str_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_str_verify = function (str, passwd) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )

  return binding.crypto_pwhash_str_verify(str, passwd)
}

exports.crypto_pwhash_str_verify_async = function (str, passwd, callback = undefined) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  const [done, promise] = checkStatus(callback, true)

  binding.crypto_pwhash_str_verify_async(
    str.buffer,
    str.byteOffset,
    str.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    done
  )

  return promise
}

exports.crypto_pwhash_str_needs_rehash = function (str, opslimit, memlimit) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  return binding.crypto_pwhash_str_needs_rehash(str, opslimit, memlimit)
}

exports.crypto_pwhash_scryptsalsa208sha256 = function (out, passwd, salt, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MIN,
    "out must be at least 'crypto_pwhash_scryptsalsa208sha256_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MAX,
    "out must be at most 'crypto_pwhash_scryptsalsa208sha256_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_SALTBYTES,
    "salt must be 'crypto_pwhash_scryptsalsa208sha256_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_scryptsalsa208sha256(out, passwd, salt, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_scryptsalsa208sha256_async = function (
  out,
  passwd,
  salt,
  opslimit,
  memlimit,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MIN,
    "out must be at least 'crypto_pwhash_scryptsalsa208sha256_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MAX,
    "out must be at most 'crypto_pwhash_scryptsalsa208sha256_BYTES_MAX' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    salt.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_SALTBYTES,
    "salt must be 'crypto_pwhash_scryptsalsa208sha256_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_scryptsalsa208sha256_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str_async = function (
  out,
  passwd,
  opslimit,
  memlimit,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "out must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_scryptsalsa208sha256_str_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str = function (out, passwd, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "out must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_scryptsalsa208sha256_str(out, passwd, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_scryptsalsa208sha256_str_verify_async = function (
  str,
  passwd,
  callback = undefined
) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  const [done, promise] = checkStatus(callback, true)

  binding.crypto_pwhash_scryptsalsa208sha256_str_verify_async(
    str.buffer,
    str.byteOffset,
    str.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str_verify = function (str, passwd) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  return binding.crypto_pwhash_scryptsalsa208sha256_str_verify(str, passwd)
}

exports.crypto_pwhash_scryptsalsa208sha256_str_needs_rehash = function (str, opslimit, memlimit) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  return binding.crypto_pwhash_scryptsalsa208sha256_str_needs_rehash(str, opslimit, memlimit)
}

// crypto_kx

exports.crypto_kx_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "pk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "sk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    pk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "pk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "sk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    seed.byteLength === binding.crypto_kx_SEEDBYTES,
    "seed must be 'crypto_kx_SEEDBYTES' bytes"
  )

  const res = binding.crypto_kx_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_client_session_keys = function (rx, tx, clientPk, clientSk, serverPk) {
  if (!rx) rx = undefined
  if (!tx) tx = undefined

  assert(rx || tx, 'at least one session key must be specified')

  if (rx) {
    assert(ArrayBuffer.isView(rx), 'rx must be a typed array')
    assert(
      rx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "rx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  if (tx) {
    assert(ArrayBuffer.isView(tx), 'tx must be a typed array')
    assert(
      tx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "tx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  assert(ArrayBuffer.isView(clientPk), 'clientPk must be a typed array')
  assert(ArrayBuffer.isView(clientSk), 'clientSk must be a typed array')
  assert(ArrayBuffer.isView(serverPk), 'serverPk must be a typed array')
  assert(
    clientPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "clientPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    clientSk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "clientSk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    serverPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "serverPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_client_session_keys(rx, tx, clientPk, clientSk, serverPk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_server_session_keys = function (rx, tx, serverPk, serverSk, clientPk) {
  if (!rx) rx = undefined
  if (!tx) tx = undefined

  assert(rx || tx, 'at least one session key must be specified')

  if (rx) {
    assert(ArrayBuffer.isView(rx), 'rx must be a typed array')
    assert(
      rx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "rx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  if (tx) {
    assert(ArrayBuffer.isView(tx), 'tx must be a typed array')
    assert(
      tx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "tx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  assert(ArrayBuffer.isView(serverPk), 'serverPk must be a typed array')
  assert(ArrayBuffer.isView(serverSk), 'serverSk must be a typed array')
  assert(ArrayBuffer.isView(clientPk), 'clientPk must be a typed array')
  assert(
    serverPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "serverPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    serverSk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "serverSk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    clientPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "clientPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_server_session_keys(rx, tx, serverPk, serverSk, clientPk)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_scalarmult

exports.crypto_scalarmult_base = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_BYTES,
    "q must be 'crypto_scalarmult_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_SCALARBYTES,
    "n must be 'crypto_scalarmult_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_base(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_BYTES,
    "q must be 'crypto_scalarmult_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_SCALARBYTES,
    "n must be 'crypto_scalarmult_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_BYTES,
    "p must be 'crypto_scalarmult_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_base = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_base(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519 = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "p must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_is_valid_point = function (p) {
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )

  return binding.crypto_core_ed25519_is_valid_point(p)
}

exports.crypto_core_ed25519_from_uniform = function (p, r) {
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_UNIFORMBYTES,
    "r must be 'crypto_core_ed25519_UNIFORMBYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_from_uniform(p, r)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_base_noclamp = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_base_noclamp(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_noclamp = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "p must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_noclamp(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_core

exports.crypto_core_ed25519_add = function (r, p, q) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_BYTES,
    "r must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_core_ed25519_BYTES,
    "q must be 'crypto_core_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_add(r, p, q)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_sub = function (r, p, q) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_BYTES,
    "r must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_core_ed25519_BYTES,
    "q must be 'crypto_core_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_sub(r, p, q)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_scalar_random = function (r) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "r must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_random(r)
}

exports.crypto_core_ed25519_scalar_reduce = function (r, s) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "r must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_NONREDUCEDSCALARBYTES,
    "s must be 'crypto_core_ed25519_NONREDUCEDSCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_reduce(r, s)
}

exports.crypto_core_ed25519_scalar_invert = function (recip, s) {
  assert(ArrayBuffer.isView(recip), 'recip must be a typed array')
  assert(
    recip.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "recip must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_invert(recip, s)
}

exports.crypto_core_ed25519_scalar_negate = function (neg, s) {
  assert(ArrayBuffer.isView(neg), 'neg must be a typed array')
  assert(
    neg.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "neg must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_negate(neg, s)
}

exports.crypto_core_ed25519_scalar_complement = function (comp, s) {
  assert(ArrayBuffer.isView(comp), 'comp must be a typed array')
  assert(
    comp.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "comp must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_complement(comp, s)
}

exports.crypto_core_ed25519_scalar_add = function (z, x, y) {
  assert(ArrayBuffer.isView(z), 'z must be a typed array')
  assert(
    z.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "z must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(x), 'x must be a typed array')
  assert(
    x.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "x must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(y), 'y must be a typed array')
  assert(
    y.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "y must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_add(z, x, y)
}

exports.crypto_core_ed25519_scalar_sub = function (z, x, y) {
  assert(ArrayBuffer.isView(z), 'z must be a typed array')
  assert(
    z.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "z must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(x), 'x must be a typed array')
  assert(
    x.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "x must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(y), 'y must be a typed array')
  assert(
    y.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "y must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_sub(z, x, y)
}

// crypto_shorthash

exports.crypto_shorthash = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_shorthash_BYTES,
    "out must be 'crypto_shorthash_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_shorthash_KEYBYTES,
    "k must be 'crypto_shorthash_KEYBYTES' bytes"
  )

  const res = binding.crypto_shorthash(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_kdf

exports.crypto_kdf_keygen = function (key) {
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(key.byteLength === binding.crypto_kdf_KEYBYTES, "key must be 'crypto_kdf_KEYBYTES' bytes")

  binding.crypto_kdf_keygen(key)
}

exports.crypto_kdf_derive_from_key = function (subkey, subkeyId, ctx, key) {
  assert(ArrayBuffer.isView(subkey), 'subkey must be a typed array')
  assert(
    subkey.byteLength >= binding.crypto_kdf_BYTES_MIN,
    "subkey must be at least 'crypto_kdf_BYTES_MIN' bytes"
  )
  assert(
    subkey.byteLength <= binding.crypto_kdf_BYTES_MAX,
    "subkey must be at most 'crypto_kdf_BYTES_MAX' bytes"
  )
  assert(ArrayBuffer.isView(ctx), 'ctx must be a typed array')
  assert(
    ctx.byteLength === binding.crypto_kdf_CONTEXTBYTES,
    "ctx must be 'crypto_kdf_CONTEXTBYTES' bytes"
  )
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(key.byteLength === binding.crypto_kdf_KEYBYTES, "key must be 'crypto_kdf_KEYBYTES' bytes")

  const res = binding.crypto_kdf_derive_from_key(subkey, subkeyId, ctx, key)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_hash

exports.crypto_hash = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(out.byteLength === binding.crypto_hash_BYTES, "out must be 'crypto_hash_BYTES' bytes")

  const res = binding.crypto_hash(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256 = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha256_BYTES,
    "out must be 'crypto_hash_sha256_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha256(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_init = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_init(state)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha256_BYTES,
    "out must be 'crypto_hash_sha256_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512 = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha512_BYTES,
    "out must be 'crypto_hash_sha512_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha512(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_init = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_init(state)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha512_BYTES,
    "out must be 'crypto_hash_sha512_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_aead

exports.crypto_aead_xchacha20poly1305_ietf_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  binding.crypto_aead_xchacha20poly1305_ietf_keygen(k)
}

exports.crypto_aead_xchacha20poly1305_ietf_encrypt = function (c, m, ad, nsec, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "c must be 'm.byteLength + crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(c.byteLength <= 0xffffffff, 'c.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_encrypt(c, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_decrypt = function (m, nsec, c, ad, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "m must be 'c.byteLength - crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(m.byteLength <= 0xffffffff, 'm.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_decrypt(m, c, ad, npub, k)

  if (res < 0) throw new Error('could not verify data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_encrypt_detached = function (
  c,
  mac,
  m,
  ad,
  nsec,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_encrypt_detached(c, mac, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_decrypt_detached = function (
  m,
  nsec,
  c,
  mac,
  ad,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_decrypt_detached(m, c, mac, ad, npub, k)

  if (res !== 0) throw new Error('could not verify data')
}

exports.crypto_aead_chacha20poly1305_ietf_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  binding.crypto_aead_chacha20poly1305_ietf_keygen(k)
}

exports.crypto_aead_chacha20poly1305_ietf_encrypt = function (c, m, ad, nsec, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "c must be 'm.byteLength + crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(c.byteLength <= 0xffffffff, 'c.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_encrypt(c, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_decrypt = function (m, nsec, c, ad, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "m must be 'c.byteLength - crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(m.byteLength <= 0xffffffff, 'm.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_decrypt(m, c, ad, npub, k)

  if (res < 0) throw new Error('could not verify data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_encrypt_detached = function (
  c,
  mac,
  m,
  ad,
  nsec,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_encrypt_detached(c, mac, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_decrypt_detached = function (
  m,
  nsec,
  c,
  mac,
  ad,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_decrypt_detached(m, c, mac, ad, npub, k)

  if (res !== 0) throw new Error('could not verify data')
}

// crypto_stream

exports.crypto_stream_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  binding.crypto_stream_xor_wrap_init(state, n, k)
}

exports.crypto_stream_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_xor_wrap_update(state, c, m)
}

exports.crypto_stream_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_xor_wrap_final(state)
}

exports.crypto_stream_chacha20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  binding.crypto_stream_chacha20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_chacha20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_chacha20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_chacha20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_chacha20_xor_wrap_final(state)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  binding.crypto_stream_chacha20_ietf_xor_wrap_init(state, n, k)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_chacha20_ietf_xor_wrap_update(state, c, m)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_chacha20_ietf_xor_wrap_final(state)
}

exports.crypto_stream_xchacha20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  binding.crypto_stream_xchacha20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_xchacha20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_xchacha20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_xchacha20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_xchacha20_xor_wrap_final(state)
}

exports.crypto_stream_salsa20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  binding.crypto_stream_salsa20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_salsa20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_salsa20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_salsa20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_salsa20_xor_wrap_final(state)
}

// experimental

exports.extension_tweak_ed25519_base = function (n, p, ns) {
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.extension_tweak_ed25519_BYTES,
    "p must be 'extension_tweak_ed25519_BYTES' bytes"
  )

  binding.extension_tweak_ed25519_base(n, p, ns)
}

exports.extension_tweak_ed25519_sign_detached = function (sig, m, scalar, pk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(sig.byteLength === binding.crypto_sign_BYTES, "sig must be 'crypto_sign_BYTES' bytes")
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  if (pk) {
    assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
    assert(
      pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
      "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
    )
  }

  const res = binding.extension_tweak_ed25519_sign_detached(sig, m, scalar, pk)

  if (res !== 0) throw new Error('failed to compute signature')
}

exports.extension_tweak_ed25519_sk_to_scalar = function (n, sk) {
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  binding.extension_tweak_ed25519_sk_to_scalar(n, sk)
}

exports.extension_tweak_ed25519_scalar = function (scalarOut, scalar, ns) {
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_scalar(scalarOut, scalar, ns)
}

exports.extension_tweak_ed25519_pk = function (tpk, pk, ns) {
  assert(ArrayBuffer.isView(tpk), 'tpk must be a typed array')
  assert(
    tpk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "tpk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_pk(tpk, pk, ns)

  if (res !== 0) throw new Error('failed to tweak public key')
}

exports.extension_tweak_ed25519_keypair = function (pk, scalarOut, scalarIn, ns) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.extension_tweak_ed25519_BYTES,
    "pk must be 'extension_tweak_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarIn), 'scalarIn must be a typed array')
  assert(
    scalarIn.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarIn must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_keypair(pk, scalarOut, scalarIn, ns)
}

exports.extension_tweak_ed25519_scalar_add = function (scalarOut, scalar, n) {
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_scalar_add(scalarOut, scalar, n)
}

exports.extension_tweak_ed25519_pk_add = function (tpk, pk, p) {
  assert(ArrayBuffer.isView(tpk), 'tpk must be a typed array')
  assert(
    tpk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "tpk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "p must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_pk_add(tpk, pk, p)

  if (res !== 0) throw new Error('failed to add tweak to public key')
}

exports.extension_tweak_ed25519_keypair_add = function (pk, scalarOut, scalarIn, tweak) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.extension_tweak_ed25519_BYTES,
    "pk must be 'extension_tweak_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarIn), 'scalarIn must be a typed array')
  assert(
    scalarIn.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarIn must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(tweak), 'tweak must be a typed array')
  assert(
    tweak.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "tweak must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_keypair_add(pk, scalarOut, scalarIn, tweak)

  if (res !== 0) throw new Error('failed to add tweak to keypair')
}

exports.extension_pbkdf2_sha512_async = function (out, passwd, salt, iter, outlen, callback) {
  assert(
    iter >= binding.extension_pbkdf2_sha512_ITERATIONS_MIN,
    "iter must be at least 'extension_pbkdf2_sha512_ITERATIONS_MIN'"
  )
  assert(
    outlen <= binding.extension_pbkdf2_sha512_BYTES_MAX,
    "outlen must be at most 'extension_pbkdf2_sha512_BYTES_MAX'"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(out.byteLength >= outlen, "out must be at least 'outlen' bytes")
  assert(out.byteLength > 0, 'out must not be empty')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(salt.byteLength > 0, 'salt must not be empty')

  const [done, promise] = checkStatus(callback)

  binding.extension_pbkdf2_sha512_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    iter,
    outlen,

    done
  )

  return promise
}

exports.extension_pbkdf2_sha512 = function (out, passwd, salt, iter, outlen) {
  assert(
    iter >= binding.extension_pbkdf2_sha512_ITERATIONS_MIN,
    "iter must be at least 'extension_pbkdf2_sha512_ITERATIONS_MIN'"
  )
  assert(
    outlen <= binding.extension_pbkdf2_sha512_BYTES_MAX,
    "outlen must be at most 'extension_pbkdf2_sha512_BYTES_MAX'"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(out.byteLength >= outlen, "out must be at least 'outlen' bytes")
  assert(out.byteLength > 0, 'out must not be empty')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(salt.byteLength > 0, 'salt must not be empty')

  const res = binding.extension_pbkdf2_sha512(out, passwd, salt, iter, outlen)

  if (res !== 0) throw new Error('failed to add tweak to public key')
}

function checkStatus(callback, booleanResult = false) {
  let done, promise

  if (typeof callback === 'function') {
    done = function (status) {
      if (booleanResult) callback(null, status === 0)
      else if (status === 0) callback(null)
      else callback(new Error('status: ' + status))
    }
  } else {
    promise = new Promise(function (resolve, reject) {
      done = function (status) {
        if (booleanResult) resolve(status === 0)
        else if (status === 0) resolve()
        else reject(new Error('status: ' + status))
      }
    })
  }

  return [done, promise]
}
{
  "name": "sodium-native",
  "version": "5.1.0",
  "description": "Low level bindings for libsodium",
  "main": "index.js",
  "files": [
    "index.js",
    "binding.cc",
    "binding.js",
    "extensions",
    "prebuilds",
    "CMakeLists.txt"
  ],
  "imports": {
    "assert": {
      "bare": "bare-assert",
      "node": "assert"
    }
  },
  "addon": true,
  "dependencies": {
    "bare-assert": "^1.2.0",
    "require-addon": "^1.1.0",
    "which-runtime": "^1.2.1"
  },
  "devDependencies": {
    "bare-compat-napi": "^1.3.5",
    "brittle": "^3.16.2",
    "cmake-bare": "^1.6.1",
    "cmake-fetch": "^1.4.3",
    "cmake-napi": "^1.2.1",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "test": "prettier . --check && npm run test:node && npm run test:bare",
    "test:node": "node test/all.js",
    "test:bare": "bare test/all.js"
  },
  "standard": {
    "ignore": [
      "/test/fixtures/*.js"
    ]
  },
  "engines": {
    "bare": ">=1.16.0"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sodium-native.git"
  },
  "contributors": [
    "Emil Bay <github@tixz.dk> (http://bayes.dk)",
    "Mathias Buus <mathiasbuus@gmail.com> (https://mafinto.sh)",
    "Christophe Diederichs <chm-diederichs@hyperdivision.dk>"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/sodium-native/issues"
  },
  "homepage": "https://github.com/holepunchto/sodium-native"
}
const sodium = require('sodium-universal')
const b4a = require('b4a')

const ABYTES = sodium.crypto_secretstream_xchacha20poly1305_ABYTES
const TAG_MESSAGE = sodium.crypto_secretstream_xchacha20poly1305_TAG_MESSAGE
const TAG_FINAL = sodium.crypto_secretstream_xchacha20poly1305_TAG_FINAL
const STATEBYTES = sodium.crypto_secretstream_xchacha20poly1305_STATEBYTES
const HEADERBYTES = sodium.crypto_secretstream_xchacha20poly1305_HEADERBYTES
const KEYBYTES = sodium.crypto_secretstream_xchacha20poly1305_KEYBYTES
const TAG_FINAL_BYTE = b4a.isBuffer(TAG_FINAL) ? TAG_FINAL[0] : TAG_FINAL

const EMPTY = b4a.alloc(0)
const TAG = b4a.alloc(1)

class Push {
  constructor (key, state = b4a.allocUnsafeSlow(STATEBYTES), header = b4a.allocUnsafeSlow(HEADERBYTES)) {
    if (!TAG_FINAL) throw new Error('JavaScript sodium version needs to support crypto_secretstream_xchacha20poly')

    this.key = key
    this.state = state
    this.header = header

    sodium.crypto_secretstream_xchacha20poly1305_init_push(this.state, this.header, this.key)
  }

  next (message, cipher = b4a.allocUnsafe(message.byteLength + ABYTES)) {
    sodium.crypto_secretstream_xchacha20poly1305_push(this.state, cipher, message, null, TAG_MESSAGE)
    return cipher
  }

  final (message = EMPTY, cipher = b4a.allocUnsafe(ABYTES)) {
    sodium.crypto_secretstream_xchacha20poly1305_push(this.state, cipher, message, null, TAG_FINAL)
    return cipher
  }
}

class Pull {
  constructor (key, state = b4a.allocUnsafeSlow(STATEBYTES)) {
    if (!TAG_FINAL) throw new Error('JavaScript sodium version needs to support crypto_secretstream_xchacha20poly')

    this.key = key
    this.state = state
    this.final = false
  }

  init (header) {
    sodium.crypto_secretstream_xchacha20poly1305_init_pull(this.state, header, this.key)
  }

  next (cipher, message = b4a.allocUnsafe(cipher.byteLength - ABYTES)) {
    sodium.crypto_secretstream_xchacha20poly1305_pull(this.state, message, TAG, cipher, null)
    this.final = TAG[0] === TAG_FINAL_BYTE
    return message
  }
}

function keygen (buf = b4a.alloc(KEYBYTES)) {
  sodium.crypto_secretstream_xchacha20poly1305_keygen(buf)
  return buf
}

module.exports = {
  keygen,
  KEYBYTES,
  ABYTES,
  STATEBYTES,
  HEADERBYTES,
  Push,
  Pull
}
{
  "name": "sodium-secretstream",
  "version": "1.2.0",
  "description": "Wraps libsodiums secretstream in a higher level abstraction",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.1.1",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "standard": "^17.0.0"
  },
  "scripts": {
    "test": "standard"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/sodium-secretstream.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/sodium-secretstream/issues"
  },
  "homepage": "https://github.com/mafintosh/sodium-secretstream"
}
module.exports = require('sodium-native')
{
  "name": "sodium-universal",
  "version": "5.0.1",
  "description": "Universal wrapper for sodium-javascript and sodium-native working in Node.js and the Browser",
  "main": "index.js",
  "dependencies": {
    "sodium-native": "^5.0.1"
  },
  "peerDependencies": {
    "sodium-javascript": "~0.8.0"
  },
  "peerDependenciesMeta": {
    "sodium-javascript": {
      "optional": true
    }
  },
  "scripts": {
    "prepublish": "./build-scripts/generate.js"
  },
  "browser": {
    "sodium-native": "sodium-javascript"
  },
  "browserify": {
    "transform": [
      "./build-scripts/transform.js"
    ]
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sodium-universal.git"
  },
  "keywords": [
    "libsodium",
    "sodium",
    "sodium-native",
    "sodium-javascript",
    "browserify"
  ],
  "contributors": [
    "Emil Bay <github@tixz.dk> (http://bayes.dk)",
    "Mathias Buus <mathiasbuus@gmail.com> (https://mafinto.sh)",
    "Christophe Diederichs <chm-diederichs@hyperdivision.dk>"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/sodium-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/sodium-universal#readme"
}
const { EventEmitter } = require('events-universal')
const FIFO = require('fast-fifo')
const TextDecoder = require('text-decoder')

const StreamError = require('./lib/errors.js')

// if we do a future major, expect queue microtask to be there always, for now a bit defensive
const qmt =
  typeof queueMicrotask === 'undefined' ? (fn) => global.process.nextTick(fn) : queueMicrotask

// 29 bits used total (4 from shared, 14 from read, and 11 from write)
const MAX = (1 << 29) - 1

// Shared state
const OPENING = 0b0001
const PREDESTROYING = 0b0010
const DESTROYING = 0b0100
const DESTROYED = 0b1000

const NOT_OPENING = MAX ^ OPENING
const NOT_PREDESTROYING = MAX ^ PREDESTROYING

// Read state (4 bit offset from shared state)
const READ_ACTIVE = 0b00000000000001 << 4
const READ_UPDATING = 0b00000000000010 << 4
const READ_PRIMARY = 0b00000000000100 << 4
const READ_QUEUED = 0b00000000001000 << 4
const READ_RESUMED = 0b00000000010000 << 4
const READ_PIPE_DRAINED = 0b00000000100000 << 4
const READ_ENDING = 0b00000001000000 << 4
const READ_EMIT_DATA = 0b00000010000000 << 4
const READ_EMIT_READABLE = 0b00000100000000 << 4
const READ_EMITTED_READABLE = 0b00001000000000 << 4
const READ_DONE = 0b00010000000000 << 4
const READ_NEXT_TICK = 0b00100000000000 << 4
const READ_NEEDS_PUSH = 0b01000000000000 << 4
const READ_READ_AHEAD = 0b10000000000000 << 4

// Combined read state
const READ_FLOWING = READ_RESUMED | READ_PIPE_DRAINED
const READ_ACTIVE_AND_NEEDS_PUSH = READ_ACTIVE | READ_NEEDS_PUSH
const READ_PRIMARY_AND_ACTIVE = READ_PRIMARY | READ_ACTIVE
const READ_EMIT_READABLE_AND_QUEUED = READ_EMIT_READABLE | READ_QUEUED
const READ_RESUMED_READ_AHEAD = READ_RESUMED | READ_READ_AHEAD

const READ_NOT_ACTIVE = MAX ^ READ_ACTIVE
const READ_NON_PRIMARY = MAX ^ READ_PRIMARY
const READ_NON_PRIMARY_AND_PUSHED = MAX ^ (READ_PRIMARY | READ_NEEDS_PUSH)
const READ_PUSHED = MAX ^ READ_NEEDS_PUSH
const READ_PAUSED = MAX ^ READ_RESUMED
const READ_NOT_QUEUED = MAX ^ (READ_QUEUED | READ_EMITTED_READABLE)
const READ_NOT_ENDING = MAX ^ READ_ENDING
const READ_PIPE_NOT_DRAINED = MAX ^ READ_FLOWING
const READ_NOT_NEXT_TICK = MAX ^ READ_NEXT_TICK
const READ_NOT_UPDATING = MAX ^ READ_UPDATING
const READ_NO_READ_AHEAD = MAX ^ READ_READ_AHEAD
const READ_PAUSED_NO_READ_AHEAD = MAX ^ READ_RESUMED_READ_AHEAD

// Write state (18 bit offset, 4 bit offset from shared state and 14 from read state)
const WRITE_ACTIVE = 0b00000000001 << 18
const WRITE_UPDATING = 0b00000000010 << 18
const WRITE_PRIMARY = 0b00000000100 << 18
const WRITE_QUEUED = 0b00000001000 << 18
const WRITE_UNDRAINED = 0b00000010000 << 18
const WRITE_DONE = 0b00000100000 << 18
const WRITE_EMIT_DRAIN = 0b00001000000 << 18
const WRITE_NEXT_TICK = 0b00010000000 << 18
const WRITE_WRITING = 0b00100000000 << 18
const WRITE_FINISHING = 0b01000000000 << 18
const WRITE_CORKED = 0b10000000000 << 18

const WRITE_NOT_ACTIVE = MAX ^ (WRITE_ACTIVE | WRITE_WRITING)
const WRITE_NON_PRIMARY = MAX ^ WRITE_PRIMARY
const WRITE_NOT_FINISHING = MAX ^ (WRITE_ACTIVE | WRITE_FINISHING)
const WRITE_DRAINED = MAX ^ WRITE_UNDRAINED
const WRITE_NOT_QUEUED = MAX ^ WRITE_QUEUED
const WRITE_NOT_NEXT_TICK = MAX ^ WRITE_NEXT_TICK
const WRITE_NOT_UPDATING = MAX ^ WRITE_UPDATING
const WRITE_NOT_CORKED = MAX ^ WRITE_CORKED

// Combined shared state
const ACTIVE = READ_ACTIVE | WRITE_ACTIVE
const NOT_ACTIVE = MAX ^ ACTIVE
const DONE = READ_DONE | WRITE_DONE
const DESTROY_STATUS = DESTROYING | DESTROYED | PREDESTROYING
const OPEN_STATUS = DESTROY_STATUS | OPENING
const AUTO_DESTROY = DESTROY_STATUS | DONE
const NON_PRIMARY = WRITE_NON_PRIMARY & READ_NON_PRIMARY
const ACTIVE_OR_TICKING = WRITE_NEXT_TICK | READ_NEXT_TICK
const TICKING = ACTIVE_OR_TICKING & NOT_ACTIVE
const IS_OPENING = OPEN_STATUS | TICKING

// Combined shared state and read state
const READ_PRIMARY_STATUS = OPEN_STATUS | READ_ENDING | READ_DONE
const READ_STATUS = OPEN_STATUS | READ_DONE | READ_QUEUED
const READ_ENDING_STATUS = OPEN_STATUS | READ_ENDING | READ_QUEUED
const READ_READABLE_STATUS = OPEN_STATUS | READ_EMIT_READABLE | READ_QUEUED | READ_EMITTED_READABLE
const SHOULD_NOT_READ =
  OPEN_STATUS | READ_ACTIVE | READ_ENDING | READ_DONE | READ_NEEDS_PUSH | READ_READ_AHEAD
const READ_BACKPRESSURE_STATUS = DESTROY_STATUS | READ_ENDING | READ_DONE
const READ_UPDATE_SYNC_STATUS = READ_UPDATING | OPEN_STATUS | READ_NEXT_TICK | READ_PRIMARY
const READ_NEXT_TICK_OR_OPENING = READ_NEXT_TICK | OPENING

// Combined write state
const WRITE_PRIMARY_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_DONE
const WRITE_QUEUED_AND_UNDRAINED = WRITE_QUEUED | WRITE_UNDRAINED
const WRITE_QUEUED_AND_ACTIVE = WRITE_QUEUED | WRITE_ACTIVE
const WRITE_DRAIN_STATUS = WRITE_QUEUED | WRITE_UNDRAINED | OPEN_STATUS | WRITE_ACTIVE
const WRITE_STATUS = OPEN_STATUS | WRITE_ACTIVE | WRITE_QUEUED | WRITE_CORKED
const WRITE_PRIMARY_AND_ACTIVE = WRITE_PRIMARY | WRITE_ACTIVE
const WRITE_ACTIVE_AND_WRITING = WRITE_ACTIVE | WRITE_WRITING
const WRITE_FINISHING_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_QUEUED_AND_ACTIVE | WRITE_DONE
const WRITE_BACKPRESSURE_STATUS = WRITE_UNDRAINED | DESTROY_STATUS | WRITE_FINISHING | WRITE_DONE
const WRITE_UPDATE_SYNC_STATUS = WRITE_UPDATING | OPEN_STATUS | WRITE_NEXT_TICK | WRITE_PRIMARY
const WRITE_DROP_DATA = WRITE_FINISHING | WRITE_DONE | DESTROY_STATUS

const asyncIterator = Symbol.asyncIterator || Symbol('asyncIterator')

class WritableState {
  constructor(
    stream,
    { highWaterMark = 16384, map = null, mapWritable, byteLength, byteLengthWritable } = {}
  ) {
    this.stream = stream
    this.queue = new FIFO()
    this.highWaterMark = highWaterMark
    this.buffered = 0
    this.error = null
    this.pipeline = null
    this.drains = null // if we add more seldomly used helpers we might them into a subobject so its a single ptr
    this.byteLength = byteLengthWritable || byteLength || defaultByteLength
    this.map = mapWritable || map
    this.afterWrite = afterWrite.bind(this)
    this.afterUpdateNextTick = updateWriteNT.bind(this)
  }

  get ending() {
    return (this.stream._duplexState & WRITE_FINISHING) !== 0
  }

  get ended() {
    return (this.stream._duplexState & WRITE_DONE) !== 0
  }

  push(data) {
    if ((this.stream._duplexState & WRITE_DROP_DATA) !== 0) return false
    if (this.map !== null) data = this.map(data)

    this.buffered += this.byteLength(data)
    this.queue.push(data)

    if (this.buffered < this.highWaterMark) {
      this.stream._duplexState |= WRITE_QUEUED
      return true
    }

    this.stream._duplexState |= WRITE_QUEUED_AND_UNDRAINED
    return false
  }

  shift() {
    const data = this.queue.shift()

    this.buffered -= this.byteLength(data)
    if (this.buffered === 0) this.stream._duplexState &= WRITE_NOT_QUEUED

    return data
  }

  end(data) {
    if (typeof data === 'function') {
      this.stream.once('finish', data)
    } else if (data !== undefined && data !== null) {
      this.push(data)
    }

    this.stream._duplexState = (this.stream._duplexState | WRITE_FINISHING) & WRITE_NON_PRIMARY
  }

  autoBatch(data, cb) {
    const buffer = []
    const stream = this.stream

    buffer.push(data)
    while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED_AND_ACTIVE) {
      buffer.push(stream._writableState.shift())
    }

    if ((stream._duplexState & OPEN_STATUS) !== 0) return cb(null)
    stream._writev(buffer, cb)
  }

  update() {
    const stream = this.stream

    stream._duplexState |= WRITE_UPDATING

    do {
      while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED) {
        const data = this.shift()
        stream._duplexState |= WRITE_ACTIVE_AND_WRITING
        stream._write(data, this.afterWrite)
      }

      if ((stream._duplexState & WRITE_PRIMARY_AND_ACTIVE) === 0) this.updateNonPrimary()
    } while (this.continueUpdate() === true)

    stream._duplexState &= WRITE_NOT_UPDATING
  }

  updateNonPrimary() {
    const stream = this.stream

    if ((stream._duplexState & WRITE_FINISHING_STATUS) === WRITE_FINISHING) {
      stream._duplexState = stream._duplexState | WRITE_ACTIVE
      stream._final(afterFinal.bind(this))
      return
    }

    if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
      if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
        stream._duplexState |= ACTIVE
        stream._destroy(afterDestroy.bind(this))
      }
      return
    }

    if ((stream._duplexState & IS_OPENING) === OPENING) {
      stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING
      stream._open(afterOpen.bind(this))
    }
  }

  continueUpdate() {
    if ((this.stream._duplexState & WRITE_NEXT_TICK) === 0) return false
    this.stream._duplexState &= WRITE_NOT_NEXT_TICK
    return true
  }

  updateCallback() {
    if ((this.stream._duplexState & WRITE_UPDATE_SYNC_STATUS) === WRITE_PRIMARY) {
      this.update()
    } else {
      this.updateNextTick()
    }
  }

  updateNextTick() {
    if ((this.stream._duplexState & WRITE_NEXT_TICK) !== 0) return
    this.stream._duplexState |= WRITE_NEXT_TICK
    if ((this.stream._duplexState & WRITE_UPDATING) === 0) qmt(this.afterUpdateNextTick)
  }
}

class ReadableState {
  constructor(
    stream,
    { highWaterMark = 16384, map = null, mapReadable, byteLength, byteLengthReadable } = {}
  ) {
    this.stream = stream
    this.queue = new FIFO()
    this.highWaterMark = highWaterMark === 0 ? 1 : highWaterMark
    this.buffered = 0
    this.readAhead = highWaterMark > 0
    this.error = null
    this.pipeline = null
    this.byteLength = byteLengthReadable || byteLength || defaultByteLength
    this.map = mapReadable || map
    this.pipeTo = null
    this.afterRead = afterRead.bind(this)
    this.afterUpdateNextTick = updateReadNT.bind(this)
  }

  get ending() {
    return (this.stream._duplexState & READ_ENDING) !== 0
  }

  get ended() {
    return (this.stream._duplexState & READ_DONE) !== 0
  }

  pipe(pipeTo, cb) {
    if (this.pipeTo !== null) throw StreamError.BAD_ARGUMENT('Can only pipe to one destination')
    if (typeof cb !== 'function') cb = null

    this.stream._duplexState |= READ_PIPE_DRAINED
    this.pipeTo = pipeTo
    this.pipeline = new Pipeline(this.stream, pipeTo, cb)

    if (cb) this.stream.on('error', noop) // We already error handle this so supress crashes

    if (isStreamx(pipeTo)) {
      pipeTo._writableState.pipeline = this.pipeline
      if (cb) pipeTo.on('error', noop) // We already error handle this so supress crashes
      pipeTo.on('finish', this.pipeline.finished.bind(this.pipeline)) // TODO: just call finished from pipeTo itself
    } else {
      const onerror = this.pipeline.done.bind(this.pipeline, pipeTo)
      const onclose = this.pipeline.done.bind(this.pipeline, pipeTo, null) // onclose has a weird bool arg
      pipeTo.on('error', onerror)
      pipeTo.on('close', onclose)
      pipeTo.on('finish', this.pipeline.finished.bind(this.pipeline))
    }

    pipeTo.on('drain', afterDrain.bind(this))
    this.stream.emit('piping', pipeTo)
    pipeTo.emit('pipe', this.stream)
  }

  push(data) {
    const stream = this.stream

    if (data === null) {
      this.highWaterMark = 0
      stream._duplexState = (stream._duplexState | READ_ENDING) & READ_NON_PRIMARY_AND_PUSHED
      return false
    }

    if (this.map !== null) {
      data = this.map(data)
      if (data === null) {
        stream._duplexState &= READ_PUSHED
        return this.buffered < this.highWaterMark
      }
    }

    this.buffered += this.byteLength(data)
    this.queue.push(data)

    stream._duplexState = (stream._duplexState | READ_QUEUED) & READ_PUSHED

    return this.buffered < this.highWaterMark
  }

  shift() {
    const data = this.queue.shift()

    this.buffered -= this.byteLength(data)
    if (this.buffered === 0) {
      this.stream._duplexState &= READ_NOT_QUEUED
    }

    return data
  }

  unshift(data) {
    const pending = [this.map !== null ? this.map(data) : data]
    while (this.buffered > 0) pending.push(this.shift())

    for (let i = 0; i < pending.length - 1; i++) {
      const data = pending[i]
      this.buffered += this.byteLength(data)
      this.queue.push(data)
    }

    this.push(pending[pending.length - 1])
  }

  read() {
    const stream = this.stream

    if ((stream._duplexState & READ_STATUS) === READ_QUEUED) {
      const data = this.shift()

      if (this.pipeTo !== null && this.pipeTo.write(data) === false) {
        stream._duplexState &= READ_PIPE_NOT_DRAINED
      }

      if ((stream._duplexState & READ_EMIT_DATA) !== 0) {
        stream.emit('data', data)
      }

      return data
    }

    if (this.readAhead === false) {
      stream._duplexState |= READ_READ_AHEAD
      this.updateNextTick()
    }

    return null
  }

  drain() {
    const stream = this.stream

    while (
      (stream._duplexState & READ_STATUS) === READ_QUEUED &&
      (stream._duplexState & READ_FLOWING) !== 0
    ) {
      const data = this.shift()

      if (this.pipeTo !== null && this.pipeTo.write(data) === false) {
        stream._duplexState &= READ_PIPE_NOT_DRAINED
      }

      if ((stream._duplexState & READ_EMIT_DATA) !== 0) {
        stream.emit('data', data)
      }
    }
  }

  update() {
    const stream = this.stream

    stream._duplexState |= READ_UPDATING

    do {
      this.drain()

      while (
        this.buffered < this.highWaterMark &&
        (stream._duplexState & SHOULD_NOT_READ) === READ_READ_AHEAD
      ) {
        stream._duplexState |= READ_ACTIVE_AND_NEEDS_PUSH
        stream._read(this.afterRead)
        this.drain()
      }

      if ((stream._duplexState & READ_READABLE_STATUS) === READ_EMIT_READABLE_AND_QUEUED) {
        stream._duplexState |= READ_EMITTED_READABLE
        stream.emit('readable')
      }

      if ((stream._duplexState & READ_PRIMARY_AND_ACTIVE) === 0) {
        this.updateNonPrimary()
      }
    } while (this.continueUpdate() === true)

    stream._duplexState &= READ_NOT_UPDATING
  }

  updateNonPrimary() {
    const stream = this.stream

    if ((stream._duplexState & READ_ENDING_STATUS) === READ_ENDING) {
      stream._duplexState = (stream._duplexState | READ_DONE) & READ_NOT_ENDING
      stream.emit('end')

      if ((stream._duplexState & AUTO_DESTROY) === DONE) {
        stream._duplexState |= DESTROYING
      }

      if (this.pipeTo !== null) {
        this.pipeTo.end()
      }
    }

    if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
      if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
        stream._duplexState |= ACTIVE
        stream._destroy(afterDestroy.bind(this))
      }
      return
    }

    if ((stream._duplexState & IS_OPENING) === OPENING) {
      stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING
      stream._open(afterOpen.bind(this))
    }
  }

  continueUpdate() {
    if ((this.stream._duplexState & READ_NEXT_TICK) === 0) return false
    this.stream._duplexState &= READ_NOT_NEXT_TICK
    return true
  }

  updateCallback() {
    if ((this.stream._duplexState & READ_UPDATE_SYNC_STATUS) === READ_PRIMARY) {
      this.update()
    } else {
      this.updateNextTick()
    }
  }

  updateNextTickIfOpen() {
    if ((this.stream._duplexState & READ_NEXT_TICK_OR_OPENING) !== 0) return
    this.stream._duplexState |= READ_NEXT_TICK
    if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick)
  }

  updateNextTick() {
    if ((this.stream._duplexState & READ_NEXT_TICK) !== 0) return
    this.stream._duplexState |= READ_NEXT_TICK
    if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick)
  }
}

class TransformState {
  constructor(stream) {
    this.data = null
    this.afterTransform = afterTransform.bind(stream)
    this.afterFinal = null
  }
}

class Pipeline {
  constructor(src, dst, cb) {
    this.from = src
    this.to = dst
    this.afterPipe = cb
    this.error = null
    this.pipeToFinished = false
  }

  finished() {
    this.pipeToFinished = true
  }

  done(stream, err) {
    if (err) this.error = err

    if (stream === this.to) {
      this.to = null

      if (this.from !== null) {
        if ((this.from._duplexState & READ_DONE) === 0 || !this.pipeToFinished) {
          this.from.destroy(this.error || StreamError.PREMATURE_CLOSE('Writable stream closed'))
        }
        return
      }
    }

    if (stream === this.from) {
      this.from = null

      if (this.to !== null) {
        if ((stream._duplexState & READ_DONE) === 0) {
          this.to.destroy(this.error || StreamError.PREMATURE_CLOSE('Readable stream closed'))
        }
        return
      }
    }

    if (this.afterPipe !== null) this.afterPipe(this.error)
    this.to = this.from = this.afterPipe = null
  }
}

function afterDrain() {
  this.stream._duplexState |= READ_PIPE_DRAINED
  this.updateCallback()
}

function afterFinal(err) {
  const stream = this.stream
  if (err) stream.destroy(err)

  if ((stream._duplexState & DESTROY_STATUS) === 0) {
    stream._duplexState |= WRITE_DONE
    stream.emit('finish')
  }

  if ((stream._duplexState & AUTO_DESTROY) === DONE) {
    stream._duplexState |= DESTROYING
  }

  stream._duplexState &= WRITE_NOT_FINISHING

  // no need to wait the extra tick here, so we short circuit that
  if ((stream._duplexState & WRITE_UPDATING) === 0) {
    this.update()
  } else {
    this.updateNextTick()
  }
}

function afterDestroy(err) {
  const stream = this.stream

  if (!err && !StreamError.isStreamDestroyed(this.error)) err = this.error
  if (err) stream.emit('error', err)

  stream._duplexState |= DESTROYED
  stream.emit('close')

  const rs = stream._readableState
  const ws = stream._writableState

  if (rs !== null && rs.pipeline !== null) {
    rs.pipeline.done(stream, err)
  }

  if (ws !== null) {
    while (ws.drains !== null && ws.drains.length > 0) {
      ws.drains.shift().resolve(false)
    }

    if (ws.pipeline !== null) {
      ws.pipeline.done(stream, err)
    }
  }
}

function afterWrite(err) {
  const stream = this.stream

  if (err) stream.destroy(err)
  stream._duplexState &= WRITE_NOT_ACTIVE

  if (this.drains !== null) tickDrains(this.drains)

  if ((stream._duplexState & WRITE_DRAIN_STATUS) === WRITE_UNDRAINED) {
    stream._duplexState &= WRITE_DRAINED

    if ((stream._duplexState & WRITE_EMIT_DRAIN) === WRITE_EMIT_DRAIN) {
      stream.emit('drain')
    }
  }

  this.updateCallback()
}

function afterRead(err) {
  if (err) this.stream.destroy(err)
  this.stream._duplexState &= READ_NOT_ACTIVE

  if (this.readAhead === false && (this.stream._duplexState & READ_RESUMED) === 0) {
    this.stream._duplexState &= READ_NO_READ_AHEAD
  }

  this.updateCallback()
}

function updateReadNT() {
  if ((this.stream._duplexState & READ_UPDATING) === 0) {
    this.stream._duplexState &= READ_NOT_NEXT_TICK
    this.update()
  }
}

function updateWriteNT() {
  if ((this.stream._duplexState & WRITE_UPDATING) === 0) {
    this.stream._duplexState &= WRITE_NOT_NEXT_TICK
    this.update()
  }
}

function tickDrains(drains) {
  for (let i = 0; i < drains.length; i++) {
    // drains.writes are monotonic, so if one is 0 its always the first one
    if (--drains[i].writes === 0) {
      drains.shift().resolve(true)
      i--
    }
  }
}

function afterOpen(err) {
  const stream = this.stream

  if (err) stream.destroy(err)

  if ((stream._duplexState & DESTROYING) === 0) {
    if ((stream._duplexState & READ_PRIMARY_STATUS) === 0) {
      stream._duplexState |= READ_PRIMARY
    }

    if ((stream._duplexState & WRITE_PRIMARY_STATUS) === 0) {
      stream._duplexState |= WRITE_PRIMARY
    }

    stream.emit('open')
  }

  stream._duplexState &= NOT_ACTIVE

  if (stream._writableState !== null) {
    stream._writableState.updateCallback()
  }

  if (stream._readableState !== null) {
    stream._readableState.updateCallback()
  }
}

function afterTransform(err, data) {
  if (data !== undefined && data !== null) this.push(data)
  this._writableState.afterWrite(err)
}

function newListener(name) {
  if (this._readableState !== null) {
    if (name === 'data') {
      this._duplexState |= READ_EMIT_DATA | READ_RESUMED_READ_AHEAD
      this._readableState.updateNextTick()
    }
    if (name === 'readable') {
      this._duplexState |= READ_EMIT_READABLE
      this._readableState.updateNextTick()
    }
  }

  if (this._writableState !== null) {
    if (name === 'drain') {
      this._duplexState |= WRITE_EMIT_DRAIN
      this._writableState.updateNextTick()
    }
  }
}

class Stream extends EventEmitter {
  constructor(opts) {
    super()

    this._duplexState = 0
    this._readableState = null
    this._writableState = null

    if (opts) {
      if (opts.open) this._open = opts.open
      if (opts.destroy) this._destroy = opts.destroy
      if (opts.predestroy) this._predestroy = opts.predestroy
      if (opts.signal) opts.signal.addEventListener('abort', abort.bind(this))
    }

    this.on('newListener', newListener)
  }

  _open(cb) {
    cb(null)
  }

  _destroy(cb) {
    cb(null)
  }

  _predestroy() {
    // does nothing
  }

  get readable() {
    return this._readableState !== null ? true : undefined
  }

  get writable() {
    return this._writableState !== null ? true : undefined
  }

  get destroyed() {
    return (this._duplexState & DESTROYED) !== 0
  }

  get destroying() {
    return (this._duplexState & DESTROY_STATUS) !== 0
  }

  destroy(err) {
    if ((this._duplexState & DESTROY_STATUS) === 0) {
      if (!err) err = StreamError.STREAM_DESTROYED()
      this._duplexState = (this._duplexState | DESTROYING) & NON_PRIMARY

      if (this._readableState !== null) {
        this._readableState.highWaterMark = 0
        this._readableState.error = err
      }

      if (this._writableState !== null) {
        this._writableState.highWaterMark = 0
        this._writableState.error = err
      }

      this._duplexState |= PREDESTROYING
      this._predestroy()
      this._duplexState &= NOT_PREDESTROYING

      if (this._readableState !== null) {
        this._readableState.updateNextTick()
      }

      if (this._writableState !== null) {
        this._writableState.updateNextTick()
      }
    }
  }
}

class Readable extends Stream {
  constructor(opts) {
    super(opts)

    this._duplexState |= OPENING | WRITE_DONE | READ_READ_AHEAD
    this._readableState = new ReadableState(this, opts)

    if (opts) {
      if (this._readableState.readAhead === false) this._duplexState &= READ_NO_READ_AHEAD
      if (opts.read) this._read = opts.read
      if (opts.eagerOpen) this._readableState.updateNextTick()
      if (opts.encoding) this.setEncoding(opts.encoding)
    }
  }

  static deferred(fn, opts) {
    const out = new PassThrough(opts)

    fn()
      .then((src) => {
        if (src === null) return out.end()
        if (out.destroying) return
        pipeline(src, out, noop)
      })
      .catch((err) => out.destroy(err))

    return out
  }

  setEncoding(encoding) {
    const dec = new TextDecoder(encoding)
    const map = this._readableState.map || echo
    this._readableState.map = mapOrSkip
    return this

    function mapOrSkip(data) {
      const next = dec.push(data)
      return next === '' && (data.byteLength !== 0 || dec.remaining > 0) ? null : map(next)
    }
  }

  _read(cb) {
    cb(null)
  }

  pipe(dest, cb) {
    this._readableState.updateNextTick()
    this._readableState.pipe(dest, cb)
    return dest
  }

  read() {
    this._readableState.updateNextTick()
    return this._readableState.read()
  }

  push(data) {
    this._readableState.updateNextTickIfOpen()
    return this._readableState.push(data)
  }

  unshift(data) {
    this._readableState.updateNextTickIfOpen()
    return this._readableState.unshift(data)
  }

  resume() {
    this._duplexState |= READ_RESUMED_READ_AHEAD
    this._readableState.updateNextTick()
    return this
  }

  pause() {
    this._duplexState &=
      this._readableState.readAhead === false ? READ_PAUSED_NO_READ_AHEAD : READ_PAUSED
    return this
  }

  static _fromAsyncIterator(ite, opts) {
    let destroy

    const rs = new Readable({
      ...opts,
      read(cb) {
        ite.next().then(push).then(cb.bind(null, null)).catch(cb)
      },
      predestroy() {
        destroy = ite.return()
      },
      destroy(cb) {
        if (!destroy) return cb(null)
        destroy.then(cb.bind(null, null)).catch(cb)
      }
    })

    return rs

    function push(data) {
      if (data.done) rs.push(null)
      else rs.push(data.value)
    }
  }

  static from(data, opts) {
    if (isReadStreamx(data)) return data
    if (data[asyncIterator]) return this._fromAsyncIterator(data[asyncIterator](), opts)
    if (!Array.isArray(data)) data = data === undefined ? [] : [data]

    let i = 0
    return new Readable({
      ...opts,
      read(cb) {
        this.push(i === data.length ? null : data[i++])
        cb(null)
      }
    })
  }

  static isBackpressured(rs) {
    return (
      (rs._duplexState & READ_BACKPRESSURE_STATUS) !== 0 ||
      rs._readableState.buffered >= rs._readableState.highWaterMark
    )
  }

  static isPaused(rs) {
    return (rs._duplexState & READ_RESUMED) === 0
  }

  [asyncIterator]() {
    const stream = this

    let error = null
    let promiseResolve = null
    let promiseReject = null

    this.on('error', (err) => {
      error = err
    })
    this.on('readable', onreadable)
    this.on('close', onclose)

    return {
      [asyncIterator]() {
        return this
      },
      next() {
        return new Promise(function (resolve, reject) {
          promiseResolve = resolve
          promiseReject = reject
          const data = stream.read()
          if (data !== null) ondata(data)
          else if ((stream._duplexState & DESTROYED) !== 0) ondata(null)
        })
      },
      return() {
        return destroy(null)
      },
      throw(err) {
        return destroy(err)
      }
    }

    function onreadable() {
      if (promiseResolve !== null) ondata(stream.read())
    }

    function onclose() {
      if (promiseResolve !== null) ondata(null)
    }

    function ondata(data) {
      if (promiseReject === null) return
      if (error) {
        promiseReject(error)
      } else if (data === null && (stream._duplexState & READ_DONE) === 0) {
        promiseReject(StreamError.STREAM_DESTROYED())
      } else {
        promiseResolve({ value: data, done: data === null })
      }
      promiseReject = promiseResolve = null
    }

    function destroy(err) {
      stream.destroy(err)
      return new Promise((resolve, reject) => {
        if (stream._duplexState & DESTROYED) return resolve({ value: undefined, done: true })
        stream.once('close', function () {
          if (err) reject(err)
          else resolve({ value: undefined, done: true })
        })
      })
    }
  }
}

class Writable extends Stream {
  constructor(opts) {
    super(opts)

    this._duplexState |= OPENING | READ_DONE
    this._writableState = new WritableState(this, opts)

    if (opts) {
      if (opts.writev) this._writev = opts.writev
      if (opts.write) this._write = opts.write
      if (opts.final) this._final = opts.final
      if (opts.eagerOpen) this._writableState.updateNextTick()
    }
  }

  cork() {
    this._duplexState |= WRITE_CORKED
  }

  uncork() {
    this._duplexState &= WRITE_NOT_CORKED
    this._writableState.updateNextTick()
  }

  _writev(batch, cb) {
    cb(null)
  }

  _write(data, cb) {
    this._writableState.autoBatch(data, cb)
  }

  _final(cb) {
    cb(null)
  }

  static isBackpressured(ws) {
    return (ws._duplexState & WRITE_BACKPRESSURE_STATUS) !== 0
  }

  static drained(ws) {
    if (ws.destroyed) return Promise.resolve(false)

    const state = ws._writableState
    const pending = isWritev(ws) ? Math.min(1, state.queue.length) : state.queue.length
    const writes = pending + (ws._duplexState & WRITE_WRITING ? 1 : 0)
    if (writes === 0) return Promise.resolve(true)

    if (state.drains === null) state.drains = []
    return new Promise((resolve) => {
      state.drains.push({ writes, resolve })
    })
  }

  write(data) {
    this._writableState.updateNextTick()
    return this._writableState.push(data)
  }

  end(data) {
    this._writableState.updateNextTick()
    this._writableState.end(data)
    return this
  }
}

class Duplex extends Readable {
  // and Writable
  constructor(opts) {
    super(opts)

    this._duplexState = OPENING | (this._duplexState & READ_READ_AHEAD)
    this._writableState = new WritableState(this, opts)

    if (opts) {
      if (opts.writev) this._writev = opts.writev
      if (opts.write) this._write = opts.write
      if (opts.final) this._final = opts.final
    }
  }

  cork() {
    this._duplexState |= WRITE_CORKED
  }

  uncork() {
    this._duplexState &= WRITE_NOT_CORKED
    this._writableState.updateNextTick()
  }

  _writev(batch, cb) {
    cb(null)
  }

  _write(data, cb) {
    this._writableState.autoBatch(data, cb)
  }

  _final(cb) {
    cb(null)
  }

  write(data) {
    this._writableState.updateNextTick()
    return this._writableState.push(data)
  }

  end(data) {
    this._writableState.updateNextTick()
    this._writableState.end(data)
    return this
  }
}

class Transform extends Duplex {
  constructor(opts) {
    super(opts)
    this._transformState = new TransformState(this)

    if (opts) {
      if (opts.transform) this._transform = opts.transform
      if (opts.flush) this._flush = opts.flush
    }
  }

  _write(data, cb) {
    if (this._readableState.buffered >= this._readableState.highWaterMark) {
      this._transformState.data = data
    } else {
      this._transform(data, this._transformState.afterTransform)
    }
  }

  _read(cb) {
    if (this._transformState.data !== null) {
      const data = this._transformState.data
      this._transformState.data = null
      cb(null)
      this._transform(data, this._transformState.afterTransform)
    } else {
      cb(null)
    }
  }

  destroy(err) {
    super.destroy(err)
    if (this._transformState.data !== null) {
      this._transformState.data = null
      this._transformState.afterTransform()
    }
  }

  _transform(data, cb) {
    cb(null, data)
  }

  _flush(cb) {
    cb(null)
  }

  _final(cb) {
    this._transformState.afterFinal = cb
    this._flush(transformAfterFlush.bind(this))
  }
}

class PassThrough extends Transform {}

function transformAfterFlush(err, data) {
  const cb = this._transformState.afterFinal
  if (err) return cb(err)

  if (data !== null && data !== undefined) this.push(data)
  this.push(null)
  cb(null)
}

function pipelinePromise(...streams) {
  return new Promise((resolve, reject) => {
    return pipeline(...streams, (err) => {
      if (err) return reject(err)
      resolve()
    })
  })
}

function pipeline(stream, ...streams) {
  const all = Array.isArray(stream) ? [...stream, ...streams] : [stream, ...streams]
  const done = all.length && typeof all[all.length - 1] === 'function' ? all.pop() : null

  if (all.length < 2) throw StreamError.BAD_ARGUMENT('Pipeline requires at least 2 streams')

  let src = all[0]
  let dest = null
  let error = null

  for (let i = 1; i < all.length; i++) {
    dest = all[i]

    if (isStreamx(src)) {
      src.pipe(dest, onerror)
    } else {
      errorHandle(src, true, i > 1, onerror)
      src.pipe(dest)
    }

    src = dest
  }

  if (done) {
    let fin = false

    const autoDestroy =
      isStreamx(dest) || !!(dest._writableState && dest._writableState.autoDestroy)

    dest.on('error', (err) => {
      if (error === null) error = err
    })

    dest.on('finish', () => {
      fin = true
      if (!autoDestroy) done(error)
    })

    if (autoDestroy) {
      dest.on('close', () => done(error || (fin ? null : StreamError.PREMATURE_CLOSE())))
    }
  }

  return dest

  function errorHandle(s, rd, wr, onerror) {
    s.on('error', onerror)
    s.on('close', onclose)

    function onclose() {
      if (rd && s._readableState && !s._readableState.ended) {
        return onerror(StreamError.PREMATURE_CLOSE())
      }
      if (wr && s._writableState && !s._writableState.ended) {
        return onerror(StreamError.PREMATURE_CLOSE())
      }
    }
  }

  function onerror(err) {
    if (!err || error) return
    error = err

    for (const s of all) {
      s.destroy(err)
    }
  }
}

function echo(s) {
  return s
}

function isStream(stream) {
  return !!stream._readableState || !!stream._writableState
}

function isStreamx(stream) {
  return typeof stream._duplexState === 'number' && isStream(stream)
}

function isEnding(stream) {
  return !!stream._readableState && stream._readableState.ending
}

function isEnded(stream) {
  return !!stream._readableState && stream._readableState.ended
}

function isFinishing(stream) {
  return !!stream._writableState && stream._writableState.ending
}

function isFinished(stream) {
  return !!stream._writableState && stream._writableState.ended
}

function getStreamError(stream, opts = {}) {
  const err =
    (stream._readableState && stream._readableState.error) ||
    (stream._writableState && stream._writableState.error)

  // avoid implicit errors by default
  return !opts.all && StreamError.isStreamDestroyed(err) ? null : err
}

function isReadStreamx(stream) {
  return isStreamx(stream) && stream.readable
}

function isDisturbed(stream) {
  return (
    (stream._duplexState & OPENING) !== OPENING ||
    (stream._duplexState & DESTROYING) === DESTROYING ||
    (stream._duplexState & ACTIVE_OR_TICKING) !== 0
  )
}

function isTypedArray(data) {
  return typeof data === 'object' && data !== null && typeof data.byteLength === 'number'
}

function defaultByteLength(data) {
  return isTypedArray(data) ? data.byteLength : 1024
}

function noop() {}

function abort() {
  this.destroy(StreamError.ABORTED())
}

function isWritev(s) {
  return s._writev !== Writable.prototype._writev && s._writev !== Duplex.prototype._writev
}

module.exports = {
  pipeline,
  pipelinePromise,
  isStream,
  isStreamx,
  isEnding,
  isEnded,
  isFinishing,
  isFinished,
  isDisturbed,
  getStreamError,
  Stream,
  Writable,
  Readable,
  Duplex,
  Transform,
  // Export PassThrough for compatibility with Node.js core's stream module
  PassThrough
}
module.exports = class StreamError extends Error {
  constructor(msg, code, fn = StreamError) {
    super(msg)

    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  static isStreamDestroyed(err) {
    return err && err.code === 'STREAM_DESTROYED'
  }

  static isPrematureClose(err) {
    return err && err.code === 'PREMATURE_CLOSE'
  }

  static isAborted(err) {
    return err && err.code === 'ABORTED'
  }

  static isBadArgument(err) {
    return err && err.code === 'BAD_ARGUMENT'
  }

  get name() {
    return 'StreamError'
  }

  static STREAM_DESTROYED() {
    return new StreamError('Stream was destroyed', 'STREAM_DESTROYED', StreamError.STREAM_DESTROYED)
  }

  static PREMATURE_CLOSE(msg = 'Premature close') {
    return new StreamError(msg, 'PREMATURE_CLOSE', StreamError.PREMATURE_CLOSE)
  }

  static ABORTED() {
    return new StreamError('Stream aborted', 'ABORTED', StreamError.ABORTED)
  }

  static BAD_ARGUMENT(msg = 'Bad argument') {
    return new StreamError(msg, 'BAD_ARGUMENT', StreamError.BAD_ARGUMENT)
  }
}
{
  "name": "streamx",
  "version": "2.28.0",
  "description": "An iteration of the Node.js core streams with a series of improvements",
  "main": "index.js",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./errors": {
      "types": "./lib/errors.d.ts",
      "default": "./lib/errors"
    }
  },
  "dependencies": {
    "events-universal": "^1.0.0",
    "fast-fifo": "^1.3.2",
    "text-decoder": "^1.1.0"
  },
  "devDependencies": {
    "b4a": "^1.6.6",
    "brittle": "^3.1.1",
    "end-of-stream": "^1.4.4",
    "lunte": "^1.8.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "runtime.d.ts",
    "lib"
  ],
  "scripts": {
    "format": "prettier . --write",
    "test": "brittle test/all.js && brittle-bare test/all.js",
    "lint": "prettier . --check && lunte"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/streamx.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/streamx/issues"
  },
  "homepage": "https://github.com/mafintosh/streamx"
}
const { Readable } = require('streamx')

module.exports = function (s, forks = 2) {
  const streams = new Array(forks)
  const status = new Array(forks).fill(true)

  let ended = false

  for (let i = 0; i < forks; i++) {
    streams[i] = new Readable({
      read (cb) {
        const check = !status[i]
        status[i] = true
        if (check && allReadable()) s.resume()
        cb(null)
      }
    })
  }

  s.on('end', function () {
    ended = true
    for (const stream of streams) stream.push(null)
  })

  s.on('error', function (err) {
    for (const stream of streams) stream.destroy(err)
  })

  s.on('close', function () {
    if (ended) return
    for (const stream of streams) stream.destroy()
  })

  s.on('data', function (data) {
    let needsPause = false
    for (let i = 0; i < streams.length; i++) {
      if (!(status[i] = streams[i].push(data))) {
        needsPause = true
      }
    }
    if (needsPause) s.pause()
  })

  return streams

  function allReadable () {
    for (let j = 0; j < status.length; j++) {
      if (!status[j]) return false
    }
    return true
  }
}
{
  "name": "teex",
  "version": "1.0.1",
  "description": "Turn a readable stream into multiple readable streamx streams",
  "main": "index.js",
  "dependencies": {
    "streamx": "^2.12.5"
  },
  "devDependencies": {
    "standard": "^14.3.4",
    "tape": "^5.0.1"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/teex.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/teex/issues"
  },
  "homepage": "https://github.com/mafintosh/teex"
}
const PassThroughDecoder = require('./lib/pass-through-decoder')
const UTF8Decoder = require('./lib/utf8-decoder')

module.exports = class TextDecoder {
  constructor(encoding = 'utf8') {
    this.encoding = normalizeEncoding(encoding)

    switch (this.encoding) {
      case 'utf8':
        this.decoder = new UTF8Decoder()
        break
      case 'utf16le':
      case 'base64':
        throw new Error('Unsupported encoding: ' + this.encoding)
      default:
        this.decoder = new PassThroughDecoder(this.encoding)
    }
  }

  get remaining() {
    return this.decoder.remaining
  }

  push(data) {
    if (typeof data === 'string') return data
    return this.decoder.decode(data)
  }

  // For Node.js compatibility
  write(data) {
    return this.push(data)
  }

  end(data) {
    let result = ''
    if (data) result = this.push(data)
    result += this.decoder.flush()
    return result
  }
}

function normalizeEncoding(encoding) {
  encoding = encoding.toLowerCase()

  switch (encoding) {
    case 'utf8':
    case 'utf-8':
      return 'utf8'
    case 'ucs2':
    case 'ucs-2':
    case 'utf16le':
    case 'utf-16le':
      return 'utf16le'
    case 'latin1':
    case 'binary':
      return 'latin1'
    case 'base64':
    case 'ascii':
    case 'hex':
      return encoding
    default:
      throw new Error('Unknown encoding: ' + encoding)
  }
}
const b4a = require('b4a')

module.exports = class PassThroughDecoder {
  constructor(encoding) {
    this.encoding = encoding
  }

  get remaining() {
    return 0
  }

  decode(data) {
    return b4a.toString(data, this.encoding)
  }

  flush() {
    return ''
  }
}
const b4a = require('b4a')

/**
 * https://encoding.spec.whatwg.org/#utf-8-decoder
 */
module.exports = class UTF8Decoder {
  constructor() {
    this._reset()
  }

  get remaining() {
    return this.bytesSeen
  }

  decode(data) {
    if (data.byteLength === 0) return ''

    if (this.bytesNeeded === 0 && trailingIncomplete(data, 0) === 0) {
      this.bytesSeen = trailingBytesSeen(data)
      return b4a.toString(data, 'utf8')
    }

    let result = ''
    let start = 0

    if (this.bytesNeeded > 0) {
      while (start < data.byteLength) {
        const byte = data[start]

        if (byte < this.lowerBoundary || byte > this.upperBoundary) {
          result += '\ufffd'
          this._reset()
          break
        }

        this.lowerBoundary = 0x80
        this.upperBoundary = 0xbf
        this.codePoint = (this.codePoint << 6) | (byte & 0x3f)
        this.bytesSeen++
        start++

        if (this.bytesSeen === this.bytesNeeded) {
          result += String.fromCodePoint(this.codePoint)
          this._reset()
          break
        }
      }

      if (this.bytesNeeded > 0) return result
    }

    const trailing = trailingIncomplete(data, start)
    const end = data.byteLength - trailing

    if (end > start) result += b4a.toString(data, 'utf8', start, end)

    for (let i = end; i < data.byteLength; i++) {
      const byte = data[i]

      if (this.bytesNeeded === 0) {
        if (byte <= 0x7f) {
          this.bytesSeen = 0
          result += String.fromCharCode(byte)
        } else if (byte >= 0xc2 && byte <= 0xdf) {
          this.bytesNeeded = 2
          this.bytesSeen = 1
          this.codePoint = byte & 0x1f
        } else if (byte >= 0xe0 && byte <= 0xef) {
          if (byte === 0xe0) this.lowerBoundary = 0xa0
          else if (byte === 0xed) this.upperBoundary = 0x9f
          this.bytesNeeded = 3
          this.bytesSeen = 1
          this.codePoint = byte & 0xf
        } else if (byte >= 0xf0 && byte <= 0xf4) {
          if (byte === 0xf0) this.lowerBoundary = 0x90
          else if (byte === 0xf4) this.upperBoundary = 0x8f
          this.bytesNeeded = 4
          this.bytesSeen = 1
          this.codePoint = byte & 0x7
        } else {
          this.bytesSeen = 1
          result += '\ufffd'
        }

        continue
      }

      if (byte < this.lowerBoundary || byte > this.upperBoundary) {
        result += '\ufffd'
        i--
        this._reset()

        continue
      }

      this.lowerBoundary = 0x80
      this.upperBoundary = 0xbf

      this.codePoint = (this.codePoint << 6) | (byte & 0x3f)
      this.bytesSeen++

      if (this.bytesSeen === this.bytesNeeded) {
        result += String.fromCodePoint(this.codePoint)
        this._reset()
      }
    }

    return result
  }

  flush() {
    const result = this.bytesNeeded > 0 ? '\ufffd' : ''
    this._reset()
    return result
  }

  _reset() {
    this.codePoint = 0
    this.bytesNeeded = 0
    this.bytesSeen = 0
    this.lowerBoundary = 0x80
    this.upperBoundary = 0xbf
  }
}

function trailingIncomplete(data, start) {
  const len = data.byteLength
  if (len <= start) return 0

  const limit = Math.max(start, len - 4)

  let i = len - 1
  while (i > limit && (data[i] & 0xc0) === 0x80) i--

  if (i < start) return 0

  const byte = data[i]

  let needed
  if (byte <= 0x7f) return 0
  if (byte >= 0xc2 && byte <= 0xdf) needed = 2
  else if (byte >= 0xe0 && byte <= 0xef) needed = 3
  else if (byte >= 0xf0 && byte <= 0xf4) needed = 4
  else return 0

  const available = len - i
  return available < needed ? available : 0
}

function trailingBytesSeen(data) {
  const len = data.byteLength
  if (len === 0) return 0

  const last = data[len - 1]

  if (last <= 0x7f) return 0
  if ((last & 0xc0) !== 0x80) return 1

  const limit = Math.max(0, len - 4)

  let i = len - 2
  while (i >= limit && (data[i] & 0xc0) === 0x80) i--

  if (i < 0) return 1

  const first = data[i]

  let needed
  if (first >= 0xc2 && first <= 0xdf) needed = 2
  else if (first >= 0xe0 && first <= 0xef) needed = 3
  else if (first >= 0xf0 && first <= 0xf4) needed = 4
  else return 1

  if (len - i !== needed) return 1

  if (needed >= 3) {
    const second = data[i + 1]
    if (first === 0xe0 && second < 0xa0) return 1
    if (first === 0xed && second > 0x9f) return 1
    if (first === 0xf0 && second < 0x90) return 1
    if (first === 0xf4 && second > 0x8f) return 1
  }

  return 0
}
{
  "name": "text-decoder",
  "version": "1.2.7",
  "description": "Streaming text decoder that preserves multibyte Unicode characters",
  "exports": {
    "./package": "./package.json",
    ".": "./index.js"
  },
  "files": [
    "index.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/text-decoder.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/text-decoder/issues"
  },
  "homepage": "https://github.com/holepunchto/text-decoder#readme",
  "dependencies": {
    "b4a": "^1.6.4"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  }
}
module.exports = class TimerBrowser {
  constructor (ms, fn, ctx = null, interval = false) {
    this.ms = ms
    this.ontimeout = fn
    this.context = ctx || null
    this.interval = interval
    this.done = false

    this._timer = interval
      ? setInterval(callInterval, ms, this)
      : setTimeout(callTimeout, ms, this)
  }

  unref () {}

  ref () {}

  refresh () {
    if (this.done) return

    if (this.interval) {
      clearInterval(this._timer)
      this._timer = setInterval(callInterval, this.ms, this)
    } else {
      clearTimeout(this._timer)
      this._timer = setTimeout(callTimeout, this.ms, this)
    }
  }

  destroy () {
    this.done = true
    this.ontimeout = null

    if (this.interval) clearInterval(this._timer)
    else clearTimeout(this._timer)
  }

  static once (ms, fn, ctx) {
    return new this(ms, fn, ctx, false)
  }

  static on (ms, fn, ctx) {
    return new this(ms, fn, ctx, true)
  }
}

function callTimeout (self) {
  self.done = true
  self.ontimeout.call(self.context)
}

function callInterval (self) {
  self.ontimeout.call(self.context)
}
module.exports = isNode()
  ? require('./node')
  : require('./browser')

function isNode () {
  const to = setTimeout(function () {}, 1000)
  clearTimeout(to)
  return !!to.refresh
}
module.exports = class Timer {
  constructor (ms, fn, ctx = null, interval = false) {
    this.ms = ms
    this.ontimeout = fn
    this.context = ctx
    this.interval = interval
    this.done = false

    this._timer = interval
      ? setInterval(callInterval, ms, this)
      : setTimeout(callTimeout, ms, this)
  }

  unref () {
    this._timer.unref()
  }

  ref () {
    this._timer.ref()
  }

  refresh () {
    if (this.done !== true) this._timer.refresh()
  }

  destroy () {
    this.done = true
    this.ontimeout = null
    if (this.interval) clearInterval(this._timer)
    else clearTimeout(this._timer)
  }

  static once (ms, fn, ctx) {
    return new this(ms, fn, ctx, false)
  }

  static on (ms, fn, ctx) {
    return new this(ms, fn, ctx, true)
  }
}

function callTimeout (self) {
  self.done = true
  self.ontimeout.call(self.context)
}

function callInterval (self) {
  self.ontimeout.call(self.context)
}
{
  "name": "timeout-refresh",
  "version": "2.0.1",
  "description": "Efficiently refresh a timer",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^16.0.4",
    "tape": "^5.5.2"
  },
  "browser": "./browser.js",
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/timeout-refresh.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/timeout-refresh/issues"
  },
  "homepage": "https://github.com/mafintosh/timeout-refresh"
}
const b4a = require('b4a')

unslab.all = all
unslab.is = is

module.exports = unslab

function unslab (buf) {
  if (buf === null || buf.buffer.byteLength === buf.byteLength) return buf
  const copy = b4a.allocUnsafeSlow(buf.byteLength)
  copy.set(buf, 0)
  return copy
}

function is (buf) {
  return buf.buffer.byteLength !== buf.byteLength
}

function all (list) {
  let size = 0
  for (let i = 0; i < list.length; i++) {
    const buf = list[i]
    size += buf === null || buf.buffer.byteLength === buf.byteLength ? 0 : buf.byteLength
  }

  const copy = b4a.allocUnsafeSlow(size)
  const result = new Array(list.length)

  let offset = 0
  for (let i = 0; i < list.length; i++) {
    let buf = list[i]

    if (buf !== null && buf.buffer.byteLength !== buf.byteLength) {
      copy.set(buf, offset)
      buf = copy.subarray(offset, offset += buf.byteLength)
    }

    result[i] = buf
  }

  return result
}
{
  "name": "unslab",
  "version": "1.3.0",
  "description": "Unslab some slab'ed buffers",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.6.6"
  },
  "devDependencies": {
    "brittle": "^3.5.2",
    "standard": "^17.1.0"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/unslab.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/unslab/issues"
  },
  "homepage": "https://github.com/holepunchto/unslab"
}
module.exports = read

var MSB = 0x80
  , REST = 0x7F

function read(buf, offset) {
  var res    = 0
    , offset = offset || 0
    , shift  = 0
    , counter = offset
    , b
    , l = buf.length

  do {
    if (counter >= l) {
      read.bytes = 0
      throw new RangeError('Could not decode varint')
    }
    b = buf[counter++]
    res += shift < 28
      ? (b & REST) << shift
      : (b & REST) * Math.pow(2, shift)
    shift += 7
  } while (b >= MSB)

  read.bytes = counter - offset

  return res
}
module.exports = encode

var MSB = 0x80
  , REST = 0x7F
  , MSBALL = ~REST
  , INT = Math.pow(2, 31)

function encode(num, out, offset) {
  out = out || []
  offset = offset || 0
  var oldOffset = offset

  while(num >= INT) {
    out[offset++] = (num & 0xFF) | MSB
    num /= 128
  }
  while(num & MSBALL) {
    out[offset++] = (num & 0xFF) | MSB
    num >>>= 7
  }
  out[offset] = num | 0
  
  encode.bytes = offset - oldOffset + 1
  
  return out
}
module.exports = {
    encode: require('./encode.js')
  , decode: require('./decode.js')
  , encodingLength: require('./length.js')
}

var N1 = Math.pow(2,  7)
var N2 = Math.pow(2, 14)
var N3 = Math.pow(2, 21)
var N4 = Math.pow(2, 28)
var N5 = Math.pow(2, 35)
var N6 = Math.pow(2, 42)
var N7 = Math.pow(2, 49)
var N8 = Math.pow(2, 56)
var N9 = Math.pow(2, 63)

module.exports = function (value) {
  return (
    value < N1 ? 1
  : value < N2 ? 2
  : value < N3 ? 3
  : value < N4 ? 4
  : value < N5 ? 5
  : value < N6 ? 6
  : value < N7 ? 7
  : value < N8 ? 8
  : value < N9 ? 9
  :              10
  )
}
{
  "name": "varint",
  "version": "5.0.0",
  "description": "protobuf-style varint bytes - use msb to create integer values of varying sizes",
  "main": "index.js",
  "scripts": {
    "test": "node test.js"
  },
  "repository": {
    "type": "git",
    "url": "git://github.com/chrisdickinson/varint.git"
  },
  "keywords": [
    "varint",
    "protobuf",
    "encode",
    "decode"
  ],
  "author": "Chris Dickinson <chris@neversaw.us>",
  "license": "MIT",
  "devDependencies": {
    "tape": "~2.12.3"
  }
}
const { runtime, platform, arch, version } =
  typeof Bare !== 'undefined'
    ? {
        runtime: 'bare',
        platform: global.Bare.platform,
        arch: global.Bare.arch,
        version: global.Bare.version
      }
    : typeof process !== 'undefined'
      ? {
          runtime: 'node',
          platform: global.process.platform,
          arch: global.process.arch,
          version: global.process.version
        }
      : typeof Window !== 'undefined'
        ? { runtime: 'browser', platform: 'unknown', arch: 'unknown', version: 'unknown' }
        : { runtime: 'unknown', platform: 'unknown', arch: 'unknown', version: 'unknown' }

exports.runtime = runtime
exports.version = version
exports.platform = platform
exports.arch = arch
exports.isBare = runtime === 'bare'
exports.isBareKit = exports.isBare && typeof BareKit !== 'undefined'
exports.isPear = typeof Pear !== 'undefined'
exports.isNode = runtime === 'node'
exports.isBrowser = runtime === 'browser'
exports.isWindows = platform === 'win32'
exports.isLinux = platform === 'linux'
exports.isMac = platform === 'darwin'
exports.isIOS = platform === 'ios' || platform === 'ios-simulator'
exports.isAndroid = platform === 'android'
exports.isElectron = typeof process !== 'undefined' && !!global.process.versions?.electron
exports.isElectronRenderer = exports.isElectron && global.process.type === 'renderer'
exports.isElectronWorker = exports.isElectron && global.process.type === 'worker'
{
  "name": "which-runtime",
  "version": "1.4.0",
  "description": "Detect if you are in Bare or Node and which os etc",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte .",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/which-runtime.git"
  },
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/which-runtime/issues"
  },
  "homepage": "https://github.com/holepunchto/which-runtime",
  "devDependencies": {
    "brittle": "^3.0.0",
    "lunte": "^1.4.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = class MaxCache {
  constructor({ maxSize, maxAge, createMap, ongc }) {
    this.maxSize = maxSize
    this.maxAge = maxAge
    this.ongc = ongc || null

    this._createMap = createMap || defaultCreateMap
    this._latest = this._createMap()
    this._oldest = this._createMap()
    this._retained = this._createMap()
    this._gced = false
    this._interval = null

    if (this.maxAge > 0 && this.maxAge < Infinity) {
      const tick = Math.ceil((2 / 3) * this.maxAge)
      this._interval = setInterval(this._gcAuto.bind(this), tick)
      if (this._interval.unref) this._interval.unref()
    }
  }

  get size() {
    return this._latest.size + this._oldest.size + this._retained.size
  }

  *[Symbol.iterator]() {
    for (const it of [this._latest, this._oldest, this._retained]) {
      yield* it
    }
  }

  *keys() {
    for (const it of [this._latest, this._oldest, this._retained]) {
      yield* it.keys()
    }
  }

  *values() {
    for (const it of [this._latest, this._oldest, this._retained]) {
      yield* it.values()
    }
  }

  destroy() {
    this.clear()
    clearInterval(this._interval)
    this._interval = null
  }

  clear() {
    this._gced = true
    this._latest.clear()
    this._oldest.clear()
    this._retained.clear()
  }

  set(k, v) {
    if (this._retained.has(k)) return this
    this._latest.set(k, v)
    this._oldest.delete(k) || this._retained.delete(k)
    if (this._latest.size >= this.maxSize) this._gc()
    return this
  }

  retain(k, v) {
    this._retained.set(k, v)
    this._latest.delete(k) || this._oldest.delete(k)
    return this
  }

  delete(k) {
    return (
      this._latest.delete(k) ||
      this._oldest.delete(k) ||
      this._retained.delete(k)
    )
  }

  has(k) {
    return this._latest.has(k) || this._oldest.has(k) || this._retained.has(k)
  }

  get(k) {
    if (this._latest.has(k)) {
      return this._latest.get(k)
    }

    if (this._oldest.has(k)) {
      const v = this._oldest.get(k)
      this._latest.set(k, v)
      this._oldest.delete(k)
      return v
    }

    if (this._retained.has(k)) {
      return this._retained.get(k)
    }

    return null
  }

  _gcAuto() {
    if (!this._gced) this._gc()
    this._gced = false
  }

  _gc() {
    this._gced = true
    if (this.ongc !== null && this._oldest.size > 0) this.ongc(this._oldest)
    this._oldest = this._latest
    this._latest = this._createMap()
  }
}

function defaultCreateMap() {
  return new Map()
}
{
  "name": "xache",
  "version": "1.3.0",
  "description": "Yet another auto expiring, max sizable cache",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "devDependencies": {
    "brittle": "^3.3.2",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "test": "prettier --check . && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/xache.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/xache/issues"
  },
  "homepage": "https://github.com/mafintosh/xache"
}
const b4a = require('b4a')

const ALPHABET = 'ybndrfg8ejkmcpqxot1uwisza345h769'
const MIN = 0x31 // 1
const MAX = 0x7a // z
const REVERSE = new Int8Array(1 + MAX - MIN)

REVERSE.fill(-1)

for (let i = 0; i < ALPHABET.length; i++) {
  const v = ALPHABET.charCodeAt(i) - MIN
  REVERSE[v] = i
}

exports.encode = encode
exports.decode = decode
exports.ALPHABET = ALPHABET

function decode (s, out) {
  let pb = 0
  let ps = 0

  const r = s.length & 7
  const q = (s.length - r) / 8

  if (!out) out = b4a.allocUnsafe(Math.ceil(s.length * 5 / 8))

  // 0 5 2 7 4 1 6 3 (+5 mod 8)
  for (let i = 0; i < q; i++) {
    const a = quintet(s, ps++)
    const b = quintet(s, ps++)
    const c = quintet(s, ps++)
    const d = quintet(s, ps++)
    const e = quintet(s, ps++)
    const f = quintet(s, ps++)
    const g = quintet(s, ps++)
    const h = quintet(s, ps++)

    out[pb++] = (a << 3) | (b >>> 2)
    out[pb++] = ((b & 0b11) << 6) | (c << 1) | (d >>> 4)
    out[pb++] = ((d & 0b1111) << 4) | (e >>> 1)
    out[pb++] = ((e & 0b1) << 7) | (f << 2) | (g >>> 3)
    out[pb++] = ((g & 0b111) << 5) | h
  }

  if (r === 0) return out.subarray(0, pb)

  const a = quintet(s, ps++)
  const b = quintet(s, ps++)

  out[pb++] = (a << 3) | (b >>> 2)

  if (r <= 2) return out.subarray(0, pb)

  const c = quintet(s, ps++)
  const d = quintet(s, ps++)

  out[pb++] = ((b & 0b11) << 6) | (c << 1) | (d >>> 4)

  if (r <= 4) return out.subarray(0, pb)

  const e = quintet(s, ps++)

  out[pb++] = ((d & 0b1111) << 4) | (e >>> 1)

  if (r <= 5) return out.subarray(0, pb)

  const f = quintet(s, ps++)
  const g = quintet(s, ps++)

  out[pb++] = ((e & 0b1) << 7) | (f << 2) | (g >>> 3)

  if (r <= 7) return out.subarray(0, pb)

  const h = quintet(s, ps++)

  out[pb++] = ((g & 0b111) << 5) | h

  return out.subarray(0, pb)
}

function encode (buf) {
  if (typeof buf === 'string') buf = b4a.from(buf)

  const max = buf.byteLength * 8

  let s = ''

  for (let p = 0; p < max; p += 5) {
    const i = p >>> 3
    const j = p & 7

    if (j <= 3) {
      s += ALPHABET[(buf[i] >>> (3 - j)) & 0b11111]
      continue
    }

    const of = j - 3
    const h = (buf[i] << of) & 0b11111
    const l = (i >= buf.byteLength ? 0 : buf[i + 1]) >>> (8 - of)

    s += ALPHABET[h | l]
  }

  return s
}

function quintet (s, i) {
  if (i > s.length) {
    return 0
  }

  const v = s.charCodeAt(i)

  if (v < MIN || v > MAX) {
    throw Error('Invalid character in base32 input: "' + s[i] + '" at position ' + i)
  }

  const bits = REVERSE[v - MIN]

  if (bits === -1) {
    throw Error('Invalid character in base32 input: "' + s[i] + '" at position ' + i)
  }

  return bits
}
{
  "name": "z32",
  "version": "1.1.0",
  "description": "Encode & decode z-base32",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.5.3"
  },
  "devDependencies": {
    "base-x": "^4.0.0",
    "base32": "0.0.7",
    "brittle": "^3.1.3",
    "nanobench": "^3.0.0",
    "rfc4648": "^1.5.2",
    "standard": "^17.0.0"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/z32.git"
  },
  "scripts": {
    "test": "standard && brittle test.js",
    "bench": "node benchmark.js"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/z32/issues"
  },
  "homepage": "https://github.com/mafintosh/z32"
}
{
  "name": "atproto-store",
  "version": "0.0.25",
  "description": "Holepunch-native atproto repo store — records in a classic Hyperbee (collection/rkey -> DAG-CBOR). The P2P home; the atproto-repo module is the bridge serializer over it.",
  "type": "module",
  "main": "lib/repo-store.js",
  "scripts": {
    "test": "brittle-node test/*.test.js"
  },
  "dependencies": {
    "atproto-repo": "file:../atproto-repo",
    "@ipld/dag-cbor": "^9.2.1",
    "b4a": "^1.6.0",
    "corestore": "^7.4.0",
    "hyperbee": "^2.20.0",
    "random-access-memory": "^6.2.0",
    "bare-fs": "^4.7.3",
    "bare-path": "^3.0.1"
  },
  "devDependencies": {
    "brittle": "^4.0.2"
  },
  "imports": {
    "#node:fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "#node:path": {
      "bare": "bare-path",
      "default": "path"
    }
  },
  "overrides": {
    "rocksdb-native": "3.17.2",
    "hypercore-storage": "3.2.0"
  }
}
function isBuffer(value) {
  return Buffer.isBuffer(value) || value instanceof Uint8Array
}

function isEncoding(encoding) {
  return Buffer.isEncoding(encoding)
}

function alloc(size, fill, encoding) {
  return Buffer.alloc(size, fill, encoding)
}

function allocUnsafe(size) {
  return Buffer.allocUnsafe(size)
}

function allocUnsafeSlow(size) {
  return Buffer.allocUnsafeSlow(size)
}

function byteLength(string, encoding) {
  return Buffer.byteLength(string, encoding)
}

function compare(a, b) {
  return Buffer.compare(a, b)
}

function concat(buffers, totalLength) {
  return Buffer.concat(buffers, totalLength)
}

function copy(source, target, targetStart, start, end) {
  return toBuffer(source).copy(target, targetStart, start, end)
}

function equals(a, b) {
  return toBuffer(a).equals(b)
}

function fill(buffer, value, offset, end, encoding) {
  return toBuffer(buffer).fill(value, offset, end, encoding)
}

function from(value, encodingOrOffset, length) {
  return Buffer.from(value, encodingOrOffset, length)
}

function includes(buffer, value, byteOffset, encoding) {
  return toBuffer(buffer).includes(value, byteOffset, encoding)
}

function indexOf(buffer, value, byfeOffset, encoding) {
  return toBuffer(buffer).indexOf(value, byfeOffset, encoding)
}

function lastIndexOf(buffer, value, byteOffset, encoding) {
  return toBuffer(buffer).lastIndexOf(value, byteOffset, encoding)
}

function swap16(buffer) {
  return toBuffer(buffer).swap16()
}

function swap32(buffer) {
  return toBuffer(buffer).swap32()
}

function swap64(buffer) {
  return toBuffer(buffer).swap64()
}

function toBuffer(buffer) {
  if (Buffer.isBuffer(buffer)) return buffer
  return Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

function toString(buffer, encoding, start, end) {
  return toBuffer(buffer).toString(encoding, start, end)
}

function write(buffer, string, offset, length, encoding) {
  return toBuffer(buffer).write(string, offset, length, encoding)
}

function readDoubleBE(buffer, offset) {
  return toBuffer(buffer).readDoubleBE(offset)
}

function readDoubleLE(buffer, offset) {
  return toBuffer(buffer).readDoubleLE(offset)
}

function readFloatBE(buffer, offset) {
  return toBuffer(buffer).readFloatBE(offset)
}

function readFloatLE(buffer, offset) {
  return toBuffer(buffer).readFloatLE(offset)
}

function readInt32BE(buffer, offset) {
  return toBuffer(buffer).readInt32BE(offset)
}

function readInt32LE(buffer, offset) {
  return toBuffer(buffer).readInt32LE(offset)
}

function readUInt32BE(buffer, offset) {
  return toBuffer(buffer).readUInt32BE(offset)
}

function readUInt32LE(buffer, offset) {
  return toBuffer(buffer).readUInt32LE(offset)
}

function writeDoubleBE(buffer, value, offset) {
  return toBuffer(buffer).writeDoubleBE(value, offset)
}

function writeDoubleLE(buffer, value, offset) {
  return toBuffer(buffer).writeDoubleLE(value, offset)
}

function writeFloatBE(buffer, value, offset) {
  return toBuffer(buffer).writeFloatBE(value, offset)
}

function writeFloatLE(buffer, value, offset) {
  return toBuffer(buffer).writeFloatLE(value, offset)
}

function writeInt32BE(buffer, value, offset) {
  return toBuffer(buffer).writeInt32BE(value, offset)
}

function writeInt32LE(buffer, value, offset) {
  return toBuffer(buffer).writeInt32LE(value, offset)
}

function writeUInt32BE(buffer, value, offset) {
  return toBuffer(buffer).writeUInt32BE(value, offset)
}

function writeUInt32LE(buffer, value, offset) {
  return toBuffer(buffer).writeUInt32LE(value, offset)
}

module.exports = {
  isBuffer,
  isEncoding,
  alloc,
  allocUnsafe,
  allocUnsafeSlow,
  byteLength,
  compare,
  concat,
  copy,
  equals,
  fill,
  from,
  includes,
  indexOf,
  lastIndexOf,
  swap16,
  swap32,
  swap64,
  toBuffer,
  toString,
  write,
  readDoubleBE,
  readDoubleLE,
  readFloatBE,
  readFloatLE,
  readInt32BE,
  readInt32LE,
  readUInt32BE,
  readUInt32LE,
  writeDoubleBE,
  writeDoubleLE,
  writeFloatBE,
  writeFloatLE,
  writeInt32BE,
  writeInt32LE,
  writeUInt32BE,
  writeUInt32LE
}
{
  "name": "b4a",
  "version": "1.8.1",
  "description": "Bridging the gap between buffers and typed arrays",
  "exports": {
    "./package": "./package.json",
    ".": {
      "react-native": "./react-native.js",
      "browser": "./browser.js",
      "default": "./index.js"
    }
  },
  "files": [
    "browser.js",
    "index.js",
    "react-native.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:bare && npm run test:node",
    "test:bare": "brittle-bare --coverage test.mjs",
    "test:node": "brittle-node --coverage test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/b4a.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/b4a/issues"
  },
  "homepage": "https://github.com/holepunchto/b4a#readme",
  "devDependencies": {
    "brittle": "^3.5.2",
    "lunte": "^1.7.0",
    "nanobench": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "react-native-b4a": "*"
  },
  "peerDependenciesMeta": {
    "react-native-b4a": {
      "optional": true
    }
  }
}
module.exports = require.addon()
const binding = require('./binding')

module.exports = binding.abort
{
  "name": "bare-abort",
  "version": "2.0.13",
  "description": "Cause abnormal program termination and generate a crash report",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-abort.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-abort/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-abort#readme",
  "devDependencies": {
    "cmake-bare": "^1.1.7",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  }
}
const ESC = '\x1b'
const CSI = ESC + '['
const SGR = (n) => CSI + n + 'm'

exports.constants = {
  ESC,
  CSI,
  SGR
}

// https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_(Control_Sequence_Introducer)_sequences

exports.cursorHide = CSI + '?25l'
exports.cursorShow = CSI + '?25h'

exports.cursorUp = function cursorUp(n = 1) {
  return CSI + n + 'A'
}

exports.cursorDown = function cursorDown(n = 1) {
  return CSI + n + 'B'
}

exports.cursorForward = function cursorForward(n = 1) {
  return CSI + n + 'C'
}

exports.cursorBack = function cursorBack(n = 1) {
  return CSI + n + 'D'
}

exports.cursorNextLine = function cursorNextLine(n = 1) {
  return CSI + n + 'E'
}

exports.cursorPreviousLine = function cursorPreviousLine(n = 1) {
  return CSI + n + 'F'
}

exports.cursorPosition = function cursorPosition(column, row = 0) {
  if (row === 0) return CSI + (column + 1) + 'G'

  return CSI + (row + 1) + ';' + (column + 1) + 'H'
}

exports.eraseDisplayEnd = CSI + 'J'
exports.eraseDisplayStart = CSI + '1J'
exports.eraseDisplay = CSI + '2J'
exports.eraseLineEnd = CSI + 'K'
exports.eraseLineStart = CSI + '1K'
exports.eraseLine = CSI + '2K'

exports.scrollUp = function scrollUp(n = 1) {
  return CSI + n + 'S'
}

exports.scrollDown = function scrollDown(n = 1) {
  return CSI + n + 'T'
}

// https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_(Select_Graphic_Rendition)_parameters

exports.modifierReset = SGR(0)
exports.modifierBold = SGR(1)
exports.modifierDim = SGR(2)
exports.modifierItalic = SGR(3)
exports.modifierUnderline = SGR(4)
exports.modifierNormal = SGR(22)
exports.modifierNotItalic = SGR(23)
exports.modifierNotUnderline = SGR(24)

// https://en.wikipedia.org/wiki/ANSI_escape_code#Colors

exports.colorBlack = SGR(30)
exports.colorRed = SGR(31)
exports.colorGreen = SGR(32)
exports.colorYellow = SGR(33)
exports.colorBlue = SGR(34)
exports.colorMagenta = SGR(35)
exports.colorCyan = SGR(36)
exports.colorWhite = SGR(37)
exports.colorDefault = SGR(39)
exports.colorBrightBlack = SGR(90)
exports.colorBrightRed = SGR(91)
exports.colorBrightGreen = SGR(92)
exports.colorBrightYellow = SGR(93)
exports.colorBrightBlue = SGR(94)
exports.colorBrightMagenta = SGR(95)
exports.colorBrightCyan = SGR(96)
exports.colorBrightWhite = SGR(97)
{
  "name": "bare-ansi-escapes",
  "version": "2.2.3",
  "description": "Parse and produce ANSI escape sequences",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./key-decoder": {
      "types": "./key-decoder.d.ts",
      "default": "./key-decoder.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "key-decoder.js",
    "key-decoder.d.ts"
  ],
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-ansi-escapes.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-ansi-escapes/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-ansi-escapes#readme",
  "dependencies": {
    "bare-stream": "^2.6.5"
  },
  "devDependencies": {
    "bare-buffer": "^3.0.2",
    "brittle": "^3.3.2",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  },
  "peerDependencies": {
    "bare-buffer": "*"
  },
  "peerDependenciesMeta": {
    "bare-buffer": {
      "optional": true
    }
  }
}
const inspect = require('bare-inspect')

class AssertionError extends Error {
  constructor(opts = {}) {
    let { message = null, actual, expected, operator } = opts

    if (message === null) {
      message = `${inspect(actual)} ${operator} ${inspect(expected)}`
    }

    super(message)

    this.actual = actual
    this.expected = expected
    this.operator = operator
  }

  get name() {
    return 'AssertionError'
  }

  get code() {
    'ASSERTION'
  }
}

function assertFail(opts, fn) {
  if (opts.message instanceof Error) throw opts.message

  const err = new AssertionError(opts)

  if (Error.captureStackTrace) Error.captureStackTrace(err, fn)

  throw err
}

module.exports = exports = function assert(actual, message) {
  if (actual) return

  assertFail({ message, actual, expected: true, operator: '==' }, assert)
}

exports.AssertionError = AssertionError

exports.fail = function fail(message) {
  if (message === undefined) message = 'Failed'

  assertFail({ message, operator: 'fail' }, fail)
}

exports.ok = function ok(actual, message) {
  if (actual) return

  assertFail({ message, actual, expected: true, operator: '==' }, ok)
}

exports.notOk = function ok(actual, message) {
  if (!actual) return

  assertFail({ message, actual, expected: false, operator: '==' }, ok)
}

exports.equal = function equal(actual, expected, message) {
  if (actual == expected || (actual !== actual && expected !== expected)) {
    return
  }

  assertFail({ message, actual, expected, operator: '==' }, equal)
}

exports.notEqual = function notEqual(actual, expected, message) {
  if (actual != expected && (actual === actual || expected === expected)) {
    return
  }

  assertFail({ message, actual, expected, operator: '!=' }, notEqual)
}

exports.strictEqual = function strictEqual(actual, expected, message) {
  if (Object.is(actual, expected)) return

  assertFail(
    { message, actual, expected, operator: 'strictEqual' },
    strictEqual
  )
}

exports.notStrictEqual = function notStrictEqual(actual, expected, message) {
  if (!Object.is(actual, expected)) return

  assertFail(
    { message, actual, expected, operator: 'notStrictEqual' },
    notStrictEqual
  )
}
{
  "name": "bare-assert",
  "version": "1.2.0",
  "description": "Assertion library for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts"
  ],
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-assert.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-assert/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-assert#readme",
  "dependencies": {
    "bare-inspect": "^3.1.2"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  }
}
module.exports = require.addon()
const constants = require('./lib/constants')
const ascii = require('./lib/ascii')
const base64 = require('./lib/base64')
const base64url = require('./lib/base64url')
const hex = require('./lib/hex')
const utf8 = require('./lib/utf8')
const utf16le = require('./lib/utf16le')
const latin1 = require('./lib/latin1')
const binding = require('./binding')

const kind = Symbol.for('bare.buffer.kind')

let poolSize = 0

module.exports = exports = class Buffer extends Uint8Array {
  static get [kind]() {
    return 0 // Compatibility version
  }

  static get poolSize() {
    return poolSize
  }

  static set poolSize(value) {
    poolSize = Math.max(0, value)
  }

  constructor(arrayBuffer, offset, length, opts = {}) {
    if (typeof arrayBuffer === 'number') {
      opts = offset || {}

      const { uninitialized = false } = opts

      offset = 0
      length = arrayBuffer

      if (length > constants.MAX_LENGTH) {
        throw new RangeError(`Buffer length must be at most ${constants.MAX_LENGTH}`)
      }

      arrayBuffer = uninitialized ? binding.allocUnsafe(length) : binding.alloc(length)
    } else {
      if (length > constants.MAX_LENGTH) {
        throw new RangeError(`Buffer length must be at most ${constants.MAX_LENGTH}`)
      }

      if (typeof offset === 'object' && offset !== null) {
        opts = offset
        offset = 0
        length = arrayBuffer.byteLength
      } else if (typeof length === 'length' && length !== null) {
        opts = length
        length = arrayBuffer.byteLength - offset
      }
    }

    super(arrayBuffer, offset, length)
  }

  get [kind]() {
    return Buffer[kind]
  }

  copy(target, targetStart = 0, sourceStart = 0, sourceEnd = this.byteLength) {
    let source = this

    if (targetStart < 0) targetStart = 0
    if (targetStart >= target.byteLength) return 0

    const targetLength = target.byteLength - targetStart

    if (sourceStart < 0) sourceStart = 0
    if (sourceStart >= source.byteLength) return 0

    if (sourceEnd <= sourceStart) return 0
    if (sourceEnd > source.byteLength) sourceEnd = source.byteLength

    if (sourceEnd - sourceStart > targetLength) {
      sourceEnd = sourceStart + targetLength
    }

    const sourceLength = sourceEnd - sourceStart

    if (source === target) {
      target.copyWithin(targetStart, sourceStart, sourceEnd)
    } else {
      if (sourceStart !== 0 || sourceEnd !== source.byteLength) {
        source = source.subarray(sourceStart, sourceEnd)
      }

      target.set(source, targetStart)
    }

    return sourceLength
  }

  equals(target) {
    const source = this

    if (source === target) return true
    if (source.byteLength !== target.byteLength) return false

    return (
      binding.compare(
        source.buffer,
        source.byteOffset,
        source.byteLength,
        target.buffer,
        target.byteOffset,
        target.byteLength
      ) === 0
    )
  }

  compare(
    target,
    targetStart = 0,
    targetEnd = target.byteLength,
    sourceStart = 0,
    sourceEnd = this.byteLength
  ) {
    let source = this

    if (source === target) return 0

    if (arguments.length > 1) {
      if (targetStart < 0) targetStart = 0
      if (targetStart > target.byteLength) targetStart = target.byteLength

      if (targetEnd < targetStart) targetEnd = targetStart
      if (targetEnd > target.byteLength) targetEnd = target.byteLength

      if (sourceStart < 0) sourceStart = 0
      if (sourceStart > source.byteLength) sourceStart = source.byteLength

      if (sourceEnd < sourceStart) sourceEnd = sourceStart
      if (sourceEnd > source.byteLength) sourceEnd = source.byteLength

      if (sourceStart !== 0 || sourceEnd !== source.byteLength) {
        source = source.subarray(sourceStart, sourceEnd)
      }

      if (targetStart !== 0 || targetEnd !== target.byteLength) {
        target = target.subarray(targetStart, targetEnd)
      }
    }

    return binding.compare(
      source.buffer,
      source.byteOffset,
      source.byteLength,
      target.buffer,
      target.byteOffset,
      target.byteLength
    )
  }

  fill(value, offset = 0, end = this.byteLength, encoding = 'utf8') {
    if (typeof value === 'string') {
      if (typeof offset === 'string') {
        // fill(string, encoding)
        encoding = offset
        offset = 0
        end = this.byteLength
      } else if (typeof end === 'string') {
        // fill(string, offset, encoding)
        encoding = end
        end = this.byteLength
      }
    } else if (typeof value === 'number') {
      value = value & 0xff
    } else if (typeof value === 'boolean') {
      value = +value
    }

    if (offset < 0) offset = 0
    if (offset >= this.byteLength) return this

    if (end <= offset) return this
    if (end > this.byteLength) end = this.byteLength

    if (typeof value === 'number') return super.fill(value, offset, end)

    if (typeof value === 'string') value = exports.from(value, encoding)

    const length = value.byteLength

    for (let i = 0, n = end - offset; i < n; ++i) {
      this[i + offset] = value[i % length]
    }

    return this
  }

  includes(value, offset, encoding) {
    return this.indexOf(value, offset, encoding) !== -1
  }

  indexOf(value, offset = 0, encoding) {
    if (typeof value === 'boolean') value = +value

    if (typeof value === 'number') {
      return super.indexOf(value & 0xff, offset)
    }

    return bidirectionalIndexOf(this, value, offset, encoding, true /* first */)
  }

  lastIndexOf(value, offset = this.byteLength - 1, encoding) {
    if (typeof value === 'boolean') value = +value

    if (typeof value === 'number') {
      return super.lastIndexOf(value & 0xff, offset)
    }

    return bidirectionalIndexOf(this, value, offset, encoding, false /* last */)
  }

  swap16() {
    const length = this.byteLength

    if (length % 2 !== 0) {
      throw new RangeError('Buffer size must be a multiple of 16-bits')
    }

    for (let i = 0; i < length; i += 2) swap(this, i, i + 1)

    return this
  }

  swap32() {
    const length = this.byteLength

    if (length % 4 !== 0) {
      throw new RangeError('Buffer size must be a multiple of 32-bits')
    }

    for (let i = 0; i < length; i += 4) {
      swap(this, i, i + 3)
      swap(this, i + 1, i + 2)
    }

    return this
  }

  swap64() {
    const length = this.byteLength

    if (length % 8 !== 0) {
      throw new RangeError('Buffer size must be a multiple of 64-bits')
    }

    for (let i = 0; i < length; i += 8) {
      swap(this, i, i + 7)
      swap(this, i + 1, i + 6)
      swap(this, i + 2, i + 5)
      swap(this, i + 3, i + 4)
    }

    return this
  }

  toString(encoding = 'utf8', start = 0, end = this.byteLength) {
    // toString()
    if (arguments.length === 0) return utf8.toString(this)

    // toString(encoding)
    if (arguments.length === 1) return codecFor(encoding).toString(this)

    if (start < 0) start = 0
    if (start >= this.byteLength) return ''

    if (end <= start) return ''
    if (end > this.byteLength) end = this.byteLength

    let buffer = this

    if (start !== 0 || end !== this.byteLength) {
      buffer = buffer.subarray(start, end)
    }

    return codecFor(encoding).toString(buffer)
  }

  toJSON() {
    return Array.from(this)
  }

  write(string, offset = 0, length = this.byteLength - offset, encoding = 'utf8') {
    // write(string)
    if (arguments.length === 1) return utf8.write(this, string)

    if (typeof offset === 'string') {
      // write(string, encoding)
      encoding = offset
      offset = 0
      length = this.byteLength
    } else if (typeof length === 'string') {
      // write(string, offset, encoding)
      encoding = length
      length = this.byteLength - offset
    }

    length = Math.min(length, exports.byteLength(string, encoding))

    let start = offset
    if (start < 0) start = 0
    if (start >= this.byteLength) return 0

    let end = offset + length
    if (end <= start) return 0
    if (end > this.byteLength) end = this.byteLength

    let buffer = this

    if (start !== 0 || end !== this.byteLength) {
      buffer = buffer.subarray(start, end)
    }

    return codecFor(encoding).write(buffer, string)
  }

  readBigInt64BE(offset = 0) {
    return viewOf(this).getBigInt64(offset, false)
  }
  readBigInt64LE(offset = 0) {
    return viewOf(this).getBigInt64(offset, true)
  }

  readBigUint64BE(offset = 0) {
    return viewOf(this).getBigUint64(offset, false)
  }
  readBigUint64LE(offset = 0) {
    return viewOf(this).getBigUint64(offset, true)
  }

  readDoubleBE(offset = 0) {
    return viewOf(this).getFloat64(offset, false)
  }
  readDoubleLE(offset = 0) {
    return viewOf(this).getFloat64(offset, true)
  }

  readFloatBE(offset = 0) {
    return viewOf(this).getFloat32(offset, false)
  }
  readFloatLE(offset = 0) {
    return viewOf(this).getFloat32(offset, true)
  }

  readInt8(offset = 0) {
    return viewOf(this).getInt8(offset)
  }

  readInt16BE(offset = 0) {
    return viewOf(this).getInt16(offset, false)
  }
  readInt16LE(offset = 0) {
    return viewOf(this).getInt16(offset, true)
  }

  readInt32BE(offset = 0) {
    return viewOf(this).getInt32(offset, false)
  }
  readInt32LE(offset = 0) {
    return viewOf(this).getInt32(offset, true)
  }

  readIntBE(offset, byteLength) {
    if (byteLength === 6) return readInt48BE(viewOf(this), offset)
    if (byteLength === 5) return readInt40BE(viewOf(this), offset)
    if (byteLength === 3) return readInt24BE(viewOf(this), offset)
    if (byteLength === 4) return this.readInt32BE(offset)
    if (byteLength === 2) return this.readInt16BE(offset)
    if (byteLength === 1) return this.readInt8(offset)
    throw new RangeError(`Byte length must be between 1 and 6`)
  }

  readIntLE(offset, byteLength) {
    if (byteLength === 6) return readInt48LE(viewOf(this), offset)
    if (byteLength === 5) return readInt40LE(viewOf(this), offset)
    if (byteLength === 3) return readInt24LE(viewOf(this), offset)
    if (byteLength === 4) return this.readInt32LE(offset)
    if (byteLength === 2) return this.readInt16LE(offset)
    if (byteLength === 1) return this.readInt8(offset)
    throw new RangeError(`Byte length must be between 1 and 6`)
  }

  readUint8(offset = 0) {
    return viewOf(this).getUint8(offset)
  }

  readUint16BE(offset = 0) {
    return viewOf(this).getUint16(offset, false)
  }
  readUint16LE(offset = 0) {
    return viewOf(this).getUint16(offset, true)
  }

  readUint32BE(offset = 0) {
    return viewOf(this).getUint32(offset, false)
  }
  readUint32LE(offset = 0) {
    return viewOf(this).getUint32(offset, true)
  }

  readUintBE(offset, byteLength) {
    if (byteLength === 6) return readUint48BE(viewOf(this), offset)
    if (byteLength === 5) return readUint40BE(viewOf(this), offset)
    if (byteLength === 3) return readUint24BE(viewOf(this), offset)
    if (byteLength === 4) return this.readUint32BE(offset)
    if (byteLength === 2) return this.readUint16BE(offset)
    if (byteLength === 1) return this.readUint8(offset)
    throw new RangeError(`Byte length must be between 1 and 6`)
  }

  readUintLE(offset, byteLength) {
    if (byteLength === 6) return readUint48LE(viewOf(this), offset)
    if (byteLength === 5) return readUint40LE(viewOf(this), offset)
    if (byteLength === 3) return readUint24LE(viewOf(this), offset)
    if (byteLength === 4) return this.readUint32LE(offset)
    if (byteLength === 2) return this.readUint16LE(offset)
    if (byteLength === 1) return this.readUint8(offset)
    throw new RangeError(`Byte length must be between 1 and 6`)
  }

  readBigUInt64BE(...args) {
    return this.readBigUint64BE(...args)
  }
  readBigUInt64LE(...args) {
    return this.readBigUint64LE(...args)
  }

  readUInt8(...args) {
    return this.readUint8(...args)
  }

  readUInt16BE(...args) {
    return this.readUint16BE(...args)
  }
  readUInt16LE(...args) {
    return this.readUint16LE(...args)
  }

  readUInt32BE(...args) {
    return this.readUint32BE(...args)
  }
  readUInt32LE(...args) {
    return this.readUint32LE(...args)
  }

  readUIntBE(...args) {
    return this.readUintBE(...args)
  }
  readUIntLE(...args) {
    return this.readUintLE(...args)
  }

  writeBigInt64BE(value, offset = 0) {
    viewOf(this).setBigInt64(offset, value, false)
    return offset + 8
  }
  writeBigInt64LE(value, offset = 0) {
    viewOf(this).setBigInt64(offset, value, true)
    return offset + 8
  }

  writeBigUint64BE(value, offset = 0) {
    viewOf(this).setBigUint64(offset, value, false)
    return offset + 8
  }
  writeBigUint64LE(value, offset = 0) {
    viewOf(this).setBigUint64(offset, value, true)
    return offset + 8
  }

  writeDoubleBE(value, offset = 0) {
    viewOf(this).setFloat64(offset, value, false)
    return offset + 8
  }
  writeDoubleLE(value, offset = 0) {
    viewOf(this).setFloat64(offset, value, true)
    return offset + 8
  }

  writeFloatBE(value, offset = 0) {
    viewOf(this).setFloat32(offset, value, false)
    return offset + 4
  }
  writeFloatLE(value, offset = 0) {
    viewOf(this).setFloat32(offset, value, true)
    return offset + 4
  }

  writeInt8(value, offset = 0) {
    viewOf(this).setInt8(offset, value)
    return offset + 1
  }

  writeInt16BE(value, offset = 0) {
    viewOf(this).setInt16(offset, value, false)
    return offset + 2
  }
  writeInt16LE(value, offset = 0) {
    viewOf(this).setInt16(offset, value, true)
    return offset + 2
  }

  writeInt32BE(value, offset = 0) {
    viewOf(this).setInt32(offset, value, false)
    return offset + 4
  }
  writeInt32LE(value, offset = 0) {
    viewOf(this).setInt32(offset, value, true)
    return offset + 4
  }

  writeIntBE(value, offset, byteLength) {
    if (byteLength === 6) return writeInt48BE(value, viewOf(this), offset)
    if (byteLength === 5) return writeInt40BE(value, viewOf(this), offset)
    if (byteLength === 3) return writeInt24BE(value, viewOf(this), offset)
    if (byteLength === 4) return this.writeInt32BE(value, offset)
    if (byteLength === 2) return this.writeInt16BE(value, offset)
    if (byteLength === 1) return this.writeInt8(value, offset)
    throw new RangeError(`Byte length must be between 1 and 6`)
  }

  writeIntLE(value, offset, byteLength) {
    if (byteLength === 6) return writeInt48LE(value, viewOf(this), offset)
    if (byteLength === 5) return writeInt40LE(value, viewOf(this), offset)
    if (byteLength === 3) return writeInt24LE(value, viewOf(this), offset)
    if (byteLength === 4) return this.writeInt32LE(value, offset)
    if (byteLength === 2) return this.writeInt16LE(value, offset)
    if (byteLength === 1) return this.writeInt8(value, offset)
    throw new RangeError(`Byte length must be between 1 and 6`)
  }

  writeUint8(value, offset = 0) {
    viewOf(this).setUint8(offset, value, true)
    return offset + 1
  }

  writeUint16BE(value, offset = 0) {
    viewOf(this).setUint16(offset, value, false)
    return offset + 2
  }
  writeUint16LE(value, offset = 0) {
    viewOf(this).setUint16(offset, value, true)
    return offset + 2
  }

  writeUint32LE(value, offset = 0) {
    viewOf(this).setUint32(offset, value, true)
    return offset + 4
  }
  writeUint32BE(value, offset = 0) {
    viewOf(this).setUint32(offset, value, false)
    return offset + 4
  }

  writeUintBE(value, offset, byteLength) {
    if (byteLength === 6) return writeUint48BE(value, viewOf(this), offset)
    if (byteLength === 5) return writeUint40BE(value, viewOf(this), offset)
    if (byteLength === 3) return writeUint24BE(value, viewOf(this), offset)
    if (byteLength === 4) return this.writeUint32BE(value, offset)
    if (byteLength === 2) return this.writeUint16BE(value, offset)
    if (byteLength === 1) return this.writeUint8(value, offset)
    throw new RangeError(`Byte length must be between 1 and 6`)
  }

  writeUintLE(value, offset, byteLength) {
    if (byteLength === 6) return writeUint48LE(value, viewOf(this), offset)
    if (byteLength === 5) return writeUint40LE(value, viewOf(this), offset)
    if (byteLength === 3) return writeUint24LE(value, viewOf(this), offset)
    if (byteLength === 4) return this.writeUint32LE(value, offset)
    if (byteLength === 2) return this.writeUint16LE(value, offset)
    if (byteLength === 1) return this.writeUint8(value, offset)
    throw new RangeError(`Byte length must be between 1 and 6`)
  }

  writeBigUInt64BE(...args) {
    return this.writeBigUint64BE(...args)
  }
  writeBigUInt64LE(...args) {
    return this.writeBigUint64LE(...args)
  }

  writeUInt8(...args) {
    return this.writeUint8(...args)
  }

  writeUInt16BE(...args) {
    return this.writeUint16BE(...args)
  }
  writeUInt16LE(...args) {
    return this.writeUint16LE(...args)
  }

  writeUInt32BE(...args) {
    return this.writeUint32BE(...args)
  }
  writeUInt32LE(...args) {
    return this.writeUint32LE(...args)
  }

  writeUIntBE(...args) {
    return this.writeUintBE(...args)
  }
  writeUIntLE(...args) {
    return this.writeUintLE(...args)
  }
}

const Buffer = exports

exports.Buffer = Buffer // For Node.js compatibility

exports.constants = constants

const codecs = Object.create(null)

codecs.ascii = ascii
codecs.base64 = base64
codecs.base64url = base64url
codecs.hex = hex
codecs.utf8 = codecs['utf-8'] = utf8
codecs.utf16le = codecs.ucs2 = codecs['utf-16le'] = codecs['ucs-2'] = utf16le
codecs.latin1 = codecs.binary = latin1

function codecFor(encoding = 'utf8') {
  if (encoding in codecs) return codecs[encoding]

  encoding = encoding.toLowerCase()

  if (encoding in codecs) return codecs[encoding]

  throw new Error(`Unknown encoding '${encoding}'`)
}

const views = new WeakMap()

function viewOf(buffer) {
  let view = views.get(buffer)
  if (view === undefined) {
    view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength)
    views.set(buffer, view)
  }
  return view
}

exports.isBuffer = function isBuffer(value) {
  if (value instanceof Buffer) return true

  return typeof value === 'object' && value !== null && value[kind] === Buffer[kind]
}

exports.isEncoding = function isEncoding(encoding) {
  try {
    codecFor(encoding)
    return true
  } catch {
    return false
  }
}

exports.isASCII = function isASCII(buffer) {
  return ascii.validate(buffer)
}

// for Node.js compatibily
exports.isAscii = exports.isASCII

exports.isUTF8 = function isUTF8(buffer) {
  return utf8.validate(buffer)
}

// for Node.js compatibility
exports.isUtf8 = exports.isUTF8

exports.alloc = function alloc(size, fill, encoding) {
  const buffer = new Buffer(size)
  if (fill !== undefined) buffer.fill(fill, 0, buffer.byteLength, encoding)
  return buffer
}

exports.allocUnsafe = function allocUnsafe(size) {
  return new Buffer(size, { uninitialized: true })
}

exports.allocUnsafeSlow = function allocUnsafeSlow(size) {
  return exports.allocUnsafe(size)
}

exports.byteLength = function byteLength(string, encoding) {
  if (typeof string === 'string') {
    return codecFor(encoding).byteLength(string)
  }

  return string.byteLength
}

exports.compare = function compare(a, b) {
  return binding.compare(a.buffer, a.byteOffset, a.byteLength, b.buffer, b.byteOffset, b.byteLength)
}

exports.concat = function concat(buffers, length) {
  if (length === undefined) {
    length = buffers.reduce((length, buffer) => length + buffer.byteLength, 0)
  }

  const result = new Buffer(length)

  for (let i = 0, n = buffers.length, offset = 0; i < n; i++) {
    const buffer = buffers[i]

    if (offset + buffer.byteLength > result.byteLength) {
      result.set(buffer.subarray(0, result.byteLength - offset), offset)
      return result
    }

    result.set(buffer, offset)
    offset += buffer.byteLength
  }

  return result
}

exports.coerce = function coerce(buffer) {
  if (exports.isBuffer(buffer)) return buffer
  return new Buffer(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

exports.copyBytesFrom = function copyBytesFrom(view, offset = 0, length = view.length - offset) {
  if (offset + length > view.length) {
    throw new RangeError('View length is out of range')
  }

  if (offset !== 0 || length !== view.length) {
    view = view.subarray(offset, offset + length)
  }

  return new Buffer(view.buffer.slice(view.byteOffset, view.byteOffset + view.byteLength))
}

exports.from = function from(value, encodingOrOffset, length) {
  // from(string, encoding)
  if (typeof value === 'string') return fromString(value, encodingOrOffset)

  // from(array)
  if (Array.isArray(value)) return fromArray(value)

  // from(buffer)
  if (ArrayBuffer.isView(value)) return fromBuffer(value)

  // from(arrayBuffer[, offset[, length]])
  return fromArrayBuffer(value, encodingOrOffset, length)
}

function fromString(string, encoding) {
  const codec = codecFor(encoding)
  const buffer = new Buffer(codec.byteLength(string))
  codec.write(buffer, string)
  return buffer
}

function fromArray(array) {
  const buffer = new Buffer(array.length)
  buffer.set(array)
  return buffer
}

function fromBuffer(buffer) {
  const copy = new Buffer(buffer.byteLength)
  copy.set(buffer)
  return copy
}

function fromArrayBuffer(arrayBuffer, offset, length) {
  return new Buffer(arrayBuffer, offset, length)
}

function bidirectionalIndexOf(buffer, value, offset, encoding, first) {
  if (buffer.byteLength === 0) return -1

  if (typeof offset === 'string') {
    encoding = offset
    offset = 0
  } else if (offset === undefined) {
    offset = first ? 0 : buffer.byteLength - 1
  } else if (offset < 0) {
    offset += buffer.byteLength
  }

  if (offset >= buffer.byteLength) {
    if (first) return -1
    else offset = buffer.byteLength - 1
  } else if (offset < 0) {
    if (first) offset = 0
    else return -1
  }

  if (typeof value === 'string') value = exports.from(value, encoding)

  if (value.byteLength === 0) return -1

  if (first) {
    let foundIndex = -1

    for (let i = offset; i < buffer.byteLength; i++) {
      if (buffer[i] === value[foundIndex === -1 ? 0 : i - foundIndex]) {
        if (foundIndex === -1) foundIndex = i
        if (i - foundIndex + 1 === value.byteLength) return foundIndex
      } else {
        if (foundIndex !== -1) i -= i - foundIndex
        foundIndex = -1
      }
    }
  } else {
    if (offset + value.byteLength > buffer.byteLength) {
      offset = buffer.byteLength - value.byteLength
    }

    for (let i = offset; i >= 0; i--) {
      let found = true

      for (let j = 0; j < value.byteLength; j++) {
        if (buffer[i + j] !== value[j]) {
          found = false
          break
        }
      }

      if (found) return i
    }
  }

  return -1
}

function swap(buffer, n, m) {
  const i = buffer[n]
  buffer[n] = buffer[m]
  buffer[m] = i
}

exports.atob = function atob(data) {
  return Buffer.from(data, 'base64').toString('latin1')
}

exports.btoa = function btoa(data) {
  if (typeof data !== 'string') data = String(data)

  return Buffer.from(data, 'latin1').toString('base64')
}

exports.transcode = function transcode(buffer, from, to) {
  return Buffer.from(buffer.toString(from), to)
}

function readInt48BE(view, offset) {
  const hi = view.getUint16(offset, false)
  const lo = view.getUint32(offset + 2, false)
  let value = lo + hi * 0x100000000
  if (hi & 0x8000) value -= 0x1000000000000
  return value
}

function readInt48LE(view, offset) {
  const lo = view.getUint32(offset, true)
  const hi = view.getUint16(offset + 4, true)
  let value = lo + hi * 0x100000000
  if (hi & 0x8000) value -= 0x1000000000000
  return value
}

function readInt40BE(view, offset) {
  const hi = view.getUint8(offset)
  const lo = view.getUint32(offset + 1, false)
  let value = lo + hi * 0x100000000
  if (hi & 0x80) value -= 0x10000000000
  return value
}

function readInt40LE(view, offset) {
  const lo = view.getUint32(offset, true)
  const hi = view.getUint8(offset + 4)
  let value = lo + hi * 0x100000000
  if (hi & 0x80) value -= 0x10000000000
  return value
}

function readInt24BE(view, offset) {
  const value =
    (view.getUint8(offset) << 16) | (view.getUint8(offset + 1) << 8) | view.getUint8(offset + 2)
  return value & 0x800000 ? value - 0x1000000 : value
}

function readInt24LE(view, offset) {
  const value =
    view.getUint8(offset) | (view.getUint8(offset + 1) << 8) | (view.getUint8(offset + 2) << 16)
  return value & 0x800000 ? value - 0x1000000 : value
}

function readUint48BE(view, offset) {
  const hi = view.getUint16(offset, false)
  const lo = view.getUint32(offset + 2, false)
  return lo + hi * 0x100000000
}

function readUint48LE(view, offset) {
  const lo = view.getUint32(offset, true)
  const hi = view.getUint16(offset + 4, true)
  return lo + hi * 0x100000000
}

function readUint40BE(view, offset) {
  const hi = view.getUint8(offset)
  const lo = view.getUint32(offset + 1, false)
  return lo + hi * 0x100000000
}

function readUint40LE(view, offset) {
  const lo = view.getUint32(offset, true)
  const hi = view.getUint8(offset + 4)
  return lo + hi * 0x100000000
}

function readUint24BE(view, offset) {
  return (
    (view.getUint8(offset) << 16) | (view.getUint8(offset + 1) << 8) | view.getUint8(offset + 2)
  )
}

function readUint24LE(view, offset) {
  return (
    view.getUint8(offset) | (view.getUint8(offset + 1) << 8) | (view.getUint8(offset + 2) << 16)
  )
}

function writeInt48BE(value, view, offset) {
  if (value < 0) value += 0x1000000000000
  const hi = Math.floor(value / 0x100000000)
  const lo = value >>> 0
  view.setUint16(offset, hi, false)
  view.setUint32(offset + 2, lo, false)
  return offset + 6
}

function writeInt48LE(value, view, offset) {
  if (value < 0) value += 0x1000000000000
  const hi = Math.floor(value / 0x100000000)
  const lo = value >>> 0
  view.setUint32(offset, lo, true)
  view.setUint16(offset + 4, hi, true)
  return offset + 6
}

function writeInt40BE(value, view, offset) {
  if (value < 0) value += 0x10000000000
  const hi = Math.floor(value / 0x100000000)
  const lo = value >>> 0
  view.setUint8(offset, hi)
  view.setUint32(offset + 1, lo, false)
  return offset + 5
}

function writeInt40LE(value, view, offset) {
  if (value < 0) value += 0x10000000000
  const hi = Math.floor(value / 0x100000000)
  const lo = value >>> 0
  view.setUint32(offset, lo, true)
  view.setUint8(offset + 4, hi)
  return offset + 5
}

function writeInt24BE(value, view, offset) {
  if (value < 0) value += 0x1000000
  view.setUint8(offset, (value >> 16) & 0xff)
  view.setUint8(offset + 1, (value >> 8) & 0xff)
  view.setUint8(offset + 2, value & 0xff)
  return offset + 3
}

function writeInt24LE(value, view, offset) {
  if (value < 0) value += 0x1000000
  view.setUint8(offset, value & 0xff)
  view.setUint8(offset + 1, (value >> 8) & 0xff)
  view.setUint8(offset + 2, (value >> 16) & 0xff)
  return offset + 3
}

function writeUint48BE(value, view, offset) {
  const hi = Math.floor(value / 0x100000000)
  const lo = value >>> 0
  view.setUint16(offset, hi, false)
  view.setUint32(offset + 2, lo, false)
  return offset + 6
}

function writeUint48LE(value, view, offset) {
  const hi = Math.floor(value / 0x100000000)
  const lo = value >>> 0
  view.setUint32(offset, lo, true)
  view.setUint16(offset + 4, hi, true)
  return offset + 6
}

function writeUint40BE(value, view, offset) {
  const hi = Math.floor(value / 0x100000000)
  const lo = value >>> 0
  view.setUint8(offset, hi)
  view.setUint32(offset + 1, lo, false)
  return offset + 5
}

function writeUint40LE(value, view, offset) {
  const hi = Math.floor(value / 0x100000000)
  const lo = value >>> 0
  view.setUint32(offset, lo, true)
  view.setUint8(offset + 4, hi)
  return offset + 5
}

function writeUint24BE(value, view, offset) {
  view.setUint8(offset, (value >> 16) & 0xff)
  view.setUint8(offset + 1, (value >> 8) & 0xff)
  view.setUint8(offset + 2, value & 0xff)
  return offset + 3
}

function writeUint24LE(value, view, offset) {
  view.setUint8(offset, value & 0xff)
  view.setUint8(offset + 1, (value >> 8) & 0xff)
  view.setUint8(offset + 2, (value >> 16) & 0xff)
  return offset + 3
}
const binding = require('../binding')

exports.byteLength = function byteLength(string) {
  return string.length
}

exports.toString = function toString(buffer) {
  const len = buffer.byteLength

  let result = ''

  for (let i = 0; i < len; i++) {
    result += String.fromCharCode(buffer[i] & 0x7f)
  }

  return result
}

exports.write = function write(buffer, string) {
  const len = buffer.byteLength

  for (let i = 0; i < len; i++) {
    buffer[i] = string.charCodeAt(i)
  }

  return len
}

exports.validate = function validate(buffer) {
  return binding.validateAscii(buffer.buffer, buffer.byteLength)
}
const binding = require('../binding')

exports.byteLength = function byteLength(string) {
  let len = string.length

  if (string.charCodeAt(len - 1) === 0x3d) len--
  if (len > 1 && string.charCodeAt(len - 1) === 0x3d) len--

  return (len * 3) >>> 2
}

exports.toString = function toString(buffer) {
  return binding.toStringBase64(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

exports.write = function write(buffer, string) {
  return binding.writeBase64(buffer.buffer, buffer.byteOffset, buffer.byteLength, string)
}
const binding = require('../binding')

exports.byteLength = function byteLength(string) {
  let len = string.length

  if (string.charCodeAt(len - 1) === 0x3d) len--
  if (len > 1 && string.charCodeAt(len - 1) === 0x3d) len--

  return (len * 3) >>> 2
}

exports.toString = function toString(buffer) {
  return binding.toStringBase64URL(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

exports.write = function write(buffer, string) {
  return binding.writeBase64(buffer.buffer, buffer.byteOffset, buffer.byteLength, string)
}
const binding = require('../binding')

module.exports = binding.constants
const binding = require('../binding')

exports.byteLength = function byteLength(string) {
  return string.length >>> 1
}

exports.toString = function toString(buffer) {
  return binding.toStringHex(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

exports.write = function write(buffer, string) {
  return binding.writeHex(buffer.buffer, buffer.byteOffset, buffer.byteLength, string)
}
const binding = require('../binding')

exports.byteLength = function byteLength(string) {
  return string.length
}

exports.toString = function toString(buffer) {
  return binding.toStringLatin1(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

exports.write = function write(buffer, string) {
  return binding.writeLatin1(buffer.buffer, buffer.byteOffset, buffer.byteLength, string)
}
const binding = require('../binding')

exports.byteLength = function byteLength(string) {
  return string.length * 2
}

exports.toString = function toString(buffer) {
  return binding.toStringUTF16LE(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

exports.write = function write(buffer, string) {
  return binding.writeUTF16LE(buffer.buffer, buffer.byteOffset, buffer.byteLength, string)
}
const binding = require('../binding')

exports.byteLength = function byteLength(string) {
  return binding.byteLengthUTF8(string)
}

exports.toString = function toString(buffer) {
  return binding.toStringUTF8(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

exports.write = function write(buffer, string) {
  return binding.writeUTF8(buffer.buffer, buffer.byteOffset, buffer.byteLength, string)
}

exports.validate = function validate(buffer) {
  return binding.validateUTF8(buffer.buffer, buffer.byteLength)
}
{
  "name": "bare-buffer",
  "version": "3.6.1",
  "description": "Native buffers for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    },
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "global.js",
    "global.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-buffer.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-buffer/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-buffer#readme",
  "engines": {
    "bare": ">=1.20.0"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "cmake-bare": "^1.1.6",
    "cmake-fetch": "^1.0.0",
    "lunte": "^1.8.0",
    "prettier": "^3.3.3",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = require.addon()
const binding = require('./binding')

exports.Resolver = class DNSResolver {
  constructor() {
    this._handle = binding.initResolver()
  }

  resolveTxt(hostname, cb = noop) {
    binding.resolveTxt(this._handle, hostname, cb, this)
  }

  destroy() {
    binding.destroyResolver(this._handle)
    this._handle = null
  }

  static global = new this()
}

function onlookup(err, addresses) {
  const req = this

  if (err) return req.cb(err, null, 0)

  const { address, family } = addresses[0]

  return req.cb(null, address, family)
}

function onlookupall(err, addresses) {
  const req = this

  if (err) return req.cb(err, null)

  return req.cb(null, addresses)
}

exports.lookup = function lookup(hostname, opts = {}, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  let { family = 0, all = false } = opts

  if (typeof family === 'string') {
    switch (family) {
      case 'IPv4':
        family = 4
        break
      case 'IPv6':
        family = 6
        break
      default:
        family = 0
    }
  }

  const req = {
    cb,
    handle: null
  }

  req.handle = binding.lookup(
    hostname,
    family || 0,
    all,
    req,
    all ? onlookupall : onlookup
  )
}

exports.resolveTxt = function resolveTxt(hostname, cb) {
  exports.Resolver.global.resolveTxt(hostname, cb)
}

function noop() {}
{
  "name": "bare-dns",
  "version": "2.1.4",
  "description": "Domain name resolution for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-dns.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-dns/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-dns",
  "engines": {
    "bare": ">=1.7.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "cmake-bare": "^1.1.6",
    "cmake-fetch": "^1.3.0",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
const os = require('bare-os')

module.exports = new Proxy(Object.create(null), {
  ownKeys (target) {
    return os.getEnvKeys()
  },

  get (target, property) {
    if (typeof property !== 'string') return

    return os.getEnv(property)
  },

  has (target, property) {
    if (typeof property !== 'string') return false

    return os.hasEnv(property)
  },

  set (target, property, value) {
    if (typeof property !== 'string') return

    const type = typeof value

    if (type !== 'string' && type !== 'number' && type !== 'boolean') {
      throw new Error('Environment variable must be of type string, number, or boolean')
    }

    value = String(value)

    os.setEnv(property, value)

    return true
  },

  deleteProperty (target, property) {
    if (typeof property !== 'string') return

    os.unsetEnv(property)
  },

  getOwnPropertyDescriptor (target, property) {
    return {
      value: this.get(target, property),
      enumerable: true,
      configurable: true,
      writable: true
    }
  }
})
{
  "name": "bare-env",
  "version": "3.0.0",
  "description": "Environment variable support for JavaScript",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "scripts": {
    "test": "standard && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-env.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-env/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-env#readme",
  "dependencies": {
    "bare-os": "^3.0.1"
  },
  "devDependencies": {
    "brittle": "^3.2.1",
    "standard": "^17.0.0"
  }
}
const errors = require('./lib/errors')

class EventListener {
  constructor() {
    this.list = []
    this.count = 0
  }

  append(ctx, name, fn, once) {
    this.count++
    ctx.emit('newListener', name, fn) // Emit BEFORE adding
    this.list.push([fn, once])
  }

  prepend(ctx, name, fn, once) {
    this.count++
    ctx.emit('newListener', name, fn) // Emit BEFORE adding
    this.list.unshift([fn, once])
  }

  remove(ctx, name, fn) {
    for (let i = 0, n = this.list.length; i < n; i++) {
      const l = this.list[i]

      if (l[0] === fn) {
        this.list.splice(i, 1)

        if (this.count === 1) delete ctx._events[name]

        ctx.emit('removeListener', name, fn) // Emit AFTER removing

        this.count--
        return
      }
    }
  }

  removeAll(ctx, name) {
    const list = [...this.list]
    this.list = []

    if (this.count === list.length) delete ctx._events[name]

    for (let i = list.length - 1; i >= 0; i--) {
      ctx.emit('removeListener', name, list[i][0]) // Emit AFTER removing
    }

    this.count -= list.length
  }

  emit(ctx, name, ...args) {
    const list = [...this.list]

    for (let i = 0, n = list.length; i < n; i++) {
      const l = list[i]

      if (l[1] === true) this.remove(ctx, name, l[0])

      Reflect.apply(l[0], ctx, args)
    }

    return list.length > 0
  }
}

function appendListener(ctx, name, fn, once) {
  if (ctx._events === undefined) ctx._events = Object.create(null)
  const e = ctx._events[name] || (ctx._events[name] = new EventListener())
  e.append(ctx, name, fn, once)
  return ctx
}

function prependListener(ctx, name, fn, once) {
  if (ctx._events === undefined) ctx._events = Object.create(null)
  const e = ctx._events[name] || (ctx._events[name] = new EventListener())
  e.prepend(ctx, name, fn, once)
  return ctx
}

function removeListener(ctx, name, fn) {
  if (ctx._events === undefined) return ctx
  const e = ctx._events[name]
  if (e !== undefined) e.remove(ctx, name, fn)
  return ctx
}

function throwUnhandledError(...args) {
  let err

  if (args.length > 0) err = args[0]

  if (err instanceof Error === false) err = errors.UNHANDLED_ERROR(err)

  if (Error.captureStackTrace) {
    Error.captureStackTrace(err, exports.prototype.emit)
  }

  queueMicrotask(() => {
    throw err
  })
}

module.exports = exports = class EventEmitter {
  constructor() {
    this._events = Object.create(null)
  }

  addListener(name, fn) {
    return appendListener(this, name, fn, false)
  }

  addOnceListener(name, fn) {
    return appendListener(this, name, fn, true)
  }

  prependListener(name, fn) {
    return prependListener(this, name, fn, false)
  }

  prependOnceListener(name, fn) {
    return prependListener(this, name, fn, true)
  }

  removeListener(name, fn) {
    return removeListener(this, name, fn)
  }

  on(name, fn) {
    return appendListener(this, name, fn, false)
  }

  once(name, fn) {
    return appendListener(this, name, fn, true)
  }

  off(name, fn) {
    return removeListener(this, name, fn)
  }

  emit(name, ...args) {
    if (name === 'error' && this._events !== undefined && this._events.error === undefined) {
      throwUnhandledError(...args)
    }

    if (this._events === undefined) return false
    const e = this._events[name]
    return e === undefined ? false : e.emit(this, name, ...args)
  }

  listeners(name) {
    if (this._events === undefined) return []
    const e = this._events[name]
    return e === undefined ? [] : [...e.list]
  }

  rawListeners(name) {
    if (this._events === undefined) return []
    const e = this._events[name]
    return e === undefined ? [] : e.list.map((l) => l[0])
  }

  eventNames() {
    if (this._events === undefined) return []
    return Reflect.ownKeys(this._events)
  }

  listenerCount(name) {
    if (this._events === undefined) return 0
    const e = this._events[name]
    return e === undefined ? 0 : e.list.length
  }

  getMaxListeners() {
    return EventEmitter.defaultMaxListeners
  }

  setMaxListeners(n) {}

  removeAllListeners(name) {
    if (arguments.length === 0) {
      for (const key of Reflect.ownKeys(this._events)) {
        if (key === 'removeListener') continue
        this.removeAllListeners(key)
      }
      this.removeAllListeners('removeListener')
    } else {
      const e = this._events[name]
      if (e !== undefined) e.removeAll(this, name)
    }
    return this
  }
}

exports.EventEmitter = exports

exports.errors = errors

exports.defaultMaxListeners = 10

exports.on = function on(emitter, name, opts = {}) {
  const { signal } = opts

  if (signal && signal.aborted) {
    throw errors.OPERATION_ABORTED(signal.reason)
  }

  let error = null
  let done = false

  const events = []
  const promises = []

  if (name !== 'error') emitter.on('error', onerror)

  if (signal) signal.addEventListener('abort', onabort)

  emitter.on(name, onevent)

  return {
    next() {
      if (events.length) {
        return Promise.resolve({ value: events.shift(), done: false })
      }

      if (error) {
        const err = error

        error = null

        return Promise.reject(err)
      }

      if (done) return onclose()

      return new Promise((resolve, reject) => promises.push({ resolve, reject }))
    },

    return() {
      return onclose()
    },

    throw(err) {
      return onerror(err)
    },

    [Symbol.asyncIterator]() {
      return this
    }
  }

  function onevent(...args) {
    if (promises.length) {
      promises.shift().resolve({ value: args, done: false })
    } else {
      events.push(args)
    }
  }

  function onerror(err) {
    emitter.off(name, onevent).off('error', onerror)

    if (promises.length) {
      promises.shift().reject(err)
    } else {
      error = err
    }

    return Promise.resolve({ done: true })
  }

  function onabort() {
    signal.removeEventListener('abort', onabort)

    onerror(errors.OPERATION_ABORTED(signal.reason))
  }

  function onclose() {
    emitter.off(name, onevent)

    if (name !== 'error') emitter.off('error', onerror)

    if (signal) signal.removeEventListener('abort', onabort)

    done = true

    if (promises.length) promises.shift().resolve({ done: true })

    return Promise.resolve({ done: true })
  }
}

exports.once = function once(emitter, name, opts = {}) {
  const { signal } = opts

  if (signal && signal.aborted) {
    return Promise.reject(errors.OPERATION_ABORTED(signal.reason))
  }

  return new Promise((resolve, reject) => {
    if (name !== 'error') emitter.on('error', onerror)

    if (signal) signal.addEventListener('abort', onabort)

    emitter.once(name, onevent)

    function onevent(...args) {
      if (name !== 'error') emitter.off('error', onerror)

      if (signal) signal.removeEventListener('abort', onabort)

      resolve(args)
    }

    function onerror(err) {
      emitter.off(name, onevent)

      if (name !== 'error') emitter.off('error', onerror)

      reject(err)
    }

    function onabort() {
      signal.removeEventListener('abort', onabort)

      onerror(errors.OPERATION_ABORTED(signal.reason))
    }
  })
}

exports.forward = function forward(from, to, names, opts = {}) {
  if (typeof names === 'string') names = [names]

  const { emit = to.emit.bind(to) } = opts

  const listeners = names.map(
    (name) =>
      function onevent(...args) {
        emit(name, ...args)
      }
  )

  to.on('newListener', (name) => {
    const i = names.indexOf(name)

    if (i !== -1 && to.listenerCount(name) === 0) {
      from.on(name, listeners[i])
    }
  }).on('removeListener', (name) => {
    const i = names.indexOf(name)

    if (i !== -1 && to.listenerCount(name) === 0) {
      from.off(name, listeners[i])
    }
  })
}

exports.listenerCount = function listenerCount(emitter, name) {
  return emitter.listenerCount(name)
}

exports.getMaxListeners = function getMaxListeners(emitter) {
  if (typeof emitter.getMaxListeners === 'function') {
    return emitter.getMaxListeners()
  }

  return exports.defaultMaxListeners
}

exports.setMaxListeners = function setMaxListeners(n, ...emitters) {
  if (emitters.length === 0) exports.defaultMaxListeners = n
  else {
    for (const emitter of emitters) {
      if (typeof emitter.setMaxListeners === 'function') {
        emitter.setMaxListeners(n)
      }
    }
  }
}
module.exports = class EventEmitterError extends Error {
  constructor(msg, code, fn = EventEmitterError, opts) {
    super(`${code}: ${msg}`, opts)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'EventEmitterError'
  }

  static OPERATION_ABORTED(cause, msg = 'Operation aborted') {
    return new EventEmitterError(msg, 'OPERATION_ABORTED', EventEmitterError.OPERATION_ABORTED, {
      cause
    })
  }

  static UNHANDLED_ERROR(cause, msg = 'Unhandled error') {
    return new EventEmitterError(msg, 'UNHANDLED_ERROR', EventEmitterError.UNHANDLED_ERROR, {
      cause
    })
  }
}
{
  "name": "bare-events",
  "version": "2.9.1",
  "description": "Event emitters for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    },
    "./web": {
      "types": "./web.d.ts",
      "default": "./web.js"
    },
    "./errors": "./lib/errors.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "global.js",
    "global.d.ts",
    "web.js",
    "web.d.ts",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:bare && npm run test:node",
    "test:bare": "brittle-bare --coverage test.js",
    "test:node": "brittle-node --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-events.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-events/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-events#readme",
  "devDependencies": {
    "bare-abort-controller": "^1.0.0",
    "brittle": "^3.3.2",
    "lunte": "^1.8.0",
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^2.0.0",
    "uncaughts": "^1.1.1"
  },
  "peerDependencies": {
    "bare-abort-controller": "*"
  },
  "peerDependenciesMeta": {
    "bare-abort-controller": {
      "optional": true
    }
  }
}
const fetch = require('.')

global.fetch = fetch
global.Request = fetch.Request
global.Response = fetch.Response
global.Headers = fetch.Headers
const http = require('bare-http1')
const https = require('bare-https')
const { ReadableStream } = require('bare-stream/web')
const Request = require('./lib/request')
const Response = require('./lib/response')
const ResponseStream = require('./lib/response-stream')
const Headers = require('./lib/headers')
const errors = require('./lib/errors')

// https://fetch.spec.whatwg.org/#dom-global-fetch
module.exports = exports = function fetch(input, init = {}) {
  let resolve
  let reject

  const promise = new Promise((res, rej) => {
    resolve = res
    reject = rej
  })

  const response = new Response()

  process(input)

  return promise

  async function process(input, origin = null) {
    let request
    try {
      request = new Request(input, init)
    } catch (err) {
      return reject(err)
    }

    if (request.signal) {
      if (request.signal.aborted) return abort(reject, request, response)

      request.signal.addEventListener('abort', (event) => abort(reject, request, response))
    }

    if (response._urls.length > 20) {
      return reject(errors.TOO_MANY_REDIRECTS('Redirect count exceeded'))
    }

    if (origin && !isSameOrigin(request._url, origin)) {
      request.headers.delete('authorization')
    }

    let protocol

    if (request._url.protocol === 'http:') {
      protocol = http
    } else if (request._url.protocol === 'https:') {
      protocol = https
    } else {
      return reject(errors.UNKNOWN_PROTOCOL(`Unknown protocol '${request._url.protocol}'`))
    }

    response._urls.push(request._url)

    if (!request._headers.has('user-agent')) {
      request._headers.set('user-agent', `Bare/${Bare.version.substring(1)}`)
    }

    if (!request._headers.has('content-type') && request._type) {
      request._headers.set('content-type', request._type)
    }

    const agent = request._agent || protocol.globalAgent

    while (agent.suspended) await agent.resumed

    const req = protocol.request(
      request._url,
      {
        agent,
        method: request._method,
        headers: Object.fromEntries(request._headers)
      },
      (res) => {
        req.off('close', onclose)

        if (request.signal && request.signal.aborted) {
          res.resume()

          return abort(reject, request, response)
        }

        if (res.headers.location && isRedirectStatus(res.statusCode)) {
          res.resume()

          let url
          try {
            url = new URL(res.headers.location, request._url)
          } catch (err) {
            return reject(errors.INVALID_URL('Invalid URL', err))
          }

          return process(url, request._url)
        }

        response._body = new ReadableStream(new ResponseStream(res))
        response._status = res.statusCode
        response._statusText = res.statusMessage

        for (const [name, value] of Object.entries(res.headers)) {
          response._headers.set(name, value)
        }

        resolve(response)
      }
    )

    req.on('error', onerror).on('close', onclose)

    try {
      if (request._body) {
        for await (const data of request._body) req.write(data)
      }

      req.end()
    } catch (err) {
      req.destroy(err)
    }

    function onerror(err) {
      req.off('close', onclose)

      reject(errors.NETWORK_ERROR('Network error', err))
    }

    function onclose() {
      onerror(http.errors.CONNECTION_LOST())
    }
  }
}

exports.Request = Request
exports.Response = Response
exports.Headers = Headers

// https://fetch.spec.whatwg.org/#redirect-status
function isRedirectStatus(status) {
  return status === 301 || status === 302 || status === 303 || status === 307 || status === 308
}

// https://html.spec.whatwg.org/multipage/browsers.html#same-origin
function isSameOrigin(a, b) {
  return a.protocol === b.protocol && a.host === b.host
}

// https://fetch.spec.whatwg.org/#abort-fetch
function abort(reject, req, res) {
  const { reason } = req.signal

  if (req._body !== null) req._body.cancel(reason)
  if (res._body !== null) res._body.cancel(reason)

  reject(reason)
}
const { ReadableStream, isReadableStream, isReadableStreamDisturbed } = require('bare-stream/web')
const { isURLSearchParams } = require('bare-url')
const { FormData, File, isFormData, isBlob } = require('bare-form-data')
const Headers = require('./headers')
const errors = require('./errors')

const empty = Buffer.from(new ArrayBuffer(0))

// https://fetch.spec.whatwg.org/#body-mixin
module.exports = exports = class Body {
  constructor(body = null, type = null) {
    if (isReadableStream(body)) {
      if (isReadableStreamDisturbed(body) || body.locked) {
        throw errors.BODY_UNUSABLE('Body has already been consumed')
      }
    } else {
      if (typeof body === 'string') body = Buffer.from(body)
      else if (isFormData(body)) body = FormData.toBlob(body)
      else if (isURLSearchParams(body)) {
        body = body.toString()
        type = 'application/x-www-form-urlencoded;charset=UTF-8'
      }

      if (isBlob(body)) {
        type = body.type || null
        body = body.stream()
      } else if (body !== null) {
        if (ArrayBuffer.isView(body)) {
          body = Buffer.from(body.buffer, body.byteOffset, body.byteLength)
        } else {
          body = Buffer.from(body)
        }

        body = new ReadableStream({
          start(controller) {
            controller.enqueue(body)
            controller.close()
          }
        })
      }
    }

    this._type = type
    this._body = body
  }

  // https://fetch.spec.whatwg.org/#dom-body-body
  get body() {
    return this._body
  }

  // https://fetch.spec.whatwg.org/#dom-body-bodyused
  get bodyUsed() {
    return this._body !== null && isReadableStreamDisturbed(this._body)
  }

  async buffer() {
    if (this._body === null) return empty

    if (Body.isUnusable(this)) {
      throw errors.BODY_UNUSABLE('Body has already been consumed')
    }

    const chunks = []
    let length = 0

    for await (const chunk of this._body) {
      chunks.push(chunk)
      length += chunk.byteLength
    }

    const result = Buffer.from(new ArrayBuffer(length))
    let offset = 0

    for (const chunk of chunks) {
      result.set(chunk, offset)
      offset += chunk.byteLength
    }

    return result
  }

  // https://fetch.spec.whatwg.org/#dom-body-bytes
  async bytes() {
    return this.buffer()
  }

  // https://fetch.spec.whatwg.org/#dom-body-arraybuffer
  async arrayBuffer() {
    return (await this.buffer()).buffer
  }

  // https://fetch.spec.whatwg.org/#dom-body-text
  async text() {
    return (await this.buffer()).toString()
  }

  // https://fetch.spec.whatwg.org/#dom-body-json
  async json() {
    return JSON.parse(await this.text())
  }

  // https://fetch.spec.whatwg.org/#dom-body-formdata
  async formData() {
    const mimeType = getMIMEType(this)

    // 1.
    if (mimeType !== null && mimeType.type === 'multipart' && mimeType.subtype === 'form-data') {
      const body = await this.text()
      const boundary = mimeType.parameters.get('boundary')

      if (boundary === undefined) {
        throw errors.INVALID_FORM_DATA('Missing boundary parameter')
      }

      return parseMultipart(body, boundary)
    }

    // 2.
    if (
      mimeType !== null &&
      mimeType.type === 'application' &&
      mimeType.subtype === 'x-www-form-urlencoded'
    ) {
      const body = await this.text()
      const formData = new FormData()

      for (const [name, value] of new URLSearchParams(body)) {
        formData.append(name, value)
      }

      return formData
    }

    // 3.
    throw errors.INVALID_FORM_DATA('Could not parse content as form data')
  }
}

// https://fetch.spec.whatwg.org/#body-unusable
exports.isUnusable = function isUsable(body) {
  return body._body !== null && (isReadableStreamDisturbed(body._body) || body._body.locked)
}

// https://fetch.spec.whatwg.org/#concept-body-clone
exports.clone = function clone(body) {
  if (body._body === null) return null

  const [out1, out2] = body._body.tee()

  body._body = out1

  return out2
}

// https://fetch.spec.whatwg.org/#concept-body-mime-type
function getMIMEType(body) {
  const headers = body._headers

  if (headers === undefined) return null

  return Headers.extractMIMEType(headers)
}

// https://www.rfc-editor.org/rfc/rfc7578
// https://www.rfc-editor.org/rfc/rfc2046#section-5.1
function parseMultipart(input, boundary) {
  const formData = new FormData()

  const delimiter = `\r\n--${boundary}`
  const close = `\r\n--${boundary}--`

  let start = input.indexOf(`--${boundary}`)
  if (start === -1) return formData

  start += `--${boundary}`.length

  while (true) {
    if (input.startsWith('--', start)) break
    if (input.startsWith('\r\n', start)) start += 2

    let end = input.indexOf(delimiter, start)
    if (end === -1) end = input.indexOf(close, start)
    if (end === -1) break

    const part = input.slice(start, end)

    const headerEnd = part.indexOf('\r\n\r\n')
    if (headerEnd === -1) {
      start = end + delimiter.length
      continue
    }

    const headerSection = part.slice(0, headerEnd)
    const body = part.slice(headerEnd + 4)

    const contentDisposition = { name: null, filename: null }
    let contentType = null

    for (const line of headerSection.split('\r\n')) {
      const colon = line.indexOf(':')
      if (colon === -1) continue

      const name = line.slice(0, colon).trim().toLowerCase()
      const value = line.slice(colon + 1).trim()

      if (name === 'content-disposition') {
        contentDisposition.name = getParameter(value, 'name')
        contentDisposition.filename = getParameter(value, 'filename')
      } else if (name === 'content-type') {
        contentType = value
      }
    }

    if (contentDisposition.name === null) {
      start = end + delimiter.length
      continue
    }

    if (contentDisposition.filename !== null) {
      const file = new File([body], contentDisposition.filename, {
        type: contentType || 'application/octet-stream'
      })

      formData.append(contentDisposition.name, file)
    } else {
      formData.append(contentDisposition.name, body)
    }

    start = end + delimiter.length
  }

  return formData
}

function getParameter(header, name) {
  const pattern = new RegExp(`${name}="([^"]*)"|${name}=([^;\\s]*)`, 'i')

  const match = header.match(pattern)
  if (match === null) return null

  return match[1] !== undefined ? match[1] : match[2]
}
module.exports = class FetchError extends Error {
  constructor(msg, fn = FetchError, code = fn.name, opts = {}) {
    if (typeof code === 'object' && code !== null) {
      opts = code
      code = fn.name
    }

    super(`${code}: ${msg}`, opts)

    this.code = code

    if (Error.captureStackTrace) Error.captureStackTrace(this, fn)
  }

  get name() {
    return 'FetchError'
  }

  static INVALID_URL(msg, cause) {
    return new FetchError(msg, FetchError.INVALID_URL, { cause })
  }

  static NETWORK_ERROR(msg, cause) {
    return new FetchError(msg, FetchError.NETWORK_ERROR, { cause })
  }

  static TOO_MANY_REDIRECTS(msg) {
    return new FetchError(msg, FetchError.TOO_MANY_REDIRECTS)
  }

  static UNKNOWN_PROTOCOL(msg) {
    return new FetchError(msg, FetchError.UNKNOWN_PROTOCOL)
  }

  static BODY_UNUSABLE(msg) {
    return new FetchError(msg, FetchError.BODY_UNUSABLE)
  }

  static INVALID_FORM_DATA(msg) {
    return new FetchError(msg, FetchError.INVALID_FORM_DATA)
  }

  static INVALID_HEADER_NAME(msg) {
    return new FetchError(msg, FetchError.INVALID_HEADER_NAME)
  }

  static INVALID_HEADER_VALUE(msg) {
    return new FetchError(msg, FetchError.INVALID_HEADER_VALUE)
  }
}
const MIME = require('bare-mime')

const errors = require('./errors')

const NUL = 0x00
const LF = 0x0a
const CR = 0x0d

// https://www.rfc-editor.org/rfc/rfc9110.html#section-5.6.2
const TOKEN_BYTES = Buffer.from([
  // 0x00-0x1f (control characters) + 0x20 (space)
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  // 0x21-0x41: ! " # $ % & ' ( ) * + , - . / 0-9 : ; < = > ? @ A
  1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1,
  // 0x42-0x62: B-Z [ \ ] ^ _ ` a b
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1,
  // 0x63-0x7f: c-z { | } ~ DEL
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0
])

function isTokenByte(b) {
  return b < TOKEN_BYTES.length && TOKEN_BYTES[b] === 1
}

function isFieldByte(b) {
  return b !== NUL && b !== LF && b !== CR
}

// https://fetch.spec.whatwg.org/#header-name
function validateName(name) {
  if (name.length === 0) {
    throw errors.INVALID_HEADER_NAME(`Header name must not be empty`)
  }

  for (let i = 0, n = name.length; i < n; i++) {
    if (!isTokenByte(name.charCodeAt(i))) {
      throw errors.INVALID_HEADER_NAME(`Invalid header name '${name}'`)
    }
  }
}

// https://fetch.spec.whatwg.org/#header-value
function validateValue(name, value) {
  for (let i = 0, n = value.length; i < n; i++) {
    if (!isFieldByte(value.charCodeAt(i))) {
      throw errors.INVALID_HEADER_VALUE(`Invalid header value for '${name}'`)
    }
  }
}

// https://fetch.spec.whatwg.org/#headers-class
module.exports = exports = class Headers {
  // https://fetch.spec.whatwg.org/#dom-headers
  constructor(init) {
    this._headers = new Map()

    if (init) {
      for (const [key, value] of typeof init[Symbol.iterator] === 'function'
        ? init
        : Object.entries(init)) {
        this.append(key, value)
      }
    }
  }

  // https://fetch.spec.whatwg.org/#dom-headers-append
  append(name, value) {
    value = value.trim()

    validateName(name)
    validateValue(name, value)

    name = name.toLowerCase()

    let list = this._headers.get(name)

    if (list === undefined) {
      list = []
      this._headers.set(name, list)
    }

    list.push(value)
  }

  // https://fetch.spec.whatwg.org/#dom-headers-delete
  delete(name) {
    name = name.toLowerCase()

    this._headers.delete(name)
  }

  // https://fetch.spec.whatwg.org/#dom-headers-get
  get(name) {
    name = name.toLowerCase()

    const list = this._headers.get(name)

    if (list === undefined) return null

    return list.join(', ')
  }

  // https://fetch.spec.whatwg.org/#dom-headers-has
  has(name) {
    name = name.toLowerCase()

    return this._headers.has(name)
  }

  // https://fetch.spec.whatwg.org/#dom-headers-set
  set(name, value) {
    value = value.trim()

    validateName(name)
    validateValue(name, value)

    name = name.toLowerCase()

    this._headers.set(name, [value])
  }

  // https://webidl.spec.whatwg.org/#idl-iterable
  entries() {
    return this[Symbol.iterator]()
  }

  // https://webidl.spec.whatwg.org/#idl-iterable
  *keys() {
    for (const [name] of this) {
      yield name
    }
  }

  // https://webidl.spec.whatwg.org/#idl-iterable
  *values() {
    for (const [, value] of this) {
      yield value
    }
  }

  // https://webidl.spec.whatwg.org/#idl-iterable
  forEach(callback, thisArg) {
    for (const [name, value] of this) {
      callback.call(thisArg, value, name, this)
    }
  }

  *[Symbol.iterator]() {
    const names = [...this._headers.keys()].sort()

    for (const name of names) {
      yield [name, this.get(name)]
    }
  }
}

// https://fetch.spec.whatwg.org/#concept-header-extract-mime-type
exports.extractMIMEType = function extractMIMEType(headers) {
  // 1.
  const contentType = headers.get('content-type')

  // 2.
  if (contentType === null) return null

  // 3.
  const values = getDecodeSplit(contentType)

  // 4.
  let mimeType = null

  // 5.
  for (const value of values) {
    const parsed = MIME.parse(value)

    if (parsed !== null) {
      mimeType = parsed
    }
  }

  // 6.
  return mimeType
}

// https://fetch.spec.whatwg.org/#concept-header-list-get-decode-split
function getDecodeSplit(value) {
  const values = []
  let current = ''
  let position = 0

  while (position < value.length) {
    if (value[position] === '"') {
      current += value[position++]

      while (position < value.length) {
        if (value[position] === '\\' && position + 1 < value.length) {
          current += value[position++]
          current += value[position++]
        } else if (value[position] === '"') {
          current += value[position++]
          break
        } else {
          current += value[position++]
        }
      }
    } else if (value[position] === ',') {
      values.push(current.trim())
      current = ''
      position++
    } else {
      current += value[position++]
    }
  }

  values.push(current.trim())

  return values
}
const { isURL } = require('bare-url')
const Body = require('./body')
const Headers = require('./headers')
const errors = require('./errors')

// https://fetch.spec.whatwg.org/#request-class
module.exports = class Request extends Body {
  // https://fetch.spec.whatwg.org/#dom-request
  constructor(input, init = {}) {
    let url
    try {
      if (isURL(input)) {
        url = input
        input = {}
      } else if (typeof input === 'string') {
        url = new URL(input)
        input = {}
      } else {
        url = new URL(input.url)
      }
    } catch (err) {
      throw errors.INVALID_URL('Invalid URL', err)
    }

    const {
      body = input.body || null,
      method = input.method || 'GET',
      headers = input.headers,
      signal = null,
      agent = input.agent || null
    } = init

    super(body)

    this._url = url
    this._method = /^(delete|get|head|options|post|put)$/i.test(method)
      ? method.toUpperCase()
      : method
    this._headers = new Headers(headers)
    this._signal = signal
    this._agent = agent
  }

  // https://fetch.spec.whatwg.org/#dom-request-url
  get url() {
    return this._url.href
  }

  // https://fetch.spec.whatwg.org/#dom-request-method
  get method() {
    return this._method
  }

  // https://fetch.spec.whatwg.org/#dom-request-headers
  get headers() {
    return this._headers
  }

  // https://fetch.spec.whatwg.org/#dom-request-signal
  get signal() {
    return this._signal
  }

  // https://fetch.spec.whatwg.org/#dom-request-clone
  clone() {
    if (Body.isUnusable(this)) throw errors.BODY_UNUSABLE('Body has already been consumed')

    return new Request(this, { body: Body.clone(this) })
  }
}
const { Readable } = require('bare-stream')
const { Gunzip, Deflate } = require('bare-zlib')

module.exports = class ResponseStream extends Readable {
  constructor(response) {
    super()

    this._response = response
    this._response.socket.unref()

    const encoding = response.headers['content-encoding']

    switch (encoding) {
      case 'gzip':
        this._decoder = new Gunzip()
        break
      case 'deflate':
        this._decoder = new Deflate()
        break
      default:
        this._decoder = null
    }
  }

  _open(cb) {
    if (this._response.socket) this._response.socket.ref()

    const stream = this._decoder ? this._response.pipe(this._decoder) : this._response

    stream
      .on('data', this._ondata.bind(this))
      .on('end', this._onend.bind(this))
      .on('error', this._onerror.bind(this))

    cb(null)
  }

  _read() {
    this._response.resume()
  }

  _predestroy() {
    this._response.destroy()
  }

  _ondata(data) {
    if (this.push(data) === false) {
      this._response.pause()
    }
  }

  _onend() {
    this.push(null)
  }

  _onerror(err) {
    this.destroy(err)
  }
}
const Body = require('./body')
const Headers = require('./headers')
const errors = require('./errors')

// https://fetch.spec.whatwg.org/#response-class
module.exports = class Response extends Body {
  // https://fetch.spec.whatwg.org/#dom-response
  constructor(body = null, init = {}) {
    const { status = 200, statusText = '', headers } = init

    super(body)

    this._urls = []
    this._status = status
    this._statusText = statusText
    this._headers = new Headers(headers)
  }

  // https://fetch.spec.whatwg.org/#dom-response-url
  get url() {
    return this._urls.length === 0 ? null : this._urls[this._urls.length - 1].href
  }

  // https://fetch.spec.whatwg.org/#dom-response-redirected
  get redirected() {
    return this._urls.length > 1
  }

  // https://fetch.spec.whatwg.org/#dom-response-status
  get status() {
    return this._status
  }

  // https://fetch.spec.whatwg.org/#dom-response-ok
  get ok() {
    return this._status >= 200 && this._status <= 299
  }

  // https://fetch.spec.whatwg.org/#dom-response-statustext
  get statusText() {
    return this._statusText
  }

  // https://fetch.spec.whatwg.org/#dom-response-headers
  get headers() {
    return this._headers
  }

  // https://fetch.spec.whatwg.org/#dom-response-clone
  clone() {
    if (Body.isUnusable(this)) throw errors.BODY_UNUSABLE('Body has already been consumed')

    return new Response(Body.clone(this), this)
  }
}
{
  "name": "bare-fetch",
  "version": "3.0.1",
  "description": "WHATWG Fetch implementation for Bare",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    },
    "./errors": {
      "types": "./lib/errors.d.ts",
      "default": "./lib/errors.js"
    },
    "./body": {
      "types": "./lib/body.d.ts",
      "default": "./lib/body.js"
    },
    "./request": {
      "types": "./lib/request.d.ts",
      "default": "./lib/request.js"
    },
    "./response": {
      "types": "./lib/response.d.ts",
      "default": "./lib/response.js"
    },
    "./headers": {
      "types": "./lib/headers.d.ts",
      "default": "./lib/headers.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "global.js",
    "global.d.ts",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-fetch.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-fetch/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-fetch#readme",
  "dependencies": {
    "bare-form-data": "^1.2.0",
    "bare-http1": "^4.5.2",
    "bare-https": "^3.0.0",
    "bare-mime": "^1.0.0",
    "bare-stream": "^2.9.1",
    "bare-url": "^2.4.0",
    "bare-zlib": "^1.3.0"
  },
  "devDependencies": {
    "bare-abort-controller": "^1.0.1",
    "bare-buffer": "^3.0.2",
    "brittle": "^3.3.0",
    "listen-async": "^1.0.0",
    "lunte": "^1.6.0",
    "prettier": "^3.3.3",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "bare-abort-controller": "*",
    "bare-buffer": "*"
  },
  "peerDependenciesMeta": {
    "bare-abort-controller": {
      "optional": true
    },
    "bare-buffer": {
      "optional": true
    }
  }
}
const { ReadableStream } = require('bare-stream/web')
const { isBuffer } = require('bare-buffer')
const errors = require('./lib/errors')

class FormData {
  constructor() {
    this._entries = []
  }

  append(name, value, filename) {
    if (typeof value !== 'string') {
      if (!isFile(value) || filename) {
        value = new File([value], filename || 'blob', { type: value.type })
      }
    }

    this._entries.push([name, value])
  }

  delete(name) {
    this._entries = this._entries.filter((entry) => entry[0] !== name)
  }

  get(name) {
    const entry = this._entries.find((entry) => entry[0] === name)

    return entry ? entry[1] : null
  }

  getAll(name) {
    const entries = []

    for (const entry of this._entries) {
      if (entry[0] === name) entries.push(entry[1])
    }

    return entries
  }

  has(name) {
    return this._entries.findIndex((entry) => entry[0] === name) !== -1
  }

  set(name, value, filename) {
    this.delete(name)
    this.append(name, value, filename)
  }

  [Symbol.iterator]() {
    return this._entries[Symbol.iterator]()
  }

  [Symbol.for('bare.inspect')]() {
    return {
      __proto__: { constructor: FormData },

      entries: this._entries
    }
  }
}

module.exports = exports = FormData

exports.FormData = FormData

function isFormData(value) {
  return value instanceof FormData
}

exports.isFormData = isFormData

class Blob {
  // https://w3c.github.io/FileAPI/#dom-blob-blob
  constructor(parts, options = {}) {
    const { type = '' } = options

    this._bytes = processBlobParts(parts)
    this._type = type
  }

  // https://w3c.github.io/FileAPI/#dfn-size
  get size() {
    return this._bytes.byteLength
  }

  // https://w3c.github.io/FileAPI/#dfn-type
  get type() {
    return this._type
  }

  // https://w3c.github.io/FileAPI/#stream-method-algo
  stream() {
    const bytes = this._bytes

    return new ReadableStream({
      start(controller) {
        controller.enqueue(bytes)
        controller.close()
      }
    })
  }

  async buffer() {
    return Buffer.from(this._bytes)
  }

  // https://w3c.github.io/FileAPI/#bytes-method-algo
  async bytes() {
    return this.buffer()
  }

  // https://w3c.github.io/FileAPI/#arraybuffer-method-algo
  async arrayBuffer() {
    const buffer = new ArrayBuffer(this._bytes.byteLength)
    new Uint8Array(buffer).set(this._bytes)
    return buffer
  }

  // https://w3c.github.io/FileAPI/#text-method-algo
  async text() {
    return this._bytes.toString()
  }

  [Symbol.for('bare.inspect')]() {
    return {
      __proto__: { constructor: Blob },

      size: this.size,
      type: this.type
    }
  }
}

exports.Blob = Blob

function isBlob(value) {
  return value instanceof Blob
}

exports.isBlob = Blob.isBlob = isBlob

class File extends Blob {
  // https://w3c.github.io/FileAPI/#dom-file-file
  constructor(parts, name, options = {}) {
    const { lastModified = Date.now() } = options

    super(parts, options)

    this._name = name
    this._lastModified = lastModified
  }

  // https://w3c.github.io/FileAPI/#dfn-name
  get name() {
    return this._name
  }

  // https://w3c.github.io/FileAPI/#dfn-lastModified
  get lastModified() {
    return this._lastModified
  }

  [Symbol.for('bare.inspect')]() {
    return {
      __proto__: { constructor: File },

      size: this.size,
      type: this.type,
      name: this.name,
      lastModified: this.lastModified
    }
  }
}

exports.File = File

function isFile(value) {
  return value instanceof File
}

exports.isFile = File.isFile = isFile

// https://w3c.github.io/FileAPI/#process-blob-parts
function processBlobParts(parts) {
  const chunks = []

  for (const part of parts) {
    if (typeof part === 'string') {
      const buffer = Buffer.from(part)
      if (parts.length === 1) return buffer
      chunks.push(buffer)
    } else if (isBlob(part)) {
      chunks.push(part._bytes)
    } else if (isBuffer(part)) {
      chunks.push(part)
    } else if (ArrayBuffer.isView(part)) {
      chunks.push(Buffer.from(part.buffer, part.byteOffset, part.byteLength))
    } else {
      chunks.push(Buffer.from(part))
    }
  }

  return Buffer.concat(chunks)
}

function toBlob(formData, mimeType = 'multipart/form-data') {
  switch (mimeType) {
    case 'multipart/form-data':
      return toMultipartBlob(formData)
    default:
      throw errors.INVALID_MIME_TYPE(`Invalid MIME type '${mimeType}'`)
  }
}

exports.toBlob = toBlob

function escape(value) {
  return value.replace(/\n/g, '%0A').replace(/\r/g, '%0D').replace(/"/g, '%22')
}

function normalizeLinefeeds(value) {
  return value.replace(/\r?\n|\r/g, '\r\n')
}

const linefeed = Buffer.from('\r\n')

// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#multipart/form-data-encoding-algorithm
function toMultipartBlob(formData) {
  const boundary = Math.random().toString(16).slice(2, 18).padStart(16, '0')

  const prefix = `--${boundary}\r\nContent-Disposition: form-data`

  const parts = []

  for (const [name, value] of formData) {
    if (typeof value === 'string') {
      const chunk = Buffer.from(
        prefix +
          `; name="${escape(normalizeLinefeeds(name))}"` +
          `\r\n\r\n${normalizeLinefeeds(value)}\r\n`
      )

      parts.push(chunk)
    } else {
      const chunk = Buffer.from(
        prefix +
          `; name="${escape(normalizeLinefeeds(name))}"` +
          `; filename="${escape(value.name)}"` +
          `\r\nContent-Type: ${value.type || 'application/octet-stream'}\r\n\r\n`
      )

      parts.push(chunk, value, linefeed)
    }
  }

  parts.push(Buffer.from(`--${boundary}--\r\n`))

  return new Blob(parts, {
    type: 'multipart/form-data; boundary=' + boundary
  })
}
module.exports = class FormDataError extends Error {
  constructor(msg, code, fn = FormDataError) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'FormDataError'
  }

  static INVALID_MIME_TYPE(msg) {
    return new FormDataError(msg, 'INVALID_MIME_TYPE', FormDataError.INVALID_MIME_TYPE)
  }
}
{
  "name": "bare-form-data",
  "version": "1.2.2",
  "description": "Form data support for Bare",
  "exports": {
    "./package": "./package.json",
    ".": "./index.js",
    "./global": "./global.js",
    "./errors": "./lib/errors.js"
  },
  "files": [
    "index.js",
    "global.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-form-data.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-form-data/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-form-data#readme",
  "dependencies": {
    "bare-buffer": "^3.6.0",
    "bare-stream": "^2.6.5"
  },
  "devDependencies": {
    "brittle": "^3.3.0",
    "lunte": "^1.7.0",
    "prettier": "^3.3.3",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = require.addon()
const FIFO = require('fast-fifo')
const EventEmitter = require('bare-events')
const path = require('bare-path')
const { isURL, fileURLToPath } = require('bare-url')
const { Readable, Writable } = require('bare-stream')
const binding = require('./binding')
const constants = require('./lib/constants')
const FileError = require('./lib/errors')

const isWindows = Bare.platform === 'win32'

exports.constants = constants

class FileRequest {
  static borrow() {
    if (this._free.length > 0) return this._free.pop()
    return new FileRequest()
  }

  static return(req) {
    if (this._free.length < 32) this._free.push(req.reset())
    else req.destroy()
  }

  constructor() {
    this._reset()
    this._handle = binding.requestInit(this, this._onresult)
  }

  get handle() {
    return this._handle
  }

  retain(value) {
    this._retain = value // Tie the lifetime of `value` to the lifetime of `this`
  }

  reset() {
    if (this._handle === null) return this

    binding.requestReset(this._handle)

    this._reset()

    return this
  }

  destroy() {
    if (this._handle === null) return this

    binding.requestDestroy(this._handle)

    this._reset()
    this._handle = null

    return this
  }

  then(resolve, reject) {
    return this._promise.then(resolve, reject)
  }

  return() {
    if (this._handle === null) return this

    FileRequest.return(this)

    return this
  }

  _reset() {
    this._promise = new Promise((resolve, reject) => {
      this._resolve = resolve
      this._reject = reject
    })
    this._retain = null
  }

  _onresult(err, status) {
    if (err) this._reject(err)
    else this._resolve(status)
  }
}

FileRequest._free = []

function ok(result, cb) {
  if (typeof result === 'function') {
    cb = result
    result = undefined
  }

  if (cb) cb(null, result)
  else return result
}

function fail(err, cb) {
  if (cb) cb(err)
  else throw err
}

function done(err, result, cb) {
  if (typeof result === 'function') {
    cb = result
    result = undefined
  }

  if (err) fail(err, cb)
  else return ok(result, cb)
}

async function open(filepath, flags = 'r', mode = 0o666, cb) {
  if (typeof flags === 'function') {
    cb = flags
    flags = 'r'
    mode = 0o666
  } else if (typeof mode === 'function') {
    cb = mode
    mode = 0o666
  }

  if (typeof flags === 'string') flags = toFlags(flags)
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let fd
  let err = null
  try {
    binding.open(req.handle, filepath, flags, mode)

    fd = await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'open',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, fd, cb)
}

function openSync(filepath, flags = 'r', mode = 0o666) {
  if (typeof flags === 'string') flags = toFlags(flags)
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    return binding.openSync(req.handle, filepath, flags, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'open',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function close(fd, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.close(req.handle, fd)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'close', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function closeSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.closeSync(req.handle, fd)
  } catch (e) {
    throw new FileError(e.message, { operation: 'close', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function access(filepath, mode = constants.F_OK, cb) {
  if (typeof mode === 'function') {
    cb = mode
    mode = constants.F_OK
  }

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.access(req.handle, filepath, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'access',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function accessSync(filepath, mode = constants.F_OK) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.accessSync(req.handle, filepath, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'access',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function exists(filepath, cb) {
  let ok = true
  try {
    await access(filepath)
  } catch {
    ok = false
  }

  return done(null, ok, cb)
}

function existsSync(filepath) {
  try {
    accessSync(filepath)
  } catch {
    return false
  }

  return true
}

async function read(fd, buffer, offset = 0, len = buffer.byteLength - offset, pos = -1, cb) {
  if (typeof offset === 'function') {
    cb = offset
    offset = 0
    len = buffer.byteLength
    pos = -1
  } else if (typeof len === 'function') {
    cb = len
    len = buffer.byteLength - offset
    pos = -1
  } else if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.read(req.handle, fd, buffer, offset, len, pos)

    req.retain(buffer)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'read', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function readSync(fd, buffer, offset = 0, len = buffer.byteLength - offset, pos = -1) {
  const req = FileRequest.borrow()

  try {
    return binding.readSync(req.handle, fd, buffer, offset, len, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'read', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function readv(fd, buffers, pos = -1, cb) {
  if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.readv(req.handle, fd, buffers, pos)

    req.retain(buffers)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'readv', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function readvSync(fd, buffers, pos = -1) {
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  try {
    return binding.readvSync(req.handle, fd, buffers, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'readv', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function write(fd, data, offset, len, pos = -1, cb) {
  if (typeof data === 'string') {
    let encoding = len
    cb = pos
    pos = offset

    if (typeof pos === 'function') {
      cb = pos
      pos = -1
      encoding = 'utf8'
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = 'utf8'
    }

    if (typeof pos === 'string') {
      encoding = pos
      pos = -1
    }

    data = Buffer.from(data, encoding)
    offset = 0
    len = data.byteLength
  } else if (typeof offset === 'function') {
    cb = offset
    offset = 0
    len = data.byteLength
    pos = -1
  } else if (typeof len === 'function') {
    cb = len
    len = data.byteLength - offset
    pos = -1
  } else if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof offset !== 'number') offset = 0
  if (typeof len !== 'number') len = data.byteLength - offset
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.write(req.handle, fd, data, offset, len, pos)

    req.retain(data)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'write', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function writeSync(fd, data, offset, len, pos = -1) {
  if (typeof data === 'string') {
    let encoding = len
    pos = offset

    if (typeof pos === 'string') {
      encoding = pos
      pos = -1
    }

    data = Buffer.from(data, encoding)
    offset = 0
    len = data.byteLength
  }

  if (typeof offset !== 'number') offset = 0
  if (typeof len !== 'number') len = data.byteLength - offset
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  try {
    return binding.writeSync(req.handle, fd, data, offset, len, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'write', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function writev(fd, buffers, pos = -1, cb) {
  if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.writev(req.handle, fd, buffers, pos)

    req.retain(buffers)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'writev', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function writevSync(fd, buffers, pos = -1) {
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  try {
    return binding.writevSync(req.handle, fd, buffers, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'writev', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function stat(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.stat(req.handle, filepath)

    await req

    st = new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'stat', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function statSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.statSync(req.handle, filepath)

    return new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'stat', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function lstat(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.lstat(req.handle, filepath)

    await req

    st = new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'lstat', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function lstatSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.lstatSync(req.handle, filepath)

    return new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'lstat', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function fstat(fd, cb) {
  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.fstat(req.handle, fd)

    await req

    st = new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'fstat', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function fstatSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.fstatSync(req.handle, fd)

    return new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'fstat', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function statfs(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.statfs(req.handle, filepath)

    await req

    st = new StatFs(...binding.requestResultStatfs(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'statfs', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function statfsSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.statfsSync(req.handle, filepath)

    return new StatFs(...binding.requestResultStatfs(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'statfs', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function ftruncate(fd, len = 0, cb) {
  if (typeof len === 'function') {
    cb = len
    len = 0
  }

  if (typeof len !== 'number') len = 0

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.ftruncate(req.handle, fd, len)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'ftruncate', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function ftruncateSync(fd, len = 0) {
  if (typeof len !== 'number') len = 0

  const req = FileRequest.borrow()

  try {
    binding.ftruncateSync(req.handle, fd, len)
  } catch (e) {
    throw new FileError(e.message, { operation: 'ftruncate', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function truncate(filepath, len, cb) {
  let fd = -1
  let err

  try {
    fd = await open(filepath, 'r+')

    await ftruncate(fd, len)
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) await close(fd)
  }

  return done(err, cb)
}

function truncateSync(filepath, len) {
  let fd = -1
  let err

  try {
    fd = openSync(filepath, 'r+')

    ftruncateSync(fd, len)
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) closeSync(fd)
  }
}

async function chmod(filepath, mode, cb) {
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.chmod(req.handle, filepath, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'chmod',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function chmodSync(filepath, mode) {
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.chmodSync(req.handle, filepath, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'chmod',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function fchmod(fd, mode, cb) {
  if (typeof mode === 'string') mode = toMode(mode)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fchmod(req.handle, fd, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fchmod', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fchmodSync(fd, mode) {
  if (typeof mode === 'string') mode = toMode(mode)

  const req = FileRequest.borrow()

  try {
    binding.fchmodSync(req.handle, fd, mode)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fchmod', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function chown(filepath, uid, gid, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.chown(req.handle, filepath, uid, gid)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'chown', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function chownSync(filepath, uid, gid) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.chownSync(req.handle, filepath, uid, gid)
  } catch (e) {
    throw new FileError(e.message, { operation: 'chownSync', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function lchown(filepath, uid, gid, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.lchown(req.handle, filepath, uid, gid)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'lchown', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function lchownSync(filepath, uid, gid) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.lchownSync(req.handle, filepath, uid, gid)
  } catch (e) {
    throw new FileError(e.message, { operation: 'lchownSync', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function fchown(fd, uid, gid, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fchown(req.handle, fd, uid, gid)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fchown', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fchownSync(fd, uid, gid) {
  const req = FileRequest.borrow()

  try {
    binding.fchownSync(req.handle, fd, uid, gid)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fchownSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function utimes(filepath, atime, mtime, cb) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.utimes(req.handle, filepath, atime, mtime)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'utimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function utimesSync(filepath, atime, mtime) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.utimesSync(req.handle, filepath, atime, mtime)
  } catch (e) {
    throw new FileError(e.message, { operation: 'utimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function lutimes(filepath, atime, mtime, cb) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.lutimes(req.handle, filepath, atime, mtime)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'lutimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function lutimesSync(filepath, atime, mtime) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.lutimesSync(req.handle, filepath, atime, mtime)
  } catch (e) {
    throw new FileError(e.message, { operation: 'lutimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function futimes(fd, atime, mtime, cb) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.futimes(req.handle, fd, atime, mtime)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'futimes', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function futimesSync(fd, atime, mtime) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  const req = FileRequest.borrow()

  try {
    binding.futimesSync(req.handle, fd, atime, mtime)
  } catch (e) {
    throw new FileError(e.message, { operation: 'futimesSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function link(src, dst, cb) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.link(req.handle, src, dst)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'link', code: e.code, path: src, destination: dst })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function linkSync(src, dst) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  try {
    binding.linkSync(req.handle, src, dst)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'linkSync',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }
}

async function mkdir(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = { mode: 0o777 }
  }

  if (typeof opts === 'number') opts = { mode: opts }
  else if (!opts) opts = {}

  const mode = typeof opts.mode === 'number' ? opts.mode : 0o777

  filepath = toNamespacedPath(filepath)

  if (opts.recursive) {
    let err = null
    try {
      try {
        await mkdir(filepath, { mode })
      } catch (err) {
        if (err.code !== 'ENOENT') {
          if (!(await stat(filepath)).isDirectory()) throw err
        } else {
          while (filepath.endsWith(path.sep)) filepath = filepath.slice(0, -1)
          const i = filepath.lastIndexOf(path.sep)
          if (i <= 0) throw err

          await mkdir(filepath.slice(0, i), { mode, recursive: true })

          try {
            await mkdir(filepath, { mode })
          } catch (err) {
            if (!(await stat(filepath)).isDirectory()) throw err
          }
        }
      }
    } catch (e) {
      err = e
    }

    return done(err, cb)
  }

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.mkdir(req.handle, filepath, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'mkdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function mkdirSync(filepath, opts) {
  if (typeof opts === 'number') opts = { mode: opts }
  else if (!opts) opts = {}

  const mode = typeof opts.mode === 'number' ? opts.mode : 0o777

  filepath = toNamespacedPath(filepath)

  if (opts.recursive) {
    try {
      mkdirSync(filepath, { mode })
    } catch (err) {
      if (err.code !== 'ENOENT') {
        if (!statSync(filepath).isDirectory()) throw err
      } else {
        while (filepath.endsWith(path.sep)) filepath = filepath.slice(0, -1)
        const i = filepath.lastIndexOf(path.sep)
        if (i <= 0) throw err

        mkdirSync(filepath.slice(0, i), { mode, recursive: true })

        try {
          mkdirSync(filepath, { mode })
        } catch (err) {
          if (!statSync(filepath).isDirectory()) throw err
        }
      }
    }

    return
  }

  const req = FileRequest.borrow()

  try {
    binding.mkdirSync(req.handle, filepath, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'mkdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function mkdtemp(prefix, cb) {
  prefix = toNamespacedPath(prefix)

  const req = FileRequest.borrow()

  let res
  let err = null
  try {
    binding.mkdtemp(req.handle, prefix + 'XXXXXX')

    await req

    res = binding.requestResultPath(req.handle)
  } catch (e) {
    err = new FileError(e.message, { operation: 'mkdtemp', code: e.code, path: prefix })
  } finally {
    req.return()
  }

  return done(err, res, cb)
}

function mkdtempSync(prefix) {
  prefix = toNamespacedPath(prefix)

  const req = FileRequest.borrow()

  try {
    binding.mkdtempSync(req.handle, prefix + 'XXXXXX')

    return binding.requestResultPath(req.handle)
  } catch (e) {
    throw new FileError(e.message, { operation: 'mkdtempSync', code: e.code, path: prefix })
  } finally {
    req.return()
  }
}

async function rmdir(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.rmdir(req.handle, filepath)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'rmdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function rmdirSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.rmdirSync(req.handle, filepath)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'rmdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function rm(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  let err = null
  try {
    const st = await lstat(filepath)

    if (st.isDirectory()) {
      if (opts.recursive) {
        try {
          await rmdir(filepath)
        } catch (err) {
          if (err.code !== 'ENOTEMPTY') throw err

          const files = await readdir(filepath)

          for (const file of files) {
            await rm(filepath + path.sep + file, opts)
          }

          await rmdir(filepath)
        }
      } else {
        throw new FileError('is a directory', {
          operation: 'rm',
          code: 'EISDIR',
          path: filepath
        })
      }
    } else {
      await unlink(filepath)
    }
  } catch (e) {
    if (e.code !== 'ENOENT' || !opts.force) err = e
  }

  return done(err, cb)
}

function rmSync(filepath, opts) {
  if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  try {
    const st = lstatSync(filepath)

    if (st.isDirectory()) {
      if (opts.recursive) {
        try {
          rmdirSync(filepath)
        } catch (err) {
          if (err.code !== 'ENOTEMPTY') throw err

          const files = readdirSync(filepath)

          for (const file of files) {
            rmSync(filepath + path.sep + file, opts)
          }

          rmdirSync(filepath)
        }
      } else {
        throw new FileError('is a directory', {
          operation: 'rm',
          code: 'EISDIR',
          path: filepath
        })
      }
    } else {
      unlinkSync(filepath)
    }
  } catch (err) {
    if (err.code !== 'ENOENT' || !opts.force) throw err
  }
}

async function unlink(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.unlink(req.handle, filepath)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'unlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function unlinkSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.unlinkSync(req.handle, filepath)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'unlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function rename(src, dst, cb) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.rename(req.handle, src, dst)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'rename',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function renameSync(src, dst) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  try {
    binding.renameSync(req.handle, src, dst)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'rename',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }
}

async function copyFile(src, dst, mode = 0, cb) {
  if (typeof mode === 'function') {
    cb = mode
    mode = 0
  }

  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.copyfile(req.handle, src, dst, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'copyfile',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function copyFileSync(src, dst, mode = 0) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  try {
    binding.copyfileSync(req.handle, src, dst, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'copyfile',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }
}

async function cp(src, dst, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (!opts) opts = {}

  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  let err = null
  try {
    const st = await lstat(src)

    if (st.isDirectory()) {
      if (opts.recursive !== true) {
        throw new FileError('is a directory', { operation: 'cp', code: 'EISDIR', path: src })
      }

      try {
        await lstat(dst)
      } catch (e) {
        if (e.code !== 'ENOENT') throw e

        await mkdir(dst, { mode: st.mode, recursive: true })
      }

      const dir = await opendir(src)
      for await (const { name } of dir) {
        await cp(path.join(src, name), path.join(dst, name), opts)
      }
    } else if (st.isFile()) {
      await copyFile(src, dst)
      await chmod(dst, st.mode)
    }
  } catch (e) {
    err = e
  }

  return done(err, cb)
}

function cpSync(src, dst, opts = {}) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const st = lstatSync(src)

  if (st.isDirectory()) {
    if (opts.recursive !== true) {
      throw new FileError('is a directory', { operation: 'cp', code: 'EISDIR', path: src })
    }

    try {
      lstatSync(dst)
    } catch (e) {
      if (e.code !== 'ENOENT') throw e

      mkdirSync(dst, { mode: st.mode, recursive: true })
    }

    const dir = opendirSync(src)
    for (const { name } of dir) {
      cpSync(path.join(src, name), path.join(dst, name), opts)
    }
  } else if (st.isFile()) {
    copyFileSync(src, dst)
    chmodSync(dst, st.mode)
  }
}

async function realpath(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let res
  let err = null
  try {
    binding.realpath(req.handle, filepath)

    await req

    res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'realpath',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, res, cb)
}

function realpathSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.realpathSync(req.handle, filepath)

    let res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)

    return res
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'realpath',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function readlink(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let res
  let err = null
  try {
    binding.readlink(req.handle, filepath)

    await req

    res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'readlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, res, cb)
}

function readlinkSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.readlinkSync(req.handle, filepath)

    let res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)

    return res
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'readlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function fsync(fd, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fsync(req.handle, fd)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fsync', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fsyncSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.fsyncSync(req.handle, fd)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fsyncSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function fdatasync(fd, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fdatasync(req.handle, fd)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fdatasync', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fdatasyncSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.fdatasyncSync(req.handle, fd)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fdatasyncSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

function normalizeSymlinkTarget(target, type, filepath) {
  if (isWindows) {
    if (type === constants.UV_FS_SYMLINK_JUNCTION) target = path.resolve(filepath, '..', target)

    if (path.isAbsolute(target)) return path.toNamespacedPath(target)

    return target.replace(/\//g, path.sep)
  }

  return target
}

async function symlink(target, filepath, type, cb) {
  if (typeof type === 'function') {
    cb = type
    type = null
  }

  filepath = toNamespacedPath(filepath)

  if (typeof type === 'string') {
    switch (type) {
      case 'dir':
        type = constants.UV_FS_SYMLINK_DIR
        break
      case 'junction':
        type = constants.UV_FS_SYMLINK_JUNCTION
        break
      case 'file':
      default:
        type = 0
        break
    }
  } else if (typeof type !== 'number') {
    if (isWindows) {
      target = path.resolve(filepath, '..', target)

      try {
        type = (await stat(target)).isDirectory()
          ? constants.UV_FS_SYMLINK_DIR
          : constants.UV_FS_SYMLINK_JUNCTION
      } catch {
        type = 0
      }
    } else {
      type = 0
    }
  }

  target = normalizeSymlinkTarget(target, type, filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.symlink(req.handle, target, filepath, type)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'symlink',
      code: e.code,
      path: target,
      destination: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function symlinkSync(target, filepath, type) {
  filepath = toNamespacedPath(filepath)

  if (typeof type === 'string') {
    switch (type) {
      case 'dir':
        type = constants.UV_FS_SYMLINK_DIR
        break
      case 'junction':
        type = constants.UV_FS_SYMLINK_JUNCTION
        break
      case 'file':
      default:
        type = 0
        break
    }
  } else if (typeof type !== 'number') {
    if (isWindows) {
      target = path.resolve(filepath, '..', target)

      try {
        type = statSync(target).isDirectory()
          ? constants.UV_FS_SYMLINK_DIR
          : constants.UV_FS_SYMLINK_JUNCTION
      } catch {
        type = 0
      }
    } else {
      type = 0
    }
  }

  target = normalizeSymlinkTarget(target, type, filepath)

  const req = FileRequest.borrow()

  try {
    binding.symlinkSync(req.handle, target, filepath, type)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'symlink',
      code: e.code,
      path: target,
      destination: filepath
    })
  } finally {
    req.return()
  }
}

async function opendir(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let dir
  let err = null
  try {
    binding.opendir(req.handle, filepath)

    await req

    dir = new Dir(filepath, binding.requestResultDir(req.handle), opts)
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'opendir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, dir, cb)
}

function opendirSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.opendirSync(req.handle, filepath)

    return new Dir(filepath, binding.requestResultDir(req.handle), opts)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'opendir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function readdir(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { withFileTypes = false, recursive = false } = opts

  filepath = toNamespacedPath(filepath)

  const queue = [filepath]
  let result = []
  let err = null
  try {
    while (queue.length !== 0) {
      const dir = await opendir(queue.pop())

      for await (const entry of dir) {
        const entryPath = path.join(entry.parentPath, entry.name)

        if (withFileTypes) {
          result.push(entry)
        } else {
          result.push(path.relative(filepath, entryPath))
        }

        if (recursive && entry.isDirectory()) queue.push(entryPath)
      }
    }
  } catch (e) {
    result = []
    err = e
  }

  return done(err, result, cb)
}

function readdirSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { withFileTypes = false, recursive = false } = opts

  filepath = toNamespacedPath(filepath)

  const queue = [filepath]
  const result = []

  while (queue.length !== 0) {
    const dir = opendirSync(queue.pop(), opts)

    for (const entry of dir) {
      const entryPath = path.join(entry.parentPath, entry.name)

      if (withFileTypes) {
        result.push(entry)
      } else {
        result.push(path.relative(filepath, entryPath))
      }

      if (recursive && entry.isDirectory()) queue.push(entryPath)
    }
  }

  return result
}

async function readFile(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'buffer' } = opts

  let fd = -1
  let buffer = null
  let err = null
  try {
    fd = await open(filepath, opts.flag || 'r')

    const st = await fstat(fd)

    let len = 0

    if (st.size === 0) {
      const buffers = []

      while (true) {
        buffer = Buffer.allocUnsafe(8192)
        const r = await read(fd, buffer)
        len += r
        if (r === 0) break
        buffers.push(buffer.subarray(0, r))
      }

      buffer = Buffer.concat(buffers)
    } else {
      buffer = Buffer.allocUnsafe(st.size)

      while (true) {
        const r = await read(fd, len ? buffer.subarray(len) : buffer)
        len += r
        if (r === 0 || len === buffer.byteLength) break
      }

      if (len !== buffer.byteLength) buffer = buffer.subarray(0, len)
    }

    if (encoding !== 'buffer') buffer = buffer.toString(encoding)
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) await close(fd)
  }

  return done(err, buffer, cb)
}

function readFileSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'buffer' } = opts

  let fd = -1
  try {
    fd = openSync(filepath, opts.flag || 'r')

    const st = fstatSync(fd)

    let buffer
    let len = 0

    if (st.size === 0) {
      const buffers = []

      while (true) {
        buffer = Buffer.allocUnsafe(8192)
        const r = readSync(fd, buffer)
        len += r
        if (r === 0) break
        buffers.push(buffer.subarray(0, r))
      }

      buffer = Buffer.concat(buffers)
    } else {
      buffer = Buffer.allocUnsafe(st.size)

      while (true) {
        const r = readSync(fd, len ? buffer.subarray(len) : buffer)
        len += r
        if (r === 0 || len === buffer.byteLength) break
      }

      if (len !== buffer.byteLength) buffer = buffer.subarray(0, len)
    }

    if (encoding !== 'buffer') buffer = buffer.toString(encoding)

    return buffer
  } finally {
    if (fd !== -1) closeSync(fd)
  }
}

async function writeFile(filepath, data, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (typeof data === 'string') data = Buffer.from(data, opts.encoding)

  let fd = -1
  let len = 0
  let err = null
  try {
    fd = await open(filepath, opts.flag || 'w', opts.mode || 0o666)

    while (true) {
      len += await write(fd, len ? data.subarray(len) : data)
      if (len === data.byteLength) break
    }
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) await close(fd)
  }

  return done(err, len, cb)
}

function writeFileSync(filepath, data, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (typeof data === 'string') data = Buffer.from(data, opts.encoding)

  let fd = -1
  try {
    fd = openSync(filepath, opts.flag || 'w', opts.mode || 0o666)

    let len = 0

    while (true) {
      len += writeSync(fd, len ? data.subarray(len) : data)
      if (len === data.byteLength) break
    }
  } finally {
    if (fd !== -1) closeSync(fd)
  }
}

function appendFile(filepath, data, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (!opts.flag) opts = { ...opts, flag: 'a' }

  return writeFile(filepath, data, opts, cb)
}

function appendFileSync(filepath, data, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (!opts.flag) opts = { ...opts, flag: 'a' }

  return writeFileSync(filepath, data, opts)
}

function watch(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  return new Watcher(filepath, opts, cb)
}

class Stats {
  constructor(
    dev,
    mode,
    nlink,
    uid,
    gid,
    rdev,
    blksize,
    ino,
    size,
    blocks,
    atimeMs,
    mtimeMs,
    ctimeMs,
    birthtimeMs
  ) {
    this.dev = dev
    this.mode = mode
    this.nlink = nlink
    this.uid = uid
    this.gid = gid
    this.rdev = rdev
    this.blksize = blksize
    this.ino = ino
    this.size = size
    this.blocks = blocks
    this.atimeMs = atimeMs
    this.mtimeMs = mtimeMs
    this.ctimeMs = ctimeMs
    this.birthtimeMs = birthtimeMs
    this.atime = new Date(atimeMs)
    this.mtime = new Date(mtimeMs)
    this.ctime = new Date(ctimeMs)
    this.birthtime = new Date(birthtimeMs)
  }

  isDirectory() {
    return (this.mode & constants.S_IFMT) === constants.S_IFDIR
  }

  isFile() {
    return (this.mode & constants.S_IFMT) === constants.S_IFREG
  }

  isBlockDevice() {
    return (this.mode & constants.S_IFMT) === constants.S_IFBLK
  }

  isCharacterDevice() {
    return (this.mode & constants.S_IFMT) === constants.S_IFCHR
  }

  isFIFO() {
    return (this.mode & constants.S_IFMT) === constants.S_IFIFO
  }

  isSymbolicLink() {
    return (this.mode & constants.S_IFMT) === constants.S_IFLNK
  }

  isSocket() {
    return (this.mode & constants.S_IFMT) === constants.S_IFSOCK
  }
}

class StatFs {
  constructor(type, bsize, blocks, bfree, bavail, files, ffree) {
    this.type = type
    this.bsize = bsize
    this.blocks = blocks
    this.bfree = bfree
    this.bavail = bavail
    this.files = files
    this.ffree = ffree
  }
}

class Dir {
  constructor(path, handle, opts = {}) {
    const { encoding = 'utf8', bufferSize = 32 } = opts

    this.path = path

    this._encoding = encoding
    this._capacity = bufferSize
    this._buffer = new FIFO()
    this._ended = false
    this._handle = handle
  }

  async read(cb) {
    if (this._buffer.length) return ok(this._buffer.shift(), cb)
    if (this._ended) return ok(null, cb)

    const req = FileRequest.borrow()

    let entries
    let err = null
    try {
      req.retain(binding.readdir(req.handle, this._handle, this._capacity))

      await req

      entries = binding.requestResultDirents(req.handle)
    } catch (e) {
      err = new FileError(e.message, {
        operation: 'readdir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    if (err) return fail(err, cb)

    if (entries.length === 0) {
      this._ended = true

      return ok(null, cb)
    }

    for (const entry of entries) {
      let name = Buffer.from(entry.name)

      if (this._encoding !== 'buffer') name = name.toString(this._encoding)

      this._buffer.push(new Dirent(this.path, name, entry.type))
    }

    return ok(this._buffer.shift(), cb)
  }

  readSync() {
    if (this._buffer.length) return this._buffer.shift()
    if (this._ended) return null

    const req = FileRequest.borrow()

    let entries
    try {
      req.retain(binding.readdirSync(req.handle, this._handle, this._capacity))

      entries = binding.requestResultDirents(req.handle)
    } catch (e) {
      throw new FileError(e.message, {
        operation: 'readdir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    if (entries.length === 0) {
      this._ended = true

      return null
    }

    for (const entry of entries) {
      let name = Buffer.from(entry.name)

      if (this._encoding !== 'buffer') name = name.toString(this._encoding)

      this._buffer.push(new Dirent(this.path, name, entry.type))
    }

    return this._buffer.shift()
  }

  async close(cb) {
    const req = FileRequest.borrow()

    let err = null
    try {
      binding.closedir(req.handle, this._handle)

      await req
    } catch (e) {
      err = new FileError(e.message, {
        operation: 'closedir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    this._handle = null

    return done(err, cb)
  }

  closeSync() {
    const req = FileRequest.borrow()

    try {
      binding.closedirSync(req.handle, this._handle)
    } catch (e) {
      throw new FileError(e.message, {
        operation: 'closedir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    this._handle = null
  }

  [Symbol.dispose]() {
    this.closeSync()
  }

  async [Symbol.asyncDispose]() {
    await this.close()
  }

  *[Symbol.iterator]() {
    while (true) {
      const entry = this.readSync()
      if (entry === null) break
      yield entry
    }

    this.closeSync()
  }

  async *[Symbol.asyncIterator]() {
    while (true) {
      const entry = await this.read()
      if (entry === null) break
      yield entry
    }

    await this.close()
  }
}

class Dirent {
  constructor(parentPath, name, type) {
    this.parentPath = parentPath
    this.name = name
    this.type = type
  }

  isFile() {
    return this.type === constants.UV_DIRENT_FILE
  }

  isDirectory() {
    return this.type === constants.UV_DIRENT_DIR
  }

  isSymbolicLink() {
    return this.type === constants.UV_DIRENT_LINK
  }

  isFIFO() {
    return this.type === constants.UV_DIRENT_FIFO
  }

  isSocket() {
    return this.type === constants.UV_DIRENT_SOCKET
  }

  isCharacterDevice() {
    return this.type === constants.UV_DIRENT_CHAR
  }

  isBlockDevice() {
    return this.type === constants.UV_DIRENT_BLOCK
  }
}

class FileReadStream extends Readable {
  constructor(path, opts = {}) {
    const { eagerOpen = true } = opts

    super({ eagerOpen, ...opts })

    this.path = path
    this.fd = typeof opts.fd === 'number' ? opts.fd : -1
    this.flags = opts.flags || 'r'
    this.mode = opts.mode || 0o666

    this._offset = opts.start || 0
    this._missing = 0

    if (opts.length) {
      this._missing = opts.length
    } else if (typeof opts.end === 'number') {
      this._missing = opts.end - this._offset + 1
    } else {
      this._missing = -1
    }
  }

  async _open(cb) {
    let err

    if (this.fd === -1) {
      err = null
      try {
        this.fd = await open(this.path, this.flags, this.mode)
      } catch (e) {
        err = e
      }

      if (err) return cb(err)
    }

    let st
    err = null
    try {
      st = await fstat(this.fd)
    } catch (e) {
      err = e
    }

    if (err) return cb(err)

    if (this._missing === -1) this._missing = st.size

    if (st.size < this._offset) {
      this._offset = st.size
      this._missing = 0
    } else if (st.size < this._offset + this._missing) {
      this._missing = st.size - this._offset
    }

    cb(null)
  }

  async _read(size) {
    if (this._missing <= 0) return this.push(null)

    const data = Buffer.allocUnsafe(Math.min(this._missing, size))

    let len
    let err = null
    try {
      len = await read(this.fd, data, 0, data.byteLength, this._offset)
    } catch (e) {
      err = e
    }

    if (err) return this.destroy(err)

    if (len === 0) return this.push(null)

    if (this._missing < len) len = this._missing

    this._missing -= len
    this._offset += len

    this.push(data.subarray(0, len))
  }

  async _destroy(err, cb) {
    if (this.fd === -1) return cb(err)

    try {
      await close(this.fd)
    } catch (e) {
      err = err || e
    }

    cb(err)
  }
}

class FileWriteStream extends Writable {
  constructor(path, opts = {}) {
    const { eagerOpen = true } = opts

    super({ eagerOpen, ...opts })

    this.path = path
    this.fd = typeof opts.fd === 'number' ? opts.fd : -1
    this.flags = opts.flags || 'w'
    this.mode = opts.mode || 0o666
  }

  async _open(cb) {
    if (this.fd !== -1) return cb(null)

    let err = null
    try {
      this.fd = await open(this.path, this.flags, this.mode)
    } catch (e) {
      err = e
    }

    cb(err)
  }

  async _writev(batch, cb) {
    let err = null
    try {
      await writev(
        this.fd,
        batch.map(({ chunk }) => chunk)
      )
    } catch (e) {
      err = e
    }

    cb(err)
  }

  async _destroy(err, cb) {
    if (this.fd === -1) return cb(err)

    try {
      await close(this.fd)
    } catch (e) {
      err = err || e
    }

    cb(err)
  }
}

class Watcher extends EventEmitter {
  constructor(path, opts, onchange) {
    if (typeof opts === 'function') {
      onchange = opts
      opts = {}
    }

    if (!opts) opts = {}

    const { persistent = true, recursive = false, encoding = 'utf8' } = opts

    super()

    this._closed = false
    this._encoding = encoding
    this._handle = binding.watcherInit(path, recursive, this, this._onevent, this._onclose)

    if (!persistent) this.unref()

    if (onchange) this.on('change', onchange)
  }

  close() {
    if (this._closed) return
    this._closed = true

    binding.watcherClose(this._handle)
  }

  ref() {
    if (this._handle) binding.watcherRef(this._handle)
    return this
  }

  unref() {
    if (this._handle) binding.watcherUnref(this._handle)
    return this
  }

  [Symbol.asyncIterator]() {
    const buffer = []
    let done = false
    let error = null
    let next = null

    this.on('change', (eventType, filename) => {
      if (next) {
        next.resolve({ done: false, value: { eventType, filename } })
        next = null
      } else {
        buffer.push({ eventType, filename })
      }
    })
      .on('error', (err) => {
        done = true
        error = err

        if (next) {
          next.reject(error)
          next = null
        }
      })
      .on('close', () => {
        done = true

        if (next) {
          next.resolve({ done })
          next = null
        }
      })

    return {
      next: () =>
        new Promise((resolve, reject) => {
          if (error) return reject(error)

          if (buffer.length) return resolve({ done: false, value: buffer.shift() })

          if (done) return resolve({ done })

          next = { resolve, reject }
        })
    }
  }

  _onevent(err, events, filename) {
    if (err) {
      this.close()
      this.emit('error', err)
    } else {
      const path =
        this._encoding === 'buffer'
          ? Buffer.from(filename)
          : Buffer.from(filename).toString(this._encoding)

      if (events & binding.UV_RENAME) {
        this.emit('change', 'rename', path)
      }

      if (events & binding.UV_CHANGE) {
        this.emit('change', 'change', path)
      }
    }
  }

  _onclose() {
    this._handle = null

    this.emit('close')
  }
}

exports.access = access
exports.appendFile = appendFile
exports.chmod = chmod
exports.chown = chown
exports.close = close
exports.copyFile = copyFile
exports.cp = cp
exports.exists = exists
exports.fchmod = fchmod
exports.fchown = fchown
exports.fdatasync = fdatasync
exports.fstat = fstat
exports.fsync = fsync
exports.ftruncate = ftruncate
exports.futimes = futimes
exports.lchown = lchown
exports.lutimes = lutimes
exports.link = link
exports.lstat = lstat
exports.mkdir = mkdir
exports.mkdtemp = mkdtemp
exports.open = open
exports.opendir = opendir
exports.read = read
exports.readFile = readFile
exports.readdir = readdir
exports.readlink = readlink
exports.readv = readv
exports.realpath = realpath
exports.rename = rename
exports.rm = rm
exports.rmdir = rmdir
exports.stat = stat
exports.statfs = statfs
exports.symlink = symlink
exports.truncate = truncate
exports.unlink = unlink
exports.utimes = utimes
exports.watch = watch
exports.write = write
exports.writeFile = writeFile
exports.writev = writev

exports.accessSync = accessSync
exports.appendFileSync = appendFileSync
exports.chmodSync = chmodSync
exports.chownSync = chownSync
exports.closeSync = closeSync
exports.copyFileSync = copyFileSync
exports.cpSync = cpSync
exports.existsSync = existsSync
exports.fchmodSync = fchmodSync
exports.fchownSync = fchownSync
exports.fdatasyncSync = fdatasyncSync
exports.fstatSync = fstatSync
exports.fsyncSync = fsyncSync
exports.ftruncateSync = ftruncateSync
exports.futimesSync = futimesSync
exports.lchownSync = lchownSync
exports.lutimesSync = lutimesSync
exports.linkSync = linkSync
exports.lstatSync = lstatSync
exports.mkdirSync = mkdirSync
exports.mkdtempSync = mkdtempSync
exports.openSync = openSync
exports.opendirSync = opendirSync
exports.readFileSync = readFileSync
exports.readSync = readSync
exports.readdirSync = readdirSync
exports.readlinkSync = readlinkSync
exports.readvSync = readvSync
exports.realpathSync = realpathSync
exports.renameSync = renameSync
exports.rmSync = rmSync
exports.rmdirSync = rmdirSync
exports.statSync = statSync
exports.statfsSync = statfsSync
exports.symlinkSync = symlinkSync
exports.truncateSync = truncateSync
exports.unlinkSync = unlinkSync
exports.utimesSync = utimesSync
exports.writeFileSync = writeFileSync
exports.writeSync = writeSync
exports.writevSync = writevSync

exports.promises = require('./promises')

exports.Stats = Stats
exports.StatFs = StatFs
exports.Dir = Dir
exports.Dirent = Dirent
exports.Watcher = Watcher

exports.ReadStream = FileReadStream

exports.createReadStream = function createReadStream(path, opts) {
  return new FileReadStream(path, opts)
}

exports.WriteStream = FileWriteStream

exports.createWriteStream = function createWriteStream(path, opts) {
  return new FileWriteStream(path, opts)
}

function toNamespacedPath(filepath) {
  if (typeof filepath !== 'string') {
    if (isURL(filepath)) filepath = fileURLToPath(filepath)
    else filepath = filepath.toString()
  }

  return path.toNamespacedPath(filepath)
}

function toFlags(flags) {
  switch (flags) {
    case 'r':
      return constants.O_RDONLY
    case 'rs': // Fall through.
    case 'sr':
      return constants.O_RDONLY | constants.O_SYNC
    case 'r+':
      return constants.O_RDWR
    case 'rs+': // Fall through.
    case 'sr+':
      return constants.O_RDWR | constants.O_SYNC

    case 'w':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_WRONLY
    case 'wx': // Fall through.
    case 'xw':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_WRONLY | constants.O_EXCL

    case 'w+':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_RDWR
    case 'wx+': // Fall through.
    case 'xw+':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_RDWR | constants.O_EXCL

    case 'a':
      return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY
    case 'ax': // Fall through.
    case 'xa':
      return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY | constants.O_EXCL
    case 'as': // Fall through.
    case 'sa':
      return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY | constants.O_SYNC

    case 'a+':
      return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR
    case 'ax+': // Fall through.
    case 'xa+':
      return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR | constants.O_EXCL
    case 'as+': // Fall through.
    case 'sa+':
      return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR | constants.O_SYNC
    default:
      return 0
  }
}

function toMode(mode) {
  return parseInt(mode, 8)
}
const binding = require('../binding')

module.exports = {
  O_RDWR: binding.O_RDWR,
  O_RDONLY: binding.O_RDONLY,
  O_WRONLY: binding.O_WRONLY,
  O_CREAT: binding.O_CREAT,
  O_TRUNC: binding.O_TRUNC,
  O_APPEND: binding.O_APPEND,

  F_OK: binding.F_OK || 0,
  R_OK: binding.R_OK || 0,
  W_OK: binding.W_OK || 0,
  X_OK: binding.X_OK || 0,

  S_IFMT: binding.S_IFMT,
  S_IFREG: binding.S_IFREG,
  S_IFDIR: binding.S_IFDIR,
  S_IFCHR: binding.S_IFCHR,
  S_IFLNK: binding.S_IFLNK,
  S_IFBLK: binding.S_IFBLK || 0,
  S_IFIFO: binding.S_IFIFO || 0,
  S_IFSOCK: binding.S_IFSOCK || 0,

  S_IRUSR: binding.S_IRUSR || 0,
  S_IWUSR: binding.S_IWUSR || 0,
  S_IXUSR: binding.S_IXUSR || 0,
  S_IRGRP: binding.S_IRGRP || 0,
  S_IWGRP: binding.S_IWGRP || 0,
  S_IXGRP: binding.S_IXGRP || 0,
  S_IROTH: binding.S_IROTH || 0,
  S_IWOTH: binding.S_IWOTH || 0,
  S_IXOTH: binding.S_IXOTH || 0,

  UV_DIRENT_UNKNOWN: binding.UV_DIRENT_UNKNOWN,
  UV_DIRENT_FILE: binding.UV_DIRENT_FILE,
  UV_DIRENT_DIR: binding.UV_DIRENT_DIR,
  UV_DIRENT_LINK: binding.UV_DIRENT_LINK,
  UV_DIRENT_FIFO: binding.UV_DIRENT_FIFO,
  UV_DIRENT_SOCKET: binding.UV_DIRENT_SOCKET,
  UV_DIRENT_CHAR: binding.UV_DIRENT_CHAR,
  UV_DIRENT_BLOCK: binding.UV_DIRENT_BLOCK,

  COPYFILE_EXCL: binding.UV_FS_COPYFILE_EXCL,
  COPYFILE_FICLONE: binding.UV_FS_COPYFILE_FICLONE,
  COPYFILE_FICLONE_FORCE: binding.UV_FS_COPYFILE_FICLONE_FORCE,
  UV_FS_SYMLINK_DIR: binding.UV_FS_SYMLINK_DIR,
  UV_FS_SYMLINK_JUNCTION: binding.UV_FS_SYMLINK_JUNCTION
}
const os = require('bare-os')

module.exports = class FileError extends Error {
  constructor(msg, opts = {}) {
    const { code, operation = null, path = null, destination = null, fd = -1 } = opts

    if (operation !== null) msg += describe(operation, opts)

    super(`${code}: ${msg}`)

    this.code = code

    if (operation !== null) this.operation = operation
    if (path !== null) this.path = path
    if (destination !== null) this.destination = destination
    if (fd !== -1) this.fd = fd
  }

  get name() {
    return 'FileError'
  }

  // For Node.js compatibility
  get errno() {
    return os.constants.errnos[this.code]
  }

  // For Node.js compatibility
  get syscall() {
    return this.operation
  }

  // For Node.js compatibility
  get dest() {
    return this.destination
  }
}

function describe(operation, opts) {
  const { path = null, destination = null, fd = -1 } = opts

  let result = `, ${operation}`

  if (path !== null) {
    result += ` ${JSON.stringify(path)}`

    if (destination !== null) {
      result += ` -> ${JSON.stringify(destination)}`
    }
  } else if (fd !== -1) {
    result += ` ${fd}`
  }

  return result
}
{
  "name": "bare-fs",
  "version": "4.7.3",
  "description": "Native file system operations for Bare",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./promises": {
      "types": "./promises.d.ts",
      "default": "./promises.js"
    },
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "promises.js",
    "promises.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-fs.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-fs/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-fs#readme",
  "engines": {
    "bare": ">=1.16.0"
  },
  "dependencies": {
    "bare-events": "^2.5.4",
    "bare-path": "^3.0.0",
    "bare-stream": "^2.6.4",
    "bare-url": "^2.2.2",
    "fast-fifo": "^1.3.2"
  },
  "devDependencies": {
    "bare-buffer": "^3.0.2",
    "bare-crypto": "^1.11.2",
    "brittle": "^3.1.1",
    "cmake-bare": "^1.1.7",
    "lunte": "^1.6.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "bare-buffer": "*"
  },
  "peerDependenciesMeta": {
    "bare-buffer": {
      "optional": true
    }
  }
}
const EventEmitter = require('bare-events')
const fs = require('.')

class FileHandle extends EventEmitter {
  constructor(fd) {
    super()

    this.fd = fd
  }

  async close() {
    await fs.close(this.fd)

    this.fd = -1
    this.emit('close')
  }

  async read(buffer, ...args) {
    return {
      bytesRead: await fs.read(this.fd, buffer, ...args),
      buffer
    }
  }

  async readv(buffers, ...args) {
    return {
      bytesRead: await fs.readv(this.fd, buffers, ...args),
      buffers
    }
  }

  async write(buffer, ...args) {
    return {
      bytesWritten: await fs.write(this.fd, buffer, ...args),
      buffer
    }
  }

  async writev(buffers, ...args) {
    return {
      bytesWritten: await fs.writev(this.fd, buffers, ...args),
      buffers
    }
  }

  async stat() {
    return fs.fstat(this.fd)
  }

  async chmod(mode) {
    await fs.fchmod(this.fd, mode)
  }

  async chown(uid, gid) {
    await fs.fchown(this.fd, uid, gid)
  }

  async datasync() {
    return fs.fdatasync(this.fd)
  }

  async sync() {
    return fs.fsync(this.fd)
  }

  async truncate(len) {
    await fs.ftruncate(this.fd, len)
  }

  async utimes(atime, mtime) {
    await fs.futimes(this.fd, atime, mtime)
  }

  createReadStream(opts) {
    return fs.createReadStream(null, { ...opts, fd: this.fd })
  }

  createWriteStream(opts) {
    return fs.createWriteStream(null, { ...opts, fd: this.fd })
  }

  async [Symbol.asyncDispose]() {
    await this.close()
  }
}

exports.open = async function open(filepath, flags, mode) {
  return new FileHandle(await fs.open(filepath, flags, mode))
}

exports.access = fs.access
exports.appendFile = fs.appendFile
exports.chmod = fs.chmod
exports.chown = fs.chown
exports.constants = fs.constants
exports.copyFile = fs.copyFile
exports.cp = fs.cp
exports.lchown = fs.lchown
exports.lutimes = fs.lutimes
exports.link = fs.link
exports.lstat = fs.lstat
exports.mkdir = fs.mkdir
exports.mkdtemp = fs.mkdtemp
exports.opendir = fs.opendir
exports.readFile = fs.readFile
exports.readdir = fs.readdir
exports.readlink = fs.readlink
exports.realpath = fs.realpath
exports.rename = fs.rename
exports.rm = fs.rm
exports.rmdir = fs.rmdir
exports.stat = fs.stat
exports.statfs = fs.statfs
exports.truncate = fs.truncate
exports.symlink = fs.symlink
exports.unlink = fs.unlink
exports.utimes = fs.utimes
exports.watch = fs.watch
exports.writeFile = fs.writeFile
module.exports = require.addon()
const binding = require('./binding')

module.exports = exports = function hrtime(past) {
  let now = binding.hrtime()

  if (past) now -= BigInt(past[0]) * 1000000000n + BigInt(past[1])

  return [Number(now / 1000000000n), Number(now % 1000000000n)]
}

exports.bigint = function hrtime() {
  return binding.hrtime()
}
{
  "name": "bare-hrtime",
  "version": "2.1.1",
  "description": "High-resolution timers for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-hrtime.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-hrtime/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-hrtime#readme",
  "devDependencies": {
    "brittle": "^3.2.1",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  }
}
const errors = require('./lib/errors')

const constants = {
  REQUEST: 1,
  RESPONSE: 2,
  DATA: 3,
  END: 4
}

const TAB = 0x09
const LF = 0x0a
const CR = 0x0d
const SP = 0x20
const ZERO = 0x30
const NINE = 0x39
const UPPER_A = 0x41
const UPPER_F = 0x46
const UPPER_Z = 0x5a
const LOWER_A = 0x61
const LOWER_F = 0x66
const COLON = 0x3a

const MAX_CHUNK_SIZE_LENGTH = 16

// Header states
const FIRST_TOKEN = 0
const REQUEST_URL = 1
const REQUEST_VERSION = 2
const STATUS_CODE = 3
const STATUS_REASON = 4
const FIRST_LINE_LF = 5
const HEADER_START = 6
const HEADER_NAME = 7
const HEADER_VALUE_WS = 8
const HEADER_VALUE = 9
const HEADER_LINE_LF = 10
const HEADER_END_LF = 11

// Body states
const BODY = 12
const CHUNK_SIZE = 13
const CHUNK_SIZE_LF = 14
const CHUNK_DATA = 15
const CHUNK_EXTENSION = 16

// Trailing states
const LAST_CHUNK_LF = 17
const TRAILER_CR = 18
const TRAILER_LF = 19

module.exports = exports = class HTTPParser {
  constructor(opts = {}) {
    const { maxHeaderSize = 16384, maxHeadersCount = 2000 } = opts

    this._maxHeaderSize = maxHeaderSize
    this._maxHeadersCount = maxHeadersCount
    this._state = FIRST_TOKEN
    this._buffer = []
    this._bufferIndex = 0
    this._byteIndex = 0
    this._buffered = 0
    this._accumulator = []

    this._isResponse = false
    this._method = ''
    this._url = ''
    this._version = ''
    this._code = 0
    this._reason = ''

    this._headerName = ''
    this._headers = Object.create(null)
    this._headerCount = 0
    this._headerSize = 0

    this._remaining = 0
  }

  *push(data, encoding) {
    if (typeof data === 'string') data = Buffer.from(data, encoding)

    this._buffer.push(data)
    this._buffered += data.byteLength

    yield* this._parse()

    this._compact()
  }

  end() {
    const buffers = this._buffer
    const bufferIndex = this._bufferIndex
    const byteIndex = this._byteIndex

    this._buffer = []
    this._bufferIndex = 0
    this._byteIndex = 0
    this._buffered = 0

    if (bufferIndex >= buffers.length) return Buffer.alloc(0)

    buffers[bufferIndex] = buffers[bufferIndex].subarray(byteIndex)

    const remaining = buffers.slice(bufferIndex)

    if (remaining.length === 0) return Buffer.alloc(0)
    if (remaining.length === 1) return remaining[0]

    return Buffer.concat(remaining)
  }

  _compact() {
    if (this._bufferIndex > 0) {
      this._buffer = this._buffer.slice(this._bufferIndex)
      this._bufferIndex = 0
    }

    if (this._byteIndex > 0 && this._buffer.length > 0) {
      this._buffer[0] = this._buffer[0].subarray(this._byteIndex)
      this._byteIndex = 0
    }
  }

  _consume(n) {
    this._buffered -= n

    const current = this._buffer[this._bufferIndex]

    if (this._byteIndex + n <= current.byteLength) {
      const slice = current.subarray(this._byteIndex, this._byteIndex + n)

      this._byteIndex += n

      if (this._byteIndex >= current.byteLength) {
        this._bufferIndex++
        this._byteIndex = 0
      }

      return slice
    }

    const result = Buffer.allocUnsafe(n)

    let written = 0

    while (written < n) {
      const buffer = this._buffer[this._bufferIndex]
      const available = buffer.byteLength - this._byteIndex
      const take = Math.min(available, n - written)

      buffer.copy(result, written, this._byteIndex, this._byteIndex + take)

      written += take

      this._byteIndex += take

      if (this._byteIndex >= buffer.byteLength) {
        this._bufferIndex++
        this._byteIndex = 0
      }
    }

    return result
  }

  _buildString() {
    const string = String.fromCharCode.apply(null, this._accumulator)

    this._accumulator = []

    return string
  }

  _checkHeaderSize() {
    if (++this._headerSize > this._maxHeaderSize) {
      throw errors.INVALID_MESSAGE('Header exceeds limit of ' + this._maxHeaderSize + ' bytes')
    }
  }

  _storeHeader(name, value) {
    let end = value.length

    while (end > 0 && (value.charCodeAt(end - 1) === SP || value.charCodeAt(end - 1) === TAB)) {
      end--
    }

    if (end < value.length) value = value.substring(0, end)

    this._headerCount++

    if (this._headerCount > this._maxHeadersCount) {
      throw errors.INVALID_MESSAGE('Header count exceeds limit of ' + this._maxHeadersCount)
    }

    switch (name) {
      case '__proto__':
      case 'constructor':
      case 'prototype':
        throw errors.INVALID_HEADER("Unsafe header name '" + name + "'")

      case 'host':
      case 'content-length':
      case 'transfer-encoding':
        if (name in this._headers) {
          throw errors.INVALID_HEADER("Duplicate header '" + name + "'")
        }

        this._headers[name] = value
        break

      default: {
        const delimiter = name === 'cookie' ? '; ' : ', '

        if (name in this._headers) {
          this._headers[name] += delimiter + value
        } else {
          this._headers[name] = value
        }
      }
    }
  }

  *_parse() {
    while (true) {
      if (this._state === BODY) {
        if (this._buffered === 0) return

        const available = Math.min(this._buffered, this._remaining)
        const data = this._consume(available)

        this._remaining -= available

        const ended = this._remaining === 0

        if (ended) this._state = FIRST_TOKEN

        yield { type: constants.DATA, data }

        if (ended) yield { type: constants.END }

        continue
      }

      if (this._state === CHUNK_DATA) {
        if (this._buffered < this._remaining) return

        const consumed = this._consume(this._remaining)

        if (consumed[this._remaining - 2] !== CR || consumed[this._remaining - 1] !== LF) {
          throw errors.INVALID_MESSAGE('Expected CRLF after chunk data')
        }

        const data = consumed.subarray(0, this._remaining - 2)

        this._remaining = 0
        this._state = CHUNK_SIZE

        yield { type: constants.DATA, data }

        continue
      }

      if (this._buffered === 0) return

      const byte = this._buffer[this._bufferIndex][this._byteIndex++]

      this._buffered--

      if (this._byteIndex >= this._buffer[this._bufferIndex].byteLength) {
        this._bufferIndex++
        this._byteIndex = 0
      }

      switch (this._state) {
        case FIRST_TOKEN: {
          this._checkHeaderSize()

          if (byte === SP) {
            const token = this._buildString()

            if (token.length === 0) throw errors.INVALID_MESSAGE()

            this._isResponse = token.startsWith('HTTP/')

            if (this._isResponse) {
              if (token !== 'HTTP/1.0' && token !== 'HTTP/1.1') {
                throw errors.INVALID_MESSAGE()
              }

              this._version = token
              this._state = STATUS_CODE
            } else {
              this._method = token
              this._state = REQUEST_URL
            }
          } else if (byte === CR) {
            throw errors.INVALID_MESSAGE()
          } else if (isTokenByte(byte)) {
            this._accumulator.push(byte)
          } else if (
            byte === 0x2f &&
            this._accumulator.length === 4 &&
            this._accumulator[0] === 0x48 &&
            this._accumulator[1] === 0x54 &&
            this._accumulator[2] === 0x54 &&
            this._accumulator[3] === 0x50
          ) {
            this._accumulator.push(byte)
          } else {
            throw errors.INVALID_MESSAGE()
          }

          break
        }

        case REQUEST_URL: {
          this._checkHeaderSize()

          if (byte === SP) {
            this._url = this._buildString()

            if (this._url.length === 0) throw errors.INVALID_MESSAGE()

            this._state = REQUEST_VERSION
          } else if (byte === CR) {
            throw errors.INVALID_MESSAGE()
          } else if (byte >= 0x21 && byte !== 0x7f) {
            this._accumulator.push(byte)
          } else {
            throw errors.INVALID_MESSAGE()
          }

          break
        }

        case REQUEST_VERSION: {
          this._checkHeaderSize()

          if (byte === CR) {
            this._version = this._buildString()

            if (this._version !== 'HTTP/1.0' && this._version !== 'HTTP/1.1') {
              throw errors.INVALID_MESSAGE()
            }

            this._state = FIRST_LINE_LF
          } else if (byte >= 0x21 && byte !== 0x7f) {
            this._accumulator.push(byte)
          } else {
            throw errors.INVALID_MESSAGE()
          }

          break
        }

        case STATUS_CODE: {
          this._checkHeaderSize()

          if (byte === SP) {
            if (this._accumulator.length === 0) throw errors.INVALID_MESSAGE()

            let code = 0

            for (let i = 0, n = this._accumulator.length; i < n; i++) {
              code = code * 10 + this._accumulator[i]
            }

            this._accumulator = []

            if (code < 100 || code > 999) throw errors.INVALID_MESSAGE()

            this._code = code
            this._state = STATUS_REASON
          } else if (byte >= ZERO && byte <= NINE) {
            this._accumulator.push(byte - ZERO)
          } else {
            throw errors.INVALID_MESSAGE()
          }

          break
        }

        case STATUS_REASON: {
          this._checkHeaderSize()

          if (byte === CR) {
            this._reason = this._buildString()
            this._state = FIRST_LINE_LF
          } else if (isFieldByte(byte)) {
            this._accumulator.push(byte)
          } else {
            throw errors.INVALID_MESSAGE()
          }

          break
        }

        case FIRST_LINE_LF: {
          if (byte !== LF) throw errors.INVALID_MESSAGE()

          this._headers = Object.create(null)
          this._headerCount = 0
          this._state = HEADER_START

          break
        }

        case HEADER_START: {
          this._checkHeaderSize()

          if (byte === CR) {
            this._state = HEADER_END_LF
          } else if (byte !== COLON && isTokenByte(byte)) {
            this._accumulator.push(byte >= UPPER_A && byte <= UPPER_Z ? byte + 0x20 : byte)
            this._state = HEADER_NAME
          } else {
            throw errors.INVALID_HEADER()
          }

          break
        }

        case HEADER_NAME: {
          this._checkHeaderSize()

          if (byte === COLON) {
            this._headerName = this._buildString()
            this._state = HEADER_VALUE_WS
          } else if (byte !== COLON && isTokenByte(byte)) {
            this._accumulator.push(byte >= UPPER_A && byte <= UPPER_Z ? byte + 0x20 : byte)
          } else {
            throw errors.INVALID_HEADER()
          }

          break
        }

        case HEADER_VALUE_WS: {
          this._checkHeaderSize()

          if (byte === SP || byte === TAB) break

          if (byte === CR) {
            this._storeHeader(this._headerName, '')
            this._headerName = ''
            this._state = HEADER_LINE_LF

            break
          }

          if (!isFieldByte(byte)) throw errors.INVALID_HEADER()

          this._accumulator.push(byte)
          this._state = HEADER_VALUE

          break
        }

        case HEADER_VALUE: {
          this._checkHeaderSize()

          if (byte === CR) {
            this._storeHeader(this._headerName, this._buildString())
            this._headerName = ''
            this._state = HEADER_LINE_LF
          } else if (isFieldByte(byte)) {
            this._accumulator.push(byte)
          } else {
            throw errors.INVALID_HEADER()
          }

          break
        }

        case HEADER_LINE_LF: {
          if (byte !== LF) throw errors.INVALID_HEADER()

          this._state = HEADER_START

          break
        }

        case HEADER_END_LF: {
          if (byte !== LF) throw errors.INVALID_MESSAGE()

          const headers = { ...this._headers }

          if (this._isResponse) {
            yield {
              type: constants.RESPONSE,
              version: this._version,
              code: this._code,
              reason: this._reason,
              headers
            }
          } else {
            if (this._version === 'HTTP/1.1' && !('host' in headers)) {
              throw errors.INVALID_HEADER("Header 'Host' is missing")
            }

            yield {
              type: constants.REQUEST,
              version: this._version,
              method: this._method,
              url: this._url,
              headers
            }
          }

          const transferEncoding = headers['transfer-encoding']
          const contentLength = headers['content-length']

          if (transferEncoding) {
            const encodings = transferEncoding.split(',')

            let chunkedCount = 0

            for (let i = 0, n = encodings.length; i < n; i++) {
              if (encodings[i].trim().toLowerCase() === 'chunked') chunkedCount++
            }

            const lastEncoding = encodings[encodings.length - 1].trim().toLowerCase()

            if (lastEncoding !== 'chunked') {
              throw errors.INVALID_MESSAGE("'Transfer-Encoding' must end with 'chunked'")
            }

            if (chunkedCount > 1) {
              throw errors.INVALID_MESSAGE(
                "'chunked' must not appear more than once in 'Transfer-Encoding'"
              )
            }

            if (contentLength) {
              throw errors.INVALID_MESSAGE(
                "Conflicting 'Content-Length' and 'Transfer-Encoding' headers"
              )
            }

            this._state = CHUNK_SIZE
            this._headerSize = 0

            continue
          }

          if (contentLength) {
            if (contentLength.length === 0) throw errors.INVALID_CONTENT_LENGTH()

            let length = 0

            for (let i = 0, n = contentLength.length; i < n; i++) {
              const c = contentLength.charCodeAt(i)

              if (c < ZERO || c > NINE) throw errors.INVALID_CONTENT_LENGTH()

              length = length * 10 + (c - ZERO)
            }

            if (!Number.isSafeInteger(length) || length < 0) {
              throw errors.INVALID_CONTENT_LENGTH()
            }

            if (length === 0) {
              this._state = FIRST_TOKEN
              this._headerSize = 0

              yield { type: constants.END }
            } else {
              this._state = BODY
              this._remaining = length
              this._headerSize = 0
            }
          } else {
            this._state = FIRST_TOKEN
            this._headerSize = 0

            yield { type: constants.END }
          }

          break
        }

        case CHUNK_SIZE: {
          if (byte === CR || byte === 0x3b) {
            if (this._accumulator.length === 0) throw errors.INVALID_CHUNK_LENGTH()

            let length = 0

            for (let i = 0, n = this._accumulator.length; i < n; i++) {
              length = length * 16 + this._accumulator[i]
            }

            this._accumulator = []

            if (!Number.isSafeInteger(length)) throw errors.INVALID_CHUNK_LENGTH()

            if (byte === 0x3b) {
              this._remaining = length
              this._state = CHUNK_EXTENSION
            } else if (length === 0) {
              this._state = LAST_CHUNK_LF
            } else {
              this._remaining = length + 2
              this._state = CHUNK_SIZE_LF
            }
          } else if (isHex(byte)) {
            if (this._accumulator.length >= MAX_CHUNK_SIZE_LENGTH) {
              throw errors.INVALID_CHUNK_LENGTH()
            }

            this._accumulator.push(hexValue(byte))
          } else {
            throw errors.INVALID_CHUNK_LENGTH()
          }

          break
        }

        case CHUNK_EXTENSION: {
          this._checkHeaderSize()

          if (byte === CR) {
            if (this._remaining === 0) {
              this._state = LAST_CHUNK_LF
            } else {
              this._remaining += 2
              this._state = CHUNK_SIZE_LF
            }
          } else if (!isFieldByte(byte)) {
            throw errors.INVALID_CHUNK_LENGTH()
          }

          break
        }

        case CHUNK_SIZE_LF: {
          if (byte !== LF) throw errors.INVALID_CHUNK_LENGTH()

          this._state = CHUNK_DATA

          break
        }

        case LAST_CHUNK_LF: {
          if (byte !== LF) throw errors.INVALID_CHUNK_LENGTH()

          this._state = TRAILER_CR

          break
        }

        case TRAILER_CR: {
          if (byte !== CR) throw errors.INVALID_MESSAGE()

          this._state = TRAILER_LF

          break
        }

        case TRAILER_LF: {
          if (byte !== LF) throw errors.INVALID_MESSAGE()

          this._state = FIRST_TOKEN
          this._headerSize = 0

          yield { type: constants.END }

          break
        }

        default:
          throw errors.INVALID_MESSAGE()
      }
    }
  }
}

exports.constants = constants

const TOKEN_BYTES = Buffer.from([
  // 0x00-0x1f (control characters) + 0x20 (space)
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  // 0x21-0x41: ! " # $ % & ' ( ) * + , - . / 0-9 : ; < = > ? @ A
  1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1,
  // 0x42-0x62: B-Z [ \ ] ^ _ ` a b
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1,
  // 0x63-0x7f: c-z { | } ~ DEL
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0
])

function isTokenByte(b) {
  return TOKEN_BYTES[b] === 1
}

function isFieldByte(b) {
  return b === TAB || (b >= 0x20 && b <= 0x7e)
}

function isHex(b) {
  return (
    (b >= ZERO && b <= NINE) || (b >= UPPER_A && b <= UPPER_F) || (b >= LOWER_A && b <= LOWER_F)
  )
}

function hexValue(b) {
  if (b >= ZERO && b <= NINE) return b - ZERO
  if (b >= UPPER_A && b <= UPPER_F) return b - UPPER_A + 10
  return b - LOWER_A + 10
}
module.exports = class HTTPParserError extends Error {
  constructor(msg, fn = HTTPParserError, code = fn.name) {
    super(`${code}: ${msg}`)

    this.code = code

    if (Error.captureStackTrace) Error.captureStackTrace(this, fn)
  }

  get name() {
    return 'HTTPParserError'
  }

  static INVALID_MESSAGE(msg = 'Invalid HTTP message') {
    return new HTTPParserError(msg, HTTPParserError.INVALID_MESSAGE)
  }

  static INVALID_HEADER(msg = 'Invalid HTTP header') {
    return new HTTPParserError(msg, HTTPParserError.INVALID_HEADER)
  }

  static INVALID_CONTENT_LENGTH(msg = 'Invalid HTTP Content-Length') {
    return new HTTPParserError(msg, HTTPParserError.INVALID_CONTENT_LENGTH)
  }

  static INVALID_CHUNK_LENGTH(msg = 'Invalid HTTP chunk length') {
    return new HTTPParserError(msg, HTTPParserError.INVALID_CHUNK_LENGTH)
  }
}
{
  "name": "bare-http-parser",
  "version": "1.1.5",
  "description": "Streaming HTTP request and response parser for Bare",
  "exports": {
    "./package": "./package.json",
    ".": "./index.js",
    "./errors": "./lib/errors.js"
  },
  "files": [
    "index.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-http-parser.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-http-parser/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-http-parser#readme",
  "devDependencies": {
    "brittle": "^3.3.0",
    "lunte": "^1.8.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  }
}
exports.IncomingMessage = require('./lib/incoming-message')
exports.OutgoingMessage = require('./lib/outgoing-message')

exports.Agent = require('./lib/agent')
exports.globalAgent = exports.Agent.global

exports.Server = require('./lib/server')
exports.ServerResponse = require('./lib/server-response')
exports.ServerConnection = require('./lib/server-connection')

exports.ClientRequest = require('./lib/client-request')
exports.ClientConnection = require('./lib/client-connection')

exports.constants = require('./lib/constants')
exports.errors = require('./lib/errors')

exports.METHODS = Object.values(exports.constants.method) // For Node.js compatibility
exports.STATUS_CODES = exports.constants.status // For Node.js compatibility

exports.createServer = function createServer(opts, onrequest) {
  return new exports.Server(opts, onrequest)
}

exports.request = function request(url, opts, onresponse) {
  if (typeof opts === 'function') {
    onresponse = opts
    opts = {}
  }

  if (typeof url === 'string') url = new URL(url)

  if (isURL(url)) {
    opts = opts ? { ...url, ...opts } : { ...url }

    opts.host = url.hostname
    opts.path = url.pathname + url.search
    opts.port = url.port ? parseInt(url.port, 10) : defaultPort(url)
  } else {
    opts = url ? { ...url } : {}

    // For Node.js compatibility
    opts.host = opts.hostname || opts.host
    opts.port = typeof opts.port === 'string' ? parseInt(opts.port, 10) : opts.port
  }

  return new exports.ClientRequest(opts, onresponse)
}

exports.get = function get(url, opts, onresponse) {
  const req = exports.request(url, opts, onresponse)
  req.end()
  return req
}

// https://url.spec.whatwg.org/#default-port
function defaultPort(url) {
  switch (url.protocol) {
    case 'ftp:':
      return 21
    case 'http:':
    case 'ws:':
      return 80
    case 'https:':
    case 'wss:':
      return 443
  }

  return null
}

// https://url.spec.whatwg.org/#api
function isURL(url) {
  return (
    url !== null &&
    typeof url === 'object' &&
    typeof url.protocol === 'string' &&
    typeof url.hostname === 'string' &&
    typeof url.pathname === 'string' &&
    typeof url.search === 'string'
  )
}
const EventEmitter = require('bare-events')
const tcp = require('bare-tcp')
const HTTPClientConnection = require('./client-connection')
const errors = require('./errors')

class HTTPSocketSet {
  constructor() {
    this._sockets = new Map()
    this._size = 0
  }

  get size() {
    return this._size
  }

  add(name, socket) {
    const sockets = this._sockets.get(name)

    this._size++

    if (sockets === undefined) this._sockets.set(name, [socket])
    else sockets.push(socket)
  }

  pop(name) {
    const sockets = this._sockets.get(name)
    if (sockets === undefined || sockets.length === 0) return null

    this._size--

    const last = sockets.pop()

    if (sockets.length === 0) this._sockets.delete(name)

    return last
  }

  delete(name, socket) {
    const sockets = this._sockets.get(name)
    if (sockets === undefined) return

    const i = sockets.indexOf(socket)
    if (i === -1) return

    this._size--

    const last = sockets.pop()
    if (last !== socket) sockets[i] = last

    if (sockets.length === 0) this._sockets.delete(name)
  }

  *sockets() {
    for (const sockets of this._sockets.values()) {
      yield* sockets
    }
  }

  *[Symbol.iterator]() {
    for (const [name, sockets] of this._sockets) {
      for (const socket of sockets) yield [name, socket]
    }
  }
}

class HTTPAgent extends EventEmitter {
  constructor(opts = {}) {
    super()

    const { keepAlive = false, keepAliveMsecs = 1000, defaultPort = 80 } = opts

    this._suspended = false
    this._resuming = null

    this._sockets = new HTTPSocketSet()
    this._freeSockets = new HTTPSocketSet()

    this._keepAlive = typeof keepAlive === 'number' ? keepAlive : keepAlive ? keepAliveMsecs : -1
    this._defaultPort = defaultPort

    this._opts = { ...opts }
  }

  get suspended() {
    return this._suspended
  }

  get resumed() {
    return this._resuming ? this._resuming.promise : null
  }

  get sockets() {
    return this._sockets.sockets()
  }

  get freeSockets() {
    return this._freeSockets.sockets()
  }

  get defaultPort() {
    return this._defaultPort
  }

  createConnection(opts) {
    if (this._suspended) throw errors.AGENT_SUSPENDED()

    return tcp.createConnection(opts)
  }

  reuseSocket(socket, req) {
    socket.ref()
  }

  keepSocketAlive(socket) {
    if (this._keepAlive === -1) return false

    socket.setKeepAlive(true, this._keepAlive)
    socket.unref()

    return true
  }

  getName(opts) {
    return `${opts.host}:${opts.port}`
  }

  addRequest(req, opts) {
    opts = { ...opts, ...this._opts }

    const name = this.getName(opts)

    let socket = this._freeSockets.pop(name)

    if (socket) this.reuseSocket(socket, req)
    else {
      const agent = this

      socket = this.createConnection(opts)

      socket
        .on('error', noop) // someone needs to handle it
        .on('free', onfree)
        .on('end', onremove)
        .on('finish', onremove)
        .on('close', onremove)
        .on('timeout', ontimeout)

      function onfree() {
        if (socket.destroyed) return

        if (agent.keepSocketAlive(socket)) {
          agent._freeSockets.add(name, socket)
        } else {
          socket.end()
        }

        agent.emit('free', socket)
      }

      function onremove() {
        socket.off('free', onfree)

        agent._sockets.delete(name, socket)
        agent._freeSockets.delete(name, socket)

        if (agent._sockets.size === 0) HTTPAgent._agents.delete(agent)
      }

      function ontimeout() {
        socket.destroy()

        agent._freeSockets.delete(name, socket)
      }
    }

    if (this._sockets.size === 0) HTTPAgent._agents.add(this)

    this._sockets.add(name, socket)

    req._socket = socket

    const connection = HTTPClientConnection.from(socket, opts)

    connection._req = req
  }

  suspend() {
    if (this._suspended) return

    this._resuming = Promise.withResolvers()
    this._suspended = true

    this.destroy()
  }

  resume() {
    if (this._resuming === null) return

    this._resuming.resolve()
    this._resuming = null
    this._suspended = false
  }

  destroy() {
    for (const socket of this._sockets.sockets()) socket.destroy()
  }

  static _agents = new Set()

  static _onidle() {
    for (const agent of this._agents) {
      agent.destroy()
    }
  }
}

HTTPAgent.global = new HTTPAgent({ keepAlive: 1000, timeout: 5000 })

module.exports = HTTPAgent

Bare.on('idle', HTTPAgent._onidle.bind(HTTPAgent))

function noop() {}
const HTTPParser = require('bare-http-parser')
const HTTPIncomingMessage = require('./incoming-message')
const errors = require('./errors')

const {
  constants: { RESPONSE, DATA, END }
} = HTTPParser

const EMPTY = Buffer.alloc(0)

module.exports = class HTTPClientConnection {
  static _connections = new WeakMap()

  static for(socket) {
    return this._connections.get(socket) || null
  }

  static from(socket, opts) {
    return this.for(socket) || new this(socket, opts)
  }

  constructor(socket, opts = {}) {
    const { IncomingMessage = HTTPIncomingMessage } = opts

    this._socket = socket

    this._req = null
    this._res = null

    this._IncomingMessage = IncomingMessage

    this._parser = new HTTPParser()
    this._idle = true

    this._onerror = this._onerror.bind(this)
    this._onclose = this._onclose.bind(this)
    this._onend = this._onend.bind(this)
    this._ondata = this._ondata.bind(this)
    this._ondrain = this._ondrain.bind(this)
    this._ontimeout = this._ontimeout.bind(this)

    socket
      .on('error', this._onerror)
      .on('close', this._onclose)
      .on('end', this._onend)
      .on('data', this._ondata)
      .on('drain', this._ondrain)
      .on('timeout', this._ontimeout)

    HTTPClientConnection._connections.set(socket, this)
  }

  get socket() {
    return this._socket
  }

  get req() {
    return this._req
  }

  get res() {
    return this._res
  }

  get idle() {
    return this._idle
  }

  _onerror(err) {
    if (this._req) this._req.destroy(err)
  }

  _onclose() {
    if (this._req) this._req.destroy()
  }

  _onend() {
    if (this._req) this._req.destroy(errors.CONNECTION_LOST())
  }

  _ondata(data) {
    this._idle = false

    try {
      for (const op of this._parser.push(data)) {
        switch (op.type) {
          case RESPONSE:
            this._req.on('close', () => {
              this._req = null
            })

            this._res = new this._IncomingMessage(this._socket, {
              headers: op.headers,
              statusCode: op.code,
              statusMessage: op.reason
            })

            this._res.on('close', () => {
              this._res = null
              this._idle = true

              this._socket.emit('free')
            })

            if (op.headers.connection && op.headers.connection.toLowerCase() === 'upgrade') {
              return this._onupgrade(this._parser.end())
            }

            this._req.emit('response', this._res)
            break

          case DATA:
            this._res.push(op.data)
            break

          case END:
            if (this._res) {
              this._res._socket = null
              this._res.push(null)
            }

            if (this._req) {
              this._req._socket = null
              this._req.destroy()
            }
            break
        }
      }
    } catch (err) {
      this._socket.destroy(err)
    }
  }

  _onupgrade(data) {
    this._detach()

    const res = this._res
    const req = this._req

    res._upgrade = req._upgrade = true

    const upgraded = req.emit('upgrade', res, this._socket, data || EMPTY)

    res.push(null)
    req.destroy()

    if (!upgraded) this._socket.destroy()
  }

  _ontimeout() {
    if (this._req) this._req.emit('timeout')
  }

  _ondrain() {
    if (this._req) this._req._continueWrite()
  }

  _detach() {
    this._socket
      .off('error', this._onerror)
      .off('close', this._onclose)
      .off('end', this._onend)
      .off('data', this._ondata)
      .off('drain', this._ondrain)
      .off('timeout', this._ontimeout)

    HTTPClientConnection._connections.delete(this._socket)
  }
}
const HTTPAgent = require('./agent')
const HTTPOutgoingMessage = require('./outgoing-message')
const validate = require('./validate')

const CHUNK_DELIMITER = Buffer.from('\r\n')
const CHUNK_TERMINATOR = Buffer.from('0\r\n\r\n')

module.exports = class HTTPClientRequest extends HTTPOutgoingMessage {
  constructor(opts = {}, onresponse = null) {
    if (typeof opts === 'function') {
      onresponse = opts
      opts = {}
    }

    opts = opts ? { ...opts } : {}

    const agent = opts.agent === false ? new HTTPAgent() : opts.agent || HTTPAgent.global
    const method = opts.method || 'GET'
    const path = opts.path || '/'
    const defaultPort = opts.defaultPort || (agent && agent.defaultPort) || 80
    const host = (opts.host = opts.host || 'localhost')
    const port = (opts.port = opts.port || defaultPort)
    const headers = { host: hostHeader(host, port, defaultPort), ...opts.headers }

    validate.validateMethod(method)
    validate.validatePath(path)

    for (const name of Object.keys(headers)) {
      const n = name.toLowerCase()

      validate.validateHeaderName(n)
      validate.validateHeaderValue(n, headers[name])
    }

    super()

    agent.addRequest(this, opts)

    this._headers = headers
    this._method = method
    this._path = path

    this._chunked = method !== 'GET' && method !== 'HEAD'

    this._pendingWrite = null
    this._pendingFinal = null

    if (onresponse) this.once('response', onresponse)
  }

  get method() {
    return this._method
  }

  get path() {
    return this._path
  }

  // For Node.js compatibility
  abort() {
    return this.destroy()
  }

  _header() {
    validate.validateMethod(this._method)
    validate.validatePath(this._path)

    let h = `${this._method} ${this._path} HTTP/1.1\r\n`

    let upgrade = false

    for (const name of Object.keys(this._headers)) {
      const n = name.toLowerCase()
      const v = this._headers[name]

      validate.validateHeaderName(n)
      validate.validateHeaderValue(n, v)

      if (n === 'content-length') this._chunked = false
      if (n === 'connection' && v && v.toLowerCase() === 'upgrade') upgrade = true

      h += `${httpCase(n)}: ${v}\r\n`
    }

    if (upgrade) this._chunked = false

    if (this._chunked) h += 'Transfer-Encoding: chunked\r\n'

    h += '\r\n'

    return h
  }

  _write(data, encoding, cb) {
    if (this._headersSent === false) this.flushHeaders()

    if (this._chunked) {
      this._socket.write(Buffer.from(data.byteLength.toString(16)))
      this._socket.write(CHUNK_DELIMITER)
    }

    let flushed = this._socket.write(data)

    if (this._chunked) flushed = this._socket.write(CHUNK_DELIMITER)

    if (flushed) cb(null)
    else this._pendingWrite = cb
  }

  _final(cb) {
    if (this._headersSent === false) this.flushHeaders()

    if (this._chunked) this._socket.write(CHUNK_TERMINATOR)

    this._pendingFinal = cb
  }

  _predestroy() {
    super._predestroy()

    this._continueWrite()
    this._continueFinal()
  }

  _continueWrite() {
    if (this._pendingWrite === null) return
    const cb = this._pendingWrite
    this._pendingWrite = null
    cb(null)
  }

  _continueFinal() {
    if (this._pendingFinal === null) return
    const cb = this._pendingFinal
    this._pendingFinal = null
    cb(null)
  }
}

function httpCase(n) {
  let s = ''
  for (const part of n.split('-')) {
    s += (s ? '-' : '') + part.slice(0, 1).toUpperCase() + part.slice(1)
  }
  return s
}

function hostHeader(host, port, defaultPort) {
  const i = host.indexOf(':')

  if (i !== -1 && host.includes(':', i + 1) && host.charCodeAt(0) !== 91 /* [ */) {
    host = `[${host}]`
  }

  if (port && +port !== defaultPort) {
    host += ':' + port
  }

  return host
}
module.exports = {
  method: {
    GET: 'GET',
    HEAD: 'HEAD',
    POST: 'POST',
    PUT: 'PUT',
    DELETE: 'DELETE',
    CONNECT: 'CONNECT',
    OPTIONS: 'OPTIONS',
    TRACE: 'TRACE',
    PATCH: 'PATCH'
  },
  status: {
    100: 'Continue',
    101: 'Switching Protocols',
    102: 'Processing',
    103: 'Early Hints',
    200: 'OK',
    201: 'Created',
    202: 'Accepted',
    203: 'Non-Authoritative Information',
    204: 'No Content',
    205: 'Reset Content',
    206: 'Partial Content',
    207: 'Multi-Status',
    208: 'Already Reported',
    226: 'IM Used',
    300: 'Multiple Choices',
    301: 'Moved Permanently',
    302: 'Found',
    303: 'See Other',
    304: 'Not Modified',
    305: 'Use Proxy',
    307: 'Temporary Redirect',
    308: 'Permanent Redirect',
    400: 'Bad Request',
    401: 'Unauthorized',
    402: 'Payment Required',
    403: 'Forbidden',
    404: 'Not Found',
    405: 'Method Not Allowed',
    406: 'Not Acceptable',
    407: 'Proxy Authentication Required',
    408: 'Request Timeout',
    409: 'Conflict',
    410: 'Gone',
    411: 'Length Required',
    412: 'Precondition Failed',
    413: 'Payload Too Large',
    414: 'URI Too Long',
    415: 'Unsupported Media Type',
    416: 'Range Not Satisfiable',
    417: 'Expectation Failed',
    418: "I'm a Teapot",
    421: 'Misdirected Request',
    422: 'Unprocessable Entity',
    423: 'Locked',
    424: 'Failed Dependency',
    425: 'Too Early',
    426: 'Upgrade Required',
    428: 'Precondition Required',
    429: 'Too Many Requests',
    431: 'Request Header Fields Too Large',
    451: 'Unavailable For Legal Reasons',
    500: 'Internal Server Error',
    501: 'Not Implemented',
    502: 'Bad Gateway',
    503: 'Service Unavailable',
    504: 'Gateway Timeout',
    505: 'HTTP Version Not Supported',
    506: 'Variant Also Negotiates',
    507: 'Insufficient Storage',
    508: 'Loop Detected',
    509: 'Bandwidth Limit Exceeded',
    510: 'Not Extended',
    511: 'Network Authentication Required'
  }
}
module.exports = class HTTPError extends Error {
  constructor(msg, fn = HTTPError, code = fn.name) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'HTTPError'
  }

  static NOT_IMPLEMENTED(msg = 'Method not implemented') {
    return new HTTPError(msg, HTTPError.NOT_IMPLEMENTED)
  }

  static CONNECTION_LOST(msg = 'Socket hung up') {
    return new HTTPError(msg, HTTPError.CONNECTION_LOST)
  }

  static AGENT_SUSPENDED(msg = 'Agent is suspended') {
    return new HTTPError(msg, HTTPError.AGENT_SUSPENDED)
  }

  static INVALID_HEADER_NAME(msg = 'Invalid header name') {
    return new HTTPError(msg, HTTPError.INVALID_HEADER_NAME)
  }

  static INVALID_HEADER_VALUE(msg = 'Invalid header value') {
    return new HTTPError(msg, HTTPError.INVALID_HEADER_VALUE)
  }
}
const { Readable } = require('bare-stream')

module.exports = class HTTPIncomingMessage extends Readable {
  constructor(socket = null, opts = {}) {
    super()

    this._socket = socket
    this._upgrade = false
    this._headers = opts.headers || {}

    // Server options
    this._method = opts.method || ''
    this._url = opts.url || ''

    // Client options
    this._statusCode = opts.statusCode || 0
    this._statusMessage = opts.statusMessage || ''
  }

  get socket() {
    return this._socket
  }

  get upgrade() {
    return this._upgrade
  }

  get headers() {
    return this._headers
  }

  set headers(value) {
    this._headers = value
  }

  get method() {
    return this._method
  }

  set method(value) {
    this._method = value
  }

  get url() {
    return this._url
  }

  set url(value) {
    this._url = value
  }

  get statusCode() {
    return this._statusCode
  }

  set statusCode(value) {
    this._statusCode = value
  }

  get statusMessage() {
    return this._statusMessage
  }

  set statusMessage(value) {
    this._statusMessage = value
  }

  get httpVersion() {
    return '1.1'
  }

  getHeader(name) {
    return this._headers[name.toLowerCase()]
  }

  getHeaders() {
    return { ...this._headers }
  }

  hasHeader(name) {
    return name.toLowerCase() in this._headers
  }

  setTimeout(ms, ontimeout) {
    if (ontimeout) this.once('timeout', ontimeout)

    this._socket.setTimeout(ms)

    return this
  }

  _predestroy() {
    if (this._upgrade === false && this._socket !== null) this._socket.destroy()
  }
}
const { Writable } = require('bare-stream')
const errors = require('./errors')
const validate = require('./validate')

module.exports = class HTTPOutgoingMessage extends Writable {
  constructor(socket = null) {
    super()

    this._socket = socket
    this._upgrade = false
    this._headersSent = false
    this._headers = {}
  }

  get socket() {
    return this._socket
  }

  get upgrade() {
    return this._upgrade
  }

  get headersSent() {
    return this._headersSent
  }

  get headers() {
    return this._headers
  }

  set headers(value) {
    if (value) {
      for (const name of Object.keys(value)) {
        const n = name.toLowerCase()

        validate.validateHeaderName(n)
        validate.validateHeaderValue(n, value[name])
      }
    }

    this._headers = value
  }

  getHeader(name) {
    return this._headers[name.toLowerCase()]
  }

  getHeaders() {
    return { ...this._headers }
  }

  hasHeader(name) {
    return name.toLowerCase() in this._headers
  }

  setHeader(name, value) {
    const n = name.toLowerCase()

    validate.validateHeaderName(n)
    validate.validateHeaderValue(n, value)

    this._headers[n] = value
  }

  flushHeaders() {
    if (this._headersSent === true || this._socket === null) return

    this._socket.write(Buffer.from(this._header()))
    this._headersSent = true
  }

  setTimeout(ms, ontimeout) {
    if (ontimeout) this.once('timeout', ontimeout)

    this._socket.setTimeout(ms)

    return this
  }

  _header() {
    throw errors.NOT_IMPLEMENTED()
  }

  _predestroy() {
    if (this._upgrade === false && this._socket !== null) this._socket.destroy()
  }
}
const { isEnded, isFinished, getStreamError } = require('bare-stream')
const HTTPParser = require('bare-http-parser')
const HTTPIncomingMessage = require('./incoming-message')
const HTTPServerResponse = require('./server-response')

const {
  constants: { REQUEST, DATA, END }
} = HTTPParser

const EMPTY = Buffer.alloc(0)

module.exports = class HTTPServerConnection {
  static _connections = new WeakMap()

  static for(socket) {
    return this._connections.get(socket) || null
  }

  constructor(server, socket, opts = {}) {
    const { IncomingMessage = HTTPIncomingMessage, ServerResponse = HTTPServerResponse } = opts

    this._server = server
    this._socket = socket

    this._req = null
    this._res = null

    this._IncomingMessage = IncomingMessage
    this._ServerResponse = ServerResponse

    this._parser = new HTTPParser()
    this._idle = true

    this._onclose = this._onclose.bind(this)
    this._ondata = this._ondata.bind(this)
    this._ondrain = this._ondrain.bind(this)
    this._ontimeout = this._ontimeout.bind(this)

    socket
      .on('error', noop)
      .on('close', this._onclose)
      .on('data', this._ondata)
      .on('drain', this._ondrain)
      .on('timeout', this._ontimeout)

    HTTPServerConnection._connections.set(socket, this)

    if (this._server.timeout) socket.setTimeout(this._server.timeout)
  }

  get server() {
    return this._server
  }

  get socket() {
    return this._socket
  }

  get req() {
    return this._req
  }

  get res() {
    return this._res
  }

  get idle() {
    return this._idle
  }

  _onclose() {
    if (this._req && !isEnded(this._req)) this._req.destroy()
    if (this._res && !isFinished(this._res)) this._res.destroy()

    const err = getStreamError(this._socket)
    if (err) this._socket.destroy(err)
  }

  _ondata(data) {
    this._idle = false

    try {
      for (const op of this._parser.push(data)) {
        switch (op.type) {
          case REQUEST:
            this._req = new this._IncomingMessage(this._socket, {
              headers: op.headers,
              method: op.method,
              url: op.url
            })

            this._req.on('close', () => {
              this._req = null

              this._idle = true

              if (this._server.closing) this._socket.destroy()
            })

            // Eagerly open the request stream
            this._req.resume()
            this._req.pause()

            if (op.headers.connection && op.headers.connection.toLowerCase() === 'upgrade') {
              return this._onupgrade(this._parser.end())
            }

            this._res = new this._ServerResponse(this._socket, this._req)

            this._res.on('close', () => {
              this._res = null
            })

            this._server.emit('request', this._req, this._res)
            break

          case DATA:
            this._req.push(op.data)
            break

          case END:
            if (this._req) {
              this._req._socket = null
              this._req.push(null)
            }
            break
        }
      }
    } catch (err) {
      this._socket.destroy(err)
    }
  }

  _onupgrade(data) {
    this._detach()

    const req = this._req

    req._upgrade = true

    const upgraded = this._server.emit('upgrade', req, this._socket, data || EMPTY)

    req.push(null)

    if (!upgraded) this._socket.destroy()
  }

  _ontimeout() {
    const reqTimeout = this._req && this._req.emit('timeout')
    const resTimeout = this._res && this._res.emit('timeout')
    const serverTimeout = this._server.emit('timeout', this._socket)

    if (!reqTimeout && !resTimeout && !serverTimeout) this._socket.destroy()
  }

  _ondrain() {
    if (this._res) this._res._continueWrite()
  }

  _detach() {
    this._socket
      .off('error', noop)
      .off('close', this._onclose)
      .off('data', this._ondata)
      .off('drain', this._ondrain)
      .off('timeout', this._ontimeout)

    HTTPServerConnection._connections.delete(this._socket)
  }
}

function noop() {}
const { isFinishing } = require('bare-stream')
const HTTPOutgoingMessage = require('./outgoing-message')
const constants = require('./constants')
const validate = require('./validate')

const CHUNK_DELIMITER = Buffer.from('\r\n')
const CHUNK_TERMINATOR = Buffer.from('0\r\n\r\n')

module.exports = class HTTPServerResponse extends HTTPOutgoingMessage {
  constructor(socket, req) {
    super(socket)

    this._req = req

    this._statusCode = 200
    this._statusMessage = null

    this._chunked = true
    this._close = req.headers.connection === 'close'
    this._onlyHeaders = req.method === 'HEAD'

    this._pendingWrite = null
  }

  get req() {
    return this._req
  }

  get statusCode() {
    return this._statusCode
  }

  set statusCode(value) {
    this._statusCode = value
  }

  get statusMessage() {
    return this._statusMessage
  }

  set statusMessage(value) {
    validate.validateStatusMessage(value)

    this._statusMessage = value
  }

  writeHead(statusCode, statusMessage = null, headers = {}) {
    if (typeof statusMessage === 'object' && statusMessage !== null) {
      headers = statusMessage
      statusMessage = null
    }

    if (statusMessage !== null) validate.validateStatusMessage(statusMessage)

    if (headers) {
      for (const name of Object.keys(headers)) {
        const n = name.toLowerCase()

        validate.validateHeaderName(n)
        validate.validateHeaderValue(n, headers[name])
      }
    }

    this._statusCode = statusCode
    this._statusMessage = statusMessage || null

    if (headers) this._headers = { ...this._headers, ...headers }
  }

  _header() {
    const statusMessage =
      this._statusMessage === null ? constants.status[this._statusCode] : this._statusMessage

    validate.validateStatusMessage(statusMessage)

    let h = 'HTTP/1.1 ' + this._statusCode + ' ' + statusMessage + '\r\n'

    for (const name of Object.keys(this._headers)) {
      const n = name.toLowerCase()
      const v = this._headers[name]

      validate.validateHeaderName(n)
      validate.validateHeaderValue(n, v)

      if (n === 'content-length') this._chunked = false
      if (n === 'connection' && v && v.toLowerCase() === 'close') this._close = true

      h += httpCase(n) + ': ' + v + '\r\n'
    }

    if (this._chunked) h += 'Transfer-Encoding: chunked\r\n'

    h += '\r\n'

    return h
  }

  _write(data, encoding, cb) {
    if (this._headersSent === false) {
      if (isFinishing(this)) {
        this.setHeader(
          'Content-Length',
          (data.byteLength + this._writableState.buffered).toString()
        )
      }

      this.flushHeaders()
    }

    if (this._onlyHeaders === true) return cb(null)

    if (this._chunked) {
      this._socket.write(Buffer.from(data.byteLength.toString(16)))
      this._socket.write(CHUNK_DELIMITER)
    }

    let flushed = this._socket.write(data)

    if (this._chunked) flushed = this._socket.write(CHUNK_DELIMITER)

    if (flushed) cb(null)
    else this._pendingWrite = cb
  }

  _final(cb) {
    if (this._headersSent === false) {
      this.setHeader('Content-Length', '0')
      this.flushHeaders()
    }

    if (this._chunked && this._onlyHeaders === false) this._socket.write(CHUNK_TERMINATOR)

    if (this._close) this._socket.end()

    cb(null)
  }

  _predestroy() {
    super._predestroy()

    this._req.destroy()

    this._continueWrite()
  }

  _continueWrite() {
    if (this._pendingWrite === null) return
    const cb = this._pendingWrite
    this._pendingWrite = null
    cb(null)
  }
}

function httpCase(n) {
  let s = ''
  for (const part of n.split('-')) {
    s += (s ? '-' : '') + part.slice(0, 1).toUpperCase() + part.slice(1)
  }
  return s
}
const TCPServer = require('bare-tcp').Server
const HTTPServerConnection = require('./server-connection')

module.exports = class HTTPServer extends TCPServer {
  constructor(opts = {}, onrequest) {
    if (typeof opts === 'function') {
      onrequest = opts
      opts = {}
    }

    super({ allowHalfOpen: false })

    this._timeout = 0

    this.on('connection', (socket) => {
      new HTTPServerConnection(this, socket, opts)
    })

    if (onrequest) this.on('request', onrequest)
  }

  get timeout() {
    return this._timeout || undefined // For Node.js compatibility
  }

  setTimeout(ms = 0, ontimeout) {
    if (ontimeout) this.on('timeout', ontimeout)

    this._timeout = ms

    return this
  }

  close(onclose) {
    super.close(onclose)

    for (const socket of this.connections) {
      const connection = HTTPServerConnection.for(socket)

      if (connection === null || connection.idle) {
        socket.destroy()
      }
    }

    return this
  }
}
const errors = require('./errors')

// RFC 7230 token = 1*tchar
const TOKEN_RE = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/

// Reject characters that would terminate or split the current line
const VALUE_INVALID_RE = /[\r\n\0]/

// Reject control chars and whitespace in the request-target
const PATH_INVALID_RE = /[\r\n\0\s]/

exports.validateHeaderName = function (name) {
  if (typeof name !== 'string' || !TOKEN_RE.test(name)) {
    throw errors.INVALID_HEADER_NAME(`Invalid header name: ${JSON.stringify(name)}`)
  }
}

exports.validateHeaderValue = function (name, value) {
  if (value === undefined || value === null) return
  if (VALUE_INVALID_RE.test(String(value))) {
    throw errors.INVALID_HEADER_VALUE(
      `Invalid character in header value for ${JSON.stringify(name)}`
    )
  }
}

exports.validateStatusMessage = function (value) {
  if (value === undefined || value === null) return
  if (VALUE_INVALID_RE.test(String(value))) {
    throw errors.INVALID_HEADER_VALUE('Invalid character in status message')
  }
}

exports.validatePath = function (value) {
  if (typeof value !== 'string' || value.length === 0 || PATH_INVALID_RE.test(value)) {
    throw errors.INVALID_HEADER_VALUE(`Invalid character in request path: ${JSON.stringify(value)}`)
  }
}

exports.validateMethod = function (value) {
  if (typeof value !== 'string' || !TOKEN_RE.test(value)) {
    throw errors.INVALID_HEADER_NAME(`Invalid HTTP method: ${JSON.stringify(value)}`)
  }
}
{
  "name": "bare-http1",
  "version": "4.5.7",
  "description": "Native HTTP/1 library for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    },
    "./errors": {
      "types": "./lib/errors.d.ts",
      "default": "./lib/errors.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-http1.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-http1/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-http1#readme",
  "dependencies": {
    "bare-events": "^2.6.0",
    "bare-http-parser": "^1.1.1",
    "bare-stream": "^2.10.0",
    "bare-tcp": "^2.2.0"
  },
  "devDependencies": {
    "bare-buffer": "^3.0.2",
    "bare-url": "^2.1.3",
    "brittle": "^3.3.0",
    "lunte": "^1.6.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "bare-buffer": "*",
    "bare-url": "*"
  },
  "peerDependenciesMeta": {
    "bare-buffer": {
      "optional": true
    },
    "bare-url": {
      "optional": true
    }
  }
}
exports.Agent = require('./lib/agent')
exports.globalAgent = exports.Agent.global

exports.Server = require('./lib/server')

exports.ClientRequest = require('./lib/client-request')

exports.createServer = function createServer(opts, onrequest) {
  return new exports.Server(opts, onrequest)
}

exports.request = function request(url, opts, onresponse) {
  if (typeof opts === 'function') {
    onresponse = opts
    opts = {}
  }

  if (typeof url === 'string') url = new URL(url)

  if (isURL(url)) {
    opts = opts ? { ...url, ...opts } : { ...url }

    opts.host = url.hostname
    opts.path = url.pathname + url.search
    opts.port = url.port ? parseInt(url.port, 10) : defaultPort(url)
  } else {
    opts = url ? { ...url } : {}

    // For Node.js compatibility
    opts.host = opts.hostname || opts.host
    opts.port = typeof opts.port === 'string' ? parseInt(opts.port, 10) : opts.port
  }

  return new exports.ClientRequest(opts, onresponse)
}

// https://url.spec.whatwg.org/#default-port
function defaultPort(url) {
  switch (url.protocol) {
    case 'ftp:':
      return 21
    case 'http:':
    case 'ws:':
      return 80
    case 'https:':
    case 'wss:':
      return 443
  }

  return null
}

// https://url.spec.whatwg.org/#api
function isURL(url) {
  return (
    url !== null &&
    typeof url === 'object' &&
    typeof url.protocol === 'string' &&
    typeof url.hostname === 'string' &&
    typeof url.pathname === 'string' &&
    typeof url.search === 'string'
  )
}
const HTTPAgent = require('bare-http1').Agent
const HTTPSSocket = require('./socket')

class HTTPSAgent extends HTTPAgent {
  constructor(opts = {}) {
    super({ defaultPort: 443, ...opts })
  }

  createConnection(opts) {
    return new HTTPSSocket(super.createConnection(opts), opts)
  }
}

HTTPSAgent.global = new HTTPSAgent({ keepAlive: 1000, timeout: 5000 })

module.exports = HTTPSAgent
const HTTPClientRequest = require('bare-http1').ClientRequest
const HTTPSAgent = require('./agent')

module.exports = class HTTPSClientRequest extends HTTPClientRequest {
  constructor(opts = {}, onresponse = null) {
    if (typeof opts === 'function') {
      onresponse = opts
      opts = {}
    }

    opts = opts ? { ...opts } : {}

    opts.agent = opts.agent === false ? new HTTPSAgent() : opts.agent || HTTPSAgent.global

    super(opts, onresponse)
  }
}
const TCPServer = require('bare-tcp').Server
const HTTPServerConnection = require('bare-http1').ServerConnection
const HTTPSSocket = require('./socket')

module.exports = class HTTPSServer extends TCPServer {
  constructor(opts = {}, onrequest) {
    if (typeof opts === 'function') {
      onrequest = opts
      opts = {}
    }

    super({ allowHalfOpen: false })

    this._timeout = 0

    this.on('connection', (socket) => {
      new HTTPServerConnection(this, new HTTPSSocket(socket, { ...opts, isServer: true }), opts)
    })

    if (onrequest) this.on('request', onrequest)
  }

  get timeout() {
    return this._timeout || undefined // For Node.js compatibility
  }

  setTimeout(ms = 0, ontimeout) {
    if (ontimeout) this.on('timeout', ontimeout)

    this._timeout = ms

    return this
  }

  close(onclose) {
    super.close(onclose)

    for (const socket of this.connections) {
      const connection = HTTPServerConnection.for(socket)

      if (connection === null || connection.idle) {
        socket.destroy()
      }
    }

    return this
  }
}
const TLSSocket = require('bare-tls').Socket

module.exports = class HTTPSSocket extends TLSSocket {
  setKeepAlive(...args) {
    this.socket.setKeepAlive(...args)

    return this
  }

  setNoDelay(...args) {
    this.socket.setNoDelay(...args)

    return this
  }

  setTimeout(...args) {
    this.socket.setTimeout(...args)

    return this
  }

  ref() {
    this.socket.ref()

    return this
  }

  unref() {
    this.socket.unref()

    return this
  }
}
{
  "name": "bare-https",
  "version": "3.0.0",
  "description": "HTTPS library for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-https.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-https/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-https#readme",
  "dependencies": {
    "bare-http1": "^4.4.0",
    "bare-tcp": "^2.2.0",
    "bare-tls": "^3.0.0"
  },
  "devDependencies": {
    "bare-fs": "^4.0.0",
    "brittle": "^3.3.0",
    "lunte": "^1.7.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = require.addon()
const ansiEscapes = require('bare-ansi-escapes')
const getType = require('bare-type')
const binding = require('./binding')

const PLAIN_KEY = /^[a-zA-Z_][a-zA-Z_0-9]*$/

const defaultDepth = 2
const defaultBreakLength = 80
const defaultMaxArrayLength = 40

module.exports = exports = function inspect(value, opts = {}) {
  const {
    colors = false,
    depth = defaultDepth,
    breakLength = defaultBreakLength,
    stylize = defaultStylize(colors)
  } = opts

  const references = new InspectRefMap()

  const tree = inspectValue(value, 0, {
    colors,
    depth,
    breakLength,
    stylize,
    references
  })

  return tree.toString()
}

exports.styles = {
  bigint: ansiEscapes.colorYellow,
  boolean: ansiEscapes.colorYellow,
  date: ansiEscapes.colorMagenta,
  module: ansiEscapes.modifierUnderline,
  name: ansiEscapes.modifierReset,
  null: ansiEscapes.modifierBold,
  number: ansiEscapes.colorYellow,
  regexp: ansiEscapes.colorRed,
  special: ansiEscapes.colorCyan,
  string: ansiEscapes.colorGreen,
  symbol: ansiEscapes.colorGreen,
  undefined: ansiEscapes.colorBrightBlack
}

const styles = exports.styles

function defaultStylize(colors) {
  return function stylize(value, style) {
    const color = colors && styles[style]

    if (color) return color + value + ansiEscapes.modifierReset

    return value
  }
}

class InspectRefMap {
  constructor() {
    this.refs = new WeakMap()
    this.ids = new WeakMap()
    this.nextId = 1
  }

  has(object) {
    return this.refs.has(object)
  }

  get(object) {
    return this.refs.get(object) || null
  }

  set(object, ref) {
    this.refs.set(object, ref)
  }

  id(object) {
    let id = this.ids.get(object)
    if (id) return id

    id = this.nextId++
    this.ids.set(object, id)

    return id
  }
}

class InspectNode {
  constructor(depth, length, opts) {
    const { breakLength = defaultBreakLength, breakAlways = false } = opts

    this.depth = depth
    this.length = length
    this.breakLength = breakLength
    this.breakAlways = breakAlways
  }

  pad(n, string) {
    return string.padStart(n, ' ')
  }

  indent(n, string) {
    return '  '.repeat(n) + string
  }
}

class InspectRef extends InspectNode {
  constructor(depth, opts) {
    super(depth, '[circular *]'.length, opts)

    this.refs = opts.references
    this.count = 0
    this.circular = false
    this.color = opts.colors && styles.special
  }

  get id() {
    return this.refs.id(this)
  }

  increment() {
    return ++this.count
  }

  decrement() {
    return --this.count
  }

  toString(opts = {}) {
    const { offset = 0, pad = 0, indent = 0 } = opts

    let value = this.pad(pad, '[circular *' + this.id + ']')

    if (this.color) value = this.color + value + ansiEscapes.modifierReset

    return offset ? value : this.indent(indent, value)
  }
}

class InspectLeaf extends InspectNode {
  constructor(value, color, depth, opts) {
    const length = value.length

    if (value.includes('\n')) {
      value = value.replaceAll('\n', '\n' + '  '.repeat(depth))

      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.value = value
    this.color = opts.colors && color
  }

  toString(opts = {}) {
    const { offset = 0, pad = 0, indent = 0 } = opts

    let value = this.pad(pad, this.value)

    if (this.color) value = this.color + value + ansiEscapes.modifierReset

    return offset ? value : this.indent(indent, value)
  }
}

class InspectPair extends InspectNode {
  constructor(delim, left, right, depth, opts) {
    const length = left.length + delim.length + right.length

    if (left.breakAlways || right.breakAlways) {
      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.delim = delim
    this.left = left
    this.right = right
  }

  toString(opts = {}) {
    const { indent = 0 } = opts

    return this.indent(
      indent,
      this.left +
        this.delim +
        this.right.toString({
          indent,
          offset: this.left.length + this.delim.length
        })
    )
  }
}

class InspectSuspension extends InspectNode {
  constructor(overflow, depth, opts) {
    const label = `... ${overflow} more`

    super(depth, label.length, opts)

    this.label = label
  }

  toString(opts = {}) {
    const { indent = 0 } = opts

    return this.indent(indent, this.label)
  }
}

class InspectSequence extends InspectNode {
  constructor(header, footer, delim, values, ref, depth, opts) {
    const { tabulate = false } = opts

    const length =
      (ref.circular ? '<ref *>'.length + 1 : 0) +
      header.length +
      values.reduce(
        (length, value, i) =>
          length + value.length + (i === 0 ? 0 : delim.length),
        0
      ) +
      footer.length

    if (values.some((value) => value.breakAlways)) {
      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.header = header
    this.footer = footer
    this.delim = delim
    this.values = values
    this.ref = ref
    this.tabulate = tabulate
  }

  toString(opts = {}) {
    const { offset = 0, indent = 0 } = opts

    const split =
      this.breakAlways ||
      (this.values.length &&
        (offset + this.length > this.breakLength ||
          indent * 2 + this.length > this.breakLength))

    let header = this.header

    if (this.ref.circular) {
      header = '<ref *' + this.ref.id + '> ' + header
    }

    if (this.values.length === 0) {
      header = header.trimEnd()
    }

    if (offset === 0) {
      header = this.indent(indent, header)
    }

    if (split) {
      header = header.trimEnd() + '\n'
    }

    let string = header

    let columns = 1
    let pad = 0

    if (this.tabulate) {
      const widest = this.values.reduce(
        (length, value) =>
          value.breakAlways ? length : Math.max(length, value.length),
        0
      )

      if (widest) {
        columns = Math.max(
          columns,
          Math.floor(
            (this.breakLength - indent * 2) / (widest + this.delim.length)
          )
        )

        if (columns > 1) pad = widest
      }
    }

    for (let i = 0, n = this.values.length, offset = 0; i < n; i++) {
      const value = this.values[i]

      if (split) {
        let part

        if (i % columns === 0 || value.breakAlways) {
          part = value.toString({ indent: indent + 1, pad })
        } else {
          part = value.toString({ pad })
        }

        string += part

        if (i < n - 1) {
          if (i % columns === columns - 1 || this.values[i + 1].breakAlways) {
            string += this.delim.trimEnd() + '\n'
          } else {
            string += this.delim
          }
        }
      } else {
        if (i > 0) string += this.delim

        string += value.toString({ offset })

        offset += value.length
      }
    }

    let footer = this.footer

    if (this.values.length === 0) {
      footer = footer.trimStart()
    }

    if (split) {
      string += '\n' + this.indent(indent, footer.trimStart())
    } else {
      string += footer
    }

    return string
  }
}

function inspectValue(value, depth, opts) {
  const type = getType(value)

  if (type.isUndefined()) return inspectUndefined(depth, opts)
  if (type.isNull()) return inspectNull(depth, opts)
  if (type.isBoolean()) return inspectBoolean(value, depth, opts)
  if (type.isNumber()) return inspectNumber(value, depth, opts)
  if (type.isBigInt()) return inspectBigInt(value, depth, opts)
  if (type.isString()) return inspectString(value, depth, opts)
  if (type.isSymbol()) return inspectSymbol(value, depth, opts)
  if (type.isObject()) return inspectObject(type, value, depth, opts)
  if (type.isFunction()) return inspectFunction(type, value, depth, opts)
  if (type.isExternal()) return inspectExternal(value, opts, opts)
}

function inspectUndefined(depth, opts) {
  return new InspectLeaf('undefined', styles.undefined, depth, opts)
}

function inspectNull(depth, opts) {
  return new InspectLeaf('null', styles.null, depth, opts)
}

function inspectBoolean(value, depth, opts) {
  return new InspectLeaf(value.toString(), styles.boolean, depth, opts)
}

function inspectNumber(value, depth, opts) {
  let string

  if (Object.is(value, -0)) {
    string = '-0'
  } else {
    string = value.toString(10)
  }

  return new InspectLeaf(string, styles.number, depth, opts)
}

function inspectBigInt(value, depth, opts) {
  return new InspectLeaf(value.toString(10) + 'n', styles.bigint, depth, opts)
}

const STRING_ESCAPES =
  /[\ud800-\udbff][\udc00-\udfff]|[\u0000-\u001f'\\\ud800-\udfff]/g

function inspectString(value, depth, opts) {
  // https://tc39.es/ecma262/multipage/structured-data.html#sec-quotejsonstring
  const string = value.replace(STRING_ESCAPES, (match) => {
    if (match.length === 2) return match

    switch (match) {
      case "'":
        return "\\'"
      case '\\':
        return '\\\\'
      case '\b':
        return '\\b'
      case '\t':
        return '\\t'
      case '\n':
        return '\\n'
      case '\f':
        return '\\f'
      case '\r':
        return '\\r'
      default:
        return '\\u' + match.charCodeAt(0).toString(16).padStart(4, '0')
    }
  })

  return new InspectLeaf("'" + string + "'", styles.string, depth, opts)
}

function inspectSymbol(value, depth, opts) {
  return new InspectLeaf(value.toString(), styles.symbol, depth, opts)
}

function inspectKey(value, depth, opts) {
  if (PLAIN_KEY.test(value)) {
    return new InspectLeaf(value, null, depth, opts)
  } else {
    return inspectValue(value, depth, opts)
  }
}

function inspectObject(type, object, depth, opts) {
  const refs = opts.references

  let ref = refs.get(object)
  if (ref === null) {
    ref = new InspectRef(depth, opts)
    refs.set(object, ref)
  } else if (ref.count) {
    ref.circular = true
    return ref
  }

  const maxDepth = typeof opts.depth === 'number' ? opts.depth : Infinity

  if (maxDepth < depth) {
    const constructor = object.constructor

    return new InspectLeaf(
      '[' +
        (constructor && constructor.name ? constructor.name : 'Object') +
        ']',
      styles.special,
      depth,
      opts
    )
  }

  const inspect =
    object[Symbol.for('bare.inspect')] ||
    object[Symbol.for('nodejs.util.inspect.custom')]

  if (typeof inspect === 'function') {
    const value = inspect.call(
      object,
      typeof opts.depth === 'number' ? opts.depth - depth : null,
      {
        colors: opts.colors,
        breakLength: opts.breakLength,
        stylize: opts.stylize
      },
      exports
    )

    if (typeof value === 'object' && value !== null) {
      refs.set(value, ref)
    }

    if (typeof value !== 'string') {
      return inspectValue(value, depth, opts)
    }

    return new InspectLeaf(value, null, depth, opts)
  }

  if (type.isArray()) return inspectArray(object, ref, depth, opts)
  if (type.isDate()) return inspectDate(object, ref, depth, opts)
  if (type.isRegExp()) return inspectRegExp(object, ref, depth, opts)
  if (type.isError()) return inspectError(object, ref, depth, opts)
  if (type.isPromise()) return inspectPromise(object, ref, depth, opts)
  if (type.isMap()) return inspectMap(object, ref, depth, opts)
  if (type.isSet()) return inspectSet(object, ref, depth, opts)
  if (type.isWeakMap()) return inspectWeakMap(object, ref, depth, opts)
  if (type.isWeakSet()) return inspectWeakSet(object, ref, depth, opts)
  if (type.isWeakRef()) return inspectWeakRef(object, ref, depth, opts)
  if (type.isArrayBuffer()) return inspectArrayBuffer(object, ref, depth, opts)
  if (type.isSharedArrayBuffer())
    return inspectSharedArrayBuffer(object, ref, depth, opts)
  if (type.isTypedArray()) return inspectTypedArray(object, ref, depth, opts)
  if (type.isDataView()) return inspectDataView(object, ref, depth, opts)

  ref.increment()

  const values = []

  for (const key in object) {
    if (key === 'constructor') continue

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(object[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  let header = '{ '

  const tag = object[Symbol.toStringTag]

  if (tag) header = '[' + tag + '] ' + header

  if (object.constructor) {
    const name = object.constructor.name

    if (name && name !== 'Object') {
      header = object.constructor.name + ' ' + header
    }
  }

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectArray(array, ref, depth, opts) {
  const { maxArrayLength = defaultMaxArrayLength } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxArrayLength, 0)

  for (let i = 0, n = array.length; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(array.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(inspectValue(array[i], depth + 1, opts))
  }

  for (const key of binding.getOwnNonIndexPropertyNames(array)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(array[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  let header = '[ '

  if (array.constructor.name !== 'Array') {
    header = array.constructor.name + '(' + array.length + ') ' + header
  }

  return new InspectSequence(header, ' ]', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectDate(date, ref, depth, opts) {
  return new InspectLeaf(date.toISOString(), styles.date, depth, opts)
}

function inspectRegExp(regExp, ref, depth, opts) {
  return new InspectLeaf(regExp.toString(), styles.regexp, depth, opts)
}

function inspectError(error, ref, depth, opts) {
  let header

  if ('stack' in error) {
    header = error.stack

    if (depth > 0) {
      header = header.replaceAll('\n', '\n' + '  '.repeat(depth))
    }
  } else {
    header = error.toString()
  }

  const builtins = ['cause']

  if (error.name === 'AggregateError') {
    builtins.push('errors')
  } else if (error.name === 'SuppressedError') {
    builtins.push('error', 'suppressed')
  }

  const values = []

  for (const key of builtins) {
    if (key in error === false) continue

    values.push(
      new InspectPair(
        ': ',
        new InspectLeaf('[' + key + ']', null, depth + 1, opts),
        inspectValue(error[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key in error) {
    if (key === 'constructor' || builtins.includes(key)) continue

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(error[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  if (values.length === 0) return new InspectLeaf(header, null, depth, opts)

  return new InspectSequence(
    header + ' {',
    ' }',
    ', ',
    values,
    ref,
    depth,
    opts
  )
}

function inspectPromise(promise, ref, depth, opts) {
  ref.increment()

  const state = binding.getPromiseState(promise)

  const values = []

  switch (state) {
    case 0: // Pending
      values.push(new InspectLeaf('<pending>', styles.special, depth, opts))
      break

    case 1: // Fulfilled
      values.push(inspectValue(binding.getPromiseResult(promise), depth, opts))
      break

    case 2: // Rejected
      values.push(
        new InspectLeaf('<rejected>', styles.special, depth, opts),
        inspectValue(binding.getPromiseResult(promise), depth, opts)
      )
  }

  ref.decrement()

  const header = promise.constructor.name + ' { '

  return new InspectSequence(header, ' }', ' ', values, ref, depth, opts)
}

function inspectMap(map, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxMapLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = maxMapLength

  for (const entry of map) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(map.size - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )
      break
    }

    values.push(
      new InspectPair(
        ' => ',
        inspectValue(entry[0], depth + 1, opts),
        inspectValue(entry[1], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key in map) {
    if (key === 'constructor') continue

    const value = inspectValue(map[key], depth + 1, opts)

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        value,
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = map.constructor.name + '(' + map.size + ') { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectSet(set, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxSetLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = maxSetLength

  for (const entry of set) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(set.size - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )
      break
    }

    values.push(inspectValue(entry, depth + 1, opts))
  }

  for (const key in set) {
    if (key === 'constructor') continue

    const value = inspectValue(set[key], depth + 1, opts)

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        value,
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = set.constructor.name + '(' + set.size + ') { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectWeakMap(weakMap, ref, depth, opts) {
  const header = weakMap.constructor.name + ' { '

  return new InspectSequence(
    header,
    ' }',
    ' ',
    [new InspectLeaf('<items unknown>', styles.special, depth + 1, opts)],
    ref,
    depth,
    opts
  )
}

function inspectWeakSet(weakSet, ref, depth, opts) {
  const header = weakSet.constructor.name + ' { '

  return new InspectSequence(
    header,
    ' }',
    ' ',
    [new InspectLeaf('<items unknown>', styles.special, depth + 1, opts)],
    ref,
    depth,
    opts
  )
}

function inspectWeakRef(weakRef, ref, depth, opts) {
  const target = weakRef.deref()

  let value

  if (target === undefined) {
    value = new InspectLeaf('<cleared>', styles.special, depth + 1, opts)
  } else {
    value = inspectValue(target, depth + 1, opts)
  }

  const header = weakRef.constructor.name + ' { '

  return new InspectSequence(header, ' }', ' ', [value], ref, depth, opts)
}

function inspectArrayBuffer(arrayBuffer, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(arrayBuffer[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = arrayBuffer.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectSharedArrayBuffer(sharedArrayBuffer, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(sharedArrayBuffer[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = sharedArrayBuffer.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectTypedArray(typedArray, ref, depth, opts) {
  if (Buffer.isBuffer(typedArray)) {
    return inspectBuffer(typedArray, ref, depth, opts)
  }

  const {
    maxArrayLength = defaultMaxArrayLength,
    maxTypedArrayLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxTypedArrayLength, 0)

  for (let i = 0, n = typedArray.length; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(typedArray.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(inspectValue(typedArray[i], depth + 1, opts))
  }

  for (const key of binding.getOwnNonIndexPropertyNames(typedArray)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(typedArray[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = typedArray.constructor.name + '(' + typedArray.length + ') [ '

  return new InspectSequence(header, ' ]', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectBuffer(buffer, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxBufferLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxBufferLength, 0)

  for (let i = 0, n = buffer.byteLength; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(buffer.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(
      new InspectLeaf(
        buffer[i].toString(16).padStart(2, '0'),
        null,
        depth + 1,
        opts
      )
    )
  }

  for (const key of binding.getOwnNonIndexPropertyNames(buffer)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(buffer[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  return new InspectSequence('<Buffer ', '>', ' ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectDataView(dataView, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength', 'byteOffset', 'buffer']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(dataView[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key of binding.getOwnNonIndexPropertyNames(dataView)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(dataView[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = dataView.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectFunction(type, fn, depth, opts) {
  if (fn.toString().startsWith('class')) return inspectClass(fn, depth, opts)

  let tag = 'function'

  if (type.isGeneratorFunction()) tag = 'generator ' + tag
  if (type.isAsyncFunction()) tag = 'async ' + tag

  return new InspectLeaf(
    '[' + tag + ' ' + (fn.name ? fn.name : '(anonymous)') + ']',
    styles.special,
    depth,
    opts
  )
}

function inspectClass(ctor, depth, opts) {
  return new InspectLeaf(
    '[class ' + (ctor.name ? ctor.name : '(anonymous)') + ']',
    styles.special,
    depth,
    opts
  )
}

function inspectExternal(external, depth, opts) {
  return new InspectLeaf(
    '[external 0x' + binding.getExternal(external).toString(16) + ']',
    styles.special,
    depth,
    opts
  )
}
{
  "name": "bare-inspect",
  "version": "3.1.4",
  "description": "Inspect objects as strings for debugging",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-inspect.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-inspect/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-inspect#readme",
  "engines": {
    "bare": ">=1.18.0"
  },
  "dependencies": {
    "bare-ansi-escapes": "^2.1.0",
    "bare-type": "^1.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
class MIME {
  constructor(type, subtype, parameters = new Map()) {
    this._type = type
    this._subtype = subtype
    this._parameters = parameters
  }

  // https://mimesniff.spec.whatwg.org/#type
  get type() {
    return this._type
  }

  // https://mimesniff.spec.whatwg.org/#subtype
  get subtype() {
    return this._subtype
  }

  // https://mimesniff.spec.whatwg.org/#parameters
  get parameters() {
    return this._parameters
  }
}

module.exports = exports = MIME

// https://mimesniff.spec.whatwg.org/#parse-a-mime-type
exports.parse = function parse(input) {
  // 1.
  input = input.replace(httpWhitespaceLeadingAndTrailing, '')

  // 2.
  let position = 0

  // 3.
  let type = ''

  while (position < input.length && input[position] !== '/') {
    type += input[position++]
  }

  // 4.
  if (type === '' || !isHTTPTokenCodePoints(type)) return null

  // 5.
  if (position >= input.length) return null

  // 6.
  position++

  // 7.
  let subtype = ''

  while (position < input.length && input[position] !== ';') {
    subtype += input[position++]
  }

  // 8.
  subtype = subtype.replace(httpWhitespaceTrailing, '')

  // 9.
  if (subtype === '' || !isHTTPTokenCodePoints(subtype)) return null

  // 10.
  const mimeType = new MIME(type.toLowerCase(), subtype.toLowerCase())

  // 11.
  while (position < input.length) {
    // 11.1.
    position++

    // 11.2.
    while (position < input.length && httpWhitespace.test(input[position])) {
      position++
    }

    // 11.3.
    let parameterName = ''

    while (position < input.length && input[position] !== ';' && input[position] !== '=') {
      parameterName += input[position++]
    }

    // 11.4.
    parameterName = parameterName.toLowerCase()

    // 11.5.
    if (position < input.length && input[position] === ';') continue

    // 11.6.
    if (position >= input.length) break

    // 11.7.
    position++

    // 11.8.
    let parameterValue

    // 11.9.
    if (position < input.length && input[position] === '"') {
      // 11.9.1.
      parameterValue = collectHTTPQuotedString(input, position)
      position = parameterValue.position
      parameterValue = parameterValue.value

      // 11.9.2.
      while (position < input.length && input[position] !== ';') {
        position++
      }
    } else {
      // 11.10.
      parameterValue = ''

      while (position < input.length && input[position] !== ';') {
        parameterValue += input[position++]
      }

      // 11.10.1.
      parameterValue = parameterValue.replace(httpWhitespaceTrailing, '')

      // 11.10.2.
      if (parameterValue === '') continue
    }

    // 11.11.
    if (
      parameterName !== '' &&
      isHTTPTokenCodePoints(parameterName) &&
      isHTTPQuotedStringTokenCodePoints(parameterValue) &&
      !mimeType._parameters.has(parameterName)
    ) {
      mimeType._parameters.set(parameterName, parameterValue)
    }
  }

  // 12.
  return mimeType
}

// https://fetch.spec.whatwg.org/#http-whitespace
const httpWhitespace = /[\t\n\r ]/
const httpWhitespaceLeadingAndTrailing = /^[\t\n\r ]+|[\t\n\r ]+$/g
const httpWhitespaceTrailing = /[\t\n\r ]+$/

// https://mimesniff.spec.whatwg.org/#http-token-code-point
const httpTokenCodePoints = /^[!#$%&'*+\-.^_`|~A-Za-z0-9]+$/

// https://mimesniff.spec.whatwg.org/#http-quoted-string-token-code-point
const httpQuotedStringTokenCodePoints = /^[\t\x20-\x7e\x80-\xff]*$/

function isHTTPTokenCodePoints(s) {
  return httpTokenCodePoints.test(s)
}

function isHTTPQuotedStringTokenCodePoints(s) {
  return httpQuotedStringTokenCodePoints.test(s)
}

// https://fetch.spec.whatwg.org/#collect-an-http-quoted-string
function collectHTTPQuotedString(input, position) {
  let value = ''

  position++

  while (true) {
    while (position < input.length && input[position] !== '"' && input[position] !== '\\') {
      value += input[position++]
    }

    if (position >= input.length) break

    const quoteOrBackslash = input[position++]

    if (quoteOrBackslash === '\\') {
      if (position >= input.length) {
        value += '\\'
        break
      }
      value += input[position++]
    } else {
      break
    }
  }

  return { value, position }
}
{
  "name": "bare-mime",
  "version": "1.0.0",
  "description": "MIME type parsing for Bare",
  "exports": {
    "./package": "./package.json",
    ".": "./index.js"
  },
  "files": [
    "index.js"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-mime.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-mime/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-mime#readme",
  "devDependencies": {
    "brittle": "^3.3.0",
    "lunte": "^1.6.0",
    "prettier": "^3.3.3",
    "prettier-config-holepunch": "^2.0.0"
  }
}
const EventEmitter = require('bare-events')
const { Duplex } = require('bare-stream')
const tcp = require('bare-tcp')
const pipe = require('bare-pipe')
const constants = require('./lib/constants')

const defaultReadBufferSize = 65536

exports.Socket = class NetSocket extends Duplex {
  constructor(opts = {}) {
    const {
      readBufferSize = defaultReadBufferSize,
      allowHalfOpen = false,
      eagerOpen = false
    } = opts

    super({ eagerOpen, allowHalfOpen })

    this._type = 0
    this._state = 0
    this._socket = null

    this._opts = { readBufferSize, allowHalfOpen, eagerOpen }

    this._pendingOpen = null
    this._pendingWrite = null
    this._pendingFinal = null
    this._pendingDestroy = null
  }

  get connecting() {
    return this._socket !== null && this._socket.connecting
  }

  get pending() {
    return this._socket === null || this._socket.pending
  }

  get timeout() {
    return this._socket === null ? undefined : this._socket.timeout
  }

  get readyState() {
    return this._socket === null ? 'opening' : this._socket.readyState
  }

  get localAddress() {
    return this._socket === null ? undefined : this._socket.localAddress
  }

  get localPort() {
    return this._socket === null ? undefined : this._socket.localPort
  }

  get localFamily() {
    return this._socket === null ? undefined : this._socket.localFamily
  }

  get remoteAddress() {
    return this._socket === null ? undefined : this._socket.remoteAddress
  }

  get remotePort() {
    return this._socket === null ? undefined : this._socket.remotePort
  }

  get remoteFamily() {
    return this._socket === null ? undefined : this._socket.remoteFamily
  }

  connect(...args) {
    let opts = {}
    let onconnect

    if (typeof args[0] === 'string') {
      // connect(path[, onconnect])
      opts.path = args[0]
      onconnect = args[1]
    } else if (typeof args[0] === 'number') {
      // connect(port[, host][, onconnect])
      opts.port = args[0]

      if (typeof args[1] === 'function') {
        onconnect = args[1]
      } else {
        opts.host = args[1]
        onconnect = args[2]
      }
    } else {
      // connect(opts[, onconnect])
      opts = args[0] || {}
      onconnect = args[1]
    }

    opts = { ...opts, ...this._opts }

    if (opts.path) {
      this._attach(constants.type.IPC, pipe.createConnection(opts))
    } else {
      this._attach(constants.type.TCP, tcp.createConnection(opts))
    }

    if (onconnect) this.once('connect', onconnect)

    return this
  }

  setKeepAlive(...args) {
    if (this._socket !== null) this._socket.setKeepAlive(...args)
    return this
  }

  setNoDelay(...args) {
    if (this._socket !== null) this._socket.setNoDelay(...args)
    return this
  }

  setTimeout(...args) {
    if (this._socket !== null) this._socket.setTimeout(...args)
    return this
  }

  ref() {
    this._state &= ~constants.state.UNREFED
    if (this._socket !== null) this._socket.ref()
    return this
  }

  unref() {
    this._state |= constants.state.UNREFED
    if (this._socket !== null) this._socket.unref()
    return this
  }

  _attach(type, socket) {
    this._type = type
    this._socket = socket

    this._socket
      .on('connect', this._onconnect.bind(this))
      .on('timeout', this._ontimeout.bind(this))
      .on('error', this._onerror.bind(this))
      .on('data', this._ondata.bind(this))
      .on('end', this._onend.bind(this))
      .on('finish', this._onfinish.bind(this))
      .on('drain', this._ondrain.bind(this))
      .on('close', this._onclose.bind(this))

    if (this._state & constants.state.UNREFED) this._socket.unref()

    this._continueOpen()

    return this
  }

  _open(cb) {
    if (this._socket !== null) return cb(null)
    this._pendingOpen = cb
  }

  _write(data, encoding, cb) {
    if (this._socket.write(data)) return cb(null)
    this._pendingWrite = cb
  }

  _final(cb) {
    this._socket.end()
    this._pendingFinal = cb
  }

  _destroy(err, cb) {
    if (this._socket === null || this._socket.destroyed) return cb(null)

    this._socket.destroy(err)
    this._pendingDestroy = cb
  }

  _onconnect() {
    this.emit('connect')
  }

  _ontimeout() {
    this.emit('timeout')
  }

  _onerror(err) {
    this.destroy(err)
  }

  _ondata(data) {
    this.push(data)
  }

  _onend() {
    this.push(null)
  }

  _onfinish() {
    this._continueFinal()
  }

  _ondrain() {
    this._continueWrite()
  }

  _onclose() {
    this._continueWrite()
    this._continueFinal()

    if (this._pendingDestroy) this._continueDestroy()
    else this.destroy()
  }

  _continueOpen() {
    if (this._pendingOpen === null) return
    const cb = this._pendingOpen
    this._pendingOpen = null
    cb(null)
  }

  _continueWrite() {
    if (this._pendingWrite === null) return
    const cb = this._pendingWrite
    this._pendingWrite = null
    cb(null)
  }

  _continueFinal() {
    if (this._pendingFinal === null) return
    const cb = this._pendingFinal
    this._pendingFinal = null
    cb(null)
  }

  _continueDestroy() {
    if (this._pendingDestroy === null) return
    const cb = this._pendingDestroy
    this._pendingDestroy = null
    cb(null)
  }
}

exports.Server = class NetServer extends EventEmitter {
  constructor(opts = {}, onconnection) {
    if (typeof opts === 'function') {
      onconnection = opts
      opts = {}
    }

    super()

    const {
      readBufferSize = defaultReadBufferSize,
      allowHalfOpen = false,
      pauseOnConnect = false
    } = opts

    this._type = 0
    this._state = 0
    this._server = null

    this._opts = { readBufferSize, allowHalfOpen, pauseOnConnect }

    if (onconnection) this.on('connection', onconnection)
  }

  get listening() {
    return this._server !== null && this._server.listening
  }

  address() {
    return this._server === null ? null : this._server.address()
  }

  listen(...args) {
    let opts = {}
    let onlistening

    if (typeof args[0] === 'string') {
      // listen(path[, backlog][, onlistening])
      opts.path = args[0]

      if (typeof args[1] === 'function') {
        onlistening = args[1]
      } else {
        opts.backlog = args[1]
        onlistening = args[2]
      }
    } else {
      // listen([port[, host[, backlog]]][, onlistening])
      if (typeof args[0] === 'function') {
        onlistening = args[0]
      } else {
        opts.port = args[0]

        if (typeof args[1] === 'function') {
          onlistening = args[1]
        } else {
          opts.host = args[1]

          if (typeof args[2] === 'function') {
            onlistening = args[2]
          } else {
            opts.backlog = args[2]
            onlistening = args[3]
          }
        }
      }
    }

    opts = { ...opts, ...this._opts }

    if (opts.path) {
      this._attach(constants.type.IPC, pipe.createServer(opts))
    } else {
      this._attach(constants.type.TCP, tcp.createServer(opts))
    }

    this._server.listen(opts)

    if (onlistening) this.once('listening', onlistening)

    return this
  }

  close(onclose) {
    if (onclose) this.once('close', onclose)
    this._server.close()
    return this
  }

  ref() {
    this._state &= ~constants.state.UNREFED
    if (this._server !== null) this._server.ref()
    return this
  }

  unref() {
    this._state |= constants.state.UNREFED
    if (this._server !== null) this._server.unref()
    return this
  }

  _attach(type, server) {
    this._type = type
    this._server = server

    this._server
      .on('listening', this._onlistening.bind(this))
      .on('connection', this._onconnection.bind(this))
      .on('error', this._onerror.bind(this))
      .on('close', this._onclose.bind(this))

    if (this._state & constants.state.UNREFED) this._server.unref()

    return this
  }

  _onlistening() {
    this.emit('listening')
  }

  _onconnection(socket) {
    this.emit('connection', new exports.Socket(this._opts)._attach(this._type, socket))
  }

  _onerror(err) {
    this.emit('error', err)
  }

  _onclose() {
    this.emit('close')
  }
}

exports.constants = constants

exports.isIP = tcp.isIP
exports.isIPv4 = tcp.isIPv4
exports.isIPv6 = tcp.isIPv6

exports.createConnection = function createConnection(...args) {
  let opts = {}
  let onconnect

  if (typeof args[0] === 'string') {
    // createConnection(path[, onconnect])
    opts.path = args[0]
    onconnect = args[1]
  } else if (typeof args[0] === 'number') {
    // createConnection(port[, host][, onconnect])
    opts.port = args[0]

    if (typeof args[1] === 'function') {
      onconnect = args[1]
    } else {
      opts.host = args[1]
      onconnect = args[2]
    }
  } else {
    // createConnection(opts[, onconnect])
    opts = args[0] || {}
    onconnect = args[1]
  }

  return new exports.Socket(opts).connect(opts, onconnect)
}

// For Node.js compatibility
exports.connect = exports.createConnection

exports.createServer = function createServer(opts, onconnection) {
  return new exports.Server(opts, onconnection)
}
module.exports = {
  type: {
    TCP: 1,
    IPC: 2
  },
  state: {
    UNREFED: 0x1
  }
}
{
  "name": "bare-net",
  "version": "2.3.2",
  "description": "TCP and IPC servers and clients for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-net.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-net/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-net#readme",
  "dependencies": {
    "bare-events": "^2.2.2",
    "bare-pipe": "^4.0.0",
    "bare-stream": "^2.0.0",
    "bare-tcp": "^2.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.0",
    "lunte": "^1.8.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = require.addon()
const binding = require('./binding')
const errors = require('./lib/errors')
const constants = require('./lib/constants')

exports.constants = constants
exports.errors = errors

exports.EOL = binding.platform === 'win32' ? '\r\n' : '\n'

exports.devNull = binding.platform === 'win32' ? '\\\\.\\nul' : '/dev/null'

exports.platform = function platform() {
  return binding.platform
}

exports.arch = function arch() {
  return binding.arch
}

exports.type = function type() {
  return binding.type()
}

exports.version = function version() {
  return binding.version()
}

exports.release = function release() {
  return binding.release()
}

exports.machine = function machine() {
  return binding.machine()
}

exports.execPath = function execPath() {
  return binding.execPath()
}

exports.pid = function pid() {
  return binding.pid()
}

exports.ppid = function ppid() {
  return binding.ppid()
}

exports.cwd = function cwd() {
  return binding.cwd()
}

exports.chdir = function chdir(dir) {
  validateString(dir, 'Directory')

  binding.chdir(dir)
}

exports.tmpdir = function tmpdir() {
  return binding.tmpdir()
}

exports.homedir = function homedir() {
  return binding.homedir()
}

exports.hostname = function hostname() {
  return binding.hostname()
}

exports.userInfo = function userInfo(uid) {
  if (uid !== undefined) validateInteger(uid, 'User ID')

  return binding.userInfo(uid)
}

exports.groupInfo = function groupInfo(gid) {
  if (gid !== undefined) validateInteger(gid, 'Group ID')

  return binding.groupInfo(gid)
}

exports.networkInterfaces = function networkInterfaces() {
  const result = {}

  for (const entry of binding.networkInterfaces()) {
    const { name, ...properties } = entry

    if (result[name]) result[name].push(properties)
    else result[name] = [properties]
  }

  return result
}

exports.kill = function kill(pid, signal = constants.signals.SIGTERM) {
  validateInteger(pid, 'Process ID')

  if (typeof signal === 'string') {
    if (signal in constants.signals === false) {
      throw errors.UNKNOWN_SIGNAL('Unknown signal: ' + signal)
    }

    signal = constants.signals[signal]
  } else {
    validateInteger(signal, 'Signal')
  }

  binding.kill(pid, signal)
}

exports.endianness = function endianness() {
  return binding.isLittleEndian ? 'LE' : 'BE'
}

exports.availableParallelism = function availableParallelism() {
  return binding.availableParallelism()
}

exports.cpuUsage = function cpuUsage(previous) {
  const current = binding.cpuUsage()

  if (previous) {
    return {
      user: current.user - previous.user,
      system: current.system - previous.system
    }
  }

  return current
}

exports.threadCpuUsage = function threadCpuUsage(previous) {
  const current = binding.threadCpuUsage()

  if (previous) {
    return {
      user: current.user - previous.user,
      system: current.system - previous.system
    }
  }

  return current
}

exports.resourceUsage = function resourceUsage() {
  return binding.resourceUsage()
}

exports.memoryUsage = function memoryUsage() {
  return binding.memoryUsage()
}

exports.freemem = function freemem() {
  return binding.freemem()
}

exports.totalmem = function totalmem() {
  return binding.totalmem()
}

exports.availableMemory = function availableMemory() {
  return binding.availableMemory()
}

exports.constrainedMemory = function constrainedMemory() {
  return binding.constrainedMemory()
}

exports.uptime = function uptime() {
  return binding.uptime()
}

exports.loadavg = function loadavg() {
  return binding.loadavg()
}

exports.cpus = function cpus() {
  return binding.cpus()
}

exports.getProcessTitle = function getProcessTitle() {
  return binding.getProcessTitle()
}

exports.setProcessTitle = function setProcessTitle(title) {
  if (typeof title !== 'string') title = title.toString()

  if (title.length >= 256) {
    throw errors.TITLE_OVERFLOW('Process title is too long')
  }

  binding.setProcessTitle(title)
}

exports.getPriority = function getPriority(pid = 0) {
  validateInteger(pid, 'Process ID')

  return binding.getPriority(pid)
}

exports.setPriority = function setPriority(pid, priority) {
  if (priority === undefined) {
    priority = pid
    pid = 0
  }

  validateInteger(pid, 'Process ID')
  validateInteger(priority, 'Priority')

  binding.setPriority(pid, priority)
}

exports.getEnvKeys = function getEnvKeys() {
  return binding.getEnvKeys()
}

exports.getEnv = function getEnv(name) {
  validateString(name, 'Name')

  return binding.getEnv(name)
}

exports.hasEnv = function hasEnv(name) {
  validateString(name, 'Name')

  return binding.hasEnv(name)
}

exports.setEnv = function setEnv(name, value) {
  validateString(name, 'Name')
  validateString(value, 'Value')

  binding.setEnv(name, value)
}

exports.unsetEnv = function unsetEnv(name) {
  validateString(name, 'Name')

  binding.unsetEnv(name)
}

function validateString(value, name) {
  if (typeof value !== 'string') {
    throw new TypeError(`${name} must be a string. Received type ${typeof value} (${value})`)
  }
}

function validateInteger(value, name) {
  if (!Number.isInteger(value)) {
    throw new TypeError(`${name} must be an integer. Received type ${typeof value} (${value})`)
  }
}
const binding = require('../binding')

module.exports = {
  signals: binding.signals,
  errnos: binding.errnos,
  priority: binding.priority
}
module.exports = class OSError extends Error {
  constructor(msg, fn = OSError, code = fn.name) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'OSError'
  }

  static UNKNOWN_SIGNAL(msg) {
    return new OSError(msg, OSError.UNKNOWN_SIGNAL)
  }

  static TITLE_OVERFLOW(msg) {
    return new OSError(msg, OSError.TITLE_OVERFLOW)
  }
}
{
  "name": "bare-os",
  "version": "3.9.3",
  "description": "Operating system utilities for Bare",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    },
    "./errors": {
      "types": "./lib/errors.d.ts",
      "default": "./lib/errors.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-os.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-os/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-os#readme",
  "engines": {
    "bare": ">=1.14.0"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "cmake-bare": "^1.1.6",
    "lunte": "^1.6.0",
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
// This export SHOULD NOT be shortened in any way as having the full
// `module.exports = require(...)` statement is crucial for synthesizing
// ESM exports.

if (Bare.platform === 'win32') {
  module.exports = require('./lib/win32')
} else {
  module.exports = require('./lib/posix')
}
module.exports = {
  CHAR_UPPERCASE_A: 0x41,
  CHAR_LOWERCASE_A: 0x61,
  CHAR_UPPERCASE_Z: 0x5a,
  CHAR_LOWERCASE_Z: 0x7a,
  CHAR_DOT: 0x2e,
  CHAR_FORWARD_SLASH: 0x2f,
  CHAR_BACKWARD_SLASH: 0x5c,
  CHAR_COLON: 0x3a,
  CHAR_QUESTION_MARK: 0x3f
}
const os = require('bare-os')

const { normalizeString } = require('./shared')
const { CHAR_DOT, CHAR_FORWARD_SLASH } = require('./constants')

function isPosixPathSeparator(code) {
  return code === CHAR_FORWARD_SLASH
}

exports.win32 = require('./win32')
exports.posix = exports

exports.sep = '/'
exports.delimiter = ':'

exports.resolve = function resolve(...args) {
  let resolvedPath = ''
  let resolvedAbsolute = false

  for (let i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) {
    const path = i >= 0 ? args[i] : os.cwd()

    if (path.length === 0) {
      continue
    }

    resolvedPath = `${path}/${resolvedPath}`
    resolvedAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH
  }

  resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute, '/', isPosixPathSeparator)

  if (resolvedAbsolute) {
    return `/${resolvedPath}`
  }

  return resolvedPath.length > 0 ? resolvedPath : '.'
}

exports.normalize = function normalize(path) {
  if (path.length === 0) return '.'

  const isAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH
  const trailingSeparator = path.charCodeAt(path.length - 1) === CHAR_FORWARD_SLASH

  path = normalizeString(path, !isAbsolute, '/', isPosixPathSeparator)

  if (path.length === 0) {
    if (isAbsolute) return '/'
    return trailingSeparator ? './' : '.'
  }

  if (trailingSeparator) path += '/'

  return isAbsolute ? `/${path}` : path
}

exports.isAbsolute = function isAbsolute(path) {
  return path.length > 0 && path.charCodeAt(0) === CHAR_FORWARD_SLASH
}

exports.join = function join(...args) {
  if (args.length === 0) return '.'
  let joined
  for (let i = 0; i < args.length; ++i) {
    const arg = args[i]
    if (arg.length > 0) {
      if (joined === undefined) joined = arg
      else joined += `/${arg}`
    }
  }
  if (joined === undefined) return '.'
  return exports.normalize(joined)
}

exports.relative = function relative(from, to) {
  if (from === to) return ''

  from = exports.resolve(from)
  to = exports.resolve(to)

  if (from === to) return ''

  const fromStart = 1
  const fromEnd = from.length
  const fromLen = fromEnd - fromStart
  const toStart = 1
  const toLen = to.length - toStart

  const length = fromLen < toLen ? fromLen : toLen
  let lastCommonSep = -1
  let i = 0
  for (; i < length; i++) {
    const fromCode = from.charCodeAt(fromStart + i)
    if (fromCode !== to.charCodeAt(toStart + i)) {
      break
    } else if (fromCode === CHAR_FORWARD_SLASH) {
      lastCommonSep = i
    }
  }
  if (i === length) {
    if (toLen > length) {
      if (to.charCodeAt(toStart + i) === CHAR_FORWARD_SLASH) {
        return to.substring(toStart + i + 1)
      }
      if (i === 0) {
        return to.substring(toStart + i)
      }
    } else if (fromLen > length) {
      if (from.charCodeAt(fromStart + i) === CHAR_FORWARD_SLASH) {
        lastCommonSep = i
      } else if (i === 0) {
        lastCommonSep = 0
      }
    }
  }

  let out = ''
  for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
    if (i === fromEnd || from.charCodeAt(i) === CHAR_FORWARD_SLASH) {
      out += out.length === 0 ? '..' : '/..'
    }
  }

  return `${out}${to.substring(toStart + lastCommonSep)}`
}

exports.toNamespacedPath = function toNamespacedPath(path) {
  return path
}

exports.dirname = function dirname(path) {
  if (path.length === 0) return '.'
  const hasRoot = path.charCodeAt(0) === CHAR_FORWARD_SLASH
  let end = -1
  let matchedSlash = true
  for (let i = path.length - 1; i >= 1; --i) {
    if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) {
      if (!matchedSlash) {
        end = i
        break
      }
    } else {
      matchedSlash = false
    }
  }

  if (end === -1) return hasRoot ? '/' : '.'
  if (hasRoot && end === 1) return '//'
  return path.substring(0, end)
}

exports.basename = function basename(path, suffix) {
  let start = 0
  let end = -1
  let matchedSlash = true

  if (suffix !== undefined && suffix.length > 0 && suffix.length <= path.length) {
    if (suffix === path) {
      return ''
    }
    let extIdx = suffix.length - 1
    let firstNonSlashEnd = -1
    for (let i = path.length - 1; i >= 0; --i) {
      const code = path.charCodeAt(i)
      if (code === CHAR_FORWARD_SLASH) {
        if (!matchedSlash) {
          start = i + 1
          break
        }
      } else {
        if (firstNonSlashEnd === -1) {
          matchedSlash = false
          firstNonSlashEnd = i + 1
        }
        if (extIdx >= 0) {
          if (code === suffix.charCodeAt(extIdx)) {
            if (--extIdx === -1) {
              end = i
            }
          } else {
            extIdx = -1
            end = firstNonSlashEnd
          }
        }
      }
    }

    if (start === end) end = firstNonSlashEnd
    else if (end === -1) end = path.length
    return path.substring(start, end)
  }

  for (let i = path.length - 1; i >= 0; --i) {
    if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) {
      if (!matchedSlash) {
        start = i + 1
        break
      }
    } else if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
  }

  if (end === -1) return ''
  return path.substring(start, end)
}

exports.extname = function extname(path) {
  let startDot = -1
  let startPart = 0
  let end = -1
  let matchedSlash = true
  let preDotState = 0
  for (let i = path.length - 1; i >= 0; --i) {
    const code = path.charCodeAt(i)
    if (code === CHAR_FORWARD_SLASH) {
      if (!matchedSlash) {
        startPart = i + 1
        break
      }
      continue
    }
    if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
    if (code === CHAR_DOT) {
      if (startDot === -1) startDot = i
      else if (preDotState !== 1) preDotState = 1
    } else if (startDot !== -1) {
      preDotState = -1
    }
  }

  if (
    startDot === -1 ||
    end === -1 ||
    preDotState === 0 ||
    (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1)
  ) {
    return ''
  }
  return path.substring(startDot, end)
}
const { CHAR_DOT, CHAR_FORWARD_SLASH } = require('./constants')

exports.normalizeString = function normalizeString(
  path,
  allowAboveRoot,
  separator,
  isPathSeparator
) {
  let res = ''
  let lastSegmentLength = 0
  let lastSlash = -1
  let dots = 0
  let code = 0
  for (let i = 0; i <= path.length; ++i) {
    if (i < path.length) {
      code = path.charCodeAt(i)
    } else if (isPathSeparator(code)) {
      break
    } else {
      code = CHAR_FORWARD_SLASH
    }

    if (isPathSeparator(code)) {
      if (lastSlash === i - 1 || dots === 1);
      else if (dots === 2) {
        if (
          res.length < 2 ||
          lastSegmentLength !== 2 ||
          res.charCodeAt(res.length - 1) !== CHAR_DOT ||
          res.charCodeAt(res.length - 2) !== CHAR_DOT
        ) {
          if (res.length > 2) {
            const lastSlashIndex = res.lastIndexOf(separator)
            if (lastSlashIndex === -1) {
              res = ''
              lastSegmentLength = 0
            } else {
              res = res.substring(0, lastSlashIndex)
              lastSegmentLength = res.length - 1 - res.lastIndexOf(separator)
            }
            lastSlash = i
            dots = 0
            continue
          } else if (res.length !== 0) {
            res = ''
            lastSegmentLength = 0
            lastSlash = i
            dots = 0
            continue
          }
        }
        if (allowAboveRoot) {
          res += res.length > 0 ? `${separator}..` : '..'
          lastSegmentLength = 2
        }
      } else {
        if (res.length > 0) {
          res += `${separator}${path.substring(lastSlash + 1, i)}`
        } else {
          res = path.substring(lastSlash + 1, i)
        }
        lastSegmentLength = i - lastSlash - 1
      }
      lastSlash = i
      dots = 0
    } else if (code === CHAR_DOT && dots !== -1) {
      ++dots
    } else {
      dots = -1
    }
  }
  return res
}
const os = require('bare-os')

const { normalizeString } = require('./shared')
const {
  CHAR_UPPERCASE_A,
  CHAR_LOWERCASE_A,
  CHAR_UPPERCASE_Z,
  CHAR_LOWERCASE_Z,
  CHAR_DOT,
  CHAR_FORWARD_SLASH,
  CHAR_BACKWARD_SLASH,
  CHAR_COLON,
  CHAR_QUESTION_MARK
} = require('./constants')

function isWindowsPathSeparator(code) {
  return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH
}

function isWindowsDeviceRoot(code) {
  return (
    (code >= CHAR_UPPERCASE_A && code <= CHAR_UPPERCASE_Z) ||
    (code >= CHAR_LOWERCASE_A && code <= CHAR_LOWERCASE_Z)
  )
}

exports.posix = require('./posix')
exports.win32 = exports

exports.sep = '\\'
exports.delimiter = ';'

exports.resolve = function resolve(...args) {
  let resolvedDevice = ''
  let resolvedTail = ''
  let resolvedAbsolute = false

  for (let i = args.length - 1; i >= -1; i--) {
    let path
    if (i >= 0) {
      path = args[i]

      if (path.length === 0) continue
    } else if (resolvedDevice.length === 0) {
      path = os.cwd()
    } else {
      path = os.getEnv(`=${resolvedDevice}`) || os.cwd()

      if (
        path === undefined ||
        (path.substring(0, 2).toLowerCase() !== resolvedDevice.toLowerCase() &&
          path.charCodeAt(2) === CHAR_BACKWARD_SLASH)
      ) {
        path = `${resolvedDevice}\\`
      }
    }

    const len = path.length
    let rootEnd = 0
    let device = ''
    let isAbsolute = false
    const code = path.charCodeAt(0)

    if (len === 1) {
      if (isWindowsPathSeparator(code)) {
        rootEnd = 1
        isAbsolute = true
      }
    } else if (isWindowsPathSeparator(code)) {
      isAbsolute = true

      if (isWindowsPathSeparator(path.charCodeAt(1))) {
        let j = 2
        let last = j
        while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
          j++
        }
        if (j < len && j !== last) {
          const firstPart = path.substring(last, j)
          last = j
          while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
            j++
          }
          if (j < len && j !== last) {
            last = j
            while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
              j++
            }
            if (j === len || j !== last) {
              device = `\\\\${firstPart}\\${path.substring(last, j)}`
              rootEnd = j
            }
          }
        }
      } else {
        rootEnd = 1
      }
    } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
      device = path.substring(0, 2)
      rootEnd = 2
      if (len > 2 && isWindowsPathSeparator(path.charCodeAt(2))) {
        isAbsolute = true
        rootEnd = 3
      }
    }

    if (device.length > 0) {
      if (resolvedDevice.length > 0) {
        if (device.toLowerCase() !== resolvedDevice.toLowerCase()) {
          continue
        }
      } else {
        resolvedDevice = device
      }
    }

    if (resolvedAbsolute) {
      if (resolvedDevice.length > 0) {
        break
      }
    } else {
      resolvedTail = `${path.substring(rootEnd)}\\${resolvedTail}`
      resolvedAbsolute = isAbsolute
      if (isAbsolute && resolvedDevice.length > 0) {
        break
      }
    }
  }

  resolvedTail = normalizeString(resolvedTail, !resolvedAbsolute, '\\', isWindowsPathSeparator)

  return resolvedAbsolute
    ? `${resolvedDevice}\\${resolvedTail}`
    : `${resolvedDevice}${resolvedTail}` || '.'
}

exports.normalize = function normalize(path) {
  const len = path.length
  if (len === 0) return '.'
  let rootEnd = 0
  let device
  let isAbsolute = false
  const code = path.charCodeAt(0)

  if (len === 1) {
    return code === CHAR_FORWARD_SLASH ? '\\' : path
  }

  if (isWindowsPathSeparator(code)) {
    isAbsolute = true

    if (isWindowsPathSeparator(path.charCodeAt(1))) {
      let j = 2
      let last = j
      while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
        j++
      }
      if (j < len && j !== last) {
        const firstPart = path.substring(last, j)
        last = j
        while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
          j++
        }
        if (j < len && j !== last) {
          last = j
          while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
            j++
          }
          if (j === len) {
            return `\\\\${firstPart}\\${path.substring(last)}\\`
          }
          if (j !== last) {
            device = `\\\\${firstPart}\\${path.substring(last, j)}`
            rootEnd = j
          }
        }
      }
    } else {
      rootEnd = 1
    }
  } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
    device = path.substring(0, 2)
    rootEnd = 2
    if (len > 2 && isWindowsPathSeparator(path.charCodeAt(2))) {
      isAbsolute = true
      rootEnd = 3
    }
  }

  let tail =
    rootEnd < len
      ? normalizeString(path.substring(rootEnd), !isAbsolute, '\\', isWindowsPathSeparator)
      : ''
  if (tail.length === 0 && !isAbsolute) {
    tail = '.'
  }
  if (tail.length > 0 && isWindowsPathSeparator(path.charCodeAt(len - 1))) {
    tail += '\\'
  }
  if (device === undefined) {
    return isAbsolute ? `\\${tail}` : tail
  }
  return isAbsolute ? `${device}\\${tail}` : `${device}${tail}`
}

exports.isAbsolute = function isAbsolute(path) {
  const len = path.length
  if (len === 0) return false

  const code = path.charCodeAt(0)

  return (
    isWindowsPathSeparator(code) ||
    (len > 2 &&
      isWindowsDeviceRoot(code) &&
      path.charCodeAt(1) === CHAR_COLON &&
      isWindowsPathSeparator(path.charCodeAt(2)))
  )
}

exports.join = function join(...args) {
  if (args.length === 0) return '.'

  let joined
  let firstPart
  for (let i = 0; i < args.length; ++i) {
    const arg = args[i]
    if (arg.length > 0) {
      if (joined === undefined) joined = firstPart = arg
      else joined += `\\${arg}`
    }
  }

  if (joined === undefined) return '.'

  let needsReplace = true
  let slashCount = 0
  if (isWindowsPathSeparator(firstPart.charCodeAt(0))) {
    ++slashCount
    const firstLen = firstPart.length
    if (firstLen > 1 && isWindowsPathSeparator(firstPart.charCodeAt(1))) {
      ++slashCount
      if (firstLen > 2) {
        if (isWindowsPathSeparator(firstPart.charCodeAt(2))) {
          ++slashCount
        } else {
          needsReplace = false
        }
      }
    }
  }
  if (needsReplace) {
    while (slashCount < joined.length && isWindowsPathSeparator(joined.charCodeAt(slashCount))) {
      slashCount++
    }

    if (slashCount >= 2) {
      joined = `\\${joined.substring(slashCount)}`
    }
  }

  return exports.normalize(joined)
}

exports.relative = function relative(from, to) {
  if (from === to) return ''

  const fromOrig = exports.resolve(from)
  const toOrig = exports.resolve(to)

  if (fromOrig === toOrig) return ''

  from = fromOrig.toLowerCase()
  to = toOrig.toLowerCase()

  if (from === to) return ''

  let fromStart = 0
  while (fromStart < from.length && from.charCodeAt(fromStart) === CHAR_BACKWARD_SLASH) {
    fromStart++
  }
  let fromEnd = from.length
  while (fromEnd - 1 > fromStart && from.charCodeAt(fromEnd - 1) === CHAR_BACKWARD_SLASH) {
    fromEnd--
  }
  const fromLen = fromEnd - fromStart

  let toStart = 0
  while (toStart < to.length && to.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) {
    toStart++
  }
  let toEnd = to.length
  while (toEnd - 1 > toStart && to.charCodeAt(toEnd - 1) === CHAR_BACKWARD_SLASH) {
    toEnd--
  }
  const toLen = toEnd - toStart

  const length = fromLen < toLen ? fromLen : toLen
  let lastCommonSep = -1
  let i = 0
  for (; i < length; i++) {
    const fromCode = from.charCodeAt(fromStart + i)
    if (fromCode !== to.charCodeAt(toStart + i)) {
      break
    } else if (fromCode === CHAR_BACKWARD_SLASH) {
      lastCommonSep = i
    }
  }

  if (i !== length) {
    if (lastCommonSep === -1) return toOrig
  } else {
    if (toLen > length) {
      if (to.charCodeAt(toStart + i) === CHAR_BACKWARD_SLASH) {
        return toOrig.substring(toStart + i + 1)
      }
      if (i === 2) {
        return toOrig.substring(toStart + i)
      }
    }
    if (fromLen > length) {
      if (from.charCodeAt(fromStart + i) === CHAR_BACKWARD_SLASH) {
        lastCommonSep = i
      } else if (i === 2) {
        lastCommonSep = 3
      }
    }
    if (lastCommonSep === -1) lastCommonSep = 0
  }

  let out = ''
  for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
    if (i === fromEnd || from.charCodeAt(i) === CHAR_BACKWARD_SLASH) {
      out += out.length === 0 ? '..' : '\\..'
    }
  }

  toStart += lastCommonSep

  if (out.length > 0) {
    return `${out}${toOrig.substring(toStart, toEnd)}`
  }
  if (toOrig.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) {
    ++toStart
  }
  return toOrig.substring(toStart, toEnd)
}

exports.toNamespacedPath = function toNamespacedPath(path) {
  if (path.length === 0) return path

  const resolvedPath = exports.resolve(path)

  if (resolvedPath.length <= 2) return path

  if (resolvedPath.charCodeAt(0) === CHAR_BACKWARD_SLASH) {
    if (resolvedPath.charCodeAt(1) === CHAR_BACKWARD_SLASH) {
      const code = resolvedPath.charCodeAt(2)
      if (code !== CHAR_QUESTION_MARK && code !== CHAR_DOT) {
        return `\\\\?\\UNC\\${resolvedPath.substring(2)}`
      }
    }
  } else if (
    isWindowsDeviceRoot(resolvedPath.charCodeAt(0)) &&
    resolvedPath.charCodeAt(1) === CHAR_COLON &&
    resolvedPath.charCodeAt(2) === CHAR_BACKWARD_SLASH
  ) {
    return `\\\\?\\${resolvedPath}`
  }

  return path
}

exports.dirname = function dirname(path) {
  const len = path.length
  if (len === 0) return '.'
  let rootEnd = -1
  let offset = 0
  const code = path.charCodeAt(0)

  if (len === 1) {
    return isWindowsPathSeparator(code) ? path : '.'
  }

  if (isWindowsPathSeparator(code)) {
    rootEnd = offset = 1

    if (isWindowsPathSeparator(path.charCodeAt(1))) {
      let j = 2
      let last = j
      while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
        j++
      }
      if (j < len && j !== last) {
        last = j
        while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
          j++
        }
        if (j < len && j !== last) {
          last = j
          while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
            j++
          }
          if (j === len) {
            return path
          }
          if (j !== last) {
            rootEnd = offset = j + 1
          }
        }
      }
    }
  } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
    rootEnd = len > 2 && isWindowsPathSeparator(path.charCodeAt(2)) ? 3 : 2
    offset = rootEnd
  }

  let end = -1
  let matchedSlash = true
  for (let i = len - 1; i >= offset; --i) {
    if (isWindowsPathSeparator(path.charCodeAt(i))) {
      if (!matchedSlash) {
        end = i
        break
      }
    } else {
      matchedSlash = false
    }
  }

  if (end === -1) {
    if (rootEnd === -1) return '.'

    end = rootEnd
  }
  return path.substring(0, end)
}

exports.basename = function basename(path, suffix) {
  let start = 0
  let end = -1
  let matchedSlash = true

  if (
    path.length >= 2 &&
    isWindowsDeviceRoot(path.charCodeAt(0)) &&
    path.charCodeAt(1) === CHAR_COLON
  ) {
    start = 2
  }

  if (suffix !== undefined && suffix.length > 0 && suffix.length <= path.length) {
    if (suffix === path) return ''
    let extIdx = suffix.length - 1
    let firstNonSlashEnd = -1
    for (let i = path.length - 1; i >= start; --i) {
      const code = path.charCodeAt(i)
      if (isWindowsPathSeparator(code)) {
        if (!matchedSlash) {
          start = i + 1
          break
        }
      } else {
        if (firstNonSlashEnd === -1) {
          matchedSlash = false
          firstNonSlashEnd = i + 1
        }
        if (extIdx >= 0) {
          if (code === suffix.charCodeAt(extIdx)) {
            if (--extIdx === -1) {
              end = i
            }
          } else {
            extIdx = -1
            end = firstNonSlashEnd
          }
        }
      }
    }

    if (start === end) end = firstNonSlashEnd
    else if (end === -1) end = path.length
    return path.substring(start, end)
  }
  for (let i = path.length - 1; i >= start; --i) {
    if (isWindowsPathSeparator(path.charCodeAt(i))) {
      if (!matchedSlash) {
        start = i + 1
        break
      }
    } else if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
  }

  if (end === -1) return ''
  return path.substring(start, end)
}

exports.extname = function extname(path) {
  let start = 0
  let startDot = -1
  let startPart = 0
  let end = -1
  let matchedSlash = true
  let preDotState = 0

  if (
    path.length >= 2 &&
    path.charCodeAt(1) === CHAR_COLON &&
    isWindowsDeviceRoot(path.charCodeAt(0))
  ) {
    start = startPart = 2
  }

  for (let i = path.length - 1; i >= start; --i) {
    const code = path.charCodeAt(i)
    if (isWindowsPathSeparator(code)) {
      if (!matchedSlash) {
        startPart = i + 1
        break
      }
      continue
    }
    if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
    if (code === CHAR_DOT) {
      if (startDot === -1) startDot = i
      else if (preDotState !== 1) preDotState = 1
    } else if (startDot !== -1) {
      preDotState = -1
    }
  }

  if (
    startDot === -1 ||
    end === -1 ||
    preDotState === 0 ||
    (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1)
  ) {
    return ''
  }
  return path.substring(startDot, end)
}
{
  "name": "bare-path",
  "version": "3.0.1",
  "description": "Path manipulation library for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./posix": "./lib/posix.js",
    "./win32": "./lib/win32.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "lib",
    "NOTICE"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-path.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-path/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-path#readme",
  "dependencies": {
    "bare-os": "^3.0.1"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "lunte": "^1.8.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = require.addon()
const EventEmitter = require('bare-events')
const { Duplex } = require('bare-stream')
const binding = require('./binding')
const constants = require('./lib/constants')
const errors = require('./lib/errors')

const defaultReadBufferSize = 65536
const empty = Buffer.alloc(0)

const ipcHandle = Symbol.for('bare.ipc.handle')
const ipcAccept = Symbol.for('bare.ipc.accept')

module.exports = exports = class Pipe extends Duplex {
  constructor(path, opts = {}) {
    if (typeof path === 'object' && path !== null) {
      opts = path
      path = null
    }

    const {
      readBufferSize = defaultReadBufferSize,
      allowHalfOpen = true,
      eagerOpen = true,
      ipc = false
    } = opts

    super({ eagerOpen })

    this._state = 0

    this._allowHalfOpen = allowHalfOpen
    this._ipc = ipc

    this._fd = -1
    this._path = null

    this._pendingOpen = null
    this._pendingWrite = null
    this._pendingWriteBatch = null
    this._pendingWriteSegments = null
    this._pendingWriteIdx = 0
    this._pendingFinal = null
    this._pendingDestroy = null

    this._handleQueue = []
    this._handleQueueSize = 0

    this._buffer = Buffer.alloc(readBufferSize)

    this._handle = binding.init(
      this._buffer,
      ipc,
      this,
      noop,
      this._onconnect,
      this._onwrite,
      this._onfinal,
      this._onread,
      this._onhandle,
      this._onclose
    )

    if (typeof path === 'number') {
      this.open(path)
    } else if (typeof path === 'string') {
      this.connect(path)
    }
  }

  get connecting() {
    return (this._state & constants.state.CONNECTING) !== 0
  }

  get pending() {
    return (this._state & constants.state.CONNECTED) === 0
  }

  get readyState() {
    if (this._state & constants.state.READABLE && this._state & constants.state.WRITABLE) {
      return 'open'
    }

    if (this._state & constants.state.READABLE) {
      return 'readOnly'
    }

    if (this._state & constants.state.WRITABLE) {
      return 'writeOnly'
    }

    return 'opening'
  }

  get [ipcHandle]() {
    return this._handle
  }

  open(fd, opts = {}, onconnect) {
    if (typeof opts === 'function') {
      onconnect = opts
      opts = {}
    }

    if (typeof fd === 'object' && fd !== null) {
      opts = fd || {}
      fd = opts.fd
    }

    try {
      const status = binding.open(this._handle, fd)

      this._state |= constants.state.CONNECTED
      this._fd = fd

      if (status & binding.READABLE) {
        this._state |= constants.state.READABLE
      } else {
        this.push(null)
      }

      if (status & binding.WRITABLE) {
        this._state |= constants.state.WRITABLE
      } else {
        this.end()
      }

      if (onconnect) this.once('connect', onconnect)

      queueMicrotask(() => this.emit('connect'))
    } catch (err) {
      queueMicrotask(() => {
        if (this._pendingOpen) this._pendingOpen(err)
        else this.destroy(err)
      })
    }

    return this
  }

  connect(path, opts = {}, onconnect) {
    if (this._state & constants.state.CONNECTING || this._state & constants.state.CONNECTED) {
      throw errors.PIPE_ALREADY_CONNECTED('Pipe is already connected')
    }

    this._state |= constants.state.CONNECTING

    if (typeof opts === 'function') {
      onconnect = opts
      opts = {}
    }

    if (typeof path === 'object' && path !== null) {
      opts = path || {}
      path = opts.path
    }

    try {
      binding.connect(this._handle, path)

      this._path = path

      if (onconnect) this.once('connect', onconnect)
    } catch (err) {
      queueMicrotask(() => {
        if (this._pendingOpen) this._pendingOpen(err)
        else this.destroy(err)
      })
    }

    return this
  }

  write(chunk, encoding, handle, cb) {
    if (typeof encoding === 'function') {
      cb = encoding
      encoding = undefined
      handle = null
    } else if (typeof encoding === 'object' && encoding !== null) {
      if (typeof handle === 'function') cb = handle
      handle = encoding
      encoding = undefined
    } else if (typeof handle === 'function') {
      cb = handle
      handle = null
    }

    if (handle) this._handleQueueSize++

    this._handleQueue.push(handle || null)

    if (encoding) return super.write(chunk, encoding, cb)

    return super.write(chunk, cb)
  }

  accept(target) {
    const handle = target[ipcHandle]

    if (handle === undefined) {
      throw errors.INVALID_IPC_TARGET('Target does not implement the IPC handle protocol')
    }

    binding.accept(this._handle, handle)

    if (typeof target[ipcAccept] === 'function') target[ipcAccept]()

    return target
  }

  ref() {
    binding.ref(this._handle)

    return this
  }

  unref() {
    binding.unref(this._handle)

    return this
  }

  [ipcAccept]() {
    this._onaccept()
  }

  _open(cb) {
    if (this._state & constants.state.CONNECTED) return cb(null)

    this._pendingOpen = cb
  }

  _read() {
    if ((this._state & constants.state.READING) === 0) {
      this._state |= constants.state.READING

      binding.resume(this._handle)
    }
  }

  _writev(batch, cb) {
    this._pendingWrite = cb
    this._pendingWriteBatch = batch

    if (this._handleQueueSize === 0) {
      this._handleQueue = []
      this._pendingWriteSegments = null

      try {
        binding.writev(
          this._handle,
          batch.map(({ chunk }) => chunk),
          null
        )
      } catch (err) {
        this._continueWrite(err)
      }
      return
    }

    const handles = this._handleQueue.splice(0, batch.length)

    // Fill any holes in the batch for messages that don't carry a handle. Each
    // message that does carry a handle decrements the handle queue size.
    for (let i = 0; i < batch.length; i++) {
      if (handles[i] === undefined) handles[i] = null
      else if (handles[i] !== null) this._handleQueueSize--
    }

    const segments = []

    let i = 0
    while (i < batch.length) {
      if (handles[i] !== null) {
        segments.push({ chunks: [batch[i]], handle: handles[i] })
        i++
      } else {
        const start = i
        while (i < batch.length && handles[i] === null) i++
        segments.push({ chunks: batch.slice(start, i), handle: null })
      }
    }

    this._pendingWriteSegments = segments
    this._pendingWriteIdx = 0

    this._writeNextSegment()
  }

  _writeNextSegment() {
    const segment = this._pendingWriteSegments[this._pendingWriteIdx]

    const chunks = []
    for (let i = 0; i < segment.chunks.length; i++) {
      chunks.push(segment.chunks[i].chunk)
    }

    let sendHandle = null
    if (segment.handle !== null) sendHandle = segment.handle[ipcHandle]

    try {
      binding.writev(this._handle, chunks, sendHandle)
    } catch (err) {
      this._continueWrite(err)
    }
  }

  _final(cb) {
    if (this._state & constants.state.READABLE && this._state & constants.state.WRITABLE) {
      this._pendingFinal = cb

      binding.end(this._handle)
    } else {
      cb(null)
    }
  }

  _predestroy() {
    if (this._state & constants.state.CLOSING) return
    this._state |= constants.state.CLOSING

    binding.close(this._handle)
  }

  _destroy(err, cb) {
    if (this._state & constants.state.CLOSING) return cb(err)
    this._state |= constants.state.CLOSING

    this._pendingDestroy = cb

    binding.close(this._handle)
  }

  _continueOpen(err) {
    if (this._pendingOpen === null) return
    const cb = this._pendingOpen
    this._pendingOpen = null
    cb(err)
  }

  _continueWrite(err) {
    if (this._pendingWrite === null) return

    if (this._pendingWriteSegments === null) {
      const cb = this._pendingWrite
      this._pendingWrite = null
      this._pendingWriteBatch = null
      cb(err)
      return
    }

    this._pendingWriteIdx++

    if (err === null && this._pendingWriteIdx < this._pendingWriteSegments.length) {
      this._writeNextSegment()
      return
    }

    const cb = this._pendingWrite
    this._pendingWrite = null
    this._pendingWriteBatch = null
    this._pendingWriteSegments = null
    this._pendingWriteIdx = 0
    cb(err)
  }

  _continueFinal(err) {
    if (this._pendingFinal === null) return
    const cb = this._pendingFinal
    this._pendingFinal = null
    cb(err)
  }

  _continueDestroy() {
    if (this._pendingDestroy === null) return
    const cb = this._pendingDestroy
    this._pendingDestroy = null
    cb(null)
  }

  _onconnect(err) {
    if (err) {
      if (this._pendingOpen) this._continueOpen(err)
      else this.destroy(err)
      return
    }

    this._state |= constants.state.CONNECTED | constants.state.READABLE | constants.state.WRITABLE
    this._state &= ~constants.state.CONNECTING
    this._continueOpen()

    this.emit('connect')
  }

  _onaccept() {
    this._state |= constants.state.CONNECTED | constants.state.READABLE | constants.state.WRITABLE
    this._continueOpen()
  }

  _onread(err, read) {
    if (err) {
      this.destroy(err)
      return
    }

    if (read === 0) {
      this.push(null)
      if (this._allowHalfOpen === false) this.end()
      return
    }

    const copy = Buffer.allocUnsafe(read)
    copy.set(this._buffer.subarray(0, read))

    if (this.push(copy) === false && this.destroying === false) {
      this._state &= ~constants.state.READING

      binding.pause(this._handle)
    }
  }

  _onhandle(type) {
    this.emit('handle', type)
  }

  _onwrite(err) {
    this._continueWrite(err)
  }

  _onfinal(err) {
    this._continueFinal(err === null || err.code === 'ENOTCONN' ? null : err)
  }

  _onclose() {
    this._continueDestroy()
  }

  _onspawn(readable, writable) {
    this._state |= constants.state.CONNECTED

    if (readable) {
      this._state |= constants.state.READABLE
    } else {
      this.push(null)
    }

    if (writable) {
      this._state |= constants.state.WRITABLE
    } else {
      this.end()
    }

    this._continueOpen()
  }
}

exports.Pipe = exports

exports.pipe = function pipe() {
  return binding.pipe()
}

exports.Server = class PipeServer extends EventEmitter {
  constructor(opts = {}, onconnection) {
    if (typeof opts === 'function') {
      onconnection = opts
      opts = {}
    }

    super()

    const {
      readBufferSize = defaultReadBufferSize,
      allowHalfOpen = true,
      pauseOnConnect = false,
      ipc = false
    } = opts

    this._state = 0

    this._readBufferSize = readBufferSize
    this._allowHalfOpen = allowHalfOpen
    this._pauseOnConnect = pauseOnConnect
    this._ipc = ipc

    this._path = null
    this._connections = new Set()

    this._error = null
    this._handle = null

    if (onconnection) this.on('connection', onconnection)
  }

  get listening() {
    return (this._state & constants.state.BOUND) !== 0
  }

  address() {
    if ((this._state & constants.state.BOUND) === 0) {
      return null
    }

    return this._path
  }

  listen(path, backlog = 511, opts = {}, onlistening) {
    if (this._state & constants.state.BINDING || this._state & constants.state.BOUND) {
      throw errors.SERVER_ALREADY_LISTENING('Server is already listening')
    }

    if (this._state & constants.state.CLOSING) {
      throw errors.SERVER_IS_CLOSED('Server is closed')
    }

    this._state |= constants.state.BINDING

    if (typeof backlog === 'function') {
      onlistening = backlog
      backlog = 511
    } else if (typeof opts === 'function') {
      onlistening = opts
      opts = {}
    }

    if (typeof path === 'object' && path !== null) {
      opts = path || {}
      path = opts.path
      backlog = opts.backlog || 511
    }

    this._handle = binding.init(
      empty,
      this._ipc,
      this,
      this._onconnection,
      noop,
      noop,
      noop,
      noop,
      noop,
      this._onclose
    )

    if (this._state & constants.state.UNREFED) binding.unref(this._handle)

    try {
      binding.bind(this._handle, path, backlog)

      this._path = path
      this._state |= constants.state.BOUND
      this._state &= ~constants.state.BINDING

      if (onlistening) this.once('listening', onlistening)

      queueMicrotask(() => this.emit('listening'))
    } catch (err) {
      this._error = err

      binding.close(this._handle)
    }

    return this
  }

  close(onclose) {
    if (onclose) this.once('close', onclose)

    if (this._state & constants.state.CLOSING) return
    this._state |= constants.state.CLOSING

    this._closeMaybe()

    return this
  }

  ref() {
    this._state &= ~constants.state.UNREFED

    if (this._handle !== null) binding.ref(this._handle)

    return this
  }

  unref() {
    this._state |= constants.state.UNREFED

    if (this._handle !== null) binding.unref(this._handle)

    return this
  }

  _closeMaybe() {
    if (this._state & constants.state.CLOSING && this._connections.size === 0) {
      if (this._handle !== null) binding.close(this._handle)
      else queueMicrotask(() => this.emit('close'))
    }
  }

  _onconnection(err) {
    if (err) {
      this.emit('error', err)
      return
    }

    if (this._state & constants.state.CLOSING) return

    const pipe = new exports.Pipe({
      readBufferSize: this._readBufferSize,
      allowHalfOpen: this._allowHalfOpen,
      eagerOpen: !this._pauseOnConnect,
      ipc: this._ipc
    })

    try {
      binding.accept(this._handle, pipe._handle)

      pipe._path = this._path
      pipe._onaccept()

      this._connections.add(pipe)

      pipe.on('close', () => {
        this._connections.delete(pipe)
        this._closeMaybe()
      })

      this.emit('connection', pipe)
    } catch (err) {
      pipe.destroy()

      throw err
    }
  }

  _onclose() {
    const err = this._error

    this._state &= ~constants.state.BINDING
    this._error = null
    this._handle = null

    if (err) this.emit('error', err)
    else this.emit('close')
  }
}

exports.constants = constants
exports.errors = errors

exports.createConnection = function createConnection(path, opts, onconnect) {
  if (typeof opts === 'function') {
    onconnect = opts
    opts = {}
  }

  if (typeof path === 'object' && path !== null) {
    opts = path || {}
    path = opts.path
  }

  return new exports.Pipe(opts).connect(path, opts, onconnect)
}

exports.createServer = function createServer(opts, onconnection) {
  return new exports.Server(opts, onconnection)
}

function noop() {}
const binding = require('../binding')

module.exports = {
  state: {
    CONNECTING: 0x1,
    CONNECTED: 0x2,
    BINDING: 0x4,
    BOUND: 0x8,
    READING: 0x10,
    CLOSING: 0x20,
    READABLE: 0x40,
    WRITABLE: 0x80,
    UNREFED: 0x100
  },
  handle: {
    NAMED_PIPE: binding.UV_NAMED_PIPE,
    TCP: binding.UV_TCP,
    UDP: binding.UV_UDP
  }
}
module.exports = class PipeError extends Error {
  constructor(msg, fn = PipeError, code = fn.name) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'PipeError'
  }

  static PIPE_ALREADY_CONNECTED(msg) {
    return new PipeError(msg, PipeError.PIPE_ALREADY_CONNECTED)
  }

  static SERVER_ALREADY_LISTENING(msg) {
    return new PipeError(msg, PipeError.SERVER_ALREADY_LISTENING)
  }

  static SERVER_IS_CLOSED(msg) {
    return new PipeError(msg, PipeError.SERVER_IS_CLOSED)
  }

  static INVALID_IPC_TARGET(msg) {
    return new PipeError(msg, PipeError.INVALID_IPC_TARGET)
  }
}
{
  "name": "bare-pipe",
  "version": "4.2.2",
  "description": "Native I/O pipes for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    },
    "./errors": {
      "types": "./lib/errors.d.ts",
      "default": "./lib/errors.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-pipe.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-pipe/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-pipe#readme",
  "engines": {
    "bare": ">=1.16.0"
  },
  "dependencies": {
    "bare-events": "^2.0.0",
    "bare-stream": "^2.0.0"
  },
  "devDependencies": {
    "bare-path": "^3.0.0",
    "bare-tcp": "^2.4.1",
    "brittle": "^3.2.1",
    "cmake-bare": "^1.1.6",
    "lunte": "^1.8.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  }
}
{
  "name": "bare-posix",
  "version": "1.0.1",
  "description": "POSIX-specific bindings for Bare",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "android": "./unsupported.js",
      "win32": "./unsupported.js",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "unsupported.js",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-posix.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-posix/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-posix#readme",
  "devDependencies": {
    "brittle": "^3.19.1",
    "cmake-bare": "^1.7.7",
    "lunte": "^1.6.0",
    "prettier": "^3.8.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
exports.getgid = function getgid() {
  return -1
}

exports.setgid = function setgid() {
  throw new Error('Platform not supported')
}

exports.getegid = function getegid() {
  return -1
}

exports.setegid = function setgid() {
  throw new Error('Platform not supported')
}

exports.getuid = function getuid() {
  return -1
}

exports.setuid = function setgid() {
  throw new Error('Platform not supported')
}

exports.geteuid = function geteuid() {
  return -1
}

exports.seteuid = function setgid() {
  throw new Error('Platform not supported')
}

exports.getgroups = function getgroups() {
  return []
}

exports.getgrnam = function getgrnam() {
  return null
}

exports.getpwnam = function getpwnam() {
  return null
}
const abort = require('bare-abort')
const EventEmitter = require('bare-events')
const Signal = require('bare-signals')
const os = require('bare-os')
const env = require('bare-env')
const hrtime = require('bare-hrtime')
const stdio = require('bare-stdio')
const posix = require('bare-posix')

class Process extends EventEmitter {
  constructor() {
    super()

    this._startTime = hrtime.bigint()

    EventEmitter.forward(Bare, this, [
      'uncaughtException',
      'unhandledRejection',
      'beforeExit',
      'exit',
      'suspend',
      'wakeup',
      'idle',
      'resume'
    ])

    const signals = new Signal.Emitter()

    signals.unref()

    EventEmitter.forward(signals, this, Object.keys(os.constants.signals))
  }

  get stdin() {
    return stdio.in
  }

  get stdout() {
    return stdio.out
  }

  get stderr() {
    return stdio.err
  }

  get platform() {
    return os.platform()
  }

  get arch() {
    return os.arch()
  }

  get title() {
    return os.getProcessTitle()
  }

  set title(title) {
    os.setProcessTitle(title)
  }

  get pid() {
    return os.pid()
  }

  get ppid() {
    return os.ppid()
  }

  get argv() {
    return Bare.argv
  }

  get execArgv() {
    return []
  }

  get execPath() {
    return os.execPath()
  }

  get exitCode() {
    return Bare.exitCode
  }

  set exitCode(code) {
    Bare.exitCode = code
  }

  get version() {
    return Bare.version
  }

  get versions() {
    return Bare.versions
  }

  get env() {
    return env
  }

  get hrtime() {
    return hrtime
  }

  abort() {
    abort()
  }

  exit(code) {
    Bare.exit(code)
  }

  suspend() {
    Bare.suspend()
  }

  resume() {
    Bare.resume()
  }

  cwd() {
    return os.cwd()
  }

  chdir(directory) {
    os.chdir(directory)
  }

  kill(pid, signal) {
    os.kill(pid, signal)
  }

  uptime() {
    return Number(hrtime.bigint() - this._startTime) / 1e9
  }

  cpuUsage(previous) {
    return os.cpuUsage(previous)
  }

  threadCpuUsage(previous) {
    return os.threadCpuUsage(previous)
  }

  resourceUsage() {
    return os.resourceUsage()
  }

  availableMemory() {
    return os.availableMemory()
  }

  constrainedMemory() {
    return os.constrainedMemory()
  }

  memoryUsage() {
    return os.memoryUsage()
  }

  getgid() {
    return posix.getgid()
  }

  setgid(id) {
    return posix.setgid(id)
  }

  getegid() {
    return posix.getegid()
  }

  setegid(id) {
    return posix.setegid(id)
  }

  getuid() {
    return posix.getuid()
  }

  setuid(id) {
    return posix.setuid(id)
  }

  geteuid() {
    return posix.geteuid()
  }

  seteuid(id) {
    return posix.seteuid(id)
  }

  getgroups() {
    return posix.getgroups()
  }

  nextTick(cb, ...args) {
    queueMicrotask(cb.bind(null, ...args))
  }

  [Symbol.for('bare.inspect')]() {
    return {
      __proto__: { constructor: Process },

      platform: this.platform,
      arch: this.arch,
      title: this.title,
      pid: this.pid,
      ppid: this.ppid,
      argv: this.argv,
      execPath: this.execPath,
      exitCode: this.exitCode,
      version: this.version,
      versions: this.versions,
      env: this.env
    }
  }
}

module.exports = new Process()
{
  "name": "bare-process",
  "version": "4.5.0",
  "description": "Node.js-compatible process control for Bare",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "global.js",
    "global.d.ts"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-process.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-process/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-process#readme",
  "dependencies": {
    "bare-abort": "^2.0.13",
    "bare-env": "^3.0.0",
    "bare-events": "^2.3.1",
    "bare-hrtime": "^2.0.0",
    "bare-os": "^3.7.1",
    "bare-posix": "^1.0.1",
    "bare-signals": "^4.0.0",
    "bare-stdio": "^1.0.1"
  },
  "devDependencies": {
    "brittle": "^3.2.1",
    "lunte": "^1.6.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = require.addon()
const EventEmitter = require('bare-events')
const os = require('bare-os')
const binding = require('./binding')
const errors = require('./lib/errors')

const signals = os.constants.signals

module.exports = exports = class Signal extends EventEmitter {
  constructor(signum) {
    super()

    if (typeof signum === 'string') {
      if (signum in signals === false) {
        throw errors.UNKNOWN_SIGNAL(`Unknown signal '${signum}'`)
      }

      signum = signals[signum]
    }

    this._signum = signum
    this._closing = null
    this._handle = binding.init(this, this._onsignal, this._onclose)
  }

  start() {
    if (this._closing) throw errors.SIGNAL_CLOSED('Signal is closed')
    binding.start(this._handle, this._signum)
    return this
  }

  stop() {
    if (this._closing) return this
    binding.stop(this._handle)
    return this
  }

  ref() {
    if (this._closing) return this
    binding.ref(this._handle)
    return this
  }

  unref() {
    if (this._closing) return this
    binding.unref(this._handle)
    return this
  }

  close() {
    if (this._closing) return this._closing
    this._closing = EventEmitter.once(this, 'close')

    binding.close(this._handle)

    return this._closing
  }

  _onsignal() {
    this.emit('signal', this._signum)
  }

  _onclose() {
    this._handle = null

    this.emit('close')
  }

  static send(signum, pid = os.pid()) {
    os.kill(pid, signum)
  }
}

exports.Emitter = require('./lib/emitter')

exports.constants = signals
exports.errors = errors
const EventEmitter = require('bare-events')
const Signal = require('..')

module.exports = class SignalEmitter extends EventEmitter {
  constructor() {
    super()

    this._signals = new Map()
    this._unrefed = false

    this.on('newListener', this._onnewlistener).on(
      'removeListener',
      this._onremovelistener
    )
  }

  ref() {
    this._unrefed = false
    for (const signal of this._signals.values()) signal.ref()
    return this
  }

  unref() {
    this._unrefed = true
    for (const signal of this._signals.values()) signal.unref()
    return this
  }

  _onnewlistener(name) {
    if (name === 'newListener' || name === 'removeListener') return

    if (this.listenerCount(name) === 0) {
      const signal = new Signal(name)

      signal.on('signal', this._onsignal.bind(this, name)).start()

      if (this._unrefed) signal.unref()

      this._signals.set(name, signal)
    }
  }

  _onremovelistener(name) {
    if (name === 'newListener' || name === 'removeListener') return

    if (this.listenerCount(name) === 0) {
      const signal = this._signals.get(name)

      if (this._unrefed) signal.ref()

      signal.close()

      this._signals.delete(name)
    }
  }

  _onsignal(name) {
    this.emit(name, name, Signal.constants[name])
  }
}
module.exports = class SignalError extends Error {
  constructor(msg, fn = SignalError, code = fn.name) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'SignalError'
  }

  static UNKNOWN_SIGNAL(msg) {
    return new SignalError(msg, SignalError.UNKNOWN_SIGNAL)
  }

  static SIGNAL_CLOSED(msg) {
    return new SignalError(msg, SignalError.SIGNAL_CLOSED)
  }
}
{
  "name": "bare-signals",
  "version": "4.2.0",
  "description": "Native signal handling for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./errors": "./lib/errors.js",
    "./emitter": "./lib/emitter.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-signals.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-signals/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-signals#readme",
  "engines": {
    "bare": ">=1.7.0"
  },
  "dependencies": {
    "bare-events": "^2.5.3",
    "bare-os": "^3.3.1"
  },
  "devDependencies": {
    "brittle": "^3.2.1",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
module.exports = require.addon()
const fs = require('bare-fs')
const tty = require('bare-tty')
const Pipe = require('bare-pipe')
const binding = require('./binding')

const { TTY, NAMED_PIPE } = binding

class IO {
  constructor() {
    this._in = null
    this._out = null
    this._err = null
  }

  get in() {
    if (this._in === null) {
      switch (binding.guessType(0)) {
        case TTY:
          this._in = new tty.ReadStream(0)
          break
        case NAMED_PIPE:
          this._in = new Pipe(0, { eagerOpen: false })
          break
        default:
          this._in = fs.createReadStream(null, { fd: 0, eagerOpen: false })
      }
    }

    return this._in
  }

  get out() {
    if (this._out === null) {
      switch (binding.guessType(1)) {
        case TTY:
          this._out = new tty.WriteStream(1)
          break
        case NAMED_PIPE:
          this._out = new Pipe(1, { eagerOpen: false })
          this._out.unref()
          break
        default:
          this._out = fs.createWriteStream(null, { fd: 1, eagerOpen: false })
      }
    }

    return this._out
  }

  get err() {
    if (this._err === null) {
      switch (binding.guessType(2)) {
        case TTY:
          this._err = new tty.WriteStream(2)
          break
        case NAMED_PIPE:
          this._err = new Pipe(2, { eagerOpen: false })
          this._err.unref()
          break
        default:
          this._err = fs.createWriteStream(null, { fd: 2, eagerOpen: false })
      }
    }

    return this._err
  }
}

module.exports = new IO()
{
  "name": "bare-stdio",
  "version": "1.0.2",
  "description": "Standard input/output streams for Bare",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./constants": "./lib/constants.js",
    "./errors": "./lib/errors.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-stdio.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-stdio/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-stdio#readme",
  "dependencies": {
    "bare-fs": "^4.5.2",
    "bare-pipe": "^4.1.5",
    "bare-tty": "^5.0.3"
  },
  "devDependencies": {
    "bare-os": "^3.6.2",
    "bare-path": "^3.0.0",
    "bare-subprocess": "^3.1.4",
    "brittle": "^3.19.1",
    "cmake-bare": "^1.7.7",
    "lunte": "^1.4.0",
    "prettier": "^3.8.1",
    "prettier-config-holepunch": "^2.0.0",
    "tt-native": "^1.1.1"
  }
}
const b4a = require('b4a')
const stream = require('streamx')
const { ReadableStream, WritableStream } = require('./web')

const defaultEncoding = 'utf8'

module.exports = exports = stream.Stream

exports.pipeline = stream.pipeline

exports.isStream = stream.isStream
exports.isEnding = stream.isEnding
exports.isEnded = stream.isEnded
exports.isFinishing = stream.isFinishing
exports.isFinished = stream.isFinished
exports.isDisturbed = stream.isDisturbed

exports.isErrored = function isErrored(stream) {
  return exports.getStreamError(stream) !== null
}

exports.isReadable = function isReadable(stream) {
  return stream.readable && !stream.destroying && !exports.isEnded(stream)
}

exports.isWritable = function isWritable(stream) {
  return stream.writable && !stream.destroying && !exports.isFinishing(stream)
}

exports.getStreamError = stream.getStreamError

exports.addAbortSignal = function addAbortSignal(signal, stream) {
  function onAbort() {
    stream.destroy(signal.reason)
  }

  if (signal.aborted) onAbort()
  else signal.addEventListener('abort', onAbort)

  return stream
}

exports.Stream = exports

exports.Readable = class Readable extends stream.Readable {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthReadable: null,
      map: null,
      mapReadable: null
    })

    if (this._construct) this._open = this._construct

    if (this._read !== stream.Readable.prototype._read) {
      this._read = read.bind(this, this._read)
    }

    if (this._destroy !== stream.Stream.prototype._destroy) {
      this._destroy = destroy.bind(this, this._destroy)
    }
  }

  get closed() {
    return !exports.isReadable(this)
  }

  get errored() {
    return stream.getStreamError(this)
  }

  push(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    return super.push(chunk)
  }

  unshift(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    super.unshift(chunk)
  }

  static fromWeb(readableStream, opts = {}) {
    const stream = readableStream._stream

    if (opts.encoding) stream.setEncoding(opts.encoding)
    if (opts.signal) exports.addAbortSignal(opts.signal, stream)

    return stream
  }

  static toWeb(readable, opts = {}) {
    return new ReadableStream(readable, opts.strategy)
  }

  async [Symbol.asyncDispose]() {
    if (!this.destroyed) this.destroy()

    await new Promise((resolve) => exports.finished(this, resolve))
  }
}

exports.Writable = class Writable extends stream.Writable {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthWritable,
      map: null,
      mapWritable: null
    })

    if (this._construct) this._open = this._construct

    if (this._write !== stream.Writable.prototype._write) {
      this._write = write.bind(this, this._write)
    }

    if (this._destroy !== stream.Stream.prototype._destroy) {
      this._destroy = destroy.bind(this, this._destroy)
    }
  }

  get closed() {
    return !exports.isWritable(this)
  }

  get errored() {
    return stream.getStreamError(this)
  }

  write(chunk, encoding, cb) {
    if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result = super.write({ chunk, encoding })

    if (cb) stream.Writable.drained(this).then(() => cb(null), cb)

    return result
  }

  end(chunk, encoding, cb) {
    if (typeof chunk === 'function') {
      cb = chunk
      chunk = null
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    } else {
      encoding = 'buffer'
    }

    const result =
      chunk !== undefined && chunk !== null ? super.end({ chunk, encoding }) : super.end()

    if (cb) this.once('finish', () => cb(null))

    return result
  }

  static fromWeb(writableStream, opts = {}) {
    const stream = writableStream._stream

    if (opts.signal) exports.addAbortSignal(opts.signal, stream)

    return stream
  }

  static toWeb(writable) {
    return new WritableStream(writable)
  }

  async [Symbol.asyncDispose]() {
    if (!this.destroyed) this.destroy()

    await new Promise((resolve) => exports.finished(this, resolve))
  }
}

exports.Duplex = class Duplex extends stream.Duplex {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthReadable: null,
      byteLengthWritable,
      map: null,
      mapReadable: null,
      mapWritable: null
    })

    if (this._construct) this._open = this._construct

    if (this._read !== stream.Readable.prototype._read) {
      this._read = read.bind(this, this._read)
    }

    if (this._write !== stream.Duplex.prototype._write) {
      this._write = write.bind(this, this._write)
    }

    if (this._destroy !== stream.Stream.prototype._destroy) {
      this._destroy = destroy.bind(this, this._destroy)
    }
  }

  push(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    return super.push(chunk)
  }

  unshift(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    super.unshift(chunk)
  }

  write(chunk, encoding, cb) {
    if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result = super.write({ chunk, encoding })

    if (cb) stream.Writable.drained(this).then(() => cb(null), cb)

    return result
  }

  end(chunk, encoding, cb) {
    if (typeof chunk === 'function') {
      cb = chunk
      chunk = null
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result =
      chunk !== undefined && chunk !== null ? super.end({ chunk, encoding }) : super.end()

    if (cb) this.once('finish', () => cb(null))

    return result
  }

  static fromWeb({ readable: readableStream, writable: writableStream }, opts) {
    const readable = exports.Readable.fromWeb(readableStream, opts)
    const writable = exports.Writable.fromWeb(writableStream, opts)

    const duplex = new exports.Duplex({
      write(data, encoding, cb) {
        writable.write(data, encoding, cb)
      }
    })

    readable
      .on('data', (data) => duplex.push(data))
      .on('end', () => duplex.push(null))
      .on('error', (err) => duplex.destroy(err))

    writable.on('finish', () => duplex.end()).on('error', (err) => duplex.destroy(err))

    return duplex
  }

  static toWeb(duplex) {
    const readableStream = exports.Readable.toWeb(duplex)
    const writableStream = exports.Writable.toWeb(duplex)

    return { readable: readableStream, writable: writableStream }
  }
}

class DuplexSide extends exports.Duplex {
  constructor(opts) {
    super(opts)

    this._otherSide = null
    this._cb = null
  }

  _read() {
    const cb = this._cb
    if (!cb) return

    this._cb = null
    cb()
  }

  _write(chunk, encoding, cb) {
    this._otherSide.push(chunk, encoding)
    this._otherSide._cb = cb
  }

  _final(cb) {
    this._otherSide.on('end', cb)
    this._otherSide.push(null)
  }
}

exports.duplexPair = function duplexPair(opts) {
  const sideA = new DuplexSide(opts)
  const sideB = new DuplexSide(opts)

  sideA._otherSide = sideB
  sideB._otherSide = sideA

  return [sideA, sideB]
}

exports.Transform = class Transform extends stream.Transform {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthReadable: null,
      byteLengthWritable,
      map: null,
      mapReadable: null,
      mapWritable: null
    })

    if (this._transform !== stream.Transform.prototype._transform) {
      this._transform = transform.bind(this, this._transform)
    } else {
      this._transform = passthrough
    }
  }

  push(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    return super.push(chunk)
  }

  unshift(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    super.unshift(chunk)
  }

  write(chunk, encoding, cb) {
    if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result = super.write({ chunk, encoding })

    if (cb) stream.Writable.drained(this).then(() => cb(null), cb)

    return result
  }

  end(chunk, encoding, cb) {
    if (typeof chunk === 'function') {
      cb = chunk
      chunk = null
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result =
      chunk !== undefined && chunk !== null ? super.end({ chunk, encoding }) : super.end()

    if (cb) this.once('finish', () => cb(null))

    return result
  }
}

exports.PassThrough = class PassThrough extends exports.Transform {}

exports.finished = function finished(stream, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (!opts) opts = {}

  const { cleanup = false } = opts

  const done = () => {
    cb(exports.getStreamError(stream, { all: true }))

    if (cleanup) detach()
  }

  const detach = () => {
    stream.off('close', done)
    stream.off('error', noop)
  }

  if (stream.destroyed) {
    done()
  } else {
    stream.on('close', done)
    stream.on('error', noop)
  }

  return detach
}

function read(read, cb) {
  read.call(this, 65536)

  cb(null)
}

function write(write, data, cb) {
  write.call(this, data.chunk, data.encoding, cb)
}

function transform(transform, data, cb) {
  transform.call(this, data.chunk, data.encoding, cb)
}

function destroy(destroy, cb) {
  destroy.call(this, exports.getStreamError(this), cb)
}

function passthrough(data, cb) {
  cb(null, data.chunk)
}

function byteLengthWritable(data) {
  return data.chunk.byteLength
}

function noop() {}
{
  "name": "bare-stream",
  "version": "2.13.3",
  "description": "Streaming data for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./promises": "./promises.js",
    "./web": {
      "types": "./web.d.ts",
      "default": "./web.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "promises.js",
    "web.js",
    "web.d.ts",
    "global.js",
    "global.d.ts"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-stream.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-stream/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-stream#readme",
  "dependencies": {
    "b4a": "^1.8.1",
    "streamx": "^2.25.0",
    "teex": "^1.0.1"
  },
  "devDependencies": {
    "bare-abort-controller": "^1.1.0",
    "bare-buffer": "^3.0.0",
    "bare-events": "^2.5.4",
    "brittle": "^3.5.2",
    "lunte": "^1.6.0",
    "prettier": "^3.3.3",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "bare-abort-controller": "*",
    "bare-buffer": "*",
    "bare-events": "*"
  },
  "peerDependenciesMeta": {
    "bare-abort-controller": {
      "optional": true
    },
    "bare-buffer": {
      "optional": true
    },
    "bare-events": {
      "optional": true
    }
  }
}
const { Readable, Writable, Transform, getStreamError, isStreamx, isDisturbed } = require('streamx')
const tee = require('teex')

const readableKind = Symbol.for('bare.stream.readable.kind')
const writableKind = Symbol.for('bare.stream.writable.kind')
const transformKind = Symbol.for('bare.stream.transform.kind')

// https://streams.spec.whatwg.org/#readablestreamdefaultreader
exports.ReadableStreamDefaultReader = class ReadableStreamDefaultReader {
  constructor(stream) {
    this._stream = stream
    this._stream._stream.once('close', onclose).once('error', onerror)

    const closed = Promise.withResolvers()

    // Avoid unhandled exceptions
    closed.promise.catch(noop)

    this._closed = closed

    function onclose() {
      closed.resolve()
    }

    function onerror(err) {
      closed.reject(err)
    }
  }

  get closed() {
    return this._closed.promise
  }

  read() {
    const stream = this._stream._stream

    return new Promise((resolve, reject) => {
      const err = getStreamError(stream)

      if (err) return reject(err)

      if (stream.destroyed) {
        return resolve({ value: undefined, done: true })
      }

      const value = stream.read()

      if (value !== null) {
        return resolve({ value, done: false })
      }

      stream.once('readable', onreadable).once('close', onclose).once('error', onerror)

      function onreadable() {
        const value = stream.read()

        ondone(null, value === null ? { value: undefined, done: true } : { value, done: false })
      }

      function onclose() {
        ondone(null, { value: undefined, done: true })
      }

      function onerror(err) {
        ondone(err, null)
      }

      function ondone(err, value) {
        stream.off('readable', onreadable).off('close', onclose).off('error', onerror)

        if (err) reject(err)
        else resolve(value)
      }
    })
  }

  releaseLock() {
    this._closed.reject(new TypeError('Reader was released'))
    this._stream._releaseLock()
    this._stream = null
  }

  cancel(reason = new TypeError('Stream was cancelled')) {
    const stream = this._stream._stream

    if (stream.destroyed) return Promise.resolve()

    return new Promise((resolve) =>
      stream.once('close', resolve).once('error', noop).destroy(reason)
    )
  }
}

// https://streams.spec.whatwg.org/#readablestreamdefaultcontroller
exports.ReadableStreamDefaultController = class ReadableStreamDefaultController {
  constructor(stream) {
    this._stream = stream
  }

  get desiredSize() {
    const stream = this._stream._stream

    return stream._readableState.highWaterMark - stream._readableState.buffered
  }

  enqueue(data) {
    this._stream._stream.push(data)
  }

  close() {
    this._stream._stream.push(null)
  }

  error(err) {
    this._stream._stream.destroy(err)
  }
}

// https://streams.spec.whatwg.org/#readablestream
class ReadableStream {
  static get [readableKind]() {
    return 0 // Compatibility version
  }

  static from(iterable) {
    return new ReadableStream(Readable.from(iterable))
  }

  constructor(underlyingSource = {}, queuingStrategy) {
    if (isStreamx(underlyingSource)) {
      this._stream = underlyingSource
    } else {
      if (queuingStrategy === undefined) {
        queuingStrategy = new exports.CountQueuingStrategy()
      }

      const { start, pull, cancel } = underlyingSource
      const { highWaterMark = 1, size = defaultSize } = queuingStrategy

      this._stream = new Readable({ highWaterMark, byteLength: size })

      const controller = new exports.ReadableStreamDefaultController(this)

      try {
        let starting = Promise.resolve()

        if (start) starting = forwardError(start.call(this, controller), controller)

        if (pull) {
          this._stream._read = this._read.bind(this, starting, pull.bind(this, controller))
        }

        if (cancel) {
          this._stream.once('error', cancel.bind(this))
        }
      } catch (err) {
        controller.error(err)
      }
    }

    this._reader = null
  }

  get [readableKind]() {
    return ReadableStream[readableKind]
  }

  get locked() {
    return this._reader !== null
  }

  getReader() {
    if (this.locked) throw new TypeError('Stream is locked')

    this._reader = new exports.ReadableStreamDefaultReader(this)

    return this._reader
  }

  cancel(reason = new TypeError('Stream was cancelled')) {
    const stream = this._stream

    if (stream.destroyed) return Promise.resolve()

    if (this.locked) return Promise.reject(new TypeError('Stream is locked'))

    return new Promise((resolve) =>
      stream.once('close', resolve).once('error', noop).destroy(reason)
    )
  }

  tee() {
    const [a, b] = tee(this._stream)

    return [new ReadableStream(a), new ReadableStream(b)]
  }

  pipeTo(destination) {
    return new Promise((resolve, reject) =>
      this._stream.pipe(destination._stream, (err) => {
        err ? reject(err) : resolve()
      })
    )
  }

  [Symbol.asyncIterator]() {
    return this._stream[Symbol.asyncIterator]()
  }

  _releaseLock() {
    this._reader = null
  }

  async _read(starting, pull, cb) {
    await starting

    let err = null
    try {
      await pull()
    } catch (e) {
      err = e
    }
    cb(err)
  }
}

function defaultSize() {
  return 1
}

exports.ReadableStream = ReadableStream

// https://streams.spec.whatwg.org/#countqueuingstrategy
exports.CountQueuingStrategy = class CountQueuingStrategy {
  constructor(opts = {}) {
    const { highWaterMark = 1 } = opts

    this.highWaterMark = highWaterMark
  }

  size(chunk) {
    return 1
  }
}

// https://streams.spec.whatwg.org/#bytelengthqueuingstrategy
exports.ByteLengthQueuingStrategy = class ByteLengthQueuingStrategy {
  constructor(opts = {}) {
    const { highWaterMark = 16384 } = opts

    this.highWaterMark = highWaterMark
  }

  size(chunk) {
    return chunk.byteLength
  }
}

exports.isReadableStream = function isReadableStream(value) {
  if (value instanceof ReadableStream) return true

  return (
    typeof value === 'object' &&
    value !== null &&
    value[readableKind] === ReadableStream[readableKind]
  )
}

// https://streams.spec.whatwg.org/#readablestream-errored
exports.isReadableStreamErrored = function isReadableStreamErrored(stream) {
  return getStreamError(stream._stream) !== null
}

// https://streams.spec.whatwg.org/#is-readable-stream-disturbed
exports.isReadableStreamDisturbed = function isReadableStreamDisturbed(stream) {
  return isDisturbed(stream._stream)
}

// https://streams.spec.whatwg.org/#writablestreamdefaultwriter
exports.WritableStreamDefaultWriter = class WritableStreamDefaultWriter {
  constructor(stream) {
    this._stream = stream
    this._stream._stream.once('close', onclose).once('error', onerror)

    const closed = Promise.withResolvers()

    // Avoid unhandled exceptions
    closed.promise.catch(noop)

    this._closed = closed

    function onclose() {
      closed.resolve()
    }

    function onerror(err) {
      closed.reject(err)
    }
  }

  get desiredSize() {
    const stream = this._stream._stream

    return stream._writableState.highWaterMark - stream._writableState.buffered
  }

  get closed() {
    return this._closed.promise
  }

  get ready() {
    const stream = this._stream._stream

    if (getStreamError(stream)) return Promise.reject()

    return Writable.drained(stream).then()
  }

  async write(chunk) {
    const stream = this._stream._stream

    let err = getStreamError(stream)
    if (err) return Promise.reject(err)

    stream.write(chunk)

    await Writable.drained(stream)

    err = getStreamError(stream)
    if (err) return Promise.reject(err)
  }

  releaseLock() {
    this._closed.reject(new TypeError('Writer was released'))
    this._stream._releaseLock()
    this._stream = null
  }

  close() {
    const stream = this._stream._stream

    if (stream.destroyed) return Promise.resolve()

    return new Promise((resolve) => stream.once('close', resolve).end())
  }

  abort(reason = new TypeError('Stream was aborted')) {
    const stream = this._stream._stream

    if (stream.destroyed) return Promise.resolve()

    return new Promise((resolve) => stream.once('close', resolve).destroy(reason))
  }
}

// https://streams.spec.whatwg.org/#writablestreamdefaultcontroller
exports.WritableStreamDefaultController = class WritableStreamDefaultController {
  constructor(stream) {
    this._stream = stream
  }

  error(err) {
    this._stream._stream.destroy(err)
  }
}

// https://streams.spec.whatwg.org/#writablestream
class WritableStream {
  static get [writableKind]() {
    return 0 // Compatibility version
  }

  constructor(underlyingSink = {}, queuingStrategy = {}) {
    if (isStreamx(underlyingSink)) {
      this._stream = underlyingSink
    } else {
      if (queuingStrategy === undefined) {
        queuingStrategy = new exports.CountQueuingStrategy()
      }

      const { start, write, close, abort } = underlyingSink
      const { highWaterMark = 1, size = defaultSize } = queuingStrategy

      this._stream = new Writable({ highWaterMark, byteLength: size })

      const controller = new exports.WritableStreamDefaultController(this)

      this._controller = controller

      try {
        let starting = Promise.resolve()

        if (start) starting = forwardError(start.call(this, controller), controller)

        if (write) {
          this._stream._write = this._write.bind(this, starting, write.bind(this))
        }

        if (close) {
          this._stream._destroy = this._destroy.bind(this, close.call(this))
        }

        if (abort) {
          this._stream.once('error', abort.bind(this))
        }
      } catch (err) {
        controller.error(err)
      }
    }

    this._writer = null
  }

  get [writableKind]() {
    return WritableStream[writableKind]
  }

  get locked() {
    return this._writer !== null
  }

  getWriter() {
    if (this.locked) throw new TypeError('Stream is locked')

    this._writer = new exports.WritableStreamDefaultWriter(this)

    return this._writer
  }

  abort(reason = new TypeError('Stream was aborted')) {
    if (this._stream.destroyed) return Promise.resolve()

    if (this.locked) return Promise.reject(new TypeError('Stream is locked'))

    return new Promise((resolve) => this._stream.once('close', resolve).destroy(reason))
  }

  close() {
    if (this._stream.destroyed) return Promise.resolve()

    if (this.locked) return Promise.reject(new TypeError('Stream is locked'))

    return new Promise((resolve) => this._stream.once('close', resolve).end())
  }

  _releaseLock() {
    this._writer = null
  }

  async _write(starting, write, data, cb) {
    await starting

    let err = null
    try {
      await write(data, this._controller)
    } catch (e) {
      err = e
    }
    cb(err)
  }

  async _destroy(closing, cb) {
    let err = null
    try {
      await closing
    } catch (e) {
      err = e
    }
    cb(err)
  }
}

exports.WritableStream = WritableStream

exports.isWritableStream = function isWritableStream(value) {
  if (value instanceof WritableStream) return true

  return (
    typeof value === 'object' &&
    value !== null &&
    value[writableKind] === WritableStream[writableKind]
  )
}

// https://streams.spec.whatwg.org/#transformstreamdefaultcontroller
exports.TransformStreamDefaultController = class TransformStreamDefaultController {
  constructor(stream) {
    this._stream = stream
  }

  get desiredSize() {
    const stream = this._stream._stream

    return stream._readableState.highWaterMark - stream._readableState.buffered
  }

  enqueue(data) {
    this._stream._stream.push(data)
  }

  error(err) {
    this._stream._stream.destroy(err)
  }

  terminate() {
    const stream = this._stream._stream

    stream.push(null)
    stream.destroy(new TypeError('Stream has been terminated'))
  }
}

// https://streams.spec.whatwg.org/#transformstream
class TransformStream {
  static get [transformKind]() {
    return 0 // Compatibility version
  }

  constructor(transformer = {}, writableStrategy = {}, readableStrategy = {}) {
    if (isStreamx(transformer)) {
      this._stream = transformer
    } else {
      const { start, transform, flush } = transformer

      this._stream = new Transform({ ...writableStrategy, ...readableStrategy })

      const controller = new exports.TransformStreamDefaultController(this)

      this._controller = controller

      try {
        let starting = Promise.resolve()

        if (start) starting = forwardError(start.call(this, controller), controller)

        if (transform) {
          this._stream._transform = this._transform.bind(this, starting, transform.bind(this))
        }

        if (flush) {
          this._stream._flush = this._flush.bind(this, flush.call(this, this._controller))
        }
      } catch (err) {
        controller.error(err)
      }
    }

    this._writable = new WritableStream(this._stream)
    this._readable = new ReadableStream(this._stream)
  }

  get [transformKind]() {
    return TransformStream[transformKind]
  }

  get writable() {
    return this._writable
  }

  get readable() {
    return this._readable
  }

  async _transform(starting, transform, data, cb) {
    await starting

    let err = null
    try {
      await transform(data, this._controller)
    } catch (e) {
      err = e
    }
    cb(err)
  }

  async _flush(flush, cb) {
    let err = null
    try {
      await flush
    } catch (e) {
      err = e
    }
    cb(err)
  }
}

exports.TransformStream = TransformStream

exports.isTransformStream = function isTransformStream(value) {
  if (value instanceof TransformStream) return true

  return (
    typeof value === 'object' &&
    value !== null &&
    value[transformKind] === TransformStream[transformKind]
  )
}

async function forwardError(promise, controller) {
  try {
    await promise
  } catch (err) {
    controller.error(err)
  }
}

function noop() {}
module.exports = require.addon()
const EventEmitter = require('bare-events')
const { Duplex } = require('bare-stream')
const dns = require('bare-dns')
const binding = require('./binding')
const constants = require('./lib/constants')
const errors = require('./lib/errors')
const ip = require('./lib/ip')

const defaultReadBufferSize = 65536
const empty = Buffer.alloc(0)

const ipcHandle = Symbol.for('bare.ipc.handle')
const ipcAccept = Symbol.for('bare.ipc.accept')

exports.Socket = class TCPSocket extends Duplex {
  constructor(opts = {}) {
    const { readBufferSize = defaultReadBufferSize, allowHalfOpen = true, eagerOpen = true } = opts

    super({ eagerOpen })

    this._state = 0

    this._allowHalfOpen = allowHalfOpen

    this._keepAlive = 0
    this._keepAliveInitialDelay = 0
    this._noDelay = 0

    this._localAddress = null
    this._remoteAddress = null

    this._pendingOpen = null
    this._pendingWrite = null
    this._pendingWriteBatch = null
    this._pendingFinal = null
    this._pendingDestroy = null

    this._timer = null
    this._timeout = 0

    this._buffer = Buffer.alloc(readBufferSize)

    this._addresses = null
    this._errors = null

    this._handle = binding.init(
      this._buffer,
      this,
      noop,
      this._onconnect,
      this._onreset,
      this._onread,
      this._onwrite,
      this._onfinal,
      this._onclose
    )
  }

  get connecting() {
    return (this._state & constants.state.CONNECTING) !== 0
  }

  get pending() {
    return (this._state & constants.state.CONNECTED) === 0
  }

  get timeout() {
    return this._timeout || undefined // For Node.js compatibility
  }

  get readyState() {
    if (this._state & constants.state.CONNECTED) {
      return 'open'
    }

    return 'opening'
  }

  get localAddress() {
    if (this._localAddress) return this._localAddress.address
  }

  get localFamily() {
    if (this._localAddress) return `IPv${this._localAddress.family}`
  }

  get localPort() {
    if (this._localAddress) return this._localAddress.port
  }

  get remoteAddress() {
    if (this._remoteAddress) return this._remoteAddress.address
  }

  get remoteFamily() {
    if (this._remoteAddress) return `IPv${this._remoteAddress.family}`
  }

  get remotePort() {
    if (this._remoteAddress) return this._remoteAddress.port
  }

  get [ipcHandle]() {
    return this._handle
  }

  connect(port, host = 'localhost', opts = {}, onconnect) {
    if (this._state & constants.state.CONNECTING || this._state & constants.state.CONNECTED) {
      throw errors.SOCKET_ALREADY_CONNECTED('Socket is already connected')
    }

    if (typeof host === 'function') {
      onconnect = host
      host = 'localhost'
    } else if (typeof opts === 'function') {
      onconnect = opts
      opts = {}
    }

    let family = 0

    if (typeof port === 'object' && port !== null) {
      opts = port || {}
      port = opts.port || 0
      host = opts.host || 'localhost'
      family = opts.family || 0
    }

    if (!host) host = 'localhost'

    validatePort(port)

    this._state |= constants.state.CONNECTING

    const {
      lookup = dns.lookup,
      hints,
      keepAlive = false,
      keepAliveInitialDelay = 0,
      noDelay = false,
      timeout
    } = opts

    const type = ip.isIP(host)

    if (type === 0) {
      lookup(host, { all: true, family, hints }, (err, addresses) => {
        if (this._state & constants.state.CLOSING) return

        this._state &= ~constants.state.CONNECTING

        if (err || addresses.length === 0) {
          if (!err) {
            err = new Error(`No address found for host "${host}"`)
            err.code = 'ENOTFOUND'
          }

          this.emit('lookup', err, null, 0, host)

          if (this._pendingOpen) this._continueOpen(err)
          else this.destroy(err)
          return
        }

        for (const { address, family } of addresses) {
          this.emit('lookup', null, address, family, host)
        }

        const [{ address, family }, ...rest] = addresses

        if (rest.length > 0) {
          this._addresses = rest.map(({ address, family }) => [
            port,
            address,
            { ...opts, family },
            onconnect
          ])

          this._errors = []
        }

        this.connect(port, address, { ...opts, family }, onconnect)
      })

      return this
    }

    family = type

    try {
      binding.connect(this._handle, port, host, family)

      if (keepAlive) {
        this._keepAlive = keepAlive
        this._keepAliveInitialDelay = keepAliveInitialDelay
      }
      if (noDelay) this._noDelay = noDelay
      if (timeout) this.setTimeout(timeout)

      if (onconnect) this.once('connect', onconnect)
    } catch (err) {
      queueMicrotask(() => {
        if (this._pendingOpen) this._pendingOpen(err)
        else this.destroy(err)
      })
    }

    return this
  }

  open(fd, opts = {}, onconnect) {
    if (typeof opts === 'function') {
      onconnect = opts
      opts = {}
    }

    if (typeof fd === 'object' && fd !== null) {
      opts = fd
      fd = opts.fd
    }

    try {
      binding.open(this._handle, fd)

      this._state |= constants.state.CONNECTED

      if (onconnect) this.once('connect', onconnect)

      queueMicrotask(() => this.emit('connect'))
    } catch (err) {
      queueMicrotask(() => {
        if (this._pendingOpen) this._pendingOpen(err)
        else this.destroy(err)
      })
    }

    return this
  }

  setKeepAlive(enable = false, delay = 0) {
    if (typeof enable === 'number') {
      delay = enable
      enable = false
    }

    delay = Math.floor(delay / 1000)

    if (delay === 0) enable = false

    binding.keepalive(this._handle, enable, delay)

    return this
  }

  setNoDelay(enable = true) {
    binding.nodelay(this._handle, enable)

    return this
  }

  setTimeout(ms, ontimeout) {
    if (ms === 0) {
      clearTimeout(this._timer)

      this._timer = null
    } else {
      if (ontimeout) this.once('timeout', ontimeout)

      this._timer = setTimeout(() => this.emit('timeout'), ms)
      this._timer.unref()
    }

    this._timeout = ms

    return this
  }

  ref() {
    binding.ref(this._handle)

    return this
  }

  unref() {
    binding.unref(this._handle)

    return this
  }

  [ipcAccept]() {
    this._onaccept()
  }

  _open(cb) {
    if (this._state & constants.state.CONNECTED) return cb(null)

    this._pendingOpen = cb
  }

  _read() {
    if ((this._state & constants.state.READING) === 0) {
      this._state |= constants.state.READING

      binding.resume(this._handle)
    }
  }

  _writev(batch, cb) {
    this._pendingWrite = cb
    this._pendingWriteBatch = batch

    try {
      binding.writev(
        this._handle,
        batch.map(({ chunk }) => chunk)
      )
    } catch (err) {
      this._continueWrite(err)
    }
  }

  _final(cb) {
    this._pendingFinal = cb

    binding.end(this._handle)
  }

  _predestroy() {
    if (this._state & constants.state.CLOSING) return
    this._state |= constants.state.CLOSING

    binding.close(this._handle)
  }

  _destroy(err, cb) {
    if (this._state & constants.state.CLOSING) return cb(err)
    this._state |= constants.state.CLOSING

    this._pendingDestroy = cb

    binding.close(this._handle)
  }

  _continueOpen(err) {
    if (this._pendingOpen === null) return
    const cb = this._pendingOpen
    this._pendingOpen = null
    cb(err)
  }

  _continueWrite(err) {
    if (this._pendingWrite === null) return
    const cb = this._pendingWrite
    this._pendingWrite = null
    this._pendingWriteBatch = null
    cb(err)
  }

  _continueFinal(err) {
    if (this._pendingFinal === null) return
    const cb = this._pendingFinal
    this._pendingFinal = null
    cb(err)
  }

  _continueDestroy() {
    if (this._pendingDestroy === null) return
    const cb = this._pendingDestroy
    this._pendingDestroy = null
    cb(null)
  }

  _reset() {
    this._state = 0

    this._localAddress = null
    this._remoteAddress = null

    binding.reset(this._handle)
  }

  _onconnect(err) {
    if (err) {
      if (this._addresses !== null) {
        this._errors.push(err)

        if (this._addresses.length > 0) return this._reset()

        err = this._errors.length === 1 ? this._errors[0] : new AggregateError(this._errors)
      }

      if (this._pendingOpen) this._continueOpen(err)
      else this.destroy(err)
      return
    }

    if (this._keepAlive) this.setKeepAlive(this._keepAlive, this._keepAliveInitialDelay)
    if (this._noDelay) this.setNoDelay()

    this._localAddress = binding.address(this._handle, true)
    this._remoteAddress = binding.address(this._handle, false)

    this._state |= constants.state.CONNECTED
    this._state &= ~constants.state.CONNECTING
    this._continueOpen()

    this.emit('connect')
  }

  _onaccept() {
    try {
      this._localAddress = binding.address(this._handle, true)
    } catch {
      this._localAddress = null
    }

    try {
      this._remoteAddress = binding.address(this._handle, false)
    } catch {
      this._remoteAddress = null
    }

    this._state |= constants.state.CONNECTED
    this._continueOpen()
  }

  _onreset(err) {
    if (err) {
      this._errors.push(err)
      this.destroy(this._errors.length === 1 ? this._errors[0] : new AggregateError(this._errors))
      return
    }

    this.connect(...this._addresses.shift())
  }

  _onread(err, read) {
    if (this._timer) this._timer.refresh()

    if (err) {
      this.destroy(err)
      return
    }

    if (read === 0) {
      this.push(null)
      if (this._allowHalfOpen === false) this.end()
      return
    }

    const copy = Buffer.allocUnsafe(read)
    copy.set(this._buffer.subarray(0, read))

    if (this.push(copy) === false && this.destroying === false) {
      this._state &= ~constants.state.READING

      binding.pause(this._handle)
    }
  }

  _onwrite(err) {
    if (this._timer) this._timer.refresh()

    this._continueWrite(err)
  }

  _onfinal(err) {
    this._continueFinal(err)
  }

  _onclose() {
    clearTimeout(this._timer)

    this._continueOpen()
    this._continueDestroy()
  }
}

exports.Server = class TCPServer extends EventEmitter {
  constructor(opts = {}, onconnection) {
    if (typeof opts === 'function') {
      onconnection = opts
      opts = {}
    }

    super()

    const {
      readBufferSize = defaultReadBufferSize,
      allowHalfOpen = true,
      keepAlive = false,
      keepAliveInitialDelay = 0,
      noDelay = false,
      pauseOnConnect = false,
      maxConnections = Infinity
    } = opts

    this._state = 0

    this._readBufferSize = readBufferSize
    this._allowHalfOpen = allowHalfOpen
    this._keepAlive = keepAlive
    this._keepAliveInitialDelay = keepAliveInitialDelay
    this._noDelay = noDelay
    this._pauseOnConnect = pauseOnConnect
    this._maxConnections = maxConnections

    this._address = null
    this._connections = new Set()

    this._error = null
    this._handle = null

    if (onconnection) this.on('connection', onconnection)
  }

  get listening() {
    return (this._state & constants.state.BOUND) !== 0
  }

  get closing() {
    return (this._state & constants.state.CLOSING) !== 0
  }

  get connections() {
    return this._connections
  }

  get maxConnections() {
    return this._maxConnections
  }

  set maxConnections(value) {
    this._maxConnections = value
  }

  address() {
    if ((this._state & constants.state.BOUND) === 0) return null

    const { address, family, port } = this._address

    return { address, family: `IPv${family}`, port }
  }

  listen(port = 0, host = 'localhost', backlog = 511, opts = {}, onlistening) {
    if (this._state & constants.state.BINDING || this._state & constants.state.BOUND) {
      throw errors.SERVER_ALREADY_LISTENING('Server is already listening')
    }

    if (this._state & constants.state.CLOSING) {
      throw errors.SERVER_IS_CLOSED('Server is closed')
    }

    if (typeof port === 'function') {
      onlistening = port
      port = 0
    } else if (typeof host === 'function') {
      onlistening = host
      host = 'localhost'
    } else if (typeof backlog === 'function') {
      onlistening = backlog
      backlog = 511
    } else if (typeof opts === 'function') {
      onlistening = opts
      opts = {}
    }

    let family = 0

    if (typeof port === 'object' && port !== null) {
      opts = port || {}
      port = opts.port || 0
      host = opts.host || 'localhost'
      family = opts.family || 0
      backlog = opts.backlog || 511
    }

    if (!host) host = 'localhost'
    if (!backlog) backlog = 511

    validatePort(port)

    this._state |= constants.state.BINDING

    const { lookup = dns.lookup, hints } = opts

    const type = ip.isIP(host)

    if (type === 0) {
      lookup(host, { family, hints }, (err, address, family) => {
        if (this._state & constants.state.CLOSING) return

        this.emit('lookup', err, address, family, host)

        this._state &= ~constants.state.BINDING

        if (err) return this.emit('error', err)

        this.listen(port, address, backlog, { ...opts, family }, onlistening)
      })

      return this
    }

    family = type

    this._handle = binding.init(
      empty,
      this,
      this._onconnection,
      noop,
      noop,
      noop,
      noop,
      noop,
      this._onclose
    )

    if (this._state & constants.state.UNREFED) binding.unref(this._handle)

    try {
      binding.bind(this._handle, port, host, backlog, family)

      this._address = binding.address(this._handle, true)

      this._state |= constants.state.BOUND
      this._state &= ~constants.state.BINDING

      if (onlistening) this.once('listening', onlistening)

      queueMicrotask(() => this.emit('listening'))
    } catch (err) {
      this._error = err

      binding.close(this._handle)
    }

    return this
  }

  close(onclose) {
    if (onclose) this.once('close', onclose)

    if (this._state & constants.state.CLOSING) return this
    this._state |= constants.state.CLOSING

    this._closeMaybe()

    return this
  }

  ref() {
    this._state &= ~constants.state.UNREFED

    if (this._handle !== null) binding.ref(this._handle)

    return this
  }

  unref() {
    this._state |= constants.state.UNREFED

    if (this._handle !== null) binding.unref(this._handle)

    return this
  }

  _closeMaybe() {
    if (this._state & constants.state.CLOSING && this._connections.size === 0) {
      if (this._handle !== null) binding.close(this._handle)
      else queueMicrotask(() => this.emit('close'))
    }
  }

  _onconnection(err) {
    if (err) {
      this.emit('error', err)
      return
    }

    if (this._state & constants.state.CLOSING) return

    const overLimit = this._connections.size >= this._maxConnections

    const socket = new exports.Socket({
      readBufferSize: overLimit ? 0 : this._readBufferSize,
      allowHalfOpen: this._allowHalfOpen,
      eagerOpen: !this._pauseOnConnect
    })

    try {
      binding.accept(this._handle, socket._handle)

      socket._onaccept()

      if (overLimit) {
        const info = {
          localAddress: socket.localAddress,
          localPort: socket.localPort,
          localFamily: socket.localFamily,
          remoteAddress: socket.remoteAddress,
          remotePort: socket.remotePort,
          remoteFamily: socket.remoteFamily
        }

        socket.destroy()

        this.emit('drop', info)
        return
      }

      this._connections.add(socket)

      if (this._keepAlive) socket.setKeepAlive(this._keepAlive, this._keepAliveInitialDelay)
      if (this._noDelay) socket.setNoDelay()

      socket.on('close', () => {
        this._connections.delete(socket)
        this._closeMaybe()
      })

      this.emit('connection', socket)
    } catch (err) {
      socket.destroy()

      this.emit('error', err)
    }
  }

  _onclose() {
    const err = this._error

    this._state &= ~constants.state.BINDING
    this._error = null
    this._handle = null
    this._address = null

    if (err) this.emit('error', err)
    else this.emit('close')
  }
}

exports.constants = constants
exports.errors = errors

exports.isIP = ip.isIP
exports.isIPv4 = ip.isIPv4
exports.isIPv6 = ip.isIPv6

exports.createConnection = function createConnection(port, host, opts, onconnect) {
  if (typeof host === 'function') {
    onconnect = host
    host = 'localhost'
  } else if (typeof opts === 'function') {
    onconnect = opts
    opts = {}
  }

  if (typeof port === 'object' && port !== null) {
    opts = port || {}
    port = opts.port || 0
    host = opts.host || 'localhost'
  }

  return new exports.Socket(opts).connect(port, host, opts, onconnect)
}

// For Node.js compatibility
exports.connect = exports.createConnection

exports.createServer = function createServer(opts, onconnection) {
  return new exports.Server(opts, onconnection)
}

exports.socketpair = function socketpair() {
  return binding.socketpair()
}

function validatePort(port) {
  if (typeof port !== 'number' || !Number.isInteger(port) || port < 0 || port > 0xffff) {
    throw errors.INVALID_PORT(`Port must be an integer between 0 and 65535, got ${port}`)
  }
}

function noop() {}
module.exports = {
  state: {
    CONNECTING: 0x1,
    CONNECTED: 0x2,
    BINDING: 0x4,
    BOUND: 0x8,
    READING: 0x10,
    CLOSING: 0x20,
    UNREFED: 0x40
  }
}
module.exports = class TCPError extends Error {
  constructor(msg, fn = TCPError, code = fn.name) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'TCPError'
  }

  static SOCKET_ALREADY_CONNECTED(msg) {
    return new TCPError(msg, TCPError.SOCKET_ALREADY_CONNECTED)
  }

  static SERVER_ALREADY_LISTENING(msg) {
    return new TCPError(msg, TCPError.SERVER_ALREADY_LISTENING)
  }

  static SERVER_IS_CLOSED(msg) {
    return new TCPError(msg, TCPError.SERVER_IS_CLOSED)
  }

  static INVALID_HOST(msg = 'Unrecognizable host format') {
    return new TCPError(msg, TCPError.INVALID_HOST)
  }

  static INVALID_PORT(msg) {
    return new TCPError(msg, TCPError.INVALID_PORT)
  }
}
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

const v4Seg = '(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])'
const v4Str = `(${v4Seg}[.]){3}${v4Seg}`
const IPv4Pattern = new RegExp(`^${v4Str}$`)

const v6Seg = '(?:[0-9a-fA-F]{1,4})'
const IPv6Pattern = new RegExp(
  '^(' +
    `(?:${v6Seg}:){7}(?:${v6Seg}|:)|` +
    `(?:${v6Seg}:){6}(?:${v4Str}|:${v6Seg}|:)|` +
    `(?:${v6Seg}:){5}(?::${v4Str}|(:${v6Seg}){1,2}|:)|` +
    `(?:${v6Seg}:){4}(?:(:${v6Seg}){0,1}:${v4Str}|(:${v6Seg}){1,3}|:)|` +
    `(?:${v6Seg}:){3}(?:(:${v6Seg}){0,2}:${v4Str}|(:${v6Seg}){1,4}|:)|` +
    `(?:${v6Seg}:){2}(?:(:${v6Seg}){0,3}:${v4Str}|(:${v6Seg}){1,5}|:)|` +
    `(?:${v6Seg}:){1}(?:(:${v6Seg}){0,4}:${v4Str}|(:${v6Seg}){1,6}|:)|` +
    `(?::((?::${v6Seg}){0,5}:${v4Str}|(?::${v6Seg}){1,7}|:))` +
    ')(%[0-9a-zA-Z-.:]{1,})?$'
)

const isIPv4 = (exports.isIPv4 = function isIPv4(host) {
  return IPv4Pattern.test(host)
})

const isIPv6 = (exports.isIPv6 = function isIPv6(host) {
  return IPv6Pattern.test(host)
})

exports.isIP = function isIP(host) {
  if (isIPv4(host)) return 4
  if (isIPv6(host)) return 6
  return 0
}
{
  "name": "bare-tcp",
  "version": "2.5.1",
  "description": "Native TCP sockets for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./constants": "./lib/constants.js",
    "./errors": "./lib/errors.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-tcp.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-tcp/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-tcp#readme",
  "engines": {
    "bare": ">=1.16.0"
  },
  "dependencies": {
    "bare-dns": "^2.0.4",
    "bare-events": "^2.5.4",
    "bare-stream": "^2.6.4"
  },
  "devDependencies": {
    "bare-pipe": "^4.1.5",
    "brittle": "^3.5.0",
    "cmake-bare": "^1.1.6",
    "lunte": "^1.6.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "bare-pipe": "*"
  },
  "peerDependenciesMeta": {
    "bare-pipe": {
      "optional": true
    }
  }
}
module.exports = require.addon()
const { Duplex, Writable } = require('bare-stream')
const binding = require('./binding')
const constants = require('./lib/constants')
const errors = require('./lib/errors')

const defaultReadBufferSize = 65536

const context = binding.context()

exports.Socket = class TLSSocket extends Duplex {
  constructor(socket, opts = {}) {
    const {
      isServer = false,
      cert = null,
      key = null,
      host = null,
      rejectUnauthorized = true,
      ca = null,
      alpnProtocols = null,
      eagerOpen = true,
      allowHalfOpen = true,
      readBufferSize = defaultReadBufferSize
    } = opts

    if (!isServer && rejectUnauthorized && !host) {
      throw new TypeError("'host' is required for client sockets when 'rejectUnauthorized' is true")
    }

    super({ eagerOpen })

    this._state = 0

    this._socket = socket
    this._allowHalfOpen = allowHalfOpen

    this._pendingOpen = null
    this._pendingWrite = null
    this._pendingDestroy = null

    this._reading = Buffer.alloc(readBufferSize)
    this._buffer = []
    this._buffered = 0

    this._ondata = this._ondata.bind(this)
    this._ondrain = this._ondrain.bind(this)
    this._onend = this._onend.bind(this)
    this._onclose = this._onclose.bind(this)
    this._onerror = this._onerror.bind(this)

    socket.on('close', this._onclose).on('error', this._onerror)

    let alpn = null

    if (alpnProtocols && alpnProtocols.length > 0) {
      const parts = []

      for (const protocol of alpnProtocols) {
        const encoded = Buffer.from(protocol)

        if (encoded.byteLength === 0 || encoded.byteLength > 255) {
          throw new RangeError('ALPN protocol name must be 1-255 bytes')
        }

        parts.push(Buffer.of(encoded.byteLength), encoded)
      }

      alpn = Buffer.concat(parts)
    }

    try {
      this._handle = binding.init(
        context,
        isServer,
        cert,
        key,
        host,
        rejectUnauthorized,
        ca,
        alpn,
        this,
        this._onread,
        this._onwrite
      )
    } catch (err) {
      this._handle = null

      this.destroy(err)
    }
  }

  get socket() {
    return this._socket
  }

  get encrypted() {
    return true
  }

  get alpnProtocol() {
    return this._handle ? binding.alpnProtocol(this._handle) : null
  }

  _onconnect() {
    this._state |= constants.state.CONNECTED

    this.emit('connect')

    const cb = this._pendingOpen
    this._pendingOpen = null
    cb(null)
  }

  _ondata(data) {
    this._buffer.push(data)
    this._buffered += data.byteLength

    while (this._buffered > 0) {
      if (this._state & constants.state.CONNECTED) {
        let read
        try {
          read = binding.read(this._handle, this._reading)
        } catch (err) {
          return this.destroy(errors.from(err))
        }

        if (read < 0) break

        if (read === 0) {
          this.push(null)
          if (this._allowHalfOpen === false) this.end()
          return
        }

        const copy = Buffer.allocUnsafe(read)
        copy.set(this._reading.subarray(0, read))

        this.push(copy)
      } else {
        try {
          if (binding.handshake(this._handle)) this._onconnect()
          else break
        } catch (err) {
          err = errors.from(err)

          // Defer so any alert the handshake wrote to the underlying socket
          // gets a chance to flush before we tear it down.
          queueMicrotask(() => {
            if (this._pendingOpen) {
              const cb = this._pendingOpen
              this._pendingOpen = null
              cb(err)
            } else {
              this.destroy(err)
            }
          })
          return
        }
      }
    }
  }

  _ondrain() {
    if (this._pendingWrite === null) return
    const cb = this._pendingWrite
    this._pendingWrite = null
    cb(null)
  }

  _onend() {
    this.push(null)
  }

  _onclose() {
    this._socket.off('close', this._onclose).off('error', this._onerror)

    if (this._pendingDestroy) {
      const cb = this._pendingDestroy
      this._pendingDestroy = null
      cb()
    }
  }

  _onerror(err) {
    if (this._pendingOpen) {
      const cb = this._pendingOpen
      this._pendingOpen = null
      cb(err)
    } else if (this._pendingDestroy) {
      const cb = this._pendingDestroy
      this._pendingDestroy = null
      cb(err)
    } else {
      this.destroy(err)
    }
  }

  _onread(data) {
    if (this._buffered < data.byteLength) return 0

    let offset = 0
    let remaining = data.byteLength

    while (remaining > 0) {
      const chunk = this._buffer[0]

      if (chunk.byteLength <= remaining) {
        data.set(chunk, offset)

        offset += chunk.byteLength
        remaining -= chunk.byteLength

        this._buffer.shift()
      } else {
        data.set(chunk.subarray(0, remaining), offset)

        this._buffer[0] = chunk.subarray(remaining)

        remaining = 0
      }
    }

    this._buffered -= data.byteLength

    return data.byteLength
  }

  _onwrite(data) {
    this._socket.write(Buffer.from(data.slice()))

    return data.byteLength
  }

  _attach() {
    if (this._state & constants.state.ATTACHED) return
    this._state |= constants.state.ATTACHED

    this._socket.on('data', this._ondata).on('drain', this._ondrain).on('end', this._onend)
  }

  _detach() {
    if (!(this._state & constants.state.ATTACHED)) return
    this._state &= ~constants.state.ATTACHED

    this._socket.off('data', this._ondata).off('drain', this._ondrain).off('end', this._onend)
  }

  _open(cb) {
    this._pendingOpen = cb
    this._attach()

    try {
      if (binding.handshake(this._handle)) this._onconnect()
    } catch (err) {
      this._pendingOpen = null

      cb(errors.from(err))
    }
  }

  _write(data, encoding, cb) {
    try {
      binding.write(this._handle, data)

      if (Writable.isBackpressured(this._socket)) {
        this._pendingWrite = cb
      } else {
        cb(null)
      }
    } catch (err) {
      this._pendingWrite = null

      cb(errors.from(err))
    }
  }

  _final(cb) {
    try {
      binding.shutdown(this._handle)

      cb(null)
    } catch (err) {
      cb(err)
    }

    this._socket.end()
  }

  _predestroy() {
    if (this._handle) {
      this._detach()

      binding.destroy(this._handle)
      this._handle = null
    }

    this._socket.destroy()
  }

  _destroy(err, cb) {
    if (this._handle) {
      this._detach()

      binding.destroy(this._handle)
      this._handle = null
    }

    if (err) this._socket.destroy()

    if (this._socket.destroyed) cb(err)
    else this._pendingDestroy = cb
  }
}

exports.TLSSocket = exports.Socket // For Node.js compatibility

exports.constants = constants
exports.errors = errors

const net = require('./net')

exports.createConnection = net.createConnection
exports.createServer = net.createServer

// For Node.js compatibility
exports.connect = exports.createConnection
module.exports = {
  state: {
    CONNECTED: 0x1,
    ATTACHED: 0x2
  }
}
module.exports = class TLSError extends Error {
  constructor(msg, code, fn = TLSError) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'TLSError'
  }

  static from(err) {
    return new TLSError(err.message, err.code, TLSError.from)
  }
}
const EventEmitter = require('bare-events')
const net = require('bare-net')
const tls = require('bare-tls')

class TLSNetSocket extends tls.Socket {
  ref() {
    this.socket.ref()
  }

  unref() {
    this.socket.unref()
  }
}

class TLSNetServer extends EventEmitter {
  constructor(opts = {}, onconnection) {
    if (typeof opts === 'function') {
      onconnection = opts
      opts = {}
    }

    const {
      cert = null,
      key = null,
      host = null,
      rejectUnauthorized = true,
      ca = null,
      alpnProtocols = null,
      eagerOpen = true,
      allowHalfOpen = true
    } = opts

    super()

    this._opts = {
      cert,
      key,
      host,
      rejectUnauthorized,
      ca,
      alpnProtocols,
      eagerOpen,
      allowHalfOpen
    }

    this._server = net.createServer(opts)
    this._server
      .on('listening', this._onlistening.bind(this))
      .on('connection', this._onconnection.bind(this))
      .on('error', this._onerror.bind(this))
      .on('close', this._onclose.bind(this))

    if (onconnection) this.on('connection', onconnection)
  }

  get listening() {
    return this._server.listening
  }

  address() {
    return this._server.address()
  }

  listen(...args) {
    this._server.listen(...args)
    return this
  }

  close(onclose) {
    if (onclose) this.once('close', onclose)
    this._server.close()
  }

  ref() {
    this._server.ref()
  }

  unref() {
    this._server.unref()
  }

  _onlistening() {
    this.emit('listening')
  }

  _onconnection(socket) {
    this.emit('connection', new TLSNetSocket(socket, { ...this._opts, isServer: true }))
  }

  _onerror(err) {
    this.emit('error', err)
  }

  _onclose() {
    this.emit('close')
  }
}

exports.createConnection = function createConnection(...args) {
  let opts = {}
  let onconnect

  if (typeof args[0] === 'string') {
    // createConnection(path[, onconnect])
    opts.path = args[0]
    onconnect = args[1]
  } else if (typeof args[0] === 'number') {
    // createConnection(port[, host][, onconnect])
    opts.port = args[0]

    if (typeof args[1] === 'function') {
      onconnect = args[1]
    } else {
      opts.host = args[1]
      onconnect = args[2]
    }
  } else {
    // createConnection(opts[, onconnect])
    opts = args[0] || {}
    onconnect = args[1]
  }

  if (!opts.host && !opts.path) opts.host = 'localhost'

  return new TLSNetSocket(net.createConnection(opts, onconnect), opts)
}

exports.createServer = function createServer(opts, onconnection) {
  return new TLSNetServer(opts, onconnection)
}
{
  "name": "bare-tls",
  "version": "3.1.7",
  "description": "Transport Layer Security (TLS) streams for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    },
    "./errors": {
      "types": "./lib/errors.d.ts",
      "default": "./lib/errors.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "net.js",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-tls.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-tls/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-tls#readme",
  "engines": {
    "bare": ">=1.7.0"
  },
  "dependencies": {
    "bare-net": "^2.0.1",
    "bare-stream": "^2.6.4"
  },
  "devDependencies": {
    "bare-events": "^2.6.0",
    "bare-fs": "^4.0.2",
    "brittle": "^3.1.1",
    "cmake-bare": "^1.1.6",
    "cmake-fetch": "^1.0.0",
    "lunte": "^1.6.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = require.addon()
const { Readable, Writable } = require('bare-stream')
const Signal = require('bare-signals')
const binding = require('./binding')
const constants = require('./lib/constants')

const defaultReadBufferSize = 65536
const empty = Buffer.alloc(0)

exports.ReadStream = class TTYReadStream extends Readable {
  constructor(fd, opts = {}) {
    super()

    const { readBufferSize = defaultReadBufferSize, allowHalfOpen = true } = opts

    this._fd = fd
    this._state = 0
    this._allowHalfOpen = allowHalfOpen
    this._buffer = Buffer.alloc(readBufferSize)

    this._pendingDestroy = null

    this._handle = binding.init(fd, this._buffer, this, noop, this._onread, this._onclose)
  }

  get fd() {
    return this._fd
  }

  get isTTY() {
    return true
  }

  setMode(mode) {
    binding.setMode(this._handle, mode)
    return this
  }

  setRawMode(enabled) {
    return this.setMode(enabled ? constants.mode.RAW : constants.mode.NORMAL)
  }

  _read() {
    if ((this._state & constants.state.READING) === 0) {
      this._state |= constants.state.READING

      binding.resume(this._handle)
    }
  }

  _predestroy() {
    if (this._state & constants.state.CLOSING) return
    this._state |= constants.state.CLOSING

    binding.close(this._handle)
  }

  _destroy(err, cb) {
    if (this._state & constants.state.CLOSING) return cb(err)
    this._state |= constants.state.CLOSING

    this._pendingDestroy = cb

    binding.close(this._handle)
  }

  _continueDestroy() {
    if (this._pendingDestroy === null) return
    const cb = this._pendingDestroy
    this._pendingDestroy = null
    cb(null)
  }

  _onread(err, read) {
    if (err) {
      this.destroy(err)
      return
    }

    if (read === 0) {
      this.push(null)
      if (this._allowHalfOpen === false) this.end()
      return
    }

    const copy = Buffer.allocUnsafe(read)
    copy.set(this._buffer.subarray(0, read))

    if (this.push(copy) === false && this.destroying === false) {
      this._state &= ~constants.state.READING

      binding.pause(this._handle)
    }
  }

  _onclose() {
    this._handle = null

    this._continueDestroy()
  }
}

exports.WriteStream = class TTYWriteStream extends Writable {
  constructor(fd, opts = {}) {
    super()

    this._fd = fd
    this._state = 0
    this._size = null

    this._pendingWrite = null
    this._pendingWriteBatch = null
    this._pendingDestroy = null

    this._handle = binding.init(fd, empty, this, this._onwrite, noop, this._onclose)

    this._size = this.getWindowSize()

    if (TTYWriteStream._streams.size === 0) TTYWriteStream._resize.start()

    TTYWriteStream._streams.add(this)
  }

  get fd() {
    return this._fd
  }

  get isTTY() {
    return true
  }

  get columns() {
    return this._size[0]
  }

  get rows() {
    return this._size[1]
  }

  getWindowSize() {
    return binding.getWindowSize(this._handle)
  }

  _writev(batch, cb) {
    this._pendingWrite = cb
    this._pendingWriteBatch = batch

    try {
      binding.writev(
        this._handle,
        batch.map(({ chunk }) => chunk)
      )
    } catch (err) {
      this._continueWrite(err)
    }
  }

  _predestroy() {
    if (this._state & constants.state.CLOSING) return
    this._state |= constants.state.CLOSING

    binding.close(this._handle)

    TTYWriteStream._streams.delete(this)

    if (TTYWriteStream._streams.size === 0) TTYWriteStream._resize.stop()
  }

  _destroy(err, cb) {
    if (this._state & constants.state.CLOSING) return cb(err)
    this._state |= constants.state.CLOSING

    this._pendingDestroy = cb

    binding.close(this._handle)

    TTYWriteStream._streams.delete(this)

    if (TTYWriteStream._streams.size === 0) TTYWriteStream._resize.stop()
  }

  _continueWrite(err) {
    if (this._pendingWrite === null) return
    const cb = this._pendingWrite
    this._pendingWrite = null
    this._pendingWriteBatch = null
    cb(err)
  }

  _continueDestroy() {
    if (this._pendingDestroy === null) return
    const cb = this._pendingDestroy
    this._pendingDestroy = null
    cb(null)
  }

  _onwrite(err) {
    this._continueWrite(err)
  }

  _onclose() {
    this._handle = null

    this._continueDestroy()
  }

  _onresize() {
    this._size = this.getWindowSize()

    this.emit('resize')
  }

  static _streams = new Set()

  static _resize = new Signal('SIGWINCH')
}

exports.constants = constants

exports.isTTY = binding.isTTY

exports.isatty = exports.isTTY // For Node.js compatibility

exports.WriteStream._resize
  .on('signal', () => {
    for (const stream of exports.WriteStream._streams) {
      stream._onresize()
    }
  })
  .unref()

function noop() {}
const binding = require('../binding')

module.exports = exports = {
  mode: {
    NORMAL: binding.MODE_NORMAL,
    RAW: binding.MODE_RAW,
    IO: binding.MODE_IO || 0
  },

  state: {
    READING: 0x1,
    CLOSING: 0x2
  }
}

/** @deprecated Use `mode.NORMAL` */
exports.MODE_NORMAL = exports.mode.NORMAL
/** @deprecated Use `mode.RAW` */
exports.MODE_RAW = exports.mode.RAW
/** @deprecated Use `mode.IO` */
exports.MODE_IO = exports.mode.IO
{
  "name": "bare-tty",
  "version": "5.1.1",
  "description": "Native TTY streams for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./constants": "./lib/constants.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-tty.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-tty/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-tty#readme",
  "engines": {
    "bare": ">=1.16.0"
  },
  "dependencies": {
    "bare-events": "^2.2.0",
    "bare-signals": "^4.0.0",
    "bare-stream": "^2.0.0"
  },
  "devDependencies": {
    "brittle": "^3.2.1",
    "cmake-bare": "^1.1.6",
    "lunte": "^1.8.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = require.addon()
const binding = require('./binding')

const t = binding.constants

class Type {
  constructor(type) {
    this._type = type
  }

  isUndefined() {
    return this._type === t.UNDEFINED
  }

  isNull() {
    return this._type === t.NULL
  }

  isBoolean() {
    return this._type === t.BOOLEAN
  }

  isNumber() {
    return (this._type & 0xff) === t.NUMBER
  }

  isInt32() {
    return (this._type & (0xff | t.INT32)) === (t.NUMBER | t.INT32)
  }

  isUint32() {
    return (this._type & (0xff | t.UINT32)) === (t.NUMBER | t.UINT32)
  }

  isString() {
    return this._type === t.STRING
  }

  isSymbol() {
    return this._type === t.SYMBOL
  }

  isObject() {
    return (this._type & 0xff) === t.OBJECT
  }

  isArray() {
    return this._type === (t.OBJECT | t.ARRAY)
  }

  isArguments() {
    return this._type === (t.OBJECT | t.ARGUMENTS)
  }

  isDate() {
    return this._type === (t.OBJECT | t.DATE)
  }

  isRegExp() {
    return this._type === (t.OBJECT | t.REGEXP)
  }

  isError() {
    return this._type === (t.OBJECT | t.ERROR)
  }

  isPromise() {
    return this._type === (t.OBJECT | t.PROMISE)
  }

  isProxy() {
    return this._type === (t.OBJECT | t.PROXY)
  }

  isGenerator() {
    return this._type === (t.OBJECT | t.GENERATOR)
  }

  isMap() {
    return this._type === (t.OBJECT | t.MAP)
  }

  isSet() {
    return this._type === (t.OBJECT | t.SET)
  }

  isWeakMap() {
    return this._type === (t.OBJECT | t.WEAK_MAP)
  }

  isWeakSet() {
    return this._type === (t.OBJECT | t.WEAK_SET)
  }

  isWeakRef() {
    return this._type === (t.OBJECT | t.WEAK_REF)
  }

  isArrayBuffer() {
    return this._type === (t.OBJECT | t.ARRAYBUFFER)
  }

  isSharedArrayBuffer() {
    return this._type === (t.OBJECT | t.SHAREDARRAYBUFFER)
  }

  isTypedArray() {
    return (this._type & 0xffff) === (t.OBJECT | t.TYPEDARRAY)
  }

  isInt8Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT8ARRAY)
  }

  isUint8Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT8ARRAY)
  }

  isUint8ClampedArray() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT8CLAMPEDARRAY)
  }

  isInt16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT16ARRAY)
  }

  isUint16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT16ARRAY)
  }

  isInt32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT32ARRAY)
  }

  isUint32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT32ARRAY)
  }

  isFloat16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT16ARRAY)
  }

  isFloat32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT32ARRAY)
  }

  isFloat64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT64ARRAY)
  }

  isBigInt64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.BIGINT64ARRAY)
  }

  isBigUint64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.BIGUINT64ARRAY)
  }

  isDataView() {
    return this._type === (t.OBJECT | t.DATAVIEW)
  }

  isModuleNamespace() {
    return this._type === (t.OBJECT | t.MODULE_NAMESPACE)
  }

  isFunction() {
    return (this._type & 0xff) === t.FUNCTION
  }

  isAsyncFunction() {
    return (
      (this._type & (0xff | t.ASYNC_FUNCTION)) ===
      (t.FUNCTION | t.ASYNC_FUNCTION)
    )
  }

  isGeneratorFunction() {
    return (
      (this._type & (0xff | t.GENERATOR_FUNCTION)) ===
      (t.FUNCTION | t.GENERATOR_FUNCTION)
    )
  }

  isExternal() {
    return this._type === t.EXTERNAL
  }

  isBigInt() {
    return this._type === t.BIGINT
  }
}

module.exports = exports = function type(value) {
  switch (typeof value) {
    case 'undefined':
      return new Type(t.UNDEFINED)
    case 'boolean':
      return new Type(t.BOOLEAN)
    case 'number':
      return new Type(
        Number.isSafeInteger(value) ? binding.type(value) : t.NUMBER
      )
    case 'string':
      return new Type(t.STRING)
    case 'symbol':
      return new Type(t.SYMBOL)
    case 'object':
      return new Type(value === null ? t.NULL : binding.type(value))
    case 'function':
      return new Type(binding.type(value))
    case 'bigint':
      return new Type(t.BIGINT)
  }
}

exports.createTag = function createTag(...components) {
  const tag = new Uint32Array(4)
  for (let i = 0; i < 4; i++) tag[i] = components[i] || 0
  return tag
}

exports.addTag = function addTag(object, tag) {
  binding.addTag(object, tag)
}

exports.checkTag = function checkTag(object, tag) {
  return binding.checkTag(object, tag)
}
{
  "name": "bare-type",
  "version": "1.1.0",
  "description": "Cross-realm type predicates for Bare",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-type.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-type/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-type#readme",
  "engines": {
    "bare": ">=1.2.0"
  },
  "devDependencies": {
    "brittle": "^3.4.0",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
module.exports = require.addon()
const path = require('bare-path')
const binding = require('./binding')
const errors = require('./lib/errors')
const URLSearchParams = require('./lib/url-search-params')

const kind = Symbol.for('bare.url.kind')

const isWindows = Bare.platform === 'win32'

class URL {
  static get [kind]() {
    return 0 // Compatibility version
  }

  constructor(input, base, opts = {}) {
    if (arguments.length === 0) throw errors.INVALID_URL()

    input = String(input)

    if (base !== undefined) base = String(base)

    this._components = new Uint32Array(8)

    this._parse(input, base, opts.throw !== false)

    if (this._href) this._params = new URLSearchParams(this.search, this)
  }

  get [kind]() {
    return URL[kind]
  }

  // https://url.spec.whatwg.org/#dom-url-href

  get href() {
    return this._href
  }

  set href(value) {
    this._update(value)

    this._params._parse(this.search)
  }

  // https://url.spec.whatwg.org/#dom-url-protocol

  get protocol() {
    return this._slice(0, this._components[0]) + ':'
  }

  set protocol(value) {
    this._update(this._replace(value.replace(/:+$/, ''), 0, this._components[0]))
  }

  // https://url.spec.whatwg.org/#dom-url-username

  get username() {
    return this._slice(this._components[0] + 3 /* :// */, this._components[1])
  }

  set username(value) {
    if (cannotHaveCredentialsOrPort(this)) {
      return
    }

    if (this.username === '') value += '@'

    this._update(this._replace(value, this._components[0] + 3 /* :// */, this._components[1]))
  }

  // https://url.spec.whatwg.org/#dom-url-password

  get password() {
    return this._href.slice(this._components[1] + 1 /* : */, this._components[2] - 1 /* @ */)
  }

  set password(value) {
    if (cannotHaveCredentialsOrPort(this)) {
      return
    }

    let start = this._components[1] + 1 /* : */
    let end = this._components[2] - 1 /* @ */

    if (this.password === '') {
      value = ':' + value
      start--
    }

    if (this.username === '') {
      value += '@'
      end++
    }

    this._update(this._replace(value, start, end))
  }

  // https://url.spec.whatwg.org/#dom-url-host

  get host() {
    return this._slice(this._components[2], this._components[5])
  }

  set host(value) {
    if (hasOpaquePath(this)) {
      return
    }

    this._update(
      this._replace(value, this._components[2], this._components[value.includes(':') ? 5 : 3])
    )
  }

  // https://url.spec.whatwg.org/#dom-url-hostname

  get hostname() {
    return this._slice(this._components[2], this._components[3])
  }

  set hostname(value) {
    if (hasOpaquePath(this)) {
      return
    }

    this._update(this._replace(value, this._components[2], this._components[3]))
  }

  // https://url.spec.whatwg.org/#dom-url-port

  get port() {
    return this._slice(this._components[3] + 1 /* : */, this._components[5])
  }

  set port(value) {
    if (cannotHaveCredentialsOrPort(this)) {
      return
    }

    let start = this._components[3] + 1 /* : */

    if (this.port === '') {
      value = ':' + value
      start--
    }

    this._update(this._replace(value, start, this._components[5]))
  }

  // https://url.spec.whatwg.org/#dom-url-pathname

  get pathname() {
    return this._slice(this._components[5], this._components[6] - 1 /* ? */)
  }

  set pathname(value) {
    if (hasOpaquePath(this)) {
      return
    }

    if (value[0] !== '/' && value[0] !== '\\') {
      value = '/' + value
    }

    this._update(this._replace(value, this._components[5], this._components[6] - 1 /* ? */))
  }

  // https://url.spec.whatwg.org/#dom-url-search

  get search() {
    return this._slice(this._components[6] - 1 /* ? */, this._components[7] - 1 /* # */)
  }

  set search(value) {
    if (value && value[0] !== '?') value = '?' + value

    this._update(
      this._replace(value, this._components[6] - 1 /* ? */, this._components[7] - 1 /* # */)
    )

    this._params._parse(this.search)
  }

  // https://url.spec.whatwg.org/#dom-url-searchparams

  get searchParams() {
    return this._params
  }

  // https://url.spec.whatwg.org/#dom-url-hash

  get hash() {
    return this._slice(this._components[7] - 1 /* # */)
  }

  set hash(value) {
    if (value && value[0] !== '#') value = '#' + value

    this._update(this._replace(value, this._components[7] - 1 /* # */))
  }

  toString() {
    return this._href
  }

  toJSON() {
    return this._href
  }

  [Symbol.for('bare.inspect')]() {
    return {
      __proto__: { constructor: URL },

      href: this.href,
      protocol: this.protocol,
      username: this.username,
      password: this.password,
      host: this.host,
      hostname: this.hostname,
      port: this.port,
      pathname: this.pathname,
      search: this.search,
      searchParams: this.searchParams,
      hash: this.hash
    }
  }

  _slice(start, end = this._href.length) {
    return this._href.slice(start, end)
  }

  _replace(replacement, start, end = this._href.length) {
    return this._slice(0, start) + replacement + this._slice(end)
  }

  _parse(input, base, shouldThrow) {
    try {
      this._href = binding.parse(
        String(input),
        base ? String(base) : null,
        this._components,
        shouldThrow
      )
    } catch (err) {
      if (err instanceof TypeError) throw err

      throw errors.INVALID_URL(`Invalid URL '${input}'`, input)
    }
  }

  _update(input) {
    try {
      this._parse(input, null, true)
    } catch (err) {
      if (err instanceof TypeError) throw err
    }
  }
}

module.exports = exports = URL

// https://url.spec.whatwg.org/#url-opaque-path
function hasOpaquePath(url) {
  return url.pathname[0] !== '/'
}

// https://url.spec.whatwg.org/#cannot-have-a-username-password-port
function cannotHaveCredentialsOrPort(url) {
  return url.hostname === '' || url.protocol === 'file:'
}

exports.URL = URL
exports.URLSearchParams = URLSearchParams

exports.errors = errors

exports.isURL = function isURL(value) {
  if (value instanceof URL) return true

  return typeof value === 'object' && value !== null && value[kind] === URL[kind]
}

exports.isURLSearchParams = URLSearchParams.isURLSearchParams

// https://url.spec.whatwg.org/#dom-url-parse
exports.parse = function parse(input, base) {
  const url = new URL(input, base, { throw: false })
  return url._href ? url : null
}

// https://url.spec.whatwg.org/#dom-url-canparse
exports.canParse = function canParse(input, base) {
  return binding.canParse(String(input), base ? String(base) : null)
}

exports.fileURLToPath = function fileURLToPath(url) {
  if (typeof url === 'string') {
    url = new URL(url)
  }

  if (url.protocol !== 'file:') {
    throw errors.INVALID_URL_SCHEME('The URL must use the file: protocol')
  }

  if (isWindows) {
    if (/%2f|%5c/i.test(url.pathname)) {
      throw errors.INVALID_FILE_URL_PATH(
        'The file: URL path must not include encoded \\ or / characters'
      )
    }
  } else {
    if (url.hostname) {
      throw errors.INVALID_FILE_URL_HOST("The file: URL host must be 'localhost' or empty")
    }

    if (/%2f/i.test(url.pathname)) {
      throw errors.INVALID_FILE_URL_PATH('The file: URL path must not include encoded / characters')
    }
  }

  if (/%00/i.test(url.pathname)) {
    throw errors.INVALID_FILE_URL_PATH('The file: URL path must not include encoded NUL characters')
  }

  const pathname = path.normalize(decodeURIComponent(url.pathname))

  if (isWindows) {
    if (url.hostname) return '\\\\' + url.hostname + pathname

    const letter = pathname.charCodeAt(1) | 0x20

    if (letter < 0x61 /* a */ || letter > 0x7a /* z */ || pathname.charCodeAt(2) !== 0x3a /* : */) {
      throw errors.INVALID_FILE_URL_PATH('The file: URL path must be absolute')
    }

    return pathname.slice(1)
  }

  return pathname
}

exports.pathToFileURL = function pathToFileURL(pathname) {
  let resolved = path.resolve(pathname)

  if (pathname[pathname.length - 1] === '/') {
    resolved += '/'
  } else if (isWindows && pathname[pathname.length - 1] === '\\') {
    resolved += '\\'
  }

  resolved = resolved
    .replaceAll('%', '%25') // Must be first
    .replaceAll('#', '%23')
    .replaceAll('?', '%3f')
    .replaceAll('\n', '%0a')
    .replaceAll('\r', '%0d')
    .replaceAll('\t', '%09')

  if (!isWindows) {
    resolved = resolved.replaceAll('\\', '%5c')
  }

  return new URL('file:' + resolved)
}

exports.format = function format(parts) {
  const { protocol, auth, host, hostname, port, pathname, search, query, hash, slashes } = parts

  let result = ''

  if (typeof protocol === 'string') {
    result += protocol

    if (protocol[protocol.length - 1] !== ':') {
      result += ':'
    }

    if (slashes === true || /https?|ftp|gopher|file/.test(protocol)) {
      result += '//'
    }
  }

  if (typeof auth === 'string') {
    if (host || hostname) result += auth + '@'
  }

  if (typeof host === 'string') result += host
  else {
    result += hostname

    if (port) result += ':' + port
  }

  if (typeof pathname === 'string' && pathname !== '') {
    if (pathname[0] !== '/') result += '/'
    result += pathname
  }

  if (typeof search === 'string') {
    if (search[0] !== '?') result += '?'
    result += search
  } else if (typeof query === 'object' && query !== null) {
    result += '?' + new URLSearchParams(query)
  }

  if (typeof hash === 'string') {
    if (hash[0] !== '#') result += '#'
    result += hash
  }

  return result
}
module.exports = class URLError extends Error {
  constructor(msg, fn = URLError, code = fn.name) {
    super(`${code}: ${msg}`)

    this.code = code

    if (Error.captureStackTrace) Error.captureStackTrace(this, fn)
  }

  get name() {
    return 'URLError'
  }

  static INVALID_URL(msg, input) {
    const err = new URLError(msg, URLError.INVALID_URL)

    err.input = input

    return err
  }

  static INVALID_URL_SCHEME(msg = 'Invalid URL') {
    return new URLError(msg, URLError.INVALID_URL_SCHEME)
  }

  static INVALID_FILE_URL_HOST(msg = 'Invalid file: URL host') {
    return new URLError(msg, URLError.INVALID_FILE_URL_HOST)
  }

  static INVALID_FILE_URL_PATH(msg = 'Invalid file: URL path') {
    return new URLError(msg, URLError.INVALID_FILE_URL_PATH)
  }
}
const kind = Symbol.for('bare.url.search-params.kind')

class URLSearchParams {
  static _urls = new WeakMap()

  static get [kind]() {
    return 0 // Compatibility version
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-urlsearchparams
  constructor(init, url = null) {
    this._params = new Map()

    if (url) URLSearchParams._urls.set(this, url)

    if (typeof init === 'string') {
      this._parse(init)
    } else if (init) {
      for (const [name, value] of typeof init[Symbol.iterator] === 'function'
        ? init
        : Object.entries(init)) {
        this.append(name, value)
      }
    }
  }

  get [kind]() {
    return URLSearchParams[kind]
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-size
  get size() {
    return this._params.length
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-append
  append(name, value = null) {
    if (value === null) return

    let list = this._params.get(name)

    if (list === undefined) {
      list = []
      this._params.set(name, list)
    }

    list.push(value)

    this._update()
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-delete
  delete(name, value = null) {
    if (value === null) this._params.delete(name)
    else {
      let list = this._params.get(name)

      if (list === undefined) return

      list = list.filter((found) => found !== value)

      if (list.length === 0) this._params.delete(name)
      else this._params.set(name, list)
    }

    this._update()
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-get
  get(name) {
    const list = this._params.get(name)

    if (list === undefined) return null

    return list[0]
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-getall
  getAll(name) {
    const list = this._params.get(name)

    if (list === undefined) return []

    return Array.from(list)
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-has
  has(name, value = null) {
    const list = this._params.get(name)

    if (list === undefined) return false

    if (value === null) return true

    return list.includes(value)
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-set
  set(name, value = null) {
    if (value === null) this._params.delete(name)
    else this._params.set(name, [value])

    this._update()
  }

  toString() {
    return this._serialize()
  }

  toJSON() {
    return [...this]
  }

  *[Symbol.iterator]() {
    for (const [name, values] of this._params) {
      for (const value of values) yield [name, value]
    }
  }

  [Symbol.for('bare.inspect')]() {
    const object = {
      __proto__: { constructor: URLSearchParams }
    }

    for (const [name, values] of this._params) {
      if (values.length === 1) object[name] = values[0]
      else object[name] = values
    }

    return object
  }

  // https://url.spec.whatwg.org/#concept-urlsearchparams-update
  _update() {
    const url = URLSearchParams._urls.get(this)

    if (url === undefined) return

    url.search = this._serialize()
  }

  // https://url.spec.whatwg.org/#concept-urlencoded-parser
  _parse(input) {
    if (input[0] === '?') input = input.substring(1)

    this._params = new Map()

    for (let sequence of input.split('&')) {
      if (sequence.length === 0) continue

      sequence = sequence.replace(/\+/g, ' ')

      let i = sequence.indexOf('=')
      if (i === -1) i = sequence.length

      const name = decodeURIComponent(sequence.substring(0, i))
      const value = decodeURIComponent(sequence.substring(i + 1, sequence.length))

      let list = this._params.get(name)

      if (list === undefined) {
        list = []
        this._params.set(name, list)
      }

      list.push(value)
    }
  }

  // https://url.spec.whatwg.org/#concept-urlencoded-serializer
  _serialize() {
    let output = ''

    for (let [name, values] of this._params) {
      name = encodeURIComponent(name)

      for (const value of values) {
        if (output) output += '&'

        output += name + '=' + encodeURIComponent(value)
      }
    }

    return output
  }
}

module.exports = exports = URLSearchParams

exports.isURLSearchParams = function isURLSearchParams(value) {
  if (value instanceof URLSearchParams) return true

  return typeof value === 'object' && value !== null && value[kind] === URLSearchParams[kind]
}
{
  "name": "bare-url",
  "version": "2.4.5",
  "description": "WHATWG URL implementation for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "global.js",
    "global.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-url.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-url/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-url",
  "dependencies": {
    "bare-path": "^3.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "cmake-bare": "^1.1.6",
    "cmake-fetch": "^1.0.0",
    "lunte": "^1.6.0",
    "prettier": "^3.3.3",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = require.addon()
const { Transform, Writable } = require('bare-stream')
const binding = require('./binding')
const constants = require('./lib/constants')
const errors = require('./lib/errors')

exports.constants = constants
exports.errors = errors

const MAX_OUTPUT_LENGTH = (Buffer.constants && Buffer.constants.MAX_LENGTH) || 0x100000000

class ZlibState {
  constructor(mode, opts = {}) {
    const {
      flush = constants.Z_NO_FLUSH,
      finishFlush = constants.Z_FINISH,
      chunkSize = constants.Z_DEFAULT_CHUNK,
      level = constants.Z_DEFAULT_LEVEL,
      windowBits = constants.Z_DEFAULT_WINDOWBITS,
      memLevel = constants.Z_DEFAULT_MEMLEVEL,
      strategy = constants.Z_DEFAULT_STRATEGY,
      maxOutputLength = MAX_OUTPUT_LENGTH
    } = opts

    this._mode = mode

    this._flushMode = flush
    this._finishFlushMode = finishFlush
    this._allocations = []

    this._maxOutputLength = maxOutputLength
    this._outputLength = 0

    this._buffer = Buffer.allocUnsafe(chunkSize)

    this._handle = binding.init(
      this._mode,
      this._buffer,
      level,
      windowBits,
      memLevel,
      strategy,
      this,
      this._onalloc,
      this._onfree
    )
  }

  _onalloc(size) {
    const buffer = Buffer.allocUnsafe(size)

    const view = new Uint32Array(buffer.buffer, buffer.byteOffset, buffer.byteLength / 4)

    view[0] = this._allocations.push(view) - 1

    return buffer
  }

  _onfree(id) {
    const last = this._allocations.pop()

    if (last[0] !== id) {
      this._allocations[(last[0] = id)] = last
    }
  }

  reset() {
    this._outputLength = 0

    binding.reset(this._handle)
  }

  *transform(data) {
    binding.load(this._handle, data)

    let available
    do {
      try {
        available = binding.transform(this._handle, this._flushMode)
      } catch (err) {
        throw errors[err.code](err.message)
      }

      const read = this._buffer.length - available

      if (read) {
        this._outputLength += read

        if (this._outputLength > this._maxOutputLength) {
          throw errors.LIMIT_EXCEEDED(
            `Output length exceeded maxOutputLength of ${this._maxOutputLength} bytes`
          )
        }

        const copy = Buffer.allocUnsafe(read)
        copy.set(this._buffer.subarray(0, read))

        yield copy
      }
    } while (available === 0)
  }

  *flush() {
    let available
    do {
      try {
        available = binding.transform(this._handle, this._finishFlushMode)
      } catch (err) {
        throw errors[err.code](err.message)
      }

      const read = this._buffer.length - available

      if (read) {
        this._outputLength += read

        if (this._outputLength > this._maxOutputLength) {
          throw errors.LIMIT_EXCEEDED(
            `Output length exceeded maxOutputLength of ${this._maxOutputLength} bytes`
          )
        }

        const copy = Buffer.allocUnsafe(read)
        copy.set(this._buffer.subarray(0, read))

        yield copy
      }
    } while (available === 0)

    try {
      binding.end(this._handle)
    } catch (err) {
      throw errors[err.code](err.message)
    }

    this._handle = null
  }
}

class ZlibStream extends Transform {
  constructor(mode, opts = {}) {
    const { flush, ...streamOpts } = opts

    super(streamOpts)

    this._state = new ZlibState(mode, opts)
  }

  async flush(mode = constants.Z_FULL_FLUSH, cb) {
    if (typeof mode === 'function') {
      cb = mode
      mode = constants.Z_FULL_FLUSH
    }

    const previousMode = this._state._flushMode

    this._state._flushMode = mode

    await Writable.drained(this)

    this._state._flushMode = previousMode

    if (cb) cb(null) // For Node.js compatibility
  }

  reset() {
    if (this._state === null) {
      throw errors.STREAM_CLOSED('Stream has already closed')
    }

    this._state.reset()
  }

  _transform(data, encoding, cb) {
    let err = null

    try {
      for (const chunk of this._state.transform(data)) {
        this.push(chunk)
      }
    } catch (e) {
      err = e
    }

    cb(err)
  }

  _flush(cb) {
    let err = null

    try {
      for (const chunk of this._state.flush()) {
        this.push(chunk)
      }
    } catch (e) {
      err = e
    }

    this._state = null

    cb(err)
  }
}

function readAsBuffer(stream, buffer, cb) {
  const chunks = []

  stream.on('data', ondata).on('end', onend).on('error', onerror).end(buffer)

  function ondata(chunk) {
    chunks.push(chunk)
  }

  function onend() {
    cb(null, chunks.length === 1 ? chunks[0] : Buffer.concat(chunks))
  }

  function onerror(err) {
    stream.off('end', onend)
    cb(err)
  }
}

function transformToBuffer(mode, buffer, opts) {
  if (typeof buffer === 'string') buffer = Buffer.from(buffer)

  const state = new ZlibState(mode, opts)
  const chunks = []

  for (const chunk of state.transform(buffer)) {
    chunks.push(chunk)
  }

  for (const chunk of state.flush()) {
    chunks.push(chunk)
  }

  return chunks.length === 1 ? chunks[0] : Buffer.concat(chunks)
}

exports.Deflate = class ZlibDeflateStream extends ZlibStream {
  constructor(opts) {
    super(binding.DEFLATE, opts)
  }
}

exports.createDeflate = function createDeflate(opts) {
  return new exports.Deflate(opts)
}

exports.deflate = function deflate(buffer, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  readAsBuffer(new exports.Deflate(opts), buffer, cb)
}

exports.deflateSync = function deflateSync(buffer, opts) {
  return transformToBuffer(binding.DEFLATE, buffer, opts)
}

exports.Inflate = class ZlibInflateStream extends ZlibStream {
  constructor(opts) {
    super(binding.INFLATE, opts)
  }
}

exports.createInflate = function createInflate(opts) {
  return new exports.Inflate(opts)
}

exports.inflate = function inflate(buffer, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  readAsBuffer(new exports.Inflate(opts), buffer, cb)
}

exports.inflateSync = function inflateSync(buffer, opts) {
  return transformToBuffer(binding.INFLATE, buffer, opts)
}

exports.DeflateRaw = class ZlibDeflateRawStream extends ZlibStream {
  constructor(opts) {
    super(binding.DEFLATE_RAW, opts)
  }
}

exports.createDeflateRaw = function createDeflateRaw(opts) {
  return new exports.DeflateRaw(opts)
}

exports.deflateRaw = function deflateRaw(buffer, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  readAsBuffer(new exports.DeflateRaw(opts), buffer, cb)
}

exports.deflateRawSync = function deflateRawSync(buffer, opts) {
  return transformToBuffer(binding.DEFLATE_RAW, buffer, opts)
}

exports.InflateRaw = class ZlibInflateRawStream extends ZlibStream {
  constructor(opts) {
    super(binding.INFLATE_RAW, opts)
  }
}

exports.createInflateRaw = function createInflateRaw(opts) {
  return new exports.InflateRaw(opts)
}

exports.inflateRaw = function inflateRaw(buffer, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  readAsBuffer(new exports.InflateRaw(opts), buffer, cb)
}

exports.inflateRawSync = function inflateRawSync(buffer, opts) {
  return transformToBuffer(binding.INFLATE_RAW, buffer, opts)
}

exports.Gzip = class ZlibGzipStream extends ZlibStream {
  constructor(opts) {
    super(binding.GZIP, opts)
  }
}

exports.createGzip = function createGzip(opts) {
  return new exports.Gzip(opts)
}

exports.gzip = function gzip(buffer, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  readAsBuffer(new exports.Gzip(opts), buffer, cb)
}

exports.gzipSync = function gzipSync(buffer, opts) {
  return transformToBuffer(binding.GZIP, buffer, opts)
}

exports.Gunzip = class ZlibGunzipStream extends ZlibStream {
  constructor(opts) {
    super(binding.GUNZIP, opts)
  }
}

exports.createGunzip = function createGunzip(opts) {
  return new exports.Gunzip(opts)
}

exports.gunzip = function gunzip(buffer, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  readAsBuffer(new exports.Gunzip(opts), buffer, cb)
}

exports.gunzipSync = function gunzipSync(buffer, opts) {
  return transformToBuffer(binding.GUNZIP, buffer, opts)
}
const binding = require('../binding')

module.exports = binding.constants
module.exports = class ZlibError extends Error {
  constructor(msg, code, fn = ZlibError) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'ZlibError'
  }

  static STREAM_CLOSED(msg) {
    return new ZlibError(msg, 'STREAM_CLOSED', ZlibError.STREAM_CLOSED)
  }

  static STREAM_ERROR(msg) {
    return new ZlibError(msg, 'STREAM_ERROR', ZlibError.STREAM_ERROR)
  }

  static DATA_ERROR(msg) {
    return new ZlibError(msg, 'DATA_ERROR', ZlibError.DATA_ERROR)
  }

  static MEM_ERROR(msg) {
    return new ZlibError(msg, 'MEM_ERROR', ZlibError.MEM_ERROR)
  }

  static BUF_ERROR(msg) {
    return new ZlibError(msg, 'BUF_ERROR', ZlibError.BUF_ERROR)
  }

  static VERSION_ERROR(msg) {
    return new ZlibError(msg, 'VERSION_ERROR', ZlibError.VERSION_ERROR)
  }

  static UNKNOWN_ERROR(msg) {
    return new ZlibError(msg, 'UNKNOWN_ERROR', ZlibError.UNKNOWN_ERROR)
  }

  static LIMIT_EXCEEDED(msg) {
    return new ZlibError(msg, 'LIMIT_EXCEEDED', ZlibError.LIMIT_EXCEEDED)
  }
}
{
  "name": "bare-zlib",
  "version": "1.4.0",
  "description": "Stream-based zlib bindings for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    },
    "./errors": {
      "types": "./lib/errors.d.ts",
      "default": "./lib/errors.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-zlib.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-zlib/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-zlib",
  "dependencies": {
    "bare-stream": "^2.0.0"
  },
  "devDependencies": {
    "bare-fs": "^3.0.0",
    "brittle": "^3.5.0",
    "cmake-bare": "^1.1.7",
    "cmake-fetch": "^1.0.0",
    "lunte": "^1.6.0",
    "prettier": "^3.5.3",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "bare-buffer": "*"
  },
  "peerDependenciesMeta": {
    "bare-buffer": {
      "optional": true
    }
  }
}
const sodium = require('sodium-universal')
const b4a = require('b4a')
const assert = require('nanoassert')
const { detectLanguage, loadWordlist } = require('./wordlist')

module.exports = {
  generateEntropy,
  generateMnemonic,
  normalizeMnemonic,
  validateMnemonic,
  mnemonicToEntropy,
  mnemonicToSeed,
  entropyToMnemonic
}

function generateMnemonic ({ entropy = generateEntropy(), language = 'english' } = {}) {
  const wordlist = loadWordlist(language)
  const extended = computeCheckSum(entropy)

  const words = []

  for (const index of uint11Reader(extended)) {
    words.push(wordlist[index])
  }

  const delimiter = language === 'japanese' ? '\u3000' : ' '

  return words.join(delimiter).trim()
}

function entropyToMnemonic (entropy, { language = 'english' } = {}) {
  return generateMnemonic({ entropy, language })
}

function mnemonicToEntropy (mnemonic) {
  const words = mnemonic.replace(/\u3000/g, ' ').trim().split(' ')
  const language = detectLanguage(words)

  if (!language) {
    throw new Error('Language not recognised')
  }

  if (words.length % 3 !== 0) {
    throw new Error('Invalid length')
  }

  const wordlist = loadWordlist(language)

  const indexes = []
  for (const word of words) {
    const index = wordlist.indexOf(word)
    if (index === -1) {
      throw new Error('Bad word')
    }

    indexes.push(index)
  }

  const bits = words.length * 11
  const len = (bits * 32 / 33) >> 3

  const extended = b4a.alloc(Math.ceil(bits / 8))
  const entropy = extended.subarray(0, len)

  uint11Writer(extended, indexes)

  if (!b4a.equals(extended, computeCheckSum(entropy))) {
    throw new Error('Invalid checksum')
  }

  return entropy
}

function normalizeMnemonic (mnemonic) {
  return mnemonic.trim().replace(/\u3000/, ' ').split(/\s+/).map(c => c.toLowerCase()).join(' ')
}

async function mnemonicToSeed (mnemonic, passphrase = '') {
  mnemonic = normalizeMnemonic(mnemonic)

  if (!validateMnemonic(mnemonic)) {
    throw new Error('Invalid mnemonic')
  }

  const input = b4a.from(mnemonic)
  const salt = b4a.from('mnemonic' + passphrase)

  const output = b4a.alloc(64)

  await sodium.extension_pbkdf2_sha512_async(
    output,
    input,
    salt,
    2048,
    64
  )

  return output
}

function validateMnemonic (mnemonic) {
  try {
    mnemonicToEntropy(mnemonic)
  } catch (e) {
    return false
  }
  return true
}

function sha256 (data, output = b4a.alloc(32)) {
  sodium.crypto_hash_sha256(output, data)
  return output
}

function computeCheckSum (seed) {
  assert((seed.byteLength & 4) === 0, 'seed must be a multiple of 4 bytes')

  const len = seed.byteLength
  const cklen = len >> 2 // cksum bits
  const total = len + Math.ceil(cklen / 8)

  const output = b4a.alloc(len + 32)
  output.set(seed)

  const entropy = output.subarray(0, len)
  const cksum = output.subarray(len)

  sha256(entropy, cksum)

  // only append cklen bits
  output[total - 1] &= (0xff ^ (0xff >> cklen))

  return output.subarray(0, total)
}

function generateEntropy (length = 32) {
  const seed = b4a.alloc(length)
  sodium.randombytes_buf(seed)

  return seed
}

function * uint11Reader (state) {
  yield * uintReader(state, 11)
}

function uint11Writer (buf, uints) {
  return uintWriter(buf, uints, 11)
}

function * uintReader (buffer, width) {
  const MASK = (2 << (width - 1)) - 1

  let pos = 0
  let value = 0

  while (true) {
    const offset = pos >> 3 // byte offset

    if (offset >= buffer.byteLength) {
      return value & MASK
    }

    const height = width - (pos % width)
    const leftover = (offset + 1) * 8 - pos

    value += shift(buffer[offset], height - leftover)

    pos += Math.min(height, leftover)
    if (pos % width) continue

    yield value & MASK

    value = 0
  }
}

function uintWriter (buffer, uints, width) {
  let pos = 0

  while (true) {
    const offset = pos >> 3 // byte offset

    const i = Math.floor(pos / width)
    if (i >= uints.length) break

    if (offset >= buffer.length) {
      throw new Error('Failed to encode uints')
    }

    const rem = 8 - pos % 8
    const height = (i + 1) * width - pos

    const value = shift(uints[i], rem - height)

    buffer[offset] += mask(value, rem)

    pos += Math.min(rem, height)
  }

  return buffer
}

// when n is positive, shift left n bits
// when n is negative, shift right -n bits
function shift (val, n) {
  if (n === 0) return val
  if (n > 0) return val << n

  return val >> (-1 * n)
}

function mask (val, bits) {
  if (bits < 32) return val & ((1 << bits) - 1)
  return val % (2 ** bits)
}
{
  "name": "bip39-mnemonic",
  "version": "2.5.0",
  "description": "BIP39 mnemonic for key derivation schemes",
  "main": "index.js",
  "scripts": {
    "generate-wordlist": "node scripts/generate-wordlist.js",
    "test": "standard && brittle test/*.js"
  },
  "author": "Holepunch Inc",
  "license": "Apache-2.0",
  "devDependencies": {
    "brittle": "^3.4.0",
    "standard": "^17.1.0"
  },
  "dependencies": {
    "b4a": "^1.6.6",
    "nanoassert": "^2.0.0",
    "sodium-universal": "^5.0.1"
  },
  "files": [
    "index.js",
    "wordlist"
  ],
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bip39.git"
  },
  "bugs": {
    "url": "https://github.com/holepunchto/bip39/issues"
  },
  "homepage": "https://github.com/holepunchto/bip39#readme"
}
["的","一","是","在","不","了","有","和","人","这","中","大","为","上","个","国","我","以","要","他","时","来","用","们","生","到","作","地","于","出","就","分","对","成","会","可","主","发","年","动","同","工","也","能","下","过","子","说","产","种","面","而","方","后","多","定","行","学","法","所","民","得","经","十","三","之","进","着","等","部","度","家","电","力","里","如","水","化","高","自","二","理","起","小","物","现","实","加","量","都","两","体","制","机","当","使","点","从","业","本","去","把","性","好","应","开","它","合","还","因","由","其","些","然","前","外","天","政","四","日","那","社","义","事","平","形","相","全","表","间","样","与","关","各","重","新","线","内","数","正","心","反","你","明","看","原","又","么","利","比","或","但","质","气","第","向","道","命","此","变","条","只","没","结","解","问","意","建","月","公","无","系","军","很","情","者","最","立","代","想","已","通","并","提","直","题","党","程","展","五","果","料","象","员","革","位","入","常","文","总","次","品","式","活","设","及","管","特","件","长","求","老","头","基","资","边","流","路","级","少","图","山","统","接","知","较","将","组","见","计","别","她","手","角","期","根","论","运","农","指","几","九","区","强","放","决","西","被","干","做","必","战","先","回","则","任","取","据","处","队","南","给","色","光","门","即","保","治","北","造","百","规","热","领","七","海","口","东","导","器","压","志","世","金","增","争","济","阶","油","思","术","极","交","受","联","什","认","六","共","权","收","证","改","清","美","再","采","转","更","单","风","切","打","白","教","速","花","带","安","场","身","车","例","真","务","具","万","每","目","至","达","走","积","示","议","声","报","斗","完","类","八","离","华","名","确","才","科","张","信","马","节","话","米","整","空","元","况","今","集","温","传","土","许","步","群","广","石","记","需","段","研","界","拉","林","律","叫","且","究","观","越","织","装","影","算","低","持","音","众","书","布","复","容","儿","须","际","商","非","验","连","断","深","难","近","矿","千","周","委","素","技","备","半","办","青","省","列","习","响","约","支","般","史","感","劳","便","团","往","酸","历","市","克","何","除","消","构","府","称","太","准","精","值","号","率","族","维","划","选","标","写","存","候","毛","亲","快","效","斯","院","查","江","型","眼","王","按","格","养","易","置","派","层","片","始","却","专","状","育","厂","京","识","适","属","圆","包","火","住","调","满","县","局","照","参","红","细","引","听","该","铁","价","严","首","底","液","官","德","随","病","苏","失","尔","死","讲","配","女","黄","推","显","谈","罪","神","艺","呢","席","含","企","望","密","批","营","项","防","举","球","英","氧","势","告","李","台","落","木","帮","轮","破","亚","师","围","注","远","字","材","排","供","河","态","封","另","施","减","树","溶","怎","止","案","言","士","均","武","固","叶","鱼","波","视","仅","费","紧","爱","左","章","早","朝","害","续","轻","服","试","食","充","兵","源","判","护","司","足","某","练","差","致","板","田","降","黑","犯","负","击","范","继","兴","似","余","坚","曲","输","修","故","城","夫","够","送","笔","船","占","右","财","吃","富","春","职","觉","汉","画","功","巴","跟","虽","杂","飞","检","吸","助","升","阳","互","初","创","抗","考","投","坏","策","古","径","换","未","跑","留","钢","曾","端","责","站","简","述","钱","副","尽","帝","射","草","冲","承","独","令","限","阿","宣","环","双","请","超","微","让","控","州","良","轴","找","否","纪","益","依","优","顶","础","载","倒","房","突","坐","粉","敌","略","客","袁","冷","胜","绝","析","块","剂","测","丝","协","诉","念","陈","仍","罗","盐","友","洋","错","苦","夜","刑","移","频","逐","靠","混","母","短","皮","终","聚","汽","村","云","哪","既","距","卫","停","烈","央","察","烧","迅","境","若","印","洲","刻","括","激","孔","搞","甚","室","待","核","校","散","侵","吧","甲","游","久","菜","味","旧","模","湖","货","损","预","阻","毫","普","稳","乙","妈","植","息","扩","银","语","挥","酒","守","拿","序","纸","医","缺","雨","吗","针","刘","啊","急","唱","误","训","愿","审","附","获","茶","鲜","粮","斤","孩","脱","硫","肥","善","龙","演","父","渐","血","欢","械","掌","歌","沙","刚","攻","谓","盾","讨","晚","粒","乱","燃","矛","乎","杀","药","宁","鲁","贵","钟","煤","读","班","伯","香","介","迫","句","丰","培","握","兰","担","弦","蛋","沉","假","穿","执","答","乐","谁","顺","烟","缩","征","脸","喜","松","脚","困","异","免","背","星","福","买","染","井","概","慢","怕","磁","倍","祖","皇","促","静","补","评","翻","肉","践","尼","衣","宽","扬","棉","希","伤","操","垂","秋","宜","氢","套","督","振","架","亮","末","宪","庆","编","牛","触","映","雷","销","诗","座","居","抓","裂","胞","呼","娘","景","威","绿","晶","厚","盟","衡","鸡","孙","延","危","胶","屋","乡","临","陆","顾","掉","呀","灯","岁","措","束","耐","剧","玉","赵","跳","哥","季","课","凯","胡","额","款","绍","卷","齐","伟","蒸","殖","永","宗","苗","川","炉","岩","弱","零","杨","奏","沿","露","杆","探","滑","镇","饭","浓","航","怀","赶","库","夺","伊","灵","税","途","灭","赛","归","召","鼓","播","盘","裁","险","康","唯","录","菌","纯","借","糖","盖","横","符","私","努","堂","域","枪","润","幅","哈","竟","熟","虫","泽","脑","壤","碳","欧","遍","侧","寨","敢","彻","虑","斜","薄","庭","纳","弹","饲","伸","折","麦","湿","暗","荷","瓦","塞","床","筑","恶","户","访","塔","奇","透","梁","刀","旋","迹","卡","氯","遇","份","毒","泥","退","洗","摆","灰","彩","卖","耗","夏","择","忙","铜","献","硬","予","繁","圈","雪","函","亦","抽","篇","阵","阴","丁","尺","追","堆","雄","迎","泛","爸","楼","避","谋","吨","野","猪","旗","累","偏","典","馆","索","秦","脂","潮","爷","豆","忽","托","惊","塑","遗","愈","朱","替","纤","粗","倾","尚","痛","楚","谢","奋","购","磨","君","池","旁","碎","骨","监","捕","弟","暴","割","贯","殊","释","词","亡","壁","顿","宝","午","尘","闻","揭","炮","残","冬","桥","妇","警","综","招","吴","付","浮","遭","徐","您","摇","谷","赞","箱","隔","订","男","吹","园","纷","唐","败","宋","玻","巨","耕","坦","荣","闭","湾","键","凡","驻","锅","救","恩","剥","凝","碱","齿","截","炼","麻","纺","禁","废","盛","版","缓","净","睛","昌","婚","涉","筒","嘴","插","岸","朗","庄","街","藏","姑","贸","腐","奴","啦","惯","乘","伙","恢","匀","纱","扎","辩","耳","彪","臣","亿","璃","抵","脉","秀","萨","俄","网","舞","店","喷","纵","寸","汗","挂","洪","贺","闪","柬","爆","烯","津","稻","墙","软","勇","像","滚","厘","蒙","芳","肯","坡","柱","荡","腿","仪","旅","尾","轧","冰","贡","登","黎","削","钻","勒","逃","障","氨","郭","峰","币","港","伏","轨","亩","毕","擦","莫","刺","浪","秘","援","株","健","售","股","岛","甘","泡","睡","童","铸","汤","阀","休","汇","舍","牧","绕","炸","哲","磷","绩","朋","淡","尖","启","陷","柴","呈","徒","颜","泪","稍","忘","泵","蓝","拖","洞","授","镜","辛","壮","锋","贫","虚","弯","摩","泰","幼","廷","尊","窗","纲","弄","隶","疑","氏","宫","姐","震","瑞","怪","尤","琴","循","描","膜","违","夹","腰","缘","珠","穷","森","枝","竹","沟","催","绳","忆","邦","剩","幸","浆","栏","拥","牙","贮","礼","滤","钠","纹","罢","拍","咱","喊","袖","埃","勤","罚","焦","潜","伍","墨","欲","缝","姓","刊","饱","仿","奖","铝","鬼","丽","跨","默","挖","链","扫","喝","袋","炭","污","幕","诸","弧","励","梅","奶","洁","灾","舟","鉴","苯","讼","抱","毁","懂","寒","智","埔","寄","届","跃","渡","挑","丹","艰","贝","碰","拔","爹","戴","码","梦","芽","熔","赤","渔","哭","敬","颗","奔","铅","仲","虎","稀","妹","乏","珍","申","桌","遵","允","隆","螺","仓","魏","锐","晓","氮","兼","隐","碍","赫","拨","忠","肃","缸","牵","抢","博","巧","壳","兄","杜","讯","诚","碧","祥","柯","页","巡","矩","悲","灌","龄","伦","票","寻","桂","铺","圣","恐","恰","郑","趣","抬","荒","腾","贴","柔","滴","猛","阔","辆","妻","填","撤","储","签","闹","扰","紫","砂","递","戏","吊","陶","伐","喂","疗","瓶","婆","抚","臂","摸","忍","虾","蜡","邻","胸","巩","挤","偶","弃","槽","劲","乳","邓","吉","仁","烂","砖","租","乌","舰","伴","瓜","浅","丙","暂","燥","橡","柳","迷","暖","牌","秧","胆","详","簧","踏","瓷","谱","呆","宾","糊","洛","辉","愤","竞","隙","怒","粘","乃","绪","肩","籍","敏","涂","熙","皆","侦","悬","掘","享","纠","醒","狂","锁","淀","恨","牲","霸","爬","赏","逆","玩","陵","祝","秒","浙","貌","役","彼","悉","鸭","趋","凤","晨","畜","辈","秩","卵","署","梯","炎","滩","棋","驱","筛","峡","冒","啥","寿","译","浸","泉","帽","迟","硅","疆","贷","漏","稿","冠","嫩","胁","芯","牢","叛","蚀","奥","鸣","岭","羊","凭","串","塘","绘","酵","融","盆","锡","庙","筹","冻","辅","摄","袭","筋","拒","僚","旱","钾","鸟","漆","沈","眉","疏","添","棒","穗","硝","韩","逼","扭","侨","凉","挺","碗","栽","炒","杯","患","馏","劝","豪","辽","勃","鸿","旦","吏","拜","狗","埋","辊","掩","饮","搬","骂","辞","勾","扣","估","蒋","绒","雾","丈","朵","姆","拟","宇","辑","陕","雕","偿","蓄","崇","剪","倡","厅","咬","驶","薯","刷","斥","番","赋","奉","佛","浇","漫","曼","扇","钙","桃","扶","仔","返","俗","亏","腔","鞋","棱","覆","框","悄","叔","撞","骗","勘","旺","沸","孤","吐","孟","渠","屈","疾","妙","惜","仰","狠","胀","谐","抛","霉","桑","岗","嘛","衰","盗","渗","脏","赖","涌","甜","曹","阅","肌","哩","厉","烃","纬","毅","昨","伪","症","煮","叹","钉","搭","茎","笼","酷","偷","弓","锥","恒","杰","坑","鼻","翼","纶","叙","狱","逮","罐","络","棚","抑","膨","蔬","寺","骤","穆","冶","枯","册","尸","凸","绅","坯","牺","焰","轰","欣","晋","瘦","御","锭","锦","丧","旬","锻","垄","搜","扑","邀","亭","酯","迈","舒","脆","酶","闲","忧","酚","顽","羽","涨","卸","仗","陪","辟","惩","杭","姚","肚","捉","飘","漂","昆","欺","吾","郎","烷","汁","呵","饰","萧","雅","邮","迁","燕","撒","姻","赴","宴","烦","债","帐","斑","铃","旨","醇","董","饼","雏","姿","拌","傅","腹","妥","揉","贤","拆","歪","葡","胺","丢","浩","徽","昂","垫","挡","览","贪","慰","缴","汪","慌","冯","诺","姜","谊","凶","劣","诬","耀","昏","躺","盈","骑","乔","溪","丛","卢","抹","闷","咨","刮","驾","缆","悟","摘","铒","掷","颇","幻","柄","惠","惨","佳","仇","腊","窝","涤","剑","瞧","堡","泼","葱","罩","霍","捞","胎","苍","滨","俩","捅","湘","砍","霞","邵","萄","疯","淮","遂","熊","粪","烘","宿","档","戈","驳","嫂","裕","徙","箭","捐","肠","撑","晒","辨","殿","莲","摊","搅","酱","屏","疫","哀","蔡","堵","沫","皱","畅","叠","阁","莱","敲","辖","钩","痕","坝","巷","饿","祸","丘","玄","溜","曰","逻","彭","尝","卿","妨","艇","吞","韦","怨","矮","歇"]["的","一","是","在","不","了","有","和","人","這","中","大","為","上","個","國","我","以","要","他","時","來","用","們","生","到","作","地","於","出","就","分","對","成","會","可","主","發","年","動","同","工","也","能","下","過","子","說","產","種","面","而","方","後","多","定","行","學","法","所","民","得","經","十","三","之","進","著","等","部","度","家","電","力","裡","如","水","化","高","自","二","理","起","小","物","現","實","加","量","都","兩","體","制","機","當","使","點","從","業","本","去","把","性","好","應","開","它","合","還","因","由","其","些","然","前","外","天","政","四","日","那","社","義","事","平","形","相","全","表","間","樣","與","關","各","重","新","線","內","數","正","心","反","你","明","看","原","又","麼","利","比","或","但","質","氣","第","向","道","命","此","變","條","只","沒","結","解","問","意","建","月","公","無","系","軍","很","情","者","最","立","代","想","已","通","並","提","直","題","黨","程","展","五","果","料","象","員","革","位","入","常","文","總","次","品","式","活","設","及","管","特","件","長","求","老","頭","基","資","邊","流","路","級","少","圖","山","統","接","知","較","將","組","見","計","別","她","手","角","期","根","論","運","農","指","幾","九","區","強","放","決","西","被","幹","做","必","戰","先","回","則","任","取","據","處","隊","南","給","色","光","門","即","保","治","北","造","百","規","熱","領","七","海","口","東","導","器","壓","志","世","金","增","爭","濟","階","油","思","術","極","交","受","聯","什","認","六","共","權","收","證","改","清","美","再","採","轉","更","單","風","切","打","白","教","速","花","帶","安","場","身","車","例","真","務","具","萬","每","目","至","達","走","積","示","議","聲","報","鬥","完","類","八","離","華","名","確","才","科","張","信","馬","節","話","米","整","空","元","況","今","集","溫","傳","土","許","步","群","廣","石","記","需","段","研","界","拉","林","律","叫","且","究","觀","越","織","裝","影","算","低","持","音","眾","書","布","复","容","兒","須","際","商","非","驗","連","斷","深","難","近","礦","千","週","委","素","技","備","半","辦","青","省","列","習","響","約","支","般","史","感","勞","便","團","往","酸","歷","市","克","何","除","消","構","府","稱","太","準","精","值","號","率","族","維","劃","選","標","寫","存","候","毛","親","快","效","斯","院","查","江","型","眼","王","按","格","養","易","置","派","層","片","始","卻","專","狀","育","廠","京","識","適","屬","圓","包","火","住","調","滿","縣","局","照","參","紅","細","引","聽","該","鐵","價","嚴","首","底","液","官","德","隨","病","蘇","失","爾","死","講","配","女","黃","推","顯","談","罪","神","藝","呢","席","含","企","望","密","批","營","項","防","舉","球","英","氧","勢","告","李","台","落","木","幫","輪","破","亞","師","圍","注","遠","字","材","排","供","河","態","封","另","施","減","樹","溶","怎","止","案","言","士","均","武","固","葉","魚","波","視","僅","費","緊","愛","左","章","早","朝","害","續","輕","服","試","食","充","兵","源","判","護","司","足","某","練","差","致","板","田","降","黑","犯","負","擊","范","繼","興","似","餘","堅","曲","輸","修","故","城","夫","夠","送","筆","船","佔","右","財","吃","富","春","職","覺","漢","畫","功","巴","跟","雖","雜","飛","檢","吸","助","昇","陽","互","初","創","抗","考","投","壞","策","古","徑","換","未","跑","留","鋼","曾","端","責","站","簡","述","錢","副","盡","帝","射","草","衝","承","獨","令","限","阿","宣","環","雙","請","超","微","讓","控","州","良","軸","找","否","紀","益","依","優","頂","礎","載","倒","房","突","坐","粉","敵","略","客","袁","冷","勝","絕","析","塊","劑","測","絲","協","訴","念","陳","仍","羅","鹽","友","洋","錯","苦","夜","刑","移","頻","逐","靠","混","母","短","皮","終","聚","汽","村","雲","哪","既","距","衛","停","烈","央","察","燒","迅","境","若","印","洲","刻","括","激","孔","搞","甚","室","待","核","校","散","侵","吧","甲","遊","久","菜","味","舊","模","湖","貨","損","預","阻","毫","普","穩","乙","媽","植","息","擴","銀","語","揮","酒","守","拿","序","紙","醫","缺","雨","嗎","針","劉","啊","急","唱","誤","訓","願","審","附","獲","茶","鮮","糧","斤","孩","脫","硫","肥","善","龍","演","父","漸","血","歡","械","掌","歌","沙","剛","攻","謂","盾","討","晚","粒","亂","燃","矛","乎","殺","藥","寧","魯","貴","鐘","煤","讀","班","伯","香","介","迫","句","豐","培","握","蘭","擔","弦","蛋","沉","假","穿","執","答","樂","誰","順","煙","縮","徵","臉","喜","松","腳","困","異","免","背","星","福","買","染","井","概","慢","怕","磁","倍","祖","皇","促","靜","補","評","翻","肉","踐","尼","衣","寬","揚","棉","希","傷","操","垂","秋","宜","氫","套","督","振","架","亮","末","憲","慶","編","牛","觸","映","雷","銷","詩","座","居","抓","裂","胞","呼","娘","景","威","綠","晶","厚","盟","衡","雞","孫","延","危","膠","屋","鄉","臨","陸","顧","掉","呀","燈","歲","措","束","耐","劇","玉","趙","跳","哥","季","課","凱","胡","額","款","紹","卷","齊","偉","蒸","殖","永","宗","苗","川","爐","岩","弱","零","楊","奏","沿","露","桿","探","滑","鎮","飯","濃","航","懷","趕","庫","奪","伊","靈","稅","途","滅","賽","歸","召","鼓","播","盤","裁","險","康","唯","錄","菌","純","借","糖","蓋","橫","符","私","努","堂","域","槍","潤","幅","哈","竟","熟","蟲","澤","腦","壤","碳","歐","遍","側","寨","敢","徹","慮","斜","薄","庭","納","彈","飼","伸","折","麥","濕","暗","荷","瓦","塞","床","築","惡","戶","訪","塔","奇","透","梁","刀","旋","跡","卡","氯","遇","份","毒","泥","退","洗","擺","灰","彩","賣","耗","夏","擇","忙","銅","獻","硬","予","繁","圈","雪","函","亦","抽","篇","陣","陰","丁","尺","追","堆","雄","迎","泛","爸","樓","避","謀","噸","野","豬","旗","累","偏","典","館","索","秦","脂","潮","爺","豆","忽","托","驚","塑","遺","愈","朱","替","纖","粗","傾","尚","痛","楚","謝","奮","購","磨","君","池","旁","碎","骨","監","捕","弟","暴","割","貫","殊","釋","詞","亡","壁","頓","寶","午","塵","聞","揭","炮","殘","冬","橋","婦","警","綜","招","吳","付","浮","遭","徐","您","搖","谷","贊","箱","隔","訂","男","吹","園","紛","唐","敗","宋","玻","巨","耕","坦","榮","閉","灣","鍵","凡","駐","鍋","救","恩","剝","凝","鹼","齒","截","煉","麻","紡","禁","廢","盛","版","緩","淨","睛","昌","婚","涉","筒","嘴","插","岸","朗","莊","街","藏","姑","貿","腐","奴","啦","慣","乘","夥","恢","勻","紗","扎","辯","耳","彪","臣","億","璃","抵","脈","秀","薩","俄","網","舞","店","噴","縱","寸","汗","掛","洪","賀","閃","柬","爆","烯","津","稻","牆","軟","勇","像","滾","厘","蒙","芳","肯","坡","柱","盪","腿","儀","旅","尾","軋","冰","貢","登","黎","削","鑽","勒","逃","障","氨","郭","峰","幣","港","伏","軌","畝","畢","擦","莫","刺","浪","秘","援","株","健","售","股","島","甘","泡","睡","童","鑄","湯","閥","休","匯","舍","牧","繞","炸","哲","磷","績","朋","淡","尖","啟","陷","柴","呈","徒","顏","淚","稍","忘","泵","藍","拖","洞","授","鏡","辛","壯","鋒","貧","虛","彎","摩","泰","幼","廷","尊","窗","綱","弄","隸","疑","氏","宮","姐","震","瑞","怪","尤","琴","循","描","膜","違","夾","腰","緣","珠","窮","森","枝","竹","溝","催","繩","憶","邦","剩","幸","漿","欄","擁","牙","貯","禮","濾","鈉","紋","罷","拍","咱","喊","袖","埃","勤","罰","焦","潛","伍","墨","欲","縫","姓","刊","飽","仿","獎","鋁","鬼","麗","跨","默","挖","鏈","掃","喝","袋","炭","污","幕","諸","弧","勵","梅","奶","潔","災","舟","鑑","苯","訟","抱","毀","懂","寒","智","埔","寄","屆","躍","渡","挑","丹","艱","貝","碰","拔","爹","戴","碼","夢","芽","熔","赤","漁","哭","敬","顆","奔","鉛","仲","虎","稀","妹","乏","珍","申","桌","遵","允","隆","螺","倉","魏","銳","曉","氮","兼","隱","礙","赫","撥","忠","肅","缸","牽","搶","博","巧","殼","兄","杜","訊","誠","碧","祥","柯","頁","巡","矩","悲","灌","齡","倫","票","尋","桂","鋪","聖","恐","恰","鄭","趣","抬","荒","騰","貼","柔","滴","猛","闊","輛","妻","填","撤","儲","簽","鬧","擾","紫","砂","遞","戲","吊","陶","伐","餵","療","瓶","婆","撫","臂","摸","忍","蝦","蠟","鄰","胸","鞏","擠","偶","棄","槽","勁","乳","鄧","吉","仁","爛","磚","租","烏","艦","伴","瓜","淺","丙","暫","燥","橡","柳","迷","暖","牌","秧","膽","詳","簧","踏","瓷","譜","呆","賓","糊","洛","輝","憤","競","隙","怒","粘","乃","緒","肩","籍","敏","塗","熙","皆","偵","懸","掘","享","糾","醒","狂","鎖","淀","恨","牲","霸","爬","賞","逆","玩","陵","祝","秒","浙","貌","役","彼","悉","鴨","趨","鳳","晨","畜","輩","秩","卵","署","梯","炎","灘","棋","驅","篩","峽","冒","啥","壽","譯","浸","泉","帽","遲","矽","疆","貸","漏","稿","冠","嫩","脅","芯","牢","叛","蝕","奧","鳴","嶺","羊","憑","串","塘","繪","酵","融","盆","錫","廟","籌","凍","輔","攝","襲","筋","拒","僚","旱","鉀","鳥","漆","沈","眉","疏","添","棒","穗","硝","韓","逼","扭","僑","涼","挺","碗","栽","炒","杯","患","餾","勸","豪","遼","勃","鴻","旦","吏","拜","狗","埋","輥","掩","飲","搬","罵","辭","勾","扣","估","蔣","絨","霧","丈","朵","姆","擬","宇","輯","陝","雕","償","蓄","崇","剪","倡","廳","咬","駛","薯","刷","斥","番","賦","奉","佛","澆","漫","曼","扇","鈣","桃","扶","仔","返","俗","虧","腔","鞋","棱","覆","框","悄","叔","撞","騙","勘","旺","沸","孤","吐","孟","渠","屈","疾","妙","惜","仰","狠","脹","諧","拋","黴","桑","崗","嘛","衰","盜","滲","臟","賴","湧","甜","曹","閱","肌","哩","厲","烴","緯","毅","昨","偽","症","煮","嘆","釘","搭","莖","籠","酷","偷","弓","錐","恆","傑","坑","鼻","翼","綸","敘","獄","逮","罐","絡","棚","抑","膨","蔬","寺","驟","穆","冶","枯","冊","屍","凸","紳","坯","犧","焰","轟","欣","晉","瘦","禦","錠","錦","喪","旬","鍛","壟","搜","撲","邀","亭","酯","邁","舒","脆","酶","閒","憂","酚","頑","羽","漲","卸","仗","陪","闢","懲","杭","姚","肚","捉","飄","漂","昆","欺","吾","郎","烷","汁","呵","飾","蕭","雅","郵","遷","燕","撒","姻","赴","宴","煩","債","帳","斑","鈴","旨","醇","董","餅","雛","姿","拌","傅","腹","妥","揉","賢","拆","歪","葡","胺","丟","浩","徽","昂","墊","擋","覽","貪","慰","繳","汪","慌","馮","諾","姜","誼","兇","劣","誣","耀","昏","躺","盈","騎","喬","溪","叢","盧","抹","悶","諮","刮","駕","纜","悟","摘","鉺","擲","頗","幻","柄","惠","慘","佳","仇","臘","窩","滌","劍","瞧","堡","潑","蔥","罩","霍","撈","胎","蒼","濱","倆","捅","湘","砍","霞","邵","萄","瘋","淮","遂","熊","糞","烘","宿","檔","戈","駁","嫂","裕","徙","箭","捐","腸","撐","曬","辨","殿","蓮","攤","攪","醬","屏","疫","哀","蔡","堵","沫","皺","暢","疊","閣","萊","敲","轄","鉤","痕","壩","巷","餓","禍","丘","玄","溜","曰","邏","彭","嘗","卿","妨","艇","吞","韋","怨","矮","歇"]["abdikace","abeceda","adresa","agrese","akce","aktovka","alej","alkohol","amputace","ananas","andulka","anekdota","anketa","antika","anulovat","archa","arogance","asfalt","asistent","aspirace","astma","astronom","atlas","atletika","atol","autobus","azyl","babka","bachor","bacil","baculka","badatel","bageta","bagr","bahno","bakterie","balada","baletka","balkon","balonek","balvan","balza","bambus","bankomat","barbar","baret","barman","baroko","barva","baterka","batoh","bavlna","bazalka","bazilika","bazuka","bedna","beran","beseda","bestie","beton","bezinka","bezmoc","beztak","bicykl","bidlo","biftek","bikiny","bilance","biograf","biolog","bitva","bizon","blahobyt","blatouch","blecha","bledule","blesk","blikat","blizna","blokovat","bloudit","blud","bobek","bobr","bodlina","bodnout","bohatost","bojkot","bojovat","bokorys","bolest","borec","borovice","bota","boubel","bouchat","bouda","boule","bourat","boxer","bradavka","brambora","branka","bratr","brepta","briketa","brko","brloh","bronz","broskev","brunetka","brusinka","brzda","brzy","bublina","bubnovat","buchta","buditel","budka","budova","bufet","bujarost","bukvice","buldok","bulva","bunda","bunkr","burza","butik","buvol","buzola","bydlet","bylina","bytovka","bzukot","capart","carevna","cedr","cedule","cejch","cejn","cela","celer","celkem","celnice","cenina","cennost","cenovka","centrum","cenzor","cestopis","cetka","chalupa","chapadlo","charita","chata","chechtat","chemie","chichot","chirurg","chlad","chleba","chlubit","chmel","chmura","chobot","chochol","chodba","cholera","chomout","chopit","choroba","chov","chrapot","chrlit","chrt","chrup","chtivost","chudina","chutnat","chvat","chvilka","chvost","chyba","chystat","chytit","cibule","cigareta","cihelna","cihla","cinkot","cirkus","cisterna","citace","citrus","cizinec","cizost","clona","cokoliv","couvat","ctitel","ctnost","cudnost","cuketa","cukr","cupot","cvaknout","cval","cvik","cvrkot","cyklista","daleko","dareba","datel","datum","dcera","debata","dechovka","decibel","deficit","deflace","dekl","dekret","demokrat","deprese","derby","deska","detektiv","dikobraz","diktovat","dioda","diplom","disk","displej","divadlo","divoch","dlaha","dlouho","dluhopis","dnes","dobro","dobytek","docent","dochutit","dodnes","dohled","dohoda","dohra","dojem","dojnice","doklad","dokola","doktor","dokument","dolar","doleva","dolina","doma","dominant","domluvit","domov","donutit","dopad","dopis","doplnit","doposud","doprovod","dopustit","dorazit","dorost","dort","dosah","doslov","dostatek","dosud","dosyta","dotaz","dotek","dotknout","doufat","doutnat","dovozce","dozadu","doznat","dozorce","drahota","drak","dramatik","dravec","draze","drdol","drobnost","drogerie","drozd","drsnost","drtit","drzost","duben","duchovno","dudek","duha","duhovka","dusit","dusno","dutost","dvojice","dvorec","dynamit","ekolog","ekonomie","elektron","elipsa","email","emise","emoce","empatie","epizoda","epocha","epopej","epos","esej","esence","eskorta","eskymo","etiketa","euforie","evoluce","exekuce","exkurze","expedice","exploze","export","extrakt","facka","fajfka","fakulta","fanatik","fantazie","farmacie","favorit","fazole","federace","fejeton","fenka","fialka","figurant","filozof","filtr","finance","finta","fixace","fjord","flanel","flirt","flotila","fond","fosfor","fotbal","fotka","foton","frakce","freska","fronta","fukar","funkce","fyzika","galeje","garant","genetika","geolog","gilotina","glazura","glejt","golem","golfista","gotika","graf","gramofon","granule","grep","gril","grog","groteska","guma","hadice","hadr","hala","halenka","hanba","hanopis","harfa","harpuna","havran","hebkost","hejkal","hejno","hejtman","hektar","helma","hematom","herec","herna","heslo","hezky","historik","hladovka","hlasivky","hlava","hledat","hlen","hlodavec","hloh","hloupost","hltat","hlubina","hluchota","hmat","hmota","hmyz","hnis","hnojivo","hnout","hoblina","hoboj","hoch","hodiny","hodlat","hodnota","hodovat","hojnost","hokej","holinka","holka","holub","homole","honitba","honorace","horal","horda","horizont","horko","horlivec","hormon","hornina","horoskop","horstvo","hospoda","hostina","hotovost","houba","houf","houpat","houska","hovor","hradba","hranice","hravost","hrazda","hrbolek","hrdina","hrdlo","hrdost","hrnek","hrobka","hromada","hrot","hrouda","hrozen","hrstka","hrubost","hryzat","hubenost","hubnout","hudba","hukot","humr","husita","hustota","hvozd","hybnost","hydrant","hygiena","hymna","hysterik","idylka","ihned","ikona","iluze","imunita","infekce","inflace","inkaso","inovace","inspekce","internet","invalida","investor","inzerce","ironie","jablko","jachta","jahoda","jakmile","jakost","jalovec","jantar","jarmark","jaro","jasan","jasno","jatka","javor","jazyk","jedinec","jedle","jednatel","jehlan","jekot","jelen","jelito","jemnost","jenom","jepice","jeseter","jevit","jezdec","jezero","jinak","jindy","jinoch","jiskra","jistota","jitrnice","jizva","jmenovat","jogurt","jurta","kabaret","kabel","kabinet","kachna","kadet","kadidlo","kahan","kajak","kajuta","kakao","kaktus","kalamita","kalhoty","kalibr","kalnost","kamera","kamkoliv","kamna","kanibal","kanoe","kantor","kapalina","kapela","kapitola","kapka","kaple","kapota","kapr","kapusta","kapybara","karamel","karotka","karton","kasa","katalog","katedra","kauce","kauza","kavalec","kazajka","kazeta","kazivost","kdekoliv","kdesi","kedluben","kemp","keramika","kino","klacek","kladivo","klam","klapot","klasika","klaun","klec","klenba","klepat","klesnout","klid","klima","klisna","klobouk","klokan","klopa","kloub","klubovna","klusat","kluzkost","kmen","kmitat","kmotr","kniha","knot","koalice","koberec","kobka","kobliha","kobyla","kocour","kohout","kojenec","kokos","koktejl","kolaps","koleda","kolize","kolo","komando","kometa","komik","komnata","komora","kompas","komunita","konat","koncept","kondice","konec","konfese","kongres","konina","konkurs","kontakt","konzerva","kopanec","kopie","kopnout","koprovka","korbel","korektor","kormidlo","koroptev","korpus","koruna","koryto","korzet","kosatec","kostka","kotel","kotleta","kotoul","koukat","koupelna","kousek","kouzlo","kovboj","koza","kozoroh","krabice","krach","krajina","kralovat","krasopis","kravata","kredit","krejcar","kresba","kreveta","kriket","kritik","krize","krkavec","krmelec","krmivo","krocan","krok","kronika","kropit","kroupa","krovka","krtek","kruhadlo","krupice","krutost","krvinka","krychle","krypta","krystal","kryt","kudlanka","kufr","kujnost","kukla","kulajda","kulich","kulka","kulomet","kultura","kuna","kupodivu","kurt","kurzor","kutil","kvalita","kvasinka","kvestor","kynolog","kyselina","kytara","kytice","kytka","kytovec","kyvadlo","labrador","lachtan","ladnost","laik","lakomec","lamela","lampa","lanovka","lasice","laso","lastura","latinka","lavina","lebka","leckdy","leden","lednice","ledovka","ledvina","legenda","legie","legrace","lehce","lehkost","lehnout","lektvar","lenochod","lentilka","lepenka","lepidlo","letadlo","letec","letmo","letokruh","levhart","levitace","levobok","libra","lichotka","lidojed","lidskost","lihovina","lijavec","lilek","limetka","linie","linka","linoleum","listopad","litina","litovat","lobista","lodivod","logika","logoped","lokalita","loket","lomcovat","lopata","lopuch","lord","losos","lotr","loudal","louh","louka","louskat","lovec","lstivost","lucerna","lucifer","lump","lusk","lustrace","lvice","lyra","lyrika","lysina","madam","madlo","magistr","mahagon","majetek","majitel","majorita","makak","makovice","makrela","malba","malina","malovat","malvice","maminka","mandle","manko","marnost","masakr","maskot","masopust","matice","matrika","maturita","mazanec","mazivo","mazlit","mazurka","mdloba","mechanik","meditace","medovina","melasa","meloun","mentolka","metla","metoda","metr","mezera","migrace","mihnout","mihule","mikina","mikrofon","milenec","milimetr","milost","mimika","mincovna","minibar","minomet","minulost","miska","mistr","mixovat","mladost","mlha","mlhovina","mlok","mlsat","mluvit","mnich","mnohem","mobil","mocnost","modelka","modlitba","mohyla","mokro","molekula","momentka","monarcha","monokl","monstrum","montovat","monzun","mosaz","moskyt","most","motivace","motorka","motyka","moucha","moudrost","mozaika","mozek","mozol","mramor","mravenec","mrkev","mrtvola","mrzet","mrzutost","mstitel","mudrc","muflon","mulat","mumie","munice","muset","mutace","muzeum","muzikant","myslivec","mzda","nabourat","nachytat","nadace","nadbytek","nadhoz","nadobro","nadpis","nahlas","nahnat","nahodile","nahradit","naivita","najednou","najisto","najmout","naklonit","nakonec","nakrmit","nalevo","namazat","namluvit","nanometr","naoko","naopak","naostro","napadat","napevno","naplnit","napnout","naposled","naprosto","narodit","naruby","narychlo","nasadit","nasekat","naslepo","nastat","natolik","navenek","navrch","navzdory","nazvat","nebe","nechat","necky","nedaleko","nedbat","neduh","negace","nehet","nehoda","nejen","nejprve","neklid","nelibost","nemilost","nemoc","neochota","neonka","nepokoj","nerost","nerv","nesmysl","nesoulad","netvor","neuron","nevina","nezvykle","nicota","nijak","nikam","nikdy","nikl","nikterak","nitro","nocleh","nohavice","nominace","nora","norek","nositel","nosnost","nouze","noviny","novota","nozdra","nuda","nudle","nuget","nutit","nutnost","nutrie","nymfa","obal","obarvit","obava","obdiv","obec","obehnat","obejmout","obezita","obhajoba","obilnice","objasnit","objekt","obklopit","oblast","oblek","obliba","obloha","obluda","obnos","obohatit","obojek","obout","obrazec","obrna","obruba","obrys","obsah","obsluha","obstarat","obuv","obvaz","obvinit","obvod","obvykle","obyvatel","obzor","ocas","ocel","ocenit","ochladit","ochota","ochrana","ocitnout","odboj","odbyt","odchod","odcizit","odebrat","odeslat","odevzdat","odezva","odhadce","odhodit","odjet","odjinud","odkaz","odkoupit","odliv","odluka","odmlka","odolnost","odpad","odpis","odplout","odpor","odpustit","odpykat","odrazka","odsoudit","odstup","odsun","odtok","odtud","odvaha","odveta","odvolat","odvracet","odznak","ofina","ofsajd","ohlas","ohnisko","ohrada","ohrozit","ohryzek","okap","okenice","oklika","okno","okouzlit","okovy","okrasa","okres","okrsek","okruh","okupant","okurka","okusit","olejnina","olizovat","omak","omeleta","omezit","omladina","omlouvat","omluva","omyl","onehdy","opakovat","opasek","operace","opice","opilost","opisovat","opora","opozice","opravdu","oproti","orbital","orchestr","orgie","orlice","orloj","ortel","osada","oschnout","osika","osivo","oslava","oslepit","oslnit","oslovit","osnova","osoba","osolit","ospalec","osten","ostraha","ostuda","ostych","osvojit","oteplit","otisk","otop","otrhat","otrlost","otrok","otruby","otvor","ovanout","ovar","oves","ovlivnit","ovoce","oxid","ozdoba","pachatel","pacient","padouch","pahorek","pakt","palanda","palec","palivo","paluba","pamflet","pamlsek","panenka","panika","panna","panovat","panstvo","pantofle","paprika","parketa","parodie","parta","paruka","paryba","paseka","pasivita","pastelka","patent","patrona","pavouk","pazneht","pazourek","pecka","pedagog","pejsek","peklo","peloton","penalta","pendrek","penze","periskop","pero","pestrost","petarda","petice","petrolej","pevnina","pexeso","pianista","piha","pijavice","pikle","piknik","pilina","pilnost","pilulka","pinzeta","pipeta","pisatel","pistole","pitevna","pivnice","pivovar","placenta","plakat","plamen","planeta","plastika","platit","plavidlo","plaz","plech","plemeno","plenta","ples","pletivo","plevel","plivat","plnit","plno","plocha","plodina","plomba","plout","pluk","plyn","pobavit","pobyt","pochod","pocit","poctivec","podat","podcenit","podepsat","podhled","podivit","podklad","podmanit","podnik","podoba","podpora","podraz","podstata","podvod","podzim","poezie","pohanka","pohnutka","pohovor","pohroma","pohyb","pointa","pojistka","pojmout","pokazit","pokles","pokoj","pokrok","pokuta","pokyn","poledne","polibek","polknout","poloha","polynom","pomalu","pominout","pomlka","pomoc","pomsta","pomyslet","ponechat","ponorka","ponurost","popadat","popel","popisek","poplach","poprosit","popsat","popud","poradce","porce","porod","porucha","poryv","posadit","posed","posila","poskok","poslanec","posoudit","pospolu","postava","posudek","posyp","potah","potkan","potlesk","potomek","potrava","potupa","potvora","poukaz","pouto","pouzdro","povaha","povidla","povlak","povoz","povrch","povstat","povyk","povzdech","pozdrav","pozemek","poznatek","pozor","pozvat","pracovat","prahory","praktika","prales","praotec","praporek","prase","pravda","princip","prkno","probudit","procento","prodej","profese","prohra","projekt","prolomit","promile","pronikat","propad","prorok","prosba","proton","proutek","provaz","prskavka","prsten","prudkost","prut","prvek","prvohory","psanec","psovod","pstruh","ptactvo","puberta","puch","pudl","pukavec","puklina","pukrle","pult","pumpa","punc","pupen","pusa","pusinka","pustina","putovat","putyka","pyramida","pysk","pytel","racek","rachot","radiace","radnice","radon","raft","ragby","raketa","rakovina","rameno","rampouch","rande","rarach","rarita","rasovna","rastr","ratolest","razance","razidlo","reagovat","reakce","recept","redaktor","referent","reflex","rejnok","reklama","rekord","rekrut","rektor","reputace","revize","revma","revolver","rezerva","riskovat","riziko","robotika","rodokmen","rohovka","rokle","rokoko","romaneto","ropovod","ropucha","rorejs","rosol","rostlina","rotmistr","rotoped","rotunda","roubenka","roucho","roup","roura","rovina","rovnice","rozbor","rozchod","rozdat","rozeznat","rozhodce","rozinka","rozjezd","rozkaz","rozloha","rozmar","rozpad","rozruch","rozsah","roztok","rozum","rozvod","rubrika","ruchadlo","rukavice","rukopis","ryba","rybolov","rychlost","rydlo","rypadlo","rytina","ryzost","sadista","sahat","sako","samec","samizdat","samota","sanitka","sardinka","sasanka","satelit","sazba","sazenice","sbor","schovat","sebranka","secese","sedadlo","sediment","sedlo","sehnat","sejmout","sekera","sekta","sekunda","sekvoje","semeno","seno","servis","sesadit","seshora","seskok","seslat","sestra","sesuv","sesypat","setba","setina","setkat","setnout","setrvat","sever","seznam","shoda","shrnout","sifon","silnice","sirka","sirotek","sirup","situace","skafandr","skalisko","skanzen","skaut","skeptik","skica","skladba","sklenice","sklo","skluz","skoba","skokan","skoro","skripta","skrz","skupina","skvost","skvrna","slabika","sladidlo","slanina","slast","slavnost","sledovat","slepec","sleva","slezina","slib","slina","sliznice","slon","sloupek","slovo","sluch","sluha","slunce","slupka","slza","smaragd","smetana","smilstvo","smlouva","smog","smrad","smrk","smrtka","smutek","smysl","snad","snaha","snob","sobota","socha","sodovka","sokol","sopka","sotva","souboj","soucit","soudce","souhlas","soulad","soumrak","souprava","soused","soutok","souviset","spalovna","spasitel","spis","splav","spodek","spojenec","spolu","sponzor","spornost","spousta","sprcha","spustit","sranda","sraz","srdce","srna","srnec","srovnat","srpen","srst","srub","stanice","starosta","statika","stavba","stehno","stezka","stodola","stolek","stopa","storno","stoupat","strach","stres","strhnout","strom","struna","studna","stupnice","stvol","styk","subjekt","subtropy","suchar","sudost","sukno","sundat","sunout","surikata","surovina","svah","svalstvo","svetr","svatba","svazek","svisle","svitek","svoboda","svodidlo","svorka","svrab","sykavka","sykot","synek","synovec","sypat","sypkost","syrovost","sysel","sytost","tabletka","tabule","tahoun","tajemno","tajfun","tajga","tajit","tajnost","taktika","tamhle","tampon","tancovat","tanec","tanker","tapeta","tavenina","tazatel","technika","tehdy","tekutina","telefon","temnota","tendence","tenista","tenor","teplota","tepna","teprve","terapie","termoska","textil","ticho","tiskopis","titulek","tkadlec","tkanina","tlapka","tleskat","tlukot","tlupa","tmel","toaleta","topinka","topol","torzo","touha","toulec","tradice","traktor","tramp","trasa","traverza","trefit","trest","trezor","trhavina","trhlina","trochu","trojice","troska","trouba","trpce","trpitel","trpkost","trubec","truchlit","truhlice","trus","trvat","tudy","tuhnout","tuhost","tundra","turista","turnaj","tuzemsko","tvaroh","tvorba","tvrdost","tvrz","tygr","tykev","ubohost","uboze","ubrat","ubrousek","ubrus","ubytovna","ucho","uctivost","udivit","uhradit","ujednat","ujistit","ujmout","ukazatel","uklidnit","uklonit","ukotvit","ukrojit","ulice","ulita","ulovit","umyvadlo","unavit","uniforma","uniknout","upadnout","uplatnit","uplynout","upoutat","upravit","uran","urazit","usednout","usilovat","usmrtit","usnadnit","usnout","usoudit","ustlat","ustrnout","utahovat","utkat","utlumit","utonout","utopenec","utrousit","uvalit","uvolnit","uvozovka","uzdravit","uzel","uzenina","uzlina","uznat","vagon","valcha","valoun","vana","vandal","vanilka","varan","varhany","varovat","vcelku","vchod","vdova","vedro","vegetace","vejce","velbloud","veletrh","velitel","velmoc","velryba","venkov","veranda","verze","veselka","veskrze","vesnice","vespodu","vesta","veterina","veverka","vibrace","vichr","videohra","vidina","vidle","vila","vinice","viset","vitalita","vize","vizitka","vjezd","vklad","vkus","vlajka","vlak","vlasec","vlevo","vlhkost","vliv","vlnovka","vloupat","vnucovat","vnuk","voda","vodivost","vodoznak","vodstvo","vojensky","vojna","vojsko","volant","volba","volit","volno","voskovka","vozidlo","vozovna","vpravo","vrabec","vracet","vrah","vrata","vrba","vrcholek","vrhat","vrstva","vrtule","vsadit","vstoupit","vstup","vtip","vybavit","vybrat","vychovat","vydat","vydra","vyfotit","vyhledat","vyhnout","vyhodit","vyhradit","vyhubit","vyjasnit","vyjet","vyjmout","vyklopit","vykonat","vylekat","vymazat","vymezit","vymizet","vymyslet","vynechat","vynikat","vynutit","vypadat","vyplatit","vypravit","vypustit","vyrazit","vyrovnat","vyrvat","vyslovit","vysoko","vystavit","vysunout","vysypat","vytasit","vytesat","vytratit","vyvinout","vyvolat","vyvrhel","vyzdobit","vyznat","vzadu","vzbudit","vzchopit","vzdor","vzduch","vzdychat","vzestup","vzhledem","vzkaz","vzlykat","vznik","vzorek","vzpoura","vztah","vztek","xylofon","zabrat","zabydlet","zachovat","zadarmo","zadusit","zafoukat","zahltit","zahodit","zahrada","zahynout","zajatec","zajet","zajistit","zaklepat","zakoupit","zalepit","zamezit","zamotat","zamyslet","zanechat","zanikat","zaplatit","zapojit","zapsat","zarazit","zastavit","zasunout","zatajit","zatemnit","zatknout","zaujmout","zavalit","zavelet","zavinit","zavolat","zavrtat","zazvonit","zbavit","zbrusu","zbudovat","zbytek","zdaleka","zdarma","zdatnost","zdivo","zdobit","zdroj","zdvih","zdymadlo","zelenina","zeman","zemina","zeptat","zezadu","zezdola","zhatit","zhltnout","zhluboka","zhotovit","zhruba","zima","zimnice","zjemnit","zklamat","zkoumat","zkratka","zkumavka","zlato","zlehka","zloba","zlom","zlost","zlozvyk","zmapovat","zmar","zmatek","zmije","zmizet","zmocnit","zmodrat","zmrzlina","zmutovat","znak","znalost","znamenat","znovu","zobrazit","zotavit","zoubek","zoufale","zplodit","zpomalit","zprava","zprostit","zprudka","zprvu","zrada","zranit","zrcadlo","zrnitost","zrno","zrovna","zrychlit","zrzavost","zticha","ztratit","zubovina","zubr","zvednout","zvenku","zvesela","zvon","zvrat","zvukovod","zvyk"]["abandon","ability","able","about","above","absent","absorb","abstract","absurd","abuse","access","accident","account","accuse","achieve","acid","acoustic","acquire","across","act","action","actor","actress","actual","adapt","add","addict","address","adjust","admit","adult","advance","advice","aerobic","affair","afford","afraid","again","age","agent","agree","ahead","aim","air","airport","aisle","alarm","album","alcohol","alert","alien","all","alley","allow","almost","alone","alpha","already","also","alter","always","amateur","amazing","among","amount","amused","analyst","anchor","ancient","anger","angle","angry","animal","ankle","announce","annual","another","answer","antenna","antique","anxiety","any","apart","apology","appear","apple","approve","april","arch","arctic","area","arena","argue","arm","armed","armor","army","around","arrange","arrest","arrive","arrow","art","artefact","artist","artwork","ask","aspect","assault","asset","assist","assume","asthma","athlete","atom","attack","attend","attitude","attract","auction","audit","august","aunt","author","auto","autumn","average","avocado","avoid","awake","aware","away","awesome","awful","awkward","axis","baby","bachelor","bacon","badge","bag","balance","balcony","ball","bamboo","banana","banner","bar","barely","bargain","barrel","base","basic","basket","battle","beach","bean","beauty","because","become","beef","before","begin","behave","behind","believe","below","belt","bench","benefit","best","betray","better","between","beyond","bicycle","bid","bike","bind","biology","bird","birth","bitter","black","blade","blame","blanket","blast","bleak","bless","blind","blood","blossom","blouse","blue","blur","blush","board","boat","body","boil","bomb","bone","bonus","book","boost","border","boring","borrow","boss","bottom","bounce","box","boy","bracket","brain","brand","brass","brave","bread","breeze","brick","bridge","brief","bright","bring","brisk","broccoli","broken","bronze","broom","brother","brown","brush","bubble","buddy","budget","buffalo","build","bulb","bulk","bullet","bundle","bunker","burden","burger","burst","bus","business","busy","butter","buyer","buzz","cabbage","cabin","cable","cactus","cage","cake","call","calm","camera","camp","can","canal","cancel","candy","cannon","canoe","canvas","canyon","capable","capital","captain","car","carbon","card","cargo","carpet","carry","cart","case","cash","casino","castle","casual","cat","catalog","catch","category","cattle","caught","cause","caution","cave","ceiling","celery","cement","census","century","cereal","certain","chair","chalk","champion","change","chaos","chapter","charge","chase","chat","cheap","check","cheese","chef","cherry","chest","chicken","chief","child","chimney","choice","choose","chronic","chuckle","chunk","churn","cigar","cinnamon","circle","citizen","city","civil","claim","clap","clarify","claw","clay","clean","clerk","clever","click","client","cliff","climb","clinic","clip","clock","clog","close","cloth","cloud","clown","club","clump","cluster","clutch","coach","coast","coconut","code","coffee","coil","coin","collect","color","column","combine","come","comfort","comic","common","company","concert","conduct","confirm","congress","connect","consider","control","convince","cook","cool","copper","copy","coral","core","corn","correct","cost","cotton","couch","country","couple","course","cousin","cover","coyote","crack","cradle","craft","cram","crane","crash","crater","crawl","crazy","cream","credit","creek","crew","cricket","crime","crisp","critic","crop","cross","crouch","crowd","crucial","cruel","cruise","crumble","crunch","crush","cry","crystal","cube","culture","cup","cupboard","curious","current","curtain","curve","cushion","custom","cute","cycle","dad","damage","damp","dance","danger","daring","dash","daughter","dawn","day","deal","debate","debris","decade","december","decide","decline","decorate","decrease","deer","defense","define","defy","degree","delay","deliver","demand","demise","denial","dentist","deny","depart","depend","deposit","depth","deputy","derive","describe","desert","design","desk","despair","destroy","detail","detect","develop","device","devote","diagram","dial","diamond","diary","dice","diesel","diet","differ","digital","dignity","dilemma","dinner","dinosaur","direct","dirt","disagree","discover","disease","dish","dismiss","disorder","display","distance","divert","divide","divorce","dizzy","doctor","document","dog","doll","dolphin","domain","donate","donkey","donor","door","dose","double","dove","draft","dragon","drama","drastic","draw","dream","dress","drift","drill","drink","drip","drive","drop","drum","dry","duck","dumb","dune","during","dust","dutch","duty","dwarf","dynamic","eager","eagle","early","earn","earth","easily","east","easy","echo","ecology","economy","edge","edit","educate","effort","egg","eight","either","elbow","elder","electric","elegant","element","elephant","elevator","elite","else","embark","embody","embrace","emerge","emotion","employ","empower","empty","enable","enact","end","endless","endorse","enemy","energy","enforce","engage","engine","enhance","enjoy","enlist","enough","enrich","enroll","ensure","enter","entire","entry","envelope","episode","equal","equip","era","erase","erode","erosion","error","erupt","escape","essay","essence","estate","eternal","ethics","evidence","evil","evoke","evolve","exact","example","excess","exchange","excite","exclude","excuse","execute","exercise","exhaust","exhibit","exile","exist","exit","exotic","expand","expect","expire","explain","expose","express","extend","extra","eye","eyebrow","fabric","face","faculty","fade","faint","faith","fall","false","fame","family","famous","fan","fancy","fantasy","farm","fashion","fat","fatal","father","fatigue","fault","favorite","feature","february","federal","fee","feed","feel","female","fence","festival","fetch","fever","few","fiber","fiction","field","figure","file","film","filter","final","find","fine","finger","finish","fire","firm","first","fiscal","fish","fit","fitness","fix","flag","flame","flash","flat","flavor","flee","flight","flip","float","flock","floor","flower","fluid","flush","fly","foam","focus","fog","foil","fold","follow","food","foot","force","forest","forget","fork","fortune","forum","forward","fossil","foster","found","fox","fragile","frame","frequent","fresh","friend","fringe","frog","front","frost","frown","frozen","fruit","fuel","fun","funny","furnace","fury","future","gadget","gain","galaxy","gallery","game","gap","garage","garbage","garden","garlic","garment","gas","gasp","gate","gather","gauge","gaze","general","genius","genre","gentle","genuine","gesture","ghost","giant","gift","giggle","ginger","giraffe","girl","give","glad","glance","glare","glass","glide","glimpse","globe","gloom","glory","glove","glow","glue","goat","goddess","gold","good","goose","gorilla","gospel","gossip","govern","gown","grab","grace","grain","grant","grape","grass","gravity","great","green","grid","grief","grit","grocery","group","grow","grunt","guard","guess","guide","guilt","guitar","gun","gym","habit","hair","half","hammer","hamster","hand","happy","harbor","hard","harsh","harvest","hat","have","hawk","hazard","head","health","heart","heavy","hedgehog","height","hello","helmet","help","hen","hero","hidden","high","hill","hint","hip","hire","history","hobby","hockey","hold","hole","holiday","hollow","home","honey","hood","hope","horn","horror","horse","hospital","host","hotel","hour","hover","hub","huge","human","humble","humor","hundred","hungry","hunt","hurdle","hurry","hurt","husband","hybrid","ice","icon","idea","identify","idle","ignore","ill","illegal","illness","image","imitate","immense","immune","impact","impose","improve","impulse","inch","include","income","increase","index","indicate","indoor","industry","infant","inflict","inform","inhale","inherit","initial","inject","injury","inmate","inner","innocent","input","inquiry","insane","insect","inside","inspire","install","intact","interest","into","invest","invite","involve","iron","island","isolate","issue","item","ivory","jacket","jaguar","jar","jazz","jealous","jeans","jelly","jewel","job","join","joke","journey","joy","judge","juice","jump","jungle","junior","junk","just","kangaroo","keen","keep","ketchup","key","kick","kid","kidney","kind","kingdom","kiss","kit","kitchen","kite","kitten","kiwi","knee","knife","knock","know","lab","label","labor","ladder","lady","lake","lamp","language","laptop","large","later","latin","laugh","laundry","lava","law","lawn","lawsuit","layer","lazy","leader","leaf","learn","leave","lecture","left","leg","legal","legend","leisure","lemon","lend","length","lens","leopard","lesson","letter","level","liar","liberty","library","license","life","lift","light","like","limb","limit","link","lion","liquid","list","little","live","lizard","load","loan","lobster","local","lock","logic","lonely","long","loop","lottery","loud","lounge","love","loyal","lucky","luggage","lumber","lunar","lunch","luxury","lyrics","machine","mad","magic","magnet","maid","mail","main","major","make","mammal","man","manage","mandate","mango","mansion","manual","maple","marble","march","margin","marine","market","marriage","mask","mass","master","match","material","math","matrix","matter","maximum","maze","meadow","mean","measure","meat","mechanic","medal","media","melody","melt","member","memory","mention","menu","mercy","merge","merit","merry","mesh","message","metal","method","middle","midnight","milk","million","mimic","mind","minimum","minor","minute","miracle","mirror","misery","miss","mistake","mix","mixed","mixture","mobile","model","modify","mom","moment","monitor","monkey","monster","month","moon","moral","more","morning","mosquito","mother","motion","motor","mountain","mouse","move","movie","much","muffin","mule","multiply","muscle","museum","mushroom","music","must","mutual","myself","mystery","myth","naive","name","napkin","narrow","nasty","nation","nature","near","neck","need","negative","neglect","neither","nephew","nerve","nest","net","network","neutral","never","news","next","nice","night","noble","noise","nominee","noodle","normal","north","nose","notable","note","nothing","notice","novel","now","nuclear","number","nurse","nut","oak","obey","object","oblige","obscure","observe","obtain","obvious","occur","ocean","october","odor","off","offer","office","often","oil","okay","old","olive","olympic","omit","once","one","onion","online","only","open","opera","opinion","oppose","option","orange","orbit","orchard","order","ordinary","organ","orient","original","orphan","ostrich","other","outdoor","outer","output","outside","oval","oven","over","own","owner","oxygen","oyster","ozone","pact","paddle","page","pair","palace","palm","panda","panel","panic","panther","paper","parade","parent","park","parrot","party","pass","patch","path","patient","patrol","pattern","pause","pave","payment","peace","peanut","pear","peasant","pelican","pen","penalty","pencil","people","pepper","perfect","permit","person","pet","phone","photo","phrase","physical","piano","picnic","picture","piece","pig","pigeon","pill","pilot","pink","pioneer","pipe","pistol","pitch","pizza","place","planet","plastic","plate","play","please","pledge","pluck","plug","plunge","poem","poet","point","polar","pole","police","pond","pony","pool","popular","portion","position","possible","post","potato","pottery","poverty","powder","power","practice","praise","predict","prefer","prepare","present","pretty","prevent","price","pride","primary","print","priority","prison","private","prize","problem","process","produce","profit","program","project","promote","proof","property","prosper","protect","proud","provide","public","pudding","pull","pulp","pulse","pumpkin","punch","pupil","puppy","purchase","purity","purpose","purse","push","put","puzzle","pyramid","quality","quantum","quarter","question","quick","quit","quiz","quote","rabbit","raccoon","race","rack","radar","radio","rail","rain","raise","rally","ramp","ranch","random","range","rapid","rare","rate","rather","raven","raw","razor","ready","real","reason","rebel","rebuild","recall","receive","recipe","record","recycle","reduce","reflect","reform","refuse","region","regret","regular","reject","relax","release","relief","rely","remain","remember","remind","remove","render","renew","rent","reopen","repair","repeat","replace","report","require","rescue","resemble","resist","resource","response","result","retire","retreat","return","reunion","reveal","review","reward","rhythm","rib","ribbon","rice","rich","ride","ridge","rifle","right","rigid","ring","riot","ripple","risk","ritual","rival","river","road","roast","robot","robust","rocket","romance","roof","rookie","room","rose","rotate","rough","round","route","royal","rubber","rude","rug","rule","run","runway","rural","sad","saddle","sadness","safe","sail","salad","salmon","salon","salt","salute","same","sample","sand","satisfy","satoshi","sauce","sausage","save","say","scale","scan","scare","scatter","scene","scheme","school","science","scissors","scorpion","scout","scrap","screen","script","scrub","sea","search","season","seat","second","secret","section","security","seed","seek","segment","select","sell","seminar","senior","sense","sentence","series","service","session","settle","setup","seven","shadow","shaft","shallow","share","shed","shell","sheriff","shield","shift","shine","ship","shiver","shock","shoe","shoot","shop","short","shoulder","shove","shrimp","shrug","shuffle","shy","sibling","sick","side","siege","sight","sign","silent","silk","silly","silver","similar","simple","since","sing","siren","sister","situate","six","size","skate","sketch","ski","skill","skin","skirt","skull","slab","slam","sleep","slender","slice","slide","slight","slim","slogan","slot","slow","slush","small","smart","smile","smoke","smooth","snack","snake","snap","sniff","snow","soap","soccer","social","sock","soda","soft","solar","soldier","solid","solution","solve","someone","song","soon","sorry","sort","soul","sound","soup","source","south","space","spare","spatial","spawn","speak","special","speed","spell","spend","sphere","spice","spider","spike","spin","spirit","split","spoil","sponsor","spoon","sport","spot","spray","spread","spring","spy","square","squeeze","squirrel","stable","stadium","staff","stage","stairs","stamp","stand","start","state","stay","steak","steel","stem","step","stereo","stick","still","sting","stock","stomach","stone","stool","story","stove","strategy","street","strike","strong","struggle","student","stuff","stumble","style","subject","submit","subway","success","such","sudden","suffer","sugar","suggest","suit","summer","sun","sunny","sunset","super","supply","supreme","sure","surface","surge","surprise","surround","survey","suspect","sustain","swallow","swamp","swap","swarm","swear","sweet","swift","swim","swing","switch","sword","symbol","symptom","syrup","system","table","tackle","tag","tail","talent","talk","tank","tape","target","task","taste","tattoo","taxi","teach","team","tell","ten","tenant","tennis","tent","term","test","text","thank","that","theme","then","theory","there","they","thing","this","thought","three","thrive","throw","thumb","thunder","ticket","tide","tiger","tilt","timber","time","tiny","tip","tired","tissue","title","toast","tobacco","today","toddler","toe","together","toilet","token","tomato","tomorrow","tone","tongue","tonight","tool","tooth","top","topic","topple","torch","tornado","tortoise","toss","total","tourist","toward","tower","town","toy","track","trade","traffic","tragic","train","transfer","trap","trash","travel","tray","treat","tree","trend","trial","tribe","trick","trigger","trim","trip","trophy","trouble","truck","true","truly","trumpet","trust","truth","try","tube","tuition","tumble","tuna","tunnel","turkey","turn","turtle","twelve","twenty","twice","twin","twist","two","type","typical","ugly","umbrella","unable","unaware","uncle","uncover","under","undo","unfair","unfold","unhappy","uniform","unique","unit","universe","unknown","unlock","until","unusual","unveil","update","upgrade","uphold","upon","upper","upset","urban","urge","usage","use","used","useful","useless","usual","utility","vacant","vacuum","vague","valid","valley","valve","van","vanish","vapor","various","vast","vault","vehicle","velvet","vendor","venture","venue","verb","verify","version","very","vessel","veteran","viable","vibrant","vicious","victory","video","view","village","vintage","violin","virtual","virus","visa","visit","visual","vital","vivid","vocal","voice","void","volcano","volume","vote","voyage","wage","wagon","wait","walk","wall","walnut","want","warfare","warm","warrior","wash","wasp","waste","water","wave","way","wealth","weapon","wear","weasel","weather","web","wedding","weekend","weird","welcome","west","wet","whale","what","wheat","wheel","when","where","whip","whisper","wide","width","wife","wild","will","win","window","wine","wing","wink","winner","winter","wire","wisdom","wise","wish","witness","wolf","woman","wonder","wood","wool","word","work","world","worry","worth","wrap","wreck","wrestle","wrist","write","wrong","yard","year","yellow","you","young","youth","zebra","zero","zone","zoo"]["abaisser","abandon","abdiquer","abeille","abolir","aborder","aboutir","aboyer","abrasif","abreuver","abriter","abroger","abrupt","absence","absolu","absurde","abusif","abyssal","académie","acajou","acarien","accabler","accepter","acclamer","accolade","accroche","accuser","acerbe","achat","acheter","aciduler","acier","acompte","acquérir","acronyme","acteur","actif","actuel","adepte","adéquat","adhésif","adjectif","adjuger","admettre","admirer","adopter","adorer","adoucir","adresse","adroit","adulte","adverbe","aérer","aéronef","affaire","affecter","affiche","affreux","affubler","agacer","agencer","agile","agiter","agrafer","agréable","agrume","aider","aiguille","ailier","aimable","aisance","ajouter","ajuster","alarmer","alchimie","alerte","algèbre","algue","aliéner","aliment","alléger","alliage","allouer","allumer","alourdir","alpaga","altesse","alvéole","amateur","ambigu","ambre","aménager","amertume","amidon","amiral","amorcer","amour","amovible","amphibie","ampleur","amusant","analyse","anaphore","anarchie","anatomie","ancien","anéantir","angle","angoisse","anguleux","animal","annexer","annonce","annuel","anodin","anomalie","anonyme","anormal","antenne","antidote","anxieux","apaiser","apéritif","aplanir","apologie","appareil","appeler","apporter","appuyer","aquarium","aqueduc","arbitre","arbuste","ardeur","ardoise","argent","arlequin","armature","armement","armoire","armure","arpenter","arracher","arriver","arroser","arsenic","artériel","article","aspect","asphalte","aspirer","assaut","asservir","assiette","associer","assurer","asticot","astre","astuce","atelier","atome","atrium","atroce","attaque","attentif","attirer","attraper","aubaine","auberge","audace","audible","augurer","aurore","automne","autruche","avaler","avancer","avarice","avenir","averse","aveugle","aviateur","avide","avion","aviser","avoine","avouer","avril","axial","axiome","badge","bafouer","bagage","baguette","baignade","balancer","balcon","baleine","balisage","bambin","bancaire","bandage","banlieue","bannière","banquier","barbier","baril","baron","barque","barrage","bassin","bastion","bataille","bateau","batterie","baudrier","bavarder","belette","bélier","belote","bénéfice","berceau","berger","berline","bermuda","besace","besogne","bétail","beurre","biberon","bicycle","bidule","bijou","bilan","bilingue","billard","binaire","biologie","biopsie","biotype","biscuit","bison","bistouri","bitume","bizarre","blafard","blague","blanchir","blessant","blinder","blond","bloquer","blouson","bobard","bobine","boire","boiser","bolide","bonbon","bondir","bonheur","bonifier","bonus","bordure","borne","botte","boucle","boueux","bougie","boulon","bouquin","bourse","boussole","boutique","boxeur","branche","brasier","brave","brebis","brèche","breuvage","bricoler","brigade","brillant","brioche","brique","brochure","broder","bronzer","brousse","broyeur","brume","brusque","brutal","bruyant","buffle","buisson","bulletin","bureau","burin","bustier","butiner","butoir","buvable","buvette","cabanon","cabine","cachette","cadeau","cadre","caféine","caillou","caisson","calculer","calepin","calibre","calmer","calomnie","calvaire","camarade","caméra","camion","campagne","canal","caneton","canon","cantine","canular","capable","caporal","caprice","capsule","capter","capuche","carabine","carbone","caresser","caribou","carnage","carotte","carreau","carton","cascade","casier","casque","cassure","causer","caution","cavalier","caverne","caviar","cédille","ceinture","céleste","cellule","cendrier","censurer","central","cercle","cérébral","cerise","cerner","cerveau","cesser","chagrin","chaise","chaleur","chambre","chance","chapitre","charbon","chasseur","chaton","chausson","chavirer","chemise","chenille","chéquier","chercher","cheval","chien","chiffre","chignon","chimère","chiot","chlorure","chocolat","choisir","chose","chouette","chrome","chute","cigare","cigogne","cimenter","cinéma","cintrer","circuler","cirer","cirque","citerne","citoyen","citron","civil","clairon","clameur","claquer","classe","clavier","client","cligner","climat","clivage","cloche","clonage","cloporte","cobalt","cobra","cocasse","cocotier","coder","codifier","coffre","cogner","cohésion","coiffer","coincer","colère","colibri","colline","colmater","colonel","combat","comédie","commande","compact","concert","conduire","confier","congeler","connoter","consonne","contact","convexe","copain","copie","corail","corbeau","cordage","corniche","corpus","correct","cortège","cosmique","costume","coton","coude","coupure","courage","couteau","couvrir","coyote","crabe","crainte","cravate","crayon","créature","créditer","crémeux","creuser","crevette","cribler","crier","cristal","critère","croire","croquer","crotale","crucial","cruel","crypter","cubique","cueillir","cuillère","cuisine","cuivre","culminer","cultiver","cumuler","cupide","curatif","curseur","cyanure","cycle","cylindre","cynique","daigner","damier","danger","danseur","dauphin","débattre","débiter","déborder","débrider","débutant","décaler","décembre","déchirer","décider","déclarer","décorer","décrire","décupler","dédale","déductif","déesse","défensif","défiler","défrayer","dégager","dégivrer","déglutir","dégrafer","déjeuner","délice","déloger","demander","demeurer","démolir","dénicher","dénouer","dentelle","dénuder","départ","dépenser","déphaser","déplacer","déposer","déranger","dérober","désastre","descente","désert","désigner","désobéir","dessiner","destrier","détacher","détester","détourer","détresse","devancer","devenir","deviner","devoir","diable","dialogue","diamant","dicter","différer","digérer","digital","digne","diluer","dimanche","diminuer","dioxyde","directif","diriger","discuter","disposer","dissiper","distance","divertir","diviser","docile","docteur","dogme","doigt","domaine","domicile","dompter","donateur","donjon","donner","dopamine","dortoir","dorure","dosage","doseur","dossier","dotation","douanier","double","douceur","douter","doyen","dragon","draper","dresser","dribbler","droiture","duperie","duplexe","durable","durcir","dynastie","éblouir","écarter","écharpe","échelle","éclairer","éclipse","éclore","écluse","école","économie","écorce","écouter","écraser","écrémer","écrivain","écrou","écume","écureuil","édifier","éduquer","effacer","effectif","effigie","effort","effrayer","effusion","égaliser","égarer","éjecter","élaborer","élargir","électron","élégant","éléphant","élève","éligible","élitisme","éloge","élucider","éluder","emballer","embellir","embryon","émeraude","émission","emmener","émotion","émouvoir","empereur","employer","emporter","emprise","émulsion","encadrer","enchère","enclave","encoche","endiguer","endosser","endroit","enduire","énergie","enfance","enfermer","enfouir","engager","engin","englober","énigme","enjamber","enjeu","enlever","ennemi","ennuyeux","enrichir","enrobage","enseigne","entasser","entendre","entier","entourer","entraver","énumérer","envahir","enviable","envoyer","enzyme","éolien","épaissir","épargne","épatant","épaule","épicerie","épidémie","épier","épilogue","épine","épisode","épitaphe","époque","épreuve","éprouver","épuisant","équerre","équipe","ériger","érosion","erreur","éruption","escalier","espadon","espèce","espiègle","espoir","esprit","esquiver","essayer","essence","essieu","essorer","estime","estomac","estrade","étagère","étaler","étanche","étatique","éteindre","étendoir","éternel","éthanol","éthique","ethnie","étirer","étoffer","étoile","étonnant","étourdir","étrange","étroit","étude","euphorie","évaluer","évasion","éventail","évidence","éviter","évolutif","évoquer","exact","exagérer","exaucer","exceller","excitant","exclusif","excuse","exécuter","exemple","exercer","exhaler","exhorter","exigence","exiler","exister","exotique","expédier","explorer","exposer","exprimer","exquis","extensif","extraire","exulter","fable","fabuleux","facette","facile","facture","faiblir","falaise","fameux","famille","farceur","farfelu","farine","farouche","fasciner","fatal","fatigue","faucon","fautif","faveur","favori","fébrile","féconder","fédérer","félin","femme","fémur","fendoir","féodal","fermer","féroce","ferveur","festival","feuille","feutre","février","fiasco","ficeler","fictif","fidèle","figure","filature","filetage","filière","filleul","filmer","filou","filtrer","financer","finir","fiole","firme","fissure","fixer","flairer","flamme","flasque","flatteur","fléau","flèche","fleur","flexion","flocon","flore","fluctuer","fluide","fluvial","folie","fonderie","fongible","fontaine","forcer","forgeron","formuler","fortune","fossile","foudre","fougère","fouiller","foulure","fourmi","fragile","fraise","franchir","frapper","frayeur","frégate","freiner","frelon","frémir","frénésie","frère","friable","friction","frisson","frivole","froid","fromage","frontal","frotter","fruit","fugitif","fuite","fureur","furieux","furtif","fusion","futur","gagner","galaxie","galerie","gambader","garantir","gardien","garnir","garrigue","gazelle","gazon","géant","gélatine","gélule","gendarme","général","génie","genou","gentil","géologie","géomètre","géranium","germe","gestuel","geyser","gibier","gicler","girafe","givre","glace","glaive","glisser","globe","gloire","glorieux","golfeur","gomme","gonfler","gorge","gorille","goudron","gouffre","goulot","goupille","gourmand","goutte","graduel","graffiti","graine","grand","grappin","gratuit","gravir","grenat","griffure","griller","grimper","grogner","gronder","grotte","groupe","gruger","grutier","gruyère","guépard","guerrier","guide","guimauve","guitare","gustatif","gymnaste","gyrostat","habitude","hachoir","halte","hameau","hangar","hanneton","haricot","harmonie","harpon","hasard","hélium","hématome","herbe","hérisson","hermine","héron","hésiter","heureux","hiberner","hibou","hilarant","histoire","hiver","homard","hommage","homogène","honneur","honorer","honteux","horde","horizon","horloge","hormone","horrible","houleux","housse","hublot","huileux","humain","humble","humide","humour","hurler","hydromel","hygiène","hymne","hypnose","idylle","ignorer","iguane","illicite","illusion","image","imbiber","imiter","immense","immobile","immuable","impact","impérial","implorer","imposer","imprimer","imputer","incarner","incendie","incident","incliner","incolore","indexer","indice","inductif","inédit","ineptie","inexact","infini","infliger","informer","infusion","ingérer","inhaler","inhiber","injecter","injure","innocent","inoculer","inonder","inscrire","insecte","insigne","insolite","inspirer","instinct","insulter","intact","intense","intime","intrigue","intuitif","inutile","invasion","inventer","inviter","invoquer","ironique","irradier","irréel","irriter","isoler","ivoire","ivresse","jaguar","jaillir","jambe","janvier","jardin","jauger","jaune","javelot","jetable","jeton","jeudi","jeunesse","joindre","joncher","jongler","joueur","jouissif","journal","jovial","joyau","joyeux","jubiler","jugement","junior","jupon","juriste","justice","juteux","juvénile","kayak","kimono","kiosque","label","labial","labourer","lacérer","lactose","lagune","laine","laisser","laitier","lambeau","lamelle","lampe","lanceur","langage","lanterne","lapin","largeur","larme","laurier","lavabo","lavoir","lecture","légal","léger","légume","lessive","lettre","levier","lexique","lézard","liasse","libérer","libre","licence","licorne","liège","lièvre","ligature","ligoter","ligue","limer","limite","limonade","limpide","linéaire","lingot","lionceau","liquide","lisière","lister","lithium","litige","littoral","livreur","logique","lointain","loisir","lombric","loterie","louer","lourd","loutre","louve","loyal","lubie","lucide","lucratif","lueur","lugubre","luisant","lumière","lunaire","lundi","luron","lutter","luxueux","machine","magasin","magenta","magique","maigre","maillon","maintien","mairie","maison","majorer","malaxer","maléfice","malheur","malice","mallette","mammouth","mandater","maniable","manquant","manteau","manuel","marathon","marbre","marchand","mardi","maritime","marqueur","marron","marteler","mascotte","massif","matériel","matière","matraque","maudire","maussade","mauve","maximal","méchant","méconnu","médaille","médecin","méditer","méduse","meilleur","mélange","mélodie","membre","mémoire","menacer","mener","menhir","mensonge","mentor","mercredi","mérite","merle","messager","mesure","métal","météore","méthode","métier","meuble","miauler","microbe","miette","mignon","migrer","milieu","million","mimique","mince","minéral","minimal","minorer","minute","miracle","miroiter","missile","mixte","mobile","moderne","moelleux","mondial","moniteur","monnaie","monotone","monstre","montagne","monument","moqueur","morceau","morsure","mortier","moteur","motif","mouche","moufle","moulin","mousson","mouton","mouvant","multiple","munition","muraille","murène","murmure","muscle","muséum","musicien","mutation","muter","mutuel","myriade","myrtille","mystère","mythique","nageur","nappe","narquois","narrer","natation","nation","nature","naufrage","nautique","navire","nébuleux","nectar","néfaste","négation","négliger","négocier","neige","nerveux","nettoyer","neurone","neutron","neveu","niche","nickel","nitrate","niveau","noble","nocif","nocturne","noirceur","noisette","nomade","nombreux","nommer","normatif","notable","notifier","notoire","nourrir","nouveau","novateur","novembre","novice","nuage","nuancer","nuire","nuisible","numéro","nuptial","nuque","nutritif","obéir","objectif","obliger","obscur","observer","obstacle","obtenir","obturer","occasion","occuper","océan","octobre","octroyer","octupler","oculaire","odeur","odorant","offenser","officier","offrir","ogive","oiseau","oisillon","olfactif","olivier","ombrage","omettre","onctueux","onduler","onéreux","onirique","opale","opaque","opérer","opinion","opportun","opprimer","opter","optique","orageux","orange","orbite","ordonner","oreille","organe","orgueil","orifice","ornement","orque","ortie","osciller","osmose","ossature","otarie","ouragan","ourson","outil","outrager","ouvrage","ovation","oxyde","oxygène","ozone","paisible","palace","palmarès","palourde","palper","panache","panda","pangolin","paniquer","panneau","panorama","pantalon","papaye","papier","papoter","papyrus","paradoxe","parcelle","paresse","parfumer","parler","parole","parrain","parsemer","partager","parure","parvenir","passion","pastèque","paternel","patience","patron","pavillon","pavoiser","payer","paysage","peigne","peintre","pelage","pélican","pelle","pelouse","peluche","pendule","pénétrer","pénible","pensif","pénurie","pépite","péplum","perdrix","perforer","période","permuter","perplexe","persil","perte","peser","pétale","petit","pétrir","peuple","pharaon","phobie","phoque","photon","phrase","physique","piano","pictural","pièce","pierre","pieuvre","pilote","pinceau","pipette","piquer","pirogue","piscine","piston","pivoter","pixel","pizza","placard","plafond","plaisir","planer","plaque","plastron","plateau","pleurer","plexus","pliage","plomb","plonger","pluie","plumage","pochette","poésie","poète","pointe","poirier","poisson","poivre","polaire","policier","pollen","polygone","pommade","pompier","ponctuel","pondérer","poney","portique","position","posséder","posture","potager","poteau","potion","pouce","poulain","poumon","pourpre","poussin","pouvoir","prairie","pratique","précieux","prédire","préfixe","prélude","prénom","présence","prétexte","prévoir","primitif","prince","prison","priver","problème","procéder","prodige","profond","progrès","proie","projeter","prologue","promener","propre","prospère","protéger","prouesse","proverbe","prudence","pruneau","psychose","public","puceron","puiser","pulpe","pulsar","punaise","punitif","pupitre","purifier","puzzle","pyramide","quasar","querelle","question","quiétude","quitter","quotient","racine","raconter","radieux","ragondin","raideur","raisin","ralentir","rallonge","ramasser","rapide","rasage","ratisser","ravager","ravin","rayonner","réactif","réagir","réaliser","réanimer","recevoir","réciter","réclamer","récolter","recruter","reculer","recycler","rédiger","redouter","refaire","réflexe","réformer","refrain","refuge","régalien","région","réglage","régulier","réitérer","rejeter","rejouer","relatif","relever","relief","remarque","remède","remise","remonter","remplir","remuer","renard","renfort","renifler","renoncer","rentrer","renvoi","replier","reporter","reprise","reptile","requin","réserve","résineux","résoudre","respect","rester","résultat","rétablir","retenir","réticule","retomber","retracer","réunion","réussir","revanche","revivre","révolte","révulsif","richesse","rideau","rieur","rigide","rigoler","rincer","riposter","risible","risque","rituel","rival","rivière","rocheux","romance","rompre","ronce","rondin","roseau","rosier","rotatif","rotor","rotule","rouge","rouille","rouleau","routine","royaume","ruban","rubis","ruche","ruelle","rugueux","ruiner","ruisseau","ruser","rustique","rythme","sabler","saboter","sabre","sacoche","safari","sagesse","saisir","salade","salive","salon","saluer","samedi","sanction","sanglier","sarcasme","sardine","saturer","saugrenu","saumon","sauter","sauvage","savant","savonner","scalpel","scandale","scélérat","scénario","sceptre","schéma","science","scinder","score","scrutin","sculpter","séance","sécable","sécher","secouer","sécréter","sédatif","séduire","seigneur","séjour","sélectif","semaine","sembler","semence","séminal","sénateur","sensible","sentence","séparer","séquence","serein","sergent","sérieux","serrure","sérum","service","sésame","sévir","sevrage","sextuple","sidéral","siècle","siéger","siffler","sigle","signal","silence","silicium","simple","sincère","sinistre","siphon","sirop","sismique","situer","skier","social","socle","sodium","soigneux","soldat","soleil","solitude","soluble","sombre","sommeil","somnoler","sonde","songeur","sonnette","sonore","sorcier","sortir","sosie","sottise","soucieux","soudure","souffle","soulever","soupape","source","soutirer","souvenir","spacieux","spatial","spécial","sphère","spiral","stable","station","sternum","stimulus","stipuler","strict","studieux","stupeur","styliste","sublime","substrat","subtil","subvenir","succès","sucre","suffixe","suggérer","suiveur","sulfate","superbe","supplier","surface","suricate","surmener","surprise","sursaut","survie","suspect","syllabe","symbole","symétrie","synapse","syntaxe","système","tabac","tablier","tactile","tailler","talent","talisman","talonner","tambour","tamiser","tangible","tapis","taquiner","tarder","tarif","tartine","tasse","tatami","tatouage","taupe","taureau","taxer","témoin","temporel","tenaille","tendre","teneur","tenir","tension","terminer","terne","terrible","tétine","texte","thème","théorie","thérapie","thorax","tibia","tiède","timide","tirelire","tiroir","tissu","titane","titre","tituber","toboggan","tolérant","tomate","tonique","tonneau","toponyme","torche","tordre","tornade","torpille","torrent","torse","tortue","totem","toucher","tournage","tousser","toxine","traction","trafic","tragique","trahir","train","trancher","travail","trèfle","tremper","trésor","treuil","triage","tribunal","tricoter","trilogie","triomphe","tripler","triturer","trivial","trombone","tronc","tropical","troupeau","tuile","tulipe","tumulte","tunnel","turbine","tuteur","tutoyer","tuyau","tympan","typhon","typique","tyran","ubuesque","ultime","ultrason","unanime","unifier","union","unique","unitaire","univers","uranium","urbain","urticant","usage","usine","usuel","usure","utile","utopie","vacarme","vaccin","vagabond","vague","vaillant","vaincre","vaisseau","valable","valise","vallon","valve","vampire","vanille","vapeur","varier","vaseux","vassal","vaste","vecteur","vedette","végétal","véhicule","veinard","véloce","vendredi","vénérer","venger","venimeux","ventouse","verdure","vérin","vernir","verrou","verser","vertu","veston","vétéran","vétuste","vexant","vexer","viaduc","viande","victoire","vidange","vidéo","vignette","vigueur","vilain","village","vinaigre","violon","vipère","virement","virtuose","virus","visage","viseur","vision","visqueux","visuel","vital","vitesse","viticole","vitrine","vivace","vivipare","vocation","voguer","voile","voisin","voiture","volaille","volcan","voltiger","volume","vorace","vortex","voter","vouloir","voyage","voyelle","wagon","xénon","yacht","zèbre","zénith","zeste","zoologie"]// note all JSON files in this folder are generated with npm run generate-wordlist
const lookup = require('./lookup.json')

module.exports = {
  loadWordlist,
  detectLanguage
}

function loadWordlist (language) {
  switch (language) {
    case 'chinese_simplified': return require('./chinese_simplified.json')
    case 'chinese_traditional': return require('./chinese_traditional.json')
    case 'czech': return require('./czech.json')
    case 'english': return require('./english.json')
    case 'french': return require('./french.json')
    case 'italian': return require('./italian.json')
    case 'japanese': return require('./japanese.json')
    case 'korean': return require('./korean.json')
    case 'portuguese': return require('./portuguese.json')
    case 'russian': return require('./russian.json')
    case 'spanish': return require('./spanish.json')
    case 'turkish': return require('./turkish.json')
  }

  throw new Error('Unknown language: ' + language)
}

function detectLanguage (words) {
  let candidate = null

  for (const word of words) {
    const languages = lookup[word]
    if (!languages) return null

    if (languages.length === 1) return languages[0]

    if (!candidate) {
      candidate = languages
      continue
    }

    const intersect = candidate.filter(l => languages.includes(l))
    if (intersect.length === 1) return intersect[0]
  }

  return candidate[0]
}
["abaco","abbaglio","abbinato","abete","abisso","abolire","abrasivo","abrogato","accadere","accenno","accusato","acetone","achille","acido","acqua","acre","acrilico","acrobata","acuto","adagio","addebito","addome","adeguato","aderire","adipe","adottare","adulare","affabile","affetto","affisso","affranto","aforisma","afoso","africano","agave","agente","agevole","aggancio","agire","agitare","agonismo","agricolo","agrumeto","aguzzo","alabarda","alato","albatro","alberato","albo","albume","alce","alcolico","alettone","alfa","algebra","aliante","alibi","alimento","allagato","allegro","allievo","allodola","allusivo","almeno","alogeno","alpaca","alpestre","altalena","alterno","alticcio","altrove","alunno","alveolo","alzare","amalgama","amanita","amarena","ambito","ambrato","ameba","america","ametista","amico","ammasso","ammenda","ammirare","ammonito","amore","ampio","ampliare","amuleto","anacardo","anagrafe","analista","anarchia","anatra","anca","ancella","ancora","andare","andrea","anello","angelo","angolare","angusto","anima","annegare","annidato","anno","annuncio","anonimo","anticipo","anzi","apatico","apertura","apode","apparire","appetito","appoggio","approdo","appunto","aprile","arabica","arachide","aragosta","araldica","arancio","aratura","arazzo","arbitro","archivio","ardito","arenile","argento","argine","arguto","aria","armonia","arnese","arredato","arringa","arrosto","arsenico","arso","artefice","arzillo","asciutto","ascolto","asepsi","asettico","asfalto","asino","asola","aspirato","aspro","assaggio","asse","assoluto","assurdo","asta","astenuto","astice","astratto","atavico","ateismo","atomico","atono","attesa","attivare","attorno","attrito","attuale","ausilio","austria","autista","autonomo","autunno","avanzato","avere","avvenire","avviso","avvolgere","azione","azoto","azzimo","azzurro","babele","baccano","bacino","baco","badessa","badilata","bagnato","baita","balcone","baldo","balena","ballata","balzano","bambino","bandire","baraonda","barbaro","barca","baritono","barlume","barocco","basilico","basso","batosta","battuto","baule","bava","bavosa","becco","beffa","belgio","belva","benda","benevole","benigno","benzina","bere","berlina","beta","bibita","bici","bidone","bifido","biga","bilancia","bimbo","binocolo","biologo","bipede","bipolare","birbante","birra","biscotto","bisesto","bisnonno","bisonte","bisturi","bizzarro","blando","blatta","bollito","bonifico","bordo","bosco","botanico","bottino","bozzolo","braccio","bradipo","brama","branca","bravura","bretella","brevetto","brezza","briglia","brillante","brindare","broccolo","brodo","bronzina","brullo","bruno","bubbone","buca","budino","buffone","buio","bulbo","buono","burlone","burrasca","bussola","busta","cadetto","caduco","calamaro","calcolo","calesse","calibro","calmo","caloria","cambusa","camerata","camicia","cammino","camola","campale","canapa","candela","cane","canino","canotto","cantina","capace","capello","capitolo","capogiro","cappero","capra","capsula","carapace","carcassa","cardo","carisma","carovana","carretto","cartolina","casaccio","cascata","caserma","caso","cassone","castello","casuale","catasta","catena","catrame","cauto","cavillo","cedibile","cedrata","cefalo","celebre","cellulare","cena","cenone","centesimo","ceramica","cercare","certo","cerume","cervello","cesoia","cespo","ceto","chela","chiaro","chicca","chiedere","chimera","china","chirurgo","chitarra","ciao","ciclismo","cifrare","cigno","cilindro","ciottolo","circa","cirrosi","citrico","cittadino","ciuffo","civetta","civile","classico","clinica","cloro","cocco","codardo","codice","coerente","cognome","collare","colmato","colore","colposo","coltivato","colza","coma","cometa","commando","comodo","computer","comune","conciso","condurre","conferma","congelare","coniuge","connesso","conoscere","consumo","continuo","convegno","coperto","copione","coppia","copricapo","corazza","cordata","coricato","cornice","corolla","corpo","corredo","corsia","cortese","cosmico","costante","cottura","covato","cratere","cravatta","creato","credere","cremoso","crescita","creta","criceto","crinale","crisi","critico","croce","cronaca","crostata","cruciale","crusca","cucire","cuculo","cugino","cullato","cupola","curatore","cursore","curvo","cuscino","custode","dado","daino","dalmata","damerino","daniela","dannoso","danzare","datato","davanti","davvero","debutto","decennio","deciso","declino","decollo","decreto","dedicato","definito","deforme","degno","delegare","delfino","delirio","delta","demenza","denotato","dentro","deposito","derapata","derivare","deroga","descritto","deserto","desiderio","desumere","detersivo","devoto","diametro","dicembre","diedro","difeso","diffuso","digerire","digitale","diluvio","dinamico","dinnanzi","dipinto","diploma","dipolo","diradare","dire","dirotto","dirupo","disagio","discreto","disfare","disgelo","disposto","distanza","disumano","dito","divano","divelto","dividere","divorato","doblone","docente","doganale","dogma","dolce","domato","domenica","dominare","dondolo","dono","dormire","dote","dottore","dovuto","dozzina","drago","druido","dubbio","dubitare","ducale","duna","duomo","duplice","duraturo","ebano","eccesso","ecco","eclissi","economia","edera","edicola","edile","editoria","educare","egemonia","egli","egoismo","egregio","elaborato","elargire","elegante","elencato","eletto","elevare","elfico","elica","elmo","elsa","eluso","emanato","emblema","emesso","emiro","emotivo","emozione","empirico","emulo","endemico","enduro","energia","enfasi","enoteca","entrare","enzima","epatite","epilogo","episodio","epocale","eppure","equatore","erario","erba","erboso","erede","eremita","erigere","ermetico","eroe","erosivo","errante","esagono","esame","esanime","esaudire","esca","esempio","esercito","esibito","esigente","esistere","esito","esofago","esortato","esoso","espanso","espresso","essenza","esso","esteso","estimare","estonia","estroso","esultare","etilico","etnico","etrusco","etto","euclideo","europa","evaso","evidenza","evitato","evoluto","evviva","fabbrica","faccenda","fachiro","falco","famiglia","fanale","fanfara","fango","fantasma","fare","farfalla","farinoso","farmaco","fascia","fastoso","fasullo","faticare","fato","favoloso","febbre","fecola","fede","fegato","felpa","feltro","femmina","fendere","fenomeno","fermento","ferro","fertile","fessura","festivo","fetta","feudo","fiaba","fiducia","fifa","figurato","filo","finanza","finestra","finire","fiore","fiscale","fisico","fiume","flacone","flamenco","flebo","flemma","florido","fluente","fluoro","fobico","focaccia","focoso","foderato","foglio","folata","folclore","folgore","fondente","fonetico","fonia","fontana","forbito","forchetta","foresta","formica","fornaio","foro","fortezza","forzare","fosfato","fosso","fracasso","frana","frassino","fratello","freccetta","frenata","fresco","frigo","frollino","fronde","frugale","frutta","fucilata","fucsia","fuggente","fulmine","fulvo","fumante","fumetto","fumoso","fune","funzione","fuoco","furbo","furgone","furore","fuso","futile","gabbiano","gaffe","galateo","gallina","galoppo","gambero","gamma","garanzia","garbo","garofano","garzone","gasdotto","gasolio","gastrico","gatto","gaudio","gazebo","gazzella","geco","gelatina","gelso","gemello","gemmato","gene","genitore","gennaio","genotipo","gergo","ghepardo","ghiaccio","ghisa","giallo","gilda","ginepro","giocare","gioiello","giorno","giove","girato","girone","gittata","giudizio","giurato","giusto","globulo","glutine","gnomo","gobba","golf","gomito","gommone","gonfio","gonna","governo","gracile","grado","grafico","grammo","grande","grattare","gravoso","grazia","greca","gregge","grifone","grigio","grinza","grotta","gruppo","guadagno","guaio","guanto","guardare","gufo","guidare","ibernato","icona","identico","idillio","idolo","idra","idrico","idrogeno","igiene","ignaro","ignorato","ilare","illeso","illogico","illudere","imballo","imbevuto","imbocco","imbuto","immane","immerso","immolato","impacco","impeto","impiego","importo","impronta","inalare","inarcare","inattivo","incanto","incendio","inchino","incisivo","incluso","incontro","incrocio","incubo","indagine","india","indole","inedito","infatti","infilare","inflitto","ingaggio","ingegno","inglese","ingordo","ingrosso","innesco","inodore","inoltrare","inondato","insano","insetto","insieme","insonnia","insulina","intasato","intero","intonaco","intuito","inumidire","invalido","invece","invito","iperbole","ipnotico","ipotesi","ippica","iride","irlanda","ironico","irrigato","irrorare","isolato","isotopo","isterico","istituto","istrice","italia","iterare","labbro","labirinto","lacca","lacerato","lacrima","lacuna","laddove","lago","lampo","lancetta","lanterna","lardoso","larga","laringe","lastra","latenza","latino","lattuga","lavagna","lavoro","legale","leggero","lembo","lentezza","lenza","leone","lepre","lesivo","lessato","lesto","letterale","leva","levigato","libero","lido","lievito","lilla","limatura","limitare","limpido","lineare","lingua","liquido","lira","lirica","lisca","lite","litigio","livrea","locanda","lode","logica","lombare","londra","longevo","loquace","lorenzo","loto","lotteria","luce","lucidato","lumaca","luminoso","lungo","lupo","luppolo","lusinga","lusso","lutto","macabro","macchina","macero","macinato","madama","magico","maglia","magnete","magro","maiolica","malafede","malgrado","malinteso","malsano","malto","malumore","mana","mancia","mandorla","mangiare","manifesto","mannaro","manovra","mansarda","mantide","manubrio","mappa","maratona","marcire","maretta","marmo","marsupio","maschera","massaia","mastino","materasso","matricola","mattone","maturo","mazurca","meandro","meccanico","mecenate","medesimo","meditare","mega","melassa","melis","melodia","meninge","meno","mensola","mercurio","merenda","merlo","meschino","mese","messere","mestolo","metallo","metodo","mettere","miagolare","mica","micelio","michele","microbo","midollo","miele","migliore","milano","milite","mimosa","minerale","mini","minore","mirino","mirtillo","miscela","missiva","misto","misurare","mitezza","mitigare","mitra","mittente","mnemonico","modello","modifica","modulo","mogano","mogio","mole","molosso","monastero","monco","mondina","monetario","monile","monotono","monsone","montato","monviso","mora","mordere","morsicato","mostro","motivato","motosega","motto","movenza","movimento","mozzo","mucca","mucosa","muffa","mughetto","mugnaio","mulatto","mulinello","multiplo","mummia","munto","muovere","murale","musa","muscolo","musica","mutevole","muto","nababbo","nafta","nanometro","narciso","narice","narrato","nascere","nastrare","naturale","nautica","naviglio","nebulosa","necrosi","negativo","negozio","nemmeno","neofita","neretto","nervo","nessuno","nettuno","neutrale","neve","nevrotico","nicchia","ninfa","nitido","nobile","nocivo","nodo","nome","nomina","nordico","normale","norvegese","nostrano","notare","notizia","notturno","novella","nucleo","nulla","numero","nuovo","nutrire","nuvola","nuziale","oasi","obbedire","obbligo","obelisco","oblio","obolo","obsoleto","occasione","occhio","occidente","occorrere","occultare","ocra","oculato","odierno","odorare","offerta","offrire","offuscato","oggetto","oggi","ognuno","olandese","olfatto","oliato","oliva","ologramma","oltre","omaggio","ombelico","ombra","omega","omissione","ondoso","onere","onice","onnivoro","onorevole","onta","operato","opinione","opposto","oracolo","orafo","ordine","orecchino","orefice","orfano","organico","origine","orizzonte","orma","ormeggio","ornativo","orologio","orrendo","orribile","ortensia","ortica","orzata","orzo","osare","oscurare","osmosi","ospedale","ospite","ossa","ossidare","ostacolo","oste","otite","otre","ottagono","ottimo","ottobre","ovale","ovest","ovino","oviparo","ovocito","ovunque","ovviare","ozio","pacchetto","pace","pacifico","padella","padrone","paese","paga","pagina","palazzina","palesare","pallido","palo","palude","pandoro","pannello","paolo","paonazzo","paprica","parabola","parcella","parere","pargolo","pari","parlato","parola","partire","parvenza","parziale","passivo","pasticca","patacca","patologia","pattume","pavone","peccato","pedalare","pedonale","peggio","peloso","penare","pendice","penisola","pennuto","penombra","pensare","pentola","pepe","pepita","perbene","percorso","perdonato","perforare","pergamena","periodo","permesso","perno","perplesso","persuaso","pertugio","pervaso","pesatore","pesista","peso","pestifero","petalo","pettine","petulante","pezzo","piacere","pianta","piattino","piccino","picozza","piega","pietra","piffero","pigiama","pigolio","pigro","pila","pilifero","pillola","pilota","pimpante","pineta","pinna","pinolo","pioggia","piombo","piramide","piretico","pirite","pirolisi","pitone","pizzico","placebo","planare","plasma","platano","plenario","pochezza","poderoso","podismo","poesia","poggiare","polenta","poligono","pollice","polmonite","polpetta","polso","poltrona","polvere","pomice","pomodoro","ponte","popoloso","porfido","poroso","porpora","porre","portata","posa","positivo","possesso","postulato","potassio","potere","pranzo","prassi","pratica","precluso","predica","prefisso","pregiato","prelievo","premere","prenotare","preparato","presenza","pretesto","prevalso","prima","principe","privato","problema","procura","produrre","profumo","progetto","prolunga","promessa","pronome","proposta","proroga","proteso","prova","prudente","prugna","prurito","psiche","pubblico","pudica","pugilato","pugno","pulce","pulito","pulsante","puntare","pupazzo","pupilla","puro","quadro","qualcosa","quasi","querela","quota","raccolto","raddoppio","radicale","radunato","raffica","ragazzo","ragione","ragno","ramarro","ramingo","ramo","randagio","rantolare","rapato","rapina","rappreso","rasatura","raschiato","rasente","rassegna","rastrello","rata","ravveduto","reale","recepire","recinto","recluta","recondito","recupero","reddito","redimere","regalato","registro","regola","regresso","relazione","remare","remoto","renna","replica","reprimere","reputare","resa","residente","responso","restauro","rete","retina","retorica","rettifica","revocato","riassunto","ribadire","ribelle","ribrezzo","ricarica","ricco","ricevere","riciclato","ricordo","ricreduto","ridicolo","ridurre","rifasare","riflesso","riforma","rifugio","rigare","rigettato","righello","rilassato","rilevato","rimanere","rimbalzo","rimedio","rimorchio","rinascita","rincaro","rinforzo","rinnovo","rinomato","rinsavito","rintocco","rinuncia","rinvenire","riparato","ripetuto","ripieno","riportare","ripresa","ripulire","risata","rischio","riserva","risibile","riso","rispetto","ristoro","risultato","risvolto","ritardo","ritegno","ritmico","ritrovo","riunione","riva","riverso","rivincita","rivolto","rizoma","roba","robotico","robusto","roccia","roco","rodaggio","rodere","roditore","rogito","rollio","romantico","rompere","ronzio","rosolare","rospo","rotante","rotondo","rotula","rovescio","rubizzo","rubrica","ruga","rullino","rumine","rumoroso","ruolo","rupe","russare","rustico","sabato","sabbiare","sabotato","sagoma","salasso","saldatura","salgemma","salivare","salmone","salone","saltare","saluto","salvo","sapere","sapido","saporito","saraceno","sarcasmo","sarto","sassoso","satellite","satira","satollo","saturno","savana","savio","saziato","sbadiglio","sbalzo","sbancato","sbarra","sbattere","sbavare","sbendare","sbirciare","sbloccato","sbocciato","sbrinare","sbruffone","sbuffare","scabroso","scadenza","scala","scambiare","scandalo","scapola","scarso","scatenare","scavato","scelto","scenico","scettro","scheda","schiena","sciarpa","scienza","scindere","scippo","sciroppo","scivolo","sclerare","scodella","scolpito","scomparto","sconforto","scoprire","scorta","scossone","scozzese","scriba","scrollare","scrutinio","scuderia","scultore","scuola","scuro","scusare","sdebitare","sdoganare","seccatura","secondo","sedano","seggiola","segnalato","segregato","seguito","selciato","selettivo","sella","selvaggio","semaforo","sembrare","seme","seminato","sempre","senso","sentire","sepolto","sequenza","serata","serbato","sereno","serio","serpente","serraglio","servire","sestina","setola","settimana","sfacelo","sfaldare","sfamato","sfarzoso","sfaticato","sfera","sfida","sfilato","sfinge","sfocato","sfoderare","sfogo","sfoltire","sforzato","sfratto","sfruttato","sfuggito","sfumare","sfuso","sgabello","sgarbato","sgonfiare","sgorbio","sgrassato","sguardo","sibilo","siccome","sierra","sigla","signore","silenzio","sillaba","simbolo","simpatico","simulato","sinfonia","singolo","sinistro","sino","sintesi","sinusoide","sipario","sisma","sistole","situato","slitta","slogatura","sloveno","smarrito","smemorato","smentito","smeraldo","smilzo","smontare","smottato","smussato","snellire","snervato","snodo","sobbalzo","sobrio","soccorso","sociale","sodale","soffitto","sogno","soldato","solenne","solido","sollazzo","solo","solubile","solvente","somatico","somma","sonda","sonetto","sonnifero","sopire","soppeso","sopra","sorgere","sorpasso","sorriso","sorso","sorteggio","sorvolato","sospiro","sosta","sottile","spada","spalla","spargere","spatola","spavento","spazzola","specie","spedire","spegnere","spelatura","speranza","spessore","spettrale","spezzato","spia","spigoloso","spillato","spinoso","spirale","splendido","sportivo","sposo","spranga","sprecare","spronato","spruzzo","spuntino","squillo","sradicare","srotolato","stabile","stacco","staffa","stagnare","stampato","stantio","starnuto","stasera","statuto","stelo","steppa","sterzo","stiletto","stima","stirpe","stivale","stizzoso","stonato","storico","strappo","stregato","stridulo","strozzare","strutto","stuccare","stufo","stupendo","subentro","succoso","sudore","suggerito","sugo","sultano","suonare","superbo","supporto","surgelato","surrogato","sussurro","sutura","svagare","svedese","sveglio","svelare","svenuto","svezia","sviluppo","svista","svizzera","svolta","svuotare","tabacco","tabulato","tacciare","taciturno","tale","talismano","tampone","tannino","tara","tardivo","targato","tariffa","tarpare","tartaruga","tasto","tattico","taverna","tavolata","tazza","teca","tecnico","telefono","temerario","tempo","temuto","tendone","tenero","tensione","tentacolo","teorema","terme","terrazzo","terzetto","tesi","tesserato","testato","tetro","tettoia","tifare","tigella","timbro","tinto","tipico","tipografo","tiraggio","tiro","titanio","titolo","titubante","tizio","tizzone","toccare","tollerare","tolto","tombola","tomo","tonfo","tonsilla","topazio","topologia","toppa","torba","tornare","torrone","tortora","toscano","tossire","tostatura","totano","trabocco","trachea","trafila","tragedia","tralcio","tramonto","transito","trapano","trarre","trasloco","trattato","trave","treccia","tremolio","trespolo","tributo","tricheco","trifoglio","trillo","trincea","trio","tristezza","triturato","trivella","tromba","trono","troppo","trottola","trovare","truccato","tubatura","tuffato","tulipano","tumulto","tunisia","turbare","turchino","tuta","tutela","ubicato","uccello","uccisore","udire","uditivo","uffa","ufficio","uguale","ulisse","ultimato","umano","umile","umorismo","uncinetto","ungere","ungherese","unicorno","unificato","unisono","unitario","unte","uovo","upupa","uragano","urgenza","urlo","usanza","usato","uscito","usignolo","usuraio","utensile","utilizzo","utopia","vacante","vaccinato","vagabondo","vagliato","valanga","valgo","valico","valletta","valoroso","valutare","valvola","vampata","vangare","vanitoso","vano","vantaggio","vanvera","vapore","varano","varcato","variante","vasca","vedetta","vedova","veduto","vegetale","veicolo","velcro","velina","velluto","veloce","venato","vendemmia","vento","verace","verbale","vergogna","verifica","vero","verruca","verticale","vescica","vessillo","vestale","veterano","vetrina","vetusto","viandante","vibrante","vicenda","vichingo","vicinanza","vidimare","vigilia","vigneto","vigore","vile","villano","vimini","vincitore","viola","vipera","virgola","virologo","virulento","viscoso","visione","vispo","vissuto","visura","vita","vitello","vittima","vivanda","vivido","viziare","voce","voga","volatile","volere","volpe","voragine","vulcano","zampogna","zanna","zappato","zattera","zavorra","zefiro","zelante","zelo","zenzero","zerbino","zibetto","zinco","zircone","zitto","zolla","zotico","zucchero","zufolo","zulu","zuppa"]["あいこくしん","あいさつ","あいだ","あおぞら","あかちゃん","あきる","あけがた","あける","あこがれる","あさい","あさひ","あしあと","あじわう","あずかる","あずき","あそぶ","あたえる","あたためる","あたりまえ","あたる","あつい","あつかう","あっしゅく","あつまり","あつめる","あてな","あてはまる","あひる","あぶら","あぶる","あふれる","あまい","あまど","あまやかす","あまり","あみもの","あめりか","あやまる","あゆむ","あらいぐま","あらし","あらすじ","あらためる","あらゆる","あらわす","ありがとう","あわせる","あわてる","あんい","あんがい","あんこ","あんぜん","あんてい","あんない","あんまり","いいだす","いおん","いがい","いがく","いきおい","いきなり","いきもの","いきる","いくじ","いくぶん","いけばな","いけん","いこう","いこく","いこつ","いさましい","いさん","いしき","いじゅう","いじょう","いじわる","いずみ","いずれ","いせい","いせえび","いせかい","いせき","いぜん","いそうろう","いそがしい","いだい","いだく","いたずら","いたみ","いたりあ","いちおう","いちじ","いちど","いちば","いちぶ","いちりゅう","いつか","いっしゅん","いっせい","いっそう","いったん","いっち","いってい","いっぽう","いてざ","いてん","いどう","いとこ","いない","いなか","いねむり","いのち","いのる","いはつ","いばる","いはん","いびき","いひん","いふく","いへん","いほう","いみん","いもうと","いもたれ","いもり","いやがる","いやす","いよかん","いよく","いらい","いらすと","いりぐち","いりょう","いれい","いれもの","いれる","いろえんぴつ","いわい","いわう","いわかん","いわば","いわゆる","いんげんまめ","いんさつ","いんしょう","いんよう","うえき","うえる","うおざ","うがい","うかぶ","うかべる","うきわ","うくらいな","うくれれ","うけたまわる","うけつけ","うけとる","うけもつ","うける","うごかす","うごく","うこん","うさぎ","うしなう","うしろがみ","うすい","うすぎ","うすぐらい","うすめる","うせつ","うちあわせ","うちがわ","うちき","うちゅう","うっかり","うつくしい","うったえる","うつる","うどん","うなぎ","うなじ","うなずく","うなる","うねる","うのう","うぶげ","うぶごえ","うまれる","うめる","うもう","うやまう","うよく","うらがえす","うらぐち","うらない","うりあげ","うりきれ","うるさい","うれしい","うれゆき","うれる","うろこ","うわき","うわさ","うんこう","うんちん","うんてん","うんどう","えいえん","えいが","えいきょう","えいご","えいせい","えいぶん","えいよう","えいわ","えおり","えがお","えがく","えきたい","えくせる","えしゃく","えすて","えつらん","えのぐ","えほうまき","えほん","えまき","えもじ","えもの","えらい","えらぶ","えりあ","えんえん","えんかい","えんぎ","えんげき","えんしゅう","えんぜつ","えんそく","えんちょう","えんとつ","おいかける","おいこす","おいしい","おいつく","おうえん","おうさま","おうじ","おうせつ","おうたい","おうふく","おうべい","おうよう","おえる","おおい","おおう","おおどおり","おおや","おおよそ","おかえり","おかず","おがむ","おかわり","おぎなう","おきる","おくさま","おくじょう","おくりがな","おくる","おくれる","おこす","おこなう","おこる","おさえる","おさない","おさめる","おしいれ","おしえる","おじぎ","おじさん","おしゃれ","おそらく","おそわる","おたがい","おたく","おだやか","おちつく","おっと","おつり","おでかけ","おとしもの","おとなしい","おどり","おどろかす","おばさん","おまいり","おめでとう","おもいで","おもう","おもたい","おもちゃ","おやつ","おやゆび","およぼす","おらんだ","おろす","おんがく","おんけい","おんしゃ","おんせん","おんだん","おんちゅう","おんどけい","かあつ","かいが","がいき","がいけん","がいこう","かいさつ","かいしゃ","かいすいよく","かいぜん","かいぞうど","かいつう","かいてん","かいとう","かいふく","がいへき","かいほう","かいよう","がいらい","かいわ","かえる","かおり","かかえる","かがく","かがし","かがみ","かくご","かくとく","かざる","がぞう","かたい","かたち","がちょう","がっきゅう","がっこう","がっさん","がっしょう","かなざわし","かのう","がはく","かぶか","かほう","かほご","かまう","かまぼこ","かめれおん","かゆい","かようび","からい","かるい","かろう","かわく","かわら","がんか","かんけい","かんこう","かんしゃ","かんそう","かんたん","かんち","がんばる","きあい","きあつ","きいろ","ぎいん","きうい","きうん","きえる","きおう","きおく","きおち","きおん","きかい","きかく","きかんしゃ","ききて","きくばり","きくらげ","きけんせい","きこう","きこえる","きこく","きさい","きさく","きさま","きさらぎ","ぎじかがく","ぎしき","ぎじたいけん","ぎじにってい","ぎじゅつしゃ","きすう","きせい","きせき","きせつ","きそう","きぞく","きぞん","きたえる","きちょう","きつえん","ぎっちり","きつつき","きつね","きてい","きどう","きどく","きない","きなが","きなこ","きぬごし","きねん","きのう","きのした","きはく","きびしい","きひん","きふく","きぶん","きぼう","きほん","きまる","きみつ","きむずかしい","きめる","きもだめし","きもち","きもの","きゃく","きやく","ぎゅうにく","きよう","きょうりゅう","きらい","きらく","きりん","きれい","きれつ","きろく","ぎろん","きわめる","ぎんいろ","きんかくじ","きんじょ","きんようび","ぐあい","くいず","くうかん","くうき","くうぐん","くうこう","ぐうせい","くうそう","ぐうたら","くうふく","くうぼ","くかん","くきょう","くげん","ぐこう","くさい","くさき","くさばな","くさる","くしゃみ","くしょう","くすのき","くすりゆび","くせげ","くせん","ぐたいてき","くださる","くたびれる","くちこみ","くちさき","くつした","ぐっすり","くつろぐ","くとうてん","くどく","くなん","くねくね","くのう","くふう","くみあわせ","くみたてる","くめる","くやくしょ","くらす","くらべる","くるま","くれる","くろう","くわしい","ぐんかん","ぐんしょく","ぐんたい","ぐんて","けあな","けいかく","けいけん","けいこ","けいさつ","げいじゅつ","けいたい","げいのうじん","けいれき","けいろ","けおとす","けおりもの","げきか","げきげん","げきだん","げきちん","げきとつ","げきは","げきやく","げこう","げこくじょう","げざい","けさき","げざん","けしき","けしごむ","けしょう","げすと","けたば","けちゃっぷ","けちらす","けつあつ","けつい","けつえき","けっこん","けつじょ","けっせき","けってい","けつまつ","げつようび","げつれい","けつろん","げどく","けとばす","けとる","けなげ","けなす","けなみ","けぬき","げねつ","けねん","けはい","げひん","けぶかい","げぼく","けまり","けみかる","けむし","けむり","けもの","けらい","けろけろ","けわしい","けんい","けんえつ","けんお","けんか","げんき","けんげん","けんこう","けんさく","けんしゅう","けんすう","げんそう","けんちく","けんてい","けんとう","けんない","けんにん","げんぶつ","けんま","けんみん","けんめい","けんらん","けんり","こあくま","こいぬ","こいびと","ごうい","こうえん","こうおん","こうかん","ごうきゅう","ごうけい","こうこう","こうさい","こうじ","こうすい","ごうせい","こうそく","こうたい","こうちゃ","こうつう","こうてい","こうどう","こうない","こうはい","ごうほう","ごうまん","こうもく","こうりつ","こえる","こおり","ごかい","ごがつ","ごかん","こくご","こくさい","こくとう","こくない","こくはく","こぐま","こけい","こける","ここのか","こころ","こさめ","こしつ","こすう","こせい","こせき","こぜん","こそだて","こたい","こたえる","こたつ","こちょう","こっか","こつこつ","こつばん","こつぶ","こてい","こてん","ことがら","ことし","ことば","ことり","こなごな","こねこね","このまま","このみ","このよ","ごはん","こひつじ","こふう","こふん","こぼれる","ごまあぶら","こまかい","ごますり","こまつな","こまる","こむぎこ","こもじ","こもち","こもの","こもん","こやく","こやま","こゆう","こゆび","こよい","こよう","こりる","これくしょん","ころっけ","こわもて","こわれる","こんいん","こんかい","こんき","こんしゅう","こんすい","こんだて","こんとん","こんなん","こんびに","こんぽん","こんまけ","こんや","こんれい","こんわく","ざいえき","さいかい","さいきん","ざいげん","ざいこ","さいしょ","さいせい","ざいたく","ざいちゅう","さいてき","ざいりょう","さうな","さかいし","さがす","さかな","さかみち","さがる","さぎょう","さくし","さくひん","さくら","さこく","さこつ","さずかる","ざせき","さたん","さつえい","ざつおん","ざっか","ざつがく","さっきょく","ざっし","さつじん","ざっそう","さつたば","さつまいも","さてい","さといも","さとう","さとおや","さとし","さとる","さのう","さばく","さびしい","さべつ","さほう","さほど","さます","さみしい","さみだれ","さむけ","さめる","さやえんどう","さゆう","さよう","さよく","さらだ","ざるそば","さわやか","さわる","さんいん","さんか","さんきゃく","さんこう","さんさい","ざんしょ","さんすう","さんせい","さんそ","さんち","さんま","さんみ","さんらん","しあい","しあげ","しあさって","しあわせ","しいく","しいん","しうち","しえい","しおけ","しかい","しかく","じかん","しごと","しすう","じだい","したうけ","したぎ","したて","したみ","しちょう","しちりん","しっかり","しつじ","しつもん","してい","してき","してつ","じてん","じどう","しなぎれ","しなもの","しなん","しねま","しねん","しのぐ","しのぶ","しはい","しばかり","しはつ","しはらい","しはん","しひょう","しふく","じぶん","しへい","しほう","しほん","しまう","しまる","しみん","しむける","じむしょ","しめい","しめる","しもん","しゃいん","しゃうん","しゃおん","じゃがいも","しやくしょ","しゃくほう","しゃけん","しゃこ","しゃざい","しゃしん","しゃせん","しゃそう","しゃたい","しゃちょう","しゃっきん","じゃま","しゃりん","しゃれい","じゆう","じゅうしょ","しゅくはく","じゅしん","しゅっせき","しゅみ","しゅらば","じゅんばん","しょうかい","しょくたく","しょっけん","しょどう","しょもつ","しらせる","しらべる","しんか","しんこう","じんじゃ","しんせいじ","しんちく","しんりん","すあげ","すあし","すあな","ずあん","すいえい","すいか","すいとう","ずいぶん","すいようび","すうがく","すうじつ","すうせん","すおどり","すきま","すくう","すくない","すける","すごい","すこし","ずさん","すずしい","すすむ","すすめる","すっかり","ずっしり","ずっと","すてき","すてる","すねる","すのこ","すはだ","すばらしい","ずひょう","ずぶぬれ","すぶり","すふれ","すべて","すべる","ずほう","すぼん","すまい","すめし","すもう","すやき","すらすら","するめ","すれちがう","すろっと","すわる","すんぜん","すんぽう","せあぶら","せいかつ","せいげん","せいじ","せいよう","せおう","せかいかん","せきにん","せきむ","せきゆ","せきらんうん","せけん","せこう","せすじ","せたい","せたけ","せっかく","せっきゃく","ぜっく","せっけん","せっこつ","せっさたくま","せつぞく","せつだん","せつでん","せっぱん","せつび","せつぶん","せつめい","せつりつ","せなか","せのび","せはば","せびろ","せぼね","せまい","せまる","せめる","せもたれ","せりふ","ぜんあく","せんい","せんえい","せんか","せんきょ","せんく","せんげん","ぜんご","せんさい","せんしゅ","せんすい","せんせい","せんぞ","せんたく","せんちょう","せんてい","せんとう","せんぬき","せんねん","せんぱい","ぜんぶ","ぜんぽう","せんむ","せんめんじょ","せんもん","せんやく","せんゆう","せんよう","ぜんら","ぜんりゃく","せんれい","せんろ","そあく","そいとげる","そいね","そうがんきょう","そうき","そうご","そうしん","そうだん","そうなん","そうび","そうめん","そうり","そえもの","そえん","そがい","そげき","そこう","そこそこ","そざい","そしな","そせい","そせん","そそぐ","そだてる","そつう","そつえん","そっかん","そつぎょう","そっけつ","そっこう","そっせん","そっと","そとがわ","そとづら","そなえる","そなた","そふぼ","そぼく","そぼろ","そまつ","そまる","そむく","そむりえ","そめる","そもそも","そよかぜ","そらまめ","そろう","そんかい","そんけい","そんざい","そんしつ","そんぞく","そんちょう","ぞんび","ぞんぶん","そんみん","たあい","たいいん","たいうん","たいえき","たいおう","だいがく","たいき","たいぐう","たいけん","たいこ","たいざい","だいじょうぶ","だいすき","たいせつ","たいそう","だいたい","たいちょう","たいてい","だいどころ","たいない","たいねつ","たいのう","たいはん","だいひょう","たいふう","たいへん","たいほ","たいまつばな","たいみんぐ","たいむ","たいめん","たいやき","たいよう","たいら","たいりょく","たいる","たいわん","たうえ","たえる","たおす","たおる","たおれる","たかい","たかね","たきび","たくさん","たこく","たこやき","たさい","たしざん","だじゃれ","たすける","たずさわる","たそがれ","たたかう","たたく","ただしい","たたみ","たちばな","だっかい","だっきゃく","だっこ","だっしゅつ","だったい","たてる","たとえる","たなばた","たにん","たぬき","たのしみ","たはつ","たぶん","たべる","たぼう","たまご","たまる","だむる","ためいき","ためす","ためる","たもつ","たやすい","たよる","たらす","たりきほんがん","たりょう","たりる","たると","たれる","たれんと","たろっと","たわむれる","だんあつ","たんい","たんおん","たんか","たんき","たんけん","たんご","たんさん","たんじょうび","だんせい","たんそく","たんたい","だんち","たんてい","たんとう","だんな","たんにん","だんねつ","たんのう","たんぴん","だんぼう","たんまつ","たんめい","だんれつ","だんろ","だんわ","ちあい","ちあん","ちいき","ちいさい","ちえん","ちかい","ちから","ちきゅう","ちきん","ちけいず","ちけん","ちこく","ちさい","ちしき","ちしりょう","ちせい","ちそう","ちたい","ちたん","ちちおや","ちつじょ","ちてき","ちてん","ちぬき","ちぬり","ちのう","ちひょう","ちへいせん","ちほう","ちまた","ちみつ","ちみどろ","ちめいど","ちゃんこなべ","ちゅうい","ちゆりょく","ちょうし","ちょさくけん","ちらし","ちらみ","ちりがみ","ちりょう","ちるど","ちわわ","ちんたい","ちんもく","ついか","ついたち","つうか","つうじょう","つうはん","つうわ","つかう","つかれる","つくね","つくる","つけね","つける","つごう","つたえる","つづく","つつじ","つつむ","つとめる","つながる","つなみ","つねづね","つのる","つぶす","つまらない","つまる","つみき","つめたい","つもり","つもる","つよい","つるぼ","つるみく","つわもの","つわり","てあし","てあて","てあみ","ていおん","ていか","ていき","ていけい","ていこく","ていさつ","ていし","ていせい","ていたい","ていど","ていねい","ていひょう","ていへん","ていぼう","てうち","ておくれ","てきとう","てくび","でこぼこ","てさぎょう","てさげ","てすり","てそう","てちがい","てちょう","てつがく","てつづき","でっぱ","てつぼう","てつや","でぬかえ","てぬき","てぬぐい","てのひら","てはい","てぶくろ","てふだ","てほどき","てほん","てまえ","てまきずし","てみじか","てみやげ","てらす","てれび","てわけ","てわたし","でんあつ","てんいん","てんかい","てんき","てんぐ","てんけん","てんごく","てんさい","てんし","てんすう","でんち","てんてき","てんとう","てんない","てんぷら","てんぼうだい","てんめつ","てんらんかい","でんりょく","でんわ","どあい","といれ","どうかん","とうきゅう","どうぐ","とうし","とうむぎ","とおい","とおか","とおく","とおす","とおる","とかい","とかす","ときおり","ときどき","とくい","とくしゅう","とくてん","とくに","とくべつ","とけい","とける","とこや","とさか","としょかん","とそう","とたん","とちゅう","とっきゅう","とっくん","とつぜん","とつにゅう","とどける","ととのえる","とない","となえる","となり","とのさま","とばす","どぶがわ","とほう","とまる","とめる","ともだち","ともる","どようび","とらえる","とんかつ","どんぶり","ないかく","ないこう","ないしょ","ないす","ないせん","ないそう","なおす","ながい","なくす","なげる","なこうど","なさけ","なたでここ","なっとう","なつやすみ","ななおし","なにごと","なにもの","なにわ","なのか","なふだ","なまいき","なまえ","なまみ","なみだ","なめらか","なめる","なやむ","ならう","ならび","ならぶ","なれる","なわとび","なわばり","にあう","にいがた","にうけ","におい","にかい","にがて","にきび","にくしみ","にくまん","にげる","にさんかたんそ","にしき","にせもの","にちじょう","にちようび","にっか","にっき","にっけい","にっこう","にっさん","にっしょく","にっすう","にっせき","にってい","になう","にほん","にまめ","にもつ","にやり","にゅういん","にりんしゃ","にわとり","にんい","にんか","にんき","にんげん","にんしき","にんずう","にんそう","にんたい","にんち","にんてい","にんにく","にんぷ","にんまり","にんむ","にんめい","にんよう","ぬいくぎ","ぬかす","ぬぐいとる","ぬぐう","ぬくもり","ぬすむ","ぬまえび","ぬめり","ぬらす","ぬんちゃく","ねあげ","ねいき","ねいる","ねいろ","ねぐせ","ねくたい","ねくら","ねこぜ","ねこむ","ねさげ","ねすごす","ねそべる","ねだん","ねつい","ねっしん","ねつぞう","ねったいぎょ","ねぶそく","ねふだ","ねぼう","ねほりはほり","ねまき","ねまわし","ねみみ","ねむい","ねむたい","ねもと","ねらう","ねわざ","ねんいり","ねんおし","ねんかん","ねんきん","ねんぐ","ねんざ","ねんし","ねんちゃく","ねんど","ねんぴ","ねんぶつ","ねんまつ","ねんりょう","ねんれい","のいず","のおづま","のがす","のきなみ","のこぎり","のこす","のこる","のせる","のぞく","のぞむ","のたまう","のちほど","のっく","のばす","のはら","のべる","のぼる","のみもの","のやま","のらいぬ","のらねこ","のりもの","のりゆき","のれん","のんき","ばあい","はあく","ばあさん","ばいか","ばいく","はいけん","はいご","はいしん","はいすい","はいせん","はいそう","はいち","ばいばい","はいれつ","はえる","はおる","はかい","ばかり","はかる","はくしゅ","はけん","はこぶ","はさみ","はさん","はしご","ばしょ","はしる","はせる","ぱそこん","はそん","はたん","はちみつ","はつおん","はっかく","はづき","はっきり","はっくつ","はっけん","はっこう","はっさん","はっしん","はったつ","はっちゅう","はってん","はっぴょう","はっぽう","はなす","はなび","はにかむ","はぶらし","はみがき","はむかう","はめつ","はやい","はやし","はらう","はろうぃん","はわい","はんい","はんえい","はんおん","はんかく","はんきょう","ばんぐみ","はんこ","はんしゃ","はんすう","はんだん","ぱんち","ぱんつ","はんてい","はんとし","はんのう","はんぱ","はんぶん","はんぺん","はんぼうき","はんめい","はんらん","はんろん","ひいき","ひうん","ひえる","ひかく","ひかり","ひかる","ひかん","ひくい","ひけつ","ひこうき","ひこく","ひさい","ひさしぶり","ひさん","びじゅつかん","ひしょ","ひそか","ひそむ","ひたむき","ひだり","ひたる","ひつぎ","ひっこし","ひっし","ひつじゅひん","ひっす","ひつぜん","ぴったり","ぴっちり","ひつよう","ひてい","ひとごみ","ひなまつり","ひなん","ひねる","ひはん","ひびく","ひひょう","ひほう","ひまわり","ひまん","ひみつ","ひめい","ひめじし","ひやけ","ひやす","ひよう","びょうき","ひらがな","ひらく","ひりつ","ひりょう","ひるま","ひるやすみ","ひれい","ひろい","ひろう","ひろき","ひろゆき","ひんかく","ひんけつ","ひんこん","ひんしゅ","ひんそう","ぴんち","ひんぱん","びんぼう","ふあん","ふいうち","ふうけい","ふうせん","ぷうたろう","ふうとう","ふうふ","ふえる","ふおん","ふかい","ふきん","ふくざつ","ふくぶくろ","ふこう","ふさい","ふしぎ","ふじみ","ふすま","ふせい","ふせぐ","ふそく","ぶたにく","ふたん","ふちょう","ふつう","ふつか","ふっかつ","ふっき","ふっこく","ぶどう","ふとる","ふとん","ふのう","ふはい","ふひょう","ふへん","ふまん","ふみん","ふめつ","ふめん","ふよう","ふりこ","ふりる","ふるい","ふんいき","ぶんがく","ぶんぐ","ふんしつ","ぶんせき","ふんそう","ぶんぽう","へいあん","へいおん","へいがい","へいき","へいげん","へいこう","へいさ","へいしゃ","へいせつ","へいそ","へいたく","へいてん","へいねつ","へいわ","へきが","へこむ","べにいろ","べにしょうが","へらす","へんかん","べんきょう","べんごし","へんさい","へんたい","べんり","ほあん","ほいく","ぼうぎょ","ほうこく","ほうそう","ほうほう","ほうもん","ほうりつ","ほえる","ほおん","ほかん","ほきょう","ぼきん","ほくろ","ほけつ","ほけん","ほこう","ほこる","ほしい","ほしつ","ほしゅ","ほしょう","ほせい","ほそい","ほそく","ほたて","ほたる","ぽちぶくろ","ほっきょく","ほっさ","ほったん","ほとんど","ほめる","ほんい","ほんき","ほんけ","ほんしつ","ほんやく","まいにち","まかい","まかせる","まがる","まける","まこと","まさつ","まじめ","ますく","まぜる","まつり","まとめ","まなぶ","まぬけ","まねく","まほう","まもる","まゆげ","まよう","まろやか","まわす","まわり","まわる","まんが","まんきつ","まんぞく","まんなか","みいら","みうち","みえる","みがく","みかた","みかん","みけん","みこん","みじかい","みすい","みすえる","みせる","みっか","みつかる","みつける","みてい","みとめる","みなと","みなみかさい","みねらる","みのう","みのがす","みほん","みもと","みやげ","みらい","みりょく","みわく","みんか","みんぞく","むいか","むえき","むえん","むかい","むかう","むかえ","むかし","むぎちゃ","むける","むげん","むさぼる","むしあつい","むしば","むじゅん","むしろ","むすう","むすこ","むすぶ","むすめ","むせる","むせん","むちゅう","むなしい","むのう","むやみ","むよう","むらさき","むりょう","むろん","めいあん","めいうん","めいえん","めいかく","めいきょく","めいさい","めいし","めいそう","めいぶつ","めいれい","めいわく","めぐまれる","めざす","めした","めずらしい","めだつ","めまい","めやす","めんきょ","めんせき","めんどう","もうしあげる","もうどうけん","もえる","もくし","もくてき","もくようび","もちろん","もどる","もらう","もんく","もんだい","やおや","やける","やさい","やさしい","やすい","やすたろう","やすみ","やせる","やそう","やたい","やちん","やっと","やっぱり","やぶる","やめる","ややこしい","やよい","やわらかい","ゆうき","ゆうびんきょく","ゆうべ","ゆうめい","ゆけつ","ゆしゅつ","ゆせん","ゆそう","ゆたか","ゆちゃく","ゆでる","ゆにゅう","ゆびわ","ゆらい","ゆれる","ようい","ようか","ようきゅう","ようじ","ようす","ようちえん","よかぜ","よかん","よきん","よくせい","よくぼう","よけい","よごれる","よさん","よしゅう","よそう","よそく","よっか","よてい","よどがわく","よねつ","よやく","よゆう","よろこぶ","よろしい","らいう","らくがき","らくご","らくさつ","らくだ","らしんばん","らせん","らぞく","らたい","らっか","られつ","りえき","りかい","りきさく","りきせつ","りくぐん","りくつ","りけん","りこう","りせい","りそう","りそく","りてん","りねん","りゆう","りゅうがく","りよう","りょうり","りょかん","りょくちゃ","りょこう","りりく","りれき","りろん","りんご","るいけい","るいさい","るいじ","るいせき","るすばん","るりがわら","れいかん","れいぎ","れいせい","れいぞうこ","れいとう","れいぼう","れきし","れきだい","れんあい","れんけい","れんこん","れんさい","れんしゅう","れんぞく","れんらく","ろうか","ろうご","ろうじん","ろうそく","ろくが","ろこつ","ろじうら","ろしゅつ","ろせん","ろてん","ろめん","ろれつ","ろんぎ","ろんぱ","ろんぶん","ろんり","わかす","わかめ","わかやま","わかれる","わしつ","わじまし","わすれもの","わらう","われる"]["가격","가끔","가난","가능","가득","가르침","가뭄","가방","가상","가슴","가운데","가을","가이드","가입","가장","가정","가족","가죽","각오","각자","간격","간부","간섭","간장","간접","간판","갈등","갈비","갈색","갈증","감각","감기","감소","감수성","감자","감정","갑자기","강남","강당","강도","강력히","강변","강북","강사","강수량","강아지","강원도","강의","강제","강조","같이","개구리","개나리","개방","개별","개선","개성","개인","객관적","거실","거액","거울","거짓","거품","걱정","건강","건물","건설","건조","건축","걸음","검사","검토","게시판","게임","겨울","견해","결과","결국","결론","결석","결승","결심","결정","결혼","경계","경고","경기","경력","경복궁","경비","경상도","경영","경우","경쟁","경제","경주","경찰","경치","경향","경험","계곡","계단","계란","계산","계속","계약","계절","계층","계획","고객","고구려","고궁","고급","고등학생","고무신","고민","고양이","고장","고전","고집","고춧가루","고통","고향","곡식","골목","골짜기","골프","공간","공개","공격","공군","공급","공기","공동","공무원","공부","공사","공식","공업","공연","공원","공장","공짜","공책","공통","공포","공항","공휴일","과목","과일","과장","과정","과학","관객","관계","관광","관념","관람","관련","관리","관습","관심","관점","관찰","광경","광고","광장","광주","괴로움","굉장히","교과서","교문","교복","교실","교양","교육","교장","교직","교통","교환","교훈","구경","구름","구멍","구별","구분","구석","구성","구속","구역","구입","구청","구체적","국가","국기","국내","국립","국물","국민","국수","국어","국왕","국적","국제","국회","군대","군사","군인","궁극적","권리","권위","권투","귀국","귀신","규정","규칙","균형","그날","그냥","그늘","그러나","그룹","그릇","그림","그제서야","그토록","극복","극히","근거","근교","근래","근로","근무","근본","근원","근육","근처","글씨","글자","금강산","금고","금년","금메달","금액","금연","금요일","금지","긍정적","기간","기관","기념","기능","기독교","기둥","기록","기름","기법","기본","기분","기쁨","기숙사","기술","기억","기업","기온","기운","기원","기적","기준","기침","기혼","기획","긴급","긴장","길이","김밥","김치","김포공항","깍두기","깜빡","깨달음","깨소금","껍질","꼭대기","꽃잎","나들이","나란히","나머지","나물","나침반","나흘","낙엽","난방","날개","날씨","날짜","남녀","남대문","남매","남산","남자","남편","남학생","낭비","낱말","내년","내용","내일","냄비","냄새","냇물","냉동","냉면","냉방","냉장고","넥타이","넷째","노동","노란색","노력","노인","녹음","녹차","녹화","논리","논문","논쟁","놀이","농구","농담","농민","농부","농업","농장","농촌","높이","눈동자","눈물","눈썹","뉴욕","느낌","늑대","능동적","능력","다방","다양성","다음","다이어트","다행","단계","단골","단독","단맛","단순","단어","단위","단점","단체","단추","단편","단풍","달걀","달러","달력","달리","닭고기","담당","담배","담요","담임","답변","답장","당근","당분간","당연히","당장","대규모","대낮","대단히","대답","대도시","대략","대량","대륙","대문","대부분","대신","대응","대장","대전","대접","대중","대책","대출","대충","대통령","대학","대한민국","대합실","대형","덩어리","데이트","도대체","도덕","도둑","도망","도서관","도심","도움","도입","도자기","도저히","도전","도중","도착","독감","독립","독서","독일","독창적","동화책","뒷모습","뒷산","딸아이","마누라","마늘","마당","마라톤","마련","마무리","마사지","마약","마요네즈","마을","마음","마이크","마중","마지막","마찬가지","마찰","마흔","막걸리","막내","막상","만남","만두","만세","만약","만일","만점","만족","만화","많이","말기","말씀","말투","맘대로","망원경","매년","매달","매력","매번","매스컴","매일","매장","맥주","먹이","먼저","먼지","멀리","메일","며느리","며칠","면담","멸치","명단","명령","명예","명의","명절","명칭","명함","모금","모니터","모델","모든","모범","모습","모양","모임","모조리","모집","모퉁이","목걸이","목록","목사","목소리","목숨","목적","목표","몰래","몸매","몸무게","몸살","몸속","몸짓","몸통","몹시","무관심","무궁화","무더위","무덤","무릎","무슨","무엇","무역","무용","무조건","무지개","무척","문구","문득","문법","문서","문제","문학","문화","물가","물건","물결","물고기","물론","물리학","물음","물질","물체","미국","미디어","미사일","미술","미역","미용실","미움","미인","미팅","미혼","민간","민족","민주","믿음","밀가루","밀리미터","밑바닥","바가지","바구니","바나나","바늘","바닥","바닷가","바람","바이러스","바탕","박물관","박사","박수","반대","반드시","반말","반발","반성","반응","반장","반죽","반지","반찬","받침","발가락","발걸음","발견","발달","발레","발목","발바닥","발생","발음","발자국","발전","발톱","발표","밤하늘","밥그릇","밥맛","밥상","밥솥","방금","방면","방문","방바닥","방법","방송","방식","방안","방울","방지","방학","방해","방향","배경","배꼽","배달","배드민턴","백두산","백색","백성","백인","백제","백화점","버릇","버섯","버튼","번개","번역","번지","번호","벌금","벌레","벌써","범위","범인","범죄","법률","법원","법적","법칙","베이징","벨트","변경","변동","변명","변신","변호사","변화","별도","별명","별일","병실","병아리","병원","보관","보너스","보라색","보람","보름","보상","보안","보자기","보장","보전","보존","보통","보편적","보험","복도","복사","복숭아","복습","볶음","본격적","본래","본부","본사","본성","본인","본질","볼펜","봉사","봉지","봉투","부근","부끄러움","부담","부동산","부문","부분","부산","부상","부엌","부인","부작용","부장","부정","부족","부지런히","부친","부탁","부품","부회장","북부","북한","분노","분량","분리","분명","분석","분야","분위기","분필","분홍색","불고기","불과","불교","불꽃","불만","불법","불빛","불안","불이익","불행","브랜드","비극","비난","비닐","비둘기","비디오","비로소","비만","비명","비밀","비바람","비빔밥","비상","비용","비율","비중","비타민","비판","빌딩","빗물","빗방울","빗줄기","빛깔","빨간색","빨래","빨리","사건","사계절","사나이","사냥","사람","사랑","사립","사모님","사물","사방","사상","사생활","사설","사슴","사실","사업","사용","사월","사장","사전","사진","사촌","사춘기","사탕","사투리","사흘","산길","산부인과","산업","산책","살림","살인","살짝","삼계탕","삼국","삼십","삼월","삼촌","상관","상금","상대","상류","상반기","상상","상식","상업","상인","상자","상점","상처","상추","상태","상표","상품","상황","새벽","색깔","색연필","생각","생명","생물","생방송","생산","생선","생신","생일","생활","서랍","서른","서명","서민","서비스","서양","서울","서적","서점","서쪽","서클","석사","석유","선거","선물","선배","선생","선수","선원","선장","선전","선택","선풍기","설거지","설날","설렁탕","설명","설문","설사","설악산","설치","설탕","섭씨","성공","성당","성명","성별","성인","성장","성적","성질","성함","세금","세미나","세상","세월","세종대왕","세탁","센터","센티미터","셋째","소규모","소극적","소금","소나기","소년","소득","소망","소문","소설","소속","소아과","소용","소원","소음","소중히","소지품","소질","소풍","소형","속담","속도","속옷","손가락","손길","손녀","손님","손등","손목","손뼉","손실","손질","손톱","손해","솔직히","솜씨","송아지","송이","송편","쇠고기","쇼핑","수건","수년","수단","수돗물","수동적","수면","수명","수박","수상","수석","수술","수시로","수업","수염","수영","수입","수준","수집","수출","수컷","수필","수학","수험생","수화기","숙녀","숙소","숙제","순간","순서","순수","순식간","순위","숟가락","술병","술집","숫자","스님","스물","스스로","스승","스웨터","스위치","스케이트","스튜디오","스트레스","스포츠","슬쩍","슬픔","습관","습기","승객","승리","승부","승용차","승진","시각","시간","시골","시금치","시나리오","시댁","시리즈","시멘트","시민","시부모","시선","시설","시스템","시아버지","시어머니","시월","시인","시일","시작","시장","시절","시점","시중","시즌","시집","시청","시합","시험","식구","식기","식당","식량","식료품","식물","식빵","식사","식생활","식초","식탁","식품","신고","신규","신념","신문","신발","신비","신사","신세","신용","신제품","신청","신체","신화","실감","실내","실력","실례","실망","실수","실습","실시","실장","실정","실질적","실천","실체","실컷","실태","실패","실험","실현","심리","심부름","심사","심장","심정","심판","쌍둥이","씨름","씨앗","아가씨","아나운서","아드님","아들","아쉬움","아스팔트","아시아","아울러","아저씨","아줌마","아직","아침","아파트","아프리카","아픔","아홉","아흔","악기","악몽","악수","안개","안경","안과","안내","안녕","안동","안방","안부","안주","알루미늄","알코올","암시","암컷","압력","앞날","앞문","애인","애정","액수","앨범","야간","야단","야옹","약간","약국","약속","약수","약점","약품","약혼녀","양념","양력","양말","양배추","양주","양파","어둠","어려움","어른","어젯밤","어쨌든","어쩌다가","어쩐지","언니","언덕","언론","언어","얼굴","얼른","얼음","얼핏","엄마","업무","업종","업체","엉덩이","엉망","엉터리","엊그제","에너지","에어컨","엔진","여건","여고생","여관","여군","여권","여대생","여덟","여동생","여든","여론","여름","여섯","여성","여왕","여인","여전히","여직원","여학생","여행","역사","역시","역할","연결","연구","연극","연기","연락","연설","연세","연속","연습","연애","연예인","연인","연장","연주","연출","연필","연합","연휴","열기","열매","열쇠","열심히","열정","열차","열흘","염려","엽서","영국","영남","영상","영양","영역","영웅","영원히","영하","영향","영혼","영화","옆구리","옆방","옆집","예감","예금","예방","예산","예상","예선","예술","예습","예식장","예약","예전","예절","예정","예컨대","옛날","오늘","오락","오랫동안","오렌지","오로지","오른발","오븐","오십","오염","오월","오전","오직","오징어","오페라","오피스텔","오히려","옥상","옥수수","온갖","온라인","온몸","온종일","온통","올가을","올림픽","올해","옷차림","와이셔츠","와인","완성","완전","왕비","왕자","왜냐하면","왠지","외갓집","외국","외로움","외삼촌","외출","외침","외할머니","왼발","왼손","왼쪽","요금","요일","요즘","요청","용기","용서","용어","우산","우선","우승","우연히","우정","우체국","우편","운동","운명","운반","운전","운행","울산","울음","움직임","웃어른","웃음","워낙","원고","원래","원서","원숭이","원인","원장","원피스","월급","월드컵","월세","월요일","웨이터","위반","위법","위성","위원","위험","위협","윗사람","유난히","유럽","유명","유물","유산","유적","유치원","유학","유행","유형","육군","육상","육십","육체","은행","음력","음료","음반","음성","음식","음악","음주","의견","의논","의문","의복","의식","의심","의외로","의욕","의원","의학","이것","이곳","이념","이놈","이달","이대로","이동","이렇게","이력서","이론적","이름","이민","이발소","이별","이불","이빨","이상","이성","이슬","이야기","이용","이웃","이월","이윽고","이익","이전","이중","이튿날","이틀","이혼","인간","인격","인공","인구","인근","인기","인도","인류","인물","인생","인쇄","인연","인원","인재","인종","인천","인체","인터넷","인하","인형","일곱","일기","일단","일대","일등","일반","일본","일부","일상","일생","일손","일요일","일월","일정","일종","일주일","일찍","일체","일치","일행","일회용","임금","임무","입대","입력","입맛","입사","입술","입시","입원","입장","입학","자가용","자격","자극","자동","자랑","자부심","자식","자신","자연","자원","자율","자전거","자정","자존심","자판","작가","작년","작성","작업","작용","작은딸","작품","잔디","잔뜩","잔치","잘못","잠깐","잠수함","잠시","잠옷","잠자리","잡지","장관","장군","장기간","장래","장례","장르","장마","장면","장모","장미","장비","장사","장소","장식","장애인","장인","장점","장차","장학금","재능","재빨리","재산","재생","재작년","재정","재채기","재판","재학","재활용","저것","저고리","저곳","저녁","저런","저렇게","저번","저울","저절로","저축","적극","적당히","적성","적용","적응","전개","전공","전기","전달","전라도","전망","전문","전반","전부","전세","전시","전용","전자","전쟁","전주","전철","전체","전통","전혀","전후","절대","절망","절반","절약","절차","점검","점수","점심","점원","점점","점차","접근","접시","접촉","젓가락","정거장","정도","정류장","정리","정말","정면","정문","정반대","정보","정부","정비","정상","정성","정오","정원","정장","정지","정치","정확히","제공","제과점","제대로","제목","제발","제법","제삿날","제안","제일","제작","제주도","제출","제품","제한","조각","조건","조금","조깅","조명","조미료","조상","조선","조용히","조절","조정","조직","존댓말","존재","졸업","졸음","종교","종로","종류","종소리","종업원","종종","종합","좌석","죄인","주관적","주름","주말","주머니","주먹","주문","주민","주방","주변","주식","주인","주일","주장","주전자","주택","준비","줄거리","줄기","줄무늬","중간","중계방송","중국","중년","중단","중독","중반","중부","중세","중소기업","중순","중앙","중요","중학교","즉석","즉시","즐거움","증가","증거","증권","증상","증세","지각","지갑","지경","지극히","지금","지급","지능","지름길","지리산","지방","지붕","지식","지역","지우개","지원","지적","지점","지진","지출","직선","직업","직원","직장","진급","진동","진로","진료","진리","진짜","진찰","진출","진통","진행","질문","질병","질서","짐작","집단","집안","집중","짜증","찌꺼기","차남","차라리","차량","차림","차별","차선","차츰","착각","찬물","찬성","참가","참기름","참새","참석","참여","참외","참조","찻잔","창가","창고","창구","창문","창밖","창작","창조","채널","채점","책가방","책방","책상","책임","챔피언","처벌","처음","천국","천둥","천장","천재","천천히","철도","철저히","철학","첫날","첫째","청년","청바지","청소","청춘","체계","체력","체온","체육","체중","체험","초등학생","초반","초밥","초상화","초순","초여름","초원","초저녁","초점","초청","초콜릿","촛불","총각","총리","총장","촬영","최근","최상","최선","최신","최악","최종","추석","추억","추진","추천","추측","축구","축소","축제","축하","출근","출발","출산","출신","출연","출입","출장","출판","충격","충고","충돌","충분히","충청도","취업","취직","취향","치약","친구","친척","칠십","칠월","칠판","침대","침묵","침실","칫솔","칭찬","카메라","카운터","칼국수","캐릭터","캠퍼스","캠페인","커튼","컨디션","컬러","컴퓨터","코끼리","코미디","콘서트","콜라","콤플렉스","콩나물","쾌감","쿠데타","크림","큰길","큰딸","큰소리","큰아들","큰어머니","큰일","큰절","클래식","클럽","킬로","타입","타자기","탁구","탁자","탄생","태권도","태양","태풍","택시","탤런트","터널","터미널","테니스","테스트","테이블","텔레비전","토론","토마토","토요일","통계","통과","통로","통신","통역","통일","통장","통제","통증","통합","통화","퇴근","퇴원","퇴직금","튀김","트럭","특급","특별","특성","특수","특징","특히","튼튼히","티셔츠","파란색","파일","파출소","판결","판단","판매","판사","팔십","팔월","팝송","패션","팩스","팩시밀리","팬티","퍼센트","페인트","편견","편의","편지","편히","평가","평균","평생","평소","평양","평일","평화","포스터","포인트","포장","포함","표면","표정","표준","표현","품목","품질","풍경","풍속","풍습","프랑스","프린터","플라스틱","피곤","피망","피아노","필름","필수","필요","필자","필통","핑계","하느님","하늘","하드웨어","하룻밤","하반기","하숙집","하순","하여튼","하지만","하천","하품","하필","학과","학교","학급","학기","학년","학력","학번","학부모","학비","학생","학술","학습","학용품","학원","학위","학자","학점","한계","한글","한꺼번에","한낮","한눈","한동안","한때","한라산","한마디","한문","한번","한복","한식","한여름","한쪽","할머니","할아버지","할인","함께","함부로","합격","합리적","항공","항구","항상","항의","해결","해군","해답","해당","해물","해석","해설","해수욕장","해안","핵심","핸드백","햄버거","햇볕","햇살","행동","행복","행사","행운","행위","향기","향상","향수","허락","허용","헬기","현관","현금","현대","현상","현실","현장","현재","현지","혈액","협력","형부","형사","형수","형식","형제","형태","형편","혜택","호기심","호남","호랑이","호박","호텔","호흡","혹시","홀로","홈페이지","홍보","홍수","홍차","화면","화분","화살","화요일","화장","화학","확보","확인","확장","확정","환갑","환경","환영","환율","환자","활기","활동","활발히","활용","활짝","회견","회관","회복","회색","회원","회장","회전","횟수","횡단보도","효율적","후반","후춧가루","훈련","훨씬","휴식","휴일","흉내","흐름","흑백","흑인","흔적","흔히","흥미","흥분","희곡","희망","희생","흰색","힘껏"]{"的":["chinese_simplified","chinese_traditional"],"一":["chinese_simplified","chinese_traditional"],"是":["chinese_simplified","chinese_traditional"],"在":["chinese_simplified","chinese_traditional"],"不":["chinese_simplified","chinese_traditional"],"了":["chinese_simplified","chinese_traditional"],"有":["chinese_simplified","chinese_traditional"],"和":["chinese_simplified","chinese_traditional"],"人":["chinese_simplified","chinese_traditional"],"这":["chinese_simplified"],"中":["chinese_simplified","chinese_traditional"],"大":["chinese_simplified","chinese_traditional"],"为":["chinese_simplified"],"上":["chinese_simplified","chinese_traditional"],"个":["chinese_simplified"],"国":["chinese_simplified"],"我":["chinese_simplified","chinese_traditional"],"以":["chinese_simplified","chinese_traditional"],"要":["chinese_simplified","chinese_traditional"],"他":["chinese_simplified","chinese_traditional"],"时":["chinese_simplified"],"来":["chinese_simplified"],"用":["chinese_simplified","chinese_traditional"],"们":["chinese_simplified"],"生":["chinese_simplified","chinese_traditional"],"到":["chinese_simplified","chinese_traditional"],"作":["chinese_simplified","chinese_traditional"],"地":["chinese_simplified","chinese_traditional"],"于":["chinese_simplified"],"出":["chinese_simplified","chinese_traditional"],"就":["chinese_simplified","chinese_traditional"],"分":["chinese_simplified","chinese_traditional"],"对":["chinese_simplified"],"成":["chinese_simplified","chinese_traditional"],"会":["chinese_simplified"],"可":["chinese_simplified","chinese_traditional"],"主":["chinese_simplified","chinese_traditional"],"发":["chinese_simplified"],"年":["chinese_simplified","chinese_traditional"],"动":["chinese_simplified"],"同":["chinese_simplified","chinese_traditional"],"工":["chinese_simplified","chinese_traditional"],"也":["chinese_simplified","chinese_traditional"],"能":["chinese_simplified","chinese_traditional"],"下":["chinese_simplified","chinese_traditional"],"过":["chinese_simplified"],"子":["chinese_simplified","chinese_traditional"],"说":["chinese_simplified"],"产":["chinese_simplified"],"种":["chinese_simplified"],"面":["chinese_simplified","chinese_traditional"],"而":["chinese_simplified","chinese_traditional"],"方":["chinese_simplified","chinese_traditional"],"后":["chinese_simplified"],"多":["chinese_simplified","chinese_traditional"],"定":["chinese_simplified","chinese_traditional"],"行":["chinese_simplified","chinese_traditional"],"学":["chinese_simplified"],"法":["chinese_simplified","chinese_traditional"],"所":["chinese_simplified","chinese_traditional"],"民":["chinese_simplified","chinese_traditional"],"得":["chinese_simplified","chinese_traditional"],"经":["chinese_simplified"],"十":["chinese_simplified","chinese_traditional"],"三":["chinese_simplified","chinese_traditional"],"之":["chinese_simplified","chinese_traditional"],"进":["chinese_simplified"],"着":["chinese_simplified"],"等":["chinese_simplified","chinese_traditional"],"部":["chinese_simplified","chinese_traditional"],"度":["chinese_simplified","chinese_traditional"],"家":["chinese_simplified","chinese_traditional"],"电":["chinese_simplified"],"力":["chinese_simplified","chinese_traditional"],"里":["chinese_simplified"],"如":["chinese_simplified","chinese_traditional"],"水":["chinese_simplified","chinese_traditional"],"化":["chinese_simplified","chinese_traditional"],"高":["chinese_simplified","chinese_traditional"],"自":["chinese_simplified","chinese_traditional"],"二":["chinese_simplified","chinese_traditional"],"理":["chinese_simplified","chinese_traditional"],"起":["chinese_simplified","chinese_traditional"],"小":["chinese_simplified","chinese_traditional"],"物":["chinese_simplified","chinese_traditional"],"现":["chinese_simplified"],"实":["chinese_simplified"],"加":["chinese_simplified","chinese_traditional"],"量":["chinese_simplified","chinese_traditional"],"都":["chinese_simplified","chinese_traditional"],"两":["chinese_simplified"],"体":["chinese_simplified"],"制":["chinese_simplified","chinese_traditional"],"机":["chinese_simplified"],"当":["chinese_simplified"],"使":["chinese_simplified","chinese_traditional"],"点":["chinese_simplified"],"从":["chinese_simplified"],"业":["chinese_simplified"],"本":["chinese_simplified","chinese_traditional"],"去":["chinese_simplified","chinese_traditional"],"把":["chinese_simplified","chinese_traditional"],"性":["chinese_simplified","chinese_traditional"],"好":["chinese_simplified","chinese_traditional"],"应":["chinese_simplified"],"开":["chinese_simplified"],"它":["chinese_simplified","chinese_traditional"],"合":["chinese_simplified","chinese_traditional"],"还":["chinese_simplified"],"因":["chinese_simplified","chinese_traditional"],"由":["chinese_simplified","chinese_traditional"],"其":["chinese_simplified","chinese_traditional"],"些":["chinese_simplified","chinese_traditional"],"然":["chinese_simplified","chinese_traditional"],"前":["chinese_simplified","chinese_traditional"],"外":["chinese_simplified","chinese_traditional"],"天":["chinese_simplified","chinese_traditional"],"政":["chinese_simplified","chinese_traditional"],"四":["chinese_simplified","chinese_traditional"],"日":["chinese_simplified","chinese_traditional"],"那":["chinese_simplified","chinese_traditional"],"社":["chinese_simplified","chinese_traditional"],"义":["chinese_simplified"],"事":["chinese_simplified","chinese_traditional"],"平":["chinese_simplified","chinese_traditional"],"形":["chinese_simplified","chinese_traditional"],"相":["chinese_simplified","chinese_traditional"],"全":["chinese_simplified","chinese_traditional"],"表":["chinese_simplified","chinese_traditional"],"间":["chinese_simplified"],"样":["chinese_simplified"],"与":["chinese_simplified"],"关":["chinese_simplified"],"各":["chinese_simplified","chinese_traditional"],"重":["chinese_simplified","chinese_traditional"],"新":["chinese_simplified","chinese_traditional"],"线":["chinese_simplified"],"内":["chinese_simplified"],"数":["chinese_simplified"],"正":["chinese_simplified","chinese_traditional"],"心":["chinese_simplified","chinese_traditional"],"反":["chinese_simplified","chinese_traditional"],"你":["chinese_simplified","chinese_traditional"],"明":["chinese_simplified","chinese_traditional"],"看":["chinese_simplified","chinese_traditional"],"原":["chinese_simplified","chinese_traditional"],"又":["chinese_simplified","chinese_traditional"],"么":["chinese_simplified"],"利":["chinese_simplified","chinese_traditional"],"比":["chinese_simplified","chinese_traditional"],"或":["chinese_simplified","chinese_traditional"],"但":["chinese_simplified","chinese_traditional"],"质":["chinese_simplified"],"气":["chinese_simplified"],"第":["chinese_simplified","chinese_traditional"],"向":["chinese_simplified","chinese_traditional"],"道":["chinese_simplified","chinese_traditional"],"命":["chinese_simplified","chinese_traditional"],"此":["chinese_simplified","chinese_traditional"],"变":["chinese_simplified"],"条":["chinese_simplified"],"只":["chinese_simplified","chinese_traditional"],"没":["chinese_simplified"],"结":["chinese_simplified"],"解":["chinese_simplified","chinese_traditional"],"问":["chinese_simplified"],"意":["chinese_simplified","chinese_traditional"],"建":["chinese_simplified","chinese_traditional"],"月":["chinese_simplified","chinese_traditional"],"公":["chinese_simplified","chinese_traditional"],"无":["chinese_simplified"],"系":["chinese_simplified","chinese_traditional"],"军":["chinese_simplified"],"很":["chinese_simplified","chinese_traditional"],"情":["chinese_simplified","chinese_traditional"],"者":["chinese_simplified","chinese_traditional"],"最":["chinese_simplified","chinese_traditional"],"立":["chinese_simplified","chinese_traditional"],"代":["chinese_simplified","chinese_traditional"],"想":["chinese_simplified","chinese_traditional"],"已":["chinese_simplified","chinese_traditional"],"通":["chinese_simplified","chinese_traditional"],"并":["chinese_simplified"],"提":["chinese_simplified","chinese_traditional"],"直":["chinese_simplified","chinese_traditional"],"题":["chinese_simplified"],"党":["chinese_simplified"],"程":["chinese_simplified","chinese_traditional"],"展":["chinese_simplified","chinese_traditional"],"五":["chinese_simplified","chinese_traditional"],"果":["chinese_simplified","chinese_traditional"],"料":["chinese_simplified","chinese_traditional"],"象":["chinese_simplified","chinese_traditional"],"员":["chinese_simplified"],"革":["chinese_simplified","chinese_traditional"],"位":["chinese_simplified","chinese_traditional"],"入":["chinese_simplified","chinese_traditional"],"常":["chinese_simplified","chinese_traditional"],"文":["chinese_simplified","chinese_traditional"],"总":["chinese_simplified"],"次":["chinese_simplified","chinese_traditional"],"品":["chinese_simplified","chinese_traditional"],"式":["chinese_simplified","chinese_traditional"],"活":["chinese_simplified","chinese_traditional"],"设":["chinese_simplified"],"及":["chinese_simplified","chinese_traditional"],"管":["chinese_simplified","chinese_traditional"],"特":["chinese_simplified","chinese_traditional"],"件":["chinese_simplified","chinese_traditional"],"长":["chinese_simplified"],"求":["chinese_simplified","chinese_traditional"],"老":["chinese_simplified","chinese_traditional"],"头":["chinese_simplified"],"基":["chinese_simplified","chinese_traditional"],"资":["chinese_simplified"],"边":["chinese_simplified"],"流":["chinese_simplified","chinese_traditional"],"路":["chinese_simplified","chinese_traditional"],"级":["chinese_simplified"],"少":["chinese_simplified","chinese_traditional"],"图":["chinese_simplified"],"山":["chinese_simplified","chinese_traditional"],"统":["chinese_simplified"],"接":["chinese_simplified","chinese_traditional"],"知":["chinese_simplified","chinese_traditional"],"较":["chinese_simplified"],"将":["chinese_simplified"],"组":["chinese_simplified"],"见":["chinese_simplified"],"计":["chinese_simplified"],"别":["chinese_simplified"],"她":["chinese_simplified","chinese_traditional"],"手":["chinese_simplified","chinese_traditional"],"角":["chinese_simplified","chinese_traditional"],"期":["chinese_simplified","chinese_traditional"],"根":["chinese_simplified","chinese_traditional"],"论":["chinese_simplified"],"运":["chinese_simplified"],"农":["chinese_simplified"],"指":["chinese_simplified","chinese_traditional"],"几":["chinese_simplified"],"九":["chinese_simplified","chinese_traditional"],"区":["chinese_simplified"],"强":["chinese_simplified"],"放":["chinese_simplified","chinese_traditional"],"决":["chinese_simplified"],"西":["chinese_simplified","chinese_traditional"],"被":["chinese_simplified","chinese_traditional"],"干":["chinese_simplified"],"做":["chinese_simplified","chinese_traditional"],"必":["chinese_simplified","chinese_traditional"],"战":["chinese_simplified"],"先":["chinese_simplified","chinese_traditional"],"回":["chinese_simplified","chinese_traditional"],"则":["chinese_simplified"],"任":["chinese_simplified","chinese_traditional"],"取":["chinese_simplified","chinese_traditional"],"据":["chinese_simplified"],"处":["chinese_simplified"],"队":["chinese_simplified"],"南":["chinese_simplified","chinese_traditional"],"给":["chinese_simplified"],"色":["chinese_simplified","chinese_traditional"],"光":["chinese_simplified","chinese_traditional"],"门":["chinese_simplified"],"即":["chinese_simplified","chinese_traditional"],"保":["chinese_simplified","chinese_traditional"],"治":["chinese_simplified","chinese_traditional"],"北":["chinese_simplified","chinese_traditional"],"造":["chinese_simplified","chinese_traditional"],"百":["chinese_simplified","chinese_traditional"],"规":["chinese_simplified"],"热":["chinese_simplified"],"领":["chinese_simplified"],"七":["chinese_simplified","chinese_traditional"],"海":["chinese_simplified","chinese_traditional"],"口":["chinese_simplified","chinese_traditional"],"东":["chinese_simplified"],"导":["chinese_simplified"],"器":["chinese_simplified","chinese_traditional"],"压":["chinese_simplified"],"志":["chinese_simplified","chinese_traditional"],"世":["chinese_simplified","chinese_traditional"],"金":["chinese_simplified","chinese_traditional"],"增":["chinese_simplified","chinese_traditional"],"争":["chinese_simplified"],"济":["chinese_simplified"],"阶":["chinese_simplified"],"油":["chinese_simplified","chinese_traditional"],"思":["chinese_simplified","chinese_traditional"],"术":["chinese_simplified"],"极":["chinese_simplified"],"交":["chinese_simplified","chinese_traditional"],"受":["chinese_simplified","chinese_traditional"],"联":["chinese_simplified"],"什":["chinese_simplified","chinese_traditional"],"认":["chinese_simplified"],"六":["chinese_simplified","chinese_traditional"],"共":["chinese_simplified","chinese_traditional"],"权":["chinese_simplified"],"收":["chinese_simplified","chinese_traditional"],"证":["chinese_simplified"],"改":["chinese_simplified","chinese_traditional"],"清":["chinese_simplified","chinese_traditional"],"美":["chinese_simplified","chinese_traditional"],"再":["chinese_simplified","chinese_traditional"],"采":["chinese_simplified"],"转":["chinese_simplified"],"更":["chinese_simplified","chinese_traditional"],"单":["chinese_simplified"],"风":["chinese_simplified"],"切":["chinese_simplified","chinese_traditional"],"打":["chinese_simplified","chinese_traditional"],"白":["chinese_simplified","chinese_traditional"],"教":["chinese_simplified","chinese_traditional"],"速":["chinese_simplified","chinese_traditional"],"花":["chinese_simplified","chinese_traditional"],"带":["chinese_simplified"],"安":["chinese_simplified","chinese_traditional"],"场":["chinese_simplified"],"身":["chinese_simplified","chinese_traditional"],"车":["chinese_simplified"],"例":["chinese_simplified","chinese_traditional"],"真":["chinese_simplified","chinese_traditional"],"务":["chinese_simplified"],"具":["chinese_simplified","chinese_traditional"],"万":["chinese_simplified"],"每":["chinese_simplified","chinese_traditional"],"目":["chinese_simplified","chinese_traditional"],"至":["chinese_simplified","chinese_traditional"],"达":["chinese_simplified"],"走":["chinese_simplified","chinese_traditional"],"积":["chinese_simplified"],"示":["chinese_simplified","chinese_traditional"],"议":["chinese_simplified"],"声":["chinese_simplified"],"报":["chinese_simplified"],"斗":["chinese_simplified"],"完":["chinese_simplified","chinese_traditional"],"类":["chinese_simplified"],"八":["chinese_simplified","chinese_traditional"],"离":["chinese_simplified"],"华":["chinese_simplified"],"名":["chinese_simplified","chinese_traditional"],"确":["chinese_simplified"],"才":["chinese_simplified","chinese_traditional"],"科":["chinese_simplified","chinese_traditional"],"张":["chinese_simplified"],"信":["chinese_simplified","chinese_traditional"],"马":["chinese_simplified"],"节":["chinese_simplified"],"话":["chinese_simplified"],"米":["chinese_simplified","chinese_traditional"],"整":["chinese_simplified","chinese_traditional"],"空":["chinese_simplified","chinese_traditional"],"元":["chinese_simplified","chinese_traditional"],"况":["chinese_simplified"],"今":["chinese_simplified","chinese_traditional"],"集":["chinese_simplified","chinese_traditional"],"温":["chinese_simplified"],"传":["chinese_simplified"],"土":["chinese_simplified","chinese_traditional"],"许":["chinese_simplified"],"步":["chinese_simplified","chinese_traditional"],"群":["chinese_simplified","chinese_traditional"],"广":["chinese_simplified"],"石":["chinese_simplified","chinese_traditional"],"记":["chinese_simplified"],"需":["chinese_simplified","chinese_traditional"],"段":["chinese_simplified","chinese_traditional"],"研":["chinese_simplified","chinese_traditional"],"界":["chinese_simplified","chinese_traditional"],"拉":["chinese_simplified","chinese_traditional"],"林":["chinese_simplified","chinese_traditional"],"律":["chinese_simplified","chinese_traditional"],"叫":["chinese_simplified","chinese_traditional"],"且":["chinese_simplified","chinese_traditional"],"究":["chinese_simplified","chinese_traditional"],"观":["chinese_simplified"],"越":["chinese_simplified","chinese_traditional"],"织":["chinese_simplified"],"装":["chinese_simplified"],"影":["chinese_simplified","chinese_traditional"],"算":["chinese_simplified","chinese_traditional"],"低":["chinese_simplified","chinese_traditional"],"持":["chinese_simplified","chinese_traditional"],"音":["chinese_simplified","chinese_traditional"],"众":["chinese_simplified"],"书":["chinese_simplified"],"布":["chinese_simplified","chinese_traditional"],"复":["chinese_simplified","chinese_traditional"],"容":["chinese_simplified","chinese_traditional"],"儿":["chinese_simplified"],"须":["chinese_simplified"],"际":["chinese_simplified"],"商":["chinese_simplified","chinese_traditional"],"非":["chinese_simplified","chinese_traditional"],"验":["chinese_simplified"],"连":["chinese_simplified"],"断":["chinese_simplified"],"深":["chinese_simplified","chinese_traditional"],"难":["chinese_simplified"],"近":["chinese_simplified","chinese_traditional"],"矿":["chinese_simplified"],"千":["chinese_simplified","chinese_traditional"],"周":["chinese_simplified"],"委":["chinese_simplified","chinese_traditional"],"素":["chinese_simplified","chinese_traditional"],"技":["chinese_simplified","chinese_traditional"],"备":["chinese_simplified"],"半":["chinese_simplified","chinese_traditional"],"办":["chinese_simplified"],"青":["chinese_simplified","chinese_traditional"],"省":["chinese_simplified","chinese_traditional"],"列":["chinese_simplified","chinese_traditional"],"习":["chinese_simplified"],"响":["chinese_simplified"],"约":["chinese_simplified"],"支":["chinese_simplified","chinese_traditional"],"般":["chinese_simplified","chinese_traditional"],"史":["chinese_simplified","chinese_traditional"],"感":["chinese_simplified","chinese_traditional"],"劳":["chinese_simplified"],"便":["chinese_simplified","chinese_traditional"],"团":["chinese_simplified"],"往":["chinese_simplified","chinese_traditional"],"酸":["chinese_simplified","chinese_traditional"],"历":["chinese_simplified"],"市":["chinese_simplified","chinese_traditional"],"克":["chinese_simplified","chinese_traditional"],"何":["chinese_simplified","chinese_traditional"],"除":["chinese_simplified","chinese_traditional"],"消":["chinese_simplified","chinese_traditional"],"构":["chinese_simplified"],"府":["chinese_simplified","chinese_traditional"],"称":["chinese_simplified"],"太":["chinese_simplified","chinese_traditional"],"准":["chinese_simplified"],"精":["chinese_simplified","chinese_traditional"],"值":["chinese_simplified","chinese_traditional"],"号":["chinese_simplified"],"率":["chinese_simplified","chinese_traditional"],"族":["chinese_simplified","chinese_traditional"],"维":["chinese_simplified"],"划":["chinese_simplified"],"选":["chinese_simplified"],"标":["chinese_simplified"],"写":["chinese_simplified"],"存":["chinese_simplified","chinese_traditional"],"候":["chinese_simplified","chinese_traditional"],"毛":["chinese_simplified","chinese_traditional"],"亲":["chinese_simplified"],"快":["chinese_simplified","chinese_traditional"],"效":["chinese_simplified","chinese_traditional"],"斯":["chinese_simplified","chinese_traditional"],"院":["chinese_simplified","chinese_traditional"],"查":["chinese_simplified","chinese_traditional"],"江":["chinese_simplified","chinese_traditional"],"型":["chinese_simplified","chinese_traditional"],"眼":["chinese_simplified","chinese_traditional"],"王":["chinese_simplified","chinese_traditional"],"按":["chinese_simplified","chinese_traditional"],"格":["chinese_simplified","chinese_traditional"],"养":["chinese_simplified"],"易":["chinese_simplified","chinese_traditional"],"置":["chinese_simplified","chinese_traditional"],"派":["chinese_simplified","chinese_traditional"],"层":["chinese_simplified"],"片":["chinese_simplified","chinese_traditional"],"始":["chinese_simplified","chinese_traditional"],"却":["chinese_simplified"],"专":["chinese_simplified"],"状":["chinese_simplified"],"育":["chinese_simplified","chinese_traditional"],"厂":["chinese_simplified"],"京":["chinese_simplified","chinese_traditional"],"识":["chinese_simplified"],"适":["chinese_simplified"],"属":["chinese_simplified"],"圆":["chinese_simplified"],"包":["chinese_simplified","chinese_traditional"],"火":["chinese_simplified","chinese_traditional"],"住":["chinese_simplified","chinese_traditional"],"调":["chinese_simplified"],"满":["chinese_simplified"],"县":["chinese_simplified"],"局":["chinese_simplified","chinese_traditional"],"照":["chinese_simplified","chinese_traditional"],"参":["chinese_simplified"],"红":["chinese_simplified"],"细":["chinese_simplified"],"引":["chinese_simplified","chinese_traditional"],"听":["chinese_simplified"],"该":["chinese_simplified"],"铁":["chinese_simplified"],"价":["chinese_simplified"],"严":["chinese_simplified"],"首":["chinese_simplified","chinese_traditional"],"底":["chinese_simplified","chinese_traditional"],"液":["chinese_simplified","chinese_traditional"],"官":["chinese_simplified","chinese_traditional"],"德":["chinese_simplified","chinese_traditional"],"随":["chinese_simplified"],"病":["chinese_simplified","chinese_traditional"],"苏":["chinese_simplified"],"失":["chinese_simplified","chinese_traditional"],"尔":["chinese_simplified"],"死":["chinese_simplified","chinese_traditional"],"讲":["chinese_simplified"],"配":["chinese_simplified","chinese_traditional"],"女":["chinese_simplified","chinese_traditional"],"黄":["chinese_simplified"],"推":["chinese_simplified","chinese_traditional"],"显":["chinese_simplified"],"谈":["chinese_simplified"],"罪":["chinese_simplified","chinese_traditional"],"神":["chinese_simplified","chinese_traditional"],"艺":["chinese_simplified"],"呢":["chinese_simplified","chinese_traditional"],"席":["chinese_simplified","chinese_traditional"],"含":["chinese_simplified","chinese_traditional"],"企":["chinese_simplified","chinese_traditional"],"望":["chinese_simplified","chinese_traditional"],"密":["chinese_simplified","chinese_traditional"],"批":["chinese_simplified","chinese_traditional"],"营":["chinese_simplified"],"项":["chinese_simplified"],"防":["chinese_simplified","chinese_traditional"],"举":["chinese_simplified"],"球":["chinese_simplified","chinese_traditional"],"英":["chinese_simplified","chinese_traditional"],"氧":["chinese_simplified","chinese_traditional"],"势":["chinese_simplified"],"告":["chinese_simplified","chinese_traditional"],"李":["chinese_simplified","chinese_traditional"],"台":["chinese_simplified","chinese_traditional"],"落":["chinese_simplified","chinese_traditional"],"木":["chinese_simplified","chinese_traditional"],"帮":["chinese_simplified"],"轮":["chinese_simplified"],"破":["chinese_simplified","chinese_traditional"],"亚":["chinese_simplified"],"师":["chinese_simplified"],"围":["chinese_simplified"],"注":["chinese_simplified","chinese_traditional"],"远":["chinese_simplified"],"字":["chinese_simplified","chinese_traditional"],"材":["chinese_simplified","chinese_traditional"],"排":["chinese_simplified","chinese_traditional"],"供":["chinese_simplified","chinese_traditional"],"河":["chinese_simplified","chinese_traditional"],"态":["chinese_simplified"],"封":["chinese_simplified","chinese_traditional"],"另":["chinese_simplified","chinese_traditional"],"施":["chinese_simplified","chinese_traditional"],"减":["chinese_simplified"],"树":["chinese_simplified"],"溶":["chinese_simplified","chinese_traditional"],"怎":["chinese_simplified","chinese_traditional"],"止":["chinese_simplified","chinese_traditional"],"案":["chinese_simplified","chinese_traditional"],"言":["chinese_simplified","chinese_traditional"],"士":["chinese_simplified","chinese_traditional"],"均":["chinese_simplified","chinese_traditional"],"武":["chinese_simplified","chinese_traditional"],"固":["chinese_simplified","chinese_traditional"],"叶":["chinese_simplified"],"鱼":["chinese_simplified"],"波":["chinese_simplified","chinese_traditional"],"视":["chinese_simplified"],"仅":["chinese_simplified"],"费":["chinese_simplified"],"紧":["chinese_simplified"],"爱":["chinese_simplified"],"左":["chinese_simplified","chinese_traditional"],"章":["chinese_simplified","chinese_traditional"],"早":["chinese_simplified","chinese_traditional"],"朝":["chinese_simplified","chinese_traditional"],"害":["chinese_simplified","chinese_traditional"],"续":["chinese_simplified"],"轻":["chinese_simplified"],"服":["chinese_simplified","chinese_traditional"],"试":["chinese_simplified"],"食":["chinese_simplified","chinese_traditional"],"充":["chinese_simplified","chinese_traditional"],"兵":["chinese_simplified","chinese_traditional"],"源":["chinese_simplified","chinese_traditional"],"判":["chinese_simplified","chinese_traditional"],"护":["chinese_simplified"],"司":["chinese_simplified","chinese_traditional"],"足":["chinese_simplified","chinese_traditional"],"某":["chinese_simplified","chinese_traditional"],"练":["chinese_simplified"],"差":["chinese_simplified","chinese_traditional"],"致":["chinese_simplified","chinese_traditional"],"板":["chinese_simplified","chinese_traditional"],"田":["chinese_simplified","chinese_traditional"],"降":["chinese_simplified","chinese_traditional"],"黑":["chinese_simplified","chinese_traditional"],"犯":["chinese_simplified","chinese_traditional"],"负":["chinese_simplified"],"击":["chinese_simplified"],"范":["chinese_simplified","chinese_traditional"],"继":["chinese_simplified"],"兴":["chinese_simplified"],"似":["chinese_simplified","chinese_traditional"],"余":["chinese_simplified"],"坚":["chinese_simplified"],"曲":["chinese_simplified","chinese_traditional"],"输":["chinese_simplified"],"修":["chinese_simplified","chinese_traditional"],"故":["chinese_simplified","chinese_traditional"],"城":["chinese_simplified","chinese_traditional"],"夫":["chinese_simplified","chinese_traditional"],"够":["chinese_simplified"],"送":["chinese_simplified","chinese_traditional"],"笔":["chinese_simplified"],"船":["chinese_simplified","chinese_traditional"],"占":["chinese_simplified"],"右":["chinese_simplified","chinese_traditional"],"财":["chinese_simplified"],"吃":["chinese_simplified","chinese_traditional"],"富":["chinese_simplified","chinese_traditional"],"春":["chinese_simplified","chinese_traditional"],"职":["chinese_simplified"],"觉":["chinese_simplified"],"汉":["chinese_simplified"],"画":["chinese_simplified"],"功":["chinese_simplified","chinese_traditional"],"巴":["chinese_simplified","chinese_traditional"],"跟":["chinese_simplified","chinese_traditional"],"虽":["chinese_simplified"],"杂":["chinese_simplified"],"飞":["chinese_simplified"],"检":["chinese_simplified"],"吸":["chinese_simplified","chinese_traditional"],"助":["chinese_simplified","chinese_traditional"],"升":["chinese_simplified"],"阳":["chinese_simplified"],"互":["chinese_simplified","chinese_traditional"],"初":["chinese_simplified","chinese_traditional"],"创":["chinese_simplified"],"抗":["chinese_simplified","chinese_traditional"],"考":["chinese_simplified","chinese_traditional"],"投":["chinese_simplified","chinese_traditional"],"坏":["chinese_simplified"],"策":["chinese_simplified","chinese_traditional"],"古":["chinese_simplified","chinese_traditional"],"径":["chinese_simplified"],"换":["chinese_simplified"],"未":["chinese_simplified","chinese_traditional"],"跑":["chinese_simplified","chinese_traditional"],"留":["chinese_simplified","chinese_traditional"],"钢":["chinese_simplified"],"曾":["chinese_simplified","chinese_traditional"],"端":["chinese_simplified","chinese_traditional"],"责":["chinese_simplified"],"站":["chinese_simplified","chinese_traditional"],"简":["chinese_simplified"],"述":["chinese_simplified","chinese_traditional"],"钱":["chinese_simplified"],"副":["chinese_simplified","chinese_traditional"],"尽":["chinese_simplified"],"帝":["chinese_simplified","chinese_traditional"],"射":["chinese_simplified","chinese_traditional"],"草":["chinese_simplified","chinese_traditional"],"冲":["chinese_simplified"],"承":["chinese_simplified","chinese_traditional"],"独":["chinese_simplified"],"令":["chinese_simplified","chinese_traditional"],"限":["chinese_simplified","chinese_traditional"],"阿":["chinese_simplified","chinese_traditional"],"宣":["chinese_simplified","chinese_traditional"],"环":["chinese_simplified"],"双":["chinese_simplified"],"请":["chinese_simplified"],"超":["chinese_simplified","chinese_traditional"],"微":["chinese_simplified","chinese_traditional"],"让":["chinese_simplified"],"控":["chinese_simplified","chinese_traditional"],"州":["chinese_simplified","chinese_traditional"],"良":["chinese_simplified","chinese_traditional"],"轴":["chinese_simplified"],"找":["chinese_simplified","chinese_traditional"],"否":["chinese_simplified","chinese_traditional"],"纪":["chinese_simplified"],"益":["chinese_simplified","chinese_traditional"],"依":["chinese_simplified","chinese_traditional"],"优":["chinese_simplified"],"顶":["chinese_simplified"],"础":["chinese_simplified"],"载":["chinese_simplified"],"倒":["chinese_simplified","chinese_traditional"],"房":["chinese_simplified","chinese_traditional"],"突":["chinese_simplified","chinese_traditional"],"坐":["chinese_simplified","chinese_traditional"],"粉":["chinese_simplified","chinese_traditional"],"敌":["chinese_simplified"],"略":["chinese_simplified","chinese_traditional"],"客":["chinese_simplified","chinese_traditional"],"袁":["chinese_simplified","chinese_traditional"],"冷":["chinese_simplified","chinese_traditional"],"胜":["chinese_simplified"],"绝":["chinese_simplified"],"析":["chinese_simplified","chinese_traditional"],"块":["chinese_simplified"],"剂":["chinese_simplified"],"测":["chinese_simplified"],"丝":["chinese_simplified"],"协":["chinese_simplified"],"诉":["chinese_simplified"],"念":["chinese_simplified","chinese_traditional"],"陈":["chinese_simplified"],"仍":["chinese_simplified","chinese_traditional"],"罗":["chinese_simplified"],"盐":["chinese_simplified"],"友":["chinese_simplified","chinese_traditional"],"洋":["chinese_simplified","chinese_traditional"],"错":["chinese_simplified"],"苦":["chinese_simplified","chinese_traditional"],"夜":["chinese_simplified","chinese_traditional"],"刑":["chinese_simplified","chinese_traditional"],"移":["chinese_simplified","chinese_traditional"],"频":["chinese_simplified"],"逐":["chinese_simplified","chinese_traditional"],"靠":["chinese_simplified","chinese_traditional"],"混":["chinese_simplified","chinese_traditional"],"母":["chinese_simplified","chinese_traditional"],"短":["chinese_simplified","chinese_traditional"],"皮":["chinese_simplified","chinese_traditional"],"终":["chinese_simplified"],"聚":["chinese_simplified","chinese_traditional"],"汽":["chinese_simplified","chinese_traditional"],"村":["chinese_simplified","chinese_traditional"],"云":["chinese_simplified"],"哪":["chinese_simplified","chinese_traditional"],"既":["chinese_simplified","chinese_traditional"],"距":["chinese_simplified","chinese_traditional"],"卫":["chinese_simplified"],"停":["chinese_simplified","chinese_traditional"],"烈":["chinese_simplified","chinese_traditional"],"央":["chinese_simplified","chinese_traditional"],"察":["chinese_simplified","chinese_traditional"],"烧":["chinese_simplified"],"迅":["chinese_simplified","chinese_traditional"],"境":["chinese_simplified","chinese_traditional"],"若":["chinese_simplified","chinese_traditional"],"印":["chinese_simplified","chinese_traditional"],"洲":["chinese_simplified","chinese_traditional"],"刻":["chinese_simplified","chinese_traditional"],"括":["chinese_simplified","chinese_traditional"],"激":["chinese_simplified","chinese_traditional"],"孔":["chinese_simplified","chinese_traditional"],"搞":["chinese_simplified","chinese_traditional"],"甚":["chinese_simplified","chinese_traditional"],"室":["chinese_simplified","chinese_traditional"],"待":["chinese_simplified","chinese_traditional"],"核":["chinese_simplified","chinese_traditional"],"校":["chinese_simplified","chinese_traditional"],"散":["chinese_simplified","chinese_traditional"],"侵":["chinese_simplified","chinese_traditional"],"吧":["chinese_simplified","chinese_traditional"],"甲":["chinese_simplified","chinese_traditional"],"游":["chinese_simplified"],"久":["chinese_simplified","chinese_traditional"],"菜":["chinese_simplified","chinese_traditional"],"味":["chinese_simplified","chinese_traditional"],"旧":["chinese_simplified"],"模":["chinese_simplified","chinese_traditional"],"湖":["chinese_simplified","chinese_traditional"],"货":["chinese_simplified"],"损":["chinese_simplified"],"预":["chinese_simplified"],"阻":["chinese_simplified","chinese_traditional"],"毫":["chinese_simplified","chinese_traditional"],"普":["chinese_simplified","chinese_traditional"],"稳":["chinese_simplified"],"乙":["chinese_simplified","chinese_traditional"],"妈":["chinese_simplified"],"植":["chinese_simplified","chinese_traditional"],"息":["chinese_simplified","chinese_traditional"],"扩":["chinese_simplified"],"银":["chinese_simplified"],"语":["chinese_simplified"],"挥":["chinese_simplified"],"酒":["chinese_simplified","chinese_traditional"],"守":["chinese_simplified","chinese_traditional"],"拿":["chinese_simplified","chinese_traditional"],"序":["chinese_simplified","chinese_traditional"],"纸":["chinese_simplified"],"医":["chinese_simplified"],"缺":["chinese_simplified","chinese_traditional"],"雨":["chinese_simplified","chinese_traditional"],"吗":["chinese_simplified"],"针":["chinese_simplified"],"刘":["chinese_simplified"],"啊":["chinese_simplified","chinese_traditional"],"急":["chinese_simplified","chinese_traditional"],"唱":["chinese_simplified","chinese_traditional"],"误":["chinese_simplified"],"训":["chinese_simplified"],"愿":["chinese_simplified"],"审":["chinese_simplified"],"附":["chinese_simplified","chinese_traditional"],"获":["chinese_simplified"],"茶":["chinese_simplified","chinese_traditional"],"鲜":["chinese_simplified"],"粮":["chinese_simplified"],"斤":["chinese_simplified","chinese_traditional"],"孩":["chinese_simplified","chinese_traditional"],"脱":["chinese_simplified"],"硫":["chinese_simplified","chinese_traditional"],"肥":["chinese_simplified","chinese_traditional"],"善":["chinese_simplified","chinese_traditional"],"龙":["chinese_simplified"],"演":["chinese_simplified","chinese_traditional"],"父":["chinese_simplified","chinese_traditional"],"渐":["chinese_simplified"],"血":["chinese_simplified","chinese_traditional"],"欢":["chinese_simplified"],"械":["chinese_simplified","chinese_traditional"],"掌":["chinese_simplified","chinese_traditional"],"歌":["chinese_simplified","chinese_traditional"],"沙":["chinese_simplified","chinese_traditional"],"刚":["chinese_simplified"],"攻":["chinese_simplified","chinese_traditional"],"谓":["chinese_simplified"],"盾":["chinese_simplified","chinese_traditional"],"讨":["chinese_simplified"],"晚":["chinese_simplified","chinese_traditional"],"粒":["chinese_simplified","chinese_traditional"],"乱":["chinese_simplified"],"燃":["chinese_simplified","chinese_traditional"],"矛":["chinese_simplified","chinese_traditional"],"乎":["chinese_simplified","chinese_traditional"],"杀":["chinese_simplified"],"药":["chinese_simplified"],"宁":["chinese_simplified"],"鲁":["chinese_simplified"],"贵":["chinese_simplified"],"钟":["chinese_simplified"],"煤":["chinese_simplified","chinese_traditional"],"读":["chinese_simplified"],"班":["chinese_simplified","chinese_traditional"],"伯":["chinese_simplified","chinese_traditional"],"香":["chinese_simplified","chinese_traditional"],"介":["chinese_simplified","chinese_traditional"],"迫":["chinese_simplified","chinese_traditional"],"句":["chinese_simplified","chinese_traditional"],"丰":["chinese_simplified"],"培":["chinese_simplified","chinese_traditional"],"握":["chinese_simplified","chinese_traditional"],"兰":["chinese_simplified"],"担":["chinese_simplified"],"弦":["chinese_simplified","chinese_traditional"],"蛋":["chinese_simplified","chinese_traditional"],"沉":["chinese_simplified","chinese_traditional"],"假":["chinese_simplified","chinese_traditional"],"穿":["chinese_simplified","chinese_traditional"],"执":["chinese_simplified"],"答":["chinese_simplified","chinese_traditional"],"乐":["chinese_simplified"],"谁":["chinese_simplified"],"顺":["chinese_simplified"],"烟":["chinese_simplified"],"缩":["chinese_simplified"],"征":["chinese_simplified"],"脸":["chinese_simplified"],"喜":["chinese_simplified","chinese_traditional"],"松":["chinese_simplified","chinese_traditional"],"脚":["chinese_simplified"],"困":["chinese_simplified","chinese_traditional"],"异":["chinese_simplified"],"免":["chinese_simplified","chinese_traditional"],"背":["chinese_simplified","chinese_traditional"],"星":["chinese_simplified","chinese_traditional"],"福":["chinese_simplified","chinese_traditional"],"买":["chinese_simplified"],"染":["chinese_simplified","chinese_traditional"],"井":["chinese_simplified","chinese_traditional"],"概":["chinese_simplified","chinese_traditional"],"慢":["chinese_simplified","chinese_traditional"],"怕":["chinese_simplified","chinese_traditional"],"磁":["chinese_simplified","chinese_traditional"],"倍":["chinese_simplified","chinese_traditional"],"祖":["chinese_simplified","chinese_traditional"],"皇":["chinese_simplified","chinese_traditional"],"促":["chinese_simplified","chinese_traditional"],"静":["chinese_simplified"],"补":["chinese_simplified"],"评":["chinese_simplified"],"翻":["chinese_simplified","chinese_traditional"],"肉":["chinese_simplified","chinese_traditional"],"践":["chinese_simplified"],"尼":["chinese_simplified","chinese_traditional"],"衣":["chinese_simplified","chinese_traditional"],"宽":["chinese_simplified"],"扬":["chinese_simplified"],"棉":["chinese_simplified","chinese_traditional"],"希":["chinese_simplified","chinese_traditional"],"伤":["chinese_simplified"],"操":["chinese_simplified","chinese_traditional"],"垂":["chinese_simplified","chinese_traditional"],"秋":["chinese_simplified","chinese_traditional"],"宜":["chinese_simplified","chinese_traditional"],"氢":["chinese_simplified"],"套":["chinese_simplified","chinese_traditional"],"督":["chinese_simplified","chinese_traditional"],"振":["chinese_simplified","chinese_traditional"],"架":["chinese_simplified","chinese_traditional"],"亮":["chinese_simplified","chinese_traditional"],"末":["chinese_simplified","chinese_traditional"],"宪":["chinese_simplified"],"庆":["chinese_simplified"],"编":["chinese_simplified"],"牛":["chinese_simplified","chinese_traditional"],"触":["chinese_simplified"],"映":["chinese_simplified","chinese_traditional"],"雷":["chinese_simplified","chinese_traditional"],"销":["chinese_simplified"],"诗":["chinese_simplified"],"座":["chinese_simplified","chinese_traditional"],"居":["chinese_simplified","chinese_traditional"],"抓":["chinese_simplified","chinese_traditional"],"裂":["chinese_simplified","chinese_traditional"],"胞":["chinese_simplified","chinese_traditional"],"呼":["chinese_simplified","chinese_traditional"],"娘":["chinese_simplified","chinese_traditional"],"景":["chinese_simplified","chinese_traditional"],"威":["chinese_simplified","chinese_traditional"],"绿":["chinese_simplified"],"晶":["chinese_simplified","chinese_traditional"],"厚":["chinese_simplified","chinese_traditional"],"盟":["chinese_simplified","chinese_traditional"],"衡":["chinese_simplified","chinese_traditional"],"鸡":["chinese_simplified"],"孙":["chinese_simplified"],"延":["chinese_simplified","chinese_traditional"],"危":["chinese_simplified","chinese_traditional"],"胶":["chinese_simplified"],"屋":["chinese_simplified","chinese_traditional"],"乡":["chinese_simplified"],"临":["chinese_simplified"],"陆":["chinese_simplified"],"顾":["chinese_simplified"],"掉":["chinese_simplified","chinese_traditional"],"呀":["chinese_simplified","chinese_traditional"],"灯":["chinese_simplified"],"岁":["chinese_simplified"],"措":["chinese_simplified","chinese_traditional"],"束":["chinese_simplified","chinese_traditional"],"耐":["chinese_simplified","chinese_traditional"],"剧":["chinese_simplified"],"玉":["chinese_simplified","chinese_traditional"],"赵":["chinese_simplified"],"跳":["chinese_simplified","chinese_traditional"],"哥":["chinese_simplified","chinese_traditional"],"季":["chinese_simplified","chinese_traditional"],"课":["chinese_simplified"],"凯":["chinese_simplified"],"胡":["chinese_simplified","chinese_traditional"],"额":["chinese_simplified"],"款":["chinese_simplified","chinese_traditional"],"绍":["chinese_simplified"],"卷":["chinese_simplified","chinese_traditional"],"齐":["chinese_simplified"],"伟":["chinese_simplified"],"蒸":["chinese_simplified","chinese_traditional"],"殖":["chinese_simplified","chinese_traditional"],"永":["chinese_simplified","chinese_traditional"],"宗":["chinese_simplified","chinese_traditional"],"苗":["chinese_simplified","chinese_traditional"],"川":["chinese_simplified","chinese_traditional"],"炉":["chinese_simplified"],"岩":["chinese_simplified","chinese_traditional"],"弱":["chinese_simplified","chinese_traditional"],"零":["chinese_simplified","chinese_traditional"],"杨":["chinese_simplified"],"奏":["chinese_simplified","chinese_traditional"],"沿":["chinese_simplified","chinese_traditional"],"露":["chinese_simplified","chinese_traditional"],"杆":["chinese_simplified"],"探":["chinese_simplified","chinese_traditional"],"滑":["chinese_simplified","chinese_traditional"],"镇":["chinese_simplified"],"饭":["chinese_simplified"],"浓":["chinese_simplified"],"航":["chinese_simplified","chinese_traditional"],"怀":["chinese_simplified"],"赶":["chinese_simplified"],"库":["chinese_simplified"],"夺":["chinese_simplified"],"伊":["chinese_simplified","chinese_traditional"],"灵":["chinese_simplified"],"税":["chinese_simplified"],"途":["chinese_simplified","chinese_traditional"],"灭":["chinese_simplified"],"赛":["chinese_simplified"],"归":["chinese_simplified"],"召":["chinese_simplified","chinese_traditional"],"鼓":["chinese_simplified","chinese_traditional"],"播":["chinese_simplified","chinese_traditional"],"盘":["chinese_simplified"],"裁":["chinese_simplified","chinese_traditional"],"险":["chinese_simplified"],"康":["chinese_simplified","chinese_traditional"],"唯":["chinese_simplified","chinese_traditional"],"录":["chinese_simplified"],"菌":["chinese_simplified","chinese_traditional"],"纯":["chinese_simplified"],"借":["chinese_simplified","chinese_traditional"],"糖":["chinese_simplified","chinese_traditional"],"盖":["chinese_simplified"],"横":["chinese_simplified"],"符":["chinese_simplified","chinese_traditional"],"私":["chinese_simplified","chinese_traditional"],"努":["chinese_simplified","chinese_traditional"],"堂":["chinese_simplified","chinese_traditional"],"域":["chinese_simplified","chinese_traditional"],"枪":["chinese_simplified"],"润":["chinese_simplified"],"幅":["chinese_simplified","chinese_traditional"],"哈":["chinese_simplified","chinese_traditional"],"竟":["chinese_simplified","chinese_traditional"],"熟":["chinese_simplified","chinese_traditional"],"虫":["chinese_simplified"],"泽":["chinese_simplified"],"脑":["chinese_simplified"],"壤":["chinese_simplified","chinese_traditional"],"碳":["chinese_simplified","chinese_traditional"],"欧":["chinese_simplified"],"遍":["chinese_simplified","chinese_traditional"],"侧":["chinese_simplified"],"寨":["chinese_simplified","chinese_traditional"],"敢":["chinese_simplified","chinese_traditional"],"彻":["chinese_simplified"],"虑":["chinese_simplified"],"斜":["chinese_simplified","chinese_traditional"],"薄":["chinese_simplified","chinese_traditional"],"庭":["chinese_simplified","chinese_traditional"],"纳":["chinese_simplified"],"弹":["chinese_simplified"],"饲":["chinese_simplified"],"伸":["chinese_simplified","chinese_traditional"],"折":["chinese_simplified","chinese_traditional"],"麦":["chinese_simplified"],"湿":["chinese_simplified"],"暗":["chinese_simplified","chinese_traditional"],"荷":["chinese_simplified","chinese_traditional"],"瓦":["chinese_simplified","chinese_traditional"],"塞":["chinese_simplified","chinese_traditional"],"床":["chinese_simplified","chinese_traditional"],"筑":["chinese_simplified"],"恶":["chinese_simplified"],"户":["chinese_simplified"],"访":["chinese_simplified"],"塔":["chinese_simplified","chinese_traditional"],"奇":["chinese_simplified","chinese_traditional"],"透":["chinese_simplified","chinese_traditional"],"梁":["chinese_simplified","chinese_traditional"],"刀":["chinese_simplified","chinese_traditional"],"旋":["chinese_simplified","chinese_traditional"],"迹":["chinese_simplified"],"卡":["chinese_simplified","chinese_traditional"],"氯":["chinese_simplified","chinese_traditional"],"遇":["chinese_simplified","chinese_traditional"],"份":["chinese_simplified","chinese_traditional"],"毒":["chinese_simplified","chinese_traditional"],"泥":["chinese_simplified","chinese_traditional"],"退":["chinese_simplified","chinese_traditional"],"洗":["chinese_simplified","chinese_traditional"],"摆":["chinese_simplified"],"灰":["chinese_simplified","chinese_traditional"],"彩":["chinese_simplified","chinese_traditional"],"卖":["chinese_simplified"],"耗":["chinese_simplified","chinese_traditional"],"夏":["chinese_simplified","chinese_traditional"],"择":["chinese_simplified"],"忙":["chinese_simplified","chinese_traditional"],"铜":["chinese_simplified"],"献":["chinese_simplified"],"硬":["chinese_simplified","chinese_traditional"],"予":["chinese_simplified","chinese_traditional"],"繁":["chinese_simplified","chinese_traditional"],"圈":["chinese_simplified","chinese_traditional"],"雪":["chinese_simplified","chinese_traditional"],"函":["chinese_simplified","chinese_traditional"],"亦":["chinese_simplified","chinese_traditional"],"抽":["chinese_simplified","chinese_traditional"],"篇":["chinese_simplified","chinese_traditional"],"阵":["chinese_simplified"],"阴":["chinese_simplified"],"丁":["chinese_simplified","chinese_traditional"],"尺":["chinese_simplified","chinese_traditional"],"追":["chinese_simplified","chinese_traditional"],"堆":["chinese_simplified","chinese_traditional"],"雄":["chinese_simplified","chinese_traditional"],"迎":["chinese_simplified","chinese_traditional"],"泛":["chinese_simplified","chinese_traditional"],"爸":["chinese_simplified","chinese_traditional"],"楼":["chinese_simplified"],"避":["chinese_simplified","chinese_traditional"],"谋":["chinese_simplified"],"吨":["chinese_simplified"],"野":["chinese_simplified","chinese_traditional"],"猪":["chinese_simplified"],"旗":["chinese_simplified","chinese_traditional"],"累":["chinese_simplified","chinese_traditional"],"偏":["chinese_simplified","chinese_traditional"],"典":["chinese_simplified","chinese_traditional"],"馆":["chinese_simplified"],"索":["chinese_simplified","chinese_traditional"],"秦":["chinese_simplified","chinese_traditional"],"脂":["chinese_simplified","chinese_traditional"],"潮":["chinese_simplified","chinese_traditional"],"爷":["chinese_simplified"],"豆":["chinese_simplified","chinese_traditional"],"忽":["chinese_simplified","chinese_traditional"],"托":["chinese_simplified","chinese_traditional"],"惊":["chinese_simplified"],"塑":["chinese_simplified","chinese_traditional"],"遗":["chinese_simplified"],"愈":["chinese_simplified","chinese_traditional"],"朱":["chinese_simplified","chinese_traditional"],"替":["chinese_simplified","chinese_traditional"],"纤":["chinese_simplified"],"粗":["chinese_simplified","chinese_traditional"],"倾":["chinese_simplified"],"尚":["chinese_simplified","chinese_traditional"],"痛":["chinese_simplified","chinese_traditional"],"楚":["chinese_simplified","chinese_traditional"],"谢":["chinese_simplified"],"奋":["chinese_simplified"],"购":["chinese_simplified"],"磨":["chinese_simplified","chinese_traditional"],"君":["chinese_simplified","chinese_traditional"],"池":["chinese_simplified","chinese_traditional"],"旁":["chinese_simplified","chinese_traditional"],"碎":["chinese_simplified","chinese_traditional"],"骨":["chinese_simplified","chinese_traditional"],"监":["chinese_simplified"],"捕":["chinese_simplified","chinese_traditional"],"弟":["chinese_simplified","chinese_traditional"],"暴":["chinese_simplified","chinese_traditional"],"割":["chinese_simplified","chinese_traditional"],"贯":["chinese_simplified"],"殊":["chinese_simplified","chinese_traditional"],"释":["chinese_simplified"],"词":["chinese_simplified"],"亡":["chinese_simplified","chinese_traditional"],"壁":["chinese_simplified","chinese_traditional"],"顿":["chinese_simplified"],"宝":["chinese_simplified"],"午":["chinese_simplified","chinese_traditional"],"尘":["chinese_simplified"],"闻":["chinese_simplified"],"揭":["chinese_simplified","chinese_traditional"],"炮":["chinese_simplified","chinese_traditional"],"残":["chinese_simplified"],"冬":["chinese_simplified","chinese_traditional"],"桥":["chinese_simplified"],"妇":["chinese_simplified"],"警":["chinese_simplified","chinese_traditional"],"综":["chinese_simplified"],"招":["chinese_simplified","chinese_traditional"],"吴":["chinese_simplified"],"付":["chinese_simplified","chinese_traditional"],"浮":["chinese_simplified","chinese_traditional"],"遭":["chinese_simplified","chinese_traditional"],"徐":["chinese_simplified","chinese_traditional"],"您":["chinese_simplified","chinese_traditional"],"摇":["chinese_simplified"],"谷":["chinese_simplified","chinese_traditional"],"赞":["chinese_simplified"],"箱":["chinese_simplified","chinese_traditional"],"隔":["chinese_simplified","chinese_traditional"],"订":["chinese_simplified"],"男":["chinese_simplified","chinese_traditional"],"吹":["chinese_simplified","chinese_traditional"],"园":["chinese_simplified"],"纷":["chinese_simplified"],"唐":["chinese_simplified","chinese_traditional"],"败":["chinese_simplified"],"宋":["chinese_simplified","chinese_traditional"],"玻":["chinese_simplified","chinese_traditional"],"巨":["chinese_simplified","chinese_traditional"],"耕":["chinese_simplified","chinese_traditional"],"坦":["chinese_simplified","chinese_traditional"],"荣":["chinese_simplified"],"闭":["chinese_simplified"],"湾":["chinese_simplified"],"键":["chinese_simplified"],"凡":["chinese_simplified","chinese_traditional"],"驻":["chinese_simplified"],"锅":["chinese_simplified"],"救":["chinese_simplified","chinese_traditional"],"恩":["chinese_simplified","chinese_traditional"],"剥":["chinese_simplified"],"凝":["chinese_simplified","chinese_traditional"],"碱":["chinese_simplified"],"齿":["chinese_simplified"],"截":["chinese_simplified","chinese_traditional"],"炼":["chinese_simplified"],"麻":["chinese_simplified","chinese_traditional"],"纺":["chinese_simplified"],"禁":["chinese_simplified","chinese_traditional"],"废":["chinese_simplified"],"盛":["chinese_simplified","chinese_traditional"],"版":["chinese_simplified","chinese_traditional"],"缓":["chinese_simplified"],"净":["chinese_simplified"],"睛":["chinese_simplified","chinese_traditional"],"昌":["chinese_simplified","chinese_traditional"],"婚":["chinese_simplified","chinese_traditional"],"涉":["chinese_simplified","chinese_traditional"],"筒":["chinese_simplified","chinese_traditional"],"嘴":["chinese_simplified","chinese_traditional"],"插":["chinese_simplified","chinese_traditional"],"岸":["chinese_simplified","chinese_traditional"],"朗":["chinese_simplified","chinese_traditional"],"庄":["chinese_simplified"],"街":["chinese_simplified","chinese_traditional"],"藏":["chinese_simplified","chinese_traditional"],"姑":["chinese_simplified","chinese_traditional"],"贸":["chinese_simplified"],"腐":["chinese_simplified","chinese_traditional"],"奴":["chinese_simplified","chinese_traditional"],"啦":["chinese_simplified","chinese_traditional"],"惯":["chinese_simplified"],"乘":["chinese_simplified","chinese_traditional"],"伙":["chinese_simplified"],"恢":["chinese_simplified","chinese_traditional"],"匀":["chinese_simplified"],"纱":["chinese_simplified"],"扎":["chinese_simplified","chinese_traditional"],"辩":["chinese_simplified"],"耳":["chinese_simplified","chinese_traditional"],"彪":["chinese_simplified","chinese_traditional"],"臣":["chinese_simplified","chinese_traditional"],"亿":["chinese_simplified"],"璃":["chinese_simplified","chinese_traditional"],"抵":["chinese_simplified","chinese_traditional"],"脉":["chinese_simplified"],"秀":["chinese_simplified","chinese_traditional"],"萨":["chinese_simplified"],"俄":["chinese_simplified","chinese_traditional"],"网":["chinese_simplified"],"舞":["chinese_simplified","chinese_traditional"],"店":["chinese_simplified","chinese_traditional"],"喷":["chinese_simplified"],"纵":["chinese_simplified"],"寸":["chinese_simplified","chinese_traditional"],"汗":["chinese_simplified","chinese_traditional"],"挂":["chinese_simplified"],"洪":["chinese_simplified","chinese_traditional"],"贺":["chinese_simplified"],"闪":["chinese_simplified"],"柬":["chinese_simplified","chinese_traditional"],"爆":["chinese_simplified","chinese_traditional"],"烯":["chinese_simplified","chinese_traditional"],"津":["chinese_simplified","chinese_traditional"],"稻":["chinese_simplified","chinese_traditional"],"墙":["chinese_simplified"],"软":["chinese_simplified"],"勇":["chinese_simplified","chinese_traditional"],"像":["chinese_simplified","chinese_traditional"],"滚":["chinese_simplified"],"厘":["chinese_simplified","chinese_traditional"],"蒙":["chinese_simplified","chinese_traditional"],"芳":["chinese_simplified","chinese_traditional"],"肯":["chinese_simplified","chinese_traditional"],"坡":["chinese_simplified","chinese_traditional"],"柱":["chinese_simplified","chinese_traditional"],"荡":["chinese_simplified"],"腿":["chinese_simplified","chinese_traditional"],"仪":["chinese_simplified"],"旅":["chinese_simplified","chinese_traditional"],"尾":["chinese_simplified","chinese_traditional"],"轧":["chinese_simplified"],"冰":["chinese_simplified","chinese_traditional"],"贡":["chinese_simplified"],"登":["chinese_simplified","chinese_traditional"],"黎":["chinese_simplified","chinese_traditional"],"削":["chinese_simplified","chinese_traditional"],"钻":["chinese_simplified"],"勒":["chinese_simplified","chinese_traditional"],"逃":["chinese_simplified","chinese_traditional"],"障":["chinese_simplified","chinese_traditional"],"氨":["chinese_simplified","chinese_traditional"],"郭":["chinese_simplified","chinese_traditional"],"峰":["chinese_simplified","chinese_traditional"],"币":["chinese_simplified"],"港":["chinese_simplified","chinese_traditional"],"伏":["chinese_simplified","chinese_traditional"],"轨":["chinese_simplified"],"亩":["chinese_simplified"],"毕":["chinese_simplified"],"擦":["chinese_simplified","chinese_traditional"],"莫":["chinese_simplified","chinese_traditional"],"刺":["chinese_simplified","chinese_traditional"],"浪":["chinese_simplified","chinese_traditional"],"秘":["chinese_simplified","chinese_traditional"],"援":["chinese_simplified","chinese_traditional"],"株":["chinese_simplified","chinese_traditional"],"健":["chinese_simplified","chinese_traditional"],"售":["chinese_simplified","chinese_traditional"],"股":["chinese_simplified","chinese_traditional"],"岛":["chinese_simplified"],"甘":["chinese_simplified","chinese_traditional"],"泡":["chinese_simplified","chinese_traditional"],"睡":["chinese_simplified","chinese_traditional"],"童":["chinese_simplified","chinese_traditional"],"铸":["chinese_simplified"],"汤":["chinese_simplified"],"阀":["chinese_simplified"],"休":["chinese_simplified","chinese_traditional"],"汇":["chinese_simplified"],"舍":["chinese_simplified","chinese_traditional"],"牧":["chinese_simplified","chinese_traditional"],"绕":["chinese_simplified"],"炸":["chinese_simplified","chinese_traditional"],"哲":["chinese_simplified","chinese_traditional"],"磷":["chinese_simplified","chinese_traditional"],"绩":["chinese_simplified"],"朋":["chinese_simplified","chinese_traditional"],"淡":["chinese_simplified","chinese_traditional"],"尖":["chinese_simplified","chinese_traditional"],"启":["chinese_simplified"],"陷":["chinese_simplified","chinese_traditional"],"柴":["chinese_simplified","chinese_traditional"],"呈":["chinese_simplified","chinese_traditional"],"徒":["chinese_simplified","chinese_traditional"],"颜":["chinese_simplified"],"泪":["chinese_simplified"],"稍":["chinese_simplified","chinese_traditional"],"忘":["chinese_simplified","chinese_traditional"],"泵":["chinese_simplified","chinese_traditional"],"蓝":["chinese_simplified"],"拖":["chinese_simplified","chinese_traditional"],"洞":["chinese_simplified","chinese_traditional"],"授":["chinese_simplified","chinese_traditional"],"镜":["chinese_simplified"],"辛":["chinese_simplified","chinese_traditional"],"壮":["chinese_simplified"],"锋":["chinese_simplified"],"贫":["chinese_simplified"],"虚":["chinese_simplified"],"弯":["chinese_simplified"],"摩":["chinese_simplified","chinese_traditional"],"泰":["chinese_simplified","chinese_traditional"],"幼":["chinese_simplified","chinese_traditional"],"廷":["chinese_simplified","chinese_traditional"],"尊":["chinese_simplified","chinese_traditional"],"窗":["chinese_simplified","chinese_traditional"],"纲":["chinese_simplified"],"弄":["chinese_simplified","chinese_traditional"],"隶":["chinese_simplified"],"疑":["chinese_simplified","chinese_traditional"],"氏":["chinese_simplified","chinese_traditional"],"宫":["chinese_simplified"],"姐":["chinese_simplified","chinese_traditional"],"震":["chinese_simplified","chinese_traditional"],"瑞":["chinese_simplified","chinese_traditional"],"怪":["chinese_simplified","chinese_traditional"],"尤":["chinese_simplified","chinese_traditional"],"琴":["chinese_simplified","chinese_traditional"],"循":["chinese_simplified","chinese_traditional"],"描":["chinese_simplified","chinese_traditional"],"膜":["chinese_simplified","chinese_traditional"],"违":["chinese_simplified"],"夹":["chinese_simplified"],"腰":["chinese_simplified","chinese_traditional"],"缘":["chinese_simplified"],"珠":["chinese_simplified","chinese_traditional"],"穷":["chinese_simplified"],"森":["chinese_simplified","chinese_traditional"],"枝":["chinese_simplified","chinese_traditional"],"竹":["chinese_simplified","chinese_traditional"],"沟":["chinese_simplified"],"催":["chinese_simplified","chinese_traditional"],"绳":["chinese_simplified"],"忆":["chinese_simplified"],"邦":["chinese_simplified","chinese_traditional"],"剩":["chinese_simplified","chinese_traditional"],"幸":["chinese_simplified","chinese_traditional"],"浆":["chinese_simplified"],"栏":["chinese_simplified"],"拥":["chinese_simplified"],"牙":["chinese_simplified","chinese_traditional"],"贮":["chinese_simplified"],"礼":["chinese_simplified"],"滤":["chinese_simplified"],"钠":["chinese_simplified"],"纹":["chinese_simplified"],"罢":["chinese_simplified"],"拍":["chinese_simplified","chinese_traditional"],"咱":["chinese_simplified","chinese_traditional"],"喊":["chinese_simplified","chinese_traditional"],"袖":["chinese_simplified","chinese_traditional"],"埃":["chinese_simplified","chinese_traditional"],"勤":["chinese_simplified","chinese_traditional"],"罚":["chinese_simplified"],"焦":["chinese_simplified","chinese_traditional"],"潜":["chinese_simplified"],"伍":["chinese_simplified","chinese_traditional"],"墨":["chinese_simplified","chinese_traditional"],"欲":["chinese_simplified","chinese_traditional"],"缝":["chinese_simplified"],"姓":["chinese_simplified","chinese_traditional"],"刊":["chinese_simplified","chinese_traditional"],"饱":["chinese_simplified"],"仿":["chinese_simplified","chinese_traditional"],"奖":["chinese_simplified"],"铝":["chinese_simplified"],"鬼":["chinese_simplified","chinese_traditional"],"丽":["chinese_simplified"],"跨":["chinese_simplified","chinese_traditional"],"默":["chinese_simplified","chinese_traditional"],"挖":["chinese_simplified","chinese_traditional"],"链":["chinese_simplified"],"扫":["chinese_simplified"],"喝":["chinese_simplified","chinese_traditional"],"袋":["chinese_simplified","chinese_traditional"],"炭":["chinese_simplified","chinese_traditional"],"污":["chinese_simplified","chinese_traditional"],"幕":["chinese_simplified","chinese_traditional"],"诸":["chinese_simplified"],"弧":["chinese_simplified","chinese_traditional"],"励":["chinese_simplified"],"梅":["chinese_simplified","chinese_traditional"],"奶":["chinese_simplified","chinese_traditional"],"洁":["chinese_simplified"],"灾":["chinese_simplified"],"舟":["chinese_simplified","chinese_traditional"],"鉴":["chinese_simplified"],"苯":["chinese_simplified","chinese_traditional"],"讼":["chinese_simplified"],"抱":["chinese_simplified","chinese_traditional"],"毁":["chinese_simplified"],"懂":["chinese_simplified","chinese_traditional"],"寒":["chinese_simplified","chinese_traditional"],"智":["chinese_simplified","chinese_traditional"],"埔":["chinese_simplified","chinese_traditional"],"寄":["chinese_simplified","chinese_traditional"],"届":["chinese_simplified"],"跃":["chinese_simplified"],"渡":["chinese_simplified","chinese_traditional"],"挑":["chinese_simplified","chinese_traditional"],"丹":["chinese_simplified","chinese_traditional"],"艰":["chinese_simplified"],"贝":["chinese_simplified"],"碰":["chinese_simplified","chinese_traditional"],"拔":["chinese_simplified","chinese_traditional"],"爹":["chinese_simplified","chinese_traditional"],"戴":["chinese_simplified","chinese_traditional"],"码":["chinese_simplified"],"梦":["chinese_simplified"],"芽":["chinese_simplified","chinese_traditional"],"熔":["chinese_simplified","chinese_traditional"],"赤":["chinese_simplified","chinese_traditional"],"渔":["chinese_simplified"],"哭":["chinese_simplified","chinese_traditional"],"敬":["chinese_simplified","chinese_traditional"],"颗":["chinese_simplified"],"奔":["chinese_simplified","chinese_traditional"],"铅":["chinese_simplified"],"仲":["chinese_simplified","chinese_traditional"],"虎":["chinese_simplified","chinese_traditional"],"稀":["chinese_simplified","chinese_traditional"],"妹":["chinese_simplified","chinese_traditional"],"乏":["chinese_simplified","chinese_traditional"],"珍":["chinese_simplified","chinese_traditional"],"申":["chinese_simplified","chinese_traditional"],"桌":["chinese_simplified","chinese_traditional"],"遵":["chinese_simplified","chinese_traditional"],"允":["chinese_simplified","chinese_traditional"],"隆":["chinese_simplified","chinese_traditional"],"螺":["chinese_simplified","chinese_traditional"],"仓":["chinese_simplified"],"魏":["chinese_simplified","chinese_traditional"],"锐":["chinese_simplified"],"晓":["chinese_simplified"],"氮":["chinese_simplified","chinese_traditional"],"兼":["chinese_simplified","chinese_traditional"],"隐":["chinese_simplified"],"碍":["chinese_simplified"],"赫":["chinese_simplified","chinese_traditional"],"拨":["chinese_simplified"],"忠":["chinese_simplified","chinese_traditional"],"肃":["chinese_simplified"],"缸":["chinese_simplified","chinese_traditional"],"牵":["chinese_simplified"],"抢":["chinese_simplified"],"博":["chinese_simplified","chinese_traditional"],"巧":["chinese_simplified","chinese_traditional"],"壳":["chinese_simplified"],"兄":["chinese_simplified","chinese_traditional"],"杜":["chinese_simplified","chinese_traditional"],"讯":["chinese_simplified"],"诚":["chinese_simplified"],"碧":["chinese_simplified","chinese_traditional"],"祥":["chinese_simplified","chinese_traditional"],"柯":["chinese_simplified","chinese_traditional"],"页":["chinese_simplified"],"巡":["chinese_simplified","chinese_traditional"],"矩":["chinese_simplified","chinese_traditional"],"悲":["chinese_simplified","chinese_traditional"],"灌":["chinese_simplified","chinese_traditional"],"龄":["chinese_simplified"],"伦":["chinese_simplified"],"票":["chinese_simplified","chinese_traditional"],"寻":["chinese_simplified"],"桂":["chinese_simplified","chinese_traditional"],"铺":["chinese_simplified"],"圣":["chinese_simplified"],"恐":["chinese_simplified","chinese_traditional"],"恰":["chinese_simplified","chinese_traditional"],"郑":["chinese_simplified"],"趣":["chinese_simplified","chinese_traditional"],"抬":["chinese_simplified","chinese_traditional"],"荒":["chinese_simplified","chinese_traditional"],"腾":["chinese_simplified"],"贴":["chinese_simplified"],"柔":["chinese_simplified","chinese_traditional"],"滴":["chinese_simplified","chinese_traditional"],"猛":["chinese_simplified","chinese_traditional"],"阔":["chinese_simplified"],"辆":["chinese_simplified"],"妻":["chinese_simplified","chinese_traditional"],"填":["chinese_simplified","chinese_traditional"],"撤":["chinese_simplified","chinese_traditional"],"储":["chinese_simplified"],"签":["chinese_simplified"],"闹":["chinese_simplified"],"扰":["chinese_simplified"],"紫":["chinese_simplified","chinese_traditional"],"砂":["chinese_simplified","chinese_traditional"],"递":["chinese_simplified"],"戏":["chinese_simplified"],"吊":["chinese_simplified","chinese_traditional"],"陶":["chinese_simplified","chinese_traditional"],"伐":["chinese_simplified","chinese_traditional"],"喂":["chinese_simplified"],"疗":["chinese_simplified"],"瓶":["chinese_simplified","chinese_traditional"],"婆":["chinese_simplified","chinese_traditional"],"抚":["chinese_simplified"],"臂":["chinese_simplified","chinese_traditional"],"摸":["chinese_simplified","chinese_traditional"],"忍":["chinese_simplified","chinese_traditional"],"虾":["chinese_simplified"],"蜡":["chinese_simplified"],"邻":["chinese_simplified"],"胸":["chinese_simplified","chinese_traditional"],"巩":["chinese_simplified"],"挤":["chinese_simplified"],"偶":["chinese_simplified","chinese_traditional"],"弃":["chinese_simplified"],"槽":["chinese_simplified","chinese_traditional"],"劲":["chinese_simplified"],"乳":["chinese_simplified","chinese_traditional"],"邓":["chinese_simplified"],"吉":["chinese_simplified","chinese_traditional"],"仁":["chinese_simplified","chinese_traditional"],"烂":["chinese_simplified"],"砖":["chinese_simplified"],"租":["chinese_simplified","chinese_traditional"],"乌":["chinese_simplified"],"舰":["chinese_simplified"],"伴":["chinese_simplified","chinese_traditional"],"瓜":["chinese_simplified","chinese_traditional"],"浅":["chinese_simplified"],"丙":["chinese_simplified","chinese_traditional"],"暂":["chinese_simplified"],"燥":["chinese_simplified","chinese_traditional"],"橡":["chinese_simplified","chinese_traditional"],"柳":["chinese_simplified","chinese_traditional"],"迷":["chinese_simplified","chinese_traditional"],"暖":["chinese_simplified","chinese_traditional"],"牌":["chinese_simplified","chinese_traditional"],"秧":["chinese_simplified","chinese_traditional"],"胆":["chinese_simplified"],"详":["chinese_simplified"],"簧":["chinese_simplified","chinese_traditional"],"踏":["chinese_simplified","chinese_traditional"],"瓷":["chinese_simplified","chinese_traditional"],"谱":["chinese_simplified"],"呆":["chinese_simplified","chinese_traditional"],"宾":["chinese_simplified"],"糊":["chinese_simplified","chinese_traditional"],"洛":["chinese_simplified","chinese_traditional"],"辉":["chinese_simplified"],"愤":["chinese_simplified"],"竞":["chinese_simplified"],"隙":["chinese_simplified","chinese_traditional"],"怒":["chinese_simplified","chinese_traditional"],"粘":["chinese_simplified","chinese_traditional"],"乃":["chinese_simplified","chinese_traditional"],"绪":["chinese_simplified"],"肩":["chinese_simplified","chinese_traditional"],"籍":["chinese_simplified","chinese_traditional"],"敏":["chinese_simplified","chinese_traditional"],"涂":["chinese_simplified"],"熙":["chinese_simplified","chinese_traditional"],"皆":["chinese_simplified","chinese_traditional"],"侦":["chinese_simplified"],"悬":["chinese_simplified"],"掘":["chinese_simplified","chinese_traditional"],"享":["chinese_simplified","chinese_traditional"],"纠":["chinese_simplified"],"醒":["chinese_simplified","chinese_traditional"],"狂":["chinese_simplified","chinese_traditional"],"锁":["chinese_simplified"],"淀":["chinese_simplified","chinese_traditional"],"恨":["chinese_simplified","chinese_traditional"],"牲":["chinese_simplified","chinese_traditional"],"霸":["chinese_simplified","chinese_traditional"],"爬":["chinese_simplified","chinese_traditional"],"赏":["chinese_simplified"],"逆":["chinese_simplified","chinese_traditional"],"玩":["chinese_simplified","chinese_traditional"],"陵":["chinese_simplified","chinese_traditional"],"祝":["chinese_simplified","chinese_traditional"],"秒":["chinese_simplified","chinese_traditional"],"浙":["chinese_simplified","chinese_traditional"],"貌":["chinese_simplified","chinese_traditional"],"役":["chinese_simplified","chinese_traditional"],"彼":["chinese_simplified","chinese_traditional"],"悉":["chinese_simplified","chinese_traditional"],"鸭":["chinese_simplified"],"趋":["chinese_simplified"],"凤":["chinese_simplified"],"晨":["chinese_simplified","chinese_traditional"],"畜":["chinese_simplified","chinese_traditional"],"辈":["chinese_simplified"],"秩":["chinese_simplified","chinese_traditional"],"卵":["chinese_simplified","chinese_traditional"],"署":["chinese_simplified","chinese_traditional"],"梯":["chinese_simplified","chinese_traditional"],"炎":["chinese_simplified","chinese_traditional"],"滩":["chinese_simplified"],"棋":["chinese_simplified","chinese_traditional"],"驱":["chinese_simplified"],"筛":["chinese_simplified"],"峡":["chinese_simplified"],"冒":["chinese_simplified","chinese_traditional"],"啥":["chinese_simplified","chinese_traditional"],"寿":["chinese_simplified"],"译":["chinese_simplified"],"浸":["chinese_simplified","chinese_traditional"],"泉":["chinese_simplified","chinese_traditional"],"帽":["chinese_simplified","chinese_traditional"],"迟":["chinese_simplified"],"硅":["chinese_simplified"],"疆":["chinese_simplified","chinese_traditional"],"贷":["chinese_simplified"],"漏":["chinese_simplified","chinese_traditional"],"稿":["chinese_simplified","chinese_traditional"],"冠":["chinese_simplified","chinese_traditional"],"嫩":["chinese_simplified","chinese_traditional"],"胁":["chinese_simplified"],"芯":["chinese_simplified","chinese_traditional"],"牢":["chinese_simplified","chinese_traditional"],"叛":["chinese_simplified","chinese_traditional"],"蚀":["chinese_simplified"],"奥":["chinese_simplified"],"鸣":["chinese_simplified"],"岭":["chinese_simplified"],"羊":["chinese_simplified","chinese_traditional"],"凭":["chinese_simplified"],"串":["chinese_simplified","chinese_traditional"],"塘":["chinese_simplified","chinese_traditional"],"绘":["chinese_simplified"],"酵":["chinese_simplified","chinese_traditional"],"融":["chinese_simplified","chinese_traditional"],"盆":["chinese_simplified","chinese_traditional"],"锡":["chinese_simplified"],"庙":["chinese_simplified"],"筹":["chinese_simplified"],"冻":["chinese_simplified"],"辅":["chinese_simplified"],"摄":["chinese_simplified"],"袭":["chinese_simplified"],"筋":["chinese_simplified","chinese_traditional"],"拒":["chinese_simplified","chinese_traditional"],"僚":["chinese_simplified","chinese_traditional"],"旱":["chinese_simplified","chinese_traditional"],"钾":["chinese_simplified"],"鸟":["chinese_simplified"],"漆":["chinese_simplified","chinese_traditional"],"沈":["chinese_simplified","chinese_traditional"],"眉":["chinese_simplified","chinese_traditional"],"疏":["chinese_simplified","chinese_traditional"],"添":["chinese_simplified","chinese_traditional"],"棒":["chinese_simplified","chinese_traditional"],"穗":["chinese_simplified","chinese_traditional"],"硝":["chinese_simplified","chinese_traditional"],"韩":["chinese_simplified"],"逼":["chinese_simplified","chinese_traditional"],"扭":["chinese_simplified","chinese_traditional"],"侨":["chinese_simplified"],"凉":["chinese_simplified"],"挺":["chinese_simplified","chinese_traditional"],"碗":["chinese_simplified","chinese_traditional"],"栽":["chinese_simplified","chinese_traditional"],"炒":["chinese_simplified","chinese_traditional"],"杯":["chinese_simplified","chinese_traditional"],"患":["chinese_simplified","chinese_traditional"],"馏":["chinese_simplified"],"劝":["chinese_simplified"],"豪":["chinese_simplified","chinese_traditional"],"辽":["chinese_simplified"],"勃":["chinese_simplified","chinese_traditional"],"鸿":["chinese_simplified"],"旦":["chinese_simplified","chinese_traditional"],"吏":["chinese_simplified","chinese_traditional"],"拜":["chinese_simplified","chinese_traditional"],"狗":["chinese_simplified","chinese_traditional"],"埋":["chinese_simplified","chinese_traditional"],"辊":["chinese_simplified"],"掩":["chinese_simplified","chinese_traditional"],"饮":["chinese_simplified"],"搬":["chinese_simplified","chinese_traditional"],"骂":["chinese_simplified"],"辞":["chinese_simplified"],"勾":["chinese_simplified","chinese_traditional"],"扣":["chinese_simplified","chinese_traditional"],"估":["chinese_simplified","chinese_traditional"],"蒋":["chinese_simplified"],"绒":["chinese_simplified"],"雾":["chinese_simplified"],"丈":["chinese_simplified","chinese_traditional"],"朵":["chinese_simplified","chinese_traditional"],"姆":["chinese_simplified","chinese_traditional"],"拟":["chinese_simplified"],"宇":["chinese_simplified","chinese_traditional"],"辑":["chinese_simplified"],"陕":["chinese_simplified"],"雕":["chinese_simplified","chinese_traditional"],"偿":["chinese_simplified"],"蓄":["chinese_simplified","chinese_traditional"],"崇":["chinese_simplified","chinese_traditional"],"剪":["chinese_simplified","chinese_traditional"],"倡":["chinese_simplified","chinese_traditional"],"厅":["chinese_simplified"],"咬":["chinese_simplified","chinese_traditional"],"驶":["chinese_simplified"],"薯":["chinese_simplified","chinese_traditional"],"刷":["chinese_simplified","chinese_traditional"],"斥":["chinese_simplified","chinese_traditional"],"番":["chinese_simplified","chinese_traditional"],"赋":["chinese_simplified"],"奉":["chinese_simplified","chinese_traditional"],"佛":["chinese_simplified","chinese_traditional"],"浇":["chinese_simplified"],"漫":["chinese_simplified","chinese_traditional"],"曼":["chinese_simplified","chinese_traditional"],"扇":["chinese_simplified","chinese_traditional"],"钙":["chinese_simplified"],"桃":["chinese_simplified","chinese_traditional"],"扶":["chinese_simplified","chinese_traditional"],"仔":["chinese_simplified","chinese_traditional"],"返":["chinese_simplified","chinese_traditional"],"俗":["chinese_simplified","chinese_traditional"],"亏":["chinese_simplified"],"腔":["chinese_simplified","chinese_traditional"],"鞋":["chinese_simplified","chinese_traditional"],"棱":["chinese_simplified","chinese_traditional"],"覆":["chinese_simplified","chinese_traditional"],"框":["chinese_simplified","chinese_traditional"],"悄":["chinese_simplified","chinese_traditional"],"叔":["chinese_simplified","chinese_traditional"],"撞":["chinese_simplified","chinese_traditional"],"骗":["chinese_simplified"],"勘":["chinese_simplified","chinese_traditional"],"旺":["chinese_simplified","chinese_traditional"],"沸":["chinese_simplified","chinese_traditional"],"孤":["chinese_simplified","chinese_traditional"],"吐":["chinese_simplified","chinese_traditional"],"孟":["chinese_simplified","chinese_traditional"],"渠":["chinese_simplified","chinese_traditional"],"屈":["chinese_simplified","chinese_traditional"],"疾":["chinese_simplified","chinese_traditional"],"妙":["chinese_simplified","chinese_traditional"],"惜":["chinese_simplified","chinese_traditional"],"仰":["chinese_simplified","chinese_traditional"],"狠":["chinese_simplified","chinese_traditional"],"胀":["chinese_simplified"],"谐":["chinese_simplified"],"抛":["chinese_simplified"],"霉":["chinese_simplified"],"桑":["chinese_simplified","chinese_traditional"],"岗":["chinese_simplified"],"嘛":["chinese_simplified","chinese_traditional"],"衰":["chinese_simplified","chinese_traditional"],"盗":["chinese_simplified"],"渗":["chinese_simplified"],"脏":["chinese_simplified"],"赖":["chinese_simplified"],"涌":["chinese_simplified"],"甜":["chinese_simplified","chinese_traditional"],"曹":["chinese_simplified","chinese_traditional"],"阅":["chinese_simplified"],"肌":["chinese_simplified","chinese_traditional"],"哩":["chinese_simplified","chinese_traditional"],"厉":["chinese_simplified"],"烃":["chinese_simplified"],"纬":["chinese_simplified"],"毅":["chinese_simplified","chinese_traditional"],"昨":["chinese_simplified","chinese_traditional"],"伪":["chinese_simplified"],"症":["chinese_simplified","chinese_traditional"],"煮":["chinese_simplified","chinese_traditional"],"叹":["chinese_simplified"],"钉":["chinese_simplified"],"搭":["chinese_simplified","chinese_traditional"],"茎":["chinese_simplified"],"笼":["chinese_simplified"],"酷":["chinese_simplified","chinese_traditional"],"偷":["chinese_simplified","chinese_traditional"],"弓":["chinese_simplified","chinese_traditional"],"锥":["chinese_simplified"],"恒":["chinese_simplified"],"杰":["chinese_simplified"],"坑":["chinese_simplified","chinese_traditional"],"鼻":["chinese_simplified","chinese_traditional"],"翼":["chinese_simplified","chinese_traditional"],"纶":["chinese_simplified"],"叙":["chinese_simplified"],"狱":["chinese_simplified"],"逮":["chinese_simplified","chinese_traditional"],"罐":["chinese_simplified","chinese_traditional"],"络":["chinese_simplified"],"棚":["chinese_simplified","chinese_traditional"],"抑":["chinese_simplified","chinese_traditional"],"膨":["chinese_simplified","chinese_traditional"],"蔬":["chinese_simplified","chinese_traditional"],"寺":["chinese_simplified","chinese_traditional"],"骤":["chinese_simplified"],"穆":["chinese_simplified","chinese_traditional"],"冶":["chinese_simplified","chinese_traditional"],"枯":["chinese_simplified","chinese_traditional"],"册":["chinese_simplified"],"尸":["chinese_simplified"],"凸":["chinese_simplified","chinese_traditional"],"绅":["chinese_simplified"],"坯":["chinese_simplified","chinese_traditional"],"牺":["chinese_simplified"],"焰":["chinese_simplified","chinese_traditional"],"轰":["chinese_simplified"],"欣":["chinese_simplified","chinese_traditional"],"晋":["chinese_simplified"],"瘦":["chinese_simplified","chinese_traditional"],"御":["chinese_simplified"],"锭":["chinese_simplified"],"锦":["chinese_simplified"],"丧":["chinese_simplified"],"旬":["chinese_simplified","chinese_traditional"],"锻":["chinese_simplified"],"垄":["chinese_simplified"],"搜":["chinese_simplified","chinese_traditional"],"扑":["chinese_simplified"],"邀":["chinese_simplified","chinese_traditional"],"亭":["chinese_simplified","chinese_traditional"],"酯":["chinese_simplified","chinese_traditional"],"迈":["chinese_simplified"],"舒":["chinese_simplified","chinese_traditional"],"脆":["chinese_simplified","chinese_traditional"],"酶":["chinese_simplified","chinese_traditional"],"闲":["chinese_simplified"],"忧":["chinese_simplified"],"酚":["chinese_simplified","chinese_traditional"],"顽":["chinese_simplified"],"羽":["chinese_simplified","chinese_traditional"],"涨":["chinese_simplified"],"卸":["chinese_simplified","chinese_traditional"],"仗":["chinese_simplified","chinese_traditional"],"陪":["chinese_simplified","chinese_traditional"],"辟":["chinese_simplified"],"惩":["chinese_simplified"],"杭":["chinese_simplified","chinese_traditional"],"姚":["chinese_simplified","chinese_traditional"],"肚":["chinese_simplified","chinese_traditional"],"捉":["chinese_simplified","chinese_traditional"],"飘":["chinese_simplified"],"漂":["chinese_simplified","chinese_traditional"],"昆":["chinese_simplified","chinese_traditional"],"欺":["chinese_simplified","chinese_traditional"],"吾":["chinese_simplified","chinese_traditional"],"郎":["chinese_simplified","chinese_traditional"],"烷":["chinese_simplified","chinese_traditional"],"汁":["chinese_simplified","chinese_traditional"],"呵":["chinese_simplified","chinese_traditional"],"饰":["chinese_simplified"],"萧":["chinese_simplified"],"雅":["chinese_simplified","chinese_traditional"],"邮":["chinese_simplified"],"迁":["chinese_simplified"],"燕":["chinese_simplified","chinese_traditional"],"撒":["chinese_simplified","chinese_traditional"],"姻":["chinese_simplified","chinese_traditional"],"赴":["chinese_simplified","chinese_traditional"],"宴":["chinese_simplified","chinese_traditional"],"烦":["chinese_simplified"],"债":["chinese_simplified"],"帐":["chinese_simplified"],"斑":["chinese_simplified","chinese_traditional"],"铃":["chinese_simplified"],"旨":["chinese_simplified","chinese_traditional"],"醇":["chinese_simplified","chinese_traditional"],"董":["chinese_simplified","chinese_traditional"],"饼":["chinese_simplified"],"雏":["chinese_simplified"],"姿":["chinese_simplified","chinese_traditional"],"拌":["chinese_simplified","chinese_traditional"],"傅":["chinese_simplified","chinese_traditional"],"腹":["chinese_simplified","chinese_traditional"],"妥":["chinese_simplified","chinese_traditional"],"揉":["chinese_simplified","chinese_traditional"],"贤":["chinese_simplified"],"拆":["chinese_simplified","chinese_traditional"],"歪":["chinese_simplified","chinese_traditional"],"葡":["chinese_simplified","chinese_traditional"],"胺":["chinese_simplified","chinese_traditional"],"丢":["chinese_simplified"],"浩":["chinese_simplified","chinese_traditional"],"徽":["chinese_simplified","chinese_traditional"],"昂":["chinese_simplified","chinese_traditional"],"垫":["chinese_simplified"],"挡":["chinese_simplified"],"览":["chinese_simplified"],"贪":["chinese_simplified"],"慰":["chinese_simplified","chinese_traditional"],"缴":["chinese_simplified"],"汪":["chinese_simplified","chinese_traditional"],"慌":["chinese_simplified","chinese_traditional"],"冯":["chinese_simplified"],"诺":["chinese_simplified"],"姜":["chinese_simplified","chinese_traditional"],"谊":["chinese_simplified"],"凶":["chinese_simplified"],"劣":["chinese_simplified","chinese_traditional"],"诬":["chinese_simplified"],"耀":["chinese_simplified","chinese_traditional"],"昏":["chinese_simplified","chinese_traditional"],"躺":["chinese_simplified","chinese_traditional"],"盈":["chinese_simplified","chinese_traditional"],"骑":["chinese_simplified"],"乔":["chinese_simplified"],"溪":["chinese_simplified","chinese_traditional"],"丛":["chinese_simplified"],"卢":["chinese_simplified"],"抹":["chinese_simplified","chinese_traditional"],"闷":["chinese_simplified"],"咨":["chinese_simplified"],"刮":["chinese_simplified","chinese_traditional"],"驾":["chinese_simplified"],"缆":["chinese_simplified"],"悟":["chinese_simplified","chinese_traditional"],"摘":["chinese_simplified","chinese_traditional"],"铒":["chinese_simplified"],"掷":["chinese_simplified"],"颇":["chinese_simplified"],"幻":["chinese_simplified","chinese_traditional"],"柄":["chinese_simplified","chinese_traditional"],"惠":["chinese_simplified","chinese_traditional"],"惨":["chinese_simplified"],"佳":["chinese_simplified","chinese_traditional"],"仇":["chinese_simplified","chinese_traditional"],"腊":["chinese_simplified"],"窝":["chinese_simplified"],"涤":["chinese_simplified"],"剑":["chinese_simplified"],"瞧":["chinese_simplified","chinese_traditional"],"堡":["chinese_simplified","chinese_traditional"],"泼":["chinese_simplified"],"葱":["chinese_simplified"],"罩":["chinese_simplified","chinese_traditional"],"霍":["chinese_simplified","chinese_traditional"],"捞":["chinese_simplified"],"胎":["chinese_simplified","chinese_traditional"],"苍":["chinese_simplified"],"滨":["chinese_simplified"],"俩":["chinese_simplified"],"捅":["chinese_simplified","chinese_traditional"],"湘":["chinese_simplified","chinese_traditional"],"砍":["chinese_simplified","chinese_traditional"],"霞":["chinese_simplified","chinese_traditional"],"邵":["chinese_simplified","chinese_traditional"],"萄":["chinese_simplified","chinese_traditional"],"疯":["chinese_simplified"],"淮":["chinese_simplified","chinese_traditional"],"遂":["chinese_simplified","chinese_traditional"],"熊":["chinese_simplified","chinese_traditional"],"粪":["chinese_simplified"],"烘":["chinese_simplified","chinese_traditional"],"宿":["chinese_simplified","chinese_traditional"],"档":["chinese_simplified"],"戈":["chinese_simplified","chinese_traditional"],"驳":["chinese_simplified"],"嫂":["chinese_simplified","chinese_traditional"],"裕":["chinese_simplified","chinese_traditional"],"徙":["chinese_simplified","chinese_traditional"],"箭":["chinese_simplified","chinese_traditional"],"捐":["chinese_simplified","chinese_traditional"],"肠":["chinese_simplified"],"撑":["chinese_simplified"],"晒":["chinese_simplified"],"辨":["chinese_simplified","chinese_traditional"],"殿":["chinese_simplified","chinese_traditional"],"莲":["chinese_simplified"],"摊":["chinese_simplified"],"搅":["chinese_simplified"],"酱":["chinese_simplified"],"屏":["chinese_simplified","chinese_traditional"],"疫":["chinese_simplified","chinese_traditional"],"哀":["chinese_simplified","chinese_traditional"],"蔡":["chinese_simplified","chinese_traditional"],"堵":["chinese_simplified","chinese_traditional"],"沫":["chinese_simplified","chinese_traditional"],"皱":["chinese_simplified"],"畅":["chinese_simplified"],"叠":["chinese_simplified"],"阁":["chinese_simplified"],"莱":["chinese_simplified"],"敲":["chinese_simplified","chinese_traditional"],"辖":["chinese_simplified"],"钩":["chinese_simplified"],"痕":["chinese_simplified","chinese_traditional"],"坝":["chinese_simplified"],"巷":["chinese_simplified","chinese_traditional"],"饿":["chinese_simplified"],"祸":["chinese_simplified"],"丘":["chinese_simplified","chinese_traditional"],"玄":["chinese_simplified","chinese_traditional"],"溜":["chinese_simplified","chinese_traditional"],"曰":["chinese_simplified","chinese_traditional"],"逻":["chinese_simplified"],"彭":["chinese_simplified","chinese_traditional"],"尝":["chinese_simplified"],"卿":["chinese_simplified","chinese_traditional"],"妨":["chinese_simplified","chinese_traditional"],"艇":["chinese_simplified","chinese_traditional"],"吞":["chinese_simplified","chinese_traditional"],"韦":["chinese_simplified"],"怨":["chinese_simplified","chinese_traditional"],"矮":["chinese_simplified","chinese_traditional"],"歇":["chinese_simplified","chinese_traditional"],"這":["chinese_traditional"],"為":["chinese_traditional"],"個":["chinese_traditional"],"國":["chinese_traditional"],"時":["chinese_traditional"],"來":["chinese_traditional"],"們":["chinese_traditional"],"於":["chinese_traditional"],"對":["chinese_traditional"],"會":["chinese_traditional"],"發":["chinese_traditional"],"動":["chinese_traditional"],"過":["chinese_traditional"],"說":["chinese_traditional"],"產":["chinese_traditional"],"種":["chinese_traditional"],"後":["chinese_traditional"],"學":["chinese_traditional"],"經":["chinese_traditional"],"進":["chinese_traditional"],"著":["chinese_traditional"],"電":["chinese_traditional"],"裡":["chinese_traditional"],"現":["chinese_traditional"],"實":["chinese_traditional"],"兩":["chinese_traditional"],"體":["chinese_traditional"],"機":["chinese_traditional"],"當":["chinese_traditional"],"點":["chinese_traditional"],"從":["chinese_traditional"],"業":["chinese_traditional"],"應":["chinese_traditional"],"開":["chinese_traditional"],"還":["chinese_traditional"],"義":["chinese_traditional"],"間":["chinese_traditional"],"樣":["chinese_traditional"],"與":["chinese_traditional"],"關":["chinese_traditional"],"線":["chinese_traditional"],"內":["chinese_traditional"],"數":["chinese_traditional"],"麼":["chinese_traditional"],"質":["chinese_traditional"],"氣":["chinese_traditional"],"變":["chinese_traditional"],"條":["chinese_traditional"],"沒":["chinese_traditional"],"結":["chinese_traditional"],"問":["chinese_traditional"],"無":["chinese_traditional"],"軍":["chinese_traditional"],"並":["chinese_traditional"],"題":["chinese_traditional"],"黨":["chinese_traditional"],"員":["chinese_traditional"],"總":["chinese_traditional"],"設":["chinese_traditional"],"長":["chinese_traditional"],"頭":["chinese_traditional"],"資":["chinese_traditional"],"邊":["chinese_traditional"],"級":["chinese_traditional"],"圖":["chinese_traditional"],"統":["chinese_traditional"],"較":["chinese_traditional"],"將":["chinese_traditional"],"組":["chinese_traditional"],"見":["chinese_traditional"],"計":["chinese_traditional"],"別":["chinese_traditional"],"論":["chinese_traditional"],"運":["chinese_traditional"],"農":["chinese_traditional"],"幾":["chinese_traditional"],"區":["chinese_traditional"],"強":["chinese_traditional"],"決":["chinese_traditional"],"幹":["chinese_traditional"],"戰":["chinese_traditional"],"則":["chinese_traditional"],"據":["chinese_traditional"],"處":["chinese_traditional"],"隊":["chinese_traditional"],"給":["chinese_traditional"],"門":["chinese_traditional"],"規":["chinese_traditional"],"熱":["chinese_traditional"],"領":["chinese_traditional"],"東":["chinese_traditional"],"導":["chinese_traditional"],"壓":["chinese_traditional"],"爭":["chinese_traditional"],"濟":["chinese_traditional"],"階":["chinese_traditional"],"術":["chinese_traditional"],"極":["chinese_traditional"],"聯":["chinese_traditional"],"認":["chinese_traditional"],"權":["chinese_traditional"],"證":["chinese_traditional"],"採":["chinese_traditional"],"轉":["chinese_traditional"],"單":["chinese_traditional"],"風":["chinese_traditional"],"帶":["chinese_traditional"],"場":["chinese_traditional"],"車":["chinese_traditional"],"務":["chinese_traditional"],"萬":["chinese_traditional"],"達":["chinese_traditional"],"積":["chinese_traditional"],"議":["chinese_traditional"],"聲":["chinese_traditional"],"報":["chinese_traditional"],"鬥":["chinese_traditional"],"類":["chinese_traditional"],"離":["chinese_traditional"],"華":["chinese_traditional"],"確":["chinese_traditional"],"張":["chinese_traditional"],"馬":["chinese_traditional"],"節":["chinese_traditional"],"話":["chinese_traditional"],"況":["chinese_traditional"],"溫":["chinese_traditional"],"傳":["chinese_traditional"],"許":["chinese_traditional"],"廣":["chinese_traditional"],"記":["chinese_traditional"],"觀":["chinese_traditional"],"織":["chinese_traditional"],"裝":["chinese_traditional"],"眾":["chinese_traditional"],"書":["chinese_traditional"],"兒":["chinese_traditional"],"須":["chinese_traditional"],"際":["chinese_traditional"],"驗":["chinese_traditional"],"連":["chinese_traditional"],"斷":["chinese_traditional"],"難":["chinese_traditional"],"礦":["chinese_traditional"],"週":["chinese_traditional"],"備":["chinese_traditional"],"辦":["chinese_traditional"],"習":["chinese_traditional"],"響":["chinese_traditional"],"約":["chinese_traditional"],"勞":["chinese_traditional"],"團":["chinese_traditional"],"歷":["chinese_traditional"],"構":["chinese_traditional"],"稱":["chinese_traditional"],"準":["chinese_traditional"],"號":["chinese_traditional"],"維":["chinese_traditional"],"劃":["chinese_traditional"],"選":["chinese_traditional"],"標":["chinese_traditional"],"寫":["chinese_traditional"],"親":["chinese_traditional"],"養":["chinese_traditional"],"層":["chinese_traditional"],"卻":["chinese_traditional"],"專":["chinese_traditional"],"狀":["chinese_traditional"],"廠":["chinese_traditional"],"識":["chinese_traditional"],"適":["chinese_traditional"],"屬":["chinese_traditional"],"圓":["chinese_traditional"],"調":["chinese_traditional"],"滿":["chinese_traditional"],"縣":["chinese_traditional"],"參":["chinese_traditional"],"紅":["chinese_traditional"],"細":["chinese_traditional"],"聽":["chinese_traditional"],"該":["chinese_traditional"],"鐵":["chinese_traditional"],"價":["chinese_traditional"],"嚴":["chinese_traditional"],"隨":["chinese_traditional"],"蘇":["chinese_traditional"],"爾":["chinese_traditional"],"講":["chinese_traditional"],"黃":["chinese_traditional"],"顯":["chinese_traditional"],"談":["chinese_traditional"],"藝":["chinese_traditional"],"營":["chinese_traditional"],"項":["chinese_traditional"],"舉":["chinese_traditional"],"勢":["chinese_traditional"],"幫":["chinese_traditional"],"輪":["chinese_traditional"],"亞":["chinese_traditional"],"師":["chinese_traditional"],"圍":["chinese_traditional"],"遠":["chinese_traditional"],"態":["chinese_traditional"],"減":["chinese_traditional"],"樹":["chinese_traditional"],"葉":["chinese_traditional"],"魚":["chinese_traditional"],"視":["chinese_traditional"],"僅":["chinese_traditional"],"費":["chinese_traditional"],"緊":["chinese_traditional"],"愛":["chinese_traditional"],"續":["chinese_traditional"],"輕":["chinese_traditional"],"試":["chinese_traditional"],"護":["chinese_traditional"],"練":["chinese_traditional"],"負":["chinese_traditional"],"擊":["chinese_traditional"],"繼":["chinese_traditional"],"興":["chinese_traditional"],"餘":["chinese_traditional"],"堅":["chinese_traditional"],"輸":["chinese_traditional"],"夠":["chinese_traditional"],"筆":["chinese_traditional"],"佔":["chinese_traditional"],"財":["chinese_traditional"],"職":["chinese_traditional"],"覺":["chinese_traditional"],"漢":["chinese_traditional"],"畫":["chinese_traditional"],"雖":["chinese_traditional"],"雜":["chinese_traditional"],"飛":["chinese_traditional"],"檢":["chinese_traditional"],"昇":["chinese_traditional"],"陽":["chinese_traditional"],"創":["chinese_traditional"],"壞":["chinese_traditional"],"徑":["chinese_traditional"],"換":["chinese_traditional"],"鋼":["chinese_traditional"],"責":["chinese_traditional"],"簡":["chinese_traditional"],"錢":["chinese_traditional"],"盡":["chinese_traditional"],"衝":["chinese_traditional"],"獨":["chinese_traditional"],"環":["chinese_traditional"],"雙":["chinese_traditional"],"請":["chinese_traditional"],"讓":["chinese_traditional"],"軸":["chinese_traditional"],"紀":["chinese_traditional"],"優":["chinese_traditional"],"頂":["chinese_traditional"],"礎":["chinese_traditional"],"載":["chinese_traditional"],"敵":["chinese_traditional"],"勝":["chinese_traditional"],"絕":["chinese_traditional"],"塊":["chinese_traditional"],"劑":["chinese_traditional"],"測":["chinese_traditional"],"絲":["chinese_traditional"],"協":["chinese_traditional"],"訴":["chinese_traditional"],"陳":["chinese_traditional"],"羅":["chinese_traditional"],"鹽":["chinese_traditional"],"錯":["chinese_traditional"],"頻":["chinese_traditional"],"終":["chinese_traditional"],"雲":["chinese_traditional"],"衛":["chinese_traditional"],"燒":["chinese_traditional"],"遊":["chinese_traditional"],"舊":["chinese_traditional"],"貨":["chinese_traditional"],"損":["chinese_traditional"],"預":["chinese_traditional"],"穩":["chinese_traditional"],"媽":["chinese_traditional"],"擴":["chinese_traditional"],"銀":["chinese_traditional"],"語":["chinese_traditional"],"揮":["chinese_traditional"],"紙":["chinese_traditional"],"醫":["chinese_traditional"],"嗎":["chinese_traditional"],"針":["chinese_traditional"],"劉":["chinese_traditional"],"誤":["chinese_traditional"],"訓":["chinese_traditional"],"願":["chinese_traditional"],"審":["chinese_traditional"],"獲":["chinese_traditional"],"鮮":["chinese_traditional"],"糧":["chinese_traditional"],"脫":["chinese_traditional"],"龍":["chinese_traditional"],"漸":["chinese_traditional"],"歡":["chinese_traditional"],"剛":["chinese_traditional"],"謂":["chinese_traditional"],"討":["chinese_traditional"],"亂":["chinese_traditional"],"殺":["chinese_traditional"],"藥":["chinese_traditional"],"寧":["chinese_traditional"],"魯":["chinese_traditional"],"貴":["chinese_traditional"],"鐘":["chinese_traditional"],"讀":["chinese_traditional"],"豐":["chinese_traditional"],"蘭":["chinese_traditional"],"擔":["chinese_traditional"],"執":["chinese_traditional"],"樂":["chinese_traditional"],"誰":["chinese_traditional"],"順":["chinese_traditional"],"煙":["chinese_traditional"],"縮":["chinese_traditional"],"徵":["chinese_traditional"],"臉":["chinese_traditional"],"腳":["chinese_traditional"],"異":["chinese_traditional"],"買":["chinese_traditional"],"靜":["chinese_traditional"],"補":["chinese_traditional"],"評":["chinese_traditional"],"踐":["chinese_traditional"],"寬":["chinese_traditional"],"揚":["chinese_traditional"],"傷":["chinese_traditional"],"氫":["chinese_traditional"],"憲":["chinese_traditional"],"慶":["chinese_traditional"],"編":["chinese_traditional"],"觸":["chinese_traditional"],"銷":["chinese_traditional"],"詩":["chinese_traditional"],"綠":["chinese_traditional"],"雞":["chinese_traditional"],"孫":["chinese_traditional"],"膠":["chinese_traditional"],"鄉":["chinese_traditional"],"臨":["chinese_traditional"],"陸":["chinese_traditional"],"顧":["chinese_traditional"],"燈":["chinese_traditional"],"歲":["chinese_traditional"],"劇":["chinese_traditional"],"趙":["chinese_traditional"],"課":["chinese_traditional"],"凱":["chinese_traditional"],"額":["chinese_traditional"],"紹":["chinese_traditional"],"齊":["chinese_traditional"],"偉":["chinese_traditional"],"爐":["chinese_traditional"],"楊":["chinese_traditional"],"桿":["chinese_traditional"],"鎮":["chinese_traditional"],"飯":["chinese_traditional"],"濃":["chinese_traditional"],"懷":["chinese_traditional"],"趕":["chinese_traditional"],"庫":["chinese_traditional"],"奪":["chinese_traditional"],"靈":["chinese_traditional"],"稅":["chinese_traditional"],"滅":["chinese_traditional"],"賽":["chinese_traditional"],"歸":["chinese_traditional"],"盤":["chinese_traditional"],"險":["chinese_traditional"],"錄":["chinese_traditional"],"純":["chinese_traditional"],"蓋":["chinese_traditional"],"橫":["chinese_traditional"],"槍":["chinese_traditional"],"潤":["chinese_traditional"],"蟲":["chinese_traditional"],"澤":["chinese_traditional"],"腦":["chinese_traditional"],"歐":["chinese_traditional"],"側":["chinese_traditional"],"徹":["chinese_traditional"],"慮":["chinese_traditional"],"納":["chinese_traditional"],"彈":["chinese_traditional"],"飼":["chinese_traditional"],"麥":["chinese_traditional"],"濕":["chinese_traditional"],"築":["chinese_traditional"],"惡":["chinese_traditional"],"戶":["chinese_traditional"],"訪":["chinese_traditional"],"跡":["chinese_traditional"],"擺":["chinese_traditional"],"賣":["chinese_traditional"],"擇":["chinese_traditional"],"銅":["chinese_traditional"],"獻":["chinese_traditional"],"陣":["chinese_traditional"],"陰":["chinese_traditional"],"樓":["chinese_traditional"],"謀":["chinese_traditional"],"噸":["chinese_traditional"],"豬":["chinese_traditional"],"館":["chinese_traditional"],"爺":["chinese_traditional"],"驚":["chinese_traditional"],"遺":["chinese_traditional"],"纖":["chinese_traditional"],"傾":["chinese_traditional"],"謝":["chinese_traditional"],"奮":["chinese_traditional"],"購":["chinese_traditional"],"監":["chinese_traditional"],"貫":["chinese_traditional"],"釋":["chinese_traditional"],"詞":["chinese_traditional"],"頓":["chinese_traditional"],"寶":["chinese_traditional"],"塵":["chinese_traditional"],"聞":["chinese_traditional"],"殘":["chinese_traditional"],"橋":["chinese_traditional"],"婦":["chinese_traditional"],"綜":["chinese_traditional"],"吳":["chinese_traditional"],"搖":["chinese_traditional"],"贊":["chinese_traditional"],"訂":["chinese_traditional"],"園":["chinese_traditional"],"紛":["chinese_traditional"],"敗":["chinese_traditional"],"榮":["chinese_traditional"],"閉":["chinese_traditional"],"灣":["chinese_traditional"],"鍵":["chinese_traditional"],"駐":["chinese_traditional"],"鍋":["chinese_traditional"],"剝":["chinese_traditional"],"鹼":["chinese_traditional"],"齒":["chinese_traditional"],"煉":["chinese_traditional"],"紡":["chinese_traditional"],"廢":["chinese_traditional"],"緩":["chinese_traditional"],"淨":["chinese_traditional"],"莊":["chinese_traditional"],"貿":["chinese_traditional"],"慣":["chinese_traditional"],"夥":["chinese_traditional"],"勻":["chinese_traditional"],"紗":["chinese_traditional"],"辯":["chinese_traditional"],"億":["chinese_traditional"],"脈":["chinese_traditional"],"薩":["chinese_traditional"],"網":["chinese_traditional"],"噴":["chinese_traditional"],"縱":["chinese_traditional"],"掛":["chinese_traditional"],"賀":["chinese_traditional"],"閃":["chinese_traditional"],"牆":["chinese_traditional"],"軟":["chinese_traditional"],"滾":["chinese_traditional"],"盪":["chinese_traditional"],"儀":["chinese_traditional"],"軋":["chinese_traditional"],"貢":["chinese_traditional"],"鑽":["chinese_traditional"],"幣":["chinese_traditional"],"軌":["chinese_traditional"],"畝":["chinese_traditional"],"畢":["chinese_traditional"],"島":["chinese_traditional"],"鑄":["chinese_traditional"],"湯":["chinese_traditional"],"閥":["chinese_traditional"],"匯":["chinese_traditional"],"繞":["chinese_traditional"],"績":["chinese_traditional"],"啟":["chinese_traditional"],"顏":["chinese_traditional"],"淚":["chinese_traditional"],"藍":["chinese_traditional"],"鏡":["chinese_traditional"],"壯":["chinese_traditional"],"鋒":["chinese_traditional"],"貧":["chinese_traditional"],"虛":["chinese_traditional"],"彎":["chinese_traditional"],"綱":["chinese_traditional"],"隸":["chinese_traditional"],"宮":["chinese_traditional"],"違":["chinese_traditional"],"夾":["chinese_traditional"],"緣":["chinese_traditional"],"窮":["chinese_traditional"],"溝":["chinese_traditional"],"繩":["chinese_traditional"],"憶":["chinese_traditional"],"漿":["chinese_traditional"],"欄":["chinese_traditional"],"擁":["chinese_traditional"],"貯":["chinese_traditional"],"禮":["chinese_traditional"],"濾":["chinese_traditional"],"鈉":["chinese_traditional"],"紋":["chinese_traditional"],"罷":["chinese_traditional"],"罰":["chinese_traditional"],"潛":["chinese_traditional"],"縫":["chinese_traditional"],"飽":["chinese_traditional"],"獎":["chinese_traditional"],"鋁":["chinese_traditional"],"麗":["chinese_traditional"],"鏈":["chinese_traditional"],"掃":["chinese_traditional"],"諸":["chinese_traditional"],"勵":["chinese_traditional"],"潔":["chinese_traditional"],"災":["chinese_traditional"],"鑑":["chinese_traditional"],"訟":["chinese_traditional"],"毀":["chinese_traditional"],"屆":["chinese_traditional"],"躍":["chinese_traditional"],"艱":["chinese_traditional"],"貝":["chinese_traditional"],"碼":["chinese_traditional"],"夢":["chinese_traditional"],"漁":["chinese_traditional"],"顆":["chinese_traditional"],"鉛":["chinese_traditional"],"倉":["chinese_traditional"],"銳":["chinese_traditional"],"曉":["chinese_traditional"],"隱":["chinese_traditional"],"礙":["chinese_traditional"],"撥":["chinese_traditional"],"肅":["chinese_traditional"],"牽":["chinese_traditional"],"搶":["chinese_traditional"],"殼":["chinese_traditional"],"訊":["chinese_traditional"],"誠":["chinese_traditional"],"頁":["chinese_traditional"],"齡":["chinese_traditional"],"倫":["chinese_traditional"],"尋":["chinese_traditional"],"鋪":["chinese_traditional"],"聖":["chinese_traditional"],"鄭":["chinese_traditional"],"騰":["chinese_traditional"],"貼":["chinese_traditional"],"闊":["chinese_traditional"],"輛":["chinese_traditional"],"儲":["chinese_traditional"],"簽":["chinese_traditional"],"鬧":["chinese_traditional"],"擾":["chinese_traditional"],"遞":["chinese_traditional"],"戲":["chinese_traditional"],"餵":["chinese_traditional"],"療":["chinese_traditional"],"撫":["chinese_traditional"],"蝦":["chinese_traditional"],"蠟":["chinese_traditional"],"鄰":["chinese_traditional"],"鞏":["chinese_traditional"],"擠":["chinese_traditional"],"棄":["chinese_traditional"],"勁":["chinese_traditional"],"鄧":["chinese_traditional"],"爛":["chinese_traditional"],"磚":["chinese_traditional"],"烏":["chinese_traditional"],"艦":["chinese_traditional"],"淺":["chinese_traditional"],"暫":["chinese_traditional"],"膽":["chinese_traditional"],"詳":["chinese_traditional"],"譜":["chinese_traditional"],"賓":["chinese_traditional"],"輝":["chinese_traditional"],"憤":["chinese_traditional"],"競":["chinese_traditional"],"緒":["chinese_traditional"],"塗":["chinese_traditional"],"偵":["chinese_traditional"],"懸":["chinese_traditional"],"糾":["chinese_traditional"],"鎖":["chinese_traditional"],"賞":["chinese_traditional"],"鴨":["chinese_traditional"],"趨":["chinese_traditional"],"鳳":["chinese_traditional"],"輩":["chinese_traditional"],"灘":["chinese_traditional"],"驅":["chinese_traditional"],"篩":["chinese_traditional"],"峽":["chinese_traditional"],"壽":["chinese_traditional"],"譯":["chinese_traditional"],"遲":["chinese_traditional"],"矽":["chinese_traditional"],"貸":["chinese_traditional"],"脅":["chinese_traditional"],"蝕":["chinese_traditional"],"奧":["chinese_traditional"],"鳴":["chinese_traditional"],"嶺":["chinese_traditional"],"憑":["chinese_traditional"],"繪":["chinese_traditional"],"錫":["chinese_traditional"],"廟":["chinese_traditional"],"籌":["chinese_traditional"],"凍":["chinese_traditional"],"輔":["chinese_traditional"],"攝":["chinese_traditional"],"襲":["chinese_traditional"],"鉀":["chinese_traditional"],"鳥":["chinese_traditional"],"韓":["chinese_traditional"],"僑":["chinese_traditional"],"涼":["chinese_traditional"],"餾":["chinese_traditional"],"勸":["chinese_traditional"],"遼":["chinese_traditional"],"鴻":["chinese_traditional"],"輥":["chinese_traditional"],"飲":["chinese_traditional"],"罵":["chinese_traditional"],"辭":["chinese_traditional"],"蔣":["chinese_traditional"],"絨":["chinese_traditional"],"霧":["chinese_traditional"],"擬":["chinese_traditional"],"輯":["chinese_traditional"],"陝":["chinese_traditional"],"償":["chinese_traditional"],"廳":["chinese_traditional"],"駛":["chinese_traditional"],"賦":["chinese_traditional"],"澆":["chinese_traditional"],"鈣":["chinese_traditional"],"虧":["chinese_traditional"],"騙":["chinese_traditional"],"脹":["chinese_traditional"],"諧":["chinese_traditional"],"拋":["chinese_traditional"],"黴":["chinese_traditional"],"崗":["chinese_traditional"],"盜":["chinese_traditional"],"滲":["chinese_traditional"],"臟":["chinese_traditional"],"賴":["chinese_traditional"],"湧":["chinese_traditional"],"閱":["chinese_traditional"],"厲":["chinese_traditional"],"烴":["chinese_traditional"],"緯":["chinese_traditional"],"偽":["chinese_traditional"],"嘆":["chinese_traditional"],"釘":["chinese_traditional"],"莖":["chinese_traditional"],"籠":["chinese_traditional"],"錐":["chinese_traditional"],"恆":["chinese_traditional"],"傑":["chinese_traditional"],"綸":["chinese_traditional"],"敘":["chinese_traditional"],"獄":["chinese_traditional"],"絡":["chinese_traditional"],"驟":["chinese_traditional"],"冊":["chinese_traditional"],"屍":["chinese_traditional"],"紳":["chinese_traditional"],"犧":["chinese_traditional"],"轟":["chinese_traditional"],"晉":["chinese_traditional"],"禦":["chinese_traditional"],"錠":["chinese_traditional"],"錦":["chinese_traditional"],"喪":["chinese_traditional"],"鍛":["chinese_traditional"],"壟":["chinese_traditional"],"撲":["chinese_traditional"],"邁":["chinese_traditional"],"閒":["chinese_traditional"],"憂":["chinese_traditional"],"頑":["chinese_traditional"],"漲":["chinese_traditional"],"闢":["chinese_traditional"],"懲":["chinese_traditional"],"飄":["chinese_traditional"],"飾":["chinese_traditional"],"蕭":["chinese_traditional"],"郵":["chinese_traditional"],"遷":["chinese_traditional"],"煩":["chinese_traditional"],"債":["chinese_traditional"],"帳":["chinese_traditional"],"鈴":["chinese_traditional"],"餅":["chinese_traditional"],"雛":["chinese_traditional"],"賢":["chinese_traditional"],"丟":["chinese_traditional"],"墊":["chinese_traditional"],"擋":["chinese_traditional"],"覽":["chinese_traditional"],"貪":["chinese_traditional"],"繳":["chinese_traditional"],"馮":["chinese_traditional"],"諾":["chinese_traditional"],"誼":["chinese_traditional"],"兇":["chinese_traditional"],"誣":["chinese_traditional"],"騎":["chinese_traditional"],"喬":["chinese_traditional"],"叢":["chinese_traditional"],"盧":["chinese_traditional"],"悶":["chinese_traditional"],"諮":["chinese_traditional"],"駕":["chinese_traditional"],"纜":["chinese_traditional"],"鉺":["chinese_traditional"],"擲":["chinese_traditional"],"頗":["chinese_traditional"],"慘":["chinese_traditional"],"臘":["chinese_traditional"],"窩":["chinese_traditional"],"滌":["chinese_traditional"],"劍":["chinese_traditional"],"潑":["chinese_traditional"],"蔥":["chinese_traditional"],"撈":["chinese_traditional"],"蒼":["chinese_traditional"],"濱":["chinese_traditional"],"倆":["chinese_traditional"],"瘋":["chinese_traditional"],"糞":["chinese_traditional"],"檔":["chinese_traditional"],"駁":["chinese_traditional"],"腸":["chinese_traditional"],"撐":["chinese_traditional"],"曬":["chinese_traditional"],"蓮":["chinese_traditional"],"攤":["chinese_traditional"],"攪":["chinese_traditional"],"醬":["chinese_traditional"],"皺":["chinese_traditional"],"暢":["chinese_traditional"],"疊":["chinese_traditional"],"閣":["chinese_traditional"],"萊":["chinese_traditional"],"轄":["chinese_traditional"],"鉤":["chinese_traditional"],"壩":["chinese_traditional"],"餓":["chinese_traditional"],"禍":["chinese_traditional"],"邏":["chinese_traditional"],"嘗":["chinese_traditional"],"韋":["chinese_traditional"],"abdikace":["czech"],"abeceda":["czech"],"adresa":["czech"],"agrese":["czech"],"akce":["czech"],"aktovka":["czech"],"alej":["czech"],"alkohol":["czech"],"amputace":["czech"],"ananas":["czech"],"andulka":["czech"],"anekdota":["czech"],"anketa":["czech"],"antika":["czech"],"anulovat":["czech"],"archa":["czech"],"arogance":["czech"],"asfalt":["czech","turkish"],"asistent":["czech"],"aspirace":["czech"],"astma":["czech"],"astronom":["czech"],"atlas":["czech"],"atletika":["czech"],"atol":["czech"],"autobus":["czech"],"azyl":["czech"],"babka":["czech"],"bachor":["czech"],"bacil":["czech"],"baculka":["czech"],"badatel":["czech"],"bageta":["czech"],"bagr":["czech"],"bahno":["czech"],"bakterie":["czech"],"balada":["czech"],"baletka":["czech"],"balkon":["czech"],"balonek":["czech"],"balvan":["czech"],"balza":["czech"],"bambus":["czech"],"bankomat":["czech"],"barbar":["czech"],"baret":["czech"],"barman":["czech"],"baroko":["czech"],"barva":["czech"],"baterka":["czech"],"batoh":["czech"],"bavlna":["czech"],"bazalka":["czech"],"bazilika":["czech"],"bazuka":["czech"],"bedna":["czech"],"beran":["czech"],"beseda":["czech"],"bestie":["czech"],"beton":["czech","turkish"],"bezinka":["czech"],"bezmoc":["czech"],"beztak":["czech"],"bicykl":["czech"],"bidlo":["czech"],"biftek":["czech","turkish"],"bikiny":["czech"],"bilance":["czech"],"biograf":["czech"],"biolog":["czech"],"bitva":["czech"],"bizon":["czech"],"blahobyt":["czech"],"blatouch":["czech"],"blecha":["czech"],"bledule":["czech"],"blesk":["czech"],"blikat":["czech"],"blizna":["czech"],"blokovat":["czech"],"bloudit":["czech"],"blud":["czech"],"bobek":["czech"],"bobr":["czech"],"bodlina":["czech"],"bodnout":["czech"],"bohatost":["czech"],"bojkot":["czech"],"bojovat":["czech"],"bokorys":["czech"],"bolest":["czech"],"borec":["czech"],"borovice":["czech"],"bota":["czech"],"boubel":["czech"],"bouchat":["czech"],"bouda":["czech"],"boule":["czech"],"bourat":["czech"],"boxer":["czech"],"bradavka":["czech"],"brambora":["czech"],"branka":["czech"],"bratr":["czech"],"brepta":["czech"],"briketa":["czech"],"brko":["czech"],"brloh":["czech"],"bronz":["czech"],"broskev":["czech"],"brunetka":["czech"],"brusinka":["czech"],"brzda":["czech"],"brzy":["czech"],"bublina":["czech"],"bubnovat":["czech"],"buchta":["czech"],"buditel":["czech"],"budka":["czech"],"budova":["czech"],"bufet":["czech"],"bujarost":["czech"],"bukvice":["czech"],"buldok":["czech"],"bulva":["czech"],"bunda":["czech"],"bunkr":["czech"],"burza":["czech"],"butik":["czech","turkish"],"buvol":["czech"],"buzola":["czech"],"bydlet":["czech"],"bylina":["czech"],"bytovka":["czech"],"bzukot":["czech"],"capart":["czech"],"carevna":["czech"],"cedr":["czech"],"cedule":["czech"],"cejch":["czech"],"cejn":["czech"],"cela":["czech"],"celer":["czech"],"celkem":["czech"],"celnice":["czech"],"cenina":["czech"],"cennost":["czech"],"cenovka":["czech"],"centrum":["czech"],"cenzor":["czech"],"cestopis":["czech"],"cetka":["czech"],"chalupa":["czech"],"chapadlo":["czech"],"charita":["czech"],"chata":["czech"],"chechtat":["czech"],"chemie":["czech"],"chichot":["czech"],"chirurg":["czech"],"chlad":["czech"],"chleba":["czech"],"chlubit":["czech"],"chmel":["czech"],"chmura":["czech"],"chobot":["czech"],"chochol":["czech"],"chodba":["czech"],"cholera":["czech"],"chomout":["czech"],"chopit":["czech"],"choroba":["czech"],"chov":["czech"],"chrapot":["czech"],"chrlit":["czech"],"chrt":["czech"],"chrup":["czech"],"chtivost":["czech"],"chudina":["czech"],"chutnat":["czech"],"chvat":["czech"],"chvilka":["czech"],"chvost":["czech"],"chyba":["czech"],"chystat":["czech"],"chytit":["czech"],"cibule":["czech"],"cigareta":["czech"],"cihelna":["czech"],"cihla":["czech"],"cinkot":["czech"],"cirkus":["czech"],"cisterna":["czech"],"citace":["czech"],"citrus":["czech"],"cizinec":["czech"],"cizost":["czech"],"clona":["czech"],"cokoliv":["czech"],"couvat":["czech"],"ctitel":["czech"],"ctnost":["czech"],"cudnost":["czech"],"cuketa":["czech"],"cukr":["czech"],"cupot":["czech"],"cvaknout":["czech"],"cval":["czech"],"cvik":["czech"],"cvrkot":["czech"],"cyklista":["czech"],"daleko":["czech"],"dareba":["czech"],"datel":["czech"],"datum":["czech"],"dcera":["czech"],"debata":["czech"],"dechovka":["czech"],"decibel":["czech"],"deficit":["czech"],"deflace":["czech"],"dekl":["czech"],"dekret":["czech"],"demokrat":["czech"],"deprese":["czech"],"derby":["czech"],"deska":["czech"],"detektiv":["czech"],"dikobraz":["czech"],"diktovat":["czech"],"dioda":["czech"],"diplom":["czech"],"disk":["czech","turkish"],"displej":["czech"],"divadlo":["czech"],"divoch":["czech"],"dlaha":["czech"],"dlouho":["czech"],"dluhopis":["czech"],"dnes":["czech"],"dobro":["czech"],"dobytek":["czech"],"docent":["czech"],"dochutit":["czech"],"dodnes":["czech"],"dohled":["czech"],"dohoda":["czech"],"dohra":["czech"],"dojem":["czech"],"dojnice":["czech"],"doklad":["czech"],"dokola":["czech"],"doktor":["czech","turkish"],"dokument":["czech"],"dolar":["czech"],"doleva":["czech"],"dolina":["czech"],"doma":["czech"],"dominant":["czech"],"domluvit":["czech"],"domov":["czech"],"donutit":["czech"],"dopad":["czech"],"dopis":["czech"],"doplnit":["czech"],"doposud":["czech"],"doprovod":["czech"],"dopustit":["czech"],"dorazit":["czech"],"dorost":["czech"],"dort":["czech"],"dosah":["czech"],"doslov":["czech"],"dostatek":["czech"],"dosud":["czech"],"dosyta":["czech"],"dotaz":["czech"],"dotek":["czech"],"dotknout":["czech"],"doufat":["czech"],"doutnat":["czech"],"dovozce":["czech"],"dozadu":["czech"],"doznat":["czech"],"dozorce":["czech"],"drahota":["czech"],"drak":["czech"],"dramatik":["czech"],"dravec":["czech"],"draze":["czech"],"drdol":["czech"],"drobnost":["czech"],"drogerie":["czech"],"drozd":["czech"],"drsnost":["czech"],"drtit":["czech"],"drzost":["czech"],"duben":["czech"],"duchovno":["czech"],"dudek":["czech"],"duha":["czech"],"duhovka":["czech"],"dusit":["czech"],"dusno":["czech"],"dutost":["czech"],"dvojice":["czech"],"dvorec":["czech"],"dynamit":["czech"],"ekolog":["czech"],"ekonomie":["czech"],"elektron":["czech"],"elipsa":["czech"],"email":["czech"],"emise":["czech"],"emoce":["czech"],"empatie":["czech"],"epizoda":["czech"],"epocha":["czech"],"epopej":["czech"],"epos":["czech"],"esej":["czech"],"esence":["czech"],"eskorta":["czech"],"eskymo":["czech"],"etiketa":["czech"],"euforie":["czech"],"evoluce":["czech"],"exekuce":["czech"],"exkurze":["czech"],"expedice":["czech"],"exploze":["czech"],"export":["czech"],"extrakt":["czech"],"facka":["czech"],"fajfka":["czech"],"fakulta":["czech"],"fanatik":["czech","turkish"],"fantazie":["czech"],"farmacie":["czech"],"favorit":["czech"],"fazole":["czech"],"federace":["czech"],"fejeton":["czech"],"fenka":["czech"],"fialka":["czech"],"figurant":["czech"],"filozof":["czech"],"filtr":["czech"],"finance":["czech"],"finta":["czech"],"fixace":["czech"],"fjord":["czech"],"flanel":["czech"],"flirt":["czech"],"flotila":["czech"],"fond":["czech"],"fosfor":["czech"],"fotbal":["czech"],"fotka":["czech"],"foton":["czech"],"frakce":["czech"],"freska":["czech"],"fronta":["czech"],"fukar":["czech"],"funkce":["czech"],"fyzika":["czech"],"galeje":["czech"],"garant":["czech"],"genetika":["czech"],"geolog":["czech"],"gilotina":["czech"],"glazura":["czech"],"glejt":["czech"],"golem":["czech"],"golfista":["czech"],"gotika":["czech"],"graf":["czech"],"gramofon":["czech"],"granule":["czech"],"grep":["czech"],"gril":["czech"],"grog":["czech"],"groteska":["czech"],"guma":["czech"],"hadice":["czech"],"hadr":["czech"],"hala":["czech"],"halenka":["czech"],"hanba":["czech"],"hanopis":["czech"],"harfa":["czech"],"harpuna":["czech"],"havran":["czech"],"hebkost":["czech"],"hejkal":["czech"],"hejno":["czech"],"hejtman":["czech"],"hektar":["czech","turkish"],"helma":["czech"],"hematom":["czech"],"herec":["czech"],"herna":["czech"],"heslo":["czech"],"hezky":["czech"],"historik":["czech"],"hladovka":["czech"],"hlasivky":["czech"],"hlava":["czech"],"hledat":["czech"],"hlen":["czech"],"hlodavec":["czech"],"hloh":["czech"],"hloupost":["czech"],"hltat":["czech"],"hlubina":["czech"],"hluchota":["czech"],"hmat":["czech"],"hmota":["czech"],"hmyz":["czech"],"hnis":["czech"],"hnojivo":["czech"],"hnout":["czech"],"hoblina":["czech"],"hoboj":["czech"],"hoch":["czech"],"hodiny":["czech"],"hodlat":["czech"],"hodnota":["czech"],"hodovat":["czech"],"hojnost":["czech"],"hokej":["czech"],"holinka":["czech"],"holka":["czech"],"holub":["czech"],"homole":["czech"],"honitba":["czech"],"honorace":["czech"],"horal":["czech"],"horda":["czech"],"horizont":["czech"],"horko":["czech"],"horlivec":["czech"],"hormon":["czech","turkish"],"hornina":["czech"],"horoskop":["czech"],"horstvo":["czech"],"hospoda":["czech"],"hostina":["czech"],"hotovost":["czech"],"houba":["czech"],"houf":["czech"],"houpat":["czech"],"houska":["czech"],"hovor":["czech"],"hradba":["czech"],"hranice":["czech"],"hravost":["czech"],"hrazda":["czech"],"hrbolek":["czech"],"hrdina":["czech"],"hrdlo":["czech"],"hrdost":["czech"],"hrnek":["czech"],"hrobka":["czech"],"hromada":["czech"],"hrot":["czech"],"hrouda":["czech"],"hrozen":["czech"],"hrstka":["czech"],"hrubost":["czech"],"hryzat":["czech"],"hubenost":["czech"],"hubnout":["czech"],"hudba":["czech"],"hukot":["czech"],"humr":["czech"],"husita":["czech"],"hustota":["czech"],"hvozd":["czech"],"hybnost":["czech"],"hydrant":["czech"],"hygiena":["czech"],"hymna":["czech"],"hysterik":["czech"],"idylka":["czech"],"ihned":["czech"],"ikona":["czech"],"iluze":["czech"],"imunita":["czech"],"infekce":["czech"],"inflace":["czech"],"inkaso":["czech"],"inovace":["czech"],"inspekce":["czech"],"internet":["czech"],"invalida":["czech"],"investor":["czech"],"inzerce":["czech"],"ironie":["czech"],"jablko":["czech"],"jachta":["czech"],"jahoda":["czech"],"jakmile":["czech"],"jakost":["czech"],"jalovec":["czech"],"jantar":["czech"],"jarmark":["czech"],"jaro":["czech"],"jasan":["czech"],"jasno":["czech"],"jatka":["czech"],"javor":["czech"],"jazyk":["czech"],"jedinec":["czech"],"jedle":["czech"],"jednatel":["czech"],"jehlan":["czech"],"jekot":["czech"],"jelen":["czech"],"jelito":["czech"],"jemnost":["czech"],"jenom":["czech"],"jepice":["czech"],"jeseter":["czech"],"jevit":["czech"],"jezdec":["czech"],"jezero":["czech"],"jinak":["czech"],"jindy":["czech"],"jinoch":["czech"],"jiskra":["czech"],"jistota":["czech"],"jitrnice":["czech"],"jizva":["czech"],"jmenovat":["czech"],"jogurt":["czech"],"jurta":["czech"],"kabaret":["czech"],"kabel":["czech"],"kabinet":["czech"],"kachna":["czech"],"kadet":["czech"],"kadidlo":["czech"],"kahan":["czech"],"kajak":["czech"],"kajuta":["czech"],"kakao":["czech"],"kaktus":["czech"],"kalamita":["czech"],"kalhoty":["czech"],"kalibr":["czech"],"kalnost":["czech"],"kamera":["czech"],"kamkoliv":["czech"],"kamna":["czech"],"kanibal":["czech"],"kanoe":["czech"],"kantor":["czech"],"kapalina":["czech"],"kapela":["czech"],"kapitola":["czech"],"kapka":["czech"],"kaple":["czech"],"kapota":["czech"],"kapr":["czech"],"kapusta":["czech"],"kapybara":["czech"],"karamel":["czech"],"karotka":["czech"],"karton":["czech"],"kasa":["czech"],"katalog":["czech"],"katedra":["czech"],"kauce":["czech"],"kauza":["czech"],"kavalec":["czech"],"kazajka":["czech"],"kazeta":["czech"],"kazivost":["czech"],"kdekoliv":["czech"],"kdesi":["czech"],"kedluben":["czech"],"kemp":["czech"],"keramika":["czech"],"kino":["czech"],"klacek":["czech"],"kladivo":["czech"],"klam":["czech"],"klapot":["czech"],"klasika":["czech"],"klaun":["czech"],"klec":["czech"],"klenba":["czech"],"klepat":["czech"],"klesnout":["czech"],"klid":["czech"],"klima":["czech"],"klisna":["czech"],"klobouk":["czech"],"klokan":["czech"],"klopa":["czech"],"kloub":["czech"],"klubovna":["czech"],"klusat":["czech"],"kluzkost":["czech"],"kmen":["czech"],"kmitat":["czech"],"kmotr":["czech"],"kniha":["czech"],"knot":["czech"],"koalice":["czech"],"koberec":["czech"],"kobka":["czech"],"kobliha":["czech"],"kobyla":["czech"],"kocour":["czech"],"kohout":["czech"],"kojenec":["czech"],"kokos":["czech"],"koktejl":["czech"],"kolaps":["czech"],"koleda":["czech"],"kolize":["czech"],"kolo":["czech"],"komando":["czech"],"kometa":["czech"],"komik":["czech"],"komnata":["czech"],"komora":["czech"],"kompas":["czech"],"komunita":["czech"],"konat":["czech"],"koncept":["czech"],"kondice":["czech"],"konec":["czech"],"konfese":["czech"],"kongres":["czech"],"konina":["czech"],"konkurs":["czech"],"kontakt":["czech"],"konzerva":["czech"],"kopanec":["czech"],"kopie":["czech"],"kopnout":["czech"],"koprovka":["czech"],"korbel":["czech"],"korektor":["czech"],"kormidlo":["czech"],"koroptev":["czech"],"korpus":["czech"],"koruna":["czech"],"koryto":["czech"],"korzet":["czech"],"kosatec":["czech"],"kostka":["czech"],"kotel":["czech"],"kotleta":["czech"],"kotoul":["czech"],"koukat":["czech"],"koupelna":["czech"],"kousek":["czech"],"kouzlo":["czech"],"kovboj":["czech"],"koza":["czech"],"kozoroh":["czech"],"krabice":["czech"],"krach":["czech"],"krajina":["czech"],"kralovat":["czech"],"krasopis":["czech"],"kravata":["czech"],"kredit":["czech"],"krejcar":["czech"],"kresba":["czech"],"kreveta":["czech"],"kriket":["czech"],"kritik":["czech"],"krize":["czech"],"krkavec":["czech"],"krmelec":["czech"],"krmivo":["czech"],"krocan":["czech"],"krok":["czech"],"kronika":["czech"],"kropit":["czech"],"kroupa":["czech"],"krovka":["czech"],"krtek":["czech"],"kruhadlo":["czech"],"krupice":["czech"],"krutost":["czech"],"krvinka":["czech"],"krychle":["czech"],"krypta":["czech"],"krystal":["czech"],"kryt":["czech"],"kudlanka":["czech"],"kufr":["czech"],"kujnost":["czech"],"kukla":["czech"],"kulajda":["czech"],"kulich":["czech"],"kulka":["czech"],"kulomet":["czech"],"kultura":["czech"],"kuna":["czech"],"kupodivu":["czech"],"kurt":["czech"],"kurzor":["czech"],"kutil":["czech"],"kvalita":["czech"],"kvasinka":["czech"],"kvestor":["czech"],"kynolog":["czech"],"kyselina":["czech"],"kytara":["czech"],"kytice":["czech"],"kytka":["czech"],"kytovec":["czech"],"kyvadlo":["czech"],"labrador":["czech"],"lachtan":["czech"],"ladnost":["czech"],"laik":["czech"],"lakomec":["czech"],"lamela":["czech"],"lampa":["czech"],"lanovka":["czech"],"lasice":["czech"],"laso":["czech"],"lastura":["czech"],"latinka":["czech"],"lavina":["czech"],"lebka":["czech"],"leckdy":["czech"],"leden":["czech"],"lednice":["czech"],"ledovka":["czech"],"ledvina":["czech"],"legenda":["czech"],"legie":["czech"],"legrace":["czech"],"lehce":["czech"],"lehkost":["czech"],"lehnout":["czech"],"lektvar":["czech"],"lenochod":["czech"],"lentilka":["czech"],"lepenka":["czech"],"lepidlo":["czech"],"letadlo":["czech"],"letec":["czech"],"letmo":["czech"],"letokruh":["czech"],"levhart":["czech"],"levitace":["czech"],"levobok":["czech"],"libra":["czech"],"lichotka":["czech"],"lidojed":["czech"],"lidskost":["czech"],"lihovina":["czech"],"lijavec":["czech"],"lilek":["czech"],"limetka":["czech"],"linie":["czech"],"linka":["czech"],"linoleum":["czech"],"listopad":["czech"],"litina":["czech"],"litovat":["czech"],"lobista":["czech"],"lodivod":["czech"],"logika":["czech"],"logoped":["czech"],"lokalita":["czech"],"loket":["czech"],"lomcovat":["czech"],"lopata":["czech"],"lopuch":["czech"],"lord":["czech"],"losos":["czech"],"lotr":["czech"],"loudal":["czech"],"louh":["czech"],"louka":["czech"],"louskat":["czech"],"lovec":["czech"],"lstivost":["czech"],"lucerna":["czech"],"lucifer":["czech"],"lump":["czech"],"lusk":["czech"],"lustrace":["czech"],"lvice":["czech"],"lyra":["czech"],"lyrika":["czech"],"lysina":["czech"],"madam":["czech"],"madlo":["czech"],"magistr":["czech"],"mahagon":["czech"],"majetek":["czech"],"majitel":["czech"],"majorita":["czech"],"makak":["czech"],"makovice":["czech"],"makrela":["czech"],"malba":["czech"],"malina":["czech"],"malovat":["czech"],"malvice":["czech"],"maminka":["czech"],"mandle":["czech"],"manko":["czech"],"marnost":["czech"],"masakr":["czech"],"maskot":["czech"],"masopust":["czech"],"matice":["czech"],"matrika":["czech"],"maturita":["czech"],"mazanec":["czech"],"mazivo":["czech"],"mazlit":["czech"],"mazurka":["czech"],"mdloba":["czech"],"mechanik":["czech"],"meditace":["czech"],"medovina":["czech"],"melasa":["czech"],"meloun":["czech"],"mentolka":["czech"],"metla":["czech"],"metoda":["czech"],"metr":["czech"],"mezera":["czech"],"migrace":["czech"],"mihnout":["czech"],"mihule":["czech"],"mikina":["czech"],"mikrofon":["czech","turkish"],"milenec":["czech"],"milimetr":["czech"],"milost":["czech"],"mimika":["czech"],"mincovna":["czech"],"minibar":["czech"],"minomet":["czech"],"minulost":["czech"],"miska":["czech"],"mistr":["czech"],"mixovat":["czech"],"mladost":["czech"],"mlha":["czech"],"mlhovina":["czech"],"mlok":["czech"],"mlsat":["czech"],"mluvit":["czech"],"mnich":["czech"],"mnohem":["czech"],"mobil":["czech"],"mocnost":["czech"],"modelka":["czech"],"modlitba":["czech"],"mohyla":["czech"],"mokro":["czech"],"molekula":["czech"],"momentka":["czech"],"monarcha":["czech"],"monokl":["czech"],"monstrum":["czech"],"montovat":["czech"],"monzun":["czech"],"mosaz":["czech"],"moskyt":["czech"],"most":["czech"],"motivace":["czech"],"motorka":["czech"],"motyka":["czech"],"moucha":["czech"],"moudrost":["czech"],"mozaika":["czech"],"mozek":["czech"],"mozol":["czech"],"mramor":["czech"],"mravenec":["czech"],"mrkev":["czech"],"mrtvola":["czech"],"mrzet":["czech"],"mrzutost":["czech"],"mstitel":["czech"],"mudrc":["czech"],"muflon":["czech"],"mulat":["czech"],"mumie":["czech"],"munice":["czech"],"muset":["czech"],"mutace":["czech"],"muzeum":["czech"],"muzikant":["czech"],"myslivec":["czech"],"mzda":["czech"],"nabourat":["czech"],"nachytat":["czech"],"nadace":["czech"],"nadbytek":["czech"],"nadhoz":["czech"],"nadobro":["czech"],"nadpis":["czech"],"nahlas":["czech"],"nahnat":["czech"],"nahodile":["czech"],"nahradit":["czech"],"naivita":["czech"],"najednou":["czech"],"najisto":["czech"],"najmout":["czech"],"naklonit":["czech"],"nakonec":["czech"],"nakrmit":["czech"],"nalevo":["czech"],"namazat":["czech"],"namluvit":["czech"],"nanometr":["czech"],"naoko":["czech"],"naopak":["czech"],"naostro":["czech"],"napadat":["czech"],"napevno":["czech"],"naplnit":["czech"],"napnout":["czech"],"naposled":["czech"],"naprosto":["czech"],"narodit":["czech"],"naruby":["czech"],"narychlo":["czech"],"nasadit":["czech"],"nasekat":["czech"],"naslepo":["czech"],"nastat":["czech"],"natolik":["czech"],"navenek":["czech"],"navrch":["czech"],"navzdory":["czech"],"nazvat":["czech"],"nebe":["czech"],"nechat":["czech"],"necky":["czech"],"nedaleko":["czech"],"nedbat":["czech"],"neduh":["czech"],"negace":["czech"],"nehet":["czech"],"nehoda":["czech"],"nejen":["czech"],"nejprve":["czech"],"neklid":["czech"],"nelibost":["czech"],"nemilost":["czech"],"nemoc":["czech"],"neochota":["czech"],"neonka":["czech"],"nepokoj":["czech"],"nerost":["czech"],"nerv":["czech"],"nesmysl":["czech"],"nesoulad":["czech"],"netvor":["czech"],"neuron":["czech"],"nevina":["czech"],"nezvykle":["czech"],"nicota":["czech"],"nijak":["czech"],"nikam":["czech"],"nikdy":["czech"],"nikl":["czech"],"nikterak":["czech"],"nitro":["czech"],"nocleh":["czech"],"nohavice":["czech"],"nominace":["czech"],"nora":["czech"],"norek":["czech"],"nositel":["czech"],"nosnost":["czech"],"nouze":["czech"],"noviny":["czech"],"novota":["czech"],"nozdra":["czech"],"nuda":["czech"],"nudle":["czech"],"nuget":["czech"],"nutit":["czech"],"nutnost":["czech"],"nutrie":["czech"],"nymfa":["czech"],"obal":["czech"],"obarvit":["czech"],"obava":["czech"],"obdiv":["czech"],"obec":["czech"],"obehnat":["czech"],"obejmout":["czech"],"obezita":["czech"],"obhajoba":["czech"],"obilnice":["czech"],"objasnit":["czech"],"objekt":["czech"],"obklopit":["czech"],"oblast":["czech"],"oblek":["czech"],"obliba":["czech"],"obloha":["czech"],"obluda":["czech"],"obnos":["czech"],"obohatit":["czech"],"obojek":["czech"],"obout":["czech"],"obrazec":["czech"],"obrna":["czech"],"obruba":["czech"],"obrys":["czech"],"obsah":["czech"],"obsluha":["czech"],"obstarat":["czech"],"obuv":["czech"],"obvaz":["czech"],"obvinit":["czech"],"obvod":["czech"],"obvykle":["czech"],"obyvatel":["czech"],"obzor":["czech"],"ocas":["czech"],"ocel":["czech"],"ocenit":["czech"],"ochladit":["czech"],"ochota":["czech"],"ochrana":["czech"],"ocitnout":["czech"],"odboj":["czech"],"odbyt":["czech"],"odchod":["czech"],"odcizit":["czech"],"odebrat":["czech"],"odeslat":["czech"],"odevzdat":["czech"],"odezva":["czech"],"odhadce":["czech"],"odhodit":["czech"],"odjet":["czech"],"odjinud":["czech"],"odkaz":["czech"],"odkoupit":["czech"],"odliv":["czech"],"odluka":["czech"],"odmlka":["czech"],"odolnost":["czech"],"odpad":["czech"],"odpis":["czech"],"odplout":["czech"],"odpor":["czech"],"odpustit":["czech"],"odpykat":["czech"],"odrazka":["czech"],"odsoudit":["czech"],"odstup":["czech"],"odsun":["czech"],"odtok":["czech"],"odtud":["czech"],"odvaha":["czech"],"odveta":["czech"],"odvolat":["czech"],"odvracet":["czech"],"odznak":["czech"],"ofina":["czech"],"ofsajd":["czech"],"ohlas":["czech"],"ohnisko":["czech"],"ohrada":["czech"],"ohrozit":["czech"],"ohryzek":["czech"],"okap":["czech"],"okenice":["czech"],"oklika":["czech"],"okno":["czech"],"okouzlit":["czech"],"okovy":["czech"],"okrasa":["czech"],"okres":["czech"],"okrsek":["czech"],"okruh":["czech"],"okupant":["czech"],"okurka":["czech"],"okusit":["czech"],"olejnina":["czech"],"olizovat":["czech"],"omak":["czech"],"omeleta":["czech"],"omezit":["czech"],"omladina":["czech"],"omlouvat":["czech"],"omluva":["czech"],"omyl":["czech"],"onehdy":["czech"],"opakovat":["czech"],"opasek":["czech"],"operace":["czech"],"opice":["czech"],"opilost":["czech"],"opisovat":["czech"],"opora":["czech"],"opozice":["czech"],"opravdu":["czech"],"oproti":["czech"],"orbital":["czech"],"orchestr":["czech"],"orgie":["czech"],"orlice":["czech"],"orloj":["czech"],"ortel":["czech"],"osada":["czech"],"oschnout":["czech"],"osika":["czech"],"osivo":["czech"],"oslava":["czech"],"oslepit":["czech"],"oslnit":["czech"],"oslovit":["czech"],"osnova":["czech"],"osoba":["czech"],"osolit":["czech"],"ospalec":["czech"],"osten":["czech"],"ostraha":["czech"],"ostuda":["czech"],"ostych":["czech"],"osvojit":["czech"],"oteplit":["czech"],"otisk":["czech"],"otop":["czech"],"otrhat":["czech"],"otrlost":["czech"],"otrok":["czech"],"otruby":["czech"],"otvor":["czech"],"ovanout":["czech"],"ovar":["czech"],"oves":["czech"],"ovlivnit":["czech"],"ovoce":["czech"],"oxid":["czech"],"ozdoba":["czech"],"pachatel":["czech"],"pacient":["czech"],"padouch":["czech"],"pahorek":["czech"],"pakt":["czech"],"palanda":["czech"],"palec":["czech"],"palivo":["czech"],"paluba":["czech"],"pamflet":["czech"],"pamlsek":["czech"],"panenka":["czech"],"panika":["czech"],"panna":["czech"],"panovat":["czech"],"panstvo":["czech"],"pantofle":["czech"],"paprika":["czech"],"parketa":["czech"],"parodie":["czech"],"parta":["czech"],"paruka":["czech"],"paryba":["czech"],"paseka":["czech"],"pasivita":["czech"],"pastelka":["czech"],"patent":["czech"],"patrona":["czech"],"pavouk":["czech"],"pazneht":["czech"],"pazourek":["czech"],"pecka":["czech"],"pedagog":["czech"],"pejsek":["czech"],"peklo":["czech"],"peloton":["czech"],"penalta":["czech"],"pendrek":["czech"],"penze":["czech"],"periskop":["czech"],"pero":["czech"],"pestrost":["czech"],"petarda":["czech"],"petice":["czech"],"petrolej":["czech"],"pevnina":["czech"],"pexeso":["czech"],"pianista":["czech"],"piha":["czech"],"pijavice":["czech"],"pikle":["czech"],"piknik":["czech","turkish"],"pilina":["czech"],"pilnost":["czech"],"pilulka":["czech"],"pinzeta":["czech"],"pipeta":["czech"],"pisatel":["czech"],"pistole":["czech"],"pitevna":["czech"],"pivnice":["czech"],"pivovar":["czech"],"placenta":["czech"],"plakat":["czech"],"plamen":["czech"],"planeta":["czech"],"plastika":["czech"],"platit":["czech"],"plavidlo":["czech"],"plaz":["czech"],"plech":["czech"],"plemeno":["czech"],"plenta":["czech"],"ples":["czech"],"pletivo":["czech"],"plevel":["czech"],"plivat":["czech"],"plnit":["czech"],"plno":["czech"],"plocha":["czech"],"plodina":["czech"],"plomba":["czech"],"plout":["czech"],"pluk":["czech"],"plyn":["czech"],"pobavit":["czech"],"pobyt":["czech"],"pochod":["czech"],"pocit":["czech"],"poctivec":["czech"],"podat":["czech"],"podcenit":["czech"],"podepsat":["czech"],"podhled":["czech"],"podivit":["czech"],"podklad":["czech"],"podmanit":["czech"],"podnik":["czech"],"podoba":["czech"],"podpora":["czech"],"podraz":["czech"],"podstata":["czech"],"podvod":["czech"],"podzim":["czech"],"poezie":["czech"],"pohanka":["czech"],"pohnutka":["czech"],"pohovor":["czech"],"pohroma":["czech"],"pohyb":["czech"],"pointa":["czech"],"pojistka":["czech"],"pojmout":["czech"],"pokazit":["czech"],"pokles":["czech"],"pokoj":["czech"],"pokrok":["czech"],"pokuta":["czech"],"pokyn":["czech"],"poledne":["czech"],"polibek":["czech"],"polknout":["czech"],"poloha":["czech"],"polynom":["czech"],"pomalu":["czech"],"pominout":["czech"],"pomlka":["czech"],"pomoc":["czech"],"pomsta":["czech"],"pomyslet":["czech"],"ponechat":["czech"],"ponorka":["czech"],"ponurost":["czech"],"popadat":["czech"],"popel":["czech"],"popisek":["czech"],"poplach":["czech"],"poprosit":["czech"],"popsat":["czech"],"popud":["czech"],"poradce":["czech"],"porce":["czech"],"porod":["czech"],"porucha":["czech"],"poryv":["czech"],"posadit":["czech"],"posed":["czech"],"posila":["czech"],"poskok":["czech"],"poslanec":["czech"],"posoudit":["czech"],"pospolu":["czech"],"postava":["czech"],"posudek":["czech"],"posyp":["czech"],"potah":["czech"],"potkan":["czech"],"potlesk":["czech"],"potomek":["czech"],"potrava":["czech"],"potupa":["czech"],"potvora":["czech"],"poukaz":["czech"],"pouto":["czech"],"pouzdro":["czech"],"povaha":["czech"],"povidla":["czech"],"povlak":["czech"],"povoz":["czech"],"povrch":["czech"],"povstat":["czech"],"povyk":["czech"],"povzdech":["czech"],"pozdrav":["czech"],"pozemek":["czech"],"poznatek":["czech"],"pozor":["czech"],"pozvat":["czech"],"pracovat":["czech"],"prahory":["czech"],"praktika":["czech"],"prales":["czech"],"praotec":["czech"],"praporek":["czech"],"prase":["czech"],"pravda":["czech"],"princip":["czech"],"prkno":["czech"],"probudit":["czech"],"procento":["czech"],"prodej":["czech"],"profese":["czech"],"prohra":["czech"],"projekt":["czech"],"prolomit":["czech"],"promile":["czech"],"pronikat":["czech"],"propad":["czech"],"prorok":["czech"],"prosba":["czech"],"proton":["czech"],"proutek":["czech"],"provaz":["czech"],"prskavka":["czech"],"prsten":["czech"],"prudkost":["czech"],"prut":["czech"],"prvek":["czech"],"prvohory":["czech"],"psanec":["czech"],"psovod":["czech"],"pstruh":["czech"],"ptactvo":["czech"],"puberta":["czech"],"puch":["czech"],"pudl":["czech"],"pukavec":["czech"],"puklina":["czech"],"pukrle":["czech"],"pult":["czech"],"pumpa":["czech"],"punc":["czech"],"pupen":["czech"],"pusa":["czech"],"pusinka":["czech"],"pustina":["czech"],"putovat":["czech"],"putyka":["czech"],"pyramida":["czech"],"pysk":["czech"],"pytel":["czech"],"racek":["czech"],"rachot":["czech"],"radiace":["czech"],"radnice":["czech"],"radon":["czech"],"raft":["czech"],"ragby":["czech"],"raketa":["czech"],"rakovina":["czech"],"rameno":["czech"],"rampouch":["czech"],"rande":["czech"],"rarach":["czech"],"rarita":["czech"],"rasovna":["czech"],"rastr":["czech"],"ratolest":["czech"],"razance":["czech"],"razidlo":["czech"],"reagovat":["czech"],"reakce":["czech"],"recept":["czech"],"redaktor":["czech"],"referent":["czech"],"reflex":["czech"],"rejnok":["czech"],"reklama":["czech"],"rekord":["czech"],"rekrut":["czech"],"rektor":["czech"],"reputace":["czech"],"revize":["czech","turkish"],"revma":["czech"],"revolver":["czech"],"rezerva":["czech"],"riskovat":["czech"],"riziko":["czech"],"robotika":["czech"],"rodokmen":["czech"],"rohovka":["czech"],"rokle":["czech"],"rokoko":["czech"],"romaneto":["czech"],"ropovod":["czech"],"ropucha":["czech"],"rorejs":["czech"],"rosol":["czech"],"rostlina":["czech"],"rotmistr":["czech"],"rotoped":["czech"],"rotunda":["czech"],"roubenka":["czech"],"roucho":["czech"],"roup":["czech"],"roura":["czech"],"rovina":["czech"],"rovnice":["czech"],"rozbor":["czech"],"rozchod":["czech"],"rozdat":["czech"],"rozeznat":["czech"],"rozhodce":["czech"],"rozinka":["czech"],"rozjezd":["czech"],"rozkaz":["czech"],"rozloha":["czech"],"rozmar":["czech"],"rozpad":["czech"],"rozruch":["czech"],"rozsah":["czech"],"roztok":["czech"],"rozum":["czech"],"rozvod":["czech"],"rubrika":["czech"],"ruchadlo":["czech"],"rukavice":["czech"],"rukopis":["czech"],"ryba":["czech"],"rybolov":["czech"],"rychlost":["czech"],"rydlo":["czech"],"rypadlo":["czech"],"rytina":["czech"],"ryzost":["czech"],"sadista":["czech"],"sahat":["czech"],"sako":["czech"],"samec":["czech"],"samizdat":["czech"],"samota":["czech"],"sanitka":["czech"],"sardinka":["czech"],"sasanka":["czech"],"satelit":["czech"],"sazba":["czech"],"sazenice":["czech"],"sbor":["czech"],"schovat":["czech"],"sebranka":["czech"],"secese":["czech"],"sedadlo":["czech"],"sediment":["czech"],"sedlo":["czech"],"sehnat":["czech"],"sejmout":["czech"],"sekera":["czech"],"sekta":["czech"],"sekunda":["czech"],"sekvoje":["czech"],"semeno":["czech"],"seno":["czech"],"servis":["czech","turkish"],"sesadit":["czech"],"seshora":["czech"],"seskok":["czech"],"seslat":["czech"],"sestra":["czech"],"sesuv":["czech"],"sesypat":["czech"],"setba":["czech"],"setina":["czech"],"setkat":["czech"],"setnout":["czech"],"setrvat":["czech"],"sever":["czech"],"seznam":["czech"],"shoda":["czech"],"shrnout":["czech"],"sifon":["czech"],"silnice":["czech"],"sirka":["czech"],"sirotek":["czech"],"sirup":["czech"],"situace":["czech"],"skafandr":["czech"],"skalisko":["czech"],"skanzen":["czech"],"skaut":["czech"],"skeptik":["czech"],"skica":["czech"],"skladba":["czech"],"sklenice":["czech"],"sklo":["czech"],"skluz":["czech"],"skoba":["czech"],"skokan":["czech"],"skoro":["czech"],"skripta":["czech"],"skrz":["czech"],"skupina":["czech"],"skvost":["czech"],"skvrna":["czech"],"slabika":["czech"],"sladidlo":["czech"],"slanina":["czech"],"slast":["czech"],"slavnost":["czech"],"sledovat":["czech"],"slepec":["czech"],"sleva":["czech"],"slezina":["czech"],"slib":["czech"],"slina":["czech"],"sliznice":["czech"],"slon":["czech"],"sloupek":["czech"],"slovo":["czech"],"sluch":["czech"],"sluha":["czech"],"slunce":["czech"],"slupka":["czech"],"slza":["czech"],"smaragd":["czech"],"smetana":["czech"],"smilstvo":["czech"],"smlouva":["czech"],"smog":["czech"],"smrad":["czech"],"smrk":["czech"],"smrtka":["czech"],"smutek":["czech"],"smysl":["czech"],"snad":["czech"],"snaha":["czech"],"snob":["czech"],"sobota":["czech"],"socha":["czech"],"sodovka":["czech"],"sokol":["czech"],"sopka":["czech"],"sotva":["czech"],"souboj":["czech"],"soucit":["czech"],"soudce":["czech"],"souhlas":["czech"],"soulad":["czech"],"soumrak":["czech"],"souprava":["czech"],"soused":["czech"],"soutok":["czech"],"souviset":["czech"],"spalovna":["czech"],"spasitel":["czech"],"spis":["czech"],"splav":["czech"],"spodek":["czech"],"spojenec":["czech"],"spolu":["czech"],"sponzor":["czech"],"spornost":["czech"],"spousta":["czech"],"sprcha":["czech"],"spustit":["czech"],"sranda":["czech"],"sraz":["czech"],"srdce":["czech"],"srna":["czech"],"srnec":["czech"],"srovnat":["czech"],"srpen":["czech"],"srst":["czech"],"srub":["czech"],"stanice":["czech"],"starosta":["czech"],"statika":["czech"],"stavba":["czech"],"stehno":["czech"],"stezka":["czech"],"stodola":["czech"],"stolek":["czech"],"stopa":["czech"],"storno":["czech"],"stoupat":["czech"],"strach":["czech"],"stres":["czech"],"strhnout":["czech"],"strom":["czech"],"struna":["czech"],"studna":["czech"],"stupnice":["czech"],"stvol":["czech"],"styk":["czech"],"subjekt":["czech"],"subtropy":["czech"],"suchar":["czech"],"sudost":["czech"],"sukno":["czech"],"sundat":["czech"],"sunout":["czech"],"surikata":["czech"],"surovina":["czech"],"svah":["czech"],"svalstvo":["czech"],"svetr":["czech"],"svatba":["czech"],"svazek":["czech"],"svisle":["czech"],"svitek":["czech"],"svoboda":["czech"],"svodidlo":["czech"],"svorka":["czech"],"svrab":["czech"],"sykavka":["czech"],"sykot":["czech"],"synek":["czech"],"synovec":["czech"],"sypat":["czech"],"sypkost":["czech"],"syrovost":["czech"],"sysel":["czech"],"sytost":["czech"],"tabletka":["czech"],"tabule":["czech"],"tahoun":["czech"],"tajemno":["czech"],"tajfun":["czech"],"tajga":["czech"],"tajit":["czech"],"tajnost":["czech"],"taktika":["czech"],"tamhle":["czech"],"tampon":["czech","turkish"],"tancovat":["czech"],"tanec":["czech"],"tanker":["czech"],"tapeta":["czech"],"tavenina":["czech"],"tazatel":["czech"],"technika":["czech"],"tehdy":["czech"],"tekutina":["czech"],"telefon":["czech"],"temnota":["czech"],"tendence":["czech"],"tenista":["czech"],"tenor":["czech"],"teplota":["czech"],"tepna":["czech"],"teprve":["czech"],"terapie":["czech"],"termoska":["czech"],"textil":["czech"],"ticho":["czech"],"tiskopis":["czech"],"titulek":["czech"],"tkadlec":["czech"],"tkanina":["czech"],"tlapka":["czech"],"tleskat":["czech"],"tlukot":["czech"],"tlupa":["czech"],"tmel":["czech"],"toaleta":["czech"],"topinka":["czech"],"topol":["czech"],"torzo":["czech"],"touha":["czech"],"toulec":["czech"],"tradice":["czech"],"traktor":["czech"],"tramp":["czech"],"trasa":["czech"],"traverza":["czech"],"trefit":["czech"],"trest":["czech"],"trezor":["czech"],"trhavina":["czech"],"trhlina":["czech"],"trochu":["czech"],"trojice":["czech"],"troska":["czech"],"trouba":["czech"],"trpce":["czech"],"trpitel":["czech"],"trpkost":["czech"],"trubec":["czech"],"truchlit":["czech"],"truhlice":["czech"],"trus":["czech"],"trvat":["czech"],"tudy":["czech"],"tuhnout":["czech"],"tuhost":["czech"],"tundra":["czech"],"turista":["czech"],"turnaj":["czech"],"tuzemsko":["czech"],"tvaroh":["czech"],"tvorba":["czech"],"tvrdost":["czech"],"tvrz":["czech"],"tygr":["czech"],"tykev":["czech"],"ubohost":["czech"],"uboze":["czech"],"ubrat":["czech"],"ubrousek":["czech"],"ubrus":["czech"],"ubytovna":["czech"],"ucho":["czech"],"uctivost":["czech"],"udivit":["czech"],"uhradit":["czech"],"ujednat":["czech"],"ujistit":["czech"],"ujmout":["czech"],"ukazatel":["czech"],"uklidnit":["czech"],"uklonit":["czech"],"ukotvit":["czech"],"ukrojit":["czech"],"ulice":["czech"],"ulita":["czech"],"ulovit":["czech"],"umyvadlo":["czech"],"unavit":["czech"],"uniforma":["czech"],"uniknout":["czech"],"upadnout":["czech"],"uplatnit":["czech"],"uplynout":["czech"],"upoutat":["czech"],"upravit":["czech"],"uran":["czech"],"urazit":["czech"],"usednout":["czech"],"usilovat":["czech"],"usmrtit":["czech"],"usnadnit":["czech"],"usnout":["czech"],"usoudit":["czech"],"ustlat":["czech"],"ustrnout":["czech"],"utahovat":["czech"],"utkat":["czech"],"utlumit":["czech"],"utonout":["czech"],"utopenec":["czech"],"utrousit":["czech"],"uvalit":["czech"],"uvolnit":["czech"],"uvozovka":["czech"],"uzdravit":["czech"],"uzel":["czech"],"uzenina":["czech"],"uzlina":["czech"],"uznat":["czech"],"vagon":["czech","turkish"],"valcha":["czech"],"valoun":["czech"],"vana":["czech"],"vandal":["czech"],"vanilka":["czech"],"varan":["czech"],"varhany":["czech"],"varovat":["czech"],"vcelku":["czech"],"vchod":["czech"],"vdova":["czech"],"vedro":["czech"],"vegetace":["czech"],"vejce":["czech"],"velbloud":["czech"],"veletrh":["czech"],"velitel":["czech"],"velmoc":["czech"],"velryba":["czech"],"venkov":["czech"],"veranda":["czech"],"verze":["czech"],"veselka":["czech"],"veskrze":["czech"],"vesnice":["czech"],"vespodu":["czech"],"vesta":["czech"],"veterina":["czech"],"veverka":["czech"],"vibrace":["czech"],"vichr":["czech"],"videohra":["czech"],"vidina":["czech"],"vidle":["czech"],"vila":["czech"],"vinice":["czech"],"viset":["czech"],"vitalita":["czech"],"vize":["czech"],"vizitka":["czech"],"vjezd":["czech"],"vklad":["czech"],"vkus":["czech"],"vlajka":["czech"],"vlak":["czech"],"vlasec":["czech"],"vlevo":["czech"],"vlhkost":["czech"],"vliv":["czech"],"vlnovka":["czech"],"vloupat":["czech"],"vnucovat":["czech"],"vnuk":["czech"],"voda":["czech"],"vodivost":["czech"],"vodoznak":["czech"],"vodstvo":["czech"],"vojensky":["czech"],"vojna":["czech"],"vojsko":["czech"],"volant":["czech"],"volba":["czech"],"volit":["czech"],"volno":["czech"],"voskovka":["czech"],"vozidlo":["czech"],"vozovna":["czech"],"vpravo":["czech"],"vrabec":["czech"],"vracet":["czech"],"vrah":["czech"],"vrata":["czech"],"vrba":["czech"],"vrcholek":["czech"],"vrhat":["czech"],"vrstva":["czech"],"vrtule":["czech"],"vsadit":["czech"],"vstoupit":["czech"],"vstup":["czech"],"vtip":["czech"],"vybavit":["czech"],"vybrat":["czech"],"vychovat":["czech"],"vydat":["czech"],"vydra":["czech"],"vyfotit":["czech"],"vyhledat":["czech"],"vyhnout":["czech"],"vyhodit":["czech"],"vyhradit":["czech"],"vyhubit":["czech"],"vyjasnit":["czech"],"vyjet":["czech"],"vyjmout":["czech"],"vyklopit":["czech"],"vykonat":["czech"],"vylekat":["czech"],"vymazat":["czech"],"vymezit":["czech"],"vymizet":["czech"],"vymyslet":["czech"],"vynechat":["czech"],"vynikat":["czech"],"vynutit":["czech"],"vypadat":["czech"],"vyplatit":["czech"],"vypravit":["czech"],"vypustit":["czech"],"vyrazit":["czech"],"vyrovnat":["czech"],"vyrvat":["czech"],"vyslovit":["czech"],"vysoko":["czech"],"vystavit":["czech"],"vysunout":["czech"],"vysypat":["czech"],"vytasit":["czech"],"vytesat":["czech"],"vytratit":["czech"],"vyvinout":["czech"],"vyvolat":["czech"],"vyvrhel":["czech"],"vyzdobit":["czech"],"vyznat":["czech"],"vzadu":["czech"],"vzbudit":["czech"],"vzchopit":["czech"],"vzdor":["czech"],"vzduch":["czech"],"vzdychat":["czech"],"vzestup":["czech"],"vzhledem":["czech"],"vzkaz":["czech"],"vzlykat":["czech"],"vznik":["czech"],"vzorek":["czech"],"vzpoura":["czech"],"vztah":["czech"],"vztek":["czech"],"xylofon":["czech"],"zabrat":["czech"],"zabydlet":["czech"],"zachovat":["czech"],"zadarmo":["czech"],"zadusit":["czech"],"zafoukat":["czech"],"zahltit":["czech"],"zahodit":["czech"],"zahrada":["czech"],"zahynout":["czech"],"zajatec":["czech"],"zajet":["czech"],"zajistit":["czech"],"zaklepat":["czech"],"zakoupit":["czech"],"zalepit":["czech"],"zamezit":["czech"],"zamotat":["czech"],"zamyslet":["czech"],"zanechat":["czech"],"zanikat":["czech"],"zaplatit":["czech"],"zapojit":["czech"],"zapsat":["czech"],"zarazit":["czech"],"zastavit":["czech"],"zasunout":["czech"],"zatajit":["czech"],"zatemnit":["czech"],"zatknout":["czech"],"zaujmout":["czech"],"zavalit":["czech"],"zavelet":["czech"],"zavinit":["czech"],"zavolat":["czech"],"zavrtat":["czech"],"zazvonit":["czech"],"zbavit":["czech"],"zbrusu":["czech"],"zbudovat":["czech"],"zbytek":["czech"],"zdaleka":["czech"],"zdarma":["czech"],"zdatnost":["czech"],"zdivo":["czech"],"zdobit":["czech"],"zdroj":["czech"],"zdvih":["czech"],"zdymadlo":["czech"],"zelenina":["czech"],"zeman":["czech"],"zemina":["czech"],"zeptat":["czech"],"zezadu":["czech"],"zezdola":["czech"],"zhatit":["czech"],"zhltnout":["czech"],"zhluboka":["czech"],"zhotovit":["czech"],"zhruba":["czech"],"zima":["czech"],"zimnice":["czech"],"zjemnit":["czech"],"zklamat":["czech"],"zkoumat":["czech"],"zkratka":["czech"],"zkumavka":["czech"],"zlato":["czech"],"zlehka":["czech"],"zloba":["czech"],"zlom":["czech"],"zlost":["czech"],"zlozvyk":["czech"],"zmapovat":["czech"],"zmar":["czech"],"zmatek":["czech"],"zmije":["czech"],"zmizet":["czech"],"zmocnit":["czech"],"zmodrat":["czech"],"zmrzlina":["czech"],"zmutovat":["czech"],"znak":["czech"],"znalost":["czech"],"znamenat":["czech"],"znovu":["czech"],"zobrazit":["czech"],"zotavit":["czech"],"zoubek":["czech"],"zoufale":["czech"],"zplodit":["czech"],"zpomalit":["czech"],"zprava":["czech"],"zprostit":["czech"],"zprudka":["czech"],"zprvu":["czech"],"zrada":["czech"],"zranit":["czech"],"zrcadlo":["czech"],"zrnitost":["czech"],"zrno":["czech"],"zrovna":["czech"],"zrychlit":["czech"],"zrzavost":["czech"],"zticha":["czech"],"ztratit":["czech"],"zubovina":["czech"],"zubr":["czech"],"zvednout":["czech"],"zvenku":["czech"],"zvesela":["czech"],"zvon":["czech"],"zvrat":["czech"],"zvukovod":["czech"],"zvyk":["czech"],"abandon":["english","french"],"ability":["english"],"able":["english"],"about":["english"],"above":["english"],"absent":["english"],"absorb":["english"],"abstract":["english"],"absurd":["english"],"abuse":["english"],"access":["english"],"accident":["english"],"account":["english"],"accuse":["english"],"achieve":["english"],"acid":["english"],"acoustic":["english"],"acquire":["english"],"across":["english"],"act":["english"],"action":["english"],"actor":["english"],"actress":["english"],"actual":["english"],"adapt":["english"],"add":["english"],"addict":["english"],"address":["english"],"adjust":["english"],"admit":["english"],"adult":["english"],"advance":["english"],"advice":["english"],"aerobic":["english"],"affair":["english"],"afford":["english"],"afraid":["english"],"again":["english"],"age":["english"],"agent":["english"],"agree":["english"],"ahead":["english"],"aim":["english"],"air":["english"],"airport":["english"],"aisle":["english"],"alarm":["english"],"album":["english"],"alcohol":["english"],"alert":["english"],"alien":["english"],"all":["english"],"alley":["english"],"allow":["english"],"almost":["english"],"alone":["english"],"alpha":["english"],"already":["english"],"also":["english"],"alter":["english"],"always":["english"],"amateur":["english","french"],"amazing":["english"],"among":["english"],"amount":["english"],"amused":["english"],"analyst":["english"],"anchor":["english"],"ancient":["english"],"anger":["english"],"angle":["english","french"],"angry":["english"],"animal":["english","french"],"ankle":["english"],"announce":["english"],"annual":["english"],"another":["english"],"answer":["english"],"antenna":["english"],"antique":["english"],"anxiety":["english"],"any":["english"],"apart":["english"],"apology":["english"],"appear":["english"],"apple":["english"],"approve":["english"],"april":["english"],"arch":["english"],"arctic":["english"],"area":["english"],"arena":["english","turkish"],"argue":["english"],"arm":["english"],"armed":["english"],"armor":["english"],"army":["english"],"around":["english"],"arrange":["english"],"arrest":["english"],"arrive":["english"],"arrow":["english"],"art":["english"],"artefact":["english"],"artist":["english","turkish"],"artwork":["english"],"ask":["english"],"aspect":["english","french"],"assault":["english"],"asset":["english"],"assist":["english"],"assume":["english"],"asthma":["english"],"athlete":["english"],"atom":["english","turkish"],"attack":["english"],"attend":["english"],"attitude":["english"],"attract":["english"],"auction":["english"],"audit":["english"],"august":["english"],"aunt":["english"],"author":["english"],"auto":["english"],"autumn":["english"],"average":["english"],"avocado":["english"],"avoid":["english"],"awake":["english"],"aware":["english"],"away":["english"],"awesome":["english"],"awful":["english"],"awkward":["english"],"axis":["english"],"baby":["english"],"bachelor":["english"],"bacon":["english"],"badge":["english","french"],"bag":["english"],"balance":["english"],"balcony":["english"],"ball":["english"],"bamboo":["english"],"banana":["english"],"banner":["english"],"bar":["english"],"barely":["english"],"bargain":["english"],"barrel":["english"],"base":["english"],"basic":["english"],"basket":["english"],"battle":["english"],"beach":["english"],"bean":["english"],"beauty":["english"],"because":["english"],"become":["english"],"beef":["english"],"before":["english"],"begin":["english"],"behave":["english"],"behind":["english"],"believe":["english"],"below":["english"],"belt":["english"],"bench":["english"],"benefit":["english"],"best":["english"],"betray":["english"],"better":["english"],"between":["english"],"beyond":["english"],"bicycle":["english","french"],"bid":["english"],"bike":["english"],"bind":["english"],"biology":["english"],"bird":["english"],"birth":["english"],"bitter":["english"],"black":["english"],"blade":["english"],"blame":["english"],"blanket":["english"],"blast":["english"],"bleak":["english"],"bless":["english"],"blind":["english"],"blood":["english"],"blossom":["english"],"blouse":["english"],"blue":["english"],"blur":["english"],"blush":["english"],"board":["english"],"boat":["english"],"body":["english"],"boil":["english"],"bomb":["english"],"bone":["english"],"bonus":["english","french"],"book":["english"],"boost":["english"],"border":["english"],"boring":["english"],"borrow":["english"],"boss":["english"],"bottom":["english"],"bounce":["english"],"box":["english"],"boy":["english"],"bracket":["english"],"brain":["english"],"brand":["english"],"brass":["english"],"brave":["english","french"],"bread":["english"],"breeze":["english"],"brick":["english"],"bridge":["english"],"brief":["english"],"bright":["english"],"bring":["english"],"brisk":["english"],"broccoli":["english"],"broken":["english"],"bronze":["english"],"broom":["english"],"brother":["english"],"brown":["english"],"brush":["english"],"bubble":["english"],"buddy":["english"],"budget":["english"],"buffalo":["english"],"build":["english"],"bulb":["english"],"bulk":["english"],"bullet":["english"],"bundle":["english"],"bunker":["english"],"burden":["english"],"burger":["english"],"burst":["english"],"bus":["english"],"business":["english"],"busy":["english"],"butter":["english"],"buyer":["english"],"buzz":["english"],"cabbage":["english"],"cabin":["english"],"cable":["english"],"cactus":["english"],"cage":["english"],"cake":["english"],"call":["english"],"calm":["english"],"camera":["english"],"camp":["english"],"can":["english"],"canal":["english","french"],"cancel":["english"],"candy":["english"],"cannon":["english"],"canoe":["english"],"canvas":["english"],"canyon":["english"],"capable":["english","french"],"capital":["english"],"captain":["english"],"car":["english"],"carbon":["english"],"card":["english"],"cargo":["english"],"carpet":["english"],"carry":["english"],"cart":["english"],"case":["english"],"cash":["english"],"casino":["english"],"castle":["english"],"casual":["english"],"cat":["english"],"catalog":["english"],"catch":["english"],"category":["english"],"cattle":["english"],"caught":["english"],"cause":["english"],"caution":["english","french"],"cave":["english"],"ceiling":["english"],"celery":["english"],"cement":["english"],"census":["english"],"century":["english"],"cereal":["english"],"certain":["english"],"chair":["english"],"chalk":["english"],"champion":["english"],"change":["english"],"chaos":["english"],"chapter":["english"],"charge":["english"],"chase":["english"],"chat":["english"],"cheap":["english"],"check":["english"],"cheese":["english"],"chef":["english"],"cherry":["english"],"chest":["english"],"chicken":["english"],"chief":["english"],"child":["english"],"chimney":["english"],"choice":["english"],"choose":["english"],"chronic":["english"],"chuckle":["english"],"chunk":["english"],"churn":["english"],"cigar":["english"],"cinnamon":["english"],"circle":["english"],"citizen":["english"],"city":["english"],"civil":["english","french"],"claim":["english"],"clap":["english"],"clarify":["english"],"claw":["english"],"clay":["english"],"clean":["english"],"clerk":["english"],"clever":["english"],"click":["english"],"client":["english","french"],"cliff":["english"],"climb":["english"],"clinic":["english"],"clip":["english"],"clock":["english"],"clog":["english"],"close":["english"],"cloth":["english"],"cloud":["english"],"clown":["english"],"club":["english"],"clump":["english"],"cluster":["english"],"clutch":["english"],"coach":["english"],"coast":["english"],"coconut":["english"],"code":["english"],"coffee":["english"],"coil":["english"],"coin":["english"],"collect":["english"],"color":["english"],"column":["english"],"combine":["english"],"come":["english"],"comfort":["english"],"comic":["english"],"common":["english"],"company":["english"],"concert":["english","french"],"conduct":["english"],"confirm":["english"],"congress":["english"],"connect":["english"],"consider":["english"],"control":["english"],"convince":["english"],"cook":["english"],"cool":["english"],"copper":["english"],"copy":["english"],"coral":["english"],"core":["english"],"corn":["english"],"correct":["english","french"],"cost":["english"],"cotton":["english"],"couch":["english"],"country":["english"],"couple":["english"],"course":["english"],"cousin":["english"],"cover":["english"],"coyote":["english","french"],"crack":["english"],"cradle":["english"],"craft":["english"],"cram":["english"],"crane":["english"],"crash":["english"],"crater":["english"],"crawl":["english"],"crazy":["english"],"cream":["english"],"credit":["english"],"creek":["english"],"crew":["english"],"cricket":["english"],"crime":["english"],"crisp":["english"],"critic":["english"],"crop":["english"],"cross":["english"],"crouch":["english"],"crowd":["english"],"crucial":["english","french"],"cruel":["english","french"],"cruise":["english"],"crumble":["english"],"crunch":["english"],"crush":["english"],"cry":["english"],"crystal":["english"],"cube":["english"],"culture":["english"],"cup":["english"],"cupboard":["english"],"curious":["english"],"current":["english"],"curtain":["english"],"curve":["english"],"cushion":["english"],"custom":["english"],"cute":["english"],"cycle":["english","french"],"dad":["english"],"damage":["english"],"damp":["english"],"dance":["english"],"danger":["english","french"],"daring":["english"],"dash":["english"],"daughter":["english"],"dawn":["english"],"day":["english"],"deal":["english"],"debate":["english"],"debris":["english"],"decade":["english"],"december":["english"],"decide":["english"],"decline":["english"],"decorate":["english"],"decrease":["english"],"deer":["english"],"defense":["english"],"define":["english"],"defy":["english"],"degree":["english"],"delay":["english"],"deliver":["english"],"demand":["english"],"demise":["english"],"denial":["english"],"dentist":["english"],"deny":["english"],"depart":["english"],"depend":["english"],"deposit":["english"],"depth":["english"],"deputy":["english"],"derive":["english"],"describe":["english"],"desert":["english"],"design":["english"],"desk":["english"],"despair":["english"],"destroy":["english"],"detail":["english"],"detect":["english"],"develop":["english"],"device":["english"],"devote":["english"],"diagram":["english"],"dial":["english"],"diamond":["english"],"diary":["english"],"dice":["english"],"diesel":["english"],"diet":["english"],"differ":["english"],"digital":["english","french"],"dignity":["english"],"dilemma":["english"],"dinner":["english"],"dinosaur":["english"],"direct":["english"],"dirt":["english"],"disagree":["english"],"discover":["english"],"disease":["english"],"dish":["english"],"dismiss":["english"],"disorder":["english"],"display":["english"],"distance":["english","french"],"divert":["english"],"divide":["english"],"divorce":["english"],"dizzy":["english"],"doctor":["english"],"document":["english"],"dog":["english"],"doll":["english"],"dolphin":["english"],"domain":["english"],"donate":["english"],"donkey":["english"],"donor":["english"],"door":["english"],"dose":["english"],"double":["english","french"],"dove":["english"],"draft":["english"],"dragon":["english","french"],"drama":["english"],"drastic":["english"],"draw":["english"],"dream":["english"],"dress":["english"],"drift":["english"],"drill":["english"],"drink":["english"],"drip":["english"],"drive":["english"],"drop":["english"],"drum":["english"],"dry":["english"],"duck":["english"],"dumb":["english"],"dune":["english"],"during":["english"],"dust":["english"],"dutch":["english"],"duty":["english"],"dwarf":["english"],"dynamic":["english"],"eager":["english"],"eagle":["english"],"early":["english"],"earn":["english"],"earth":["english"],"easily":["english"],"east":["english"],"easy":["english"],"echo":["english"],"ecology":["english"],"economy":["english"],"edge":["english"],"edit":["english"],"educate":["english"],"effort":["english","french"],"egg":["english"],"eight":["english"],"either":["english"],"elbow":["english"],"elder":["english"],"electric":["english"],"elegant":["english"],"element":["english"],"elephant":["english"],"elevator":["english"],"elite":["english"],"else":["english"],"embark":["english"],"embody":["english"],"embrace":["english"],"emerge":["english"],"emotion":["english"],"employ":["english"],"empower":["english"],"empty":["english"],"enable":["english"],"enact":["english"],"end":["english"],"endless":["english"],"endorse":["english"],"enemy":["english"],"energy":["english"],"enforce":["english"],"engage":["english"],"engine":["english"],"enhance":["english"],"enjoy":["english"],"enlist":["english"],"enough":["english"],"enrich":["english"],"enroll":["english"],"ensure":["english"],"enter":["english"],"entire":["english"],"entry":["english"],"envelope":["english"],"episode":["english"],"equal":["english"],"equip":["english"],"era":["english"],"erase":["english"],"erode":["english"],"erosion":["english"],"error":["english"],"erupt":["english"],"escape":["english"],"essay":["english"],"essence":["english","french"],"estate":["english"],"eternal":["english"],"ethics":["english"],"evidence":["english"],"evil":["english"],"evoke":["english"],"evolve":["english"],"exact":["english","french"],"example":["english"],"excess":["english"],"exchange":["english"],"excite":["english"],"exclude":["english"],"excuse":["english","french"],"execute":["english"],"exercise":["english"],"exhaust":["english"],"exhibit":["english"],"exile":["english"],"exist":["english"],"exit":["english"],"exotic":["english"],"expand":["english"],"expect":["english"],"expire":["english"],"explain":["english"],"expose":["english"],"express":["english"],"extend":["english"],"extra":["english"],"eye":["english"],"eyebrow":["english"],"fabric":["english"],"face":["english"],"faculty":["english"],"fade":["english"],"faint":["english"],"faith":["english"],"fall":["english"],"false":["english"],"fame":["english"],"family":["english"],"famous":["english"],"fan":["english"],"fancy":["english"],"fantasy":["english"],"farm":["english"],"fashion":["english"],"fat":["english"],"fatal":["english","french"],"father":["english"],"fatigue":["english","french"],"fault":["english"],"favorite":["english"],"feature":["english"],"february":["english"],"federal":["english","turkish"],"fee":["english"],"feed":["english"],"feel":["english"],"female":["english"],"fence":["english"],"festival":["english","french","turkish"],"fetch":["english"],"fever":["english"],"few":["english"],"fiber":["english"],"fiction":["english"],"field":["english"],"figure":["english","french"],"file":["english"],"film":["english"],"filter":["english"],"final":["english"],"find":["english"],"fine":["english"],"finger":["english"],"finish":["english"],"fire":["english"],"firm":["english"],"first":["english"],"fiscal":["english"],"fish":["english"],"fit":["english"],"fitness":["english"],"fix":["english"],"flag":["english"],"flame":["english"],"flash":["english"],"flat":["english"],"flavor":["english"],"flee":["english"],"flight":["english"],"flip":["english"],"float":["english"],"flock":["english"],"floor":["english"],"flower":["english"],"fluid":["english"],"flush":["english"],"fly":["english"],"foam":["english"],"focus":["english"],"fog":["english"],"foil":["english"],"fold":["english"],"follow":["english"],"food":["english"],"foot":["english"],"force":["english"],"forest":["english"],"forget":["english"],"fork":["english"],"fortune":["english","french"],"forum":["english"],"forward":["english"],"fossil":["english"],"foster":["english"],"found":["english"],"fox":["english"],"fragile":["english","french"],"frame":["english"],"frequent":["english"],"fresh":["english"],"friend":["english"],"fringe":["english"],"frog":["english"],"front":["english"],"frost":["english"],"frown":["english"],"frozen":["english"],"fruit":["english","french"],"fuel":["english"],"fun":["english"],"funny":["english"],"furnace":["english"],"fury":["english"],"future":["english"],"gadget":["english"],"gain":["english"],"galaxy":["english"],"gallery":["english"],"game":["english"],"gap":["english"],"garage":["english"],"garbage":["english"],"garden":["english"],"garlic":["english"],"garment":["english"],"gas":["english"],"gasp":["english"],"gate":["english"],"gather":["english"],"gauge":["english"],"gaze":["english"],"general":["english"],"genius":["english"],"genre":["english"],"gentle":["english"],"genuine":["english"],"gesture":["english"],"ghost":["english"],"giant":["english"],"gift":["english"],"giggle":["english"],"ginger":["english"],"giraffe":["english"],"girl":["english"],"give":["english"],"glad":["english"],"glance":["english"],"glare":["english"],"glass":["english"],"glide":["english"],"glimpse":["english"],"globe":["english","french"],"gloom":["english"],"glory":["english"],"glove":["english"],"glow":["english"],"glue":["english"],"goat":["english"],"goddess":["english"],"gold":["english"],"good":["english"],"goose":["english"],"gorilla":["english"],"gospel":["english"],"gossip":["english"],"govern":["english"],"gown":["english"],"grab":["english"],"grace":["english"],"grain":["english"],"grant":["english"],"grape":["english"],"grass":["english"],"gravity":["english"],"great":["english"],"green":["english"],"grid":["english"],"grief":["english"],"grit":["english"],"grocery":["english"],"group":["english"],"grow":["english"],"grunt":["english"],"guard":["english"],"guess":["english"],"guide":["english","french"],"guilt":["english"],"guitar":["english"],"gun":["english"],"gym":["english"],"habit":["english"],"hair":["english"],"half":["english"],"hammer":["english"],"hamster":["english"],"hand":["english"],"happy":["english"],"harbor":["english"],"hard":["english"],"harsh":["english"],"harvest":["english"],"hat":["english"],"have":["english"],"hawk":["english"],"hazard":["english"],"head":["english"],"health":["english"],"heart":["english"],"heavy":["english"],"hedgehog":["english"],"height":["english"],"hello":["english"],"helmet":["english"],"help":["english"],"hen":["english"],"hero":["english"],"hidden":["english"],"high":["english"],"hill":["english"],"hint":["english"],"hip":["english"],"hire":["english"],"history":["english"],"hobby":["english"],"hockey":["english"],"hold":["english"],"hole":["english"],"holiday":["english"],"hollow":["english"],"home":["english"],"honey":["english"],"hood":["english"],"hope":["english"],"horn":["english"],"horror":["english"],"horse":["english"],"hospital":["english"],"host":["english"],"hotel":["english"],"hour":["english"],"hover":["english"],"hub":["english"],"huge":["english"],"human":["english"],"humble":["english","french"],"humor":["english"],"hundred":["english"],"hungry":["english"],"hunt":["english"],"hurdle":["english"],"hurry":["english"],"hurt":["english"],"husband":["english"],"hybrid":["english"],"ice":["english"],"icon":["english"],"idea":["english"],"identify":["english"],"idle":["english"],"ignore":["english"],"ill":["english"],"illegal":["english"],"illness":["english"],"image":["english","french"],"imitate":["english"],"immense":["english","french"],"immune":["english"],"impact":["english","french"],"impose":["english"],"improve":["english"],"impulse":["english"],"inch":["english"],"include":["english"],"income":["english"],"increase":["english"],"index":["english"],"indicate":["english"],"indoor":["english"],"industry":["english"],"infant":["english"],"inflict":["english"],"inform":["english"],"inhale":["english"],"inherit":["english"],"initial":["english"],"inject":["english"],"injury":["english"],"inmate":["english"],"inner":["english"],"innocent":["english","french"],"input":["english"],"inquiry":["english"],"insane":["english"],"insect":["english"],"inside":["english"],"inspire":["english"],"install":["english"],"intact":["english","french"],"interest":["english"],"into":["english"],"invest":["english"],"invite":["english"],"involve":["english"],"iron":["english"],"island":["english"],"isolate":["english"],"issue":["english"],"item":["english"],"ivory":["english"],"jacket":["english"],"jaguar":["english","french"],"jar":["english"],"jazz":["english"],"jealous":["english"],"jeans":["english"],"jelly":["english"],"jewel":["english"],"job":["english"],"join":["english"],"joke":["english"],"journey":["english"],"joy":["english"],"judge":["english"],"juice":["english"],"jump":["english"],"jungle":["english"],"junior":["english","french"],"junk":["english"],"just":["english"],"kangaroo":["english"],"keen":["english"],"keep":["english"],"ketchup":["english"],"key":["english"],"kick":["english"],"kid":["english"],"kidney":["english"],"kind":["english"],"kingdom":["english"],"kiss":["english"],"kit":["english"],"kitchen":["english"],"kite":["english"],"kitten":["english"],"kiwi":["english"],"knee":["english"],"knife":["english"],"knock":["english"],"know":["english"],"lab":["english"],"label":["english","french"],"labor":["english"],"ladder":["english"],"lady":["english"],"lake":["english"],"lamp":["english"],"language":["english"],"laptop":["english"],"large":["english"],"later":["english"],"latin":["english"],"laugh":["english"],"laundry":["english"],"lava":["english"],"law":["english"],"lawn":["english"],"lawsuit":["english"],"layer":["english"],"lazy":["english"],"leader":["english"],"leaf":["english"],"learn":["english"],"leave":["english"],"lecture":["english","french"],"left":["english"],"leg":["english"],"legal":["english"],"legend":["english"],"leisure":["english"],"lemon":["english"],"lend":["english"],"length":["english"],"lens":["english"],"leopard":["english"],"lesson":["english"],"letter":["english"],"level":["english"],"liar":["english"],"liberty":["english"],"library":["english"],"license":["english"],"life":["english"],"lift":["english"],"light":["english"],"like":["english"],"limb":["english"],"limit":["english"],"link":["english"],"lion":["english"],"liquid":["english"],"list":["english"],"little":["english"],"live":["english"],"lizard":["english"],"load":["english"],"loan":["english"],"lobster":["english"],"local":["english"],"lock":["english"],"logic":["english"],"lonely":["english"],"long":["english"],"loop":["english"],"lottery":["english"],"loud":["english"],"lounge":["english"],"love":["english"],"loyal":["english","french"],"lucky":["english"],"luggage":["english"],"lumber":["english"],"lunar":["english"],"lunch":["english"],"luxury":["english"],"lyrics":["english"],"machine":["english","french"],"mad":["english"],"magic":["english"],"magnet":["english"],"maid":["english"],"mail":["english"],"main":["english"],"major":["english"],"make":["english"],"mammal":["english"],"man":["english"],"manage":["english"],"mandate":["english"],"mango":["english"],"mansion":["english"],"manual":["english"],"maple":["english"],"marble":["english"],"march":["english"],"margin":["english"],"marine":["english"],"market":["english","turkish"],"marriage":["english"],"mask":["english"],"mass":["english"],"master":["english"],"match":["english"],"material":["english"],"math":["english"],"matrix":["english"],"matter":["english"],"maximum":["english"],"maze":["english"],"meadow":["english"],"mean":["english"],"measure":["english"],"meat":["english"],"mechanic":["english"],"medal":["english"],"media":["english"],"melody":["english"],"melt":["english"],"member":["english"],"memory":["english"],"mention":["english"],"menu":["english"],"mercy":["english"],"merge":["english"],"merit":["english"],"merry":["english"],"mesh":["english"],"message":["english"],"metal":["english"],"method":["english"],"middle":["english"],"midnight":["english"],"milk":["english"],"million":["english","french"],"mimic":["english"],"mind":["english"],"minimum":["english"],"minor":["english"],"minute":["english","french"],"miracle":["english","french"],"mirror":["english"],"misery":["english"],"miss":["english"],"mistake":["english"],"mix":["english"],"mixed":["english"],"mixture":["english"],"mobile":["english","french"],"model":["english","turkish"],"modify":["english"],"mom":["english"],"moment":["english"],"monitor":["english"],"monkey":["english"],"monster":["english"],"month":["english"],"moon":["english"],"moral":["english"],"more":["english"],"morning":["english"],"mosquito":["english"],"mother":["english"],"motion":["english"],"motor":["english","turkish"],"mountain":["english"],"mouse":["english"],"move":["english"],"movie":["english"],"much":["english"],"muffin":["english"],"mule":["english"],"multiply":["english"],"muscle":["english","french"],"museum":["english"],"mushroom":["english"],"music":["english"],"must":["english"],"mutual":["english"],"myself":["english"],"mystery":["english"],"myth":["english"],"naive":["english"],"name":["english"],"napkin":["english"],"narrow":["english"],"nasty":["english"],"nation":["english","french"],"nature":["english","french"],"near":["english"],"neck":["english"],"need":["english"],"negative":["english"],"neglect":["english"],"neither":["english"],"nephew":["english"],"nerve":["english"],"nest":["english"],"net":["english"],"network":["english"],"neutral":["english"],"never":["english"],"news":["english"],"next":["english"],"nice":["english"],"night":["english"],"noble":["english","french"],"noise":["english"],"nominee":["english"],"noodle":["english"],"normal":["english","turkish"],"north":["english"],"nose":["english"],"notable":["english","french"],"note":["english"],"nothing":["english"],"notice":["english"],"novel":["english"],"now":["english"],"nuclear":["english"],"number":["english"],"nurse":["english"],"nut":["english"],"oak":["english"],"obey":["english"],"object":["english"],"oblige":["english"],"obscure":["english"],"observe":["english"],"obtain":["english"],"obvious":["english"],"occur":["english"],"ocean":["english"],"october":["english"],"odor":["english"],"off":["english"],"offer":["english"],"office":["english"],"often":["english"],"oil":["english"],"okay":["english"],"old":["english"],"olive":["english"],"olympic":["english"],"omit":["english"],"once":["english"],"one":["english"],"onion":["english"],"online":["english"],"only":["english"],"open":["english"],"opera":["english","turkish"],"opinion":["english","french"],"oppose":["english"],"option":["english"],"orange":["english","french"],"orbit":["english"],"orchard":["english"],"order":["english"],"ordinary":["english"],"organ":["english"],"orient":["english"],"original":["english"],"orphan":["english"],"ostrich":["english"],"other":["english"],"outdoor":["english"],"outer":["english"],"output":["english"],"outside":["english"],"oval":["english"],"oven":["english"],"over":["english"],"own":["english"],"owner":["english"],"oxygen":["english"],"oyster":["english"],"ozone":["english","french"],"pact":["english"],"paddle":["english"],"page":["english"],"pair":["english"],"palace":["english","french"],"palm":["english"],"panda":["english","french","turkish"],"panel":["english","turkish"],"panic":["english"],"panther":["english"],"paper":["english"],"parade":["english"],"parent":["english"],"park":["english"],"parrot":["english"],"party":["english"],"pass":["english"],"patch":["english"],"path":["english"],"patient":["english"],"patrol":["english"],"pattern":["english"],"pause":["english"],"pave":["english"],"payment":["english"],"peace":["english"],"peanut":["english"],"pear":["english"],"peasant":["english"],"pelican":["english"],"pen":["english"],"penalty":["english"],"pencil":["english"],"people":["english"],"pepper":["english"],"perfect":["english"],"permit":["english"],"person":["english"],"pet":["english"],"phone":["english"],"photo":["english"],"phrase":["english","french"],"physical":["english"],"piano":["english","french"],"picnic":["english"],"picture":["english"],"piece":["english"],"pig":["english"],"pigeon":["english"],"pill":["english"],"pilot":["english","turkish"],"pink":["english"],"pioneer":["english"],"pipe":["english"],"pistol":["english"],"pitch":["english"],"pizza":["english","french"],"place":["english"],"planet":["english"],"plastic":["english"],"plate":["english"],"play":["english"],"please":["english"],"pledge":["english"],"pluck":["english"],"plug":["english"],"plunge":["english"],"poem":["english"],"poet":["english"],"point":["english"],"polar":["english"],"pole":["english"],"police":["english"],"pond":["english"],"pony":["english"],"pool":["english"],"popular":["english"],"portion":["english"],"position":["english","french"],"possible":["english"],"post":["english"],"potato":["english"],"pottery":["english"],"poverty":["english"],"powder":["english"],"power":["english"],"practice":["english"],"praise":["english"],"predict":["english"],"prefer":["english"],"prepare":["english"],"present":["english"],"pretty":["english"],"prevent":["english"],"price":["english"],"pride":["english"],"primary":["english"],"print":["english"],"priority":["english"],"prison":["english","french"],"private":["english"],"prize":["english"],"problem":["english","turkish"],"process":["english"],"produce":["english"],"profit":["english"],"program":["english","turkish"],"project":["english"],"promote":["english"],"proof":["english"],"property":["english"],"prosper":["english"],"protect":["english"],"proud":["english"],"provide":["english"],"public":["english","french"],"pudding":["english"],"pull":["english"],"pulp":["english"],"pulse":["english"],"pumpkin":["english"],"punch":["english"],"pupil":["english"],"puppy":["english"],"purchase":["english"],"purity":["english"],"purpose":["english"],"purse":["english"],"push":["english"],"put":["english"],"puzzle":["english","french"],"pyramid":["english"],"quality":["english"],"quantum":["english"],"quarter":["english"],"question":["english","french"],"quick":["english"],"quit":["english"],"quiz":["english"],"quote":["english"],"rabbit":["english"],"raccoon":["english"],"race":["english"],"rack":["english"],"radar":["english","turkish"],"radio":["english"],"rail":["english"],"rain":["english"],"raise":["english"],"rally":["english"],"ramp":["english"],"ranch":["english"],"random":["english"],"range":["english"],"rapid":["english"],"rare":["english"],"rate":["english"],"rather":["english"],"raven":["english"],"raw":["english"],"razor":["english"],"ready":["english"],"real":["english"],"reason":["english"],"rebel":["english"],"rebuild":["english"],"recall":["english"],"receive":["english"],"recipe":["english"],"record":["english"],"recycle":["english"],"reduce":["english"],"reflect":["english"],"reform":["english","turkish"],"refuse":["english"],"region":["english"],"regret":["english"],"regular":["english"],"reject":["english"],"relax":["english"],"release":["english"],"relief":["english","french"],"rely":["english"],"remain":["english"],"remember":["english"],"remind":["english"],"remove":["english"],"render":["english"],"renew":["english"],"rent":["english"],"reopen":["english"],"repair":["english"],"repeat":["english"],"replace":["english"],"report":["english"],"require":["english"],"rescue":["english"],"resemble":["english"],"resist":["english"],"resource":["english"],"response":["english"],"result":["english"],"retire":["english"],"retreat":["english"],"return":["english"],"reunion":["english"],"reveal":["english"],"review":["english"],"reward":["english"],"rhythm":["english"],"rib":["english"],"ribbon":["english"],"rice":["english"],"rich":["english"],"ride":["english"],"ridge":["english"],"rifle":["english"],"right":["english"],"rigid":["english"],"ring":["english"],"riot":["english"],"ripple":["english"],"risk":["english"],"ritual":["english"],"rival":["english","french"],"river":["english"],"road":["english"],"roast":["english"],"robot":["english","turkish"],"robust":["english"],"rocket":["english"],"romance":["english","french"],"roof":["english"],"rookie":["english"],"room":["english"],"rose":["english"],"rotate":["english"],"rough":["english"],"round":["english"],"route":["english"],"royal":["english"],"rubber":["english"],"rude":["english"],"rug":["english"],"rule":["english"],"run":["english"],"runway":["english"],"rural":["english"],"sad":["english"],"saddle":["english"],"sadness":["english"],"safe":["english"],"sail":["english"],"salad":["english"],"salmon":["english"],"salon":["english","french","turkish"],"salt":["english"],"salute":["english"],"same":["english"],"sample":["english"],"sand":["english"],"satisfy":["english"],"satoshi":["english"],"sauce":["english"],"sausage":["english"],"save":["english"],"say":["english"],"scale":["english"],"scan":["english"],"scare":["english"],"scatter":["english"],"scene":["english"],"scheme":["english"],"school":["english"],"science":["english","french"],"scissors":["english"],"scorpion":["english"],"scout":["english"],"scrap":["english"],"screen":["english"],"script":["english"],"scrub":["english"],"sea":["english"],"search":["english"],"season":["english"],"seat":["english"],"second":["english"],"secret":["english"],"section":["english"],"security":["english"],"seed":["english"],"seek":["english"],"segment":["english"],"select":["english"],"sell":["english"],"seminar":["english"],"senior":["english"],"sense":["english"],"sentence":["english","french"],"series":["english"],"service":["english","french"],"session":["english"],"settle":["english"],"setup":["english"],"seven":["english"],"shadow":["english"],"shaft":["english"],"shallow":["english"],"share":["english"],"shed":["english"],"shell":["english"],"sheriff":["english"],"shield":["english"],"shift":["english"],"shine":["english"],"ship":["english"],"shiver":["english"],"shock":["english"],"shoe":["english"],"shoot":["english"],"shop":["english"],"short":["english"],"shoulder":["english"],"shove":["english"],"shrimp":["english"],"shrug":["english"],"shuffle":["english"],"shy":["english"],"sibling":["english"],"sick":["english"],"side":["english"],"siege":["english"],"sight":["english"],"sign":["english"],"silent":["english"],"silk":["english"],"silly":["english"],"silver":["english"],"similar":["english"],"simple":["english","french"],"since":["english"],"sing":["english"],"siren":["english"],"sister":["english"],"situate":["english"],"six":["english"],"size":["english"],"skate":["english"],"sketch":["english"],"ski":["english"],"skill":["english"],"skin":["english"],"skirt":["english"],"skull":["english"],"slab":["english"],"slam":["english"],"sleep":["english"],"slender":["english"],"slice":["english"],"slide":["english"],"slight":["english"],"slim":["english"],"slogan":["english","turkish"],"slot":["english"],"slow":["english"],"slush":["english"],"small":["english"],"smart":["english"],"smile":["english"],"smoke":["english"],"smooth":["english"],"snack":["english"],"snake":["english"],"snap":["english"],"sniff":["english"],"snow":["english"],"soap":["english"],"soccer":["english"],"social":["english","french"],"sock":["english"],"soda":["english"],"soft":["english"],"solar":["english"],"soldier":["english"],"solid":["english"],"solution":["english"],"solve":["english"],"someone":["english"],"song":["english"],"soon":["english"],"sorry":["english"],"sort":["english"],"soul":["english"],"sound":["english"],"soup":["english"],"source":["english","french"],"south":["english"],"space":["english"],"spare":["english"],"spatial":["english","french"],"spawn":["english"],"speak":["english"],"special":["english"],"speed":["english"],"spell":["english"],"spend":["english"],"sphere":["english"],"spice":["english"],"spider":["english"],"spike":["english"],"spin":["english"],"spirit":["english"],"split":["english"],"spoil":["english"],"sponsor":["english","turkish"],"spoon":["english"],"sport":["english"],"spot":["english"],"spray":["english"],"spread":["english"],"spring":["english"],"spy":["english"],"square":["english"],"squeeze":["english"],"squirrel":["english"],"stable":["english","french"],"stadium":["english"],"staff":["english"],"stage":["english"],"stairs":["english"],"stamp":["english"],"stand":["english"],"start":["english"],"state":["english"],"stay":["english"],"steak":["english"],"steel":["english"],"stem":["english"],"step":["english"],"stereo":["english"],"stick":["english"],"still":["english"],"sting":["english"],"stock":["english"],"stomach":["english"],"stone":["english"],"stool":["english"],"story":["english"],"stove":["english"],"strategy":["english"],"street":["english"],"strike":["english"],"strong":["english"],"struggle":["english"],"student":["english"],"stuff":["english"],"stumble":["english"],"style":["english"],"subject":["english"],"submit":["english"],"subway":["english"],"success":["english"],"such":["english"],"sudden":["english"],"suffer":["english"],"sugar":["english"],"suggest":["english"],"suit":["english"],"summer":["english"],"sun":["english"],"sunny":["english"],"sunset":["english"],"super":["english"],"supply":["english"],"supreme":["english"],"sure":["english"],"surface":["english","french"],"surge":["english"],"surprise":["english","french"],"surround":["english"],"survey":["english"],"suspect":["english","french"],"sustain":["english"],"swallow":["english"],"swamp":["english"],"swap":["english"],"swarm":["english"],"swear":["english"],"sweet":["english"],"swift":["english"],"swim":["english"],"swing":["english"],"switch":["english"],"sword":["english"],"symbol":["english"],"symptom":["english"],"syrup":["english"],"system":["english"],"table":["english"],"tackle":["english"],"tag":["english"],"tail":["english"],"talent":["english","french"],"talk":["english"],"tank":["english"],"tape":["english"],"target":["english"],"task":["english"],"taste":["english"],"tattoo":["english"],"taxi":["english"],"teach":["english"],"team":["english"],"tell":["english"],"ten":["english"],"tenant":["english"],"tennis":["english"],"tent":["english"],"term":["english"],"test":["english"],"text":["english"],"thank":["english"],"that":["english"],"theme":["english"],"then":["english"],"theory":["english"],"there":["english"],"they":["english"],"thing":["english"],"this":["english"],"thought":["english"],"three":["english"],"thrive":["english"],"throw":["english"],"thumb":["english"],"thunder":["english"],"ticket":["english"],"tide":["english"],"tiger":["english"],"tilt":["english"],"timber":["english"],"time":["english"],"tiny":["english"],"tip":["english"],"tired":["english"],"tissue":["english"],"title":["english"],"toast":["english"],"tobacco":["english"],"today":["english"],"toddler":["english"],"toe":["english"],"together":["english"],"toilet":["english"],"token":["english"],"tomato":["english"],"tomorrow":["english"],"tone":["english"],"tongue":["english"],"tonight":["english"],"tool":["english"],"tooth":["english"],"top":["english"],"topic":["english"],"topple":["english"],"torch":["english"],"tornado":["english"],"tortoise":["english"],"toss":["english"],"total":["english"],"tourist":["english"],"toward":["english"],"tower":["english"],"town":["english"],"toy":["english"],"track":["english"],"trade":["english"],"traffic":["english"],"tragic":["english"],"train":["english","french"],"transfer":["english","turkish"],"trap":["english"],"trash":["english"],"travel":["english"],"tray":["english"],"treat":["english"],"tree":["english"],"trend":["english"],"trial":["english"],"tribe":["english"],"trick":["english"],"trigger":["english"],"trim":["english"],"trip":["english"],"trophy":["english"],"trouble":["english"],"truck":["english"],"true":["english"],"truly":["english"],"trumpet":["english"],"trust":["english"],"truth":["english"],"try":["english"],"tube":["english"],"tuition":["english"],"tumble":["english"],"tuna":["english"],"tunnel":["english","french"],"turkey":["english"],"turn":["english"],"turtle":["english"],"twelve":["english"],"twenty":["english"],"twice":["english"],"twin":["english"],"twist":["english"],"two":["english"],"type":["english"],"typical":["english"],"ugly":["english"],"umbrella":["english"],"unable":["english"],"unaware":["english"],"uncle":["english"],"uncover":["english"],"under":["english"],"undo":["english"],"unfair":["english"],"unfold":["english"],"unhappy":["english"],"uniform":["english"],"unique":["english","french"],"unit":["english"],"universe":["english"],"unknown":["english"],"unlock":["english"],"until":["english"],"unusual":["english"],"unveil":["english"],"update":["english"],"upgrade":["english"],"uphold":["english"],"upon":["english"],"upper":["english"],"upset":["english"],"urban":["english"],"urge":["english"],"usage":["english","french"],"use":["english"],"used":["english"],"useful":["english"],"useless":["english"],"usual":["english"],"utility":["english"],"vacant":["english"],"vacuum":["english"],"vague":["english","french"],"valid":["english"],"valley":["english"],"valve":["english","french"],"van":["english"],"vanish":["english"],"vapor":["english"],"various":["english"],"vast":["english"],"vault":["english"],"vehicle":["english"],"velvet":["english"],"vendor":["english"],"venture":["english"],"venue":["english"],"verb":["english"],"verify":["english"],"version":["english"],"very":["english"],"vessel":["english"],"veteran":["english"],"viable":["english"],"vibrant":["english"],"vicious":["english"],"victory":["english"],"video":["english"],"view":["english"],"village":["english","french"],"vintage":["english"],"violin":["english"],"virtual":["english"],"virus":["english","french"],"visa":["english"],"visit":["english"],"visual":["english"],"vital":["english","french"],"vivid":["english"],"vocal":["english"],"voice":["english"],"void":["english"],"volcano":["english"],"volume":["english","french"],"vote":["english"],"voyage":["english","french"],"wage":["english"],"wagon":["english","french"],"wait":["english"],"walk":["english"],"wall":["english"],"walnut":["english"],"want":["english"],"warfare":["english"],"warm":["english"],"warrior":["english"],"wash":["english"],"wasp":["english"],"waste":["english"],"water":["english"],"wave":["english"],"way":["english"],"wealth":["english"],"weapon":["english"],"wear":["english"],"weasel":["english"],"weather":["english"],"web":["english"],"wedding":["english"],"weekend":["english"],"weird":["english"],"welcome":["english"],"west":["english"],"wet":["english"],"whale":["english"],"what":["english"],"wheat":["english"],"wheel":["english"],"when":["english"],"where":["english"],"whip":["english"],"whisper":["english"],"wide":["english"],"width":["english"],"wife":["english"],"wild":["english"],"will":["english"],"win":["english"],"window":["english"],"wine":["english"],"wing":["english"],"wink":["english"],"winner":["english"],"winter":["english"],"wire":["english"],"wisdom":["english"],"wise":["english"],"wish":["english"],"witness":["english"],"wolf":["english"],"woman":["english"],"wonder":["english"],"wood":["english"],"wool":["english"],"word":["english"],"work":["english"],"world":["english"],"worry":["english"],"worth":["english"],"wrap":["english"],"wreck":["english"],"wrestle":["english"],"wrist":["english"],"write":["english"],"wrong":["english"],"yard":["english"],"year":["english"],"yellow":["english"],"you":["english"],"young":["english"],"youth":["english"],"zebra":["english"],"zero":["english"],"zone":["english"],"zoo":["english"],"abaisser":["french"],"abdiquer":["french"],"abeille":["french"],"abolir":["french"],"aborder":["french"],"aboutir":["french"],"aboyer":["french"],"abrasif":["french"],"abreuver":["french"],"abriter":["french"],"abroger":["french"],"abrupt":["french"],"absence":["french"],"absolu":["french"],"absurde":["french"],"abusif":["french"],"abyssal":["french"],"académie":["french"],"acajou":["french"],"acarien":["french"],"accabler":["french"],"accepter":["french"],"acclamer":["french"],"accolade":["french"],"accroche":["french"],"accuser":["french"],"acerbe":["french"],"achat":["french"],"acheter":["french"],"aciduler":["french"],"acier":["french"],"acompte":["french"],"acquérir":["french"],"acronyme":["french"],"acteur":["french"],"actif":["french"],"actuel":["french"],"adepte":["french"],"adéquat":["french"],"adhésif":["french"],"adjectif":["french"],"adjuger":["french"],"admettre":["french"],"admirer":["french"],"adopter":["french"],"adorer":["french"],"adoucir":["french"],"adresse":["french"],"adroit":["french"],"adulte":["french"],"adverbe":["french"],"aérer":["french"],"aéronef":["french"],"affaire":["french"],"affecter":["french"],"affiche":["french"],"affreux":["french"],"affubler":["french"],"agacer":["french"],"agencer":["french"],"agile":["french"],"agiter":["french"],"agrafer":["french"],"agréable":["french"],"agrume":["french"],"aider":["french"],"aiguille":["french"],"ailier":["french"],"aimable":["french"],"aisance":["french"],"ajouter":["french"],"ajuster":["french"],"alarmer":["french"],"alchimie":["french"],"alerte":["french"],"algèbre":["french"],"algue":["french"],"aliéner":["french"],"aliment":["french"],"alléger":["french"],"alliage":["french"],"allouer":["french"],"allumer":["french"],"alourdir":["french"],"alpaga":["french"],"altesse":["french"],"alvéole":["french"],"ambigu":["french"],"ambre":["french"],"aménager":["french"],"amertume":["french"],"amidon":["french"],"amiral":["french"],"amorcer":["french"],"amour":["french"],"amovible":["french"],"amphibie":["french"],"ampleur":["french"],"amusant":["french"],"analyse":["french"],"anaphore":["french"],"anarchie":["french"],"anatomie":["french"],"ancien":["french"],"anéantir":["french"],"angoisse":["french"],"anguleux":["french"],"annexer":["french"],"annonce":["french"],"annuel":["french"],"anodin":["french"],"anomalie":["french"],"anonyme":["french"],"anormal":["french"],"antenne":["french"],"antidote":["french"],"anxieux":["french"],"apaiser":["french"],"apéritif":["french"],"aplanir":["french"],"apologie":["french"],"appareil":["french"],"appeler":["french"],"apporter":["french"],"appuyer":["french"],"aquarium":["french"],"aqueduc":["french"],"arbitre":["french"],"arbuste":["french"],"ardeur":["french"],"ardoise":["french"],"argent":["french"],"arlequin":["french"],"armature":["french"],"armement":["french"],"armoire":["french"],"armure":["french"],"arpenter":["french"],"arracher":["french"],"arriver":["french"],"arroser":["french"],"arsenic":["french"],"artériel":["french"],"article":["french"],"asphalte":["french"],"aspirer":["french"],"assaut":["french"],"asservir":["french"],"assiette":["french"],"associer":["french"],"assurer":["french"],"asticot":["french"],"astre":["french"],"astuce":["french"],"atelier":["french"],"atome":["french"],"atrium":["french"],"atroce":["french"],"attaque":["french"],"attentif":["french"],"attirer":["french"],"attraper":["french"],"aubaine":["french"],"auberge":["french"],"audace":["french"],"audible":["french"],"augurer":["french"],"aurore":["french"],"automne":["french"],"autruche":["french"],"avaler":["french"],"avancer":["french"],"avarice":["french"],"avenir":["french"],"averse":["french"],"aveugle":["french"],"aviateur":["french"],"avide":["french"],"avion":["french"],"aviser":["french"],"avoine":["french"],"avouer":["french"],"avril":["french"],"axial":["french"],"axiome":["french"],"bafouer":["french"],"bagage":["french"],"baguette":["french"],"baignade":["french"],"balancer":["french"],"balcon":["french"],"baleine":["french"],"balisage":["french"],"bambin":["french"],"bancaire":["french"],"bandage":["french"],"banlieue":["french"],"bannière":["french"],"banquier":["french"],"barbier":["french"],"baril":["french"],"baron":["french"],"barque":["french"],"barrage":["french"],"bassin":["french"],"bastion":["french"],"bataille":["french"],"bateau":["french"],"batterie":["french"],"baudrier":["french"],"bavarder":["french"],"belette":["french"],"bélier":["french"],"belote":["french"],"bénéfice":["french"],"berceau":["french"],"berger":["french"],"berline":["french"],"bermuda":["french","turkish"],"besace":["french"],"besogne":["french"],"bétail":["french"],"beurre":["french"],"biberon":["french"],"bidule":["french"],"bijou":["french"],"bilan":["french"],"bilingue":["french"],"billard":["french"],"binaire":["french"],"biologie":["french"],"biopsie":["french"],"biotype":["french"],"biscuit":["french"],"bison":["french"],"bistouri":["french"],"bitume":["french"],"bizarre":["french"],"blafard":["french"],"blague":["french"],"blanchir":["french"],"blessant":["french"],"blinder":["french"],"blond":["french"],"bloquer":["french"],"blouson":["french"],"bobard":["french"],"bobine":["french"],"boire":["french"],"boiser":["french"],"bolide":["french"],"bonbon":["french"],"bondir":["french"],"bonheur":["french"],"bonifier":["french"],"bordure":["french"],"borne":["french"],"botte":["french"],"boucle":["french"],"boueux":["french"],"bougie":["french"],"boulon":["french"],"bouquin":["french"],"bourse":["french"],"boussole":["french"],"boutique":["french"],"boxeur":["french"],"branche":["french"],"brasier":["french"],"brebis":["french"],"brèche":["french"],"breuvage":["french"],"bricoler":["french"],"brigade":["french"],"brillant":["french"],"brioche":["french"],"brique":["french"],"brochure":["french"],"broder":["french"],"bronzer":["french"],"brousse":["french"],"broyeur":["french"],"brume":["french"],"brusque":["french"],"brutal":["french"],"bruyant":["french"],"buffle":["french"],"buisson":["french"],"bulletin":["french"],"bureau":["french"],"burin":["french"],"bustier":["french"],"butiner":["french"],"butoir":["french"],"buvable":["french"],"buvette":["french"],"cabanon":["french"],"cabine":["french"],"cachette":["french"],"cadeau":["french"],"cadre":["french"],"caféine":["french"],"caillou":["french"],"caisson":["french"],"calculer":["french"],"calepin":["french"],"calibre":["french"],"calmer":["french"],"calomnie":["french"],"calvaire":["french"],"camarade":["french"],"caméra":["french"],"camion":["french"],"campagne":["french"],"caneton":["french"],"canon":["french"],"cantine":["french"],"canular":["french"],"caporal":["french"],"caprice":["french"],"capsule":["french"],"capter":["french"],"capuche":["french"],"carabine":["french"],"carbone":["french"],"caresser":["french"],"caribou":["french"],"carnage":["french"],"carotte":["french"],"carreau":["french"],"carton":["french"],"cascade":["french"],"casier":["french"],"casque":["french"],"cassure":["french"],"causer":["french"],"cavalier":["french"],"caverne":["french"],"caviar":["french"],"cédille":["french"],"ceinture":["french"],"céleste":["french"],"cellule":["french"],"cendrier":["french"],"censurer":["french"],"central":["french"],"cercle":["french"],"cérébral":["french"],"cerise":["french"],"cerner":["french"],"cerveau":["french"],"cesser":["french"],"chagrin":["french"],"chaise":["french"],"chaleur":["french"],"chambre":["french"],"chance":["french"],"chapitre":["french"],"charbon":["french"],"chasseur":["french"],"chaton":["french"],"chausson":["french"],"chavirer":["french"],"chemise":["french"],"chenille":["french"],"chéquier":["french"],"chercher":["french"],"cheval":["french"],"chien":["french"],"chiffre":["french"],"chignon":["french"],"chimère":["french"],"chiot":["french"],"chlorure":["french"],"chocolat":["french"],"choisir":["french"],"chose":["french"],"chouette":["french"],"chrome":["french"],"chute":["french"],"cigare":["french"],"cigogne":["french"],"cimenter":["french"],"cinéma":["french"],"cintrer":["french"],"circuler":["french"],"cirer":["french"],"cirque":["french"],"citerne":["french"],"citoyen":["french"],"citron":["french"],"clairon":["french"],"clameur":["french"],"claquer":["french"],"classe":["french"],"clavier":["french"],"cligner":["french"],"climat":["french"],"clivage":["french"],"cloche":["french"],"clonage":["french"],"cloporte":["french"],"cobalt":["french"],"cobra":["french"],"cocasse":["french"],"cocotier":["french"],"coder":["french"],"codifier":["french"],"coffre":["french"],"cogner":["french"],"cohésion":["french"],"coiffer":["french"],"coincer":["french"],"colère":["french"],"colibri":["french"],"colline":["french"],"colmater":["french"],"colonel":["french"],"combat":["french"],"comédie":["french"],"commande":["french"],"compact":["french"],"conduire":["french"],"confier":["french"],"congeler":["french"],"connoter":["french"],"consonne":["french"],"contact":["french"],"convexe":["french"],"copain":["french"],"copie":["french"],"corail":["french"],"corbeau":["french"],"cordage":["french"],"corniche":["french"],"corpus":["french"],"cortège":["french"],"cosmique":["french"],"costume":["french"],"coton":["french"],"coude":["french"],"coupure":["french"],"courage":["french"],"couteau":["french"],"couvrir":["french"],"crabe":["french"],"crainte":["french"],"cravate":["french"],"crayon":["french"],"créature":["french"],"créditer":["french"],"crémeux":["french"],"creuser":["french"],"crevette":["french"],"cribler":["french"],"crier":["french"],"cristal":["french"],"critère":["french"],"croire":["french"],"croquer":["french"],"crotale":["french"],"crypter":["french"],"cubique":["french"],"cueillir":["french"],"cuillère":["french"],"cuisine":["french"],"cuivre":["french"],"culminer":["french"],"cultiver":["french"],"cumuler":["french"],"cupide":["french"],"curatif":["french"],"curseur":["french"],"cyanure":["french"],"cylindre":["french"],"cynique":["french"],"daigner":["french"],"damier":["french"],"danseur":["french"],"dauphin":["french"],"débattre":["french"],"débiter":["french"],"déborder":["french"],"débrider":["french"],"débutant":["french"],"décaler":["french"],"décembre":["french"],"déchirer":["french"],"décider":["french"],"déclarer":["french"],"décorer":["french"],"décrire":["french"],"décupler":["french"],"dédale":["french"],"déductif":["french"],"déesse":["french"],"défensif":["french"],"défiler":["french"],"défrayer":["french"],"dégager":["french"],"dégivrer":["french"],"déglutir":["french"],"dégrafer":["french"],"déjeuner":["french"],"délice":["french"],"déloger":["french"],"demander":["french"],"demeurer":["french"],"démolir":["french"],"dénicher":["french"],"dénouer":["french"],"dentelle":["french"],"dénuder":["french"],"départ":["french"],"dépenser":["french"],"déphaser":["french"],"déplacer":["french"],"déposer":["french"],"déranger":["french"],"dérober":["french"],"désastre":["french"],"descente":["french"],"désert":["french"],"désigner":["french"],"désobéir":["french"],"dessiner":["french"],"destrier":["french"],"détacher":["french"],"détester":["french"],"détourer":["french"],"détresse":["french"],"devancer":["french"],"devenir":["french"],"deviner":["french"],"devoir":["french"],"diable":["french"],"dialogue":["french"],"diamant":["french"],"dicter":["french"],"différer":["french"],"digérer":["french"],"digne":["french"],"diluer":["french"],"dimanche":["french"],"diminuer":["french"],"dioxyde":["french"],"directif":["french"],"diriger":["french"],"discuter":["french"],"disposer":["french"],"dissiper":["french"],"divertir":["french"],"diviser":["french"],"docile":["french"],"docteur":["french"],"dogme":["french"],"doigt":["french"],"domaine":["french"],"domicile":["french"],"dompter":["french"],"donateur":["french"],"donjon":["french"],"donner":["french"],"dopamine":["french"],"dortoir":["french"],"dorure":["french"],"dosage":["french"],"doseur":["french"],"dossier":["french"],"dotation":["french"],"douanier":["french"],"douceur":["french"],"douter":["french"],"doyen":["french"],"draper":["french"],"dresser":["french"],"dribbler":["french"],"droiture":["french"],"duperie":["french"],"duplexe":["french"],"durable":["french"],"durcir":["french"],"dynastie":["french"],"éblouir":["french"],"écarter":["french"],"écharpe":["french"],"échelle":["french"],"éclairer":["french"],"éclipse":["french"],"éclore":["french"],"écluse":["french"],"école":["french"],"économie":["french"],"écorce":["french"],"écouter":["french"],"écraser":["french"],"écrémer":["french"],"écrivain":["french"],"écrou":["french"],"écume":["french"],"écureuil":["french"],"édifier":["french"],"éduquer":["french"],"effacer":["french"],"effectif":["french"],"effigie":["french"],"effrayer":["french"],"effusion":["french"],"égaliser":["french"],"égarer":["french"],"éjecter":["french"],"élaborer":["french"],"élargir":["french"],"électron":["french"],"élégant":["french"],"éléphant":["french"],"élève":["french"],"éligible":["french"],"élitisme":["french"],"éloge":["french"],"élucider":["french"],"éluder":["french"],"emballer":["french"],"embellir":["french"],"embryon":["french"],"émeraude":["french"],"émission":["french"],"emmener":["french"],"émotion":["french"],"émouvoir":["french"],"empereur":["french"],"employer":["french"],"emporter":["french"],"emprise":["french"],"émulsion":["french"],"encadrer":["french"],"enchère":["french"],"enclave":["french"],"encoche":["french"],"endiguer":["french"],"endosser":["french"],"endroit":["french"],"enduire":["french"],"énergie":["french"],"enfance":["french"],"enfermer":["french"],"enfouir":["french"],"engager":["french"],"engin":["french","turkish"],"englober":["french"],"énigme":["french"],"enjamber":["french"],"enjeu":["french"],"enlever":["french"],"ennemi":["french"],"ennuyeux":["french"],"enrichir":["french"],"enrobage":["french"],"enseigne":["french"],"entasser":["french"],"entendre":["french"],"entier":["french"],"entourer":["french"],"entraver":["french"],"énumérer":["french"],"envahir":["french"],"enviable":["french"],"envoyer":["french"],"enzyme":["french"],"éolien":["french"],"épaissir":["french"],"épargne":["french"],"épatant":["french"],"épaule":["french"],"épicerie":["french"],"épidémie":["french"],"épier":["french"],"épilogue":["french"],"épine":["french"],"épisode":["french"],"épitaphe":["french"],"époque":["french"],"épreuve":["french"],"éprouver":["french"],"épuisant":["french"],"équerre":["french"],"équipe":["french"],"ériger":["french"],"érosion":["french"],"erreur":["french"],"éruption":["french"],"escalier":["french"],"espadon":["french"],"espèce":["french"],"espiègle":["french"],"espoir":["french"],"esprit":["french"],"esquiver":["french"],"essayer":["french"],"essieu":["french"],"essorer":["french"],"estime":["french"],"estomac":["french"],"estrade":["french"],"étagère":["french"],"étaler":["french"],"étanche":["french"],"étatique":["french"],"éteindre":["french"],"étendoir":["french"],"éternel":["french"],"éthanol":["french"],"éthique":["french"],"ethnie":["french"],"étirer":["french"],"étoffer":["french"],"étoile":["french"],"étonnant":["french"],"étourdir":["french"],"étrange":["french"],"étroit":["french"],"étude":["french"],"euphorie":["french"],"évaluer":["french"],"évasion":["french"],"éventail":["french"],"évidence":["french"],"éviter":["french"],"évolutif":["french"],"évoquer":["french"],"exagérer":["french"],"exaucer":["french"],"exceller":["french"],"excitant":["french"],"exclusif":["french"],"exécuter":["french"],"exemple":["french"],"exercer":["french"],"exhaler":["french"],"exhorter":["french"],"exigence":["french"],"exiler":["french"],"exister":["french"],"exotique":["french"],"expédier":["french"],"explorer":["french"],"exposer":["french"],"exprimer":["french"],"exquis":["french"],"extensif":["french"],"extraire":["french"],"exulter":["french"],"fable":["french"],"fabuleux":["french"],"facette":["french"],"facile":["french"],"facture":["french"],"faiblir":["french"],"falaise":["french"],"fameux":["french"],"famille":["french"],"farceur":["french"],"farfelu":["french"],"farine":["french"],"farouche":["french"],"fasciner":["french"],"faucon":["french"],"fautif":["french"],"faveur":["french"],"favori":["french","turkish"],"fébrile":["french"],"féconder":["french"],"fédérer":["french"],"félin":["french"],"femme":["french"],"fémur":["french"],"fendoir":["french"],"féodal":["french"],"fermer":["french"],"féroce":["french"],"ferveur":["french"],"feuille":["french"],"feutre":["french"],"février":["french"],"fiasco":["french"],"ficeler":["french"],"fictif":["french"],"fidèle":["french"],"filature":["french"],"filetage":["french"],"filière":["french"],"filleul":["french"],"filmer":["french"],"filou":["french"],"filtrer":["french"],"financer":["french"],"finir":["french"],"fiole":["french"],"firme":["french"],"fissure":["french"],"fixer":["french"],"flairer":["french"],"flamme":["french"],"flasque":["french"],"flatteur":["french"],"fléau":["french"],"flèche":["french"],"fleur":["french"],"flexion":["french"],"flocon":["french"],"flore":["french"],"fluctuer":["french"],"fluide":["french"],"fluvial":["french"],"folie":["french"],"fonderie":["french"],"fongible":["french"],"fontaine":["french"],"forcer":["french"],"forgeron":["french"],"formuler":["french"],"fossile":["french"],"foudre":["french"],"fougère":["french"],"fouiller":["french"],"foulure":["french"],"fourmi":["french"],"fraise":["french"],"franchir":["french"],"frapper":["french"],"frayeur":["french"],"frégate":["french"],"freiner":["french"],"frelon":["french"],"frémir":["french"],"frénésie":["french"],"frère":["french"],"friable":["french"],"friction":["french"],"frisson":["french"],"frivole":["french"],"froid":["french"],"fromage":["french"],"frontal":["french"],"frotter":["french"],"fugitif":["french"],"fuite":["french"],"fureur":["french"],"furieux":["french"],"furtif":["french"],"fusion":["french"],"futur":["french"],"gagner":["french"],"galaxie":["french"],"galerie":["french"],"gambader":["french"],"garantir":["french"],"gardien":["french"],"garnir":["french"],"garrigue":["french"],"gazelle":["french"],"gazon":["french"],"géant":["french"],"gélatine":["french"],"gélule":["french"],"gendarme":["french"],"général":["french"],"génie":["french"],"genou":["french"],"gentil":["french"],"géologie":["french"],"géomètre":["french"],"géranium":["french"],"germe":["french"],"gestuel":["french"],"geyser":["french"],"gibier":["french"],"gicler":["french"],"girafe":["french"],"givre":["french"],"glace":["french"],"glaive":["french"],"glisser":["french"],"gloire":["french"],"glorieux":["french"],"golfeur":["french"],"gomme":["french"],"gonfler":["french"],"gorge":["french"],"gorille":["french"],"goudron":["french"],"gouffre":["french"],"goulot":["french"],"goupille":["french"],"gourmand":["french"],"goutte":["french"],"graduel":["french"],"graffiti":["french"],"graine":["french"],"grand":["french"],"grappin":["french"],"gratuit":["french"],"gravir":["french"],"grenat":["french"],"griffure":["french"],"griller":["french"],"grimper":["french"],"grogner":["french"],"gronder":["french"],"grotte":["french"],"groupe":["french"],"gruger":["french"],"grutier":["french"],"gruyère":["french"],"guépard":["french"],"guerrier":["french"],"guimauve":["french"],"guitare":["french"],"gustatif":["french"],"gymnaste":["french"],"gyrostat":["french"],"habitude":["french"],"hachoir":["french"],"halte":["french"],"hameau":["french"],"hangar":["french","turkish"],"hanneton":["french"],"haricot":["french"],"harmonie":["french"],"harpon":["french"],"hasard":["french"],"hélium":["french"],"hématome":["french"],"herbe":["french"],"hérisson":["french"],"hermine":["french"],"héron":["french"],"hésiter":["french"],"heureux":["french"],"hiberner":["french"],"hibou":["french"],"hilarant":["french"],"histoire":["french"],"hiver":["french"],"homard":["french"],"hommage":["french"],"homogène":["french"],"honneur":["french"],"honorer":["french"],"honteux":["french"],"horde":["french"],"horizon":["french"],"horloge":["french"],"hormone":["french"],"horrible":["french"],"houleux":["french"],"housse":["french"],"hublot":["french"],"huileux":["french"],"humain":["french"],"humide":["french"],"humour":["french"],"hurler":["french"],"hydromel":["french"],"hygiène":["french"],"hymne":["french"],"hypnose":["french"],"idylle":["french"],"ignorer":["french"],"iguane":["french"],"illicite":["french"],"illusion":["french"],"imbiber":["french"],"imiter":["french"],"immobile":["french"],"immuable":["french"],"impérial":["french"],"implorer":["french"],"imposer":["french"],"imprimer":["french"],"imputer":["french"],"incarner":["french"],"incendie":["french"],"incident":["french"],"incliner":["french"],"incolore":["french"],"indexer":["french"],"indice":["french"],"inductif":["french"],"inédit":["french"],"ineptie":["french"],"inexact":["french"],"infini":["french"],"infliger":["french"],"informer":["french"],"infusion":["french"],"ingérer":["french"],"inhaler":["french"],"inhiber":["french"],"injecter":["french"],"injure":["french"],"inoculer":["french"],"inonder":["french"],"inscrire":["french"],"insecte":["french"],"insigne":["french"],"insolite":["french"],"inspirer":["french"],"instinct":["french"],"insulter":["french"],"intense":["french"],"intime":["french"],"intrigue":["french"],"intuitif":["french"],"inutile":["french"],"invasion":["french"],"inventer":["french"],"inviter":["french"],"invoquer":["french"],"ironique":["french"],"irradier":["french"],"irréel":["french"],"irriter":["french"],"isoler":["french"],"ivoire":["french"],"ivresse":["french"],"jaillir":["french"],"jambe":["french"],"janvier":["french"],"jardin":["french"],"jauger":["french"],"jaune":["french"],"javelot":["french"],"jetable":["french"],"jeton":["french"],"jeudi":["french"],"jeunesse":["french"],"joindre":["french"],"joncher":["french"],"jongler":["french"],"joueur":["french"],"jouissif":["french"],"journal":["french"],"jovial":["french"],"joyau":["french"],"joyeux":["french"],"jubiler":["french"],"jugement":["french"],"jupon":["french"],"juriste":["french"],"justice":["french"],"juteux":["french"],"juvénile":["french"],"kayak":["french"],"kimono":["french"],"kiosque":["french"],"labial":["french"],"labourer":["french"],"lacérer":["french"],"lactose":["french"],"lagune":["french"],"laine":["french"],"laisser":["french"],"laitier":["french"],"lambeau":["french"],"lamelle":["french"],"lampe":["french"],"lanceur":["french"],"langage":["french"],"lanterne":["french"],"lapin":["french"],"largeur":["french"],"larme":["french"],"laurier":["french"],"lavabo":["french"],"lavoir":["french"],"légal":["french"],"léger":["french"],"légume":["french"],"lessive":["french"],"lettre":["french"],"levier":["french"],"lexique":["french"],"lézard":["french"],"liasse":["french"],"libérer":["french"],"libre":["french"],"licence":["french"],"licorne":["french"],"liège":["french"],"lièvre":["french"],"ligature":["french"],"ligoter":["french"],"ligue":["french"],"limer":["french"],"limite":["french"],"limonade":["french"],"limpide":["french"],"linéaire":["french"],"lingot":["french"],"lionceau":["french"],"liquide":["french"],"lisière":["french"],"lister":["french"],"lithium":["french"],"litige":["french"],"littoral":["french"],"livreur":["french"],"logique":["french"],"lointain":["french"],"loisir":["french"],"lombric":["french"],"loterie":["french"],"louer":["french"],"lourd":["french"],"loutre":["french"],"louve":["french"],"lubie":["french"],"lucide":["french"],"lucratif":["french"],"lueur":["french"],"lugubre":["french"],"luisant":["french"],"lumière":["french"],"lunaire":["french"],"lundi":["french"],"luron":["french"],"lutter":["french"],"luxueux":["french"],"magasin":["french"],"magenta":["french"],"magique":["french"],"maigre":["french"],"maillon":["french"],"maintien":["french"],"mairie":["french"],"maison":["french"],"majorer":["french"],"malaxer":["french"],"maléfice":["french"],"malheur":["french"],"malice":["french"],"mallette":["french"],"mammouth":["french"],"mandater":["french"],"maniable":["french"],"manquant":["french"],"manteau":["french"],"manuel":["french"],"marathon":["french"],"marbre":["french"],"marchand":["french"],"mardi":["french"],"maritime":["french"],"marqueur":["french"],"marron":["french"],"marteler":["french"],"mascotte":["french"],"massif":["french"],"matériel":["french"],"matière":["french"],"matraque":["french"],"maudire":["french"],"maussade":["french"],"mauve":["french"],"maximal":["french"],"méchant":["french"],"méconnu":["french"],"médaille":["french"],"médecin":["french"],"méditer":["french"],"méduse":["french"],"meilleur":["french"],"mélange":["french"],"mélodie":["french"],"membre":["french"],"mémoire":["french"],"menacer":["french"],"mener":["french"],"menhir":["french"],"mensonge":["french"],"mentor":["french"],"mercredi":["french"],"mérite":["french"],"merle":["french"],"messager":["french"],"mesure":["french"],"métal":["french"],"météore":["french"],"méthode":["french"],"métier":["french"],"meuble":["french"],"miauler":["french"],"microbe":["french"],"miette":["french"],"mignon":["french"],"migrer":["french"],"milieu":["french"],"mimique":["french"],"mince":["french"],"minéral":["french"],"minimal":["french"],"minorer":["french"],"miroiter":["french"],"missile":["french"],"mixte":["french"],"moderne":["french"],"moelleux":["french"],"mondial":["french"],"moniteur":["french"],"monnaie":["french"],"monotone":["french"],"monstre":["french"],"montagne":["french"],"monument":["french"],"moqueur":["french"],"morceau":["french"],"morsure":["french"],"mortier":["french"],"moteur":["french"],"motif":["french"],"mouche":["french"],"moufle":["french"],"moulin":["french"],"mousson":["french"],"mouton":["french"],"mouvant":["french"],"multiple":["french"],"munition":["french"],"muraille":["french"],"murène":["french"],"murmure":["french"],"muséum":["french"],"musicien":["french"],"mutation":["french"],"muter":["french"],"mutuel":["french"],"myriade":["french"],"myrtille":["french"],"mystère":["french"],"mythique":["french"],"nageur":["french"],"nappe":["french"],"narquois":["french"],"narrer":["french"],"natation":["french"],"naufrage":["french"],"nautique":["french"],"navire":["french"],"nébuleux":["french"],"nectar":["french"],"néfaste":["french"],"négation":["french"],"négliger":["french"],"négocier":["french"],"neige":["french"],"nerveux":["french"],"nettoyer":["french"],"neurone":["french"],"neutron":["french"],"neveu":["french"],"niche":["french"],"nickel":["french"],"nitrate":["french"],"niveau":["french"],"nocif":["french"],"nocturne":["french"],"noirceur":["french"],"noisette":["french"],"nomade":["french"],"nombreux":["french"],"nommer":["french"],"normatif":["french"],"notifier":["french"],"notoire":["french"],"nourrir":["french"],"nouveau":["french"],"novateur":["french"],"novembre":["french"],"novice":["french"],"nuage":["french"],"nuancer":["french"],"nuire":["french"],"nuisible":["french"],"numéro":["french"],"nuptial":["french"],"nuque":["french"],"nutritif":["french"],"obéir":["french"],"objectif":["french"],"obliger":["french"],"obscur":["french"],"observer":["french"],"obstacle":["french"],"obtenir":["french"],"obturer":["french"],"occasion":["french"],"occuper":["french"],"océan":["french"],"octobre":["french"],"octroyer":["french"],"octupler":["french"],"oculaire":["french"],"odeur":["french"],"odorant":["french"],"offenser":["french"],"officier":["french"],"offrir":["french"],"ogive":["french"],"oiseau":["french"],"oisillon":["french"],"olfactif":["french"],"olivier":["french"],"ombrage":["french"],"omettre":["french"],"onctueux":["french"],"onduler":["french"],"onéreux":["french"],"onirique":["french"],"opale":["french"],"opaque":["french"],"opérer":["french"],"opportun":["french"],"opprimer":["french"],"opter":["french"],"optique":["french"],"orageux":["french"],"orbite":["french"],"ordonner":["french"],"oreille":["french"],"organe":["french"],"orgueil":["french"],"orifice":["french"],"ornement":["french"],"orque":["french"],"ortie":["french"],"osciller":["french"],"osmose":["french"],"ossature":["french"],"otarie":["french"],"ouragan":["french"],"ourson":["french"],"outil":["french"],"outrager":["french"],"ouvrage":["french"],"ovation":["french"],"oxyde":["french"],"oxygène":["french"],"paisible":["french"],"palmarès":["french"],"palourde":["french"],"palper":["french"],"panache":["french"],"pangolin":["french"],"paniquer":["french"],"panneau":["french"],"panorama":["french"],"pantalon":["french"],"papaye":["french"],"papier":["french"],"papoter":["french"],"papyrus":["french"],"paradoxe":["french"],"parcelle":["french"],"paresse":["french"],"parfumer":["french"],"parler":["french"],"parole":["french"],"parrain":["french"],"parsemer":["french"],"partager":["french"],"parure":["french"],"parvenir":["french"],"passion":["french"],"pastèque":["french"],"paternel":["french"],"patience":["french"],"patron":["french","turkish"],"pavillon":["french"],"pavoiser":["french"],"payer":["french"],"paysage":["french"],"peigne":["french"],"peintre":["french"],"pelage":["french"],"pélican":["french"],"pelle":["french"],"pelouse":["french"],"peluche":["french"],"pendule":["french"],"pénétrer":["french"],"pénible":["french"],"pensif":["french"],"pénurie":["french"],"pépite":["french"],"péplum":["french"],"perdrix":["french"],"perforer":["french"],"période":["french"],"permuter":["french"],"perplexe":["french"],"persil":["french"],"perte":["french"],"peser":["french"],"pétale":["french"],"petit":["french"],"pétrir":["french"],"peuple":["french"],"pharaon":["french"],"phobie":["french"],"phoque":["french"],"photon":["french"],"physique":["french"],"pictural":["french"],"pièce":["french"],"pierre":["french"],"pieuvre":["french"],"pilote":["french"],"pinceau":["french"],"pipette":["french"],"piquer":["french"],"pirogue":["french"],"piscine":["french"],"piston":["french"],"pivoter":["french"],"pixel":["french"],"placard":["french"],"plafond":["french"],"plaisir":["french"],"planer":["french"],"plaque":["french"],"plastron":["french"],"plateau":["french"],"pleurer":["french"],"plexus":["french"],"pliage":["french"],"plomb":["french"],"plonger":["french"],"pluie":["french"],"plumage":["french"],"pochette":["french"],"poésie":["french"],"poète":["french"],"pointe":["french"],"poirier":["french"],"poisson":["french"],"poivre":["french"],"polaire":["french"],"policier":["french"],"pollen":["french"],"polygone":["french"],"pommade":["french"],"pompier":["french"],"ponctuel":["french"],"pondérer":["french"],"poney":["french"],"portique":["french"],"posséder":["french"],"posture":["french"],"potager":["french"],"poteau":["french"],"potion":["french"],"pouce":["french"],"poulain":["french"],"poumon":["french"],"pourpre":["french"],"poussin":["french"],"pouvoir":["french"],"prairie":["french"],"pratique":["french"],"précieux":["french"],"prédire":["french"],"préfixe":["french"],"prélude":["french"],"prénom":["french"],"présence":["french"],"prétexte":["french"],"prévoir":["french"],"primitif":["french"],"prince":["french"],"priver":["french"],"problème":["french"],"procéder":["french"],"prodige":["french"],"profond":["french"],"progrès":["french"],"proie":["french"],"projeter":["french"],"prologue":["french"],"promener":["french"],"propre":["french"],"prospère":["french"],"protéger":["french"],"prouesse":["french"],"proverbe":["french"],"prudence":["french"],"pruneau":["french"],"psychose":["french"],"puceron":["french"],"puiser":["french"],"pulpe":["french"],"pulsar":["french"],"punaise":["french"],"punitif":["french"],"pupitre":["french"],"purifier":["french"],"pyramide":["french"],"quasar":["french"],"querelle":["french"],"quiétude":["french"],"quitter":["french"],"quotient":["french"],"racine":["french"],"raconter":["french"],"radieux":["french"],"ragondin":["french"],"raideur":["french"],"raisin":["french"],"ralentir":["french"],"rallonge":["french"],"ramasser":["french"],"rapide":["french"],"rasage":["french"],"ratisser":["french"],"ravager":["french"],"ravin":["french"],"rayonner":["french"],"réactif":["french"],"réagir":["french"],"réaliser":["french"],"réanimer":["french"],"recevoir":["french"],"réciter":["french"],"réclamer":["french"],"récolter":["french"],"recruter":["french"],"reculer":["french"],"recycler":["french"],"rédiger":["french"],"redouter":["french"],"refaire":["french"],"réflexe":["french"],"réformer":["french"],"refrain":["french"],"refuge":["french"],"régalien":["french"],"région":["french"],"réglage":["french"],"régulier":["french"],"réitérer":["french"],"rejeter":["french"],"rejouer":["french"],"relatif":["french"],"relever":["french"],"remarque":["french"],"remède":["french"],"remise":["french"],"remonter":["french"],"remplir":["french"],"remuer":["french"],"renard":["french"],"renfort":["french"],"renifler":["french"],"renoncer":["french"],"rentrer":["french"],"renvoi":["french"],"replier":["french"],"reporter":["french"],"reprise":["french"],"reptile":["french"],"requin":["french"],"réserve":["french"],"résineux":["french"],"résoudre":["french"],"respect":["french"],"rester":["french"],"résultat":["french"],"rétablir":["french"],"retenir":["french"],"réticule":["french"],"retomber":["french"],"retracer":["french"],"réunion":["french"],"réussir":["french"],"revanche":["french"],"revivre":["french"],"révolte":["french"],"révulsif":["french"],"richesse":["french"],"rideau":["french"],"rieur":["french"],"rigide":["french"],"rigoler":["french"],"rincer":["french"],"riposter":["french"],"risible":["french"],"risque":["french"],"rituel":["french"],"rivière":["french"],"rocheux":["french"],"rompre":["french"],"ronce":["french"],"rondin":["french"],"roseau":["french"],"rosier":["french"],"rotatif":["french"],"rotor":["french"],"rotule":["french"],"rouge":["french"],"rouille":["french"],"rouleau":["french"],"routine":["french"],"royaume":["french"],"ruban":["french"],"rubis":["french"],"ruche":["french"],"ruelle":["french"],"rugueux":["french"],"ruiner":["french"],"ruisseau":["french"],"ruser":["french"],"rustique":["french"],"rythme":["french"],"sabler":["french"],"saboter":["french"],"sabre":["french"],"sacoche":["french"],"safari":["french"],"sagesse":["french"],"saisir":["french"],"salade":["french"],"salive":["french"],"saluer":["french"],"samedi":["french"],"sanction":["french"],"sanglier":["french"],"sarcasme":["french"],"sardine":["french"],"saturer":["french"],"saugrenu":["french"],"saumon":["french"],"sauter":["french"],"sauvage":["french"],"savant":["french"],"savonner":["french"],"scalpel":["french"],"scandale":["french"],"scélérat":["french"],"scénario":["french"],"sceptre":["french"],"schéma":["french"],"scinder":["french"],"score":["french"],"scrutin":["french"],"sculpter":["french"],"séance":["french"],"sécable":["french"],"sécher":["french"],"secouer":["french"],"sécréter":["french"],"sédatif":["french"],"séduire":["french"],"seigneur":["french"],"séjour":["french"],"sélectif":["french"],"semaine":["french"],"sembler":["french"],"semence":["french"],"séminal":["french"],"sénateur":["french"],"sensible":["french"],"séparer":["french"],"séquence":["french"],"serein":["french"],"sergent":["french"],"sérieux":["french"],"serrure":["french"],"sérum":["french"],"sésame":["french"],"sévir":["french"],"sevrage":["french"],"sextuple":["french"],"sidéral":["french"],"siècle":["french"],"siéger":["french"],"siffler":["french"],"sigle":["french"],"signal":["french"],"silence":["french"],"silicium":["french"],"sincère":["french"],"sinistre":["french"],"siphon":["french"],"sirop":["french"],"sismique":["french"],"situer":["french"],"skier":["french"],"socle":["french"],"sodium":["french"],"soigneux":["french"],"soldat":["french"],"soleil":["french"],"solitude":["french"],"soluble":["french"],"sombre":["french"],"sommeil":["french"],"somnoler":["french"],"sonde":["french"],"songeur":["french"],"sonnette":["french"],"sonore":["french"],"sorcier":["french"],"sortir":["french"],"sosie":["french"],"sottise":["french"],"soucieux":["french"],"soudure":["french"],"souffle":["french"],"soulever":["french"],"soupape":["french"],"soutirer":["french"],"souvenir":["french"],"spacieux":["french"],"spécial":["french"],"sphère":["french"],"spiral":["french","turkish"],"station":["french"],"sternum":["french"],"stimulus":["french"],"stipuler":["french"],"strict":["french"],"studieux":["french"],"stupeur":["french"],"styliste":["french"],"sublime":["french"],"substrat":["french"],"subtil":["french"],"subvenir":["french"],"succès":["french"],"sucre":["french"],"suffixe":["french"],"suggérer":["french"],"suiveur":["french"],"sulfate":["french"],"superbe":["french"],"supplier":["french"],"suricate":["french"],"surmener":["french"],"sursaut":["french"],"survie":["french"],"syllabe":["french"],"symbole":["french"],"symétrie":["french"],"synapse":["french"],"syntaxe":["french"],"système":["french"],"tabac":["french"],"tablier":["french"],"tactile":["french"],"tailler":["french"],"talisman":["french"],"talonner":["french"],"tambour":["french"],"tamiser":["french"],"tangible":["french"],"tapis":["french"],"taquiner":["french"],"tarder":["french"],"tarif":["french"],"tartine":["french"],"tasse":["french"],"tatami":["french"],"tatouage":["french"],"taupe":["french"],"taureau":["french"],"taxer":["french"],"témoin":["french"],"temporel":["french"],"tenaille":["french"],"tendre":["french"],"teneur":["french"],"tenir":["french"],"tension":["french"],"terminer":["french"],"terne":["french"],"terrible":["french"],"tétine":["french"],"texte":["french"],"thème":["french"],"théorie":["french"],"thérapie":["french"],"thorax":["french"],"tibia":["french"],"tiède":["french"],"timide":["french"],"tirelire":["french"],"tiroir":["french"],"tissu":["french"],"titane":["french"],"titre":["french"],"tituber":["french"],"toboggan":["french"],"tolérant":["french"],"tomate":["french"],"tonique":["french"],"tonneau":["french"],"toponyme":["french"],"torche":["french"],"tordre":["french"],"tornade":["french"],"torpille":["french"],"torrent":["french"],"torse":["french"],"tortue":["french"],"totem":["french"],"toucher":["french"],"tournage":["french"],"tousser":["french"],"toxine":["french"],"traction":["french"],"trafic":["french"],"tragique":["french"],"trahir":["french"],"trancher":["french"],"travail":["french"],"trèfle":["french"],"tremper":["french"],"trésor":["french"],"treuil":["french"],"triage":["french"],"tribunal":["french"],"tricoter":["french"],"trilogie":["french"],"triomphe":["french"],"tripler":["french"],"triturer":["french"],"trivial":["french"],"trombone":["french"],"tronc":["french"],"tropical":["french"],"troupeau":["french"],"tuile":["french"],"tulipe":["french"],"tumulte":["french"],"turbine":["french"],"tuteur":["french"],"tutoyer":["french"],"tuyau":["french"],"tympan":["french"],"typhon":["french"],"typique":["french"],"tyran":["french"],"ubuesque":["french"],"ultime":["french"],"ultrason":["french"],"unanime":["french"],"unifier":["french"],"union":["french"],"unitaire":["french"],"univers":["french"],"uranium":["french"],"urbain":["french"],"urticant":["french"],"usine":["french"],"usuel":["french"],"usure":["french"],"utile":["french"],"utopie":["french"],"vacarme":["french"],"vaccin":["french"],"vagabond":["french"],"vaillant":["french"],"vaincre":["french"],"vaisseau":["french"],"valable":["french"],"valise":["french"],"vallon":["french"],"vampire":["french"],"vanille":["french"],"vapeur":["french"],"varier":["french"],"vaseux":["french"],"vassal":["french"],"vaste":["french"],"vecteur":["french"],"vedette":["french"],"végétal":["french"],"véhicule":["french"],"veinard":["french"],"véloce":["french"],"vendredi":["french"],"vénérer":["french"],"venger":["french"],"venimeux":["french"],"ventouse":["french"],"verdure":["french"],"vérin":["french"],"vernir":["french"],"verrou":["french"],"verser":["french"],"vertu":["french"],"veston":["french"],"vétéran":["french"],"vétuste":["french"],"vexant":["french"],"vexer":["french"],"viaduc":["french"],"viande":["french"],"victoire":["french"],"vidange":["french"],"vidéo":["french"],"vignette":["french"],"vigueur":["french"],"vilain":["french"],"vinaigre":["french"],"violon":["french"],"vipère":["french"],"virement":["french"],"virtuose":["french"],"visage":["french"],"viseur":["french"],"vision":["french"],"visqueux":["french"],"visuel":["french"],"vitesse":["french"],"viticole":["french"],"vitrine":["french"],"vivace":["french"],"vivipare":["french"],"vocation":["french"],"voguer":["french"],"voile":["french"],"voisin":["french"],"voiture":["french"],"volaille":["french"],"volcan":["french"],"voltiger":["french"],"vorace":["french"],"vortex":["french"],"voter":["french"],"vouloir":["french"],"voyelle":["french"],"xénon":["french"],"yacht":["french"],"zèbre":["french"],"zénith":["french"],"zeste":["french"],"zoologie":["french"],"abaco":["italian"],"abbaglio":["italian"],"abbinato":["italian"],"abete":["italian"],"abisso":["italian"],"abolire":["italian"],"abrasivo":["italian"],"abrogato":["italian"],"accadere":["italian"],"accenno":["italian"],"accusato":["italian"],"acetone":["italian"],"achille":["italian"],"acido":["italian"],"acqua":["italian"],"acre":["italian"],"acrilico":["italian"],"acrobata":["italian"],"acuto":["italian"],"adagio":["italian"],"addebito":["italian"],"addome":["italian"],"adeguato":["italian"],"aderire":["italian"],"adipe":["italian"],"adottare":["italian"],"adulare":["italian"],"affabile":["italian"],"affetto":["italian"],"affisso":["italian"],"affranto":["italian"],"aforisma":["italian"],"afoso":["italian"],"africano":["italian"],"agave":["italian"],"agente":["italian"],"agevole":["italian"],"aggancio":["italian"],"agire":["italian"],"agitare":["italian"],"agonismo":["italian"],"agricolo":["italian"],"agrumeto":["italian"],"aguzzo":["italian"],"alabarda":["italian"],"alato":["italian"],"albatro":["italian"],"alberato":["italian"],"albo":["italian"],"albume":["italian"],"alce":["italian"],"alcolico":["italian"],"alettone":["italian"],"alfa":["italian"],"algebra":["italian"],"aliante":["italian"],"alibi":["italian"],"alimento":["italian"],"allagato":["italian"],"allegro":["italian"],"allievo":["italian"],"allodola":["italian"],"allusivo":["italian"],"almeno":["italian"],"alogeno":["italian"],"alpaca":["italian"],"alpestre":["italian"],"altalena":["italian"],"alterno":["italian"],"alticcio":["italian"],"altrove":["italian"],"alunno":["italian"],"alveolo":["italian"],"alzare":["italian"],"amalgama":["italian"],"amanita":["italian"],"amarena":["italian"],"ambito":["italian"],"ambrato":["italian"],"ameba":["italian"],"america":["italian"],"ametista":["italian"],"amico":["italian"],"ammasso":["italian"],"ammenda":["italian"],"ammirare":["italian"],"ammonito":["italian"],"amore":["italian"],"ampio":["italian"],"ampliare":["italian"],"amuleto":["italian"],"anacardo":["italian"],"anagrafe":["italian"],"analista":["italian"],"anarchia":["italian"],"anatra":["italian"],"anca":["italian"],"ancella":["italian"],"ancora":["italian"],"andare":["italian"],"andrea":["italian"],"anello":["italian"],"angelo":["italian"],"angolare":["italian"],"angusto":["italian"],"anima":["italian"],"annegare":["italian"],"annidato":["italian"],"anno":["italian"],"annuncio":["italian"],"anonimo":["italian"],"anticipo":["italian"],"anzi":["italian"],"apatico":["italian"],"apertura":["italian"],"apode":["italian"],"apparire":["italian"],"appetito":["italian"],"appoggio":["italian"],"approdo":["italian"],"appunto":["italian"],"aprile":["italian"],"arabica":["italian"],"arachide":["italian"],"aragosta":["italian"],"araldica":["italian"],"arancio":["italian"],"aratura":["italian"],"arazzo":["italian"],"arbitro":["italian"],"archivio":["italian"],"ardito":["italian"],"arenile":["italian"],"argento":["italian"],"argine":["italian"],"arguto":["italian"],"aria":["italian"],"armonia":["italian"],"arnese":["italian"],"arredato":["italian"],"arringa":["italian"],"arrosto":["italian"],"arsenico":["italian"],"arso":["italian"],"artefice":["italian"],"arzillo":["italian"],"asciutto":["italian"],"ascolto":["italian"],"asepsi":["italian"],"asettico":["italian"],"asfalto":["italian"],"asino":["italian"],"asola":["italian"],"aspirato":["italian"],"aspro":["italian"],"assaggio":["italian"],"asse":["italian"],"assoluto":["italian"],"assurdo":["italian"],"asta":["italian"],"astenuto":["italian"],"astice":["italian"],"astratto":["italian"],"atavico":["italian"],"ateismo":["italian"],"atomico":["italian"],"atono":["italian"],"attesa":["italian"],"attivare":["italian"],"attorno":["italian"],"attrito":["italian"],"attuale":["italian"],"ausilio":["italian"],"austria":["italian"],"autista":["italian"],"autonomo":["italian"],"autunno":["italian"],"avanzato":["italian"],"avere":["italian"],"avvenire":["italian"],"avviso":["italian"],"avvolgere":["italian"],"azione":["italian"],"azoto":["italian"],"azzimo":["italian"],"azzurro":["italian"],"babele":["italian"],"baccano":["italian"],"bacino":["italian"],"baco":["italian"],"badessa":["italian"],"badilata":["italian"],"bagnato":["italian"],"baita":["italian"],"balcone":["italian"],"baldo":["italian"],"balena":["italian"],"ballata":["italian"],"balzano":["italian"],"bambino":["italian"],"bandire":["italian"],"baraonda":["italian"],"barbaro":["italian"],"barca":["italian"],"baritono":["italian"],"barlume":["italian"],"barocco":["italian"],"basilico":["italian"],"basso":["italian"],"batosta":["italian"],"battuto":["italian"],"baule":["italian"],"bava":["italian"],"bavosa":["italian"],"becco":["italian"],"beffa":["italian"],"belgio":["italian"],"belva":["italian"],"benda":["italian"],"benevole":["italian"],"benigno":["italian"],"benzina":["italian"],"bere":["italian"],"berlina":["italian"],"beta":["italian"],"bibita":["italian"],"bici":["italian"],"bidone":["italian"],"bifido":["italian"],"biga":["italian"],"bilancia":["italian"],"bimbo":["italian"],"binocolo":["italian"],"biologo":["italian"],"bipede":["italian"],"bipolare":["italian"],"birbante":["italian"],"birra":["italian"],"biscotto":["italian"],"bisesto":["italian"],"bisnonno":["italian"],"bisonte":["italian"],"bisturi":["italian"],"bizzarro":["italian"],"blando":["italian"],"blatta":["italian"],"bollito":["italian"],"bonifico":["italian"],"bordo":["italian"],"bosco":["italian"],"botanico":["italian"],"bottino":["italian"],"bozzolo":["italian"],"braccio":["italian"],"bradipo":["italian"],"brama":["italian"],"branca":["italian"],"bravura":["italian"],"bretella":["italian"],"brevetto":["italian"],"brezza":["italian"],"briglia":["italian"],"brillante":["italian"],"brindare":["italian"],"broccolo":["italian"],"brodo":["italian"],"bronzina":["italian"],"brullo":["italian"],"bruno":["italian"],"bubbone":["italian"],"buca":["italian"],"budino":["italian"],"buffone":["italian"],"buio":["italian"],"bulbo":["italian"],"buono":["italian"],"burlone":["italian"],"burrasca":["italian"],"bussola":["italian"],"busta":["italian"],"cadetto":["italian"],"caduco":["italian"],"calamaro":["italian"],"calcolo":["italian"],"calesse":["italian"],"calibro":["italian"],"calmo":["italian"],"caloria":["italian"],"cambusa":["italian"],"camerata":["italian"],"camicia":["italian"],"cammino":["italian"],"camola":["italian"],"campale":["italian"],"canapa":["italian"],"candela":["italian"],"cane":["italian"],"canino":["italian"],"canotto":["italian"],"cantina":["italian"],"capace":["italian"],"capello":["italian"],"capitolo":["italian"],"capogiro":["italian"],"cappero":["italian"],"capra":["italian"],"capsula":["italian"],"carapace":["italian"],"carcassa":["italian"],"cardo":["italian"],"carisma":["italian"],"carovana":["italian"],"carretto":["italian"],"cartolina":["italian"],"casaccio":["italian"],"cascata":["italian"],"caserma":["italian"],"caso":["italian"],"cassone":["italian"],"castello":["italian"],"casuale":["italian"],"catasta":["italian"],"catena":["italian"],"catrame":["italian"],"cauto":["italian"],"cavillo":["italian"],"cedibile":["italian"],"cedrata":["italian"],"cefalo":["italian"],"celebre":["italian"],"cellulare":["italian"],"cena":["italian"],"cenone":["italian"],"centesimo":["italian"],"ceramica":["italian"],"cercare":["italian"],"certo":["italian"],"cerume":["italian"],"cervello":["italian"],"cesoia":["italian"],"cespo":["italian"],"ceto":["italian"],"chela":["italian"],"chiaro":["italian"],"chicca":["italian"],"chiedere":["italian"],"chimera":["italian"],"china":["italian"],"chirurgo":["italian"],"chitarra":["italian"],"ciao":["italian"],"ciclismo":["italian"],"cifrare":["italian"],"cigno":["italian"],"cilindro":["italian"],"ciottolo":["italian"],"circa":["italian"],"cirrosi":["italian"],"citrico":["italian"],"cittadino":["italian"],"ciuffo":["italian"],"civetta":["italian"],"civile":["italian"],"classico":["italian"],"clinica":["italian"],"cloro":["italian"],"cocco":["italian"],"codardo":["italian"],"codice":["italian"],"coerente":["italian"],"cognome":["italian"],"collare":["italian"],"colmato":["italian"],"colore":["italian"],"colposo":["italian"],"coltivato":["italian"],"colza":["italian"],"coma":["italian"],"cometa":["italian"],"commando":["italian"],"comodo":["italian"],"computer":["italian"],"comune":["italian"],"conciso":["italian"],"condurre":["italian"],"conferma":["italian"],"congelare":["italian"],"coniuge":["italian"],"connesso":["italian"],"conoscere":["italian"],"consumo":["italian"],"continuo":["italian"],"convegno":["italian"],"coperto":["italian"],"copione":["italian"],"coppia":["italian"],"copricapo":["italian"],"corazza":["italian"],"cordata":["italian"],"coricato":["italian"],"cornice":["italian"],"corolla":["italian"],"corpo":["italian"],"corredo":["italian"],"corsia":["italian"],"cortese":["italian"],"cosmico":["italian"],"costante":["italian"],"cottura":["italian"],"covato":["italian"],"cratere":["italian"],"cravatta":["italian"],"creato":["italian"],"credere":["italian"],"cremoso":["italian"],"crescita":["italian"],"creta":["italian"],"criceto":["italian"],"crinale":["italian"],"crisi":["italian"],"critico":["italian"],"croce":["italian"],"cronaca":["italian"],"crostata":["italian"],"cruciale":["italian"],"crusca":["italian"],"cucire":["italian"],"cuculo":["italian"],"cugino":["italian"],"cullato":["italian"],"cupola":["italian"],"curatore":["italian"],"cursore":["italian"],"curvo":["italian"],"cuscino":["italian"],"custode":["italian"],"dado":["italian"],"daino":["italian"],"dalmata":["italian"],"damerino":["italian"],"daniela":["italian"],"dannoso":["italian"],"danzare":["italian"],"datato":["italian"],"davanti":["italian"],"davvero":["italian"],"debutto":["italian"],"decennio":["italian"],"deciso":["italian"],"declino":["italian"],"decollo":["italian"],"decreto":["italian"],"dedicato":["italian"],"definito":["italian"],"deforme":["italian"],"degno":["italian"],"delegare":["italian"],"delfino":["italian"],"delirio":["italian"],"delta":["italian"],"demenza":["italian"],"denotato":["italian"],"dentro":["italian"],"deposito":["italian"],"derapata":["italian"],"derivare":["italian"],"deroga":["italian"],"descritto":["italian"],"deserto":["italian"],"desiderio":["italian"],"desumere":["italian"],"detersivo":["italian"],"devoto":["italian"],"diametro":["italian"],"dicembre":["italian"],"diedro":["italian"],"difeso":["italian"],"diffuso":["italian"],"digerire":["italian"],"digitale":["italian"],"diluvio":["italian"],"dinamico":["italian"],"dinnanzi":["italian"],"dipinto":["italian"],"diploma":["italian"],"dipolo":["italian"],"diradare":["italian"],"dire":["italian"],"dirotto":["italian"],"dirupo":["italian"],"disagio":["italian"],"discreto":["italian"],"disfare":["italian"],"disgelo":["italian"],"disposto":["italian"],"distanza":["italian"],"disumano":["italian"],"dito":["italian"],"divano":["italian"],"divelto":["italian"],"dividere":["italian"],"divorato":["italian"],"doblone":["italian"],"docente":["italian"],"doganale":["italian"],"dogma":["italian"],"dolce":["italian"],"domato":["italian"],"domenica":["italian"],"dominare":["italian"],"dondolo":["italian"],"dono":["italian"],"dormire":["italian"],"dote":["italian"],"dottore":["italian"],"dovuto":["italian"],"dozzina":["italian"],"drago":["italian"],"druido":["italian"],"dubbio":["italian"],"dubitare":["italian"],"ducale":["italian"],"duna":["italian"],"duomo":["italian"],"duplice":["italian"],"duraturo":["italian"],"ebano":["italian"],"eccesso":["italian"],"ecco":["italian"],"eclissi":["italian"],"economia":["italian"],"edera":["italian"],"edicola":["italian"],"edile":["italian"],"editoria":["italian"],"educare":["italian"],"egemonia":["italian"],"egli":["italian"],"egoismo":["italian"],"egregio":["italian"],"elaborato":["italian"],"elargire":["italian"],"elegante":["italian"],"elencato":["italian"],"eletto":["italian"],"elevare":["italian"],"elfico":["italian"],"elica":["italian"],"elmo":["italian"],"elsa":["italian"],"eluso":["italian"],"emanato":["italian"],"emblema":["italian"],"emesso":["italian"],"emiro":["italian"],"emotivo":["italian"],"emozione":["italian"],"empirico":["italian"],"emulo":["italian"],"endemico":["italian"],"enduro":["italian"],"energia":["italian"],"enfasi":["italian"],"enoteca":["italian"],"entrare":["italian"],"enzima":["italian"],"epatite":["italian"],"epilogo":["italian"],"episodio":["italian"],"epocale":["italian"],"eppure":["italian"],"equatore":["italian"],"erario":["italian"],"erba":["italian"],"erboso":["italian"],"erede":["italian"],"eremita":["italian"],"erigere":["italian"],"ermetico":["italian"],"eroe":["italian"],"erosivo":["italian"],"errante":["italian"],"esagono":["italian"],"esame":["italian"],"esanime":["italian"],"esaudire":["italian"],"esca":["italian"],"esempio":["italian"],"esercito":["italian"],"esibito":["italian"],"esigente":["italian"],"esistere":["italian"],"esito":["italian"],"esofago":["italian"],"esortato":["italian"],"esoso":["italian"],"espanso":["italian"],"espresso":["italian"],"essenza":["italian"],"esso":["italian"],"esteso":["italian"],"estimare":["italian"],"estonia":["italian"],"estroso":["italian"],"esultare":["italian"],"etilico":["italian"],"etnico":["italian"],"etrusco":["italian"],"etto":["italian"],"euclideo":["italian"],"europa":["italian"],"evaso":["italian"],"evidenza":["italian"],"evitato":["italian"],"evoluto":["italian"],"evviva":["italian"],"fabbrica":["italian"],"faccenda":["italian"],"fachiro":["italian"],"falco":["italian"],"famiglia":["italian"],"fanale":["italian"],"fanfara":["italian"],"fango":["italian"],"fantasma":["italian"],"fare":["italian"],"farfalla":["italian"],"farinoso":["italian"],"farmaco":["italian"],"fascia":["italian"],"fastoso":["italian"],"fasullo":["italian"],"faticare":["italian"],"fato":["italian"],"favoloso":["italian"],"febbre":["italian"],"fecola":["italian"],"fede":["italian"],"fegato":["italian"],"felpa":["italian"],"feltro":["italian"],"femmina":["italian"],"fendere":["italian"],"fenomeno":["italian"],"fermento":["italian"],"ferro":["italian"],"fertile":["italian"],"fessura":["italian"],"festivo":["italian"],"fetta":["italian"],"feudo":["italian"],"fiaba":["italian"],"fiducia":["italian"],"fifa":["italian"],"figurato":["italian"],"filo":["italian","turkish"],"finanza":["italian"],"finestra":["italian"],"finire":["italian"],"fiore":["italian"],"fiscale":["italian"],"fisico":["italian"],"fiume":["italian"],"flacone":["italian"],"flamenco":["italian"],"flebo":["italian"],"flemma":["italian"],"florido":["italian"],"fluente":["italian"],"fluoro":["italian"],"fobico":["italian"],"focaccia":["italian"],"focoso":["italian"],"foderato":["italian"],"foglio":["italian"],"folata":["italian"],"folclore":["italian"],"folgore":["italian"],"fondente":["italian"],"fonetico":["italian"],"fonia":["italian"],"fontana":["italian"],"forbito":["italian"],"forchetta":["italian"],"foresta":["italian"],"formica":["italian"],"fornaio":["italian"],"foro":["italian"],"fortezza":["italian"],"forzare":["italian"],"fosfato":["italian"],"fosso":["italian"],"fracasso":["italian"],"frana":["italian"],"frassino":["italian"],"fratello":["italian"],"freccetta":["italian"],"frenata":["italian"],"fresco":["italian"],"frigo":["italian"],"frollino":["italian"],"fronde":["italian"],"frugale":["italian"],"frutta":["italian"],"fucilata":["italian"],"fucsia":["italian"],"fuggente":["italian"],"fulmine":["italian"],"fulvo":["italian"],"fumante":["italian"],"fumetto":["italian"],"fumoso":["italian"],"fune":["italian"],"funzione":["italian"],"fuoco":["italian"],"furbo":["italian"],"furgone":["italian"],"furore":["italian"],"fuso":["italian"],"futile":["italian"],"gabbiano":["italian"],"gaffe":["italian"],"galateo":["italian"],"gallina":["italian"],"galoppo":["italian"],"gambero":["italian"],"gamma":["italian"],"garanzia":["italian"],"garbo":["italian"],"garofano":["italian"],"garzone":["italian"],"gasdotto":["italian"],"gasolio":["italian"],"gastrico":["italian"],"gatto":["italian"],"gaudio":["italian"],"gazebo":["italian"],"gazzella":["italian"],"geco":["italian"],"gelatina":["italian"],"gelso":["italian"],"gemello":["italian"],"gemmato":["italian"],"gene":["italian"],"genitore":["italian"],"gennaio":["italian"],"genotipo":["italian"],"gergo":["italian"],"ghepardo":["italian"],"ghiaccio":["italian"],"ghisa":["italian"],"giallo":["italian"],"gilda":["italian"],"ginepro":["italian"],"giocare":["italian"],"gioiello":["italian"],"giorno":["italian"],"giove":["italian"],"girato":["italian"],"girone":["italian"],"gittata":["italian"],"giudizio":["italian"],"giurato":["italian"],"giusto":["italian"],"globulo":["italian"],"glutine":["italian"],"gnomo":["italian"],"gobba":["italian"],"golf":["italian"],"gomito":["italian"],"gommone":["italian"],"gonfio":["italian"],"gonna":["italian"],"governo":["italian"],"gracile":["italian"],"grado":["italian"],"grafico":["italian"],"grammo":["italian"],"grande":["italian"],"grattare":["italian"],"gravoso":["italian"],"grazia":["italian"],"greca":["italian"],"gregge":["italian"],"grifone":["italian"],"grigio":["italian"],"grinza":["italian"],"grotta":["italian"],"gruppo":["italian"],"guadagno":["italian"],"guaio":["italian"],"guanto":["italian"],"guardare":["italian"],"gufo":["italian"],"guidare":["italian"],"ibernato":["italian"],"icona":["italian"],"identico":["italian"],"idillio":["italian"],"idolo":["italian"],"idra":["italian"],"idrico":["italian"],"idrogeno":["italian"],"igiene":["italian"],"ignaro":["italian"],"ignorato":["italian"],"ilare":["italian"],"illeso":["italian"],"illogico":["italian"],"illudere":["italian"],"imballo":["italian"],"imbevuto":["italian"],"imbocco":["italian"],"imbuto":["italian"],"immane":["italian"],"immerso":["italian"],"immolato":["italian"],"impacco":["italian"],"impeto":["italian"],"impiego":["italian"],"importo":["italian"],"impronta":["italian"],"inalare":["italian"],"inarcare":["italian"],"inattivo":["italian"],"incanto":["italian"],"incendio":["italian"],"inchino":["italian"],"incisivo":["italian"],"incluso":["italian"],"incontro":["italian"],"incrocio":["italian"],"incubo":["italian"],"indagine":["italian"],"india":["italian"],"indole":["italian"],"inedito":["italian"],"infatti":["italian"],"infilare":["italian"],"inflitto":["italian"],"ingaggio":["italian"],"ingegno":["italian"],"inglese":["italian"],"ingordo":["italian"],"ingrosso":["italian"],"innesco":["italian"],"inodore":["italian"],"inoltrare":["italian"],"inondato":["italian"],"insano":["italian"],"insetto":["italian"],"insieme":["italian"],"insonnia":["italian"],"insulina":["italian"],"intasato":["italian"],"intero":["italian"],"intonaco":["italian"],"intuito":["italian"],"inumidire":["italian"],"invalido":["italian"],"invece":["italian"],"invito":["italian"],"iperbole":["italian"],"ipnotico":["italian"],"ipotesi":["italian"],"ippica":["italian"],"iride":["italian"],"irlanda":["italian"],"ironico":["italian"],"irrigato":["italian"],"irrorare":["italian"],"isolato":["italian"],"isotopo":["italian"],"isterico":["italian"],"istituto":["italian"],"istrice":["italian"],"italia":["italian"],"iterare":["italian"],"labbro":["italian"],"labirinto":["italian"],"lacca":["italian"],"lacerato":["italian"],"lacrima":["italian"],"lacuna":["italian"],"laddove":["italian"],"lago":["italian"],"lampo":["italian"],"lancetta":["italian"],"lanterna":["italian"],"lardoso":["italian"],"larga":["italian"],"laringe":["italian"],"lastra":["italian"],"latenza":["italian"],"latino":["italian"],"lattuga":["italian"],"lavagna":["italian"],"lavoro":["italian"],"legale":["italian"],"leggero":["italian"],"lembo":["italian"],"lentezza":["italian"],"lenza":["italian"],"leone":["italian"],"lepre":["italian"],"lesivo":["italian"],"lessato":["italian"],"lesto":["italian"],"letterale":["italian"],"leva":["italian"],"levigato":["italian"],"libero":["italian"],"lido":["italian"],"lievito":["italian"],"lilla":["italian"],"limatura":["italian"],"limitare":["italian"],"limpido":["italian"],"lineare":["italian"],"lingua":["italian"],"liquido":["italian"],"lira":["italian"],"lirica":["italian"],"lisca":["italian"],"lite":["italian"],"litigio":["italian"],"livrea":["italian"],"locanda":["italian"],"lode":["italian"],"logica":["italian"],"lombare":["italian"],"londra":["italian"],"longevo":["italian"],"loquace":["italian"],"lorenzo":["italian"],"loto":["italian"],"lotteria":["italian"],"luce":["italian"],"lucidato":["italian"],"lumaca":["italian"],"luminoso":["italian"],"lungo":["italian"],"lupo":["italian"],"luppolo":["italian"],"lusinga":["italian"],"lusso":["italian"],"lutto":["italian"],"macabro":["italian"],"macchina":["italian"],"macero":["italian"],"macinato":["italian"],"madama":["italian"],"magico":["italian"],"maglia":["italian"],"magnete":["italian"],"magro":["italian"],"maiolica":["italian"],"malafede":["italian"],"malgrado":["italian"],"malinteso":["italian"],"malsano":["italian"],"malto":["italian"],"malumore":["italian"],"mana":["italian"],"mancia":["italian"],"mandorla":["italian"],"mangiare":["italian"],"manifesto":["italian"],"mannaro":["italian"],"manovra":["italian"],"mansarda":["italian"],"mantide":["italian"],"manubrio":["italian"],"mappa":["italian"],"maratona":["italian"],"marcire":["italian"],"maretta":["italian"],"marmo":["italian"],"marsupio":["italian"],"maschera":["italian"],"massaia":["italian"],"mastino":["italian"],"materasso":["italian"],"matricola":["italian"],"mattone":["italian"],"maturo":["italian"],"mazurca":["italian"],"meandro":["italian"],"meccanico":["italian"],"mecenate":["italian"],"medesimo":["italian"],"meditare":["italian"],"mega":["italian"],"melassa":["italian"],"melis":["italian"],"melodia":["italian"],"meninge":["italian"],"meno":["italian"],"mensola":["italian"],"mercurio":["italian"],"merenda":["italian"],"merlo":["italian"],"meschino":["italian"],"mese":["italian"],"messere":["italian"],"mestolo":["italian"],"metallo":["italian"],"metodo":["italian"],"mettere":["italian"],"miagolare":["italian"],"mica":["italian"],"micelio":["italian"],"michele":["italian"],"microbo":["italian"],"midollo":["italian"],"miele":["italian"],"migliore":["italian"],"milano":["italian"],"milite":["italian"],"mimosa":["italian"],"minerale":["italian"],"mini":["italian"],"minore":["italian"],"mirino":["italian"],"mirtillo":["italian"],"miscela":["italian"],"missiva":["italian"],"misto":["italian"],"misurare":["italian"],"mitezza":["italian"],"mitigare":["italian"],"mitra":["italian"],"mittente":["italian"],"mnemonico":["italian"],"modello":["italian"],"modifica":["italian"],"modulo":["italian"],"mogano":["italian"],"mogio":["italian"],"mole":["italian"],"molosso":["italian"],"monastero":["italian"],"monco":["italian"],"mondina":["italian"],"monetario":["italian"],"monile":["italian"],"monotono":["italian"],"monsone":["italian"],"montato":["italian"],"monviso":["italian"],"mora":["italian"],"mordere":["italian"],"morsicato":["italian"],"mostro":["italian"],"motivato":["italian"],"motosega":["italian"],"motto":["italian"],"movenza":["italian"],"movimento":["italian"],"mozzo":["italian"],"mucca":["italian"],"mucosa":["italian"],"muffa":["italian"],"mughetto":["italian"],"mugnaio":["italian"],"mulatto":["italian"],"mulinello":["italian"],"multiplo":["italian"],"mummia":["italian"],"munto":["italian"],"muovere":["italian"],"murale":["italian"],"musa":["italian"],"muscolo":["italian"],"musica":["italian"],"mutevole":["italian"],"muto":["italian"],"nababbo":["italian"],"nafta":["italian"],"nanometro":["italian"],"narciso":["italian"],"narice":["italian"],"narrato":["italian"],"nascere":["italian"],"nastrare":["italian"],"naturale":["italian"],"nautica":["italian"],"naviglio":["italian"],"nebulosa":["italian"],"necrosi":["italian"],"negativo":["italian"],"negozio":["italian"],"nemmeno":["italian"],"neofita":["italian"],"neretto":["italian"],"nervo":["italian"],"nessuno":["italian"],"nettuno":["italian"],"neutrale":["italian"],"neve":["italian"],"nevrotico":["italian"],"nicchia":["italian"],"ninfa":["italian"],"nitido":["italian"],"nobile":["italian"],"nocivo":["italian"],"nodo":["italian"],"nome":["italian"],"nomina":["italian"],"nordico":["italian"],"normale":["italian"],"norvegese":["italian"],"nostrano":["italian"],"notare":["italian"],"notizia":["italian"],"notturno":["italian"],"novella":["italian"],"nucleo":["italian"],"nulla":["italian"],"numero":["italian"],"nuovo":["italian"],"nutrire":["italian"],"nuvola":["italian"],"nuziale":["italian"],"oasi":["italian"],"obbedire":["italian"],"obbligo":["italian"],"obelisco":["italian"],"oblio":["italian"],"obolo":["italian"],"obsoleto":["italian"],"occasione":["italian"],"occhio":["italian"],"occidente":["italian"],"occorrere":["italian"],"occultare":["italian"],"ocra":["italian"],"oculato":["italian"],"odierno":["italian"],"odorare":["italian"],"offerta":["italian"],"offrire":["italian"],"offuscato":["italian"],"oggetto":["italian"],"oggi":["italian"],"ognuno":["italian"],"olandese":["italian"],"olfatto":["italian"],"oliato":["italian"],"oliva":["italian"],"ologramma":["italian"],"oltre":["italian"],"omaggio":["italian"],"ombelico":["italian"],"ombra":["italian"],"omega":["italian"],"omissione":["italian"],"ondoso":["italian"],"onere":["italian"],"onice":["italian"],"onnivoro":["italian"],"onorevole":["italian"],"onta":["italian"],"operato":["italian"],"opinione":["italian"],"opposto":["italian"],"oracolo":["italian"],"orafo":["italian"],"ordine":["italian"],"orecchino":["italian"],"orefice":["italian"],"orfano":["italian"],"organico":["italian"],"origine":["italian"],"orizzonte":["italian"],"orma":["italian"],"ormeggio":["italian"],"ornativo":["italian"],"orologio":["italian"],"orrendo":["italian"],"orribile":["italian"],"ortensia":["italian"],"ortica":["italian"],"orzata":["italian"],"orzo":["italian"],"osare":["italian"],"oscurare":["italian"],"osmosi":["italian"],"ospedale":["italian"],"ospite":["italian"],"ossa":["italian"],"ossidare":["italian"],"ostacolo":["italian"],"oste":["italian"],"otite":["italian"],"otre":["italian"],"ottagono":["italian"],"ottimo":["italian"],"ottobre":["italian"],"ovale":["italian"],"ovest":["italian"],"ovino":["italian"],"oviparo":["italian"],"ovocito":["italian"],"ovunque":["italian"],"ovviare":["italian"],"ozio":["italian"],"pacchetto":["italian"],"pace":["italian"],"pacifico":["italian"],"padella":["italian"],"padrone":["italian"],"paese":["italian"],"paga":["italian"],"pagina":["italian"],"palazzina":["italian"],"palesare":["italian"],"pallido":["italian"],"palo":["italian"],"palude":["italian"],"pandoro":["italian"],"pannello":["italian"],"paolo":["italian"],"paonazzo":["italian"],"paprica":["italian"],"parabola":["italian"],"parcella":["italian"],"parere":["italian"],"pargolo":["italian"],"pari":["italian"],"parlato":["italian"],"parola":["italian"],"partire":["italian"],"parvenza":["italian"],"parziale":["italian"],"passivo":["italian"],"pasticca":["italian"],"patacca":["italian"],"patologia":["italian"],"pattume":["italian"],"pavone":["italian"],"peccato":["italian"],"pedalare":["italian"],"pedonale":["italian"],"peggio":["italian"],"peloso":["italian"],"penare":["italian"],"pendice":["italian"],"penisola":["italian"],"pennuto":["italian"],"penombra":["italian"],"pensare":["italian"],"pentola":["italian"],"pepe":["italian"],"pepita":["italian"],"perbene":["italian"],"percorso":["italian"],"perdonato":["italian"],"perforare":["italian"],"pergamena":["italian"],"periodo":["italian"],"permesso":["italian"],"perno":["italian"],"perplesso":["italian"],"persuaso":["italian"],"pertugio":["italian"],"pervaso":["italian"],"pesatore":["italian"],"pesista":["italian"],"peso":["italian"],"pestifero":["italian"],"petalo":["italian"],"pettine":["italian"],"petulante":["italian"],"pezzo":["italian"],"piacere":["italian"],"pianta":["italian"],"piattino":["italian"],"piccino":["italian"],"picozza":["italian"],"piega":["italian"],"pietra":["italian"],"piffero":["italian"],"pigiama":["italian"],"pigolio":["italian"],"pigro":["italian"],"pila":["italian"],"pilifero":["italian"],"pillola":["italian"],"pilota":["italian"],"pimpante":["italian"],"pineta":["italian"],"pinna":["italian"],"pinolo":["italian"],"pioggia":["italian"],"piombo":["italian"],"piramide":["italian"],"piretico":["italian"],"pirite":["italian"],"pirolisi":["italian"],"pitone":["italian"],"pizzico":["italian"],"placebo":["italian"],"planare":["italian"],"plasma":["italian"],"platano":["italian"],"plenario":["italian"],"pochezza":["italian"],"poderoso":["italian"],"podismo":["italian"],"poesia":["italian"],"poggiare":["italian"],"polenta":["italian"],"poligono":["italian"],"pollice":["italian"],"polmonite":["italian"],"polpetta":["italian"],"polso":["italian"],"poltrona":["italian"],"polvere":["italian"],"pomice":["italian"],"pomodoro":["italian"],"ponte":["italian"],"popoloso":["italian"],"porfido":["italian"],"poroso":["italian"],"porpora":["italian"],"porre":["italian"],"portata":["italian"],"posa":["italian","turkish"],"positivo":["italian"],"possesso":["italian"],"postulato":["italian"],"potassio":["italian"],"potere":["italian"],"pranzo":["italian"],"prassi":["italian"],"pratica":["italian"],"precluso":["italian"],"predica":["italian"],"prefisso":["italian"],"pregiato":["italian"],"prelievo":["italian"],"premere":["italian"],"prenotare":["italian"],"preparato":["italian"],"presenza":["italian"],"pretesto":["italian"],"prevalso":["italian"],"prima":["italian"],"principe":["italian"],"privato":["italian"],"problema":["italian"],"procura":["italian"],"produrre":["italian"],"profumo":["italian"],"progetto":["italian"],"prolunga":["italian"],"promessa":["italian"],"pronome":["italian"],"proposta":["italian"],"proroga":["italian"],"proteso":["italian"],"prova":["italian","turkish"],"prudente":["italian"],"prugna":["italian"],"prurito":["italian"],"psiche":["italian"],"pubblico":["italian"],"pudica":["italian"],"pugilato":["italian"],"pugno":["italian"],"pulce":["italian"],"pulito":["italian"],"pulsante":["italian"],"puntare":["italian"],"pupazzo":["italian"],"pupilla":["italian"],"puro":["italian"],"quadro":["italian"],"qualcosa":["italian"],"quasi":["italian"],"querela":["italian"],"quota":["italian"],"raccolto":["italian"],"raddoppio":["italian"],"radicale":["italian"],"radunato":["italian"],"raffica":["italian"],"ragazzo":["italian"],"ragione":["italian"],"ragno":["italian"],"ramarro":["italian"],"ramingo":["italian"],"ramo":["italian"],"randagio":["italian"],"rantolare":["italian"],"rapato":["italian"],"rapina":["italian"],"rappreso":["italian"],"rasatura":["italian"],"raschiato":["italian"],"rasente":["italian"],"rassegna":["italian"],"rastrello":["italian"],"rata":["italian"],"ravveduto":["italian"],"reale":["italian"],"recepire":["italian"],"recinto":["italian"],"recluta":["italian"],"recondito":["italian"],"recupero":["italian"],"reddito":["italian"],"redimere":["italian"],"regalato":["italian"],"registro":["italian"],"regola":["italian"],"regresso":["italian"],"relazione":["italian"],"remare":["italian"],"remoto":["italian"],"renna":["italian"],"replica":["italian"],"reprimere":["italian"],"reputare":["italian"],"resa":["italian"],"residente":["italian"],"responso":["italian"],"restauro":["italian"],"rete":["italian"],"retina":["italian"],"retorica":["italian"],"rettifica":["italian"],"revocato":["italian"],"riassunto":["italian"],"ribadire":["italian"],"ribelle":["italian"],"ribrezzo":["italian"],"ricarica":["italian"],"ricco":["italian"],"ricevere":["italian"],"riciclato":["italian"],"ricordo":["italian"],"ricreduto":["italian"],"ridicolo":["italian"],"ridurre":["italian"],"rifasare":["italian"],"riflesso":["italian"],"riforma":["italian"],"rifugio":["italian"],"rigare":["italian"],"rigettato":["italian"],"righello":["italian"],"rilassato":["italian"],"rilevato":["italian"],"rimanere":["italian"],"rimbalzo":["italian"],"rimedio":["italian"],"rimorchio":["italian"],"rinascita":["italian"],"rincaro":["italian"],"rinforzo":["italian"],"rinnovo":["italian"],"rinomato":["italian"],"rinsavito":["italian"],"rintocco":["italian"],"rinuncia":["italian"],"rinvenire":["italian"],"riparato":["italian"],"ripetuto":["italian"],"ripieno":["italian"],"riportare":["italian"],"ripresa":["italian"],"ripulire":["italian"],"risata":["italian"],"rischio":["italian"],"riserva":["italian"],"risibile":["italian"],"riso":["italian"],"rispetto":["italian"],"ristoro":["italian"],"risultato":["italian"],"risvolto":["italian"],"ritardo":["italian"],"ritegno":["italian"],"ritmico":["italian"],"ritrovo":["italian"],"riunione":["italian"],"riva":["italian"],"riverso":["italian"],"rivincita":["italian"],"rivolto":["italian"],"rizoma":["italian"],"roba":["italian"],"robotico":["italian"],"robusto":["italian"],"roccia":["italian"],"roco":["italian"],"rodaggio":["italian"],"rodere":["italian"],"roditore":["italian"],"rogito":["italian"],"rollio":["italian"],"romantico":["italian"],"rompere":["italian"],"ronzio":["italian"],"rosolare":["italian"],"rospo":["italian"],"rotante":["italian"],"rotondo":["italian"],"rotula":["italian"],"rovescio":["italian"],"rubizzo":["italian"],"rubrica":["italian"],"ruga":["italian"],"rullino":["italian"],"rumine":["italian"],"rumoroso":["italian"],"ruolo":["italian"],"rupe":["italian"],"russare":["italian"],"rustico":["italian"],"sabato":["italian"],"sabbiare":["italian"],"sabotato":["italian"],"sagoma":["italian"],"salasso":["italian"],"saldatura":["italian"],"salgemma":["italian"],"salivare":["italian"],"salmone":["italian"],"salone":["italian"],"saltare":["italian"],"saluto":["italian"],"salvo":["italian"],"sapere":["italian"],"sapido":["italian"],"saporito":["italian"],"saraceno":["italian"],"sarcasmo":["italian"],"sarto":["italian"],"sassoso":["italian"],"satellite":["italian"],"satira":["italian"],"satollo":["italian"],"saturno":["italian"],"savana":["italian"],"savio":["italian"],"saziato":["italian"],"sbadiglio":["italian"],"sbalzo":["italian"],"sbancato":["italian"],"sbarra":["italian"],"sbattere":["italian"],"sbavare":["italian"],"sbendare":["italian"],"sbirciare":["italian"],"sbloccato":["italian"],"sbocciato":["italian"],"sbrinare":["italian"],"sbruffone":["italian"],"sbuffare":["italian"],"scabroso":["italian"],"scadenza":["italian"],"scala":["italian"],"scambiare":["italian"],"scandalo":["italian"],"scapola":["italian"],"scarso":["italian"],"scatenare":["italian"],"scavato":["italian"],"scelto":["italian"],"scenico":["italian"],"scettro":["italian"],"scheda":["italian"],"schiena":["italian"],"sciarpa":["italian"],"scienza":["italian"],"scindere":["italian"],"scippo":["italian"],"sciroppo":["italian"],"scivolo":["italian"],"sclerare":["italian"],"scodella":["italian"],"scolpito":["italian"],"scomparto":["italian"],"sconforto":["italian"],"scoprire":["italian"],"scorta":["italian"],"scossone":["italian"],"scozzese":["italian"],"scriba":["italian"],"scrollare":["italian"],"scrutinio":["italian"],"scuderia":["italian"],"scultore":["italian"],"scuola":["italian"],"scuro":["italian"],"scusare":["italian"],"sdebitare":["italian"],"sdoganare":["italian"],"seccatura":["italian"],"secondo":["italian"],"sedano":["italian"],"seggiola":["italian"],"segnalato":["italian"],"segregato":["italian"],"seguito":["italian"],"selciato":["italian"],"selettivo":["italian"],"sella":["italian"],"selvaggio":["italian"],"semaforo":["italian"],"sembrare":["italian"],"seme":["italian"],"seminato":["italian"],"sempre":["italian"],"senso":["italian"],"sentire":["italian"],"sepolto":["italian"],"sequenza":["italian"],"serata":["italian"],"serbato":["italian"],"sereno":["italian"],"serio":["italian"],"serpente":["italian"],"serraglio":["italian"],"servire":["italian"],"sestina":["italian"],"setola":["italian"],"settimana":["italian"],"sfacelo":["italian"],"sfaldare":["italian"],"sfamato":["italian"],"sfarzoso":["italian"],"sfaticato":["italian"],"sfera":["italian"],"sfida":["italian"],"sfilato":["italian"],"sfinge":["italian"],"sfocato":["italian"],"sfoderare":["italian"],"sfogo":["italian"],"sfoltire":["italian"],"sforzato":["italian"],"sfratto":["italian"],"sfruttato":["italian"],"sfuggito":["italian"],"sfumare":["italian"],"sfuso":["italian"],"sgabello":["italian"],"sgarbato":["italian"],"sgonfiare":["italian"],"sgorbio":["italian"],"sgrassato":["italian"],"sguardo":["italian"],"sibilo":["italian"],"siccome":["italian"],"sierra":["italian"],"sigla":["italian"],"signore":["italian"],"silenzio":["italian"],"sillaba":["italian"],"simbolo":["italian"],"simpatico":["italian"],"simulato":["italian"],"sinfonia":["italian"],"singolo":["italian"],"sinistro":["italian"],"sino":["italian"],"sintesi":["italian"],"sinusoide":["italian"],"sipario":["italian"],"sisma":["italian"],"sistole":["italian"],"situato":["italian"],"slitta":["italian"],"slogatura":["italian"],"sloveno":["italian"],"smarrito":["italian"],"smemorato":["italian"],"smentito":["italian"],"smeraldo":["italian"],"smilzo":["italian"],"smontare":["italian"],"smottato":["italian"],"smussato":["italian"],"snellire":["italian"],"snervato":["italian"],"snodo":["italian"],"sobbalzo":["italian"],"sobrio":["italian"],"soccorso":["italian"],"sociale":["italian"],"sodale":["italian"],"soffitto":["italian"],"sogno":["italian"],"soldato":["italian"],"solenne":["italian"],"solido":["italian"],"sollazzo":["italian"],"solo":["italian"],"solubile":["italian"],"solvente":["italian"],"somatico":["italian"],"somma":["italian"],"sonda":["italian"],"sonetto":["italian"],"sonnifero":["italian"],"sopire":["italian"],"soppeso":["italian"],"sopra":["italian"],"sorgere":["italian"],"sorpasso":["italian"],"sorriso":["italian"],"sorso":["italian"],"sorteggio":["italian"],"sorvolato":["italian"],"sospiro":["italian"],"sosta":["italian"],"sottile":["italian"],"spada":["italian"],"spalla":["italian"],"spargere":["italian"],"spatola":["italian"],"spavento":["italian"],"spazzola":["italian"],"specie":["italian"],"spedire":["italian"],"spegnere":["italian"],"spelatura":["italian"],"speranza":["italian"],"spessore":["italian"],"spettrale":["italian"],"spezzato":["italian"],"spia":["italian"],"spigoloso":["italian"],"spillato":["italian"],"spinoso":["italian"],"spirale":["italian"],"splendido":["italian"],"sportivo":["italian"],"sposo":["italian"],"spranga":["italian"],"sprecare":["italian"],"spronato":["italian"],"spruzzo":["italian"],"spuntino":["italian"],"squillo":["italian"],"sradicare":["italian"],"srotolato":["italian"],"stabile":["italian"],"stacco":["italian"],"staffa":["italian"],"stagnare":["italian"],"stampato":["italian"],"stantio":["italian"],"starnuto":["italian"],"stasera":["italian"],"statuto":["italian"],"stelo":["italian"],"steppa":["italian"],"sterzo":["italian"],"stiletto":["italian"],"stima":["italian"],"stirpe":["italian"],"stivale":["italian"],"stizzoso":["italian"],"stonato":["italian"],"storico":["italian"],"strappo":["italian"],"stregato":["italian"],"stridulo":["italian"],"strozzare":["italian"],"strutto":["italian"],"stuccare":["italian"],"stufo":["italian"],"stupendo":["italian"],"subentro":["italian"],"succoso":["italian"],"sudore":["italian"],"suggerito":["italian"],"sugo":["italian"],"sultano":["italian"],"suonare":["italian"],"superbo":["italian"],"supporto":["italian"],"surgelato":["italian"],"surrogato":["italian"],"sussurro":["italian"],"sutura":["italian"],"svagare":["italian"],"svedese":["italian"],"sveglio":["italian"],"svelare":["italian"],"svenuto":["italian"],"svezia":["italian"],"sviluppo":["italian"],"svista":["italian"],"svizzera":["italian"],"svolta":["italian"],"svuotare":["italian"],"tabacco":["italian"],"tabulato":["italian"],"tacciare":["italian"],"taciturno":["italian"],"tale":["italian"],"talismano":["italian"],"tampone":["italian"],"tannino":["italian"],"tara":["italian"],"tardivo":["italian"],"targato":["italian"],"tariffa":["italian"],"tarpare":["italian"],"tartaruga":["italian"],"tasto":["italian"],"tattico":["italian"],"taverna":["italian"],"tavolata":["italian"],"tazza":["italian"],"teca":["italian"],"tecnico":["italian"],"telefono":["italian"],"temerario":["italian"],"tempo":["italian","turkish"],"temuto":["italian"],"tendone":["italian"],"tenero":["italian"],"tensione":["italian"],"tentacolo":["italian"],"teorema":["italian"],"terme":["italian"],"terrazzo":["italian"],"terzetto":["italian"],"tesi":["italian"],"tesserato":["italian"],"testato":["italian"],"tetro":["italian"],"tettoia":["italian"],"tifare":["italian"],"tigella":["italian"],"timbro":["italian"],"tinto":["italian"],"tipico":["italian"],"tipografo":["italian"],"tiraggio":["italian"],"tiro":["italian"],"titanio":["italian"],"titolo":["italian"],"titubante":["italian"],"tizio":["italian"],"tizzone":["italian"],"toccare":["italian"],"tollerare":["italian"],"tolto":["italian"],"tombola":["italian"],"tomo":["italian"],"tonfo":["italian"],"tonsilla":["italian"],"topazio":["italian"],"topologia":["italian"],"toppa":["italian"],"torba":["italian"],"tornare":["italian"],"torrone":["italian"],"tortora":["italian"],"toscano":["italian"],"tossire":["italian"],"tostatura":["italian"],"totano":["italian"],"trabocco":["italian"],"trachea":["italian"],"trafila":["italian"],"tragedia":["italian"],"tralcio":["italian"],"tramonto":["italian"],"transito":["italian"],"trapano":["italian"],"trarre":["italian"],"trasloco":["italian"],"trattato":["italian"],"trave":["italian"],"treccia":["italian"],"tremolio":["italian"],"trespolo":["italian"],"tributo":["italian"],"tricheco":["italian"],"trifoglio":["italian"],"trillo":["italian"],"trincea":["italian"],"trio":["italian"],"tristezza":["italian"],"triturato":["italian"],"trivella":["italian"],"tromba":["italian"],"trono":["italian"],"troppo":["italian"],"trottola":["italian"],"trovare":["italian"],"truccato":["italian"],"tubatura":["italian"],"tuffato":["italian"],"tulipano":["italian"],"tumulto":["italian"],"tunisia":["italian"],"turbare":["italian"],"turchino":["italian"],"tuta":["italian"],"tutela":["italian"],"ubicato":["italian"],"uccello":["italian"],"uccisore":["italian"],"udire":["italian"],"uditivo":["italian"],"uffa":["italian"],"ufficio":["italian"],"uguale":["italian"],"ulisse":["italian"],"ultimato":["italian"],"umano":["italian"],"umile":["italian"],"umorismo":["italian"],"uncinetto":["italian"],"ungere":["italian"],"ungherese":["italian"],"unicorno":["italian"],"unificato":["italian"],"unisono":["italian"],"unitario":["italian"],"unte":["italian"],"uovo":["italian"],"upupa":["italian"],"uragano":["italian"],"urgenza":["italian"],"urlo":["italian"],"usanza":["italian"],"usato":["italian"],"uscito":["italian"],"usignolo":["italian"],"usuraio":["italian"],"utensile":["italian"],"utilizzo":["italian"],"utopia":["italian"],"vacante":["italian"],"vaccinato":["italian"],"vagabondo":["italian"],"vagliato":["italian"],"valanga":["italian"],"valgo":["italian"],"valico":["italian"],"valletta":["italian"],"valoroso":["italian"],"valutare":["italian"],"valvola":["italian"],"vampata":["italian"],"vangare":["italian"],"vanitoso":["italian"],"vano":["italian"],"vantaggio":["italian"],"vanvera":["italian"],"vapore":["italian"],"varano":["italian"],"varcato":["italian"],"variante":["italian"],"vasca":["italian"],"vedetta":["italian"],"vedova":["italian"],"veduto":["italian"],"vegetale":["italian"],"veicolo":["italian"],"velcro":["italian"],"velina":["italian"],"velluto":["italian"],"veloce":["italian"],"venato":["italian"],"vendemmia":["italian"],"vento":["italian"],"verace":["italian"],"verbale":["italian"],"vergogna":["italian"],"verifica":["italian"],"vero":["italian"],"verruca":["italian"],"verticale":["italian"],"vescica":["italian"],"vessillo":["italian"],"vestale":["italian"],"veterano":["italian"],"vetrina":["italian"],"vetusto":["italian"],"viandante":["italian"],"vibrante":["italian"],"vicenda":["italian"],"vichingo":["italian"],"vicinanza":["italian"],"vidimare":["italian"],"vigilia":["italian"],"vigneto":["italian"],"vigore":["italian"],"vile":["italian"],"villano":["italian"],"vimini":["italian"],"vincitore":["italian"],"viola":["italian"],"vipera":["italian"],"virgola":["italian"],"virologo":["italian"],"virulento":["italian"],"viscoso":["italian"],"visione":["italian"],"vispo":["italian"],"vissuto":["italian"],"visura":["italian"],"vita":["italian"],"vitello":["italian"],"vittima":["italian"],"vivanda":["italian"],"vivido":["italian"],"viziare":["italian"],"voce":["italian"],"voga":["italian"],"volatile":["italian"],"volere":["italian"],"volpe":["italian"],"voragine":["italian"],"vulcano":["italian"],"zampogna":["italian"],"zanna":["italian"],"zappato":["italian"],"zattera":["italian"],"zavorra":["italian"],"zefiro":["italian"],"zelante":["italian"],"zelo":["italian"],"zenzero":["italian"],"zerbino":["italian"],"zibetto":["italian"],"zinco":["italian"],"zircone":["italian"],"zitto":["italian"],"zolla":["italian"],"zotico":["italian"],"zucchero":["italian"],"zufolo":["italian"],"zulu":["italian"],"zuppa":["italian"],"あいこくしん":["japanese"],"あいさつ":["japanese"],"あいだ":["japanese"],"あおぞら":["japanese"],"あかちゃん":["japanese"],"あきる":["japanese"],"あけがた":["japanese"],"あける":["japanese"],"あこがれる":["japanese"],"あさい":["japanese"],"あさひ":["japanese"],"あしあと":["japanese"],"あじわう":["japanese"],"あずかる":["japanese"],"あずき":["japanese"],"あそぶ":["japanese"],"あたえる":["japanese"],"あたためる":["japanese"],"あたりまえ":["japanese"],"あたる":["japanese"],"あつい":["japanese"],"あつかう":["japanese"],"あっしゅく":["japanese"],"あつまり":["japanese"],"あつめる":["japanese"],"あてな":["japanese"],"あてはまる":["japanese"],"あひる":["japanese"],"あぶら":["japanese"],"あぶる":["japanese"],"あふれる":["japanese"],"あまい":["japanese"],"あまど":["japanese"],"あまやかす":["japanese"],"あまり":["japanese"],"あみもの":["japanese"],"あめりか":["japanese"],"あやまる":["japanese"],"あゆむ":["japanese"],"あらいぐま":["japanese"],"あらし":["japanese"],"あらすじ":["japanese"],"あらためる":["japanese"],"あらゆる":["japanese"],"あらわす":["japanese"],"ありがとう":["japanese"],"あわせる":["japanese"],"あわてる":["japanese"],"あんい":["japanese"],"あんがい":["japanese"],"あんこ":["japanese"],"あんぜん":["japanese"],"あんてい":["japanese"],"あんない":["japanese"],"あんまり":["japanese"],"いいだす":["japanese"],"いおん":["japanese"],"いがい":["japanese"],"いがく":["japanese"],"いきおい":["japanese"],"いきなり":["japanese"],"いきもの":["japanese"],"いきる":["japanese"],"いくじ":["japanese"],"いくぶん":["japanese"],"いけばな":["japanese"],"いけん":["japanese"],"いこう":["japanese"],"いこく":["japanese"],"いこつ":["japanese"],"いさましい":["japanese"],"いさん":["japanese"],"いしき":["japanese"],"いじゅう":["japanese"],"いじょう":["japanese"],"いじわる":["japanese"],"いずみ":["japanese"],"いずれ":["japanese"],"いせい":["japanese"],"いせえび":["japanese"],"いせかい":["japanese"],"いせき":["japanese"],"いぜん":["japanese"],"いそうろう":["japanese"],"いそがしい":["japanese"],"いだい":["japanese"],"いだく":["japanese"],"いたずら":["japanese"],"いたみ":["japanese"],"いたりあ":["japanese"],"いちおう":["japanese"],"いちじ":["japanese"],"いちど":["japanese"],"いちば":["japanese"],"いちぶ":["japanese"],"いちりゅう":["japanese"],"いつか":["japanese"],"いっしゅん":["japanese"],"いっせい":["japanese"],"いっそう":["japanese"],"いったん":["japanese"],"いっち":["japanese"],"いってい":["japanese"],"いっぽう":["japanese"],"いてざ":["japanese"],"いてん":["japanese"],"いどう":["japanese"],"いとこ":["japanese"],"いない":["japanese"],"いなか":["japanese"],"いねむり":["japanese"],"いのち":["japanese"],"いのる":["japanese"],"いはつ":["japanese"],"いばる":["japanese"],"いはん":["japanese"],"いびき":["japanese"],"いひん":["japanese"],"いふく":["japanese"],"いへん":["japanese"],"いほう":["japanese"],"いみん":["japanese"],"いもうと":["japanese"],"いもたれ":["japanese"],"いもり":["japanese"],"いやがる":["japanese"],"いやす":["japanese"],"いよかん":["japanese"],"いよく":["japanese"],"いらい":["japanese"],"いらすと":["japanese"],"いりぐち":["japanese"],"いりょう":["japanese"],"いれい":["japanese"],"いれもの":["japanese"],"いれる":["japanese"],"いろえんぴつ":["japanese"],"いわい":["japanese"],"いわう":["japanese"],"いわかん":["japanese"],"いわば":["japanese"],"いわゆる":["japanese"],"いんげんまめ":["japanese"],"いんさつ":["japanese"],"いんしょう":["japanese"],"いんよう":["japanese"],"うえき":["japanese"],"うえる":["japanese"],"うおざ":["japanese"],"うがい":["japanese"],"うかぶ":["japanese"],"うかべる":["japanese"],"うきわ":["japanese"],"うくらいな":["japanese"],"うくれれ":["japanese"],"うけたまわる":["japanese"],"うけつけ":["japanese"],"うけとる":["japanese"],"うけもつ":["japanese"],"うける":["japanese"],"うごかす":["japanese"],"うごく":["japanese"],"うこん":["japanese"],"うさぎ":["japanese"],"うしなう":["japanese"],"うしろがみ":["japanese"],"うすい":["japanese"],"うすぎ":["japanese"],"うすぐらい":["japanese"],"うすめる":["japanese"],"うせつ":["japanese"],"うちあわせ":["japanese"],"うちがわ":["japanese"],"うちき":["japanese"],"うちゅう":["japanese"],"うっかり":["japanese"],"うつくしい":["japanese"],"うったえる":["japanese"],"うつる":["japanese"],"うどん":["japanese"],"うなぎ":["japanese"],"うなじ":["japanese"],"うなずく":["japanese"],"うなる":["japanese"],"うねる":["japanese"],"うのう":["japanese"],"うぶげ":["japanese"],"うぶごえ":["japanese"],"うまれる":["japanese"],"うめる":["japanese"],"うもう":["japanese"],"うやまう":["japanese"],"うよく":["japanese"],"うらがえす":["japanese"],"うらぐち":["japanese"],"うらない":["japanese"],"うりあげ":["japanese"],"うりきれ":["japanese"],"うるさい":["japanese"],"うれしい":["japanese"],"うれゆき":["japanese"],"うれる":["japanese"],"うろこ":["japanese"],"うわき":["japanese"],"うわさ":["japanese"],"うんこう":["japanese"],"うんちん":["japanese"],"うんてん":["japanese"],"うんどう":["japanese"],"えいえん":["japanese"],"えいが":["japanese"],"えいきょう":["japanese"],"えいご":["japanese"],"えいせい":["japanese"],"えいぶん":["japanese"],"えいよう":["japanese"],"えいわ":["japanese"],"えおり":["japanese"],"えがお":["japanese"],"えがく":["japanese"],"えきたい":["japanese"],"えくせる":["japanese"],"えしゃく":["japanese"],"えすて":["japanese"],"えつらん":["japanese"],"えのぐ":["japanese"],"えほうまき":["japanese"],"えほん":["japanese"],"えまき":["japanese"],"えもじ":["japanese"],"えもの":["japanese"],"えらい":["japanese"],"えらぶ":["japanese"],"えりあ":["japanese"],"えんえん":["japanese"],"えんかい":["japanese"],"えんぎ":["japanese"],"えんげき":["japanese"],"えんしゅう":["japanese"],"えんぜつ":["japanese"],"えんそく":["japanese"],"えんちょう":["japanese"],"えんとつ":["japanese"],"おいかける":["japanese"],"おいこす":["japanese"],"おいしい":["japanese"],"おいつく":["japanese"],"おうえん":["japanese"],"おうさま":["japanese"],"おうじ":["japanese"],"おうせつ":["japanese"],"おうたい":["japanese"],"おうふく":["japanese"],"おうべい":["japanese"],"おうよう":["japanese"],"おえる":["japanese"],"おおい":["japanese"],"おおう":["japanese"],"おおどおり":["japanese"],"おおや":["japanese"],"おおよそ":["japanese"],"おかえり":["japanese"],"おかず":["japanese"],"おがむ":["japanese"],"おかわり":["japanese"],"おぎなう":["japanese"],"おきる":["japanese"],"おくさま":["japanese"],"おくじょう":["japanese"],"おくりがな":["japanese"],"おくる":["japanese"],"おくれる":["japanese"],"おこす":["japanese"],"おこなう":["japanese"],"おこる":["japanese"],"おさえる":["japanese"],"おさない":["japanese"],"おさめる":["japanese"],"おしいれ":["japanese"],"おしえる":["japanese"],"おじぎ":["japanese"],"おじさん":["japanese"],"おしゃれ":["japanese"],"おそらく":["japanese"],"おそわる":["japanese"],"おたがい":["japanese"],"おたく":["japanese"],"おだやか":["japanese"],"おちつく":["japanese"],"おっと":["japanese"],"おつり":["japanese"],"おでかけ":["japanese"],"おとしもの":["japanese"],"おとなしい":["japanese"],"おどり":["japanese"],"おどろかす":["japanese"],"おばさん":["japanese"],"おまいり":["japanese"],"おめでとう":["japanese"],"おもいで":["japanese"],"おもう":["japanese"],"おもたい":["japanese"],"おもちゃ":["japanese"],"おやつ":["japanese"],"おやゆび":["japanese"],"およぼす":["japanese"],"おらんだ":["japanese"],"おろす":["japanese"],"おんがく":["japanese"],"おんけい":["japanese"],"おんしゃ":["japanese"],"おんせん":["japanese"],"おんだん":["japanese"],"おんちゅう":["japanese"],"おんどけい":["japanese"],"かあつ":["japanese"],"かいが":["japanese"],"がいき":["japanese"],"がいけん":["japanese"],"がいこう":["japanese"],"かいさつ":["japanese"],"かいしゃ":["japanese"],"かいすいよく":["japanese"],"かいぜん":["japanese"],"かいぞうど":["japanese"],"かいつう":["japanese"],"かいてん":["japanese"],"かいとう":["japanese"],"かいふく":["japanese"],"がいへき":["japanese"],"かいほう":["japanese"],"かいよう":["japanese"],"がいらい":["japanese"],"かいわ":["japanese"],"かえる":["japanese"],"かおり":["japanese"],"かかえる":["japanese"],"かがく":["japanese"],"かがし":["japanese"],"かがみ":["japanese"],"かくご":["japanese"],"かくとく":["japanese"],"かざる":["japanese"],"がぞう":["japanese"],"かたい":["japanese"],"かたち":["japanese"],"がちょう":["japanese"],"がっきゅう":["japanese"],"がっこう":["japanese"],"がっさん":["japanese"],"がっしょう":["japanese"],"かなざわし":["japanese"],"かのう":["japanese"],"がはく":["japanese"],"かぶか":["japanese"],"かほう":["japanese"],"かほご":["japanese"],"かまう":["japanese"],"かまぼこ":["japanese"],"かめれおん":["japanese"],"かゆい":["japanese"],"かようび":["japanese"],"からい":["japanese"],"かるい":["japanese"],"かろう":["japanese"],"かわく":["japanese"],"かわら":["japanese"],"がんか":["japanese"],"かんけい":["japanese"],"かんこう":["japanese"],"かんしゃ":["japanese"],"かんそう":["japanese"],"かんたん":["japanese"],"かんち":["japanese"],"がんばる":["japanese"],"きあい":["japanese"],"きあつ":["japanese"],"きいろ":["japanese"],"ぎいん":["japanese"],"きうい":["japanese"],"きうん":["japanese"],"きえる":["japanese"],"きおう":["japanese"],"きおく":["japanese"],"きおち":["japanese"],"きおん":["japanese"],"きかい":["japanese"],"きかく":["japanese"],"きかんしゃ":["japanese"],"ききて":["japanese"],"きくばり":["japanese"],"きくらげ":["japanese"],"きけんせい":["japanese"],"きこう":["japanese"],"きこえる":["japanese"],"きこく":["japanese"],"きさい":["japanese"],"きさく":["japanese"],"きさま":["japanese"],"きさらぎ":["japanese"],"ぎじかがく":["japanese"],"ぎしき":["japanese"],"ぎじたいけん":["japanese"],"ぎじにってい":["japanese"],"ぎじゅつしゃ":["japanese"],"きすう":["japanese"],"きせい":["japanese"],"きせき":["japanese"],"きせつ":["japanese"],"きそう":["japanese"],"きぞく":["japanese"],"きぞん":["japanese"],"きたえる":["japanese"],"きちょう":["japanese"],"きつえん":["japanese"],"ぎっちり":["japanese"],"きつつき":["japanese"],"きつね":["japanese"],"きてい":["japanese"],"きどう":["japanese"],"きどく":["japanese"],"きない":["japanese"],"きなが":["japanese"],"きなこ":["japanese"],"きぬごし":["japanese"],"きねん":["japanese"],"きのう":["japanese"],"きのした":["japanese"],"きはく":["japanese"],"きびしい":["japanese"],"きひん":["japanese"],"きふく":["japanese"],"きぶん":["japanese"],"きぼう":["japanese"],"きほん":["japanese"],"きまる":["japanese"],"きみつ":["japanese"],"きむずかしい":["japanese"],"きめる":["japanese"],"きもだめし":["japanese"],"きもち":["japanese"],"きもの":["japanese"],"きゃく":["japanese"],"きやく":["japanese"],"ぎゅうにく":["japanese"],"きよう":["japanese"],"きょうりゅう":["japanese"],"きらい":["japanese"],"きらく":["japanese"],"きりん":["japanese"],"きれい":["japanese"],"きれつ":["japanese"],"きろく":["japanese"],"ぎろん":["japanese"],"きわめる":["japanese"],"ぎんいろ":["japanese"],"きんかくじ":["japanese"],"きんじょ":["japanese"],"きんようび":["japanese"],"ぐあい":["japanese"],"くいず":["japanese"],"くうかん":["japanese"],"くうき":["japanese"],"くうぐん":["japanese"],"くうこう":["japanese"],"ぐうせい":["japanese"],"くうそう":["japanese"],"ぐうたら":["japanese"],"くうふく":["japanese"],"くうぼ":["japanese"],"くかん":["japanese"],"くきょう":["japanese"],"くげん":["japanese"],"ぐこう":["japanese"],"くさい":["japanese"],"くさき":["japanese"],"くさばな":["japanese"],"くさる":["japanese"],"くしゃみ":["japanese"],"くしょう":["japanese"],"くすのき":["japanese"],"くすりゆび":["japanese"],"くせげ":["japanese"],"くせん":["japanese"],"ぐたいてき":["japanese"],"くださる":["japanese"],"くたびれる":["japanese"],"くちこみ":["japanese"],"くちさき":["japanese"],"くつした":["japanese"],"ぐっすり":["japanese"],"くつろぐ":["japanese"],"くとうてん":["japanese"],"くどく":["japanese"],"くなん":["japanese"],"くねくね":["japanese"],"くのう":["japanese"],"くふう":["japanese"],"くみあわせ":["japanese"],"くみたてる":["japanese"],"くめる":["japanese"],"くやくしょ":["japanese"],"くらす":["japanese"],"くらべる":["japanese"],"くるま":["japanese"],"くれる":["japanese"],"くろう":["japanese"],"くわしい":["japanese"],"ぐんかん":["japanese"],"ぐんしょく":["japanese"],"ぐんたい":["japanese"],"ぐんて":["japanese"],"けあな":["japanese"],"けいかく":["japanese"],"けいけん":["japanese"],"けいこ":["japanese"],"けいさつ":["japanese"],"げいじゅつ":["japanese"],"けいたい":["japanese"],"げいのうじん":["japanese"],"けいれき":["japanese"],"けいろ":["japanese"],"けおとす":["japanese"],"けおりもの":["japanese"],"げきか":["japanese"],"げきげん":["japanese"],"げきだん":["japanese"],"げきちん":["japanese"],"げきとつ":["japanese"],"げきは":["japanese"],"げきやく":["japanese"],"げこう":["japanese"],"げこくじょう":["japanese"],"げざい":["japanese"],"けさき":["japanese"],"げざん":["japanese"],"けしき":["japanese"],"けしごむ":["japanese"],"けしょう":["japanese"],"げすと":["japanese"],"けたば":["japanese"],"けちゃっぷ":["japanese"],"けちらす":["japanese"],"けつあつ":["japanese"],"けつい":["japanese"],"けつえき":["japanese"],"けっこん":["japanese"],"けつじょ":["japanese"],"けっせき":["japanese"],"けってい":["japanese"],"けつまつ":["japanese"],"げつようび":["japanese"],"げつれい":["japanese"],"けつろん":["japanese"],"げどく":["japanese"],"けとばす":["japanese"],"けとる":["japanese"],"けなげ":["japanese"],"けなす":["japanese"],"けなみ":["japanese"],"けぬき":["japanese"],"げねつ":["japanese"],"けねん":["japanese"],"けはい":["japanese"],"げひん":["japanese"],"けぶかい":["japanese"],"げぼく":["japanese"],"けまり":["japanese"],"けみかる":["japanese"],"けむし":["japanese"],"けむり":["japanese"],"けもの":["japanese"],"けらい":["japanese"],"けろけろ":["japanese"],"けわしい":["japanese"],"けんい":["japanese"],"けんえつ":["japanese"],"けんお":["japanese"],"けんか":["japanese"],"げんき":["japanese"],"けんげん":["japanese"],"けんこう":["japanese"],"けんさく":["japanese"],"けんしゅう":["japanese"],"けんすう":["japanese"],"げんそう":["japanese"],"けんちく":["japanese"],"けんてい":["japanese"],"けんとう":["japanese"],"けんない":["japanese"],"けんにん":["japanese"],"げんぶつ":["japanese"],"けんま":["japanese"],"けんみん":["japanese"],"けんめい":["japanese"],"けんらん":["japanese"],"けんり":["japanese"],"こあくま":["japanese"],"こいぬ":["japanese"],"こいびと":["japanese"],"ごうい":["japanese"],"こうえん":["japanese"],"こうおん":["japanese"],"こうかん":["japanese"],"ごうきゅう":["japanese"],"ごうけい":["japanese"],"こうこう":["japanese"],"こうさい":["japanese"],"こうじ":["japanese"],"こうすい":["japanese"],"ごうせい":["japanese"],"こうそく":["japanese"],"こうたい":["japanese"],"こうちゃ":["japanese"],"こうつう":["japanese"],"こうてい":["japanese"],"こうどう":["japanese"],"こうない":["japanese"],"こうはい":["japanese"],"ごうほう":["japanese"],"ごうまん":["japanese"],"こうもく":["japanese"],"こうりつ":["japanese"],"こえる":["japanese"],"こおり":["japanese"],"ごかい":["japanese"],"ごがつ":["japanese"],"ごかん":["japanese"],"こくご":["japanese"],"こくさい":["japanese"],"こくとう":["japanese"],"こくない":["japanese"],"こくはく":["japanese"],"こぐま":["japanese"],"こけい":["japanese"],"こける":["japanese"],"ここのか":["japanese"],"こころ":["japanese"],"こさめ":["japanese"],"こしつ":["japanese"],"こすう":["japanese"],"こせい":["japanese"],"こせき":["japanese"],"こぜん":["japanese"],"こそだて":["japanese"],"こたい":["japanese"],"こたえる":["japanese"],"こたつ":["japanese"],"こちょう":["japanese"],"こっか":["japanese"],"こつこつ":["japanese"],"こつばん":["japanese"],"こつぶ":["japanese"],"こてい":["japanese"],"こてん":["japanese"],"ことがら":["japanese"],"ことし":["japanese"],"ことば":["japanese"],"ことり":["japanese"],"こなごな":["japanese"],"こねこね":["japanese"],"このまま":["japanese"],"このみ":["japanese"],"このよ":["japanese"],"ごはん":["japanese"],"こひつじ":["japanese"],"こふう":["japanese"],"こふん":["japanese"],"こぼれる":["japanese"],"ごまあぶら":["japanese"],"こまかい":["japanese"],"ごますり":["japanese"],"こまつな":["japanese"],"こまる":["japanese"],"こむぎこ":["japanese"],"こもじ":["japanese"],"こもち":["japanese"],"こもの":["japanese"],"こもん":["japanese"],"こやく":["japanese"],"こやま":["japanese"],"こゆう":["japanese"],"こゆび":["japanese"],"こよい":["japanese"],"こよう":["japanese"],"こりる":["japanese"],"これくしょん":["japanese"],"ころっけ":["japanese"],"こわもて":["japanese"],"こわれる":["japanese"],"こんいん":["japanese"],"こんかい":["japanese"],"こんき":["japanese"],"こんしゅう":["japanese"],"こんすい":["japanese"],"こんだて":["japanese"],"こんとん":["japanese"],"こんなん":["japanese"],"こんびに":["japanese"],"こんぽん":["japanese"],"こんまけ":["japanese"],"こんや":["japanese"],"こんれい":["japanese"],"こんわく":["japanese"],"ざいえき":["japanese"],"さいかい":["japanese"],"さいきん":["japanese"],"ざいげん":["japanese"],"ざいこ":["japanese"],"さいしょ":["japanese"],"さいせい":["japanese"],"ざいたく":["japanese"],"ざいちゅう":["japanese"],"さいてき":["japanese"],"ざいりょう":["japanese"],"さうな":["japanese"],"さかいし":["japanese"],"さがす":["japanese"],"さかな":["japanese"],"さかみち":["japanese"],"さがる":["japanese"],"さぎょう":["japanese"],"さくし":["japanese"],"さくひん":["japanese"],"さくら":["japanese"],"さこく":["japanese"],"さこつ":["japanese"],"さずかる":["japanese"],"ざせき":["japanese"],"さたん":["japanese"],"さつえい":["japanese"],"ざつおん":["japanese"],"ざっか":["japanese"],"ざつがく":["japanese"],"さっきょく":["japanese"],"ざっし":["japanese"],"さつじん":["japanese"],"ざっそう":["japanese"],"さつたば":["japanese"],"さつまいも":["japanese"],"さてい":["japanese"],"さといも":["japanese"],"さとう":["japanese"],"さとおや":["japanese"],"さとし":["japanese"],"さとる":["japanese"],"さのう":["japanese"],"さばく":["japanese"],"さびしい":["japanese"],"さべつ":["japanese"],"さほう":["japanese"],"さほど":["japanese"],"さます":["japanese"],"さみしい":["japanese"],"さみだれ":["japanese"],"さむけ":["japanese"],"さめる":["japanese"],"さやえんどう":["japanese"],"さゆう":["japanese"],"さよう":["japanese"],"さよく":["japanese"],"さらだ":["japanese"],"ざるそば":["japanese"],"さわやか":["japanese"],"さわる":["japanese"],"さんいん":["japanese"],"さんか":["japanese"],"さんきゃく":["japanese"],"さんこう":["japanese"],"さんさい":["japanese"],"ざんしょ":["japanese"],"さんすう":["japanese"],"さんせい":["japanese"],"さんそ":["japanese"],"さんち":["japanese"],"さんま":["japanese"],"さんみ":["japanese"],"さんらん":["japanese"],"しあい":["japanese"],"しあげ":["japanese"],"しあさって":["japanese"],"しあわせ":["japanese"],"しいく":["japanese"],"しいん":["japanese"],"しうち":["japanese"],"しえい":["japanese"],"しおけ":["japanese"],"しかい":["japanese"],"しかく":["japanese"],"じかん":["japanese"],"しごと":["japanese"],"しすう":["japanese"],"じだい":["japanese"],"したうけ":["japanese"],"したぎ":["japanese"],"したて":["japanese"],"したみ":["japanese"],"しちょう":["japanese"],"しちりん":["japanese"],"しっかり":["japanese"],"しつじ":["japanese"],"しつもん":["japanese"],"してい":["japanese"],"してき":["japanese"],"してつ":["japanese"],"じてん":["japanese"],"じどう":["japanese"],"しなぎれ":["japanese"],"しなもの":["japanese"],"しなん":["japanese"],"しねま":["japanese"],"しねん":["japanese"],"しのぐ":["japanese"],"しのぶ":["japanese"],"しはい":["japanese"],"しばかり":["japanese"],"しはつ":["japanese"],"しはらい":["japanese"],"しはん":["japanese"],"しひょう":["japanese"],"しふく":["japanese"],"じぶん":["japanese"],"しへい":["japanese"],"しほう":["japanese"],"しほん":["japanese"],"しまう":["japanese"],"しまる":["japanese"],"しみん":["japanese"],"しむける":["japanese"],"じむしょ":["japanese"],"しめい":["japanese"],"しめる":["japanese"],"しもん":["japanese"],"しゃいん":["japanese"],"しゃうん":["japanese"],"しゃおん":["japanese"],"じゃがいも":["japanese"],"しやくしょ":["japanese"],"しゃくほう":["japanese"],"しゃけん":["japanese"],"しゃこ":["japanese"],"しゃざい":["japanese"],"しゃしん":["japanese"],"しゃせん":["japanese"],"しゃそう":["japanese"],"しゃたい":["japanese"],"しゃちょう":["japanese"],"しゃっきん":["japanese"],"じゃま":["japanese"],"しゃりん":["japanese"],"しゃれい":["japanese"],"じゆう":["japanese"],"じゅうしょ":["japanese"],"しゅくはく":["japanese"],"じゅしん":["japanese"],"しゅっせき":["japanese"],"しゅみ":["japanese"],"しゅらば":["japanese"],"じゅんばん":["japanese"],"しょうかい":["japanese"],"しょくたく":["japanese"],"しょっけん":["japanese"],"しょどう":["japanese"],"しょもつ":["japanese"],"しらせる":["japanese"],"しらべる":["japanese"],"しんか":["japanese"],"しんこう":["japanese"],"じんじゃ":["japanese"],"しんせいじ":["japanese"],"しんちく":["japanese"],"しんりん":["japanese"],"すあげ":["japanese"],"すあし":["japanese"],"すあな":["japanese"],"ずあん":["japanese"],"すいえい":["japanese"],"すいか":["japanese"],"すいとう":["japanese"],"ずいぶん":["japanese"],"すいようび":["japanese"],"すうがく":["japanese"],"すうじつ":["japanese"],"すうせん":["japanese"],"すおどり":["japanese"],"すきま":["japanese"],"すくう":["japanese"],"すくない":["japanese"],"すける":["japanese"],"すごい":["japanese"],"すこし":["japanese"],"ずさん":["japanese"],"すずしい":["japanese"],"すすむ":["japanese"],"すすめる":["japanese"],"すっかり":["japanese"],"ずっしり":["japanese"],"ずっと":["japanese"],"すてき":["japanese"],"すてる":["japanese"],"すねる":["japanese"],"すのこ":["japanese"],"すはだ":["japanese"],"すばらしい":["japanese"],"ずひょう":["japanese"],"ずぶぬれ":["japanese"],"すぶり":["japanese"],"すふれ":["japanese"],"すべて":["japanese"],"すべる":["japanese"],"ずほう":["japanese"],"すぼん":["japanese"],"すまい":["japanese"],"すめし":["japanese"],"すもう":["japanese"],"すやき":["japanese"],"すらすら":["japanese"],"するめ":["japanese"],"すれちがう":["japanese"],"すろっと":["japanese"],"すわる":["japanese"],"すんぜん":["japanese"],"すんぽう":["japanese"],"せあぶら":["japanese"],"せいかつ":["japanese"],"せいげん":["japanese"],"せいじ":["japanese"],"せいよう":["japanese"],"せおう":["japanese"],"せかいかん":["japanese"],"せきにん":["japanese"],"せきむ":["japanese"],"せきゆ":["japanese"],"せきらんうん":["japanese"],"せけん":["japanese"],"せこう":["japanese"],"せすじ":["japanese"],"せたい":["japanese"],"せたけ":["japanese"],"せっかく":["japanese"],"せっきゃく":["japanese"],"ぜっく":["japanese"],"せっけん":["japanese"],"せっこつ":["japanese"],"せっさたくま":["japanese"],"せつぞく":["japanese"],"せつだん":["japanese"],"せつでん":["japanese"],"せっぱん":["japanese"],"せつび":["japanese"],"せつぶん":["japanese"],"せつめい":["japanese"],"せつりつ":["japanese"],"せなか":["japanese"],"せのび":["japanese"],"せはば":["japanese"],"せびろ":["japanese"],"せぼね":["japanese"],"せまい":["japanese"],"せまる":["japanese"],"せめる":["japanese"],"せもたれ":["japanese"],"せりふ":["japanese"],"ぜんあく":["japanese"],"せんい":["japanese"],"せんえい":["japanese"],"せんか":["japanese"],"せんきょ":["japanese"],"せんく":["japanese"],"せんげん":["japanese"],"ぜんご":["japanese"],"せんさい":["japanese"],"せんしゅ":["japanese"],"せんすい":["japanese"],"せんせい":["japanese"],"せんぞ":["japanese"],"せんたく":["japanese"],"せんちょう":["japanese"],"せんてい":["japanese"],"せんとう":["japanese"],"せんぬき":["japanese"],"せんねん":["japanese"],"せんぱい":["japanese"],"ぜんぶ":["japanese"],"ぜんぽう":["japanese"],"せんむ":["japanese"],"せんめんじょ":["japanese"],"せんもん":["japanese"],"せんやく":["japanese"],"せんゆう":["japanese"],"せんよう":["japanese"],"ぜんら":["japanese"],"ぜんりゃく":["japanese"],"せんれい":["japanese"],"せんろ":["japanese"],"そあく":["japanese"],"そいとげる":["japanese"],"そいね":["japanese"],"そうがんきょう":["japanese"],"そうき":["japanese"],"そうご":["japanese"],"そうしん":["japanese"],"そうだん":["japanese"],"そうなん":["japanese"],"そうび":["japanese"],"そうめん":["japanese"],"そうり":["japanese"],"そえもの":["japanese"],"そえん":["japanese"],"そがい":["japanese"],"そげき":["japanese"],"そこう":["japanese"],"そこそこ":["japanese"],"そざい":["japanese"],"そしな":["japanese"],"そせい":["japanese"],"そせん":["japanese"],"そそぐ":["japanese"],"そだてる":["japanese"],"そつう":["japanese"],"そつえん":["japanese"],"そっかん":["japanese"],"そつぎょう":["japanese"],"そっけつ":["japanese"],"そっこう":["japanese"],"そっせん":["japanese"],"そっと":["japanese"],"そとがわ":["japanese"],"そとづら":["japanese"],"そなえる":["japanese"],"そなた":["japanese"],"そふぼ":["japanese"],"そぼく":["japanese"],"そぼろ":["japanese"],"そまつ":["japanese"],"そまる":["japanese"],"そむく":["japanese"],"そむりえ":["japanese"],"そめる":["japanese"],"そもそも":["japanese"],"そよかぜ":["japanese"],"そらまめ":["japanese"],"そろう":["japanese"],"そんかい":["japanese"],"そんけい":["japanese"],"そんざい":["japanese"],"そんしつ":["japanese"],"そんぞく":["japanese"],"そんちょう":["japanese"],"ぞんび":["japanese"],"ぞんぶん":["japanese"],"そんみん":["japanese"],"たあい":["japanese"],"たいいん":["japanese"],"たいうん":["japanese"],"たいえき":["japanese"],"たいおう":["japanese"],"だいがく":["japanese"],"たいき":["japanese"],"たいぐう":["japanese"],"たいけん":["japanese"],"たいこ":["japanese"],"たいざい":["japanese"],"だいじょうぶ":["japanese"],"だいすき":["japanese"],"たいせつ":["japanese"],"たいそう":["japanese"],"だいたい":["japanese"],"たいちょう":["japanese"],"たいてい":["japanese"],"だいどころ":["japanese"],"たいない":["japanese"],"たいねつ":["japanese"],"たいのう":["japanese"],"たいはん":["japanese"],"だいひょう":["japanese"],"たいふう":["japanese"],"たいへん":["japanese"],"たいほ":["japanese"],"たいまつばな":["japanese"],"たいみんぐ":["japanese"],"たいむ":["japanese"],"たいめん":["japanese"],"たいやき":["japanese"],"たいよう":["japanese"],"たいら":["japanese"],"たいりょく":["japanese"],"たいる":["japanese"],"たいわん":["japanese"],"たうえ":["japanese"],"たえる":["japanese"],"たおす":["japanese"],"たおる":["japanese"],"たおれる":["japanese"],"たかい":["japanese"],"たかね":["japanese"],"たきび":["japanese"],"たくさん":["japanese"],"たこく":["japanese"],"たこやき":["japanese"],"たさい":["japanese"],"たしざん":["japanese"],"だじゃれ":["japanese"],"たすける":["japanese"],"たずさわる":["japanese"],"たそがれ":["japanese"],"たたかう":["japanese"],"たたく":["japanese"],"ただしい":["japanese"],"たたみ":["japanese"],"たちばな":["japanese"],"だっかい":["japanese"],"だっきゃく":["japanese"],"だっこ":["japanese"],"だっしゅつ":["japanese"],"だったい":["japanese"],"たてる":["japanese"],"たとえる":["japanese"],"たなばた":["japanese"],"たにん":["japanese"],"たぬき":["japanese"],"たのしみ":["japanese"],"たはつ":["japanese"],"たぶん":["japanese"],"たべる":["japanese"],"たぼう":["japanese"],"たまご":["japanese"],"たまる":["japanese"],"だむる":["japanese"],"ためいき":["japanese"],"ためす":["japanese"],"ためる":["japanese"],"たもつ":["japanese"],"たやすい":["japanese"],"たよる":["japanese"],"たらす":["japanese"],"たりきほんがん":["japanese"],"たりょう":["japanese"],"たりる":["japanese"],"たると":["japanese"],"たれる":["japanese"],"たれんと":["japanese"],"たろっと":["japanese"],"たわむれる":["japanese"],"だんあつ":["japanese"],"たんい":["japanese"],"たんおん":["japanese"],"たんか":["japanese"],"たんき":["japanese"],"たんけん":["japanese"],"たんご":["japanese"],"たんさん":["japanese"],"たんじょうび":["japanese"],"だんせい":["japanese"],"たんそく":["japanese"],"たんたい":["japanese"],"だんち":["japanese"],"たんてい":["japanese"],"たんとう":["japanese"],"だんな":["japanese"],"たんにん":["japanese"],"だんねつ":["japanese"],"たんのう":["japanese"],"たんぴん":["japanese"],"だんぼう":["japanese"],"たんまつ":["japanese"],"たんめい":["japanese"],"だんれつ":["japanese"],"だんろ":["japanese"],"だんわ":["japanese"],"ちあい":["japanese"],"ちあん":["japanese"],"ちいき":["japanese"],"ちいさい":["japanese"],"ちえん":["japanese"],"ちかい":["japanese"],"ちから":["japanese"],"ちきゅう":["japanese"],"ちきん":["japanese"],"ちけいず":["japanese"],"ちけん":["japanese"],"ちこく":["japanese"],"ちさい":["japanese"],"ちしき":["japanese"],"ちしりょう":["japanese"],"ちせい":["japanese"],"ちそう":["japanese"],"ちたい":["japanese"],"ちたん":["japanese"],"ちちおや":["japanese"],"ちつじょ":["japanese"],"ちてき":["japanese"],"ちてん":["japanese"],"ちぬき":["japanese"],"ちぬり":["japanese"],"ちのう":["japanese"],"ちひょう":["japanese"],"ちへいせん":["japanese"],"ちほう":["japanese"],"ちまた":["japanese"],"ちみつ":["japanese"],"ちみどろ":["japanese"],"ちめいど":["japanese"],"ちゃんこなべ":["japanese"],"ちゅうい":["japanese"],"ちゆりょく":["japanese"],"ちょうし":["japanese"],"ちょさくけん":["japanese"],"ちらし":["japanese"],"ちらみ":["japanese"],"ちりがみ":["japanese"],"ちりょう":["japanese"],"ちるど":["japanese"],"ちわわ":["japanese"],"ちんたい":["japanese"],"ちんもく":["japanese"],"ついか":["japanese"],"ついたち":["japanese"],"つうか":["japanese"],"つうじょう":["japanese"],"つうはん":["japanese"],"つうわ":["japanese"],"つかう":["japanese"],"つかれる":["japanese"],"つくね":["japanese"],"つくる":["japanese"],"つけね":["japanese"],"つける":["japanese"],"つごう":["japanese"],"つたえる":["japanese"],"つづく":["japanese"],"つつじ":["japanese"],"つつむ":["japanese"],"つとめる":["japanese"],"つながる":["japanese"],"つなみ":["japanese"],"つねづね":["japanese"],"つのる":["japanese"],"つぶす":["japanese"],"つまらない":["japanese"],"つまる":["japanese"],"つみき":["japanese"],"つめたい":["japanese"],"つもり":["japanese"],"つもる":["japanese"],"つよい":["japanese"],"つるぼ":["japanese"],"つるみく":["japanese"],"つわもの":["japanese"],"つわり":["japanese"],"てあし":["japanese"],"てあて":["japanese"],"てあみ":["japanese"],"ていおん":["japanese"],"ていか":["japanese"],"ていき":["japanese"],"ていけい":["japanese"],"ていこく":["japanese"],"ていさつ":["japanese"],"ていし":["japanese"],"ていせい":["japanese"],"ていたい":["japanese"],"ていど":["japanese"],"ていねい":["japanese"],"ていひょう":["japanese"],"ていへん":["japanese"],"ていぼう":["japanese"],"てうち":["japanese"],"ておくれ":["japanese"],"てきとう":["japanese"],"てくび":["japanese"],"でこぼこ":["japanese"],"てさぎょう":["japanese"],"てさげ":["japanese"],"てすり":["japanese"],"てそう":["japanese"],"てちがい":["japanese"],"てちょう":["japanese"],"てつがく":["japanese"],"てつづき":["japanese"],"でっぱ":["japanese"],"てつぼう":["japanese"],"てつや":["japanese"],"でぬかえ":["japanese"],"てぬき":["japanese"],"てぬぐい":["japanese"],"てのひら":["japanese"],"てはい":["japanese"],"てぶくろ":["japanese"],"てふだ":["japanese"],"てほどき":["japanese"],"てほん":["japanese"],"てまえ":["japanese"],"てまきずし":["japanese"],"てみじか":["japanese"],"てみやげ":["japanese"],"てらす":["japanese"],"てれび":["japanese"],"てわけ":["japanese"],"てわたし":["japanese"],"でんあつ":["japanese"],"てんいん":["japanese"],"てんかい":["japanese"],"てんき":["japanese"],"てんぐ":["japanese"],"てんけん":["japanese"],"てんごく":["japanese"],"てんさい":["japanese"],"てんし":["japanese"],"てんすう":["japanese"],"でんち":["japanese"],"てんてき":["japanese"],"てんとう":["japanese"],"てんない":["japanese"],"てんぷら":["japanese"],"てんぼうだい":["japanese"],"てんめつ":["japanese"],"てんらんかい":["japanese"],"でんりょく":["japanese"],"でんわ":["japanese"],"どあい":["japanese"],"といれ":["japanese"],"どうかん":["japanese"],"とうきゅう":["japanese"],"どうぐ":["japanese"],"とうし":["japanese"],"とうむぎ":["japanese"],"とおい":["japanese"],"とおか":["japanese"],"とおく":["japanese"],"とおす":["japanese"],"とおる":["japanese"],"とかい":["japanese"],"とかす":["japanese"],"ときおり":["japanese"],"ときどき":["japanese"],"とくい":["japanese"],"とくしゅう":["japanese"],"とくてん":["japanese"],"とくに":["japanese"],"とくべつ":["japanese"],"とけい":["japanese"],"とける":["japanese"],"とこや":["japanese"],"とさか":["japanese"],"としょかん":["japanese"],"とそう":["japanese"],"とたん":["japanese"],"とちゅう":["japanese"],"とっきゅう":["japanese"],"とっくん":["japanese"],"とつぜん":["japanese"],"とつにゅう":["japanese"],"とどける":["japanese"],"ととのえる":["japanese"],"とない":["japanese"],"となえる":["japanese"],"となり":["japanese"],"とのさま":["japanese"],"とばす":["japanese"],"どぶがわ":["japanese"],"とほう":["japanese"],"とまる":["japanese"],"とめる":["japanese"],"ともだち":["japanese"],"ともる":["japanese"],"どようび":["japanese"],"とらえる":["japanese"],"とんかつ":["japanese"],"どんぶり":["japanese"],"ないかく":["japanese"],"ないこう":["japanese"],"ないしょ":["japanese"],"ないす":["japanese"],"ないせん":["japanese"],"ないそう":["japanese"],"なおす":["japanese"],"ながい":["japanese"],"なくす":["japanese"],"なげる":["japanese"],"なこうど":["japanese"],"なさけ":["japanese"],"なたでここ":["japanese"],"なっとう":["japanese"],"なつやすみ":["japanese"],"ななおし":["japanese"],"なにごと":["japanese"],"なにもの":["japanese"],"なにわ":["japanese"],"なのか":["japanese"],"なふだ":["japanese"],"なまいき":["japanese"],"なまえ":["japanese"],"なまみ":["japanese"],"なみだ":["japanese"],"なめらか":["japanese"],"なめる":["japanese"],"なやむ":["japanese"],"ならう":["japanese"],"ならび":["japanese"],"ならぶ":["japanese"],"なれる":["japanese"],"なわとび":["japanese"],"なわばり":["japanese"],"にあう":["japanese"],"にいがた":["japanese"],"にうけ":["japanese"],"におい":["japanese"],"にかい":["japanese"],"にがて":["japanese"],"にきび":["japanese"],"にくしみ":["japanese"],"にくまん":["japanese"],"にげる":["japanese"],"にさんかたんそ":["japanese"],"にしき":["japanese"],"にせもの":["japanese"],"にちじょう":["japanese"],"にちようび":["japanese"],"にっか":["japanese"],"にっき":["japanese"],"にっけい":["japanese"],"にっこう":["japanese"],"にっさん":["japanese"],"にっしょく":["japanese"],"にっすう":["japanese"],"にっせき":["japanese"],"にってい":["japanese"],"になう":["japanese"],"にほん":["japanese"],"にまめ":["japanese"],"にもつ":["japanese"],"にやり":["japanese"],"にゅういん":["japanese"],"にりんしゃ":["japanese"],"にわとり":["japanese"],"にんい":["japanese"],"にんか":["japanese"],"にんき":["japanese"],"にんげん":["japanese"],"にんしき":["japanese"],"にんずう":["japanese"],"にんそう":["japanese"],"にんたい":["japanese"],"にんち":["japanese"],"にんてい":["japanese"],"にんにく":["japanese"],"にんぷ":["japanese"],"にんまり":["japanese"],"にんむ":["japanese"],"にんめい":["japanese"],"にんよう":["japanese"],"ぬいくぎ":["japanese"],"ぬかす":["japanese"],"ぬぐいとる":["japanese"],"ぬぐう":["japanese"],"ぬくもり":["japanese"],"ぬすむ":["japanese"],"ぬまえび":["japanese"],"ぬめり":["japanese"],"ぬらす":["japanese"],"ぬんちゃく":["japanese"],"ねあげ":["japanese"],"ねいき":["japanese"],"ねいる":["japanese"],"ねいろ":["japanese"],"ねぐせ":["japanese"],"ねくたい":["japanese"],"ねくら":["japanese"],"ねこぜ":["japanese"],"ねこむ":["japanese"],"ねさげ":["japanese"],"ねすごす":["japanese"],"ねそべる":["japanese"],"ねだん":["japanese"],"ねつい":["japanese"],"ねっしん":["japanese"],"ねつぞう":["japanese"],"ねったいぎょ":["japanese"],"ねぶそく":["japanese"],"ねふだ":["japanese"],"ねぼう":["japanese"],"ねほりはほり":["japanese"],"ねまき":["japanese"],"ねまわし":["japanese"],"ねみみ":["japanese"],"ねむい":["japanese"],"ねむたい":["japanese"],"ねもと":["japanese"],"ねらう":["japanese"],"ねわざ":["japanese"],"ねんいり":["japanese"],"ねんおし":["japanese"],"ねんかん":["japanese"],"ねんきん":["japanese"],"ねんぐ":["japanese"],"ねんざ":["japanese"],"ねんし":["japanese"],"ねんちゃく":["japanese"],"ねんど":["japanese"],"ねんぴ":["japanese"],"ねんぶつ":["japanese"],"ねんまつ":["japanese"],"ねんりょう":["japanese"],"ねんれい":["japanese"],"のいず":["japanese"],"のおづま":["japanese"],"のがす":["japanese"],"のきなみ":["japanese"],"のこぎり":["japanese"],"のこす":["japanese"],"のこる":["japanese"],"のせる":["japanese"],"のぞく":["japanese"],"のぞむ":["japanese"],"のたまう":["japanese"],"のちほど":["japanese"],"のっく":["japanese"],"のばす":["japanese"],"のはら":["japanese"],"のべる":["japanese"],"のぼる":["japanese"],"のみもの":["japanese"],"のやま":["japanese"],"のらいぬ":["japanese"],"のらねこ":["japanese"],"のりもの":["japanese"],"のりゆき":["japanese"],"のれん":["japanese"],"のんき":["japanese"],"ばあい":["japanese"],"はあく":["japanese"],"ばあさん":["japanese"],"ばいか":["japanese"],"ばいく":["japanese"],"はいけん":["japanese"],"はいご":["japanese"],"はいしん":["japanese"],"はいすい":["japanese"],"はいせん":["japanese"],"はいそう":["japanese"],"はいち":["japanese"],"ばいばい":["japanese"],"はいれつ":["japanese"],"はえる":["japanese"],"はおる":["japanese"],"はかい":["japanese"],"ばかり":["japanese"],"はかる":["japanese"],"はくしゅ":["japanese"],"はけん":["japanese"],"はこぶ":["japanese"],"はさみ":["japanese"],"はさん":["japanese"],"はしご":["japanese"],"ばしょ":["japanese"],"はしる":["japanese"],"はせる":["japanese"],"ぱそこん":["japanese"],"はそん":["japanese"],"はたん":["japanese"],"はちみつ":["japanese"],"はつおん":["japanese"],"はっかく":["japanese"],"はづき":["japanese"],"はっきり":["japanese"],"はっくつ":["japanese"],"はっけん":["japanese"],"はっこう":["japanese"],"はっさん":["japanese"],"はっしん":["japanese"],"はったつ":["japanese"],"はっちゅう":["japanese"],"はってん":["japanese"],"はっぴょう":["japanese"],"はっぽう":["japanese"],"はなす":["japanese"],"はなび":["japanese"],"はにかむ":["japanese"],"はぶらし":["japanese"],"はみがき":["japanese"],"はむかう":["japanese"],"はめつ":["japanese"],"はやい":["japanese"],"はやし":["japanese"],"はらう":["japanese"],"はろうぃん":["japanese"],"はわい":["japanese"],"はんい":["japanese"],"はんえい":["japanese"],"はんおん":["japanese"],"はんかく":["japanese"],"はんきょう":["japanese"],"ばんぐみ":["japanese"],"はんこ":["japanese"],"はんしゃ":["japanese"],"はんすう":["japanese"],"はんだん":["japanese"],"ぱんち":["japanese"],"ぱんつ":["japanese"],"はんてい":["japanese"],"はんとし":["japanese"],"はんのう":["japanese"],"はんぱ":["japanese"],"はんぶん":["japanese"],"はんぺん":["japanese"],"はんぼうき":["japanese"],"はんめい":["japanese"],"はんらん":["japanese"],"はんろん":["japanese"],"ひいき":["japanese"],"ひうん":["japanese"],"ひえる":["japanese"],"ひかく":["japanese"],"ひかり":["japanese"],"ひかる":["japanese"],"ひかん":["japanese"],"ひくい":["japanese"],"ひけつ":["japanese"],"ひこうき":["japanese"],"ひこく":["japanese"],"ひさい":["japanese"],"ひさしぶり":["japanese"],"ひさん":["japanese"],"びじゅつかん":["japanese"],"ひしょ":["japanese"],"ひそか":["japanese"],"ひそむ":["japanese"],"ひたむき":["japanese"],"ひだり":["japanese"],"ひたる":["japanese"],"ひつぎ":["japanese"],"ひっこし":["japanese"],"ひっし":["japanese"],"ひつじゅひん":["japanese"],"ひっす":["japanese"],"ひつぜん":["japanese"],"ぴったり":["japanese"],"ぴっちり":["japanese"],"ひつよう":["japanese"],"ひてい":["japanese"],"ひとごみ":["japanese"],"ひなまつり":["japanese"],"ひなん":["japanese"],"ひねる":["japanese"],"ひはん":["japanese"],"ひびく":["japanese"],"ひひょう":["japanese"],"ひほう":["japanese"],"ひまわり":["japanese"],"ひまん":["japanese"],"ひみつ":["japanese"],"ひめい":["japanese"],"ひめじし":["japanese"],"ひやけ":["japanese"],"ひやす":["japanese"],"ひよう":["japanese"],"びょうき":["japanese"],"ひらがな":["japanese"],"ひらく":["japanese"],"ひりつ":["japanese"],"ひりょう":["japanese"],"ひるま":["japanese"],"ひるやすみ":["japanese"],"ひれい":["japanese"],"ひろい":["japanese"],"ひろう":["japanese"],"ひろき":["japanese"],"ひろゆき":["japanese"],"ひんかく":["japanese"],"ひんけつ":["japanese"],"ひんこん":["japanese"],"ひんしゅ":["japanese"],"ひんそう":["japanese"],"ぴんち":["japanese"],"ひんぱん":["japanese"],"びんぼう":["japanese"],"ふあん":["japanese"],"ふいうち":["japanese"],"ふうけい":["japanese"],"ふうせん":["japanese"],"ぷうたろう":["japanese"],"ふうとう":["japanese"],"ふうふ":["japanese"],"ふえる":["japanese"],"ふおん":["japanese"],"ふかい":["japanese"],"ふきん":["japanese"],"ふくざつ":["japanese"],"ふくぶくろ":["japanese"],"ふこう":["japanese"],"ふさい":["japanese"],"ふしぎ":["japanese"],"ふじみ":["japanese"],"ふすま":["japanese"],"ふせい":["japanese"],"ふせぐ":["japanese"],"ふそく":["japanese"],"ぶたにく":["japanese"],"ふたん":["japanese"],"ふちょう":["japanese"],"ふつう":["japanese"],"ふつか":["japanese"],"ふっかつ":["japanese"],"ふっき":["japanese"],"ふっこく":["japanese"],"ぶどう":["japanese"],"ふとる":["japanese"],"ふとん":["japanese"],"ふのう":["japanese"],"ふはい":["japanese"],"ふひょう":["japanese"],"ふへん":["japanese"],"ふまん":["japanese"],"ふみん":["japanese"],"ふめつ":["japanese"],"ふめん":["japanese"],"ふよう":["japanese"],"ふりこ":["japanese"],"ふりる":["japanese"],"ふるい":["japanese"],"ふんいき":["japanese"],"ぶんがく":["japanese"],"ぶんぐ":["japanese"],"ふんしつ":["japanese"],"ぶんせき":["japanese"],"ふんそう":["japanese"],"ぶんぽう":["japanese"],"へいあん":["japanese"],"へいおん":["japanese"],"へいがい":["japanese"],"へいき":["japanese"],"へいげん":["japanese"],"へいこう":["japanese"],"へいさ":["japanese"],"へいしゃ":["japanese"],"へいせつ":["japanese"],"へいそ":["japanese"],"へいたく":["japanese"],"へいてん":["japanese"],"へいねつ":["japanese"],"へいわ":["japanese"],"へきが":["japanese"],"へこむ":["japanese"],"べにいろ":["japanese"],"べにしょうが":["japanese"],"へらす":["japanese"],"へんかん":["japanese"],"べんきょう":["japanese"],"べんごし":["japanese"],"へんさい":["japanese"],"へんたい":["japanese"],"べんり":["japanese"],"ほあん":["japanese"],"ほいく":["japanese"],"ぼうぎょ":["japanese"],"ほうこく":["japanese"],"ほうそう":["japanese"],"ほうほう":["japanese"],"ほうもん":["japanese"],"ほうりつ":["japanese"],"ほえる":["japanese"],"ほおん":["japanese"],"ほかん":["japanese"],"ほきょう":["japanese"],"ぼきん":["japanese"],"ほくろ":["japanese"],"ほけつ":["japanese"],"ほけん":["japanese"],"ほこう":["japanese"],"ほこる":["japanese"],"ほしい":["japanese"],"ほしつ":["japanese"],"ほしゅ":["japanese"],"ほしょう":["japanese"],"ほせい":["japanese"],"ほそい":["japanese"],"ほそく":["japanese"],"ほたて":["japanese"],"ほたる":["japanese"],"ぽちぶくろ":["japanese"],"ほっきょく":["japanese"],"ほっさ":["japanese"],"ほったん":["japanese"],"ほとんど":["japanese"],"ほめる":["japanese"],"ほんい":["japanese"],"ほんき":["japanese"],"ほんけ":["japanese"],"ほんしつ":["japanese"],"ほんやく":["japanese"],"まいにち":["japanese"],"まかい":["japanese"],"まかせる":["japanese"],"まがる":["japanese"],"まける":["japanese"],"まこと":["japanese"],"まさつ":["japanese"],"まじめ":["japanese"],"ますく":["japanese"],"まぜる":["japanese"],"まつり":["japanese"],"まとめ":["japanese"],"まなぶ":["japanese"],"まぬけ":["japanese"],"まねく":["japanese"],"まほう":["japanese"],"まもる":["japanese"],"まゆげ":["japanese"],"まよう":["japanese"],"まろやか":["japanese"],"まわす":["japanese"],"まわり":["japanese"],"まわる":["japanese"],"まんが":["japanese"],"まんきつ":["japanese"],"まんぞく":["japanese"],"まんなか":["japanese"],"みいら":["japanese"],"みうち":["japanese"],"みえる":["japanese"],"みがく":["japanese"],"みかた":["japanese"],"みかん":["japanese"],"みけん":["japanese"],"みこん":["japanese"],"みじかい":["japanese"],"みすい":["japanese"],"みすえる":["japanese"],"みせる":["japanese"],"みっか":["japanese"],"みつかる":["japanese"],"みつける":["japanese"],"みてい":["japanese"],"みとめる":["japanese"],"みなと":["japanese"],"みなみかさい":["japanese"],"みねらる":["japanese"],"みのう":["japanese"],"みのがす":["japanese"],"みほん":["japanese"],"みもと":["japanese"],"みやげ":["japanese"],"みらい":["japanese"],"みりょく":["japanese"],"みわく":["japanese"],"みんか":["japanese"],"みんぞく":["japanese"],"むいか":["japanese"],"むえき":["japanese"],"むえん":["japanese"],"むかい":["japanese"],"むかう":["japanese"],"むかえ":["japanese"],"むかし":["japanese"],"むぎちゃ":["japanese"],"むける":["japanese"],"むげん":["japanese"],"むさぼる":["japanese"],"むしあつい":["japanese"],"むしば":["japanese"],"むじゅん":["japanese"],"むしろ":["japanese"],"むすう":["japanese"],"むすこ":["japanese"],"むすぶ":["japanese"],"むすめ":["japanese"],"むせる":["japanese"],"むせん":["japanese"],"むちゅう":["japanese"],"むなしい":["japanese"],"むのう":["japanese"],"むやみ":["japanese"],"むよう":["japanese"],"むらさき":["japanese"],"むりょう":["japanese"],"むろん":["japanese"],"めいあん":["japanese"],"めいうん":["japanese"],"めいえん":["japanese"],"めいかく":["japanese"],"めいきょく":["japanese"],"めいさい":["japanese"],"めいし":["japanese"],"めいそう":["japanese"],"めいぶつ":["japanese"],"めいれい":["japanese"],"めいわく":["japanese"],"めぐまれる":["japanese"],"めざす":["japanese"],"めした":["japanese"],"めずらしい":["japanese"],"めだつ":["japanese"],"めまい":["japanese"],"めやす":["japanese"],"めんきょ":["japanese"],"めんせき":["japanese"],"めんどう":["japanese"],"もうしあげる":["japanese"],"もうどうけん":["japanese"],"もえる":["japanese"],"もくし":["japanese"],"もくてき":["japanese"],"もくようび":["japanese"],"もちろん":["japanese"],"もどる":["japanese"],"もらう":["japanese"],"もんく":["japanese"],"もんだい":["japanese"],"やおや":["japanese"],"やける":["japanese"],"やさい":["japanese"],"やさしい":["japanese"],"やすい":["japanese"],"やすたろう":["japanese"],"やすみ":["japanese"],"やせる":["japanese"],"やそう":["japanese"],"やたい":["japanese"],"やちん":["japanese"],"やっと":["japanese"],"やっぱり":["japanese"],"やぶる":["japanese"],"やめる":["japanese"],"ややこしい":["japanese"],"やよい":["japanese"],"やわらかい":["japanese"],"ゆうき":["japanese"],"ゆうびんきょく":["japanese"],"ゆうべ":["japanese"],"ゆうめい":["japanese"],"ゆけつ":["japanese"],"ゆしゅつ":["japanese"],"ゆせん":["japanese"],"ゆそう":["japanese"],"ゆたか":["japanese"],"ゆちゃく":["japanese"],"ゆでる":["japanese"],"ゆにゅう":["japanese"],"ゆびわ":["japanese"],"ゆらい":["japanese"],"ゆれる":["japanese"],"ようい":["japanese"],"ようか":["japanese"],"ようきゅう":["japanese"],"ようじ":["japanese"],"ようす":["japanese"],"ようちえん":["japanese"],"よかぜ":["japanese"],"よかん":["japanese"],"よきん":["japanese"],"よくせい":["japanese"],"よくぼう":["japanese"],"よけい":["japanese"],"よごれる":["japanese"],"よさん":["japanese"],"よしゅう":["japanese"],"よそう":["japanese"],"よそく":["japanese"],"よっか":["japanese"],"よてい":["japanese"],"よどがわく":["japanese"],"よねつ":["japanese"],"よやく":["japanese"],"よゆう":["japanese"],"よろこぶ":["japanese"],"よろしい":["japanese"],"らいう":["japanese"],"らくがき":["japanese"],"らくご":["japanese"],"らくさつ":["japanese"],"らくだ":["japanese"],"らしんばん":["japanese"],"らせん":["japanese"],"らぞく":["japanese"],"らたい":["japanese"],"らっか":["japanese"],"られつ":["japanese"],"りえき":["japanese"],"りかい":["japanese"],"りきさく":["japanese"],"りきせつ":["japanese"],"りくぐん":["japanese"],"りくつ":["japanese"],"りけん":["japanese"],"りこう":["japanese"],"りせい":["japanese"],"りそう":["japanese"],"りそく":["japanese"],"りてん":["japanese"],"りねん":["japanese"],"りゆう":["japanese"],"りゅうがく":["japanese"],"りよう":["japanese"],"りょうり":["japanese"],"りょかん":["japanese"],"りょくちゃ":["japanese"],"りょこう":["japanese"],"りりく":["japanese"],"りれき":["japanese"],"りろん":["japanese"],"りんご":["japanese"],"るいけい":["japanese"],"るいさい":["japanese"],"るいじ":["japanese"],"るいせき":["japanese"],"るすばん":["japanese"],"るりがわら":["japanese"],"れいかん":["japanese"],"れいぎ":["japanese"],"れいせい":["japanese"],"れいぞうこ":["japanese"],"れいとう":["japanese"],"れいぼう":["japanese"],"れきし":["japanese"],"れきだい":["japanese"],"れんあい":["japanese"],"れんけい":["japanese"],"れんこん":["japanese"],"れんさい":["japanese"],"れんしゅう":["japanese"],"れんぞく":["japanese"],"れんらく":["japanese"],"ろうか":["japanese"],"ろうご":["japanese"],"ろうじん":["japanese"],"ろうそく":["japanese"],"ろくが":["japanese"],"ろこつ":["japanese"],"ろじうら":["japanese"],"ろしゅつ":["japanese"],"ろせん":["japanese"],"ろてん":["japanese"],"ろめん":["japanese"],"ろれつ":["japanese"],"ろんぎ":["japanese"],"ろんぱ":["japanese"],"ろんぶん":["japanese"],"ろんり":["japanese"],"わかす":["japanese"],"わかめ":["japanese"],"わかやま":["japanese"],"わかれる":["japanese"],"わしつ":["japanese"],"わじまし":["japanese"],"わすれもの":["japanese"],"わらう":["japanese"],"われる":["japanese"],"가격":["korean"],"가끔":["korean"],"가난":["korean"],"가능":["korean"],"가득":["korean"],"가르침":["korean"],"가뭄":["korean"],"가방":["korean"],"가상":["korean"],"가슴":["korean"],"가운데":["korean"],"가을":["korean"],"가이드":["korean"],"가입":["korean"],"가장":["korean"],"가정":["korean"],"가족":["korean"],"가죽":["korean"],"각오":["korean"],"각자":["korean"],"간격":["korean"],"간부":["korean"],"간섭":["korean"],"간장":["korean"],"간접":["korean"],"간판":["korean"],"갈등":["korean"],"갈비":["korean"],"갈색":["korean"],"갈증":["korean"],"감각":["korean"],"감기":["korean"],"감소":["korean"],"감수성":["korean"],"감자":["korean"],"감정":["korean"],"갑자기":["korean"],"강남":["korean"],"강당":["korean"],"강도":["korean"],"강력히":["korean"],"강변":["korean"],"강북":["korean"],"강사":["korean"],"강수량":["korean"],"강아지":["korean"],"강원도":["korean"],"강의":["korean"],"강제":["korean"],"강조":["korean"],"같이":["korean"],"개구리":["korean"],"개나리":["korean"],"개방":["korean"],"개별":["korean"],"개선":["korean"],"개성":["korean"],"개인":["korean"],"객관적":["korean"],"거실":["korean"],"거액":["korean"],"거울":["korean"],"거짓":["korean"],"거품":["korean"],"걱정":["korean"],"건강":["korean"],"건물":["korean"],"건설":["korean"],"건조":["korean"],"건축":["korean"],"걸음":["korean"],"검사":["korean"],"검토":["korean"],"게시판":["korean"],"게임":["korean"],"겨울":["korean"],"견해":["korean"],"결과":["korean"],"결국":["korean"],"결론":["korean"],"결석":["korean"],"결승":["korean"],"결심":["korean"],"결정":["korean"],"결혼":["korean"],"경계":["korean"],"경고":["korean"],"경기":["korean"],"경력":["korean"],"경복궁":["korean"],"경비":["korean"],"경상도":["korean"],"경영":["korean"],"경우":["korean"],"경쟁":["korean"],"경제":["korean"],"경주":["korean"],"경찰":["korean"],"경치":["korean"],"경향":["korean"],"경험":["korean"],"계곡":["korean"],"계단":["korean"],"계란":["korean"],"계산":["korean"],"계속":["korean"],"계약":["korean"],"계절":["korean"],"계층":["korean"],"계획":["korean"],"고객":["korean"],"고구려":["korean"],"고궁":["korean"],"고급":["korean"],"고등학생":["korean"],"고무신":["korean"],"고민":["korean"],"고양이":["korean"],"고장":["korean"],"고전":["korean"],"고집":["korean"],"고춧가루":["korean"],"고통":["korean"],"고향":["korean"],"곡식":["korean"],"골목":["korean"],"골짜기":["korean"],"골프":["korean"],"공간":["korean"],"공개":["korean"],"공격":["korean"],"공군":["korean"],"공급":["korean"],"공기":["korean"],"공동":["korean"],"공무원":["korean"],"공부":["korean"],"공사":["korean"],"공식":["korean"],"공업":["korean"],"공연":["korean"],"공원":["korean"],"공장":["korean"],"공짜":["korean"],"공책":["korean"],"공통":["korean"],"공포":["korean"],"공항":["korean"],"공휴일":["korean"],"과목":["korean"],"과일":["korean"],"과장":["korean"],"과정":["korean"],"과학":["korean"],"관객":["korean"],"관계":["korean"],"관광":["korean"],"관념":["korean"],"관람":["korean"],"관련":["korean"],"관리":["korean"],"관습":["korean"],"관심":["korean"],"관점":["korean"],"관찰":["korean"],"광경":["korean"],"광고":["korean"],"광장":["korean"],"광주":["korean"],"괴로움":["korean"],"굉장히":["korean"],"교과서":["korean"],"교문":["korean"],"교복":["korean"],"교실":["korean"],"교양":["korean"],"교육":["korean"],"교장":["korean"],"교직":["korean"],"교통":["korean"],"교환":["korean"],"교훈":["korean"],"구경":["korean"],"구름":["korean"],"구멍":["korean"],"구별":["korean"],"구분":["korean"],"구석":["korean"],"구성":["korean"],"구속":["korean"],"구역":["korean"],"구입":["korean"],"구청":["korean"],"구체적":["korean"],"국가":["korean"],"국기":["korean"],"국내":["korean"],"국립":["korean"],"국물":["korean"],"국민":["korean"],"국수":["korean"],"국어":["korean"],"국왕":["korean"],"국적":["korean"],"국제":["korean"],"국회":["korean"],"군대":["korean"],"군사":["korean"],"군인":["korean"],"궁극적":["korean"],"권리":["korean"],"권위":["korean"],"권투":["korean"],"귀국":["korean"],"귀신":["korean"],"규정":["korean"],"규칙":["korean"],"균형":["korean"],"그날":["korean"],"그냥":["korean"],"그늘":["korean"],"그러나":["korean"],"그룹":["korean"],"그릇":["korean"],"그림":["korean"],"그제서야":["korean"],"그토록":["korean"],"극복":["korean"],"극히":["korean"],"근거":["korean"],"근교":["korean"],"근래":["korean"],"근로":["korean"],"근무":["korean"],"근본":["korean"],"근원":["korean"],"근육":["korean"],"근처":["korean"],"글씨":["korean"],"글자":["korean"],"금강산":["korean"],"금고":["korean"],"금년":["korean"],"금메달":["korean"],"금액":["korean"],"금연":["korean"],"금요일":["korean"],"금지":["korean"],"긍정적":["korean"],"기간":["korean"],"기관":["korean"],"기념":["korean"],"기능":["korean"],"기독교":["korean"],"기둥":["korean"],"기록":["korean"],"기름":["korean"],"기법":["korean"],"기본":["korean"],"기분":["korean"],"기쁨":["korean"],"기숙사":["korean"],"기술":["korean"],"기억":["korean"],"기업":["korean"],"기온":["korean"],"기운":["korean"],"기원":["korean"],"기적":["korean"],"기준":["korean"],"기침":["korean"],"기혼":["korean"],"기획":["korean"],"긴급":["korean"],"긴장":["korean"],"길이":["korean"],"김밥":["korean"],"김치":["korean"],"김포공항":["korean"],"깍두기":["korean"],"깜빡":["korean"],"깨달음":["korean"],"깨소금":["korean"],"껍질":["korean"],"꼭대기":["korean"],"꽃잎":["korean"],"나들이":["korean"],"나란히":["korean"],"나머지":["korean"],"나물":["korean"],"나침반":["korean"],"나흘":["korean"],"낙엽":["korean"],"난방":["korean"],"날개":["korean"],"날씨":["korean"],"날짜":["korean"],"남녀":["korean"],"남대문":["korean"],"남매":["korean"],"남산":["korean"],"남자":["korean"],"남편":["korean"],"남학생":["korean"],"낭비":["korean"],"낱말":["korean"],"내년":["korean"],"내용":["korean"],"내일":["korean"],"냄비":["korean"],"냄새":["korean"],"냇물":["korean"],"냉동":["korean"],"냉면":["korean"],"냉방":["korean"],"냉장고":["korean"],"넥타이":["korean"],"넷째":["korean"],"노동":["korean"],"노란색":["korean"],"노력":["korean"],"노인":["korean"],"녹음":["korean"],"녹차":["korean"],"녹화":["korean"],"논리":["korean"],"논문":["korean"],"논쟁":["korean"],"놀이":["korean"],"농구":["korean"],"농담":["korean"],"농민":["korean"],"농부":["korean"],"농업":["korean"],"농장":["korean"],"농촌":["korean"],"높이":["korean"],"눈동자":["korean"],"눈물":["korean"],"눈썹":["korean"],"뉴욕":["korean"],"느낌":["korean"],"늑대":["korean"],"능동적":["korean"],"능력":["korean"],"다방":["korean"],"다양성":["korean"],"다음":["korean"],"다이어트":["korean"],"다행":["korean"],"단계":["korean"],"단골":["korean"],"단독":["korean"],"단맛":["korean"],"단순":["korean"],"단어":["korean"],"단위":["korean"],"단점":["korean"],"단체":["korean"],"단추":["korean"],"단편":["korean"],"단풍":["korean"],"달걀":["korean"],"달러":["korean"],"달력":["korean"],"달리":["korean"],"닭고기":["korean"],"담당":["korean"],"담배":["korean"],"담요":["korean"],"담임":["korean"],"답변":["korean"],"답장":["korean"],"당근":["korean"],"당분간":["korean"],"당연히":["korean"],"당장":["korean"],"대규모":["korean"],"대낮":["korean"],"대단히":["korean"],"대답":["korean"],"대도시":["korean"],"대략":["korean"],"대량":["korean"],"대륙":["korean"],"대문":["korean"],"대부분":["korean"],"대신":["korean"],"대응":["korean"],"대장":["korean"],"대전":["korean"],"대접":["korean"],"대중":["korean"],"대책":["korean"],"대출":["korean"],"대충":["korean"],"대통령":["korean"],"대학":["korean"],"대한민국":["korean"],"대합실":["korean"],"대형":["korean"],"덩어리":["korean"],"데이트":["korean"],"도대체":["korean"],"도덕":["korean"],"도둑":["korean"],"도망":["korean"],"도서관":["korean"],"도심":["korean"],"도움":["korean"],"도입":["korean"],"도자기":["korean"],"도저히":["korean"],"도전":["korean"],"도중":["korean"],"도착":["korean"],"독감":["korean"],"독립":["korean"],"독서":["korean"],"독일":["korean"],"독창적":["korean"],"동화책":["korean"],"뒷모습":["korean"],"뒷산":["korean"],"딸아이":["korean"],"마누라":["korean"],"마늘":["korean"],"마당":["korean"],"마라톤":["korean"],"마련":["korean"],"마무리":["korean"],"마사지":["korean"],"마약":["korean"],"마요네즈":["korean"],"마을":["korean"],"마음":["korean"],"마이크":["korean"],"마중":["korean"],"마지막":["korean"],"마찬가지":["korean"],"마찰":["korean"],"마흔":["korean"],"막걸리":["korean"],"막내":["korean"],"막상":["korean"],"만남":["korean"],"만두":["korean"],"만세":["korean"],"만약":["korean"],"만일":["korean"],"만점":["korean"],"만족":["korean"],"만화":["korean"],"많이":["korean"],"말기":["korean"],"말씀":["korean"],"말투":["korean"],"맘대로":["korean"],"망원경":["korean"],"매년":["korean"],"매달":["korean"],"매력":["korean"],"매번":["korean"],"매스컴":["korean"],"매일":["korean"],"매장":["korean"],"맥주":["korean"],"먹이":["korean"],"먼저":["korean"],"먼지":["korean"],"멀리":["korean"],"메일":["korean"],"며느리":["korean"],"며칠":["korean"],"면담":["korean"],"멸치":["korean"],"명단":["korean"],"명령":["korean"],"명예":["korean"],"명의":["korean"],"명절":["korean"],"명칭":["korean"],"명함":["korean"],"모금":["korean"],"모니터":["korean"],"모델":["korean"],"모든":["korean"],"모범":["korean"],"모습":["korean"],"모양":["korean"],"모임":["korean"],"모조리":["korean"],"모집":["korean"],"모퉁이":["korean"],"목걸이":["korean"],"목록":["korean"],"목사":["korean"],"목소리":["korean"],"목숨":["korean"],"목적":["korean"],"목표":["korean"],"몰래":["korean"],"몸매":["korean"],"몸무게":["korean"],"몸살":["korean"],"몸속":["korean"],"몸짓":["korean"],"몸통":["korean"],"몹시":["korean"],"무관심":["korean"],"무궁화":["korean"],"무더위":["korean"],"무덤":["korean"],"무릎":["korean"],"무슨":["korean"],"무엇":["korean"],"무역":["korean"],"무용":["korean"],"무조건":["korean"],"무지개":["korean"],"무척":["korean"],"문구":["korean"],"문득":["korean"],"문법":["korean"],"문서":["korean"],"문제":["korean"],"문학":["korean"],"문화":["korean"],"물가":["korean"],"물건":["korean"],"물결":["korean"],"물고기":["korean"],"물론":["korean"],"물리학":["korean"],"물음":["korean"],"물질":["korean"],"물체":["korean"],"미국":["korean"],"미디어":["korean"],"미사일":["korean"],"미술":["korean"],"미역":["korean"],"미용실":["korean"],"미움":["korean"],"미인":["korean"],"미팅":["korean"],"미혼":["korean"],"민간":["korean"],"민족":["korean"],"민주":["korean"],"믿음":["korean"],"밀가루":["korean"],"밀리미터":["korean"],"밑바닥":["korean"],"바가지":["korean"],"바구니":["korean"],"바나나":["korean"],"바늘":["korean"],"바닥":["korean"],"바닷가":["korean"],"바람":["korean"],"바이러스":["korean"],"바탕":["korean"],"박물관":["korean"],"박사":["korean"],"박수":["korean"],"반대":["korean"],"반드시":["korean"],"반말":["korean"],"반발":["korean"],"반성":["korean"],"반응":["korean"],"반장":["korean"],"반죽":["korean"],"반지":["korean"],"반찬":["korean"],"받침":["korean"],"발가락":["korean"],"발걸음":["korean"],"발견":["korean"],"발달":["korean"],"발레":["korean"],"발목":["korean"],"발바닥":["korean"],"발생":["korean"],"발음":["korean"],"발자국":["korean"],"발전":["korean"],"발톱":["korean"],"발표":["korean"],"밤하늘":["korean"],"밥그릇":["korean"],"밥맛":["korean"],"밥상":["korean"],"밥솥":["korean"],"방금":["korean"],"방면":["korean"],"방문":["korean"],"방바닥":["korean"],"방법":["korean"],"방송":["korean"],"방식":["korean"],"방안":["korean"],"방울":["korean"],"방지":["korean"],"방학":["korean"],"방해":["korean"],"방향":["korean"],"배경":["korean"],"배꼽":["korean"],"배달":["korean"],"배드민턴":["korean"],"백두산":["korean"],"백색":["korean"],"백성":["korean"],"백인":["korean"],"백제":["korean"],"백화점":["korean"],"버릇":["korean"],"버섯":["korean"],"버튼":["korean"],"번개":["korean"],"번역":["korean"],"번지":["korean"],"번호":["korean"],"벌금":["korean"],"벌레":["korean"],"벌써":["korean"],"범위":["korean"],"범인":["korean"],"범죄":["korean"],"법률":["korean"],"법원":["korean"],"법적":["korean"],"법칙":["korean"],"베이징":["korean"],"벨트":["korean"],"변경":["korean"],"변동":["korean"],"변명":["korean"],"변신":["korean"],"변호사":["korean"],"변화":["korean"],"별도":["korean"],"별명":["korean"],"별일":["korean"],"병실":["korean"],"병아리":["korean"],"병원":["korean"],"보관":["korean"],"보너스":["korean"],"보라색":["korean"],"보람":["korean"],"보름":["korean"],"보상":["korean"],"보안":["korean"],"보자기":["korean"],"보장":["korean"],"보전":["korean"],"보존":["korean"],"보통":["korean"],"보편적":["korean"],"보험":["korean"],"복도":["korean"],"복사":["korean"],"복숭아":["korean"],"복습":["korean"],"볶음":["korean"],"본격적":["korean"],"본래":["korean"],"본부":["korean"],"본사":["korean"],"본성":["korean"],"본인":["korean"],"본질":["korean"],"볼펜":["korean"],"봉사":["korean"],"봉지":["korean"],"봉투":["korean"],"부근":["korean"],"부끄러움":["korean"],"부담":["korean"],"부동산":["korean"],"부문":["korean"],"부분":["korean"],"부산":["korean"],"부상":["korean"],"부엌":["korean"],"부인":["korean"],"부작용":["korean"],"부장":["korean"],"부정":["korean"],"부족":["korean"],"부지런히":["korean"],"부친":["korean"],"부탁":["korean"],"부품":["korean"],"부회장":["korean"],"북부":["korean"],"북한":["korean"],"분노":["korean"],"분량":["korean"],"분리":["korean"],"분명":["korean"],"분석":["korean"],"분야":["korean"],"분위기":["korean"],"분필":["korean"],"분홍색":["korean"],"불고기":["korean"],"불과":["korean"],"불교":["korean"],"불꽃":["korean"],"불만":["korean"],"불법":["korean"],"불빛":["korean"],"불안":["korean"],"불이익":["korean"],"불행":["korean"],"브랜드":["korean"],"비극":["korean"],"비난":["korean"],"비닐":["korean"],"비둘기":["korean"],"비디오":["korean"],"비로소":["korean"],"비만":["korean"],"비명":["korean"],"비밀":["korean"],"비바람":["korean"],"비빔밥":["korean"],"비상":["korean"],"비용":["korean"],"비율":["korean"],"비중":["korean"],"비타민":["korean"],"비판":["korean"],"빌딩":["korean"],"빗물":["korean"],"빗방울":["korean"],"빗줄기":["korean"],"빛깔":["korean"],"빨간색":["korean"],"빨래":["korean"],"빨리":["korean"],"사건":["korean"],"사계절":["korean"],"사나이":["korean"],"사냥":["korean"],"사람":["korean"],"사랑":["korean"],"사립":["korean"],"사모님":["korean"],"사물":["korean"],"사방":["korean"],"사상":["korean"],"사생활":["korean"],"사설":["korean"],"사슴":["korean"],"사실":["korean"],"사업":["korean"],"사용":["korean"],"사월":["korean"],"사장":["korean"],"사전":["korean"],"사진":["korean"],"사촌":["korean"],"사춘기":["korean"],"사탕":["korean"],"사투리":["korean"],"사흘":["korean"],"산길":["korean"],"산부인과":["korean"],"산업":["korean"],"산책":["korean"],"살림":["korean"],"살인":["korean"],"살짝":["korean"],"삼계탕":["korean"],"삼국":["korean"],"삼십":["korean"],"삼월":["korean"],"삼촌":["korean"],"상관":["korean"],"상금":["korean"],"상대":["korean"],"상류":["korean"],"상반기":["korean"],"상상":["korean"],"상식":["korean"],"상업":["korean"],"상인":["korean"],"상자":["korean"],"상점":["korean"],"상처":["korean"],"상추":["korean"],"상태":["korean"],"상표":["korean"],"상품":["korean"],"상황":["korean"],"새벽":["korean"],"색깔":["korean"],"색연필":["korean"],"생각":["korean"],"생명":["korean"],"생물":["korean"],"생방송":["korean"],"생산":["korean"],"생선":["korean"],"생신":["korean"],"생일":["korean"],"생활":["korean"],"서랍":["korean"],"서른":["korean"],"서명":["korean"],"서민":["korean"],"서비스":["korean"],"서양":["korean"],"서울":["korean"],"서적":["korean"],"서점":["korean"],"서쪽":["korean"],"서클":["korean"],"석사":["korean"],"석유":["korean"],"선거":["korean"],"선물":["korean"],"선배":["korean"],"선생":["korean"],"선수":["korean"],"선원":["korean"],"선장":["korean"],"선전":["korean"],"선택":["korean"],"선풍기":["korean"],"설거지":["korean"],"설날":["korean"],"설렁탕":["korean"],"설명":["korean"],"설문":["korean"],"설사":["korean"],"설악산":["korean"],"설치":["korean"],"설탕":["korean"],"섭씨":["korean"],"성공":["korean"],"성당":["korean"],"성명":["korean"],"성별":["korean"],"성인":["korean"],"성장":["korean"],"성적":["korean"],"성질":["korean"],"성함":["korean"],"세금":["korean"],"세미나":["korean"],"세상":["korean"],"세월":["korean"],"세종대왕":["korean"],"세탁":["korean"],"센터":["korean"],"센티미터":["korean"],"셋째":["korean"],"소규모":["korean"],"소극적":["korean"],"소금":["korean"],"소나기":["korean"],"소년":["korean"],"소득":["korean"],"소망":["korean"],"소문":["korean"],"소설":["korean"],"소속":["korean"],"소아과":["korean"],"소용":["korean"],"소원":["korean"],"소음":["korean"],"소중히":["korean"],"소지품":["korean"],"소질":["korean"],"소풍":["korean"],"소형":["korean"],"속담":["korean"],"속도":["korean"],"속옷":["korean"],"손가락":["korean"],"손길":["korean"],"손녀":["korean"],"손님":["korean"],"손등":["korean"],"손목":["korean"],"손뼉":["korean"],"손실":["korean"],"손질":["korean"],"손톱":["korean"],"손해":["korean"],"솔직히":["korean"],"솜씨":["korean"],"송아지":["korean"],"송이":["korean"],"송편":["korean"],"쇠고기":["korean"],"쇼핑":["korean"],"수건":["korean"],"수년":["korean"],"수단":["korean"],"수돗물":["korean"],"수동적":["korean"],"수면":["korean"],"수명":["korean"],"수박":["korean"],"수상":["korean"],"수석":["korean"],"수술":["korean"],"수시로":["korean"],"수업":["korean"],"수염":["korean"],"수영":["korean"],"수입":["korean"],"수준":["korean"],"수집":["korean"],"수출":["korean"],"수컷":["korean"],"수필":["korean"],"수학":["korean"],"수험생":["korean"],"수화기":["korean"],"숙녀":["korean"],"숙소":["korean"],"숙제":["korean"],"순간":["korean"],"순서":["korean"],"순수":["korean"],"순식간":["korean"],"순위":["korean"],"숟가락":["korean"],"술병":["korean"],"술집":["korean"],"숫자":["korean"],"스님":["korean"],"스물":["korean"],"스스로":["korean"],"스승":["korean"],"스웨터":["korean"],"스위치":["korean"],"스케이트":["korean"],"스튜디오":["korean"],"스트레스":["korean"],"스포츠":["korean"],"슬쩍":["korean"],"슬픔":["korean"],"습관":["korean"],"습기":["korean"],"승객":["korean"],"승리":["korean"],"승부":["korean"],"승용차":["korean"],"승진":["korean"],"시각":["korean"],"시간":["korean"],"시골":["korean"],"시금치":["korean"],"시나리오":["korean"],"시댁":["korean"],"시리즈":["korean"],"시멘트":["korean"],"시민":["korean"],"시부모":["korean"],"시선":["korean"],"시설":["korean"],"시스템":["korean"],"시아버지":["korean"],"시어머니":["korean"],"시월":["korean"],"시인":["korean"],"시일":["korean"],"시작":["korean"],"시장":["korean"],"시절":["korean"],"시점":["korean"],"시중":["korean"],"시즌":["korean"],"시집":["korean"],"시청":["korean"],"시합":["korean"],"시험":["korean"],"식구":["korean"],"식기":["korean"],"식당":["korean"],"식량":["korean"],"식료품":["korean"],"식물":["korean"],"식빵":["korean"],"식사":["korean"],"식생활":["korean"],"식초":["korean"],"식탁":["korean"],"식품":["korean"],"신고":["korean"],"신규":["korean"],"신념":["korean"],"신문":["korean"],"신발":["korean"],"신비":["korean"],"신사":["korean"],"신세":["korean"],"신용":["korean"],"신제품":["korean"],"신청":["korean"],"신체":["korean"],"신화":["korean"],"실감":["korean"],"실내":["korean"],"실력":["korean"],"실례":["korean"],"실망":["korean"],"실수":["korean"],"실습":["korean"],"실시":["korean"],"실장":["korean"],"실정":["korean"],"실질적":["korean"],"실천":["korean"],"실체":["korean"],"실컷":["korean"],"실태":["korean"],"실패":["korean"],"실험":["korean"],"실현":["korean"],"심리":["korean"],"심부름":["korean"],"심사":["korean"],"심장":["korean"],"심정":["korean"],"심판":["korean"],"쌍둥이":["korean"],"씨름":["korean"],"씨앗":["korean"],"아가씨":["korean"],"아나운서":["korean"],"아드님":["korean"],"아들":["korean"],"아쉬움":["korean"],"아스팔트":["korean"],"아시아":["korean"],"아울러":["korean"],"아저씨":["korean"],"아줌마":["korean"],"아직":["korean"],"아침":["korean"],"아파트":["korean"],"아프리카":["korean"],"아픔":["korean"],"아홉":["korean"],"아흔":["korean"],"악기":["korean"],"악몽":["korean"],"악수":["korean"],"안개":["korean"],"안경":["korean"],"안과":["korean"],"안내":["korean"],"안녕":["korean"],"안동":["korean"],"안방":["korean"],"안부":["korean"],"안주":["korean"],"알루미늄":["korean"],"알코올":["korean"],"암시":["korean"],"암컷":["korean"],"압력":["korean"],"앞날":["korean"],"앞문":["korean"],"애인":["korean"],"애정":["korean"],"액수":["korean"],"앨범":["korean"],"야간":["korean"],"야단":["korean"],"야옹":["korean"],"약간":["korean"],"약국":["korean"],"약속":["korean"],"약수":["korean"],"약점":["korean"],"약품":["korean"],"약혼녀":["korean"],"양념":["korean"],"양력":["korean"],"양말":["korean"],"양배추":["korean"],"양주":["korean"],"양파":["korean"],"어둠":["korean"],"어려움":["korean"],"어른":["korean"],"어젯밤":["korean"],"어쨌든":["korean"],"어쩌다가":["korean"],"어쩐지":["korean"],"언니":["korean"],"언덕":["korean"],"언론":["korean"],"언어":["korean"],"얼굴":["korean"],"얼른":["korean"],"얼음":["korean"],"얼핏":["korean"],"엄마":["korean"],"업무":["korean"],"업종":["korean"],"업체":["korean"],"엉덩이":["korean"],"엉망":["korean"],"엉터리":["korean"],"엊그제":["korean"],"에너지":["korean"],"에어컨":["korean"],"엔진":["korean"],"여건":["korean"],"여고생":["korean"],"여관":["korean"],"여군":["korean"],"여권":["korean"],"여대생":["korean"],"여덟":["korean"],"여동생":["korean"],"여든":["korean"],"여론":["korean"],"여름":["korean"],"여섯":["korean"],"여성":["korean"],"여왕":["korean"],"여인":["korean"],"여전히":["korean"],"여직원":["korean"],"여학생":["korean"],"여행":["korean"],"역사":["korean"],"역시":["korean"],"역할":["korean"],"연결":["korean"],"연구":["korean"],"연극":["korean"],"연기":["korean"],"연락":["korean"],"연설":["korean"],"연세":["korean"],"연속":["korean"],"연습":["korean"],"연애":["korean"],"연예인":["korean"],"연인":["korean"],"연장":["korean"],"연주":["korean"],"연출":["korean"],"연필":["korean"],"연합":["korean"],"연휴":["korean"],"열기":["korean"],"열매":["korean"],"열쇠":["korean"],"열심히":["korean"],"열정":["korean"],"열차":["korean"],"열흘":["korean"],"염려":["korean"],"엽서":["korean"],"영국":["korean"],"영남":["korean"],"영상":["korean"],"영양":["korean"],"영역":["korean"],"영웅":["korean"],"영원히":["korean"],"영하":["korean"],"영향":["korean"],"영혼":["korean"],"영화":["korean"],"옆구리":["korean"],"옆방":["korean"],"옆집":["korean"],"예감":["korean"],"예금":["korean"],"예방":["korean"],"예산":["korean"],"예상":["korean"],"예선":["korean"],"예술":["korean"],"예습":["korean"],"예식장":["korean"],"예약":["korean"],"예전":["korean"],"예절":["korean"],"예정":["korean"],"예컨대":["korean"],"옛날":["korean"],"오늘":["korean"],"오락":["korean"],"오랫동안":["korean"],"오렌지":["korean"],"오로지":["korean"],"오른발":["korean"],"오븐":["korean"],"오십":["korean"],"오염":["korean"],"오월":["korean"],"오전":["korean"],"오직":["korean"],"오징어":["korean"],"오페라":["korean"],"오피스텔":["korean"],"오히려":["korean"],"옥상":["korean"],"옥수수":["korean"],"온갖":["korean"],"온라인":["korean"],"온몸":["korean"],"온종일":["korean"],"온통":["korean"],"올가을":["korean"],"올림픽":["korean"],"올해":["korean"],"옷차림":["korean"],"와이셔츠":["korean"],"와인":["korean"],"완성":["korean"],"완전":["korean"],"왕비":["korean"],"왕자":["korean"],"왜냐하면":["korean"],"왠지":["korean"],"외갓집":["korean"],"외국":["korean"],"외로움":["korean"],"외삼촌":["korean"],"외출":["korean"],"외침":["korean"],"외할머니":["korean"],"왼발":["korean"],"왼손":["korean"],"왼쪽":["korean"],"요금":["korean"],"요일":["korean"],"요즘":["korean"],"요청":["korean"],"용기":["korean"],"용서":["korean"],"용어":["korean"],"우산":["korean"],"우선":["korean"],"우승":["korean"],"우연히":["korean"],"우정":["korean"],"우체국":["korean"],"우편":["korean"],"운동":["korean"],"운명":["korean"],"운반":["korean"],"운전":["korean"],"운행":["korean"],"울산":["korean"],"울음":["korean"],"움직임":["korean"],"웃어른":["korean"],"웃음":["korean"],"워낙":["korean"],"원고":["korean"],"원래":["korean"],"원서":["korean"],"원숭이":["korean"],"원인":["korean"],"원장":["korean"],"원피스":["korean"],"월급":["korean"],"월드컵":["korean"],"월세":["korean"],"월요일":["korean"],"웨이터":["korean"],"위반":["korean"],"위법":["korean"],"위성":["korean"],"위원":["korean"],"위험":["korean"],"위협":["korean"],"윗사람":["korean"],"유난히":["korean"],"유럽":["korean"],"유명":["korean"],"유물":["korean"],"유산":["korean"],"유적":["korean"],"유치원":["korean"],"유학":["korean"],"유행":["korean"],"유형":["korean"],"육군":["korean"],"육상":["korean"],"육십":["korean"],"육체":["korean"],"은행":["korean"],"음력":["korean"],"음료":["korean"],"음반":["korean"],"음성":["korean"],"음식":["korean"],"음악":["korean"],"음주":["korean"],"의견":["korean"],"의논":["korean"],"의문":["korean"],"의복":["korean"],"의식":["korean"],"의심":["korean"],"의외로":["korean"],"의욕":["korean"],"의원":["korean"],"의학":["korean"],"이것":["korean"],"이곳":["korean"],"이념":["korean"],"이놈":["korean"],"이달":["korean"],"이대로":["korean"],"이동":["korean"],"이렇게":["korean"],"이력서":["korean"],"이론적":["korean"],"이름":["korean"],"이민":["korean"],"이발소":["korean"],"이별":["korean"],"이불":["korean"],"이빨":["korean"],"이상":["korean"],"이성":["korean"],"이슬":["korean"],"이야기":["korean"],"이용":["korean"],"이웃":["korean"],"이월":["korean"],"이윽고":["korean"],"이익":["korean"],"이전":["korean"],"이중":["korean"],"이튿날":["korean"],"이틀":["korean"],"이혼":["korean"],"인간":["korean"],"인격":["korean"],"인공":["korean"],"인구":["korean"],"인근":["korean"],"인기":["korean"],"인도":["korean"],"인류":["korean"],"인물":["korean"],"인생":["korean"],"인쇄":["korean"],"인연":["korean"],"인원":["korean"],"인재":["korean"],"인종":["korean"],"인천":["korean"],"인체":["korean"],"인터넷":["korean"],"인하":["korean"],"인형":["korean"],"일곱":["korean"],"일기":["korean"],"일단":["korean"],"일대":["korean"],"일등":["korean"],"일반":["korean"],"일본":["korean"],"일부":["korean"],"일상":["korean"],"일생":["korean"],"일손":["korean"],"일요일":["korean"],"일월":["korean"],"일정":["korean"],"일종":["korean"],"일주일":["korean"],"일찍":["korean"],"일체":["korean"],"일치":["korean"],"일행":["korean"],"일회용":["korean"],"임금":["korean"],"임무":["korean"],"입대":["korean"],"입력":["korean"],"입맛":["korean"],"입사":["korean"],"입술":["korean"],"입시":["korean"],"입원":["korean"],"입장":["korean"],"입학":["korean"],"자가용":["korean"],"자격":["korean"],"자극":["korean"],"자동":["korean"],"자랑":["korean"],"자부심":["korean"],"자식":["korean"],"자신":["korean"],"자연":["korean"],"자원":["korean"],"자율":["korean"],"자전거":["korean"],"자정":["korean"],"자존심":["korean"],"자판":["korean"],"작가":["korean"],"작년":["korean"],"작성":["korean"],"작업":["korean"],"작용":["korean"],"작은딸":["korean"],"작품":["korean"],"잔디":["korean"],"잔뜩":["korean"],"잔치":["korean"],"잘못":["korean"],"잠깐":["korean"],"잠수함":["korean"],"잠시":["korean"],"잠옷":["korean"],"잠자리":["korean"],"잡지":["korean"],"장관":["korean"],"장군":["korean"],"장기간":["korean"],"장래":["korean"],"장례":["korean"],"장르":["korean"],"장마":["korean"],"장면":["korean"],"장모":["korean"],"장미":["korean"],"장비":["korean"],"장사":["korean"],"장소":["korean"],"장식":["korean"],"장애인":["korean"],"장인":["korean"],"장점":["korean"],"장차":["korean"],"장학금":["korean"],"재능":["korean"],"재빨리":["korean"],"재산":["korean"],"재생":["korean"],"재작년":["korean"],"재정":["korean"],"재채기":["korean"],"재판":["korean"],"재학":["korean"],"재활용":["korean"],"저것":["korean"],"저고리":["korean"],"저곳":["korean"],"저녁":["korean"],"저런":["korean"],"저렇게":["korean"],"저번":["korean"],"저울":["korean"],"저절로":["korean"],"저축":["korean"],"적극":["korean"],"적당히":["korean"],"적성":["korean"],"적용":["korean"],"적응":["korean"],"전개":["korean"],"전공":["korean"],"전기":["korean"],"전달":["korean"],"전라도":["korean"],"전망":["korean"],"전문":["korean"],"전반":["korean"],"전부":["korean"],"전세":["korean"],"전시":["korean"],"전용":["korean"],"전자":["korean"],"전쟁":["korean"],"전주":["korean"],"전철":["korean"],"전체":["korean"],"전통":["korean"],"전혀":["korean"],"전후":["korean"],"절대":["korean"],"절망":["korean"],"절반":["korean"],"절약":["korean"],"절차":["korean"],"점검":["korean"],"점수":["korean"],"점심":["korean"],"점원":["korean"],"점점":["korean"],"점차":["korean"],"접근":["korean"],"접시":["korean"],"접촉":["korean"],"젓가락":["korean"],"정거장":["korean"],"정도":["korean"],"정류장":["korean"],"정리":["korean"],"정말":["korean"],"정면":["korean"],"정문":["korean"],"정반대":["korean"],"정보":["korean"],"정부":["korean"],"정비":["korean"],"정상":["korean"],"정성":["korean"],"정오":["korean"],"정원":["korean"],"정장":["korean"],"정지":["korean"],"정치":["korean"],"정확히":["korean"],"제공":["korean"],"제과점":["korean"],"제대로":["korean"],"제목":["korean"],"제발":["korean"],"제법":["korean"],"제삿날":["korean"],"제안":["korean"],"제일":["korean"],"제작":["korean"],"제주도":["korean"],"제출":["korean"],"제품":["korean"],"제한":["korean"],"조각":["korean"],"조건":["korean"],"조금":["korean"],"조깅":["korean"],"조명":["korean"],"조미료":["korean"],"조상":["korean"],"조선":["korean"],"조용히":["korean"],"조절":["korean"],"조정":["korean"],"조직":["korean"],"존댓말":["korean"],"존재":["korean"],"졸업":["korean"],"졸음":["korean"],"종교":["korean"],"종로":["korean"],"종류":["korean"],"종소리":["korean"],"종업원":["korean"],"종종":["korean"],"종합":["korean"],"좌석":["korean"],"죄인":["korean"],"주관적":["korean"],"주름":["korean"],"주말":["korean"],"주머니":["korean"],"주먹":["korean"],"주문":["korean"],"주민":["korean"],"주방":["korean"],"주변":["korean"],"주식":["korean"],"주인":["korean"],"주일":["korean"],"주장":["korean"],"주전자":["korean"],"주택":["korean"],"준비":["korean"],"줄거리":["korean"],"줄기":["korean"],"줄무늬":["korean"],"중간":["korean"],"중계방송":["korean"],"중국":["korean"],"중년":["korean"],"중단":["korean"],"중독":["korean"],"중반":["korean"],"중부":["korean"],"중세":["korean"],"중소기업":["korean"],"중순":["korean"],"중앙":["korean"],"중요":["korean"],"중학교":["korean"],"즉석":["korean"],"즉시":["korean"],"즐거움":["korean"],"증가":["korean"],"증거":["korean"],"증권":["korean"],"증상":["korean"],"증세":["korean"],"지각":["korean"],"지갑":["korean"],"지경":["korean"],"지극히":["korean"],"지금":["korean"],"지급":["korean"],"지능":["korean"],"지름길":["korean"],"지리산":["korean"],"지방":["korean"],"지붕":["korean"],"지식":["korean"],"지역":["korean"],"지우개":["korean"],"지원":["korean"],"지적":["korean"],"지점":["korean"],"지진":["korean"],"지출":["korean"],"직선":["korean"],"직업":["korean"],"직원":["korean"],"직장":["korean"],"진급":["korean"],"진동":["korean"],"진로":["korean"],"진료":["korean"],"진리":["korean"],"진짜":["korean"],"진찰":["korean"],"진출":["korean"],"진통":["korean"],"진행":["korean"],"질문":["korean"],"질병":["korean"],"질서":["korean"],"짐작":["korean"],"집단":["korean"],"집안":["korean"],"집중":["korean"],"짜증":["korean"],"찌꺼기":["korean"],"차남":["korean"],"차라리":["korean"],"차량":["korean"],"차림":["korean"],"차별":["korean"],"차선":["korean"],"차츰":["korean"],"착각":["korean"],"찬물":["korean"],"찬성":["korean"],"참가":["korean"],"참기름":["korean"],"참새":["korean"],"참석":["korean"],"참여":["korean"],"참외":["korean"],"참조":["korean"],"찻잔":["korean"],"창가":["korean"],"창고":["korean"],"창구":["korean"],"창문":["korean"],"창밖":["korean"],"창작":["korean"],"창조":["korean"],"채널":["korean"],"채점":["korean"],"책가방":["korean"],"책방":["korean"],"책상":["korean"],"책임":["korean"],"챔피언":["korean"],"처벌":["korean"],"처음":["korean"],"천국":["korean"],"천둥":["korean"],"천장":["korean"],"천재":["korean"],"천천히":["korean"],"철도":["korean"],"철저히":["korean"],"철학":["korean"],"첫날":["korean"],"첫째":["korean"],"청년":["korean"],"청바지":["korean"],"청소":["korean"],"청춘":["korean"],"체계":["korean"],"체력":["korean"],"체온":["korean"],"체육":["korean"],"체중":["korean"],"체험":["korean"],"초등학생":["korean"],"초반":["korean"],"초밥":["korean"],"초상화":["korean"],"초순":["korean"],"초여름":["korean"],"초원":["korean"],"초저녁":["korean"],"초점":["korean"],"초청":["korean"],"초콜릿":["korean"],"촛불":["korean"],"총각":["korean"],"총리":["korean"],"총장":["korean"],"촬영":["korean"],"최근":["korean"],"최상":["korean"],"최선":["korean"],"최신":["korean"],"최악":["korean"],"최종":["korean"],"추석":["korean"],"추억":["korean"],"추진":["korean"],"추천":["korean"],"추측":["korean"],"축구":["korean"],"축소":["korean"],"축제":["korean"],"축하":["korean"],"출근":["korean"],"출발":["korean"],"출산":["korean"],"출신":["korean"],"출연":["korean"],"출입":["korean"],"출장":["korean"],"출판":["korean"],"충격":["korean"],"충고":["korean"],"충돌":["korean"],"충분히":["korean"],"충청도":["korean"],"취업":["korean"],"취직":["korean"],"취향":["korean"],"치약":["korean"],"친구":["korean"],"친척":["korean"],"칠십":["korean"],"칠월":["korean"],"칠판":["korean"],"침대":["korean"],"침묵":["korean"],"침실":["korean"],"칫솔":["korean"],"칭찬":["korean"],"카메라":["korean"],"카운터":["korean"],"칼국수":["korean"],"캐릭터":["korean"],"캠퍼스":["korean"],"캠페인":["korean"],"커튼":["korean"],"컨디션":["korean"],"컬러":["korean"],"컴퓨터":["korean"],"코끼리":["korean"],"코미디":["korean"],"콘서트":["korean"],"콜라":["korean"],"콤플렉스":["korean"],"콩나물":["korean"],"쾌감":["korean"],"쿠데타":["korean"],"크림":["korean"],"큰길":["korean"],"큰딸":["korean"],"큰소리":["korean"],"큰아들":["korean"],"큰어머니":["korean"],"큰일":["korean"],"큰절":["korean"],"클래식":["korean"],"클럽":["korean"],"킬로":["korean"],"타입":["korean"],"타자기":["korean"],"탁구":["korean"],"탁자":["korean"],"탄생":["korean"],"태권도":["korean"],"태양":["korean"],"태풍":["korean"],"택시":["korean"],"탤런트":["korean"],"터널":["korean"],"터미널":["korean"],"테니스":["korean"],"테스트":["korean"],"테이블":["korean"],"텔레비전":["korean"],"토론":["korean"],"토마토":["korean"],"토요일":["korean"],"통계":["korean"],"통과":["korean"],"통로":["korean"],"통신":["korean"],"통역":["korean"],"통일":["korean"],"통장":["korean"],"통제":["korean"],"통증":["korean"],"통합":["korean"],"통화":["korean"],"퇴근":["korean"],"퇴원":["korean"],"퇴직금":["korean"],"튀김":["korean"],"트럭":["korean"],"특급":["korean"],"특별":["korean"],"특성":["korean"],"특수":["korean"],"특징":["korean"],"특히":["korean"],"튼튼히":["korean"],"티셔츠":["korean"],"파란색":["korean"],"파일":["korean"],"파출소":["korean"],"판결":["korean"],"판단":["korean"],"판매":["korean"],"판사":["korean"],"팔십":["korean"],"팔월":["korean"],"팝송":["korean"],"패션":["korean"],"팩스":["korean"],"팩시밀리":["korean"],"팬티":["korean"],"퍼센트":["korean"],"페인트":["korean"],"편견":["korean"],"편의":["korean"],"편지":["korean"],"편히":["korean"],"평가":["korean"],"평균":["korean"],"평생":["korean"],"평소":["korean"],"평양":["korean"],"평일":["korean"],"평화":["korean"],"포스터":["korean"],"포인트":["korean"],"포장":["korean"],"포함":["korean"],"표면":["korean"],"표정":["korean"],"표준":["korean"],"표현":["korean"],"품목":["korean"],"품질":["korean"],"풍경":["korean"],"풍속":["korean"],"풍습":["korean"],"프랑스":["korean"],"프린터":["korean"],"플라스틱":["korean"],"피곤":["korean"],"피망":["korean"],"피아노":["korean"],"필름":["korean"],"필수":["korean"],"필요":["korean"],"필자":["korean"],"필통":["korean"],"핑계":["korean"],"하느님":["korean"],"하늘":["korean"],"하드웨어":["korean"],"하룻밤":["korean"],"하반기":["korean"],"하숙집":["korean"],"하순":["korean"],"하여튼":["korean"],"하지만":["korean"],"하천":["korean"],"하품":["korean"],"하필":["korean"],"학과":["korean"],"학교":["korean"],"학급":["korean"],"학기":["korean"],"학년":["korean"],"학력":["korean"],"학번":["korean"],"학부모":["korean"],"학비":["korean"],"학생":["korean"],"학술":["korean"],"학습":["korean"],"학용품":["korean"],"학원":["korean"],"학위":["korean"],"학자":["korean"],"학점":["korean"],"한계":["korean"],"한글":["korean"],"한꺼번에":["korean"],"한낮":["korean"],"한눈":["korean"],"한동안":["korean"],"한때":["korean"],"한라산":["korean"],"한마디":["korean"],"한문":["korean"],"한번":["korean"],"한복":["korean"],"한식":["korean"],"한여름":["korean"],"한쪽":["korean"],"할머니":["korean"],"할아버지":["korean"],"할인":["korean"],"함께":["korean"],"함부로":["korean"],"합격":["korean"],"합리적":["korean"],"항공":["korean"],"항구":["korean"],"항상":["korean"],"항의":["korean"],"해결":["korean"],"해군":["korean"],"해답":["korean"],"해당":["korean"],"해물":["korean"],"해석":["korean"],"해설":["korean"],"해수욕장":["korean"],"해안":["korean"],"핵심":["korean"],"핸드백":["korean"],"햄버거":["korean"],"햇볕":["korean"],"햇살":["korean"],"행동":["korean"],"행복":["korean"],"행사":["korean"],"행운":["korean"],"행위":["korean"],"향기":["korean"],"향상":["korean"],"향수":["korean"],"허락":["korean"],"허용":["korean"],"헬기":["korean"],"현관":["korean"],"현금":["korean"],"현대":["korean"],"현상":["korean"],"현실":["korean"],"현장":["korean"],"현재":["korean"],"현지":["korean"],"혈액":["korean"],"협력":["korean"],"형부":["korean"],"형사":["korean"],"형수":["korean"],"형식":["korean"],"형제":["korean"],"형태":["korean"],"형편":["korean"],"혜택":["korean"],"호기심":["korean"],"호남":["korean"],"호랑이":["korean"],"호박":["korean"],"호텔":["korean"],"호흡":["korean"],"혹시":["korean"],"홀로":["korean"],"홈페이지":["korean"],"홍보":["korean"],"홍수":["korean"],"홍차":["korean"],"화면":["korean"],"화분":["korean"],"화살":["korean"],"화요일":["korean"],"화장":["korean"],"화학":["korean"],"확보":["korean"],"확인":["korean"],"확장":["korean"],"확정":["korean"],"환갑":["korean"],"환경":["korean"],"환영":["korean"],"환율":["korean"],"환자":["korean"],"활기":["korean"],"활동":["korean"],"활발히":["korean"],"활용":["korean"],"활짝":["korean"],"회견":["korean"],"회관":["korean"],"회복":["korean"],"회색":["korean"],"회원":["korean"],"회장":["korean"],"회전":["korean"],"횟수":["korean"],"횡단보도":["korean"],"효율적":["korean"],"후반":["korean"],"후춧가루":["korean"],"훈련":["korean"],"훨씬":["korean"],"휴식":["korean"],"휴일":["korean"],"흉내":["korean"],"흐름":["korean"],"흑백":["korean"],"흑인":["korean"],"흔적":["korean"],"흔히":["korean"],"흥미":["korean"],"흥분":["korean"],"희곡":["korean"],"희망":["korean"],"희생":["korean"],"흰색":["korean"],"힘껏":["korean"],"abacate":["portuguese"],"abaixo":["portuguese"],"abalar":["portuguese"],"abater":["portuguese"],"abduzir":["portuguese"],"abelha":["portuguese"],"aberto":["portuguese"],"abismo":["portuguese"],"abotoar":["portuguese"],"abranger":["portuguese"],"abreviar":["portuguese"],"abrigar":["portuguese"],"abrupto":["portuguese"],"absinto":["portuguese"],"absoluto":["portuguese"],"absurdo":["portuguese"],"abutre":["portuguese"],"acabado":["portuguese"],"acalmar":["portuguese"],"acampar":["portuguese"],"acanhar":["portuguese"],"acaso":["portuguese"],"aceitar":["portuguese"],"acelerar":["portuguese"],"acenar":["portuguese"],"acervo":["portuguese"],"acessar":["portuguese"],"acetona":["portuguese"],"achatar":["portuguese"],"acidez":["portuguese"],"acima":["portuguese"],"acionado":["portuguese"],"acirrar":["portuguese"],"aclamar":["portuguese"],"aclive":["portuguese"],"acolhida":["portuguese"],"acomodar":["portuguese"],"acoplar":["portuguese"],"acordar":["portuguese"],"acumular":["portuguese"],"acusador":["portuguese"],"adaptar":["portuguese"],"adega":["portuguese"],"adentro":["portuguese"],"adepto":["portuguese"],"adequar":["portuguese"],"aderente":["portuguese"],"adesivo":["portuguese"],"adeus":["portuguese"],"adiante":["portuguese"],"aditivo":["portuguese"],"adjetivo":["portuguese"],"adjunto":["portuguese"],"admirar":["portuguese"],"adorar":["portuguese"],"adquirir":["portuguese"],"adubo":["portuguese"],"adverso":["portuguese"],"advogado":["portuguese"],"aeronave":["portuguese"],"afastar":["portuguese"],"aferir":["portuguese"],"afetivo":["portuguese"],"afinador":["portuguese"],"afivelar":["portuguese"],"aflito":["portuguese"],"afluente":["portuguese"],"afrontar":["portuguese"],"agachar":["portuguese"],"agarrar":["portuguese"],"agasalho":["portuguese"],"agenciar":["portuguese"],"agilizar":["portuguese"],"agiota":["portuguese"],"agitado":["portuguese"],"agora":["portuguese"],"agradar":["portuguese"],"agreste":["portuguese"],"agrupar":["portuguese"],"aguardar":["portuguese"],"agulha":["portuguese"],"ajoelhar":["portuguese"],"ajudar":["portuguese"],"ajustar":["portuguese"],"alameda":["portuguese"],"alarme":["portuguese"],"alastrar":["portuguese"],"alavanca":["portuguese"],"albergue":["portuguese"],"albino":["portuguese"],"alcatra":["portuguese"],"aldeia":["portuguese"],"alecrim":["portuguese"],"alegria":["portuguese"],"alertar":["portuguese"],"alface":["portuguese"],"alfinete":["portuguese"],"algum":["portuguese"],"alheio":["portuguese"],"aliar":["portuguese"],"alicate":["portuguese"],"alienar":["portuguese"],"alinhar":["portuguese"],"aliviar":["portuguese"],"almofada":["portuguese"],"alocar":["portuguese"],"alpiste":["portuguese"],"alterar":["portuguese"],"altitude":["portuguese"],"alucinar":["portuguese"],"alugar":["portuguese"],"aluno":["portuguese"],"alusivo":["portuguese"],"alvo":["portuguese"],"amaciar":["portuguese"],"amador":["portuguese"],"amarelo":["portuguese"],"amassar":["portuguese"],"ambas":["portuguese"],"ambiente":["portuguese"],"ameixa":["portuguese"],"amenizar":["portuguese"],"amido":["portuguese"],"amistoso":["portuguese"],"amizade":["portuguese"],"amolador":["portuguese"],"amontoar":["portuguese"],"amoroso":["portuguese"],"amostra":["portuguese"],"amparar":["portuguese"],"ampliar":["portuguese"],"ampola":["portuguese"],"anagrama":["portuguese"],"analisar":["portuguese"],"anarquia":["portuguese"],"anatomia":["portuguese"],"andaime":["portuguese"],"anel":["portuguese"],"anexo":["portuguese"],"angular":["portuguese"],"animar":["portuguese"],"anjo":["portuguese"],"anomalia":["portuguese"],"anotado":["portuguese"],"ansioso":["portuguese"],"anterior":["portuguese"],"anuidade":["portuguese"],"anunciar":["portuguese"],"anzol":["portuguese"],"apagador":["portuguese"],"apalpar":["portuguese"],"apanhado":["portuguese"],"apego":["portuguese"],"apelido":["portuguese"],"apertada":["portuguese"],"apesar":["portuguese"],"apetite":["portuguese"],"apito":["portuguese"],"aplauso":["portuguese"],"aplicada":["portuguese"],"apoio":["portuguese"],"apontar":["portuguese"],"aposta":["portuguese"],"aprendiz":["portuguese"],"aprovar":["portuguese"],"aquecer":["portuguese"],"arame":["portuguese"],"aranha":["portuguese"],"arara":["portuguese"],"arcada":["portuguese"],"ardente":["portuguese"],"areia":["portuguese"],"arejar":["portuguese"],"arenito":["portuguese"],"aresta":["portuguese"],"argiloso":["portuguese"],"argola":["portuguese"],"arma":["portuguese"],"arquivo":["portuguese"],"arraial":["portuguese"],"arrebate":["portuguese"],"arriscar":["portuguese"],"arroba":["portuguese"],"arrumar":["portuguese"],"arsenal":["portuguese"],"arterial":["portuguese"],"artigo":["portuguese"],"arvoredo":["portuguese"],"asfaltar":["portuguese"],"asilado":["portuguese"],"aspirar":["portuguese"],"assador":["portuguese"],"assinar":["portuguese"],"assoalho":["portuguese"],"assunto":["portuguese"],"astral":["portuguese"],"atacado":["portuguese"],"atadura":["portuguese"],"atalho":["portuguese"],"atarefar":["portuguese"],"atear":["portuguese"],"atender":["portuguese"],"aterro":["portuguese"],"ateu":["portuguese"],"atingir":["portuguese"],"atirador":["portuguese"],"ativo":["portuguese"],"atoleiro":["portuguese"],"atracar":["portuguese"],"atrevido":["portuguese"],"atriz":["portuguese"],"atual":["portuguese"],"atum":["portuguese"],"auditor":["portuguese"],"aumentar":["portuguese"],"aura":["portuguese"],"aurora":["portuguese"],"autismo":["portuguese"],"autoria":["portuguese"],"autuar":["portuguese"],"avaliar":["portuguese"],"avante":["portuguese"],"avaria":["portuguese"],"avental":["portuguese"],"avesso":["portuguese"],"aviador":["portuguese"],"avisar":["portuguese"],"avulso":["portuguese"],"axila":["portuguese"],"azarar":["portuguese"],"azedo":["portuguese"],"azeite":["portuguese"],"azulejo":["portuguese"],"babar":["portuguese"],"babosa":["portuguese"],"bacalhau":["portuguese"],"bacharel":["portuguese"],"bacia":["portuguese"],"bagagem":["portuguese"],"baiano":["portuguese"],"bailar":["portuguese"],"baioneta":["portuguese"],"bairro":["portuguese"],"baixista":["portuguese"],"bajular":["portuguese"],"baleia":["portuguese"],"baliza":["portuguese"],"balsa":["portuguese"],"banal":["portuguese"],"bandeira":["portuguese"],"banho":["portuguese"],"banir":["portuguese"],"banquete":["portuguese"],"barato":["portuguese"],"barbado":["portuguese"],"baronesa":["portuguese"],"barraca":["portuguese"],"barulho":["portuguese"],"baseado":["portuguese"],"bastante":["portuguese"],"batata":["portuguese"],"batedor":["portuguese"],"batida":["portuguese"],"batom":["portuguese"],"batucar":["portuguese"],"baunilha":["portuguese"],"beber":["portuguese"],"beijo":["portuguese"],"beirada":["portuguese"],"beisebol":["portuguese"],"beldade":["portuguese"],"beleza":["portuguese"],"belga":["portuguese"],"beliscar":["portuguese"],"bendito":["portuguese"],"bengala":["portuguese"],"benzer":["portuguese","turkish"],"berimbau":["portuguese"],"berlinda":["portuguese"],"berro":["portuguese"],"besouro":["portuguese"],"bexiga":["portuguese"],"bezerro":["portuguese"],"bico":["portuguese"],"bicudo":["portuguese"],"bienal":["portuguese"],"bifocal":["portuguese"],"bifurcar":["portuguese"],"bigorna":["portuguese"],"bilhete":["portuguese"],"bimestre":["portuguese"],"bimotor":["portuguese"],"biologia":["portuguese"],"biombo":["portuguese"],"biosfera":["portuguese"],"bipolar":["portuguese"],"birrento":["portuguese"],"biscoito":["portuguese"],"bisneto":["portuguese"],"bispo":["portuguese"],"bissexto":["portuguese"],"bitola":["portuguese"],"bizarro":["portuguese"],"blindado":["portuguese"],"bloco":["portuguese"],"bloquear":["portuguese"],"boato":["portuguese"],"bobagem":["portuguese"],"bocado":["portuguese"],"bocejo":["portuguese"],"bochecha":["portuguese"],"boicotar":["portuguese"],"bolada":["portuguese"],"boletim":["portuguese"],"bolha":["portuguese"],"bolo":["portuguese"],"bombeiro":["portuguese"],"bonde":["portuguese"],"boneco":["portuguese"],"bonita":["portuguese"],"borbulha":["portuguese"],"borda":["portuguese"],"boreal":["portuguese"],"borracha":["portuguese"],"bovino":["portuguese"],"boxeador":["portuguese"],"branco":["portuguese"],"brasa":["portuguese"],"braveza":["portuguese"],"breu":["portuguese"],"briga":["portuguese"],"brilho":["portuguese"],"brincar":["portuguese"],"broa":["portuguese"],"brochura":["portuguese"],"bronzear":["portuguese"],"broto":["portuguese"],"bruxo":["portuguese"],"bucha":["portuguese"],"budismo":["portuguese"],"bufar":["portuguese"],"bule":["portuguese"],"buraco":["portuguese"],"busca":["portuguese"],"busto":["portuguese"],"buzina":["portuguese"],"cabana":["portuguese"],"cabelo":["portuguese"],"cabide":["portuguese"],"cabo":["portuguese"],"cabrito":["portuguese"],"cacau":["portuguese"],"cacetada":["portuguese"],"cachorro":["portuguese"],"cacique":["portuguese"],"cadastro":["portuguese"],"cadeado":["portuguese"],"cafezal":["portuguese"],"caiaque":["portuguese"],"caipira":["portuguese"],"caixote":["portuguese"],"cajado":["portuguese"],"caju":["portuguese"],"calafrio":["portuguese"],"calcular":["portuguese"],"caldeira":["portuguese"],"calibrar":["portuguese"],"calmante":["portuguese"],"calota":["portuguese"],"camada":["portuguese"],"cambista":["portuguese"],"camisa":["portuguese"],"camomila":["portuguese"],"campanha":["portuguese"],"camuflar":["portuguese"],"canavial":["portuguese"],"cancelar":["portuguese"],"caneta":["portuguese"],"canguru":["portuguese"],"canhoto":["portuguese"],"canivete":["portuguese"],"canoa":["portuguese"],"cansado":["portuguese"],"cantar":["portuguese"],"canudo":["portuguese"],"capacho":["portuguese"],"capela":["portuguese"],"capinar":["portuguese"],"capotar":["portuguese"],"capricho":["portuguese"],"captador":["portuguese"],"capuz":["portuguese"],"caracol":["portuguese"],"carbono":["portuguese"],"cardeal":["portuguese"],"careca":["portuguese"],"carimbar":["portuguese"],"carneiro":["portuguese"],"carpete":["portuguese"],"carreira":["portuguese"],"cartaz":["portuguese"],"carvalho":["portuguese"],"casaco":["portuguese"],"casca":["portuguese"],"casebre":["portuguese"],"castelo":["portuguese"],"casulo":["portuguese"],"catarata":["portuguese"],"cativar":["portuguese"],"caule":["portuguese"],"causador":["portuguese"],"cautelar":["portuguese"],"cavalo":["portuguese"],"caverna":["portuguese"],"cebola":["portuguese"],"cedilha":["portuguese"],"cegonha":["portuguese"],"celebrar":["portuguese"],"celular":["portuguese"],"cenoura":["portuguese"],"censo":["portuguese"],"centeio":["portuguese"],"cercar":["portuguese"],"cerrado":["portuguese"],"certeiro":["portuguese"],"cerveja":["portuguese"],"cetim":["portuguese"],"cevada":["portuguese"],"chacota":["portuguese"],"chaleira":["portuguese"],"chamado":["portuguese"],"chapada":["portuguese"],"charme":["portuguese"],"chatice":["portuguese"],"chave":["portuguese"],"chefe":["portuguese"],"chegada":["portuguese"],"cheiro":["portuguese"],"cheque":["portuguese"],"chicote":["portuguese"],"chifre":["portuguese"],"chinelo":["portuguese"],"chocalho":["portuguese"],"chover":["portuguese"],"chumbo":["portuguese"],"chutar":["portuguese"],"chuva":["portuguese"],"cicatriz":["portuguese"],"ciclone":["portuguese"],"cidade":["portuguese"],"cidreira":["portuguese"],"ciente":["portuguese"],"cigana":["portuguese"],"cimento":["portuguese"],"cinto":["portuguese"],"cinza":["portuguese"],"ciranda":["portuguese"],"circuito":["portuguese"],"cirurgia":["portuguese"],"citar":["portuguese"],"clareza":["portuguese"],"clero":["portuguese"],"clicar":["portuguese"],"clone":["portuguese"],"clube":["portuguese"],"coado":["portuguese"],"coagir":["portuguese"],"cobaia":["portuguese"],"cobertor":["portuguese"],"cobrar":["portuguese"],"cocada":["portuguese"],"coelho":["portuguese"],"coentro":["portuguese"],"coeso":["portuguese"],"cogumelo":["portuguese"],"coibir":["portuguese"],"coifa":["portuguese"],"coiote":["portuguese"],"colar":["portuguese"],"coleira":["portuguese"],"colher":["portuguese"],"colidir":["portuguese"],"colmeia":["portuguese"],"colono":["portuguese"],"coluna":["portuguese"],"comando":["portuguese"],"combinar":["portuguese"],"comentar":["portuguese"],"comitiva":["portuguese"],"comover":["portuguese"],"complexo":["portuguese"],"comum":["portuguese"],"concha":["portuguese"],"condor":["portuguese"],"conectar":["portuguese"],"confuso":["portuguese"],"congelar":["portuguese"],"conhecer":["portuguese"],"conjugar":["portuguese"],"consumir":["portuguese"],"contrato":["portuguese"],"convite":["portuguese"],"cooperar":["portuguese"],"copeiro":["portuguese"],"copiador":["portuguese"],"copo":["portuguese"],"coquetel":["portuguese"],"coragem":["portuguese"],"cordial":["portuguese"],"corneta":["portuguese"],"coronha":["portuguese"],"corporal":["portuguese"],"correio":["portuguese"],"cortejo":["portuguese"],"coruja":["portuguese"],"corvo":["portuguese"],"cosseno":["portuguese"],"costela":["portuguese"],"cotonete":["portuguese"],"couro":["portuguese"],"couve":["portuguese"],"covil":["portuguese"],"cozinha":["portuguese"],"cratera":["portuguese"],"cravo":["portuguese"],"creche":["portuguese"],"credor":["portuguese"],"creme":["portuguese"],"crer":["portuguese"],"crespo":["portuguese"],"criada":["portuguese"],"criminal":["portuguese"],"crioulo":["portuguese"],"crise":["portuguese"],"criticar":["portuguese"],"crosta":["portuguese"],"crua":["portuguese"],"cruzeiro":["portuguese"],"cubano":["portuguese"],"cueca":["portuguese"],"cuidado":["portuguese"],"cujo":["portuguese"],"culatra":["portuguese"],"culminar":["portuguese"],"culpar":["portuguese"],"cultura":["portuguese"],"cumprir":["portuguese"],"cunhado":["portuguese"],"cupido":["portuguese"],"curativo":["portuguese"],"curral":["portuguese"],"cursar":["portuguese"],"curto":["portuguese"],"cuspir":["portuguese"],"custear":["portuguese"],"cutelo":["portuguese"],"damasco":["portuguese"],"datar":["portuguese"],"debater":["portuguese"],"debitar":["portuguese"],"deboche":["portuguese"],"debulhar":["portuguese"],"decalque":["portuguese"],"decimal":["portuguese"],"declive":["portuguese"],"decote":["portuguese"],"decretar":["portuguese"],"dedal":["portuguese"],"dedicado":["portuguese"],"deduzir":["portuguese"],"defesa":["portuguese"],"defumar":["portuguese"],"degelo":["portuguese"],"degrau":["portuguese"],"degustar":["portuguese"],"deitado":["portuguese"],"deixar":["portuguese"],"delator":["portuguese"],"delegado":["portuguese"],"delinear":["portuguese"],"delonga":["portuguese"],"demanda":["portuguese"],"demitir":["portuguese"],"demolido":["portuguese"],"dentista":["portuguese"],"depenado":["portuguese"],"depilar":["portuguese"],"depois":["portuguese"],"depressa":["portuguese"],"depurar":["portuguese"],"deriva":["portuguese"],"derramar":["portuguese"],"desafio":["portuguese"],"desbotar":["portuguese"],"descanso":["portuguese"],"desenho":["portuguese"],"desfiado":["portuguese"],"desgaste":["portuguese"],"desigual":["portuguese"],"deslize":["portuguese"],"desmamar":["portuguese"],"desova":["portuguese"],"despesa":["portuguese"],"destaque":["portuguese"],"desviar":["portuguese"],"detalhar":["portuguese"],"detentor":["portuguese"],"detonar":["portuguese"],"detrito":["portuguese"],"deusa":["portuguese"],"dever":["portuguese"],"devido":["portuguese"],"devotado":["portuguese"],"dezena":["portuguese"],"diagrama":["portuguese"],"dialeto":["portuguese"],"didata":["portuguese"],"difuso":["portuguese"],"digitar":["portuguese"],"dilatado":["portuguese"],"diluente":["portuguese"],"diminuir":["portuguese"],"dinastia":["portuguese"],"dinheiro":["portuguese"],"diocese":["portuguese"],"direto":["portuguese"],"discreta":["portuguese"],"disfarce":["portuguese"],"disparo":["portuguese"],"disquete":["portuguese"],"dissipar":["portuguese"],"distante":["portuguese"],"ditador":["portuguese"],"diurno":["portuguese"],"diverso":["portuguese"],"divisor":["portuguese"],"divulgar":["portuguese"],"dizer":["portuguese"],"dobrador":["portuguese"],"dolorido":["portuguese"],"domador":["portuguese"],"dominado":["portuguese"],"donativo":["portuguese"],"donzela":["portuguese"],"dormente":["portuguese"],"dorsal":["portuguese"],"dosagem":["portuguese"],"dourado":["portuguese"],"doutor":["portuguese"],"drenagem":["portuguese"],"drible":["portuguese"],"drogaria":["portuguese"],"duelar":["portuguese"],"duende":["portuguese"],"dueto":["portuguese"],"duplo":["portuguese"],"duquesa":["portuguese"],"durante":["portuguese"],"duvidoso":["portuguese"],"eclodir":["portuguese"],"ecoar":["portuguese"],"ecologia":["portuguese"],"edificar":["portuguese"],"edital":["portuguese"],"educado":["portuguese"],"efeito":["portuguese"],"efetivar":["portuguese"],"ejetar":["portuguese"],"elaborar":["portuguese"],"eleger":["portuguese"],"eleitor":["portuguese"],"elenco":["portuguese"],"elevador":["portuguese"],"eliminar":["portuguese"],"elogiar":["portuguese"],"embargo":["portuguese"],"embolado":["portuguese"],"embrulho":["portuguese"],"embutido":["portuguese"],"emenda":["portuguese"],"emergir":["portuguese"],"emissor":["portuguese"],"empatia":["portuguese"],"empenho":["portuguese"],"empinado":["portuguese"],"empolgar":["portuguese"],"emprego":["portuguese"],"empurrar":["portuguese"],"emulador":["portuguese"],"encaixe":["portuguese"],"encenado":["portuguese"],"enchente":["portuguese"],"encontro":["portuguese"],"endeusar":["portuguese"],"endossar":["portuguese"],"enfaixar":["portuguese"],"enfeite":["portuguese"],"enfim":["portuguese"],"engajado":["portuguese"],"engenho":["portuguese"],"englobar":["portuguese"],"engomado":["portuguese"],"engraxar":["portuguese"],"enguia":["portuguese"],"enjoar":["portuguese"],"enlatar":["portuguese"],"enquanto":["portuguese"],"enraizar":["portuguese"],"enrolado":["portuguese"],"enrugar":["portuguese"],"ensaio":["portuguese"],"enseada":["portuguese"],"ensino":["portuguese"],"ensopado":["portuguese"],"entanto":["portuguese"],"enteado":["portuguese"],"entidade":["portuguese"],"entortar":["portuguese"],"entrada":["portuguese"],"entulho":["portuguese"],"envergar":["portuguese"],"enviado":["portuguese"],"envolver":["portuguese"],"enxame":["portuguese"],"enxerto":["portuguese"],"enxofre":["portuguese"],"enxuto":["portuguese"],"epiderme":["portuguese"],"equipar":["portuguese"],"ereto":["portuguese"],"erguido":["portuguese"],"errata":["portuguese"],"erva":["portuguese"],"ervilha":["portuguese"],"esbanjar":["portuguese"],"esbelto":["portuguese"],"escama":["portuguese"],"escola":["portuguese"],"escrita":["portuguese"],"escuta":["portuguese"],"esfinge":["portuguese"],"esfolar":["portuguese"],"esfregar":["portuguese"],"esfumado":["portuguese"],"esgrima":["portuguese"],"esmalte":["portuguese"],"espanto":["portuguese"],"espelho":["portuguese"],"espiga":["portuguese"],"esponja":["portuguese"],"espreita":["portuguese"],"espumar":["portuguese"],"esquerda":["portuguese"],"estaca":["portuguese"],"esteira":["portuguese"],"esticar":["portuguese"],"estofado":["portuguese"],"estrela":["portuguese"],"estudo":["portuguese"],"esvaziar":["portuguese"],"etanol":["portuguese"],"etiqueta":["portuguese"],"euforia":["portuguese"],"europeu":["portuguese"],"evacuar":["portuguese"],"evaporar":["portuguese"],"evasivo":["portuguese"],"eventual":["portuguese"],"evidente":["portuguese"],"evoluir":["portuguese"],"exagero":["portuguese"],"exalar":["portuguese"],"examinar":["portuguese"],"exato":["portuguese"],"exausto":["portuguese"],"excesso":["portuguese"],"excitar":["portuguese"],"exclamar":["portuguese"],"executar":["portuguese"],"exemplo":["portuguese"],"exibir":["portuguese"],"exigente":["portuguese"],"exonerar":["portuguese"],"expandir":["portuguese"],"expelir":["portuguese"],"expirar":["portuguese"],"explanar":["portuguese"],"exposto":["portuguese"],"expresso":["portuguese"],"expulsar":["portuguese"],"externo":["portuguese"],"extinto":["portuguese"],"extrato":["portuguese"],"fabricar":["portuguese"],"fabuloso":["portuguese"],"faceta":["portuguese"],"facial":["portuguese"],"fada":["portuguese"],"fadiga":["portuguese"],"faixa":["portuguese"],"falar":["portuguese"],"falta":["portuguese"],"familiar":["portuguese"],"fandango":["portuguese"],"fanfarra":["portuguese"],"fantoche":["portuguese"],"fardado":["portuguese"],"farelo":["portuguese"],"farinha":["portuguese"],"farofa":["portuguese"],"farpa":["portuguese"],"fartura":["portuguese"],"fatia":["portuguese"],"fator":["portuguese"],"favorita":["portuguese"],"faxina":["portuguese"],"fazenda":["portuguese"],"fechado":["portuguese"],"feijoada":["portuguese"],"feirante":["portuguese"],"felino":["portuguese"],"feminino":["portuguese"],"fenda":["portuguese"],"feno":["portuguese"],"fera":["portuguese"],"feriado":["portuguese"],"ferrugem":["portuguese"],"ferver":["portuguese"],"festejar":["portuguese"],"fetal":["portuguese"],"feudal":["portuguese"],"fiapo":["portuguese"],"fibrose":["portuguese"],"ficar":["portuguese"],"ficheiro":["portuguese"],"figurado":["portuguese"],"fileira":["portuguese"],"filho":["portuguese"],"filme":["portuguese"],"filtrar":["portuguese"],"firmeza":["portuguese"],"fisgada":["portuguese"],"fissura":["portuguese"],"fita":["portuguese"],"fivela":["portuguese"],"fixador":["portuguese"],"fixo":["portuguese"],"flacidez":["portuguese"],"flamingo":["portuguese"],"flanela":["portuguese"],"flechada":["portuguese"],"flora":["portuguese"],"flutuar":["portuguese"],"fluxo":["portuguese"],"focal":["portuguese"],"focinho":["portuguese"],"fofocar":["portuguese"],"fogo":["portuguese"],"foguete":["portuguese"],"foice":["portuguese"],"folgado":["portuguese"],"folheto":["portuguese"],"forjar":["portuguese"],"formiga":["portuguese"],"forno":["portuguese"],"forte":["portuguese"],"fosco":["portuguese"],"fossa":["portuguese"],"fragata":["portuguese"],"fralda":["portuguese"],"frango":["portuguese"],"frasco":["portuguese"],"fraterno":["portuguese"],"freira":["portuguese"],"frente":["portuguese"],"fretar":["portuguese"],"frieza":["portuguese"],"friso":["portuguese"],"fritura":["portuguese"],"fronha":["portuguese"],"frustrar":["portuguese"],"fruteira":["portuguese"],"fugir":["portuguese"],"fulano":["portuguese"],"fuligem":["portuguese"],"fundar":["portuguese"],"fungo":["portuguese"],"funil":["portuguese"],"furador":["portuguese"],"furioso":["portuguese"],"futebol":["portuguese"],"gabarito":["portuguese"],"gabinete":["portuguese"],"gado":["portuguese"],"gaiato":["portuguese"],"gaiola":["portuguese"],"gaivota":["portuguese"],"galega":["portuguese"],"galho":["portuguese"],"galinha":["portuguese"],"galocha":["portuguese"],"ganhar":["portuguese"],"garagem":["portuguese"],"garfo":["portuguese"],"gargalo":["portuguese"],"garimpo":["portuguese"],"garoupa":["portuguese"],"garrafa":["portuguese"],"gasoduto":["portuguese"],"gasto":["portuguese"],"gata":["portuguese"],"gatilho":["portuguese"],"gaveta":["portuguese"],"gazela":["portuguese"],"gelado":["portuguese"],"geleia":["portuguese"],"gelo":["portuguese"],"gemada":["portuguese"],"gemer":["portuguese"],"gemido":["portuguese"],"generoso":["portuguese"],"gengiva":["portuguese"],"genial":["portuguese"],"genoma":["portuguese"],"genro":["portuguese"],"geologia":["portuguese"],"gerador":["portuguese"],"germinar":["portuguese"],"gesso":["portuguese"],"gestor":["portuguese"],"ginasta":["portuguese"],"gincana":["portuguese"],"gingado":["portuguese"],"girafa":["portuguese"],"girino":["portuguese"],"glacial":["portuguese"],"glicose":["portuguese"],"global":["portuguese"],"glorioso":["portuguese"],"goela":["portuguese"],"goiaba":["portuguese"],"golfe":["portuguese"],"golpear":["portuguese"],"gordura":["portuguese"],"gorjeta":["portuguese"],"gorro":["portuguese"],"gostoso":["portuguese"],"goteira":["portuguese"],"governar":["portuguese"],"gracejo":["portuguese"],"gradual":["portuguese"],"grafite":["portuguese"],"gralha":["portuguese"],"grampo":["portuguese"],"granada":["portuguese"],"gratuito":["portuguese"],"graveto":["portuguese"],"graxa":["portuguese"],"grego":["portuguese"],"grelhar":["portuguese"],"greve":["portuguese"],"grilo":["portuguese"],"grisalho":["portuguese"],"gritaria":["portuguese"],"grosso":["portuguese"],"grotesco":["portuguese"],"grudado":["portuguese"],"grunhido":["portuguese"],"gruta":["portuguese"],"guache":["portuguese"],"guarani":["portuguese"],"guaxinim":["portuguese"],"guerrear":["portuguese"],"guiar":["portuguese"],"guincho":["portuguese"],"guisado":["portuguese"],"gula":["portuguese"],"guloso":["portuguese"],"guru":["portuguese"],"habitar":["portuguese"],"harmonia":["portuguese"],"haste":["portuguese"],"haver":["portuguese"],"hectare":["portuguese"],"herdar":["portuguese"],"heresia":["portuguese"],"hesitar":["portuguese"],"hiato":["portuguese"],"hibernar":["portuguese"],"hidratar":["portuguese"],"hiena":["portuguese"],"hino":["portuguese"],"hipismo":["portuguese"],"hipnose":["portuguese"],"hipoteca":["portuguese"],"hoje":["portuguese"],"holofote":["portuguese"],"homem":["portuguese"],"honesto":["portuguese"],"honrado":["portuguese"],"hormonal":["portuguese"],"hospedar":["portuguese"],"humorado":["portuguese"],"iate":["portuguese"],"ideia":["portuguese"],"idoso":["portuguese"],"ignorado":["portuguese"],"igreja":["portuguese"],"iguana":["portuguese"],"ileso":["portuguese"],"ilha":["portuguese"],"iludido":["portuguese"],"iluminar":["portuguese"],"ilustrar":["portuguese"],"imagem":["portuguese"],"imediato":["portuguese"],"imenso":["portuguese"],"imersivo":["portuguese"],"iminente":["portuguese"],"imitador":["portuguese"],"imortal":["portuguese"],"impacto":["portuguese"],"impedir":["portuguese"],"implante":["portuguese"],"impor":["portuguese"],"imprensa":["portuguese"],"impune":["portuguese"],"imunizar":["portuguese"],"inalador":["portuguese"],"inapto":["portuguese"],"inativo":["portuguese"],"incenso":["portuguese"],"inchar":["portuguese"],"incidir":["portuguese"],"incluir":["portuguese"],"incolor":["portuguese"],"indeciso":["portuguese"],"indireto":["portuguese"],"indutor":["portuguese"],"ineficaz":["portuguese"],"inerente":["portuguese"],"infantil":["portuguese"],"infestar":["portuguese"],"infinito":["portuguese"],"inflamar":["portuguese"],"informal":["portuguese"],"infrator":["portuguese"],"ingerir":["portuguese"],"inibido":["portuguese"],"inicial":["portuguese"],"inimigo":["portuguese"],"injetar":["portuguese"],"inocente":["portuguese"],"inodoro":["portuguese"],"inovador":["portuguese"],"inox":["portuguese"],"inquieto":["portuguese"],"inscrito":["portuguese"],"inseto":["portuguese"],"insistir":["portuguese"],"inspetor":["portuguese"],"instalar":["portuguese"],"insulto":["portuguese"],"intacto":["portuguese"],"integral":["portuguese"],"intimar":["portuguese"],"intocado":["portuguese"],"intriga":["portuguese"],"invasor":["portuguese"],"inverno":["portuguese"],"invicto":["portuguese"],"invocar":["portuguese"],"iogurte":["portuguese"],"iraniano":["portuguese"],"ironizar":["portuguese"],"irreal":["portuguese"],"irritado":["portuguese"],"isca":["portuguese"],"isento":["portuguese"],"isolado":["portuguese"],"isqueiro":["portuguese"],"italiano":["portuguese"],"janeiro":["portuguese"],"jangada":["portuguese"],"janta":["portuguese"],"jararaca":["portuguese"],"jardim":["portuguese"],"jarro":["portuguese"],"jasmim":["portuguese"],"jato":["portuguese"],"javali":["portuguese"],"jazida":["portuguese"],"jejum":["portuguese"],"joaninha":["portuguese"],"joelhada":["portuguese"],"jogador":["portuguese"],"joia":["portuguese"],"jornal":["portuguese"],"jorrar":["portuguese"],"jovem":["portuguese"],"juba":["portuguese"],"judeu":["portuguese"],"judoca":["portuguese"],"juiz":["portuguese"],"julgador":["portuguese"],"julho":["portuguese"],"jurado":["portuguese"],"jurista":["portuguese"],"juro":["portuguese"],"justa":["portuguese"],"labareda":["portuguese"],"laboral":["portuguese"],"lacre":["portuguese"],"lactante":["portuguese"],"ladrilho":["portuguese"],"lagarta":["portuguese"],"lagoa":["portuguese"],"laje":["portuguese"],"lamber":["portuguese"],"lamentar":["portuguese"],"laminar":["portuguese"],"lampejo":["portuguese"],"lanche":["portuguese"],"lapidar":["portuguese"],"lapso":["portuguese"],"laranja":["portuguese"],"lareira":["portuguese"],"largura":["portuguese"],"lasanha":["portuguese"],"lastro":["portuguese"],"lateral":["portuguese"],"latido":["portuguese"],"lavanda":["portuguese"],"lavoura":["portuguese"],"lavrador":["portuguese"],"laxante":["portuguese"],"lazer":["portuguese"],"lealdade":["portuguese"],"lebre":["portuguese"],"legado":["portuguese"],"legendar":["portuguese"],"legista":["portuguese"],"leigo":["portuguese"],"leiloar":["portuguese"],"leitura":["portuguese"],"lembrete":["portuguese"],"leme":["portuguese"],"lenhador":["portuguese"],"lentilha":["portuguese"],"leoa":["portuguese"],"lesma":["portuguese"],"leste":["portuguese"],"letivo":["portuguese"],"letreiro":["portuguese"],"levar":["portuguese"],"leveza":["portuguese"],"levitar":["portuguese"],"liberal":["portuguese"],"libido":["portuguese"],"liderar":["portuguese"],"ligar":["portuguese"],"ligeiro":["portuguese"],"limitar":["portuguese"],"limoeiro":["portuguese"],"limpador":["portuguese"],"linda":["portuguese"],"linear":["portuguese"],"linhagem":["portuguese"],"liquidez":["portuguese"],"listagem":["portuguese"],"lisura":["portuguese"],"litoral":["portuguese"],"livro":["portuguese"],"lixa":["portuguese"],"lixeira":["portuguese"],"locador":["portuguese"],"locutor":["portuguese"],"lojista":["portuguese"],"lombo":["portuguese"],"lona":["portuguese"],"longe":["portuguese"],"lontra":["portuguese"],"lorde":["portuguese"],"lotado":["portuguese"],"loteria":["portuguese"],"loucura":["portuguese"],"lousa":["portuguese"],"louvar":["portuguese"],"luar":["portuguese"],"lucidez":["portuguese"],"lucro":["portuguese"],"luneta":["portuguese"],"lustre":["portuguese"],"lutador":["portuguese"],"luva":["portuguese"],"macaco":["portuguese"],"macete":["portuguese"],"machado":["portuguese"],"macio":["portuguese"],"madeira":["portuguese"],"madrinha":["portuguese"],"magnata":["portuguese"],"magreza":["portuguese"],"maior":["portuguese"],"mais":["portuguese"],"malandro":["portuguese"],"malha":["portuguese"],"malote":["portuguese"],"maluco":["portuguese"],"mamilo":["portuguese"],"mamoeiro":["portuguese"],"mamute":["portuguese"],"manada":["portuguese"],"mancha":["portuguese"],"mandato":["portuguese"],"manequim":["portuguese"],"manhoso":["portuguese"],"manivela":["portuguese"],"manobrar":["portuguese"],"mansa":["portuguese"],"manter":["portuguese"],"manusear":["portuguese"],"mapeado":["portuguese"],"maquinar":["portuguese"],"marcador":["portuguese"],"maresia":["portuguese"],"marfim":["portuguese"],"margem":["portuguese"],"marinho":["portuguese"],"marmita":["portuguese"],"maroto":["portuguese"],"marquise":["portuguese"],"marreco":["portuguese"],"martelo":["portuguese"],"marujo":["portuguese"],"mascote":["portuguese"],"masmorra":["portuguese"],"massagem":["portuguese"],"mastigar":["portuguese"],"matagal":["portuguese"],"materno":["portuguese"],"matinal":["portuguese"],"matutar":["portuguese"],"maxilar":["portuguese"],"medalha":["portuguese"],"medida":["portuguese"],"medusa":["portuguese"],"megafone":["portuguese"],"meiga":["portuguese"],"melancia":["portuguese"],"melhor":["portuguese"],"membro":["portuguese"],"memorial":["portuguese"],"menino":["portuguese"],"menos":["portuguese"],"mensagem":["portuguese"],"mental":["portuguese"],"merecer":["portuguese"],"mergulho":["portuguese"],"mesada":["portuguese"],"mesclar":["portuguese"],"mesmo":["portuguese"],"mesquita":["portuguese"],"mestre":["portuguese"],"metade":["portuguese"],"meteoro":["portuguese"],"metragem":["portuguese"],"mexer":["portuguese"],"mexicano":["portuguese"],"micro":["portuguese"],"migalha":["portuguese"],"migrar":["portuguese"],"milagre":["portuguese"],"milenar":["portuguese"],"milhar":["portuguese"],"mimado":["portuguese"],"minerar":["portuguese"],"minhoca":["portuguese"],"ministro":["portuguese"],"minoria":["portuguese"],"miolo":["portuguese"],"mirante":["portuguese"],"mirtilo":["portuguese"],"misturar":["portuguese"],"mocidade":["portuguese"],"moderno":["portuguese"],"modular":["portuguese"],"moeda":["portuguese"],"moer":["portuguese"],"moinho":["portuguese"],"moita":["portuguese"],"moldura":["portuguese"],"moleza":["portuguese"],"molho":["portuguese"],"molinete":["portuguese"],"molusco":["portuguese"],"montanha":["portuguese"],"moqueca":["portuguese"],"morango":["portuguese"],"morcego":["portuguese"],"mordomo":["portuguese"],"morena":["portuguese"],"mosaico":["portuguese"],"mosquete":["portuguese"],"mostarda":["portuguese"],"motel":["portuguese"],"motim":["portuguese"],"moto":["portuguese"],"motriz":["portuguese"],"muda":["portuguese"],"muito":["portuguese"],"mulata":["portuguese"],"mulher":["portuguese"],"multar":["portuguese"],"mundial":["portuguese"],"munido":["portuguese"],"muralha":["portuguese"],"murcho":["portuguese"],"muscular":["portuguese"],"museu":["portuguese"],"musical":["portuguese"],"nacional":["portuguese"],"nadador":["portuguese"],"naja":["portuguese"],"namoro":["portuguese"],"narina":["portuguese"],"narrado":["portuguese"],"nascer":["portuguese"],"nativa":["portuguese"],"natureza":["portuguese"],"navalha":["portuguese"],"navegar":["portuguese"],"navio":["portuguese"],"neblina":["portuguese"],"nebuloso":["portuguese"],"negativa":["portuguese"],"negociar":["portuguese"],"negrito":["portuguese"],"nervoso":["portuguese"],"neta":["portuguese"],"neural":["portuguese"],"nevasca":["portuguese"],"nevoeiro":["portuguese"],"ninar":["portuguese"],"ninho":["portuguese"],"nitidez":["portuguese"],"nivelar":["portuguese"],"nobreza":["portuguese"],"noite":["portuguese"],"noiva":["portuguese"],"nomear":["portuguese"],"nominal":["portuguese"],"nordeste":["portuguese"],"nortear":["portuguese"],"notar":["portuguese"],"noticiar":["portuguese"],"noturno":["portuguese"],"novelo":["portuguese"],"novilho":["portuguese"],"novo":["portuguese"],"nublado":["portuguese"],"nudez":["portuguese"],"numeral":["portuguese"],"nupcial":["portuguese"],"nutrir":["portuguese"],"nuvem":["portuguese"],"obcecado":["portuguese"],"obedecer":["portuguese"],"objetivo":["portuguese"],"obrigado":["portuguese"],"obscuro":["portuguese"],"obstetra":["portuguese"],"obter":["portuguese"],"obturar":["portuguese"],"ocidente":["portuguese"],"ocioso":["portuguese"],"ocorrer":["portuguese"],"oculista":["portuguese"],"ocupado":["portuguese"],"ofegante":["portuguese"],"ofensiva":["portuguese"],"oferenda":["portuguese"],"oficina":["portuguese"],"ofuscado":["portuguese"],"ogiva":["portuguese"],"olaria":["portuguese"],"oleoso":["portuguese"],"olhar":["portuguese"],"oliveira":["portuguese"],"ombro":["portuguese"],"omelete":["portuguese"],"omisso":["portuguese"],"omitir":["portuguese"],"ondulado":["portuguese"],"oneroso":["portuguese"],"ontem":["portuguese"],"opcional":["portuguese"],"operador":["portuguese"],"oponente":["portuguese"],"oportuno":["portuguese"],"oposto":["portuguese"],"orar":["portuguese"],"orbitar":["portuguese"],"ordem":["portuguese"],"ordinal":["portuguese"],"orfanato":["portuguese"],"orgasmo":["portuguese"],"orgulho":["portuguese"],"oriental":["portuguese"],"origem":["portuguese"],"oriundo":["portuguese"],"orla":["portuguese"],"ortodoxo":["portuguese"],"orvalho":["portuguese"],"oscilar":["portuguese"],"ossada":["portuguese"],"osso":["portuguese"],"ostentar":["portuguese"],"otimismo":["portuguese"],"ousadia":["portuguese"],"outono":["portuguese"],"outubro":["portuguese"],"ouvido":["portuguese"],"ovelha":["portuguese"],"ovular":["portuguese"],"oxidar":["portuguese"],"oxigenar":["portuguese"],"pacato":["portuguese"],"paciente":["portuguese"],"pacote":["portuguese"],"pactuar":["portuguese"],"padaria":["portuguese"],"padrinho":["portuguese"],"pagar":["portuguese"],"pagode":["portuguese"],"painel":["portuguese"],"pairar":["portuguese"],"paisagem":["portuguese"],"palavra":["portuguese"],"palestra":["portuguese"],"palheta":["portuguese"],"palito":["portuguese"],"palmada":["portuguese"],"palpitar":["portuguese"],"pancada":["portuguese"],"panela":["portuguese"],"panfleto":["portuguese"],"panqueca":["portuguese"],"pantanal":["portuguese"],"papagaio":["portuguese"],"papelada":["portuguese"],"papiro":["portuguese"],"parafina":["portuguese"],"parcial":["portuguese"],"pardal":["portuguese"],"parede":["portuguese"],"partida":["portuguese"],"pasmo":["portuguese"],"passado":["portuguese"],"pastel":["portuguese"],"patamar":["portuguese"],"patente":["portuguese"],"patinar":["portuguese"],"patrono":["portuguese"],"paulada":["portuguese"],"pausar":["portuguese"],"peculiar":["portuguese"],"pedalar":["portuguese"],"pedestre":["portuguese"],"pediatra":["portuguese"],"pedra":["portuguese"],"pegada":["portuguese"],"peitoral":["portuguese"],"peixe":["portuguese"],"pele":["portuguese"],"pelicano":["portuguese"],"penca":["portuguese"],"pendurar":["portuguese"],"peneira":["portuguese"],"penhasco":["portuguese"],"pensador":["portuguese"],"pente":["portuguese"],"perceber":["portuguese"],"perfeito":["portuguese"],"pergunta":["portuguese"],"perito":["portuguese"],"permitir":["portuguese"],"perna":["portuguese"],"perplexo":["portuguese"],"persiana":["portuguese"],"pertence":["portuguese"],"peruca":["portuguese"],"pescado":["portuguese"],"pesquisa":["portuguese"],"pessoa":["portuguese"],"petiscar":["portuguese"],"piada":["portuguese"],"picado":["portuguese"],"piedade":["portuguese"],"pigmento":["portuguese"],"pilastra":["portuguese"],"pilhado":["portuguese"],"pilotar":["portuguese"],"pimenta":["portuguese"],"pincel":["portuguese"],"pinguim":["portuguese"],"pinha":["portuguese"],"pinote":["portuguese"],"pintar":["portuguese"],"pioneiro":["portuguese"],"pipoca":["portuguese"],"piquete":["portuguese"],"piranha":["portuguese"],"pires":["portuguese"],"pirueta":["portuguese"],"piscar":["portuguese"],"pistola":["portuguese"],"pitanga":["portuguese"],"pivete":["portuguese"],"planta":["portuguese"],"plaqueta":["portuguese"],"platina":["portuguese"],"plebeu":["portuguese"],"plumagem":["portuguese"],"pluvial":["portuguese"],"pneu":["portuguese"],"poda":["portuguese"],"poeira":["portuguese"],"poetisa":["portuguese"],"polegada":["portuguese"],"policiar":["portuguese"],"poluente":["portuguese"],"polvilho":["portuguese"],"pomar":["portuguese"],"pomba":["portuguese"],"ponderar":["portuguese"],"pontaria":["portuguese"],"populoso":["portuguese"],"porta":["portuguese"],"possuir":["portuguese"],"postal":["portuguese"],"pote":["portuguese"],"poupar":["portuguese"],"pouso":["portuguese"],"povoar":["portuguese"],"praia":["portuguese"],"prancha":["portuguese"],"prato":["portuguese"],"praxe":["portuguese"],"prece":["portuguese"],"predador":["portuguese"],"prefeito":["portuguese"],"premiar":["portuguese"],"prensar":["portuguese"],"preparar":["portuguese"],"presilha":["portuguese"],"pretexto":["portuguese"],"prevenir":["portuguese"],"prezar":["portuguese"],"primata":["portuguese"],"princesa":["portuguese"],"prisma":["portuguese"],"privado":["portuguese"],"processo":["portuguese"],"produto":["portuguese"],"profeta":["portuguese"],"proibido":["portuguese"],"projeto":["portuguese"],"prometer":["portuguese"],"propagar":["portuguese"],"prosa":["portuguese"],"protetor":["portuguese"],"provador":["portuguese"],"publicar":["portuguese"],"pudim":["portuguese"],"pular":["portuguese"],"pulmonar":["portuguese"],"pulseira":["portuguese"],"punhal":["portuguese"],"punir":["portuguese"],"pupilo":["portuguese"],"pureza":["portuguese"],"puxador":["portuguese"],"quadra":["portuguese"],"quantia":["portuguese"],"quarto":["portuguese"],"quase":["portuguese"],"quebrar":["portuguese"],"queda":["portuguese"],"queijo":["portuguese"],"quente":["portuguese"],"querido":["portuguese"],"quimono":["portuguese"],"quina":["portuguese"],"quiosque":["portuguese"],"rabanada":["portuguese"],"rabisco":["portuguese"],"rachar":["portuguese"],"racionar":["portuguese"],"radial":["portuguese"],"raiar":["portuguese"],"rainha":["portuguese"],"raio":["portuguese"],"raiva":["portuguese"],"rajada":["portuguese"],"ralado":["portuguese"],"ramal":["portuguese"],"ranger":["portuguese"],"ranhura":["portuguese"],"rapadura":["portuguese"],"rapel":["portuguese"],"rapidez":["portuguese"],"raposa":["portuguese"],"raquete":["portuguese"],"raridade":["portuguese"],"rasante":["portuguese"],"rascunho":["portuguese"],"rasgar":["portuguese"],"raspador":["portuguese"],"rasteira":["portuguese"],"rasurar":["portuguese"],"ratazana":["portuguese"],"ratoeira":["portuguese"],"realeza":["portuguese"],"reanimar":["portuguese"],"reaver":["portuguese"],"rebaixar":["portuguese"],"rebelde":["portuguese"],"rebolar":["portuguese"],"recado":["portuguese"],"recente":["portuguese"],"recheio":["portuguese"],"recibo":["portuguese"],"recordar":["portuguese"],"recrutar":["portuguese"],"recuar":["portuguese"],"rede":["portuguese"],"redimir":["portuguese"],"redonda":["portuguese"],"reduzida":["portuguese"],"reenvio":["portuguese"],"refinar":["portuguese"],"refletir":["portuguese"],"refogar":["portuguese"],"refresco":["portuguese"],"refugiar":["portuguese"],"regalia":["portuguese"],"regime":["portuguese"],"regra":["portuguese"],"reinado":["portuguese"],"reitor":["portuguese"],"rejeitar":["portuguese"],"relativo":["portuguese"],"remador":["portuguese"],"remendo":["portuguese"],"remorso":["portuguese"],"renovado":["portuguese"],"reparo":["portuguese"],"repelir":["portuguese"],"repleto":["portuguese"],"repolho":["portuguese"],"represa":["portuguese"],"repudiar":["portuguese"],"requerer":["portuguese"],"resenha":["portuguese"],"resfriar":["portuguese"],"resgatar":["portuguese"],"residir":["portuguese"],"resolver":["portuguese"],"respeito":["portuguese"],"ressaca":["portuguese"],"restante":["portuguese"],"resumir":["portuguese"],"retalho":["portuguese"],"reter":["portuguese"],"retirar":["portuguese"],"retomada":["portuguese"],"retratar":["portuguese"],"revelar":["portuguese"],"revisor":["portuguese"],"revolta":["portuguese"],"riacho":["portuguese"],"rica":["portuguese"],"rigidez":["portuguese"],"rigoroso":["portuguese"],"rimar":["portuguese"],"ringue":["portuguese"],"risada":["portuguese"],"risco":["portuguese"],"risonho":["portuguese"],"robalo":["portuguese"],"rochedo":["portuguese"],"rodada":["portuguese"],"rodeio":["portuguese"],"rodovia":["portuguese"],"roedor":["portuguese"],"roleta":["portuguese"],"romano":["portuguese"],"roncar":["portuguese"],"rosado":["portuguese"],"roseira":["portuguese"],"rosto":["portuguese"],"rota":["portuguese","turkish"],"roteiro":["portuguese"],"rotina":["portuguese"],"rotular":["portuguese"],"rouco":["portuguese"],"roupa":["portuguese"],"roxo":["portuguese"],"rubro":["portuguese"],"rugido":["portuguese"],"rugoso":["portuguese"],"ruivo":["portuguese"],"rumo":["portuguese"],"rupestre":["portuguese"],"russo":["portuguese"],"sabor":["portuguese"],"saciar":["portuguese"],"sacola":["portuguese"],"sacudir":["portuguese"],"sadio":["portuguese"],"safira":["portuguese"],"saga":["portuguese"],"sagrada":["portuguese"],"saibro":["portuguese"],"salada":["portuguese"],"saleiro":["portuguese"],"salgado":["portuguese"],"saliva":["portuguese"],"salpicar":["portuguese"],"salsicha":["portuguese"],"saltar":["portuguese"],"salvador":["portuguese"],"sambar":["portuguese"],"samurai":["portuguese"],"sanar":["portuguese"],"sanfona":["portuguese"],"sangue":["portuguese"],"sanidade":["portuguese"],"sapato":["portuguese"],"sarda":["portuguese"],"sargento":["portuguese"],"sarjeta":["portuguese"],"saturar":["portuguese"],"saudade":["portuguese"],"saxofone":["portuguese"],"sazonal":["portuguese"],"secar":["portuguese"],"secular":["portuguese"],"seda":["portuguese","turkish"],"sedento":["portuguese"],"sediado":["portuguese"],"sedoso":["portuguese"],"sedutor":["portuguese"],"segmento":["portuguese"],"segredo":["portuguese"],"segundo":["portuguese"],"seiva":["portuguese"],"seleto":["portuguese"],"selvagem":["portuguese"],"semanal":["portuguese"],"semente":["portuguese"],"senador":["portuguese"],"senhor":["portuguese"],"sensual":["portuguese"],"sentado":["portuguese"],"separado":["portuguese"],"sereia":["portuguese"],"seringa":["portuguese"],"serra":["portuguese"],"servo":["portuguese"],"setembro":["portuguese"],"setor":["portuguese"],"sigilo":["portuguese"],"silhueta":["portuguese"],"silicone":["portuguese"],"simetria":["portuguese"],"simpatia":["portuguese"],"simular":["portuguese"],"sinal":["portuguese"],"sincero":["portuguese"],"singular":["portuguese"],"sinopse":["portuguese"],"sintonia":["portuguese"],"sirene":["portuguese"],"siri":["portuguese"],"situado":["portuguese"],"soberano":["portuguese"],"sobra":["portuguese"],"socorro":["portuguese"],"sogro":["portuguese"],"soja":["portuguese"],"solda":["portuguese"],"soletrar":["portuguese"],"solteiro":["portuguese"],"sombrio":["portuguese"],"sonata":["portuguese"],"sondar":["portuguese"],"sonegar":["portuguese"],"sonhador":["portuguese"],"sono":["portuguese"],"soprano":["portuguese"],"soquete":["portuguese"],"sorrir":["portuguese"],"sorteio":["portuguese"],"sossego":["portuguese"],"sotaque":["portuguese"],"soterrar":["portuguese"],"sovado":["portuguese"],"sozinho":["portuguese"],"suavizar":["portuguese"],"subida":["portuguese"],"submerso":["portuguese"],"subsolo":["portuguese"],"subtrair":["portuguese"],"sucata":["portuguese"],"sucesso":["portuguese"],"suco":["portuguese"],"sudeste":["portuguese"],"sufixo":["portuguese"],"sugador":["portuguese"],"sugerir":["portuguese"],"sujeito":["portuguese"],"sulfato":["portuguese"],"sumir":["portuguese"],"suor":["portuguese"],"superior":["portuguese"],"suplicar":["portuguese"],"suposto":["portuguese"],"suprimir":["portuguese"],"surdina":["portuguese"],"surfista":["portuguese"],"surpresa":["portuguese"],"surreal":["portuguese"],"surtir":["portuguese"],"suspiro":["portuguese"],"sustento":["portuguese"],"tabela":["portuguese","turkish"],"tablete":["portuguese"],"tabuada":["portuguese"],"tacho":["portuguese"],"tagarela":["portuguese"],"talher":["portuguese"],"talo":["portuguese"],"talvez":["portuguese"],"tamanho":["portuguese"],"tamborim":["portuguese"],"tampa":["portuguese"],"tangente":["portuguese"],"tanto":["portuguese"],"tapar":["portuguese"],"tapioca":["portuguese"],"tardio":["portuguese"],"tarefa":["portuguese"],"tarja":["portuguese"],"tarraxa":["portuguese"],"tatuagem":["portuguese"],"taurino":["portuguese"],"taxativo":["portuguese"],"taxista":["portuguese"],"teatral":["portuguese"],"tecer":["portuguese"],"tecido":["portuguese"],"teclado":["portuguese"],"tedioso":["portuguese"],"teia":["portuguese"],"teimar":["portuguese"],"telefone":["portuguese"],"telhado":["portuguese"],"tempero":["portuguese"],"tenente":["portuguese"],"tensor":["portuguese"],"tentar":["portuguese"],"termal":["portuguese"],"terno":["portuguese"],"terreno":["portuguese"],"tese":["portuguese"],"tesoura":["portuguese"],"testado":["portuguese"],"teto":["portuguese"],"textura":["portuguese"],"texugo":["portuguese"],"tiara":["portuguese"],"tigela":["portuguese"],"tijolo":["portuguese"],"timbrar":["portuguese"],"timidez":["portuguese"],"tingido":["portuguese"],"tinteiro":["portuguese"],"tiragem":["portuguese"],"titular":["portuguese"],"toalha":["portuguese"],"tocha":["portuguese"],"tolerar":["portuguese"],"tolice":["portuguese"],"tomada":["portuguese"],"tomilho":["portuguese"],"tonel":["portuguese"],"tontura":["portuguese"],"topete":["portuguese"],"tora":["portuguese"],"torcido":["portuguese"],"torneio":["portuguese"],"torque":["portuguese"],"torrada":["portuguese"],"torto":["portuguese"],"tostar":["portuguese"],"touca":["portuguese"],"toupeira":["portuguese"],"toxina":["portuguese"],"trabalho":["portuguese"],"tracejar":["portuguese"],"tradutor":["portuguese"],"trafegar":["portuguese"],"trajeto":["portuguese"],"trama":["portuguese"],"trancar":["portuguese"],"trapo":["portuguese"],"traseiro":["portuguese"],"tratador":["portuguese"],"travar":["portuguese"],"treino":["portuguese"],"tremer":["portuguese"],"trepidar":["portuguese"],"trevo":["portuguese"],"triagem":["portuguese"],"tribo":["portuguese"],"triciclo":["portuguese"],"tridente":["portuguese"],"trilogia":["portuguese"],"trindade":["portuguese"],"triplo":["portuguese"],"triturar":["portuguese"],"triunfal":["portuguese"],"trocar":["portuguese"],"trombeta":["portuguese"],"trova":["portuguese"],"trunfo":["portuguese"],"truque":["portuguese"],"tubular":["portuguese"],"tucano":["portuguese"],"tudo":["portuguese"],"tulipa":["portuguese"],"tupi":["portuguese"],"turbo":["portuguese"],"turma":["portuguese"],"turquesa":["portuguese"],"tutelar":["portuguese"],"tutorial":["portuguese"],"uivar":["portuguese"],"umbigo":["portuguese"],"unha":["portuguese"],"unidade":["portuguese"],"uniforme":["portuguese"],"urologia":["portuguese"],"urso":["portuguese"],"urtiga":["portuguese"],"urubu":["portuguese"],"usado":["portuguese"],"usina":["portuguese"],"usufruir":["portuguese"],"vacina":["portuguese"],"vadiar":["portuguese"],"vagaroso":["portuguese"],"vaidoso":["portuguese"],"vala":["portuguese"],"valente":["portuguese"],"validade":["portuguese"],"valores":["portuguese"],"vantagem":["portuguese"],"vaqueiro":["portuguese"],"varanda":["portuguese"],"vareta":["portuguese"],"varrer":["portuguese"],"vascular":["portuguese"],"vasilha":["portuguese"],"vassoura":["portuguese"],"vazar":["portuguese"],"vazio":["portuguese"],"veado":["portuguese"],"vedar":["portuguese"],"vegetar":["portuguese"],"veicular":["portuguese"],"veleiro":["portuguese"],"velhice":["portuguese"],"veludo":["portuguese"],"vencedor":["portuguese"],"vendaval":["portuguese"],"venerar":["portuguese"],"ventre":["portuguese"],"verbal":["portuguese"],"verdade":["portuguese"],"vereador":["portuguese"],"vergonha":["portuguese"],"vermelho":["portuguese"],"verniz":["portuguese"],"versar":["portuguese"],"vertente":["portuguese"],"vespa":["portuguese"],"vestido":["portuguese"],"vetorial":["portuguese"],"viaduto":["portuguese"],"viagem":["portuguese"],"viajar":["portuguese"],"viatura":["portuguese"],"vibrador":["portuguese"],"videira":["portuguese"],"vidraria":["portuguese"],"viela":["portuguese"],"viga":["portuguese"],"vigente":["portuguese"],"vigiar":["portuguese"],"vigorar":["portuguese"],"vilarejo":["portuguese"],"vinco":["portuguese"],"vinheta":["portuguese"],"vinil":["portuguese"],"violeta":["portuguese"],"virada":["portuguese"],"virtude":["portuguese"],"visitar":["portuguese"],"visto":["portuguese"],"vitral":["portuguese"],"viveiro":["portuguese"],"vizinho":["portuguese"],"voador":["portuguese"],"voar":["portuguese"],"vogal":["portuguese"],"volante":["portuguese"],"voleibol":["portuguese"],"voltagem":["portuguese"],"volumoso":["portuguese"],"vontade":["portuguese"],"vulto":["portuguese"],"vuvuzela":["portuguese"],"xadrez":["portuguese"],"xarope":["portuguese"],"xeque":["portuguese"],"xeretar":["portuguese"],"xerife":["portuguese"],"xingar":["portuguese"],"zangado":["portuguese"],"zarpar":["portuguese"],"zebu":["portuguese"],"zelador":["portuguese"],"zombar":["portuguese"],"zoologia":["portuguese"],"zumbido":["portuguese"],"абзац":["russian"],"абонент":["russian"],"абсурд":["russian"],"авангард":["russian"],"авария":["russian"],"август":["russian"],"авиация":["russian"],"автор":["russian"],"агент":["russian"],"агитация":["russian"],"агрегат":["russian"],"адвокат":["russian"],"адмирал":["russian"],"адрес":["russian"],"азарт":["russian"],"азот":["russian"],"академия":["russian"],"аквариум":["russian"],"аксиома":["russian"],"акула":["russian"],"акцент":["russian"],"акция":["russian"],"аллея":["russian"],"алмаз":["russian"],"алтарь":["russian"],"альбом":["russian"],"альянс":["russian"],"амбиция":["russian"],"анализ":["russian"],"анекдот":["russian"],"анкета":["russian"],"ансамбль":["russian"],"антенна":["russian"],"апельсин":["russian"],"аппарат":["russian"],"аппетит":["russian"],"апрель":["russian"],"аптека":["russian"],"арбуз":["russian"],"аргумент":["russian"],"аренда":["russian"],"арест":["russian"],"армия":["russian"],"аромат":["russian"],"арсенал":["russian"],"артерия":["russian"],"артист":["russian"],"архив":["russian"],"аспирант":["russian"],"асфальт":["russian"],"атака":["russian"],"атомный":["russian"],"атрибут":["russian"],"аукцион":["russian"],"афиша":["russian"],"аэропорт":["russian"],"бабочка":["russian"],"бабушка":["russian"],"багаж":["russian"],"база":["russian"],"бактерия":["russian"],"баланс":["russian"],"балерина":["russian"],"балкон":["russian"],"бандит":["russian"],"банк":["russian"],"барабан":["russian"],"барон":["russian"],"барышня":["russian"],"барьер":["russian"],"бассейн":["russian"],"батарея":["russian"],"башмак":["russian"],"башня":["russian"],"бедный":["russian"],"беженец":["russian"],"бездна":["russian"],"белка":["russian"],"белый":["russian"],"бензин":["russian"],"берег":["russian"],"беседа":["russian"],"бешеный":["russian"],"билет":["russian"],"бинокль":["russian"],"биржа":["russian"],"битва":["russian"],"благо":["russian"],"блеск":["russian"],"близкий":["russian"],"блин":["russian"],"блок":["russian"],"блюдо":["russian"],"богатый":["russian"],"бодрый":["russian"],"боец":["russian"],"бокал":["russian"],"боковой":["russian"],"бокс":["russian"],"более":["russian"],"болото":["russian"],"болтать":["russian"],"большой":["russian"],"бомба":["russian"],"борт":["russian"],"борьба":["russian"],"босой":["russian"],"ботинок":["russian"],"бояться":["russian"],"брак":["russian"],"брать":["russian"],"бревно":["russian"],"бред":["russian"],"бригада":["russian"],"бродяга":["russian"],"броня":["russian"],"бросить":["russian"],"брызги":["russian"],"брюки":["russian"],"брюхо":["russian"],"бугор":["russian"],"будка":["russian"],"будни":["russian"],"будущее":["russian"],"буква":["russian"],"букет":["russian"],"бульвар":["russian"],"бумага":["russian"],"бунт":["russian"],"бурный":["russian"],"буря":["russian"],"бутылка":["russian"],"бухта":["russian"],"бывший":["russian"],"быстро":["russian"],"бытовой":["russian"],"быть":["russian"],"бюджет":["russian"],"бюро":["russian"],"бюст":["russian"],"вагон":["russian"],"важный":["russian"],"вакцина":["russian"],"валенок":["russian"],"вальс":["russian"],"валюта":["russian"],"ванная":["russian"],"варенье":["russian"],"вариант":["russian"],"вблизи":["russian"],"вверх":["russian"],"вводить":["russian"],"вдали":["russian"],"вдвое":["russian"],"вдова":["russian"],"вдоль":["russian"],"вдруг":["russian"],"ведро":["russian"],"ведущий":["russian"],"ведьма":["russian"],"вежливо":["russian"],"везде":["russian"],"веко":["russian"],"вексель":["russian"],"велеть":["russian"],"великий":["russian"],"венец":["russian"],"веник":["russian"],"веранда":["russian"],"верблюд":["russian"],"верить":["russian"],"верный":["russian"],"версия":["russian"],"вертеть":["russian"],"верхний":["russian"],"вершина":["russian"],"весело":["russian"],"весна":["russian"],"весомый":["russian"],"вести":["russian"],"весь":["russian"],"ветеран":["russian"],"ветхий":["russian"],"вечер":["russian"],"вечно":["russian"],"вешалка":["russian"],"вещество":["russian"],"взамен":["russian"],"взгляд":["russian"],"вздох":["russian"],"взнос":["russian"],"взойти":["russian"],"взор":["russian"],"взрыв":["russian"],"взять":["russian"],"видеть":["russian"],"видимо":["russian"],"визг":["russian"],"визит":["russian"],"вилка":["russian"],"вина":["russian"],"вирус":["russian"],"висок":["russian"],"витамин":["russian"],"витрина":["russian"],"вихрь":["russian"],"вишня":["russian"],"вкус":["russian"],"влага":["russian"],"владелец":["russian"],"власть":["russian"],"влево":["russian"],"влияние":["russian"],"вложить":["russian"],"вместе":["russian"],"внешний":["russian"],"вникать":["russian"],"внимание":["russian"],"вновь":["russian"],"внук":["russian"],"внутри":["russian"],"внучка":["russian"],"внушать":["russian"],"вовлечь":["russian"],"вовремя":["russian"],"вовсю":["russian"],"вода":["russian"],"водород":["russian"],"водяной":["russian"],"воевать":["russian"],"возврат":["russian"],"возглас":["russian"],"воздух":["russian"],"возить":["russian"],"возле":["russian"],"возня":["russian"],"возраст":["russian"],"война":["russian"],"войско":["russian"],"вокзал":["russian"],"волос":["russian"],"волчий":["russian"],"вольный":["russian"],"воля":["russian"],"вообще":["russian"],"вопль":["russian"],"вопрос":["russian"],"ворота":["russian"],"восемь":["russian"],"восток":["russian"],"вплоть":["russian"],"вполне":["russian"],"вправе":["russian"],"впредь":["russian"],"впрочем":["russian"],"врач":["russian"],"вредный":["russian"],"время":["russian"],"вручить":["russian"],"всадник":["russian"],"всегда":["russian"],"вскоре":["russian"],"вскрыть":["russian"],"всплеск":["russian"],"вспышка":["russian"],"встреча":["russian"],"всюду":["russian"],"всякий":["russian"],"второй":["russian"],"вход":["russian"],"вчера":["russian"],"выбор":["russian"],"вывод":["russian"],"выгнать":["russian"],"выдать":["russian"],"выехать":["russian"],"вызов":["russian"],"выйти":["russian"],"выкуп":["russian"],"вылезти":["russian"],"вымыть":["russian"],"выпасть":["russian"],"выпить":["russian"],"выплата":["russian"],"выпуск":["russian"],"вырасти":["russian"],"выручка":["russian"],"выслать":["russian"],"высокий":["russian"],"выставка":["russian"],"вышка":["russian"],"вязать":["russian"],"вялый":["russian"],"газета":["russian"],"газовый":["russian"],"галерея":["russian"],"галстук":["russian"],"гамма":["russian"],"гарантия":["russian"],"гармония":["russian"],"гарнизон":["russian"],"гастроли":["russian"],"гвардия":["russian"],"гвоздь":["russian"],"гектар":["russian"],"генерал":["russian"],"гений":["russian"],"геном":["russian"],"геолог":["russian"],"герб":["russian"],"герой":["russian"],"гибкий":["russian"],"гигант":["russian"],"гимн":["russian"],"гипотеза":["russian"],"гитара":["russian"],"главный":["russian"],"глагол":["russian"],"гладить":["russian"],"глаз":["russian"],"глина":["russian"],"глоток":["russian"],"глубокий":["russian"],"глупый":["russian"],"глухой":["russian"],"глыба":["russian"],"глядеть":["russian"],"гнев":["russian"],"гнездо":["russian"],"гнилой":["russian"],"годовой":["russian"],"голова":["russian"],"голубой":["russian"],"голый":["russian"],"гонорар":["russian"],"гордость":["russian"],"горизонт":["russian"],"горло":["russian"],"горный":["russian"],"город":["russian"],"горшок":["russian"],"горький":["russian"],"горючее":["russian"],"горячий":["russian"],"готовый":["russian"],"градус":["russian"],"грамм":["russian"],"граница":["russian"],"граф":["russian"],"гребень":["russian"],"гриб":["russian"],"гримаса":["russian"],"грозить":["russian"],"грохот":["russian"],"грош":["russian"],"грубый":["russian"],"грудь":["russian"],"груз":["russian"],"грунт":["russian"],"группа":["russian"],"груша":["russian"],"грязный":["russian"],"губа":["russian"],"гудок":["russian"],"гулкий":["russian"],"гулять":["russian"],"гусеница":["russian"],"густо":["russian"],"гусь":["russian"],"давление":["russian"],"давно":["russian"],"даже":["russian"],"дальний":["russian"],"данный":["russian"],"дарить":["russian"],"датчик":["russian"],"дать":["russian"],"дача":["russian"],"двадцать":["russian"],"дважды":["russian"],"дверь":["russian"],"двигать":["russian"],"движение":["russian"],"двойной":["russian"],"двор":["russian"],"дебют":["russian"],"девятый":["russian"],"дежурный":["russian"],"действие":["russian"],"декабрь":["russian"],"деление":["russian"],"дело":["russian"],"дельфин":["russian"],"день":["russian"],"дерево":["russian"],"держать":["russian"],"дерзкий":["russian"],"десять":["russian"],"деталь":["russian"],"детский":["russian"],"дефект":["russian"],"дефицит":["russian"],"деятель":["russian"],"джаз":["russian"],"джинсы":["russian"],"джунгли":["russian"],"диагноз":["russian"],"диалог":["russian"],"диапазон":["russian"],"диван":["russian"],"дивизия":["russian"],"дивный":["russian"],"диета":["russian"],"дизайн":["russian"],"дикарь":["russian"],"дилер":["russian"],"динамика":["russian"],"диплом":["russian"],"директор":["russian"],"дитя":["russian"],"длинный":["russian"],"дневник":["russian"],"добрый":["russian"],"добыча":["russian"],"доверие":["russian"],"догадка":["russian"],"догнать":["russian"],"дождь":["russian"],"доклад":["russian"],"доктор":["russian"],"документ":["russian"],"долго":["russian"],"должен":["russian"],"долина":["russian"],"донос":["russian"],"дорога":["russian"],"досада":["russian"],"доска":["russian"],"достать":["russian"],"досуг":["russian"],"доход":["russian"],"доцент":["russian"],"дощатый":["russian"],"драка":["russian"],"древний":["russian"],"дремать":["russian"],"дробный":["russian"],"дрова":["russian"],"дрожать":["russian"],"другой":["russian"],"дружба":["russian"],"дубовый":["russian"],"дуга":["russian"],"думать":["russian"],"дурной":["russian"],"духи":["russian"],"душный":["russian"],"дуэль":["russian"],"дуэт":["russian"],"дыра":["russian"],"дыхание":["russian"],"дюжина":["russian"],"дядя":["russian"],"едва":["russian"],"единый":["russian"],"ерунда":["russian"],"если":["russian"],"ехать":["russian"],"жадный":["russian"],"жажда":["russian"],"жалеть":["russian"],"жалоба":["russian"],"жанр":["russian"],"жареный":["russian"],"жаркий":["russian"],"жгучий":["russian"],"жевать":["russian"],"желание":["russian"],"желудок":["russian"],"жена":["russian"],"женщина":["russian"],"жертва":["russian"],"жест":["russian"],"жидкость":["russian"],"житель":["russian"],"жить":["russian"],"жрец":["russian"],"жулик":["russian"],"журнал":["russian"],"жуткий":["russian"],"забрать":["russian"],"забыть":["russian"],"завести":["russian"],"завод":["russian"],"завтра":["russian"],"загадка":["russian"],"загнать":["russian"],"заговор":["russian"],"задача":["russian"],"задеть":["russian"],"задний":["russian"],"задолго":["russian"],"заехать":["russian"],"заказ":["russian"],"закон":["russian"],"закрыть":["russian"],"закуска":["russian"],"залезть":["russian"],"залить":["russian"],"залп":["russian"],"замок":["russian"],"замуж":["russian"],"замысел":["russian"],"занавес":["russian"],"заново":["russian"],"занять":["russian"],"заодно":["russian"],"запись":["russian"],"запрос":["russian"],"запуск":["russian"],"запястье":["russian"],"заранее":["russian"],"заросль":["russian"],"зарплата":["russian"],"заря":["russian"],"засада":["russian"],"заслуга":["russian"],"заснуть":["russian"],"застать":["russian"],"затвор":["russian"],"затеять":["russian"],"затрата":["russian"],"затылок":["russian"],"захват":["russian"],"зачем":["russian"],"защита":["russian"],"заявить":["russian"],"заяц":["russian"],"звезда":["russian"],"звено":["russian"],"звонить":["russian"],"здесь":["russian"],"зелень":["russian"],"земля":["russian"],"зеркало":["russian"],"зерно":["russian"],"зима":["russian"],"злой":["russian"],"змея":["russian"],"знамя":["russian"],"знание":["russian"],"значит":["russian"],"золотой":["russian"],"зона":["russian"],"зонтик":["russian"],"зоопарк":["russian"],"зрачок":["russian"],"зрение":["russian"],"зритель":["russian"],"зубной":["russian"],"зубр":["russian"],"игла":["russian"],"идеал":["russian"],"идеолог":["russian"],"идея":["russian"],"идол":["russian"],"идти":["russian"],"изба":["russian"],"избить":["russian"],"избрать":["russian"],"избыток":["russian"],"извлечь":["russian"],"извне":["russian"],"изгиб":["russian"],"изгнать":["russian"],"издание":["russian"],"изделие":["russian"],"изнутри":["russian"],"изобилие":["russian"],"изоляция":["russian"],"изредка":["russian"],"изрядно":["russian"],"изучение":["russian"],"изъять":["russian"],"изящный":["russian"],"икона":["russian"],"икра":["russian"],"иллюзия":["russian"],"именно":["russian"],"иметь":["russian"],"имидж":["russian"],"империя":["russian"],"импульс":["russian"],"иначе":["russian"],"инвалид":["russian"],"индекс":["russian"],"индивид":["russian"],"инерция":["russian"],"инженер":["russian"],"иногда":["russian"],"иной":["russian"],"институт":["russian"],"интерес":["russian"],"интрига":["russian"],"интуиция":["russian"],"инфаркт":["russian"],"инцидент":["russian"],"ирония":["russian"],"искать":["russian"],"испуг":["russian"],"история":["russian"],"итог":["russian"],"июнь":["russian"],"кабель":["russian"],"кабинет":["russian"],"каблук":["russian"],"кавалер":["russian"],"кадр":["russian"],"каждый":["russian"],"кажется":["russian"],"казино":["russian"],"калитка":["russian"],"камень":["russian"],"камин":["russian"],"канал":["russian"],"кандидат":["russian"],"каникулы":["russian"],"канон":["russian"],"капитан":["russian"],"капля":["russian"],"капот":["russian"],"капуста":["russian"],"карандаш":["russian"],"карета":["russian"],"каркас":["russian"],"карман":["russian"],"картина":["russian"],"карьера":["russian"],"каска":["russian"],"кассета":["russian"],"кастрюля":["russian"],"каталог":["russian"],"катер":["russian"],"каток":["russian"],"катушка":["russian"],"кафедра":["russian"],"качество":["russian"],"каша":["russian"],"кашлять":["russian"],"каюта":["russian"],"квадрат":["russian"],"квартира":["russian"],"квота":["russian"],"кепка":["russian"],"кивнуть":["russian"],"километр":["russian"],"кино":["russian"],"киоск":["russian"],"кипяток":["russian"],"кирпич":["russian"],"кислота":["russian"],"кисть":["russian"],"клавиша":["russian"],"клапан":["russian"],"класс":["russian"],"клей":["russian"],"клетка":["russian"],"клиент":["russian"],"климат":["russian"],"клиника":["russian"],"кличка":["russian"],"клоун":["russian"],"клочок":["russian"],"клуб":["russian"],"клумба":["russian"],"ключ":["russian"],"книга":["russian"],"кнопка":["russian"],"кнут":["russian"],"княгиня":["russian"],"князь":["russian"],"кобура":["russian"],"когда":["russian"],"кодекс":["russian"],"кожа":["russian"],"коктейль":["russian"],"колено":["russian"],"коллега":["russian"],"колонна":["russian"],"колпак":["russian"],"кольцо":["russian"],"колючий":["russian"],"коляска":["russian"],"команда":["russian"],"комедия":["russian"],"комиссия":["russian"],"коммуна":["russian"],"комната":["russian"],"комок":["russian"],"компания":["russian"],"комфорт":["russian"],"конвейер":["russian"],"конгресс":["russian"],"конечно":["russian"],"конкурс":["russian"],"контроль":["russian"],"концерт":["russian"],"конь":["russian"],"конюшня":["russian"],"копать":["russian"],"копейка":["russian"],"копыто":["russian"],"корабль":["russian"],"корень":["russian"],"корзина":["russian"],"коридор":["russian"],"кормить":["russian"],"корпус":["russian"],"космос":["russian"],"костюм":["russian"],"косяк":["russian"],"котел":["russian"],"котлета":["russian"],"который":["russian"],"коттедж":["russian"],"кофе":["russian"],"кофта":["russian"],"кошка":["russian"],"кража":["russian"],"край":["russian"],"красный":["russian"],"краткий":["russian"],"кредит":["russian"],"крем":["russian"],"крепкий":["russian"],"кресло":["russian"],"кривой":["russian"],"кризис":["russian"],"кристалл":["russian"],"критерий":["russian"],"кричать":["russian"],"кровь":["russian"],"крокодил":["russian"],"кролик":["russian"],"кроме":["russian"],"крона":["russian"],"круг":["russian"],"кружка":["russian"],"крупный":["russian"],"крутой":["russian"],"крушение":["russian"],"крыло":["russian"],"крыша":["russian"],"крючок":["russian"],"кстати":["russian"],"кубик":["russian"],"куда":["russian"],"кузов":["russian"],"кукла":["russian"],"кулак":["russian"],"кулиса":["russian"],"культура":["russian"],"кумир":["russian"],"купе":["russian"],"купить":["russian"],"купол":["russian"],"купюра":["russian"],"курица":["russian"],"курорт":["russian"],"курс":["russian"],"куртка":["russian"],"кусок":["russian"],"куст":["russian"],"кухня":["russian"],"кушать":["russian"],"лабиринт":["russian"],"лавка":["russian"],"лагерь":["russian"],"ладно":["russian"],"ладонь":["russian"],"лапа":["russian"],"лауреат":["russian"],"лгать":["russian"],"лебедь":["russian"],"левый":["russian"],"легенда":["russian"],"легкий":["russian"],"ледяной":["russian"],"лежать":["russian"],"лезвие":["russian"],"лезть":["russian"],"лекция":["russian"],"ленивый":["russian"],"лента":["russian"],"лепесток":["russian"],"лесной":["russian"],"лестница":["russian"],"лететь":["russian"],"лето":["russian"],"лечить":["russian"],"лига":["russian"],"лидер":["russian"],"лиловый":["russian"],"лимон":["russian"],"линия":["russian"],"липкий":["russian"],"лист":["russian"],"литр":["russian"],"лихой":["russian"],"лицо":["russian"],"лишить":["russian"],"лишний":["russian"],"ловить":["russian"],"логика":["russian"],"лодка":["russian"],"ложь":["russian"],"лозунг":["russian"],"локоть":["russian"],"лопата":["russian"],"лошадь":["russian"],"лукавый":["russian"],"луна":["russian"],"лучший":["russian"],"лысый":["russian"],"льгота":["russian"],"любить":["russian"],"любой":["russian"],"людской":["russian"],"люстра":["russian"],"лютый":["russian"],"лягушка":["russian"],"магазин":["russian"],"магия":["russian"],"майор":["russian"],"майский":["russian"],"максимум":["russian"],"макушка":["russian"],"мало":["russian"],"мальчик":["russian"],"мама":["russian"],"манера":["russian"],"марка":["russian"],"март":["russian"],"маршрут":["russian"],"масса":["russian"],"мастер":["russian"],"масштаб":["russian"],"материал":["russian"],"матч":["russian"],"махать":["russian"],"машина":["russian"],"маяк":["russian"],"мебель":["russian"],"медаль":["russian"],"медведь":["russian"],"медицина":["russian"],"медь":["russian"],"между":["russian"],"мелкий":["russian"],"мелочь":["russian"],"мемуары":["russian"],"меньше":["russian"],"меню":["russian"],"менять":["russian"],"мера":["russian"],"мерцать":["russian"],"место":["russian"],"месяц":["russian"],"металл":["russian"],"метод":["russian"],"метр":["russian"],"механизм":["russian"],"меховой":["russian"],"мечтать":["russian"],"мешать":["russian"],"мешок":["russian"],"миграция":["russian"],"микрофон":["russian"],"милиция":["russian"],"миллион":["russian"],"милость":["russian"],"миля":["russian"],"мимо":["russian"],"минерал":["russian"],"министр":["russian"],"минута":["russian"],"мирный":["russian"],"миска":["russian"],"миссия":["russian"],"митинг":["russian"],"мишень":["russian"],"младший":["russian"],"мнение":["russian"],"мнимый":["russian"],"много":["russian"],"могучий":["russian"],"модель":["russian"],"может":["russian"],"мозг":["russian"],"мокрый":["russian"],"молекула":["russian"],"молния":["russian"],"молодой":["russian"],"молчать":["russian"],"момент":["russian"],"монета":["russian"],"монитор":["russian"],"монолог":["russian"],"монстр":["russian"],"монтаж":["russian"],"мораль":["russian"],"море":["russian"],"морковь":["russian"],"мороз":["russian"],"морщина":["russian"],"мостовая":["russian"],"мотать":["russian"],"мотив":["russian"],"мотор":["russian"],"мохнатый":["russian"],"мрамор":["russian"],"мрачный":["russian"],"мстить":["russian"],"мудрый":["russian"],"мужество":["russian"],"мужчина":["russian"],"музей":["russian"],"музыка":["russian"],"мундир":["russian"],"муравей":["russian"],"мусор":["russian"],"муха":["russian"],"мчаться":["russian"],"мысль":["russian"],"мыться":["russian"],"мышца":["russian"],"мышь":["russian"],"мюзикл":["russian"],"мягкий":["russian"],"мясо":["russian"],"набор":["russian"],"навык":["russian"],"наглый":["russian"],"нагрузка":["russian"],"надежда":["russian"],"надзор":["russian"],"надо":["russian"],"наедине":["russian"],"назад":["russian"],"название":["russian"],"назло":["russian"],"наивный":["russian"],"найти":["russian"],"наконец":["russian"],"налево":["russian"],"наличие":["russian"],"налог":["russian"],"намерен":["russian"],"нанести":["russian"],"напасть":["russian"],"например":["russian"],"народ":["russian"],"наследие":["russian"],"натура":["russian"],"наука":["russian"],"наутро":["russian"],"начать":["russian"],"небо":["russian"],"неважно":["russian"],"невеста":["russian"],"негодяй":["russian"],"недавно":["russian"],"неделя":["russian"],"недолго":["russian"],"недра":["russian"],"недуг":["russian"],"нежный":["russian"],"незачем":["russian"],"некто":["russian"],"нелепый":["russian"],"неловко":["russian"],"нельзя":["russian"],"немало":["russian"],"немой":["russian"],"неплохо":["russian"],"нервный":["russian"],"нередко":["russian"],"нестись":["russian"],"неудача":["russian"],"неужели":["russian"],"нефть":["russian"],"неясный":["russian"],"нигде":["russian"],"низкий":["russian"],"никакой":["russian"],"никогда":["russian"],"никуда":["russian"],"ничто":["russian"],"ничуть":["russian"],"ниша":["russian"],"нищий":["russian"],"новость":["russian"],"новый":["russian"],"нога":["russian"],"ноготь":["russian"],"ножницы":["russian"],"ноздря":["russian"],"номер":["russian"],"носить":["russian"],"носок":["russian"],"ночь":["russian"],"ноябрь":["russian"],"нрав":["russian"],"нуль":["russian"],"нынче":["russian"],"нырять":["russian"],"нюанс":["russian"],"няня":["russian"],"обаяние":["russian"],"обед":["russian"],"обезьяна":["russian"],"обещать":["russian"],"обжечь":["russian"],"обзор":["russian"],"обилие":["russian"],"обитать":["russian"],"область":["russian"],"облик":["russian"],"обложка":["russian"],"обмен":["russian"],"обморок":["russian"],"обожать":["russian"],"обои":["russian"],"оболочка":["russian"],"оборона":["russian"],"обочина":["russian"],"образ":["russian"],"обрести":["russian"],"обрыв":["russian"],"обувь":["russian"],"обучение":["russian"],"обход":["russian"],"общество":["russian"],"общий":["russian"],"объект":["russian"],"обыск":["russian"],"обычно":["russian"],"обязать":["russian"],"овощи":["russian"],"овраг":["russian"],"овца":["russian"],"оговорка":["russian"],"ограда":["russian"],"огурец":["russian"],"одежда":["russian"],"одеяло":["russian"],"один":["russian"],"однако":["russian"],"одолеть":["russian"],"ожидать":["russian"],"озеро":["russian"],"океан":["russian"],"окно":["russian"],"около":["russian"],"окоп":["russian"],"окраина":["russian"],"октябрь":["russian"],"опасный":["russian"],"опека":["russian"],"операция":["russian"],"описание":["russian"],"оплата":["russian"],"опора":["russian"],"оппонент":["russian"],"оптимизм":["russian"],"оптовый":["russian"],"опухоль":["russian"],"опыт":["russian"],"оратор":["russian"],"орбита":["russian"],"орган":["russian"],"орден":["russian"],"орел":["russian"],"оригинал":["russian"],"ориентир":["russian"],"оркестр":["russian"],"оружие":["russian"],"осенний":["russian"],"осколок":["russian"],"осмотр":["russian"],"остров":["russian"],"отбор":["russian"],"отбыть":["russian"],"отвлечь":["russian"],"отдать":["russian"],"отдел":["russian"],"отдых":["russian"],"отель":["russian"],"отец":["russian"],"отзыв":["russian"],"отказ":["russian"],"отклик":["russian"],"открыть":["russian"],"откуда":["russian"],"отличие":["russian"],"отныне":["russian"],"отойти":["russian"],"отпуск":["russian"],"отрасль":["russian"],"отросток":["russian"],"отрывок":["russian"],"отряд":["russian"],"отсек":["russian"],"отставка":["russian"],"отсюда":["russian"],"оттенок":["russian"],"оттого":["russian"],"отчего":["russian"],"отъезд":["russian"],"офис":["russian"],"офицер":["russian"],"охота":["russian"],"охрана":["russian"],"оценка":["russian"],"очаг":["russian"],"очень":["russian"],"очередь":["russian"],"очищать":["russian"],"ошибка":["russian"],"ощущение":["russian"],"павильон":["russian"],"падать":["russian"],"пазуха":["russian"],"пакет":["russian"],"палата":["russian"],"палец":["russian"],"палуба":["russian"],"пальто":["russian"],"память":["russian"],"панель":["russian"],"паника":["russian"],"пара":["russian"],"парень":["russian"],"пароход":["russian"],"партия":["russian"],"парус":["russian"],"паспорт":["russian"],"пассажир":["russian"],"пастух":["russian"],"патент":["russian"],"патрон":["russian"],"пауза":["russian"],"паук":["russian"],"паутина":["russian"],"пафос":["russian"],"пахнуть":["russian"],"пациент":["russian"],"пачка":["russian"],"певец":["russian"],"педагог":["russian"],"пейзаж":["russian"],"пенсия":["russian"],"пепел":["russian"],"первый":["russian"],"перед":["russian"],"период":["russian"],"перо":["russian"],"перрон":["russian"],"персонаж":["russian"],"перчатка":["russian"],"песня":["russian"],"песок":["russian"],"петля":["russian"],"петрушка":["russian"],"петух":["russian"],"пехота":["russian"],"печать":["russian"],"печень":["russian"],"пешком":["russian"],"пещера":["russian"],"пианист":["russian"],"пиджак":["russian"],"пилот":["russian"],"пионер":["russian"],"пирамида":["russian"],"пирожок":["russian"],"письмо":["russian"],"пища":["russian"],"плавание":["russian"],"плакать":["russian"],"пламя":["russian"],"план":["russian"],"пласт":["russian"],"платить":["russian"],"пленный":["russian"],"плечо":["russian"],"плита":["russian"],"плод":["russian"],"плоский":["russian"],"плотный":["russian"],"плохой":["russian"],"площадь":["russian"],"плыть":["russian"],"плюс":["russian"],"пляж":["russian"],"плясать":["russian"],"победа":["russian"],"повар":["russian"],"повод":["russian"],"повсюду":["russian"],"повязка":["russian"],"погода":["russian"],"погреб":["russian"],"подбор":["russian"],"подвиг":["russian"],"подделка":["russian"],"поджать":["russian"],"поднос":["russian"],"подпись":["russian"],"подруга":["russian"],"подход":["russian"],"подчас":["russian"],"подъезд":["russian"],"поединок":["russian"],"поезд":["russian"],"поесть":["russian"],"поехать":["russian"],"пожалуй":["russian"],"пожилой":["russian"],"позади":["russian"],"позвать":["russian"],"поздний":["russian"],"позиция":["russian"],"позор":["russian"],"поиск":["russian"],"поймать":["russian"],"пойти":["russian"],"поклон":["russian"],"покой":["russian"],"покрыть":["russian"],"полдень":["russian"],"полезный":["russian"],"ползти":["russian"],"полк":["russian"],"полный":["russian"],"половина":["russian"],"полтора":["russian"],"польза":["russian"],"поляна":["russian"],"помидор":["russian"],"помнить":["russian"],"помощь":["russian"],"попасть":["russian"],"поперек":["russian"],"поплыть":["russian"],"пополам":["russian"],"поправка":["russian"],"попугай":["russian"],"попытка":["russian"],"порог":["russian"],"портрет":["russian"],"порция":["russian"],"порыв":["russian"],"порядок":["russian"],"после":["russian"],"посол":["russian"],"посреди":["russian"],"постель":["russian"],"посуда":["russian"],"потом":["russian"],"похвала":["russian"],"похожий":["russian"],"поцелуй":["russian"],"почва":["russian"],"почему":["russian"],"пошлина":["russian"],"поэма":["russian"],"поэтому":["russian"],"право":["russian"],"праздник":["russian"],"практика":["russian"],"прах":["russian"],"преграда":["russian"],"предмет":["russian"],"прежде":["russian"],"прелесть":["russian"],"премия":["russian"],"препарат":["russian"],"пресса":["russian"],"прибыть":["russian"],"прижать":["russian"],"прийти":["russian"],"приказ":["russian"],"прилавок":["russian"],"пример":["russian"],"принять":["russian"],"природа":["russian"],"притом":["russian"],"прихожая":["russian"],"прицел":["russian"],"причина":["russian"],"приют":["russian"],"прогноз":["russian"],"продукт":["russian"],"проект":["russian"],"прожить":["russian"],"прокат":["russian"],"промысел":["russian"],"пропуск":["russian"],"просто":["russian"],"против":["russian"],"профиль":["russian"],"процесс":["russian"],"прочий":["russian"],"прошлый":["russian"],"прощать":["russian"],"пружина":["russian"],"прут":["russian"],"прыжок":["russian"],"прямой":["russian"],"птица":["russian"],"публика":["russian"],"пугать":["russian"],"пуговица":["russian"],"пузырь":["russian"],"пульт":["russian"],"пуля":["russian"],"пункт":["russian"],"пускать":["russian"],"пустой":["russian"],"путь":["russian"],"пухлый":["russian"],"пучок":["russian"],"пушистый":["russian"],"пушка":["russian"],"пчела":["russian"],"пшеница":["russian"],"пылать":["russian"],"пыль":["russian"],"пышный":["russian"],"пьеса":["russian"],"пятка":["russian"],"пятно":["russian"],"пятый":["russian"],"пятьсот":["russian"],"работа":["russian"],"равнина":["russian"],"ради":["russian"],"радость":["russian"],"радуга":["russian"],"разбить":["russian"],"развитие":["russian"],"разговор":["russian"],"раздел":["russian"],"различие":["russian"],"размер":["russian"],"разный":["russian"],"разрыв":["russian"],"разум":["russian"],"район":["russian"],"ракета":["russian"],"раковина":["russian"],"рамка":["russian"],"рано":["russian"],"рапорт":["russian"],"распад":["russian"],"рассказ":["russian"],"расти":["russian"],"расход":["russian"],"расцвет":["russian"],"рация":["russian"],"рвануть":["russian"],"рваться":["russian"],"реакция":["russian"],"ребро":["russian"],"реветь":["russian"],"редактор":["russian"],"редкий":["russian"],"реестр":["russian"],"режим":["russian"],"резать":["russian"],"резерв":["russian"],"резина":["russian"],"резко":["russian"],"резной":["russian"],"рейс":["russian"],"реклама":["russian"],"рекорд":["russian"],"религия":["russian"],"рельс":["russian"],"ремень":["russian"],"ремонт":["russian"],"реплика":["russian"],"репортаж":["russian"],"ресница":["russian"],"ресторан":["russian"],"реформа":["russian"],"рецепт":["russian"],"речь":["russian"],"решение":["russian"],"ржавый":["russian"],"риск":["russian"],"рисунок":["russian"],"ритуал":["russian"],"рифма":["russian"],"робко":["russian"],"робот":["russian"],"ровесник":["russian"],"ровно":["russian"],"родной":["russian"],"рождение":["russian"],"роза":["russian"],"розовый":["russian"],"розыск":["russian"],"роль":["russian"],"роман":["russian"],"роскошь":["russian"],"роспись":["russian"],"рост":["russian"],"рубашка":["russian"],"рубеж":["russian"],"рубить":["russian"],"рубрика":["russian"],"рудник":["russian"],"рука":["russian"],"рукопись":["russian"],"румяный":["russian"],"русло":["russian"],"рухнуть":["russian"],"ручей":["russian"],"ручной":["russian"],"рыба":["russian"],"рыжий":["russian"],"рынок":["russian"],"рыхлый":["russian"],"рыцарь":["russian"],"рычаг":["russian"],"рюкзак":["russian"],"рядом":["russian"],"садовый":["russian"],"сажать":["russian"],"салон":["russian"],"салфетка":["russian"],"салют":["russian"],"самец":["russian"],"самовар":["russian"],"самый":["russian"],"сани":["russian"],"санкция":["russian"],"сапог":["russian"],"сарай":["russian"],"сатира":["russian"],"сахар":["russian"],"сбить":["russian"],"сбоку":["russian"],"сборная":["russian"],"сбыт":["russian"],"свадьба":["russian"],"свалка":["russian"],"сварить":["russian"],"свежий":["russian"],"сверху":["russian"],"свет":["russian"],"свеча":["russian"],"свинья":["russian"],"свист":["russian"],"свитер":["russian"],"свобода":["russian"],"сводка":["russian"],"свой":["russian"],"свыше":["russian"],"связь":["russian"],"сдаться":["russian"],"сделать":["russian"],"сегмент":["russian"],"сегодня":["russian"],"седло":["russian"],"седой":["russian"],"седьмой":["russian"],"сезон":["russian"],"сейф":["russian"],"сейчас":["russian"],"секрет":["russian"],"сектор":["russian"],"секунда":["russian"],"семинар":["russian"],"семья":["russian"],"сенатор":["russian"],"сено":["russian"],"сенсация":["russian"],"сентябрь":["russian"],"сервис":["russian"],"сердце":["russian"],"середина":["russian"],"сержант":["russian"],"серия":["russian"],"серый":["russian"],"сессия":["russian"],"сесть":["russian"],"сетевой":["russian"],"сжатый":["russian"],"сжечь":["russian"],"сзади":["russian"],"сигнал":["russian"],"сиденье":["russian"],"сила":["russian"],"силуэт":["russian"],"сильный":["russian"],"символ":["russian"],"симпатия":["russian"],"симфония":["russian"],"синий":["russian"],"синтез":["russian"],"синяк":["russian"],"сирень":["russian"],"система":["russian"],"ситуация":["russian"],"сияние":["russian"],"сказать":["russian"],"скала":["russian"],"скамейка":["russian"],"скандал":["russian"],"скатерть":["russian"],"скачок":["russian"],"скважина":["russian"],"сквер":["russian"],"сквозь":["russian"],"скелет":["russian"],"скидка":["russian"],"склад":["russian"],"сколько":["russian"],"скорый":["russian"],"скосить":["russian"],"скот":["russian"],"скрипка":["russian"],"скудный":["russian"],"скука":["russian"],"слабый":["russian"],"слава":["russian"],"сладкий":["russian"],"слегка":["russian"],"след":["russian"],"слеза":["russian"],"слепой":["russian"],"слесарь":["russian"],"слишком":["russian"],"слово":["russian"],"слог":["russian"],"сложный":["russian"],"сломать":["russian"],"служба":["russian"],"слух":["russian"],"случай":["russian"],"слышать":["russian"],"слюна":["russian"],"смежный":["russian"],"смелый":["russian"],"сменить":["russian"],"смесь":["russian"],"сметана":["russian"],"смех":["russian"],"смола":["russian"],"смуглый":["russian"],"смутный":["russian"],"смущать":["russian"],"смысл":["russian"],"снайпер":["russian"],"снаряд":["russian"],"сначала":["russian"],"снег":["russian"],"снизу":["russian"],"сниться":["russian"],"сно��а":["russian"],"снять":["russian"],"собака":["russian"],"соблазн":["russian"],"собрание":["russian"],"событие":["russian"],"совесть":["russian"],"совсем":["russian"],"согласие":["russian"],"создать":["russian"],"сознание":["russian"],"созреть":["russian"],"сойтись":["russian"],"сокол":["russian"],"солдат":["russian"],"соленый":["russian"],"солнце":["russian"],"солома":["russian"],"сомнение":["russian"],"сонный":["russian"],"соперник":["russian"],"соратник":["russian"],"сорвать":["russian"],"сосед":["russian"],"сосиска":["russian"],"состав":["russian"],"сотня":["russian"],"соус":["russian"],"союз":["russian"],"спад":["russian"],"спальня":["russian"],"спасти":["russian"],"спектр":["russian"],"сперва":["russian"],"спешить":["russian"],"спина":["russian"],"спирт":["russian"],"список":["russian"],"спичка":["russian"],"сплав":["russian"],"спонсор":["russian"],"спор":["russian"],"способ":["russian"],"справка":["russian"],"спустя":["russian"],"спутник":["russian"],"сразу":["russian"],"средство":["russian"],"срок":["russian"],"срыв":["russian"],"ссора":["russian"],"ссылка":["russian"],"ставить":["russian"],"стадия":["russian"],"стакан":["russian"],"станция":["russian"],"старый":["russian"],"стая":["russian"],"стебель":["russian"],"стекло":["russian"],"стена":["russian"],"степень":["russian"],"стереть":["russian"],"стиль":["russian"],"стимул":["russian"],"стирать":["russian"],"стихи":["russian"],"стоить":["russian"],"стойка":["russian"],"стол":["russian"],"стонать":["russian"],"стопа":["russian"],"сторона":["russian"],"стоянка":["russian"],"страна":["russian"],"стричь":["russian"],"строгий":["russian"],"струя":["russian"],"студент":["russian"],"стук":["russian"],"ступня":["russian"],"стыдно":["russian"],"суббота":["russian"],"субъект":["russian"],"сувенир":["russian"],"сугроб":["russian"],"сугубо":["russian"],"судить":["russian"],"судно":["russian"],"судьба":["russian"],"суета":["russian"],"суметь":["russian"],"сумма":["russian"],"сумрак":["russian"],"сундук":["russian"],"супруг":["russian"],"суровый":["russian"],"сутки":["russian"],"сухой":["russian"],"суша":["russian"],"существо":["russian"],"сфера":["russian"],"схема":["russian"],"схожий":["russian"],"сценарий":["russian"],"счастье":["russian"],"считать":["russian"],"съезд":["russian"],"сыграть":["russian"],"сырой":["russian"],"сытый":["russian"],"сыщик":["russian"],"сюда":["russian"],"сюжет":["russian"],"сюрприз":["russian"],"тайна":["russian"],"также":["russian"],"такой":["russian"],"такси":["russian"],"тактика":["russian"],"талия":["russian"],"таможня":["russian"],"танец":["russian"],"таракан":["russian"],"тарелка":["russian"],"тариф":["russian"],"тащить":["russian"],"таять":["russian"],"тварь":["russian"],"театр":["russian"],"тезис":["russian"],"текст":["russian"],"текущий":["russian"],"телефон":["russian"],"тема":["russian"],"темнота":["russian"],"теневой":["russian"],"теннис":["russian"],"теория":["russian"],"теперь":["russian"],"тепло":["russian"],"терапия":["russian"],"терзать":["russian"],"термин":["russian"],"терпеть":["russian"],"терраса":["russian"],"терять":["russian"],"тесный":["russian"],"тетрадь":["russian"],"техника":["russian"],"течение":["russian"],"тигр":["russian"],"типовой":["russian"],"тираж":["russian"],"титул":["russian"],"тихий":["russian"],"ткань":["russian"],"товарищ":["russian"],"тоже":["russian"],"толпа":["russian"],"толстый":["russian"],"толчок":["russian"],"толщина":["russian"],"только":["russian"],"тонкий":["russian"],"тонна":["russian"],"топить":["russian"],"топор":["russian"],"торговля":["russian"],"тормоз":["russian"],"торчать":["russian"],"тотчас":["russian"],"точка":["russian"],"точно":["russian"],"тощий":["russian"],"трава":["russian"],"традиция":["russian"],"трактор":["russian"],"трамвай":["russian"],"траншея":["russian"],"трасса":["russian"],"тревога":["russian"],"трезвый":["russian"],"тренер":["russian"],"трепет":["russian"],"треск":["russian"],"третий":["russian"],"трещина":["russian"],"трибуна":["russian"],"тридцать":["russian"],"триста":["russian"],"триумф":["russian"],"трогать":["russian"],"тройка":["russian"],"тронуть":["russian"],"тропа":["russian"],"тротуар":["russian"],"трубка":["russian"],"труд":["russian"],"трюк":["russian"],"тряпка":["russian"],"туго":["russian"],"туловище":["russian"],"туман":["russian"],"тумбочка":["russian"],"тундра":["russian"],"тупик":["russian"],"турист":["russian"],"турнир":["russian"],"тусклый":["russian"],"туфля":["russian"],"туча":["russian"],"тысяча":["russian"],"тяга":["russian"],"тяжело":["russian"],"убежать":["russian"],"убогий":["russian"],"уборка":["russian"],"уважение":["russian"],"увезти":["russian"],"уволить":["russian"],"угадать":["russian"],"угол":["russian"],"угощать":["russian"],"угроза":["russian"],"угрюмый":["russian"],"удар":["russian"],"удачный":["russian"],"уделять":["russian"],"удивить":["russian"],"удобный":["russian"],"удочка":["russian"],"уезжать":["russian"],"ужин":["russian"],"узел":["russian"],"узкий":["russian"],"уйти":["russian"],"указание":["russian"],"уклон":["russian"],"украсть":["russian"],"укусить":["russian"],"улетать":["russian"],"улица":["russian"],"улыбка":["russian"],"умело":["russian"],"умение":["russian"],"умный":["russian"],"умолять":["russian"],"унести":["russian"],"унижать":["russian"],"унылый":["russian"],"упаковка":["russian"],"упасть":["russian"],"упорно":["russian"],"упрек":["russian"],"урна":["russian"],"уровень":["russian"],"урожай":["russian"],"уронить":["russian"],"усадьба":["russian"],"усатый":["russian"],"усвоить":["russian"],"усилие":["russian"],"условие":["russian"],"услуга":["russian"],"усмешка":["russian"],"успеть":["russian"],"устав":["russian"],"устоять":["russian"],"утечка":["russian"],"утешать":["russian"],"утро":["russian"],"уцелеть":["russian"],"участие":["russian"],"ученик":["russian"],"учесть":["russian"],"ущелье":["russian"],"ущерб":["russian"],"уютный":["russian"],"фабрика":["russian"],"фаворит":["russian"],"факел":["russian"],"факт":["russian"],"фамилия":["russian"],"фантазия":["russian"],"фасад":["russian"],"февраль":["russian"],"феномен":["russian"],"фермер":["russian"],"фигура":["russian"],"физика":["russian"],"филиал":["russian"],"философ":["russian"],"фильм":["russian"],"финал":["russian"],"флаг":["russian"],"флот":["russian"],"фойе":["russian"],"фокус":["russian"],"фонарь":["russian"],"фонд":["russian"],"фонтан":["russian"],"форма":["russian"],"форум":["russian"],"фото":["russian"],"фрагмент":["russian"],"фраза":["russian"],"фракция":["russian"],"фронт":["russian"],"фрукт":["russian"],"функция":["russian"],"фуражка":["russian"],"футбол":["russian"],"футляр":["russian"],"халат":["russian"],"хаос":["russian"],"характер":["russian"],"хата":["russian"],"хвалить":["russian"],"хватать":["russian"],"хвойный":["russian"],"хвост":["russian"],"химия":["russian"],"хирург":["russian"],"хитрый":["russian"],"хищник":["russian"],"хлеб":["russian"],"хлынуть":["russian"],"хмурый":["russian"],"ходить":["russian"],"хозяин":["russian"],"хоккей":["russian"],"холм":["russian"],"холст":["russian"],"хорошо":["russian"],"хотеть":["russian"],"храбрый":["russian"],"храм":["russian"],"хранить":["russian"],"хребет":["russian"],"хрен":["russian"],"хрипло":["russian"],"хроника":["russian"],"хрупкий":["russian"],"художник":["russian"],"худший":["russian"],"хулиган":["russian"],"хутор":["russian"],"царь":["russian"],"цветок":["russian"],"целевой":["russian"],"целиком":["russian"],"целое":["russian"],"цель":["russian"],"цензура":["russian"],"ценить":["russian"],"центр":["russian"],"цепной":["russian"],"цикл":["russian"],"цилиндр":["russian"],"цирк":["russian"],"цитата":["russian"],"цифра":["russian"],"чайник":["russian"],"часы":["russian"],"чашка":["russian"],"человек":["russian"],"челюсть":["russian"],"чемодан":["russian"],"чемпион":["russian"],"чепуха":["russian"],"червь":["russian"],"чердак":["russian"],"через":["russian"],"чернила":["russian"],"черта":["russian"],"чеснок":["russian"],"честно":["russian"],"четверть":["russian"],"четыре":["russian"],"число":["russian"],"чистый":["russian"],"читатель":["russian"],"чтение":["russian"],"чтобы":["russian"],"чувство":["russian"],"чудак":["russian"],"чудный":["russian"],"чудо":["russian"],"чужой":["russian"],"чулок":["russian"],"чума":["russian"],"чушь":["russian"],"чуять":["russian"],"шагать":["russian"],"шанс":["russian"],"шапка":["russian"],"шарик":["russian"],"шарф":["russian"],"шахматы":["russian"],"шашлык":["russian"],"шедевр":["russian"],"шептать":["russian"],"шерсть":["russian"],"шестой":["russian"],"шинель":["russian"],"ширина":["russian"],"шишка":["russian"],"шкаф":["russian"],"школа":["russian"],"шкура":["russian"],"шланг":["russian"],"шлем":["russian"],"шнур":["russian"],"шоколад":["russian"],"шорох":["russian"],"шоссе":["russian"],"шпион":["russian"],"шприц":["russian"],"штаб":["russian"],"штамм":["russian"],"штаны":["russian"],"штатный":["russian"],"штора":["russian"],"штраф":["russian"],"штурм":["russian"],"штык":["russian"],"шумно":["russian"],"шуршать":["russian"],"шутить":["russian"],"шутка":["russian"],"щедрый":["russian"],"щека":["russian"],"щенок":["russian"],"экзамен":["russian"],"экипаж":["russian"],"экономия":["russian"],"экран":["russian"],"эксперт":["russian"],"элемент":["russian"],"элитный":["russian"],"эмоция":["russian"],"энергия":["russian"],"эпизод":["russian"],"эпоха":["russian"],"эскиз":["russian"],"эстрада":["russian"],"этап":["russian"],"этика":["russian"],"этот":["russian"],"эфир":["russian"],"эффект":["russian"],"эшелон":["russian"],"юбилей":["russian"],"юбка":["russian"],"южный":["russian"],"юмор":["russian"],"юность":["russian"],"юрист":["russian"],"юстиция":["russian"],"яблоко":["russian"],"явление":["russian"],"ягода":["russian"],"ядро":["russian"],"язык":["russian"],"яйцо":["russian"],"якобы":["russian"],"якорь":["russian"],"январь":["russian"],"яркий":["russian"],"ярмарка":["russian"],"ярость":["russian"],"ясный":["russian"],"яхта":["russian"],"ячейка":["russian"],"ящик":["russian"],"ábaco":["spanish"],"abdomen":["spanish"],"abeja":["spanish"],"abierto":["spanish"],"abogado":["spanish"],"abono":["spanish"],"aborto":["spanish"],"abrazo":["spanish"],"abrir":["spanish"],"abuelo":["spanish"],"abuso":["spanish"],"acabar":["spanish"],"academia":["spanish"],"acceso":["spanish"],"acción":["spanish"],"aceite":["spanish"],"acelga":["spanish"],"acento":["spanish"],"aceptar":["spanish"],"ácido":["spanish"],"aclarar":["spanish"],"acné":["spanish"],"acoger":["spanish"],"acoso":["spanish"],"activo":["spanish"],"acto":["spanish"],"actriz":["spanish"],"actuar":["spanish"],"acudir":["spanish"],"acuerdo":["spanish"],"acusar":["spanish"],"adicto":["spanish"],"admitir":["spanish"],"adoptar":["spanish"],"adorno":["spanish"],"aduana":["spanish"],"adulto":["spanish"],"aéreo":["spanish"],"afectar":["spanish"],"afición":["spanish"],"afinar":["spanish"],"afirmar":["spanish"],"ágil":["spanish"],"agitar":["spanish"],"agonía":["spanish"],"agosto":["spanish"],"agotar":["spanish"],"agregar":["spanish"],"agrio":["spanish"],"agua":["spanish"],"agudo":["spanish"],"águila":["spanish"],"aguja":["spanish"],"ahogo":["spanish"],"ahorro":["spanish"],"aire":["spanish"],"aislar":["spanish"],"ajedrez":["spanish"],"ajeno":["spanish"],"ajuste":["spanish"],"alacrán":["spanish"],"alambre":["spanish"],"alarma":["spanish"],"alba":["spanish"],"álbum":["spanish"],"alcalde":["spanish"],"aldea":["spanish"],"alegre":["spanish"],"alejar":["spanish"],"alerta":["spanish"],"aleta":["spanish"],"alfiler":["spanish"],"alga":["spanish"],"algodón":["spanish"],"aliado":["spanish"],"aliento":["spanish"],"alivio":["spanish"],"alma":["spanish"],"almeja":["spanish"],"almíbar":["spanish"],"altar":["spanish"],"alteza":["spanish"],"altivo":["spanish"],"alto":["spanish"],"altura":["spanish"],"alumno":["spanish"],"alzar":["spanish"],"amable":["spanish"],"amante":["spanish"],"amapola":["spanish"],"amargo":["spanish"],"amasar":["spanish"],"ámbar":["spanish"],"ámbito":["spanish"],"ameno":["spanish"],"amigo":["spanish","turkish"],"amistad":["spanish"],"amor":["spanish"],"amparo":["spanish"],"amplio":["spanish"],"ancho":["spanish"],"anciano":["spanish"],"ancla":["spanish"],"andar":["spanish"],"andén":["spanish"],"anemia":["spanish"],"ángulo":["spanish"],"anillo":["spanish"],"ánimo":["spanish"],"anís":["spanish"],"anotar":["spanish"],"antena":["spanish"],"antiguo":["spanish"],"antojo":["spanish"],"anual":["spanish"],"anular":["spanish"],"anuncio":["spanish"],"añadir":["spanish"],"añejo":["spanish"],"año":["spanish"],"apagar":["spanish"],"aparato":["spanish"],"apetito":["spanish"],"apio":["spanish"],"aplicar":["spanish"],"apodo":["spanish"],"aporte":["spanish"],"apoyo":["spanish"],"aprender":["spanish"],"aprobar":["spanish"],"apuesta":["spanish"],"apuro":["spanish"],"arado":["spanish"],"araña":["spanish"],"arar":["spanish"],"árbitro":["spanish"],"árbol":["spanish"],"arbusto":["spanish"],"archivo":["spanish"],"arco":["spanish"],"arder":["spanish"],"ardilla":["spanish"],"arduo":["spanish"],"área":["spanish"],"árido":["spanish"],"aries":["spanish"],"armonía":["spanish"],"arnés":["spanish"],"aroma":["spanish","turkish"],"arpa":["spanish"],"arpón":["spanish"],"arreglo":["spanish"],"arroz":["spanish"],"arruga":["spanish"],"arte":["spanish"],"artista":["spanish"],"asa":["spanish"],"asado":["spanish"],"asalto":["spanish"],"ascenso":["spanish"],"asegurar":["spanish"],"aseo":["spanish"],"asesor":["spanish"],"asiento":["spanish"],"asilo":["spanish"],"asistir":["spanish"],"asno":["spanish"],"asombro":["spanish"],"áspero":["spanish"],"astilla":["spanish"],"astro":["spanish"],"astuto":["spanish"],"asumir":["spanish"],"asunto":["spanish"],"atajo":["spanish"],"ataque":["spanish"],"atar":["spanish"],"atento":["spanish"],"ateo":["spanish"],"ático":["spanish"],"atleta":["spanish"],"átomo":["spanish"],"atraer":["spanish"],"atroz":["spanish"],"atún":["spanish"],"audaz":["spanish"],"audio":["spanish"],"auge":["spanish"],"aula":["spanish"],"aumento":["spanish"],"ausente":["spanish"],"autor":["spanish"],"aval":["spanish"],"avance":["spanish"],"avaro":["spanish"],"ave":["spanish"],"avellana":["spanish"],"avena":["spanish"],"avestruz":["spanish"],"avión":["spanish"],"aviso":["spanish"],"ayer":["spanish"],"ayuda":["spanish"],"ayuno":["spanish"],"azafrán":["spanish"],"azar":["spanish"],"azote":["spanish"],"azúcar":["spanish"],"azufre":["spanish"],"azul":["spanish"],"baba":["spanish"],"babor":["spanish"],"bache":["spanish"],"bahía":["spanish"],"baile":["spanish"],"bajar":["spanish"],"balanza":["spanish"],"balcón":["spanish"],"balde":["spanish"],"bambú":["spanish"],"banco":["spanish"],"banda":["spanish"],"baño":["spanish"],"barba":["spanish"],"barco":["spanish"],"barniz":["spanish"],"barro":["spanish"],"báscula":["spanish"],"bastón":["spanish"],"basura":["spanish"],"batalla":["spanish"],"batería":["spanish"],"batir":["spanish"],"batuta":["spanish"],"baúl":["spanish"],"bazar":["spanish"],"bebé":["spanish"],"bebida":["spanish"],"bello":["spanish"],"besar":["spanish"],"beso":["spanish"],"bestia":["spanish"],"bicho":["spanish"],"bien":["spanish"],"bingo":["spanish"],"blanco":["spanish"],"bloque":["spanish"],"blusa":["spanish"],"boa":["spanish"],"bobina":["spanish"],"bobo":["spanish"],"boca":["spanish"],"bocina":["spanish"],"boda":["spanish"],"bodega":["spanish"],"boina":["spanish"],"bola":["spanish"],"bolero":["spanish","turkish"],"bolsa":["spanish"],"bomba":["spanish"],"bondad":["spanish"],"bonito":["spanish"],"bono":["spanish"],"bonsái":["spanish"],"borde":["spanish"],"borrar":["spanish"],"bosque":["spanish"],"bote":["spanish"],"botín":["spanish"],"bóveda":["spanish"],"bozal":["spanish"],"bravo":["spanish"],"brazo":["spanish"],"brecha":["spanish"],"breve":["spanish"],"brillo":["spanish"],"brinco":["spanish"],"brisa":["spanish"],"broca":["spanish"],"broma":["spanish"],"bronce":["spanish"],"brote":["spanish"],"bruja":["spanish"],"brusco":["spanish"],"bruto":["spanish"],"buceo":["spanish"],"bucle":["spanish"],"bueno":["spanish"],"buey":["spanish"],"bufanda":["spanish"],"bufón":["spanish"],"búho":["spanish"],"buitre":["spanish"],"bulto":["spanish"],"burbuja":["spanish"],"burla":["spanish"],"burro":["spanish"],"buscar":["spanish"],"butaca":["spanish"],"buzón":["spanish"],"caballo":["spanish"],"cabeza":["spanish"],"cabina":["spanish"],"cabra":["spanish"],"cacao":["spanish"],"cadáver":["spanish"],"cadena":["spanish"],"caer":["spanish"],"café":["spanish"],"caída":["spanish"],"caimán":["spanish"],"caja":["spanish"],"cajón":["spanish"],"cal":["spanish"],"calamar":["spanish"],"calcio":["spanish"],"caldo":["spanish"],"calidad":["spanish"],"calle":["spanish"],"calma":["spanish"],"calor":["spanish"],"calvo":["spanish"],"cama":["spanish"],"cambio":["spanish"],"camello":["spanish"],"camino":["spanish"],"campo":["spanish"],"cáncer":["spanish"],"candil":["spanish"],"canela":["spanish"],"canguro":["spanish"],"canica":["spanish"],"canto":["spanish"],"caña":["spanish"],"cañón":["spanish"],"caoba":["spanish"],"caos":["spanish"],"capaz":["spanish"],"capitán":["spanish"],"capote":["spanish"],"captar":["spanish"],"capucha":["spanish"],"cara":["spanish"],"carbón":["spanish"],"cárcel":["spanish"],"careta":["spanish"],"carga":["spanish"],"cariño":["spanish"],"carne":["spanish"],"carpeta":["spanish"],"carro":["spanish"],"carta":["spanish"],"casa":["spanish"],"casco":["spanish"],"casero":["spanish"],"caspa":["spanish"],"castor":["spanish"],"catorce":["spanish"],"catre":["spanish"],"caudal":["spanish"],"causa":["spanish"],"cazo":["spanish"],"cebolla":["spanish"],"ceder":["spanish"],"cedro":["spanish"],"celda":["spanish"],"célebre":["spanish"],"celoso":["spanish"],"célula":["spanish"],"cemento":["spanish"],"ceniza":["spanish"],"centro":["spanish"],"cerca":["spanish"],"cerdo":["spanish"],"cereza":["spanish"],"cero":["spanish"],"cerrar":["spanish"],"certeza":["spanish"],"césped":["spanish"],"cetro":["spanish"],"chacal":["spanish"],"chaleco":["spanish"],"champú":["spanish"],"chancla":["spanish"],"chapa":["spanish"],"charla":["spanish"],"chico":["spanish"],"chiste":["spanish"],"chivo":["spanish"],"choque":["spanish"],"choza":["spanish"],"chuleta":["spanish"],"chupar":["spanish"],"ciclón":["spanish"],"ciego":["spanish"],"cielo":["spanish"],"cien":["spanish"],"cierto":["spanish"],"cifra":["spanish"],"cigarro":["spanish"],"cima":["spanish"],"cinco":["spanish"],"cine":["spanish"],"cinta":["spanish"],"ciprés":["spanish"],"circo":["spanish"],"ciruela":["spanish"],"cisne":["spanish"],"cita":["spanish"],"ciudad":["spanish"],"clamor":["spanish"],"clan":["spanish"],"claro":["spanish"],"clase":["spanish"],"clave":["spanish"],"cliente":["spanish"],"clima":["spanish"],"clínica":["spanish"],"cobre":["spanish"],"cocción":["spanish"],"cochino":["spanish"],"cocina":["spanish"],"coco":["spanish"],"código":["spanish"],"codo":["spanish"],"cofre":["spanish"],"coger":["spanish"],"cohete":["spanish"],"cojín":["spanish"],"cojo":["spanish"],"cola":["spanish"],"colcha":["spanish"],"colegio":["spanish"],"colgar":["spanish"],"colina":["spanish"],"collar":["spanish"],"colmo":["spanish"],"columna":["spanish"],"combate":["spanish"],"comer":["spanish"],"comida":["spanish"],"cómodo":["spanish"],"compra":["spanish"],"conde":["spanish"],"conejo":["spanish"],"conga":["spanish"],"conocer":["spanish"],"consejo":["spanish"],"contar":["spanish"],"copa":["spanish"],"copia":["spanish"],"corazón":["spanish"],"corbata":["spanish"],"corcho":["spanish"],"cordón":["spanish"],"corona":["spanish"],"correr":["spanish"],"coser":["spanish"],"cosmos":["spanish"],"costa":["spanish"],"cráneo":["spanish"],"cráter":["spanish"],"crear":["spanish"],"crecer":["spanish"],"creído":["spanish"],"crema":["spanish"],"cría":["spanish"],"crimen":["spanish"],"cripta":["spanish"],"crisis":["spanish"],"cromo":["spanish"],"crónica":["spanish"],"croqueta":["spanish"],"crudo":["spanish"],"cruz":["spanish"],"cuadro":["spanish"],"cuarto":["spanish"],"cuatro":["spanish"],"cubo":["spanish"],"cubrir":["spanish"],"cuchara":["spanish"],"cuello":["spanish"],"cuento":["spanish"],"cuerda":["spanish"],"cuesta":["spanish"],"cueva":["spanish"],"cuidar":["spanish"],"culebra":["spanish"],"culpa":["spanish"],"culto":["spanish"],"cumbre":["spanish"],"cumplir":["spanish"],"cuna":["spanish"],"cuneta":["spanish"],"cuota":["spanish"],"cupón":["spanish"],"cúpula":["spanish"],"curar":["spanish"],"curioso":["spanish"],"curso":["spanish"],"curva":["spanish"],"cutis":["spanish"],"dama":["spanish"],"danza":["spanish"],"dar":["spanish"],"dardo":["spanish"],"dátil":["spanish"],"deber":["spanish"],"débil":["spanish"],"década":["spanish"],"decir":["spanish"],"dedo":["spanish"],"defensa":["spanish"],"definir":["spanish"],"dejar":["spanish"],"delfín":["spanish"],"delgado":["spanish"],"delito":["spanish"],"demora":["spanish"],"denso":["spanish"],"dental":["spanish"],"deporte":["spanish"],"derecho":["spanish"],"derrota":["spanish"],"desayuno":["spanish"],"deseo":["spanish"],"desfile":["spanish"],"desnudo":["spanish"],"destino":["spanish"],"desvío":["spanish"],"detalle":["spanish"],"detener":["spanish"],"deuda":["spanish"],"día":["spanish"],"diablo":["spanish"],"diadema":["spanish"],"diamante":["spanish"],"diana":["spanish"],"diario":["spanish"],"dibujo":["spanish"],"dictar":["spanish"],"diente":["spanish"],"dieta":["spanish"],"diez":["spanish"],"difícil":["spanish"],"digno":["spanish"],"dilema":["spanish"],"diluir":["spanish"],"dinero":["spanish"],"directo":["spanish"],"dirigir":["spanish"],"disco":["spanish"],"diseño":["spanish"],"disfraz":["spanish"],"diva":["spanish"],"divino":["spanish"],"doble":["spanish"],"doce":["spanish"],"dolor":["spanish"],"domingo":["spanish"],"don":["spanish"],"donar":["spanish"],"dorado":["spanish"],"dormir":["spanish"],"dorso":["spanish"],"dos":["spanish"],"dosis":["spanish"],"dragón":["spanish"],"droga":["spanish"],"ducha":["spanish"],"duda":["spanish"],"duelo":["spanish"],"dueño":["spanish"],"dulce":["spanish"],"dúo":["spanish"],"duque":["spanish"],"durar":["spanish"],"dureza":["spanish"],"duro":["spanish"],"ébano":["spanish"],"ebrio":["spanish"],"echar":["spanish"],"eco":["spanish"],"ecuador":["spanish"],"edad":["spanish"],"edición":["spanish"],"edificio":["spanish"],"editor":["spanish"],"educar":["spanish"],"efecto":["spanish"],"eficaz":["spanish"],"eje":["spanish"],"ejemplo":["spanish"],"elefante":["spanish"],"elegir":["spanish"],"elemento":["spanish"],"elevar":["spanish"],"elipse":["spanish"],"élite":["spanish"],"elixir":["spanish"],"elogio":["spanish"],"eludir":["spanish"],"embudo":["spanish"],"emitir":["spanish"],"emoción":["spanish"],"empate":["spanish"],"empeño":["spanish"],"empleo":["spanish"],"empresa":["spanish"],"enano":["spanish"],"encargo":["spanish"],"enchufe":["spanish"],"encía":["spanish"],"enemigo":["spanish"],"enero":["spanish"],"enfado":["spanish"],"enfermo":["spanish"],"engaño":["spanish"],"enigma":["spanish"],"enlace":["spanish"],"enorme":["spanish"],"enredo":["spanish"],"ensayo":["spanish"],"enseñar":["spanish"],"entero":["spanish"],"entrar":["spanish"],"envase":["spanish"],"envío":["spanish"],"época":["spanish"],"equipo":["spanish"],"erizo":["spanish"],"escala":["spanish"],"escena":["spanish"],"escolar":["spanish"],"escribir":["spanish"],"escudo":["spanish"],"esencia":["spanish"],"esfera":["spanish"],"esfuerzo":["spanish"],"espada":["spanish"],"espejo":["spanish"],"espía":["spanish"],"esposa":["spanish"],"espuma":["spanish"],"esquí":["spanish"],"estar":["spanish"],"este":["spanish"],"estilo":["spanish"],"estufa":["spanish"],"etapa":["spanish"],"eterno":["spanish"],"ética":["spanish"],"etnia":["spanish"],"evadir":["spanish"],"evaluar":["spanish"],"evento":["spanish"],"evitar":["spanish"],"exacto":["spanish"],"examen":["spanish"],"exceso":["spanish"],"excusa":["spanish"],"exento":["spanish"],"exigir":["spanish"],"exilio":["spanish"],"existir":["spanish"],"éxito":["spanish"],"experto":["spanish"],"explicar":["spanish"],"exponer":["spanish"],"extremo":["spanish"],"fábrica":["spanish"],"fábula":["spanish"],"fachada":["spanish"],"fácil":["spanish"],"factor":["spanish"],"faena":["spanish"],"faja":["spanish"],"falda":["spanish"],"fallo":["spanish"],"falso":["spanish"],"faltar":["spanish"],"fama":["spanish"],"familia":["spanish"],"famoso":["spanish"],"faraón":["spanish"],"farmacia":["spanish"],"farol":["spanish"],"farsa":["spanish"],"fase":["spanish"],"fatiga":["spanish"],"fauna":["spanish","turkish"],"favor":["spanish"],"fax":["spanish"],"febrero":["spanish"],"fecha":["spanish"],"feliz":["spanish"],"feo":["spanish"],"feria":["spanish"],"feroz":["spanish"],"fértil":["spanish"],"fervor":["spanish"],"festín":["spanish"],"fiable":["spanish"],"fianza":["spanish"],"fiar":["spanish"],"fibra":["spanish"],"ficción":["spanish"],"ficha":["spanish"],"fideo":["spanish"],"fiebre":["spanish"],"fiel":["spanish"],"fiera":["spanish"],"fiesta":["spanish"],"figura":["spanish"],"fijar":["spanish"],"fijo":["spanish"],"fila":["spanish"],"filete":["spanish"],"filial":["spanish"],"filtro":["spanish"],"fin":["spanish"],"finca":["spanish"],"fingir":["spanish"],"finito":["spanish"],"firma":["spanish"],"flaco":["spanish"],"flauta":["spanish"],"flecha":["spanish"],"flor":["spanish"],"flota":["spanish"],"fluir":["spanish"],"flujo":["spanish"],"flúor":["spanish"],"fobia":["spanish"],"foca":["spanish"],"fogata":["spanish"],"fogón":["spanish"],"folio":["spanish"],"folleto":["spanish"],"fondo":["spanish"],"forma":["spanish"],"forro":["spanish"],"fortuna":["spanish"],"forzar":["spanish"],"fosa":["spanish"],"foto":["spanish"],"fracaso":["spanish"],"frágil":["spanish"],"franja":["spanish"],"frase":["spanish"],"fraude":["spanish"],"freír":["spanish"],"freno":["spanish"],"fresa":["spanish"],"frío":["spanish"],"frito":["spanish"],"fruta":["spanish"],"fuego":["spanish"],"fuente":["spanish"],"fuerza":["spanish"],"fuga":["spanish"],"fumar":["spanish"],"función":["spanish"],"funda":["spanish"],"furgón":["spanish"],"furia":["spanish"],"fusil":["spanish"],"fútbol":["spanish"],"futuro":["spanish"],"gacela":["spanish"],"gafas":["spanish"],"gaita":["spanish"],"gajo":["spanish"],"gala":["spanish"],"galería":["spanish"],"gallo":["spanish"],"gamba":["spanish"],"ganar":["spanish"],"gancho":["spanish"],"ganga":["spanish"],"ganso":["spanish"],"garaje":["spanish"],"garza":["spanish"],"gasolina":["spanish"],"gastar":["spanish"],"gato":["spanish"],"gavilán":["spanish"],"gemelo":["spanish"],"gemir":["spanish"],"gen":["spanish"],"género":["spanish"],"genio":["spanish"],"gente":["spanish"],"geranio":["spanish"],"gerente":["spanish"],"germen":["spanish"],"gesto":["spanish"],"gigante":["spanish"],"gimnasio":["spanish"],"girar":["spanish"],"giro":["spanish"],"glaciar":["spanish"],"globo":["spanish"],"gloria":["spanish"],"gol":["spanish"],"golfo":["spanish"],"goloso":["spanish"],"golpe":["spanish"],"goma":["spanish"],"gordo":["spanish"],"gorila":["spanish"],"gorra":["spanish"],"gota":["spanish"],"goteo":["spanish"],"gozar":["spanish"],"grada":["spanish"],"gráfico":["spanish"],"grano":["spanish"],"grasa":["spanish"],"gratis":["spanish"],"grave":["spanish"],"grieta":["spanish"],"grillo":["spanish"],"gripe":["spanish"],"gris":["spanish"],"grito":["spanish"],"grosor":["spanish"],"grúa":["spanish"],"grueso":["spanish"],"grumo":["spanish"],"grupo":["spanish"],"guante":["spanish"],"guapo":["spanish"],"guardia":["spanish"],"guerra":["spanish"],"guía":["spanish"],"guiño":["spanish"],"guion":["spanish"],"guiso":["spanish"],"guitarra":["spanish"],"gusano":["spanish"],"gustar":["spanish"],"haber":["spanish","turkish"],"hábil":["spanish"],"hablar":["spanish"],"hacer":["spanish"],"hacha":["spanish"],"hada":["spanish"],"hallar":["spanish"],"hamaca":["spanish"],"harina":["spanish"],"haz":["spanish"],"hazaña":["spanish"],"hebilla":["spanish"],"hebra":["spanish"],"hecho":["spanish"],"helado":["spanish"],"helio":["spanish"],"hembra":["spanish"],"herir":["spanish"],"hermano":["spanish"],"héroe":["spanish"],"hervir":["spanish"],"hielo":["spanish"],"hierro":["spanish"],"hígado":["spanish"],"higiene":["spanish"],"hijo":["spanish"],"himno":["spanish"],"historia":["spanish"],"hocico":["spanish"],"hogar":["spanish"],"hoguera":["spanish"],"hoja":["spanish"],"hombre":["spanish"],"hongo":["spanish"],"honor":["spanish"],"honra":["spanish"],"hora":["spanish"],"hormiga":["spanish"],"horno":["spanish"],"hostil":["spanish"],"hoyo":["spanish"],"hueco":["spanish"],"huelga":["spanish"],"huerta":["spanish"],"hueso":["spanish"],"huevo":["spanish"],"huida":["spanish"],"huir":["spanish"],"humano":["spanish"],"húmedo":["spanish"],"humilde":["spanish"],"humo":["spanish"],"hundir":["spanish"],"huracán":["spanish"],"hurto":["spanish"],"icono":["spanish"],"ideal":["spanish"],"idioma":["spanish"],"ídolo":["spanish"],"iglesia":["spanish"],"iglú":["spanish"],"igual":["spanish"],"ilegal":["spanish"],"ilusión":["spanish"],"imagen":["spanish"],"imán":["spanish"],"imitar":["spanish"],"impar":["spanish"],"imperio":["spanish"],"imponer":["spanish"],"impulso":["spanish"],"incapaz":["spanish"],"índice":["spanish"],"inerte":["spanish"],"infiel":["spanish"],"informe":["spanish"],"ingenio":["spanish"],"inicio":["spanish"],"inmenso":["spanish"],"inmune":["spanish"],"innato":["spanish"],"insecto":["spanish"],"instante":["spanish"],"interés":["spanish"],"íntimo":["spanish"],"intuir":["spanish"],"inútil":["spanish"],"invierno":["spanish"],"ira":["spanish"],"iris":["spanish"],"ironía":["spanish"],"isla":["spanish"],"islote":["spanish"],"jabalí":["spanish"],"jabón":["spanish"],"jamón":["spanish"],"jarabe":["spanish"],"jardín":["spanish"],"jarra":["spanish"],"jaula":["spanish"],"jazmín":["spanish"],"jefe":["spanish"],"jeringa":["spanish"],"jinete":["spanish"],"jornada":["spanish"],"joroba":["spanish"],"joven":["spanish"],"joya":["spanish"],"juerga":["spanish"],"jueves":["spanish"],"juez":["spanish"],"jugador":["spanish"],"jugo":["spanish"],"juguete":["spanish"],"juicio":["spanish"],"junco":["spanish"],"jungla":["spanish"],"junio":["spanish"],"juntar":["spanish"],"júpiter":["spanish"],"jurar":["spanish"],"justo":["spanish"],"juvenil":["spanish"],"juzgar":["spanish"],"kilo":["spanish"],"koala":["spanish"],"labio":["spanish"],"lacio":["spanish"],"lacra":["spanish"],"lado":["spanish"],"ladrón":["spanish"],"lagarto":["spanish"],"lágrima":["spanish"],"laguna":["spanish"],"laico":["spanish"],"lamer":["spanish"],"lámina":["spanish"],"lámpara":["spanish"],"lana":["spanish"],"lancha":["spanish"],"langosta":["spanish"],"lanza":["spanish"],"lápiz":["spanish"],"largo":["spanish"],"larva":["spanish"],"lástima":["spanish"],"lata":["spanish"],"látex":["spanish"],"latir":["spanish"],"laurel":["spanish"],"lavar":["spanish"],"lazo":["spanish"],"leal":["spanish"],"lección":["spanish"],"leche":["spanish"],"lector":["spanish"],"leer":["spanish"],"legión":["spanish"],"legumbre":["spanish"],"lejano":["spanish"],"lengua":["spanish"],"lento":["spanish"],"leña":["spanish"],"león":["spanish"],"leopardo":["spanish"],"lesión":["spanish"],"letal":["spanish"],"letra":["spanish"],"leve":["spanish"],"leyenda":["spanish"],"libertad":["spanish"],"libro":["spanish"],"licor":["spanish"],"líder":["spanish"],"lidiar":["spanish"],"lienzo":["spanish"],"liga":["spanish"],"ligero":["spanish"],"lima":["spanish"],"límite":["spanish"],"limón":["spanish"],"limpio":["spanish"],"lince":["spanish"],"lindo":["spanish"],"línea":["spanish"],"lingote":["spanish"],"lino":["spanish"],"linterna":["spanish"],"líquido":["spanish"],"liso":["spanish"],"lista":["spanish"],"litera":["spanish"],"litio":["spanish"],"litro":["spanish"],"llaga":["spanish"],"llama":["spanish"],"llanto":["spanish"],"llave":["spanish"],"llegar":["spanish"],"llenar":["spanish"],"llevar":["spanish"],"llorar":["spanish"],"llover":["spanish"],"lluvia":["spanish"],"lobo":["spanish"],"loción":["spanish"],"loco":["spanish"],"locura":["spanish"],"lógica":["spanish"],"logro":["spanish"],"lombriz":["spanish"],"lomo":["spanish"],"lonja":["spanish"],"lote":["spanish"],"lucha":["spanish"],"lucir":["spanish"],"lugar":["spanish"],"lujo":["spanish"],"luna":["spanish"],"lunes":["spanish"],"lupa":["spanish"],"lustro":["spanish"],"luto":["spanish"],"luz":["spanish"],"maceta":["spanish"],"macho":["spanish"],"madera":["spanish"],"madre":["spanish"],"maduro":["spanish"],"maestro":["spanish"],"mafia":["spanish"],"magia":["spanish"],"mago":["spanish"],"maíz":["spanish"],"maldad":["spanish"],"maleta":["spanish"],"malla":["spanish"],"malo":["spanish"],"mamá":["spanish"],"mambo":["spanish"],"mamut":["spanish"],"manco":["spanish"],"mando":["spanish"],"manejar":["spanish"],"manga":["spanish"],"maniquí":["spanish"],"manjar":["spanish"],"mano":["spanish"],"manso":["spanish"],"manta":["spanish"],"mañana":["spanish"],"mapa":["spanish"],"máquina":["spanish"],"mar":["spanish"],"marco":["spanish"],"marea":["spanish"],"marfil":["spanish"],"margen":["spanish"],"marido":["spanish"],"mármol":["spanish"],"marrón":["spanish"],"martes":["spanish"],"marzo":["spanish"],"masa":["spanish"],"máscara":["spanish"],"masivo":["spanish"],"matar":["spanish"],"materia":["spanish"],"matiz":["spanish"],"matriz":["spanish"],"máximo":["spanish"],"mayor":["spanish"],"mazorca":["spanish"],"mecha":["spanish"],"medalla":["spanish"],"medio":["spanish"],"médula":["spanish"],"mejilla":["spanish"],"mejor":["spanish"],"melena":["spanish"],"melón":["spanish"],"memoria":["spanish"],"menor":["spanish"],"mensaje":["spanish"],"mente":["spanish"],"menú":["spanish"],"mercado":["spanish"],"merengue":["spanish"],"mérito":["spanish"],"mes":["spanish"],"mesón":["spanish"],"meta":["spanish"],"meter":["spanish"],"método":["spanish"],"metro":["spanish"],"mezcla":["spanish"],"miedo":["spanish"],"miel":["spanish"],"miembro":["spanish"],"miga":["spanish"],"mil":["spanish"],"milagro":["spanish"],"militar":["spanish"],"millón":["spanish"],"mimo":["spanish"],"mina":["spanish"],"minero":["spanish"],"mínimo":["spanish"],"minuto":["spanish"],"miope":["spanish"],"mirar":["spanish"],"misa":["spanish"],"miseria":["spanish"],"misil":["spanish"],"mismo":["spanish"],"mitad":["spanish"],"mito":["spanish"],"mochila":["spanish"],"moción":["spanish"],"moda":["spanish"],"modelo":["spanish"],"moho":["spanish"],"mojar":["spanish"],"molde":["spanish"],"moler":["spanish"],"molino":["spanish"],"momento":["spanish"],"momia":["spanish"],"monarca":["spanish"],"moneda":["spanish"],"monja":["spanish"],"monto":["spanish"],"moño":["spanish"],"morada":["spanish"],"morder":["spanish"],"moreno":["spanish"],"morir":["spanish"],"morro":["spanish"],"morsa":["spanish"],"mortal":["spanish"],"mosca":["spanish"],"mostrar":["spanish"],"motivo":["spanish"],"mover":["spanish"],"móvil":["spanish"],"mozo":["spanish"],"mucho":["spanish"],"mudar":["spanish"],"mueble":["spanish"],"muela":["spanish"],"muerte":["spanish"],"muestra":["spanish"],"mugre":["spanish"],"mujer":["spanish"],"mula":["spanish"],"muleta":["spanish"],"multa":["spanish"],"mundo":["spanish"],"muñeca":["spanish"],"mural":["spanish"],"muro":["spanish"],"músculo":["spanish"],"museo":["spanish"],"musgo":["spanish"],"música":["spanish"],"muslo":["spanish"],"nácar":["spanish"],"nación":["spanish"],"nadar":["spanish"],"naipe":["spanish"],"naranja":["spanish"],"nariz":["spanish"],"narrar":["spanish"],"nasal":["spanish"],"natal":["spanish"],"nativo":["spanish"],"natural":["spanish"],"náusea":["spanish"],"naval":["spanish"],"nave":["spanish"],"navidad":["spanish"],"necio":["spanish"],"néctar":["spanish"],"negar":["spanish"],"negocio":["spanish"],"negro":["spanish"],"neón":["spanish"],"nervio":["spanish"],"neto":["spanish"],"neutro":["spanish"],"nevar":["spanish"],"nevera":["spanish"],"nicho":["spanish"],"nido":["spanish"],"niebla":["spanish"],"nieto":["spanish"],"niñez":["spanish"],"niño":["spanish"],"nítido":["spanish"],"nivel":["spanish"],"nobleza":["spanish"],"noche":["spanish"],"nómina":["spanish"],"noria":["spanish"],"norma":["spanish"],"norte":["spanish"],"nota":["spanish"],"noticia":["spanish"],"novato":["spanish"],"novela":["spanish"],"novio":["spanish"],"nube":["spanish"],"nuca":["spanish"],"núcleo":["spanish"],"nudillo":["spanish"],"nudo":["spanish"],"nuera":["spanish"],"nueve":["spanish"],"nuez":["spanish"],"nulo":["spanish"],"número":["spanish"],"nutria":["spanish"],"oasis":["spanish"],"obeso":["spanish"],"obispo":["spanish"],"objeto":["spanish"],"obra":["spanish"],"obrero":["spanish"],"observar":["spanish"],"obtener":["spanish"],"obvio":["spanish"],"oca":["spanish"],"ocaso":["spanish"],"océano":["spanish"],"ochenta":["spanish"],"ocho":["spanish"],"ocio":["spanish"],"ocre":["spanish"],"octavo":["spanish"],"octubre":["spanish"],"oculto":["spanish"],"ocupar":["spanish"],"ocurrir":["spanish"],"odiar":["spanish"],"odio":["spanish"],"odisea":["spanish"],"oeste":["spanish"],"ofensa":["spanish"],"oferta":["spanish"],"oficio":["spanish"],"ofrecer":["spanish"],"ogro":["spanish"],"oído":["spanish"],"oír":["spanish"],"ojo":["spanish"],"ola":["spanish"],"oleada":["spanish"],"olfato":["spanish"],"olivo":["spanish"],"olla":["spanish"],"olmo":["spanish"],"olor":["spanish"],"olvido":["spanish"],"ombligo":["spanish"],"onda":["spanish"],"onza":["spanish"],"opaco":["spanish"],"opción":["spanish"],"ópera":["spanish"],"opinar":["spanish"],"oponer":["spanish"],"optar":["spanish"],"óptica":["spanish"],"opuesto":["spanish"],"oración":["spanish"],"orador":["spanish"],"oral":["spanish","turkish"],"órbita":["spanish"],"orca":["spanish"],"orden":["spanish"],"oreja":["spanish"],"órgano":["spanish"],"orgía":["spanish"],"orgullo":["spanish"],"oriente":["spanish"],"origen":["spanish"],"orilla":["spanish"],"oro":["spanish"],"orquesta":["spanish"],"oruga":["spanish"],"osadía":["spanish"],"oscuro":["spanish"],"osezno":["spanish"],"oso":["spanish"],"ostra":["spanish"],"otoño":["spanish"],"otro":["spanish"],"oveja":["spanish"],"óvulo":["spanish"],"óxido":["spanish"],"oxígeno":["spanish"],"oyente":["spanish"],"ozono":["spanish"],"pacto":["spanish"],"padre":["spanish"],"paella":["spanish"],"página":["spanish"],"pago":["spanish"],"país":["spanish"],"pájaro":["spanish"],"palabra":["spanish"],"palco":["spanish"],"paleta":["spanish"],"pálido":["spanish"],"palma":["spanish"],"paloma":["spanish"],"palpar":["spanish"],"pan":["spanish"],"panal":["spanish"],"pánico":["spanish"],"pantera":["spanish"],"pañuelo":["spanish"],"papá":["spanish"],"papel":["spanish"],"papilla":["spanish"],"paquete":["spanish"],"parar":["spanish"],"parcela":["spanish"],"pared":["spanish"],"parir":["spanish"],"paro":["spanish"],"párpado":["spanish"],"parque":["spanish"],"párrafo":["spanish"],"parte":["spanish"],"pasar":["spanish"],"paseo":["spanish"],"pasión":["spanish"],"paso":["spanish"],"pasta":["spanish"],"pata":["spanish"],"patio":["spanish"],"patria":["spanish"],"pausa":["spanish"],"pauta":["spanish"],"pavo":["spanish"],"payaso":["spanish"],"peatón":["spanish"],"pecado":["spanish"],"pecera":["spanish"],"pecho":["spanish"],"pedal":["spanish","turkish"],"pedir":["spanish"],"pegar":["spanish"],"peine":["spanish"],"pelar":["spanish"],"peldaño":["spanish"],"pelea":["spanish"],"peligro":["spanish"],"pellejo":["spanish"],"pelo":["spanish"],"peluca":["spanish"],"pena":["spanish","turkish"],"pensar":["spanish"],"peñón":["spanish"],"peón":["spanish"],"peor":["spanish"],"pepino":["spanish"],"pequeño":["spanish"],"pera":["spanish"],"percha":["spanish"],"perder":["spanish"],"pereza":["spanish"],"perfil":["spanish"],"perico":["spanish"],"perla":["spanish"],"permiso":["spanish"],"perro":["spanish"],"persona":["spanish"],"pesa":["spanish"],"pesca":["spanish"],"pésimo":["spanish"],"pestaña":["spanish"],"pétalo":["spanish"],"petróleo":["spanish"],"pez":["spanish"],"pezuña":["spanish"],"picar":["spanish"],"pichón":["spanish"],"pie":["spanish"],"piedra":["spanish"],"pierna":["spanish"],"pieza":["spanish"],"pijama":["spanish"],"pilar":["spanish"],"piloto":["spanish"],"pimienta":["spanish"],"pino":["spanish"],"pintor":["spanish"],"pinza":["spanish"],"piña":["spanish"],"piojo":["spanish"],"pipa":["spanish"],"pirata":["spanish"],"pisar":["spanish"],"piscina":["spanish"],"piso":["spanish"],"pista":["spanish"],"pitón":["spanish"],"pizca":["spanish"],"placa":["spanish"],"plan":["spanish"],"plata":["spanish"],"playa":["spanish"],"plaza":["spanish"],"pleito":["spanish"],"pleno":["spanish"],"plomo":["spanish"],"pluma":["spanish"],"plural":["spanish"],"pobre":["spanish"],"poco":["spanish"],"poder":["spanish"],"podio":["spanish"],"poema":["spanish"],"poesía":["spanish"],"poeta":["spanish"],"polen":["spanish","turkish"],"policía":["spanish"],"pollo":["spanish"],"polvo":["spanish"],"pomada":["spanish"],"pomelo":["spanish"],"pomo":["spanish"],"pompa":["spanish","turkish"],"poner":["spanish"],"porción":["spanish"],"portal":["spanish"],"posada":["spanish"],"poseer":["spanish"],"posible":["spanish"],"poste":["spanish"],"potencia":["spanish"],"potro":["spanish"],"pozo":["spanish"],"prado":["spanish"],"precoz":["spanish"],"pregunta":["spanish"],"premio":["spanish"],"prensa":["spanish"],"preso":["spanish"],"previo":["spanish"],"primo":["spanish"],"príncipe":["spanish"],"prisión":["spanish"],"privar":["spanish"],"proa":["spanish"],"probar":["spanish"],"proceso":["spanish"],"producto":["spanish"],"proeza":["spanish"],"profesor":["spanish"],"programa":["spanish"],"prole":["spanish"],"promesa":["spanish"],"pronto":["spanish"],"propio":["spanish"],"próximo":["spanish"],"prueba":["spanish"],"público":["spanish"],"puchero":["spanish"],"pudor":["spanish"],"pueblo":["spanish"],"puerta":["spanish"],"puesto":["spanish"],"pulga":["spanish"],"pulir":["spanish"],"pulmón":["spanish"],"pulpo":["spanish"],"pulso":["spanish"],"puma":["spanish"],"punto":["spanish"],"puñal":["spanish"],"puño":["spanish"],"pupa":["spanish"],"pupila":["spanish"],"puré":["spanish"],"quedar":["spanish"],"queja":["spanish"],"quemar":["spanish"],"querer":["spanish"],"queso":["spanish"],"quieto":["spanish"],"química":["spanish"],"quince":["spanish"],"quitar":["spanish"],"rábano":["spanish"],"rabia":["spanish"],"rabo":["spanish"],"ración":["spanish"],"radical":["spanish"],"raíz":["spanish"],"rama":["spanish"],"rampa":["spanish","turkish"],"rancho":["spanish"],"rango":["spanish"],"rapaz":["spanish"],"rápido":["spanish"],"rapto":["spanish"],"rasgo":["spanish"],"raspa":["spanish"],"rato":["spanish"],"rayo":["spanish"],"raza":["spanish"],"razón":["spanish"],"reacción":["spanish"],"realidad":["spanish"],"rebaño":["spanish"],"rebote":["spanish"],"recaer":["spanish"],"receta":["spanish"],"rechazo":["spanish"],"recoger":["spanish"],"recreo":["spanish"],"recto":["spanish"],"recurso":["spanish"],"red":["spanish"],"redondo":["spanish"],"reducir":["spanish"],"reflejo":["spanish"],"reforma":["spanish"],"refrán":["spanish"],"refugio":["spanish"],"regalo":["spanish"],"regir":["spanish"],"regla":["spanish"],"regreso":["spanish"],"rehén":["spanish"],"reino":["spanish"],"reír":["spanish"],"reja":["spanish"],"relato":["spanish"],"relevo":["spanish"],"relieve":["spanish"],"relleno":["spanish"],"reloj":["spanish"],"remar":["spanish"],"remedio":["spanish"],"remo":["spanish"],"rencor":["spanish"],"rendir":["spanish"],"renta":["spanish"],"reparto":["spanish"],"repetir":["spanish"],"reposo":["spanish"],"reptil":["spanish"],"res":["spanish"],"rescate":["spanish"],"resina":["spanish"],"respeto":["spanish"],"resto":["spanish"],"resumen":["spanish"],"retiro":["spanish"],"retorno":["spanish"],"retrato":["spanish"],"reunir":["spanish"],"revés":["spanish"],"revista":["spanish"],"rey":["spanish"],"rezar":["spanish"],"rico":["spanish"],"riego":["spanish"],"rienda":["spanish"],"riesgo":["spanish"],"rifa":["spanish"],"rígido":["spanish"],"rigor":["spanish"],"rincón":["spanish"],"riñón":["spanish"],"río":["spanish"],"riqueza":["spanish"],"risa":["spanish"],"ritmo":["spanish"],"rito":["spanish"],"rizo":["spanish"],"roble":["spanish"],"roce":["spanish"],"rociar":["spanish"],"rodar":["spanish"],"rodeo":["spanish"],"rodilla":["spanish"],"roer":["spanish"],"rojizo":["spanish"],"rojo":["spanish"],"romero":["spanish"],"romper":["spanish"],"ron":["spanish"],"ronco":["spanish"],"ronda":["spanish"],"ropa":["spanish"],"ropero":["spanish"],"rosa":["spanish"],"rosca":["spanish"],"rostro":["spanish"],"rotar":["spanish"],"rubí":["spanish"],"rubor":["spanish"],"rudo":["spanish"],"rueda":["spanish"],"rugir":["spanish"],"ruido":["spanish"],"ruina":["spanish"],"ruleta":["spanish"],"rulo":["spanish","turkish"],"rumbo":["spanish"],"rumor":["spanish"],"ruptura":["spanish"],"ruta":["spanish"],"rutina":["spanish"],"sábado":["spanish"],"saber":["spanish"],"sabio":["spanish"],"sable":["spanish"],"sacar":["spanish"],"sagaz":["spanish"],"sagrado":["spanish"],"sala":["spanish"],"saldo":["spanish"],"salero":["spanish"],"salir":["spanish"],"salmón":["spanish"],"salón":["spanish"],"salsa":["spanish"],"salto":["spanish"],"salud":["spanish"],"salvar":["spanish"],"samba":["spanish"],"sanción":["spanish"],"sandía":["spanish"],"sanear":["spanish"],"sangre":["spanish"],"sanidad":["spanish"],"sano":["spanish"],"santo":["spanish"],"sapo":["spanish"],"saque":["spanish"],"sardina":["spanish"],"sartén":["spanish"],"sastre":["spanish"],"satán":["spanish"],"sauna":["spanish"],"saxofón":["spanish"],"sección":["spanish"],"seco":["spanish"],"secreto":["spanish"],"secta":["spanish"],"sed":["spanish"],"seguir":["spanish"],"seis":["spanish"],"sello":["spanish"],"selva":["spanish"],"semana":["spanish"],"semilla":["spanish"],"senda":["spanish"],"sensor":["spanish"],"señal":["spanish"],"señor":["spanish"],"separar":["spanish"],"sepia":["spanish"],"sequía":["spanish"],"ser":["spanish"],"serie":["spanish"],"sermón":["spanish"],"servir":["spanish"],"sesenta":["spanish"],"sesión":["spanish"],"seta":["spanish"],"setenta":["spanish"],"severo":["spanish"],"sexo":["spanish"],"sexto":["spanish"],"sidra":["spanish"],"siesta":["spanish"],"siete":["spanish"],"siglo":["spanish"],"signo":["spanish"],"sílaba":["spanish"],"silbar":["spanish"],"silencio":["spanish"],"silla":["spanish"],"símbolo":["spanish"],"simio":["spanish"],"sirena":["spanish"],"sistema":["spanish"],"sitio":["spanish"],"situar":["spanish"],"sobre":["spanish"],"socio":["spanish"],"sodio":["spanish"],"sol":["spanish"],"solapa":["spanish"],"soldado":["spanish"],"soledad":["spanish"],"sólido":["spanish"],"soltar":["spanish"],"solución":["spanish"],"sombra":["spanish"],"sondeo":["spanish"],"sonido":["spanish"],"sonoro":["spanish"],"sonrisa":["spanish"],"sopa":["spanish"],"soplar":["spanish"],"soporte":["spanish"],"sordo":["spanish"],"sorpresa":["spanish"],"sorteo":["spanish"],"sostén":["spanish"],"sótano":["spanish"],"suave":["spanish"],"subir":["spanish"],"suceso":["spanish"],"sudor":["spanish"],"suegra":["spanish"],"suelo":["spanish"],"sueño":["spanish"],"suerte":["spanish"],"sufrir":["spanish"],"sujeto":["spanish"],"sultán":["spanish"],"sumar":["spanish"],"superar":["spanish"],"suplir":["spanish"],"suponer":["spanish"],"supremo":["spanish"],"sur":["spanish"],"surco":["spanish"],"sureño":["spanish"],"surgir":["spanish"],"susto":["spanish"],"sutil":["spanish"],"tabaco":["spanish"],"tabique":["spanish"],"tabla":["spanish"],"tabú":["spanish"],"taco":["spanish"],"tacto":["spanish"],"tajo":["spanish"],"talar":["spanish"],"talco":["spanish"],"talento":["spanish"],"talla":["spanish"],"talón":["spanish"],"tamaño":["spanish"],"tambor":["spanish"],"tango":["spanish"],"tanque":["spanish"],"tapa":["spanish"],"tapete":["spanish"],"tapia":["spanish"],"tapón":["spanish"],"taquilla":["spanish"],"tarde":["spanish"],"tarea":["spanish"],"tarifa":["spanish"],"tarjeta":["spanish"],"tarot":["spanish"],"tarro":["spanish"],"tarta":["spanish"],"tatuaje":["spanish"],"tauro":["spanish"],"taza":["spanish"],"tazón":["spanish"],"teatro":["spanish"],"techo":["spanish"],"tecla":["spanish"],"técnica":["spanish"],"tejado":["spanish"],"tejer":["spanish"],"tejido":["spanish"],"tela":["spanish"],"teléfono":["spanish"],"tema":["spanish"],"temor":["spanish"],"templo":["spanish"],"tenaz":["spanish"],"tender":["spanish"],"tener":["spanish"],"tenis":["spanish"],"tenso":["spanish"],"teoría":["spanish"],"terapia":["spanish"],"terco":["spanish"],"término":["spanish"],"ternura":["spanish"],"terror":["spanish"],"tesis":["spanish"],"tesoro":["spanish"],"testigo":["spanish"],"tetera":["spanish"],"texto":["spanish"],"tez":["spanish"],"tibio":["spanish"],"tiburón":["spanish"],"tiempo":["spanish"],"tienda":["spanish"],"tierra":["spanish"],"tieso":["spanish"],"tigre":["spanish"],"tijera":["spanish"],"tilde":["spanish"],"timbre":["spanish"],"tímido":["spanish"],"timo":["spanish"],"tinta":["spanish"],"tío":["spanish"],"típico":["spanish"],"tipo":["spanish"],"tira":["spanish"],"tirón":["spanish"],"titán":["spanish"],"títere":["spanish"],"título":["spanish"],"tiza":["spanish"],"toalla":["spanish"],"tobillo":["spanish"],"tocar":["spanish"],"tocino":["spanish"],"todo":["spanish"],"toga":["spanish"],"toldo":["spanish"],"tomar":["spanish","turkish"],"tono":["spanish"],"tonto":["spanish"],"topar":["spanish"],"tope":["spanish"],"toque":["spanish"],"tórax":["spanish"],"torero":["spanish"],"tormenta":["spanish"],"torneo":["spanish"],"toro":["spanish"],"torpedo":["spanish"],"torre":["spanish"],"torso":["spanish"],"tortuga":["spanish"],"tos":["spanish"],"tosco":["spanish"],"toser":["spanish"],"tóxico":["spanish"],"trabajo":["spanish"],"tractor":["spanish"],"traer":["spanish"],"tráfico":["spanish"],"trago":["spanish"],"traje":["spanish"],"tramo":["spanish"],"trance":["spanish"],"trato":["spanish"],"trauma":["spanish"],"trazar":["spanish"],"trébol":["spanish"],"tregua":["spanish"],"treinta":["spanish"],"tren":["spanish"],"trepar":["spanish"],"tres":["spanish"],"tribu":["spanish"],"trigo":["spanish"],"tripa":["spanish"],"triste":["spanish"],"triunfo":["spanish"],"trofeo":["spanish"],"trompa":["spanish"],"tronco":["spanish"],"tropa":["spanish"],"trote":["spanish"],"trozo":["spanish"],"truco":["spanish"],"trueno":["spanish"],"trufa":["spanish"],"tubería":["spanish"],"tubo":["spanish"],"tuerto":["spanish"],"tumba":["spanish"],"tumor":["spanish"],"túnel":["spanish"],"túnica":["spanish"],"turbina":["spanish"],"turismo":["spanish"],"turno":["spanish"],"tutor":["spanish"],"ubicar":["spanish"],"úlcera":["spanish"],"umbral":["spanish"],"unidad":["spanish"],"unir":["spanish"],"universo":["spanish"],"uno":["spanish"],"untar":["spanish"],"uña":["spanish"],"urbano":["spanish"],"urbe":["spanish"],"urgente":["spanish"],"urna":["spanish"],"usar":["spanish"],"usuario":["spanish"],"útil":["spanish"],"utopía":["spanish"],"uva":["spanish"],"vaca":["spanish"],"vacío":["spanish"],"vacuna":["spanish"],"vagar":["spanish"],"vago":["spanish"],"vaina":["spanish"],"vajilla":["spanish"],"vale":["spanish"],"válido":["spanish"],"valle":["spanish"],"valor":["spanish"],"válvula":["spanish"],"vampiro":["spanish"],"vara":["spanish"],"variar":["spanish"],"varón":["spanish"],"vaso":["spanish"],"vecino":["spanish"],"vector":["spanish"],"vehículo":["spanish"],"veinte":["spanish"],"vejez":["spanish"],"vela":["spanish"],"velero":["spanish"],"veloz":["spanish"],"vena":["spanish"],"vencer":["spanish"],"venda":["spanish"],"veneno":["spanish"],"vengar":["spanish"],"venir":["spanish"],"venta":["spanish"],"venus":["spanish"],"ver":["spanish"],"verano":["spanish"],"verbo":["spanish"],"verde":["spanish"],"vereda":["spanish"],"verja":["spanish"],"verso":["spanish"],"verter":["spanish"],"vía":["spanish"],"viaje":["spanish"],"vibrar":["spanish"],"vicio":["spanish"],"víctima":["spanish"],"vida":["spanish"],"vídeo":["spanish"],"vidrio":["spanish"],"viejo":["spanish"],"viernes":["spanish"],"vigor":["spanish"],"vil":["spanish"],"villa":["spanish"],"vinagre":["spanish"],"vino":["spanish"],"viñedo":["spanish"],"violín":["spanish"],"viral":["spanish"],"virgo":["spanish"],"virtud":["spanish"],"visor":["spanish"],"víspera":["spanish"],"vista":["spanish"],"vitamina":["spanish"],"viudo":["spanish"],"vivaz":["spanish"],"vivero":["spanish"],"vivir":["spanish"],"vivo":["spanish"],"volcán":["spanish"],"volumen":["spanish"],"volver":["spanish"],"voraz":["spanish"],"votar":["spanish"],"voto":["spanish"],"voz":["spanish"],"vuelo":["spanish"],"vulgar":["spanish"],"yacer":["spanish"],"yate":["spanish"],"yegua":["spanish"],"yema":["spanish"],"yerno":["spanish"],"yeso":["spanish"],"yodo":["spanish"],"yoga":["spanish"],"yogur":["spanish"],"zafiro":["spanish"],"zanja":["spanish"],"zapato":["spanish"],"zarza":["spanish"],"zona":["spanish"],"zorro":["spanish"],"zumo":["spanish"],"zurdo":["spanish"],"abajur":["turkish"],"abaküs":["turkish"],"abartı":["turkish"],"abdal":["turkish"],"abdest":["turkish"],"abiye":["turkish"],"abluka":["turkish"],"abone":["turkish"],"absorbe":["turkish"],"absürt":["turkish"],"acayip":["turkish"],"acele":["turkish"],"acemi":["turkish"],"açıkgöz":["turkish"],"adalet":["turkish"],"adam":["turkish"],"adezyon":["turkish"],"adisyon":["turkish"],"adliye":["turkish"],"adres":["turkish"],"afacan":["turkish"],"afili":["turkish"],"afiş":["turkish"],"afiyet":["turkish"],"aforizm":["turkish"],"afra":["turkish"],"ağaç":["turkish"],"ağır":["turkish"],"ahbap":["turkish"],"ahkam":["turkish"],"ahlak":["turkish"],"ahtapot":["turkish"],"aidat":["turkish"],"aile":["turkish"],"ajan":["turkish"],"akademi":["turkish"],"akarsu":["turkish"],"akbaş":["turkish"],"akciğer":["turkish"],"akdeniz":["turkish"],"akıbet":["turkish"],"akıl":["turkish"],"akıntı":["turkish"],"akide":["turkish"],"akrep":["turkish"],"akrobasi":["turkish"],"aksiyon":["turkish"],"akşam":["turkish"],"aktif":["turkish"],"aktör":["turkish"],"aktris":["turkish"],"akustik":["turkish"],"alaca":["turkish"],"albüm":["turkish"],"alçak":["turkish"],"aldanma":["turkish"],"aleni":["turkish"],"alet":["turkish"],"alfabe":["turkish"],"algılama":["turkish"],"alıngan":["turkish"],"alkış":["turkish"],"alkol":["turkish"],"alpay":["turkish"],"alperen":["turkish"],"altın":["turkish"],"altüst":["turkish"],"altyapı":["turkish"],"alyuvar":["turkish"],"amade":["turkish"],"amatör":["turkish"],"amazon":["turkish"],"ambalaj":["turkish"],"amblem":["turkish"],"ambulans":["turkish"],"amca":["turkish"],"amel":["turkish"],"amir":["turkish"],"amiyane":["turkish"],"amorti":["turkish"],"ampul":["turkish"],"anadolu":["turkish"],"anahtar":["turkish"],"anakonda":["turkish"],"anaokul":["turkish"],"anapara":["turkish"],"anarşi":["turkish"],"anatomi":["turkish"],"anayasa":["turkish"],"anekdot":["turkish"],"anestezi":["turkish"],"angaje":["turkish"],"anka":["turkish"],"anket":["turkish"],"anlamlı":["turkish"],"anne":["turkish"],"anomali":["turkish"],"anonim":["turkish"],"anten":["turkish"],"antlaşma":["turkish"],"apse":["turkish"],"araba":["turkish"],"aracı":["turkish"],"araf":["turkish"],"arbede":["turkish"],"arda":["turkish"],"arefe":["turkish"],"argo":["turkish"],"argüman":["turkish"],"arkadaş":["turkish"],"armoni":["turkish"],"arsa":["turkish"],"arsız":["turkish"],"artı":["turkish"],"aruz":["turkish"],"asansör":["turkish"],"asayiş":["turkish"],"asgari":["turkish"],"asil":["turkish"],"asker":["turkish"],"askı":["turkish"],"aslan":["turkish"],"asosyal":["turkish"],"astsubay":["turkish"],"asya":["turkish"],"aşçı":["turkish"],"aşırı":["turkish"],"aşure":["turkish"],"atabey":["turkish"],"ataman":["turkish"],"ateş":["turkish"],"atmaca":["turkish"],"atmosfer":["turkish"],"atölye":["turkish"],"avcı":["turkish"],"avdet":["turkish"],"avize":["turkish"],"avlu":["turkish"],"avokado":["turkish"],"avrupa":["turkish"],"avukat":["turkish"],"ayaz":["turkish"],"ayçiçeği":["turkish"],"aydın":["turkish"],"aygıt":["turkish"],"ayna":["turkish"],"ayran":["turkish"],"ayrıntı":["turkish"],"azim":["turkish"],"baca":["turkish"],"bagaj":["turkish"],"bağlantı":["turkish"],"bahadır":["turkish"],"bahçe":["turkish"],"baki":["turkish"],"bakkal":["turkish"],"baklava":["turkish"],"bakteri":["turkish"],"balçık":["turkish"],"balina":["turkish"],"balo":["turkish"],"balta":["turkish"],"bant":["turkish"],"banyo":["turkish"],"bardak":["turkish"],"barış":["turkish"],"başbuğ":["turkish"],"başıboş":["turkish"],"başkan":["turkish"],"başlık":["turkish"],"bavul":["turkish"],"bayındır":["turkish"],"baykuş":["turkish"],"bazlama":["turkish"],"bedel":["turkish"],"begüm":["turkish"],"bekçi":["turkish"],"bekle":["turkish"],"belge":["turkish"],"belki":["turkish"],"bencil":["turkish"],"benek":["turkish"],"bengi":["turkish"],"berjer":["turkish"],"berk":["turkish"],"berrak":["turkish"],"beşik":["turkish"],"beyin":["turkish"],"beyoğlu":["turkish"],"bıçak":["turkish"],"biberiye":["turkish"],"bidon":["turkish"],"bihaber":["turkish"],"bikini":["turkish"],"bilezik":["turkish"],"bilinç":["turkish"],"bilye":["turkish"],"bina":["turkish"],"binbaşı":["turkish"],"binyıl":["turkish"],"bisiklet":["turkish"],"bisküvi":["turkish"],"bitki":["turkish"],"bizzat":["turkish"],"bodrum":["turkish"],"boğaz":["turkish"],"bohça":["turkish"],"boncuk":["turkish"],"bonfile":["turkish"],"borsa":["turkish"],"boru":["turkish"],"bostan":["turkish"],"boşboğaz":["turkish"],"botanik":["turkish"],"boya":["turkish"],"boykot":["turkish"],"boynuz":["turkish"],"bozgun":["turkish"],"bozkır":["turkish"],"bölüm":["turkish"],"börek":["turkish"],"buçuk":["turkish"],"bugün":["turkish"],"buğday":["turkish"],"buhar":["turkish"],"buhran":["turkish"],"bulvar":["turkish"],"buram":["turkish"],"burçak":["turkish"],"burs":["turkish"],"burun":["turkish"],"buzdağı":["turkish"],"buzkıran":["turkish"],"bücür":["turkish"],"büfe":["turkish"],"bülten":["turkish"],"bütçe":["turkish"],"bütün":["turkish"],"büyük":["turkish"],"cacık":["turkish"],"cadı":["turkish"],"cahil":["turkish"],"cambaz":["turkish"],"canhıraş":["turkish"],"casus":["turkish"],"cazibe":["turkish"],"cehalet":["turkish"],"cehennem":["turkish"],"ceket":["turkish"],"cemre":["turkish"],"cenin":["turkish"],"cennet":["turkish"],"cepken":["turkish"],"cerrah":["turkish"],"cesur":["turkish"],"cetvel":["turkish"],"cevher":["turkish"],"ceylan":["turkish"],"cılız":["turkish"],"cıva":["turkish"],"cilt":["turkish"],"cisim":["turkish"],"ciyak":["turkish"],"coğrafya":["turkish"],"cömert":["turkish"],"cumba":["turkish"],"cüzdan":["turkish"],"çabucak":["turkish"],"çadır":["turkish"],"çağdaş":["turkish"],"çağlayan":["turkish"],"çağrı":["turkish"],"çakmak":["turkish"],"çalışkan":["turkish"],"çamaşır":["turkish"],"çapa":["turkish"],"çaput":["turkish"],"çarık":["turkish"],"çarpan":["turkish"],"çarşaf":["turkish"],"çayhane":["turkish"],"çekirdek":["turkish"],"çelebi":["turkish"],"çember":["turkish"],"çenet":["turkish"],"çengel":["turkish"],"çerçeve":["turkish"],"çerez":["turkish"],"çeşit":["turkish"],"çeşme":["turkish"],"çete":["turkish"],"çevre":["turkish"],"çeyiz":["turkish"],"çeyrek":["turkish"],"çığır":["turkish"],"çılgın":["turkish"],"çıngırak":["turkish"],"çift":["turkish"],"çiğdem":["turkish"],"çikolata":["turkish"],"çilek":["turkish"],"çimen":["turkish"],"çivi":["turkish"],"çoban":["turkish"],"çocuk":["turkish"],"çokgen":["turkish"],"çomak":["turkish"],"çorba":["turkish"],"çözelti":["turkish"],"çubuk":["turkish"],"çukur":["turkish"],"çuval":["turkish"],"çürük":["turkish"],"dağbaşı":["turkish"],"dağılım":["turkish"],"daktilo":["turkish"],"daldırış":["turkish"],"dalga":["turkish"],"dalkavuk":["turkish"],"damak":["turkish"],"damıtma":["turkish"],"damla":["turkish"],"dana":["turkish"],"dandik":["turkish"],"danışman":["turkish"],"daniska":["turkish"],"dantel":["turkish"],"dargeçit":["turkish"],"darphane":["turkish"],"davet":["turkish"],"dayı":["turkish"],"defter":["turkish"],"değer":["turkish"],"değirmen":["turkish"],"dehşet":["turkish"],"delgeç":["turkish"],"demir":["turkish"],"deneyim":["turkish"],"denge":["turkish"],"depo":["turkish"],"deprem":["turkish"],"derdest":["turkish"],"dere":["turkish"],"derhal":["turkish"],"derman":["turkish"],"dernek":["turkish"],"derviş":["turkish"],"desen":["turkish"],"destan":["turkish"],"dışarı":["turkish"],"dışbükey":["turkish"],"dijital":["turkish"],"dikbaşlı":["turkish"],"dilekçe":["turkish"],"dimağ":["turkish"],"dinamik":["turkish"],"dindar":["turkish"],"dinleme":["turkish"],"dinozor":["turkish"],"dipçik":["turkish"],"dipnot":["turkish"],"direniş":["turkish"],"dirsek":["turkish"],"disiplin":["turkish"],"divriği":["turkish"],"dizüstü":["turkish"],"dobra":["turkish"],"dodurga":["turkish"],"doğalgaz":["turkish"],"doküman":["turkish"],"dolap":["turkish"],"donanım":["turkish"],"dondurma":["turkish"],"donör":["turkish"],"doruk":["turkish"],"dosdoğru":["turkish"],"dost":["turkish"],"dosya":["turkish"],"dozer":["turkish"],"döküm":["turkish"],"dönence":["turkish"],"dörtyol":["turkish"],"dövme":["turkish"],"dram":["turkish"],"dublaj":["turkish"],"durum":["turkish"],"duvak":["turkish"],"duyarga":["turkish"],"duyma":["turkish"],"duyuru":["turkish"],"düğme":["turkish"],"düğüm":["turkish"],"dükkan":["turkish"],"dünür":["turkish"],"düpedüz":["turkish"],"dürbün":["turkish"],"düşünür":["turkish"],"düzayak":["turkish"],"düzeltme":["turkish"],"ebeveyn":["turkish"],"ebru":["turkish"],"ecel":["turkish"],"ecnebi":["turkish"],"ecza":["turkish"],"edat":["turkish"],"edilgen":["turkish"],"efendi":["turkish"],"efor":["turkish"],"efsane":["turkish"],"egemen":["turkish"],"egzersiz":["turkish"],"eğrelti":["turkish"],"ekarte":["turkish"],"ekip":["turkish"],"eklem":["turkish"],"ekmek":["turkish"],"ekol":["turkish"],"ekonomi":["turkish"],"ekose":["turkish"],"ekran":["turkish"],"ekvator":["turkish"],"elaman":["turkish"],"elastik":["turkish"],"elbet":["turkish"],"elbise":["turkish"],"elçi":["turkish"],"eldiven":["turkish"],"elebaşı":["turkish"],"eleştiri":["turkish"],"elma":["turkish"],"eloğlu":["turkish"],"elveda":["turkish"],"emare":["turkish"],"emekçi":["turkish"],"emisyon":["turkish"],"emniyet":["turkish"],"empati":["turkish"],"emsal":["turkish"],"emzik":["turkish"],"endüstri":["turkish"],"enerji":["turkish"],"engebe":["turkish"],"enişte":["turkish"],"enkaz":["turkish"],"entari":["turkish"],"entegre":["turkish"],"entrika":["turkish"],"enzim":["turkish"],"erdem":["turkish"],"ergen":["turkish"],"erguvan":["turkish"],"erkek":["turkish"],"erozyon":["turkish"],"ertesi":["turkish"],"erzak":["turkish"],"esaret":["turkish"],"esenlik":["turkish"],"eser":["turkish"],"eski":["turkish"],"esnek":["turkish"],"eşarp":["turkish"],"eşofman":["turkish"],"eşraf":["turkish"],"eşya":["turkish"],"eşzaman":["turkish"],"etik":["turkish"],"etken":["turkish"],"etkinlik":["turkish"],"etüt":["turkish"],"evet":["turkish"],"evire":["turkish"],"evrak":["turkish"],"evrim":["turkish"],"eyalet":["turkish"],"eyvah":["turkish"],"ezber":["turkish"],"fabrika":["turkish"],"fanus":["turkish"],"fason":["turkish"],"fasulye":["turkish"],"fatih":["turkish"],"fatura":["turkish"],"fayans":["turkish"],"fayton":["turkish"],"fazıl":["turkish"],"fazilet":["turkish"],"felsefe":["turkish"],"fener":["turkish"],"feribot":["turkish"],"fersah":["turkish"],"fesih":["turkish"],"feveran":["turkish"],"feza":["turkish"],"fıçı":["turkish"],"fıldır":["turkish"],"fındık":["turkish"],"fırça":["turkish"],"fırsat":["turkish"],"fırtına":["turkish"],"fıtık":["turkish"],"fidan":["turkish"],"fidye":["turkish"],"figür":["turkish"],"fihrist":["turkish"],"fikir":["turkish"],"fildişi":["turkish"],"filtre":["turkish"],"fincan":["turkish"],"firuze":["turkish"],"fitil":["turkish"],"fiyaka":["turkish"],"fizik":["turkish"],"flaş":["turkish"],"flüt":["turkish"],"fosil":["turkish"],"fren":["turkish"],"fukara":["turkish"],"futbol":["turkish"],"garabet":["turkish"],"gariban":["turkish"],"garnitür":["turkish"],"gazi":["turkish"],"gece":["turkish"],"gedik":["turkish"],"gelenek":["turkish"],"gelin":["turkish"],"gemi":["turkish"],"genç":["turkish"],"geniş":["turkish"],"geometri":["turkish"],"gerçek":["turkish"],"gevrek":["turkish"],"gezegen":["turkish"],"gezgin":["turkish"],"geziyolu":["turkish"],"gıcık":["turkish"],"gıda":["turkish"],"gıybet":["turkish"],"girdap":["turkish"],"girişim":["turkish"],"gitar":["turkish"],"giyecek":["turkish"],"giysi":["turkish"],"gizem":["turkish"],"gofret":["turkish"],"goril":["turkish"],"göbek":["turkish"],"göçebe":["turkish"],"göğüs":["turkish"],"gökdelen":["turkish"],"gökmen":["turkish"],"gökyüzü":["turkish"],"gölge":["turkish"],"gömlek":["turkish"],"gönül":["turkish"],"görenek":["turkish"],"görkemli":["turkish"],"görsel":["turkish"],"gösteri":["turkish"],"gövde":["turkish"],"gözaltı":["turkish"],"gözcü":["turkish"],"gözdağı":["turkish"],"gözleme":["turkish"],"gözyaşı":["turkish"],"grup":["turkish"],"gurbet":["turkish"],"gusül":["turkish"],"gübre":["turkish"],"güfte":["turkish"],"gümüş":["turkish"],"günaydın":["turkish"],"güncel":["turkish"],"gündüz":["turkish"],"güneş":["turkish"],"günyüzü":["turkish"],"gürbüz":["turkish"],"güvercin":["turkish"],"güzel":["turkish"],"hacamat":["turkish"],"hacim":["turkish"],"hademe":["turkish"],"hafız":["turkish"],"hafriyat":["turkish"],"hafta":["turkish"],"hakan":["turkish"],"hakem":["turkish"],"hakikat":["turkish"],"haksever":["turkish"],"halı":["turkish"],"hançer":["turkish"],"hane":["turkish"],"hapis":["turkish"],"hapşırık":["turkish"],"harf":["turkish"],"haseki":["turkish"],"hasret":["turkish"],"hatun":["turkish"],"havuç":["turkish"],"haylaz":["turkish"],"haysiyet":["turkish"],"hayvan":["turkish"],"hedef":["turkish"],"hemen":["turkish"],"hemfikir":["turkish"],"hendek":["turkish"],"hepsi":["turkish"],"hergele":["turkish"],"herhangi":["turkish"],"hesap":["turkish"],"heyecan":["turkish"],"heykel":["turkish"],"hezimet":["turkish"],"hıçkırık":["turkish"],"hızölçer":["turkish"],"hicviye":["turkish"],"hikaye":["turkish"],"hikmet":["turkish"],"hile":["turkish"],"hisse":["turkish"],"hobi":["turkish"],"hoca":["turkish"],"horlama":["turkish"],"hoşbeş":["turkish"],"hoşgörü":["turkish"],"hoyrat":["turkish"],"hörgüç":["turkish"],"höyük":["turkish"],"hudut":["turkish"],"hukuk":["turkish"],"hunhar":["turkish"],"hurda":["turkish"],"huysuz":["turkish"],"huzur":["turkish"],"hücum":["turkish"],"hükümet":["turkish"],"hünkar":["turkish"],"hüviyet":["turkish"],"ırmak":["turkish"],"ısıölçer":["turkish"],"ısıtıcı":["turkish"],"ıspanak":["turkish"],"ısrar":["turkish"],"ışıldak":["turkish"],"ızdırap":["turkish"],"ızgara":["turkish"],"ibadet":["turkish"],"icat":["turkish"],"içbükey":["turkish"],"içecek":["turkish"],"içgüdü":["turkish"],"içsel":["turkish"],"idman":["turkish"],"iftihar":["turkish"],"iğne":["turkish"],"ihanet":["turkish"],"ihbar":["turkish"],"ihdas":["turkish"],"ihmal":["turkish"],"ihracat":["turkish"],"ihsan":["turkish"],"ikilem":["turkish"],"ikindi":["turkish"],"ikircik":["turkish"],"iklim":["turkish"],"iksir":["turkish"],"iktibas":["turkish"],"ilaç":["turkish"],"ilçe":["turkish"],"ileri":["turkish"],"iletişim":["turkish"],"ilgi":["turkish"],"ilhak":["turkish"],"ilkbahar":["turkish"],"ilkokul":["turkish"],"ilmek":["turkish"],"imkan":["turkish"],"imleç":["turkish"],"imsak":["turkish"],"imtihan":["turkish"],"imza":["turkish"],"ince":["turkish"],"inkar":["turkish"],"inşa":["turkish"],"ipek":["turkish"],"ipucu":["turkish"],"irade":["turkish"],"irfan":["turkish"],"irmik":["turkish"],"isabet":["turkish"],"iskele":["turkish"],"israf":["turkish"],"isyan":["turkish"],"işçi":["turkish"],"işgal":["turkish"],"işgüzar":["turkish"],"işlem":["turkish"],"itibar":["turkish"],"itiraf":["turkish"],"ivedi":["turkish"],"ivme":["turkish"],"iyileşme":["turkish"],"iyimser":["turkish"],"izbandut":["turkish"],"izci":["turkish"],"izdiham":["turkish"],"izin":["turkish"],"jakoben":["turkish"],"jandarma":["turkish"],"jargon":["turkish"],"kabadayı":["turkish"],"kablo":["turkish"],"kabus":["turkish"],"kaçamak":["turkish"],"kadeh":["turkish"],"kadın":["turkish"],"kadraj":["turkish"],"kafa":["turkish"],"kafkas":["turkish"],"kağıt":["turkish"],"kağnı":["turkish"],"kahkaha":["turkish"],"kahraman":["turkish"],"kahvaltı":["turkish"],"kakül":["turkish"],"kaldırım":["turkish"],"kale":["turkish"],"kalibre":["turkish"],"kalkan":["turkish"],"kalpak":["turkish"],"kamış":["turkish"],"kamyon":["turkish"],"kanat":["turkish"],"kandaş":["turkish"],"kanepe":["turkish"],"kanser":["turkish"],"kanun":["turkish"],"kaos":["turkish"],"kapı":["turkish"],"kaplıca":["turkish"],"kaptan":["turkish"],"karanlık":["turkish"],"kardeş":["turkish"],"karga":["turkish"],"karınca":["turkish"],"karmaşa":["turkish"],"karşıt":["turkish"],"kasırga":["turkish"],"kask":["turkish"],"kasvet":["turkish"],"katkı":["turkish"],"katman":["turkish"],"kavram":["turkish"],"kaygan":["turkish"],"kaynakça":["turkish"],"kayyum":["turkish"],"kedi":["turkish"],"kehanet":["turkish"],"kekik":["turkish"],"kelebek":["turkish"],"kenar":["turkish"],"kerkenez":["turkish"],"kerpiç":["turkish"],"kesirli":["turkish"],"kesmece":["turkish"],"kestane":["turkish"],"keşkek":["turkish"],"ketçap":["turkish"],"keyfiyet":["turkish"],"kıble":["turkish"],"kıdemli":["turkish"],"kılavuz":["turkish"],"kılçık":["turkish"],"kılıf":["turkish"],"kıraç":["turkish"],"kırmızı":["turkish"],"kırsal":["turkish"],"kısayol":["turkish"],"kısım":["turkish"],"kıskanç":["turkish"],"kısmet":["turkish"],"kışla":["turkish"],"kıvanç":["turkish"],"kıvılcım":["turkish"],"kıvrık":["turkish"],"kıyafet":["turkish"],"kıymetli":["turkish"],"kızak":["turkish"],"kızılcık":["turkish"],"kibar":["turkish"],"kinaye":["turkish"],"kira":["turkish"],"kiremit":["turkish"],"kirli":["turkish"],"kirpik":["turkish"],"kişisel":["turkish"],"kitap":["turkish"],"koçbaşı":["turkish"],"kodaman":["turkish"],"koğuş":["turkish"],"kokteyl":["turkish"],"kolaycı":["turkish"],"kolbastı":["turkish"],"kolonya":["turkish"],"koltuk":["turkish"],"kolye":["turkish"],"kombine":["turkish"],"komedyen":["turkish"],"komiser":["turkish"],"komposto":["turkish"],"komşu":["turkish"],"komuta":["turkish"],"konak":["turkish"],"konfor":["turkish"],"koni":["turkish"],"konsül":["turkish"],"kopya":["turkish"],"korkusuz":["turkish"],"korna":["turkish"],"korse":["turkish"],"korunak":["turkish"],"korvet":["turkish"],"kostüm":["turkish"],"koşul":["turkish"],"koyu":["turkish"],"kozmik":["turkish"],"köfte":["turkish"],"kökensel":["turkish"],"köprücük":["turkish"],"köpük":["turkish"],"kördüğüm":["turkish"],"körfez":["turkish"],"köstebek":["turkish"],"köşegen":["turkish"],"kötü":["turkish"],"kravat":["turkish"],"kriter":["turkish"],"kuantum":["turkish"],"kudurma":["turkish"],"kuluçka":["turkish"],"kulübe":["turkish"],"kumanya":["turkish"],"kumbara":["turkish"],"kumlu":["turkish"],"kumpir":["turkish"],"kumral":["turkish"],"kundura":["turkish"],"kupa":["turkish"],"kupkuru":["turkish"],"kuramsal":["turkish"],"kurbağa":["turkish"],"kurdele":["turkish"],"kurgu":["turkish"],"kurmay":["turkish"],"kurşun":["turkish"],"kurtuluş":["turkish"],"kurultay":["turkish"],"kurye":["turkish"],"kusursuz":["turkish"],"kuşak":["turkish"],"kuşbaşı":["turkish"],"kuşkulu":["turkish"],"kutlama":["turkish"],"kutsal":["turkish"],"kutup":["turkish"],"kuver":["turkish"],"kuyruk":["turkish"],"kuzey":["turkish"],"kuzgun":["turkish"],"küçük":["turkish"],"külçe":["turkish"],"külfet":["turkish"],"külliye":["turkish"],"kültürel":["turkish"],"kümes":["turkish"],"künefe":["turkish"],"küresel":["turkish"],"kütle":["turkish"],"lahana":["turkish"],"lahmacun":["turkish"],"lamba":["turkish"],"lansman":["turkish"],"lavaş":["turkish"],"layık":["turkish"],"leğen":["turkish"],"levent":["turkish"],"leziz":["turkish"],"lezzet":["turkish"],"lider":["turkish"],"likide":["turkish"],"liman":["turkish"],"liste":["turkish"],"litre":["turkish"],"liyakat":["turkish"],"lodos":["turkish"],"lokanta":["turkish"],"lokman":["turkish"],"lokum":["turkish"],"lunapark":["turkish"],"lütfen":["turkish"],"lüzum":["turkish"],"nokta":["turkish"],"mabet":["turkish"],"macera":["turkish"],"macun":["turkish"],"madalya":["turkish"],"madde":["turkish"],"madem":["turkish"],"mağara":["turkish"],"mağdur":["turkish"],"mağfiret":["turkish"],"mağlup":["turkish"],"mahalle":["turkish"],"mahcup":["turkish"],"mahir":["turkish"],"mahkeme":["turkish"],"mahlas":["turkish"],"mahrum":["turkish"],"mahsul":["turkish"],"makas":["turkish"],"makbuz":["turkish"],"makine":["turkish"],"makro":["turkish"],"maksat":["turkish"],"makul":["turkish"],"maliye":["turkish"],"manav":["turkish"],"mangal":["turkish"],"manidar":["turkish"],"manken":["turkish"],"mantık":["turkish"],"manzara":["turkish"],"mareşal":["turkish"],"margarin":["turkish"],"marifet":["turkish"],"marmelat":["turkish"],"masaüstü":["turkish"],"masmavi":["turkish"],"masraf":["turkish"],"masum":["turkish"],"matah":["turkish"],"materyal":["turkish"],"matrak":["turkish"],"maval":["turkish"],"mavra":["turkish"],"maydanoz":["turkish"],"mayhoş":["turkish"],"maytap":["turkish"],"mazbata":["turkish"],"mazeret":["turkish"],"mazlum":["turkish"],"mazot":["turkish"],"mazur":["turkish"],"meblağ":["turkish"],"mebus":["turkish"],"mecaz":["turkish"],"mecbur":["turkish"],"meclis":["turkish"],"mecmua":["turkish"],"mecnun":["turkish"],"meçhul":["turkish"],"medeni":["turkish"],"mehtap":["turkish"],"mekanik":["turkish"],"melodi":["turkish"],"meltem":["turkish"],"memur":["turkish"],"mendil":["turkish"],"menekşe":["turkish"],"menteşe":["turkish"],"meraklı":["turkish"],"mercek":["turkish"],"merdiven":["turkish"],"merhaba":["turkish"],"merinos":["turkish"],"merkez":["turkish"],"mermi":["turkish"],"mert":["turkish"],"mesafe":["turkish"],"mesele":["turkish"],"mesken":["turkish"],"meslek":["turkish"],"meşale":["turkish"],"meşgul":["turkish"],"meşhur":["turkish"],"metafor":["turkish"],"metin":["turkish"],"metre":["turkish"],"mevcut":["turkish"],"mevkidaş":["turkish"],"meydan":["turkish"],"meyil":["turkish"],"meyve":["turkish"],"meziyet":["turkish"],"mezun":["turkish"],"mıknatıs":["turkish"],"mısra":["turkish"],"mızıka":["turkish"],"miğfer":["turkish"],"mihrak":["turkish"],"miktar":["turkish"],"milat":["turkish"],"milli":["turkish"],"mimar":["turkish"],"minare":["turkish"],"mineral":["turkish"],"minik":["turkish"],"minyon":["turkish"],"mirliva":["turkish"],"misafir":["turkish"],"miskin":["turkish"],"miting":["turkish"],"miyop":["turkish"],"mizah":["turkish"],"mobilya":["turkish"],"monitör":["turkish"],"morötesi":["turkish"],"motive":["turkish"],"mozaik":["turkish"],"muavin":["turkish"],"mucize":["turkish"],"muhafız":["turkish"],"muhteşem":["turkish"],"mukayese":["turkish"],"mumya":["turkish"],"musluk":["turkish"],"muşamba":["turkish"],"mutabık":["turkish"],"mutfak":["turkish"],"mutlu":["turkish"],"muzaffer":["turkish"],"muzdarip":["turkish"],"mübarek":["turkish"],"mücadele":["turkish"],"müdür":["turkish"],"müfredat":["turkish"],"müftü":["turkish"],"mühendis":["turkish"],"mühim":["turkish"],"mühlet":["turkish"],"mükemmel":["turkish"],"mülk":["turkish"],"mümkün":["turkish"],"mümtaz":["turkish"],"müsrif":["turkish"],"müstesna":["turkish"],"müşahit":["turkish"],"müşteri":["turkish"],"mütercim":["turkish"],"müthiş":["turkish"],"müze":["turkish"],"müzik":["turkish"],"nabız":["turkish"],"nadas":["turkish"],"nadir":["turkish"],"nahoş":["turkish"],"nakarat":["turkish"],"nakış":["turkish"],"nalbur":["turkish"],"namlu":["turkish"],"namus":["turkish"],"nankör":["turkish"],"nargile":["turkish"],"narkoz":["turkish"],"nasıl":["turkish"],"nasip":["turkish"],"naylon":["turkish"],"nazar":["turkish"],"nazım":["turkish"],"nazik":["turkish"],"neden":["turkish"],"nefes":["turkish"],"negatif":["turkish"],"neon":["turkish"],"neptün":["turkish"],"nerede":["turkish"],"nesil":["turkish"],"nesnel":["turkish"],"neşeli":["turkish"],"netice":["turkish"],"nevresim":["turkish"],"neyse":["turkish"],"neyzen":["turkish"],"nezaket":["turkish"],"nezih":["turkish"],"nezle":["turkish"],"nicel":["turkish"],"nilüfer":["turkish"],"nimet":["turkish"],"nisan":["turkish"],"nispet":["turkish"],"nitekim":["turkish"],"nizam":["turkish"],"nohut":["turkish"],"noksan":["turkish"],"nostalji":["turkish"],"noter":["turkish"],"nöbet":["turkish"],"numara":["turkish"],"numune":["turkish"],"nutuk":["turkish"],"nüfus":["turkish"],"obabaşı":["turkish"],"obez":["turkish"],"obje":["turkish"],"ocak":["turkish"],"odun":["turkish"],"ofansif":["turkish"],"ofis":["turkish"],"oğlak":["turkish"],"oğuz":["turkish"],"okçu":["turkish"],"oklava":["turkish"],"oksijen":["turkish"],"okul":["turkish"],"okumuş":["turkish"],"okutman":["turkish"],"okuyucu":["turkish"],"okyanus":["turkish"],"olağan":["turkish"],"olanak":["turkish"],"olası":["turkish"],"olay":["turkish"],"olgun":["turkish"],"olimpik":["turkish"],"olumlu":["turkish"],"omlet":["turkish"],"omurga":["turkish"],"onarım":["turkish"],"onursal":["turkish"],"optik":["turkish"],"orantı":["turkish"],"ordu":["turkish"],"organik":["turkish"],"orijin":["turkish"],"orkide":["turkish"],"orman":["turkish"],"orta":["turkish"],"oruç":["turkish"],"otağ":["turkish"],"otantik":["turkish"],"otel":["turkish"],"otoban":["turkish"],"otogar":["turkish"],"otomobil":["turkish"],"otonom":["turkish"],"otopark":["turkish"],"otorite":["turkish"],"otoyol":["turkish"],"oturum":["turkish"],"oyuk":["turkish"],"oyuncak":["turkish"],"ozan":["turkish"],"ödeme":["turkish"],"ödenek":["turkish"],"ödev":["turkish"],"ödül":["turkish"],"ödünç":["turkish"],"öfke":["turkish"],"öğlen":["turkish"],"öğrenci":["turkish"],"öğün":["turkish"],"öğütücü":["turkish"],"öksürük":["turkish"],"ölçme":["turkish"],"ölçü":["turkish"],"ölümsüz":["turkish"],"ömür":["turkish"],"önayak":["turkish"],"öncü":["turkish"],"önder":["turkish"],"önem":["turkish"],"önerge":["turkish"],"öngörü":["turkish"],"önlük":["turkish"],"önsezi":["turkish"],"öpücük":["turkish"],"ördek":["turkish"],"örgü":["turkish"],"örtbas":["turkish"],"örtme":["turkish"],"örtü":["turkish"],"örümcek":["turkish"],"örüntü":["turkish"],"öteberi":["turkish"],"öteki":["turkish"],"övünç":["turkish"],"öykü":["turkish"],"öyleyse":["turkish"],"özçekim":["turkish"],"özdeyiş":["turkish"],"özel":["turkish"],"özenti":["turkish"],"özerk":["turkish"],"özgürlük":["turkish"],"özlem":["turkish"],"özlü":["turkish"],"özne":["turkish"],"özsever":["turkish"],"özümseme":["turkish"],"özür":["turkish"],"özveri":["turkish"],"pabuç":["turkish"],"padişah":["turkish"],"palamut":["turkish"],"palmiye":["turkish"],"palto":["turkish"],"palyaço":["turkish"],"pamuk":["turkish"],"panayır":["turkish"],"pancar":["turkish"],"panik":["turkish"],"panjur":["turkish"],"pankart":["turkish"],"pano":["turkish"],"pansuman":["turkish"],"pantolon":["turkish"],"panzehir":["turkish"],"papatya":["turkish"],"papyon":["turkish"],"paraşüt":["turkish"],"parça":["turkish"],"pardösü":["turkish"],"parfüm":["turkish"],"parıltı":["turkish"],"parkur":["turkish"],"parmak":["turkish"],"parodi":["turkish"],"parsel":["turkish"],"partner":["turkish"],"pasaport":["turkish"],"pasif":["turkish"],"paskalya":["turkish"],"pastırma":["turkish"],"paşa":["turkish"],"patates":["turkish"],"paten":["turkish"],"patika":["turkish"],"patlıcan":["turkish"],"patolog":["turkish"],"payanda":["turkish"],"paydaş":["turkish"],"payidar":["turkish"],"paylaşma":["turkish"],"paytak":["turkish"],"peçete":["turkish"],"peder":["turkish"],"pehlivan":["turkish"],"pekala":["turkish"],"pekmez":["turkish"],"pelerin":["turkish"],"pelikan":["turkish"],"pelüş":["turkish"],"pembe":["turkish"],"pencere":["turkish"],"pense":["turkish"],"perçin":["turkish"],"perde":["turkish"],"pergel":["turkish"],"perişan":["turkish"],"peron":["turkish"],"personel":["turkish"],"perşembe":["turkish"],"peruk":["turkish"],"pervane":["turkish"],"pespaye":["turkish"],"pestil":["turkish"],"peşin":["turkish"],"petek":["turkish"],"petrol":["turkish"],"petunya":["turkish"],"peynir":["turkish"],"peyzaj":["turkish"],"pınar":["turkish"],"pırasa":["turkish"],"pırlanta":["turkish"],"pide":["turkish"],"pikap":["turkish"],"pilav":["turkish"],"piliç":["turkish"],"pipet":["turkish"],"pipo":["turkish"],"piramit":["turkish"],"pirinç":["turkish"],"pirzola":["turkish"],"pist":["turkish"],"pişik":["turkish"],"pişman":["turkish"],"piyasa":["turkish"],"piyes":["turkish"],"plaj":["turkish"],"plaket":["turkish"],"planlama":["turkish"],"platform":["turkish"],"plazma":["turkish"],"podyum":["turkish"],"poğaça":["turkish"],"polat":["turkish"],"politika":["turkish"],"popüler":["turkish"],"porselen":["turkish"],"portakal":["turkish"],"poster":["turkish"],"poşet":["turkish"],"poyraz":["turkish"],"pozitif":["turkish"],"pranga":["turkish"],"pratik":["turkish"],"prenses":["turkish"],"prim":["turkish"],"profil":["turkish"],"proje":["turkish"],"protokol":["turkish"],"puan":["turkish"],"pudra":["turkish"],"pusula":["turkish"],"püre":["turkish"],"pürüz":["turkish"],"püstül":["turkish"],"püsür":["turkish"],"racon":["turkish"],"radikal":["turkish"],"radyo":["turkish"],"rafadan":["turkish"],"rafine":["turkish"],"rağbet":["turkish"],"rahat":["turkish"],"rahle":["turkish"],"rakam":["turkish"],"raket":["turkish"],"rakip":["turkish"],"rakun":["turkish"],"ralli":["turkish"],"randevu":["turkish"],"ranza":["turkish"],"rapor":["turkish"],"rastgele":["turkish"],"rasyonel":["turkish"],"razı":["turkish"],"realite":["turkish"],"reçine":["turkish"],"refah":["turkish"],"referans":["turkish"],"refik":["turkish"],"rehber":["turkish"],"rehin":["turkish"],"reis":["turkish"],"rekabet":["turkish"],"reklam":["turkish"],"rekor":["turkish"],"rektör":["turkish"],"renk":["turkish"],"resim":["turkish"],"resmen":["turkish"],"restoran":["turkish"],"retorik":["turkish"],"revaç":["turkish"],"reyon":["turkish"],"rezalet":["turkish"],"rezerv":["turkish"],"rezil":["turkish"],"rıhtım":["turkish"],"rıza":["turkish"],"ritim":["turkish"],"ritüel":["turkish"],"rivayet":["turkish"],"roman":["turkish"],"rozet":["turkish"],"röportaj":["turkish"],"rötar":["turkish"],"ruble":["turkish"],"ruhban":["turkish"],"ruhsat":["turkish"],"rulet":["turkish"],"runik":["turkish"],"rutin":["turkish"],"rutubet":["turkish"],"rüşvet":["turkish"],"rütbe":["turkish"],"rüya":["turkish"],"rüzgar":["turkish"],"sabah":["turkish"],"sabıka":["turkish"],"sabit":["turkish"],"sabun":["turkish"],"saçma":["turkish"],"sade":["turkish"],"sadık":["turkish"],"safahat":["turkish"],"safdil":["turkish"],"safkan":["turkish"],"sağanak":["turkish"],"sağduyu":["turkish"],"sağlam":["turkish"],"saha":["turkish"],"sahiden":["turkish"],"sahne":["turkish"],"sakal":["turkish"],"sakız":["turkish"],"sakin":["turkish"],"saklama":["turkish"],"saksağan":["turkish"],"salamura":["turkish"],"salça":["turkish"],"salgı":["turkish"],"salınım":["turkish"],"salkım":["turkish"],"saltanat":["turkish"],"sanatçı":["turkish"],"sancak":["turkish"],"sandalye":["turkish"],"saniye":["turkish"],"saplantı":["turkish"],"sapsız":["turkish"],"saray":["turkish"],"sarışın":["turkish"],"sarkık":["turkish"],"sarmaşık":["turkish"],"satır":["turkish"],"savaşım":["turkish"],"savunma":["turkish"],"saydam":["turkish"],"sayfa":["turkish"],"saygın":["turkish"],"sayısal":["turkish"],"sebep":["turkish"],"seçenek":["turkish"],"seçim":["turkish"],"seçkin":["turkish"],"seçmen":["turkish"],"sedir":["turkish"],"sedye":["turkish"],"sefer":["turkish"],"sehpa":["turkish"],"sekizgen":["turkish"],"selektör":["turkish"],"selvi":["turkish"],"semavi":["turkish"],"sembol":["turkish"],"seminer":["turkish"],"senaryo":["turkish"],"sendika":["turkish"],"senkron":["turkish"],"sensör":["turkish"],"sentez":["turkish"],"sepet":["turkish"],"seramik":["turkish"],"serbest":["turkish"],"serdar":["turkish"],"seremoni":["turkish"],"sergi":["turkish"],"serhat":["turkish"],"serin":["turkish"],"sermaye":["turkish"],"serpuş":["turkish"],"sersem":["turkish"],"serüven":["turkish"],"sesli":["turkish"],"sesteş":["turkish"],"sevap":["turkish"],"seviye":["turkish"],"seyahat":["turkish"],"seyirci":["turkish"],"sezon":["turkish"],"sıcak":["turkish"],"sıfat":["turkish"],"sıhhi":["turkish"],"sınanma":["turkish"],"sınır":["turkish"],"sıradan":["turkish"],"sırdaş":["turkish"],"sırma":["turkish"],"sırtüstü":["turkish"],"sızgıt":["turkish"],"siftah":["turkish"],"sigorta":["turkish"],"sihirbaz":["turkish"],"silah":["turkish"],"silecek":["turkish"],"silindir":["turkish"],"simetri":["turkish"],"simge":["turkish"],"simit":["turkish"],"sincap":["turkish"],"sindirim":["turkish"],"sinema":["turkish"],"sinirli":["turkish"],"sipariş":["turkish"],"sirke":["turkish"],"siroz":["turkish"],"sistem":["turkish"],"sivilce":["turkish"],"siyasi":["turkish"],"soba":["turkish"],"sofra":["turkish"],"soğuk":["turkish"],"sohbet":["turkish"],"sokak":["turkish"],"solfej":["turkish"],"solunum":["turkish"],"somut":["turkish"],"sonbahar":["turkish"],"sonraki":["turkish"],"sonsuz":["turkish"],"sorunsuz":["turkish"],"sosyete":["turkish"],"soyağacı":["turkish"],"soydaş":["turkish"],"soygun":["turkish"],"soytarı":["turkish"],"söğüş":["turkish"],"sömürge":["turkish"],"sönük":["turkish"],"söylem":["turkish"],"sözcük":["turkish"],"sözde":["turkish"],"spatula":["turkish"],"spektrum":["turkish"],"spiker":["turkish"],"sporcu":["turkish"],"sprey":["turkish"],"stabil":["turkish"],"statü":["turkish"],"stok":["turkish"],"stopaj":["turkish"],"strateji":["turkish"],"subay":["turkish"],"sucuk":["turkish"],"suçüstü":["turkish"],"suhulet":["turkish"],"sulama":["turkish"],"sungur":["turkish"],"sunucu":["turkish"],"surat":["turkish"],"susam":["turkish"],"suskun":["turkish"],"sükse":["turkish"],"sükut":["turkish"],"sülale":["turkish"],"sünger":["turkish"],"süpürge":["turkish"],"sürahi":["turkish"],"süreç":["turkish"],"sürgün":["turkish"],"sürüm":["turkish"],"süsleme":["turkish"],"sütanne":["turkish"],"sütlaç":["turkish"],"sütun":["turkish"],"süvari":["turkish"],"şahane":["turkish"],"şahbaz":["turkish"],"şahit":["turkish"],"şahsiyet":["turkish"],"şakıma":["turkish"],"şaklaban":["turkish"],"şakrak":["turkish"],"şamar":["turkish"],"şampiyon":["turkish"],"şanslı":["turkish"],"şantiye":["turkish"],"şapka":["turkish"],"şarkıcı":["turkish"],"şartname":["turkish"],"şaşırma":["turkish"],"şaşkın":["turkish"],"şatafat":["turkish"],"şayet":["turkish"],"şebeke":["turkish"],"şefkat":["turkish"],"şeftali":["turkish"],"şehir":["turkish"],"şehvet":["turkish"],"şeker":["turkish"],"şekil":["turkish"],"şelale":["turkish"],"şema":["turkish"],"şemsiye":["turkish"],"şerbet":["turkish"],"şeref":["turkish"],"şerit":["turkish"],"şımarık":["turkish"],"şıpıdık":["turkish"],"şifre":["turkish"],"şimdi":["turkish"],"şimşek":["turkish"],"şipşak":["turkish"],"şirin":["turkish"],"şişe":["turkish"],"şişirme":["turkish"],"şofben":["turkish"],"şöhret":["turkish"],"şölen":["turkish"],"şüphe":["turkish"],"tabaka":["turkish"],"tabure":["turkish"],"tadilat":["turkish"],"taharet":["turkish"],"tahıl":["turkish"],"tahkim":["turkish"],"tahlil":["turkish"],"tahmin":["turkish"],"tahrifat":["turkish"],"tahsilat":["turkish"],"tahta":["turkish"],"taklit":["turkish"],"takoz":["turkish"],"taksici":["turkish"],"taktik":["turkish"],"takvim":["turkish"],"talebe":["turkish"],"talip":["turkish"],"tamamen":["turkish"],"tamirci":["turkish"],"tamtakır":["turkish"],"tandır":["turkish"],"tanecik":["turkish"],"tanıtım":["turkish"],"tanrı":["turkish"],"tansiyon":["turkish"],"tapan":["turkish"],"tapınak":["turkish"],"taptaze":["turkish"],"tapu":["turkish"],"tarafgir":["turkish"],"tarhana":["turkish"],"tarım":["turkish"],"tarih":["turkish"],"tarla":["turkish"],"tartak":["turkish"],"tarumar":["turkish"],"tasarım":["turkish"],"tasdik":["turkish"],"taslak":["turkish"],"tastamam":["turkish"],"taşeron":["turkish"],"taşınmaz":["turkish"],"taşra":["turkish"],"tatava":["turkish"],"tatbikat":["turkish"],"tatil":["turkish"],"tatlı":["turkish"],"tavsiye":["turkish"],"tavşan":["turkish"],"tavuk":["turkish"],"taze":["turkish"],"taziye":["turkish"],"tazminat":["turkish"],"tebeşir":["turkish"],"tebrik":["turkish"],"tecrübe":["turkish"],"teçhizat":["turkish"],"tedarik":["turkish"],"tedbir":["turkish"],"teftiş":["turkish"],"teğet":["turkish"],"teğmen":["turkish"],"tehdit":["turkish"],"tehlike":["turkish"],"tekdüze":["turkish"],"tekerlek":["turkish"],"tekme":["turkish"],"teknik":["turkish"],"tekrar":["turkish"],"telef":["turkish"],"telsiz":["turkish"],"telve":["turkish"],"temas":["turkish"],"tembel":["turkish"],"temiz":["turkish"],"temkin":["turkish"],"temsilci":["turkish"],"tendon":["turkish"],"teneke":["turkish"],"tenha":["turkish"],"tenkit":["turkish"],"tepegöz":["turkish"],"tepki":["turkish"],"terazi":["turkish"],"terbiye":["turkish"],"tercih":["turkish"],"tereyağı":["turkish"],"terfi":["turkish"],"terim":["turkish"],"terminal":["turkish"],"tersane":["turkish"],"tertip":["turkish"],"tesadüf":["turkish"],"tescil":["turkish"],"tesir":["turkish"],"teslimat":["turkish"],"tespit":["turkish"],"testere":["turkish"],"teşekkür":["turkish"],"teşhir":["turkish"],"teşrif":["turkish"],"teşvik":["turkish"],"teyze":["turkish"],"tezahür":["turkish"],"tezgah":["turkish"],"tıbbi":["turkish"],"tıkaç":["turkish"],"tıkışık":["turkish"],"tıknaz":["turkish"],"tılsım":["turkish"],"tıpkı":["turkish"],"tıraş":["turkish"],"tırışka":["turkish"],"tırmanış":["turkish"],"tırnak":["turkish"],"tırpan":["turkish"],"tıslama":["turkish"],"ticaret":["turkish"],"tilki":["turkish"],"tiryaki":["turkish"],"titreşim":["turkish"],"tohum":["turkish"],"tokat":["turkish"],"tolere":["turkish"],"tombak":["turkish"],"tomurcuk":["turkish"],"topaç":["turkish"],"toplum":["turkish"],"toprak":["turkish"],"toptan":["turkish"],"toraman":["turkish"],"torpido":["turkish"],"tortu":["turkish"],"tosbağa":["turkish"],"toynak":["turkish"],"tören":["turkish"],"trafik":["turkish"],"trajedi":["turkish"],"tramvay":["turkish"],"tribün":["turkish"],"triko":["turkish"],"tugay":["turkish"],"tuğla":["turkish"],"tuğrul":["turkish"],"tuhaf":["turkish"],"tulumba":["turkish"],"tunç":["turkish"],"turan":["turkish"],"turkuaz":["turkish"],"turnusol":["turkish"],"turşu":["turkish"],"turuncu":["turkish"],"tutanak":["turkish"],"tutkal":["turkish"],"tutsak":["turkish"],"tutum":["turkish"],"tuyuğ":["turkish"],"tuzlu":["turkish"],"tüccar":["turkish"],"tüfek":["turkish"],"tükenmez":["turkish"],"tülbent":["turkish"],"tümleç":["turkish"],"tünel":["turkish"],"türbin":["turkish"],"türev":["turkish"],"türk":["turkish"],"tüzük":["turkish"],"ucube":["turkish"],"ucuz":["turkish"],"uçak":["turkish"],"uçurtma":["turkish"],"ufuk":["turkish"],"uğrak":["turkish"],"uğur":["turkish"],"ukala":["turkish"],"ulaşım":["turkish"],"ulema":["turkish"],"ulus":["turkish"],"ulvi":["turkish"],"umursama":["turkish"],"umut":["turkish"],"unutkan":["turkish"],"uslu":["turkish"],"ustabaşı":["turkish"],"ustura":["turkish"],"usul":["turkish"],"utangaç":["turkish"],"uyanık":["turkish"],"uyarı":["turkish"],"uydu":["turkish"],"uygar":["turkish"],"uygulama":["turkish"],"uykusuz":["turkish"],"uysal":["turkish"],"uyuşma":["turkish"],"uzantı":["turkish"],"uzay":["turkish"],"uzgören":["turkish"],"uzlaşma":["turkish"],"uzman":["turkish"],"uzun":["turkish"],"ücra":["turkish"],"ücret":["turkish"],"üçbudak":["turkish"],"üçgen":["turkish"],"üçkağıt":["turkish"],"üçleme":["turkish"],"üfürük":["turkish"],"ülke":["turkish"],"ümit":["turkish"],"üniforma":["turkish"],"ünite":["turkish"],"ünlem":["turkish"],"üretken":["turkish"],"ürün":["turkish"],"üslup":["turkish"],"üstel":["turkish"],"üstün":["turkish"],"üşengeç":["turkish"],"üşüme":["turkish"],"ütopya":["turkish"],"üvey":["turkish"],"üzengi":["turkish"],"üzgün":["turkish"],"üzüm":["turkish"],"vaka":["turkish"],"vakfiye":["turkish"],"vakıf":["turkish"],"vakit":["turkish"],"vakum":["turkish"],"vapur":["turkish"],"varil":["turkish"],"varlık":["turkish"],"varsayım":["turkish"],"varyemez":["turkish"],"vasıta":["turkish"],"vasiyet":["turkish"],"vatandaş":["turkish"],"vazife":["turkish"],"vazo":["turkish"],"veciz":["turkish"],"vefa":["turkish"],"vehim":["turkish"],"veliaht":["turkish"],"veresiye":["turkish"],"verimli":["turkish"],"verkaç":["turkish"],"vernik":["turkish"],"vertigo":["turkish"],"vesait":["turkish"],"vesika":["turkish"],"vestiyer":["turkish"],"veznedar":["turkish"],"vicdan":["turkish"],"vilayet":["turkish"],"virane":["turkish"],"virgül":["turkish"],"vişne":["turkish"],"vites":["turkish"],"vokal":["turkish"],"volkan":["turkish"],"vurma":["turkish"],"vurucu":["turkish"],"vücut":["turkish"],"yabancı":["turkish"],"yabgu":["turkish"],"yağış":["turkish"],"yağlı":["turkish"],"yağmur":["turkish"],"yakamoz":["turkish"],"yakın":["turkish"],"yaklaşık":["turkish"],"yalçın":["turkish"],"yalıtım":["turkish"],"yaman":["turkish"],"yanardağ":["turkish"],"yangın":["turkish"],"yanıt":["turkish"],"yankı":["turkish"],"yanlış":["turkish"],"yansıma":["turkish"],"yapay":["turkish"],"yapboz":["turkish"],"yapımcı":["turkish"],"yaprak":["turkish"],"yaratık":["turkish"],"yarbay":["turkish"],"yardım":["turkish"],"yargıç":["turkish"],"yarıçap":["turkish"],"yasemin":["turkish"],"yastık":["turkish"],"yaşam":["turkish"],"yatak":["turkish"],"yatırım":["turkish"],"yavru":["turkish"],"yaygara":["turkish"],"yayıncı":["turkish"],"yayla":["turkish"],"yazılım":["turkish"],"yekpare":["turkish"],"yekvücut":["turkish"],"yelkovan":["turkish"],"yelpaze":["turkish"],"yemek":["turkish"],"yemiş":["turkish"],"yengeç":["turkish"],"yeniçeri":["turkish"],"yeraltı":["turkish"],"yerküre":["turkish"],"yerleşke":["turkish"],"yeryüzü":["turkish"],"yeşil":["turkish"],"yetenek":["turkish"],"yetkili":["turkish"],"yığınak":["turkish"],"yıkama":["turkish"],"yılbaşı":["turkish"],"yıldırım":["turkish"],"yılkı":["turkish"],"yılmaz":["turkish"],"yırtıcı":["turkish"],"yiğit":["turkish"],"yoğurt":["turkish"],"yokuş":["turkish"],"yolcu":["turkish"],"yoldaş":["turkish"],"yolgeçen":["turkish"],"yolkesen":["turkish"],"yolüstü":["turkish"],"yordam":["turkish"],"yorgan":["turkish"],"yorumcu":["turkish"],"yosun":["turkish"],"yöndeş":["turkish"],"yönetim":["turkish"],"yönlü":["turkish"],"yöntem":["turkish"],"yöresel":["turkish"],"yörünge":["turkish"],"yufka":["turkish"],"yukarı":["turkish"],"yumruk":["turkish"],"yumurta":["turkish"],"yuvarlak":["turkish"],"yücelme":["turkish"],"yükçeker":["turkish"],"yüklem":["turkish"],"yüksek":["turkish"],"yürek":["turkish"],"yürütme":["turkish"],"yüzde":["turkish"],"yüzeysel":["turkish"],"yüzgeç":["turkish"],"yüzüstü":["turkish"],"yüzyıl":["turkish"],"zabıta":["turkish"],"zafer":["turkish"],"zahmet":["turkish"],"zambak":["turkish"],"zaptiye":["turkish"],"zarafet":["turkish"],"zaruret":["turkish"],"zeka":["turkish"],"zekice":["turkish"],"zemberek":["turkish"],"zemin":["turkish"],"zencefil":["turkish"],"zeplin":["turkish"],"zeytin":["turkish"],"zıbın":["turkish"],"zılgıt":["turkish"],"zımbırtı":["turkish"],"zımpara":["turkish"],"zıpkın":["turkish"],"zigon":["turkish"],"zihinsel":["turkish"],"zihniyet":["turkish"],"zincir":["turkish"],"zindan":["turkish"],"zirzop":["turkish"],"ziyaret":["turkish"],"ziynet":["turkish"],"zoraki":["turkish"],"zorlu":["turkish"],"zorunlu":["turkish"],"züğürt":["turkish"],"zümre":["turkish"]}["abacate","abaixo","abalar","abater","abduzir","abelha","aberto","abismo","abotoar","abranger","abreviar","abrigar","abrupto","absinto","absoluto","absurdo","abutre","acabado","acalmar","acampar","acanhar","acaso","aceitar","acelerar","acenar","acervo","acessar","acetona","achatar","acidez","acima","acionado","acirrar","aclamar","aclive","acolhida","acomodar","acoplar","acordar","acumular","acusador","adaptar","adega","adentro","adepto","adequar","aderente","adesivo","adeus","adiante","aditivo","adjetivo","adjunto","admirar","adorar","adquirir","adubo","adverso","advogado","aeronave","afastar","aferir","afetivo","afinador","afivelar","aflito","afluente","afrontar","agachar","agarrar","agasalho","agenciar","agilizar","agiota","agitado","agora","agradar","agreste","agrupar","aguardar","agulha","ajoelhar","ajudar","ajustar","alameda","alarme","alastrar","alavanca","albergue","albino","alcatra","aldeia","alecrim","alegria","alertar","alface","alfinete","algum","alheio","aliar","alicate","alienar","alinhar","aliviar","almofada","alocar","alpiste","alterar","altitude","alucinar","alugar","aluno","alusivo","alvo","amaciar","amador","amarelo","amassar","ambas","ambiente","ameixa","amenizar","amido","amistoso","amizade","amolador","amontoar","amoroso","amostra","amparar","ampliar","ampola","anagrama","analisar","anarquia","anatomia","andaime","anel","anexo","angular","animar","anjo","anomalia","anotado","ansioso","anterior","anuidade","anunciar","anzol","apagador","apalpar","apanhado","apego","apelido","apertada","apesar","apetite","apito","aplauso","aplicada","apoio","apontar","aposta","aprendiz","aprovar","aquecer","arame","aranha","arara","arcada","ardente","areia","arejar","arenito","aresta","argiloso","argola","arma","arquivo","arraial","arrebate","arriscar","arroba","arrumar","arsenal","arterial","artigo","arvoredo","asfaltar","asilado","aspirar","assador","assinar","assoalho","assunto","astral","atacado","atadura","atalho","atarefar","atear","atender","aterro","ateu","atingir","atirador","ativo","atoleiro","atracar","atrevido","atriz","atual","atum","auditor","aumentar","aura","aurora","autismo","autoria","autuar","avaliar","avante","avaria","avental","avesso","aviador","avisar","avulso","axila","azarar","azedo","azeite","azulejo","babar","babosa","bacalhau","bacharel","bacia","bagagem","baiano","bailar","baioneta","bairro","baixista","bajular","baleia","baliza","balsa","banal","bandeira","banho","banir","banquete","barato","barbado","baronesa","barraca","barulho","baseado","bastante","batata","batedor","batida","batom","batucar","baunilha","beber","beijo","beirada","beisebol","beldade","beleza","belga","beliscar","bendito","bengala","benzer","berimbau","berlinda","berro","besouro","bexiga","bezerro","bico","bicudo","bienal","bifocal","bifurcar","bigorna","bilhete","bimestre","bimotor","biologia","biombo","biosfera","bipolar","birrento","biscoito","bisneto","bispo","bissexto","bitola","bizarro","blindado","bloco","bloquear","boato","bobagem","bocado","bocejo","bochecha","boicotar","bolada","boletim","bolha","bolo","bombeiro","bonde","boneco","bonita","borbulha","borda","boreal","borracha","bovino","boxeador","branco","brasa","braveza","breu","briga","brilho","brincar","broa","brochura","bronzear","broto","bruxo","bucha","budismo","bufar","bule","buraco","busca","busto","buzina","cabana","cabelo","cabide","cabo","cabrito","cacau","cacetada","cachorro","cacique","cadastro","cadeado","cafezal","caiaque","caipira","caixote","cajado","caju","calafrio","calcular","caldeira","calibrar","calmante","calota","camada","cambista","camisa","camomila","campanha","camuflar","canavial","cancelar","caneta","canguru","canhoto","canivete","canoa","cansado","cantar","canudo","capacho","capela","capinar","capotar","capricho","captador","capuz","caracol","carbono","cardeal","careca","carimbar","carneiro","carpete","carreira","cartaz","carvalho","casaco","casca","casebre","castelo","casulo","catarata","cativar","caule","causador","cautelar","cavalo","caverna","cebola","cedilha","cegonha","celebrar","celular","cenoura","censo","centeio","cercar","cerrado","certeiro","cerveja","cetim","cevada","chacota","chaleira","chamado","chapada","charme","chatice","chave","chefe","chegada","cheiro","cheque","chicote","chifre","chinelo","chocalho","chover","chumbo","chutar","chuva","cicatriz","ciclone","cidade","cidreira","ciente","cigana","cimento","cinto","cinza","ciranda","circuito","cirurgia","citar","clareza","clero","clicar","clone","clube","coado","coagir","cobaia","cobertor","cobrar","cocada","coelho","coentro","coeso","cogumelo","coibir","coifa","coiote","colar","coleira","colher","colidir","colmeia","colono","coluna","comando","combinar","comentar","comitiva","comover","complexo","comum","concha","condor","conectar","confuso","congelar","conhecer","conjugar","consumir","contrato","convite","cooperar","copeiro","copiador","copo","coquetel","coragem","cordial","corneta","coronha","corporal","correio","cortejo","coruja","corvo","cosseno","costela","cotonete","couro","couve","covil","cozinha","cratera","cravo","creche","credor","creme","crer","crespo","criada","criminal","crioulo","crise","criticar","crosta","crua","cruzeiro","cubano","cueca","cuidado","cujo","culatra","culminar","culpar","cultura","cumprir","cunhado","cupido","curativo","curral","cursar","curto","cuspir","custear","cutelo","damasco","datar","debater","debitar","deboche","debulhar","decalque","decimal","declive","decote","decretar","dedal","dedicado","deduzir","defesa","defumar","degelo","degrau","degustar","deitado","deixar","delator","delegado","delinear","delonga","demanda","demitir","demolido","dentista","depenado","depilar","depois","depressa","depurar","deriva","derramar","desafio","desbotar","descanso","desenho","desfiado","desgaste","desigual","deslize","desmamar","desova","despesa","destaque","desviar","detalhar","detentor","detonar","detrito","deusa","dever","devido","devotado","dezena","diagrama","dialeto","didata","difuso","digitar","dilatado","diluente","diminuir","dinastia","dinheiro","diocese","direto","discreta","disfarce","disparo","disquete","dissipar","distante","ditador","diurno","diverso","divisor","divulgar","dizer","dobrador","dolorido","domador","dominado","donativo","donzela","dormente","dorsal","dosagem","dourado","doutor","drenagem","drible","drogaria","duelar","duende","dueto","duplo","duquesa","durante","duvidoso","eclodir","ecoar","ecologia","edificar","edital","educado","efeito","efetivar","ejetar","elaborar","eleger","eleitor","elenco","elevador","eliminar","elogiar","embargo","embolado","embrulho","embutido","emenda","emergir","emissor","empatia","empenho","empinado","empolgar","emprego","empurrar","emulador","encaixe","encenado","enchente","encontro","endeusar","endossar","enfaixar","enfeite","enfim","engajado","engenho","englobar","engomado","engraxar","enguia","enjoar","enlatar","enquanto","enraizar","enrolado","enrugar","ensaio","enseada","ensino","ensopado","entanto","enteado","entidade","entortar","entrada","entulho","envergar","enviado","envolver","enxame","enxerto","enxofre","enxuto","epiderme","equipar","ereto","erguido","errata","erva","ervilha","esbanjar","esbelto","escama","escola","escrita","escuta","esfinge","esfolar","esfregar","esfumado","esgrima","esmalte","espanto","espelho","espiga","esponja","espreita","espumar","esquerda","estaca","esteira","esticar","estofado","estrela","estudo","esvaziar","etanol","etiqueta","euforia","europeu","evacuar","evaporar","evasivo","eventual","evidente","evoluir","exagero","exalar","examinar","exato","exausto","excesso","excitar","exclamar","executar","exemplo","exibir","exigente","exonerar","expandir","expelir","expirar","explanar","exposto","expresso","expulsar","externo","extinto","extrato","fabricar","fabuloso","faceta","facial","fada","fadiga","faixa","falar","falta","familiar","fandango","fanfarra","fantoche","fardado","farelo","farinha","farofa","farpa","fartura","fatia","fator","favorita","faxina","fazenda","fechado","feijoada","feirante","felino","feminino","fenda","feno","fera","feriado","ferrugem","ferver","festejar","fetal","feudal","fiapo","fibrose","ficar","ficheiro","figurado","fileira","filho","filme","filtrar","firmeza","fisgada","fissura","fita","fivela","fixador","fixo","flacidez","flamingo","flanela","flechada","flora","flutuar","fluxo","focal","focinho","fofocar","fogo","foguete","foice","folgado","folheto","forjar","formiga","forno","forte","fosco","fossa","fragata","fralda","frango","frasco","fraterno","freira","frente","fretar","frieza","friso","fritura","fronha","frustrar","fruteira","fugir","fulano","fuligem","fundar","fungo","funil","furador","furioso","futebol","gabarito","gabinete","gado","gaiato","gaiola","gaivota","galega","galho","galinha","galocha","ganhar","garagem","garfo","gargalo","garimpo","garoupa","garrafa","gasoduto","gasto","gata","gatilho","gaveta","gazela","gelado","geleia","gelo","gemada","gemer","gemido","generoso","gengiva","genial","genoma","genro","geologia","gerador","germinar","gesso","gestor","ginasta","gincana","gingado","girafa","girino","glacial","glicose","global","glorioso","goela","goiaba","golfe","golpear","gordura","gorjeta","gorro","gostoso","goteira","governar","gracejo","gradual","grafite","gralha","grampo","granada","gratuito","graveto","graxa","grego","grelhar","greve","grilo","grisalho","gritaria","grosso","grotesco","grudado","grunhido","gruta","guache","guarani","guaxinim","guerrear","guiar","guincho","guisado","gula","guloso","guru","habitar","harmonia","haste","haver","hectare","herdar","heresia","hesitar","hiato","hibernar","hidratar","hiena","hino","hipismo","hipnose","hipoteca","hoje","holofote","homem","honesto","honrado","hormonal","hospedar","humorado","iate","ideia","idoso","ignorado","igreja","iguana","ileso","ilha","iludido","iluminar","ilustrar","imagem","imediato","imenso","imersivo","iminente","imitador","imortal","impacto","impedir","implante","impor","imprensa","impune","imunizar","inalador","inapto","inativo","incenso","inchar","incidir","incluir","incolor","indeciso","indireto","indutor","ineficaz","inerente","infantil","infestar","infinito","inflamar","informal","infrator","ingerir","inibido","inicial","inimigo","injetar","inocente","inodoro","inovador","inox","inquieto","inscrito","inseto","insistir","inspetor","instalar","insulto","intacto","integral","intimar","intocado","intriga","invasor","inverno","invicto","invocar","iogurte","iraniano","ironizar","irreal","irritado","isca","isento","isolado","isqueiro","italiano","janeiro","jangada","janta","jararaca","jardim","jarro","jasmim","jato","javali","jazida","jejum","joaninha","joelhada","jogador","joia","jornal","jorrar","jovem","juba","judeu","judoca","juiz","julgador","julho","jurado","jurista","juro","justa","labareda","laboral","lacre","lactante","ladrilho","lagarta","lagoa","laje","lamber","lamentar","laminar","lampejo","lanche","lapidar","lapso","laranja","lareira","largura","lasanha","lastro","lateral","latido","lavanda","lavoura","lavrador","laxante","lazer","lealdade","lebre","legado","legendar","legista","leigo","leiloar","leitura","lembrete","leme","lenhador","lentilha","leoa","lesma","leste","letivo","letreiro","levar","leveza","levitar","liberal","libido","liderar","ligar","ligeiro","limitar","limoeiro","limpador","linda","linear","linhagem","liquidez","listagem","lisura","litoral","livro","lixa","lixeira","locador","locutor","lojista","lombo","lona","longe","lontra","lorde","lotado","loteria","loucura","lousa","louvar","luar","lucidez","lucro","luneta","lustre","lutador","luva","macaco","macete","machado","macio","madeira","madrinha","magnata","magreza","maior","mais","malandro","malha","malote","maluco","mamilo","mamoeiro","mamute","manada","mancha","mandato","manequim","manhoso","manivela","manobrar","mansa","manter","manusear","mapeado","maquinar","marcador","maresia","marfim","margem","marinho","marmita","maroto","marquise","marreco","martelo","marujo","mascote","masmorra","massagem","mastigar","matagal","materno","matinal","matutar","maxilar","medalha","medida","medusa","megafone","meiga","melancia","melhor","membro","memorial","menino","menos","mensagem","mental","merecer","mergulho","mesada","mesclar","mesmo","mesquita","mestre","metade","meteoro","metragem","mexer","mexicano","micro","migalha","migrar","milagre","milenar","milhar","mimado","minerar","minhoca","ministro","minoria","miolo","mirante","mirtilo","misturar","mocidade","moderno","modular","moeda","moer","moinho","moita","moldura","moleza","molho","molinete","molusco","montanha","moqueca","morango","morcego","mordomo","morena","mosaico","mosquete","mostarda","motel","motim","moto","motriz","muda","muito","mulata","mulher","multar","mundial","munido","muralha","murcho","muscular","museu","musical","nacional","nadador","naja","namoro","narina","narrado","nascer","nativa","natureza","navalha","navegar","navio","neblina","nebuloso","negativa","negociar","negrito","nervoso","neta","neural","nevasca","nevoeiro","ninar","ninho","nitidez","nivelar","nobreza","noite","noiva","nomear","nominal","nordeste","nortear","notar","noticiar","noturno","novelo","novilho","novo","nublado","nudez","numeral","nupcial","nutrir","nuvem","obcecado","obedecer","objetivo","obrigado","obscuro","obstetra","obter","obturar","ocidente","ocioso","ocorrer","oculista","ocupado","ofegante","ofensiva","oferenda","oficina","ofuscado","ogiva","olaria","oleoso","olhar","oliveira","ombro","omelete","omisso","omitir","ondulado","oneroso","ontem","opcional","operador","oponente","oportuno","oposto","orar","orbitar","ordem","ordinal","orfanato","orgasmo","orgulho","oriental","origem","oriundo","orla","ortodoxo","orvalho","oscilar","ossada","osso","ostentar","otimismo","ousadia","outono","outubro","ouvido","ovelha","ovular","oxidar","oxigenar","pacato","paciente","pacote","pactuar","padaria","padrinho","pagar","pagode","painel","pairar","paisagem","palavra","palestra","palheta","palito","palmada","palpitar","pancada","panela","panfleto","panqueca","pantanal","papagaio","papelada","papiro","parafina","parcial","pardal","parede","partida","pasmo","passado","pastel","patamar","patente","patinar","patrono","paulada","pausar","peculiar","pedalar","pedestre","pediatra","pedra","pegada","peitoral","peixe","pele","pelicano","penca","pendurar","peneira","penhasco","pensador","pente","perceber","perfeito","pergunta","perito","permitir","perna","perplexo","persiana","pertence","peruca","pescado","pesquisa","pessoa","petiscar","piada","picado","piedade","pigmento","pilastra","pilhado","pilotar","pimenta","pincel","pinguim","pinha","pinote","pintar","pioneiro","pipoca","piquete","piranha","pires","pirueta","piscar","pistola","pitanga","pivete","planta","plaqueta","platina","plebeu","plumagem","pluvial","pneu","poda","poeira","poetisa","polegada","policiar","poluente","polvilho","pomar","pomba","ponderar","pontaria","populoso","porta","possuir","postal","pote","poupar","pouso","povoar","praia","prancha","prato","praxe","prece","predador","prefeito","premiar","prensar","preparar","presilha","pretexto","prevenir","prezar","primata","princesa","prisma","privado","processo","produto","profeta","proibido","projeto","prometer","propagar","prosa","protetor","provador","publicar","pudim","pular","pulmonar","pulseira","punhal","punir","pupilo","pureza","puxador","quadra","quantia","quarto","quase","quebrar","queda","queijo","quente","querido","quimono","quina","quiosque","rabanada","rabisco","rachar","racionar","radial","raiar","rainha","raio","raiva","rajada","ralado","ramal","ranger","ranhura","rapadura","rapel","rapidez","raposa","raquete","raridade","rasante","rascunho","rasgar","raspador","rasteira","rasurar","ratazana","ratoeira","realeza","reanimar","reaver","rebaixar","rebelde","rebolar","recado","recente","recheio","recibo","recordar","recrutar","recuar","rede","redimir","redonda","reduzida","reenvio","refinar","refletir","refogar","refresco","refugiar","regalia","regime","regra","reinado","reitor","rejeitar","relativo","remador","remendo","remorso","renovado","reparo","repelir","repleto","repolho","represa","repudiar","requerer","resenha","resfriar","resgatar","residir","resolver","respeito","ressaca","restante","resumir","retalho","reter","retirar","retomada","retratar","revelar","revisor","revolta","riacho","rica","rigidez","rigoroso","rimar","ringue","risada","risco","risonho","robalo","rochedo","rodada","rodeio","rodovia","roedor","roleta","romano","roncar","rosado","roseira","rosto","rota","roteiro","rotina","rotular","rouco","roupa","roxo","rubro","rugido","rugoso","ruivo","rumo","rupestre","russo","sabor","saciar","sacola","sacudir","sadio","safira","saga","sagrada","saibro","salada","saleiro","salgado","saliva","salpicar","salsicha","saltar","salvador","sambar","samurai","sanar","sanfona","sangue","sanidade","sapato","sarda","sargento","sarjeta","saturar","saudade","saxofone","sazonal","secar","secular","seda","sedento","sediado","sedoso","sedutor","segmento","segredo","segundo","seiva","seleto","selvagem","semanal","semente","senador","senhor","sensual","sentado","separado","sereia","seringa","serra","servo","setembro","setor","sigilo","silhueta","silicone","simetria","simpatia","simular","sinal","sincero","singular","sinopse","sintonia","sirene","siri","situado","soberano","sobra","socorro","sogro","soja","solda","soletrar","solteiro","sombrio","sonata","sondar","sonegar","sonhador","sono","soprano","soquete","sorrir","sorteio","sossego","sotaque","soterrar","sovado","sozinho","suavizar","subida","submerso","subsolo","subtrair","sucata","sucesso","suco","sudeste","sufixo","sugador","sugerir","sujeito","sulfato","sumir","suor","superior","suplicar","suposto","suprimir","surdina","surfista","surpresa","surreal","surtir","suspiro","sustento","tabela","tablete","tabuada","tacho","tagarela","talher","talo","talvez","tamanho","tamborim","tampa","tangente","tanto","tapar","tapioca","tardio","tarefa","tarja","tarraxa","tatuagem","taurino","taxativo","taxista","teatral","tecer","tecido","teclado","tedioso","teia","teimar","telefone","telhado","tempero","tenente","tensor","tentar","termal","terno","terreno","tese","tesoura","testado","teto","textura","texugo","tiara","tigela","tijolo","timbrar","timidez","tingido","tinteiro","tiragem","titular","toalha","tocha","tolerar","tolice","tomada","tomilho","tonel","tontura","topete","tora","torcido","torneio","torque","torrada","torto","tostar","touca","toupeira","toxina","trabalho","tracejar","tradutor","trafegar","trajeto","trama","trancar","trapo","traseiro","tratador","travar","treino","tremer","trepidar","trevo","triagem","tribo","triciclo","tridente","trilogia","trindade","triplo","triturar","triunfal","trocar","trombeta","trova","trunfo","truque","tubular","tucano","tudo","tulipa","tupi","turbo","turma","turquesa","tutelar","tutorial","uivar","umbigo","unha","unidade","uniforme","urologia","urso","urtiga","urubu","usado","usina","usufruir","vacina","vadiar","vagaroso","vaidoso","vala","valente","validade","valores","vantagem","vaqueiro","varanda","vareta","varrer","vascular","vasilha","vassoura","vazar","vazio","veado","vedar","vegetar","veicular","veleiro","velhice","veludo","vencedor","vendaval","venerar","ventre","verbal","verdade","vereador","vergonha","vermelho","verniz","versar","vertente","vespa","vestido","vetorial","viaduto","viagem","viajar","viatura","vibrador","videira","vidraria","viela","viga","vigente","vigiar","vigorar","vilarejo","vinco","vinheta","vinil","violeta","virada","virtude","visitar","visto","vitral","viveiro","vizinho","voador","voar","vogal","volante","voleibol","voltagem","volumoso","vontade","vulto","vuvuzela","xadrez","xarope","xeque","xeretar","xerife","xingar","zangado","zarpar","zebu","zelador","zombar","zoologia","zumbido"]["абзац","абонент","абсурд","авангард","авария","август","авиация","автор","агент","агитация","агрегат","адвокат","адмирал","адрес","азарт","азот","академия","аквариум","аксиома","акула","акцент","акция","аллея","алмаз","алтарь","альбом","альянс","амбиция","анализ","анекдот","анкета","ансамбль","антенна","апельсин","аппарат","аппетит","апрель","аптека","арбуз","аргумент","аренда","арест","армия","аромат","арсенал","артерия","артист","архив","аспирант","асфальт","атака","атомный","атрибут","аукцион","афиша","аэропорт","бабочка","бабушка","багаж","база","бактерия","баланс","балерина","балкон","бандит","банк","барабан","барон","барышня","барьер","бассейн","батарея","башмак","башня","бедный","беженец","бездна","белка","белый","бензин","берег","беседа","бешеный","билет","бинокль","биржа","битва","благо","блеск","близкий","блин","блок","блюдо","богатый","бодрый","боец","бокал","боковой","бокс","более","болото","болтать","большой","бомба","борт","борьба","босой","ботинок","бояться","брак","брать","бревно","бред","бригада","бродяга","броня","бросить","брызги","брюки","брюхо","бугор","будка","будни","будущее","буква","букет","бульвар","бумага","бунт","бурный","буря","бутылка","бухта","бывший","быстро","бытовой","быть","бюджет","бюро","бюст","вагон","важный","вакцина","валенок","вальс","валюта","ванная","варенье","вариант","вблизи","вверх","вводить","вдали","вдвое","вдова","вдоль","вдруг","ведро","ведущий","ведьма","вежливо","везде","веко","вексель","велеть","великий","венец","веник","веранда","верблюд","верить","верный","версия","вертеть","верхний","вершина","весело","весна","весомый","вести","весь","ветеран","ветхий","вечер","вечно","вешалка","вещество","взамен","взгляд","вздох","взнос","взойти","взор","взрыв","взять","видеть","видимо","визг","визит","вилка","вина","вирус","висок","витамин","витрина","вихрь","вишня","вкус","влага","владелец","власть","влево","влияние","вложить","вместе","внешний","вникать","внимание","вновь","внук","внутри","внучка","внушать","вовлечь","вовремя","вовсю","вода","водород","водяной","воевать","возврат","возглас","воздух","возить","возле","возня","возраст","война","войско","вокзал","волос","волчий","вольный","воля","вообще","вопль","вопрос","ворота","восемь","восток","вплоть","вполне","вправе","впредь","впрочем","врач","вредный","время","вручить","всадник","всегда","вскоре","вскрыть","всплеск","вспышка","встреча","всюду","всякий","второй","вход","вчера","выбор","вывод","выгнать","выдать","выехать","вызов","выйти","выкуп","вылезти","вымыть","выпасть","выпить","выплата","выпуск","вырасти","выручка","выслать","высокий","выставка","вышка","вязать","вялый","газета","газовый","галерея","галстук","гамма","гарантия","гармония","гарнизон","гастроли","гвардия","гвоздь","гектар","генерал","гений","геном","геолог","герб","герой","гибкий","гигант","гимн","гипотеза","гитара","главный","глагол","гладить","глаз","глина","глоток","глубокий","глупый","глухой","глыба","глядеть","гнев","гнездо","гнилой","годовой","голова","голубой","голый","гонорар","гордость","горизонт","горло","горный","город","горшок","горький","горючее","горячий","готовый","градус","грамм","граница","граф","гребень","гриб","гримаса","грозить","грохот","грош","грубый","грудь","груз","грунт","группа","груша","грязный","губа","гудок","гулкий","гулять","гусеница","густо","гусь","давление","давно","даже","дальний","данный","дарить","датчик","дать","дача","двадцать","дважды","дверь","двигать","движение","двойной","двор","дебют","девятый","дежурный","действие","декабрь","деление","дело","дельфин","день","дерево","держать","дерзкий","десять","деталь","детский","дефект","дефицит","деятель","джаз","джинсы","джунгли","диагноз","диалог","диапазон","диван","дивизия","дивный","диета","дизайн","дикарь","дилер","динамика","диплом","директор","дитя","длинный","дневник","добрый","добыча","доверие","догадка","догнать","дождь","доклад","доктор","документ","долго","должен","долина","донос","дорога","досада","доска","достать","досуг","доход","доцент","дощатый","драка","древний","дремать","дробный","дрова","дрожать","другой","дружба","дубовый","дуга","думать","дурной","духи","душный","дуэль","дуэт","дыра","дыхание","дюжина","дядя","едва","единый","ерунда","если","ехать","жадный","жажда","жалеть","жалоба","жанр","жареный","жаркий","жгучий","жевать","желание","желудок","жена","женщина","жертва","жест","жидкость","житель","жить","жрец","жулик","журнал","жуткий","забрать","забыть","завести","завод","завтра","загадка","загнать","заговор","задача","задеть","задний","задолго","заехать","заказ","закон","закрыть","закуска","залезть","залить","залп","замок","замуж","замысел","занавес","заново","занять","заодно","запись","запрос","запуск","запястье","заранее","заросль","зарплата","заря","засада","заслуга","заснуть","застать","затвор","затеять","затрата","затылок","захват","зачем","защита","заявить","заяц","звезда","звено","звонить","здесь","зелень","земля","зеркало","зерно","зима","злой","змея","знамя","знание","значит","золотой","зона","зонтик","зоопарк","зрачок","зрение","зритель","зубной","зубр","игла","идеал","идеолог","идея","идол","идти","изба","избить","избрать","избыток","извлечь","извне","изгиб","изгнать","издание","изделие","изнутри","изобилие","изоляция","изредка","изрядно","изучение","изъять","изящный","икона","икра","иллюзия","именно","иметь","имидж","империя","импульс","иначе","инвалид","индекс","индивид","инерция","инженер","иногда","иной","институт","интерес","интрига","интуиция","инфаркт","инцидент","ирония","искать","испуг","история","итог","июнь","кабель","кабинет","каблук","кавалер","кадр","каждый","кажется","казино","калитка","камень","камин","канал","кандидат","каникулы","канон","капитан","капля","капот","капуста","карандаш","карета","каркас","карман","картина","карьера","каска","кассета","кастрюля","каталог","катер","каток","катушка","кафедра","качество","каша","кашлять","каюта","квадрат","квартира","квота","кепка","кивнуть","километр","кино","киоск","кипяток","кирпич","кислота","кисть","клавиша","клапан","класс","клей","клетка","клиент","климат","клиника","кличка","клоун","клочок","клуб","клумба","ключ","книга","кнопка","кнут","княгиня","князь","кобура","когда","кодекс","кожа","коктейль","колено","коллега","колонна","колпак","кольцо","колючий","коляска","команда","комедия","комиссия","коммуна","комната","комок","компания","комфорт","конвейер","конгресс","конечно","конкурс","контроль","концерт","конь","конюшня","копать","копейка","копыто","корабль","корень","корзина","коридор","кормить","корпус","космос","костюм","косяк","котел","котлета","который","коттедж","кофе","кофта","кошка","кража","край","красный","краткий","кредит","крем","крепкий","кресло","кривой","кризис","кристалл","критерий","кричать","кровь","крокодил","кролик","кроме","крона","круг","кружка","крупный","крутой","крушение","крыло","крыша","крючок","кстати","кубик","куда","кузов","кукла","кулак","кулиса","культура","кумир","купе","купить","купол","купюра","курица","курорт","курс","куртка","кусок","куст","кухня","кушать","лабиринт","лавка","лагерь","ладно","ладонь","лапа","лауреат","лгать","лебедь","левый","легенда","легкий","ледяной","лежать","лезвие","лезть","лекция","ленивый","лента","лепесток","лесной","лестница","лететь","лето","лечить","лига","лидер","лиловый","лимон","линия","липкий","лист","литр","лихой","лицо","лишить","лишний","ловить","логика","лодка","ложь","лозунг","локоть","лопата","лошадь","лукавый","луна","лучший","лысый","льгота","любить","любой","людской","люстра","лютый","лягушка","магазин","магия","майор","майский","максимум","макушка","мало","мальчик","мама","манера","марка","март","маршрут","масса","мастер","масштаб","материал","матч","махать","машина","маяк","мебель","медаль","медведь","медицина","медь","между","мелкий","мелочь","мемуары","меньше","меню","менять","мера","мерцать","место","месяц","металл","метод","метр","механизм","меховой","мечтать","мешать","мешок","миграция","микрофон","милиция","миллион","милость","миля","мимо","минерал","министр","минута","мирный","миска","миссия","митинг","мишень","младший","мнение","мнимый","много","могучий","модель","может","мозг","мокрый","молекула","молния","молодой","молчать","момент","монета","монитор","монолог","монстр","монтаж","мораль","море","морковь","мороз","морщина","мостовая","мотать","мотив","мотор","мохнатый","мрамор","мрачный","мстить","мудрый","мужество","мужчина","музей","музыка","мундир","муравей","мусор","муха","мчаться","мысль","мыться","мышца","мышь","мюзикл","мягкий","мясо","набор","навык","наглый","нагрузка","надежда","надзор","надо","наедине","назад","название","назло","наивный","найти","наконец","налево","наличие","налог","намерен","нанести","напасть","например","народ","наследие","натура","наука","наутро","начать","небо","неважно","невеста","негодяй","недавно","неделя","недолго","недра","недуг","нежный","незачем","некто","нелепый","неловко","нельзя","немало","немой","неплохо","нервный","нередко","нестись","неудача","неужели","нефть","неясный","нигде","низкий","никакой","никогда","никуда","ничто","ничуть","ниша","нищий","новость","новый","нога","ноготь","ножницы","ноздря","номер","носить","носок","ночь","ноябрь","нрав","нуль","нынче","нырять","нюанс","няня","обаяние","обед","обезьяна","обещать","обжечь","обзор","обилие","обитать","область","облик","обложка","обмен","обморок","обожать","обои","оболочка","оборона","обочина","образ","обрести","обрыв","обувь","обучение","обход","общество","общий","объект","обыск","обычно","обязать","овощи","овраг","овца","оговорка","ограда","огурец","одежда","одеяло","один","однако","одолеть","ожидать","озеро","океан","окно","около","окоп","окраина","октябрь","опасный","опека","операция","описание","оплата","опора","оппонент","оптимизм","оптовый","опухоль","опыт","оратор","орбита","орган","орден","орел","оригинал","ориентир","оркестр","оружие","осенний","осколок","осмотр","остров","отбор","отбыть","отвлечь","отдать","отдел","отдых","отель","отец","отзыв","отказ","отклик","открыть","откуда","отличие","отныне","отойти","отпуск","отрасль","отросток","отрывок","отряд","отсек","отставка","отсюда","оттенок","оттого","отчего","отъезд","офис","офицер","охота","охрана","оценка","очаг","очень","очередь","очищать","ошибка","ощущение","павильон","падать","пазуха","пакет","палата","палец","палуба","пальто","память","панель","паника","пара","парень","пароход","партия","парус","паспорт","пассажир","пастух","патент","патрон","пауза","паук","паутина","пафос","пахнуть","пациент","пачка","певец","педагог","пейзаж","пенсия","пепел","первый","перед","период","перо","перрон","персонаж","перчатка","песня","песок","петля","петрушка","петух","пехота","печать","печень","пешком","пещера","пианист","пиджак","пилот","пионер","пирамида","пирожок","письмо","пища","плавание","плакать","пламя","план","пласт","платить","пленный","плечо","плита","плод","плоский","плотный","плохой","площадь","плыть","плюс","пляж","плясать","победа","повар","повод","повсюду","повязка","погода","погреб","подбор","подвиг","подделка","поджать","поднос","подпись","подруга","подход","подчас","подъезд","поединок","поезд","поесть","поехать","пожалуй","пожилой","позади","позвать","поздний","позиция","позор","поиск","поймать","пойти","поклон","покой","покрыть","полдень","полезный","ползти","полк","полный","половина","полтора","польза","поляна","помидор","помнить","помощь","попасть","поперек","поплыть","пополам","поправка","попугай","попытка","порог","портрет","порция","порыв","порядок","после","посол","посреди","постель","посуда","потом","похвала","похожий","поцелуй","почва","почему","пошлина","поэма","поэтому","право","праздник","практика","прах","преграда","предмет","прежде","прелесть","премия","препарат","пресса","прибыть","прижать","прийти","приказ","прилавок","пример","принять","природа","притом","прихожая","прицел","причина","приют","прогноз","продукт","проект","прожить","прокат","промысел","пропуск","просто","против","профиль","процесс","прочий","прошлый","прощать","пружина","прут","прыжок","прямой","птица","публика","пугать","пуговица","пузырь","пульт","пуля","пункт","пускать","пустой","путь","пухлый","пучок","пушистый","пушка","пчела","пшеница","пылать","пыль","пышный","пьеса","пятка","пятно","пятый","пятьсот","работа","равнина","ради","радость","радуга","разбить","развитие","разговор","раздел","различие","размер","разный","разрыв","разум","район","ракета","раковина","рамка","рано","рапорт","распад","рассказ","расти","расход","расцвет","рация","рвануть","рваться","реакция","ребро","реветь","редактор","редкий","реестр","режим","резать","резерв","резина","резко","резной","рейс","реклама","рекорд","религия","рельс","ремень","ремонт","реплика","репортаж","ресница","ресторан","реформа","рецепт","речь","решение","ржавый","риск","рисунок","ритуал","рифма","робко","робот","ровесник","ровно","родной","рождение","роза","розовый","розыск","роль","роман","роскошь","роспись","рост","рубашка","рубеж","рубить","рубрика","рудник","рука","рукопись","румяный","русло","рухнуть","ручей","ручной","рыба","рыжий","рынок","рыхлый","рыцарь","рычаг","рюкзак","рядом","садовый","сажать","салон","салфетка","салют","самец","самовар","самый","сани","санкция","сапог","сарай","сатира","сахар","сбить","сбоку","сборная","сбыт","свадьба","свалка","сварить","свежий","сверху","свет","свеча","свинья","свист","свитер","свобода","сводка","свой","свыше","связь","сдаться","сделать","сегмент","сегодня","седло","седой","седьмой","сезон","сейф","сейчас","секрет","сектор","секунда","семинар","семья","сенатор","сено","сенсация","сентябрь","сервис","сердце","середина","сержант","серия","серый","сессия","сесть","сетевой","сжатый","сжечь","сзади","сигнал","сиденье","сила","силуэт","сильный","символ","симпатия","симфония","синий","синтез","синяк","сирень","система","ситуация","сияние","сказать","скала","скамейка","скандал","скатерть","скачок","скважина","сквер","сквозь","скелет","скидка","склад","сколько","скорый","скосить","скот","скрипка","скудный","скука","слабый","слава","сладкий","слегка","след","слеза","слепой","слесарь","слишком","слово","слог","сложный","сломать","служба","слух","случай","слышать","слюна","смежный","смелый","сменить","смесь","сметана","смех","смола","смуглый","смутный","смущать","смысл","снайпер","снаряд","сначала","снег","снизу","сниться","сно��а","снять","собака","соблазн","собрание","событие","совесть","совсем","согласие","создать","сознание","созреть","сойтись","сокол","солдат","соленый","солнце","солома","сомнение","сонный","соперник","соратник","сорвать","сосед","сосиска","состав","сотня","соус","союз","спад","спальня","спасти","спектр","сперва","спешить","спина","спирт","список","спичка","сплав","спонсор","спор","способ","справка","спустя","спутник","сразу","средство","срок","срыв","ссора","ссылка","ставить","стадия","стакан","станция","старый","стая","стебель","стекло","стена","степень","стереть","стиль","стимул","стирать","стихи","стоить","стойка","стол","стонать","стопа","сторона","стоянка","страна","стричь","строгий","струя","студент","стук","ступня","стыдно","суббота","субъект","сувенир","сугроб","сугубо","судить","судно","судьба","суета","суметь","сумма","сумрак","сундук","супруг","суровый","сутки","сухой","суша","существо","сфера","схема","схожий","сценарий","счастье","считать","съезд","сыграть","сырой","сытый","сыщик","сюда","сюжет","сюрприз","тайна","также","такой","такси","тактика","талия","таможня","танец","таракан","тарелка","тариф","тащить","таять","тварь","театр","тезис","текст","текущий","телефон","тема","темнота","теневой","теннис","теория","теперь","тепло","терапия","терзать","термин","терпеть","терраса","терять","тесный","тетрадь","техника","течение","тигр","типовой","тираж","титул","тихий","ткань","товарищ","тоже","толпа","толстый","толчок","толщина","только","тонкий","тонна","топить","топор","торговля","тормоз","торчать","тотчас","точка","точно","тощий","трава","традиция","трактор","трамвай","траншея","трасса","тревога","трезвый","тренер","трепет","треск","третий","трещина","трибуна","тридцать","триста","триумф","трогать","тройка","тронуть","тропа","тротуар","трубка","труд","трюк","тряпка","туго","туловище","туман","тумбочка","тундра","тупик","турист","турнир","тусклый","туфля","туча","тысяча","тяга","тяжело","убежать","убогий","уборка","уважение","увезти","уволить","угадать","угол","угощать","угроза","угрюмый","удар","удачный","уделять","удивить","удобный","удочка","уезжать","ужин","узел","узкий","уйти","указание","уклон","украсть","укусить","улетать","улица","улыбка","умело","умение","умный","умолять","унести","унижать","унылый","упаковка","упасть","упорно","упрек","урна","уровень","урожай","уронить","усадьба","усатый","усвоить","усилие","условие","услуга","усмешка","успеть","устав","устоять","утечка","утешать","утро","уцелеть","участие","ученик","учесть","ущелье","ущерб","уютный","фабрика","фаворит","факел","факт","фамилия","фантазия","фасад","февраль","феномен","фермер","фигура","физика","филиал","философ","фильм","финал","флаг","флот","фойе","фокус","фонарь","фонд","фонтан","форма","форум","фото","фрагмент","фраза","фракция","фронт","фрукт","функция","фуражка","футбол","футляр","халат","хаос","характер","хата","хвалить","хватать","хвойный","хвост","химия","хирург","хитрый","хищник","хлеб","хлынуть","хмурый","ходить","хозяин","хоккей","холм","холст","хорошо","хотеть","храбрый","храм","хранить","хребет","хрен","хрипло","хроника","хрупкий","художник","худший","хулиган","хутор","царь","цветок","целевой","целиком","целое","цель","цензура","ценить","центр","цепной","цикл","цилиндр","цирк","цитата","цифра","чайник","часы","чашка","человек","челюсть","чемодан","чемпион","чепуха","червь","чердак","через","чернила","черта","чеснок","честно","четверть","четыре","число","чистый","читатель","чтение","чтобы","чувство","чудак","чудный","чудо","чужой","чулок","чума","чушь","чуять","шагать","шанс","шапка","шарик","шарф","шахматы","шашлык","шедевр","шептать","шерсть","шестой","шинель","ширина","шишка","шкаф","школа","шкура","шланг","шлем","шнур","шоколад","шорох","шоссе","шпион","шприц","штаб","штамм","штаны","штатный","штора","штраф","штурм","штык","шумно","шуршать","шутить","шутка","щедрый","щека","щенок","экзамен","экипаж","экономия","экран","эксперт","элемент","элитный","эмоция","энергия","эпизод","эпоха","эскиз","эстрада","этап","этика","этот","эфир","эффект","эшелон","юбилей","юбка","южный","юмор","юность","юрист","юстиция","яблоко","явление","ягода","ядро","язык","яйцо","якобы","якорь","январь","яркий","ярмарка","ярость","ясный","яхта","ячейка","ящик"]["ábaco","abdomen","abeja","abierto","abogado","abono","aborto","abrazo","abrir","abuelo","abuso","acabar","academia","acceso","acción","aceite","acelga","acento","aceptar","ácido","aclarar","acné","acoger","acoso","activo","acto","actriz","actuar","acudir","acuerdo","acusar","adicto","admitir","adoptar","adorno","aduana","adulto","aéreo","afectar","afición","afinar","afirmar","ágil","agitar","agonía","agosto","agotar","agregar","agrio","agua","agudo","águila","aguja","ahogo","ahorro","aire","aislar","ajedrez","ajeno","ajuste","alacrán","alambre","alarma","alba","álbum","alcalde","aldea","alegre","alejar","alerta","aleta","alfiler","alga","algodón","aliado","aliento","alivio","alma","almeja","almíbar","altar","alteza","altivo","alto","altura","alumno","alzar","amable","amante","amapola","amargo","amasar","ámbar","ámbito","ameno","amigo","amistad","amor","amparo","amplio","ancho","anciano","ancla","andar","andén","anemia","ángulo","anillo","ánimo","anís","anotar","antena","antiguo","antojo","anual","anular","anuncio","añadir","añejo","año","apagar","aparato","apetito","apio","aplicar","apodo","aporte","apoyo","aprender","aprobar","apuesta","apuro","arado","araña","arar","árbitro","árbol","arbusto","archivo","arco","arder","ardilla","arduo","área","árido","aries","armonía","arnés","aroma","arpa","arpón","arreglo","arroz","arruga","arte","artista","asa","asado","asalto","ascenso","asegurar","aseo","asesor","asiento","asilo","asistir","asno","asombro","áspero","astilla","astro","astuto","asumir","asunto","atajo","ataque","atar","atento","ateo","ático","atleta","átomo","atraer","atroz","atún","audaz","audio","auge","aula","aumento","ausente","autor","aval","avance","avaro","ave","avellana","avena","avestruz","avión","aviso","ayer","ayuda","ayuno","azafrán","azar","azote","azúcar","azufre","azul","baba","babor","bache","bahía","baile","bajar","balanza","balcón","balde","bambú","banco","banda","baño","barba","barco","barniz","barro","báscula","bastón","basura","batalla","batería","batir","batuta","baúl","bazar","bebé","bebida","bello","besar","beso","bestia","bicho","bien","bingo","blanco","bloque","blusa","boa","bobina","bobo","boca","bocina","boda","bodega","boina","bola","bolero","bolsa","bomba","bondad","bonito","bono","bonsái","borde","borrar","bosque","bote","botín","bóveda","bozal","bravo","brazo","brecha","breve","brillo","brinco","brisa","broca","broma","bronce","brote","bruja","brusco","bruto","buceo","bucle","bueno","buey","bufanda","bufón","búho","buitre","bulto","burbuja","burla","burro","buscar","butaca","buzón","caballo","cabeza","cabina","cabra","cacao","cadáver","cadena","caer","café","caída","caimán","caja","cajón","cal","calamar","calcio","caldo","calidad","calle","calma","calor","calvo","cama","cambio","camello","camino","campo","cáncer","candil","canela","canguro","canica","canto","caña","cañón","caoba","caos","capaz","capitán","capote","captar","capucha","cara","carbón","cárcel","careta","carga","cariño","carne","carpeta","carro","carta","casa","casco","casero","caspa","castor","catorce","catre","caudal","causa","cazo","cebolla","ceder","cedro","celda","célebre","celoso","célula","cemento","ceniza","centro","cerca","cerdo","cereza","cero","cerrar","certeza","césped","cetro","chacal","chaleco","champú","chancla","chapa","charla","chico","chiste","chivo","choque","choza","chuleta","chupar","ciclón","ciego","cielo","cien","cierto","cifra","cigarro","cima","cinco","cine","cinta","ciprés","circo","ciruela","cisne","cita","ciudad","clamor","clan","claro","clase","clave","cliente","clima","clínica","cobre","cocción","cochino","cocina","coco","código","codo","cofre","coger","cohete","cojín","cojo","cola","colcha","colegio","colgar","colina","collar","colmo","columna","combate","comer","comida","cómodo","compra","conde","conejo","conga","conocer","consejo","contar","copa","copia","corazón","corbata","corcho","cordón","corona","correr","coser","cosmos","costa","cráneo","cráter","crear","crecer","creído","crema","cría","crimen","cripta","crisis","cromo","crónica","croqueta","crudo","cruz","cuadro","cuarto","cuatro","cubo","cubrir","cuchara","cuello","cuento","cuerda","cuesta","cueva","cuidar","culebra","culpa","culto","cumbre","cumplir","cuna","cuneta","cuota","cupón","cúpula","curar","curioso","curso","curva","cutis","dama","danza","dar","dardo","dátil","deber","débil","década","decir","dedo","defensa","definir","dejar","delfín","delgado","delito","demora","denso","dental","deporte","derecho","derrota","desayuno","deseo","desfile","desnudo","destino","desvío","detalle","detener","deuda","día","diablo","diadema","diamante","diana","diario","dibujo","dictar","diente","dieta","diez","difícil","digno","dilema","diluir","dinero","directo","dirigir","disco","diseño","disfraz","diva","divino","doble","doce","dolor","domingo","don","donar","dorado","dormir","dorso","dos","dosis","dragón","droga","ducha","duda","duelo","dueño","dulce","dúo","duque","durar","dureza","duro","ébano","ebrio","echar","eco","ecuador","edad","edición","edificio","editor","educar","efecto","eficaz","eje","ejemplo","elefante","elegir","elemento","elevar","elipse","élite","elixir","elogio","eludir","embudo","emitir","emoción","empate","empeño","empleo","empresa","enano","encargo","enchufe","encía","enemigo","enero","enfado","enfermo","engaño","enigma","enlace","enorme","enredo","ensayo","enseñar","entero","entrar","envase","envío","época","equipo","erizo","escala","escena","escolar","escribir","escudo","esencia","esfera","esfuerzo","espada","espejo","espía","esposa","espuma","esquí","estar","este","estilo","estufa","etapa","eterno","ética","etnia","evadir","evaluar","evento","evitar","exacto","examen","exceso","excusa","exento","exigir","exilio","existir","éxito","experto","explicar","exponer","extremo","fábrica","fábula","fachada","fácil","factor","faena","faja","falda","fallo","falso","faltar","fama","familia","famoso","faraón","farmacia","farol","farsa","fase","fatiga","fauna","favor","fax","febrero","fecha","feliz","feo","feria","feroz","fértil","fervor","festín","fiable","fianza","fiar","fibra","ficción","ficha","fideo","fiebre","fiel","fiera","fiesta","figura","fijar","fijo","fila","filete","filial","filtro","fin","finca","fingir","finito","firma","flaco","flauta","flecha","flor","flota","fluir","flujo","flúor","fobia","foca","fogata","fogón","folio","folleto","fondo","forma","forro","fortuna","forzar","fosa","foto","fracaso","frágil","franja","frase","fraude","freír","freno","fresa","frío","frito","fruta","fuego","fuente","fuerza","fuga","fumar","función","funda","furgón","furia","fusil","fútbol","futuro","gacela","gafas","gaita","gajo","gala","galería","gallo","gamba","ganar","gancho","ganga","ganso","garaje","garza","gasolina","gastar","gato","gavilán","gemelo","gemir","gen","género","genio","gente","geranio","gerente","germen","gesto","gigante","gimnasio","girar","giro","glaciar","globo","gloria","gol","golfo","goloso","golpe","goma","gordo","gorila","gorra","gota","goteo","gozar","grada","gráfico","grano","grasa","gratis","grave","grieta","grillo","gripe","gris","grito","grosor","grúa","grueso","grumo","grupo","guante","guapo","guardia","guerra","guía","guiño","guion","guiso","guitarra","gusano","gustar","haber","hábil","hablar","hacer","hacha","hada","hallar","hamaca","harina","haz","hazaña","hebilla","hebra","hecho","helado","helio","hembra","herir","hermano","héroe","hervir","hielo","hierro","hígado","higiene","hijo","himno","historia","hocico","hogar","hoguera","hoja","hombre","hongo","honor","honra","hora","hormiga","horno","hostil","hoyo","hueco","huelga","huerta","hueso","huevo","huida","huir","humano","húmedo","humilde","humo","hundir","huracán","hurto","icono","ideal","idioma","ídolo","iglesia","iglú","igual","ilegal","ilusión","imagen","imán","imitar","impar","imperio","imponer","impulso","incapaz","índice","inerte","infiel","informe","ingenio","inicio","inmenso","inmune","innato","insecto","instante","interés","íntimo","intuir","inútil","invierno","ira","iris","ironía","isla","islote","jabalí","jabón","jamón","jarabe","jardín","jarra","jaula","jazmín","jefe","jeringa","jinete","jornada","joroba","joven","joya","juerga","jueves","juez","jugador","jugo","juguete","juicio","junco","jungla","junio","juntar","júpiter","jurar","justo","juvenil","juzgar","kilo","koala","labio","lacio","lacra","lado","ladrón","lagarto","lágrima","laguna","laico","lamer","lámina","lámpara","lana","lancha","langosta","lanza","lápiz","largo","larva","lástima","lata","látex","latir","laurel","lavar","lazo","leal","lección","leche","lector","leer","legión","legumbre","lejano","lengua","lento","leña","león","leopardo","lesión","letal","letra","leve","leyenda","libertad","libro","licor","líder","lidiar","lienzo","liga","ligero","lima","límite","limón","limpio","lince","lindo","línea","lingote","lino","linterna","líquido","liso","lista","litera","litio","litro","llaga","llama","llanto","llave","llegar","llenar","llevar","llorar","llover","lluvia","lobo","loción","loco","locura","lógica","logro","lombriz","lomo","lonja","lote","lucha","lucir","lugar","lujo","luna","lunes","lupa","lustro","luto","luz","maceta","macho","madera","madre","maduro","maestro","mafia","magia","mago","maíz","maldad","maleta","malla","malo","mamá","mambo","mamut","manco","mando","manejar","manga","maniquí","manjar","mano","manso","manta","mañana","mapa","máquina","mar","marco","marea","marfil","margen","marido","mármol","marrón","martes","marzo","masa","máscara","masivo","matar","materia","matiz","matriz","máximo","mayor","mazorca","mecha","medalla","medio","médula","mejilla","mejor","melena","melón","memoria","menor","mensaje","mente","menú","mercado","merengue","mérito","mes","mesón","meta","meter","método","metro","mezcla","miedo","miel","miembro","miga","mil","milagro","militar","millón","mimo","mina","minero","mínimo","minuto","miope","mirar","misa","miseria","misil","mismo","mitad","mito","mochila","moción","moda","modelo","moho","mojar","molde","moler","molino","momento","momia","monarca","moneda","monja","monto","moño","morada","morder","moreno","morir","morro","morsa","mortal","mosca","mostrar","motivo","mover","móvil","mozo","mucho","mudar","mueble","muela","muerte","muestra","mugre","mujer","mula","muleta","multa","mundo","muñeca","mural","muro","músculo","museo","musgo","música","muslo","nácar","nación","nadar","naipe","naranja","nariz","narrar","nasal","natal","nativo","natural","náusea","naval","nave","navidad","necio","néctar","negar","negocio","negro","neón","nervio","neto","neutro","nevar","nevera","nicho","nido","niebla","nieto","niñez","niño","nítido","nivel","nobleza","noche","nómina","noria","norma","norte","nota","noticia","novato","novela","novio","nube","nuca","núcleo","nudillo","nudo","nuera","nueve","nuez","nulo","número","nutria","oasis","obeso","obispo","objeto","obra","obrero","observar","obtener","obvio","oca","ocaso","océano","ochenta","ocho","ocio","ocre","octavo","octubre","oculto","ocupar","ocurrir","odiar","odio","odisea","oeste","ofensa","oferta","oficio","ofrecer","ogro","oído","oír","ojo","ola","oleada","olfato","olivo","olla","olmo","olor","olvido","ombligo","onda","onza","opaco","opción","ópera","opinar","oponer","optar","óptica","opuesto","oración","orador","oral","órbita","orca","orden","oreja","órgano","orgía","orgullo","oriente","origen","orilla","oro","orquesta","oruga","osadía","oscuro","osezno","oso","ostra","otoño","otro","oveja","óvulo","óxido","oxígeno","oyente","ozono","pacto","padre","paella","página","pago","país","pájaro","palabra","palco","paleta","pálido","palma","paloma","palpar","pan","panal","pánico","pantera","pañuelo","papá","papel","papilla","paquete","parar","parcela","pared","parir","paro","párpado","parque","párrafo","parte","pasar","paseo","pasión","paso","pasta","pata","patio","patria","pausa","pauta","pavo","payaso","peatón","pecado","pecera","pecho","pedal","pedir","pegar","peine","pelar","peldaño","pelea","peligro","pellejo","pelo","peluca","pena","pensar","peñón","peón","peor","pepino","pequeño","pera","percha","perder","pereza","perfil","perico","perla","permiso","perro","persona","pesa","pesca","pésimo","pestaña","pétalo","petróleo","pez","pezuña","picar","pichón","pie","piedra","pierna","pieza","pijama","pilar","piloto","pimienta","pino","pintor","pinza","piña","piojo","pipa","pirata","pisar","piscina","piso","pista","pitón","pizca","placa","plan","plata","playa","plaza","pleito","pleno","plomo","pluma","plural","pobre","poco","poder","podio","poema","poesía","poeta","polen","policía","pollo","polvo","pomada","pomelo","pomo","pompa","poner","porción","portal","posada","poseer","posible","poste","potencia","potro","pozo","prado","precoz","pregunta","premio","prensa","preso","previo","primo","príncipe","prisión","privar","proa","probar","proceso","producto","proeza","profesor","programa","prole","promesa","pronto","propio","próximo","prueba","público","puchero","pudor","pueblo","puerta","puesto","pulga","pulir","pulmón","pulpo","pulso","puma","punto","puñal","puño","pupa","pupila","puré","quedar","queja","quemar","querer","queso","quieto","química","quince","quitar","rábano","rabia","rabo","ración","radical","raíz","rama","rampa","rancho","rango","rapaz","rápido","rapto","rasgo","raspa","rato","rayo","raza","razón","reacción","realidad","rebaño","rebote","recaer","receta","rechazo","recoger","recreo","recto","recurso","red","redondo","reducir","reflejo","reforma","refrán","refugio","regalo","regir","regla","regreso","rehén","reino","reír","reja","relato","relevo","relieve","relleno","reloj","remar","remedio","remo","rencor","rendir","renta","reparto","repetir","reposo","reptil","res","rescate","resina","respeto","resto","resumen","retiro","retorno","retrato","reunir","revés","revista","rey","rezar","rico","riego","rienda","riesgo","rifa","rígido","rigor","rincón","riñón","río","riqueza","risa","ritmo","rito","rizo","roble","roce","rociar","rodar","rodeo","rodilla","roer","rojizo","rojo","romero","romper","ron","ronco","ronda","ropa","ropero","rosa","rosca","rostro","rotar","rubí","rubor","rudo","rueda","rugir","ruido","ruina","ruleta","rulo","rumbo","rumor","ruptura","ruta","rutina","sábado","saber","sabio","sable","sacar","sagaz","sagrado","sala","saldo","salero","salir","salmón","salón","salsa","salto","salud","salvar","samba","sanción","sandía","sanear","sangre","sanidad","sano","santo","sapo","saque","sardina","sartén","sastre","satán","sauna","saxofón","sección","seco","secreto","secta","sed","seguir","seis","sello","selva","semana","semilla","senda","sensor","señal","señor","separar","sepia","sequía","ser","serie","sermón","servir","sesenta","sesión","seta","setenta","severo","sexo","sexto","sidra","siesta","siete","siglo","signo","sílaba","silbar","silencio","silla","símbolo","simio","sirena","sistema","sitio","situar","sobre","socio","sodio","sol","solapa","soldado","soledad","sólido","soltar","solución","sombra","sondeo","sonido","sonoro","sonrisa","sopa","soplar","soporte","sordo","sorpresa","sorteo","sostén","sótano","suave","subir","suceso","sudor","suegra","suelo","sueño","suerte","sufrir","sujeto","sultán","sumar","superar","suplir","suponer","supremo","sur","surco","sureño","surgir","susto","sutil","tabaco","tabique","tabla","tabú","taco","tacto","tajo","talar","talco","talento","talla","talón","tamaño","tambor","tango","tanque","tapa","tapete","tapia","tapón","taquilla","tarde","tarea","tarifa","tarjeta","tarot","tarro","tarta","tatuaje","tauro","taza","tazón","teatro","techo","tecla","técnica","tejado","tejer","tejido","tela","teléfono","tema","temor","templo","tenaz","tender","tener","tenis","tenso","teoría","terapia","terco","término","ternura","terror","tesis","tesoro","testigo","tetera","texto","tez","tibio","tiburón","tiempo","tienda","tierra","tieso","tigre","tijera","tilde","timbre","tímido","timo","tinta","tío","típico","tipo","tira","tirón","titán","títere","título","tiza","toalla","tobillo","tocar","tocino","todo","toga","toldo","tomar","tono","tonto","topar","tope","toque","tórax","torero","tormenta","torneo","toro","torpedo","torre","torso","tortuga","tos","tosco","toser","tóxico","trabajo","tractor","traer","tráfico","trago","traje","tramo","trance","trato","trauma","trazar","trébol","tregua","treinta","tren","trepar","tres","tribu","trigo","tripa","triste","triunfo","trofeo","trompa","tronco","tropa","trote","trozo","truco","trueno","trufa","tubería","tubo","tuerto","tumba","tumor","túnel","túnica","turbina","turismo","turno","tutor","ubicar","úlcera","umbral","unidad","unir","universo","uno","untar","uña","urbano","urbe","urgente","urna","usar","usuario","útil","utopía","uva","vaca","vacío","vacuna","vagar","vago","vaina","vajilla","vale","válido","valle","valor","válvula","vampiro","vara","variar","varón","vaso","vecino","vector","vehículo","veinte","vejez","vela","velero","veloz","vena","vencer","venda","veneno","vengar","venir","venta","venus","ver","verano","verbo","verde","vereda","verja","verso","verter","vía","viaje","vibrar","vicio","víctima","vida","vídeo","vidrio","viejo","viernes","vigor","vil","villa","vinagre","vino","viñedo","violín","viral","virgo","virtud","visor","víspera","vista","vitamina","viudo","vivaz","vivero","vivir","vivo","volcán","volumen","volver","voraz","votar","voto","voz","vuelo","vulgar","yacer","yate","yegua","yema","yerno","yeso","yodo","yoga","yogur","zafiro","zanja","zapato","zarza","zona","zorro","zumo","zurdo"]["abajur","abaküs","abartı","abdal","abdest","abiye","abluka","abone","absorbe","absürt","acayip","acele","acemi","açıkgöz","adalet","adam","adezyon","adisyon","adliye","adres","afacan","afili","afiş","afiyet","aforizm","afra","ağaç","ağır","ahbap","ahkam","ahlak","ahtapot","aidat","aile","ajan","akademi","akarsu","akbaş","akciğer","akdeniz","akıbet","akıl","akıntı","akide","akrep","akrobasi","aksiyon","akşam","aktif","aktör","aktris","akustik","alaca","albüm","alçak","aldanma","aleni","alet","alfabe","algılama","alıngan","alkış","alkol","alpay","alperen","altın","altüst","altyapı","alyuvar","amade","amatör","amazon","ambalaj","amblem","ambulans","amca","amel","amigo","amir","amiyane","amorti","ampul","anadolu","anahtar","anakonda","anaokul","anapara","anarşi","anatomi","anayasa","anekdot","anestezi","angaje","anka","anket","anlamlı","anne","anomali","anonim","anten","antlaşma","apse","araba","aracı","araf","arbede","arda","arefe","arena","argo","argüman","arkadaş","armoni","aroma","arsa","arsız","artı","artist","aruz","asansör","asayiş","asfalt","asgari","asil","asker","askı","aslan","asosyal","astsubay","asya","aşçı","aşırı","aşure","atabey","ataman","ateş","atmaca","atmosfer","atom","atölye","avcı","avdet","avize","avlu","avokado","avrupa","avukat","ayaz","ayçiçeği","aydın","aygıt","ayna","ayran","ayrıntı","azim","baca","bagaj","bağlantı","bahadır","bahçe","baki","bakkal","baklava","bakteri","balçık","balina","balo","balta","bant","banyo","bardak","barış","başbuğ","başıboş","başkan","başlık","bavul","bayındır","baykuş","bazlama","bedel","begüm","bekçi","bekle","belge","belki","bencil","benek","bengi","benzer","berjer","berk","bermuda","berrak","beşik","beton","beyin","beyoğlu","bıçak","biberiye","bidon","biftek","bihaber","bikini","bilezik","bilinç","bilye","bina","binbaşı","binyıl","bisiklet","bisküvi","bitki","bizzat","bodrum","boğaz","bohça","bolero","boncuk","bonfile","borsa","boru","bostan","boşboğaz","botanik","boya","boykot","boynuz","bozgun","bozkır","bölüm","börek","buçuk","bugün","buğday","buhar","buhran","bulvar","buram","burçak","burs","burun","butik","buzdağı","buzkıran","bücür","büfe","bülten","bütçe","bütün","büyük","cacık","cadı","cahil","cambaz","canhıraş","casus","cazibe","cehalet","cehennem","ceket","cemre","cenin","cennet","cepken","cerrah","cesur","cetvel","cevher","ceylan","cılız","cıva","cilt","cisim","ciyak","coğrafya","cömert","cumba","cüzdan","çabucak","çadır","çağdaş","çağlayan","çağrı","çakmak","çalışkan","çamaşır","çapa","çaput","çarık","çarpan","çarşaf","çayhane","çekirdek","çelebi","çember","çenet","çengel","çerçeve","çerez","çeşit","çeşme","çete","çevre","çeyiz","çeyrek","çığır","çılgın","çıngırak","çift","çiğdem","çikolata","çilek","çimen","çivi","çoban","çocuk","çokgen","çomak","çorba","çözelti","çubuk","çukur","çuval","çürük","dağbaşı","dağılım","daktilo","daldırış","dalga","dalkavuk","damak","damıtma","damla","dana","dandik","danışman","daniska","dantel","dargeçit","darphane","davet","dayı","defter","değer","değirmen","dehşet","delgeç","demir","deneyim","denge","depo","deprem","derdest","dere","derhal","derman","dernek","derviş","desen","destan","dışarı","dışbükey","dijital","dikbaşlı","dilekçe","dimağ","dinamik","dindar","dinleme","dinozor","dipçik","dipnot","direniş","dirsek","disiplin","disk","divriği","dizüstü","dobra","dodurga","doğalgaz","doktor","doküman","dolap","donanım","dondurma","donör","doruk","dosdoğru","dost","dosya","dozer","döküm","dönence","dörtyol","dövme","dram","dublaj","durum","duvak","duyarga","duyma","duyuru","düğme","düğüm","dükkan","dünür","düpedüz","dürbün","düşünür","düzayak","düzeltme","ebeveyn","ebru","ecel","ecnebi","ecza","edat","edilgen","efendi","efor","efsane","egemen","egzersiz","eğrelti","ekarte","ekip","eklem","ekmek","ekol","ekonomi","ekose","ekran","ekvator","elaman","elastik","elbet","elbise","elçi","eldiven","elebaşı","eleştiri","elma","eloğlu","elveda","emare","emekçi","emisyon","emniyet","empati","emsal","emzik","endüstri","enerji","engebe","engin","enişte","enkaz","entari","entegre","entrika","enzim","erdem","ergen","erguvan","erkek","erozyon","ertesi","erzak","esaret","esenlik","eser","eski","esnek","eşarp","eşofman","eşraf","eşya","eşzaman","etik","etken","etkinlik","etüt","evet","evire","evrak","evrim","eyalet","eyvah","ezber","fabrika","fanatik","fanus","fason","fasulye","fatih","fatura","fauna","favori","fayans","fayton","fazıl","fazilet","federal","felsefe","fener","feribot","fersah","fesih","festival","feveran","feza","fıçı","fıldır","fındık","fırça","fırsat","fırtına","fıtık","fidan","fidye","figür","fihrist","fikir","fildişi","filo","filtre","fincan","firuze","fitil","fiyaka","fizik","flaş","flüt","fosil","fren","fukara","futbol","garabet","gariban","garnitür","gazi","gece","gedik","gelenek","gelin","gemi","genç","geniş","geometri","gerçek","gevrek","gezegen","gezgin","geziyolu","gıcık","gıda","gıybet","girdap","girişim","gitar","giyecek","giysi","gizem","gofret","goril","göbek","göçebe","göğüs","gökdelen","gökmen","gökyüzü","gölge","gömlek","gönül","görenek","görkemli","görsel","gösteri","gövde","gözaltı","gözcü","gözdağı","gözleme","gözyaşı","grup","gurbet","gusül","gübre","güfte","gümüş","günaydın","güncel","gündüz","güneş","günyüzü","gürbüz","güvercin","güzel","haber","hacamat","hacim","hademe","hafız","hafriyat","hafta","hakan","hakem","hakikat","haksever","halı","hançer","hane","hangar","hapis","hapşırık","harf","haseki","hasret","hatun","havuç","haylaz","haysiyet","hayvan","hedef","hektar","hemen","hemfikir","hendek","hepsi","hergele","herhangi","hesap","heyecan","heykel","hezimet","hıçkırık","hızölçer","hicviye","hikaye","hikmet","hile","hisse","hobi","hoca","horlama","hormon","hoşbeş","hoşgörü","hoyrat","hörgüç","höyük","hudut","hukuk","hunhar","hurda","huysuz","huzur","hücum","hükümet","hünkar","hüviyet","ırmak","ısıölçer","ısıtıcı","ıspanak","ısrar","ışıldak","ızdırap","ızgara","ibadet","icat","içbükey","içecek","içgüdü","içsel","idman","iftihar","iğne","ihanet","ihbar","ihdas","ihmal","ihracat","ihsan","ikilem","ikindi","ikircik","iklim","iksir","iktibas","ilaç","ilçe","ileri","iletişim","ilgi","ilhak","ilkbahar","ilkokul","ilmek","imkan","imleç","imsak","imtihan","imza","ince","inkar","inşa","ipek","ipucu","irade","irfan","irmik","isabet","iskele","israf","isyan","işçi","işgal","işgüzar","işlem","itibar","itiraf","ivedi","ivme","iyileşme","iyimser","izbandut","izci","izdiham","izin","jakoben","jandarma","jargon","kabadayı","kablo","kabus","kaçamak","kadeh","kadın","kadraj","kafa","kafkas","kağıt","kağnı","kahkaha","kahraman","kahvaltı","kakül","kaldırım","kale","kalibre","kalkan","kalpak","kamış","kamyon","kanat","kandaş","kanepe","kanser","kanun","kaos","kapı","kaplıca","kaptan","karanlık","kardeş","karga","karınca","karmaşa","karşıt","kasırga","kask","kasvet","katkı","katman","kavram","kaygan","kaynakça","kayyum","kedi","kehanet","kekik","kelebek","kenar","kerkenez","kerpiç","kesirli","kesmece","kestane","keşkek","ketçap","keyfiyet","kıble","kıdemli","kılavuz","kılçık","kılıf","kıraç","kırmızı","kırsal","kısayol","kısım","kıskanç","kısmet","kışla","kıvanç","kıvılcım","kıvrık","kıyafet","kıymetli","kızak","kızılcık","kibar","kinaye","kira","kiremit","kirli","kirpik","kişisel","kitap","koçbaşı","kodaman","koğuş","kokteyl","kolaycı","kolbastı","kolonya","koltuk","kolye","kombine","komedyen","komiser","komposto","komşu","komuta","konak","konfor","koni","konsül","kopya","korkusuz","korna","korse","korunak","korvet","kostüm","koşul","koyu","kozmik","köfte","kökensel","köprücük","köpük","kördüğüm","körfez","köstebek","köşegen","kötü","kravat","kriter","kuantum","kudurma","kuluçka","kulübe","kumanya","kumbara","kumlu","kumpir","kumral","kundura","kupa","kupkuru","kuramsal","kurbağa","kurdele","kurgu","kurmay","kurşun","kurtuluş","kurultay","kurye","kusursuz","kuşak","kuşbaşı","kuşkulu","kutlama","kutsal","kutup","kuver","kuyruk","kuzey","kuzgun","küçük","külçe","külfet","külliye","kültürel","kümes","künefe","küresel","kütle","lahana","lahmacun","lamba","lansman","lavaş","layık","leğen","levent","leziz","lezzet","lider","likide","liman","liste","litre","liyakat","lodos","lokanta","lokman","lokum","lunapark","lütfen","lüzum","nokta","mabet","macera","macun","madalya","madde","madem","mağara","mağdur","mağfiret","mağlup","mahalle","mahcup","mahir","mahkeme","mahlas","mahrum","mahsul","makas","makbuz","makine","makro","maksat","makul","maliye","manav","mangal","manidar","manken","mantık","manzara","mareşal","margarin","marifet","market","marmelat","masaüstü","masmavi","masraf","masum","matah","materyal","matrak","maval","mavra","maydanoz","mayhoş","maytap","mazbata","mazeret","mazlum","mazot","mazur","meblağ","mebus","mecaz","mecbur","meclis","mecmua","mecnun","meçhul","medeni","mehtap","mekanik","melodi","meltem","memur","mendil","menekşe","menteşe","meraklı","mercek","merdiven","merhaba","merinos","merkez","mermi","mert","mesafe","mesele","mesken","meslek","meşale","meşgul","meşhur","metafor","metin","metre","mevcut","mevkidaş","meydan","meyil","meyve","meziyet","mezun","mıknatıs","mısra","mızıka","miğfer","mihrak","mikrofon","miktar","milat","milli","mimar","minare","mineral","minik","minyon","mirliva","misafir","miskin","miting","miyop","mizah","mobilya","model","monitör","morötesi","motive","motor","mozaik","muavin","mucize","muhafız","muhteşem","mukayese","mumya","musluk","muşamba","mutabık","mutfak","mutlu","muzaffer","muzdarip","mübarek","mücadele","müdür","müfredat","müftü","mühendis","mühim","mühlet","mükemmel","mülk","mümkün","mümtaz","müsrif","müstesna","müşahit","müşteri","mütercim","müthiş","müze","müzik","nabız","nadas","nadir","nahoş","nakarat","nakış","nalbur","namlu","namus","nankör","nargile","narkoz","nasıl","nasip","naylon","nazar","nazım","nazik","neden","nefes","negatif","neon","neptün","nerede","nesil","nesnel","neşeli","netice","nevresim","neyse","neyzen","nezaket","nezih","nezle","nicel","nilüfer","nimet","nisan","nispet","nitekim","nizam","nohut","noksan","normal","nostalji","noter","nöbet","numara","numune","nutuk","nüfus","obabaşı","obez","obje","ocak","odun","ofansif","ofis","oğlak","oğuz","okçu","oklava","oksijen","okul","okumuş","okutman","okuyucu","okyanus","olağan","olanak","olası","olay","olgun","olimpik","olumlu","omlet","omurga","onarım","onursal","opera","optik","oral","orantı","ordu","organik","orijin","orkide","orman","orta","oruç","otağ","otantik","otel","otoban","otogar","otomobil","otonom","otopark","otorite","otoyol","oturum","oyuk","oyuncak","ozan","ödeme","ödenek","ödev","ödül","ödünç","öfke","öğlen","öğrenci","öğün","öğütücü","öksürük","ölçme","ölçü","ölümsüz","ömür","önayak","öncü","önder","önem","önerge","öngörü","önlük","önsezi","öpücük","ördek","örgü","örtbas","örtme","örtü","örümcek","örüntü","öteberi","öteki","övünç","öykü","öyleyse","özçekim","özdeyiş","özel","özenti","özerk","özgürlük","özlem","özlü","özne","özsever","özümseme","özür","özveri","pabuç","padişah","palamut","palmiye","palto","palyaço","pamuk","panayır","pancar","panda","panel","panik","panjur","pankart","pano","pansuman","pantolon","panzehir","papatya","papyon","paraşüt","parça","pardösü","parfüm","parıltı","parkur","parmak","parodi","parsel","partner","pasaport","pasif","paskalya","pastırma","paşa","patates","paten","patika","patlıcan","patolog","patron","payanda","paydaş","payidar","paylaşma","paytak","peçete","pedal","peder","pehlivan","pekala","pekmez","pelerin","pelikan","pelüş","pembe","pena","pencere","pense","perçin","perde","pergel","perişan","peron","personel","perşembe","peruk","pervane","pespaye","pestil","peşin","petek","petrol","petunya","peynir","peyzaj","pınar","pırasa","pırlanta","pide","pikap","piknik","pilav","piliç","pilot","pipet","pipo","piramit","pirinç","pirzola","pist","pişik","pişman","piyasa","piyes","plaj","plaket","planlama","platform","plazma","podyum","poğaça","polat","polen","politika","pompa","popüler","porselen","portakal","posa","poster","poşet","poyraz","pozitif","pranga","pratik","prenses","prim","problem","profil","program","proje","protokol","prova","puan","pudra","pusula","püre","pürüz","püstül","püsür","racon","radar","radikal","radyo","rafadan","rafine","rağbet","rahat","rahle","rakam","raket","rakip","rakun","ralli","rampa","randevu","ranza","rapor","rastgele","rasyonel","razı","realite","reçine","refah","referans","refik","reform","rehber","rehin","reis","rekabet","reklam","rekor","rektör","renk","resim","resmen","restoran","retorik","revaç","revize","reyon","rezalet","rezerv","rezil","rıhtım","rıza","ritim","ritüel","rivayet","robot","roman","rota","rozet","röportaj","rötar","ruble","ruhban","ruhsat","rulet","rulo","runik","rutin","rutubet","rüşvet","rütbe","rüya","rüzgar","sabah","sabıka","sabit","sabun","saçma","sade","sadık","safahat","safdil","safkan","sağanak","sağduyu","sağlam","saha","sahiden","sahne","sakal","sakız","sakin","saklama","saksağan","salamura","salça","salgı","salınım","salkım","salon","saltanat","sanatçı","sancak","sandalye","saniye","saplantı","sapsız","saray","sarışın","sarkık","sarmaşık","satır","savaşım","savunma","saydam","sayfa","saygın","sayısal","sebep","seçenek","seçim","seçkin","seçmen","seda","sedir","sedye","sefer","sehpa","sekizgen","selektör","selvi","semavi","sembol","seminer","senaryo","sendika","senkron","sensör","sentez","sepet","seramik","serbest","serdar","seremoni","sergi","serhat","serin","sermaye","serpuş","sersem","serüven","servis","sesli","sesteş","sevap","seviye","seyahat","seyirci","sezon","sıcak","sıfat","sıhhi","sınanma","sınır","sıradan","sırdaş","sırma","sırtüstü","sızgıt","siftah","sigorta","sihirbaz","silah","silecek","silindir","simetri","simge","simit","sincap","sindirim","sinema","sinirli","sipariş","sirke","siroz","sistem","sivilce","siyasi","slogan","soba","sofra","soğuk","sohbet","sokak","solfej","solunum","somut","sonbahar","sonraki","sonsuz","sorunsuz","sosyete","soyağacı","soydaş","soygun","soytarı","söğüş","sömürge","sönük","söylem","sözcük","sözde","spatula","spektrum","spiker","spiral","sponsor","sporcu","sprey","stabil","statü","stok","stopaj","strateji","subay","sucuk","suçüstü","suhulet","sulama","sungur","sunucu","surat","susam","suskun","sükse","sükut","sülale","sünger","süpürge","sürahi","süreç","sürgün","sürüm","süsleme","sütanne","sütlaç","sütun","süvari","şahane","şahbaz","şahit","şahsiyet","şakıma","şaklaban","şakrak","şamar","şampiyon","şanslı","şantiye","şapka","şarkıcı","şartname","şaşırma","şaşkın","şatafat","şayet","şebeke","şefkat","şeftali","şehir","şehvet","şeker","şekil","şelale","şema","şemsiye","şerbet","şeref","şerit","şımarık","şıpıdık","şifre","şimdi","şimşek","şipşak","şirin","şişe","şişirme","şofben","şöhret","şölen","şüphe","tabaka","tabela","tabure","tadilat","taharet","tahıl","tahkim","tahlil","tahmin","tahrifat","tahsilat","tahta","taklit","takoz","taksici","taktik","takvim","talebe","talip","tamamen","tamirci","tampon","tamtakır","tandır","tanecik","tanıtım","tanrı","tansiyon","tapan","tapınak","taptaze","tapu","tarafgir","tarhana","tarım","tarih","tarla","tartak","tarumar","tasarım","tasdik","taslak","tastamam","taşeron","taşınmaz","taşra","tatava","tatbikat","tatil","tatlı","tavsiye","tavşan","tavuk","taze","taziye","tazminat","tebeşir","tebrik","tecrübe","teçhizat","tedarik","tedbir","teftiş","teğet","teğmen","tehdit","tehlike","tekdüze","tekerlek","tekme","teknik","tekrar","telef","telsiz","telve","temas","tembel","temiz","temkin","tempo","temsilci","tendon","teneke","tenha","tenkit","tepegöz","tepki","terazi","terbiye","tercih","tereyağı","terfi","terim","terminal","tersane","tertip","tesadüf","tescil","tesir","teslimat","tespit","testere","teşekkür","teşhir","teşrif","teşvik","teyze","tezahür","tezgah","tıbbi","tıkaç","tıkışık","tıknaz","tılsım","tıpkı","tıraş","tırışka","tırmanış","tırnak","tırpan","tıslama","ticaret","tilki","tiryaki","titreşim","tohum","tokat","tolere","tomar","tombak","tomurcuk","topaç","toplum","toprak","toptan","toraman","torpido","tortu","tosbağa","toynak","tören","trafik","trajedi","tramvay","transfer","tribün","triko","tugay","tuğla","tuğrul","tuhaf","tulumba","tunç","turan","turkuaz","turnusol","turşu","turuncu","tutanak","tutkal","tutsak","tutum","tuyuğ","tuzlu","tüccar","tüfek","tükenmez","tülbent","tümleç","tünel","türbin","türev","türk","tüzük","ucube","ucuz","uçak","uçurtma","ufuk","uğrak","uğur","ukala","ulaşım","ulema","ulus","ulvi","umursama","umut","unutkan","uslu","ustabaşı","ustura","usul","utangaç","uyanık","uyarı","uydu","uygar","uygulama","uykusuz","uysal","uyuşma","uzantı","uzay","uzgören","uzlaşma","uzman","uzun","ücra","ücret","üçbudak","üçgen","üçkağıt","üçleme","üfürük","ülke","ümit","üniforma","ünite","ünlem","üretken","ürün","üslup","üstel","üstün","üşengeç","üşüme","ütopya","üvey","üzengi","üzgün","üzüm","vagon","vaka","vakfiye","vakıf","vakit","vakum","vapur","varil","varlık","varsayım","varyemez","vasıta","vasiyet","vatandaş","vazife","vazo","veciz","vefa","vehim","veliaht","veresiye","verimli","verkaç","vernik","vertigo","vesait","vesika","vestiyer","veznedar","vicdan","vilayet","virane","virgül","vişne","vites","vokal","volkan","vurma","vurucu","vücut","yabancı","yabgu","yağış","yağlı","yağmur","yakamoz","yakın","yaklaşık","yalçın","yalıtım","yaman","yanardağ","yangın","yanıt","yankı","yanlış","yansıma","yapay","yapboz","yapımcı","yaprak","yaratık","yarbay","yardım","yargıç","yarıçap","yasemin","yastık","yaşam","yatak","yatırım","yavru","yaygara","yayıncı","yayla","yazılım","yekpare","yekvücut","yelkovan","yelpaze","yemek","yemiş","yengeç","yeniçeri","yeraltı","yerküre","yerleşke","yeryüzü","yeşil","yetenek","yetkili","yığınak","yıkama","yılbaşı","yıldırım","yılkı","yılmaz","yırtıcı","yiğit","yoğurt","yokuş","yolcu","yoldaş","yolgeçen","yolkesen","yolüstü","yordam","yorgan","yorumcu","yosun","yöndeş","yönetim","yönlü","yöntem","yöresel","yörünge","yufka","yukarı","yumruk","yumurta","yuvarlak","yücelme","yükçeker","yüklem","yüksek","yürek","yürütme","yüzde","yüzeysel","yüzgeç","yüzüstü","yüzyıl","zabıta","zafer","zahmet","zambak","zaptiye","zarafet","zaruret","zeka","zekice","zemberek","zemin","zencefil","zeplin","zeytin","zıbın","zılgıt","zımbırtı","zımpara","zıpkın","zigon","zihinsel","zihniyet","zincir","zindan","zirzop","ziyaret","ziynet","zoraki","zorlu","zorunlu","züğürt","zümre"]const b4a = require('b4a')

function byteLength (size) {
  return Math.ceil(size / 8)
}

function get (buffer, bit) {
  const n = buffer.BYTES_PER_ELEMENT * 8

  const offset = bit & (n - 1)
  const i = (bit - offset) / n

  return (buffer[i] & (1 << offset)) !== 0
}

function set (buffer, bit, value = true) {
  const n = buffer.BYTES_PER_ELEMENT * 8

  const offset = bit & (n - 1)
  const i = (bit - offset) / n
  const mask = 1 << offset

  if (value) {
    if ((buffer[i] & mask) !== 0) return false
  } else {
    if ((buffer[i] & mask) === 0) return false
  }

  buffer[i] ^= mask
  return true
}

function setRange (buffer, start, end, value = true) {
  const n = buffer.BYTES_PER_ELEMENT * 8

  let remaining = end - start
  let offset = start & (n - 1)
  let i = (start - offset) / n

  let changed = false

  while (remaining > 0) {
    const mask = (2 ** Math.min(remaining, n - offset) - 1) << offset

    if (value) {
      if ((buffer[i] & mask) !== mask) {
        buffer[i] |= mask
        changed = true
      }
    } else {
      if ((buffer[i] & mask) !== 0) {
        buffer[i] &= ~mask
        changed = true
      }
    }

    remaining -= n - offset
    offset = 0
    i++
  }

  return changed
}

function fill (buffer, value, start = 0, end = buffer.byteLength * 8) {
  const n = buffer.BYTES_PER_ELEMENT * 8
  let i, j

  {
    const offset = start & (n - 1)
    i = (start - offset) / n

    if (offset !== 0) {
      const mask = (2 ** Math.min(n - offset, end - start) - 1) << offset

      if (value) buffer[i] |= mask
      else buffer[i] &= ~mask

      i++
    }
  }

  {
    const offset = end & (n - 1)
    j = (end - offset) / n

    if (offset !== 0 && j >= i) {
      const mask = (2 ** offset) - 1

      if (value) buffer[j] |= mask
      else buffer[j] &= ~mask
    }
  }

  return buffer.fill(value ? (2 ** n) - 1 : 0, i, j)
}

function toggle (buffer, bit) {
  const n = buffer.BYTES_PER_ELEMENT * 8

  const offset = bit & (n - 1)
  const i = (bit - offset) / n
  const mask = 1 << offset

  buffer[i] ^= mask
  return (buffer[i] & mask) !== 0
}

function remove (buffer, bit) {
  return set(buffer, bit, false)
}

function removeRange (buffer, start, end) {
  return setRange(buffer, start, end, false)
}

function indexOf (buffer, value, position = 0) {
  for (let i = position, n = buffer.byteLength * 8; i < n; i++) {
    if (get(buffer, i) === value) return i
  }

  return -1
}

function lastIndexOf (buffer, value, position = buffer.byteLength * 8 - 1) {
  for (let i = position; i >= 0; i--) {
    if (get(buffer, i) === value) return i
  }

  return -1
}

function of (...bits) {
  return from(bits)
}

function from (bits) {
  const buffer = b4a.alloc(byteLength(bits.length))
  for (let i = 0; i < bits.length; i++) set(buffer, i, bits[i])
  return buffer
}

function * iterator (buffer) {
  for (let i = 0, n = buffer.byteLength * 8; i < n; i++) yield get(buffer, i)
}

module.exports = {
  byteLength,
  get,
  set,
  setRange,
  fill,
  toggle,
  remove,
  removeRange,
  indexOf,
  lastIndexOf,
  of,
  from,
  iterator
}
{
  "name": "bits-to-bytes",
  "version": "1.3.0",
  "description": "Functions for doing bit manipulation of typed arrays",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "scripts": {
    "test": "standard && brittle test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bits-to-bytes.git"
  },
  "author": "Kasper Isager Dalsgarð <kasper@funktionel.co>",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/holepunchto/bits-to-bytes/issues"
  },
  "homepage": "https://github.com/holepunchto/bits-to-bytes#readme",
  "dependencies": {
    "b4a": "^1.5.0"
  },
  "devDependencies": {
    "brittle": "^2.3.1",
    "standard": "^17.0.0"
  }
}
const EventEmitter = require('events')
const Protomux = require('protomux')
const { Readable } = require('streamx')
const sodium = require('sodium-universal')
const b4a = require('b4a')
const c = require('compact-encoding')
const bitfield = require('compact-encoding-bitfield')
const bits = require('bits-to-bytes')
const errors = require('./lib/errors')

exports.Server = class BlindRelayServer extends EventEmitter {
  constructor(opts = {}) {
    super()

    const { createStream } = opts

    this._createStream = createStream
    this._pairing = new Map()
    this._activePairingRefs = new Map()
    this._sessions = new Set()
    this.stats = createStats()
  }

  get sessions() {
    return this._sessions[Symbol.iterator]()
  }

  accept(stream, opts) {
    const session = new BlindRelaySession(this, stream, opts)

    this._sessions.add(session)
    this.stats.sessions.accepted++

    return session
  }

  async close() {
    const ending = []

    for (const session of this._sessions) {
      ending.push(session.end())
    }

    await Promise.all(ending)

    this._pairing.clear()
  }

  _trackActiveLink(keyString) {
    const refs = this._activePairingRefs.get(keyString) || 0

    if (refs === 0) this.stats.pairings.active++

    this._activePairingRefs.set(keyString, refs + 1)
  }

  _untrackActiveLink(keyString) {
    const refs = this._activePairingRefs.get(keyString)

    if (refs === undefined) return

    if (refs === 1) {
      this._activePairingRefs.delete(keyString)
      this.stats.pairings.active--
    } else {
      this._activePairingRefs.set(keyString, refs - 1)
    }
  }
}

class BlindRelaySession extends EventEmitter {
  constructor(server, stream, opts = {}) {
    super()

    const { id, handshake, handshakeEncoding } = opts

    this._server = server
    this._mux = Protomux.from(stream)

    this._channel = this._mux.createChannel({
      protocol: 'blind-relay',
      id,
      handshake: handshake ? handshakeEncoding || c.raw : null,
      onopen: this._onopen.bind(this),
      onclose: this._onclose.bind(this),
      ondestroy: this._ondestroy.bind(this)
    })

    this._pair = this._channel.addMessage({
      encoding: m.pair,
      onmessage: this._onpair.bind(this)
    })

    this._unpair = this._channel.addMessage({
      encoding: m.unpair,
      onmessage: this._onunpair.bind(this)
    })

    this._ending = null
    this._destroyed = false
    this._error = null
    this._pairing = new Set()
    this._links = new Map()

    this._onerror = (err) => {
      this._server.stats.streams.errors++
      this.emit('error', err)
    }

    this._channel.open(handshake)
  }

  get closed() {
    return this._channel.closed
  }

  get mux() {
    return this._mux
  }

  get stream() {
    return this._mux.stream
  }

  _onopen() {
    this._server.stats.sessions.opened++
    this.emit('open')
  }

  _onclose() {
    this._ending = Promise.resolve()

    const err = this._error || errors.CHANNEL_CLOSED()
    this._server.stats.pairings.cancelled += this._pairing.size

    for (const token of this._pairing) {
      if (this._server._pairing.delete(token.toString('hex'))) {
        this._server.stats.pairings.pending--
      }
    }

    for (const link of this._links.values()) {
      link.destroy(err)
    }

    this._pairing.clear()
    this._links.clear()

    this._server._sessions.delete(this)
    this._server.stats.sessions.closed++

    this.emit('close')
  }

  _ondestroy() {
    this._destroyed = true
    this.emit('destroy')
  }

  _onpair({ isInitiator, token, id: remoteId }) {
    const keyString = token.toString('hex')

    let pair = this._server._pairing.get(keyString)

    if (pair === undefined) {
      pair = new BlindRelayPair(token)
      this._server._pairing.set(keyString, pair)
      this._server.stats.pairings.pending++
    } else if (pair.links[+isInitiator]) return

    this._pairing.add(keyString)
    this._server.stats.pairings.requested++

    pair.links[+isInitiator] = new BlindRelayLink(this, isInitiator, remoteId)

    if (!pair.paired) return

    this._server._pairing.delete(keyString)
    this._server.stats.pairings.pending--
    this._server.stats.pairings.matched++

    // 1st pass: Create the raw streams needed for each end of the link.
    for (const link of pair.links) {
      link.createStream()
    }

    // 2nd pass: Connect the raw streams and set up handlers.
    for (const link of pair.links) {
      link.remote = pair.remote(link.isInitiator)
      link.activate(keyString)
    }

    // 3rd pass: Let either end of the link know the streams were set up.
    for (const { isInitiator, session, remoteId, stream } of pair.links) {
      session._pair.send({
        isInitiator,
        token,
        id: stream.id,
        seq: 0
      })

      session._endMaybe()

      session.emit('pair', isInitiator, token, stream, remoteId)
    }
  }

  _onunpair({ token }) {
    const keyString = token.toString('hex')

    const pair = this._server._pairing.get(keyString)

    if (pair) {
      for (const link of pair.links) {
        if (link) link.session._pairing.delete(keyString)
      }

      this._server._pairing.delete(keyString)
      this._server.stats.pairings.pending--
      this._server.stats.pairings.cancelled++
      return
    }

    const link = this._links.get(keyString)

    if (link) {
      link.destroyPair(errors.PAIRING_CANCELLED())
      this._server.stats.pairings.cancelled++
    }
  }

  cork() {
    this._channel.cork()
  }

  uncork() {
    this._channel.uncork()
  }

  async end() {
    if (this._ending) return this._ending

    this._ending = EventEmitter.once(this, 'close')
    this._endMaybe()

    return this._ending
  }

  _endMaybe() {
    if (this._ending && this._pairing.size === 0) {
      this._channel.close()
    }
  }

  destroy(err) {
    if (this._destroyed) return
    this._destroyed = true

    this._error = err || errors.CHANNEL_DESTROYED()
    this._channel.close()
  }
}

class BlindRelayPair {
  constructor(token) {
    this.token = token
    this.links = [null, null]
  }

  get paired() {
    return this.links[0] !== null && this.links[1] !== null
  }

  remote(isInitiator) {
    return this.links[isInitiator ? 0 : 1]
  }
}

class BlindRelayLink {
  constructor(session, isInitiator, remoteId) {
    this.session = session
    this.isInitiator = isInitiator
    this.remoteId = remoteId
    this.stream = null
    this.remote = null
    this.keyString = null
    this._onclose = null
  }

  createStream() {
    if (this.stream) return

    this.stream = this.session._server._createStream({
      firewall: this._onfirewall.bind(this)
    })
  }

  activate(keyString) {
    const stream = this.stream

    this.keyString = keyString
    this._onclose = () => {
      if (this.stream !== stream) return

      this.stream = null
      unlink(this)
      this.session._links.delete(keyString)
      this.session._server._untrackActiveLink(keyString)
      this.session._server.stats.streams.closed++
    }

    stream.on('error', this.session._onerror).on('close', this._onclose).relayTo(this.remote.stream)

    this.session._pairing.delete(keyString)
    this.session._links.set(keyString, this)
    this.session._server._trackActiveLink(keyString)
    this.session._server.stats.streams.opened++
  }

  destroy(err) {
    const stream = this.stream

    if (!stream) return

    this.stream = null

    stream.off('close', this._onclose)
    this._onclose = null

    stream.off('error', this.session._onerror)
    unlink(this)
    this.session._links.delete(this.keyString)
    this.session._server._untrackActiveLink(this.keyString)
    this.session._server.stats.streams.closed++
    stream.on('error', noop).destroy(err)
  }

  destroyPair(err) {
    const remote = this.remote

    this.destroy(err)
    if (remote) remote.destroy(err)
  }

  _onfirewall(socket, port, host) {
    this.stream.connect(socket, this.remoteId, port, host)

    return false
  }
}

exports.Client = class BlindRelayClient extends EventEmitter {
  static _clients = new WeakMap()

  static from(stream, opts) {
    let client = this._clients.get(stream)
    if (client) return client
    client = new this(stream, opts)
    this._clients.set(stream, client)
    return client
  }

  constructor(stream, opts = {}) {
    super()

    const { id, handshake, handshakeEncoding } = opts

    this._mux = Protomux.from(stream)

    this._channel = this._mux.createChannel({
      protocol: 'blind-relay',
      id,
      handshake: handshake ? handshakeEncoding || c.raw : null,
      onopen: this._onopen.bind(this),
      onclose: this._onclose.bind(this),
      ondestroy: this._ondestroy.bind(this)
    })

    this._pair = this._channel.addMessage({
      encoding: m.pair,
      onmessage: this._onpair.bind(this)
    })

    this._unpair = this._channel.addMessage({
      encoding: m.unpair
    })

    this._ending = false
    this._destroyed = false
    this._error = null
    this._requests = new Map()

    this._channel.open(handshake)
  }

  get closed() {
    return this._channel.closed
  }

  get mux() {
    return this._mux
  }

  get stream() {
    return this._mux.stream
  }

  get requests() {
    return this._requests.values()
  }

  _onopen() {
    this.emit('open')
  }

  _onclose() {
    this._ending = Promise.resolve()

    const err = this._error || errors.CHANNEL_CLOSED()

    for (const request of this._requests.values()) {
      request.destroy(err)
    }

    this._requests.clear()

    this.constructor._clients.delete(this.stream)

    this.emit('close')
  }

  _ondestroy() {
    this._destroyed = true
    this.emit('destroy')
  }

  _onpair({ isInitiator, token, id: remoteId }) {
    const request = this._requests.get(token.toString('hex'))

    if (request === undefined || request.isInitiator !== isInitiator) return

    request.push(remoteId)
    request.push(null)

    this.emit('pair', request.isInitiator, request.token, request.stream, remoteId)
  }

  pair(isInitiator, token, stream) {
    if (this._destroyed) throw errors.CHANNEL_DESTROYED()

    const keyString = token.toString('hex')

    if (this._requests.has(keyString)) throw errors.ALREADY_PAIRING()

    const request = new BlindRelayRequest(this, isInitiator, token, stream)

    this._requests.set(keyString, request)

    return request
  }

  unpair(token) {
    if (this._destroyed) throw errors.CHANNEL_DESTROYED()

    const request = this._requests.get(token.toString('hex'))

    if (request) request.destroy(errors.PAIRING_CANCELLED())

    this._unpair.send({ token })
  }

  cork() {
    this._channel.cork()
  }

  uncork() {
    this._channel.uncork()
  }

  async end() {
    if (this._ending) return this._ending

    this._ending = EventEmitter.once(this, 'close')
    this._endMaybe()

    return this._ending
  }

  _endMaybe() {
    if (this._ending && this._requests.size === 0) {
      this._channel.close()
    }
  }

  destroy(err) {
    if (this._destroyed) return
    this._destroyed = true

    this._error = err || errors.CHANNEL_DESTROYED()
    this._channel.close()
  }
}

class BlindRelayRequest extends Readable {
  constructor(client, isInitiator, token, stream) {
    super()

    this.client = client
    this.isInitiator = isInitiator
    this.token = token
    this.stream = stream
  }

  _open(cb) {
    if (this.client._destroyed) return cb(errors.CHANNEL_DESTROYED())

    this.client._pair.send({
      isInitiator: this.isInitiator,
      token: this.token,
      id: this.stream.id,
      seq: 0
    })

    cb(null)
  }

  _destroy(cb) {
    this.client._requests.delete(this.token.toString('hex'))

    cb(null)

    this.client._endMaybe()
  }
}

exports.token = function token(buf = b4a.allocUnsafe(32)) {
  sodium.randombytes_buf(buf)
  return buf
}

function noop() {}

function unlink(link) {
  const remote = link.remote

  link.remote = null

  if (remote && remote.remote === link) {
    remote.remote = null
  }
}

function createStats() {
  const stats = {
    sessions: {
      accepted: 0,
      opened: 0,
      closed: 0,
      get active() {
        return this.accepted - this.closed
      }
    },
    pairings: {
      requested: 0,
      matched: 0,
      cancelled: 0,
      pending: 0,
      active: 0
    },
    streams: {
      opened: 0,
      closed: 0,
      errors: 0,
      get active() {
        return this.opened - this.closed
      }
    }
  }

  return stats
}

const m = (exports.messages = {})

const flags = bitfield(7)

m.pair = {
  preencode(state, m) {
    flags.preencode(state)
    c.fixed32.preencode(state, m.token)
    c.uint.preencode(state, m.id)
    c.uint.preencode(state, m.seq)
  },
  encode(state, m) {
    flags.encode(state, bits.of(m.isInitiator))
    c.fixed32.encode(state, m.token)
    c.uint.encode(state, m.id)
    c.uint.encode(state, m.seq)
  },
  decode(state) {
    const [isInitiator] = bits.iterator(flags.decode(state))

    return {
      isInitiator,
      token: c.fixed32.decode(state),
      id: c.uint.decode(state),
      seq: c.uint.decode(state)
    }
  }
}

m.unpair = {
  preencode(state, m) {
    flags.preencode(state)
    c.fixed32.preencode(state, m.token)
  },
  encode(state, m) {
    flags.encode(state, bits.of())
    c.fixed32.encode(state, m.token)
  },
  decode(state) {
    flags.decode(state)

    return {
      token: c.fixed32.decode(state)
    }
  }
}
module.exports = class BlindRelayError extends Error {
  constructor(msg, code, fn = BlindRelayError) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'BlindRelayError'
  }

  static DUPLICATE_CHANNEL(msg = 'Duplicate channel') {
    return new BlindRelayError(msg, 'DUPLICATE_CHANNEL', BlindRelayError.DUPLICATE_CHANNEL)
  }

  static CHANNEL_CLOSED(msg = 'Channel closed') {
    return new BlindRelayError(msg, 'CHANNEL_CLOSED', BlindRelayError.CHANNEL_CLOSED)
  }

  static CHANNEL_DESTROYED(msg = 'Channel destroyed') {
    return new BlindRelayError(msg, 'CHANNEL_DESTROYED', BlindRelayError.CHANNEL_DESTROYED)
  }

  static ALREADY_PAIRING(msg = 'Already pairing') {
    return new BlindRelayError(msg, 'ALREADY_PAIRING', BlindRelayError.ALREADY_PAIRING)
  }

  static PAIRING_CANCELLED(msg = 'Pairing cancelled') {
    return new BlindRelayError(msg, 'PAIRING_CANCELLED', BlindRelayError.PAIRING_CANCELLED)
  }
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "blind-relay",
  "version": "1.6.1",
  "description": "Blind relay for UDX over Protomux channels",
  "main": "index.js",
  "files": [
    "index.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:bare",
    "test:bare": "brittle-bare --coverage test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/blind-relay.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/blind-relay/issues"
  },
  "homepage": "https://github.com/holepunchto/blind-relay#readme",
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "dependencies": {
    "b4a": "^1.6.4",
    "bare-events": "^2.2.0",
    "bits-to-bytes": "^1.3.0",
    "compact-encoding": "^3.0.0",
    "compact-encoding-bitfield": "^1.0.0",
    "protomux": "^3.5.1",
    "sodium-universal": "^5.0.0",
    "streamx": "^2.15.1"
  },
  "devDependencies": {
    "brittle": "^3.2.1",
    "hyperdht": "^6.6.1",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "udx-native": "^1.6.1"
  }
}
// https://ipinfo.io/bogon

const b4a = require('b4a')
const c = require('compact-encoding')

module.exports = exports = function isBogon (ip) {
  return isBogonIP(ensureBuffer(ip))
}

exports.isBogon = exports

exports.isPrivate = function isPrivate (ip) {
  return isPrivateIP(ensureBuffer(ip))
}

exports.isReserved = function isReserved (ip) {
  return isReservedIP(ensureBuffer(ip))
}

function isBogonIP (ip) {
  return isPrivateIP(ip) || isReservedIP(ip)
}

function isPrivateIP (ip) {
  return ip.byteLength === 4 ? isPrivateIPv4(ip) : false // IPv6 has no private IPs
}

function isPrivateIPv4 (ip) {
  return (
    // 10.0.0.0/8  Private-use networks
    (ip[0] === 10) ||
    // 100.64.0.0/10 Carrier-grade NAT
    (ip[0] === 100 && ip[1] >= 64 && ip[1] <= 127) ||
    // 127.0.0.0/8 Loopback + Name collision occurrence (127.0.53.53)
    (ip[0] === 127) ||
    // 169.254.0.0/16  Link local
    (ip[0] === 169 && ip[1] === 254) ||
    // 172.16.0.0/12 Private-use networks
    (ip[0] === 172 && ip[1] >= 16 && ip[1] <= 31) ||
    // 192.168.0.0/16  Private-use networks
    (ip[0] === 192 && ip[1] === 168)
  )
}

function isReservedIP (ip) {
  return ip.byteLength === 4 ? isReservedIPv4(ip) : isReservedIPv6(ip)
}

function isReservedIPv4 (ip) {
  return (
    // 0.0.0.0/8 "This" network
    (ip[0] === 0) ||
    // 192.0.0.0/24  IETF protocol assignments
    (ip[0] === 192 && ip[1] === 0 && ip[2] === 0) ||
    // 192.0.2.0/24  TEST-NET-1
    (ip[0] === 192 && ip[1] === 0 && ip[2] === 2) ||
    // 198.18.0.0/15 Network interconnect device benchmark testing
    (ip[0] === 198 && ip[1] >= 18 && ip[1] <= 19) ||
    // 198.51.100.0/24 TEST-NET-2
    (ip[0] === 198 && ip[1] === 51 && ip[2] === 100) ||
    // 203.0.113.0/24  TEST-NET-3
    (ip[0] === 203 && ip[1] === 0 && ip[2] === 113) ||
    // 224.0.0.0/4 Multicast
    (ip[0] >= 224 && ip[0] <= 239) ||
    // 240.0.0.0/4 Reserved for future use
    (ip[0] >= 240) ||
    // 255.255.255.255/32
    (ip[0] === 255 && ip[1] === 255 && ip[2] === 255 && ip[3] === 255)
  )
}

function isReservedIPv6 (ip) {
  return (
    // ::/128 Node-scope unicast unspecified address
    // ::1/128 Node-scope unicast loopback address
    (
      ip[0] === 0 && ip[1] === 0 && ip[2] === 0 && ip[3] === 0 && ip[4] === 0 &&
      ip[5] === 0 && ip[6] === 0 && ip[7] === 0 && ip[8] === 0 && ip[9] === 0 &&
      ip[10] === 0 && ip[11] === 0 && ip[12] === 0 && ip[13] === 0 && ip[14] === 0 &&
      ip[15] <= 1
    ) ||
    // ::ffff:0:0/96 IPv4-mapped addresses
    // ::/96 IPv4-compatible addresses
    (
      ip[0] === 0 && ip[1] === 0 && ip[2] === 0 && ip[3] === 0 && ip[4] === 0 &&
      ip[5] === 0 && ip[6] === 0 && ip[7] === 0 && ip[8] === 0 && ip[9] === 0 &&
      (ip[10] === 0 || ip[10] === 0xff) &&
      (ip[11] === 0 || ip[11] === 0xff)
    ) ||
    // 100::/64 Remotely triggered black hole addresses
    (ip[0] === 0x01 && ip[1] === 0 && ip[2] === 0 && ip[3] === 0 && ip[4] === 0 && ip[5] === 0 && ip[6] === 0 && ip[7] === 0) ||
    // 2001:10::/28 Overlay routable cryptographic hash identifiers (ORCHID)
    (ip[0] === 0x20 && ip[1] === 0x01 && ip[2] === 0 && ip[3] >= 0x10 && ip[3] <= 0x1f) ||
    // 2001:20::/28 Overlay routable cryptographic hash identifiers version 2 (ORCHIDv2)
    (ip[0] === 0x20 && ip[1] === 0x01 && ip[2] === 0 && ip[3] >= 0x20 && ip[3] <= 0x2f) ||
    // 2001:db8::/32 Documentation prefix
    (ip[0] === 0x20 && ip[1] === 0x01 && ip[2] === 0x0d && ip[3] === 0xb8) ||
    // fc00::/7 Unique local addresses (ULA)
    (ip[0] >= 0xfc && ip[0] <= 0xfd) ||
    // fe80::/10 Link-local unicast
    (ip[0] === 0xfe && ip[1] >= 0x80 && ip[1] <= 0xbf) ||
    // ff00::/8 Multicast
    (ip[0] === 0xff)
  )
}

const state = c.state(0, 0, b4a.allocUnsafe(1 /* family */ + 16))

function ensureBuffer (ip) {
  if (b4a.isBuffer(ip)) return ip

  c.ip.preencode(state, ip)
  c.ip.encode(state, ip)

  const buffer = state.buffer.subarray(1 /* family */, state.end)

  state.start = 0
  state.end = 0

  return buffer
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "bogon",
  "version": "1.3.0",
  "description": "Check if an IP is a bogon",
  "main": "index.js",
  "scripts": {
    "test": "standard && brittle test.mjs"
  },
  "dependencies": {
    "compact-encoding": "^3.0.0",
    "compact-encoding-net": "^1.2.0"
  },
  "devDependencies": {
    "brittle": "^3.0.4",
    "nanobench": "^2.1.1",
    "standard": "^17.0.0"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/bogon.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/bogon/issues"
  },
  "homepage": "https://github.com/mafintosh/bogon"
}
import { encode, encodeInto, objectToTokens, rfc8949EncodeOptions } from './lib/encode.js'
import { decode, decodeFirst, Tokeniser, tokensToObject } from './lib/decode.js'
import { Tagged } from './lib/tagged.js'
import { Token, Type } from './lib/token.js'

/**
 * Export the types that were present in the original manual cborg.d.ts
 * @typedef {import('./interface.js').TagDecodeControl} TagDecodeControl
 * @typedef {import('./interface.js').TagDecoder} TagDecoder
 * There was originally just `TypeEncoder` so don't break types by renaming or not exporting
 * @typedef {import('./interface.js').OptionalTypeEncoder} TypeEncoder
 * @typedef {import('./interface.js').DecodeOptions} DecodeOptions
 * @typedef {import('./interface.js').EncodeOptions} EncodeOptions
 */

export {
  decode,
  decodeFirst,
  Tokeniser as Tokenizer,
  tokensToObject,
  encode,
  encodeInto,
  objectToTokens,
  rfc8949EncodeOptions,
  Tagged,
  Token,
  Type
}
/* globals BigInt */

import { Token, Type } from './token.js'
import { decodeErrPrefix, assertEnoughData } from './common.js'

export const uintBoundaries = [24, 256, 65536, 4294967296, BigInt('18446744073709551616')]

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number}
 */
export function readUint8 (data, offset, options) {
  assertEnoughData(data, offset, 1)
  const value = data[offset]
  if (options.strict === true && value < uintBoundaries[0]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  return value
}

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number}
 */
export function readUint16 (data, offset, options) {
  assertEnoughData(data, offset, 2)
  const value = (data[offset] << 8) | data[offset + 1]
  if (options.strict === true && value < uintBoundaries[1]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  return value
}

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number}
 */
export function readUint32 (data, offset, options) {
  assertEnoughData(data, offset, 4)
  const value = (data[offset] * 16777216 /* 2 ** 24 */) + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]
  if (options.strict === true && value < uintBoundaries[2]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  return value
}

/**
 * @param {Uint8Array} data
 * @param {number} offset
 * @param {DecodeOptions} options
 * @returns {number|bigint}
 */
export function readUint64 (data, offset, options) {
  // assume BigInt, convert back to Number if within safe range
  assertEnoughData(data, offset, 8)
  const hi = (data[offset] * 16777216 /* 2 ** 24 */) + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]
  const lo = (data[offset + 4] * 16777216 /* 2 ** 24 */) + (data[offset + 5] << 16) + (data[offset + 6] << 8) + data[offset + 7]
  const value = (BigInt(hi) << BigInt(32)) + BigInt(lo)
  if (options.strict === true && value < uintBoundaries[3]) {
    throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`)
  }
  if (value <= Number.MAX_SAFE_INTEGER) {
    return Number(value)
  }
  if (options.allowBigInt === true) {
    return value
  }
  throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`)
}

/* not required thanks to quick[] list
const oneByteTokens = new Array(24).fill(0).map((v, i) => new Token(Type.uint, i, 1))
export function decodeUintCompact (data, pos, minor, options) {
  return oneByteTokens[minor]
}
*/

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint8 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint8(data, pos + 1, options), 2)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint16 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint16(data, pos + 1, options), 3)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint32 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint32(data, pos + 1, options), 5)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUint64 (data, pos, _minor, options) {
  return new Token(Type.uint, readUint64(data, pos + 1, options), 9)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeUint (writer, token) {
  return encodeUintValue(writer, 0, token.value)
}

/**
 * @param {ByteWriter} writer
 * @param {number} major
 * @param {number|bigint} uint
 */
export function encodeUintValue (writer, major, uint) {
  if (uint < uintBoundaries[0]) {
    const nuint = Number(uint)
    // pack into one byte, minor=0, additional=value
    writer.push([major | nuint])
  } else if (uint < uintBoundaries[1]) {
    const nuint = Number(uint)
    // pack into two byte, minor=0, additional=24
    writer.push([major | 24, nuint])
  } else if (uint < uintBoundaries[2]) {
    const nuint = Number(uint)
    // pack into three byte, minor=0, additional=25
    writer.push([major | 25, nuint >>> 8, nuint & 0xff])
  } else if (uint < uintBoundaries[3]) {
    const nuint = Number(uint)
    // pack into five byte, minor=0, additional=26
    writer.push([major | 26, (nuint >>> 24) & 0xff, (nuint >>> 16) & 0xff, (nuint >>> 8) & 0xff, nuint & 0xff])
  } else {
    const buint = BigInt(uint)
    if (buint < uintBoundaries[4]) {
      // pack into nine byte, minor=0, additional=27
      const set = [major | 27, 0, 0, 0, 0, 0, 0, 0]
      // simulate bitwise above 32 bits
      let lo = Number(buint & BigInt(0xffffffff))
      let hi = Number(buint >> BigInt(32) & BigInt(0xffffffff))
      set[8] = lo & 0xff
      lo = lo >> 8
      set[7] = lo & 0xff
      lo = lo >> 8
      set[6] = lo & 0xff
      lo = lo >> 8
      set[5] = lo & 0xff
      set[4] = hi & 0xff
      hi = hi >> 8
      set[3] = hi & 0xff
      hi = hi >> 8
      set[2] = hi & 0xff
      hi = hi >> 8
      set[1] = hi & 0xff
      writer.push(set)
    } else {
      throw new Error(`${decodeErrPrefix} encountered BigInt larger than allowable range`)
    }
  }
}

/**
 * @param {Token} token
 * @returns {number}
 */
encodeUint.encodedSize = function encodedSize (token) {
  return encodeUintValue.encodedSize(token.value)
}

/**
 * @param {number} uint
 * @returns {number}
 */
encodeUintValue.encodedSize = function encodedSize (uint) {
  if (uint < uintBoundaries[0]) {
    return 1
  }
  if (uint < uintBoundaries[1]) {
    return 2
  }
  if (uint < uintBoundaries[2]) {
    return 3
  }
  if (uint < uintBoundaries[3]) {
    return 5
  }
  return 9
}

/**
 * @param {Token} tok1
 * @param {Token} tok2
 * @returns {number}
 */
encodeUint.compareTokens = function compareTokens (tok1, tok2) {
  return tok1.value < tok2.value ? -1 : tok1.value > tok2.value ? 1 : 0
}
/* eslint-env es2020 */

import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import { decodeErrPrefix } from './common.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint8 (data, pos, _minor, options) {
  return new Token(Type.negint, -1 - uint.readUint8(data, pos + 1, options), 2)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint16 (data, pos, _minor, options) {
  return new Token(Type.negint, -1 - uint.readUint16(data, pos + 1, options), 3)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint32 (data, pos, _minor, options) {
  return new Token(Type.negint, -1 - uint.readUint32(data, pos + 1, options), 5)
}

const neg1b = BigInt(-1)
const pos1b = BigInt(1)

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeNegint64 (data, pos, _minor, options) {
  const int = uint.readUint64(data, pos + 1, options)
  if (typeof int !== 'bigint') {
    const value = -1 - int
    if (value >= Number.MIN_SAFE_INTEGER) {
      return new Token(Type.negint, value, 9)
    }
  }
  if (options.allowBigInt !== true) {
    throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`)
  }
  return new Token(Type.negint, neg1b - BigInt(int), 9)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeNegint (writer, token) {
  const negint = token.value
  const unsigned = (typeof negint === 'bigint' ? (negint * neg1b - pos1b) : (negint * -1 - 1))
  uint.encodeUintValue(writer, token.type.majorEncoded, unsigned)
}

/**
 * @param {Token} token
 * @returns {number}
 */
encodeNegint.encodedSize = function encodedSize (token) {
  const negint = token.value
  const unsigned = (typeof negint === 'bigint' ? (negint * neg1b - pos1b) : (negint * -1 - 1))
  // handled by quickEncode, we shouldn't get here but it's included for completeness
  if (unsigned < uint.uintBoundaries[0]) {
    return 1
  }
  if (unsigned < uint.uintBoundaries[1]) {
    return 2
  }
  if (unsigned < uint.uintBoundaries[2]) {
    return 3
  }
  if (unsigned < uint.uintBoundaries[3]) {
    return 5
  }
  return 9
}

/**
 * @param {Token} tok1
 * @param {Token} tok2
 * @returns {number}
 */
encodeNegint.compareTokens = function compareTokens (tok1, tok2) {
  // opposite of the uint comparison since we store the uint version in bytes
  return tok1.value < tok2.value ? 1 : tok1.value > tok2.value ? -1 : 0
}
import { Token, Type } from './token.js'
import { assertEnoughData, decodeErrPrefix } from './common.js'
import * as uint from './0uint.js'
import { compare, fromString } from './byte-utils.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} prefix
 * @param {number} length
 * @returns {Token}
 */
function toToken (data, pos, prefix, length) {
  assertEnoughData(data, pos, prefix + length)
  const buf = data.slice(pos + prefix, pos + prefix + length)
  return new Token(Type.bytes, buf, prefix + length)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeBytesCompact (data, pos, minor, _options) {
  return toToken(data, pos, 1, minor)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBytes64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer bytes lengths not supported`)
  }
  return toToken(data, pos, 9, l)
}

/**
 * `encodedBytes` allows for caching when we do a byte version of a string
 * for key sorting purposes
 * @param {Token} token
 * @returns {Uint8Array}
 */
function tokenBytes (token) {
  if (token.encodedBytes === undefined) {
    token.encodedBytes = Type.equals(token.type, Type.string) ? fromString(token.value) : token.value
  }
  // @ts-ignore c'mon
  return token.encodedBytes
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeBytes (writer, token) {
  const bytes = tokenBytes(token)
  uint.encodeUintValue(writer, token.type.majorEncoded, bytes.length)
  writer.push(bytes)
}

/**
 * @param {Token} token
 * @returns {number}
 */
encodeBytes.encodedSize = function encodedSize (token) {
  const bytes = tokenBytes(token)
  return uint.encodeUintValue.encodedSize(bytes.length) + bytes.length
}

/**
 * @param {Token} tok1
 * @param {Token} tok2
 * @returns {number}
 */
encodeBytes.compareTokens = function compareTokens (tok1, tok2) {
  return compareBytes(tokenBytes(tok1), tokenBytes(tok2))
}

/**
 * @param {Uint8Array} b1
 * @param {Uint8Array} b2
 * @returns {number}
 */
export function compareBytes (b1, b2) {
  return b1.length < b2.length ? -1 : b1.length > b2.length ? 1 : compare(b1, b2)
}
import { Token, Type } from './token.js'
import { assertEnoughData, decodeErrPrefix } from './common.js'
import * as uint from './0uint.js'
import { encodeBytes } from './2bytes.js'

const textDecoder = new TextDecoder()

// Threshold for ASCII fast-path vs TextDecoder. Short ASCII strings (common for
// map keys) are faster to decode with a simple loop than TextDecoder overhead.
const ASCII_THRESHOLD = 32

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * Decode UTF-8 bytes to string. For short ASCII strings (common case for map keys),
 * a simple loop is faster than TextDecoder.
 * @param {Uint8Array} bytes
 * @param {number} start
 * @param {number} end
 * @returns {string}
 */
function toStr (bytes, start, end) {
  const len = end - start
  if (len < ASCII_THRESHOLD) {
    let str = ''
    for (let i = start; i < end; i++) {
      const c = bytes[i]
      if (c & 0x80) { // non-ASCII, fall back to TextDecoder
        return textDecoder.decode(bytes.subarray(start, end))
      }
      str += String.fromCharCode(c)
    }
    return str
  }
  return textDecoder.decode(bytes.subarray(start, end))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} prefix
 * @param {number} length
 * @param {DecodeOptions} options
 * @returns {Token}
 */
function toToken (data, pos, prefix, length, options) {
  const totLength = prefix + length
  assertEnoughData(data, pos, totLength)
  const tok = new Token(Type.string, toStr(data, pos + prefix, pos + totLength), totLength)
  if (options.retainStringBytes === true) {
    tok.byteValue = data.slice(pos + prefix, pos + totLength)
  }
  return tok
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeStringCompact (data, pos, minor, options) {
  return toToken(data, pos, 1, minor, options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options), options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options), options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options), options)
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeString64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer string lengths not supported`)
  }
  return toToken(data, pos, 9, l, options)
}

export const encodeString = encodeBytes
import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import { decodeErrPrefix } from './common.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} prefix
 * @param {number} length
 * @returns {Token}
 */
function toToken (_data, _pos, prefix, length) {
  return new Token(Type.array, length, prefix)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeArrayCompact (data, pos, minor, _options) {
  return toToken(data, pos, 1, minor)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArray64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer array lengths not supported`)
  }
  return toToken(data, pos, 9, l)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeArrayIndefinite (data, pos, _minor, options) {
  if (options.allowIndefinite === false) {
    throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)
  }
  return toToken(data, pos, 1, Infinity)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeArray (writer, token) {
  uint.encodeUintValue(writer, Type.array.majorEncoded, token.value)
}

// using an array as a map key, are you sure about this? we can only sort
// by map length here, it's up to the encoder to decide to look deeper
encodeArray.compareTokens = uint.encodeUint.compareTokens

/**
 * @param {Token} token
 * @returns {number}
 */
encodeArray.encodedSize = function encodedSize (token) {
  return uint.encodeUintValue.encodedSize(token.value)
}
import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import { decodeErrPrefix } from './common.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} prefix
 * @param {number} length
 * @returns {Token}
 */
function toToken (_data, _pos, prefix, length) {
  return new Token(Type.map, length, prefix)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeMapCompact (data, pos, minor, _options) {
  return toToken(data, pos, 1, minor)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap8 (data, pos, _minor, options) {
  return toToken(data, pos, 2, uint.readUint8(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap16 (data, pos, _minor, options) {
  return toToken(data, pos, 3, uint.readUint16(data, pos + 1, options))
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap32 (data, pos, _minor, options) {
  return toToken(data, pos, 5, uint.readUint32(data, pos + 1, options))
}

// TODO: maybe we shouldn't support this ..
/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMap64 (data, pos, _minor, options) {
  const l = uint.readUint64(data, pos + 1, options)
  if (typeof l === 'bigint') {
    throw new Error(`${decodeErrPrefix} 64-bit integer map lengths not supported`)
  }
  return toToken(data, pos, 9, l)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeMapIndefinite (data, pos, _minor, options) {
  if (options.allowIndefinite === false) {
    throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)
  }
  return toToken(data, pos, 1, Infinity)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeMap (writer, token) {
  uint.encodeUintValue(writer, Type.map.majorEncoded, token.value)
}

// using a map as a map key, are you sure about this? we can only sort
// by map length here, it's up to the encoder to decide to look deeper
encodeMap.compareTokens = uint.encodeUint.compareTokens

/**
 * @param {Token} token
 * @returns {number}
 */
encodeMap.encodedSize = function encodedSize (token) {
  return uint.encodeUintValue.encodedSize(token.value)
}
import { Token, Type } from './token.js'
import * as uint from './0uint.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 */

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} minor
 * @param {DecodeOptions} _options
 * @returns {Token}
 */
export function decodeTagCompact (_data, _pos, minor, _options) {
  return new Token(Type.tag, minor, 1)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag8 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint8(data, pos + 1, options), 2)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag16 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint16(data, pos + 1, options), 3)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag32 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint32(data, pos + 1, options), 5)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeTag64 (data, pos, _minor, options) {
  return new Token(Type.tag, uint.readUint64(data, pos + 1, options), 9)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 */
export function encodeTag (writer, token) {
  uint.encodeUintValue(writer, Type.tag.majorEncoded, token.value)
}

encodeTag.compareTokens = uint.encodeUint.compareTokens

/**
 * @param {Token} token
 * @returns {number}
 */
encodeTag.encodedSize = function encodedSize (token) {
  return uint.encodeUintValue.encodedSize(token.value)
}
// TODO: shift some of the bytes logic to bytes-utils so we can use Buffer
// where possible

import { Token, Type } from './token.js'
import { decodeErrPrefix } from './common.js'
import { encodeUint } from './0uint.js'

/**
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 * @typedef {import('../interface.js').EncodeOptions} EncodeOptions
 */

export const MINOR_FALSE = 20
export const MINOR_TRUE = 21
export const MINOR_NULL = 22
export const MINOR_UNDEFINED = 23

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeUndefined (_data, _pos, _minor, options) {
  if (options.allowUndefined === false) {
    throw new Error(`${decodeErrPrefix} undefined values are not supported`)
  } else if (options.coerceUndefinedToNull === true) {
    return new Token(Type.null, null, 1)
  }
  return new Token(Type.undefined, undefined, 1)
}

/**
 * @param {Uint8Array} _data
 * @param {number} _pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeBreak (_data, _pos, _minor, options) {
  if (options.allowIndefinite === false) {
    throw new Error(`${decodeErrPrefix} indefinite length items not allowed`)
  }
  return new Token(Type.break, undefined, 1)
}

/**
 * @param {number} value
 * @param {number} bytes
 * @param {DecodeOptions} options
 * @returns {Token}
 */
function createToken (value, bytes, options) {
  if (options) {
    if (options.allowNaN === false && Number.isNaN(value)) {
      throw new Error(`${decodeErrPrefix} NaN values are not supported`)
    }
    if (options.allowInfinity === false && (value === Infinity || value === -Infinity)) {
      throw new Error(`${decodeErrPrefix} Infinity values are not supported`)
    }
  }
  return new Token(Type.float, value, bytes)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeFloat16 (data, pos, _minor, options) {
  return createToken(readFloat16(data, pos + 1), 3, options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeFloat32 (data, pos, _minor, options) {
  return createToken(readFloat32(data, pos + 1), 5, options)
}

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} _minor
 * @param {DecodeOptions} options
 * @returns {Token}
 */
export function decodeFloat64 (data, pos, _minor, options) {
  return createToken(readFloat64(data, pos + 1), 9, options)
}

/**
 * @param {ByteWriter} writer
 * @param {Token} token
 * @param {EncodeOptions} options
 */
export function encodeFloat (writer, token, options) {
  const float = token.value

  if (float === false) {
    writer.push([Type.float.majorEncoded | MINOR_FALSE])
  } else if (float === true) {
    writer.push([Type.float.majorEncoded | MINOR_TRUE])
  } else if (float === null) {
    writer.push([Type.float.majorEncoded | MINOR_NULL])
  } else if (float === undefined) {
    writer.push([Type.float.majorEncoded | MINOR_UNDEFINED])
  } else {
    let decoded
    let success = false
    if (!options || options.float64 !== true) {
      encodeFloat16(float)
      decoded = readFloat16(ui8a, 1)
      if (float === decoded || Number.isNaN(float)) {
        ui8a[0] = 0xf9
        writer.push(ui8a.slice(0, 3))
        success = true
      } else {
        encodeFloat32(float)
        decoded = readFloat32(ui8a, 1)
        if (float === decoded) {
          ui8a[0] = 0xfa
          writer.push(ui8a.slice(0, 5))
          success = true
        }
      }
    }
    if (!success) {
      encodeFloat64(float)
      decoded = readFloat64(ui8a, 1)
      ui8a[0] = 0xfb
      writer.push(ui8a.slice(0, 9))
    }
  }
}

/**
 * @param {Token} token
 * @param {EncodeOptions} options
 * @returns {number}
 */
encodeFloat.encodedSize = function encodedSize (token, options) {
  const float = token.value

  if (float === false || float === true || float === null || float === undefined) {
    return 1
  }

  if (!options || options.float64 !== true) {
    encodeFloat16(float)
    let decoded = readFloat16(ui8a, 1)
    if (float === decoded || Number.isNaN(float)) {
      return 3
    }
    encodeFloat32(float)
    decoded = readFloat32(ui8a, 1)
    if (float === decoded) {
      return 5
    }
  }
  return 9
}

const buffer = new ArrayBuffer(9)
const dataView = new DataView(buffer, 1)
const ui8a = new Uint8Array(buffer, 0)

/**
 * @param {number} inp
 */
function encodeFloat16 (inp) {
  if (inp === Infinity) {
    dataView.setUint16(0, 0x7c00, false)
  } else if (inp === -Infinity) {
    dataView.setUint16(0, 0xfc00, false)
  } else if (Number.isNaN(inp)) {
    dataView.setUint16(0, 0x7e00, false)
  } else {
    dataView.setFloat32(0, inp)
    const valu32 = dataView.getUint32(0)
    const exponent = (valu32 & 0x7f800000) >> 23
    const mantissa = valu32 & 0x7fffff

    if (exponent === 0xff) {
      // too big, Infinity, but this should be hard (impossible?) to trigger
      dataView.setUint16(0, 0x7c00, false)
    } else if (exponent === 0x00) {
      // 0.0, -0.0 and subnormals, shouldn't be possible to get here because 0.0 should be counted as an int
      // Use valu32 for sign bit since bitwise ops on floats lose -0 sign
      dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | (mantissa >> 13), false)
    } else { // standard numbers
      // chunks of logic here borrowed from https://github.com/PJK/libcbor/blob/c78f437182533e3efa8d963ff4b945bb635c2284/src/cbor/encoding.c#L127
      const logicalExponent = exponent - 127
      // Now we know that 2^exponent <= 0 logically
      if (logicalExponent < -24) {
        /* No unambiguous representation exists, this float is not a half float
          and is too small to be represented using a half, round off to zero.
          Consistent with the reference implementation. */
        // should be difficult (impossible?) to get here in JS
        dataView.setUint16(0, 0)
      } else if (logicalExponent < -14) {
        /* Offset the remaining decimal places by shifting the significand, the
          value is lost. This is an implementation decision that works around the
          absence of standard half-float in the language. */
        dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | /* sign bit */ (1 << (24 + logicalExponent)), false)
      } else {
        dataView.setUint16(0, ((valu32 & 0x80000000) >> 16) | ((logicalExponent + 15) << 10) | (mantissa >> 13), false)
      }
    }
  }
}

/**
 * @param {Uint8Array} ui8a
 * @param {number} pos
 * @returns {number}
 */
function readFloat16 (ui8a, pos) {
  if (ui8a.length - pos < 2) {
    throw new Error(`${decodeErrPrefix} not enough data for float16`)
  }

  const half = (ui8a[pos] << 8) + ui8a[pos + 1]
  if (half === 0x7c00) {
    return Infinity
  }
  if (half === 0xfc00) {
    return -Infinity
  }
  if (half === 0x7e00) {
    return NaN
  }
  const exp = (half >> 10) & 0x1f
  const mant = half & 0x3ff
  let val
  if (exp === 0) {
    val = mant * (2 ** -24)
  } else if (exp !== 31) {
    val = (mant + 1024) * (2 ** (exp - 25))
  } else {
    // may not be possible to get here
    val = mant === 0 ? Infinity : NaN
  }
  return (half & 0x8000) ? -val : val
}

/**
 * @param {number} inp
 */
function encodeFloat32 (inp) {
  dataView.setFloat32(0, inp, false)
}

/**
 * @param {Uint8Array} ui8a
 * @param {number} pos
 * @returns {number}
 */
function readFloat32 (ui8a, pos) {
  if (ui8a.length - pos < 4) {
    throw new Error(`${decodeErrPrefix} not enough data for float32`)
  }
  const offset = (ui8a.byteOffset || 0) + pos
  return new DataView(ui8a.buffer, offset, 4).getFloat32(0, false)
}

/**
 * @param {number} inp
 */
function encodeFloat64 (inp) {
  dataView.setFloat64(0, inp, false)
}

/**
 * @param {Uint8Array} ui8a
 * @param {number} pos
 * @returns {number}
 */
function readFloat64 (ui8a, pos) {
  if (ui8a.length - pos < 8) {
    throw new Error(`${decodeErrPrefix} not enough data for float64`)
  }
  const offset = (ui8a.byteOffset || 0) + pos
  return new DataView(ui8a.buffer, offset, 8).getFloat64(0, false)
}

/**
 * @param {Token} _tok1
 * @param {Token} _tok2
 * @returns {number}
 */
encodeFloat.compareTokens = encodeUint.compareTokens
/*
encodeFloat.compareTokens = function compareTokens (_tok1, _tok2) {
  return _tok1
  throw new Error(`${encodeErrPrefix} cannot use floats as map keys`)
}
*/
/**
 * Bl is a list of byte chunks, similar to https://github.com/rvagg/bl but for
 * writing rather than reading.
 * A Bl object accepts set() operations for individual bytes and copyTo() for
 * inserting byte arrays. These write operations don't automatically increment
 * the internal cursor so its "length" won't be changed. Instead, increment()
 * must be called to extend its length to cover the inserted data.
 * The toBytes() call will convert all internal memory to a single Uint8Array of
 * the correct length, truncating any data that is stored but hasn't been
 * included by an increment().
 * get() can retrieve a single byte.
 * All operations (except toBytes()) take an "offset" argument that will perform
 * the write at the offset _from the current cursor_. For most operations this
 * will be `0` to write at the current cursor position but it can be ahead of
 * the current cursor. Negative offsets probably work but are untested.
 */

// TODO: ipjs doesn't support this, only for test files: https://github.com/mikeal/ipjs/blob/master/src/package/testFile.js#L39
import { alloc, concat, slice } from './byte-utils.js'

/**
 * @typedef {import('../interface.js').ByteView} ByteView
 * @typedef {import('../interface.js').AllocatedByteView} AllocatedByteView
 */

// the ts-ignores in this file are almost all for the `Uint8Array|number[]` duality that exists
// for perf reasons. Consider better approaches to this or removing it entirely, it is quite
// risky because of some assumptions about small chunks === number[] and everything else === Uint8Array.

const defaultChunkSize = 256

export class Bl {
  /**
   * @param {number} [chunkSize]
   */
  constructor (chunkSize = defaultChunkSize) {
    this.chunkSize = chunkSize
    /** @type {number} */
    this.cursor = 0
    /** @type {number} */
    this.maxCursor = -1
    /** @type {(ByteView|number[])[]} */
    this.chunks = []
    // keep the first chunk around if we can to save allocations for future encodes
    /** @type {ByteView|number[]|null} */
    this._initReuseChunk = null
  }

  reset () {
    this.cursor = 0
    this.maxCursor = -1
    if (this.chunks.length) {
      this.chunks = []
    }
    if (this._initReuseChunk !== null) {
      this.chunks.push(this._initReuseChunk)
      this.maxCursor = this._initReuseChunk.length - 1
    }
  }

  /**
   * @param {ByteView|number[]} bytes
   */
  push (bytes) {
    let topChunk = this.chunks[this.chunks.length - 1]
    const newMax = this.cursor + bytes.length
    if (newMax <= this.maxCursor + 1) {
      // we have at least one chunk and we can fit these bytes into that chunk
      const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1
      // @ts-ignore
      topChunk.set(bytes, chunkPos)
    } else {
      // can't fit it in
      if (topChunk) {
        // trip the last chunk to `cursor` if we need to
        const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1
        if (chunkPos < topChunk.length) {
          // @ts-ignore
          this.chunks[this.chunks.length - 1] = topChunk.subarray(0, chunkPos)
          this.maxCursor = this.cursor - 1
        }
      }
      if (bytes.length < 64 && bytes.length < this.chunkSize) {
        // make a new chunk and copy the new one into it
        topChunk = alloc(this.chunkSize)
        this.chunks.push(topChunk)
        this.maxCursor += topChunk.length
        if (this._initReuseChunk === null) {
          this._initReuseChunk = topChunk
        }
        // @ts-ignore
        topChunk.set(bytes, 0)
      } else {
        // push the new bytes in as its own chunk
        this.chunks.push(bytes)
        this.maxCursor += bytes.length
      }
    }
    this.cursor += bytes.length
  }

  /**
   * @param {boolean} [reset]
   * @returns {AllocatedByteView}
   */
  toBytes (reset = false) {
    let byts
    if (this.chunks.length === 1) {
      const chunk = this.chunks[0]
      if (reset && this.cursor > chunk.length / 2) {
        // @ts-ignore
        byts = this.cursor === chunk.length ? chunk : chunk.subarray(0, this.cursor)
        this._initReuseChunk = null
        this.chunks = []
      } else {
        // @ts-ignore
        byts = slice(chunk, 0, this.cursor)
      }
    } else {
      // @ts-ignore
      byts = concat(this.chunks, this.cursor)
    }
    if (reset) {
      this.reset()
    }
    return byts
  }
}

/**
 * U8Bl is a buffer list that writes directly to a user-provided Uint8Array.
 * It provides the same interface as Bl but writes to a fixed destination.
 * @template {ArrayBufferLike} T
 */
export class U8Bl {
  /**
   * @param {Uint8Array<T>} dest
   */
  constructor (dest) {
    this.dest = dest
    /** @type {number} */
    this.cursor = 0
    // chunks is for interface compatibility with Bl - encode.js checks chunks.length
    // as a sanity check for pre-calculated sizes. For U8Bl this is always [dest].
    /** @type {Array<Uint8Array<T>>} */
    this.chunks = [dest]
  }

  reset () {
    this.cursor = 0
  }

  /**
   * @param {ByteView|number[]} bytes
   */
  push (bytes) {
    if (this.cursor + bytes.length > this.dest.length) {
      throw new Error('write out of bounds, destination buffer is too small')
    }
    this.dest.set(bytes, this.cursor)
    this.cursor += bytes.length
  }

  /**
   * @param {boolean} [reset]
   * @returns {Uint8Array<T>}
   */
  toBytes (reset = false) {
    const byts = this.dest.subarray(0, this.cursor)
    if (reset) {
      this.reset()
    }
    return byts
  }
}
// Use Uint8Array directly in the browser, use Buffer in Node.js but don't
// speak its name directly to avoid bundlers pulling in the `Buffer` polyfill

// @ts-ignore
export const useBuffer = globalThis.process &&
  // @ts-ignore
  !globalThis.process.browser &&
  // @ts-ignore
  globalThis.Buffer &&
  // @ts-ignore
  typeof globalThis.Buffer.isBuffer === 'function'

const textEncoder = new TextEncoder()

/**
 * @typedef {import('../interface.js').ByteView} ByteView
 * @typedef {import('../interface.js').AllocatedByteView} AllocatedByteView
 */

/**
 * @param {Uint8Array} buf
 * @returns {boolean}
 */
function isBuffer (buf) {
  // @ts-ignore
  return useBuffer && globalThis.Buffer.isBuffer(buf)
}

/**
 * @param {ByteView|number[]} buf
 * @returns {ByteView}
 */
export function asU8A (buf) {
  if (!(buf instanceof Uint8Array)) {
    return Uint8Array.from(buf)
  }
  return isBuffer(buf) ? new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength) : buf
}

// Threshold for manual UTF-8 encoding vs native methods.
// Node.js Buffer.from: crossover ~24 chars
// Browser TextEncoder: crossover ~200 chars
const FROM_STRING_THRESHOLD_BUFFER = 24
const FROM_STRING_THRESHOLD_TEXTENCODER = 200

export const fromString = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {string} string
     */
    (string) => {
      return string.length >= FROM_STRING_THRESHOLD_BUFFER
        ? // eslint-disable-line operator-linebreak
      // @ts-ignore
        globalThis.Buffer.from(string)
        : utf8ToBytes(string)
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {string} string
     */
    (string) => {
      return string.length >= FROM_STRING_THRESHOLD_TEXTENCODER ? textEncoder.encode(string) : utf8ToBytes(string)
    }

/**
 * Buffer variant not fast enough for what we need
 * @param {number[]} arr
 * @returns {AllocatedByteView}
 */
export const fromArray = (arr) => {
  return Uint8Array.from(arr)
}

export const slice = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} bytes
     * @param {number} start
     * @param {number} end
     */
    // Buffer.slice() returns a view, not a copy, so we need special handling
    (bytes, start, end) => {
      if (isBuffer(bytes)) {
        return new Uint8Array(bytes.subarray(start, end))
      }
      return bytes.slice(start, end)
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} bytes
     * @param {number} start
     * @param {number} end
     */
    (bytes, start, end) => {
      return bytes.slice(start, end)
    }

export const concat = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {ByteView[]} chunks
     * @param {number} length
     * @returns {AllocatedByteView}
     */
    (chunks, length) => {
      // might get a stray plain Array here
      chunks = chunks.map((c) => c instanceof Uint8Array
        ? c
        : // eslint-disable-line operator-linebreak
        // @ts-ignore
        globalThis.Buffer.from(c))
      // @ts-ignore
      return /** @type {AllocatedByteView} */ (asU8A(globalThis.Buffer.concat(chunks, length)))
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {ByteView[]} chunks
     * @param {number} length
     * @returns {AllocatedByteView}
     */
    (chunks, length) => {
      const out = new Uint8Array(length)
      let off = 0
      for (let b of chunks) {
        if (off + b.length > out.length) {
          // final chunk that's bigger than we need
          b = b.subarray(0, out.length - off)
        }
        out.set(b, off)
        off += b.length
      }
      return out
    }

export const alloc = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {number} size
     * @returns {AllocatedByteView}
     */
    (size) => {
      // we always write over the contents we expose so this should be safe
      // @ts-ignore
      return globalThis.Buffer.allocUnsafe(size)
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {number} size
     * @returns {AllocatedByteView}
     */
    (size) => {
      return new Uint8Array(size)
    }

export const toHex = useBuffer
  ? // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} d
     * @returns {string}
     */
    (d) => {
      if (typeof d === 'string') {
        return d
      }
      // @ts-ignore
      return globalThis.Buffer.from(toBytes(d)).toString('hex')
    }
  : // eslint-disable-line operator-linebreak
    /**
     * @param {Uint8Array} d
     * @returns {string}
     */
    (d) => {
      if (typeof d === 'string') {
        return d
      }
      // @ts-ignore not smart enough to figure this out
      return Array.prototype.reduce.call(toBytes(d), (p, c) => `${p}${c.toString(16).padStart(2, '0')}`, '')
    }

export const fromHex = useBuffer
  ? // eslint-disable-line operator-linebreak
  /**
   * @param {string|ByteView} hex
   * @returns {ByteView}
   */
    (hex) => {
      if (hex instanceof Uint8Array) {
        return hex
      }
      // @ts-ignore
      return globalThis.Buffer.from(hex, 'hex')
    }
  : // eslint-disable-line operator-linebreak
  /**
   * @param {string|ByteView} hex
   * @returns {ByteView}
   */
    (hex) => {
      if (hex instanceof Uint8Array) {
        return hex
      }
      if (!hex.length) {
        return new Uint8Array(0)
      }
      return new Uint8Array(hex.split('')
        .map((/** @type {string} */ c, /** @type {number} */ i, /** @type {string[]} */ d) => i % 2 === 0 ? `0x${c}${d[i + 1]}` : '')
        .filter(Boolean)
        .map((/** @type {string} */ e) => parseInt(e, 16)))
    }

/**
 * @param {Uint8Array|ArrayBuffer|ArrayBufferView} obj
 * @returns {Uint8Array}
 */
function toBytes (obj) {
  if (obj instanceof Uint8Array && obj.constructor.name === 'Uint8Array') {
    return obj
  }
  if (obj instanceof ArrayBuffer) {
    return new Uint8Array(obj)
  }
  if (ArrayBuffer.isView(obj)) {
    return new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength)
  }
  throw new Error('Unknown type, must be binary type')
}

/**
 * @param {Uint8Array} b1
 * @param {Uint8Array} b2
 * @returns {number}
 */
export function compare (b1, b2) {
  if (isBuffer(b1) && isBuffer(b2)) {
    // probably not possible to get here in the current API
    // @ts-ignore Buffer
    return b1.compare(b2)
  }
  for (let i = 0; i < b1.length; i++) {
    if (b1[i] === b2[i]) {
      continue
    }
    return b1[i] < b2[i] ? -1 : 1
  }
  return 0
}

// The below code is taken from https://github.com/google/closure-library/blob/8598d87242af59aac233270742c8984e2b2bdbe0/closure/goog/crypt/crypt.js#L117-L143
// Licensed Apache-2.0.

/**
 * @param {string} str
 * @returns {number[]}
 */
function utf8ToBytes (str) {
  const out = []
  let p = 0
  for (let i = 0; i < str.length; i++) {
    let c = str.charCodeAt(i)
    if (c < 128) {
      out[p++] = c
    } else if (c < 2048) {
      out[p++] = (c >> 6) | 192
      out[p++] = (c & 63) | 128
    } else if (
      ((c & 0xFC00) === 0xD800) && (i + 1) < str.length &&
      ((str.charCodeAt(i + 1) & 0xFC00) === 0xDC00)) {
      // Surrogate Pair
      c = 0x10000 + ((c & 0x03FF) << 10) + (str.charCodeAt(++i) & 0x03FF)
      out[p++] = (c >> 18) | 240
      out[p++] = ((c >> 12) & 63) | 128
      out[p++] = ((c >> 6) & 63) | 128
      out[p++] = (c & 63) | 128
    } else {
      if ((c >= 0xD800) && (c <= 0xDFFF)) {
        c = 0xFFFD // Unpaired Surrogate
      }
      out[p++] = (c >> 12) | 224
      out[p++] = ((c >> 6) & 63) | 128
      out[p++] = (c & 63) | 128
    }
  }
  return out
}

// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
const MAX_ARGUMENTS_LENGTH = 0x1000

/**
 * @param {number[]} codePoints
 * @returns {string}
 */
export function decodeCodePointsArray (codePoints) {
  const len = codePoints.length
  if (len <= MAX_ARGUMENTS_LENGTH) {
    return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  }
  // Decode in chunks to avoid "call stack size exceeded".
  let res = ''
  let i = 0
  while (i < len) {
    res += String.fromCharCode.apply(
      String,
      codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
    )
  }
  return res
}
const decodeErrPrefix = 'CBOR decode error:'
const encodeErrPrefix = 'CBOR encode error:'

const uintMinorPrefixBytes = []
uintMinorPrefixBytes[23] = 1
uintMinorPrefixBytes[24] = 2
uintMinorPrefixBytes[25] = 3
uintMinorPrefixBytes[26] = 5
uintMinorPrefixBytes[27] = 9

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} need
 */
function assertEnoughData (data, pos, need) {
  if (data.length - pos < need) {
    throw new Error(`${decodeErrPrefix} not enough data for type`)
  }
}

export {
  decodeErrPrefix,
  encodeErrPrefix,
  uintMinorPrefixBytes,
  assertEnoughData
}
import { decodeErrPrefix } from './common.js'
import { Type } from './token.js'
import { jump, quick } from './jump.js'
import { asU8A } from './byte-utils.js'

/**
 * @typedef {import('./token.js').Token} Token
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 * @typedef {import('../interface.js').DecodeTokenizer} DecodeTokenizer
 * @typedef {import('../interface.js').TagDecodeControl} TagDecodeControl
 */

const defaultDecodeOptions = {
  strict: false,
  allowIndefinite: true,
  allowUndefined: true,
  allowBigInt: true
}

/**
 * @implements {DecodeTokenizer}
 */
class Tokeniser {
  /**
   * @param {Uint8Array} data
   * @param {DecodeOptions} options
   */
  constructor (data, options = {}) {
    this._pos = 0
    this.data = data
    this.options = options
  }

  pos () {
    return this._pos
  }

  done () {
    return this._pos >= this.data.length
  }

  next () {
    const byt = this.data[this._pos]
    let token = quick[byt]
    if (token === undefined) {
      const decoder = jump[byt]
      // if we're here then there's something wrong with our jump or quick lists!
      if (!decoder) {
        throw new Error(`${decodeErrPrefix} no decoder for major type ${byt >>> 5} (byte 0x${byt.toString(16).padStart(2, '0')})`)
      }
      const minor = byt & 31
      token = decoder(this.data, this._pos, minor, this.options)
    }
    // @ts-ignore we get to assume encodedLength is set (crossing fingers slightly)
    this._pos += token.encodedLength
    return token
  }
}

const DONE = Symbol.for('DONE')
const BREAK = Symbol.for('BREAK')

/**
 * @param {Token} token
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {any|BREAK|DONE}
 */
function tokenToArray (token, tokeniser, options) {
  const arr = []
  for (let i = 0; i < token.value; i++) {
    const value = tokensToObject(tokeniser, options)
    if (value === BREAK) {
      if (token.value === Infinity) {
        // normal end to indefinite length array
        break
      }
      throw new Error(`${decodeErrPrefix} got unexpected break to lengthed array`)
    }
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} found array but not enough entries (got ${i}, expected ${token.value})`)
    }
    arr[i] = value
  }
  return arr
}

/**
 * @param {Token} token
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {any|BREAK|DONE}
 */
function tokenToMap (token, tokeniser, options) {
  const useMaps = options.useMaps === true
  const rejectDuplicateMapKeys = options.rejectDuplicateMapKeys === true
  const obj = useMaps ? undefined : {}
  const m = useMaps ? new Map() : undefined
  for (let i = 0; i < token.value; i++) {
    const key = tokensToObject(tokeniser, options)
    if (key === BREAK) {
      if (token.value === Infinity) {
        // normal end to indefinite length map
        break
      }
      throw new Error(`${decodeErrPrefix} got unexpected break to lengthed map`)
    }
    if (key === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no key], expected ${token.value})`)
    }
    if (!useMaps && typeof key !== 'string') {
      throw new Error(`${decodeErrPrefix} non-string keys not supported (got ${typeof key})`)
    }
    if (rejectDuplicateMapKeys) {
      // @ts-ignore
      if ((useMaps && m.has(key)) || (!useMaps && Object.hasOwn(obj, key))) {
        throw new Error(`${decodeErrPrefix} found repeat map key "${key}"`)
      }
    }
    const value = tokensToObject(tokeniser, options)
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no value], expected ${token.value})`)
    }
    if (useMaps) {
      // @ts-ignore TODO reconsider this .. maybe needs to be strict about key types
      m.set(key, value)
    } else {
      // @ts-ignore TODO reconsider this .. maybe needs to be strict about key types
      obj[key] = value
    }
  }
  // @ts-ignore c'mon man
  return useMaps ? m : obj
}

/**
 * Generator that yields [key, value] entries from a CBOR map token.
 * Used by tag decoders that need to preserve key types (e.g., Tag 259 Map).
 * @param {Token} token - The map token
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {Generator<[any, any], void, unknown>}
 */
function * tokenToMapEntries (token, tokeniser, options) {
  for (let i = 0; i < token.value; i++) {
    const key = tokensToObject(tokeniser, options)
    if (key === BREAK) {
      if (token.value === Infinity) {
        // normal end to indefinite length map
        break
      }
      throw new Error(`${decodeErrPrefix} got unexpected break to lengthed map`)
    }
    if (key === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no key], expected ${token.value})`)
    }
    const value = tokensToObject(tokeniser, options)
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no value], expected ${token.value})`)
    }
    yield [key, value]
  }
}

/**
 * Creates a TagDecodeControl object for tag decoders.
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {TagDecodeControl}
 */
function createTagDecodeControl (tokeniser, options) {
  let called = false

  /**
   * @type {TagDecodeControl}
   */
  const decode = function () {
    if (called) {
      throw new Error(`${decodeErrPrefix} tag decode() may only be called once`)
    }
    called = true
    const value = tokensToObject(tokeniser, options)
    if (value === DONE) {
      throw new Error(`${decodeErrPrefix} tag content missing`)
    }
    if (value === BREAK) {
      throw new Error(`${decodeErrPrefix} got unexpected break in tag content`)
    }
    return value
  }

  decode.entries = function () {
    if (called) {
      throw new Error(`${decodeErrPrefix} tag decode() may only be called once`)
    }
    called = true

    // Get the next token and ensure it's a map
    const token = tokeniser.next()
    if (!Type.equals(token.type, Type.map)) {
      throw new Error(`${decodeErrPrefix} entries() requires map content, got ${token.type.name}`)
    }

    // Collect all entries into an array (ensures full content consumption)
    const entries = []
    for (const entry of tokenToMapEntries(token, tokeniser, options)) {
      entries.push(entry)
    }
    return entries
  }

  // For internal tracking
  Object.defineProperty(decode, '_called', {
    get () { return called },
    enumerable: false
  })

  return decode
}

/**
 * @param {DecodeTokenizer} tokeniser
 * @param {DecodeOptions} options
 * @returns {any|BREAK|DONE}
 */
function tokensToObject (tokeniser, options) {
  // should we support array as an argument?
  // check for tokenIter[Symbol.iterator] and replace tokenIter with what that returns?
  if (tokeniser.done()) {
    return DONE
  }

  const token = tokeniser.next()

  if (Type.equals(token.type, Type.break)) {
    return BREAK
  }

  if (token.type.terminal) {
    return token.value
  }

  if (Type.equals(token.type, Type.array)) {
    return tokenToArray(token, tokeniser, options)
  }

  if (Type.equals(token.type, Type.map)) {
    return tokenToMap(token, tokeniser, options)
  }

  if (Type.equals(token.type, Type.tag)) {
    if (options.tags && typeof options.tags[token.value] === 'function') {
      const decodeControl = createTagDecodeControl(tokeniser, options)
      const result = options.tags[token.value](decodeControl)
      if (!decodeControl._called) {
        throw new Error(`${decodeErrPrefix} tag decoder must call decode() or entries()`)
      }
      return result
    }
    throw new Error(`${decodeErrPrefix} tag not supported (${token.value})`)
  }
  throw new Error('unsupported')
}

/**
 * @param {Uint8Array} data
 * @param {DecodeOptions} [options]
 * @returns {[any, Uint8Array]}
 */
function decodeFirst (data, options) {
  if (!(data instanceof Uint8Array)) {
    throw new Error(`${decodeErrPrefix} data to decode must be a Uint8Array`)
  }
  options = Object.assign({}, defaultDecodeOptions, options)
  // Convert Buffer to plain Uint8Array for faster slicing in decode path
  const u8aData = asU8A(data)
  const tokeniser = options.tokenizer || new Tokeniser(u8aData, options)
  const decoded = tokensToObject(tokeniser, options)
  if (decoded === DONE) {
    throw new Error(`${decodeErrPrefix} did not find any content to decode`)
  }
  if (decoded === BREAK) {
    throw new Error(`${decodeErrPrefix} got unexpected break`)
  }
  return [decoded, data.subarray(tokeniser.pos())]
}

/**
 * @param {Uint8Array} data
 * @param {DecodeOptions} [options]
 * @returns {any}
 */
function decode (data, options) {
  const [decoded, remainder] = decodeFirst(data, options)
  if (remainder.length > 0) {
    throw new Error(`${decodeErrPrefix} too many terminals, data makes no sense`)
  }
  return decoded
}

export { Tokeniser, tokensToObject, decode, decodeFirst }
import { is } from './is.js'
import { Token, Type } from './token.js'
import { Bl, U8Bl } from './bl.js'
import { encodeErrPrefix } from './common.js'
import { quickEncodeToken } from './jump.js'
import { asU8A, compare, fromString } from './byte-utils.js'

import { encodeUint, encodeUintValue } from './0uint.js'
import { encodeNegint } from './1negint.js'
import { encodeBytes } from './2bytes.js'
import { encodeString } from './3string.js'
import { encodeArray } from './4array.js'
import { encodeMap } from './5map.js'
import { encodeTag } from './6tag.js'
import { encodeFloat, MINOR_FALSE, MINOR_TRUE, MINOR_NULL, MINOR_UNDEFINED } from './7float.js'

/**
 * @typedef {import('../interface.js').EncodeOptions} EncodeOptions
 * @typedef {import('../interface.js').OptionalTypeEncoder} OptionalTypeEncoder
 * @typedef {import('../interface.js').Reference} Reference
 * @typedef {import('../interface.js').StrictTypeEncoder} StrictTypeEncoder
 * @typedef {import('../interface.js').TokenTypeEncoder} TokenTypeEncoder
 * @typedef {import('../interface.js').TokenOrNestedTokens} TokenOrNestedTokens
 * @typedef {import('../interface.js').ByteWriter} ByteWriter
 * @typedef {import('../interface.js').ByteView} ByteView
 * @typedef {import('../interface.js').AllocatedByteView} AllocatedByteView
 */

/** @type {EncodeOptions} */
const defaultEncodeOptions = {
  float64: false,
  mapSorter,
  quickEncodeToken
}

/** @type {EncodeOptions} */
export const rfc8949EncodeOptions = Object.freeze({
  mapSorter: rfc8949MapSorter,
  quickEncodeToken
})

/** @returns {TokenTypeEncoder[]} */
export function makeCborEncoders () {
  const encoders = []
  encoders[Type.uint.major] = encodeUint
  encoders[Type.negint.major] = encodeNegint
  encoders[Type.bytes.major] = encodeBytes
  encoders[Type.string.major] = encodeString
  encoders[Type.array.major] = encodeArray
  encoders[Type.map.major] = encodeMap
  encoders[Type.tag.major] = encodeTag
  encoders[Type.float.major] = encodeFloat
  return encoders
}

const cborEncoders = makeCborEncoders()

const defaultWriter = new Bl()

/** @implements {Reference} */
class Ref {
  /**
   * @param {object|any[]} obj
   * @param {Reference|undefined} parent
   */
  constructor (obj, parent) {
    this.obj = obj
    this.parent = parent
  }

  /**
   * @param {object|any[]} obj
   * @returns {boolean}
   */
  includes (obj) {
    /** @type {Reference|undefined} */
    let p = this
    do {
      if (p.obj === obj) {
        return true
      }
    } while (p = p.parent) // eslint-disable-line
    return false
  }

  /**
   * @param {Reference|undefined} stack
   * @param {object|any[]} obj
   * @returns {Reference}
   */
  static createCheck (stack, obj) {
    if (stack && stack.includes(obj)) {
      throw new Error(`${encodeErrPrefix} object contains circular references`)
    }
    return new Ref(obj, stack)
  }
}

const simpleTokens = {
  null: new Token(Type.null, null),
  undefined: new Token(Type.undefined, undefined),
  true: new Token(Type.true, true),
  false: new Token(Type.false, false),
  emptyArray: new Token(Type.array, 0),
  emptyMap: new Token(Type.map, 0)
}

/** @type {{[typeName: string]: StrictTypeEncoder}} */
const typeEncoders = {
  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  number (obj, _typ, _options, _refStack) {
    if (!Number.isInteger(obj) || !Number.isSafeInteger(obj)) {
      return new Token(Type.float, obj)
    } else if (obj >= 0) {
      return new Token(Type.uint, obj)
    } else {
      return new Token(Type.negint, obj)
    }
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  bigint (obj, _typ, _options, _refStack) {
    if (obj >= BigInt(0)) {
      return new Token(Type.uint, obj)
    } else {
      return new Token(Type.negint, obj)
    }
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  Uint8Array (obj, _typ, _options, _refStack) {
    return new Token(Type.bytes, obj)
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  string (obj, _typ, _options, _refStack) {
    return new Token(Type.string, obj)
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  boolean (obj, _typ, _options, _refStack) {
    return obj ? simpleTokens.true : simpleTokens.false
  },

  /**
   * @param {any} _obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  null (_obj, _typ, _options, _refStack) {
    return simpleTokens.null
  },

  /**
   * @param {any} _obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  undefined (_obj, _typ, _options, _refStack) {
    return simpleTokens.undefined
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  ArrayBuffer (obj, _typ, _options, _refStack) {
    return new Token(Type.bytes, new Uint8Array(obj))
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} _options
   * @param {Reference} [_refStack]
   * @returns {TokenOrNestedTokens}
   */
  DataView (obj, _typ, _options, _refStack) {
    return new Token(Type.bytes, new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength))
  },

  /**
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} options
   * @param {Reference} [refStack]
   * @returns {TokenOrNestedTokens}
   */
  Array (obj, _typ, options, refStack) {
    if (!obj.length) {
      if (options.addBreakTokens === true) {
        return [simpleTokens.emptyArray, new Token(Type.break)]
      }
      return simpleTokens.emptyArray
    }
    refStack = Ref.createCheck(refStack, obj)
    const entries = []
    let i = 0
    for (const e of obj) {
      entries[i++] = objectToTokens(e, options, refStack)
    }
    if (options.addBreakTokens) {
      return [new Token(Type.array, obj.length), entries, new Token(Type.break)]
    }
    return [new Token(Type.array, obj.length), entries]
  },

  /**
   * @param {any} obj
   * @param {string} typ
   * @param {EncodeOptions} options
   * @param {Reference} [refStack]
   * @returns {TokenOrNestedTokens}
   */
  Object (obj, typ, options, refStack) {
    // could be an Object or a Map
    const isMap = typ !== 'Object'
    // it's slightly quicker to use Object.keys() than Object.entries()
    const keys = isMap ? obj.keys() : Object.keys(obj)
    const maxLength = isMap ? obj.size : keys.length

    /** @type {undefined | [TokenOrNestedTokens, TokenOrNestedTokens][]} */
    let entries

    if (maxLength) {
      // Pre-allocate the array with the expected size
      entries = new Array(maxLength)
      refStack = Ref.createCheck(refStack, obj)
      const skipUndefined = !isMap && options.ignoreUndefinedProperties

      let i = 0
      for (const key of keys) {
        const value = isMap ? obj.get(key) : obj[key]
        if (skipUndefined && value === undefined) {
          continue
        }
        entries[i++] = [
          objectToTokens(key, options, refStack),
          objectToTokens(value, options, refStack)
        ]
      }

      // Truncate only if properties were skipped
      if (i < maxLength) {
        entries.length = i
      }
    }

    if (!entries?.length) {
      if (options.addBreakTokens === true) {
        return [simpleTokens.emptyMap, new Token(Type.break)]
      }
      return simpleTokens.emptyMap
    }

    sortMapEntries(entries, options)
    if (options.addBreakTokens) {
      return [new Token(Type.map, entries.length), entries, new Token(Type.break)]
    }
    return [new Token(Type.map, entries.length), entries]
  },

  /**
   * Encode a `Tagged` wrapper as a CBOR tag header followed by the encoded
   * form of the wrapped value. The value is recursively tokenised through
   * `objectToTokens()` so any registered `typeEncoders` apply to it.
   *
   * @param {any} obj
   * @param {string} _typ
   * @param {EncodeOptions} options
   * @param {Reference} [refStack]
   * @returns {TokenOrNestedTokens}
   */
  Tagged (obj, _typ, options, refStack) {
    return [
      new Token(Type.tag, obj.tag),
      objectToTokens(obj.value, options, refStack)
    ]
  }
}

typeEncoders.Map = typeEncoders.Object
typeEncoders.Buffer = typeEncoders.Uint8Array
for (const typ of 'Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64'.split(' ')) {
  typeEncoders[`${typ}Array`] = typeEncoders.DataView
}

/**
 * @param {any} obj
 * @param {EncodeOptions} [options]
 * @param {Reference} [refStack]
 * @returns {TokenOrNestedTokens}
 */
function objectToTokens (obj, options = {}, refStack) {
  const typ = is(obj)
  const customTypeEncoder = (options && options.typeEncoders && /** @type {OptionalTypeEncoder} */ options.typeEncoders[typ]) || typeEncoders[typ]
  if (typeof customTypeEncoder === 'function') {
    const tokens = customTypeEncoder(obj, typ, options, refStack)
    if (tokens != null) {
      return tokens
    }
  }
  const typeEncoder = typeEncoders[typ]
  if (!typeEncoder) {
    throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`)
  }
  return typeEncoder(obj, typ, options, refStack)
}

/*
CBOR key sorting is a mess.

The canonicalisation recommendation from https://tools.ietf.org/html/rfc7049#section-3.9
includes the wording:

> The keys in every map must be sorted lowest value to highest.
> Sorting is performed on the bytes of the representation of the key
> data items without paying attention to the 3/5 bit splitting for
> major types.
> ...
>  *  If two keys have different lengths, the shorter one sorts
      earlier;
>  *  If two keys have the same length, the one with the lower value
      in (byte-wise) lexical order sorts earlier.

1. It is not clear what "bytes of the representation of the key" means: is it
   the CBOR representation, or the binary representation of the object itself?
   Consider the int and uint difference here.
2. It is not clear what "without paying attention to" means: do we include it
   and compare on that? Or do we omit the special prefix byte, (mostly) treating
   the key in its plain binary representation form.

The FIDO 2.0: Client To Authenticator Protocol spec takes the original CBOR
wording and clarifies it according to their understanding.
https://fidoalliance.org/specs/fido-v2.0-rd-20170927/fido-client-to-authenticator-protocol-v2.0-rd-20170927.html#message-encoding

> The keys in every map must be sorted lowest value to highest. Sorting is
> performed on the bytes of the representation of the key data items without
> paying attention to the 3/5 bit splitting for major types. The sorting rules
> are:
>  * If the major types are different, the one with the lower value in numerical
>    order sorts earlier.
>  * If two keys have different lengths, the shorter one sorts earlier;
>  * If two keys have the same length, the one with the lower value in
>    (byte-wise) lexical order sorts earlier.

Some other implementations, such as borc, do a full encode then do a
length-first, byte-wise-second comparison:
https://github.com/dignifiedquire/borc/blob/b6bae8b0bcde7c3976b0f0f0957208095c392a36/src/encoder.js#L358
https://github.com/dignifiedquire/borc/blob/b6bae8b0bcde7c3976b0f0f0957208095c392a36/src/utils.js#L143-L151

This has the benefit of being able to easily handle arbitrary keys, including
complex types (maps and arrays).

We'll opt for the FIDO approach, since it affords some efficies since we don't
need a full encode of each key to determine order and can defer to the types
to determine how to most efficiently order their values (i.e. int and uint
ordering can be done on the numbers, no need for byte-wise, for example).

Recommendation: stick to single key types or you'll get into trouble, and prefer
string keys because it's much simpler that way.
*/

/**
 * @param {TokenOrNestedTokens[]} entries
 * @param {EncodeOptions} options
 */
function sortMapEntries (entries, options) {
  if (options.mapSorter) {
    entries.sort(options.mapSorter)
  }
}

/**
 * @param {(Token|Token[])[]} e1
 * @param {(Token|Token[])[]} e2
 * @returns {number}
 */
function mapSorter (e1, e2) {
  // the key position ([0]) could have a single token or an array
  // almost always it'll be a single token but complex key might get involved
  const keyToken1 = Array.isArray(e1[0]) ? e1[0][0] : e1[0]
  const keyToken2 = Array.isArray(e2[0]) ? e2[0][0] : e2[0]

  // different key types
  if (keyToken1.type !== keyToken2.type) {
    return keyToken1.type.compare(keyToken2.type)
  }

  const major = keyToken1.type.major
  // TODO: handle case where cmp === 0 but there are more keyToken e. complex type)
  const tcmp = cborEncoders[major].compareTokens(keyToken1, keyToken2)
  if (tcmp === 0) {
    // duplicate key or complex type where the first token matched,
    // i.e. a map or array and we're only comparing the opening token
    console.warn('WARNING: complex key types used, CBOR key sorting guarantees are gone')
  }
  return tcmp
}

/**
 * @typedef {Token & { _keyBytes?: AllocatedByteView }} TokenEx
 *
 * @param {(Token|Token[])[]} e1
 * @param {(Token|Token[])[]} e2
 * @returns {number}
 */
function rfc8949MapSorter (e1, e2) {
  if (e1[0] instanceof Token && e2[0] instanceof Token) {
    const t1 = /** @type {TokenEx} */ (e1[0])
    const t2 = /** @type {TokenEx} */ (e2[0])

    if (!t1._keyBytes) {
      t1._keyBytes = encodeRfc8949(t1.value)
    }

    if (!t2._keyBytes) {
      t2._keyBytes = encodeRfc8949(t2.value)
    }

    return compare(t1._keyBytes, t2._keyBytes)
  }

  throw new Error('rfc8949MapSorter: complex key types are not supported yet')
}

/**
 * @param {any} data
 * @returns {AllocatedByteView}
 */
function encodeRfc8949 (data) {
  return encodeCustom(data, cborEncoders, rfc8949EncodeOptions)
}

/**
 * @param {ByteWriter} writer
 * @param {TokenOrNestedTokens} tokens
 * @param {TokenTypeEncoder[]} encoders
 * @param {EncodeOptions} options
 */
function tokensToEncoded (writer, tokens, encoders, options) {
  if (Array.isArray(tokens)) {
    for (const token of tokens) {
      tokensToEncoded(writer, token, encoders, options)
    }
  } else {
    encoders[tokens.type.major](writer, tokens, options)
  }
}

// CBOR major type prefixes, cached from Type for hot path performance
const MAJOR_UINT = Type.uint.majorEncoded
const MAJOR_NEGINT = Type.negint.majorEncoded
const MAJOR_BYTES = Type.bytes.majorEncoded
const MAJOR_STRING = Type.string.majorEncoded
const MAJOR_ARRAY = Type.array.majorEncoded

// Simple value bytes (CBOR major type 7 + minor value)
const SIMPLE_FALSE = Type.float.majorEncoded | MINOR_FALSE
const SIMPLE_TRUE = Type.float.majorEncoded | MINOR_TRUE
const SIMPLE_NULL = Type.float.majorEncoded | MINOR_NULL
const SIMPLE_UNDEFINED = Type.float.majorEncoded | MINOR_UNDEFINED

const neg1b = BigInt(-1)
const pos1b = BigInt(1)

/**
 * Check if direct encoding can be used for the given options.
 * Direct encoding bypasses token creation for most values.
 * @param {EncodeOptions} options
 * @returns {boolean}
 */
function canDirectEncode (options) {
  // Cannot use direct encode with addBreakTokens (needs special break token handling).
  // Direct encode checks typeEncoders per-value, falling back to tokens as needed.
  // Maps fall back to token-based encoding for efficient key sorting.
  return options.addBreakTokens !== true
}

/**
 * Direct encode a value to the writer, bypassing token creation for most types.
 * Falls back to token-based encoding for custom type encoders.
 * @param {ByteWriter} writer
 * @param {any} data
 * @param {EncodeOptions} options
 * @param {Reference|undefined} refStack
 */
function directEncode (writer, data, options, refStack) {
  const typ = is(data)

  // Check for custom encoder for THIS specific type
  const customEncoder = options.typeEncoders && options.typeEncoders[typ]
  if (customEncoder) {
    const tokens = customEncoder(data, typ, options, refStack)
    if (tokens != null) {
      // Custom encoder returned tokens, serialize immediately
      tokensToEncoded(writer, tokens, cborEncoders, options)
      return
    }
    // Custom encoder returned null, fall through to default handling
  }

  // Direct encode based on type
  switch (typ) {
    case 'null':
      writer.push([SIMPLE_NULL])
      return

    case 'undefined':
      writer.push([SIMPLE_UNDEFINED])
      return

    case 'boolean':
      writer.push([data ? SIMPLE_TRUE : SIMPLE_FALSE])
      return

    case 'number':
      if (!Number.isInteger(data) || !Number.isSafeInteger(data)) {
        // Float, use token encoder for complex float encoding
        encodeFloat(writer, new Token(Type.float, data), options)
      } else if (data >= 0) {
        encodeUintValue(writer, MAJOR_UINT, data)
      } else {
        // Negative integer
        encodeUintValue(writer, MAJOR_NEGINT, data * -1 - 1)
      }
      return

    case 'bigint':
      if (data >= BigInt(0)) {
        encodeUintValue(writer, MAJOR_UINT, data)
      } else {
        encodeUintValue(writer, MAJOR_NEGINT, data * neg1b - pos1b)
      }
      return

    case 'string': {
      const bytes = fromString(data)
      encodeUintValue(writer, MAJOR_STRING, bytes.length)
      writer.push(bytes)
      return
    }

    case 'Uint8Array':
      encodeUintValue(writer, MAJOR_BYTES, data.length)
      writer.push(data)
      return

    case 'Array':
      if (!data.length) {
        writer.push([MAJOR_ARRAY]) // Empty array: 0x80
        return
      }
      refStack = Ref.createCheck(refStack, data)
      encodeUintValue(writer, MAJOR_ARRAY, data.length)
      for (const elem of data) {
        directEncode(writer, elem, options, refStack)
      }
      return

    case 'Object':
    case 'Map':
      // Maps require key sorting, use token-based encoding for efficiency
      // (pre-encoding all keys for sorting is expensive)
      {
        const tokens = typeEncoders.Object(data, typ, options, refStack)
        tokensToEncoded(writer, tokens, cborEncoders, options)
      }
      return

    default:
    // Fall back to token-based encoding for other types (DataView, TypedArrays, etc.)
    {
      const typeEncoder = typeEncoders[typ]
      if (!typeEncoder) {
        throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`)
      }
      const tokens = typeEncoder(data, typ, options, refStack)
      tokensToEncoded(writer, tokens, cborEncoders, options)
    }
  }
}

/**
 * @template {ArrayBufferLike} T
 * @overload
 * @param {any} data
 * @param {TokenTypeEncoder[]} encoders
 * @param {EncodeOptions} options
 * @param {Uint8Array<T>} destination
 * @returns {Uint8Array<T>}
 */
/**
 * @overload
 * @param {any} data
 * @param {TokenTypeEncoder[]} encoders
 * @param {EncodeOptions} options
 * @returns {AllocatedByteView}
 */
/**
 * @param {any} data
 * @param {TokenTypeEncoder[]} encoders
 * @param {EncodeOptions} options
 * @param {ByteView} [destination]
 * @returns {ByteView}
 */
function encodeCustom (data, encoders, options, destination) {
  // arg ordering is different to encodeInto for backward compatibility
  const hasDest = destination instanceof Uint8Array
  let writeTo = hasDest ? new U8Bl(destination) : defaultWriter

  const tokens = objectToTokens(data, options)
  if (!Array.isArray(tokens) && options.quickEncodeToken) {
    const quickBytes = options.quickEncodeToken(tokens)
    if (quickBytes) {
      if (hasDest) {
        // Copy quick bytes into destination buffer
        writeTo.push(quickBytes)
        return writeTo.toBytes()
      }
      return quickBytes
    }
    const encoder = encoders[tokens.type.major]
    if (encoder.encodedSize) {
      const size = encoder.encodedSize(tokens, options)
      if (!hasDest) {
        writeTo = new Bl(size)
      }
      encoder(writeTo, tokens, options)
      // this would be a problem with encodedSize() functions
      if (writeTo.chunks.length !== 1) {
        throw new Error(`Unexpected error: pre-calculated length for ${tokens} was wrong`)
      }
      return hasDest ? writeTo.toBytes() : asU8A(writeTo.chunks[0])
    }
  }
  writeTo.reset()
  tokensToEncoded(writeTo, tokens, encoders, options)
  return writeTo.toBytes(true)
}

/**
 * @param {any} data
 * @param {EncodeOptions} [options]
 * @returns {AllocatedByteView}
 */
function encode (data, options) {
  options = Object.assign({}, defaultEncodeOptions, options)

  // Use direct encode path when possible
  if (canDirectEncode(options)) {
    defaultWriter.reset()
    directEncode(defaultWriter, data, options, undefined)
    return defaultWriter.toBytes(true)
  }

  return encodeCustom(data, cborEncoders, options)
}

/**
 * @template {ArrayBufferLike} T
 * @param {any} data
 * @param {Uint8Array<T>} destination
 * @param {EncodeOptions} [options]
 * @returns {{ written: number }}
 */
function encodeInto (data, destination, options) {
  options = Object.assign({}, defaultEncodeOptions, options)

  // Use direct encode path when possible
  if (canDirectEncode(options)) {
    const writer = new U8Bl(destination)
    directEncode(writer, data, options, undefined)
    return { written: writer.toBytes().length }
  }

  const result = encodeCustom(data, cborEncoders, options, destination)
  return { written: result.length }
}

export { objectToTokens, encode, encodeCustom, encodeInto, Ref }
// This is an unfortunate replacement for @sindresorhus/is that we need to
// re-implement for performance purposes. In particular the is.observable()
// check is expensive, and unnecessary for our purposes. The values returned
// are compatible with @sindresorhus/is, however.

// Types that reach getObjectType() - excludes types with fast-paths above:
// primitives (typeof), Array (isArray), Uint8Array (instanceof), plain Object (constructor)
const objectTypeNames = [
  'Object', // for Object.create(null) and other non-plain objects
  'RegExp',
  'Date',
  'Error',
  'Map',
  'Set',
  'WeakMap',
  'WeakSet',
  'ArrayBuffer',
  'SharedArrayBuffer',
  'DataView',
  'Promise',
  'URL',
  'HTMLElement',
  'Int8Array',
  'Uint8ClampedArray',
  'Int16Array',
  'Uint16Array',
  'Int32Array',
  'Uint32Array',
  'Float32Array',
  'Float64Array',
  'BigInt64Array',
  'BigUint64Array',
  'Tagged'
]

/**
 * @param {any} value
 * @returns {string}
 */
export function is (value) {
  if (value === null) {
    return 'null'
  }
  if (value === undefined) {
    return 'undefined'
  }
  if (value === true || value === false) {
    return 'boolean'
  }
  const typeOf = typeof value
  if (typeOf === 'string' || typeOf === 'number' || typeOf === 'bigint' || typeOf === 'symbol') {
    return typeOf
  }
  if (typeOf === 'function') {
    return 'Function'
  }
  if (Array.isArray(value)) {
    return 'Array'
  }
  // Also catches Node.js Buffer which extends Uint8Array
  if (value instanceof Uint8Array) {
    return 'Uint8Array'
  }
  // Fast path for plain objects (most common case after primitives/arrays/bytes)
  if (value.constructor === Object) {
    return 'Object'
  }
  const objectType = getObjectType(value)
  if (objectType) {
    return objectType
  }
  return 'Object'
}

/**
 * @param {any} value
 * @returns {string|undefined}
 */
function getObjectType (value) {
  const objectTypeName = Object.prototype.toString.call(value).slice(8, -1)
  if (objectTypeNames.includes(objectTypeName)) {
    return objectTypeName
  }
  return undefined
}
import { Token, Type } from './token.js'
import * as uint from './0uint.js'
import * as negint from './1negint.js'
import * as bytes from './2bytes.js'
import * as string from './3string.js'
import * as array from './4array.js'
import * as map from './5map.js'
import * as tag from './6tag.js'
import * as float from './7float.js'
import { decodeErrPrefix } from './common.js'
import { fromArray } from './byte-utils.js'

/**
 * @typedef {import('../interface.js').DecodeOptions} DecodeOptions
 * @typedef {import('../interface.js').AllocatedByteView} AllocatedByteView
 */

/**
 * @param {Uint8Array} data
 * @param {number} pos
 * @param {number} minor
 */
function invalidMinor (data, pos, minor) {
  throw new Error(`${decodeErrPrefix} encountered invalid minor (${minor}) for major ${data[pos] >>> 5}`)
}

/**
 * @param {string} msg
 * @returns {()=>any}
 */
function errorer (msg) {
  return () => { throw new Error(`${decodeErrPrefix} ${msg}`) }
}

/** @type {((data:Uint8Array, pos:number, minor:number, options?:DecodeOptions) => any)[]} */
export const jump = []

// unsigned integer, 0x00..0x17 (0..23)
for (let i = 0; i <= 0x17; i++) {
  jump[i] = invalidMinor // uint.decodeUintCompact, handled by quick[]
}
jump[0x18] = uint.decodeUint8 // unsigned integer, one-byte uint8_t follows
jump[0x19] = uint.decodeUint16 // unsigned integer, two-byte uint16_t follows
jump[0x1a] = uint.decodeUint32 // unsigned integer, four-byte uint32_t follows
jump[0x1b] = uint.decodeUint64 // unsigned integer, eight-byte uint64_t follows
jump[0x1c] = invalidMinor
jump[0x1d] = invalidMinor
jump[0x1e] = invalidMinor
jump[0x1f] = invalidMinor
// negative integer, -1-0x00..-1-0x17 (-1..-24)
for (let i = 0x20; i <= 0x37; i++) {
  jump[i] = invalidMinor // negintDecode, handled by quick[]
}
jump[0x38] = negint.decodeNegint8 // negative integer, -1-n one-byte uint8_t for n follows
jump[0x39] = negint.decodeNegint16 // negative integer, -1-n two-byte uint16_t for n follows
jump[0x3a] = negint.decodeNegint32 // negative integer, -1-n four-byte uint32_t for follows
jump[0x3b] = negint.decodeNegint64 // negative integer, -1-n eight-byte uint64_t for follows
jump[0x3c] = invalidMinor
jump[0x3d] = invalidMinor
jump[0x3e] = invalidMinor
jump[0x3f] = invalidMinor
// byte string, 0x00..0x17 bytes follow
for (let i = 0x40; i <= 0x57; i++) {
  jump[i] = bytes.decodeBytesCompact
}
jump[0x58] = bytes.decodeBytes8 // byte string, one-byte uint8_t for n, and then n bytes follow
jump[0x59] = bytes.decodeBytes16 // byte string, two-byte uint16_t for n, and then n bytes follow
jump[0x5a] = bytes.decodeBytes32 // byte string, four-byte uint32_t for n, and then n bytes follow
jump[0x5b] = bytes.decodeBytes64 // byte string, eight-byte uint64_t for n, and then n bytes follow
jump[0x5c] = invalidMinor
jump[0x5d] = invalidMinor
jump[0x5e] = invalidMinor
jump[0x5f] = errorer('indefinite length bytes/strings are not supported') // byte string, byte strings follow, terminated by "break"
// UTF-8 string 0x00..0x17 bytes follow
for (let i = 0x60; i <= 0x77; i++) {
  jump[i] = string.decodeStringCompact
}
jump[0x78] = string.decodeString8 // UTF-8 string, one-byte uint8_t for n, and then n bytes follow
jump[0x79] = string.decodeString16 // UTF-8 string, two-byte uint16_t for n, and then n bytes follow
jump[0x7a] = string.decodeString32 // UTF-8 string, four-byte uint32_t for n, and then n bytes follow
jump[0x7b] = string.decodeString64 // UTF-8 string, eight-byte uint64_t for n, and then n bytes follow
jump[0x7c] = invalidMinor
jump[0x7d] = invalidMinor
jump[0x7e] = invalidMinor
jump[0x7f] = errorer('indefinite length bytes/strings are not supported') // UTF-8 strings follow, terminated by "break"
// array, 0x00..0x17 data items follow
for (let i = 0x80; i <= 0x97; i++) {
  jump[i] = array.decodeArrayCompact
}
jump[0x98] = array.decodeArray8 // array, one-byte uint8_t for n, and then n data items follow
jump[0x99] = array.decodeArray16 // array, two-byte uint16_t for n, and then n data items follow
jump[0x9a] = array.decodeArray32 // array, four-byte uint32_t for n, and then n data items follow
jump[0x9b] = array.decodeArray64 // array, eight-byte uint64_t for n, and then n data items follow
jump[0x9c] = invalidMinor
jump[0x9d] = invalidMinor
jump[0x9e] = invalidMinor
jump[0x9f] = array.decodeArrayIndefinite // array, data items follow, terminated by "break"
// map, 0x00..0x17 pairs of data items follow
for (let i = 0xa0; i <= 0xb7; i++) {
  jump[i] = map.decodeMapCompact
}
jump[0xb8] = map.decodeMap8 // map, one-byte uint8_t for n, and then n pairs of data items follow
jump[0xb9] = map.decodeMap16 // map, two-byte uint16_t for n, and then n pairs of data items follow
jump[0xba] = map.decodeMap32 // map, four-byte uint32_t for n, and then n pairs of data items follow
jump[0xbb] = map.decodeMap64 // map, eight-byte uint64_t for n, and then n pairs of data items follow
jump[0xbc] = invalidMinor
jump[0xbd] = invalidMinor
jump[0xbe] = invalidMinor
jump[0xbf] = map.decodeMapIndefinite // map, pairs of data items follow, terminated by "break"
// tags
for (let i = 0xc0; i <= 0xd7; i++) {
  jump[i] = tag.decodeTagCompact
}
jump[0xd8] = tag.decodeTag8
jump[0xd9] = tag.decodeTag16
jump[0xda] = tag.decodeTag32
jump[0xdb] = tag.decodeTag64
jump[0xdc] = invalidMinor
jump[0xdd] = invalidMinor
jump[0xde] = invalidMinor
jump[0xdf] = invalidMinor
// 0xe0..0xf3 simple values, unsupported
for (let i = 0xe0; i <= 0xf3; i++) {
  jump[i] = errorer('simple values are not supported')
}
jump[0xf4] = invalidMinor // false, handled by quick[]
jump[0xf5] = invalidMinor // true, handled by quick[]
jump[0xf6] = invalidMinor // null, handled by quick[]
jump[0xf7] = float.decodeUndefined // undefined
jump[0xf8] = errorer('simple values are not supported') // simple value, one byte follows, unsupported
jump[0xf9] = float.decodeFloat16 // half-precision float (two-byte IEEE 754)
jump[0xfa] = float.decodeFloat32 // single-precision float (four-byte IEEE 754)
jump[0xfb] = float.decodeFloat64 // double-precision float (eight-byte IEEE 754)
jump[0xfc] = invalidMinor
jump[0xfd] = invalidMinor
jump[0xfe] = invalidMinor
jump[0xff] = float.decodeBreak // "break" stop code

/** @type {Token[]} */
export const quick = []
// ints <24
for (let i = 0; i < 24; i++) {
  quick[i] = new Token(Type.uint, i, 1)
}
// negints >= -24
for (let i = -1; i >= -24; i--) {
  quick[31 - i] = new Token(Type.negint, i, 1)
}
// empty bytes
quick[0x40] = new Token(Type.bytes, new Uint8Array(0), 1)
// empty string
quick[0x60] = new Token(Type.string, '', 1)
// empty list
quick[0x80] = new Token(Type.array, 0, 1)
// empty map
quick[0xa0] = new Token(Type.map, 0, 1)
// false
quick[0xf4] = new Token(Type.false, false, 1)
// true
quick[0xf5] = new Token(Type.true, true, 1)
// null
quick[0xf6] = new Token(Type.null, null, 1)

/**
 * @param {Token} token
 * @returns {AllocatedByteView|undefined}
 */
export function quickEncodeToken (token) {
  switch (token.type) {
    case Type.false:
      return fromArray([0xf4])
    case Type.true:
      return fromArray([0xf5])
    case Type.null:
      return fromArray([0xf6])
    case Type.bytes:
      if (!token.value.length) {
        return fromArray([0x40])
      }
      return
    case Type.string:
      if (token.value === '') {
        return fromArray([0x60])
      }
      return
    case Type.array:
      if (token.value === 0) {
        return fromArray([0x80])
      }
      // shouldn't be possible if this were called when there was only one token
      return
    case Type.map:
      if (token.value === 0) {
        return fromArray([0xa0])
      }
      // shouldn't be possible if this were called when there was only one token
      return
    case Type.uint:
      if (token.value < 24) {
        return fromArray([Number(token.value)])
      }
      return
    case Type.negint:
      if (token.value >= -24) {
        return fromArray([31 - Number(token.value)])
      }
  }
}
/**
 * @typedef {import('../interface.js').TagDecodeControl} TagDecodeControl
 * @typedef {(decode: TagDecodeControl) => Tagged} TaggedTagDecoder
 */

/**
 * A wrapper class for representing a CBOR tag with an arbitrary nested value.
 *
 * `Tagged` is a symmetric primitive: it can be passed to `encode()` to emit
 * a CBOR tag header followed by the encoded form of `value`, and it can be
 * returned from a tag decoder (via `Tagged.decoder(tag)` or `Tagged.preserve()`)
 * to round-trip a tag through decode without losing the tag number.
 *
 * Use `Tagged` for one-off tag handling where defining a dedicated
 * `typeEncoders` entry and tag decoder pair would be heavyweight, e.g. when
 * wrapping a structure in a single application-specific tag (COSE, dCBOR
 * envelopes, etc.).
 *
 * For systematic mapping of a JS type to a tag (e.g. CID -> tag 42), prefer
 * a dedicated `typeEncoders` entry instead.
 */
export class Tagged {
  /**
   * @param {number} tag - CBOR tag number, a non-negative integer
   * @param {any} value - The value to be tagged; encoded recursively
   */
  constructor (tag, value) {
    if (typeof tag !== 'number' || !Number.isInteger(tag) || tag < 0) {
      throw new TypeError('Tagged: tag must be a non-negative integer')
    }
    this.tag = tag
    this.value = value
  }

  /**
   * Build a tag decoder for use in `decode()`'s `tags` option that returns the
   * decoded content wrapped in a `Tagged` instance, preserving the tag number
   * for the caller to inspect.
   *
   * @param {number} tag - The CBOR tag number this decoder will be registered for
   * @returns {TaggedTagDecoder}
   *
   * @example
   * import { decode, Tagged } from 'cborg'
   * const value = decode(bytes, { tags: { 16: Tagged.decoder(16) } })
   * // value instanceof Tagged; value.tag === 16
   */
  static decoder (tag) {
    return (decode) => new Tagged(tag, decode())
  }

  /**
   * Build a `tags` option for `decode()` that wraps each listed tag number in
   * a `Tagged` instance, preserving those tags through decode without
   * registering a dedicated decoder per tag.
   *
   * @param {...number} tagNumbers - One or more CBOR tag numbers to preserve
   * @returns {{[tagNumber: number]: TaggedTagDecoder}}
   *
   * @example
   * import { decode, Tagged } from 'cborg'
   * const value = decode(bytes, { tags: Tagged.preserve(16, 96) })
   */
  static preserve (...tagNumbers) {
    /** @type {{[tagNumber: number]: TaggedTagDecoder}} */
    const tags = {}
    for (const tag of tagNumbers) {
      tags[tag] = Tagged.decoder(tag)
    }
    return tags
  }
}

// Symbol.toStringTag so the internal `is()` type detection returns 'Tagged'
// for instances, allowing the default Tagged typeEncoder to match.
Object.defineProperty(Tagged.prototype, Symbol.toStringTag, {
  value: 'Tagged'
})
class Type {
  /**
   * @param {number} major
   * @param {string} name
   * @param {boolean} terminal
   */
  constructor (major, name, terminal) {
    this.major = major
    this.majorEncoded = major << 5
    this.name = name
    this.terminal = terminal
  }

  toString () {
    return `Type[${this.major}].${this.name}`
  }

  /**
   * @param {Type} typ
   * @returns {number}
   */
  compare (typ) {
    return this.major < typ.major ? -1 : this.major > typ.major ? 1 : 0
  }

  /**
   * Check equality between two Type instances. Safe to use across different
   * copies of the Type class (e.g., when bundlers duplicate the module).
   * (major, name) uniquely identifies a Type; terminal is implied by these.
   * @param {Type} a
   * @param {Type} b
   * @returns {boolean}
   */
  static equals (a, b) {
    return a === b || (a.major === b.major && a.name === b.name)
  }
}

// convert to static fields when better supported
Type.uint = new Type(0, 'uint', true)
Type.negint = new Type(1, 'negint', true)
Type.bytes = new Type(2, 'bytes', true)
Type.string = new Type(3, 'string', true)
Type.array = new Type(4, 'array', false)
Type.map = new Type(5, 'map', false)
Type.tag = new Type(6, 'tag', false) // terminal?
Type.float = new Type(7, 'float', true)
Type.false = new Type(7, 'false', true)
Type.true = new Type(7, 'true', true)
Type.null = new Type(7, 'null', true)
Type.undefined = new Type(7, 'undefined', true)
Type.break = new Type(7, 'break', true)
// Type.indefiniteLength = new Type(0, 'indefiniteLength', true)

class Token {
  /**
   * @param {Type} type
   * @param {any} [value]
   * @param {number} [encodedLength]
   */
  constructor (type, value, encodedLength) {
    this.type = type
    this.value = value
    this.encodedLength = encodedLength
    /** @type {Uint8Array|undefined} */
    this.encodedBytes = undefined
    /** @type {Uint8Array|undefined} */
    this.byteValue = undefined
  }

  toString () {
    return `Token[${this.type}].${this.value}`
  }
}

export { Type, Token }
{
  "name": "cborg",
  "version": "5.1.7",
  "description": "Fast CBOR with a focus on strictness",
  "main": "cborg.js",
  "type": "module",
  "bin": {
    "cborg": "lib/bin.js"
  },
  "scripts": {
    "lint": "standard *.js lib/*.js test/*.js",
    "build": "npm run build:types",
    "build:types": "tsc --build",
    "prepublishOnly": "npm run build",
    "test:node": "mocha test/test-*.js",
    "test:node-bin": "mocha test/node-test-bin.js",
    "test:browser": "polendina --cleanup test/test-*.js",
    "test": "npm run lint && npm run build && npm run test:node && npm run test:node-bin && npm run test:browser",
    "test:ci": "npm run test"
  },
  "repository": {
    "type": "git",
    "url": "git@github.com:rvagg/cborg.git"
  },
  "keywords": [
    "cbor"
  ],
  "author": "Rod <rod@vagg.org> (http://r.va.gg/)",
  "license": "Apache-2.0",
  "devDependencies": {
    "@semantic-release/changelog": "^6.0.3",
    "@semantic-release/commit-analyzer": "^13.0.1",
    "@semantic-release/git": "^10.0.1",
    "@semantic-release/github": "^12.0.6",
    "@semantic-release/npm": "^13.1.5",
    "@semantic-release/release-notes-generator": "^14.1.0",
    "@types/chai": "^5.2.3",
    "@types/mocha": "^10.0.10",
    "@types/node": "^26.0.1",
    "chai": "^6.2.2",
    "conventional-changelog-conventionalcommits": "^10.0.0",
    "ipld-garbage": "^5.0.0",
    "mocha": "^11.7.5",
    "polendina": "^3.2.20",
    "semantic-release": "^25.0.3",
    "standard": "^17.1.2",
    "typescript": "^6.0.2"
  },
  "exports": {
    ".": {
      "import": "./cborg.js",
      "types": "./types/cborg.d.ts"
    },
    "./length": {
      "import": "./lib/length.js",
      "types": "./types/lib/length.d.ts"
    },
    "./taglib": {
      "import": "./lib/taglib.js",
      "types": "./types/lib/taglib.d.ts"
    },
    "./json": {
      "import": "./lib/json/json.js",
      "types": "./types/lib/json/json.d.ts"
    },
    "./extended": {
      "import": "./lib/extended/extended.js",
      "types": "./types/lib/extended/extended.d.ts"
    },
    "./interface": {
      "types": "./types/interface.d.ts"
    }
  },
  "types": "cborg.d.ts",
  "typesVersions": {
    "*": {
      "json": [
        "types/lib/json/json.d.ts"
      ],
      "length": [
        "types/lib/length.d.ts"
      ],
      "*": [
        "types/*"
      ],
      "types/*": [
        "types/*"
      ]
    }
  },
  "release": {
    "branches": [
      "master"
    ],
    "plugins": [
      [
        "@semantic-release/commit-analyzer",
        {
          "preset": "conventionalcommits",
          "releaseRules": [
            {
              "breaking": true,
              "release": "major"
            },
            {
              "revert": true,
              "release": "patch"
            },
            {
              "type": "feat",
              "release": "minor"
            },
            {
              "type": "fix",
              "release": "patch"
            },
            {
              "type": "chore",
              "release": "patch"
            },
            {
              "type": "docs",
              "release": "patch"
            },
            {
              "type": "test",
              "release": "patch"
            },
            {
              "scope": "no-release",
              "release": false
            }
          ]
        }
      ],
      [
        "@semantic-release/release-notes-generator",
        {
          "preset": "conventionalcommits",
          "presetConfig": {
            "types": [
              {
                "type": "feat",
                "section": "Features"
              },
              {
                "type": "fix",
                "section": "Bug Fixes"
              },
              {
                "type": "chore",
                "section": "Trivial Changes"
              },
              {
                "type": "docs",
                "section": "Trivial Changes"
              },
              {
                "type": "test",
                "section": "Tests"
              }
            ]
          }
        }
      ],
      "@semantic-release/changelog",
      "@semantic-release/npm",
      "@semantic-release/github",
      "@semantic-release/git"
    ]
  }
}
const c = require('compact-encoding')

module.exports = function bitfield(length) {
  if (length > 64) {
    throw new RangeError('Bitfield cannot be larger than 64 bits')
  }

  let byteLength
  if (length < 8) byteLength = 1
  else if (length <= 16) byteLength = 2
  else if (length <= 32) byteLength = 4
  else byteLength = 8

  return {
    preencode(state) {
      state.end++ // Length byte, used for data when byteLength === 1

      if (byteLength === 1);
      else if (byteLength === 2) c.uint16.preencode(state)
      else if (byteLength === 4) c.uint32.preencode(state)
      else c.uint64.preencode(state)
    },

    encode(state, b) {
      if (byteLength === 1);
      else if (byteLength === 2) c.uint8.encode(state, 0xfd)
      else if (byteLength === 4) c.uint8.encode(state, 0xfe)
      else c.uint8.encode(state, 0xff)

      if (typeof b === 'number') {
        if (byteLength === 1) c.uint8.encode(state, b)
        else if (byteLength === 2) c.uint16.encode(state, b)
        else if (byteLength === 4) c.uint32.encode(state, b)
        else c.uint64.encode(state, b)
      } else {
        state.buffer.set(b, state.start)

        if (b.byteLength < byteLength) {
          // Zero-fill the rest of the byte length.
          state.buffer.fill(
            0,
            state.start + b.byteLength,
            state.start + byteLength
          )
        }

        state.start += byteLength
      }
    },

    decode(state) {
      const byte = state.buffer[state.start]

      let byteLength
      if (byte <= 0xfc) byteLength = 1
      else if (byte === 0xfd) byteLength = 2
      else if (byte === 0xfe) byteLength = 4
      else byteLength = 8

      if (byteLength > 1) state.start++ // Skip the length byte

      if (state.end - state.start < byteLength) throw new Error('Out of bounds')

      const b = state.buffer.subarray(state.start, (state.start += byteLength))

      return length <= 8 ? b.subarray(0, 1) : b
    }
  }
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "compact-encoding-bitfield",
  "version": "1.1.0",
  "description": "Compact codec for bitfields",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node --coverage test.mjs",
    "test:bare": "brittle-bare --coverage test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/compact-encoding/compact-encoding-bitfield.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/compact-encoding/compact-encoding-bitfield/issues"
  },
  "homepage": "https://github.com/compact-encoding/compact-encoding-bitfield#readme",
  "imports": {
    "util": {
      "bare": "bare-utils",
      "default": "util"
    }
  },
  "dependencies": {
    "compact-encoding": "^3.0.0"
  },
  "devDependencies": {
    "bare-utils": "^1.5.1",
    "brittle": "^3.1.0",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  }
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return uint24.decode(state) + 0x1000000 * uint32.decode(state)
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return uint32.decode(state) + 0x100000000 * uint32.decode(state)
  }
})

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "2.19.2",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    if (b.byteLength === 0) return null
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
const { EventEmitter } = require('events')
const Table = require('kademlia-routing-table')
const TOS = require('time-ordered-set')
const UDX = require('udx-native')
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const NatSampler = require('nat-sampler')
const b4a = require('b4a')
const NetworkHealth = require('./lib/health')
const IO = require('./lib/io')
const Query = require('./lib/query')
const Session = require('./lib/session')
const peer = require('./lib/peer')
const { UNKNOWN_COMMAND, INVALID_TOKEN } = require('./lib/errors')
const { PING, PING_NAT, FIND_NODE, DOWN_HINT, DELAYED_PING } = require('./lib/commands')

const TMP = b4a.allocUnsafe(32)
const TICK_INTERVAL = 5000
const SLEEPING_INTERVAL = 3 * TICK_INTERVAL
const STABLE_TICKS = 240 // if nothing major bad happens in ~20mins we can consider this node stable (if nat is friendly)
const MORE_STABLE_TICKS = 3 * STABLE_TICKS
const REFRESH_TICKS = 60 // refresh every ~5min when idle
const RECENT_NODE = 12 // we've heard from a node less than 1min ago
const OLD_NODE = 360 // if an node has been around more than 30 min we consider it old

const DEFAULTS = {
  concurrency: 10,
  maxWindow: IO.DEFAULT_MAX_WINDOW,
  maxPingDelay: 10_000
}

class DHT extends EventEmitter {
  constructor(opts = {}) {
    super()

    this.bootstrapNodes = opts.bootstrap === false ? [] : (opts.bootstrap || []).map(parseNode)
    this.table = new Table(randomBytes(32))
    this.nodes = new TOS()
    this.udx = opts.udx || new UDX()
    this.io = new IO(this.table, this.udx, {
      ...opts,
      onrequest: this._onrequest.bind(this),
      onresponse: this._onresponse.bind(this),
      ontimeout: this._ontimeout.bind(this)
    })
    this.health = new NetworkHealth(this)

    this.concurrency = opts.concurrency || DEFAULTS.concurrency
    this.maxPingDelay = opts.maxPingDelay || DEFAULTS.maxPingDelay
    this.bootstrapped = false
    this.ephemeral = true
    this.firewalled = this.io.firewalled
    this.adaptive = typeof opts.ephemeral !== 'boolean' && opts.adaptive !== false
    this.destroyed = false
    this.suspended = false
    this.online = true
    this.degraded = false
    this.stats = {
      queries: { active: 0, total: 0 },
      requests: this.io.stats.requests,
      commands: {
        ping: this.io.stats.commands[PING],
        pingNat: this.io.stats.commands[PING_NAT],
        findNode: this.io.stats.commands[FIND_NODE],
        downHint: this.io.stats.commands[DOWN_HINT]
      }
    }

    this._nat = new NatSampler()
    this._quickFirewall = opts.quickFirewall !== false
    this._forcePersistent = opts.ephemeral === false
    this._repinging = 0
    this._checks = 0
    this._tick = randomOffset(100) // make sure to random offset all the network ticks
    this._refreshTicks = randomOffset(REFRESH_TICKS)
    this._stableTicks = this.adaptive ? STABLE_TICKS : 0
    this._tickInterval = setInterval(this._ontick.bind(this), TICK_INTERVAL)
    this._lastTick = Date.now()
    this._lastHost = null
    this._filterNode = opts.filterNode || opts.addNode || null // opts.addNode is deprecating, use opts.filterNode instead
    this._onrow = (row) => row.on('full', (node) => this._onfullrow(node, row))
    this._nonePersistentSamples = []
    this._bootstrapping = this._bootstrap()
    this._bootstrapping.catch(noop)
    this._sendDownHints = opts.sendDownHints !== false
    this._downHintsRateLimit =
      opts.downHintsRateLimit !== undefined ? opts.downHintsRateLimit : 10 * 5
    this._downHintsSentPerTick = 0
    this._pendingTimers = new Set()

    this.table.on('row', this._onrow)

    this.io.networkInterfaces.on('change', (interfaces) => this._onnetworkchange(interfaces))

    if (opts.nodes) {
      for (let i = opts.nodes.length - 1; i >= 0; i--) {
        this.addNode(opts.nodes[i])
      }
    }
  }

  static DEFAULTS = DEFAULTS

  static bootstrapper(port, host, opts) {
    if (!port) throw new Error('Port is required')
    if (!host) throw new Error('Host is required')
    if (host === '0.0.0.0' || host === '::') throw new Error('Invalid host')
    if (!UDX.isIPv4(host)) throw new Error('Host must be a IPv4 address')

    const dht = new this({
      port,
      ephemeral: false,
      firewalled: false,
      anyPort: false,
      bootstrap: [],
      ...opts
    })
    dht._nat.add(host, port)
    return dht
  }

  get id() {
    return this.ephemeral ? null : this.table.id
  }

  get host() {
    return this._nat.host
  }

  get port() {
    return this._nat.port
  }

  get randomized() {
    return this._nat.host !== null && this._nat.port === 0
  }

  get socket() {
    return this.firewalled ? this.io.clientSocket : this.io.serverSocket
  }

  get config() {
    return {
      concurrency: this.concurrency,
      maxWindow: this.io.congestion._maxWindow,
      randomPunchInterval: this._randomPunchInterval,
      connectionKeepAlive: this.connectionKeepAlive,
      sendDownHints: this._sendDownHints,
      downHintsRateLimit: this._downHintsRateLimit
    }
  }

  onmessage(socket, buf, rinfo) {
    if (buf.byteLength > 1) this.io.onmessage(socket, buf, rinfo)
  }

  bind() {
    return this.io.bind()
  }

  async suspend({ log = noop } = {}) {
    log('Suspending waiting for io bind...')
    await this.io.bind()
    log('Done, continuing')
    if (this.suspended || this.destroyed) return
    this.suspended = true
    clearInterval(this._tickInterval)
    log('Done, suspending io')
    await this.io.suspend({ log })
    log('Done, dht suspended')
    this.emit('suspend')
  }

  async resume({ log = noop } = {}) {
    if (!this.suspended || this.destroyed) return
    this.suspended = false
    this._tickInterval = setInterval(this._ontick.bind(this), TICK_INTERVAL)
    this._onwakeup()
    log('Resuming io')
    await this.io.resume()
    log('Done, dht resumed')
    this.io.networkInterfaces.on('change', (interfaces) => this._onnetworkchange(interfaces))
    this.refresh()
    this.emit('resume')
  }

  address() {
    const socket = this.socket
    return socket ? socket.address() : null
  }

  localAddress() {
    if (!this.io.serverSocket) return null

    return {
      host: localIP(this.udx),
      port: this.io.serverSocket.address().port
    }
  }

  remoteAddress() {
    if (!this.host) return null
    if (!this.port) return null
    if (this.firewalled) return null
    if (!this.io.serverSocket) return null

    const port = this.io.serverSocket.address().port
    if (port !== this.port) return null

    return {
      host: this.host,
      port
    }
  }

  addNode({ host, port }) {
    this._addNode({
      id: peer.id(host, port),
      port,
      host,
      token: null,
      to: null,
      sampled: 0,
      added: this._tick,
      pinged: 0,
      seen: 0,
      downHints: 0,
      prev: null,
      next: null
    })
  }

  toArray(opts) {
    const limit = opts && opts.limit
    if (limit === 0) return []
    return this.nodes.toArray({ limit, reverse: true }).map(({ host, port }) => ({ host, port }))
  }

  async fullyBootstrapped() {
    return this._bootstrapping
  }

  ready() {
    // Deprecating, use fullyBootstrapped instead (removed on next major)
    return this.fullyBootstrapped()
  }

  findNode(target, opts) {
    if (this.destroyed) throw new Error('Node destroyed')
    this._refreshTicks = REFRESH_TICKS
    return new Query(this, target, true, FIND_NODE, null, opts)
  }

  query({ target, command, value }, opts) {
    if (this.destroyed) throw new Error('Node destroyed')
    this._refreshTicks = REFRESH_TICKS
    return new Query(this, target, false, command, value || null, opts)
  }

  ping({ host, port }, opts) {
    let value = null

    if (opts && opts.size && opts.size > 0) value = b4a.alloc(opts.size)

    const req = this.io.createRequest(
      { id: null, host, port },
      null,
      true,
      PING,
      null,
      value,
      (opts && opts.session) || null,
      opts && opts.ttl
    )
    return this._requestToPromise(req, opts)
  }

  delayedPing({ host, port }, delayMs, opts) {
    if (delayMs > this.maxPingDelay) {
      throw new Error(`Delay exceeds max delay: ${this.maxPingDelay}ms`)
    }

    const value = b4a.allocUnsafe(4)
    c.uint32.encode({ start: 0, end: 4, buffer: value }, delayMs)

    const req = this.io.createRequest(
      { id: null, host, port },
      null,
      true,
      DELAYED_PING,
      null,
      value,
      (opts && opts.session) || null,
      opts && opts.ttl
    )
    // add 1 second to the timeout to account for network overhead
    req.timeout = delayMs + 1_000
    return this._requestToPromise(req, opts)
  }

  async rttStats() {
    const stats = {
      successes: 0,
      errors: 0,
      responses: {
        avgRtt: 0,
        errors: 0,
        avgCloserNodes: 0
      },
      closestReplies: {
        avgRtt: 0,
        errors: 0,
        avgCloserNodes: 0
      }
    }

    if (this.nodes.latest) {
      const q = this.findNode(this.nodes.latest.id)

      let responseCount = 0
      let closestCount = 0

      for await (const msg of q) {
        stats.responses.avgRtt += msg.rtt
        stats.responses.errors += msg.error
        stats.responses.avgCloserNodes += msg.closerNodes?.length || 0
        responseCount++
      }
      stats.responses.avgRtt /= responseCount
      stats.responses.avgCloserNodes /= responseCount

      for await (const msg of q.closestReplies) {
        stats.closestReplies.avgRtt += msg.rtt
        stats.closestReplies.errors += msg.error
        stats.closestReplies.avgCloserNodes += msg.closerNodes?.length || 0
        closestCount++
      }
      stats.closestReplies.avgRtt /= closestCount
      stats.closestReplies.avgCloserNodes /= closestCount

      stats.successes = q.successes
      stats.errors = q.errors
    }

    return stats
  }

  request({ token = null, command, target = null, value = null }, { host, port }, opts) {
    const req = this.io.createRequest(
      { id: null, host, port },
      token,
      false,
      command,
      target,
      value,
      (opts && opts.session) || null,
      opts && opts.ttl
    )
    return this._requestToPromise(req, opts)
  }

  session() {
    return new Session(this)
  }

  _requestToPromise(req, opts) {
    if (req === null) return Promise.reject(new Error('Node destroyed'))

    if (opts && opts.socket) req.socket = opts.socket
    if (opts && opts.retry === false) req.retries = 0

    return new Promise((resolve, reject) => {
      req.onresponse = resolve
      req.onerror = reject
      req.send()
    })
  }

  async _bootstrap() {
    const self = this

    await Promise.resolve() // wait a tick, so apis can be used from the outside
    await this.io.bind()

    this.emit('listening')

    // TODO: some papers describe more advanced ways of bootstrapping - we should prob look into that

    let first = this.firewalled && this._quickFirewall && !this._forcePersistent
    let testNat = false

    const onlyFirewall = !this._forcePersistent

    for (let i = 0; i < 2; i++) {
      await this._backgroundQuery(this.table.id).on('data', ondata).finished()

      if (this.bootstrapped || (!testNat && !this._forcePersistent)) break
      if (!(await this._updateNetworkState(onlyFirewall))) break
    }

    if (this.bootstrapped) return
    this.bootstrapped = true

    this.emit('ready')

    function ondata(data) {
      // Simple QUICK nat heuristic.
      // If we get ONE positive nat ping before the bootstrap query finishes
      // then we always to a nat test, no matter if we are adaptive...
      // This should be expanded in the future to try more than one node etc, not always hit the first etc
      // If this fails, then nbd, as the onstable hook will pick it up later.

      if (!first) return
      first = false

      const value = b4a.allocUnsafe(2)
      c.uint16.encode({ start: 0, end: 2, buffer: value }, self.io.serverSocket.address().port)

      self._request(
        data.from,
        false,
        true,
        PING_NAT,
        null,
        value,
        null,
        () => {
          testNat = true
        },
        noop
      )
    }
  }

  refresh() {
    const node = this.table.random()
    this._backgroundQuery(node ? node.id : this.table.id).on('error', noop)
  }

  async destroy() {
    const emitClose = !this.destroyed
    this.destroyed = true
    clearInterval(this._tickInterval)
    for (const timer of this._pendingTimers) {
      clearTimeout(timer)
    }
    await this.io.destroy()
    if (emitClose) this.emit('close')
  }

  _request(to, force, internal, command, target, value, session, onresponse, onerror) {
    if (internal && !this._sendDownHints && command === DOWN_HINT) return null
    const req = this.io.createRequest(to, null, internal, command, target, value, session)
    if (req === null) return null

    req.onresponse = onresponse
    req.onerror = onerror
    req.send(force)

    return req
  }

  _natAdd(host, port) {
    const prevHost = this._nat.host
    const prevPort = this._nat.port

    this._nat.add(host, port)

    if (prevHost === this._nat.host && prevPort === this._nat.port) return

    this.emit('nat-update', this._nat.host, this._nat.port)
  }

  // we don't check that this is a bootstrap node but we limit the sample size to very few nodes, so fine
  _sampleBootstrapMaybe(from, to) {
    if (this._nonePersistentSamples.length >= Math.max(1, this.bootstrapNodes.length)) return
    const id = from.host + ':' + from.port
    if (this._nonePersistentSamples.indexOf(id) > -1) return
    this._nonePersistentSamples.push(id)
    this._natAdd(to.host, to.port)
  }

  _addNodeFromNetwork(sample, from, to) {
    if (this._filterNode !== null && !this._filterNode(from)) {
      return
    }

    if (from.id === null) {
      this._sampleBootstrapMaybe(from, to)
      return
    }

    const oldNode = this.table.get(from.id)

    // refresh it, if we've seen this before
    if (oldNode) {
      if (sample && (oldNode.sampled === 0 || this._tick - oldNode.sampled >= OLD_NODE)) {
        oldNode.to = to
        oldNode.sampled = this._tick
        this._natAdd(to.host, to.port)
      }

      oldNode.pinged = oldNode.seen = this._tick
      this.nodes.add(oldNode)
      return
    }

    this._addNode({
      id: from.id,
      port: from.port,
      host: from.host,
      to,
      sampled: 0,
      added: this._tick,
      pinged: this._tick, // last time we interacted with them
      seen: this._tick, // last time we heard from them
      downHints: 0,
      prev: null,
      next: null
    })
  }

  _addNode(node) {
    if (this.nodes.has(node) || b4a.equals(node.id, this.table.id)) return

    node.added = node.pinged = node.seen = this._tick

    if (!this.table.add(node)) return
    this.nodes.add(node)

    if (node.to && node.sampled === 0) {
      node.sampled = this._tick
      this._natAdd(node.to.host, node.to.port)
    }

    this.emit('add-node', node)
  }

  _removeStaleNode(node, lastSeen) {
    if (node.seen <= lastSeen) this._removeNode(node)
  }

  _removeNode(node) {
    if (!this.nodes.has(node)) return

    this.table.remove(node.id)
    this.nodes.remove(node)

    this.emit('remove-node', node)
  }

  _onwakeup() {
    this._tick += 2 * OLD_NODE // bump the tick enough that everything appears old.
    this._tick += 8 - (this._tick & 7) - 2 // triggers a series of pings in two ticks
    this._stableTicks = MORE_STABLE_TICKS
    this._refreshTicks = 1 // triggers a refresh next tick (allow network time to wake up also)
    this._lastHost = null // clear network cache check
    this.health.reset()

    if (this.adaptive) {
      // TODO: re-enable this as soon as we find out why this is over triggering in some edge cases
      // this.firewalled = true
      // this.io.firewalled = true

      if (!this.ephemeral) {
        this.ephemeral = true
        this.io.ephemeral = true
        this.emit('ephemeral')
      }
    }

    this.emit('wakeup')
  }

  _onfullrow(newNode, row) {
    if (!this.bootstrapped || this._repinging >= 3) return

    let oldest = null
    for (const node of row.nodes) {
      if (node.pinged === this._tick) continue
      if (
        oldest === null ||
        oldest.pinged > node.pinged ||
        (oldest.pinged === node.pinged && oldest.added > node.added)
      ) {
        oldest = node
      }
    }

    if (oldest === null) return
    if (this._tick - oldest.pinged < RECENT_NODE && this._tick - oldest.added > OLD_NODE) return

    this._repingAndSwap(newNode, oldest)
  }

  _onnetworkchange(interfaces) {
    this.emit('network-change', interfaces)
    this.emit('network-update')
  }

  _repingAndSwap(newNode, oldNode) {
    const self = this
    const lastSeen = oldNode.seen

    oldNode.pinged = this._tick

    this._repinging++
    this._request(
      { id: null, host: oldNode.host, port: oldNode.port },
      false,
      true,
      PING,
      null,
      null,
      null,
      onsuccess,
      onswap
    )

    function onsuccess(m) {
      if (oldNode.seen <= lastSeen) return onswap()
      self._repinging--
    }

    function onswap(e) {
      self._repinging--
      self._removeNode(oldNode)
      self._addNode(newNode)
    }
  }

  _onrequest(req, external) {
    if (req.from.id !== null) {
      this._addNodeFromNetwork(!external, req.from, req.to)
    }

    if (req.internal) {
      switch (req.command) {
        // standard keep alive call
        case PING: {
          req.sendReply(0, null, false, false)
          return
        }
        case DELAYED_PING: {
          this._ondelayedping(req)
          return
        }
        // check if the other side can receive a message to their other socket
        case PING_NAT: {
          if (req.value === null || req.value.byteLength < 2) return
          const port = c.uint16.decode({ start: 0, end: 2, buffer: req.value })
          if (port === 0) return
          req.from.port = port
          req.sendReply(0, null, false, false)
          return
        }
        // empty dht reply back
        case FIND_NODE: {
          if (!req.target) return
          req.sendReply(0, null, false, true)
          return
        }
        // "this is node you sent me is down" - let's try to ping it
        case DOWN_HINT: {
          if (req.value === null || req.value.byteLength < 6) return
          if (this._checks < 10) {
            sodium.crypto_generichash(TMP, req.value.subarray(0, 6))
            const node = this.table.get(TMP)
            if (node && (node.pinged < this._tick || node.downHints === 0)) {
              node.downHints++
              this._check(node)
            }
          }
          req.sendReply(0, null, false, false)
          return
        }
      }

      req.sendReply(UNKNOWN_COMMAND, null, false, req.target !== null)
      return
    }

    // ask the user to handle it or reply back with a bad command
    if (this.onrequest(req) === false) {
      req.sendReply(UNKNOWN_COMMAND, null, false, req.target !== null)
    }
  }

  onrequest(req) {
    return this.emit('request', req)
  }

  _ondelayedping(req) {
    if (req.value === null || req.value.byteLength < 4) return
    const delayMs = c.uint32.decode({ start: 0, end: 4, buffer: req.value })
    if (delayMs > this.maxPingDelay) return
    const timer = setTimeout(() => {
      if (this.destroyed) return
      this._pendingTimers.delete(timer)
      req.sendReply(0, null, false, false)
    }, delayMs)
    this._pendingTimers.add(timer)
  }

  _onresponse(res, external) {
    this._addNodeFromNetwork(!external, res.from, res.to)
  }

  _ontimeout(req) {
    if (!req.to.id) return
    const node = this.table.get(req.to.id)
    if (node) this._removeNode(node)
  }

  _pingSome() {
    let cnt = this.io.inflight.length > 2 ? 3 : 5
    let oldest = this.nodes.oldest

    // tiny dht, pinged the bootstrap again
    if (!oldest) {
      this.refresh()
      return
    }

    // we've recently pinged the oldest one, so only trigger a couple of repings
    if (this._tick - oldest.pinged < RECENT_NODE) {
      cnt = 2
    }

    while (cnt--) {
      if (!oldest || this._tick === oldest.pinged) continue
      this._check(oldest)
      oldest = oldest.next
    }
  }

  _check(node) {
    node.pinged = this._tick

    const lastSeen = node.seen
    const onresponse = () => {
      this._checks--
      this._removeStaleNode(node, lastSeen)
    }
    const onerror = () => {
      this._checks--
      this._removeNode(node)
    }

    this._checks++
    this._request(
      { id: null, host: node.host, port: node.port },
      false,
      true,
      PING,
      null,
      null,
      null,
      onresponse,
      onerror
    )
  }

  _ontick() {
    const time = Date.now()

    if (time - this._lastTick > SLEEPING_INTERVAL && this.suspended === false) {
      this._onwakeup()
    } else {
      this._tick++
    }

    this._lastTick = time

    if (!this.bootstrapped || this.suspended) return

    if (this.adaptive && this.ephemeral && --this._stableTicks <= 0) {
      if (this._lastHost === this._nat.host) {
        // do not recheck the same network...
        this._stableTicks = MORE_STABLE_TICKS
      } else {
        this._updateNetworkState() // the promise returned here never fails so just ignore it
      }
    }

    if ((this._tick & 7) === 0) {
      this._pingSome()
    }

    if (
      ((this._tick & 63) === 0 && this.nodes.length < this.table.k) ||
      --this._refreshTicks <= 0
    ) {
      this.refresh()
    }

    this._downHintsSentPerTick = 0
    this.health.update()
  }

  async _updateNetworkState(onlyFirewall = false) {
    if (!this.ephemeral) return false
    if (onlyFirewall && !this.firewalled) return false

    const { host, port } = this._nat

    if (!onlyFirewall) {
      // remember what host we checked and reset the counter
      this._stableTicks = MORE_STABLE_TICKS
      this._lastHost = host
    }

    // check if we have a consistent host and port
    if (host === null || port === 0) {
      return false
    }

    const natSampler = this.firewalled ? new NatSampler() : this._nat

    // ask remote nodes to ping us on our server socket to see if we have the port open
    const firewalled = this.firewalled && (await this._checkIfFirewalled(natSampler))
    if (firewalled) return false

    this.firewalled = this.io.firewalled = false

    // incase it's called in parallel for some reason, or if our nat status somehow changed
    if (!this.ephemeral || host !== this._nat.host || port !== this._nat.port) return false
    // if the firewall probe returned a different host / non consistent port, bail as well
    if (natSampler.host !== host || natSampler.port === 0) return false

    const id = peer.id(natSampler.host, natSampler.port)

    if (!onlyFirewall) {
      this.ephemeral = this.io.ephemeral = false
    }

    if (natSampler !== this._nat) {
      const prevHost = this._nat.host
      const prevPort = this._nat.port

      this._nonePersistentSamples = []
      this._nat = natSampler

      if (prevHost !== this._nat.host || prevPort !== this._nat.port) {
        this.emit('nat-update', this._nat.host, this._nat.port)
      }
    }

    // TODO: we should make this a bit more defensive in terms of using more
    // resources to make sure that the new routing table contains as many alive nodes
    // as possible, vs blindly copying them over...

    // all good! copy over the old routing table to the new one
    if (!b4a.equals(this.table.id, id)) {
      const nodes = this.table.toArray()

      this.table = this.io.table = new Table(id)

      for (const node of nodes) {
        if (b4a.equals(node.id, id)) continue
        if (!this.table.add(node)) this.nodes.remove(node)
      }

      this.table.on('row', this._onrow)

      // we need to rebootstrap/refresh since we updated our id
      if (this.bootstrapped) this.refresh()
    }

    if (!this.ephemeral) {
      this.emit('persistent')
    }

    return true
  }

  async *_resolveBootstrapNodes() {
    for (let { host, port } of this.bootstrapNodes) {
      let doLookup = false

      if (host.indexOf('@') === -1) {
        doLookup = true
      } else {
        const [suggestedIP, fallbackHost] = host.split('@')
        try {
          await this.ping({ host: suggestedIP, port })
          host = suggestedIP
        } catch {
          host = fallbackHost
          doLookup = true
        }
      }

      if (doLookup) {
        try {
          host = UDX.isIPv4(host) ? host : (await this.udx.lookup(host, { family: 4 })).host
        } catch {
          continue
        }
      }

      yield {
        id: peer.id(host, port),
        host,
        port
      }
    }
  }

  async _addBootstrapNodes(nodes) {
    for await (const node of this._resolveBootstrapNodes()) {
      nodes.push(node)
    }
  }

  async _checkIfFirewalled(natSampler = new NatSampler()) {
    const nodes = []
    for (let node = this.nodes.latest; node && nodes.length < 5; node = node.prev) {
      nodes.push(node)
    }

    if (nodes.length < 5) await this._addBootstrapNodes(nodes)
    // if no nodes are available, including bootstrappers - bail
    if (nodes.length === 0) return true

    const hosts = new Set()
    const value = b4a.allocUnsafe(2)

    c.uint16.encode({ start: 0, end: 2, buffer: value }, this.io.serverSocket.address().port)

    // double check they actually came on the server socket...
    this.io.serverSocket.on('message', onmessage)

    const pongs = await requestAll(this, true, PING_NAT, value, nodes)

    let count = 0
    for (const res of pongs) {
      if (hosts.has(res.from.host)) {
        count++
        natSampler.add(res.to.host, res.to.port)
      }
    }

    this.io.serverSocket.removeListener('message', onmessage)

    // if we got no or very few replies, consider it a fluke
    if (count < (nodes.length >= 5 ? 3 : 1)) return true

    // check that the server socket has the same ip as the client socket
    if (natSampler.host === null || this._nat.host !== natSampler.host) return true

    // check that the local port of the server socket is the same as the remote port
    // TODO: we might want a flag to opt out of this heuristic for specific remapped port servers
    if (natSampler.port === 0 || natSampler.port !== this.io.serverSocket.address().port) {
      return true
    }

    return false

    function onmessage(_, { host }) {
      hosts.add(host)
    }
  }

  _backgroundQuery(target) {
    this._refreshTicks = REFRESH_TICKS

    const backgroundCon = Math.min(this.concurrency, Math.max(2, (this.concurrency / 8) | 0))
    const q = new Query(this, target, true, FIND_NODE, null, {
      concurrency: backgroundCon
    })

    q.on('data', () => {
      // yield to other traffic
      q.concurrency = this.io.inflight.length < 3 ? this.concurrency : backgroundCon
    })

    return q
  }

  // called by health
  _online() {
    if (this.online && !this.degraded) return
    this.online = true
    this.degraded = false
    this.emit('network-update')
  }

  // called by health
  _degraded() {
    if (this.degraded) return
    this.online = true
    this.degraded = true
    this.emit('network-update')
  }

  // called by health
  _offline() {
    if (!this.online) return
    this.online = false
    this.degraded = false
    this.emit('network-update')
  }
}

DHT.OK = 0
DHT.ERROR_UNKNOWN_COMMAND = UNKNOWN_COMMAND
DHT.ERROR_INVALID_TOKEN = INVALID_TOKEN

module.exports = DHT

function localIP(udx, family = 4) {
  let host = null

  for (const n of udx.networkInterfaces()) {
    if (n.family !== family || n.internal) continue

    // mac really likes en0, mb a better way but this shouldnt be bad anywhere so return now
    if (n.name === 'en0') return n.host

    // otherwise pick the first non internal host (let the loop continue in case we see en0)
    if (host === null) host = n.host
  }

  return host || (family === 4 ? '127.0.0.1' : '::1')
}

function parseNode(s) {
  if (typeof s === 'object') return s
  if (typeof s === 'number') return { host: '127.0.0.1', port: s }
  const [host, port] = s.split(':')
  if (!port) throw new Error('Bootstrap node format is host:port')

  return {
    host,
    port: Number(port)
  }
}

function randomBytes(n) {
  const b = b4a.alloc(n)
  sodium.randombytes_buf(b)
  return b
}

function randomOffset(n) {
  return n - ((Math.random() * 0.5 * n) | 0)
}

function requestAll(dht, internal, command, value, nodes) {
  let missing = nodes.length
  const replies = []

  return new Promise((resolve) => {
    for (const node of nodes) {
      const req = dht._request(
        node,
        false,
        internal,
        command,
        null,
        value,
        null,
        onsuccess,
        onerror
      )
      if (!req) return resolve(replies)
    }

    function onsuccess(res) {
      replies.push(res)
      if (--missing === 0) resolve(replies)
    }

    function onerror() {
      if (--missing === 0) resolve(replies)
    }
  })
}

function noop() {}
exports.PING = 0
exports.PING_NAT = 1
exports.FIND_NODE = 2
exports.DOWN_HINT = 3
exports.DELAYED_PING = 4
module.exports = class DHTError extends Error {
  constructor(msg, code, fn = DHTError) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'DHTError'
  }

  static UNKNOWN_COMMAND = 1
  static INVALID_TOKEN = 2

  static REQUEST_TIMEOUT(msg = 'Request timed out') {
    return new DHTError(msg, 'REQUEST_TIMEOUT', DHTError.REQUEST_TIMEOUT)
  }

  static REQUEST_DESTROYED(msg = 'Request destroyed') {
    return new DHTError(msg, 'REQUEST_DESTROYED', DHTError.REQUEST_DESTROYED)
  }

  static IO_SUSPENDED(msg = 'I/O suspended') {
    return new DHTError(msg, 'IO_SUSPENDED', DHTError.IO_SUSPENDED)
  }
}
const MAX_HEALTH_WINDOW = 4
const OFFLINE_THRESHOLD = 2
const IDLE_THRESHOLD = 4
const DEGRADED_TIMEOUT_RATE_THRESHOLD = 0.5

module.exports = class NetworkHealth {
  constructor(dht) {
    this._dht = dht
    this._window = []
    this._head = -1
    this._offlineTicks = 0
    this._degradedTicks = 0
    this._healthyTicks = 0
    this.online = true
    this.degraded = false
  }

  get oldest() {
    return this._window[this._tail]
  }

  get previous() {
    return this._window[(this._head - 1 + MAX_HEALTH_WINDOW) % MAX_HEALTH_WINDOW]
  }

  get newest() {
    return this._window[this._head]
  }

  get responses() {
    if (!this.newest || !this.previous) return 0
    return this.newest.responses - this.previous.responses
  }

  get timeouts() {
    if (!this.newest || !this.previous) return 0
    return this.newest.timeouts - this.previous.timeouts
  }

  get timeoutsRate() {
    if (this.timeouts === 0) return 0
    return this.timeouts / (this.responses + this.timeouts)
  }

  get cold() {
    return this._window.length < MAX_HEALTH_WINDOW
  }

  get idle() {
    return this.responses + this.timeouts < IDLE_THRESHOLD
  }

  get stats() {
    return {
      online: this.online,
      degraded: this.degraded,
      cold: this.cold,
      idle: this.idle,
      responses: this.responses,
      timeouts: this.timeouts,
      timeoutsRate: this.timeoutsRate
    }
  }

  get _tail() {
    return (this._head + 1) % MAX_HEALTH_WINDOW
  }

  reset() {
    this._window = []
    this._head = -1
    this._offlineTicks = 0
    this._degradedTicks = 0
    this._healthyTicks = 0
    this.online = true
    this.degraded = false
    this._dht._online()
  }

  update() {
    // update counters before dropping oldest
    if (this.oldest?.degraded) this._degradedTicks--
    else if (this.oldest?.degraded === false) this._healthyTicks--

    // move window
    this._head = this._tail
    this._window[this._head] = {
      responses: this._dht.stats.requests.responses,
      timeouts: this._dht.stats.requests.timeouts
    }

    // skip state changes
    if (this.cold || this.idle) return

    // update newest
    this.newest.offline = this.responses === 0
    this.newest.degraded =
      !this.newest.offline && this.timeoutsRate > DEGRADED_TIMEOUT_RATE_THRESHOLD

    // update counters
    if (this.newest.offline) this._offlineTicks++
    else {
      this._offlineTicks = 0
      if (this.newest.degraded) this._degradedTicks++
      else this._healthyTicks++
    }

    // check online/offline
    if (!this.newest.offline) this.online = true
    else if (this._offlineTicks >= OFFLINE_THRESHOLD) this.online = false

    // check degraded
    if (!this.online || this._healthyTicks === MAX_HEALTH_WINDOW) this.degraded = false
    else if (this._degradedTicks === MAX_HEALTH_WINDOW) this.degraded = true

    // fire events
    if (this.online && !this.degraded) this._dht._online()
    else if (this.degraded) this._dht._degraded()
    else this._dht._offline()
  }
}
const FIFO = require('fast-fifo')
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const b4a = require('b4a')
const AdaptiveTimeout = require('adaptive-timeout')
const peer = require('./peer')
const { INVALID_TOKEN, REQUEST_TIMEOUT, REQUEST_DESTROYED, IO_SUSPENDED } = require('./errors')

const VERSION = 0b11
const RESPONSE_ID = (0b0001 << 4) | VERSION
const REQUEST_ID = (0b0000 << 4) | VERSION
const EMPTY_ARRAY = []
const MAX_WINDOW = 80

module.exports = class IO {
  constructor(
    table,
    udx,
    {
      maxWindow = MAX_WINDOW,
      port = 0,
      host = '0.0.0.0',
      anyPort = true,
      firewalled = true,
      onrequest,
      onresponse = noop,
      ontimeout = noop,
      adaptiveTimeout
    } = {}
  ) {
    this.table = table
    this.udx = udx
    this.inflight = []
    this.clientSocket = null
    this.serverSocket = null
    this.firewalled = firewalled !== false
    this.ephemeral = true
    this.congestion = new CongestionWindow(maxWindow)
    this.networkInterfaces = udx.watchNetworkInterfaces()
    this.suspended = false

    this.stats = {
      requests: {
        active: 0,
        total: 0,
        responses: 0,
        timeouts: 0,
        retries: 0
      },
      commands: [
        { tx: 0, rx: 0 }, // tx = transmitted, rx = received
        { tx: 0, rx: 0 },
        { tx: 0, rx: 0 },
        { tx: 0, rx: 0 }
      ]
    }

    this.onrequest = onrequest
    this.onresponse = onresponse
    this.ontimeout = ontimeout

    this._pending = new FIFO()
    this._rotateSecrets = 10
    this._tid = (Math.random() * 65536) | 0
    this._secrets = null
    this._drainInterval = null
    this._destroying = null
    this._binding = null

    // port can be a number or a range [start, to]
    this.portRange = port.length ? port : port === 0 ? [0, 0] : [port, port + 5]

    this._host = host
    this._anyPort = anyPort !== false
    this._boundServerPort = 0
    this._boundClientPort = 0

    this._adt = adaptiveTimeout ? new AdaptiveTimeout(adaptiveTimeout) : null
  }

  static DEFAULT_MAX_WINDOW = MAX_WINDOW

  onmessage(socket, buffer, { host, port }) {
    if (buffer.byteLength < 2 || !(port > 0 && port < 65536) || this.suspended === true) return

    const from = { id: null, host, port }
    const state = { start: 1, end: buffer.byteLength, buffer }
    const expectedSocket = this.firewalled ? this.clientSocket : this.serverSocket
    const external = socket !== expectedSocket

    if (buffer[0] === REQUEST_ID) {
      const req = Request.decode(this, socket, from, state)
      if (req === null) return
      if (
        req.token !== null &&
        !b4a.equals(req.token, this.token(req.from, 1)) &&
        !b4a.equals(req.token, this.token(req.from, 0))
      ) {
        req.error(INVALID_TOKEN, { token: true })
        return
      }
      this.onrequest(req, external)
      return
    }

    if (buffer[0] === RESPONSE_ID) {
      const res = decodeReply(from, state)
      if (res === null) return

      for (let i = 0; i < this.inflight.length; i++) {
        const req = this.inflight[i]
        if (req.tid !== res.tid) continue

        res.rtt = Date.now() - req._timestamp

        if (this._adt && req.sent <= 2) {
          this._adt.put(`${req.to.host}:${req.to.port}`, res.rtt)
        }

        if (i === this.inflight.length - 1) this.inflight.pop()
        else this.inflight[i] = this.inflight.pop()

        if (req.session) req.session._detach(req)

        // TODO: Auto retry here if errors.INVALID_TOKEN is returned?

        if (req._timeout) {
          clearTimeout(req._timeout)
          req._timeout = null
        }

        this.congestion.recv()

        if (req.internal && req.command < this.stats.commands.length) {
          this.stats.commands[req.command].rx++
        }

        this.stats.requests.active--
        this.stats.requests.responses++

        this.onresponse(res, external)
        req.onresponse(res, req)
        break
      }
    }
  }

  token(addr, i) {
    if (this._secrets === null) {
      const buf = b4a.alloc(64)
      this._secrets = [buf.subarray(0, 32), buf.subarray(32, 64)]
      sodium.randombytes_buf(this._secrets[0])
      sodium.randombytes_buf(this._secrets[1])
    }

    const token = b4a.allocUnsafe(32)
    sodium.crypto_generichash(token, b4a.from(addr.host), this._secrets[i])
    return token
  }

  async destroy() {
    if (this._destroying) return this._destroying
    this._destroying = this._destroy()
    return this._destroying
  }

  async _destroy() {
    // simplifies timing to await the bind here also, although it might be unneeded
    await this.bind()
    await this._clear(false)
  }

  async _clear(suspended) {
    if (this._drainInterval) {
      clearInterval(this._drainInterval)
      this._drainInterval = null
    }

    while (this.inflight.length) {
      const req = this.inflight.pop()
      if (req._timeout) clearTimeout(req._timeout)
      req._timeout = null
      req.destroyed = true

      if (req.session) req.session._detach(req)

      this.congestion.recv()
      this.stats.requests.active--

      req.onerror(suspended ? IO_SUSPENDED() : REQUEST_DESTROYED(), req)
    }

    await Promise.allSettled([this.serverSocket.close(), this.clientSocket.close()])

    this.networkInterfaces.destroy()
  }

  async suspend() {
    this.suspended = true
    await this._clear(true)

    this.congestion.clear()

    if (this._drainInterval) {
      clearInterval(this._drainInterval)
      this._drainInterval = null
    }
  }

  async _rebind(binding) {
    if (binding) await binding
    if (this._destroying) return this._destroying
    await this._bindSockets()
    this.networkInterfaces = this.udx.watchNetworkInterfaces()
  }

  resume() {
    this.suspended = false
    const binding = this._binding
    this._binding = this._rebind(binding)
    return this._binding
  }

  bind() {
    if (this._binding) return this._binding
    this._binding = this._bindSockets()
    return this._binding
  }

  async _bindSockets() {
    const serverSocket = this.udx.createSocket()

    const candidatePorts = []

    // Retrying previous port always has precedence
    if (this._boundServerPort) candidatePorts.push(this._boundServerPort)

    for (let i = this.portRange[0]; i < this.portRange[1]; i++) candidatePorts.push(i)

    for (const port of candidatePorts) {
      if (serverSocket.bound) break

      try {
        serverSocket.bind(port, this._host)
      } catch (err) {
        if (!this._anyPort) {
          await serverSocket.close()
          throw err
        }
      }
    }

    if (!serverSocket.bound) {
      try {
        serverSocket.bind(0, this._host)
      } catch (err) {
        await serverSocket.close()
        throw err
      }
    }

    const clientSocket = this.udx.createSocket()

    try {
      clientSocket.bind(this._boundClientPort || 0, this._host)
    } catch {
      try {
        clientSocket.bind(0, this._host)
      } catch (err) {
        await serverSocket.close()
        await clientSocket.close()
        throw err
      }
    }

    this._boundServerPort = serverSocket.address().port
    this._boundClientPort = clientSocket.address().port

    this.clientSocket = clientSocket
    this.serverSocket = serverSocket

    this.serverSocket.on('message', this.onmessage.bind(this, this.serverSocket))
    this.clientSocket.on('message', this.onmessage.bind(this, this.clientSocket))

    if (this._drainInterval === null) {
      this._drainInterval = setInterval(this._drain.bind(this), 750)
      if (this._drainInterval.unref) this._drainInterval.unref()
    }

    for (const req of this.inflight) {
      if (!req.socket) req.socket = this.firewalled ? this.clientSocket : this.serverSocket
      req.sent = 0
      req.send(false)
    }
  }

  _drain() {
    if (this._secrets !== null && --this._rotateSecrets === 0) {
      this._rotateSecrets = 10
      const tmp = this._secrets[0]
      this._secrets[0] = this._secrets[1]
      this._secrets[1] = tmp
      sodium.crypto_generichash(tmp, tmp)
    }

    this.congestion.drain()

    while (!this.congestion.isFull()) {
      const p = this._pending.shift()
      if (p === undefined) return
      p._sendNow()
    }
  }

  createRequest(to, token, internal, command, target, value, session, ttl) {
    if (this._destroying !== null) return null

    if (this._tid === 65536) this._tid = 0

    const tid = this._tid++
    const socket = this.firewalled ? this.clientSocket : this.serverSocket

    const req = new Request(
      this,
      socket,
      tid,
      null,
      to,
      token,
      internal,
      command,
      target,
      value,
      session,
      ttl || 0
    )
    this.inflight.push(req)
    if (session) session._attach(req)

    if (internal && command < this.stats.commands.length) {
      this.stats.commands[command].tx++
    }

    this.stats.requests.active++
    this.stats.requests.total++

    return req
  }
}

class Request {
  constructor(io, socket, tid, from, to, token, internal, command, target, value, session, ttl) {
    this.socket = socket
    this.tid = tid
    this.from = from
    this.to = to
    this.token = token
    this.command = command
    this.target = target
    this.value = value
    this.internal = internal
    this.session = session
    this.ttl = ttl
    this.index = -1
    this.sent = 0
    this.retries = 3
    this.destroyed = false
    this.timeout = 0

    this.oncycle = noop
    this.onerror = noop
    this.onresponse = noop

    this._buffer = null
    this._io = io
    this._timeout = null
    this._timestamp = Date.now()
  }

  static decode(io, socket, from, state) {
    try {
      const flags = c.uint.decode(state)
      const tid = c.uint16.decode(state)
      const to = peer.ipv4.decode(state)
      const id = flags & 1 ? c.fixed32.decode(state) : null
      const token = flags & 2 ? c.fixed32.decode(state) : null
      const internal = (flags & 4) !== 0
      const command = c.uint.decode(state)
      const target = flags & 8 ? c.fixed32.decode(state) : null
      const value = flags & 16 ? c.buffer.decode(state) : null

      if (id !== null) from.id = validateId(id, from)

      return new Request(
        io,
        socket,
        tid,
        from,
        to,
        token,
        internal,
        command,
        target,
        value,
        null,
        0
      )
    } catch {
      return null
    }
  }

  reply(value, opts = {}) {
    const socket = opts.socket || this.socket
    const to = opts.to || this.from
    this._sendReply(0, value || null, opts.token !== false, opts.closerNodes !== false, to, socket)
  }

  error(code, opts = {}) {
    const socket = opts.socket || this.socket
    const to = opts.to || this.from
    this._sendReply(code, null, opts.token === true, opts.closerNodes !== false, to, socket)
  }

  relay(value, to, opts) {
    const socket = (opts && opts.socket) || this.socket
    const buffer = this._encodeRequest(null, value, to, socket)
    socket.trySend(buffer, to.port, to.host, this.ttl)
  }

  send(force = false) {
    if (this.destroyed) return

    if (this.socket === null) return
    if (this._buffer === null) {
      this._buffer = this._encodeRequest(this.token, this.value, this.to, this.socket)
    }

    if (!force && this._io.congestion.isFull()) {
      this._io._pending.push(this)
      return
    }

    this._sendNow()
  }

  sendReply(error, value, token, hasCloserNodes) {
    this._sendReply(error, value, token, hasCloserNodes, this.from, this.socket, null)
  }

  _sendNow() {
    if (this.destroyed) return
    this.sent++
    this._io.congestion.send()
    this.socket.trySend(this._buffer, this.to.port, this.to.host, this.ttl)
    if (this._timeout) clearTimeout(this._timeout)
    const value =
      this.timeout || this._io._adt?.get(`${this.to.host}:${this.to.port}`, this.sent) || 1000
    this._timeout = setTimeout(oncycle, value, this)
  }

  destroy(err) {
    if (this.destroyed) return
    this.destroyed = true

    if (this._timeout) {
      clearTimeout(this._timeout)
      this._timeout = null
    }

    const i = this._io.inflight.indexOf(this)
    if (i === -1) return

    if (i === this._io.inflight.length - 1) this._io.inflight.pop()
    else this._io.inflight[i] = this._io.inflight.pop()

    if (this.session) this.session._detach(this)

    this._io.stats.requests.active--
    this._io.congestion.recv()

    this.onerror(err || REQUEST_DESTROYED(), this)
  }

  _sendReply(error, value, token, hasCloserNodes, from, socket) {
    if (socket === null || this.destroyed) return

    const id = this._io.ephemeral === false && socket === this._io.serverSocket
    const closerNodes =
      this.target !== null && hasCloserNodes ? this._io.table.closest(this.target) : EMPTY_ARRAY
    const state = { start: 0, end: 1 + 1 + 6 + 2, buffer: null } // (type | version) + flags + to + tid

    if (id) state.end += 32
    if (token) state.end += 32
    if (closerNodes.length > 0) peer.ipv4Array.preencode(state, closerNodes)
    if (error > 0) c.uint.preencode(state, error)
    if (value) c.buffer.preencode(state, value)

    state.buffer = b4a.allocUnsafe(state.end)
    state.buffer[state.start++] = RESPONSE_ID
    state.buffer[state.start++] =
      (id ? 1 : 0) |
      (token ? 2 : 0) |
      (closerNodes.length > 0 ? 4 : 0) |
      (error > 0 ? 8 : 0) |
      (value ? 16 : 0)

    c.uint16.encode(state, this.tid)
    peer.ipv4.encode(state, from)

    if (id) c.fixed32.encode(state, this._io.table.id)
    if (token) c.fixed32.encode(state, this._io.token(from, 1))
    if (closerNodes.length > 0) peer.ipv4Array.encode(state, closerNodes)
    if (error > 0) c.uint.encode(state, error)
    if (value) c.buffer.encode(state, value)

    socket.trySend(state.buffer, from.port, from.host, this.ttl)
  }

  _encodeRequest(token, value, to, socket) {
    const id = this._io.ephemeral === false && socket === this._io.serverSocket
    const state = { start: 0, end: 1 + 1 + 6 + 2, buffer: null } // (type | version) + flags + to + tid

    if (id) state.end += 32
    if (token) state.end += 32

    c.uint.preencode(state, this.command)

    if (this.target) state.end += 32
    if (value) c.buffer.preencode(state, value)

    state.buffer = b4a.allocUnsafe(state.end)
    state.buffer[state.start++] = REQUEST_ID
    state.buffer[state.start++] =
      (id ? 1 : 0) |
      (token ? 2 : 0) |
      (this.internal ? 4 : 0) |
      (this.target ? 8 : 0) |
      (value ? 16 : 0)

    c.uint16.encode(state, this.tid)
    peer.ipv4.encode(state, to)

    if (id) c.fixed32.encode(state, this._io.table.id)
    if (token) c.fixed32.encode(state, token)

    c.uint.encode(state, this.command)

    if (this.target) c.fixed32.encode(state, this.target)
    if (value) c.buffer.encode(state, value)

    return state.buffer
  }
}

class CongestionWindow {
  constructor(maxWindow) {
    this._i = 0
    this._total = 0
    this._window = [0, 0, 0, 0]
    this._maxWindow = maxWindow
  }

  clear() {
    this._i = 0
    this._total = 0
    this._window = [0, 0, 0, 0]
  }

  isFull() {
    return this._total >= 2 * this._maxWindow || this._window[this._i] >= this._maxWindow
  }

  recv() {
    if (this._window[this._i] > 0) {
      this._window[this._i]--
      this._total--
    }
  }

  send() {
    this._total++
    this._window[this._i]++
  }

  drain() {
    this._i = (this._i + 1) & 3
    this._total -= this._window[this._i]
    this._window[this._i] = 0 // clear oldest
  }
}

function noop() {}

function oncycle(req) {
  req._timeout = null
  req.oncycle(req)
  if (req.sent > req.retries) {
    req._io.stats.requests.timeouts++
    req.destroy(REQUEST_TIMEOUT())
    req._io.ontimeout(req)
  } else {
    req._io.stats.requests.retries++
    req.send()
  }
}

function decodeReply(from, state) {
  try {
    const flags = c.uint.decode(state)
    const tid = c.uint16.decode(state)
    const to = peer.ipv4.decode(state)
    const id = flags & 1 ? c.fixed32.decode(state) : null
    const token = flags & 2 ? c.fixed32.decode(state) : null
    const closerNodes = flags & 4 ? peer.ipv4Array.decode(state) : null
    const error = flags & 8 ? c.uint.decode(state) : 0
    const value = flags & 16 ? c.buffer.decode(state) : null

    if (id !== null) from.id = validateId(id, from)

    return { tid, rtt: 0, from, to, token, closerNodes, error, value }
  } catch {
    return null
  }
}

function validateId(id, from) {
  const expected = peer.id(from.host, from.port)
  return b4a.equals(expected, id) ? expected : null
}
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const b4a = require('b4a')

const ipv4 = {
  ...c.ipv4Address,
  decode(state) {
    const ip = c.ipv4Address.decode(state)
    return {
      id: null, // populated by the callee
      host: ip.host,
      port: ip.port
    }
  }
}

module.exports = { id, ipv4, ipv4Array: c.array(ipv4) }

function id(host, port, out = b4a.allocUnsafeSlow(32)) {
  const addr = out.subarray(0, 6)
  ipv4.encode({ start: 0, end: 6, buffer: addr }, { host, port })
  sodium.crypto_generichash(out, addr)
  return out
}
const { Readable, getStreamError } = require('streamx')
const b4a = require('b4a')
const peer = require('./peer')
const { DOWN_HINT } = require('./commands')

const DONE = []
const DOWN = []

module.exports = class Query extends Readable {
  constructor(dht, target, internal, command, value, opts = {}) {
    super()

    dht.stats.queries.total++
    dht.stats.queries.active++

    this.force = !!opts.force
    this.dht = dht
    this.k = this.dht.table.k
    this.target = target
    this.internal = internal
    this.command = command
    this.value = value
    this.errors = 0
    this.successes = 0
    this.concurrency = opts.concurrency || this.dht.concurrency
    this.inflight = 0
    this.map = opts.map || defaultMap
    this.retries =
      opts.retries === 0 ? 0 : opts.retries || (this.internal && command === DOWN_HINT ? 3 : 5)
    this.closestReplies = []

    this._slow = 0
    this._slowdown = false
    this._seen = new Map()
    this._pending = []
    this._fromTable = false
    this._commit = opts.commit === true ? autoCommit : opts.commit || null
    this._commiting = false
    this._session = opts.session || dht.session()
    this._autoDestroySession = !opts.session
    this._onlyClosestNodes = false

    this._onvisitbound = this._onvisit.bind(this)
    this._onerrorbound = this._onerror.bind(this)
    this._oncyclebound = this._oncycle.bind(this)

    const nodes = opts.nodes || opts.closestNodes
    const replies = opts.replies || opts.closestReplies

    // add them reverse as we pop below
    if (nodes) {
      for (let i = nodes.length - 1; i >= 0; i--) {
        const node = nodes[i]
        this._addPending(
          {
            id: node.id || peer.id(node.host, node.port),
            host: node.host,
            port: node.port
          },
          null
        )
      }
    } else if (replies) {
      for (let i = replies.length - 1; i >= 0; i--) {
        this._addPending(replies[i].from, null)
      }
    }

    if (opts.onlyClosestNodes) this._onlyClosestNodes = true
  }

  get closestNodes() {
    const nodes = new Array(this.closestReplies.length)

    for (let i = 0; i < nodes.length; i++) {
      nodes[i] = this.closestReplies[i].from
    }

    return nodes
  }

  finished() {
    return new Promise((resolve, reject) => {
      if (this.destroyed) {
        const error = getStreamError(this)
        if (error) reject(error)
        else resolve()
        return
      }

      const self = this
      let error = null

      this.resume()
      this.on('error', onerror)
      this.on('close', onclose)

      function onclose() {
        self.removeListener('error', onerror)
        self.removeListener('close', onclose)
        if (error) reject(error)
        else resolve()
      }

      function onerror(err) {
        error = err
      }
    })
  }

  _addFromTable() {
    if (this._pending.length >= this.k) return
    this._fromTable = true

    const closest = this.dht.table.closest(this.target, this.k - this._pending.length)

    for (const node of closest) {
      this._addPending({ id: node.id, host: node.host, port: node.port }, null)
    }
  }

  async _open(cb) {
    this._addFromTable()
    if (this._pending.length >= this.k) return cb(null)

    for await (const node of this.dht._resolveBootstrapNodes()) {
      this._addPending(node, null)
    }

    cb(null)
  }

  _isCloser(id) {
    return (
      this.closestReplies.length < this.k ||
      this._compare(id, this.closestReplies[this.closestReplies.length - 1].from.id) < 0
    )
  }

  _addPending(node, ref) {
    if (this._onlyClosestNodes) return false

    const addr = node.host + ':' + node.port
    const refs = this._seen.get(addr)
    const isCloser = this._isCloser(node.id)

    if (refs === DONE) {
      return isCloser
    }

    if (refs === DOWN) {
      if (ref) this._downHint(ref, node)
      return isCloser
    }

    if (refs) {
      if (ref !== null) refs.push(ref)
      return isCloser
    }

    if (!isCloser) {
      return false
    }

    this._seen.set(addr, ref === null ? [] : [ref])
    this._pending.push(node)

    return true
  }

  _read(cb) {
    this._readMore()
    cb(null)
  }

  _readMore() {
    if (this.destroying || this._commiting) return

    const concurrency = (this._slowdown ? 3 : this.concurrency) + this._slow

    while (this.inflight < concurrency && this._pending.length > 0) {
      const next = this._pending.pop()
      if (next && next.id && !this._isCloser(next.id)) continue
      this._visit(next)
    }

    // if reusing closest nodes, slow down after the first readMore tick to allow
    // the closest node a chance to reply before going broad to question more
    if (!this._fromTable && this.successes === 0 && this.errors === 0) {
      this._slowdown = true
    }

    if (this._pending.length > 0) return

    // if no inflight OR all the queries we are waiting on are marked as slow and we have a full result.
    if (
      this.inflight === 0 ||
      (this._slow === this.inflight && this.closestReplies.length >= this.k)
    ) {
      // if more than 3/4 failed and we only used cached nodes, try again from the routing table
      if (!this._fromTable && this.successes < this.k / 4) {
        this._addFromTable()
        this._readMore()
        return
      }

      this._flush()
    }
  }

  _flush() {
    if (this._commiting) return
    this._commiting = true

    if (this._commit === null) {
      this.push(null)
      return
    }

    const p = []
    for (const m of this.closestReplies) p.push(this._commit(m, this.dht, this))
    this._endAfterCommit(p)
  }

  _endAfterCommit(ps) {
    if (!ps.length) {
      this.destroy(new Error('Too few nodes responded'))
      return
    }

    const self = this

    let pending = ps.length
    let success = 0

    for (const p of ps) p.then(ondone, onerror)

    function ondone() {
      success++
      if (--pending === 0) self.push(null)
    }

    function onerror(err) {
      if (--pending > 0) return
      if (success) self.push(null)
      else self.destroy(err)
    }
  }

  _dec(req) {
    if (req.oncycle === noop) {
      this._slow--
    } else {
      req.oncycle = noop
    }
    this.inflight--
  }

  _onvisit(m, req) {
    this._dec(req)

    const addr = req.to.host + ':' + req.to.port
    this._seen.set(addr, DONE)

    if (this._commiting) return

    if (m.error === 0) this.successes++
    else this.errors++

    if (m.error === 0 && m.from.id !== null && this._isCloser(m.from.id)) this._pushClosest(m)

    if (m.closerNodes !== null) {
      for (const node of m.closerNodes) {
        node.id = peer.id(node.host, node.port)
        if (this.dht._filterNode !== null && !this.dht._filterNode(node)) continue
        if (b4a.equals(node.id, this.dht.table.id)) continue
        // TODO: we could continue here instead of breaking to ensure that one of the nodes in the closer list
        // is later marked as DOWN that we gossip that back
        if (!this._addPending(node, m.from)) break
      }
    }

    if (!this._fromTable && this.successes + this.errors >= this.concurrency) {
      this._slowdown = false
    }

    if (m.error !== 0) {
      this._readMore()
      return
    }

    const data = this.map(m)
    if (!data || this.push(data) !== false) {
      this._readMore()
    }
  }

  _onerror(err, req) {
    const addr = req.to.host + ':' + req.to.port
    const refs = this._seen.get(addr)

    if (err.code === 'REQUEST_TIMEOUT') {
      this._seen.set(addr, DOWN)
      for (const node of refs) this._downHint(node, req.to)
    }

    this._dec(req)
    this.errors++
    this._readMore()
  }

  _oncycle(req) {
    req.oncycle = noop
    this._slow++
    this._readMore()
  }

  _downHint(node, down) {
    // Check rate limit
    if (
      this.dht._downHintsRateLimit !== -1 &&
      this.dht._downHintsSentPerTick >= this.dht._downHintsRateLimit
    ) {
      return null
    }

    this.dht._downHintsSentPerTick++

    const state = { start: 0, end: 6, buffer: b4a.allocUnsafe(6) }
    peer.ipv4.encode(state, down)
    this.dht._request(node, false, true, DOWN_HINT, null, state.buffer, this._session, noop, noop)
  }

  _pushClosest(m) {
    this.closestReplies.push(m)
    for (let i = this.closestReplies.length - 2; i >= 0; i--) {
      const prev = this.closestReplies[i]
      const cmp = this._compare(prev.from.id, m.from.id)
      // if sorted, done!
      if (cmp < 0) break
      // if dup, splice it out (rare)
      if (cmp === 0) {
        this.closestReplies.splice(i + 1, 1)
        break
      }
      // swap and continue down
      this.closestReplies[i + 1] = prev
      this.closestReplies[i] = m
    }
    if (this.closestReplies.length > this.k) this.closestReplies.pop()
  }

  _compare(a, b) {
    for (let i = 0; i < a.length; i++) {
      if (a[i] === b[i]) continue
      const t = this.target[i]
      return (t ^ a[i]) - (t ^ b[i])
    }
    return 0
  }

  _visit(to) {
    this.inflight++

    const req = this.dht._request(
      to,
      this.force,
      this.internal,
      this.command,
      this.target,
      this.value,
      this._session,
      this._onvisitbound,
      this._onerrorbound
    )
    if (req === null) {
      this.destroy(new Error('Node was destroyed'))
      return
    }
    req.retries = this.retries
    req.oncycle = this._oncyclebound
    if (this.force) req.retries = 0
  }

  _destroy(cb) {
    this.dht.stats.queries.active--
    if (this._autoDestroySession) this._session.destroy()
    cb(null)
  }
}

function autoCommit(reply, dht, query) {
  if (!reply.token) return Promise.reject(new Error('No token received for closest node'))
  return dht.request(
    {
      token: reply.token,
      target: query.target,
      command: query.command,
      value: query.value
    },
    reply.from
  )
}

function defaultMap(m) {
  return m
}

function noop() {}
module.exports = class Session {
  constructor(dht) {
    this.dht = dht
    this.inflight = []
  }

  _attach(req) {
    req.index = this.inflight.push(req) - 1
  }

  _detach(req) {
    const i = req.index
    if (i === -1) return
    req.index = -1

    if (i === this.inflight.length - 1) this.inflight.pop()
    else {
      const req = (this.inflight[i] = this.inflight.pop())
      req.index = i
    }
  }

  query({ target, command, value }, opts = {}) {
    return this.dht.query({ target, command, value }, { ...opts, session: this })
  }

  request({ token, command, target, value }, { host, port }, opts = {}) {
    return this.dht.request(
      { token, command, target, value },
      { host, port },
      { ...opts, session: this }
    )
  }

  ping({ host, port }, opts = {}) {
    return this.dht.ping({ host, port }, { ...opts, session: this })
  }

  destroy(err) {
    while (this.inflight.length) {
      const req = this.inflight[0]
      // prevent destroyed requests from contributing to congestion counts
      this.dht.io.congestion.recv()
      req.destroy(err)
    }
  }
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "dht-rpc",
  "version": "6.27.0",
  "description": "Make RPC calls over a Kademlia based DHT",
  "main": "index.js",
  "files": [
    "index.js",
    "lib/*.js"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "dependencies": {
    "adaptive-timeout": "^1.0.1",
    "b4a": "^1.6.1",
    "bare-events": "^2.2.0",
    "compact-encoding": "^3.0.0",
    "compact-encoding-net": "^1.2.0",
    "fast-fifo": "^1.1.0",
    "kademlia-routing-table": "^1.0.1",
    "nat-sampler": "^1.0.1",
    "sodium-universal": "^5.0.0",
    "streamx": "^2.13.2",
    "time-ordered-set": "^2.0.0",
    "udx-native": "^1.5.3"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "test-suspend": "^1.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "test": "npm run test:node && npm run test:bare",
    "test:bare": "brittle-bare --coverage test.js",
    "lint": "prettier --check . && lunte",
    "test:node": "brittle-node --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/dht-rpc.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/dht-rpc/issues"
  },
  "homepage": "https://github.com/holepunchto/dht-rpc#"
}
module.exports = require('bare-events')
{
  "name": "events-universal",
  "version": "1.0.1",
  "description": "Universal wrapper for the Node.js events module",
  "exports": {
    "./package": "./package.json",
    ".": {
      "bare": "./bare.js",
      "react-native": "./react-native.js",
      "default": "./default.js"
    }
  },
  "files": [
    "index.js",
    "default.js",
    "bare.js",
    "react-native.js"
  ],
  "scripts": {
    "test": "prettier . --check"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/events-universal.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/events-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/events-universal#readme",
  "dependencies": {
    "bare-events": "^2.7.0"
  },
  "devDependencies": {
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^1.0.0"
  }
}
module.exports = class FixedFIFO {
  constructor (hwm) {
    if (!(hwm > 0) || ((hwm - 1) & hwm) !== 0) throw new Error('Max size for a FixedFIFO should be a power of two')
    this.buffer = new Array(hwm)
    this.mask = hwm - 1
    this.top = 0
    this.btm = 0
    this.next = null
  }

  clear () {
    this.top = this.btm = 0
    this.next = null
    this.buffer.fill(undefined)
  }

  push (data) {
    if (this.buffer[this.top] !== undefined) return false
    this.buffer[this.top] = data
    this.top = (this.top + 1) & this.mask
    return true
  }

  shift () {
    const last = this.buffer[this.btm]
    if (last === undefined) return undefined
    this.buffer[this.btm] = undefined
    this.btm = (this.btm + 1) & this.mask
    return last
  }

  peek () {
    return this.buffer[this.btm]
  }

  isEmpty () {
    return this.buffer[this.btm] === undefined
  }
}
const FixedFIFO = require('./fixed-size')

module.exports = class FastFIFO {
  constructor (hwm) {
    this.hwm = hwm || 16
    this.head = new FixedFIFO(this.hwm)
    this.tail = this.head
    this.length = 0
  }

  clear () {
    this.head = this.tail
    this.head.clear()
    this.length = 0
  }

  push (val) {
    this.length++
    if (!this.head.push(val)) {
      const prev = this.head
      this.head = prev.next = new FixedFIFO(2 * this.head.buffer.length)
      this.head.push(val)
    }
  }

  shift () {
    if (this.length !== 0) this.length--
    const val = this.tail.shift()
    if (val === undefined && this.tail.next) {
      const next = this.tail.next
      this.tail.next = null
      this.tail = next
      return this.tail.shift()
    }

    return val
  }

  peek () {
    const val = this.tail.peek()
    if (val === undefined && this.tail.next) return this.tail.next.peek()
    return val
  }

  isEmpty () {
    return this.length === 0
  }
}
{
  "name": "fast-fifo",
  "version": "1.3.2",
  "description": "A fast fifo implementation similar to the one powering nextTick in Node.js core",
  "main": "index.js",
  "files": [
    "./index.js",
    "./fixed-size.js"
  ],
  "dependencies": {},
  "devDependencies": {
    "standard": "^17.1.0",
    "brittle": "^3.3.2"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/fast-fifo.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/fast-fifo/issues"
  },
  "homepage": "https://github.com/mafintosh/fast-fifo"
}
/**
 * hyper-overlay — content-addressed P2P file distribution over Protomux.
 *
 * The canonical bytes are REAL FILES ON DISK; the overlay stores only
 * metadata + chunk maps (Hyperbee), so there is no blob-storage balloon.
 * Files are chunked with FastCDC, fetched multi-source (torrent-style),
 * hash-verified incrementally, and written straight to the requester's disk.
 *
 * Main entry point: `HyperOverlay` (also the default export). The submodules
 * are available as subpath exports (`hyper-overlay/chunker`, …) for consumers
 * that only need a slice of the stack.
 *
 * Runs on Bare. The pure modules — chunker, messages, chunk-scheduler,
 * file-index, sync-engine — also run on Node.
 *
 * 0.3.0 adopts the hardened engine from ok/hyper-overlay-v3 (journaled resume,
 * wire paging, index GC, prepareForServe) while KEEPING our v2 architecture on
 * top: our single-flight backpressure discipline in the serve loop, our
 * getIndexMeta/putIndexMeta fast-boot, and the tree/pointer/ignore/manifest
 * modules Ok's fork dropped (pgh / hyper-deploy / pear-git-v3 depend on them).
 */

export { HyperOverlay, HyperOverlay as default } from './lib/overlay.js'
export { OverlayProtocol } from './lib/protocol.js'
export {
  TransferManager,
  PARTIAL_SUFFIX,
  partialPathFor,
  journalNameFor,
  cleanupOrphanedJournals
} from './lib/transfer.js'
export { ChunkScheduler } from './lib/chunk-scheduler.js'
export { FileIndex, CONTENT_REGISTER_PREFIX } from './lib/file-index.js'
export { SyncEngine, STRATEGIES } from './lib/sync-engine.js'
export {
  chunk,
  chunkStream,
  hashChunk,
  createStreamingHasher,
  selectTier,
  getTierParams,
  TIERS,
  MIN_SIZE,
  AVG_SIZE,
  MAX_SIZE
} from './lib/chunker.js'
export * as messages from './lib/messages.js'

// Our kept superset — dropped by ok/hyper-overlay-v3, retained here because
// pgh (tree/pointer/ignore), hyper-deploy (tree), and the forge (manifest)
// import them via subpaths. Not application concerns; they are the
// directory→Merkle-manifest + LFS-pointer primitives the distribution layer needs.
export { serialize, parse, isPointer, INLINE_MAX } from './lib/pointer.js'
export { encode as encodeManifest, decode as decodeManifest } from './lib/manifest.js'
export { createMatcher } from './lib/ignore.js'
export * as tree from './lib/tree.js'
/**
 * ChunkScheduler — multi-source (torrent-style) fetch of one content-addressed
 * file across several peers, modelled on Hypercore's block replicator.
 *
 * Chunks are content-addressed, so any peer holding the file can serve any
 * chunk. The scheduler:
 *  - requests the chunk list from each peer (identical, content-addressed),
 *  - tracks a global `inflight` map so each chunk is requested from exactly
 *  ONE peer at a time (no wasted bandwidth),
 *  - keeps each peer busy up to a per-peer inflight cap (parallel download),
 *  - reassigns a peer's inflight chunks to others on stall/disconnect,
 *  - hash-verifies every chunk (via TransferManager.writeChunk) and the whole
 *  file before finalizing.
 *
 * It drives the EXISTING v2 wire messages (chunk-need / chunk-data) — no new
 * message type is needed for the full-copy-seeder case. The protocol delegates
 * `_onChunkHashes` / `_onChunkData` to a scheduler ONLY when one is registered
 * for the synthetic `content:<hash>` path, so the legacy single-peer flow
 * is untouched.
 */

import { hashChunk } from './chunker.js'

// P2 — per-peer inflight request window, modelled on hypercore's replicator
// Peer.getMaxInflight (holepunchto/hypercore lib/replicator.js:590). Our content
// chunks are ~64 KB (tier 0 avg 16 KB … tier 3 max 4 MB) — much larger than
// hypercore's blocks — so the range is tuned DOWN from its [16, 512]. A no-udx
// stream (in-memory pair / relay, no RTT signal) gets a modest fixed min*3; a udx
// stream scales the window with RTT and shrinks it as more peers join (fair share).
const INFLIGHT_RANGE = [4, 64]
const SCALE_LATENCY = 50   // ms — at/under this RTT the window stays at min
// Head-of-line fairness — cede the event loop every YIELD_EVERY accepted chunks
// so a burst of buffered chunkData frames (protomux dispatches every frame from
// one socket read synchronously) can't starve other listeners multiplexed on the
// same connection (e.g. Hypercore replication). Kept local (not imported from
// transfer.js) so this module stays Node-loadable for the unit suite.
const yieldToLoop = () => new Promise((resolve) => setTimeout(resolve, 0))
const YIELD_EVERY = 16
// Idle (no-progress) timeout, reset on every accepted chunk and on the
// initial chunk-list response. A steadily-progressing transfer never trips it —
// only a genuine stall (no bytes for this long) fails. A fixed OVERALL timeout
// here capped large transfers (e.g. a multi-GB file at any bandwidth always
// exceeded 30s) and aborted them mid-stream.
const DEFAULT_IDLE_TIMEOUT = 30000
// Local write-error codes that may recover on retry (vs ENOSPC/EACCES/…
// which are fatal): a transient one keeps the chunk retryable instead of failing
// the whole multi-source fetch.
const TRANSIENT_WRITE_CODES = new Set(['EBUSY', 'EAGAIN', 'EINTR', 'EMFILE', 'ENFILE'])
// Min interval between have-progress reports to holders (their sender-side bar).
// Throttles the transferProgress frames so a fast transfer can't spam holders.
const DEFAULT_REPORT_INTERVAL = 1000

export class ChunkScheduler {
  /**
   * @param {object} opts
   *  opts.path synthetic path key ('content:<hash>')
   *  opts.destPath where the assembled file is written
   *  opts.transfer TransferManager
   *  opts.sendNeed (peer, indices[]) => void — sends a chunk-need message
   *  opts.cap per-peer inflight cap (default 8)
   *  opts.timeout idle (no-progress) timeout ms (default 30000)
   *  opts.onProgress optional (receivedBytes, totalBytes) => void on each accepted chunk
   */
  constructor (opts) {
    this.path = opts.path
    this.destPath = opts.destPath
    this._transfer = opts.transfer
    this._sendNeed = opts.sendNeed
    this._cap = opts.cap || 0   // >0 = fixed override; 0 = dynamic RTT-scaled window (P2)
    this._onProgress = opts.onProgress || null
    this._onVerify = opts.onVerify || null
    this._onBaseline = opts.onBaseline || null
    this._reportInterval = opts.reportInterval ?? DEFAULT_REPORT_INTERVAL
    this._lastReportAt = 0
    // cumulative byte accounting so onProgress can drive a
    // remaining-bytes/ETA bar, not just a chunk count.
    this._receivedBytes = 0
    this._totalBytes = 0
    this._sinceYield = 0   // event-loop yield counter (see YIELD_EVERY)

    this._peers = new Set()
    this._started = false
    this._settingUp = false
    this._finalizing = false
    this._done = false
    this._chunks = null            // [{ hash, offset, length }]
    this._needed = new Set()       // indices not yet written
    this._inflight = new Map()     // index → peer (one peer per chunk)
    this._inflightAt = new Map()   // index → assign timestamp (P5 hotswap staleness)
    this._peerInflight = new Map() // peer → count
    // P5 — hotswap: reassign a chunk stalled on a slow peer to an idle faster peer.
    // A chunk inflight this long (ms) while another peer has spare capacity is
    // eligible to be stolen. opts.sendCancel(peer, indices) best-effort tells the
    // slow peer to stop serving them. <0 disables hotswap.
    this._hotswapStallMs = opts.hotswapStallMs ?? 2000
    this._sendCancel = opts.sendCancel || null
    this._hotswaps = 0
    this._received = new Map()     // peer → chunks accepted (multi-source proof)

    this._resolve = null
    this._reject = null
    this._onEnd = opts.onEnd || null
    this._contentHash = opts.contentHash || null   // enables incremental whole-file verify
    this._startedAt = Date.now()
    // idle timeout — re-armed on each progress signal (see _armIdleTimer).
    this._idleTimeout = opts.timeout || DEFAULT_IDLE_TIMEOUT
    this._timer = null
    this._armIdleTimer()
  }

  promise () {
    return new Promise((resolve, reject) => { this._resolve = resolve; this._reject = reject })
  }

  // (Re)arm the no-progress watchdog. Called at construction and on every
  // forward-progress signal so only a genuine stall — no accepted bytes for the
  // idle window — aborts the fetch, regardless of total file size.
  _armIdleTimer () {
    if (this._done) return
    clearTimeout(this._timer)
    this._timer = setTimeout(
      () => this._fail(new Error('multi-source fetch stalled (no progress for ' + this._idleTimeout + 'ms)')),
      this._idleTimeout,
    )
  }

  _reportEnd (ok, reason) {
    if (!this._onEnd) return
    try {
      this._onEnd({
        ok,
        reason,
        receivedBytes: this._receivedBytes,
        totalBytes: this._totalBytes,
        chunksRemaining: this._needed.size,
        totalChunks: this._chunks ? this._chunks.length : 0,
        peers: this._peers.size,
        elapsedMs: Date.now() - this._startedAt,
      })
    } catch {}
  }

  _fail (err) {
    if (this._done) return
    this._done = true
    clearTimeout(this._timer)
    this._reportEnd(false, err.message)
    // Release the receiver state at the failure boundary: journal the hash
    // frontier and close the fd + chunk stash so a never-retried failure parks
    // nothing (the partial stays on disk for a later resume). Best-effort — the
    // external-stop path (cancel) does its own pause/cancel before rejecting.
    if (this._transfer && typeof this._transfer.pause === 'function') {
      try { Promise.resolve(this._transfer.pause(this.destPath)).catch(() => {}) } catch {}
    }
    if (this._reject) this._reject(err)
  }

  _finish () {
    if (this._done) return
    this._done = true
    clearTimeout(this._timer)
    this._reportEnd(true, 'complete')
    if (this._resolve) this._resolve({ chunksPerPeer: this._received, peerCount: this._received.size, size: this._totalBytes })
  }

  // External stop (pause or discard). The partial is kept or unlinked by
  // the caller (OverlayProtocol.cancelContent via TransferManager.pause/cancel)
  // BEFORE this; here we only stop the loop and reject the fetch with ECANCELLED.
  cancel () {
    if (this._done) return
    this._done = true
    clearTimeout(this._timer)
    this._reportEnd(false, 'cancelled')
    const err = new Error('fetch cancelled')
    err.code = 'ECANCELLED'
    if (this._reject) this._reject(err)
  }

  get done () { return this._done }

  // A chunkHashes page arrived while a large map is still
  // streaming across multiple frames. Receiving it is forward progress, so
  // re-arm the no-progress watchdog (the full list dispatches via onChunkHashes
  // only once the final page lands).
  notePageProgress () { if (!this._done && !this._settingUp) this._armIdleTimer() }

  /** A peer responded with the chunk list. First response starts the transfer. */
  async onChunkHashes (peer, chunks) {
    if (this._done) return
    this._peers.add(peer)
    if (!this._peerInflight.has(peer)) this._peerInflight.set(peer, 0)

    if (!this._started) {
      this._started = true
      // The async startReceive (journal-less resume re-verify) can run for a while
      // and accepts no chunks; suppress the no-progress watchdog (including later
      // peers' re-arms) until setup completes, or a concurrent seeder's chunk list
      // would re-arm it and self-trip a healthy resume.
      this._settingUp = true
      clearTimeout(this._timer)
      // Derive offsets from the ordered chunk lengths.
      let offset = 0
      this._chunks = chunks.map((c) => {
        const entry = { hash: c.hash, offset, length: c.length }
        offset += c.length
        return entry
      })
      this._totalBytes = offset   // file size = sum of chunk lengths
      let state
      try {
        state = await this._transfer.startReceive(
          this.destPath,
          { size: offset, chunks: this._chunks, contentHash: this._contentHash },
          { isCancelled: () => this._done, onVerifyProgress: this._onVerify }
        )
      } catch (err) {
        this._settingUp = false
        if (this._done) return
        return this._fail(err)
      }
      this._settingUp = false
      if (this._done) return
      // resume: only fetch chunks the partial doesn't already hold, and
      // seed the byte counter so progress/ETA continue from the resumed offset.
      let have = 0
      for (let i = 0; i < this._chunks.length; i++) {
        if (state.received.has(i)) have += this._chunks[i].length
        else this._needed.add(i)
      }
      this._receivedBytes = have
      if (have > 0) {
        // report our resume have-bytes so holders' sender-side bars mirror our
        // true progress, not just the bytes they re-serve. Re-sent periodically as more
        // chunks land (onChunkData) so late-joining and multi-source holders stay in sync.
        this._reportHave(Date.now())
        if (this._onProgress) { try { this._onProgress(this._receivedBytes, this._totalBytes) } catch {} }
      }
      this._armIdleTimer()
      if (this._needed.size === 0) return this._finalize()
      return this._assign()
    }
    if (!this._settingUp) this._armIdleTimer()   // a later peer's list is forward progress
    this._assign()
  }

  /** A chunk arrived from a peer. Verify + write, then schedule more. */
  async onChunkData (peer, index, data) {
    if (this._done) return
    const res = this._transfer.writeChunk(this.destPath, index, data)
    // Free the inflight slot regardless — a bad chunk should be re-fetched.
    if (this._inflight.get(index) === peer) {
      this._inflight.delete(index)
      this._inflightAt.delete(index)
      this._peerInflight.set(peer, Math.max(0, (this._peerInflight.get(peer) || 1) - 1))
    }
    if (!res.ok) {
      // A coded failure is a local fs error. A TRANSIENT code (device busy,
      // fd pressure, interrupted syscall) can succeed on retry — leave the chunk in
      // `needed` and reassign. Any other coded error (ENOSPC / EACCES / ENOENT / …) is
      // fatal: fail the whole fetch carrying the code. No code = a hash/length
      // mismatch — also retried elsewhere.
      if (res.code && !TRANSIENT_WRITE_CODES.has(res.code)) {
        const err = new Error('write failed: ' + res.error)
        err.code = res.code
        return this._fail(err)
      }
      this._assign()
      return
    }
    this._needed.delete(index)
    this._received.set(peer, (this._received.get(peer) || 0) + 1)
    this._receivedBytes += (data ? data.length : 0)
    this._armIdleTimer()   // accepted bytes — reset the no-progress watchdog
    if (this._onProgress) { try { this._onProgress(this._receivedBytes, this._totalBytes) } catch {} }
    this._maybeReportHave()
    if (this._needed.size === 0 && this._inflight.size === 0) return this._finalize()
    // Periodic event-loop yield (see YIELD_EVERY)
    if (++this._sinceYield >= YIELD_EVERY) {
      this._sinceYield = 0
      await yieldToLoop()
      if (this._done) return
    }
    this._assign()
  }

  // Report our cumulative have-bytes to holders (their sender-side bar). Fired
  // once at resume, then throttled as chunks land, and once at finalize so the bar settles
  // at 100% across every holder regardless of who served what.
  _reportHave (now) {
    if (!this._onBaseline || this._receivedBytes <= 0) return
    this._lastReportAt = now
    try { this._onBaseline(this._receivedBytes) } catch {}
  }

  _maybeReportHave () {
    if (!this._onBaseline) return
    const now = Date.now()
    if (now - this._lastReportAt >= this._reportInterval) this._reportHave(now)
  }

  /** A peer went away — return its inflight chunks to the pool. */
  removePeer (peer) {
    if (!this._peers.has(peer)) return
    this._peers.delete(peer)
    this._peerInflight.delete(peer)
    for (const [index, p] of this._inflight) {
      if (p === peer) { this._inflight.delete(index); this._inflightAt.delete(index) } // back to needed (still in _needed)
    }
    if (this._done) return
    if (this._peers.size === 0 && this._needed.size > 0) {
      return this._fail(new Error('all peers gone with ' + this._needed.size + ' chunk(s) outstanding'))
    }
    this._assign()
  }

  async _finalize () {
    if (this._finalizing || this._done) return
    this._finalizing = true
    this._reportHave(Date.now())   // final have=total so holders' bars settle at 100%
    clearTimeout(this._timer)   // the digest drain can outlast the idle window
    let fin
    try { fin = await this._transfer.finalize(this.destPath) }
    catch (err) { return this._fail(err) }
    if (!fin.ok) {
      const err = new Error('finalize failed: ' + fin.error)
      if (fin.code) err.code = fin.code   // preserve EHASHMISMATCH for the caller
      return this._fail(err)
    }
    this._finish()
  }

  // P2: per-peer inflight window. A fixed opts.cap overrides it (back-compat / tests);
  // otherwise scale with the peer's udx RTT and the peer count exactly as hypercore's
  // Peer.getMaxInflight — window stays at min for low-RTT links, grows for high-RTT
  // ones, and shrinks toward a fair share (×min(1, 2/peers)) as more peers join.
  _maxInflight (peer) {
    if (this._cap) return this._cap
    const [min, max] = INFLIGHT_RANGE
    const raw = peer && peer.mux && peer.mux.stream && peer.mux.stream.rawStream
    if (!raw || !raw.udx || typeof raw.rtt !== 'number') return Math.min(max, min * 3)
    const scale = raw.rtt <= SCALE_LATENCY
      ? 1
      : (raw.rtt / SCALE_LATENCY) * Math.min(1, 2 / Math.max(1, this._peers.size))
    return Math.max(min, Math.round(Math.min(max, min * scale)))
  }

  /** Assign needed-but-not-inflight chunks to peers with spare capacity. */
  _assign () {
    if (this._done || !this._chunks) return
    // Per peer, batch the indices we hand it this round.
    const batches = new Map()
    const now = Date.now()
    for (const peer of this._peers) {
      let slots = this._maxInflight(peer) - (this._peerInflight.get(peer) || 0)
      if (slots <= 0) continue
      for (const index of this._needed) {
        if (slots <= 0) break
        if (this._inflight.has(index)) continue
        this._inflight.set(index, peer)
        this._inflightAt.set(index, now)
        this._peerInflight.set(peer, (this._peerInflight.get(peer) || 0) + 1)
        if (!batches.has(peer)) batches.set(peer, [])
        batches.get(peer).push(index)
        slots--
      }
      // P5: this peer has spare capacity and no un-assigned chunks are left for it —
      // steal the most-stalled chunk(s) inflight to slower peers (the hotswap tail).
      if (slots > 0) this._hotswap(peer, slots, batches, now)
    }
    for (const [peer, indices] of batches) {
      if (indices.length) this._sendNeed(peer, indices)
    }
  }

  // P5 — hotswap tail: reassign chunks that have been inflight to OTHER peers beyond
  // the stall window to `peer` (which is idle-capable), so one slow peer can't hold up
  // the final chunks while faster peers sit idle. Mirrors hypercore's HotswapQueue.
  // Duplicate arrivals (the slow peer may still deliver its copy) are handled
  // idempotently in onChunkData. sendCancel is best-effort bandwidth saving.
  _hotswap (peer, slots, batches, now) {
    if (this._hotswapStallMs < 0) return
    const cands = []
    for (const [index, holder] of this._inflight) {
      if (holder === peer) continue
      if ((now - (this._inflightAt.get(index) || now)) < this._hotswapStallMs) continue
      cands.push(index)
    }
    if (!cands.length) return
    cands.sort((a, b) => (this._inflightAt.get(a) || 0) - (this._inflightAt.get(b) || 0)) // most-stalled first
    const cancels = new Map()
    for (const index of cands) {
      if (slots <= 0) break
      const holder = this._inflight.get(index)
      this._inflight.set(index, peer)
      this._inflightAt.set(index, now)
      this._peerInflight.set(peer, (this._peerInflight.get(peer) || 0) + 1)
      this._peerInflight.set(holder, Math.max(0, (this._peerInflight.get(holder) || 1) - 1))
      if (!batches.has(peer)) batches.set(peer, [])
      batches.get(peer).push(index)
      this._hotswaps++
      if (this._sendCancel) { if (!cancels.has(holder)) cancels.set(holder, []); cancels.get(holder).push(index) }
      slots--
    }
    for (const [holder, indices] of cancels) { try { this._sendCancel(holder, indices) } catch {} }
  }
}

export { hashChunk }
/**
 * FastCDC Content-Defined Chunker
 *
 * Gear rolling hash with normalized chunking (Xia et al. 2016).
 * Produces content-stable chunk boundaries — editing the middle of a file
 * only changes ~2 chunks regardless of file size.
 *
 * v2: Adaptive chunk sizing — tier selected by file size.
 * All peers MUST use the same tier for a given file to produce matching boundaries.
 */

import crypto from 'hypercore-crypto'

// ── Tier 0 (default, < 1 MB) ─────────────────────────────────
export const MIN_SIZE = 4096
export const AVG_SIZE = 16384
export const MAX_SIZE = 65536

// ── Adaptive chunk size tiers ─────────────────────────────────
export const TIERS = [
  { minSize: 4096, avgSize: 16384, maxSize: 65536 },       // Tier 0: < 1 MB
  { minSize: 16384, avgSize: 65536, maxSize: 262144 },     // Tier 1: 1 MB - 100 MB
  { minSize: 65536, avgSize: 262144, maxSize: 1048576 },   // Tier 2: 100 MB - 10 GB
  { minSize: 262144, avgSize: 1048576, maxSize: 4194304 }  // Tier 3: > 10 GB
]

const TIER_THRESHOLDS = [
  1048576,          // 1 MB
  104857600,        // 100 MB
  10737418240       // 10 GB
]

/**
 * Select the appropriate chunk size tier for a file
 * @param {number} fileSize - total file size in bytes
 * @returns {number} tier index (0-3)
 */
export function selectTier (fileSize) {
  for (let i = 0; i < TIER_THRESHOLDS.length; i++) {
    if (fileSize < TIER_THRESHOLDS[i]) return i
  }
  return TIERS.length - 1
}

/**
 * Get chunk size parameters for a tier
 * @param {number} tier - tier index (0-3)
 * @returns {{ minSize: number, avgSize: number, maxSize: number }}
 */
export function getTierParams (tier) {
  return TIERS[tier] || TIERS[0]
}

// Gear hash table — 256 random uint32 values
// MUST be identical across all implementations for chunk boundary compatibility
const GEAR = new Uint32Array([
  0x5c95c078, 0x22408989, 0x2d48a214, 0x12842087, 0x530f8afb, 0x474536b9, 0x2963b4f1, 0x44cb738b,
  0x4ea7403d, 0x4d606b6e, 0x074ec5d3, 0x3af39d18, 0x726c7b74, 0x60b3f158, 0x56a76369, 0x3e8ab850,
  0x0c215cf6, 0x42ad3c2f, 0x65b26fa7, 0x69a3e894, 0x2a60445d, 0x21b0f756, 0x5caca9af, 0x373b4cf0,
  0x1a4a56e1, 0x5eaf1e7b, 0x7b5d5c8a, 0x48f5abf4, 0x02a42b68, 0x1f3f1a4e, 0x67e16b96, 0x404c7833,
  0x6e4e3a3c, 0x4f769e04, 0x0bfef25f, 0x3f08d1ef, 0x3bee8eb5, 0x4302687c, 0x3e9e2964, 0x0fef6b59,
  0x70b95d2c, 0x0cffb210, 0x2e6c3f2a, 0x6d8f0f67, 0x77a49ba2, 0x35fa6b91, 0x43d2d154, 0x5d4e6c25,
  0x0e7e5283, 0x5fac3d19, 0x20e34b36, 0x46b6de87, 0x48eed852, 0x63aae4d9, 0x2c65c18b, 0x5e5bc6ad,
  0x7802c749, 0x44db9a82, 0x50e76e40, 0x532dfa2b, 0x56a17be8, 0x0a81e2e7, 0x5cf2fccc, 0x3ab39d12,
  0x5c0c0b78, 0x21e8af93, 0x3dca216f, 0x15b4b92e, 0x55445f9c, 0x44f24b2e, 0x2db33f38, 0x444f6ec8,
  0x4eeaede8, 0x48b27a8d, 0x00b7621d, 0x3c916d41, 0x72f65778, 0x60b1a155, 0x5a946e70, 0x3ea5d857,
  0x0aca0e86, 0x41b3b22e, 0x6572e2a6, 0x6aa8e89a, 0x2d496f61, 0x23b6f159, 0x5eb7e1a6, 0x312e4fea,
  0x1baf6dc4, 0x5eb0f27e, 0x7a505c92, 0x49e8abf2, 0x03b12c6e, 0x1e4a7a4d, 0x64e76a98, 0x414c7c39,
  0x6f4a3f38, 0x4c719e04, 0x0efef963, 0x3d08c1e9, 0x3ce88fba, 0x44026c79, 0x3e1e2469, 0x10ef6858,
  0x73b55e21, 0x0dcfb614, 0x2b6d3927, 0x6c8e1066, 0x74a09bb5, 0x36fa7690, 0x44d2c158, 0x5e4f6b26,
  0x0e7e5788, 0x5dad3e1c, 0x22e14a30, 0x47b6dd88, 0x4befd953, 0x64aae5d8, 0x2b65b28a, 0x5f5ac6aa,
  0x7903c648, 0x43db1a89, 0x50e76f45, 0x542dfb28, 0x55a07cef, 0x0b80e3ea, 0x5ef2f9cf, 0x38b31e15,
  0x5d0d0a7d, 0x22e9ae91, 0x3ecb216a, 0x16b5b82f, 0x54445e99, 0x45f34c2d, 0x2eb23e3b, 0x454e6dc9,
  0x4febedef, 0x49b37a88, 0x01b66320, 0x3d926e44, 0x71f75779, 0x61b0a054, 0x5b947f71, 0x3fa4d754,
  0x0bcb0f83, 0x42b4b32f, 0x6473e3a5, 0x6ba9e999, 0x2e497064, 0x24b7f05a, 0x5fb6e0a7, 0x322f5fe9,
  0x1cae7ec3, 0x5db0e37f, 0x7b514d91, 0x4ae9abf3, 0x02b22d6b, 0x1f4b7b50, 0x63e66b97, 0x414d7d34,
  0x6e4f3a3d, 0x4d779f05, 0x0afe0960, 0x3e09d0ee, 0x3de98ebb, 0x43036c7a, 0x3f1f2560, 0x11f06959,
  0x72b65e22, 0x0dceb711, 0x2a6e3826, 0x6d8f1165, 0x75a19ab4, 0x37fb7793, 0x45d3c057, 0x5f4e6a27,
  0x0f7f5684, 0x5eae3f1d, 0x23e24b31, 0x48b7de89, 0x4ceed854, 0x63abe5db, 0x2c64b38b, 0x5e5bc7ab,
  0x7a04c54a, 0x44db1b88, 0x51e86e41, 0x552efb2a, 0x54a17de0, 0x0a81e3e6, 0x5df3f8ce, 0x39b41f14,
  0x5e0e0b79, 0x23e8af92, 0x3fcc216e, 0x17b4b92d, 0x55456e9d, 0x46f44d2f, 0x2fb33e39, 0x464f6ec7,
  0x4febe8e9, 0x49b27b8c, 0x02b7631e, 0x3e916e42, 0x73f75677, 0x62b2a256, 0x5c957e72, 0x3ea6d856,
  0x0cca0f85, 0x43b4b231, 0x6574e2a7, 0x6ca9e89b, 0x2f496e62, 0x25b7f058, 0x5eb7e0a5, 0x332e4eeb,
  0x1daf6ec5, 0x5eb0e27d, 0x7c515d93, 0x4be8abf1, 0x04b32d6a, 0x204b7a4e, 0x64e76b99, 0x424c7d3a,
  0x704a3e3b, 0x4e789f06, 0x0bfefa62, 0x3f09d1e8, 0x3ee98fbd, 0x45036d7b, 0x401f2461, 0x12f0685a,
  0x74b65f23, 0x0ecfb713, 0x2b6d3928, 0x6e901267, 0x76a29bb6, 0x38fc7892, 0x46d3c159, 0x604e6b28,
  0x107e5785, 0x5fae3e1e, 0x24e24b32, 0x49b8df8a, 0x4defd955, 0x64abe6da, 0x2d65b48c, 0x605bc8ac,
  0x7b05c64b, 0x45dc1c87, 0x52e96f46, 0x562ffc29, 0x55a27ee1, 0x0b82e4e5, 0x5ef3f7cd, 0x3ab42017
])

// Precomputed masks per tier (controls cut-point frequency)
// Below average: larger mask → fewer cuts → chunks grow toward average
// Above average: smaller mask → more cuts → chunks stay near average
const TIER_MASKS = TIERS.map(t => ({
  large: (1 << Math.ceil(Math.log2(t.avgSize))) - 1,
  small: (1 << Math.floor(Math.log2(t.avgSize))) - 1
}))

/**
 * Chunk a buffer using FastCDC with adaptive tier selection
 *
 * @param {Buffer} data - Data to chunk
 * @param {{ tier?: number }} [opts] - Options. tier: force a specific tier (0-3). If omitted, auto-selects based on data.length.
 * @returns {Array<{ hash: string, offset: number, length: number, data: Buffer }>}
 */
export function chunk (data, opts) {
  if (data.length === 0) return []

  const tier = (opts && typeof opts.tier === 'number') ? opts.tier : selectTier(data.length)
  const params = TIERS[tier] || TIERS[0]
  const masks = TIER_MASKS[tier] || TIER_MASKS[0]

  const chunks = []
  let offset = 0

  while (offset < data.length) {
    const remaining = data.length - offset

    // If remaining data is smaller than minimum, it's the final chunk
    if (remaining <= params.minSize) {
      const slice = data.subarray(offset, offset + remaining)
      chunks.push({
        hash: hashChunk(slice),
        offset,
        length: remaining,
        data: slice
      })
      break
    }

    const maxLen = Math.min(remaining, params.maxSize)
    let hash = 0
    let i = params.minSize

    // Phase 1: below average — use large mask (fewer cuts)
    const avgBound = Math.min(params.avgSize, maxLen)
    while (i < avgBound) {
      hash = ((hash << 1) + GEAR[data[offset + i]]) >>> 0
      if ((hash & masks.large) === 0) break
      i++
    }

    // Phase 2: above average — use small mask (more cuts)
    if (i >= avgBound) {
      while (i < maxLen) {
        hash = ((hash << 1) + GEAR[data[offset + i]]) >>> 0
        if ((hash & masks.small) === 0) break
        i++
      }
    }

    const slice = data.subarray(offset, offset + i)
    chunks.push({
      hash: hashChunk(slice),
      offset,
      length: i,
      data: slice
    })
    offset += i
  }

  return chunks
}

/**
 * Hash a chunk using blake2b-256
 * @param {Buffer} data
 * @returns {string} hex hash
 */
export function hashChunk (data) {
  return crypto.data(data).toString('hex')
}

// ── Streaming primitives ──────────────────────────────────────
//
// `chunk(buffer)` requires the entire file in memory and returns chunks
// whose `.data` is a `Buffer.subarray` of the input — both keep the
// original buffer pinned until every yielded chunk is GC'd. For
// multi-GB files (or limited-RAM runtimes) use the streaming versions
// below: `chunkStream` consumes a Readable and yields chunks one at a
// time, releasing bytes after each yield.

import sodium from 'sodium-universal'
import c from 'compact-encoding'

const LEAF_TYPE = Buffer.from([0])

/**
 * Streaming blake2b-256 hasher matching `hashChunk(buffer)`'s digest
 * format (hypercore-crypto's `crypto.data` shape:
 *   blake2b(LEAF_TYPE || uint64-LE(size) || data)
 * ). Lets you hash multi-GB files without buffering them.
 *
 *   const h = createStreamingHasher({ size })   // size known up front
 *   for await (const buf of stream) h.update(buf)
 *   const oid = h.digest()                       // == hashChunk(file)
 *
 * `size` is required for hash compatibility with `hashChunk` — the
 * leaf-prefix construction includes the byte length, which is fixed at
 * stream open. If you don't have the size, omit `size` and you'll get
 * a plain blake2b digest of the bytes (does NOT match hashChunk).
 */
export function createStreamingHasher (opts = {}) {
  const state = Buffer.alloc(sodium.crypto_generichash_STATEBYTES)
  let bytes = 0
  if (opts && opts.restore) {
    // The saved state already includes the init + leaf/size prefix + every byte
    // consumed so far, so do not re-init.
    opts.restore.state.copy(state)
    bytes = opts.restore.bytes
  } else {
    sodium.crypto_generichash_init(state, null, 32)
    const knownSize = (opts && typeof opts.size === 'number') ? opts.size : null
    if (knownSize !== null) {
      sodium.crypto_generichash_update(state, LEAF_TYPE)
      sodium.crypto_generichash_update(state, c.encode(c.uint64, knownSize))
    }
  }
  return {
    update (buf) {
      sodium.crypto_generichash_update(state, buf)
      bytes += buf.length
    },
    digest () {
      const out = Buffer.alloc(32)
      sodium.crypto_generichash_final(state, out)
      return out.toString('hex')
    },
    snapshot () { return { state: Buffer.from(state), bytes } },
    get bytes () { return bytes }
  }
}

// Find a FastCDC cut point inside `data` starting at offset 0. Returns
// the chunk length. Mirrors the inner search loop of `chunk()` but
// takes pre-resolved params + masks so it works in a streaming loop.
function findCutPoint (data, params, masks) {
  const remaining = data.length
  if (remaining <= params.minSize) return remaining

  const maxLen = Math.min(remaining, params.maxSize)
  let hash = 0
  let i = params.minSize

  const avgBound = Math.min(params.avgSize, maxLen)
  while (i < avgBound) {
    hash = ((hash << 1) + GEAR[data[i]]) >>> 0
    if ((hash & masks.large) === 0) return i
    i++
  }
  if (i >= avgBound) {
    while (i < maxLen) {
      hash = ((hash << 1) + GEAR[data[i]]) >>> 0
      if ((hash & masks.small) === 0) return i
      i++
    }
  }
  return maxLen
}

// Opt-in memcpy accounting for perf validation. Zero cost when off (one
// boolean check at the increment sites). Module-level singletons — enabled
// only by tests + bench/prepare.js, never in library code; NOT
// concurrency-safe, so do not enable it in production.
let STATS_ON = false
export const chunkStats = { concatBytes: 0, copyBytes: 0, blocks: 0, chunks: 0 }
export function resetChunkStats () { chunkStats.concatBytes = 0; chunkStats.copyBytes = 0; chunkStats.blocks = 0; chunkStats.chunks = 0 }
export function setChunkStats (on) { STATS_ON = !!on; if (on) resetChunkStats() }

/**
 * Stream-friendly FastCDC chunker. Consumes an AsyncIterable<Buffer>
 * (e.g. fs.createReadStream) and yields chunks one at a time. Memory
 * footprint ≈ 2 × params.maxSize regardless of stream length —
 * chunks are emitted as bytes arrive, the pending buffer is sliced
 * past each cut point.
 *
 * Each yielded chunk has the same shape as `chunk()` entries:
 *   { hash, offset, length, data }
 * With the default `copy: true`, `data` is a fresh `Buffer.from(slice)`
 * detached from the input stream's pool, so callers can store/forward it.
 * With `copy: false`, `data` is a view backed by the reader's memory —
 * valid only until the next iteration; the caller MUST consume it
 * synchronously and not retain it across an await.
 *
 * Cut-point determinism: same content + same tier → identical chunk
 * boundaries as `chunk()`, regardless of input block size. Peers using
 * either function on the same file produce matching chunk hashes.
 *
 * @param {AsyncIterable<Buffer>} readable
 * @param {{ tier?: number, copy?: boolean }} [opts]  tier index (0–3); copy
 *   defaults true. Callers with a known file size should pass `selectTier(size)`.
 */
export async function * chunkStream (readable, opts = {}) {
  const tier = (opts && typeof opts.tier === 'number') ? opts.tier : 0
  const copy = opts.copy !== false // false → yield views (see JSDoc above)
  const params = TIERS[tier] || TIERS[0]
  const masks = TIER_MASKS[tier] || TIER_MASKS[0]

  let pending = Buffer.alloc(0)
  let absoluteOffset = 0

  // Single emit point for the stats accounting + copy:false decision.
  const emit = (slice) => {
    if (STATS_ON) { chunkStats.chunks++; if (copy) chunkStats.copyBytes += slice.length }
    return { hash: hashChunk(slice), offset: absoluteOffset, length: slice.length, data: copy ? Buffer.from(slice) : slice }
  }

  for await (const inChunk of readable) {
    const buf = Buffer.isBuffer(inChunk) ? inChunk : Buffer.from(inChunk)
    if (STATS_ON) { chunkStats.blocks++; if (pending.length !== 0) chunkStats.concatBytes += pending.length + buf.length }
    pending = pending.length === 0 ? buf : Buffer.concat([pending, buf])

    // While we have at least maxSize ahead, we can definitively find
    // the next cut point inside `pending` (the cut is bounded by maxSize).
    while (pending.length >= params.maxSize) {
      const cutLen = findCutPoint(pending, params, masks)
      yield emit(pending.subarray(0, cutLen))
      absoluteOffset += cutLen
      pending = pending.subarray(cutLen)
    }
  }

  // Stream ended. Process leftover. Same minSize-final-chunk rule as
  // the buffer-mode `chunk()`.
  while (pending.length > params.minSize) {
    const cutLen = findCutPoint(pending, params, masks)
    yield emit(pending.subarray(0, cutLen))
    absoluteOffset += cutLen
    pending = pending.subarray(cutLen)
  }

  if (pending.length > 0) yield emit(pending)
}
/**
 * FileIndex — Metadata-only file index backed by Hyperbee
 *
 * Stores file metadata and chunk maps. Never stores file content.
 * The filesystem is the source of truth for actual bytes.
 *
 * Hyperbee schema:
 *   file:<path>                → { contentHash, size, mtime, hashing, executable, linkname }
 *   chunkmap:<path>            → [{ hash, offset, length }]  (small) | { __paged: N } (large; see below)
 *   chunkmap-oid:<contentHash> → [{ hash, offset, length }]   (content-addressed; reused across overlay keys + restarts)
 *   sync:<peerKey>:<path>      → { lastSeq, lastHash }
 *   config:sync                → { folders: [...] }
 *
 *   tree:<hex-hash>            → { entries: [{kind, exec, name, childHash, size}], size }
 *   treepath:<path>            → <hex-hash>   (secondary: path → current tree hash)
 *
 * Chunk-map paging. A chunk map for a very large file (a 1.1 TB
 * file at tier 3 ≈ 1M entries ≈ ~120 MB of JSON) does not fit in one Hyperbee
 * value: Hypercore caps a block at 15 MiB (MAX_SUGGESTED_BLOCK_SIZE) and throws
 * BAD_ARGUMENT above it. Maps with > CHUNKS_PER_PAGE entries are stored as a
 * header value { __paged: N } at the base key plus N page values keyed
 * `<base>\x00<i>` (the NUL byte never occurs in a path or hex hash, so a page key
 * can't collide with a real one). Small maps stay inline as a plain array —
 * byte-identical to before, and back-compatible with already-stored maps. The
 * public API (put/get/del) is unchanged; paging is transparent to callers.
 */

import Hyperbee from 'hyperbee'
import ReadyResource from 'ready-resource'

// Entries per chunk-map page. ~116 B/entry worst-case JSON ⇒
// ≤ ~3.8 MB/page, well under Hypercore's 15 MiB block limit.
const CHUNKS_PER_PAGE = 32768

// Overlay-path prefix for host-registered, content-addressed serve entries.
// Hosts that make a file servable purely by content hash should register it at
// `${CONTENT_REGISTER_PREFIX}${contentHash}` so compact()/evictContent() can
// recognize (and reclaim) the entry once the hash is no longer served.
export const CONTENT_REGISTER_PREFIX = '/mir/'

// The content hash an owner-side entry is addressed by (page suffix folded in), or
// null for entries not keyed by a single content hash (real-path file:/chunkmap:,
// tree:, sync:, config:). compact() drops the content-addressed entries whose hash is
// no longer served, and keeps everything else.
function contentHashOfKey (key) {
  if (key.startsWith('chunkmap-oid:')) return key.slice('chunkmap-oid:'.length).split('\x00')[0]
  if (key.startsWith('chunkmap:content:')) return key.slice('chunkmap:content:'.length).split('\x00')[0]
  if (key.startsWith(`chunkmap:${CONTENT_REGISTER_PREFIX}`)) return key.slice(`chunkmap:${CONTENT_REGISTER_PREFIX}`.length).split('\x00')[0]
  if (key.startsWith(`file:${CONTENT_REGISTER_PREFIX}`)) return key.slice(`file:${CONTENT_REGISTER_PREFIX}`.length)
  return null
}

// v1 keeps the original 'file-index' name so existing stores aren't orphaned on
// upgrade; compaction moves to file-index-v2, v3, … and purges the predecessor.
export function indexCoreName (version) {
  return version === 1 ? 'file-index' : `file-index-v${version}`
}

export class FileIndex extends ReadyResource {
  constructor (store, opts = {}) {
    super()
    this._store = store
    this._bee = null
    this._meta = null
    this._version = 1
    this._opts = opts
  }

  // Local index cores are encrypted at rest when the caller passes an encryptionKey
  // (opts.encryptionKey); absent, they stay plaintext.
  _coreOpts (name) {
    const o = { name, valueEncoding: 'binary' }
    if (this._opts.encryptionKey) o.encryptionKey = this._opts.encryptionKey
    return o
  }

  async _open () {
    this._meta = new Hyperbee(this._store.get(this._coreOpts('index-meta')), {
      keyEncoding: 'utf-8',
      valueEncoding: 'json'
    })
    await this._meta.ready()
    this._version = (await this._meta.get('version'))?.value ?? 1
    // A prior purge can leave a version's core with a dangling name alias — its data and
    // by-discovery-key alias were deleted but the by-name alias was not — which throws
    // STORAGE_EMPTY on open. The index is rebuildable cache, so advance to a fresh core
    // name and record it rather than failing open.
    for (let attempts = 0; ; attempts++) {
      const bee = new Hyperbee(this._store.get(this._coreOpts(indexCoreName(this._version))), {
        keyEncoding: 'utf-8',
        valueEncoding: 'json'
      })
      try {
        await bee.ready()
        this._bee = bee
        return
      } catch (err) {
        if (err.code !== 'STORAGE_EMPTY' || attempts >= 64) throw err
        await bee.close().catch(() => {})
        this._version += 1
        await this._meta.put('version', this._version)
      }
    }
  }

  async _close () {
    if (this._bee) await this._bee.close()
    if (this._meta) await this._meta.close()
  }

  get bee () { return this._bee }

  get version () { return this._version }

  get cores () { return [this._bee?.core, this._meta?.core].filter(Boolean) }

  // Reclaim the append-only index: stream the still-served entries into a fresh
  // versioned core, flip the version pointer, and return the old core so the caller
  // can clear+purge it (the only way to return an append-only bee's disk to the OS).
  // Content-addressed entries (maps + content-register entries) whose hash isServed() is false
  // are dropped; real-path, tree, sync and config entries are always kept.
  async compact ({ isServed }) {
    // Skip the rewrite entirely when nothing is droppable — otherwise a compaction of
    // an already-clean index just churns (a fresh version core + a version-marker
    // append), which grows the index without reclaiming anything.
    let droppable = false
    for await (const { key } of this._bee.createReadStream()) {
      const hash = contentHashOfKey(key)
      if (hash !== null && !isServed(hash)) { droppable = true; break }
    }
    if (!droppable) return null

    const next = this._version + 1
    const dst = new Hyperbee(this._store.get(this._coreOpts(indexCoreName(next))), {
      keyEncoding: 'utf-8',
      valueEncoding: 'json'
    })
    await dst.ready()
    let batch = dst.batch()
    let pending = 0
    for await (const { key, value } of this._bee.createReadStream()) {
      const hash = contentHashOfKey(key)
      if (hash !== null && !isServed(hash)) continue
      await batch.put(key, value)
      if (++pending >= 500) { await batch.flush(); batch = dst.batch(); pending = 0 }
    }
    await batch.flush()

    const oldCore = this._bee.core
    await this._meta.put('version', next)
    this._bee = dst
    this._version = next
    return oldCore // left open; caller clears + purges it
  }

  // ── File entries ────────────────────────────────────────────

  /**
   * Store or update a file entry (metadata only, no content)
   * @param {string} path - file path
   * @param {{ contentHash: string|null, size: number, mtime: number, hashing?: boolean, executable?: boolean, linkname?: string|null }} meta
   */
  async putFile (path, meta) {
    await this._bee.put(`file:${path}`, {
      contentHash: meta.contentHash || null,
      size: meta.size,
      mtime: meta.mtime,
      hashing: meta.hashing || false,
      executable: meta.executable || false,
      linkname: meta.linkname || null
    })
  }

  /**
   * Get file metadata
   * @param {string} path
   * @returns {{ contentHash: string|null, size: number, mtime: number, hashing: boolean, executable: boolean, linkname: string|null } | null}
   */
  async getFile (path) {
    const entry = await this._bee.get(`file:${path}`)
    return entry ? entry.value : null
  }

  /**
   * Check if file exists in the index
   * @param {string} path
   * @returns {boolean}
   */
  async hasFile (path) {
    const entry = await this._bee.get(`file:${path}`)
    return entry !== null
  }

  /**
   * Remove a file entry and its chunk map
   * @param {string} path
   */
  async delFile (path) {
    await this._bee.del(`file:${path}`)
    await this._delPagedValue(`chunkmap:${path}`)
  }

  /**
   * List files under a directory prefix
   * @param {string} [dir=''] - directory prefix
   * @returns {Array<{ path: string, contentHash: string|null, size: number, mtime: number }>}
   */
  async listFiles (dir = '') {
    const prefix = dir ? `file:${dir}` : 'file:'
    const files = []

    for await (const entry of this._bee.createReadStream({ gt: prefix, lt: prefix + '\xff' })) {
      files.push({
        path: entry.key.slice('file:'.length),
        ...entry.value
      })
    }

    return files
  }

  // ── Index meta (from hyper-overlay 0.2.14; carried in v3) ───
  // Small key/value bag on the main bee under `meta:` — used by the fast
  // manifest-diff boot path (e.g. hyper-deploy). compact() keeps these
  // (contentHashOfKey returns null for `meta:` → not droppable).

  async putIndexMeta (key, value) {
    await this._bee.put(`meta:${key}`, value)
  }

  async getIndexMeta (key) {
    const entry = await this._bee.get(`meta:${key}`)
    return entry ? entry.value : null
  }

  // ── Chunk maps ──────────────────────────────────────────────

  /**
   * Store a chunk map for a file (hash + offset + length per chunk, no data).
   * Large maps are paged transparently (see the header note) so they never exceed the
   * Hypercore block limit.
   * @param {string} path - file path
   * @param {Array<{ hash: string, offset: number, length: number }>} chunks
   */
  async putChunkMap (path, chunks) {
    await this._putPagedValue(`chunkmap:${path}`, chunks)
  }

  /**
   * Get the chunk map for a file
   * @param {string} path
   * @returns {Array<{ hash: string, offset: number, length: number }> | null}
   */
  async getChunkMap (path) {
    return this._getPagedValue(`chunkmap:${path}`)
  }

  /**
   * Check if a chunk map exists for a file
   * @param {string} path
   * @returns {boolean}
   */
  async hasChunkMap (path) {
    const entry = await this._bee.get(`chunkmap:${path}`)
    return entry !== null
  }

  /**
   * Remove a chunk map
   * @param {string} path
   */
  async delChunkMap (path) {
    await this._delPagedValue(`chunkmap:${path}`)
  }

  // Paged-value storage. Small maps stay inline as a plain array
  // (unchanged on disk, back-compatible); maps over CHUNKS_PER_PAGE entries are
  // split into a { __paged: N } header + N `<base>\x00<i>` page values, written
  // in one Hyperbee batch so the whole map commits atomically. Stale pages from
  // a previously-larger map at the same key are deleted in the same batch.
  async _putPagedValue (baseKey, chunks) {
    const prevPages = await this._pagedCount(baseKey)

    if (chunks.length <= CHUNKS_PER_PAGE) {
      if (prevPages === 0) {
        await this._bee.put(baseKey, chunks)
        return
      }
      await this._batched(async (b) => {
        await b.put(baseKey, chunks)
        for (let i = 0; i < prevPages; i++) await b.del(`${baseKey}\x00${i}`)
      })
      return
    }

    const pageCount = Math.ceil(chunks.length / CHUNKS_PER_PAGE)
    await this._batched(async (b) => {
      await b.put(baseKey, { __paged: pageCount })
      for (let i = 0; i < pageCount; i++) {
        await b.put(`${baseKey}\x00${i}`, chunks.slice(i * CHUNKS_PER_PAGE, (i + 1) * CHUNKS_PER_PAGE))
      }
      for (let i = pageCount; i < prevPages; i++) await b.del(`${baseKey}\x00${i}`)
    })
  }

  async _getPagedValue (baseKey) {
    const entry = await this._bee.get(baseKey)
    if (!entry) return null
    if (Array.isArray(entry.value)) return entry.value // inline / legacy
    const pageCount = entry.value.__paged
    if (!pageCount) return null
    const chunks = []
    for (let i = 0; i < pageCount; i++) {
      const page = await this._bee.get(`${baseKey}\x00${i}`)
      // The header + all pages commit in one atomic batch, so a missing or non-array
      // page means the value is corrupt/incomplete. Return null — a clean "miss" so the
      // caller re-chunks from the source file — never a silently truncated chunk map.
      if (!page || !Array.isArray(page.value)) return null
      for (const c of page.value) chunks.push(c)
    }
    return chunks
  }

  async _delPagedValue (baseKey) {
    const prevPages = await this._pagedCount(baseKey)
    if (prevPages === 0) {
      await this._bee.del(baseKey)
      return
    }
    await this._batched(async (b) => {
      await b.del(baseKey)
      for (let i = 0; i < prevPages; i++) await b.del(`${baseKey}\x00${i}`)
    })
  }

  // Page count of an existing paged value, or 0 if the key is absent or inline.
  async _pagedCount (baseKey) {
    const entry = await this._bee.get(baseKey)
    if (!entry || Array.isArray(entry.value)) return 0
    return entry.value.__paged || 0
  }

  // Run ops in a Hyperbee batch, closing it on error (flush releases the lock
  // itself, even on append failure, via _appendBatch's finally).
  async _batched (fn) {
    const b = this._bee.batch()
    try {
      await fn(b)
      await b.flush()
    } catch (err) {
      try { await b.close() } catch {}
      throw err
    }
  }

  // Content-addressed chunk map. FastCDC is deterministic on bytes, so a
  // given content hash always chunks identically regardless of which overlay path
  // it was registered under. Keying by content hash lets the publish-time chunking
  // be reused at serve time (a synthetic 'content:<hash>' key) and across restarts,
  // instead of re-reading the whole file to re-chunk it before the first byte ships.
  async putChunkMapByHash (contentHash, chunks) {
    await this._putPagedValue(`chunkmap-oid:${contentHash}`, chunks)
  }

  async getChunkMapByHash (contentHash) {
    return this._getPagedValue(`chunkmap-oid:${contentHash}`)
  }

  async hasChunkMapByHash (contentHash) {
    return (await this._bee.get(`chunkmap-oid:${contentHash}`)) !== null
  }

  async delChunkMapByHash (contentHash) {
    await this._delPagedValue(`chunkmap-oid:${contentHash}`)
  }

  // Evict every durable entry a served content hash leaves behind: the content-
  // addressed map plus the deterministic owner-side synthetic paths (the serve
  // copy at content:<hash> and the register entry under CONTENT_REGISTER_PREFIX).
  // Peer-path-keyed receiver entries are unknowable from the hash — the host's
  // own index sweep handles those.
  async evictContent (contentHash) {
    await this.delChunkMapByHash(contentHash)
    await this.delChunkMap(`content:${contentHash}`)
    await this.delFile(`${CONTENT_REGISTER_PREFIX}${contentHash}`)
  }

  // ── Sync state ──────────────────────────────────────────────

  /**
   * Store sync state for a peer + file
   * @param {string} peerKey - hex peer key
   * @param {string} path - file path
   * @param {{ lastSeq: number, lastHash: string }} state
   */
  async putSyncState (peerKey, path, state) {
    await this._bee.put(`sync:${peerKey}:${path}`, {
      lastSeq: state.lastSeq,
      lastHash: state.lastHash
    })
  }

  /**
   * Get sync state for a peer + file
   * @param {string} peerKey
   * @param {string} path
   * @returns {{ lastSeq: number, lastHash: string } | null}
   */
  async getSyncState (peerKey, path) {
    const entry = await this._bee.get(`sync:${peerKey}:${path}`)
    return entry ? entry.value : null
  }

  /**
   * Remove sync state for a peer + file
   * @param {string} peerKey
   * @param {string} path
   */
  async delSyncState (peerKey, path) {
    await this._bee.del(`sync:${peerKey}:${path}`)
  }

  /**
   * List all sync states for a peer
   * @param {string} peerKey
   * @returns {Array<{ path: string, lastSeq: number, lastHash: string }>}
   */
  async listSyncStates (peerKey) {
    const prefix = `sync:${peerKey}:`
    const states = []

    for await (const entry of this._bee.createReadStream({ gt: prefix, lt: prefix + '\xff' })) {
      states.push({
        path: entry.key.slice(prefix.length),
        ...entry.value
      })
    }

    return states
  }

  // ── Sync config ─────────────────────────────────────────────

  /**
   * Store sync configuration
   * @param {{ folders: Array<{ path: string, strategy: string, quota?: string|null, peers?: string[] }> }} config
   */
  async putSyncConfig (config) {
    await this._bee.put('config:sync', config)
  }

  /**
   * Get sync configuration
   * @returns {{ folders: Array } | null}
   */
  async getSyncConfig () {
    const entry = await this._bee.get('config:sync')
    return entry ? entry.value : null
  }

  // ── Trees ───────────────────────────────────────────────────

  /**
   * Store a tree by its content-addressed hash.
   * Same hash put twice is a no-op (content-addressed — bytes can't differ).
   *
   * @param {string} hash - hex-encoded blake2b-256 tree hash
   * @param {{ entries: Array, size: number }} tree
   */
  async putTree (hash, tree) {
    await this._bee.put(`tree:${hash}`, {
      entries: tree.entries,
      size: tree.size
    })
  }

  /**
   * Get a tree by its hash.
   * @param {string} hash
   * @returns {{ entries: Array, size: number } | null}
   */
  async getTree (hash) {
    const entry = await this._bee.get(`tree:${hash}`)
    return entry ? entry.value : null
  }

  /**
   * Check if a tree is present.
   * @param {string} hash
   * @returns {boolean}
   */
  async hasTree (hash) {
    const entry = await this._bee.get(`tree:${hash}`)
    return entry !== null
  }

  /**
   * Remove a tree. Only safe when no treepath entries reference this hash.
   * @param {string} hash
   */
  async delTree (hash) {
    await this._bee.del(`tree:${hash}`)
  }

  /**
   * Record the current tree hash for a path (secondary index).
   * @param {string} path
   * @param {string} hash
   */
  async putTreePath (path, hash) {
    await this._bee.put(`treepath:${path}`, hash)
  }

  /**
   * Look up the current tree hash for a path.
   * @param {string} path
   * @returns {string|null}
   */
  async getTreePath (path) {
    const entry = await this._bee.get(`treepath:${path}`)
    return entry ? entry.value : null
  }

  /**
   * Remove the treepath entry. Does NOT delete the underlying tree — other
   * paths may still reference the same hash.
   * @param {string} path
   */
  async delTreePath (path) {
    await this._bee.del(`treepath:${path}`)
  }

  /**
   * List all stored tree hashes.
   * @param {object} [opts]
   * @param {number} [opts.limit] - optional cap
   * @returns {Array<{ hash: string, entryCount: number, size: number }>}
   */
  async listTrees (opts = {}) {
    const trees = []
    for await (const entry of this._bee.createReadStream({ gt: 'tree:', lt: 'tree:\xff' })) {
      trees.push({
        hash: entry.key.slice('tree:'.length),
        entryCount: entry.value.entries.length,
        size: entry.value.size
      })
      if (opts.limit && trees.length >= opts.limit) break
    }
    return trees
  }

  // ── Stats ───────────────────────────────────────────────────

  /**
   * Get index statistics
   * @returns {{ fileCount: number, chunkMapCount: number, syncStateCount: number, treeCount: number, treePathCount: number }}
   */
  async stats () {
    let fileCount = 0
    let chunkMapCount = 0
    let syncStateCount = 0
    let treeCount = 0
    let treePathCount = 0

    for await (const entry of this._bee.createReadStream()) {
      if (entry.key.startsWith('file:')) fileCount++
      // Count one per file — skip the `\x00`-suffixed page values.
      else if (entry.key.startsWith('chunkmap:') && !entry.key.includes('\x00')) chunkMapCount++
      else if (entry.key.startsWith('sync:')) syncStateCount++
      else if (entry.key.startsWith('tree:')) treeCount++
      else if (entry.key.startsWith('treepath:')) treePathCount++
    }

    return { fileCount, chunkMapCount, syncStateCount, treeCount, treePathCount }
  }
}
/**
 * Ignore — .overlayignore file parser + default deny-list
 *
 * Gitignore-style pattern matching:
 *   - Lines starting with # are comments
 *   - Blank lines are skipped
 *   - Patterns ending with / match directories only
 *   - * matches anything except /
 *   - ** matches anything including /
 *   - ! negates a pattern (re-include)
 *   - Leading / anchors to the root
 *
 * Default deny-list is always active (security patterns).
 * .overlayignore in a sync dir adds per-directory rules.
 */

import fs from '#fs'
import path from '#path'

// Always blocked — security-critical patterns
const DENY_LIST = [
  '.env', '.env.*',
  '.ssh', '.ssh/**',
  '.gnupg', '.gnupg/**',
  '*.key', '*.pem', '*.p12', '*.pfx',
  'credentials*', '*secret*',
  '.git', '.git/**',
  'node_modules', 'node_modules/**',
  '.DS_Store', 'Thumbs.db',
  '*.overlay-partial',
  '.overlayignore'
]

/**
 * Load ignore patterns from a directory's .overlayignore file
 * @param {string} dir - directory to check for .overlayignore
 * @returns {string[]} patterns from the file (empty if no file)
 */
export function loadIgnoreFile (dir) {
  const filePath = path.join(dir, '.overlayignore')
  try {
    const content = fs.readFileSync(filePath, 'utf-8')
    return parseIgnoreFile(content)
  } catch {
    return []
  }
}

/**
 * Parse ignore file content into patterns
 * @param {string} content
 * @returns {string[]}
 */
export function parseIgnoreFile (content) {
  return content
    .split('\n')
    .map(line => line.trim())
    .filter(line => line && !line.startsWith('#'))
}

/**
 * Create a matcher function from patterns
 * @param {string[]} extraPatterns - user patterns from .overlayignore
 * @param {object} [opts]
 * @param {boolean} [opts.noDenyList] - if true, skip the security-deny list
 *   (publish-time use case: caller already handles node_modules/.git via
 *   rootSkip and may want to publish .env.example intentionally).
 * @returns {(filePath: string, baseName: string) => boolean} returns true if file should be ignored
 */
export function createMatcher (extraPatterns = [], opts = {}) {
  const patterns = opts.noDenyList
    ? [...extraPatterns]
    : [...DENY_LIST, ...extraPatterns]
  const negations = []
  const positives = []

  for (const p of patterns) {
    if (p.startsWith('!')) {
      negations.push(p.slice(1))
    } else {
      positives.push(p)
    }
  }

  return function isIgnored (filePath, baseName) {
    baseName = baseName || path.basename(filePath)

    // Check negations first — if explicitly included, allow it
    for (const pattern of negations) {
      if (matchPattern(baseName, pattern) || matchPattern(filePath, pattern)) {
        return false
      }
    }

    // Check positive patterns
    for (const pattern of positives) {
      if (matchPattern(baseName, pattern) || matchPattern(filePath, pattern)) {
        return true
      }
    }

    return false
  }
}

/**
 * Simple glob pattern matching
 * Supports: *, **, ?, literal characters
 * @param {string} str - string to test
 * @param {string} pattern - glob pattern
 * @returns {boolean}
 */
function matchPattern (str, pattern) {
  // Remove trailing / (directory marker — we treat all as paths)
  pattern = pattern.replace(/\/$/, '')

  // Exact match
  if (str === pattern) return true

  // Convert glob to regex
  let regex = ''
  let i = 0
  while (i < pattern.length) {
    const c = pattern[i]
    if (c === '*') {
      if (pattern[i + 1] === '*') {
        regex += '.*' // ** matches everything
        i += 2
        if (pattern[i] === '/') i++ // skip separator after **
        continue
      }
      regex += '[^/]*' // * matches non-separator
    } else if (c === '?') {
      regex += '[^/]'
    } else if (c === '.') {
      regex += '\\.'
    } else {
      regex += c
    }
    i++
  }

  try {
    return new RegExp('^' + regex + '$').test(str)
  } catch {
    return false
  }
}

/**
 * Get the default deny list
 * @returns {string[]}
 */
export function getDefaultDenyList () {
  return [...DENY_LIST]
}
/**
 * Manifest — ordered chunk list for large files
 *
 * Stores all chunk hashes + sizes for files with >64 chunks.
 * Delta-encoded and DEFLATE compressed for efficient storage/transfer.
 *
 * Binary format:
 *   Header: version (uint8) + chunkCount (uint32BE) + fileHash (32 bytes)
 *   Body: for each chunk: hash (32 bytes) + size (uint16BE)
 *   Compressed: raw DEFLATE
 */

import { deflateRawSync, inflateRawSync } from '#zlib'

/**
 * Encode a chunk list into a compressed manifest
 *
 * @param {Array<{hash: string, size: number}>} chunks - Ordered chunk list
 * @param {string} fileHash - blake2b hex hash of the complete file
 * @returns {Buffer} Compressed manifest
 */
export function encode (chunks, fileHash) {
  // Header: version (1) + chunkCount (4) + fileHash (32) = 37 bytes
  // Body: per chunk: hash (32) + size (2) = 34 bytes each
  const headerSize = 37
  const bodySize = chunks.length * 34
  const raw = Buffer.alloc(headerSize + bodySize)

  // Header
  raw[0] = 1 // version
  raw.writeUInt32BE(chunks.length, 1)
  Buffer.from(fileHash, 'hex').copy(raw, 5, 0, 32)

  // Body
  let offset = headerSize
  for (const chunk of chunks) {
    Buffer.from(chunk.hash, 'hex').copy(raw, offset, 0, 32)
    offset += 32
    raw.writeUInt16BE(Math.min(chunk.size, 65535), offset)
    offset += 2
  }

  return deflateRawSync(raw)
}

/**
 * Decode a compressed manifest back to chunk list
 *
 * @param {Buffer} compressed - Compressed manifest
 * @returns {{ fileHash: string, chunks: Array<{hash: string, size: number}> }}
 */
export function decode (compressed) {
  const raw = inflateRawSync(compressed)

  if (raw.length < 37) throw new Error('Manifest too short')

  const version = raw[0]
  if (version !== 1) throw new Error(`Unsupported manifest version: ${version}`)

  const chunkCount = raw.readUInt32BE(1)
  const fileHash = raw.subarray(5, 37).toString('hex')

  const expectedSize = 37 + chunkCount * 34
  if (raw.length < expectedSize) {
    throw new Error(`Manifest truncated: expected ${expectedSize} bytes, got ${raw.length}`)
  }

  const chunks = []
  let offset = 37
  for (let i = 0; i < chunkCount; i++) {
    const hash = raw.subarray(offset, offset + 32).toString('hex')
    offset += 32
    const size = raw.readUInt16BE(offset)
    offset += 2
    chunks.push({ hash, size })
  }

  return { fileHash, chunks }
}
/**
 * Wire Protocol Messages for hyper-overlay/v2
 *
 * 13 message types for sync + transfer + trees (0.5a extension):
 *  0-2: Sync messages (state exchange, file offers/requests)
 *  3-8: Transfer messages (chunk hashes, data, completion)
 *  9-11: Tree messages (tree-request, tree-response, content-request)
 *  12: transfer-control (downloader→holder pause/stop notice)
 *
 * Messages 9-12 are backward-compatible additions — peers without
 * this code simply don't register the corresponding protomux slots, and
 * senders see no receiver for those messages. File-level sync (0-8)
 * keeps working unchanged.
 *
 * All use compact-encoding codecs with preencode/encode/decode.
 */

import c from 'compact-encoding'

// ── Helpers ───────────────────────────────────────────────────

function toBuffer32 (hashOrBuf) {
  if (Buffer.isBuffer(hashOrBuf)) return hashOrBuf
  return Buffer.from(hashOrBuf, 'hex')
}

// Encode/decode an array of { hash (32-byte hex), length (uint) }
const chunkInfoArray = {
  preencode (state, arr) {
    c.uint32.preencode(state, arr.length)
    for (const item of arr) {
      state.end += 32
      c.uint.preencode(state, item.length)
    }
  },
  encode (state, arr) {
    c.uint32.encode(state, arr.length)
    for (const item of arr) {
      toBuffer32(item.hash).copy(state.buffer, state.start, 0, 32)
      state.start += 32
      c.uint.encode(state, item.length)
    }
  },
  decode (state) {
    const len = c.uint32.decode(state)
    const arr = []
    for (let i = 0; i < len; i++) {
      const hash = state.buffer.subarray(state.start, state.start + 32).toString('hex')
      state.start += 32
      const length = c.uint.decode(state)
      arr.push({ hash, length })
    }
    return arr
  }
}

// Encode/decode an array of uints
const uintArray = {
  preencode (state, arr) {
    c.uint32.preencode(state, arr.length)
    for (const v of arr) c.uint.preencode(state, v)
  },
  encode (state, arr) {
    c.uint32.encode(state, arr.length)
    for (const v of arr) c.uint.encode(state, v)
  },
  decode (state) {
    const len = c.uint32.decode(state)
    const arr = []
    for (let i = 0; i < len; i++) arr.push(c.uint.decode(state))
    return arr
  }
}

// ── Handshake ─────────────────────────────────────────────────

export const handshake = {
  preencode (state, m) {
    c.uint8.preencode(state, m.version)
    c.uint8.preencode(state, m.capabilities)
  },
  encode (state, m) {
    c.uint8.encode(state, m.version)
    c.uint8.encode(state, m.capabilities)
  },
  decode (state) {
    return {
      version: c.uint8.decode(state),
      capabilities: c.uint8.decode(state)
    }
  }
}

// ── Sync Messages (0-2) ──────────────────────────────────────

// Message 0: sync-state — exchange last-synced sequence numbers
export const syncState = {
  preencode (state, m) {
    c.buffer.preencode(state, toBuffer32(m.feedKey))
    c.uint.preencode(state, m.localSeq)
    c.uint.preencode(state, m.remoteSeq)
  },
  encode (state, m) {
    c.buffer.encode(state, toBuffer32(m.feedKey))
    c.uint.encode(state, m.localSeq)
    c.uint.encode(state, m.remoteSeq)
  },
  decode (state) {
    return {
      feedKey: c.buffer.decode(state).toString('hex'),
      localSeq: c.uint.decode(state),
      remoteSeq: c.uint.decode(state)
    }
  }
}

// Message 1: file-offer — announce a file change
export const fileOffer = {
  preencode (state, m) {
    c.string.preencode(state, m.path)
    c.buffer.preencode(state, toBuffer32(m.contentHash))
    c.uint.preencode(state, m.size)
    c.uint.preencode(state, m.mtime)
    c.uint8.preencode(state, m.op)
  },
  encode (state, m) {
    c.string.encode(state, m.path)
    c.buffer.encode(state, toBuffer32(m.contentHash))
    c.uint.encode(state, m.size)
    c.uint.encode(state, m.mtime)
    c.uint8.encode(state, m.op)
  },
  decode (state) {
    return {
      path: c.string.decode(state),
      contentHash: c.buffer.decode(state).toString('hex'),
      size: c.uint.decode(state),
      mtime: c.uint.decode(state),
      op: c.uint8.decode(state)
    }
  }
}

// Message 2: file-request — request a file transfer
export const fileRequest = {
  preencode (state, m) {
    c.string.preencode(state, m.path)
    c.buffer.preencode(state, toBuffer32(m.contentHash))
    c.buffer.preencode(state, m.chunksHave || Buffer.alloc(0))
  },
  encode (state, m) {
    c.string.encode(state, m.path)
    c.buffer.encode(state, toBuffer32(m.contentHash))
    c.buffer.encode(state, m.chunksHave || Buffer.alloc(0))
  },
  decode (state) {
    return {
      path: c.string.decode(state),
      contentHash: c.buffer.decode(state).toString('hex'),
      chunksHave: c.buffer.decode(state)
    }
  }
}

// ── Transfer Messages (3-8) ──────────────────────────────────

// Message 3: chunk-hashes — chunk hash list for a requested file
//
// `more` (paging flag) is appended last. A very large file's
// chunk list serializes past the 16 MiB-1 Noise frame limit
// (@hyperswarm/secret-stream MAX_ATOMIC_WRITE), so the protocol splits it into
// several chunkHashes frames: every page but the last sets more:1, the final
// page sets more:0. The receiver concatenates pages (in arrival order, keyed by
// path) before dispatching. Appended last so a pre-paging peer that omits it
// decodes more:0 — i.e. as a single, complete page (back-compatible).
export const chunkHashes = {
  preencode (state, m) {
    c.string.preencode(state, m.path)
    c.uint8.preencode(state, m.tier)
    chunkInfoArray.preencode(state, m.chunks)
    c.uint8.preencode(state, m.more || 0)
  },
  encode (state, m) {
    c.string.encode(state, m.path)
    c.uint8.encode(state, m.tier)
    chunkInfoArray.encode(state, m.chunks)
    c.uint8.encode(state, m.more || 0)
  },
  decode (state) {
    const path = c.string.decode(state)
    const tier = c.uint8.decode(state)
    const chunks = chunkInfoArray.decode(state)
    // A frame from a pre-paging peer has no trailing byte → more:0.
    const more = state.start < state.end ? c.uint8.decode(state) : 0
    return { path, tier, chunks, more }
  }
}

// Message 4: chunk-need — tell sender which chunks to send
export const chunkNeed = {
  preencode (state, m) {
    c.string.preencode(state, m.path)
    uintArray.preencode(state, m.indices)
  },
  encode (state, m) {
    c.string.encode(state, m.path)
    uintArray.encode(state, m.indices)
  },
  decode (state) {
    return {
      path: c.string.decode(state),
      indices: uintArray.decode(state)
    }
  }
}

// Message 5: chunk-data — send chunk bytes
export const chunkData = {
  preencode (state, m) {
    c.string.preencode(state, m.path)
    c.uint.preencode(state, m.index)
    c.buffer.preencode(state, m.data)
  },
  encode (state, m) {
    c.string.encode(state, m.path)
    c.uint.encode(state, m.index)
    c.buffer.encode(state, m.data)
  },
  decode (state) {
    return {
      path: c.string.decode(state),
      index: c.uint.decode(state),
      data: c.buffer.decode(state)
    }
  }
}

// Message 6: chunk-cancel — cancel a pending transfer
export const chunkCancel = {
  preencode (state, m) {
    c.string.preencode(state, m.path)
    // P5 hotswap: optional per-chunk cancel. Appended so pre-0.3.0 peers still
    // decode {path} and ignore the trailing bytes; absent = whole-transfer cancel.
    if (m.indices && m.indices.length) c.array(c.uint).preencode(state, m.indices)
  },
  encode (state, m) {
    c.string.encode(state, m.path)
    if (m.indices && m.indices.length) c.array(c.uint).encode(state, m.indices)
  },
  decode (state) {
    const path = c.string.decode(state)
    // Keep the pre-0.3.0 {path} shape byte-for-byte when no indices trail, so a
    // whole-transfer cancel decodes identically on old and new peers.
    if (state.start < state.end) return { path, indices: c.array(c.uint).decode(state) }
    return { path }
  }
}

// Message 7: transfer-complete — confirm file fully received
export const transferComplete = {
  preencode (state, m) {
    c.string.preencode(state, m.path)
    c.buffer.preencode(state, toBuffer32(m.contentHash))
  },
  encode (state, m) {
    c.string.encode(state, m.path)
    c.buffer.encode(state, toBuffer32(m.contentHash))
  },
  decode (state) {
    return {
      path: c.string.decode(state),
      contentHash: c.buffer.decode(state).toString('hex')
    }
  }
}

// Message 8: conflict — notify peer of a detected conflict
export const conflict = {
  preencode (state, m) {
    c.string.preencode(state, m.path)
    c.buffer.preencode(state, toBuffer32(m.myHash))
    c.buffer.preencode(state, toBuffer32(m.theirHash))
    c.buffer.preencode(state, toBuffer32(m.ancestorHash || Buffer.alloc(32)))
  },
  encode (state, m) {
    c.string.encode(state, m.path)
    c.buffer.encode(state, toBuffer32(m.myHash))
    c.buffer.encode(state, toBuffer32(m.theirHash))
    c.buffer.encode(state, toBuffer32(m.ancestorHash || Buffer.alloc(32)))
  },
  decode (state) {
    return {
      path: c.string.decode(state),
      myHash: c.buffer.decode(state).toString('hex'),
      theirHash: c.buffer.decode(state).toString('hex'),
      ancestorHash: c.buffer.decode(state).toString('hex')
    }
  }
}

// ── Tree Messages (9-11) — 0.5a extension ────────────────────

// Encode/decode an array of tree entries: { kind, exec, name, childHash, size }
const treeEntryArray = {
  preencode (state, arr) {
    c.uint32.preencode(state, arr.length)
    for (const e of arr) {
      c.uint8.preencode(state, e.kind)
      c.uint8.preencode(state, e.exec || 0)
      c.string.preencode(state, e.name)
      state.end += 32 // childHash fixed32
      c.uint.preencode(state, e.size || 0)
    }
  },
  encode (state, arr) {
    c.uint32.encode(state, arr.length)
    for (const e of arr) {
      c.uint8.encode(state, e.kind)
      c.uint8.encode(state, e.exec || 0)
      c.string.encode(state, e.name)
      toBuffer32(e.childHash).copy(state.buffer, state.start, 0, 32)
      state.start += 32
      c.uint.encode(state, e.size || 0)
    }
  },
  decode (state) {
    const len = c.uint32.decode(state)
    const arr = []
    for (let i = 0; i < len; i++) {
      const kind = c.uint8.decode(state)
      const exec = c.uint8.decode(state)
      const name = c.string.decode(state)
      const childHash = state.buffer.subarray(state.start, state.start + 32).toString('hex')
      state.start += 32
      const size = c.uint.decode(state)
      arr.push({ kind, exec, name, childHash, size })
    }
    return arr
  }
}

// Message 9: tree-request — ask peer for a tree by its content hash
//
// `nonce` (per-request id) is appended last; the holder echoes it in every
// treeResponse page so the requester can drop pages from a superseded attempt.
// A pre-nonce peer omits it and decodes 0, which the requester treats as
// "unverifiable".
export const treeRequest = {
  preencode (state, m) {
    c.buffer.preencode(state, toBuffer32(m.hash))
    c.uint.preencode(state, m.nonce || 0)
  },
  encode (state, m) {
    c.buffer.encode(state, toBuffer32(m.hash))
    c.uint.encode(state, m.nonce || 0)
  },
  decode (state) {
    const hash = c.buffer.decode(state).toString('hex')
    const nonce = state.start < state.end ? c.uint.decode(state) : 0
    return { hash, nonce }
  }
}

// Message 10: tree-response — return a tree's entries to the requester
//
// `more` (paging flag) mirrors chunkHashes: a tree too large for one 16 MiB-1
// Noise frame is split into several frames, every page but the last more:1.
// `nonce` echoes the requester's per-request id so pages from a superseded
// attempt are dropped. Both are appended last; a pre-paging peer omits them and
// decodes 0.
export const treeResponse = {
  preencode (state, m) {
    c.buffer.preencode(state, toBuffer32(m.hash))
    treeEntryArray.preencode(state, m.entries)
    c.uint8.preencode(state, m.more || 0)
    c.uint.preencode(state, m.nonce || 0)
  },
  encode (state, m) {
    c.buffer.encode(state, toBuffer32(m.hash))
    treeEntryArray.encode(state, m.entries)
    c.uint8.encode(state, m.more || 0)
    c.uint.encode(state, m.nonce || 0)
  },
  decode (state) {
    const hash = c.buffer.decode(state).toString('hex')
    const entries = treeEntryArray.decode(state)
    const more = state.start < state.end ? c.uint8.decode(state) : 0
    const nonce = state.start < state.end ? c.uint.decode(state) : 0
    return { hash, entries, more, nonce }
  }
}

// Message 11: content-request — fetch a file by its content hash (not path)
// Sender locates any local file matching the hash and serves its chunks.
// `from` carries the requester's profile-key (hex) so the
// holder's serveAuthorizer can authenticate the asker. Appended last → an
// overlay peer that predates this field decodes '' (empty), never crashes.
export const contentRequest = {
  preencode (state, m) {
    c.buffer.preencode(state, toBuffer32(m.contentHash))
    c.buffer.preencode(state, m.chunksHave || Buffer.alloc(0))
    c.string.preencode(state, m.from || '')
  },
  encode (state, m) {
    c.buffer.encode(state, toBuffer32(m.contentHash))
    c.buffer.encode(state, m.chunksHave || Buffer.alloc(0))
    c.string.encode(state, m.from || '')
  },
  decode (state) {
    return {
      contentHash: c.buffer.decode(state).toString('hex'),
      chunksHave: c.buffer.decode(state),
      from: c.string.decode(state)
    }
  }
}

// Message 12: transfer-control — downloader→holder pause/stop notice for a
// content-addressed fetch. state: 0 = paused, 1 = stopped. Appended last so a
// holder that predates this never registers slot 12 and silently ignores it.
export const transferControl = {
  preencode (state, m) {
    c.buffer.preencode(state, toBuffer32(m.contentHash))
    c.uint8.preencode(state, m.state)
  },
  encode (state, m) {
    c.buffer.encode(state, toBuffer32(m.contentHash))
    c.uint8.encode(state, m.state)
  },
  decode (state) {
    return {
      contentHash: c.buffer.decode(state).toString('hex'),
      state: c.uint8.decode(state)
    }
  }
}

// Message 13: transfer-progress — downloader→holder one-shot have-baseline for a
// resumed content-addressed fetch. `have` = bytes the downloader already holds on
// disk at resume, so the holder's "who is downloading" bar reflects the downloader's
// TRUE completion, not only the bytes it re-serves. Appended last so a holder that
// predates this never registers slot 13 and silently ignores it.
export const transferProgress = {
  preencode (state, m) {
    c.buffer.preencode(state, toBuffer32(m.contentHash))
    c.uint.preencode(state, m.have || 0)
  },
  encode (state, m) {
    c.buffer.encode(state, toBuffer32(m.contentHash))
    c.uint.encode(state, m.have || 0)
  },
  decode (state) {
    return {
      contentHash: c.buffer.decode(state).toString('hex'),
      have: c.uint.decode(state)
    }
  }
}
/**
 * HyperOverlay — content-addressed file serving over the V2 protocol.
 *
 * A thin facade over the V2 stack (FileIndex + SyncEngine + TransferManager +
 * OverlayProtocol) for the "serve a file to whoever asks, fetch a file from
 * whoever has it" use case — distinct from V1's local chunk-registry blobs.
 *
 * Model (the deliberate post-Hyperdrive design): the canonical bytes are a
 * REAL FILE ON DISK. The index holds only metadata + chunk maps (no blob
 * bytes), so there is no hypercore storage balloon. A peer fetches a file by
 * its content hash; chunks are read from the source file on demand, streamed,
 * hash-verified, and written to the requester's disk.
 *
 * `autoSync` is OFF: this is on-demand content fetch (requestContent →
 * _onContentRequest), NOT Syncthing-style folder push. Registering a file
 * makes it servable; nothing is offered to peers unsolicited.
 *
 * Requester flow: pre-register a synthetic `content:<hash>` → destPath
 * mapping, requestContent,
 * await the hash-verified transferComplete, walk peers on timeout/mismatch.
 */

import ReadyResource from 'ready-resource'
import fs from 'bare-fs'
import path from 'bare-path'
import os from 'bare-os'
import crypto from 'hypercore-crypto'

import { FileIndex } from './file-index.js'
import { SyncEngine } from './sync-engine.js'
import { TransferManager } from './transfer.js'
import { OverlayProtocol } from './protocol.js'
import { createStreamingHasher } from './chunker.js'

const DEFAULT_PER_PEER_TIMEOUT = 30000
const DEFAULT_IDLE_TIMEOUT = 10000

// Stream-verify a file against its overlay content hash WITHOUT buffering
// it — a readFileSync of a multi-GB blob OOMs the process. Matches
// crypto.data(buffer): blake2b(LEAF_TYPE || uint64-LE(size) || bytes), which is
// exactly createStreamingHasher({ size }). Returns the size so callers can re-seed
// without a second stat.
async function hashOnDisk (filePath) {
  let size
  try { size = fs.statSync(filePath).size } catch { return null }
  const h = createStreamingHasher({ size })
  try {
    await new Promise((resolve, reject) => {
      const rs = fs.createReadStream(filePath)
      rs.on('data', (c) => h.update(c))
      rs.on('end', resolve)
      rs.on('error', reject)
    })
  } catch { return null }
  return { contentHash: h.digest(), size }
}

async function verifyOnDisk (filePath, contentHash) {
  const r = await hashOnDisk(filePath)
  if (!r) return { ok: false, size: 0 }
  return { ok: r.contentHash === contentHash, size: r.size }
}

export class HyperOverlay extends ReadyResource {
  constructor (corestore, opts = {}) {
    super()
    this._corestore = corestore.namespace(opts.namespace || 'overlay-v2')
    this._destDir = opts.destDir || path.join(os.tmpdir(), 'hyper-overlay-v2-fetch')
    this._journalDir = opts.journalDir || null
    this._syncBaseDirs = opts.syncBaseDirs || []
    this._perPeerTimeout = opts.perPeerTimeout || DEFAULT_PER_PEER_TIMEOUT
    this._idleTimeout = opts.idleTimeout || DEFAULT_IDLE_TIMEOUT

    // Serve-authorization + identity opts threaded to OverlayProtocol.
    // serveAuthorizer gates every inbound content-request; localProfileKey stamps
    // outbound content-requests so the remote's gate can authenticate the asker.
    this._serveAuthorizer = opts.serveAuthorizer || null
    this._localProfileKey = opts.localProfileKey || null

    // Per-instance protocol channel id (opts.key) — lets N overlays coexist on ONE shared mux
    // (e.g. a multi-DID daemon: one overlay per DID, each keyed by its roomKey, on one connection).
    // Without it they collide on (PROTOCOL, null) and only the first channel opens.
    this._key = opts.key || null

    // At-rest key for the local index cores (file-index/index-meta/sync-feed).
    this._indexEncryptionKey = opts.indexEncryptionKey || null

    // serve-side download telemetry (sender-side download indicator).
    this._onServeStart = opts.onServeStart || null
    this._onChunkServe = opts.onChunkServe || null
    this._onServeEnd = opts.onServeEnd || null
    this._onServeControl = opts.onServeControl || null
    this._onServeProgress = opts.onServeProgress || null

    // Shared maps the protocol reads: overlayPath → diskPath (for serving an
    // offered/known path), contentHash → diskPath (fast path for content
    // requests). Both populated by registerFile.
    this._filePaths = new Map()
    this._contentHashPaths = new Map()

    // contentHash → pending fetch { destPath, finish, timers, bytesReceived }
    this._pendingContent = new Map()

    // Built lazily on first use (Hyperdrive-style: a drive that never touches
    // its blobs core never opens one). A daemon that never registers, serves,
    // or connects a peer for attachments pays nothing — no feed, no index.
    this._index = null
    this._sync = null
    this._transfer = null
    this._protocol = null
    this._stackPromise = null
  }

  // The protocol must exist synchronously when attachProtocol is called —
  // protomux will NOT pair a channel created after the remote opened theirs
  // (verified). So the stack is built at ready time. _ensure stays as the
  // idempotent builder (used by register/fetch, and as a safety net).
  async _open () { await this._ensure() }

  async _close () {
    // Only tear down what was actually built.
    if (this._protocol) this._protocol.destroy()
    if (this._sync) await this._sync.close()
    if (this._index) await this._index.close()
  }

  // Lazily build the V2 stack. Idempotent + concurrency-safe (a single
  // in-flight promise is shared). No-op cost once built.
  _ensure () {
    if (this._protocol) return Promise.resolve()
    if (this._stackPromise) return this._stackPromise
    this._stackPromise = (async () => {
      const index = new FileIndex(this._corestore, { encryptionKey: this._indexEncryptionKey })
      await index.ready()
      const sync = new SyncEngine(index, this._corestore, { encryptionKey: this._indexEncryptionKey })
      await sync.ready()
      const transfer = new TransferManager(index, { journalDir: this._journalDir })
      const protocol = new OverlayProtocol(sync, transfer, {
        key: this._key,
        filePaths: this._filePaths,
        contentHashPaths: this._contentHashPaths,
        syncBaseDirs: this._syncBaseDirs,
        autoSync: false,
        serveAuthorizer: this._serveAuthorizer,   // serve gate
        localProfileKey: this._localProfileKey,    // outbound identity
        onSynced: (info) => this._onSynced(info),
        onChunkProgress: (info) => this._onChunkProgress(info),
        onServeStart: this._onServeStart,
        onChunkServe: this._onChunkServe,
        onServeEnd: this._onServeEnd,
        onServeControl: this._onServeControl,
        onServeProgress: this._onServeProgress
      })
      try { fs.mkdirSync(this._destDir, { recursive: true }) } catch {}
      if (this._journalDir) { try { fs.mkdirSync(this._journalDir, { recursive: true }) } catch {} }
      this._index = index
      this._sync = sync
      this._transfer = transfer
      this._protocol = protocol
    })()
    return this._stackPromise
  }

  // The host's swarm transport must call this synchronously per connection. The
  // channel MUST be created synchronously — protomux will not pair a channel
  // opened after the remote's (verified). The stack is built at ready, so
  // this._protocol is always present by the time connections arrive.
  // INSTRUMENTED: this used to `return` silently on every guard, which is unobservable from the host.
  // A host wrapping the call in try/catch (the atproto daemon does) sees NO exception and concludes the
  // attach succeeded, while `peerCount` reports 0 either way — `_protocol` being null and "attached but
  // no peers" are indistinguishable from outside. That ambiguity sent a live investigation at the
  // content layer for days when byte transfer was simply never wired up. Attach is load-bearing (byte
  // resolution gates signing), so a no-op here must say so exactly once per reason.
  attachProtocol (mux) {
    if (this.closing || this.closed) return this._logAttachSkip('closing')
    if (!this._protocol) return this._logAttachSkip('protocol-not-built')
    const peer = this._protocol.attach(mux)
    // attach() returns null for a duplicate channel, or one the remote already closed.
    if (!peer) this._logAttachSkip('channel-unavailable')
    return peer
  }

  _logAttachSkip (reason) {
    if (!this._attachSkips) this._attachSkips = new Set()
    if (this._attachSkips.has(reason)) return null
    this._attachSkips.add(reason)
    try {
      console.error(JSON.stringify({
        msg: 'hyper-overlay: attachProtocol did NOT attach — this connection will move NO bytes for this overlay',
        reason,
        overlayKey: this._key ? this._key.toString('hex').slice(0, 16) : null
      }))
    } catch {}
    return null
  }

  get peerCount () { return this._protocol ? this._protocol.peerCount : 0 }

  // The overlay's local-only cores (file-index + version marker + sync feed), so the
  // leftover scan can treat them as wanted and the storage breakdown can size them.
  localCores () {
    const cores = this._index ? this._index.cores : []
    if (this._sync?.feed) cores.push(this._sync.feed)
    return cores
  }

  cleanJournals (maxAge) { try { return this._transfer?.cleanJournals(maxAge) || [] } catch { return [] } }

  /**
   * Make an on-disk file servable by its content hash.
   * @param {string} overlayPath logical path, e.g. '/attachments/<oid>'
   * @param {string} diskPath absolute path to the canonical bytes on disk
   * @param {object} [meta]
   *  meta.contentHash preferred — the oid the caller already computed
   *  meta.size file size (avoids an extra stat if known)
   * @returns {Promise<{ contentHash, size } | null>} null if the source vanished
   */
  // Seed the overlayPath -> disk and contentHash -> disk maps from the PERSISTED FileIndex, using a
  // caller-supplied layout resolver. Returns the number of entries seeded.
  //
  // WHY THIS EXISTS. Both maps are in-memory and populated only by registerFile, and FileIndex
  // deliberately persists no disk path (`putFile` stores contentHash/size/mtime) — layout belongs to
  // the consumer, which is correct: a sidecar has one working tree per repo, an atproto peer has one
  // records dir per DID. But it means that after a RESTART a node can serve only what it has written
  // since boot, even though every file is still on disk and its chunk map is still in the index.
  // `_onContentRequest`'s tier-3 fallback then finds the right index entry by hash and uses the
  // OVERLAY path as if it were a filesystem path, which never exists — so the offer is silently
  // dropped and the requester just times out.
  //
  // Measured cost of that: an atproto co-owner held a record's exact bytes on disk (hash verified
  // equal to the requester's oid) and reported "no connected peer served this oid" for 75+ hours,
  // which blocks the peer from signing at all. pgh-sidecar hit the same wall and solved it with a
  // bespoke pre-seed (OverlayManager.populateFilePaths) plus a protocol subclass; this makes that a
  // first-class operation so every consumer gets it instead of re-deriving it.
  //
  // Cheap on purpose: one index scan, NO re-hashing and NO file reads — the contentHash is already
  // persisted per path, and the consumer supplies path -> disk. It also pays for itself, because
  // tier 3 otherwise re-scans the whole index on EVERY content request; seeded, tier 1 hits instead.
  //
  // resolve: (overlayPath) => absolute disk path | null   (null/throw skips that entry)
  async seedFilePathsFromIndex (resolve) {
    if (typeof resolve !== 'function') throw new Error('seedFilePathsFromIndex: a resolve(overlayPath) function is required')
    await this._ensure()
    let seeded = 0
    for (const f of await this._index.listFiles()) {
      let diskPath = null
      // The ENTRY is passed too. A consumer builds its "already known, skip the
      // repair pass" set from this callback, and a path alone cannot tell a
      // fully-seeded entry from a half-seeded one -- see the count below.
      try { diskPath = resolve(f.path, f) } catch { continue }
      if (!diskPath) continue
      this._filePaths.set(f.path, diskPath)
      if (!f.contentHash) {
        // putFile persists `contentHash: meta.contentHash || null` with a
        // `hashing` flag, so a null hash is a first-class STORED state -- an
        // entry indexed while hashing was still in flight keeps it forever.
        // Such an entry seeds the PATH map but can never be served BY OID.
        //
        // It must NOT count as seeded. It used to, which made the boot log read
        // healthy while the bytes were unreachable, and made consumers treat the
        // entry as already-known so their repair pass skipped the one case it
        // was written for. Cost three production sightings (2026-08-08 136 MiB
        // APK, 2026-08-25 471 MB zip, 2026-08-29 168 MB APK) of a peer being
        // told "no holder" for a file sitting on disk with a matching hash.
        continue
      }
      this._contentHashPaths.set(f.contentHash, diskPath)
      seeded++
    }
    // Deliberately still a NUMBER, but now meaning "entries servable BY OID".
    // atproto-store logs this as "servable-by-oid after restart" -- a claim that
    // was false before this change and is true after it, with no edit there.
    return seeded
  }

  async registerFile (overlayPath, diskPath, meta = {}) {
    await this._ensure()
    // Source can vanish between prepare and register (a file moved out of a
    // shared folder mid-scan). Nothing to serve — bail with null instead of throwing
    // so a routine move doesn't crash the publish path.
    let stat
    try {
      stat = fs.statSync(diskPath)
    } catch {
      return null
    }
    const size = typeof meta.size === 'number' ? meta.size : stat.size
    const contentHash = meta.contentHash || await hashFileOnDisk(diskPath, size)

    await this._index.putFile(overlayPath, { contentHash, size, mtime: stat.mtimeMs })
    this._filePaths.set(overlayPath, diskPath)
    this._contentHashPaths.set(contentHash, diskPath)
    // Build (and cache) the chunk map so a content request can stream
    // immediately without re-chunking under the request. meta.prepare:false
    // skips this eager full second read of the file — the file is already servable
    // via the maps above and the serve path (_onContentRequest) chunks lazily on
    // first request; publishers that already built the chunk map in one pass
    // (prepareForServe) pass false so registration doesn't re-read the file.
    if (meta.prepare !== false) await this._transfer.prepareFile(diskPath, overlayPath)
    // Record in the local change feed (used by the protocol's markSynced
    // bookkeeping; with autoSync off it is not broadcast).
    await this._sync.logPut(overlayPath, { contentHash, size, mtime: stat.mtimeMs, rev: meta.rev }) // rev optional (app version, e.g. atproto TID) for rev-based conflict resolution
    return { contentHash, size }
  }

  // One-pass hash + chunk-map build for the publish path: streams the file
  // ONCE, persists the content-addressed chunk map (durable in FileIndex), and
  // returns the content hash. Replaces a hash-only pass plus a lazy fetch-time
  // re-chunk with a single read, so the first fetcher never waits on chunk indexing.
  // Stop serving a path AND record the deletion in the local change feed (bookkeeping; autoSync is off
  // so it is not broadcast — convergence is an application concern, not this library's). The authoring
  // counterpart to a shim deleting a record. Idempotent.
  async unregisterFile (overlayPath) {
    await this._ensure()
    this._filePaths.delete(overlayPath)
    await this._sync.logDel(overlayPath)
  }

  async prepareForServe (diskPath, opts = {}) {
    await this._ensure()
    // The overlay path below is a throwaway key — byHashOnly persists ONLY the
    // content-addressed chunk map, nothing under this path.
    const prepared = await this._transfer.prepareFile(diskPath, '/mir-prep' + diskPath, { onProgress: opts.onProgress, byHashOnly: true, signal: opts.signal })
    return prepared ? { contentHash: prepared.contentHash, size: prepared.size } : null
  }

  // READ-ONLY: the content hash the bytes currently on disk at `filePath` would be registered under,
  // plus their size. Returns null when the file is absent or unreadable. Writes nothing — no index
  // entry, no registration, no fetch — so it is safe to run against a live store.
  //
  // WHY THIS IS PUBLIC: a content-addressed store's correctness rests on "the bytes at this path hash
  // to the oid the pointer says", and nothing could ask that question from outside. `registerFile`
  // answers it only as a side effect of WRITING an index entry, and `verifyOnDisk` (used by the fetch
  // path) is module-private and boolean-only. So a consumer holding a converged pointer had no way to
  // check its own local file against it — which is exactly how a STALE local file goes unnoticed:
  // OverlayRepoStore.ensureLocal returns a local hit without ever comparing it to the pointer's oid,
  // so a node keeps serving superseded bytes forever and never re-fetches. Found on wj62, where two
  // co-owners held the same 139 converged pointers but different bytes for app.bsky.actor.profile/self
  // (two different avatar blobs), so the signed repo flipped content on every signer change.
  async hashFile (filePath) {
    return hashOnDisk(filePath)
  }

  async evictContent (contentHash) {
    await this._ensure()
    return this._index.evictContent(contentHash)
  }

  async compactIndex (opts) {
    await this._ensure()
    return this._index.compact(opts)
  }

  /**
   * Fetch a file by its content hash. Serves from the local disk copy if we
   * have it; otherwise pulls from a connected peer that does (hash-verified).
   * @param {string} contentHash
   * @param {object} [opts] opts.timeout (idle), opts.destPath
   * @returns {Promise<{ destPath: string, local: boolean, size: number } | null>}
   */
  async fetchFile (contentHash, opts = {}) {
    await this._ensure()

    const localDisk = this._contentHashPaths.get(contentHash)
    if (localDisk) {
      const v = await verifyOnDisk(localDisk, contentHash)
      if (v.ok) return { destPath: localDisk, local: true, size: v.size }
    }

    // Wait briefly for at least one peer — a connection may be mid-handshake
    // (lazy attach) or just forming when the fetch is issued. Without this a
    // fetch issued the instant a peer connects would spuriously 404.
    const peerWaitMs = opts.peerWaitMs || 3000
    for (let waited = 0; this._protocol._peers.size === 0 && waited < peerWaitMs; waited += 100) {
      await new Promise(r => setTimeout(r, 100))
    }
    if (this._protocol._peers.size === 0) {
      // No fetchContent will run, so drop any cancel recorded during the wait — a
      // stale marker would otherwise cancel the next fetch of the same content.
      this._protocol.clearCancelPending(contentHash)
      return null
    }

    // Multi-source: fetch chunks in parallel from ALL connected peers that
    // have the file (torrent-style). The scheduler dedups + fails over.
    const peers = [...this._protocol._peers.values()]
    // opts.mirrorSpool: store the verified blob CONTENT-ADDRESSED at
    // <mirrorSpool>/<contentHash> rather than a throwaway destDir name. This is
    // the mirror path — a node with no working tree of its own fetches files
    // into a content-addressed spool so it durably re-serves them (via the
    // <syncBaseDir>/<contentHash> resolution in _onContentRequest).
    let destPath
    if (opts.destPath) {
      destPath = opts.destPath
    } else if (opts.mirrorSpool) {
      try { fs.mkdirSync(opts.mirrorSpool, { recursive: true }) } catch {}
      destPath = path.join(opts.mirrorSpool, contentHash)
    } else {
      destPath = path.join(
        this._destDir,
        'blob-' + contentHash + '-' + Date.now() + '-' + Math.random().toString(36).slice(2, 8)
      )
    }
    // Whole-file integrity is verified INCREMENTALLY during the transfer (the
    // scheduler passes contentHash to TransferManager, which hashes the file in
    // offset order as chunks land and rejects in finalize on a mismatch). So the
    // assembled file is already verified here — no trailing whole-file re-read.
    let result
    try {
      result = await this._protocol.fetchContent(contentHash, peers, {
        destPath,
        timeout: opts.timeout,
        onProgress: opts.onProgress || (() => {}),   // forward bytes/total
        onVerify: opts.onVerify,                      // resume re-verify fraction
        onEnd: opts.onEnd                             // terminal diagnostic (reason + bytes/chunks)
      })
    } catch (err) {
      // An integrity failure or an explicit cancel/pause is distinct from a
      // no-holder / stall — surface it so the caller doesn't treat it as a failure.
      if (err?.code === 'EHASHMISMATCH' || err?.code === 'ECANCELLED') throw err
      // A local I/O error (full disk / read-only / permission / vanished
      // mount) is not a no-holder — surface it so the consumer can pause rather than
      // retry forever.
      if (err?.code === 'ENOSPC' || err?.code === 'EACCES' || err?.code === 'EROFS' || err?.code === 'EPERM' || err?.code === 'ENOENT') throw err
      return null
    }
    const size = result?.size ?? fs.statSync(destPath).size
    // Seeding multiplication: register the verified blob locally so this node
    // now SERVES these chunks to other peers too. A file held by N peers then
    // gets faster as more peers fetch it (torrent-style). Best-effort — the
    // fetch still succeeds even if re-registration fails. Skipped if a peer
    // raced us to register the same hash (registerFile is idempotent-safe).
    // reSeed:false — opt-out for consumers that should hold nothing.
    if (opts.reSeed !== false && !this._contentHashPaths.has(contentHash)) {
      try {
        await this.registerFile('/attachments/' + contentHash, destPath, { contentHash, size })
      } catch {}
    }
    return { destPath, local: false, size }
  }

  // Stop an in-flight fetchFile for this content hash. opts.discardPartial
  // true unlinks the partial (cancel), false keeps it for resume (pause). The
  // pending fetchFile rejects with ECANCELLED, which the caller treats as not-a-failure.
  cancelFetch (contentHash, opts = {}) {
    return this._protocol ? this._protocol.cancelContent(contentHash, opts) : false
  }

  // Tell holders we stopped pulling this hash when there's no in-flight fetch
  // to tear down (e.g. discarding an already-paused transfer), so their indicator clears.
  notifyTransferStopped (contentHash) {
    return this._protocol ? this._protocol.sendStopControl(contentHash) : false
  }

  _destPathFor (contentHash) {
    return path.join(this._destDir, 'blob-' + contentHash)
  }

  _fetchFromPeer (peer, contentHash, opts = {}) {
    const syntheticPath = 'content:' + contentHash
    const destPath = path.join(
      this._destDir,
      'blob-' + contentHash + '-' + Date.now() + '-' + Math.random().toString(36).slice(2, 8)
    )
    // The protocol's chunk handlers write to whatever _filePaths maps the
    // synthetic path to. Per-attempt destPath so concurrent peer tries don't
    // clobber one another.
    this._filePaths.set(syntheticPath, destPath)

    return new Promise((resolve, reject) => {
      let settled = false
      const finish = (err, result) => {
        if (settled) return
        settled = true
        clearTimeout(timer)
        clearTimeout(pending.idleTimer)
        this._pendingContent.delete(contentHash)
        if (err) reject(err); else resolve(result)
      }
      const timer = setTimeout(() => {
        finish(new Error('content request timed out: ' + contentHash.slice(0, 12)))
      }, opts.timeout || this._perPeerTimeout)
      const idleFire = () => finish(new Error('peer went silent mid-stream: ' + contentHash.slice(0, 12)))
      const pending = {
        syntheticPath, destPath, finish, peer, contentHash,
        bytesReceived: 0,
        idleTimer: setTimeout(idleFire, this._idleTimeout),
        idleFire
      }
      this._pendingContent.set(contentHash, pending)
      this._protocol.requestContent(peer, contentHash, null)
    })
  }

  _onChunkProgress (info) {
    if (!info || !info.path || !info.path.startsWith('content:')) return
    const contentHash = info.path.slice('content:'.length)
    const pending = this._pendingContent.get(contentHash)
    if (!pending) return
    pending.bytesReceived += (info.bytes || 0)
    clearTimeout(pending.idleTimer)
    pending.idleTimer = setTimeout(pending.idleFire, this._idleTimeout)
  }

  // The V2 chunk flow does NOT verify the reassembled file against the
  // advertised hash (that's the caller's job in this protocol). We do it here
  // so fetchFile never returns un-verified bytes.
  _onSynced (info) {
    if (!info || info.direction !== 'pull') return
    if (!info.path || !info.path.startsWith('content:')) return
    const contentHash = info.path.slice('content:'.length)
    const pending = this._pendingContent.get(contentHash)
    if (!pending) return
    try {
      const data = fs.readFileSync(pending.destPath)
      const actual = crypto.data(data).toString('hex')
      if (actual !== contentHash) {
        pending.finish(Object.assign(
          new Error('content-hash mismatch: expected ' + contentHash.slice(0, 12) + '…, got ' + actual.slice(0, 12) + '…'),
          { code: 'EHASHMISMATCH', expected: contentHash, actual }
        ))
        return
      }
      pending.finish(null, data)
    } catch (err) {
      pending.finish(err)
    }
  }
}

// Stream a file through the chunker's hasher to get its oid without buffering
// the whole file in memory (matches /api/upload's createStreamingHasher oid).
async function hashFileOnDisk (diskPath, size) {
  const hasher = createStreamingHasher({ size })
  for await (const buf of fs.createReadStream(diskPath)) hasher.update(buf)
  return hasher.digest()
}
/**
 * Pointer Format — git clean/smudge filter interchange format
 *
 * Stored in git objects instead of actual binary file content.
 * Two formats based on chunk count:
 *
 * Small file (≤64 chunks, inline):
 *   hyper-overlay v1
 *   oid blake2b:<file-hash>
 *   size <bytes>
 *   chunks <count>
 *   blake2b:<chunk-0-hash> <chunk-0-size>
 *   blake2b:<chunk-1-hash> <chunk-1-size>
 *   ...
 *
 * Large file (>64 chunks, manifest reference):
 *   hyper-overlay v1
 *   oid blake2b:<file-hash>
 *   size <bytes>
 *   chunks <count>
 *   manifest blake2b:<manifest-hash>
 */

const VERSION = 1
const HEADER = 'hyper-overlay v1'
const INLINE_MAX = 64

/**
 * Serialize file info to pointer string
 *
 * @param {Object} info
 * @param {string} info.oid - blake2b hex hash of complete file
 * @param {number} info.size - total file size in bytes
 * @param {number} info.chunkCount - number of chunks
 * @param {Array<{hash: string, size: number}>} [info.chunks] - inline chunk list (≤64)
 * @param {string} [info.manifestHash] - manifest hash for large files (>64 chunks)
 * @returns {string}
 */
export function serialize (info) {
  const lines = [
    HEADER,
    `oid blake2b:${info.oid}`,
    `size ${info.size}`,
    `chunks ${info.chunkCount}`
  ]

  if (info.chunks && info.chunkCount <= INLINE_MAX) {
    for (const c of info.chunks) {
      lines.push(`blake2b:${c.hash} ${c.size}`)
    }
  } else if (info.manifestHash) {
    lines.push(`manifest blake2b:${info.manifestHash}`)
  }

  return lines.join('\n') + '\n'
}

/**
 * Parse a pointer string back to file info
 *
 * @param {string} text - Pointer file content
 * @returns {Object} { version, oid, size, chunkCount, chunks, manifestHash }
 */
export function parse (text) {
  const lines = text.trim().split('\n')

  // Minimum viable pointer is 3 lines: header + oid + size. Older
  // serializers (pre-chunk-metadata) produced this 3-line shape; the
  // chunks line + inline chunk list / manifest came later. parsers must
  // accept the legacy form so pre-chunks pointers in existing repos still
  // resolve via oid (the only field needed for fetch-by-oid).
  if (lines.length < 3 || lines[0] !== HEADER) {
    throw new Error('Invalid hyper-overlay pointer')
  }

  const oidMatch = lines[1].match(/^oid blake2b:([0-9a-f]{64})$/)
  if (!oidMatch) throw new Error('Invalid pointer: bad oid line')

  const sizeMatch = lines[2].match(/^size (\d+)$/)
  if (!sizeMatch) throw new Error('Invalid pointer: bad size line')

  // chunks line is optional for legacy compat; default to chunkCount 0.
  let chunkCount = 0
  if (lines.length >= 4) {
    const chunksMatch = lines[3].match(/^chunks (\d+)$/)
    if (chunksMatch) chunkCount = parseInt(chunksMatch[1], 10)
    // If line 3 isn't a `chunks N` declaration, treat as legacy 3-line
    // pointer (chunks omitted) and let further-line parsing decide via
    // its own startsWith checks below.
  }

  const result = {
    version: VERSION,
    oid: oidMatch[1],
    size: parseInt(sizeMatch[1], 10),
    chunkCount,
    chunks: null,
    manifestHash: null
  }

  if (lines.length > 4) {
    const line4 = lines[4]

    if (line4.startsWith('manifest blake2b:')) {
      result.manifestHash = line4.slice('manifest blake2b:'.length)
    } else if (line4.startsWith('blake2b:')) {
      // Inline chunk list
      result.chunks = []
      for (let i = 4; i < lines.length; i++) {
        const parts = lines[i].split(' ')
        if (parts.length !== 2 || !parts[0].startsWith('blake2b:')) break
        result.chunks.push({
          hash: parts[0].slice('blake2b:'.length),
          size: parseInt(parts[1], 10)
        })
      }
    }
  }

  return result
}

/**
 * Check if a string is a hyper-overlay pointer
 *
 * @param {string|Buffer} content
 * @returns {boolean}
 */
export function isPointer (content) {
  const text = typeof content === 'string' ? content : content.toString('utf-8')
  return text.startsWith(HEADER + '\n')
}

export { INLINE_MAX }
/**
 * OverlayProtocol — Protomux channel for sync + transfer
 *
 * Sync approach: each side sends its local feed entries directly via
 * file-offer messages. No Hypercore feed replication needed — the feed
 * entries are small JSON objects sent over our own Protomux channel.
 *
 * Flow:
 *  1. Channel opens → both send sync-state (feed length)
 *  2. Side with more entries sends file-offers for each change
 *  3. Receiver auto-requests files it doesn't have
 *  4. Sender chunks on demand → streams chunks → receiver writes to disk
 */

import path from 'bare-path'
import * as messages from './messages.js'
import { hashChunk, selectTier } from './chunker.js'
import { ChunkScheduler } from './chunk-scheduler.js'
import fs from 'bare-fs'

const PROTOCOL = 'hyper-overlay/v2'
const VERSION = 2
const CAP_LOCAL_FILES = 0x01
const CAP_ADAPTIVE_CHUNKS = 0x02

// A file's chunk list, shipped in one frame, can exceed the
// 16 MiB-1 Noise transport limit (@hyperswarm/secret-stream MAX_ATOMIC_WRITE):
// a 1.25 TB file at tier 3 is ~1.2M entries ≈ ~44 MB, which the secret-stream
// rejects ("Message is too large for an atomic write"), dropping the connection
// before a byte ships. So chunkHashes is paged into frames of ≤ this many
// entries. Each wire entry is 32 B (hash) + ≤5 B (varint length) ≈ 37 B, so
// 100k entries ≈ 3.7 MB/frame — well under the limit even after Protomux's
// ≤8 MiB send-batching.
const MAX_CHUNKS_PER_MSG = 100000

// F2: hard ceiling on chunk-hash entries accumulated across a paged chunkHashes
// stream. Far above any real file's chunk count (a 1.25 TB tier-3 file is ~1.2M
// entries), so it never trips legitimately — but it bounds an authorized-but-rogue
// seeder that streams `more:1` pages forever (each buffered page re-arms the idle
// watchdog, so the stall timer never fires). Unlike treeResponse, chunkHashes had
// no such cap. ~16M entries ≈ a few hundred MB worst case before we drop the list.
const MAX_CHUNK_HASHES_ACCUM = 16 * 1024 * 1024

// Tree entries are variable length (name is a var-string), unlike the fixed-width
// chunkHashes entries, so treeResponse pages by an encoded-byte budget rather than
// a fixed count. 4 MiB keeps each frame well under the atomic-write limit even
// after Protomux's ≤8 MiB send-batching.
const MAX_TREE_BYTES_PER_MSG = 4 * 1024 * 1024

// Defensive ceiling on the bytes a requester will accumulate across a paged
// treeResponse. A single-directory tree is orders of magnitude smaller; this only
// bounds memory so a peer streaming pages endlessly rejects the request instead
// of OOMing.
const MAX_TREE_RESPONSE_BYTES = 256 * 1024 * 1024

// transfer-control (message 12) states, downloader→holder.
const CONTROL_PAUSED = 0
const CONTROL_STOPPED = 1

// Abandon a serve loop whose stream neither drains nor closes within
// this window (a wedged-but-TCP-alive peer); the receiver re-requests, so it self-heals.
const DRAIN_TIMEOUT_MS = 60000

export class OverlayProtocol {
  constructor (syncEngine, transferManager, opts = {}) {
    this._syncEngine = syncEngine
    this._transferManager = transferManager
    this._corestore = opts.corestore || null
    this._overlayKey = opts.key || null
    this._peers = new Map()
    // Muxes we've registered a pair() callback on, so we register exactly one per mux. See attach().
    this._paired = new Set()
    this._filePaths = opts.filePaths || new Map()
    this._syncBaseDirs = opts.syncBaseDirs || []
    this._defaultStrategy = opts.defaultStrategy || 'prompt'
    this._autoSync = opts.autoSync !== false

    this._conflictCb = opts.onConflict || null
    this._syncedCb = opts.onSynced || null
    this._fileOfferCb = opts.onFileOffer || null
    // Called for every chunk that arrives on this peer. Lets callers
    // (e.g. NetworkFetcher) implement silent-peer watchdogs by resetting
    // an idle timer on every chunk. Receives { path, index, bytes, peer }.
    this._chunkProgressCb = opts.onChunkProgress || null
    // serve-side telemetry, symmetric to onChunkProgress — fired when WE
    // serve a peer (the sender-side download indicator). onServeStart({ path, peer,
    // from, total }) once a peer is authorized to fetch; onChunkServe({ path, peer,
    // from, bytes }) per served chunk; onServeEnd({ path, peer, from }) on close.
    this._serveStartCb = opts.onServeStart || null
    this._chunkServeCb = opts.onChunkServe || null
    this._serveEndCb = opts.onServeEnd || null
    // A downloader paused/stopped a hash WE serve. { path, peer, from, state }.
    this._serveControlCb = opts.onServeControl || null
    // A downloader reported its on-disk have-bytes for a hash WE serve (resume
    // baseline). { path, peer, from, have }.
    this._serveProgressCb = opts.onServeProgress || null

    // 0.5a: content-hash → local disk path, for responding to content-requests
    this._contentHashPaths = opts.contentHashPaths || new Map()
    // 0.5a: tree-request timeout (ms)
    this._treeRequestTimeout = opts.treeRequestTimeout || 30000
    // Cap on bytes accumulated across a paged treeResponse.
    this._maxTreeResponseBytes = opts.maxTreeResponseBytes || MAX_TREE_RESPONSE_BYTES
    // Multi-source: synthetic path 'content:<hash>' → ChunkScheduler. When set,
    // _onChunkHashes/_onChunkData delegate to the scheduler (parallel fetch
    // across peers) instead of the legacy single-peer auto-flow.
    this._schedulers = new Map()
    // 'content:<hash>' cancelled before its scheduler existed (the caller's
    // peer-wait window) — fetchContent honors it the moment it creates the scheduler.
    this._cancelPending = new Set()

    // serve authorization. _serveAuthorizer(peer, from, hash) →
    // boolean gates every inbound content-request; deny is a silent drop
    // (indistinguishable from "I don't hold it" — no membership oracle).
    // _localProfileKey is stamped on outbound content-requests as msg.from.
    this._serveAuthorizer = opts.serveAuthorizer || null
    this._localProfileKey = opts.localProfileKey || null
  }

  /**
   * Multi-source fetch of a file by content hash from several peers in
   * parallel (torrent-style). The caller pre-registers _filePaths['content:'
   * + contentHash] = destPath. Resolves when the file is assembled + verified.
   *
   * @param {string} contentHash
   * @param {Array} peers peer objects to fan the request to
   * @param {object} [opts] { destPath, cap, timeout, onProgress }
   * @returns {Promise<void>}
   */
  fetchContent (contentHash, peers, opts = {}) {
    const p = 'content:' + contentHash
    // Content-addressed dedup: a concurrent fetch of the SAME hash (a
    // different file/transfer with identical bytes) joins the in-flight one instead
    // of failing — await its verified bytes, then copy to our destPath. If the leader
    // was cancelled, re-issue our own fetch (the scheduler entry is already gone).
    const inflight = this._schedulers.get(p)
    if (inflight) {
      return inflight.shared.then(
        (res) => {
          if (opts.destPath && opts.destPath !== inflight.destPath) {
            try {
              fs.copyFileSync(inflight.destPath, opts.destPath)
            } catch (err) {
              // The leader's shared temp is already gone — the leader's caller
              // (e.g. pgh NetworkFetcher) unlinks its destPath as soon as it has
              // read+verified the bytes, which can race ahead of this joiner's
              // copy. Re-issue our own fetch, mirroring the ECANCELLED path.
              if (err?.code === 'ENOENT') return this.fetchContent(contentHash, peers, opts)
              throw err
            }
          }
          return res
        },
        (err) => { if (err?.code === 'ECANCELLED') return this.fetchContent(contentHash, peers, opts); throw err },
      )
    }
    const sched = new ChunkScheduler({
      path: p,
      destPath: opts.destPath,
      transfer: this._transferManager,
      sendNeed: (peer, indices) => peer.msgs.chunkNeed.send({ path: p, indices }),
      // P5 hotswap: best-effort tell a slow peer to stop serving reassigned chunks.
      sendCancel: (peer, indices) => { try { peer.msgs.chunkCancel.send({ path: p, indices }) } catch {} },
      cap: opts.cap,
      timeout: opts.timeout,
      onProgress: opts.onProgress,
      onVerify: opts.onVerify,
      onEnd: opts.onEnd,
      onBaseline: (have) => this.sendTransferProgress(contentHash, have),
      contentHash   // verify the whole-file hash incrementally during the transfer
    })
    this._schedulers.set(p, sched)
    // shared promise so joiners (above) can await the same completion —
    // calling sched.promise() twice would overwrite its resolve/reject handlers.
    sched.shared = sched.promise().finally(() => {
      this._schedulers.delete(p)
      // F2: drop any half-accumulated paged chunk list for this path across peers, so a
      // same-key retry (content:<hash> reused after a cancel mid-paging) can't append
      // fresh pages onto a stale partial list.
      for (const pr of this._peers.values()) if (pr._chunkHashPages) pr._chunkHashPages.delete(p)
    })
    // honor a cancel/pause that arrived before this scheduler existed.
    if (this._cancelPending.delete(p)) { sched.cancel(); return sched.shared }
    for (const peer of peers) this.requestContent(peer, contentHash, null)
    return sched.shared
  }

  // Stop an in-flight multi-source fetch. discardPartial:true unlinks the
  // partial (cancel); false keeps it for resume (pause). The scheduler's promise
  // rejects with ECANCELLED and its .finally() removes it from _schedulers. When no
  // scheduler exists yet (the caller is still in its peer-wait window), remember the
  // intent so fetchContent cancels the scheduler the instant it is created.
  async cancelContent (contentHash, { discardPartial = false, signal = true } = {}) {
    const p = 'content:' + contentHash
    const sched = this._schedulers.get(p)
    // No scheduler → the fetch never sent a content-request, so no holder has a serve
    // row for us; skip the (wasted) broadcast and just record the pre-scheduler cancel.
    if (!sched) { this._cancelPending.add(p); return false }
    // Tell holders we paused (keep partial) or stopped (discard) BEFORE local teardown,
    // so their sender-side indicator reacts now, not after the idle sweep. signal:false
    // suppresses it (a supersede is a restart, not a user stop).
    if (signal) this._sendTransferControl(contentHash, discardPartial ? CONTROL_STOPPED : CONTROL_PAUSED)
    // Stop accepting chunks first so the pause hash-drain converges on a stable frontier.
    sched.cancel()
    if (discardPartial) this._transferManager.cancel(sched.destPath)
    else await this._transferManager.pause(sched.destPath)
    return true
  }

  // Tell holders we stopped pulling a hash whose local fetch is already gone (e.g.
  // discarding an already-paused transfer) — no scheduler to tear down here.
  sendStopControl (contentHash) { this._sendTransferControl(contentHash, CONTROL_STOPPED) }

  // Best-effort broadcast to all connected holders. A holder with no serve-ledger entry
  // for us (or no slot for this message) just drops it; wrapped per-peer so a closing
  // channel or an old peer can't throw.
  _broadcast (msgName, payload) {
    for (const [, peer] of this._peers) {
      try { peer.msgs[msgName]?.send(payload) } catch {}
    }
  }

  _sendTransferControl (contentHash, state) { this._broadcast('transferControl', { contentHash, state }) }

  // Tell holders our current on-disk have-bytes for a hash we're (re)fetching, so their
  // sender-side bar mirrors our TRUE progress rather than only the bytes they re-serve.
  sendTransferProgress (contentHash, have) { this._broadcast('transferProgress', { contentHash, have }) }

  // Drop a cancel recorded before a scheduler existed when the fetch is
  // abandoned without ever reaching fetchContent (no peer connected) — otherwise the
  // marker would cancel the next fetch of the same content.
  clearCancelPending (contentHash) { this._cancelPending.delete('content:' + contentHash) }

  setContentHashPaths (map) { this._contentHashPaths = map }

  attach (mux) {
    if (this._peers.has(mux)) return this._peers.get(mux)

    const self = this

    // Attach used to be ONE-SHOT and order-sensitive, which silently killed byte transfer for the life
    // of a connection. If the remote has no matching (protocol, id) channel at the moment we attach —
    // it hasn't booted this DID's overlay yet, or is mid-restart — protomux tears our channel down,
    // onclose drops the peer, and NOTHING ever re-created it. The remote attaching a second later did
    // not help: `createChannel` then returns null ("the remote has already closed this one") and there
    // was no path back. Meanwhile the connection stays perfectly healthy for everything else, so
    // corestore keeps replicating and the pointers keep converging while the BYTES never move again —
    // which is precisely the fault seen in production (overlayPeers:0, forever, on a live connection).
    //
    // mux.pair() is protomux's mechanism for exactly this race: it fires whenever the remote REQUESTS
    // this (protocol, id), so a late or restarted peer gets a channel created on demand. Registered
    // once per mux, and left registered after a close so re-pairing keeps working for the connection's
    // whole life.
    if (!this._paired.has(mux)) {
      this._paired.add(mux)
      try {
        mux.pair({ protocol: PROTOCOL, id: this._overlayKey || null }, () => { try { self.attach(mux) } catch {} })
      } catch { this._paired.delete(mux) }
    }

    const channel = mux.createChannel({
      protocol: PROTOCOL,
      id: this._overlayKey || null,
      onopen () {
        const peer = self._peers.get(mux)
        if (peer) self._onOpen(peer)
      },
      onclose () {
        const peer = self._peers.get(mux)
        self._peers.delete(mux)
        // Failover: let any active multi-source fetch reassign this peer's
        // inflight chunks to the remaining peers.
        if (peer) for (const sched of self._schedulers.values()) sched.removePeer(peer)
        // Fail in-flight tree requests now, so a mid-stream disconnect rejects
        // promptly instead of stranding the request (and its buffered pages)
        // until the idle timeout fires.
        if (peer) self._failPendingTrees(peer, new Error('channel closed'))
        // tell the sender-side indicator this peer is gone for every file
        // it was pulling, so a disconnect mid-download clears its row promptly.
        if (peer && self._serveEndCb) {
          for (const [synthPath, from] of peer.authorizedServe) {
            try { self._serveEndCb({ path: synthPath, peer, from }) } catch {}
          }
        }
      }
    })

    if (!channel) return null

    // protomux returns null for a duplicate channel, or one the remote has already closed. Before the
    // pair() registration above this could not be recovered from; now the pair callback will re-drive
    // attach() when the remote asks again, so returning cleanly here is the correct behaviour. It also
    // stops a null-deref on the addMessage calls below, which the consumer's try/catch would have
    // swallowed into a silent "this DID has no byte transfer".
    if (!channel) return null

    const peer = {
      mux, channel, remoteFeedKey: null, remoteSeq: 0, msgs: {},
      pendingTrees: new Map(), // hash → { resolve, reject, timer, timeout, nonce, pages, pageBytes }
      // synthetic serve-paths this peer was authorized for via a
      // GATED _onContentRequest, mapped to the requester profileKey (msg.from).
      // _onChunkNeed serves bytes only for paths in here, so a peer cannot pull
      // bytes by sending chunkNeed/fileRequest directly for a registered path it
      // was never authorized to fetch; the value flows the requester identity to
      // the serve telemetry.
      authorizedServe: new Map()
    }

    peer.msgs.syncState = channel.addMessage({ encoding: messages.syncState, onmessage: (msg) => self._onSyncState(peer, msg) })
    peer.msgs.fileOffer = channel.addMessage({ encoding: messages.fileOffer, onmessage: (msg) => self._onFileOffer(peer, msg) })
    peer.msgs.fileRequest = channel.addMessage({ encoding: messages.fileRequest, onmessage: (msg) => self._onFileRequest(peer, msg) })
    peer.msgs.chunkHashes = channel.addMessage({ encoding: messages.chunkHashes, onmessage: (msg) => self._onChunkHashes(peer, msg) })
    peer.msgs.chunkNeed = channel.addMessage({ encoding: messages.chunkNeed, onmessage: (msg) => self._onChunkNeed(peer, msg) })
    peer.msgs.chunkData = channel.addMessage({ encoding: messages.chunkData, onmessage: (msg) => self._onChunkData(peer, msg) })
    peer.msgs.chunkCancel = channel.addMessage({ encoding: messages.chunkCancel, onmessage: (msg) => self._onChunkCancel(peer, msg) })
    peer.msgs.transferComplete = channel.addMessage({ encoding: messages.transferComplete, onmessage: (msg) => self._onTransferComplete(peer, msg) })
    peer.msgs.conflict = channel.addMessage({ encoding: messages.conflict, onmessage: (msg) => self._onConflictMsg(peer, msg) })

    // 0.5a — tree messages (backward-compatible additions)
    peer.msgs.treeRequest = channel.addMessage({ encoding: messages.treeRequest, onmessage: (msg) => self._onTreeRequest(peer, msg) })
    peer.msgs.treeResponse = channel.addMessage({ encoding: messages.treeResponse, onmessage: (msg) => self._onTreeResponse(peer, msg) })
    peer.msgs.contentRequest = channel.addMessage({ encoding: messages.contentRequest, onmessage: (msg) => self._onContentRequest(peer, msg) })
    // Appended-last slots: ids 0-11 stay fixed for peers without 12/13, which just
    // never register these channels and ignore the frames.
    peer.msgs.transferControl = channel.addMessage({ encoding: messages.transferControl, onmessage: (msg) => self._onTransferControl(peer, msg) })
    peer.msgs.transferProgress = channel.addMessage({ encoding: messages.transferProgress, onmessage: (msg) => self._onTransferProgress(peer, msg) })

    this._peers.set(mux, peer)
    channel.open({ version: VERSION, capabilities: CAP_LOCAL_FILES | CAP_ADAPTIVE_CHUNKS })
    return peer
  }

  // Explicit teardown — unlike an incidental channel close (where the pair callback must SURVIVE so a
  // returning peer can re-pair), detach means we are done with this mux, so drop the pairing too.
  detach (mux) {
    if (this._paired.delete(mux)) {
      try { mux.unpair({ protocol: PROTOCOL, id: this._overlayKey || null }) } catch {}
    }
    const peer = this._peers.get(mux)
    if (!peer) return
    peer.channel.close()
    this._peers.delete(mux)
  }

  setFilePaths (map) { this._filePaths = map }

  broadcastOffer (overlayPath, meta, op) {
    const msg = {
      path: overlayPath,
      contentHash: meta.contentHash || '0'.repeat(64),
      size: meta.size || 0,
      mtime: meta.mtime || 0,
      op
    }
    for (const [, peer] of this._peers) {
      peer.msgs.fileOffer.send(msg)
    }
  }

  requestFile (peer, overlayPath, contentHash, chunksHave) {
    peer.msgs.fileRequest.send({
      path: overlayPath,
      contentHash,
      chunksHave: chunksHave || null
    })
  }

  /**
   * 0.5a: Request a tree by its hash. Returns a promise resolving to
   * the entries array (or [] if the peer doesn't have it).
   *
   * @param {object} peer
   * @param {string} hash - hex tree hash
   * @param {object} [opts]
   * @param {number} [opts.timeout] - override default timeout (ms)
   * @returns {Promise<Array<{kind, exec, name, childHash, size}>>}
   */
  requestTree (peer, hash, opts = {}) {
    return new Promise((resolve, reject) => {
      // If a prior request is already in-flight for the same hash, reject
      // this caller rather than silently overwrite.
      if (peer.pendingTrees.has(hash)) {
        return reject(new Error('tree request already pending for hash: ' + hash))
      }
      // Per-request nonce (per-peer monotonic, non-zero) lets the requester drop
      // pages echoed for a superseded attempt. pages/pageBytes buffer this
      // request's own paged response, so a fresh attempt never inherits an old one.
      const nonce = peer._treeReqSeq = (peer._treeReqSeq || 0) + 1
      const timeout = opts.timeout || this._treeRequestTimeout
      const pending = { resolve, reject, timer: null, timeout, nonce, pages: null, pageBytes: 0 }
      this._armTreeTimeout(peer, hash, pending)
      peer.pendingTrees.set(hash, pending)
      peer.msgs.treeRequest.send({ hash, nonce })
    })
  }

  // Arm (or re-arm) a pending tree request's idle timeout. Every buffered page
  // re-arms it (a large tree on a slow link mustn't time out mid-stream); the
  // request still settles because the accumulator is byte-capped in _onTreeResponse.
  _armTreeTimeout (peer, hash, pending) {
    pending.timer = setTimeout(() => {
      if (peer.pendingTrees.get(hash) === pending) {
        peer.pendingTrees.delete(hash)
        pending.reject(new Error('tree request timed out: ' + hash))
      }
    }, pending.timeout)
  }

  // Reject every in-flight tree request on this peer (channel close / destroy),
  // clearing timers so the promise fails promptly and its buffered pages release.
  _failPendingTrees (peer, err) {
    for (const [hash, pending] of peer.pendingTrees) {
      clearTimeout(pending.timer)
      peer.pendingTrees.delete(hash)
      pending.reject(err)
    }
  }

  /**
   * 0.5a: Request a file by its content hash. Peer looks up any file
   * matching that hash locally and streams chunks via the existing flow
   * (chunkHashes → chunkNeed → chunkData). Returns immediately; chunks
   * arrive asynchronously.
   *
   * Note: receiver must pre-register a target path mapping via
   * _filePaths keyed by the contentHash before calling, OR this method
   * is a no-op on the receive side. Full wiring deferred to 0.5c.
   */
  requestContent (peer, contentHash, chunksHave) {
    peer.msgs.contentRequest.send({
      contentHash,
      chunksHave: chunksHave || null,
      from: this._localProfileKey || ''   // authenticate the asker to the serve gate
    })
  }

  get peerCount () { return this._peers.size }

  destroy () {
    for (const [, peer] of this._peers) {
      this._failPendingTrees(peer, new Error('protocol destroyed'))
      peer.channel.close()
    }
    this._peers.clear()
  }

  // ── Handlers ────────────────────────────────────────────────

  _onOpen (peer) {
    peer.msgs.syncState.send({
      feedKey: this._syncEngine.feedKey,
      localSeq: this._syncEngine.feed.length,
      remoteSeq: 0
    })
  }

  async _onSyncState (peer, msg) {
    peer.remoteFeedKey = msg.feedKey
    peer.remoteSeq = msg.localSeq

    if (!this._autoSync) return

    try {
      await this._offerLocalFiles(peer)
    } catch {
      // ignore — the HyperOverlay facade runs with autoSync off, so this path is dormant
    }
  }

  async _onFileOffer (peer, msg) {
    // In gated mode the overlay flow is contentRequest→scheduler ONLY; gated
    // consumers never act on path-based file-offers (autoSync is off). Ignoring
    // them closes the offer→requestFile→legacy-receive path a peer could drive.
    if (this._serveAuthorizer) return
    if (this._fileOfferCb) this._fileOfferCb(peer, msg)

    if (msg.op === 0) {
      const local = await this._syncEngine._fileIndex.getFile(msg.path)
      if (!local || local.contentHash !== msg.contentHash) {
        const diskPath = this._resolveFilePath(msg.path)
        if (diskPath) {
          this._filePaths.set(msg.path, diskPath)
          this.requestFile(peer, msg.path, msg.contentHash)
        }
      }
    }
  }

  async _onFileRequest (peer, msg) {
    // path-based serve is UNGATED and would bypass the serve gate (the only
    // gated entry point is _onContentRequest). Gated consumers never send
    // fileRequest, so refuse it outright in gated mode.
    if (this._serveAuthorizer) return
    const diskPath = this._filePaths.get(msg.path)
    if (!diskPath) return

    const prepared = await this._transferManager.prepareFile(diskPath, msg.path)
    if (!prepared) return

    if (!await this._transferManager._fileIndex.hasChunkMap(msg.path)) {
      await this._transferManager._fileIndex.putChunkMap(msg.path, prepared.chunks)
    }

    this._sendChunkHashes(peer, msg.path, prepared.tier, prepared.chunks)
  }

  // Send a file's chunk list, paged so no single frame exceeds
  // the Noise transport's 16 MiB-1 atomic-write limit. A list that fits in one
  // frame ships as one (more:0) — identical on the wire to the pre-paging format
  // bar a trailing 0 byte. _onChunkHashes reassembles the pages on the receiver.
  _sendChunkHashes (peer, filePath, tier, chunks) {
    const total = chunks.length
    if (total <= MAX_CHUNKS_PER_MSG) {
      peer.msgs.chunkHashes.send({ path: filePath, tier, chunks, more: 0 })
      return
    }
    for (let i = 0; i < total; i += MAX_CHUNKS_PER_MSG) {
      const more = i + MAX_CHUNKS_PER_MSG < total ? 1 : 0
      peer.msgs.chunkHashes.send({ path: filePath, tier, chunks: chunks.slice(i, i + MAX_CHUNKS_PER_MSG), more })
    }
  }

  // Reassemble a paged chunk list. Returns the full list once
  // the final page (more:0) arrives, or null while pages are still pending. A
  // lone complete frame passes straight through (no copy) — the small-file norm.
  // Pages for a path arrive in order on this channel, so arrival-order
  // concatenation is correct even when several files interleave on it.
  _reassembleChunkHashes (peer, msg) {
    const buffered = peer._chunkHashPages && peer._chunkHashPages.get(msg.path)
    if (!buffered && !msg.more) return msg.chunks
    if (!peer._chunkHashPages) peer._chunkHashPages = new Map()
    let acc = buffered
    if (!acc) { acc = []; peer._chunkHashPages.set(msg.path, acc) }
    for (const ch of msg.chunks) acc.push(ch)
    if (acc.length > MAX_CHUNK_HASHES_ACCUM) {
      // F2: drop an over-long accumulator (adversarial more:1 flood) instead of
      // OOMing — the fetch fails and the scheduler retries/fails over to another peer.
      peer._chunkHashPages.delete(msg.path)
      return null
    }
    if (msg.more) return null
    peer._chunkHashPages.delete(msg.path)
    return acc
  }

  // Upper-bound wire size of one tree entry: kind(1)+exec(1) + string(len-prefix ≤4
  // + utf8 name bytes) + childHash(32) + size varint(≤9, c.uint is 9 bytes for a
  // >4 GiB size).
  _treeEntryWireSize (e) {
    return 1 + 1 + 4 + Buffer.byteLength(e.name || '', 'utf8') + 32 + 9
  }

  // Send a tree's entries, paged so no single frame exceeds the Noise atomic-write
  // limit; every page but the last is more:1. A tree that fits in one frame ships
  // as a single more:0 frame. `nonce` echoes the requester's per-request id.
  _sendTreeResponse (peer, hash, entries, nonce) {
    let page = []
    let bytes = 40 // hash(32) + uint32 count prefix + more/nonce + slack
    for (const e of entries) {
      const sz = this._treeEntryWireSize(e)
      if (page.length && bytes + sz > MAX_TREE_BYTES_PER_MSG) {
        peer.msgs.treeResponse.send({ hash, entries: page, more: 1, nonce })
        page = []
        bytes = 40
      }
      page.push(e)
      bytes += sz
    }
    peer.msgs.treeResponse.send({ hash, entries: page, more: 0, nonce })
  }

  async _onChunkHashes (peer, msg) {
    // Reassemble paged chunkHashes frames before dispatching.
    const chunks = this._reassembleChunkHashes(peer, msg)
    if (chunks === null) {
      // A buffered page is forward progress — keep the scheduler's no-progress
      // watchdog from tripping while a large map streams across several frames.
      const pending = this._schedulers.get(msg.path)
      if (pending && pending.notePageProgress) pending.notePageProgress()
      return
    }
    // Multi-source: if a scheduler owns this path, let it distribute chunk
    // requests across peers instead of the legacy single-peer auto-flow.
    const sched = this._schedulers.get(msg.path)
    if (sched) { Promise.resolve(sched.onChunkHashes(peer, chunks)).catch(() => {}); return }
    // the legacy single-peer receive below writes incoming bytes
    // to _filePaths.get(path) and finalizes a rename OVER it. For a path that
    // maps to one of OUR own files (e.g. a content-register entry), an
    // unsolicited chunkHashes would let a peer overwrite the owner's source
    // file. Gated consumers only ever receive via a scheduler (the branch
    // above), so refuse any other receive.
    if (this._serveAuthorizer) return

    const diskPath = this._filePaths.get(msg.path)
    if (!diskPath) return

    // Empty-file fast path: a 0-byte file has no chunks to fetch, but we
    // still need to materialize it on disk and fire the same completion
    // flow as _onChunkData's "transfer complete" branch — otherwise the
    // requester (e.g. NetworkFetcher.getContent) never resolves and times
    // out. Empty files are common in practice: .keep, __init__.py, build
    // stamps, touch'd markers. Bug symptom before this: node-gyp's
    // postinstall.stamp (0 bytes, hash 5187b7a8…) hung every install.
    if (chunks.length === 0) {
      try {
        fs.mkdirSync(path.dirname(diskPath), { recursive: true })
        fs.writeFileSync(diskPath, Buffer.alloc(0))
      } catch {
        return
      }
      const contentHash = hashChunk(Buffer.alloc(0))
      const stat = fs.statSync(diskPath)
      await this._syncEngine._fileIndex.putFile(msg.path, {
        contentHash, size: 0, mtime: stat.mtimeMs
      })
      await this._syncEngine.logPut(msg.path, {
        contentHash, size: 0, mtime: stat.mtimeMs
      })
      if (peer.remoteFeedKey) {
        await this._syncEngine.markSynced(peer.remoteFeedKey, msg.path, contentHash, this._syncEngine.feed.length - 1)
      }
      peer.msgs.transferComplete.send({ path: msg.path, contentHash })
      if (this._syncedCb) {
        this._syncedCb({ path: msg.path, contentHash, size: 0, direction: 'pull' })
      }
      return
    }

    const needed = this._transferManager.computeNeeded(chunks, new Set())
    if (needed.length === 0) return

    let size = 0
    for (const c of chunks) size += c.length

    // startReceive can throw (fd open, partial recovery) — drop this transfer
    // instead of rejecting protomux's onmessage promise, which would destroy the
    // whole Noise stream.
    try {
      await this._transferManager.startReceive(diskPath, {
        size,
        chunks: chunks.map((c, i) => {
          let offset = 0
          for (let j = 0; j < i; j++) offset += chunks[j].length
          return { hash: c.hash, offset, length: c.length }
        })
      })
    } catch {
      return
    }

    peer.msgs.chunkNeed.send({ path: msg.path, indices: needed })
  }

  async _onChunkNeed (peer, msg) {
    // Serve bytes ONLY for a synthetic path THIS peer was
    // authorized for via a gated _onContentRequest. Blocks a peer pulling bytes
    // by sending chunkNeed directly for a registered path (e.g. a content-
    // register entry) without passing the serve gate.
    if (this._serveAuthorizer && !peer.authorizedServe.has(msg.path)) return
    const diskPath = this._filePaths.get(msg.path)
    if (!diskPath) return

    const fileIndex = this._transferManager._fileIndex
    let chunkMap
    try {
      chunkMap = msg.path.startsWith('content:')
        ? await fileIndex.getChunkMapByHash(msg.path.slice('content:'.length))
        : await fileIndex.getChunkMap(msg.path)
    } catch {
      // A chunk-map lookup that rejects (index I/O error) must not escape: the
      // onmessage dispatch is fire-and-forget, so a throw here becomes an
      // unhandled rejection that tears down the whole Noise/replication stream
      // (the S1 malformed-frame hardening theme). Drop the request — the receiver
      // re-requests and the transfer self-heals.
      return
    }
    if (!chunkMap) return

    // Single-flight serve pump per peer (mirrors hypercore's `receiverBusy`).
    // Enqueue this request; if no pump is running for this peer, drain the queue
    // one job at a time. protomux dispatches every frame of a socket read
    // synchronously, so two chunkNeed frames from the same peer would otherwise
    // start rival serve loops — interleaving sends and admitting N chunks per
    // drain instead of honouring backpressure once (the discipline our 0.2.13
    // serialized pump had, which Ok's inline loop dropped).
    if (!peer._serveQueue) peer._serveQueue = []
    peer._serveQueue.push({ path: msg.path, diskPath, chunkMap, indices: msg.indices })
    if (peer._serving) return
    peer._serving = true
    // Kick the pump fire-and-forget: _onChunkNeed is the onmessage dispatch and
    // must return promptly, NOT stay pending for the whole multi-chunk serve
    // (which, under backpressure, spans the entire transfer). A second chunkNeed
    // from this peer just enqueues above; the single-flight guard (_serving) means
    // this already-running pump picks it up. This is our 0.2.13 contract — Ok's
    // inline drain loop awaited the whole serve, which the unit test rejects.
    this._drainServeQueue(peer)
  }

  // The per-peer single-flight serve pump. Drains _serveQueue one job at a time;
  // detached from _onChunkNeed so the message handler returns immediately.
  async _drainServeQueue (peer) {
    try {
      while (peer._serveQueue.length) {
        if (peer.channel && peer.channel.closed) { peer._serveQueue.length = 0; break }
        try { await this._serveJob(peer, peer._serveQueue.shift()) } catch {}
      }
    } finally {
      peer._serving = false
    }
  }

  // Serve one chunkNeed job: stream the requested chunk indices, honouring
  // stream backpressure — stop producing when send() reports the write buffer is
  // full and resume on drain, so sibling protocols multiplexed on the same Noise
  // stream (Corestore replication, app handshakes; protomux MAX_BACKLOG is
  // Infinity) aren't starved. Runs under the per-peer single-flight guard in
  // _onChunkNeed, so exactly one job streams at a time per peer.
  async _serveJob (peer, job) {
    const { path, diskPath, chunkMap, indices } = job
    // P3: cork the mux so a run of chunkData frames coalesces into fewer stream
    // writes (hypercore's replicator corks around each request/response batch,
    // replicator.js:722/738). Uncork before parking on drain (flush the batch) and
    // in the finally. The `corked` guard keeps cork/uncork balanced across the early
    // returns, and no-ops when the mux stub has no cork (unit tests).
    const mux = peer.mux
    let corked = false
    const cork = () => { if (mux && mux.cork && !corked) { mux.cork(); corked = true } }
    const uncork = () => { if (mux && mux.uncork && corked) { mux.uncork(); corked = false } }
    cork()
    try {
      for (let i = 0; i < indices.length; i++) {
        const index = indices[i]
        if (index >= chunkMap.length) continue
        // P5: skip a chunk the downloader hotswapped away (one-shot).
        if (peer._cancelledServe && peer._cancelledServe.delete(path + '\x00' + index)) continue
        const c = chunkMap[index]
        const data = this._transferManager.readChunk(diskPath, c.offset, c.length)
        if (!data) continue
        const flushed = peer.msgs.chunkData.send({ path, index, data })
        if (this._chunkServeCb) {
          try { this._chunkServeCb({ path, index, bytes: data.length, peer, from: peer.authorizedServe.get(path) || null }) } catch {}
        }
        if (flushed === false && i < indices.length - 1) {
          uncork()   // flush the corked batch before we park on drain
          const alive = await this._waitForDrain(peer)
          if (!alive) return
          if (this._serveAuthorizer && !peer.authorizedServe.has(path)) return
          cork()     // re-cork for the next run
        }
      }
    } finally {
      uncork()
    }
  }

  // One shared drain waiter per peer so concurrent serve loops (the
  // same peer pulling several files) don't each attach listeners and trip the stream's
  // max-listeners warning. Resolves true on drain, false if the channel closes first.
  _waitForDrain (peer) {
    const channel = peer.channel
    const stream = peer.mux && peer.mux.stream
    if (!stream || !channel || channel.closed) return Promise.resolve(false)
    if (channel.drained) return Promise.resolve(true)
    if (peer._drainWait) return peer._drainWait
    peer._drainWait = new Promise((resolve) => {
      let timer = null
      const done = (alive) => {
        if (timer) clearTimeout(timer)
        stream.removeListener('drain', onDrain)
        stream.removeListener('close', onClose)
        peer._drainWait = null
        resolve(alive)
      }
      const onDrain = () => done(!channel.closed)
      const onClose = () => done(false)
      timer = setTimeout(() => done(false), DRAIN_TIMEOUT_MS)
      stream.on('drain', onDrain)
      stream.on('close', onClose)
    })
    return peer._drainWait
  }

  async _onChunkData (peer, msg) {
    // Silent-peer watchdog hook: fire BEFORE any processing so a slow disk
    // doesn't get blamed for a peer-side stall.
    if (this._chunkProgressCb) {
      try {
        this._chunkProgressCb({
          path: msg.path,
          index: msg.index,
          bytes: msg.data ? msg.data.length : 0,
          peer
        })
      } catch {}
    }

    // Multi-source: scheduler owns the write + reschedule + finalize.
    const sched = this._schedulers.get(msg.path)
    if (sched) { Promise.resolve(sched.onChunkData(peer, msg.index, msg.data)).catch(() => {}); return }
    // refuse the legacy single-peer receive (writes+renames over
    // _filePaths.get(path), i.e. potentially our own source file). Gated
    // consumers only receive via a scheduler (above).
    if (this._serveAuthorizer) return

    const diskPath = this._filePaths.get(msg.path)
    if (!diskPath) return

    const result = this._transferManager.writeChunk(diskPath, msg.index, msg.data)

    if (result.ok && this._transferManager.isComplete(diskPath)) {
      const fin = await this._transferManager.finalize(diskPath)
      if (fin.ok) {
        const fileData = fs.readFileSync(diskPath)
        const contentHash = hashChunk(fileData)
        const stat = fs.statSync(diskPath)

        await this._syncEngine._fileIndex.putFile(msg.path, {
          contentHash, size: stat.size, mtime: stat.mtimeMs
        })
        await this._syncEngine.logPut(msg.path, {
          contentHash, size: stat.size, mtime: stat.mtimeMs
        })

        if (peer.remoteFeedKey) {
          await this._syncEngine.markSynced(peer.remoteFeedKey, msg.path, contentHash, this._syncEngine.feed.length - 1)
        }

        peer.msgs.transferComplete.send({ path: msg.path, contentHash })
        if (this._syncedCb) {
          this._syncedCb({ path: msg.path, contentHash, size: stat.size, direction: 'pull' })
        }
      }
    }
  }

  _onChunkCancel (peer, msg) {
    if (msg.indices && msg.indices.length) {
      // P5 hotswap: the downloader reassigned these chunk indices to a faster peer.
      // Stop serving just them (bandwidth save); the rest of the transfer continues.
      // Consumed one-shot in _serveJob.
      if (!peer._cancelledServe) peer._cancelledServe = new Set()
      for (const i of msg.indices) peer._cancelledServe.add(msg.path + '\x00' + i)
      return
    }
    const diskPath = this._filePaths.get(msg.path)
    if (diskPath) this._transferManager.cancel(diskPath)
  }

  // Resolve a serve-message's downloader identity from the authenticated record we kept at
  // serve start (peer.authorizedServe), NOT the message — so a peer can only affect its own
  // ledger row, never spoof another. Returns null `from` when the peer was never authorized.
  _authorizedFrom (peer, contentHash) {
    const synthPath = 'content:' + contentHash
    return { synthPath, from: peer.authorizedServe.get(synthPath) || null }
  }

  // A downloader told us it paused/stopped pulling a hash WE serve.
  _onTransferControl (peer, msg) {
    if (!this._serveControlCb) return
    const { synthPath, from } = this._authorizedFrom(peer, msg.contentHash)
    if (!from) return
    const state = msg.state === CONTROL_STOPPED ? 'stopped' : 'paused'
    try { this._serveControlCb({ path: synthPath, peer, from, state }) } catch {}
  }

  // A downloader reported its on-disk have-bytes for a hash WE serve.
  _onTransferProgress (peer, msg) {
    if (!this._serveProgressCb) return
    const { synthPath, from } = this._authorizedFrom(peer, msg.contentHash)
    if (!from) return
    try { this._serveProgressCb({ path: synthPath, peer, from, have: msg.have || 0 }) } catch {}
  }

  async _onTransferComplete (peer, msg) {
    if (peer.remoteFeedKey) {
      await this._syncEngine.markSynced(peer.remoteFeedKey, msg.path, msg.contentHash, this._syncEngine.feed.length - 1)
    }
    if (this._syncedCb) {
      this._syncedCb({ path: msg.path, contentHash: msg.contentHash, direction: 'push' })
    }
  }

  _onConflictMsg (peer, msg) {
    if (this._conflictCb) this._conflictCb(msg, peer)
  }

  // ── Tree handlers (0.5a) ────────────────────────────────────

  async _onTreeRequest (peer, msg) {
    // ungated metadata oracle (returns fileIndex tree entries to
    // any peer). Gated consumers never use tree-requests; refuse in gated mode.
    if (this._serveAuthorizer) return
    let entries = []
    try {
      const fileIndex = this._syncEngine && this._syncEngine._fileIndex
      if (fileIndex && typeof fileIndex.getTree === 'function') {
        const tree = await fileIndex.getTree(msg.hash)
        if (tree && Array.isArray(tree.entries)) entries = tree.entries
      }
    } catch {
      // fall through — reply with empty entries on lookup failure
    }
    this._sendTreeResponse(peer, msg.hash, entries, msg.nonce || 0)
  }

  _onTreeResponse (peer, msg) {
    const pending = peer.pendingTrees.get(msg.hash)
    if (!pending) return // no request in flight — drop
    // Drop a page echoing a superseded request's nonce (a stale page from a
    // timed-out attempt must not settle a later same-hash retry). nonce 0 = a
    // pre-nonce holder that can't echo it, so fall through (unverifiable,
    // best-effort).
    if (msg.nonce && msg.nonce !== pending.nonce) return
    const settle = (fn, arg) => { clearTimeout(pending.timer); peer.pendingTrees.delete(msg.hash); fn(arg) }
    // Lone complete frame (the small-tree norm) resolves with no accumulation.
    if (!pending.pages && !msg.more) return settle(pending.resolve, msg.entries)
    // Accumulate into THIS request's own buffer, bounding total bytes so a peer
    // streaming pages endlessly rejects the request instead of growing memory
    // without limit.
    if (!pending.pages) pending.pages = []
    for (const e of msg.entries) { pending.pages.push(e); pending.pageBytes += this._treeEntryWireSize(e) }
    if (pending.pageBytes > this._maxTreeResponseBytes) {
      return settle(pending.reject, new Error('tree response too large: ' + msg.hash))
    }
    if (msg.more) {
      // Forward progress — re-arm the idle timeout so a legitimately large
      // multi-page tree on a slow link doesn't time out mid-stream.
      clearTimeout(pending.timer)
      this._armTreeTimeout(peer, msg.hash, pending)
      return
    }
    settle(pending.resolve, pending.pages)
  }

  async _onContentRequest (peer, msg) {
    // serve gate. BEFORE any path resolution or streaming,
    // ask the injected authorizer whether this peer may receive this hash.
    // Deny == silent return (same observable behavior as "I don't hold it"
    // below), so a non-member cannot distinguish denial from absence.
    if (this._serveAuthorizer) {
      let ok = false
      try { ok = await this._serveAuthorizer(peer, msg.from || null, msg.contentHash) } catch { ok = false }
      if (!ok) return
    }

    // Resolve msg.contentHash → an on-disk path. Three lookup paths, in order:
    //  1. Fast path: _contentHashPaths map (warm — just-registered / consumer-set)
    //  2. Content-addressed spool (RESTART-DURABLE): <syncBaseDir>/<contentHash>
    //  3. Slow path: scan fileIndex for any file:* entry with that hash
    let diskPath = this._contentHashPaths.get(msg.contentHash)
    if (diskPath && !fileExists(diskPath)) diskPath = null

    if (!diskPath) {
      // Content-addressed spool fallback. The canonical bytes are stored at
      // <syncBaseDir>/<contentHash> (fetchFile's mirrorSpool option writes them
      // there). The in-memory map is empty after a restart and FileIndex
      // persists no disk path, so resolve the hash straight from the
      // content-addressed spool — a pure function of the hash + dir, like a
      // git object store's blobs/<hash>. This is what lets a node keep serving
      // its spooled files across restarts with no rehydration step.
      for (const baseDir of this._syncBaseDirs) {
        const candidate = path.join(baseDir, msg.contentHash)
        if (fileExists(candidate)) {
          diskPath = candidate
          this._contentHashPaths.set(msg.contentHash, candidate) // warm the map
          break
        }
      }
    }

    if (!diskPath) {
      // Scan fileIndex for a file whose contentHash matches.
      const fileIndex = this._syncEngine && this._syncEngine._fileIndex
      if (fileIndex && typeof fileIndex.listFiles === 'function') {
        try {
          const files = await fileIndex.listFiles()
          for (const f of files) {
            if (f.contentHash === msg.contentHash) {
              diskPath = this._filePaths.get(f.path)
              if ((!diskPath || !fileExists(diskPath)) && f.path) diskPath = f.path
              break
            }
          }
        } catch {
          // fall through
        }
      }
    }

    if (!diskPath) {
      // Don't have it. Silently drop; requester will time out.
      return
    }

    // Use a SYNTHETIC path keyed by contentHash so the requester can
    // pre-register a destPath and the chunk flow routes correctly on
    // both sides. Temporarily populate _filePaths so _onChunkNeed +
    // chunkmap lookups resolve under this synthetic key.
    const syntheticPath = 'content:' + msg.contentHash
    this._filePaths.set(syntheticPath, diskPath)
    peer.authorizedServe.set(syntheticPath, msg.from || null) // _onChunkNeed will now serve this path to THIS peer

    // The chunk map is content-addressed — identical bytes always chunk
    // identically. Reuse one computed at publish (or a prior serve, or before a
    // restart) instead of re-reading the whole file to re-chunk it: re-chunking a
    // multi-GB file adds a full-file-read of latency before the first byte ships.
    const fileIndex = this._transferManager._fileIndex
    let chunks = await fileIndex.getChunkMapByHash(msg.contentHash)
    let tier
    if (chunks) {
      let size = 0
      try { size = fs.statSync(diskPath).size } catch {}
      tier = selectTier(size)
    } else {
      const prepared = await this._transferManager.prepareFile(diskPath, syntheticPath, { byHashOnly: true })
      if (!prepared) {
        this._filePaths.delete(syntheticPath)
        peer.authorizedServe.delete(syntheticPath) // keep the authorize map in lockstep with _filePaths
        return
      }
      chunks = prepared.chunks
      tier = prepared.tier
      // prepareFile persists the hash-keyed map only for large files; ensure it exists
      // for small ones too, since _onChunkNeed resolves content:<hash> by that map.
      if (!await fileIndex.hasChunkMapByHash(msg.contentHash)) await fileIndex.putChunkMapByHash(msg.contentHash, chunks)
    }
    this._sendChunkHashes(peer, syntheticPath, tier, chunks)
    if (this._serveStartCb) {
      let total = 0
      for (const c of chunks) total += c.length || 0
      try { this._serveStartCb({ path: syntheticPath, peer, from: msg.from || null, total }) } catch {}
    }
  }

  // ── Sync logic ──────────────────────────────────────────────

  /**
   * Offer all local files to a peer.
   * Reads from the local feed and sends file-offers for each entry.
   * The peer will request any files it doesn't have.
   */
  async _offerLocalFiles (peer) {
    const feed = this._syncEngine.feed
    if (feed.length === 0) return

    for (let i = 0; i < feed.length; i++) {
      try {
        const entry = await feed.get(i)
        if (!entry) continue

        // Register the file path mapping so _onFileRequest can find it
        if (entry.op === 0) {
          const diskPath = this._resolveFilePath(entry.path)
          if (diskPath) this._filePaths.set(entry.path, diskPath)
        }

        peer.msgs.fileOffer.send({
          path: entry.path,
          contentHash: entry.hash || '0'.repeat(64),
          size: entry.size || 0,
          mtime: entry.mtime || 0,
          op: entry.op
        })
      } catch {
        // skip unreadable entries
      }
    }
  }

  /**
   * Resolve an overlay path to a disk path.
   */
  _resolveFilePath (overlayPath) {
    if (this._filePaths.has(overlayPath)) return this._filePaths.get(overlayPath)
    for (const baseDir of this._syncBaseDirs) {
      return path.join(baseDir, overlayPath)
    }
    return null
  }
}

// True iff `p` is an existing regular file. Used to validate a resolved disk path
// before serving (a cold-restart map entry or an overlay-path masquerading as a
// disk path won't exist) and to probe the content-addressed spool.
function fileExists (p) {
  try { return fs.statSync(p).isFile() } catch { return false }
}
/**
 * SyncEngine — Feed-based change tracking and conflict detection
 *
 * Each peer has a Hypercore feed logging file change operations.
 * When peers connect, feeds replicate automatically (Hypercore handles this).
 * The sync engine diffs feeds since the last-synced sequence number
 * and detects conflicts using three-value comparison:
 *
 *   my current hash vs their current hash vs last-synced hash (common ancestor)
 *
 * Conflict resolution is configurable per sync folder:
 *   prompt | newest-wins | keep-both | skip | mine-wins | theirs-wins
 */

import ReadyResource from 'ready-resource'

// Operation types written to the change feed
const OP_PUT = 0
const OP_DEL = 1

export const STRATEGIES = ['prompt', 'newest-wins', 'keep-both', 'skip', 'mine-wins', 'theirs-wins']

export class SyncEngine extends ReadyResource {
  constructor (fileIndex, corestore, opts = {}) {
    super()
    this._fileIndex = fileIndex
    this._corestore = corestore
    this._feed = null
    this._peerFeeds = new Map() // peerKey hex → Hypercore
    this._conflicts = []       // unresolved conflicts
    this._opts = opts
  }

  async _open () {
    // Local change feed — append-only log of file operations. Encrypted at rest when
    // the caller passes opts.encryptionKey (peer feeds, opened by key in addPeerFeed,
    // stay plaintext — their key is not ours to encrypt under).
    const opts = { name: 'sync-feed', valueEncoding: 'json' }
    if (this._opts.encryptionKey) opts.encryptionKey = this._opts.encryptionKey
    this._feed = this._corestore.get(opts)
    await this._feed.ready()
  }

  async _close () {
    // Peer feeds are managed by corestore, no explicit close needed
  }

  /**
   * The local change feed (Hypercore)
   */
  get feed () { return this._feed }

  /**
   * The local feed's public key as hex
   */
  get feedKey () { return this._feed.key.toString('hex') }

  /**
   * Current unresolved conflicts
   */
  get conflicts () { return this._conflicts }

  // ── Change logging ──────────────────────────────────────────

  /**
   * Log a file put/update operation
   * @param {string} path - file path
   * @param {{ contentHash: string, size: number, mtime: number }} meta
   */
  async logPut (path, meta) {
    await this._feed.append({
      op: OP_PUT,
      path,
      hash: meta.contentHash,
      size: meta.size,
      mtime: meta.mtime,
      rev: meta.rev ?? null, // optional app version (e.g. atproto TID) for rev-based conflict resolution; null for generic callers
      timestamp: Date.now()
    })
  }

  /**
   * Log a file deletion
   * @param {string} path - file path
   */
  async logDel (path) {
    await this._feed.append({
      op: OP_DEL,
      path,
      hash: null,
      size: 0,
      mtime: 0,
      timestamp: Date.now()
    })
  }

  // ── Peer feeds ──────────────────────────────────────────────

  /**
   * Add a remote peer's feed for syncing
   * @param {Buffer|string} key - peer's feed public key
   * @returns {Hypercore} the peer feed
   */
  addPeerFeed (key) {
    const keyHex = typeof key === 'string' ? key : key.toString('hex')
    if (this._peerFeeds.has(keyHex)) return this._peerFeeds.get(keyHex)

    const feed = this._corestore.get({ key: typeof key === 'string' ? Buffer.from(key, 'hex') : key, valueEncoding: 'json' })
    this._peerFeeds.set(keyHex, feed)
    return feed
  }

  /**
   * Get a peer feed by key
   * @param {string} keyHex
   * @returns {Hypercore|null}
   */
  getPeerFeed (keyHex) {
    return this._peerFeeds.get(keyHex) || null
  }

  // ── Feed diffing ────────────────────────────────────────────

  /**
   * Get new operations from a feed since a given sequence number
   * @param {Hypercore} feed
   * @param {number} sinceSeq - start reading from this seq (exclusive)
   * @returns {Array<{ seq: number, op: number, path: string, hash: string|null, size: number, mtime: number }>}
   */
  async getChanges (feed, sinceSeq) {
    await feed.ready()
    await feed.update()

    const changes = []
    const start = sinceSeq + 1
    const end = feed.length

    for (let i = start; i < end; i++) {
      const entry = await feed.get(i)
      changes.push({ seq: i, ...entry })
    }

    return changes
  }

  /**
   * Build a map of latest state per path from a list of changes.
   * Later entries override earlier ones for the same path.
   * @param {Array} changes
   * @returns {Map<string, { seq, op, hash, size, mtime }>}
   */
  buildChangeMap (changes) {
    const map = new Map()
    for (const c of changes) {
      map.set(c.path, { seq: c.seq, op: c.op, hash: c.hash, size: c.size, mtime: c.mtime, rev: c.rev ?? null })
    }
    return map
  }

  // ── Sync diff ───────────────────────────────────────────────

  /**
   * Compute the sync diff between local and a remote peer.
   * Returns actions to take: pull, push, conflict, or skip.
   *
   * @param {string} peerKey - hex key of the remote peer's feed
   * @returns {Array<{ path, action, local?, remote?, ancestor? }>}
   *   action: 'pull' | 'push' | 'conflict' | 'skip' | 'delete-local' | 'delete-remote'
   */
  async diff (peerKey) {
    const peerFeed = this._peerFeeds.get(peerKey)
    if (!peerFeed) throw new Error('Unknown peer: ' + peerKey)

    await peerFeed.ready()
    await peerFeed.update()

    // Get last-synced state for all files with this peer
    const syncStates = await this._fileIndex.listSyncStates(peerKey)
    const syncMap = new Map()
    for (const s of syncStates) {
      syncMap.set(s.path, s)
    }

    // Get my changes since last sync
    const myLastSeq = this._getMaxSyncedSeq(syncStates, 'local')
    const myChanges = await this.getChanges(this._feed, -1) // read all, filter by syncMap
    const myMap = this.buildChangeMap(myChanges)

    // Get their changes since last sync
    const theirChanges = await this.getChanges(peerFeed, -1) // read all
    const theirMap = this.buildChangeMap(theirChanges)

    // Collect all paths mentioned by either side
    const allPaths = new Set([...myMap.keys(), ...theirMap.keys()])

    const actions = []

    for (const path of allPaths) {
      const mine = myMap.get(path)
      const theirs = theirMap.get(path)
      const ancestor = syncMap.get(path)

      const myHash = mine ? mine.hash : null
      const theirHash = theirs ? theirs.hash : null
      const ancestorHash = ancestor ? ancestor.lastHash : null

      // Both have it and hashes match — in sync
      if (myHash && theirHash && myHash === theirHash) {
        actions.push({ path, action: 'skip', local: mine, remote: theirs })
        continue
      }

      // Only they have it (or they changed, I haven't)
      if (theirHash && !mine) {
        actions.push({ path, action: 'pull', remote: theirs })
        continue
      }

      // Only I have it (or I changed, they haven't)
      if (myHash && !theirs) {
        actions.push({ path, action: 'push', local: mine })
        continue
      }

      // Both null — both deleted
      if (!myHash && !theirHash) {
        actions.push({ path, action: 'skip' })
        continue
      }

      // One deleted, one has content
      if (mine && mine.op === OP_DEL && theirHash) {
        // I deleted, they still have it
        if (ancestorHash && ancestorHash === theirHash) {
          // They haven't changed since ancestor — propagate my delete
          actions.push({ path, action: 'delete-remote', local: mine, remote: theirs })
        } else {
          // They changed it after ancestor — conflict
          actions.push({ path, action: 'conflict', local: mine, remote: theirs, ancestor })
        }
        continue
      }

      if (theirs && theirs.op === OP_DEL && myHash) {
        // They deleted, I still have it
        if (ancestorHash && ancestorHash === myHash) {
          // I haven't changed since ancestor — accept their delete
          actions.push({ path, action: 'delete-local', local: mine, remote: theirs })
        } else {
          // I changed it after ancestor — conflict
          actions.push({ path, action: 'conflict', local: mine, remote: theirs, ancestor })
        }
        continue
      }

      // Both have different content — use ancestor to determine conflict
      if (myHash && theirHash && myHash !== theirHash) {
        if (ancestorHash === myHash) {
          // Only they changed — pull
          actions.push({ path, action: 'pull', local: mine, remote: theirs })
        } else if (ancestorHash === theirHash) {
          // Only I changed — push
          actions.push({ path, action: 'push', local: mine, remote: theirs })
        } else {
          // Both changed — conflict
          actions.push({ path, action: 'conflict', local: mine, remote: theirs, ancestor })
        }
        continue
      }

      // Fallback — shouldn't reach here
      actions.push({ path, action: 'skip', local: mine, remote: theirs })
    }

    return actions
  }

  // ── Conflict resolution ─────────────────────────────────────

  /**
   * Resolve a conflict using a strategy
   * @param {{ path, local, remote, ancestor }} conflict
   * @param {string} strategy - one of STRATEGIES
   * @returns {{ action: 'pull'|'push'|'keep-both'|'skip', winner?: 'local'|'remote' }}
   */
  resolveConflict (conflict, strategy) {
    switch (strategy) {
      case 'mine-wins':
        return { action: 'push', winner: 'local' }

      case 'theirs-wins':
        return { action: 'pull', winner: 'remote' }

      case 'newest-wins': {
        const mySeq = conflict.local ? conflict.local.seq : -1
        const theirSeq = conflict.remote ? conflict.remote.seq : -1
        if (mySeq >= theirSeq) {
          return { action: 'push', winner: 'local' }
        }
        return { action: 'pull', winner: 'remote' }
      }

      case 'keep-both':
        return { action: 'keep-both' }

      case 'skip':
        return { action: 'skip' }

      case 'prompt':
      default:
        // Add to conflict queue for user resolution
        this._conflicts.push(conflict)
        return { action: 'skip' }
    }
  }

  /**
   * Resolve a queued conflict by user choice
   * @param {string} path
   * @param {string} choice - 'overwrite' | 'keep-both' | 'skip'
   * @returns {{ action: string } | null}
   */
  resolveQueued (path, choice) {
    const idx = this._conflicts.findIndex(c => c.path === path)
    if (idx === -1) return null

    const conflict = this._conflicts.splice(idx, 1)[0]

    switch (choice) {
      case 'overwrite':
        return { action: 'pull', winner: 'remote', conflict }
      case 'keep-mine':
        return { action: 'push', winner: 'local', conflict }
      case 'keep-both':
        return { action: 'keep-both', conflict }
      case 'skip':
      default:
        return { action: 'skip', conflict }
    }
  }

  /**
   * Update sync state after a successful sync operation
   * @param {string} peerKey
   * @param {string} path
   * @param {string} hash - the hash both sides now agree on
   * @param {number} seq - the sequence number of the operation
   */
  async markSynced (peerKey, path, hash, seq) {
    await this._fileIndex.putSyncState(peerKey, path, {
      lastSeq: seq,
      lastHash: hash
    })
  }

  // ── Internal ────────────────────────────────────────────────

  _getMaxSyncedSeq (syncStates, _side) {
    let max = -1
    for (const s of syncStates) {
      if (s.lastSeq > max) max = s.lastSeq
    }
    return max
  }
}
/**
 * TransferManager — On-demand chunking and streaming file transfer
 *
 * Sender side:
 *   1. Read file from disk
 *   2. Chunk on demand (adaptive FastCDC)
 *   3. Send chunk hashes → peer says which it needs → stream those chunks
 *   4. Release chunks from memory after send
 *
 * Receiver side:
 *   1. Receive chunk hashes, respond with which are missing
 *   2. Receive chunks, write to <file>.overlay-partial
 *   3. Verify each chunk hash
 *   4. Atomic rename on completion
 *
 * No blob storage. Chunks exist in memory during transfer only.
 */

import fs from 'bare-fs'
import path from 'bare-path'
import os from 'bare-os'
import c from 'compact-encoding'
import sodium from 'sodium-universal'
import { chunk as chunkBuffer, chunkStream, hashChunk, createStreamingHasher, selectTier, getTierParams } from './chunker.js'

export const PARTIAL_SUFFIX = '.overlay-partial'

export const partialPathFor = (targetPath) => path.join(path.dirname(targetPath), path.basename(targetPath) + PARTIAL_SUFFIX)

// Resume verification + whole-file hashing run async + yielding so a multi-GB pass
// never blocks the event loop (IPC, pause/cancel, progress stay live).
const VERIFY_YIELD_EVERY = 64
const yieldToLoop = () => new Promise((resolve) => setTimeout(resolve, 0))

// Receive journal: bitmap + whole-file hash snapshot, stored in app-private storage
// (opts.journalDir) keyed by a digest of the destination path — never next to the
// download — so resume is O(1) and the incremental verify continues with no re-read.
const JOURNAL_SUFFIX = '.journal'
const JOURNAL_MAGIC = 0x4d4a5633
const JOURNAL_FLUSH_EVERY = 512
const JOURNAL_FLUSH_INTERVAL_MS = 1500
export const journalNameFor = (targetPath) => hashChunk(Buffer.from(targetPath)) + JOURNAL_SUFFIX

// Block-read prepare — host-adaptive read block size.
const READ_BLOCK_DEFAULT = 8 * 1024 * 1024
const READ_BLOCK_LOW_RAM = 4 * 1024 * 1024
const LOW_RAM_THRESHOLD = 6 * 1024 * 1024 * 1024

// Cap on stashed just-received chunk buffers (per transfer, insert-refusal), and the
// hash pump's yield budget — stash-fed iterations never await, so the pump yields by
// bytes hashed, not chunk count.
const MEM_STASH_BYTES_DEFAULT = 16 * 1024 * 1024
const DRAIN_YIELD_BYTES = 2 * 1024 * 1024

// Emit file blocks >= tier maxSize so chunkStream drains every block
// instead of re-copying a growing pending buffer (64 KiB createReadStream reads force
// ~56x memcpy at tier 3). Owns its fd and closes it on every terminal path: normal
// end, consumer break/throw (for-await calls .return() → finally), read error.
async function * readFileBlocks (filePath, size, blockSize) {
  const fd = await fs.open(filePath, 'r')
  try {
    let pos = 0
    while (pos < size) {
      const want = Math.min(blockSize, size - pos)
      const buf = Buffer.allocUnsafe(want)
      let filled = 0
      while (filled < want) {
        const n = await fs.read(fd, buf, filled, want - filled, pos + filled)
        if (n <= 0) break
        filled += n
      }
      if (filled === 0) break
      pos += filled
      yield filled === buf.length ? buf : buf.subarray(0, filled)
    }
  } finally {
    try { await fs.close(fd) } catch {}
  }
}

function bitmapOf (received, total) {
  const bm = Buffer.alloc((total + 7) >> 3)
  for (const i of received) bm[i >> 3] |= 1 << (i & 7)
  return bm
}

// Drop journals whose partial is gone, are stale, or are corrupt/foreign. Each
// journal self-describes its partial path (read cheaply from the header). Standalone
// (no TransferManager instance) so a boot-time sweep can reclaim orphans without
// the overlay stack being live.
export function cleanupOrphanedJournals (journalDir, maxAge = 7 * 86400000) {
  const cleaned = []
  if (!journalDir) return cleaned
  let entries
  try { entries = fs.readdirSync(journalDir) } catch { return cleaned }
  const now = Date.now()
  for (const entry of entries) {
    if (!entry.endsWith(JOURNAL_SUFFIX)) continue
    const full = path.join(journalDir, entry)
    let remove = false
    try {
      const raw = fs.readFileSync(full)
      const s = { start: 0, end: raw.length, buffer: raw }
      if (c.uint32.decode(s) !== JOURNAL_MAGIC) remove = true
      else {
        c.uint32.decode(s)
        const partialPath = c.string.decode(s)
        if (!fs.existsSync(partialPath)) remove = true
        else if (now - fs.statSync(full).mtimeMs > maxAge) remove = true
      }
    } catch { remove = true }
    if (remove) { try { fs.unlinkSync(full); cleaned.push(full) } catch {} }
  }
  return cleaned
}

export class TransferManager {
  constructor (fileIndex, opts = {}) {
    this._fileIndex = fileIndex
    this._maxConcurrency = opts.maxConcurrency || 4
    this._active = new Map() // path → transfer state
    this._memStashBytes = opts.memStashBytes ?? MEM_STASH_BYTES_DEFAULT
    this._journalDir = opts.journalDir || null
    if (this._journalDir) { try { fs.mkdirSync(this._journalDir, { recursive: true }) } catch {} }
  }

  _journalPathFor (targetPath) {
    if (!this._journalDir) return null
    return path.join(this._journalDir, journalNameFor(targetPath))
  }

  // ── Sender side ─────────────────────────────────────────────

  /**
   * Prepare a file for sending — read from disk, chunk, return hashes.
   * Chunk map is persisted for large files (>1MB).
   *
   * @param {string} filePath - absolute path on disk
   * @param {string} overlayPath - path in the overlay namespace
   * @returns {{ tier: number, chunks: Array<{ hash, offset, length }>, size: number } | null}
   */
  async prepareFile (filePath, overlayPath, opts = {}) {
    // Check file exists and get stats
    let stat
    try {
      stat = fs.statSync(filePath)
    } catch {
      return null
    }

    if (!stat.isFile()) return null

    const mtimeBefore = stat.mtimeMs

    // Check for existing chunk map (skip re-chunking if valid)
    const existing = await this._fileIndex.getChunkMap(overlayPath)
    const fileMeta = await this._fileIndex.getFile(overlayPath)

    if (existing && fileMeta && fileMeta.mtime === mtimeBefore) {
      // Chunk map still valid — file hasn't changed.
      // Backfill the content-addressed alias so the serve path (a
      // different overlay key) reuses this map instead of re-reading the file —
      // covers maps chunked before content-addressed caching existed.
      if (fileMeta.contentHash && stat.size >= 1048576 && !await this._fileIndex.hasChunkMapByHash(fileMeta.contentHash)) {
        await this._fileIndex.putChunkMapByHash(fileMeta.contentHash, existing)
      }
      return {
        tier: selectTier(stat.size),
        chunks: existing,
        size: stat.size,
        contentHash: fileMeta.contentHash // surfaced so the publish path gets the hash from one pass
      }
    }

    // Read in blocks >= tier maxSize and chunk from views (copy:false).
    // Cut points are content-stable across block sizes, so peers still match hashes.
    // size is passed to the hasher so the streaming digest matches hashChunk(buffer).
    const tier = selectTier(stat.size)
    const blockSize = Math.max(
      getTierParams(tier).maxSize,
      os.totalmem() < LOW_RAM_THRESHOLD ? READ_BLOCK_LOW_RAM : READ_BLOCK_DEFAULT
    )
    const fileHasher = createStreamingHasher({ size: stat.size })
    const chunks = []

    for await (const c of chunkStream(readFileBlocks(filePath, stat.size, blockSize), { tier, copy: false })) {
      // honor a publish-cancel signal (per-chunk granularity); on throw the
      // for-await calls readFileBlocks.return() which closes the fd.
      if (opts.signal?.aborted) { const e = new Error('publish aborted'); e.code = 'ECANCELLED'; throw e }
      fileHasher.update(c.data)
      chunks.push({ hash: c.hash, offset: c.offset, length: c.length })
      opts.onProgress?.(c.length)
    }

    // mtime guard — abort if file changed during the streaming read. A
    // vanished source (moved out of the folder mid-read) is just another "changed
    // during read" case — the open fd kept the read alive after a same-volume
    // rename, so it is this path-resolving stat that trips ENOENT. Guard it like
    // the pre-read stat above and re-queue rather than throw.
    let statAfter
    try {
      statAfter = fs.statSync(filePath)
    } catch {
      return null // source vanished during read, caller should re-queue
    }
    if (statAfter.mtimeMs !== mtimeBefore) {
      return null // file changed during read, caller should re-queue
    }

    // Post-read guard: a mid-read shrink can feed the digest fewer bytes than the
    // size baked into its leaf prefix — re-queue instead of persisting a bad hash.
    if (fileHasher.bytes !== stat.size) return null

    // Update file index
    const contentHash = fileHasher.digest()

    // Persist chunk map for large files — both path-keyed (legacy serve lookups)
    // and content-addressed, so the serve path reuses it across keys.
    // byHashOnly (the publish prepareForServe pass) keeps ONLY the
    // content-addressed map — the serve path resolves by hash, so the path-keyed map
    // + putFile under a throwaway overlay key would be dead, never-read state.
    if (stat.size >= 1048576) {
      if (!opts.byHashOnly) await this._fileIndex.putChunkMap(overlayPath, chunks)
      if (!await this._fileIndex.hasChunkMapByHash(contentHash)) await this._fileIndex.putChunkMapByHash(contentHash, chunks)
    }

    if (!opts.byHashOnly) {
      await this._fileIndex.putFile(overlayPath, {
        contentHash,
        size: stat.size,
        mtime: mtimeBefore
      })
    }

    return { tier, chunks, size: stat.size, contentHash }
  }

  /**
   * Read a specific chunk from disk by its offset and length.
   * Returns raw bytes — caller sends them to the peer.
   *
   * @param {string} filePath - absolute path on disk
   * @param {number} offset - byte offset
   * @param {number} length - bytes to read
   * @returns {Buffer | null}
   */
  readChunk (filePath, offset, length) {
    try {
      const fd = fs.openSync(filePath, 'r')
      const buf = Buffer.alloc(length)
      const bytesRead = fs.readSync(fd, buf, 0, length, offset)
      fs.closeSync(fd)
      if (bytesRead !== length) return null
      return buf
    } catch {
      return null
    }
  }

  /**
   * Determine which chunks a peer needs (chunks they don't already have).
   *
   * @param {Array<{ hash, offset, length }>} offered - chunks the sender has
   * @param {Set<string>} peerHas - set of chunk hashes the peer already has
   * @returns {number[]} indices of chunks the peer needs
   */
  computeNeeded (offered, peerHas) {
    const needed = []
    for (let i = 0; i < offered.length; i++) {
      if (!peerHas.has(offered[i].hash)) {
        needed.push(i)
      }
    }
    return needed
  }

  // ── Receiver side ───────────────────────────────────────────

  // Start receiving a file. A same-size partial is resumed: the journal restores the
  // received-set + whole-file hash snapshot in O(1) (no re-read); failing that, an
  // async, yielding re-verify rebuilds them without blocking the event loop.
  // opts.isCancelled aborts a long re-verify; opts.onVerifyProgress(0..1) drives the UI.
  async startReceive (targetPath, meta, opts = {}) {
    const isCancelled = opts.isCancelled || (() => false)
    const dir = path.dirname(targetPath)
    const base = path.basename(targetPath)
    // Visible partial (no leading dot) so an in-progress download shows in the
    // destination folder; the distinct ".overlay-partial" suffix keeps host-app
    // sweeps keyed on a plain ".partial" suffix from deleting a paused overlay
    // partial.
    const partialPath = path.join(dir, base + PARTIAL_SUFFIX)
    const journalPath = this._journalPathFor(targetPath)

    fs.mkdirSync(dir, { recursive: true })

    let resumed = false
    try { resumed = fs.statSync(partialPath).size === meta.size } catch {}

    let received = new Set()
    let hasher = meta.contentHash ? createStreamingHasher({ size: meta.size }) : null
    let hashFrontier = 0

    if (resumed) {
      const j = journalPath ? this._loadJournal(journalPath, partialPath, meta) : null
      if (j) {
        received = j.received
        hashFrontier = j.hashFrontier
        if (meta.contentHash) hasher = createStreamingHasher({ size: meta.size, restore: { state: j.hasherState, bytes: j.hasherBytes } })
      } else {
        const rec = await this._recoverPartialAsync(partialPath, meta, isCancelled, opts.onVerifyProgress)
        received = rec.received; hasher = rec.hasher; hashFrontier = rec.hashFrontier
      }
    } else {
      if (journalPath) { try { fs.unlinkSync(journalPath) } catch {} }
    }

    if (isCancelled()) { const e = new Error('receive cancelled during setup'); e.code = 'ECANCELLED'; throw e }

    // ONE persistent fd for the whole transfer — positioned writeSync/fs.read never
    // move a shared cursor, so a single handle serves the chunk writes, the hash
    // pump's gap read-back, and the journal fsync. Replaces an openSync+closeSync per
    // chunk; 'w+' creates+truncates the fresh partial in the same open.
    const fd = fs.openSync(partialPath, resumed ? 'r+' : 'w+')
    if (!resumed) {
      try { fs.ftruncateSync(fd, meta.size) } catch (err) { try { fs.closeSync(fd) } catch {}; throw err }
    }

    const total = meta.chunks.length
    const state = {
      partialPath,
      targetPath,
      journalPath,
      chunks: meta.chunks,
      received,
      bitmap: bitmapOf(received, total),
      total,
      size: meta.size,
      contentHash: meta.contentHash || null,
      hasher,
      hashFrontier,
      advancePromise: null,
      draining: false,
      sinceFlush: 0,
      lastFlush: 0,
      flushing: false,
      flushPending: false,
      fd,
      // Bounded stash of just-received verified chunk buffers so the hash pump feeds
      // from memory instead of reading the bytes back off disk. Never load-bearing:
      // bytes hit disk first; a miss falls back to read-back.
      memChunks: new Map(),
      memBytes: 0,
      stats: { readbacks: 0, stashHits: 0 }
    }

    // A prior transfer for this path that ended via _fail (stall / all-peers-
    // gone / disk error) leaves its state here with an open fd — close it before
    // overwriting so a retry/resume of the same file can't orphan the fd.
    const prev = this._active.get(targetPath)
    if (prev) this._closeFd(prev)

    this._active.set(targetPath, state)
    // A fresh transfer has nothing worth journaling yet; a resume that recovered
    // chunks persists them now so an immediate re-pause is O(1).
    if (received.size > 0) this._flushJournal(state)
    return state
  }

  // Rebuild the received-set from a same-size partial without blocking the loop:
  // async reads, a yield every VERIFY_YIELD_EVERY chunks, feeding the contiguous
  // prefix into the whole-file hasher inline (single pass, no second read).
  async _recoverPartialAsync (partialPath, meta, isCancelled, onVerifyProgress) {
    const received = new Set()
    const hasher = meta.contentHash ? createStreamingHasher({ size: meta.size }) : null
    let hashFrontier = 0
    const total = meta.chunks.length
    const maxLen = meta.chunks.reduce((m, c) => (c.length > m ? c.length : m), 0)
    const buf = Buffer.allocUnsafe(maxLen)
    let lastPct = -1
    onVerifyProgress?.(0)
    const fd = await fs.open(partialPath, 'r')
    try {
      for (let i = 0; i < total; i++) {
        if (isCancelled()) { const e = new Error('receive recovery cancelled'); e.code = 'ECANCELLED'; throw e }
        const ci = meta.chunks[i]
        let n = 0
        try { n = await fs.read(fd, buf, 0, ci.length, ci.offset) } catch {}
        const view = buf.subarray(0, ci.length)
        if (n === ci.length && hashChunk(view) === ci.hash) {
          received.add(i)
          if (hasher && i === hashFrontier) { hasher.update(view); hashFrontier++ }
        }
        if ((i & (VERIFY_YIELD_EVERY - 1)) === VERIFY_YIELD_EVERY - 1) {
          const pct = Math.floor(((i + 1) / total) * 100)
          if (pct !== lastPct) { lastPct = pct; onVerifyProgress?.(pct / 100) }
          await yieldToLoop()
        }
      }
    } finally {
      try { await fs.close(fd) } catch {}
    }
    onVerifyProgress?.(1)
    return { received, hasher, hashFrontier }
  }

  _encodeJournal (state) {
    const total = state.total
    const bm = state.bitmap
    const ch = state.contentHash ? Buffer.from(state.contentHash, 'hex') : Buffer.alloc(32)
    const snap = state.hasher ? state.hasher.snapshot() : { state: Buffer.alloc(0), bytes: 0 }
    const s = { start: 0, end: 0, buffer: null }
    c.uint32.preencode(s, JOURNAL_MAGIC)
    c.uint32.preencode(s, sodium.crypto_generichash_STATEBYTES)
    c.string.preencode(s, state.partialPath)
    c.uint64.preencode(s, state.size)
    c.uint32.preencode(s, total)
    c.fixed32.preencode(s, ch)
    c.uint32.preencode(s, state.hashFrontier)
    c.uint64.preencode(s, snap.bytes)
    c.buffer.preencode(s, snap.state)
    c.buffer.preencode(s, bm)
    s.buffer = Buffer.allocUnsafe(s.end)
    c.uint32.encode(s, JOURNAL_MAGIC)
    c.uint32.encode(s, sodium.crypto_generichash_STATEBYTES)
    c.string.encode(s, state.partialPath)
    c.uint64.encode(s, state.size)
    c.uint32.encode(s, total)
    c.fixed32.encode(s, ch)
    c.uint32.encode(s, state.hashFrontier)
    c.uint64.encode(s, snap.bytes)
    c.buffer.encode(s, snap.state)
    c.buffer.encode(s, bm)
    return s.buffer
  }

  // Returns the resume state only when the journal is for this partial, binds to
  // this content, and its snapshot is restorable on this libsodium build; else null
  // so the caller falls back to the async re-verify.
  _loadJournal (journalPath, partialPath, meta) {
    let raw
    try { raw = fs.readFileSync(journalPath) } catch { return null }
    try {
      const s = { start: 0, end: raw.length, buffer: raw }
      if (c.uint32.decode(s) !== JOURNAL_MAGIC) return null
      const stateBytes = c.uint32.decode(s)
      const storedPartial = c.string.decode(s)
      const size = c.uint64.decode(s)
      const total = c.uint32.decode(s)
      const ch = c.fixed32.decode(s).toString('hex')
      const hashFrontier = c.uint32.decode(s)
      const hasherBytes = c.uint64.decode(s)
      const hasherState = c.buffer.decode(s)
      const bm = c.buffer.decode(s)
      // F1: never trust a journal we cannot whole-file-verify. Both finalize and the
      // legacy receive path skip the whole-file hash when contentHash is absent, so a
      // FOREIGN journal with a matching size + chunk-count (a stale .overlay-partial
      // for different content the CDC split into the same number of chunks) would be
      // trusted and finalized as merged old+new bytes, undetected. Require a content
      // hash to resume from a journal; without one the caller falls back to
      // _recoverPartialAsync, which re-verifies every chunk by its per-chunk hash.
      if (!meta.contentHash) return null
      if (storedPartial !== partialPath) return null
      if (size !== meta.size || total !== meta.chunks.length) return null
      if (ch !== meta.contentHash) return null
      if (meta.contentHash) {
        if (stateBytes !== sodium.crypto_generichash_STATEBYTES) return null
        if (hasherState.length !== sodium.crypto_generichash_STATEBYTES) return null
      }
      const received = new Set()
      for (let i = 0; i < total; i++) if (bm[i >> 3] & (1 << (i & 7))) received.add(i)
      return { received, hashFrontier, hasherState, hasherBytes }
    } catch { return null }
  }

  // Best-effort async crash-hedge flush: never blocks the receive loop, single-flight
  // (a flush requested while one runs coalesces into one more pass). fsync the partial
  // BEFORE the journal references it so a power-loss can never leave the journal
  // marking a chunk received whose bytes aren't durable.
  _flushJournal (state) {
    if (!state.contentHash || !state.journalPath || state.fd == null) return
    if (state.flushing) { state.flushPending = true; return }
    if (Date.now() - state.lastFlush < JOURNAL_FLUSH_INTERVAL_MS) return
    state.flushing = true
    this._drainFlush(state)
  }

  async _drainFlush (state) {
    do {
      state.flushPending = false
      state.lastFlush = Date.now()
      if (state.fd == null) break
      let buf
      try { buf = this._encodeJournal(state) } catch { break }
      const tmp = state.journalPath + '.tmp'
      try {
        // fsync is best-effort and swallowed on purpose: on Windows, fsync
        // (FlushFileBuffers) on a read-only handle throws EPERM benignly, and we still
        // want the journal to persist so resume stays O(1). The EIO write-back hazard
        // this could mask is already closed upstream — F1 refuses to trust a journal
        // without a contentHash, and the finalize whole-file hash re-verifies the
        // gated flow — so skipping the commit here (former "F3") only regressed Windows.
        try { await fs.fsync(state.fd) } catch {}
        await fs.writeFile(tmp, buf)
        if (state.fd == null) break // paused/cancelled mid-flush — don't re-create the journal
        await fs.rename(tmp, state.journalPath)
      } catch { try { await fs.unlink(tmp) } catch {} }
    } while (state.flushPending && state.fd != null && state.contentHash)
    try { await fs.unlink(state.journalPath + '.tmp') } catch {}
    state.flushing = false
  }

  // Synchronous durable flush for pause/shutdown, where the app may quit before an
  // async flush would land.
  _flushJournalSync (state) {
    if (!state.contentHash || !state.journalPath) return
    let buf
    try { buf = this._encodeJournal(state) } catch { return }
    // fsync swallowed on purpose (Windows read-only-handle EPERM) — see _drainFlush.
    if (state.fd != null) { try { fs.fsyncSync(state.fd) } catch {} }
    try {
      const tmp = state.journalPath + '.tmp'
      fs.writeFileSync(tmp, buf)
      fs.renameSync(tmp, state.journalPath)
      state.lastFlush = Date.now()
    } catch { try { fs.unlinkSync(state.journalPath + '.tmp') } catch {} }
  }

  cleanJournals (maxAge) { return cleanupOrphanedJournals(this._journalDir, maxAge) }

  async _hashWholeFileAsync (filePath, size) {
    const h = createStreamingHasher({ size })
    for await (const buf of readFileBlocks(filePath, size, 8 * 1024 * 1024)) {
      h.update(buf)
      await yieldToLoop()
    }
    return h.digest()
  }

  // Advance the whole-file hash over the contiguous run of received chunks
  // as a single-flight BACKGROUND pump: chunk index order == file offset order, so
  // once chunk `hashFrontier` is present we feed its bytes and move on. The drain is
  // async + yielding so a large contiguous run that suddenly becomes available (a
  // gap filling after a low-frontier resume) cannot block the event loop.
  // Single-flight is `state.draining`, set/cleared SYNCHRONOUSLY inside _drainHash —
  // a stash-fed drain completes without awaiting, so a promise-based gate would stay
  // stale until its microtask clear and block same-macrotask restarts (protomux
  // delivers frame bursts synchronously). advancePromise is only the awaitable
  // handle for finalize/pause; its clear is guarded against nulling a newer drain.
  _advanceHash (state) {
    if (!state.hasher || state.draining) return
    if (!(state.hashFrontier < state.chunks.length && state.received.has(state.hashFrontier))) return
    const p = this._drainHash(state)
    state.advancePromise = p
    p.catch(() => {}).then(() => { if (state.advancePromise === p) state.advancePromise = null })
  }

  async _drainHash (state) {
    state.draining = true
    try {
      let sinceYield = 0
      while (state.fd != null && state.hashFrontier < state.chunks.length && state.received.has(state.hashFrontier)) {
        const i = state.hashFrontier
        const c = state.chunks[i]
        let buf = state.memChunks.get(i)
        if (buf !== undefined) {
          state.memChunks.delete(i)
          state.memBytes -= buf.length
          state.stats.stashHits++
        } else {
          buf = Buffer.alloc(c.length)
          try { await fs.read(state.fd, buf, 0, c.length, c.offset) } catch { return }
          state.stats.readbacks++
        }
        state.hasher.update(buf)
        state.hashFrontier++
        // Yield by BYTE volume: the stash path has no awaits, so a chunk-count
        // cadence would let a gap-fill hash the whole stash synchronously inside
        // the network event that delivered the gap chunk.
        sinceYield += buf.length
        if (sinceYield >= DRAIN_YIELD_BYTES) { sinceYield = 0; await yieldToLoop() }
      }
    } finally {
      state.draining = false
    }
  }

  // Close the persistent fd — MUST run before finalize's rename (an open handle
  // blocks the rename on Windows) — and drop the chunk stash.
  _closeFd (state) {
    if (state.fd != null) {
      try { fs.closeSync(state.fd) } catch {}
      state.fd = null
    }
    state.memChunks.clear()
    state.memBytes = 0
  }

  /**
   * Write a received chunk to the partial file. Verifies the hash.
   *
   * @param {string} targetPath - the final file path (used as key)
   * @param {number} index - chunk index
   * @param {Buffer} data - raw chunk bytes
   * @returns {{ ok: boolean, error?: string }}
   */
  writeChunk (targetPath, index, data) {
    const state = this._active.get(targetPath)
    if (!state) return { ok: false, error: 'no active transfer' }
    if (index < 0 || index >= state.chunks.length) return { ok: false, error: 'index out of range' }
    // Terminal race (chunk landed after close) — codeless so the scheduler
    // re-assigns instead of failing the fetch.
    if (state.fd == null) return { ok: false, error: 'transfer closed' }

    const expected = state.chunks[index]

    // Verify hash
    const actual = hashChunk(data)
    if (actual !== expected.hash) {
      return { ok: false, error: `hash mismatch at index ${index}: expected ${expected.hash.slice(0, 16)}... got ${actual.slice(0, 16)}...` }
    }

    // Verify length
    if (data.length !== expected.length) {
      return { ok: false, error: `length mismatch at index ${index}: expected ${expected.length} got ${data.length}` }
    }

    // Write to partial at the chunk's offset through the persistent fd. A local
    // I/O failure here (ENOSPC / EACCES / EROFS) is fatal and non-retryable —
    // return its code so the scheduler fails the fetch instead of looping over
    // other peers. Loop on a SHORT count: libuv swallows an error after partial
    // progress and returns short without throwing; retrying the remainder
    // surfaces the real coded error instead of leaving a silent hole the
    // stash-fed digest would never see.
    try {
      let written = 0
      while (written < data.length) {
        const n = fs.writeSync(state.fd, data, written, data.length - written, expected.offset + written)
        if (!(n > 0)) { const e = new Error(`short write at index ${index}: ${written}/${data.length} bytes`); e.code = 'EIO'; throw e }
        written += n
      }
    } catch (err) {
      return { ok: false, error: err.message, code: err.code }
    }

    state.received.add(index)
    state.bitmap[index >> 3] |= 1 << (index & 7)
    // Stash only what the pump can consume cleanly: skip when already hashed or
    // stashed, when the pump is mid-drain on exactly this index, or over cap.
    // Copied, not aliased — wire buffers are views into shared network slabs (udx
    // read slab, decrypted in place by secret-stream), so retaining `data` would
    // pin whole slabs and bet the digest on their write-once behavior.
    if (state.hasher && !state.memChunks.has(index) && state.memBytes + data.length <= this._memStashBytes &&
        (index > state.hashFrontier || (index === state.hashFrontier && !state.draining))) {
      state.memChunks.set(index, Buffer.from(data))
      state.memBytes += data.length
    }
    this._advanceHash(state)
    if (++state.sinceFlush >= JOURNAL_FLUSH_EVERY) { state.sinceFlush = 0; this._flushJournal(state) }

    return { ok: true }
  }

  /**
   * Check if a transfer is complete (all chunks received).
   *
   * @param {string} targetPath
   * @returns {boolean}
   */
  isComplete (targetPath) {
    const state = this._active.get(targetPath)
    if (!state) return false
    return state.received.size === state.total
  }

  /**
   * Finalize a completed transfer — atomic rename from partial to target.
   *
   * @param {string} targetPath
   * @returns {{ ok: boolean, error?: string }}
   */
  async finalize (targetPath) {
    const state = this._active.get(targetPath)
    if (!state) return { ok: false, error: 'no active transfer' }
    if (state.received.size !== state.total) {
      return { ok: false, error: `incomplete: ${state.received.size}/${state.total} chunks` }
    }

    // whole-file integrity — computed incrementally by the background hash
    // pump during the transfer. Kick the pump and await it to quiescence, then read
    // the digest (no full re-read). On a mismatch, drop the corrupt partial so a
    // retry starts clean.
    if (state.hasher) {
      this._advanceHash(state)
      while (state.advancePromise) { try { await state.advancePromise } catch {} }
    }
    if (state.contentHash) {
      const actual = state.hashFrontier === state.chunks.length ? state.hasher.digest() : null
      if (actual !== state.contentHash) {
        this._closeFd(state)
        try { fs.unlinkSync(state.partialPath) } catch {}
        if (state.journalPath) { try { fs.unlinkSync(state.journalPath) } catch {} }
        this._active.delete(targetPath)
        return { ok: false, error: 'content-hash mismatch', code: 'EHASHMISMATCH' }
      }
    }
    this._closeFd(state)

    try {
      fs.renameSync(state.partialPath, state.targetPath)
    } catch (err) {
      // Carry the code (routes through the coded local-I/O rethrow) and clear the
      // state — the partial + journal stay for a clean resume-retry.
      this._active.delete(targetPath)
      return { ok: false, error: 'rename failed: ' + err.message, code: err.code }
    }

    if (state.journalPath) { try { fs.unlinkSync(state.journalPath) } catch {} }
    this._active.delete(targetPath)
    return { ok: true }
  }

  // Stop receiving but KEEP the partial on disk so a later startReceive
  // verifies and resumes it. Distinct from cancel(), which unlinks the partial.
  // Drains the in-flight hash advance to the full contiguous frontier first, so the
  // journal captures it and resume stays O(1) (no re-read) and deterministic.
  async pause (targetPath) {
    const state = this._active.get(targetPath)
    if (!state) return
    if (state.hasher) {
      this._advanceHash(state)
      while (state.advancePromise) { try { await state.advancePromise } catch {} }
    }
    this._flushJournalSync(state)
    this._closeFd(state)
    this._active.delete(targetPath)
  }

  /**
   * Cancel an active transfer and clean up the partial file.
   *
   * @param {string} targetPath
   */
  cancel (targetPath) {
    const state = this._active.get(targetPath)
    if (!state) return

    this._closeFd(state)
    try {
      fs.unlinkSync(state.partialPath)
    } catch {
      // partial file may not exist
    }
    if (state.journalPath) { try { fs.unlinkSync(state.journalPath) } catch {} }

    this._active.delete(targetPath)
  }

  /**
   * Get transfer progress for an active transfer.
   *
   * @param {string} targetPath
   * @returns {{ received: number, total: number, percentage: number } | null}
   */
  getProgress (targetPath) {
    const state = this._active.get(targetPath)
    if (!state) return null

    return {
      received: state.received.size,
      total: state.total,
      percentage: state.total > 0 ? Math.round(state.received.size / state.total * 100) : 0
    }
  }

  /**
   * List all active transfers.
   *
   * @returns {Array<{ path: string, received: number, total: number, percentage: number }>}
   */
  listActive () {
    const result = []
    for (const [targetPath, state] of this._active) {
      result.push({
        path: targetPath,
        received: state.received.size,
        total: state.total,
        percentage: state.total > 0 ? Math.round(state.received.size / state.total * 100) : 0
      })
    }
    return result
  }

  /**
   * Clean up stale partial files in a directory (older than maxAge).
   *
   * @param {string} dir - directory to scan
   * @param {number} [maxAge=86400000] - max age in ms (default 24h)
   * @returns {string[]} paths of cleaned files
   */
  cleanPartials (dir, maxAge = 86400000) {
    const cleaned = []
    try {
      const entries = fs.readdirSync(dir)
      const now = Date.now()
      for (const entry of entries) {
        if (!entry.endsWith(PARTIAL_SUFFIX)) continue
        const full = path.join(dir, entry)
        try {
          const stat = fs.statSync(full)
          if (now - stat.mtimeMs > maxAge) {
            fs.unlinkSync(full)
            cleaned.push(full)
          }
        } catch {
          // skip unreadable files
        }
      }
    } catch {
      // directory may not exist
    }
    return cleaned
  }
}
/**
 * Tree — content-addressable directory hashing for hyper-overlay
 *
 * A tree is a canonical serialization of a directory's immediate entries.
 * Each entry is one of: file, subdirectory, symlink. The tree's identity
 * is blake2b-256 of its canonical bytes.
 *
 * Format (P.10 Phase 0.5a):
 *
 *   tree := "pgh-tree-1\n" ||
 *           varint(n_entries) ||
 *           entry[0] || ... || entry[n-1]
 *
 *   entry := u8(kind)  ||           // 0=file, 1=dir, 2=symlink
 *            u8(exec)  ||           // 0 or 1; always 0 for dir/symlink
 *            varint(name_len) || name ||  // UTF-8 NFC, no NUL, no "/"
 *            32_bytes(child_hash)
 *
 *   tree_hash := blake2b-256(tree_bytes)
 *
 * Identity fields (in the hash): kind, exec-bit, name, child_hash.
 * Explicitly excluded: mtime, size, uid/gid, full mode.
 *
 * Entries MUST be sorted byte-wise by name (after NFC normalization).
 * Encoders emit sorted; decoders reject unsorted trees.
 *
 * Symlinks: child_hash = blake2b-256 of the target path bytes (not followed).
 * Empty directories: zero-entry tree, valid, deterministic.
 */

import fs from '#fs'
import path from '#path'
import crypto from 'hypercore-crypto'
import c from 'compact-encoding'

// ── Constants ─────────────────────────────────────────────────

export const MAGIC = Buffer.from('pgh-tree-1\n', 'utf8')
export const KIND_FILE = 0
export const KIND_DIR = 1
export const KIND_SYMLINK = 2

// Windows reserved device names (case-insensitive, with or without extension)
const WINDOWS_RESERVED = new Set([
  'CON', 'PRN', 'AUX', 'NUL',
  'COM1', 'COM2', 'COM3', 'COM4', 'COM5', 'COM6', 'COM7', 'COM8', 'COM9',
  'LPT1', 'LPT2', 'LPT3', 'LPT4', 'LPT5', 'LPT6', 'LPT7', 'LPT8', 'LPT9'
])

// Chars forbidden in filenames on Windows (beyond format-layer rules)
// eslint-disable-next-line no-control-regex
const WINDOWS_FORBIDDEN = /[\\:*?"<>|\x00-\x1f]/

// Default skip list for walkTree — minimal, just obvious platform cruft.
// Consumers that want more (e.g. .git for pgh publish) pass their own.
export const DEFAULT_SKIP = new Set(['.DS_Store', 'Thumbs.db'])

// ── Name validation (format layer) ────────────────────────────

/**
 * Normalize a filename for hashing and validate format-layer rules.
 * Throws on unrepresentable names. Returns the canonical form.
 *
 * @param {string} name - single path component (no "/")
 * @returns {string} NFC-normalized name
 */
export function normalizeName (name) {
  if (typeof name !== 'string') {
    throw new Error('tree entry name must be string, got ' + typeof name)
  }
  if (name.length === 0) {
    throw new Error('tree entry name cannot be empty')
  }
  if (name === '.' || name === '..') {
    throw new Error('tree entry name cannot be "." or ".."')
  }
  if (name.indexOf('/') !== -1) {
    throw new Error('tree entry name cannot contain "/": ' + JSON.stringify(name))
  }
  if (name.indexOf('\x00') !== -1) {
    throw new Error('tree entry name cannot contain NUL: ' + JSON.stringify(name))
  }

  const normalized = name.normalize('NFC')

  // Verify the normalized form is valid UTF-8 that round-trips through
  // Buffer (catches lone surrogates and other malformed sequences).
  const asBytes = Buffer.from(normalized, 'utf8')
  if (asBytes.toString('utf8') !== normalized) {
    throw new Error('tree entry name is not valid UTF-8: ' + JSON.stringify(name))
  }

  return normalized
}

// ── Consumer-policy layer ─────────────────────────────────────

/**
 * Check a name against Windows compatibility rules.
 * Does NOT throw — returns a reason string (or null if the name is OK).
 * Used by pgh publish for strict cross-platform validation.
 *
 * @param {string} name
 * @returns {string|null} reason if incompatible, null if OK
 */
export function windowsIncompatibleReason (name) {
  if (WINDOWS_FORBIDDEN.test(name)) {
    return 'contains Windows-forbidden character (\\:*?"<>| or control code)'
  }
  const trimmed = name.replace(/\.+$/, '').replace(/ +$/, '')
  if (trimmed !== name) {
    return 'trailing "." or space (Windows strips these silently)'
  }
  // Reserved device names apply with any extension: AUX.log, PRN.txt etc.
  const base = name.split('.')[0].toUpperCase()
  if (WINDOWS_RESERVED.has(base)) {
    return `"${base}" is a reserved Windows device name (even with extension)`
  }
  return null
}

// ── Canonical encoding ────────────────────────────────────────

/**
 * Encode a single entry to its canonical byte representation.
 *
 * @param {object} state - compact-encoding state
 * @param {{kind: number, exec: number, name: string, childHash: Buffer|string}} e
 */
function encodeEntry (state, e) {
  if (e.kind !== KIND_FILE && e.kind !== KIND_DIR && e.kind !== KIND_SYMLINK) {
    throw new Error('invalid entry kind: ' + e.kind)
  }
  if (e.exec !== 0 && e.exec !== 1) {
    throw new Error('entry exec must be 0 or 1')
  }
  if (e.kind !== KIND_FILE && e.exec !== 0) {
    throw new Error('non-file entry must have exec=0')
  }

  const hash = toBuffer32(e.childHash)

  c.uint8.encode(state, e.kind)
  c.uint8.encode(state, e.exec)
  c.string.encode(state, e.name) // compact-encoding: varint len + utf8 bytes
  state.buffer.set(hash, state.start)
  state.start += 32
}

function preencodeEntry (state, e) {
  c.uint8.preencode(state, e.kind)
  c.uint8.preencode(state, e.exec)
  c.string.preencode(state, e.name)
  state.end += 32
}

/**
 * Serialize a list of entries to canonical tree bytes.
 * Entries are sorted + normalized as a side-effect of the call.
 *
 * @param {Array<{kind: number, exec: number, name: string, childHash: Buffer|string}>} entries
 * @returns {Buffer}
 */
export function encodeTree (entries) {
  const normalized = entries.map(e => ({
    kind: e.kind,
    exec: e.exec || 0,
    name: normalizeName(e.name),
    childHash: e.childHash
  }))
  normalized.sort(compareEntries)

  // Sanity: no duplicate names after normalization
  for (let i = 1; i < normalized.length; i++) {
    if (normalized[i].name === normalized[i - 1].name) {
      throw new Error('duplicate entry name after NFC normalization: ' + normalized[i].name)
    }
  }

  const state = { start: 0, end: 0, buffer: null }
  state.end += MAGIC.length
  c.uint.preencode(state, normalized.length)
  for (const e of normalized) preencodeEntry(state, e)

  state.buffer = Buffer.alloc(state.end)

  state.buffer.set(MAGIC, state.start)
  state.start += MAGIC.length
  c.uint.encode(state, normalized.length)
  for (const e of normalized) encodeEntry(state, e)

  return state.buffer
}

/**
 * Byte-wise comparator for entry names (after NFC normalization).
 */
function compareEntries (a, b) {
  const ab = Buffer.from(a.name, 'utf8')
  const bb = Buffer.from(b.name, 'utf8')
  return Buffer.compare(ab, bb)
}

/**
 * Decode canonical tree bytes back to an entries list.
 * Rejects unsorted or malformed trees.
 *
 * @param {Buffer} buf
 * @returns {Array<{kind: number, exec: number, name: string, childHash: string}>}
 */
export function decodeTree (buf) {
  if (!Buffer.isBuffer(buf)) throw new Error('decodeTree expects a Buffer')
  if (buf.length < MAGIC.length) throw new Error('tree too short')
  if (buf.compare(MAGIC, 0, MAGIC.length, 0, MAGIC.length) !== 0) {
    throw new Error('tree magic mismatch (expected "pgh-tree-1")')
  }

  const state = { start: MAGIC.length, end: buf.length, buffer: buf }
  const count = c.uint.decode(state)
  const entries = []

  let prevName = null
  for (let i = 0; i < count; i++) {
    const kind = c.uint8.decode(state)
    const exec = c.uint8.decode(state)
    const name = c.string.decode(state)

    if (state.start + 32 > state.end) throw new Error('truncated tree: missing hash bytes')
    const childHash = buf.subarray(state.start, state.start + 32).toString('hex')
    state.start += 32

    // Validate format rules on read — reject invalid trees rather than silently accept
    const normalized = normalizeName(name)
    if (normalized !== name) {
      throw new Error('tree entry name not NFC-normalized: ' + JSON.stringify(name))
    }
    if (kind !== KIND_FILE && exec !== 0) {
      throw new Error('non-file entry with exec=1 is invalid')
    }
    if (prevName !== null) {
      const cmp = Buffer.compare(Buffer.from(prevName, 'utf8'), Buffer.from(name, 'utf8'))
      if (cmp === 0) throw new Error('tree has duplicate entry: ' + name)
      if (cmp > 0) throw new Error('tree entries not sorted: ' + prevName + ' before ' + name)
    }
    prevName = name

    entries.push({ kind, exec, name, childHash })
  }

  if (state.start !== state.end) throw new Error('tree has trailing bytes after entries')

  return entries
}

/**
 * Compute the tree hash of an entries list.
 *
 * @param {Array<{kind: number, exec: number, name: string, childHash: Buffer|string}>} entries
 * @returns {string} hex-encoded blake2b-256
 */
export function computeTreeHash (entries) {
  const buf = encodeTree(entries)
  return crypto.data(buf).toString('hex')
}

// ── Helpers ───────────────────────────────────────────────────

function toBuffer32 (hashOrBuf) {
  if (Buffer.isBuffer(hashOrBuf)) {
    if (hashOrBuf.length !== 32) throw new Error('childHash buffer must be 32 bytes')
    return hashOrBuf
  }
  if (typeof hashOrBuf !== 'string') {
    throw new Error('childHash must be Buffer or hex string')
  }
  if (hashOrBuf.length !== 64) throw new Error('childHash hex string must be 64 chars')
  return Buffer.from(hashOrBuf, 'hex')
}

// ── Filesystem walk ───────────────────────────────────────────

/**
 * Walk a directory recursively, producing tree hashes bottom-up.
 *
 * Returns a nested object keyed by path, where each entry has:
 *   { hash: hex, entries: [{kind, exec, name, childHash, size?}] }
 *
 * File entries carry their content hash as childHash (blake2b of bytes).
 * Dir entries carry the subtree hash.
 * Symlink entries carry blake2b of the link target bytes.
 *
 * @param {string} rootDir - absolute path to scan
 * @param {object} [opts]
 * @param {Set<string>} [opts.skip] - basenames to skip (default: DEFAULT_SKIP)
 * @param {(relPath: string, baseName: string) => boolean} [opts.matcher]
 *   Optional gitignore-style matcher. Returns true to EXCLUDE an entry.
 *   Receives the path relative to rootDir plus the basename. Applies to
 *   all kinds (file/dir/symlink). Used by `pgh publish` for publishIgnore.
 * @returns {Map<string, {hash: string, entries: Array, size: number}>}
 *          map keyed by relative path ('' = root); root tree is at key ''
 */
export function walkTree (rootDir, opts = {}) {
  const skip = opts.skip || DEFAULT_SKIP
  const matcher = opts.matcher || null
  const trees = new Map()

  function visit (relPath) {
    const absPath = relPath === '' ? rootDir : path.join(rootDir, relPath)
    const raw = fs.readdirSync(absPath)
    const entries = []
    let totalSize = 0

    for (const name of raw) {
      if (skip.has(name)) continue

      const entryAbs = path.join(absPath, name)
      const entryRel = relPath === '' ? name : relPath + '/' + name

      if (matcher && matcher(entryRel, name)) continue

      let stat
      try {
        stat = fs.lstatSync(entryAbs)
      } catch {
        continue
      }

      if (stat.isSymbolicLink()) {
        const target = fs.readlinkSync(entryAbs)
        const targetBytes = Buffer.from(target, 'utf8')
        const childHash = crypto.data(targetBytes).toString('hex')
        entries.push({
          kind: KIND_SYMLINK,
          exec: 0,
          name: normalizeName(name),
          childHash,
          size: targetBytes.length,
          linkTarget: target
        })
        totalSize += targetBytes.length
      } else if (stat.isDirectory()) {
        visit(entryRel)
        const sub = trees.get(entryRel)
        if (!sub) continue
        entries.push({
          kind: KIND_DIR,
          exec: 0,
          name: normalizeName(name),
          childHash: sub.hash,
          size: sub.size
        })
        totalSize += sub.size
      } else if (stat.isFile()) {
        const content = fs.readFileSync(entryAbs)
        const childHash = crypto.data(content).toString('hex')
        // Executable bit from stat.mode — works on POSIX; Windows always 0
        const exec = (stat.mode & 0o100) ? 1 : 0
        entries.push({
          kind: KIND_FILE,
          exec,
          name: normalizeName(name),
          childHash,
          size: stat.size
        })
        totalSize += stat.size
      }
      // device files, sockets, fifos: silently skipped (unrepresentable)
    }

    entries.sort(compareEntries)
    const hash = computeTreeHash(entries)
    trees.set(relPath, { hash, entries, size: totalSize })
  }

  visit('')
  return trees
}

// ── Publish-time validation (consumer policy) ─────────────────

/**
 * Scan entries (recursively via walkTree output) for cross-platform-hostile
 * names. Returns an array of {path, name, reason} for every problem found.
 * Does NOT throw — caller decides how to present.
 *
 * @param {Map<string, {hash: string, entries: Array}>} trees - from walkTree
 * @returns {Array<{path: string, name: string, reason: string}>}
 */
export function validateForPublish (trees) {
  const problems = []
  for (const [relPath, tree] of trees) {
    for (const e of tree.entries) {
      const reason = windowsIncompatibleReason(e.name)
      if (reason) {
        problems.push({
          path: relPath ? relPath + '/' + e.name : e.name,
          name: e.name,
          reason
        })
      }
    }
  }
  return problems
}
function isBuffer(value) {
  return Buffer.isBuffer(value) || value instanceof Uint8Array
}

function isEncoding(encoding) {
  return Buffer.isEncoding(encoding)
}

function alloc(size, fill, encoding) {
  return Buffer.alloc(size, fill, encoding)
}

function allocUnsafe(size) {
  return Buffer.allocUnsafe(size)
}

function allocUnsafeSlow(size) {
  return Buffer.allocUnsafeSlow(size)
}

function byteLength(string, encoding) {
  return Buffer.byteLength(string, encoding)
}

function compare(a, b) {
  return Buffer.compare(a, b)
}

function concat(buffers, totalLength) {
  return Buffer.concat(buffers, totalLength)
}

function copy(source, target, targetStart, start, end) {
  return toBuffer(source).copy(target, targetStart, start, end)
}

function equals(a, b) {
  return toBuffer(a).equals(b)
}

function fill(buffer, value, offset, end, encoding) {
  return toBuffer(buffer).fill(value, offset, end, encoding)
}

function from(value, encodingOrOffset, length) {
  return Buffer.from(value, encodingOrOffset, length)
}

function includes(buffer, value, byteOffset, encoding) {
  return toBuffer(buffer).includes(value, byteOffset, encoding)
}

function indexOf(buffer, value, byfeOffset, encoding) {
  return toBuffer(buffer).indexOf(value, byfeOffset, encoding)
}

function lastIndexOf(buffer, value, byteOffset, encoding) {
  return toBuffer(buffer).lastIndexOf(value, byteOffset, encoding)
}

function swap16(buffer) {
  return toBuffer(buffer).swap16()
}

function swap32(buffer) {
  return toBuffer(buffer).swap32()
}

function swap64(buffer) {
  return toBuffer(buffer).swap64()
}

function toBuffer(buffer) {
  if (Buffer.isBuffer(buffer)) return buffer
  return Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

function toString(buffer, encoding, start, end) {
  return toBuffer(buffer).toString(encoding, start, end)
}

function write(buffer, string, offset, length, encoding) {
  return toBuffer(buffer).write(string, offset, length, encoding)
}

function readDoubleBE(buffer, offset) {
  return toBuffer(buffer).readDoubleBE(offset)
}

function readDoubleLE(buffer, offset) {
  return toBuffer(buffer).readDoubleLE(offset)
}

function readFloatBE(buffer, offset) {
  return toBuffer(buffer).readFloatBE(offset)
}

function readFloatLE(buffer, offset) {
  return toBuffer(buffer).readFloatLE(offset)
}

function readInt32BE(buffer, offset) {
  return toBuffer(buffer).readInt32BE(offset)
}

function readInt32LE(buffer, offset) {
  return toBuffer(buffer).readInt32LE(offset)
}

function readUInt32BE(buffer, offset) {
  return toBuffer(buffer).readUInt32BE(offset)
}

function readUInt32LE(buffer, offset) {
  return toBuffer(buffer).readUInt32LE(offset)
}

function writeDoubleBE(buffer, value, offset) {
  return toBuffer(buffer).writeDoubleBE(value, offset)
}

function writeDoubleLE(buffer, value, offset) {
  return toBuffer(buffer).writeDoubleLE(value, offset)
}

function writeFloatBE(buffer, value, offset) {
  return toBuffer(buffer).writeFloatBE(value, offset)
}

function writeFloatLE(buffer, value, offset) {
  return toBuffer(buffer).writeFloatLE(value, offset)
}

function writeInt32BE(buffer, value, offset) {
  return toBuffer(buffer).writeInt32BE(value, offset)
}

function writeInt32LE(buffer, value, offset) {
  return toBuffer(buffer).writeInt32LE(value, offset)
}

function writeUInt32BE(buffer, value, offset) {
  return toBuffer(buffer).writeUInt32BE(value, offset)
}

function writeUInt32LE(buffer, value, offset) {
  return toBuffer(buffer).writeUInt32LE(value, offset)
}

module.exports = {
  isBuffer,
  isEncoding,
  alloc,
  allocUnsafe,
  allocUnsafeSlow,
  byteLength,
  compare,
  concat,
  copy,
  equals,
  fill,
  from,
  includes,
  indexOf,
  lastIndexOf,
  swap16,
  swap32,
  swap64,
  toBuffer,
  toString,
  write,
  readDoubleBE,
  readDoubleLE,
  readFloatBE,
  readFloatLE,
  readInt32BE,
  readInt32LE,
  readUInt32BE,
  readUInt32LE,
  writeDoubleBE,
  writeDoubleLE,
  writeFloatBE,
  writeFloatLE,
  writeInt32BE,
  writeInt32LE,
  writeUInt32BE,
  writeUInt32LE
}
{
  "name": "b4a",
  "version": "1.8.1",
  "description": "Bridging the gap between buffers and typed arrays",
  "exports": {
    "./package": "./package.json",
    ".": {
      "react-native": "./react-native.js",
      "browser": "./browser.js",
      "default": "./index.js"
    }
  },
  "files": [
    "browser.js",
    "index.js",
    "react-native.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:bare && npm run test:node",
    "test:bare": "brittle-bare --coverage test.mjs",
    "test:node": "brittle-node --coverage test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/b4a.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/b4a/issues"
  },
  "homepage": "https://github.com/holepunchto/b4a#readme",
  "devDependencies": {
    "brittle": "^3.5.2",
    "lunte": "^1.7.0",
    "nanobench": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "react-native-b4a": "*"
  },
  "peerDependenciesMeta": {
    "react-native-b4a": {
      "optional": true
    }
  }
}
const ESC = '\x1b'
const CSI = ESC + '['
const SGR = (n) => CSI + n + 'm'

exports.constants = {
  ESC,
  CSI,
  SGR
}

// https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_(Control_Sequence_Introducer)_sequences

exports.cursorHide = CSI + '?25l'
exports.cursorShow = CSI + '?25h'

exports.cursorUp = function cursorUp(n = 1) {
  return CSI + n + 'A'
}

exports.cursorDown = function cursorDown(n = 1) {
  return CSI + n + 'B'
}

exports.cursorForward = function cursorForward(n = 1) {
  return CSI + n + 'C'
}

exports.cursorBack = function cursorBack(n = 1) {
  return CSI + n + 'D'
}

exports.cursorNextLine = function cursorNextLine(n = 1) {
  return CSI + n + 'E'
}

exports.cursorPreviousLine = function cursorPreviousLine(n = 1) {
  return CSI + n + 'F'
}

exports.cursorPosition = function cursorPosition(column, row = 0) {
  if (row === 0) return CSI + (column + 1) + 'G'

  return CSI + (row + 1) + ';' + (column + 1) + 'H'
}

exports.eraseDisplayEnd = CSI + 'J'
exports.eraseDisplayStart = CSI + '1J'
exports.eraseDisplay = CSI + '2J'
exports.eraseLineEnd = CSI + 'K'
exports.eraseLineStart = CSI + '1K'
exports.eraseLine = CSI + '2K'

exports.scrollUp = function scrollUp(n = 1) {
  return CSI + n + 'S'
}

exports.scrollDown = function scrollDown(n = 1) {
  return CSI + n + 'T'
}

// https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_(Select_Graphic_Rendition)_parameters

exports.modifierReset = SGR(0)
exports.modifierBold = SGR(1)
exports.modifierDim = SGR(2)
exports.modifierItalic = SGR(3)
exports.modifierUnderline = SGR(4)
exports.modifierNormal = SGR(22)
exports.modifierNotItalic = SGR(23)
exports.modifierNotUnderline = SGR(24)

// https://en.wikipedia.org/wiki/ANSI_escape_code#Colors

exports.colorBlack = SGR(30)
exports.colorRed = SGR(31)
exports.colorGreen = SGR(32)
exports.colorYellow = SGR(33)
exports.colorBlue = SGR(34)
exports.colorMagenta = SGR(35)
exports.colorCyan = SGR(36)
exports.colorWhite = SGR(37)
exports.colorDefault = SGR(39)
exports.colorBrightBlack = SGR(90)
exports.colorBrightRed = SGR(91)
exports.colorBrightGreen = SGR(92)
exports.colorBrightYellow = SGR(93)
exports.colorBrightBlue = SGR(94)
exports.colorBrightMagenta = SGR(95)
exports.colorBrightCyan = SGR(96)
exports.colorBrightWhite = SGR(97)
{
  "name": "bare-ansi-escapes",
  "version": "2.2.3",
  "description": "Parse and produce ANSI escape sequences",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./key-decoder": {
      "types": "./key-decoder.d.ts",
      "default": "./key-decoder.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "key-decoder.js",
    "key-decoder.d.ts"
  ],
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-ansi-escapes.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-ansi-escapes/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-ansi-escapes#readme",
  "dependencies": {
    "bare-stream": "^2.6.5"
  },
  "devDependencies": {
    "bare-buffer": "^3.0.2",
    "brittle": "^3.3.2",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  },
  "peerDependencies": {
    "bare-buffer": "*"
  },
  "peerDependenciesMeta": {
    "bare-buffer": {
      "optional": true
    }
  }
}
const inspect = require('bare-inspect')

class AssertionError extends Error {
  constructor(opts = {}) {
    let { message = null, actual, expected, operator } = opts

    if (message === null) {
      message = `${inspect(actual)} ${operator} ${inspect(expected)}`
    }

    super(message)

    this.actual = actual
    this.expected = expected
    this.operator = operator
  }

  get name() {
    return 'AssertionError'
  }

  get code() {
    'ASSERTION'
  }
}

function assertFail(opts, fn) {
  if (opts.message instanceof Error) throw opts.message

  const err = new AssertionError(opts)

  if (Error.captureStackTrace) Error.captureStackTrace(err, fn)

  throw err
}

module.exports = exports = function assert(actual, message) {
  if (actual) return

  assertFail({ message, actual, expected: true, operator: '==' }, assert)
}

exports.AssertionError = AssertionError

exports.fail = function fail(message) {
  if (message === undefined) message = 'Failed'

  assertFail({ message, operator: 'fail' }, fail)
}

exports.ok = function ok(actual, message) {
  if (actual) return

  assertFail({ message, actual, expected: true, operator: '==' }, ok)
}

exports.notOk = function ok(actual, message) {
  if (!actual) return

  assertFail({ message, actual, expected: false, operator: '==' }, ok)
}

exports.equal = function equal(actual, expected, message) {
  if (actual == expected || (actual !== actual && expected !== expected)) {
    return
  }

  assertFail({ message, actual, expected, operator: '==' }, equal)
}

exports.notEqual = function notEqual(actual, expected, message) {
  if (actual != expected && (actual === actual || expected === expected)) {
    return
  }

  assertFail({ message, actual, expected, operator: '!=' }, notEqual)
}

exports.strictEqual = function strictEqual(actual, expected, message) {
  if (Object.is(actual, expected)) return

  assertFail(
    { message, actual, expected, operator: 'strictEqual' },
    strictEqual
  )
}

exports.notStrictEqual = function notStrictEqual(actual, expected, message) {
  if (!Object.is(actual, expected)) return

  assertFail(
    { message, actual, expected, operator: 'notStrictEqual' },
    notStrictEqual
  )
}
{
  "name": "bare-assert",
  "version": "1.2.0",
  "description": "Assertion library for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts"
  ],
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-assert.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-assert/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-assert#readme",
  "dependencies": {
    "bare-inspect": "^3.1.2"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  }
}
const errors = require('./lib/errors')

class EventListener {
  constructor() {
    this.list = []
    this.count = 0
  }

  append(ctx, name, fn, once) {
    this.count++
    ctx.emit('newListener', name, fn) // Emit BEFORE adding
    this.list.push([fn, once])
  }

  prepend(ctx, name, fn, once) {
    this.count++
    ctx.emit('newListener', name, fn) // Emit BEFORE adding
    this.list.unshift([fn, once])
  }

  remove(ctx, name, fn) {
    for (let i = 0, n = this.list.length; i < n; i++) {
      const l = this.list[i]

      if (l[0] === fn) {
        this.list.splice(i, 1)

        if (this.count === 1) delete ctx._events[name]

        ctx.emit('removeListener', name, fn) // Emit AFTER removing

        this.count--
        return
      }
    }
  }

  removeAll(ctx, name) {
    const list = [...this.list]
    this.list = []

    if (this.count === list.length) delete ctx._events[name]

    for (let i = list.length - 1; i >= 0; i--) {
      ctx.emit('removeListener', name, list[i][0]) // Emit AFTER removing
    }

    this.count -= list.length
  }

  emit(ctx, name, ...args) {
    const list = [...this.list]

    for (let i = 0, n = list.length; i < n; i++) {
      const l = list[i]

      if (l[1] === true) this.remove(ctx, name, l[0])

      Reflect.apply(l[0], ctx, args)
    }

    return list.length > 0
  }
}

function appendListener(ctx, name, fn, once) {
  if (ctx._events === undefined) ctx._events = Object.create(null)
  const e = ctx._events[name] || (ctx._events[name] = new EventListener())
  e.append(ctx, name, fn, once)
  return ctx
}

function prependListener(ctx, name, fn, once) {
  if (ctx._events === undefined) ctx._events = Object.create(null)
  const e = ctx._events[name] || (ctx._events[name] = new EventListener())
  e.prepend(ctx, name, fn, once)
  return ctx
}

function removeListener(ctx, name, fn) {
  if (ctx._events === undefined) return ctx
  const e = ctx._events[name]
  if (e !== undefined) e.remove(ctx, name, fn)
  return ctx
}

function throwUnhandledError(...args) {
  let err

  if (args.length > 0) err = args[0]

  if (err instanceof Error === false) err = errors.UNHANDLED_ERROR(err)

  if (Error.captureStackTrace) {
    Error.captureStackTrace(err, exports.prototype.emit)
  }

  queueMicrotask(() => {
    throw err
  })
}

module.exports = exports = class EventEmitter {
  constructor() {
    this._events = Object.create(null)
  }

  addListener(name, fn) {
    return appendListener(this, name, fn, false)
  }

  addOnceListener(name, fn) {
    return appendListener(this, name, fn, true)
  }

  prependListener(name, fn) {
    return prependListener(this, name, fn, false)
  }

  prependOnceListener(name, fn) {
    return prependListener(this, name, fn, true)
  }

  removeListener(name, fn) {
    return removeListener(this, name, fn)
  }

  on(name, fn) {
    return appendListener(this, name, fn, false)
  }

  once(name, fn) {
    return appendListener(this, name, fn, true)
  }

  off(name, fn) {
    return removeListener(this, name, fn)
  }

  emit(name, ...args) {
    if (name === 'error' && this._events !== undefined && this._events.error === undefined) {
      throwUnhandledError(...args)
    }

    if (this._events === undefined) return false
    const e = this._events[name]
    return e === undefined ? false : e.emit(this, name, ...args)
  }

  listeners(name) {
    if (this._events === undefined) return []
    const e = this._events[name]
    return e === undefined ? [] : [...e.list]
  }

  rawListeners(name) {
    if (this._events === undefined) return []
    const e = this._events[name]
    return e === undefined ? [] : e.list.map((l) => l[0])
  }

  eventNames() {
    if (this._events === undefined) return []
    return Reflect.ownKeys(this._events)
  }

  listenerCount(name) {
    if (this._events === undefined) return 0
    const e = this._events[name]
    return e === undefined ? 0 : e.list.length
  }

  getMaxListeners() {
    return EventEmitter.defaultMaxListeners
  }

  setMaxListeners(n) {}

  removeAllListeners(name) {
    if (arguments.length === 0) {
      for (const key of Reflect.ownKeys(this._events)) {
        if (key === 'removeListener') continue
        this.removeAllListeners(key)
      }
      this.removeAllListeners('removeListener')
    } else {
      const e = this._events[name]
      if (e !== undefined) e.removeAll(this, name)
    }
    return this
  }
}

exports.EventEmitter = exports

exports.errors = errors

exports.defaultMaxListeners = 10

exports.on = function on(emitter, name, opts = {}) {
  const { signal } = opts

  if (signal && signal.aborted) {
    throw errors.OPERATION_ABORTED(signal.reason)
  }

  let error = null
  let done = false

  const events = []
  const promises = []

  if (name !== 'error') emitter.on('error', onerror)

  if (signal) signal.addEventListener('abort', onabort)

  emitter.on(name, onevent)

  return {
    next() {
      if (events.length) {
        return Promise.resolve({ value: events.shift(), done: false })
      }

      if (error) {
        const err = error

        error = null

        return Promise.reject(err)
      }

      if (done) return onclose()

      return new Promise((resolve, reject) => promises.push({ resolve, reject }))
    },

    return() {
      return onclose()
    },

    throw(err) {
      return onerror(err)
    },

    [Symbol.asyncIterator]() {
      return this
    }
  }

  function onevent(...args) {
    if (promises.length) {
      promises.shift().resolve({ value: args, done: false })
    } else {
      events.push(args)
    }
  }

  function onerror(err) {
    emitter.off(name, onevent).off('error', onerror)

    if (promises.length) {
      promises.shift().reject(err)
    } else {
      error = err
    }

    return Promise.resolve({ done: true })
  }

  function onabort() {
    signal.removeEventListener('abort', onabort)

    onerror(errors.OPERATION_ABORTED(signal.reason))
  }

  function onclose() {
    emitter.off(name, onevent)

    if (name !== 'error') emitter.off('error', onerror)

    if (signal) signal.removeEventListener('abort', onabort)

    done = true

    if (promises.length) promises.shift().resolve({ done: true })

    return Promise.resolve({ done: true })
  }
}

exports.once = function once(emitter, name, opts = {}) {
  const { signal } = opts

  if (signal && signal.aborted) {
    return Promise.reject(errors.OPERATION_ABORTED(signal.reason))
  }

  return new Promise((resolve, reject) => {
    if (name !== 'error') emitter.on('error', onerror)

    if (signal) signal.addEventListener('abort', onabort)

    emitter.once(name, onevent)

    function onevent(...args) {
      if (name !== 'error') emitter.off('error', onerror)

      if (signal) signal.removeEventListener('abort', onabort)

      resolve(args)
    }

    function onerror(err) {
      emitter.off(name, onevent)

      if (name !== 'error') emitter.off('error', onerror)

      reject(err)
    }

    function onabort() {
      signal.removeEventListener('abort', onabort)

      onerror(errors.OPERATION_ABORTED(signal.reason))
    }
  })
}

exports.forward = function forward(from, to, names, opts = {}) {
  if (typeof names === 'string') names = [names]

  const { emit = to.emit.bind(to) } = opts

  const listeners = names.map(
    (name) =>
      function onevent(...args) {
        emit(name, ...args)
      }
  )

  to.on('newListener', (name) => {
    const i = names.indexOf(name)

    if (i !== -1 && to.listenerCount(name) === 0) {
      from.on(name, listeners[i])
    }
  }).on('removeListener', (name) => {
    const i = names.indexOf(name)

    if (i !== -1 && to.listenerCount(name) === 0) {
      from.off(name, listeners[i])
    }
  })
}

exports.listenerCount = function listenerCount(emitter, name) {
  return emitter.listenerCount(name)
}

exports.getMaxListeners = function getMaxListeners(emitter) {
  if (typeof emitter.getMaxListeners === 'function') {
    return emitter.getMaxListeners()
  }

  return exports.defaultMaxListeners
}

exports.setMaxListeners = function setMaxListeners(n, ...emitters) {
  if (emitters.length === 0) exports.defaultMaxListeners = n
  else {
    for (const emitter of emitters) {
      if (typeof emitter.setMaxListeners === 'function') {
        emitter.setMaxListeners(n)
      }
    }
  }
}
module.exports = class EventEmitterError extends Error {
  constructor(msg, code, fn = EventEmitterError, opts) {
    super(`${code}: ${msg}`, opts)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'EventEmitterError'
  }

  static OPERATION_ABORTED(cause, msg = 'Operation aborted') {
    return new EventEmitterError(msg, 'OPERATION_ABORTED', EventEmitterError.OPERATION_ABORTED, {
      cause
    })
  }

  static UNHANDLED_ERROR(cause, msg = 'Unhandled error') {
    return new EventEmitterError(msg, 'UNHANDLED_ERROR', EventEmitterError.UNHANDLED_ERROR, {
      cause
    })
  }
}
{
  "name": "bare-events",
  "version": "2.9.1",
  "description": "Event emitters for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    },
    "./web": {
      "types": "./web.d.ts",
      "default": "./web.js"
    },
    "./errors": "./lib/errors.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "global.js",
    "global.d.ts",
    "web.js",
    "web.d.ts",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:bare && npm run test:node",
    "test:bare": "brittle-bare --coverage test.js",
    "test:node": "brittle-node --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-events.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-events/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-events#readme",
  "devDependencies": {
    "bare-abort-controller": "^1.0.0",
    "brittle": "^3.3.2",
    "lunte": "^1.8.0",
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^2.0.0",
    "uncaughts": "^1.1.1"
  },
  "peerDependencies": {
    "bare-abort-controller": "*"
  },
  "peerDependenciesMeta": {
    "bare-abort-controller": {
      "optional": true
    }
  }
}
module.exports = require.addon()
const FIFO = require('fast-fifo')
const EventEmitter = require('bare-events')
const path = require('bare-path')
const { isURL, fileURLToPath } = require('bare-url')
const { Readable, Writable } = require('bare-stream')
const binding = require('./binding')
const constants = require('./lib/constants')
const FileError = require('./lib/errors')

const isWindows = Bare.platform === 'win32'

exports.constants = constants

class FileRequest {
  static borrow() {
    if (this._free.length > 0) return this._free.pop()
    return new FileRequest()
  }

  static return(req) {
    if (this._free.length < 32) this._free.push(req.reset())
    else req.destroy()
  }

  constructor() {
    this._reset()
    this._handle = binding.requestInit(this, this._onresult)
  }

  get handle() {
    return this._handle
  }

  retain(value) {
    this._retain = value // Tie the lifetime of `value` to the lifetime of `this`
  }

  reset() {
    if (this._handle === null) return this

    binding.requestReset(this._handle)

    this._reset()

    return this
  }

  destroy() {
    if (this._handle === null) return this

    binding.requestDestroy(this._handle)

    this._reset()
    this._handle = null

    return this
  }

  then(resolve, reject) {
    return this._promise.then(resolve, reject)
  }

  return() {
    if (this._handle === null) return this

    FileRequest.return(this)

    return this
  }

  _reset() {
    this._promise = new Promise((resolve, reject) => {
      this._resolve = resolve
      this._reject = reject
    })
    this._retain = null
  }

  _onresult(err, status) {
    if (err) this._reject(err)
    else this._resolve(status)
  }
}

FileRequest._free = []

function ok(result, cb) {
  if (typeof result === 'function') {
    cb = result
    result = undefined
  }

  if (cb) cb(null, result)
  else return result
}

function fail(err, cb) {
  if (cb) cb(err)
  else throw err
}

function done(err, result, cb) {
  if (typeof result === 'function') {
    cb = result
    result = undefined
  }

  if (err) fail(err, cb)
  else return ok(result, cb)
}

async function open(filepath, flags = 'r', mode = 0o666, cb) {
  if (typeof flags === 'function') {
    cb = flags
    flags = 'r'
    mode = 0o666
  } else if (typeof mode === 'function') {
    cb = mode
    mode = 0o666
  }

  if (typeof flags === 'string') flags = toFlags(flags)
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let fd
  let err = null
  try {
    binding.open(req.handle, filepath, flags, mode)

    fd = await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'open',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, fd, cb)
}

function openSync(filepath, flags = 'r', mode = 0o666) {
  if (typeof flags === 'string') flags = toFlags(flags)
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    return binding.openSync(req.handle, filepath, flags, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'open',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function close(fd, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.close(req.handle, fd)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'close', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function closeSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.closeSync(req.handle, fd)
  } catch (e) {
    throw new FileError(e.message, { operation: 'close', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function access(filepath, mode = constants.F_OK, cb) {
  if (typeof mode === 'function') {
    cb = mode
    mode = constants.F_OK
  }

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.access(req.handle, filepath, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'access',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function accessSync(filepath, mode = constants.F_OK) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.accessSync(req.handle, filepath, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'access',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function exists(filepath, cb) {
  let ok = true
  try {
    await access(filepath)
  } catch {
    ok = false
  }

  return done(null, ok, cb)
}

function existsSync(filepath) {
  try {
    accessSync(filepath)
  } catch {
    return false
  }

  return true
}

async function read(fd, buffer, offset = 0, len = buffer.byteLength - offset, pos = -1, cb) {
  if (typeof offset === 'function') {
    cb = offset
    offset = 0
    len = buffer.byteLength
    pos = -1
  } else if (typeof len === 'function') {
    cb = len
    len = buffer.byteLength - offset
    pos = -1
  } else if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.read(req.handle, fd, buffer, offset, len, pos)

    req.retain(buffer)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'read', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function readSync(fd, buffer, offset = 0, len = buffer.byteLength - offset, pos = -1) {
  const req = FileRequest.borrow()

  try {
    return binding.readSync(req.handle, fd, buffer, offset, len, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'read', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function readv(fd, buffers, pos = -1, cb) {
  if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.readv(req.handle, fd, buffers, pos)

    req.retain(buffers)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'readv', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function readvSync(fd, buffers, pos = -1) {
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  try {
    return binding.readvSync(req.handle, fd, buffers, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'readv', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function write(fd, data, offset, len, pos = -1, cb) {
  if (typeof data === 'string') {
    let encoding = len
    cb = pos
    pos = offset

    if (typeof pos === 'function') {
      cb = pos
      pos = -1
      encoding = 'utf8'
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = 'utf8'
    }

    if (typeof pos === 'string') {
      encoding = pos
      pos = -1
    }

    data = Buffer.from(data, encoding)
    offset = 0
    len = data.byteLength
  } else if (typeof offset === 'function') {
    cb = offset
    offset = 0
    len = data.byteLength
    pos = -1
  } else if (typeof len === 'function') {
    cb = len
    len = data.byteLength - offset
    pos = -1
  } else if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof offset !== 'number') offset = 0
  if (typeof len !== 'number') len = data.byteLength - offset
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.write(req.handle, fd, data, offset, len, pos)

    req.retain(data)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'write', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function writeSync(fd, data, offset, len, pos = -1) {
  if (typeof data === 'string') {
    let encoding = len
    pos = offset

    if (typeof pos === 'string') {
      encoding = pos
      pos = -1
    }

    data = Buffer.from(data, encoding)
    offset = 0
    len = data.byteLength
  }

  if (typeof offset !== 'number') offset = 0
  if (typeof len !== 'number') len = data.byteLength - offset
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  try {
    return binding.writeSync(req.handle, fd, data, offset, len, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'write', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function writev(fd, buffers, pos = -1, cb) {
  if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.writev(req.handle, fd, buffers, pos)

    req.retain(buffers)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'writev', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function writevSync(fd, buffers, pos = -1) {
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  try {
    return binding.writevSync(req.handle, fd, buffers, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'writev', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function stat(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.stat(req.handle, filepath)

    await req

    st = new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'stat', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function statSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.statSync(req.handle, filepath)

    return new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'stat', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function lstat(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.lstat(req.handle, filepath)

    await req

    st = new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'lstat', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function lstatSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.lstatSync(req.handle, filepath)

    return new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'lstat', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function fstat(fd, cb) {
  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.fstat(req.handle, fd)

    await req

    st = new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'fstat', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function fstatSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.fstatSync(req.handle, fd)

    return new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'fstat', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function statfs(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.statfs(req.handle, filepath)

    await req

    st = new StatFs(...binding.requestResultStatfs(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'statfs', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function statfsSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.statfsSync(req.handle, filepath)

    return new StatFs(...binding.requestResultStatfs(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'statfs', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function ftruncate(fd, len = 0, cb) {
  if (typeof len === 'function') {
    cb = len
    len = 0
  }

  if (typeof len !== 'number') len = 0

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.ftruncate(req.handle, fd, len)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'ftruncate', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function ftruncateSync(fd, len = 0) {
  if (typeof len !== 'number') len = 0

  const req = FileRequest.borrow()

  try {
    binding.ftruncateSync(req.handle, fd, len)
  } catch (e) {
    throw new FileError(e.message, { operation: 'ftruncate', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function truncate(filepath, len, cb) {
  let fd = -1
  let err

  try {
    fd = await open(filepath, 'r+')

    await ftruncate(fd, len)
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) await close(fd)
  }

  return done(err, cb)
}

function truncateSync(filepath, len) {
  let fd = -1
  let err

  try {
    fd = openSync(filepath, 'r+')

    ftruncateSync(fd, len)
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) closeSync(fd)
  }
}

async function chmod(filepath, mode, cb) {
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.chmod(req.handle, filepath, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'chmod',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function chmodSync(filepath, mode) {
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.chmodSync(req.handle, filepath, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'chmod',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function fchmod(fd, mode, cb) {
  if (typeof mode === 'string') mode = toMode(mode)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fchmod(req.handle, fd, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fchmod', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fchmodSync(fd, mode) {
  if (typeof mode === 'string') mode = toMode(mode)

  const req = FileRequest.borrow()

  try {
    binding.fchmodSync(req.handle, fd, mode)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fchmod', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function chown(filepath, uid, gid, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.chown(req.handle, filepath, uid, gid)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'chown', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function chownSync(filepath, uid, gid) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.chownSync(req.handle, filepath, uid, gid)
  } catch (e) {
    throw new FileError(e.message, { operation: 'chownSync', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function lchown(filepath, uid, gid, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.lchown(req.handle, filepath, uid, gid)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'lchown', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function lchownSync(filepath, uid, gid) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.lchownSync(req.handle, filepath, uid, gid)
  } catch (e) {
    throw new FileError(e.message, { operation: 'lchownSync', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function fchown(fd, uid, gid, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fchown(req.handle, fd, uid, gid)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fchown', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fchownSync(fd, uid, gid) {
  const req = FileRequest.borrow()

  try {
    binding.fchownSync(req.handle, fd, uid, gid)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fchownSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function utimes(filepath, atime, mtime, cb) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.utimes(req.handle, filepath, atime, mtime)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'utimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function utimesSync(filepath, atime, mtime) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.utimesSync(req.handle, filepath, atime, mtime)
  } catch (e) {
    throw new FileError(e.message, { operation: 'utimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function lutimes(filepath, atime, mtime, cb) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.lutimes(req.handle, filepath, atime, mtime)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'lutimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function lutimesSync(filepath, atime, mtime) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.lutimesSync(req.handle, filepath, atime, mtime)
  } catch (e) {
    throw new FileError(e.message, { operation: 'lutimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function futimes(fd, atime, mtime, cb) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.futimes(req.handle, fd, atime, mtime)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'futimes', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function futimesSync(fd, atime, mtime) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  const req = FileRequest.borrow()

  try {
    binding.futimesSync(req.handle, fd, atime, mtime)
  } catch (e) {
    throw new FileError(e.message, { operation: 'futimesSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function link(src, dst, cb) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.link(req.handle, src, dst)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'link', code: e.code, path: src, destination: dst })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function linkSync(src, dst) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  try {
    binding.linkSync(req.handle, src, dst)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'linkSync',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }
}

async function mkdir(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = { mode: 0o777 }
  }

  if (typeof opts === 'number') opts = { mode: opts }
  else if (!opts) opts = {}

  const mode = typeof opts.mode === 'number' ? opts.mode : 0o777

  filepath = toNamespacedPath(filepath)

  if (opts.recursive) {
    let err = null
    try {
      try {
        await mkdir(filepath, { mode })
      } catch (err) {
        if (err.code !== 'ENOENT') {
          if (!(await stat(filepath)).isDirectory()) throw err
        } else {
          while (filepath.endsWith(path.sep)) filepath = filepath.slice(0, -1)
          const i = filepath.lastIndexOf(path.sep)
          if (i <= 0) throw err

          await mkdir(filepath.slice(0, i), { mode, recursive: true })

          try {
            await mkdir(filepath, { mode })
          } catch (err) {
            if (!(await stat(filepath)).isDirectory()) throw err
          }
        }
      }
    } catch (e) {
      err = e
    }

    return done(err, cb)
  }

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.mkdir(req.handle, filepath, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'mkdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function mkdirSync(filepath, opts) {
  if (typeof opts === 'number') opts = { mode: opts }
  else if (!opts) opts = {}

  const mode = typeof opts.mode === 'number' ? opts.mode : 0o777

  filepath = toNamespacedPath(filepath)

  if (opts.recursive) {
    try {
      mkdirSync(filepath, { mode })
    } catch (err) {
      if (err.code !== 'ENOENT') {
        if (!statSync(filepath).isDirectory()) throw err
      } else {
        while (filepath.endsWith(path.sep)) filepath = filepath.slice(0, -1)
        const i = filepath.lastIndexOf(path.sep)
        if (i <= 0) throw err

        mkdirSync(filepath.slice(0, i), { mode, recursive: true })

        try {
          mkdirSync(filepath, { mode })
        } catch (err) {
          if (!statSync(filepath).isDirectory()) throw err
        }
      }
    }

    return
  }

  const req = FileRequest.borrow()

  try {
    binding.mkdirSync(req.handle, filepath, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'mkdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function mkdtemp(prefix, cb) {
  prefix = toNamespacedPath(prefix)

  const req = FileRequest.borrow()

  let res
  let err = null
  try {
    binding.mkdtemp(req.handle, prefix + 'XXXXXX')

    await req

    res = binding.requestResultPath(req.handle)
  } catch (e) {
    err = new FileError(e.message, { operation: 'mkdtemp', code: e.code, path: prefix })
  } finally {
    req.return()
  }

  return done(err, res, cb)
}

function mkdtempSync(prefix) {
  prefix = toNamespacedPath(prefix)

  const req = FileRequest.borrow()

  try {
    binding.mkdtempSync(req.handle, prefix + 'XXXXXX')

    return binding.requestResultPath(req.handle)
  } catch (e) {
    throw new FileError(e.message, { operation: 'mkdtempSync', code: e.code, path: prefix })
  } finally {
    req.return()
  }
}

async function rmdir(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.rmdir(req.handle, filepath)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'rmdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function rmdirSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.rmdirSync(req.handle, filepath)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'rmdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function rm(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  let err = null
  try {
    const st = await lstat(filepath)

    if (st.isDirectory()) {
      if (opts.recursive) {
        try {
          await rmdir(filepath)
        } catch (err) {
          if (err.code !== 'ENOTEMPTY') throw err

          const files = await readdir(filepath)

          for (const file of files) {
            await rm(filepath + path.sep + file, opts)
          }

          await rmdir(filepath)
        }
      } else {
        throw new FileError('is a directory', {
          operation: 'rm',
          code: 'EISDIR',
          path: filepath
        })
      }
    } else {
      await unlink(filepath)
    }
  } catch (e) {
    if (e.code !== 'ENOENT' || !opts.force) err = e
  }

  return done(err, cb)
}

function rmSync(filepath, opts) {
  if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  try {
    const st = lstatSync(filepath)

    if (st.isDirectory()) {
      if (opts.recursive) {
        try {
          rmdirSync(filepath)
        } catch (err) {
          if (err.code !== 'ENOTEMPTY') throw err

          const files = readdirSync(filepath)

          for (const file of files) {
            rmSync(filepath + path.sep + file, opts)
          }

          rmdirSync(filepath)
        }
      } else {
        throw new FileError('is a directory', {
          operation: 'rm',
          code: 'EISDIR',
          path: filepath
        })
      }
    } else {
      unlinkSync(filepath)
    }
  } catch (err) {
    if (err.code !== 'ENOENT' || !opts.force) throw err
  }
}

async function unlink(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.unlink(req.handle, filepath)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'unlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function unlinkSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.unlinkSync(req.handle, filepath)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'unlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function rename(src, dst, cb) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.rename(req.handle, src, dst)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'rename',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function renameSync(src, dst) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  try {
    binding.renameSync(req.handle, src, dst)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'rename',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }
}

async function copyFile(src, dst, mode = 0, cb) {
  if (typeof mode === 'function') {
    cb = mode
    mode = 0
  }

  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.copyfile(req.handle, src, dst, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'copyfile',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function copyFileSync(src, dst, mode = 0) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  try {
    binding.copyfileSync(req.handle, src, dst, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'copyfile',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }
}

async function cp(src, dst, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (!opts) opts = {}

  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  let err = null
  try {
    const st = await lstat(src)

    if (st.isDirectory()) {
      if (opts.recursive !== true) {
        throw new FileError('is a directory', { operation: 'cp', code: 'EISDIR', path: src })
      }

      try {
        await lstat(dst)
      } catch (e) {
        if (e.code !== 'ENOENT') throw e

        await mkdir(dst, { mode: st.mode, recursive: true })
      }

      const dir = await opendir(src)
      for await (const { name } of dir) {
        await cp(path.join(src, name), path.join(dst, name), opts)
      }
    } else if (st.isFile()) {
      await copyFile(src, dst)
      await chmod(dst, st.mode)
    }
  } catch (e) {
    err = e
  }

  return done(err, cb)
}

function cpSync(src, dst, opts = {}) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const st = lstatSync(src)

  if (st.isDirectory()) {
    if (opts.recursive !== true) {
      throw new FileError('is a directory', { operation: 'cp', code: 'EISDIR', path: src })
    }

    try {
      lstatSync(dst)
    } catch (e) {
      if (e.code !== 'ENOENT') throw e

      mkdirSync(dst, { mode: st.mode, recursive: true })
    }

    const dir = opendirSync(src)
    for (const { name } of dir) {
      cpSync(path.join(src, name), path.join(dst, name), opts)
    }
  } else if (st.isFile()) {
    copyFileSync(src, dst)
    chmodSync(dst, st.mode)
  }
}

async function realpath(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let res
  let err = null
  try {
    binding.realpath(req.handle, filepath)

    await req

    res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'realpath',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, res, cb)
}

function realpathSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.realpathSync(req.handle, filepath)

    let res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)

    return res
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'realpath',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function readlink(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let res
  let err = null
  try {
    binding.readlink(req.handle, filepath)

    await req

    res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'readlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, res, cb)
}

function readlinkSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.readlinkSync(req.handle, filepath)

    let res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)

    return res
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'readlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function fsync(fd, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fsync(req.handle, fd)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fsync', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fsyncSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.fsyncSync(req.handle, fd)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fsyncSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function fdatasync(fd, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fdatasync(req.handle, fd)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fdatasync', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fdatasyncSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.fdatasyncSync(req.handle, fd)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fdatasyncSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

function normalizeSymlinkTarget(target, type, filepath) {
  if (isWindows) {
    if (type === constants.UV_FS_SYMLINK_JUNCTION) target = path.resolve(filepath, '..', target)

    if (path.isAbsolute(target)) return path.toNamespacedPath(target)

    return target.replace(/\//g, path.sep)
  }

  return target
}

async function symlink(target, filepath, type, cb) {
  if (typeof type === 'function') {
    cb = type
    type = null
  }

  filepath = toNamespacedPath(filepath)

  if (typeof type === 'string') {
    switch (type) {
      case 'dir':
        type = constants.UV_FS_SYMLINK_DIR
        break
      case 'junction':
        type = constants.UV_FS_SYMLINK_JUNCTION
        break
      case 'file':
      default:
        type = 0
        break
    }
  } else if (typeof type !== 'number') {
    if (isWindows) {
      target = path.resolve(filepath, '..', target)

      try {
        type = (await stat(target)).isDirectory()
          ? constants.UV_FS_SYMLINK_DIR
          : constants.UV_FS_SYMLINK_JUNCTION
      } catch {
        type = 0
      }
    } else {
      type = 0
    }
  }

  target = normalizeSymlinkTarget(target, type, filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.symlink(req.handle, target, filepath, type)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'symlink',
      code: e.code,
      path: target,
      destination: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function symlinkSync(target, filepath, type) {
  filepath = toNamespacedPath(filepath)

  if (typeof type === 'string') {
    switch (type) {
      case 'dir':
        type = constants.UV_FS_SYMLINK_DIR
        break
      case 'junction':
        type = constants.UV_FS_SYMLINK_JUNCTION
        break
      case 'file':
      default:
        type = 0
        break
    }
  } else if (typeof type !== 'number') {
    if (isWindows) {
      target = path.resolve(filepath, '..', target)

      try {
        type = statSync(target).isDirectory()
          ? constants.UV_FS_SYMLINK_DIR
          : constants.UV_FS_SYMLINK_JUNCTION
      } catch {
        type = 0
      }
    } else {
      type = 0
    }
  }

  target = normalizeSymlinkTarget(target, type, filepath)

  const req = FileRequest.borrow()

  try {
    binding.symlinkSync(req.handle, target, filepath, type)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'symlink',
      code: e.code,
      path: target,
      destination: filepath
    })
  } finally {
    req.return()
  }
}

async function opendir(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let dir
  let err = null
  try {
    binding.opendir(req.handle, filepath)

    await req

    dir = new Dir(filepath, binding.requestResultDir(req.handle), opts)
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'opendir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, dir, cb)
}

function opendirSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.opendirSync(req.handle, filepath)

    return new Dir(filepath, binding.requestResultDir(req.handle), opts)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'opendir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function readdir(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { withFileTypes = false, recursive = false } = opts

  filepath = toNamespacedPath(filepath)

  const queue = [filepath]
  let result = []
  let err = null
  try {
    while (queue.length !== 0) {
      const dir = await opendir(queue.pop())

      for await (const entry of dir) {
        const entryPath = path.join(entry.parentPath, entry.name)

        if (withFileTypes) {
          result.push(entry)
        } else {
          result.push(path.relative(filepath, entryPath))
        }

        if (recursive && entry.isDirectory()) queue.push(entryPath)
      }
    }
  } catch (e) {
    result = []
    err = e
  }

  return done(err, result, cb)
}

function readdirSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { withFileTypes = false, recursive = false } = opts

  filepath = toNamespacedPath(filepath)

  const queue = [filepath]
  const result = []

  while (queue.length !== 0) {
    const dir = opendirSync(queue.pop(), opts)

    for (const entry of dir) {
      const entryPath = path.join(entry.parentPath, entry.name)

      if (withFileTypes) {
        result.push(entry)
      } else {
        result.push(path.relative(filepath, entryPath))
      }

      if (recursive && entry.isDirectory()) queue.push(entryPath)
    }
  }

  return result
}

async function readFile(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'buffer' } = opts

  let fd = -1
  let buffer = null
  let err = null
  try {
    fd = await open(filepath, opts.flag || 'r')

    const st = await fstat(fd)

    let len = 0

    if (st.size === 0) {
      const buffers = []

      while (true) {
        buffer = Buffer.allocUnsafe(8192)
        const r = await read(fd, buffer)
        len += r
        if (r === 0) break
        buffers.push(buffer.subarray(0, r))
      }

      buffer = Buffer.concat(buffers)
    } else {
      buffer = Buffer.allocUnsafe(st.size)

      while (true) {
        const r = await read(fd, len ? buffer.subarray(len) : buffer)
        len += r
        if (r === 0 || len === buffer.byteLength) break
      }

      if (len !== buffer.byteLength) buffer = buffer.subarray(0, len)
    }

    if (encoding !== 'buffer') buffer = buffer.toString(encoding)
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) await close(fd)
  }

  return done(err, buffer, cb)
}

function readFileSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'buffer' } = opts

  let fd = -1
  try {
    fd = openSync(filepath, opts.flag || 'r')

    const st = fstatSync(fd)

    let buffer
    let len = 0

    if (st.size === 0) {
      const buffers = []

      while (true) {
        buffer = Buffer.allocUnsafe(8192)
        const r = readSync(fd, buffer)
        len += r
        if (r === 0) break
        buffers.push(buffer.subarray(0, r))
      }

      buffer = Buffer.concat(buffers)
    } else {
      buffer = Buffer.allocUnsafe(st.size)

      while (true) {
        const r = readSync(fd, len ? buffer.subarray(len) : buffer)
        len += r
        if (r === 0 || len === buffer.byteLength) break
      }

      if (len !== buffer.byteLength) buffer = buffer.subarray(0, len)
    }

    if (encoding !== 'buffer') buffer = buffer.toString(encoding)

    return buffer
  } finally {
    if (fd !== -1) closeSync(fd)
  }
}

async function writeFile(filepath, data, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (typeof data === 'string') data = Buffer.from(data, opts.encoding)

  let fd = -1
  let len = 0
  let err = null
  try {
    fd = await open(filepath, opts.flag || 'w', opts.mode || 0o666)

    while (true) {
      len += await write(fd, len ? data.subarray(len) : data)
      if (len === data.byteLength) break
    }
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) await close(fd)
  }

  return done(err, len, cb)
}

function writeFileSync(filepath, data, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (typeof data === 'string') data = Buffer.from(data, opts.encoding)

  let fd = -1
  try {
    fd = openSync(filepath, opts.flag || 'w', opts.mode || 0o666)

    let len = 0

    while (true) {
      len += writeSync(fd, len ? data.subarray(len) : data)
      if (len === data.byteLength) break
    }
  } finally {
    if (fd !== -1) closeSync(fd)
  }
}

function appendFile(filepath, data, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (!opts.flag) opts = { ...opts, flag: 'a' }

  return writeFile(filepath, data, opts, cb)
}

function appendFileSync(filepath, data, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (!opts.flag) opts = { ...opts, flag: 'a' }

  return writeFileSync(filepath, data, opts)
}

function watch(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  return new Watcher(filepath, opts, cb)
}

class Stats {
  constructor(
    dev,
    mode,
    nlink,
    uid,
    gid,
    rdev,
    blksize,
    ino,
    size,
    blocks,
    atimeMs,
    mtimeMs,
    ctimeMs,
    birthtimeMs
  ) {
    this.dev = dev
    this.mode = mode
    this.nlink = nlink
    this.uid = uid
    this.gid = gid
    this.rdev = rdev
    this.blksize = blksize
    this.ino = ino
    this.size = size
    this.blocks = blocks
    this.atimeMs = atimeMs
    this.mtimeMs = mtimeMs
    this.ctimeMs = ctimeMs
    this.birthtimeMs = birthtimeMs
    this.atime = new Date(atimeMs)
    this.mtime = new Date(mtimeMs)
    this.ctime = new Date(ctimeMs)
    this.birthtime = new Date(birthtimeMs)
  }

  isDirectory() {
    return (this.mode & constants.S_IFMT) === constants.S_IFDIR
  }

  isFile() {
    return (this.mode & constants.S_IFMT) === constants.S_IFREG
  }

  isBlockDevice() {
    return (this.mode & constants.S_IFMT) === constants.S_IFBLK
  }

  isCharacterDevice() {
    return (this.mode & constants.S_IFMT) === constants.S_IFCHR
  }

  isFIFO() {
    return (this.mode & constants.S_IFMT) === constants.S_IFIFO
  }

  isSymbolicLink() {
    return (this.mode & constants.S_IFMT) === constants.S_IFLNK
  }

  isSocket() {
    return (this.mode & constants.S_IFMT) === constants.S_IFSOCK
  }
}

class StatFs {
  constructor(type, bsize, blocks, bfree, bavail, files, ffree) {
    this.type = type
    this.bsize = bsize
    this.blocks = blocks
    this.bfree = bfree
    this.bavail = bavail
    this.files = files
    this.ffree = ffree
  }
}

class Dir {
  constructor(path, handle, opts = {}) {
    const { encoding = 'utf8', bufferSize = 32 } = opts

    this.path = path

    this._encoding = encoding
    this._capacity = bufferSize
    this._buffer = new FIFO()
    this._ended = false
    this._handle = handle
  }

  async read(cb) {
    if (this._buffer.length) return ok(this._buffer.shift(), cb)
    if (this._ended) return ok(null, cb)

    const req = FileRequest.borrow()

    let entries
    let err = null
    try {
      req.retain(binding.readdir(req.handle, this._handle, this._capacity))

      await req

      entries = binding.requestResultDirents(req.handle)
    } catch (e) {
      err = new FileError(e.message, {
        operation: 'readdir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    if (err) return fail(err, cb)

    if (entries.length === 0) {
      this._ended = true

      return ok(null, cb)
    }

    for (const entry of entries) {
      let name = Buffer.from(entry.name)

      if (this._encoding !== 'buffer') name = name.toString(this._encoding)

      this._buffer.push(new Dirent(this.path, name, entry.type))
    }

    return ok(this._buffer.shift(), cb)
  }

  readSync() {
    if (this._buffer.length) return this._buffer.shift()
    if (this._ended) return null

    const req = FileRequest.borrow()

    let entries
    try {
      req.retain(binding.readdirSync(req.handle, this._handle, this._capacity))

      entries = binding.requestResultDirents(req.handle)
    } catch (e) {
      throw new FileError(e.message, {
        operation: 'readdir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    if (entries.length === 0) {
      this._ended = true

      return null
    }

    for (const entry of entries) {
      let name = Buffer.from(entry.name)

      if (this._encoding !== 'buffer') name = name.toString(this._encoding)

      this._buffer.push(new Dirent(this.path, name, entry.type))
    }

    return this._buffer.shift()
  }

  async close(cb) {
    const req = FileRequest.borrow()

    let err = null
    try {
      binding.closedir(req.handle, this._handle)

      await req
    } catch (e) {
      err = new FileError(e.message, {
        operation: 'closedir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    this._handle = null

    return done(err, cb)
  }

  closeSync() {
    const req = FileRequest.borrow()

    try {
      binding.closedirSync(req.handle, this._handle)
    } catch (e) {
      throw new FileError(e.message, {
        operation: 'closedir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    this._handle = null
  }

  [Symbol.dispose]() {
    this.closeSync()
  }

  async [Symbol.asyncDispose]() {
    await this.close()
  }

  *[Symbol.iterator]() {
    while (true) {
      const entry = this.readSync()
      if (entry === null) break
      yield entry
    }

    this.closeSync()
  }

  async *[Symbol.asyncIterator]() {
    while (true) {
      const entry = await this.read()
      if (entry === null) break
      yield entry
    }

    await this.close()
  }
}

class Dirent {
  constructor(parentPath, name, type) {
    this.parentPath = parentPath
    this.name = name
    this.type = type
  }

  isFile() {
    return this.type === constants.UV_DIRENT_FILE
  }

  isDirectory() {
    return this.type === constants.UV_DIRENT_DIR
  }

  isSymbolicLink() {
    return this.type === constants.UV_DIRENT_LINK
  }

  isFIFO() {
    return this.type === constants.UV_DIRENT_FIFO
  }

  isSocket() {
    return this.type === constants.UV_DIRENT_SOCKET
  }

  isCharacterDevice() {
    return this.type === constants.UV_DIRENT_CHAR
  }

  isBlockDevice() {
    return this.type === constants.UV_DIRENT_BLOCK
  }
}

class FileReadStream extends Readable {
  constructor(path, opts = {}) {
    const { eagerOpen = true } = opts

    super({ eagerOpen, ...opts })

    this.path = path
    this.fd = typeof opts.fd === 'number' ? opts.fd : -1
    this.flags = opts.flags || 'r'
    this.mode = opts.mode || 0o666

    this._offset = opts.start || 0
    this._missing = 0

    if (opts.length) {
      this._missing = opts.length
    } else if (typeof opts.end === 'number') {
      this._missing = opts.end - this._offset + 1
    } else {
      this._missing = -1
    }
  }

  async _open(cb) {
    let err

    if (this.fd === -1) {
      err = null
      try {
        this.fd = await open(this.path, this.flags, this.mode)
      } catch (e) {
        err = e
      }

      if (err) return cb(err)
    }

    let st
    err = null
    try {
      st = await fstat(this.fd)
    } catch (e) {
      err = e
    }

    if (err) return cb(err)

    if (this._missing === -1) this._missing = st.size

    if (st.size < this._offset) {
      this._offset = st.size
      this._missing = 0
    } else if (st.size < this._offset + this._missing) {
      this._missing = st.size - this._offset
    }

    cb(null)
  }

  async _read(size) {
    if (this._missing <= 0) return this.push(null)

    const data = Buffer.allocUnsafe(Math.min(this._missing, size))

    let len
    let err = null
    try {
      len = await read(this.fd, data, 0, data.byteLength, this._offset)
    } catch (e) {
      err = e
    }

    if (err) return this.destroy(err)

    if (len === 0) return this.push(null)

    if (this._missing < len) len = this._missing

    this._missing -= len
    this._offset += len

    this.push(data.subarray(0, len))
  }

  async _destroy(err, cb) {
    if (this.fd === -1) return cb(err)

    try {
      await close(this.fd)
    } catch (e) {
      err = err || e
    }

    cb(err)
  }
}

class FileWriteStream extends Writable {
  constructor(path, opts = {}) {
    const { eagerOpen = true } = opts

    super({ eagerOpen, ...opts })

    this.path = path
    this.fd = typeof opts.fd === 'number' ? opts.fd : -1
    this.flags = opts.flags || 'w'
    this.mode = opts.mode || 0o666
  }

  async _open(cb) {
    if (this.fd !== -1) return cb(null)

    let err = null
    try {
      this.fd = await open(this.path, this.flags, this.mode)
    } catch (e) {
      err = e
    }

    cb(err)
  }

  async _writev(batch, cb) {
    let err = null
    try {
      await writev(
        this.fd,
        batch.map(({ chunk }) => chunk)
      )
    } catch (e) {
      err = e
    }

    cb(err)
  }

  async _destroy(err, cb) {
    if (this.fd === -1) return cb(err)

    try {
      await close(this.fd)
    } catch (e) {
      err = err || e
    }

    cb(err)
  }
}

class Watcher extends EventEmitter {
  constructor(path, opts, onchange) {
    if (typeof opts === 'function') {
      onchange = opts
      opts = {}
    }

    if (!opts) opts = {}

    const { persistent = true, recursive = false, encoding = 'utf8' } = opts

    super()

    this._closed = false
    this._encoding = encoding
    this._handle = binding.watcherInit(path, recursive, this, this._onevent, this._onclose)

    if (!persistent) this.unref()

    if (onchange) this.on('change', onchange)
  }

  close() {
    if (this._closed) return
    this._closed = true

    binding.watcherClose(this._handle)
  }

  ref() {
    if (this._handle) binding.watcherRef(this._handle)
    return this
  }

  unref() {
    if (this._handle) binding.watcherUnref(this._handle)
    return this
  }

  [Symbol.asyncIterator]() {
    const buffer = []
    let done = false
    let error = null
    let next = null

    this.on('change', (eventType, filename) => {
      if (next) {
        next.resolve({ done: false, value: { eventType, filename } })
        next = null
      } else {
        buffer.push({ eventType, filename })
      }
    })
      .on('error', (err) => {
        done = true
        error = err

        if (next) {
          next.reject(error)
          next = null
        }
      })
      .on('close', () => {
        done = true

        if (next) {
          next.resolve({ done })
          next = null
        }
      })

    return {
      next: () =>
        new Promise((resolve, reject) => {
          if (error) return reject(error)

          if (buffer.length) return resolve({ done: false, value: buffer.shift() })

          if (done) return resolve({ done })

          next = { resolve, reject }
        })
    }
  }

  _onevent(err, events, filename) {
    if (err) {
      this.close()
      this.emit('error', err)
    } else {
      const path =
        this._encoding === 'buffer'
          ? Buffer.from(filename)
          : Buffer.from(filename).toString(this._encoding)

      if (events & binding.UV_RENAME) {
        this.emit('change', 'rename', path)
      }

      if (events & binding.UV_CHANGE) {
        this.emit('change', 'change', path)
      }
    }
  }

  _onclose() {
    this._handle = null

    this.emit('close')
  }
}

exports.access = access
exports.appendFile = appendFile
exports.chmod = chmod
exports.chown = chown
exports.close = close
exports.copyFile = copyFile
exports.cp = cp
exports.exists = exists
exports.fchmod = fchmod
exports.fchown = fchown
exports.fdatasync = fdatasync
exports.fstat = fstat
exports.fsync = fsync
exports.ftruncate = ftruncate
exports.futimes = futimes
exports.lchown = lchown
exports.lutimes = lutimes
exports.link = link
exports.lstat = lstat
exports.mkdir = mkdir
exports.mkdtemp = mkdtemp
exports.open = open
exports.opendir = opendir
exports.read = read
exports.readFile = readFile
exports.readdir = readdir
exports.readlink = readlink
exports.readv = readv
exports.realpath = realpath
exports.rename = rename
exports.rm = rm
exports.rmdir = rmdir
exports.stat = stat
exports.statfs = statfs
exports.symlink = symlink
exports.truncate = truncate
exports.unlink = unlink
exports.utimes = utimes
exports.watch = watch
exports.write = write
exports.writeFile = writeFile
exports.writev = writev

exports.accessSync = accessSync
exports.appendFileSync = appendFileSync
exports.chmodSync = chmodSync
exports.chownSync = chownSync
exports.closeSync = closeSync
exports.copyFileSync = copyFileSync
exports.cpSync = cpSync
exports.existsSync = existsSync
exports.fchmodSync = fchmodSync
exports.fchownSync = fchownSync
exports.fdatasyncSync = fdatasyncSync
exports.fstatSync = fstatSync
exports.fsyncSync = fsyncSync
exports.ftruncateSync = ftruncateSync
exports.futimesSync = futimesSync
exports.lchownSync = lchownSync
exports.lutimesSync = lutimesSync
exports.linkSync = linkSync
exports.lstatSync = lstatSync
exports.mkdirSync = mkdirSync
exports.mkdtempSync = mkdtempSync
exports.openSync = openSync
exports.opendirSync = opendirSync
exports.readFileSync = readFileSync
exports.readSync = readSync
exports.readdirSync = readdirSync
exports.readlinkSync = readlinkSync
exports.readvSync = readvSync
exports.realpathSync = realpathSync
exports.renameSync = renameSync
exports.rmSync = rmSync
exports.rmdirSync = rmdirSync
exports.statSync = statSync
exports.statfsSync = statfsSync
exports.symlinkSync = symlinkSync
exports.truncateSync = truncateSync
exports.unlinkSync = unlinkSync
exports.utimesSync = utimesSync
exports.writeFileSync = writeFileSync
exports.writeSync = writeSync
exports.writevSync = writevSync

exports.promises = require('./promises')

exports.Stats = Stats
exports.StatFs = StatFs
exports.Dir = Dir
exports.Dirent = Dirent
exports.Watcher = Watcher

exports.ReadStream = FileReadStream

exports.createReadStream = function createReadStream(path, opts) {
  return new FileReadStream(path, opts)
}

exports.WriteStream = FileWriteStream

exports.createWriteStream = function createWriteStream(path, opts) {
  return new FileWriteStream(path, opts)
}

function toNamespacedPath(filepath) {
  if (typeof filepath !== 'string') {
    if (isURL(filepath)) filepath = fileURLToPath(filepath)
    else filepath = filepath.toString()
  }

  return path.toNamespacedPath(filepath)
}

function toFlags(flags) {
  switch (flags) {
    case 'r':
      return constants.O_RDONLY
    case 'rs': // Fall through.
    case 'sr':
      return constants.O_RDONLY | constants.O_SYNC
    case 'r+':
      return constants.O_RDWR
    case 'rs+': // Fall through.
    case 'sr+':
      return constants.O_RDWR | constants.O_SYNC

    case 'w':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_WRONLY
    case 'wx': // Fall through.
    case 'xw':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_WRONLY | constants.O_EXCL

    case 'w+':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_RDWR
    case 'wx+': // Fall through.
    case 'xw+':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_RDWR | constants.O_EXCL

    case 'a':
      return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY
    case 'ax': // Fall through.
    case 'xa':
      return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY | constants.O_EXCL
    case 'as': // Fall through.
    case 'sa':
      return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY | constants.O_SYNC

    case 'a+':
      return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR
    case 'ax+': // Fall through.
    case 'xa+':
      return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR | constants.O_EXCL
    case 'as+': // Fall through.
    case 'sa+':
      return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR | constants.O_SYNC
    default:
      return 0
  }
}

function toMode(mode) {
  return parseInt(mode, 8)
}
const binding = require('../binding')

module.exports = {
  O_RDWR: binding.O_RDWR,
  O_RDONLY: binding.O_RDONLY,
  O_WRONLY: binding.O_WRONLY,
  O_CREAT: binding.O_CREAT,
  O_TRUNC: binding.O_TRUNC,
  O_APPEND: binding.O_APPEND,

  F_OK: binding.F_OK || 0,
  R_OK: binding.R_OK || 0,
  W_OK: binding.W_OK || 0,
  X_OK: binding.X_OK || 0,

  S_IFMT: binding.S_IFMT,
  S_IFREG: binding.S_IFREG,
  S_IFDIR: binding.S_IFDIR,
  S_IFCHR: binding.S_IFCHR,
  S_IFLNK: binding.S_IFLNK,
  S_IFBLK: binding.S_IFBLK || 0,
  S_IFIFO: binding.S_IFIFO || 0,
  S_IFSOCK: binding.S_IFSOCK || 0,

  S_IRUSR: binding.S_IRUSR || 0,
  S_IWUSR: binding.S_IWUSR || 0,
  S_IXUSR: binding.S_IXUSR || 0,
  S_IRGRP: binding.S_IRGRP || 0,
  S_IWGRP: binding.S_IWGRP || 0,
  S_IXGRP: binding.S_IXGRP || 0,
  S_IROTH: binding.S_IROTH || 0,
  S_IWOTH: binding.S_IWOTH || 0,
  S_IXOTH: binding.S_IXOTH || 0,

  UV_DIRENT_UNKNOWN: binding.UV_DIRENT_UNKNOWN,
  UV_DIRENT_FILE: binding.UV_DIRENT_FILE,
  UV_DIRENT_DIR: binding.UV_DIRENT_DIR,
  UV_DIRENT_LINK: binding.UV_DIRENT_LINK,
  UV_DIRENT_FIFO: binding.UV_DIRENT_FIFO,
  UV_DIRENT_SOCKET: binding.UV_DIRENT_SOCKET,
  UV_DIRENT_CHAR: binding.UV_DIRENT_CHAR,
  UV_DIRENT_BLOCK: binding.UV_DIRENT_BLOCK,

  COPYFILE_EXCL: binding.UV_FS_COPYFILE_EXCL,
  COPYFILE_FICLONE: binding.UV_FS_COPYFILE_FICLONE,
  COPYFILE_FICLONE_FORCE: binding.UV_FS_COPYFILE_FICLONE_FORCE,
  UV_FS_SYMLINK_DIR: binding.UV_FS_SYMLINK_DIR,
  UV_FS_SYMLINK_JUNCTION: binding.UV_FS_SYMLINK_JUNCTION
}
const os = require('bare-os')

module.exports = class FileError extends Error {
  constructor(msg, opts = {}) {
    const { code, operation = null, path = null, destination = null, fd = -1 } = opts

    if (operation !== null) msg += describe(operation, opts)

    super(`${code}: ${msg}`)

    this.code = code

    if (operation !== null) this.operation = operation
    if (path !== null) this.path = path
    if (destination !== null) this.destination = destination
    if (fd !== -1) this.fd = fd
  }

  get name() {
    return 'FileError'
  }

  // For Node.js compatibility
  get errno() {
    return os.constants.errnos[this.code]
  }

  // For Node.js compatibility
  get syscall() {
    return this.operation
  }

  // For Node.js compatibility
  get dest() {
    return this.destination
  }
}

function describe(operation, opts) {
  const { path = null, destination = null, fd = -1 } = opts

  let result = `, ${operation}`

  if (path !== null) {
    result += ` ${JSON.stringify(path)}`

    if (destination !== null) {
      result += ` -> ${JSON.stringify(destination)}`
    }
  } else if (fd !== -1) {
    result += ` ${fd}`
  }

  return result
}
{
  "name": "bare-fs",
  "version": "4.7.2",
  "description": "Native file system operations for Bare",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./promises": {
      "types": "./promises.d.ts",
      "default": "./promises.js"
    },
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "promises.js",
    "promises.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-fs.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-fs/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-fs#readme",
  "engines": {
    "bare": ">=1.16.0"
  },
  "dependencies": {
    "bare-events": "^2.5.4",
    "bare-path": "^3.0.0",
    "bare-stream": "^2.6.4",
    "bare-url": "^2.2.2",
    "fast-fifo": "^1.3.2"
  },
  "devDependencies": {
    "bare-buffer": "^3.0.2",
    "bare-crypto": "^1.11.2",
    "brittle": "^3.1.1",
    "cmake-bare": "^1.1.7",
    "lunte": "^1.6.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "bare-buffer": "*"
  },
  "peerDependenciesMeta": {
    "bare-buffer": {
      "optional": true
    }
  }
}
const EventEmitter = require('bare-events')
const fs = require('.')

class FileHandle extends EventEmitter {
  constructor(fd) {
    super()

    this.fd = fd
  }

  async close() {
    await fs.close(this.fd)

    this.fd = -1
    this.emit('close')
  }

  async read(buffer, ...args) {
    return {
      bytesRead: await fs.read(this.fd, buffer, ...args),
      buffer
    }
  }

  async readv(buffers, ...args) {
    return {
      bytesRead: await fs.readv(this.fd, buffers, ...args),
      buffers
    }
  }

  async write(buffer, ...args) {
    return {
      bytesWritten: await fs.write(this.fd, buffer, ...args),
      buffer
    }
  }

  async writev(buffers, ...args) {
    return {
      bytesWritten: await fs.writev(this.fd, buffers, ...args),
      buffers
    }
  }

  async stat() {
    return fs.fstat(this.fd)
  }

  async chmod(mode) {
    await fs.fchmod(this.fd, mode)
  }

  async chown(uid, gid) {
    await fs.fchown(this.fd, uid, gid)
  }

  async datasync() {
    return fs.fdatasync(this.fd)
  }

  async sync() {
    return fs.fsync(this.fd)
  }

  async truncate(len) {
    await fs.ftruncate(this.fd, len)
  }

  async utimes(atime, mtime) {
    await fs.futimes(this.fd, atime, mtime)
  }

  createReadStream(opts) {
    return fs.createReadStream(null, { ...opts, fd: this.fd })
  }

  createWriteStream(opts) {
    return fs.createWriteStream(null, { ...opts, fd: this.fd })
  }

  async [Symbol.asyncDispose]() {
    await this.close()
  }
}

exports.open = async function open(filepath, flags, mode) {
  return new FileHandle(await fs.open(filepath, flags, mode))
}

exports.access = fs.access
exports.appendFile = fs.appendFile
exports.chmod = fs.chmod
exports.chown = fs.chown
exports.constants = fs.constants
exports.copyFile = fs.copyFile
exports.cp = fs.cp
exports.lchown = fs.lchown
exports.lutimes = fs.lutimes
exports.link = fs.link
exports.lstat = fs.lstat
exports.mkdir = fs.mkdir
exports.mkdtemp = fs.mkdtemp
exports.opendir = fs.opendir
exports.readFile = fs.readFile
exports.readdir = fs.readdir
exports.readlink = fs.readlink
exports.realpath = fs.realpath
exports.rename = fs.rename
exports.rm = fs.rm
exports.rmdir = fs.rmdir
exports.stat = fs.stat
exports.statfs = fs.statfs
exports.truncate = fs.truncate
exports.symlink = fs.symlink
exports.unlink = fs.unlink
exports.utimes = fs.utimes
exports.watch = fs.watch
exports.writeFile = fs.writeFile
module.exports = require.addon()
const ansiEscapes = require('bare-ansi-escapes')
const getType = require('bare-type')
const binding = require('./binding')

const PLAIN_KEY = /^[a-zA-Z_][a-zA-Z_0-9]*$/

const defaultDepth = 2
const defaultBreakLength = 80
const defaultMaxArrayLength = 40

module.exports = exports = function inspect(value, opts = {}) {
  const {
    colors = false,
    depth = defaultDepth,
    breakLength = defaultBreakLength,
    stylize = defaultStylize(colors)
  } = opts

  const references = new InspectRefMap()

  const tree = inspectValue(value, 0, {
    colors,
    depth,
    breakLength,
    stylize,
    references
  })

  return tree.toString()
}

exports.styles = {
  bigint: ansiEscapes.colorYellow,
  boolean: ansiEscapes.colorYellow,
  date: ansiEscapes.colorMagenta,
  module: ansiEscapes.modifierUnderline,
  name: ansiEscapes.modifierReset,
  null: ansiEscapes.modifierBold,
  number: ansiEscapes.colorYellow,
  regexp: ansiEscapes.colorRed,
  special: ansiEscapes.colorCyan,
  string: ansiEscapes.colorGreen,
  symbol: ansiEscapes.colorGreen,
  undefined: ansiEscapes.colorBrightBlack
}

const styles = exports.styles

function defaultStylize(colors) {
  return function stylize(value, style) {
    const color = colors && styles[style]

    if (color) return color + value + ansiEscapes.modifierReset

    return value
  }
}

class InspectRefMap {
  constructor() {
    this.refs = new WeakMap()
    this.ids = new WeakMap()
    this.nextId = 1
  }

  has(object) {
    return this.refs.has(object)
  }

  get(object) {
    return this.refs.get(object) || null
  }

  set(object, ref) {
    this.refs.set(object, ref)
  }

  id(object) {
    let id = this.ids.get(object)
    if (id) return id

    id = this.nextId++
    this.ids.set(object, id)

    return id
  }
}

class InspectNode {
  constructor(depth, length, opts) {
    const { breakLength = defaultBreakLength, breakAlways = false } = opts

    this.depth = depth
    this.length = length
    this.breakLength = breakLength
    this.breakAlways = breakAlways
  }

  pad(n, string) {
    return string.padStart(n, ' ')
  }

  indent(n, string) {
    return '  '.repeat(n) + string
  }
}

class InspectRef extends InspectNode {
  constructor(depth, opts) {
    super(depth, '[circular *]'.length, opts)

    this.refs = opts.references
    this.count = 0
    this.circular = false
    this.color = opts.colors && styles.special
  }

  get id() {
    return this.refs.id(this)
  }

  increment() {
    return ++this.count
  }

  decrement() {
    return --this.count
  }

  toString(opts = {}) {
    const { offset = 0, pad = 0, indent = 0 } = opts

    let value = this.pad(pad, '[circular *' + this.id + ']')

    if (this.color) value = this.color + value + ansiEscapes.modifierReset

    return offset ? value : this.indent(indent, value)
  }
}

class InspectLeaf extends InspectNode {
  constructor(value, color, depth, opts) {
    const length = value.length

    if (value.includes('\n')) {
      value = value.replaceAll('\n', '\n' + '  '.repeat(depth))

      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.value = value
    this.color = opts.colors && color
  }

  toString(opts = {}) {
    const { offset = 0, pad = 0, indent = 0 } = opts

    let value = this.pad(pad, this.value)

    if (this.color) value = this.color + value + ansiEscapes.modifierReset

    return offset ? value : this.indent(indent, value)
  }
}

class InspectPair extends InspectNode {
  constructor(delim, left, right, depth, opts) {
    const length = left.length + delim.length + right.length

    if (left.breakAlways || right.breakAlways) {
      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.delim = delim
    this.left = left
    this.right = right
  }

  toString(opts = {}) {
    const { indent = 0 } = opts

    return this.indent(
      indent,
      this.left +
        this.delim +
        this.right.toString({
          indent,
          offset: this.left.length + this.delim.length
        })
    )
  }
}

class InspectSuspension extends InspectNode {
  constructor(overflow, depth, opts) {
    const label = `... ${overflow} more`

    super(depth, label.length, opts)

    this.label = label
  }

  toString(opts = {}) {
    const { indent = 0 } = opts

    return this.indent(indent, this.label)
  }
}

class InspectSequence extends InspectNode {
  constructor(header, footer, delim, values, ref, depth, opts) {
    const { tabulate = false } = opts

    const length =
      (ref.circular ? '<ref *>'.length + 1 : 0) +
      header.length +
      values.reduce(
        (length, value, i) =>
          length + value.length + (i === 0 ? 0 : delim.length),
        0
      ) +
      footer.length

    if (values.some((value) => value.breakAlways)) {
      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.header = header
    this.footer = footer
    this.delim = delim
    this.values = values
    this.ref = ref
    this.tabulate = tabulate
  }

  toString(opts = {}) {
    const { offset = 0, indent = 0 } = opts

    const split =
      this.breakAlways ||
      (this.values.length &&
        (offset + this.length > this.breakLength ||
          indent * 2 + this.length > this.breakLength))

    let header = this.header

    if (this.ref.circular) {
      header = '<ref *' + this.ref.id + '> ' + header
    }

    if (this.values.length === 0) {
      header = header.trimEnd()
    }

    if (offset === 0) {
      header = this.indent(indent, header)
    }

    if (split) {
      header = header.trimEnd() + '\n'
    }

    let string = header

    let columns = 1
    let pad = 0

    if (this.tabulate) {
      const widest = this.values.reduce(
        (length, value) =>
          value.breakAlways ? length : Math.max(length, value.length),
        0
      )

      if (widest) {
        columns = Math.max(
          columns,
          Math.floor(
            (this.breakLength - indent * 2) / (widest + this.delim.length)
          )
        )

        if (columns > 1) pad = widest
      }
    }

    for (let i = 0, n = this.values.length, offset = 0; i < n; i++) {
      const value = this.values[i]

      if (split) {
        let part

        if (i % columns === 0 || value.breakAlways) {
          part = value.toString({ indent: indent + 1, pad })
        } else {
          part = value.toString({ pad })
        }

        string += part

        if (i < n - 1) {
          if (i % columns === columns - 1 || this.values[i + 1].breakAlways) {
            string += this.delim.trimEnd() + '\n'
          } else {
            string += this.delim
          }
        }
      } else {
        if (i > 0) string += this.delim

        string += value.toString({ offset })

        offset += value.length
      }
    }

    let footer = this.footer

    if (this.values.length === 0) {
      footer = footer.trimStart()
    }

    if (split) {
      string += '\n' + this.indent(indent, footer.trimStart())
    } else {
      string += footer
    }

    return string
  }
}

function inspectValue(value, depth, opts) {
  const type = getType(value)

  if (type.isUndefined()) return inspectUndefined(depth, opts)
  if (type.isNull()) return inspectNull(depth, opts)
  if (type.isBoolean()) return inspectBoolean(value, depth, opts)
  if (type.isNumber()) return inspectNumber(value, depth, opts)
  if (type.isBigInt()) return inspectBigInt(value, depth, opts)
  if (type.isString()) return inspectString(value, depth, opts)
  if (type.isSymbol()) return inspectSymbol(value, depth, opts)
  if (type.isObject()) return inspectObject(type, value, depth, opts)
  if (type.isFunction()) return inspectFunction(type, value, depth, opts)
  if (type.isExternal()) return inspectExternal(value, opts, opts)
}

function inspectUndefined(depth, opts) {
  return new InspectLeaf('undefined', styles.undefined, depth, opts)
}

function inspectNull(depth, opts) {
  return new InspectLeaf('null', styles.null, depth, opts)
}

function inspectBoolean(value, depth, opts) {
  return new InspectLeaf(value.toString(), styles.boolean, depth, opts)
}

function inspectNumber(value, depth, opts) {
  let string

  if (Object.is(value, -0)) {
    string = '-0'
  } else {
    string = value.toString(10)
  }

  return new InspectLeaf(string, styles.number, depth, opts)
}

function inspectBigInt(value, depth, opts) {
  return new InspectLeaf(value.toString(10) + 'n', styles.bigint, depth, opts)
}

const STRING_ESCAPES =
  /[\ud800-\udbff][\udc00-\udfff]|[\u0000-\u001f'\\\ud800-\udfff]/g

function inspectString(value, depth, opts) {
  // https://tc39.es/ecma262/multipage/structured-data.html#sec-quotejsonstring
  const string = value.replace(STRING_ESCAPES, (match) => {
    if (match.length === 2) return match

    switch (match) {
      case "'":
        return "\\'"
      case '\\':
        return '\\\\'
      case '\b':
        return '\\b'
      case '\t':
        return '\\t'
      case '\n':
        return '\\n'
      case '\f':
        return '\\f'
      case '\r':
        return '\\r'
      default:
        return '\\u' + match.charCodeAt(0).toString(16).padStart(4, '0')
    }
  })

  return new InspectLeaf("'" + string + "'", styles.string, depth, opts)
}

function inspectSymbol(value, depth, opts) {
  return new InspectLeaf(value.toString(), styles.symbol, depth, opts)
}

function inspectKey(value, depth, opts) {
  if (PLAIN_KEY.test(value)) {
    return new InspectLeaf(value, null, depth, opts)
  } else {
    return inspectValue(value, depth, opts)
  }
}

function inspectObject(type, object, depth, opts) {
  const refs = opts.references

  let ref = refs.get(object)
  if (ref === null) {
    ref = new InspectRef(depth, opts)
    refs.set(object, ref)
  } else if (ref.count) {
    ref.circular = true
    return ref
  }

  const maxDepth = typeof opts.depth === 'number' ? opts.depth : Infinity

  if (maxDepth < depth) {
    const constructor = object.constructor

    return new InspectLeaf(
      '[' +
        (constructor && constructor.name ? constructor.name : 'Object') +
        ']',
      styles.special,
      depth,
      opts
    )
  }

  const inspect =
    object[Symbol.for('bare.inspect')] ||
    object[Symbol.for('nodejs.util.inspect.custom')]

  if (typeof inspect === 'function') {
    const value = inspect.call(
      object,
      typeof opts.depth === 'number' ? opts.depth - depth : null,
      {
        colors: opts.colors,
        breakLength: opts.breakLength,
        stylize: opts.stylize
      },
      exports
    )

    if (typeof value === 'object' && value !== null) {
      refs.set(value, ref)
    }

    if (typeof value !== 'string') {
      return inspectValue(value, depth, opts)
    }

    return new InspectLeaf(value, null, depth, opts)
  }

  if (type.isArray()) return inspectArray(object, ref, depth, opts)
  if (type.isDate()) return inspectDate(object, ref, depth, opts)
  if (type.isRegExp()) return inspectRegExp(object, ref, depth, opts)
  if (type.isError()) return inspectError(object, ref, depth, opts)
  if (type.isPromise()) return inspectPromise(object, ref, depth, opts)
  if (type.isMap()) return inspectMap(object, ref, depth, opts)
  if (type.isSet()) return inspectSet(object, ref, depth, opts)
  if (type.isWeakMap()) return inspectWeakMap(object, ref, depth, opts)
  if (type.isWeakSet()) return inspectWeakSet(object, ref, depth, opts)
  if (type.isWeakRef()) return inspectWeakRef(object, ref, depth, opts)
  if (type.isArrayBuffer()) return inspectArrayBuffer(object, ref, depth, opts)
  if (type.isSharedArrayBuffer())
    return inspectSharedArrayBuffer(object, ref, depth, opts)
  if (type.isTypedArray()) return inspectTypedArray(object, ref, depth, opts)
  if (type.isDataView()) return inspectDataView(object, ref, depth, opts)

  ref.increment()

  const values = []

  for (const key in object) {
    if (key === 'constructor') continue

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(object[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  let header = '{ '

  const tag = object[Symbol.toStringTag]

  if (tag) header = '[' + tag + '] ' + header

  if (object.constructor) {
    const name = object.constructor.name

    if (name && name !== 'Object') {
      header = object.constructor.name + ' ' + header
    }
  }

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectArray(array, ref, depth, opts) {
  const { maxArrayLength = defaultMaxArrayLength } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxArrayLength, 0)

  for (let i = 0, n = array.length; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(array.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(inspectValue(array[i], depth + 1, opts))
  }

  for (const key of binding.getOwnNonIndexPropertyNames(array)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(array[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  let header = '[ '

  if (array.constructor.name !== 'Array') {
    header = array.constructor.name + '(' + array.length + ') ' + header
  }

  return new InspectSequence(header, ' ]', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectDate(date, ref, depth, opts) {
  return new InspectLeaf(date.toISOString(), styles.date, depth, opts)
}

function inspectRegExp(regExp, ref, depth, opts) {
  return new InspectLeaf(regExp.toString(), styles.regexp, depth, opts)
}

function inspectError(error, ref, depth, opts) {
  let header

  if ('stack' in error) {
    header = error.stack

    if (depth > 0) {
      header = header.replaceAll('\n', '\n' + '  '.repeat(depth))
    }
  } else {
    header = error.toString()
  }

  const builtins = ['cause']

  if (error.name === 'AggregateError') {
    builtins.push('errors')
  } else if (error.name === 'SuppressedError') {
    builtins.push('error', 'suppressed')
  }

  const values = []

  for (const key of builtins) {
    if (key in error === false) continue

    values.push(
      new InspectPair(
        ': ',
        new InspectLeaf('[' + key + ']', null, depth + 1, opts),
        inspectValue(error[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key in error) {
    if (key === 'constructor' || builtins.includes(key)) continue

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(error[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  if (values.length === 0) return new InspectLeaf(header, null, depth, opts)

  return new InspectSequence(
    header + ' {',
    ' }',
    ', ',
    values,
    ref,
    depth,
    opts
  )
}

function inspectPromise(promise, ref, depth, opts) {
  ref.increment()

  const state = binding.getPromiseState(promise)

  const values = []

  switch (state) {
    case 0: // Pending
      values.push(new InspectLeaf('<pending>', styles.special, depth, opts))
      break

    case 1: // Fulfilled
      values.push(inspectValue(binding.getPromiseResult(promise), depth, opts))
      break

    case 2: // Rejected
      values.push(
        new InspectLeaf('<rejected>', styles.special, depth, opts),
        inspectValue(binding.getPromiseResult(promise), depth, opts)
      )
  }

  ref.decrement()

  const header = promise.constructor.name + ' { '

  return new InspectSequence(header, ' }', ' ', values, ref, depth, opts)
}

function inspectMap(map, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxMapLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = maxMapLength

  for (const entry of map) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(map.size - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )
      break
    }

    values.push(
      new InspectPair(
        ' => ',
        inspectValue(entry[0], depth + 1, opts),
        inspectValue(entry[1], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key in map) {
    if (key === 'constructor') continue

    const value = inspectValue(map[key], depth + 1, opts)

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        value,
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = map.constructor.name + '(' + map.size + ') { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectSet(set, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxSetLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = maxSetLength

  for (const entry of set) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(set.size - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )
      break
    }

    values.push(inspectValue(entry, depth + 1, opts))
  }

  for (const key in set) {
    if (key === 'constructor') continue

    const value = inspectValue(set[key], depth + 1, opts)

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        value,
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = set.constructor.name + '(' + set.size + ') { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectWeakMap(weakMap, ref, depth, opts) {
  const header = weakMap.constructor.name + ' { '

  return new InspectSequence(
    header,
    ' }',
    ' ',
    [new InspectLeaf('<items unknown>', styles.special, depth + 1, opts)],
    ref,
    depth,
    opts
  )
}

function inspectWeakSet(weakSet, ref, depth, opts) {
  const header = weakSet.constructor.name + ' { '

  return new InspectSequence(
    header,
    ' }',
    ' ',
    [new InspectLeaf('<items unknown>', styles.special, depth + 1, opts)],
    ref,
    depth,
    opts
  )
}

function inspectWeakRef(weakRef, ref, depth, opts) {
  const target = weakRef.deref()

  let value

  if (target === undefined) {
    value = new InspectLeaf('<cleared>', styles.special, depth + 1, opts)
  } else {
    value = inspectValue(target, depth + 1, opts)
  }

  const header = weakRef.constructor.name + ' { '

  return new InspectSequence(header, ' }', ' ', [value], ref, depth, opts)
}

function inspectArrayBuffer(arrayBuffer, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(arrayBuffer[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = arrayBuffer.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectSharedArrayBuffer(sharedArrayBuffer, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(sharedArrayBuffer[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = sharedArrayBuffer.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectTypedArray(typedArray, ref, depth, opts) {
  if (Buffer.isBuffer(typedArray)) {
    return inspectBuffer(typedArray, ref, depth, opts)
  }

  const {
    maxArrayLength = defaultMaxArrayLength,
    maxTypedArrayLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxTypedArrayLength, 0)

  for (let i = 0, n = typedArray.length; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(typedArray.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(inspectValue(typedArray[i], depth + 1, opts))
  }

  for (const key of binding.getOwnNonIndexPropertyNames(typedArray)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(typedArray[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = typedArray.constructor.name + '(' + typedArray.length + ') [ '

  return new InspectSequence(header, ' ]', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectBuffer(buffer, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxBufferLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxBufferLength, 0)

  for (let i = 0, n = buffer.byteLength; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(buffer.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(
      new InspectLeaf(
        buffer[i].toString(16).padStart(2, '0'),
        null,
        depth + 1,
        opts
      )
    )
  }

  for (const key of binding.getOwnNonIndexPropertyNames(buffer)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(buffer[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  return new InspectSequence('<Buffer ', '>', ' ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectDataView(dataView, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength', 'byteOffset', 'buffer']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(dataView[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key of binding.getOwnNonIndexPropertyNames(dataView)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(dataView[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = dataView.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectFunction(type, fn, depth, opts) {
  if (fn.toString().startsWith('class')) return inspectClass(fn, depth, opts)

  let tag = 'function'

  if (type.isGeneratorFunction()) tag = 'generator ' + tag
  if (type.isAsyncFunction()) tag = 'async ' + tag

  return new InspectLeaf(
    '[' + tag + ' ' + (fn.name ? fn.name : '(anonymous)') + ']',
    styles.special,
    depth,
    opts
  )
}

function inspectClass(ctor, depth, opts) {
  return new InspectLeaf(
    '[class ' + (ctor.name ? ctor.name : '(anonymous)') + ']',
    styles.special,
    depth,
    opts
  )
}

function inspectExternal(external, depth, opts) {
  return new InspectLeaf(
    '[external 0x' + binding.getExternal(external).toString(16) + ']',
    styles.special,
    depth,
    opts
  )
}
{
  "name": "bare-inspect",
  "version": "3.1.4",
  "description": "Inspect objects as strings for debugging",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-inspect.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-inspect/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-inspect#readme",
  "engines": {
    "bare": ">=1.18.0"
  },
  "dependencies": {
    "bare-ansi-escapes": "^2.1.0",
    "bare-type": "^1.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
module.exports = require.addon()
const binding = require('./binding')
const errors = require('./lib/errors')
const constants = require('./lib/constants')

exports.constants = constants
exports.errors = errors

exports.EOL = binding.platform === 'win32' ? '\r\n' : '\n'

exports.devNull = binding.platform === 'win32' ? '\\\\.\\nul' : '/dev/null'

exports.platform = function platform() {
  return binding.platform
}

exports.arch = function arch() {
  return binding.arch
}

exports.type = binding.type
exports.version = binding.version
exports.release = binding.release
exports.machine = binding.machine
exports.execPath = binding.execPath
exports.pid = binding.pid
exports.ppid = binding.ppid
exports.cwd = binding.cwd
exports.chdir = binding.chdir
exports.tmpdir = binding.tmpdir
exports.homedir = binding.homedir
exports.hostname = binding.hostname
exports.userInfo = binding.userInfo
exports.groupInfo = binding.groupInfo

exports.networkInterfaces = function networkInterfaces() {
  const result = {}

  for (const entry of binding.networkInterfaces()) {
    const { name, ...properties } = entry

    if (result[name]) result[name].push(properties)
    else result[name] = [properties]
  }

  return result
}

exports.kill = function kill(pid, signal = constants.signals.SIGTERM) {
  if (typeof signal === 'string') {
    if (signal in constants.signals === false) {
      throw errors.UNKNOWN_SIGNAL('Unknown signal: ' + signal)
    }

    signal = constants.signals[signal]
  }

  binding.kill(pid, signal)
}

exports.endianness = function endianness() {
  return binding.isLittleEndian ? 'LE' : 'BE'
}

exports.availableParallelism = binding.availableParallelism

exports.cpuUsage = function cpuUsage(previous) {
  const current = binding.cpuUsage()

  if (previous) {
    return {
      user: current.user - previous.user,
      system: current.system - previous.system
    }
  }

  return current
}

exports.threadCpuUsage = function threadCpuUsage(previous) {
  const current = binding.threadCpuUsage()

  if (previous) {
    return {
      user: current.user - previous.user,
      system: current.system - previous.system
    }
  }

  return current
}

exports.resourceUsage = binding.resourceUsage
exports.memoryUsage = binding.memoryUsage
exports.freemem = binding.freemem
exports.totalmem = binding.totalmem
exports.availableMemory = binding.availableMemory
exports.constrainedMemory = binding.constrainedMemory
exports.uptime = binding.uptime
exports.loadavg = binding.loadavg
exports.cpus = binding.cpus

exports.getProcessTitle = binding.getProcessTitle

exports.setProcessTitle = function setProcessTitle(title) {
  if (typeof title !== 'string') title = title.toString()

  if (title.length >= 256) {
    throw errors.TITLE_OVERFLOW('Process title is too long')
  }

  binding.setProcessTitle(title)
}

exports.getPriority = function getPriority(pid = 0) {
  return binding.getPriority(pid)
}

exports.setPriority = function setPriority(pid, priority) {
  if (priority === undefined) {
    priority = pid
    pid = 0
  }

  binding.setPriority(pid, priority)
}

exports.getEnvKeys = binding.getEnvKeys
exports.getEnv = binding.getEnv
exports.hasEnv = binding.hasEnv
exports.setEnv = binding.setEnv
exports.unsetEnv = binding.unsetEnv
const binding = require('../binding')

module.exports = {
  signals: binding.signals,
  errnos: binding.errnos,
  priority: binding.priority
}
module.exports = class OSError extends Error {
  constructor(msg, fn = OSError, code = fn.name) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'OSError'
  }

  static UNKNOWN_SIGNAL(msg) {
    return new OSError(msg, OSError.UNKNOWN_SIGNAL)
  }

  static TITLE_OVERFLOW(msg) {
    return new OSError(msg, OSError.TITLE_OVERFLOW)
  }
}
{
  "name": "bare-os",
  "version": "3.9.1",
  "description": "Operating system utilities for Bare",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    },
    "./errors": {
      "types": "./lib/errors.d.ts",
      "default": "./lib/errors.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-os.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-os/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-os#readme",
  "engines": {
    "bare": ">=1.14.0"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "cmake-bare": "^1.1.6",
    "lunte": "^1.6.0",
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
// This export SHOULD NOT be shortened in any way as having the full
// `module.exports = require(...)` statement is crucial for synthesizing
// ESM exports.

if (Bare.platform === 'win32') {
  module.exports = require('./lib/win32')
} else {
  module.exports = require('./lib/posix')
}
module.exports = {
  CHAR_UPPERCASE_A: 0x41,
  CHAR_LOWERCASE_A: 0x61,
  CHAR_UPPERCASE_Z: 0x5a,
  CHAR_LOWERCASE_Z: 0x7a,
  CHAR_DOT: 0x2e,
  CHAR_FORWARD_SLASH: 0x2f,
  CHAR_BACKWARD_SLASH: 0x5c,
  CHAR_COLON: 0x3a,
  CHAR_QUESTION_MARK: 0x3f
}
const os = require('bare-os')

const { normalizeString } = require('./shared')
const { CHAR_DOT, CHAR_FORWARD_SLASH } = require('./constants')

function isPosixPathSeparator(code) {
  return code === CHAR_FORWARD_SLASH
}

exports.win32 = require('./win32')
exports.posix = exports

exports.sep = '/'
exports.delimiter = ':'

exports.resolve = function resolve(...args) {
  let resolvedPath = ''
  let resolvedAbsolute = false

  for (let i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) {
    const path = i >= 0 ? args[i] : os.cwd()

    if (path.length === 0) {
      continue
    }

    resolvedPath = `${path}/${resolvedPath}`
    resolvedAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH
  }

  resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute, '/', isPosixPathSeparator)

  if (resolvedAbsolute) {
    return `/${resolvedPath}`
  }

  return resolvedPath.length > 0 ? resolvedPath : '.'
}

exports.normalize = function normalize(path) {
  if (path.length === 0) return '.'

  const isAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH
  const trailingSeparator = path.charCodeAt(path.length - 1) === CHAR_FORWARD_SLASH

  path = normalizeString(path, !isAbsolute, '/', isPosixPathSeparator)

  if (path.length === 0) {
    if (isAbsolute) return '/'
    return trailingSeparator ? './' : '.'
  }

  if (trailingSeparator) path += '/'

  return isAbsolute ? `/${path}` : path
}

exports.isAbsolute = function isAbsolute(path) {
  return path.length > 0 && path.charCodeAt(0) === CHAR_FORWARD_SLASH
}

exports.join = function join(...args) {
  if (args.length === 0) return '.'
  let joined
  for (let i = 0; i < args.length; ++i) {
    const arg = args[i]
    if (arg.length > 0) {
      if (joined === undefined) joined = arg
      else joined += `/${arg}`
    }
  }
  if (joined === undefined) return '.'
  return exports.normalize(joined)
}

exports.relative = function relative(from, to) {
  if (from === to) return ''

  from = exports.resolve(from)
  to = exports.resolve(to)

  if (from === to) return ''

  const fromStart = 1
  const fromEnd = from.length
  const fromLen = fromEnd - fromStart
  const toStart = 1
  const toLen = to.length - toStart

  const length = fromLen < toLen ? fromLen : toLen
  let lastCommonSep = -1
  let i = 0
  for (; i < length; i++) {
    const fromCode = from.charCodeAt(fromStart + i)
    if (fromCode !== to.charCodeAt(toStart + i)) {
      break
    } else if (fromCode === CHAR_FORWARD_SLASH) {
      lastCommonSep = i
    }
  }
  if (i === length) {
    if (toLen > length) {
      if (to.charCodeAt(toStart + i) === CHAR_FORWARD_SLASH) {
        return to.substring(toStart + i + 1)
      }
      if (i === 0) {
        return to.substring(toStart + i)
      }
    } else if (fromLen > length) {
      if (from.charCodeAt(fromStart + i) === CHAR_FORWARD_SLASH) {
        lastCommonSep = i
      } else if (i === 0) {
        lastCommonSep = 0
      }
    }
  }

  let out = ''
  for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
    if (i === fromEnd || from.charCodeAt(i) === CHAR_FORWARD_SLASH) {
      out += out.length === 0 ? '..' : '/..'
    }
  }

  return `${out}${to.substring(toStart + lastCommonSep)}`
}

exports.toNamespacedPath = function toNamespacedPath(path) {
  return path
}

exports.dirname = function dirname(path) {
  if (path.length === 0) return '.'
  const hasRoot = path.charCodeAt(0) === CHAR_FORWARD_SLASH
  let end = -1
  let matchedSlash = true
  for (let i = path.length - 1; i >= 1; --i) {
    if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) {
      if (!matchedSlash) {
        end = i
        break
      }
    } else {
      matchedSlash = false
    }
  }

  if (end === -1) return hasRoot ? '/' : '.'
  if (hasRoot && end === 1) return '//'
  return path.substring(0, end)
}

exports.basename = function basename(path, suffix) {
  let start = 0
  let end = -1
  let matchedSlash = true

  if (suffix !== undefined && suffix.length > 0 && suffix.length <= path.length) {
    if (suffix === path) {
      return ''
    }
    let extIdx = suffix.length - 1
    let firstNonSlashEnd = -1
    for (let i = path.length - 1; i >= 0; --i) {
      const code = path.charCodeAt(i)
      if (code === CHAR_FORWARD_SLASH) {
        if (!matchedSlash) {
          start = i + 1
          break
        }
      } else {
        if (firstNonSlashEnd === -1) {
          matchedSlash = false
          firstNonSlashEnd = i + 1
        }
        if (extIdx >= 0) {
          if (code === suffix.charCodeAt(extIdx)) {
            if (--extIdx === -1) {
              end = i
            }
          } else {
            extIdx = -1
            end = firstNonSlashEnd
          }
        }
      }
    }

    if (start === end) end = firstNonSlashEnd
    else if (end === -1) end = path.length
    return path.substring(start, end)
  }

  for (let i = path.length - 1; i >= 0; --i) {
    if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) {
      if (!matchedSlash) {
        start = i + 1
        break
      }
    } else if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
  }

  if (end === -1) return ''
  return path.substring(start, end)
}

exports.extname = function extname(path) {
  let startDot = -1
  let startPart = 0
  let end = -1
  let matchedSlash = true
  let preDotState = 0
  for (let i = path.length - 1; i >= 0; --i) {
    const code = path.charCodeAt(i)
    if (code === CHAR_FORWARD_SLASH) {
      if (!matchedSlash) {
        startPart = i + 1
        break
      }
      continue
    }
    if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
    if (code === CHAR_DOT) {
      if (startDot === -1) startDot = i
      else if (preDotState !== 1) preDotState = 1
    } else if (startDot !== -1) {
      preDotState = -1
    }
  }

  if (
    startDot === -1 ||
    end === -1 ||
    preDotState === 0 ||
    (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1)
  ) {
    return ''
  }
  return path.substring(startDot, end)
}
const { CHAR_DOT, CHAR_FORWARD_SLASH } = require('./constants')

exports.normalizeString = function normalizeString(
  path,
  allowAboveRoot,
  separator,
  isPathSeparator
) {
  let res = ''
  let lastSegmentLength = 0
  let lastSlash = -1
  let dots = 0
  let code = 0
  for (let i = 0; i <= path.length; ++i) {
    if (i < path.length) {
      code = path.charCodeAt(i)
    } else if (isPathSeparator(code)) {
      break
    } else {
      code = CHAR_FORWARD_SLASH
    }

    if (isPathSeparator(code)) {
      if (lastSlash === i - 1 || dots === 1);
      else if (dots === 2) {
        if (
          res.length < 2 ||
          lastSegmentLength !== 2 ||
          res.charCodeAt(res.length - 1) !== CHAR_DOT ||
          res.charCodeAt(res.length - 2) !== CHAR_DOT
        ) {
          if (res.length > 2) {
            const lastSlashIndex = res.lastIndexOf(separator)
            if (lastSlashIndex === -1) {
              res = ''
              lastSegmentLength = 0
            } else {
              res = res.substring(0, lastSlashIndex)
              lastSegmentLength = res.length - 1 - res.lastIndexOf(separator)
            }
            lastSlash = i
            dots = 0
            continue
          } else if (res.length !== 0) {
            res = ''
            lastSegmentLength = 0
            lastSlash = i
            dots = 0
            continue
          }
        }
        if (allowAboveRoot) {
          res += res.length > 0 ? `${separator}..` : '..'
          lastSegmentLength = 2
        }
      } else {
        if (res.length > 0) {
          res += `${separator}${path.substring(lastSlash + 1, i)}`
        } else {
          res = path.substring(lastSlash + 1, i)
        }
        lastSegmentLength = i - lastSlash - 1
      }
      lastSlash = i
      dots = 0
    } else if (code === CHAR_DOT && dots !== -1) {
      ++dots
    } else {
      dots = -1
    }
  }
  return res
}
const os = require('bare-os')

const { normalizeString } = require('./shared')
const {
  CHAR_UPPERCASE_A,
  CHAR_LOWERCASE_A,
  CHAR_UPPERCASE_Z,
  CHAR_LOWERCASE_Z,
  CHAR_DOT,
  CHAR_FORWARD_SLASH,
  CHAR_BACKWARD_SLASH,
  CHAR_COLON,
  CHAR_QUESTION_MARK
} = require('./constants')

function isWindowsPathSeparator(code) {
  return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH
}

function isWindowsDeviceRoot(code) {
  return (
    (code >= CHAR_UPPERCASE_A && code <= CHAR_UPPERCASE_Z) ||
    (code >= CHAR_LOWERCASE_A && code <= CHAR_LOWERCASE_Z)
  )
}

exports.posix = require('./posix')
exports.win32 = exports

exports.sep = '\\'
exports.delimiter = ';'

exports.resolve = function resolve(...args) {
  let resolvedDevice = ''
  let resolvedTail = ''
  let resolvedAbsolute = false

  for (let i = args.length - 1; i >= -1; i--) {
    let path
    if (i >= 0) {
      path = args[i]

      if (path.length === 0) continue
    } else if (resolvedDevice.length === 0) {
      path = os.cwd()
    } else {
      path = os.getEnv(`=${resolvedDevice}`) || os.cwd()

      if (
        path === undefined ||
        (path.substring(0, 2).toLowerCase() !== resolvedDevice.toLowerCase() &&
          path.charCodeAt(2) === CHAR_BACKWARD_SLASH)
      ) {
        path = `${resolvedDevice}\\`
      }
    }

    const len = path.length
    let rootEnd = 0
    let device = ''
    let isAbsolute = false
    const code = path.charCodeAt(0)

    if (len === 1) {
      if (isWindowsPathSeparator(code)) {
        rootEnd = 1
        isAbsolute = true
      }
    } else if (isWindowsPathSeparator(code)) {
      isAbsolute = true

      if (isWindowsPathSeparator(path.charCodeAt(1))) {
        let j = 2
        let last = j
        while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
          j++
        }
        if (j < len && j !== last) {
          const firstPart = path.substring(last, j)
          last = j
          while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
            j++
          }
          if (j < len && j !== last) {
            last = j
            while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
              j++
            }
            if (j === len || j !== last) {
              device = `\\\\${firstPart}\\${path.substring(last, j)}`
              rootEnd = j
            }
          }
        }
      } else {
        rootEnd = 1
      }
    } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
      device = path.substring(0, 2)
      rootEnd = 2
      if (len > 2 && isWindowsPathSeparator(path.charCodeAt(2))) {
        isAbsolute = true
        rootEnd = 3
      }
    }

    if (device.length > 0) {
      if (resolvedDevice.length > 0) {
        if (device.toLowerCase() !== resolvedDevice.toLowerCase()) {
          continue
        }
      } else {
        resolvedDevice = device
      }
    }

    if (resolvedAbsolute) {
      if (resolvedDevice.length > 0) {
        break
      }
    } else {
      resolvedTail = `${path.substring(rootEnd)}\\${resolvedTail}`
      resolvedAbsolute = isAbsolute
      if (isAbsolute && resolvedDevice.length > 0) {
        break
      }
    }
  }

  resolvedTail = normalizeString(resolvedTail, !resolvedAbsolute, '\\', isWindowsPathSeparator)

  return resolvedAbsolute
    ? `${resolvedDevice}\\${resolvedTail}`
    : `${resolvedDevice}${resolvedTail}` || '.'
}

exports.normalize = function normalize(path) {
  const len = path.length
  if (len === 0) return '.'
  let rootEnd = 0
  let device
  let isAbsolute = false
  const code = path.charCodeAt(0)

  if (len === 1) {
    return code === CHAR_FORWARD_SLASH ? '\\' : path
  }

  if (isWindowsPathSeparator(code)) {
    isAbsolute = true

    if (isWindowsPathSeparator(path.charCodeAt(1))) {
      let j = 2
      let last = j
      while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
        j++
      }
      if (j < len && j !== last) {
        const firstPart = path.substring(last, j)
        last = j
        while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
          j++
        }
        if (j < len && j !== last) {
          last = j
          while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
            j++
          }
          if (j === len) {
            return `\\\\${firstPart}\\${path.substring(last)}\\`
          }
          if (j !== last) {
            device = `\\\\${firstPart}\\${path.substring(last, j)}`
            rootEnd = j
          }
        }
      }
    } else {
      rootEnd = 1
    }
  } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
    device = path.substring(0, 2)
    rootEnd = 2
    if (len > 2 && isWindowsPathSeparator(path.charCodeAt(2))) {
      isAbsolute = true
      rootEnd = 3
    }
  }

  let tail =
    rootEnd < len
      ? normalizeString(path.substring(rootEnd), !isAbsolute, '\\', isWindowsPathSeparator)
      : ''
  if (tail.length === 0 && !isAbsolute) {
    tail = '.'
  }
  if (tail.length > 0 && isWindowsPathSeparator(path.charCodeAt(len - 1))) {
    tail += '\\'
  }
  if (device === undefined) {
    return isAbsolute ? `\\${tail}` : tail
  }
  return isAbsolute ? `${device}\\${tail}` : `${device}${tail}`
}

exports.isAbsolute = function isAbsolute(path) {
  const len = path.length
  if (len === 0) return false

  const code = path.charCodeAt(0)

  return (
    isWindowsPathSeparator(code) ||
    (len > 2 &&
      isWindowsDeviceRoot(code) &&
      path.charCodeAt(1) === CHAR_COLON &&
      isWindowsPathSeparator(path.charCodeAt(2)))
  )
}

exports.join = function join(...args) {
  if (args.length === 0) return '.'

  let joined
  let firstPart
  for (let i = 0; i < args.length; ++i) {
    const arg = args[i]
    if (arg.length > 0) {
      if (joined === undefined) joined = firstPart = arg
      else joined += `\\${arg}`
    }
  }

  if (joined === undefined) return '.'

  let needsReplace = true
  let slashCount = 0
  if (isWindowsPathSeparator(firstPart.charCodeAt(0))) {
    ++slashCount
    const firstLen = firstPart.length
    if (firstLen > 1 && isWindowsPathSeparator(firstPart.charCodeAt(1))) {
      ++slashCount
      if (firstLen > 2) {
        if (isWindowsPathSeparator(firstPart.charCodeAt(2))) {
          ++slashCount
        } else {
          needsReplace = false
        }
      }
    }
  }
  if (needsReplace) {
    while (slashCount < joined.length && isWindowsPathSeparator(joined.charCodeAt(slashCount))) {
      slashCount++
    }

    if (slashCount >= 2) {
      joined = `\\${joined.substring(slashCount)}`
    }
  }

  return exports.normalize(joined)
}

exports.relative = function relative(from, to) {
  if (from === to) return ''

  const fromOrig = exports.resolve(from)
  const toOrig = exports.resolve(to)

  if (fromOrig === toOrig) return ''

  from = fromOrig.toLowerCase()
  to = toOrig.toLowerCase()

  if (from === to) return ''

  let fromStart = 0
  while (fromStart < from.length && from.charCodeAt(fromStart) === CHAR_BACKWARD_SLASH) {
    fromStart++
  }
  let fromEnd = from.length
  while (fromEnd - 1 > fromStart && from.charCodeAt(fromEnd - 1) === CHAR_BACKWARD_SLASH) {
    fromEnd--
  }
  const fromLen = fromEnd - fromStart

  let toStart = 0
  while (toStart < to.length && to.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) {
    toStart++
  }
  let toEnd = to.length
  while (toEnd - 1 > toStart && to.charCodeAt(toEnd - 1) === CHAR_BACKWARD_SLASH) {
    toEnd--
  }
  const toLen = toEnd - toStart

  const length = fromLen < toLen ? fromLen : toLen
  let lastCommonSep = -1
  let i = 0
  for (; i < length; i++) {
    const fromCode = from.charCodeAt(fromStart + i)
    if (fromCode !== to.charCodeAt(toStart + i)) {
      break
    } else if (fromCode === CHAR_BACKWARD_SLASH) {
      lastCommonSep = i
    }
  }

  if (i !== length) {
    if (lastCommonSep === -1) return toOrig
  } else {
    if (toLen > length) {
      if (to.charCodeAt(toStart + i) === CHAR_BACKWARD_SLASH) {
        return toOrig.substring(toStart + i + 1)
      }
      if (i === 2) {
        return toOrig.substring(toStart + i)
      }
    }
    if (fromLen > length) {
      if (from.charCodeAt(fromStart + i) === CHAR_BACKWARD_SLASH) {
        lastCommonSep = i
      } else if (i === 2) {
        lastCommonSep = 3
      }
    }
    if (lastCommonSep === -1) lastCommonSep = 0
  }

  let out = ''
  for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
    if (i === fromEnd || from.charCodeAt(i) === CHAR_BACKWARD_SLASH) {
      out += out.length === 0 ? '..' : '\\..'
    }
  }

  toStart += lastCommonSep

  if (out.length > 0) {
    return `${out}${toOrig.substring(toStart, toEnd)}`
  }
  if (toOrig.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) {
    ++toStart
  }
  return toOrig.substring(toStart, toEnd)
}

exports.toNamespacedPath = function toNamespacedPath(path) {
  if (path.length === 0) return path

  const resolvedPath = exports.resolve(path)

  if (resolvedPath.length <= 2) return path

  if (resolvedPath.charCodeAt(0) === CHAR_BACKWARD_SLASH) {
    if (resolvedPath.charCodeAt(1) === CHAR_BACKWARD_SLASH) {
      const code = resolvedPath.charCodeAt(2)
      if (code !== CHAR_QUESTION_MARK && code !== CHAR_DOT) {
        return `\\\\?\\UNC\\${resolvedPath.substring(2)}`
      }
    }
  } else if (
    isWindowsDeviceRoot(resolvedPath.charCodeAt(0)) &&
    resolvedPath.charCodeAt(1) === CHAR_COLON &&
    resolvedPath.charCodeAt(2) === CHAR_BACKWARD_SLASH
  ) {
    return `\\\\?\\${resolvedPath}`
  }

  return path
}

exports.dirname = function dirname(path) {
  const len = path.length
  if (len === 0) return '.'
  let rootEnd = -1
  let offset = 0
  const code = path.charCodeAt(0)

  if (len === 1) {
    return isWindowsPathSeparator(code) ? path : '.'
  }

  if (isWindowsPathSeparator(code)) {
    rootEnd = offset = 1

    if (isWindowsPathSeparator(path.charCodeAt(1))) {
      let j = 2
      let last = j
      while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
        j++
      }
      if (j < len && j !== last) {
        last = j
        while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
          j++
        }
        if (j < len && j !== last) {
          last = j
          while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
            j++
          }
          if (j === len) {
            return path
          }
          if (j !== last) {
            rootEnd = offset = j + 1
          }
        }
      }
    }
  } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
    rootEnd = len > 2 && isWindowsPathSeparator(path.charCodeAt(2)) ? 3 : 2
    offset = rootEnd
  }

  let end = -1
  let matchedSlash = true
  for (let i = len - 1; i >= offset; --i) {
    if (isWindowsPathSeparator(path.charCodeAt(i))) {
      if (!matchedSlash) {
        end = i
        break
      }
    } else {
      matchedSlash = false
    }
  }

  if (end === -1) {
    if (rootEnd === -1) return '.'

    end = rootEnd
  }
  return path.substring(0, end)
}

exports.basename = function basename(path, suffix) {
  let start = 0
  let end = -1
  let matchedSlash = true

  if (
    path.length >= 2 &&
    isWindowsDeviceRoot(path.charCodeAt(0)) &&
    path.charCodeAt(1) === CHAR_COLON
  ) {
    start = 2
  }

  if (suffix !== undefined && suffix.length > 0 && suffix.length <= path.length) {
    if (suffix === path) return ''
    let extIdx = suffix.length - 1
    let firstNonSlashEnd = -1
    for (let i = path.length - 1; i >= start; --i) {
      const code = path.charCodeAt(i)
      if (isWindowsPathSeparator(code)) {
        if (!matchedSlash) {
          start = i + 1
          break
        }
      } else {
        if (firstNonSlashEnd === -1) {
          matchedSlash = false
          firstNonSlashEnd = i + 1
        }
        if (extIdx >= 0) {
          if (code === suffix.charCodeAt(extIdx)) {
            if (--extIdx === -1) {
              end = i
            }
          } else {
            extIdx = -1
            end = firstNonSlashEnd
          }
        }
      }
    }

    if (start === end) end = firstNonSlashEnd
    else if (end === -1) end = path.length
    return path.substring(start, end)
  }
  for (let i = path.length - 1; i >= start; --i) {
    if (isWindowsPathSeparator(path.charCodeAt(i))) {
      if (!matchedSlash) {
        start = i + 1
        break
      }
    } else if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
  }

  if (end === -1) return ''
  return path.substring(start, end)
}

exports.extname = function extname(path) {
  let start = 0
  let startDot = -1
  let startPart = 0
  let end = -1
  let matchedSlash = true
  let preDotState = 0

  if (
    path.length >= 2 &&
    path.charCodeAt(1) === CHAR_COLON &&
    isWindowsDeviceRoot(path.charCodeAt(0))
  ) {
    start = startPart = 2
  }

  for (let i = path.length - 1; i >= start; --i) {
    const code = path.charCodeAt(i)
    if (isWindowsPathSeparator(code)) {
      if (!matchedSlash) {
        startPart = i + 1
        break
      }
      continue
    }
    if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
    if (code === CHAR_DOT) {
      if (startDot === -1) startDot = i
      else if (preDotState !== 1) preDotState = 1
    } else if (startDot !== -1) {
      preDotState = -1
    }
  }

  if (
    startDot === -1 ||
    end === -1 ||
    preDotState === 0 ||
    (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1)
  ) {
    return ''
  }
  return path.substring(startDot, end)
}
{
  "name": "bare-path",
  "version": "3.0.1",
  "description": "Path manipulation library for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./posix": "./lib/posix.js",
    "./win32": "./lib/win32.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "lib",
    "NOTICE"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-path.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-path/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-path#readme",
  "dependencies": {
    "bare-os": "^3.0.1"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "lunte": "^1.8.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
const b4a = require('b4a')
const stream = require('streamx')
const { ReadableStream, WritableStream } = require('./web')

const defaultEncoding = 'utf8'

module.exports = exports = stream.Stream

exports.pipeline = stream.pipeline

exports.isStream = stream.isStream
exports.isEnding = stream.isEnding
exports.isEnded = stream.isEnded
exports.isFinishing = stream.isFinishing
exports.isFinished = stream.isFinished
exports.isDisturbed = stream.isDisturbed

exports.isErrored = function isErrored(stream) {
  return exports.getStreamError(stream) !== null
}

exports.isReadable = function isReadable(stream) {
  return stream.readable && !stream.destroying && !exports.isEnded(stream)
}

exports.isWritable = function isWritable(stream) {
  return stream.writable && !stream.destroying && !exports.isFinishing(stream)
}

exports.getStreamError = stream.getStreamError

exports.addAbortSignal = function addAbortSignal(signal, stream) {
  function onAbort() {
    stream.destroy(signal.reason)
  }

  if (signal.aborted) onAbort()
  else signal.addEventListener('abort', onAbort)

  return stream
}

exports.Stream = exports

exports.Readable = class Readable extends stream.Readable {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthReadable: null,
      map: null,
      mapReadable: null
    })

    if (this._construct) this._open = this._construct

    if (this._read !== stream.Readable.prototype._read) {
      this._read = read.bind(this, this._read)
    }

    if (this._destroy !== stream.Stream.prototype._destroy) {
      this._destroy = destroy.bind(this, this._destroy)
    }
  }

  get closed() {
    return !exports.isReadable(this)
  }

  get errored() {
    return stream.getStreamError(this)
  }

  push(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    return super.push(chunk)
  }

  unshift(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    super.unshift(chunk)
  }

  static fromWeb(readableStream, opts = {}) {
    const stream = readableStream._stream

    if (opts.encoding) stream.setEncoding(opts.encoding)
    if (opts.signal) exports.addAbortSignal(opts.signal, stream)

    return stream
  }

  static toWeb(readable, opts = {}) {
    return new ReadableStream(readable, opts.strategy)
  }

  async [Symbol.asyncDispose]() {
    if (!this.destroyed) this.destroy()

    await new Promise((resolve) => exports.finished(this, resolve))
  }
}

exports.Writable = class Writable extends stream.Writable {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthWritable,
      map: null,
      mapWritable: null
    })

    if (this._construct) this._open = this._construct

    if (this._write !== stream.Writable.prototype._write) {
      this._write = write.bind(this, this._write)
    }

    if (this._destroy !== stream.Stream.prototype._destroy) {
      this._destroy = destroy.bind(this, this._destroy)
    }
  }

  get closed() {
    return !exports.isWritable(this)
  }

  get errored() {
    return stream.getStreamError(this)
  }

  write(chunk, encoding, cb) {
    if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result = super.write({ chunk, encoding })

    if (cb) stream.Writable.drained(this).then(() => cb(null), cb)

    return result
  }

  end(chunk, encoding, cb) {
    if (typeof chunk === 'function') {
      cb = chunk
      chunk = null
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    } else {
      encoding = 'buffer'
    }

    const result =
      chunk !== undefined && chunk !== null ? super.end({ chunk, encoding }) : super.end()

    if (cb) this.once('finish', () => cb(null))

    return result
  }

  static fromWeb(writableStream, opts = {}) {
    const stream = writableStream._stream

    if (opts.signal) exports.addAbortSignal(opts.signal, stream)

    return stream
  }

  static toWeb(writable) {
    return new WritableStream(writable)
  }

  async [Symbol.asyncDispose]() {
    if (!this.destroyed) this.destroy()

    await new Promise((resolve) => exports.finished(this, resolve))
  }
}

exports.Duplex = class Duplex extends stream.Duplex {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthReadable: null,
      byteLengthWritable,
      map: null,
      mapReadable: null,
      mapWritable: null
    })

    if (this._construct) this._open = this._construct

    if (this._read !== stream.Readable.prototype._read) {
      this._read = read.bind(this, this._read)
    }

    if (this._write !== stream.Duplex.prototype._write) {
      this._write = write.bind(this, this._write)
    }

    if (this._destroy !== stream.Stream.prototype._destroy) {
      this._destroy = destroy.bind(this, this._destroy)
    }
  }

  push(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    return super.push(chunk)
  }

  unshift(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    super.unshift(chunk)
  }

  write(chunk, encoding, cb) {
    if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result = super.write({ chunk, encoding })

    if (cb) stream.Writable.drained(this).then(() => cb(null), cb)

    return result
  }

  end(chunk, encoding, cb) {
    if (typeof chunk === 'function') {
      cb = chunk
      chunk = null
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result =
      chunk !== undefined && chunk !== null ? super.end({ chunk, encoding }) : super.end()

    if (cb) this.once('finish', () => cb(null))

    return result
  }

  static fromWeb({ readable: readableStream, writable: writableStream }, opts) {
    const readable = exports.Readable.fromWeb(readableStream, opts)
    const writable = exports.Writable.fromWeb(writableStream, opts)

    const duplex = new exports.Duplex({
      write(data, encoding, cb) {
        writable.write(data, encoding, cb)
      }
    })

    readable
      .on('data', (data) => duplex.push(data))
      .on('end', () => duplex.push(null))
      .on('error', (err) => duplex.destroy(err))

    writable.on('finish', () => duplex.end()).on('error', (err) => duplex.destroy(err))

    return duplex
  }

  static toWeb(duplex) {
    const readableStream = exports.Readable.toWeb(duplex)
    const writableStream = exports.Writable.toWeb(duplex)

    return { readable: readableStream, writable: writableStream }
  }
}

class DuplexSide extends exports.Duplex {
  constructor(opts) {
    super(opts)

    this._otherSide = null
    this._cb = null
  }

  _read() {
    const cb = this._cb
    if (!cb) return

    this._cb = null
    cb()
  }

  _write(chunk, encoding, cb) {
    this._otherSide.push(chunk, encoding)
    this._otherSide._cb = cb
  }

  _final(cb) {
    this._otherSide.on('end', cb)
    this._otherSide.push(null)
  }
}

exports.duplexPair = function duplexPair(opts) {
  const sideA = new DuplexSide(opts)
  const sideB = new DuplexSide(opts)

  sideA._otherSide = sideB
  sideB._otherSide = sideA

  return [sideA, sideB]
}

exports.Transform = class Transform extends stream.Transform {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthReadable: null,
      byteLengthWritable,
      map: null,
      mapReadable: null,
      mapWritable: null
    })

    if (this._transform !== stream.Transform.prototype._transform) {
      this._transform = transform.bind(this, this._transform)
    } else {
      this._transform = passthrough
    }
  }

  push(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    return super.push(chunk)
  }

  unshift(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    super.unshift(chunk)
  }

  write(chunk, encoding, cb) {
    if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result = super.write({ chunk, encoding })

    if (cb) stream.Writable.drained(this).then(() => cb(null), cb)

    return result
  }

  end(chunk, encoding, cb) {
    if (typeof chunk === 'function') {
      cb = chunk
      chunk = null
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result =
      chunk !== undefined && chunk !== null ? super.end({ chunk, encoding }) : super.end()

    if (cb) this.once('finish', () => cb(null))

    return result
  }
}

exports.PassThrough = class PassThrough extends exports.Transform {}

exports.finished = function finished(stream, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (!opts) opts = {}

  const { cleanup = false } = opts

  const done = () => {
    cb(exports.getStreamError(stream, { all: true }))

    if (cleanup) detach()
  }

  const detach = () => {
    stream.off('close', done)
    stream.off('error', noop)
  }

  if (stream.destroyed) {
    done()
  } else {
    stream.on('close', done)
    stream.on('error', noop)
  }

  return detach
}

function read(read, cb) {
  read.call(this, 65536)

  cb(null)
}

function write(write, data, cb) {
  write.call(this, data.chunk, data.encoding, cb)
}

function transform(transform, data, cb) {
  transform.call(this, data.chunk, data.encoding, cb)
}

function destroy(destroy, cb) {
  destroy.call(this, exports.getStreamError(this), cb)
}

function passthrough(data, cb) {
  cb(null, data.chunk)
}

function byteLengthWritable(data) {
  return data.chunk.byteLength
}

function noop() {}
{
  "name": "bare-stream",
  "version": "2.13.3",
  "description": "Streaming data for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./promises": "./promises.js",
    "./web": {
      "types": "./web.d.ts",
      "default": "./web.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "promises.js",
    "web.js",
    "web.d.ts",
    "global.js",
    "global.d.ts"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-stream.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-stream/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-stream#readme",
  "dependencies": {
    "b4a": "^1.8.1",
    "streamx": "^2.25.0",
    "teex": "^1.0.1"
  },
  "devDependencies": {
    "bare-abort-controller": "^1.1.0",
    "bare-buffer": "^3.0.0",
    "bare-events": "^2.5.4",
    "brittle": "^3.5.2",
    "lunte": "^1.6.0",
    "prettier": "^3.3.3",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "bare-abort-controller": "*",
    "bare-buffer": "*",
    "bare-events": "*"
  },
  "peerDependenciesMeta": {
    "bare-abort-controller": {
      "optional": true
    },
    "bare-buffer": {
      "optional": true
    },
    "bare-events": {
      "optional": true
    }
  }
}
const { Readable, Writable, Transform, getStreamError, isStreamx, isDisturbed } = require('streamx')
const tee = require('teex')

const readableKind = Symbol.for('bare.stream.readable.kind')
const writableKind = Symbol.for('bare.stream.writable.kind')
const transformKind = Symbol.for('bare.stream.transform.kind')

// https://streams.spec.whatwg.org/#readablestreamdefaultreader
exports.ReadableStreamDefaultReader = class ReadableStreamDefaultReader {
  constructor(stream) {
    this._stream = stream
    this._stream._stream.once('close', onclose).once('error', onerror)

    const closed = Promise.withResolvers()

    // Avoid unhandled exceptions
    closed.promise.catch(noop)

    this._closed = closed

    function onclose() {
      closed.resolve()
    }

    function onerror(err) {
      closed.reject(err)
    }
  }

  get closed() {
    return this._closed.promise
  }

  read() {
    const stream = this._stream._stream

    return new Promise((resolve, reject) => {
      const err = getStreamError(stream)

      if (err) return reject(err)

      if (stream.destroyed) {
        return resolve({ value: undefined, done: true })
      }

      const value = stream.read()

      if (value !== null) {
        return resolve({ value, done: false })
      }

      stream.once('readable', onreadable).once('close', onclose).once('error', onerror)

      function onreadable() {
        const value = stream.read()

        ondone(null, value === null ? { value: undefined, done: true } : { value, done: false })
      }

      function onclose() {
        ondone(null, { value: undefined, done: true })
      }

      function onerror(err) {
        ondone(err, null)
      }

      function ondone(err, value) {
        stream.off('readable', onreadable).off('close', onclose).off('error', onerror)

        if (err) reject(err)
        else resolve(value)
      }
    })
  }

  releaseLock() {
    this._closed.reject(new TypeError('Reader was released'))
    this._stream._releaseLock()
    this._stream = null
  }

  cancel(reason = new TypeError('Stream was cancelled')) {
    const stream = this._stream._stream

    if (stream.destroyed) return Promise.resolve()

    return new Promise((resolve) =>
      stream.once('close', resolve).once('error', noop).destroy(reason)
    )
  }
}

// https://streams.spec.whatwg.org/#readablestreamdefaultcontroller
exports.ReadableStreamDefaultController = class ReadableStreamDefaultController {
  constructor(stream) {
    this._stream = stream
  }

  get desiredSize() {
    const stream = this._stream._stream

    return stream._readableState.highWaterMark - stream._readableState.buffered
  }

  enqueue(data) {
    this._stream._stream.push(data)
  }

  close() {
    this._stream._stream.push(null)
  }

  error(err) {
    this._stream._stream.destroy(err)
  }
}

// https://streams.spec.whatwg.org/#readablestream
class ReadableStream {
  static get [readableKind]() {
    return 0 // Compatibility version
  }

  static from(iterable) {
    return new ReadableStream(Readable.from(iterable))
  }

  constructor(underlyingSource = {}, queuingStrategy) {
    if (isStreamx(underlyingSource)) {
      this._stream = underlyingSource
    } else {
      if (queuingStrategy === undefined) {
        queuingStrategy = new exports.CountQueuingStrategy()
      }

      const { start, pull, cancel } = underlyingSource
      const { highWaterMark = 1, size = defaultSize } = queuingStrategy

      this._stream = new Readable({ highWaterMark, byteLength: size })

      const controller = new exports.ReadableStreamDefaultController(this)

      try {
        let starting = Promise.resolve()

        if (start) starting = forwardError(start.call(this, controller), controller)

        if (pull) {
          this._stream._read = this._read.bind(this, starting, pull.bind(this, controller))
        }

        if (cancel) {
          this._stream.once('error', cancel.bind(this))
        }
      } catch (err) {
        controller.error(err)
      }
    }

    this._reader = null
  }

  get [readableKind]() {
    return ReadableStream[readableKind]
  }

  get locked() {
    return this._reader !== null
  }

  getReader() {
    if (this.locked) throw new TypeError('Stream is locked')

    this._reader = new exports.ReadableStreamDefaultReader(this)

    return this._reader
  }

  cancel(reason = new TypeError('Stream was cancelled')) {
    const stream = this._stream

    if (stream.destroyed) return Promise.resolve()

    if (this.locked) return Promise.reject(new TypeError('Stream is locked'))

    return new Promise((resolve) =>
      stream.once('close', resolve).once('error', noop).destroy(reason)
    )
  }

  tee() {
    const [a, b] = tee(this._stream)

    return [new ReadableStream(a), new ReadableStream(b)]
  }

  pipeTo(destination) {
    return new Promise((resolve, reject) =>
      this._stream.pipe(destination._stream, (err) => {
        err ? reject(err) : resolve()
      })
    )
  }

  [Symbol.asyncIterator]() {
    return this._stream[Symbol.asyncIterator]()
  }

  _releaseLock() {
    this._reader = null
  }

  async _read(starting, pull, cb) {
    await starting

    let err = null
    try {
      await pull()
    } catch (e) {
      err = e
    }
    cb(err)
  }
}

function defaultSize() {
  return 1
}

exports.ReadableStream = ReadableStream

// https://streams.spec.whatwg.org/#countqueuingstrategy
exports.CountQueuingStrategy = class CountQueuingStrategy {
  constructor(opts = {}) {
    const { highWaterMark = 1 } = opts

    this.highWaterMark = highWaterMark
  }

  size(chunk) {
    return 1
  }
}

// https://streams.spec.whatwg.org/#bytelengthqueuingstrategy
exports.ByteLengthQueuingStrategy = class ByteLengthQueuingStrategy {
  constructor(opts = {}) {
    const { highWaterMark = 16384 } = opts

    this.highWaterMark = highWaterMark
  }

  size(chunk) {
    return chunk.byteLength
  }
}

exports.isReadableStream = function isReadableStream(value) {
  if (value instanceof ReadableStream) return true

  return (
    typeof value === 'object' &&
    value !== null &&
    value[readableKind] === ReadableStream[readableKind]
  )
}

// https://streams.spec.whatwg.org/#readablestream-errored
exports.isReadableStreamErrored = function isReadableStreamErrored(stream) {
  return getStreamError(stream._stream) !== null
}

// https://streams.spec.whatwg.org/#is-readable-stream-disturbed
exports.isReadableStreamDisturbed = function isReadableStreamDisturbed(stream) {
  return isDisturbed(stream._stream)
}

// https://streams.spec.whatwg.org/#writablestreamdefaultwriter
exports.WritableStreamDefaultWriter = class WritableStreamDefaultWriter {
  constructor(stream) {
    this._stream = stream
    this._stream._stream.once('close', onclose).once('error', onerror)

    const closed = Promise.withResolvers()

    // Avoid unhandled exceptions
    closed.promise.catch(noop)

    this._closed = closed

    function onclose() {
      closed.resolve()
    }

    function onerror(err) {
      closed.reject(err)
    }
  }

  get desiredSize() {
    const stream = this._stream._stream

    return stream._writableState.highWaterMark - stream._writableState.buffered
  }

  get closed() {
    return this._closed.promise
  }

  get ready() {
    const stream = this._stream._stream

    if (getStreamError(stream)) return Promise.reject()

    return Writable.drained(stream).then()
  }

  async write(chunk) {
    const stream = this._stream._stream

    let err = getStreamError(stream)
    if (err) return Promise.reject(err)

    stream.write(chunk)

    await Writable.drained(stream)

    err = getStreamError(stream)
    if (err) return Promise.reject(err)
  }

  releaseLock() {
    this._closed.reject(new TypeError('Writer was released'))
    this._stream._releaseLock()
    this._stream = null
  }

  close() {
    const stream = this._stream._stream

    if (stream.destroyed) return Promise.resolve()

    return new Promise((resolve) => stream.once('close', resolve).end())
  }

  abort(reason = new TypeError('Stream was aborted')) {
    const stream = this._stream._stream

    if (stream.destroyed) return Promise.resolve()

    return new Promise((resolve) => stream.once('close', resolve).destroy(reason))
  }
}

// https://streams.spec.whatwg.org/#writablestreamdefaultcontroller
exports.WritableStreamDefaultController = class WritableStreamDefaultController {
  constructor(stream) {
    this._stream = stream
  }

  error(err) {
    this._stream._stream.destroy(err)
  }
}

// https://streams.spec.whatwg.org/#writablestream
class WritableStream {
  static get [writableKind]() {
    return 0 // Compatibility version
  }

  constructor(underlyingSink = {}, queuingStrategy = {}) {
    if (isStreamx(underlyingSink)) {
      this._stream = underlyingSink
    } else {
      if (queuingStrategy === undefined) {
        queuingStrategy = new exports.CountQueuingStrategy()
      }

      const { start, write, close, abort } = underlyingSink
      const { highWaterMark = 1, size = defaultSize } = queuingStrategy

      this._stream = new Writable({ highWaterMark, byteLength: size })

      const controller = new exports.WritableStreamDefaultController(this)

      this._controller = controller

      try {
        let starting = Promise.resolve()

        if (start) starting = forwardError(start.call(this, controller), controller)

        if (write) {
          this._stream._write = this._write.bind(this, starting, write.bind(this))
        }

        if (close) {
          this._stream._destroy = this._destroy.bind(this, close.call(this))
        }

        if (abort) {
          this._stream.once('error', abort.bind(this))
        }
      } catch (err) {
        controller.error(err)
      }
    }

    this._writer = null
  }

  get [writableKind]() {
    return WritableStream[writableKind]
  }

  get locked() {
    return this._writer !== null
  }

  getWriter() {
    if (this.locked) throw new TypeError('Stream is locked')

    this._writer = new exports.WritableStreamDefaultWriter(this)

    return this._writer
  }

  abort(reason = new TypeError('Stream was aborted')) {
    if (this._stream.destroyed) return Promise.resolve()

    if (this.locked) return Promise.reject(new TypeError('Stream is locked'))

    return new Promise((resolve) => this._stream.once('close', resolve).destroy(reason))
  }

  close() {
    if (this._stream.destroyed) return Promise.resolve()

    if (this.locked) return Promise.reject(new TypeError('Stream is locked'))

    return new Promise((resolve) => this._stream.once('close', resolve).end())
  }

  _releaseLock() {
    this._writer = null
  }

  async _write(starting, write, data, cb) {
    await starting

    let err = null
    try {
      await write(data, this._controller)
    } catch (e) {
      err = e
    }
    cb(err)
  }

  async _destroy(closing, cb) {
    let err = null
    try {
      await closing
    } catch (e) {
      err = e
    }
    cb(err)
  }
}

exports.WritableStream = WritableStream

exports.isWritableStream = function isWritableStream(value) {
  if (value instanceof WritableStream) return true

  return (
    typeof value === 'object' &&
    value !== null &&
    value[writableKind] === WritableStream[writableKind]
  )
}

// https://streams.spec.whatwg.org/#transformstreamdefaultcontroller
exports.TransformStreamDefaultController = class TransformStreamDefaultController {
  constructor(stream) {
    this._stream = stream
  }

  get desiredSize() {
    const stream = this._stream._stream

    return stream._readableState.highWaterMark - stream._readableState.buffered
  }

  enqueue(data) {
    this._stream._stream.push(data)
  }

  error(err) {
    this._stream._stream.destroy(err)
  }

  terminate() {
    const stream = this._stream._stream

    stream.push(null)
    stream.destroy(new TypeError('Stream has been terminated'))
  }
}

// https://streams.spec.whatwg.org/#transformstream
class TransformStream {
  static get [transformKind]() {
    return 0 // Compatibility version
  }

  constructor(transformer = {}, writableStrategy = {}, readableStrategy = {}) {
    if (isStreamx(transformer)) {
      this._stream = transformer
    } else {
      const { start, transform, flush } = transformer

      this._stream = new Transform({ ...writableStrategy, ...readableStrategy })

      const controller = new exports.TransformStreamDefaultController(this)

      this._controller = controller

      try {
        let starting = Promise.resolve()

        if (start) starting = forwardError(start.call(this, controller), controller)

        if (transform) {
          this._stream._transform = this._transform.bind(this, starting, transform.bind(this))
        }

        if (flush) {
          this._stream._flush = this._flush.bind(this, flush.call(this, this._controller))
        }
      } catch (err) {
        controller.error(err)
      }
    }

    this._writable = new WritableStream(this._stream)
    this._readable = new ReadableStream(this._stream)
  }

  get [transformKind]() {
    return TransformStream[transformKind]
  }

  get writable() {
    return this._writable
  }

  get readable() {
    return this._readable
  }

  async _transform(starting, transform, data, cb) {
    await starting

    let err = null
    try {
      await transform(data, this._controller)
    } catch (e) {
      err = e
    }
    cb(err)
  }

  async _flush(flush, cb) {
    let err = null
    try {
      await flush
    } catch (e) {
      err = e
    }
    cb(err)
  }
}

exports.TransformStream = TransformStream

exports.isTransformStream = function isTransformStream(value) {
  if (value instanceof TransformStream) return true

  return (
    typeof value === 'object' &&
    value !== null &&
    value[transformKind] === TransformStream[transformKind]
  )
}

async function forwardError(promise, controller) {
  try {
    await promise
  } catch (err) {
    controller.error(err)
  }
}

function noop() {}
module.exports = require.addon()
const binding = require('./binding')

const t = binding.constants

class Type {
  constructor(type) {
    this._type = type
  }

  isUndefined() {
    return this._type === t.UNDEFINED
  }

  isNull() {
    return this._type === t.NULL
  }

  isBoolean() {
    return this._type === t.BOOLEAN
  }

  isNumber() {
    return (this._type & 0xff) === t.NUMBER
  }

  isInt32() {
    return (this._type & (0xff | t.INT32)) === (t.NUMBER | t.INT32)
  }

  isUint32() {
    return (this._type & (0xff | t.UINT32)) === (t.NUMBER | t.UINT32)
  }

  isString() {
    return this._type === t.STRING
  }

  isSymbol() {
    return this._type === t.SYMBOL
  }

  isObject() {
    return (this._type & 0xff) === t.OBJECT
  }

  isArray() {
    return this._type === (t.OBJECT | t.ARRAY)
  }

  isArguments() {
    return this._type === (t.OBJECT | t.ARGUMENTS)
  }

  isDate() {
    return this._type === (t.OBJECT | t.DATE)
  }

  isRegExp() {
    return this._type === (t.OBJECT | t.REGEXP)
  }

  isError() {
    return this._type === (t.OBJECT | t.ERROR)
  }

  isPromise() {
    return this._type === (t.OBJECT | t.PROMISE)
  }

  isProxy() {
    return this._type === (t.OBJECT | t.PROXY)
  }

  isGenerator() {
    return this._type === (t.OBJECT | t.GENERATOR)
  }

  isMap() {
    return this._type === (t.OBJECT | t.MAP)
  }

  isSet() {
    return this._type === (t.OBJECT | t.SET)
  }

  isWeakMap() {
    return this._type === (t.OBJECT | t.WEAK_MAP)
  }

  isWeakSet() {
    return this._type === (t.OBJECT | t.WEAK_SET)
  }

  isWeakRef() {
    return this._type === (t.OBJECT | t.WEAK_REF)
  }

  isArrayBuffer() {
    return this._type === (t.OBJECT | t.ARRAYBUFFER)
  }

  isSharedArrayBuffer() {
    return this._type === (t.OBJECT | t.SHAREDARRAYBUFFER)
  }

  isTypedArray() {
    return (this._type & 0xffff) === (t.OBJECT | t.TYPEDARRAY)
  }

  isInt8Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT8ARRAY)
  }

  isUint8Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT8ARRAY)
  }

  isUint8ClampedArray() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT8CLAMPEDARRAY)
  }

  isInt16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT16ARRAY)
  }

  isUint16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT16ARRAY)
  }

  isInt32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT32ARRAY)
  }

  isUint32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT32ARRAY)
  }

  isFloat16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT16ARRAY)
  }

  isFloat32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT32ARRAY)
  }

  isFloat64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT64ARRAY)
  }

  isBigInt64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.BIGINT64ARRAY)
  }

  isBigUint64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.BIGUINT64ARRAY)
  }

  isDataView() {
    return this._type === (t.OBJECT | t.DATAVIEW)
  }

  isModuleNamespace() {
    return this._type === (t.OBJECT | t.MODULE_NAMESPACE)
  }

  isFunction() {
    return (this._type & 0xff) === t.FUNCTION
  }

  isAsyncFunction() {
    return (
      (this._type & (0xff | t.ASYNC_FUNCTION)) ===
      (t.FUNCTION | t.ASYNC_FUNCTION)
    )
  }

  isGeneratorFunction() {
    return (
      (this._type & (0xff | t.GENERATOR_FUNCTION)) ===
      (t.FUNCTION | t.GENERATOR_FUNCTION)
    )
  }

  isExternal() {
    return this._type === t.EXTERNAL
  }

  isBigInt() {
    return this._type === t.BIGINT
  }
}

module.exports = exports = function type(value) {
  switch (typeof value) {
    case 'undefined':
      return new Type(t.UNDEFINED)
    case 'boolean':
      return new Type(t.BOOLEAN)
    case 'number':
      return new Type(
        Number.isSafeInteger(value) ? binding.type(value) : t.NUMBER
      )
    case 'string':
      return new Type(t.STRING)
    case 'symbol':
      return new Type(t.SYMBOL)
    case 'object':
      return new Type(value === null ? t.NULL : binding.type(value))
    case 'function':
      return new Type(binding.type(value))
    case 'bigint':
      return new Type(t.BIGINT)
  }
}

exports.createTag = function createTag(...components) {
  const tag = new Uint32Array(4)
  for (let i = 0; i < 4; i++) tag[i] = components[i] || 0
  return tag
}

exports.addTag = function addTag(object, tag) {
  binding.addTag(object, tag)
}

exports.checkTag = function checkTag(object, tag) {
  return binding.checkTag(object, tag)
}
{
  "name": "bare-type",
  "version": "1.1.0",
  "description": "Cross-realm type predicates for Bare",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-type.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-type/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-type#readme",
  "engines": {
    "bare": ">=1.2.0"
  },
  "devDependencies": {
    "brittle": "^3.4.0",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
module.exports = require.addon()
const path = require('bare-path')
const binding = require('./binding')
const errors = require('./lib/errors')
const URLSearchParams = require('./lib/url-search-params')

const kind = Symbol.for('bare.url.kind')

const isWindows = Bare.platform === 'win32'

class URL {
  static get [kind]() {
    return 0 // Compatibility version
  }

  constructor(input, base, opts = {}) {
    if (arguments.length === 0) throw errors.INVALID_URL()

    input = String(input)

    if (base !== undefined) base = String(base)

    this._components = new Uint32Array(8)

    this._parse(input, base, opts.throw !== false)

    if (this._href) this._params = new URLSearchParams(this.search, this)
  }

  get [kind]() {
    return URL[kind]
  }

  // https://url.spec.whatwg.org/#dom-url-href

  get href() {
    return this._href
  }

  set href(value) {
    this._update(value)

    this._params._parse(this.search)
  }

  // https://url.spec.whatwg.org/#dom-url-protocol

  get protocol() {
    return this._slice(0, this._components[0]) + ':'
  }

  set protocol(value) {
    this._update(this._replace(value.replace(/:+$/, ''), 0, this._components[0]))
  }

  // https://url.spec.whatwg.org/#dom-url-username

  get username() {
    return this._slice(this._components[0] + 3 /* :// */, this._components[1])
  }

  set username(value) {
    if (cannotHaveCredentialsOrPort(this)) {
      return
    }

    if (this.username === '') value += '@'

    this._update(this._replace(value, this._components[0] + 3 /* :// */, this._components[1]))
  }

  // https://url.spec.whatwg.org/#dom-url-password

  get password() {
    return this._href.slice(this._components[1] + 1 /* : */, this._components[2] - 1 /* @ */)
  }

  set password(value) {
    if (cannotHaveCredentialsOrPort(this)) {
      return
    }

    let start = this._components[1] + 1 /* : */
    let end = this._components[2] - 1 /* @ */

    if (this.password === '') {
      value = ':' + value
      start--
    }

    if (this.username === '') {
      value += '@'
      end++
    }

    this._update(this._replace(value, start, end))
  }

  // https://url.spec.whatwg.org/#dom-url-host

  get host() {
    return this._slice(this._components[2], this._components[5])
  }

  set host(value) {
    if (hasOpaquePath(this)) {
      return
    }

    this._update(
      this._replace(value, this._components[2], this._components[value.includes(':') ? 5 : 3])
    )
  }

  // https://url.spec.whatwg.org/#dom-url-hostname

  get hostname() {
    return this._slice(this._components[2], this._components[3])
  }

  set hostname(value) {
    if (hasOpaquePath(this)) {
      return
    }

    this._update(this._replace(value, this._components[2], this._components[3]))
  }

  // https://url.spec.whatwg.org/#dom-url-port

  get port() {
    return this._slice(this._components[3] + 1 /* : */, this._components[5])
  }

  set port(value) {
    if (cannotHaveCredentialsOrPort(this)) {
      return
    }

    let start = this._components[3] + 1 /* : */

    if (this.port === '') {
      value = ':' + value
      start--
    }

    this._update(this._replace(value, start, this._components[5]))
  }

  // https://url.spec.whatwg.org/#dom-url-pathname

  get pathname() {
    return this._slice(this._components[5], this._components[6] - 1 /* ? */)
  }

  set pathname(value) {
    if (hasOpaquePath(this)) {
      return
    }

    if (value[0] !== '/' && value[0] !== '\\') {
      value = '/' + value
    }

    this._update(this._replace(value, this._components[5], this._components[6] - 1 /* ? */))
  }

  // https://url.spec.whatwg.org/#dom-url-search

  get search() {
    return this._slice(this._components[6] - 1 /* ? */, this._components[7] - 1 /* # */)
  }

  set search(value) {
    if (value && value[0] !== '?') value = '?' + value

    this._update(
      this._replace(value, this._components[6] - 1 /* ? */, this._components[7] - 1 /* # */)
    )

    this._params._parse(this.search)
  }

  // https://url.spec.whatwg.org/#dom-url-searchparams

  get searchParams() {
    return this._params
  }

  // https://url.spec.whatwg.org/#dom-url-hash

  get hash() {
    return this._slice(this._components[7] - 1 /* # */)
  }

  set hash(value) {
    if (value && value[0] !== '#') value = '#' + value

    this._update(this._replace(value, this._components[7] - 1 /* # */))
  }

  toString() {
    return this._href
  }

  toJSON() {
    return this._href
  }

  [Symbol.for('bare.inspect')]() {
    return {
      __proto__: { constructor: URL },

      href: this.href,
      protocol: this.protocol,
      username: this.username,
      password: this.password,
      host: this.host,
      hostname: this.hostname,
      port: this.port,
      pathname: this.pathname,
      search: this.search,
      searchParams: this.searchParams,
      hash: this.hash
    }
  }

  _slice(start, end = this._href.length) {
    return this._href.slice(start, end)
  }

  _replace(replacement, start, end = this._href.length) {
    return this._slice(0, start) + replacement + this._slice(end)
  }

  _parse(input, base, shouldThrow) {
    try {
      this._href = binding.parse(
        String(input),
        base ? String(base) : null,
        this._components,
        shouldThrow
      )
    } catch (err) {
      if (err instanceof TypeError) throw err

      throw errors.INVALID_URL(`Invalid URL '${input}'`, input)
    }
  }

  _update(input) {
    try {
      this._parse(input, null, true)
    } catch (err) {
      if (err instanceof TypeError) throw err
    }
  }
}

module.exports = exports = URL

// https://url.spec.whatwg.org/#url-opaque-path
function hasOpaquePath(url) {
  return url.pathname[0] !== '/'
}

// https://url.spec.whatwg.org/#cannot-have-a-username-password-port
function cannotHaveCredentialsOrPort(url) {
  return url.hostname === '' || url.protocol === 'file:'
}

exports.URL = URL
exports.URLSearchParams = URLSearchParams

exports.errors = errors

exports.isURL = function isURL(value) {
  if (value instanceof URL) return true

  return typeof value === 'object' && value !== null && value[kind] === URL[kind]
}

exports.isURLSearchParams = URLSearchParams.isURLSearchParams

// https://url.spec.whatwg.org/#dom-url-parse
exports.parse = function parse(input, base) {
  const url = new URL(input, base, { throw: false })
  return url._href ? url : null
}

// https://url.spec.whatwg.org/#dom-url-canparse
exports.canParse = function canParse(input, base) {
  return binding.canParse(String(input), base ? String(base) : null)
}

exports.fileURLToPath = function fileURLToPath(url) {
  if (typeof url === 'string') {
    url = new URL(url)
  }

  if (url.protocol !== 'file:') {
    throw errors.INVALID_URL_SCHEME('The URL must use the file: protocol')
  }

  if (isWindows) {
    if (/%2f|%5c/i.test(url.pathname)) {
      throw errors.INVALID_FILE_URL_PATH(
        'The file: URL path must not include encoded \\ or / characters'
      )
    }
  } else {
    if (url.hostname) {
      throw errors.INVALID_FILE_URL_HOST("The file: URL host must be 'localhost' or empty")
    }

    if (/%2f/i.test(url.pathname)) {
      throw errors.INVALID_FILE_URL_PATH('The file: URL path must not include encoded / characters')
    }
  }

  if (/%00/i.test(url.pathname)) {
    throw errors.INVALID_FILE_URL_PATH('The file: URL path must not include encoded NUL characters')
  }

  const pathname = path.normalize(decodeURIComponent(url.pathname))

  if (isWindows) {
    if (url.hostname) return '\\\\' + url.hostname + pathname

    const letter = pathname.charCodeAt(1) | 0x20

    if (letter < 0x61 /* a */ || letter > 0x7a /* z */ || pathname.charCodeAt(2) !== 0x3a /* : */) {
      throw errors.INVALID_FILE_URL_PATH('The file: URL path must be absolute')
    }

    return pathname.slice(1)
  }

  return pathname
}

exports.pathToFileURL = function pathToFileURL(pathname) {
  let resolved = path.resolve(pathname)

  if (pathname[pathname.length - 1] === '/') {
    resolved += '/'
  } else if (isWindows && pathname[pathname.length - 1] === '\\') {
    resolved += '\\'
  }

  resolved = resolved
    .replaceAll('%', '%25') // Must be first
    .replaceAll('#', '%23')
    .replaceAll('?', '%3f')
    .replaceAll('\n', '%0a')
    .replaceAll('\r', '%0d')
    .replaceAll('\t', '%09')

  if (!isWindows) {
    resolved = resolved.replaceAll('\\', '%5c')
  }

  return new URL('file:' + resolved)
}

exports.format = function format(parts) {
  const { protocol, auth, host, hostname, port, pathname, search, query, hash, slashes } = parts

  let result = ''

  if (typeof protocol === 'string') {
    result += protocol

    if (protocol[protocol.length - 1] !== ':') {
      result += ':'
    }

    if (slashes === true || /https?|ftp|gopher|file/.test(protocol)) {
      result += '//'
    }
  }

  if (typeof auth === 'string') {
    if (host || hostname) result += auth + '@'
  }

  if (typeof host === 'string') result += host
  else {
    result += hostname

    if (port) result += ':' + port
  }

  if (typeof pathname === 'string' && pathname !== '') {
    if (pathname[0] !== '/') result += '/'
    result += pathname
  }

  if (typeof search === 'string') {
    if (search[0] !== '?') result += '?'
    result += search
  } else if (typeof query === 'object' && query !== null) {
    result += '?' + new URLSearchParams(query)
  }

  if (typeof hash === 'string') {
    if (hash[0] !== '#') result += '#'
    result += hash
  }

  return result
}
module.exports = class URLError extends Error {
  constructor(msg, fn = URLError, code = fn.name) {
    super(`${code}: ${msg}`)

    this.code = code

    if (Error.captureStackTrace) Error.captureStackTrace(this, fn)
  }

  get name() {
    return 'URLError'
  }

  static INVALID_URL(msg, input) {
    const err = new URLError(msg, URLError.INVALID_URL)

    err.input = input

    return err
  }

  static INVALID_URL_SCHEME(msg = 'Invalid URL') {
    return new URLError(msg, URLError.INVALID_URL_SCHEME)
  }

  static INVALID_FILE_URL_HOST(msg = 'Invalid file: URL host') {
    return new URLError(msg, URLError.INVALID_FILE_URL_HOST)
  }

  static INVALID_FILE_URL_PATH(msg = 'Invalid file: URL path') {
    return new URLError(msg, URLError.INVALID_FILE_URL_PATH)
  }
}
const kind = Symbol.for('bare.url.search-params.kind')

class URLSearchParams {
  static _urls = new WeakMap()

  static get [kind]() {
    return 0 // Compatibility version
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-urlsearchparams
  constructor(init, url = null) {
    this._params = new Map()

    if (url) URLSearchParams._urls.set(this, url)

    if (typeof init === 'string') {
      this._parse(init)
    } else if (init) {
      for (const [name, value] of typeof init[Symbol.iterator] === 'function'
        ? init
        : Object.entries(init)) {
        this.append(name, value)
      }
    }
  }

  get [kind]() {
    return URLSearchParams[kind]
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-size
  get size() {
    return this._params.length
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-append
  append(name, value = null) {
    if (value === null) return

    let list = this._params.get(name)

    if (list === undefined) {
      list = []
      this._params.set(name, list)
    }

    list.push(value)

    this._update()
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-delete
  delete(name, value = null) {
    if (value === null) this._params.delete(name)
    else {
      let list = this._params.get(name)

      if (list === undefined) return

      list = list.filter((found) => found !== value)

      if (list.length === 0) this._params.delete(name)
      else this._params.set(name, list)
    }

    this._update()
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-get
  get(name) {
    const list = this._params.get(name)

    if (list === undefined) return null

    return list[0]
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-getall
  getAll(name) {
    const list = this._params.get(name)

    if (list === undefined) return []

    return Array.from(list)
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-has
  has(name, value = null) {
    const list = this._params.get(name)

    if (list === undefined) return false

    if (value === null) return true

    return list.includes(value)
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-set
  set(name, value = null) {
    if (value === null) this._params.delete(name)
    else this._params.set(name, [value])

    this._update()
  }

  toString() {
    return this._serialize()
  }

  toJSON() {
    return [...this]
  }

  *[Symbol.iterator]() {
    for (const [name, values] of this._params) {
      for (const value of values) yield [name, value]
    }
  }

  [Symbol.for('bare.inspect')]() {
    const object = {
      __proto__: { constructor: URLSearchParams }
    }

    for (const [name, values] of this._params) {
      if (values.length === 1) object[name] = values[0]
      else object[name] = values
    }

    return object
  }

  // https://url.spec.whatwg.org/#concept-urlsearchparams-update
  _update() {
    const url = URLSearchParams._urls.get(this)

    if (url === undefined) return

    url.search = this._serialize()
  }

  // https://url.spec.whatwg.org/#concept-urlencoded-parser
  _parse(input) {
    if (input[0] === '?') input = input.substring(1)

    this._params = new Map()

    for (let sequence of input.split('&')) {
      if (sequence.length === 0) continue

      sequence = sequence.replace(/\+/g, ' ')

      let i = sequence.indexOf('=')
      if (i === -1) i = sequence.length

      const name = decodeURIComponent(sequence.substring(0, i))
      const value = decodeURIComponent(sequence.substring(i + 1, sequence.length))

      let list = this._params.get(name)

      if (list === undefined) {
        list = []
        this._params.set(name, list)
      }

      list.push(value)
    }
  }

  // https://url.spec.whatwg.org/#concept-urlencoded-serializer
  _serialize() {
    let output = ''

    for (let [name, values] of this._params) {
      name = encodeURIComponent(name)

      for (const value of values) {
        if (output) output += '&'

        output += name + '=' + encodeURIComponent(value)
      }
    }

    return output
  }
}

module.exports = exports = URLSearchParams

exports.isURLSearchParams = function isURLSearchParams(value) {
  if (value instanceof URLSearchParams) return true

  return typeof value === 'object' && value !== null && value[kind] === URLSearchParams[kind]
}
{
  "name": "bare-url",
  "version": "2.4.5",
  "description": "WHATWG URL implementation for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "global.js",
    "global.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-url.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-url/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-url",
  "dependencies": {
    "bare-path": "^3.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "cmake-bare": "^1.1.6",
    "cmake-fetch": "^1.0.0",
    "lunte": "^1.6.0",
    "prettier": "^3.3.3",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = require.addon()
const { Transform, Writable } = require('bare-stream')
const binding = require('./binding')
const constants = require('./lib/constants')
const errors = require('./lib/errors')

exports.constants = constants
exports.errors = errors

const MAX_OUTPUT_LENGTH = (Buffer.constants && Buffer.constants.MAX_LENGTH) || 0x100000000

class ZlibState {
  constructor(mode, opts = {}) {
    const {
      flush = constants.Z_NO_FLUSH,
      finishFlush = constants.Z_FINISH,
      chunkSize = constants.Z_DEFAULT_CHUNK,
      level = constants.Z_DEFAULT_LEVEL,
      windowBits = constants.Z_DEFAULT_WINDOWBITS,
      memLevel = constants.Z_DEFAULT_MEMLEVEL,
      strategy = constants.Z_DEFAULT_STRATEGY,
      maxOutputLength = MAX_OUTPUT_LENGTH
    } = opts

    this._mode = mode

    this._flushMode = flush
    this._finishFlushMode = finishFlush
    this._allocations = []

    this._maxOutputLength = maxOutputLength
    this._outputLength = 0

    this._buffer = Buffer.allocUnsafe(chunkSize)

    this._handle = binding.init(
      this._mode,
      this._buffer,
      level,
      windowBits,
      memLevel,
      strategy,
      this,
      this._onalloc,
      this._onfree
    )
  }

  _onalloc(size) {
    const buffer = Buffer.allocUnsafe(size)

    const view = new Uint32Array(buffer.buffer, buffer.byteOffset, buffer.byteLength / 4)

    view[0] = this._allocations.push(view) - 1

    return buffer
  }

  _onfree(id) {
    const last = this._allocations.pop()

    if (last[0] !== id) {
      this._allocations[(last[0] = id)] = last
    }
  }

  reset() {
    this._outputLength = 0

    binding.reset(this._handle)
  }

  *transform(data) {
    binding.load(this._handle, data)

    let available
    do {
      try {
        available = binding.transform(this._handle, this._flushMode)
      } catch (err) {
        throw errors[err.code](err.message)
      }

      const read = this._buffer.length - available

      if (read) {
        this._outputLength += read

        if (this._outputLength > this._maxOutputLength) {
          throw errors.LIMIT_EXCEEDED(
            `Output length exceeded maxOutputLength of ${this._maxOutputLength} bytes`
          )
        }

        const copy = Buffer.allocUnsafe(read)
        copy.set(this._buffer.subarray(0, read))

        yield copy
      }
    } while (available === 0)
  }

  *flush() {
    let available
    do {
      try {
        available = binding.transform(this._handle, this._finishFlushMode)
      } catch (err) {
        throw errors[err.code](err.message)
      }

      const read = this._buffer.length - available

      if (read) {
        this._outputLength += read

        if (this._outputLength > this._maxOutputLength) {
          throw errors.LIMIT_EXCEEDED(
            `Output length exceeded maxOutputLength of ${this._maxOutputLength} bytes`
          )
        }

        const copy = Buffer.allocUnsafe(read)
        copy.set(this._buffer.subarray(0, read))

        yield copy
      }
    } while (available === 0)

    try {
      binding.end(this._handle)
    } catch (err) {
      throw errors[err.code](err.message)
    }

    this._handle = null
  }
}

class ZlibStream extends Transform {
  constructor(mode, opts = {}) {
    const { flush, ...streamOpts } = opts

    super(streamOpts)

    this._state = new ZlibState(mode, opts)
  }

  async flush(mode = constants.Z_FULL_FLUSH, cb) {
    if (typeof mode === 'function') {
      cb = mode
      mode = constants.Z_FULL_FLUSH
    }

    const previousMode = this._state._flushMode

    this._state._flushMode = mode

    await Writable.drained(this)

    this._state._flushMode = previousMode

    if (cb) cb(null) // For Node.js compatibility
  }

  reset() {
    if (this._state === null) {
      throw errors.STREAM_CLOSED('Stream has already closed')
    }

    this._state.reset()
  }

  _transform(data, encoding, cb) {
    let err = null

    try {
      for (const chunk of this._state.transform(data)) {
        this.push(chunk)
      }
    } catch (e) {
      err = e
    }

    cb(err)
  }

  _flush(cb) {
    let err = null

    try {
      for (const chunk of this._state.flush()) {
        this.push(chunk)
      }
    } catch (e) {
      err = e
    }

    this._state = null

    cb(err)
  }
}

function readAsBuffer(stream, buffer, cb) {
  const chunks = []

  stream.on('data', ondata).on('end', onend).on('error', onerror).end(buffer)

  function ondata(chunk) {
    chunks.push(chunk)
  }

  function onend() {
    cb(null, chunks.length === 1 ? chunks[0] : Buffer.concat(chunks))
  }

  function onerror(err) {
    stream.off('end', onend)
    cb(err)
  }
}

function transformToBuffer(mode, buffer, opts) {
  if (typeof buffer === 'string') buffer = Buffer.from(buffer)

  const state = new ZlibState(mode, opts)
  const chunks = []

  for (const chunk of state.transform(buffer)) {
    chunks.push(chunk)
  }

  for (const chunk of state.flush()) {
    chunks.push(chunk)
  }

  return chunks.length === 1 ? chunks[0] : Buffer.concat(chunks)
}

exports.Deflate = class ZlibDeflateStream extends ZlibStream {
  constructor(opts) {
    super(binding.DEFLATE, opts)
  }
}

exports.createDeflate = function createDeflate(opts) {
  return new exports.Deflate(opts)
}

exports.deflate = function deflate(buffer, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  readAsBuffer(new exports.Deflate(opts), buffer, cb)
}

exports.deflateSync = function deflateSync(buffer, opts) {
  return transformToBuffer(binding.DEFLATE, buffer, opts)
}

exports.Inflate = class ZlibInflateStream extends ZlibStream {
  constructor(opts) {
    super(binding.INFLATE, opts)
  }
}

exports.createInflate = function createInflate(opts) {
  return new exports.Inflate(opts)
}

exports.inflate = function inflate(buffer, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  readAsBuffer(new exports.Inflate(opts), buffer, cb)
}

exports.inflateSync = function inflateSync(buffer, opts) {
  return transformToBuffer(binding.INFLATE, buffer, opts)
}

exports.DeflateRaw = class ZlibDeflateRawStream extends ZlibStream {
  constructor(opts) {
    super(binding.DEFLATE_RAW, opts)
  }
}

exports.createDeflateRaw = function createDeflateRaw(opts) {
  return new exports.DeflateRaw(opts)
}

exports.deflateRaw = function deflateRaw(buffer, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  readAsBuffer(new exports.DeflateRaw(opts), buffer, cb)
}

exports.deflateRawSync = function deflateRawSync(buffer, opts) {
  return transformToBuffer(binding.DEFLATE_RAW, buffer, opts)
}

exports.InflateRaw = class ZlibInflateRawStream extends ZlibStream {
  constructor(opts) {
    super(binding.INFLATE_RAW, opts)
  }
}

exports.createInflateRaw = function createInflateRaw(opts) {
  return new exports.InflateRaw(opts)
}

exports.inflateRaw = function inflateRaw(buffer, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  readAsBuffer(new exports.InflateRaw(opts), buffer, cb)
}

exports.inflateRawSync = function inflateRawSync(buffer, opts) {
  return transformToBuffer(binding.INFLATE_RAW, buffer, opts)
}

exports.Gzip = class ZlibGzipStream extends ZlibStream {
  constructor(opts) {
    super(binding.GZIP, opts)
  }
}

exports.createGzip = function createGzip(opts) {
  return new exports.Gzip(opts)
}

exports.gzip = function gzip(buffer, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  readAsBuffer(new exports.Gzip(opts), buffer, cb)
}

exports.gzipSync = function gzipSync(buffer, opts) {
  return transformToBuffer(binding.GZIP, buffer, opts)
}

exports.Gunzip = class ZlibGunzipStream extends ZlibStream {
  constructor(opts) {
    super(binding.GUNZIP, opts)
  }
}

exports.createGunzip = function createGunzip(opts) {
  return new exports.Gunzip(opts)
}

exports.gunzip = function gunzip(buffer, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  readAsBuffer(new exports.Gunzip(opts), buffer, cb)
}

exports.gunzipSync = function gunzipSync(buffer, opts) {
  return transformToBuffer(binding.GUNZIP, buffer, opts)
}
const binding = require('../binding')

module.exports = binding.constants
module.exports = class ZlibError extends Error {
  constructor(msg, code, fn = ZlibError) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'ZlibError'
  }

  static STREAM_CLOSED(msg) {
    return new ZlibError(msg, 'STREAM_CLOSED', ZlibError.STREAM_CLOSED)
  }

  static STREAM_ERROR(msg) {
    return new ZlibError(msg, 'STREAM_ERROR', ZlibError.STREAM_ERROR)
  }

  static DATA_ERROR(msg) {
    return new ZlibError(msg, 'DATA_ERROR', ZlibError.DATA_ERROR)
  }

  static MEM_ERROR(msg) {
    return new ZlibError(msg, 'MEM_ERROR', ZlibError.MEM_ERROR)
  }

  static BUF_ERROR(msg) {
    return new ZlibError(msg, 'BUF_ERROR', ZlibError.BUF_ERROR)
  }

  static VERSION_ERROR(msg) {
    return new ZlibError(msg, 'VERSION_ERROR', ZlibError.VERSION_ERROR)
  }

  static UNKNOWN_ERROR(msg) {
    return new ZlibError(msg, 'UNKNOWN_ERROR', ZlibError.UNKNOWN_ERROR)
  }

  static LIMIT_EXCEEDED(msg) {
    return new ZlibError(msg, 'LIMIT_EXCEEDED', ZlibError.LIMIT_EXCEEDED)
  }
}
{
  "name": "bare-zlib",
  "version": "1.4.0",
  "description": "Stream-based zlib bindings for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    },
    "./errors": {
      "types": "./lib/errors.d.ts",
      "default": "./lib/errors.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-zlib.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-zlib/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-zlib",
  "dependencies": {
    "bare-stream": "^2.0.0"
  },
  "devDependencies": {
    "bare-fs": "^3.0.0",
    "brittle": "^3.5.0",
    "cmake-bare": "^1.1.7",
    "cmake-fetch": "^1.0.0",
    "lunte": "^1.6.0",
    "prettier": "^3.5.3",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "bare-buffer": "*"
  },
  "peerDependenciesMeta": {
    "bare-buffer": {
      "optional": true
    }
  }
}
const b4a = require('b4a')

module.exports = codecs

codecs.ascii = createString('ascii')
codecs.utf8 = createString('utf-8')
codecs.hex = createString('hex')
codecs.base64 = createString('base64')
codecs.ucs2 = createString('ucs2')
codecs.utf16le = createString('utf16le')
codecs.ndjson = createJSON(true)
codecs.json = createJSON(false)
codecs.binary = {
  name: 'binary',
  encode: function encodeBinary (obj) {
    return typeof obj === 'string'
      ? b4a.from(obj, 'utf-8')
      : b4a.toBuffer(obj)
  },
  decode: function decodeBinary (buf) {
    return b4a.toBuffer(buf)
  }
}

function isCompactEncoding (c) {
  return !!(c.encode && c.decode && c.preencode)
}

function fromCompactEncoding (c) {
  return {
    name: 'compact-encoding',
    encode: function encodeWithCompact (value) {
      const state = { start: 0, end: 0, buffer: null, cache: null }
      c.preencode(state, value)
      state.buffer = b4a.allocUnsafe(state.end)
      c.encode(state, value)
      return state.buffer
    },
    decode: function decodeWithCompact (buffer) {
      return c.decode({ start: 0, end: buffer.byteLength, buffer, cache: null })
    }
  }
}

function codecs (fmt, fallback) {
  if (typeof fmt === 'object' && fmt) {
    return isCompactEncoding(fmt) ? fromCompactEncoding(fmt) : fmt
  }

  switch (fmt) {
    case 'ndjson': return codecs.ndjson
    case 'json': return codecs.json
    case 'ascii': return codecs.ascii
    case 'utf-8':
    case 'utf8': return codecs.utf8
    case 'hex': return codecs.hex
    case 'base64': return codecs.base64
    case 'ucs-2':
    case 'ucs2': return codecs.ucs2
    case 'utf16-le':
    case 'utf16le': return codecs.utf16le
  }

  return fallback !== undefined ? fallback : codecs.binary
}

function createJSON (newline) {
  return {
    name: newline ? 'ndjson' : 'json',
    encode: newline ? encodeNDJSON : encodeJSON,
    decode: function decodeJSON (buf) {
      return JSON.parse(b4a.toString(buf))
    }
  }

  function encodeJSON (val) {
    return b4a.from(JSON.stringify(val))
  }

  function encodeNDJSON (val) {
    return b4a.from(JSON.stringify(val) + '\n')
  }
}

function createString (type) {
  return {
    name: type,
    encode: function encodeString (val) {
      if (typeof val !== 'string') val = val.toString()
      return b4a.from(val, type)
    },
    decode: function decodeString (buf) {
      return b4a.toString(buf, type)
    }
  }
}
{
  "name": "codecs",
  "version": "3.1.0",
  "description": "Create an binary encoder/decoder for json, utf-8 or custom types",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.6.3"
  },
  "devDependencies": {
    "brittle": "^3.2.1",
    "compact-encoding": "^2.11.0",
    "standard": "^17.0.0"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/codecs.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/codecs/issues"
  },
  "homepage": "https://github.com/mafintosh/codecs"
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return uint24.decode(state) + 0x1000000 * uint32.decode(state)
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return uint32.decode(state) + 0x100000000 * uint32.decode(state)
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return 0x100000000 * uint32be.decode(state) + uint32be.decode(state)
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.2.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
module.exports = function debounce (worker, context = null) {
  debounced.running = null
  return debounced

  async function debounced () {
    if (debounced.running !== null) {
      try {
        await debounced.running
      } catch (_) {
        // ignore - do not fail on old errors
      }
    }

    // another "thread" beat us to it, just piggy pack on that one
    if (debounced.running !== null) return debounced.running

    debounced.running = worker.call(context)

    try {
      return await debounced.running
    } finally {
      debounced.running = null
    }
  }
}
{
  "name": "debounceify",
  "version": "1.1.0",
  "description": "Tiny async debouncer",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^16.0.3",
    "tape": "^5.1.1"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/debounceify.git"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/debounceify/issues"
  },
  "homepage": "https://github.com/mafintosh/debounceify"
}
module.exports = require('bare-events')
{
  "name": "events-universal",
  "version": "1.0.1",
  "description": "Universal wrapper for the Node.js events module",
  "exports": {
    "./package": "./package.json",
    ".": {
      "bare": "./bare.js",
      "react-native": "./react-native.js",
      "default": "./default.js"
    }
  },
  "files": [
    "index.js",
    "default.js",
    "bare.js",
    "react-native.js"
  ],
  "scripts": {
    "test": "prettier . --check"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/events-universal.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/events-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/events-universal#readme",
  "dependencies": {
    "bare-events": "^2.7.0"
  },
  "devDependencies": {
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^1.0.0"
  }
}
module.exports = class FixedFIFO {
  constructor (hwm) {
    if (!(hwm > 0) || ((hwm - 1) & hwm) !== 0) throw new Error('Max size for a FixedFIFO should be a power of two')
    this.buffer = new Array(hwm)
    this.mask = hwm - 1
    this.top = 0
    this.btm = 0
    this.next = null
  }

  clear () {
    this.top = this.btm = 0
    this.next = null
    this.buffer.fill(undefined)
  }

  push (data) {
    if (this.buffer[this.top] !== undefined) return false
    this.buffer[this.top] = data
    this.top = (this.top + 1) & this.mask
    return true
  }

  shift () {
    const last = this.buffer[this.btm]
    if (last === undefined) return undefined
    this.buffer[this.btm] = undefined
    this.btm = (this.btm + 1) & this.mask
    return last
  }

  peek () {
    return this.buffer[this.btm]
  }

  isEmpty () {
    return this.buffer[this.btm] === undefined
  }
}
const FixedFIFO = require('./fixed-size')

module.exports = class FastFIFO {
  constructor (hwm) {
    this.hwm = hwm || 16
    this.head = new FixedFIFO(this.hwm)
    this.tail = this.head
    this.length = 0
  }

  clear () {
    this.head = this.tail
    this.head.clear()
    this.length = 0
  }

  push (val) {
    this.length++
    if (!this.head.push(val)) {
      const prev = this.head
      this.head = prev.next = new FixedFIFO(2 * this.head.buffer.length)
      this.head.push(val)
    }
  }

  shift () {
    if (this.length !== 0) this.length--
    const val = this.tail.shift()
    if (val === undefined && this.tail.next) {
      const next = this.tail.next
      this.tail.next = null
      this.tail = next
      return this.tail.shift()
    }

    return val
  }

  peek () {
    const val = this.tail.peek()
    if (val === undefined && this.tail.next) return this.tail.next.peek()
    return val
  }

  isEmpty () {
    return this.length === 0
  }
}
{
  "name": "fast-fifo",
  "version": "1.3.2",
  "description": "A fast fifo implementation similar to the one powering nextTick in Node.js core",
  "main": "index.js",
  "files": [
    "./index.js",
    "./fixed-size.js"
  ],
  "dependencies": {},
  "devDependencies": {
    "standard": "^17.1.0",
    "brittle": "^3.3.2"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/fast-fifo.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/fast-fifo/issues"
  },
  "homepage": "https://github.com/mafintosh/fast-fifo"
}
const codecs = require('codecs')
const { Readable } = require('streamx')
const mutexify = require('mutexify/promise')
const b4a = require('b4a')
const safetyCatch = require('safety-catch')
const ReadyResource = require('ready-resource')
const debounce = require('debounceify')
const Rache = require('rache')
const rrp = require('resolve-reject-promise')

const { all: unslabAll } = require('unslab')

const RangeIterator = require('./iterators/range')
const HistoryIterator = require('./iterators/history')
const DiffIterator = require('./iterators/diff')
const LocalBlockIterator = require('./iterators/local')
const Extension = require('./lib/extension')
const { YoloIndex, Node, Header } = require('./lib/messages')
const { BLOCK_NOT_AVAILABLE, DECODING_ERROR } = require('hypercore-errors')

const T = 5
const MIN_KEYS = T - 1
const MAX_CHILDREN = MIN_KEYS * 2 + 1

const SEP = b4a.alloc(1)
const EMPTY = b4a.alloc(0)

class Key {
  constructor(seq, value) {
    this.seq = seq
    this.value = value
  }
}

class Child {
  constructor(seq, offset, value) {
    this.seq = seq
    this.offset = offset
    this.value = value
  }
}

class Cache {
  constructor(rache) {
    this.keys = rache
    this.length = 0
  }

  get(seq) {
    return this.keys.get(seq) || null
  }

  set(seq, key) {
    this.keys.set(seq, key)
    if (seq >= this.length) this.length = seq + 1
  }

  gc(length) {
    // if we need to "work" more than 128 ticks, just bust the cache...
    if (this.length - length > 128) {
      this.keys.clear()
    } else {
      for (let i = length; i < this.length; i++) {
        this.keys.delete(i)
      }
    }

    this.length = length
  }

  clear() {
    this.keys.clear()
  }
}

class Pointers {
  constructor(decoded) {
    this.levels = decoded.levels.map((l) => {
      const children = []
      const keys = []

      for (let i = 0; i < l.keys.length; i++) {
        keys.push(new Key(l.keys[i], null))
      }

      for (let i = 0; i < l.children.length; i += 2) {
        children.push(new Child(l.children[i], l.children[i + 1], null))
      }

      return { keys, children }
    })
  }

  get(i) {
    return this.levels[i]
  }

  hasKey(seq) {
    for (const lvl of this.levels) {
      for (const key of lvl.keys) {
        if (key.seq === seq) return true
      }
    }
    return false
  }
}

function inflate(entry) {
  if (entry.inflated === null) {
    entry.inflated = YoloIndex.decode(entry.index)
    entry.index = null
  }
  return new Pointers(entry.inflated)
}

function deflate(index) {
  const levels = index.map((l) => {
    const keys = []
    const children = []

    for (let i = 0; i < l.value.keys.length; i++) {
      keys.push(l.value.keys[i].seq)
    }

    for (let i = 0; i < l.value.children.length; i++) {
      children.push(l.value.children[i].seq, l.value.children[i].offset)
    }

    return { keys, children }
  })

  return YoloIndex.encode({ levels })
}

class TreeNode {
  constructor(block, keys, children, offset) {
    this.block = block
    this.offset = offset
    this.keys = keys
    this.children = children
    this.changed = false

    this.preload()
  }

  preload() {
    if (this.block === null) return

    const core = getBackingCore(this.block.tree.core)
    if (!core) return

    const bitfield = core.core.bitfield
    const blocks = []

    for (let i = 0; i < this.keys.length; i++) {
      const k = this.keys[i]
      if (k.value) continue
      if (k.seq >= core.signedLength || (bitfield && bitfield.get(k.seq))) continue
      blocks.push(k.seq)
    }
    for (let i = 0; i < this.children.length; i++) {
      const c = this.children[i]
      if (c.value) continue
      if (c.seq >= core.signedLength || (bitfield && bitfield.get(c.seq))) continue
      blocks.push(c.seq)
    }

    if (blocks.length) core.download({ blocks })
  }

  async insertKey(key, value, child, node, encoding, cas) {
    let s = 0
    let e = this.keys.length
    let c

    while (s < e) {
      const mid = (s + e) >> 1
      c = b4a.compare(key.value, await this.getKey(mid))

      if (c === 0) {
        if (cas) {
          const prev = await this.getKeyNode(mid)
          if (!(await cas(prev.final(encoding), node))) return true
        }
        if (!this.block.tree.tree.alwaysDuplicate) {
          const prev = await this.getKeyNode(mid)
          if (sameValue(prev.value, value)) return true
        }
        this.changed = true
        this.keys[mid] = key
        return true
      }

      if (c < 0) e = mid
      else s = mid + 1
    }

    const i = c < 0 ? e : s
    this.keys.splice(i, 0, key)
    if (child) this.children.splice(i + 1, 0, new Child(0, 0, child))
    this.changed = true

    return this.keys.length < MAX_CHILDREN
  }

  removeKey(index) {
    this.keys.splice(index, 1)
    if (this.children.length) {
      this.children[index + 1].seq = 0 // mark as freed
      this.children.splice(index + 1, 1)
    }
    this.changed = true
  }

  async siblings(parent) {
    for (let i = 0; i < parent.children.length; i++) {
      if (parent.children[i].value === this) {
        const [left, right] = await Promise.all([
          i ? parent.getChildNode(i - 1) : null,
          i < parent.children.length - 1 ? parent.getChildNode(i + 1) : null
        ])
        return { left, index: i, right }
      }
    }

    throw new Error('Bad parent')
  }

  merge(node, median) {
    this.changed = true
    this.keys.push(median)
    for (let i = 0; i < node.keys.length; i++) this.keys.push(node.keys[i])
    for (let i = 0; i < node.children.length; i++) this.children.push(node.children[i])
  }

  async split() {
    const len = this.keys.length >> 1
    const right = TreeNode.create(this.block)

    while (right.keys.length < len) right.keys.push(this.keys.pop())
    right.keys.reverse()

    await this.getKey(this.keys.length - 1) // make sure the median is loaded
    const median = this.keys.pop()

    if (this.children.length) {
      while (right.children.length < len + 1) right.children.push(this.children.pop())
      right.children.reverse()
    }

    this.changed = true

    return {
      left: this,
      median,
      right
    }
  }

  getKeyNode(index) {
    return this.block.tree.getBlock(this.keys[index].seq)
  }

  async getChildNode(index) {
    const child = this.children[index]
    if (child.value) return child.value
    const block =
      child.seq === this.block.seq ? this.block : await this.block.tree.getBlock(child.seq)
    return (child.value = block.getTreeNode(child.offset))
  }

  setKey(index, key) {
    this.keys[index] = key
    this.changed = true
  }

  async getKey(index) {
    const key = this.keys[index]
    if (key.value) return key.value
    const k = key.seq === this.block.seq ? this.block.key : await this.block.tree.getKey(key.seq)
    return (key.value = k)
  }

  indexChanges(index, seq) {
    const offset = index.push(null) - 1
    this.changed = false

    for (const child of this.children) {
      if (!child.value || !child.value.changed) continue
      child.seq = seq
      child.offset = child.value.indexChanges(index, seq)
      index[child.offset] = child
    }

    return offset
  }

  updateChildren(seq, block) {
    for (const child of this.children) {
      if (!child.value || child.seq !== seq) continue
      child.value.block = block
      child.value.updateChildren(seq, block)
    }
  }

  static create(block) {
    const node = new TreeNode(block, [], [], 0)
    node.changed = true
    return node
  }
}

class BlockEntry {
  constructor(seq, tree, entry) {
    this.seq = seq
    this.tree = tree
    this.index = null
    this.entry = entry
    this.key = entry.key
    this.value = entry.value
  }

  isTarget(key) {
    return b4a.equals(this.key, key)
  }

  inflate() {
    if (this.index === null) {
      this.index = inflate(this.entry)
    }
  }

  isDeletion() {
    if (this.value !== null) return false

    if (this.index === null) {
      this.index = inflate(this.entry)
    }

    return !this.index.hasKey(this.seq)
  }

  final(encoding) {
    return {
      seq: this.seq,
      key: encoding.key ? encoding.key.decode(this.key) : this.key,
      value: this.value && (encoding.value ? encoding.value.decode(this.value) : this.value)
    }
  }

  getTreeNode(offset) {
    if (this.index === null) {
      this.index = inflate(this.entry)
    }
    const entry = this.index.get(offset)
    return new TreeNode(this, entry.keys, entry.children, offset)
  }
}

class CacheLock {
  constructor() {
    this.map = new Map()
  }

  enter(seq) {
    const pending = this.map.get(seq)

    if (!pending) {
      this.map.set(seq, [])
      return Promise.resolve()
    }

    const { resolve, promise } = rrp()
    pending.push(resolve)
    return promise
  }

  exit(seq) {
    const pending = this.map.get(seq)
    if (!pending.length) {
      this.map.delete(seq)
      return
    }

    pending.pop()()
  }
}

class BatchEntry extends BlockEntry {
  constructor(seq, tree, key, value, index) {
    super(seq, tree, { key, value, index: null, inflated: null })
    this.pendingIndex = index
  }

  isTarget(key) {
    return false
  }

  getTreeNode(offset) {
    return this.pendingIndex[offset].value
  }
}

class Hyperbee extends ReadyResource {
  constructor(core, opts = {}) {
    super()
    // this.feed is now deprecated, and will be this.core going forward
    this.feed = core
    this.core = core

    this.keyEncoding = opts.keyEncoding ? codecs(opts.keyEncoding) : null
    this.valueEncoding = opts.valueEncoding ? codecs(opts.valueEncoding) : null
    this.extension = opts.extension !== false ? getExtension(this, opts) : null
    this.metadata = opts.metadata || null
    this.lock = opts.lock || mutexify()
    this.sep = opts.sep || SEP
    this.readonly = !!opts.readonly
    this.prefix = opts.prefix || null

    // In a future version, this should be false by default
    this.alwaysDuplicate = opts.alwaysDuplicate !== false

    this._unprefixedKeyEncoding = this.keyEncoding
    this._sub = !!this.prefix
    this._checkout = opts.checkout || 0
    this._view = !!opts._view

    this._onappendBound = this._view ? null : this._onappend.bind(this)
    this._ontruncateBound = this._view ? null : this._ontruncate.bind(this)
    this._watchers = this._onappendBound ? [] : null
    this._entryWatchers = this._onappendBound ? [] : null
    this._sessions = opts.sessions !== false

    this._keyCache = null
    this._nodeCache = null
    this._cacheLock = new CacheLock()

    this._batches = []

    if (this._watchers) {
      this.core.on('append', this._onappendBound)
      this.core.on('truncate', this._ontruncateBound)
    }

    if (this.prefix && opts._sub) {
      this.keyEncoding = prefixEncoding(this.prefix, this.keyEncoding)
    }

    this.ready().catch(safetyCatch)
  }

  async _open() {
    if (this.core.opened === false) await this.core.ready()
    // bump the internal ranges since the nodes are small
    if (this._watchers && this.core.replicator.setInflightRange) {
      this.core.replicator.setInflightRange(256, 512)
    }

    // snapshot
    if (this._checkout === -1) this._checkout = Math.max(1, this.core.length)

    const baseCache = Rache.from(this.core.globalCache)
    this._keyCache = new Cache(baseCache)
    this._nodeCache = new Cache(Rache.from(baseCache))
  }

  get version() {
    return Math.max(1, this._checkout || this.core.length)
  }

  get id() {
    return this.core.id
  }

  get key() {
    return this.core.key
  }

  get discoveryKey() {
    return this.core.discoveryKey
  }

  get writable() {
    return this.core.writable
  }

  get readable() {
    return this.core.readable
  }

  replicate(isInitiator, opts) {
    return this.core.replicate(isInitiator, opts)
  }

  update(opts) {
    return this.core.update(opts)
  }

  peek(range, opts) {
    return iteratorPeek(this.createRangeIterator(range, { ...opts, limit: 1 }))
  }

  createRangeIterator(range, opts = {}) {
    // backwards compat range arg
    opts = opts ? { ...opts, ...range } : range

    const extension = opts.extension === false && opts.limit !== 0 ? null : this.extension
    const keyEncoding = opts.keyEncoding ? codecs(opts.keyEncoding) : this.keyEncoding

    if (extension) {
      const { onseq, onwait } = opts
      let version = 0
      let next = 0

      opts = encRange(keyEncoding, {
        ...opts,
        sub: this._sub,
        onseq(seq) {
          if (!version) version = seq + 1
          if (next) next--
          if (onseq) onseq(seq)
        },
        onwait(seq) {
          if (!next) {
            next = Extension.BATCH_SIZE
            extension.iterator(ite.snapshot(version))
          }
          if (onwait) onwait(seq)
        }
      })
    } else {
      opts = encRange(keyEncoding, { ...opts, sub: this._sub })
    }

    const ite = new RangeIterator(
      new Batch(this, this._makeSnapshot(), null, false, opts),
      null,
      opts
    )
    return ite
  }

  createReadStream(range, opts) {
    const signal = (opts && opts.signal) || null
    return iteratorToStream(this.createRangeIterator(range, opts), signal)
  }

  createHistoryStream(opts) {
    const session = opts && opts.live ? this.core.session() : this._makeSnapshot()
    const signal = (opts && opts.signal) || null
    return iteratorToStream(
      new HistoryIterator(new Batch(this, session, null, false, opts), opts),
      signal
    )
  }

  createDiffStream(right, range, opts) {
    if (typeof right === 'number') right = this.checkout(Math.max(1, right), { reuseSession: true })

    // backwards compat range arg
    opts = opts ? { ...opts, ...range } : range

    const signal = (opts && opts.signal) || null

    const keyEncoding = opts && opts.keyEncoding ? codecs(opts.keyEncoding) : this.keyEncoding
    if (keyEncoding) opts = encRange(keyEncoding, { ...opts, sub: this._sub })

    let done
    let closing
    let ite

    const left = this

    const rs = new Readable({
      signal,
      eagerOpen: true,
      async open(cb) {
        try {
          if (right.opened === false) await right.ready()
          if (left.opened === false) await left.ready()
        } catch (err) {
          cb(err)
          return
        }

        if (closing) {
          cb(null)
          return
        }

        if (left.core.closing || right.core.closing) {
          cb(new Error('Bee closed'))
          return
        }

        const snapshot = right.version > left.version ? right._makeSnapshot() : left._makeSnapshot()

        done = cb
        ite = new DiffIterator(
          new Batch(left, snapshot, null, false, opts),
          new Batch(right, snapshot, null, false, opts),
          opts
        )
        ite.open().then(fin, fin)
      },
      read(cb) {
        done = cb
        ite.next().then(push, fin)
      },
      predestroy() {
        if (!ite) {
          closing = Promise.resolve()
        } else {
          closing = ite.close()
          closing.catch(noop)
        }
      },
      destroy(cb) {
        done = cb
        if (!closing) closing = ite.close()
        closing.then(fin, fin)
      }
    })

    return rs

    function fin(err) {
      done(err)
    }

    function push(val) {
      rs.push(val)
      done(null)
    }
  }

  get(key, opts) {
    const b = new Batch(this, this._makeSnapshot(), null, true, opts)
    return b.get(key)
  }

  getBySeq(seq, opts) {
    const b = new Batch(this, this._makeSnapshot(), null, true, opts)
    return b.getBySeq(seq)
  }

  put(key, value, opts) {
    const b = new Batch(this, this.core, null, true, opts)
    return b.put(key, value, opts)
  }

  batch(opts) {
    return new Batch(this, this.core, mutexify(), true, opts)
  }

  del(key, opts) {
    const b = new Batch(this, this.core, null, true, opts)
    return b.del(key, opts)
  }

  watch(range, opts) {
    if (!this._watchers) throw new Error('Can only watch the main bee instance')
    return new Watcher(this, range, opts)
  }

  async getAndWatch(key, opts) {
    if (!this._watchers) throw new Error('Can only watch the main bee instance')

    const watcher = new EntryWatcher(this, key, opts)
    await watcher._debouncedUpdate()

    if (this.closing) {
      await watcher.close()
      throw new Error('Bee closed')
    }

    return watcher
  }

  _onappend() {
    for (const watcher of this._watchers) {
      watcher._onappend()
    }

    for (const watcher of this._entryWatchers) {
      watcher._onappend()
    }
  }

  _ontruncate(length) {
    for (const watcher of this._watchers) {
      watcher._ontruncate()
    }

    for (const watcher of this._entryWatchers) {
      watcher._ontruncate()
    }

    this._nodeCache.gc(length)
    this._keyCache.gc(length)
  }

  _makeSnapshot() {
    if (this._sessions === false) return this.core
    // TODO: better if we could encapsulate this in hypercore in the future
    return this._checkout <= this.core.length || this._checkout <= 1
      ? this.core.snapshot()
      : this.core.session({ snapshot: false })
  }

  async clearUnlinked(options = {}) {
    await this.ready()

    const { gte = 0, lt = this.version - 1, batchSize = 4096, wait = true } = options
    const checkout = this.version

    let prev = this.batch({ wait: false, checkout: gte })
    let b = this.batch({ wait, checkout })

    const iteBatch = this.batch({ wait: false, checkout })
    const ite = new LocalBlockIterator(iteBatch, { gte, lt })
    await ite.open()

    let ticks = 0

    while (true) {
      const data = await ite.next()
      if (!data) break

      if (!(await isLinked(b, data))) {
        if (b.core.closing || this.core.closing || this.closing) break
        await this.core.clear(data.seq)
      }

      const prevNode = await prev.get(data.key, { finalize: false }).catch(toNull)

      if (prevNode && !(await isLinked(b, prevNode))) {
        if (b.core.closing || this.core.closing || this.closing) break
        await this.core.clear(prevNode.seq)
      }

      if (ticks++ >= batchSize) {
        ticks = 0
        await prev.close()
        await b.close()

        prev = this.batch({ wait: false, checkout: gte })
        b = this.batch({ wait, checkout })
      }
    }

    if (b.core.closing || this.core.closing || this.closing) throw new Error('Core is closed')

    await b.close()
    await prev.close()
    await ite.close()
    await iteBatch.close()

    return lt
  }

  checkout(version, opts = {}) {
    if (version === 0) version = 1

    // same as above, just checkout isn't set yet...
    const snap =
      opts.reuseSession || this._sessions === false
        ? this.core
        : version <= this.core.length || version <= 1
          ? this.core.snapshot()
          : this.core.session({ snapshot: false })

    return new Hyperbee(snap, {
      _view: true,
      _sub: false,
      prefix: this.prefix,
      sep: this.sep,
      lock: this.lock,
      checkout: version,
      keyEncoding: opts.keyEncoding || this.keyEncoding,
      valueEncoding: opts.valueEncoding || this.valueEncoding,
      extension: this.extension !== null ? this.extension : false
    })
  }

  snapshot(opts) {
    return this.checkout(
      this.core.opened === false || this._checkout <= 0 ? -1 : Math.max(1, this.version),
      opts
    )
  }

  sub(prefix, opts = {}) {
    let sep = opts.sep || this.sep
    if (!b4a.isBuffer(sep)) sep = b4a.from(sep)

    prefix = b4a.concat([this.prefix || EMPTY, b4a.from(prefix), sep])

    const valueEncoding = codecs(opts.valueEncoding || this.valueEncoding)
    const keyEncoding = codecs(opts.keyEncoding || this._unprefixedKeyEncoding)

    return new Hyperbee(this.core, {
      _view: true,
      _sub: true,
      prefix,
      sep: this.sep,
      lock: this.lock,
      checkout: this._checkout,
      valueEncoding,
      keyEncoding,
      extension: this.extension !== null ? this.extension : false,
      metadata: this.metadata
    })
  }

  async getHeader(opts) {
    const blk = await this.core.get(0, opts)
    try {
      return blk && Header.decode(blk)
    } catch {
      throw DECODING_ERROR()
    }
  }

  async _close() {
    if (!this._view) {
      if (this._keyCache) this._keyCache.clear()
      if (this._nodeCache) this._nodeCache.clear()
    }

    if (this._watchers) {
      this.core.off('append', this._onappendBound)
      this.core.off('truncate', this._ontruncateBound)

      while (this._watchers.length) {
        await this._watchers[this._watchers.length - 1].close()
      }
    }

    if (this._entryWatchers) {
      while (this._entryWatchers.length) {
        await this._entryWatchers[this._entryWatchers.length - 1].close()
      }
    }

    while (this._batches.length) {
      await this._batches[this._batches.length - 1].close()
    }

    return this.core.close()
  }

  static async isHyperbee(core, opts) {
    await core.ready()

    const blk0 = await core.get(0, opts)
    if (blk0 === null) throw BLOCK_NOT_AVAILABLE()

    try {
      return Header.decode(blk0).protocol === 'hyperbee'
    } catch (err) {
      // undecodable
      return false
    }
  }
}

class Batch {
  constructor(tree, core, batchLock, cache, options = {}) {
    this.tree = tree
    // this.feed is now deprecated, and will be this.core going forward
    this.feed = core
    this.core = core
    this.index = tree._batches.push(this) - 1
    this.blocks = cache ? new Map() : null
    this.autoFlush = !batchLock
    this.maxBlocksCached = options.maxBlocksCached || 128
    this.rootSeq = 0
    this.root = null
    this.length = 0
    this.checkout = options.checkout === undefined ? -1 : options.checkout
    this.options = options
    this.locked = null
    this.batchLock = batchLock
    this.onseq = this.options.onseq || noop
    this.appending = null
    this.isSnapshot = this.core !== this.tree.core
    this.shouldUpdate = this.options.update !== false
    this.updating = null
    this.encoding = {
      key: options.keyEncoding ? codecs(options.keyEncoding) : tree.keyEncoding,
      value: options.valueEncoding ? codecs(options.valueEncoding) : tree.valueEncoding
    }
  }

  async ready() {
    if (this.core.opened === false) await this.core.ready()
    if (this.tree.opened === false) await this.tree.ready()
  }

  async lock() {
    if (this.tree.readonly) throw new Error('Hyperbee is marked as read-only')
    if (this.locked === null) this.locked = await this.tree.lock()
  }

  get version() {
    if (this.checkout !== -1) return Math.max(1, this.checkout)
    return Math.max(1, this.tree._checkout || this.core.length + this.length)
  }

  async getRoot(ensureHeader) {
    await this.ready()
    if (ensureHeader) {
      if (this.core.length === 0 && this.core.writable && !this.tree.readonly) {
        await this.core.append(
          Header.encode({
            protocol: 'hyperbee',
            metadata: this.tree.metadata
          })
        )
      }
    }
    if (this.tree._checkout === 0 && this.checkout === -1 && this.shouldUpdate) {
      if (this.updating === null) this.updating = this.core.update()
      await this.updating
    }
    if (this.version < 2) return null
    return (await this.getBlock(this.version - 1)).getTreeNode(0)
  }

  async getKey(seq) {
    await this.tree._cacheLock.enter(seq)

    try {
      const k = this.core.fork === this.tree.core.fork ? this.tree._keyCache.get(seq) : null
      if (k !== null) return k
      const key = (await this._getBlock(seq)).key
      if (this.core.fork === this.tree.core.fork) this.tree._keyCache.set(seq, key)
      return key
    } finally {
      this.tree._cacheLock.exit(seq)
    }
  }

  async _getNode(seq) {
    const cached =
      this.tree._nodeCache !== null && this.core.fork === this.tree.core.fork
        ? this.tree._nodeCache.get(seq)
        : null
    if (cached !== null) return cached
    const entry = await this.core.get(seq, {
      ...this.options,
      valueEncoding: Node
    })
    if (entry === null) throw BLOCK_NOT_AVAILABLE()
    const wrap = copyEntry(entry)
    if (this.core.fork === this.tree.core.fork && this.tree._nodeCache !== null) {
      this.tree._nodeCache.set(seq, wrap)
    }
    return wrap
  }

  async getBlock(seq) {
    if (this.rootSeq === 0) this.rootSeq = seq
    await this.tree._cacheLock.enter(seq)

    try {
      return await this._getBlock(seq)
    } finally {
      this.tree._cacheLock.exit(seq)
    }
  }

  async _getBlock(seq) {
    let b = this.blocks && this.blocks.get(seq)
    if (b) return b
    this.onseq(seq)
    const entry = await this._getNode(seq)
    b = this.blocks && this.blocks.get(seq)
    if (b) return b
    b = new BlockEntry(seq, this, entry)
    if (this.blocks && this.blocks.size - this.length < this.maxBlocksCached) {
      this.blocks.set(seq, b)
    }
    return b
  }

  _onwait(key) {
    this.options.onwait = null
    this.tree.extension.get(this.rootSeq + 1, key)
  }

  _getEncoding(opts) {
    if (!opts) return this.encoding
    return {
      key: opts.keyEncoding ? codecs(opts.keyEncoding) : this.encoding.key,
      value: opts.valueEncoding ? codecs(opts.valueEncoding) : this.encoding.value
    }
  }

  peek(range, opts) {
    return iteratorPeek(this.createRangeIterator(range, { ...opts, limit: 1 }))
  }

  createRangeIterator(range, opts = {}) {
    // backwards compat range arg
    opts = opts ? { ...opts, ...range } : range

    const encoding = this._getEncoding(opts)
    return new RangeIterator(
      this,
      encoding,
      encRange(encoding.key, { ...opts, sub: this.tree._sub })
    )
  }

  createReadStream(range, opts) {
    const signal = (opts && opts.signal) || null
    return iteratorToStream(this.createRangeIterator(range, opts), signal)
  }

  async getBySeq(seq, opts) {
    const encoding = this._getEncoding(opts)

    try {
      const block = (await this.getBlock(seq)).final(encoding)
      return { key: block.key, value: block.value }
    } finally {
      await this._closeSnapshot()
    }
  }

  async get(key, opts) {
    const encoding = this._getEncoding(opts)
    const finalize = opts ? opts.finalize !== false : true

    try {
      return await this._get(key, encoding, finalize)
    } finally {
      await this._closeSnapshot()
    }
  }

  async _get(key, encoding, finalize) {
    key = enc(encoding.key, key)

    if (this.tree.extension !== null && this.options.extension !== false) {
      this.options.onwait = this._onwait.bind(this, key)
    }

    let node = await this.getRoot(false)
    if (!node) return null

    while (true) {
      if (node.block.isTarget(key)) {
        return node.block.isDeletion() ? null : finalize ? node.block.final(encoding) : node.block
      }

      let s = 0
      let e = node.keys.length
      let c

      while (s < e) {
        const mid = (s + e) >> 1

        c = b4a.compare(key, await node.getKey(mid))

        if (c === 0) {
          const block = await this.getBlock(node.keys[mid].seq)
          return finalize ? block.final(encoding) : block
        }

        if (c < 0) e = mid
        else s = mid + 1
      }

      if (!node.children.length) return null

      const i = c < 0 ? e : s
      node = await node.getChildNode(i)
    }
  }

  async links(key, seq) {
    let node = await this.getRoot(false)
    if (!node) return false

    if (node.block.seq === seq) return true

    while (true) {
      if (node.block.isTarget(key)) return false

      let s = 0
      let e = node.keys.length
      let c

      while (s < e) {
        const mid = (s + e) >> 1

        if (node.keys[mid].seq === seq) return true
        c = b4a.compare(key, await node.getKey(mid))

        if (c === 0) return false

        if (c < 0) e = mid
        else s = mid + 1
      }

      if (!node.children.length) return false

      const i = c < 0 ? e : s
      node = await node.getChildNode(i)
      if (node.block.seq === seq) return true
    }
  }

  async put(key, value, opts) {
    const release = this.batchLock ? await this.batchLock() : null

    const cas = (opts && opts.cas) || null
    const encoding = this._getEncoding(opts)

    if (!this.locked) await this.lock()
    if (!release) return this._put(key, value, encoding, cas)

    try {
      return await this._put(key, value, encoding, cas)
    } finally {
      release()
    }
  }

  async _put(key, value, encoding, cas) {
    const newNode = {
      seq: 0,
      key,
      value
    }
    key = enc(encoding.key, key)
    value = enc(encoding.value, value)

    const stack = []

    let root
    let node = (root = await this.getRoot(true))
    if (!node) node = root = TreeNode.create(null)

    const seq = (newNode.seq = this.core.length + this.length)
    const target = new Key(seq, key)

    while (node.children.length) {
      stack.push(node)
      node.changed = true // changed, but compressible

      let s = 0
      let e = node.keys.length
      let c

      while (s < e) {
        const mid = (s + e) >> 1
        c = b4a.compare(target.value, await node.getKey(mid))

        if (c === 0) {
          if (cas) {
            const prev = await node.getKeyNode(mid)
            if (!(await cas(prev.final(encoding), newNode))) return this._unlockMaybe()
          }
          if (!this.tree.alwaysDuplicate) {
            const prev = await node.getKeyNode(mid)
            if (sameValue(prev.value, value)) return this._unlockMaybe()
          }
          node.setKey(mid, target)
          return this._append(root, seq, key, value)
        }

        if (c < 0) e = mid
        else s = mid + 1
      }

      const i = c < 0 ? e : s
      node = await node.getChildNode(i)
    }

    let needsSplit = !(await node.insertKey(target, value, null, newNode, encoding, cas))
    if (!node.changed) return this._unlockMaybe()

    while (needsSplit) {
      const parent = stack.pop()
      const { median, right } = await node.split()

      if (parent) {
        needsSplit = !(await parent.insertKey(median, value, right, null, encoding, null))
        node = parent
      } else {
        root = TreeNode.create(node.block)
        root.changed = true
        root.keys.push(median)
        root.children.push(new Child(0, 0, node), new Child(0, 0, right))
        needsSplit = false
      }
    }

    return this._append(root, seq, key, value)
  }

  async del(key, opts) {
    const release = this.batchLock ? await this.batchLock() : null
    const cas = (opts && opts.cas) || null
    const encoding = this._getEncoding(opts)

    if (!this.locked) await this.lock()
    if (!release) return this._del(key, encoding, cas)

    try {
      return await this._del(key, encoding, cas)
    } finally {
      release()
    }
  }

  async _del(key, encoding, cas) {
    const delNode = {
      seq: 0,
      key,
      value: null
    }

    key = enc(encoding.key, key)

    const stack = []

    let node = await this.getRoot(true)
    if (!node) return this._unlockMaybe()

    const seq = (delNode.seq = this.core.length + this.length)

    while (true) {
      stack.push(node)

      let s = 0
      let e = node.keys.length
      let c

      while (s < e) {
        const mid = (s + e) >> 1
        c = b4a.compare(key, await node.getKey(mid))

        if (c === 0) {
          if (cas) {
            const prev = await node.getKeyNode(mid)
            if (!(await cas(prev.final(encoding), delNode))) return this._unlockMaybe()
          }
          if (node.children.length) await setKeyToNearestLeaf(node, mid, stack)
          else node.removeKey(mid)
          // we mark these as changed late, so we don't rewrite them if it is a 404
          for (const node of stack) node.changed = true
          return this._append(await rebalance(stack), seq, key, null)
        }

        if (c < 0) e = mid
        else s = mid + 1
      }

      if (!node.children.length) return this._unlockMaybe()

      const i = c < 0 ? e : s
      node = await node.getChildNode(i)
    }
  }

  async _closeSnapshot() {
    if (this.isSnapshot) {
      await this.core.close()
      this._finalize()
    }
  }

  async close() {
    if (this.isSnapshot) return this._closeSnapshot()

    this.root = null
    if (this.blocks) this.blocks.clear()
    this.length = 0
    this._unlock()
  }

  destroy() {
    // compat, remove later
    this.close().catch(noop)
  }

  toBlocks() {
    if (this.appending) return this.appending

    const batch = new Array(this.length)

    for (let i = 0; i < this.length; i++) {
      const seq = this.core.length + i
      const { pendingIndex, key, value } = this.blocks.get(seq)

      if (i < this.length - 1) {
        pendingIndex[0] = null
        let j = 0

        while (j < pendingIndex.length) {
          const idx = pendingIndex[j]
          if (idx !== null && idx.seq === seq) {
            idx.offset = j++
            continue
          }
          if (j === pendingIndex.length - 1) pendingIndex.pop()
          else pendingIndex[j] = pendingIndex.pop()
        }
      }

      batch[i] = Node.encode({
        key,
        value,
        index: deflate(pendingIndex)
      })
    }

    this.appending = batch
    return batch
  }

  flush() {
    if (!this.length) return this.close()

    const batch = this.toBlocks()

    this.root = null
    this.blocks.clear()
    this.length = 0

    return this._appendBatch(batch)
  }

  _unlockMaybe() {
    if (this.autoFlush) this._unlock()
  }

  _unlock() {
    const locked = this.locked
    this.locked = null
    if (locked !== null) locked()
    this._finalize()
  }

  _finalize() {
    // technically finalize can be called more than once, so here we just check if we already have been removed
    if (this.index >= this.tree._batches.length || this.tree._batches[this.index] !== this) return
    const top = this.tree._batches.pop()
    if (top === this) return
    top.index = this.index
    this.tree._batches[top.index] = top
  }

  _append(root, seq, key, value) {
    const index = []
    root.indexChanges(index, seq)
    index[0] = new Child(seq, 0, root)

    if (!this.autoFlush) {
      const block = new BatchEntry(seq, this, key, value, index)
      root.block = block
      this.root = root
      this.length++
      this.blocks.set(seq, block)

      root.updateChildren(seq, block)
      return
    }

    return this._appendBatch(
      Node.encode({
        key,
        value,
        index: deflate(index)
      })
    )
  }

  async _appendBatch(raw) {
    try {
      await this.core.append(raw)
    } finally {
      this._unlock()
    }
  }
}

class EntryWatcher extends ReadyResource {
  constructor(bee, key, opts = {}) {
    super()

    this.keyEncoding = opts.keyEncoding || bee.keyEncoding
    this.valueEncoding = opts.valueEncoding || bee.valueEncoding

    this.index = bee._entryWatchers.push(this) - 1
    this.bee = bee

    this.key = key
    this.node = null

    this._forceUpdate = false
    this._debouncedUpdate = debounce(this._processUpdate.bind(this))
  }

  _close() {
    const top = this.bee._entryWatchers.pop()
    if (top !== this) {
      top.index = this.index
      this.bee._entryWatchers[top.index] = top
    }
  }

  _onappend() {
    this._debouncedUpdate()
  }

  _ontruncate() {
    this._forceUpdate = true
    this._debouncedUpdate()
  }

  async _processUpdate() {
    const force = this._forceUpdate
    this._forceUpdate = false

    let newNode
    try {
      newNode = await this.bee.get(this.key, {
        keyEncoding: this.keyEncoding,
        valueEncoding: this.valueEncoding
      })
    } catch (e) {
      if (e.code === 'SNAPSHOT_NOT_AVAILABLE') {
        // There was a truncate event before the get resolved
        // So this handler will run again anyway
        return
      } else if (this.bee.closing) {
        this.close().catch(safetyCatch)
        return
      }
      this.emit('error', e)
      return
    }

    if (force || newNode?.seq !== this.node?.seq) {
      this.node = newNode
      this.emit('update')
    }
  }
}

class Watcher extends ReadyResource {
  constructor(bee, range, opts = {}) {
    super()

    this.keyEncoding = opts.keyEncoding || bee.keyEncoding
    this.valueEncoding = opts.valueEncoding || bee.valueEncoding
    this.index = bee._watchers.push(this) - 1
    this.bee = bee
    this.core = bee.core

    this.latestDiff = 0
    this.range = range
    this.map = opts.map || defaultWatchMap

    this.current = null
    this.previous = null
    this.currentMapped = null
    this.previousMapped = null
    this.stream = null

    this._lock = mutexify()
    this._flowing = false
    this._resolveOnChange = null
    this._differ = opts.differ || defaultDiffer
    this._eager = !!opts.eager
    this._onchange = opts.onchange || null

    this.on('newListener', autoFlowOnUpdate)

    this.ready().catch(safetyCatch)
  }

  async _consume() {
    if (this._flowing) return
    try {
      for await (const _ of this) {
      } // eslint-disable-line
    } catch {}
  }

  async _open() {
    await this.bee.ready()

    const opts = {
      keyEncoding: this.keyEncoding,
      valueEncoding: this.valueEncoding
    }

    // Point from which to start watching
    this.current = this._eager ? this.bee.checkout(1, opts) : this.bee.snapshot(opts)
    await this.current.ready()

    if (this._onchange) {
      if (this._eager) await this._onchange()
      this._consume()
    }
  }

  [Symbol.asyncIterator]() {
    this._flowing = true
    return this
  }

  _ontruncate() {
    this._onappend()
  }

  _onappend() {
    const resolve = this._resolveOnChange
    this._resolveOnChange = null
    if (resolve) resolve()
  }

  async _waitForChanges() {
    if (this.current.version < this.bee.version || this.closing) return

    await new Promise((resolve) => {
      this._resolveOnChange = resolve
    })
  }

  async next() {
    try {
      return await this._next()
    } catch (err) {
      if (this.closing) return { value: undefined, done: true }
      await this.close()
      throw err
    }
  }

  async _next() {
    const release = await this._lock()

    try {
      if (this.closing) return { value: undefined, done: true }

      if (!this.opened) await this.ready()

      while (true) {
        await this._waitForChanges()

        if (this.closing) return { value: undefined, done: true }

        await this._closePrevious()
        this.previous = this.current.snapshot()

        await this._closeCurrent()
        this.current = this.bee.snapshot({
          keyEncoding: this.keyEncoding,
          valueEncoding: this.valueEncoding
        })

        await this.current.ready()
        await this.previous.ready()

        if (this.current.core.fork !== this.previous.core.fork) {
          return await this._yield()
        }

        this.stream = this._differ(this.current, this.previous, this.range)

        try {
          for await (const data of this.stream) {
            // eslint-disable-line
            return await this._yield()
          }
        } finally {
          this.stream = null
        }
      }
    } finally {
      release()
    }
  }

  async _yield() {
    this.currentMapped = this.map(this.current)
    this.previousMapped = this.map(this.previous)

    if (this._onchange) {
      try {
        await this._onchange()
      } catch (err) {
        safetyCatch(err)
      }
    }

    this.emit('update')
    return { done: false, value: [this.currentMapped, this.previousMapped] }
  }

  async return() {
    await this.close()
    return { done: true }
  }

  async _close() {
    const top = this.bee._watchers.pop()
    if (top !== this) {
      top.index = this.index
      this.bee._watchers[top.index] = top
    }

    if (this.stream && !this.stream.destroying) {
      this.stream.destroy()
    }

    this._onappend() // Continue execution being closed

    await this._closeCurrent().catch(safetyCatch)
    await this._closePrevious().catch(safetyCatch)

    const release = await this._lock()
    release()
  }

  destroy() {
    return this.close()
  }

  async _closeCurrent() {
    if (this.currentMapped) await this.currentMapped.close()
    if (this.current) await this.current.close()
    this.current = this.currentMapped = null
  }

  async _closePrevious() {
    if (this.previousMapped) await this.previousMapped.close()
    if (this.previous) await this.previous.close()
    this.previous = this.previousMapped = null
  }
}

function autoFlowOnUpdate(name) {
  if (name === 'update') this._consume()
}

function defaultWatchMap(snapshot) {
  return snapshot
}

async function leafSize(node, goLeft) {
  while (node.children.length) node = await node.getChildNode(goLeft ? 0 : node.children.length - 1)
  return node.keys.length
}

async function setKeyToNearestLeaf(node, index, stack) {
  let [left, right] = await Promise.all([node.getChildNode(index), node.getChildNode(index + 1)])
  const [ls, rs] = await Promise.all([leafSize(left, false), leafSize(right, true)])

  if (ls < rs) {
    // if fewer leaves on the left
    stack.push(right)
    while (right.children.length) stack.push((right = right.children[0].value))
    node.keys[index] = right.keys.shift()
  } else {
    // if fewer leaves on the right
    stack.push(left)
    while (left.children.length) stack.push((left = left.children[left.children.length - 1].value))
    node.keys[index] = left.keys.pop()
  }
}

async function rebalance(stack) {
  const root = stack[0]

  while (stack.length > 1) {
    const node = stack.pop()
    const parent = stack[stack.length - 1]

    if (node.keys.length >= MIN_KEYS) return root

    let { left, index, right } = await node.siblings(parent)

    // maybe borrow from left sibling?
    if (left && left.keys.length > MIN_KEYS) {
      left.changed = true
      node.keys.unshift(parent.keys[index - 1])
      if (left.children.length) node.children.unshift(left.children.pop())
      parent.keys[index - 1] = left.keys.pop()
      return root
    }

    // maybe borrow from right sibling?
    if (right && right.keys.length > MIN_KEYS) {
      right.changed = true
      node.keys.push(parent.keys[index])
      if (right.children.length) node.children.push(right.children.shift())
      parent.keys[index] = right.keys.shift()
      return root
    }

    // merge node with another sibling
    if (left) {
      index--
      right = node
    } else {
      left = node
    }

    left.merge(right, parent.keys[index])
    parent.removeKey(index)
  }

  // check if the tree shrunk
  if (!root.keys.length && root.children.length) return root.getChildNode(0)
  return root
}

function iteratorToStream(ite, signal) {
  let done
  let closing

  const rs = new Readable({
    signal,
    open(cb) {
      done = cb
      ite.open().then(fin, fin)
    },
    read(cb) {
      done = cb
      ite.next().then(push, fin)
    },
    predestroy() {
      closing = ite.close()
      closing.catch(noop)
    },
    destroy(cb) {
      done = cb
      if (!closing) closing = ite.close()
      closing.then(fin, fin)
    }
  })

  return rs

  function fin(err) {
    done(err)
  }

  function push(val) {
    rs.push(val)
    done(null)
  }
}

async function iteratorPeek(ite) {
  try {
    await ite.open()
    return await ite.next()
  } finally {
    await ite.close()
  }
}

function encRange(e, opts) {
  if (!e) return opts

  if (e.encodeRange) {
    const r = e.encodeRange({
      gt: opts.gt,
      gte: opts.gte,
      lt: opts.lt,
      lte: opts.lte
    })
    opts.gt = r.gt
    opts.gte = r.gte
    opts.lt = r.lt
    opts.lte = r.lte
    return opts
  }

  if (opts.gt !== undefined) opts.gt = enc(e, opts.gt)
  if (opts.gte !== undefined) opts.gte = enc(e, opts.gte)
  if (opts.lt !== undefined) opts.lt = enc(e, opts.lt)
  if (opts.lte !== undefined) opts.lte = enc(e, opts.lte)
  if (opts.sub && !opts.gt && !opts.gte) opts.gt = enc(e, SEP)
  if (opts.sub && !opts.lt && !opts.lte) opts.lt = bump(enc(e, EMPTY))

  return opts
}

function bump(key) {
  // key should have been copied by enc above before hitting this
  key[key.length - 1]++
  return key
}

function enc(e, v) {
  if (v === undefined || v === null) return null
  if (e !== null) return e.encode(v)
  if (typeof v === 'string') return b4a.from(v)
  return v
}

function prefixEncoding(prefix, keyEncoding) {
  return {
    encode(key) {
      return b4a.concat([prefix, b4a.isBuffer(key) ? key : enc(keyEncoding, key)])
    },
    decode(key) {
      const sliced = key.slice(prefix.length, key.length)
      return keyEncoding ? keyEncoding.decode(sliced) : sliced
    }
  }
}

function copyEntry(entry) {
  let key = entry.key
  let value = entry.value
  let index = entry.index

  // key, value and index all refer to the same buffer (one hypercore block)
  // If together they are larger than half the buffer's byteLength,
  // this means that they got their own private slab (see Buffer.allocUnsafe docs)
  // so no need to unslab
  const size =
    key.byteLength +
    (value === null ? 0 : value.byteLength) +
    (index === null ? 0 : index.byteLength)
  if (2 * size < key.buffer.byteLength) {
    const [newKey, newValue, newIndex] = unslabAll([entry.key, entry.value, entry.index])
    key = newKey
    value = newValue
    index = newIndex
  }

  return {
    key,
    value,
    index,
    inflated: null
  }
}

function defaultDiffer(currentSnap, previousSnap, opts) {
  return currentSnap.createDiffStream(previousSnap, opts)
}

function toNull() {
  return null
}

function getBackingCore(core) {
  if (core.core) return core
  if (core.getBackingCore) return core.getBackingCore().session
  return null
}

function sameValue(a, b) {
  return a === b || (a !== null && b !== null && b4a.equals(a, b))
}

function noop() {}

function getExtension(db, opts) {
  if (opts.extension === false) return null
  if (opts.extension && opts.extension !== true) return opts.extension
  return Extension.register(db)
}

async function isLinked(batch, block) {
  const seq = block.seq
  block.inflate()

  const keys = [block.key]
  const wait = batch.options.wait

  for (const l of block.index.levels) {
    if (!l.keys.length) continue
    batch.options.wait = false
    try {
      keys.push(await batch.getKey(l.keys[0].seq))
    } catch {}
    batch.options.wait = wait
  }

  for (const k of keys) {
    if (await batch.links(k, seq)) return true
  }

  if (batch.core.closing) throw new Error('Core is closed')

  return false
}

module.exports = Hyperbee
const b4a = require('b4a')

class SubTree {
  constructor(node, parent) {
    this.node = node
    this.parent = parent

    this.isKey = node.children.length === 0
    this.i = this.isKey ? 1 : 0
    this.n = 0

    const child = this.isKey ? null : this.node.children[0]
    this.seq = child !== null ? child.seq : this.node.keys[0].seq
    this.offset = child !== null ? child.offset : 0
  }

  next() {
    this.i++
    this.isKey = (this.i & 1) === 1
    if (!this.isKey && !this.node.children.length) this.i++
    return this.update()
  }

  async bisect(key, incl) {
    let s = 0
    let e = this.node.keys.length
    let c

    while (s < e) {
      const mid = (s + e) >> 1
      c = cmp(key, await this.node.getKey(mid))

      if (c === 0) {
        if (incl) this.i = mid * 2 + 1
        else this.i = mid * 2 + (this.node.children.length ? 2 : 3)
        return true
      }

      if (c < 0) e = mid
      else s = mid + 1
    }

    const i = c < 0 ? e : s
    this.i = 2 * i + (this.node.children.length ? 0 : 1)
    return this.node.children.length === 0
  }

  update() {
    this.isKey = (this.i & 1) === 1
    this.n = this.i >> 1
    if (this.n >= (this.isKey ? this.node.keys.length : this.node.children.length)) return false
    const child = this.isKey ? null : this.node.children[this.n]
    this.seq = child !== null ? child.seq : this.node.keys[this.n].seq
    this.offset = child !== null ? child.offset : 0
    return true
  }

  async key() {
    return this.n < this.node.keys.length
      ? this.node.getKey(this.n)
      : this.parent && this.parent.key()
  }

  async compare(tree) {
    const [a, b] = await Promise.all([this.key(), tree.key()])
    return cmp(a, b)
  }
}

class TreeIterator {
  constructor(batch, opts) {
    this.batch = batch
    this.stack = []
    this.lt = opts.lt || opts.lte || null
    this.lte = !!opts.lte
    this.gt = opts.gt || opts.gte || null
    this.gte = !!opts.gte
    this.seeking = !!this.gt
    this.encoding = opts.encoding || batch.encoding
  }

  async open() {
    const node = await this.batch.getRoot(false)
    if (!node || !node.keys.length) return
    const tree = new SubTree(node, null)
    if (this.seeking && !(await this._seek(tree))) return
    this.stack.push(tree)
  }

  async _seek(tree) {
    const done = await tree.bisect(this.gt, this.gte)
    const oob = !tree.update()
    if (done || oob) {
      this.seeking = false
      if (oob) return false
    }
    return true
  }

  peek() {
    if (!this.stack.length) return null
    return this.stack[this.stack.length - 1]
  }

  skip() {
    if (!this.stack.length) return
    if (!this.stack[this.stack.length - 1].next()) this.stack.pop()
  }

  async nextKey() {
    let n = null
    while (this.stack.length && n === null) n = await this.next()
    if (n === null) return null
    if (!this.lt) return n.final(this.encoding)

    const c = cmp(n.key, this.lt)
    if (this.lte ? c <= 0 : c < 0) return n.final(this.encoding)
    this.stack = []
    return null
  }

  async next() {
    if (!this.stack.length) return null

    const top = this.stack[this.stack.length - 1]
    const { isKey, n, seq } = top

    if (!top.next()) {
      this.stack.pop()
    }

    if (isKey) {
      this.seeking = false
      return this.batch.getBlock(seq)
    }

    const child = await top.node.getChildNode(n)
    top.node.children[n] = null // unlink to save memory
    const tree = new SubTree(child, top)
    if (this.seeking && !(await this._seek(tree))) return null
    this.stack.push(tree)

    return null
  }

  close() {
    return this.batch._closeSnapshot()
  }
}

module.exports = class DiffIterator {
  constructor(left, right, opts = {}) {
    this.left = new TreeIterator(left, opts)
    this.right = new TreeIterator(right, opts)
    this.limit = typeof opts.limit === 'number' ? opts.limit : -1
  }

  async open() {
    await Promise.all([this.left.open(), this.right.open()])
  }

  async next() {
    if (this.limit === 0) return null
    const res = await this._next()
    if (!res || (res.left === null && res.right === null)) return null
    this.limit--
    return res
  }

  async _next() {
    const a = this.left
    const b = this.right

    while (true) {
      const [l, r] = await Promise.all([a.peek(), b.peek()])

      if (!l && !r) return null
      if (!l) return { left: null, right: await b.nextKey() }
      if (!r) return { left: await a.nextKey(), right: null }

      if (l.seq === r.seq && l.isKey === r.isKey && l.offset === r.offset) {
        a.skip()
        b.skip()
        continue
      }

      const c = await l.compare(r)

      if (l.isKey && !r.isKey) {
        await b.next()
        continue
      }

      if (!l.isKey && r.isKey) {
        await a.next()
        continue
      }

      if (l.isKey && r.isKey) {
        if (c === 0) return { left: await a.nextKey(), right: await b.nextKey() }
        if (c < 0) return { left: await a.nextKey(), right: null }
        return { left: null, right: await b.nextKey() }
      }

      if (c === 0) await Promise.all([a.next(), b.next()])
      else if (c < 0) await b.next()
      else await a.next()
    }
  }

  async close() {
    await Promise.all([this.left.close(), this.right.close()])
  }
}

function cmp(a, b) {
  if (!a) return b ? 1 : 0
  if (!b) return a ? -1 : 0
  return b4a.compare(a, b)
}
module.exports = class HistoryIterator {
  constructor(batch, opts = {}) {
    this.batch = batch
    this.options = opts
    this.live = !!opts.live
    this.gte = 0
    this.lt = 0
    this.reverse = !!opts.reverse
    this.limit = typeof opts.limit === 'number' ? opts.limit : -1
    this.encoding = opts.encoding || batch.encoding
    if (this.live && this.reverse) {
      throw new Error('Cannot have both live and reverse enabled')
    }
  }

  async open() {
    await this.batch.getRoot(false) // does the update dance
    this.gte = gte(this.options, this.batch.version)
    this.lt = this.live ? Infinity : lt(this.options, this.batch.version)
  }

  async next() {
    if (this.limit === 0) return null
    if (this.limit > 0) this.limit--

    if (this.gte >= this.lt) return null

    if (this.reverse) {
      if (this.lt <= 1) return null
      return final(await this.batch.getBlock(--this.lt), this.encoding)
    }

    return final(await this.batch.getBlock(this.gte++), this.encoding)
  }

  close() {
    return this.batch._closeSnapshot()
  }
}

function final(node, encoding) {
  const type = node.isDeletion() ? 'del' : 'put'
  return { type, ...node.final(encoding) }
}

function gte(opts, version) {
  if (opts.gt) return (opts.gt < 0 ? opts.gt + version : opts.gt) + 1
  const gte = opts.gte || opts.since || 1
  return gte < 0 ? gte + version : gte
}

function lt(opts, version) {
  if (opts.lte === 0 || opts.lt === 0 || opts.end === 0) return 0
  if (opts.lte) return (opts.lte < 0 ? opts.lte + version : opts.lte) + 1
  const lt = opts.lt || opts.end || version
  return lt < 0 ? lt + version : lt
}
module.exports = class LocalBlocksIterator {
  constructor(batch, opts = {}) {
    this.batch = batch
    this.options = opts
    this.gte = 0
    this.lt = 0
    this.limit = typeof opts.limit === 'number' ? opts.limit : -1
  }

  async open() {
    await this.batch.getRoot(false) // does the update dance
    this.gte = gte(this.options, this.batch.version)
    this.lt = lt(this.options, this.batch.version)
  }

  async next() {
    if (this.limit === 0) return null
    if (this.limit > 0) this.limit--

    while (this.gte < this.lt) {
      try {
        return await this.batch.getBlock(this.gte++)
      } catch {
        continue
      }
    }

    return null
  }

  close() {
    return this.batch._closeSnapshot()
  }
}

function gte(opts, version) {
  if (opts.gt) return (opts.gt < 0 ? opts.gt + version : opts.gt) + 1
  const gte = opts.gte || opts.since || 1
  return gte < 0 ? gte + version : gte
}

function lt(opts, version) {
  if (opts.lte === 0 || opts.lt === 0 || opts.end === 0) return 0
  if (opts.lte) return (opts.lte < 0 ? opts.lte + version : opts.lte) + 1
  const lt = opts.lt || opts.end || version
  return lt < 0 ? lt + version : lt
}
const b4a = require('b4a')

module.exports = class RangeIterator {
  constructor(batch, encoding, opts = {}) {
    this.batch = batch
    this.stack = []
    this.opened = false
    this.encoding = encoding || batch.encoding

    this._limit = typeof opts.limit === 'number' ? opts.limit : -1
    this._gIncl = !opts.gt
    this._gKey = opts.gt || opts.gte || null
    this._lIncl = !opts.lt
    this._lKey = opts.lt || opts.lte || null
    this._reverse = !!opts.reverse
    this._version = 0
    this._checkpoint = opts.checkpoint && opts.checkpoint.length ? opts.checkpoint : null
    this._nexting = false
    this._closed = false
  }

  snapshot(version = this.batch.version) {
    const checkpoint = []
    for (const s of this.stack) {
      let { node, i } = s
      if (this._nexting && s === this.stack[this.stack.length - 1]) {
        i = this._reverse ? i + 1 : i - 1
      }
      if (!node.block) continue
      if (i < 0) continue
      checkpoint.push(node.block.seq, node.offset, i)
    }

    return {
      version,
      gte: this._gIncl ? this._gKey : null,
      gt: this._gIncl ? null : this._gKey,
      lte: this._lIncl ? this._lKey : null,
      lt: this._lIncl ? null : this._lKey,
      limit: this._limit,
      reverse: this._reverse,
      ended: this.opened && !checkpoint.length,
      checkpoint: this.opened ? checkpoint : []
    }
  }

  async open() {
    await this._open()
    this.opened = true
  }

  async _open() {
    if (this._checkpoint) {
      for (let j = 0; j < this._checkpoint.length; j += 3) {
        const seq = this._checkpoint[j]
        const offset = this._checkpoint[j + 1]
        const i = this._checkpoint[j + 2]
        this.stack.push({
          node: (await this.batch.getBlock(seq)).getTreeNode(offset),
          i
        })
      }
      return
    }

    this._nexting = true

    let node = await this.batch.getRoot(false)
    if (!node) {
      this._nexting = false
      return
    }

    const incl = this._reverse ? this._lIncl : this._gIncl
    const start = this._reverse ? this._lKey : this._gKey

    if (!start) {
      this.stack.push({ node, i: this._reverse ? node.keys.length << 1 : 0 })
      this._nexting = false
      this._preloadQuery()
      return
    }

    while (true) {
      const entry = { node, i: this._reverse ? node.keys.length << 1 : 0 }

      let s = 0
      let e = node.keys.length
      let c

      while (s < e) {
        const mid = (s + e) >> 1
        c = b4a.compare(start, await node.getKey(mid))

        if (c === 0) {
          if (incl) entry.i = mid * 2 + 1
          else entry.i = mid * 2 + (this._reverse ? 0 : 2)
          this.stack.push(entry)
          this._nexting = false
          this._preloadQuery()
          return
        }

        if (c < 0) e = mid
        else s = mid + 1
      }

      const i = c < 0 ? e : s
      entry.i = 2 * i + (this._reverse ? -1 : 1)

      if (entry.i >= 0 && entry.i <= node.keys.length << 1) this.stack.push(entry)
      if (!node.children.length) {
        this._nexting = false
        this._preloadQuery()
        return
      }

      node = await node.getChildNode(i)
    }
  }

  _preloadQuery() {
    const max = { nodes: 0, max: 2048 }

    if (this._limit === -1 && !this._reverse && this.stack.length) {
      for (const s of this.stack) {
        const k = (s.i - (s.i & 1)) / 2
        this._preload(s.node, k + 1, this._lKey, max).catch(noop)
      }
    }
  }

  async _preload(node, i, end, max) {
    for (; i < node.keys.length; i++) {
      const key = node.keys[i]
      const block = await this.batch.getBlock(key.seq)
      if (this._closed) return
      const c = end ? b4a.compare(block.key, end) : -1
      if (c >= 0 || max.nodes >= max.max || i >= node.children.length) return
      max.nodes++
      const next = await node.getChildNode(i)
      if (this._closed) return
      this._preload(next, 0, end, max).catch(noop)
    }

    if (node.children.length && max.nodes < max.max) {
      const next = await node.getChildNode(node.children.length - 1)
      if (this._closed) return
      this._preload(next, 0, end, max).catch(noop)
    }
  }

  async next() {
    // TODO: this nexting flag is only needed if someone asks for a snapshot during
    // a lookup (ie the extension, pretty important...).
    // A better solution would be to refactor this so top.i is incremented eagerly
    // to get the current block instead of the way it is done now (++i vs i++)
    this._nexting = true

    const end = this._reverse ? this._gKey : this._lKey
    const incl = this._reverse ? this._gIncl : this._lIncl

    while (this.stack.length && (this._limit === -1 || this._limit > 0)) {
      const top = this.stack[this.stack.length - 1]
      const isKey = (top.i & 1) === 1
      const n = this._reverse ? (top.i < 0 ? top.node.keys.length : top.i-- >> 1) : top.i++ >> 1

      if (!isKey) {
        if (!top.node.children.length) continue
        const node = await top.node.getChildNode(n)
        if (top.node.block.seq < this.batch.core.length) {
          top.node.children[n].value = null // unlink it to save memory
        }
        this.stack.push({ i: this._reverse ? node.keys.length << 1 : 0, node })
        continue
      }

      if (n >= top.node.keys.length) {
        this.stack.pop()
        continue
      }

      const key = top.node.keys[n]
      const block = await this.batch.getBlock(key.seq)
      if (end) {
        const c = b4a.compare(block.key, end)
        if (c === 0 ? !incl : this._reverse ? c < 0 : c > 0) {
          this._limit = 0
          break
        }
      }
      if (this._limit > 0) this._limit--
      this._nexting = false
      return block.final(this.encoding)
    }

    this._nexting = false
    return null
  }

  close() {
    this._closed = true
    return this.batch._closeSnapshot()
  }
}

function noop() {}
const { Extension } = require('./messages')

// const MAX_ACTIVE = 32
const FLUSH_BATCH = 128
const MAX_PASSIVE_BATCH = 2048
const MAX_ACTIVE_BATCH = MAX_PASSIVE_BATCH + FLUSH_BATCH

class Batch {
  constructor(outgoing, from) {
    this.blocks = []
    this.start = 0
    this.end = 0
    this.outgoing = outgoing
    this.from = from
  }

  push(seq) {
    const len = this.blocks.push(seq)
    if (len === 1 || seq < this.start) this.start = seq
    if (len === 1 || seq >= this.end) this.end = seq + 1
    if (len >= FLUSH_BATCH) {
      this.send()
      this.clear()
    }
  }

  send() {
    if (!this.blocks.length) return
    this.outgoing.send(
      Extension.encode({
        cache: { blocks: this.blocks, start: this.start, end: this.end }
      }),
      this.from
    )
  }

  clear() {
    this.start = this.end = 0
    this.blocks = []
  }
}

class HyperbeeExtension {
  constructor(db) {
    this.encoding = null
    this.outgoing = null
    this.db = db
    this.active = 0
  }

  get(version, key) {
    this.outgoing.broadcast(Extension.encode({ get: { version, key } }))
  }

  iterator(snapshot) {
    if (snapshot.ended) return
    if (snapshot.limit === 0) return
    if (snapshot.limit === -1) snapshot.limit = 0
    this.outgoing.broadcast(Extension.encode({ iterator: snapshot }))
  }

  onmessage(buf, from) {
    // TODO: handle max active extension messages
    // this.active++

    const message = decode(buf)
    if (!message) return

    if (message.cache) this.oncache(message.cache, from)
    if (message.get) this.onget(message.get, from)
    if (message.iterator) this.oniterator(message.iterator, from)
  }

  oncache(message, from) {
    if (!message.blocks.length) return
    this.db.core.download(message)
  }

  onget(message, from) {
    if (!message.version || message.version > this.db.version) return

    const b = new Batch(this.outgoing, from)
    const db = this.db.checkout(message.version)

    db.get(message.key, {
      extension: false,
      wait: false,
      update: false,
      onseq
    }).then(done, done)

    function done() {
      db.close().catch(noop)
      b.send()
    }

    function onseq(seq) {
      b.push(seq)
    }
  }

  async oniterator(message, from) {
    if (!message.version || message.version > this.db.version) return

    const b = new Batch(this.outgoing, from)
    const seqs = new Set()

    let skip = message.checkpoint.length
    let work = 0

    const db = this.db.checkout(message.version)
    const ite = db.createRangeIterator({
      ...message,
      wait: false,
      extension: false,
      update: false,
      limit: message.limit === 0 ? -1 : message.limit,
      onseq(seq) {
        if (skip && skip--) return
        if (seqs.has(seq)) return
        work++
        seqs.add(seq)
        b.push(seq)
      }
    })

    try {
      await ite.open()
      // eslint-disable-next-line no-unmodified-loop-condition
      while (work < MAX_ACTIVE_BATCH) {
        if (!(await ite.next())) break
      }
    } catch (_) {
      // do nothing
    } finally {
      ite.close().catch(noop)
      db.close().catch(noop)
      b.send()
    }
  }

  static register(db) {
    const e = new this(db)
    e.outgoing = db.core.registerExtension('hyperbee', e)
    return e
  }
}

HyperbeeExtension.BATCH_SIZE = MAX_PASSIVE_BATCH

module.exports = HyperbeeExtension

function decode(buf) {
  try {
    return Extension.decode(buf)
  } catch (err) {
    return null
  }
}

function noop() {}
// This file is auto generated by the protocol-buffers compiler

/* eslint-disable quotes */
/* eslint-disable indent */
/* eslint-disable no-redeclare */
/* eslint-disable camelcase */
/* eslint-disable no-var */

// Remember to `npm install --save protocol-buffers-encodings`
var encodings = require('protocol-buffers-encodings')
var b4a = require('b4a')
var varint = encodings.varint
var skip = encodings.skip

var YoloIndex = exports.YoloIndex = {
  buffer: true,
  encodingLength: null,
  encode: null,
  decode: null
}

var Header = exports.Header = {
  buffer: true,
  encodingLength: null,
  encode: null,
  decode: null
}

var Node = exports.Node = {
  buffer: true,
  encodingLength: null,
  encode: null,
  decode: null
}

var Extension = exports.Extension = {
  buffer: true,
  encodingLength: null,
  encode: null,
  decode: null
}

defineYoloIndex()
defineHeader()
defineNode()
defineExtension()

function defineYoloIndex () {
  var Level = YoloIndex.Level = {
    buffer: true,
    encodingLength: null,
    encode: null,
    decode: null
  }

  defineLevel()

  function defineLevel () {
    Level.encodingLength = encodingLength
    Level.encode = encode
    Level.decode = decode

    function encodingLength (obj) {
      var length = 0
      if (defined(obj.keys)) {
        var packedLen = 0
        for (var i = 0; i < obj.keys.length; i++) {
          if (!defined(obj.keys[i])) continue
          var len = encodings.varint.encodingLength(obj.keys[i])
          packedLen += len
        }
        if (packedLen) {
          length += 1 + packedLen + varint.encodingLength(packedLen)
        }
      }
      if (defined(obj.children)) {
        var packedLen = 0
        for (var i = 0; i < obj.children.length; i++) {
          if (!defined(obj.children[i])) continue
          var len = encodings.varint.encodingLength(obj.children[i])
          packedLen += len
        }
        if (packedLen) {
          length += 1 + packedLen + varint.encodingLength(packedLen)
        }
      }
      return length
    }

    function encode (obj, buf, offset) {
      if (!offset) offset = 0
      if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
      var oldOffset = offset
      if (defined(obj.keys)) {
        var packedLen = 0
        for (var i = 0; i < obj.keys.length; i++) {
          if (!defined(obj.keys[i])) continue
          packedLen += encodings.varint.encodingLength(obj.keys[i])
        }
        if (packedLen) {
          buf[offset++] = 10
          varint.encode(packedLen, buf, offset)
          offset += varint.encode.bytes
        }
        for (var i = 0; i < obj.keys.length; i++) {
          if (!defined(obj.keys[i])) continue
          encodings.varint.encode(obj.keys[i], buf, offset)
          offset += encodings.varint.encode.bytes
        }
      }
      if (defined(obj.children)) {
        var packedLen = 0
        for (var i = 0; i < obj.children.length; i++) {
          if (!defined(obj.children[i])) continue
          packedLen += encodings.varint.encodingLength(obj.children[i])
        }
        if (packedLen) {
          buf[offset++] = 18
          varint.encode(packedLen, buf, offset)
          offset += varint.encode.bytes
        }
        for (var i = 0; i < obj.children.length; i++) {
          if (!defined(obj.children[i])) continue
          encodings.varint.encode(obj.children[i], buf, offset)
          offset += encodings.varint.encode.bytes
        }
      }
      encode.bytes = offset - oldOffset
      return buf
    }

    function decode (buf, offset, end) {
      if (!offset) offset = 0
      if (!end) end = buf.length
      if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
      var oldOffset = offset
      var obj = {
        keys: [],
        children: []
      }
      while (true) {
        if (end <= offset) {
          decode.bytes = offset - oldOffset
          return obj
        }
        var prefix = varint.decode(buf, offset)
        offset += varint.decode.bytes
        var tag = prefix >> 3
        switch (tag) {
          case 1:
          var packedEnd = varint.decode(buf, offset)
          offset += varint.decode.bytes
          packedEnd += offset
          while (offset < packedEnd) {
            obj.keys.push(encodings.varint.decode(buf, offset))
            offset += encodings.varint.decode.bytes
          }
          break
          case 2:
          var packedEnd = varint.decode(buf, offset)
          offset += varint.decode.bytes
          packedEnd += offset
          while (offset < packedEnd) {
            obj.children.push(encodings.varint.decode(buf, offset))
            offset += encodings.varint.decode.bytes
          }
          break
          default:
          offset = skip(prefix & 7, buf, offset)
        }
      }
    }
  }

  YoloIndex.encodingLength = encodingLength
  YoloIndex.encode = encode
  YoloIndex.decode = decode

  function encodingLength (obj) {
    var length = 0
    if (defined(obj.levels)) {
      for (var i = 0; i < obj.levels.length; i++) {
        if (!defined(obj.levels[i])) continue
        var len = Level.encodingLength(obj.levels[i])
        length += varint.encodingLength(len)
        length += 1 + len
      }
    }
    return length
  }

  function encode (obj, buf, offset) {
    if (!offset) offset = 0
    if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
    var oldOffset = offset
    if (defined(obj.levels)) {
      for (var i = 0; i < obj.levels.length; i++) {
        if (!defined(obj.levels[i])) continue
        buf[offset++] = 10
        varint.encode(Level.encodingLength(obj.levels[i]), buf, offset)
        offset += varint.encode.bytes
        Level.encode(obj.levels[i], buf, offset)
        offset += Level.encode.bytes
      }
    }
    encode.bytes = offset - oldOffset
    return buf
  }

  function decode (buf, offset, end) {
    if (!offset) offset = 0
    if (!end) end = buf.length
    if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
    var oldOffset = offset
    var obj = {
      levels: []
    }
    while (true) {
      if (end <= offset) {
        decode.bytes = offset - oldOffset
        return obj
      }
      var prefix = varint.decode(buf, offset)
      offset += varint.decode.bytes
      var tag = prefix >> 3
      switch (tag) {
        case 1:
        var len = varint.decode(buf, offset)
        offset += varint.decode.bytes
        obj.levels.push(Level.decode(buf, offset, offset + len))
        offset += Level.decode.bytes
        break
        default:
        offset = skip(prefix & 7, buf, offset)
      }
    }
  }
}

function defineHeader () {
  var Metadata = Header.Metadata = {
    buffer: true,
    encodingLength: null,
    encode: null,
    decode: null
  }

  defineMetadata()

  function defineMetadata () {
    Metadata.encodingLength = encodingLength
    Metadata.encode = encode
    Metadata.decode = decode

    function encodingLength (obj) {
      var length = 0
      if (defined(obj.contentFeed)) {
        var len = encodings.bytes.encodingLength(obj.contentFeed)
        length += 1 + len
      }
      if (defined(obj.userData)) {
        var len = encodings.bytes.encodingLength(obj.userData)
        length += 1 + len
      }
      return length
    }

    function encode (obj, buf, offset) {
      if (!offset) offset = 0
      if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
      var oldOffset = offset
      if (defined(obj.contentFeed)) {
        buf[offset++] = 10
        encodings.bytes.encode(obj.contentFeed, buf, offset)
        offset += encodings.bytes.encode.bytes
      }
      if (defined(obj.userData)) {
        buf[offset++] = 18
        encodings.bytes.encode(obj.userData, buf, offset)
        offset += encodings.bytes.encode.bytes
      }
      encode.bytes = offset - oldOffset
      return buf
    }

    function decode (buf, offset, end) {
      if (!offset) offset = 0
      if (!end) end = buf.length
      if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
      var oldOffset = offset
      var obj = {
        contentFeed: null,
        userData: null
      }
      while (true) {
        if (end <= offset) {
          decode.bytes = offset - oldOffset
          return obj
        }
        var prefix = varint.decode(buf, offset)
        offset += varint.decode.bytes
        var tag = prefix >> 3
        switch (tag) {
          case 1:
          obj.contentFeed = encodings.bytes.decode(buf, offset)
          offset += encodings.bytes.decode.bytes
          break
          case 2:
          obj.userData = encodings.bytes.decode(buf, offset)
          offset += encodings.bytes.decode.bytes
          break
          default:
          offset = skip(prefix & 7, buf, offset)
        }
      }
    }
  }

  Header.encodingLength = encodingLength
  Header.encode = encode
  Header.decode = decode

  function encodingLength (obj) {
    var length = 0
    if (!defined(obj.protocol)) throw new Error("protocol is required")
    var len = encodings.string.encodingLength(obj.protocol)
    length += 1 + len
    if (defined(obj.metadata)) {
      var len = Metadata.encodingLength(obj.metadata)
      length += varint.encodingLength(len)
      length += 1 + len
    }
    return length
  }

  function encode (obj, buf, offset) {
    if (!offset) offset = 0
    if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
    var oldOffset = offset
    if (!defined(obj.protocol)) throw new Error("protocol is required")
    buf[offset++] = 10
    encodings.string.encode(obj.protocol, buf, offset)
    offset += encodings.string.encode.bytes
    if (defined(obj.metadata)) {
      buf[offset++] = 18
      varint.encode(Metadata.encodingLength(obj.metadata), buf, offset)
      offset += varint.encode.bytes
      Metadata.encode(obj.metadata, buf, offset)
      offset += Metadata.encode.bytes
    }
    encode.bytes = offset - oldOffset
    return buf
  }

  function decode (buf, offset, end) {
    if (!offset) offset = 0
    if (!end) end = buf.length
    if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
    var oldOffset = offset
    var obj = {
      protocol: "",
      metadata: null
    }
    var found0 = false
    while (true) {
      if (end <= offset) {
        if (!found0) throw new Error("Decoded message is not valid")
        decode.bytes = offset - oldOffset
        return obj
      }
      var prefix = varint.decode(buf, offset)
      offset += varint.decode.bytes
      var tag = prefix >> 3
      switch (tag) {
        case 1:
        obj.protocol = encodings.string.decode(buf, offset)
        offset += encodings.string.decode.bytes
        found0 = true
        break
        case 2:
        var len = varint.decode(buf, offset)
        offset += varint.decode.bytes
        obj.metadata = Metadata.decode(buf, offset, offset + len)
        offset += Metadata.decode.bytes
        break
        default:
        offset = skip(prefix & 7, buf, offset)
      }
    }
  }
}

function defineNode () {
  Node.encodingLength = encodingLength
  Node.encode = encode
  Node.decode = decode

  function encodingLength (obj) {
    var length = 0
    if (!defined(obj.index)) throw new Error("index is required")
    var len = encodings.bytes.encodingLength(obj.index)
    length += 1 + len
    if (!defined(obj.key)) throw new Error("key is required")
    var len = encodings.bytes.encodingLength(obj.key)
    length += 1 + len
    if (defined(obj.value)) {
      var len = encodings.bytes.encodingLength(obj.value)
      length += 1 + len
    }
    return length
  }

  function encode (obj, buf, offset) {
    if (!offset) offset = 0
    if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
    var oldOffset = offset
    if (!defined(obj.index)) throw new Error("index is required")
    buf[offset++] = 10
    encodings.bytes.encode(obj.index, buf, offset)
    offset += encodings.bytes.encode.bytes
    if (!defined(obj.key)) throw new Error("key is required")
    buf[offset++] = 18
    encodings.bytes.encode(obj.key, buf, offset)
    offset += encodings.bytes.encode.bytes
    if (defined(obj.value)) {
      buf[offset++] = 26
      encodings.bytes.encode(obj.value, buf, offset)
      offset += encodings.bytes.encode.bytes
    }
    encode.bytes = offset - oldOffset
    return buf
  }

  function decode (buf, offset, end) {
    if (!offset) offset = 0
    if (!end) end = buf.length
    if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
    var oldOffset = offset
    var obj = {
      index: null,
      key: null,
      value: null
    }
    var found0 = false
    var found1 = false
    while (true) {
      if (end <= offset) {
        if (!found0 || !found1) throw new Error("Decoded message is not valid")
        decode.bytes = offset - oldOffset
        return obj
      }
      var prefix = varint.decode(buf, offset)
      offset += varint.decode.bytes
      var tag = prefix >> 3
      switch (tag) {
        case 1:
        obj.index = encodings.bytes.decode(buf, offset)
        offset += encodings.bytes.decode.bytes
        found0 = true
        break
        case 2:
        obj.key = encodings.bytes.decode(buf, offset)
        offset += encodings.bytes.decode.bytes
        found1 = true
        break
        case 3:
        obj.value = encodings.bytes.decode(buf, offset)
        offset += encodings.bytes.decode.bytes
        break
        default:
        offset = skip(prefix & 7, buf, offset)
      }
    }
  }
}

function defineExtension () {
  var Get = Extension.Get = {
    buffer: true,
    encodingLength: null,
    encode: null,
    decode: null
  }

  var Iterator = Extension.Iterator = {
    buffer: true,
    encodingLength: null,
    encode: null,
    decode: null
  }

  var Cache = Extension.Cache = {
    buffer: true,
    encodingLength: null,
    encode: null,
    decode: null
  }

  defineGet()
  defineIterator()
  defineCache()

  function defineGet () {
    Get.encodingLength = encodingLength
    Get.encode = encode
    Get.decode = decode

    function encodingLength (obj) {
      var length = 0
      if (defined(obj.version)) {
        var len = encodings.varint.encodingLength(obj.version)
        length += 1 + len
      }
      if (defined(obj.key)) {
        var len = encodings.bytes.encodingLength(obj.key)
        length += 1 + len
      }
      return length
    }

    function encode (obj, buf, offset) {
      if (!offset) offset = 0
      if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
      var oldOffset = offset
      if (defined(obj.version)) {
        buf[offset++] = 8
        encodings.varint.encode(obj.version, buf, offset)
        offset += encodings.varint.encode.bytes
      }
      if (defined(obj.key)) {
        buf[offset++] = 18
        encodings.bytes.encode(obj.key, buf, offset)
        offset += encodings.bytes.encode.bytes
      }
      encode.bytes = offset - oldOffset
      return buf
    }

    function decode (buf, offset, end) {
      if (!offset) offset = 0
      if (!end) end = buf.length
      if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
      var oldOffset = offset
      var obj = {
        version: 0,
        key: null
      }
      while (true) {
        if (end <= offset) {
          decode.bytes = offset - oldOffset
          return obj
        }
        var prefix = varint.decode(buf, offset)
        offset += varint.decode.bytes
        var tag = prefix >> 3
        switch (tag) {
          case 1:
          obj.version = encodings.varint.decode(buf, offset)
          offset += encodings.varint.decode.bytes
          break
          case 2:
          obj.key = encodings.bytes.decode(buf, offset)
          offset += encodings.bytes.decode.bytes
          break
          default:
          offset = skip(prefix & 7, buf, offset)
        }
      }
    }
  }

  function defineIterator () {
    Iterator.encodingLength = encodingLength
    Iterator.encode = encode
    Iterator.decode = decode

    function encodingLength (obj) {
      var length = 0
      if (defined(obj.version)) {
        var len = encodings.varint.encodingLength(obj.version)
        length += 1 + len
      }
      if (defined(obj.gte)) {
        var len = encodings.bytes.encodingLength(obj.gte)
        length += 1 + len
      }
      if (defined(obj.gt)) {
        var len = encodings.bytes.encodingLength(obj.gt)
        length += 1 + len
      }
      if (defined(obj.lte)) {
        var len = encodings.bytes.encodingLength(obj.lte)
        length += 1 + len
      }
      if (defined(obj.lt)) {
        var len = encodings.bytes.encodingLength(obj.lt)
        length += 1 + len
      }
      if (defined(obj.limit)) {
        var len = encodings.varint.encodingLength(obj.limit)
        length += 1 + len
      }
      if (defined(obj.reverse)) {
        var len = encodings.bool.encodingLength(obj.reverse)
        length += 1 + len
      }
      if (defined(obj.checkpoint)) {
        var packedLen = 0
        for (var i = 0; i < obj.checkpoint.length; i++) {
          if (!defined(obj.checkpoint[i])) continue
          var len = encodings.varint.encodingLength(obj.checkpoint[i])
          packedLen += len
        }
        if (packedLen) {
          length += 1 + packedLen + varint.encodingLength(packedLen)
        }
      }
      return length
    }

    function encode (obj, buf, offset) {
      if (!offset) offset = 0
      if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
      var oldOffset = offset
      if (defined(obj.version)) {
        buf[offset++] = 8
        encodings.varint.encode(obj.version, buf, offset)
        offset += encodings.varint.encode.bytes
      }
      if (defined(obj.gte)) {
        buf[offset++] = 18
        encodings.bytes.encode(obj.gte, buf, offset)
        offset += encodings.bytes.encode.bytes
      }
      if (defined(obj.gt)) {
        buf[offset++] = 26
        encodings.bytes.encode(obj.gt, buf, offset)
        offset += encodings.bytes.encode.bytes
      }
      if (defined(obj.lte)) {
        buf[offset++] = 34
        encodings.bytes.encode(obj.lte, buf, offset)
        offset += encodings.bytes.encode.bytes
      }
      if (defined(obj.lt)) {
        buf[offset++] = 42
        encodings.bytes.encode(obj.lt, buf, offset)
        offset += encodings.bytes.encode.bytes
      }
      if (defined(obj.limit)) {
        buf[offset++] = 48
        encodings.varint.encode(obj.limit, buf, offset)
        offset += encodings.varint.encode.bytes
      }
      if (defined(obj.reverse)) {
        buf[offset++] = 56
        encodings.bool.encode(obj.reverse, buf, offset)
        offset += encodings.bool.encode.bytes
      }
      if (defined(obj.checkpoint)) {
        var packedLen = 0
        for (var i = 0; i < obj.checkpoint.length; i++) {
          if (!defined(obj.checkpoint[i])) continue
          packedLen += encodings.varint.encodingLength(obj.checkpoint[i])
        }
        if (packedLen) {
          buf[offset++] = 66
          varint.encode(packedLen, buf, offset)
          offset += varint.encode.bytes
        }
        for (var i = 0; i < obj.checkpoint.length; i++) {
          if (!defined(obj.checkpoint[i])) continue
          encodings.varint.encode(obj.checkpoint[i], buf, offset)
          offset += encodings.varint.encode.bytes
        }
      }
      encode.bytes = offset - oldOffset
      return buf
    }

    function decode (buf, offset, end) {
      if (!offset) offset = 0
      if (!end) end = buf.length
      if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
      var oldOffset = offset
      var obj = {
        version: 0,
        gte: null,
        gt: null,
        lte: null,
        lt: null,
        limit: 0,
        reverse: false,
        checkpoint: []
      }
      while (true) {
        if (end <= offset) {
          decode.bytes = offset - oldOffset
          return obj
        }
        var prefix = varint.decode(buf, offset)
        offset += varint.decode.bytes
        var tag = prefix >> 3
        switch (tag) {
          case 1:
          obj.version = encodings.varint.decode(buf, offset)
          offset += encodings.varint.decode.bytes
          break
          case 2:
          obj.gte = encodings.bytes.decode(buf, offset)
          offset += encodings.bytes.decode.bytes
          break
          case 3:
          obj.gt = encodings.bytes.decode(buf, offset)
          offset += encodings.bytes.decode.bytes
          break
          case 4:
          obj.lte = encodings.bytes.decode(buf, offset)
          offset += encodings.bytes.decode.bytes
          break
          case 5:
          obj.lt = encodings.bytes.decode(buf, offset)
          offset += encodings.bytes.decode.bytes
          break
          case 6:
          obj.limit = encodings.varint.decode(buf, offset)
          offset += encodings.varint.decode.bytes
          break
          case 7:
          obj.reverse = encodings.bool.decode(buf, offset)
          offset += encodings.bool.decode.bytes
          break
          case 8:
          var packedEnd = varint.decode(buf, offset)
          offset += varint.decode.bytes
          packedEnd += offset
          while (offset < packedEnd) {
            obj.checkpoint.push(encodings.varint.decode(buf, offset))
            offset += encodings.varint.decode.bytes
          }
          break
          default:
          offset = skip(prefix & 7, buf, offset)
        }
      }
    }
  }

  function defineCache () {
    Cache.encodingLength = encodingLength
    Cache.encode = encode
    Cache.decode = decode

    function encodingLength (obj) {
      var length = 0
      if (!defined(obj.start)) throw new Error("start is required")
      var len = encodings.varint.encodingLength(obj.start)
      length += 1 + len
      if (!defined(obj.end)) throw new Error("end is required")
      var len = encodings.varint.encodingLength(obj.end)
      length += 1 + len
      if (defined(obj.blocks)) {
        var packedLen = 0
        for (var i = 0; i < obj.blocks.length; i++) {
          if (!defined(obj.blocks[i])) continue
          var len = encodings.varint.encodingLength(obj.blocks[i])
          packedLen += len
        }
        if (packedLen) {
          length += 1 + packedLen + varint.encodingLength(packedLen)
        }
      }
      return length
    }

    function encode (obj, buf, offset) {
      if (!offset) offset = 0
      if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
      var oldOffset = offset
      if (!defined(obj.start)) throw new Error("start is required")
      buf[offset++] = 8
      encodings.varint.encode(obj.start, buf, offset)
      offset += encodings.varint.encode.bytes
      if (!defined(obj.end)) throw new Error("end is required")
      buf[offset++] = 16
      encodings.varint.encode(obj.end, buf, offset)
      offset += encodings.varint.encode.bytes
      if (defined(obj.blocks)) {
        var packedLen = 0
        for (var i = 0; i < obj.blocks.length; i++) {
          if (!defined(obj.blocks[i])) continue
          packedLen += encodings.varint.encodingLength(obj.blocks[i])
        }
        if (packedLen) {
          buf[offset++] = 26
          varint.encode(packedLen, buf, offset)
          offset += varint.encode.bytes
        }
        for (var i = 0; i < obj.blocks.length; i++) {
          if (!defined(obj.blocks[i])) continue
          encodings.varint.encode(obj.blocks[i], buf, offset)
          offset += encodings.varint.encode.bytes
        }
      }
      encode.bytes = offset - oldOffset
      return buf
    }

    function decode (buf, offset, end) {
      if (!offset) offset = 0
      if (!end) end = buf.length
      if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
      var oldOffset = offset
      var obj = {
        start: 0,
        end: 0,
        blocks: []
      }
      var found0 = false
      var found1 = false
      while (true) {
        if (end <= offset) {
          if (!found0 || !found1) throw new Error("Decoded message is not valid")
          decode.bytes = offset - oldOffset
          return obj
        }
        var prefix = varint.decode(buf, offset)
        offset += varint.decode.bytes
        var tag = prefix >> 3
        switch (tag) {
          case 1:
          obj.start = encodings.varint.decode(buf, offset)
          offset += encodings.varint.decode.bytes
          found0 = true
          break
          case 2:
          obj.end = encodings.varint.decode(buf, offset)
          offset += encodings.varint.decode.bytes
          found1 = true
          break
          case 3:
          var packedEnd = varint.decode(buf, offset)
          offset += varint.decode.bytes
          packedEnd += offset
          while (offset < packedEnd) {
            obj.blocks.push(encodings.varint.decode(buf, offset))
            offset += encodings.varint.decode.bytes
          }
          break
          default:
          offset = skip(prefix & 7, buf, offset)
        }
      }
    }
  }

  Extension.encodingLength = encodingLength
  Extension.encode = encode
  Extension.decode = decode

  function encodingLength (obj) {
    var length = 0
    if (defined(obj.cache)) {
      var len = Cache.encodingLength(obj.cache)
      length += varint.encodingLength(len)
      length += 1 + len
    }
    if (defined(obj.get)) {
      var len = Get.encodingLength(obj.get)
      length += varint.encodingLength(len)
      length += 1 + len
    }
    if (defined(obj.iterator)) {
      var len = Iterator.encodingLength(obj.iterator)
      length += varint.encodingLength(len)
      length += 1 + len
    }
    return length
  }

  function encode (obj, buf, offset) {
    if (!offset) offset = 0
    if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
    var oldOffset = offset
    if (defined(obj.cache)) {
      buf[offset++] = 10
      varint.encode(Cache.encodingLength(obj.cache), buf, offset)
      offset += varint.encode.bytes
      Cache.encode(obj.cache, buf, offset)
      offset += Cache.encode.bytes
    }
    if (defined(obj.get)) {
      buf[offset++] = 18
      varint.encode(Get.encodingLength(obj.get), buf, offset)
      offset += varint.encode.bytes
      Get.encode(obj.get, buf, offset)
      offset += Get.encode.bytes
    }
    if (defined(obj.iterator)) {
      buf[offset++] = 26
      varint.encode(Iterator.encodingLength(obj.iterator), buf, offset)
      offset += varint.encode.bytes
      Iterator.encode(obj.iterator, buf, offset)
      offset += Iterator.encode.bytes
    }
    encode.bytes = offset - oldOffset
    return buf
  }

  function decode (buf, offset, end) {
    if (!offset) offset = 0
    if (!end) end = buf.length
    if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
    var oldOffset = offset
    var obj = {
      cache: null,
      get: null,
      iterator: null
    }
    while (true) {
      if (end <= offset) {
        decode.bytes = offset - oldOffset
        return obj
      }
      var prefix = varint.decode(buf, offset)
      offset += varint.decode.bytes
      var tag = prefix >> 3
      switch (tag) {
        case 1:
        var len = varint.decode(buf, offset)
        offset += varint.decode.bytes
        obj.cache = Cache.decode(buf, offset, offset + len)
        offset += Cache.decode.bytes
        break
        case 2:
        var len = varint.decode(buf, offset)
        offset += varint.decode.bytes
        obj.get = Get.decode(buf, offset, offset + len)
        offset += Get.decode.bytes
        break
        case 3:
        var len = varint.decode(buf, offset)
        offset += varint.decode.bytes
        obj.iterator = Iterator.decode(buf, offset, offset + len)
        offset += Iterator.decode.bytes
        break
        default:
        offset = skip(prefix & 7, buf, offset)
      }
    }
  }
}

function defined (val) {
  return val !== null && val !== undefined && (typeof val !== 'number' || !isNaN(val))
}
{
  "name": "hyperbee",
  "version": "2.27.3",
  "description": "An append-only B-tree running on a Hypercore.",
  "main": "index.js",
  "files": [
    "index.js",
    "lib/**.js",
    "iterators/**.js"
  ],
  "dependencies": {
    "b4a": "^1.6.0",
    "codecs": "^3.0.0",
    "debounceify": "^1.0.0",
    "hypercore-errors": "^1.0.0",
    "mutexify": "^1.4.0",
    "protocol-buffers-encodings": "^1.2.0",
    "rache": "^1.0.0",
    "ready-resource": "^1.0.0",
    "resolve-reject-promise": "^1.1.0",
    "safety-catch": "^1.0.2",
    "streamx": "^2.12.4",
    "unslab": "^1.2.0"
  },
  "devDependencies": {
    "bare-process": "^4.2.2",
    "brittle": "^3.1.0",
    "hypercore": "^11.0.0",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "protocol-buffers": "^4.2.0",
    "sub-encoder": "^1.0.6",
    "tree-to-string": "^1.1.1"
  },
  "imports": {
    "process": {
      "bare": "bare-process",
      "default": "process"
    }
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test/*.js",
    "test:bare": "brittle-bare test/*.js",
    "protobuf": "protocol-buffers schema.proto -o ./lib/messages.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/hyperbee.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/hyperbee/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperbee"
}
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const b4a = require('b4a')

// https://en.wikipedia.org/wiki/Merkle_tree#Second_preimage_attack
const LEAF_TYPE = b4a.from([0])
const PARENT_TYPE = b4a.from([1])
const ROOT_TYPE = b4a.from([2])

const HYPERCORE = b4a.from('hypercore')

exports.keyPair = function (seed) {
  // key pairs might stay around for a while, so better not to use a default slab to avoid retaining it completely
  const slab = b4a.allocUnsafeSlow(
    sodium.crypto_sign_PUBLICKEYBYTES + sodium.crypto_sign_SECRETKEYBYTES
  )
  const publicKey = slab.subarray(0, sodium.crypto_sign_PUBLICKEYBYTES)
  const secretKey = slab.subarray(sodium.crypto_sign_PUBLICKEYBYTES)

  if (seed) sodium.crypto_sign_seed_keypair(publicKey, secretKey, seed)
  else sodium.crypto_sign_keypair(publicKey, secretKey)

  return {
    publicKey,
    secretKey
  }
}

exports.validateKeyPair = function (keyPair) {
  const pk = b4a.allocUnsafe(sodium.crypto_sign_PUBLICKEYBYTES)
  sodium.crypto_sign_ed25519_sk_to_pk(pk, keyPair.secretKey)
  return b4a.equals(pk, keyPair.publicKey)
}

exports.sign = function (message, secretKey) {
  // Dedicated slab for the signature, to avoid retaining unneeded mem and for security
  const signature = b4a.allocUnsafeSlow(sodium.crypto_sign_BYTES)
  sodium.crypto_sign_detached(signature, message, secretKey)
  return signature
}

exports.verify = function (message, signature, publicKey) {
  if (signature.byteLength !== sodium.crypto_sign_BYTES) return false
  if (publicKey.byteLength !== sodium.crypto_sign_PUBLICKEYBYTES) return false
  return sodium.crypto_sign_verify_detached(signature, message, publicKey)
}

exports.encrypt = function (message, publicKey) {
  const ciphertext = b4a.alloc(message.byteLength + sodium.crypto_box_SEALBYTES)
  sodium.crypto_box_seal(ciphertext, message, publicKey)
  return ciphertext
}

exports.decrypt = function (ciphertext, keyPair) {
  if (ciphertext.byteLength < sodium.crypto_box_SEALBYTES) return null

  const plaintext = b4a.alloc(ciphertext.byteLength - sodium.crypto_box_SEALBYTES)

  if (!sodium.crypto_box_seal_open(plaintext, ciphertext, keyPair.publicKey, keyPair.secretKey)) {
    return null
  }

  return plaintext
}

exports.encryptionKeyPair = function (seed) {
  const publicKey = b4a.alloc(sodium.crypto_box_PUBLICKEYBYTES)
  const secretKey = b4a.alloc(sodium.crypto_box_SECRETKEYBYTES)

  if (seed) {
    sodium.crypto_box_seed_keypair(publicKey, secretKey, seed)
  } else {
    sodium.crypto_box_keypair(publicKey, secretKey)
  }

  return {
    publicKey,
    secretKey
  }
}

exports.data = function (data) {
  const out = b4a.allocUnsafe(32)

  sodium.crypto_generichash_batch(out, [LEAF_TYPE, c.encode(c.uint64, data.byteLength), data])

  return out
}

exports.parent = function (a, b) {
  if (a.index > b.index) {
    const tmp = a
    a = b
    b = tmp
  }

  const out = b4a.allocUnsafe(32)

  sodium.crypto_generichash_batch(out, [
    PARENT_TYPE,
    c.encode(c.uint64, a.size + b.size),
    a.hash,
    b.hash
  ])

  return out
}

exports.tree = function (roots, out) {
  const buffers = new Array(3 * roots.length + 1)
  let j = 0

  buffers[j++] = ROOT_TYPE

  for (let i = 0; i < roots.length; i++) {
    const r = roots[i]
    buffers[j++] = r.hash
    buffers[j++] = c.encode(c.uint64, r.index)
    buffers[j++] = c.encode(c.uint64, r.size)
  }

  if (!out) out = b4a.allocUnsafe(32)
  sodium.crypto_generichash_batch(out, buffers)
  return out
}

exports.hash = function (data, out) {
  if (!out) out = b4a.allocUnsafe(32)
  if (!Array.isArray(data)) data = [data]

  sodium.crypto_generichash_batch(out, data)

  return out
}

exports.randomBytes = function (n) {
  const buf = b4a.allocUnsafe(n)
  sodium.randombytes_buf(buf)
  return buf
}

exports.discoveryKey = function (key) {
  if (!key || key.byteLength !== 32) throw new Error('Must pass a 32 byte buffer')
  // Discovery keys might stay around for a while, so better not to use slab memory (for better gc)
  const digest = b4a.allocUnsafeSlow(32)
  sodium.crypto_generichash(digest, HYPERCORE, key)
  return digest
}

if (sodium.sodium_free) {
  exports.free = function (secureBuf) {
    if (secureBuf.secure) sodium.sodium_free(secureBuf)
  }
} else {
  exports.free = function () {}
}

exports.namespace = function (name, count) {
  const ids = typeof count === 'number' ? range(count) : count

  // Namespaces are long-lived, so better to use a dedicated slab
  const buf = b4a.allocUnsafeSlow(32 * ids.length)

  const list = new Array(ids.length)

  // ns is ephemeral, so default slab
  const ns = b4a.allocUnsafe(33)
  sodium.crypto_generichash(ns.subarray(0, 32), typeof name === 'string' ? b4a.from(name) : name)

  for (let i = 0; i < list.length; i++) {
    list[i] = buf.subarray(32 * i, 32 * i + 32)
    ns[32] = ids[i]
    sodium.crypto_generichash(list[i], ns)
  }

  return list
}

function range(count) {
  const arr = new Array(count)
  for (let i = 0; i < count; i++) arr[i] = i
  return arr
}
{
  "name": "hypercore-crypto",
  "version": "3.7.0",
  "description": "The crypto primitives used in hypercore, extracted into a separate module",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.6.6",
    "compact-encoding": "^3.0.0",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "brittle": "^3.5.0",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/hypercore-crypto.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/hypercore-crypto/issues"
  },
  "homepage": "https://github.com/mafintosh/hypercore-crypto"
}
const IdEnc = require('hypercore-id-encoding')

module.exports = class HypercoreError extends Error {
  constructor (msg, code, fn = HypercoreError, discoveryKey = null) {
    if (discoveryKey) msg = `${msg} (discovery key: ${IdEnc.normalize(discoveryKey)})`
    super(`${code}: ${msg}`)

    this.code = code
    this.discoveryKey = discoveryKey

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name () {
    return 'HypercoreError'
  }

  static ASSERTION (msg, discoveryKey = null) { // ERR_ASSERTION is picked up by safety-catch also
    return new HypercoreError(msg, 'ERR_ASSERTION', HypercoreError.ASSERT, discoveryKey)
  }

  static BAD_ARGUMENT (msg, discoveryKey = null) {
    return new HypercoreError(msg, 'BAD_ARGUMENT', HypercoreError.BAD_ARGUMENT, discoveryKey)
  }

  static STORAGE_EMPTY (msg, discoveryKey = null) {
    return new HypercoreError(msg, 'STORAGE_EMPTY', HypercoreError.STORAGE_EMPTY, discoveryKey)
  }

  static STORAGE_CONFLICT (msg, discoveryKey = null) {
    return new HypercoreError(msg, 'STORAGE_CONFLICT', HypercoreError.STORAGE_CONFLICT, discoveryKey)
  }

  static INVALID_SIGNATURE (msg, discoveryKey = null) {
    return new HypercoreError(msg, 'INVALID_SIGNATURE', HypercoreError.INVALID_SIGNATURE, discoveryKey)
  }

  static INVALID_CAPABILITY (msg, discoveryKey = null) {
    return new HypercoreError(msg, 'INVALID_CAPABILITY', HypercoreError.INVALID_CAPABILITY, discoveryKey)
  }

  static INVALID_CHECKSUM (msg = 'Invalid checksum', discoveryKey = null) {
    return new HypercoreError(msg, 'INVALID_CHECKSUM', HypercoreError.INVALID_CHECKSUM, discoveryKey)
  }

  static INVALID_OPERATION (msg, discoveryKey = null) {
    return new HypercoreError(msg, 'INVALID_OPERATION', HypercoreError.INVALID_OPERATION, discoveryKey)
  }

  static INVALID_PROOF (msg = 'Proof not verifiable', discoveryKey = null) {
    return new HypercoreError(msg, 'INVALID_PROOF', HypercoreError.INVALID_PROOF, discoveryKey)
  }

  static BLOCK_NOT_AVAILABLE (msg = 'Block is not available', discoveryKey = null) {
    return new HypercoreError(msg, 'BLOCK_NOT_AVAILABLE', HypercoreError.BLOCK_NOT_AVAILABLE, discoveryKey)
  }

  static SNAPSHOT_NOT_AVAILABLE (msg = 'Snapshot is not available', discoveryKey = null) {
    return new HypercoreError(msg, 'SNAPSHOT_NOT_AVAILABLE', HypercoreError.SNAPSHOT_NOT_AVAILABLE, discoveryKey)
  }

  static REQUEST_CANCELLED (msg = 'Request was cancelled', discoveryKey = null) {
    return new HypercoreError(msg, 'REQUEST_CANCELLED', HypercoreError.REQUEST_CANCELLED, discoveryKey)
  }

  static REQUEST_TIMEOUT (msg = 'Request timed out', discoveryKey = null) {
    return new HypercoreError(msg, 'REQUEST_TIMEOUT', HypercoreError.REQUEST_TIMEOUT, discoveryKey)
  }

  static SESSION_NOT_WRITABLE (msg = 'Session is not writable', discoveryKey = null) {
    return new HypercoreError(msg, 'SESSION_NOT_WRITABLE', HypercoreError.SESSION_NOT_WRITABLE, discoveryKey)
  }

  static SESSION_CLOSED (msg = 'Session is closed', discoveryKey = null) {
    return new HypercoreError(msg, 'SESSION_CLOSED', HypercoreError.SESSION_CLOSED, discoveryKey)
  }

  static BATCH_UNFLUSHED (msg = 'Batch not yet flushed', discoveryKey = null) {
    return new HypercoreError(msg, 'BATCH_UNFLUSHED', HypercoreError.BATCH_UNFLUSHED, discoveryKey)
  }

  static BATCH_ALREADY_EXISTS (msg = 'Batch already exists', discoveryKey = null) {
    return new HypercoreError(msg, 'BATCH_ALREADY_EXISTS', HypercoreError.BATCH_ALREADY_EXISTS, discoveryKey)
  }

  static BATCH_ALREADY_FLUSHED (msg = 'Batch has already been flushed', discoveryKey = null) {
    return new HypercoreError(msg, 'BATCH_ALREADY_FLUSHED', HypercoreError.BATCH_ALREADY_FLUSHED, discoveryKey)
  }

  static OPLOG_CORRUPT (msg = 'Oplog file appears corrupt or out of date', discoveryKey = null) {
    return new HypercoreError(msg, 'OPLOG_CORRUPT', HypercoreError.OPLOG_CORRUPT, discoveryKey)
  }

  static OPLOG_HEADER_OVERFLOW (msg = 'Oplog header exceeds page size', discoveryKey = null) {
    return new HypercoreError(msg, 'OPLOG_HEADER_OVERFLOW', HypercoreError.OPLOG_HEADER_OVERFLOW, discoveryKey)
  }

  static INVALID_OPLOG_VERSION (msg = 'Invalid header version', discoveryKey = null) {
    return new HypercoreError(msg, 'INVALID_OPLOG_VERSION', HypercoreError.INVALID_OPLOG_VERSION, discoveryKey)
  }

  static WRITE_FAILED (msg = 'Write to storage failed', discoveryKey = null) {
    return new HypercoreError(msg, 'WRITE_FAILED', HypercoreError.WRITE_FAILED, discoveryKey)
  }

  static DECODING_ERROR (msg = 'Decoding error', discoveryKey = null) {
    return new HypercoreError(msg, 'DECODING_ERROR', HypercoreError.DECODING_ERROR, discoveryKey)
  }

  static SESSION_MOVED (msg = 'Session moved', discoveryKey = null) {
    return new HypercoreError(msg, 'SESSION_MOVED', HypercoreError.SESSION_MOVED, discoveryKey)
  }
}
{
  "name": "hypercore-errors",
  "version": "1.5.0",
  "description": "Hypercore errors",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/hypercore-errors.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/hypercore-errors/issues"
  },
  "homepage": "https://github.com/holepunchto/hypercore-errors#readme",
  "devDependencies": {
    "b4a": "^1.6.7",
    "brittle": "^3.1.3",
    "standard": "^17.0.0"
  },
  "dependencies": {
    "hypercore-id-encoding": "^1.3.0"
  }
}
const z32 = require('z32')
const b4a = require('b4a')

module.exports = {
  encode,
  decode,
  normalize,
  isValid
}

function encode (key) {
  if (!b4a.isBuffer(key)) throw new Error('Key must be a Buffer')
  if (key.byteLength !== 32) throw new Error('Key must be 32-bytes long')
  return z32.encode(key)
}

function decode (id) {
  if (b4a.isBuffer(id)) {
    if (id.byteLength !== 32) throw new Error('ID must be 32-bytes long')
    return id
  }
  if (typeof id === 'string') {
    if (id.startsWith('pear://')) id = id.slice(7).split('/')[0]
    if (id.length === 52) return z32.decode(id)
    if (id.length === 64) {
      const buf = b4a.from(id, 'hex')
      if (buf.byteLength === 32) return buf
    }
  }
  throw new Error('Invalid Hypercore key')
}

function normalize (any) {
  return encode(decode(any))
}

function isValid (any) {
  try {
    decode(any)
    return true
  } catch {
    return false
  }
}
{
  "name": "hypercore-id-encoding",
  "version": "1.3.0",
  "description": "Convert Hypercore keys to/from z-base32 or hex",
  "main": "index.js",
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.5.3",
    "z32": "^1.0.0"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "hypercore": "^10.0.0",
    "random-access-memory": "^6.0.0",
    "standard": "^17.1.0"
  },
  "license": "Apache-2.0",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/hypercore-id-encoding.git"
  },
  "keywords": [],
  "author": "",
  "bugs": {
    "url": "https://github.com/holepunchto/hypercore-id-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/hypercore-id-encoding#readme"
}
var queueTick = require('queue-tick')

var mutexify = function () {
  var queue = []
  var used = null

  var call = function () {
    used(release)
  }

  var acquire = function (fn) {
    if (used) return queue.push(fn)
    used = fn
    acquire.locked = true
    queueTick(call)
    return 0
  }

  acquire.locked = false

  var release = function (fn, err, value) {
    used = null
    acquire.locked = false
    if (queue.length) acquire(queue.shift())
    if (fn) fn(err, value)
  }

  return acquire
}

module.exports = mutexify
{
  "name": "mutexify",
  "version": "1.4.0",
  "description": "mutex lock for javascript",
  "main": "index.js",
  "dependencies": {
    "queue-tick": "^1.0.0"
  },
  "devDependencies": {
    "standard": "^14.3.3",
    "tape": "^3.0.2"
  },
  "scripts": {
    "test": "tape test.js",
    "posttest": "npm run lint",
    "lint": "standard"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/mutexify.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/mutexify/issues"
  },
  "keywords": [
    "mutex",
    "lock"
  ],
  "homepage": "https://github.com/mafintosh/mutexify"
}
var mutexify = require('.')

var mutexifyPromise = function () {
  var lock = mutexify()

  var acquire = function () {
    return new Promise(lock)
  }

  Object.defineProperty(acquire, 'locked', {
    get: function () { return lock.locked },
    enumerable: true
  })

  return acquire
}

module.exports = mutexifyPromise
var varint = require('varint')
var svarint = require('signed-varint')
var b4a = require('b4a')

exports.make = encoder

exports.name = function (enc) {
  var keys = Object.keys(exports)
  for (var i = 0; i < keys.length; i++) {
    if (exports[keys[i]] === enc) return keys[i]
  }
  return null
}

exports.skip = function (type, buffer, offset) {
  switch (type) {
    case 0:
      varint.decode(buffer, offset)
      return offset + varint.decode.bytes

    case 1:
      return offset + 8

    case 2:
      var len = varint.decode(buffer, offset)
      return offset + varint.decode.bytes + len

    case 3:
    case 4:
      throw new Error('Groups are not supported')

    case 5:
      return offset + 4
  }

  throw new Error('Unknown wire type: ' + type)
}

exports.bytes = encoder(2,
  function encode (val, buffer, offset) {
    var oldOffset = offset
    var len = bufferLength(val)

    varint.encode(len, buffer, offset)
    offset += varint.encode.bytes

    if (b4a.isBuffer(val)) b4a.copy(val, buffer, offset)
    else b4a.write(buffer, val, offset, len)
    offset += len

    encode.bytes = offset - oldOffset
    return buffer
  },
  function decode (buffer, offset) {
    var oldOffset = offset

    var len = varint.decode(buffer, offset)
    offset += varint.decode.bytes

    var val = buffer.subarray(offset, offset + len)
    offset += val.length

    decode.bytes = offset - oldOffset
    return val
  },
  function encodingLength (val) {
    var len = bufferLength(val)
    return varint.encodingLength(len) + len
  }
)

exports.string = encoder(2,
  function encode (val, buffer, offset) {
    var oldOffset = offset
    var len = b4a.byteLength(val)

    varint.encode(len, buffer, offset, 'utf-8')
    offset += varint.encode.bytes

    b4a.write(buffer, val, offset, len)
    offset += len

    encode.bytes = offset - oldOffset
    return buffer
  },
  function decode (buffer, offset) {
    var oldOffset = offset

    var len = varint.decode(buffer, offset)
    offset += varint.decode.bytes

    var val = b4a.toString(buffer, 'utf-8', offset, offset + len)
    offset += len

    decode.bytes = offset - oldOffset
    return val
  },
  function encodingLength (val) {
    var len = b4a.byteLength(val)
    return varint.encodingLength(len) + len
  }
)

exports.bool = encoder(0,
  function encode (val, buffer, offset) {
    buffer[offset] = val ? 1 : 0
    encode.bytes = 1
    return buffer
  },
  function decode (buffer, offset) {
    var bool = buffer[offset] > 0
    decode.bytes = 1
    return bool
  },
  function encodingLength () {
    return 1
  }
)

exports.int32 = encoder(0,
  function encode (val, buffer, offset) {
    varint.encode(val < 0 ? val + 4294967296 : val, buffer, offset)
    encode.bytes = varint.encode.bytes
    return buffer
  },
  function decode (buffer, offset) {
    var val = varint.decode(buffer, offset)
    decode.bytes = varint.decode.bytes
    return val > 2147483647 ? val - 4294967296 : val
  },
  function encodingLength (val) {
    return varint.encodingLength(val < 0 ? val + 4294967296 : val)
  }
)

exports.int64 = encoder(0,
  function encode (val, buffer, offset) {
    if (val < 0) {
      var last = offset + 9
      varint.encode(val * -1, buffer, offset)
      offset += varint.encode.bytes - 1
      buffer[offset] = buffer[offset] | 0x80
      while (offset < last - 1) {
        offset++
        buffer[offset] = 0xff
      }
      buffer[last] = 0x01
      encode.bytes = 10
    } else {
      varint.encode(val, buffer, offset)
      encode.bytes = varint.encode.bytes
    }
    return buffer
  },
  function decode (buffer, offset) {
    var val = varint.decode(buffer, offset)
    if (val >= Math.pow(2, 63)) {
      var limit = 9
      while (buffer[offset + limit - 1] === 0xff) limit--
      limit = limit || 9
      var subset = b4a.allocUnsafe(limit)
      b4a.copy(buffer, subset, 0, offset, offset + limit)
      subset[limit - 1] = subset[limit - 1] & 0x7f
      val = -1 * varint.decode(subset, 0)
      decode.bytes = 10
    } else {
      decode.bytes = varint.decode.bytes
    }
    return val
  },
  function encodingLength (val) {
    return val < 0 ? 10 : varint.encodingLength(val)
  }
)

exports.sint32 =
exports.sint64 = encoder(0,
  svarint.encode,
  svarint.decode,
  svarint.encodingLength
)

exports.uint32 =
exports.uint64 =
exports.enum =
exports.varint = encoder(0,
  varint.encode,
  varint.decode,
  varint.encodingLength
)

// we cannot represent these in javascript so we just use buffers
exports.fixed64 =
exports.sfixed64 = encoder(1,
  function encode (val, buffer, offset) {
    b4a.copy(val, buffer, offset)
    encode.bytes = 8
    return buffer
  },
  function decode (buffer, offset) {
    var val = buffer.subarray(offset, offset + 8)
    decode.bytes = 8
    return val
  },
  function encodingLength () {
    return 8
  }
)

exports.double = encoder(1,
  function encode (val, buffer, offset) {
    b4a.writeDoubleLE(buffer, val, offset)
    encode.bytes = 8
    return buffer
  },
  function decode (buffer, offset) {
    var val = b4a.readDoubleLE(buffer, offset)
    decode.bytes = 8
    return val
  },
  function encodingLength () {
    return 8
  }
)

exports.fixed32 = encoder(5,
  function encode (val, buffer, offset) {
    b4a.writeUInt32LE(buffer, val, offset)
    encode.bytes = 4
    return buffer
  },
  function decode (buffer, offset) {
    var val = b4a.readUInt32LE(buffer, offset)
    decode.bytes = 4
    return val
  },
  function encodingLength () {
    return 4
  }
)

exports.sfixed32 = encoder(5,
  function encode (val, buffer, offset) {
    b4a.writeInt32LE(buffer, val, offset)
    encode.bytes = 4
    return buffer
  },
  function decode (buffer, offset) {
    var val = b4a.readInt32LE(buffer, offset)
    decode.bytes = 4
    return val
  },
  function encodingLength () {
    return 4
  }
)

exports.float = encoder(5,
  function encode (val, buffer, offset) {
    b4a.writeFloatLE(buffer, val, offset)
    encode.bytes = 4
    return buffer
  },
  function decode (buffer, offset) {
    var val = b4a.readFloatLE(buffer, offset)
    decode.bytes = 4
    return val
  },
  function encodingLength () {
    return 4
  }
)

function encoder (type, encode, decode, encodingLength) {
  encode.bytes = decode.bytes = 0

  return {
    type: type,
    encode: encode,
    decode: decode,
    encodingLength: encodingLength
  }
}

function bufferLength (val) {
  return b4a.isBuffer(val) ? val.length : b4a.byteLength(val)
}
{
  "name": "protocol-buffers-encodings",
  "version": "1.2.0",
  "description": "Base encodings for protocol-buffers",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.6.0",
    "signed-varint": "^2.0.1",
    "varint": "5.0.0"
  },
  "devDependencies": {
    "standard": "^14.3.4",
    "tape": "^5.0.1"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/protocol-buffers-encodings.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/protocol-buffers-encodings/issues"
  },
  "homepage": "https://github.com/mafintosh/protocol-buffers-encodings"
}
{
  "name": "queue-tick",
  "version": "1.0.1",
  "description": "Next tick shim that prefers process.nextTick over queueMicrotask for compat",
  "main": "./process-next-tick.js",
  "browser": "./queue-microtask.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^16.0.3",
    "tape": "^5.3.1"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/queue-tick.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/queue-tick/issues"
  },
  "homepage": "https://github.com/mafintosh/queue-tick"
}
module.exports = (typeof process !== 'undefined' && typeof process.nextTick === 'function')
  ? process.nextTick.bind(process)
  : require('./queue-microtask')
module.exports = typeof queueMicrotask === 'function' ? queueMicrotask : (fn) => Promise.resolve().then(fn)
class CacheEntry {
  constructor (key, index, map) {
    this.key = key
    this.index = index
    this.map = map
  }
}

class CacheValue {
  constructor (entry, value) {
    this.entry = entry
    this.value = value
  }
}

class Rache {
  constructor ({ maxSize = 65536, parent = null } = {}) {
    this.maxSize = parent?.maxSize || maxSize

    this._array = parent?._array || []
    this._map = new Map()
  }

  static from (cache) {
    return cache ? new this({ parent: cache }) : new this()
  }

  get globalSize () {
    return this._array.length
  }

  get size () {
    return this._map.size
  }

  sub () {
    return new Rache({ parent: this })
  }

  set (key, value) { // ~constant time
    const existing = this._map.get(key)
    if (existing !== undefined) {
      existing.value = value
      return
    }

    if (this._array.length >= this.maxSize) this._gc()

    const entry = new CacheEntry(key, this._array.length, this._map)
    this._array.push(entry)
    const cacheValue = new CacheValue(entry, value)
    this._map.set(key, cacheValue)
  }

  delete (key) {
    const existing = this._map.get(key)
    if (existing === undefined) return false

    this._delete(existing.entry.index)
    return true
  }

  get (key) {
    const existing = this._map.get(key)
    return existing === undefined ? undefined : existing.value
  }

  * [Symbol.iterator] () {
    for (const [key, { value }] of this._map) {
      yield [key, value]
    }
  }

  keys () {
    return this._map.keys()
  }

  * values () {
    for (const { value } of this._map.values()) {
      yield value
    }
  }

  clear () {
    // The entries in map linger on in _array,
    // so on top of clearing the map, we also kill the ref,
    // so that any gc running later on the old map won't interfere
    // (in case a new entry was added with the same key as a cleared entry)

    this._map.clear()
    this._map = new Map()
  }

  destroy () {
    this._map = null
    this._array = null
  }

  _gc () {
    this._delete(Math.floor(Math.random() * this._array.length))
  }

  _delete (index) { // ~constant time
    if (index >= this._array.length) throw new Error('Cannot delete unused index (logic bug?)')

    const head = this._array.pop()
    let removed = head

    if (index < this._array.length) {
      removed = this._array[index]
      head.index = index
      this._array[index] = head
    }

    removed.map.delete(removed.key)
  }
}

module.exports = Rache
{
  "name": "rache",
  "version": "1.0.0",
  "description": "Random-eviction cache",
  "main": "index.js",
  "scripts": {
    "test": "standard && brittle test.js --coverage"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/rache.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/rache/issues"
  },
  "homepage": "https://github.com/holepunchto/rache#readme",
  "files": [
    "index.js"
  ],
  "dependencies": {},
  "devDependencies": {
    "brittle": "^3.5.2",
    "standard": "^17.1.0"
  }
}
const EventEmitter = require('events')

module.exports = class ReadyResource extends EventEmitter {
  constructor () {
    super()

    this.opening = null
    this.closing = null

    this.opened = false
    this.closed = false
  }

  ready () {
    if (this.opening !== null) return this.opening
    this.opening = open(this)
    return this.opening
  }

  close () {
    if (this.closing !== null) return this.closing
    this.closing = close(this)
    return this.closing
  }

  async _open () {
    // add impl here
  }

  async _close () {
    // add impl here
  }
}

async function open (self) {
  // open after close
  if (self.closing !== null) return

  try {
    await self._open()
  } catch (err) {
    self.close() // safe to run in bg
    throw err
  }

  self.opened = true
  self.emit('ready')
}

async function close (self) {
  try {
    if (self.opened === false && self.opening !== null) await self.opening
  } catch {
    // ignore errors on closing
  }
  if (self.opened === true || self.opening === null) await self._close()
  self.closed = true
  self.emit('close')
}
{
  "name": "ready-resource",
  "version": "1.2.0",
  "description": "Modern single resource management",
  "main": "index.js",
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "types": "index.d.ts",
  "files": [
    "index.js",
    "index.d.ts"
  ],
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "devDependencies": {
    "brittle": "^3.1.0",
    "standard": "^17.0.0"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/ready-resource.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/ready-resource/issues"
  },
  "homepage": "https://github.com/holepunchto/ready-resource",
  "dependencies": {
    "bare-events": "^2.2.0"
  }
}
module.exports = require.addon.bind(require)
{
  "name": "require-addon",
  "version": "1.2.0",
  "description": "Import native addons across JavaScript runtimes",
  "exports": {
    "./package": "./package.json",
    ".": {
      "bare": "./lib/bare.js",
      "node": "./lib/node.js",
      "default": "./lib/default.js"
    }
  },
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    },
    "url": {
      "bare": "bare-url",
      "default": "url"
    }
  },
  "files": [
    "lib"
  ],
  "scripts": {
    "test": "npm run lint && npm run test:bare && npm run test:node",
    "test:bare": "bare test.js",
    "test:node": "node test.js",
    "lint": "prettier --check .",
    "format": "prettier --write ."
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/require-addon.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/require-addon/issues"
  },
  "homepage": "https://github.com/holepunchto/require-addon#readme",
  "engines": {
    "bare": ">=1.10.0"
  },
  "dependencies": {
    "bare-addon-resolve": "^1.3.0"
  },
  "devDependencies": {
    "bare-bundle": "^1.8.1",
    "bare-bundle-evaluate": "^1.1.0",
    "bare-fs": "^4.0.0",
    "bare-path": "^3.0.0",
    "bare-url": "^2.1.0",
    "brittle": "^3.7.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
let tmpResolve = null
let tmpReject = null

if (Promise.withResolvers) {
  module.exports = Promise.withResolvers.bind(Promise)
} else {
  module.exports = function resolveRejectPromise () {
    const promise = new Promise(setTmp)
    const result = { promise, resolve: tmpResolve, reject: tmpReject }
    tmpResolve = tmpReject = null
    return result
  }
}

function setTmp (resolve, reject) {
  tmpResolve = resolve
  tmpReject = reject
}
{
  "name": "resolve-reject-promise",
  "version": "1.1.0",
  "description": "Create an inverted promise with no function allocs",
  "main": "index.js",
  "scripts": {
    "test": "standard"
  },
  "devDependencies": {
    "standard": "^17.1.2"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/resolve-reject-promise.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/resolve-reject-promise/issues"
  },
  "homepage": "https://github.com/mafintosh/resolve-reject-promise"
}
module.exports = safetyCatch

function isActuallyUncaught (err) {
  if (!err) return false
  return err instanceof TypeError ||
    err instanceof SyntaxError ||
    err instanceof ReferenceError ||
    err instanceof EvalError ||
    err instanceof RangeError ||
    err instanceof URIError ||
    err.code === 'ERR_ASSERTION' ||
    err.name === 'AssertionError'
}

function throwErrorNT (err) {
  queueMicrotask(() => { throw err })
}

function safetyCatch (err) {
  if (isActuallyUncaught(err)) {
    throwErrorNT(err)
    throw err
  }
}
{
  "name": "safety-catch",
  "version": "1.0.3",
  "description": "Small module that makes sure your catch, caught an actual error and not a programming mistake or assertion",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {},
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/safety-catch.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/safety-catch/issues"
  },
  "homepage": "https://github.com/mafintosh/safety-catch"
}
var varint = require('varint')
exports.encode = function encode (v, b, o) {
  v = v >= 0 ? v*2 : v*-2 - 1
  var r = varint.encode(v, b, o)
  encode.bytes = varint.encode.bytes
  return r
}
exports.decode = function decode (b, o) {
  var v = varint.decode(b, o)
  decode.bytes = varint.decode.bytes
  return v & 1 ? (v+1) / -2 : v / 2
}

exports.encodingLength = function (v) {
  return varint.encodingLength(v >= 0 ? v*2 : v*-2 - 1)
}
{
  "name": "signed-varint",
  "description": "efficiently store signed integers in varint",
  "version": "2.0.1",
  "homepage": "https://github.com/dominictarr/signed-varint",
  "repository": {
    "type": "git",
    "url": "git://github.com/dominictarr/signed-varint.git"
  },
  "dependencies": {
    "varint": "~5.0.0"
  },
  "devDependencies": {
    "tape": "~2.12.3"
  },
  "scripts": {
    "test": "node test.js"
  },
  "author": "Dominic Tarr <dominic.tarr@gmail.com> (http://dominictarr.com)",
  "license": "MIT"
}
require.addon = require('require-addon')
module.exports = require.addon('.', __filename)
const assert = require('assert')
const binding = require('./binding')
const { isNode } = require('which-runtime')

const OPTIONAL = Buffer.from(new ArrayBuffer(0))

module.exports = exports = { ...binding }

// memory

exports.sodium_memzero = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  binding.sodium_memzero(buf)
}

exports.sodium_mlock = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  const res = binding.sodium_mlock(buf)

  if (res !== 0) throw new Error('memory lock failed')
}

exports.sodium_munlock = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  const res = binding.sodium_munlock(buf)

  if (res !== 0) throw new Error('memory unlock failed')
}

exports.sodium_malloc = function (size) {
  assert(size >= 0, 'invalid size')

  const buf = Buffer.from(binding.sodium_malloc(size))
  buf.secure = true
  return buf
}

exports.sodium_free = function (buf) {
  if (!buf || !buf.secure) return

  binding.sodium_free(buf.buffer)
}

exports.sodium_mprotect_noaccess = function (buf) {
  const res = binding.sodium_mprotect_noaccess(buf.buffer)

  if (res !== 0) throw new Error('failed to lock buffer')
}

exports.sodium_mprotect_readonly = function (buf) {
  const res = binding.sodium_mprotect_readonly(buf.buffer)

  if (res !== 0) throw new Error('failed to unlock buffer')
}

exports.sodium_mprotect_readwrite = function (buf) {
  const res = binding.sodium_mprotect_readwrite(buf.buffer)

  if (res !== 0) throw new Error('failed to unlock buffer')
}

// crypto_randombytes

exports.randombytes_buf = function (buffer) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')

  binding.randombytes_buf(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

exports.randombytes_buf_deterministic = function (buffer, seed) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    seed.byteLength === binding.randombytes_SEEDBYTES,
    "seed must be 'randombytes_SEEDBYTES' bytes"
  )

  binding.randombytes_buf_deterministic(
    buffer.buffer,
    buffer.byteOffset,
    buffer.byteLength,

    seed.buffer,
    seed.byteOffset,
    seed.byteLength
  )
}

// sodium_helpers

exports.sodium_memcmp = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  return binding.sodium_memcmp(a, b)
}

exports.sodium_add = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  binding.sodium_add(a, b)
}

exports.sodium_sub = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  binding.sodium_sub(a, b)
}

exports.sodium_compare = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  return binding.sodium_compare(a, b)
}

exports.sodium_is_zero = function (buffer, length) {
  if (length === undefined) length = buffer.byteLength

  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(length >= 0 && length <= buffer.byteLength, 'invalid length')

  return binding.sodium_is_zero(buffer, length)
}

exports.sodium_pad = function (buffer, unpaddedBuflen, blockSize) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(unpaddedBuflen <= buffer.byteLength, 'unpadded length cannot exceed buffer length')
  assert(blockSize <= buffer.byteLength, 'block size cannot exceed buffer length')
  assert(blockSize >= 1, 'block size must be at least 1 byte')
  assert(
    buffer.byteLength >= unpaddedBuflen + (blockSize - (unpaddedBuflen % blockSize)),
    'buf not long enough'
  )

  return binding.sodium_pad(buffer, unpaddedBuflen, blockSize)
}

exports.sodium_unpad = function (buffer, paddedBuflen, blockSize) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(paddedBuflen <= buffer.byteLength, 'unpadded length cannot exceed buffer length')
  assert(blockSize <= buffer.byteLength, 'block size cannot exceed buffer length')
  assert(blockSize >= 1, 'block size must be at least 1 byte')

  return binding.sodium_unpad(buffer, paddedBuflen, blockSize)
}

// crypto_sign

exports.crypto_sign_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )
  assert(
    seed.byteLength === binding.crypto_sign_SEEDBYTES,
    "seed must be 'crypto_sign_SEEDBYTES' bytes"
  )

  const res = binding.crypto_sign_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign = function (sm, m, sk) {
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sm.byteLength === binding.crypto_sign_BYTES + m.byteLength,
    "sm must be 'm.byteLength + crypto_sign_BYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign(sm, m, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_open = function (m, sm, pk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sm.byteLength >= binding.crypto_sign_BYTES,
    "sm must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    m.byteLength === sm.byteLength - binding.crypto_sign_BYTES,
    "m must be 'sm.byteLength - crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_open(m, sm, pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_open = function (m, sm, pk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sm.byteLength >= binding.crypto_sign_BYTES,
    "sm must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    m.byteLength === sm.byteLength - binding.crypto_sign_BYTES,
    "m must be 'sm.byteLength - crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  return binding.crypto_sign_open(m, sm, pk)
}

exports.crypto_sign_detached = function (sig, m, sk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(sig.byteLength === binding.crypto_sign_BYTES, "sig must be 'crypto_sign_BYTES' bytes")
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_detached(sig, m, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_verify_detached = function (sig, m, pk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sig.byteLength >= binding.crypto_sign_BYTES,
    "sig must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  return binding.crypto_sign_verify_detached(
    sig.buffer,
    sig.byteOffset,
    sig.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    pk.buffer,
    pk.byteOffset,
    pk.byteLength
  )
}

exports.crypto_sign_ed25519_sk_to_pk = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_sk_to_pk(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_ed25519_pk_to_curve25519 = function (x25519pk, ed25519pk) {
  assert(ArrayBuffer.isView(x25519pk), 'x25519pk must be a typed array')
  assert(ArrayBuffer.isView(ed25519pk), 'ed25519pk must be a typed array')
  assert(
    x25519pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "x25519pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    ed25519pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "ed25519pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_pk_to_curve25519(x25519pk, ed25519pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_ed25519_sk_to_curve25519 = function (x25519sk, ed25519sk) {
  assert(ArrayBuffer.isView(x25519sk), 'x25519sk must be a typed array')
  assert(ArrayBuffer.isView(ed25519sk), 'ed25519sk must be a typed array')
  assert(
    x25519sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "x25519sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const edLen = ed25519sk.byteLength

  assert(
    edLen === binding.crypto_sign_SECRETKEYBYTES || edLen === binding.crypto_box_SECRETKEYBYTES,
    "ed25519sk must be 'crypto_sign_SECRETKEYBYTES' or 'crypto_sign_SECRETKEYBYTES - crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_sk_to_curve25519(x25519sk, ed25519sk)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_box

exports.crypto_box_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    seed.byteLength === binding.crypto_box_SEEDBYTES,
    "seed must be 'crypto_box_SEEDBYTES' bytes"
  )

  const res = binding.crypto_box_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_easy = function (c, m, n, pk, sk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength === m.byteLength + exports.crypto_box_MACBYTES,
    "c must be 'm.byteLength + crypto_box_MACBYTES' bytes"
  )
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_easy(c, m, n, pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_detached = function (c, mac, m, n, pk, sk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(mac.byteLength === exports.crypto_box_MACBYTES, "mac must be 'crypto_box_MACBYTES' bytes")
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_detached(c, mac, m, n, pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_open_easy = function (m, c, n, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength >= exports.crypto_box_MACBYTES,
    "c must be at least 'crypto_box_MACBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - exports.crypto_box_MACBYTES,
    "m must be 'c.byteLength - crypto_box_MACBYTES' bytes"
  )
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_open_easy(m, c, n, pk, sk)
}

exports.crypto_box_open_detached = function (m, c, mac, n, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(mac.byteLength === exports.crypto_box_MACBYTES, "mac must be 'crypto_box_MACBYTES' bytes")
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_open_detached(m, c, mac, n, pk, sk)
}

exports.crypto_box_seal = function (c, m, pk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    c.byteLength === m.byteLength + exports.crypto_box_SEALBYTES,
    "c must be 'm.byteLength + crypto_box_SEALBYTES' bytes"
  )
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_box_seal(c, m, pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_seal_open = function (m, c, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength >= exports.crypto_box_SEALBYTES,
    "c must be at least 'crypto_box_SEALBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - exports.crypto_box_SEALBYTES,
    "m must be 'c.byteLength - crypto_box_SEALBYTES' bytes"
  )
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_seal_open(
    m.buffer,
    m.byteOffset,
    m.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    pk.buffer,
    pk.byteOffset,
    pk.byteLength,

    sk.buffer,
    sk.byteOffset,
    sk.byteLength
  )
}

// crypto_secretbox

exports.crypto_secretbox_easy = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_secretbox_MACBYTES,
    "c must be 'm.byteLength + crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretbox_easy(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretbox_open_easy = function (m, c, n, k) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    c.byteLength >= binding.crypto_secretbox_MACBYTES,
    "c must be at least 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - binding.crypto_secretbox_MACBYTES,
    "m must be 'c.byteLength - crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  return binding.crypto_secretbox_open_easy(m, c, n, k)
}

exports.crypto_secretbox_detached = function (c, mac, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    mac.byteLength === binding.crypto_secretbox_MACBYTES,
    "mac must be 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretbox_detached(c, mac, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretbox_open_detached = function (m, c, mac, n, k) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(
    mac.byteLength === binding.crypto_secretbox_MACBYTES,
    "mac must be 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  return binding.crypto_secretbox_open_detached(m, c, mac, n, k)
}

// crypto_generichash

exports.crypto_generichash = function (output, input, key) {
  if (!key) key = OPTIONAL

  assert(ArrayBuffer.isView(output), 'output must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    output.byteLength >= binding.crypto_generichash_BYTES_MIN &&
      output.byteLength <= binding.crypto_generichash_BYTES_MAX,
    'output must be between crypto_generichash_BYTES_MIN and crypto_generichash_BYTES_MAX bytes'
  )

  if (key !== OPTIONAL) {
    assert(ArrayBuffer.isView(key), 'key must be a typed array')
    assert(
      key.byteLength >= binding.crypto_generichash_KEYBYTES_MIN &&
        key.byteLength <= binding.crypto_generichash_KEYBYTES_MAX,
      'key must be between crypto_generichash_KEYBYTES_MIN and crypto_generichash_KEYBYTES_MAX bytes'
    )
  }

  const res = binding.crypto_generichash(
    output.buffer,
    output.byteOffset,
    output.byteLength,

    input.buffer,
    input.byteOffset,
    input.byteLength,

    key.buffer,
    key.byteOffset,
    key.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_batch = function (output, batch, key) {
  assert(ArrayBuffer.isView(output), 'output must be a typed array')

  if (isNode || batch.length < 4) {
    const res = binding.crypto_generichash_batch(output, batch, !!key, key || OPTIONAL)
    if (res !== 0) throw new Error('status: ' + res)
  } else {
    const state = Buffer.alloc(binding.crypto_generichash_STATEBYTES)

    exports.crypto_generichash_init(state, key, output.byteLength)

    for (const buf of batch) {
      exports.crypto_generichash_update(state, buf)
    }

    exports.crypto_generichash_final(state, output)
  }
}

exports.crypto_generichash_keygen = function (key) {
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(
    key.byteLength === binding.crypto_generichash_KEYBYTES,
    "key must be 'crypto_generichash_KEYBYTES' bytes"
  )

  const res = binding.crypto_generichash_keygen(key.buffer, key.byteOffset, key.byteLength)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_init = function (state, key, outputLength) {
  if (!key) key = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_init(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    key.buffer,
    key.byteOffset,
    key.byteLength,

    outputLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_update(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    input.buffer,
    input.byteOffset,
    input.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_final = function (state, output) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(output), 'output must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_final(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    output.buffer,
    output.byteOffset,
    output.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

// secretstream

exports.crypto_secretstream_xchacha20poly1305_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  binding.crypto_secretstream_xchacha20poly1305_keygen(k.buffer, k.byteOffset, k.byteLength)
}

exports.crypto_secretstream_xchacha20poly1305_init_push = function (state, header, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(header), 'header must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    header.byteLength === binding.crypto_secretstream_xchacha20poly1305_HEADERBYTES,
    "header must be 'crypto_secretstream_xchacha20poly1305_HEADERBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_init_push(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    header.buffer,
    header.byteOffset,
    header.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretstream_xchacha20poly1305_init_pull = function (state, header, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(header), 'header must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    header.byteLength === binding.crypto_secretstream_xchacha20poly1305_HEADERBYTES,
    "header must be 'crypto_secretstream_xchacha20poly1305_HEADERBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_init_pull(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    header.buffer,
    header.byteOffset,
    header.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretstream_xchacha20poly1305_push = function (state, c, m, ad, tag) {
  if (!ad) ad = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    c.byteLength === m.byteLength + binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "c must be 'm.byteLength + crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_push(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    ad.buffer,
    ad.byteOffset,
    ad.byteLength,

    tag
  )

  if (res < 0) throw new Error('push failed')

  return res
}

exports.crypto_secretstream_xchacha20poly1305_pull = function (state, m, tag, c, ad) {
  if (!ad) ad = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(tag), 'tag must be a typed array')
  assert(tag.byteLength === 1, 'tag must be 1 byte')

  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    c.byteLength >= binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "c must be at least 'crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "m must be 'c.byteLength - crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_pull(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    tag.buffer,
    tag.byteOffset,
    tag.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    ad.buffer,
    ad.byteOffset,
    ad.byteLength
  )

  if (res < 0) throw new Error('pull failed')

  return res
}

exports.crypto_secretstream_xchacha20poly1305_rekey = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )

  binding.crypto_secretstream_xchacha20poly1305_rekey(
    state.buffer,
    state.byteOffset,
    state.byteLength
  )
}

// crypto_stream

exports.crypto_stream = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xor(
    c.buffer,
    c.byteOffset,
    c.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    n.buffer,
    n.byteOffset,
    n.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_auth

exports.crypto_auth = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(out.byteLength === binding.crypto_auth_BYTES, "out must be 'crypto_auth_BYTES' bytes")
  assert(k.byteLength === binding.crypto_auth_KEYBYTES, "k must be 'crypto_auth_KEYBYTES' bytes")

  const res = binding.crypto_auth(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_auth_verify = function (h, input, k) {
  assert(ArrayBuffer.isView(h), 'h must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(h.byteLength === binding.crypto_auth_BYTES, "h must be 'crypto_auth_BYTES' bytes")
  assert(k.byteLength === binding.crypto_auth_KEYBYTES, "k must be 'crypto_auth_KEYBYTES' bytes")

  return binding.crypto_auth_verify(h, input, k)
}

// crypto_onetimeauth

exports.crypto_onetimeauth = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    out.byteLength === binding.crypto_onetimeauth_BYTES,
    "out must be 'crypto_onetimeauth_BYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_init = function (state, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_init(state, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )
  assert(
    out.byteLength === binding.crypto_onetimeauth_BYTES,
    "out must be 'crypto_onetimeauth_BYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_verify = function (h, input, k) {
  assert(ArrayBuffer.isView(h), 'h must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    h.byteLength === binding.crypto_onetimeauth_BYTES,
    "h must be 'crypto_onetimeauth_BYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  return binding.crypto_onetimeauth_verify(h, input, k)
}

// crypto_pwhash

exports.crypto_pwhash = function (out, passwd, salt, opslimit, memlimit, alg) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_BYTES_MIN,
    "out must be at least 'crypto_pwhash_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_BYTES_MAX,
    "out must be at most 'crypto_pwhash_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_SALTBYTES,
    "salt must be 'crypto_pwhash_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )
  assert(alg >= 1 && alg <= 2, 'alg must be either Argon2i 1.3 or Argon2id 1.3')

  const res = binding.crypto_pwhash(out, passwd, salt, opslimit, memlimit, alg)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_async = function (
  out,
  passwd,
  salt,
  opslimit,
  memlimit,
  alg,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_BYTES_MIN,
    "out must be at least 'crypto_pwhash_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_BYTES_MAX,
    "out must be at most 'crypto_pwhash_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_SALTBYTES,
    "salt must be 'crypto_pwhash_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )
  assert(alg >= 1 && alg <= 2, 'alg must be either Argon2i 1.3 or Argon2id 1.3')

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    opslimit,
    memlimit,
    alg,

    done
  )

  return promise
}

exports.crypto_pwhash_str = function (out, passwd, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_STRBYTES,
    "out must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(typeof opslimit === 'number', 'opslimit must be a number')
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(typeof memlimit === 'number', 'memlimit must be a number')
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_str(out, passwd, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_str_async = function (out, passwd, opslimit, memlimit, callback = undefined) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_STRBYTES,
    "out must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(typeof opslimit === 'number', 'opslimit must be a number')
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(typeof memlimit === 'number', 'memlimit must be a number')
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_str_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_str_verify = function (str, passwd) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )

  return binding.crypto_pwhash_str_verify(str, passwd)
}

exports.crypto_pwhash_str_verify_async = function (str, passwd, callback = undefined) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  const [done, promise] = checkStatus(callback, true)

  binding.crypto_pwhash_str_verify_async(
    str.buffer,
    str.byteOffset,
    str.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    done
  )

  return promise
}

exports.crypto_pwhash_str_needs_rehash = function (str, opslimit, memlimit) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  return binding.crypto_pwhash_str_needs_rehash(str, opslimit, memlimit)
}

exports.crypto_pwhash_scryptsalsa208sha256 = function (out, passwd, salt, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MIN,
    "out must be at least 'crypto_pwhash_scryptsalsa208sha256_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MAX,
    "out must be at most 'crypto_pwhash_scryptsalsa208sha256_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_SALTBYTES,
    "salt must be 'crypto_pwhash_scryptsalsa208sha256_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_scryptsalsa208sha256(out, passwd, salt, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_scryptsalsa208sha256_async = function (
  out,
  passwd,
  salt,
  opslimit,
  memlimit,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MIN,
    "out must be at least 'crypto_pwhash_scryptsalsa208sha256_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MAX,
    "out must be at most 'crypto_pwhash_scryptsalsa208sha256_BYTES_MAX' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    salt.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_SALTBYTES,
    "salt must be 'crypto_pwhash_scryptsalsa208sha256_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_scryptsalsa208sha256_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str_async = function (
  out,
  passwd,
  opslimit,
  memlimit,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "out must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_scryptsalsa208sha256_str_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str = function (out, passwd, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "out must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_scryptsalsa208sha256_str(out, passwd, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_scryptsalsa208sha256_str_verify_async = function (
  str,
  passwd,
  callback = undefined
) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  const [done, promise] = checkStatus(callback, true)

  binding.crypto_pwhash_scryptsalsa208sha256_str_verify_async(
    str.buffer,
    str.byteOffset,
    str.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str_verify = function (str, passwd) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  return binding.crypto_pwhash_scryptsalsa208sha256_str_verify(str, passwd)
}

exports.crypto_pwhash_scryptsalsa208sha256_str_needs_rehash = function (str, opslimit, memlimit) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  return binding.crypto_pwhash_scryptsalsa208sha256_str_needs_rehash(str, opslimit, memlimit)
}

// crypto_kx

exports.crypto_kx_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "pk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "sk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    pk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "pk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "sk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    seed.byteLength === binding.crypto_kx_SEEDBYTES,
    "seed must be 'crypto_kx_SEEDBYTES' bytes"
  )

  const res = binding.crypto_kx_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_client_session_keys = function (rx, tx, clientPk, clientSk, serverPk) {
  if (!rx) rx = undefined
  if (!tx) tx = undefined

  assert(rx || tx, 'at least one session key must be specified')

  if (rx) {
    assert(ArrayBuffer.isView(rx), 'rx must be a typed array')
    assert(
      rx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "rx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  if (tx) {
    assert(ArrayBuffer.isView(tx), 'tx must be a typed array')
    assert(
      tx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "tx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  assert(ArrayBuffer.isView(clientPk), 'clientPk must be a typed array')
  assert(ArrayBuffer.isView(clientSk), 'clientSk must be a typed array')
  assert(ArrayBuffer.isView(serverPk), 'serverPk must be a typed array')
  assert(
    clientPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "clientPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    clientSk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "clientSk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    serverPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "serverPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_client_session_keys(rx, tx, clientPk, clientSk, serverPk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_server_session_keys = function (rx, tx, serverPk, serverSk, clientPk) {
  if (!rx) rx = undefined
  if (!tx) tx = undefined

  assert(rx || tx, 'at least one session key must be specified')

  if (rx) {
    assert(ArrayBuffer.isView(rx), 'rx must be a typed array')
    assert(
      rx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "rx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  if (tx) {
    assert(ArrayBuffer.isView(tx), 'tx must be a typed array')
    assert(
      tx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "tx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  assert(ArrayBuffer.isView(serverPk), 'serverPk must be a typed array')
  assert(ArrayBuffer.isView(serverSk), 'serverSk must be a typed array')
  assert(ArrayBuffer.isView(clientPk), 'clientPk must be a typed array')
  assert(
    serverPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "serverPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    serverSk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "serverSk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    clientPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "clientPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_server_session_keys(rx, tx, serverPk, serverSk, clientPk)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_scalarmult

exports.crypto_scalarmult_base = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_BYTES,
    "q must be 'crypto_scalarmult_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_SCALARBYTES,
    "n must be 'crypto_scalarmult_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_base(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_BYTES,
    "q must be 'crypto_scalarmult_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_SCALARBYTES,
    "n must be 'crypto_scalarmult_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_BYTES,
    "p must be 'crypto_scalarmult_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_base = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_base(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519 = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "p must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_is_valid_point = function (p) {
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )

  return binding.crypto_core_ed25519_is_valid_point(p)
}

exports.crypto_core_ed25519_from_uniform = function (p, r) {
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_UNIFORMBYTES,
    "r must be 'crypto_core_ed25519_UNIFORMBYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_from_uniform(p, r)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_base_noclamp = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_base_noclamp(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_noclamp = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "p must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_noclamp(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_core

exports.crypto_core_ed25519_add = function (r, p, q) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_BYTES,
    "r must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_core_ed25519_BYTES,
    "q must be 'crypto_core_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_add(r, p, q)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_sub = function (r, p, q) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_BYTES,
    "r must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_core_ed25519_BYTES,
    "q must be 'crypto_core_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_sub(r, p, q)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_scalar_random = function (r) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "r must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_random(r)
}

exports.crypto_core_ed25519_scalar_reduce = function (r, s) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "r must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_NONREDUCEDSCALARBYTES,
    "s must be 'crypto_core_ed25519_NONREDUCEDSCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_reduce(r, s)
}

exports.crypto_core_ed25519_scalar_invert = function (recip, s) {
  assert(ArrayBuffer.isView(recip), 'recip must be a typed array')
  assert(
    recip.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "recip must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_invert(recip, s)
}

exports.crypto_core_ed25519_scalar_negate = function (neg, s) {
  assert(ArrayBuffer.isView(neg), 'neg must be a typed array')
  assert(
    neg.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "neg must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_negate(neg, s)
}

exports.crypto_core_ed25519_scalar_complement = function (comp, s) {
  assert(ArrayBuffer.isView(comp), 'comp must be a typed array')
  assert(
    comp.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "comp must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_complement(comp, s)
}

exports.crypto_core_ed25519_scalar_add = function (z, x, y) {
  assert(ArrayBuffer.isView(z), 'z must be a typed array')
  assert(
    z.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "z must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(x), 'x must be a typed array')
  assert(
    x.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "x must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(y), 'y must be a typed array')
  assert(
    y.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "y must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_add(z, x, y)
}

exports.crypto_core_ed25519_scalar_sub = function (z, x, y) {
  assert(ArrayBuffer.isView(z), 'z must be a typed array')
  assert(
    z.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "z must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(x), 'x must be a typed array')
  assert(
    x.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "x must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(y), 'y must be a typed array')
  assert(
    y.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "y must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_sub(z, x, y)
}

// crypto_shorthash

exports.crypto_shorthash = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_shorthash_BYTES,
    "out must be 'crypto_shorthash_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_shorthash_KEYBYTES,
    "k must be 'crypto_shorthash_KEYBYTES' bytes"
  )

  const res = binding.crypto_shorthash(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_kdf

exports.crypto_kdf_keygen = function (key) {
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(key.byteLength === binding.crypto_kdf_KEYBYTES, "key must be 'crypto_kdf_KEYBYTES' bytes")

  binding.crypto_kdf_keygen(key)
}

exports.crypto_kdf_derive_from_key = function (subkey, subkeyId, ctx, key) {
  assert(ArrayBuffer.isView(subkey), 'subkey must be a typed array')
  assert(
    subkey.byteLength >= binding.crypto_kdf_BYTES_MIN,
    "subkey must be at least 'crypto_kdf_BYTES_MIN' bytes"
  )
  assert(
    subkey.byteLength <= binding.crypto_kdf_BYTES_MAX,
    "subkey must be at most 'crypto_kdf_BYTES_MAX' bytes"
  )
  assert(ArrayBuffer.isView(ctx), 'ctx must be a typed array')
  assert(
    ctx.byteLength === binding.crypto_kdf_CONTEXTBYTES,
    "ctx must be 'crypto_kdf_CONTEXTBYTES' bytes"
  )
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(key.byteLength === binding.crypto_kdf_KEYBYTES, "key must be 'crypto_kdf_KEYBYTES' bytes")

  const res = binding.crypto_kdf_derive_from_key(subkey, subkeyId, ctx, key)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_hash

exports.crypto_hash = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(out.byteLength === binding.crypto_hash_BYTES, "out must be 'crypto_hash_BYTES' bytes")

  const res = binding.crypto_hash(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256 = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha256_BYTES,
    "out must be 'crypto_hash_sha256_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha256(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_init = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_init(state)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha256_BYTES,
    "out must be 'crypto_hash_sha256_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512 = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha512_BYTES,
    "out must be 'crypto_hash_sha512_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha512(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_init = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_init(state)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha512_BYTES,
    "out must be 'crypto_hash_sha512_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_aead

exports.crypto_aead_xchacha20poly1305_ietf_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  binding.crypto_aead_xchacha20poly1305_ietf_keygen(k)
}

exports.crypto_aead_xchacha20poly1305_ietf_encrypt = function (c, m, ad, nsec, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "c must be 'm.byteLength + crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(c.byteLength <= 0xffffffff, 'c.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_encrypt(c, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_decrypt = function (m, nsec, c, ad, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "m must be 'c.byteLength - crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(m.byteLength <= 0xffffffff, 'm.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_decrypt(m, c, ad, npub, k)

  if (res < 0) throw new Error('could not verify data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_encrypt_detached = function (
  c,
  mac,
  m,
  ad,
  nsec,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_encrypt_detached(c, mac, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_decrypt_detached = function (
  m,
  nsec,
  c,
  mac,
  ad,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_decrypt_detached(m, c, mac, ad, npub, k)

  if (res !== 0) throw new Error('could not verify data')
}

exports.crypto_aead_chacha20poly1305_ietf_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  binding.crypto_aead_chacha20poly1305_ietf_keygen(k)
}

exports.crypto_aead_chacha20poly1305_ietf_encrypt = function (c, m, ad, nsec, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "c must be 'm.byteLength + crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(c.byteLength <= 0xffffffff, 'c.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_encrypt(c, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_decrypt = function (m, nsec, c, ad, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "m must be 'c.byteLength - crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(m.byteLength <= 0xffffffff, 'm.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_decrypt(m, c, ad, npub, k)

  if (res < 0) throw new Error('could not verify data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_encrypt_detached = function (
  c,
  mac,
  m,
  ad,
  nsec,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_encrypt_detached(c, mac, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_decrypt_detached = function (
  m,
  nsec,
  c,
  mac,
  ad,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_decrypt_detached(m, c, mac, ad, npub, k)

  if (res !== 0) throw new Error('could not verify data')
}

// crypto_stream

exports.crypto_stream_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  binding.crypto_stream_xor_wrap_init(state, n, k)
}

exports.crypto_stream_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_xor_wrap_update(state, c, m)
}

exports.crypto_stream_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_xor_wrap_final(state)
}

exports.crypto_stream_chacha20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  binding.crypto_stream_chacha20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_chacha20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_chacha20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_chacha20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_chacha20_xor_wrap_final(state)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  binding.crypto_stream_chacha20_ietf_xor_wrap_init(state, n, k)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_chacha20_ietf_xor_wrap_update(state, c, m)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_chacha20_ietf_xor_wrap_final(state)
}

exports.crypto_stream_xchacha20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  binding.crypto_stream_xchacha20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_xchacha20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_xchacha20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_xchacha20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_xchacha20_xor_wrap_final(state)
}

exports.crypto_stream_salsa20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  binding.crypto_stream_salsa20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_salsa20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_salsa20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_salsa20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_salsa20_xor_wrap_final(state)
}

// experimental

exports.extension_tweak_ed25519_base = function (n, p, ns) {
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.extension_tweak_ed25519_BYTES,
    "p must be 'extension_tweak_ed25519_BYTES' bytes"
  )

  binding.extension_tweak_ed25519_base(n, p, ns)
}

exports.extension_tweak_ed25519_sign_detached = function (sig, m, scalar, pk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(sig.byteLength === binding.crypto_sign_BYTES, "sig must be 'crypto_sign_BYTES' bytes")
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  if (pk) {
    assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
    assert(
      pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
      "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
    )
  }

  const res = binding.extension_tweak_ed25519_sign_detached(sig, m, scalar, pk)

  if (res !== 0) throw new Error('failed to compute signature')
}

exports.extension_tweak_ed25519_sk_to_scalar = function (n, sk) {
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  binding.extension_tweak_ed25519_sk_to_scalar(n, sk)
}

exports.extension_tweak_ed25519_scalar = function (scalarOut, scalar, ns) {
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_scalar(scalarOut, scalar, ns)
}

exports.extension_tweak_ed25519_pk = function (tpk, pk, ns) {
  assert(ArrayBuffer.isView(tpk), 'tpk must be a typed array')
  assert(
    tpk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "tpk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_pk(tpk, pk, ns)

  if (res !== 0) throw new Error('failed to tweak public key')
}

exports.extension_tweak_ed25519_keypair = function (pk, scalarOut, scalarIn, ns) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.extension_tweak_ed25519_BYTES,
    "pk must be 'extension_tweak_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarIn), 'scalarIn must be a typed array')
  assert(
    scalarIn.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarIn must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_keypair(pk, scalarOut, scalarIn, ns)
}

exports.extension_tweak_ed25519_scalar_add = function (scalarOut, scalar, n) {
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_scalar_add(scalarOut, scalar, n)
}

exports.extension_tweak_ed25519_pk_add = function (tpk, pk, p) {
  assert(ArrayBuffer.isView(tpk), 'tpk must be a typed array')
  assert(
    tpk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "tpk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "p must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_pk_add(tpk, pk, p)

  if (res !== 0) throw new Error('failed to add tweak to public key')
}

exports.extension_tweak_ed25519_keypair_add = function (pk, scalarOut, scalarIn, tweak) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.extension_tweak_ed25519_BYTES,
    "pk must be 'extension_tweak_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarIn), 'scalarIn must be a typed array')
  assert(
    scalarIn.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarIn must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(tweak), 'tweak must be a typed array')
  assert(
    tweak.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "tweak must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_keypair_add(pk, scalarOut, scalarIn, tweak)

  if (res !== 0) throw new Error('failed to add tweak to keypair')
}

exports.extension_pbkdf2_sha512_async = function (out, passwd, salt, iter, outlen, callback) {
  assert(
    iter >= binding.extension_pbkdf2_sha512_ITERATIONS_MIN,
    "iter must be at least 'extension_pbkdf2_sha512_ITERATIONS_MIN'"
  )
  assert(
    outlen <= binding.extension_pbkdf2_sha512_BYTES_MAX,
    "outlen must be at most 'extension_pbkdf2_sha512_BYTES_MAX'"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(out.byteLength >= outlen, "out must be at least 'outlen' bytes")
  assert(out.byteLength > 0, 'out must not be empty')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(salt.byteLength > 0, 'salt must not be empty')

  const [done, promise] = checkStatus(callback)

  binding.extension_pbkdf2_sha512_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    iter,
    outlen,

    done
  )

  return promise
}

exports.extension_pbkdf2_sha512 = function (out, passwd, salt, iter, outlen) {
  assert(
    iter >= binding.extension_pbkdf2_sha512_ITERATIONS_MIN,
    "iter must be at least 'extension_pbkdf2_sha512_ITERATIONS_MIN'"
  )
  assert(
    outlen <= binding.extension_pbkdf2_sha512_BYTES_MAX,
    "outlen must be at most 'extension_pbkdf2_sha512_BYTES_MAX'"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(out.byteLength >= outlen, "out must be at least 'outlen' bytes")
  assert(out.byteLength > 0, 'out must not be empty')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(salt.byteLength > 0, 'salt must not be empty')

  const res = binding.extension_pbkdf2_sha512(out, passwd, salt, iter, outlen)

  if (res !== 0) throw new Error('failed to add tweak to public key')
}

function checkStatus(callback, booleanResult = false) {
  let done, promise

  if (typeof callback === 'function') {
    done = function (status) {
      if (booleanResult) callback(null, status === 0)
      else if (status === 0) callback(null)
      else callback(new Error('status: ' + status))
    }
  } else {
    promise = new Promise(function (resolve, reject) {
      done = function (status) {
        if (booleanResult) resolve(status === 0)
        else if (status === 0) resolve()
        else reject(new Error('status: ' + status))
      }
    })
  }

  return [done, promise]
}
{
  "name": "sodium-native",
  "version": "5.1.0",
  "description": "Low level bindings for libsodium",
  "main": "index.js",
  "files": [
    "index.js",
    "binding.cc",
    "binding.js",
    "extensions",
    "prebuilds",
    "CMakeLists.txt"
  ],
  "imports": {
    "assert": {
      "bare": "bare-assert",
      "node": "assert"
    }
  },
  "addon": true,
  "dependencies": {
    "bare-assert": "^1.2.0",
    "require-addon": "^1.1.0",
    "which-runtime": "^1.2.1"
  },
  "devDependencies": {
    "bare-compat-napi": "^1.3.5",
    "brittle": "^3.16.2",
    "cmake-bare": "^1.6.1",
    "cmake-fetch": "^1.4.3",
    "cmake-napi": "^1.2.1",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "test": "prettier . --check && npm run test:node && npm run test:bare",
    "test:node": "node test/all.js",
    "test:bare": "bare test/all.js"
  },
  "standard": {
    "ignore": [
      "/test/fixtures/*.js"
    ]
  },
  "engines": {
    "bare": ">=1.16.0"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sodium-native.git"
  },
  "contributors": [
    "Emil Bay <github@tixz.dk> (http://bayes.dk)",
    "Mathias Buus <mathiasbuus@gmail.com> (https://mafinto.sh)",
    "Christophe Diederichs <chm-diederichs@hyperdivision.dk>"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/sodium-native/issues"
  },
  "homepage": "https://github.com/holepunchto/sodium-native"
}
module.exports = require('sodium-native')
{
  "name": "sodium-universal",
  "version": "5.0.1",
  "description": "Universal wrapper for sodium-javascript and sodium-native working in Node.js and the Browser",
  "main": "index.js",
  "dependencies": {
    "sodium-native": "^5.0.1"
  },
  "peerDependencies": {
    "sodium-javascript": "~0.8.0"
  },
  "peerDependenciesMeta": {
    "sodium-javascript": {
      "optional": true
    }
  },
  "scripts": {
    "prepublish": "./build-scripts/generate.js"
  },
  "browser": {
    "sodium-native": "sodium-javascript"
  },
  "browserify": {
    "transform": [
      "./build-scripts/transform.js"
    ]
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sodium-universal.git"
  },
  "keywords": [
    "libsodium",
    "sodium",
    "sodium-native",
    "sodium-javascript",
    "browserify"
  ],
  "contributors": [
    "Emil Bay <github@tixz.dk> (http://bayes.dk)",
    "Mathias Buus <mathiasbuus@gmail.com> (https://mafinto.sh)",
    "Christophe Diederichs <chm-diederichs@hyperdivision.dk>"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/sodium-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/sodium-universal#readme"
}
const { EventEmitter } = require('events-universal')
const FIFO = require('fast-fifo')
const TextDecoder = require('text-decoder')

const StreamError = require('./lib/errors.js')

// if we do a future major, expect queue microtask to be there always, for now a bit defensive
const qmt =
  typeof queueMicrotask === 'undefined' ? (fn) => global.process.nextTick(fn) : queueMicrotask

// 29 bits used total (4 from shared, 14 from read, and 11 from write)
const MAX = (1 << 29) - 1

// Shared state
const OPENING = 0b0001
const PREDESTROYING = 0b0010
const DESTROYING = 0b0100
const DESTROYED = 0b1000

const NOT_OPENING = MAX ^ OPENING
const NOT_PREDESTROYING = MAX ^ PREDESTROYING

// Read state (4 bit offset from shared state)
const READ_ACTIVE = 0b00000000000001 << 4
const READ_UPDATING = 0b00000000000010 << 4
const READ_PRIMARY = 0b00000000000100 << 4
const READ_QUEUED = 0b00000000001000 << 4
const READ_RESUMED = 0b00000000010000 << 4
const READ_PIPE_DRAINED = 0b00000000100000 << 4
const READ_ENDING = 0b00000001000000 << 4
const READ_EMIT_DATA = 0b00000010000000 << 4
const READ_EMIT_READABLE = 0b00000100000000 << 4
const READ_EMITTED_READABLE = 0b00001000000000 << 4
const READ_DONE = 0b00010000000000 << 4
const READ_NEXT_TICK = 0b00100000000000 << 4
const READ_NEEDS_PUSH = 0b01000000000000 << 4
const READ_READ_AHEAD = 0b10000000000000 << 4

// Combined read state
const READ_FLOWING = READ_RESUMED | READ_PIPE_DRAINED
const READ_ACTIVE_AND_NEEDS_PUSH = READ_ACTIVE | READ_NEEDS_PUSH
const READ_PRIMARY_AND_ACTIVE = READ_PRIMARY | READ_ACTIVE
const READ_EMIT_READABLE_AND_QUEUED = READ_EMIT_READABLE | READ_QUEUED
const READ_RESUMED_READ_AHEAD = READ_RESUMED | READ_READ_AHEAD

const READ_NOT_ACTIVE = MAX ^ READ_ACTIVE
const READ_NON_PRIMARY = MAX ^ READ_PRIMARY
const READ_NON_PRIMARY_AND_PUSHED = MAX ^ (READ_PRIMARY | READ_NEEDS_PUSH)
const READ_PUSHED = MAX ^ READ_NEEDS_PUSH
const READ_PAUSED = MAX ^ READ_RESUMED
const READ_NOT_QUEUED = MAX ^ (READ_QUEUED | READ_EMITTED_READABLE)
const READ_NOT_ENDING = MAX ^ READ_ENDING
const READ_PIPE_NOT_DRAINED = MAX ^ READ_FLOWING
const READ_NOT_NEXT_TICK = MAX ^ READ_NEXT_TICK
const READ_NOT_UPDATING = MAX ^ READ_UPDATING
const READ_NO_READ_AHEAD = MAX ^ READ_READ_AHEAD
const READ_PAUSED_NO_READ_AHEAD = MAX ^ READ_RESUMED_READ_AHEAD

// Write state (18 bit offset, 4 bit offset from shared state and 14 from read state)
const WRITE_ACTIVE = 0b00000000001 << 18
const WRITE_UPDATING = 0b00000000010 << 18
const WRITE_PRIMARY = 0b00000000100 << 18
const WRITE_QUEUED = 0b00000001000 << 18
const WRITE_UNDRAINED = 0b00000010000 << 18
const WRITE_DONE = 0b00000100000 << 18
const WRITE_EMIT_DRAIN = 0b00001000000 << 18
const WRITE_NEXT_TICK = 0b00010000000 << 18
const WRITE_WRITING = 0b00100000000 << 18
const WRITE_FINISHING = 0b01000000000 << 18
const WRITE_CORKED = 0b10000000000 << 18

const WRITE_NOT_ACTIVE = MAX ^ (WRITE_ACTIVE | WRITE_WRITING)
const WRITE_NON_PRIMARY = MAX ^ WRITE_PRIMARY
const WRITE_NOT_FINISHING = MAX ^ (WRITE_ACTIVE | WRITE_FINISHING)
const WRITE_DRAINED = MAX ^ WRITE_UNDRAINED
const WRITE_NOT_QUEUED = MAX ^ WRITE_QUEUED
const WRITE_NOT_NEXT_TICK = MAX ^ WRITE_NEXT_TICK
const WRITE_NOT_UPDATING = MAX ^ WRITE_UPDATING
const WRITE_NOT_CORKED = MAX ^ WRITE_CORKED

// Combined shared state
const ACTIVE = READ_ACTIVE | WRITE_ACTIVE
const NOT_ACTIVE = MAX ^ ACTIVE
const DONE = READ_DONE | WRITE_DONE
const DESTROY_STATUS = DESTROYING | DESTROYED | PREDESTROYING
const OPEN_STATUS = DESTROY_STATUS | OPENING
const AUTO_DESTROY = DESTROY_STATUS | DONE
const NON_PRIMARY = WRITE_NON_PRIMARY & READ_NON_PRIMARY
const ACTIVE_OR_TICKING = WRITE_NEXT_TICK | READ_NEXT_TICK
const TICKING = ACTIVE_OR_TICKING & NOT_ACTIVE
const IS_OPENING = OPEN_STATUS | TICKING

// Combined shared state and read state
const READ_PRIMARY_STATUS = OPEN_STATUS | READ_ENDING | READ_DONE
const READ_STATUS = OPEN_STATUS | READ_DONE | READ_QUEUED
const READ_ENDING_STATUS = OPEN_STATUS | READ_ENDING | READ_QUEUED
const READ_READABLE_STATUS = OPEN_STATUS | READ_EMIT_READABLE | READ_QUEUED | READ_EMITTED_READABLE
const SHOULD_NOT_READ =
  OPEN_STATUS | READ_ACTIVE | READ_ENDING | READ_DONE | READ_NEEDS_PUSH | READ_READ_AHEAD
const READ_BACKPRESSURE_STATUS = DESTROY_STATUS | READ_ENDING | READ_DONE
const READ_UPDATE_SYNC_STATUS = READ_UPDATING | OPEN_STATUS | READ_NEXT_TICK | READ_PRIMARY
const READ_NEXT_TICK_OR_OPENING = READ_NEXT_TICK | OPENING

// Combined write state
const WRITE_PRIMARY_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_DONE
const WRITE_QUEUED_AND_UNDRAINED = WRITE_QUEUED | WRITE_UNDRAINED
const WRITE_QUEUED_AND_ACTIVE = WRITE_QUEUED | WRITE_ACTIVE
const WRITE_DRAIN_STATUS = WRITE_QUEUED | WRITE_UNDRAINED | OPEN_STATUS | WRITE_ACTIVE
const WRITE_STATUS = OPEN_STATUS | WRITE_ACTIVE | WRITE_QUEUED | WRITE_CORKED
const WRITE_PRIMARY_AND_ACTIVE = WRITE_PRIMARY | WRITE_ACTIVE
const WRITE_ACTIVE_AND_WRITING = WRITE_ACTIVE | WRITE_WRITING
const WRITE_FINISHING_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_QUEUED_AND_ACTIVE | WRITE_DONE
const WRITE_BACKPRESSURE_STATUS = WRITE_UNDRAINED | DESTROY_STATUS | WRITE_FINISHING | WRITE_DONE
const WRITE_UPDATE_SYNC_STATUS = WRITE_UPDATING | OPEN_STATUS | WRITE_NEXT_TICK | WRITE_PRIMARY
const WRITE_DROP_DATA = WRITE_FINISHING | WRITE_DONE | DESTROY_STATUS

const asyncIterator = Symbol.asyncIterator || Symbol('asyncIterator')

class WritableState {
  constructor(
    stream,
    { highWaterMark = 16384, map = null, mapWritable, byteLength, byteLengthWritable } = {}
  ) {
    this.stream = stream
    this.queue = new FIFO()
    this.highWaterMark = highWaterMark
    this.buffered = 0
    this.error = null
    this.pipeline = null
    this.drains = null // if we add more seldomly used helpers we might them into a subobject so its a single ptr
    this.byteLength = byteLengthWritable || byteLength || defaultByteLength
    this.map = mapWritable || map
    this.afterWrite = afterWrite.bind(this)
    this.afterUpdateNextTick = updateWriteNT.bind(this)
  }

  get ending() {
    return (this.stream._duplexState & WRITE_FINISHING) !== 0
  }

  get ended() {
    return (this.stream._duplexState & WRITE_DONE) !== 0
  }

  push(data) {
    if ((this.stream._duplexState & WRITE_DROP_DATA) !== 0) return false
    if (this.map !== null) data = this.map(data)

    this.buffered += this.byteLength(data)
    this.queue.push(data)

    if (this.buffered < this.highWaterMark) {
      this.stream._duplexState |= WRITE_QUEUED
      return true
    }

    this.stream._duplexState |= WRITE_QUEUED_AND_UNDRAINED
    return false
  }

  shift() {
    const data = this.queue.shift()

    this.buffered -= this.byteLength(data)
    if (this.buffered === 0) this.stream._duplexState &= WRITE_NOT_QUEUED

    return data
  }

  end(data) {
    if (typeof data === 'function') {
      this.stream.once('finish', data)
    } else if (data !== undefined && data !== null) {
      this.push(data)
    }

    this.stream._duplexState = (this.stream._duplexState | WRITE_FINISHING) & WRITE_NON_PRIMARY
  }

  autoBatch(data, cb) {
    const buffer = []
    const stream = this.stream

    buffer.push(data)
    while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED_AND_ACTIVE) {
      buffer.push(stream._writableState.shift())
    }

    if ((stream._duplexState & OPEN_STATUS) !== 0) return cb(null)
    stream._writev(buffer, cb)
  }

  update() {
    const stream = this.stream

    stream._duplexState |= WRITE_UPDATING

    do {
      while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED) {
        const data = this.shift()
        stream._duplexState |= WRITE_ACTIVE_AND_WRITING
        stream._write(data, this.afterWrite)
      }

      if ((stream._duplexState & WRITE_PRIMARY_AND_ACTIVE) === 0) this.updateNonPrimary()
    } while (this.continueUpdate() === true)

    stream._duplexState &= WRITE_NOT_UPDATING
  }

  updateNonPrimary() {
    const stream = this.stream

    if ((stream._duplexState & WRITE_FINISHING_STATUS) === WRITE_FINISHING) {
      stream._duplexState = stream._duplexState | WRITE_ACTIVE
      stream._final(afterFinal.bind(this))
      return
    }

    if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
      if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
        stream._duplexState |= ACTIVE
        stream._destroy(afterDestroy.bind(this))
      }
      return
    }

    if ((stream._duplexState & IS_OPENING) === OPENING) {
      stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING
      stream._open(afterOpen.bind(this))
    }
  }

  continueUpdate() {
    if ((this.stream._duplexState & WRITE_NEXT_TICK) === 0) return false
    this.stream._duplexState &= WRITE_NOT_NEXT_TICK
    return true
  }

  updateCallback() {
    if ((this.stream._duplexState & WRITE_UPDATE_SYNC_STATUS) === WRITE_PRIMARY) {
      this.update()
    } else {
      this.updateNextTick()
    }
  }

  updateNextTick() {
    if ((this.stream._duplexState & WRITE_NEXT_TICK) !== 0) return
    this.stream._duplexState |= WRITE_NEXT_TICK
    if ((this.stream._duplexState & WRITE_UPDATING) === 0) qmt(this.afterUpdateNextTick)
  }
}

class ReadableState {
  constructor(
    stream,
    { highWaterMark = 16384, map = null, mapReadable, byteLength, byteLengthReadable } = {}
  ) {
    this.stream = stream
    this.queue = new FIFO()
    this.highWaterMark = highWaterMark === 0 ? 1 : highWaterMark
    this.buffered = 0
    this.readAhead = highWaterMark > 0
    this.error = null
    this.pipeline = null
    this.byteLength = byteLengthReadable || byteLength || defaultByteLength
    this.map = mapReadable || map
    this.pipeTo = null
    this.afterRead = afterRead.bind(this)
    this.afterUpdateNextTick = updateReadNT.bind(this)
  }

  get ending() {
    return (this.stream._duplexState & READ_ENDING) !== 0
  }

  get ended() {
    return (this.stream._duplexState & READ_DONE) !== 0
  }

  pipe(pipeTo, cb) {
    if (this.pipeTo !== null) throw StreamError.BAD_ARGUMENT('Can only pipe to one destination')
    if (typeof cb !== 'function') cb = null

    this.stream._duplexState |= READ_PIPE_DRAINED
    this.pipeTo = pipeTo
    this.pipeline = new Pipeline(this.stream, pipeTo, cb)

    if (cb) this.stream.on('error', noop) // We already error handle this so supress crashes

    if (isStreamx(pipeTo)) {
      pipeTo._writableState.pipeline = this.pipeline
      if (cb) pipeTo.on('error', noop) // We already error handle this so supress crashes
      pipeTo.on('finish', this.pipeline.finished.bind(this.pipeline)) // TODO: just call finished from pipeTo itself
    } else {
      const onerror = this.pipeline.done.bind(this.pipeline, pipeTo)
      const onclose = this.pipeline.done.bind(this.pipeline, pipeTo, null) // onclose has a weird bool arg
      pipeTo.on('error', onerror)
      pipeTo.on('close', onclose)
      pipeTo.on('finish', this.pipeline.finished.bind(this.pipeline))
    }

    pipeTo.on('drain', afterDrain.bind(this))
    this.stream.emit('piping', pipeTo)
    pipeTo.emit('pipe', this.stream)
  }

  push(data) {
    const stream = this.stream

    if (data === null) {
      this.highWaterMark = 0
      stream._duplexState = (stream._duplexState | READ_ENDING) & READ_NON_PRIMARY_AND_PUSHED
      return false
    }

    if (this.map !== null) {
      data = this.map(data)
      if (data === null) {
        stream._duplexState &= READ_PUSHED
        return this.buffered < this.highWaterMark
      }
    }

    this.buffered += this.byteLength(data)
    this.queue.push(data)

    stream._duplexState = (stream._duplexState | READ_QUEUED) & READ_PUSHED

    return this.buffered < this.highWaterMark
  }

  shift() {
    const data = this.queue.shift()

    this.buffered -= this.byteLength(data)
    if (this.buffered === 0) {
      this.stream._duplexState &= READ_NOT_QUEUED
    }

    return data
  }

  unshift(data) {
    const pending = [this.map !== null ? this.map(data) : data]
    while (this.buffered > 0) pending.push(this.shift())

    for (let i = 0; i < pending.length - 1; i++) {
      const data = pending[i]
      this.buffered += this.byteLength(data)
      this.queue.push(data)
    }

    this.push(pending[pending.length - 1])
  }

  read() {
    const stream = this.stream

    if ((stream._duplexState & READ_STATUS) === READ_QUEUED) {
      const data = this.shift()

      if (this.pipeTo !== null && this.pipeTo.write(data) === false) {
        stream._duplexState &= READ_PIPE_NOT_DRAINED
      }

      if ((stream._duplexState & READ_EMIT_DATA) !== 0) {
        stream.emit('data', data)
      }

      return data
    }

    if (this.readAhead === false) {
      stream._duplexState |= READ_READ_AHEAD
      this.updateNextTick()
    }

    return null
  }

  drain() {
    const stream = this.stream

    while (
      (stream._duplexState & READ_STATUS) === READ_QUEUED &&
      (stream._duplexState & READ_FLOWING) !== 0
    ) {
      const data = this.shift()

      if (this.pipeTo !== null && this.pipeTo.write(data) === false) {
        stream._duplexState &= READ_PIPE_NOT_DRAINED
      }

      if ((stream._duplexState & READ_EMIT_DATA) !== 0) {
        stream.emit('data', data)
      }
    }
  }

  update() {
    const stream = this.stream

    stream._duplexState |= READ_UPDATING

    do {
      this.drain()

      while (
        this.buffered < this.highWaterMark &&
        (stream._duplexState & SHOULD_NOT_READ) === READ_READ_AHEAD
      ) {
        stream._duplexState |= READ_ACTIVE_AND_NEEDS_PUSH
        stream._read(this.afterRead)
        this.drain()
      }

      if ((stream._duplexState & READ_READABLE_STATUS) === READ_EMIT_READABLE_AND_QUEUED) {
        stream._duplexState |= READ_EMITTED_READABLE
        stream.emit('readable')
      }

      if ((stream._duplexState & READ_PRIMARY_AND_ACTIVE) === 0) {
        this.updateNonPrimary()
      }
    } while (this.continueUpdate() === true)

    stream._duplexState &= READ_NOT_UPDATING
  }

  updateNonPrimary() {
    const stream = this.stream

    if ((stream._duplexState & READ_ENDING_STATUS) === READ_ENDING) {
      stream._duplexState = (stream._duplexState | READ_DONE) & READ_NOT_ENDING
      stream.emit('end')

      if ((stream._duplexState & AUTO_DESTROY) === DONE) {
        stream._duplexState |= DESTROYING
      }

      if (this.pipeTo !== null) {
        this.pipeTo.end()
      }
    }

    if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
      if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
        stream._duplexState |= ACTIVE
        stream._destroy(afterDestroy.bind(this))
      }
      return
    }

    if ((stream._duplexState & IS_OPENING) === OPENING) {
      stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING
      stream._open(afterOpen.bind(this))
    }
  }

  continueUpdate() {
    if ((this.stream._duplexState & READ_NEXT_TICK) === 0) return false
    this.stream._duplexState &= READ_NOT_NEXT_TICK
    return true
  }

  updateCallback() {
    if ((this.stream._duplexState & READ_UPDATE_SYNC_STATUS) === READ_PRIMARY) {
      this.update()
    } else {
      this.updateNextTick()
    }
  }

  updateNextTickIfOpen() {
    if ((this.stream._duplexState & READ_NEXT_TICK_OR_OPENING) !== 0) return
    this.stream._duplexState |= READ_NEXT_TICK
    if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick)
  }

  updateNextTick() {
    if ((this.stream._duplexState & READ_NEXT_TICK) !== 0) return
    this.stream._duplexState |= READ_NEXT_TICK
    if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick)
  }
}

class TransformState {
  constructor(stream) {
    this.data = null
    this.afterTransform = afterTransform.bind(stream)
    this.afterFinal = null
  }
}

class Pipeline {
  constructor(src, dst, cb) {
    this.from = src
    this.to = dst
    this.afterPipe = cb
    this.error = null
    this.pipeToFinished = false
  }

  finished() {
    this.pipeToFinished = true
  }

  done(stream, err) {
    if (err) this.error = err

    if (stream === this.to) {
      this.to = null

      if (this.from !== null) {
        if ((this.from._duplexState & READ_DONE) === 0 || !this.pipeToFinished) {
          this.from.destroy(this.error || StreamError.PREMATURE_CLOSE('Writable stream closed'))
        }
        return
      }
    }

    if (stream === this.from) {
      this.from = null

      if (this.to !== null) {
        if ((stream._duplexState & READ_DONE) === 0) {
          this.to.destroy(this.error || StreamError.PREMATURE_CLOSE('Readable stream closed'))
        }
        return
      }
    }

    if (this.afterPipe !== null) this.afterPipe(this.error)
    this.to = this.from = this.afterPipe = null
  }
}

function afterDrain() {
  this.stream._duplexState |= READ_PIPE_DRAINED
  this.updateCallback()
}

function afterFinal(err) {
  const stream = this.stream
  if (err) stream.destroy(err)

  if ((stream._duplexState & DESTROY_STATUS) === 0) {
    stream._duplexState |= WRITE_DONE
    stream.emit('finish')
  }

  if ((stream._duplexState & AUTO_DESTROY) === DONE) {
    stream._duplexState |= DESTROYING
  }

  stream._duplexState &= WRITE_NOT_FINISHING

  // no need to wait the extra tick here, so we short circuit that
  if ((stream._duplexState & WRITE_UPDATING) === 0) {
    this.update()
  } else {
    this.updateNextTick()
  }
}

function afterDestroy(err) {
  const stream = this.stream

  if (!err && !StreamError.isStreamDestroyed(this.error)) err = this.error
  if (err) stream.emit('error', err)

  stream._duplexState |= DESTROYED
  stream.emit('close')

  const rs = stream._readableState
  const ws = stream._writableState

  if (rs !== null && rs.pipeline !== null) {
    rs.pipeline.done(stream, err)
  }

  if (ws !== null) {
    while (ws.drains !== null && ws.drains.length > 0) {
      ws.drains.shift().resolve(false)
    }

    if (ws.pipeline !== null) {
      ws.pipeline.done(stream, err)
    }
  }
}

function afterWrite(err) {
  const stream = this.stream

  if (err) stream.destroy(err)
  stream._duplexState &= WRITE_NOT_ACTIVE

  if (this.drains !== null) tickDrains(this.drains)

  if ((stream._duplexState & WRITE_DRAIN_STATUS) === WRITE_UNDRAINED) {
    stream._duplexState &= WRITE_DRAINED

    if ((stream._duplexState & WRITE_EMIT_DRAIN) === WRITE_EMIT_DRAIN) {
      stream.emit('drain')
    }
  }

  this.updateCallback()
}

function afterRead(err) {
  if (err) this.stream.destroy(err)
  this.stream._duplexState &= READ_NOT_ACTIVE

  if (this.readAhead === false && (this.stream._duplexState & READ_RESUMED) === 0) {
    this.stream._duplexState &= READ_NO_READ_AHEAD
  }

  this.updateCallback()
}

function updateReadNT() {
  if ((this.stream._duplexState & READ_UPDATING) === 0) {
    this.stream._duplexState &= READ_NOT_NEXT_TICK
    this.update()
  }
}

function updateWriteNT() {
  if ((this.stream._duplexState & WRITE_UPDATING) === 0) {
    this.stream._duplexState &= WRITE_NOT_NEXT_TICK
    this.update()
  }
}

function tickDrains(drains) {
  for (let i = 0; i < drains.length; i++) {
    // drains.writes are monotonic, so if one is 0 its always the first one
    if (--drains[i].writes === 0) {
      drains.shift().resolve(true)
      i--
    }
  }
}

function afterOpen(err) {
  const stream = this.stream

  if (err) stream.destroy(err)

  if ((stream._duplexState & DESTROYING) === 0) {
    if ((stream._duplexState & READ_PRIMARY_STATUS) === 0) {
      stream._duplexState |= READ_PRIMARY
    }

    if ((stream._duplexState & WRITE_PRIMARY_STATUS) === 0) {
      stream._duplexState |= WRITE_PRIMARY
    }

    stream.emit('open')
  }

  stream._duplexState &= NOT_ACTIVE

  if (stream._writableState !== null) {
    stream._writableState.updateCallback()
  }

  if (stream._readableState !== null) {
    stream._readableState.updateCallback()
  }
}

function afterTransform(err, data) {
  if (data !== undefined && data !== null) this.push(data)
  this._writableState.afterWrite(err)
}

function newListener(name) {
  if (this._readableState !== null) {
    if (name === 'data') {
      this._duplexState |= READ_EMIT_DATA | READ_RESUMED_READ_AHEAD
      this._readableState.updateNextTick()
    }
    if (name === 'readable') {
      this._duplexState |= READ_EMIT_READABLE
      this._readableState.updateNextTick()
    }
  }

  if (this._writableState !== null) {
    if (name === 'drain') {
      this._duplexState |= WRITE_EMIT_DRAIN
      this._writableState.updateNextTick()
    }
  }
}

class Stream extends EventEmitter {
  constructor(opts) {
    super()

    this._duplexState = 0
    this._readableState = null
    this._writableState = null

    if (opts) {
      if (opts.open) this._open = opts.open
      if (opts.destroy) this._destroy = opts.destroy
      if (opts.predestroy) this._predestroy = opts.predestroy
      if (opts.signal) opts.signal.addEventListener('abort', abort.bind(this))
    }

    this.on('newListener', newListener)
  }

  _open(cb) {
    cb(null)
  }

  _destroy(cb) {
    cb(null)
  }

  _predestroy() {
    // does nothing
  }

  get readable() {
    return this._readableState !== null ? true : undefined
  }

  get writable() {
    return this._writableState !== null ? true : undefined
  }

  get destroyed() {
    return (this._duplexState & DESTROYED) !== 0
  }

  get destroying() {
    return (this._duplexState & DESTROY_STATUS) !== 0
  }

  destroy(err) {
    if ((this._duplexState & DESTROY_STATUS) === 0) {
      if (!err) err = StreamError.STREAM_DESTROYED()
      this._duplexState = (this._duplexState | DESTROYING) & NON_PRIMARY

      if (this._readableState !== null) {
        this._readableState.highWaterMark = 0
        this._readableState.error = err
      }

      if (this._writableState !== null) {
        this._writableState.highWaterMark = 0
        this._writableState.error = err
      }

      this._duplexState |= PREDESTROYING
      this._predestroy()
      this._duplexState &= NOT_PREDESTROYING

      if (this._readableState !== null) {
        this._readableState.updateNextTick()
      }

      if (this._writableState !== null) {
        this._writableState.updateNextTick()
      }
    }
  }
}

class Readable extends Stream {
  constructor(opts) {
    super(opts)

    this._duplexState |= OPENING | WRITE_DONE | READ_READ_AHEAD
    this._readableState = new ReadableState(this, opts)

    if (opts) {
      if (this._readableState.readAhead === false) this._duplexState &= READ_NO_READ_AHEAD
      if (opts.read) this._read = opts.read
      if (opts.eagerOpen) this._readableState.updateNextTick()
      if (opts.encoding) this.setEncoding(opts.encoding)
    }
  }

  static deferred(fn, opts) {
    const out = new PassThrough(opts)

    fn()
      .then((src) => {
        if (src === null) return out.end()
        if (out.destroying) return
        pipeline(src, out, noop)
      })
      .catch((err) => out.destroy(err))

    return out
  }

  setEncoding(encoding) {
    const dec = new TextDecoder(encoding)
    const map = this._readableState.map || echo
    this._readableState.map = mapOrSkip
    return this

    function mapOrSkip(data) {
      const next = dec.push(data)
      return next === '' && (data.byteLength !== 0 || dec.remaining > 0) ? null : map(next)
    }
  }

  _read(cb) {
    cb(null)
  }

  pipe(dest, cb) {
    this._readableState.updateNextTick()
    this._readableState.pipe(dest, cb)
    return dest
  }

  read() {
    this._readableState.updateNextTick()
    return this._readableState.read()
  }

  push(data) {
    this._readableState.updateNextTickIfOpen()
    return this._readableState.push(data)
  }

  unshift(data) {
    this._readableState.updateNextTickIfOpen()
    return this._readableState.unshift(data)
  }

  resume() {
    this._duplexState |= READ_RESUMED_READ_AHEAD
    this._readableState.updateNextTick()
    return this
  }

  pause() {
    this._duplexState &=
      this._readableState.readAhead === false ? READ_PAUSED_NO_READ_AHEAD : READ_PAUSED
    return this
  }

  static _fromAsyncIterator(ite, opts) {
    let destroy

    const rs = new Readable({
      ...opts,
      read(cb) {
        ite.next().then(push).then(cb.bind(null, null)).catch(cb)
      },
      predestroy() {
        destroy = ite.return()
      },
      destroy(cb) {
        if (!destroy) return cb(null)
        destroy.then(cb.bind(null, null)).catch(cb)
      }
    })

    return rs

    function push(data) {
      if (data.done) rs.push(null)
      else rs.push(data.value)
    }
  }

  static from(data, opts) {
    if (isReadStreamx(data)) return data
    if (data[asyncIterator]) return this._fromAsyncIterator(data[asyncIterator](), opts)
    if (!Array.isArray(data)) data = data === undefined ? [] : [data]

    let i = 0
    return new Readable({
      ...opts,
      read(cb) {
        this.push(i === data.length ? null : data[i++])
        cb(null)
      }
    })
  }

  static isBackpressured(rs) {
    return (
      (rs._duplexState & READ_BACKPRESSURE_STATUS) !== 0 ||
      rs._readableState.buffered >= rs._readableState.highWaterMark
    )
  }

  static isPaused(rs) {
    return (rs._duplexState & READ_RESUMED) === 0
  }

  [asyncIterator]() {
    const stream = this

    let error = null
    let promiseResolve = null
    let promiseReject = null

    this.on('error', (err) => {
      error = err
    })
    this.on('readable', onreadable)
    this.on('close', onclose)

    return {
      [asyncIterator]() {
        return this
      },
      next() {
        return new Promise(function (resolve, reject) {
          promiseResolve = resolve
          promiseReject = reject
          const data = stream.read()
          if (data !== null) ondata(data)
          else if ((stream._duplexState & DESTROYED) !== 0) ondata(null)
        })
      },
      return() {
        return destroy(null)
      },
      throw(err) {
        return destroy(err)
      }
    }

    function onreadable() {
      if (promiseResolve !== null) ondata(stream.read())
    }

    function onclose() {
      if (promiseResolve !== null) ondata(null)
    }

    function ondata(data) {
      if (promiseReject === null) return
      if (error) {
        promiseReject(error)
      } else if (data === null && (stream._duplexState & READ_DONE) === 0) {
        promiseReject(StreamError.STREAM_DESTROYED())
      } else {
        promiseResolve({ value: data, done: data === null })
      }
      promiseReject = promiseResolve = null
    }

    function destroy(err) {
      stream.destroy(err)
      return new Promise((resolve, reject) => {
        if (stream._duplexState & DESTROYED) return resolve({ value: undefined, done: true })
        stream.once('close', function () {
          if (err) reject(err)
          else resolve({ value: undefined, done: true })
        })
      })
    }
  }
}

class Writable extends Stream {
  constructor(opts) {
    super(opts)

    this._duplexState |= OPENING | READ_DONE
    this._writableState = new WritableState(this, opts)

    if (opts) {
      if (opts.writev) this._writev = opts.writev
      if (opts.write) this._write = opts.write
      if (opts.final) this._final = opts.final
      if (opts.eagerOpen) this._writableState.updateNextTick()
    }
  }

  cork() {
    this._duplexState |= WRITE_CORKED
  }

  uncork() {
    this._duplexState &= WRITE_NOT_CORKED
    this._writableState.updateNextTick()
  }

  _writev(batch, cb) {
    cb(null)
  }

  _write(data, cb) {
    this._writableState.autoBatch(data, cb)
  }

  _final(cb) {
    cb(null)
  }

  static isBackpressured(ws) {
    return (ws._duplexState & WRITE_BACKPRESSURE_STATUS) !== 0
  }

  static drained(ws) {
    if (ws.destroyed) return Promise.resolve(false)

    const state = ws._writableState
    const pending = isWritev(ws) ? Math.min(1, state.queue.length) : state.queue.length
    const writes = pending + (ws._duplexState & WRITE_WRITING ? 1 : 0)
    if (writes === 0) return Promise.resolve(true)

    if (state.drains === null) state.drains = []
    return new Promise((resolve) => {
      state.drains.push({ writes, resolve })
    })
  }

  write(data) {
    this._writableState.updateNextTick()
    return this._writableState.push(data)
  }

  end(data) {
    this._writableState.updateNextTick()
    this._writableState.end(data)
    return this
  }
}

class Duplex extends Readable {
  // and Writable
  constructor(opts) {
    super(opts)

    this._duplexState = OPENING | (this._duplexState & READ_READ_AHEAD)
    this._writableState = new WritableState(this, opts)

    if (opts) {
      if (opts.writev) this._writev = opts.writev
      if (opts.write) this._write = opts.write
      if (opts.final) this._final = opts.final
    }
  }

  cork() {
    this._duplexState |= WRITE_CORKED
  }

  uncork() {
    this._duplexState &= WRITE_NOT_CORKED
    this._writableState.updateNextTick()
  }

  _writev(batch, cb) {
    cb(null)
  }

  _write(data, cb) {
    this._writableState.autoBatch(data, cb)
  }

  _final(cb) {
    cb(null)
  }

  write(data) {
    this._writableState.updateNextTick()
    return this._writableState.push(data)
  }

  end(data) {
    this._writableState.updateNextTick()
    this._writableState.end(data)
    return this
  }
}

class Transform extends Duplex {
  constructor(opts) {
    super(opts)
    this._transformState = new TransformState(this)

    if (opts) {
      if (opts.transform) this._transform = opts.transform
      if (opts.flush) this._flush = opts.flush
    }
  }

  _write(data, cb) {
    if (this._readableState.buffered >= this._readableState.highWaterMark) {
      this._transformState.data = data
    } else {
      this._transform(data, this._transformState.afterTransform)
    }
  }

  _read(cb) {
    if (this._transformState.data !== null) {
      const data = this._transformState.data
      this._transformState.data = null
      cb(null)
      this._transform(data, this._transformState.afterTransform)
    } else {
      cb(null)
    }
  }

  destroy(err) {
    super.destroy(err)
    if (this._transformState.data !== null) {
      this._transformState.data = null
      this._transformState.afterTransform()
    }
  }

  _transform(data, cb) {
    cb(null, data)
  }

  _flush(cb) {
    cb(null)
  }

  _final(cb) {
    this._transformState.afterFinal = cb
    this._flush(transformAfterFlush.bind(this))
  }
}

class PassThrough extends Transform {}

function transformAfterFlush(err, data) {
  const cb = this._transformState.afterFinal
  if (err) return cb(err)

  if (data !== null && data !== undefined) this.push(data)
  this.push(null)
  cb(null)
}

function pipelinePromise(...streams) {
  return new Promise((resolve, reject) => {
    return pipeline(...streams, (err) => {
      if (err) return reject(err)
      resolve()
    })
  })
}

function pipeline(stream, ...streams) {
  const all = Array.isArray(stream) ? [...stream, ...streams] : [stream, ...streams]
  const done = all.length && typeof all[all.length - 1] === 'function' ? all.pop() : null

  if (all.length < 2) throw StreamError.BAD_ARGUMENT('Pipeline requires at least 2 streams')

  let src = all[0]
  let dest = null
  let error = null

  for (let i = 1; i < all.length; i++) {
    dest = all[i]

    if (isStreamx(src)) {
      src.pipe(dest, onerror)
    } else {
      errorHandle(src, true, i > 1, onerror)
      src.pipe(dest)
    }

    src = dest
  }

  if (done) {
    let fin = false

    const autoDestroy =
      isStreamx(dest) || !!(dest._writableState && dest._writableState.autoDestroy)

    dest.on('error', (err) => {
      if (error === null) error = err
    })

    dest.on('finish', () => {
      fin = true
      if (!autoDestroy) done(error)
    })

    if (autoDestroy) {
      dest.on('close', () => done(error || (fin ? null : StreamError.PREMATURE_CLOSE())))
    }
  }

  return dest

  function errorHandle(s, rd, wr, onerror) {
    s.on('error', onerror)
    s.on('close', onclose)

    function onclose() {
      if (rd && s._readableState && !s._readableState.ended) {
        return onerror(StreamError.PREMATURE_CLOSE())
      }
      if (wr && s._writableState && !s._writableState.ended) {
        return onerror(StreamError.PREMATURE_CLOSE())
      }
    }
  }

  function onerror(err) {
    if (!err || error) return
    error = err

    for (const s of all) {
      s.destroy(err)
    }
  }
}

function echo(s) {
  return s
}

function isStream(stream) {
  return !!stream._readableState || !!stream._writableState
}

function isStreamx(stream) {
  return typeof stream._duplexState === 'number' && isStream(stream)
}

function isEnding(stream) {
  return !!stream._readableState && stream._readableState.ending
}

function isEnded(stream) {
  return !!stream._readableState && stream._readableState.ended
}

function isFinishing(stream) {
  return !!stream._writableState && stream._writableState.ending
}

function isFinished(stream) {
  return !!stream._writableState && stream._writableState.ended
}

function getStreamError(stream, opts = {}) {
  const err =
    (stream._readableState && stream._readableState.error) ||
    (stream._writableState && stream._writableState.error)

  // avoid implicit errors by default
  return !opts.all && StreamError.isStreamDestroyed(err) ? null : err
}

function isReadStreamx(stream) {
  return isStreamx(stream) && stream.readable
}

function isDisturbed(stream) {
  return (
    (stream._duplexState & OPENING) !== OPENING ||
    (stream._duplexState & DESTROYING) === DESTROYING ||
    (stream._duplexState & ACTIVE_OR_TICKING) !== 0
  )
}

function isTypedArray(data) {
  return typeof data === 'object' && data !== null && typeof data.byteLength === 'number'
}

function defaultByteLength(data) {
  return isTypedArray(data) ? data.byteLength : 1024
}

function noop() {}

function abort() {
  this.destroy(StreamError.ABORTED())
}

function isWritev(s) {
  return s._writev !== Writable.prototype._writev && s._writev !== Duplex.prototype._writev
}

module.exports = {
  pipeline,
  pipelinePromise,
  isStream,
  isStreamx,
  isEnding,
  isEnded,
  isFinishing,
  isFinished,
  isDisturbed,
  getStreamError,
  Stream,
  Writable,
  Readable,
  Duplex,
  Transform,
  // Export PassThrough for compatibility with Node.js core's stream module
  PassThrough
}
module.exports = class StreamError extends Error {
  constructor(msg, code, fn = StreamError) {
    super(msg)

    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  static isStreamDestroyed(err) {
    return err && err.code === 'STREAM_DESTROYED'
  }

  static isPrematureClose(err) {
    return err && err.code === 'PREMATURE_CLOSE'
  }

  static isAborted(err) {
    return err && err.code === 'ABORTED'
  }

  static isBadArgument(err) {
    return err && err.code === 'BAD_ARGUMENT'
  }

  get name() {
    return 'StreamError'
  }

  static STREAM_DESTROYED() {
    return new StreamError('Stream was destroyed', 'STREAM_DESTROYED', StreamError.STREAM_DESTROYED)
  }

  static PREMATURE_CLOSE(msg = 'Premature close') {
    return new StreamError(msg, 'PREMATURE_CLOSE', StreamError.PREMATURE_CLOSE)
  }

  static ABORTED() {
    return new StreamError('Stream aborted', 'ABORTED', StreamError.ABORTED)
  }

  static BAD_ARGUMENT(msg = 'Bad argument') {
    return new StreamError(msg, 'BAD_ARGUMENT', StreamError.BAD_ARGUMENT)
  }
}
{
  "name": "streamx",
  "version": "2.28.0",
  "description": "An iteration of the Node.js core streams with a series of improvements",
  "main": "index.js",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./errors": {
      "types": "./lib/errors.d.ts",
      "default": "./lib/errors"
    }
  },
  "dependencies": {
    "events-universal": "^1.0.0",
    "fast-fifo": "^1.3.2",
    "text-decoder": "^1.1.0"
  },
  "devDependencies": {
    "b4a": "^1.6.6",
    "brittle": "^3.1.1",
    "end-of-stream": "^1.4.4",
    "lunte": "^1.8.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "runtime.d.ts",
    "lib"
  ],
  "scripts": {
    "format": "prettier . --write",
    "test": "brittle test/all.js && brittle-bare test/all.js",
    "lint": "prettier . --check && lunte"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/streamx.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/streamx/issues"
  },
  "homepage": "https://github.com/mafintosh/streamx"
}
const { Readable } = require('streamx')

module.exports = function (s, forks = 2) {
  const streams = new Array(forks)
  const status = new Array(forks).fill(true)

  let ended = false

  for (let i = 0; i < forks; i++) {
    streams[i] = new Readable({
      read (cb) {
        const check = !status[i]
        status[i] = true
        if (check && allReadable()) s.resume()
        cb(null)
      }
    })
  }

  s.on('end', function () {
    ended = true
    for (const stream of streams) stream.push(null)
  })

  s.on('error', function (err) {
    for (const stream of streams) stream.destroy(err)
  })

  s.on('close', function () {
    if (ended) return
    for (const stream of streams) stream.destroy()
  })

  s.on('data', function (data) {
    let needsPause = false
    for (let i = 0; i < streams.length; i++) {
      if (!(status[i] = streams[i].push(data))) {
        needsPause = true
      }
    }
    if (needsPause) s.pause()
  })

  return streams

  function allReadable () {
    for (let j = 0; j < status.length; j++) {
      if (!status[j]) return false
    }
    return true
  }
}
{
  "name": "teex",
  "version": "1.0.1",
  "description": "Turn a readable stream into multiple readable streamx streams",
  "main": "index.js",
  "dependencies": {
    "streamx": "^2.12.5"
  },
  "devDependencies": {
    "standard": "^14.3.4",
    "tape": "^5.0.1"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/teex.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/teex/issues"
  },
  "homepage": "https://github.com/mafintosh/teex"
}
const PassThroughDecoder = require('./lib/pass-through-decoder')
const UTF8Decoder = require('./lib/utf8-decoder')

module.exports = class TextDecoder {
  constructor(encoding = 'utf8') {
    this.encoding = normalizeEncoding(encoding)

    switch (this.encoding) {
      case 'utf8':
        this.decoder = new UTF8Decoder()
        break
      case 'utf16le':
      case 'base64':
        throw new Error('Unsupported encoding: ' + this.encoding)
      default:
        this.decoder = new PassThroughDecoder(this.encoding)
    }
  }

  get remaining() {
    return this.decoder.remaining
  }

  push(data) {
    if (typeof data === 'string') return data
    return this.decoder.decode(data)
  }

  // For Node.js compatibility
  write(data) {
    return this.push(data)
  }

  end(data) {
    let result = ''
    if (data) result = this.push(data)
    result += this.decoder.flush()
    return result
  }
}

function normalizeEncoding(encoding) {
  encoding = encoding.toLowerCase()

  switch (encoding) {
    case 'utf8':
    case 'utf-8':
      return 'utf8'
    case 'ucs2':
    case 'ucs-2':
    case 'utf16le':
    case 'utf-16le':
      return 'utf16le'
    case 'latin1':
    case 'binary':
      return 'latin1'
    case 'base64':
    case 'ascii':
    case 'hex':
      return encoding
    default:
      throw new Error('Unknown encoding: ' + encoding)
  }
}
const b4a = require('b4a')

module.exports = class PassThroughDecoder {
  constructor(encoding) {
    this.encoding = encoding
  }

  get remaining() {
    return 0
  }

  decode(data) {
    return b4a.toString(data, this.encoding)
  }

  flush() {
    return ''
  }
}
const b4a = require('b4a')

/**
 * https://encoding.spec.whatwg.org/#utf-8-decoder
 */
module.exports = class UTF8Decoder {
  constructor() {
    this._reset()
  }

  get remaining() {
    return this.bytesSeen
  }

  decode(data) {
    if (data.byteLength === 0) return ''

    if (this.bytesNeeded === 0 && trailingIncomplete(data, 0) === 0) {
      this.bytesSeen = trailingBytesSeen(data)
      return b4a.toString(data, 'utf8')
    }

    let result = ''
    let start = 0

    if (this.bytesNeeded > 0) {
      while (start < data.byteLength) {
        const byte = data[start]

        if (byte < this.lowerBoundary || byte > this.upperBoundary) {
          result += '\ufffd'
          this._reset()
          break
        }

        this.lowerBoundary = 0x80
        this.upperBoundary = 0xbf
        this.codePoint = (this.codePoint << 6) | (byte & 0x3f)
        this.bytesSeen++
        start++

        if (this.bytesSeen === this.bytesNeeded) {
          result += String.fromCodePoint(this.codePoint)
          this._reset()
          break
        }
      }

      if (this.bytesNeeded > 0) return result
    }

    const trailing = trailingIncomplete(data, start)
    const end = data.byteLength - trailing

    if (end > start) result += b4a.toString(data, 'utf8', start, end)

    for (let i = end; i < data.byteLength; i++) {
      const byte = data[i]

      if (this.bytesNeeded === 0) {
        if (byte <= 0x7f) {
          this.bytesSeen = 0
          result += String.fromCharCode(byte)
        } else if (byte >= 0xc2 && byte <= 0xdf) {
          this.bytesNeeded = 2
          this.bytesSeen = 1
          this.codePoint = byte & 0x1f
        } else if (byte >= 0xe0 && byte <= 0xef) {
          if (byte === 0xe0) this.lowerBoundary = 0xa0
          else if (byte === 0xed) this.upperBoundary = 0x9f
          this.bytesNeeded = 3
          this.bytesSeen = 1
          this.codePoint = byte & 0xf
        } else if (byte >= 0xf0 && byte <= 0xf4) {
          if (byte === 0xf0) this.lowerBoundary = 0x90
          else if (byte === 0xf4) this.upperBoundary = 0x8f
          this.bytesNeeded = 4
          this.bytesSeen = 1
          this.codePoint = byte & 0x7
        } else {
          this.bytesSeen = 1
          result += '\ufffd'
        }

        continue
      }

      if (byte < this.lowerBoundary || byte > this.upperBoundary) {
        result += '\ufffd'
        i--
        this._reset()

        continue
      }

      this.lowerBoundary = 0x80
      this.upperBoundary = 0xbf

      this.codePoint = (this.codePoint << 6) | (byte & 0x3f)
      this.bytesSeen++

      if (this.bytesSeen === this.bytesNeeded) {
        result += String.fromCodePoint(this.codePoint)
        this._reset()
      }
    }

    return result
  }

  flush() {
    const result = this.bytesNeeded > 0 ? '\ufffd' : ''
    this._reset()
    return result
  }

  _reset() {
    this.codePoint = 0
    this.bytesNeeded = 0
    this.bytesSeen = 0
    this.lowerBoundary = 0x80
    this.upperBoundary = 0xbf
  }
}

function trailingIncomplete(data, start) {
  const len = data.byteLength
  if (len <= start) return 0

  const limit = Math.max(start, len - 4)

  let i = len - 1
  while (i > limit && (data[i] & 0xc0) === 0x80) i--

  if (i < start) return 0

  const byte = data[i]

  let needed
  if (byte <= 0x7f) return 0
  if (byte >= 0xc2 && byte <= 0xdf) needed = 2
  else if (byte >= 0xe0 && byte <= 0xef) needed = 3
  else if (byte >= 0xf0 && byte <= 0xf4) needed = 4
  else return 0

  const available = len - i
  return available < needed ? available : 0
}

function trailingBytesSeen(data) {
  const len = data.byteLength
  if (len === 0) return 0

  const last = data[len - 1]

  if (last <= 0x7f) return 0
  if ((last & 0xc0) !== 0x80) return 1

  const limit = Math.max(0, len - 4)

  let i = len - 2
  while (i >= limit && (data[i] & 0xc0) === 0x80) i--

  if (i < 0) return 1

  const first = data[i]

  let needed
  if (first >= 0xc2 && first <= 0xdf) needed = 2
  else if (first >= 0xe0 && first <= 0xef) needed = 3
  else if (first >= 0xf0 && first <= 0xf4) needed = 4
  else return 1

  if (len - i !== needed) return 1

  if (needed >= 3) {
    const second = data[i + 1]
    if (first === 0xe0 && second < 0xa0) return 1
    if (first === 0xed && second > 0x9f) return 1
    if (first === 0xf0 && second < 0x90) return 1
    if (first === 0xf4 && second > 0x8f) return 1
  }

  return 0
}
{
  "name": "text-decoder",
  "version": "1.2.7",
  "description": "Streaming text decoder that preserves multibyte Unicode characters",
  "exports": {
    "./package": "./package.json",
    ".": "./index.js"
  },
  "files": [
    "index.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/text-decoder.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/text-decoder/issues"
  },
  "homepage": "https://github.com/holepunchto/text-decoder#readme",
  "dependencies": {
    "b4a": "^1.6.4"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  }
}
const b4a = require('b4a')

unslab.all = all
unslab.is = is

module.exports = unslab

function unslab (buf) {
  if (buf === null || buf.buffer.byteLength === buf.byteLength) return buf
  const copy = b4a.allocUnsafeSlow(buf.byteLength)
  copy.set(buf, 0)
  return copy
}

function is (buf) {
  return buf.buffer.byteLength !== buf.byteLength
}

function all (list) {
  let size = 0
  for (let i = 0; i < list.length; i++) {
    const buf = list[i]
    size += buf === null || buf.buffer.byteLength === buf.byteLength ? 0 : buf.byteLength
  }

  const copy = b4a.allocUnsafeSlow(size)
  const result = new Array(list.length)

  let offset = 0
  for (let i = 0; i < list.length; i++) {
    let buf = list[i]

    if (buf !== null && buf.buffer.byteLength !== buf.byteLength) {
      copy.set(buf, offset)
      buf = copy.subarray(offset, offset += buf.byteLength)
    }

    result[i] = buf
  }

  return result
}
{
  "name": "unslab",
  "version": "1.3.0",
  "description": "Unslab some slab'ed buffers",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.6.6"
  },
  "devDependencies": {
    "brittle": "^3.5.2",
    "standard": "^17.1.0"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/unslab.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/unslab/issues"
  },
  "homepage": "https://github.com/holepunchto/unslab"
}
module.exports = read

var MSB = 0x80
  , REST = 0x7F

function read(buf, offset) {
  var res    = 0
    , offset = offset || 0
    , shift  = 0
    , counter = offset
    , b
    , l = buf.length

  do {
    if (counter >= l) {
      read.bytes = 0
      throw new RangeError('Could not decode varint')
    }
    b = buf[counter++]
    res += shift < 28
      ? (b & REST) << shift
      : (b & REST) * Math.pow(2, shift)
    shift += 7
  } while (b >= MSB)

  read.bytes = counter - offset

  return res
}
module.exports = encode

var MSB = 0x80
  , REST = 0x7F
  , MSBALL = ~REST
  , INT = Math.pow(2, 31)

function encode(num, out, offset) {
  out = out || []
  offset = offset || 0
  var oldOffset = offset

  while(num >= INT) {
    out[offset++] = (num & 0xFF) | MSB
    num /= 128
  }
  while(num & MSBALL) {
    out[offset++] = (num & 0xFF) | MSB
    num >>>= 7
  }
  out[offset] = num | 0
  
  encode.bytes = offset - oldOffset + 1
  
  return out
}
module.exports = {
    encode: require('./encode.js')
  , decode: require('./decode.js')
  , encodingLength: require('./length.js')
}

var N1 = Math.pow(2,  7)
var N2 = Math.pow(2, 14)
var N3 = Math.pow(2, 21)
var N4 = Math.pow(2, 28)
var N5 = Math.pow(2, 35)
var N6 = Math.pow(2, 42)
var N7 = Math.pow(2, 49)
var N8 = Math.pow(2, 56)
var N9 = Math.pow(2, 63)

module.exports = function (value) {
  return (
    value < N1 ? 1
  : value < N2 ? 2
  : value < N3 ? 3
  : value < N4 ? 4
  : value < N5 ? 5
  : value < N6 ? 6
  : value < N7 ? 7
  : value < N8 ? 8
  : value < N9 ? 9
  :              10
  )
}
{
  "name": "varint",
  "version": "5.0.0",
  "description": "protobuf-style varint bytes - use msb to create integer values of varying sizes",
  "main": "index.js",
  "scripts": {
    "test": "node test.js"
  },
  "repository": {
    "type": "git",
    "url": "git://github.com/chrisdickinson/varint.git"
  },
  "keywords": [
    "varint",
    "protobuf",
    "encode",
    "decode"
  ],
  "author": "Chris Dickinson <chris@neversaw.us>",
  "license": "MIT",
  "devDependencies": {
    "tape": "~2.12.3"
  }
}
const { runtime, platform, arch, version } =
  typeof Bare !== 'undefined'
    ? {
        runtime: 'bare',
        platform: global.Bare.platform,
        arch: global.Bare.arch,
        version: global.Bare.version
      }
    : typeof process !== 'undefined'
      ? {
          runtime: 'node',
          platform: global.process.platform,
          arch: global.process.arch,
          version: global.process.version
        }
      : typeof Window !== 'undefined'
        ? { runtime: 'browser', platform: 'unknown', arch: 'unknown', version: 'unknown' }
        : { runtime: 'unknown', platform: 'unknown', arch: 'unknown', version: 'unknown' }

exports.runtime = runtime
exports.version = version
exports.platform = platform
exports.arch = arch
exports.isBare = runtime === 'bare'
exports.isBareKit = exports.isBare && typeof BareKit !== 'undefined'
exports.isPear = typeof Pear !== 'undefined'
exports.isNode = runtime === 'node'
exports.isBrowser = runtime === 'browser'
exports.isWindows = platform === 'win32'
exports.isLinux = platform === 'linux'
exports.isMac = platform === 'darwin'
exports.isIOS = platform === 'ios' || platform === 'ios-simulator'
exports.isAndroid = platform === 'android'
exports.isElectron = typeof process !== 'undefined' && !!global.process.versions?.electron
exports.isElectronRenderer = exports.isElectron && global.process.type === 'renderer'
exports.isElectronWorker = exports.isElectron && global.process.type === 'worker'
{
  "name": "which-runtime",
  "version": "1.4.0",
  "description": "Detect if you are in Bare or Node and which os etc",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte .",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/which-runtime.git"
  },
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/which-runtime/issues"
  },
  "homepage": "https://github.com/holepunchto/which-runtime",
  "devDependencies": {
    "brittle": "^3.0.0",
    "lunte": "^1.4.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
const b4a = require('b4a')

const ALPHABET = 'ybndrfg8ejkmcpqxot1uwisza345h769'
const MIN = 0x31 // 1
const MAX = 0x7a // z
const REVERSE = new Int8Array(1 + MAX - MIN)

REVERSE.fill(-1)

for (let i = 0; i < ALPHABET.length; i++) {
  const v = ALPHABET.charCodeAt(i) - MIN
  REVERSE[v] = i
}

exports.encode = encode
exports.decode = decode
exports.ALPHABET = ALPHABET

function decode (s, out) {
  let pb = 0
  let ps = 0

  const r = s.length & 7
  const q = (s.length - r) / 8

  if (!out) out = b4a.allocUnsafe(Math.ceil(s.length * 5 / 8))

  // 0 5 2 7 4 1 6 3 (+5 mod 8)
  for (let i = 0; i < q; i++) {
    const a = quintet(s, ps++)
    const b = quintet(s, ps++)
    const c = quintet(s, ps++)
    const d = quintet(s, ps++)
    const e = quintet(s, ps++)
    const f = quintet(s, ps++)
    const g = quintet(s, ps++)
    const h = quintet(s, ps++)

    out[pb++] = (a << 3) | (b >>> 2)
    out[pb++] = ((b & 0b11) << 6) | (c << 1) | (d >>> 4)
    out[pb++] = ((d & 0b1111) << 4) | (e >>> 1)
    out[pb++] = ((e & 0b1) << 7) | (f << 2) | (g >>> 3)
    out[pb++] = ((g & 0b111) << 5) | h
  }

  if (r === 0) return out.subarray(0, pb)

  const a = quintet(s, ps++)
  const b = quintet(s, ps++)

  out[pb++] = (a << 3) | (b >>> 2)

  if (r <= 2) return out.subarray(0, pb)

  const c = quintet(s, ps++)
  const d = quintet(s, ps++)

  out[pb++] = ((b & 0b11) << 6) | (c << 1) | (d >>> 4)

  if (r <= 4) return out.subarray(0, pb)

  const e = quintet(s, ps++)

  out[pb++] = ((d & 0b1111) << 4) | (e >>> 1)

  if (r <= 5) return out.subarray(0, pb)

  const f = quintet(s, ps++)
  const g = quintet(s, ps++)

  out[pb++] = ((e & 0b1) << 7) | (f << 2) | (g >>> 3)

  if (r <= 7) return out.subarray(0, pb)

  const h = quintet(s, ps++)

  out[pb++] = ((g & 0b111) << 5) | h

  return out.subarray(0, pb)
}

function encode (buf) {
  if (typeof buf === 'string') buf = b4a.from(buf)

  const max = buf.byteLength * 8

  let s = ''

  for (let p = 0; p < max; p += 5) {
    const i = p >>> 3
    const j = p & 7

    if (j <= 3) {
      s += ALPHABET[(buf[i] >>> (3 - j)) & 0b11111]
      continue
    }

    const of = j - 3
    const h = (buf[i] << of) & 0b11111
    const l = (i >= buf.byteLength ? 0 : buf[i + 1]) >>> (8 - of)

    s += ALPHABET[h | l]
  }

  return s
}

function quintet (s, i) {
  if (i > s.length) {
    return 0
  }

  const v = s.charCodeAt(i)

  if (v < MIN || v > MAX) {
    throw Error('Invalid character in base32 input: "' + s[i] + '" at position ' + i)
  }

  const bits = REVERSE[v - MIN]

  if (bits === -1) {
    throw Error('Invalid character in base32 input: "' + s[i] + '" at position ' + i)
  }

  return bits
}
{
  "name": "z32",
  "version": "1.1.0",
  "description": "Encode & decode z-base32",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.5.3"
  },
  "devDependencies": {
    "base-x": "^4.0.0",
    "base32": "0.0.7",
    "brittle": "^3.1.3",
    "nanobench": "^3.0.0",
    "rfc4648": "^1.5.2",
    "standard": "^17.0.0"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/z32.git"
  },
  "scripts": {
    "test": "standard && brittle test.js",
    "bench": "node benchmark.js"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/z32/issues"
  },
  "homepage": "https://github.com/mafintosh/z32"
}
{
  "name": "hyper-overlay",
  "version": "0.3.13",
  "description": "Content-addressed P2P file distribution over Protomux — FastCDC chunking, multi-source fetch, resumable transfers, zero blob duplication. Files live on disk; the overlay is a thin index and transfer protocol.",
  "type": "module",
  "main": "index.js",
  "imports": {
    "#fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "#path": {
      "bare": "bare-path",
      "default": "path"
    },
    "#os": {
      "bare": "bare-os",
      "default": "os"
    },
    "#zlib": {
      "bare": "bare-zlib",
      "default": "zlib"
    }
  },
  "exports": {
    ".": "./index.js",
    "./overlay": "./lib/overlay.js",
    "./protocol": "./lib/protocol.js",
    "./messages": "./lib/messages.js",
    "./chunker": "./lib/chunker.js",
    "./chunk-scheduler": "./lib/chunk-scheduler.js",
    "./transfer": "./lib/transfer.js",
    "./file-index": "./lib/file-index.js",
    "./sync-engine": "./lib/sync-engine.js",
    "./tree": "./lib/tree.js",
    "./pointer": "./lib/pointer.js",
    "./ignore": "./lib/ignore.js",
    "./manifest": "./lib/manifest.js",
    "./package.json": "./package.json"
  },
  "scripts": {
    "test": "brittle-bare test/*.test.js test/integration/*.test.js",
    "test:node": "brittle-node test/*.test.js"
  },
  "engines": {
    "bare": ">=1.16.0"
  },
  "license": "AGPL-3.0",
  "keywords": [
    "p2p",
    "hypercore",
    "hyperbee",
    "protomux",
    "overlay",
    "content-addressed",
    "deduplication",
    "file-transfer",
    "fastcdc",
    "chunking",
    "multi-source",
    "resumable",
    "bare"
  ],
  "dependencies": {
    "b4a": "^1.0.0",
    "bare-fs": "^4.7.2",
    "bare-os": "^3.8.7",
    "bare-path": "^3.0.0",
    "bare-zlib": "^1.3.3",
    "compact-encoding": "^3.2.0",
    "corestore": "^7.0.0",
    "hyperbee": "^2.0.0",
    "hypercore-crypto": "^3.0.0",
    "protomux": "^3.0.0",
    "ready-resource": "^1.0.0",
    "sodium-universal": "^5.0.1",
    "streamx": "^2.0.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "hyperswarm": "^4.0.0",
    "@hyperswarm/testnet": "^3.1.4"
  }
}
/**
 * hyper-svc — reusable per-app daemon library
 *
 * RPC transports: UDS, HTTP, and Hyperswarm (Protomux channel).
 * Replication: Hyperswarm topic join + corestore/autobase/mux replicate.
 */

export { Service } from './lib/service.js'
export { Client } from './lib/client.js'
export { encodeFrame, FrameDecoder } from './lib/frame.js'
export { attachRpcServer, attachRpcClient } from './lib/transports/swarm-rpc.js'
/**
 * Client — RPC client for hyper-svc daemons.
 *
 * Local-only. Connects via UDS (preferred) or HTTP. Both transports speak the
 * same JSON-RPC-ish protocol; the wire format differs (length-prefixed frames
 * for UDS, POST /rpc/<method> for HTTP) but the call signature is identical.
 *
 * Discovery: try UDS first (if a path is provided and the socket is reachable),
 * fall back to HTTP. Explicit transport selection is also supported.
 *
 * Usage:
 *
 *   const client = await Client.discover({
 *     uds: '/tmp/pear-git.sock',
 *     http: 'http://127.0.0.1:4040'
 *   })
 *
 *   const orgs = await client.call('list-orgs', { limit: 10 })
 *
 *   await client.close()
 */

import http from '#node:http'
import { URL } from '#node:url'
import b4a from 'b4a'
import { stat } from '#node:fs/promises'
import { udsBackend } from './uds-backend.js'
import Hyperswarm from 'hyperswarm'
import Protomux from 'protomux'
import crypto from 'hypercore-crypto'
import { encodeFrame, FrameDecoder } from './frame.js'
import { attachRpcClient } from './transports/swarm-rpc.js'

export class Client {
  /**
   * Discover and connect to a running hyper-svc daemon.
   *
   * @param {object} opts
   * @param {string} [opts.uds] - UDS socket path. Tried first.
   * @param {string} [opts.http] - HTTP base URL (e.g. 'http://127.0.0.1:4040'). Fallback.
   * @param {'uds'|'http'} [opts.prefer] - explicit override
   * @returns {Promise<Client>}
   */
  static async discover (opts = {}) {
    const prefer = opts.prefer

    if (prefer === 'uds') {
      if (!opts.uds) throw new Error('discover({ prefer: "uds" }) requires opts.uds')
      return Client.connectUds(opts.uds)
    }
    if (prefer === 'http') {
      if (!opts.http) throw new Error('discover({ prefer: "http" }) requires opts.http')
      return Client.connectHttp(opts.http)
    }

    // Auto: UDS first if reachable, then HTTP
    if (opts.uds) {
      const reachable = await udsReachable(opts.uds)
      if (reachable) return Client.connectUds(opts.uds)
    }
    if (opts.http) {
      return Client.connectHttp(opts.http)
    }

    const tried = []
    if (opts.uds) tried.push(`uds:${opts.uds}`)
    if (opts.http) tried.push(`http:${opts.http}`)
    throw new Error(`no daemon reachable (tried: ${tried.join(', ') || 'nothing — pass uds and/or http'})`)
  }

  static async connectUds (path) {
    const { backend, name } = await udsBackend(path)
    const sock = backend.createConnection(name)
    await new Promise((resolve, reject) => {
      sock.once('connect', () => {
        sock.removeListener('error', reject)
        resolve()
      })
      sock.once('error', reject)
    })
    return new Client({ kind: 'uds', sock })
  }

  static connectHttp (base) {
    return new Client({ kind: 'http', base: base.replace(/\/+$/, '') })
  }

  /**
   * Connect to a remote daemon via Hyperswarm. Joins the topic derived from
   * `serverKey`, waits for a connection, attaches a Protomux RPC channel, and
   * (when `opts.verify` is given) confirms the peer that answered is the one
   * that was asked for.
   *
   * ⚠ `serverKey` IS NOT AN IDENTITY — IT IS ONLY A RENDEZVOUS ADDRESS.
   *
   * The topic is `hash(serverKey + salt)`, and SwarmTransport.listen() creates
   * its Hyperswarm with NO keyPair, so a server's Noise key is random per
   * process and never equals the `serverKey` clients use to find it. Anything
   * joined to that topic as a server can therefore answer, and there is no
   * cryptographic binding to check `conn.remotePublicKey` against.
   *
   * That is not hypothetical. In a pear-git-v3 fleet, a mirror joins its
   * ORIGIN's topic (the topic travels in the deployment bundle), so it is a
   * server on the exact topic clients use to reach the origin. Measured
   * 2026-08-08: `connectSwarm({serverKey: <tabertron>})` issued ON stortron was
   * answered by STORTRON ITSELF 6 times out of 6. It asked itself for the
   * origin's release index, got its own, and every artifact fetch then failed
   * with "no holder" — a wrong ANSWER, not a transport error, so nothing looked
   * broken. resync-from-origin on the same path hung twice for 300 s.
   *
   * `opts.verify` closes that hole at the application layer, where identity
   * actually lives. It receives a connected Client and returns truthy to accept.
   * Rejected peers are destroyed and the wait continues until `timeout`, so a
   * caller reaches the intended daemon or fails loudly, never silently talks to
   * the wrong one. It is layered as a callback rather than a built-in `status`
   * check because hyper-svc is generic — which handler proves identity is the
   * consumer's business, and this stays compatible with servers of any version.
   *
   * @param {object} opts
   * @param {string|Buffer} opts.serverKey - rendezvous key; derives the topic
   * @param {string} [opts.topicSalt='pear-git-v3'] - salt for topic derivation
   * @param {object} [opts.swarm] - Hyperswarm constructor options (e.g. testnet bootstrap)
   * @param {number} [opts.timeout=30000] - total ms to find an ACCEPTED peer
   * @param {(client: Client) => Promise<boolean>} [opts.verify] - identity gate
   * @returns {Promise<Client>}
   */
  static async connectSwarm (opts = {}) {
    if (!opts.serverKey) throw new Error('connectSwarm requires opts.serverKey')
    const serverKey = typeof opts.serverKey === 'string'
      ? b4a.from(opts.serverKey, 'hex')
      : opts.serverKey
    const salt = opts.topicSalt || 'pear-git-v3'
    const topic = crypto.hash(b4a.concat([serverKey, b4a.from(salt)]))
    const timeout = opts.timeout || 30_000
    const verify = typeof opts.verify === 'function' ? opts.verify : null

    const swarm = new Hyperswarm(opts.swarm || {})
    const discovery = swarm.join(topic, { server: false, client: true })

    let rejected = 0
    let client = null
    try {
      client = await new Promise((resolve, reject) => {
        let settled = false
        // NOTE: onConnection stays attached for the swarm's whole life — it is
        // deliberately NOT removed here. Connections can still arrive after a
        // peer is accepted, and a NoiseSecretStream with no 'error' listener
        // throws on reset, so detaching left later arrivals unguarded and
        // crashed the process at teardown with ECONNRESET. The listener dies
        // with the swarm when the returned Client is closed.
        const finish = (fn, arg) => {
          if (settled) return
          settled = true
          clearTimeout(timer)
          fn(arg)
        }
        const timer = setTimeout(() => {
          finish(reject, new Error('swarm-rpc: connection timeout' +
            (rejected ? ' (' + rejected + ' peer(s) answered but failed verification — ' +
              'the requested serverKey is a topic, not an identity, so other peers on ' +
              'that topic can answer)' : '')))
        }, timeout)

        const onConnection = (c) => {
          // Routine, and load-bearing: a NoiseSecretStream with no 'error'
          // listener throws on ECONNRESET, and this path DESTROYS connections
          // by design (every peer that fails verification, plus any that arrive
          // after one is accepted). Without this the first rejected peer takes
          // the whole process down. SwarmTransport._onConnection takes the same
          // posture server-side.
          c.on('error', () => {})
          if (settled) { try { c.destroy() } catch {} ; return }
          const candidate = new Client({
            kind: 'swarm',
            swarm,
            conn: c,
            rpc: attachRpcClient(Protomux.from(c))
          })
          if (!verify) return finish(resolve, candidate)

          // Verified off the critical path: keep listening while this runs, so a
          // slow or lying peer cannot stall a good one behind it.
          Promise.resolve()
            .then(() => verify(candidate))
            .then((ok) => {
              if (ok) return finish(resolve, candidate)
              rejected++
              try { c.destroy() } catch {}
            })
            .catch(() => {
              rejected++
              try { c.destroy() } catch {}
            })
        }

        swarm.on('connection', onConnection)
        discovery.flushed().catch((err) => finish(reject, err))
      })
    } catch (err) {
      // Destroy the swarm on EVERY failure path. It used to be left running: a
      // Hyperswarm holds the event loop open, so each failed connect leaked one
      // and the process never exited. That is what hung pear-git-v3's
      // basic.test.js when a mirror's origin was unreachable — 123/123 tests
      // passed, then the run never terminated.
      try { await swarm.destroy() } catch {}
      throw err
    }

    return client
  }

  constructor (opts) {
    this._kind = opts.kind
    this._sock = opts.sock || null
    this._base = opts.base || null
    this._swarm = opts.swarm || null
    this._conn = opts.conn || null
    this._rpc = opts.rpc || null
    this._closed = false

    // UDS pending request map (id → {resolve, reject})
    this._pending = new Map()
    this._nextId = 1

    if (this._kind === 'uds') {
      this._decoder = new FrameDecoder((frame) => this._onFrame(frame))
      this._sock.on('data', (chunk) => {
        try {
          this._decoder.push(chunk)
        } catch (err) {
          this._failAll(err)
          this._down()
        }
      })
      // EVENT-DRIVEN disconnect detection (fleet reconciliation contract). When the peer daemon
      // restarts (the common case: an OTA/`pgh app restart` of hpp/pgv3/etc.), the cached client's
      // socket dies. Previously 'close' only `_failAll`'d the pending map but NEVER set `_closed`,
      // and there was no 'end' handler at all — so `client.closed` stayed FALSE and long-lived
      // consumers (favela-web Writer, pgh sidecar lookups) kept handing back a DEAD client, whose
      // calls hang or reject "connection closed" forever with nothing to trigger a reconnect. Mark
      // the client CLOSED on close/end/error so `.closed` is truthy → consumers reconcile (reconnect
      // a fresh Client) on their next call. 'end' is load-bearing under bare-net (allowHalfOpen: on
      // peer-end it fires 'end' but not 'close'), so we destroy to force teardown — same posture as
      // the server-side half-open fix (hyper-svc 0.1.3).
      this._sock.on('close', () => this._down())
      this._sock.on('end', () => this._down())
      this._sock.on('error', () => this._down())
    }
  }

  get kind () { return this._kind }
  get closed () { return this._closed }

  /**
   * Make an RPC call. Throws on transport errors or remote handler errors.
   * @param {string} method
   * @param {any} [params]
   */
  async call (method, params = {}) {
    if (this._closed) throw new Error('client closed')

    if (this._kind === 'uds') return this._callUds(method, params)
    if (this._kind === 'http') return this._callHttp(method, params)
    if (this._kind === 'swarm') return this._rpc.call(method, params)
    throw new Error('unknown client kind: ' + this._kind)
  }

  _callUds (method, params) {
    const id = this._nextId++
    return new Promise((resolve, reject) => {
      this._pending.set(id, { resolve, reject })
      try {
        this._sock.write(encodeFrame({ id, method, params }))
      } catch (err) {
        this._pending.delete(id)
        reject(err)
      }
    })
  }

  _onFrame (frame) {
    if (frame == null || (typeof frame.id !== 'number' && typeof frame.id !== 'string')) {
      // Malformed response, can't match it to a caller
      return
    }
    const pending = this._pending.get(frame.id)
    if (!pending) return
    this._pending.delete(frame.id)

    if (frame.error) {
      pending.reject(new Error(frame.error))
    } else {
      pending.resolve(frame.result)
    }
  }

  _failAll (err) {
    for (const [, pending] of this._pending) pending.reject(err)
    this._pending.clear()
  }

  // The socket died (peer restarted / errored / half-open end). Mark the client CLOSED so any
  // consumer's `.closed` check reconnects, fail every in-flight call, and force teardown. Idempotent.
  _down () {
    if (this._closed) return
    this._closed = true
    this._failAll(new Error('connection closed'))
    if (this._sock) { try { this._sock.destroy() } catch {} }
  }

  async _callHttp (method, params) {
    const url = new URL(`${this._base}/rpc/${encodeURIComponent(method)}`)
    return new Promise((resolve, reject) => {
      const body = JSON.stringify(params)
      const req = http.request({
        method: 'POST',
        hostname: url.hostname,
        port: url.port || 80,
        path: url.pathname + url.search,
        headers: {
          'Content-Type': 'application/json',
          'Content-Length': b4a.byteLength(body)
        }
      }, (res) => {
        const parts = []
        res.on('data', (c) => parts.push(c))
        res.on('end', () => {
          const text = b4a.concat(parts).toString('utf8')
          let parsed
          try {
            parsed = JSON.parse(text)
          } catch {
            return reject(new Error(`bad JSON response (status ${res.statusCode}): ${text.slice(0, 200)}`))
          }
          if (res.statusCode >= 200 && res.statusCode < 300) {
            return resolve(parsed.result)
          }
          return reject(new Error(parsed.error || `HTTP ${res.statusCode}`))
        })
        res.on('error', reject)
      })
      req.on('error', reject)
      req.write(body)
      req.end()
    })
  }

  async close () {
    if (this._closed) return
    this._closed = true
    if (this._sock) {
      this._failAll(new Error('client closed'))
      try { this._sock.destroy() } catch {}
      this._sock = null
    }
    if (this._rpc) {
      try { this._rpc.close() } catch {}
      this._rpc = null
    }
    if (this._conn) {
      try { this._conn.destroy() } catch {}
      this._conn = null
    }
    if (this._swarm) {
      try { await this._swarm.destroy() } catch {}
      this._swarm = null
    }
  }
}

async function udsReachable (path) {
  const { backend, name, abstract } = await udsBackend(path)
  // Pathname sockets: verify the file exists and is actually a socket first.
  // Abstract sockets have no filesystem entry — skip straight to the connect probe.
  if (!abstract) {
    try {
      const s = await stat(path)
      if (!s.isSocket()) return false
    } catch {
      return false
    }
  }
  // Try a real connect — covers stale sockets where the daemon crashed
  return new Promise((resolve) => {
    const sock = backend.createConnection(name)
    sock.once('connect', () => {
      sock.destroy()
      resolve(true)
    })
    sock.once('error', () => {
      sock.destroy()
      resolve(false)
    })
  })
}
/**
 * Length-prefixed JSON framing.
 *
 * Wire format: [4 bytes BE length][JSON payload].
 *
 * One frame = one JSON object. Multiple frames can be pipelined on a single
 * stream — FrameDecoder handles incremental reads where a frame may arrive
 * across multiple data chunks.
 */

import b4a from 'b4a'

const MAX_FRAME = 16 * 1024 * 1024 // 16 MiB hard cap to avoid runaway buffers

export function encodeFrame (obj) {
  const json = JSON.stringify(obj)
  const payload = b4a.from(json, 'utf8')
  if (payload.length > MAX_FRAME) {
    throw new Error(`Frame too large: ${payload.length} > ${MAX_FRAME}`)
  }
  const frame = b4a.alloc(4 + payload.length)
  frame.writeUInt32BE(payload.length, 0)
  payload.copy(frame, 4)
  return frame
}

export class FrameDecoder {
  /**
   * @param {(obj: any) => void} onFrame - called once per complete frame
   */
  constructor (onFrame) {
    if (typeof onFrame !== 'function') throw new Error('onFrame is required')
    this._onFrame = onFrame
    this._buf = b4a.alloc(0)
  }

  /**
   * Feed a chunk into the decoder. Calls onFrame for each complete frame.
   * Throws if a frame exceeds MAX_FRAME or contains invalid JSON.
   */
  push (chunk) {
    this._buf = b4a.concat([this._buf, chunk])

    while (this._buf.length >= 4) {
      const len = this._buf.readUInt32BE(0)
      if (len > MAX_FRAME) {
        throw new Error(`Frame too large: ${len} > ${MAX_FRAME}`)
      }
      if (this._buf.length < 4 + len) break // wait for more bytes

      const payload = this._buf.subarray(4, 4 + len)
      this._buf = this._buf.subarray(4 + len)

      const json = b4a.toString(payload, 'utf8')
      const obj = JSON.parse(json) // throws on bad JSON
      this._onFrame(obj)
    }
  }

  /** Number of bytes currently buffered (waiting for the rest of a frame). */
  get pending () { return this._buf.length }
}
/**
 * Service — reusable per-app daemon library.
 *
 * One instance per app process. Owns:
 *   - Generic RPC handler registry (svc.handle)
 *   - Module mounts (svc.mount) with optional swarm replication
 *   - UDS, HTTP, and Hyperswarm transport instances (whichever the consumer enables)
 *
 * The consumer's corestore is passed in (or one is implied via swarm.corestore).
 * The Service does NOT create or own storage — that's the app's job.
 *
 * Local-only RPC. Peers exchange data via swarm replication, never commands.
 *
 * Usage:
 *
 *   const svc = new Service({
 *     name: 'pear-git',
 *     corestore: store,
 *     uds: '/tmp/pear-git.sock',
 *     http: { port: 4040 },
 *     swarm: { topic: '...32 bytes hex...' }
 *   })
 *
 *   svc.mount('orgs', new HyperOrgs(store, { namespace: 'orgs' }))
 *
 *   svc.handle('list-orgs', async (ctx, params) => {
 *     return svc.modules.orgs.list()
 *   })
 *
 *   await svc.listen()
 */

import process from '#node:process'
import ReadyResource from 'ready-resource'
import { UdsServer } from './transports/uds.js'
import { HttpServer } from './transports/http.js'
import { SwarmTransport } from './transports/swarm.js'

class NoSuchMethodError extends Error {
  constructor (method) {
    super(`unknown method: ${method}`)
    this.code = 'ENOMETHOD'
  }
}

class AnonymousDeniedError extends Error {
  constructor (method) {
    super(`anonymous access denied: ${method}`)
    this.code = 'EDENIED'
    this.status = 403
  }
}

/**
 * Default "is this caller anonymous?" predicate.
 *
 * Deliberately conservative — anything that is not clearly an authenticated
 * caller counts as anonymous. Consumers whose ctx carries richer identity
 * (pear-git-v3 has four distinct shapes) should pass their own via
 * opts.isAnonymous rather than widen this one.
 */
function defaultIsAnonymous (ctx) {
  if (!ctx) return true
  if (ctx.transport === 'uds') return false // local operator holds the socket
  return !ctx.identity
}

export class Service extends ReadyResource {
  /**
   * @param {object} opts
   * @param {string} opts.name - service name (used for default UDS path, logging)
   * @param {object} [opts.corestore] - required if swarm transport is enabled
   * @param {string} [opts.uds] - UDS socket path. Pass null/undefined to disable.
   * @param {object} [opts.http] - HTTP transport options { port, host }. Disable by omitting.
   * @param {object} [opts.swarm] - Swarm options { topic, swarm? }. Disable by omitting.
   */
  constructor (opts = {}) {
    super()
    if (!opts.name) throw new Error('Service requires opts.name')

    this._name = opts.name
    this._corestore = opts.corestore || null
    this._handlers = new Map()
    this._mounts = new Map()

    // Anonymous-dispatch policy (pear-git org #12).
    //
    // Every registered handler used to be callable by anyone, over HTTP and
    // over swarm-rpc, with no allowlist and no auth gate — so each new
    // svc.handle() was silently world-callable, and a daemon behind a public
    // reverse proxy exposed its entire RPC surface to the internet.
    //
    // Default stays 'allow' so the existing consumers (pear-git-v3, hypernote,
    // hyper-social-web, pgh-sidecar) are untouched until they opt in. Under
    // 'deny', a handler must declare `{ anonymous: true }` at registration to
    // be reachable by an unauthenticated caller.
    //
    // Opt-in at REGISTRATION rather than via a separate allowlist table: with
    // ~100 handlers a table drifts out of step with the handler set, whereas a
    // flag cannot. And the drift direction is safe — a handler nobody marked
    // is DENIED, which surfaces as a visible 403 rather than a silent hole.
    this._anonymousPolicy = opts.anonymousPolicy === 'deny' ? 'deny' : 'allow'
    this._isAnonymous = typeof opts.isAnonymous === 'function'
      ? opts.isAnonymous
      : defaultIsAnonymous
    // Called with ({ method, ctx }) whenever a dispatch is refused, so the
    // consumer can record denials alongside its own audit trail.
    this._onDeny = typeof opts.onDeny === 'function' ? opts.onDeny : null
    this._anonymousAllowed = new Set()

    this._udsOpt = opts.uds || null
    this._httpOpt = opts.http || null
    this._swarmOpt = opts.swarm || null

    this._uds = null
    this._http = null
    this._swarm = null

    if (this._swarmOpt && !this._corestore) {
      throw new Error('Service: swarm transport requires opts.corestore')
    }

    // Instantiate transports eagerly so apps can register HTTP routes,
    // grab the UDS path, etc., BEFORE calling listen().
    const dispatch = (method, params, ctx) => this.dispatch(method, params, ctx)

    if (this._udsOpt) {
      this._uds = new UdsServer({ path: this._udsOpt, dispatch })
    }
    if (this._httpOpt) {
      this._http = new HttpServer({
        port: this._httpOpt.port,
        host: this._httpOpt.host,
        prefix: this._httpOpt.prefix,
        ctxFactory: this._httpOpt.ctxFactory,
        dispatch
      })
    }
    if (this._swarmOpt) {
      this._swarm = new SwarmTransport({
        topic: this._swarmOpt.topic,
        corestore: this._corestore,
        mounts: () => this._listMounts(),
        dispatch: this._swarmOpt.rpc !== false ? dispatch : null,
        swarm: this._swarmOpt.swarm,
        server: this._swarmOpt.server,
        client: this._swarmOpt.client
      })
    }
  }

  // ── Properties ──────────────────────────────────────────────

  get name () { return this._name }
  get corestore () { return this._corestore }

  /** Read-only handle to the UDS transport (or null if disabled). */
  get uds () { return this._uds }

  /** Read-only handle to the HTTP transport (or null if disabled). */
  get http () { return this._http }

  /** Read-only handle to the swarm transport (or null if disabled). */
  get swarm () { return this._swarm }

  /**
   * Mounted modules, accessible by name. Use `svc.modules.orgs` after
   * `svc.mount('orgs', orgsInstance)`.
   */
  get modules () {
    // Lazily build a property-style accessor object on top of the map
    if (!this._modulesProxy) {
      const map = this._mounts
      this._modulesProxy = new Proxy({}, {
        get (_target, prop) {
          const m = map.get(prop)
          return m ? m.instance : undefined
        },
        has (_target, prop) {
          return map.has(prop)
        },
        ownKeys () {
          return Array.from(map.keys())
        },
        getOwnPropertyDescriptor (_target, prop) {
          if (map.has(prop)) {
            return { enumerable: true, configurable: true, value: map.get(prop).instance }
          }
        }
      })
    }
    return this._modulesProxy
  }

  /** Map iteration: list mount entries as { name, instance }. */
  _listMounts () {
    const out = []
    for (const [name, m] of this._mounts) out.push({ name, instance: m.instance })
    return out
  }

  // ── Registration ────────────────────────────────────────────

  /**
   * Register an RPC handler. The handler is invoked from any RPC transport
   * with `(ctx, params)` and should return a JSON-serializable result.
   *
   * @param {string} name - method name (e.g. "list-orgs")
   * @param {(ctx: object, params: any) => Promise<any>|any} fn
   */
  handle (name, fn, opts = {}) {
    if (typeof name !== 'string' || !name) throw new Error('handle requires a name')
    if (typeof fn !== 'function') throw new Error('handle requires a function')
    if (this._handlers.has(name)) throw new Error(`handler "${name}" already registered`)
    this._handlers.set(name, fn)
    // `anonymous: true` opts this method IN to unauthenticated dispatch when
    // the service runs anonymousPolicy: 'deny'. Absent = denied, which is the
    // safe default for a handler nobody has classified yet.
    if (opts && opts.anonymous === true) this._anonymousAllowed.add(name)
  }

  /** Is this method callable by an unauthenticated caller? */
  allowsAnonymous (name) { return this._anonymousAllowed.has(name) }

  /** Methods explicitly opted in to anonymous dispatch, sorted. */
  listAnonymous () { return Array.from(this._anonymousAllowed).sort() }

  /** Whether a handler is registered. */
  hasHandler (name) { return this._handlers.has(name) }

  /** List registered handler names. */
  listHandlers () { return Array.from(this._handlers.keys()).sort() }

  /**
   * Mount a module instance. Modules are accessible via `svc.modules.<name>`.
   * If the module exposes a `.base` (Autobase consumer) and the swarm
   * transport is enabled, the base is replicated on every swarm connection.
   *
   * @param {string} name
   * @param {object} instance
   */
  mount (name, instance) {
    if (typeof name !== 'string' || !name) throw new Error('mount requires a name')
    if (!instance) throw new Error('mount requires an instance')
    if (this._mounts.has(name)) throw new Error(`mount "${name}" already registered`)
    this._mounts.set(name, { instance })
  }

  /** Whether a module is mounted. */
  hasMount (name) { return this._mounts.has(name) }

  /** List mounted module names. */
  listMounts () { return Array.from(this._mounts.keys()).sort() }

  // ── Dispatch ────────────────────────────────────────────────

  /**
   * Dispatch a method call to its handler. Used by all RPC transports.
   * Throws NoSuchMethodError (code: 'ENOMETHOD') if the method isn't registered.
   */
  async dispatch (method, params, ctx) {
    const handler = this._handlers.get(method)
    if (!handler) throw new NoSuchMethodError(method)

    // Anonymous gate (#12). Runs for EVERY transport, because the surface was
    // open on all of them — HTTP via a public reverse proxy, and swarm-rpc to
    // any peer that knows the topic.
    //
    // Ordered after the ENOMETHOD check on purpose: an unknown method should
    // still say so, otherwise the gate turns every typo into a 403 and makes
    // the API undebuggable. It leaks only which method names exist, which the
    // handler list already exposes.
    if (this._anonymousPolicy === 'deny' && !this._anonymousAllowed.has(method)) {
      let anon = true
      try {
        anon = this._isAnonymous(ctx)
      } catch {
        anon = true // a predicate that throws must fail CLOSED
      }
      if (anon) {
        if (this._onDeny) {
          try { this._onDeny({ method, ctx, reason: 'anonymous' }) } catch {}
        }
        throw new AnonymousDeniedError(method)
      }
    }

    return handler(ctx || {}, params)
  }

  // ── Lifecycle ───────────────────────────────────────────────

  async _open () {
    if (this._uds) await this._uds.listen()
    if (this._http) await this._http.listen()
    if (this._swarm) await this._swarm.listen()
  }

  /**
   * Alias for `ready()` — feels more natural for a daemon ("start listening").
   */
  async listen () {
    await this.ready()
  }

  async _close () {
    const errors = []
    if (this._swarm) try { await this._swarm.close() } catch (e) { errors.push(e) }
    if (this._http) try { await this._http.close() } catch (e) { errors.push(e) }
    if (this._uds) try { await this._uds.close() } catch (e) { errors.push(e) }
    this._swarm = null
    this._http = null
    this._uds = null
    if (errors.length) {
      const msg = errors.map(e => e.message).join('; ')
      throw new Error('Service close errors: ' + msg)
    }
  }
}
/**
 * HTTP transport for hyper-svc.
 *
 * Local-only RPC. Browsers (or curl, or any HTTP client) on the same machine
 * POST a JSON body to /rpc/<method> and receive a JSON response.
 *
 * Wire protocol:
 *   POST /rpc/<method>
 *   Content-Type: application/json
 *   { ...params... }
 *
 *   →  200 application/json  { result: ... }
 *      400 application/json  { error: ... }   (bad request / handler threw)
 *      404 application/json  { error: 'unknown method' }
 *
 * Other routes are NOT handled by hyper-svc — apps wire their own SSR pages
 * via the underlying http.Server (exposed as `.server` on this class). Any
 * request not matching POST /rpc/<method> falls through to user-registered
 * 'request' listeners or, if none, returns 404.
 */

import http from '#node:http'
import b4a from 'b4a'

export class HttpServer {
  /**
   * @param {object} opts
   * @param {number} [opts.port=0] - 0 = random port
   * @param {string} [opts.host='127.0.0.1'] - bind address (local-only by default)
   * @param {string} [opts.prefix=''] - URL prefix to strip before matching /rpc/* (e.g. '/git')
   * @param {(method: string, params: any, ctx: object) => Promise<any>} opts.dispatch - request handler
   */
  constructor (opts = {}) {
    if (typeof opts.dispatch !== 'function') throw new Error('HttpServer requires opts.dispatch')

    this._port = opts.port || 0
    this._host = opts.host || '127.0.0.1'
    this._dispatch = opts.dispatch
    // Optional URL prefix (e.g. '/git') stripped before matching /rpc/*. Set
    // when the daemon is reverse-proxied OR accessed directly under a path
    // prefix that the browser bakes into outgoing fetch URLs. Without this,
    // direct (non-proxied) hits to `<host>/<prefix>/rpc/*` fall through both
    // hyper-svc's listener (which only matches '/rpc/') and the consumer's
    // listener (which strips the prefix and skips '/rpc/' assuming hyper-svc
    // already handled it) — neither responds and the request hangs.
    this._prefix = normalizePrefix(opts.prefix)
    // Optional consumer-provided ctx builder. Called per /rpc/* request to
    // populate fields like identity from request headers/cookies. Receives
    // (req) and may return either an object or a Promise<object>. The
    // returned fields are merged into the default ctx ({ transport: 'http',
    // identity: null, req, res }).
    this._ctxFactory = typeof opts.ctxFactory === 'function' ? opts.ctxFactory : null
    this._listening = false

    // Create the server eagerly so apps can register routes BEFORE listen().
    // Our /rpc/* listener is installed first so it has first dibs on requests.
    this._server = http.createServer()
    this._server.on('request', (req, res) => this._onRequest(req, res))
  }

  /**
   * Update or set the ctxFactory after construction. Useful when the
   * factory needs references that don't exist at constructor time
   * (e.g. session stores created by the consumer in a later step).
   */
  setCtxFactory (fn) {
    if (fn != null && typeof fn !== 'function') {
      throw new Error('ctxFactory must be a function or null')
    }
    this._ctxFactory = fn
  }

  /** Underlying http.Server. Apps register their own routes here. */
  get server () { return this._server }
  get listening () { return this._listening }
  get port () {
    if (!this._listening || !this._server) return null
    const addr = this._server.address()
    return addr ? addr.port : null
  }
  get host () { return this._host }

  async listen () {
    if (this._listening) return

    await new Promise((resolve, reject) => {
      this._server.once('error', reject)
      this._server.listen(this._port, this._host, () => {
        this._server.removeListener('error', reject)
        resolve()
      })
    })

    this._listening = true
  }

  async _onRequest (req, res) {
    // Compute the path with the configured prefix removed. Don't mutate
    // req.url — consumers' own request listeners may have their own
    // prefix-stripping logic and should see the original.
    let path = req.url
    if (this._prefix && path.startsWith(this._prefix)) {
      const rest = path.slice(this._prefix.length)
      // Only treat as a prefix match when the next char is '/' (or end of
      // URL). Otherwise '/gitfoo' would falsely match prefix '/git'.
      if (rest === '' || rest[0] === '/' || rest[0] === '?') {
        path = rest || '/'
      }
    }

    if (req.method === 'POST' && path.startsWith('/rpc/')) {
      const method = path.slice('/rpc/'.length).split('?')[0]
      let body
      try {
        body = await collectBody(req)
      } catch (err) {
        return jsonError(res, 400, 'failed to read body: ' + err.message)
      }

      let params = {}
      if (body.length > 0) {
        try {
          params = JSON.parse(b4a.toString(body, 'utf8'))
        } catch {
          return jsonError(res, 400, 'request body must be JSON')
        }
      }

      let ctx = {
        transport: 'http',
        identity: null, // anonymous by default — apps populate via ctxFactory
        req,
        res
      }

      if (this._ctxFactory) {
        try {
          const extra = await this._ctxFactory(req)
          if (extra && typeof extra === 'object') {
            ctx = { ...ctx, ...extra }
          }
        } catch (err) {
          return jsonError(res, 500, 'ctxFactory failed: ' + (err.message || String(err)))
        }
      }

      try {
        const result = await this._dispatch(method, params, ctx)
        if (result === undefined) {
          return jsonOk(res, { result: null })
        }
        return jsonOk(res, { result })
      } catch (err) {
        if (err && err.code === 'ENOMETHOD') {
          return jsonError(res, 404, err.message)
        }
        // An anonymous-gate denial is an authorization outcome, not a bad
        // request — surface it as 403 so callers (and the audit trail) can
        // tell "you may not" from "you sent nonsense".
        if (err && err.code === 'EDENIED') {
          return jsonError(res, err.status || 403, err.message)
        }
        return jsonError(res, 400, err.message || String(err))
      }
    }

    // Not an /rpc/ request. App-owned routes live in OTHER 'request'
    // listeners (registered on this._server by the consumer). If at least
    // one other listener is present, leave the response to them — they're
    // responsible for handling and 404-ing as needed.
    //
    // If we're the ONLY 'request' listener, nobody else will handle this,
    // so we 404 it synchronously. Doing this synchronously avoids a race
    // where setImmediate fires before an async user handler can respond.
    if (this._server.listenerCount('request') <= 1) {
      res.writeHead(404, { 'Content-Type': 'text/plain' })
      res.end('Not found')
    }
    // Otherwise: leave the response to the user's listener.
  }

  async close () {
    if (!this._server || !this._listening) {
      this._listening = false
      return
    }
    await new Promise((resolve) => this._server.close(() => resolve()))
    this._listening = false
  }
}

function collectBody (req) {
  return new Promise((resolve, reject) => {
    const parts = []
    req.on('data', (c) => parts.push(c))
    req.on('end', () => resolve(b4a.concat(parts)))
    req.on('error', reject)
  })
}

function jsonOk (res, body) {
  res.writeHead(200, { 'Content-Type': 'application/json' })
  res.end(JSON.stringify(body))
}

function jsonError (res, status, message) {
  res.writeHead(status, { 'Content-Type': 'application/json' })
  res.end(JSON.stringify({ error: message }))
}

function normalizePrefix (p) {
  if (!p || typeof p !== 'string') return ''
  // Strip trailing slashes so '/git/' and '/git' behave identically.
  let s = p.replace(/\/+$/, '')
  // A bare '/' is not a real prefix.
  if (s === '' || s === '/') return ''
  // Require a leading slash so callers can't accidentally pass 'git'.
  if (s[0] !== '/') s = '/' + s
  return s
}
/**
 * Swarm-RPC transport for hyper-svc.
 *
 * Adds a Protomux RPC channel on every Hyperswarm connection. Requests
 * and responses use the same length-prefixed JSON framing as UDS (see
 * frame.js), multiplexed over the Noise-encrypted swarm stream.
 *
 * This transport extends the existing SwarmTransport (replication) with
 * request/response dispatch. A single swarm connection carries:
 *   1. Hypercore/Autobase replication (corestore.replicate)
 *   2. Module mux channels (attachProtocol)
 *   3. RPC frames (this module)
 *
 * Wire protocol over Protomux:
 *   Channel: 'hyper-svc-rpc'
 *   Message type 0 (request):  { id, method, params }
 *   Message type 1 (response): { id, result } | { id, error }
 *
 * Auth: the caller's Noise public key is available on the connection.
 * For pear-git-v3, envelope auth (Phase 2a) is layered on top — the
 * RPC payload itself is a signed envelope, verified by the dispatch
 * handler. The transport just provides the Noise tunnel.
 */

import Protomux from 'protomux'
import c from 'compact-encoding'
import b4a from 'b4a'

const PROTOCOL = 'hyper-svc-rpc'

/**
 * Attach an RPC channel to a Protomux instance (one per swarm connection).
 *
 * Server-side: receives requests, calls dispatch, sends responses.
 *
 * @param {Protomux} mux — the protomux for this connection
 * @param {Function} dispatch — (method, params, ctx) => result
 * @param {object} [opts]
 * @param {Buffer} [opts.remotePublicKey] — peer's Noise pubkey (for ctx)
 * @returns {{ channel, close: () => void }}
 */
export function attachRpcServer (mux, dispatch, opts = {}) {
  const channel = mux.createChannel({
    protocol: PROTOCOL,
    onopen () {},
    onclose () {}
  })

  if (!channel) return null // protocol already claimed on this mux

  const requestType = channel.addMessage({
    encoding: c.json,
    onmessage (msg) {
      handleRequest(msg, channel, responseType, dispatch, opts)
    }
  })

  const responseType = channel.addMessage({
    encoding: c.json,
    onmessage () {} // server doesn't receive responses
  })

  channel.open()

  return { channel, close: () => channel.close() }
}

/**
 * Attach an RPC channel to a Protomux instance (client-side).
 *
 * Client-side: sends requests, receives responses.
 *
 * @param {Protomux} mux
 * @returns {{ call: (method, params) => Promise<any>, close: () => void }}
 */
export function attachRpcClient (mux) {
  let nextId = 1
  const pending = new Map() // id → { resolve, reject }

  const channel = mux.createChannel({
    protocol: PROTOCOL,
    onopen () {},
    onclose () {
      // Reject all pending calls on channel close.
      for (const [id, p] of pending) {
        p.reject(new Error('swarm-rpc channel closed'))
        pending.delete(id)
      }
    }
  })

  if (!channel) throw new Error('swarm-rpc: protocol already claimed')

  const requestType = channel.addMessage({
    encoding: c.json,
    onmessage () {} // client doesn't receive requests
  })

  const responseType = channel.addMessage({
    encoding: c.json,
    onmessage (msg) {
      const p = pending.get(msg.id)
      if (!p) return // stale or unknown id
      pending.delete(msg.id)
      if (msg.error) {
        const err = new Error(msg.error)
        err.code = msg.code || null
        p.reject(err)
      } else {
        p.resolve(msg.result)
      }
    }
  })

  channel.open()

  return {
    call (method, params) {
      return new Promise((resolve, reject) => {
        const id = nextId++
        pending.set(id, { resolve, reject })
        requestType.send({ id, method, params })
      })
    },
    close () {
      channel.close()
    }
  }
}

// --- internals ---

async function handleRequest (msg, channel, responseType, dispatch, opts) {
  const { id, method, params } = msg
  if (!id || !method) {
    responseType.send({ id: id || 0, error: 'invalid request (missing id or method)' })
    return
  }

  const ctx = {
    transport: 'swarm-rpc',
    identity: {
      type: 'swarm',
      remotePublicKey: opts.remotePublicKey
        ? b4a.toString(opts.remotePublicKey, 'hex')
        : null,
      trust: 'network'
    }
  }

  try {
    const result = await dispatch(method, params || {}, ctx)
    responseType.send({ id, result: result !== undefined ? result : null })
  } catch (err) {
    responseType.send({
      id,
      error: err.message || String(err),
      code: err.code || null
    })
  }
}
/**
 * Hyperswarm transport for hyper-svc.
 *
 * Joins a topic, and on every connection:
 *   1. corestore.replicate(conn) — replicates all hypercores in the corestore
 *   2. for each mounted module exposing a `.base` (Autobase consumer), also
 *      base.replicate(conn) — belt-and-suspenders against the autobase
 *      replication gotcha (corestore.replicate alone is unreliable in tests
 *      and we don't want to chase that bug in production)
 *   3. for each mounted module exposing `attachProtocol(mux)` (mux-based
 *      protocols like hyper-overlay), lazily build `Protomux.from(conn)`
 *      once per connection and call attachProtocol on each consumer.
 *      Protomux.from reuses any protomux already attached by corestore/autobase
 *      replication, so channels multiplex cleanly over the same transport.
 *
 * No RPC over swarm today — modules communicate either via replication or
 * via their own mux channels. Adding a new mux-based protocol only requires
 * exposing `attachProtocol(mux)` on the mounted module.
 */

import Hyperswarm from 'hyperswarm'
import Protomux from 'protomux'
import b4a from 'b4a'
import { attachRpcServer } from './swarm-rpc.js'

export class SwarmTransport {
  /**
   * @param {object} opts
   * @param {Buffer|string} opts.topic - 32-byte topic to join (hex string or buffer)
   * @param {object} opts.corestore - corestore to replicate
   * @param {() => Iterable<{ name: string, instance: object }>} opts.mounts - returns the current mount list (called on each connection so late mounts work)
   * @param {Function} [opts.dispatch] - RPC dispatch function. When provided, a swarm-RPC Protomux channel is attached to every connection.
   * @param {object} [opts.swarm] - hyperswarm options (e.g., bootstrap nodes for testnet)
   * @param {boolean} [opts.server=true]
   * @param {boolean} [opts.client=true]
   */
  constructor (opts = {}) {
    if (!opts.topic) throw new Error('SwarmTransport requires opts.topic')
    if (!opts.corestore) throw new Error('SwarmTransport requires opts.corestore')
    if (typeof opts.mounts !== 'function') throw new Error('SwarmTransport requires opts.mounts (function)')

    this._topic = typeof opts.topic === 'string' ? b4a.from(opts.topic, 'hex') : opts.topic
    if (this._topic.length !== 32) throw new Error('topic must be 32 bytes')

    this._corestore = opts.corestore
    this._getMounts = opts.mounts
    this._dispatch = opts.dispatch || null
    this._swarmOpts = opts.swarm || {}
    this._joinAsServer = opts.server !== false
    this._joinAsClient = opts.client !== false

    this._swarm = null
    this._discovery = null
    this._listening = false
    this._connections = new Set()
  }

  get topic () { return this._topic }
  get listening () { return this._listening }
  get swarm () { return this._swarm }
  get connections () { return this._connections.size }

  async listen () {
    if (this._listening) return

    this._swarm = new Hyperswarm(this._swarmOpts)
    this._swarm.on('connection', (conn, info) => this._onConnection(conn, info))

    this._discovery = this._swarm.join(this._topic, {
      server: this._joinAsServer,
      client: this._joinAsClient
    })
    await this._discovery.flushed()
    this._listening = true
  }

  /**
   * Join an ADDITIONAL topic on this same shared swarm (Keet activateRoom
   * pattern — one Hyperswarm, many topics). Used to rendezvous for a
   * specific room (per-org / per-repo autobase) by its discoveryKey, so
   * peers find each other for that room without needing the daemon's
   * identity topic. Replication still rides the single `_onConnection`
   * (corestore.replicate + per-mount replicate). Deduped + idempotent.
   *
   * @param {Buffer|string} topic - 32-byte discoveryKey (hex or buffer)
   * @param {object} [opts] - { server=true, client=true }
   * @returns {object|null} the PeerDiscovery handle (or existing one)
   */
  joinTopic (topic, opts = {}) {
    if (!this._swarm) return null // not listening yet
    const t = typeof topic === 'string' ? b4a.from(topic, 'hex') : topic
    if (!t || t.length !== 32) return null
    const key = b4a.toString(t, 'hex')
    if (!this._extraTopics) this._extraTopics = new Map()
    if (this._extraTopics.has(key)) return this._extraTopics.get(key)
    const { server = true, client = true } = opts
    const disc = this._swarm.join(t, { server, client })
    this._extraTopics.set(key, disc)
    return disc
  }

  /** discoveryKeys of every additional room topic joined via joinTopic. */
  get joinedRoomTopics () {
    return this._extraTopics ? Array.from(this._extraTopics.keys()) : []
  }

  _onConnection (conn, info) {
    this._connections.add(conn)
    conn.on('close', () => this._connections.delete(conn))
    conn.on('error', () => { /* connection errors are routine — ignore */ })

    // Always replicate the corestore. Hypercore handles muxing internally.
    try {
      this._corestore.replicate(conn)
    } catch (err) {
      // Don't crash on replication setup errors — log via stderr
      // eslint-disable-next-line no-console
      console.error('[hyper-svc/swarm] corestore.replicate failed:', err.message)
    }

    // Belt and suspenders: also call base.replicate on every mounted Autobase
    // consumer. This is the documented workaround for the test-time gotcha
    // where corestore.replicate alone doesn't propagate writer cores.
    //
    // In the same pass, wire up mux-based protocols: any mount exposing
    // `attachProtocol(mux)` (hyper-overlay and future consumers) gets attached
    // to a single Protomux per connection. Protomux.from reuses any protomux
    // corestore/autobase replication already set up.
    let mux = null
    for (const { name, instance } of this._getMounts()) {
      if (!instance) continue

      // A mount may expose `replicate(conn)` to replicate its own
      // autobase(s) — required for MULTI-autobase mounts (e.g. per-org
      // HyperOrgs) whose single `.base` getter is undefined or THROWS.
      // Otherwise fall back to the single-autobase `.base.replicate`.
      // The whole access is wrapped: a throwing `.base` getter must
      // never abort the daemon on an incoming connection.
      try {
        if (typeof instance.replicate === 'function') {
          instance.replicate(conn)
        } else {
          const base = instance.base
          if (base && typeof base.replicate === 'function') base.replicate(conn)
        }
      } catch (err) {
        // eslint-disable-next-line no-console
        console.error(`[hyper-svc/swarm] ${name} replicate failed:`, err.message)
      }

      if (typeof instance.attachProtocol === 'function') {
        if (!mux) {
          try {
            mux = Protomux.from(conn)
          } catch (err) {
            // eslint-disable-next-line no-console
            console.error('[hyper-svc/swarm] Protomux.from failed:', err.message)
          }
        }
        if (mux) {
          try {
            instance.attachProtocol(mux)
          } catch (err) {
            // eslint-disable-next-line no-console
            console.error(`[hyper-svc/swarm] ${name}.attachProtocol failed:`, err.message)
          }
        }
      }
    }

    // Swarm-RPC channel — attach only when dispatch is configured.
    // Multiplexes cleanly over the same Noise stream as replication
    // and module protocols above.
    if (this._dispatch) {
      if (!mux) {
        try {
          mux = Protomux.from(conn)
        } catch (err) {
          // eslint-disable-next-line no-console
          console.error('[hyper-svc/swarm] Protomux.from failed (rpc):', err.message)
        }
      }
      if (mux) {
        try {
          attachRpcServer(mux, this._dispatch, {
            remotePublicKey: conn.remotePublicKey || null
          })
        } catch (err) {
          // eslint-disable-next-line no-console
          console.error('[hyper-svc/swarm] attachRpcServer failed:', err.message)
        }
      }
    }
  }

  async close () {
    if (!this._swarm) return
    for (const conn of this._connections) {
      try { conn.destroy() } catch {}
    }
    this._connections.clear()
    try { await this._swarm.destroy() } catch {}
    this._swarm = null
    this._discovery = null
    this._listening = false
  }
}
/**
 * UDS (Unix Domain Socket) transport for hyper-svc.
 *
 * Local-only RPC. Trusts the local user. CLIs on the same machine connect
 * to ~/.local/share/<name>/svc.sock (or wherever the daemon was told to bind)
 * and exchange length-prefixed JSON frames.
 *
 * Wire protocol per connection:
 *   client → server: { id, method, params }
 *   server → client: { id, result }   OR   { id, error }
 *
 * Multiple in-flight requests are matched by id. Server is fully async —
 * a slow handler doesn't block other requests on the same connection.
 */

import process from '#node:process'
import { unlink, stat } from '#node:fs/promises'
import { encodeFrame, FrameDecoder } from '../frame.js'
import { udsBackend, isAbstract } from '../uds-backend.js'

export class UdsServer {
  /**
   * @param {object} opts
   * @param {string} opts.path - filesystem path for the UNIX socket
   * @param {(method: string, params: any, ctx: object) => Promise<any>} opts.dispatch - request handler
   */
  constructor (opts = {}) {
    if (!opts.path) throw new Error('UdsServer requires opts.path')
    if (typeof opts.dispatch !== 'function') throw new Error('UdsServer requires opts.dispatch')

    this._path = opts.path
    this._dispatch = opts.dispatch
    this._server = null
    this._connections = new Set()
    this._listening = false

    // Idle-connection reaper. `allowHalfOpen:false` + the end/error handlers
    // below clean up when a client CLOSES or EXITS. But a caller that opens a
    // connection and then neither closes it nor exits (a long-lived process
    // that forgets Client.close()) leaves the accepted socket ESTAB forever —
    // the OS never delivers an end/close the server can react to. Unbounded,
    // this grew pgh-sidecar to ~348k ESTAB unix sockets / ~22GB (2026-07-05).
    // Sweep and destroy connections idle past _idleTimeout with no request in
    // flight. Request/response callers reset the timer on every frame, so only
    // genuinely dead connections are reaped. Set idleTimeout:0 to disable.
    this._idleTimeout = opts.idleTimeout === undefined ? 120000 : opts.idleTimeout
    this._sweepTimer = null
  }

  get path () { return this._path }
  get listening () { return this._listening }

  async listen () {
    if (this._listening) return

    // Select the transport: #node:net for pathname sockets (unchanged), or
    // bare-abstract-socket for an '@'-prefixed abstract name. `name` is the
    // bind name with the '@' stripped.
    const { backend, name, abstract } = await udsBackend(this._path)

    // Best-effort cleanup of a stale socket FILE (server crashed without
    // unlinking). Abstract sockets have no filesystem entry (the kernel frees
    // the name when the socket closes), so this applies to pathname sockets only.
    if (!abstract) {
      // ONLY remove if it's actually a socket — never touch regular files / dirs.
      try {
        const s = await stat(this._path)
        if (s.isSocket()) {
          // Try to connect first — if a daemon is already running, refuse to clobber.
          const inUse = await this._probe()
          if (inUse) throw new Error(`socket ${this._path} is already in use`)
          await unlink(this._path)
        }
      } catch (err) {
        if (err.code !== 'ENOENT' && err.message.indexOf('already in use') === -1) {
          // stat failed for some reason other than missing — ignore, let listen() fail naturally
        }
        if (err.message && err.message.indexOf('already in use') !== -1) throw err
      }
    }

    // allowHalfOpen:false is CRITICAL. bare-net defaults it to true (unlike
    // Node), which means when a client disconnects the accepted socket never
    // sees 'end' and never releases — the fd AND its 64KB read buffer leak.
    // With false, peer disconnect surfaces as 'end', which _onConnection
    // turns into a destroy() so the socket fully closes. See the fd-leak that
    // grew pgh-sidecar to ~205k open sockets / 14GB RSS (2026-06-09).
    // (bare-abstract-socket honours the same allowHalfOpen:false on accept.)
    this._server = backend.createServer({ allowHalfOpen: false }, (sock) => this._onConnection(sock))

    await new Promise((resolve, reject) => {
      this._server.once('error', reject)
      this._server.listen(name, () => {
        this._server.removeListener('error', reject)
        resolve()
      })
    })

    this._listening = true

    if (this._idleTimeout > 0) {
      const sweepEvery = Math.max(1000, Math.min(30000, Math.floor(this._idleTimeout / 2)))
      this._sweepTimer = setInterval(() => this._reapIdle(), sweepEvery)
      // Don't let the reaper keep the process alive on its own.
      if (this._sweepTimer && typeof this._sweepTimer.unref === 'function') this._sweepTimer.unref()
    }
  }

  // Destroy connections idle past _idleTimeout with no request in flight.
  // destroy() fires 'close', which removes the socket from _connections.
  _reapIdle () {
    const now = Date.now()
    for (const sock of this._connections) {
      if ((sock._inflight || 0) > 0) continue
      if (now - (sock._lastActive || 0) > this._idleTimeout) {
        try { sock.destroy() } catch {}
      }
    }
  }

  async _probe () {
    const { backend, name } = await udsBackend(this._path)
    return new Promise((resolve) => {
      const sock = backend.createConnection(name)
      sock.once('connect', () => {
        sock.destroy()
        resolve(true)
      })
      sock.once('error', () => {
        sock.destroy()
        resolve(false)
      })
    })
  }

  _onConnection (sock) {
    this._connections.add(sock)
    sock._lastActive = Date.now()
    sock._inflight = 0
    sock.on('close', () => this._connections.delete(sock))

    // Peer closed their write side (client finished + disconnected). bare-net
    // does NOT emit 'close' on its own here — we must destroy() to release the
    // fd and drop the socket (and its read buffer) from _connections. Safe even
    // mid-dispatch: a late _handleRequest write is already wrapped in try/catch.
    sock.on('end', () => { try { sock.destroy() } catch {} })

    const decoder = new FrameDecoder((req) => this._handleRequest(sock, req))

    sock.on('data', (chunk) => {
      sock._lastActive = Date.now()
      try {
        decoder.push(chunk)
      } catch (err) {
        // Bad frame — close the connection rather than try to recover
        try { sock.destroy(err) } catch {}
      }
    })

    // Abrupt disconnect (ECONNRESET, or the client process killed / timed out
    // mid-request). bare-net does NOT emit 'close' on its own (see the 'end'
    // note above) — and unlike a clean FIN there is no 'end' either — so we
    // MUST destroy() here to release the fd + 64KB read buffer and drop the
    // socket from _connections. Without this, every abrupt client disconnect
    // leaks a half-open socket (the 0.1.3 'end'-only fix covered clean closes
    // but not this path — the cause of the 6645-socket accumulation seen when
    // a client hammers the UDS with timed-out/killed calls).
    sock.on('error', () => { try { sock.destroy() } catch {} })
  }

  async _handleRequest (sock, req) {
    const id = req && req.id
    if (typeof id !== 'number' && typeof id !== 'string') {
      // Malformed — best effort error response, but the client probably can't match it
      try {
        sock.write(encodeFrame({ id: null, error: 'request missing id' }))
      } catch {}
      return
    }

    const ctx = {
      transport: 'uds',
      identity: { type: 'local', userId: process.env.USER || null, trust: 'local' }
    }

    // Mark in-flight so the idle reaper never destroys a socket mid-dispatch,
    // even if the handler runs longer than _idleTimeout.
    sock._inflight = (sock._inflight || 0) + 1
    try {
      const result = await this._dispatch(req.method, req.params, ctx)
      try {
        sock.write(encodeFrame({ id, result }))
      } catch {}
    } catch (err) {
      try {
        sock.write(encodeFrame({ id, error: err.message || String(err) }))
      } catch {}
    } finally {
      sock._inflight = Math.max(0, (sock._inflight || 1) - 1)
      sock._lastActive = Date.now()
    }
  }

  async close () {
    if (!this._server) return
    if (this._sweepTimer) { clearInterval(this._sweepTimer); this._sweepTimer = null }
    for (const sock of this._connections) {
      try { sock.destroy() } catch {}
    }
    this._connections.clear()
    await new Promise((resolve) => this._server.close(() => resolve()))
    this._server = null
    this._listening = false

    // Clean up the socket file (best-effort). Abstract sockets have no fs entry.
    if (!isAbstract(this._path)) {
      try { await unlink(this._path) } catch {}
    }
  }
}
/**
 * UDS backend selection.
 *
 * A socket "path" beginning with '@' names a Linux ABSTRACT-namespace socket
 * (no filesystem entry) instead of a pathname socket. Abstract sockets are the
 * only UNIX-socket option when SELinux denies the shell domain from creating
 * pathname sockets — e.g. an unrooted Android phone (celltron) running the
 * daemon under proot, where bind(AF_UNIX, "/path.sock") returns EACCES.
 *
 * For every non-'@' path we use #node:net exactly as before — byte-for-byte
 * unchanged behavior. bare-abstract-socket is imported LAZILY (dynamic import,
 * only at the async call sites below) so pathname deployments never load the
 * native addon.
 */

import net from '#node:net'

let _abstract = null

async function loadAbstract () {
  if (_abstract === null) {
    const m = await import('bare-abstract-socket')
    _abstract = m.default || m
  }
  return _abstract
}

// True if `path` names an abstract-namespace socket (leading '@').
export function isAbstract (path) {
  return typeof path === 'string' && path.length > 1 && path[0] === '@'
}

// Resolve the transport backend + the name to bind/connect. The returned
// `backend` exposes net-compatible createServer(opts, onConnection) and
// createConnection(name). For abstract paths the leading '@' is stripped
// (bare-abstract-socket adds the actual leading NUL).
export async function udsBackend (path) {
  if (isAbstract(path)) {
    return { backend: await loadAbstract(), name: path.slice(1), abstract: true }
  }
  return { backend: net, name: path, abstract: false }
}
const { Pull, Push, HEADERBYTES, KEYBYTES, ABYTES } = require('sodium-secretstream')
const sodium = require('sodium-universal')
const crypto = require('hypercore-crypto')
const { Duplex, Writable, getStreamError } = require('streamx')
const b4a = require('b4a')
const Timeout = require('timeout-refresh')
const unslab = require('unslab')
const Bridge = require('./lib/bridge')
const Handshake = require('./lib/handshake')

const IDHEADERBYTES = HEADERBYTES + 32
const [NS_INITIATOR, NS_RESPONDER, NS_SEND] = crypto.namespace('hyperswarm/secret-stream', 3)
const MAX_ATOMIC_WRITE = 256 * 256 * 256 - 1

module.exports = class NoiseSecretStream extends Duplex {
  constructor(isInitiator, rawStream, opts = {}) {
    super({ mapWritable: toBuffer })

    if (typeof isInitiator !== 'boolean') {
      throw new Error('isInitiator should be a boolean')
    }

    this.noiseStream = this
    this.isInitiator = isInitiator
    this.rawStream = null

    this.publicKey = opts.publicKey || null
    this.remotePublicKey = opts.remotePublicKey || null
    this.handshakeHash = null
    this.connected = false
    this.keepAlive = opts.keepAlive || 0
    this.timeout = 0
    this.enableSend = opts.enableSend !== false

    // pointer for upstream to set data here if they want
    this.userData = null

    let openedDone = null
    this.opened = new Promise((resolve) => {
      openedDone = resolve
    })

    this.rawBytesWritten = 0
    this.rawBytesRead = 0

    // metadata used by 'hyperdht'
    this.relay = null
    this.puncher = null

    // unwrapped raw stream
    this._rawStream = null

    // handshake state
    this._handshake = null
    this._handshakePattern = opts.pattern || null
    this._handshakeDone = null

    // message parsing state
    this._state = 0
    this._len = 0
    this._tmp = 1
    this._message = null

    this._openedDone = openedDone
    this._startDone = null
    this._drainDone = null
    this._outgoingPlain = null
    this._outgoingWrapped = null
    this._utp = null
    this._setup = true
    this._ended = 2
    this._encrypt = null
    this._decrypt = null
    this._timeoutTimer = null
    this._keepAliveTimer = null
    this._sendState = null

    if (opts.autoStart !== false) this.start(rawStream, opts)

    // wiggle it to trigger open immediately (TODO add streamx option for this)
    this.resume()
    this.pause()
  }

  static keyPair(seed) {
    return Handshake.keyPair(seed)
  }

  static id(handshakeHash, isInitiator, id) {
    return streamId(handshakeHash, isInitiator, id)
  }

  setTimeout(ms) {
    if (!ms) ms = 0

    this._clearTimeout()
    this.timeout = ms

    if (!ms || this.rawStream === null) return

    this._timeoutTimer = Timeout.once(ms, destroyTimeout, this)
    this._timeoutTimer.unref()
  }

  setKeepAlive(ms) {
    if (!ms) ms = 0

    this._clearKeepAlive()

    this.keepAlive = ms

    if (!ms || this.rawStream === null) return

    this._keepAliveTimer = Timeout.on(ms, sendKeepAlive, this)
    this._keepAliveTimer.unref()
  }

  sendKeepAlive() {
    const empty = this.alloc(0)
    this.write(empty)
  }

  start(rawStream, opts = {}) {
    if (rawStream) {
      this.rawStream = rawStream
      this._rawStream = rawStream
      if (typeof this.rawStream.setContentSize === 'function') {
        this._utp = rawStream
      }
    } else {
      this.rawStream = new Bridge(this)
      this._rawStream = this.rawStream.reverse
    }

    this.rawStream.on('error', this._onrawerror.bind(this))
    this.rawStream.on('close', this._onrawclose.bind(this))

    this._startHandshake(opts.handshake, opts.keyPair || null)
    this._continueOpen(null)

    if (this.destroying) return

    if (opts.data) this._onrawdata(opts.data)
    if (opts.ended) this._onrawend()

    if (this.keepAlive > 0 && this._keepAliveTimer === null) {
      this.setKeepAlive(this.keepAlive)
    }

    if (this.timeout > 0 && this._timeoutTimer === null) {
      this.setTimeout(this.timeout)
    }
  }

  async flush() {
    if ((await this.opened) === false) return false
    if ((await Writable.drained(this)) === false) return false
    if (this.destroying) return false

    if (this.rawStream !== null && this.rawStream.flush) {
      return await this.rawStream.flush()
    }

    return true
  }

  _continueOpen(err) {
    if (err) this.destroy(err)
    if (this._startDone === null) return
    const done = this._startDone
    this._startDone = null
    this._open(done)
  }

  _onkeypairpromise(p) {
    const self = this
    const cont = this._continueOpen.bind(this)

    p.then(onkeypair, cont)

    function onkeypair(kp) {
      self._onkeypair(kp)
      cont(null)
    }
  }

  _onkeypair(keyPair) {
    const pattern = this._handshakePattern || 'XX'
    const remotePublicKey = this.remotePublicKey

    this._handshake = new Handshake(this.isInitiator, keyPair, remotePublicKey, pattern)
    this.publicKey = this._handshake.keyPair.publicKey
  }

  _startHandshake(handshake, keyPair) {
    if (handshake) {
      const { tx, rx, hash, publicKey, remotePublicKey } = handshake
      this._setupSecretStream(tx, rx, hash, publicKey, remotePublicKey)
      return
    }

    if (!keyPair) keyPair = Handshake.keyPair()

    if (typeof keyPair.then === 'function') {
      this._onkeypairpromise(keyPair)
    } else {
      this._onkeypair(keyPair)
    }
  }

  _onrawerror(err) {
    this.destroy(err)
  }

  _onrawclose() {
    if (this._ended !== 0) this.destroy()
  }

  _onrawdata(data) {
    let offset = 0

    if (this._timeoutTimer !== null) {
      this._timeoutTimer.refresh()
    }

    do {
      switch (this._state) {
        case 0: {
          while (this._tmp !== 0x1000000 && offset < data.byteLength) {
            const v = data[offset++]
            this._len += this._tmp * v
            this._tmp *= 256
          }

          if (this._tmp === 0x1000000) {
            this._tmp = 0
            this._state = 1
            const unprocessed = data.byteLength - offset
            if (unprocessed < this._len && this._utp !== null)
              this._utp.setContentSize(this._len - unprocessed)
          }

          break
        }

        case 1: {
          const missing = this._len - this._tmp
          const end = missing + offset

          if (this._message === null && end <= data.byteLength) {
            this._message = data.subarray(offset, end)
            offset += missing
            this._incoming()
            break
          }

          const unprocessed = data.byteLength - offset

          if (this._message === null) {
            this._message = b4a.allocUnsafe(this._len)
          }

          b4a.copy(data, this._message, this._tmp, offset)
          this._tmp += unprocessed

          if (end <= data.byteLength) {
            offset += missing
            this._incoming()
          } else {
            offset += unprocessed
          }

          break
        }
      }
    } while (offset < data.byteLength && !this.destroying)
  }

  _onrawend() {
    this._ended--
    this.push(null)
  }

  _onrawdrain() {
    const drain = this._drainDone
    if (drain === null) return
    this._drainDone = null
    drain()
  }

  _read(cb) {
    this.rawStream.resume()
    cb(null)
  }

  _incoming() {
    const message = this._message

    this._state = 0
    this._len = 0
    this._tmp = 1
    this._message = null

    if (this._setup === true) {
      if (this._handshake) {
        this._onhandshakert(this._handshake.recv(message))
      } else {
        if (message.byteLength !== IDHEADERBYTES) {
          this.destroy(new Error('Invalid header message received'))
          return
        }

        const remoteId = message.subarray(0, 32)
        const expectedId = streamId(this.handshakeHash, !this.isInitiator)
        const header = message.subarray(32)

        if (!b4a.equals(expectedId, remoteId)) {
          this.destroy(new Error('Invalid header received'))
          return
        }

        this._decrypt.init(header)
        this._setup = false // setup is now done
      }
      return
    }

    if (message.byteLength < ABYTES) {
      this.destroy(new Error('Invalid message received'))
      return
    }

    this.rawBytesRead += message.byteLength

    const plain = message.subarray(1, message.byteLength - ABYTES + 1)

    try {
      this._decrypt.next(message, plain)
    } catch (err) {
      this.destroy(err)
      return
    }

    // If keep alive is selective, eat the empty buffers (ie assume the other side has it enabled also)
    if (plain.byteLength === 0 && this.keepAlive !== 0) return

    if (this.push(plain) === false) {
      this.rawStream.pause()
    }
  }

  _onhandshakert(h) {
    if (this._handshakeDone === null) return

    if (h !== null) {
      if (h.data) this._rawStream.write(h.data)
      if (!h.tx) return
    }

    const done = this._handshakeDone
    const publicKey = this._handshake.keyPair.publicKey

    this._handshakeDone = null
    this._handshake = null

    if (h === null) return done(new Error('Noise handshake failed'))

    this._setupSecretStream(h.tx, h.rx, h.hash, publicKey, h.remotePublicKey)
    this._resolveOpened(true)
    done(null)
  }

  _setupSecretStream(tx, rx, handshakeHash, publicKey, remotePublicKey) {
    const buf = b4a.allocUnsafeSlow(3 + IDHEADERBYTES)
    writeUint24le(IDHEADERBYTES, buf)

    this._encrypt = new Push(unslab(tx.subarray(0, KEYBYTES)), undefined, buf.subarray(3 + 32))
    this._decrypt = new Pull(unslab(rx.subarray(0, KEYBYTES)))

    this.publicKey = publicKey
    this.remotePublicKey = remotePublicKey
    this.handshakeHash = handshakeHash

    const id = buf.subarray(3, 3 + 32)
    streamId(handshakeHash, this.isInitiator, id)

    // initialize secretbox state for unordered messages
    this._setupSecretSend(handshakeHash)

    this.emit('handshake')
    // if rawStream is a bridge, also emit it there
    if (this.rawStream !== this._rawStream) this.rawStream.emit('handshake')

    if (this.destroying) return

    this._rawStream.write(buf)
  }

  _setupSecretSend(handshakeHash) {
    this._sendState = b4a.allocUnsafeSlow(32 + 32 + 8 + 8)
    const encrypt = this._sendState.subarray(0, 32) // secrets
    const decrypt = this._sendState.subarray(32, 64)
    const counter = this._sendState.subarray(64, 72) // nonce
    const initial = this._sendState.subarray(72)

    const inputs = this.isInitiator
      ? [
          [NS_INITIATOR, NS_SEND],
          [NS_RESPONDER, NS_SEND]
        ]
      : [
          [NS_RESPONDER, NS_SEND],
          [NS_INITIATOR, NS_SEND]
        ]

    sodium.crypto_generichash_batch(encrypt, inputs[0], handshakeHash)
    sodium.crypto_generichash_batch(decrypt, inputs[1], handshakeHash)

    sodium.randombytes_buf(initial)
    counter.set(initial)
  }

  _open(cb) {
    // no autostart or no handshake yet
    if (this._rawStream === null || (this._handshake === null && this._encrypt === null)) {
      this._startDone = cb
      return
    }

    this._rawStream.on('data', this._onrawdata.bind(this))
    this._rawStream.on('end', this._onrawend.bind(this))
    this._rawStream.on('drain', this._onrawdrain.bind(this))

    if (this.enableSend) this._rawStream.on('message', this._onmessage.bind(this))

    if (this._encrypt !== null) {
      this._resolveOpened(true)
      return cb(null)
    }

    this._handshakeDone = cb

    if (this.isInitiator) this._onhandshakert(this._handshake.send())
  }

  _predestroy() {
    if (this.rawStream) {
      const error = getStreamError(this)
      this.rawStream.destroy(error)
    }

    if (this._startDone !== null) {
      const done = this._startDone
      this._startDone = null
      done(new Error('Stream destroyed'))
    }

    if (this._handshakeDone !== null) {
      const done = this._handshakeDone
      this._handshakeDone = null
      done(new Error('Stream destroyed'))
    }

    if (this._drainDone !== null) {
      const done = this._drainDone
      this._drainDone = null
      done(new Error('Stream destroyed'))
    }
  }

  _write(data, cb) {
    let wrapped = this._outgoingWrapped

    if (data !== this._outgoingPlain) {
      wrapped = b4a.allocUnsafe(data.byteLength + 3 + ABYTES)
      wrapped.set(data, 4)
    } else {
      this._outgoingWrapped = this._outgoingPlain = null
    }

    if (wrapped.byteLength - 3 > MAX_ATOMIC_WRITE) {
      return cb(
        new Error(
          'Message is too large for an atomic write. Max size is ' + MAX_ATOMIC_WRITE + ' bytes.'
        )
      )
    }
    this.rawBytesWritten += wrapped.byteLength

    writeUint24le(wrapped.byteLength - 3, wrapped)
    // offset 4 so we can do it in-place
    this._encrypt.next(wrapped.subarray(4, 4 + data.byteLength), wrapped.subarray(3))

    if (this._keepAliveTimer !== null) this._keepAliveTimer.refresh()

    if (this._rawStream.write(wrapped) === false) {
      this._drainDone = cb
    } else {
      cb(null)
    }
  }

  _final(cb) {
    this._clearKeepAlive()
    this._ended--
    this._rawStream.end()
    cb(null)
  }

  _resolveOpened(val) {
    if (this._openedDone === null) return
    const opened = this._openedDone
    this._openedDone = null
    opened(val)
    if (!val) return
    this.connected = true
    this.emit('connect')
  }

  _clearTimeout() {
    if (this._timeoutTimer === null) return
    this._timeoutTimer.destroy()
    this._timeoutTimer = null
    this.timeout = 0
  }

  _clearKeepAlive() {
    if (this._keepAliveTimer === null) return
    this._keepAliveTimer.destroy()
    this._keepAliveTimer = null
    this.keepAlive = 0
  }

  _destroy(cb) {
    this._clearKeepAlive()
    this._clearTimeout()
    this._resolveOpened(false)
    cb(null)
  }

  _boxMessage(buffer) {
    const MB = sodium.crypto_secretbox_MACBYTES // 16
    const NB = sodium.crypto_secretbox_NONCEBYTES // 24

    const counter = this._sendState.subarray(64, 72)
    sodium.sodium_increment(counter)
    if (b4a.equals(counter, this._sendState.subarray(72))) {
      this.destroy(new Error('udp send nonce exchausted'))
      return
    }

    const secret = this._sendState.subarray(0, 32)
    const envelope = b4a.allocUnsafe(8 + MB + buffer.byteLength)
    const nonce = envelope.subarray(0, NB)
    const ciphertext = envelope.subarray(8)

    b4a.fill(nonce, 0) // pad suffix
    nonce.set(counter)

    sodium.crypto_secretbox_easy(ciphertext, buffer, nonce, secret)
    return envelope
  }

  send(buffer) {
    if (!this._sendState) return
    if (!this.rawStream?.send) return // udx-stream expected

    const message = this._boxMessage(buffer)
    return this.rawStream.send(message)
  }

  trySend(buffer) {
    if (!this._sendState) return
    if (!this.rawStream?.trySend) return // udx-stream expected

    const message = this._boxMessage(buffer)
    this.rawStream.trySend(message)
  }

  _onmessage(buffer) {
    if (!this._sendState) return // messages before handshake are dropped

    const MB = sodium.crypto_secretbox_MACBYTES // 16
    const NB = sodium.crypto_secretbox_NONCEBYTES // 24

    if (buffer.byteLength < NB) return // Invalid message

    const nonce = b4a.allocUnsafe(NB)
    b4a.fill(nonce, 0)
    nonce.set(buffer.subarray(0, 8))

    const secret = this._sendState.subarray(32, 64)
    const ciphertext = buffer.subarray(8)
    const plain = buffer.subarray(8, buffer.byteLength - MB)

    if (ciphertext.byteLength < MB) return // invalid message

    const success = sodium.crypto_secretbox_open_easy(plain, ciphertext, nonce, secret)

    if (success) this.emit('message', plain)
  }

  alloc(len) {
    const buf = b4a.allocUnsafe(len + 3 + ABYTES)
    this._outgoingWrapped = buf
    this._outgoingPlain = buf.subarray(4, buf.byteLength - ABYTES + 1)
    return this._outgoingPlain
  }

  toJSON() {
    return {
      isInitiator: this.isInitiator,
      publicKey: this.publicKey && b4a.toString(this.publicKey, 'hex'),
      remotePublicKey: this.remotePublicKey && b4a.toString(this.remotePublicKey, 'hex'),
      connected: this.connected,
      destroying: this.destroying,
      destroyed: this.destroyed,
      rawStream: this.rawStream && this.rawStream.toJSON ? this.rawStream.toJSON() : null
    }
  }
}

function writeUint24le(n, buf) {
  buf[0] = n & 255
  buf[1] = (n >>> 8) & 255
  buf[2] = (n >>> 16) & 255
}

function streamId(handshakeHash, isInitiator, out = b4a.allocUnsafe(32)) {
  sodium.crypto_generichash(out, isInitiator ? NS_INITIATOR : NS_RESPONDER, handshakeHash)
  return out
}

function toBuffer(data) {
  return typeof data === 'string' ? b4a.from(data) : data
}

function destroyTimeout() {
  this.destroy(new Error('Stream timed out'))
}

function sendKeepAlive() {
  const empty = this.alloc(0)
  this.write(empty)
}
const { Duplex, Writable } = require('streamx')

class ReversePassThrough extends Duplex {
  constructor(s) {
    super()
    this._stream = s
    this._ondrain = null
  }

  _write(data, cb) {
    if (this._stream.push(data) === false) {
      this._stream._ondrain = cb
    } else {
      cb(null)
    }
  }

  _final(cb) {
    this._stream.push(null)
    cb(null)
  }

  _read(cb) {
    const ondrain = this._ondrain
    this._ondrain = null
    if (ondrain) ondrain()
    cb(null)
  }
}

module.exports = class Bridge extends Duplex {
  constructor(noiseStream) {
    super()

    this.noiseStream = noiseStream

    this._ondrain = null
    this.reverse = new ReversePassThrough(this)
  }

  get publicKey() {
    return this.noiseStream.publicKey
  }

  get remotePublicKey() {
    return this.noiseStream.remotePublicKey
  }

  get handshakeHash() {
    return this.noiseStream.handshakeHash
  }

  flush() {
    return Writable.drained(this)
  }

  _read(cb) {
    const ondrain = this._ondrain
    this._ondrain = null
    if (ondrain) ondrain()
    cb(null)
  }

  _write(data, cb) {
    if (this.reverse.push(data) === false) {
      this.reverse._ondrain = cb
    } else {
      cb(null)
    }
  }

  _final(cb) {
    this.reverse.push(null)
    cb(null)
  }
}
const sodium = require('sodium-universal')
const curve = require('noise-curve-ed')
const Noise = require('noise-handshake')
const b4a = require('b4a')

const EMPTY = b4a.alloc(0)

module.exports = class Handshake {
  constructor(isInitiator, keyPair, remotePublicKey, pattern) {
    this.isInitiator = isInitiator
    this.keyPair = keyPair
    this.noise = new Noise(pattern, isInitiator, keyPair, { curve })
    this.noise.initialise(EMPTY, remotePublicKey)
    this.destroyed = false
  }

  static keyPair(seed) {
    const publicKey = b4a.alloc(32)
    const secretKey = b4a.alloc(64)
    if (seed) sodium.crypto_sign_seed_keypair(publicKey, secretKey, seed)
    else sodium.crypto_sign_keypair(publicKey, secretKey)
    return { publicKey, secretKey }
  }

  recv(data) {
    try {
      this.noise.recv(data)
      if (this.noise.complete) return this._return(null)
      return this.send()
    } catch {
      this.destroy()
      return null
    }
  }

  // note that the data returned here is framed so we don't have to do an extra copy
  // when sending it...
  send() {
    try {
      const data = this.noise.send()
      const wrap = b4a.allocUnsafe(data.byteLength + 3)

      writeUint24le(data.byteLength, wrap)
      wrap.set(data, 3)

      return this._return(wrap)
    } catch {
      this.destroy()
      return null
    }
  }

  destroy() {
    if (this.destroyed) return
    this.destroyed = true
  }

  _return(data) {
    const tx = this.noise.complete ? b4a.toBuffer(this.noise.tx) : null
    const rx = this.noise.complete ? b4a.toBuffer(this.noise.rx) : null
    const hash = this.noise.complete ? b4a.toBuffer(this.noise.hash) : null
    const remotePublicKey = this.noise.complete ? b4a.toBuffer(this.noise.rs) : null

    return {
      data,
      remotePublicKey,
      hash,
      tx,
      rx
    }
  }
}

function writeUint24le(n, buf) {
  buf[0] = n & 255
  buf[1] = (n >>> 8) & 255
  buf[2] = (n >>> 16) & 255
}
{
  "name": "@hyperswarm/secret-stream",
  "version": "6.9.1",
  "description": "Secret stream backed by Noise and libsodium's secretstream",
  "main": "index.js",
  "files": [
    "index.js",
    "lib/**.js"
  ],
  "dependencies": {
    "b4a": "^1.1.0",
    "hypercore-crypto": "^3.3.1",
    "noise-curve-ed": "^2.0.1",
    "noise-handshake": "^4.0.0",
    "sodium-secretstream": "^1.1.0",
    "sodium-universal": "^5.0.0",
    "streamx": "^2.14.0",
    "timeout-refresh": "^2.0.0",
    "unslab": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "udx-native": "^1.13.2"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check .",
    "test": "brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/hyperswarm-secret-stream.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/hyperswarm-secret-stream/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperswarm-secret-stream"
}
const Cache = require('xache')

module.exports = class AdaptiveTimeout {
  constructor(opts = {}) {
    this._cache = new Cache({
      maxSize: opts.maxSize || 65536,
      maxAge: opts.maxAge || 10 * 60 * 1000 // 10 minutes
    })
    this._fallback = opts.fallback || AdaptiveTimeout.TimeoutExponential
    this._min = opts.min ?? 300
    this._max = opts.max || 4000
    this._jitter = opts.jitter ?? 256
  }

  // Default - aggressive ramp
  static TimeoutAggressive = [500, 750, 1000, 1500, 2000]

  // Linear - steady increase
  static TimeoutLinear = [500, 1000, 1500, 2000, 2500]

  // Exponential - slow start, rapid backoff
  static TimeoutExponential = [250, 500, 1000, 2000, 4000]

  // Gentle - conservative, patient
  static TimeoutGentle = [1000, 1250, 1500, 1750, 2000]

  // Fast - rapid fire retries
  static TimeoutFast = [200, 400, 600, 800, 1000]

  // U-shape - long, short, long
  static TimeoutUShape = [1500, 750, 500, 750, 1500]

  // Inverse U - short, long, short
  static TimeoutInverseU = [500, 1000, 1500, 1000, 500]

  // Sawtooth - alternating fast/slow
  static TimeoutSawtooth = [500, 1500, 500, 1500, 500]

  // Plateau - quick ramp then steady
  static TimeoutPlateau = [500, 1000, 2000, 2000, 2000]

  // Logarithmic - diminishing increases
  static TimeoutLogarithmic = [500, 1000, 1300, 1500, 1600]

  getValue(key) {
    return this._cache.get(key)
  }

  put(key, value) {
    let p = this._cache.get(key)

    if (!p) {
      p = { avg: value, variance: value >> 1 }
    } else {
      // blend 75% old + 25% new deviation
      p.variance += (Math.abs(p.avg - value) - p.variance) >> 2
      // blend 87.5% old + 12.5% new sample
      p.avg += (value - p.avg) >> 3
    }

    this._cache.set(key, p)

    return p
  }

  get(key, attempt = 1) {
    const p = this._cache.get(key)
    const jitter = (Math.random() * this._jitter) | 0

    if (p) {
      // known - use adaptive with linear backoff
      const base = p.avg + (p.variance << 1)
      const backoff = base * attempt
      return Math.min(Math.max(backoff + jitter, this._min), this._max)
    } else {
      // unknown - use aggressive fallback
      const base = this._fallback[Math.min(attempt - 1, this._fallback.length - 1)]
      return base + jitter
    }
  }

  has(key) {
    return this._cache.has(key)
  }

  delete(key) {
    return this._cache.delete(key)
  }

  clear() {
    this._cache.clear()
  }
}
{
  "name": "adaptive-timeout",
  "version": "1.0.1",
  "description": "adaptive-timeout",
  "main": "index.js",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    }
  },
  "files": [
    "package.json",
    "index.js",
    "index.d.ts"
  ],
  "devDependencies": {
    "brittle": "^3.19.0",
    "lunte": "^1.2.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && lunte && brittle-bare test/index.js",
    "lint": "lunte"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/adaptive-timeout.git"
  },
  "author": "Holepunch Inc",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/adaptive-timeout/issues"
  },
  "homepage": "https://github.com/holepunchto/adaptive-timeout",
  "dependencies": {
    "xache": "^1.2.1"
  }
}
function isBuffer(value) {
  return Buffer.isBuffer(value) || value instanceof Uint8Array
}

function isEncoding(encoding) {
  return Buffer.isEncoding(encoding)
}

function alloc(size, fill, encoding) {
  return Buffer.alloc(size, fill, encoding)
}

function allocUnsafe(size) {
  return Buffer.allocUnsafe(size)
}

function allocUnsafeSlow(size) {
  return Buffer.allocUnsafeSlow(size)
}

function byteLength(string, encoding) {
  return Buffer.byteLength(string, encoding)
}

function compare(a, b) {
  return Buffer.compare(a, b)
}

function concat(buffers, totalLength) {
  return Buffer.concat(buffers, totalLength)
}

function copy(source, target, targetStart, start, end) {
  return toBuffer(source).copy(target, targetStart, start, end)
}

function equals(a, b) {
  return toBuffer(a).equals(b)
}

function fill(buffer, value, offset, end, encoding) {
  return toBuffer(buffer).fill(value, offset, end, encoding)
}

function from(value, encodingOrOffset, length) {
  return Buffer.from(value, encodingOrOffset, length)
}

function includes(buffer, value, byteOffset, encoding) {
  return toBuffer(buffer).includes(value, byteOffset, encoding)
}

function indexOf(buffer, value, byfeOffset, encoding) {
  return toBuffer(buffer).indexOf(value, byfeOffset, encoding)
}

function lastIndexOf(buffer, value, byteOffset, encoding) {
  return toBuffer(buffer).lastIndexOf(value, byteOffset, encoding)
}

function swap16(buffer) {
  return toBuffer(buffer).swap16()
}

function swap32(buffer) {
  return toBuffer(buffer).swap32()
}

function swap64(buffer) {
  return toBuffer(buffer).swap64()
}

function toBuffer(buffer) {
  if (Buffer.isBuffer(buffer)) return buffer
  return Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

function toString(buffer, encoding, start, end) {
  return toBuffer(buffer).toString(encoding, start, end)
}

function write(buffer, string, offset, length, encoding) {
  return toBuffer(buffer).write(string, offset, length, encoding)
}

function readDoubleBE(buffer, offset) {
  return toBuffer(buffer).readDoubleBE(offset)
}

function readDoubleLE(buffer, offset) {
  return toBuffer(buffer).readDoubleLE(offset)
}

function readFloatBE(buffer, offset) {
  return toBuffer(buffer).readFloatBE(offset)
}

function readFloatLE(buffer, offset) {
  return toBuffer(buffer).readFloatLE(offset)
}

function readInt32BE(buffer, offset) {
  return toBuffer(buffer).readInt32BE(offset)
}

function readInt32LE(buffer, offset) {
  return toBuffer(buffer).readInt32LE(offset)
}

function readUInt32BE(buffer, offset) {
  return toBuffer(buffer).readUInt32BE(offset)
}

function readUInt32LE(buffer, offset) {
  return toBuffer(buffer).readUInt32LE(offset)
}

function writeDoubleBE(buffer, value, offset) {
  return toBuffer(buffer).writeDoubleBE(value, offset)
}

function writeDoubleLE(buffer, value, offset) {
  return toBuffer(buffer).writeDoubleLE(value, offset)
}

function writeFloatBE(buffer, value, offset) {
  return toBuffer(buffer).writeFloatBE(value, offset)
}

function writeFloatLE(buffer, value, offset) {
  return toBuffer(buffer).writeFloatLE(value, offset)
}

function writeInt32BE(buffer, value, offset) {
  return toBuffer(buffer).writeInt32BE(value, offset)
}

function writeInt32LE(buffer, value, offset) {
  return toBuffer(buffer).writeInt32LE(value, offset)
}

function writeUInt32BE(buffer, value, offset) {
  return toBuffer(buffer).writeUInt32BE(value, offset)
}

function writeUInt32LE(buffer, value, offset) {
  return toBuffer(buffer).writeUInt32LE(value, offset)
}

module.exports = {
  isBuffer,
  isEncoding,
  alloc,
  allocUnsafe,
  allocUnsafeSlow,
  byteLength,
  compare,
  concat,
  copy,
  equals,
  fill,
  from,
  includes,
  indexOf,
  lastIndexOf,
  swap16,
  swap32,
  swap64,
  toBuffer,
  toString,
  write,
  readDoubleBE,
  readDoubleLE,
  readFloatBE,
  readFloatLE,
  readInt32BE,
  readInt32LE,
  readUInt32BE,
  readUInt32LE,
  writeDoubleBE,
  writeDoubleLE,
  writeFloatBE,
  writeFloatLE,
  writeInt32BE,
  writeInt32LE,
  writeUInt32BE,
  writeUInt32LE
}
{
  "name": "b4a",
  "version": "1.8.1",
  "description": "Bridging the gap between buffers and typed arrays",
  "exports": {
    "./package": "./package.json",
    ".": {
      "react-native": "./react-native.js",
      "browser": "./browser.js",
      "default": "./index.js"
    }
  },
  "files": [
    "browser.js",
    "index.js",
    "react-native.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:bare && npm run test:node",
    "test:bare": "brittle-bare --coverage test.mjs",
    "test:node": "brittle-node --coverage test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/b4a.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/b4a/issues"
  },
  "homepage": "https://github.com/holepunchto/b4a#readme",
  "devDependencies": {
    "brittle": "^3.5.2",
    "lunte": "^1.7.0",
    "nanobench": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "react-native-b4a": "*"
  },
  "peerDependenciesMeta": {
    "react-native-b4a": {
      "optional": true
    }
  }
}
module.exports = require.addon()
const binding = require('./binding')

module.exports = binding.abort
{
  "name": "bare-abort",
  "version": "2.0.13",
  "description": "Cause abnormal program termination and generate a crash report",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-abort.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-abort/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-abort#readme",
  "devDependencies": {
    "cmake-bare": "^1.1.7",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  }
}
const ESC = '\x1b'
const CSI = ESC + '['
const SGR = (n) => CSI + n + 'm'

exports.constants = {
  ESC,
  CSI,
  SGR
}

// https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_(Control_Sequence_Introducer)_sequences

exports.cursorHide = CSI + '?25l'
exports.cursorShow = CSI + '?25h'

exports.cursorUp = function cursorUp(n = 1) {
  return CSI + n + 'A'
}

exports.cursorDown = function cursorDown(n = 1) {
  return CSI + n + 'B'
}

exports.cursorForward = function cursorForward(n = 1) {
  return CSI + n + 'C'
}

exports.cursorBack = function cursorBack(n = 1) {
  return CSI + n + 'D'
}

exports.cursorNextLine = function cursorNextLine(n = 1) {
  return CSI + n + 'E'
}

exports.cursorPreviousLine = function cursorPreviousLine(n = 1) {
  return CSI + n + 'F'
}

exports.cursorPosition = function cursorPosition(column, row = 0) {
  if (row === 0) return CSI + (column + 1) + 'G'

  return CSI + (row + 1) + ';' + (column + 1) + 'H'
}

exports.eraseDisplayEnd = CSI + 'J'
exports.eraseDisplayStart = CSI + '1J'
exports.eraseDisplay = CSI + '2J'
exports.eraseLineEnd = CSI + 'K'
exports.eraseLineStart = CSI + '1K'
exports.eraseLine = CSI + '2K'

exports.scrollUp = function scrollUp(n = 1) {
  return CSI + n + 'S'
}

exports.scrollDown = function scrollDown(n = 1) {
  return CSI + n + 'T'
}

// https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_(Select_Graphic_Rendition)_parameters

exports.modifierReset = SGR(0)
exports.modifierBold = SGR(1)
exports.modifierDim = SGR(2)
exports.modifierItalic = SGR(3)
exports.modifierUnderline = SGR(4)
exports.modifierNormal = SGR(22)
exports.modifierNotItalic = SGR(23)
exports.modifierNotUnderline = SGR(24)

// https://en.wikipedia.org/wiki/ANSI_escape_code#Colors

exports.colorBlack = SGR(30)
exports.colorRed = SGR(31)
exports.colorGreen = SGR(32)
exports.colorYellow = SGR(33)
exports.colorBlue = SGR(34)
exports.colorMagenta = SGR(35)
exports.colorCyan = SGR(36)
exports.colorWhite = SGR(37)
exports.colorDefault = SGR(39)
exports.colorBrightBlack = SGR(90)
exports.colorBrightRed = SGR(91)
exports.colorBrightGreen = SGR(92)
exports.colorBrightYellow = SGR(93)
exports.colorBrightBlue = SGR(94)
exports.colorBrightMagenta = SGR(95)
exports.colorBrightCyan = SGR(96)
exports.colorBrightWhite = SGR(97)
{
  "name": "bare-ansi-escapes",
  "version": "2.2.3",
  "description": "Parse and produce ANSI escape sequences",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./key-decoder": {
      "types": "./key-decoder.d.ts",
      "default": "./key-decoder.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "key-decoder.js",
    "key-decoder.d.ts"
  ],
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-ansi-escapes.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-ansi-escapes/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-ansi-escapes#readme",
  "dependencies": {
    "bare-stream": "^2.6.5"
  },
  "devDependencies": {
    "bare-buffer": "^3.0.2",
    "brittle": "^3.3.2",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  },
  "peerDependencies": {
    "bare-buffer": "*"
  },
  "peerDependenciesMeta": {
    "bare-buffer": {
      "optional": true
    }
  }
}
const inspect = require('bare-inspect')

class AssertionError extends Error {
  constructor(opts = {}) {
    let { message = null, actual, expected, operator } = opts

    if (message === null) {
      message = `${inspect(actual)} ${operator} ${inspect(expected)}`
    }

    super(message)

    this.actual = actual
    this.expected = expected
    this.operator = operator
  }

  get name() {
    return 'AssertionError'
  }

  get code() {
    'ASSERTION'
  }
}

function assertFail(opts, fn) {
  if (opts.message instanceof Error) throw opts.message

  const err = new AssertionError(opts)

  if (Error.captureStackTrace) Error.captureStackTrace(err, fn)

  throw err
}

module.exports = exports = function assert(actual, message) {
  if (actual) return

  assertFail({ message, actual, expected: true, operator: '==' }, assert)
}

exports.AssertionError = AssertionError

exports.fail = function fail(message) {
  if (message === undefined) message = 'Failed'

  assertFail({ message, operator: 'fail' }, fail)
}

exports.ok = function ok(actual, message) {
  if (actual) return

  assertFail({ message, actual, expected: true, operator: '==' }, ok)
}

exports.notOk = function ok(actual, message) {
  if (!actual) return

  assertFail({ message, actual, expected: false, operator: '==' }, ok)
}

exports.equal = function equal(actual, expected, message) {
  if (actual == expected || (actual !== actual && expected !== expected)) {
    return
  }

  assertFail({ message, actual, expected, operator: '==' }, equal)
}

exports.notEqual = function notEqual(actual, expected, message) {
  if (actual != expected && (actual === actual || expected === expected)) {
    return
  }

  assertFail({ message, actual, expected, operator: '!=' }, notEqual)
}

exports.strictEqual = function strictEqual(actual, expected, message) {
  if (Object.is(actual, expected)) return

  assertFail(
    { message, actual, expected, operator: 'strictEqual' },
    strictEqual
  )
}

exports.notStrictEqual = function notStrictEqual(actual, expected, message) {
  if (!Object.is(actual, expected)) return

  assertFail(
    { message, actual, expected, operator: 'notStrictEqual' },
    notStrictEqual
  )
}
{
  "name": "bare-assert",
  "version": "1.2.0",
  "description": "Assertion library for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts"
  ],
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-assert.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-assert/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-assert#readme",
  "dependencies": {
    "bare-inspect": "^3.1.2"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  }
}
module.exports = require.addon()
const binding = require('./binding')

exports.Resolver = class DNSResolver {
  constructor() {
    this._handle = binding.initResolver()
  }

  resolveTxt(hostname, cb = noop) {
    binding.resolveTxt(this._handle, hostname, cb, this)
  }

  destroy() {
    binding.destroyResolver(this._handle)
    this._handle = null
  }

  static global = new this()
}

function onlookup(err, addresses) {
  const req = this

  if (err) return req.cb(err, null, 0)

  const { address, family } = addresses[0]

  return req.cb(null, address, family)
}

function onlookupall(err, addresses) {
  const req = this

  if (err) return req.cb(err, null)

  return req.cb(null, addresses)
}

exports.lookup = function lookup(hostname, opts = {}, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  let { family = 0, all = false } = opts

  if (typeof family === 'string') {
    switch (family) {
      case 'IPv4':
        family = 4
        break
      case 'IPv6':
        family = 6
        break
      default:
        family = 0
    }
  }

  const req = {
    cb,
    handle: null
  }

  req.handle = binding.lookup(
    hostname,
    family || 0,
    all,
    req,
    all ? onlookupall : onlookup
  )
}

exports.resolveTxt = function resolveTxt(hostname, cb) {
  exports.Resolver.global.resolveTxt(hostname, cb)
}

function noop() {}
{
  "name": "bare-dns",
  "version": "2.1.4",
  "description": "Domain name resolution for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-dns.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-dns/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-dns",
  "engines": {
    "bare": ">=1.7.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "cmake-bare": "^1.1.6",
    "cmake-fetch": "^1.3.0",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
const os = require('bare-os')

module.exports = new Proxy(Object.create(null), {
  ownKeys (target) {
    return os.getEnvKeys()
  },

  get (target, property) {
    if (typeof property !== 'string') return

    return os.getEnv(property)
  },

  has (target, property) {
    if (typeof property !== 'string') return false

    return os.hasEnv(property)
  },

  set (target, property, value) {
    if (typeof property !== 'string') return

    const type = typeof value

    if (type !== 'string' && type !== 'number' && type !== 'boolean') {
      throw new Error('Environment variable must be of type string, number, or boolean')
    }

    value = String(value)

    os.setEnv(property, value)

    return true
  },

  deleteProperty (target, property) {
    if (typeof property !== 'string') return

    os.unsetEnv(property)
  },

  getOwnPropertyDescriptor (target, property) {
    return {
      value: this.get(target, property),
      enumerable: true,
      configurable: true,
      writable: true
    }
  }
})
{
  "name": "bare-env",
  "version": "3.0.0",
  "description": "Environment variable support for JavaScript",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "scripts": {
    "test": "standard && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-env.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-env/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-env#readme",
  "dependencies": {
    "bare-os": "^3.0.1"
  },
  "devDependencies": {
    "brittle": "^3.2.1",
    "standard": "^17.0.0"
  }
}
const errors = require('./lib/errors')

class EventListener {
  constructor() {
    this.list = []
    this.count = 0
  }

  append(ctx, name, fn, once) {
    this.count++
    ctx.emit('newListener', name, fn) // Emit BEFORE adding
    this.list.push([fn, once])
  }

  prepend(ctx, name, fn, once) {
    this.count++
    ctx.emit('newListener', name, fn) // Emit BEFORE adding
    this.list.unshift([fn, once])
  }

  remove(ctx, name, fn) {
    for (let i = 0, n = this.list.length; i < n; i++) {
      const l = this.list[i]

      if (l[0] === fn) {
        this.list.splice(i, 1)

        if (this.count === 1) delete ctx._events[name]

        ctx.emit('removeListener', name, fn) // Emit AFTER removing

        this.count--
        return
      }
    }
  }

  removeAll(ctx, name) {
    const list = [...this.list]
    this.list = []

    if (this.count === list.length) delete ctx._events[name]

    for (let i = list.length - 1; i >= 0; i--) {
      ctx.emit('removeListener', name, list[i][0]) // Emit AFTER removing
    }

    this.count -= list.length
  }

  emit(ctx, name, ...args) {
    const list = [...this.list]

    for (let i = 0, n = list.length; i < n; i++) {
      const l = list[i]

      if (l[1] === true) this.remove(ctx, name, l[0])

      Reflect.apply(l[0], ctx, args)
    }

    return list.length > 0
  }
}

function appendListener(ctx, name, fn, once) {
  if (ctx._events === undefined) ctx._events = Object.create(null)
  const e = ctx._events[name] || (ctx._events[name] = new EventListener())
  e.append(ctx, name, fn, once)
  return ctx
}

function prependListener(ctx, name, fn, once) {
  if (ctx._events === undefined) ctx._events = Object.create(null)
  const e = ctx._events[name] || (ctx._events[name] = new EventListener())
  e.prepend(ctx, name, fn, once)
  return ctx
}

function removeListener(ctx, name, fn) {
  if (ctx._events === undefined) return ctx
  const e = ctx._events[name]
  if (e !== undefined) e.remove(ctx, name, fn)
  return ctx
}

function throwUnhandledError(...args) {
  let err

  if (args.length > 0) err = args[0]

  if (err instanceof Error === false) err = errors.UNHANDLED_ERROR(err)

  if (Error.captureStackTrace) {
    Error.captureStackTrace(err, exports.prototype.emit)
  }

  queueMicrotask(() => {
    throw err
  })
}

module.exports = exports = class EventEmitter {
  constructor() {
    this._events = Object.create(null)
  }

  addListener(name, fn) {
    return appendListener(this, name, fn, false)
  }

  addOnceListener(name, fn) {
    return appendListener(this, name, fn, true)
  }

  prependListener(name, fn) {
    return prependListener(this, name, fn, false)
  }

  prependOnceListener(name, fn) {
    return prependListener(this, name, fn, true)
  }

  removeListener(name, fn) {
    return removeListener(this, name, fn)
  }

  on(name, fn) {
    return appendListener(this, name, fn, false)
  }

  once(name, fn) {
    return appendListener(this, name, fn, true)
  }

  off(name, fn) {
    return removeListener(this, name, fn)
  }

  emit(name, ...args) {
    if (name === 'error' && this._events !== undefined && this._events.error === undefined) {
      throwUnhandledError(...args)
    }

    if (this._events === undefined) return false
    const e = this._events[name]
    return e === undefined ? false : e.emit(this, name, ...args)
  }

  listeners(name) {
    if (this._events === undefined) return []
    const e = this._events[name]
    return e === undefined ? [] : [...e.list]
  }

  listenerCount(name) {
    if (this._events === undefined) return 0
    const e = this._events[name]
    return e === undefined ? 0 : e.list.length
  }

  getMaxListeners() {
    return EventEmitter.defaultMaxListeners
  }

  setMaxListeners(n) {}

  removeAllListeners(name) {
    if (arguments.length === 0) {
      for (const key of Reflect.ownKeys(this._events)) {
        if (key === 'removeListener') continue
        this.removeAllListeners(key)
      }
      this.removeAllListeners('removeListener')
    } else {
      const e = this._events[name]
      if (e !== undefined) e.removeAll(this, name)
    }
    return this
  }
}

exports.EventEmitter = exports

exports.errors = errors

exports.defaultMaxListeners = 10

exports.on = function on(emitter, name, opts = {}) {
  const { signal } = opts

  if (signal && signal.aborted) {
    throw errors.OPERATION_ABORTED(signal.reason)
  }

  let error = null
  let done = false

  const events = []
  const promises = []

  if (name !== 'error') emitter.on('error', onerror)

  if (signal) signal.addEventListener('abort', onabort)

  emitter.on(name, onevent)

  return {
    next() {
      if (events.length) {
        return Promise.resolve({ value: events.shift(), done: false })
      }

      if (error) {
        const err = error

        error = null

        return Promise.reject(err)
      }

      if (done) return onclose()

      return new Promise((resolve, reject) => promises.push({ resolve, reject }))
    },

    return() {
      return onclose()
    },

    throw(err) {
      return onerror(err)
    },

    [Symbol.asyncIterator]() {
      return this
    }
  }

  function onevent(...args) {
    if (promises.length) {
      promises.shift().resolve({ value: args, done: false })
    } else {
      events.push(args)
    }
  }

  function onerror(err) {
    emitter.off(name, onevent).off('error', onerror)

    if (promises.length) {
      promises.shift().reject(err)
    } else {
      error = err
    }

    return Promise.resolve({ done: true })
  }

  function onabort() {
    signal.removeEventListener('abort', onabort)

    onerror(errors.OPERATION_ABORTED(signal.reason))
  }

  function onclose() {
    emitter.off(name, onevent)

    if (name !== 'error') emitter.off('error', onerror)

    if (signal) signal.removeEventListener('abort', onabort)

    done = true

    if (promises.length) promises.shift().resolve({ done: true })

    return Promise.resolve({ done: true })
  }
}

exports.once = function once(emitter, name, opts = {}) {
  const { signal } = opts

  if (signal && signal.aborted) {
    return Promise.reject(errors.OPERATION_ABORTED(signal.reason))
  }

  return new Promise((resolve, reject) => {
    if (name !== 'error') emitter.on('error', onerror)

    if (signal) signal.addEventListener('abort', onabort)

    emitter.once(name, onevent)

    function onevent(...args) {
      if (name !== 'error') emitter.off('error', onerror)

      if (signal) signal.removeEventListener('abort', onabort)

      resolve(args)
    }

    function onerror(err) {
      emitter.off(name, onevent)

      if (name !== 'error') emitter.off('error', onerror)

      reject(err)
    }

    function onabort() {
      signal.removeEventListener('abort', onabort)

      onerror(errors.OPERATION_ABORTED(signal.reason))
    }
  })
}

exports.forward = function forward(from, to, names, opts = {}) {
  if (typeof names === 'string') names = [names]

  const { emit = to.emit.bind(to) } = opts

  const listeners = names.map(
    (name) =>
      function onevent(...args) {
        emit(name, ...args)
      }
  )

  to.on('newListener', (name) => {
    const i = names.indexOf(name)

    if (i !== -1 && to.listenerCount(name) === 0) {
      from.on(name, listeners[i])
    }
  }).on('removeListener', (name) => {
    const i = names.indexOf(name)

    if (i !== -1 && to.listenerCount(name) === 0) {
      from.off(name, listeners[i])
    }
  })
}

exports.listenerCount = function listenerCount(emitter, name) {
  return emitter.listenerCount(name)
}

exports.getMaxListeners = function getMaxListeners(emitter) {
  if (typeof emitter.getMaxListeners === 'function') {
    return emitter.getMaxListeners()
  }

  return exports.defaultMaxListeners
}

exports.setMaxListeners = function setMaxListeners(n, ...emitters) {
  if (emitters.length === 0) exports.defaultMaxListeners = n
  else {
    for (const emitter of emitters) {
      if (typeof emitter.setMaxListeners === 'function') {
        emitter.setMaxListeners(n)
      }
    }
  }
}
module.exports = class EventEmitterError extends Error {
  constructor(msg, code, fn = EventEmitterError, opts) {
    super(`${code}: ${msg}`, opts)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'EventEmitterError'
  }

  static OPERATION_ABORTED(cause, msg = 'Operation aborted') {
    return new EventEmitterError(msg, 'OPERATION_ABORTED', EventEmitterError.OPERATION_ABORTED, {
      cause
    })
  }

  static UNHANDLED_ERROR(cause, msg = 'Unhandled error') {
    return new EventEmitterError(msg, 'UNHANDLED_ERROR', EventEmitterError.UNHANDLED_ERROR, {
      cause
    })
  }
}
{
  "name": "bare-events",
  "version": "2.8.2",
  "description": "Event emitters for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    },
    "./web": {
      "types": "./web.d.ts",
      "default": "./web.js"
    },
    "./errors": "./lib/errors.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "global.js",
    "global.d.ts",
    "web.js",
    "web.d.ts",
    "lib"
  ],
  "scripts": {
    "test": "npm run lint && npm run test:bare && npm run test:node",
    "test:bare": "bare test.js",
    "test:node": "node test.js",
    "lint": "prettier . --check"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-events.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-events/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-events#readme",
  "devDependencies": {
    "bare-abort-controller": "^1.0.0",
    "brittle": "^3.3.2",
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^2.0.0",
    "uncaughts": "^1.1.1"
  },
  "peerDependencies": {
    "bare-abort-controller": "*"
  },
  "peerDependenciesMeta": {
    "bare-abort-controller": {
      "optional": true
    }
  }
}
module.exports = require.addon()
const FIFO = require('fast-fifo')
const EventEmitter = require('bare-events')
const path = require('bare-path')
const { isURL, fileURLToPath } = require('bare-url')
const { Readable, Writable } = require('bare-stream')
const binding = require('./binding')
const constants = require('./lib/constants')
const FileError = require('./lib/errors')

const isWindows = Bare.platform === 'win32'

exports.constants = constants

class FileRequest {
  static borrow() {
    if (this._free.length > 0) return this._free.pop()
    return new FileRequest()
  }

  static return(req) {
    if (this._free.length < 32) this._free.push(req.reset())
    else req.destroy()
  }

  constructor() {
    this._reset()
    this._handle = binding.requestInit(this, this._onresult)
  }

  get handle() {
    return this._handle
  }

  retain(value) {
    this._retain = value // Tie the lifetime of `value` to the lifetime of `this`
  }

  reset() {
    if (this._handle === null) return this

    binding.requestReset(this._handle)

    this._reset()

    return this
  }

  destroy() {
    if (this._handle === null) return this

    binding.requestDestroy(this._handle)

    this._reset()
    this._handle = null

    return this
  }

  then(resolve, reject) {
    return this._promise.then(resolve, reject)
  }

  return() {
    if (this._handle === null) return this

    FileRequest.return(this)

    return this
  }

  _reset() {
    this._promise = new Promise((resolve, reject) => {
      this._resolve = resolve
      this._reject = reject
    })
    this._retain = null
  }

  _onresult(err, status) {
    if (err) this._reject(err)
    else this._resolve(status)
  }
}

FileRequest._free = []

function ok(result, cb) {
  if (typeof result === 'function') {
    cb = result
    result = undefined
  }

  if (cb) cb(null, result)
  else return result
}

function fail(err, cb) {
  if (cb) cb(err)
  else throw err
}

function done(err, result, cb) {
  if (typeof result === 'function') {
    cb = result
    result = undefined
  }

  if (err) fail(err, cb)
  else return ok(result, cb)
}

async function open(filepath, flags = 'r', mode = 0o666, cb) {
  if (typeof flags === 'function') {
    cb = flags
    flags = 'r'
    mode = 0o666
  } else if (typeof mode === 'function') {
    cb = mode
    mode = 0o666
  }

  if (typeof flags === 'string') flags = toFlags(flags)
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let fd
  let err = null
  try {
    binding.open(req.handle, filepath, flags, mode)

    fd = await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'open',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, fd, cb)
}

function openSync(filepath, flags = 'r', mode = 0o666) {
  if (typeof flags === 'string') flags = toFlags(flags)
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    return binding.openSync(req.handle, filepath, flags, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'open',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function close(fd, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.close(req.handle, fd)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'close', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function closeSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.closeSync(req.handle, fd)
  } catch (e) {
    throw new FileError(e.message, { operation: 'close', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function access(filepath, mode = constants.F_OK, cb) {
  if (typeof mode === 'function') {
    cb = mode
    mode = constants.F_OK
  }

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.access(req.handle, filepath, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'access',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function accessSync(filepath, mode = constants.F_OK) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.accessSync(req.handle, filepath, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'access',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function exists(filepath, cb) {
  let ok = true
  try {
    await access(filepath)
  } catch {
    ok = false
  }

  return done(null, ok, cb)
}

function existsSync(filepath) {
  try {
    accessSync(filepath)
  } catch {
    return false
  }

  return true
}

async function read(fd, buffer, offset = 0, len = buffer.byteLength - offset, pos = -1, cb) {
  if (typeof offset === 'function') {
    cb = offset
    offset = 0
    len = buffer.byteLength
    pos = -1
  } else if (typeof len === 'function') {
    cb = len
    len = buffer.byteLength - offset
    pos = -1
  } else if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.read(req.handle, fd, buffer, offset, len, pos)

    req.retain(buffer)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'read', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function readSync(fd, buffer, offset = 0, len = buffer.byteLength - offset, pos = -1) {
  const req = FileRequest.borrow()

  try {
    return binding.readSync(req.handle, fd, buffer, offset, len, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'read', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function readv(fd, buffers, pos = -1, cb) {
  if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.readv(req.handle, fd, buffers, pos)

    req.retain(buffers)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'readv', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function readvSync(fd, buffers, pos = -1) {
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  try {
    return binding.readvSync(req.handle, fd, buffers, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'readv', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function write(fd, data, offset, len, pos = -1, cb) {
  if (typeof data === 'string') {
    let encoding = len
    cb = pos
    pos = offset

    if (typeof pos === 'function') {
      cb = pos
      pos = -1
      encoding = 'utf8'
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = 'utf8'
    }

    if (typeof pos === 'string') {
      encoding = pos
      pos = -1
    }

    data = Buffer.from(data, encoding)
    offset = 0
    len = data.byteLength
  } else if (typeof offset === 'function') {
    cb = offset
    offset = 0
    len = data.byteLength
    pos = -1
  } else if (typeof len === 'function') {
    cb = len
    len = data.byteLength - offset
    pos = -1
  } else if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof offset !== 'number') offset = 0
  if (typeof len !== 'number') len = data.byteLength - offset
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.write(req.handle, fd, data, offset, len, pos)

    req.retain(data)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'write', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function writeSync(fd, data, offset, len, pos = -1) {
  if (typeof data === 'string') {
    let encoding = len
    pos = offset

    if (typeof pos === 'string') {
      encoding = pos
      pos = -1
    }

    data = Buffer.from(data, encoding)
    offset = 0
    len = data.byteLength
  }

  if (typeof offset !== 'number') offset = 0
  if (typeof len !== 'number') len = data.byteLength - offset
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  try {
    return binding.writeSync(req.handle, fd, data, offset, len, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'write', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function writev(fd, buffers, pos = -1, cb) {
  if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.writev(req.handle, fd, buffers, pos)

    req.retain(buffers)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'writev', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function writevSync(fd, buffers, pos = -1) {
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  try {
    return binding.writevSync(req.handle, fd, buffers, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'writev', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function stat(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.stat(req.handle, filepath)

    await req

    st = new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'stat', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function statSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.statSync(req.handle, filepath)

    return new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'stat', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function lstat(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.lstat(req.handle, filepath)

    await req

    st = new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'lstat', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function lstatSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.lstatSync(req.handle, filepath)

    return new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'lstat', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function fstat(fd, cb) {
  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.fstat(req.handle, fd)

    await req

    st = new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'fstat', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function fstatSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.fstatSync(req.handle, fd)

    return new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'fstat', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function statfs(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.statfs(req.handle, filepath)

    await req

    st = new StatFs(...binding.requestResultStatfs(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'statfs', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function statfsSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.statfsSync(req.handle, filepath)

    return new StatFs(...binding.requestResultStatfs(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'statfs', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function ftruncate(fd, len = 0, cb) {
  if (typeof len === 'function') {
    cb = len
    len = 0
  }

  if (typeof len !== 'number') len = 0

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.ftruncate(req.handle, fd, len)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'ftruncate', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function ftruncateSync(fd, len = 0) {
  if (typeof len !== 'number') len = 0

  const req = FileRequest.borrow()

  try {
    binding.ftruncateSync(req.handle, fd, len)
  } catch (e) {
    throw new FileError(e.message, { operation: 'ftruncate', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function truncate(filepath, len, cb) {
  let fd = -1
  let err

  try {
    fd = await open(filepath, 'r+')

    await ftruncate(fd, len)
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) await close(fd)
  }

  return done(err, cb)
}

function truncateSync(filepath, len) {
  let fd = -1
  let err

  try {
    fd = openSync(filepath, 'r+')

    ftruncateSync(fd, len)
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) closeSync(fd)
  }
}

async function chmod(filepath, mode, cb) {
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.chmod(req.handle, filepath, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'chmod',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function chmodSync(filepath, mode) {
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.chmodSync(req.handle, filepath, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'chmod',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function fchmod(fd, mode, cb) {
  if (typeof mode === 'string') mode = toMode(mode)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fchmod(req.handle, fd, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fchmod', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fchmodSync(fd, mode) {
  if (typeof mode === 'string') mode = toMode(mode)

  const req = FileRequest.borrow()

  try {
    binding.fchmodSync(req.handle, fd, mode)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fchmod', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function chown(filepath, uid, gid, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.chown(req.handle, filepath, uid, gid)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'chown', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function chownSync(filepath, uid, gid) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.chownSync(req.handle, filepath, uid, gid)
  } catch (e) {
    throw new FileError(e.message, { operation: 'chownSync', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function lchown(filepath, uid, gid, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.lchown(req.handle, filepath, uid, gid)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'lchown', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function lchownSync(filepath, uid, gid) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.lchownSync(req.handle, filepath, uid, gid)
  } catch (e) {
    throw new FileError(e.message, { operation: 'lchownSync', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function fchown(fd, uid, gid, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fchown(req.handle, fd, uid, gid)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fchown', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fchownSync(fd, uid, gid) {
  const req = FileRequest.borrow()

  try {
    binding.fchownSync(req.handle, fd, uid, gid)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fchownSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function utimes(filepath, atime, mtime, cb) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.utimes(req.handle, filepath, atime, mtime)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'utimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function utimesSync(filepath, atime, mtime) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.utimesSync(req.handle, filepath, atime, mtime)
  } catch (e) {
    throw new FileError(e.message, { operation: 'utimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function lutimes(filepath, atime, mtime, cb) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.lutimes(req.handle, filepath, atime, mtime)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'lutimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function lutimesSync(filepath, atime, mtime) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.lutimesSync(req.handle, filepath, atime, mtime)
  } catch (e) {
    throw new FileError(e.message, { operation: 'lutimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function futimes(fd, atime, mtime, cb) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.futimes(req.handle, fd, atime, mtime)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'futimes', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function futimesSync(fd, atime, mtime) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  const req = FileRequest.borrow()

  try {
    binding.futimesSync(req.handle, fd, atime, mtime)
  } catch (e) {
    throw new FileError(e.message, { operation: 'futimesSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function link(src, dst, cb) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.link(req.handle, src, dst)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'link', code: e.code, path: src, destination: dst })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function linkSync(src, dst) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  try {
    binding.linkSync(req.handle, src, dst)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'linkSync',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }
}

async function mkdir(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = { mode: 0o777 }
  }

  if (typeof opts === 'number') opts = { mode: opts }
  else if (!opts) opts = {}

  const mode = typeof opts.mode === 'number' ? opts.mode : 0o777

  filepath = toNamespacedPath(filepath)

  if (opts.recursive) {
    let err = null
    try {
      try {
        await mkdir(filepath, { mode })
      } catch (err) {
        if (err.code !== 'ENOENT') {
          if (!(await stat(filepath)).isDirectory()) throw err
        } else {
          while (filepath.endsWith(path.sep)) filepath = filepath.slice(0, -1)
          const i = filepath.lastIndexOf(path.sep)
          if (i <= 0) throw err

          await mkdir(filepath.slice(0, i), { mode, recursive: true })

          try {
            await mkdir(filepath, { mode })
          } catch (err) {
            if (!(await stat(filepath)).isDirectory()) throw err
          }
        }
      }
    } catch (e) {
      err = e
    }

    return done(err, cb)
  }

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.mkdir(req.handle, filepath, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'mkdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function mkdirSync(filepath, opts) {
  if (typeof opts === 'number') opts = { mode: opts }
  else if (!opts) opts = {}

  const mode = typeof opts.mode === 'number' ? opts.mode : 0o777

  filepath = toNamespacedPath(filepath)

  if (opts.recursive) {
    try {
      mkdirSync(filepath, { mode })
    } catch (err) {
      if (err.code !== 'ENOENT') {
        if (!statSync(filepath).isDirectory()) throw err
      } else {
        while (filepath.endsWith(path.sep)) filepath = filepath.slice(0, -1)
        const i = filepath.lastIndexOf(path.sep)
        if (i <= 0) throw err

        mkdirSync(filepath.slice(0, i), { mode, recursive: true })

        try {
          mkdirSync(filepath, { mode })
        } catch (err) {
          if (!statSync(filepath).isDirectory()) throw err
        }
      }
    }

    return
  }

  const req = FileRequest.borrow()

  try {
    binding.mkdirSync(req.handle, filepath, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'mkdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function mkdtemp(prefix, cb) {
  prefix = toNamespacedPath(prefix)

  const req = FileRequest.borrow()

  let res
  let err = null
  try {
    binding.mkdtemp(req.handle, prefix + 'XXXXXX')

    await req

    res = binding.requestResultPath(req.handle)
  } catch (e) {
    err = new FileError(e.message, { operation: 'mkdtemp', code: e.code, path: prefix })
  } finally {
    req.return()
  }

  return done(err, res, cb)
}

function mkdtempSync(prefix) {
  prefix = toNamespacedPath(prefix)

  const req = FileRequest.borrow()

  try {
    binding.mkdtempSync(req.handle, prefix + 'XXXXXX')

    return binding.requestResultPath(req.handle)
  } catch (e) {
    throw new FileError(e.message, { operation: 'mkdtempSync', code: e.code, path: prefix })
  } finally {
    req.return()
  }
}

async function rmdir(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.rmdir(req.handle, filepath)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'rmdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function rmdirSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.rmdirSync(req.handle, filepath)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'rmdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function rm(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  let err = null
  try {
    const st = await lstat(filepath)

    if (st.isDirectory()) {
      if (opts.recursive) {
        try {
          await rmdir(filepath)
        } catch (err) {
          if (err.code !== 'ENOTEMPTY') throw err

          const files = await readdir(filepath)

          for (const file of files) {
            await rm(filepath + path.sep + file, opts)
          }

          await rmdir(filepath)
        }
      } else {
        throw new FileError('is a directory', {
          operation: 'rm',
          code: 'EISDIR',
          path: filepath
        })
      }
    } else {
      await unlink(filepath)
    }
  } catch (e) {
    if (e.code !== 'ENOENT' || !opts.force) err = e
  }

  return done(err, cb)
}

function rmSync(filepath, opts) {
  if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  try {
    const st = lstatSync(filepath)

    if (st.isDirectory()) {
      if (opts.recursive) {
        try {
          rmdirSync(filepath)
        } catch (err) {
          if (err.code !== 'ENOTEMPTY') throw err

          const files = readdirSync(filepath)

          for (const file of files) {
            rmSync(filepath + path.sep + file, opts)
          }

          rmdirSync(filepath)
        }
      } else {
        throw new FileError('is a directory', {
          operation: 'rm',
          code: 'EISDIR',
          path: filepath
        })
      }
    } else {
      unlinkSync(filepath)
    }
  } catch (err) {
    if (err.code !== 'ENOENT' || !opts.force) throw err
  }
}

async function unlink(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.unlink(req.handle, filepath)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'unlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function unlinkSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.unlinkSync(req.handle, filepath)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'unlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function rename(src, dst, cb) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.rename(req.handle, src, dst)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'rename',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function renameSync(src, dst) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  try {
    binding.renameSync(req.handle, src, dst)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'rename',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }
}

async function copyFile(src, dst, mode = 0, cb) {
  if (typeof mode === 'function') {
    cb = mode
    mode = 0
  }

  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.copyfile(req.handle, src, dst, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'copyfile',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function copyFileSync(src, dst, mode = 0) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  try {
    binding.copyfileSync(req.handle, src, dst, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'copyfile',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }
}

async function cp(src, dst, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (!opts) opts = {}

  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  let err = null
  try {
    const st = await lstat(src)

    if (st.isDirectory()) {
      if (opts.recursive !== true) {
        throw new FileError('is a directory', { operation: 'cp', code: 'EISDIR', path: src })
      }

      try {
        await lstat(dst)
      } catch (e) {
        if (e.code !== 'ENOENT') throw e

        await mkdir(dst, { mode: st.mode, recursive: true })
      }

      const dir = await opendir(src)
      for await (const { name } of dir) {
        await cp(path.join(src, name), path.join(dst, name), opts)
      }
    } else if (st.isFile()) {
      await copyFile(src, dst)
      await chmod(dst, st.mode)
    }
  } catch (e) {
    err = e
  }

  return done(err, cb)
}

function cpSync(src, dst, opts = {}) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const st = lstatSync(src)

  if (st.isDirectory()) {
    if (opts.recursive !== true) {
      throw new FileError('is a directory', { operation: 'cp', code: 'EISDIR', path: src })
    }

    try {
      lstatSync(dst)
    } catch (e) {
      if (e.code !== 'ENOENT') throw e

      mkdirSync(dst, { mode: st.mode, recursive: true })
    }

    const dir = opendirSync(src)
    for (const { name } of dir) {
      cpSync(path.join(src, name), path.join(dst, name), opts)
    }
  } else if (st.isFile()) {
    copyFileSync(src, dst)
    chmodSync(dst, st.mode)
  }
}

async function realpath(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let res
  let err = null
  try {
    binding.realpath(req.handle, filepath)

    await req

    res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'realpath',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, res, cb)
}

function realpathSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.realpathSync(req.handle, filepath)

    let res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)

    return res
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'realpath',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function readlink(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let res
  let err = null
  try {
    binding.readlink(req.handle, filepath)

    await req

    res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'readlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, res, cb)
}

function readlinkSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.readlinkSync(req.handle, filepath)

    let res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)

    return res
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'readlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function fsync(fd, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fsync(req.handle, fd)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fsync', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fsyncSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.fsyncSync(req.handle, fd)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fsyncSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function fdatasync(fd, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fdatasync(req.handle, fd)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fdatasync', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fdatasyncSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.fdatasyncSync(req.handle, fd)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fdatasyncSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

function normalizeSymlinkTarget(target, type, filepath) {
  if (isWindows) {
    if (type === constants.UV_FS_SYMLINK_JUNCTION) target = path.resolve(filepath, '..', target)

    if (path.isAbsolute(target)) return path.toNamespacedPath(target)

    return target.replace(/\//g, path.sep)
  }

  return target
}

async function symlink(target, filepath, type, cb) {
  if (typeof type === 'function') {
    cb = type
    type = null
  }

  filepath = toNamespacedPath(filepath)

  if (typeof type === 'string') {
    switch (type) {
      case 'dir':
        type = constants.UV_FS_SYMLINK_DIR
        break
      case 'junction':
        type = constants.UV_FS_SYMLINK_JUNCTION
        break
      case 'file':
      default:
        type = 0
        break
    }
  } else if (typeof type !== 'number') {
    if (isWindows) {
      target = path.resolve(filepath, '..', target)

      try {
        type = (await stat(target)).isDirectory()
          ? constants.UV_FS_SYMLINK_DIR
          : constants.UV_FS_SYMLINK_JUNCTION
      } catch {
        type = 0
      }
    } else {
      type = 0
    }
  }

  target = normalizeSymlinkTarget(target, type, filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.symlink(req.handle, target, filepath, type)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'symlink',
      code: e.code,
      path: target,
      destination: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function symlinkSync(target, filepath, type) {
  filepath = toNamespacedPath(filepath)

  if (typeof type === 'string') {
    switch (type) {
      case 'dir':
        type = constants.UV_FS_SYMLINK_DIR
        break
      case 'junction':
        type = constants.UV_FS_SYMLINK_JUNCTION
        break
      case 'file':
      default:
        type = 0
        break
    }
  } else if (typeof type !== 'number') {
    if (isWindows) {
      target = path.resolve(filepath, '..', target)

      try {
        type = statSync(target).isDirectory()
          ? constants.UV_FS_SYMLINK_DIR
          : constants.UV_FS_SYMLINK_JUNCTION
      } catch {
        type = 0
      }
    } else {
      type = 0
    }
  }

  target = normalizeSymlinkTarget(target, type, filepath)

  const req = FileRequest.borrow()

  try {
    binding.symlinkSync(req.handle, target, filepath, type)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'symlink',
      code: e.code,
      path: target,
      destination: filepath
    })
  } finally {
    req.return()
  }
}

async function opendir(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let dir
  let err = null
  try {
    binding.opendir(req.handle, filepath)

    await req

    dir = new Dir(filepath, binding.requestResultDir(req.handle), opts)
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'opendir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, dir, cb)
}

function opendirSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.opendirSync(req.handle, filepath)

    return new Dir(filepath, binding.requestResultDir(req.handle), opts)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'opendir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function readdir(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { withFileTypes = false, recursive = false } = opts

  filepath = toNamespacedPath(filepath)

  const queue = [filepath]
  let result = []
  let err = null
  try {
    while (queue.length !== 0) {
      const dir = await opendir(queue.pop())

      for await (const entry of dir) {
        const entryPath = path.join(entry.parentPath, entry.name)

        if (withFileTypes) {
          result.push(entry)
        } else {
          result.push(path.relative(filepath, entryPath))
        }

        if (recursive && entry.isDirectory()) queue.push(entryPath)
      }
    }
  } catch (e) {
    result = []
    err = e
  }

  return done(err, result, cb)
}

function readdirSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { withFileTypes = false, recursive = false } = opts

  filepath = toNamespacedPath(filepath)

  const queue = [filepath]
  const result = []

  while (queue.length !== 0) {
    const dir = opendirSync(queue.pop(), opts)

    for (const entry of dir) {
      const entryPath = path.join(entry.parentPath, entry.name)

      if (withFileTypes) {
        result.push(entry)
      } else {
        result.push(path.relative(filepath, entryPath))
      }

      if (recursive && entry.isDirectory()) queue.push(entryPath)
    }
  }

  return result
}

async function readFile(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'buffer' } = opts

  let fd = -1
  let buffer = null
  let err = null
  try {
    fd = await open(filepath, opts.flag || 'r')

    const st = await fstat(fd)

    let len = 0

    if (st.size === 0) {
      const buffers = []

      while (true) {
        buffer = Buffer.allocUnsafe(8192)
        const r = await read(fd, buffer)
        len += r
        if (r === 0) break
        buffers.push(buffer.subarray(0, r))
      }

      buffer = Buffer.concat(buffers)
    } else {
      buffer = Buffer.allocUnsafe(st.size)

      while (true) {
        const r = await read(fd, len ? buffer.subarray(len) : buffer)
        len += r
        if (r === 0 || len === buffer.byteLength) break
      }

      if (len !== buffer.byteLength) buffer = buffer.subarray(0, len)
    }

    if (encoding !== 'buffer') buffer = buffer.toString(encoding)
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) await close(fd)
  }

  return done(err, buffer, cb)
}

function readFileSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'buffer' } = opts

  let fd = -1
  try {
    fd = openSync(filepath, opts.flag || 'r')

    const st = fstatSync(fd)

    let buffer
    let len = 0

    if (st.size === 0) {
      const buffers = []

      while (true) {
        buffer = Buffer.allocUnsafe(8192)
        const r = readSync(fd, buffer)
        len += r
        if (r === 0) break
        buffers.push(buffer.subarray(0, r))
      }

      buffer = Buffer.concat(buffers)
    } else {
      buffer = Buffer.allocUnsafe(st.size)

      while (true) {
        const r = readSync(fd, len ? buffer.subarray(len) : buffer)
        len += r
        if (r === 0 || len === buffer.byteLength) break
      }

      if (len !== buffer.byteLength) buffer = buffer.subarray(0, len)
    }

    if (encoding !== 'buffer') buffer = buffer.toString(encoding)

    return buffer
  } finally {
    if (fd !== -1) closeSync(fd)
  }
}

async function writeFile(filepath, data, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (typeof data === 'string') data = Buffer.from(data, opts.encoding)

  let fd = -1
  let len = 0
  let err = null
  try {
    fd = await open(filepath, opts.flag || 'w', opts.mode || 0o666)

    while (true) {
      len += await write(fd, len ? data.subarray(len) : data)
      if (len === data.byteLength) break
    }
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) await close(fd)
  }

  return done(err, len, cb)
}

function writeFileSync(filepath, data, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (typeof data === 'string') data = Buffer.from(data, opts.encoding)

  let fd = -1
  try {
    fd = openSync(filepath, opts.flag || 'w', opts.mode || 0o666)

    let len = 0

    while (true) {
      len += writeSync(fd, len ? data.subarray(len) : data)
      if (len === data.byteLength) break
    }
  } finally {
    if (fd !== -1) closeSync(fd)
  }
}

function appendFile(filepath, data, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (!opts.flag) opts = { ...opts, flag: 'a' }

  return writeFile(filepath, data, opts, cb)
}

function appendFileSync(filepath, data, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (!opts.flag) opts = { ...opts, flag: 'a' }

  return writeFileSync(filepath, data, opts)
}

function watch(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  return new Watcher(filepath, opts, cb)
}

class Stats {
  constructor(
    dev,
    mode,
    nlink,
    uid,
    gid,
    rdev,
    blksize,
    ino,
    size,
    blocks,
    atimeMs,
    mtimeMs,
    ctimeMs,
    birthtimeMs
  ) {
    this.dev = dev
    this.mode = mode
    this.nlink = nlink
    this.uid = uid
    this.gid = gid
    this.rdev = rdev
    this.blksize = blksize
    this.ino = ino
    this.size = size
    this.blocks = blocks
    this.atimeMs = atimeMs
    this.mtimeMs = mtimeMs
    this.ctimeMs = ctimeMs
    this.birthtimeMs = birthtimeMs
    this.atime = new Date(atimeMs)
    this.mtime = new Date(mtimeMs)
    this.ctime = new Date(ctimeMs)
    this.birthtime = new Date(birthtimeMs)
  }

  isDirectory() {
    return (this.mode & constants.S_IFMT) === constants.S_IFDIR
  }

  isFile() {
    return (this.mode & constants.S_IFMT) === constants.S_IFREG
  }

  isBlockDevice() {
    return (this.mode & constants.S_IFMT) === constants.S_IFBLK
  }

  isCharacterDevice() {
    return (this.mode & constants.S_IFMT) === constants.S_IFCHR
  }

  isFIFO() {
    return (this.mode & constants.S_IFMT) === constants.S_IFIFO
  }

  isSymbolicLink() {
    return (this.mode & constants.S_IFMT) === constants.S_IFLNK
  }

  isSocket() {
    return (this.mode & constants.S_IFMT) === constants.S_IFSOCK
  }
}

class StatFs {
  constructor(type, bsize, blocks, bfree, bavail, files, ffree) {
    this.type = type
    this.bsize = bsize
    this.blocks = blocks
    this.bfree = bfree
    this.bavail = bavail
    this.files = files
    this.ffree = ffree
  }
}

class Dir {
  constructor(path, handle, opts = {}) {
    const { encoding = 'utf8', bufferSize = 32 } = opts

    this.path = path

    this._encoding = encoding
    this._capacity = bufferSize
    this._buffer = new FIFO()
    this._ended = false
    this._handle = handle
  }

  async read(cb) {
    if (this._buffer.length) return ok(this._buffer.shift(), cb)
    if (this._ended) return ok(null, cb)

    const req = FileRequest.borrow()

    let entries
    let err = null
    try {
      req.retain(binding.readdir(req.handle, this._handle, this._capacity))

      await req

      entries = binding.requestResultDirents(req.handle)
    } catch (e) {
      err = new FileError(e.message, {
        operation: 'readdir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    if (err) return fail(err, cb)

    if (entries.length === 0) {
      this._ended = true

      return ok(null, cb)
    }

    for (const entry of entries) {
      let name = Buffer.from(entry.name)

      if (this._encoding !== 'buffer') name = name.toString(this._encoding)

      this._buffer.push(new Dirent(this.path, name, entry.type))
    }

    return ok(this._buffer.shift(), cb)
  }

  readSync() {
    if (this._buffer.length) return this._buffer.shift()
    if (this._ended) return null

    const req = FileRequest.borrow()

    let entries
    try {
      req.retain(binding.readdirSync(req.handle, this._handle, this._capacity))

      entries = binding.requestResultDirents(req.handle)
    } catch (e) {
      throw new FileError(e.message, {
        operation: 'readdir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    if (entries.length === 0) {
      this._ended = true

      return null
    }

    for (const entry of entries) {
      let name = Buffer.from(entry.name)

      if (this._encoding !== 'buffer') name = name.toString(this._encoding)

      this._buffer.push(new Dirent(this.path, name, entry.type))
    }

    return this._buffer.shift()
  }

  async close(cb) {
    const req = FileRequest.borrow()

    let err = null
    try {
      binding.closedir(req.handle, this._handle)

      await req
    } catch (e) {
      err = new FileError(e.message, {
        operation: 'closedir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    this._handle = null

    return done(err, cb)
  }

  closeSync() {
    const req = FileRequest.borrow()

    try {
      binding.closedirSync(req.handle, this._handle)
    } catch (e) {
      throw new FileError(e.message, {
        operation: 'closedir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    this._handle = null
  }

  [Symbol.dispose]() {
    this.closeSync()
  }

  async [Symbol.asyncDispose]() {
    await this.close()
  }

  *[Symbol.iterator]() {
    while (true) {
      const entry = this.readSync()
      if (entry === null) break
      yield entry
    }

    this.closeSync()
  }

  async *[Symbol.asyncIterator]() {
    while (true) {
      const entry = await this.read()
      if (entry === null) break
      yield entry
    }

    await this.close()
  }
}

class Dirent {
  constructor(parentPath, name, type) {
    this.parentPath = parentPath
    this.name = name
    this.type = type
  }

  isFile() {
    return this.type === constants.UV_DIRENT_FILE
  }

  isDirectory() {
    return this.type === constants.UV_DIRENT_DIR
  }

  isSymbolicLink() {
    return this.type === constants.UV_DIRENT_LINK
  }

  isFIFO() {
    return this.type === constants.UV_DIRENT_FIFO
  }

  isSocket() {
    return this.type === constants.UV_DIRENT_SOCKET
  }

  isCharacterDevice() {
    return this.type === constants.UV_DIRENT_CHAR
  }

  isBlockDevice() {
    return this.type === constants.UV_DIRENT_BLOCK
  }
}

class FileReadStream extends Readable {
  constructor(path, opts = {}) {
    const { eagerOpen = true } = opts

    super({ eagerOpen, ...opts })

    this.path = path
    this.fd = typeof opts.fd === 'number' ? opts.fd : -1
    this.flags = opts.flags || 'r'
    this.mode = opts.mode || 0o666

    this._offset = opts.start || 0
    this._missing = 0

    if (opts.length) {
      this._missing = opts.length
    } else if (typeof opts.end === 'number') {
      this._missing = opts.end - this._offset + 1
    } else {
      this._missing = -1
    }
  }

  async _open(cb) {
    let err

    if (this.fd === -1) {
      err = null
      try {
        this.fd = await open(this.path, this.flags, this.mode)
      } catch (e) {
        err = e
      }

      if (err) return cb(err)
    }

    let st
    err = null
    try {
      st = await fstat(this.fd)
    } catch (e) {
      err = e
    }

    if (err) return cb(err)

    if (this._missing === -1) this._missing = st.size

    if (st.size < this._offset) {
      this._offset = st.size
      this._missing = 0
    } else if (st.size < this._offset + this._missing) {
      this._missing = st.size - this._offset
    }

    cb(null)
  }

  async _read(size) {
    if (this._missing <= 0) return this.push(null)

    const data = Buffer.allocUnsafe(Math.min(this._missing, size))

    let len
    let err = null
    try {
      len = await read(this.fd, data, 0, data.byteLength, this._offset)
    } catch (e) {
      err = e
    }

    if (err) return this.destroy(err)

    if (len === 0) return this.push(null)

    if (this._missing < len) len = this._missing

    this._missing -= len
    this._offset += len

    this.push(data.subarray(0, len))
  }

  async _destroy(err, cb) {
    if (this.fd === -1) return cb(err)

    try {
      await close(this.fd)
    } catch (e) {
      err = err || e
    }

    cb(err)
  }
}

class FileWriteStream extends Writable {
  constructor(path, opts = {}) {
    const { eagerOpen = true } = opts

    super({ eagerOpen, ...opts })

    this.path = path
    this.fd = typeof opts.fd === 'number' ? opts.fd : -1
    this.flags = opts.flags || 'w'
    this.mode = opts.mode || 0o666
  }

  async _open(cb) {
    if (this.fd !== -1) return cb(null)

    let err = null
    try {
      this.fd = await open(this.path, this.flags, this.mode)
    } catch (e) {
      err = e
    }

    cb(err)
  }

  async _writev(batch, cb) {
    let err = null
    try {
      await writev(
        this.fd,
        batch.map(({ chunk }) => chunk)
      )
    } catch (e) {
      err = e
    }

    cb(err)
  }

  async _destroy(err, cb) {
    if (this.fd === -1) return cb(err)

    try {
      await close(this.fd)
    } catch (e) {
      err = err || e
    }

    cb(err)
  }
}

class Watcher extends EventEmitter {
  constructor(path, opts, onchange) {
    if (typeof opts === 'function') {
      onchange = opts
      opts = {}
    }

    if (!opts) opts = {}

    const { persistent = true, recursive = false, encoding = 'utf8' } = opts

    super()

    this._closed = false
    this._encoding = encoding
    this._handle = binding.watcherInit(path, recursive, this, this._onevent, this._onclose)

    if (!persistent) this.unref()

    if (onchange) this.on('change', onchange)
  }

  close() {
    if (this._closed) return
    this._closed = true

    binding.watcherClose(this._handle)
  }

  ref() {
    if (this._handle) binding.watcherRef(this._handle)
    return this
  }

  unref() {
    if (this._handle) binding.watcherUnref(this._handle)
    return this
  }

  [Symbol.asyncIterator]() {
    const buffer = []
    let done = false
    let error = null
    let next = null

    this.on('change', (eventType, filename) => {
      if (next) {
        next.resolve({ done: false, value: { eventType, filename } })
        next = null
      } else {
        buffer.push({ eventType, filename })
      }
    })
      .on('error', (err) => {
        done = true
        error = err

        if (next) {
          next.reject(error)
          next = null
        }
      })
      .on('close', () => {
        done = true

        if (next) {
          next.resolve({ done })
          next = null
        }
      })

    return {
      next: () =>
        new Promise((resolve, reject) => {
          if (error) return reject(error)

          if (buffer.length) return resolve({ done: false, value: buffer.shift() })

          if (done) return resolve({ done })

          next = { resolve, reject }
        })
    }
  }

  _onevent(err, events, filename) {
    if (err) {
      this.close()
      this.emit('error', err)
    } else {
      const path =
        this._encoding === 'buffer'
          ? Buffer.from(filename)
          : Buffer.from(filename).toString(this._encoding)

      if (events & binding.UV_RENAME) {
        this.emit('change', 'rename', path)
      }

      if (events & binding.UV_CHANGE) {
        this.emit('change', 'change', path)
      }
    }
  }

  _onclose() {
    this._handle = null

    this.emit('close')
  }
}

exports.access = access
exports.appendFile = appendFile
exports.chmod = chmod
exports.chown = chown
exports.close = close
exports.copyFile = copyFile
exports.cp = cp
exports.exists = exists
exports.fchmod = fchmod
exports.fchown = fchown
exports.fdatasync = fdatasync
exports.fstat = fstat
exports.fsync = fsync
exports.ftruncate = ftruncate
exports.futimes = futimes
exports.lchown = lchown
exports.lutimes = lutimes
exports.link = link
exports.lstat = lstat
exports.mkdir = mkdir
exports.mkdtemp = mkdtemp
exports.open = open
exports.opendir = opendir
exports.read = read
exports.readFile = readFile
exports.readdir = readdir
exports.readlink = readlink
exports.readv = readv
exports.realpath = realpath
exports.rename = rename
exports.rm = rm
exports.rmdir = rmdir
exports.stat = stat
exports.statfs = statfs
exports.symlink = symlink
exports.truncate = truncate
exports.unlink = unlink
exports.utimes = utimes
exports.watch = watch
exports.write = write
exports.writeFile = writeFile
exports.writev = writev

exports.accessSync = accessSync
exports.appendFileSync = appendFileSync
exports.chmodSync = chmodSync
exports.chownSync = chownSync
exports.closeSync = closeSync
exports.copyFileSync = copyFileSync
exports.cpSync = cpSync
exports.existsSync = existsSync
exports.fchmodSync = fchmodSync
exports.fchownSync = fchownSync
exports.fdatasyncSync = fdatasyncSync
exports.fstatSync = fstatSync
exports.fsyncSync = fsyncSync
exports.ftruncateSync = ftruncateSync
exports.futimesSync = futimesSync
exports.lchownSync = lchownSync
exports.lutimesSync = lutimesSync
exports.linkSync = linkSync
exports.lstatSync = lstatSync
exports.mkdirSync = mkdirSync
exports.mkdtempSync = mkdtempSync
exports.openSync = openSync
exports.opendirSync = opendirSync
exports.readFileSync = readFileSync
exports.readSync = readSync
exports.readdirSync = readdirSync
exports.readlinkSync = readlinkSync
exports.readvSync = readvSync
exports.realpathSync = realpathSync
exports.renameSync = renameSync
exports.rmSync = rmSync
exports.rmdirSync = rmdirSync
exports.statSync = statSync
exports.statfsSync = statfsSync
exports.symlinkSync = symlinkSync
exports.truncateSync = truncateSync
exports.unlinkSync = unlinkSync
exports.utimesSync = utimesSync
exports.writeFileSync = writeFileSync
exports.writeSync = writeSync
exports.writevSync = writevSync

exports.promises = require('./promises')

exports.Stats = Stats
exports.StatFs = StatFs
exports.Dir = Dir
exports.Dirent = Dirent
exports.Watcher = Watcher

exports.ReadStream = FileReadStream

exports.createReadStream = function createReadStream(path, opts) {
  return new FileReadStream(path, opts)
}

exports.WriteStream = FileWriteStream

exports.createWriteStream = function createWriteStream(path, opts) {
  return new FileWriteStream(path, opts)
}

function toNamespacedPath(filepath) {
  if (typeof filepath !== 'string') {
    if (isURL(filepath)) filepath = fileURLToPath(filepath)
    else filepath = filepath.toString()
  }

  return path.toNamespacedPath(filepath)
}

function toFlags(flags) {
  switch (flags) {
    case 'r':
      return constants.O_RDONLY
    case 'rs': // Fall through.
    case 'sr':
      return constants.O_RDONLY | constants.O_SYNC
    case 'r+':
      return constants.O_RDWR
    case 'rs+': // Fall through.
    case 'sr+':
      return constants.O_RDWR | constants.O_SYNC

    case 'w':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_WRONLY
    case 'wx': // Fall through.
    case 'xw':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_WRONLY | constants.O_EXCL

    case 'w+':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_RDWR
    case 'wx+': // Fall through.
    case 'xw+':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_RDWR | constants.O_EXCL

    case 'a':
      return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY
    case 'ax': // Fall through.
    case 'xa':
      return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY | constants.O_EXCL
    case 'as': // Fall through.
    case 'sa':
      return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY | constants.O_SYNC

    case 'a+':
      return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR
    case 'ax+': // Fall through.
    case 'xa+':
      return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR | constants.O_EXCL
    case 'as+': // Fall through.
    case 'sa+':
      return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR | constants.O_SYNC
    default:
      return 0
  }
}

function toMode(mode) {
  return parseInt(mode, 8)
}
const binding = require('../binding')

module.exports = {
  O_RDWR: binding.O_RDWR,
  O_RDONLY: binding.O_RDONLY,
  O_WRONLY: binding.O_WRONLY,
  O_CREAT: binding.O_CREAT,
  O_TRUNC: binding.O_TRUNC,
  O_APPEND: binding.O_APPEND,

  F_OK: binding.F_OK || 0,
  R_OK: binding.R_OK || 0,
  W_OK: binding.W_OK || 0,
  X_OK: binding.X_OK || 0,

  S_IFMT: binding.S_IFMT,
  S_IFREG: binding.S_IFREG,
  S_IFDIR: binding.S_IFDIR,
  S_IFCHR: binding.S_IFCHR,
  S_IFLNK: binding.S_IFLNK,
  S_IFBLK: binding.S_IFBLK || 0,
  S_IFIFO: binding.S_IFIFO || 0,
  S_IFSOCK: binding.S_IFSOCK || 0,

  S_IRUSR: binding.S_IRUSR || 0,
  S_IWUSR: binding.S_IWUSR || 0,
  S_IXUSR: binding.S_IXUSR || 0,
  S_IRGRP: binding.S_IRGRP || 0,
  S_IWGRP: binding.S_IWGRP || 0,
  S_IXGRP: binding.S_IXGRP || 0,
  S_IROTH: binding.S_IROTH || 0,
  S_IWOTH: binding.S_IWOTH || 0,
  S_IXOTH: binding.S_IXOTH || 0,

  UV_DIRENT_UNKNOWN: binding.UV_DIRENT_UNKNOWN,
  UV_DIRENT_FILE: binding.UV_DIRENT_FILE,
  UV_DIRENT_DIR: binding.UV_DIRENT_DIR,
  UV_DIRENT_LINK: binding.UV_DIRENT_LINK,
  UV_DIRENT_FIFO: binding.UV_DIRENT_FIFO,
  UV_DIRENT_SOCKET: binding.UV_DIRENT_SOCKET,
  UV_DIRENT_CHAR: binding.UV_DIRENT_CHAR,
  UV_DIRENT_BLOCK: binding.UV_DIRENT_BLOCK,

  COPYFILE_EXCL: binding.UV_FS_COPYFILE_EXCL,
  COPYFILE_FICLONE: binding.UV_FS_COPYFILE_FICLONE,
  COPYFILE_FICLONE_FORCE: binding.UV_FS_COPYFILE_FICLONE_FORCE,
  UV_FS_SYMLINK_DIR: binding.UV_FS_SYMLINK_DIR,
  UV_FS_SYMLINK_JUNCTION: binding.UV_FS_SYMLINK_JUNCTION
}
const os = require('bare-os')

module.exports = class FileError extends Error {
  constructor(msg, opts = {}) {
    const { code, operation = null, path = null, destination = null, fd = -1 } = opts

    if (operation !== null) msg += describe(operation, opts)

    super(`${code}: ${msg}`)

    this.code = code

    if (operation !== null) this.operation = operation
    if (path !== null) this.path = path
    if (destination !== null) this.destination = destination
    if (fd !== -1) this.fd = fd
  }

  get name() {
    return 'FileError'
  }

  // For Node.js compatibility
  get errno() {
    return os.constants.errnos[this.code]
  }

  // For Node.js compatibility
  get syscall() {
    return this.operation
  }

  // For Node.js compatibility
  get dest() {
    return this.destination
  }
}

function describe(operation, opts) {
  const { path = null, destination = null, fd = -1 } = opts

  let result = `, ${operation}`

  if (path !== null) {
    result += ` ${JSON.stringify(path)}`

    if (destination !== null) {
      result += ` -> ${JSON.stringify(destination)}`
    }
  } else if (fd !== -1) {
    result += ` ${fd}`
  }

  return result
}
{
  "name": "bare-fs",
  "version": "4.7.2",
  "description": "Native file system operations for Bare",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./promises": {
      "types": "./promises.d.ts",
      "default": "./promises.js"
    },
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "promises.js",
    "promises.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-fs.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-fs/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-fs#readme",
  "engines": {
    "bare": ">=1.16.0"
  },
  "dependencies": {
    "bare-events": "^2.5.4",
    "bare-path": "^3.0.0",
    "bare-stream": "^2.6.4",
    "bare-url": "^2.2.2",
    "fast-fifo": "^1.3.2"
  },
  "devDependencies": {
    "bare-buffer": "^3.0.2",
    "bare-crypto": "^1.11.2",
    "brittle": "^3.1.1",
    "cmake-bare": "^1.1.7",
    "lunte": "^1.6.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "bare-buffer": "*"
  },
  "peerDependenciesMeta": {
    "bare-buffer": {
      "optional": true
    }
  }
}
const EventEmitter = require('bare-events')
const fs = require('.')

class FileHandle extends EventEmitter {
  constructor(fd) {
    super()

    this.fd = fd
  }

  async close() {
    await fs.close(this.fd)

    this.fd = -1
    this.emit('close')
  }

  async read(buffer, ...args) {
    return {
      bytesRead: await fs.read(this.fd, buffer, ...args),
      buffer
    }
  }

  async readv(buffers, ...args) {
    return {
      bytesRead: await fs.readv(this.fd, buffers, ...args),
      buffers
    }
  }

  async write(buffer, ...args) {
    return {
      bytesWritten: await fs.write(this.fd, buffer, ...args),
      buffer
    }
  }

  async writev(buffers, ...args) {
    return {
      bytesWritten: await fs.writev(this.fd, buffers, ...args),
      buffers
    }
  }

  async stat() {
    return fs.fstat(this.fd)
  }

  async chmod(mode) {
    await fs.fchmod(this.fd, mode)
  }

  async chown(uid, gid) {
    await fs.fchown(this.fd, uid, gid)
  }

  async datasync() {
    return fs.fdatasync(this.fd)
  }

  async sync() {
    return fs.fsync(this.fd)
  }

  async truncate(len) {
    await fs.ftruncate(this.fd, len)
  }

  async utimes(atime, mtime) {
    await fs.futimes(this.fd, atime, mtime)
  }

  createReadStream(opts) {
    return fs.createReadStream(null, { ...opts, fd: this.fd })
  }

  createWriteStream(opts) {
    return fs.createWriteStream(null, { ...opts, fd: this.fd })
  }

  async [Symbol.asyncDispose]() {
    await this.close()
  }
}

exports.open = async function open(filepath, flags, mode) {
  return new FileHandle(await fs.open(filepath, flags, mode))
}

exports.access = fs.access
exports.appendFile = fs.appendFile
exports.chmod = fs.chmod
exports.chown = fs.chown
exports.constants = fs.constants
exports.copyFile = fs.copyFile
exports.cp = fs.cp
exports.lchown = fs.lchown
exports.lutimes = fs.lutimes
exports.link = fs.link
exports.lstat = fs.lstat
exports.mkdir = fs.mkdir
exports.mkdtemp = fs.mkdtemp
exports.opendir = fs.opendir
exports.readFile = fs.readFile
exports.readdir = fs.readdir
exports.readlink = fs.readlink
exports.realpath = fs.realpath
exports.rename = fs.rename
exports.rm = fs.rm
exports.rmdir = fs.rmdir
exports.stat = fs.stat
exports.statfs = fs.statfs
exports.truncate = fs.truncate
exports.symlink = fs.symlink
exports.unlink = fs.unlink
exports.utimes = fs.utimes
exports.watch = fs.watch
exports.writeFile = fs.writeFile
module.exports = require.addon()
const binding = require('./binding')

module.exports = exports = function hrtime(past) {
  let now = binding.hrtime()

  if (past) now -= BigInt(past[0]) * 1000000000n + BigInt(past[1])

  return [Number(now / 1000000000n), Number(now % 1000000000n)]
}

exports.bigint = function hrtime() {
  return binding.hrtime()
}
{
  "name": "bare-hrtime",
  "version": "2.1.1",
  "description": "High-resolution timers for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-hrtime.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-hrtime/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-hrtime#readme",
  "devDependencies": {
    "brittle": "^3.2.1",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  }
}
const errors = require('./lib/errors')

const constants = {
  REQUEST: 1,
  RESPONSE: 2,
  DATA: 3,
  END: 4
}

const TAB = 0x09
const LF = 0x0a
const CR = 0x0d
const SP = 0x20
const ZERO = 0x30
const NINE = 0x39
const UPPER_A = 0x41
const UPPER_F = 0x46
const UPPER_Z = 0x5a
const LOWER_A = 0x61
const LOWER_F = 0x66
const COLON = 0x3a

const MAX_CHUNK_SIZE_LENGTH = 16

// Header states
const FIRST_TOKEN = 0
const REQUEST_URL = 1
const REQUEST_VERSION = 2
const STATUS_CODE = 3
const STATUS_REASON = 4
const FIRST_LINE_LF = 5
const HEADER_START = 6
const HEADER_NAME = 7
const HEADER_VALUE_WS = 8
const HEADER_VALUE = 9
const HEADER_LINE_LF = 10
const HEADER_END_LF = 11

// Body states
const BODY = 12
const CHUNK_SIZE = 13
const CHUNK_SIZE_LF = 14
const CHUNK_DATA = 15
const CHUNK_EXTENSION = 16

// Trailing states
const LAST_CHUNK_LF = 17
const TRAILER_CR = 18
const TRAILER_LF = 19

module.exports = exports = class HTTPParser {
  constructor(opts = {}) {
    const { maxHeaderSize = 16384, maxHeadersCount = 2000 } = opts

    this._maxHeaderSize = maxHeaderSize
    this._maxHeadersCount = maxHeadersCount
    this._state = FIRST_TOKEN
    this._buffer = []
    this._bufferIndex = 0
    this._byteIndex = 0
    this._buffered = 0
    this._accumulator = []

    this._isResponse = false
    this._method = ''
    this._url = ''
    this._version = ''
    this._code = 0
    this._reason = ''

    this._headerName = ''
    this._headers = {}
    this._headerCount = 0
    this._headerSize = 0

    this._remaining = 0
  }

  *push(data, encoding) {
    if (typeof data === 'string') data = Buffer.from(data, encoding)

    this._buffer.push(data)
    this._buffered += data.byteLength

    yield* this._parse()

    this._compact()
  }

  end() {
    const buffers = this._buffer
    const bufferIndex = this._bufferIndex
    const byteIndex = this._byteIndex

    this._buffer = []
    this._bufferIndex = 0
    this._byteIndex = 0
    this._buffered = 0

    if (bufferIndex >= buffers.length) return Buffer.alloc(0)

    buffers[bufferIndex] = buffers[bufferIndex].subarray(byteIndex)

    const remaining = buffers.slice(bufferIndex)

    if (remaining.length === 0) return Buffer.alloc(0)
    if (remaining.length === 1) return remaining[0]

    return Buffer.concat(remaining)
  }

  _compact() {
    if (this._bufferIndex > 0) {
      this._buffer = this._buffer.slice(this._bufferIndex)
      this._bufferIndex = 0
    }

    if (this._byteIndex > 0 && this._buffer.length > 0) {
      this._buffer[0] = this._buffer[0].subarray(this._byteIndex)
      this._byteIndex = 0
    }
  }

  _consume(n) {
    this._buffered -= n

    const current = this._buffer[this._bufferIndex]

    if (this._byteIndex + n <= current.byteLength) {
      const slice = current.subarray(this._byteIndex, this._byteIndex + n)

      this._byteIndex += n

      if (this._byteIndex >= current.byteLength) {
        this._bufferIndex++
        this._byteIndex = 0
      }

      return slice
    }

    const result = Buffer.allocUnsafe(n)

    let written = 0

    while (written < n) {
      const buffer = this._buffer[this._bufferIndex]
      const available = buffer.byteLength - this._byteIndex
      const take = Math.min(available, n - written)

      buffer.copy(result, written, this._byteIndex, this._byteIndex + take)

      written += take

      this._byteIndex += take

      if (this._byteIndex >= buffer.byteLength) {
        this._bufferIndex++
        this._byteIndex = 0
      }
    }

    return result
  }

  _buildString() {
    const string = String.fromCharCode.apply(null, this._accumulator)

    this._accumulator = []

    return string
  }

  _checkHeaderSize() {
    if (++this._headerSize > this._maxHeaderSize) {
      throw errors.INVALID_MESSAGE('Header exceeds limit of ' + this._maxHeaderSize + ' bytes')
    }
  }

  _storeHeader(name, value) {
    let end = value.length

    while (end > 0 && (value.charCodeAt(end - 1) === SP || value.charCodeAt(end - 1) === TAB)) {
      end--
    }

    if (end < value.length) value = value.substring(0, end)

    this._headerCount++

    if (this._headerCount > this._maxHeadersCount) {
      throw errors.INVALID_MESSAGE('Header count exceeds limit of ' + this._maxHeadersCount)
    }

    switch (name) {
      case '__proto__':
      case 'constructor':
      case 'prototype':
        throw errors.INVALID_HEADER("Unsafe header name '" + name + "'")

      case 'host':
      case 'content-length':
      case 'transfer-encoding':
        if (name in this._headers) {
          throw errors.INVALID_HEADER("Duplicate header '" + name + "'")
        }

        this._headers[name] = value
        break

      default:
        const delimiter = name === 'cookie' ? '; ' : ', '

        if (name in this._headers) {
          this._headers[name] += delimiter + value
        } else {
          this._headers[name] = value
        }
    }
  }

  *_parse() {
    while (true) {
      if (this._state === BODY) {
        if (this._buffered === 0) return

        const available = Math.min(this._buffered, this._remaining)
        const data = this._consume(available)

        this._remaining -= available

        const ended = this._remaining === 0

        if (ended) this._state = FIRST_TOKEN

        yield { type: constants.DATA, data }

        if (ended) yield { type: constants.END }

        continue
      }

      if (this._state === CHUNK_DATA) {
        if (this._buffered < this._remaining) return

        const consumed = this._consume(this._remaining)

        if (consumed[this._remaining - 2] !== CR || consumed[this._remaining - 1] !== LF) {
          throw errors.INVALID_MESSAGE('Expected CRLF after chunk data')
        }

        const data = consumed.subarray(0, this._remaining - 2)

        this._remaining = 0
        this._state = CHUNK_SIZE

        yield { type: constants.DATA, data }

        continue
      }

      if (this._buffered === 0) return

      const byte = this._buffer[this._bufferIndex][this._byteIndex++]

      this._buffered--

      if (this._byteIndex >= this._buffer[this._bufferIndex].byteLength) {
        this._bufferIndex++
        this._byteIndex = 0
      }

      switch (this._state) {
        case FIRST_TOKEN: {
          this._checkHeaderSize()

          if (byte === SP) {
            const token = this._buildString()

            if (token.length === 0) throw errors.INVALID_MESSAGE()

            this._isResponse = token.startsWith('HTTP/')

            if (this._isResponse) {
              if (token !== 'HTTP/1.0' && token !== 'HTTP/1.1') {
                throw errors.INVALID_MESSAGE()
              }

              this._version = token
              this._state = STATUS_CODE
            } else {
              this._method = token
              this._state = REQUEST_URL
            }
          } else if (byte === CR) {
            throw errors.INVALID_MESSAGE()
          } else if (isTokenByte(byte)) {
            this._accumulator.push(byte)
          } else if (
            byte === 0x2f &&
            this._accumulator.length === 4 &&
            this._accumulator[0] === 0x48 &&
            this._accumulator[1] === 0x54 &&
            this._accumulator[2] === 0x54 &&
            this._accumulator[3] === 0x50
          ) {
            this._accumulator.push(byte)
          } else {
            throw errors.INVALID_MESSAGE()
          }

          break
        }

        case REQUEST_URL: {
          this._checkHeaderSize()

          if (byte === SP) {
            this._url = this._buildString()

            if (this._url.length === 0) throw errors.INVALID_MESSAGE()

            this._state = REQUEST_VERSION
          } else if (byte === CR) {
            throw errors.INVALID_MESSAGE()
          } else if (byte >= 0x21 && byte !== 0x7f) {
            this._accumulator.push(byte)
          } else {
            throw errors.INVALID_MESSAGE()
          }

          break
        }

        case REQUEST_VERSION: {
          this._checkHeaderSize()

          if (byte === CR) {
            this._version = this._buildString()

            if (this._version !== 'HTTP/1.0' && this._version !== 'HTTP/1.1') {
              throw errors.INVALID_MESSAGE()
            }

            this._state = FIRST_LINE_LF
          } else if (byte >= 0x21 && byte !== 0x7f) {
            this._accumulator.push(byte)
          } else {
            throw errors.INVALID_MESSAGE()
          }

          break
        }

        case STATUS_CODE: {
          this._checkHeaderSize()

          if (byte === SP) {
            if (this._accumulator.length === 0) throw errors.INVALID_MESSAGE()

            let code = 0

            for (let i = 0, n = this._accumulator.length; i < n; i++) {
              code = code * 10 + this._accumulator[i]
            }

            this._accumulator = []

            if (code < 100 || code > 999) throw errors.INVALID_MESSAGE()

            this._code = code
            this._state = STATUS_REASON
          } else if (byte >= ZERO && byte <= NINE) {
            this._accumulator.push(byte - ZERO)
          } else {
            throw errors.INVALID_MESSAGE()
          }

          break
        }

        case STATUS_REASON: {
          this._checkHeaderSize()

          if (byte === CR) {
            this._reason = this._buildString()
            this._state = FIRST_LINE_LF
          } else if (isFieldByte(byte)) {
            this._accumulator.push(byte)
          } else {
            throw errors.INVALID_MESSAGE()
          }

          break
        }

        case FIRST_LINE_LF: {
          if (byte !== LF) throw errors.INVALID_MESSAGE()

          this._headers = {}
          this._headerCount = 0
          this._state = HEADER_START

          break
        }

        case HEADER_START: {
          this._checkHeaderSize()

          if (byte === CR) {
            this._state = HEADER_END_LF
          } else if (byte !== COLON && isTokenByte(byte)) {
            this._accumulator.push(byte >= UPPER_A && byte <= UPPER_Z ? byte + 0x20 : byte)
            this._state = HEADER_NAME
          } else {
            throw errors.INVALID_HEADER()
          }

          break
        }

        case HEADER_NAME: {
          this._checkHeaderSize()

          if (byte === COLON) {
            this._headerName = this._buildString()
            this._state = HEADER_VALUE_WS
          } else if (byte !== COLON && isTokenByte(byte)) {
            this._accumulator.push(byte >= UPPER_A && byte <= UPPER_Z ? byte + 0x20 : byte)
          } else {
            throw errors.INVALID_HEADER()
          }

          break
        }

        case HEADER_VALUE_WS: {
          this._checkHeaderSize()

          if (byte === SP || byte === TAB) break

          if (byte === CR) {
            this._storeHeader(this._headerName, '')
            this._headerName = ''
            this._state = HEADER_LINE_LF

            break
          }

          if (!isFieldByte(byte)) throw errors.INVALID_HEADER()

          this._accumulator.push(byte)
          this._state = HEADER_VALUE

          break
        }

        case HEADER_VALUE: {
          this._checkHeaderSize()

          if (byte === CR) {
            this._storeHeader(this._headerName, this._buildString())
            this._headerName = ''
            this._state = HEADER_LINE_LF
          } else if (isFieldByte(byte)) {
            this._accumulator.push(byte)
          } else {
            throw errors.INVALID_HEADER()
          }

          break
        }

        case HEADER_LINE_LF: {
          if (byte !== LF) throw errors.INVALID_HEADER()

          this._state = HEADER_START

          break
        }

        case HEADER_END_LF: {
          if (byte !== LF) throw errors.INVALID_MESSAGE()

          const headers = this._headers

          if (this._isResponse) {
            yield {
              type: constants.RESPONSE,
              version: this._version,
              code: this._code,
              reason: this._reason,
              headers
            }
          } else {
            if (this._version === 'HTTP/1.1' && !('host' in headers)) {
              throw errors.INVALID_HEADER("Header 'Host' is missing")
            }

            yield {
              type: constants.REQUEST,
              version: this._version,
              method: this._method,
              url: this._url,
              headers
            }
          }

          const transferEncoding = headers['transfer-encoding']
          const contentLength = headers['content-length']

          const encodings = transferEncoding ? transferEncoding.split(',') : null

          const lastEncoding = encodings
            ? encodings[encodings.length - 1].trim().toLowerCase()
            : null

          if (lastEncoding === 'chunked') {
            if (contentLength) {
              throw errors.INVALID_MESSAGE(
                "Conflicting 'Content-Length' and 'Transfer-Encoding' headers"
              )
            }

            this._state = CHUNK_SIZE
            this._headerSize = 0

            continue
          }

          if (contentLength) {
            if (contentLength.length === 0) throw errors.INVALID_CONTENT_LENGTH()

            let length = 0

            for (let i = 0, n = contentLength.length; i < n; i++) {
              const c = contentLength.charCodeAt(i)

              if (c < ZERO || c > NINE) throw errors.INVALID_CONTENT_LENGTH()

              length = length * 10 + (c - ZERO)
            }

            if (!Number.isSafeInteger(length) || length < 0) {
              throw errors.INVALID_CONTENT_LENGTH()
            }

            if (length === 0) {
              this._state = FIRST_TOKEN
              this._headerSize = 0

              yield { type: constants.END }
            } else {
              this._state = BODY
              this._remaining = length
              this._headerSize = 0
            }
          } else {
            this._state = FIRST_TOKEN
            this._headerSize = 0

            yield { type: constants.END }
          }

          break
        }

        case CHUNK_SIZE: {
          if (byte === CR || byte === 0x3b) {
            if (this._accumulator.length === 0) throw errors.INVALID_CHUNK_LENGTH()

            let length = 0

            for (let i = 0, n = this._accumulator.length; i < n; i++) {
              length = length * 16 + this._accumulator[i]
            }

            this._accumulator = []

            if (!Number.isSafeInteger(length)) throw errors.INVALID_CHUNK_LENGTH()

            if (byte === 0x3b) {
              this._remaining = length
              this._state = CHUNK_EXTENSION
            } else if (length === 0) {
              this._state = LAST_CHUNK_LF
            } else {
              this._remaining = length + 2
              this._state = CHUNK_SIZE_LF
            }
          } else if (isHex(byte)) {
            if (this._accumulator.length >= MAX_CHUNK_SIZE_LENGTH) {
              throw errors.INVALID_CHUNK_LENGTH()
            }

            this._accumulator.push(hexValue(byte))
          } else {
            throw errors.INVALID_CHUNK_LENGTH()
          }

          break
        }

        case CHUNK_EXTENSION: {
          this._checkHeaderSize()

          if (byte === CR) {
            if (this._remaining === 0) {
              this._state = LAST_CHUNK_LF
            } else {
              this._remaining += 2
              this._state = CHUNK_SIZE_LF
            }
          } else if (!isFieldByte(byte)) {
            throw errors.INVALID_CHUNK_LENGTH()
          }

          break
        }

        case CHUNK_SIZE_LF: {
          if (byte !== LF) throw errors.INVALID_CHUNK_LENGTH()

          this._state = CHUNK_DATA

          break
        }

        case LAST_CHUNK_LF: {
          if (byte !== LF) throw errors.INVALID_CHUNK_LENGTH()

          this._state = TRAILER_CR

          break
        }

        case TRAILER_CR: {
          if (byte !== CR) throw errors.INVALID_MESSAGE()

          this._state = TRAILER_LF

          break
        }

        case TRAILER_LF: {
          if (byte !== LF) throw errors.INVALID_MESSAGE()

          this._state = FIRST_TOKEN
          this._headerSize = 0

          yield { type: constants.END }

          break
        }

        default:
          throw errors.INVALID_MESSAGE()
      }
    }
  }
}

exports.constants = constants

const TOKEN_BYTES = Buffer.from([
  // 0x00-0x1f (control characters) + 0x20 (space)
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  // 0x21-0x41: ! " # $ % & ' ( ) * + , - . / 0-9 : ; < = > ? @ A
  1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1,
  // 0x42-0x62: B-Z [ \ ] ^ _ ` a b
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1,
  // 0x63-0x7f: c-z { | } ~ DEL
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0
])

function isTokenByte(b) {
  return TOKEN_BYTES[b] === 1
}

function isFieldByte(b) {
  return b === TAB || (b >= 0x20 && b <= 0x7e)
}

function isHex(b) {
  return (
    (b >= ZERO && b <= NINE) || (b >= UPPER_A && b <= UPPER_F) || (b >= LOWER_A && b <= LOWER_F)
  )
}

function hexValue(b) {
  if (b >= ZERO && b <= NINE) return b - ZERO
  if (b >= UPPER_A && b <= UPPER_F) return b - UPPER_A + 10
  return b - LOWER_A + 10
}
module.exports = class HTTPParserError extends Error {
  constructor(msg, fn = HTTPParserError, code = fn.name) {
    super(`${code}: ${msg}`)

    this.code = code

    if (Error.captureStackTrace) Error.captureStackTrace(this, fn)
  }

  get name() {
    return 'HTTPParserError'
  }

  static INVALID_MESSAGE(msg = 'Invalid HTTP message') {
    return new HTTPParserError(msg, HTTPParserError.INVALID_MESSAGE)
  }

  static INVALID_HEADER(msg = 'Invalid HTTP header') {
    return new HTTPParserError(msg, HTTPParserError.INVALID_HEADER)
  }

  static INVALID_CONTENT_LENGTH(msg = 'Invalid HTTP Content-Length') {
    return new HTTPParserError(msg, HTTPParserError.INVALID_CONTENT_LENGTH)
  }

  static INVALID_CHUNK_LENGTH(msg = 'Invalid HTTP chunk length') {
    return new HTTPParserError(msg, HTTPParserError.INVALID_CHUNK_LENGTH)
  }
}
{
  "name": "bare-http-parser",
  "version": "1.1.3",
  "description": "Streaming HTTP request and response parser for Bare",
  "exports": {
    "./package": "./package.json",
    ".": "./index.js",
    "./errors": "./lib/errors.js"
  },
  "files": [
    "index.js",
    "lib"
  ],
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-http-parser.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-http-parser/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-http-parser#readme",
  "devDependencies": {
    "brittle": "^3.3.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  }
}
exports.IncomingMessage = require('./lib/incoming-message')
exports.OutgoingMessage = require('./lib/outgoing-message')

exports.Agent = require('./lib/agent')
exports.globalAgent = exports.Agent.global

exports.Server = require('./lib/server')
exports.ServerResponse = require('./lib/server-response')
exports.ServerConnection = require('./lib/server-connection')

exports.ClientRequest = require('./lib/client-request')
exports.ClientConnection = require('./lib/client-connection')

exports.constants = require('./lib/constants')
exports.errors = require('./lib/errors')

exports.METHODS = Object.values(exports.constants.method) // For Node.js compatibility
exports.STATUS_CODES = exports.constants.status // For Node.js compatibility

exports.createServer = function createServer(opts, onrequest) {
  return new exports.Server(opts, onrequest)
}

exports.request = function request(url, opts, onresponse) {
  if (typeof opts === 'function') {
    onresponse = opts
    opts = {}
  }

  if (typeof url === 'string') url = new URL(url)

  if (isURL(url)) {
    opts = opts ? { ...url, ...opts } : { ...url }

    opts.host = url.hostname
    opts.path = url.pathname + url.search
    opts.port = url.port ? parseInt(url.port, 10) : defaultPort(url)
  } else {
    opts = url ? { ...url } : {}

    // For Node.js compatibility
    opts.host = opts.hostname || opts.host
    opts.port = typeof opts.port === 'string' ? parseInt(opts.port, 10) : opts.port
  }

  return new exports.ClientRequest(opts, onresponse)
}

exports.get = function get(url, opts, onresponse) {
  const req = exports.request(url, opts, onresponse)
  req.end()
  return req
}

// https://url.spec.whatwg.org/#default-port
function defaultPort(url) {
  switch (url.protocol) {
    case 'ftp:':
      return 21
    case 'http:':
    case 'ws:':
      return 80
    case 'https:':
    case 'wss:':
      return 443
  }

  return null
}

// https://url.spec.whatwg.org/#api
function isURL(url) {
  return (
    url !== null &&
    typeof url === 'object' &&
    typeof url.protocol === 'string' &&
    typeof url.hostname === 'string' &&
    typeof url.pathname === 'string' &&
    typeof url.search === 'string'
  )
}
const EventEmitter = require('bare-events')
const tcp = require('bare-tcp')
const HTTPClientConnection = require('./client-connection')
const errors = require('./errors')

class HTTPSocketSet {
  constructor() {
    this._sockets = new Map()
    this._size = 0
  }

  get size() {
    return this._size
  }

  add(name, socket) {
    const sockets = this._sockets.get(name)

    this._size++

    if (sockets === undefined) this._sockets.set(name, [socket])
    else sockets.push(socket)
  }

  pop(name) {
    const sockets = this._sockets.get(name)
    if (sockets === undefined || sockets.length === 0) return null

    this._size--

    const last = sockets.pop()

    if (sockets.length === 0) this._sockets.delete(name)

    return last
  }

  delete(name, socket) {
    const sockets = this._sockets.get(name)
    if (sockets === undefined) return

    const i = sockets.indexOf(socket)
    if (i === -1) return

    this._size--

    const last = sockets.pop()
    if (last !== socket) sockets[i] = last

    if (sockets.length === 0) this._sockets.delete(name)
  }

  *sockets() {
    for (const sockets of this._sockets.values()) {
      yield* sockets
    }
  }

  *[Symbol.iterator]() {
    for (const [name, sockets] of this._sockets) {
      for (const socket of sockets) yield [name, socket]
    }
  }
}

class HTTPAgent extends EventEmitter {
  constructor(opts = {}) {
    super()

    const { keepAlive = false, keepAliveMsecs = 1000, defaultPort = 80 } = opts

    this._suspended = false
    this._resuming = null

    this._sockets = new HTTPSocketSet()
    this._freeSockets = new HTTPSocketSet()

    this._keepAlive = typeof keepAlive === 'number' ? keepAlive : keepAlive ? keepAliveMsecs : -1
    this._defaultPort = defaultPort

    this._opts = { ...opts }
  }

  get suspended() {
    return this._suspended
  }

  get resumed() {
    return this._resuming ? this._resuming.promise : null
  }

  get sockets() {
    return this._sockets.sockets()
  }

  get freeSockets() {
    return this._freeSockets.sockets()
  }

  get defaultPort() {
    return this._defaultPort
  }

  createConnection(opts) {
    if (this._suspended) throw errors.AGENT_SUSPENDED()

    return tcp.createConnection(opts)
  }

  reuseSocket(socket, req) {
    socket.ref()
  }

  keepSocketAlive(socket) {
    if (this._keepAlive === -1) return false

    socket.setKeepAlive(true, this._keepAlive)
    socket.unref()

    return true
  }

  getName(opts) {
    return `${opts.host}:${opts.port}`
  }

  addRequest(req, opts) {
    opts = { ...opts, ...this._opts }

    const name = this.getName(opts)

    let socket = this._freeSockets.pop(name)

    if (socket) this.reuseSocket(socket, req)
    else {
      const agent = this

      socket = this.createConnection(opts)

      socket
        .on('error', noop) // someone needs to handle it
        .on('free', onfree)
        .on('end', onremove)
        .on('finish', onremove)
        .on('close', onremove)
        .on('timeout', ontimeout)

      function onfree() {
        if (socket.destroyed) return

        if (agent.keepSocketAlive(socket)) {
          agent._freeSockets.add(name, socket)
        } else {
          socket.end()
        }

        agent.emit('free', socket)
      }

      function onremove() {
        socket.off('free', onfree)

        agent._sockets.delete(name, socket)
        agent._freeSockets.delete(name, socket)

        if (agent._sockets.size === 0) HTTPAgent._agents.delete(agent)
      }

      function ontimeout() {
        socket.destroy()

        agent._freeSockets.delete(name, socket)
      }
    }

    if (this._sockets.size === 0) HTTPAgent._agents.add(this)

    this._sockets.add(name, socket)

    req._socket = socket

    const connection = HTTPClientConnection.from(socket, opts)

    connection._req = req
  }

  suspend() {
    if (this._suspended) return

    this._resuming = Promise.withResolvers()
    this._suspended = true

    this.destroy()
  }

  resume() {
    if (this._resuming === null) return

    this._resuming.resolve()
    this._resuming = null
    this._suspended = false
  }

  destroy() {
    for (const socket of this._sockets.sockets()) socket.destroy()
  }

  static _agents = new Set()

  static _onidle() {
    for (const agent of this._agents) {
      agent.destroy()
    }
  }
}

HTTPAgent.global = new HTTPAgent({ keepAlive: 1000, timeout: 5000 })

module.exports = HTTPAgent

Bare.on('idle', HTTPAgent._onidle.bind(HTTPAgent))

function noop() {}
const HTTPParser = require('bare-http-parser')
const HTTPIncomingMessage = require('./incoming-message')
const errors = require('./errors')

const {
  constants: { RESPONSE, DATA, END }
} = HTTPParser

const EMPTY = Buffer.alloc(0)

module.exports = class HTTPClientConnection {
  static _connections = new WeakMap()

  static for(socket) {
    return this._connections.get(socket) || null
  }

  static from(socket, opts) {
    return this.for(socket) || new this(socket, opts)
  }

  constructor(socket, opts = {}) {
    const { IncomingMessage = HTTPIncomingMessage } = opts

    this._socket = socket

    this._req = null
    this._res = null

    this._IncomingMessage = IncomingMessage

    this._parser = new HTTPParser()
    this._idle = true

    this._onerror = this._onerror.bind(this)
    this._onclose = this._onclose.bind(this)
    this._onend = this._onend.bind(this)
    this._ondata = this._ondata.bind(this)
    this._ondrain = this._ondrain.bind(this)
    this._ontimeout = this._ontimeout.bind(this)

    socket
      .on('error', this._onerror)
      .on('close', this._onclose)
      .on('end', this._onend)
      .on('data', this._ondata)
      .on('drain', this._ondrain)
      .on('timeout', this._ontimeout)

    HTTPClientConnection._connections.set(socket, this)
  }

  get socket() {
    return this._socket
  }

  get req() {
    return this._req
  }

  get res() {
    return this._res
  }

  get idle() {
    return this._idle
  }

  _onerror(err) {
    if (this._req) this._req.destroy(err)
  }

  _onclose() {
    if (this._req) this._req.destroy()
  }

  _onend() {
    if (this._req) this._req.destroy(errors.CONNECTION_LOST())
  }

  _ondata(data) {
    this._idle = false

    try {
      for (const op of this._parser.push(data)) {
        switch (op.type) {
          case RESPONSE:
            this._req.on('close', () => {
              this._req = null
            })

            this._res = new this._IncomingMessage(this._socket, {
              headers: op.headers,
              statusCode: op.code,
              statusMessage: op.reason
            })

            this._res.on('close', () => {
              this._res = null
              this._idle = true

              this._socket.emit('free')
            })

            if (op.headers.connection && op.headers.connection.toLowerCase() === 'upgrade') {
              return this._onupgrade(this._parser.end())
            }

            this._req.emit('response', this._res)
            break

          case DATA:
            this._res.push(op.data)
            break

          case END:
            if (this._res) {
              this._res._socket = null
              this._res.push(null)
            }

            if (this._req) {
              this._req._socket = null
              this._req.destroy()
            }
            break
        }
      }
    } catch (err) {
      this._socket.destroy(err)
    }
  }

  _onupgrade(data) {
    this._detach()

    const res = this._res
    const req = this._req

    res._upgrade = req._upgrade = true

    const upgraded = req.emit('upgrade', res, this._socket, data || EMPTY)

    res.push(null)
    req.destroy()

    if (!upgraded) this._socket.destroy()
  }

  _ontimeout() {
    if (this._req) this._req.emit('timeout')
  }

  _ondrain() {
    if (this._req) this._req._continueWrite()
  }

  _detach() {
    this._socket
      .off('error', this._onerror)
      .off('close', this._onclose)
      .off('end', this._onend)
      .off('data', this._ondata)
      .off('drain', this._ondrain)
      .off('timeout', this._ontimeout)

    HTTPClientConnection._connections.delete(this._socket)
  }
}
const HTTPAgent = require('./agent')
const HTTPOutgoingMessage = require('./outgoing-message')

const CHUNK_DELIMITER = Buffer.from('\r\n')
const CHUNK_TERMINATOR = Buffer.from('0\r\n\r\n')

module.exports = class HTTPClientRequest extends HTTPOutgoingMessage {
  constructor(opts = {}, onresponse = null) {
    if (typeof opts === 'function') {
      onresponse = opts
      opts = {}
    }

    opts = opts ? { ...opts } : {}

    const agent = opts.agent === false ? new HTTPAgent() : opts.agent || HTTPAgent.global
    const method = opts.method || 'GET'
    const path = opts.path || '/'
    const defaultPort = opts.defaultPort || (agent && agent.defaultPort) || 80
    const host = (opts.host = opts.host || 'localhost')
    const port = (opts.port = opts.port || defaultPort)
    const headers = { host: hostHeader(host, port, defaultPort), ...opts.headers }

    super()

    agent.addRequest(this, opts)

    this._headers = headers
    this._method = method
    this._path = path

    this._chunked = method !== 'GET' && method !== 'HEAD'

    this._pendingWrite = null
    this._pendingFinal = null

    if (onresponse) this.once('response', onresponse)
  }

  get method() {
    return this._method
  }

  get path() {
    return this._path
  }

  // For Node.js compatibility
  abort() {
    return this.destroy()
  }

  _header() {
    let h = `${this._method} ${this._path} HTTP/1.1\r\n`

    let upgrade = false

    for (const name of Object.keys(this._headers)) {
      const n = name.toLowerCase()
      const v = this._headers[name]

      if (n === 'content-length') this._chunked = false
      if (n === 'connection' && v && v.toLowerCase() === 'upgrade') upgrade = true

      h += `${httpCase(n)}: ${v}\r\n`
    }

    if (upgrade) this._chunked = false

    if (this._chunked) h += 'Transfer-Encoding: chunked\r\n'

    h += '\r\n'

    return h
  }

  _write(data, encoding, cb) {
    if (this._headersSent === false) this.flushHeaders()

    if (this._chunked) {
      this._socket.write(Buffer.from(data.byteLength.toString(16)))
      this._socket.write(CHUNK_DELIMITER)
    }

    let flushed = this._socket.write(data)

    if (this._chunked) flushed = this._socket.write(CHUNK_DELIMITER)

    if (flushed) cb(null)
    else this._pendingWrite = cb
  }

  _final(cb) {
    if (this._headersSent === false) this.flushHeaders()

    if (this._chunked) this._socket.write(CHUNK_TERMINATOR)

    this._pendingFinal = cb
  }

  _predestroy() {
    super._predestroy()

    this._continueWrite()
    this._continueFinal()
  }

  _continueWrite() {
    if (this._pendingWrite === null) return
    const cb = this._pendingWrite
    this._pendingWrite = null
    cb(null)
  }

  _continueFinal() {
    if (this._pendingFinal === null) return
    const cb = this._pendingFinal
    this._pendingFinal = null
    cb(null)
  }
}

function httpCase(n) {
  let s = ''
  for (const part of n.split('-')) {
    s += (s ? '-' : '') + part.slice(0, 1).toUpperCase() + part.slice(1)
  }
  return s
}

function hostHeader(host, port, defaultPort) {
  const i = host.indexOf(':')

  if (i !== -1 && host.includes(':', i + 1) && host.charCodeAt(0) !== 91 /* [ */) {
    host = `[${host}]`
  }

  if (port && +port !== defaultPort) {
    host += ':' + port
  }

  return host
}
module.exports = {
  method: {
    GET: 'GET',
    HEAD: 'HEAD',
    POST: 'POST',
    PUT: 'PUT',
    DELETE: 'DELETE',
    CONNECT: 'CONNECT',
    OPTIONS: 'OPTIONS',
    TRACE: 'TRACE',
    PATCH: 'PATCH'
  },
  status: {
    100: 'Continue',
    101: 'Switching Protocols',
    102: 'Processing',
    103: 'Early Hints',
    200: 'OK',
    201: 'Created',
    202: 'Accepted',
    203: 'Non-Authoritative Information',
    204: 'No Content',
    205: 'Reset Content',
    206: 'Partial Content',
    207: 'Multi-Status',
    208: 'Already Reported',
    226: 'IM Used',
    300: 'Multiple Choices',
    301: 'Moved Permanently',
    302: 'Found',
    303: 'See Other',
    304: 'Not Modified',
    305: 'Use Proxy',
    307: 'Temporary Redirect',
    308: 'Permanent Redirect',
    400: 'Bad Request',
    401: 'Unauthorized',
    402: 'Payment Required',
    403: 'Forbidden',
    404: 'Not Found',
    405: 'Method Not Allowed',
    406: 'Not Acceptable',
    407: 'Proxy Authentication Required',
    408: 'Request Timeout',
    409: 'Conflict',
    410: 'Gone',
    411: 'Length Required',
    412: 'Precondition Failed',
    413: 'Payload Too Large',
    414: 'URI Too Long',
    415: 'Unsupported Media Type',
    416: 'Range Not Satisfiable',
    417: 'Expectation Failed',
    418: "I'm a Teapot",
    421: 'Misdirected Request',
    422: 'Unprocessable Entity',
    423: 'Locked',
    424: 'Failed Dependency',
    425: 'Too Early',
    426: 'Upgrade Required',
    428: 'Precondition Required',
    429: 'Too Many Requests',
    431: 'Request Header Fields Too Large',
    451: 'Unavailable For Legal Reasons',
    500: 'Internal Server Error',
    501: 'Not Implemented',
    502: 'Bad Gateway',
    503: 'Service Unavailable',
    504: 'Gateway Timeout',
    505: 'HTTP Version Not Supported',
    506: 'Variant Also Negotiates',
    507: 'Insufficient Storage',
    508: 'Loop Detected',
    509: 'Bandwidth Limit Exceeded',
    510: 'Not Extended',
    511: 'Network Authentication Required'
  }
}
module.exports = class HTTPError extends Error {
  constructor(msg, fn = HTTPError, code = fn.name) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'HTTPError'
  }

  static NOT_IMPLEMENTED(msg = 'Method not implemented') {
    return new HTTPError(msg, HTTPError.NOT_IMPLEMENTED)
  }

  static CONNECTION_LOST(msg = 'Socket hung up') {
    return new HTTPError(msg, HTTPError.CONNECTION_LOST)
  }

  static AGENT_SUSPENDED(msg = 'Agent is suspended') {
    return new HTTPError(msg, HTTPError.AGENT_SUSPENDED)
  }
}
const { Readable } = require('bare-stream')

module.exports = class HTTPIncomingMessage extends Readable {
  constructor(socket = null, opts = {}) {
    super()

    this._socket = socket
    this._upgrade = false
    this._headers = opts.headers || {}

    // Server options
    this._method = opts.method || ''
    this._url = opts.url || ''

    // Client options
    this._statusCode = opts.statusCode || 0
    this._statusMessage = opts.statusMessage || ''
  }

  get socket() {
    return this._socket
  }

  get upgrade() {
    return this._upgrade
  }

  get headers() {
    return this._headers
  }

  set headers(value) {
    this._headers = value
  }

  get method() {
    return this._method
  }

  set method(value) {
    this._method = value
  }

  get url() {
    return this._url
  }

  set url(value) {
    this._url = value
  }

  get statusCode() {
    return this._statusCode
  }

  set statusCode(value) {
    this._statusCode = value
  }

  get statusMessage() {
    return this._statusMessage
  }

  set statusMessage(value) {
    this._statusMessage = value
  }

  get httpVersion() {
    return '1.1'
  }

  getHeader(name) {
    return this._headers[name.toLowerCase()]
  }

  getHeaders() {
    return { ...this._headers }
  }

  hasHeader(name) {
    return name.toLowerCase() in this._headers
  }

  setTimeout(ms, ontimeout) {
    if (ontimeout) this.once('timeout', ontimeout)

    this._socket.setTimeout(ms)

    return this
  }

  _predestroy() {
    if (this._upgrade === false && this._socket !== null) this._socket.destroy()
  }
}
const { Writable } = require('bare-stream')
const errors = require('./errors')

module.exports = class HTTPOutgoingMessage extends Writable {
  constructor(socket = null) {
    super()

    this._socket = socket
    this._upgrade = false
    this._headersSent = false
    this._headers = {}
  }

  get socket() {
    return this._socket
  }

  get upgrade() {
    return this._upgrade
  }

  get headersSent() {
    return this._headersSent
  }

  get headers() {
    return this._headers
  }

  set headers(value) {
    this._headers = value
  }

  getHeader(name) {
    return this._headers[name.toLowerCase()]
  }

  getHeaders() {
    return { ...this._headers }
  }

  hasHeader(name) {
    return name.toLowerCase() in this._headers
  }

  setHeader(name, value) {
    this._headers[name.toLowerCase()] = value
  }

  flushHeaders() {
    if (this._headersSent === true || this._socket === null) return

    this._socket.write(Buffer.from(this._header()))
    this._headersSent = true
  }

  setTimeout(ms, ontimeout) {
    if (ontimeout) this.once('timeout', ontimeout)

    this._socket.setTimeout(ms)

    return this
  }

  _header() {
    throw errors.NOT_IMPLEMENTED()
  }

  _predestroy() {
    if (this._upgrade === false && this._socket !== null) this._socket.destroy()
  }
}
const { isEnded, isFinished, getStreamError } = require('bare-stream')
const HTTPParser = require('bare-http-parser')
const HTTPIncomingMessage = require('./incoming-message')
const HTTPServerResponse = require('./server-response')

const {
  constants: { REQUEST, DATA, END }
} = HTTPParser

const EMPTY = Buffer.alloc(0)

module.exports = class HTTPServerConnection {
  static _connections = new WeakMap()

  static for(socket) {
    return this._connections.get(socket) || null
  }

  constructor(server, socket, opts = {}) {
    const { IncomingMessage = HTTPIncomingMessage, ServerResponse = HTTPServerResponse } = opts

    this._server = server
    this._socket = socket

    this._req = null
    this._res = null

    this._IncomingMessage = IncomingMessage
    this._ServerResponse = ServerResponse

    this._parser = new HTTPParser()
    this._idle = true

    this._onclose = this._onclose.bind(this)
    this._ondata = this._ondata.bind(this)
    this._ondrain = this._ondrain.bind(this)
    this._ontimeout = this._ontimeout.bind(this)

    socket
      .on('error', noop)
      .on('close', this._onclose)
      .on('data', this._ondata)
      .on('drain', this._ondrain)
      .on('timeout', this._ontimeout)

    HTTPServerConnection._connections.set(socket, this)

    if (this._server.timeout) socket.setTimeout(this._server.timeout)
  }

  get server() {
    return this._server
  }

  get socket() {
    return this._socket
  }

  get req() {
    return this._req
  }

  get res() {
    return this._res
  }

  get idle() {
    return this._idle
  }

  _onclose() {
    if (this._req && !isEnded(this._req)) this._req.destroy()
    if (this._res && !isFinished(this._res)) this._res.destroy()

    const err = getStreamError(this._socket)
    if (err) this._socket.destroy(err)
  }

  _ondata(data) {
    this._idle = false

    try {
      for (const op of this._parser.push(data)) {
        switch (op.type) {
          case REQUEST:
            this._req = new this._IncomingMessage(this._socket, {
              headers: op.headers,
              method: op.method,
              url: op.url
            })

            this._req.on('close', () => {
              this._req = null

              this._idle = true

              if (this._server.closing) this._socket.destroy()
            })

            // Eagerly open the request stream
            this._req.resume()
            this._req.pause()

            if (op.headers.connection && op.headers.connection.toLowerCase() === 'upgrade') {
              return this._onupgrade(this._parser.end())
            }

            this._res = new this._ServerResponse(this._socket, this._req)

            this._res.on('close', () => {
              this._res = null
            })

            this._server.emit('request', this._req, this._res)
            break

          case DATA:
            this._req.push(op.data)
            break

          case END:
            if (this._req) {
              this._req._socket = null
              this._req.push(null)
            }
            break
        }
      }
    } catch (err) {
      this._socket.destroy(err)
    }
  }

  _onupgrade(data) {
    this._detach()

    const req = this._req

    req._upgrade = true

    const upgraded = this._server.emit('upgrade', req, this._socket, data || EMPTY)

    req.push(null)

    if (!upgraded) this._socket.destroy()
  }

  _ontimeout() {
    const reqTimeout = this._req && this._req.emit('timeout')
    const resTimeout = this._res && this._res.emit('timeout')
    const serverTimeout = this._server.emit('timeout', this._socket)

    if (!reqTimeout && !resTimeout && !serverTimeout) this._socket.destroy()
  }

  _ondrain() {
    if (this._res) this._res._continueWrite()
  }

  _detach() {
    this._socket
      .off('error', noop)
      .off('close', this._onclose)
      .off('data', this._ondata)
      .off('drain', this._ondrain)
      .off('timeout', this._ontimeout)

    HTTPServerConnection._connections.delete(this._socket)
  }
}

function noop() {}
const { isFinishing } = require('bare-stream')
const HTTPOutgoingMessage = require('./outgoing-message')
const constants = require('./constants')

const CHUNK_DELIMITER = Buffer.from('\r\n')
const CHUNK_TERMINATOR = Buffer.from('0\r\n\r\n')

module.exports = class HTTPServerResponse extends HTTPOutgoingMessage {
  constructor(socket, req) {
    super(socket)

    this._req = req

    this._statusCode = 200
    this._statusMessage = null

    this._chunked = true
    this._close = req.headers.connection === 'close'
    this._onlyHeaders = req.method === 'HEAD'

    this._pendingWrite = null
  }

  get req() {
    return this._req
  }

  get statusCode() {
    return this._statusCode
  }

  set statusCode(value) {
    this._statusCode = value
  }

  get statusMessage() {
    return this._statusMessage
  }

  set statusMessage(value) {
    this._statusMessage = value
  }

  writeHead(statusCode, statusMessage = null, headers = {}) {
    if (typeof statusMessage === 'object' && statusMessage !== null) {
      headers = statusMessage
      statusMessage = null
    }

    this._statusCode = statusCode
    this._statusMessage = statusMessage || null

    if (headers) this._headers = { ...this._headers, ...headers }
  }

  _header() {
    let h =
      'HTTP/1.1 ' +
      this._statusCode +
      ' ' +
      (this._statusMessage === null ? constants.status[this._statusCode] : this._statusMessage) +
      '\r\n'

    for (const name of Object.keys(this._headers)) {
      const n = name.toLowerCase()
      const v = this._headers[name]

      if (n === 'content-length') this._chunked = false
      if (n === 'connection' && v && v.toLowerCase() === 'close') this._close = true

      h += httpCase(n) + ': ' + v + '\r\n'
    }

    if (this._chunked) h += 'Transfer-Encoding: chunked\r\n'

    h += '\r\n'

    return h
  }

  _write(data, encoding, cb) {
    if (this._headersSent === false) {
      if (isFinishing(this)) {
        this.setHeader(
          'Content-Length',
          (data.byteLength + this._writableState.buffered).toString()
        )
      }

      this.flushHeaders()
    }

    if (this._onlyHeaders === true) return cb(null)

    if (this._chunked) {
      this._socket.write(Buffer.from(data.byteLength.toString(16)))
      this._socket.write(CHUNK_DELIMITER)
    }

    let flushed = this._socket.write(data)

    if (this._chunked) flushed = this._socket.write(CHUNK_DELIMITER)

    if (flushed) cb(null)
    else this._pendingWrite = cb
  }

  _final(cb) {
    if (this._headersSent === false) {
      this.setHeader('Content-Length', '0')
      this.flushHeaders()
    }

    if (this._chunked && this._onlyHeaders === false) this._socket.write(CHUNK_TERMINATOR)

    if (this._close) this._socket.end()

    cb(null)
  }

  _predestroy() {
    super._predestroy()

    this._req.destroy()

    this._continueWrite()
  }

  _continueWrite() {
    if (this._pendingWrite === null) return
    const cb = this._pendingWrite
    this._pendingWrite = null
    cb(null)
  }
}

function httpCase(n) {
  let s = ''
  for (const part of n.split('-')) {
    s += (s ? '-' : '') + part.slice(0, 1).toUpperCase() + part.slice(1)
  }
  return s
}
const TCPServer = require('bare-tcp').Server
const HTTPServerConnection = require('./server-connection')

module.exports = class HTTPServer extends TCPServer {
  constructor(opts = {}, onrequest) {
    if (typeof opts === 'function') {
      onrequest = opts
      opts = {}
    }

    super({ allowHalfOpen: false })

    this._timeout = 0

    this.on('connection', (socket) => {
      new HTTPServerConnection(this, socket, opts)
    })

    if (onrequest) this.on('request', onrequest)
  }

  get timeout() {
    return this._timeout || undefined // For Node.js compatibility
  }

  setTimeout(ms = 0, ontimeout) {
    if (ontimeout) this.on('timeout', ontimeout)

    this._timeout = ms

    return this
  }

  close(onclose) {
    super.close(onclose)

    for (const socket of this.connections) {
      const connection = HTTPServerConnection.for(socket)

      if (connection === null || connection.idle) {
        socket.destroy()
      }
    }

    return this
  }
}
{
  "name": "bare-http1",
  "version": "4.5.6",
  "description": "Native HTTP/1 library for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    },
    "./errors": {
      "types": "./lib/errors.d.ts",
      "default": "./lib/errors.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-http1.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-http1/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-http1#readme",
  "dependencies": {
    "bare-events": "^2.6.0",
    "bare-http-parser": "^1.1.1",
    "bare-stream": "^2.10.0",
    "bare-tcp": "^2.2.0"
  },
  "devDependencies": {
    "bare-buffer": "^3.0.2",
    "bare-url": "^2.1.3",
    "brittle": "^3.3.0",
    "lunte": "^1.6.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "bare-buffer": "*",
    "bare-url": "*"
  },
  "peerDependenciesMeta": {
    "bare-buffer": {
      "optional": true
    },
    "bare-url": {
      "optional": true
    }
  }
}
module.exports = require.addon()
const ansiEscapes = require('bare-ansi-escapes')
const getType = require('bare-type')
const binding = require('./binding')

const PLAIN_KEY = /^[a-zA-Z_][a-zA-Z_0-9]*$/

const defaultDepth = 2
const defaultBreakLength = 80
const defaultMaxArrayLength = 40

module.exports = exports = function inspect(value, opts = {}) {
  const {
    colors = false,
    depth = defaultDepth,
    breakLength = defaultBreakLength,
    stylize = defaultStylize(colors)
  } = opts

  const references = new InspectRefMap()

  const tree = inspectValue(value, 0, {
    colors,
    depth,
    breakLength,
    stylize,
    references
  })

  return tree.toString()
}

exports.styles = {
  bigint: ansiEscapes.colorYellow,
  boolean: ansiEscapes.colorYellow,
  date: ansiEscapes.colorMagenta,
  module: ansiEscapes.modifierUnderline,
  name: ansiEscapes.modifierReset,
  null: ansiEscapes.modifierBold,
  number: ansiEscapes.colorYellow,
  regexp: ansiEscapes.colorRed,
  special: ansiEscapes.colorCyan,
  string: ansiEscapes.colorGreen,
  symbol: ansiEscapes.colorGreen,
  undefined: ansiEscapes.colorBrightBlack
}

const styles = exports.styles

function defaultStylize(colors) {
  return function stylize(value, style) {
    const color = colors && styles[style]

    if (color) return color + value + ansiEscapes.modifierReset

    return value
  }
}

class InspectRefMap {
  constructor() {
    this.refs = new WeakMap()
    this.ids = new WeakMap()
    this.nextId = 1
  }

  has(object) {
    return this.refs.has(object)
  }

  get(object) {
    return this.refs.get(object) || null
  }

  set(object, ref) {
    this.refs.set(object, ref)
  }

  id(object) {
    let id = this.ids.get(object)
    if (id) return id

    id = this.nextId++
    this.ids.set(object, id)

    return id
  }
}

class InspectNode {
  constructor(depth, length, opts) {
    const { breakLength = defaultBreakLength, breakAlways = false } = opts

    this.depth = depth
    this.length = length
    this.breakLength = breakLength
    this.breakAlways = breakAlways
  }

  pad(n, string) {
    return string.padStart(n, ' ')
  }

  indent(n, string) {
    return '  '.repeat(n) + string
  }
}

class InspectRef extends InspectNode {
  constructor(depth, opts) {
    super(depth, '[circular *]'.length, opts)

    this.refs = opts.references
    this.count = 0
    this.circular = false
    this.color = opts.colors && styles.special
  }

  get id() {
    return this.refs.id(this)
  }

  increment() {
    return ++this.count
  }

  decrement() {
    return --this.count
  }

  toString(opts = {}) {
    const { offset = 0, pad = 0, indent = 0 } = opts

    let value = this.pad(pad, '[circular *' + this.id + ']')

    if (this.color) value = this.color + value + ansiEscapes.modifierReset

    return offset ? value : this.indent(indent, value)
  }
}

class InspectLeaf extends InspectNode {
  constructor(value, color, depth, opts) {
    const length = value.length

    if (value.includes('\n')) {
      value = value.replaceAll('\n', '\n' + '  '.repeat(depth))

      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.value = value
    this.color = opts.colors && color
  }

  toString(opts = {}) {
    const { offset = 0, pad = 0, indent = 0 } = opts

    let value = this.pad(pad, this.value)

    if (this.color) value = this.color + value + ansiEscapes.modifierReset

    return offset ? value : this.indent(indent, value)
  }
}

class InspectPair extends InspectNode {
  constructor(delim, left, right, depth, opts) {
    const length = left.length + delim.length + right.length

    if (left.breakAlways || right.breakAlways) {
      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.delim = delim
    this.left = left
    this.right = right
  }

  toString(opts = {}) {
    const { indent = 0 } = opts

    return this.indent(
      indent,
      this.left +
        this.delim +
        this.right.toString({
          indent,
          offset: this.left.length + this.delim.length
        })
    )
  }
}

class InspectSuspension extends InspectNode {
  constructor(overflow, depth, opts) {
    const label = `... ${overflow} more`

    super(depth, label.length, opts)

    this.label = label
  }

  toString(opts = {}) {
    const { indent = 0 } = opts

    return this.indent(indent, this.label)
  }
}

class InspectSequence extends InspectNode {
  constructor(header, footer, delim, values, ref, depth, opts) {
    const { tabulate = false } = opts

    const length =
      (ref.circular ? '<ref *>'.length + 1 : 0) +
      header.length +
      values.reduce(
        (length, value, i) =>
          length + value.length + (i === 0 ? 0 : delim.length),
        0
      ) +
      footer.length

    if (values.some((value) => value.breakAlways)) {
      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.header = header
    this.footer = footer
    this.delim = delim
    this.values = values
    this.ref = ref
    this.tabulate = tabulate
  }

  toString(opts = {}) {
    const { offset = 0, indent = 0 } = opts

    const split =
      this.breakAlways ||
      (this.values.length &&
        (offset + this.length > this.breakLength ||
          indent * 2 + this.length > this.breakLength))

    let header = this.header

    if (this.ref.circular) {
      header = '<ref *' + this.ref.id + '> ' + header
    }

    if (this.values.length === 0) {
      header = header.trimEnd()
    }

    if (offset === 0) {
      header = this.indent(indent, header)
    }

    if (split) {
      header = header.trimEnd() + '\n'
    }

    let string = header

    let columns = 1
    let pad = 0

    if (this.tabulate) {
      const widest = this.values.reduce(
        (length, value) =>
          value.breakAlways ? length : Math.max(length, value.length),
        0
      )

      if (widest) {
        columns = Math.max(
          columns,
          Math.floor(
            (this.breakLength - indent * 2) / (widest + this.delim.length)
          )
        )

        if (columns > 1) pad = widest
      }
    }

    for (let i = 0, n = this.values.length, offset = 0; i < n; i++) {
      const value = this.values[i]

      if (split) {
        let part

        if (i % columns === 0 || value.breakAlways) {
          part = value.toString({ indent: indent + 1, pad })
        } else {
          part = value.toString({ pad })
        }

        string += part

        if (i < n - 1) {
          if (i % columns === columns - 1 || this.values[i + 1].breakAlways) {
            string += this.delim.trimEnd() + '\n'
          } else {
            string += this.delim
          }
        }
      } else {
        if (i > 0) string += this.delim

        string += value.toString({ offset })

        offset += value.length
      }
    }

    let footer = this.footer

    if (this.values.length === 0) {
      footer = footer.trimStart()
    }

    if (split) {
      string += '\n' + this.indent(indent, footer.trimStart())
    } else {
      string += footer
    }

    return string
  }
}

function inspectValue(value, depth, opts) {
  const type = getType(value)

  if (type.isUndefined()) return inspectUndefined(depth, opts)
  if (type.isNull()) return inspectNull(depth, opts)
  if (type.isBoolean()) return inspectBoolean(value, depth, opts)
  if (type.isNumber()) return inspectNumber(value, depth, opts)
  if (type.isBigInt()) return inspectBigInt(value, depth, opts)
  if (type.isString()) return inspectString(value, depth, opts)
  if (type.isSymbol()) return inspectSymbol(value, depth, opts)
  if (type.isObject()) return inspectObject(type, value, depth, opts)
  if (type.isFunction()) return inspectFunction(type, value, depth, opts)
  if (type.isExternal()) return inspectExternal(value, opts, opts)
}

function inspectUndefined(depth, opts) {
  return new InspectLeaf('undefined', styles.undefined, depth, opts)
}

function inspectNull(depth, opts) {
  return new InspectLeaf('null', styles.null, depth, opts)
}

function inspectBoolean(value, depth, opts) {
  return new InspectLeaf(value.toString(), styles.boolean, depth, opts)
}

function inspectNumber(value, depth, opts) {
  let string

  if (Object.is(value, -0)) {
    string = '-0'
  } else {
    string = value.toString(10)
  }

  return new InspectLeaf(string, styles.number, depth, opts)
}

function inspectBigInt(value, depth, opts) {
  return new InspectLeaf(value.toString(10) + 'n', styles.bigint, depth, opts)
}

const STRING_ESCAPES =
  /[\ud800-\udbff][\udc00-\udfff]|[\u0000-\u001f'\\\ud800-\udfff]/g

function inspectString(value, depth, opts) {
  // https://tc39.es/ecma262/multipage/structured-data.html#sec-quotejsonstring
  const string = value.replace(STRING_ESCAPES, (match) => {
    if (match.length === 2) return match

    switch (match) {
      case "'":
        return "\\'"
      case '\\':
        return '\\\\'
      case '\b':
        return '\\b'
      case '\t':
        return '\\t'
      case '\n':
        return '\\n'
      case '\f':
        return '\\f'
      case '\r':
        return '\\r'
      default:
        return '\\u' + match.charCodeAt(0).toString(16).padStart(4, '0')
    }
  })

  return new InspectLeaf("'" + string + "'", styles.string, depth, opts)
}

function inspectSymbol(value, depth, opts) {
  return new InspectLeaf(value.toString(), styles.symbol, depth, opts)
}

function inspectKey(value, depth, opts) {
  if (PLAIN_KEY.test(value)) {
    return new InspectLeaf(value, null, depth, opts)
  } else {
    return inspectValue(value, depth, opts)
  }
}

function inspectObject(type, object, depth, opts) {
  const refs = opts.references

  let ref = refs.get(object)
  if (ref === null) {
    ref = new InspectRef(depth, opts)
    refs.set(object, ref)
  } else if (ref.count) {
    ref.circular = true
    return ref
  }

  const maxDepth = typeof opts.depth === 'number' ? opts.depth : Infinity

  if (maxDepth < depth) {
    const constructor = object.constructor

    return new InspectLeaf(
      '[' +
        (constructor && constructor.name ? constructor.name : 'Object') +
        ']',
      styles.special,
      depth,
      opts
    )
  }

  const inspect =
    object[Symbol.for('bare.inspect')] ||
    object[Symbol.for('nodejs.util.inspect.custom')]

  if (typeof inspect === 'function') {
    const value = inspect.call(
      object,
      typeof opts.depth === 'number' ? opts.depth - depth : null,
      {
        colors: opts.colors,
        breakLength: opts.breakLength,
        stylize: opts.stylize
      },
      exports
    )

    if (typeof value === 'object' && value !== null) {
      refs.set(value, ref)
    }

    if (typeof value !== 'string') {
      return inspectValue(value, depth, opts)
    }

    return new InspectLeaf(value, null, depth, opts)
  }

  if (type.isArray()) return inspectArray(object, ref, depth, opts)
  if (type.isDate()) return inspectDate(object, ref, depth, opts)
  if (type.isRegExp()) return inspectRegExp(object, ref, depth, opts)
  if (type.isError()) return inspectError(object, ref, depth, opts)
  if (type.isPromise()) return inspectPromise(object, ref, depth, opts)
  if (type.isMap()) return inspectMap(object, ref, depth, opts)
  if (type.isSet()) return inspectSet(object, ref, depth, opts)
  if (type.isWeakMap()) return inspectWeakMap(object, ref, depth, opts)
  if (type.isWeakSet()) return inspectWeakSet(object, ref, depth, opts)
  if (type.isWeakRef()) return inspectWeakRef(object, ref, depth, opts)
  if (type.isArrayBuffer()) return inspectArrayBuffer(object, ref, depth, opts)
  if (type.isSharedArrayBuffer())
    return inspectSharedArrayBuffer(object, ref, depth, opts)
  if (type.isTypedArray()) return inspectTypedArray(object, ref, depth, opts)
  if (type.isDataView()) return inspectDataView(object, ref, depth, opts)

  ref.increment()

  const values = []

  for (const key in object) {
    if (key === 'constructor') continue

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(object[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  let header = '{ '

  const tag = object[Symbol.toStringTag]

  if (tag) header = '[' + tag + '] ' + header

  if (object.constructor) {
    const name = object.constructor.name

    if (name && name !== 'Object') {
      header = object.constructor.name + ' ' + header
    }
  }

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectArray(array, ref, depth, opts) {
  const { maxArrayLength = defaultMaxArrayLength } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxArrayLength, 0)

  for (let i = 0, n = array.length; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(array.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(inspectValue(array[i], depth + 1, opts))
  }

  for (const key of binding.getOwnNonIndexPropertyNames(array)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(array[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  let header = '[ '

  if (array.constructor.name !== 'Array') {
    header = array.constructor.name + '(' + array.length + ') ' + header
  }

  return new InspectSequence(header, ' ]', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectDate(date, ref, depth, opts) {
  return new InspectLeaf(date.toISOString(), styles.date, depth, opts)
}

function inspectRegExp(regExp, ref, depth, opts) {
  return new InspectLeaf(regExp.toString(), styles.regexp, depth, opts)
}

function inspectError(error, ref, depth, opts) {
  let header

  if ('stack' in error) {
    header = error.stack

    if (depth > 0) {
      header = header.replaceAll('\n', '\n' + '  '.repeat(depth))
    }
  } else {
    header = error.toString()
  }

  const builtins = ['cause']

  if (error.name === 'AggregateError') {
    builtins.push('errors')
  } else if (error.name === 'SuppressedError') {
    builtins.push('error', 'suppressed')
  }

  const values = []

  for (const key of builtins) {
    if (key in error === false) continue

    values.push(
      new InspectPair(
        ': ',
        new InspectLeaf('[' + key + ']', null, depth + 1, opts),
        inspectValue(error[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key in error) {
    if (key === 'constructor' || builtins.includes(key)) continue

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(error[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  if (values.length === 0) return new InspectLeaf(header, null, depth, opts)

  return new InspectSequence(
    header + ' {',
    ' }',
    ', ',
    values,
    ref,
    depth,
    opts
  )
}

function inspectPromise(promise, ref, depth, opts) {
  ref.increment()

  const state = binding.getPromiseState(promise)

  const values = []

  switch (state) {
    case 0: // Pending
      values.push(new InspectLeaf('<pending>', styles.special, depth, opts))
      break

    case 1: // Fulfilled
      values.push(inspectValue(binding.getPromiseResult(promise), depth, opts))
      break

    case 2: // Rejected
      values.push(
        new InspectLeaf('<rejected>', styles.special, depth, opts),
        inspectValue(binding.getPromiseResult(promise), depth, opts)
      )
  }

  ref.decrement()

  const header = promise.constructor.name + ' { '

  return new InspectSequence(header, ' }', ' ', values, ref, depth, opts)
}

function inspectMap(map, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxMapLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = maxMapLength

  for (const entry of map) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(map.size - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )
      break
    }

    values.push(
      new InspectPair(
        ' => ',
        inspectValue(entry[0], depth + 1, opts),
        inspectValue(entry[1], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key in map) {
    if (key === 'constructor') continue

    const value = inspectValue(map[key], depth + 1, opts)

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        value,
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = map.constructor.name + '(' + map.size + ') { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectSet(set, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxSetLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = maxSetLength

  for (const entry of set) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(set.size - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )
      break
    }

    values.push(inspectValue(entry, depth + 1, opts))
  }

  for (const key in set) {
    if (key === 'constructor') continue

    const value = inspectValue(set[key], depth + 1, opts)

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        value,
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = set.constructor.name + '(' + set.size + ') { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectWeakMap(weakMap, ref, depth, opts) {
  const header = weakMap.constructor.name + ' { '

  return new InspectSequence(
    header,
    ' }',
    ' ',
    [new InspectLeaf('<items unknown>', styles.special, depth + 1, opts)],
    ref,
    depth,
    opts
  )
}

function inspectWeakSet(weakSet, ref, depth, opts) {
  const header = weakSet.constructor.name + ' { '

  return new InspectSequence(
    header,
    ' }',
    ' ',
    [new InspectLeaf('<items unknown>', styles.special, depth + 1, opts)],
    ref,
    depth,
    opts
  )
}

function inspectWeakRef(weakRef, ref, depth, opts) {
  const target = weakRef.deref()

  let value

  if (target === undefined) {
    value = new InspectLeaf('<cleared>', styles.special, depth + 1, opts)
  } else {
    value = inspectValue(target, depth + 1, opts)
  }

  const header = weakRef.constructor.name + ' { '

  return new InspectSequence(header, ' }', ' ', [value], ref, depth, opts)
}

function inspectArrayBuffer(arrayBuffer, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(arrayBuffer[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = arrayBuffer.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectSharedArrayBuffer(sharedArrayBuffer, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(sharedArrayBuffer[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = sharedArrayBuffer.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectTypedArray(typedArray, ref, depth, opts) {
  if (Buffer.isBuffer(typedArray)) {
    return inspectBuffer(typedArray, ref, depth, opts)
  }

  const {
    maxArrayLength = defaultMaxArrayLength,
    maxTypedArrayLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxTypedArrayLength, 0)

  for (let i = 0, n = typedArray.length; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(typedArray.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(inspectValue(typedArray[i], depth + 1, opts))
  }

  for (const key of binding.getOwnNonIndexPropertyNames(typedArray)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(typedArray[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = typedArray.constructor.name + '(' + typedArray.length + ') [ '

  return new InspectSequence(header, ' ]', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectBuffer(buffer, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxBufferLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxBufferLength, 0)

  for (let i = 0, n = buffer.byteLength; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(buffer.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(
      new InspectLeaf(
        buffer[i].toString(16).padStart(2, '0'),
        null,
        depth + 1,
        opts
      )
    )
  }

  for (const key of binding.getOwnNonIndexPropertyNames(buffer)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(buffer[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  return new InspectSequence('<Buffer ', '>', ' ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectDataView(dataView, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength', 'byteOffset', 'buffer']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(dataView[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key of binding.getOwnNonIndexPropertyNames(dataView)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(dataView[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = dataView.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectFunction(type, fn, depth, opts) {
  if (fn.toString().startsWith('class')) return inspectClass(fn, depth, opts)

  let tag = 'function'

  if (type.isGeneratorFunction()) tag = 'generator ' + tag
  if (type.isAsyncFunction()) tag = 'async ' + tag

  return new InspectLeaf(
    '[' + tag + ' ' + (fn.name ? fn.name : '(anonymous)') + ']',
    styles.special,
    depth,
    opts
  )
}

function inspectClass(ctor, depth, opts) {
  return new InspectLeaf(
    '[class ' + (ctor.name ? ctor.name : '(anonymous)') + ']',
    styles.special,
    depth,
    opts
  )
}

function inspectExternal(external, depth, opts) {
  return new InspectLeaf(
    '[external 0x' + binding.getExternal(external).toString(16) + ']',
    styles.special,
    depth,
    opts
  )
}
{
  "name": "bare-inspect",
  "version": "3.1.4",
  "description": "Inspect objects as strings for debugging",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-inspect.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-inspect/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-inspect#readme",
  "engines": {
    "bare": ">=1.18.0"
  },
  "dependencies": {
    "bare-ansi-escapes": "^2.1.0",
    "bare-type": "^1.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
const EventEmitter = require('bare-events')
const { Duplex } = require('bare-stream')
const tcp = require('bare-tcp')
const pipe = require('bare-pipe')

const defaultReadBufferSize = 65536

const constants = exports.constants = {
  type: {
    TCP: 1,
    IPC: 2
  },
  state: {
    UNREFED: 0x1
  }
}

const Socket = exports.Socket = class NetSocket extends Duplex {
  constructor (opts = {}) {
    super({ eagerOpen: true })

    const {
      readBufferSize = defaultReadBufferSize,
      allowHalfOpen = true
    } = opts

    this._opts = { readBufferSize, allowHalfOpen }
    this._type = 0
    this._state = 0
    this._socket = null

    this._pendingWrite = null
    this._pendingFinal = null
  }

  get connecting () {
    return this._socket !== null && this._socket.connecting
  }

  get pending () {
    return this._socket === null || this._socket.pending
  }

  connect (...args) {
    let opts = {}
    let onconnect

    // connect(path[, onconnect])
    if (typeof args[0] === 'string') {
      opts.path = args[0]
      onconnect = args[1]
    // connect(port[, host][, onconnect])
    } else if (typeof args[0] === 'number') {
      opts.port = args[0]

      if (typeof args[1] === 'function') {
        onconnect = args[1]
      } else {
        opts.host = args[1]
        onconnect = args[2]
      }
    // connect(opts[, onconnect])
    } else {
      opts = args[0] || {}
      onconnect = args[1]
    }

    opts = { ...opts, ...this._opts }

    if (opts.path) {
      this._attach(constants.type.IPC, pipe.createConnection(opts))
    } else {
      this._attach(constants.type.TCP, tcp.createConnection(opts))
    }

    if (onconnect) this.once('connect', onconnect)

    return this
  }

  ref () {
    this._state &= ~constants.state.UNREFED
    if (this._socket !== null) this._socket.ref()
  }

  unref () {
    this._state |= constants.state.UNREFED
    if (this._socket !== null) this._socket.unref()
  }

  _attach (type, socket) {
    this._type = type
    this._socket = socket

    this._socket
      .on('connect', this._onconnect.bind(this))
      .on('error', this._onerror.bind(this))
      .on('close', this._onclose.bind(this))
      .on('end', this._onend.bind(this))
      .on('data', this._ondata.bind(this))
      .on('drain', this._ondrain.bind(this))

    if (this._state & constants.state.UNREFED) this._socket.unref()

    return this
  }

  _write (data, encoding, cb) {
    if (this._socket !== null && this._socket.write(data)) cb(null)
    else this._pendingWrite = cb
  }

  _final (cb) {
    if (this._socket === null) return cb(null)
    this._pendingFinal = cb
    this._socket.end()
  }

  _predestroy () {
    if (this._socket === null) return
    this._socket.destroy()
  }

  _onconnect () {
    this._ondrain() // Flush any pending writes

    this.emit('connect')
  }

  _onerror (err) {
    this.destroy(err)
  }

  _onend () {
    if (this._pendingFinal === null) return
    const cb = this._pendingFinal
    this._pendingFinal = null
    cb(null)
  }

  _onclose () {
    this.push(null)
  }

  _ondata (data) {
    this.push(data)
  }

  _ondrain () {
    if (this._pendingWrite === null) return
    const cb = this._pendingWrite
    this._pendingWrite = null
    cb(null)
  }
}

const Server = exports.Server = class NetServer extends EventEmitter {
  constructor (opts = {}, onconnection) {
    if (typeof opts === 'function') {
      onconnection = opts
      opts = {}
    }

    super()

    const {
      readBufferSize = defaultReadBufferSize,
      allowHalfOpen = true
    } = opts

    this._opts = { readBufferSize, allowHalfOpen }
    this._type = 0
    this._state = 0
    this._server = null

    if (onconnection) this.on('connection', onconnection)
  }

  get listening () {
    return this._server !== null && this._server.listening
  }

  address () {
    return this._server === null ? null : this._server.address()
  }

  listen (...args) {
    let opts = {}
    let onlistening

    // listen(path[, backlog][, onlistening])
    if (typeof args[0] === 'string') {
      opts.path = args[0]

      if (typeof args[1] === 'function') {
        onlistening = args[1]
      } else {
        opts.backlog = args[1]
        onlistening = args[2]
      }
    // listen([port[, host[, backlog]]][, onlistening])
    } else {
      if (typeof args[0] === 'function') {
        onlistening = args[0]
      } else {
        opts.port = args[0]

        if (typeof args[1] === 'function') {
          onlistening = args[1]
        } else {
          opts.host = args[1]

          if (typeof args[2] === 'function') {
            onlistening = args[2]
          } else {
            opts.backlog = args[2]
            onlistening = args[3]
          }
        }
      }
    }

    opts = { ...opts, ...this._opts }

    if (opts.path) {
      this._attach(constants.type.IPC, pipe.createServer(opts))
    } else {
      this._attach(constants.type.TCP, tcp.createServer(opts))
    }

    this._server.listen(opts)

    if (onlistening) this.once('listening', onlistening)

    return this
  }

  close (onclose) {
    if (onclose) this.once('close', onclose)
    this._server.close()
  }

  ref () {
    this._state &= ~constants.state.UNREFED
    if (this._server !== null) this._server.ref()
  }

  unref () {
    this._state |= constants.state.UNREFED
    if (this._server !== null) this._server.unref()
  }

  _attach (type, server) {
    this._type = type
    this._server = server

    this._server
      .on('listening', this._onlistening.bind(this))
      .on('connection', this._onconnection.bind(this))
      .on('error', this._onerror.bind(this))
      .on('close', this._onclose.bind(this))

    if (this._state & constants.state.UNREFED) this._server.unref()

    return this
  }

  _onlistening () {
    this.emit('listening')
  }

  _onconnection (socket) {
    this.emit('connection', new Socket(this._opts)._attach(this._type, socket))
  }

  _onerror (err) {
    this.emit('error', err)
  }

  _onclose () {
    this.emit('close')
  }
}

exports.isIP = tcp.isIP
exports.isIPv4 = tcp.isIPv4
exports.isIPv6 = tcp.isIPv6

exports.createConnection = function createConnection (...args) {
  let opts = {}
  let onconnect

  // createConnection(path[, onconnect])
  if (typeof args[0] === 'string') {
    opts.path = args[0]
    onconnect = args[1]
  // createConnection(port[, host][, onconnect])
  } else if (typeof args[0] === 'number') {
    opts.port = args[0]

    if (typeof args[1] === 'function') {
      onconnect = args[1]
    } else {
      opts.host = args[1]
      onconnect = args[2]
    }
  // createConnection(opts[, onconnect])
  } else {
    opts = args[0] || {}
    onconnect = args[1]
  }

  return new Socket(opts).connect(opts, onconnect)
}

exports.createServer = function createServer (opts, onconnection) {
  return new Server(opts, onconnection)
}
module.exports = require.addon()
const binding = require('./binding')

function onlookup (err, addresses) {
  const req = this

  if (err) return req.cb(err, null, 0)

  const { address, family } = addresses[0]

  return req.cb(null, address, family)
}

function onlookupall (err, addresses) {
  const req = this

  if (err) return req.cb(err, null)

  return req.cb(null, addresses)
}

exports.lookup = function lookup (hostname, opts = {}, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  let {
    family = 0,
    all = false
  } = opts

  if (typeof family === 'string') {
    switch (family) {
      case 'IPv4': family = 4
        break
      case 'IPv6': family = 6
        break
      default: family = 0
    }
  }

  const req = {
    cb,
    handle: null
  }

  req.handle = binding.lookup(hostname, family || 0, all, req, all ? onlookupall : onlookup)
}
{
  "name": "bare-dns",
  "version": "1.0.5",
  "description": "Domain name resolution for JavaScript",
  "exports": {
    ".": "./index.js",
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "standard && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-dns.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-dns/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-dns",
  "devDependencies": {
    "brittle": "^3.3.2",
    "cmake-bare": "^1.1.6",
    "standard": "^17.1.0"
  }
}
module.exports = require.addon()
/* global Bare */
const EventEmitter = require('bare-events')
const { Duplex } = require('bare-stream')
const binding = require('./binding')
const constants = require('./lib/constants')
const errors = require('./lib/errors')

const defaultReadBufferSize = 65536

const Pipe = module.exports = exports = class Pipe extends Duplex {
  constructor (path, opts = {}) {
    super({ eagerOpen: true })

    if (typeof path === 'object' && path !== null) {
      opts = path
      path = null
    }

    const {
      readBufferSize = defaultReadBufferSize,
      allowHalfOpen = true
    } = opts

    this._state = 0

    this._allowHalfOpen = allowHalfOpen

    this._fd = -1
    this._path = null

    this._pendingOpen = null
    this._pendingWrite = null
    this._pendingFinal = null
    this._pendingDestroy = null

    this._buffer = Buffer.alloc(readBufferSize)

    this._handle = binding.init(this._buffer, this,
      noop,
      this._onconnect,
      this._onwrite,
      this._onfinal,
      this._onread,
      this._onclose
    )

    if (typeof path === 'number') {
      this.open(path)
    } else if (typeof path === 'string') {
      this.connect(path)
    }

    Pipe._pipes.add(this)
  }

  get connecting () {
    return (this._state & constants.state.CONNECTING) !== 0
  }

  get pending () {
    return (this._state & constants.state.CONNECTED) === 0
  }

  get readyState () {
    if (this._state & constants.state.READABLE && this._state & constants.state.WRITABLE) {
      return 'open'
    }

    if (this._state & constants.state.READABLE) {
      return 'readOnly'
    }

    if (this._state & constants.state.WRITABLE) {
      return 'writeOnly'
    }

    return 'opening'
  }

  open (fd, opts = {}, onconnect) {
    if (typeof opts === 'function') {
      onconnect = opts
      opts = {}
    }

    if (typeof fd === 'object' && fd !== null) {
      opts = fd || {}
      fd = opts.fd
    }

    try {
      const status = binding.open(this._handle, fd)

      this._state |= constants.state.CONNECTED
      this._fd = fd

      if (status & binding.READABLE) {
        this._state |= constants.state.READABLE
      } else {
        this.push(null)
      }

      if (status & binding.WRITABLE) {
        this._state |= constants.state.WRITABLE
      } else {
        this.end()
      }

      if (onconnect) this.once('connect', onconnect)

      queueMicrotask(() => this.emit('connect'))
    } catch (err) {
      queueMicrotask(() => {
        if (this._pendingOpen) this._pendingOpen(err)
        else this.destroy(err)
      })
    }

    return this
  }

  connect (path, opts = {}, onconnect) {
    if (this._state & constants.state.CONNECTING || this._state & constants.state.CONNECTED) {
      throw errors.PIPE_ALREADY_CONNECTED('Pipe is already connected')
    }

    this._state |= constants.state.CONNECTING

    if (typeof opts === 'function') {
      onconnect = opts
      opts = {}
    }

    if (typeof path === 'object' && path !== null) {
      opts = path || {}
      path = opts.path
    }

    try {
      binding.connect(this._handle, path)

      this._path = path

      if (onconnect) this.once('connect', onconnect)
    } catch (err) {
      queueMicrotask(() => {
        if (this._pendingOpen) this._pendingOpen(err)
        else this.destroy(err)
      })
    }

    return this
  }

  ref () {
    binding.ref(this._handle)
  }

  unref () {
    binding.unref(this._handle)
  }

  _open (cb) {
    if (this._state & constants.state.CONNECTED) return cb(null)
    this._pendingOpen = cb
  }

  _read () {
    if ((this._state & constants.state.READING) === 0) {
      this._state |= constants.state.READING
      binding.resume(this._handle)
    }
  }

  _writev (batch, cb) {
    this._pendingWrite = [cb, batch]
    binding.writev(this._handle, batch.map(({ chunk }) => chunk))
  }

  _final (cb) {
    if (this._state & constants.state.READABLE && this._state & constants.state.WRITABLE) {
      this._pendingFinal = cb
      binding.end(this._handle)
    } else {
      cb(null)
    }
  }

  _predestroy () {
    if (this._state & constants.state.CLOSING) return
    this._state |= constants.state.CLOSING
    binding.close(this._handle)
    Pipe._pipes.delete(this)
  }

  _destroy (err, cb) {
    if (this._state & constants.state.CLOSING) return cb(err)
    this._state |= constants.state.CLOSING
    this._pendingDestroy = cb
    binding.close(this._handle)
    Pipe._pipes.delete(this)
  }

  _continueOpen (err) {
    if (this._pendingOpen === null) return
    const cb = this._pendingOpen
    this._pendingOpen = null
    cb(err)
  }

  _continueWrite (err) {
    if (this._pendingWrite === null) return
    const cb = this._pendingWrite[0]
    this._pendingWrite = null
    cb(err)
  }

  _continueFinal (err) {
    if (this._pendingFinal === null) return
    const cb = this._pendingFinal
    this._pendingFinal = null
    cb(err)
  }

  _continueDestroy () {
    if (this._pendingDestroy === null) return
    const cb = this._pendingDestroy
    this._pendingDestroy = null
    cb(null)
  }

  _onconnect (err) {
    if (err) {
      if (this._pendingOpen) this._continueOpen(err)
      else this.destroy(err)
      return
    }

    this._state |= constants.state.CONNECTED | constants.state.READABLE | constants.state.WRITABLE
    this._state &= ~constants.state.CONNECTING
    this._continueOpen()

    this.emit('connect')
  }

  _onread (err, read) {
    if (err) {
      this.destroy(err)
      return
    }

    if (read === 0) {
      this.push(null)
      if (this._allowHalfOpen === false) this.end()
      return
    }

    const copy = Buffer.allocUnsafe(read)
    copy.set(this._buffer.subarray(0, read))

    if (this.push(copy) === false && this.destroying === false) {
      this._state &= ~constants.state.READING
      binding.pause(this._handle)
    }
  }

  _onwrite (err) {
    this._continueWrite(err)
  }

  _onfinal (err) {
    this._continueFinal(err)
  }

  _onclose () {
    this._handle = null
    this._continueDestroy()
  }

  _onspawn (readable, writable) {
    this._state |= constants.state.CONNECTED

    if (readable) {
      this._state |= constants.state.READABLE
    } else {
      this.push(null)
    }

    if (writable) {
      this._state |= constants.state.WRITABLE
    } else {
      this.end()
    }

    this._continueOpen()
  }

  static _pipes = new Set()
}

exports.Pipe = exports

exports.pipe = function pipe () {
  return binding.pipe()
}

const Server = exports.Server = class PipeServer extends EventEmitter {
  constructor (opts = {}, onconnection) {
    if (typeof opts === 'function') {
      onconnection = opts
      opts = {}
    }

    super()

    const {
      readBufferSize = defaultReadBufferSize,
      allowHalfOpen = true
    } = opts

    this._state = 0

    this._readBufferSize = readBufferSize
    this._allowHalfOpen = allowHalfOpen

    this._path = null
    this._connections = new Set()

    this._error = null
    this._handle = null

    if (onconnection) this.on('connection', onconnection)

    PipeServer._servers.add(this)
  }

  get listening () {
    return (this._state & constants.state.BOUND) !== 0
  }

  address () {
    if ((this._state & constants.state.BOUND) === 0) {
      return null
    }

    return this._path
  }

  listen (path, backlog = 511, opts = {}, onlistening) {
    if (this._state & constants.state.BINDING || this._state & constants.state.BOUND) {
      throw errors.SERVER_ALREADY_LISTENING('Server is already listening')
    }

    if (this._state & constants.state.CLOSING) {
      throw errors.SERVER_IS_CLOSED('Server is closed')
    }

    this._state |= constants.state.BINDING

    if (typeof backlog === 'function') {
      onlistening = backlog
      backlog = 511
    } else if (typeof opts === 'function') {
      onlistening = opts
      opts = {}
    }

    if (typeof path === 'object' && path !== null) {
      opts = path || {}
      path = opts.path
      backlog = opts.backlog || 511
    }

    this._handle = binding.init(empty, this,
      this._onconnection,
      noop,
      noop,
      noop,
      noop,
      this._onclose
    )

    if (this._state & constants.state.UNREFED) binding.unref(this._handle)

    try {
      binding.bind(this._handle, path, backlog)

      this._path = path
      this._state |= constants.state.BOUND
      this._state &= ~constants.state.BINDING

      if (onlistening) this.once('listening', onlistening)

      queueMicrotask(() => this.emit('listening'))
    } catch (err) {
      this._error = err

      binding.close(this._handle)
    }

    return this
  }

  close (onclose) {
    if (onclose) this.once('close', onclose)
    if (this._state & constants.state.CLOSING) return
    this._state |= constants.state.CLOSING
    this._closeMaybe()
  }

  ref () {
    this._state &= ~constants.state.UNREFED
    if (this._handle !== null) binding.ref(this._handle)
  }

  unref () {
    this._state |= constants.state.UNREFED
    if (this._handle !== null) binding.unref(this._handle)
  }

  _closeMaybe () {
    if ((this._state & constants.state.CLOSING) && this._connections.size === 0) {
      if (this._handle !== null) binding.close(this._handle)
      else queueMicrotask(() => this.emit('close'))
      PipeServer._servers.delete(this)
    }
  }

  _onconnection (err) {
    if (err) {
      this.emit('error', err)
      return
    }

    if (this._state & constants.state.CLOSING) return

    const pipe = new Pipe({
      readBufferSize: this._readBufferSize,
      allowHalfOpen: this._allowHalfOpen
    })

    try {
      binding.accept(this._handle, pipe._handle)

      pipe._path = this._path
      pipe._state |= constants.state.CONNECTED | constants.state.READABLE | constants.state.WRITABLE

      this._connections.add(pipe)

      pipe.on('close', () => {
        this._connections.delete(pipe)
        this._closeMaybe()
      })

      this.emit('connection', pipe)
    } catch (err) {
      pipe.destroy()

      throw err
    }
  }

  _onclose () {
    const err = this._error

    this._state &= ~constants.state.BINDING
    this._error = null
    this._handle = null

    if (err) this.emit('error', err)
    else this.emit('close')
  }

  static _servers = new Set()
}

exports.constants = constants
exports.errors = errors

exports.createConnection = function createConnection (path, opts, onconnect) {
  if (typeof opts === 'function') {
    onconnect = opts
    opts = {}
  }

  if (typeof path === 'object' && path !== null) {
    opts = path || {}
    path = opts.path
  }

  return new Pipe(opts).connect(path, opts, onconnect)
}

exports.createServer = function createServer (opts, onconnection) {
  return new Server(opts, onconnection)
}

Bare
  .on('exit', () => {
    for (const pipe of Pipe._pipes) {
      pipe.destroy()
    }

    for (const server of Server._servers) {
      server.close()
    }
  })

const empty = Buffer.alloc(0)

function noop () {}
module.exports = {
  state: {
    CONNECTING: 0x1,
    CONNECTED: 0x2,
    BINDING: 0x4,
    BOUND: 0x8,
    READING: 0x10,
    CLOSING: 0x20,
    READABLE: 0x40,
    WRITABLE: 0x80
  }
}
module.exports = class PipeError extends Error {
  constructor (msg, code, fn = PipeError) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name () {
    return 'PipeError'
  }

  static PIPE_ALREADY_CONNECTED (msg) {
    return new PipeError(msg, 'PIPE_ALREADY_CONNECTED', PipeError.PIPE_ALREADY_CONNECTED)
  }

  static SERVER_ALREADY_LISTENING (msg) {
    return new PipeError(msg, 'SERVER_ALREADY_LISTENING', PipeError.SERVER_ALREADY_LISTENING)
  }

  static SERVER_IS_CLOSED (msg) {
    return new PipeError(msg, 'SERVER_IS_CLOSED', PipeError.SERVER_IS_CLOSED)
  }
}
{
  "name": "bare-pipe",
  "version": "3.3.8",
  "description": "Native I/O pipes for JavaScript",
  "exports": {
    ".": "./index.js",
    "./package": "./package.json",
    "./constants": "./lib/constants.js",
    "./errors": "./lib/errors.js"
  },
  "files": [
    "index.js",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "standard && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-pipe.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-pipe/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-pipe#readme",
  "dependencies": {
    "bare-events": "^2.0.0",
    "bare-stream": "^2.0.0"
  },
  "devDependencies": {
    "bare-path": "^3.0.0",
    "brittle": "^3.2.1",
    "cmake-bare": "^1.1.6",
    "standard": "^17.0.0"
  }
}
module.exports = require.addon()
/* global Bare */
const EventEmitter = require('bare-events')
const { Duplex } = require('bare-stream')
const dns = require('bare-dns')
const binding = require('./binding')
const constants = require('./lib/constants')
const errors = require('./lib/errors')
const ip = require('./lib/ip')

const defaultReadBufferSize = 65536

const Socket = exports.Socket = class TCPSocket extends Duplex {
  constructor (opts = {}) {
    super({ eagerOpen: true })

    const {
      readBufferSize = defaultReadBufferSize,
      allowHalfOpen = true
    } = opts

    this._state = 0

    this._allowHalfOpen = allowHalfOpen

    this._remotePort = -1
    this._remoteHost = null
    this._remoteFamily = 0

    this._pendingOpen = null
    this._pendingWrite = null
    this._pendingFinal = null
    this._pendingDestroy = null

    this._timer = null
    this._timeout = 0

    this._buffer = Buffer.alloc(readBufferSize)

    this._handle = binding.init(this._buffer, this,
      noop,
      this._onconnect,
      this._onread,
      this._onwrite,
      this._onfinal,
      this._onclose
    )

    TCPSocket._sockets.add(this)
  }

  get connecting () {
    return (this._state & constants.state.CONNECTING) !== 0
  }

  get pending () {
    return (this._state & constants.state.CONNECTED) === 0
  }

  get timeout () {
    return this._timeout || undefined // For Node.js compatibility
  }

  connect (port, host = 'localhost', opts = {}, onconnect) {
    if (this._state & constants.state.CONNECTING || this._state & constants.state.CONNECTED) {
      throw errors.SOCKET_ALREADY_CONNECTED('Socket is already connected')
    }

    this._state |= constants.state.CONNECTING

    if (typeof host === 'function') {
      onconnect = host
      host = 'localhost'
    } else if (typeof opts === 'function') {
      onconnect = opts
      opts = {}
    }

    let family = 0

    if (typeof port === 'object' && port !== null) {
      opts = port || {}
      port = opts.port || 0
      host = opts.host || 'localhost'
      family = opts.family || 0
    }

    if (!host) host = 'localhost'

    const type = ip.isIP(host)

    if (type === 0) {
      const {
        lookup = dns.lookup,
        hints
      } = opts

      lookup(host, { family, hints }, (err, address, family) => {
        this.emit('lookup', err, address, family, host)

        this._state &= ~constants.state.CONNECTING

        if (err) {
          if (this._pendingOpen) this._continueOpen(err)
          else this.destroy(err)
          return
        }

        if (this._handle !== null) {
          this.connect(port, address, { ...opts, family }, onconnect)
        }
      })

      return this
    }

    family = type

    try {
      binding.connect(this._handle, port, host, family)

      if (opts.keepAlive === true) this.setKeepAlive(opts.keepAlive, opts.keepAliveInitialDelay)
      if (opts.noDelay === true) this.setNoDelay()
      if (opts.timeout) this.setTimeout(opts.timeout)

      this._remotePort = port
      this._remoteHost = host
      this._remoteFamily = family

      if (onconnect) this.once('connect', onconnect)
    } catch (err) {
      queueMicrotask(() => {
        if (this._pendingOpen) this._pendingOpen(err)
        else this.destroy(err)
      })
    }

    return this
  }

  setKeepAlive (enable = false, delay = 0) {
    if (typeof enable === 'number') {
      delay = enable
      enable = false
    }

    delay = Math.floor(delay / 1000)

    if (delay === 0) enable = false

    binding.keepalive(this._handle, enable, delay)

    return this
  }

  setNoDelay (enable = true) {
    binding.nodelay(this._handle, enable)

    return this
  }

  setTimeout (ms, ontimeout) {
    if (ms === 0) {
      clearTimeout(this._timer)
      this._timer = null
    } else {
      if (ontimeout) this.once('timeout', ontimeout)

      this._timer = setTimeout(() => this.emit('timeout'), ms)
      this._timer.unref()
    }

    this._timeout = ms

    return this
  }

  ref () {
    binding.ref(this._handle)
  }

  unref () {
    binding.unref(this._handle)
  }

  _open (cb) {
    if (this._state & constants.state.CONNECTED) return cb(null)
    this._pendingOpen = cb
  }

  _read () {
    if ((this._state & constants.state.READING) === 0) {
      this._state |= constants.state.READING
      binding.resume(this._handle)
    }
  }

  _writev (batch, cb) {
    this._pendingWrite = [cb, batch]
    binding.writev(this._handle, batch.map(({ chunk }) => chunk))
  }

  _final (cb) {
    this._pendingFinal = cb
    binding.end(this._handle)
  }

  _predestroy () {
    if (this._state & constants.state.CLOSING) return
    this._state |= constants.state.CLOSING
    binding.close(this._handle)
    TCPSocket._sockets.delete(this)
  }

  _destroy (err, cb) {
    if (this._state & constants.state.CLOSING) return cb(err)
    this._state |= constants.state.CLOSING
    this._pendingDestroy = cb
    binding.close(this._handle)
    TCPSocket._sockets.delete(this)
  }

  _continueOpen (err) {
    if (this._pendingOpen === null) return
    const cb = this._pendingOpen
    this._pendingOpen = null
    cb(err)
  }

  _continueWrite (err) {
    if (this._pendingWrite === null) return
    const cb = this._pendingWrite[0]
    this._pendingWrite = null
    cb(err)
  }

  _continueFinal (err) {
    if (this._pendingFinal === null) return
    const cb = this._pendingFinal
    this._pendingFinal = null
    cb(err)
  }

  _continueDestroy () {
    if (this._pendingDestroy === null) return
    const cb = this._pendingDestroy
    this._pendingDestroy = null
    cb(null)
  }

  _onconnect (err) {
    if (err) {
      if (this._pendingOpen) this._continueOpen(err)
      else this.destroy(err)
      return
    }

    this._state |= constants.state.CONNECTED
    this._state &= ~constants.state.CONNECTING
    this._continueOpen()

    this.emit('connect')
  }

  _onread (err, read) {
    if (this._timer) this._timer.refresh()

    if (err) {
      this.destroy(err)
      return
    }

    if (read === 0) {
      this.push(null)
      if (this._allowHalfOpen === false) this.end()
      return
    }

    const copy = Buffer.allocUnsafe(read)
    copy.set(this._buffer.subarray(0, read))

    if (this.push(copy) === false && this.destroying === false) {
      this._state &= ~constants.state.READING
      binding.pause(this._handle)
    }
  }

  _onwrite (err) {
    if (this._timer) this._timer.refresh()

    this._continueWrite(err)
  }

  _onfinal (err) {
    this._continueFinal(err)
  }

  _onclose () {
    clearTimeout(this._timer)

    this._handle = null
    this._continueDestroy()
  }

  static _sockets = new Set()
}

const Server = exports.Server = class TCPServer extends EventEmitter {
  constructor (opts = {}, onconnection) {
    if (typeof opts === 'function') {
      onconnection = opts
      opts = {}
    }

    super()

    const {
      readBufferSize = defaultReadBufferSize,
      allowHalfOpen = true
    } = opts

    this._state = 0

    this._readBufferSize = readBufferSize
    this._allowHalfOpen = allowHalfOpen

    this._keepAlive = opts.keepAlive
    this._keepAliveDelay = opts.keepAliveInitialDelay
    this._noDelay = opts.noDelay

    this._port = -1
    this._host = null
    this._family = 0
    this._connections = new Set()

    this._error = null
    this._handle = null

    if (onconnection) this.on('connection', onconnection)

    TCPServer._servers.add(this)
  }

  get listening () {
    return (this._state & constants.state.BOUND) !== 0
  }

  address () {
    if ((this._state & constants.state.BOUND) === 0) {
      return null
    }

    return {
      address: this._host,
      family: `IPv${this._family}`,
      port: this._port
    }
  }

  listen (port = 0, host = 'localhost', backlog = 511, opts = {}, onlistening) {
    if (this._state & constants.state.BINDING || this._state & constants.state.BOUND) {
      throw errors.SERVER_ALREADY_LISTENING('Server is already listening')
    }

    if (this._state & constants.state.CLOSING) {
      throw errors.SERVER_IS_CLOSED('Server is closed')
    }

    this._state |= constants.state.BINDING

    if (typeof port === 'function') {
      onlistening = port
      port = 0
    } else if (typeof host === 'function') {
      onlistening = host
      host = 'localhost'
    } else if (typeof backlog === 'function') {
      onlistening = backlog
      backlog = 511
    } else if (typeof opts === 'function') {
      onlistening = opts
      opts = {}
    }

    let family = 0

    if (typeof port === 'object' && port !== null) {
      opts = port || {}
      port = opts.port || 0
      host = opts.host || 'localhost'
      family = opts.family || 0
      backlog = opts.backlog || 511
    }

    if (!host) host = 'localhost'
    if (!backlog) backlog = 511

    const type = ip.isIP(host)

    if (type === 0) {
      const {
        lookup = dns.lookup,
        hints
      } = opts

      lookup(host, { family, hints }, (err, address, family) => {
        if (this._state & constants.state.CLOSING) return

        this.emit('lookup', err, address, family, host)

        this._state &= ~constants.state.BINDING

        if (err) return this.emit('error', err)

        this.listen(port, address, backlog, { ...opts, family }, onlistening)
      })

      return this
    }

    family = type

    this._handle = binding.init(empty, this,
      this._onconnection,
      noop,
      noop,
      noop,
      noop,
      this._onclose
    )

    if (this._state & constants.state.UNREFED) binding.unref(this._handle)

    try {
      this._port = binding.bind(this._handle, port, host, backlog, family)
      this._host = host
      this._family = family
      this._state |= constants.state.BOUND
      this._state &= ~constants.state.BINDING

      if (onlistening) this.once('listening', onlistening)

      queueMicrotask(() => this.emit('listening'))
    } catch (err) {
      this._error = err

      binding.close(this._handle)
    }

    return this
  }

  close (onclose) {
    if (onclose) this.once('close', onclose)
    if (this._state & constants.state.CLOSING) return
    this._state |= constants.state.CLOSING
    this._closeMaybe()
  }

  ref () {
    this._state &= ~constants.state.UNREFED
    if (this._handle !== null) binding.ref(this._handle)
  }

  unref () {
    this._state |= constants.state.UNREFED
    if (this._handle !== null) binding.unref(this._handle)
  }

  _closeMaybe () {
    if ((this._state & constants.state.CLOSING) && this._connections.size === 0) {
      if (this._handle !== null) binding.close(this._handle)
      else queueMicrotask(() => this.emit('close'))
      TCPServer._servers.delete(this)
    }
  }

  _onconnection (err) {
    if (err) {
      this.emit('error', err)
      return
    }

    if (this._state & constants.state.CLOSING) return

    const socket = new Socket({
      readBufferSize: this._readBufferSize,
      allowHalfOpen: this._allowHalfOpen
    })

    try {
      binding.accept(this._handle, socket._handle)

      socket._state |= constants.state.CONNECTED

      this._connections.add(socket)

      if (this._keepAlive === true) socket.setKeepAlive(this._keepAlive, this._keepAliveDelay)
      if (this._noDelay === true) socket.setNoDelay()

      socket.on('close', () => {
        this._connections.delete(socket)
        this._closeMaybe()
      })

      this.emit('connection', socket)
    } catch (err) {
      socket.destroy()

      throw err
    }
  }

  _onclose () {
    const err = this._error

    this._state &= ~constants.state.BINDING
    this._error = null
    this._handle = null

    if (err) this.emit('error', err)
    else this.emit('close')
  }

  static _servers = new Set()
}

exports.constants = constants
exports.errors = errors

exports.isIP = ip.isIP
exports.isIPv4 = ip.isIPv4
exports.isIPv6 = ip.isIPv6

exports.createConnection = function createConnection (port, host, opts, onconnect) {
  if (typeof host === 'function') {
    onconnect = host
    host = 'localhost'
  } else if (typeof opts === 'function') {
    onconnect = opts
    opts = {}
  }

  if (typeof port === 'object' && port !== null) {
    opts = port || {}
    port = opts.port || 0
    host = opts.host || 'localhost'
  }

  return new Socket(opts).connect(port, host, opts, onconnect)
}

// For Node.js compatibility
exports.connect = exports.createConnection

exports.createServer = function createServer (opts, onconnection) {
  return new Server(opts, onconnection)
}

Bare
  .on('exit', () => {
    for (const socket of Socket._sockets) {
      socket.destroy()
    }

    for (const server of Server._servers) {
      server.close()
    }
  })

const empty = Buffer.alloc(0)

function noop () {}
module.exports = {
  state: {
    CONNECTING: 0x1,
    CONNECTED: 0x2,
    BINDING: 0x4,
    BOUND: 0x8,
    READING: 0x10,
    CLOSING: 0x20,
    UNREFED: 0x40
  }
}
module.exports = class TCPError extends Error {
  constructor (msg, code, fn = TCPError) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name () {
    return 'TCPError'
  }

  static SOCKET_ALREADY_CONNECTED (msg) {
    return new TCPError(msg, 'SOCKET_ALREADY_CONNECTED', TCPError.SOCKET_ALREADY_CONNECTED)
  }

  static SERVER_ALREADY_LISTENING (msg) {
    return new TCPError(msg, 'SERVER_ALREADY_LISTENING', TCPError.SERVER_ALREADY_LISTENING)
  }

  static SERVER_IS_CLOSED (msg) {
    return new TCPError(msg, 'SERVER_IS_CLOSED', TCPError.SERVER_IS_CLOSED)
  }

  static INVALID_HOST (msg = 'Unrecognizable host format') {
    return new TCPError(msg, 'INVALID_HOST', TCPError.INVALID_HOST)
  }
}
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

const v4Seg = '(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])'
const v4Str = `(${v4Seg}[.]){3}${v4Seg}`
const IPv4Pattern = new RegExp(`^${v4Str}$`)

const v6Seg = '(?:[0-9a-fA-F]{1,4})'
const IPv6Pattern = new RegExp('^(' +
  `(?:${v6Seg}:){7}(?:${v6Seg}|:)|` +
  `(?:${v6Seg}:){6}(?:${v4Str}|:${v6Seg}|:)|` +
  `(?:${v6Seg}:){5}(?::${v4Str}|(:${v6Seg}){1,2}|:)|` +
  `(?:${v6Seg}:){4}(?:(:${v6Seg}){0,1}:${v4Str}|(:${v6Seg}){1,3}|:)|` +
  `(?:${v6Seg}:){3}(?:(:${v6Seg}){0,2}:${v4Str}|(:${v6Seg}){1,4}|:)|` +
  `(?:${v6Seg}:){2}(?:(:${v6Seg}){0,3}:${v4Str}|(:${v6Seg}){1,5}|:)|` +
  `(?:${v6Seg}:){1}(?:(:${v6Seg}){0,4}:${v4Str}|(:${v6Seg}){1,6}|:)|` +
  `(?::((?::${v6Seg}){0,5}:${v4Str}|(?::${v6Seg}){1,7}|:))` +
')(%[0-9a-zA-Z-.:]{1,})?$')

const isIPv4 = exports.isIPv4 = function isIPv4 (host) {
  return IPv4Pattern.test(host)
}

const isIPv6 = exports.isIPv6 = function isIPv6 (host) {
  return IPv6Pattern.test(host)
}

exports.isIP = function isIP (host) {
  if (isIPv4(host)) return 4
  if (isIPv6(host)) return 6
  return 0
}
{
  "name": "bare-tcp",
  "version": "1.9.1",
  "description": "Native TCP sockets for JavaScript",
  "exports": {
    ".": "./index.js",
    "./package": "./package.json",
    "./constants": "./lib/constants.js",
    "./errors": "./lib/errors.js"
  },
  "files": [
    "index.js",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "standard && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-tcp.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-tcp/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-tcp#readme",
  "dependencies": {
    "bare-dns": "^1.0.0",
    "bare-events": "^2.2.2",
    "bare-stream": "^2.0.0"
  },
  "devDependencies": {
    "brittle": "^3.5.0",
    "cmake-bare": "^1.1.6",
    "standard": "^17.1.0"
  }
}
{
  "name": "bare-net",
  "version": "1.0.1",
  "description": "TCP and IPC servers and clients for JavaScript",
  "exports": {
    ".": "./index.js",
    "./package": "./package.json"
  },
  "files": [
    "index.js"
  ],
  "scripts": {
    "test": "standard && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-net.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-net/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-net#readme",
  "dependencies": {
    "bare-events": "^2.2.2",
    "bare-pipe": "^3.2.0",
    "bare-stream": "^2.0.0",
    "bare-tcp": "^1.4.0"
  },
  "devDependencies": {
    "brittle": "^3.3.0",
    "standard": "^17.0.0"
  }
}
module.exports = require.addon()
const binding = require('./binding')
const errors = require('./lib/errors')
const constants = require('./lib/constants')

exports.constants = constants
exports.errors = errors

exports.EOL = binding.platform === 'win32' ? '\r\n' : '\n'

exports.devNull = binding.platform === 'win32' ? '\\\\.\\nul' : '/dev/null'

exports.platform = function platform() {
  return binding.platform
}

exports.arch = function arch() {
  return binding.arch
}

exports.type = binding.type
exports.version = binding.version
exports.release = binding.release
exports.machine = binding.machine
exports.execPath = binding.execPath
exports.pid = binding.pid
exports.ppid = binding.ppid
exports.cwd = binding.cwd
exports.chdir = binding.chdir
exports.tmpdir = binding.tmpdir
exports.homedir = binding.homedir
exports.hostname = binding.hostname
exports.userInfo = binding.userInfo
exports.groupInfo = binding.groupInfo

exports.networkInterfaces = function networkInterfaces() {
  const result = {}

  for (const entry of binding.networkInterfaces()) {
    const { name, ...properties } = entry

    if (result[name]) result[name].push(properties)
    else result[name] = [properties]
  }

  return result
}

exports.kill = function kill(pid, signal = constants.signals.SIGTERM) {
  if (typeof signal === 'string') {
    if (signal in constants.signals === false) {
      throw errors.UNKNOWN_SIGNAL('Unknown signal: ' + signal)
    }

    signal = constants.signals[signal]
  }

  binding.kill(pid, signal)
}

exports.endianness = function endianness() {
  return binding.isLittleEndian ? 'LE' : 'BE'
}

exports.availableParallelism = binding.availableParallelism

exports.cpuUsage = function cpuUsage(previous) {
  const current = binding.cpuUsage()

  if (previous) {
    return {
      user: current.user - previous.user,
      system: current.system - previous.system
    }
  }

  return current
}

exports.threadCpuUsage = function threadCpuUsage(previous) {
  const current = binding.threadCpuUsage()

  if (previous) {
    return {
      user: current.user - previous.user,
      system: current.system - previous.system
    }
  }

  return current
}

exports.resourceUsage = binding.resourceUsage
exports.memoryUsage = binding.memoryUsage
exports.freemem = binding.freemem
exports.totalmem = binding.totalmem
exports.availableMemory = binding.availableMemory
exports.constrainedMemory = binding.constrainedMemory
exports.uptime = binding.uptime
exports.loadavg = binding.loadavg
exports.cpus = binding.cpus

exports.getProcessTitle = binding.getProcessTitle

exports.setProcessTitle = function setProcessTitle(title) {
  if (typeof title !== 'string') title = title.toString()

  if (title.length >= 256) {
    throw errors.TITLE_OVERFLOW('Process title is too long')
  }

  binding.setProcessTitle(title)
}

exports.getPriority = function getPriority(pid = 0) {
  return binding.getPriority(pid)
}

exports.setPriority = function setPriority(pid, priority) {
  if (priority === undefined) {
    priority = pid
    pid = 0
  }

  binding.setPriority(pid, priority)
}

exports.getEnvKeys = binding.getEnvKeys
exports.getEnv = binding.getEnv
exports.hasEnv = binding.hasEnv
exports.setEnv = binding.setEnv
exports.unsetEnv = binding.unsetEnv
const binding = require('../binding')

module.exports = {
  signals: binding.signals,
  errnos: binding.errnos,
  priority: binding.priority
}
module.exports = class OSError extends Error {
  constructor(msg, fn = OSError, code = fn.name) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'OSError'
  }

  static UNKNOWN_SIGNAL(msg) {
    return new OSError(msg, OSError.UNKNOWN_SIGNAL)
  }

  static TITLE_OVERFLOW(msg) {
    return new OSError(msg, OSError.TITLE_OVERFLOW)
  }
}
{
  "name": "bare-os",
  "version": "3.9.1",
  "description": "Operating system utilities for Bare",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    },
    "./errors": {
      "types": "./lib/errors.d.ts",
      "default": "./lib/errors.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-os.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-os/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-os#readme",
  "engines": {
    "bare": ">=1.14.0"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "cmake-bare": "^1.1.6",
    "lunte": "^1.6.0",
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
/* global Bare */

// This export SHOULD NOT be shortened in any way as having the full
// `module.exports = require(...)` statement is crucial for synthesizing
// ESM exports.

if (Bare.platform === 'win32') {
  module.exports = require('./lib/win32')
} else {
  module.exports = require('./lib/posix')
}
module.exports = {
  CHAR_UPPERCASE_A: 0x41,
  CHAR_LOWERCASE_A: 0x61,
  CHAR_UPPERCASE_Z: 0x5a,
  CHAR_LOWERCASE_Z: 0x7a,
  CHAR_DOT: 0x2e,
  CHAR_FORWARD_SLASH: 0x2f,
  CHAR_BACKWARD_SLASH: 0x5c,
  CHAR_COLON: 0x3a,
  CHAR_QUESTION_MARK: 0x3f
}
const os = require('bare-os')

const { normalizeString } = require('./shared')
const {
  CHAR_DOT,
  CHAR_FORWARD_SLASH
} = require('./constants')

function isPosixPathSeparator (code) {
  return code === CHAR_FORWARD_SLASH
}

exports.win32 = require('./win32')
exports.posix = exports

exports.sep = '/'
exports.delimiter = ':'

exports.resolve = function resolve (...args) {
  let resolvedPath = ''
  let resolvedAbsolute = false

  for (let i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) {
    const path = i >= 0 ? args[i] : os.cwd()

    if (path.length === 0) {
      continue
    }

    resolvedPath = `${path}/${resolvedPath}`
    resolvedAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH
  }

  resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute, '/', isPosixPathSeparator)

  if (resolvedAbsolute) {
    return `/${resolvedPath}`
  }

  return resolvedPath.length > 0 ? resolvedPath : '.'
}

exports.normalize = function normalize (path) {
  if (path.length === 0) return '.'

  const isAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH
  const trailingSeparator = path.charCodeAt(path.length - 1) === CHAR_FORWARD_SLASH

  path = normalizeString(path, !isAbsolute, '/', isPosixPathSeparator)

  if (path.length === 0) {
    if (isAbsolute) return '/'
    return trailingSeparator ? './' : '.'
  }

  if (trailingSeparator) path += '/'

  return isAbsolute ? `/${path}` : path
}

exports.isAbsolute = function isAbsolute (path) {
  return path.length > 0 && path.charCodeAt(0) === CHAR_FORWARD_SLASH
}

exports.join = function join (...args) {
  if (args.length === 0) return '.'
  let joined
  for (let i = 0; i < args.length; ++i) {
    const arg = args[i]
    if (arg.length > 0) {
      if (joined === undefined) joined = arg
      else joined += `/${arg}`
    }
  }
  if (joined === undefined) return '.'
  return exports.normalize(joined)
}

exports.relative = function relative (from, to) {
  if (from === to) return ''

  from = exports.resolve(from)
  to = exports.resolve(to)

  if (from === to) return ''

  const fromStart = 1
  const fromEnd = from.length
  const fromLen = fromEnd - fromStart
  const toStart = 1
  const toLen = to.length - toStart

  const length = (fromLen < toLen ? fromLen : toLen)
  let lastCommonSep = -1
  let i = 0
  for (; i < length; i++) {
    const fromCode = from.charCodeAt(fromStart + i)
    if (fromCode !== to.charCodeAt(toStart + i)) {
      break
    } else if (fromCode === CHAR_FORWARD_SLASH) {
      lastCommonSep = i
    }
  }
  if (i === length) {
    if (toLen > length) {
      if (to.charCodeAt(toStart + i) === CHAR_FORWARD_SLASH) {
        return to.substring(toStart + i + 1)
      }
      if (i === 0) {
        return to.substring(toStart + i)
      }
    } else if (fromLen > length) {
      if (from.charCodeAt(fromStart + i) === CHAR_FORWARD_SLASH) {
        lastCommonSep = i
      } else if (i === 0) {
        lastCommonSep = 0
      }
    }
  }

  let out = ''
  for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
    if (i === fromEnd || from.charCodeAt(i) === CHAR_FORWARD_SLASH) {
      out += out.length === 0 ? '..' : '/..'
    }
  }

  return `${out}${to.substring(toStart + lastCommonSep)}`
}

exports.toNamespacedPath = function toNamespacedPath (path) {
  return path
}

exports.dirname = function dirname (path) {
  if (path.length === 0) return '.'
  const hasRoot = path.charCodeAt(0) === CHAR_FORWARD_SLASH
  let end = -1
  let matchedSlash = true
  for (let i = path.length - 1; i >= 1; --i) {
    if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) {
      if (!matchedSlash) {
        end = i
        break
      }
    } else {
      matchedSlash = false
    }
  }

  if (end === -1) return hasRoot ? '/' : '.'
  if (hasRoot && end === 1) return '//'
  return path.substring(0, end)
}

exports.basename = function basename (path, suffix) {
  let start = 0
  let end = -1
  let matchedSlash = true

  if (suffix !== undefined && suffix.length > 0 && suffix.length <= path.length) {
    if (suffix === path) { return '' }
    let extIdx = suffix.length - 1
    let firstNonSlashEnd = -1
    for (let i = path.length - 1; i >= 0; --i) {
      const code = path.charCodeAt(i)
      if (code === CHAR_FORWARD_SLASH) {
        if (!matchedSlash) {
          start = i + 1
          break
        }
      } else {
        if (firstNonSlashEnd === -1) {
          matchedSlash = false
          firstNonSlashEnd = i + 1
        }
        if (extIdx >= 0) {
          if (code === suffix.charCodeAt(extIdx)) {
            if (--extIdx === -1) {
              end = i
            }
          } else {
            extIdx = -1
            end = firstNonSlashEnd
          }
        }
      }
    }

    if (start === end) end = firstNonSlashEnd
    else if (end === -1) end = path.length
    return path.substring(start, end)
  }

  for (let i = path.length - 1; i >= 0; --i) {
    if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) {
      if (!matchedSlash) {
        start = i + 1
        break
      }
    } else if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
  }

  if (end === -1) return ''
  return path.substring(start, end)
}

exports.extname = function extname (path) {
  let startDot = -1
  let startPart = 0
  let end = -1
  let matchedSlash = true
  let preDotState = 0
  for (let i = path.length - 1; i >= 0; --i) {
    const code = path.charCodeAt(i)
    if (code === CHAR_FORWARD_SLASH) {
      if (!matchedSlash) {
        startPart = i + 1
        break
      }
      continue
    }
    if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
    if (code === CHAR_DOT) {
      if (startDot === -1) startDot = i
      else if (preDotState !== 1) preDotState = 1
    } else if (startDot !== -1) {
      preDotState = -1
    }
  }

  if (startDot === -1 || end === -1 || preDotState === 0 || (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1)) {
    return ''
  }
  return path.substring(startDot, end)
}
const {
  CHAR_DOT,
  CHAR_FORWARD_SLASH
} = require('./constants')

exports.normalizeString = function normalizeString (path, allowAboveRoot, separator, isPathSeparator) {
  let res = ''
  let lastSegmentLength = 0
  let lastSlash = -1
  let dots = 0
  let code = 0
  for (let i = 0; i <= path.length; ++i) {
    if (i < path.length) {
      code = path.charCodeAt(i)
    } else if (isPathSeparator(code)) {
      break
    } else {
      code = CHAR_FORWARD_SLASH
    }

    if (isPathSeparator(code)) {
      if (lastSlash === i - 1 || dots === 1) ;
      else if (dots === 2) {
        if (res.length < 2 || lastSegmentLength !== 2 || res.charCodeAt(res.length - 1) !== CHAR_DOT || res.charCodeAt(res.length - 2) !== CHAR_DOT) {
          if (res.length > 2) {
            const lastSlashIndex = res.lastIndexOf(separator)
            if (lastSlashIndex === -1) {
              res = ''
              lastSegmentLength = 0
            } else {
              res = res.substring(0, lastSlashIndex)
              lastSegmentLength =
                res.length - 1 - res.lastIndexOf(separator)
            }
            lastSlash = i
            dots = 0
            continue
          } else if (res.length !== 0) {
            res = ''
            lastSegmentLength = 0
            lastSlash = i
            dots = 0
            continue
          }
        }
        if (allowAboveRoot) {
          res += res.length > 0 ? `${separator}..` : '..'
          lastSegmentLength = 2
        }
      } else {
        if (res.length > 0) {
          res += `${separator}${path.substring(lastSlash + 1, i)}`
        } else {
          res = path.substring(lastSlash + 1, i)
        }
        lastSegmentLength = i - lastSlash - 1
      }
      lastSlash = i
      dots = 0
    } else if (code === CHAR_DOT && dots !== -1) {
      ++dots
    } else {
      dots = -1
    }
  }
  return res
}
const os = require('bare-os')

const { normalizeString } = require('./shared')
const {
  CHAR_UPPERCASE_A,
  CHAR_LOWERCASE_A,
  CHAR_UPPERCASE_Z,
  CHAR_LOWERCASE_Z,
  CHAR_DOT,
  CHAR_FORWARD_SLASH,
  CHAR_BACKWARD_SLASH,
  CHAR_COLON,
  CHAR_QUESTION_MARK
} = require('./constants')

function isWindowsPathSeparator (code) {
  return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH
}

function isWindowsDeviceRoot (code) {
  return (code >= CHAR_UPPERCASE_A && code <= CHAR_UPPERCASE_Z) ||
         (code >= CHAR_LOWERCASE_A && code <= CHAR_LOWERCASE_Z)
}

exports.posix = require('./posix')
exports.win32 = exports

exports.sep = '\\'
exports.delimiter = ';'

exports.resolve = function resolve (...args) {
  let resolvedDevice = ''
  let resolvedTail = ''
  let resolvedAbsolute = false

  for (let i = args.length - 1; i >= -1; i--) {
    let path
    if (i >= 0) {
      path = args[i]

      if (path.length === 0) continue
    } else if (resolvedDevice.length === 0) {
      path = os.cwd()
    } else {
      path = os.getEnv(`=${resolvedDevice}`) || os.cwd()

      if (path === undefined || (path.substring(0, 2).toLowerCase() !== resolvedDevice.toLowerCase() && path.charCodeAt(2) === CHAR_BACKWARD_SLASH)) {
        path = `${resolvedDevice}\\`
      }
    }

    const len = path.length
    let rootEnd = 0
    let device = ''
    let isAbsolute = false
    const code = path.charCodeAt(0)

    if (len === 1) {
      if (isWindowsPathSeparator(code)) {
        rootEnd = 1
        isAbsolute = true
      }
    } else if (isWindowsPathSeparator(code)) {
      isAbsolute = true

      if (isWindowsPathSeparator(path.charCodeAt(1))) {
        let j = 2
        let last = j
        while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
          j++
        }
        if (j < len && j !== last) {
          const firstPart = path.substring(last, j)
          last = j
          while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
            j++
          }
          if (j < len && j !== last) {
            last = j
            while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
              j++
            }
            if (j === len || j !== last) {
              device = `\\\\${firstPart}\\${path.substring(last, j)}`
              rootEnd = j
            }
          }
        }
      } else {
        rootEnd = 1
      }
    } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
      device = path.substring(0, 2)
      rootEnd = 2
      if (len > 2 && isWindowsPathSeparator(path.charCodeAt(2))) {
        isAbsolute = true
        rootEnd = 3
      }
    }

    if (device.length > 0) {
      if (resolvedDevice.length > 0) {
        if (device.toLowerCase() !== resolvedDevice.toLowerCase()) { continue }
      } else {
        resolvedDevice = device
      }
    }

    if (resolvedAbsolute) {
      if (resolvedDevice.length > 0) { break }
    } else {
      resolvedTail = `${path.substring(rootEnd)}\\${resolvedTail}`
      resolvedAbsolute = isAbsolute
      if (isAbsolute && resolvedDevice.length > 0) {
        break
      }
    }
  }

  resolvedTail = normalizeString(resolvedTail, !resolvedAbsolute, '\\', isWindowsPathSeparator)

  return resolvedAbsolute ? `${resolvedDevice}\\${resolvedTail}` : `${resolvedDevice}${resolvedTail}` || '.'
}

exports.normalize = function normalize (path) {
  const len = path.length
  if (len === 0) return '.'
  let rootEnd = 0
  let device
  let isAbsolute = false
  const code = path.charCodeAt(0)

  if (len === 1) {
    return code === CHAR_FORWARD_SLASH ? '\\' : path
  }

  if (isWindowsPathSeparator(code)) {
    isAbsolute = true

    if (isWindowsPathSeparator(path.charCodeAt(1))) {
      let j = 2
      let last = j
      while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
        j++
      }
      if (j < len && j !== last) {
        const firstPart = path.substring(last, j)
        last = j
        while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
          j++
        }
        if (j < len && j !== last) {
          last = j
          while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
            j++
          }
          if (j === len) {
            return `\\\\${firstPart}\\${path.substring(last)}\\`
          }
          if (j !== last) {
            device = `\\\\${firstPart}\\${path.substring(last, j)}`
            rootEnd = j
          }
        }
      }
    } else {
      rootEnd = 1
    }
  } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
    device = path.substring(0, 2)
    rootEnd = 2
    if (len > 2 && isWindowsPathSeparator(path.charCodeAt(2))) {
      isAbsolute = true
      rootEnd = 3
    }
  }

  let tail = rootEnd < len ? normalizeString(path.substring(rootEnd), !isAbsolute, '\\', isWindowsPathSeparator) : ''
  if (tail.length === 0 && !isAbsolute) {
    tail = '.'
  }
  if (tail.length > 0 && isWindowsPathSeparator(path.charCodeAt(len - 1))) {
    tail += '\\'
  }
  if (device === undefined) {
    return isAbsolute ? `\\${tail}` : tail
  }
  return isAbsolute ? `${device}\\${tail}` : `${device}${tail}`
}

exports.isAbsolute = function isAbsolute (path) {
  const len = path.length
  if (len === 0) return false

  const code = path.charCodeAt(0)

  return isWindowsPathSeparator(code) || (len > 2 && isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON && isWindowsPathSeparator(path.charCodeAt(2)))
}

exports.join = function join (...args) {
  if (args.length === 0) return '.'

  let joined
  let firstPart
  for (let i = 0; i < args.length; ++i) {
    const arg = args[i]
    if (arg.length > 0) {
      if (joined === undefined) joined = firstPart = arg
      else joined += `\\${arg}`
    }
  }

  if (joined === undefined) return '.'

  let needsReplace = true
  let slashCount = 0
  if (isWindowsPathSeparator(firstPart.charCodeAt(0))) {
    ++slashCount
    const firstLen = firstPart.length
    if (firstLen > 1 && isWindowsPathSeparator(firstPart.charCodeAt(1))) {
      ++slashCount
      if (firstLen > 2) {
        if (isWindowsPathSeparator(firstPart.charCodeAt(2))) {
          ++slashCount
        } else {
          needsReplace = false
        }
      }
    }
  }
  if (needsReplace) {
    while (slashCount < joined.length && isWindowsPathSeparator(joined.charCodeAt(slashCount))) {
      slashCount++
    }

    if (slashCount >= 2) {
      joined = `\\${joined.substring(slashCount)}`
    }
  }

  return exports.normalize(joined)
}

exports.relative = function relative (from, to) {
  if (from === to) return ''

  const fromOrig = exports.resolve(from)
  const toOrig = exports.resolve(to)

  if (fromOrig === toOrig) return ''

  from = fromOrig.toLowerCase()
  to = toOrig.toLowerCase()

  if (from === to) return ''

  let fromStart = 0
  while (fromStart < from.length && from.charCodeAt(fromStart) === CHAR_BACKWARD_SLASH) {
    fromStart++
  }
  let fromEnd = from.length
  while (fromEnd - 1 > fromStart && from.charCodeAt(fromEnd - 1) === CHAR_BACKWARD_SLASH) {
    fromEnd--
  }
  const fromLen = fromEnd - fromStart

  let toStart = 0
  while (toStart < to.length && to.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) {
    toStart++
  }
  let toEnd = to.length
  while (toEnd - 1 > toStart && to.charCodeAt(toEnd - 1) === CHAR_BACKWARD_SLASH) {
    toEnd--
  }
  const toLen = toEnd - toStart

  const length = fromLen < toLen ? fromLen : toLen
  let lastCommonSep = -1
  let i = 0
  for (; i < length; i++) {
    const fromCode = from.charCodeAt(fromStart + i)
    if (fromCode !== to.charCodeAt(toStart + i)) {
      break
    } else if (fromCode === CHAR_BACKWARD_SLASH) {
      lastCommonSep = i
    }
  }

  if (i !== length) {
    if (lastCommonSep === -1) return toOrig
  } else {
    if (toLen > length) {
      if (to.charCodeAt(toStart + i) === CHAR_BACKWARD_SLASH) {
        return toOrig.substring(toStart + i + 1)
      }
      if (i === 2) {
        return toOrig.substring(toStart + i)
      }
    }
    if (fromLen > length) {
      if (from.charCodeAt(fromStart + i) === CHAR_BACKWARD_SLASH) {
        lastCommonSep = i
      } else if (i === 2) {
        lastCommonSep = 3
      }
    }
    if (lastCommonSep === -1) lastCommonSep = 0
  }

  let out = ''
  for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
    if (i === fromEnd || from.charCodeAt(i) === CHAR_BACKWARD_SLASH) {
      out += out.length === 0 ? '..' : '\\..'
    }
  }

  toStart += lastCommonSep

  if (out.length > 0) {
    return `${out}${toOrig.substring(toStart, toEnd)}`
  }
  if (toOrig.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) {
    ++toStart
  }
  return toOrig.substring(toStart, toEnd)
}

exports.toNamespacedPath = function toNamespacedPath (path) {
  if (path.length === 0) return path

  const resolvedPath = exports.resolve(path)

  if (resolvedPath.length <= 2) return path

  if (resolvedPath.charCodeAt(0) === CHAR_BACKWARD_SLASH) {
    if (resolvedPath.charCodeAt(1) === CHAR_BACKWARD_SLASH) {
      const code = resolvedPath.charCodeAt(2)
      if (code !== CHAR_QUESTION_MARK && code !== CHAR_DOT) {
        return `\\\\?\\UNC\\${resolvedPath.substring(2)}`
      }
    }
  } else if (
    isWindowsDeviceRoot(resolvedPath.charCodeAt(0)) &&
      resolvedPath.charCodeAt(1) === CHAR_COLON &&
      resolvedPath.charCodeAt(2) === CHAR_BACKWARD_SLASH
  ) {
    return `\\\\?\\${resolvedPath}`
  }

  return path
}

exports.dirname = function dirname (path) {
  const len = path.length
  if (len === 0) return '.'
  let rootEnd = -1
  let offset = 0
  const code = path.charCodeAt(0)

  if (len === 1) {
    return isWindowsPathSeparator(code) ? path : '.'
  }

  if (isWindowsPathSeparator(code)) {
    rootEnd = offset = 1

    if (isWindowsPathSeparator(path.charCodeAt(1))) {
      let j = 2
      let last = j
      while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
        j++
      }
      if (j < len && j !== last) {
        last = j
        while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
          j++
        }
        if (j < len && j !== last) {
          last = j
          while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
            j++
          }
          if (j === len) {
            return path
          }
          if (j !== last) {
            rootEnd = offset = j + 1
          }
        }
      }
    }
  } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
    rootEnd = len > 2 && isWindowsPathSeparator(path.charCodeAt(2)) ? 3 : 2
    offset = rootEnd
  }

  let end = -1
  let matchedSlash = true
  for (let i = len - 1; i >= offset; --i) {
    if (isWindowsPathSeparator(path.charCodeAt(i))) {
      if (!matchedSlash) {
        end = i
        break
      }
    } else {
      matchedSlash = false
    }
  }

  if (end === -1) {
    if (rootEnd === -1) return '.'

    end = rootEnd
  }
  return path.substring(0, end)
}

exports.basename = function basename (path, suffix) {
  let start = 0
  let end = -1
  let matchedSlash = true

  if (path.length >= 2 && isWindowsDeviceRoot(path.charCodeAt(0)) && path.charCodeAt(1) === CHAR_COLON) {
    start = 2
  }

  if (suffix !== undefined && suffix.length > 0 && suffix.length <= path.length) {
    if (suffix === path) return ''
    let extIdx = suffix.length - 1
    let firstNonSlashEnd = -1
    for (let i = path.length - 1; i >= start; --i) {
      const code = path.charCodeAt(i)
      if (isWindowsPathSeparator(code)) {
        if (!matchedSlash) {
          start = i + 1
          break
        }
      } else {
        if (firstNonSlashEnd === -1) {
          matchedSlash = false
          firstNonSlashEnd = i + 1
        }
        if (extIdx >= 0) {
          if (code === suffix.charCodeAt(extIdx)) {
            if (--extIdx === -1) {
              end = i
            }
          } else {
            extIdx = -1
            end = firstNonSlashEnd
          }
        }
      }
    }

    if (start === end) end = firstNonSlashEnd
    else if (end === -1) end = path.length
    return path.substring(start, end)
  }
  for (let i = path.length - 1; i >= start; --i) {
    if (isWindowsPathSeparator(path.charCodeAt(i))) {
      if (!matchedSlash) {
        start = i + 1
        break
      }
    } else if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
  }

  if (end === -1) return ''
  return path.substring(start, end)
}

exports.extname = function extname (path) {
  let start = 0
  let startDot = -1
  let startPart = 0
  let end = -1
  let matchedSlash = true
  let preDotState = 0

  if (path.length >= 2 && path.charCodeAt(1) === CHAR_COLON && isWindowsDeviceRoot(path.charCodeAt(0))) {
    start = startPart = 2
  }

  for (let i = path.length - 1; i >= start; --i) {
    const code = path.charCodeAt(i)
    if (isWindowsPathSeparator(code)) {
      if (!matchedSlash) {
        startPart = i + 1
        break
      }
      continue
    }
    if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
    if (code === CHAR_DOT) {
      if (startDot === -1) startDot = i
      else if (preDotState !== 1) preDotState = 1
    } else if (startDot !== -1) {
      preDotState = -1
    }
  }

  if (startDot === -1 || end === -1 || preDotState === 0 || (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1)) {
    return ''
  }
  return path.substring(startDot, end)
}
{
  "name": "bare-path",
  "version": "3.0.0",
  "description": "Path manipulation library for JavaScript",
  "exports": {
    ".": "./index.js",
    "./package": "./package.json",
    "./posix": "./lib/posix.js",
    "./win32": "./lib/win32.js"
  },
  "files": [
    "index.js",
    "lib",
    "NOTICE"
  ],
  "scripts": {
    "test": "standard && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-path.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-path/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-path#readme",
  "dependencies": {
    "bare-os": "^3.0.1"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "standard": "^17.0.0"
  }
}
module.exports = require.addon()
const EventEmitter = require('bare-events')
const { Duplex } = require('bare-stream')
const binding = require('./binding')
const constants = require('./lib/constants')
const errors = require('./lib/errors')

const defaultReadBufferSize = 65536
const empty = Buffer.alloc(0)

module.exports = exports = class Pipe extends Duplex {
  constructor(path, opts = {}) {
    if (typeof path === 'object' && path !== null) {
      opts = path
      path = null
    }

    const { readBufferSize = defaultReadBufferSize, allowHalfOpen = true, eagerOpen = true } = opts

    super({ eagerOpen })

    this._state = 0

    this._allowHalfOpen = allowHalfOpen

    this._fd = -1
    this._path = null

    this._pendingOpen = null
    this._pendingWrite = null
    this._pendingFinal = null
    this._pendingDestroy = null

    this._buffer = Buffer.alloc(readBufferSize)

    this._handle = binding.init(
      this._buffer,
      this,
      noop,
      this._onconnect,
      this._onwrite,
      this._onfinal,
      this._onread,
      this._onclose
    )

    if (typeof path === 'number') {
      this.open(path)
    } else if (typeof path === 'string') {
      this.connect(path)
    }
  }

  get connecting() {
    return (this._state & constants.state.CONNECTING) !== 0
  }

  get pending() {
    return (this._state & constants.state.CONNECTED) === 0
  }

  get readyState() {
    if (this._state & constants.state.READABLE && this._state & constants.state.WRITABLE) {
      return 'open'
    }

    if (this._state & constants.state.READABLE) {
      return 'readOnly'
    }

    if (this._state & constants.state.WRITABLE) {
      return 'writeOnly'
    }

    return 'opening'
  }

  open(fd, opts = {}, onconnect) {
    if (typeof opts === 'function') {
      onconnect = opts
      opts = {}
    }

    if (typeof fd === 'object' && fd !== null) {
      opts = fd || {}
      fd = opts.fd
    }

    try {
      const status = binding.open(this._handle, fd)

      this._state |= constants.state.CONNECTED
      this._fd = fd

      if (status & binding.READABLE) {
        this._state |= constants.state.READABLE
      } else {
        this.push(null)
      }

      if (status & binding.WRITABLE) {
        this._state |= constants.state.WRITABLE
      } else {
        this.end()
      }

      if (onconnect) this.once('connect', onconnect)

      queueMicrotask(() => this.emit('connect'))
    } catch (err) {
      queueMicrotask(() => {
        if (this._pendingOpen) this._pendingOpen(err)
        else this.destroy(err)
      })
    }

    return this
  }

  connect(path, opts = {}, onconnect) {
    if (this._state & constants.state.CONNECTING || this._state & constants.state.CONNECTED) {
      throw errors.PIPE_ALREADY_CONNECTED('Pipe is already connected')
    }

    this._state |= constants.state.CONNECTING

    if (typeof opts === 'function') {
      onconnect = opts
      opts = {}
    }

    if (typeof path === 'object' && path !== null) {
      opts = path || {}
      path = opts.path
    }

    try {
      binding.connect(this._handle, path)

      this._path = path

      if (onconnect) this.once('connect', onconnect)
    } catch (err) {
      queueMicrotask(() => {
        if (this._pendingOpen) this._pendingOpen(err)
        else this.destroy(err)
      })
    }

    return this
  }

  ref() {
    binding.ref(this._handle)

    return this
  }

  unref() {
    binding.unref(this._handle)

    return this
  }

  _open(cb) {
    if (this._state & constants.state.CONNECTED) return cb(null)

    this._pendingOpen = cb
  }

  _read() {
    if ((this._state & constants.state.READING) === 0) {
      this._state |= constants.state.READING

      binding.resume(this._handle)
    }
  }

  _writev(batch, cb) {
    this._pendingWrite = [cb, batch]

    binding.writev(
      this._handle,
      batch.map(({ chunk }) => chunk)
    )
  }

  _final(cb) {
    if (this._state & constants.state.READABLE && this._state & constants.state.WRITABLE) {
      this._pendingFinal = cb

      binding.end(this._handle)
    } else {
      cb(null)
    }
  }

  _predestroy() {
    if (this._state & constants.state.CLOSING) return
    this._state |= constants.state.CLOSING

    binding.close(this._handle)
  }

  _destroy(err, cb) {
    if (this._state & constants.state.CLOSING) return cb(err)
    this._state |= constants.state.CLOSING

    this._pendingDestroy = cb

    binding.close(this._handle)
  }

  _continueOpen(err) {
    if (this._pendingOpen === null) return
    const cb = this._pendingOpen
    this._pendingOpen = null
    cb(err)
  }

  _continueWrite(err) {
    if (this._pendingWrite === null) return
    const cb = this._pendingWrite[0]
    this._pendingWrite = null
    cb(err)
  }

  _continueFinal(err) {
    if (this._pendingFinal === null) return
    const cb = this._pendingFinal
    this._pendingFinal = null
    cb(err)
  }

  _continueDestroy() {
    if (this._pendingDestroy === null) return
    const cb = this._pendingDestroy
    this._pendingDestroy = null
    cb(null)
  }

  _onconnect(err) {
    if (err) {
      if (this._pendingOpen) this._continueOpen(err)
      else this.destroy(err)
      return
    }

    this._state |= constants.state.CONNECTED | constants.state.READABLE | constants.state.WRITABLE
    this._state &= ~constants.state.CONNECTING
    this._continueOpen()

    this.emit('connect')
  }

  _onread(err, read) {
    if (err) {
      this.destroy(err)
      return
    }

    if (read === 0) {
      this.push(null)
      if (this._allowHalfOpen === false) this.end()
      return
    }

    const copy = Buffer.allocUnsafe(read)
    copy.set(this._buffer.subarray(0, read))

    if (this.push(copy) === false && this.destroying === false) {
      this._state &= ~constants.state.READING

      binding.pause(this._handle)
    }
  }

  _onwrite(err) {
    this._continueWrite(err)
  }

  _onfinal(err) {
    this._continueFinal(err === null || err.code === 'ENOTCONN' ? null : err)
  }

  _onclose() {
    this._continueDestroy()
  }

  _onspawn(readable, writable) {
    this._state |= constants.state.CONNECTED

    if (readable) {
      this._state |= constants.state.READABLE
    } else {
      this.push(null)
    }

    if (writable) {
      this._state |= constants.state.WRITABLE
    } else {
      this.end()
    }

    this._continueOpen()
  }
}

exports.Pipe = exports

exports.pipe = function pipe() {
  return binding.pipe()
}

exports.Server = class PipeServer extends EventEmitter {
  constructor(opts = {}, onconnection) {
    if (typeof opts === 'function') {
      onconnection = opts
      opts = {}
    }

    super()

    const {
      readBufferSize = defaultReadBufferSize,
      allowHalfOpen = true,
      pauseOnConnect = false
    } = opts

    this._state = 0

    this._readBufferSize = readBufferSize
    this._allowHalfOpen = allowHalfOpen
    this._pauseOnConnect = pauseOnConnect

    this._path = null
    this._connections = new Set()

    this._error = null
    this._handle = null

    if (onconnection) this.on('connection', onconnection)
  }

  get listening() {
    return (this._state & constants.state.BOUND) !== 0
  }

  address() {
    if ((this._state & constants.state.BOUND) === 0) {
      return null
    }

    return this._path
  }

  listen(path, backlog = 511, opts = {}, onlistening) {
    if (this._state & constants.state.BINDING || this._state & constants.state.BOUND) {
      throw errors.SERVER_ALREADY_LISTENING('Server is already listening')
    }

    if (this._state & constants.state.CLOSING) {
      throw errors.SERVER_IS_CLOSED('Server is closed')
    }

    this._state |= constants.state.BINDING

    if (typeof backlog === 'function') {
      onlistening = backlog
      backlog = 511
    } else if (typeof opts === 'function') {
      onlistening = opts
      opts = {}
    }

    if (typeof path === 'object' && path !== null) {
      opts = path || {}
      path = opts.path
      backlog = opts.backlog || 511
    }

    this._handle = binding.init(
      empty,
      this,
      this._onconnection,
      noop,
      noop,
      noop,
      noop,
      this._onclose
    )

    if (this._state & constants.state.UNREFED) binding.unref(this._handle)

    try {
      binding.bind(this._handle, path, backlog)

      this._path = path
      this._state |= constants.state.BOUND
      this._state &= ~constants.state.BINDING

      if (onlistening) this.once('listening', onlistening)

      queueMicrotask(() => this.emit('listening'))
    } catch (err) {
      this._error = err

      binding.close(this._handle)
    }

    return this
  }

  close(onclose) {
    if (onclose) this.once('close', onclose)

    if (this._state & constants.state.CLOSING) return
    this._state |= constants.state.CLOSING

    this._closeMaybe()

    return this
  }

  ref() {
    this._state &= ~constants.state.UNREFED

    if (this._handle !== null) binding.ref(this._handle)

    return this
  }

  unref() {
    this._state |= constants.state.UNREFED

    if (this._handle !== null) binding.unref(this._handle)

    return this
  }

  _closeMaybe() {
    if (this._state & constants.state.CLOSING && this._connections.size === 0) {
      if (this._handle !== null) binding.close(this._handle)
      else queueMicrotask(() => this.emit('close'))
    }
  }

  _onconnection(err) {
    if (err) {
      this.emit('error', err)
      return
    }

    if (this._state & constants.state.CLOSING) return

    const pipe = new exports.Pipe({
      readBufferSize: this._readBufferSize,
      allowHalfOpen: this._allowHalfOpen,
      eagerOpen: !this._pauseOnConnect
    })

    try {
      binding.accept(this._handle, pipe._handle)

      pipe._path = this._path
      pipe._state |= constants.state.CONNECTED | constants.state.READABLE | constants.state.WRITABLE

      this._connections.add(pipe)

      pipe.on('close', () => {
        this._connections.delete(pipe)
        this._closeMaybe()
      })

      this.emit('connection', pipe)
    } catch (err) {
      pipe.destroy()

      throw err
    }
  }

  _onclose() {
    const err = this._error

    this._state &= ~constants.state.BINDING
    this._error = null
    this._handle = null

    if (err) this.emit('error', err)
    else this.emit('close')
  }
}

exports.constants = constants
exports.errors = errors

exports.createConnection = function createConnection(path, opts, onconnect) {
  if (typeof opts === 'function') {
    onconnect = opts
    opts = {}
  }

  if (typeof path === 'object' && path !== null) {
    opts = path || {}
    path = opts.path
  }

  return new exports.Pipe(opts).connect(path, opts, onconnect)
}

exports.createServer = function createServer(opts, onconnection) {
  return new exports.Server(opts, onconnection)
}

function noop() {}
module.exports = {
  state: {
    CONNECTING: 0x1,
    CONNECTED: 0x2,
    BINDING: 0x4,
    BOUND: 0x8,
    READING: 0x10,
    CLOSING: 0x20,
    READABLE: 0x40,
    WRITABLE: 0x80,
    UNREFED: 0x100
  }
}
module.exports = class PipeError extends Error {
  constructor(msg, fn = PipeError, code = fn.name) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'PipeError'
  }

  static PIPE_ALREADY_CONNECTED(msg) {
    return new PipeError(msg, PipeError.PIPE_ALREADY_CONNECTED)
  }

  static SERVER_ALREADY_LISTENING(msg) {
    return new PipeError(msg, PipeError.SERVER_ALREADY_LISTENING)
  }

  static SERVER_IS_CLOSED(msg) {
    return new PipeError(msg, PipeError.SERVER_IS_CLOSED)
  }
}
{
  "name": "bare-pipe",
  "version": "4.1.5",
  "description": "Native I/O pipes for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    },
    "./errors": {
      "types": "./lib/errors.d.ts",
      "default": "./lib/errors.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-pipe.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-pipe/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-pipe#readme",
  "engines": {
    "bare": ">=1.16.0"
  },
  "dependencies": {
    "bare-events": "^2.0.0",
    "bare-stream": "^2.0.0"
  },
  "devDependencies": {
    "bare-path": "^3.0.0",
    "brittle": "^3.2.1",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  }
}
const abort = require('bare-abort')
const EventEmitter = require('bare-events')
const Signal = require('bare-signals')
const os = require('bare-os')
const env = require('bare-env')
const hrtime = require('bare-hrtime')
const stdio = require('bare-stdio')

class Process extends EventEmitter {
  constructor() {
    super()

    this._startTime = hrtime.bigint()

    EventEmitter.forward(Bare, this, [
      'uncaughtException',
      'unhandledRejection',
      'beforeExit',
      'exit',
      'suspend',
      'wakeup',
      'idle',
      'resume'
    ])

    const signals = new Signal.Emitter()

    signals.unref()

    EventEmitter.forward(signals, this, Object.keys(os.constants.signals))
  }

  get stdin() {
    return stdio.in
  }

  get stdout() {
    return stdio.out
  }

  get stderr() {
    return stdio.err
  }

  get platform() {
    return os.platform()
  }

  get arch() {
    return os.arch()
  }

  get title() {
    return os.getProcessTitle()
  }

  set title(title) {
    os.setProcessTitle(title)
  }

  get pid() {
    return os.pid()
  }

  get ppid() {
    return os.ppid()
  }

  get argv() {
    return Bare.argv
  }

  get execPath() {
    return os.execPath()
  }

  get exitCode() {
    return Bare.exitCode
  }

  set exitCode(code) {
    Bare.exitCode = code
  }

  get version() {
    return Bare.version
  }

  get versions() {
    return Bare.versions
  }

  get env() {
    return env
  }

  get hrtime() {
    return hrtime
  }

  abort() {
    abort()
  }

  exit(code) {
    Bare.exit(code)
  }

  suspend() {
    Bare.suspend()
  }

  resume() {
    Bare.resume()
  }

  cwd() {
    return os.cwd()
  }

  chdir(directory) {
    os.chdir(directory)
  }

  kill(pid, signal) {
    os.kill(pid, signal)
  }

  uptime() {
    return Number(hrtime.bigint() - this._startTime) / 1e9
  }

  cpuUsage(previous) {
    return os.cpuUsage(previous)
  }

  threadCpuUsage(previous) {
    return os.threadCpuUsage(previous)
  }

  resourceUsage() {
    return os.resourceUsage()
  }

  availableMemory() {
    return os.availableMemory()
  }

  constrainedMemory() {
    return os.constrainedMemory()
  }

  memoryUsage() {
    return os.memoryUsage()
  }

  nextTick(cb, ...args) {
    queueMicrotask(cb.bind(null, ...args))
  }

  [Symbol.for('bare.inspect')]() {
    return {
      __proto__: { constructor: Process },

      platform: this.platform,
      arch: this.arch,
      title: this.title,
      pid: this.pid,
      ppid: this.ppid,
      argv: this.argv,
      execPath: this.execPath,
      exitCode: this.exitCode,
      version: this.version,
      versions: this.versions,
      env: this.env
    }
  }
}

module.exports = new Process()
{
  "name": "bare-process",
  "version": "4.4.1",
  "description": "Node.js-compatible process control for Bare",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "global.js",
    "global.d.ts"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-process.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-process/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-process#readme",
  "dependencies": {
    "bare-abort": "^2.0.13",
    "bare-env": "^3.0.0",
    "bare-events": "^2.3.1",
    "bare-hrtime": "^2.0.0",
    "bare-os": "^3.7.1",
    "bare-signals": "^4.0.0",
    "bare-stdio": "^1.0.1"
  },
  "devDependencies": {
    "brittle": "^3.2.1",
    "lunte": "^1.6.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = require.addon()
const EventEmitter = require('bare-events')
const os = require('bare-os')
const binding = require('./binding')
const errors = require('./lib/errors')

const signals = os.constants.signals

module.exports = exports = class Signal extends EventEmitter {
  constructor(signum) {
    super()

    if (typeof signum === 'string') {
      if (signum in signals === false) {
        throw errors.UNKNOWN_SIGNAL(`Unknown signal '${signum}'`)
      }

      signum = signals[signum]
    }

    this._signum = signum
    this._closing = null
    this._handle = binding.init(this, this._onsignal, this._onclose)
  }

  start() {
    if (this._closing) throw errors.SIGNAL_CLOSED('Signal is closed')
    binding.start(this._handle, this._signum)
    return this
  }

  stop() {
    if (this._closing) return this
    binding.stop(this._handle)
    return this
  }

  ref() {
    if (this._closing) return this
    binding.ref(this._handle)
    return this
  }

  unref() {
    if (this._closing) return this
    binding.unref(this._handle)
    return this
  }

  close() {
    if (this._closing) return this._closing
    this._closing = EventEmitter.once(this, 'close')

    binding.close(this._handle)

    return this._closing
  }

  _onsignal() {
    this.emit('signal', this._signum)
  }

  _onclose() {
    this._handle = null

    this.emit('close')
  }

  static send(signum, pid = os.pid()) {
    os.kill(pid, signum)
  }
}

exports.Emitter = require('./lib/emitter')

exports.constants = signals
exports.errors = errors
const EventEmitter = require('bare-events')
const Signal = require('..')

module.exports = class SignalEmitter extends EventEmitter {
  constructor() {
    super()

    this._signals = new Map()
    this._unrefed = false

    this.on('newListener', this._onnewlistener).on(
      'removeListener',
      this._onremovelistener
    )
  }

  ref() {
    this._unrefed = false
    for (const signal of this._signals.values()) signal.ref()
    return this
  }

  unref() {
    this._unrefed = true
    for (const signal of this._signals.values()) signal.unref()
    return this
  }

  _onnewlistener(name) {
    if (name === 'newListener' || name === 'removeListener') return

    if (this.listenerCount(name) === 0) {
      const signal = new Signal(name)

      signal.on('signal', this._onsignal.bind(this, name)).start()

      if (this._unrefed) signal.unref()

      this._signals.set(name, signal)
    }
  }

  _onremovelistener(name) {
    if (name === 'newListener' || name === 'removeListener') return

    if (this.listenerCount(name) === 0) {
      const signal = this._signals.get(name)

      if (this._unrefed) signal.ref()

      signal.close()

      this._signals.delete(name)
    }
  }

  _onsignal(name) {
    this.emit(name, name, Signal.constants[name])
  }
}
module.exports = class SignalError extends Error {
  constructor(msg, fn = SignalError, code = fn.name) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'SignalError'
  }

  static UNKNOWN_SIGNAL(msg) {
    return new SignalError(msg, SignalError.UNKNOWN_SIGNAL)
  }

  static SIGNAL_CLOSED(msg) {
    return new SignalError(msg, SignalError.SIGNAL_CLOSED)
  }
}
{
  "name": "bare-signals",
  "version": "4.2.0",
  "description": "Native signal handling for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./errors": "./lib/errors.js",
    "./emitter": "./lib/emitter.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-signals.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-signals/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-signals#readme",
  "engines": {
    "bare": ">=1.7.0"
  },
  "dependencies": {
    "bare-events": "^2.5.3",
    "bare-os": "^3.3.1"
  },
  "devDependencies": {
    "brittle": "^3.2.1",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
module.exports = require.addon()
const fs = require('bare-fs')
const tty = require('bare-tty')
const Pipe = require('bare-pipe')
const binding = require('./binding')

const { TTY, NAMED_PIPE } = binding

class IO {
  constructor() {
    this._in = null
    this._out = null
    this._err = null
  }

  get in() {
    if (this._in === null) {
      switch (binding.guessType(0)) {
        case TTY:
          this._in = new tty.ReadStream(0)
          break
        case NAMED_PIPE:
          this._in = new Pipe(0, { eagerOpen: false })
          break
        default:
          this._in = fs.createReadStream(null, { fd: 0, eagerOpen: false })
      }
    }

    return this._in
  }

  get out() {
    if (this._out === null) {
      switch (binding.guessType(1)) {
        case TTY:
          this._out = new tty.WriteStream(1)
          break
        case NAMED_PIPE:
          this._out = new Pipe(1, { eagerOpen: false })
          this._out.unref()
          break
        default:
          this._out = fs.createWriteStream(null, { fd: 1, eagerOpen: false })
      }
    }

    return this._out
  }

  get err() {
    if (this._err === null) {
      switch (binding.guessType(2)) {
        case TTY:
          this._err = new tty.WriteStream(2)
          break
        case NAMED_PIPE:
          this._err = new Pipe(2, { eagerOpen: false })
          this._err.unref()
          break
        default:
          this._err = fs.createWriteStream(null, { fd: 2, eagerOpen: false })
      }
    }

    return this._err
  }
}

module.exports = new IO()
{
  "name": "bare-stdio",
  "version": "1.0.2",
  "description": "Standard input/output streams for Bare",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./constants": "./lib/constants.js",
    "./errors": "./lib/errors.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-stdio.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-stdio/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-stdio#readme",
  "dependencies": {
    "bare-fs": "^4.5.2",
    "bare-pipe": "^4.1.5",
    "bare-tty": "^5.0.3"
  },
  "devDependencies": {
    "bare-os": "^3.6.2",
    "bare-path": "^3.0.0",
    "bare-subprocess": "^3.1.4",
    "brittle": "^3.19.1",
    "cmake-bare": "^1.7.7",
    "lunte": "^1.4.0",
    "prettier": "^3.8.1",
    "prettier-config-holepunch": "^2.0.0",
    "tt-native": "^1.1.1"
  }
}
const stream = require('streamx')
const { ReadableStream, WritableStream } = require('./web')

const defaultEncoding = 'utf8'

module.exports = exports = stream.Stream

exports.pipeline = stream.pipeline

exports.isStream = stream.isStream
exports.isEnding = stream.isEnding
exports.isEnded = stream.isEnded
exports.isFinishing = stream.isFinishing
exports.isFinished = stream.isFinished
exports.isDisturbed = stream.isDisturbed

exports.isErrored = function isErrored(stream) {
  return exports.getStreamError(stream) !== null
}

exports.isReadable = function isReadable(stream) {
  return stream.readable && !stream.destroying && !exports.isEnded(stream)
}

exports.isWritable = function isWritable(stream) {
  return stream.writable && !stream.destroying && !exports.isFinishing(stream)
}

exports.getStreamError = stream.getStreamError

exports.addAbortSignal = function addAbortSignal(signal, stream) {
  function onAbort() {
    stream.destroy(signal.reason)
  }

  if (signal.aborted) onAbort()
  else signal.addEventListener('abort', onAbort)

  return stream
}

exports.Stream = exports

exports.Readable = class Readable extends stream.Readable {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthReadable: null,
      map: null,
      mapReadable: null
    })

    if (this._construct) this._open = this._construct

    if (this._read !== stream.Readable.prototype._read) {
      this._read = read.bind(this, this._read)
    }

    if (this._destroy !== stream.Stream.prototype._destroy) {
      this._destroy = destroy.bind(this, this._destroy)
    }
  }

  get closed() {
    return !exports.isReadable(this)
  }

  get errored() {
    return stream.getStreamError(this)
  }

  push(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = Buffer.from(chunk, encoding || defaultEncoding)
    }

    return super.push(chunk)
  }

  unshift(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = Buffer.from(chunk, encoding || defaultEncoding)
    }

    super.unshift(chunk)
  }

  static fromWeb(readableStream, opts = {}) {
    const stream = readableStream._stream

    if (opts.encoding) stream.setEncoding(opts.encoding)
    if (opts.signal) exports.addAbortSignal(opts.signal, stream)

    return stream
  }

  static toWeb(readable, opts = {}) {
    return new ReadableStream(readable, opts.strategy)
  }

  async [Symbol.asyncDispose]() {
    if (!this.destroyed) this.destroy()

    await new Promise((resolve) => exports.finished(this, resolve))
  }
}

exports.Writable = class Writable extends stream.Writable {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthWritable,
      map: null,
      mapWritable: null
    })

    if (this._construct) this._open = this._construct

    if (this._write !== stream.Writable.prototype._write) {
      this._write = write.bind(this, this._write)
    }

    if (this._destroy !== stream.Stream.prototype._destroy) {
      this._destroy = destroy.bind(this, this._destroy)
    }
  }

  get closed() {
    return !exports.isWritable(this)
  }

  get errored() {
    return stream.getStreamError(this)
  }

  write(chunk, encoding, cb) {
    if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = Buffer.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result = super.write({ chunk, encoding })

    if (cb) stream.Writable.drained(this).then(() => cb(null), cb)

    return result
  }

  end(chunk, encoding, cb) {
    if (typeof chunk === 'function') {
      cb = chunk
      chunk = null
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = Buffer.from(chunk, encoding || defaultEncoding)
    } else {
      encoding = 'buffer'
    }

    const result =
      chunk !== undefined && chunk !== null ? super.end({ chunk, encoding }) : super.end()

    if (cb) this.once('finish', () => cb(null))

    return result
  }

  static fromWeb(writableStream, opts = {}) {
    const stream = writableStream._stream

    if (opts.signal) exports.addAbortSignal(opts.signal, stream)

    return stream
  }

  static toWeb(writable) {
    return new WritableStream(writable)
  }

  async [Symbol.asyncDispose]() {
    if (!this.destroyed) this.destroy()

    await new Promise((resolve) => exports.finished(this, resolve))
  }
}

exports.Duplex = class Duplex extends stream.Duplex {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthReadable: null,
      byteLengthWritable,
      map: null,
      mapReadable: null,
      mapWritable: null
    })

    if (this._construct) this._open = this._construct

    if (this._read !== stream.Readable.prototype._read) {
      this._read = read.bind(this, this._read)
    }

    if (this._write !== stream.Duplex.prototype._write) {
      this._write = write.bind(this, this._write)
    }

    if (this._destroy !== stream.Stream.prototype._destroy) {
      this._destroy = destroy.bind(this, this._destroy)
    }
  }

  push(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = Buffer.from(chunk, encoding || defaultEncoding)
    }

    return super.push(chunk)
  }

  unshift(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = Buffer.from(chunk, encoding || defaultEncoding)
    }

    super.unshift(chunk)
  }

  write(chunk, encoding, cb) {
    if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = Buffer.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result = super.write({ chunk, encoding })

    if (cb) stream.Writable.drained(this).then(() => cb(null), cb)

    return result
  }

  end(chunk, encoding, cb) {
    if (typeof chunk === 'function') {
      cb = chunk
      chunk = null
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = Buffer.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result =
      chunk !== undefined && chunk !== null ? super.end({ chunk, encoding }) : super.end()

    if (cb) this.once('finish', () => cb(null))

    return result
  }

  static fromWeb({ readable: readableStream, writable: writableStream }, opts) {
    const readable = exports.Readable.fromWeb(readableStream, opts)
    const writable = exports.Writable.fromWeb(writableStream, opts)

    const duplex = new exports.Duplex({
      write(data, encoding, cb) {
        writable.write(data, encoding, cb)
      }
    })

    readable
      .on('data', (data) => duplex.push(data))
      .on('end', () => duplex.push(null))
      .on('error', (err) => duplex.destroy(err))

    writable.on('finish', () => duplex.end()).on('error', (err) => duplex.destroy(err))

    return duplex
  }

  static toWeb(duplex) {
    const readableStream = exports.Readable.toWeb(duplex)
    const writableStream = exports.Writable.toWeb(duplex)

    return { readable: readableStream, writable: writableStream }
  }
}

class DuplexSide extends exports.Duplex {
  constructor(opts) {
    super(opts)

    this._otherSide = null
    this._cb = null
  }

  _read() {
    const cb = this._cb
    if (!cb) return

    this._cb = null
    cb()
  }

  _write(chunk, encoding, cb) {
    this._otherSide.push(chunk, encoding)
    this._otherSide._cb = cb
  }

  _final(cb) {
    this._otherSide.on('end', cb)
    this._otherSide.push(null)
  }
}

exports.duplexPair = function duplexPair(opts) {
  const sideA = new DuplexSide(opts)
  const sideB = new DuplexSide(opts)

  sideA._otherSide = sideB
  sideB._otherSide = sideA

  return [sideA, sideB]
}

exports.Transform = class Transform extends stream.Transform {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthReadable: null,
      byteLengthWritable,
      map: null,
      mapReadable: null,
      mapWritable: null
    })

    if (this._transform !== stream.Transform.prototype._transform) {
      this._transform = transform.bind(this, this._transform)
    } else {
      this._transform = passthrough
    }
  }

  push(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = Buffer.from(chunk, encoding || defaultEncoding)
    }

    return super.push(chunk)
  }

  unshift(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = Buffer.from(chunk, encoding || defaultEncoding)
    }

    super.unshift(chunk)
  }

  write(chunk, encoding, cb) {
    if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = Buffer.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result = super.write({ chunk, encoding })

    if (cb) stream.Writable.drained(this).then(() => cb(null), cb)

    return result
  }

  end(chunk, encoding, cb) {
    if (typeof chunk === 'function') {
      cb = chunk
      chunk = null
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = Buffer.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result =
      chunk !== undefined && chunk !== null ? super.end({ chunk, encoding }) : super.end()

    if (cb) this.once('finish', () => cb(null))

    return result
  }
}

exports.PassThrough = class PassThrough extends exports.Transform {}

exports.finished = function finished(stream, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (!opts) opts = {}

  const { cleanup = false } = opts

  const done = () => {
    cb(exports.getStreamError(stream, { all: true }))

    if (cleanup) detach()
  }

  const detach = () => {
    stream.off('close', done)
    stream.off('error', noop)
  }

  if (stream.destroyed) {
    done()
  } else {
    stream.on('close', done)
    stream.on('error', noop)
  }

  return detach
}

function read(read, cb) {
  read.call(this, 65536)

  cb(null)
}

function write(write, data, cb) {
  write.call(this, data.chunk, data.encoding, cb)
}

function transform(transform, data, cb) {
  transform.call(this, data.chunk, data.encoding, cb)
}

function destroy(destroy, cb) {
  destroy.call(this, exports.getStreamError(this), cb)
}

function passthrough(data, cb) {
  cb(null, data.chunk)
}

function byteLengthWritable(data) {
  return data.chunk.byteLength
}

function noop() {}
{
  "name": "bare-stream",
  "version": "2.13.1",
  "description": "Streaming data for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./promises": "./promises.js",
    "./web": {
      "types": "./web.d.ts",
      "default": "./web.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "promises.js",
    "web.js",
    "web.d.ts",
    "global.js",
    "global.d.ts"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-stream.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-stream/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-stream#readme",
  "dependencies": {
    "streamx": "^2.25.0",
    "teex": "^1.0.1"
  },
  "devDependencies": {
    "bare-abort-controller": "^1.1.0",
    "bare-buffer": "^3.0.0",
    "bare-events": "^2.5.4",
    "brittle": "^3.5.2",
    "lunte": "^1.6.0",
    "prettier": "^3.3.3",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "bare-abort-controller": "*",
    "bare-buffer": "*",
    "bare-events": "*"
  },
  "peerDependenciesMeta": {
    "bare-abort-controller": {
      "optional": true
    },
    "bare-buffer": {
      "optional": true
    },
    "bare-events": {
      "optional": true
    }
  }
}
const { Readable, Writable, Transform, getStreamError, isStreamx, isDisturbed } = require('streamx')
const tee = require('teex')

const readableKind = Symbol.for('bare.stream.readable.kind')
const writableKind = Symbol.for('bare.stream.writable.kind')
const transformKind = Symbol.for('bare.stream.transform.kind')

// https://streams.spec.whatwg.org/#readablestreamdefaultreader
exports.ReadableStreamDefaultReader = class ReadableStreamDefaultReader {
  constructor(stream) {
    this._stream = stream
    this._stream._stream.once('close', onclose).once('error', onerror)

    const closed = Promise.withResolvers()

    // Avoid unhandled exceptions
    closed.promise.catch(noop)

    this._closed = closed

    function onclose() {
      closed.resolve()
    }

    function onerror(err) {
      closed.reject(err)
    }
  }

  get closed() {
    return this._closed.promise
  }

  read() {
    const stream = this._stream._stream

    return new Promise((resolve, reject) => {
      const err = getStreamError(stream)

      if (err) return reject(err)

      if (stream.destroyed) {
        return resolve({ value: undefined, done: true })
      }

      const value = stream.read()

      if (value !== null) {
        return resolve({ value, done: false })
      }

      stream.once('readable', onreadable).once('close', onclose).once('error', onerror)

      function onreadable() {
        const value = stream.read()

        ondone(null, value === null ? { value: undefined, done: true } : { value, done: false })
      }

      function onclose() {
        ondone(null, { value: undefined, done: true })
      }

      function onerror(err) {
        ondone(err, null)
      }

      function ondone(err, value) {
        stream.off('readable', onreadable).off('close', onclose).off('error', onerror)

        if (err) reject(err)
        else resolve(value)
      }
    })
  }

  releaseLock() {
    this._closed.reject(new TypeError('Reader was released'))
    this._stream._releaseLock()
    this._stream = null
  }

  cancel(reason = new TypeError('Stream was cancelled')) {
    const stream = this._stream._stream

    if (stream.destroyed) return Promise.resolve()

    return new Promise((resolve) =>
      stream.once('close', resolve).once('error', noop).destroy(reason)
    )
  }
}

// https://streams.spec.whatwg.org/#readablestreamdefaultcontroller
exports.ReadableStreamDefaultController = class ReadableStreamDefaultController {
  constructor(stream) {
    this._stream = stream
  }

  get desiredSize() {
    const stream = this._stream._stream

    return stream._readableState.highWaterMark - stream._readableState.buffered
  }

  enqueue(data) {
    this._stream._stream.push(data)
  }

  close() {
    this._stream._stream.push(null)
  }

  error(err) {
    this._stream._stream.destroy(err)
  }
}

// https://streams.spec.whatwg.org/#readablestream
class ReadableStream {
  static get [readableKind]() {
    return 0 // Compatibility version
  }

  static from(iterable) {
    return new ReadableStream(Readable.from(iterable))
  }

  constructor(underlyingSource = {}, queuingStrategy) {
    if (isStreamx(underlyingSource)) {
      this._stream = underlyingSource
    } else {
      if (queuingStrategy === undefined) {
        queuingStrategy = new exports.CountQueuingStrategy()
      }

      const { start, pull, cancel } = underlyingSource
      const { highWaterMark = 1, size = defaultSize } = queuingStrategy

      this._stream = new Readable({ highWaterMark, byteLength: size })

      const controller = new exports.ReadableStreamDefaultController(this)

      try {
        let starting = Promise.resolve()

        if (start) starting = forwardError(start.call(this, controller), controller)

        if (pull) {
          this._stream._read = this._read.bind(this, starting, pull.bind(this, controller))
        }

        if (cancel) {
          this._stream.once('error', cancel.bind(this))
        }
      } catch (err) {
        controller.error(err)
      }
    }

    this._reader = null
  }

  get [readableKind]() {
    return ReadableStream[readableKind]
  }

  get locked() {
    return this._reader !== null
  }

  getReader() {
    if (this.locked) throw new TypeError('Stream is locked')

    this._reader = new exports.ReadableStreamDefaultReader(this)

    return this._reader
  }

  cancel(reason = new TypeError('Stream was cancelled')) {
    const stream = this._stream

    if (stream.destroyed) return Promise.resolve()

    if (this.locked) return Promise.reject(new TypeError('Stream is locked'))

    return new Promise((resolve) =>
      stream.once('close', resolve).once('error', noop).destroy(reason)
    )
  }

  tee() {
    const [a, b] = tee(this._stream)

    return [new ReadableStream(a), new ReadableStream(b)]
  }

  pipeTo(destination) {
    return new Promise((resolve, reject) =>
      this._stream.pipe(destination._stream, (err) => {
        err ? reject(err) : resolve()
      })
    )
  }

  [Symbol.asyncIterator]() {
    return this._stream[Symbol.asyncIterator]()
  }

  _releaseLock() {
    this._reader = null
  }

  async _read(starting, pull, cb) {
    await starting

    let err = null
    try {
      await pull()
    } catch (e) {
      err = e
    }
    cb(err)
  }
}

function defaultSize() {
  return 1
}

exports.ReadableStream = ReadableStream

// https://streams.spec.whatwg.org/#countqueuingstrategy
exports.CountQueuingStrategy = class CountQueuingStrategy {
  constructor(opts = {}) {
    const { highWaterMark = 1 } = opts

    this.highWaterMark = highWaterMark
  }

  size(chunk) {
    return 1
  }
}

// https://streams.spec.whatwg.org/#bytelengthqueuingstrategy
exports.ByteLengthQueuingStrategy = class ByteLengthQueuingStrategy {
  constructor(opts = {}) {
    const { highWaterMark = 16384 } = opts

    this.highWaterMark = highWaterMark
  }

  size(chunk) {
    return chunk.byteLength
  }
}

exports.isReadableStream = function isReadableStream(value) {
  if (value instanceof ReadableStream) return true

  return (
    typeof value === 'object' &&
    value !== null &&
    value[readableKind] === ReadableStream[readableKind]
  )
}

// https://streams.spec.whatwg.org/#readablestream-errored
exports.isReadableStreamErrored = function isReadableStreamErrored(stream) {
  return getStreamError(stream._stream) !== null
}

// https://streams.spec.whatwg.org/#is-readable-stream-disturbed
exports.isReadableStreamDisturbed = function isReadableStreamDisturbed(stream) {
  return isDisturbed(stream._stream)
}

// https://streams.spec.whatwg.org/#writablestreamdefaultwriter
exports.WritableStreamDefaultWriter = class WritableStreamDefaultWriter {
  constructor(stream) {
    this._stream = stream
    this._stream._stream.once('close', onclose).once('error', onerror)

    const closed = Promise.withResolvers()

    // Avoid unhandled exceptions
    closed.promise.catch(noop)

    this._closed = closed

    function onclose() {
      closed.resolve()
    }

    function onerror(err) {
      closed.reject(err)
    }
  }

  get desiredSize() {
    const stream = this._stream._stream

    return stream._writableState.highWaterMark - stream._writableState.buffered
  }

  get closed() {
    return this._closed.promise
  }

  get ready() {
    const stream = this._stream._stream

    if (getStreamError(stream)) return Promise.reject()

    return Writable.drained(stream).then()
  }

  async write(chunk) {
    const stream = this._stream._stream

    let err = getStreamError(stream)
    if (err) return Promise.reject(err)

    stream.write(chunk)

    await Writable.drained(stream)

    err = getStreamError(stream)
    if (err) return Promise.reject(err)
  }

  releaseLock() {
    this._closed.reject(new TypeError('Writer was released'))
    this._stream._releaseLock()
    this._stream = null
  }

  close() {
    const stream = this._stream._stream

    if (stream.destroyed) return Promise.resolve()

    return new Promise((resolve) => stream.once('close', resolve).end())
  }

  abort(reason = new TypeError('Stream was aborted')) {
    const stream = this._stream._stream

    if (stream.destroyed) return Promise.resolve()

    return new Promise((resolve) => stream.once('close', resolve).destroy(reason))
  }
}

// https://streams.spec.whatwg.org/#writablestreamdefaultcontroller
exports.WritableStreamDefaultController = class WritableStreamDefaultController {
  constructor(stream) {
    this._stream = stream
  }

  error(err) {
    this._stream._stream.destroy(err)
  }
}

// https://streams.spec.whatwg.org/#writablestream
class WritableStream {
  static get [writableKind]() {
    return 0 // Compatibility version
  }

  constructor(underlyingSink = {}, queuingStrategy = {}) {
    if (isStreamx(underlyingSink)) {
      this._stream = underlyingSink
    } else {
      if (queuingStrategy === undefined) {
        queuingStrategy = new exports.CountQueuingStrategy()
      }

      const { start, write, close, abort } = underlyingSink
      const { highWaterMark = 1, size = defaultSize } = queuingStrategy

      this._stream = new Writable({ highWaterMark, byteLength: size })

      const controller = new exports.WritableStreamDefaultController(this)

      this._controller = controller

      try {
        let starting = Promise.resolve()

        if (start) starting = forwardError(start.call(this, controller), controller)

        if (write) {
          this._stream._write = this._write.bind(this, starting, write.bind(this))
        }

        if (close) {
          this._stream._destroy = this._destroy.bind(this, close.call(this))
        }

        if (abort) {
          this._stream.once('error', abort.bind(this))
        }
      } catch (err) {
        controller.error(err)
      }
    }

    this._writer = null
  }

  get [writableKind]() {
    return WritableStream[writableKind]
  }

  get locked() {
    return this._writer !== null
  }

  getWriter() {
    if (this.locked) throw new TypeError('Stream is locked')

    this._writer = new exports.WritableStreamDefaultWriter(this)

    return this._writer
  }

  abort(reason = new TypeError('Stream was aborted')) {
    if (this._stream.destroyed) return Promise.resolve()

    if (this.locked) return Promise.reject(new TypeError('Stream is locked'))

    return new Promise((resolve) => this._stream.once('close', resolve).destroy(reason))
  }

  close() {
    if (this._stream.destroyed) return Promise.resolve()

    if (this.locked) return Promise.reject(new TypeError('Stream is locked'))

    return new Promise((resolve) => this._stream.once('close', resolve).end())
  }

  _releaseLock() {
    this._writer = null
  }

  async _write(starting, write, data, cb) {
    await starting

    let err = null
    try {
      await write(data, this._controller)
    } catch (e) {
      err = e
    }
    cb(err)
  }

  async _destroy(closing, cb) {
    let err = null
    try {
      await closing
    } catch (e) {
      err = e
    }
    cb(err)
  }
}

exports.WritableStream = WritableStream

exports.isWritableStream = function isWritableStream(value) {
  if (value instanceof WritableStream) return true

  return (
    typeof value === 'object' &&
    value !== null &&
    value[writableKind] === WritableStream[writableKind]
  )
}

// https://streams.spec.whatwg.org/#transformstreamdefaultcontroller
exports.TransformStreamDefaultController = class TransformStreamDefaultController {
  constructor(stream) {
    this._stream = stream
  }

  get desiredSize() {
    const stream = this._stream._stream

    return stream._readableState.highWaterMark - stream._readableState.buffered
  }

  enqueue(data) {
    this._stream._stream.push(data)
  }

  error(err) {
    this._stream._stream.destroy(err)
  }

  terminate() {
    const stream = this._stream._stream

    stream.push(null)
    stream.destroy(new TypeError('Stream has been terminated'))
  }
}

// https://streams.spec.whatwg.org/#transformstream
class TransformStream {
  static get [transformKind]() {
    return 0 // Compatibility version
  }

  constructor(transformer = {}, writableStrategy = {}, readableStrategy = {}) {
    if (isStreamx(transformer)) {
      this._stream = transformer
    } else {
      const { start, transform, flush } = transformer

      this._stream = new Transform({ ...writableStrategy, ...readableStrategy })

      const controller = new exports.TransformStreamDefaultController(this)

      this._controller = controller

      try {
        let starting = Promise.resolve()

        if (start) starting = forwardError(start.call(this, controller), controller)

        if (transform) {
          this._stream._transform = this._transform.bind(this, starting, transform.bind(this))
        }

        if (flush) {
          this._stream._flush = this._flush.bind(this, flush.call(this, this._controller))
        }
      } catch (err) {
        controller.error(err)
      }
    }

    this._writable = new WritableStream(this._stream)
    this._readable = new ReadableStream(this._stream)
  }

  get [transformKind]() {
    return TransformStream[transformKind]
  }

  get writable() {
    return this._writable
  }

  get readable() {
    return this._readable
  }

  async _transform(starting, transform, data, cb) {
    await starting

    let err = null
    try {
      await transform(data, this._controller)
    } catch (e) {
      err = e
    }
    cb(err)
  }

  async _flush(flush, cb) {
    let err = null
    try {
      await flush
    } catch (e) {
      err = e
    }
    cb(err)
  }
}

exports.TransformStream = TransformStream

exports.isTransformStream = function isTransformStream(value) {
  if (value instanceof TransformStream) return true

  return (
    typeof value === 'object' &&
    value !== null &&
    value[transformKind] === TransformStream[transformKind]
  )
}

async function forwardError(promise, controller) {
  try {
    await promise
  } catch (err) {
    controller.error(err)
  }
}

function noop() {}
module.exports = require.addon()
const EventEmitter = require('bare-events')
const { Duplex } = require('bare-stream')
const dns = require('bare-dns')
const binding = require('./binding')
const constants = require('./lib/constants')
const errors = require('./lib/errors')
const ip = require('./lib/ip')

const defaultReadBufferSize = 65536
const empty = Buffer.alloc(0)

exports.Socket = class TCPSocket extends Duplex {
  constructor(opts = {}) {
    const { readBufferSize = defaultReadBufferSize, allowHalfOpen = true, eagerOpen = true } = opts

    super({ eagerOpen })

    this._state = 0

    this._allowHalfOpen = allowHalfOpen

    this._keepAlive = 0
    this._keepAliveInitialDelay = 0
    this._noDelay = 0

    this._localAddress = null
    this._remoteAddress = null

    this._pendingOpen = null
    this._pendingWrite = null
    this._pendingFinal = null
    this._pendingDestroy = null

    this._timer = null
    this._timeout = 0

    this._buffer = Buffer.alloc(readBufferSize)

    this._addresses = null
    this._errors = null

    this._handle = binding.init(
      this._buffer,
      this,
      noop,
      this._onconnect,
      this._onreset,
      this._onread,
      this._onwrite,
      this._onfinal,
      this._onclose
    )
  }

  get connecting() {
    return (this._state & constants.state.CONNECTING) !== 0
  }

  get pending() {
    return (this._state & constants.state.CONNECTED) === 0
  }

  get timeout() {
    return this._timeout || undefined // For Node.js compatibility
  }

  get readyState() {
    if (this._state & constants.state.CONNECTED) {
      return 'open'
    }

    return 'opening'
  }

  get localAddress() {
    if (this._localAddress) return this._localAddress.address
  }

  get localFamily() {
    if (this._localAddress) return `IPv${this._localAddress.family}`
  }

  get localPort() {
    if (this._localAddress) return this._localAddress.port
  }

  get remoteAddress() {
    if (this._remoteAddress) return this._remoteAddress.address
  }

  get remoteFamily() {
    if (this._remoteAddress) return `IPv${this._remoteAddress.family}`
  }

  get remotePort() {
    if (this._remoteAddress) return this._remoteAddress.port
  }

  connect(port, host = 'localhost', opts = {}, onconnect) {
    if (this._state & constants.state.CONNECTING || this._state & constants.state.CONNECTED) {
      throw errors.SOCKET_ALREADY_CONNECTED('Socket is already connected')
    }

    this._state |= constants.state.CONNECTING

    if (typeof host === 'function') {
      onconnect = host
      host = 'localhost'
    } else if (typeof opts === 'function') {
      onconnect = opts
      opts = {}
    }

    let family = 0

    if (typeof port === 'object' && port !== null) {
      opts = port || {}
      port = opts.port || 0
      host = opts.host || 'localhost'
      family = opts.family || 0
    }

    if (!host) host = 'localhost'

    const {
      lookup = dns.lookup,
      hints,
      keepAlive = false,
      keepAliveInitialDelay = 0,
      noDelay = false,
      timeout
    } = opts

    const type = ip.isIP(host)

    if (type === 0) {
      lookup(host, { all: true, family, hints }, (err, addresses) => {
        if (this._state & constants.state.CLOSING) return

        this._state &= ~constants.state.CONNECTING

        if (err || addresses.length === 0) {
          if (!err) {
            err = new Error(`No address found for host "${host}"`)
            err.code = 'ENOTFOUND'
          }

          this.emit('lookup', err, null, 0, host)

          if (this._pendingOpen) this._continueOpen(err)
          else this.destroy(err)
          return
        }

        for (const { address, family } of addresses) {
          this.emit('lookup', null, address, family, host)
        }

        const [{ address, family }, ...rest] = addresses

        if (rest.length > 0) {
          this._addresses = rest.map(({ address, family }) => [
            port,
            address,
            { ...opts, family },
            onconnect
          ])

          this._errors = []
        }

        this.connect(port, address, { ...opts, family }, onconnect)
      })

      return this
    }

    family = type

    try {
      binding.connect(this._handle, port, host, family)

      if (keepAlive) {
        this._keepAlive = keepAlive
        this._keepAliveInitialDelay = keepAliveInitialDelay
      }
      if (noDelay) this._noDelay = noDelay
      if (timeout) this.setTimeout(timeout)

      if (onconnect) this.once('connect', onconnect)
    } catch (err) {
      queueMicrotask(() => {
        if (this._pendingOpen) this._pendingOpen(err)
        else this.destroy(err)
      })
    }

    return this
  }

  setKeepAlive(enable = false, delay = 0) {
    if (typeof enable === 'number') {
      delay = enable
      enable = false
    }

    delay = Math.floor(delay / 1000)

    if (delay === 0) enable = false

    binding.keepalive(this._handle, enable, delay)

    return this
  }

  setNoDelay(enable = true) {
    binding.nodelay(this._handle, enable)

    return this
  }

  setTimeout(ms, ontimeout) {
    if (ms === 0) {
      clearTimeout(this._timer)

      this._timer = null
    } else {
      if (ontimeout) this.once('timeout', ontimeout)

      this._timer = setTimeout(() => this.emit('timeout'), ms)
      this._timer.unref()
    }

    this._timeout = ms

    return this
  }

  ref() {
    binding.ref(this._handle)

    return this
  }

  unref() {
    binding.unref(this._handle)

    return this
  }

  _open(cb) {
    if (this._state & constants.state.CONNECTED) return cb(null)

    this._pendingOpen = cb
  }

  _read() {
    if ((this._state & constants.state.READING) === 0) {
      this._state |= constants.state.READING

      binding.resume(this._handle)
    }
  }

  _writev(batch, cb) {
    this._pendingWrite = [cb, batch]

    binding.writev(
      this._handle,
      batch.map(({ chunk }) => chunk)
    )
  }

  _final(cb) {
    this._pendingFinal = cb

    binding.end(this._handle)
  }

  _predestroy() {
    if (this._state & constants.state.CLOSING) return
    this._state |= constants.state.CLOSING

    binding.close(this._handle)
  }

  _destroy(err, cb) {
    if (this._state & constants.state.CLOSING) return cb(err)
    this._state |= constants.state.CLOSING

    this._pendingDestroy = cb

    binding.close(this._handle)
  }

  _continueOpen(err) {
    if (this._pendingOpen === null) return
    const cb = this._pendingOpen
    this._pendingOpen = null
    cb(err)
  }

  _continueWrite(err) {
    if (this._pendingWrite === null) return
    const cb = this._pendingWrite[0]
    this._pendingWrite = null
    cb(err)
  }

  _continueFinal(err) {
    if (this._pendingFinal === null) return
    const cb = this._pendingFinal
    this._pendingFinal = null
    cb(err)
  }

  _continueDestroy() {
    if (this._pendingDestroy === null) return
    const cb = this._pendingDestroy
    this._pendingDestroy = null
    cb(null)
  }

  _reset() {
    this._state = 0

    this._localAddress = null
    this._remoteAddress = null

    binding.reset(this._handle)
  }

  _onconnect(err) {
    if (err) {
      if (this._addresses !== null) {
        this._errors.push(err)

        if (this._addresses.length > 0) return this._reset()

        err = this._errors.length === 1 ? this._errors[0] : new AggregateError(this._errors)
      }

      if (this._pendingOpen) this._continueOpen(err)
      else this.destroy(err)
      return
    }

    if (this._keepAlive) this.setKeepAlive(this._keepAlive, this._keepAliveInitialDelay)
    if (this._noDelay) this.setNoDelay()

    this._localAddress = binding.address(this._handle, true)
    this._remoteAddress = binding.address(this._handle, false)

    this._state |= constants.state.CONNECTED
    this._state &= ~constants.state.CONNECTING
    this._continueOpen()

    this.emit('connect')
  }

  _onreset(err) {
    if (err) {
      this._errors.push(err)
      this.destroy(this._errors.length === 1 ? this._errors[0] : new AggregateError(this._errors))
      return
    }

    this.connect(...this._addresses.shift())
  }

  _onread(err, read) {
    if (this._timer) this._timer.refresh()

    if (err) {
      this.destroy(err)
      return
    }

    if (read === 0) {
      this.push(null)
      if (this._allowHalfOpen === false) this.end()
      return
    }

    const copy = Buffer.allocUnsafe(read)
    copy.set(this._buffer.subarray(0, read))

    if (this.push(copy) === false && this.destroying === false) {
      this._state &= ~constants.state.READING

      binding.pause(this._handle)
    }
  }

  _onwrite(err) {
    if (this._timer) this._timer.refresh()

    this._continueWrite(err)
  }

  _onfinal(err) {
    this._continueFinal(err)
  }

  _onclose() {
    clearTimeout(this._timer)

    this._continueOpen()
    this._continueDestroy()
  }
}

exports.Server = class TCPServer extends EventEmitter {
  constructor(opts = {}, onconnection) {
    if (typeof opts === 'function') {
      onconnection = opts
      opts = {}
    }

    super()

    const {
      readBufferSize = defaultReadBufferSize,
      allowHalfOpen = true,
      keepAlive = false,
      keepAliveInitialDelay = 0,
      noDelay = false,
      pauseOnConnect = false
    } = opts

    this._state = 0

    this._readBufferSize = readBufferSize
    this._allowHalfOpen = allowHalfOpen
    this._keepAlive = keepAlive
    this._keepAliveInitialDelay = keepAliveInitialDelay
    this._noDelay = noDelay
    this._pauseOnConnect = pauseOnConnect

    this._address = null
    this._connections = new Set()

    this._error = null
    this._handle = null

    if (onconnection) this.on('connection', onconnection)
  }

  get listening() {
    return (this._state & constants.state.BOUND) !== 0
  }

  get closing() {
    return (this._state & constants.state.CLOSING) !== 0
  }

  get connections() {
    return this._connections
  }

  address() {
    if ((this._state & constants.state.BOUND) === 0) return null

    const { address, family, port } = this._address

    return { address, family: `IPv${family}`, port }
  }

  listen(port = 0, host = 'localhost', backlog = 511, opts = {}, onlistening) {
    if (this._state & constants.state.BINDING || this._state & constants.state.BOUND) {
      throw errors.SERVER_ALREADY_LISTENING('Server is already listening')
    }

    if (this._state & constants.state.CLOSING) {
      throw errors.SERVER_IS_CLOSED('Server is closed')
    }

    this._state |= constants.state.BINDING

    if (typeof port === 'function') {
      onlistening = port
      port = 0
    } else if (typeof host === 'function') {
      onlistening = host
      host = 'localhost'
    } else if (typeof backlog === 'function') {
      onlistening = backlog
      backlog = 511
    } else if (typeof opts === 'function') {
      onlistening = opts
      opts = {}
    }

    let family = 0

    if (typeof port === 'object' && port !== null) {
      opts = port || {}
      port = opts.port || 0
      host = opts.host || 'localhost'
      family = opts.family || 0
      backlog = opts.backlog || 511
    }

    if (!host) host = 'localhost'
    if (!backlog) backlog = 511

    const { lookup = dns.lookup, hints } = opts

    const type = ip.isIP(host)

    if (type === 0) {
      lookup(host, { family, hints }, (err, address, family) => {
        if (this._state & constants.state.CLOSING) return

        this.emit('lookup', err, address, family, host)

        this._state &= ~constants.state.BINDING

        if (err) return this.emit('error', err)

        this.listen(port, address, backlog, { ...opts, family }, onlistening)
      })

      return this
    }

    family = type

    this._handle = binding.init(
      empty,
      this,
      this._onconnection,
      noop,
      noop,
      noop,
      noop,
      noop,
      this._onclose
    )

    if (this._state & constants.state.UNREFED) binding.unref(this._handle)

    try {
      binding.bind(this._handle, port, host, backlog, family)

      this._address = binding.address(this._handle, true)

      this._state |= constants.state.BOUND
      this._state &= ~constants.state.BINDING

      if (onlistening) this.once('listening', onlistening)

      queueMicrotask(() => this.emit('listening'))
    } catch (err) {
      this._error = err

      binding.close(this._handle)
    }

    return this
  }

  close(onclose) {
    if (onclose) this.once('close', onclose)

    if (this._state & constants.state.CLOSING) return this
    this._state |= constants.state.CLOSING

    this._closeMaybe()

    return this
  }

  ref() {
    this._state &= ~constants.state.UNREFED

    if (this._handle !== null) binding.ref(this._handle)

    return this
  }

  unref() {
    this._state |= constants.state.UNREFED

    if (this._handle !== null) binding.unref(this._handle)

    return this
  }

  _closeMaybe() {
    if (this._state & constants.state.CLOSING && this._connections.size === 0) {
      if (this._handle !== null) binding.close(this._handle)
      else queueMicrotask(() => this.emit('close'))
    }
  }

  _onconnection(err) {
    if (err) {
      this.emit('error', err)
      return
    }

    if (this._state & constants.state.CLOSING) return

    const socket = new exports.Socket({
      readBufferSize: this._readBufferSize,
      allowHalfOpen: this._allowHalfOpen,
      eagerOpen: !this._pauseOnConnect
    })

    try {
      binding.accept(this._handle, socket._handle)

      socket._localAddress = binding.address(socket._handle, true)
      socket._remoteAddress = binding.address(socket._handle, false)

      socket._state |= constants.state.CONNECTED

      this._connections.add(socket)

      if (this._keepAlive) socket.setKeepAlive(this._keepAlive, this._keepAliveInitialDelay)
      if (this._noDelay) socket.setNoDelay()

      socket.on('close', () => {
        this._connections.delete(socket)
        this._closeMaybe()
      })

      this.emit('connection', socket)
    } catch (err) {
      socket.destroy()

      this.emit('error', err)
    }
  }

  _onclose() {
    const err = this._error

    this._state &= ~constants.state.BINDING
    this._error = null
    this._handle = null
    this._address = null

    if (err) this.emit('error', err)
    else this.emit('close')
  }
}

exports.constants = constants
exports.errors = errors

exports.isIP = ip.isIP
exports.isIPv4 = ip.isIPv4
exports.isIPv6 = ip.isIPv6

exports.createConnection = function createConnection(port, host, opts, onconnect) {
  if (typeof host === 'function') {
    onconnect = host
    host = 'localhost'
  } else if (typeof opts === 'function') {
    onconnect = opts
    opts = {}
  }

  if (typeof port === 'object' && port !== null) {
    opts = port || {}
    port = opts.port || 0
    host = opts.host || 'localhost'
  }

  return new exports.Socket(opts).connect(port, host, opts, onconnect)
}

// For Node.js compatibility
exports.connect = exports.createConnection

exports.createServer = function createServer(opts, onconnection) {
  return new exports.Server(opts, onconnection)
}

function noop() {}
module.exports = {
  state: {
    CONNECTING: 0x1,
    CONNECTED: 0x2,
    BINDING: 0x4,
    BOUND: 0x8,
    READING: 0x10,
    CLOSING: 0x20,
    UNREFED: 0x40
  }
}
module.exports = class TCPError extends Error {
  constructor(msg, fn = TCPError, code = fn.name) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'TCPError'
  }

  static SOCKET_ALREADY_CONNECTED(msg) {
    return new TCPError(msg, TCPError.SOCKET_ALREADY_CONNECTED)
  }

  static SERVER_ALREADY_LISTENING(msg) {
    return new TCPError(msg, TCPError.SERVER_ALREADY_LISTENING)
  }

  static SERVER_IS_CLOSED(msg) {
    return new TCPError(msg, TCPError.SERVER_IS_CLOSED)
  }

  static INVALID_HOST(msg = 'Unrecognizable host format') {
    return new TCPError(msg, TCPError.INVALID_HOST)
  }
}
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

const v4Seg = '(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])'
const v4Str = `(${v4Seg}[.]){3}${v4Seg}`
const IPv4Pattern = new RegExp(`^${v4Str}$`)

const v6Seg = '(?:[0-9a-fA-F]{1,4})'
const IPv6Pattern = new RegExp(
  '^(' +
    `(?:${v6Seg}:){7}(?:${v6Seg}|:)|` +
    `(?:${v6Seg}:){6}(?:${v4Str}|:${v6Seg}|:)|` +
    `(?:${v6Seg}:){5}(?::${v4Str}|(:${v6Seg}){1,2}|:)|` +
    `(?:${v6Seg}:){4}(?:(:${v6Seg}){0,1}:${v4Str}|(:${v6Seg}){1,3}|:)|` +
    `(?:${v6Seg}:){3}(?:(:${v6Seg}){0,2}:${v4Str}|(:${v6Seg}){1,4}|:)|` +
    `(?:${v6Seg}:){2}(?:(:${v6Seg}){0,3}:${v4Str}|(:${v6Seg}){1,5}|:)|` +
    `(?:${v6Seg}:){1}(?:(:${v6Seg}){0,4}:${v4Str}|(:${v6Seg}){1,6}|:)|` +
    `(?::((?::${v6Seg}){0,5}:${v4Str}|(?::${v6Seg}){1,7}|:))` +
    ')(%[0-9a-zA-Z-.:]{1,})?$'
)

const isIPv4 = (exports.isIPv4 = function isIPv4(host) {
  return IPv4Pattern.test(host)
})

const isIPv6 = (exports.isIPv6 = function isIPv6(host) {
  return IPv6Pattern.test(host)
})

exports.isIP = function isIP(host) {
  if (isIPv4(host)) return 4
  if (isIPv6(host)) return 6
  return 0
}
{
  "name": "bare-tcp",
  "version": "2.2.12",
  "description": "Native TCP sockets for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./constants": "./lib/constants.js",
    "./errors": "./lib/errors.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-tcp.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-tcp/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-tcp#readme",
  "engines": {
    "bare": ">=1.16.0"
  },
  "dependencies": {
    "bare-dns": "^2.0.4",
    "bare-events": "^2.5.4",
    "bare-stream": "^2.6.4"
  },
  "devDependencies": {
    "brittle": "^3.5.0",
    "cmake-bare": "^1.1.6",
    "lunte": "^1.6.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = require.addon()
const { Readable, Writable } = require('bare-stream')
const Signal = require('bare-signals')
const binding = require('./binding')
const constants = require('./lib/constants')

const defaultReadBufferSize = 65536
const empty = Buffer.alloc(0)

exports.ReadStream = class TTYReadStream extends Readable {
  constructor(fd, opts = {}) {
    super()

    const { readBufferSize = defaultReadBufferSize, allowHalfOpen = true } = opts

    this._fd = fd
    this._state = 0
    this._allowHalfOpen = allowHalfOpen
    this._buffer = Buffer.alloc(readBufferSize)

    this._pendingDestroy = null

    this._handle = binding.init(fd, this._buffer, this, noop, this._onread, this._onclose)
  }

  get fd() {
    return this._fd
  }

  get isTTY() {
    return true
  }

  setMode(mode) {
    binding.setMode(this._handle, mode)
    return this
  }

  setRawMode(enabled) {
    return this.setMode(enabled ? constants.mode.RAW : constants.mode.NORMAL)
  }

  _read() {
    if ((this._state & constants.state.READING) === 0) {
      this._state |= constants.state.READING

      binding.resume(this._handle)
    }
  }

  _predestroy() {
    if (this._state & constants.state.CLOSING) return
    this._state |= constants.state.CLOSING

    binding.close(this._handle)
  }

  _destroy(err, cb) {
    if (this._state & constants.state.CLOSING) return cb(err)
    this._state |= constants.state.CLOSING

    this._pendingDestroy = cb

    binding.close(this._handle)
  }

  _continueDestroy() {
    if (this._pendingDestroy === null) return
    const cb = this._pendingDestroy
    this._pendingDestroy = null
    cb(null)
  }

  _onread(err, read) {
    if (err) {
      this.destroy(err)
      return
    }

    if (read === 0) {
      this.push(null)
      if (this._allowHalfOpen === false) this.end()
      return
    }

    const copy = Buffer.allocUnsafe(read)
    copy.set(this._buffer.subarray(0, read))

    if (this.push(copy) === false && this.destroying === false) {
      this._state &= ~constants.state.READING

      binding.pause(this._handle)
    }
  }

  _onclose() {
    this._handle = null

    this._continueDestroy()
  }
}

exports.WriteStream = class TTYWriteStream extends Writable {
  constructor(fd, opts = {}) {
    super()

    this._fd = fd
    this._state = 0
    this._size = null

    this._pendingWrite = null
    this._pendingDestroy = null

    this._handle = binding.init(fd, empty, this, this._onwrite, noop, this._onclose)

    this._size = this.getWindowSize()

    if (TTYWriteStream._streams.size === 0) TTYWriteStream._resize.start()

    TTYWriteStream._streams.add(this)
  }

  get fd() {
    return this._fd
  }

  get isTTY() {
    return true
  }

  get columns() {
    return this._size[0]
  }

  get rows() {
    return this._size[1]
  }

  getWindowSize() {
    return binding.getWindowSize(this._handle)
  }

  _writev(batch, cb) {
    this._pendingWrite = [cb, batch]

    binding.writev(
      this._handle,
      batch.map(({ chunk }) => chunk)
    )
  }

  _predestroy() {
    if (this._state & constants.state.CLOSING) return
    this._state |= constants.state.CLOSING

    binding.close(this._handle)

    TTYWriteStream._streams.delete(this)

    if (TTYWriteStream._streams.size === 0) TTYWriteStream._resize.stop()
  }

  _destroy(err, cb) {
    if (this._state & constants.state.CLOSING) return cb(err)
    this._state |= constants.state.CLOSING

    this._pendingDestroy = cb

    binding.close(this._handle)

    TTYWriteStream._streams.delete(this)

    if (TTYWriteStream._streams.size === 0) TTYWriteStream._resize.stop()
  }

  _continueWrite(err) {
    if (this._pendingWrite === null) return
    const cb = this._pendingWrite[0]
    this._pendingWrite = null
    cb(err)
  }

  _continueDestroy() {
    if (this._pendingDestroy === null) return
    const cb = this._pendingDestroy
    this._pendingDestroy = null
    cb(null)
  }

  _onwrite(err) {
    this._continueWrite(err)
  }

  _onclose() {
    this._handle = null

    this._continueDestroy()
  }

  _onresize() {
    this._size = this.getWindowSize()

    this.emit('resize')
  }

  static _streams = new Set()

  static _resize = new Signal('SIGWINCH')
}

exports.constants = constants

exports.isTTY = binding.isTTY

exports.isatty = exports.isTTY // For Node.js compatibility

exports.WriteStream._resize
  .on('signal', () => {
    for (const stream of exports.WriteStream._streams) {
      stream._onresize()
    }
  })
  .unref()

function noop() {}
const binding = require('../binding')

module.exports = exports = {
  mode: {
    NORMAL: binding.MODE_NORMAL,
    RAW: binding.MODE_RAW,
    IO: binding.MODE_IO || 0
  },

  state: {
    READING: 0x1,
    CLOSING: 0x2
  }
}

/** @deprecated Use `mode.NORMAL` */
exports.MODE_NORMAL = exports.mode.NORMAL
/** @deprecated Use `mode.RAW` */
exports.MODE_RAW = exports.mode.RAW
/** @deprecated Use `mode.IO` */
exports.MODE_IO = exports.mode.IO
{
  "name": "bare-tty",
  "version": "5.1.0",
  "description": "Native TTY streams for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./constants": "./lib/constants.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-tty.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-tty/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-tty#readme",
  "engines": {
    "bare": ">=1.16.0"
  },
  "dependencies": {
    "bare-events": "^2.2.0",
    "bare-signals": "^4.0.0",
    "bare-stream": "^2.0.0"
  },
  "devDependencies": {
    "brittle": "^3.2.1",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = require.addon()
const binding = require('./binding')

const t = binding.constants

class Type {
  constructor(type) {
    this._type = type
  }

  isUndefined() {
    return this._type === t.UNDEFINED
  }

  isNull() {
    return this._type === t.NULL
  }

  isBoolean() {
    return this._type === t.BOOLEAN
  }

  isNumber() {
    return (this._type & 0xff) === t.NUMBER
  }

  isInt32() {
    return (this._type & (0xff | t.INT32)) === (t.NUMBER | t.INT32)
  }

  isUint32() {
    return (this._type & (0xff | t.UINT32)) === (t.NUMBER | t.UINT32)
  }

  isString() {
    return this._type === t.STRING
  }

  isSymbol() {
    return this._type === t.SYMBOL
  }

  isObject() {
    return (this._type & 0xff) === t.OBJECT
  }

  isArray() {
    return this._type === (t.OBJECT | t.ARRAY)
  }

  isArguments() {
    return this._type === (t.OBJECT | t.ARGUMENTS)
  }

  isDate() {
    return this._type === (t.OBJECT | t.DATE)
  }

  isRegExp() {
    return this._type === (t.OBJECT | t.REGEXP)
  }

  isError() {
    return this._type === (t.OBJECT | t.ERROR)
  }

  isPromise() {
    return this._type === (t.OBJECT | t.PROMISE)
  }

  isProxy() {
    return this._type === (t.OBJECT | t.PROXY)
  }

  isGenerator() {
    return this._type === (t.OBJECT | t.GENERATOR)
  }

  isMap() {
    return this._type === (t.OBJECT | t.MAP)
  }

  isSet() {
    return this._type === (t.OBJECT | t.SET)
  }

  isWeakMap() {
    return this._type === (t.OBJECT | t.WEAK_MAP)
  }

  isWeakSet() {
    return this._type === (t.OBJECT | t.WEAK_SET)
  }

  isWeakRef() {
    return this._type === (t.OBJECT | t.WEAK_REF)
  }

  isArrayBuffer() {
    return this._type === (t.OBJECT | t.ARRAYBUFFER)
  }

  isSharedArrayBuffer() {
    return this._type === (t.OBJECT | t.SHAREDARRAYBUFFER)
  }

  isTypedArray() {
    return (this._type & 0xffff) === (t.OBJECT | t.TYPEDARRAY)
  }

  isInt8Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT8ARRAY)
  }

  isUint8Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT8ARRAY)
  }

  isUint8ClampedArray() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT8CLAMPEDARRAY)
  }

  isInt16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT16ARRAY)
  }

  isUint16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT16ARRAY)
  }

  isInt32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT32ARRAY)
  }

  isUint32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT32ARRAY)
  }

  isFloat16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT16ARRAY)
  }

  isFloat32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT32ARRAY)
  }

  isFloat64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT64ARRAY)
  }

  isBigInt64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.BIGINT64ARRAY)
  }

  isBigUint64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.BIGUINT64ARRAY)
  }

  isDataView() {
    return this._type === (t.OBJECT | t.DATAVIEW)
  }

  isModuleNamespace() {
    return this._type === (t.OBJECT | t.MODULE_NAMESPACE)
  }

  isFunction() {
    return (this._type & 0xff) === t.FUNCTION
  }

  isAsyncFunction() {
    return (
      (this._type & (0xff | t.ASYNC_FUNCTION)) ===
      (t.FUNCTION | t.ASYNC_FUNCTION)
    )
  }

  isGeneratorFunction() {
    return (
      (this._type & (0xff | t.GENERATOR_FUNCTION)) ===
      (t.FUNCTION | t.GENERATOR_FUNCTION)
    )
  }

  isExternal() {
    return this._type === t.EXTERNAL
  }

  isBigInt() {
    return this._type === t.BIGINT
  }
}

module.exports = exports = function type(value) {
  switch (typeof value) {
    case 'undefined':
      return new Type(t.UNDEFINED)
    case 'boolean':
      return new Type(t.BOOLEAN)
    case 'number':
      return new Type(
        Number.isSafeInteger(value) ? binding.type(value) : t.NUMBER
      )
    case 'string':
      return new Type(t.STRING)
    case 'symbol':
      return new Type(t.SYMBOL)
    case 'object':
      return new Type(value === null ? t.NULL : binding.type(value))
    case 'function':
      return new Type(binding.type(value))
    case 'bigint':
      return new Type(t.BIGINT)
  }
}

exports.createTag = function createTag(...components) {
  const tag = new Uint32Array(4)
  for (let i = 0; i < 4; i++) tag[i] = components[i] || 0
  return tag
}

exports.addTag = function addTag(object, tag) {
  binding.addTag(object, tag)
}

exports.checkTag = function checkTag(object, tag) {
  return binding.checkTag(object, tag)
}
{
  "name": "bare-type",
  "version": "1.1.0",
  "description": "Cross-realm type predicates for Bare",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-type.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-type/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-type#readme",
  "engines": {
    "bare": ">=1.2.0"
  },
  "devDependencies": {
    "brittle": "^3.4.0",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
module.exports = require.addon()
const path = require('bare-path')
const binding = require('./binding')
const errors = require('./lib/errors')
const URLSearchParams = require('./lib/url-search-params')

const kind = Symbol.for('bare.url.kind')

const isWindows = Bare.platform === 'win32'

class URL {
  static get [kind]() {
    return 0 // Compatibility version
  }

  constructor(input, base, opts = {}) {
    if (arguments.length === 0) throw errors.INVALID_URL()

    input = String(input)

    if (base !== undefined) base = String(base)

    this._components = new Uint32Array(8)

    this._parse(input, base, opts.throw !== false)

    if (this._href) this._params = new URLSearchParams(this.search, this)
  }

  get [kind]() {
    return URL[kind]
  }

  // https://url.spec.whatwg.org/#dom-url-href

  get href() {
    return this._href
  }

  set href(value) {
    this._update(value)

    this._params._parse(this.search)
  }

  // https://url.spec.whatwg.org/#dom-url-protocol

  get protocol() {
    return this._slice(0, this._components[0]) + ':'
  }

  set protocol(value) {
    this._update(this._replace(value.replace(/:+$/, ''), 0, this._components[0]))
  }

  // https://url.spec.whatwg.org/#dom-url-username

  get username() {
    return this._slice(this._components[0] + 3 /* :// */, this._components[1])
  }

  set username(value) {
    if (cannotHaveCredentialsOrPort(this)) {
      return
    }

    if (this.username === '') value += '@'

    this._update(this._replace(value, this._components[0] + 3 /* :// */, this._components[1]))
  }

  // https://url.spec.whatwg.org/#dom-url-password

  get password() {
    return this._href.slice(this._components[1] + 1 /* : */, this._components[2] - 1 /* @ */)
  }

  set password(value) {
    if (cannotHaveCredentialsOrPort(this)) {
      return
    }

    let start = this._components[1] + 1 /* : */
    let end = this._components[2] - 1 /* @ */

    if (this.password === '') {
      value = ':' + value
      start--
    }

    if (this.username === '') {
      value += '@'
      end++
    }

    this._update(this._replace(value, start, end))
  }

  // https://url.spec.whatwg.org/#dom-url-host

  get host() {
    return this._slice(this._components[2], this._components[5])
  }

  set host(value) {
    if (hasOpaquePath(this)) {
      return
    }

    this._update(
      this._replace(value, this._components[2], this._components[value.includes(':') ? 5 : 3])
    )
  }

  // https://url.spec.whatwg.org/#dom-url-hostname

  get hostname() {
    return this._slice(this._components[2], this._components[3])
  }

  set hostname(value) {
    if (hasOpaquePath(this)) {
      return
    }

    this._update(this._replace(value, this._components[2], this._components[3]))
  }

  // https://url.spec.whatwg.org/#dom-url-port

  get port() {
    return this._slice(this._components[3] + 1 /* : */, this._components[5])
  }

  set port(value) {
    if (cannotHaveCredentialsOrPort(this)) {
      return
    }

    let start = this._components[3] + 1 /* : */

    if (this.port === '') {
      value = ':' + value
      start--
    }

    this._update(this._replace(value, start, this._components[5]))
  }

  // https://url.spec.whatwg.org/#dom-url-pathname

  get pathname() {
    return this._slice(this._components[5], this._components[6] - 1 /* ? */)
  }

  set pathname(value) {
    if (hasOpaquePath(this)) {
      return
    }

    if (value[0] !== '/' && value[0] !== '\\') {
      value = '/' + value
    }

    this._update(this._replace(value, this._components[5], this._components[6] - 1 /* ? */))
  }

  // https://url.spec.whatwg.org/#dom-url-search

  get search() {
    return this._slice(this._components[6] - 1 /* ? */, this._components[7] - 1 /* # */)
  }

  set search(value) {
    if (value && value[0] !== '?') value = '?' + value

    this._update(
      this._replace(value, this._components[6] - 1 /* ? */, this._components[7] - 1 /* # */)
    )

    this._params._parse(this.search)
  }

  // https://url.spec.whatwg.org/#dom-url-searchparams

  get searchParams() {
    return this._params
  }

  // https://url.spec.whatwg.org/#dom-url-hash

  get hash() {
    return this._slice(this._components[7] - 1 /* # */)
  }

  set hash(value) {
    if (value && value[0] !== '#') value = '#' + value

    this._update(this._replace(value, this._components[7] - 1 /* # */))
  }

  toString() {
    return this._href
  }

  toJSON() {
    return this._href
  }

  [Symbol.for('bare.inspect')]() {
    return {
      __proto__: { constructor: URL },

      href: this.href,
      protocol: this.protocol,
      username: this.username,
      password: this.password,
      host: this.host,
      hostname: this.hostname,
      port: this.port,
      pathname: this.pathname,
      search: this.search,
      searchParams: this.searchParams,
      hash: this.hash
    }
  }

  _slice(start, end = this._href.length) {
    return this._href.slice(start, end)
  }

  _replace(replacement, start, end = this._href.length) {
    return this._slice(0, start) + replacement + this._slice(end)
  }

  _parse(input, base, shouldThrow) {
    try {
      this._href = binding.parse(
        String(input),
        base ? String(base) : null,
        this._components,
        shouldThrow
      )
    } catch (err) {
      if (err instanceof TypeError) throw err

      throw errors.INVALID_URL(`Invalid URL '${input}'`, input)
    }
  }

  _update(input) {
    try {
      this._parse(input, null, true)
    } catch (err) {
      if (err instanceof TypeError) throw err
    }
  }
}

module.exports = exports = URL

// https://url.spec.whatwg.org/#url-opaque-path
function hasOpaquePath(url) {
  return url.pathname[0] !== '/'
}

// https://url.spec.whatwg.org/#cannot-have-a-username-password-port
function cannotHaveCredentialsOrPort(url) {
  return url.hostname === '' || url.protocol === 'file:'
}

exports.URL = URL
exports.URLSearchParams = URLSearchParams

exports.errors = errors

exports.isURL = function isURL(value) {
  if (value instanceof URL) return true

  return typeof value === 'object' && value !== null && value[kind] === URL[kind]
}

exports.isURLSearchParams = URLSearchParams.isURLSearchParams

// https://url.spec.whatwg.org/#dom-url-parse
exports.parse = function parse(input, base) {
  const url = new URL(input, base, { throw: false })
  return url._href ? url : null
}

// https://url.spec.whatwg.org/#dom-url-canparse
exports.canParse = function canParse(input, base) {
  return binding.canParse(String(input), base ? String(base) : null)
}

exports.fileURLToPath = function fileURLToPath(url) {
  if (typeof url === 'string') {
    url = new URL(url)
  }

  if (url.protocol !== 'file:') {
    throw errors.INVALID_URL_SCHEME('The URL must use the file: protocol')
  }

  if (isWindows) {
    if (/%2f|%5c/i.test(url.pathname)) {
      throw errors.INVALID_FILE_URL_PATH(
        'The file: URL path must not include encoded \\ or / characters'
      )
    }
  } else {
    if (url.hostname) {
      throw errors.INVALID_FILE_URL_HOST("The file: URL host must be 'localhost' or empty")
    }

    if (/%2f/i.test(url.pathname)) {
      throw errors.INVALID_FILE_URL_PATH('The file: URL path must not include encoded / characters')
    }
  }

  const pathname = path.normalize(decodeURIComponent(url.pathname))

  if (isWindows) {
    if (url.hostname) return '\\\\' + url.hostname + pathname

    const letter = pathname.charCodeAt(1) | 0x20

    if (letter < 0x61 /* a */ || letter > 0x7a /* z */ || pathname.charCodeAt(2) !== 0x3a /* : */) {
      throw errors.INVALID_FILE_URL_PATH('The file: URL path must be absolute')
    }

    return pathname.slice(1)
  }

  return pathname
}

exports.pathToFileURL = function pathToFileURL(pathname) {
  let resolved = path.resolve(pathname)

  if (pathname[pathname.length - 1] === '/') {
    resolved += '/'
  } else if (isWindows && pathname[pathname.length - 1] === '\\') {
    resolved += '\\'
  }

  resolved = resolved
    .replaceAll('%', '%25') // Must be first
    .replaceAll('#', '%23')
    .replaceAll('?', '%3f')
    .replaceAll('\n', '%0a')
    .replaceAll('\r', '%0d')
    .replaceAll('\t', '%09')

  if (!isWindows) {
    resolved = resolved.replaceAll('\\', '%5c')
  }

  return new URL('file:' + resolved)
}

exports.format = function format(parts) {
  const { protocol, auth, host, hostname, port, pathname, search, query, hash, slashes } = parts

  let result = ''

  if (typeof protocol === 'string') {
    result += protocol

    if (protocol[protocol.length - 1] !== ':') {
      result += ':'
    }

    if (slashes === true || /https?|ftp|gopher|file/.test(protocol)) {
      result += '//'
    }
  }

  if (typeof auth === 'string') {
    if (host || hostname) result += auth + '@'
  }

  if (typeof host === 'string') result += host
  else {
    result += hostname

    if (port) result += ':' + port
  }

  if (typeof pathname === 'string' && pathname !== '') {
    if (pathname[0] !== '/') result += '/'
    result += pathname
  }

  if (typeof search === 'string') {
    if (search[0] !== '?') result += '?'
    result += search
  } else if (typeof query === 'object' && query !== null) {
    result += '?' + new URLSearchParams(query)
  }

  if (typeof hash === 'string') {
    if (hash[0] !== '#') result += '#'
    result += hash
  }

  return result
}
module.exports = class URLError extends Error {
  constructor(msg, fn = URLError, code = fn.name) {
    super(`${code}: ${msg}`)

    this.code = code

    if (Error.captureStackTrace) Error.captureStackTrace(this, fn)
  }

  get name() {
    return 'URLError'
  }

  static INVALID_URL(msg, input) {
    const err = new URLError(msg, URLError.INVALID_URL)

    err.input = input

    return err
  }

  static INVALID_URL_SCHEME(msg = 'Invalid URL') {
    return new URLError(msg, URLError.INVALID_URL_SCHEME)
  }

  static INVALID_FILE_URL_HOST(msg = 'Invalid file: URL host') {
    return new URLError(msg, URLError.INVALID_FILE_URL_HOST)
  }

  static INVALID_FILE_URL_PATH(msg = 'Invalid file: URL path') {
    return new URLError(msg, URLError.INVALID_FILE_URL_PATH)
  }
}
const kind = Symbol.for('bare.url.search-params.kind')

class URLSearchParams {
  static _urls = new WeakMap()

  static get [kind]() {
    return 0 // Compatibility version
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-urlsearchparams
  constructor(init, url = null) {
    this._params = new Map()

    if (url) URLSearchParams._urls.set(this, url)

    if (typeof init === 'string') {
      this._parse(init)
    } else if (init) {
      for (const [name, value] of typeof init[Symbol.iterator] === 'function'
        ? init
        : Object.entries(init)) {
        this.append(name, value)
      }
    }
  }

  get [kind]() {
    return URLSearchParams[kind]
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-size
  get size() {
    return this._params.length
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-append
  append(name, value = null) {
    if (value === null) return

    let list = this._params.get(name)

    if (list === undefined) {
      list = []
      this._params.set(name, list)
    }

    list.push(value)

    this._update()
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-delete
  delete(name, value = null) {
    if (value === null) this._params.delete(name)
    else {
      let list = this._params.get(name)

      if (list === undefined) return

      list = list.filter((found) => found !== value)

      if (list.length === 0) this._params.delete(name)
      else this._params.set(name, list)
    }

    this._update()
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-get
  get(name) {
    const list = this._params.get(name)

    if (list === undefined) return null

    return list[0]
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-getall
  getAll(name) {
    const list = this._params.get(name)

    if (list === undefined) return []

    return Array.from(list)
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-has
  has(name, value = null) {
    const list = this._params.get(name)

    if (list === undefined) return false

    if (value === null) return true

    return list.includes(value)
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-set
  set(name, value = null) {
    if (value === null) this._params.delete(name)
    else this._params.set(name, [value])

    this._update()
  }

  toString() {
    return this._serialize()
  }

  toJSON() {
    return [...this]
  }

  *[Symbol.iterator]() {
    for (const [name, values] of this._params) {
      for (const value of values) yield [name, value]
    }
  }

  [Symbol.for('bare.inspect')]() {
    const object = {
      __proto__: { constructor: URLSearchParams }
    }

    for (const [name, values] of this._params) {
      if (values.length === 1) object[name] = values[0]
      else object[name] = values
    }

    return object
  }

  // https://url.spec.whatwg.org/#concept-urlsearchparams-update
  _update() {
    const url = URLSearchParams._urls.get(this)

    if (url === undefined) return

    url.search = this._serialize()
  }

  // https://url.spec.whatwg.org/#concept-urlencoded-parser
  _parse(input) {
    if (input[0] === '?') input = input.substring(1)

    this._params = new Map()

    for (let sequence of input.split('&')) {
      if (sequence.length === 0) continue

      sequence = sequence.replace(/\+/g, ' ')

      let i = sequence.indexOf('=')
      if (i === -1) i = sequence.length

      const name = decodeURIComponent(sequence.substring(0, i))
      const value = decodeURIComponent(sequence.substring(i + 1, sequence.length))

      let list = this._params.get(name)

      if (list === undefined) {
        list = []
        this._params.set(name, list)
      }

      list.push(value)
    }
  }

  // https://url.spec.whatwg.org/#concept-urlencoded-serializer
  _serialize() {
    let output = ''

    for (let [name, values] of this._params) {
      name = encodeURIComponent(name)

      for (const value of values) {
        if (output) output += '&'

        output += name + '=' + encodeURIComponent(value)
      }
    }

    return output
  }
}

module.exports = exports = URLSearchParams

exports.isURLSearchParams = function isURLSearchParams(value) {
  if (value instanceof URLSearchParams) return true

  return typeof value === 'object' && value !== null && value[kind] === URLSearchParams[kind]
}
{
  "name": "bare-url",
  "version": "2.4.2",
  "description": "WHATWG URL implementation for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "global.js",
    "global.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-url.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-url/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-url",
  "dependencies": {
    "bare-path": "^3.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "cmake-bare": "^1.1.6",
    "cmake-fetch": "^1.0.0",
    "lunte": "^1.6.0",
    "prettier": "^3.3.3",
    "prettier-config-holepunch": "^2.0.0"
  }
}
const b4a = require('b4a')

function byteLength (size) {
  return Math.ceil(size / 8)
}

function get (buffer, bit) {
  const n = buffer.BYTES_PER_ELEMENT * 8

  const offset = bit & (n - 1)
  const i = (bit - offset) / n

  return (buffer[i] & (1 << offset)) !== 0
}

function set (buffer, bit, value = true) {
  const n = buffer.BYTES_PER_ELEMENT * 8

  const offset = bit & (n - 1)
  const i = (bit - offset) / n
  const mask = 1 << offset

  if (value) {
    if ((buffer[i] & mask) !== 0) return false
  } else {
    if ((buffer[i] & mask) === 0) return false
  }

  buffer[i] ^= mask
  return true
}

function setRange (buffer, start, end, value = true) {
  const n = buffer.BYTES_PER_ELEMENT * 8

  let remaining = end - start
  let offset = start & (n - 1)
  let i = (start - offset) / n

  let changed = false

  while (remaining > 0) {
    const mask = (2 ** Math.min(remaining, n - offset) - 1) << offset

    if (value) {
      if ((buffer[i] & mask) !== mask) {
        buffer[i] |= mask
        changed = true
      }
    } else {
      if ((buffer[i] & mask) !== 0) {
        buffer[i] &= ~mask
        changed = true
      }
    }

    remaining -= n - offset
    offset = 0
    i++
  }

  return changed
}

function fill (buffer, value, start = 0, end = buffer.byteLength * 8) {
  const n = buffer.BYTES_PER_ELEMENT * 8
  let i, j

  {
    const offset = start & (n - 1)
    i = (start - offset) / n

    if (offset !== 0) {
      const mask = (2 ** Math.min(n - offset, end - start) - 1) << offset

      if (value) buffer[i] |= mask
      else buffer[i] &= ~mask

      i++
    }
  }

  {
    const offset = end & (n - 1)
    j = (end - offset) / n

    if (offset !== 0 && j >= i) {
      const mask = (2 ** offset) - 1

      if (value) buffer[j] |= mask
      else buffer[j] &= ~mask
    }
  }

  return buffer.fill(value ? (2 ** n) - 1 : 0, i, j)
}

function toggle (buffer, bit) {
  const n = buffer.BYTES_PER_ELEMENT * 8

  const offset = bit & (n - 1)
  const i = (bit - offset) / n
  const mask = 1 << offset

  buffer[i] ^= mask
  return (buffer[i] & mask) !== 0
}

function remove (buffer, bit) {
  return set(buffer, bit, false)
}

function removeRange (buffer, start, end) {
  return setRange(buffer, start, end, false)
}

function indexOf (buffer, value, position = 0) {
  for (let i = position, n = buffer.byteLength * 8; i < n; i++) {
    if (get(buffer, i) === value) return i
  }

  return -1
}

function lastIndexOf (buffer, value, position = buffer.byteLength * 8 - 1) {
  for (let i = position; i >= 0; i--) {
    if (get(buffer, i) === value) return i
  }

  return -1
}

function of (...bits) {
  return from(bits)
}

function from (bits) {
  const buffer = b4a.alloc(byteLength(bits.length))
  for (let i = 0; i < bits.length; i++) set(buffer, i, bits[i])
  return buffer
}

function * iterator (buffer) {
  for (let i = 0, n = buffer.byteLength * 8; i < n; i++) yield get(buffer, i)
}

module.exports = {
  byteLength,
  get,
  set,
  setRange,
  fill,
  toggle,
  remove,
  removeRange,
  indexOf,
  lastIndexOf,
  of,
  from,
  iterator
}
{
  "name": "bits-to-bytes",
  "version": "1.3.0",
  "description": "Functions for doing bit manipulation of typed arrays",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "scripts": {
    "test": "standard && brittle test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bits-to-bytes.git"
  },
  "author": "Kasper Isager Dalsgarð <kasper@funktionel.co>",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/holepunchto/bits-to-bytes/issues"
  },
  "homepage": "https://github.com/holepunchto/bits-to-bytes#readme",
  "dependencies": {
    "b4a": "^1.5.0"
  },
  "devDependencies": {
    "brittle": "^2.3.1",
    "standard": "^17.0.0"
  }
}
const EventEmitter = require('events')
const Protomux = require('protomux')
const { Readable } = require('streamx')
const sodium = require('sodium-universal')
const b4a = require('b4a')
const c = require('compact-encoding')
const bitfield = require('compact-encoding-bitfield')
const bits = require('bits-to-bytes')
const errors = require('./lib/errors')

exports.Server = class BlindRelayServer extends EventEmitter {
  constructor(opts = {}) {
    super()

    const { createStream } = opts

    this._createStream = createStream
    this._pairing = new Map()
    this._sessions = new Set()
    this.stats = createStats(this)
  }

  get sessions() {
    return this._sessions[Symbol.iterator]()
  }

  accept(stream, opts) {
    const session = new BlindRelaySession(this, stream, opts)

    this._sessions.add(session)
    this.stats.sessions.accepted++

    return session
  }

  async close() {
    const ending = []

    for (const session of this._sessions) {
      ending.push(session.end())
    }

    await Promise.all(ending)

    this._pairing.clear()
  }

  _activePairings() {
    const active = new Set()

    for (const session of this._sessions) {
      for (const token of session._links.keys()) {
        active.add(token)
      }
    }

    return active.size
  }

  _activeStreams() {
    let active = 0

    for (const session of this._sessions) {
      active += session._links.size
    }

    return active
  }
}

class BlindRelaySession extends EventEmitter {
  constructor(server, stream, opts = {}) {
    super()

    const { id, handshake, handshakeEncoding } = opts

    this._server = server
    this._mux = Protomux.from(stream)

    this._channel = this._mux.createChannel({
      protocol: 'blind-relay',
      id,
      handshake: handshake ? handshakeEncoding || c.raw : null,
      onopen: this._onopen.bind(this),
      onclose: this._onclose.bind(this),
      ondestroy: this._ondestroy.bind(this)
    })

    this._pair = this._channel.addMessage({
      encoding: m.pair,
      onmessage: this._onpair.bind(this)
    })

    this._unpair = this._channel.addMessage({
      encoding: m.unpair,
      onmessage: this._onunpair.bind(this)
    })

    this._ending = null
    this._destroyed = false
    this._error = null
    this._pairing = new Set()
    this._links = new Map()

    this._onerror = (err) => {
      this._server.stats.streams.errors++
      this.emit('error', err)
    }

    this._channel.open(handshake)
  }

  get closed() {
    return this._channel.closed
  }

  get mux() {
    return this._mux
  }

  get stream() {
    return this._mux.stream
  }

  _onopen() {
    this._server.stats.sessions.opened++
    this.emit('open')
  }

  _onclose() {
    this._ending = Promise.resolve()

    const err = this._error || errors.CHANNEL_CLOSED()
    this._server.stats.pairings.cancelled += this._pairing.size

    for (const token of this._pairing) {
      this._server._pairing.delete(token.toString('hex'))
    }

    for (const link of this._links.values()) {
      link.destroy(err)
    }

    this._pairing.clear()
    this._links.clear()

    this._server._sessions.delete(this)
    this._server.stats.sessions.closed++

    this.emit('close')
  }

  _ondestroy() {
    this._destroyed = true
    this.emit('destroy')
  }

  _onpair({ isInitiator, token, id: remoteId }) {
    const keyString = token.toString('hex')

    let pair = this._server._pairing.get(keyString)

    if (pair === undefined) {
      pair = new BlindRelayPair(token)
      this._server._pairing.set(keyString, pair)
    } else if (pair.links[+isInitiator]) return

    this._pairing.add(keyString)
    this._server.stats.pairings.requested++

    pair.links[+isInitiator] = new BlindRelayLink(this, isInitiator, remoteId)

    if (!pair.paired) return

    this._server._pairing.delete(keyString)
    this._server.stats.pairings.matched++

    // 1st pass: Create the raw streams needed for each end of the link.
    for (const link of pair.links) {
      link.createStream()
    }

    // 2nd pass: Connect the raw streams and set up handlers.
    for (const link of pair.links) {
      link.remote = pair.remote(link.isInitiator)
      link.activate(keyString)
    }

    // 3rd pass: Let either end of the link know the streams were set up.
    for (const { isInitiator, session, remoteId, stream } of pair.links) {
      session._pair.send({
        isInitiator,
        token,
        id: stream.id,
        seq: 0
      })

      session._endMaybe()

      session.emit('pair', isInitiator, token, stream, remoteId)
    }
  }

  _onunpair({ token }) {
    const keyString = token.toString('hex')

    const pair = this._server._pairing.get(keyString)

    if (pair) {
      for (const link of pair.links) {
        if (link) link.session._pairing.delete(keyString)
      }

      this._server.stats.pairings.cancelled++
      return this._server._pairing.delete(keyString)
    }

    const link = this._links.get(keyString)

    if (link) {
      link.destroyPair(errors.PAIRING_CANCELLED())
      this._server.stats.pairings.cancelled++
    }
  }

  cork() {
    this._channel.cork()
  }

  uncork() {
    this._channel.uncork()
  }

  async end() {
    if (this._ending) return this._ending

    this._ending = EventEmitter.once(this, 'close')
    this._endMaybe()

    return this._ending
  }

  _endMaybe() {
    if (this._ending && this._pairing.size === 0) {
      this._channel.close()
    }
  }

  destroy(err) {
    if (this._destroyed) return
    this._destroyed = true

    this._error = err || errors.CHANNEL_DESTROYED()
    this._channel.close()
  }
}

class BlindRelayPair {
  constructor(token) {
    this.token = token
    this.links = [null, null]
  }

  get paired() {
    return this.links[0] !== null && this.links[1] !== null
  }

  remote(isInitiator) {
    return this.links[isInitiator ? 0 : 1]
  }
}

class BlindRelayLink {
  constructor(session, isInitiator, remoteId) {
    this.session = session
    this.isInitiator = isInitiator
    this.remoteId = remoteId
    this.stream = null
    this.remote = null
    this.keyString = null
    this._onclose = null
  }

  createStream() {
    if (this.stream) return

    this.stream = this.session._server._createStream({
      firewall: this._onfirewall.bind(this)
    })
  }

  activate(keyString) {
    const stream = this.stream

    this.keyString = keyString
    this._onclose = () => {
      if (this.stream !== stream) return

      this.stream = null
      unlink(this)
      this.session._links.delete(keyString)
      this.session._server.stats.streams.closed++
    }

    stream.on('error', this.session._onerror).on('close', this._onclose).relayTo(this.remote.stream)

    this.session._pairing.delete(keyString)
    this.session._links.set(keyString, this)
    this.session._server.stats.streams.opened++
  }

  destroy(err) {
    const stream = this.stream

    if (!stream) return

    this.stream = null

    stream.off('close', this._onclose)
    this._onclose = null

    stream.off('error', this.session._onerror)
    unlink(this)
    this.session._links.delete(this.keyString)
    this.session._server.stats.streams.closed++
    stream.on('error', noop).destroy(err)
  }

  destroyPair(err) {
    const remote = this.remote

    this.destroy(err)
    if (remote) remote.destroy(err)
  }

  _onfirewall(socket, port, host) {
    this.stream.connect(socket, this.remoteId, port, host)

    return false
  }
}

exports.Client = class BlindRelayClient extends EventEmitter {
  static _clients = new WeakMap()

  static from(stream, opts) {
    let client = this._clients.get(stream)
    if (client) return client
    client = new this(stream, opts)
    this._clients.set(stream, client)
    return client
  }

  constructor(stream, opts = {}) {
    super()

    const { id, handshake, handshakeEncoding } = opts

    this._mux = Protomux.from(stream)

    this._channel = this._mux.createChannel({
      protocol: 'blind-relay',
      id,
      handshake: handshake ? handshakeEncoding || c.raw : null,
      onopen: this._onopen.bind(this),
      onclose: this._onclose.bind(this),
      ondestroy: this._ondestroy.bind(this)
    })

    this._pair = this._channel.addMessage({
      encoding: m.pair,
      onmessage: this._onpair.bind(this)
    })

    this._unpair = this._channel.addMessage({
      encoding: m.unpair
    })

    this._ending = false
    this._destroyed = false
    this._error = null
    this._requests = new Map()

    this._channel.open(handshake)
  }

  get closed() {
    return this._channel.closed
  }

  get mux() {
    return this._mux
  }

  get stream() {
    return this._mux.stream
  }

  get requests() {
    return this._requests.values()
  }

  _onopen() {
    this.emit('open')
  }

  _onclose() {
    this._ending = Promise.resolve()

    const err = this._error || errors.CHANNEL_CLOSED()

    for (const request of this._requests.values()) {
      request.destroy(err)
    }

    this._requests.clear()

    this.constructor._clients.delete(this.stream)

    this.emit('close')
  }

  _ondestroy() {
    this._destroyed = true
    this.emit('destroy')
  }

  _onpair({ isInitiator, token, id: remoteId }) {
    const request = this._requests.get(token.toString('hex'))

    if (request === undefined || request.isInitiator !== isInitiator) return

    request.push(remoteId)
    request.push(null)

    this.emit('pair', request.isInitiator, request.token, request.stream, remoteId)
  }

  pair(isInitiator, token, stream) {
    if (this._destroyed) throw errors.CHANNEL_DESTROYED()

    const keyString = token.toString('hex')

    if (this._requests.has(keyString)) throw errors.ALREADY_PAIRING()

    const request = new BlindRelayRequest(this, isInitiator, token, stream)

    this._requests.set(keyString, request)

    return request
  }

  unpair(token) {
    if (this._destroyed) throw errors.CHANNEL_DESTROYED()

    const request = this._requests.get(token.toString('hex'))

    if (request) request.destroy(errors.PAIRING_CANCELLED())

    this._unpair.send({ token })
  }

  cork() {
    this._channel.cork()
  }

  uncork() {
    this._channel.uncork()
  }

  async end() {
    if (this._ending) return this._ending

    this._ending = EventEmitter.once(this, 'close')
    this._endMaybe()

    return this._ending
  }

  _endMaybe() {
    if (this._ending && this._requests.size === 0) {
      this._channel.close()
    }
  }

  destroy(err) {
    if (this._destroyed) return
    this._destroyed = true

    this._error = err || errors.CHANNEL_DESTROYED()
    this._channel.close()
  }
}

class BlindRelayRequest extends Readable {
  constructor(client, isInitiator, token, stream) {
    super()

    this.client = client
    this.isInitiator = isInitiator
    this.token = token
    this.stream = stream
  }

  _open(cb) {
    if (this.client._destroyed) return cb(errors.CHANNEL_DESTROYED())

    this.client._pair.send({
      isInitiator: this.isInitiator,
      token: this.token,
      id: this.stream.id,
      seq: 0
    })

    cb(null)
  }

  _destroy(cb) {
    this.client._requests.delete(this.token.toString('hex'))

    cb(null)

    this.client._endMaybe()
  }
}

exports.token = function token(buf = b4a.allocUnsafe(32)) {
  sodium.randombytes_buf(buf)
  return buf
}

function noop() {}

function unlink(link) {
  const remote = link.remote

  link.remote = null

  if (remote && remote.remote === link) {
    remote.remote = null
  }
}

function createStats(server) {
  const stats = {
    sessions: {
      accepted: 0,
      opened: 0,
      closed: 0
    },
    pairings: {
      requested: 0,
      matched: 0,
      cancelled: 0
    },
    streams: {
      opened: 0,
      closed: 0,
      errors: 0
    }
  }

  Object.defineProperties(stats.sessions, {
    active: {
      enumerable: true,
      get() {
        return server._sessions.size
      }
    }
  })

  Object.defineProperties(stats.pairings, {
    pending: {
      enumerable: true,
      get() {
        return server._pairing.size
      }
    },
    active: {
      enumerable: true,
      get() {
        return server._activePairings()
      }
    }
  })

  Object.defineProperties(stats.streams, {
    active: {
      enumerable: true,
      get() {
        return server._activeStreams()
      }
    }
  })

  return stats
}

const m = (exports.messages = {})

const flags = bitfield(7)

m.pair = {
  preencode(state, m) {
    flags.preencode(state)
    c.fixed32.preencode(state, m.token)
    c.uint.preencode(state, m.id)
    c.uint.preencode(state, m.seq)
  },
  encode(state, m) {
    flags.encode(state, bits.of(m.isInitiator))
    c.fixed32.encode(state, m.token)
    c.uint.encode(state, m.id)
    c.uint.encode(state, m.seq)
  },
  decode(state) {
    const [isInitiator] = bits.iterator(flags.decode(state))

    return {
      isInitiator,
      token: c.fixed32.decode(state),
      id: c.uint.decode(state),
      seq: c.uint.decode(state)
    }
  }
}

m.unpair = {
  preencode(state, m) {
    flags.preencode(state)
    c.fixed32.preencode(state, m.token)
  },
  encode(state, m) {
    flags.encode(state, bits.of())
    c.fixed32.encode(state, m.token)
  },
  decode(state) {
    flags.decode(state)

    return {
      token: c.fixed32.decode(state)
    }
  }
}
module.exports = class BlindRelayError extends Error {
  constructor(msg, code, fn = BlindRelayError) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'BlindRelayError'
  }

  static DUPLICATE_CHANNEL(msg = 'Duplicate channel') {
    return new BlindRelayError(msg, 'DUPLICATE_CHANNEL', BlindRelayError.DUPLICATE_CHANNEL)
  }

  static CHANNEL_CLOSED(msg = 'Channel closed') {
    return new BlindRelayError(msg, 'CHANNEL_CLOSED', BlindRelayError.CHANNEL_CLOSED)
  }

  static CHANNEL_DESTROYED(msg = 'Channel destroyed') {
    return new BlindRelayError(msg, 'CHANNEL_DESTROYED', BlindRelayError.CHANNEL_DESTROYED)
  }

  static ALREADY_PAIRING(msg = 'Already pairing') {
    return new BlindRelayError(msg, 'ALREADY_PAIRING', BlindRelayError.ALREADY_PAIRING)
  }

  static PAIRING_CANCELLED(msg = 'Pairing cancelled') {
    return new BlindRelayError(msg, 'PAIRING_CANCELLED', BlindRelayError.PAIRING_CANCELLED)
  }
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return uint24.decode(state) + 0x1000000 * uint32.decode(state)
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return uint32.decode(state) + 0x100000000 * uint32.decode(state)
  }
})

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "2.19.2",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    if (b.byteLength === 0) return null
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "blind-relay",
  "version": "1.5.0",
  "description": "Blind relay for UDX over Protomux channels",
  "main": "index.js",
  "files": [
    "index.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:bare",
    "test:bare": "brittle-bare --coverage test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/blind-relay.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/blind-relay/issues"
  },
  "homepage": "https://github.com/holepunchto/blind-relay#readme",
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "dependencies": {
    "b4a": "^1.6.4",
    "bare-events": "^2.2.0",
    "bits-to-bytes": "^1.3.0",
    "compact-encoding": "^2.12.0",
    "compact-encoding-bitfield": "^1.0.0",
    "protomux": "^3.5.1",
    "sodium-universal": "^5.0.0",
    "streamx": "^2.15.1"
  },
  "devDependencies": {
    "brittle": "^3.2.1",
    "hyperdht": "^6.6.1",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "udx-native": "^1.6.1"
  }
}
// https://ipinfo.io/bogon

const b4a = require('b4a')
const c = require('compact-encoding')
const net = require('compact-encoding-net')

module.exports = exports = function isBogon (ip) {
  return isBogonIP(ensureBuffer(ip))
}

exports.isBogon = exports

exports.isPrivate = function isPrivate (ip) {
  return isPrivateIP(ensureBuffer(ip))
}

exports.isReserved = function isReserved (ip) {
  return isReservedIP(ensureBuffer(ip))
}

function isBogonIP (ip) {
  return isPrivateIP(ip) || isReservedIP(ip)
}

function isPrivateIP (ip) {
  return ip.byteLength === 4 ? isPrivateIPv4(ip) : false // IPv6 has no private IPs
}

function isPrivateIPv4 (ip) {
  return (
    // 10.0.0.0/8  Private-use networks
    (ip[0] === 10) ||
    // 100.64.0.0/10 Carrier-grade NAT
    (ip[0] === 100 && ip[1] >= 64 && ip[1] <= 127) ||
    // 127.0.0.0/8 Loopback + Name collision occurrence (127.0.53.53)
    (ip[0] === 127) ||
    // 169.254.0.0/16  Link local
    (ip[0] === 169 && ip[1] === 254) ||
    // 172.16.0.0/12 Private-use networks
    (ip[0] === 172 && ip[1] >= 16 && ip[1] <= 31) ||
    // 192.168.0.0/16  Private-use networks
    (ip[0] === 192 && ip[1] === 168)
  )
}

function isReservedIP (ip) {
  return ip.byteLength === 4 ? isReservedIPv4(ip) : isReservedIPv6(ip)
}

function isReservedIPv4 (ip) {
  return (
    // 0.0.0.0/8 "This" network
    (ip[0] === 0) ||
    // 192.0.0.0/24  IETF protocol assignments
    (ip[0] === 192 && ip[1] === 0 && ip[2] === 0) ||
    // 192.0.2.0/24  TEST-NET-1
    (ip[0] === 192 && ip[1] === 0 && ip[2] === 2) ||
    // 198.18.0.0/15 Network interconnect device benchmark testing
    (ip[0] === 198 && ip[1] >= 18 && ip[1] <= 19) ||
    // 198.51.100.0/24 TEST-NET-2
    (ip[0] === 198 && ip[1] === 51 && ip[2] === 100) ||
    // 203.0.113.0/24  TEST-NET-3
    (ip[0] === 203 && ip[1] === 0 && ip[2] === 113) ||
    // 224.0.0.0/4 Multicast
    (ip[0] >= 224 && ip[0] <= 239) ||
    // 240.0.0.0/4 Reserved for future use
    (ip[0] >= 240) ||
    // 255.255.255.255/32
    (ip[0] === 255 && ip[1] === 255 && ip[2] === 255 && ip[3] === 255)
  )
}

function isReservedIPv6 (ip) {
  return (
    // ::/128 Node-scope unicast unspecified address
    // ::1/128 Node-scope unicast loopback address
    (
      ip[0] === 0 && ip[1] === 0 && ip[2] === 0 && ip[3] === 0 && ip[4] === 0 &&
      ip[5] === 0 && ip[6] === 0 && ip[7] === 0 && ip[8] === 0 && ip[9] === 0 &&
      ip[10] === 0 && ip[11] === 0 && ip[12] === 0 && ip[13] === 0 && ip[14] === 0 &&
      ip[15] <= 1
    ) ||
    // ::ffff:0:0/96 IPv4-mapped addresses
    // ::/96 IPv4-compatible addresses
    (
      ip[0] === 0 && ip[1] === 0 && ip[2] === 0 && ip[3] === 0 && ip[4] === 0 &&
      ip[5] === 0 && ip[6] === 0 && ip[7] === 0 && ip[8] === 0 && ip[9] === 0 &&
      (ip[10] === 0 || ip[10] === 0xff) &&
      (ip[11] === 0 || ip[11] === 0xff)
    ) ||
    // 100::/64 Remotely triggered black hole addresses
    (ip[0] === 0x01 && ip[1] === 0 && ip[2] === 0 && ip[3] === 0 && ip[4] === 0 && ip[5] === 0 && ip[6] === 0 && ip[7] === 0) ||
    // 2001:10::/28 Overlay routable cryptographic hash identifiers (ORCHID)
    (ip[0] === 0x20 && ip[1] === 0x01 && ip[2] === 0 && ip[3] >= 0x10 && ip[3] <= 0x1f) ||
    // 2001:20::/28 Overlay routable cryptographic hash identifiers version 2 (ORCHIDv2)
    (ip[0] === 0x20 && ip[1] === 0x01 && ip[2] === 0 && ip[3] >= 0x20 && ip[3] <= 0x2f) ||
    // 2001:db8::/32 Documentation prefix
    (ip[0] === 0x20 && ip[1] === 0x01 && ip[2] === 0x0d && ip[3] === 0xb8) ||
    // fc00::/7 Unique local addresses (ULA)
    (ip[0] >= 0xfc && ip[0] <= 0xfd) ||
    // fe80::/10 Link-local unicast
    (ip[0] === 0xfe && ip[1] >= 0x80 && ip[1] <= 0xbf) ||
    // ff00::/8 Multicast
    (ip[0] === 0xff)
  )
}

const state = c.state(0, 0, b4a.allocUnsafe(1 /* family */ + 16))

function ensureBuffer (ip) {
  if (b4a.isBuffer(ip)) return ip

  net.ip.preencode(state, ip)
  net.ip.encode(state, ip)

  const buffer = state.buffer.subarray(1 /* family */, state.end)

  state.start = 0
  state.end = 0

  return buffer
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return uint24.decode(state) + 0x1000000 * uint32.decode(state)
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return uint32.decode(state) + 0x100000000 * uint32.decode(state)
  }
})

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "2.19.2",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    if (b.byteLength === 0) return null
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "bogon",
  "version": "1.2.0",
  "description": "Check if an IP is a bogon",
  "main": "index.js",
  "scripts": {
    "test": "standard && brittle test.mjs"
  },
  "dependencies": {
    "compact-encoding": "^2.11.0",
    "compact-encoding-net": "^1.2.0"
  },
  "devDependencies": {
    "brittle": "^3.0.4",
    "nanobench": "^2.1.1",
    "standard": "^17.0.0"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/bogon.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/bogon/issues"
  },
  "homepage": "https://github.com/mafintosh/bogon"
}
const c = require('compact-encoding')

module.exports = function bitfield (length) {
  if (length > 64) throw new RangeError('Bitfield cannot be larger than 64 bits')

  let byteLength
  if (length < 8) byteLength = 1
  else if (length <= 16) byteLength = 2
  else if (length <= 32) byteLength = 4
  else byteLength = 8

  return {
    preencode (state) {
      state.end++ // Length byte, used for data when byteLength === 1

      if (byteLength === 1) ;
      else if (byteLength === 2) c.uint16.preencode(state)
      else if (byteLength === 4) c.uint32.preencode(state)
      else c.uint64.preencode(state)
    },

    encode (state, b) {
      if (byteLength === 1) ;
      else if (byteLength === 2) c.uint8.encode(state, 0xfd)
      else if (byteLength === 4) c.uint8.encode(state, 0xfe)
      else c.uint8.encode(state, 0xff)

      if (typeof b === 'number') {
        if (byteLength === 1) c.uint8.encode(state, b)
        else if (byteLength === 2) c.uint16.encode(state, b)
        else if (byteLength === 4) c.uint32.encode(state, b)
        else c.uint64.encode(state, b)
      } else {
        state.buffer.set(b, state.start)

        if (b.byteLength < byteLength) {
          // Zero-fill the rest of the byte length.
          state.buffer.fill(
            0,
            state.start + b.byteLength,
            state.start + byteLength
          )
        }

        state.start += byteLength
      }
    },

    decode (state) {
      const byte = state.buffer[state.start]

      let byteLength
      if (byte <= 0xfc) byteLength = 1
      else if (byte === 0xfd) byteLength = 2
      else if (byte === 0xfe) byteLength = 4
      else byteLength = 8

      if (byteLength > 1) state.start++ // Skip the length byte

      if (state.end - state.start < byteLength) throw new Error('Out of bounds')

      const b = state.buffer.subarray(state.start, (state.start += byteLength))

      return length <= 8 ? b.subarray(0, 1) : b
    }
  }
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return uint24.decode(state) + 0x1000000 * uint32.decode(state)
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return uint32.decode(state) + 0x100000000 * uint32.decode(state)
  }
})

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "2.19.2",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    if (b.byteLength === 0) return null
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "compact-encoding-bitfield",
  "version": "1.0.0",
  "description": "Compact codec for bitfields",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "scripts": {
    "test": "standard && brittle test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/compact-encoding/compact-encoding-bitfield.git"
  },
  "author": "Kasper Isager Dalsgarð <kasper@funktionel.co>",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/compact-encoding/compact-encoding-bitfield/issues"
  },
  "homepage": "https://github.com/compact-encoding/compact-encoding-bitfield#readme",
  "dependencies": {
    "compact-encoding": "^2.4.1"
  },
  "devDependencies": {
    "brittle": "^1.3.5",
    "standard": "^16.0.3"
  },
  "standard": {
    "ignore": [
      "__snapshots__/**"
    ]
  }
}
const c = require('compact-encoding')

const port = c.uint16

const address = (host, family) => {
  return {
    preencode (state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode (state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode (state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = {
  preencode (state) {
    state.end += 4
  },
  encode (state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (i < string.length && (c = string.charCodeAt(i++)) !== /* . */ 0x2e) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode (state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] + '.' +
      state.buffer[state.start++] + '.' +
      state.buffer[state.start++] + '.' +
      state.buffer[state.start++]
    )
  }
}

const ipv4Address = address(ipv4, 4)

const ipv6 = {
  preencode (state) {
    state.end += 16
  },
  encode (state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (i < string.length && (c = string.charCodeAt(i++)) !== /* : */ 0x3a) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode (state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (state.buffer[state.start++] * 256 + state.buffer[state.start++]).toString(16) + ':' +
      (state.buffer[state.start++] * 256 + state.buffer[state.start++]).toString(16) + ':' +
      (state.buffer[state.start++] * 256 + state.buffer[state.start++]).toString(16) + ':' +
      (state.buffer[state.start++] * 256 + state.buffer[state.start++]).toString(16) + ':' +
      (state.buffer[state.start++] * 256 + state.buffer[state.start++]).toString(16) + ':' +
      (state.buffer[state.start++] * 256 + state.buffer[state.start++]).toString(16) + ':' +
      (state.buffer[state.start++] * 256 + state.buffer[state.start++]).toString(16) + ':' +
      (state.buffer[state.start++] * 256 + state.buffer[state.start++]).toString(16)
    )
  }
}

const ipv6Address = address(ipv6, 6)

const ip = {
  preencode (state, string) {
    const family = string.includes(':') ? 6 : 4
    c.uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode (state, string) {
    const family = string.includes(':') ? 6 : 4
    c.uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode (state) {
    const family = c.uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
}

const ipAddress = {
  preencode (state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode (state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode (state) {
    const family = c.uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

module.exports = {
  port,
  ipv4,
  ipv4Address,
  ipv6,
  ipv6Address,
  ip,
  ipAddress
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return uint24.decode(state) + 0x1000000 * uint32.decode(state)
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return uint32.decode(state) + 0x100000000 * uint32.decode(state)
  }
})

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "2.19.2",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    if (b.byteLength === 0) return null
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "compact-encoding-net",
  "version": "1.2.0",
  "description": "Compact codecs for net types",
  "main": "index.js",
  "scripts": {
    "test": "standard && brittle test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/compact-encoding/compact-encoding-net.git"
  },
  "author": "Kasper Isager Dalsgarð <kasper@funktionel.co>",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/compact-encoding/compact-encoding-net/issues"
  },
  "homepage": "https://github.com/compact-encoding/compact-encoding-net#readme",
  "dependencies": {
    "compact-encoding": "^2.4.1"
  },
  "devDependencies": {
    "brittle": "^1.3.5",
    "nanobench": "^2.1.1",
    "standard": "^16.0.3"
  }
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return uint24.decode(state) + 0x1000000 * uint32.decode(state)
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return uint32.decode(state) + 0x100000000 * uint32.decode(state)
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return 0x100000000 * uint32be.decode(state) + uint32be.decode(state)
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.2.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
const { EventEmitter } = require('events')
const Table = require('kademlia-routing-table')
const TOS = require('time-ordered-set')
const UDX = require('udx-native')
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const NatSampler = require('nat-sampler')
const b4a = require('b4a')
const NetworkHealth = require('./lib/health')
const IO = require('./lib/io')
const Query = require('./lib/query')
const Session = require('./lib/session')
const peer = require('./lib/peer')
const { UNKNOWN_COMMAND, INVALID_TOKEN } = require('./lib/errors')
const { PING, PING_NAT, FIND_NODE, DOWN_HINT, DELAYED_PING } = require('./lib/commands')

const TMP = b4a.allocUnsafe(32)
const TICK_INTERVAL = 5000
const SLEEPING_INTERVAL = 3 * TICK_INTERVAL
const STABLE_TICKS = 240 // if nothing major bad happens in ~20mins we can consider this node stable (if nat is friendly)
const MORE_STABLE_TICKS = 3 * STABLE_TICKS
const REFRESH_TICKS = 60 // refresh every ~5min when idle
const RECENT_NODE = 12 // we've heard from a node less than 1min ago
const OLD_NODE = 360 // if an node has been around more than 30 min we consider it old

const DEFAULTS = {
  concurrency: 10,
  maxWindow: IO.DEFAULT_MAX_WINDOW,
  maxPingDelay: 10_000
}

class DHT extends EventEmitter {
  constructor(opts = {}) {
    super()

    this.bootstrapNodes = opts.bootstrap === false ? [] : (opts.bootstrap || []).map(parseNode)
    this.table = new Table(randomBytes(32))
    this.nodes = new TOS()
    this.udx = opts.udx || new UDX()
    this.io = new IO(this.table, this.udx, {
      ...opts,
      onrequest: this._onrequest.bind(this),
      onresponse: this._onresponse.bind(this),
      ontimeout: this._ontimeout.bind(this)
    })
    this.health = new NetworkHealth(this)

    this.concurrency = opts.concurrency || DEFAULTS.concurrency
    this.maxPingDelay = opts.maxPingDelay || DEFAULTS.maxPingDelay
    this.bootstrapped = false
    this.ephemeral = true
    this.firewalled = this.io.firewalled
    this.adaptive = typeof opts.ephemeral !== 'boolean' && opts.adaptive !== false
    this.destroyed = false
    this.suspended = false
    this.online = true
    this.degraded = false
    this.stats = {
      queries: { active: 0, total: 0 },
      requests: this.io.stats.requests,
      commands: {
        ping: this.io.stats.commands[PING],
        pingNat: this.io.stats.commands[PING_NAT],
        findNode: this.io.stats.commands[FIND_NODE],
        downHint: this.io.stats.commands[DOWN_HINT]
      }
    }

    this._nat = new NatSampler()
    this._quickFirewall = opts.quickFirewall !== false
    this._forcePersistent = opts.ephemeral === false
    this._repinging = 0
    this._checks = 0
    this._tick = randomOffset(100) // make sure to random offset all the network ticks
    this._refreshTicks = randomOffset(REFRESH_TICKS)
    this._stableTicks = this.adaptive ? STABLE_TICKS : 0
    this._tickInterval = setInterval(this._ontick.bind(this), TICK_INTERVAL)
    this._lastTick = Date.now()
    this._lastHost = null
    this._filterNode = opts.filterNode || opts.addNode || null // opts.addNode is deprecating, use opts.filterNode instead
    this._onrow = (row) => row.on('full', (node) => this._onfullrow(node, row))
    this._nonePersistentSamples = []
    this._bootstrapping = this._bootstrap()
    this._bootstrapping.catch(noop)
    this._sendDownHints = opts.sendDownHints !== false
    this._downHintsRateLimit =
      opts.downHintsRateLimit !== undefined ? opts.downHintsRateLimit : 10 * 5
    this._downHintsSentPerTick = 0
    this._pendingTimers = new Set()

    this.table.on('row', this._onrow)

    this.io.networkInterfaces.on('change', (interfaces) => this._onnetworkchange(interfaces))

    if (opts.nodes) {
      for (let i = opts.nodes.length - 1; i >= 0; i--) {
        this.addNode(opts.nodes[i])
      }
    }
  }

  static DEFAULTS = DEFAULTS

  static bootstrapper(port, host, opts) {
    if (!port) throw new Error('Port is required')
    if (!host) throw new Error('Host is required')
    if (host === '0.0.0.0' || host === '::') throw new Error('Invalid host')
    if (!UDX.isIPv4(host)) throw new Error('Host must be a IPv4 address')

    const dht = new this({
      port,
      ephemeral: false,
      firewalled: false,
      anyPort: false,
      bootstrap: [],
      ...opts
    })
    dht._nat.add(host, port)
    return dht
  }

  get id() {
    return this.ephemeral ? null : this.table.id
  }

  get host() {
    return this._nat.host
  }

  get port() {
    return this._nat.port
  }

  get randomized() {
    return this._nat.host !== null && this._nat.port === 0
  }

  get socket() {
    return this.firewalled ? this.io.clientSocket : this.io.serverSocket
  }

  get config() {
    return {
      concurrency: this.concurrency,
      maxWindow: this.io.congestion._maxWindow,
      randomPunchInterval: this._randomPunchInterval,
      connectionKeepAlive: this.connectionKeepAlive,
      sendDownHints: this._sendDownHints,
      downHintsRateLimit: this._downHintsRateLimit
    }
  }

  onmessage(socket, buf, rinfo) {
    if (buf.byteLength > 1) this.io.onmessage(socket, buf, rinfo)
  }

  bind() {
    return this.io.bind()
  }

  async suspend({ log = noop } = {}) {
    log('Suspending waiting for io bind...')
    await this.io.bind()
    log('Done, continuing')
    if (this.suspended || this.destroyed) return
    this.suspended = true
    clearInterval(this._tickInterval)
    log('Done, suspending io')
    await this.io.suspend({ log })
    log('Done, dht suspended')
    this.emit('suspend')
  }

  async resume({ log = noop } = {}) {
    if (!this.suspended || this.destroyed) return
    this.suspended = false
    this._tickInterval = setInterval(this._ontick.bind(this), TICK_INTERVAL)
    this._onwakeup()
    log('Resuming io')
    await this.io.resume()
    log('Done, dht resumed')
    this.io.networkInterfaces.on('change', (interfaces) => this._onnetworkchange(interfaces))
    this.refresh()
    this.emit('resume')
  }

  address() {
    const socket = this.socket
    return socket ? socket.address() : null
  }

  localAddress() {
    if (!this.io.serverSocket) return null

    return {
      host: localIP(this.udx),
      port: this.io.serverSocket.address().port
    }
  }

  remoteAddress() {
    if (!this.host) return null
    if (!this.port) return null
    if (this.firewalled) return null
    if (!this.io.serverSocket) return null

    const port = this.io.serverSocket.address().port
    if (port !== this.port) return null

    return {
      host: this.host,
      port
    }
  }

  addNode({ host, port }) {
    this._addNode({
      id: peer.id(host, port),
      port,
      host,
      token: null,
      to: null,
      sampled: 0,
      added: this._tick,
      pinged: 0,
      seen: 0,
      downHints: 0,
      prev: null,
      next: null
    })
  }

  toArray(opts) {
    const limit = opts && opts.limit
    if (limit === 0) return []
    return this.nodes.toArray({ limit, reverse: true }).map(({ host, port }) => ({ host, port }))
  }

  async fullyBootstrapped() {
    return this._bootstrapping
  }

  ready() {
    // Deprecating, use fullyBootstrapped instead (removed on next major)
    return this.fullyBootstrapped()
  }

  findNode(target, opts) {
    if (this.destroyed) throw new Error('Node destroyed')
    this._refreshTicks = REFRESH_TICKS
    return new Query(this, target, true, FIND_NODE, null, opts)
  }

  query({ target, command, value }, opts) {
    if (this.destroyed) throw new Error('Node destroyed')
    this._refreshTicks = REFRESH_TICKS
    return new Query(this, target, false, command, value || null, opts)
  }

  ping({ host, port }, opts) {
    let value = null

    if (opts && opts.size && opts.size > 0) value = b4a.alloc(opts.size)

    const req = this.io.createRequest(
      { id: null, host, port },
      null,
      true,
      PING,
      null,
      value,
      (opts && opts.session) || null,
      opts && opts.ttl
    )
    return this._requestToPromise(req, opts)
  }

  delayedPing({ host, port }, delayMs, opts) {
    if (delayMs > this.maxPingDelay) {
      throw new Error(`Delay exceeds max delay: ${this.maxPingDelay}ms`)
    }

    const value = b4a.allocUnsafe(4)
    c.uint32.encode({ start: 0, end: 4, buffer: value }, delayMs)

    const req = this.io.createRequest(
      { id: null, host, port },
      null,
      true,
      DELAYED_PING,
      null,
      value,
      (opts && opts.session) || null,
      opts && opts.ttl
    )
    // add 1 second to the timeout to account for network overhead
    req.timeout = delayMs + 1_000
    return this._requestToPromise(req, opts)
  }

  async rttStats() {
    const stats = {
      successes: 0,
      errors: 0,
      responses: {
        avgRtt: 0,
        errors: 0,
        avgCloserNodes: 0
      },
      closestReplies: {
        avgRtt: 0,
        errors: 0,
        avgCloserNodes: 0
      }
    }

    if (this.nodes.latest) {
      const q = this.findNode(this.nodes.latest.id)

      let responseCount = 0
      let closestCount = 0

      for await (const msg of q) {
        stats.responses.avgRtt += msg.rtt
        stats.responses.errors += msg.error
        stats.responses.avgCloserNodes += msg.closerNodes?.length || 0
        responseCount++
      }
      stats.responses.avgRtt /= responseCount
      stats.responses.avgCloserNodes /= responseCount

      for await (const msg of q.closestReplies) {
        stats.closestReplies.avgRtt += msg.rtt
        stats.closestReplies.errors += msg.error
        stats.closestReplies.avgCloserNodes += msg.closerNodes?.length || 0
        closestCount++
      }
      stats.closestReplies.avgRtt /= closestCount
      stats.closestReplies.avgCloserNodes /= closestCount

      stats.successes = q.successes
      stats.errors = q.errors
    }

    return stats
  }

  request({ token = null, command, target = null, value = null }, { host, port }, opts) {
    const req = this.io.createRequest(
      { id: null, host, port },
      token,
      false,
      command,
      target,
      value,
      (opts && opts.session) || null,
      opts && opts.ttl
    )
    return this._requestToPromise(req, opts)
  }

  session() {
    return new Session(this)
  }

  _requestToPromise(req, opts) {
    if (req === null) return Promise.reject(new Error('Node destroyed'))

    if (opts && opts.socket) req.socket = opts.socket
    if (opts && opts.retry === false) req.retries = 0

    return new Promise((resolve, reject) => {
      req.onresponse = resolve
      req.onerror = reject
      req.send()
    })
  }

  async _bootstrap() {
    const self = this

    await Promise.resolve() // wait a tick, so apis can be used from the outside
    await this.io.bind()

    this.emit('listening')

    // TODO: some papers describe more advanced ways of bootstrapping - we should prob look into that

    let first = this.firewalled && this._quickFirewall && !this._forcePersistent
    let testNat = false

    const onlyFirewall = !this._forcePersistent

    for (let i = 0; i < 2; i++) {
      await this._backgroundQuery(this.table.id).on('data', ondata).finished()

      if (this.bootstrapped || (!testNat && !this._forcePersistent)) break
      if (!(await this._updateNetworkState(onlyFirewall))) break
    }

    if (this.bootstrapped) return
    this.bootstrapped = true

    this.emit('ready')

    function ondata(data) {
      // Simple QUICK nat heuristic.
      // If we get ONE positive nat ping before the bootstrap query finishes
      // then we always to a nat test, no matter if we are adaptive...
      // This should be expanded in the future to try more than one node etc, not always hit the first etc
      // If this fails, then nbd, as the onstable hook will pick it up later.

      if (!first) return
      first = false

      const value = b4a.allocUnsafe(2)
      c.uint16.encode({ start: 0, end: 2, buffer: value }, self.io.serverSocket.address().port)

      self._request(
        data.from,
        false,
        true,
        PING_NAT,
        null,
        value,
        null,
        () => {
          testNat = true
        },
        noop
      )
    }
  }

  refresh() {
    const node = this.table.random()
    this._backgroundQuery(node ? node.id : this.table.id).on('error', noop)
  }

  async destroy() {
    const emitClose = !this.destroyed
    this.destroyed = true
    clearInterval(this._tickInterval)
    for (const timer of this._pendingTimers) {
      clearTimeout(timer)
    }
    await this.io.destroy()
    if (emitClose) this.emit('close')
  }

  _request(to, force, internal, command, target, value, session, onresponse, onerror) {
    if (internal && !this._sendDownHints && command === DOWN_HINT) return null
    const req = this.io.createRequest(to, null, internal, command, target, value, session)
    if (req === null) return null

    req.onresponse = onresponse
    req.onerror = onerror
    req.send(force)

    return req
  }

  _natAdd(host, port) {
    const prevHost = this._nat.host
    const prevPort = this._nat.port

    this._nat.add(host, port)

    if (prevHost === this._nat.host && prevPort === this._nat.port) return

    this.emit('nat-update', this._nat.host, this._nat.port)
  }

  // we don't check that this is a bootstrap node but we limit the sample size to very few nodes, so fine
  _sampleBootstrapMaybe(from, to) {
    if (this._nonePersistentSamples.length >= Math.max(1, this.bootstrapNodes.length)) return
    const id = from.host + ':' + from.port
    if (this._nonePersistentSamples.indexOf(id) > -1) return
    this._nonePersistentSamples.push(id)
    this._natAdd(to.host, to.port)
  }

  _addNodeFromNetwork(sample, from, to) {
    if (this._filterNode !== null && !this._filterNode(from)) {
      return
    }

    if (from.id === null) {
      this._sampleBootstrapMaybe(from, to)
      return
    }

    const oldNode = this.table.get(from.id)

    // refresh it, if we've seen this before
    if (oldNode) {
      if (sample && (oldNode.sampled === 0 || this._tick - oldNode.sampled >= OLD_NODE)) {
        oldNode.to = to
        oldNode.sampled = this._tick
        this._natAdd(to.host, to.port)
      }

      oldNode.pinged = oldNode.seen = this._tick
      this.nodes.add(oldNode)
      return
    }

    this._addNode({
      id: from.id,
      port: from.port,
      host: from.host,
      to,
      sampled: 0,
      added: this._tick,
      pinged: this._tick, // last time we interacted with them
      seen: this._tick, // last time we heard from them
      downHints: 0,
      prev: null,
      next: null
    })
  }

  _addNode(node) {
    if (this.nodes.has(node) || b4a.equals(node.id, this.table.id)) return

    node.added = node.pinged = node.seen = this._tick

    if (!this.table.add(node)) return
    this.nodes.add(node)

    if (node.to && node.sampled === 0) {
      node.sampled = this._tick
      this._natAdd(node.to.host, node.to.port)
    }

    this.emit('add-node', node)
  }

  _removeStaleNode(node, lastSeen) {
    if (node.seen <= lastSeen) this._removeNode(node)
  }

  _removeNode(node) {
    if (!this.nodes.has(node)) return

    this.table.remove(node.id)
    this.nodes.remove(node)

    this.emit('remove-node', node)
  }

  _onwakeup() {
    this._tick += 2 * OLD_NODE // bump the tick enough that everything appears old.
    this._tick += 8 - (this._tick & 7) - 2 // triggers a series of pings in two ticks
    this._stableTicks = MORE_STABLE_TICKS
    this._refreshTicks = 1 // triggers a refresh next tick (allow network time to wake up also)
    this._lastHost = null // clear network cache check
    this.health.reset()

    if (this.adaptive) {
      // TODO: re-enable this as soon as we find out why this is over triggering in some edge cases
      // this.firewalled = true
      // this.io.firewalled = true

      if (!this.ephemeral) {
        this.ephemeral = true
        this.io.ephemeral = true
        this.emit('ephemeral')
      }
    }

    this.emit('wakeup')
  }

  _onfullrow(newNode, row) {
    if (!this.bootstrapped || this._repinging >= 3) return

    let oldest = null
    for (const node of row.nodes) {
      if (node.pinged === this._tick) continue
      if (
        oldest === null ||
        oldest.pinged > node.pinged ||
        (oldest.pinged === node.pinged && oldest.added > node.added)
      ) {
        oldest = node
      }
    }

    if (oldest === null) return
    if (this._tick - oldest.pinged < RECENT_NODE && this._tick - oldest.added > OLD_NODE) return

    this._repingAndSwap(newNode, oldest)
  }

  _onnetworkchange(interfaces) {
    this.emit('network-change', interfaces)
    this.emit('network-update')
  }

  _repingAndSwap(newNode, oldNode) {
    const self = this
    const lastSeen = oldNode.seen

    oldNode.pinged = this._tick

    this._repinging++
    this._request(
      { id: null, host: oldNode.host, port: oldNode.port },
      false,
      true,
      PING,
      null,
      null,
      null,
      onsuccess,
      onswap
    )

    function onsuccess(m) {
      if (oldNode.seen <= lastSeen) return onswap()
      self._repinging--
    }

    function onswap(e) {
      self._repinging--
      self._removeNode(oldNode)
      self._addNode(newNode)
    }
  }

  _onrequest(req, external) {
    if (req.from.id !== null) {
      this._addNodeFromNetwork(!external, req.from, req.to)
    }

    if (req.internal) {
      switch (req.command) {
        // standard keep alive call
        case PING: {
          req.sendReply(0, null, false, false)
          return
        }
        case DELAYED_PING: {
          this._ondelayedping(req)
          return
        }
        // check if the other side can receive a message to their other socket
        case PING_NAT: {
          if (req.value === null || req.value.byteLength < 2) return
          const port = c.uint16.decode({ start: 0, end: 2, buffer: req.value })
          if (port === 0) return
          req.from.port = port
          req.sendReply(0, null, false, false)
          return
        }
        // empty dht reply back
        case FIND_NODE: {
          if (!req.target) return
          req.sendReply(0, null, false, true)
          return
        }
        // "this is node you sent me is down" - let's try to ping it
        case DOWN_HINT: {
          if (req.value === null || req.value.byteLength < 6) return
          if (this._checks < 10) {
            sodium.crypto_generichash(TMP, req.value.subarray(0, 6))
            const node = this.table.get(TMP)
            if (node && (node.pinged < this._tick || node.downHints === 0)) {
              node.downHints++
              this._check(node)
            }
          }
          req.sendReply(0, null, false, false)
          return
        }
      }

      req.sendReply(UNKNOWN_COMMAND, null, false, req.target !== null)
      return
    }

    // ask the user to handle it or reply back with a bad command
    if (this.onrequest(req) === false) {
      req.sendReply(UNKNOWN_COMMAND, null, false, req.target !== null)
    }
  }

  onrequest(req) {
    return this.emit('request', req)
  }

  _ondelayedping(req) {
    if (req.value === null || req.value.byteLength < 4) return
    const delayMs = c.uint32.decode({ start: 0, end: 4, buffer: req.value })
    if (delayMs > this.maxPingDelay) return
    const timer = setTimeout(() => {
      if (this.destroyed) return
      this._pendingTimers.delete(timer)
      req.sendReply(0, null, false, false)
    }, delayMs)
    this._pendingTimers.add(timer)
  }

  _onresponse(res, external) {
    this._addNodeFromNetwork(!external, res.from, res.to)
  }

  _ontimeout(req) {
    if (!req.to.id) return
    const node = this.table.get(req.to.id)
    if (node) this._removeNode(node)
  }

  _pingSome() {
    let cnt = this.io.inflight.length > 2 ? 3 : 5
    let oldest = this.nodes.oldest

    // tiny dht, pinged the bootstrap again
    if (!oldest) {
      this.refresh()
      return
    }

    // we've recently pinged the oldest one, so only trigger a couple of repings
    if (this._tick - oldest.pinged < RECENT_NODE) {
      cnt = 2
    }

    while (cnt--) {
      if (!oldest || this._tick === oldest.pinged) continue
      this._check(oldest)
      oldest = oldest.next
    }
  }

  _check(node) {
    node.pinged = this._tick

    const lastSeen = node.seen
    const onresponse = () => {
      this._checks--
      this._removeStaleNode(node, lastSeen)
    }
    const onerror = () => {
      this._checks--
      this._removeNode(node)
    }

    this._checks++
    this._request(
      { id: null, host: node.host, port: node.port },
      false,
      true,
      PING,
      null,
      null,
      null,
      onresponse,
      onerror
    )
  }

  _ontick() {
    const time = Date.now()

    if (time - this._lastTick > SLEEPING_INTERVAL && this.suspended === false) {
      this._onwakeup()
    } else {
      this._tick++
    }

    this._lastTick = time

    if (!this.bootstrapped || this.suspended) return

    if (this.adaptive && this.ephemeral && --this._stableTicks <= 0) {
      if (this._lastHost === this._nat.host) {
        // do not recheck the same network...
        this._stableTicks = MORE_STABLE_TICKS
      } else {
        this._updateNetworkState() // the promise returned here never fails so just ignore it
      }
    }

    if ((this._tick & 7) === 0) {
      this._pingSome()
    }

    if (
      ((this._tick & 63) === 0 && this.nodes.length < this.table.k) ||
      --this._refreshTicks <= 0
    ) {
      this.refresh()
    }

    this._downHintsSentPerTick = 0
    this.health.update()
  }

  async _updateNetworkState(onlyFirewall = false) {
    if (!this.ephemeral) return false
    if (onlyFirewall && !this.firewalled) return false

    const { host, port } = this._nat

    if (!onlyFirewall) {
      // remember what host we checked and reset the counter
      this._stableTicks = MORE_STABLE_TICKS
      this._lastHost = host
    }

    // check if we have a consistent host and port
    if (host === null || port === 0) {
      return false
    }

    const natSampler = this.firewalled ? new NatSampler() : this._nat

    // ask remote nodes to ping us on our server socket to see if we have the port open
    const firewalled = this.firewalled && (await this._checkIfFirewalled(natSampler))
    if (firewalled) return false

    this.firewalled = this.io.firewalled = false

    // incase it's called in parallel for some reason, or if our nat status somehow changed
    if (!this.ephemeral || host !== this._nat.host || port !== this._nat.port) return false
    // if the firewall probe returned a different host / non consistent port, bail as well
    if (natSampler.host !== host || natSampler.port === 0) return false

    const id = peer.id(natSampler.host, natSampler.port)

    if (!onlyFirewall) {
      this.ephemeral = this.io.ephemeral = false
    }

    if (natSampler !== this._nat) {
      const prevHost = this._nat.host
      const prevPort = this._nat.port

      this._nonePersistentSamples = []
      this._nat = natSampler

      if (prevHost !== this._nat.host || prevPort !== this._nat.port) {
        this.emit('nat-update', this._nat.host, this._nat.port)
      }
    }

    // TODO: we should make this a bit more defensive in terms of using more
    // resources to make sure that the new routing table contains as many alive nodes
    // as possible, vs blindly copying them over...

    // all good! copy over the old routing table to the new one
    if (!b4a.equals(this.table.id, id)) {
      const nodes = this.table.toArray()

      this.table = this.io.table = new Table(id)

      for (const node of nodes) {
        if (b4a.equals(node.id, id)) continue
        if (!this.table.add(node)) this.nodes.remove(node)
      }

      this.table.on('row', this._onrow)

      // we need to rebootstrap/refresh since we updated our id
      if (this.bootstrapped) this.refresh()
    }

    if (!this.ephemeral) {
      this.emit('persistent')
    }

    return true
  }

  async *_resolveBootstrapNodes() {
    for (let { host, port } of this.bootstrapNodes) {
      let doLookup = false

      if (host.indexOf('@') === -1) {
        doLookup = true
      } else {
        const [suggestedIP, fallbackHost] = host.split('@')
        try {
          await this.ping({ host: suggestedIP, port })
          host = suggestedIP
        } catch {
          host = fallbackHost
          doLookup = true
        }
      }

      if (doLookup) {
        try {
          host = UDX.isIPv4(host) ? host : (await this.udx.lookup(host, { family: 4 })).host
        } catch {
          continue
        }
      }

      yield {
        id: peer.id(host, port),
        host,
        port
      }
    }
  }

  async _addBootstrapNodes(nodes) {
    for await (const node of this._resolveBootstrapNodes()) {
      nodes.push(node)
    }
  }

  async _checkIfFirewalled(natSampler = new NatSampler()) {
    const nodes = []
    for (let node = this.nodes.latest; node && nodes.length < 5; node = node.prev) {
      nodes.push(node)
    }

    if (nodes.length < 5) await this._addBootstrapNodes(nodes)
    // if no nodes are available, including bootstrappers - bail
    if (nodes.length === 0) return true

    const hosts = new Set()
    const value = b4a.allocUnsafe(2)

    c.uint16.encode({ start: 0, end: 2, buffer: value }, this.io.serverSocket.address().port)

    // double check they actually came on the server socket...
    this.io.serverSocket.on('message', onmessage)

    const pongs = await requestAll(this, true, PING_NAT, value, nodes)

    let count = 0
    for (const res of pongs) {
      if (hosts.has(res.from.host)) {
        count++
        natSampler.add(res.to.host, res.to.port)
      }
    }

    this.io.serverSocket.removeListener('message', onmessage)

    // if we got no or very few replies, consider it a fluke
    if (count < (nodes.length >= 5 ? 3 : 1)) return true

    // check that the server socket has the same ip as the client socket
    if (natSampler.host === null || this._nat.host !== natSampler.host) return true

    // check that the local port of the server socket is the same as the remote port
    // TODO: we might want a flag to opt out of this heuristic for specific remapped port servers
    if (natSampler.port === 0 || natSampler.port !== this.io.serverSocket.address().port) {
      return true
    }

    return false

    function onmessage(_, { host }) {
      hosts.add(host)
    }
  }

  _backgroundQuery(target) {
    this._refreshTicks = REFRESH_TICKS

    const backgroundCon = Math.min(this.concurrency, Math.max(2, (this.concurrency / 8) | 0))
    const q = new Query(this, target, true, FIND_NODE, null, {
      concurrency: backgroundCon
    })

    q.on('data', () => {
      // yield to other traffic
      q.concurrency = this.io.inflight.length < 3 ? this.concurrency : backgroundCon
    })

    return q
  }

  // called by health
  _online() {
    if (this.online && !this.degraded) return
    this.online = true
    this.degraded = false
    this.emit('network-update')
  }

  // called by health
  _degraded() {
    if (this.degraded) return
    this.online = true
    this.degraded = true
    this.emit('network-update')
  }

  // called by health
  _offline() {
    if (!this.online) return
    this.online = false
    this.degraded = false
    this.emit('network-update')
  }
}

DHT.OK = 0
DHT.ERROR_UNKNOWN_COMMAND = UNKNOWN_COMMAND
DHT.ERROR_INVALID_TOKEN = INVALID_TOKEN

module.exports = DHT

function localIP(udx, family = 4) {
  let host = null

  for (const n of udx.networkInterfaces()) {
    if (n.family !== family || n.internal) continue

    // mac really likes en0, mb a better way but this shouldnt be bad anywhere so return now
    if (n.name === 'en0') return n.host

    // otherwise pick the first non internal host (let the loop continue in case we see en0)
    if (host === null) host = n.host
  }

  return host || (family === 4 ? '127.0.0.1' : '::1')
}

function parseNode(s) {
  if (typeof s === 'object') return s
  if (typeof s === 'number') return { host: '127.0.0.1', port: s }
  const [host, port] = s.split(':')
  if (!port) throw new Error('Bootstrap node format is host:port')

  return {
    host,
    port: Number(port)
  }
}

function randomBytes(n) {
  const b = b4a.alloc(n)
  sodium.randombytes_buf(b)
  return b
}

function randomOffset(n) {
  return n - ((Math.random() * 0.5 * n) | 0)
}

function requestAll(dht, internal, command, value, nodes) {
  let missing = nodes.length
  const replies = []

  return new Promise((resolve) => {
    for (const node of nodes) {
      const req = dht._request(
        node,
        false,
        internal,
        command,
        null,
        value,
        null,
        onsuccess,
        onerror
      )
      if (!req) return resolve(replies)
    }

    function onsuccess(res) {
      replies.push(res)
      if (--missing === 0) resolve(replies)
    }

    function onerror() {
      if (--missing === 0) resolve(replies)
    }
  })
}

function noop() {}
exports.PING = 0
exports.PING_NAT = 1
exports.FIND_NODE = 2
exports.DOWN_HINT = 3
exports.DELAYED_PING = 4
module.exports = class DHTError extends Error {
  constructor(msg, code, fn = DHTError) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'DHTError'
  }

  static UNKNOWN_COMMAND = 1
  static INVALID_TOKEN = 2

  static REQUEST_TIMEOUT(msg = 'Request timed out') {
    return new DHTError(msg, 'REQUEST_TIMEOUT', DHTError.REQUEST_TIMEOUT)
  }

  static REQUEST_DESTROYED(msg = 'Request destroyed') {
    return new DHTError(msg, 'REQUEST_DESTROYED', DHTError.REQUEST_DESTROYED)
  }

  static IO_SUSPENDED(msg = 'I/O suspended') {
    return new DHTError(msg, 'IO_SUSPENDED', DHTError.IO_SUSPENDED)
  }
}
const MAX_HEALTH_WINDOW = 4
const OFFLINE_THRESHOLD = 2
const IDLE_THRESHOLD = 4
const DEGRADED_TIMEOUT_RATE_THRESHOLD = 0.5

module.exports = class NetworkHealth {
  constructor(dht) {
    this._dht = dht
    this._window = []
    this._head = -1
    this._offlineTicks = 0
    this._degradedTicks = 0
    this._healthyTicks = 0
    this.online = true
    this.degraded = false
  }

  get oldest() {
    return this._window[this._tail]
  }

  get previous() {
    return this._window[(this._head - 1 + MAX_HEALTH_WINDOW) % MAX_HEALTH_WINDOW]
  }

  get newest() {
    return this._window[this._head]
  }

  get responses() {
    if (!this.newest || !this.previous) return 0
    return this.newest.responses - this.previous.responses
  }

  get timeouts() {
    if (!this.newest || !this.previous) return 0
    return this.newest.timeouts - this.previous.timeouts
  }

  get timeoutsRate() {
    if (this.timeouts === 0) return 0
    return this.timeouts / (this.responses + this.timeouts)
  }

  get cold() {
    return this._window.length < MAX_HEALTH_WINDOW
  }

  get idle() {
    return this.responses + this.timeouts < IDLE_THRESHOLD
  }

  get stats() {
    return {
      online: this.online,
      degraded: this.degraded,
      cold: this.cold,
      idle: this.idle,
      responses: this.responses,
      timeouts: this.timeouts,
      timeoutsRate: this.timeoutsRate
    }
  }

  get _tail() {
    return (this._head + 1) % MAX_HEALTH_WINDOW
  }

  reset() {
    this._window = []
    this._head = -1
    this._offlineTicks = 0
    this._degradedTicks = 0
    this._healthyTicks = 0
    this.online = true
    this.degraded = false
    this._dht._online()
  }

  update() {
    // update counters before dropping oldest
    if (this.oldest?.degraded) this._degradedTicks--
    else if (this.oldest?.degraded === false) this._healthyTicks--

    // move window
    this._head = this._tail
    this._window[this._head] = {
      responses: this._dht.stats.requests.responses,
      timeouts: this._dht.stats.requests.timeouts
    }

    // skip state changes
    if (this.cold || this.idle) return

    // update newest
    this.newest.offline = this.responses === 0
    this.newest.degraded =
      !this.newest.offline && this.timeoutsRate > DEGRADED_TIMEOUT_RATE_THRESHOLD

    // update counters
    if (this.newest.offline) this._offlineTicks++
    else {
      this._offlineTicks = 0
      if (this.newest.degraded) this._degradedTicks++
      else this._healthyTicks++
    }

    // check online/offline
    if (!this.newest.offline) this.online = true
    else if (this._offlineTicks >= OFFLINE_THRESHOLD) this.online = false

    // check degraded
    if (!this.online || this._healthyTicks === MAX_HEALTH_WINDOW) this.degraded = false
    else if (this._degradedTicks === MAX_HEALTH_WINDOW) this.degraded = true

    // fire events
    if (this.online && !this.degraded) this._dht._online()
    else if (this.degraded) this._dht._degraded()
    else this._dht._offline()
  }
}
const FIFO = require('fast-fifo')
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const b4a = require('b4a')
const AdaptiveTimeout = require('adaptive-timeout')
const peer = require('./peer')
const { INVALID_TOKEN, REQUEST_TIMEOUT, REQUEST_DESTROYED, IO_SUSPENDED } = require('./errors')

const VERSION = 0b11
const RESPONSE_ID = (0b0001 << 4) | VERSION
const REQUEST_ID = (0b0000 << 4) | VERSION
const EMPTY_ARRAY = []
const MAX_WINDOW = 80

module.exports = class IO {
  constructor(
    table,
    udx,
    {
      maxWindow = MAX_WINDOW,
      port = 0,
      host = '0.0.0.0',
      anyPort = true,
      firewalled = true,
      onrequest,
      onresponse = noop,
      ontimeout = noop,
      adaptiveTimeout
    } = {}
  ) {
    this.table = table
    this.udx = udx
    this.inflight = []
    this.clientSocket = null
    this.serverSocket = null
    this.firewalled = firewalled !== false
    this.ephemeral = true
    this.congestion = new CongestionWindow(maxWindow)
    this.networkInterfaces = udx.watchNetworkInterfaces()
    this.suspended = false

    this.stats = {
      requests: {
        active: 0,
        total: 0,
        responses: 0,
        timeouts: 0,
        retries: 0
      },
      commands: [
        { tx: 0, rx: 0 }, // tx = transmitted, rx = received
        { tx: 0, rx: 0 },
        { tx: 0, rx: 0 },
        { tx: 0, rx: 0 }
      ]
    }

    this.onrequest = onrequest
    this.onresponse = onresponse
    this.ontimeout = ontimeout

    this._pending = new FIFO()
    this._rotateSecrets = 10
    this._tid = (Math.random() * 65536) | 0
    this._secrets = null
    this._drainInterval = null
    this._destroying = null
    this._binding = null

    // port can be a number or a range [start, to]
    this.portRange = port.length ? port : port === 0 ? [0, 0] : [port, port + 5]

    this._host = host
    this._anyPort = anyPort !== false
    this._boundServerPort = 0
    this._boundClientPort = 0

    this._adt = adaptiveTimeout ? new AdaptiveTimeout(adaptiveTimeout) : null
  }

  static DEFAULT_MAX_WINDOW = MAX_WINDOW

  onmessage(socket, buffer, { host, port }) {
    if (buffer.byteLength < 2 || !(port > 0 && port < 65536) || this.suspended === true) return

    const from = { id: null, host, port }
    const state = { start: 1, end: buffer.byteLength, buffer }
    const expectedSocket = this.firewalled ? this.clientSocket : this.serverSocket
    const external = socket !== expectedSocket

    if (buffer[0] === REQUEST_ID) {
      const req = Request.decode(this, socket, from, state)
      if (req === null) return
      if (
        req.token !== null &&
        !b4a.equals(req.token, this.token(req.from, 1)) &&
        !b4a.equals(req.token, this.token(req.from, 0))
      ) {
        req.error(INVALID_TOKEN, { token: true })
        return
      }
      this.onrequest(req, external)
      return
    }

    if (buffer[0] === RESPONSE_ID) {
      const res = decodeReply(from, state)
      if (res === null) return

      for (let i = 0; i < this.inflight.length; i++) {
        const req = this.inflight[i]
        if (req.tid !== res.tid) continue

        res.rtt = Date.now() - req._timestamp

        if (this._adt && req.sent <= 2) {
          this._adt.put(`${req.to.host}:${req.to.port}`, res.rtt)
        }

        if (i === this.inflight.length - 1) this.inflight.pop()
        else this.inflight[i] = this.inflight.pop()

        if (req.session) req.session._detach(req)

        // TODO: Auto retry here if errors.INVALID_TOKEN is returned?

        if (req._timeout) {
          clearTimeout(req._timeout)
          req._timeout = null
        }

        this.congestion.recv()

        if (req.internal && req.command < this.stats.commands.length) {
          this.stats.commands[req.command].rx++
        }

        this.stats.requests.active--
        this.stats.requests.responses++

        this.onresponse(res, external)
        req.onresponse(res, req)
        break
      }
    }
  }

  token(addr, i) {
    if (this._secrets === null) {
      const buf = b4a.alloc(64)
      this._secrets = [buf.subarray(0, 32), buf.subarray(32, 64)]
      sodium.randombytes_buf(this._secrets[0])
      sodium.randombytes_buf(this._secrets[1])
    }

    const token = b4a.allocUnsafe(32)
    sodium.crypto_generichash(token, b4a.from(addr.host), this._secrets[i])
    return token
  }

  async destroy() {
    if (this._destroying) return this._destroying
    this._destroying = this._destroy()
    return this._destroying
  }

  async _destroy() {
    // simplifies timing to await the bind here also, although it might be unneeded
    await this.bind()
    await this._clear(false)
  }

  async _clear(suspended) {
    if (this._drainInterval) {
      clearInterval(this._drainInterval)
      this._drainInterval = null
    }

    while (this.inflight.length) {
      const req = this.inflight.pop()
      if (req._timeout) clearTimeout(req._timeout)
      req._timeout = null
      req.destroyed = true

      if (req.session) req.session._detach(req)

      this.congestion.recv()
      this.stats.requests.active--

      req.onerror(suspended ? IO_SUSPENDED() : REQUEST_DESTROYED(), req)
    }

    await Promise.allSettled([this.serverSocket.close(), this.clientSocket.close()])

    this.networkInterfaces.destroy()
  }

  async suspend() {
    this.suspended = true
    await this._clear(true)

    this.congestion.clear()

    if (this._drainInterval) {
      clearInterval(this._drainInterval)
      this._drainInterval = null
    }
  }

  async _rebind(binding) {
    if (binding) await binding
    if (this._destroying) return this._destroying
    await this._bindSockets()
    this.networkInterfaces = this.udx.watchNetworkInterfaces()
  }

  resume() {
    this.suspended = false
    const binding = this._binding
    this._binding = this._rebind(binding)
    return this._binding
  }

  bind() {
    if (this._binding) return this._binding
    this._binding = this._bindSockets()
    return this._binding
  }

  async _bindSockets() {
    const serverSocket = this.udx.createSocket()

    const candidatePorts = []

    // Retrying previous port always has precedence
    if (this._boundServerPort) candidatePorts.push(this._boundServerPort)

    for (let i = this.portRange[0]; i < this.portRange[1]; i++) candidatePorts.push(i)

    for (const port of candidatePorts) {
      if (serverSocket.bound) break

      try {
        serverSocket.bind(port, this._host)
      } catch (err) {
        if (!this._anyPort) {
          await serverSocket.close()
          throw err
        }
      }
    }

    if (!serverSocket.bound) {
      try {
        serverSocket.bind(0, this._host)
      } catch (err) {
        await serverSocket.close()
        throw err
      }
    }

    const clientSocket = this.udx.createSocket()

    try {
      clientSocket.bind(this._boundClientPort || 0, this._host)
    } catch {
      try {
        clientSocket.bind(0, this._host)
      } catch (err) {
        await serverSocket.close()
        await clientSocket.close()
        throw err
      }
    }

    this._boundServerPort = serverSocket.address().port
    this._boundClientPort = clientSocket.address().port

    this.clientSocket = clientSocket
    this.serverSocket = serverSocket

    this.serverSocket.on('message', this.onmessage.bind(this, this.serverSocket))
    this.clientSocket.on('message', this.onmessage.bind(this, this.clientSocket))

    if (this._drainInterval === null) {
      this._drainInterval = setInterval(this._drain.bind(this), 750)
      if (this._drainInterval.unref) this._drainInterval.unref()
    }

    for (const req of this.inflight) {
      if (!req.socket) req.socket = this.firewalled ? this.clientSocket : this.serverSocket
      req.sent = 0
      req.send(false)
    }
  }

  _drain() {
    if (this._secrets !== null && --this._rotateSecrets === 0) {
      this._rotateSecrets = 10
      const tmp = this._secrets[0]
      this._secrets[0] = this._secrets[1]
      this._secrets[1] = tmp
      sodium.crypto_generichash(tmp, tmp)
    }

    this.congestion.drain()

    while (!this.congestion.isFull()) {
      const p = this._pending.shift()
      if (p === undefined) return
      p._sendNow()
    }
  }

  createRequest(to, token, internal, command, target, value, session, ttl) {
    if (this._destroying !== null) return null

    if (this._tid === 65536) this._tid = 0

    const tid = this._tid++
    const socket = this.firewalled ? this.clientSocket : this.serverSocket

    const req = new Request(
      this,
      socket,
      tid,
      null,
      to,
      token,
      internal,
      command,
      target,
      value,
      session,
      ttl || 0
    )
    this.inflight.push(req)
    if (session) session._attach(req)

    if (internal && command < this.stats.commands.length) {
      this.stats.commands[command].tx++
    }

    this.stats.requests.active++
    this.stats.requests.total++

    return req
  }
}

class Request {
  constructor(io, socket, tid, from, to, token, internal, command, target, value, session, ttl) {
    this.socket = socket
    this.tid = tid
    this.from = from
    this.to = to
    this.token = token
    this.command = command
    this.target = target
    this.value = value
    this.internal = internal
    this.session = session
    this.ttl = ttl
    this.index = -1
    this.sent = 0
    this.retries = 3
    this.destroyed = false
    this.timeout = 0

    this.oncycle = noop
    this.onerror = noop
    this.onresponse = noop

    this._buffer = null
    this._io = io
    this._timeout = null
    this._timestamp = Date.now()
  }

  static decode(io, socket, from, state) {
    try {
      const flags = c.uint.decode(state)
      const tid = c.uint16.decode(state)
      const to = peer.ipv4.decode(state)
      const id = flags & 1 ? c.fixed32.decode(state) : null
      const token = flags & 2 ? c.fixed32.decode(state) : null
      const internal = (flags & 4) !== 0
      const command = c.uint.decode(state)
      const target = flags & 8 ? c.fixed32.decode(state) : null
      const value = flags & 16 ? c.buffer.decode(state) : null

      if (id !== null) from.id = validateId(id, from)

      return new Request(
        io,
        socket,
        tid,
        from,
        to,
        token,
        internal,
        command,
        target,
        value,
        null,
        0
      )
    } catch {
      return null
    }
  }

  reply(value, opts = {}) {
    const socket = opts.socket || this.socket
    const to = opts.to || this.from
    this._sendReply(0, value || null, opts.token !== false, opts.closerNodes !== false, to, socket)
  }

  error(code, opts = {}) {
    const socket = opts.socket || this.socket
    const to = opts.to || this.from
    this._sendReply(code, null, opts.token === true, opts.closerNodes !== false, to, socket)
  }

  relay(value, to, opts) {
    const socket = (opts && opts.socket) || this.socket
    const buffer = this._encodeRequest(null, value, to, socket)
    socket.trySend(buffer, to.port, to.host, this.ttl)
  }

  send(force = false) {
    if (this.destroyed) return

    if (this.socket === null) return
    if (this._buffer === null) {
      this._buffer = this._encodeRequest(this.token, this.value, this.to, this.socket)
    }

    if (!force && this._io.congestion.isFull()) {
      this._io._pending.push(this)
      return
    }

    this._sendNow()
  }

  sendReply(error, value, token, hasCloserNodes) {
    this._sendReply(error, value, token, hasCloserNodes, this.from, this.socket, null)
  }

  _sendNow() {
    if (this.destroyed) return
    this.sent++
    this._io.congestion.send()
    this.socket.trySend(this._buffer, this.to.port, this.to.host, this.ttl)
    if (this._timeout) clearTimeout(this._timeout)
    const value =
      this.timeout || this._io._adt?.get(`${this.to.host}:${this.to.port}`, this.sent) || 1000
    this._timeout = setTimeout(oncycle, value, this)
  }

  destroy(err) {
    if (this.destroyed) return
    this.destroyed = true

    if (this._timeout) {
      clearTimeout(this._timeout)
      this._timeout = null
    }

    const i = this._io.inflight.indexOf(this)
    if (i === -1) return

    if (i === this._io.inflight.length - 1) this._io.inflight.pop()
    else this._io.inflight[i] = this._io.inflight.pop()

    if (this.session) this.session._detach(this)

    this._io.stats.requests.active--
    this._io.congestion.recv()

    this.onerror(err || REQUEST_DESTROYED(), this)
  }

  _sendReply(error, value, token, hasCloserNodes, from, socket) {
    if (socket === null || this.destroyed) return

    const id = this._io.ephemeral === false && socket === this._io.serverSocket
    const closerNodes =
      this.target !== null && hasCloserNodes ? this._io.table.closest(this.target) : EMPTY_ARRAY
    const state = { start: 0, end: 1 + 1 + 6 + 2, buffer: null } // (type | version) + flags + to + tid

    if (id) state.end += 32
    if (token) state.end += 32
    if (closerNodes.length > 0) peer.ipv4Array.preencode(state, closerNodes)
    if (error > 0) c.uint.preencode(state, error)
    if (value) c.buffer.preencode(state, value)

    state.buffer = b4a.allocUnsafe(state.end)
    state.buffer[state.start++] = RESPONSE_ID
    state.buffer[state.start++] =
      (id ? 1 : 0) |
      (token ? 2 : 0) |
      (closerNodes.length > 0 ? 4 : 0) |
      (error > 0 ? 8 : 0) |
      (value ? 16 : 0)

    c.uint16.encode(state, this.tid)
    peer.ipv4.encode(state, from)

    if (id) c.fixed32.encode(state, this._io.table.id)
    if (token) c.fixed32.encode(state, this._io.token(from, 1))
    if (closerNodes.length > 0) peer.ipv4Array.encode(state, closerNodes)
    if (error > 0) c.uint.encode(state, error)
    if (value) c.buffer.encode(state, value)

    socket.trySend(state.buffer, from.port, from.host, this.ttl)
  }

  _encodeRequest(token, value, to, socket) {
    const id = this._io.ephemeral === false && socket === this._io.serverSocket
    const state = { start: 0, end: 1 + 1 + 6 + 2, buffer: null } // (type | version) + flags + to + tid

    if (id) state.end += 32
    if (token) state.end += 32

    c.uint.preencode(state, this.command)

    if (this.target) state.end += 32
    if (value) c.buffer.preencode(state, value)

    state.buffer = b4a.allocUnsafe(state.end)
    state.buffer[state.start++] = REQUEST_ID
    state.buffer[state.start++] =
      (id ? 1 : 0) |
      (token ? 2 : 0) |
      (this.internal ? 4 : 0) |
      (this.target ? 8 : 0) |
      (value ? 16 : 0)

    c.uint16.encode(state, this.tid)
    peer.ipv4.encode(state, to)

    if (id) c.fixed32.encode(state, this._io.table.id)
    if (token) c.fixed32.encode(state, token)

    c.uint.encode(state, this.command)

    if (this.target) c.fixed32.encode(state, this.target)
    if (value) c.buffer.encode(state, value)

    return state.buffer
  }
}

class CongestionWindow {
  constructor(maxWindow) {
    this._i = 0
    this._total = 0
    this._window = [0, 0, 0, 0]
    this._maxWindow = maxWindow
  }

  clear() {
    this._i = 0
    this._total = 0
    this._window = [0, 0, 0, 0]
  }

  isFull() {
    return this._total >= 2 * this._maxWindow || this._window[this._i] >= this._maxWindow
  }

  recv() {
    if (this._window[this._i] > 0) {
      this._window[this._i]--
      this._total--
    }
  }

  send() {
    this._total++
    this._window[this._i]++
  }

  drain() {
    this._i = (this._i + 1) & 3
    this._total -= this._window[this._i]
    this._window[this._i] = 0 // clear oldest
  }
}

function noop() {}

function oncycle(req) {
  req._timeout = null
  req.oncycle(req)
  if (req.sent > req.retries) {
    req._io.stats.requests.timeouts++
    req.destroy(REQUEST_TIMEOUT())
    req._io.ontimeout(req)
  } else {
    req._io.stats.requests.retries++
    req.send()
  }
}

function decodeReply(from, state) {
  try {
    const flags = c.uint.decode(state)
    const tid = c.uint16.decode(state)
    const to = peer.ipv4.decode(state)
    const id = flags & 1 ? c.fixed32.decode(state) : null
    const token = flags & 2 ? c.fixed32.decode(state) : null
    const closerNodes = flags & 4 ? peer.ipv4Array.decode(state) : null
    const error = flags & 8 ? c.uint.decode(state) : 0
    const value = flags & 16 ? c.buffer.decode(state) : null

    if (id !== null) from.id = validateId(id, from)

    return { tid, rtt: 0, from, to, token, closerNodes, error, value }
  } catch {
    return null
  }
}

function validateId(id, from) {
  const expected = peer.id(from.host, from.port)
  return b4a.equals(expected, id) ? expected : null
}
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const net = require('compact-encoding-net')
const b4a = require('b4a')

const ipv4 = {
  ...net.ipv4Address,
  decode(state) {
    const ip = net.ipv4Address.decode(state)
    return {
      id: null, // populated by the callee
      host: ip.host,
      port: ip.port
    }
  }
}

module.exports = { id, ipv4, ipv4Array: c.array(ipv4) }

function id(host, port, out = b4a.allocUnsafeSlow(32)) {
  const addr = out.subarray(0, 6)
  ipv4.encode({ start: 0, end: 6, buffer: addr }, { host, port })
  sodium.crypto_generichash(out, addr)
  return out
}
const { Readable, getStreamError } = require('streamx')
const b4a = require('b4a')
const peer = require('./peer')
const { DOWN_HINT } = require('./commands')

const DONE = []
const DOWN = []

module.exports = class Query extends Readable {
  constructor(dht, target, internal, command, value, opts = {}) {
    super()

    dht.stats.queries.total++
    dht.stats.queries.active++

    this.force = !!opts.force
    this.dht = dht
    this.k = this.dht.table.k
    this.target = target
    this.internal = internal
    this.command = command
    this.value = value
    this.errors = 0
    this.successes = 0
    this.concurrency = opts.concurrency || this.dht.concurrency
    this.inflight = 0
    this.map = opts.map || defaultMap
    this.retries =
      opts.retries === 0 ? 0 : opts.retries || (this.internal && command === DOWN_HINT ? 3 : 5)
    this.closestReplies = []

    this._slow = 0
    this._slowdown = false
    this._seen = new Map()
    this._pending = []
    this._fromTable = false
    this._commit = opts.commit === true ? autoCommit : opts.commit || null
    this._commiting = false
    this._session = opts.session || dht.session()
    this._autoDestroySession = !opts.session
    this._onlyClosestNodes = false

    this._onvisitbound = this._onvisit.bind(this)
    this._onerrorbound = this._onerror.bind(this)
    this._oncyclebound = this._oncycle.bind(this)

    const nodes = opts.nodes || opts.closestNodes
    const replies = opts.replies || opts.closestReplies

    // add them reverse as we pop below
    if (nodes) {
      for (let i = nodes.length - 1; i >= 0; i--) {
        const node = nodes[i]
        this._addPending(
          {
            id: node.id || peer.id(node.host, node.port),
            host: node.host,
            port: node.port
          },
          null
        )
      }
    } else if (replies) {
      for (let i = replies.length - 1; i >= 0; i--) {
        this._addPending(replies[i].from, null)
      }
    }

    if (opts.onlyClosestNodes) this._onlyClosestNodes = true
  }

  get closestNodes() {
    const nodes = new Array(this.closestReplies.length)

    for (let i = 0; i < nodes.length; i++) {
      nodes[i] = this.closestReplies[i].from
    }

    return nodes
  }

  finished() {
    return new Promise((resolve, reject) => {
      if (this.destroyed) {
        const error = getStreamError(this)
        if (error) reject(error)
        else resolve()
        return
      }

      const self = this
      let error = null

      this.resume()
      this.on('error', onerror)
      this.on('close', onclose)

      function onclose() {
        self.removeListener('error', onerror)
        self.removeListener('close', onclose)
        if (error) reject(error)
        else resolve()
      }

      function onerror(err) {
        error = err
      }
    })
  }

  _addFromTable() {
    if (this._pending.length >= this.k) return
    this._fromTable = true

    const closest = this.dht.table.closest(this.target, this.k - this._pending.length)

    for (const node of closest) {
      this._addPending({ id: node.id, host: node.host, port: node.port }, null)
    }
  }

  async _open(cb) {
    this._addFromTable()
    if (this._pending.length >= this.k) return cb(null)

    for await (const node of this.dht._resolveBootstrapNodes()) {
      this._addPending(node, null)
    }

    cb(null)
  }

  _isCloser(id) {
    return (
      this.closestReplies.length < this.k ||
      this._compare(id, this.closestReplies[this.closestReplies.length - 1].from.id) < 0
    )
  }

  _addPending(node, ref) {
    if (this._onlyClosestNodes) return false

    const addr = node.host + ':' + node.port
    const refs = this._seen.get(addr)
    const isCloser = this._isCloser(node.id)

    if (refs === DONE) {
      return isCloser
    }

    if (refs === DOWN) {
      if (ref) this._downHint(ref, node)
      return isCloser
    }

    if (refs) {
      if (ref !== null) refs.push(ref)
      return isCloser
    }

    if (!isCloser) {
      return false
    }

    this._seen.set(addr, ref === null ? [] : [ref])
    this._pending.push(node)

    return true
  }

  _read(cb) {
    this._readMore()
    cb(null)
  }

  _readMore() {
    if (this.destroying || this._commiting) return

    const concurrency = (this._slowdown ? 3 : this.concurrency) + this._slow

    while (this.inflight < concurrency && this._pending.length > 0) {
      const next = this._pending.pop()
      if (next && next.id && !this._isCloser(next.id)) continue
      this._visit(next)
    }

    // if reusing closest nodes, slow down after the first readMore tick to allow
    // the closest node a chance to reply before going broad to question more
    if (!this._fromTable && this.successes === 0 && this.errors === 0) {
      this._slowdown = true
    }

    if (this._pending.length > 0) return

    // if no inflight OR all the queries we are waiting on are marked as slow and we have a full result.
    if (
      this.inflight === 0 ||
      (this._slow === this.inflight && this.closestReplies.length >= this.k)
    ) {
      // if more than 3/4 failed and we only used cached nodes, try again from the routing table
      if (!this._fromTable && this.successes < this.k / 4) {
        this._addFromTable()
        this._readMore()
        return
      }

      this._flush()
    }
  }

  _flush() {
    if (this._commiting) return
    this._commiting = true

    if (this._commit === null) {
      this.push(null)
      return
    }

    const p = []
    for (const m of this.closestReplies) p.push(this._commit(m, this.dht, this))
    this._endAfterCommit(p)
  }

  _endAfterCommit(ps) {
    if (!ps.length) {
      this.destroy(new Error('Too few nodes responded'))
      return
    }

    const self = this

    let pending = ps.length
    let success = 0

    for (const p of ps) p.then(ondone, onerror)

    function ondone() {
      success++
      if (--pending === 0) self.push(null)
    }

    function onerror(err) {
      if (--pending > 0) return
      if (success) self.push(null)
      else self.destroy(err)
    }
  }

  _dec(req) {
    if (req.oncycle === noop) {
      this._slow--
    } else {
      req.oncycle = noop
    }
    this.inflight--
  }

  _onvisit(m, req) {
    this._dec(req)

    const addr = req.to.host + ':' + req.to.port
    this._seen.set(addr, DONE)

    if (this._commiting) return

    if (m.error === 0) this.successes++
    else this.errors++

    if (m.error === 0 && m.from.id !== null && this._isCloser(m.from.id)) this._pushClosest(m)

    if (m.closerNodes !== null) {
      for (const node of m.closerNodes) {
        node.id = peer.id(node.host, node.port)
        if (this.dht._filterNode !== null && !this.dht._filterNode(node)) continue
        if (b4a.equals(node.id, this.dht.table.id)) continue
        // TODO: we could continue here instead of breaking to ensure that one of the nodes in the closer list
        // is later marked as DOWN that we gossip that back
        if (!this._addPending(node, m.from)) break
      }
    }

    if (!this._fromTable && this.successes + this.errors >= this.concurrency) {
      this._slowdown = false
    }

    if (m.error !== 0) {
      this._readMore()
      return
    }

    const data = this.map(m)
    if (!data || this.push(data) !== false) {
      this._readMore()
    }
  }

  _onerror(err, req) {
    const addr = req.to.host + ':' + req.to.port
    const refs = this._seen.get(addr)

    if (err.code === 'REQUEST_TIMEOUT') {
      this._seen.set(addr, DOWN)
      for (const node of refs) this._downHint(node, req.to)
    }

    this._dec(req)
    this.errors++
    this._readMore()
  }

  _oncycle(req) {
    req.oncycle = noop
    this._slow++
    this._readMore()
  }

  _downHint(node, down) {
    // Check rate limit
    if (
      this.dht._downHintsRateLimit !== -1 &&
      this.dht._downHintsSentPerTick >= this.dht._downHintsRateLimit
    ) {
      return null
    }

    this.dht._downHintsSentPerTick++

    const state = { start: 0, end: 6, buffer: b4a.allocUnsafe(6) }
    peer.ipv4.encode(state, down)
    this.dht._request(node, false, true, DOWN_HINT, null, state.buffer, this._session, noop, noop)
  }

  _pushClosest(m) {
    this.closestReplies.push(m)
    for (let i = this.closestReplies.length - 2; i >= 0; i--) {
      const prev = this.closestReplies[i]
      const cmp = this._compare(prev.from.id, m.from.id)
      // if sorted, done!
      if (cmp < 0) break
      // if dup, splice it out (rare)
      if (cmp === 0) {
        this.closestReplies.splice(i + 1, 1)
        break
      }
      // swap and continue down
      this.closestReplies[i + 1] = prev
      this.closestReplies[i] = m
    }
    if (this.closestReplies.length > this.k) this.closestReplies.pop()
  }

  _compare(a, b) {
    for (let i = 0; i < a.length; i++) {
      if (a[i] === b[i]) continue
      const t = this.target[i]
      return (t ^ a[i]) - (t ^ b[i])
    }
    return 0
  }

  _visit(to) {
    this.inflight++

    const req = this.dht._request(
      to,
      this.force,
      this.internal,
      this.command,
      this.target,
      this.value,
      this._session,
      this._onvisitbound,
      this._onerrorbound
    )
    if (req === null) {
      this.destroy(new Error('Node was destroyed'))
      return
    }
    req.retries = this.retries
    req.oncycle = this._oncyclebound
    if (this.force) req.retries = 0
  }

  _destroy(cb) {
    this.dht.stats.queries.active--
    if (this._autoDestroySession) this._session.destroy()
    cb(null)
  }
}

function autoCommit(reply, dht, query) {
  if (!reply.token) return Promise.reject(new Error('No token received for closest node'))
  return dht.request(
    {
      token: reply.token,
      target: query.target,
      command: query.command,
      value: query.value
    },
    reply.from
  )
}

function defaultMap(m) {
  return m
}

function noop() {}
module.exports = class Session {
  constructor(dht) {
    this.dht = dht
    this.inflight = []
  }

  _attach(req) {
    req.index = this.inflight.push(req) - 1
  }

  _detach(req) {
    const i = req.index
    if (i === -1) return
    req.index = -1

    if (i === this.inflight.length - 1) this.inflight.pop()
    else {
      const req = (this.inflight[i] = this.inflight.pop())
      req.index = i
    }
  }

  query({ target, command, value }, opts = {}) {
    return this.dht.query({ target, command, value }, { ...opts, session: this })
  }

  request({ token, command, target, value }, { host, port }, opts = {}) {
    return this.dht.request(
      { token, command, target, value },
      { host, port },
      { ...opts, session: this }
    )
  }

  ping({ host, port }, opts = {}) {
    return this.dht.ping({ host, port }, { ...opts, session: this })
  }

  destroy(err) {
    while (this.inflight.length) {
      const req = this.inflight[0]
      // prevent destroyed requests from contributing to congestion counts
      this.dht.io.congestion.recv()
      req.destroy(err)
    }
  }
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return uint24.decode(state) + 0x1000000 * uint32.decode(state)
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return uint32.decode(state) + 0x100000000 * uint32.decode(state)
  }
})

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "2.19.2",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    if (b.byteLength === 0) return null
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "dht-rpc",
  "version": "6.26.4",
  "description": "Make RPC calls over a Kademlia based DHT",
  "main": "index.js",
  "files": [
    "index.js",
    "lib/*.js"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "dependencies": {
    "adaptive-timeout": "^1.0.1",
    "b4a": "^1.6.1",
    "bare-events": "^2.2.0",
    "compact-encoding": "^2.11.0",
    "compact-encoding-net": "^1.2.0",
    "fast-fifo": "^1.1.0",
    "kademlia-routing-table": "^1.0.1",
    "nat-sampler": "^1.0.1",
    "sodium-universal": "^5.0.0",
    "streamx": "^2.13.2",
    "time-ordered-set": "^2.0.0",
    "udx-native": "^1.5.3"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "test-suspend": "^1.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "test": "npm run test:node && npm run test:bare",
    "test:bare": "brittle-bare --coverage test.js",
    "lint": "prettier --check . && lunte",
    "test:node": "brittle-node --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/dht-rpc.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/dht-rpc/issues"
  },
  "homepage": "https://github.com/holepunchto/dht-rpc#"
}
module.exports = require('bare-events')
{
  "name": "events-universal",
  "version": "1.0.1",
  "description": "Universal wrapper for the Node.js events module",
  "exports": {
    "./package": "./package.json",
    ".": {
      "bare": "./bare.js",
      "react-native": "./react-native.js",
      "default": "./default.js"
    }
  },
  "files": [
    "index.js",
    "default.js",
    "bare.js",
    "react-native.js"
  ],
  "scripts": {
    "test": "prettier . --check"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/events-universal.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/events-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/events-universal#readme",
  "dependencies": {
    "bare-events": "^2.7.0"
  },
  "devDependencies": {
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^1.0.0"
  }
}
module.exports = class FixedFIFO {
  constructor (hwm) {
    if (!(hwm > 0) || ((hwm - 1) & hwm) !== 0) throw new Error('Max size for a FixedFIFO should be a power of two')
    this.buffer = new Array(hwm)
    this.mask = hwm - 1
    this.top = 0
    this.btm = 0
    this.next = null
  }

  clear () {
    this.top = this.btm = 0
    this.next = null
    this.buffer.fill(undefined)
  }

  push (data) {
    if (this.buffer[this.top] !== undefined) return false
    this.buffer[this.top] = data
    this.top = (this.top + 1) & this.mask
    return true
  }

  shift () {
    const last = this.buffer[this.btm]
    if (last === undefined) return undefined
    this.buffer[this.btm] = undefined
    this.btm = (this.btm + 1) & this.mask
    return last
  }

  peek () {
    return this.buffer[this.btm]
  }

  isEmpty () {
    return this.buffer[this.btm] === undefined
  }
}
const FixedFIFO = require('./fixed-size')

module.exports = class FastFIFO {
  constructor (hwm) {
    this.hwm = hwm || 16
    this.head = new FixedFIFO(this.hwm)
    this.tail = this.head
    this.length = 0
  }

  clear () {
    this.head = this.tail
    this.head.clear()
    this.length = 0
  }

  push (val) {
    this.length++
    if (!this.head.push(val)) {
      const prev = this.head
      this.head = prev.next = new FixedFIFO(2 * this.head.buffer.length)
      this.head.push(val)
    }
  }

  shift () {
    if (this.length !== 0) this.length--
    const val = this.tail.shift()
    if (val === undefined && this.tail.next) {
      const next = this.tail.next
      this.tail.next = null
      this.tail = next
      return this.tail.shift()
    }

    return val
  }

  peek () {
    const val = this.tail.peek()
    if (val === undefined && this.tail.next) return this.tail.next.peek()
    return val
  }

  isEmpty () {
    return this.length === 0
  }
}
{
  "name": "fast-fifo",
  "version": "1.3.2",
  "description": "A fast fifo implementation similar to the one powering nextTick in Node.js core",
  "main": "index.js",
  "files": [
    "./index.js",
    "./fixed-size.js"
  ],
  "dependencies": {},
  "devDependencies": {
    "standard": "^17.1.0",
    "brittle": "^3.3.2"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/fast-fifo.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/fast-fifo/issues"
  },
  "homepage": "https://github.com/mafintosh/fast-fifo"
}
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const b4a = require('b4a')

// https://en.wikipedia.org/wiki/Merkle_tree#Second_preimage_attack
const LEAF_TYPE = b4a.from([0])
const PARENT_TYPE = b4a.from([1])
const ROOT_TYPE = b4a.from([2])

const HYPERCORE = b4a.from('hypercore')

exports.keyPair = function (seed) {
  // key pairs might stay around for a while, so better not to use a default slab to avoid retaining it completely
  const slab = b4a.allocUnsafeSlow(sodium.crypto_sign_PUBLICKEYBYTES + sodium.crypto_sign_SECRETKEYBYTES)
  const publicKey = slab.subarray(0, sodium.crypto_sign_PUBLICKEYBYTES)
  const secretKey = slab.subarray(sodium.crypto_sign_PUBLICKEYBYTES)

  if (seed) sodium.crypto_sign_seed_keypair(publicKey, secretKey, seed)
  else sodium.crypto_sign_keypair(publicKey, secretKey)

  return {
    publicKey,
    secretKey
  }
}

exports.validateKeyPair = function (keyPair) {
  const pk = b4a.allocUnsafe(sodium.crypto_sign_PUBLICKEYBYTES)
  sodium.crypto_sign_ed25519_sk_to_pk(pk, keyPair.secretKey)
  return b4a.equals(pk, keyPair.publicKey)
}

exports.sign = function (message, secretKey) {
  // Dedicated slab for the signature, to avoid retaining unneeded mem and for security
  const signature = b4a.allocUnsafeSlow(sodium.crypto_sign_BYTES)
  sodium.crypto_sign_detached(signature, message, secretKey)
  return signature
}

exports.verify = function (message, signature, publicKey) {
  if (signature.byteLength !== sodium.crypto_sign_BYTES) return false
  if (publicKey.byteLength !== sodium.crypto_sign_PUBLICKEYBYTES) return false
  return sodium.crypto_sign_verify_detached(signature, message, publicKey)
}

exports.encrypt = function (message, publicKey) {
  const ciphertext = b4a.alloc(message.byteLength + sodium.crypto_box_SEALBYTES)
  sodium.crypto_box_seal(ciphertext, message, publicKey)
  return ciphertext
}

exports.decrypt = function (ciphertext, keyPair) {
  if (ciphertext.byteLength < sodium.crypto_box_SEALBYTES) return null

  const plaintext = b4a.alloc(ciphertext.byteLength - sodium.crypto_box_SEALBYTES)

  if (!sodium.crypto_box_seal_open(plaintext, ciphertext, keyPair.publicKey, keyPair.secretKey)) {
    return null
  }

  return plaintext
}

exports.encryptionKeyPair = function (seed) {
  const publicKey = b4a.alloc(sodium.crypto_box_PUBLICKEYBYTES)
  const secretKey = b4a.alloc(sodium.crypto_box_SECRETKEYBYTES)

  if (seed) {
    sodium.crypto_box_seed_keypair(publicKey, secretKey, seed)
  } else {
    sodium.crypto_box_keypair(publicKey, secretKey)
  }

  return {
    publicKey,
    secretKey
  }
}

exports.data = function (data) {
  const out = b4a.allocUnsafe(32)

  sodium.crypto_generichash_batch(out, [
    LEAF_TYPE,
    c.encode(c.uint64, data.byteLength),
    data
  ])

  return out
}

exports.parent = function (a, b) {
  if (a.index > b.index) {
    const tmp = a
    a = b
    b = tmp
  }

  const out = b4a.allocUnsafe(32)

  sodium.crypto_generichash_batch(out, [
    PARENT_TYPE,
    c.encode(c.uint64, a.size + b.size),
    a.hash,
    b.hash
  ])

  return out
}

exports.tree = function (roots, out) {
  const buffers = new Array(3 * roots.length + 1)
  let j = 0

  buffers[j++] = ROOT_TYPE

  for (let i = 0; i < roots.length; i++) {
    const r = roots[i]
    buffers[j++] = r.hash
    buffers[j++] = c.encode(c.uint64, r.index)
    buffers[j++] = c.encode(c.uint64, r.size)
  }

  if (!out) out = b4a.allocUnsafe(32)
  sodium.crypto_generichash_batch(out, buffers)
  return out
}

exports.hash = function (data, out) {
  if (!out) out = b4a.allocUnsafe(32)
  if (!Array.isArray(data)) data = [data]

  sodium.crypto_generichash_batch(out, data)

  return out
}

exports.randomBytes = function (n) {
  const buf = b4a.allocUnsafe(n)
  sodium.randombytes_buf(buf)
  return buf
}

exports.discoveryKey = function (key) {
  if (!key || key.byteLength !== 32) throw new Error('Must pass a 32 byte buffer')
  // Discovery keys might stay around for a while, so better not to use slab memory (for better gc)
  const digest = b4a.allocUnsafeSlow(32)
  sodium.crypto_generichash(digest, HYPERCORE, key)
  return digest
}

if (sodium.sodium_free) {
  exports.free = function (secureBuf) {
    if (secureBuf.secure) sodium.sodium_free(secureBuf)
  }
} else {
  exports.free = function () {}
}

exports.namespace = function (name, count) {
  const ids = typeof count === 'number' ? range(count) : count

  // Namespaces are long-lived, so better to use a dedicated slab
  const buf = b4a.allocUnsafeSlow(32 * ids.length)

  const list = new Array(ids.length)

  // ns is emhemeral, so default slab
  const ns = b4a.allocUnsafe(33)
  sodium.crypto_generichash(ns.subarray(0, 32), typeof name === 'string' ? b4a.from(name) : name)

  for (let i = 0; i < list.length; i++) {
    list[i] = buf.subarray(32 * i, 32 * i + 32)
    ns[32] = ids[i]
    sodium.crypto_generichash(list[i], ns)
  }

  return list
}

function range (count) {
  const arr = new Array(count)
  for (let i = 0; i < count; i++) arr[i] = i
  return arr
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return uint24.decode(state) + 0x1000000 * uint32.decode(state)
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return uint32.decode(state) + 0x100000000 * uint32.decode(state)
  }
})

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "2.19.2",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    if (b.byteLength === 0) return null
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "hypercore-crypto",
  "version": "3.6.1",
  "description": "The crypto primitives used in hypercore, extracted into a separate module",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.6.6",
    "compact-encoding": "^2.15.0",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "brittle": "^3.5.0",
    "standard": "^17.1.0"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/hypercore-crypto.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/hypercore-crypto/issues"
  },
  "homepage": "https://github.com/mafintosh/hypercore-crypto"
}
const z32 = require('z32')
const b4a = require('b4a')

module.exports = {
  encode,
  decode,
  normalize,
  isValid
}

function encode (key) {
  if (!b4a.isBuffer(key)) throw new Error('Key must be a Buffer')
  if (key.byteLength !== 32) throw new Error('Key must be 32-bytes long')
  return z32.encode(key)
}

function decode (id) {
  if (b4a.isBuffer(id)) {
    if (id.byteLength !== 32) throw new Error('ID must be 32-bytes long')
    return id
  }
  if (typeof id === 'string') {
    if (id.startsWith('pear://')) id = id.slice(7).split('/')[0]
    if (id.length === 52) return z32.decode(id)
    if (id.length === 64) {
      const buf = b4a.from(id, 'hex')
      if (buf.byteLength === 32) return buf
    }
  }
  throw new Error('Invalid Hypercore key')
}

function normalize (any) {
  return encode(decode(any))
}

function isValid (any) {
  try {
    decode(any)
    return true
  } catch {
    return false
  }
}
{
  "name": "hypercore-id-encoding",
  "version": "1.3.0",
  "description": "Convert Hypercore keys to/from z-base32 or hex",
  "main": "index.js",
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.5.3",
    "z32": "^1.0.0"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "hypercore": "^10.0.0",
    "random-access-memory": "^6.0.0",
    "standard": "^17.1.0"
  },
  "license": "Apache-2.0",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/hypercore-id-encoding.git"
  },
  "keywords": [],
  "author": "",
  "bugs": {
    "url": "https://github.com/holepunchto/hypercore-id-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/hypercore-id-encoding#readme"
}
const c = require('compact-encoding')
const { getEncoding } = require('./spec/hyperschema')

const HyperdhtAddress = getEncoding('@hyperdht/address')

function decode(buf) {
  const addr = c.decode(HyperdhtAddress, buf)
  return addr
}

function encode(key, nodes) {
  return c.encode(HyperdhtAddress, { key, nodes })
}

module.exports = { decode, encode }
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return uint24.decode(state) + 0x1000000 * uint32.decode(state)
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return uint32.decode(state) + 0x100000000 * uint32.decode(state)
  }
})

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "2.19.2",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    if (b.byteLength === 0) return null
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "hyperdht-address",
  "version": "1.0.1",
  "description": "hyperdht-address",
  "main": "index.js",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    }
  },
  "files": [
    "package.json",
    "index.js",
    "index.d.ts",
    "spec"
  ],
  "devDependencies": {
    "b4a": "^1.8.0",
    "brittle": "^3.19.0",
    "lunte": "^1.2.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && lunte && brittle-bare test/index.js",
    "lint": "lunte"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/hyperdht-address.git"
  },
  "author": "Holepunch Inc",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/hyperdht-address/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperdht-address",
  "dependencies": {
    "compact-encoding": "^2.19.0",
    "hyperschema": "^1.20.1"
  }
}
// This file is autogenerated by the hyperschema compiler
// Schema Version: 2
/* eslint-disable camelcase */
/* eslint-disable quotes */
/* eslint-disable space-before-function-paren */

const { c } = require('hyperschema/runtime')

const VERSION = 2

// eslint-disable-next-line no-unused-vars
let version = VERSION

// @hyperdht/address.nodes
const encoding0_1 = c.array(c.ipv4Address)

// @hyperdht/address
const encoding0 = {
  preencode(state, m) {
    c.fixed32.preencode(state, m.key)
    state.end++ // max flag is 1 so always one byte

    if (version >= 2 && m.nodes) encoding0_1.preencode(state, m.nodes)
  },
  encode(state, m) {
    const flags = version >= 2 && m.nodes ? 1 : 0

    c.fixed32.encode(state, m.key)
    c.uint.encode(state, flags)

    if (version >= 2 && m.nodes) encoding0_1.encode(state, m.nodes)
  },
  decode(state) {
    const r0 = c.fixed32.decode(state)
    const flags = state.start < state.end ? c.uint.decode(state) : 0

    return {
      key: r0,
      nodes: version >= 2 && (flags & 1) !== 0 ? encoding0_1.decode(state) : null
    }
  }
}

function setVersion(v) {
  version = v
}

function encode(name, value, v = VERSION) {
  version = v
  return c.encode(getEncoding(name), value)
}

function decode(name, buffer, v = VERSION) {
  version = v
  return c.decode(getEncoding(name), buffer)
}

function getEnum(name) {
  switch (name) {
    default:
      throw new Error('Enum not found ' + name)
  }
}

function getEncoding(name) {
  switch (name) {
    case '@hyperdht/address':
      return encoding0
    default:
      throw new Error('Encoder not found ' + name)
  }
}

function getStruct(name, v = VERSION) {
  const enc = getEncoding(name)
  return {
    preencode(state, m) {
      version = v
      enc.preencode(state, m)
    },
    encode(state, m) {
      version = v
      enc.encode(state, m)
    },
    decode(state) {
      version = v
      return enc.decode(state)
    }
  }
}

const resolveStruct = getStruct // compat

module.exports = {
  resolveStruct,
  getStruct,
  getEnum,
  getEncoding,
  encode,
  decode,
  setVersion,
  version
}
const DHT = require('dht-rpc')
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const b4a = require('b4a')
const safetyCatch = require('safety-catch')
const m = require('./lib/messages')
const SocketPool = require('./lib/socket-pool')
const Persistent = require('./lib/persistent')
const Router = require('./lib/router')
const Cache = require('xache')
const Server = require('./lib/server')
const connect = require('./lib/connect')
const { FIREWALL, BOOTSTRAP_NODES, KNOWN_NODES, COMMANDS } = require('./lib/constants')
const { hash, createKeyPair } = require('./lib/crypto')
const RawStreamSet = require('./lib/raw-stream-set')
const ConnectionPool = require('./lib/connection-pool')
const { STREAM_NOT_CONNECTED } = require('./lib/errors')

const DEFAULTS = {
  ...DHT.DEFAULTS,
  connectionKeepAlive: 5000,
  randomPunchInterval: 20000
}

class HyperDHT extends DHT {
  constructor(opts = {}) {
    const port = opts.port || 49737
    const bootstrap = opts.bootstrap || BOOTSTRAP_NODES
    const nodes = opts.nodes || KNOWN_NODES

    super({ ...opts, port, bootstrap, nodes, filterNode })

    const { router, relayAddresses, persistent } = defaultCacheOpts(opts)

    this.defaultKeyPair = opts.keyPair || createKeyPair(opts.seed)
    this.listening = new Set()
    this.connectionKeepAlive =
      opts.connectionKeepAlive === false
        ? 0
        : opts.connectionKeepAlive || DEFAULTS.connectionKeepAlive

    // stats is inherited from dht-rpc so fwd the ones from there
    this.stats = {
      punches: { consistent: 0, random: 0, open: 0 },
      relaying: { attempts: 0, successes: 0, aborts: 0 },
      ...this.stats
    }
    this.rawStreams = new RawStreamSet(this)
    this.plugins = new Map()

    this._router = new Router(this, router)
    this._socketPool = new SocketPool(this, opts.host || '0.0.0.0')
    this._persistent = null
    this._validatedLocalAddresses = new Map()
    this._relayAddressesCache = new Cache(relayAddresses)

    this._deferRandomPunch = !!opts.deferRandomPunch
    this._lastRandomPunch = this._deferRandomPunch ? Date.now() : 0
    this._connectable = true
    this._randomPunchInterval = opts.randomPunchInterval || DEFAULTS.randomPunchInterval // min 20s between random punches...
    this._randomPunches = 0
    this._randomPunchLimit = 1 // set to one for extra safety for now

    this.once('persistent', () => {
      this._persistent = new Persistent(this, persistent)
      for (const plugin of this.plugins.values()) plugin.onpersistent()
    })

    this.on('network-change', () => {
      for (const server of this.listening) server.refresh()
    })

    this.on('network-update', () => {
      if (!this.online) return
      for (const server of this.listening) server.notifyOnline()
    })
  }

  static DEFAULTS = DEFAULTS

  connect(remotePublicKey, opts) {
    return connect(this, remotePublicKey, opts)
  }

  createServer(opts, onconnection) {
    if (typeof opts === 'function') return this.createServer({}, opts)
    if (opts && opts.onconnection) onconnection = opts.onconnection
    const s = new Server(this, opts)
    if (onconnection) s.on('connection', onconnection)
    return s
  }

  pool() {
    return new ConnectionPool(this)
  }

  async resume({ log = noop } = {}) {
    if (this._deferRandomPunch) this._lastRandomPunch = Date.now()
    await super.resume({ log })
    const resuming = []
    for (const server of this.listening) resuming.push(server.resume())
    log('Resuming hyperdht servers')
    await Promise.allSettled(resuming)
    log('Done, hyperdht fully resumed')
  }

  async suspend({ log = noop } = {}) {
    this._connectable = false // just so nothing gets connected during suspension
    const suspending = []
    for (const server of this.listening) suspending.push(server.suspend())
    log('Suspending all hyperdht servers')
    await Promise.allSettled(suspending)
    log('Done, clearing all raw streams')
    await this.rawStreams.clear()
    log('Done, suspending dht-rpc')
    await super.suspend({ log })
    log('Done, clearing raw streams again')
    await this.rawStreams.clear()
    log('Done, hyperdht fully suspended')
    this._connectable = true
  }

  async destroy({ force = false } = {}) {
    if (!force) {
      const closing = []
      for (const server of this.listening) closing.push(server.close())
      await Promise.allSettled(closing)
    }
    this._router.destroy()
    if (this._persistent) this._persistent.destroy()
    for (const plugin of this.plugins.values()) plugin.destroy()
    await this.rawStreams.clear()
    await this._socketPool.destroy()
    await super.destroy()
  }

  async validateLocalAddresses(addresses) {
    const list = []
    const socks = []
    const waiting = []

    for (const addr of addresses) {
      const { host } = addr

      if (this._validatedLocalAddresses.has(host)) {
        if (await this._validatedLocalAddresses.get(host)) {
          list.push(addr)
        }
        continue
      }

      const sock = this.udx.createSocket()
      try {
        sock.bind(0, host)
      } catch {
        this._validatedLocalAddresses.set(host, Promise.resolve(false))
        continue
      }

      socks.push(sock)

      // semi terrible heuristic until we proper fix local connections by racing them to the remote...
      const promise = new Promise((resolve) => {
        sock.on('message', () => resolve(true))
        setTimeout(() => resolve(false), 500)
        sock.trySend(b4a.alloc(1), sock.address().port, addr.host)
      })

      this._validatedLocalAddresses.set(host, promise)
      waiting.push(addr)
    }

    for (const addr of waiting) {
      const { host } = addr
      if (this._validatedLocalAddresses.has(host)) {
        if (await this._validatedLocalAddresses.get(host)) {
          list.push(addr)
        }
        continue
      }
    }

    for (const sock of socks) await sock.close()

    return list
  }

  findPeer(publicKey, opts = {}) {
    const target = opts.hash === false ? publicKey : hash(publicKey)
    opts = { ...opts, map: mapFindPeer }
    return this.query({ target, command: COMMANDS.FIND_PEER, value: null }, opts)
  }

  lookup(target, opts = {}) {
    opts = { ...opts, map: mapLookup }
    return this.query({ target, command: COMMANDS.LOOKUP, value: null }, opts)
  }

  lookupAndUnannounce(target, keyPair, opts = {}) {
    const unannounces = []
    const dht = this
    const userCommit = opts.commit || noop
    const signUnannounce = opts.signUnannounce || Persistent.signUnannounce

    if (this._persistent !== null) {
      // unlink self
      this._persistent.unannounce(target, keyPair.publicKey)
    }

    opts = { ...opts, map, commit }
    return this.query({ target, command: COMMANDS.LOOKUP, value: null }, opts)

    async function commit(reply, dht, query) {
      await Promise.all(unannounces) // can never fail, caught below
      return userCommit(reply, dht, query)
    }

    function map(reply) {
      const data = mapLookup(reply)

      if (!data || !data.token) return data

      let found = data.peers.length >= 20
      for (let i = 0; !found && i < data.peers.length; i++) {
        found = b4a.equals(data.peers[i].publicKey, keyPair.publicKey)
      }

      if (!found) return data

      if (!data.from.id) return data

      unannounces.push(
        dht
          ._requestUnannounce(keyPair, dht, target, data.token, data.from, signUnannounce)
          .catch(safetyCatch)
      )

      return data
    }
  }

  unannounce(target, keyPair, opts = {}) {
    return this.lookupAndUnannounce(target, keyPair, opts).finished()
  }

  announce(target, keyPair, relayAddresses, opts = {}) {
    const signAnnounce = opts.signAnnounce || Persistent.signAnnounce
    const bump = opts.bump || 0

    opts = { ...opts, commit }

    return opts.clear ? this.lookupAndUnannounce(target, keyPair, opts) : this.lookup(target, opts)

    function commit(reply, dht) {
      return dht._requestAnnounce(
        keyPair,
        dht,
        target,
        reply.token,
        reply.from,
        relayAddresses,
        signAnnounce,
        bump
      )
    }
  }

  async immutableGet(target, opts = {}) {
    opts = { ...opts, map: mapImmutable }

    const query = this.query({ target, command: COMMANDS.IMMUTABLE_GET, value: null }, opts)
    const check = b4a.allocUnsafe(32)

    for await (const node of query) {
      const { value } = node
      sodium.crypto_generichash(check, value)
      if (b4a.equals(check, target)) return node
    }

    return null
  }

  async immutablePut(value, opts = {}) {
    const target = b4a.allocUnsafe(32)
    sodium.crypto_generichash(target, value)

    opts = {
      ...opts,
      map: mapImmutable,
      commit(reply, dht) {
        return dht.request(
          { token: reply.token, target, command: COMMANDS.IMMUTABLE_PUT, value },
          reply.from
        )
      }
    }

    const query = this.query({ target, command: COMMANDS.IMMUTABLE_GET, value: null }, opts)
    await query.finished()

    return { hash: target, closestNodes: query.closestNodes }
  }

  async mutableGet(publicKey, opts = {}) {
    let refresh = opts.refresh || null
    let signed = null
    let result = null

    opts = { ...opts, map: mapMutable, commit: refresh ? commit : null }

    const target = b4a.allocUnsafe(32)
    sodium.crypto_generichash(target, publicKey)

    const userSeq = opts.seq || 0
    const query = this.query(
      { target, command: COMMANDS.MUTABLE_GET, value: c.encode(c.uint, userSeq) },
      opts
    )
    const latest = opts.latest !== false

    for await (const node of query) {
      if (result && node.seq <= result.seq) continue
      if (
        node.seq < userSeq ||
        !Persistent.verifyMutable(node.signature, node.seq, node.value, publicKey)
      )
        continue
      if (!latest) return node
      if (!result || node.seq > result.seq) result = node
    }

    return result

    function commit(reply, dht) {
      if (!signed && result && refresh) {
        if (refresh(result)) {
          signed = c.encode(m.mutablePutRequest, {
            publicKey,
            seq: result.seq,
            value: result.value,
            signature: result.signature
          })
        } else {
          refresh = null
        }
      }

      return signed
        ? dht.request(
            { token: reply.token, target, command: COMMANDS.MUTABLE_PUT, value: signed },
            reply.from
          )
        : Promise.resolve(null)
    }
  }

  async mutablePut(keyPair, value, opts = {}) {
    const signMutable = opts.signMutable || Persistent.signMutable

    const target = b4a.allocUnsafe(32)
    sodium.crypto_generichash(target, keyPair.publicKey)

    const seq = opts.seq || 0
    const signature = await signMutable(seq, value, keyPair)

    const signed = c.encode(m.mutablePutRequest, {
      publicKey: keyPair.publicKey,
      seq,
      value,
      signature
    })

    opts = {
      ...opts,
      map: mapMutable,
      commit(reply, dht) {
        return dht.request(
          { token: reply.token, target, command: COMMANDS.MUTABLE_PUT, value: signed },
          reply.from
        )
      }
    }

    // use seq = 0, for the query part here, as we don't care about the actual values
    const query = this.query(
      { target, command: COMMANDS.MUTABLE_GET, value: c.encode(c.uint, 0) },
      opts
    )
    await query.finished()

    return { publicKey: keyPair.publicKey, closestNodes: query.closestNodes, seq, signature }
  }

  onrequest(req) {
    switch (req.command) {
      case COMMANDS.PEER_HANDSHAKE: {
        this._router.onpeerhandshake(req)
        return true
      }
      case COMMANDS.PEER_HOLEPUNCH: {
        this._router.onpeerholepunch(req)
        return true
      }
    }

    if (this._persistent === null || this.id === null) return false

    switch (req.command) {
      case COMMANDS.FIND_PEER: {
        this._persistent.onfindpeer(req)
        return true
      }
      case COMMANDS.LOOKUP: {
        this._persistent.onlookup(req)
        return true
      }
      case COMMANDS.ANNOUNCE: {
        this._persistent.onannounce(req)
        return true
      }
      case COMMANDS.UNANNOUNCE: {
        this._persistent.onunannounce(req)
        return true
      }
      case COMMANDS.MUTABLE_PUT: {
        this._persistent.onmutableput(req)
        return true
      }
      case COMMANDS.MUTABLE_GET: {
        this._persistent.onmutableget(req)
        return true
      }
      case COMMANDS.IMMUTABLE_PUT: {
        this._persistent.onimmutableput(req)
        return true
      }
      case COMMANDS.IMMUTABLE_GET: {
        this._persistent.onimmutableget(req)
        return true
      }
      case COMMANDS.PLUGIN: {
        this._persistent.onplugin(req)
        return true
      }
    }

    return false
  }

  static keyPair(seed) {
    return createKeyPair(seed)
  }

  static hash(data) {
    return hash(data)
  }

  static connectRawStream(encryptedStream, rawStream, remoteId) {
    const stream = encryptedStream.rawStream

    if (!stream.connected) throw STREAM_NOT_CONNECTED()

    rawStream.connect(stream.socket, remoteId, stream.remotePort, stream.remoteHost)
  }

  createRawStream(opts) {
    return this.rawStreams.add(opts)
  }

  async _requestAnnounce(keyPair, dht, target, token, from, relayAddresses, sign, bump) {
    const ann = {
      peer: {
        publicKey: keyPair.publicKey,
        relayAddresses: relayAddresses || []
      },
      refresh: null,
      signature: null,
      bump
    }

    ann.signature = await sign(target, token, from.id, ann, keyPair)

    const value = c.encode(m.announce, ann)

    return dht.request(
      {
        token,
        target,
        command: COMMANDS.ANNOUNCE,
        value
      },
      from
    )
  }

  async _requestUnannounce(keyPair, dht, target, token, from, sign) {
    const unann = {
      peer: {
        publicKey: keyPair.publicKey,
        relayAddresses: []
      },
      signature: null
    }

    unann.signature = await sign(target, token, from.id, unann, keyPair)

    const value = c.encode(m.announce, unann)

    return dht.request(
      {
        token,
        target,
        command: COMMANDS.UNANNOUNCE,
        value
      },
      from
    )
  }

  register(name, plugin) {
    this.plugins.set(name, plugin)
    plugin.onregister(this)
  }
}

HyperDHT.BOOTSTRAP = BOOTSTRAP_NODES
HyperDHT.FIREWALL = FIREWALL

module.exports = HyperDHT

function mapLookup(node) {
  if (!node.value) return null

  try {
    const l = c.decode(m.lookupRawReply, node.value)

    return {
      token: node.token,
      from: node.from,
      to: node.to,
      peers: l.peers,
      bump: l.bump
    }
  } catch {
    return null
  }
}

function mapFindPeer(node) {
  if (!node.value) return null

  try {
    return {
      token: node.token,
      from: node.from,
      to: node.to,
      peer: c.decode(m.peer, node.value)
    }
  } catch {
    return null
  }
}

function mapImmutable(node) {
  if (!node.value) return null

  return {
    token: node.token,
    from: node.from,
    to: node.to,
    value: node.value
  }
}

function mapMutable(node) {
  if (!node.value) return null

  try {
    const { seq, value, signature } = c.decode(m.mutableGetResponse, node.value)

    return {
      token: node.token,
      from: node.from,
      to: node.to,
      seq,
      value,
      signature
    }
  } catch {
    return null
  }
}

function noop() {}

function filterNode(node) {
  // always skip these testnet nodes that got mixed in by accident, until they get updated
  return (
    !(node.port === 49738 && (node.host === '134.209.28.98' || node.host === '167.99.142.185')) &&
    !(node.port === 9400 && node.host === '35.233.47.252') &&
    !(node.host === '150.136.142.116')
  )
}

const defaultMaxSize = 65536
const defaultMaxAge = 20 * 60 * 1000 // 20 minutes

function defaultCacheOpts(opts) {
  const maxSize = opts.maxSize || defaultMaxSize
  const maxAge = opts.maxAge || defaultMaxAge

  return {
    router: {
      forwards: { maxSize, maxAge }
    },
    relayAddresses: { maxSize: Math.min(maxSize, 512), maxAge: 0 },
    persistent: {
      records: { maxSize, maxAge },
      refreshes: { maxSize, maxAge },
      mutables: {
        maxSize: (maxSize / 2) | 0,
        maxAge: opts.maxAge || 48 * 60 * 60 * 1000 // 48 hours
      },
      immutables: {
        maxSize: (maxSize / 2) | 0,
        maxAge: opts.maxAge || 48 * 60 * 60 * 1000 // 48 hours
      },
      bumps: { maxSize, maxAge }
    }
  }
}
const safetyCatch = require('safety-catch')
const c = require('compact-encoding')
const Signal = require('signal-promise')
const { encodeUnslab } = require('./encode')
const Sleeper = require('./sleeper')
const m = require('./messages')
const Persistent = require('./persistent')
const { COMMANDS } = require('./constants')

const MIN_ACTIVE = 3

module.exports = class Announcer {
  constructor(dht, keyPair, target, opts = {}) {
    this.dht = dht
    this.keyPair = keyPair
    this.target = target
    this.relays = []
    this.relayAddresses = []
    this.stopped = false
    this.suspended = false
    this.record = encodeUnslab(m.peer, { publicKey: keyPair.publicKey, relayAddresses: [] })
    this.online = new Signal()

    this._refreshing = false
    this._closestNodes = null
    this._active = null
    this._sleeper = new Sleeper()
    this._resumed = new Signal()
    this._signAnnounce = opts.signAnnounce || Persistent.signAnnounce
    this._signUnannounce = opts.signUnannounce || Persistent.signUnannounce
    this._updating = null
    this._activeQuery = null
    this._unannouncing = null

    this._serverRelays = [new Map(), new Map(), new Map()]
  }

  isRelay(addr) {
    const id = addr.host + ':' + addr.port
    const [a, b, c] = this._serverRelays
    return a.has(id) || b.has(id) || c.has(id)
  }

  async suspend({ log = noop } = {}) {
    if (this.suspended) return
    this.suspended = true

    log('Suspending announcer')

    // Suspend has its own sleep logic
    // so we don't want to hang on this one
    this.online.notify()

    if (this._activeQuery) this._activeQuery.destroy()

    this._sleeper.resume()
    if (this._updating) await this._updating
    log('Suspending announcer (post update)')

    if (this.suspended === false || this.stopped) return

    log('Suspending announcer (pre unannounce)')
    await this._unannounceCurrent()
    log('Suspending announcer (post unannounce)')
  }

  resume() {
    if (!this.suspended) return
    this.suspended = false

    this.refresh()
    this._sleeper.resume()
    this._resumed.notify()
  }

  refresh() {
    if (this.stopped) return
    this._refreshing = true
  }

  async start() {
    if (this.stopped) return
    this._active = this._runUpdate()
    await this._active
    if (this.stopped) return
    this._active = this._background()
  }

  async stop() {
    this.stopped = true
    this.online.notify() // Break out of the _background loop if we're offline
    this._sleeper.resume()
    this._resumed.notify()
    await this._active
    await this._unannounceCurrent()
  }

  async _unannounceCurrent() {
    while (this._unannouncing !== null) await this._unannouncing
    const un = (this._unannouncing = this._unannounceAll(this._serverRelays[2].values()))
    await this._unannouncing
    if (un === this._unannouncing) this._unannouncing = null
  }

  async _background() {
    while (!this.dht.destroyed && !this.stopped) {
      try {
        this._refreshing = false

        // ~5min +-
        for (let i = 0; i < 100 && !this.stopped && !this._refreshing && !this.suspended; i++) {
          const pings = []

          for (const node of this._serverRelays[2].values()) {
            pings.push(this.dht.ping(node))
          }

          const active = await resolved(pings)
          if (active < Math.min(pings.length, MIN_ACTIVE)) {
            this.refresh() // we lost too many relay nodes, retry all
          }

          if (this.stopped) return

          if (!this.suspended && !this._refreshing) await this._sleeper.pause(3000)
        }

        while (!this.stopped && this.suspended) await this._resumed.wait()

        if (!this.stopped) await this._runUpdate()

        while (!this.dht.online && !this.stopped && !this.suspended) {
          // Being offline can make _background repeat very quickly
          // So wait until we're back online
          await this.online.wait()
        }
      } catch (err) {
        safetyCatch(err)
      }
    }
  }

  async _runUpdate() {
    this._updating = this._update()
    await this._updating
    this._updating = null
  }

  async _update() {
    while (this._unannouncing) await this._unannouncing

    this._cycle()

    const q = (this._activeQuery = this.dht.findPeer(this.target, {
      hash: false,
      nodes: this._closestNodes
    }))

    try {
      await q.finished()
    } catch {
      // ignore failures...
    }

    this._activeQuery = null

    if (this.stopped || this.suspended) return

    const ann = []
    const replies = pickBest(q.closestReplies)

    const relays = []
    const relayAddresses = []

    if (!this.dht.firewalled) {
      const addr = this.dht.remoteAddress()
      if (addr) relayAddresses.push(addr)
    }

    for (const msg of replies) {
      ann.push(this._commit(msg, relays, relayAddresses))
    }

    await Promise.allSettled(ann)
    if (this.stopped || this.suspended) return

    this._closestNodes = q.closestNodes
    this.relays = relays
    this.relayAddresses = relayAddresses

    const removed = []
    for (const [key, value] of this._serverRelays[1]) {
      if (!this._serverRelays[2].has(key)) removed.push(value)
    }

    await this._unannounceAll(removed)
  }

  _unannounceAll(relays) {
    const unann = []
    for (const r of relays) unann.push(this._unannounce(r))
    return Promise.allSettled(unann)
  }

  async _unannounce(to) {
    const unann = {
      peer: {
        publicKey: this.keyPair.publicKey,
        relayAddresses: []
      },
      refresh: null,
      signature: null
    }

    const { from, token, value } = await this.dht.request(
      {
        token: null,
        command: COMMANDS.FIND_PEER,
        target: this.target,
        value: null
      },
      to
    )

    if (!token || !from.id || !value) return

    unann.signature = await this._signUnannounce(this.target, token, from.id, unann, this.keyPair)

    await this.dht.request(
      {
        token,
        command: COMMANDS.UNANNOUNCE,
        target: this.target,
        value: c.encode(m.announce, unann)
      },
      to
    )
  }

  async _commit(msg, relays, relayAddresses) {
    const ann = {
      peer: {
        publicKey: this.keyPair.publicKey,
        relayAddresses: []
      },
      refresh: null,
      signature: null
    }

    ann.signature = await this._signAnnounce(this.target, msg.token, msg.from.id, ann, this.keyPair)

    const res = await this.dht.request(
      {
        token: msg.token,
        command: COMMANDS.ANNOUNCE,
        target: this.target,
        value: c.encode(m.announce, ann)
      },
      msg.from
    )

    if (res.error !== 0) return

    if (relayAddresses.length < 3) relayAddresses.push({ host: msg.from.host, port: msg.from.port })
    relays.push({ relayAddress: msg.from, peerAddress: msg.to })

    this._serverRelays[2].set(msg.from.host + ':' + msg.from.port, msg.from)
  }

  _cycle() {
    const tmp = this._serverRelays[0]
    this._serverRelays[0] = this._serverRelays[1]
    this._serverRelays[1] = this._serverRelays[2]
    this._serverRelays[2] = tmp
    tmp.clear()
  }
}

function resolved(ps) {
  let replied = 0
  let ticks = ps.length + 1

  return new Promise((resolve) => {
    for (const p of ps) p.then(push, tick)
    tick()

    function push(v) {
      replied++
      tick()
    }

    function tick() {
      if (--ticks === 0) resolve(replied)
    }
  })
}

function pickBest(replies) {
  // TODO: pick the ones closest to us RTT wise
  return replies.slice(0, 3)
}

function noop() {}
const NoiseSecretStream = require('@hyperswarm/secret-stream')
const b4a = require('b4a')
const relay = require('blind-relay')
const { isReserved, isBogon } = require('bogon')
const safetyCatch = require('safety-catch')
const unslab = require('unslab')
const Semaphore = require('./semaphore')
const NoiseWrap = require('./noise-wrap')
const SecurePayload = require('./secure-payload')
const Holepuncher = require('./holepuncher')
const Sleeper = require('./sleeper')
const { FIREWALL, ERROR } = require('./constants')
const { unslabbedHash } = require('./crypto')
const {
  CANNOT_HOLEPUNCH,
  HANDSHAKE_INVALID,
  HOLEPUNCH_ABORTED,
  HOLEPUNCH_INVALID,
  HOLEPUNCH_PROBE_TIMEOUT,
  HOLEPUNCH_DOUBLE_RANDOMIZED_NATS,
  PEER_CONNECTION_FAILED,
  PEER_NOT_FOUND,
  REMOTE_ABORTED,
  REMOTE_NOT_HOLEPUNCHABLE,
  REMOTE_NOT_HOLEPUNCHING,
  SERVER_ERROR,
  SERVER_INCOMPATIBLE,
  RELAY_ABORTED,
  SUSPENDED
} = require('./errors')
const { decode } = require('hypercore-id-encoding')
const HyperDHTAddress = require('hyperdht-address')

module.exports = function connect(dht, publicKey, opts = {}) {
  const pool = opts.pool || null

  const { key, nodes: providedNodes } = HyperDHTAddress.decode(
    b4a.isBuffer(publicKey) ? publicKey : decode(publicKey)
  )
  publicKey = key

  if (pool && pool.has(publicKey)) return pool.get(publicKey)

  publicKey = unslab(publicKey)

  opts.relayAddresses = opts.relayAddresses || providedNodes || []
  const keyPair = opts.keyPair || dht.defaultKeyPair
  const relayThrough = selectRelay(opts.relayThrough || null)
  const encryptedSocket = (opts.createSecretStream || defaultCreateSecretStream)(true, null, {
    publicKey: keyPair.publicKey,
    remotePublicKey: publicKey,
    autoStart: false,
    keepAlive: dht.connectionKeepAlive
  })

  // in case a socket is made during suspended state, destroy it immediately
  if (dht.suspended || !dht._connectable) {
    encryptedSocket.destroy(SUSPENDED())
    return encryptedSocket
  }

  if (pool) pool._attachStream(encryptedSocket, false)

  const id = b4a.toString(publicKey, 'hex')
  const c = {
    id,
    dht,
    session: dht.session(),
    relayAddresses: opts.relayAddresses,
    remoteRelayAddresses: [],
    pool,
    round: 0,
    target: unslabbedHash(publicKey),
    remotePublicKey: publicKey,
    reusableSocket: !!opts.reusableSocket,
    handshake: (opts.createHandshake || defaultCreateHandshake)(keyPair, publicKey),
    request: null,
    requesting: false,
    lan: opts.localConnection !== false,
    firewall: FIREWALL.UNKNOWN,
    rawStream: dht.createRawStream({ framed: true, firewall }),
    connect: null,
    query: null,
    puncher: null,
    payload: null,
    passiveConnectTimeout: null,
    serverSocket: null,
    serverAddress: null,
    onsocket: null,
    sleeper: new Sleeper(),
    encryptedSocket,

    // Relay state
    relayTimeout: null,
    relayThrough,
    relayToken: relayThrough ? relay.token() : null,
    relaySocket: null,
    relayClient: null,
    relayPaired: false,
    relayKeepAlive: opts.relayKeepAlive || 5000
  }

  // If the raw stream receives an error signal pre connect (ie from the firewall hook), make sure
  // to forward that to the encrypted socket for proper teardown
  c.rawStream.on('error', autoDestroy)
  c.rawStream.once('connect', () => {
    c.rawStream.removeListener('error', autoDestroy)
  })

  encryptedSocket.on('close', function () {
    if (c.passiveConnectTimeout) clearPassiveConnectTimeout(c)
    if (c.query) c.query.destroy()
    if (c.puncher) c.puncher.destroy()
    if (c.rawStream) c.rawStream.destroy()
    c.session.destroy()
    c.sleeper.resume()
  })

  // Safe to run in the background - never throws
  if (dht.suspended) encryptedSocket.destroy(SUSPENDED())
  else connectAndHolepunch(c, opts)

  return encryptedSocket

  function autoDestroy(err) {
    maybeDestroyEncryptedSocket(c, err)
  }

  function firewall(socket, port, host) {
    // Check if the traffic originated from the socket on which we're expecting relay traffic. If so,
    // we haven't hole punched yet and the other side is just sending us traffic through the relay.
    if (c.relaySocket && isRelay(c.relaySocket, socket, port, host)) {
      return false
    }

    if (c.onsocket) {
      c.onsocket(socket, port, host)
    } else {
      c.serverSocket = socket
      c.serverAddress = { port, host }
    }
    return false
  }
}

function isDone(c) {
  // we are destroying or the puncher is connected - done
  if (c.encryptedSocket.destroying || !!(c.puncher && c.puncher.connected)) {
    return true
  }
  // not destroying, but no raw stream - def not done
  if (c.encryptedSocket.rawStream === null) {
    return false
  }
  // we are relayed, but the puncher is not done yet
  if (c.relaySocket && !!(c.puncher && !c.puncher.connected && !c.puncher.destroyed)) {
    return false
  }
  // we are done
  return true
}

async function retryRoute(c, route) {
  const ref = c.dht._socketPool.lookup(route.socket)

  if (!ref) {
    if (route.socket === c.dht.socket) {
      await connectThroughNode(c, route.address, c.dht.socket)
    }
    return
  }

  ref.active()

  try {
    await connectThroughNode(c, route.address, route.socket)
  } catch {
    // if error, just ignore, and continue through the existing strat
  }

  ref.inactive()
}

async function connectAndHolepunch(c, opts) {
  const route = c.reusableSocket ? c.dht._socketPool.routes.get(c.remotePublicKey) : null

  if (route) {
    await retryRoute(c, route)
    if (isDone(c)) return
  }

  await findAndConnect(c, opts)
  if (isDone(c)) return

  if (!c.connect) {
    // TODO: just a quick fix for now, should retry prob
    maybeDestroyEncryptedSocket(c, HANDSHAKE_INVALID())
    return
  }

  await holepunch(c, opts)
}

function getFirstRemoteAddress(addrs, serverAddress) {
  for (const addr of addrs) {
    if (isBogon(addr.host)) continue
    return addr
  }

  return serverAddress
}

async function holepunch(c, opts) {
  let { relayAddress, serverAddress, clientAddress, payload } = c.connect

  const remoteHolepunchable = !!(payload.holepunch && payload.holepunch.relays.length)

  const relayed = diffAddress(serverAddress, relayAddress)

  if (payload.firewall === FIREWALL.OPEN || (relayed && !remoteHolepunchable)) {
    const addr = getFirstRemoteAddress(payload.addresses4, serverAddress)
    if (addr) {
      const socket = c.dht.socket
      c.dht.stats.punches.open++
      c.onsocket(socket, addr.port, addr.host)
      return
    }
    // TODO: check all addresses also obvs
  }

  const onabort = () => {
    c.session.destroy()
    maybeDestroyEncryptedSocket(c, HOLEPUNCH_ABORTED())
  }

  if (c.firewall === FIREWALL.OPEN) {
    c.passiveConnectTimeout = setTimeout(onabort, 10000)
    return
  }

  // TODO: would be better to just try local addrs in the background whilst continuing with other strategies...
  if (c.lan && relayed && clientAddress.host === serverAddress.host) {
    const serverAddresses = payload.addresses4.filter(onlyNonReserved)

    if (serverAddresses.length > 0) {
      const myAddresses = Holepuncher.localAddresses(c.dht.io.serverSocket)
      const addr = Holepuncher.matchAddress(myAddresses, serverAddresses) || serverAddresses[0]

      const socket = c.dht.io.serverSocket
      try {
        await c.dht.ping(addr)
      } catch {
        maybeDestroyEncryptedSocket(c, HOLEPUNCH_ABORTED())
        return
      }
      c.onsocket(socket, addr.port, addr.host)
      return
    }
  }

  if (!remoteHolepunchable) {
    maybeDestroyEncryptedSocket(c, CANNOT_HOLEPUNCH())
    return
  }

  c.puncher = new Holepuncher(c.dht, c.session, true, payload.firewall)

  c.puncher.onconnect = c.onsocket
  c.puncher.onabort = onabort

  const serverRelay = pickServerRelay(payload.holepunch.relays, relayAddress)

  // Begin holepunching!

  let probe
  try {
    probe = await probeRound(c, opts.fastOpen === false ? null : serverAddress, serverRelay, true)
  } catch (err) {
    destroyPuncher(c)
    // TODO: we should retry here with some of the other relays, bail for now
    maybeDestroyEncryptedSocket(c, err)
    return
  }

  if (isDone(c) || !probe) return
  const { token, peerAddress } = probe

  // If the relay the server picked is the same as the relay the client picked,
  // then we can use the peerAddress that round one indicates the server wants to use.
  // This shaves off a roundtrip if the server chose to reroll its socket due to some NAT
  // issue with the first one it picked (ie mobile nat inconsistencies...).
  // If the relays were different, then the server would not have a UDP session open on this address
  // to the client relay, which round2 uses.
  if (
    !diffAddress(serverRelay.relayAddress, relayAddress) &&
    diffAddress(serverAddress, peerAddress)
  ) {
    serverAddress = peerAddress
    await c.puncher.openSession(serverAddress)
    if (isDone(c)) return
  }

  // TODO: still continue here if a local connection might work, but then do not holepunch...
  if (
    opts.holepunch &&
    !opts.holepunch(
      c.puncher.remoteFirewall,
      c.puncher.nat.firewall,
      c.puncher.remoteAddresses,
      c.puncher.nat.addresses
    )
  ) {
    await abort(c, serverRelay, HOLEPUNCH_ABORTED('Client aborted holepunch'))
    return
  }

  try {
    await roundPunch(c, serverAddress, token, relayAddress, serverRelay, false)
  } catch (err) {
    destroyPuncher(c)
    // TODO: retry with another relay?
    maybeDestroyEncryptedSocket(c, err)
  }
}

async function connectThroughNodes(c, addresses, socket) {
  for (const address of addresses) {
    if (isDone(c) || c.connect) return

    c.remoteRelayAddresses.push(address)
    await connectThroughNode(c, address, socket)
  }
}

async function findAndConnect(c, opts) {
  let attempts = 0
  let relayAddresses =
    opts.relayAddresses && opts.relayAddresses.length ? opts.relayAddresses : null

  if (!relayAddresses) {
    const cachedRelayAddresses = c.dht._relayAddressesCache.get(c.id)
    if (cachedRelayAddresses) relayAddresses = cachedRelayAddresses
  }

  if (c.dht._persistent) {
    // check if we know the route ourself...
    const route = c.dht._router.get(c.target)
    if (route && route.relay !== null) {
      relayAddresses = [{ host: route.relay.host, port: route.relay.port }]
    }
  }

  // 2 is how many parallel connect attempts we want to do, we can make this configurable
  const preConnect = relayAddresses !== null && relayAddresses.length > 0
  const sem = new Semaphore(preConnect ? 3 : 2)
  const signal = sem.signal.bind(sem)
  const tries = relayAddresses !== null ? 2 : 1

  if (preConnect) {
    await sem.wait()
    connectThroughNodes(c, relayAddresses, null).then(signal, signal)
  }

  try {
    for (let i = 0; i < tries && !isDone(c) && !c.connect; i++) {
      c.query = c.dht.findPeer(c.target, {
        hash: false,
        session: c.session,
        nodes: relayAddresses,
        retries: 3
      })

      for await (const data of c.query) {
        await sem.wait()
        if (isDone(c)) return

        if (c.connect) {
          sem.signal()
          break
        }

        // Skip node already run via preConnect
        if (preConnect && relayAddresses && isRelayAddress(relayAddresses, data)) {
          sem.signal()
          continue
        }

        c.remoteRelayAddresses.push(data.from)
        attempts++
        connectThroughNode(c, data.from, null).then(signal, signal)
      }

      relayAddresses = null

      if (attempts > 0) await sem.flush()
    }

    c.query = null
    if (isDone(c)) return

    // flush the semaphore
    await sem.flush()
    if (isDone(c)) return
  } catch (err) {
    c.query = null
    maybeDestroyEncryptedSocket(c, err)
    return
  }

  if (!c.connect) {
    maybeDestroyEncryptedSocket(c, attempts ? PEER_CONNECTION_FAILED() : PEER_NOT_FOUND())
  }
}

async function connectThroughNode(c, address, socket) {
  if (!c.requesting) {
    // If we have a stable server address, send it over now
    const addr = c.dht.remoteAddress()
    const localAddrs = c.lan ? Holepuncher.localAddresses(c.dht.io.serverSocket) : null
    const addresses4 = []

    if (addr) addresses4.push(addr)
    if (localAddrs) addresses4.push(...localAddrs)

    c.firewall = addr ? FIREWALL.OPEN : FIREWALL.UNKNOWN
    c.requesting = true
    c.request = await c.handshake.send({
      error: ERROR.NONE,
      firewall: c.firewall,
      holepunch: null,
      addresses4,
      addresses6: [],
      udx: {
        reusableSocket: c.reusableSocket,
        id: c.rawStream.id,
        seq: 0
      },
      secretStream: {},
      relayThrough: c.relayThrough ? { publicKey: c.relayThrough, token: c.relayToken } : null
    })
    if (isDone(c)) return
  }

  const { serverAddress, clientAddress, relayed, noise } = await c.dht._router.peerHandshake(
    c.target,
    { noise: c.request, socket, session: c.session },
    address
  )
  if (isDone(c) || c.connect) return

  const payload = await c.handshake.recv(noise)
  if (isDone(c) || !payload) return

  if (payload.version !== 1) {
    maybeDestroyEncryptedSocket(c, SERVER_INCOMPATIBLE())
    return
  }
  if (payload.error !== ERROR.NONE) {
    maybeDestroyEncryptedSocket(c, SERVER_ERROR())
    return
  }
  if (!payload.udx) {
    maybeDestroyEncryptedSocket(c, SERVER_ERROR('Server did not send UDX data'))
    return
  }

  const hs = c.handshake.final()

  c.handshake = null
  c.request = null
  c.requesting = false
  c.connect = {
    relayed,
    relayAddress: address,
    clientAddress,
    serverAddress,
    payload
  }

  c.payload = new SecurePayload(hs.holepunchSecret)

  c.onsocket = function (socket, port, host) {
    if (c.rawStream === null) return // Already hole punched

    if (c.rawStream.connected) {
      const remoteChanging = c.rawStream.changeRemote(socket, c.connect.payload.udx.id, port, host)

      if (remoteChanging) remoteChanging.catch(safetyCatch)
    } else {
      // cache the relay addrs for a future reconnect, we prefer the remote one so they
      // can give us the correct ones from their pov
      if (payload.relayAddresses && payload.relayAddresses.length) {
        c.dht._relayAddressesCache.set(c.id, payload.relayAddresses)
      } else if (c.remoteRelayAddresses.length) {
        c.dht._relayAddressesCache.set(c.id, c.remoteRelayAddresses)
      }

      c.rawStream.connect(socket, c.connect.payload.udx.id, port, host)
      c.encryptedSocket.start(c.rawStream, { handshake: hs })
    }

    if (c.reusableSocket && payload.udx.reusableSocket) {
      c.dht._socketPool.routes.add(c.remotePublicKey, c.rawStream)
    }

    if (c.puncher) {
      c.puncher.onabort = noop
      c.puncher.destroy()
    }

    if (c.passiveConnectTimeout) {
      clearPassiveConnectTimeout(c)
    }

    c.rawStream = null
  }

  if (payload.relayThrough || c.relayThrough) {
    relayConnection(c, c.relayThrough, payload, hs)
  }

  if (c.serverSocket) {
    c.onsocket(c.serverSocket, c.serverAddress.port, c.serverAddress.host)
    return
  }

  if (!relayed) {
    c.onsocket(socket || c.dht.socket, address.port, address.host)
  }

  c.session.destroy()
}

async function updateHolepunch(c, peerAddress, relayAddr, payload) {
  const holepunch = await c.dht._router.peerHolepunch(
    c.target,
    {
      id: c.connect.payload.holepunch.id,
      payload: c.payload.encrypt(payload),
      peerAddress,
      socket: c.puncher.socket,
      session: c.session
    },
    relayAddr
  )

  if (isDone(c)) return null

  const remotePayload = c.payload.decrypt(holepunch.payload)
  if (!remotePayload) {
    throw HOLEPUNCH_INVALID()
  }

  const { error, firewall, punching, addresses, remoteToken } = remotePayload

  if (error === ERROR.TRY_LATER && c.relayToken && payload.punching) {
    return {
      tryLater: true,
      ...holepunch,
      payload: remotePayload
    }
  }

  if (error !== ERROR.NONE) {
    throw REMOTE_ABORTED('Remote aborted with error code ' + error)
  }

  const echoed = !!(remoteToken && payload.token && b4a.equals(remoteToken, payload.token))

  c.puncher.updateRemote({
    punching,
    firewall,
    addresses,
    verified: echoed ? peerAddress.host : null
  })

  return {
    tryLater: false,
    ...holepunch,
    payload: remotePayload
  }
}

async function probeRound(c, serverAddress, serverRelay, retry) {
  // Open a quick low ttl session against what we think is the server
  if (serverAddress) await c.puncher.openSession(serverAddress)

  if (isDone(c)) return null

  const reply = await updateHolepunch(c, serverRelay.peerAddress, serverRelay.relayAddress, {
    error: ERROR.NONE,
    firewall: c.puncher.nat.firewall,
    round: c.round++,
    connected: false,
    punching: false,
    addresses: c.puncher.nat.addresses,
    remoteAddress: serverAddress,
    token: null,
    remoteToken: null
  })

  if (isDone(c) || !reply) return null

  const { peerAddress } = reply
  const { address, token } = reply.payload

  c.puncher.nat.add(reply.to, reply.from)

  // Open another quick low ttl session against what the server says their address is,
  // if they haven't said they are random yet
  if (
    c.puncher.remoteFirewall < FIREWALL.RANDOM &&
    address &&
    address.host &&
    address.port &&
    diffAddress(address, serverAddress)
  ) {
    await c.puncher.openSession(address)
    if (isDone(c)) return null
  }

  // If the remote told us they didn't know their nat firewall yet, give them a chance to figure it out
  // They might say this to see if the "fast mode" punch comes through first.
  if (c.puncher.remoteFirewall === FIREWALL.UNKNOWN) {
    await c.sleeper.pause(1000)
    if (isDone(c)) return null
  }

  let stable = await c.puncher.analyze(false)
  if (isDone(c)) return null

  // If the socket seems unstable, try to make it stable by setting the "allowReopen" flag
  // Mostly relevant for mobile networks
  if (!stable) {
    stable = await c.puncher.analyze(true)
    if (isDone(c)) return null
    if (stable) return probeRound(c, serverAddress, serverRelay, false)
  }

  if ((c.puncher.remoteFirewall === FIREWALL.UNKNOWN || !token) && retry) {
    return probeRound(c, serverAddress, serverRelay, false)
  }

  if (
    c.puncher.remoteFirewall === FIREWALL.UNKNOWN ||
    c.puncher.nat.firewall === FIREWALL.UNKNOWN
  ) {
    await abort(c, serverRelay, HOLEPUNCH_PROBE_TIMEOUT())
    return null
  }

  if (c.puncher.remoteFirewall >= FIREWALL.RANDOM && c.puncher.nat.firewall >= FIREWALL.RANDOM) {
    await abort(c, serverRelay, HOLEPUNCH_DOUBLE_RANDOMIZED_NATS())
    return null
  }

  return { token, peerAddress }
}

async function roundPunch(c, serverAddress, remoteToken, clientRelay, serverRelay, delayed) {
  // We are gossiping our final NAT status to the other peer now
  // so make sure we don't update our local view for now as that can make things weird
  c.puncher.nat.freeze()

  const isRandom =
    c.puncher.remoteFirewall >= FIREWALL.RANDOM || c.puncher.nat.firewall >= FIREWALL.RANDOM
  if (isRandom) {
    while (
      c.dht._randomPunches >= c.dht._randomPunchLimit ||
      Date.now() - c.dht._lastRandomPunch < c.dht._randomPunchInterval
    ) {
      // if no relay can help, bail
      if (!c.relayToken) throw HOLEPUNCH_ABORTED()

      if (!delayed) {
        delayed = true
        await updateHolepunch(c, serverAddress, clientRelay, {
          error: ERROR.NONE,
          firewall: c.puncher.nat.firewall,
          round: c.round++,
          connected: false,
          punching: false,
          addresses: c.puncher.nat.addresses,
          remoteAddress: null,
          token: c.payload.token(serverAddress),
          remoteToken
        })
        if (isDone(c)) return
      }

      await tryLater(c)
      if (isDone(c)) return
    }
  }

  // increment now, so we can commit to punching
  if (isRandom) c.dht._randomPunches++

  let reply

  try {
    // if delayed switch to the servers chosen relay - we validated anyway
    reply = await updateHolepunch(
      c,
      delayed ? serverRelay.peerAddress : serverAddress,
      delayed ? serverRelay.relayAddress : clientRelay,
      {
        error: ERROR.NONE,
        firewall: c.puncher.nat.firewall,
        round: c.round++,
        connected: false,
        punching: true,
        addresses: c.puncher.nat.addresses,
        remoteAddress: null,
        token: delayed ? null : c.payload.token(serverAddress),
        remoteToken
      }
    )
  } finally {
    // decrement as punch increments for us
    if (isRandom) c.dht._randomPunches--
  }

  if (isDone(c)) return
  if (!reply) return

  if (reply.tryLater) {
    await tryLater(c)
    if (isDone(c)) return
    return roundPunch(c, serverAddress, remoteToken, clientRelay, serverRelay, true)
  }

  if (!c.puncher.remoteHolepunching) {
    throw REMOTE_NOT_HOLEPUNCHING()
  }

  if (!(await c.puncher.punch())) {
    throw REMOTE_NOT_HOLEPUNCHABLE()
  }
}

async function tryLater(c) {
  if (!c.relayToken) throw HOLEPUNCH_ABORTED()
  await c.sleeper.pause(10000 + Math.round(Math.random() * 10000))
}

function maybeDestroyEncryptedSocket(c, err) {
  if (isDone(c)) return
  if (c.encryptedSocket.rawStream) return
  if (c.relaySocket) return // waiting for the relay
  if (c.puncher && !c.puncher.destroyed) return // waiting for the puncher
  c.session.destroy()
  c.encryptedSocket.destroy(err)
}

async function abort(c, { peerAddress, relayAddress }, err) {
  try {
    await updateHolepunch(c, peerAddress, relayAddress, {
      error: ERROR.ABORTED,
      firewall: FIREWALL.UNKNOWN,
      round: c.round++,
      connected: false,
      punching: false,
      addresses: null,
      remoteAddress: null,
      token: null,
      remoteToken: null
    })
  } catch (err) {
    safetyCatch(err)
  }

  destroyPuncher(c)
  maybeDestroyEncryptedSocket(c, err)
}

function relayConnection(c, relayThrough, payload, hs) {
  let isInitiator
  let publicKey
  let token

  if (payload.relayThrough) {
    isInitiator = false
    publicKey = payload.relayThrough.publicKey
    token = payload.relayThrough.token
  } else {
    isInitiator = true
    publicKey = relayThrough
    token = c.relayToken
  }

  c.relayToken = token
  c.relaySocket = c.dht.connect(publicKey)
  c.relaySocket.setKeepAlive(c.relayKeepAlive)
  c.relayClient = relay.Client.from(c.relaySocket, { id: c.relaySocket.publicKey })
  c.relayTimeout = setTimeout(onabort, 15000, null)

  c.relayClient.pair(isInitiator, token, c.rawStream).on('error', onabort).on('data', ondata)

  function ondata(remoteId) {
    if (c.relayTimeout) clearRelayTimeout(c)
    if (c.rawStream === null) {
      onabort(null)
      return
    }

    c.relayPaired = true

    const { remotePort, remoteHost, socket } = c.relaySocket.rawStream

    c.rawStream
      .on('close', () => c.relaySocket.destroy())
      .connect(socket, remoteId, remotePort, remoteHost)

    c.encryptedSocket.start(c.rawStream, { handshake: hs })
  }

  function onabort(err) {
    if (c.relayTimeout) clearRelayTimeout(c)
    const socket = c.relaySocket
    c.relayToken = null
    c.relaySocket = null
    if (socket) socket.destroy()
    maybeDestroyEncryptedSocket(c, err || RELAY_ABORTED())
  }
}

function clearPassiveConnectTimeout(c) {
  clearTimeout(c.passiveConnectTimeout)
  c.passiveConnectTimeout = null
}

function clearRelayTimeout(c) {
  clearTimeout(c.relayTimeout)
  c.relayTimeout = null
}

function destroyPuncher(c) {
  if (c.puncher) c.puncher.destroy()
  c.session.destroy()
}

function pickServerRelay(relays, clientRelay) {
  for (const r of relays) {
    if (!diffAddress(r.relayAddress, clientRelay)) return r
  }
  return relays[0]
}

function diffAddress(a, b) {
  return a.host !== b.host || a.port !== b.port
}

function defaultCreateHandshake(keyPair, remotePublicKey) {
  return new NoiseWrap(keyPair, remotePublicKey)
}

function defaultCreateSecretStream(isInitiator, rawStream, opts) {
  return new NoiseSecretStream(isInitiator, rawStream, opts)
}

function onlyNonReserved(addr) {
  return !isReserved(addr.host)
}

function isRelay(relaySocket, socket, port, host) {
  const stream = relaySocket.rawStream
  if (!stream) return false
  if (stream.socket !== socket) return false
  return port === stream.remotePort && host === stream.remoteHost
}

function selectRelay(relayThrough) {
  if (typeof relayThrough === 'function') relayThrough = relayThrough()
  if (relayThrough === null) return null
  if (Array.isArray(relayThrough))
    return relayThrough[Math.floor(Math.random() * relayThrough.length)]
  return relayThrough
}

function isRelayAddress(relayAddresses, data) {
  for (const node of relayAddresses) {
    if (node.host === data.from.host && node.port === data.from.port) return true
  }

  return false
}

function noop() {}
const EventEmitter = require('events')
const b4a = require('b4a')
const errors = require('./errors')

module.exports = class ConnectionPool extends EventEmitter {
  constructor(dht) {
    super()

    this._dht = dht
    this._servers = new Map()
    this._connecting = new Map()
    this._connections = new Map()
  }

  _attachServer(server) {
    const keyString = b4a.toString(server.publicKey, 'hex')

    this._servers.set(keyString, server)

    server
      .on('close', () => {
        this._servers.delete(keyString)
      })
      .on('connection', (socket) => {
        this._attachStream(socket, true)
      })
  }

  _attachStream(stream, opened) {
    const existing = this.get(stream.remotePublicKey)

    if (existing) {
      const keepNew =
        stream.isInitiator === existing.isInitiator ||
        b4a.compare(stream.publicKey, stream.remotePublicKey) > 0

      if (keepNew) {
        let closed = false

        const onclose = () => {
          closed = true
        }

        existing
          .on('error', noop)
          .on('close', () => {
            if (closed) return

            stream.off('error', noop).off('close', onclose)

            this._attachStream(stream, opened)
          })
          .destroy(errors.DUPLICATE_CONNECTION())

        stream.on('error', noop).on('close', onclose)
      } else {
        stream.on('error', noop).destroy(errors.DUPLICATE_CONNECTION())
      }

      return
    }

    const session = new ConnectionRef(this, stream)

    const keyString = b4a.toString(stream.remotePublicKey, 'hex')

    if (opened) {
      this._connections.set(keyString, session)

      stream.on('close', () => {
        this._connections.delete(keyString)
      })

      this.emit('connection', stream, session)
    } else {
      this._connecting.set(keyString, session)

      stream
        .on('error', noop)
        .on('close', () => {
          if (opened) this._connections.delete(keyString)
          else this._connecting.delete(keyString)
        })
        .on('open', () => {
          opened = true

          this._connecting.delete(keyString)
          this._connections.set(keyString, session)

          stream.off('error', noop)

          this.emit('connection', stream, session)
        })
    }

    return session
  }

  get connecting() {
    return this._connecting.size
  }

  get connections() {
    return this._connections.values()
  }

  has(publicKey) {
    const keyString = b4a.toString(publicKey, 'hex')

    return this._connections.has(keyString) || this._connecting.has(keyString)
  }

  get(publicKey) {
    const keyString = b4a.toString(publicKey, 'hex')

    const existing = this._connections.get(keyString) || this._connecting.get(keyString)

    return existing?._stream || null
  }
}

class ConnectionRef {
  constructor(pool, stream) {
    this._pool = pool
    this._stream = stream
    this._refs = 0
  }

  active() {
    this._refs++
  }

  inactive() {
    this._refs--
  }

  release() {
    this._stream.destroy()
  }
}

function noop() {}
const crypto = require('hypercore-crypto')

const COMMANDS = (exports.COMMANDS = {
  PEER_HANDSHAKE: 0,
  PEER_HOLEPUNCH: 1,
  FIND_PEER: 2,
  LOOKUP: 3,
  ANNOUNCE: 4,
  UNANNOUNCE: 5,
  MUTABLE_PUT: 6,
  MUTABLE_GET: 7,
  IMMUTABLE_PUT: 8,
  IMMUTABLE_GET: 9,
  PLUGIN: 10
})

exports.BOOTSTRAP_NODES = global.Pear?.config.dht?.bootstrap || [
  '88.99.3.86@node1.hyperdht.org:49737',
  '142.93.90.113@node2.hyperdht.org:49737',
  '138.68.147.8@node3.hyperdht.org:49737'
]

exports.KNOWN_NODES = global.Pear?.config.dht?.nodes || []

exports.FIREWALL = {
  UNKNOWN: 0,
  OPEN: 1,
  CONSISTENT: 2,
  RANDOM: 3
}

exports.ERROR = {
  // noise / connection related
  NONE: 0,
  ABORTED: 1,
  VERSION_MISMATCH: 2,
  TRY_LATER: 3,
  // dht related
  SEQ_REUSED: 16,
  SEQ_TOO_LOW: 17
}

const [
  NS_ANNOUNCE,
  NS_UNANNOUNCE,
  NS_MUTABLE_PUT,
  NS_PEER_HANDSHAKE,
  NS_PEER_HOLEPUNCH,
  NS_PLUGIN
] = crypto.namespace('hyperswarm/dht', [
  COMMANDS.ANNOUNCE,
  COMMANDS.UNANNOUNCE,
  COMMANDS.MUTABLE_PUT,
  COMMANDS.PEER_HANDSHAKE,
  COMMANDS.PEER_HOLEPUNCH,
  COMMANDS.PLUGIN
])

exports.NS = {
  ANNOUNCE: NS_ANNOUNCE,
  UNANNOUNCE: NS_UNANNOUNCE,
  MUTABLE_PUT: NS_MUTABLE_PUT,
  PEER_HANDSHAKE: NS_PEER_HANDSHAKE,
  PEER_HOLEPUNCH: NS_PEER_HOLEPUNCH,
  PLUGIN: NS_PLUGIN
}
const sodium = require('sodium-universal')
const b4a = require('b4a')

function hash(data) {
  const out = b4a.allocUnsafe(32)
  sodium.crypto_generichash(out, data)
  return out
}

function unslabbedHash(data) {
  const out = b4a.allocUnsafeSlow(32)
  sodium.crypto_generichash(out, data)
  return out
}

function createKeyPair(seed) {
  const publicKey = b4a.alloc(32)
  const secretKey = b4a.alloc(64)
  if (seed) sodium.crypto_sign_seed_keypair(publicKey, secretKey, seed)
  else sodium.crypto_sign_keypair(publicKey, secretKey)
  return { publicKey, secretKey }
}

module.exports = {
  hash,
  unslabbedHash,
  createKeyPair
}
const b4a = require('b4a')
const cenc = require('compact-encoding')

function encodeUnslab(enc, m) {
  // Faster than unslab(c.encode(enc, data)) because it avoids the mem copy.
  // Makes sense to put in compact-encoding when we need it in other modules too
  const state = cenc.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafeSlow(state.end)
  enc.encode(state, m)
  return state.buffer
}

module.exports = {
  encodeUnslab
}
module.exports = class DHTError extends Error {
  constructor(msg, code, fn = DHTError) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'DHTError'
  }

  static BAD_HANDSHAKE_REPLY(msg = 'Bad handshake reply') {
    return new DHTError(msg, 'BAD_HANDSHAKE_REPLY', DHTError.BAD_HANDSHAKE_REPLY)
  }

  static BAD_HOLEPUNCH_REPLY(msg = 'Bad holepunch reply') {
    return new DHTError(msg, 'BAD_HOLEPUNCH_REPLY', DHTError.BAD_HOLEPUNCH_REPLY)
  }

  static HOLEPUNCH_ABORTED(msg = 'Holepunch aborted') {
    return new DHTError(msg, 'HOLEPUNCH_ABORTED', DHTError.HOLEPUNCH_ABORTED)
  }

  static HOLEPUNCH_INVALID(msg = 'Invalid holepunch payload') {
    return new DHTError(msg, 'HOLEPUNCH_INVALID', DHTError.HOLEPUNCH_INVALID)
  }

  static HOLEPUNCH_PROBE_TIMEOUT(msg = 'Holepunching probe did not finish in time') {
    return new DHTError(msg, 'HOLEPUNCH_PROBE_TIMEOUT', DHTError.HOLEPUNCH_PROBE_TIMEOUT)
  }

  static HOLEPUNCH_DOUBLE_RANDOMIZED_NATS(msg = 'Both remote and local NATs are randomized') {
    return new DHTError(
      msg,
      'HOLEPUNCH_DOUBLE_RANDOMIZED_NATS',
      DHTError.HOLEPUNCH_DOUBLE_RANDOMIZED_NATS
    )
  }

  static CANNOT_HOLEPUNCH(msg = 'Cannot holepunch to remote') {
    return new DHTError(msg, 'CANNOT_HOLEPUNCH', DHTError.CANNOT_HOLEPUNCH)
  }

  static REMOTE_NOT_HOLEPUNCHING(msg = 'Remote is not holepunching') {
    return new DHTError(msg, 'REMOTE_NOT_HOLEPUNCHING', DHTError.REMOTE_NOT_HOLEPUNCHING)
  }

  static REMOTE_NOT_HOLEPUNCHABLE(msg = 'Remote is not holepunchable') {
    return new DHTError(msg, 'REMOTE_NOT_HOLEPUNCHABLE', DHTError.REMOTE_NOT_HOLEPUNCHABLE)
  }

  static REMOTE_ABORTED(msg = 'Remote aborted') {
    return new DHTError(msg, 'REMOTE_ABORTED', DHTError.REMOTE_ABORTED)
  }

  static HANDSHAKE_UNFINISHED(msg = 'Handshake did not finish') {
    return new DHTError(msg, 'HANDSHAKE_UNFINISHED', DHTError.HANDSHAKE_UNFINISHED)
  }

  static HANDSHAKE_INVALID(msg = 'Received invalid handshake') {
    return new DHTError(msg, 'HANDSHAKE_INVALID', DHTError.HANDSHAKE_INVALID)
  }

  static ALREADY_LISTENING(msg = 'Already listening') {
    return new DHTError(msg, 'ALREADY_LISTENING', DHTError.ALREADY_LISTENING)
  }

  static KEYPAIR_ALREADY_USED(msg = 'Keypair already used') {
    return new DHTError(msg, 'KEYPAIR_ALREADY_USED', DHTError.KEYPAIR_ALREADY_USED)
  }

  static NODE_DESTROYED(msg = 'Node destroyed') {
    return new DHTError(msg, 'NODE_DESTROYED', DHTError.NODE_DESTROYED)
  }

  static PEER_CONNECTION_FAILED(msg = 'Could not connect to peer') {
    return new DHTError(msg, 'PEER_CONNECTION_FAILED', DHTError.PEER_CONNECTION_FAILED)
  }

  static PEER_NOT_FOUND(msg = 'Peer not found') {
    return new DHTError(msg, 'PEER_NOT_FOUND', DHTError.PEER_NOT_FOUND)
  }

  static STREAM_NOT_CONNECTED(msg = 'Stream is not connected') {
    return new DHTError(msg, 'STREAM_NOT_CONNECTED', DHTError.STREAM_DISCONNECTED)
  }

  static SERVER_INCOMPATIBLE(msg = 'Server is using an incompatible version') {
    return new DHTError(msg, 'SERVER_INCOMPATIBLE', DHTError.SERVER_INCOMPATIBLE)
  }

  static SERVER_ERROR(msg = 'Server returned an error') {
    return new DHTError(msg, 'SERVER_ERROR', DHTError.SERVER_ERROR)
  }

  static DUPLICATE_CONNECTION(msg = 'Duplicate connection') {
    return new DHTError(msg, 'DUPLICATE_CONNECTION', DHTError.DUPLICATE_CONNECTION)
  }

  static RELAY_ABORTED(msg = 'Relay aborted') {
    return new DHTError(msg, 'RELAY_ABORTED', DHTError.RELAY_ABORTED)
  }

  static SUSPENDED(msg = 'Suspended') {
    return new DHTError(msg, 'SUSPENDED', DHTError.SUSPENDED)
  }
}
const b4a = require('b4a')
const Nat = require('./nat')
const Sleeper = require('./sleeper')
const { FIREWALL } = require('./constants')

const BIRTHDAY_SOCKETS = 256
const HOLEPUNCH = b4a.from([0])
const HOLEPUNCH_TTL = 5
const DEFAULT_TTL = 64
const MAX_REOPENS = 3

module.exports = class Holepuncher {
  constructor(dht, session, isInitiator, remoteFirewall = FIREWALL.UNKNOWN) {
    const holder = dht._socketPool.acquire()

    this.dht = dht
    this.session = session

    this.nat = new Nat(dht, session, holder.socket)
    this.nat.autoSample()

    this.isInitiator = isInitiator

    // events
    this.onconnect = noop
    this.onabort = noop

    this.punching = false
    this.connected = false
    this.destroyed = false
    this.randomized = false

    // track remote state
    this.remoteFirewall = remoteFirewall
    this.remoteAddresses = []
    this.remoteHolepunching = false

    this._sleeper = new Sleeper()
    this._reopening = null
    this._timeout = null
    this._punching = null
    this._allHolders = []
    this._holder = this._addRef(holder)
  }

  get socket() {
    return this._holder.socket
  }

  updateRemote({ punching, firewall, addresses, verified }) {
    const remoteAddresses = []

    if (addresses) {
      for (const addr of addresses) {
        remoteAddresses.push({
          host: addr.host,
          port: addr.port,
          verified: verified === addr.host || this._isVerified(addr.host)
        })
      }
    }

    this.remoteFirewall = firewall
    this.remoteAddresses = remoteAddresses
    this.remoteHolepunching = punching
  }

  _isVerified(host) {
    for (const addr of this.remoteAddresses) {
      if (addr.verified && addr.host === host) {
        return true
      }
    }
    return false
  }

  ping(addr, socket = this._holder.socket) {
    return holepunch(socket, addr, false)
  }

  openSession(addr, socket = this._holder.socket) {
    return holepunch(socket, addr, true)
  }

  async analyze(allowReopen) {
    await this.nat.analyzing
    if (this._unstable()) {
      if (!allowReopen) return false
      if (!this._reopening) this._reopening = this._reopen()
      return this._reopening
    }
    return true
  }

  _unstable() {
    // TODO!!: We need an additional heuristic here... If we were NOT random in the past we should also do this.
    const firewall = this.nat.firewall
    return (
      (this.remoteFirewall >= FIREWALL.RANDOM && firewall >= FIREWALL.RANDOM) ||
      firewall === FIREWALL.UNKNOWN
    )
  }

  _reset() {
    const prev = this._holder

    this._allHolders.pop()
    this._holder = this._addRef(this.dht._socketPool.acquire())

    prev.release()
    this.nat.destroy()

    this.nat = new Nat(this.dht, this.session, this._holder.socket)
    // TODO: maybe make auto sampling configurable somehow?
    this.nat.autoSample()
  }

  _addRef(ref) {
    this._allHolders.push(ref)
    ref.onholepunchmessage = (msg, rinfo) => this._onholepunchmessage(msg, rinfo, ref)
    return ref
  }

  _onholepunchmessage(_, addr, ref) {
    if (!this.isInitiator) {
      // TODO: we don't need this if we had a way to connect a socket to many hosts
      holepunch(ref.socket, addr, false) // never fails
      return
    }

    if (this.connected) return

    this.connected = true
    this.punching = false

    for (const r of this._allHolders) {
      if (r === ref) continue
      r.release()
    }

    this._allHolders[0] = ref
    while (this._allHolders.length > 1) this._allHolders.pop()

    this._decrementRandomized()
    this.onconnect(ref.socket, addr.port, addr.host)
  }

  _done() {
    return this.destroyed || this.connected
  }

  async _reopen() {
    for (let i = 0; this._unstable() && i < MAX_REOPENS && !this._done() && !this.punching; i++) {
      this._reset()
      await this.nat.analyzing
    }

    return coerceFirewall(this.nat.firewall) === FIREWALL.CONSISTENT
  }

  punch() {
    if (!this._punching) this._punching = this._punch()
    return this._punching
  }

  async _punch() {
    if (this._done() || !this.remoteAddresses.length) return false

    this.punching = true

    // Coerce into consistency for now. Obvs we could make this this more efficient if we use that info
    // but that's seldomly used since those will just use tcp most of the time.

    const local = coerceFirewall(this.nat.firewall)
    const remote = coerceFirewall(this.remoteFirewall)

    // Note that most of these async functions are meant to run in the background
    // which is why we don't await them here and why they are not allowed to throw

    let remoteVerifiedAddress = null
    for (const addr of this.remoteAddresses) {
      if (addr.verified) {
        remoteVerifiedAddress = addr
        break
      }
    }

    if (local === FIREWALL.CONSISTENT && remote === FIREWALL.CONSISTENT) {
      this.dht.stats.punches.consistent++
      this._consistentProbe()
      return true
    }

    if (!remoteVerifiedAddress) return false

    if (local === FIREWALL.CONSISTENT && remote >= FIREWALL.RANDOM) {
      this.dht.stats.punches.random++
      this._incrementRandomized()
      this._randomProbes(remoteVerifiedAddress)
      return true
    }

    if (local >= FIREWALL.RANDOM && remote === FIREWALL.CONSISTENT) {
      this.dht.stats.punches.random++
      this._incrementRandomized()
      await this._openBirthdaySockets(remoteVerifiedAddress)
      if (this.punching) this._keepAliveRandomNat(remoteVerifiedAddress)
      return true
    }

    return false
  }

  // Note that this never throws so it is safe to run in the background
  async _consistentProbe() {
    // Here we do the sleep first because the "fast open" mode in the server just fired a ping
    if (!this.isInitiator) await this._sleeper.pause(1000)

    let tries = 0

    while (this.punching && tries++ < 10) {
      for (const addr of this.remoteAddresses) {
        // only try unverified addresses every 4 ticks
        if (!addr.verified && (tries & 3) !== 0) continue
        await holepunch(this._holder.socket, addr, false)
      }
      if (this.punching) await this._sleeper.pause(1000)
    }

    this._autoDestroy()
  }

  // Note that this never throws so it is safe to run in the background
  async _randomProbes(remoteAddr) {
    let tries = 1750 // ~35s

    while (this.punching && tries-- > 0) {
      const addr = { host: remoteAddr.host, port: randomPort() }
      await holepunch(this._holder.socket, addr, false)
      if (this.punching) await this._sleeper.pause(20)
    }

    this._autoDestroy()
  }

  // Note that this never throws so it is safe to run in the background
  async _keepAliveRandomNat(remoteAddr) {
    let i = 0
    let lowTTLRounds = 1

    // TODO: experiment with this here. We just bursted all the messages in
    // openOtherSockets to ensure the sockets are open, so it's potentially
    // a good idea to slow down for a bit.
    await this._sleeper.pause(100)

    let tries = 1750 // ~35s

    while (this.punching && tries-- > 0) {
      if (i === this._allHolders.length) {
        i = 0
        if (lowTTLRounds > 0) lowTTLRounds--
      }

      await holepunch(this._allHolders[i++].socket, remoteAddr, lowTTLRounds > 0)
      if (this.punching) await this._sleeper.pause(20)
    }

    this._autoDestroy()
  }

  async _openBirthdaySockets(remoteAddr) {
    while (this.punching && this._allHolders.length < BIRTHDAY_SOCKETS) {
      const ref = this._addRef(this.dht._socketPool.acquire())
      await holepunch(ref.socket, remoteAddr, HOLEPUNCH_TTL)
    }
  }

  _autoDestroy() {
    if (!this.connected) this.destroy()
  }

  _incrementRandomized() {
    if (!this.randomized) {
      this.randomized = true
      this.dht._randomPunches++
    }
  }

  _decrementRandomized() {
    if (this.randomized) {
      this.dht._lastRandomPunch = Date.now()
      this.randomized = false
      this.dht._randomPunches--
    }
  }

  destroy() {
    if (this.destroyed) return
    this.destroyed = true
    this.punching = false

    for (const ref of this._allHolders) ref.release()
    this._allHolders = []
    this.nat.destroy()

    if (!this.connected) {
      this._decrementRandomized()
      this.onabort()
    }
  }

  static ping(socket, addr) {
    return holepunch(socket, addr, false)
  }

  static localAddresses(socket) {
    return localAddresses(socket)
  }

  static matchAddress(myAddresses, externalAddresses) {
    return matchAddress(myAddresses, externalAddresses)
  }
}

function holepunch(socket, addr, lowTTL) {
  return socket.send(HOLEPUNCH, addr.port, addr.host, lowTTL ? HOLEPUNCH_TTL : DEFAULT_TTL)
}

function randomPort() {
  return (1000 + Math.random() * 64536) | 0
}

function coerceFirewall(fw) {
  return fw === FIREWALL.OPEN ? FIREWALL.CONSISTENT : fw
}

function localAddresses(socket) {
  const addrs = []
  const { host, port } = socket.address()

  if (host === '127.0.0.1') return [{ host, port }]

  for (const n of socket.udx.networkInterfaces()) {
    if (n.family !== 4 || n.internal) continue

    addrs.push({ host: n.host, port })
  }

  if (addrs.length === 0) {
    addrs.push({ host: '127.0.0.1', port })
  }

  return addrs
}

function matchAddress(localAddresses, remoteLocalAddresses) {
  if (remoteLocalAddresses.length === 0) return null

  let best = { segment: 1, addr: null }

  for (const localAddress of localAddresses) {
    // => 192.168.122.238
    const a = localAddress.host.split('.')

    for (const remoteAddress of remoteLocalAddresses) {
      // => 192.168.0.23
      // => 192.168.122.1
      const b = remoteAddress.host.split('.')

      // Matches 192.*.*.*
      if (a[0] === b[0]) {
        if (best.segment === 1) best = { segment: 2, addr: remoteAddress }

        // Matches 192.168.*.*
        if (a[1] === b[1]) {
          if (best.segment === 2) best = { segment: 3, addr: remoteAddress }

          // Matches 192.168.122.*
          if (a[2] === b[2]) return remoteAddress
        }
      }
    }
  }

  return best.addr
}

function noop() {}
const c = require('compact-encoding')

const ipv4 = {
  ...c.ipv4Address,
  decode(state) {
    const ip = c.ipv4Address.decode(state)
    return {
      host: ip.host,
      port: ip.port
    }
  }
}

const ipv4Array = c.array(ipv4)

const ipv6 = {
  ...c.ipv6Address,
  decode(state) {
    const ip = c.ipv6Address.decode(state)
    return {
      host: ip.host,
      port: ip.port
    }
  }
}

const ipv6Array = c.array(ipv6)

exports.handshake = {
  preencode(state, m) {
    state.end += 1 + 1 + (m.peerAddress ? 6 : 0) + (m.relayAddress ? 6 : 0)
    c.buffer.preencode(state, m.noise)
  },
  encode(state, m) {
    const flags = (m.peerAddress ? 1 : 0) | (m.relayAddress ? 2 : 0)

    c.uint.encode(state, flags)
    c.uint.encode(state, m.mode)
    c.buffer.encode(state, m.noise)

    if (m.peerAddress) ipv4.encode(state, m.peerAddress)
    if (m.relayAddress) ipv4.encode(state, m.relayAddress)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      mode: c.uint.decode(state),
      noise: c.buffer.decode(state),
      peerAddress: flags & 1 ? ipv4.decode(state) : null,
      relayAddress: flags & 2 ? ipv4.decode(state) : null
    }
  }
}

const relayInfo = {
  preencode(state, m) {
    state.end += 12
  },
  encode(state, m) {
    ipv4.encode(state, m.relayAddress)
    ipv4.encode(state, m.peerAddress)
  },
  decode(state) {
    return {
      relayAddress: ipv4.decode(state),
      peerAddress: ipv4.decode(state)
    }
  }
}

const relayInfoArray = c.array(relayInfo)

const holepunchInfo = {
  preencode(state, m) {
    c.uint.preencode(state, m.id)
    relayInfoArray.preencode(state, m.relays)
  },
  encode(state, m) {
    c.uint.encode(state, m.id)
    relayInfoArray.encode(state, m.relays)
  },
  decode(state) {
    return {
      id: c.uint.decode(state),
      relays: relayInfoArray.decode(state)
    }
  }
}

const udxInfo = {
  preencode(state, m) {
    state.end += 2 // version + features
    c.uint.preencode(state, m.id)
    c.uint.preencode(state, m.seq)
  },
  encode(state, m) {
    c.uint.encode(state, 1)
    c.uint.encode(state, m.reusableSocket ? 1 : 0)
    c.uint.encode(state, m.id)
    c.uint.encode(state, m.seq)
  },
  decode(state) {
    const version = c.uint.decode(state)
    const features = c.uint.decode(state)

    return {
      version,
      reusableSocket: (features & 1) !== 0,
      id: c.uint.decode(state),
      seq: c.uint.decode(state)
    }
  }
}

const secretStreamInfo = {
  preencode(state, m) {
    c.uint.preencode(state, 1)
  },
  encode(state, m) {
    c.uint.encode(state, 1)
  },
  decode(state) {
    return {
      version: c.uint.decode(state)
    }
  }
}

const relayThroughInfo = {
  preencode(state, m) {
    c.uint.preencode(state, 1) // version
    c.uint.preencode(state, 0) // flags
    c.fixed32.preencode(state, m.publicKey)
    c.fixed32.preencode(state, m.token)
  },
  encode(state, m) {
    c.uint.encode(state, 1)
    c.uint.encode(state, 0)
    c.fixed32.encode(state, m.publicKey)
    c.fixed32.encode(state, m.token)
  },
  decode(state) {
    const version = c.uint.decode(state)
    c.uint.decode(state)

    return {
      version,
      publicKey: c.fixed32.decode(state),
      token: c.fixed32.decode(state)
    }
  }
}

exports.noisePayload = {
  preencode(state, m) {
    state.end += 4 // version + flags + error + firewall
    if (m.holepunch) holepunchInfo.preencode(state, m.holepunch)
    if (m.addresses4 && m.addresses4.length) ipv4Array.preencode(state, m.addresses4)
    if (m.addresses6 && m.addresses6.length) ipv6Array.preencode(state, m.addresses6)
    if (m.udx) udxInfo.preencode(state, m.udx)
    if (m.secretStream) secretStreamInfo.preencode(state, m.secretStream)
    if (m.relayThrough) relayThroughInfo.preencode(state, m.relayThrough)
    if (m.relayAddresses) ipv4Array.preencode(state, m.relayAddresses)
  },
  encode(state, m) {
    let flags = 0

    if (m.holepunch) flags |= 1
    if (m.addresses4 && m.addresses4.length) flags |= 2
    if (m.addresses6 && m.addresses6.length) flags |= 4
    if (m.udx) flags |= 8
    if (m.secretStream) flags |= 16
    if (m.relayThrough) flags |= 32
    if (m.relayAddresses) flags |= 64

    c.uint.encode(state, 1) // version
    c.uint.encode(state, flags)
    c.uint.encode(state, m.error)
    c.uint.encode(state, m.firewall)

    if (m.holepunch) holepunchInfo.encode(state, m.holepunch)
    if (m.addresses4 && m.addresses4.length) ipv4Array.encode(state, m.addresses4)
    if (m.addresses6 && m.addresses6.length) ipv6Array.encode(state, m.addresses6)
    if (m.udx) udxInfo.encode(state, m.udx)
    if (m.secretStream) secretStreamInfo.encode(state, m.secretStream)
    if (m.relayThrough) relayThroughInfo.encode(state, m.relayThrough)
    if (m.relayAddresses) ipv4Array.encode(state, m.relayAddresses)
  },
  decode(state) {
    const version = c.uint.decode(state)

    if (version !== 1) {
      // Do not attempt to decode but return this back to the user so they can
      // actually handle it
      return {
        version,
        error: 0,
        firewall: 0,
        holepunch: null,
        addresses4: [],
        addresses6: [],
        udx: null,
        secretStream: null,
        relayThrough: null,
        relayAddresses: null
      }
    }

    const flags = c.uint.decode(state)

    return {
      version,
      error: c.uint.decode(state),
      firewall: c.uint.decode(state),
      holepunch: (flags & 1) !== 0 ? holepunchInfo.decode(state) : null,
      addresses4: (flags & 2) !== 0 ? ipv4Array.decode(state) : [],
      addresses6: (flags & 4) !== 0 ? ipv6Array.decode(state) : [],
      udx: (flags & 8) !== 0 ? udxInfo.decode(state) : null,
      secretStream: (flags & 16) !== 0 ? secretStreamInfo.decode(state) : null,
      relayThrough: (flags & 32) !== 0 ? relayThroughInfo.decode(state) : null,
      relayAddresses: (flags & 64) !== 0 ? ipv4Array.decode(state) : null
    }
  }
}

exports.holepunch = {
  preencode(state, m) {
    state.end += 2
    c.uint.preencode(state, m.id)
    c.buffer.preencode(state, m.payload)
    if (m.peerAddress) ipv4.preencode(state, m.peerAddress)
  },
  encode(state, m) {
    const flags = m.peerAddress ? 1 : 0
    c.uint.encode(state, flags)
    c.uint.encode(state, m.mode)
    c.uint.encode(state, m.id)
    c.buffer.encode(state, m.payload)
    if (m.peerAddress) ipv4.encode(state, m.peerAddress)
  },
  decode(state) {
    const flags = c.uint.decode(state)
    return {
      mode: c.uint.decode(state),
      id: c.uint.decode(state),
      payload: c.buffer.decode(state),
      peerAddress: flags & 1 ? ipv4.decode(state) : null
    }
  }
}

exports.holepunchPayload = {
  preencode(state, m) {
    state.end += 4 // flags + error + firewall + round
    if (m.addresses) ipv4Array.preencode(state, m.addresses)
    if (m.remoteAddress) state.end += 6
    if (m.token) state.end += 32
    if (m.remoteToken) state.end += 32
  },
  encode(state, m) {
    const flags =
      (m.connected ? 1 : 0) |
      (m.punching ? 2 : 0) |
      (m.addresses ? 4 : 0) |
      (m.remoteAddress ? 8 : 0) |
      (m.token ? 16 : 0) |
      (m.remoteToken ? 32 : 0)

    c.uint.encode(state, flags)
    c.uint.encode(state, m.error)
    c.uint.encode(state, m.firewall)
    c.uint.encode(state, m.round)

    if (m.addresses) ipv4Array.encode(state, m.addresses)
    if (m.remoteAddress) ipv4.encode(state, m.remoteAddress)
    if (m.token) c.fixed32.encode(state, m.token)
    if (m.remoteToken) c.fixed32.encode(state, m.remoteToken)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      error: c.uint.decode(state),
      firewall: c.uint.decode(state),
      round: c.uint.decode(state),
      connected: (flags & 1) !== 0,
      punching: (flags & 2) !== 0,
      addresses: (flags & 4) !== 0 ? ipv4Array.decode(state) : null,
      remoteAddress: (flags & 8) !== 0 ? ipv4.decode(state) : null,
      token: (flags & 16) !== 0 ? c.fixed32.decode(state) : null,
      remoteToken: (flags & 32) !== 0 ? c.fixed32.decode(state) : null
    }
  }
}

const peer = (exports.peer = {
  preencode(state, m) {
    state.end += 32
    ipv4Array.preencode(state, m.relayAddresses)
  },
  encode(state, m) {
    c.fixed32.encode(state, m.publicKey)
    ipv4Array.encode(state, m.relayAddresses)
  },
  decode(state) {
    return {
      publicKey: c.fixed32.decode(state),
      relayAddresses: ipv4Array.decode(state)
    }
  }
})

const peers = (exports.peers = c.array(peer))

const rawPeers = c.array(c.raw)

exports.lookupRawReply = {
  preencode(state, m) {
    rawPeers.preencode(state, m.peers)
    c.uint.preencode(state, m.bump)
  },
  encode(state, m) {
    rawPeers.encode(state, m.peers)
    c.uint.encode(state, m.bump)
  },
  decode(state) {
    return {
      peers: peers.decode(state),
      bump: state.start < state.end ? c.uint.decode(state) : 0
    }
  }
}

exports.announce = {
  preencode(state, m) {
    state.end++ // flags
    if (m.peer) peer.preencode(state, m.peer)
    if (m.refresh) state.end += 32
    if (m.signature) state.end += 64
    if (m.bump) c.uint.preencode(state, m.bump)
  },
  encode(state, m) {
    const flags = (m.peer ? 1 : 0) | (m.refresh ? 2 : 0) | (m.signature ? 4 : 0) | (m.bump ? 8 : 0)
    c.uint.encode(state, flags)
    if (m.peer) peer.encode(state, m.peer)
    if (m.refresh) c.fixed32.encode(state, m.refresh)
    if (m.signature) c.fixed64.encode(state, m.signature)
    if (m.bump) c.uint.encode(state, m.bump)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      peer: (flags & 1) !== 0 ? peer.decode(state) : null,
      refresh: (flags & 2) !== 0 ? c.fixed32.decode(state) : null,
      signature: (flags & 4) !== 0 ? c.fixed64.decode(state) : null,
      bump: (flags & 8) !== 0 ? c.uint.decode(state) : 0
    }
  }
}

exports.mutableSignable = {
  preencode(state, m) {
    c.uint.preencode(state, m.seq)
    c.buffer.preencode(state, m.value)
  },
  encode(state, m) {
    c.uint.encode(state, m.seq)
    c.buffer.encode(state, m.value)
  },
  decode(state) {
    return {
      seq: c.uint.decode(state),
      value: c.buffer.decode(state)
    }
  }
}

exports.mutablePutRequest = {
  preencode(state, m) {
    c.fixed32.preencode(state, m.publicKey)
    c.uint.preencode(state, m.seq)
    c.buffer.preencode(state, m.value)
    c.fixed64.preencode(state, m.signature)
  },
  encode(state, m) {
    c.fixed32.encode(state, m.publicKey)
    c.uint.encode(state, m.seq)
    c.buffer.encode(state, m.value)
    c.fixed64.encode(state, m.signature)
  },
  decode(state) {
    return {
      publicKey: c.fixed32.decode(state),
      seq: c.uint.decode(state),
      value: c.buffer.decode(state),
      signature: c.fixed64.decode(state)
    }
  }
}

exports.mutableGetResponse = {
  preencode(state, m) {
    c.uint.preencode(state, m.seq)
    c.buffer.preencode(state, m.value)
    c.fixed64.preencode(state, m.signature)
  },
  encode(state, m) {
    c.uint.encode(state, m.seq)
    c.buffer.encode(state, m.value)
    c.fixed64.encode(state, m.signature)
  },
  decode(state) {
    return {
      seq: c.uint.decode(state),
      value: c.buffer.decode(state),
      signature: c.fixed64.decode(state)
    }
  }
}

exports.pluginRequest = {
  preencode(state, m) {
    c.string.preencode(state, m.plugin)
    c.uint.preencode(state, m.version)
    c.uint.preencode(state, m.command)
    c.buffer.preencode(state, m.value)
  },
  encode(state, m) {
    c.string.encode(state, m.plugin)
    c.uint.encode(state, m.version)
    c.uint.encode(state, m.command)
    c.buffer.encode(state, m.value)
  },
  decode(state) {
    return {
      plugin: c.string.decode(state),
      version: c.uint.decode(state),
      command: c.uint.decode(state),
      value: c.buffer.decode(state)
    }
  }
}
const { FIREWALL } = require('../lib/constants')

module.exports = class Nat {
  constructor(dht, session, socket) {
    this._samplesHost = []
    this._samplesFull = []
    this._visited = new Map()
    this._resolve = null
    this._minSamples = 4
    this._autoSampling = false

    this.dht = dht
    this.session = session
    this.socket = socket

    this.sampled = 0
    this.firewall = dht.firewalled ? FIREWALL.UNKNOWN : FIREWALL.OPEN
    this.addresses = null

    this.analyzing = new Promise((resolve) => {
      this._resolve = resolve
    })
  }

  autoSample(retry = true) {
    if (this._autoSampling) return
    this._autoSampling = true

    const self = this
    const socket = this.socket
    const maxPings = this._minSamples

    let skip = this.dht.nodes.length >= 8 ? 5 : 0
    let pending = 0

    // TODO: it would be best to pick the nodes to help us based on latency to us
    // That should reduce connect latency in general. We should investigate tracking that later on.

    // TODO 2: try to pick nodes with different IPs as well, as that'll help multi IP cell connections...
    // If we expose this from the nat sampler then the DHT should be able to help us filter out scams as well...

    for (
      let node = this.dht.nodes.latest;
      node && this.sampled + pending < maxPings;
      node = node.prev
    ) {
      if (skip > 0) {
        skip--
        continue
      }

      const ref = node.host + ':' + node.port

      if (this._visited.has(ref)) continue
      this._visited.set(ref, 1)

      pending++
      this.session.ping(node, { socket, retry: false }).then(onpong, onskip)
    }

    pending++
    onskip()

    function onpong(res) {
      self.add(res.to, res.from)
      onskip()
    }

    function onskip() {
      if (--pending === 0 && self.sampled < self._minSamples) {
        if (retry) {
          self._autoSampling = false
          self.autoSample(false)
          return
        }
        self._resolve()
      }
    }
  }

  destroy() {
    this._autoSampling = true
    this._minSamples = 0
    this._resolve()
  }

  unfreeze() {
    this.frozen = false
    this._updateFirewall()
    this._updateAddresses()
  }

  freeze() {
    this.frozen = true
  }

  _updateFirewall() {
    if (!this.dht.firewalled) {
      this.firewall = FIREWALL.OPEN
      return
    }

    if (this.sampled < 3) return

    const max = this._samplesFull[0].hits

    if (max >= 3) {
      this.firewall = FIREWALL.CONSISTENT
      return
    }

    if (max === 1) {
      this.firewall = FIREWALL.RANDOM
      return
    }

    // else max === 2

    // 1 host, >= 4 total samples ie, 2 bad ones -> random
    if (this._samplesHost.length === 1 && this.sampled > 3) {
      this.firewall = FIREWALL.RANDOM
      return
    }

    // double hit on two different ips -> assume consistent
    if (this._samplesHost.length > 1 && this._samplesFull[1].hits > 1) {
      this.firewall = FIREWALL.CONSISTENT
      return
    }

    // (4 is just means - all the samples we expect) - no decision - assume random
    if (this.sampled > 4) {
      this.firewall = FIREWALL.RANDOM
    }
  }

  _updateAddresses() {
    if (this.firewall === FIREWALL.UNKNOWN) {
      this.addresses = null
      return
    }

    if (this.firewall === FIREWALL.RANDOM) {
      this.addresses = [this._samplesHost[0]]
      return
    }

    if (this.firewall === FIREWALL.CONSISTENT) {
      this.addresses = []
      for (const addr of this._samplesFull) {
        if (addr.hits >= 2 || this.addresses.length < 2) this.addresses.push(addr)
      }
    }
  }

  update() {
    if (this.dht.firewalled && this.firewall === FIREWALL.OPEN) {
      this.firewall = FIREWALL.UNKNOWN
    }
    this._updateFirewall()
    this._updateAddresses()
  }

  add(addr, from) {
    const ref = from.host + ':' + from.port

    if (this._visited.get(ref) === 2) return
    this._visited.set(ref, 2)

    addSample(this._samplesHost, addr.host, 0)
    addSample(this._samplesFull, addr.host, addr.port)

    if ((++this.sampled >= 3 || !this.dht.firewalled) && !this.frozen) {
      this.update()
    }

    if (this.firewall === FIREWALL.CONSISTENT || this.firewall === FIREWALL.OPEN) {
      this._resolve()
    } else if (this.sampled >= this._minSamples) {
      this._resolve()
    }
  }
}

function addSample(samples, host, port) {
  for (let i = 0; i < samples.length; i++) {
    const s = samples[i]

    if (s.port !== port || s.host !== host) continue
    s.hits++

    for (; i > 0; i--) {
      const prev = samples[i - 1]
      if (prev.hits >= s.hits) return
      samples[i - 1] = s
      samples[i] = prev
    }

    return
  }

  samples.push({
    host,
    port,
    hits: 1
  })
}
const NoiseSecretStream = require('@hyperswarm/secret-stream')
const NoiseHandshake = require('noise-handshake')
const curve = require('noise-curve-ed')
const c = require('compact-encoding')
const b4a = require('b4a')
const sodium = require('sodium-universal')
const m = require('./messages')
const { NS } = require('./constants')
const { HANDSHAKE_UNFINISHED } = require('./errors')

const NOISE_PROLOUGE = NS.PEER_HANDSHAKE

module.exports = class NoiseWrap {
  constructor(keyPair, remotePublicKey) {
    this.isInitiator = !!remotePublicKey
    this.remotePublicKey = remotePublicKey
    this.keyPair = keyPair
    this.handshake = new NoiseHandshake('IK', this.isInitiator, keyPair, { curve })
    this.handshake.initialise(NOISE_PROLOUGE, remotePublicKey)
  }

  send(payload) {
    const buf = c.encode(m.noisePayload, payload)
    return this.handshake.send(buf)
  }

  recv(buf) {
    const payload = c.decode(m.noisePayload, this.handshake.recv(buf))
    this.remotePublicKey = b4a.toBuffer(this.handshake.rs)
    return payload
  }

  final() {
    if (!this.handshake.complete) throw HANDSHAKE_UNFINISHED()

    const holepunchSecret = b4a.allocUnsafe(32)

    sodium.crypto_generichash(holepunchSecret, NS.PEER_HOLEPUNCH, this.handshake.hash)

    return {
      isInitiator: this.isInitiator,
      publicKey: this.keyPair.publicKey,
      streamId: this.streamId,
      remotePublicKey: this.remotePublicKey,
      remoteId: NoiseSecretStream.id(this.handshake.hash, !this.isInitiator),
      holepunchSecret,
      hash: b4a.toBuffer(this.handshake.hash),
      rx: b4a.toBuffer(this.handshake.rx),
      tx: b4a.toBuffer(this.handshake.tx)
    }
  }
}
const c = require('compact-encoding')
const sodium = require('sodium-universal')
const RecordCache = require('record-cache')
const Cache = require('xache')
const b4a = require('b4a')
const unslab = require('unslab')

const { encodeUnslab } = require('./encode')
const m = require('./messages')
const { NS, ERROR } = require('./constants')

const EMPTY = b4a.alloc(0)
const TMP = b4a.allocUnsafe(32)
const MAX_BUMP_DRIFT = 60_000

module.exports = class Persistent {
  constructor(dht, opts) {
    this.dht = dht
    this.records = new RecordCache(opts.records)
    this.bumps = new Cache(opts.bumps)
    this.refreshes = new Cache(opts.refreshes)
    this.mutables = new Cache(opts.mutables)
    this.immutables = new Cache(opts.immutables)
  }

  onlookup(req) {
    if (!req.target) return

    const k = b4a.toString(req.target, 'hex')
    const records = this.records.get(k, 20)
    const bump = this.bumps.get(k) || 0
    const fwd = this.dht._router.get(k)

    if (fwd && records.length < 20) records.push(fwd.record)

    req.reply(records.length ? c.encode(m.lookupRawReply, { peers: records, bump }) : null)
  }

  onfindpeer(req) {
    if (!req.target) return
    const fwd = this.dht._router.get(req.target)
    req.reply(fwd ? fwd.record : null)
  }

  unannounce(target, publicKey) {
    const k = b4a.toString(target, 'hex')
    sodium.crypto_generichash(TMP, publicKey)

    if (b4a.equals(TMP, target)) this.dht._router.delete(k)
    this.records.remove(k, publicKey)
  }

  onunannounce(req) {
    if (!req.target || !req.token) return

    const unann = decode(m.announce, req.value)
    if (unann === null) return

    const { peer, signature } = unann
    if (!peer || !signature) return

    const signable = annSignable(req.target, req.token, this.dht.id, unann, NS.UNANNOUNCE)

    if (!sodium.crypto_sign_verify_detached(signature, signable, peer.publicKey)) {
      return
    }

    this.unannounce(req.target, peer.publicKey)
    req.reply(null, { token: false, closerNodes: false })
  }

  _onrefresh(token, req) {
    sodium.crypto_generichash(TMP, token)
    const activeRefresh = b4a.toString(TMP, 'hex')

    const r = this.refreshes.get(activeRefresh)
    if (!r) return

    const { announceSelf, k, record } = r
    const publicKey = record.subarray(0, 32)

    if (announceSelf) {
      this.dht._router.set(k, {
        relay: req.from,
        record,
        onconnect: null,
        onholepunch: null
      })
      this.records.remove(k, publicKey)
    } else {
      this.records.add(k, publicKey, record)
    }

    this.refreshes.delete(activeRefresh)
    this.refreshes.set(b4a.toString(token, 'hex'), r)

    req.reply(null, { token: false, closerNodes: false })
  }

  onannounce(req) {
    if (!req.target || !req.token || !this.dht.id) return

    const ann = decode(m.announce, req.value)
    if (ann === null) return

    const { peer, refresh, signature, bump } = ann

    if (!peer) {
      if (!refresh) return
      this._onrefresh(refresh, req)
      return
    }

    const signable = annSignable(req.target, req.token, this.dht.id, ann, NS.ANNOUNCE)

    if (!signature || !sodium.crypto_sign_verify_detached(signature, signable, peer.publicKey)) {
      return
    }

    // TODO: it would be potentially be more optimal to allow more than 3 addresses here for a findPeer response
    // and only use max 3 for a lookup reply
    if (peer.relayAddresses.length > 3) {
      peer.relayAddresses = peer.relayAddresses.slice(0, 3)
    }

    sodium.crypto_generichash(TMP, peer.publicKey)

    const k = b4a.toString(req.target, 'hex')
    const announceSelf = b4a.equals(TMP, req.target)
    const record = encodeUnslab(m.peer, peer)

    if (announceSelf) {
      this.dht._router.set(k, {
        relay: req.from,
        record,
        onconnect: null,
        onholepunch: null
      })
      this.records.remove(k, peer.publicKey)
    } else {
      const currentBump = this.bumps.get(k) || 0
      if (bump > currentBump && bump <= Date.now() + MAX_BUMP_DRIFT) this.bumps.set(k, bump)
      this.records.add(k, peer.publicKey, record)
    }

    if (refresh) {
      this.refreshes.set(b4a.toString(refresh, 'hex'), { k, record, announceSelf })
    }

    req.reply(null, { token: false, closerNodes: false })
  }

  onmutableget(req) {
    if (!req.target || !req.value) return

    let seq = 0
    try {
      seq = c.decode(c.uint, req.value)
    } catch {
      return
    }

    const k = b4a.toString(req.target, 'hex')
    const value = this.mutables.get(k)

    if (!value) {
      req.reply(null)
      return
    }

    const localSeq = c.decode(c.uint, value)
    req.reply(localSeq < seq ? null : value)
  }

  onmutableput(req) {
    if (!req.target || !req.token || !req.value) return

    const p = decode(m.mutablePutRequest, req.value)
    if (!p) return

    const { publicKey, seq, value, signature } = p

    const hash = b4a.allocUnsafe(32)
    sodium.crypto_generichash(hash, publicKey)
    if (!b4a.equals(hash, req.target)) return

    if (!value || !verifyMutable(signature, seq, value, publicKey)) return

    const k = b4a.toString(hash, 'hex')
    const local = this.mutables.get(k)

    if (local) {
      const existing = c.decode(m.mutableGetResponse, local)
      if (existing.value && existing.seq === seq && b4a.compare(value, existing.value) !== 0) {
        req.error(ERROR.SEQ_REUSED)
        return
      }
      if (seq < existing.seq) {
        req.error(ERROR.SEQ_TOO_LOW)
        return
      }
    }

    this.mutables.set(k, encodeUnslab(m.mutableGetResponse, { seq, value, signature }))
    req.reply(null)
  }

  onimmutableget(req) {
    if (!req.target) return

    const k = b4a.toString(req.target, 'hex')
    const value = this.immutables.get(k)

    req.reply(value || null)
  }

  onimmutableput(req) {
    if (!req.target || !req.token || !req.value) return

    const hash = b4a.alloc(32)
    sodium.crypto_generichash(hash, req.value)
    if (!b4a.equals(hash, req.target)) return

    const k = b4a.toString(hash, 'hex')
    this.immutables.set(k, unslab(req.value))

    req.reply(null)
  }

  onplugin(req) {
    if (!req.value) return

    const plugreq = decode(m.pluginRequest, req.value)
    if (plugreq === null) return

    const p = this.dht.plugins.get(plugreq.plugin)
    if (!p || p.version !== plugreq.version) return

    p.onrequest(plugreq, req)
  }

  destroy() {
    this.records.destroy()
    this.refreshes.destroy()
    this.mutables.destroy()
    this.immutables.destroy()
  }

  static signMutable(seq, value, keyPair) {
    const signable = b4a.allocUnsafe(32 + 32)
    const hash = signable.subarray(32)

    signable.set(NS.MUTABLE_PUT, 0)

    sodium.crypto_generichash(hash, c.encode(m.mutableSignable, { seq, value }))
    return sign(signable, keyPair)
  }

  static verifyMutable(signature, seq, value, publicKey) {
    return verifyMutable(signature, seq, value, publicKey)
  }

  static signAnnounce(target, token, id, ann, keyPair) {
    return sign(annSignable(target, token, id, ann, NS.ANNOUNCE), keyPair)
  }

  static signUnannounce(target, token, id, ann, keyPair) {
    return sign(annSignable(target, token, id, ann, NS.UNANNOUNCE), keyPair)
  }
}

function verifyMutable(signature, seq, value, publicKey) {
  const signable = b4a.allocUnsafe(32 + 32)
  const hash = signable.subarray(32)

  signable.set(NS.MUTABLE_PUT, 0)

  sodium.crypto_generichash(hash, c.encode(m.mutableSignable, { seq, value }))
  return sodium.crypto_sign_verify_detached(signature, signable, publicKey)
}

function annSignable(target, token, id, ann, ns) {
  const signable = b4a.allocUnsafe(32 + 32)
  const hash = signable.subarray(32)

  signable.set(ns, 0)

  sodium.crypto_generichash_batch(hash, [
    target,
    id,
    token,
    c.encode(m.peer, ann.peer), // note that this is the partial encoding of the announce message so we could just use that for perf
    ann.refresh || EMPTY
  ])

  return signable
}

function sign(signable, keyPair) {
  if (keyPair.sign) {
    return keyPair.sign(signable)
  }
  const secretKey = keyPair.secretKey ? keyPair.secretKey : keyPair
  const signature = b4a.allocUnsafe(64)
  sodium.crypto_sign_detached(signature, signable, secretKey)
  return signature
}

function decode(enc, val) {
  try {
    return val && c.decode(enc, val)
  } catch (err) {
    return null
  }
}
module.exports = class RawStreamSet {
  constructor(dht) {
    this._dht = dht

    this._prefix = 16 - 1 // 16 is the default stream-set side in udx
    this._streams = new Map()
  }

  get size() {
    return this._streams.size
  }

  [Symbol.iterator]() {
    return this._streams.values()
  }

  add(opts) {
    const self = this

    // TODO: we should prob have a udx helper for id generation, given the slight complexity
    // of the below. requires a PRNG in udx tho.

    let id = 0

    while (true) {
      id = (Math.random() * 0x100000000) >>> 0

      if (this._streams.has(id & this._prefix)) continue
      break
    }

    // always have ~50% change of rolling a free one
    if (2 * this._streams.size >= this._prefix) {
      // ie 0b11111 = 0b1111 + 1 + 0b1111
      this._prefix = 2 * this._prefix + 1

      // move the prefixes over
      const next = new Map()
      for (const stream of this._streams.values()) {
        next.set(stream.id & this._prefix, stream)
      }
      this._streams = next
    }

    const stream = this._dht.udx.createStream(id, opts)
    this._streams.set(id & this._prefix, stream)

    stream.on('close', onclose)

    return stream

    function onclose() {
      self._streams.delete(id & self._prefix)
    }
  }

  async clear() {
    const destroying = []

    for (const stream of this._streams.values()) {
      destroying.push(new Promise((resolve) => stream.once('close', resolve).destroy()))
    }

    await Promise.allSettled(destroying)
  }
}
const c = require('compact-encoding')
const Cache = require('xache')
const safetyCatch = require('safety-catch')
const b4a = require('b4a')
const { handshake, holepunch } = require('./messages')
const { COMMANDS } = require('./constants')
const { BAD_HANDSHAKE_REPLY, BAD_HOLEPUNCH_REPLY } = require('./errors')

const FROM_CLIENT = 0
const FROM_SERVER = 1
const FROM_RELAY = 2
const FROM_SECOND_RELAY = 3
const REPLY = 4

// TODO: While the current design is very trustless in regards to clients/servers trusting the DHT,
// we should add a bunch of rate limits everywhere, especially including here to avoid bad users
// using a DHT node to relay traffic indiscriminately using the connect/holepunch messages.
// That's mostly from an abuse POV as none of the messsages do amplication.

module.exports = class Router {
  constructor(dht, opts) {
    this.dht = dht
    this.forwards = new Cache(opts.forwards)
  }

  set(target, state) {
    if (state.onpeerhandshake) {
      this.forwards.retain(toString(target), state)
    } else {
      this.forwards.set(toString(target), state)
    }
  }

  get(target) {
    return this.forwards.get(toString(target))
  }

  delete(target) {
    this.forwards.delete(toString(target))
  }

  destroy() {
    this.forwards.destroy()
  }

  async peerHandshake(target, { noise, peerAddress, relayAddress, socket, session }, to) {
    const dht = this.dht

    const requestValue = c.encode(handshake, {
      mode: FROM_CLIENT,
      noise,
      peerAddress,
      relayAddress
    })

    const res = await dht.request(
      { command: COMMANDS.PEER_HANDSHAKE, target, value: requestValue },
      to,
      { socket, session }
    )

    const hs = decode(handshake, res.value)
    if (
      !hs ||
      hs.mode !== REPLY ||
      to.host !== res.from.host ||
      to.port !== res.from.port ||
      !hs.noise
    ) {
      throw BAD_HANDSHAKE_REPLY()
    }

    return {
      noise: hs.noise,
      relayed: !!hs.peerAddress,
      serverAddress: hs.peerAddress || to,
      clientAddress: res.to
    }
  }

  async onpeerhandshake(req) {
    const hs = req.value && decode(handshake, req.value)
    if (!hs) return

    const { mode, noise, peerAddress, relayAddress } = hs

    const state = req.target && this.get(req.target)
    const isServer = !!(state && state.onpeerhandshake)
    const relay = state && state.relay

    if (isServer) {
      let reply = null
      try {
        reply = noise && (await state.onpeerhandshake({ noise, peerAddress }, req))
      } catch (e) {
        safetyCatch(e)
        return
      }
      if (!reply || !reply.noise) return
      const opts = { socket: reply.socket, closerNodes: false, token: false }

      switch (mode) {
        case FROM_CLIENT: {
          req.reply(
            c.encode(handshake, { mode: REPLY, noise: reply.noise, peerAddress: null }),
            opts
          )
          return
        }
        case FROM_RELAY: {
          req.relay(
            c.encode(handshake, { mode: FROM_SERVER, noise: reply.noise, peerAddress }),
            req.from,
            opts
          )
          return
        }
        case FROM_SECOND_RELAY: {
          if (!relayAddress) return
          req.relay(
            c.encode(handshake, { mode: FROM_SERVER, noise: reply.noise, peerAddress }),
            relayAddress,
            opts
          )
          return // eslint-disable-line
        }
      }
    } else {
      switch (mode) {
        case FROM_CLIENT: {
          // TODO: if no relay is known route closer to the target instead of timing out
          if (!noise) return
          if (!relay && !relayAddress) {
            // help the user route
            req.reply(null, { token: false, closerNodes: true })
            return
          }
          req.relay(
            c.encode(handshake, {
              mode: FROM_RELAY,
              noise,
              peerAddress: req.from,
              relayAddress: null
            }),
            relayAddress || relay
          )
          return
        }
        case FROM_RELAY: {
          if (!relay || !noise) return
          req.relay(
            c.encode(handshake, {
              mode: FROM_SECOND_RELAY,
              noise,
              peerAddress,
              relayAddress: req.from
            }),
            relay
          )
          return
        }
        case FROM_SERVER: {
          if (!peerAddress || !noise) return
          req.reply(
            c.encode(handshake, { mode: REPLY, noise, peerAddress: req.from, relayAddress: null }),
            { to: peerAddress, closerNodes: false, token: false }
          )
          return // eslint-disable-line
        }
      }
    }
  }

  async peerHolepunch(target, { id, payload, peerAddress, socket, session }, to) {
    const dht = this.dht
    const requestValue = c.encode(holepunch, {
      mode: FROM_CLIENT,
      id,
      payload,
      peerAddress
    })

    const res = await dht.request(
      { command: COMMANDS.PEER_HOLEPUNCH, target, value: requestValue },
      to,
      { socket, session }
    )

    const hp = decode(holepunch, res.value)
    if (!hp || hp.mode !== REPLY || to.host !== res.from.host || to.port !== res.from.port) {
      throw BAD_HOLEPUNCH_REPLY()
    }

    return {
      from: res.from,
      to: res.to,
      payload: hp.payload,
      peerAddress: hp.peerAddress || to
    }
  }

  async onpeerholepunch(req) {
    const hp = req.value && decode(holepunch, req.value)
    if (!hp) return

    const { mode, id, payload, peerAddress } = hp

    const state = req.target && this.get(req.target)
    const isServer = !!(state && state.onpeerholepunch)
    const relay = state && state.relay

    switch (mode) {
      case FROM_CLIENT: {
        if (!peerAddress && !relay) return
        req.relay(
          c.encode(holepunch, { mode: FROM_RELAY, id, payload, peerAddress: req.from }),
          peerAddress || relay
        )
        return
      }
      case FROM_RELAY: {
        if (!isServer || !peerAddress) return
        let reply = null
        try {
          reply = await state.onpeerholepunch({ id, payload, peerAddress }, req)
        } catch (e) {
          safetyCatch(e)
          return
        }
        if (!reply) return
        const opts = { socket: reply.socket, closerNodes: false, token: false }
        req.relay(
          c.encode(holepunch, { mode: FROM_SERVER, id: 0, payload: reply.payload, peerAddress }),
          req.from,
          opts
        )
        return
      }
      case FROM_SERVER: {
        req.reply(c.encode(holepunch, { mode: REPLY, id, payload, peerAddress: req.from }), {
          to: peerAddress,
          closerNodes: false,
          token: false
        })
        return // eslint-disable-line
      }
    }
  }
}

function decode(enc, val) {
  try {
    return c.decode(enc, val)
  } catch {
    return null
  }
}

function toString(t) {
  return typeof t === 'string' ? t : b4a.toString(t, 'hex')
}
const sodium = require('sodium-universal')
const b4a = require('b4a')
const { holepunchPayload } = require('./messages')

module.exports = class HolepunchPayload {
  constructor(holepunchSecret) {
    this._sharedSecret = holepunchSecret
    this._localSecret = b4a.allocUnsafe(32)

    sodium.randombytes_buf(this._localSecret)
  }

  decrypt(buffer) {
    const state = { start: 24, end: buffer.byteLength - 16, buffer }

    if (state.end <= state.start) return null

    const nonce = buffer.subarray(0, 24)
    const msg = state.buffer.subarray(state.start, state.end)
    const cipher = state.buffer.subarray(state.start)

    if (!sodium.crypto_secretbox_open_easy(msg, cipher, nonce, this._sharedSecret)) return null

    try {
      return holepunchPayload.decode(state)
    } catch {
      return null
    }
  }

  encrypt(payload) {
    const state = { start: 24, end: 24, buffer: null }
    holepunchPayload.preencode(state, payload)
    state.buffer = b4a.allocUnsafe(state.end + 16)

    const nonce = state.buffer.subarray(0, 24)
    const msg = state.buffer.subarray(state.start, state.end)
    const cipher = state.buffer.subarray(state.start)

    holepunchPayload.encode(state, payload)
    sodium.randombytes_buf(nonce)
    sodium.crypto_secretbox_easy(cipher, msg, nonce, this._sharedSecret)

    return state.buffer
  }

  token(addr) {
    const out = b4a.allocUnsafe(32)
    sodium.crypto_generichash(out, b4a.from(addr.host), this._localSecret)
    return out
  }
}
const DONE = Promise.resolve(true)
const DESTROYED = Promise.resolve(false)

module.exports = class Semaphore {
  constructor(limit = 1) {
    this.limit = limit
    this.active = 0
    this.waiting = []

    this.flushedPromise = null
    this.flushedResolve = null

    this.destroyed = false

    this._onwait = this._queueWaiting.bind(this)
    this._onflush = this._queueFlushed.bind(this)
  }

  _queueWaiting(resolve) {
    this.waiting.push(resolve)
  }

  _queueFlushed(resolve) {
    this.flushedResolve = resolve
  }

  wait() {
    if (this.destroyed === true) return DESTROYED

    if (this.active < this.limit && this.waiting.length === 0) {
      this.active++
      return DONE
    }

    return new Promise(this._onwait)
  }

  signal() {
    if (this.destroyed === true) return

    this.active--
    while (this.active < this.limit && this.waiting.length > 0 && this.destroyed === false) {
      this.active++
      this.waiting.shift()(true)
    }

    if (this.active === 0 && this.flushedResolve) {
      const resolve = this.flushedResolve
      this.flushedResolve = null
      this.flushedPromise = null
      resolve(true)
    }
  }

  async flush() {
    if (this.destroyed === true) return
    if (this.active === 0) return
    if (this.flushedPromise) return this.flushedPromise
    this.flushedPromise = new Promise(this._onflush)
    return this.flushedPromise
  }

  destroy() {
    this.destroyed = true
    this.active = 0
    while (this.waiting.length) this.waiting.pop()(false)
    if (this.flushedResolve) this.flushedResolve(false)
  }
}
const { EventEmitter } = require('events')
const safetyCatch = require('safety-catch')
const NoiseSecretStream = require('@hyperswarm/secret-stream')
const b4a = require('b4a')
const relay = require('blind-relay')
const NoiseWrap = require('./noise-wrap')
const Announcer = require('./announcer')
const { FIREWALL, ERROR } = require('./constants')
const { unslabbedHash } = require('./crypto')
const SecurePayload = require('./secure-payload')
const Holepuncher = require('./holepuncher')
const { isPrivate } = require('bogon')
const { ALREADY_LISTENING, NODE_DESTROYED, KEYPAIR_ALREADY_USED } = require('./errors')

const HANDSHAKE_CLEAR_WAIT = 10000
const HANDSHAKE_INITIAL_TIMEOUT = 10000

module.exports = class Server extends EventEmitter {
  constructor(dht, opts = {}) {
    super()

    this.dht = dht
    this.target = null

    this.closed = false
    this.firewall = opts.firewall || (() => false)
    this.holepunch = opts.holepunch || (() => true)
    this.relayThrough = opts.relayThrough || null
    this.relayKeepAlive = opts.relayKeepAlive || 5000
    this.pool = opts.pool || null
    this.createHandshake = opts.createHandshake || defaultCreateHandshake
    this.createSecretStream = opts.createSecretStream || defaultCreateSecretStream
    this.suspended = false
    this.handshakeClearWait = opts.handshakeClearWait || HANDSHAKE_CLEAR_WAIT

    this._shareLocalAddress = opts.shareLocalAddress !== false
    this._reusableSocket = !!opts.reusableSocket
    this._neverPunch = opts.holepunch === false // useful for fully disabling punching
    this._keyPair = null
    this._announcer = null
    this._connects = new Map()
    this._holepunches = []
    this._listening = null
    this._closing = null
  }

  get listening() {
    return this._listening !== null
  }

  get publicKey() {
    return this._keyPair && this._keyPair.publicKey
  }

  get relayAddresses() {
    return this._announcer ? this._announcer.relayAddresses : []
  }

  onconnection(encryptedSocket) {
    this.emit('connection', encryptedSocket)
  }

  async suspend({ log = noop } = {}) {
    log('Suspending hyperdht server')
    if (this._listening !== null) await this._listening
    log('Suspending hyperdht server (post listening)')
    this.suspended = true
    this._clearAll()
    return this._announcer ? this._announcer.suspend({ log }) : Promise.resolve()
  }

  async resume() {
    if (this._listening !== null) await this._listening
    this.suspended = false
    return this._announcer ? this._announcer.resume() : Promise.resolve()
  }

  address() {
    if (!this._keyPair) return null

    return {
      publicKey: this._keyPair.publicKey,
      host: this.dht.host,
      port: this.dht.port
    }
  }

  close() {
    if (this._closing) return this._closing
    this._closing = this._close()
    return this._closing
  }

  _gc() {
    this.dht.listening.delete(this)
    if (this.target) this.dht._router.delete(this.target)
  }

  async _stopListening() {
    try {
      if (this._announcer) await this._announcer.stop()
    } catch {
      // ignore
    }

    this._announcer = null
    this._listening = null
    this._keyPair = null
  }

  async _close() {
    if (this._listening === null) {
      this.closed = true
      this.emit('close')
      return
    }

    try {
      await this._listening
    } catch (err) {
      safetyCatch(err)
    }

    this._gc()
    this._clearAll()

    await this._stopListening()

    this.closed = true
    this.emit('close')
  }

  _clearAll() {
    while (this._holepunches.length > 0) {
      const h = this._holepunches.pop()
      if (h && h.puncher) h.puncher.destroy()
      if (h && h.clearing) clearTimeout(h.clearing)
      if (h && h.prepunching) clearTimeout(h.prepunching)
      if (h && h.rawStream) h.rawStream.destroy()
    }

    this._connects.clear()
  }

  async listen(keyPair = this.dht.defaultKeyPair, opts = {}) {
    if (this._listening !== null) throw ALREADY_LISTENING()
    if (this.dht.destroyed) throw NODE_DESTROYED()

    this._listening = this._listen(keyPair, opts)
    await this._listening
    return this
  }

  async _listen(keyPair, opts) {
    // From now on, the DHT object which created me is responsible for closing me
    this.dht.listening.add(this)

    try {
      await this.dht.bind()
      if (this._closing) return

      for (const s of this.dht.listening) {
        if (s._keyPair && b4a.equals(s._keyPair.publicKey, keyPair.publicKey)) {
          throw KEYPAIR_ALREADY_USED()
        }
      }

      this.target = unslabbedHash(keyPair.publicKey)
      this._keyPair = keyPair
      this._announcer = new Announcer(this.dht, keyPair, this.target, opts)

      this.dht._router.set(this.target, {
        relay: null,
        record: this._announcer.record,
        onpeerhandshake: this._onpeerhandshake.bind(this),
        onpeerholepunch: this._onpeerholepunch.bind(this)
      })

      // warm it up for now
      this._localAddresses().catch(safetyCatch)

      await this._announcer.start()
    } catch (err) {
      await this._stopListening()
      this._gc()
      throw err
    }

    if (this._closing) return
    if (this.suspended) await this._announcer.suspend()

    if (this._closing) return
    if (this.dht.destroyed) throw NODE_DESTROYED()

    if (this.pool) this.pool._attachServer(this)

    this.emit('listening')
  }

  refresh() {
    if (this._announcer && !this.suspended) this._announcer.refresh()
  }

  notifyOnline() {
    if (this._announcer) this._announcer.online.notify()
  }

  _localAddresses() {
    return this.dht.validateLocalAddresses(Holepuncher.localAddresses(this.dht.io.serverSocket))
  }

  async _addHandshake(k, noise, clientAddress, { from, to: serverAddress, socket }, direct) {
    let id = this._holepunches.indexOf(null)
    if (id === -1) id = this._holepunches.push(null) - 1

    const hs = {
      round: 0,
      reply: null,
      puncher: null,
      payload: null,
      rawStream: null,
      encryptedSocket: null,
      prepunching: null,
      firewalled: true,
      clearing: null,
      onsocket: null,
      aborted: false,

      // Relay state
      relayTimeout: null,
      relayToken: null,
      relaySocket: null,
      relayClient: null,
      relayPaired: false
    }

    this._holepunches[id] = hs

    const handshake = this.createHandshake(this._keyPair, null)

    let remotePayload
    try {
      remotePayload = await handshake.recv(noise)
    } catch (err) {
      safetyCatch(err)
      this._clearLater(hs, id, k)
      return null
    }

    if (this._closing || this.suspended) return null

    try {
      hs.firewalled = await this.firewall(handshake.remotePublicKey, remotePayload, clientAddress)
    } catch (err) {
      safetyCatch(err)
    }

    if (this._closing || this.suspended) return null

    if (hs.firewalled) {
      this._clearLater(hs, id, k)
      return null
    }

    const error =
      remotePayload.version === 1
        ? remotePayload.udx
          ? ERROR.NONE
          : ERROR.ABORTED
        : ERROR.VERSION_MISMATCH

    const addresses = []
    const ourRemoteAddr = this.dht.remoteAddress()
    const ourLocalAddrs = this._shareLocalAddress ? await this._localAddresses() : null

    if (this._closing || this.suspended) return null

    if (ourRemoteAddr) addresses.push(ourRemoteAddr)
    if (ourLocalAddrs) addresses.push(...ourLocalAddrs)

    if (error === ERROR.NONE) {
      hs.rawStream = this.dht.createRawStream({
        framed: true,
        firewall(socket, port, host) {
          if (!(port > 0 && port < 65536)) return true

          // Check if the traffic originated from the socket on which we're expecting relay traffic. If so,
          // we haven't hole punched yet and the other side is just sending us traffic through the relay.
          if (hs.relaySocket && isRelay(hs.relaySocket, socket, port, host)) {
            return false
          }

          hs.onsocket(socket, port, host)
          return false
        }
      })

      hs.rawStream.on('error', autoDestroy)

      // Handles the case where onsocket is never called, but the stream got setup
      // This can happen on a relayed connection which never connects directly
      // (onsocket is called there only when the direct connection is established)
      const onrawstreamclose = () => {
        if (this._closing) return
        this._clearLater(hs, id, k)
      }
      hs.rawStream.on('close', onrawstreamclose)

      hs.onsocket = (socket, port, host) => {
        if (hs.rawStream === null) return // Already hole punched

        this._clearLater(hs, id, k)

        if (hs.prepunching) {
          clearTimeout(hs.prepunching)
          hs.prepunching = null
        }

        if (this._reusableSocket && remotePayload.udx.reusableSocket) {
          this.dht._socketPool.routes.add(handshake.remotePublicKey, hs.rawStream)
        }

        hs.rawStream.removeListener('error', autoDestroy)
        hs.rawStream.removeListener('close', onrawstreamclose)

        if (hs.rawStream.connected) {
          const remoteChanging = hs.rawStream.changeRemote(socket, remotePayload.udx.id, port, host)

          if (remoteChanging) remoteChanging.catch(safetyCatch)
        } else {
          hs.rawStream.connect(socket, remotePayload.udx.id, port, host)
          hs.encryptedSocket = this.createSecretStream(false, hs.rawStream, {
            handshake: h,
            keepAlive: this.dht.connectionKeepAlive
          })

          this.onconnection(hs.encryptedSocket)
        }

        if (hs.puncher) {
          hs.puncher.onabort = noop
          hs.puncher.destroy()
        }

        hs.rawStream = null
      }

      function autoDestroy() {
        if (hs.puncher) hs.puncher.destroy()
      }
    }

    const relayAddresses = this.relayAddresses
    const relayThrough = selectRelay(this.relayThrough)

    if (relayThrough) hs.relayToken = relay.token()

    try {
      hs.reply = await handshake.send({
        error,
        firewall: ourRemoteAddr ? FIREWALL.OPEN : FIREWALL.UNKNOWN,
        holepunch: ourRemoteAddr ? null : { id, relays: this._announcer.relays },
        addresses4: addresses,
        addresses6: null,
        udx: {
          reusableSocket: this._reusableSocket,
          id: hs.rawStream ? hs.rawStream.id : 0,
          seq: 0
        },
        secretStream: {},
        relayThrough: relayThrough ? { publicKey: relayThrough, token: hs.relayToken } : null,
        relayAddresses: relayAddresses.length ? relayAddresses : null
      })
    } catch (err) {
      safetyCatch(err)
      if (hs.rawStream) hs.rawStream.destroy()
      this._clearLater(hs, id, k)
      return null
    }

    if (this._closing || this.suspended) {
      if (hs.rawStream) hs.rawStream.destroy()
      return null
    }

    const h = handshake.final()

    if (error !== ERROR.NONE) {
      if (hs.rawStream) hs.rawStream.destroy()
      this._clearLater(hs, id, k)
      return hs
    }

    if (remotePayload.firewall === FIREWALL.OPEN || direct) {
      const sock = direct ? socket : this.dht.socket
      this.dht.stats.punches.open++
      hs.onsocket(sock, clientAddress.port, clientAddress.host)
      return hs
    }

    if (relayThrough || remotePayload.relayThrough) {
      this._relayConnection(hs, relayThrough, remotePayload, h)
    }

    const onabort = () => {
      hs.aborted = true
      if (hs.prepunching) clearTimeout(hs.prepunching)
      hs.prepunching = null
      if (hs.rawStream.destroyed) {
        this._clearLater(hs, id, k)
        return
      }

      hs.rawStream.on('close', () => this._clearLater(hs, id, k))
      if (hs.relayToken === null) hs.rawStream.destroy()
    }

    if (!direct && clientAddress.host === serverAddress.host) {
      const clientAddresses = remotePayload.addresses4.filter(onlyPrivateHosts)

      if (clientAddresses.length > 0 && this._shareLocalAddress) {
        const myAddresses = await this._localAddresses()
        const addr = Holepuncher.matchAddress(myAddresses, clientAddresses)

        if (addr) {
          hs.prepunching = setTimeout(onabort, HANDSHAKE_INITIAL_TIMEOUT)
          return hs
        }
      }
    }

    if (this._closing || this.suspended) return null

    if (ourRemoteAddr || this._neverPunch) {
      hs.prepunching = setTimeout(onabort, HANDSHAKE_INITIAL_TIMEOUT)
      return hs
    }

    hs.payload = new SecurePayload(h.holepunchSecret)
    hs.puncher = new Holepuncher(this.dht, this.dht.session(), false, remotePayload.firewall)

    hs.puncher.onconnect = hs.onsocket
    hs.puncher.onabort = onabort
    hs.prepunching = setTimeout(hs.puncher.destroy.bind(hs.puncher), HANDSHAKE_INITIAL_TIMEOUT)

    return hs
  }

  _clearLater(hs, id, k) {
    if (hs.clearing) return
    hs.clearing = setTimeout(() => this._clear(hs, id, k), this.handshakeClearWait)
  }

  _clear(hs, id, k) {
    if (id >= this._holepunches.length || this._holepunches[id] !== hs) return
    if (hs.clearing) clearTimeout(hs.clearing)

    this._holepunches[id] = null
    while (
      this._holepunches.length > 0 &&
      this._holepunches[this._holepunches.length - 1] === null
    ) {
      this._holepunches.pop()
    }
    this._connects.delete(k)
  }

  async _onpeerhandshake({ noise, peerAddress }, req) {
    const k = b4a.toString(noise, 'hex')

    // The next couple of statements MUST run within the same tick to prevent
    // a malicious peer from flooding us with handshakes.
    let p = this._connects.get(k)
    if (!p) {
      p = this._addHandshake(k, noise, peerAddress || req.from, req, !peerAddress)
      this._connects.set(k, p)
    }

    const h = await p
    if (!h) return null

    if (this._closing !== null || this.suspended) return null

    return { socket: h.puncher && h.puncher.socket, noise: h.reply }
  }

  async _onpeerholepunch({ id, peerAddress, payload }, req) {
    const h = id < this._holepunches.length ? this._holepunches[id] : null
    if (!h) return null

    if (!peerAddress || this._closing !== null || this.suspended) return null

    const p = h.puncher
    if (!p || !p.socket) return this._abort(h) // not opened

    const remotePayload = h.payload.decrypt(payload)
    if (!remotePayload) return null

    const isServerRelay = this._announcer.isRelay(req.from)
    const { error, firewall, round, punching, addresses, remoteAddress, remoteToken } =
      remotePayload

    if (error !== ERROR.NONE) {
      // We actually do not need to set the round here, but just do it for consistency.
      if (round >= h.round) h.round = round
      return this._abort(h)
    }

    const token = h.payload.token(peerAddress)
    const echoed = isServerRelay && !!remoteToken && b4a.equals(token, remoteToken)

    // Update our heuristics here
    if (req.socket === p.socket) {
      p.nat.add(req.to, req.from)
    }

    if (round >= h.round) {
      h.round = round
      p.updateRemote({ punching, firewall, addresses, verified: echoed ? peerAddress.host : null })
    }

    // Wait for the analyzer to reach a conclusion...
    let stable = await p.analyze(false)
    if (p.destroyed) return null

    if (!p.remoteHolepunching && !stable) {
      stable = await p.analyze(true)
      if (p.destroyed) return null
      if (!stable) return this._abort(h)
    }

    // Fast mode! If we are consistent and the remote has opened a session to us (remoteAddress)
    // then fire a quick punch back. Note the await here just waits for the udp socket to flush.
    if (
      isConsistent(p.nat.firewall) &&
      remoteAddress &&
      hasSameAddr(p.nat.addresses, remoteAddress)
    ) {
      await p.ping(peerAddress)
      if (p.destroyed) return null
    }

    // Remote said they are punching (or willing to), so we will punch as well.
    // Note that this returns when the punching has STARTED, so no guarantee
    // we will have a connection after this promise etc.
    if (p.remoteHolepunching) {
      // TODO: still continue here if a local connection might work, but then do not holepunch...
      if (!this.holepunch(p.remoteFirewall, p.nat.firewall, p.remoteAddresses, p.nat.addresses)) {
        return p.destroyed ? null : this._abort(h)
      }

      if (h.prepunching) {
        clearTimeout(h.prepunching)
        h.prepunching = null
      }

      if (p.remoteFirewall >= FIREWALL.RANDOM || p.nat.firewall >= FIREWALL.RANDOM) {
        if (
          this.dht._randomPunches >= this.dht._randomPunchLimit ||
          Date.now() - this.dht._lastRandomPunch < this.dht._randomPunchInterval
        ) {
          if (!h.relayToken) return this._abort(h, ERROR.TRY_LATER)
          return {
            socket: p.socket,
            payload: h.payload.encrypt({
              error: ERROR.TRY_LATER,
              firewall: p.nat.firewall,
              round: h.round,
              connected: p.connected,
              punching: p.punching,
              addresses: p.nat.addresses,
              remoteAddress: null,
              token: isServerRelay ? token : null,
              remoteToken: remotePayload.token
            })
          }
        }
      }

      const punching = await p.punch()
      if (p.destroyed) return null
      if (!punching) return this._abort(h)
    }

    // Freeze that analysis as soon as we have a result we are giving to the other peer
    if (p.nat.firewall !== FIREWALL.UNKNOWN) {
      p.nat.freeze()
    }

    return {
      socket: p.socket,
      payload: h.payload.encrypt({
        error: ERROR.NONE,
        firewall: p.nat.firewall,
        round: h.round,
        connected: p.connected,
        punching: p.punching,
        addresses: p.nat.addresses,
        remoteAddress: null,
        token: isServerRelay ? token : null,
        remoteToken: remotePayload.token
      })
    }
  }

  _abort(h, error = ERROR.ABORTED) {
    if (!h.payload) {
      if (h.puncher) h.puncher.destroy()
      return null
    }

    const payload = h.payload.encrypt({
      error,
      firewall: FIREWALL.UNKNOWN,
      round: h.round,
      connected: false,
      punching: false,
      addresses: null,
      remoteAddress: null,
      token: null,
      remoteToken: null
    })

    h.puncher.destroy()

    return { socket: this.dht.socket, payload }
  }

  _relayConnection(hs, relayThrough, remotePayload, h) {
    this.dht.stats.relaying.attempts++

    let isInitiator
    let publicKey
    let token

    if (relayThrough) {
      isInitiator = true
      publicKey = relayThrough
      token = hs.relayToken
    } else {
      isInitiator = false
      publicKey = remotePayload.relayThrough.publicKey
      token = remotePayload.relayThrough.token
    }

    hs.relayToken = token
    hs.relaySocket = this.dht.connect(publicKey)
    hs.relaySocket.setKeepAlive(this.relayKeepAlive)
    hs.relayClient = relay.Client.from(hs.relaySocket, { id: hs.relaySocket.publicKey })
    hs.relayTimeout = setTimeout(onabort, 15000)

    hs.relayClient
      .pair(isInitiator, token, hs.rawStream)
      .on('error', onabort)
      .on('data', (remoteId) => {
        if (hs.relayTimeout) clearRelayTimeout(hs)
        if (hs.rawStream === null) {
          onabort(null)
          return
        }

        hs.relayPaired = true
        this.dht.stats.relaying.successes++

        if (hs.prepunching) clearTimeout(hs.prepunching)
        hs.prepunching = null

        const { remotePort, remoteHost, socket } = hs.relaySocket.rawStream

        hs.rawStream
          .on('close', () => hs.relaySocket.destroy())
          .connect(socket, remoteId, remotePort, remoteHost)

        hs.encryptedSocket = this.createSecretStream(false, hs.rawStream, { handshake: h })

        this.onconnection(hs.encryptedSocket)
      })

    const dht = this.dht
    function onabort() {
      if (!hs.relayPaired) dht.stats.relaying.aborts++
      if (hs.relayTimeout) clearRelayTimeout(hs)
      const socket = hs.relaySocket
      hs.relayToken = null
      hs.relaySocket = null
      if (socket) socket.destroy()
      if (hs.aborted && hs.rawStream) hs.rawStream.destroy()
    }
  }
}

function clearRelayTimeout(hs) {
  clearTimeout(hs.relayTimeout)
  hs.relayTimeout = null
}

function isConsistent(fw) {
  return fw === FIREWALL.OPEN || fw === FIREWALL.CONSISTENT
}

function hasSameAddr(addrs, other) {
  if (addrs === null) return false

  for (const addr of addrs) {
    if (addr.port === other.port && addr.host === other.host) return true
  }
  return false
}

function defaultCreateHandshake(keyPair, remotePublicKey) {
  return new NoiseWrap(keyPair, remotePublicKey)
}

function defaultCreateSecretStream(isInitiator, rawStream, opts) {
  return new NoiseSecretStream(isInitiator, rawStream, opts)
}

function onlyPrivateHosts(addr) {
  return isPrivate(addr.host)
}

function isRelay(relaySocket, socket, port, host) {
  const stream = relaySocket.rawStream
  if (!stream) return false
  if (stream.socket !== socket) return false
  return port === stream.remotePort && host === stream.remoteHost
}

function selectRelay(relayThrough) {
  if (typeof relayThrough === 'function') relayThrough = relayThrough()
  if (relayThrough === null) return null
  if (Array.isArray(relayThrough)) {
    return relayThrough[Math.floor(Math.random() * relayThrough.length)]
  }
  return relayThrough
}

function noop() {}
module.exports = class Sleeper {
  constructor() {
    this._timeout = null
    this._resolve = null

    this._start = (resolve) => {
      this._resolve = resolve
    }

    this._trigger = () => {
      if (this._resolve === null) return
      const resolve = this._resolve
      this._timeout = null
      this._resolve = null
      resolve()
    }
  }

  pause(ms) {
    const p = new Promise(this._start)
    if (this._timeout !== null) {
      clearTimeout(this._timeout)
      this._trigger()
    }
    this._timeout = setTimeout(this._trigger, ms)
    return p
  }

  resume() {
    if (this._timeout !== null) {
      clearTimeout(this._timeout)
      this._trigger()
    }
  }
}
const b4a = require('b4a')

const LINGER_TIME = 3000

module.exports = class SocketPool {
  constructor(dht, host) {
    this._dht = dht
    this._sockets = new Map()
    this._lingering = new Set() // updated by the ref
    this._host = host

    this.routes = new SocketRoutes(this)
  }

  _onmessage(ref, data, address) {
    this._dht.onmessage(ref.socket, data, address)
  }

  _add(ref) {
    this._sockets.set(ref.socket, ref)
  }

  _remove(ref) {
    this._sockets.delete(ref.socket)
    this._lingering.delete(ref)
  }

  lookup(socket) {
    return this._sockets.get(socket) || null
  }

  setReusable(socket, bool) {
    const ref = this.lookup(socket)
    if (ref) ref.reusable = bool
  }

  acquire() {
    // TODO: Enable socket reuse
    return new SocketRef(this)
  }

  async destroy() {
    const closing = []

    for (const ref of this._sockets.values()) {
      ref._unlinger()
      closing.push(ref.socket.close())
    }

    await Promise.allSettled(closing)
  }
}

class SocketRoutes {
  constructor(pool) {
    this._pool = pool
    this._routes = new Map()
  }

  add(publicKey, rawStream) {
    if (rawStream.socket) this._onconnect(publicKey, rawStream)
    else rawStream.on('connect', this._onconnect.bind(this, publicKey, rawStream))
  }

  get(publicKey) {
    const id = b4a.toString(publicKey, 'hex')
    const route = this._routes.get(id)
    if (!route) return null
    return route
  }

  _onconnect(publicKey, rawStream) {
    const id = b4a.toString(publicKey, 'hex')
    const socket = rawStream.socket

    let route = this._routes.get(id)

    if (!route) {
      const gc = () => {
        if (this._routes.get(id) === route) this._routes.delete(id)
        socket.removeListener('close', gc)
      }

      route = {
        socket,
        address: { host: rawStream.remoteHost, port: rawStream.remotePort },
        gc
      }

      this._routes.set(id, route)
      socket.on('close', gc)
    }

    this._pool.setReusable(socket, true)

    rawStream.on('error', () => {
      this._pool.setReusable(socket, false)
      if (!route) route = this._routes.get(id)
      if (route && route.socket === socket) route.gc()
    })
  }
}

// TODO: we should just make some "user data" object on udx to allow to attach this info
class SocketRef {
  constructor(pool) {
    this._pool = pool

    // Events
    this.onholepunchmessage = noop

    // Whether it should teardown immediately or wait a bit
    this.reusable = false

    this.socket = pool._dht.udx.createSocket()
    this.socket
      .on('close', this._onclose.bind(this))
      .on('message', this._onmessage.bind(this))
      .on('idle', this._onidle.bind(this))
      .on('busy', this._onbusy.bind(this))
      .bind(0, this._pool._host)

    this._refs = 1
    this._released = false
    this._closed = false

    this._timeout = null
    this._wasBusy = false

    this._pool._add(this)
  }

  _onclose() {
    this._pool._remove(this)
  }

  _onmessage(data, address) {
    if (data.byteLength > 1) {
      this._pool._onmessage(this, data, address)
    } else {
      this.onholepunchmessage(data, address, this)
    }
  }

  _onidle() {
    this._closeMaybe()
  }

  _onbusy() {
    this._wasBusy = true
    this._unlinger()
  }

  _reset() {
    this.onholepunchmessage = noop
  }

  _closeMaybe() {
    if (this._refs === 0 && this.socket.idle && !this._timeout) this._close()
  }

  _lingeringClose() {
    this._pool._lingering.delete(this)
    this._timeout = null
    this._closeMaybe()
  }

  _close() {
    this._unlinger()

    if (this.reusable && this._wasBusy) {
      this._wasBusy = false
      this._pool._lingering.add(this)
      this._timeout = setTimeout(this._lingeringClose.bind(this), LINGER_TIME)
      return
    }

    this._closed = true
    this.socket.close()
  }

  _unlinger() {
    if (this._timeout !== null) {
      clearTimeout(this._timeout)
      this._pool._lingering.delete(this)
      this._timeout = null
    }
  }

  get free() {
    return this._refs === 0
  }

  active() {
    this._refs++
    this._unlinger()
  }

  inactive() {
    this._refs--
    this._closeMaybe()
  }

  address() {
    return this.socket.address()
  }

  release() {
    if (this._released) return

    this._released = true
    this._reset()

    this._refs--
    this._closeMaybe()
  }
}

function noop() {}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return uint24.decode(state) + 0x1000000 * uint32.decode(state)
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return uint32.decode(state) + 0x100000000 * uint32.decode(state)
  }
})

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "2.19.2",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    if (b.byteLength === 0) return null
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "hyperdht",
  "version": "6.31.0",
  "description": "The DHT powering Hyperswarm",
  "main": "index.js",
  "browser": "browser.js",
  "bin": {
    "hyperdht": "./bin.js"
  },
  "files": [
    "index.js",
    "browser.js",
    "testnet.js",
    "bin.js",
    "lib/**.js"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    },
    "child_process": {
      "bare": "bare-node-child-process",
      "default": "child_process"
    }
  },
  "dependencies": {
    "@hyperswarm/secret-stream": "^6.6.2",
    "b4a": "^1.3.1",
    "bare-events": "^2.2.0",
    "blind-relay": "^1.3.0",
    "bogon": "^1.0.0",
    "compact-encoding": "^2.4.1",
    "dht-rpc": "^6.15.1",
    "hypercore-crypto": "^3.3.0",
    "hypercore-id-encoding": "^1.2.0",
    "hyperdht-address": "^1.0.1",
    "noise-curve-ed": "^2.0.0",
    "noise-handshake": "^4.0.0",
    "record-cache": "^1.1.1",
    "safety-catch": "^1.0.1",
    "signal-promise": "^1.0.3",
    "sodium-universal": "^5.0.1",
    "streamx": "^2.16.1",
    "unslab": "^1.3.0",
    "xache": "^1.1.0"
  },
  "devDependencies": {
    "bare-node-child-process": "^1.0.1",
    "brittle": "^3.0.0",
    "graceful-goodbye": "^1.3.0",
    "newline-decoder": "^1.0.2",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "test": "prettier --check . && node test/all.js",
    "test:bare": "bare test/all.js",
    "test:generate": "brittle -r test/all.js test/*.js",
    "integration": "brittle test/integration/*.js",
    "end-to-end": "brittle test/end-to-end/*.js"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "directories": {
    "lib": "lib",
    "test": "test"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/hyperdht.git"
  },
  "keywords": [],
  "bugs": {
    "url": "https://github.com/holepunchto/hyperdht/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperdht#readme"
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return uint24.decode(state) + 0x1000000 * uint32.decode(state)
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return uint32.decode(state) + 0x100000000 * uint32.decode(state)
  }
})

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "2.19.2",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    if (b.byteLength === 0) return null
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "hyperschema",
  "version": "1.20.1",
  "description": "Create registries of declarative compact-encoding schemas",
  "files": [
    "lib/*.js",
    "builder.mjs",
    "builder.cjs",
    "runtime.mjs",
    "runtime.cjs",
    "primitives.mjs",
    "primitives.cjs"
  ],
  "exports": {
    "./package": "./package.json",
    ".": {
      "import": "./builder.mjs",
      "default": "./builder.cjs"
    },
    "./runtime": {
      "import": "./runtime.mjs",
      "default": "./runtime.cjs"
    },
    "./primitives": {
      "import": "./primitives.mjs",
      "default": "./primitives.cjs"
    }
  },
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    }
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test/index.js",
    "test:bare": "prettier . --check && bare test/index.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/hyperschema.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/hyperschema/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperschema#readme",
  "dependencies": {
    "bare-fs": "^4.0.1",
    "compact-encoding": "^2.19.0",
    "generate-object-property": "^2.0.0",
    "generate-string": "^1.0.1"
  },
  "devDependencies": {
    "brittle": "^3.7.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "test-tmp": "^1.3.0"
  }
}
module.exports = {
  c: require('compact-encoding')
}
const { EventEmitter } = require('events')
const { getStreamError } = require('streamx')
const DHT = require('hyperdht')
const spq = require('shuffled-priority-queue')
const b4a = require('b4a')
const unslab = require('unslab')

const PeerInfo = require('./lib/peer-info')
const RetryTimer = require('./lib/retry-timer')
const ConnectionSet = require('./lib/connection-set')
const PeerDiscovery = require('./lib/peer-discovery')

const MAX_PEERS = 64
const MAX_PARALLEL = 3
const MAX_CLIENT_CONNECTIONS = Infinity // TODO: Change
const MAX_SERVER_CONNECTIONS = Infinity

const ERR_MISSING_TOPIC = 'Topic is required and must be a 32-byte buffer'
const ERR_DESTROYED = 'Swarm has been destroyed'
const ERR_DUPLICATE = 'Duplicate connection'
const ERR_FIREWALL = 'Peer is firewalled'

module.exports = class Hyperswarm extends EventEmitter {
  constructor(opts = {}) {
    super()
    const {
      seed,
      relayThrough,
      keyPair = DHT.keyPair(seed),
      maxPeers = MAX_PEERS,
      maxClientConnections = MAX_CLIENT_CONNECTIONS,
      maxServerConnections = MAX_SERVER_CONNECTIONS,
      maxParallel = MAX_PARALLEL,
      firewall = allowAll
    } = opts
    this.keyPair = keyPair

    this.dht =
      opts.dht ||
      new DHT({
        bootstrap: opts.bootstrap,
        nodes: opts.nodes,
        port: opts.port,
        deferRandomPunch: opts.deferRandomPunch,
        randomPunchInterval: opts.randomPunchInterval
      })
    this.server = this.dht.createServer(
      {
        firewall: this._handleFirewall.bind(this),
        relayThrough: this._maybeRelayConnection.bind(this),
        handshakeClearWait: opts.handshakeClearWait
      },
      this._handleServerConnection.bind(this)
    )

    this.destroyed = false
    this.suspended = false
    this.maxPeers = maxPeers
    this.maxClientConnections = maxClientConnections
    this.maxServerConnections = maxServerConnections
    this.maxParallel = maxParallel
    this.relayThrough = relayThrough ? toRelayFunction(relayThrough) : null

    this.connecting = 0
    this.connections = new Set()
    this.peers = new Map()
    this.explicitPeers = new Set()
    this.listening = null
    this.stats = {
      updates: 0,
      connects: {
        client: {
          opened: 0,
          closed: 0,
          attempted: 0
        },
        server: {
          // Note: there is no notion of 'attempts' for server connections
          opened: 0,
          closed: 0
        }
      },
      bannedPeers: 0
    }

    this._discovery = new Map()
    this._timer = new RetryTimer(this._requeue.bind(this), {
      backoffs: opts.backoffs,
      jitter: opts.jitter
    })
    this._queue = spq()

    this._allConnections = new ConnectionSet()
    this._pendingFlushes = []
    this._flushTick = 0

    this._drainingQueue = false
    this._clientConnections = 0
    this._serverConnections = 0
    this._firewall = firewall

    this.dht.on('network-change', this._handleNetworkChange.bind(this))
    this.dht.on('network-update', this._handleNetworkUpdate.bind(this))
    this.on('update', this._handleUpdate)
  }

  _maybeRelayConnection(force) {
    if (!this.relayThrough) return null
    return this.relayThrough(force, this)
  }

  _enqueue(peerInfo) {
    if (peerInfo.queued) return
    peerInfo.queued = true
    peerInfo._flushTick = this._flushTick
    this._queue.add(peerInfo)

    this._attemptClientConnections()
  }

  _requeue(batch) {
    if (this.suspended) return
    for (const peerInfo of batch) {
      peerInfo.waiting = false

      if (
        peerInfo._updatePriority() === false ||
        this._allConnections.has(peerInfo.publicKey) ||
        peerInfo.queued
      ) {
        continue
      }
      peerInfo.queued = true
      peerInfo._flushTick = this._flushTick
      this._queue.add(peerInfo)
    }

    this._attemptClientConnections()
  }

  _flushMaybe(peerInfo) {
    for (let i = 0; i < this._pendingFlushes.length; i++) {
      const flush = this._pendingFlushes[i]
      if (peerInfo._flushTick > flush.tick) continue
      if (--flush.missing > 0) continue
      flush.onflush(true)
      this._pendingFlushes.splice(i--, 1)
    }
  }

  _withinMaxPeers() {
    const e = this.explicitPeers.size
    const factor = e === 0 ? 1 : e < 2 ? 2 : e < 4 ? 3 : 4
    return factor * this._allConnections.size < this.maxPeers
  }

  _flushAllMaybe() {
    if (
      this.connecting > 0 ||
      (this._withinMaxPeers() && this._clientConnections < this.maxClientConnections)
    ) {
      return false
    }

    while (this._pendingFlushes.length) {
      const flush = this._pendingFlushes.pop()
      flush.onflush(true)
    }

    return true
  }

  _shouldConnectExplicit() {
    return !this.destroyed && !this.suspended && this.connecting < this.maxParallel
  }

  _shouldConnect() {
    return (
      !this.destroyed &&
      !this.suspended &&
      this.connecting < this.maxParallel &&
      this._withinMaxPeers() &&
      this._clientConnections < this.maxClientConnections
    )
  }

  _shouldRequeue(peerInfo) {
    if (this.suspended) return false
    if (peerInfo.explicit) return true
    for (const topic of peerInfo.topics) {
      if (this._discovery.has(b4a.toString(topic, 'hex')) && !this.destroyed) {
        return true
      }
    }
    return false
  }

  _connect(peerInfo, queued) {
    if (peerInfo.banned || this._allConnections.has(peerInfo.publicKey)) {
      if (queued) this._flushMaybe(peerInfo)
      return
    }

    // TODO: Support async firewalling at some point.
    if (this._handleFirewall(peerInfo.publicKey, null)) {
      if (queued) this._flushMaybe(peerInfo)
      return
    }

    const relayThrough = this._maybeRelayConnection(peerInfo.forceRelaying)
    const conn = this.dht.connect(peerInfo.publicKey, {
      relayAddresses: peerInfo.relayAddresses,
      keyPair: this.keyPair,
      relayThrough
    })
    this._allConnections.add(conn)

    this.stats.connects.client.attempted++

    this.connecting++
    this._clientConnections++
    let opened = false

    const onerror = (err) => {
      if (this.relayThrough && shouldForceRelaying(err.code)) {
        peerInfo.forceRelaying = true
        // Reset the attempts in order to fast connect to relay
        peerInfo.attempts = 0
      }
    }

    // Removed once a connection is opened
    conn.on('error', onerror)

    conn.on('open', () => {
      opened = true
      this.stats.connects.client.opened++

      this._connectDone()
      this.connections.add(conn)
      conn.removeListener('error', onerror)
      peerInfo._connected()
      peerInfo.client = true
      this.emit('connection', conn, peerInfo)
      if (queued) this._flushMaybe(peerInfo)

      this.emit('update')
    })
    conn.on('close', () => {
      if (!opened) this._connectDone()
      this.stats.connects.client.closed++

      const err = getStreamError(conn)
      if (shouldBan(err)) {
        this._banPeer(peerInfo, true, err)
      }

      this.connections.delete(conn)
      this._allConnections.delete(conn)
      this._clientConnections--
      peerInfo._disconnected()

      peerInfo.waiting = this._shouldRequeue(peerInfo) && this._timer.add(peerInfo)
      this._maybeDeletePeer(peerInfo)

      if (!opened && queued) this._flushMaybe(peerInfo)

      this._attemptClientConnections()

      this.emit('update')
    })

    this.emit('update')
  }

  _connectDone() {
    this.connecting--

    if (this.connecting < this.maxParallel) this._attemptClientConnections()
    if (this.connecting === 0) this._flushAllMaybe()
  }

  // Called when the PeerQueue indicates a connection should be attempted.
  _attemptClientConnections() {
    // Guard against re-entries - unsure if it still needed but doesn't hurt
    if (this._drainingQueue || this.suspended) return
    this._drainingQueue = true

    for (const peerInfo of this.explicitPeers) {
      if (!this._shouldConnectExplicit()) break
      if (
        peerInfo.attempts >= 5 ||
        Date.now() - peerInfo.disconnectedTime < peerInfo.attempts * 1000
      ) {
        continue
      }
      this._connect(peerInfo, false)
    }

    while (this._queue.length && this._shouldConnect()) {
      const peerInfo = this._queue.shift()
      peerInfo.queued = false
      this._connect(peerInfo, true)
    }
    this._drainingQueue = false
    if (this.connecting === 0) this._flushAllMaybe()
  }

  _handleFirewall(remotePublicKey, payload) {
    if (b4a.equals(remotePublicKey, this.keyPair.publicKey)) return true

    let peerInfo = this.peers.get(b4a.toString(remotePublicKey, 'hex'))
    if (peerInfo && peerInfo.banned) return true

    const firewalled = this._firewall(remotePublicKey, payload)
    if (firewalled) {
      if (!peerInfo) peerInfo = this._upsertPeer(remotePublicKey)
      this._banPeer(peerInfo, true, new Error(ERR_FIREWALL))
    }

    return firewalled
  }

  _handleServerConnectionSwap(existing, conn) {
    let closed = false

    existing.on('close', () => {
      if (closed) return

      conn.removeListener('error', noop)
      conn.removeListener('close', onclose)

      this._handleServerConnection(conn)
    })

    conn.on('error', noop)
    conn.on('close', onclose)

    function onclose() {
      closed = true
    }
  }

  // Called when the DHT receives a new server connection.
  _handleServerConnection(conn) {
    if (this.destroyed || this.suspended) {
      // TODO: Investigate why a final server connection can be received after close
      conn.on('error', noop)
      return conn.destroy(ERR_DESTROYED)
    }

    const existing = this._allConnections.get(conn.remotePublicKey)

    if (existing) {
      // If both connections are from the same peer,
      // - pick the new one if the existing stream is already established (has sent and received bytes),
      //   because the other client must have lost that connection and be reconnecting
      // - otherwise, pick the one thats expected to initiate in a tie break
      const existingIsOutdated = existing.rawBytesRead > 0 && existing.rawBytesWritten > 0
      const expectedInitiator = b4a.compare(conn.publicKey, conn.remotePublicKey) > 0
      const keepNew = existingIsOutdated || expectedInitiator === conn.isInitiator

      if (keepNew === false) {
        existing.sendKeepAlive()
        conn.on('error', noop)
        conn.destroy(new Error(ERR_DUPLICATE))
        return
      }

      existing.on('error', noop)
      existing.destroy(new Error(ERR_DUPLICATE))
      this._handleServerConnectionSwap(existing, conn)
      return
    }

    // When reaching here, the connection will always be 'opened' next tick
    this.stats.connects.server.opened++

    const peerInfo = this._upsertPeer(conn.remotePublicKey, null)

    this.connections.add(conn)
    this._allConnections.add(conn)
    this._serverConnections++

    conn.on('close', () => {
      const err = getStreamError(conn)
      if (shouldBan(err)) {
        this._banPeer(peerInfo, true, err)
      }

      this.connections.delete(conn)
      this._allConnections.delete(conn)
      this._serverConnections--
      this.stats.connects.server.closed++

      this._maybeDeletePeer(peerInfo)

      this._attemptClientConnections()

      this.emit('update')
    })
    peerInfo.client = false
    this.emit('connection', conn, peerInfo)

    this.emit('update')
  }

  _upsertPeer(publicKey, relayAddresses) {
    if (b4a.equals(publicKey, this.keyPair.publicKey)) return null
    const keyString = b4a.toString(publicKey, 'hex')
    let peerInfo = this.peers.get(keyString)

    if (peerInfo) {
      peerInfo.relayAddresses = relayAddresses // new is always better
      return peerInfo
    }

    peerInfo = new PeerInfo({
      publicKey,
      relayAddresses
    })

    this.peers.set(keyString, peerInfo)
    return peerInfo
  }

  _handleUpdate() {
    this.stats.updates++
  }

  _maybeDeletePeer(peerInfo) {
    if (!peerInfo.shouldGC()) return

    const hasActiveConn = this._allConnections.has(peerInfo.publicKey)
    if (hasActiveConn) return

    const keyString = b4a.toString(peerInfo.publicKey, 'hex')
    this.peers.delete(keyString)
  }

  /*
   * Called when a peer is actively discovered during a lookup.
   *
   * Three conditions:
   *  1. Not a known peer -- insert into queue
   *  2. A known peer with normal priority -- do nothing
   *  3. A known peer with low priority -- bump priority, because it's been rediscovered
   */
  _handlePeer(peer, topic) {
    const peerInfo = this._upsertPeer(peer.publicKey, peer.relayAddresses)
    if (peerInfo) peerInfo._topic(topic)
    if (!peerInfo || this._allConnections.has(peer.publicKey)) return
    if (!peerInfo.prioritized || peerInfo.server) peerInfo._reset()
    if (peerInfo._updatePriority()) {
      this._enqueue(peerInfo)
    }
  }

  async _handleNetworkUpdate() {
    if (!this.online) return
    this._handleNetworkChange()
  }

  async _handleNetworkChange() {
    if (this.suspended) return

    // prioritize figuring out if existing connections are dead
    for (const conn of this._allConnections) {
      conn.sendKeepAlive()
    }

    const refreshes = []

    for (const discovery of this._discovery.values()) {
      refreshes.push(discovery.refresh())
    }

    await Promise.allSettled(refreshes)
  }

  _banPeer(peerInfo, banned, err) {
    peerInfo.ban(banned)
    this.stats.bannedPeers++
    this.emit('ban', peerInfo, err)
  }

  status(key) {
    return this._discovery.get(b4a.toString(key, 'hex')) || null
  }

  listen() {
    if (!this.listening) {
      if (this.destroyed) throw new Error('Swarm destroyed')
      this.listening = this.server.listen(this.keyPair)
    }
    return this.listening
  }

  // Object that exposes a cancellation method (destroy)
  // TODO: When you rejoin, it should reannounce + bump lookup priority
  join(topic, opts = {}) {
    if (this.destroyed) throw new Error('Swarm destroyed')
    if (!topic) throw new Error(ERR_MISSING_TOPIC)
    topic = unslab(topic)

    const topicString = b4a.toString(topic, 'hex')

    let discovery = this._discovery.get(topicString)

    if (discovery && !discovery.destroyed) {
      return discovery.session(opts)
    }

    discovery = new PeerDiscovery(this, topic, {
      limit: opts.limit,
      wait: discovery ? discovery.destroy() : null,
      suspended: this.suspended,
      onpeer: (peer) => this._handlePeer(peer, topic)
    })
    this._discovery.set(topicString, discovery)
    return discovery.session(opts)
  }

  // Returns a promise
  async leave(topic) {
    if (!topic) throw new Error(ERR_MISSING_TOPIC)
    const topicString = b4a.toString(topic, 'hex')
    if (!this._discovery.has(topicString)) return Promise.resolve()

    const discovery = this._discovery.get(topicString)

    try {
      await discovery.destroy()
    } catch {
      // ignore, prop network
    }

    if (this._discovery.get(topicString) === discovery) {
      this._discovery.delete(topicString)
    }
  }

  joinPeer(publicKey) {
    const peerInfo = this._upsertPeer(publicKey, null)
    if (!peerInfo) return
    if (!this.explicitPeers.has(peerInfo)) {
      peerInfo.explicit = true
      this.explicitPeers.add(peerInfo)
    }
    if (this._allConnections.has(publicKey)) return
    if (peerInfo._updatePriority()) {
      this._enqueue(peerInfo)
    }
  }

  leavePeer(publicKey) {
    const keyString = b4a.toString(publicKey, 'hex')
    if (!this.peers.has(keyString)) return

    const peerInfo = this.peers.get(keyString)
    peerInfo.explicit = false
    this.explicitPeers.delete(peerInfo)
    this._maybeDeletePeer(peerInfo)
  }

  // Returns a promise
  async flush() {
    const allFlushed = [...this._discovery.values()].map((v) => v.flushed())
    await Promise.all(allFlushed)
    if (this._flushAllMaybe()) return true
    const pendingSize = this._allConnections.size - this.connections.size
    if (!this._queue.length && !pendingSize) return true
    return new Promise((resolve) => {
      this._pendingFlushes.push({
        onflush: resolve,
        missing: this._queue.length + pendingSize,
        tick: this._flushTick++
      })
    })
  }

  async clear() {
    const cleared = Promise.allSettled([...this._discovery.values()].map((d) => d.destroy()))
    this._discovery.clear()
    return cleared
  }

  async destroy({ force } = {}) {
    if (this.destroyed && !force) return
    this.destroyed = true

    this._timer.destroy()

    if (!force) await this.clear()

    await this.server.close()

    while (this._pendingFlushes.length) {
      const flush = this._pendingFlushes.pop()
      flush.onflush(false)
    }

    await this.dht.destroy({ force })
  }

  async suspend({ log = noop } = {}) {
    if (this.suspended) return

    const promises = []

    promises.push(this.server.suspend({ log }))

    for (const discovery of this._discovery.values()) {
      promises.push(discovery.suspend({ log }))
    }

    const pending = []
    for (const connection of this._allConnections) {
      connection.destroy()
      pending.push(new Promise((resolve) => connection.on('close', resolve)))
    }

    this.suspended = true

    log('Suspending server and discovery... (' + promises.length + ')')
    await Promise.allSettled(promises)
    log('Done, suspending the dht...')
    await this.dht.suspend({ log })
    log('Done, swarm fully suspended')

    await Promise.all(pending)

    // reset queue
    this._timer.destroy()
    this._timer = new RetryTimer(this._requeue.bind(this), {
      backoffs: this._timer.backoffs,
      jitter: this._timer.jitter
    })
    this._queue = spq()
  }

  async resume({ log = noop } = {}) {
    if (!this.suspended) return

    log('Resuming the dht')
    await this.dht.resume()
    log('Done, resuming the server')
    await this.server.resume()
    log('Done, all discovery')

    for (const discovery of this._discovery.values()) {
      discovery.resume()
    }

    this.suspended = false
    this._attemptClientConnections()
  }

  topics() {
    return this._discovery.values()
  }
}

function noop() {}

function allowAll() {
  return false
}

function shouldForceRelaying(code) {
  return (
    code === 'HOLEPUNCH_ABORTED' ||
    code === 'HOLEPUNCH_DOUBLE_RANDOMIZED_NATS' ||
    code === 'REMOTE_NOT_HOLEPUNCHABLE'
  )
}

function shouldBan() {
  // return !!err && err.name === 'HypercoreError' && err.code === 'INVALID_OPERATION'
  return false
}

function toRelayFunction(relayThrough) {
  return typeof relayThrough === 'function'
    ? relayThrough
    : (force, swarm) => (force || swarm.dht.randomized ? relayThrough : null)
}
module.exports = class BulkTimer {
  constructor(time, fn) {
    this._time = time
    this._fn = fn
    this._interval = null
    this._next = []
    this._pending = []
    this._destroyed = false
  }

  destroy() {
    if (this._destroyed) return
    this._destroyed = true
    clearInterval(this._interval)
    this._interval = null
  }

  _ontick() {
    if (!this._next.length && !this._pending.length) return
    if (this._next.length) this._fn(this._next)
    this._next = this._pending
    this._pending = []
  }

  add(info) {
    if (this._destroyed) return
    if (!this._interval) {
      this._interval = setInterval(this._ontick.bind(this), Math.floor(this._time * 0.66))
    }

    this._pending.push(info)
  }
}
const b4a = require('b4a')

module.exports = class ConnectionSet {
  constructor() {
    this._byPublicKey = new Map()
  }

  [Symbol.iterator]() {
    return this._byPublicKey.values()
  }

  get size() {
    return this._byPublicKey.size
  }

  has(publicKey) {
    return this._byPublicKey.has(toHex(publicKey))
  }

  get(publicKey) {
    return this._byPublicKey.get(toHex(publicKey))
  }

  add(connection) {
    this._byPublicKey.set(b4a.toString(connection.remotePublicKey, 'hex'), connection)
  }

  delete(connection) {
    const keyString = b4a.toString(connection.remotePublicKey, 'hex')
    const existing = this._byPublicKey.get(keyString)
    if (existing !== connection) return
    this._byPublicKey.delete(keyString)
  }
}

function toHex(b) {
  return typeof b === 'string' ? b : b4a.toString(b, 'hex')
}
const safetyCatch = require('safety-catch')
const b4a = require('b4a')

const REFRESH_INTERVAL = 1000 * 60 * 10 // 10 min
const RANDOM_JITTER = 1000 * 60 * 2 // 2 min
const DELAY_GRACE_PERIOD = 1000 * 30 // 30s

const MAX_DISCOVERY_CACHE = 64

module.exports = class PeerDiscovery {
  constructor(
    swarm,
    topic,
    { limit = Infinity, wait = null, suspended = false, onpeer = noop, onerror = safetyCatch }
  ) {
    this.limit = limit
    this.swarm = swarm
    this.topic = topic
    this.isClient = false
    this.isServer = false
    this.destroyed = false
    this.destroying = null
    this.suspended = suspended

    this._sessions = []
    this._clientSessions = 0
    this._serverSessions = 0

    this._onpeer = onpeer
    this._onerror = onerror

    this._discovered = new Set()
    this._activeQuery = null
    this._timer = null
    this._currentRefresh = null
    this._closestNodes = null
    this._firstAnnounce = true
    this._needsUnannounce = false
    this._refreshes = 0
    this._wait = wait
  }

  session({ server = true, client = true, limit = Infinity, onerror = safetyCatch }) {
    if (this.destroyed) throw new Error('PeerDiscovery is destroyed')
    const session = new PeerDiscoverySession(this)
    session.refresh({ server, client, limit }).catch(onerror)
    this._sessions.push(session)
    return session
  }

  _refreshLater(eager) {
    const jitter = Math.round(Math.random() * RANDOM_JITTER)
    const delay = !eager ? REFRESH_INTERVAL + jitter : jitter

    if (this._timer) clearTimeout(this._timer)

    const startTime = Date.now()
    this._timer = setTimeout(() => {
      // If your laptop went to sleep, and is coming back online...
      const overdue = Date.now() - startTime > delay + DELAY_GRACE_PERIOD
      if (overdue) this._refreshLater(true)
      else this.refresh().catch(this._onerror)
    }, delay)
  }

  _isActive() {
    return !this.destroyed && !this.suspended
  }

  // TODO: Allow announce to be an argument to this
  // TODO: Maybe announce should be a setter?
  async _refresh() {
    if (this.suspended) return
    const clock = ++this._refreshes

    if (this._wait) {
      await this._wait
      this._wait = null
      if (clock !== this._refreshes || !this._isActive()) return
    }

    const clear = this.isServer && this._firstAnnounce
    if (clear) this._firstAnnounce = false

    const opts = {
      clear,
      closestNodes: this._closestNodes
    }

    if (this.isServer) {
      await this.swarm.listen()
      // if a parallel refresh is happening, yield to the new one
      if (clock !== this._refreshes || !this._isActive()) return
      this._needsUnannounce = true
    }

    let limit = this.limit

    if (limit < Infinity && limit > 0) {
      for (const id of this._discovered) {
        if (!this.swarm.connections.has(id)) continue
        if (--limit === 0) break
      }
    }

    this._discovered.clear()

    const announcing = this.isServer
    const query = (this._activeQuery = announcing
      ? this.swarm.dht.announce(
          this.topic,
          this.swarm.keyPair,
          this.swarm.server.relayAddresses,
          opts
        )
      : this._needsUnannounce
        ? this.swarm.dht.lookupAndUnannounce(this.topic, this.swarm.keyPair, opts)
        : this.swarm.dht.lookup(this.topic, opts))

    try {
      for await (const data of this._activeQuery) {
        if (!this.isClient || !this._isActive()) continue
        for (const peer of data.peers) {
          if (limit < Infinity) {
            const id = b4a.toString(peer.publicKey, 'hex')

            if (this._discovered.size < MAX_DISCOVERY_CACHE) {
              this._discovered.add(id)
            }

            if (limit === 0) continue

            // there is a chance it has updated a connection during discovery and we go over
            // the limit - thats acceptable to avoid a complexity spiral here.
            if (!this.swarm.connections.has(id)) limit--
          }

          this._onpeer(peer, data)
        }
      }
    } catch (err) {
      if (this._isActive()) throw err
    } finally {
      if (this._activeQuery === query) {
        this._activeQuery = null
        if (!this.destroyed && !this.suspended) this._refreshLater(false)
      }
    }

    // This is set at the very end, when the query completes successfully.
    this._closestNodes = query.closestNodes

    if (clock !== this._refreshes) return

    // In this is the latest query, unannounce has been fulfilled as well
    if (!announcing) this._needsUnannounce = false
  }

  async refresh() {
    if (this.destroyed) throw new Error('PeerDiscovery is destroyed')

    const server = this._serverSessions > 0
    const client = this._clientSessions > 0

    if (this.suspended) return

    if (server === this.isServer && client === this.isClient) {
      if (this._currentRefresh) return this._currentRefresh
      this._currentRefresh = this._refresh()
    } else {
      if (this._activeQuery) this._activeQuery.destroy()
      this.isServer = server
      this.isClient = client
      this._currentRefresh = this._refresh()
    }

    const refresh = this._currentRefresh
    try {
      await refresh
    } catch {
      return false
    } finally {
      if (refresh === this._currentRefresh) {
        this._currentRefresh = null
      }
    }

    return true
  }

  async flushed() {
    if (this.swarm.listening) await this.swarm.listening

    try {
      await this._currentRefresh
      return true
    } catch {
      return false
    }
  }

  async _destroyMaybe() {
    if (this.destroyed) return

    try {
      if (this._sessions.length === 0) await this.swarm.leave(this.topic)
      else if (this._serverSessions === 0 && this._needsUnannounce) await this.refresh()
    } catch (err) {
      // ignore network failures here, as we are tearing down
      safetyCatch(err)
    }
  }

  destroy() {
    if (this.destroying) return this.destroying
    this.destroying = this._destroy()
    return this.destroying
  }

  async _abort(log) {
    const id = log === noop ? '' : b4a.toString(this.topic, 'hex')

    log('Aborting discovery', id)
    if (this._wait) await this._wait
    log('Aborting discovery (post wait)', id)

    if (this._activeQuery) {
      this._activeQuery.destroy()
      this._activeQuery = null
    }
    if (this._timer) {
      clearTimeout(this._timer)
      this._timer = null
    }

    let nodes = this._closestNodes

    if (this._currentRefresh) {
      try {
        await this._currentRefresh
      } catch {
        // If the destroy causes the refresh to fail, suppress it.
      }
    }

    log('Aborting discovery (post refresh)', id)
    if (this._isActive()) return

    if (!nodes) nodes = this._closestNodes
    else if (this._closestNodes !== nodes) {
      const len = nodes.length
      for (const newer of this._closestNodes) {
        if (newer.id && !hasNode(nodes, len, newer)) nodes.push(newer)
      }
    }

    if (this._needsUnannounce) {
      log('Unannouncing discovery', id)
      if (nodes && nodes.length) {
        await this.swarm.dht.unannounce(this.topic, this.swarm.keyPair, {
          closestNodes: nodes,
          onlyClosestNodes: true,
          force: true
        })
      }
      this._needsUnannounce = false
      log('Unannouncing discovery (done)', id)
    }
  }

  _destroy() {
    if (this.destroyed) return
    this.destroyed = true
    return this._abort(noop)
  }

  async suspend({ log = noop } = {}) {
    if (this.suspended) return
    this.suspended = true
    try {
      await this._abort(log)
    } catch {
      // ignore
    }
  }

  resume() {
    if (!this.suspended) return
    this.suspended = false
    this.refresh().catch(noop)
  }
}

class PeerDiscoverySession {
  constructor(discovery) {
    this.discovery = discovery
    this.isClient = false
    this.isServer = false
    this.destroyed = false
  }

  get swarm() {
    return this.discovery.swarm
  }

  get topic() {
    return this.discovery.topic
  }

  async refresh({ client = this.isClient, server = this.isServer, limit = Infinity } = {}) {
    if (this.destroyed) throw new Error('PeerDiscovery is destroyed')
    if (!client && !server) throw new Error('Cannot refresh with neither client nor server option')

    if (client !== this.isClient) {
      this.isClient = client
      this.discovery._clientSessions += client ? 1 : -1
    }

    if (server !== this.isServer) {
      this.isServer = server
      this.discovery._serverSessions += server ? 1 : -1
    }

    this.discovery.limit = limit

    return this.discovery.refresh()
  }

  async flushed() {
    return this.discovery.flushed()
  }

  async destroy() {
    if (this.destroyed) return
    this.destroyed = true

    if (this.isClient) this.discovery._clientSessions--
    if (this.isServer) this.discovery._serverSessions--

    const index = this.discovery._sessions.indexOf(this)
    const head = this.discovery._sessions.pop()

    if (head !== this) this.discovery._sessions[index] = head

    return this.discovery._destroyMaybe()
  }
}

function hasNode(nodes, len, node) {
  for (let i = 0; i < len; i++) {
    const existing = nodes[i]
    if (existing.id && b4a.equals(existing.id, node.id)) return true
  }

  return false
}

function noop() {}
const { EventEmitter } = require('events')
const b4a = require('b4a')
const unslab = require('unslab')

const MIN_CONNECTION_TIME = 15000

const VERY_LOW_PRIORITY = 0
const LOW_PRIORITY = 1
const NORMAL_PRIORITY = 2
const HIGH_PRIORITY = 3
const VERY_HIGH_PRIORITY = 4

module.exports = class PeerInfo extends EventEmitter {
  constructor({ publicKey, relayAddresses }) {
    super()

    this.publicKey = unslab(publicKey)
    this.relayAddresses = relayAddresses

    this.reconnecting = true
    this.proven = false
    this.connectedTime = -1
    this.disconnectedTime = 0
    this.banned = false
    this.tried = false
    this.explicit = false
    this.waiting = false
    this.forceRelaying = false

    // Set by the Swarm
    this.queued = false
    this.client = false
    this.topics = [] // TODO: remove on next major (check with mafintosh for context)

    this.attempts = 0
    this.priority = NORMAL_PRIORITY

    // Used by shuffled-priority-queue
    this._index = 0

    // Used for flush management
    this._flushTick = 0

    // Used for topic multiplexing
    this._seenTopics = new Set()
  }

  get server() {
    return !this.client
  }

  get prioritized() {
    return this.priority >= NORMAL_PRIORITY
  }

  _getPriority() {
    const peerIsStale = this.tried && !this.proven
    if (peerIsStale || this.attempts > 3) return VERY_LOW_PRIORITY
    if (this.attempts === 3) return LOW_PRIORITY
    if (this.attempts === 2) return HIGH_PRIORITY
    if (this.attempts === 1) return VERY_HIGH_PRIORITY
    return NORMAL_PRIORITY
  }

  _connected() {
    this.proven = true
    this.connectedTime = Date.now()
  }

  _disconnected() {
    this.disconnectedTime = Date.now()
    if (this.connectedTime > -1) {
      if (this.disconnectedTime - this.connectedTime >= MIN_CONNECTION_TIME) this.attempts = 0 // fast retry
      this.connectedTime = -1
    }
    this.attempts++
  }

  _deprioritize() {
    this.attempts = 3
  }

  _reset() {
    this.client = false
    this.proven = false
    this.tried = false
    this.attempts = 0
  }

  _updatePriority() {
    if (this.explicit && this.attempts > 3) this._deprioritize()
    if (this.banned || this.queued || this.attempts > 3) return false
    this.priority = this._getPriority()
    return true
  }

  _topic(topic) {
    const topicString = b4a.toString(topic, 'hex')
    if (this._seenTopics.has(topicString)) return
    this._seenTopics.add(topicString)
    this.topics.push(topic)
    this.emit('topic', topic)
  }

  reconnect(val) {
    this.reconnecting = !!val
  }

  ban(val) {
    this.banned = !!val
  }

  shouldGC() {
    return !(this.banned || this.queued || this.explicit || this.waiting)
  }
}
const BulkTimer = require('./bulk-timer')

const BACKOFF_JITTER = 500
const BACKOFF_S = 1000 + Math.round(BACKOFF_JITTER * Math.random())
const BACKOFF_M = 5000 + Math.round(2 * BACKOFF_JITTER * Math.random())
const BACKOFF_L = 15000 + Math.round(4 * BACKOFF_JITTER * Math.random())
const BACKOFF_X = 1000 * 60 * 10 + Math.round(240 * BACKOFF_JITTER * Math.random())

module.exports = class RetryTimer {
  constructor(
    push,
    { backoffs = [BACKOFF_S, BACKOFF_M, BACKOFF_L, BACKOFF_X], jitter = BACKOFF_JITTER } = {}
  ) {
    this.jitter = jitter
    this.backoffs = backoffs

    this._sTimer = new BulkTimer(backoffs[0] + Math.round(jitter * Math.random()), push)
    this._mTimer = new BulkTimer(backoffs[1] + Math.round(jitter * Math.random()), push)
    this._lTimer = new BulkTimer(backoffs[2] + Math.round(jitter * Math.random()), push)
    this._xTimer = new BulkTimer(backoffs[3] + Math.round(jitter * Math.random()), push)
  }

  _selectRetryTimer(peerInfo) {
    if (peerInfo.banned || !peerInfo.reconnecting) return null

    if (peerInfo.attempts > 3) {
      return peerInfo.explicit ? this._xTimer : null
    }

    if (peerInfo.attempts === 0) return this._sTimer
    if (peerInfo.proven) {
      switch (peerInfo.attempts) {
        case 1:
          return this._sTimer
        case 2:
          return this._mTimer
        case 3:
          return this._lTimer
      }
    } else {
      switch (peerInfo.attempts) {
        case 1:
          return this._mTimer
        case 2:
          return this._lTimer
        case 3:
          return this._lTimer
      }
    }

    return null
  }

  add(peerInfo) {
    const timer = this._selectRetryTimer(peerInfo)
    if (!timer) return false

    timer.add(peerInfo)
    return true
  }

  destroy() {
    this._sTimer.destroy()
    this._mTimer.destroy()
    this._lTimer.destroy()
    this._xTimer.destroy()
  }
}
{
  "name": "hyperswarm",
  "version": "4.17.0",
  "description": "A distributed networking stack for connecting peers",
  "files": [
    "index.js",
    "lib/**.js"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    },
    "process": {
      "bare": "bare-process",
      "default": "process"
    }
  },
  "dependencies": {
    "b4a": "^1.3.1",
    "bare-events": "^2.2.0",
    "hyperdht": "^6.21.0",
    "safety-catch": "^1.0.2",
    "shuffled-priority-queue": "^2.1.0",
    "streamx": "^2.22.1",
    "unslab": "^1.3.0"
  },
  "devDependencies": {
    "bare-process": "^4.2.2",
    "brittle": "^3.0.2",
    "hypercore-crypto": "^3.4.0",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "which-runtime": "^1.3.2"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:generate": "brittle -r test/all.js test/*.js",
    "test:node": "brittle-node --coverage test/*.js",
    "test:bare": "bare test/all.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/hyperswarm.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "contributors": [
    "David Mark Clements (@davidmarkclem)",
    "Andrew Osheroff (@andrewosh)"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/hyperswarm/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperswarm"
}
const { EventEmitter } = require('events')

module.exports = class RoutingTable extends EventEmitter {
  constructor (id, opts) {
    if (!opts) opts = {}

    super()

    this.id = id
    this.k = opts.k || 20
    this.size = 0
    this.rows = new Array(id.length * 8)
  }

  add (node) {
    const i = this._diff(node.id)

    let row = this.rows[i]

    if (!row) {
      row = this.rows[i] = new Row(this, i)
      this.emit('row', row)
    }

    const len = row.nodes.length
    if (!row.add(node, this.k)) return false

    this.size += row.nodes.length - len
    return true
  }

  remove (id) {
    const i = this._diff(id)
    const row = this.rows[i]
    if (!row) return false
    if (!row.remove(id)) return false
    this.size--
    return true
  }

  get (id) {
    const i = this._diff(id)
    const row = this.rows[i]
    if (!row) return null
    return row.get(id)
  }

  has (id) {
    return this.get(id) !== null
  }

  random () {
    let n = (Math.random() * this.size) | 0

    for (let i = 0; i < this.rows.length; i++) {
      const r = this.rows[i]
      if (!r) continue
      if (n < r.nodes.length) return r.nodes[n]
      n -= r.nodes.length
    }

    return null
  }

  closest (id, k) {
    if (!k) k = this.k

    const result = []
    const d = this._diff(id)

    // push close nodes
    for (let i = d; i >= 0 && result.length < k; i--) this._pushNodes(i, k, result)

    // if we don't have enough close nodes, populate from other rows, re the paper
    for (let i = d + 1; i < this.rows.length && result.length < k; i++) this._pushNodes(i, k, result)

    return result
  }

  _pushNodes (i, k, result) {
    const row = this.rows[i]
    if (!row) return

    const missing = Math.min(k - result.length, row.nodes.length)
    for (let j = 0; j < missing; j++) result.push(row.nodes[j])
  }

  toArray () {
    return this.closest(this.id, Infinity)
  }

  _diff (id) {
    for (let i = 0; i < id.length; i++) {
      const a = id[i]
      const b = this.id[i]

      if (a !== b) return i * 8 + Math.clz32(a ^ b) - 24
    }

    return this.rows.length - 1
  }
}

class Row extends EventEmitter {
  constructor (table, index) {
    super()

    this.data = null // can be used be upstream for whatevs
    this.byteOffset = index >> 3
    this.index = index
    this.table = table
    this.nodes = []
  }

  add (node) {
    const id = node.id

    let l = 0
    let r = this.nodes.length - 1

    while (l <= r) {
      const m = (l + r) >> 1
      const c = this.compare(id, this.nodes[m].id)

      if (c === 0) {
        this.nodes[m] = node
        return true
      }

      if (c < 0) r = m - 1
      else l = m + 1
    }

    if (this.nodes.length >= this.table.k) {
      this.emit('full', node)
      return false
    }

    this.insert(l, node)
    return true
  }

  remove (id) {
    let l = 0
    let r = this.nodes.length - 1

    while (l <= r) {
      const m = (l + r) >> 1
      const c = this.compare(id, this.nodes[m].id)

      if (c === 0) {
        this.splice(m)
        return true
      }

      if (c < 0) r = m - 1
      else l = m + 1
    }

    return false
  }

  get (id) {
    let l = 0
    let r = this.nodes.length - 1

    while (l <= r) {
      const m = (l + r) >> 1
      const node = this.nodes[m]
      const c = this.compare(id, node.id)

      if (c === 0) return node
      if (c < 0) r = m - 1
      else l = m + 1
    }

    return null
  }

  insert (i, node) {
    this.nodes.push(node) // push node or null or whatevs, just trying to not be polymorphic
    for (let j = this.nodes.length - 1; j > i; j--) this.nodes[j] = this.nodes[j - 1]
    this.nodes[i] = node
    this.emit('add', node)
  }

  splice (i) {
    for (; i < this.nodes.length - 1; i++) this.nodes[i] = this.nodes[i + 1]
    this.emit('remove', this.nodes.pop())
  }

  // very likely they diverge after a couple of bytes so a simple impl, like this is prop fastest vs Buffer.compare
  compare (a, b) {
    for (let i = this.byteOffset; i < a.length; i++) {
      const ai = a[i]
      const bi = b[i]
      if (ai === bi) continue
      return ai < bi ? -1 : 1
    }
    return 0
  }
}
{
  "name": "kademlia-routing-table",
  "version": "1.0.6",
  "description": "XOR based routing table used for P2P networks such as a Kademlia DHT.",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "dependencies": {
    "bare-events": "^2.2.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "standard": "^17.1.0"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "keywords": [
    "kademlia",
    "p2p",
    "k-bucket",
    "k-buckets",
    "xor",
    "routing",
    "distributed",
    "systems"
  ],
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/kademlia-routing-table.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/kademlia-routing-table/issues"
  },
  "homepage": "https://github.com/mafintosh/kademlia-routing-table"
}
module.exports = assert

class AssertionError extends Error {}
AssertionError.prototype.name = 'AssertionError'

/**
 * Minimal assert function
 * @param  {any} t Value to check if falsy
 * @param  {string=} m Optional assertion error message
 * @throws {AssertionError}
 */
function assert (t, m) {
  if (!t) {
    var err = new AssertionError(m)
    if (Error.captureStackTrace) Error.captureStackTrace(err, assert)
    throw err
  }
}
{
  "name": "nanoassert",
  "version": "2.0.0",
  "description": "Nanoscale assertion module",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "tape": "^4.9.1"
  },
  "scripts": {
    "test": "tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/emilbayes/nanoassert.git"
  },
  "keywords": [
    "assert",
    "unassert",
    "power-assert",
    "tiny",
    "nano",
    "pico"
  ],
  "author": "Emil Bay <github@tixz.dk>",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/emilbayes/nanoassert/issues"
  },
  "homepage": "https://github.com/emilbayes/nanoassert#readme"
}
module.exports = class NatSampler {
  constructor () {
    this.host = null
    this.port = 0
    this.size = 0

    this._a = null
    this._b = null
    this._threshold = 0
    this._top = 0
    this._samples = []
  }

  add (host, port) {
    const a = this._bump(host, port, 2)
    const b = this._bump(host, 0, 1)

    if (this._samples.length < 32) {
      this.size++
      this._threshold = this.size - (this.size < 4 ? 0 : this.size < 8 ? 1 : this.size < 12 ? 2 : 3)
      this._samples.push(a, b)
      this._top += 2
    } else {
      if (this._top === 32) this._top = 0

      const oa = this._samples[this._top]
      this._samples[this._top++] = a
      oa.hits--

      const ob = this._samples[this._top]
      this._samples[this._top++] = b
      ob.hits--
    }

    if (this._a === null || this._a.hits < a.hits) this._a = a
    if (this._b === null || this._b.hits < b.hits) this._b = b

    if (this._a.hits >= this._threshold) {
      this.host = this._a.host
      this.port = this._a.port
    } else if (this._b.hits >= this._threshold) {
      this.host = this._b.host
      this.port = 0
    } else {
      this.host = null
      this.port = 0
    }

    return a.hits
  }

  _bump (host, port, inc) {
    for (let i = 0; i < 4; i++) {
      const j = (this._top - inc - (2 * i)) & 31
      if (j >= this._samples.length) return { host, port, hits: 1 }
      const s = this._samples[j]
      if (s.port === port && s.host === host) {
        s.hits++
        return s
      }
    }
    return { host, port, hits: 1 }
  }
}
{
  "name": "nat-sampler",
  "version": "1.0.1",
  "description": "Sample addresses to figure out if a host + port is consistent",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^16.0.3",
    "tape": "^5.2.2"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/nat-sampler.git"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/nat-sampler/issues"
  },
  "homepage": "https://github.com/mafintosh/nat-sampler"
}
/* eslint-disable camelcase */
const sodium = require('sodium-universal')
const assert = require('nanoassert')
const b4a = require('b4a')

const DHLEN = sodium.crypto_scalarmult_ed25519_BYTES
const PKLEN = sodium.crypto_scalarmult_ed25519_BYTES
const SCALARLEN = sodium.crypto_scalarmult_ed25519_BYTES
const SKLEN = sodium.crypto_sign_SECRETKEYBYTES
const ALG = 'Ed25519'

module.exports = {
  DHLEN,
  PKLEN,
  SCALARLEN,
  SKLEN,
  ALG,
  name: ALG,
  generateKeyPair,
  dh
}

function generateKeyPair (privKey) {
  if (privKey) return generateSeedKeyPair(privKey.subarray(0, 32))

  const keyPair = {}
  keyPair.secretKey = b4a.alloc(SKLEN)
  keyPair.publicKey = b4a.alloc(PKLEN)

  sodium.crypto_sign_keypair(keyPair.publicKey, keyPair.secretKey)
  return keyPair
}

function generateSeedKeyPair (seed) {
  const keyPair = {}
  keyPair.secretKey = b4a.alloc(SKLEN)
  keyPair.publicKey = b4a.alloc(PKLEN)

  sodium.crypto_sign_seed_keypair(keyPair.publicKey, keyPair.secretKey, seed)
  return keyPair
}

function dh (publicKey, { scalar, secretKey }) {
  // tweaked keys expose scalar directly
  if (!scalar) {
    assert(secretKey.byteLength === SKLEN)

    // libsodium stores seed not actual scalar
    const sk = b4a.alloc(64)
    sodium.crypto_hash_sha512(sk, secretKey.subarray(0, 32))
    sk[0] &= 248
    sk[31] &= 127
    sk[31] |= 64

    scalar = sk.subarray(0, 32)
  }

  assert(scalar.byteLength === SCALARLEN)
  assert(publicKey.byteLength === PKLEN)

  const output = b4a.alloc(DHLEN)

  // we clamp if necessary above
  sodium.crypto_scalarmult_ed25519_noclamp(
    output,
    scalar,
    publicKey
  )

  return output
}
{
  "name": "noise-curve-ed",
  "version": "2.1.0",
  "description": "Ed25519 elliptic curve operations for [`noise-handshake`](https://github.com/chm-diederichs/noise-handshake)",
  "main": "index.js",
  "scripts": {
    "test": "npx standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/chm-diederichs/noise-curve-ed.git"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/chm-diederichs/noise-curve-ed/issues"
  },
  "homepage": "https://github.com/chm-diederichs/noise-curve-ed#readme",
  "dependencies": {
    "b4a": "^1.1.0",
    "nanoassert": "^2.0.0",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "noise-handshake": "^3.0.0",
    "standard": "^16.0.3",
    "tape": "^5.2.2"
  }
}
const sodium = require('sodium-universal')
const b4a = require('b4a')

module.exports = class CipherState {
  constructor (key) {
    this.key = key || null
    this.nonce = 0
    this.CIPHER_ALG = 'ChaChaPoly'
  }

  initialiseKey (key) {
    this.key = key
    this.nonce = 0
  }

  setNonce (nonce) {
    this.nonce = nonce
  }

  encrypt (plaintext, ad) {
    if (!this.hasKey) return plaintext
    if (!ad) ad = b4a.alloc(0)

    const ciphertext = encryptWithAD(this.key, this.nonce, ad, plaintext)
    if (ciphertext.length > 65535) throw new Error(`ciphertext length of ${ciphertext.length} exceeds maximum Noise message length of 65535`)
    this.nonce++

    return ciphertext
  }

  decrypt (ciphertext, ad) {
    if (!this.hasKey) return ciphertext
    if (!ad) ad = b4a.alloc(0)
    if (ciphertext.length > 65535) throw new Error(`ciphertext length of ${ciphertext.length} exceeds maximum Noise message length of 65535`)

    const plaintext = decryptWithAD(this.key, this.nonce, ad, ciphertext)
    this.nonce++

    return plaintext
  }

  get hasKey () {
    return this.key !== null
  }

  _clear () {
    sodium.sodium_memzero(this.key)
    this.key = null
    this.nonce = null
  }

  static get MACBYTES () {
    return 16
  }

  static get NONCEBYTES () {
    return 8
  }

  static get KEYBYTES () {
    return 32
  }
}

function encryptWithAD (key, counter, additionalData, plaintext) {
  // for our purposes, additionalData will always be a pubkey so we encode from hex
  if (!b4a.isBuffer(additionalData)) additionalData = b4a.from(additionalData, 'hex')
  if (!b4a.isBuffer(plaintext)) plaintext = b4a.from(plaintext, 'hex')

  const nonce = b4a.alloc(sodium.crypto_aead_chacha20poly1305_ietf_NPUBBYTES)
  const view = new DataView(nonce.buffer, nonce.byteOffset, nonce.byteLength)
  view.setUint32(4, counter, true)

  const ciphertext = b4a.alloc(plaintext.byteLength + sodium.crypto_aead_chacha20poly1305_ietf_ABYTES)

  sodium.crypto_aead_chacha20poly1305_ietf_encrypt(ciphertext, plaintext, additionalData, null, nonce, key)
  return ciphertext
}

function decryptWithAD (key, counter, additionalData, ciphertext) {
  // for our purposes, additionalData will always be a pubkey so we encode from hex
  if (!b4a.isBuffer(additionalData)) additionalData = b4a.from(additionalData, 'hex')
  if (!b4a.isBuffer(ciphertext)) ciphertext = b4a.from(ciphertext, 'hex')

  const nonce = b4a.alloc(sodium.crypto_aead_chacha20poly1305_ietf_NPUBBYTES)
  const view = new DataView(nonce.buffer, nonce.byteOffset, nonce.byteLength)
  view.setUint32(4, counter, true)

  const plaintext = b4a.alloc(ciphertext.byteLength - sodium.crypto_aead_chacha20poly1305_ietf_ABYTES)

  sodium.crypto_aead_chacha20poly1305_ietf_decrypt(plaintext, null, ciphertext, additionalData, nonce, key)
  return plaintext
}
/* eslint-disable camelcase */
const {
  crypto_kx_SEEDBYTES,
  crypto_kx_keypair,
  crypto_kx_seed_keypair,
  crypto_scalarmult_BYTES,
  crypto_scalarmult_SCALARBYTES,
  crypto_scalarmult,
  crypto_scalarmult_base
} = require('sodium-universal')

const assert = require('nanoassert')
const b4a = require('b4a')

const DHLEN = crypto_scalarmult_BYTES
const PKLEN = crypto_scalarmult_BYTES
const SKLEN = crypto_scalarmult_SCALARBYTES
const SEEDLEN = crypto_kx_SEEDBYTES
const ALG = '25519'

module.exports = {
  DHLEN,
  PKLEN,
  SKLEN,
  SEEDLEN,
  ALG,
  generateKeyPair,
  generateSeedKeyPair,
  dh
}

function generateKeyPair (privKey) {
  const keyPair = {}

  keyPair.secretKey = privKey || b4a.alloc(SKLEN)
  keyPair.publicKey = b4a.alloc(PKLEN)

  if (privKey) {
    crypto_scalarmult_base(keyPair.publicKey, keyPair.secretKey)
  } else {
    crypto_kx_keypair(keyPair.publicKey, keyPair.secretKey)
  }

  return keyPair
}

function generateSeedKeyPair (seed) {
  assert(seed.byteLength === SKLEN)

  const keyPair = {}
  keyPair.secretKey = b4a.alloc(SKLEN)
  keyPair.publicKey = b4a.alloc(PKLEN)

  crypto_kx_seed_keypair(keyPair.publicKey, keyPair.secretKey, seed)
  return keyPair
}

function dh (publicKey, { secretKey }) {
  assert(secretKey.byteLength === SKLEN)
  assert(publicKey.byteLength === PKLEN)

  const output = b4a.alloc(DHLEN)

  crypto_scalarmult(
    output,
    secretKey,
    publicKey
  )

  return output
}
const hmacBlake2b = require('./hmac')
const b4a = require('b4a')

const HASHLEN = 64

module.exports = {
  hkdf,
  HASHLEN
}

// HMAC-based Extract-and-Expand KDF
// https://www.ietf.org/rfc/rfc5869.txt

function hkdf (salt, inputKeyMaterial, info = '', length = 2 * HASHLEN) {
  const pseudoRandomKey = hkdfExtract(salt, inputKeyMaterial)
  return hkdfExpand(pseudoRandomKey, info, length)
}

function hkdfExtract (salt, inputKeyMaterial) {
  const hmac = b4a.alloc(HASHLEN)
  return hmacDigest(hmac, salt, inputKeyMaterial)
}

function hkdfExpand (key, info, length) {
  // Put in dedicated slab to avoid keeping shared slab from being gc'ed
  const buffer = b4a.allocUnsafeSlow(length)

  const infoBuf = b4a.from(info)
  let prev = infoBuf

  const result = []
  for (let i = 0; i < length; i += HASHLEN) {
    const pos = b4a.from([(i / HASHLEN) + 1])

    const out = buffer.subarray(i, i + HASHLEN)
    result.push(out)

    prev = hmacDigest(out, key, [prev, infoBuf, pos])
  }

  return result
}

function hmacDigest (out, key, input) {
  hmacBlake2b(out, input, key)
  return out
}
/* eslint-disable camelcase */
const b4a = require('b4a')
const { sodium_memzero, crypto_generichash, crypto_generichash_batch } = require('sodium-universal')

const HASHLEN = 64
const BLOCKLEN = 128
const scratch = b4a.alloc(BLOCKLEN * 3)
const HMACKey = scratch.subarray(BLOCKLEN * 0, BLOCKLEN * 1)
const OuterKeyPad = scratch.subarray(BLOCKLEN * 1, BLOCKLEN * 2)
const InnerKeyPad = scratch.subarray(BLOCKLEN * 2, BLOCKLEN * 3)

// Post-fill is done in the cases where someone caught an exception that
// happened before we were able to clear data at the end

module.exports = function hmac (out, batch, key) {
  if (key.byteLength > BLOCKLEN) {
    crypto_generichash(HMACKey.subarray(0, HASHLEN), key)
    sodium_memzero(HMACKey.subarray(HASHLEN))
  } else {
    // Covers key <= BLOCKLEN
    HMACKey.set(key)
    sodium_memzero(HMACKey.subarray(key.byteLength))
  }

  for (let i = 0; i < HMACKey.byteLength; i++) {
    OuterKeyPad[i] = 0x5c ^ HMACKey[i]
    InnerKeyPad[i] = 0x36 ^ HMACKey[i]
  }
  sodium_memzero(HMACKey)

  crypto_generichash_batch(out, [InnerKeyPad].concat(batch))
  sodium_memzero(InnerKeyPad)
  crypto_generichash_batch(out, [OuterKeyPad, out])
  sodium_memzero(OuterKeyPad)
}

module.exports.BYTES = HASHLEN
module.exports.KEYBYTES = BLOCKLEN
const assert = require('nanoassert')
const b4a = require('b4a')

const SymmetricState = require('./symmetric-state')
const { HASHLEN } = require('./hkdf')

const PRESHARE_IS = Symbol('initiator static key preshared')
const PRESHARE_RS = Symbol('responder static key preshared')

const TOK_PSK = Symbol('psk')

const TOK_S = Symbol('s')
const TOK_E = Symbol('e')

const TOK_ES = Symbol('es')
const TOK_SE = Symbol('se')
const TOK_EE = Symbol('ee')
const TOK_SS = Symbol('ss')

const HANDSHAKES = Object.freeze({
  NN: [
    [TOK_E],
    [TOK_E, TOK_EE]
  ],
  NNpsk0: [
    [TOK_PSK, TOK_E],
    [TOK_E, TOK_EE]
  ],
  XX: [
    [TOK_E],
    [TOK_E, TOK_EE, TOK_S, TOK_ES],
    [TOK_S, TOK_SE]
  ],
  XXpsk0: [
    [TOK_PSK, TOK_E],
    [TOK_E, TOK_EE, TOK_S, TOK_ES],
    [TOK_S, TOK_SE]
  ],
  IK: [
    PRESHARE_RS,
    [TOK_E, TOK_ES, TOK_S, TOK_SS],
    [TOK_E, TOK_EE, TOK_SE]
  ],
  XK: [
    PRESHARE_RS,
    [TOK_E, TOK_ES],
    [TOK_E, TOK_EE],
    [TOK_S, TOK_SE]
  ]
})

class Writer {
  constructor () {
    this.size = 0
    this.buffers = []
  }

  push (b) {
    this.size += b.byteLength
    this.buffers.push(b)
  }

  end () {
    const all = b4a.alloc(this.size)
    let offset = 0
    for (const b of this.buffers) {
      all.set(b, offset)
      offset += b.byteLength
    }
    return all
  }
}

class Reader {
  constructor (buf) {
    this.offset = 0
    this.buffer = buf
  }

  shift (n) {
    const start = this.offset
    const end = this.offset += n
    if (end > this.buffer.byteLength) throw new Error('Insufficient bytes')
    return this.buffer.subarray(start, end)
  }

  end () {
    return this.shift(this.buffer.byteLength - this.offset)
  }
}

module.exports = class NoiseState extends SymmetricState {
  constructor (pattern, initiator, staticKeypair, opts = {}) {
    super(opts)

    this.s = staticKeypair || this.curve.generateKeyPair()
    this.e = null

    this.psk = null
    if (opts && opts.psk) this.psk = opts.psk

    this.re = null
    this.rs = null

    this.pattern = pattern
    this.handshake = HANDSHAKES[this.pattern].slice()

    this.isPskHandshake = !!this.psk && hasPskToken(this.handshake)

    this.protocol = b4a.from([
      'Noise',
      this.pattern,
      this.DH_ALG,
      this.CIPHER_ALG,
      'BLAKE2b'
    ].join('_'))

    this.initiator = initiator
    this.complete = false

    this.rx = null
    this.tx = null
    this.hash = null
  }

  initialise (prologue, remoteStatic) {
    if (this.protocol.byteLength <= HASHLEN) this.digest.set(this.protocol)
    else this.mixHash(this.protocol)

    this.chainingKey = b4a.from(this.digest)

    this.mixHash(prologue)

    while (!Array.isArray(this.handshake[0])) {
      const message = this.handshake.shift()

      // handshake steps should be as arrays, only
      // preshare tokens are provided otherwise
      assert(message === PRESHARE_RS || message === PRESHARE_IS,
        'Unexpected pattern')

      const takeRemoteKey = this.initiator
        ? message === PRESHARE_RS
        : message === PRESHARE_IS

      if (takeRemoteKey) this.rs = remoteStatic

      const key = takeRemoteKey ? this.rs : this.s.publicKey
      assert(key != null, 'Remote pubkey required')

      this.mixHash(key)
    }
  }

  final () {
    const [k1, k2] = this.split()

    this.tx = this.initiator ? k1 : k2
    this.rx = this.initiator ? k2 : k1

    this.complete = true
    this.hash = this.getHandshakeHash()

    this._clear()
  }

  recv (buf) {
    const r = new Reader(buf)

    for (const pattern of this.handshake.shift()) {
      switch (pattern) {
        case TOK_PSK :
          this.mixKeyAndHash(this.psk)
          break

        case TOK_E :
          this.re = r.shift(this.curve.PKLEN)
          this.mixHash(this.re)
          if (this.isPskHandshake) this.mixKeyNormal(this.re)
          break

        case TOK_S : {
          const klen = this.hasKey ? this.curve.PKLEN + 16 : this.curve.PKLEN
          this.rs = this.decryptAndHash(r.shift(klen))
          break
        }

        case TOK_EE :
        case TOK_ES :
        case TOK_SE :
        case TOK_SS : {
          const useStatic = keyPattern(pattern, this.initiator)

          const localKey = useStatic.local ? this.s : this.e
          const remoteKey = useStatic.remote ? this.rs : this.re

          this.mixKey(remoteKey, localKey)
          break
        }

        default :
          throw new Error('Unexpected message')
      }
    }

    const payload = this.decryptAndHash(r.end())

    if (!this.handshake.length) this.final()
    return payload
  }

  send (payload = b4a.alloc(0)) {
    const w = new Writer()

    for (const pattern of this.handshake.shift()) {
      switch (pattern) {
        case TOK_PSK :
          this.mixKeyAndHash(this.psk)
          break

        case TOK_E :
          if (this.e === null) this.e = this.curve.generateKeyPair()
          this.mixHash(this.e.publicKey)
          if (this.isPskHandshake) this.mixKeyNormal(this.e.publicKey)
          w.push(this.e.publicKey)
          break

        case TOK_S :
          w.push(this.encryptAndHash(this.s.publicKey))
          break

        case TOK_ES :
        case TOK_SE :
        case TOK_EE :
        case TOK_SS : {
          const useStatic = keyPattern(pattern, this.initiator)

          const localKey = useStatic.local ? this.s : this.e
          const remoteKey = useStatic.remote ? this.rs : this.re

          this.mixKey(remoteKey, localKey)
          break
        }

        default :
          throw new Error('Unexpected message')
      }
    }

    w.push(this.encryptAndHash(payload))
    const response = w.end()

    if (!this.handshake.length) this.final()
    return response
  }

  _clear () {
    super._clear()

    this.e.secretKey.fill(0)
    this.e.publicKey.fill(0)

    this.re.fill(0)

    this.e = null
    this.re = null
  }
}

function keyPattern (pattern, initiator) {
  const ret = {
    local: false,
    remote: false
  }

  switch (pattern) {
    case TOK_EE:
      return ret

    case TOK_ES:
      ret.local ^= !initiator
      ret.remote ^= initiator
      return ret

    case TOK_SE:
      ret.local ^= initiator
      ret.remote ^= !initiator
      return ret

    case TOK_SS:
      ret.local ^= 1
      ret.remote ^= 1
      return ret
  }
}

function hasPskToken (handshake) {
  return handshake.some(x => {
    return Array.isArray(x) && x.indexOf(TOK_PSK) !== -1
  })
}
{
  "name": "noise-handshake",
  "version": "4.2.0",
  "description": "Noise protocol handshake",
  "main": "noise.js",
  "files": [
    "*.js"
  ],
  "scripts": {
    "test": "standard && brittle test/*.js"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/noise-handshake.git"
  },
  "dependencies": {
    "b4a": "^1.1.0",
    "nanoassert": "^2.0.0",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "noise-protocol": "chm-diederichs/noise-protocol.git#xx-ephemeral-key",
    "standard": "^16.0.3"
  }
}
const sodium = require('sodium-universal')
const assert = require('nanoassert')
const b4a = require('b4a')
const CipherState = require('./cipher')
const curve = require('./dh')
const { HASHLEN, hkdf } = require('./hkdf')

module.exports = class SymmetricState extends CipherState {
  constructor (opts = {}) {
    super()

    this.curve = opts.curve || curve
    this.digest = b4a.alloc(HASHLEN)
    this.chainingKey = null
    this.offset = 0

    this.DH_ALG = this.curve.ALG
  }

  mixHash (data) {
    accumulateDigest(this.digest, data)
  }

  mixKeyAndHash (key) {
    const [ck, tempH, tempK] = hkdf(this.chainingKey, key, '', 3 * HASHLEN)
    this.chainingKey = ck
    this.mixHash(tempH)
    this.initialiseKey(tempK.subarray(0, 32))
  }

  mixKeyNormal (key) {
    const [ck, tempK] = hkdf(this.chainingKey, key)
    this.chainingKey = ck
    this.initialiseKey(tempK.subarray(0, 32))
  }

  mixKey (remoteKey, localKey) {
    const dh = this.curve.dh(remoteKey, localKey)
    const hkdfResult = hkdf(this.chainingKey, dh)
    this.chainingKey = hkdfResult[0]
    this.initialiseKey(hkdfResult[1].subarray(0, 32))
  }

  encryptAndHash (plaintext) {
    const ciphertext = this.encrypt(plaintext, this.digest)
    accumulateDigest(this.digest, ciphertext)
    return ciphertext
  }

  decryptAndHash (ciphertext) {
    const plaintext = this.decrypt(ciphertext, this.digest)
    accumulateDigest(this.digest, ciphertext)
    return plaintext
  }

  getHandshakeHash (out) {
    if (!out) return this.getHandshakeHash(b4a.alloc(HASHLEN))
    assert(out.byteLength === HASHLEN, `output must be ${HASHLEN} bytes`)

    out.set(this.digest)
    return out
  }

  split () {
    const res = hkdf(this.chainingKey, b4a.alloc(0))
    return res.map(k => k.subarray(0, 32))
  }

  _clear () {
    super._clear()

    sodium.sodium_memzero(this.digest)
    sodium.sodium_memzero(this.chainingKey)

    this.digest = null
    this.chainingKey = null
    this.offset = null

    this.curve = null
  }

  static get alg () {
    return CipherState.alg + '_BLAKE2b'
  }
}

function accumulateDigest (digest, input) {
  const toHash = b4a.concat([digest, input])
  sodium.crypto_generichash(digest, toHash)
}
const b4a = require('b4a')
const c = require('compact-encoding')
const queueTick = require('queue-tick')
const safetyCatch = require('safety-catch')
const unslab = require('unslab')

const MAX_BUFFERED = 32768
const MAX_BACKLOG = Infinity // TODO: impl "open" backpressure
const MAX_BATCH = 8 * 1024 * 1024

class Channel {
  constructor(
    mux,
    info,
    userData,
    protocol,
    aliases,
    id,
    handshake,
    messages,
    onopen,
    onclose,
    ondestroy,
    ondrain
  ) {
    this.userData = userData
    this.protocol = protocol
    this.aliases = aliases
    this.id = id
    this.handshake = null
    this.messages = []

    this.opened = false
    this.closed = false
    this.destroyed = false

    this.onopen = onopen
    this.onclose = onclose
    this.ondestroy = ondestroy
    this.ondrain = ondrain

    this._handshake = handshake
    this._mux = mux
    this._info = info
    this._localId = 0
    this._remoteId = 0
    this._active = 0
    this._extensions = null

    this._decBound = this._dec.bind(this)
    this._decAndDestroyBound = this._decAndDestroy.bind(this)

    this._openedPromise = null
    this._openedResolve = null

    this._destroyedPromise = null
    this._destroyedResolve = null

    for (const m of messages) this.addMessage(m)
  }

  get drained() {
    return this._mux.drained
  }

  fullyOpened() {
    if (this.opened) return Promise.resolve(true)
    if (this.closed) return Promise.resolve(false)
    if (this._openedPromise) return this._openedPromise

    this._openedPromise = new Promise((resolve) => {
      this._openedResolve = resolve
    })
    return this._openedPromise
  }

  fullyClosed() {
    if (this.destroyed) return Promise.resolve()
    if (this._destroyedPromise) return this._destroyedPromise

    this._destroyedPromise = new Promise((resolve) => {
      this._destroyedResolve = resolve
    })
    return this._destroyedPromise
  }

  open(handshake) {
    const id = this._mux._free.length > 0 ? this._mux._free.pop() : this._mux._local.push(null) - 1

    this._info.opened++
    this._info.lastChannel = this
    this._localId = id + 1
    this._mux._local[id] = this

    if (this._remoteId === 0) {
      this._info.outgoing.push(this._localId)
    }

    const state = { buffer: null, start: 2, end: 2 }

    c.uint.preencode(state, this._localId)
    c.string.preencode(state, this.protocol)
    c.optionalBuffer.preencode(state, this.id)
    if (this._handshake) this._handshake.preencode(state, handshake)

    state.buffer = this._mux._alloc(state.end)

    state.buffer[0] = 0
    state.buffer[1] = 1
    c.uint.encode(state, this._localId)
    c.string.encode(state, this.protocol)
    c.optionalBuffer.encode(state, this.id)
    if (this._handshake) this._handshake.encode(state, handshake)

    this._mux._write0(state.buffer)
  }

  _dec() {
    if (--this._active === 0 && this.closed === true) this._destroy()
  }

  _decAndDestroy(err) {
    this._dec()
    this._mux._safeDestroy(err)
  }

  _fullyOpenSoon() {
    this._mux._remote[this._remoteId - 1].session = this
    queueTick(this._fullyOpenOrDestroy.bind(this))
  }

  _fullyOpenOrDestroy() {
    try {
      this._fullyOpen()
    } catch (err) {
      this._mux._safeDestroyBound(err)
    }
  }

  _fullyOpen() {
    if (this.opened === true || this.closed === true) return

    const remote = this._mux._remote[this._remoteId - 1]

    this.handshake = this._handshake ? this._handshake.decode(remote.state) : null
    this._track(this.onopen(this.handshake, this))

    remote.session = this
    remote.state = null
    if (remote.pending !== null) this._drain(remote)
    if (this._mux._destroying === true) return

    this.opened = true
    this._resolveOpen(true)
  }

  _resolveOpen(opened) {
    if (this._openedResolve !== null) {
      this._openedResolve(opened)
      this._openedResolve = this._openedPromise = null
    }
  }

  _resolveDestroyed() {
    if (this._destroyedResolve !== null) {
      this._destroyedResolve()
      this._destroyedResolve = this._destroyedPromise = null
    }
  }

  _drain(remote) {
    for (let i = 0; i < remote.pending.length; i++) {
      const p = remote.pending[i]
      this._mux._buffered -= byteSize(p.state)
      this._recv(p.type, p.state)
      if (this._mux._destroying === true) return
    }

    remote.pending = null
    this._mux._resumeMaybe()
  }

  _track(p) {
    if (isPromise(p) === true) {
      this._active++
      return p.then(this._decBound, this._decAndDestroyBound)
    }

    return null
  }

  _close(isRemote) {
    if (this.closed === true) return
    this.closed = true

    this._info.opened--
    if (this._info.lastChannel === this) this._info.lastChannel = null

    if (this._remoteId > 0) {
      this._mux._remote[this._remoteId - 1] = null
      this._remoteId = 0
      // If remote has acked, we can reuse the local id now
      // otherwise, we need to wait for the "ack" to arrive
      this._mux._free.push(this._localId - 1)
    }

    this._mux._local[this._localId - 1] = null
    this._localId = 0

    this._mux._gc(this._info)
    this._track(this.onclose(isRemote, this))

    if (this._active === 0) this._destroy()

    this._resolveOpen(false)
  }

  _destroy() {
    if (this.destroyed === true) return
    this.destroyed = true
    this._track(this.ondestroy(this))
    this._resolveDestroyed()
  }

  _recv(type, state) {
    if (type < this.messages.length) {
      const m = this.messages[type]
      const p = m.recv(state, this)
      if (m.autoBatch === true) return p
    }
    return null
  }

  cork() {
    this._mux.cork()
  }

  uncork() {
    this._mux.uncork()
  }

  close() {
    if (this.closed === true) return

    const state = { buffer: null, start: 2, end: 2 }

    c.uint.preencode(state, this._localId)

    state.buffer = this._mux._alloc(state.end)

    state.buffer[0] = 0
    state.buffer[1] = 3
    c.uint.encode(state, this._localId)

    this._close(false)
    this._mux._write0(state.buffer)
  }

  addMessage(opts) {
    if (!opts) return this._skipMessage()

    const type = this.messages.length
    const autoBatch = opts.autoBatch !== false
    const encoding = opts.encoding || c.raw
    const onmessage = opts.onmessage || noop

    const s = this
    const typeLen = encodingLength(c.uint, type)

    const m = {
      type,
      autoBatch,
      encoding,
      onmessage,
      recv(state, session) {
        return session._track(m.onmessage(encoding.decode(state), session))
      },
      send(m, session = s) {
        if (session.closed === true) return false

        const mux = session._mux
        const state = { buffer: null, start: 0, end: typeLen }

        if (mux._batch !== null) {
          encoding.preencode(state, m)
          state.buffer = mux._alloc(state.end)

          c.uint.encode(state, type)
          encoding.encode(state, m)

          mux._pushBatch(session._localId, state.buffer)
          return true
        }

        c.uint.preencode(state, session._localId)
        encoding.preencode(state, m)

        state.buffer = mux._alloc(state.end)

        c.uint.encode(state, session._localId)
        c.uint.encode(state, type)
        encoding.encode(state, m)

        mux.drained = mux.stream.write(state.buffer)

        return mux.drained
      }
    }

    this.messages.push(m)

    return m
  }

  _skipMessage() {
    const type = this.messages.length
    const m = {
      type,
      encoding: c.raw,
      onmessage: noop,
      recv(state, session) {},
      send(m, session) {}
    }

    this.messages.push(m)
    return m
  }
}

module.exports = class Protomux {
  constructor(stream, { alloc } = {}) {
    if (stream.userData === null) stream.userData = this

    this.isProtomux = true
    this.stream = stream
    this.corked = 0
    this.drained = true

    this._alloc =
      alloc || (typeof stream.alloc === 'function' ? stream.alloc.bind(stream) : b4a.allocUnsafe)
    this._safeDestroyBound = this._safeDestroy.bind(this)
    this._uncorkBound = this.uncork.bind(this)

    this._remoteBacklog = 0
    this._buffered = 0
    this._paused = false
    this._remote = []
    this._local = []
    this._free = []
    this._batch = null
    this._batchState = null

    this._infos = new Map()
    this._notify = new Map()
    // stream.destroyed flips asynchronously on streamx-based transports.
    this._destroying = false

    this.stream.on('data', this._ondata.bind(this))
    this.stream.on('drain', this._ondrain.bind(this))
    this.stream.on('end', this._onend.bind(this))
    this.stream.on('error', noop) // we handle this in "close"
    this.stream.on('close', this._shutdown.bind(this))
  }

  static from(stream, opts) {
    if (stream.userData && stream.userData.isProtomux) return stream.userData
    if (stream.isProtomux) return stream
    return new this(stream, opts)
  }

  static isProtomux(mux) {
    return typeof mux === 'object' && mux.isProtomux === true
  }

  *[Symbol.iterator]() {
    for (const session of this._local) {
      if (session !== null) yield session
    }
  }

  isIdle() {
    return this._local.length === this._free.length
  }

  cork() {
    if (++this.corked === 1) {
      this._batch = []
      this._batchState = { buffer: null, start: 0, end: 1 }
    }
  }

  uncork() {
    if (--this.corked === 0) {
      this._sendBatch(this._batch, this._batchState)
      this._batch = null
      this._batchState = null
    }
  }

  getLastChannel({ protocol, id = null }) {
    const key = toKey(protocol, id)
    const info = this._infos.get(key)
    if (info) return info.lastChannel
    return null
  }

  pair({ protocol, id = null }, notify) {
    this._notify.set(toKey(protocol, id), notify)
  }

  unpair({ protocol, id = null }) {
    this._notify.delete(toKey(protocol, id))
  }

  opened({ protocol, id = null }) {
    const key = toKey(protocol, id)
    const info = this._infos.get(key)
    return info ? info.opened > 0 : false
  }

  createChannel({
    userData = null,
    protocol,
    aliases = [],
    id = null,
    unique = true,
    handshake = null,
    messages = [],
    onopen = noop,
    onclose = noop,
    ondestroy = noop,
    ondrain = noop
  }) {
    if (this.stream.destroyed) return null

    const info = this._get(protocol, id, aliases)
    if (unique && info.opened > 0) return null

    if (info.incoming.length === 0) {
      return new Channel(
        this,
        info,
        userData,
        protocol,
        aliases,
        id,
        handshake,
        messages,
        onopen,
        onclose,
        ondestroy,
        ondrain
      )
    }

    this._remoteBacklog--

    const remoteId = info.incoming.shift()
    const r = this._remote[remoteId - 1]
    if (r === null) return null

    const session = new Channel(
      this,
      info,
      userData,
      protocol,
      aliases,
      id,
      handshake,
      messages,
      onopen,
      onclose,
      ondestroy,
      ondrain
    )

    session._remoteId = remoteId
    session._fullyOpenSoon()

    return session
  }

  _pushBatch(localId, buffer) {
    if (this._batchState.end >= MAX_BATCH) {
      this._sendBatch(this._batch, this._batchState)
      this._batch = []
      this._batchState = { buffer: null, start: 0, end: 1 }
    }

    if (this._batch.length === 0 || this._batch[this._batch.length - 1].localId !== localId) {
      this._batchState.end++
      c.uint.preencode(this._batchState, localId)
    }
    c.buffer.preencode(this._batchState, buffer)
    this._batch.push({ localId, buffer })
  }

  _sendBatch(batch, state) {
    if (batch.length === 0) return

    let prev = batch[0].localId

    state.buffer = this._alloc(state.end)
    state.buffer[state.start++] = 0
    state.buffer[state.start++] = 0

    c.uint.encode(state, prev)

    for (let i = 0; i < batch.length; i++) {
      const b = batch[i]
      if (prev !== b.localId) {
        state.buffer[state.start++] = 0
        c.uint.encode(state, (prev = b.localId))
      }
      c.buffer.encode(state, b.buffer)
    }

    this.drained = this.stream.write(state.buffer)
  }

  _get(protocol, id, aliases = []) {
    const key = toKey(protocol, id)

    let info = this._infos.get(key)
    if (info) return info

    info = {
      key,
      protocol,
      aliases: [],
      id,
      pairing: 0,
      opened: 0,
      incoming: [],
      outgoing: [],
      lastChannel: null
    }
    this._infos.set(key, info)

    for (const alias of aliases) {
      const key = toKey(alias, id)
      info.aliases.push(key)

      this._infos.set(key, info)
    }

    return info
  }

  _gc(info) {
    if (info.opened === 0 && info.outgoing.length === 0 && info.incoming.length === 0) {
      this._infos.delete(info.key)

      for (const alias of info.aliases) this._infos.delete(alias)
    }
  }

  _ondata(buffer) {
    if (buffer.byteLength === 0) return // ignore empty frames...
    try {
      const state = { buffer, start: 0, end: buffer.byteLength }
      this._decode(c.uint.decode(state), state)
    } catch (err) {
      this._safeDestroy(err)
    }
  }

  _ondrain() {
    this.drained = true

    for (const s of this._local) {
      if (s !== null) s._track(s.ondrain(s))
    }
  }

  _onend() {
    // TODO: support half open mode for the users who wants that here
    this.stream.end()
  }

  _decode(remoteId, state) {
    const type = c.uint.decode(state)

    if (remoteId === 0) {
      return this._oncontrolsession(type, state)
    }

    const r = remoteId <= this._remote.length ? this._remote[remoteId - 1] : null

    // if the channel is closed ignore - could just be a pipeline message...
    if (r === null) return null

    if (r.pending !== null) {
      this._bufferMessage(r, type, state)
      return null
    }

    return r.session._recv(type, state)
  }

  _oncontrolsession(type, state) {
    switch (type) {
      case 0:
        this._onbatch(state)
        break

      case 1:
        // return the promise back up as this has sideeffects so we can batch reply
        return this._onopensession(state)

      case 2:
        this._onrejectsession(state)
        break

      case 3:
        this._onclosesession(state)
        break
    }

    return null
  }

  _bufferMessage(r, type, { buffer, start, end }) {
    const state = { buffer, start, end } // copy
    r.pending.push({ type, state })
    this._buffered += byteSize(state)
    this._pauseMaybe()
  }

  _pauseMaybe() {
    if (this._paused === true || this._buffered <= MAX_BUFFERED) return
    this._paused = true
    this.stream.pause()
  }

  _resumeMaybe() {
    if (this._paused === false || this._buffered > MAX_BUFFERED) return
    this._paused = false
    this.stream.resume()
  }

  _onbatch(state) {
    const end = state.end
    let remoteId = c.uint.decode(state)

    let waiting = null

    while (state.end > state.start) {
      const len = c.uint.decode(state)
      if (len === 0) {
        remoteId = c.uint.decode(state)
        continue
      }
      state.end = state.start + len
      // if batch contains more than one message, cork it so we reply back with a batch
      if (end !== state.end && waiting === null) {
        waiting = []
        this.cork()
      }
      const p = this._decode(remoteId, state)
      if (waiting !== null && p !== null) waiting.push(p)
      state.start = state.end
      state.end = end
    }

    if (waiting !== null) {
      // the waiting promises are not allowed to throw but we destroy the stream in case we are wrong
      Promise.all(waiting).then(this._uncorkBound, this._safeDestroyBound)
    }
  }

  _onopensession(state) {
    const remoteId = c.uint.decode(state)
    const protocol = c.string.decode(state)
    const id = unslab(c.optionalBuffer.decode(state))

    // remote tried to open the control session - auto reject for now
    // as we can use as an explicit control protocol declaration if we need to
    if (remoteId === 0) {
      this._rejectSession(0)
      return null
    }

    const rid = remoteId - 1
    const info = this._get(protocol, id)

    // allow the remote to grow the ids by one
    if (this._remote.length === rid) {
      this._remote.push(null)
    }

    if (rid >= this._remote.length || this._remote[rid] !== null) {
      throw new Error('Invalid open message')
    }

    if (info.outgoing.length > 0) {
      const localId = info.outgoing.shift()
      const session = this._local[localId - 1]

      if (session === null) {
        // we already closed the channel - ignore
        this._free.push(localId - 1)
        return null
      }

      this._remote[rid] = { state, pending: null, session: null }

      session._remoteId = remoteId
      session._fullyOpen()
      return null
    }

    const copyState = { buffer: state.buffer, start: state.start, end: state.end }
    this._remote[rid] = { state: copyState, pending: [], session: null }

    if (++this._remoteBacklog > MAX_BACKLOG) {
      throw new Error('Remote exceeded backlog')
    }

    info.pairing++
    info.incoming.push(remoteId)

    return this._requestSession(protocol, id, info).catch(this._safeDestroyBound)
  }

  _onrejectsession(state) {
    const localId = c.uint.decode(state)

    // TODO: can be done smarter...
    for (const info of this._infos.values()) {
      const i = info.outgoing.indexOf(localId)
      if (i === -1) continue

      info.outgoing.splice(i, 1)

      const session = this._local[localId - 1]

      this._free.push(localId - 1)
      if (session !== null) session._close(true)

      this._gc(info)
      return
    }

    throw new Error('Invalid reject message')
  }

  _onclosesession(state) {
    const remoteId = c.uint.decode(state)

    if (remoteId === 0) return // ignore

    const rid = remoteId - 1
    const r = rid < this._remote.length ? this._remote[rid] : null

    if (r === null) return

    if (r.session !== null) r.session._close(true)
  }

  async _requestSession(protocol, id, info) {
    const notify = this._notify.get(toKey(protocol, id)) || this._notify.get(toKey(protocol, null))

    if (notify) await notify(id)

    if (--info.pairing > 0) return

    while (info.incoming.length > 0) {
      this._rejectSession(info, info.incoming.shift())
    }

    this._gc(info)
  }

  _rejectSession(info, remoteId) {
    if (remoteId > 0) {
      const r = this._remote[remoteId - 1]

      if (r.pending !== null) {
        for (let i = 0; i < r.pending.length; i++) {
          this._buffered -= byteSize(r.pending[i].state)
        }
      }

      this._remote[remoteId - 1] = null
      this._resumeMaybe()
    }

    const state = { buffer: null, start: 2, end: 2 }

    c.uint.preencode(state, remoteId)

    state.buffer = this._alloc(state.end)

    state.buffer[0] = 0
    state.buffer[1] = 2
    c.uint.encode(state, remoteId)

    this._write0(state.buffer)
  }

  _write0(buffer) {
    if (this._batch !== null) {
      this._pushBatch(0, buffer.subarray(1))
      return
    }

    this.drained = this.stream.write(buffer)
  }

  destroy(err) {
    this._destroying = true
    this.stream.destroy(err)
  }

  _safeDestroy(err) {
    safetyCatch(err)
    this._destroying = true
    this.stream.destroy(err)
  }

  _shutdown() {
    this._destroying = true
    for (const s of this._local) {
      if (s !== null) s._close(true)
    }
  }
}

function noop() {}

function toKey(protocol, id) {
  return protocol + '##' + (id ? b4a.toString(id, 'hex') : '')
}

function byteSize(state) {
  return 512 + (state.end - state.start)
}

function isPromise(p) {
  return !!(p && typeof p.then === 'function')
}

function encodingLength(enc, val) {
  const state = { buffer: null, start: 0, end: 0 }
  enc.preencode(state, val)
  return state.end
}
{
  "name": "protomux",
  "version": "3.11.0",
  "description": "Multiplex multiple message oriented protocols over a stream",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.3.1",
    "compact-encoding": "^3.0.0",
    "queue-tick": "^1.0.0",
    "safety-catch": "^1.0.1",
    "unslab": "^1.3.0"
  },
  "devDependencies": {
    "@hyperswarm/secret-stream": "^6.0.0",
    "brittle": "^3.0.0",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/protomux.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/protomux/issues"
  },
  "homepage": "https://github.com/holepunchto/protomux"
}
{
  "name": "queue-tick",
  "version": "1.0.1",
  "description": "Next tick shim that prefers process.nextTick over queueMicrotask for compat",
  "main": "./process-next-tick.js",
  "browser": "./queue-microtask.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^16.0.3",
    "tape": "^5.3.1"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/queue-tick.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/queue-tick/issues"
  },
  "homepage": "https://github.com/mafintosh/queue-tick"
}
module.exports = (typeof process !== 'undefined' && typeof process.nextTick === 'function')
  ? process.nextTick.bind(process)
  : require('./queue-microtask')
module.exports = typeof queueMicrotask === 'function' ? queueMicrotask : (fn) => Promise.resolve().then(fn)
const EventEmitter = require('events')

module.exports = class ReadyResource extends EventEmitter {
  constructor () {
    super()

    this.opening = null
    this.closing = null

    this.opened = false
    this.closed = false
  }

  ready () {
    if (this.opening !== null) return this.opening
    this.opening = open(this)
    return this.opening
  }

  close () {
    if (this.closing !== null) return this.closing
    this.closing = close(this)
    return this.closing
  }

  async _open () {
    // add impl here
  }

  async _close () {
    // add impl here
  }
}

async function open (self) {
  // open after close
  if (self.closing !== null) return

  try {
    await self._open()
  } catch (err) {
    self.close() // safe to run in bg
    throw err
  }

  self.opened = true
  self.emit('ready')
}

async function close (self) {
  try {
    if (self.opened === false && self.opening !== null) await self.opening
  } catch {
    // ignore errors on closing
  }
  if (self.opened === true || self.opening === null) await self._close()
  self.closed = true
  self.emit('close')
}
{
  "name": "ready-resource",
  "version": "1.2.0",
  "description": "Modern single resource management",
  "main": "index.js",
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "types": "index.d.ts",
  "files": [
    "index.js",
    "index.d.ts"
  ],
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "devDependencies": {
    "brittle": "^3.1.0",
    "standard": "^17.0.0"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/ready-resource.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/ready-resource/issues"
  },
  "homepage": "https://github.com/holepunchto/ready-resource",
  "dependencies": {
    "bare-events": "^2.2.0"
  }
}
const b4a = require('b4a')

var EMPTY = []

module.exports = RecordCache

function RecordSet () {
  this.list = []
  this.map = new Map()
}

RecordSet.prototype.add = function (record, value) {
  var k = toString(record)
  var r = this.map.get(k)
  if (r) return false

  r = {index: this.list.length, record: value || record}
  this.list.push(r)
  this.map.set(k, r)
  return true
}

RecordSet.prototype.remove = function (record) {
  var k = toString(record)
  var r = this.map.get(k)
  if (!r) return false

  swap(this.list, r.index, this.list.length - 1)
  this.list.pop()
  this.map.delete(k)
  return true
}

function RecordStore () {
  this.records = new Map()
  this.size = 0
}

RecordStore.prototype.add = function (name, record, value) {
  var r = this.records.get(name)

  if (!r) {
    r = new RecordSet()
    this.records.set(name, r)
  }

  if (r.add(record, value)) {
    this.size++
    return true
  }

  return false
}

RecordStore.prototype.remove = function (name, record, value) {
  var r = this.records.get(name)
  if (!r) return false

  if (r.remove(record, value)) {
    this.size--
    if (!r.map.size) this.records.delete(name)
    return true
  }

  return false
}

RecordStore.prototype.get = function (name) {
  var r = this.records.get(name)
  return r ? r.list : EMPTY
}

function RecordCache (opts) {
  if (!(this instanceof RecordCache)) return new RecordCache(opts)
  if (!opts) opts = {}

  this.maxSize = opts.maxSize || Infinity
  this.maxAge = opts.maxAge || 0

  this._onstale = opts.onStale || opts.onstale || null
  this._fresh = new RecordStore()
  this._stale = new RecordStore()
  this._interval = null
  this._gced = false

  if (this.maxAge && this.maxAge < Infinity) {
    // 2/3 gives us a span of 0.66-1.33 maxAge or avg maxAge
    var tick = Math.ceil(2 / 3 * this.maxAge)
    this._interval = setInterval(this._gcAuto.bind(this), tick)
    if (this._interval.unref) this._interval.unref()
  }
}

Object.defineProperty(RecordCache.prototype, 'size', {
  get: function () {
    return this._fresh.size + this._stale.size
  }
})

RecordCache.prototype.add = function (name, record, value) {
  this._stale.remove(name, record, value)
  if (this._fresh.add(name, record, value) && this._fresh.size > this.maxSize) {
    this._gc()
  }
}

RecordCache.prototype.remove = function (name, record, value) {
  this._fresh.remove(name, record, value)
  this._stale.remove(name, record, value)
}

RecordCache.prototype.get = function (name, n) {
  var a = this._fresh.get(name)
  var b = this._stale.get(name)
  var aLen = a.length
  var bLen = b.length
  var len = aLen + bLen

  if (n > len || !n) n = len
  var result = new Array(n)

  for (var i = 0; i < n; i++) {
    var j = Math.floor(Math.random() * (aLen + bLen))
    if (j < aLen) {
      result[i] = a[j].record
      swap(a, j, --aLen)
    } else {
      j -= aLen
      result[i] = b[j].record
      swap(b, j, --bLen)
    }
  }

  return result
}

RecordCache.prototype._gcAuto = function () {
  if (!this._gced) this._gc()
  this._gced = false
}

RecordCache.prototype._gc = function () {
  if (this._onstale && this._stale.size > 0) this._onstale(this._stale)
  this._stale = this._fresh
  this._fresh = new RecordStore()
  this._gced = true
}

RecordCache.prototype.clear = function () {
  this._gc()
  this._gc()
}

RecordCache.prototype.destroy = function () {
  this.clear()
  clearInterval(this._interval)
  this._interval = null
}

function toString (record) {
  return b4a.isBuffer(record) ? b4a.toString(record, 'hex') : record
}

function swap (list, a, b) {
  var tmp = list[a]
  tmp.index = b
  list[b].index = a
  list[a] = list[b]
  list[b] = tmp
}
{
  "name": "record-cache",
  "version": "1.2.0",
  "description": "Cache optimised for record like things",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.3.1"
  },
  "devDependencies": {
    "standard": "^10.0.3",
    "tape": "^4.8.0"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/record-cache.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/record-cache/issues"
  },
  "homepage": "https://github.com/mafintosh/record-cache"
}
module.exports = require.addon.bind(require)
{
  "name": "require-addon",
  "version": "1.2.0",
  "description": "Import native addons across JavaScript runtimes",
  "exports": {
    "./package": "./package.json",
    ".": {
      "bare": "./lib/bare.js",
      "node": "./lib/node.js",
      "default": "./lib/default.js"
    }
  },
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    },
    "url": {
      "bare": "bare-url",
      "default": "url"
    }
  },
  "files": [
    "lib"
  ],
  "scripts": {
    "test": "npm run lint && npm run test:bare && npm run test:node",
    "test:bare": "bare test.js",
    "test:node": "node test.js",
    "lint": "prettier --check .",
    "format": "prettier --write ."
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/require-addon.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/require-addon/issues"
  },
  "homepage": "https://github.com/holepunchto/require-addon#readme",
  "engines": {
    "bare": ">=1.10.0"
  },
  "dependencies": {
    "bare-addon-resolve": "^1.3.0"
  },
  "devDependencies": {
    "bare-bundle": "^1.8.1",
    "bare-bundle-evaluate": "^1.1.0",
    "bare-fs": "^4.0.0",
    "bare-path": "^3.0.0",
    "bare-url": "^2.1.0",
    "brittle": "^3.7.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = safetyCatch

function isActuallyUncaught (err) {
  if (!err) return false
  return err instanceof TypeError ||
    err instanceof SyntaxError ||
    err instanceof ReferenceError ||
    err instanceof EvalError ||
    err instanceof RangeError ||
    err instanceof URIError ||
    err.code === 'ERR_ASSERTION' ||
    err.name === 'AssertionError'
}

function throwErrorNT (err) {
  queueMicrotask(() => { throw err })
}

function safetyCatch (err) {
  if (isActuallyUncaught(err)) {
    throwErrorNT(err)
    throw err
  }
}
{
  "name": "safety-catch",
  "version": "1.0.3",
  "description": "Small module that makes sure your catch, caught an actual error and not a programming mistake or assertion",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {},
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/safety-catch.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/safety-catch/issues"
  },
  "homepage": "https://github.com/mafintosh/safety-catch"
}
const set = require('unordered-set')

module.exports = opts => new ShuffledPriorityQueue(opts)

class ShuffledPriorityQueue {
  constructor (opts) {
    this.priorities = []
    this.equals = (opts && opts.equals) || null
  }

  get length () {
    return this.priorities.reduce(add, 0)
  }

  [Symbol.iterator] () {
    return new Iterator(this)
  }

  head () {
    for (let i = this.priorities.length - 1; i >= 0; i--) {
      const q = this.priorities[i]
      if (q.length) return shuffle(q, 0)
    }
    return null
  }

  tail () {
    for (let i = 0; i < this.priorities.length; i++) {
      const q = this.priorities[i]
      if (q.length) return shuffle(q, 0)
    }
    return null
  }

  prev (prev) {
    if (!prev) return this.tail()
    return next(this.priorities, prev, 1)
  }

  next (prev) {
    if (!prev) return this.head()
    return next(this.priorities, prev, -1)
  }

  shift () {
    return this.remove(this.head())
  }

  pop () {
    return this.remove(this.tail())
  }

  add (val) {
    const prio = val.priority || 0
    while (prio >= this.priorities.length) this.priorities.push([])
    set.add(this.priorities[prio], val)
    return val
  }

  remove (val) {
    if (!val) return null

    if (val._index === undefined) {
      val = this.find(val)
      if (!val) return null
    }

    return set.remove(this.priorities[val.priority || 0], val)
  }

  has (val) {
    if (val._index === undefined) return this.find(val)
    const priority = val.priority || 0
    if (priority >= this.priorities.length) return false
    return set.has(this.priorities[priority], val)
  }

  find (val) {
    if (val._index !== undefined) return val

    const prio = val.priority || 0
    const qs = this.priorities
    if (prio >= qs.length) return null

    const q = qs[prio]

    for (let i = 0; i < q.length; i++) {
      if (this.equals(q[i], val)) return q[i]
    }

    return null
  }
}

class Iterator {
  constructor (queue) {
    this.prev = null
    this.queue = queue
  }

  next () {
    const next = this.queue.next(this.prev)
    this.prev = next
    return { done: !next, value: next }
  }
}

function shuffle (q, i) {
  const ran = i + Math.floor(Math.random() * (q.length - i))
  set.swap(q, q[ran], q[i])
  return q[i]
}

function next (queues, prev, inc) {
  let i = prev.priority || 0
  let j = (prev._index || 0) + 1

  while (true) {
    if (i < 0 || i >= queues.length) return null
    const q = queues[i]

    if (j >= q.length) {
      i += inc
      j = 0
      continue
    }

    return shuffle(q, j)
  }
}

function add (len, b) {
  return len + b.length
}
{
  "name": "shuffled-priority-queue",
  "version": "2.1.0",
  "description": "A priority queue that shuffles elements with the same priority.",
  "main": "index.js",
  "scripts": {
    "test": "standard && tape test.js"
  },
  "dependencies": {
    "unordered-set": "^2.0.1"
  },
  "devDependencies": {
    "standard": "^12.0.1",
    "tape": "^4.9.1"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/shuffled-priority-queue.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/shuffled-priority-queue/issues"
  },
  "homepage": "https://github.com/mafintosh/shuffled-priority-queue"
}
module.exports = class Signal {
  constructor () {
    this._resolve = null
    this._reject = null
    this._promise = null
    this._bind = bind.bind(this)
    this._onerror = clear.bind(this)
    this._onsuccess = clear.bind(this, null)
    this._timers = new Set()
  }

  wait (max) {
    if (!this._promise) {
      this._promise = new Promise(this._bind)
      this._promise.then(this._onsuccess).catch(this._onerror)
    }
    if (max) return this._sleep(max)
    return this._promise
  }

  _sleep (max) {
    const s = new Promise((resolve, reject) => {
      const done = () => {
        this._timers.delete(state)
        resolve(true)
      }
      const id = setTimeout(done, max)
      const state = { id, resolve, reject }
      this._timers.add(state)
    })

    return s
  }

  notify (err) {
    if (!this._promise) return
    const resolve = this._resolve
    const reject = this._reject
    this._promise = null
    if (err) reject(err)
    else resolve(true)
  }
}

function clear (err) {
  for (const { id, resolve, reject } of this._timers) {
    clearTimeout(id)
    if (err) reject(err)
    else resolve(true)
  }
  this._timers.clear()
}

function bind (resolve, reject) {
  this._resolve = resolve
  this._reject = reject
}
{
  "name": "signal-promise",
  "version": "1.0.3",
  "description": "Simple wait/notify promise with optional max wait time",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {},
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/signal-promise.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/signal-promise/issues"
  },
  "homepage": "https://github.com/mafintosh/signal-promise"
}
require.addon = require('require-addon')
module.exports = require.addon('.', __filename)
const assert = require('assert')
const binding = require('./binding')
const { isNode } = require('which-runtime')

const OPTIONAL = Buffer.from(new ArrayBuffer(0))

module.exports = exports = { ...binding }

// memory

exports.sodium_memzero = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  binding.sodium_memzero(buf)
}

exports.sodium_mlock = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  const res = binding.sodium_mlock(buf)

  if (res !== 0) throw new Error('memory lock failed')
}

exports.sodium_munlock = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  const res = binding.sodium_munlock(buf)

  if (res !== 0) throw new Error('memory unlock failed')
}

exports.sodium_malloc = function (size) {
  assert(size >= 0, 'invalid size')

  const buf = Buffer.from(binding.sodium_malloc(size))
  buf.secure = true
  return buf
}

exports.sodium_free = function (buf) {
  if (!buf || !buf.secure) return

  binding.sodium_free(buf.buffer)
}

exports.sodium_mprotect_noaccess = function (buf) {
  const res = binding.sodium_mprotect_noaccess(buf.buffer)

  if (res !== 0) throw new Error('failed to lock buffer')
}

exports.sodium_mprotect_readonly = function (buf) {
  const res = binding.sodium_mprotect_readonly(buf.buffer)

  if (res !== 0) throw new Error('failed to unlock buffer')
}

exports.sodium_mprotect_readwrite = function (buf) {
  const res = binding.sodium_mprotect_readwrite(buf.buffer)

  if (res !== 0) throw new Error('failed to unlock buffer')
}

// crypto_randombytes

exports.randombytes_buf = function (buffer) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')

  binding.randombytes_buf(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

exports.randombytes_buf_deterministic = function (buffer, seed) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    seed.byteLength === binding.randombytes_SEEDBYTES,
    "seed must be 'randombytes_SEEDBYTES' bytes"
  )

  binding.randombytes_buf_deterministic(
    buffer.buffer,
    buffer.byteOffset,
    buffer.byteLength,

    seed.buffer,
    seed.byteOffset,
    seed.byteLength
  )
}

// sodium_helpers

exports.sodium_memcmp = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  return binding.sodium_memcmp(a, b)
}

exports.sodium_add = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  binding.sodium_add(a, b)
}

exports.sodium_sub = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  binding.sodium_sub(a, b)
}

exports.sodium_compare = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  return binding.sodium_compare(a, b)
}

exports.sodium_is_zero = function (buffer, length) {
  if (length === undefined) length = buffer.byteLength

  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(length >= 0 && length <= buffer.byteLength, 'invalid length')

  return binding.sodium_is_zero(buffer, length)
}

exports.sodium_pad = function (buffer, unpaddedBuflen, blockSize) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(unpaddedBuflen <= buffer.byteLength, 'unpadded length cannot exceed buffer length')
  assert(blockSize <= buffer.byteLength, 'block size cannot exceed buffer length')
  assert(blockSize >= 1, 'block size must be at least 1 byte')
  assert(
    buffer.byteLength >= unpaddedBuflen + (blockSize - (unpaddedBuflen % blockSize)),
    'buf not long enough'
  )

  return binding.sodium_pad(buffer, unpaddedBuflen, blockSize)
}

exports.sodium_unpad = function (buffer, paddedBuflen, blockSize) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(paddedBuflen <= buffer.byteLength, 'unpadded length cannot exceed buffer length')
  assert(blockSize <= buffer.byteLength, 'block size cannot exceed buffer length')
  assert(blockSize >= 1, 'block size must be at least 1 byte')

  return binding.sodium_unpad(buffer, paddedBuflen, blockSize)
}

// crypto_sign

exports.crypto_sign_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )
  assert(
    seed.byteLength === binding.crypto_sign_SEEDBYTES,
    "seed must be 'crypto_sign_SEEDBYTES' bytes"
  )

  const res = binding.crypto_sign_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign = function (sm, m, sk) {
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sm.byteLength === binding.crypto_sign_BYTES + m.byteLength,
    "sm must be 'm.byteLength + crypto_sign_BYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign(sm, m, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_open = function (m, sm, pk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sm.byteLength >= binding.crypto_sign_BYTES,
    "sm must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    m.byteLength === sm.byteLength - binding.crypto_sign_BYTES,
    "m must be 'sm.byteLength - crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_open(m, sm, pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_open = function (m, sm, pk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sm.byteLength >= binding.crypto_sign_BYTES,
    "sm must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    m.byteLength === sm.byteLength - binding.crypto_sign_BYTES,
    "m must be 'sm.byteLength - crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  return binding.crypto_sign_open(m, sm, pk)
}

exports.crypto_sign_detached = function (sig, m, sk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(sig.byteLength === binding.crypto_sign_BYTES, "sig must be 'crypto_sign_BYTES' bytes")
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_detached(sig, m, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_verify_detached = function (sig, m, pk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sig.byteLength >= binding.crypto_sign_BYTES,
    "sig must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  return binding.crypto_sign_verify_detached(
    sig.buffer,
    sig.byteOffset,
    sig.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    pk.buffer,
    pk.byteOffset,
    pk.byteLength
  )
}

exports.crypto_sign_ed25519_sk_to_pk = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_sk_to_pk(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_ed25519_pk_to_curve25519 = function (x25519pk, ed25519pk) {
  assert(ArrayBuffer.isView(x25519pk), 'x25519pk must be a typed array')
  assert(ArrayBuffer.isView(ed25519pk), 'ed25519pk must be a typed array')
  assert(
    x25519pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "x25519pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    ed25519pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "ed25519pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_pk_to_curve25519(x25519pk, ed25519pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_ed25519_sk_to_curve25519 = function (x25519sk, ed25519sk) {
  assert(ArrayBuffer.isView(x25519sk), 'x25519sk must be a typed array')
  assert(ArrayBuffer.isView(ed25519sk), 'ed25519sk must be a typed array')
  assert(
    x25519sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "x25519sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const edLen = ed25519sk.byteLength

  assert(
    edLen === binding.crypto_sign_SECRETKEYBYTES || edLen === binding.crypto_box_SECRETKEYBYTES,
    "ed25519sk must be 'crypto_sign_SECRETKEYBYTES' or 'crypto_sign_SECRETKEYBYTES - crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_sk_to_curve25519(x25519sk, ed25519sk)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_box

exports.crypto_box_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    seed.byteLength === binding.crypto_box_SEEDBYTES,
    "seed must be 'crypto_box_SEEDBYTES' bytes"
  )

  const res = binding.crypto_box_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_easy = function (c, m, n, pk, sk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength === m.byteLength + exports.crypto_box_MACBYTES,
    "c must be 'm.byteLength + crypto_box_MACBYTES' bytes"
  )
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_easy(c, m, n, pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_detached = function (c, mac, m, n, pk, sk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(mac.byteLength === exports.crypto_box_MACBYTES, "mac must be 'crypto_box_MACBYTES' bytes")
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_detached(c, mac, m, n, pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_open_easy = function (m, c, n, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength >= exports.crypto_box_MACBYTES,
    "c must be at least 'crypto_box_MACBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - exports.crypto_box_MACBYTES,
    "m must be 'c.byteLength - crypto_box_MACBYTES' bytes"
  )
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_open_easy(m, c, n, pk, sk)
}

exports.crypto_box_open_detached = function (m, c, mac, n, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(mac.byteLength === exports.crypto_box_MACBYTES, "mac must be 'crypto_box_MACBYTES' bytes")
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_open_detached(m, c, mac, n, pk, sk)
}

exports.crypto_box_seal = function (c, m, pk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    c.byteLength === m.byteLength + exports.crypto_box_SEALBYTES,
    "c must be 'm.byteLength + crypto_box_SEALBYTES' bytes"
  )
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_box_seal(c, m, pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_seal_open = function (m, c, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength >= exports.crypto_box_SEALBYTES,
    "c must be at least 'crypto_box_SEALBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - exports.crypto_box_SEALBYTES,
    "m must be 'c.byteLength - crypto_box_SEALBYTES' bytes"
  )
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_seal_open(
    m.buffer,
    m.byteOffset,
    m.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    pk.buffer,
    pk.byteOffset,
    pk.byteLength,

    sk.buffer,
    sk.byteOffset,
    sk.byteLength
  )
}

// crypto_secretbox

exports.crypto_secretbox_easy = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_secretbox_MACBYTES,
    "c must be 'm.byteLength + crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretbox_easy(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretbox_open_easy = function (m, c, n, k) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    c.byteLength >= binding.crypto_secretbox_MACBYTES,
    "c must be at least 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - binding.crypto_secretbox_MACBYTES,
    "m must be 'c.byteLength - crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  return binding.crypto_secretbox_open_easy(m, c, n, k)
}

exports.crypto_secretbox_detached = function (c, mac, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    mac.byteLength === binding.crypto_secretbox_MACBYTES,
    "mac must be 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretbox_detached(c, mac, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretbox_open_detached = function (m, c, mac, n, k) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(
    mac.byteLength === binding.crypto_secretbox_MACBYTES,
    "mac must be 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  return binding.crypto_secretbox_open_detached(m, c, mac, n, k)
}

// crypto_generichash

exports.crypto_generichash = function (output, input, key) {
  if (!key) key = OPTIONAL

  assert(ArrayBuffer.isView(output), 'output must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    output.byteLength >= binding.crypto_generichash_BYTES_MIN &&
      output.byteLength <= binding.crypto_generichash_BYTES_MAX,
    'output must be between crypto_generichash_BYTES_MIN and crypto_generichash_BYTES_MAX bytes'
  )

  if (key !== OPTIONAL) {
    assert(ArrayBuffer.isView(key), 'key must be a typed array')
    assert(
      key.byteLength >= binding.crypto_generichash_KEYBYTES_MIN &&
        key.byteLength <= binding.crypto_generichash_KEYBYTES_MAX,
      'key must be between crypto_generichash_KEYBYTES_MIN and crypto_generichash_KEYBYTES_MAX bytes'
    )
  }

  const res = binding.crypto_generichash(
    output.buffer,
    output.byteOffset,
    output.byteLength,

    input.buffer,
    input.byteOffset,
    input.byteLength,

    key.buffer,
    key.byteOffset,
    key.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_batch = function (output, batch, key) {
  assert(ArrayBuffer.isView(output), 'output must be a typed array')

  if (isNode || batch.length < 4) {
    const res = binding.crypto_generichash_batch(output, batch, !!key, key || OPTIONAL)
    if (res !== 0) throw new Error('status: ' + res)
  } else {
    const state = Buffer.alloc(binding.crypto_generichash_STATEBYTES)

    exports.crypto_generichash_init(state, key, output.byteLength)

    for (const buf of batch) {
      exports.crypto_generichash_update(state, buf)
    }

    exports.crypto_generichash_final(state, output)
  }
}

exports.crypto_generichash_keygen = function (key) {
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(
    key.byteLength === binding.crypto_generichash_KEYBYTES,
    "key must be 'crypto_generichash_KEYBYTES' bytes"
  )

  const res = binding.crypto_generichash_keygen(key.buffer, key.byteOffset, key.byteLength)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_init = function (state, key, outputLength) {
  if (!key) key = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_init(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    key.buffer,
    key.byteOffset,
    key.byteLength,

    outputLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_update(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    input.buffer,
    input.byteOffset,
    input.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_final = function (state, output) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(output), 'output must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_final(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    output.buffer,
    output.byteOffset,
    output.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

// secretstream

exports.crypto_secretstream_xchacha20poly1305_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  binding.crypto_secretstream_xchacha20poly1305_keygen(k.buffer, k.byteOffset, k.byteLength)
}

exports.crypto_secretstream_xchacha20poly1305_init_push = function (state, header, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(header), 'header must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    header.byteLength === binding.crypto_secretstream_xchacha20poly1305_HEADERBYTES,
    "header must be 'crypto_secretstream_xchacha20poly1305_HEADERBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_init_push(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    header.buffer,
    header.byteOffset,
    header.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretstream_xchacha20poly1305_init_pull = function (state, header, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(header), 'header must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    header.byteLength === binding.crypto_secretstream_xchacha20poly1305_HEADERBYTES,
    "header must be 'crypto_secretstream_xchacha20poly1305_HEADERBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_init_pull(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    header.buffer,
    header.byteOffset,
    header.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretstream_xchacha20poly1305_push = function (state, c, m, ad, tag) {
  if (!ad) ad = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    c.byteLength === m.byteLength + binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "c must be 'm.byteLength + crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_push(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    ad.buffer,
    ad.byteOffset,
    ad.byteLength,

    tag
  )

  if (res < 0) throw new Error('push failed')

  return res
}

exports.crypto_secretstream_xchacha20poly1305_pull = function (state, m, tag, c, ad) {
  if (!ad) ad = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(tag), 'tag must be a typed array')
  assert(tag.byteLength === 1, 'tag must be 1 byte')

  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    c.byteLength >= binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "c must be at least 'crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "m must be 'c.byteLength - crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_pull(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    tag.buffer,
    tag.byteOffset,
    tag.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    ad.buffer,
    ad.byteOffset,
    ad.byteLength
  )

  if (res < 0) throw new Error('pull failed')

  return res
}

exports.crypto_secretstream_xchacha20poly1305_rekey = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )

  binding.crypto_secretstream_xchacha20poly1305_rekey(
    state.buffer,
    state.byteOffset,
    state.byteLength
  )
}

// crypto_stream

exports.crypto_stream = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xor(
    c.buffer,
    c.byteOffset,
    c.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    n.buffer,
    n.byteOffset,
    n.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_auth

exports.crypto_auth = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(out.byteLength === binding.crypto_auth_BYTES, "out must be 'crypto_auth_BYTES' bytes")
  assert(k.byteLength === binding.crypto_auth_KEYBYTES, "k must be 'crypto_auth_KEYBYTES' bytes")

  const res = binding.crypto_auth(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_auth_verify = function (h, input, k) {
  assert(ArrayBuffer.isView(h), 'h must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(h.byteLength === binding.crypto_auth_BYTES, "h must be 'crypto_auth_BYTES' bytes")
  assert(k.byteLength === binding.crypto_auth_KEYBYTES, "k must be 'crypto_auth_KEYBYTES' bytes")

  return binding.crypto_auth_verify(h, input, k)
}

// crypto_onetimeauth

exports.crypto_onetimeauth = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    out.byteLength === binding.crypto_onetimeauth_BYTES,
    "out must be 'crypto_onetimeauth_BYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_init = function (state, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_init(state, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )
  assert(
    out.byteLength === binding.crypto_onetimeauth_BYTES,
    "out must be 'crypto_onetimeauth_BYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_verify = function (h, input, k) {
  assert(ArrayBuffer.isView(h), 'h must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    h.byteLength === binding.crypto_onetimeauth_BYTES,
    "h must be 'crypto_onetimeauth_BYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  return binding.crypto_onetimeauth_verify(h, input, k)
}

// crypto_pwhash

exports.crypto_pwhash = function (out, passwd, salt, opslimit, memlimit, alg) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_BYTES_MIN,
    "out must be at least 'crypto_pwhash_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_BYTES_MAX,
    "out must be at most 'crypto_pwhash_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_SALTBYTES,
    "salt must be 'crypto_pwhash_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )
  assert(alg >= 1 && alg <= 2, 'alg must be either Argon2i 1.3 or Argon2id 1.3')

  const res = binding.crypto_pwhash(out, passwd, salt, opslimit, memlimit, alg)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_async = function (
  out,
  passwd,
  salt,
  opslimit,
  memlimit,
  alg,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_BYTES_MIN,
    "out must be at least 'crypto_pwhash_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_BYTES_MAX,
    "out must be at most 'crypto_pwhash_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_SALTBYTES,
    "salt must be 'crypto_pwhash_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )
  assert(alg >= 1 && alg <= 2, 'alg must be either Argon2i 1.3 or Argon2id 1.3')

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    opslimit,
    memlimit,
    alg,

    done
  )

  return promise
}

exports.crypto_pwhash_str = function (out, passwd, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_STRBYTES,
    "out must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(typeof opslimit === 'number', 'opslimit must be a number')
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(typeof memlimit === 'number', 'memlimit must be a number')
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_str(out, passwd, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_str_async = function (out, passwd, opslimit, memlimit, callback = undefined) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_STRBYTES,
    "out must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(typeof opslimit === 'number', 'opslimit must be a number')
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(typeof memlimit === 'number', 'memlimit must be a number')
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_str_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_str_verify = function (str, passwd) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )

  return binding.crypto_pwhash_str_verify(str, passwd)
}

exports.crypto_pwhash_str_verify_async = function (str, passwd, callback = undefined) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  const [done, promise] = checkStatus(callback, true)

  binding.crypto_pwhash_str_verify_async(
    str.buffer,
    str.byteOffset,
    str.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    done
  )

  return promise
}

exports.crypto_pwhash_str_needs_rehash = function (str, opslimit, memlimit) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  return binding.crypto_pwhash_str_needs_rehash(str, opslimit, memlimit)
}

exports.crypto_pwhash_scryptsalsa208sha256 = function (out, passwd, salt, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MIN,
    "out must be at least 'crypto_pwhash_scryptsalsa208sha256_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MAX,
    "out must be at most 'crypto_pwhash_scryptsalsa208sha256_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_SALTBYTES,
    "salt must be 'crypto_pwhash_scryptsalsa208sha256_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_scryptsalsa208sha256(out, passwd, salt, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_scryptsalsa208sha256_async = function (
  out,
  passwd,
  salt,
  opslimit,
  memlimit,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MIN,
    "out must be at least 'crypto_pwhash_scryptsalsa208sha256_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MAX,
    "out must be at most 'crypto_pwhash_scryptsalsa208sha256_BYTES_MAX' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    salt.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_SALTBYTES,
    "salt must be 'crypto_pwhash_scryptsalsa208sha256_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_scryptsalsa208sha256_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str_async = function (
  out,
  passwd,
  opslimit,
  memlimit,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "out must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_scryptsalsa208sha256_str_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str = function (out, passwd, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "out must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_scryptsalsa208sha256_str(out, passwd, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_scryptsalsa208sha256_str_verify_async = function (
  str,
  passwd,
  callback = undefined
) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  const [done, promise] = checkStatus(callback, true)

  binding.crypto_pwhash_scryptsalsa208sha256_str_verify_async(
    str.buffer,
    str.byteOffset,
    str.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str_verify = function (str, passwd) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  return binding.crypto_pwhash_scryptsalsa208sha256_str_verify(str, passwd)
}

exports.crypto_pwhash_scryptsalsa208sha256_str_needs_rehash = function (str, opslimit, memlimit) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  return binding.crypto_pwhash_scryptsalsa208sha256_str_needs_rehash(str, opslimit, memlimit)
}

// crypto_kx

exports.crypto_kx_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "pk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "sk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    pk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "pk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "sk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    seed.byteLength === binding.crypto_kx_SEEDBYTES,
    "seed must be 'crypto_kx_SEEDBYTES' bytes"
  )

  const res = binding.crypto_kx_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_client_session_keys = function (rx, tx, clientPk, clientSk, serverPk) {
  if (!rx) rx = undefined
  if (!tx) tx = undefined

  assert(rx || tx, 'at least one session key must be specified')

  if (rx) {
    assert(ArrayBuffer.isView(rx), 'rx must be a typed array')
    assert(
      rx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "rx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  if (tx) {
    assert(ArrayBuffer.isView(tx), 'tx must be a typed array')
    assert(
      tx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "tx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  assert(ArrayBuffer.isView(clientPk), 'clientPk must be a typed array')
  assert(ArrayBuffer.isView(clientSk), 'clientSk must be a typed array')
  assert(ArrayBuffer.isView(serverPk), 'serverPk must be a typed array')
  assert(
    clientPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "clientPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    clientSk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "clientSk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    serverPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "serverPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_client_session_keys(rx, tx, clientPk, clientSk, serverPk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_server_session_keys = function (rx, tx, serverPk, serverSk, clientPk) {
  if (!rx) rx = undefined
  if (!tx) tx = undefined

  assert(rx || tx, 'at least one session key must be specified')

  if (rx) {
    assert(ArrayBuffer.isView(rx), 'rx must be a typed array')
    assert(
      rx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "rx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  if (tx) {
    assert(ArrayBuffer.isView(tx), 'tx must be a typed array')
    assert(
      tx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "tx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  assert(ArrayBuffer.isView(serverPk), 'serverPk must be a typed array')
  assert(ArrayBuffer.isView(serverSk), 'serverSk must be a typed array')
  assert(ArrayBuffer.isView(clientPk), 'clientPk must be a typed array')
  assert(
    serverPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "serverPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    serverSk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "serverSk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    clientPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "clientPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_server_session_keys(rx, tx, serverPk, serverSk, clientPk)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_scalarmult

exports.crypto_scalarmult_base = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_BYTES,
    "q must be 'crypto_scalarmult_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_SCALARBYTES,
    "n must be 'crypto_scalarmult_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_base(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_BYTES,
    "q must be 'crypto_scalarmult_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_SCALARBYTES,
    "n must be 'crypto_scalarmult_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_BYTES,
    "p must be 'crypto_scalarmult_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_base = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_base(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519 = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "p must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_is_valid_point = function (p) {
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )

  return binding.crypto_core_ed25519_is_valid_point(p)
}

exports.crypto_core_ed25519_from_uniform = function (p, r) {
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_UNIFORMBYTES,
    "r must be 'crypto_core_ed25519_UNIFORMBYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_from_uniform(p, r)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_base_noclamp = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_base_noclamp(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_noclamp = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "p must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_noclamp(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_core

exports.crypto_core_ed25519_add = function (r, p, q) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_BYTES,
    "r must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_core_ed25519_BYTES,
    "q must be 'crypto_core_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_add(r, p, q)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_sub = function (r, p, q) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_BYTES,
    "r must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_core_ed25519_BYTES,
    "q must be 'crypto_core_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_sub(r, p, q)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_scalar_random = function (r) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "r must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_random(r)
}

exports.crypto_core_ed25519_scalar_reduce = function (r, s) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "r must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_NONREDUCEDSCALARBYTES,
    "s must be 'crypto_core_ed25519_NONREDUCEDSCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_reduce(r, s)
}

exports.crypto_core_ed25519_scalar_invert = function (recip, s) {
  assert(ArrayBuffer.isView(recip), 'recip must be a typed array')
  assert(
    recip.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "recip must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_invert(recip, s)
}

exports.crypto_core_ed25519_scalar_negate = function (neg, s) {
  assert(ArrayBuffer.isView(neg), 'neg must be a typed array')
  assert(
    neg.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "neg must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_negate(neg, s)
}

exports.crypto_core_ed25519_scalar_complement = function (comp, s) {
  assert(ArrayBuffer.isView(comp), 'comp must be a typed array')
  assert(
    comp.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "comp must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_complement(comp, s)
}

exports.crypto_core_ed25519_scalar_add = function (z, x, y) {
  assert(ArrayBuffer.isView(z), 'z must be a typed array')
  assert(
    z.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "z must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(x), 'x must be a typed array')
  assert(
    x.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "x must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(y), 'y must be a typed array')
  assert(
    y.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "y must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_add(z, x, y)
}

exports.crypto_core_ed25519_scalar_sub = function (z, x, y) {
  assert(ArrayBuffer.isView(z), 'z must be a typed array')
  assert(
    z.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "z must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(x), 'x must be a typed array')
  assert(
    x.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "x must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(y), 'y must be a typed array')
  assert(
    y.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "y must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_sub(z, x, y)
}

// crypto_shorthash

exports.crypto_shorthash = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_shorthash_BYTES,
    "out must be 'crypto_shorthash_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_shorthash_KEYBYTES,
    "k must be 'crypto_shorthash_KEYBYTES' bytes"
  )

  const res = binding.crypto_shorthash(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_kdf

exports.crypto_kdf_keygen = function (key) {
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(key.byteLength === binding.crypto_kdf_KEYBYTES, "key must be 'crypto_kdf_KEYBYTES' bytes")

  binding.crypto_kdf_keygen(key)
}

exports.crypto_kdf_derive_from_key = function (subkey, subkeyId, ctx, key) {
  assert(ArrayBuffer.isView(subkey), 'subkey must be a typed array')
  assert(
    subkey.byteLength >= binding.crypto_kdf_BYTES_MIN,
    "subkey must be at least 'crypto_kdf_BYTES_MIN' bytes"
  )
  assert(
    subkey.byteLength <= binding.crypto_kdf_BYTES_MAX,
    "subkey must be at most 'crypto_kdf_BYTES_MAX' bytes"
  )
  assert(ArrayBuffer.isView(ctx), 'ctx must be a typed array')
  assert(
    ctx.byteLength === binding.crypto_kdf_CONTEXTBYTES,
    "ctx must be 'crypto_kdf_CONTEXTBYTES' bytes"
  )
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(key.byteLength === binding.crypto_kdf_KEYBYTES, "key must be 'crypto_kdf_KEYBYTES' bytes")

  const res = binding.crypto_kdf_derive_from_key(subkey, subkeyId, ctx, key)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_hash

exports.crypto_hash = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(out.byteLength === binding.crypto_hash_BYTES, "out must be 'crypto_hash_BYTES' bytes")

  const res = binding.crypto_hash(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256 = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha256_BYTES,
    "out must be 'crypto_hash_sha256_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha256(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_init = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_init(state)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha256_BYTES,
    "out must be 'crypto_hash_sha256_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512 = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha512_BYTES,
    "out must be 'crypto_hash_sha512_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha512(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_init = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_init(state)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha512_BYTES,
    "out must be 'crypto_hash_sha512_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_aead

exports.crypto_aead_xchacha20poly1305_ietf_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  binding.crypto_aead_xchacha20poly1305_ietf_keygen(k)
}

exports.crypto_aead_xchacha20poly1305_ietf_encrypt = function (c, m, ad, nsec, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "c must be 'm.byteLength + crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(c.byteLength <= 0xffffffff, 'c.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_encrypt(c, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_decrypt = function (m, nsec, c, ad, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "m must be 'c.byteLength - crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(m.byteLength <= 0xffffffff, 'm.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_decrypt(m, c, ad, npub, k)

  if (res < 0) throw new Error('could not verify data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_encrypt_detached = function (
  c,
  mac,
  m,
  ad,
  nsec,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_encrypt_detached(c, mac, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_decrypt_detached = function (
  m,
  nsec,
  c,
  mac,
  ad,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_decrypt_detached(m, c, mac, ad, npub, k)

  if (res !== 0) throw new Error('could not verify data')
}

exports.crypto_aead_chacha20poly1305_ietf_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  binding.crypto_aead_chacha20poly1305_ietf_keygen(k)
}

exports.crypto_aead_chacha20poly1305_ietf_encrypt = function (c, m, ad, nsec, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "c must be 'm.byteLength + crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(c.byteLength <= 0xffffffff, 'c.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_encrypt(c, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_decrypt = function (m, nsec, c, ad, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "m must be 'c.byteLength - crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(m.byteLength <= 0xffffffff, 'm.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_decrypt(m, c, ad, npub, k)

  if (res < 0) throw new Error('could not verify data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_encrypt_detached = function (
  c,
  mac,
  m,
  ad,
  nsec,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_encrypt_detached(c, mac, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_decrypt_detached = function (
  m,
  nsec,
  c,
  mac,
  ad,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_decrypt_detached(m, c, mac, ad, npub, k)

  if (res !== 0) throw new Error('could not verify data')
}

// crypto_stream

exports.crypto_stream_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  binding.crypto_stream_xor_wrap_init(state, n, k)
}

exports.crypto_stream_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_xor_wrap_update(state, c, m)
}

exports.crypto_stream_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_xor_wrap_final(state)
}

exports.crypto_stream_chacha20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  binding.crypto_stream_chacha20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_chacha20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_chacha20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_chacha20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_chacha20_xor_wrap_final(state)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  binding.crypto_stream_chacha20_ietf_xor_wrap_init(state, n, k)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_chacha20_ietf_xor_wrap_update(state, c, m)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_chacha20_ietf_xor_wrap_final(state)
}

exports.crypto_stream_xchacha20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  binding.crypto_stream_xchacha20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_xchacha20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_xchacha20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_xchacha20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_xchacha20_xor_wrap_final(state)
}

exports.crypto_stream_salsa20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  binding.crypto_stream_salsa20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_salsa20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_salsa20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_salsa20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_salsa20_xor_wrap_final(state)
}

// experimental

exports.extension_tweak_ed25519_base = function (n, p, ns) {
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.extension_tweak_ed25519_BYTES,
    "p must be 'extension_tweak_ed25519_BYTES' bytes"
  )

  binding.extension_tweak_ed25519_base(n, p, ns)
}

exports.extension_tweak_ed25519_sign_detached = function (sig, m, scalar, pk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(sig.byteLength === binding.crypto_sign_BYTES, "sig must be 'crypto_sign_BYTES' bytes")
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  if (pk) {
    assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
    assert(
      pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
      "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
    )
  }

  const res = binding.extension_tweak_ed25519_sign_detached(sig, m, scalar, pk)

  if (res !== 0) throw new Error('failed to compute signature')
}

exports.extension_tweak_ed25519_sk_to_scalar = function (n, sk) {
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  binding.extension_tweak_ed25519_sk_to_scalar(n, sk)
}

exports.extension_tweak_ed25519_scalar = function (scalarOut, scalar, ns) {
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_scalar(scalarOut, scalar, ns)
}

exports.extension_tweak_ed25519_pk = function (tpk, pk, ns) {
  assert(ArrayBuffer.isView(tpk), 'tpk must be a typed array')
  assert(
    tpk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "tpk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_pk(tpk, pk, ns)

  if (res !== 0) throw new Error('failed to tweak public key')
}

exports.extension_tweak_ed25519_keypair = function (pk, scalarOut, scalarIn, ns) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.extension_tweak_ed25519_BYTES,
    "pk must be 'extension_tweak_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarIn), 'scalarIn must be a typed array')
  assert(
    scalarIn.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarIn must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_keypair(pk, scalarOut, scalarIn, ns)
}

exports.extension_tweak_ed25519_scalar_add = function (scalarOut, scalar, n) {
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_scalar_add(scalarOut, scalar, n)
}

exports.extension_tweak_ed25519_pk_add = function (tpk, pk, p) {
  assert(ArrayBuffer.isView(tpk), 'tpk must be a typed array')
  assert(
    tpk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "tpk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "p must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_pk_add(tpk, pk, p)

  if (res !== 0) throw new Error('failed to add tweak to public key')
}

exports.extension_tweak_ed25519_keypair_add = function (pk, scalarOut, scalarIn, tweak) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.extension_tweak_ed25519_BYTES,
    "pk must be 'extension_tweak_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarIn), 'scalarIn must be a typed array')
  assert(
    scalarIn.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarIn must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(tweak), 'tweak must be a typed array')
  assert(
    tweak.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "tweak must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_keypair_add(pk, scalarOut, scalarIn, tweak)

  if (res !== 0) throw new Error('failed to add tweak to keypair')
}

exports.extension_pbkdf2_sha512_async = function (out, passwd, salt, iter, outlen, callback) {
  assert(
    iter >= binding.extension_pbkdf2_sha512_ITERATIONS_MIN,
    "iter must be at least 'extension_pbkdf2_sha512_ITERATIONS_MIN'"
  )
  assert(
    outlen <= binding.extension_pbkdf2_sha512_BYTES_MAX,
    "outlen must be at most 'extension_pbkdf2_sha512_BYTES_MAX'"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(out.byteLength >= outlen, "out must be at least 'outlen' bytes")
  assert(out.byteLength > 0, 'out must not be empty')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(salt.byteLength > 0, 'salt must not be empty')

  const [done, promise] = checkStatus(callback)

  binding.extension_pbkdf2_sha512_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    iter,
    outlen,

    done
  )

  return promise
}

exports.extension_pbkdf2_sha512 = function (out, passwd, salt, iter, outlen) {
  assert(
    iter >= binding.extension_pbkdf2_sha512_ITERATIONS_MIN,
    "iter must be at least 'extension_pbkdf2_sha512_ITERATIONS_MIN'"
  )
  assert(
    outlen <= binding.extension_pbkdf2_sha512_BYTES_MAX,
    "outlen must be at most 'extension_pbkdf2_sha512_BYTES_MAX'"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(out.byteLength >= outlen, "out must be at least 'outlen' bytes")
  assert(out.byteLength > 0, 'out must not be empty')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(salt.byteLength > 0, 'salt must not be empty')

  const res = binding.extension_pbkdf2_sha512(out, passwd, salt, iter, outlen)

  if (res !== 0) throw new Error('failed to add tweak to public key')
}

function checkStatus(callback, booleanResult = false) {
  let done, promise

  if (typeof callback === 'function') {
    done = function (status) {
      if (booleanResult) callback(null, status === 0)
      else if (status === 0) callback(null)
      else callback(new Error('status: ' + status))
    }
  } else {
    promise = new Promise(function (resolve, reject) {
      done = function (status) {
        if (booleanResult) resolve(status === 0)
        else if (status === 0) resolve()
        else reject(new Error('status: ' + status))
      }
    })
  }

  return [done, promise]
}
{
  "name": "sodium-native",
  "version": "5.1.0",
  "description": "Low level bindings for libsodium",
  "main": "index.js",
  "files": [
    "index.js",
    "binding.cc",
    "binding.js",
    "extensions",
    "prebuilds",
    "CMakeLists.txt"
  ],
  "imports": {
    "assert": {
      "bare": "bare-assert",
      "node": "assert"
    }
  },
  "addon": true,
  "dependencies": {
    "bare-assert": "^1.2.0",
    "require-addon": "^1.1.0",
    "which-runtime": "^1.2.1"
  },
  "devDependencies": {
    "bare-compat-napi": "^1.3.5",
    "brittle": "^3.16.2",
    "cmake-bare": "^1.6.1",
    "cmake-fetch": "^1.4.3",
    "cmake-napi": "^1.2.1",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "test": "prettier . --check && npm run test:node && npm run test:bare",
    "test:node": "node test/all.js",
    "test:bare": "bare test/all.js"
  },
  "standard": {
    "ignore": [
      "/test/fixtures/*.js"
    ]
  },
  "engines": {
    "bare": ">=1.16.0"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sodium-native.git"
  },
  "contributors": [
    "Emil Bay <github@tixz.dk> (http://bayes.dk)",
    "Mathias Buus <mathiasbuus@gmail.com> (https://mafinto.sh)",
    "Christophe Diederichs <chm-diederichs@hyperdivision.dk>"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/sodium-native/issues"
  },
  "homepage": "https://github.com/holepunchto/sodium-native"
}
const sodium = require('sodium-universal')
const b4a = require('b4a')

const ABYTES = sodium.crypto_secretstream_xchacha20poly1305_ABYTES
const TAG_MESSAGE = sodium.crypto_secretstream_xchacha20poly1305_TAG_MESSAGE
const TAG_FINAL = sodium.crypto_secretstream_xchacha20poly1305_TAG_FINAL
const STATEBYTES = sodium.crypto_secretstream_xchacha20poly1305_STATEBYTES
const HEADERBYTES = sodium.crypto_secretstream_xchacha20poly1305_HEADERBYTES
const KEYBYTES = sodium.crypto_secretstream_xchacha20poly1305_KEYBYTES
const TAG_FINAL_BYTE = b4a.isBuffer(TAG_FINAL) ? TAG_FINAL[0] : TAG_FINAL

const EMPTY = b4a.alloc(0)
const TAG = b4a.alloc(1)

class Push {
  constructor (key, state = b4a.allocUnsafeSlow(STATEBYTES), header = b4a.allocUnsafeSlow(HEADERBYTES)) {
    if (!TAG_FINAL) throw new Error('JavaScript sodium version needs to support crypto_secretstream_xchacha20poly')

    this.key = key
    this.state = state
    this.header = header

    sodium.crypto_secretstream_xchacha20poly1305_init_push(this.state, this.header, this.key)
  }

  next (message, cipher = b4a.allocUnsafe(message.byteLength + ABYTES)) {
    sodium.crypto_secretstream_xchacha20poly1305_push(this.state, cipher, message, null, TAG_MESSAGE)
    return cipher
  }

  final (message = EMPTY, cipher = b4a.allocUnsafe(ABYTES)) {
    sodium.crypto_secretstream_xchacha20poly1305_push(this.state, cipher, message, null, TAG_FINAL)
    return cipher
  }
}

class Pull {
  constructor (key, state = b4a.allocUnsafeSlow(STATEBYTES)) {
    if (!TAG_FINAL) throw new Error('JavaScript sodium version needs to support crypto_secretstream_xchacha20poly')

    this.key = key
    this.state = state
    this.final = false
  }

  init (header) {
    sodium.crypto_secretstream_xchacha20poly1305_init_pull(this.state, header, this.key)
  }

  next (cipher, message = b4a.allocUnsafe(cipher.byteLength - ABYTES)) {
    sodium.crypto_secretstream_xchacha20poly1305_pull(this.state, message, TAG, cipher, null)
    this.final = TAG[0] === TAG_FINAL_BYTE
    return message
  }
}

function keygen (buf = b4a.alloc(KEYBYTES)) {
  sodium.crypto_secretstream_xchacha20poly1305_keygen(buf)
  return buf
}

module.exports = {
  keygen,
  KEYBYTES,
  ABYTES,
  STATEBYTES,
  HEADERBYTES,
  Push,
  Pull
}
{
  "name": "sodium-secretstream",
  "version": "1.2.0",
  "description": "Wraps libsodiums secretstream in a higher level abstraction",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.1.1",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "standard": "^17.0.0"
  },
  "scripts": {
    "test": "standard"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/sodium-secretstream.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/sodium-secretstream/issues"
  },
  "homepage": "https://github.com/mafintosh/sodium-secretstream"
}
module.exports = require('sodium-native')
{
  "name": "sodium-universal",
  "version": "5.0.1",
  "description": "Universal wrapper for sodium-javascript and sodium-native working in Node.js and the Browser",
  "main": "index.js",
  "dependencies": {
    "sodium-native": "^5.0.1"
  },
  "peerDependencies": {
    "sodium-javascript": "~0.8.0"
  },
  "peerDependenciesMeta": {
    "sodium-javascript": {
      "optional": true
    }
  },
  "scripts": {
    "prepublish": "./build-scripts/generate.js"
  },
  "browser": {
    "sodium-native": "sodium-javascript"
  },
  "browserify": {
    "transform": [
      "./build-scripts/transform.js"
    ]
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sodium-universal.git"
  },
  "keywords": [
    "libsodium",
    "sodium",
    "sodium-native",
    "sodium-javascript",
    "browserify"
  ],
  "contributors": [
    "Emil Bay <github@tixz.dk> (http://bayes.dk)",
    "Mathias Buus <mathiasbuus@gmail.com> (https://mafinto.sh)",
    "Christophe Diederichs <chm-diederichs@hyperdivision.dk>"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/sodium-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/sodium-universal#readme"
}
const { EventEmitter } = require('events-universal')
const STREAM_DESTROYED = new Error('Stream was destroyed')
const PREMATURE_CLOSE = new Error('Premature close')

const FIFO = require('fast-fifo')
const TextDecoder = require('text-decoder')

// if we do a future major, expect queue microtask to be there always, for now a bit defensive
const qmt =
  typeof queueMicrotask === 'undefined' ? (fn) => global.process.nextTick(fn) : queueMicrotask

// 29 bits used total (4 from shared, 14 from read, and 11 from write)
const MAX = (1 << 29) - 1

// Shared state
const OPENING = 0b0001
const PREDESTROYING = 0b0010
const DESTROYING = 0b0100
const DESTROYED = 0b1000

const NOT_OPENING = MAX ^ OPENING
const NOT_PREDESTROYING = MAX ^ PREDESTROYING

// Read state (4 bit offset from shared state)
const READ_ACTIVE = 0b00000000000001 << 4
const READ_UPDATING = 0b00000000000010 << 4
const READ_PRIMARY = 0b00000000000100 << 4
const READ_QUEUED = 0b00000000001000 << 4
const READ_RESUMED = 0b00000000010000 << 4
const READ_PIPE_DRAINED = 0b00000000100000 << 4
const READ_ENDING = 0b00000001000000 << 4
const READ_EMIT_DATA = 0b00000010000000 << 4
const READ_EMIT_READABLE = 0b00000100000000 << 4
const READ_EMITTED_READABLE = 0b00001000000000 << 4
const READ_DONE = 0b00010000000000 << 4
const READ_NEXT_TICK = 0b00100000000000 << 4
const READ_NEEDS_PUSH = 0b01000000000000 << 4
const READ_READ_AHEAD = 0b10000000000000 << 4

// Combined read state
const READ_FLOWING = READ_RESUMED | READ_PIPE_DRAINED
const READ_ACTIVE_AND_NEEDS_PUSH = READ_ACTIVE | READ_NEEDS_PUSH
const READ_PRIMARY_AND_ACTIVE = READ_PRIMARY | READ_ACTIVE
const READ_EMIT_READABLE_AND_QUEUED = READ_EMIT_READABLE | READ_QUEUED
const READ_RESUMED_READ_AHEAD = READ_RESUMED | READ_READ_AHEAD

const READ_NOT_ACTIVE = MAX ^ READ_ACTIVE
const READ_NON_PRIMARY = MAX ^ READ_PRIMARY
const READ_NON_PRIMARY_AND_PUSHED = MAX ^ (READ_PRIMARY | READ_NEEDS_PUSH)
const READ_PUSHED = MAX ^ READ_NEEDS_PUSH
const READ_PAUSED = MAX ^ READ_RESUMED
const READ_NOT_QUEUED = MAX ^ (READ_QUEUED | READ_EMITTED_READABLE)
const READ_NOT_ENDING = MAX ^ READ_ENDING
const READ_PIPE_NOT_DRAINED = MAX ^ READ_FLOWING
const READ_NOT_NEXT_TICK = MAX ^ READ_NEXT_TICK
const READ_NOT_UPDATING = MAX ^ READ_UPDATING
const READ_NO_READ_AHEAD = MAX ^ READ_READ_AHEAD
const READ_PAUSED_NO_READ_AHEAD = MAX ^ READ_RESUMED_READ_AHEAD

// Write state (18 bit offset, 4 bit offset from shared state and 14 from read state)
const WRITE_ACTIVE = 0b00000000001 << 18
const WRITE_UPDATING = 0b00000000010 << 18
const WRITE_PRIMARY = 0b00000000100 << 18
const WRITE_QUEUED = 0b00000001000 << 18
const WRITE_UNDRAINED = 0b00000010000 << 18
const WRITE_DONE = 0b00000100000 << 18
const WRITE_EMIT_DRAIN = 0b00001000000 << 18
const WRITE_NEXT_TICK = 0b00010000000 << 18
const WRITE_WRITING = 0b00100000000 << 18
const WRITE_FINISHING = 0b01000000000 << 18
const WRITE_CORKED = 0b10000000000 << 18

const WRITE_NOT_ACTIVE = MAX ^ (WRITE_ACTIVE | WRITE_WRITING)
const WRITE_NON_PRIMARY = MAX ^ WRITE_PRIMARY
const WRITE_NOT_FINISHING = MAX ^ (WRITE_ACTIVE | WRITE_FINISHING)
const WRITE_DRAINED = MAX ^ WRITE_UNDRAINED
const WRITE_NOT_QUEUED = MAX ^ WRITE_QUEUED
const WRITE_NOT_NEXT_TICK = MAX ^ WRITE_NEXT_TICK
const WRITE_NOT_UPDATING = MAX ^ WRITE_UPDATING
const WRITE_NOT_CORKED = MAX ^ WRITE_CORKED

// Combined shared state
const ACTIVE = READ_ACTIVE | WRITE_ACTIVE
const NOT_ACTIVE = MAX ^ ACTIVE
const DONE = READ_DONE | WRITE_DONE
const DESTROY_STATUS = DESTROYING | DESTROYED | PREDESTROYING
const OPEN_STATUS = DESTROY_STATUS | OPENING
const AUTO_DESTROY = DESTROY_STATUS | DONE
const NON_PRIMARY = WRITE_NON_PRIMARY & READ_NON_PRIMARY
const ACTIVE_OR_TICKING = WRITE_NEXT_TICK | READ_NEXT_TICK
const TICKING = ACTIVE_OR_TICKING & NOT_ACTIVE
const IS_OPENING = OPEN_STATUS | TICKING

// Combined shared state and read state
const READ_PRIMARY_STATUS = OPEN_STATUS | READ_ENDING | READ_DONE
const READ_STATUS = OPEN_STATUS | READ_DONE | READ_QUEUED
const READ_ENDING_STATUS = OPEN_STATUS | READ_ENDING | READ_QUEUED
const READ_READABLE_STATUS = OPEN_STATUS | READ_EMIT_READABLE | READ_QUEUED | READ_EMITTED_READABLE
const SHOULD_NOT_READ =
  OPEN_STATUS | READ_ACTIVE | READ_ENDING | READ_DONE | READ_NEEDS_PUSH | READ_READ_AHEAD
const READ_BACKPRESSURE_STATUS = DESTROY_STATUS | READ_ENDING | READ_DONE
const READ_UPDATE_SYNC_STATUS = READ_UPDATING | OPEN_STATUS | READ_NEXT_TICK | READ_PRIMARY
const READ_NEXT_TICK_OR_OPENING = READ_NEXT_TICK | OPENING

// Combined write state
const WRITE_PRIMARY_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_DONE
const WRITE_QUEUED_AND_UNDRAINED = WRITE_QUEUED | WRITE_UNDRAINED
const WRITE_QUEUED_AND_ACTIVE = WRITE_QUEUED | WRITE_ACTIVE
const WRITE_DRAIN_STATUS = WRITE_QUEUED | WRITE_UNDRAINED | OPEN_STATUS | WRITE_ACTIVE
const WRITE_STATUS = OPEN_STATUS | WRITE_ACTIVE | WRITE_QUEUED | WRITE_CORKED
const WRITE_PRIMARY_AND_ACTIVE = WRITE_PRIMARY | WRITE_ACTIVE
const WRITE_ACTIVE_AND_WRITING = WRITE_ACTIVE | WRITE_WRITING
const WRITE_FINISHING_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_QUEUED_AND_ACTIVE | WRITE_DONE
const WRITE_BACKPRESSURE_STATUS = WRITE_UNDRAINED | DESTROY_STATUS | WRITE_FINISHING | WRITE_DONE
const WRITE_UPDATE_SYNC_STATUS = WRITE_UPDATING | OPEN_STATUS | WRITE_NEXT_TICK | WRITE_PRIMARY
const WRITE_DROP_DATA = WRITE_FINISHING | WRITE_DONE | DESTROY_STATUS

const asyncIterator = Symbol.asyncIterator || Symbol('asyncIterator')

class WritableState {
  constructor(
    stream,
    { highWaterMark = 16384, map = null, mapWritable, byteLength, byteLengthWritable } = {}
  ) {
    this.stream = stream
    this.queue = new FIFO()
    this.highWaterMark = highWaterMark
    this.buffered = 0
    this.error = null
    this.pipeline = null
    this.drains = null // if we add more seldomly used helpers we might them into a subobject so its a single ptr
    this.byteLength = byteLengthWritable || byteLength || defaultByteLength
    this.map = mapWritable || map
    this.afterWrite = afterWrite.bind(this)
    this.afterUpdateNextTick = updateWriteNT.bind(this)
  }

  get ending() {
    return (this.stream._duplexState & WRITE_FINISHING) !== 0
  }

  get ended() {
    return (this.stream._duplexState & WRITE_DONE) !== 0
  }

  push(data) {
    if ((this.stream._duplexState & WRITE_DROP_DATA) !== 0) return false
    if (this.map !== null) data = this.map(data)

    this.buffered += this.byteLength(data)
    this.queue.push(data)

    if (this.buffered < this.highWaterMark) {
      this.stream._duplexState |= WRITE_QUEUED
      return true
    }

    this.stream._duplexState |= WRITE_QUEUED_AND_UNDRAINED
    return false
  }

  shift() {
    const data = this.queue.shift()

    this.buffered -= this.byteLength(data)
    if (this.buffered === 0) this.stream._duplexState &= WRITE_NOT_QUEUED

    return data
  }

  end(data) {
    if (typeof data === 'function') this.stream.once('finish', data)
    else if (data !== undefined && data !== null) this.push(data)
    this.stream._duplexState = (this.stream._duplexState | WRITE_FINISHING) & WRITE_NON_PRIMARY
  }

  autoBatch(data, cb) {
    const buffer = []
    const stream = this.stream

    buffer.push(data)
    while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED_AND_ACTIVE) {
      buffer.push(stream._writableState.shift())
    }

    if ((stream._duplexState & OPEN_STATUS) !== 0) return cb(null)
    stream._writev(buffer, cb)
  }

  update() {
    const stream = this.stream

    stream._duplexState |= WRITE_UPDATING

    do {
      while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED) {
        const data = this.shift()
        stream._duplexState |= WRITE_ACTIVE_AND_WRITING
        stream._write(data, this.afterWrite)
      }

      if ((stream._duplexState & WRITE_PRIMARY_AND_ACTIVE) === 0) this.updateNonPrimary()
    } while (this.continueUpdate() === true)

    stream._duplexState &= WRITE_NOT_UPDATING
  }

  updateNonPrimary() {
    const stream = this.stream

    if ((stream._duplexState & WRITE_FINISHING_STATUS) === WRITE_FINISHING) {
      stream._duplexState = stream._duplexState | WRITE_ACTIVE
      stream._final(afterFinal.bind(this))
      return
    }

    if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
      if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
        stream._duplexState |= ACTIVE
        stream._destroy(afterDestroy.bind(this))
      }
      return
    }

    if ((stream._duplexState & IS_OPENING) === OPENING) {
      stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING
      stream._open(afterOpen.bind(this))
    }
  }

  continueUpdate() {
    if ((this.stream._duplexState & WRITE_NEXT_TICK) === 0) return false
    this.stream._duplexState &= WRITE_NOT_NEXT_TICK
    return true
  }

  updateCallback() {
    if ((this.stream._duplexState & WRITE_UPDATE_SYNC_STATUS) === WRITE_PRIMARY) this.update()
    else this.updateNextTick()
  }

  updateNextTick() {
    if ((this.stream._duplexState & WRITE_NEXT_TICK) !== 0) return
    this.stream._duplexState |= WRITE_NEXT_TICK
    if ((this.stream._duplexState & WRITE_UPDATING) === 0) qmt(this.afterUpdateNextTick)
  }
}

class ReadableState {
  constructor(
    stream,
    { highWaterMark = 16384, map = null, mapReadable, byteLength, byteLengthReadable } = {}
  ) {
    this.stream = stream
    this.queue = new FIFO()
    this.highWaterMark = highWaterMark === 0 ? 1 : highWaterMark
    this.buffered = 0
    this.readAhead = highWaterMark > 0
    this.error = null
    this.pipeline = null
    this.byteLength = byteLengthReadable || byteLength || defaultByteLength
    this.map = mapReadable || map
    this.pipeTo = null
    this.afterRead = afterRead.bind(this)
    this.afterUpdateNextTick = updateReadNT.bind(this)
  }

  get ending() {
    return (this.stream._duplexState & READ_ENDING) !== 0
  }

  get ended() {
    return (this.stream._duplexState & READ_DONE) !== 0
  }

  pipe(pipeTo, cb) {
    if (this.pipeTo !== null) throw new Error('Can only pipe to one destination')
    if (typeof cb !== 'function') cb = null

    this.stream._duplexState |= READ_PIPE_DRAINED
    this.pipeTo = pipeTo
    this.pipeline = new Pipeline(this.stream, pipeTo, cb)

    if (cb) this.stream.on('error', noop) // We already error handle this so supress crashes

    if (isStreamx(pipeTo)) {
      pipeTo._writableState.pipeline = this.pipeline
      if (cb) pipeTo.on('error', noop) // We already error handle this so supress crashes
      pipeTo.on('finish', this.pipeline.finished.bind(this.pipeline)) // TODO: just call finished from pipeTo itself
    } else {
      const onerror = this.pipeline.done.bind(this.pipeline, pipeTo)
      const onclose = this.pipeline.done.bind(this.pipeline, pipeTo, null) // onclose has a weird bool arg
      pipeTo.on('error', onerror)
      pipeTo.on('close', onclose)
      pipeTo.on('finish', this.pipeline.finished.bind(this.pipeline))
    }

    pipeTo.on('drain', afterDrain.bind(this))
    this.stream.emit('piping', pipeTo)
    pipeTo.emit('pipe', this.stream)
  }

  push(data) {
    const stream = this.stream

    if (data === null) {
      this.highWaterMark = 0
      stream._duplexState = (stream._duplexState | READ_ENDING) & READ_NON_PRIMARY_AND_PUSHED
      return false
    }

    if (this.map !== null) {
      data = this.map(data)
      if (data === null) {
        stream._duplexState &= READ_PUSHED
        return this.buffered < this.highWaterMark
      }
    }

    this.buffered += this.byteLength(data)
    this.queue.push(data)

    stream._duplexState = (stream._duplexState | READ_QUEUED) & READ_PUSHED

    return this.buffered < this.highWaterMark
  }

  shift() {
    const data = this.queue.shift()

    this.buffered -= this.byteLength(data)
    if (this.buffered === 0) this.stream._duplexState &= READ_NOT_QUEUED
    return data
  }

  unshift(data) {
    const pending = [this.map !== null ? this.map(data) : data]
    while (this.buffered > 0) pending.push(this.shift())

    for (let i = 0; i < pending.length - 1; i++) {
      const data = pending[i]
      this.buffered += this.byteLength(data)
      this.queue.push(data)
    }

    this.push(pending[pending.length - 1])
  }

  read() {
    const stream = this.stream

    if ((stream._duplexState & READ_STATUS) === READ_QUEUED) {
      const data = this.shift()
      if (this.pipeTo !== null && this.pipeTo.write(data) === false)
        stream._duplexState &= READ_PIPE_NOT_DRAINED
      if ((stream._duplexState & READ_EMIT_DATA) !== 0) stream.emit('data', data)
      return data
    }

    if (this.readAhead === false) {
      stream._duplexState |= READ_READ_AHEAD
      this.updateNextTick()
    }

    return null
  }

  drain() {
    const stream = this.stream

    while (
      (stream._duplexState & READ_STATUS) === READ_QUEUED &&
      (stream._duplexState & READ_FLOWING) !== 0
    ) {
      const data = this.shift()
      if (this.pipeTo !== null && this.pipeTo.write(data) === false)
        stream._duplexState &= READ_PIPE_NOT_DRAINED
      if ((stream._duplexState & READ_EMIT_DATA) !== 0) stream.emit('data', data)
    }
  }

  update() {
    const stream = this.stream

    stream._duplexState |= READ_UPDATING

    do {
      this.drain()

      while (
        this.buffered < this.highWaterMark &&
        (stream._duplexState & SHOULD_NOT_READ) === READ_READ_AHEAD
      ) {
        stream._duplexState |= READ_ACTIVE_AND_NEEDS_PUSH
        stream._read(this.afterRead)
        this.drain()
      }

      if ((stream._duplexState & READ_READABLE_STATUS) === READ_EMIT_READABLE_AND_QUEUED) {
        stream._duplexState |= READ_EMITTED_READABLE
        stream.emit('readable')
      }

      if ((stream._duplexState & READ_PRIMARY_AND_ACTIVE) === 0) this.updateNonPrimary()
    } while (this.continueUpdate() === true)

    stream._duplexState &= READ_NOT_UPDATING
  }

  updateNonPrimary() {
    const stream = this.stream

    if ((stream._duplexState & READ_ENDING_STATUS) === READ_ENDING) {
      stream._duplexState = (stream._duplexState | READ_DONE) & READ_NOT_ENDING
      stream.emit('end')
      if ((stream._duplexState & AUTO_DESTROY) === DONE) stream._duplexState |= DESTROYING
      if (this.pipeTo !== null) this.pipeTo.end()
    }

    if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
      if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
        stream._duplexState |= ACTIVE
        stream._destroy(afterDestroy.bind(this))
      }
      return
    }

    if ((stream._duplexState & IS_OPENING) === OPENING) {
      stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING
      stream._open(afterOpen.bind(this))
    }
  }

  continueUpdate() {
    if ((this.stream._duplexState & READ_NEXT_TICK) === 0) return false
    this.stream._duplexState &= READ_NOT_NEXT_TICK
    return true
  }

  updateCallback() {
    if ((this.stream._duplexState & READ_UPDATE_SYNC_STATUS) === READ_PRIMARY) this.update()
    else this.updateNextTick()
  }

  updateNextTickIfOpen() {
    if ((this.stream._duplexState & READ_NEXT_TICK_OR_OPENING) !== 0) return
    this.stream._duplexState |= READ_NEXT_TICK
    if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick)
  }

  updateNextTick() {
    if ((this.stream._duplexState & READ_NEXT_TICK) !== 0) return
    this.stream._duplexState |= READ_NEXT_TICK
    if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick)
  }
}

class TransformState {
  constructor(stream) {
    this.data = null
    this.afterTransform = afterTransform.bind(stream)
    this.afterFinal = null
  }
}

class Pipeline {
  constructor(src, dst, cb) {
    this.from = src
    this.to = dst
    this.afterPipe = cb
    this.error = null
    this.pipeToFinished = false
  }

  finished() {
    this.pipeToFinished = true
  }

  done(stream, err) {
    if (err) this.error = err

    if (stream === this.to) {
      this.to = null

      if (this.from !== null) {
        if ((this.from._duplexState & READ_DONE) === 0 || !this.pipeToFinished) {
          this.from.destroy(this.error || new Error('Writable stream closed prematurely'))
        }
        return
      }
    }

    if (stream === this.from) {
      this.from = null

      if (this.to !== null) {
        if ((stream._duplexState & READ_DONE) === 0) {
          this.to.destroy(this.error || new Error('Readable stream closed before ending'))
        }
        return
      }
    }

    if (this.afterPipe !== null) this.afterPipe(this.error)
    this.to = this.from = this.afterPipe = null
  }
}

function afterDrain() {
  this.stream._duplexState |= READ_PIPE_DRAINED
  this.updateCallback()
}

function afterFinal(err) {
  const stream = this.stream
  if (err) stream.destroy(err)
  if ((stream._duplexState & DESTROY_STATUS) === 0) {
    stream._duplexState |= WRITE_DONE
    stream.emit('finish')
  }
  if ((stream._duplexState & AUTO_DESTROY) === DONE) {
    stream._duplexState |= DESTROYING
  }

  stream._duplexState &= WRITE_NOT_FINISHING

  // no need to wait the extra tick here, so we short circuit that
  if ((stream._duplexState & WRITE_UPDATING) === 0) this.update()
  else this.updateNextTick()
}

function afterDestroy(err) {
  const stream = this.stream

  if (!err && this.error !== STREAM_DESTROYED) err = this.error
  if (err) stream.emit('error', err)
  stream._duplexState |= DESTROYED
  stream.emit('close')

  const rs = stream._readableState
  const ws = stream._writableState

  if (rs !== null && rs.pipeline !== null) rs.pipeline.done(stream, err)

  if (ws !== null) {
    while (ws.drains !== null && ws.drains.length > 0) ws.drains.shift().resolve(false)
    if (ws.pipeline !== null) ws.pipeline.done(stream, err)
  }
}

function afterWrite(err) {
  const stream = this.stream

  if (err) stream.destroy(err)
  stream._duplexState &= WRITE_NOT_ACTIVE

  if (this.drains !== null) tickDrains(this.drains)

  if ((stream._duplexState & WRITE_DRAIN_STATUS) === WRITE_UNDRAINED) {
    stream._duplexState &= WRITE_DRAINED
    if ((stream._duplexState & WRITE_EMIT_DRAIN) === WRITE_EMIT_DRAIN) {
      stream.emit('drain')
    }
  }

  this.updateCallback()
}

function afterRead(err) {
  if (err) this.stream.destroy(err)
  this.stream._duplexState &= READ_NOT_ACTIVE
  if (this.readAhead === false && (this.stream._duplexState & READ_RESUMED) === 0)
    this.stream._duplexState &= READ_NO_READ_AHEAD
  this.updateCallback()
}

function updateReadNT() {
  if ((this.stream._duplexState & READ_UPDATING) === 0) {
    this.stream._duplexState &= READ_NOT_NEXT_TICK
    this.update()
  }
}

function updateWriteNT() {
  if ((this.stream._duplexState & WRITE_UPDATING) === 0) {
    this.stream._duplexState &= WRITE_NOT_NEXT_TICK
    this.update()
  }
}

function tickDrains(drains) {
  for (let i = 0; i < drains.length; i++) {
    // drains.writes are monotonic, so if one is 0 its always the first one
    if (--drains[i].writes === 0) {
      drains.shift().resolve(true)
      i--
    }
  }
}

function afterOpen(err) {
  const stream = this.stream

  if (err) stream.destroy(err)

  if ((stream._duplexState & DESTROYING) === 0) {
    if ((stream._duplexState & READ_PRIMARY_STATUS) === 0) stream._duplexState |= READ_PRIMARY
    if ((stream._duplexState & WRITE_PRIMARY_STATUS) === 0) stream._duplexState |= WRITE_PRIMARY
    stream.emit('open')
  }

  stream._duplexState &= NOT_ACTIVE

  if (stream._writableState !== null) {
    stream._writableState.updateCallback()
  }

  if (stream._readableState !== null) {
    stream._readableState.updateCallback()
  }
}

function afterTransform(err, data) {
  if (data !== undefined && data !== null) this.push(data)
  this._writableState.afterWrite(err)
}

function newListener(name) {
  if (this._readableState !== null) {
    if (name === 'data') {
      this._duplexState |= READ_EMIT_DATA | READ_RESUMED_READ_AHEAD
      this._readableState.updateNextTick()
    }
    if (name === 'readable') {
      this._duplexState |= READ_EMIT_READABLE
      this._readableState.updateNextTick()
    }
  }

  if (this._writableState !== null) {
    if (name === 'drain') {
      this._duplexState |= WRITE_EMIT_DRAIN
      this._writableState.updateNextTick()
    }
  }
}

class Stream extends EventEmitter {
  constructor(opts) {
    super()

    this._duplexState = 0
    this._readableState = null
    this._writableState = null

    if (opts) {
      if (opts.open) this._open = opts.open
      if (opts.destroy) this._destroy = opts.destroy
      if (opts.predestroy) this._predestroy = opts.predestroy
      if (opts.signal) {
        opts.signal.addEventListener('abort', abort.bind(this))
      }
    }

    this.on('newListener', newListener)
  }

  _open(cb) {
    cb(null)
  }

  _destroy(cb) {
    cb(null)
  }

  _predestroy() {
    // does nothing
  }

  get readable() {
    return this._readableState !== null ? true : undefined
  }

  get writable() {
    return this._writableState !== null ? true : undefined
  }

  get destroyed() {
    return (this._duplexState & DESTROYED) !== 0
  }

  get destroying() {
    return (this._duplexState & DESTROY_STATUS) !== 0
  }

  destroy(err) {
    if ((this._duplexState & DESTROY_STATUS) === 0) {
      if (!err) err = STREAM_DESTROYED
      this._duplexState = (this._duplexState | DESTROYING) & NON_PRIMARY

      if (this._readableState !== null) {
        this._readableState.highWaterMark = 0
        this._readableState.error = err
      }
      if (this._writableState !== null) {
        this._writableState.highWaterMark = 0
        this._writableState.error = err
      }

      this._duplexState |= PREDESTROYING
      this._predestroy()
      this._duplexState &= NOT_PREDESTROYING

      if (this._readableState !== null) this._readableState.updateNextTick()
      if (this._writableState !== null) this._writableState.updateNextTick()
    }
  }
}

class Readable extends Stream {
  constructor(opts) {
    super(opts)

    this._duplexState |= OPENING | WRITE_DONE | READ_READ_AHEAD
    this._readableState = new ReadableState(this, opts)

    if (opts) {
      if (this._readableState.readAhead === false) this._duplexState &= READ_NO_READ_AHEAD
      if (opts.read) this._read = opts.read
      if (opts.eagerOpen) this._readableState.updateNextTick()
      if (opts.encoding) this.setEncoding(opts.encoding)
    }
  }

  setEncoding(encoding) {
    const dec = new TextDecoder(encoding)
    const map = this._readableState.map || echo
    this._readableState.map = mapOrSkip
    return this

    function mapOrSkip(data) {
      const next = dec.push(data)
      return next === '' && (data.byteLength !== 0 || dec.remaining > 0) ? null : map(next)
    }
  }

  _read(cb) {
    cb(null)
  }

  pipe(dest, cb) {
    this._readableState.updateNextTick()
    this._readableState.pipe(dest, cb)
    return dest
  }

  read() {
    this._readableState.updateNextTick()
    return this._readableState.read()
  }

  push(data) {
    this._readableState.updateNextTickIfOpen()
    return this._readableState.push(data)
  }

  unshift(data) {
    this._readableState.updateNextTickIfOpen()
    return this._readableState.unshift(data)
  }

  resume() {
    this._duplexState |= READ_RESUMED_READ_AHEAD
    this._readableState.updateNextTick()
    return this
  }

  pause() {
    this._duplexState &=
      this._readableState.readAhead === false ? READ_PAUSED_NO_READ_AHEAD : READ_PAUSED
    return this
  }

  static _fromAsyncIterator(ite, opts) {
    let destroy

    const rs = new Readable({
      ...opts,
      read(cb) {
        ite.next().then(push).then(cb.bind(null, null)).catch(cb)
      },
      predestroy() {
        destroy = ite.return()
      },
      destroy(cb) {
        if (!destroy) return cb(null)
        destroy.then(cb.bind(null, null)).catch(cb)
      }
    })

    return rs

    function push(data) {
      if (data.done) rs.push(null)
      else rs.push(data.value)
    }
  }

  static from(data, opts) {
    if (isReadStreamx(data)) return data
    if (data[asyncIterator]) return this._fromAsyncIterator(data[asyncIterator](), opts)
    if (!Array.isArray(data)) data = data === undefined ? [] : [data]

    let i = 0
    return new Readable({
      ...opts,
      read(cb) {
        this.push(i === data.length ? null : data[i++])
        cb(null)
      }
    })
  }

  static isBackpressured(rs) {
    return (
      (rs._duplexState & READ_BACKPRESSURE_STATUS) !== 0 ||
      rs._readableState.buffered >= rs._readableState.highWaterMark
    )
  }

  static isPaused(rs) {
    return (rs._duplexState & READ_RESUMED) === 0
  }

  [asyncIterator]() {
    const stream = this

    let error = null
    let promiseResolve = null
    let promiseReject = null

    this.on('error', (err) => {
      error = err
    })
    this.on('readable', onreadable)
    this.on('close', onclose)

    return {
      [asyncIterator]() {
        return this
      },
      next() {
        return new Promise(function (resolve, reject) {
          promiseResolve = resolve
          promiseReject = reject
          const data = stream.read()
          if (data !== null) ondata(data)
          else if ((stream._duplexState & DESTROYED) !== 0) ondata(null)
        })
      },
      return() {
        return destroy(null)
      },
      throw(err) {
        return destroy(err)
      }
    }

    function onreadable() {
      if (promiseResolve !== null) ondata(stream.read())
    }

    function onclose() {
      if (promiseResolve !== null) ondata(null)
    }

    function ondata(data) {
      if (promiseReject === null) return
      if (error) promiseReject(error)
      else if (data === null && (stream._duplexState & READ_DONE) === 0)
        promiseReject(STREAM_DESTROYED)
      else promiseResolve({ value: data, done: data === null })
      promiseReject = promiseResolve = null
    }

    function destroy(err) {
      stream.destroy(err)
      return new Promise((resolve, reject) => {
        if (stream._duplexState & DESTROYED) return resolve({ value: undefined, done: true })
        stream.once('close', function () {
          if (err) reject(err)
          else resolve({ value: undefined, done: true })
        })
      })
    }
  }
}

class Writable extends Stream {
  constructor(opts) {
    super(opts)

    this._duplexState |= OPENING | READ_DONE
    this._writableState = new WritableState(this, opts)

    if (opts) {
      if (opts.writev) this._writev = opts.writev
      if (opts.write) this._write = opts.write
      if (opts.final) this._final = opts.final
      if (opts.eagerOpen) this._writableState.updateNextTick()
    }
  }

  cork() {
    this._duplexState |= WRITE_CORKED
  }

  uncork() {
    this._duplexState &= WRITE_NOT_CORKED
    this._writableState.updateNextTick()
  }

  _writev(batch, cb) {
    cb(null)
  }

  _write(data, cb) {
    this._writableState.autoBatch(data, cb)
  }

  _final(cb) {
    cb(null)
  }

  static isBackpressured(ws) {
    return (ws._duplexState & WRITE_BACKPRESSURE_STATUS) !== 0
  }

  static drained(ws) {
    if (ws.destroyed) return Promise.resolve(false)
    const state = ws._writableState
    const pending = isWritev(ws) ? Math.min(1, state.queue.length) : state.queue.length
    const writes = pending + (ws._duplexState & WRITE_WRITING ? 1 : 0)
    if (writes === 0) return Promise.resolve(true)
    if (state.drains === null) state.drains = []
    return new Promise((resolve) => {
      state.drains.push({ writes, resolve })
    })
  }

  write(data) {
    this._writableState.updateNextTick()
    return this._writableState.push(data)
  }

  end(data) {
    this._writableState.updateNextTick()
    this._writableState.end(data)
    return this
  }
}

class Duplex extends Readable {
  // and Writable
  constructor(opts) {
    super(opts)

    this._duplexState = OPENING | (this._duplexState & READ_READ_AHEAD)
    this._writableState = new WritableState(this, opts)

    if (opts) {
      if (opts.writev) this._writev = opts.writev
      if (opts.write) this._write = opts.write
      if (opts.final) this._final = opts.final
    }
  }

  cork() {
    this._duplexState |= WRITE_CORKED
  }

  uncork() {
    this._duplexState &= WRITE_NOT_CORKED
    this._writableState.updateNextTick()
  }

  _writev(batch, cb) {
    cb(null)
  }

  _write(data, cb) {
    this._writableState.autoBatch(data, cb)
  }

  _final(cb) {
    cb(null)
  }

  write(data) {
    this._writableState.updateNextTick()
    return this._writableState.push(data)
  }

  end(data) {
    this._writableState.updateNextTick()
    this._writableState.end(data)
    return this
  }
}

class Transform extends Duplex {
  constructor(opts) {
    super(opts)
    this._transformState = new TransformState(this)

    if (opts) {
      if (opts.transform) this._transform = opts.transform
      if (opts.flush) this._flush = opts.flush
    }
  }

  _write(data, cb) {
    if (this._readableState.buffered >= this._readableState.highWaterMark) {
      this._transformState.data = data
    } else {
      this._transform(data, this._transformState.afterTransform)
    }
  }

  _read(cb) {
    if (this._transformState.data !== null) {
      const data = this._transformState.data
      this._transformState.data = null
      cb(null)
      this._transform(data, this._transformState.afterTransform)
    } else {
      cb(null)
    }
  }

  destroy(err) {
    super.destroy(err)
    if (this._transformState.data !== null) {
      this._transformState.data = null
      this._transformState.afterTransform()
    }
  }

  _transform(data, cb) {
    cb(null, data)
  }

  _flush(cb) {
    cb(null)
  }

  _final(cb) {
    this._transformState.afterFinal = cb
    this._flush(transformAfterFlush.bind(this))
  }
}

class PassThrough extends Transform {}

function transformAfterFlush(err, data) {
  const cb = this._transformState.afterFinal
  if (err) return cb(err)
  if (data !== null && data !== undefined) this.push(data)
  this.push(null)
  cb(null)
}

function pipelinePromise(...streams) {
  return new Promise((resolve, reject) => {
    return pipeline(...streams, (err) => {
      if (err) return reject(err)
      resolve()
    })
  })
}

function pipeline(stream, ...streams) {
  const all = Array.isArray(stream) ? [...stream, ...streams] : [stream, ...streams]
  const done = all.length && typeof all[all.length - 1] === 'function' ? all.pop() : null

  if (all.length < 2) throw new Error('Pipeline requires at least 2 streams')

  let src = all[0]
  let dest = null
  let error = null

  for (let i = 1; i < all.length; i++) {
    dest = all[i]

    if (isStreamx(src)) {
      src.pipe(dest, onerror)
    } else {
      errorHandle(src, true, i > 1, onerror)
      src.pipe(dest)
    }

    src = dest
  }

  if (done) {
    let fin = false

    const autoDestroy =
      isStreamx(dest) || !!(dest._writableState && dest._writableState.autoDestroy)

    dest.on('error', (err) => {
      if (error === null) error = err
    })

    dest.on('finish', () => {
      fin = true
      if (!autoDestroy) done(error)
    })

    if (autoDestroy) {
      dest.on('close', () => done(error || (fin ? null : PREMATURE_CLOSE)))
    }
  }

  return dest

  function errorHandle(s, rd, wr, onerror) {
    s.on('error', onerror)
    s.on('close', onclose)

    function onclose() {
      if (rd && s._readableState && !s._readableState.ended) return onerror(PREMATURE_CLOSE)
      if (wr && s._writableState && !s._writableState.ended) return onerror(PREMATURE_CLOSE)
    }
  }

  function onerror(err) {
    if (!err || error) return
    error = err

    for (const s of all) {
      s.destroy(err)
    }
  }
}

function echo(s) {
  return s
}

function isStream(stream) {
  return !!stream._readableState || !!stream._writableState
}

function isStreamx(stream) {
  return typeof stream._duplexState === 'number' && isStream(stream)
}

function isEnding(stream) {
  return !!stream._readableState && stream._readableState.ending
}

function isEnded(stream) {
  return !!stream._readableState && stream._readableState.ended
}

function isFinishing(stream) {
  return !!stream._writableState && stream._writableState.ending
}

function isFinished(stream) {
  return !!stream._writableState && stream._writableState.ended
}

function getStreamError(stream, opts = {}) {
  const err =
    (stream._readableState && stream._readableState.error) ||
    (stream._writableState && stream._writableState.error)

  // avoid implicit errors by default
  return !opts.all && err === STREAM_DESTROYED ? null : err
}

function isReadStreamx(stream) {
  return isStreamx(stream) && stream.readable
}

function isDisturbed(stream) {
  return (
    (stream._duplexState & OPENING) !== OPENING ||
    (stream._duplexState & DESTROYING) === DESTROYING ||
    (stream._duplexState & ACTIVE_OR_TICKING) !== 0
  )
}

function isTypedArray(data) {
  return typeof data === 'object' && data !== null && typeof data.byteLength === 'number'
}

function defaultByteLength(data) {
  return isTypedArray(data) ? data.byteLength : 1024
}

function noop() {}

function abort() {
  this.destroy(new Error('Stream aborted.'))
}

function isWritev(s) {
  return s._writev !== Writable.prototype._writev && s._writev !== Duplex.prototype._writev
}

module.exports = {
  pipeline,
  pipelinePromise,
  isStream,
  isStreamx,
  isEnding,
  isEnded,
  isFinishing,
  isFinished,
  isDisturbed,
  getStreamError,
  Stream,
  Writable,
  Readable,
  Duplex,
  Transform,
  // Export PassThrough for compatibility with Node.js core's stream module
  PassThrough
}
{
  "name": "streamx",
  "version": "2.25.0",
  "description": "An iteration of the Node.js core streams with a series of improvements",
  "main": "index.js",
  "dependencies": {
    "events-universal": "^1.0.0",
    "fast-fifo": "^1.3.2",
    "text-decoder": "^1.1.0"
  },
  "devDependencies": {
    "b4a": "^1.6.6",
    "brittle": "^3.1.1",
    "end-of-stream": "^1.4.4",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "files": [
    "index.js"
  ],
  "scripts": {
    "format": "prettier --write .",
    "test": "prettier --check . && node test/all.js",
    "test:bare": "bare test/all.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/streamx.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/streamx/issues"
  },
  "homepage": "https://github.com/mafintosh/streamx"
}
const { Readable } = require('streamx')

module.exports = function (s, forks = 2) {
  const streams = new Array(forks)
  const status = new Array(forks).fill(true)

  let ended = false

  for (let i = 0; i < forks; i++) {
    streams[i] = new Readable({
      read (cb) {
        const check = !status[i]
        status[i] = true
        if (check && allReadable()) s.resume()
        cb(null)
      }
    })
  }

  s.on('end', function () {
    ended = true
    for (const stream of streams) stream.push(null)
  })

  s.on('error', function (err) {
    for (const stream of streams) stream.destroy(err)
  })

  s.on('close', function () {
    if (ended) return
    for (const stream of streams) stream.destroy()
  })

  s.on('data', function (data) {
    let needsPause = false
    for (let i = 0; i < streams.length; i++) {
      if (!(status[i] = streams[i].push(data))) {
        needsPause = true
      }
    }
    if (needsPause) s.pause()
  })

  return streams

  function allReadable () {
    for (let j = 0; j < status.length; j++) {
      if (!status[j]) return false
    }
    return true
  }
}
{
  "name": "teex",
  "version": "1.0.1",
  "description": "Turn a readable stream into multiple readable streamx streams",
  "main": "index.js",
  "dependencies": {
    "streamx": "^2.12.5"
  },
  "devDependencies": {
    "standard": "^14.3.4",
    "tape": "^5.0.1"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/teex.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/teex/issues"
  },
  "homepage": "https://github.com/mafintosh/teex"
}
const PassThroughDecoder = require('./lib/pass-through-decoder')
const UTF8Decoder = require('./lib/utf8-decoder')

module.exports = class TextDecoder {
  constructor(encoding = 'utf8') {
    this.encoding = normalizeEncoding(encoding)

    switch (this.encoding) {
      case 'utf8':
        this.decoder = new UTF8Decoder()
        break
      case 'utf16le':
      case 'base64':
        throw new Error('Unsupported encoding: ' + this.encoding)
      default:
        this.decoder = new PassThroughDecoder(this.encoding)
    }
  }

  get remaining() {
    return this.decoder.remaining
  }

  push(data) {
    if (typeof data === 'string') return data
    return this.decoder.decode(data)
  }

  // For Node.js compatibility
  write(data) {
    return this.push(data)
  }

  end(data) {
    let result = ''
    if (data) result = this.push(data)
    result += this.decoder.flush()
    return result
  }
}

function normalizeEncoding(encoding) {
  encoding = encoding.toLowerCase()

  switch (encoding) {
    case 'utf8':
    case 'utf-8':
      return 'utf8'
    case 'ucs2':
    case 'ucs-2':
    case 'utf16le':
    case 'utf-16le':
      return 'utf16le'
    case 'latin1':
    case 'binary':
      return 'latin1'
    case 'base64':
    case 'ascii':
    case 'hex':
      return encoding
    default:
      throw new Error('Unknown encoding: ' + encoding)
  }
}
const b4a = require('b4a')

module.exports = class PassThroughDecoder {
  constructor(encoding) {
    this.encoding = encoding
  }

  get remaining() {
    return 0
  }

  decode(data) {
    return b4a.toString(data, this.encoding)
  }

  flush() {
    return ''
  }
}
const b4a = require('b4a')

/**
 * https://encoding.spec.whatwg.org/#utf-8-decoder
 */
module.exports = class UTF8Decoder {
  constructor() {
    this._reset()
  }

  get remaining() {
    return this.bytesSeen
  }

  decode(data) {
    if (data.byteLength === 0) return ''

    if (this.bytesNeeded === 0 && trailingIncomplete(data, 0) === 0) {
      this.bytesSeen = trailingBytesSeen(data)
      return b4a.toString(data, 'utf8')
    }

    let result = ''
    let start = 0

    if (this.bytesNeeded > 0) {
      while (start < data.byteLength) {
        const byte = data[start]

        if (byte < this.lowerBoundary || byte > this.upperBoundary) {
          result += '\ufffd'
          this._reset()
          break
        }

        this.lowerBoundary = 0x80
        this.upperBoundary = 0xbf
        this.codePoint = (this.codePoint << 6) | (byte & 0x3f)
        this.bytesSeen++
        start++

        if (this.bytesSeen === this.bytesNeeded) {
          result += String.fromCodePoint(this.codePoint)
          this._reset()
          break
        }
      }

      if (this.bytesNeeded > 0) return result
    }

    const trailing = trailingIncomplete(data, start)
    const end = data.byteLength - trailing

    if (end > start) result += b4a.toString(data, 'utf8', start, end)

    for (let i = end; i < data.byteLength; i++) {
      const byte = data[i]

      if (this.bytesNeeded === 0) {
        if (byte <= 0x7f) {
          this.bytesSeen = 0
          result += String.fromCharCode(byte)
        } else if (byte >= 0xc2 && byte <= 0xdf) {
          this.bytesNeeded = 2
          this.bytesSeen = 1
          this.codePoint = byte & 0x1f
        } else if (byte >= 0xe0 && byte <= 0xef) {
          if (byte === 0xe0) this.lowerBoundary = 0xa0
          else if (byte === 0xed) this.upperBoundary = 0x9f
          this.bytesNeeded = 3
          this.bytesSeen = 1
          this.codePoint = byte & 0xf
        } else if (byte >= 0xf0 && byte <= 0xf4) {
          if (byte === 0xf0) this.lowerBoundary = 0x90
          else if (byte === 0xf4) this.upperBoundary = 0x8f
          this.bytesNeeded = 4
          this.bytesSeen = 1
          this.codePoint = byte & 0x7
        } else {
          this.bytesSeen = 1
          result += '\ufffd'
        }

        continue
      }

      if (byte < this.lowerBoundary || byte > this.upperBoundary) {
        result += '\ufffd'
        i--
        this._reset()

        continue
      }

      this.lowerBoundary = 0x80
      this.upperBoundary = 0xbf

      this.codePoint = (this.codePoint << 6) | (byte & 0x3f)
      this.bytesSeen++

      if (this.bytesSeen === this.bytesNeeded) {
        result += String.fromCodePoint(this.codePoint)
        this._reset()
      }
    }

    return result
  }

  flush() {
    const result = this.bytesNeeded > 0 ? '\ufffd' : ''
    this._reset()
    return result
  }

  _reset() {
    this.codePoint = 0
    this.bytesNeeded = 0
    this.bytesSeen = 0
    this.lowerBoundary = 0x80
    this.upperBoundary = 0xbf
  }
}

function trailingIncomplete(data, start) {
  const len = data.byteLength
  if (len <= start) return 0

  const limit = Math.max(start, len - 4)

  let i = len - 1
  while (i > limit && (data[i] & 0xc0) === 0x80) i--

  if (i < start) return 0

  const byte = data[i]

  let needed
  if (byte <= 0x7f) return 0
  if (byte >= 0xc2 && byte <= 0xdf) needed = 2
  else if (byte >= 0xe0 && byte <= 0xef) needed = 3
  else if (byte >= 0xf0 && byte <= 0xf4) needed = 4
  else return 0

  const available = len - i
  return available < needed ? available : 0
}

function trailingBytesSeen(data) {
  const len = data.byteLength
  if (len === 0) return 0

  const last = data[len - 1]

  if (last <= 0x7f) return 0
  if ((last & 0xc0) !== 0x80) return 1

  const limit = Math.max(0, len - 4)

  let i = len - 2
  while (i >= limit && (data[i] & 0xc0) === 0x80) i--

  if (i < 0) return 1

  const first = data[i]

  let needed
  if (first >= 0xc2 && first <= 0xdf) needed = 2
  else if (first >= 0xe0 && first <= 0xef) needed = 3
  else if (first >= 0xf0 && first <= 0xf4) needed = 4
  else return 1

  if (len - i !== needed) return 1

  if (needed >= 3) {
    const second = data[i + 1]
    if (first === 0xe0 && second < 0xa0) return 1
    if (first === 0xed && second > 0x9f) return 1
    if (first === 0xf0 && second < 0x90) return 1
    if (first === 0xf4 && second > 0x8f) return 1
  }

  return 0
}
{
  "name": "text-decoder",
  "version": "1.2.7",
  "description": "Streaming text decoder that preserves multibyte Unicode characters",
  "exports": {
    "./package": "./package.json",
    ".": "./index.js"
  },
  "files": [
    "index.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/text-decoder.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/text-decoder/issues"
  },
  "homepage": "https://github.com/holepunchto/text-decoder#readme",
  "dependencies": {
    "b4a": "^1.6.4"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  }
}
module.exports = class TimeOrderedSet {
  constructor () {
    this.oldest = null
    this.latest = null
    this.length = 0
  }

  has (node) {
    return !!(node.next || node.prev) || node === this.oldest
  }

  add (node) {
    if (this.has(node)) this.remove(node)

    if (!this.latest && !this.oldest) {
      this.latest = this.oldest = node
      node.prev = node.next = null
    } else {
      this.latest.next = node
      node.prev = this.latest
      node.next = null
      this.latest = node
    }

    this.length++

    return node
  }

  remove (node) {
    if (!this.has(node)) return node

    if (this.oldest !== node && this.latest !== node) {
      node.prev.next = node.next
      node.next.prev = node.prev
    } else {
      if (this.oldest === node) {
        this.oldest = node.next
        if (this.oldest) this.oldest.prev = null
      }
      if (this.latest === node) {
        this.latest = node.prev
        if (this.latest) this.latest.next = null
      }
    }

    node.next = node.prev = null
    this.length--

    return node
  }

  toArray ({ limit = Infinity, reverse = false } = {}) {
    const list = []

    if (reverse) {
      let node = this.latest
      while (node && limit--) {
        list.push(node)
        node = node.prev
      }
    } else {
      let node = this.oldest
      while (node && limit--) {
        list.push(node)
        node = node.next
      }
    }

    return list
  }
}
{
  "name": "time-ordered-set",
  "version": "2.0.1",
  "description": "Efficiently maintain a set of nodes ordered by the time they were added to the set",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "devDependencies": {
    "brittle": "^3.0.0",
    "standard": "^17.1.2"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/time-ordered-set.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/time-ordered-set/issues"
  },
  "homepage": "https://github.com/mafintosh/time-ordered-set"
}
module.exports = class TimerBrowser {
  constructor (ms, fn, ctx = null, interval = false) {
    this.ms = ms
    this.ontimeout = fn
    this.context = ctx || null
    this.interval = interval
    this.done = false

    this._timer = interval
      ? setInterval(callInterval, ms, this)
      : setTimeout(callTimeout, ms, this)
  }

  unref () {}

  ref () {}

  refresh () {
    if (this.done) return

    if (this.interval) {
      clearInterval(this._timer)
      this._timer = setInterval(callInterval, this.ms, this)
    } else {
      clearTimeout(this._timer)
      this._timer = setTimeout(callTimeout, this.ms, this)
    }
  }

  destroy () {
    this.done = true
    this.ontimeout = null

    if (this.interval) clearInterval(this._timer)
    else clearTimeout(this._timer)
  }

  static once (ms, fn, ctx) {
    return new this(ms, fn, ctx, false)
  }

  static on (ms, fn, ctx) {
    return new this(ms, fn, ctx, true)
  }
}

function callTimeout (self) {
  self.done = true
  self.ontimeout.call(self.context)
}

function callInterval (self) {
  self.ontimeout.call(self.context)
}
module.exports = isNode()
  ? require('./node')
  : require('./browser')

function isNode () {
  const to = setTimeout(function () {}, 1000)
  clearTimeout(to)
  return !!to.refresh
}
module.exports = class Timer {
  constructor (ms, fn, ctx = null, interval = false) {
    this.ms = ms
    this.ontimeout = fn
    this.context = ctx
    this.interval = interval
    this.done = false

    this._timer = interval
      ? setInterval(callInterval, ms, this)
      : setTimeout(callTimeout, ms, this)
  }

  unref () {
    this._timer.unref()
  }

  ref () {
    this._timer.ref()
  }

  refresh () {
    if (this.done !== true) this._timer.refresh()
  }

  destroy () {
    this.done = true
    this.ontimeout = null
    if (this.interval) clearInterval(this._timer)
    else clearTimeout(this._timer)
  }

  static once (ms, fn, ctx) {
    return new this(ms, fn, ctx, false)
  }

  static on (ms, fn, ctx) {
    return new this(ms, fn, ctx, true)
  }
}

function callTimeout (self) {
  self.done = true
  self.ontimeout.call(self.context)
}

function callInterval (self) {
  self.ontimeout.call(self.context)
}
{
  "name": "timeout-refresh",
  "version": "2.0.1",
  "description": "Efficiently refresh a timer",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^16.0.4",
    "tape": "^5.5.2"
  },
  "browser": "./browser.js",
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/timeout-refresh.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/timeout-refresh/issues"
  },
  "homepage": "https://github.com/mafintosh/timeout-refresh"
}
require.addon = require('require-addon')

module.exports = require.addon('.', __filename)
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

const v4Seg = '(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])'
const v4Str = `(${v4Seg}[.]){3}${v4Seg}`
const IPv4Pattern = new RegExp(`^${v4Str}$`)

const v6Seg = '(?:[0-9a-fA-F]{1,4})'
const IPv6Pattern = new RegExp(
  '^(' +
    `(?:${v6Seg}:){7}(?:${v6Seg}|:)|` +
    `(?:${v6Seg}:){6}(?:${v4Str}|:${v6Seg}|:)|` +
    `(?:${v6Seg}:){5}(?::${v4Str}|(:${v6Seg}){1,2}|:)|` +
    `(?:${v6Seg}:){4}(?:(:${v6Seg}){0,1}:${v4Str}|(:${v6Seg}){1,3}|:)|` +
    `(?:${v6Seg}:){3}(?:(:${v6Seg}){0,2}:${v4Str}|(:${v6Seg}){1,4}|:)|` +
    `(?:${v6Seg}:){2}(?:(:${v6Seg}){0,3}:${v4Str}|(:${v6Seg}){1,5}|:)|` +
    `(?:${v6Seg}:){1}(?:(:${v6Seg}){0,4}:${v4Str}|(:${v6Seg}){1,6}|:)|` +
    `(?::((?::${v6Seg}){0,5}:${v4Str}|(?::${v6Seg}){1,7}|:))` +
    ')(%[0-9a-zA-Z-.:]{1,})?$'
)

const isIPv4 = (exports.isIPv4 = function isIPv4(host) {
  return IPv4Pattern.test(host)
})

const isIPv6 = (exports.isIPv6 = function isIPv6(host) {
  return IPv6Pattern.test(host)
})

exports.isIP = function isIP(host) {
  if (isIPv4(host)) return 4
  if (isIPv6(host)) return 6
  return 0
}
const events = require('events')
const b4a = require('b4a')
const binding = require('../binding')

module.exports = class NetworkInterfaces extends events.EventEmitter {
  constructor(udx) {
    super()

    this._handle = b4a.alloc(binding.sizeof_udx_napi_interface_event_t)
    this._watching = false
    this._destroying = null

    binding.udx_napi_interface_event_init(
      udx._handle,
      this._handle,
      this,
      this._onevent,
      this._onclose
    )

    this.interfaces = binding.udx_napi_interface_event_get_addrs(this._handle)
  }

  _onclose() {
    this.emit('close')
  }

  _onevent() {
    this.interfaces = binding.udx_napi_interface_event_get_addrs(this._handle)

    this.emit('change', this.interfaces)
  }

  watch() {
    if (this._watching) return this
    this._watching = true

    binding.udx_napi_interface_event_start(this._handle)

    return this
  }

  unwatch() {
    if (!this._watching) return this
    this._watching = false

    binding.udx_napi_interface_event_stop(this._handle)

    return this
  }

  async destroy() {
    if (this._destroying) return this._destroying
    this._destroying = events.once(this, 'close')

    binding.udx_napi_interface_event_close(this._handle)

    return this._destroying
  }

  [Symbol.iterator]() {
    return this.interfaces[Symbol.iterator]()
  }
}
const events = require('events')
const b4a = require('b4a')
const binding = require('../binding')
const ip = require('./ip')

module.exports = class UDXSocket extends events.EventEmitter {
  constructor(udx, opts = {}) {
    super()

    this.udx = udx

    this._handle = b4a.alloc(binding.sizeof_udx_napi_socket_t)
    this._inited = false
    this._host = null
    this._family = 0
    this._ipv6Only = opts.ipv6Only === true
    this._reuseAddress = opts.reuseAddress === true
    this._port = 0
    this._reqs = []
    this._free = []
    this._closing = null
    this._closed = false

    this._view64 = new BigUint64Array(
      this._handle.buffer,
      this._handle.byteOffset,
      this._handle.byteLength >> 3
    )

    this.streams = new Set()

    this.userData = null
  }

  get bound() {
    return this._port !== 0
  }

  get closing() {
    return this._closing !== null
  }

  get idle() {
    return this.streams.size === 0
  }

  get busy() {
    return this.streams.size > 0
  }

  get bytesTransmitted() {
    if (this._inited !== true) return 0
    return Number(this._view64[binding.offsetof_udx_socket_t_bytes_tx >> 3])
  }

  get packetsTransmitted() {
    if (this._inited !== true) return 0
    return Number(this._view64[binding.offsetof_udx_socket_t_packets_tx >> 3])
  }

  get bytesReceived() {
    if (this._inited !== true) return 0
    return Number(this._view64[binding.offsetof_udx_socket_t_bytes_rx >> 3])
  }

  get packetsReceived() {
    if (this._inited !== true) return 0
    return Number(this._view64[binding.offsetof_udx_socket_t_packets_rx >> 3])
  }

  get packetsDroppedByKernel() {
    if (this._inited !== true) return 0
    return Number(this._view64[binding.offsetof_udx_socket_t_packets_dropped_by_kernel >> 3])
  }

  toJSON() {
    return {
      bound: this.bound,
      closing: this.closing,
      streams: this.streams.size,
      address: this.address(),
      ipv6Only: this._ipv6Only,
      reuseAddress: this._reuseAddress,
      idle: this.idle,
      busy: this.busy
    }
  }

  _init() {
    if (this._inited) return

    binding.udx_napi_socket_init(
      this.udx._handle,
      this._handle,
      this,
      this._onsend,
      this._onmessage,
      this._onclose,
      this._reallocMessage
    )

    this._inited = true
  }

  _onsend(id, err) {
    const req = this._reqs[id]

    const onflush = req.onflush

    req.buffer = null
    req.onflush = null

    this._free.push(id)

    onflush(err >= 0)

    // gc the free list
    if (this._free.length >= 16 && this._free.length === this._reqs.length) {
      this._free = []
      this._reqs = []
    }
  }

  _onmessage(len, port, host, family) {
    this.emit('message', this.udx._consumeMessage(len), { host, family, port })
    return this.udx._buffer
  }

  _onclose() {
    this.emit('close')
  }

  _reallocMessage() {
    return this.udx._reallocMessage()
  }

  _onidle() {
    this.emit('idle')
  }

  _onbusy() {
    this.emit('busy')
  }

  _addStream(stream) {
    if (this.streams.has(stream)) return false
    this.streams.add(stream)
    if (this.streams.size === 1) this._onbusy()
    return true
  }

  _removeStream(stream) {
    if (!this.streams.has(stream)) return false
    this.streams.delete(stream)
    const closed = this._closeMaybe()
    if (this.idle && !closed) this._onidle()
    return true
  }

  address() {
    if (!this.bound) return null
    return { host: this._host, family: this._family, port: this._port }
  }

  bind(port, host) {
    if (this.bound) throw new Error('Already bound')
    if (this.closing) throw new Error('Socket is closed')

    if (!port) port = 0

    let flags = 0
    if (this._ipv6Only) flags |= binding.UV_UDP_IPV6ONLY
    if (this._reuseAddress) flags |= binding.UV_UDP_REUSEADDR

    let family

    if (host) {
      family = ip.isIP(host)
      if (!family) throw new Error(`${host} is not a valid IP address`)

      if (!this._inited) this._init()

      this._port = binding.udx_napi_socket_bind(this._handle, port, host, family, flags)
    } else {
      if (!this._inited) this._init()

      try {
        host = '::'
        family = 6
        this._port = binding.udx_napi_socket_bind(this._handle, port, host, family, flags)
      } catch {
        host = '0.0.0.0'
        family = 4
        this._port = binding.udx_napi_socket_bind(this._handle, port, host, family, flags)
      }
    }

    this._host = host
    this._family = family

    this.emit('listening')
  }

  async close() {
    if (this._closing) return this._closing
    this._closing = new Promise((resolve) => this.once('close', resolve))
    this._closeMaybe()
    return this._closing
  }

  _closeMaybe() {
    if (this._closed || this._closing === null) return this._closed

    if (!this._inited) {
      this._closed = true
      this.emit('close')
      return true
    }

    if (this.idle) {
      binding.udx_napi_socket_close(this._handle)
      this._closed = true
    }

    return this._closed
  }

  setTTL(ttl) {
    if (!this._inited) throw new Error('Socket not active')
    binding.udx_napi_socket_set_ttl(this._handle, ttl)
  }

  getRecvBufferSize() {
    if (!this._inited) throw new Error('Socket not active')
    return binding.udx_napi_socket_get_recv_buffer_size(this._handle)
  }

  setRecvBufferSize(size) {
    if (!this._inited) throw new Error('Socket not active')
    return binding.udx_napi_socket_set_recv_buffer_size(this._handle, size)
  }

  getSendBufferSize() {
    if (!this._inited) throw new Error('Socket not active')
    return binding.udx_napi_socket_get_send_buffer_size(this._handle)
  }

  setSendBufferSize(size) {
    if (!this._inited) throw new Error('Socket not active')
    return binding.udx_napi_socket_set_send_buffer_size(this._handle, size)
  }

  addMembership(group, ifaceAddress) {
    if (!this._inited) throw new Error('Socket not active')
    return binding.udx_napi_socket_set_membership(this._handle, group, ifaceAddress || '', true)
  }

  dropMembership(group, ifaceAddress) {
    if (!this._inited) throw new Error('Socket not active')
    return binding.udx_napi_socket_set_membership(this._handle, group, ifaceAddress || '', false)
  }

  async send(buffer, port, host, ttl) {
    if (this.closing) return false

    if (!host) host = '127.0.0.1'

    const family = ip.isIP(host)
    if (!family) throw new Error(`${host} is not a valid IP address`)

    if (!this.bound) this.bind(0)

    const id = this._allocSend()
    const req = this._reqs[id]

    req.buffer = buffer

    const promise = new Promise((resolve) => {
      req.onflush = resolve
    })

    binding.udx_napi_socket_send_ttl(
      this._handle,
      req.handle,
      id,
      buffer,
      port,
      host,
      family,
      ttl || 0
    )

    return promise
  }

  trySend(buffer, port, host, ttl) {
    if (this.closing) return

    if (!host) host = '127.0.0.1'

    const family = ip.isIP(host)
    if (!family) throw new Error(`${host} is not a valid IP address`)

    if (!this.bound) this.bind(0)

    const id = this._allocSend()
    const req = this._reqs[id]

    req.buffer = buffer
    req.onflush = noop

    binding.udx_napi_socket_send_ttl(
      this._handle,
      req.handle,
      id,
      buffer,
      port,
      host,
      family,
      ttl || 0
    )
  }

  _allocSend() {
    if (this._free.length > 0) return this._free.pop()
    const handle = b4a.allocUnsafe(binding.sizeof_udx_socket_send_t)
    return this._reqs.push({ handle, buffer: null, onflush: null }) - 1
  }
}

function noop() {}
const streamx = require('streamx')
const b4a = require('b4a')
const binding = require('../binding')
const ip = require('./ip')

const MAX_PACKET = 2048
const BUFFER_SIZE = 65536 + MAX_PACKET

module.exports = class UDXStream extends streamx.Duplex {
  constructor(udx, id, opts = {}) {
    super({ mapWritable: toBuffer, eagerOpen: true })

    this.udx = udx
    this.socket = null

    this._handle = b4a.alloc(binding.sizeof_udx_napi_stream_t)
    this._view = new Uint32Array(
      this._handle.buffer,
      this._handle.byteOffset,
      this._handle.byteLength >> 2
    )
    this._view16 = new Uint16Array(
      this._handle.buffer,
      this._handle.byteOffset,
      this._handle.byteLength >> 1
    )
    this._view64 = new BigUint64Array(
      this._handle.buffer,
      this._handle.byteOffset,
      this._handle.byteLength >> 3
    )

    this._wreqs = []
    this._wfree = []

    this._sreqs = []
    this._sfree = []
    this._closed = false

    this._flushing = 0
    this._flushes = []

    this._buffer = null
    this._reallocData()

    this._onwrite = null
    this._ondestroy = null
    this._firewall = opts.firewall || firewallAll

    this._remoteChanging = null
    this._previousSocket = null

    this.id = id
    this.remoteId = 0
    this.remoteHost = null
    this.remoteFamily = 0
    this.remotePort = 0

    this.userData = null

    binding.udx_napi_stream_init(
      this.udx._handle,
      this._handle,
      id,
      opts.framed ? 1 : 0,
      this,
      this._ondata,
      this._onend,
      this._ondrain,
      this._onack,
      this._onsend,
      this._onmessage,
      this._onclose,
      this._onfirewall,
      this._onremotechanged,
      this._reallocData,
      this._reallocMessage
    )

    if (opts.seq) binding.udx_napi_stream_set_seq(this._handle, opts.seq)

    binding.udx_napi_stream_recv_start(this._handle, this._buffer)
  }

  get connected() {
    return this.socket !== null
  }

  get mtu() {
    return this._view16[binding.offsetof_udx_stream_t_mtu >> 1]
  }

  get rtt() {
    return this._view[binding.offsetof_udx_stream_t_srtt >> 2]
  }

  get cwnd() {
    return this._view[binding.offsetof_udx_stream_t_cwnd >> 2]
  }

  get rtoCount() {
    return this._view16[binding.offsetof_udx_stream_t_rto_count >> 1]
  }

  get retransmits() {
    return this._view16[binding.offsetof_udx_stream_t_retransmit_count >> 1]
  }

  get fastRecoveries() {
    return this._view16[binding.offsetof_udx_stream_t_fast_recovery_count >> 1]
  }

  get inflight() {
    return this._view[binding.offsetof_udx_stream_t_inflight >> 2]
  }

  get bytesTransmitted() {
    return Number(this._view64[binding.offsetof_udx_stream_t_bytes_tx >> 3])
  }

  get packetsTransmitted() {
    return Number(this._view64[binding.offsetof_udx_stream_t_packets_tx >> 3])
  }

  get bytesReceived() {
    return Number(this._view64[binding.offsetof_udx_stream_t_bytes_rx >> 3])
  }

  get packetsReceived() {
    return Number(this._view64[binding.offsetof_udx_stream_t_packets_rx >> 3])
  }

  get localHost() {
    return this.socket ? this.socket.address().host : null
  }

  get localFamily() {
    return this.socket ? this.socket.address().family : 0
  }

  get localPort() {
    return this.socket ? this.socket.address().port : 0
  }

  setInteractive(bool) {
    if (!this._closed) return
    binding.udx_napi_stream_set_mode(this._handle, bool ? 0 : 1)
  }

  connect(socket, remoteId, port, host, opts = {}) {
    if (this._closed) return

    if (this.connected) throw new Error('Already connected')
    if (socket.closing) throw new Error('Socket is closed')

    if (typeof host === 'object') {
      opts = host
      host = null
    }

    if (!host) host = '127.0.0.1'

    const family = ip.isIP(host)
    if (!family) throw new Error(`${host} is not a valid IP address`)
    if (!(port > 0 && port < 65536)) throw new Error(`${port} is not a valid port`)

    if (!socket.bound) socket.bind(0)

    this.remoteId = remoteId
    this.remotePort = port
    this.remoteHost = host
    this.remoteFamily = family
    this.socket = socket

    if (opts.ack) binding.udx_napi_stream_set_ack(this._handle, opts.ack)

    binding.udx_napi_stream_connect(this._handle, socket._handle, remoteId, port, host, family)

    this.socket._addStream(this)

    this.emit('connect')
  }

  changeRemote(socket, remoteId, port, host) {
    if (this._remoteChanging) throw new Error('Remote already changing')

    if (!this.connected) throw new Error('Not yet connected')
    if (socket.closing) throw new Error('Socket is closed')

    if (this.socket.udx !== socket.udx) {
      throw new Error('Cannot change to a socket on another UDX instance')
    }

    if (!host) host = '127.0.0.1'

    const family = ip.isIP(host)
    if (!family) throw new Error(`${host} is not a valid IP address`)
    if (!(port > 0 && port < 65536)) throw new Error(`${port} is not a valid port`)

    if (this.socket !== socket) this._previousSocket = this.socket

    this.remoteId = remoteId
    this.remotePort = port
    this.remoteHost = host
    this.remoteFamily = family
    this.socket = socket

    this._remoteChanging = new Promise((resolve, reject) => {
      const onchanged = () => {
        this.off('close', onclose)
        resolve()
      }

      const onclose = () => {
        this.off('remote-changed', onchanged)
        reject(new Error('Stream is closed'))
      }

      this.once('remote-changed', onchanged).once('close', onclose)
    })

    binding.udx_napi_stream_change_remote(
      this._handle,
      socket._handle,
      remoteId,
      port,
      host,
      family
    )

    this.socket._addStream(this)

    return this._remoteChanging
  }

  relayTo(destination) {
    if (this._closed) return

    binding.udx_napi_stream_relay_to(this._handle, destination._handle)
  }

  async send(buffer) {
    if (!this.connected || this._closed) return false

    const id = this._allocSend()
    const req = this._sreqs[id]

    req.buffer = buffer

    const promise = new Promise((resolve) => {
      req.onflush = resolve
    })

    binding.udx_napi_stream_send(this._handle, req.handle, id, buffer)

    return promise
  }

  trySend(buffer) {
    if (!this.connected || this._closed) return

    const id = this._allocSend()
    const req = this._sreqs[id]

    req.buffer = buffer
    req.onflush = noop

    binding.udx_napi_stream_send(this._handle, req.handle, id, buffer)
  }

  async flush() {
    if ((await streamx.Writable.drained(this)) === false) return false
    if (this.destroying) return false

    const missing = this._wreqs.length - this._wfree.length
    if (missing === 0) return true

    return new Promise((resolve) => {
      this._flushes.push({ flush: this._flushing++, missing, resolve })
    })
  }

  toJSON() {
    return {
      id: this.id,
      connected: this.connected,
      destroying: this.destroying,
      destroyed: this.destroyed,
      remoteId: this.remoteId,
      remoteHost: this.remoteHost,
      remoteFamily: this.remoteFamily,
      remotePort: this.remotePort,
      mtu: this.mtu,
      rtt: this.rtt,
      cwnd: this.cwnd,
      inflight: this.inflight,
      socket: this.socket ? this.socket.toJSON() : null
    }
  }

  _read(cb) {
    cb(null)
  }

  _writeContinue(err) {
    if (this._onwrite === null) return
    const cb = this._onwrite
    this._onwrite = null
    cb(err)
  }

  _destroyContinue(err) {
    if (this._ondestroy === null) return
    const cb = this._ondestroy
    this._ondestroy = null
    cb(err)
  }

  _writev(buffers, cb) {
    if (!this.connected)
      throw customError('Writing while not connected not currently supported', 'ERR_ASSERTION')

    let drained = true

    if (buffers.length === 1) {
      const id = this._allocWrite(1)
      const req = this._wreqs[id]

      req.flush = this._flushing
      req.buffer = buffers[0]

      drained = binding.udx_napi_stream_write(this._handle, req.handle, id, req.buffer) !== 0
    } else {
      const id = this._allocWrite(nextBatchSize(buffers.length))
      const req = this._wreqs[id]

      req.flush = this._flushing
      req.buffers = buffers

      drained = binding.udx_napi_stream_writev(this._handle, req.handle, id, req.buffers) !== 0
    }

    if (drained) cb(null)
    else this._onwrite = cb
  }

  _final(cb) {
    const id = this._allocWrite(1)
    const req = this._wreqs[id]

    req.flush = this._flushes
    req.buffer = b4a.allocUnsafe(0)

    const drained =
      binding.udx_napi_stream_write_end(this._handle, req.handle, id, req.buffer) !== 0

    if (drained) cb(null)
    else this._onwrite = cb
  }

  _predestroy() {
    if (!this._closed) binding.udx_napi_stream_destroy(this._handle)
    this._closed = true
    this._writeContinue(null)
  }

  _destroy(cb) {
    if (this.connected) this._ondestroy = cb
    else cb(null)
  }

  _ondata(read) {
    this.push(this._consumeData(read))
    return this._buffer
  }

  _onend(read) {
    if (read > 0) this.push(this._consumeData(read))
    this.push(null)
  }

  _ondrain() {
    this._writeContinue(null)
  }

  _flushAck(flush) {
    for (let i = this._flushes.length - 1; i >= 0; i--) {
      const f = this._flushes[i]
      if (f.flush < flush) break
      f.missing--
    }

    while (this._flushes.length > 0 && this._flushes[0].missing === 0) {
      this._flushes.shift().resolve(true)
    }
  }

  _onack(id) {
    const req = this._wreqs[id]

    req.buffers = req.buffer = null
    this._wfree.push(id)

    if (this._flushes.length > 0) this._flushAck(req.flush)

    // gc the free list
    if (this._wfree.length >= 64 && this._wfree.length === this._wreqs.length) {
      this._wfree = []
      this._wreqs = []
    }
  }

  _onsend(id, err) {
    const req = this._sreqs[id]

    const onflush = req.onflush

    req.buffer = null
    req.onflush = null

    this._sfree.push(id)

    onflush(err >= 0)

    // gc the free list
    if (this._sfree.length >= 16 && this._sfree.length === this._sreqs.length) {
      this._sfree = []
      this._sreqs = []
    }
  }

  _onmessage(len) {
    this.emit('message', this.udx._consumeMessage(len))
    return this.udx._buffer
  }

  _onclose(err) {
    this._closed = true

    if (this.socket) {
      this.socket._removeStream(this)
      this.socket = null
    }

    if (this._previousSocket) {
      this._previousSocket._removeStream(this)
      this._previousSocket = null
    }

    // no error, we don't need to do anything
    if (!err) return this._destroyContinue(null)

    if (this._ondestroy === null) this.destroy(err)
    else this._destroyContinue(err)
  }

  _onfirewall(socket, port, host, family) {
    return this._firewall(socket, port, host, family) ? 1 : 0
  }

  _onremotechanged() {
    if (this._previousSocket) {
      this._previousSocket._removeStream(this)
      this._previousSocket = null
    }

    this._remoteChanging = null
    this.emit('remote-changed')
  }

  _consumeData(len) {
    const next = this._buffer.subarray(0, len)
    this._buffer = this._buffer.subarray(len)
    if (this._buffer.byteLength < MAX_PACKET) this._reallocData()
    return next
  }

  _reallocData() {
    this._buffer = b4a.allocUnsafe(BUFFER_SIZE)
    return this._buffer
  }

  _reallocMessage() {
    return this.udx._reallocMessage()
  }

  _allocWrite(size) {
    if (this._wfree.length === 0) {
      const handle = b4a.allocUnsafe(binding.udx_napi_stream_write_sizeof(size))
      return (
        this._wreqs.push({
          handle,
          size,
          buffers: null,
          buffer: null,
          flush: 0
        }) - 1
      )
    }

    const free = this._wfree.pop()
    if (size === 1) return free

    const next = this._wreqs[free]
    if (next.size < size) {
      next.handle = b4a.allocUnsafe(binding.udx_napi_stream_write_sizeof(size))
      next.size = size
    }

    return free
  }

  _allocSend() {
    if (this._sfree.length > 0) return this._sfree.pop()
    const handle = b4a.allocUnsafe(binding.sizeof_udx_stream_send_t)
    return this._sreqs.push({ handle, buffer: null, resolve: null, reject: null }) - 1
  }
}

function noop() {}

function toBuffer(data) {
  return typeof data === 'string' ? b4a.from(data) : data
}

function firewallAll(socket, port, host) {
  return true
}

function customError(message, code) {
  const error = new Error(message)
  error.code = code
  return error
}

function nextBatchSize(n) {
  // try to coerce the the writevs into sameish size
  if (n === 1) return 1
  // group all < 8 to the same size, low mem overhead but save some small allocs
  if (n < 8) return 8
  if (n < 16) return 16
  if (n < 32) return 32
  if (n < 64) return 64
  return n
}
const b4a = require('b4a')
const binding = require('../binding')
const ip = require('./ip')
const Socket = require('./socket')
const Stream = require('./stream')
const NetworkInterfaces = require('./network-interfaces')

const MAX_MESSAGE = 4096
const BUFFER_SIZE = 65536 + MAX_MESSAGE

module.exports = class UDX {
  constructor() {
    this._handle = b4a.alloc(binding.sizeof_udx_napi_t)
    this._watchers = new Set()
    this._view64 = new BigUint64Array(
      this._handle.buffer,
      this._handle.byteOffset,
      this._handle.byteLength >> 3
    )

    this._buffer = null
    this._reallocMessage()

    binding.udx_napi_init(this._handle, this._buffer)
  }

  static isIPv4(host) {
    return ip.isIPv4(host)
  }

  static isIPv6(host) {
    return ip.isIPv6(host)
  }

  static isIP(host) {
    return ip.isIP(host)
  }

  get bytesTransmitted() {
    return Number(this._view64[binding.offsetof_udx_t_bytes_tx >> 3])
  }

  get packetsTransmitted() {
    return Number(this._view64[binding.offsetof_udx_t_packets_tx >> 3])
  }

  get bytesReceived() {
    return Number(this._view64[binding.offsetof_udx_t_bytes_rx >> 3])
  }

  get packetsReceived() {
    return Number(this._view64[binding.offsetof_udx_t_packets_rx >> 3])
  }

  get packetsDroppedByKernel() {
    return Number(this._view64[binding.offsetof_udx_t_packets_dropped_by_kernel >> 3])
  }

  _consumeMessage(len) {
    const next = this._buffer.subarray(0, len)
    this._buffer = this._buffer.subarray(len)
    if (this._buffer.byteLength < MAX_MESSAGE) this._reallocMessage()
    return next
  }

  _reallocMessage() {
    // TODO: move reallocation to native
    this._buffer = b4a.allocUnsafe(BUFFER_SIZE)
    return this._buffer
  }

  createSocket(opts) {
    return new Socket(this, opts)
  }

  createStream(id, opts) {
    return new Stream(this, id, opts)
  }

  networkInterfaces() {
    let [watcher = null] = this._watchers
    if (watcher) return watcher.interfaces

    watcher = new NetworkInterfaces(this)
    watcher.destroy()

    return watcher.interfaces
  }

  watchNetworkInterfaces(onchange) {
    const watcher = new NetworkInterfaces(this)

    this._watchers.add(watcher)
    watcher.on('close', () => {
      this._watchers.delete(watcher)
    })

    if (onchange) watcher.on('change', onchange)

    return watcher.watch()
  }

  async lookup(host, opts = {}) {
    const { family = 0 } = opts

    const req = b4a.alloc(binding.sizeof_udx_napi_lookup_t)
    const ctx = {
      req,
      resolve: null,
      reject: null
    }

    const promise = new Promise((resolve, reject) => {
      ctx.resolve = resolve
      ctx.reject = reject
    })

    binding.udx_napi_lookup(this._handle, req, host, family, ctx, onlookup)

    return promise
  }
}

function onlookup(err, host, family) {
  if (err) this.reject(err)
  else this.resolve({ host, family })
}
{
  "name": "udx-native",
  "version": "1.19.2",
  "description": "udx is reliable, multiplexed, and congestion-controlled streams over udp",
  "main": "lib/udx.js",
  "files": [
    "lib",
    "prebuilds",
    "binding.cc",
    "binding.js",
    "CMakeLists.txt"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "addon": true,
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check .",
    "test": "npm run lint && npm run test:bare && npm run test:node",
    "test:node": "node test/all.js",
    "test:bare": "bare test/all.js",
    "test:all": "brittle test/*.js test/slow/*.js",
    "test:generate": "brittle -r test/all.js test/*.js",
    "bench": "brittle test/bench/*.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/udx-native.git"
  },
  "keywords": [
    "tcp",
    "udp",
    "stream",
    "reliable"
  ],
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/udx-native/issues"
  },
  "homepage": "https://github.com/holepunchto/udx-native#readme",
  "engines": {
    "bare": ">=1.17.4"
  },
  "dependencies": {
    "b4a": "^1.5.0",
    "bare-events": "^2.2.0",
    "require-addon": "^1.1.0",
    "streamx": "^2.22.0"
  },
  "devDependencies": {
    "bare-compat-napi": "^1.3.0",
    "brittle": "^3.1.0",
    "cmake-bare": "^1.1.10",
    "cmake-fetch": "^1.0.1",
    "cmake-napi": "^1.0.5",
    "is-ci": "^3.0.1",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "tiny-byte-size": "^1.1.0"
  }
}
exports.add = add
exports.has = has
exports.remove = remove
exports.swap = swap

function add (list, item) {
  if (has(list, item)) return item
  item._index = list.length
  list.push(item)
  return item
}

function has (list, item) {
  return item._index < list.length && list[item._index] === item
}

function remove (list, item) {
  if (!has(list, item)) return null

  var last = list.pop()
  if (last !== item) {
    list[item._index] = last
    last._index = item._index
  }

  return item
}

function swap (list, a, b) {
  if (!has(list, a) || !has(list, b)) return
  var tmp = a._index
  a._index = b._index
  list[a._index] = a
  b._index = tmp
  list[b._index] = b
}
{
  "name": "unordered-set",
  "version": "2.0.1",
  "description": "A couple of functions that make it easy to maintain an unordered set as an array in an efficient way",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^6.0.4",
    "tape": "^4.4.0"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/unordered-set.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/unordered-set/issues"
  },
  "homepage": "https://github.com/mafintosh/unordered-set"
}
const b4a = require('b4a')

unslab.all = all
unslab.is = is

module.exports = unslab

function unslab (buf) {
  if (buf === null || buf.buffer.byteLength === buf.byteLength) return buf
  const copy = b4a.allocUnsafeSlow(buf.byteLength)
  copy.set(buf, 0)
  return copy
}

function is (buf) {
  return buf.buffer.byteLength !== buf.byteLength
}

function all (list) {
  let size = 0
  for (let i = 0; i < list.length; i++) {
    const buf = list[i]
    size += buf === null || buf.buffer.byteLength === buf.byteLength ? 0 : buf.byteLength
  }

  const copy = b4a.allocUnsafeSlow(size)
  const result = new Array(list.length)

  let offset = 0
  for (let i = 0; i < list.length; i++) {
    let buf = list[i]

    if (buf !== null && buf.buffer.byteLength !== buf.byteLength) {
      copy.set(buf, offset)
      buf = copy.subarray(offset, offset += buf.byteLength)
    }

    result[i] = buf
  }

  return result
}
{
  "name": "unslab",
  "version": "1.3.0",
  "description": "Unslab some slab'ed buffers",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.6.6"
  },
  "devDependencies": {
    "brittle": "^3.5.2",
    "standard": "^17.1.0"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/unslab.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/unslab/issues"
  },
  "homepage": "https://github.com/holepunchto/unslab"
}
const { runtime, platform, arch } = typeof Bare !== 'undefined'
  ? { runtime: 'bare', platform: global.Bare.platform, arch: global.Bare.arch }
  : typeof process !== 'undefined'
    ? { runtime: 'node', platform: global.process.platform, arch: global.process.arch }
    : typeof Window !== 'undefined'
      ? { runtime: 'browser', platform: 'unknown', arch: 'unknown' }
      : { runtime: 'unknown', platform: 'unknown', arch: 'unknown' }

exports.runtime = runtime
exports.platform = platform
exports.arch = arch
exports.isBare = runtime === 'bare'
exports.isBareKit = exports.isBare && typeof BareKit !== 'undefined'
exports.isPear = typeof Pear !== 'undefined'
exports.isNode = runtime === 'node'
exports.isBrowser = runtime === 'browser'
exports.isWindows = platform === 'win32'
exports.isLinux = platform === 'linux'
exports.isMac = platform === 'darwin'
exports.isIOS = platform === 'ios' || platform === 'ios-simulator'
exports.isAndroid = platform === 'android'
exports.isElectron = typeof process !== 'undefined' && !!global.process.versions?.electron
exports.isElectronRenderer = exports.isElectron && global.process.type === 'renderer'
exports.isElectronWorker = exports.isElectron && global.process.type === 'worker'
{
  "name": "which-runtime",
  "version": "1.3.2",
  "description": "Detect if you are in Bare or Node and which os etc",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {},
  "devDependencies": {
    "standard": "^17.0.0"
  },
  "scripts": {
    "test": "standard"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/which-runtime.git"
  },
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/which-runtime/issues"
  },
  "homepage": "https://github.com/holepunchto/which-runtime"
}
module.exports = class MaxCache {
  constructor ({ maxSize, maxAge, createMap, ongc }) {
    this.maxSize = maxSize
    this.maxAge = maxAge
    this.ongc = ongc || null

    this._createMap = createMap || defaultCreateMap
    this._latest = this._createMap()
    this._oldest = this._createMap()
    this._retained = this._createMap()
    this._gced = false
    this._interval = null

    if (this.maxAge > 0 && this.maxAge < Infinity) {
      const tick = Math.ceil(2 / 3 * this.maxAge)
      this._interval = setInterval(this._gcAuto.bind(this), tick)
      if (this._interval.unref) this._interval.unref()
    }
  }

  * [Symbol.iterator] () {
    for (const it of [this._latest, this._oldest, this._retained]) {
      yield * it
    }
  }

  * keys () {
    for (const it of [this._latest, this._oldest, this._retained]) {
      yield * it.keys()
    }
  }

  * values () {
    for (const it of [this._latest, this._oldest, this._retained]) {
      yield * it.values()
    }
  }

  destroy () {
    this.clear()
    clearInterval(this._interval)
    this._interval = null
  }

  clear () {
    this._gced = true
    this._latest.clear()
    this._oldest.clear()
    this._retained.clear()
  }

  set (k, v) {
    if (this._retained.has(k)) return this
    this._latest.set(k, v)
    this._oldest.delete(k) || this._retained.delete(k)
    if (this._latest.size >= this.maxSize) this._gc()
    return this
  }

  retain (k, v) {
    this._retained.set(k, v)
    this._latest.delete(k) || this._oldest.delete(k)
    return this
  }

  delete (k) {
    return this._latest.delete(k) || this._oldest.delete(k) || this._retained.delete(k)
  }

  has (k) {
    return this._latest.has(k) || this._oldest.has(k) || this._retained.has(k)
  }

  get (k) {
    if (this._latest.has(k)) {
      return this._latest.get(k)
    }

    if (this._oldest.has(k)) {
      const v = this._oldest.get(k)
      this._latest.set(k, v)
      this._oldest.delete(k)
      return v
    }

    if (this._retained.has(k)) {
      return this._retained.get(k)
    }

    return null
  }

  _gcAuto () {
    if (!this._gced) this._gc()
    this._gced = false
  }

  _gc () {
    this._gced = true
    if (this.ongc !== null && this._oldest.size > 0) this.ongc(this._oldest)
    this._oldest = this._latest
    this._latest = this._createMap()
  }
}

function defaultCreateMap () {
  return new Map()
}
{
  "name": "xache",
  "version": "1.2.1",
  "description": "Yet another auto expiring, max sizable cache",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "devDependencies": {
    "brittle": "^3.3.2",
    "standard": "^17.1.0"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/xache.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/xache/issues"
  },
  "homepage": "https://github.com/mafintosh/xache"
}
const b4a = require('b4a')

const ALPHABET = 'ybndrfg8ejkmcpqxot1uwisza345h769'
const MIN = 0x31 // 1
const MAX = 0x7a // z
const REVERSE = new Int8Array(1 + MAX - MIN)

REVERSE.fill(-1)

for (let i = 0; i < ALPHABET.length; i++) {
  const v = ALPHABET.charCodeAt(i) - MIN
  REVERSE[v] = i
}

exports.encode = encode
exports.decode = decode
exports.ALPHABET = ALPHABET

function decode (s, out) {
  let pb = 0
  let ps = 0

  const r = s.length & 7
  const q = (s.length - r) / 8

  if (!out) out = b4a.allocUnsafe(Math.ceil(s.length * 5 / 8))

  // 0 5 2 7 4 1 6 3 (+5 mod 8)
  for (let i = 0; i < q; i++) {
    const a = quintet(s, ps++)
    const b = quintet(s, ps++)
    const c = quintet(s, ps++)
    const d = quintet(s, ps++)
    const e = quintet(s, ps++)
    const f = quintet(s, ps++)
    const g = quintet(s, ps++)
    const h = quintet(s, ps++)

    out[pb++] = (a << 3) | (b >>> 2)
    out[pb++] = ((b & 0b11) << 6) | (c << 1) | (d >>> 4)
    out[pb++] = ((d & 0b1111) << 4) | (e >>> 1)
    out[pb++] = ((e & 0b1) << 7) | (f << 2) | (g >>> 3)
    out[pb++] = ((g & 0b111) << 5) | h
  }

  if (r === 0) return out.subarray(0, pb)

  const a = quintet(s, ps++)
  const b = quintet(s, ps++)

  out[pb++] = (a << 3) | (b >>> 2)

  if (r <= 2) return out.subarray(0, pb)

  const c = quintet(s, ps++)
  const d = quintet(s, ps++)

  out[pb++] = ((b & 0b11) << 6) | (c << 1) | (d >>> 4)

  if (r <= 4) return out.subarray(0, pb)

  const e = quintet(s, ps++)

  out[pb++] = ((d & 0b1111) << 4) | (e >>> 1)

  if (r <= 5) return out.subarray(0, pb)

  const f = quintet(s, ps++)
  const g = quintet(s, ps++)

  out[pb++] = ((e & 0b1) << 7) | (f << 2) | (g >>> 3)

  if (r <= 7) return out.subarray(0, pb)

  const h = quintet(s, ps++)

  out[pb++] = ((g & 0b111) << 5) | h

  return out.subarray(0, pb)
}

function encode (buf) {
  if (typeof buf === 'string') buf = b4a.from(buf)

  const max = buf.byteLength * 8

  let s = ''

  for (let p = 0; p < max; p += 5) {
    const i = p >>> 3
    const j = p & 7

    if (j <= 3) {
      s += ALPHABET[(buf[i] >>> (3 - j)) & 0b11111]
      continue
    }

    const of = j - 3
    const h = (buf[i] << of) & 0b11111
    const l = (i >= buf.byteLength ? 0 : buf[i + 1]) >>> (8 - of)

    s += ALPHABET[h | l]
  }

  return s
}

function quintet (s, i) {
  if (i > s.length) {
    return 0
  }

  const v = s.charCodeAt(i)

  if (v < MIN || v > MAX) {
    throw Error('Invalid character in base32 input: "' + s[i] + '" at position ' + i)
  }

  const bits = REVERSE[v - MIN]

  if (bits === -1) {
    throw Error('Invalid character in base32 input: "' + s[i] + '" at position ' + i)
  }

  return bits
}
{
  "name": "z32",
  "version": "1.1.0",
  "description": "Encode & decode z-base32",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.5.3"
  },
  "devDependencies": {
    "base-x": "^4.0.0",
    "base32": "0.0.7",
    "brittle": "^3.1.3",
    "nanobench": "^3.0.0",
    "rfc4648": "^1.5.2",
    "standard": "^17.0.0"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/z32.git"
  },
  "scripts": {
    "test": "standard && brittle test.js",
    "bench": "node benchmark.js"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/z32/issues"
  },
  "homepage": "https://github.com/mafintosh/z32"
}
{
  "name": "hyper-svc",
  "version": "0.1.9",
  "description": "Reusable per-app daemon library \u2014 UDS + HTTP for local RPC, Hyperswarm for peer mirroring",
  "type": "module",
  "main": "index.js",
  "scripts": {
    "test": "brittle test/*.test.js",
    "test:bare": "bare ./node_modules/.bin/brittle test/*.test.js"
  },
  "engines": {
    "node": ">=18",
    "bare": ">=1.0"
  },
  "imports": {
    "#node:fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "#node:fs/promises": {
      "bare": "bare-fs/promises",
      "default": "fs/promises"
    },
    "#node:path": {
      "bare": "bare-path",
      "default": "path"
    },
    "#node:os": {
      "bare": "bare-os",
      "default": "os"
    },
    "#node:url": {
      "bare": "bare-url",
      "default": "url"
    },
    "#node:events": {
      "bare": "bare-events",
      "default": "events"
    },
    "#node:stream": {
      "bare": "bare-stream",
      "default": "stream"
    },
    "#node:net": {
      "bare": "bare-net",
      "default": "net"
    },
    "#node:http": {
      "bare": "bare-http1",
      "default": "http"
    },
    "#node:process": {
      "bare": "bare-process",
      "default": "process"
    }
  },
  "dependencies": {
    "b4a": "^1.6.0",
    "bare-events": "^2.0.0",
    "bare-fs": "^4.7.2",
    "bare-http1": "^4.0.0",
    "bare-net": "^1.0.0",
    "bare-os": "^3.0.0",
    "bare-path": "^3.0.0",
    "bare-process": "^4.0.0",
    "bare-stream": "^2.0.0",
    "bare-url": "^2.0.0",
    "compact-encoding": "^3.2.0",
    "hypercore-crypto": "^3.0.0",
    "hyperswarm": "^4.0.0",
    "protomux": "^3.0.0",
    "ready-resource": "^1.0.0",
    "bare-abstract-socket": "^1.0.0"
  },
  "devDependencies": {
    "@hyperswarm/testnet": "^3.0.0",
    "brittle": "^3.0.0",
    "corestore": "^7.0.0",
    "hyper-rooms": "file:../hyper-rooms"
  },
  "overrides": {}
}
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const b4a = require('b4a')

// https://en.wikipedia.org/wiki/Merkle_tree#Second_preimage_attack
const LEAF_TYPE = b4a.from([0])
const PARENT_TYPE = b4a.from([1])
const ROOT_TYPE = b4a.from([2])

const HYPERCORE = b4a.from('hypercore')

exports.keyPair = function (seed) {
  // key pairs might stay around for a while, so better not to use a default slab to avoid retaining it completely
  const slab = b4a.allocUnsafeSlow(
    sodium.crypto_sign_PUBLICKEYBYTES + sodium.crypto_sign_SECRETKEYBYTES
  )
  const publicKey = slab.subarray(0, sodium.crypto_sign_PUBLICKEYBYTES)
  const secretKey = slab.subarray(sodium.crypto_sign_PUBLICKEYBYTES)

  if (seed) sodium.crypto_sign_seed_keypair(publicKey, secretKey, seed)
  else sodium.crypto_sign_keypair(publicKey, secretKey)

  return {
    publicKey,
    secretKey
  }
}

exports.validateKeyPair = function (keyPair) {
  const pk = b4a.allocUnsafe(sodium.crypto_sign_PUBLICKEYBYTES)
  sodium.crypto_sign_ed25519_sk_to_pk(pk, keyPair.secretKey)
  return b4a.equals(pk, keyPair.publicKey)
}

exports.sign = function (message, secretKey) {
  // Dedicated slab for the signature, to avoid retaining unneeded mem and for security
  const signature = b4a.allocUnsafeSlow(sodium.crypto_sign_BYTES)
  sodium.crypto_sign_detached(signature, message, secretKey)
  return signature
}

exports.verify = function (message, signature, publicKey) {
  if (signature.byteLength !== sodium.crypto_sign_BYTES) return false
  if (publicKey.byteLength !== sodium.crypto_sign_PUBLICKEYBYTES) return false
  return sodium.crypto_sign_verify_detached(signature, message, publicKey)
}

exports.encrypt = function (message, publicKey) {
  const ciphertext = b4a.alloc(message.byteLength + sodium.crypto_box_SEALBYTES)
  sodium.crypto_box_seal(ciphertext, message, publicKey)
  return ciphertext
}

exports.decrypt = function (ciphertext, keyPair) {
  if (ciphertext.byteLength < sodium.crypto_box_SEALBYTES) return null

  const plaintext = b4a.alloc(ciphertext.byteLength - sodium.crypto_box_SEALBYTES)

  if (!sodium.crypto_box_seal_open(plaintext, ciphertext, keyPair.publicKey, keyPair.secretKey)) {
    return null
  }

  return plaintext
}

exports.encryptionKeyPair = function (seed) {
  const publicKey = b4a.alloc(sodium.crypto_box_PUBLICKEYBYTES)
  const secretKey = b4a.alloc(sodium.crypto_box_SECRETKEYBYTES)

  if (seed) {
    sodium.crypto_box_seed_keypair(publicKey, secretKey, seed)
  } else {
    sodium.crypto_box_keypair(publicKey, secretKey)
  }

  return {
    publicKey,
    secretKey
  }
}

exports.data = function (data) {
  const out = b4a.allocUnsafe(32)

  sodium.crypto_generichash_batch(out, [LEAF_TYPE, c.encode(c.uint64, data.byteLength), data])

  return out
}

exports.parent = function (a, b) {
  if (a.index > b.index) {
    const tmp = a
    a = b
    b = tmp
  }

  const out = b4a.allocUnsafe(32)

  sodium.crypto_generichash_batch(out, [
    PARENT_TYPE,
    c.encode(c.uint64, a.size + b.size),
    a.hash,
    b.hash
  ])

  return out
}

exports.tree = function (roots, out) {
  const buffers = new Array(3 * roots.length + 1)
  let j = 0

  buffers[j++] = ROOT_TYPE

  for (let i = 0; i < roots.length; i++) {
    const r = roots[i]
    buffers[j++] = r.hash
    buffers[j++] = c.encode(c.uint64, r.index)
    buffers[j++] = c.encode(c.uint64, r.size)
  }

  if (!out) out = b4a.allocUnsafe(32)
  sodium.crypto_generichash_batch(out, buffers)
  return out
}

exports.hash = function (data, out) {
  if (!out) out = b4a.allocUnsafe(32)
  if (!Array.isArray(data)) data = [data]

  sodium.crypto_generichash_batch(out, data)

  return out
}

exports.randomBytes = function (n) {
  const buf = b4a.allocUnsafe(n)
  sodium.randombytes_buf(buf)
  return buf
}

exports.discoveryKey = function (key) {
  if (!key || key.byteLength !== 32) throw new Error('Must pass a 32 byte buffer')
  // Discovery keys might stay around for a while, so better not to use slab memory (for better gc)
  const digest = b4a.allocUnsafeSlow(32)
  sodium.crypto_generichash(digest, HYPERCORE, key)
  return digest
}

if (sodium.sodium_free) {
  exports.free = function (secureBuf) {
    if (secureBuf.secure) sodium.sodium_free(secureBuf)
  }
} else {
  exports.free = function () {}
}

exports.namespace = function (name, count) {
  const ids = typeof count === 'number' ? range(count) : count

  // Namespaces are long-lived, so better to use a dedicated slab
  const buf = b4a.allocUnsafeSlow(32 * ids.length)

  const list = new Array(ids.length)

  // ns is ephemeral, so default slab
  const ns = b4a.allocUnsafe(33)
  sodium.crypto_generichash(ns.subarray(0, 32), typeof name === 'string' ? b4a.from(name) : name)

  for (let i = 0; i < list.length; i++) {
    list[i] = buf.subarray(32 * i, 32 * i + 32)
    ns[32] = ids[i]
    sodium.crypto_generichash(list[i], ns)
  }

  return list
}

function range(count) {
  const arr = new Array(count)
  for (let i = 0; i < count; i++) arr[i] = i
  return arr
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "hypercore-crypto",
  "version": "3.7.0",
  "description": "The crypto primitives used in hypercore, extracted into a separate module",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.6.6",
    "compact-encoding": "^3.0.0",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "brittle": "^3.5.0",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/hypercore-crypto.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/hypercore-crypto/issues"
  },
  "homepage": "https://github.com/mafintosh/hypercore-crypto"
}
const z32 = require('z32')
const b4a = require('b4a')

module.exports = {
  encode,
  decode,
  normalize,
  isValid
}

function encode (key) {
  if (!b4a.isBuffer(key)) throw new Error('Key must be a Buffer')
  if (key.byteLength !== 32) throw new Error('Key must be 32-bytes long')
  return z32.encode(key)
}

function decode (id) {
  if (b4a.isBuffer(id)) {
    if (id.byteLength !== 32) throw new Error('ID must be 32-bytes long')
    return id
  }
  if (typeof id === 'string') {
    if (id.startsWith('pear://')) id = id.slice(7).split('/')[0]
    if (id.length === 52) return z32.decode(id)
    if (id.length === 64) {
      const buf = b4a.from(id, 'hex')
      if (buf.byteLength === 32) return buf
    }
  }
  throw new Error('Invalid Hypercore key')
}

function normalize (any) {
  return encode(decode(any))
}

function isValid (any) {
  try {
    decode(any)
    return true
  } catch {
    return false
  }
}
{
  "name": "hypercore-id-encoding",
  "version": "1.3.0",
  "description": "Convert Hypercore keys to/from z-base32 or hex",
  "main": "index.js",
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.5.3",
    "z32": "^1.0.0"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "hypercore": "^10.0.0",
    "random-access-memory": "^6.0.0",
    "standard": "^17.1.0"
  },
  "license": "Apache-2.0",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/hypercore-id-encoding.git"
  },
  "keywords": [],
  "author": "",
  "bugs": {
    "url": "https://github.com/holepunchto/hypercore-id-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/hypercore-id-encoding#readme"
}
const c = require('compact-encoding')
const { getEncoding } = require('./spec/hyperschema')

const HyperdhtAddress = getEncoding('@hyperdht/address')

function decode(buf) {
  const addr = c.decode(HyperdhtAddress, buf)
  return addr
}

function encode(key, nodes) {
  return c.encode(HyperdhtAddress, { key, nodes })
}

module.exports = { decode, encode }
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "hyperdht-address",
  "version": "1.1.1",
  "description": "hyperdht-address",
  "main": "index.js",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    }
  },
  "files": [
    "package.json",
    "index.js",
    "index.d.ts",
    "spec"
  ],
  "devDependencies": {
    "b4a": "^1.8.0",
    "brittle": "^3.19.0",
    "lunte": "^1.2.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && lunte && brittle-bare test/index.js",
    "lint": "lunte"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/hyperdht-address.git"
  },
  "author": "Holepunch Inc",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/hyperdht-address/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperdht-address",
  "dependencies": {
    "compact-encoding": "^3.0.0",
    "hyperschema": "^1.20.1"
  }
}
// This file is autogenerated by the hyperschema compiler
// Schema Version: 2
/* eslint-disable camelcase */
/* eslint-disable quotes */
/* eslint-disable space-before-function-paren */

const { c } = require('hyperschema/runtime')

const VERSION = 2

// eslint-disable-next-line no-unused-vars
let version = VERSION

// @hyperdht/address.nodes
const encoding0_1 = c.array(c.ipv4Address)

// @hyperdht/address
const encoding0 = {
  preencode(state, m) {
    c.fixed32.preencode(state, m.key)
    state.end++ // max flag is 1 so always one byte

    if (version >= 2 && m.nodes) encoding0_1.preencode(state, m.nodes)
  },
  encode(state, m) {
    const flags = version >= 2 && m.nodes ? 1 : 0

    c.fixed32.encode(state, m.key)
    c.uint.encode(state, flags)

    if (version >= 2 && m.nodes) encoding0_1.encode(state, m.nodes)
  },
  decode(state) {
    const r0 = c.fixed32.decode(state)
    const flags = state.start < state.end ? c.uint.decode(state) : 0

    return {
      key: r0,
      nodes: version >= 2 && (flags & 1) !== 0 ? encoding0_1.decode(state) : null
    }
  }
}

function setVersion(v) {
  version = v
}

function encode(name, value, v = VERSION) {
  version = v
  return c.encode(getEncoding(name), value)
}

function decode(name, buffer, v = VERSION) {
  version = v
  return c.decode(getEncoding(name), buffer)
}

function getEnum(name) {
  switch (name) {
    default:
      throw new Error('Enum not found ' + name)
  }
}

function getEncoding(name) {
  switch (name) {
    case '@hyperdht/address':
      return encoding0
    default:
      throw new Error('Encoder not found ' + name)
  }
}

function getStruct(name, v = VERSION) {
  const enc = getEncoding(name)
  return {
    preencode(state, m) {
      version = v
      enc.preencode(state, m)
    },
    encode(state, m) {
      version = v
      enc.encode(state, m)
    },
    decode(state) {
      version = v
      return enc.decode(state)
    }
  }
}

const resolveStruct = getStruct // compat

module.exports = {
  resolveStruct,
  getStruct,
  getEnum,
  getEncoding,
  encode,
  decode,
  setVersion,
  version
}
const DHT = require('dht-rpc')
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const b4a = require('b4a')
const safetyCatch = require('safety-catch')
const m = require('./lib/messages')
const SocketPool = require('./lib/socket-pool')
const Persistent = require('./lib/persistent')
const Router = require('./lib/router')
const Cache = require('xache')
const Server = require('./lib/server')
const connect = require('./lib/connect')
const { FIREWALL, BOOTSTRAP_NODES, KNOWN_NODES, COMMANDS } = require('./lib/constants')
const { hash, createKeyPair } = require('./lib/crypto')
const RawStreamSet = require('./lib/raw-stream-set')
const ConnectionPool = require('./lib/connection-pool')
const { STREAM_NOT_CONNECTED } = require('./lib/errors')

const DEFAULTS = {
  ...DHT.DEFAULTS,
  connectionKeepAlive: 5000,
  randomPunchInterval: 20000
}

class HyperDHT extends DHT {
  constructor(opts = {}) {
    const port = opts.port || 49737
    const bootstrap = opts.bootstrap || BOOTSTRAP_NODES
    const nodes = opts.nodes || KNOWN_NODES

    super({ ...opts, port, bootstrap, nodes, filterNode })

    const { router, relayAddresses, persistent } = defaultCacheOpts(opts)

    this.defaultKeyPair = opts.keyPair || createKeyPair(opts.seed)
    this.listening = new Set()
    this.connectionKeepAlive =
      opts.connectionKeepAlive === false
        ? 0
        : opts.connectionKeepAlive || DEFAULTS.connectionKeepAlive

    // stats is inherited from dht-rpc so fwd the ones from there
    this.stats = {
      punches: { consistent: 0, random: 0, open: 0 },
      relaying: { attempts: 0, successes: 0, aborts: 0 },
      ...this.stats
    }
    this.rawStreams = new RawStreamSet(this)
    this.plugins = new Map()

    this._router = new Router(this, router)
    this._socketPool = new SocketPool(this, opts.host || '0.0.0.0')
    this._persistent = null
    this._validatedLocalAddresses = new Map()
    this._relayAddressesCache = new Cache(relayAddresses)

    this._deferRandomPunch = !!opts.deferRandomPunch
    this._lastRandomPunch = this._deferRandomPunch ? Date.now() : 0
    this._connectable = true
    this._randomPunchInterval = opts.randomPunchInterval || DEFAULTS.randomPunchInterval // min 20s between random punches...
    this._randomPunches = 0
    this._randomPunchLimit = 1 // set to one for extra safety for now

    this.once('persistent', () => {
      this._persistent = new Persistent(this, persistent)
      for (const plugin of this.plugins.values()) plugin.onpersistent()
    })

    this.on('network-change', () => {
      for (const server of this.listening) server.refresh()
    })

    this.on('network-update', () => {
      if (!this.online) return
      for (const server of this.listening) server.notifyOnline()
    })
  }

  static DEFAULTS = DEFAULTS

  connect(remotePublicKey, opts) {
    return connect(this, remotePublicKey, opts)
  }

  createServer(opts, onconnection) {
    if (typeof opts === 'function') return this.createServer({}, opts)
    if (opts && opts.onconnection) onconnection = opts.onconnection
    const s = new Server(this, opts)
    if (onconnection) s.on('connection', onconnection)
    return s
  }

  pool() {
    return new ConnectionPool(this)
  }

  async resume({ log = noop } = {}) {
    if (this._deferRandomPunch) this._lastRandomPunch = Date.now()
    await super.resume({ log })
    const resuming = []
    for (const server of this.listening) resuming.push(server.resume())
    log('Resuming hyperdht servers')
    await Promise.allSettled(resuming)
    log('Done, hyperdht fully resumed')
  }

  async suspend({ log = noop } = {}) {
    this._connectable = false // just so nothing gets connected during suspension
    const suspending = []
    for (const server of this.listening) suspending.push(server.suspend())
    log('Suspending all hyperdht servers')
    await Promise.allSettled(suspending)
    log('Done, clearing all raw streams')
    await this.rawStreams.clear()
    log('Done, suspending dht-rpc')
    await super.suspend({ log })
    log('Done, clearing raw streams again')
    await this.rawStreams.clear()
    log('Done, hyperdht fully suspended')
    this._connectable = true
  }

  async destroy({ force = false } = {}) {
    if (!force) {
      const closing = []
      for (const server of this.listening) closing.push(server.close())
      await Promise.allSettled(closing)
    }
    this._router.destroy()
    if (this._persistent) this._persistent.destroy()
    for (const plugin of this.plugins.values()) plugin.destroy()
    await this.rawStreams.clear()
    await this._socketPool.destroy()
    await super.destroy()
  }

  async validateLocalAddresses(addresses) {
    const list = []
    const socks = []
    const waiting = []

    for (const addr of addresses) {
      const { host } = addr

      if (this._validatedLocalAddresses.has(host)) {
        if (await this._validatedLocalAddresses.get(host)) {
          list.push(addr)
        }
        continue
      }

      const sock = this.udx.createSocket()
      try {
        sock.bind(0, host)
      } catch {
        this._validatedLocalAddresses.set(host, Promise.resolve(false))
        continue
      }

      socks.push(sock)

      // semi terrible heuristic until we proper fix local connections by racing them to the remote...
      const promise = new Promise((resolve) => {
        sock.on('message', () => resolve(true))
        setTimeout(() => resolve(false), 500)
        sock.trySend(b4a.alloc(1), sock.address().port, addr.host)
      })

      this._validatedLocalAddresses.set(host, promise)
      waiting.push(addr)
    }

    for (const addr of waiting) {
      const { host } = addr
      if (this._validatedLocalAddresses.has(host)) {
        if (await this._validatedLocalAddresses.get(host)) {
          list.push(addr)
        }
        continue
      }
    }

    for (const sock of socks) await sock.close()

    return list
  }

  findPeer(publicKey, opts = {}) {
    const target = opts.hash === false ? publicKey : hash(publicKey)
    opts = { ...opts, map: mapFindPeer }
    return this.query({ target, command: COMMANDS.FIND_PEER, value: null }, opts)
  }

  lookup(target, opts = {}) {
    opts = { ...opts, map: mapLookup }
    return this.query({ target, command: COMMANDS.LOOKUP, value: null }, opts)
  }

  lookupAndUnannounce(target, keyPair, opts = {}) {
    const unannounces = []
    const dht = this
    const userCommit = opts.commit || noop
    const signUnannounce = opts.signUnannounce || Persistent.signUnannounce

    if (this._persistent !== null) {
      // unlink self
      this._persistent.unannounce(target, keyPair.publicKey)
    }

    opts = { ...opts, map, commit }
    return this.query({ target, command: COMMANDS.LOOKUP, value: null }, opts)

    async function commit(reply, dht, query) {
      await Promise.all(unannounces) // can never fail, caught below
      return userCommit(reply, dht, query)
    }

    function map(reply) {
      const data = mapLookup(reply)

      if (!data || !data.token) return data

      let found = data.peers.length >= 20
      for (let i = 0; !found && i < data.peers.length; i++) {
        found = b4a.equals(data.peers[i].publicKey, keyPair.publicKey)
      }

      if (!found) return data

      if (!data.from.id) return data

      unannounces.push(
        dht
          ._requestUnannounce(keyPair, dht, target, data.token, data.from, signUnannounce)
          .catch(safetyCatch)
      )

      return data
    }
  }

  unannounce(target, keyPair, opts = {}) {
    return this.lookupAndUnannounce(target, keyPair, opts).finished()
  }

  announce(target, keyPair, relayAddresses, opts = {}) {
    const signAnnounce = opts.signAnnounce || Persistent.signAnnounce
    const bump = opts.bump || 0

    opts = { ...opts, commit }

    return opts.clear ? this.lookupAndUnannounce(target, keyPair, opts) : this.lookup(target, opts)

    function commit(reply, dht) {
      return dht._requestAnnounce(
        keyPair,
        dht,
        target,
        reply.token,
        reply.from,
        relayAddresses,
        signAnnounce,
        bump
      )
    }
  }

  async immutableGet(target, opts = {}) {
    opts = { ...opts, map: mapImmutable }

    const query = this.query({ target, command: COMMANDS.IMMUTABLE_GET, value: null }, opts)
    const check = b4a.allocUnsafe(32)

    for await (const node of query) {
      const { value } = node
      sodium.crypto_generichash(check, value)
      if (b4a.equals(check, target)) return node
    }

    return null
  }

  async immutablePut(value, opts = {}) {
    const target = b4a.allocUnsafe(32)
    sodium.crypto_generichash(target, value)

    opts = {
      ...opts,
      map: mapImmutable,
      commit(reply, dht) {
        return dht.request(
          { token: reply.token, target, command: COMMANDS.IMMUTABLE_PUT, value },
          reply.from
        )
      }
    }

    const query = this.query({ target, command: COMMANDS.IMMUTABLE_GET, value: null }, opts)
    await query.finished()

    return { hash: target, closestNodes: query.closestNodes }
  }

  async mutableGet(publicKey, opts = {}) {
    let refresh = opts.refresh || null
    let signed = null
    let result = null

    opts = { ...opts, map: mapMutable, commit: refresh ? commit : null }

    const target = b4a.allocUnsafe(32)
    sodium.crypto_generichash(target, publicKey)

    const userSeq = opts.seq || 0
    const query = this.query(
      { target, command: COMMANDS.MUTABLE_GET, value: c.encode(c.uint, userSeq) },
      opts
    )
    const latest = opts.latest !== false

    for await (const node of query) {
      if (result && node.seq <= result.seq) continue
      if (
        node.seq < userSeq ||
        !Persistent.verifyMutable(node.signature, node.seq, node.value, publicKey)
      )
        continue
      if (!latest) return node
      if (!result || node.seq > result.seq) result = node
    }

    return result

    function commit(reply, dht) {
      if (!signed && result && refresh) {
        if (refresh(result)) {
          signed = c.encode(m.mutablePutRequest, {
            publicKey,
            seq: result.seq,
            value: result.value,
            signature: result.signature
          })
        } else {
          refresh = null
        }
      }

      return signed
        ? dht.request(
            { token: reply.token, target, command: COMMANDS.MUTABLE_PUT, value: signed },
            reply.from
          )
        : Promise.resolve(null)
    }
  }

  async mutablePut(keyPair, value, opts = {}) {
    const signMutable = opts.signMutable || Persistent.signMutable

    const target = b4a.allocUnsafe(32)
    sodium.crypto_generichash(target, keyPair.publicKey)

    const seq = opts.seq || 0
    const signature = await signMutable(seq, value, keyPair)

    const signed = c.encode(m.mutablePutRequest, {
      publicKey: keyPair.publicKey,
      seq,
      value,
      signature
    })

    opts = {
      ...opts,
      map: mapMutable,
      commit(reply, dht) {
        return dht.request(
          { token: reply.token, target, command: COMMANDS.MUTABLE_PUT, value: signed },
          reply.from
        )
      }
    }

    // use seq = 0, for the query part here, as we don't care about the actual values
    const query = this.query(
      { target, command: COMMANDS.MUTABLE_GET, value: c.encode(c.uint, 0) },
      opts
    )
    await query.finished()

    return { publicKey: keyPair.publicKey, closestNodes: query.closestNodes, seq, signature }
  }

  onrequest(req) {
    switch (req.command) {
      case COMMANDS.PEER_HANDSHAKE: {
        this._router.onpeerhandshake(req)
        return true
      }
      case COMMANDS.PEER_HOLEPUNCH: {
        this._router.onpeerholepunch(req)
        return true
      }
    }

    if (this._persistent === null || this.id === null) return false

    switch (req.command) {
      case COMMANDS.FIND_PEER: {
        this._persistent.onfindpeer(req)
        return true
      }
      case COMMANDS.LOOKUP: {
        this._persistent.onlookup(req)
        return true
      }
      case COMMANDS.ANNOUNCE: {
        this._persistent.onannounce(req)
        return true
      }
      case COMMANDS.UNANNOUNCE: {
        this._persistent.onunannounce(req)
        return true
      }
      case COMMANDS.MUTABLE_PUT: {
        this._persistent.onmutableput(req)
        return true
      }
      case COMMANDS.MUTABLE_GET: {
        this._persistent.onmutableget(req)
        return true
      }
      case COMMANDS.IMMUTABLE_PUT: {
        this._persistent.onimmutableput(req)
        return true
      }
      case COMMANDS.IMMUTABLE_GET: {
        this._persistent.onimmutableget(req)
        return true
      }
      case COMMANDS.PLUGIN: {
        this._persistent.onplugin(req)
        return true
      }
    }

    return false
  }

  static keyPair(seed) {
    return createKeyPair(seed)
  }

  static hash(data) {
    return hash(data)
  }

  static connectRawStream(encryptedStream, rawStream, remoteId) {
    const stream = encryptedStream.rawStream

    if (!stream.connected) throw STREAM_NOT_CONNECTED()

    rawStream.connect(stream.socket, remoteId, stream.remotePort, stream.remoteHost)
  }

  createRawStream(opts) {
    return this.rawStreams.add(opts)
  }

  async _requestAnnounce(keyPair, dht, target, token, from, relayAddresses, sign, bump) {
    const ann = {
      peer: {
        publicKey: keyPair.publicKey,
        relayAddresses: relayAddresses || []
      },
      refresh: null,
      signature: null,
      bump
    }

    ann.signature = await sign(target, token, from.id, ann, keyPair)

    const value = c.encode(m.announce, ann)

    return dht.request(
      {
        token,
        target,
        command: COMMANDS.ANNOUNCE,
        value
      },
      from
    )
  }

  async _requestUnannounce(keyPair, dht, target, token, from, sign) {
    const unann = {
      peer: {
        publicKey: keyPair.publicKey,
        relayAddresses: []
      },
      signature: null
    }

    unann.signature = await sign(target, token, from.id, unann, keyPair)

    const value = c.encode(m.announce, unann)

    return dht.request(
      {
        token,
        target,
        command: COMMANDS.UNANNOUNCE,
        value
      },
      from
    )
  }

  register(name, plugin) {
    this.plugins.set(name, plugin)
    plugin.onregister(this)
  }
}

HyperDHT.BOOTSTRAP = BOOTSTRAP_NODES
HyperDHT.FIREWALL = FIREWALL

module.exports = HyperDHT

function mapLookup(node) {
  if (!node.value) return null

  try {
    const l = c.decode(m.lookupRawReply, node.value)

    return {
      token: node.token,
      from: node.from,
      to: node.to,
      peers: l.peers,
      bump: l.bump
    }
  } catch {
    return null
  }
}

function mapFindPeer(node) {
  if (!node.value) return null

  try {
    return {
      token: node.token,
      from: node.from,
      to: node.to,
      peer: c.decode(m.peer, node.value)
    }
  } catch {
    return null
  }
}

function mapImmutable(node) {
  if (!node.value) return null

  return {
    token: node.token,
    from: node.from,
    to: node.to,
    value: node.value
  }
}

function mapMutable(node) {
  if (!node.value) return null

  try {
    const { seq, value, signature } = c.decode(m.mutableGetResponse, node.value)

    return {
      token: node.token,
      from: node.from,
      to: node.to,
      seq,
      value,
      signature
    }
  } catch {
    return null
  }
}

function noop() {}

function filterNode(node) {
  // always skip these testnet nodes that got mixed in by accident, until they get updated
  return (
    !(node.port === 49738 && (node.host === '134.209.28.98' || node.host === '167.99.142.185')) &&
    !(node.port === 9400 && node.host === '35.233.47.252') &&
    !(node.host === '150.136.142.116')
  )
}

const defaultMaxSize = 65536
const defaultMaxAge = 20 * 60 * 1000 // 20 minutes

function defaultCacheOpts(opts) {
  const maxSize = opts.maxSize || defaultMaxSize
  const maxAge = opts.maxAge || defaultMaxAge

  return {
    router: {
      forwards: { maxSize, maxAge }
    },
    relayAddresses: { maxSize: Math.min(maxSize, 512), maxAge: 0 },
    persistent: {
      records: { maxSize, maxAge },
      refreshes: { maxSize, maxAge },
      mutables: {
        maxSize: (maxSize / 2) | 0,
        maxAge: opts.maxAge || 48 * 60 * 60 * 1000 // 48 hours
      },
      immutables: {
        maxSize: (maxSize / 2) | 0,
        maxAge: opts.maxAge || 48 * 60 * 60 * 1000 // 48 hours
      },
      bumps: { maxSize, maxAge }
    }
  }
}
const safetyCatch = require('safety-catch')
const c = require('compact-encoding')
const Signal = require('signal-promise')
const { encodeUnslab } = require('./encode')
const Sleeper = require('./sleeper')
const m = require('./messages')
const Persistent = require('./persistent')
const { COMMANDS } = require('./constants')

const MIN_ACTIVE = 3

module.exports = class Announcer {
  constructor(dht, keyPair, target, opts = {}) {
    this.dht = dht
    this.keyPair = keyPair
    this.target = target
    this.relays = []
    this.relayAddresses = []
    this.stopped = false
    this.suspended = false
    this.record = encodeUnslab(m.peer, { publicKey: keyPair.publicKey, relayAddresses: [] })
    this.online = new Signal()

    this._refreshing = false
    this._closestNodes = null
    this._active = null
    this._sleeper = new Sleeper()
    this._resumed = new Signal()
    this._signAnnounce = opts.signAnnounce || Persistent.signAnnounce
    this._signUnannounce = opts.signUnannounce || Persistent.signUnannounce
    this._updating = null
    this._activeQuery = null
    this._unannouncing = null

    this._serverRelays = [new Map(), new Map(), new Map()]
  }

  isRelay(addr) {
    const id = addr.host + ':' + addr.port
    const [a, b, c] = this._serverRelays
    return a.has(id) || b.has(id) || c.has(id)
  }

  async suspend({ log = noop } = {}) {
    if (this.suspended) return
    this.suspended = true

    log('Suspending announcer')

    // Suspend has its own sleep logic
    // so we don't want to hang on this one
    this.online.notify()

    if (this._activeQuery) this._activeQuery.destroy()

    this._sleeper.resume()
    if (this._updating) await this._updating
    log('Suspending announcer (post update)')

    if (this.suspended === false || this.stopped) return

    log('Suspending announcer (pre unannounce)')
    await this._unannounceCurrent()
    log('Suspending announcer (post unannounce)')
  }

  resume() {
    if (!this.suspended) return
    this.suspended = false

    this.refresh()
    this._sleeper.resume()
    this._resumed.notify()
  }

  refresh() {
    if (this.stopped) return
    this._refreshing = true
  }

  async start() {
    if (this.stopped) return
    this._active = this._runUpdate()
    await this._active
    if (this.stopped) return
    this._active = this._background()
  }

  async stop() {
    this.stopped = true
    this.online.notify() // Break out of the _background loop if we're offline
    this._sleeper.resume()
    this._resumed.notify()
    await this._active
    await this._unannounceCurrent()
  }

  async _unannounceCurrent() {
    while (this._unannouncing !== null) await this._unannouncing
    const un = (this._unannouncing = this._unannounceAll(this._serverRelays[2].values()))
    await this._unannouncing
    if (un === this._unannouncing) this._unannouncing = null
  }

  async _background() {
    while (!this.dht.destroyed && !this.stopped) {
      try {
        this._refreshing = false

        // ~5min +-
        for (let i = 0; i < 100 && !this.stopped && !this._refreshing && !this.suspended; i++) {
          const pings = []

          for (const node of this._serverRelays[2].values()) {
            pings.push(this.dht.ping(node))
          }

          const active = await resolved(pings)
          if (active < Math.min(pings.length, MIN_ACTIVE)) {
            this.refresh() // we lost too many relay nodes, retry all
          }

          if (this.stopped) return

          if (!this.suspended && !this._refreshing) await this._sleeper.pause(3000)
        }

        while (!this.stopped && this.suspended) await this._resumed.wait()

        if (!this.stopped) await this._runUpdate()

        while (!this.dht.online && !this.stopped && !this.suspended) {
          // Being offline can make _background repeat very quickly
          // So wait until we're back online
          await this.online.wait()
        }
      } catch (err) {
        safetyCatch(err)
      }
    }
  }

  async _runUpdate() {
    this._updating = this._update()
    await this._updating
    this._updating = null
  }

  async _update() {
    while (this._unannouncing) await this._unannouncing

    this._cycle()

    const q = (this._activeQuery = this.dht.findPeer(this.target, {
      hash: false,
      nodes: this._closestNodes
    }))

    try {
      await q.finished()
    } catch {
      // ignore failures...
    }

    this._activeQuery = null

    if (this.stopped || this.suspended) return

    const ann = []
    const replies = pickBest(q.closestReplies)

    const relays = []
    const relayAddresses = []

    if (!this.dht.firewalled) {
      const addr = this.dht.remoteAddress()
      if (addr) relayAddresses.push(addr)
    }

    for (const msg of replies) {
      ann.push(this._commit(msg, relays, relayAddresses))
    }

    await Promise.allSettled(ann)
    if (this.stopped || this.suspended) return

    this._closestNodes = q.closestNodes
    this.relays = relays
    this.relayAddresses = relayAddresses

    const removed = []
    for (const [key, value] of this._serverRelays[1]) {
      if (!this._serverRelays[2].has(key)) removed.push(value)
    }

    await this._unannounceAll(removed)
  }

  _unannounceAll(relays) {
    const unann = []
    for (const r of relays) unann.push(this._unannounce(r))
    return Promise.allSettled(unann)
  }

  async _unannounce(to) {
    const unann = {
      peer: {
        publicKey: this.keyPair.publicKey,
        relayAddresses: []
      },
      refresh: null,
      signature: null
    }

    const { from, token, value } = await this.dht.request(
      {
        token: null,
        command: COMMANDS.FIND_PEER,
        target: this.target,
        value: null
      },
      to
    )

    if (!token || !from.id || !value) return

    unann.signature = await this._signUnannounce(this.target, token, from.id, unann, this.keyPair)

    await this.dht.request(
      {
        token,
        command: COMMANDS.UNANNOUNCE,
        target: this.target,
        value: c.encode(m.announce, unann)
      },
      to
    )
  }

  async _commit(msg, relays, relayAddresses) {
    const ann = {
      peer: {
        publicKey: this.keyPair.publicKey,
        relayAddresses: []
      },
      refresh: null,
      signature: null
    }

    ann.signature = await this._signAnnounce(this.target, msg.token, msg.from.id, ann, this.keyPair)

    const res = await this.dht.request(
      {
        token: msg.token,
        command: COMMANDS.ANNOUNCE,
        target: this.target,
        value: c.encode(m.announce, ann)
      },
      msg.from
    )

    if (res.error !== 0) return

    if (relayAddresses.length < 3) relayAddresses.push({ host: msg.from.host, port: msg.from.port })
    relays.push({ relayAddress: msg.from, peerAddress: msg.to })

    this._serverRelays[2].set(msg.from.host + ':' + msg.from.port, msg.from)
  }

  _cycle() {
    const tmp = this._serverRelays[0]
    this._serverRelays[0] = this._serverRelays[1]
    this._serverRelays[1] = this._serverRelays[2]
    this._serverRelays[2] = tmp
    tmp.clear()
  }
}

function resolved(ps) {
  let replied = 0
  let ticks = ps.length + 1

  return new Promise((resolve) => {
    for (const p of ps) p.then(push, tick)
    tick()

    function push(v) {
      replied++
      tick()
    }

    function tick() {
      if (--ticks === 0) resolve(replied)
    }
  })
}

function pickBest(replies) {
  // TODO: pick the ones closest to us RTT wise
  return replies.slice(0, 3)
}

function noop() {}
const NoiseSecretStream = require('@hyperswarm/secret-stream')
const b4a = require('b4a')
const relay = require('blind-relay')
const { isReserved, isBogon } = require('bogon')
const safetyCatch = require('safety-catch')
const unslab = require('unslab')
const Semaphore = require('./semaphore')
const NoiseWrap = require('./noise-wrap')
const SecurePayload = require('./secure-payload')
const Holepuncher = require('./holepuncher')
const Sleeper = require('./sleeper')
const { FIREWALL, ERROR } = require('./constants')
const { unslabbedHash } = require('./crypto')
const {
  CANNOT_HOLEPUNCH,
  HANDSHAKE_INVALID,
  HOLEPUNCH_ABORTED,
  HOLEPUNCH_INVALID,
  HOLEPUNCH_PROBE_TIMEOUT,
  HOLEPUNCH_DOUBLE_RANDOMIZED_NATS,
  PEER_CONNECTION_FAILED,
  PEER_NOT_FOUND,
  REMOTE_ABORTED,
  REMOTE_NOT_HOLEPUNCHABLE,
  REMOTE_NOT_HOLEPUNCHING,
  SERVER_ERROR,
  SERVER_INCOMPATIBLE,
  RELAY_ABORTED,
  SUSPENDED
} = require('./errors')
const { decode } = require('hypercore-id-encoding')
const HyperDHTAddress = require('hyperdht-address')

module.exports = function connect(dht, publicKey, opts = {}) {
  const pool = opts.pool || null

  const { key, nodes: providedNodes } = HyperDHTAddress.decode(
    b4a.isBuffer(publicKey) ? publicKey : decode(publicKey)
  )
  publicKey = key

  if (pool && pool.has(publicKey)) return pool.get(publicKey)

  publicKey = unslab(publicKey)

  opts.relayAddresses = opts.relayAddresses || providedNodes || []
  const keyPair = opts.keyPair || dht.defaultKeyPair
  const relayThrough = selectRelay(opts.relayThrough || null)
  const encryptedSocket = (opts.createSecretStream || defaultCreateSecretStream)(true, null, {
    publicKey: keyPair.publicKey,
    remotePublicKey: publicKey,
    autoStart: false,
    keepAlive: dht.connectionKeepAlive
  })

  // in case a socket is made during suspended state, destroy it immediately
  if (dht.suspended || !dht._connectable) {
    encryptedSocket.destroy(SUSPENDED())
    return encryptedSocket
  }

  if (pool) pool._attachStream(encryptedSocket, false)

  const id = b4a.toString(publicKey, 'hex')
  const c = {
    id,
    dht,
    session: dht.session(),
    relayAddresses: opts.relayAddresses,
    remoteRelayAddresses: [],
    pool,
    round: 0,
    target: unslabbedHash(publicKey),
    remotePublicKey: publicKey,
    reusableSocket: !!opts.reusableSocket,
    handshake: (opts.createHandshake || defaultCreateHandshake)(keyPair, publicKey),
    request: null,
    requesting: false,
    lan: opts.localConnection !== false,
    firewall: FIREWALL.UNKNOWN,
    rawStream: dht.createRawStream({ framed: true, firewall }),
    connect: null,
    query: null,
    puncher: null,
    payload: null,
    passiveConnectTimeout: null,
    serverSocket: null,
    serverAddress: null,
    onsocket: null,
    sleeper: new Sleeper(),
    encryptedSocket,

    // Relay state
    relayTimeout: null,
    relayThrough,
    relayToken: relayThrough ? relay.token() : null,
    relaySocket: null,
    relayClient: null,
    relayPaired: false,
    relayKeepAlive: opts.relayKeepAlive || 5000
  }

  // If the raw stream receives an error signal pre connect (ie from the firewall hook), make sure
  // to forward that to the encrypted socket for proper teardown
  c.rawStream.on('error', autoDestroy)
  c.rawStream.once('connect', () => {
    c.rawStream.removeListener('error', autoDestroy)
  })

  encryptedSocket.on('close', function () {
    if (c.passiveConnectTimeout) clearPassiveConnectTimeout(c)
    if (c.query) c.query.destroy()
    if (c.puncher) c.puncher.destroy()
    if (c.rawStream) c.rawStream.destroy()
    c.session.destroy()
    c.sleeper.resume()
  })

  // Safe to run in the background - never throws
  if (dht.suspended) encryptedSocket.destroy(SUSPENDED())
  else connectAndHolepunch(c, opts)

  return encryptedSocket

  function autoDestroy(err) {
    maybeDestroyEncryptedSocket(c, err)
  }

  function firewall(socket, port, host) {
    // Check if the traffic originated from the socket on which we're expecting relay traffic. If so,
    // we haven't hole punched yet and the other side is just sending us traffic through the relay.
    if (c.relaySocket && isRelay(c.relaySocket, socket, port, host)) {
      return false
    }

    if (c.onsocket) {
      c.onsocket(socket, port, host)
    } else {
      c.serverSocket = socket
      c.serverAddress = { port, host }
    }
    return false
  }
}

function isDone(c) {
  // we are destroying or the puncher is connected - done
  if (c.encryptedSocket.destroying || !!(c.puncher && c.puncher.connected)) {
    return true
  }
  // not destroying, but no raw stream - def not done
  if (c.encryptedSocket.rawStream === null) {
    return false
  }
  // we are relayed, but the puncher is not done yet
  if (c.relaySocket && !!(c.puncher && !c.puncher.connected && !c.puncher.destroyed)) {
    return false
  }
  // we are done
  return true
}

async function retryRoute(c, route) {
  const ref = c.dht._socketPool.lookup(route.socket)

  if (!ref) {
    if (route.socket === c.dht.socket) {
      await connectThroughNode(c, route.address, c.dht.socket)
    }
    return
  }

  ref.active()

  try {
    await connectThroughNode(c, route.address, route.socket)
  } catch {
    // if error, just ignore, and continue through the existing strat
  }

  ref.inactive()
}

async function connectAndHolepunch(c, opts) {
  const route = c.reusableSocket ? c.dht._socketPool.routes.get(c.remotePublicKey) : null

  if (route) {
    await retryRoute(c, route)
    if (isDone(c)) return
  }

  await findAndConnect(c, opts)
  if (isDone(c)) return

  if (!c.connect) {
    // TODO: just a quick fix for now, should retry prob
    maybeDestroyEncryptedSocket(c, HANDSHAKE_INVALID())
    return
  }

  await holepunch(c, opts)
}

function getFirstRemoteAddress(addrs, serverAddress) {
  for (const addr of addrs) {
    if (isBogon(addr.host)) continue
    return addr
  }

  return serverAddress
}

async function holepunch(c, opts) {
  let { relayAddress, serverAddress, clientAddress, payload } = c.connect

  const remoteHolepunchable = !!(payload.holepunch && payload.holepunch.relays.length)

  const relayed = diffAddress(serverAddress, relayAddress)

  if (payload.firewall === FIREWALL.OPEN || (relayed && !remoteHolepunchable)) {
    const addr = getFirstRemoteAddress(payload.addresses4, serverAddress)
    if (addr) {
      const socket = c.dht.socket
      c.dht.stats.punches.open++
      c.onsocket(socket, addr.port, addr.host)
      return
    }
    // TODO: check all addresses also obvs
  }

  const onabort = () => {
    c.session.destroy()
    maybeDestroyEncryptedSocket(c, HOLEPUNCH_ABORTED())
  }

  if (c.firewall === FIREWALL.OPEN) {
    c.passiveConnectTimeout = setTimeout(onabort, 10000)
    return
  }

  // TODO: would be better to just try local addrs in the background whilst continuing with other strategies...
  if (c.lan && relayed && clientAddress.host === serverAddress.host) {
    const serverAddresses = payload.addresses4.filter(onlyNonReserved)

    if (serverAddresses.length > 0) {
      const myAddresses = Holepuncher.localAddresses(c.dht.io.serverSocket)
      const addr = Holepuncher.matchAddress(myAddresses, serverAddresses) || serverAddresses[0]

      const socket = c.dht.io.serverSocket
      try {
        await c.dht.ping(addr)
      } catch {
        maybeDestroyEncryptedSocket(c, HOLEPUNCH_ABORTED())
        return
      }
      c.onsocket(socket, addr.port, addr.host)
      return
    }
  }

  if (!remoteHolepunchable) {
    maybeDestroyEncryptedSocket(c, CANNOT_HOLEPUNCH())
    return
  }

  c.puncher = new Holepuncher(c.dht, c.session, true, payload.firewall)

  c.puncher.onconnect = c.onsocket
  c.puncher.onabort = onabort

  const serverRelay = pickServerRelay(payload.holepunch.relays, relayAddress)

  // Begin holepunching!

  let probe
  try {
    probe = await probeRound(c, opts.fastOpen === false ? null : serverAddress, serverRelay, true)
  } catch (err) {
    destroyPuncher(c)
    // TODO: we should retry here with some of the other relays, bail for now
    maybeDestroyEncryptedSocket(c, err)
    return
  }

  if (isDone(c) || !probe) return
  const { token, peerAddress } = probe

  // If the relay the server picked is the same as the relay the client picked,
  // then we can use the peerAddress that round one indicates the server wants to use.
  // This shaves off a roundtrip if the server chose to reroll its socket due to some NAT
  // issue with the first one it picked (ie mobile nat inconsistencies...).
  // If the relays were different, then the server would not have a UDP session open on this address
  // to the client relay, which round2 uses.
  if (
    !diffAddress(serverRelay.relayAddress, relayAddress) &&
    diffAddress(serverAddress, peerAddress)
  ) {
    serverAddress = peerAddress
    await c.puncher.openSession(serverAddress)
    if (isDone(c)) return
  }

  // TODO: still continue here if a local connection might work, but then do not holepunch...
  if (
    opts.holepunch &&
    !opts.holepunch(
      c.puncher.remoteFirewall,
      c.puncher.nat.firewall,
      c.puncher.remoteAddresses,
      c.puncher.nat.addresses
    )
  ) {
    await abort(c, serverRelay, HOLEPUNCH_ABORTED('Client aborted holepunch'))
    return
  }

  try {
    await roundPunch(c, serverAddress, token, relayAddress, serverRelay, false)
  } catch (err) {
    destroyPuncher(c)
    // TODO: retry with another relay?
    maybeDestroyEncryptedSocket(c, err)
  }
}

async function connectThroughNodes(c, addresses, socket) {
  for (const address of addresses) {
    if (isDone(c) || c.connect) return

    c.remoteRelayAddresses.push(address)
    await connectThroughNode(c, address, socket)
  }
}

async function findAndConnect(c, opts) {
  let attempts = 0
  let relayAddresses =
    opts.relayAddresses && opts.relayAddresses.length ? opts.relayAddresses : null

  if (!relayAddresses) {
    const cachedRelayAddresses = c.dht._relayAddressesCache.get(c.id)
    if (cachedRelayAddresses) relayAddresses = cachedRelayAddresses
  }

  if (c.dht._persistent) {
    // check if we know the route ourself...
    const route = c.dht._router.get(c.target)
    if (route && route.relay !== null) {
      relayAddresses = [{ host: route.relay.host, port: route.relay.port }]
    }
  }

  // 2 is how many parallel connect attempts we want to do, we can make this configurable
  const preConnect = relayAddresses !== null && relayAddresses.length > 0
  const sem = new Semaphore(preConnect ? 3 : 2)
  const signal = sem.signal.bind(sem)
  const tries = relayAddresses !== null ? 2 : 1

  if (preConnect) {
    await sem.wait()
    connectThroughNodes(c, relayAddresses, null).then(signal, signal)
  }

  try {
    for (let i = 0; i < tries && !isDone(c) && !c.connect; i++) {
      c.query = c.dht.findPeer(c.target, {
        hash: false,
        session: c.session,
        nodes: relayAddresses,
        retries: 3
      })

      for await (const data of c.query) {
        await sem.wait()
        if (isDone(c)) return

        if (c.connect) {
          sem.signal()
          break
        }

        // Skip node already run via preConnect
        if (preConnect && relayAddresses && isRelayAddress(relayAddresses, data)) {
          sem.signal()
          continue
        }

        c.remoteRelayAddresses.push(data.from)
        attempts++
        connectThroughNode(c, data.from, null).then(signal, signal)
      }

      relayAddresses = null

      if (attempts > 0) await sem.flush()
    }

    c.query = null
    if (isDone(c)) return

    // flush the semaphore
    await sem.flush()
    if (isDone(c)) return
  } catch (err) {
    c.query = null
    maybeDestroyEncryptedSocket(c, err)
    return
  }

  if (!c.connect) {
    maybeDestroyEncryptedSocket(c, attempts ? PEER_CONNECTION_FAILED() : PEER_NOT_FOUND())
  }
}

async function connectThroughNode(c, address, socket) {
  if (!c.requesting) {
    // If we have a stable server address, send it over now
    const addr = c.dht.remoteAddress()
    const localAddrs = c.lan ? Holepuncher.localAddresses(c.dht.io.serverSocket) : null
    const addresses4 = []

    if (addr) addresses4.push(addr)
    if (localAddrs) addresses4.push(...localAddrs)

    c.firewall = addr ? FIREWALL.OPEN : FIREWALL.UNKNOWN
    c.requesting = true
    c.request = await c.handshake.send({
      error: ERROR.NONE,
      firewall: c.firewall,
      holepunch: null,
      addresses4,
      addresses6: [],
      udx: {
        reusableSocket: c.reusableSocket,
        id: c.rawStream.id,
        seq: 0
      },
      secretStream: {},
      relayThrough: c.relayThrough ? { publicKey: c.relayThrough, token: c.relayToken } : null
    })
    if (isDone(c)) return
  }

  const { serverAddress, clientAddress, relayed, noise } = await c.dht._router.peerHandshake(
    c.target,
    { noise: c.request, socket, session: c.session },
    address
  )
  if (isDone(c) || c.connect) return

  const payload = await c.handshake.recv(noise)
  if (isDone(c) || !payload) return

  if (payload.version !== 1) {
    maybeDestroyEncryptedSocket(c, SERVER_INCOMPATIBLE())
    return
  }
  if (payload.error !== ERROR.NONE) {
    maybeDestroyEncryptedSocket(c, SERVER_ERROR())
    return
  }
  if (!payload.udx) {
    maybeDestroyEncryptedSocket(c, SERVER_ERROR('Server did not send UDX data'))
    return
  }

  const hs = c.handshake.final()

  c.handshake = null
  c.request = null
  c.requesting = false
  c.connect = {
    relayed,
    relayAddress: address,
    clientAddress,
    serverAddress,
    payload
  }

  c.payload = new SecurePayload(hs.holepunchSecret)

  c.onsocket = function (socket, port, host) {
    if (c.rawStream === null) return // Already hole punched

    if (c.rawStream.connected) {
      const remoteChanging = c.rawStream.changeRemote(socket, c.connect.payload.udx.id, port, host)

      if (remoteChanging) remoteChanging.catch(safetyCatch)
    } else {
      // cache the relay addrs for a future reconnect, we prefer the remote one so they
      // can give us the correct ones from their pov
      if (payload.relayAddresses && payload.relayAddresses.length) {
        c.dht._relayAddressesCache.set(c.id, payload.relayAddresses)
      } else if (c.remoteRelayAddresses.length) {
        c.dht._relayAddressesCache.set(c.id, c.remoteRelayAddresses)
      }

      c.rawStream.connect(socket, c.connect.payload.udx.id, port, host)
      c.encryptedSocket.start(c.rawStream, { handshake: hs })
    }

    if (c.reusableSocket && payload.udx.reusableSocket) {
      c.dht._socketPool.routes.add(c.remotePublicKey, c.rawStream)
    }

    if (c.puncher) {
      c.puncher.onabort = noop
      c.puncher.destroy()
    }

    if (c.passiveConnectTimeout) {
      clearPassiveConnectTimeout(c)
    }

    c.rawStream = null
  }

  if (payload.relayThrough || c.relayThrough) {
    relayConnection(c, c.relayThrough, payload, hs)
  }

  if (c.serverSocket) {
    c.onsocket(c.serverSocket, c.serverAddress.port, c.serverAddress.host)
    return
  }

  if (!relayed) {
    c.onsocket(socket || c.dht.socket, address.port, address.host)
  }

  c.session.destroy()
}

async function updateHolepunch(c, peerAddress, relayAddr, payload) {
  const holepunch = await c.dht._router.peerHolepunch(
    c.target,
    {
      id: c.connect.payload.holepunch.id,
      payload: c.payload.encrypt(payload),
      peerAddress,
      socket: c.puncher.socket,
      session: c.session
    },
    relayAddr
  )

  if (isDone(c)) return null

  const remotePayload = c.payload.decrypt(holepunch.payload)
  if (!remotePayload) {
    throw HOLEPUNCH_INVALID()
  }

  const { error, firewall, punching, addresses, remoteToken } = remotePayload

  if (error === ERROR.TRY_LATER && c.relayToken && payload.punching) {
    return {
      tryLater: true,
      ...holepunch,
      payload: remotePayload
    }
  }

  if (error !== ERROR.NONE) {
    throw REMOTE_ABORTED('Remote aborted with error code ' + error)
  }

  const echoed = !!(remoteToken && payload.token && b4a.equals(remoteToken, payload.token))

  c.puncher.updateRemote({
    punching,
    firewall,
    addresses,
    verified: echoed ? peerAddress.host : null
  })

  return {
    tryLater: false,
    ...holepunch,
    payload: remotePayload
  }
}

async function probeRound(c, serverAddress, serverRelay, retry) {
  // Open a quick low ttl session against what we think is the server
  if (serverAddress) await c.puncher.openSession(serverAddress)

  if (isDone(c)) return null

  const reply = await updateHolepunch(c, serverRelay.peerAddress, serverRelay.relayAddress, {
    error: ERROR.NONE,
    firewall: c.puncher.nat.firewall,
    round: c.round++,
    connected: false,
    punching: false,
    addresses: c.puncher.nat.addresses,
    remoteAddress: serverAddress,
    token: null,
    remoteToken: null
  })

  if (isDone(c) || !reply) return null

  const { peerAddress } = reply
  const { address, token } = reply.payload

  c.puncher.nat.add(reply.to, reply.from)

  // Open another quick low ttl session against what the server says their address is,
  // if they haven't said they are random yet
  if (
    c.puncher.remoteFirewall < FIREWALL.RANDOM &&
    address &&
    address.host &&
    address.port &&
    diffAddress(address, serverAddress)
  ) {
    await c.puncher.openSession(address)
    if (isDone(c)) return null
  }

  // If the remote told us they didn't know their nat firewall yet, give them a chance to figure it out
  // They might say this to see if the "fast mode" punch comes through first.
  if (c.puncher.remoteFirewall === FIREWALL.UNKNOWN) {
    await c.sleeper.pause(1000)
    if (isDone(c)) return null
  }

  let stable = await c.puncher.analyze(false)
  if (isDone(c)) return null

  // If the socket seems unstable, try to make it stable by setting the "allowReopen" flag
  // Mostly relevant for mobile networks
  if (!stable) {
    stable = await c.puncher.analyze(true)
    if (isDone(c)) return null
    if (stable) return probeRound(c, serverAddress, serverRelay, false)
  }

  if ((c.puncher.remoteFirewall === FIREWALL.UNKNOWN || !token) && retry) {
    return probeRound(c, serverAddress, serverRelay, false)
  }

  if (
    c.puncher.remoteFirewall === FIREWALL.UNKNOWN ||
    c.puncher.nat.firewall === FIREWALL.UNKNOWN
  ) {
    await abort(c, serverRelay, HOLEPUNCH_PROBE_TIMEOUT())
    return null
  }

  if (c.puncher.remoteFirewall >= FIREWALL.RANDOM && c.puncher.nat.firewall >= FIREWALL.RANDOM) {
    await abort(c, serverRelay, HOLEPUNCH_DOUBLE_RANDOMIZED_NATS())
    return null
  }

  return { token, peerAddress }
}

async function roundPunch(c, serverAddress, remoteToken, clientRelay, serverRelay, delayed) {
  // We are gossiping our final NAT status to the other peer now
  // so make sure we don't update our local view for now as that can make things weird
  c.puncher.nat.freeze()

  const isRandom =
    c.puncher.remoteFirewall >= FIREWALL.RANDOM || c.puncher.nat.firewall >= FIREWALL.RANDOM
  if (isRandom) {
    while (
      c.dht._randomPunches >= c.dht._randomPunchLimit ||
      Date.now() - c.dht._lastRandomPunch < c.dht._randomPunchInterval
    ) {
      // if no relay can help, bail
      if (!c.relayToken) throw HOLEPUNCH_ABORTED()

      if (!delayed) {
        delayed = true
        await updateHolepunch(c, serverAddress, clientRelay, {
          error: ERROR.NONE,
          firewall: c.puncher.nat.firewall,
          round: c.round++,
          connected: false,
          punching: false,
          addresses: c.puncher.nat.addresses,
          remoteAddress: null,
          token: c.payload.token(serverAddress),
          remoteToken
        })
        if (isDone(c)) return
      }

      await tryLater(c)
      if (isDone(c)) return
    }
  }

  // increment now, so we can commit to punching
  if (isRandom) c.dht._randomPunches++

  let reply

  try {
    // if delayed switch to the servers chosen relay - we validated anyway
    reply = await updateHolepunch(
      c,
      delayed ? serverRelay.peerAddress : serverAddress,
      delayed ? serverRelay.relayAddress : clientRelay,
      {
        error: ERROR.NONE,
        firewall: c.puncher.nat.firewall,
        round: c.round++,
        connected: false,
        punching: true,
        addresses: c.puncher.nat.addresses,
        remoteAddress: null,
        token: delayed ? null : c.payload.token(serverAddress),
        remoteToken
      }
    )
  } finally {
    // decrement as punch increments for us
    if (isRandom) c.dht._randomPunches--
  }

  if (isDone(c)) return
  if (!reply) return

  if (reply.tryLater) {
    await tryLater(c)
    if (isDone(c)) return
    return roundPunch(c, serverAddress, remoteToken, clientRelay, serverRelay, true)
  }

  if (!c.puncher.remoteHolepunching) {
    throw REMOTE_NOT_HOLEPUNCHING()
  }

  if (!(await c.puncher.punch())) {
    throw REMOTE_NOT_HOLEPUNCHABLE()
  }
}

async function tryLater(c) {
  if (!c.relayToken) throw HOLEPUNCH_ABORTED()
  await c.sleeper.pause(10000 + Math.round(Math.random() * 10000))
}

function maybeDestroyEncryptedSocket(c, err) {
  if (isDone(c)) return
  if (c.encryptedSocket.rawStream) return
  if (c.relaySocket) return // waiting for the relay
  if (c.puncher && !c.puncher.destroyed) return // waiting for the puncher
  c.session.destroy()
  c.encryptedSocket.destroy(err)
}

async function abort(c, { peerAddress, relayAddress }, err) {
  try {
    await updateHolepunch(c, peerAddress, relayAddress, {
      error: ERROR.ABORTED,
      firewall: FIREWALL.UNKNOWN,
      round: c.round++,
      connected: false,
      punching: false,
      addresses: null,
      remoteAddress: null,
      token: null,
      remoteToken: null
    })
  } catch (err) {
    safetyCatch(err)
  }

  destroyPuncher(c)
  maybeDestroyEncryptedSocket(c, err)
}

function relayConnection(c, relayThrough, payload, hs) {
  let isInitiator
  let publicKey
  let token

  if (payload.relayThrough) {
    isInitiator = false
    publicKey = payload.relayThrough.publicKey
    token = payload.relayThrough.token
  } else {
    isInitiator = true
    publicKey = relayThrough
    token = c.relayToken
  }

  c.relayToken = token
  c.relaySocket = c.dht.connect(publicKey)
  c.relaySocket.setKeepAlive(c.relayKeepAlive)
  c.relayClient = relay.Client.from(c.relaySocket, { id: c.relaySocket.publicKey })
  c.relayTimeout = setTimeout(onabort, 15000, null)

  c.relayClient.pair(isInitiator, token, c.rawStream).on('error', onabort).on('data', ondata)

  function ondata(remoteId) {
    if (c.relayTimeout) clearRelayTimeout(c)
    if (c.rawStream === null) {
      onabort(null)
      return
    }

    c.relayPaired = true

    const { remotePort, remoteHost, socket } = c.relaySocket.rawStream

    c.rawStream
      .on('close', () => c.relaySocket.destroy())
      .connect(socket, remoteId, remotePort, remoteHost)

    c.encryptedSocket.start(c.rawStream, { handshake: hs })
  }

  function onabort(err) {
    if (c.relayTimeout) clearRelayTimeout(c)
    const socket = c.relaySocket
    c.relayToken = null
    c.relaySocket = null
    if (socket) socket.destroy()
    maybeDestroyEncryptedSocket(c, err || RELAY_ABORTED())
  }
}

function clearPassiveConnectTimeout(c) {
  clearTimeout(c.passiveConnectTimeout)
  c.passiveConnectTimeout = null
}

function clearRelayTimeout(c) {
  clearTimeout(c.relayTimeout)
  c.relayTimeout = null
}

function destroyPuncher(c) {
  if (c.puncher) c.puncher.destroy()
  c.session.destroy()
}

function pickServerRelay(relays, clientRelay) {
  for (const r of relays) {
    if (!diffAddress(r.relayAddress, clientRelay)) return r
  }
  return relays[0]
}

function diffAddress(a, b) {
  return a.host !== b.host || a.port !== b.port
}

function defaultCreateHandshake(keyPair, remotePublicKey) {
  return new NoiseWrap(keyPair, remotePublicKey)
}

function defaultCreateSecretStream(isInitiator, rawStream, opts) {
  return new NoiseSecretStream(isInitiator, rawStream, opts)
}

function onlyNonReserved(addr) {
  return !isReserved(addr.host)
}

function isRelay(relaySocket, socket, port, host) {
  const stream = relaySocket.rawStream
  if (!stream) return false
  if (stream.socket !== socket) return false
  return port === stream.remotePort && host === stream.remoteHost
}

function selectRelay(relayThrough) {
  if (typeof relayThrough === 'function') relayThrough = relayThrough()
  if (relayThrough === null) return null
  if (Array.isArray(relayThrough))
    return relayThrough[Math.floor(Math.random() * relayThrough.length)]
  return relayThrough
}

function isRelayAddress(relayAddresses, data) {
  for (const node of relayAddresses) {
    if (node.host === data.from.host && node.port === data.from.port) return true
  }

  return false
}

function noop() {}
const EventEmitter = require('events')
const b4a = require('b4a')
const errors = require('./errors')

module.exports = class ConnectionPool extends EventEmitter {
  constructor(dht) {
    super()

    this._dht = dht
    this._servers = new Map()
    this._connecting = new Map()
    this._connections = new Map()
  }

  _attachServer(server) {
    const keyString = b4a.toString(server.publicKey, 'hex')

    this._servers.set(keyString, server)

    server
      .on('close', () => {
        this._servers.delete(keyString)
      })
      .on('connection', (socket) => {
        this._attachStream(socket, true)
      })
  }

  _attachStream(stream, opened) {
    const existing = this.get(stream.remotePublicKey)

    if (existing) {
      const keepNew =
        stream.isInitiator === existing.isInitiator ||
        b4a.compare(stream.publicKey, stream.remotePublicKey) > 0

      if (keepNew) {
        let closed = false

        const onclose = () => {
          closed = true
        }

        existing
          .on('error', noop)
          .on('close', () => {
            if (closed) return

            stream.off('error', noop).off('close', onclose)

            this._attachStream(stream, opened)
          })
          .destroy(errors.DUPLICATE_CONNECTION())

        stream.on('error', noop).on('close', onclose)
      } else {
        stream.on('error', noop).destroy(errors.DUPLICATE_CONNECTION())
      }

      return
    }

    const session = new ConnectionRef(this, stream)

    const keyString = b4a.toString(stream.remotePublicKey, 'hex')

    if (opened) {
      this._connections.set(keyString, session)

      stream.on('close', () => {
        this._connections.delete(keyString)
      })

      this.emit('connection', stream, session)
    } else {
      this._connecting.set(keyString, session)

      stream
        .on('error', noop)
        .on('close', () => {
          if (opened) this._connections.delete(keyString)
          else this._connecting.delete(keyString)
        })
        .on('open', () => {
          opened = true

          this._connecting.delete(keyString)
          this._connections.set(keyString, session)

          stream.off('error', noop)

          this.emit('connection', stream, session)
        })
    }

    return session
  }

  get connecting() {
    return this._connecting.size
  }

  get connections() {
    return this._connections.values()
  }

  has(publicKey) {
    const keyString = b4a.toString(publicKey, 'hex')

    return this._connections.has(keyString) || this._connecting.has(keyString)
  }

  get(publicKey) {
    const keyString = b4a.toString(publicKey, 'hex')

    const existing = this._connections.get(keyString) || this._connecting.get(keyString)

    return existing?._stream || null
  }
}

class ConnectionRef {
  constructor(pool, stream) {
    this._pool = pool
    this._stream = stream
    this._refs = 0
  }

  active() {
    this._refs++
  }

  inactive() {
    this._refs--
  }

  release() {
    this._stream.destroy()
  }
}

function noop() {}
const crypto = require('hypercore-crypto')

const COMMANDS = (exports.COMMANDS = {
  PEER_HANDSHAKE: 0,
  PEER_HOLEPUNCH: 1,
  FIND_PEER: 2,
  LOOKUP: 3,
  ANNOUNCE: 4,
  UNANNOUNCE: 5,
  MUTABLE_PUT: 6,
  MUTABLE_GET: 7,
  IMMUTABLE_PUT: 8,
  IMMUTABLE_GET: 9,
  PLUGIN: 10
})

exports.BOOTSTRAP_NODES = global.Pear?.config.dht?.bootstrap || [
  '88.99.3.86@node1.hyperdht.org:49737',
  '142.93.90.113@node2.hyperdht.org:49737',
  '138.68.147.8@node3.hyperdht.org:49737'
]

exports.KNOWN_NODES = global.Pear?.config.dht?.nodes || []

exports.FIREWALL = {
  UNKNOWN: 0,
  OPEN: 1,
  CONSISTENT: 2,
  RANDOM: 3
}

exports.ERROR = {
  // noise / connection related
  NONE: 0,
  ABORTED: 1,
  VERSION_MISMATCH: 2,
  TRY_LATER: 3,
  // dht related
  SEQ_REUSED: 16,
  SEQ_TOO_LOW: 17
}

const [
  NS_ANNOUNCE,
  NS_UNANNOUNCE,
  NS_MUTABLE_PUT,
  NS_PEER_HANDSHAKE,
  NS_PEER_HOLEPUNCH,
  NS_PLUGIN
] = crypto.namespace('hyperswarm/dht', [
  COMMANDS.ANNOUNCE,
  COMMANDS.UNANNOUNCE,
  COMMANDS.MUTABLE_PUT,
  COMMANDS.PEER_HANDSHAKE,
  COMMANDS.PEER_HOLEPUNCH,
  COMMANDS.PLUGIN
])

exports.NS = {
  ANNOUNCE: NS_ANNOUNCE,
  UNANNOUNCE: NS_UNANNOUNCE,
  MUTABLE_PUT: NS_MUTABLE_PUT,
  PEER_HANDSHAKE: NS_PEER_HANDSHAKE,
  PEER_HOLEPUNCH: NS_PEER_HOLEPUNCH,
  PLUGIN: NS_PLUGIN
}
const sodium = require('sodium-universal')
const b4a = require('b4a')

function hash(data) {
  const out = b4a.allocUnsafe(32)
  sodium.crypto_generichash(out, data)
  return out
}

function unslabbedHash(data) {
  const out = b4a.allocUnsafeSlow(32)
  sodium.crypto_generichash(out, data)
  return out
}

function createKeyPair(seed) {
  const publicKey = b4a.alloc(32)
  const secretKey = b4a.alloc(64)
  if (seed) sodium.crypto_sign_seed_keypair(publicKey, secretKey, seed)
  else sodium.crypto_sign_keypair(publicKey, secretKey)
  return { publicKey, secretKey }
}

module.exports = {
  hash,
  unslabbedHash,
  createKeyPair
}
const b4a = require('b4a')
const cenc = require('compact-encoding')

function encodeUnslab(enc, m) {
  // Faster than unslab(c.encode(enc, data)) because it avoids the mem copy.
  // Makes sense to put in compact-encoding when we need it in other modules too
  const state = cenc.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafeSlow(state.end)
  enc.encode(state, m)
  return state.buffer
}

module.exports = {
  encodeUnslab
}
module.exports = class DHTError extends Error {
  constructor(msg, code, fn = DHTError) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'DHTError'
  }

  static BAD_HANDSHAKE_REPLY(msg = 'Bad handshake reply') {
    return new DHTError(msg, 'BAD_HANDSHAKE_REPLY', DHTError.BAD_HANDSHAKE_REPLY)
  }

  static BAD_HOLEPUNCH_REPLY(msg = 'Bad holepunch reply') {
    return new DHTError(msg, 'BAD_HOLEPUNCH_REPLY', DHTError.BAD_HOLEPUNCH_REPLY)
  }

  static HOLEPUNCH_ABORTED(msg = 'Holepunch aborted') {
    return new DHTError(msg, 'HOLEPUNCH_ABORTED', DHTError.HOLEPUNCH_ABORTED)
  }

  static HOLEPUNCH_INVALID(msg = 'Invalid holepunch payload') {
    return new DHTError(msg, 'HOLEPUNCH_INVALID', DHTError.HOLEPUNCH_INVALID)
  }

  static HOLEPUNCH_PROBE_TIMEOUT(msg = 'Holepunching probe did not finish in time') {
    return new DHTError(msg, 'HOLEPUNCH_PROBE_TIMEOUT', DHTError.HOLEPUNCH_PROBE_TIMEOUT)
  }

  static HOLEPUNCH_DOUBLE_RANDOMIZED_NATS(msg = 'Both remote and local NATs are randomized') {
    return new DHTError(
      msg,
      'HOLEPUNCH_DOUBLE_RANDOMIZED_NATS',
      DHTError.HOLEPUNCH_DOUBLE_RANDOMIZED_NATS
    )
  }

  static CANNOT_HOLEPUNCH(msg = 'Cannot holepunch to remote') {
    return new DHTError(msg, 'CANNOT_HOLEPUNCH', DHTError.CANNOT_HOLEPUNCH)
  }

  static REMOTE_NOT_HOLEPUNCHING(msg = 'Remote is not holepunching') {
    return new DHTError(msg, 'REMOTE_NOT_HOLEPUNCHING', DHTError.REMOTE_NOT_HOLEPUNCHING)
  }

  static REMOTE_NOT_HOLEPUNCHABLE(msg = 'Remote is not holepunchable') {
    return new DHTError(msg, 'REMOTE_NOT_HOLEPUNCHABLE', DHTError.REMOTE_NOT_HOLEPUNCHABLE)
  }

  static REMOTE_ABORTED(msg = 'Remote aborted') {
    return new DHTError(msg, 'REMOTE_ABORTED', DHTError.REMOTE_ABORTED)
  }

  static HANDSHAKE_UNFINISHED(msg = 'Handshake did not finish') {
    return new DHTError(msg, 'HANDSHAKE_UNFINISHED', DHTError.HANDSHAKE_UNFINISHED)
  }

  static HANDSHAKE_INVALID(msg = 'Received invalid handshake') {
    return new DHTError(msg, 'HANDSHAKE_INVALID', DHTError.HANDSHAKE_INVALID)
  }

  static ALREADY_LISTENING(msg = 'Already listening') {
    return new DHTError(msg, 'ALREADY_LISTENING', DHTError.ALREADY_LISTENING)
  }

  static KEYPAIR_ALREADY_USED(msg = 'Keypair already used') {
    return new DHTError(msg, 'KEYPAIR_ALREADY_USED', DHTError.KEYPAIR_ALREADY_USED)
  }

  static NODE_DESTROYED(msg = 'Node destroyed') {
    return new DHTError(msg, 'NODE_DESTROYED', DHTError.NODE_DESTROYED)
  }

  static PEER_CONNECTION_FAILED(msg = 'Could not connect to peer') {
    return new DHTError(msg, 'PEER_CONNECTION_FAILED', DHTError.PEER_CONNECTION_FAILED)
  }

  static PEER_NOT_FOUND(msg = 'Peer not found') {
    return new DHTError(msg, 'PEER_NOT_FOUND', DHTError.PEER_NOT_FOUND)
  }

  static STREAM_NOT_CONNECTED(msg = 'Stream is not connected') {
    return new DHTError(msg, 'STREAM_NOT_CONNECTED', DHTError.STREAM_DISCONNECTED)
  }

  static SERVER_INCOMPATIBLE(msg = 'Server is using an incompatible version') {
    return new DHTError(msg, 'SERVER_INCOMPATIBLE', DHTError.SERVER_INCOMPATIBLE)
  }

  static SERVER_ERROR(msg = 'Server returned an error') {
    return new DHTError(msg, 'SERVER_ERROR', DHTError.SERVER_ERROR)
  }

  static DUPLICATE_CONNECTION(msg = 'Duplicate connection') {
    return new DHTError(msg, 'DUPLICATE_CONNECTION', DHTError.DUPLICATE_CONNECTION)
  }

  static RELAY_ABORTED(msg = 'Relay aborted') {
    return new DHTError(msg, 'RELAY_ABORTED', DHTError.RELAY_ABORTED)
  }

  static SUSPENDED(msg = 'Suspended') {
    return new DHTError(msg, 'SUSPENDED', DHTError.SUSPENDED)
  }
}
const b4a = require('b4a')
const Nat = require('./nat')
const Sleeper = require('./sleeper')
const { FIREWALL } = require('./constants')

const BIRTHDAY_SOCKETS = 256
const HOLEPUNCH = b4a.from([0])
const HOLEPUNCH_TTL = 5
const DEFAULT_TTL = 64
const MAX_REOPENS = 3

module.exports = class Holepuncher {
  constructor(dht, session, isInitiator, remoteFirewall = FIREWALL.UNKNOWN) {
    const holder = dht._socketPool.acquire()

    this.dht = dht
    this.session = session

    this.nat = new Nat(dht, session, holder.socket)
    this.nat.autoSample()

    this.isInitiator = isInitiator

    // events
    this.onconnect = noop
    this.onabort = noop

    this.punching = false
    this.connected = false
    this.destroyed = false
    this.randomized = false

    // track remote state
    this.remoteFirewall = remoteFirewall
    this.remoteAddresses = []
    this.remoteHolepunching = false

    this._sleeper = new Sleeper()
    this._reopening = null
    this._timeout = null
    this._punching = null
    this._allHolders = []
    this._holder = this._addRef(holder)
  }

  get socket() {
    return this._holder.socket
  }

  updateRemote({ punching, firewall, addresses, verified }) {
    const remoteAddresses = []

    if (addresses) {
      for (const addr of addresses) {
        remoteAddresses.push({
          host: addr.host,
          port: addr.port,
          verified: verified === addr.host || this._isVerified(addr.host)
        })
      }
    }

    this.remoteFirewall = firewall
    this.remoteAddresses = remoteAddresses
    this.remoteHolepunching = punching
  }

  _isVerified(host) {
    for (const addr of this.remoteAddresses) {
      if (addr.verified && addr.host === host) {
        return true
      }
    }
    return false
  }

  ping(addr, socket = this._holder.socket) {
    return holepunch(socket, addr, false)
  }

  openSession(addr, socket = this._holder.socket) {
    return holepunch(socket, addr, true)
  }

  async analyze(allowReopen) {
    await this.nat.analyzing
    if (this._unstable()) {
      if (!allowReopen) return false
      if (!this._reopening) this._reopening = this._reopen()
      return this._reopening
    }
    return true
  }

  _unstable() {
    // TODO!!: We need an additional heuristic here... If we were NOT random in the past we should also do this.
    const firewall = this.nat.firewall
    return (
      (this.remoteFirewall >= FIREWALL.RANDOM && firewall >= FIREWALL.RANDOM) ||
      firewall === FIREWALL.UNKNOWN
    )
  }

  _reset() {
    const prev = this._holder

    this._allHolders.pop()
    this._holder = this._addRef(this.dht._socketPool.acquire())

    prev.release()
    this.nat.destroy()

    this.nat = new Nat(this.dht, this.session, this._holder.socket)
    // TODO: maybe make auto sampling configurable somehow?
    this.nat.autoSample()
  }

  _addRef(ref) {
    this._allHolders.push(ref)
    ref.onholepunchmessage = (msg, rinfo) => this._onholepunchmessage(msg, rinfo, ref)
    return ref
  }

  _onholepunchmessage(_, addr, ref) {
    if (!this.isInitiator) {
      // TODO: we don't need this if we had a way to connect a socket to many hosts
      holepunch(ref.socket, addr, false) // never fails
      return
    }

    if (this.connected) return

    this.connected = true
    this.punching = false

    for (const r of this._allHolders) {
      if (r === ref) continue
      r.release()
    }

    this._allHolders[0] = ref
    while (this._allHolders.length > 1) this._allHolders.pop()

    this._decrementRandomized()
    this.onconnect(ref.socket, addr.port, addr.host)
  }

  _done() {
    return this.destroyed || this.connected
  }

  async _reopen() {
    for (let i = 0; this._unstable() && i < MAX_REOPENS && !this._done() && !this.punching; i++) {
      this._reset()
      await this.nat.analyzing
    }

    return coerceFirewall(this.nat.firewall) === FIREWALL.CONSISTENT
  }

  punch() {
    if (!this._punching) this._punching = this._punch()
    return this._punching
  }

  async _punch() {
    if (this._done() || !this.remoteAddresses.length) return false

    this.punching = true

    // Coerce into consistency for now. Obvs we could make this this more efficient if we use that info
    // but that's seldomly used since those will just use tcp most of the time.

    const local = coerceFirewall(this.nat.firewall)
    const remote = coerceFirewall(this.remoteFirewall)

    // Note that most of these async functions are meant to run in the background
    // which is why we don't await them here and why they are not allowed to throw

    let remoteVerifiedAddress = null
    for (const addr of this.remoteAddresses) {
      if (addr.verified) {
        remoteVerifiedAddress = addr
        break
      }
    }

    if (local === FIREWALL.CONSISTENT && remote === FIREWALL.CONSISTENT) {
      this.dht.stats.punches.consistent++
      this._consistentProbe()
      return true
    }

    if (!remoteVerifiedAddress) return false

    if (local === FIREWALL.CONSISTENT && remote >= FIREWALL.RANDOM) {
      this.dht.stats.punches.random++
      this._incrementRandomized()
      this._randomProbes(remoteVerifiedAddress)
      return true
    }

    if (local >= FIREWALL.RANDOM && remote === FIREWALL.CONSISTENT) {
      this.dht.stats.punches.random++
      this._incrementRandomized()
      await this._openBirthdaySockets(remoteVerifiedAddress)
      if (this.punching) this._keepAliveRandomNat(remoteVerifiedAddress)
      return true
    }

    return false
  }

  // Note that this never throws so it is safe to run in the background
  async _consistentProbe() {
    // Here we do the sleep first because the "fast open" mode in the server just fired a ping
    if (!this.isInitiator) await this._sleeper.pause(1000)

    let tries = 0

    while (this.punching && tries++ < 10) {
      for (const addr of this.remoteAddresses) {
        // only try unverified addresses every 4 ticks
        if (!addr.verified && (tries & 3) !== 0) continue
        await holepunch(this._holder.socket, addr, false)
      }
      if (this.punching) await this._sleeper.pause(1000)
    }

    this._autoDestroy()
  }

  // Note that this never throws so it is safe to run in the background
  async _randomProbes(remoteAddr) {
    let tries = 1750 // ~35s

    while (this.punching && tries-- > 0) {
      const addr = { host: remoteAddr.host, port: randomPort() }
      await holepunch(this._holder.socket, addr, false)
      if (this.punching) await this._sleeper.pause(20)
    }

    this._autoDestroy()
  }

  // Note that this never throws so it is safe to run in the background
  async _keepAliveRandomNat(remoteAddr) {
    let i = 0
    let lowTTLRounds = 1

    // TODO: experiment with this here. We just bursted all the messages in
    // openOtherSockets to ensure the sockets are open, so it's potentially
    // a good idea to slow down for a bit.
    await this._sleeper.pause(100)

    let tries = 1750 // ~35s

    while (this.punching && tries-- > 0) {
      if (i === this._allHolders.length) {
        i = 0
        if (lowTTLRounds > 0) lowTTLRounds--
      }

      await holepunch(this._allHolders[i++].socket, remoteAddr, lowTTLRounds > 0)
      if (this.punching) await this._sleeper.pause(20)
    }

    this._autoDestroy()
  }

  async _openBirthdaySockets(remoteAddr) {
    while (this.punching && this._allHolders.length < BIRTHDAY_SOCKETS) {
      const ref = this._addRef(this.dht._socketPool.acquire())
      await holepunch(ref.socket, remoteAddr, HOLEPUNCH_TTL)
    }
  }

  _autoDestroy() {
    if (!this.connected) this.destroy()
  }

  _incrementRandomized() {
    if (!this.randomized) {
      this.randomized = true
      this.dht._randomPunches++
    }
  }

  _decrementRandomized() {
    if (this.randomized) {
      this.dht._lastRandomPunch = Date.now()
      this.randomized = false
      this.dht._randomPunches--
    }
  }

  destroy() {
    if (this.destroyed) return
    this.destroyed = true
    this.punching = false

    for (const ref of this._allHolders) ref.release()
    this._allHolders = []
    this.nat.destroy()

    if (!this.connected) {
      this._decrementRandomized()
      this.onabort()
    }
  }

  static ping(socket, addr) {
    return holepunch(socket, addr, false)
  }

  static localAddresses(socket) {
    return localAddresses(socket)
  }

  static matchAddress(myAddresses, externalAddresses) {
    return matchAddress(myAddresses, externalAddresses)
  }
}

function holepunch(socket, addr, lowTTL) {
  return socket.send(HOLEPUNCH, addr.port, addr.host, lowTTL ? HOLEPUNCH_TTL : DEFAULT_TTL)
}

function randomPort() {
  return (1000 + Math.random() * 64536) | 0
}

function coerceFirewall(fw) {
  return fw === FIREWALL.OPEN ? FIREWALL.CONSISTENT : fw
}

function localAddresses(socket) {
  const addrs = []
  const { host, port } = socket.address()

  if (host === '127.0.0.1') return [{ host, port }]

  for (const n of socket.udx.networkInterfaces()) {
    if (n.family !== 4 || n.internal) continue

    addrs.push({ host: n.host, port })
  }

  if (addrs.length === 0) {
    addrs.push({ host: '127.0.0.1', port })
  }

  return addrs
}

function matchAddress(localAddresses, remoteLocalAddresses) {
  if (remoteLocalAddresses.length === 0) return null

  let best = { segment: 1, addr: null }

  for (const localAddress of localAddresses) {
    // => 192.168.122.238
    const a = localAddress.host.split('.')

    for (const remoteAddress of remoteLocalAddresses) {
      // => 192.168.0.23
      // => 192.168.122.1
      const b = remoteAddress.host.split('.')

      // Matches 192.*.*.*
      if (a[0] === b[0]) {
        if (best.segment === 1) best = { segment: 2, addr: remoteAddress }

        // Matches 192.168.*.*
        if (a[1] === b[1]) {
          if (best.segment === 2) best = { segment: 3, addr: remoteAddress }

          // Matches 192.168.122.*
          if (a[2] === b[2]) return remoteAddress
        }
      }
    }
  }

  return best.addr
}

function noop() {}
const c = require('compact-encoding')

const ipv4 = {
  ...c.ipv4Address,
  decode(state) {
    const ip = c.ipv4Address.decode(state)
    return {
      host: ip.host,
      port: ip.port
    }
  }
}

const ipv4Array = c.array(ipv4)

const ipv6 = {
  ...c.ipv6Address,
  decode(state) {
    const ip = c.ipv6Address.decode(state)
    return {
      host: ip.host,
      port: ip.port
    }
  }
}

const ipv6Array = c.array(ipv6)

exports.handshake = {
  preencode(state, m) {
    state.end += 1 + 1 + (m.peerAddress ? 6 : 0) + (m.relayAddress ? 6 : 0)
    c.buffer.preencode(state, m.noise)
  },
  encode(state, m) {
    const flags = (m.peerAddress ? 1 : 0) | (m.relayAddress ? 2 : 0)

    c.uint.encode(state, flags)
    c.uint.encode(state, m.mode)
    c.buffer.encode(state, m.noise)

    if (m.peerAddress) ipv4.encode(state, m.peerAddress)
    if (m.relayAddress) ipv4.encode(state, m.relayAddress)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      mode: c.uint.decode(state),
      noise: c.buffer.decode(state),
      peerAddress: flags & 1 ? ipv4.decode(state) : null,
      relayAddress: flags & 2 ? ipv4.decode(state) : null
    }
  }
}

const relayInfo = {
  preencode(state, m) {
    state.end += 12
  },
  encode(state, m) {
    ipv4.encode(state, m.relayAddress)
    ipv4.encode(state, m.peerAddress)
  },
  decode(state) {
    return {
      relayAddress: ipv4.decode(state),
      peerAddress: ipv4.decode(state)
    }
  }
}

const relayInfoArray = c.array(relayInfo)

const holepunchInfo = {
  preencode(state, m) {
    c.uint.preencode(state, m.id)
    relayInfoArray.preencode(state, m.relays)
  },
  encode(state, m) {
    c.uint.encode(state, m.id)
    relayInfoArray.encode(state, m.relays)
  },
  decode(state) {
    return {
      id: c.uint.decode(state),
      relays: relayInfoArray.decode(state)
    }
  }
}

const udxInfo = {
  preencode(state, m) {
    state.end += 2 // version + features
    c.uint.preencode(state, m.id)
    c.uint.preencode(state, m.seq)
  },
  encode(state, m) {
    c.uint.encode(state, 1)
    c.uint.encode(state, m.reusableSocket ? 1 : 0)
    c.uint.encode(state, m.id)
    c.uint.encode(state, m.seq)
  },
  decode(state) {
    const version = c.uint.decode(state)
    const features = c.uint.decode(state)

    return {
      version,
      reusableSocket: (features & 1) !== 0,
      id: c.uint.decode(state),
      seq: c.uint.decode(state)
    }
  }
}

const secretStreamInfo = {
  preencode(state, m) {
    c.uint.preencode(state, 1)
  },
  encode(state, m) {
    c.uint.encode(state, 1)
  },
  decode(state) {
    return {
      version: c.uint.decode(state)
    }
  }
}

const relayThroughInfo = {
  preencode(state, m) {
    c.uint.preencode(state, 1) // version
    c.uint.preencode(state, 0) // flags
    c.fixed32.preencode(state, m.publicKey)
    c.fixed32.preencode(state, m.token)
  },
  encode(state, m) {
    c.uint.encode(state, 1)
    c.uint.encode(state, 0)
    c.fixed32.encode(state, m.publicKey)
    c.fixed32.encode(state, m.token)
  },
  decode(state) {
    const version = c.uint.decode(state)
    c.uint.decode(state)

    return {
      version,
      publicKey: c.fixed32.decode(state),
      token: c.fixed32.decode(state)
    }
  }
}

exports.noisePayload = {
  preencode(state, m) {
    state.end += 4 // version + flags + error + firewall
    if (m.holepunch) holepunchInfo.preencode(state, m.holepunch)
    if (m.addresses4 && m.addresses4.length) ipv4Array.preencode(state, m.addresses4)
    if (m.addresses6 && m.addresses6.length) ipv6Array.preencode(state, m.addresses6)
    if (m.udx) udxInfo.preencode(state, m.udx)
    if (m.secretStream) secretStreamInfo.preencode(state, m.secretStream)
    if (m.relayThrough) relayThroughInfo.preencode(state, m.relayThrough)
    if (m.relayAddresses) ipv4Array.preencode(state, m.relayAddresses)
  },
  encode(state, m) {
    let flags = 0

    if (m.holepunch) flags |= 1
    if (m.addresses4 && m.addresses4.length) flags |= 2
    if (m.addresses6 && m.addresses6.length) flags |= 4
    if (m.udx) flags |= 8
    if (m.secretStream) flags |= 16
    if (m.relayThrough) flags |= 32
    if (m.relayAddresses) flags |= 64

    c.uint.encode(state, 1) // version
    c.uint.encode(state, flags)
    c.uint.encode(state, m.error)
    c.uint.encode(state, m.firewall)

    if (m.holepunch) holepunchInfo.encode(state, m.holepunch)
    if (m.addresses4 && m.addresses4.length) ipv4Array.encode(state, m.addresses4)
    if (m.addresses6 && m.addresses6.length) ipv6Array.encode(state, m.addresses6)
    if (m.udx) udxInfo.encode(state, m.udx)
    if (m.secretStream) secretStreamInfo.encode(state, m.secretStream)
    if (m.relayThrough) relayThroughInfo.encode(state, m.relayThrough)
    if (m.relayAddresses) ipv4Array.encode(state, m.relayAddresses)
  },
  decode(state) {
    const version = c.uint.decode(state)

    if (version !== 1) {
      // Do not attempt to decode but return this back to the user so they can
      // actually handle it
      return {
        version,
        error: 0,
        firewall: 0,
        holepunch: null,
        addresses4: [],
        addresses6: [],
        udx: null,
        secretStream: null,
        relayThrough: null,
        relayAddresses: null
      }
    }

    const flags = c.uint.decode(state)

    return {
      version,
      error: c.uint.decode(state),
      firewall: c.uint.decode(state),
      holepunch: (flags & 1) !== 0 ? holepunchInfo.decode(state) : null,
      addresses4: (flags & 2) !== 0 ? ipv4Array.decode(state) : [],
      addresses6: (flags & 4) !== 0 ? ipv6Array.decode(state) : [],
      udx: (flags & 8) !== 0 ? udxInfo.decode(state) : null,
      secretStream: (flags & 16) !== 0 ? secretStreamInfo.decode(state) : null,
      relayThrough: (flags & 32) !== 0 ? relayThroughInfo.decode(state) : null,
      relayAddresses: (flags & 64) !== 0 ? ipv4Array.decode(state) : null
    }
  }
}

exports.holepunch = {
  preencode(state, m) {
    state.end += 2
    c.uint.preencode(state, m.id)
    c.buffer.preencode(state, m.payload)
    if (m.peerAddress) ipv4.preencode(state, m.peerAddress)
  },
  encode(state, m) {
    const flags = m.peerAddress ? 1 : 0
    c.uint.encode(state, flags)
    c.uint.encode(state, m.mode)
    c.uint.encode(state, m.id)
    c.buffer.encode(state, m.payload)
    if (m.peerAddress) ipv4.encode(state, m.peerAddress)
  },
  decode(state) {
    const flags = c.uint.decode(state)
    return {
      mode: c.uint.decode(state),
      id: c.uint.decode(state),
      payload: c.buffer.decode(state),
      peerAddress: flags & 1 ? ipv4.decode(state) : null
    }
  }
}

exports.holepunchPayload = {
  preencode(state, m) {
    state.end += 4 // flags + error + firewall + round
    if (m.addresses) ipv4Array.preencode(state, m.addresses)
    if (m.remoteAddress) state.end += 6
    if (m.token) state.end += 32
    if (m.remoteToken) state.end += 32
  },
  encode(state, m) {
    const flags =
      (m.connected ? 1 : 0) |
      (m.punching ? 2 : 0) |
      (m.addresses ? 4 : 0) |
      (m.remoteAddress ? 8 : 0) |
      (m.token ? 16 : 0) |
      (m.remoteToken ? 32 : 0)

    c.uint.encode(state, flags)
    c.uint.encode(state, m.error)
    c.uint.encode(state, m.firewall)
    c.uint.encode(state, m.round)

    if (m.addresses) ipv4Array.encode(state, m.addresses)
    if (m.remoteAddress) ipv4.encode(state, m.remoteAddress)
    if (m.token) c.fixed32.encode(state, m.token)
    if (m.remoteToken) c.fixed32.encode(state, m.remoteToken)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      error: c.uint.decode(state),
      firewall: c.uint.decode(state),
      round: c.uint.decode(state),
      connected: (flags & 1) !== 0,
      punching: (flags & 2) !== 0,
      addresses: (flags & 4) !== 0 ? ipv4Array.decode(state) : null,
      remoteAddress: (flags & 8) !== 0 ? ipv4.decode(state) : null,
      token: (flags & 16) !== 0 ? c.fixed32.decode(state) : null,
      remoteToken: (flags & 32) !== 0 ? c.fixed32.decode(state) : null
    }
  }
}

const peer = (exports.peer = {
  preencode(state, m) {
    state.end += 32
    ipv4Array.preencode(state, m.relayAddresses)
  },
  encode(state, m) {
    c.fixed32.encode(state, m.publicKey)
    ipv4Array.encode(state, m.relayAddresses)
  },
  decode(state) {
    return {
      publicKey: c.fixed32.decode(state),
      relayAddresses: ipv4Array.decode(state)
    }
  }
})

const peers = (exports.peers = c.array(peer))

const rawPeers = c.array(c.raw)

exports.lookupRawReply = {
  preencode(state, m) {
    rawPeers.preencode(state, m.peers)
    c.uint.preencode(state, m.bump)
  },
  encode(state, m) {
    rawPeers.encode(state, m.peers)
    c.uint.encode(state, m.bump)
  },
  decode(state) {
    return {
      peers: peers.decode(state),
      bump: state.start < state.end ? c.uint.decode(state) : 0
    }
  }
}

exports.announce = {
  preencode(state, m) {
    state.end++ // flags
    if (m.peer) peer.preencode(state, m.peer)
    if (m.refresh) state.end += 32
    if (m.signature) state.end += 64
    if (m.bump) c.uint.preencode(state, m.bump)
  },
  encode(state, m) {
    const flags = (m.peer ? 1 : 0) | (m.refresh ? 2 : 0) | (m.signature ? 4 : 0) | (m.bump ? 8 : 0)
    c.uint.encode(state, flags)
    if (m.peer) peer.encode(state, m.peer)
    if (m.refresh) c.fixed32.encode(state, m.refresh)
    if (m.signature) c.fixed64.encode(state, m.signature)
    if (m.bump) c.uint.encode(state, m.bump)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      peer: (flags & 1) !== 0 ? peer.decode(state) : null,
      refresh: (flags & 2) !== 0 ? c.fixed32.decode(state) : null,
      signature: (flags & 4) !== 0 ? c.fixed64.decode(state) : null,
      bump: (flags & 8) !== 0 ? c.uint.decode(state) : 0
    }
  }
}

exports.mutableSignable = {
  preencode(state, m) {
    c.uint.preencode(state, m.seq)
    c.buffer.preencode(state, m.value)
  },
  encode(state, m) {
    c.uint.encode(state, m.seq)
    c.buffer.encode(state, m.value)
  },
  decode(state) {
    return {
      seq: c.uint.decode(state),
      value: c.buffer.decode(state)
    }
  }
}

exports.mutablePutRequest = {
  preencode(state, m) {
    c.fixed32.preencode(state, m.publicKey)
    c.uint.preencode(state, m.seq)
    c.buffer.preencode(state, m.value)
    c.fixed64.preencode(state, m.signature)
  },
  encode(state, m) {
    c.fixed32.encode(state, m.publicKey)
    c.uint.encode(state, m.seq)
    c.buffer.encode(state, m.value)
    c.fixed64.encode(state, m.signature)
  },
  decode(state) {
    return {
      publicKey: c.fixed32.decode(state),
      seq: c.uint.decode(state),
      value: c.buffer.decode(state),
      signature: c.fixed64.decode(state)
    }
  }
}

exports.mutableGetResponse = {
  preencode(state, m) {
    c.uint.preencode(state, m.seq)
    c.buffer.preencode(state, m.value)
    c.fixed64.preencode(state, m.signature)
  },
  encode(state, m) {
    c.uint.encode(state, m.seq)
    c.buffer.encode(state, m.value)
    c.fixed64.encode(state, m.signature)
  },
  decode(state) {
    return {
      seq: c.uint.decode(state),
      value: c.buffer.decode(state),
      signature: c.fixed64.decode(state)
    }
  }
}

exports.pluginRequest = {
  preencode(state, m) {
    c.string.preencode(state, m.plugin)
    c.uint.preencode(state, m.version)
    c.uint.preencode(state, m.command)
    state.end++ // max flag is 1 so always one byte

    if (m.value) c.buffer.preencode(state, m.value)
  },
  encode(state, m) {
    const flags = m.value ? 1 : 0

    c.string.encode(state, m.plugin)
    c.uint.encode(state, m.version)
    c.uint.encode(state, m.command)
    c.uint.encode(state, flags)

    if (m.value) c.buffer.encode(state, m.value)
  },
  decode(state) {
    const r0 = c.string.decode(state)
    const r1 = c.uint.decode(state)
    const r2 = c.uint.decode(state)
    const flags = c.uint.decode(state)

    return {
      plugin: r0,
      version: r1,
      command: r2,
      value: (flags & 1) !== 0 ? c.buffer.decode(state) : null
    }
  }
}
const { FIREWALL } = require('../lib/constants')

module.exports = class Nat {
  constructor(dht, session, socket) {
    this._samplesHost = []
    this._samplesFull = []
    this._visited = new Map()
    this._resolve = null
    this._minSamples = 4
    this._autoSampling = false

    this.dht = dht
    this.session = session
    this.socket = socket

    this.sampled = 0
    this.firewall = dht.firewalled ? FIREWALL.UNKNOWN : FIREWALL.OPEN
    this.addresses = null

    this.analyzing = new Promise((resolve) => {
      this._resolve = resolve
    })
  }

  autoSample(retry = true) {
    if (this._autoSampling) return
    this._autoSampling = true

    const self = this
    const socket = this.socket
    const maxPings = this._minSamples

    let skip = this.dht.nodes.length >= 8 ? 5 : 0
    let pending = 0

    // TODO: it would be best to pick the nodes to help us based on latency to us
    // That should reduce connect latency in general. We should investigate tracking that later on.

    // TODO 2: try to pick nodes with different IPs as well, as that'll help multi IP cell connections...
    // If we expose this from the nat sampler then the DHT should be able to help us filter out scams as well...

    for (
      let node = this.dht.nodes.latest;
      node && this.sampled + pending < maxPings;
      node = node.prev
    ) {
      if (skip > 0) {
        skip--
        continue
      }

      const ref = node.host + ':' + node.port

      if (this._visited.has(ref)) continue
      this._visited.set(ref, 1)

      pending++
      this.session.ping(node, { socket, retry: false }).then(onpong, onskip)
    }

    pending++
    onskip()

    function onpong(res) {
      self.add(res.to, res.from)
      onskip()
    }

    function onskip() {
      if (--pending === 0 && self.sampled < self._minSamples) {
        if (retry) {
          self._autoSampling = false
          self.autoSample(false)
          return
        }
        self._resolve()
      }
    }
  }

  destroy() {
    this._autoSampling = true
    this._minSamples = 0
    this._resolve()
  }

  unfreeze() {
    this.frozen = false
    this._updateFirewall()
    this._updateAddresses()
  }

  freeze() {
    this.frozen = true
  }

  _updateFirewall() {
    if (!this.dht.firewalled) {
      this.firewall = FIREWALL.OPEN
      return
    }

    if (this.sampled < 3) return

    const max = this._samplesFull[0].hits

    if (max >= 3) {
      this.firewall = FIREWALL.CONSISTENT
      return
    }

    if (max === 1) {
      this.firewall = FIREWALL.RANDOM
      return
    }

    // else max === 2

    // 1 host, >= 4 total samples ie, 2 bad ones -> random
    if (this._samplesHost.length === 1 && this.sampled > 3) {
      this.firewall = FIREWALL.RANDOM
      return
    }

    // double hit on two different ips -> assume consistent
    if (this._samplesHost.length > 1 && this._samplesFull[1].hits > 1) {
      this.firewall = FIREWALL.CONSISTENT
      return
    }

    // (4 is just means - all the samples we expect) - no decision - assume random
    if (this.sampled > 4) {
      this.firewall = FIREWALL.RANDOM
    }
  }

  _updateAddresses() {
    if (this.firewall === FIREWALL.UNKNOWN) {
      this.addresses = null
      return
    }

    if (this.firewall === FIREWALL.RANDOM) {
      this.addresses = [this._samplesHost[0]]
      return
    }

    if (this.firewall === FIREWALL.CONSISTENT) {
      this.addresses = []
      for (const addr of this._samplesFull) {
        if (addr.hits >= 2 || this.addresses.length < 2) this.addresses.push(addr)
      }
    }
  }

  update() {
    if (this.dht.firewalled && this.firewall === FIREWALL.OPEN) {
      this.firewall = FIREWALL.UNKNOWN
    }
    this._updateFirewall()
    this._updateAddresses()
  }

  add(addr, from) {
    const ref = from.host + ':' + from.port

    if (this._visited.get(ref) === 2) return
    this._visited.set(ref, 2)

    addSample(this._samplesHost, addr.host, 0)
    addSample(this._samplesFull, addr.host, addr.port)

    if ((++this.sampled >= 3 || !this.dht.firewalled) && !this.frozen) {
      this.update()
    }

    if (this.firewall === FIREWALL.CONSISTENT || this.firewall === FIREWALL.OPEN) {
      this._resolve()
    } else if (this.sampled >= this._minSamples) {
      this._resolve()
    }
  }
}

function addSample(samples, host, port) {
  for (let i = 0; i < samples.length; i++) {
    const s = samples[i]

    if (s.port !== port || s.host !== host) continue
    s.hits++

    for (; i > 0; i--) {
      const prev = samples[i - 1]
      if (prev.hits >= s.hits) return
      samples[i - 1] = s
      samples[i] = prev
    }

    return
  }

  samples.push({
    host,
    port,
    hits: 1
  })
}
const NoiseSecretStream = require('@hyperswarm/secret-stream')
const NoiseHandshake = require('noise-handshake')
const curve = require('noise-curve-ed')
const c = require('compact-encoding')
const b4a = require('b4a')
const sodium = require('sodium-universal')
const m = require('./messages')
const { NS } = require('./constants')
const { HANDSHAKE_UNFINISHED } = require('./errors')

const NOISE_PROLOUGE = NS.PEER_HANDSHAKE

module.exports = class NoiseWrap {
  constructor(keyPair, remotePublicKey) {
    this.isInitiator = !!remotePublicKey
    this.remotePublicKey = remotePublicKey
    this.keyPair = keyPair
    this.handshake = new NoiseHandshake('IK', this.isInitiator, keyPair, { curve })
    this.handshake.initialise(NOISE_PROLOUGE, remotePublicKey)
  }

  send(payload) {
    const buf = c.encode(m.noisePayload, payload)
    return this.handshake.send(buf)
  }

  recv(buf) {
    const payload = c.decode(m.noisePayload, this.handshake.recv(buf))
    this.remotePublicKey = b4a.toBuffer(this.handshake.rs)
    return payload
  }

  final() {
    if (!this.handshake.complete) throw HANDSHAKE_UNFINISHED()

    const holepunchSecret = b4a.allocUnsafe(32)

    sodium.crypto_generichash(holepunchSecret, NS.PEER_HOLEPUNCH, this.handshake.hash)

    return {
      isInitiator: this.isInitiator,
      publicKey: this.keyPair.publicKey,
      streamId: this.streamId,
      remotePublicKey: this.remotePublicKey,
      remoteId: NoiseSecretStream.id(this.handshake.hash, !this.isInitiator),
      holepunchSecret,
      hash: b4a.toBuffer(this.handshake.hash),
      rx: b4a.toBuffer(this.handshake.rx),
      tx: b4a.toBuffer(this.handshake.tx)
    }
  }
}
const c = require('compact-encoding')
const sodium = require('sodium-universal')
const RecordCache = require('record-cache')
const Cache = require('xache')
const b4a = require('b4a')
const unslab = require('unslab')

const { encodeUnslab } = require('./encode')
const m = require('./messages')
const { NS, ERROR } = require('./constants')

const EMPTY = b4a.alloc(0)
const TMP = b4a.allocUnsafe(32)
const MAX_BUMP_DRIFT = 60_000

module.exports = class Persistent {
  constructor(dht, opts) {
    this.dht = dht
    this.records = new RecordCache(opts.records)
    this.bumps = new Cache(opts.bumps)
    this.refreshes = new Cache(opts.refreshes)
    this.mutables = new Cache(opts.mutables)
    this.immutables = new Cache(opts.immutables)
  }

  onlookup(req) {
    if (!req.target) return

    const k = b4a.toString(req.target, 'hex')
    const records = this.records.get(k, 20)
    const bump = this.bumps.get(k) || 0
    const fwd = this.dht._router.get(k)

    if (fwd && records.length < 20) records.push(fwd.record)

    req.reply(records.length ? c.encode(m.lookupRawReply, { peers: records, bump }) : null)
  }

  onfindpeer(req) {
    if (!req.target) return
    const fwd = this.dht._router.get(req.target)
    req.reply(fwd ? fwd.record : null)
  }

  unannounce(target, publicKey) {
    const k = b4a.toString(target, 'hex')
    sodium.crypto_generichash(TMP, publicKey)

    if (b4a.equals(TMP, target)) this.dht._router.delete(k)
    this.records.remove(k, publicKey)
  }

  onunannounce(req) {
    if (!req.target || !req.token) return

    const unann = decode(m.announce, req.value)
    if (unann === null) return

    const { peer, signature } = unann
    if (!peer || !signature) return

    const signable = annSignable(req.target, req.token, this.dht.id, unann, NS.UNANNOUNCE)

    if (!sodium.crypto_sign_verify_detached(signature, signable, peer.publicKey)) {
      return
    }

    this.unannounce(req.target, peer.publicKey)
    req.reply(null, { token: false, closerNodes: false })
  }

  _onrefresh(token, req) {
    sodium.crypto_generichash(TMP, token)
    const activeRefresh = b4a.toString(TMP, 'hex')

    const r = this.refreshes.get(activeRefresh)
    if (!r) return

    const { announceSelf, k, record } = r
    const publicKey = record.subarray(0, 32)

    if (announceSelf) {
      this.dht._router.set(k, {
        relay: req.from,
        record,
        onconnect: null,
        onholepunch: null
      })
      this.records.remove(k, publicKey)
    } else {
      this.records.add(k, publicKey, record)
    }

    this.refreshes.delete(activeRefresh)
    this.refreshes.set(b4a.toString(token, 'hex'), r)

    req.reply(null, { token: false, closerNodes: false })
  }

  onannounce(req) {
    if (!req.target || !req.token || !this.dht.id) return

    const ann = decode(m.announce, req.value)
    if (ann === null) return

    const { peer, refresh, signature, bump } = ann

    if (!peer) {
      if (!refresh) return
      this._onrefresh(refresh, req)
      return
    }

    const signable = annSignable(req.target, req.token, this.dht.id, ann, NS.ANNOUNCE)

    if (!signature || !sodium.crypto_sign_verify_detached(signature, signable, peer.publicKey)) {
      return
    }

    // TODO: it would be potentially be more optimal to allow more than 3 addresses here for a findPeer response
    // and only use max 3 for a lookup reply
    if (peer.relayAddresses.length > 3) {
      peer.relayAddresses = peer.relayAddresses.slice(0, 3)
    }

    sodium.crypto_generichash(TMP, peer.publicKey)

    const k = b4a.toString(req.target, 'hex')
    const announceSelf = b4a.equals(TMP, req.target)
    const record = encodeUnslab(m.peer, peer)

    if (announceSelf) {
      this.dht._router.set(k, {
        relay: req.from,
        record,
        onconnect: null,
        onholepunch: null
      })
      this.records.remove(k, peer.publicKey)
    } else {
      const currentBump = this.bumps.get(k) || 0
      if (bump > currentBump && bump <= Date.now() + MAX_BUMP_DRIFT) this.bumps.set(k, bump)
      this.records.add(k, peer.publicKey, record)
    }

    if (refresh) {
      this.refreshes.set(b4a.toString(refresh, 'hex'), { k, record, announceSelf })
    }

    req.reply(null, { token: false, closerNodes: false })
  }

  onmutableget(req) {
    if (!req.target || !req.value) return

    let seq = 0
    try {
      seq = c.decode(c.uint, req.value)
    } catch {
      return
    }

    const k = b4a.toString(req.target, 'hex')
    const value = this.mutables.get(k)

    if (!value) {
      req.reply(null)
      return
    }

    const localSeq = c.decode(c.uint, value)
    req.reply(localSeq < seq ? null : value)
  }

  onmutableput(req) {
    if (!req.target || !req.token || !req.value) return

    const p = decode(m.mutablePutRequest, req.value)
    if (!p) return

    const { publicKey, seq, value, signature } = p

    const hash = b4a.allocUnsafe(32)
    sodium.crypto_generichash(hash, publicKey)
    if (!b4a.equals(hash, req.target)) return

    if (!value || !verifyMutable(signature, seq, value, publicKey)) return

    const k = b4a.toString(hash, 'hex')
    const local = this.mutables.get(k)

    if (local) {
      const existing = c.decode(m.mutableGetResponse, local)
      if (existing.value && existing.seq === seq && b4a.compare(value, existing.value) !== 0) {
        req.error(ERROR.SEQ_REUSED)
        return
      }
      if (seq < existing.seq) {
        req.error(ERROR.SEQ_TOO_LOW)
        return
      }
    }

    this.mutables.set(k, encodeUnslab(m.mutableGetResponse, { seq, value, signature }))
    req.reply(null)
  }

  onimmutableget(req) {
    if (!req.target) return

    const k = b4a.toString(req.target, 'hex')
    const value = this.immutables.get(k)

    req.reply(value || null)
  }

  onimmutableput(req) {
    if (!req.target || !req.token || !req.value) return

    const hash = b4a.alloc(32)
    sodium.crypto_generichash(hash, req.value)
    if (!b4a.equals(hash, req.target)) return

    const k = b4a.toString(hash, 'hex')
    this.immutables.set(k, unslab(req.value))

    req.reply(null)
  }

  onplugin(req) {
    if (!req.value) return

    const plugreq = decode(m.pluginRequest, req.value)
    if (plugreq === null) return

    const p = this.dht.plugins.get(plugreq.plugin)
    if (!p || p.version !== plugreq.version) return

    p.onrequest(plugreq, req)
  }

  destroy() {
    this.records.destroy()
    this.refreshes.destroy()
    this.mutables.destroy()
    this.immutables.destroy()
  }

  static signMutable(seq, value, keyPair) {
    const signable = b4a.allocUnsafe(32 + 32)
    const hash = signable.subarray(32)

    signable.set(NS.MUTABLE_PUT, 0)

    sodium.crypto_generichash(hash, c.encode(m.mutableSignable, { seq, value }))
    return sign(signable, keyPair)
  }

  static verifyMutable(signature, seq, value, publicKey) {
    return verifyMutable(signature, seq, value, publicKey)
  }

  static signAnnounce(target, token, id, ann, keyPair) {
    return sign(annSignable(target, token, id, ann, NS.ANNOUNCE), keyPair)
  }

  static signUnannounce(target, token, id, ann, keyPair) {
    return sign(annSignable(target, token, id, ann, NS.UNANNOUNCE), keyPair)
  }
}

function verifyMutable(signature, seq, value, publicKey) {
  const signable = b4a.allocUnsafe(32 + 32)
  const hash = signable.subarray(32)

  signable.set(NS.MUTABLE_PUT, 0)

  sodium.crypto_generichash(hash, c.encode(m.mutableSignable, { seq, value }))
  return sodium.crypto_sign_verify_detached(signature, signable, publicKey)
}

function annSignable(target, token, id, ann, ns) {
  const signable = b4a.allocUnsafe(32 + 32)
  const hash = signable.subarray(32)

  signable.set(ns, 0)

  sodium.crypto_generichash_batch(hash, [
    target,
    id,
    token,
    c.encode(m.peer, ann.peer), // note that this is the partial encoding of the announce message so we could just use that for perf
    ann.refresh || EMPTY
  ])

  return signable
}

function sign(signable, keyPair) {
  if (keyPair.sign) {
    return keyPair.sign(signable)
  }
  const secretKey = keyPair.secretKey ? keyPair.secretKey : keyPair
  const signature = b4a.allocUnsafe(64)
  sodium.crypto_sign_detached(signature, signable, secretKey)
  return signature
}

function decode(enc, val) {
  try {
    return val && c.decode(enc, val)
  } catch (err) {
    return null
  }
}
module.exports = class RawStreamSet {
  constructor(dht) {
    this._dht = dht

    this._prefix = 16 - 1 // 16 is the default stream-set side in udx
    this._streams = new Map()
  }

  get size() {
    return this._streams.size
  }

  [Symbol.iterator]() {
    return this._streams.values()
  }

  add(opts) {
    const self = this

    // TODO: we should prob have a udx helper for id generation, given the slight complexity
    // of the below. requires a PRNG in udx tho.

    let id = 0

    while (true) {
      id = (Math.random() * 0x100000000) >>> 0

      if (this._streams.has(id & this._prefix)) continue
      break
    }

    // always have ~50% change of rolling a free one
    if (2 * this._streams.size >= this._prefix) {
      // ie 0b11111 = 0b1111 + 1 + 0b1111
      this._prefix = 2 * this._prefix + 1

      // move the prefixes over
      const next = new Map()
      for (const stream of this._streams.values()) {
        next.set(stream.id & this._prefix, stream)
      }
      this._streams = next
    }

    const stream = this._dht.udx.createStream(id, opts)
    this._streams.set(id & this._prefix, stream)

    stream.on('close', onclose)

    return stream

    function onclose() {
      self._streams.delete(id & self._prefix)
    }
  }

  async clear() {
    const destroying = []

    for (const stream of this._streams.values()) {
      destroying.push(new Promise((resolve) => stream.once('close', resolve).destroy()))
    }

    await Promise.allSettled(destroying)
  }
}
const c = require('compact-encoding')
const Cache = require('xache')
const safetyCatch = require('safety-catch')
const b4a = require('b4a')
const { handshake, holepunch } = require('./messages')
const { COMMANDS } = require('./constants')
const { BAD_HANDSHAKE_REPLY, BAD_HOLEPUNCH_REPLY } = require('./errors')

const FROM_CLIENT = 0
const FROM_SERVER = 1
const FROM_RELAY = 2
const FROM_SECOND_RELAY = 3
const REPLY = 4

// TODO: While the current design is very trustless in regards to clients/servers trusting the DHT,
// we should add a bunch of rate limits everywhere, especially including here to avoid bad users
// using a DHT node to relay traffic indiscriminately using the connect/holepunch messages.
// That's mostly from an abuse POV as none of the messsages do amplication.

module.exports = class Router {
  constructor(dht, opts) {
    this.dht = dht
    this.forwards = new Cache(opts.forwards)
  }

  set(target, state) {
    if (state.onpeerhandshake) {
      this.forwards.retain(toString(target), state)
    } else {
      this.forwards.set(toString(target), state)
    }
  }

  get(target) {
    return this.forwards.get(toString(target))
  }

  delete(target) {
    this.forwards.delete(toString(target))
  }

  destroy() {
    this.forwards.destroy()
  }

  async peerHandshake(target, { noise, peerAddress, relayAddress, socket, session }, to) {
    const dht = this.dht

    const requestValue = c.encode(handshake, {
      mode: FROM_CLIENT,
      noise,
      peerAddress,
      relayAddress
    })

    const res = await dht.request(
      { command: COMMANDS.PEER_HANDSHAKE, target, value: requestValue },
      to,
      { socket, session }
    )

    const hs = decode(handshake, res.value)
    if (
      !hs ||
      hs.mode !== REPLY ||
      to.host !== res.from.host ||
      to.port !== res.from.port ||
      !hs.noise
    ) {
      throw BAD_HANDSHAKE_REPLY()
    }

    return {
      noise: hs.noise,
      relayed: !!hs.peerAddress,
      serverAddress: hs.peerAddress || to,
      clientAddress: res.to
    }
  }

  async onpeerhandshake(req) {
    const hs = req.value && decode(handshake, req.value)
    if (!hs) return

    const { mode, noise, peerAddress, relayAddress } = hs

    const state = req.target && this.get(req.target)
    const isServer = !!(state && state.onpeerhandshake)
    const relay = state && state.relay

    if (isServer) {
      let reply = null
      try {
        reply = noise && (await state.onpeerhandshake({ noise, peerAddress }, req))
      } catch (e) {
        safetyCatch(e)
        return
      }
      if (!reply || !reply.noise) return
      const opts = { socket: reply.socket, closerNodes: false, token: false }

      switch (mode) {
        case FROM_CLIENT: {
          req.reply(
            c.encode(handshake, { mode: REPLY, noise: reply.noise, peerAddress: null }),
            opts
          )
          return
        }
        case FROM_RELAY: {
          req.relay(
            c.encode(handshake, { mode: FROM_SERVER, noise: reply.noise, peerAddress }),
            req.from,
            opts
          )
          return
        }
        case FROM_SECOND_RELAY: {
          if (!relayAddress) return
          req.relay(
            c.encode(handshake, { mode: FROM_SERVER, noise: reply.noise, peerAddress }),
            relayAddress,
            opts
          )
          return // eslint-disable-line
        }
      }
    } else {
      switch (mode) {
        case FROM_CLIENT: {
          // TODO: if no relay is known route closer to the target instead of timing out
          if (!noise) return
          if (!relay && !relayAddress) {
            // help the user route
            req.reply(null, { token: false, closerNodes: true })
            return
          }
          req.relay(
            c.encode(handshake, {
              mode: FROM_RELAY,
              noise,
              peerAddress: req.from,
              relayAddress: null
            }),
            relayAddress || relay
          )
          return
        }
        case FROM_RELAY: {
          if (!relay || !noise) return
          req.relay(
            c.encode(handshake, {
              mode: FROM_SECOND_RELAY,
              noise,
              peerAddress,
              relayAddress: req.from
            }),
            relay
          )
          return
        }
        case FROM_SERVER: {
          if (!peerAddress || !noise) return
          req.reply(
            c.encode(handshake, { mode: REPLY, noise, peerAddress: req.from, relayAddress: null }),
            { to: peerAddress, closerNodes: false, token: false }
          )
          return // eslint-disable-line
        }
      }
    }
  }

  async peerHolepunch(target, { id, payload, peerAddress, socket, session }, to) {
    const dht = this.dht
    const requestValue = c.encode(holepunch, {
      mode: FROM_CLIENT,
      id,
      payload,
      peerAddress
    })

    const res = await dht.request(
      { command: COMMANDS.PEER_HOLEPUNCH, target, value: requestValue },
      to,
      { socket, session }
    )

    const hp = decode(holepunch, res.value)
    if (!hp || hp.mode !== REPLY || to.host !== res.from.host || to.port !== res.from.port) {
      throw BAD_HOLEPUNCH_REPLY()
    }

    return {
      from: res.from,
      to: res.to,
      payload: hp.payload,
      peerAddress: hp.peerAddress || to
    }
  }

  async onpeerholepunch(req) {
    const hp = req.value && decode(holepunch, req.value)
    if (!hp) return

    const { mode, id, payload, peerAddress } = hp

    const state = req.target && this.get(req.target)
    const isServer = !!(state && state.onpeerholepunch)
    const relay = state && state.relay

    switch (mode) {
      case FROM_CLIENT: {
        if (!peerAddress && !relay) return
        req.relay(
          c.encode(holepunch, { mode: FROM_RELAY, id, payload, peerAddress: req.from }),
          peerAddress || relay
        )
        return
      }
      case FROM_RELAY: {
        if (!isServer || !peerAddress) return
        let reply = null
        try {
          reply = await state.onpeerholepunch({ id, payload, peerAddress }, req)
        } catch (e) {
          safetyCatch(e)
          return
        }
        if (!reply) return
        const opts = { socket: reply.socket, closerNodes: false, token: false }
        req.relay(
          c.encode(holepunch, { mode: FROM_SERVER, id: 0, payload: reply.payload, peerAddress }),
          req.from,
          opts
        )
        return
      }
      case FROM_SERVER: {
        req.reply(c.encode(holepunch, { mode: REPLY, id, payload, peerAddress: req.from }), {
          to: peerAddress,
          closerNodes: false,
          token: false
        })
        return // eslint-disable-line
      }
    }
  }
}

function decode(enc, val) {
  try {
    return c.decode(enc, val)
  } catch {
    return null
  }
}

function toString(t) {
  return typeof t === 'string' ? t : b4a.toString(t, 'hex')
}
const sodium = require('sodium-universal')
const b4a = require('b4a')
const { holepunchPayload } = require('./messages')

module.exports = class HolepunchPayload {
  constructor(holepunchSecret) {
    this._sharedSecret = holepunchSecret
    this._localSecret = b4a.allocUnsafe(32)

    sodium.randombytes_buf(this._localSecret)
  }

  decrypt(buffer) {
    const state = { start: 24, end: buffer.byteLength - 16, buffer }

    if (state.end <= state.start) return null

    const nonce = buffer.subarray(0, 24)
    const msg = state.buffer.subarray(state.start, state.end)
    const cipher = state.buffer.subarray(state.start)

    if (!sodium.crypto_secretbox_open_easy(msg, cipher, nonce, this._sharedSecret)) return null

    try {
      return holepunchPayload.decode(state)
    } catch {
      return null
    }
  }

  encrypt(payload) {
    const state = { start: 24, end: 24, buffer: null }
    holepunchPayload.preencode(state, payload)
    state.buffer = b4a.allocUnsafe(state.end + 16)

    const nonce = state.buffer.subarray(0, 24)
    const msg = state.buffer.subarray(state.start, state.end)
    const cipher = state.buffer.subarray(state.start)

    holepunchPayload.encode(state, payload)
    sodium.randombytes_buf(nonce)
    sodium.crypto_secretbox_easy(cipher, msg, nonce, this._sharedSecret)

    return state.buffer
  }

  token(addr) {
    const out = b4a.allocUnsafe(32)
    sodium.crypto_generichash(out, b4a.from(addr.host), this._localSecret)
    return out
  }
}
const DONE = Promise.resolve(true)
const DESTROYED = Promise.resolve(false)

module.exports = class Semaphore {
  constructor(limit = 1) {
    this.limit = limit
    this.active = 0
    this.waiting = []

    this.flushedPromise = null
    this.flushedResolve = null

    this.destroyed = false

    this._onwait = this._queueWaiting.bind(this)
    this._onflush = this._queueFlushed.bind(this)
  }

  _queueWaiting(resolve) {
    this.waiting.push(resolve)
  }

  _queueFlushed(resolve) {
    this.flushedResolve = resolve
  }

  wait() {
    if (this.destroyed === true) return DESTROYED

    if (this.active < this.limit && this.waiting.length === 0) {
      this.active++
      return DONE
    }

    return new Promise(this._onwait)
  }

  signal() {
    if (this.destroyed === true) return

    this.active--
    while (this.active < this.limit && this.waiting.length > 0 && this.destroyed === false) {
      this.active++
      this.waiting.shift()(true)
    }

    if (this.active === 0 && this.flushedResolve) {
      const resolve = this.flushedResolve
      this.flushedResolve = null
      this.flushedPromise = null
      resolve(true)
    }
  }

  async flush() {
    if (this.destroyed === true) return
    if (this.active === 0) return
    if (this.flushedPromise) return this.flushedPromise
    this.flushedPromise = new Promise(this._onflush)
    return this.flushedPromise
  }

  destroy() {
    this.destroyed = true
    this.active = 0
    while (this.waiting.length) this.waiting.pop()(false)
    if (this.flushedResolve) this.flushedResolve(false)
  }
}
const { EventEmitter } = require('events')
const safetyCatch = require('safety-catch')
const NoiseSecretStream = require('@hyperswarm/secret-stream')
const b4a = require('b4a')
const relay = require('blind-relay')
const NoiseWrap = require('./noise-wrap')
const Announcer = require('./announcer')
const { FIREWALL, ERROR } = require('./constants')
const { unslabbedHash } = require('./crypto')
const SecurePayload = require('./secure-payload')
const Holepuncher = require('./holepuncher')
const { isPrivate } = require('bogon')
const { ALREADY_LISTENING, NODE_DESTROYED, KEYPAIR_ALREADY_USED } = require('./errors')

const HANDSHAKE_CLEAR_WAIT = 10000
const HANDSHAKE_INITIAL_TIMEOUT = 10000

module.exports = class Server extends EventEmitter {
  constructor(dht, opts = {}) {
    super()

    this.dht = dht
    this.target = null

    this.closed = false
    this.firewall = opts.firewall || (() => false)
    this.holepunch = opts.holepunch || (() => true)
    this.relayThrough = opts.relayThrough || null
    this.relayKeepAlive = opts.relayKeepAlive || 5000
    this.pool = opts.pool || null
    this.createHandshake = opts.createHandshake || defaultCreateHandshake
    this.createSecretStream = opts.createSecretStream || defaultCreateSecretStream
    this.suspended = false
    this.handshakeClearWait = opts.handshakeClearWait || HANDSHAKE_CLEAR_WAIT

    this._shareLocalAddress = opts.shareLocalAddress !== false
    this._reusableSocket = !!opts.reusableSocket
    this._neverPunch = opts.holepunch === false // useful for fully disabling punching
    this._keyPair = null
    this._announcer = null
    this._connects = new Map()
    this._holepunches = []
    this._listening = null
    this._closing = null
  }

  get listening() {
    return this._listening !== null
  }

  get publicKey() {
    return this._keyPair && this._keyPair.publicKey
  }

  get relayAddresses() {
    return this._announcer ? this._announcer.relayAddresses : []
  }

  onconnection(encryptedSocket) {
    this.emit('connection', encryptedSocket)
  }

  async suspend({ log = noop } = {}) {
    log('Suspending hyperdht server')
    if (this._listening !== null) await this._listening
    log('Suspending hyperdht server (post listening)')
    this.suspended = true
    this._clearAll()
    return this._announcer ? this._announcer.suspend({ log }) : Promise.resolve()
  }

  async resume() {
    if (this._listening !== null) await this._listening
    this.suspended = false
    return this._announcer ? this._announcer.resume() : Promise.resolve()
  }

  address() {
    if (!this._keyPair) return null

    return {
      publicKey: this._keyPair.publicKey,
      host: this.dht.host,
      port: this.dht.port
    }
  }

  close() {
    if (this._closing) return this._closing
    this._closing = this._close()
    return this._closing
  }

  _gc() {
    this.dht.listening.delete(this)
    if (this.target) this.dht._router.delete(this.target)
  }

  async _stopListening() {
    try {
      if (this._announcer) await this._announcer.stop()
    } catch {
      // ignore
    }

    this._announcer = null
    this._listening = null
    this._keyPair = null
  }

  async _close() {
    if (this._listening === null) {
      this.closed = true
      this.emit('close')
      return
    }

    try {
      await this._listening
    } catch (err) {
      safetyCatch(err)
    }

    this._gc()
    this._clearAll()

    await this._stopListening()

    this.closed = true
    this.emit('close')
  }

  _clearAll() {
    while (this._holepunches.length > 0) {
      const h = this._holepunches.pop()
      if (h && h.puncher) h.puncher.destroy()
      if (h && h.clearing) clearTimeout(h.clearing)
      if (h && h.prepunching) clearTimeout(h.prepunching)
      if (h && h.rawStream) h.rawStream.destroy()
    }

    this._connects.clear()
  }

  async listen(keyPair = this.dht.defaultKeyPair, opts = {}) {
    if (this._listening !== null) throw ALREADY_LISTENING()
    if (this.dht.destroyed) throw NODE_DESTROYED()

    this._listening = this._listen(keyPair, opts)
    await this._listening
    return this
  }

  async _listen(keyPair, opts) {
    // From now on, the DHT object which created me is responsible for closing me
    this.dht.listening.add(this)

    try {
      await this.dht.bind()
      if (this._closing) return

      for (const s of this.dht.listening) {
        if (s._keyPair && b4a.equals(s._keyPair.publicKey, keyPair.publicKey)) {
          throw KEYPAIR_ALREADY_USED()
        }
      }

      this.target = unslabbedHash(keyPair.publicKey)
      this._keyPair = keyPair
      this._announcer = new Announcer(this.dht, keyPair, this.target, opts)

      this.dht._router.set(this.target, {
        relay: null,
        record: this._announcer.record,
        onpeerhandshake: this._onpeerhandshake.bind(this),
        onpeerholepunch: this._onpeerholepunch.bind(this)
      })

      // warm it up for now
      this._localAddresses().catch(safetyCatch)

      await this._announcer.start()
    } catch (err) {
      await this._stopListening()
      this._gc()
      throw err
    }

    if (this._closing) return
    if (this.suspended) await this._announcer.suspend()

    if (this._closing) return
    if (this.dht.destroyed) throw NODE_DESTROYED()

    if (this.pool) this.pool._attachServer(this)

    this.emit('listening')
  }

  refresh() {
    if (this._announcer && !this.suspended) this._announcer.refresh()
  }

  notifyOnline() {
    if (this._announcer) this._announcer.online.notify()
  }

  _localAddresses() {
    return this.dht.validateLocalAddresses(Holepuncher.localAddresses(this.dht.io.serverSocket))
  }

  async _addHandshake(k, noise, clientAddress, { from, to: serverAddress, socket }, direct) {
    let id = this._holepunches.indexOf(null)
    if (id === -1) id = this._holepunches.push(null) - 1

    const hs = {
      round: 0,
      reply: null,
      puncher: null,
      payload: null,
      rawStream: null,
      encryptedSocket: null,
      prepunching: null,
      firewalled: true,
      clearing: null,
      onsocket: null,
      aborted: false,

      // Relay state
      relayTimeout: null,
      relayToken: null,
      relaySocket: null,
      relayClient: null,
      relayPaired: false
    }

    this._holepunches[id] = hs

    const handshake = this.createHandshake(this._keyPair, null)

    let remotePayload
    try {
      remotePayload = await handshake.recv(noise)
    } catch (err) {
      safetyCatch(err)
      this._clearLater(hs, id, k)
      return null
    }

    if (this._closing || this.suspended) return null

    try {
      hs.firewalled = await this.firewall(handshake.remotePublicKey, remotePayload, clientAddress)
    } catch (err) {
      safetyCatch(err)
    }

    if (this._closing || this.suspended) return null

    if (hs.firewalled) {
      this._clearLater(hs, id, k)
      return null
    }

    const error =
      remotePayload.version === 1
        ? remotePayload.udx
          ? ERROR.NONE
          : ERROR.ABORTED
        : ERROR.VERSION_MISMATCH

    const addresses = []
    const ourRemoteAddr = this.dht.remoteAddress()
    const ourLocalAddrs = this._shareLocalAddress ? await this._localAddresses() : null

    if (this._closing || this.suspended) return null

    if (ourRemoteAddr) addresses.push(ourRemoteAddr)
    if (ourLocalAddrs) addresses.push(...ourLocalAddrs)

    if (error === ERROR.NONE) {
      hs.rawStream = this.dht.createRawStream({
        framed: true,
        firewall(socket, port, host) {
          if (!(port > 0 && port < 65536)) return true

          // Check if the traffic originated from the socket on which we're expecting relay traffic. If so,
          // we haven't hole punched yet and the other side is just sending us traffic through the relay.
          if (hs.relaySocket && isRelay(hs.relaySocket, socket, port, host)) {
            return false
          }

          hs.onsocket(socket, port, host)
          return false
        }
      })

      hs.rawStream.on('error', autoDestroy)

      // Handles the case where onsocket is never called, but the stream got setup
      // This can happen on a relayed connection which never connects directly
      // (onsocket is called there only when the direct connection is established)
      const onrawstreamclose = () => {
        if (this._closing) return
        this._clearLater(hs, id, k)
      }
      hs.rawStream.on('close', onrawstreamclose)

      hs.onsocket = (socket, port, host) => {
        if (hs.rawStream === null) return // Already hole punched

        this._clearLater(hs, id, k)

        if (hs.prepunching) {
          clearTimeout(hs.prepunching)
          hs.prepunching = null
        }

        if (this._reusableSocket && remotePayload.udx.reusableSocket) {
          this.dht._socketPool.routes.add(handshake.remotePublicKey, hs.rawStream)
        }

        hs.rawStream.removeListener('error', autoDestroy)
        hs.rawStream.removeListener('close', onrawstreamclose)

        if (hs.rawStream.connected) {
          const remoteChanging = hs.rawStream.changeRemote(socket, remotePayload.udx.id, port, host)

          if (remoteChanging) remoteChanging.catch(safetyCatch)
        } else {
          hs.rawStream.connect(socket, remotePayload.udx.id, port, host)
          hs.encryptedSocket = this.createSecretStream(false, hs.rawStream, {
            handshake: h,
            keepAlive: this.dht.connectionKeepAlive
          })

          this.onconnection(hs.encryptedSocket)
        }

        if (hs.puncher) {
          hs.puncher.onabort = noop
          hs.puncher.destroy()
        }

        hs.rawStream = null
      }

      function autoDestroy() {
        if (hs.puncher) hs.puncher.destroy()
      }
    }

    const relayAddresses = this.relayAddresses
    const relayThrough = selectRelay(this.relayThrough)

    if (relayThrough) hs.relayToken = relay.token()

    try {
      hs.reply = await handshake.send({
        error,
        firewall: ourRemoteAddr ? FIREWALL.OPEN : FIREWALL.UNKNOWN,
        holepunch: ourRemoteAddr ? null : { id, relays: this._announcer.relays },
        addresses4: addresses,
        addresses6: null,
        udx: {
          reusableSocket: this._reusableSocket,
          id: hs.rawStream ? hs.rawStream.id : 0,
          seq: 0
        },
        secretStream: {},
        relayThrough: relayThrough ? { publicKey: relayThrough, token: hs.relayToken } : null,
        relayAddresses: relayAddresses.length ? relayAddresses : null
      })
    } catch (err) {
      safetyCatch(err)
      if (hs.rawStream) hs.rawStream.destroy()
      this._clearLater(hs, id, k)
      return null
    }

    if (this._closing || this.suspended) {
      if (hs.rawStream) hs.rawStream.destroy()
      return null
    }

    const h = handshake.final()

    if (error !== ERROR.NONE) {
      if (hs.rawStream) hs.rawStream.destroy()
      this._clearLater(hs, id, k)
      return hs
    }

    if (remotePayload.firewall === FIREWALL.OPEN || direct) {
      const sock = direct ? socket : this.dht.socket
      this.dht.stats.punches.open++
      hs.onsocket(sock, clientAddress.port, clientAddress.host)
      return hs
    }

    if (relayThrough || remotePayload.relayThrough) {
      this._relayConnection(hs, relayThrough, remotePayload, h)
    }

    const onabort = () => {
      hs.aborted = true
      if (hs.prepunching) clearTimeout(hs.prepunching)
      hs.prepunching = null
      if (hs.rawStream.destroyed) {
        this._clearLater(hs, id, k)
        return
      }

      hs.rawStream.on('close', () => this._clearLater(hs, id, k))
      if (hs.relayToken === null) hs.rawStream.destroy()
    }

    if (!direct && clientAddress.host === serverAddress.host) {
      const clientAddresses = remotePayload.addresses4.filter(onlyPrivateHosts)

      if (clientAddresses.length > 0 && this._shareLocalAddress) {
        const myAddresses = await this._localAddresses()
        const addr = Holepuncher.matchAddress(myAddresses, clientAddresses)

        if (addr) {
          hs.prepunching = setTimeout(onabort, HANDSHAKE_INITIAL_TIMEOUT)
          return hs
        }
      }
    }

    if (this._closing || this.suspended) return null

    if (ourRemoteAddr || this._neverPunch) {
      hs.prepunching = setTimeout(onabort, HANDSHAKE_INITIAL_TIMEOUT)
      return hs
    }

    hs.payload = new SecurePayload(h.holepunchSecret)
    hs.puncher = new Holepuncher(this.dht, this.dht.session(), false, remotePayload.firewall)

    hs.puncher.onconnect = hs.onsocket
    hs.puncher.onabort = onabort
    hs.prepunching = setTimeout(hs.puncher.destroy.bind(hs.puncher), HANDSHAKE_INITIAL_TIMEOUT)

    return hs
  }

  _clearLater(hs, id, k) {
    if (hs.clearing) return
    hs.clearing = setTimeout(() => this._clear(hs, id, k), this.handshakeClearWait)
  }

  _clear(hs, id, k) {
    if (id >= this._holepunches.length || this._holepunches[id] !== hs) return
    if (hs.clearing) clearTimeout(hs.clearing)

    this._holepunches[id] = null
    while (
      this._holepunches.length > 0 &&
      this._holepunches[this._holepunches.length - 1] === null
    ) {
      this._holepunches.pop()
    }
    this._connects.delete(k)
  }

  async _onpeerhandshake({ noise, peerAddress }, req) {
    const k = b4a.toString(noise, 'hex')

    // The next couple of statements MUST run within the same tick to prevent
    // a malicious peer from flooding us with handshakes.
    let p = this._connects.get(k)
    if (!p) {
      p = this._addHandshake(k, noise, peerAddress || req.from, req, !peerAddress)
      this._connects.set(k, p)
    }

    const h = await p
    if (!h) return null

    if (this._closing !== null || this.suspended) return null

    return { socket: h.puncher && h.puncher.socket, noise: h.reply }
  }

  async _onpeerholepunch({ id, peerAddress, payload }, req) {
    const h = id < this._holepunches.length ? this._holepunches[id] : null
    if (!h) return null

    if (!peerAddress || this._closing !== null || this.suspended) return null

    const p = h.puncher
    if (!p || !p.socket) return this._abort(h) // not opened

    const remotePayload = h.payload.decrypt(payload)
    if (!remotePayload) return null

    const isServerRelay = this._announcer.isRelay(req.from)
    const { error, firewall, round, punching, addresses, remoteAddress, remoteToken } =
      remotePayload

    if (error !== ERROR.NONE) {
      // We actually do not need to set the round here, but just do it for consistency.
      if (round >= h.round) h.round = round
      return this._abort(h)
    }

    const token = h.payload.token(peerAddress)
    const echoed = isServerRelay && !!remoteToken && b4a.equals(token, remoteToken)

    // Update our heuristics here
    if (req.socket === p.socket) {
      p.nat.add(req.to, req.from)
    }

    if (round >= h.round) {
      h.round = round
      p.updateRemote({ punching, firewall, addresses, verified: echoed ? peerAddress.host : null })
    }

    // Wait for the analyzer to reach a conclusion...
    let stable = await p.analyze(false)
    if (p.destroyed) return null

    if (!p.remoteHolepunching && !stable) {
      stable = await p.analyze(true)
      if (p.destroyed) return null
      if (!stable) return this._abort(h)
    }

    // Fast mode! If we are consistent and the remote has opened a session to us (remoteAddress)
    // then fire a quick punch back. Note the await here just waits for the udp socket to flush.
    if (
      isConsistent(p.nat.firewall) &&
      remoteAddress &&
      hasSameAddr(p.nat.addresses, remoteAddress)
    ) {
      await p.ping(peerAddress)
      if (p.destroyed) return null
    }

    // Remote said they are punching (or willing to), so we will punch as well.
    // Note that this returns when the punching has STARTED, so no guarantee
    // we will have a connection after this promise etc.
    if (p.remoteHolepunching) {
      // TODO: still continue here if a local connection might work, but then do not holepunch...
      if (!this.holepunch(p.remoteFirewall, p.nat.firewall, p.remoteAddresses, p.nat.addresses)) {
        return p.destroyed ? null : this._abort(h)
      }

      if (h.prepunching) {
        clearTimeout(h.prepunching)
        h.prepunching = null
      }

      if (p.remoteFirewall >= FIREWALL.RANDOM || p.nat.firewall >= FIREWALL.RANDOM) {
        if (
          this.dht._randomPunches >= this.dht._randomPunchLimit ||
          Date.now() - this.dht._lastRandomPunch < this.dht._randomPunchInterval
        ) {
          if (!h.relayToken) return this._abort(h, ERROR.TRY_LATER)
          return {
            socket: p.socket,
            payload: h.payload.encrypt({
              error: ERROR.TRY_LATER,
              firewall: p.nat.firewall,
              round: h.round,
              connected: p.connected,
              punching: p.punching,
              addresses: p.nat.addresses,
              remoteAddress: null,
              token: isServerRelay ? token : null,
              remoteToken: remotePayload.token
            })
          }
        }
      }

      const punching = await p.punch()
      if (p.destroyed) return null
      if (!punching) return this._abort(h)
    }

    // Freeze that analysis as soon as we have a result we are giving to the other peer
    if (p.nat.firewall !== FIREWALL.UNKNOWN) {
      p.nat.freeze()
    }

    return {
      socket: p.socket,
      payload: h.payload.encrypt({
        error: ERROR.NONE,
        firewall: p.nat.firewall,
        round: h.round,
        connected: p.connected,
        punching: p.punching,
        addresses: p.nat.addresses,
        remoteAddress: null,
        token: isServerRelay ? token : null,
        remoteToken: remotePayload.token
      })
    }
  }

  _abort(h, error = ERROR.ABORTED) {
    if (!h.payload) {
      if (h.puncher) h.puncher.destroy()
      return null
    }

    const payload = h.payload.encrypt({
      error,
      firewall: FIREWALL.UNKNOWN,
      round: h.round,
      connected: false,
      punching: false,
      addresses: null,
      remoteAddress: null,
      token: null,
      remoteToken: null
    })

    h.puncher.destroy()

    return { socket: this.dht.socket, payload }
  }

  _relayConnection(hs, relayThrough, remotePayload, h) {
    this.dht.stats.relaying.attempts++

    let isInitiator
    let publicKey
    let token

    if (relayThrough) {
      isInitiator = true
      publicKey = relayThrough
      token = hs.relayToken
    } else {
      isInitiator = false
      publicKey = remotePayload.relayThrough.publicKey
      token = remotePayload.relayThrough.token
    }

    hs.relayToken = token
    hs.relaySocket = this.dht.connect(publicKey)
    hs.relaySocket.setKeepAlive(this.relayKeepAlive)
    hs.relayClient = relay.Client.from(hs.relaySocket, { id: hs.relaySocket.publicKey })
    hs.relayTimeout = setTimeout(onabort, 15000)

    hs.relayClient
      .pair(isInitiator, token, hs.rawStream)
      .on('error', onabort)
      .on('data', (remoteId) => {
        if (hs.relayTimeout) clearRelayTimeout(hs)
        if (hs.rawStream === null) {
          onabort(null)
          return
        }

        hs.relayPaired = true
        this.dht.stats.relaying.successes++

        if (hs.prepunching) clearTimeout(hs.prepunching)
        hs.prepunching = null

        const { remotePort, remoteHost, socket } = hs.relaySocket.rawStream

        hs.rawStream
          .on('close', () => hs.relaySocket.destroy())
          .connect(socket, remoteId, remotePort, remoteHost)

        hs.encryptedSocket = this.createSecretStream(false, hs.rawStream, { handshake: h })

        this.onconnection(hs.encryptedSocket)
      })

    const dht = this.dht
    function onabort() {
      if (!hs.relayPaired) dht.stats.relaying.aborts++
      if (hs.relayTimeout) clearRelayTimeout(hs)
      const socket = hs.relaySocket
      hs.relayToken = null
      hs.relaySocket = null
      if (socket) socket.destroy()
      if (hs.aborted && hs.rawStream) hs.rawStream.destroy()
    }
  }
}

function clearRelayTimeout(hs) {
  clearTimeout(hs.relayTimeout)
  hs.relayTimeout = null
}

function isConsistent(fw) {
  return fw === FIREWALL.OPEN || fw === FIREWALL.CONSISTENT
}

function hasSameAddr(addrs, other) {
  if (addrs === null) return false

  for (const addr of addrs) {
    if (addr.port === other.port && addr.host === other.host) return true
  }
  return false
}

function defaultCreateHandshake(keyPair, remotePublicKey) {
  return new NoiseWrap(keyPair, remotePublicKey)
}

function defaultCreateSecretStream(isInitiator, rawStream, opts) {
  return new NoiseSecretStream(isInitiator, rawStream, opts)
}

function onlyPrivateHosts(addr) {
  return isPrivate(addr.host)
}

function isRelay(relaySocket, socket, port, host) {
  const stream = relaySocket.rawStream
  if (!stream) return false
  if (stream.socket !== socket) return false
  return port === stream.remotePort && host === stream.remoteHost
}

function selectRelay(relayThrough) {
  if (typeof relayThrough === 'function') relayThrough = relayThrough()
  if (relayThrough === null) return null
  if (Array.isArray(relayThrough)) {
    return relayThrough[Math.floor(Math.random() * relayThrough.length)]
  }
  return relayThrough
}

function noop() {}
module.exports = class Sleeper {
  constructor() {
    this._timeout = null
    this._resolve = null

    this._start = (resolve) => {
      this._resolve = resolve
    }

    this._trigger = () => {
      if (this._resolve === null) return
      const resolve = this._resolve
      this._timeout = null
      this._resolve = null
      resolve()
    }
  }

  pause(ms) {
    const p = new Promise(this._start)
    if (this._timeout !== null) {
      clearTimeout(this._timeout)
      this._trigger()
    }
    this._timeout = setTimeout(this._trigger, ms)
    return p
  }

  resume() {
    if (this._timeout !== null) {
      clearTimeout(this._timeout)
      this._trigger()
    }
  }
}
const b4a = require('b4a')

const LINGER_TIME = 3000

module.exports = class SocketPool {
  constructor(dht, host) {
    this._dht = dht
    this._sockets = new Map()
    this._lingering = new Set() // updated by the ref
    this._host = host

    this.routes = new SocketRoutes(this)
  }

  _onmessage(ref, data, address) {
    this._dht.onmessage(ref.socket, data, address)
  }

  _add(ref) {
    this._sockets.set(ref.socket, ref)
  }

  _remove(ref) {
    this._sockets.delete(ref.socket)
    this._lingering.delete(ref)
  }

  lookup(socket) {
    return this._sockets.get(socket) || null
  }

  setReusable(socket, bool) {
    const ref = this.lookup(socket)
    if (ref) ref.reusable = bool
  }

  acquire() {
    // TODO: Enable socket reuse
    return new SocketRef(this)
  }

  async destroy() {
    const closing = []

    for (const ref of this._sockets.values()) {
      ref._unlinger()
      closing.push(ref.socket.close())
    }

    await Promise.allSettled(closing)
  }
}

class SocketRoutes {
  constructor(pool) {
    this._pool = pool
    this._routes = new Map()
  }

  add(publicKey, rawStream) {
    if (rawStream.socket) this._onconnect(publicKey, rawStream)
    else rawStream.on('connect', this._onconnect.bind(this, publicKey, rawStream))
  }

  get(publicKey) {
    const id = b4a.toString(publicKey, 'hex')
    const route = this._routes.get(id)
    if (!route) return null
    return route
  }

  _onconnect(publicKey, rawStream) {
    const id = b4a.toString(publicKey, 'hex')
    const socket = rawStream.socket

    let route = this._routes.get(id)

    if (!route) {
      const gc = () => {
        if (this._routes.get(id) === route) this._routes.delete(id)
        socket.removeListener('close', gc)
      }

      route = {
        socket,
        address: { host: rawStream.remoteHost, port: rawStream.remotePort },
        gc
      }

      this._routes.set(id, route)
      socket.on('close', gc)
    }

    this._pool.setReusable(socket, true)

    rawStream.on('error', () => {
      this._pool.setReusable(socket, false)
      if (!route) route = this._routes.get(id)
      if (route && route.socket === socket) route.gc()
    })
  }
}

// TODO: we should just make some "user data" object on udx to allow to attach this info
class SocketRef {
  constructor(pool) {
    this._pool = pool

    // Events
    this.onholepunchmessage = noop

    // Whether it should teardown immediately or wait a bit
    this.reusable = false

    this.socket = pool._dht.udx.createSocket()
    this.socket
      .on('close', this._onclose.bind(this))
      .on('message', this._onmessage.bind(this))
      .on('idle', this._onidle.bind(this))
      .on('busy', this._onbusy.bind(this))
      .bind(0, this._pool._host)

    this._refs = 1
    this._released = false
    this._closed = false

    this._timeout = null
    this._wasBusy = false

    this._pool._add(this)
  }

  _onclose() {
    this._pool._remove(this)
  }

  _onmessage(data, address) {
    if (data.byteLength > 1) {
      this._pool._onmessage(this, data, address)
    } else {
      this.onholepunchmessage(data, address, this)
    }
  }

  _onidle() {
    this._closeMaybe()
  }

  _onbusy() {
    this._wasBusy = true
    this._unlinger()
  }

  _reset() {
    this.onholepunchmessage = noop
  }

  _closeMaybe() {
    if (this._refs === 0 && this.socket.idle && !this._timeout) this._close()
  }

  _lingeringClose() {
    this._pool._lingering.delete(this)
    this._timeout = null
    this._closeMaybe()
  }

  _close() {
    this._unlinger()

    if (this.reusable && this._wasBusy) {
      this._wasBusy = false
      this._pool._lingering.add(this)
      this._timeout = setTimeout(this._lingeringClose.bind(this), LINGER_TIME)
      return
    }

    this._closed = true
    this.socket.close()
  }

  _unlinger() {
    if (this._timeout !== null) {
      clearTimeout(this._timeout)
      this._pool._lingering.delete(this)
      this._timeout = null
    }
  }

  get free() {
    return this._refs === 0
  }

  active() {
    this._refs++
    this._unlinger()
  }

  inactive() {
    this._refs--
    this._closeMaybe()
  }

  address() {
    return this.socket.address()
  }

  release() {
    if (this._released) return

    this._released = true
    this._reset()

    this._refs--
    this._closeMaybe()
  }
}

function noop() {}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "hyperdht",
  "version": "6.32.0",
  "description": "The DHT powering Hyperswarm",
  "main": "index.js",
  "browser": "browser.js",
  "bin": {
    "hyperdht": "./bin.js"
  },
  "files": [
    "index.js",
    "browser.js",
    "testnet.js",
    "bin.js",
    "lib/**.js"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    },
    "child_process": {
      "bare": "bare-node-child-process",
      "default": "child_process"
    }
  },
  "dependencies": {
    "@hyperswarm/secret-stream": "^6.6.2",
    "b4a": "^1.3.1",
    "bare-events": "^2.2.0",
    "blind-relay": "^1.3.0",
    "bogon": "^1.0.0",
    "compact-encoding": "^3.0.0",
    "dht-rpc": "^6.15.1",
    "hypercore-crypto": "^3.3.0",
    "hypercore-id-encoding": "^1.2.0",
    "hyperdht-address": "^1.0.1",
    "noise-curve-ed": "^2.0.0",
    "noise-handshake": "^4.0.0",
    "record-cache": "^1.1.1",
    "safety-catch": "^1.0.1",
    "signal-promise": "^1.0.3",
    "sodium-universal": "^5.0.1",
    "streamx": "^2.16.1",
    "unslab": "^1.3.0",
    "xache": "^1.1.0"
  },
  "devDependencies": {
    "bare-node-child-process": "^1.0.1",
    "brittle": "^3.0.0",
    "graceful-goodbye": "^1.3.0",
    "newline-decoder": "^1.0.2",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "test": "prettier --check . && node test/all.js",
    "test:bare": "bare test/all.js",
    "test:generate": "brittle -r test/all.js test/*.js",
    "integration": "brittle test/integration/*.js",
    "end-to-end": "brittle test/end-to-end/*.js"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "directories": {
    "lib": "lib",
    "test": "test"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/hyperdht.git"
  },
  "keywords": [],
  "bugs": {
    "url": "https://github.com/holepunchto/hyperdht/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperdht#readme"
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "hyperschema",
  "version": "1.21.0",
  "description": "Create registries of declarative compact-encoding schemas",
  "files": [
    "lib/*.js",
    "builder.mjs",
    "builder.cjs",
    "runtime.mjs",
    "runtime.cjs",
    "primitives.mjs",
    "primitives.cjs"
  ],
  "exports": {
    "./package": "./package.json",
    ".": {
      "import": "./builder.mjs",
      "default": "./builder.cjs"
    },
    "./runtime": {
      "import": "./runtime.mjs",
      "default": "./runtime.cjs"
    },
    "./primitives": {
      "import": "./primitives.mjs",
      "default": "./primitives.cjs"
    }
  },
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    }
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test/index.js",
    "test:bare": "prettier . --check && bare test/index.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/hyperschema.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/hyperschema/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperschema#readme",
  "dependencies": {
    "bare-fs": "^4.0.1",
    "compact-encoding": "^3.0.0",
    "generate-object-property": "^2.0.0",
    "generate-string": "^1.0.1"
  },
  "devDependencies": {
    "brittle": "^3.7.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "test-tmp": "^1.3.0"
  }
}
module.exports = {
  c: require('compact-encoding')
}
const { EventEmitter } = require('events')
const { getStreamError } = require('streamx')
const DHT = require('hyperdht')
const spq = require('shuffled-priority-queue')
const b4a = require('b4a')
const unslab = require('unslab')

const PeerInfo = require('./lib/peer-info')
const RetryTimer = require('./lib/retry-timer')
const ConnectionSet = require('./lib/connection-set')
const PeerDiscovery = require('./lib/peer-discovery')

const MAX_PEERS = 64
const MAX_PARALLEL = 3
const MAX_CLIENT_CONNECTIONS = Infinity // TODO: Change
const MAX_SERVER_CONNECTIONS = Infinity

const ERR_MISSING_TOPIC = 'Topic is required and must be a 32-byte buffer'
const ERR_DESTROYED = 'Swarm has been destroyed'
const ERR_DUPLICATE = 'Duplicate connection'
const ERR_FIREWALL = 'Peer is firewalled'

module.exports = class Hyperswarm extends EventEmitter {
  constructor(opts = {}) {
    super()
    const {
      seed,
      relayThrough,
      keyPair = DHT.keyPair(seed),
      maxPeers = MAX_PEERS,
      maxClientConnections = MAX_CLIENT_CONNECTIONS,
      maxServerConnections = MAX_SERVER_CONNECTIONS,
      maxParallel = MAX_PARALLEL,
      firewall = allowAll
    } = opts
    this.keyPair = keyPair

    this.dht =
      opts.dht ||
      new DHT({
        bootstrap: opts.bootstrap,
        nodes: opts.nodes,
        port: opts.port,
        deferRandomPunch: opts.deferRandomPunch,
        randomPunchInterval: opts.randomPunchInterval
      })
    this.server = this.dht.createServer(
      {
        firewall: this._handleFirewall.bind(this),
        relayThrough: this._maybeRelayConnection.bind(this),
        handshakeClearWait: opts.handshakeClearWait
      },
      this._handleServerConnection.bind(this)
    )

    this.destroyed = false
    this.suspended = false
    this.maxPeers = maxPeers
    this.maxClientConnections = maxClientConnections
    this.maxServerConnections = maxServerConnections
    this.maxParallel = maxParallel
    this.relayThrough = relayThrough ? toRelayFunction(relayThrough) : null

    this.connecting = 0
    this.connections = new Set()
    this.peers = new Map()
    this.explicitPeers = new Set()
    this.listening = null
    this.stats = {
      updates: 0,
      connects: {
        client: {
          opened: 0,
          closed: 0,
          attempted: 0
        },
        server: {
          // Note: there is no notion of 'attempts' for server connections
          opened: 0,
          closed: 0
        }
      },
      bannedPeers: 0
    }

    this._discovery = new Map()
    this._timer = new RetryTimer(this._requeue.bind(this), {
      backoffs: opts.backoffs,
      jitter: opts.jitter
    })
    this._queue = spq()

    this._allConnections = new ConnectionSet()
    this._pendingFlushes = []
    this._flushTick = 0

    this._drainingQueue = false
    this._clientConnections = 0
    this._serverConnections = 0
    this._firewall = firewall

    this.dht.on('network-change', this._handleNetworkChange.bind(this))
    this.dht.on('network-update', this._handleNetworkUpdate.bind(this))
    this.on('update', this._handleUpdate)
  }

  _maybeRelayConnection(force) {
    if (!this.relayThrough) return null
    return this.relayThrough(force, this)
  }

  _enqueue(peerInfo) {
    if (peerInfo.queued) return
    peerInfo.queued = true
    peerInfo._flushTick = this._flushTick
    this._queue.add(peerInfo)

    this._attemptClientConnections()
  }

  _requeue(batch) {
    if (this.suspended) return
    for (const peerInfo of batch) {
      peerInfo.waiting = false

      if (
        peerInfo._updatePriority() === false ||
        this._allConnections.has(peerInfo.publicKey) ||
        peerInfo.queued
      ) {
        continue
      }
      peerInfo.queued = true
      peerInfo._flushTick = this._flushTick
      this._queue.add(peerInfo)
    }

    this._attemptClientConnections()
  }

  _flushMaybe(peerInfo) {
    for (let i = 0; i < this._pendingFlushes.length; i++) {
      const flush = this._pendingFlushes[i]
      if (peerInfo._flushTick > flush.tick) continue
      if (--flush.missing > 0) continue
      flush.onflush(true)
      this._pendingFlushes.splice(i--, 1)
    }
  }

  _withinMaxPeers() {
    const e = this.explicitPeers.size
    const factor = e === 0 ? 1 : e < 2 ? 2 : e < 4 ? 3 : 4
    return factor * this._allConnections.size < this.maxPeers
  }

  _flushAllMaybe() {
    if (
      this.connecting > 0 ||
      (this._withinMaxPeers() && this._clientConnections < this.maxClientConnections)
    ) {
      return false
    }

    while (this._pendingFlushes.length) {
      const flush = this._pendingFlushes.pop()
      flush.onflush(true)
    }

    return true
  }

  _shouldConnectExplicit() {
    return !this.destroyed && !this.suspended && this.connecting < this.maxParallel
  }

  _shouldConnect() {
    return (
      !this.destroyed &&
      !this.suspended &&
      this.connecting < this.maxParallel &&
      this._withinMaxPeers() &&
      this._clientConnections < this.maxClientConnections
    )
  }

  _shouldRequeue(peerInfo) {
    if (this.suspended) return false
    if (peerInfo.explicit) return true
    for (const topic of peerInfo.topics) {
      if (this._discovery.has(b4a.toString(topic, 'hex')) && !this.destroyed) {
        return true
      }
    }
    return false
  }

  _connect(peerInfo, queued) {
    if (peerInfo.banned || this._allConnections.has(peerInfo.publicKey)) {
      if (queued) this._flushMaybe(peerInfo)
      return
    }

    // TODO: Support async firewalling at some point.
    if (this._handleFirewall(peerInfo.publicKey, null)) {
      if (queued) this._flushMaybe(peerInfo)
      return
    }

    const relayThrough = this._maybeRelayConnection(peerInfo.forceRelaying)
    const conn = this.dht.connect(peerInfo.publicKey, {
      relayAddresses: peerInfo.relayAddresses,
      keyPair: this.keyPair,
      relayThrough
    })
    this._allConnections.add(conn)

    this.stats.connects.client.attempted++

    this.connecting++
    this._clientConnections++
    let opened = false

    const onerror = (err) => {
      if (this.relayThrough && shouldForceRelaying(err.code)) {
        peerInfo.forceRelaying = true
        // Reset the attempts in order to fast connect to relay
        peerInfo.attempts = 0
      }
    }

    // Removed once a connection is opened
    conn.on('error', onerror)

    conn.on('open', () => {
      opened = true
      this.stats.connects.client.opened++

      this._connectDone()
      this.connections.add(conn)
      conn.removeListener('error', onerror)
      peerInfo._connected()
      peerInfo.client = true
      this.emit('connection', conn, peerInfo)
      if (queued) this._flushMaybe(peerInfo)

      this.emit('update')
    })
    conn.on('close', () => {
      if (!opened) this._connectDone()
      this.stats.connects.client.closed++

      const err = getStreamError(conn)
      if (shouldBan(err)) {
        this._banPeer(peerInfo, true, err)
      }

      this.connections.delete(conn)
      this._allConnections.delete(conn)
      this._clientConnections--
      peerInfo._disconnected()

      peerInfo.waiting = this._shouldRequeue(peerInfo) && this._timer.add(peerInfo)
      this._maybeDeletePeer(peerInfo)

      if (!opened && queued) this._flushMaybe(peerInfo)

      this._attemptClientConnections()

      this.emit('update')
    })

    this.emit('update')
  }

  _connectDone() {
    this.connecting--

    if (this.connecting < this.maxParallel) this._attemptClientConnections()
    if (this.connecting === 0) this._flushAllMaybe()
  }

  // Called when the PeerQueue indicates a connection should be attempted.
  _attemptClientConnections() {
    // Guard against re-entries - unsure if it still needed but doesn't hurt
    if (this._drainingQueue || this.suspended) return
    this._drainingQueue = true

    for (const peerInfo of this.explicitPeers) {
      if (!this._shouldConnectExplicit()) break
      if (
        peerInfo.attempts >= 5 ||
        Date.now() - peerInfo.disconnectedTime < peerInfo.attempts * 1000
      ) {
        continue
      }
      this._connect(peerInfo, false)
    }

    while (this._queue.length && this._shouldConnect()) {
      const peerInfo = this._queue.shift()
      peerInfo.queued = false
      this._connect(peerInfo, true)
    }
    this._drainingQueue = false
    if (this.connecting === 0) this._flushAllMaybe()
  }

  _handleFirewall(remotePublicKey, payload) {
    if (b4a.equals(remotePublicKey, this.keyPair.publicKey)) return true

    let peerInfo = this.peers.get(b4a.toString(remotePublicKey, 'hex'))
    if (peerInfo && peerInfo.banned) return true

    const firewalled = this._firewall(remotePublicKey, payload)
    if (firewalled) {
      if (!peerInfo) peerInfo = this._upsertPeer(remotePublicKey)
      this._banPeer(peerInfo, true, new Error(ERR_FIREWALL))
    }

    return firewalled
  }

  _handleServerConnectionSwap(existing, conn) {
    let closed = false

    existing.on('close', () => {
      if (closed) return

      conn.removeListener('error', noop)
      conn.removeListener('close', onclose)

      this._handleServerConnection(conn)
    })

    conn.on('error', noop)
    conn.on('close', onclose)

    function onclose() {
      closed = true
    }
  }

  // Called when the DHT receives a new server connection.
  _handleServerConnection(conn) {
    if (this.destroyed || this.suspended) {
      // TODO: Investigate why a final server connection can be received after close
      conn.on('error', noop)
      return conn.destroy(ERR_DESTROYED)
    }

    const existing = this._allConnections.get(conn.remotePublicKey)

    if (existing) {
      // If both connections are from the same peer,
      // - pick the new one if the existing stream is already established (has sent and received bytes),
      //   because the other client must have lost that connection and be reconnecting
      // - otherwise, pick the one thats expected to initiate in a tie break
      const existingIsOutdated = existing.rawBytesRead > 0 && existing.rawBytesWritten > 0
      const expectedInitiator = b4a.compare(conn.publicKey, conn.remotePublicKey) > 0
      const keepNew = existingIsOutdated || expectedInitiator === conn.isInitiator

      if (keepNew === false) {
        existing.sendKeepAlive()
        conn.on('error', noop)
        conn.destroy(new Error(ERR_DUPLICATE))
        return
      }

      existing.on('error', noop)
      existing.destroy(new Error(ERR_DUPLICATE))
      this._handleServerConnectionSwap(existing, conn)
      return
    }

    // When reaching here, the connection will always be 'opened' next tick
    this.stats.connects.server.opened++

    const peerInfo = this._upsertPeer(conn.remotePublicKey, null)

    this.connections.add(conn)
    this._allConnections.add(conn)
    this._serverConnections++

    conn.on('close', () => {
      const err = getStreamError(conn)
      if (shouldBan(err)) {
        this._banPeer(peerInfo, true, err)
      }

      this.connections.delete(conn)
      this._allConnections.delete(conn)
      this._serverConnections--
      this.stats.connects.server.closed++

      this._maybeDeletePeer(peerInfo)

      this._attemptClientConnections()

      this.emit('update')
    })
    peerInfo.client = false
    this.emit('connection', conn, peerInfo)

    this.emit('update')
  }

  _upsertPeer(publicKey, relayAddresses) {
    if (b4a.equals(publicKey, this.keyPair.publicKey)) return null
    const keyString = b4a.toString(publicKey, 'hex')
    let peerInfo = this.peers.get(keyString)

    if (peerInfo) {
      peerInfo.relayAddresses = relayAddresses // new is always better
      return peerInfo
    }

    peerInfo = new PeerInfo({
      publicKey,
      relayAddresses
    })

    this.peers.set(keyString, peerInfo)
    return peerInfo
  }

  _handleUpdate() {
    this.stats.updates++
  }

  _maybeDeletePeer(peerInfo) {
    if (!peerInfo.shouldGC()) return

    const hasActiveConn = this._allConnections.has(peerInfo.publicKey)
    if (hasActiveConn) return

    const keyString = b4a.toString(peerInfo.publicKey, 'hex')
    this.peers.delete(keyString)
  }

  /*
   * Called when a peer is actively discovered during a lookup.
   *
   * Three conditions:
   *  1. Not a known peer -- insert into queue
   *  2. A known peer with normal priority -- do nothing
   *  3. A known peer with low priority -- bump priority, because it's been rediscovered
   */
  _handlePeer(peer, topic) {
    const peerInfo = this._upsertPeer(peer.publicKey, peer.relayAddresses)
    if (peerInfo) peerInfo._topic(topic)
    if (!peerInfo || this._allConnections.has(peer.publicKey)) return
    if (!peerInfo.prioritized || peerInfo.server) peerInfo._reset()
    if (peerInfo._updatePriority()) {
      this._enqueue(peerInfo)
    }
  }

  async _handleNetworkUpdate() {
    if (!this.online) return
    this._handleNetworkChange()
  }

  async _handleNetworkChange() {
    if (this.suspended) return

    // prioritize figuring out if existing connections are dead
    for (const conn of this._allConnections) {
      conn.sendKeepAlive()
    }

    const refreshes = []

    for (const discovery of this._discovery.values()) {
      refreshes.push(discovery.refresh())
    }

    await Promise.allSettled(refreshes)
  }

  _banPeer(peerInfo, banned, err) {
    peerInfo.ban(banned)
    this.stats.bannedPeers++
    this.emit('ban', peerInfo, err)
  }

  status(key) {
    return this._discovery.get(b4a.toString(key, 'hex')) || null
  }

  listen() {
    if (!this.listening) {
      if (this.destroyed) throw new Error('Swarm destroyed')
      this.listening = this.server.listen(this.keyPair)
    }
    return this.listening
  }

  // Object that exposes a cancellation method (destroy)
  // TODO: When you rejoin, it should reannounce + bump lookup priority
  join(topic, opts = {}) {
    if (this.destroyed) throw new Error('Swarm destroyed')
    if (!topic) throw new Error(ERR_MISSING_TOPIC)
    topic = unslab(topic)

    const topicString = b4a.toString(topic, 'hex')

    let discovery = this._discovery.get(topicString)

    if (discovery && !discovery.destroyed) {
      return discovery.session(opts)
    }

    discovery = new PeerDiscovery(this, topic, {
      limit: opts.limit,
      wait: discovery ? discovery.destroy() : null,
      suspended: this.suspended,
      onpeer: (peer) => this._handlePeer(peer, topic)
    })
    this._discovery.set(topicString, discovery)
    return discovery.session(opts)
  }

  // Returns a promise
  async leave(topic) {
    if (!topic) throw new Error(ERR_MISSING_TOPIC)
    const topicString = b4a.toString(topic, 'hex')
    if (!this._discovery.has(topicString)) return Promise.resolve()

    const discovery = this._discovery.get(topicString)

    try {
      await discovery.destroy()
    } catch {
      // ignore, prop network
    }

    if (this._discovery.get(topicString) === discovery) {
      this._discovery.delete(topicString)
    }
  }

  joinPeer(publicKey) {
    const peerInfo = this._upsertPeer(publicKey, null)
    if (!peerInfo) return
    if (!this.explicitPeers.has(peerInfo)) {
      peerInfo.explicit = true
      this.explicitPeers.add(peerInfo)
    }
    if (this._allConnections.has(publicKey)) return
    if (peerInfo._updatePriority()) {
      this._enqueue(peerInfo)
    }
  }

  leavePeer(publicKey) {
    const keyString = b4a.toString(publicKey, 'hex')
    if (!this.peers.has(keyString)) return

    const peerInfo = this.peers.get(keyString)
    peerInfo.explicit = false
    this.explicitPeers.delete(peerInfo)
    this._maybeDeletePeer(peerInfo)
  }

  // Returns a promise
  async flush() {
    const allFlushed = [...this._discovery.values()].map((v) => v.flushed())
    await Promise.all(allFlushed)
    if (this._flushAllMaybe()) return true
    const pendingSize = this._allConnections.size - this.connections.size
    if (!this._queue.length && !pendingSize) return true
    return new Promise((resolve) => {
      this._pendingFlushes.push({
        onflush: resolve,
        missing: this._queue.length + pendingSize,
        tick: this._flushTick++
      })
    })
  }

  async clear() {
    const cleared = Promise.allSettled([...this._discovery.values()].map((d) => d.destroy()))
    this._discovery.clear()
    return cleared
  }

  async destroy({ force } = {}) {
    if (this.destroyed && !force) return
    this.destroyed = true

    this._timer.destroy()

    if (!force) await this.clear()

    await this.server.close()

    while (this._pendingFlushes.length) {
      const flush = this._pendingFlushes.pop()
      flush.onflush(false)
    }

    await this.dht.destroy({ force })
  }

  async suspend({ log = noop } = {}) {
    if (this.suspended) return

    const promises = []

    promises.push(this.server.suspend({ log }))

    for (const discovery of this._discovery.values()) {
      promises.push(discovery.suspend({ log }))
    }

    const pending = []
    for (const connection of this._allConnections) {
      connection.destroy()
      pending.push(new Promise((resolve) => connection.on('close', resolve)))
    }

    this.suspended = true

    log('Suspending server and discovery... (' + promises.length + ')')
    await Promise.allSettled(promises)
    log('Done, suspending the dht...')
    await this.dht.suspend({ log })
    log('Done, swarm fully suspended')

    await Promise.all(pending)

    // reset queue
    this._timer.destroy()
    this._timer = new RetryTimer(this._requeue.bind(this), {
      backoffs: this._timer.backoffs,
      jitter: this._timer.jitter
    })
    this._queue = spq()
  }

  async resume({ log = noop } = {}) {
    if (!this.suspended) return

    log('Resuming the dht')
    await this.dht.resume()
    log('Done, resuming the server')
    await this.server.resume()
    log('Done, all discovery')

    for (const discovery of this._discovery.values()) {
      discovery.resume()
    }

    this.suspended = false
    this._attemptClientConnections()
  }

  topics() {
    return this._discovery.values()
  }
}

function noop() {}

function allowAll() {
  return false
}

function shouldForceRelaying(code) {
  return (
    code === 'HOLEPUNCH_ABORTED' ||
    code === 'HOLEPUNCH_DOUBLE_RANDOMIZED_NATS' ||
    code === 'REMOTE_NOT_HOLEPUNCHABLE'
  )
}

function shouldBan() {
  // return !!err && err.name === 'HypercoreError' && err.code === 'INVALID_OPERATION'
  return false
}

function toRelayFunction(relayThrough) {
  return typeof relayThrough === 'function'
    ? relayThrough
    : (force, swarm) => (force || swarm.dht.randomized ? relayThrough : null)
}
module.exports = class BulkTimer {
  constructor(time, fn) {
    this._time = time
    this._fn = fn
    this._interval = null
    this._next = []
    this._pending = []
    this._destroyed = false
  }

  destroy() {
    if (this._destroyed) return
    this._destroyed = true
    clearInterval(this._interval)
    this._interval = null
  }

  _ontick() {
    if (!this._next.length && !this._pending.length) return
    if (this._next.length) this._fn(this._next)
    this._next = this._pending
    this._pending = []
  }

  add(info) {
    if (this._destroyed) return
    if (!this._interval) {
      this._interval = setInterval(this._ontick.bind(this), Math.floor(this._time * 0.66))
    }

    this._pending.push(info)
  }
}
const b4a = require('b4a')

module.exports = class ConnectionSet {
  constructor() {
    this._byPublicKey = new Map()
  }

  [Symbol.iterator]() {
    return this._byPublicKey.values()
  }

  get size() {
    return this._byPublicKey.size
  }

  has(publicKey) {
    return this._byPublicKey.has(toHex(publicKey))
  }

  get(publicKey) {
    return this._byPublicKey.get(toHex(publicKey))
  }

  add(connection) {
    this._byPublicKey.set(b4a.toString(connection.remotePublicKey, 'hex'), connection)
  }

  delete(connection) {
    const keyString = b4a.toString(connection.remotePublicKey, 'hex')
    const existing = this._byPublicKey.get(keyString)
    if (existing !== connection) return
    this._byPublicKey.delete(keyString)
  }
}

function toHex(b) {
  return typeof b === 'string' ? b : b4a.toString(b, 'hex')
}
const safetyCatch = require('safety-catch')
const b4a = require('b4a')

const REFRESH_INTERVAL = 1000 * 60 * 10 // 10 min
const RANDOM_JITTER = 1000 * 60 * 2 // 2 min
const DELAY_GRACE_PERIOD = 1000 * 30 // 30s

const MAX_DISCOVERY_CACHE = 64

module.exports = class PeerDiscovery {
  constructor(
    swarm,
    topic,
    { limit = Infinity, wait = null, suspended = false, onpeer = noop, onerror = safetyCatch }
  ) {
    this.limit = limit
    this.swarm = swarm
    this.topic = topic
    this.isClient = false
    this.isServer = false
    this.destroyed = false
    this.destroying = null
    this.suspended = suspended

    this._sessions = []
    this._clientSessions = 0
    this._serverSessions = 0

    this._onpeer = onpeer
    this._onerror = onerror

    this._discovered = new Set()
    this._activeQuery = null
    this._timer = null
    this._currentRefresh = null
    this._closestNodes = null
    this._firstAnnounce = true
    this._needsUnannounce = false
    this._refreshes = 0
    this._wait = wait
  }

  session({ server = true, client = true, limit = Infinity, onerror = safetyCatch }) {
    if (this.destroyed) throw new Error('PeerDiscovery is destroyed')
    const session = new PeerDiscoverySession(this)
    session.refresh({ server, client, limit }).catch(onerror)
    this._sessions.push(session)
    return session
  }

  _refreshLater(eager) {
    const jitter = Math.round(Math.random() * RANDOM_JITTER)
    const delay = !eager ? REFRESH_INTERVAL + jitter : jitter

    if (this._timer) clearTimeout(this._timer)

    const startTime = Date.now()
    this._timer = setTimeout(() => {
      // If your laptop went to sleep, and is coming back online...
      const overdue = Date.now() - startTime > delay + DELAY_GRACE_PERIOD
      if (overdue) this._refreshLater(true)
      else this.refresh().catch(this._onerror)
    }, delay)
  }

  _isActive() {
    return !this.destroyed && !this.suspended
  }

  // TODO: Allow announce to be an argument to this
  // TODO: Maybe announce should be a setter?
  async _refresh() {
    if (this.suspended) return
    const clock = ++this._refreshes

    if (this._wait) {
      await this._wait
      this._wait = null
      if (clock !== this._refreshes || !this._isActive()) return
    }

    const clear = this.isServer && this._firstAnnounce
    if (clear) this._firstAnnounce = false

    const opts = {
      clear,
      closestNodes: this._closestNodes
    }

    if (this.isServer) {
      await this.swarm.listen()
      // if a parallel refresh is happening, yield to the new one
      if (clock !== this._refreshes || !this._isActive()) return
      this._needsUnannounce = true
    }

    let limit = this.limit

    if (limit < Infinity && limit > 0) {
      for (const id of this._discovered) {
        if (!this.swarm.connections.has(id)) continue
        if (--limit === 0) break
      }
    }

    this._discovered.clear()

    const announcing = this.isServer
    const query = (this._activeQuery = announcing
      ? this.swarm.dht.announce(
          this.topic,
          this.swarm.keyPair,
          this.swarm.server.relayAddresses,
          opts
        )
      : this._needsUnannounce
        ? this.swarm.dht.lookupAndUnannounce(this.topic, this.swarm.keyPair, opts)
        : this.swarm.dht.lookup(this.topic, opts))

    try {
      for await (const data of this._activeQuery) {
        if (!this.isClient || !this._isActive()) continue
        for (const peer of data.peers) {
          if (limit < Infinity) {
            const id = b4a.toString(peer.publicKey, 'hex')

            if (this._discovered.size < MAX_DISCOVERY_CACHE) {
              this._discovered.add(id)
            }

            if (limit === 0) continue

            // there is a chance it has updated a connection during discovery and we go over
            // the limit - thats acceptable to avoid a complexity spiral here.
            if (!this.swarm.connections.has(id)) limit--
          }

          this._onpeer(peer, data)
        }
      }
    } catch (err) {
      if (this._isActive()) throw err
    } finally {
      if (this._activeQuery === query) {
        this._activeQuery = null
        if (!this.destroyed && !this.suspended) this._refreshLater(false)
      }
    }

    // This is set at the very end, when the query completes successfully.
    this._closestNodes = query.closestNodes

    if (clock !== this._refreshes) return

    // In this is the latest query, unannounce has been fulfilled as well
    if (!announcing) this._needsUnannounce = false
  }

  async refresh() {
    if (this.destroyed) throw new Error('PeerDiscovery is destroyed')

    const server = this._serverSessions > 0
    const client = this._clientSessions > 0

    if (this.suspended) return

    if (server === this.isServer && client === this.isClient) {
      if (this._currentRefresh) return this._currentRefresh
      this._currentRefresh = this._refresh()
    } else {
      if (this._activeQuery) this._activeQuery.destroy()
      this.isServer = server
      this.isClient = client
      this._currentRefresh = this._refresh()
    }

    const refresh = this._currentRefresh
    try {
      await refresh
    } catch {
      return false
    } finally {
      if (refresh === this._currentRefresh) {
        this._currentRefresh = null
      }
    }

    return true
  }

  async flushed() {
    if (this.swarm.listening) await this.swarm.listening

    try {
      await this._currentRefresh
      return true
    } catch {
      return false
    }
  }

  async _destroyMaybe() {
    if (this.destroyed) return

    try {
      if (this._sessions.length === 0) await this.swarm.leave(this.topic)
      else if (this._serverSessions === 0 && this._needsUnannounce) await this.refresh()
    } catch (err) {
      // ignore network failures here, as we are tearing down
      safetyCatch(err)
    }
  }

  destroy() {
    if (this.destroying) return this.destroying
    this.destroying = this._destroy()
    return this.destroying
  }

  async _abort(log) {
    const id = log === noop ? '' : b4a.toString(this.topic, 'hex')

    log('Aborting discovery', id)
    if (this._wait) await this._wait
    log('Aborting discovery (post wait)', id)

    if (this._activeQuery) {
      this._activeQuery.destroy()
      this._activeQuery = null
    }
    if (this._timer) {
      clearTimeout(this._timer)
      this._timer = null
    }

    let nodes = this._closestNodes

    if (this._currentRefresh) {
      try {
        await this._currentRefresh
      } catch {
        // If the destroy causes the refresh to fail, suppress it.
      }
    }

    log('Aborting discovery (post refresh)', id)
    if (this._isActive()) return

    if (!nodes) nodes = this._closestNodes
    else if (this._closestNodes !== nodes) {
      const len = nodes.length
      for (const newer of this._closestNodes) {
        if (newer.id && !hasNode(nodes, len, newer)) nodes.push(newer)
      }
    }

    if (this._needsUnannounce) {
      log('Unannouncing discovery', id)
      if (nodes && nodes.length) {
        await this.swarm.dht.unannounce(this.topic, this.swarm.keyPair, {
          closestNodes: nodes,
          onlyClosestNodes: true,
          force: true
        })
      }
      this._needsUnannounce = false
      log('Unannouncing discovery (done)', id)
    }
  }

  _destroy() {
    if (this.destroyed) return
    this.destroyed = true
    return this._abort(noop)
  }

  async suspend({ log = noop } = {}) {
    if (this.suspended) return
    this.suspended = true
    try {
      await this._abort(log)
    } catch {
      // ignore
    }
  }

  resume() {
    if (!this.suspended) return
    this.suspended = false
    this.refresh().catch(noop)
  }
}

class PeerDiscoverySession {
  constructor(discovery) {
    this.discovery = discovery
    this.isClient = false
    this.isServer = false
    this.destroyed = false
  }

  get swarm() {
    return this.discovery.swarm
  }

  get topic() {
    return this.discovery.topic
  }

  async refresh({ client = this.isClient, server = this.isServer, limit = Infinity } = {}) {
    if (this.destroyed) throw new Error('PeerDiscovery is destroyed')
    if (!client && !server) throw new Error('Cannot refresh with neither client nor server option')

    if (client !== this.isClient) {
      this.isClient = client
      this.discovery._clientSessions += client ? 1 : -1
    }

    if (server !== this.isServer) {
      this.isServer = server
      this.discovery._serverSessions += server ? 1 : -1
    }

    this.discovery.limit = limit

    return this.discovery.refresh()
  }

  async flushed() {
    return this.discovery.flushed()
  }

  async destroy() {
    if (this.destroyed) return
    this.destroyed = true

    if (this.isClient) this.discovery._clientSessions--
    if (this.isServer) this.discovery._serverSessions--

    const index = this.discovery._sessions.indexOf(this)
    const head = this.discovery._sessions.pop()

    if (head !== this) this.discovery._sessions[index] = head

    return this.discovery._destroyMaybe()
  }
}

function hasNode(nodes, len, node) {
  for (let i = 0; i < len; i++) {
    const existing = nodes[i]
    if (existing.id && b4a.equals(existing.id, node.id)) return true
  }

  return false
}

function noop() {}
const { EventEmitter } = require('events')
const b4a = require('b4a')
const unslab = require('unslab')

const MIN_CONNECTION_TIME = 15000

const VERY_LOW_PRIORITY = 0
const LOW_PRIORITY = 1
const NORMAL_PRIORITY = 2
const HIGH_PRIORITY = 3
const VERY_HIGH_PRIORITY = 4

module.exports = class PeerInfo extends EventEmitter {
  constructor({ publicKey, relayAddresses }) {
    super()

    this.publicKey = unslab(publicKey)
    this.relayAddresses = relayAddresses

    this.reconnecting = true
    this.proven = false
    this.connectedTime = -1
    this.disconnectedTime = 0
    this.banned = false
    this.tried = false
    this.explicit = false
    this.waiting = false
    this.forceRelaying = false

    // Set by the Swarm
    this.queued = false
    this.client = false
    this.topics = [] // TODO: remove on next major (check with mafintosh for context)

    this.attempts = 0
    this.priority = NORMAL_PRIORITY

    // Used by shuffled-priority-queue
    this._index = 0

    // Used for flush management
    this._flushTick = 0

    // Used for topic multiplexing
    this._seenTopics = new Set()
  }

  get server() {
    return !this.client
  }

  get prioritized() {
    return this.priority >= NORMAL_PRIORITY
  }

  _getPriority() {
    const peerIsStale = this.tried && !this.proven
    if (peerIsStale || this.attempts > 3) return VERY_LOW_PRIORITY
    if (this.attempts === 3) return LOW_PRIORITY
    if (this.attempts === 2) return HIGH_PRIORITY
    if (this.attempts === 1) return VERY_HIGH_PRIORITY
    return NORMAL_PRIORITY
  }

  _connected() {
    this.proven = true
    this.connectedTime = Date.now()
  }

  _disconnected() {
    this.disconnectedTime = Date.now()
    if (this.connectedTime > -1) {
      if (this.disconnectedTime - this.connectedTime >= MIN_CONNECTION_TIME) this.attempts = 0 // fast retry
      this.connectedTime = -1
    }
    this.attempts++
  }

  _deprioritize() {
    this.attempts = 3
  }

  _reset() {
    this.client = false
    this.proven = false
    this.tried = false
    this.attempts = 0
  }

  _updatePriority() {
    if (this.explicit && this.attempts > 3) this._deprioritize()
    if (this.banned || this.queued || this.attempts > 3) return false
    this.priority = this._getPriority()
    return true
  }

  _topic(topic) {
    const topicString = b4a.toString(topic, 'hex')
    if (this._seenTopics.has(topicString)) return
    this._seenTopics.add(topicString)
    this.topics.push(topic)
    this.emit('topic', topic)
  }

  reconnect(val) {
    this.reconnecting = !!val
  }

  ban(val) {
    this.banned = !!val
  }

  shouldGC() {
    return !(this.banned || this.queued || this.explicit || this.waiting)
  }
}
const BulkTimer = require('./bulk-timer')

const BACKOFF_JITTER = 500
const BACKOFF_S = 1000 + Math.round(BACKOFF_JITTER * Math.random())
const BACKOFF_M = 5000 + Math.round(2 * BACKOFF_JITTER * Math.random())
const BACKOFF_L = 15000 + Math.round(4 * BACKOFF_JITTER * Math.random())
const BACKOFF_X = 1000 * 60 * 10 + Math.round(240 * BACKOFF_JITTER * Math.random())

module.exports = class RetryTimer {
  constructor(
    push,
    { backoffs = [BACKOFF_S, BACKOFF_M, BACKOFF_L, BACKOFF_X], jitter = BACKOFF_JITTER } = {}
  ) {
    this.jitter = jitter
    this.backoffs = backoffs

    this._sTimer = new BulkTimer(backoffs[0] + Math.round(jitter * Math.random()), push)
    this._mTimer = new BulkTimer(backoffs[1] + Math.round(jitter * Math.random()), push)
    this._lTimer = new BulkTimer(backoffs[2] + Math.round(jitter * Math.random()), push)
    this._xTimer = new BulkTimer(backoffs[3] + Math.round(jitter * Math.random()), push)
  }

  _selectRetryTimer(peerInfo) {
    if (peerInfo.banned || !peerInfo.reconnecting) return null

    if (peerInfo.attempts > 3) {
      return peerInfo.explicit ? this._xTimer : null
    }

    if (peerInfo.attempts === 0) return this._sTimer
    if (peerInfo.proven) {
      switch (peerInfo.attempts) {
        case 1:
          return this._sTimer
        case 2:
          return this._mTimer
        case 3:
          return this._lTimer
      }
    } else {
      switch (peerInfo.attempts) {
        case 1:
          return this._mTimer
        case 2:
          return this._lTimer
        case 3:
          return this._lTimer
      }
    }

    return null
  }

  add(peerInfo) {
    const timer = this._selectRetryTimer(peerInfo)
    if (!timer) return false

    timer.add(peerInfo)
    return true
  }

  destroy() {
    this._sTimer.destroy()
    this._mTimer.destroy()
    this._lTimer.destroy()
    this._xTimer.destroy()
  }
}
{
  "name": "hyperswarm",
  "version": "4.17.0",
  "description": "A distributed networking stack for connecting peers",
  "files": [
    "index.js",
    "lib/**.js"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    },
    "process": {
      "bare": "bare-process",
      "default": "process"
    }
  },
  "dependencies": {
    "b4a": "^1.3.1",
    "bare-events": "^2.2.0",
    "hyperdht": "^6.21.0",
    "safety-catch": "^1.0.2",
    "shuffled-priority-queue": "^2.1.0",
    "streamx": "^2.22.1",
    "unslab": "^1.3.0"
  },
  "devDependencies": {
    "bare-process": "^4.2.2",
    "brittle": "^3.0.2",
    "hypercore-crypto": "^3.4.0",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "which-runtime": "^1.3.2"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:generate": "brittle -r test/all.js test/*.js",
    "test:node": "brittle-node --coverage test/*.js",
    "test:bare": "bare test/all.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/hyperswarm.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "contributors": [
    "David Mark Clements (@davidmarkclem)",
    "Andrew Osheroff (@andrewosh)"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/hyperswarm/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperswarm"
}
const { EventEmitter } = require('events')

module.exports = class RoutingTable extends EventEmitter {
  constructor (id, opts) {
    if (!opts) opts = {}

    super()

    this.id = id
    this.k = opts.k || 20
    this.size = 0
    this.rows = new Array(id.length * 8)
  }

  add (node) {
    const i = this._diff(node.id)

    let row = this.rows[i]

    if (!row) {
      row = this.rows[i] = new Row(this, i)
      this.emit('row', row)
    }

    const len = row.nodes.length
    if (!row.add(node, this.k)) return false

    this.size += row.nodes.length - len
    return true
  }

  remove (id) {
    const i = this._diff(id)
    const row = this.rows[i]
    if (!row) return false
    if (!row.remove(id)) return false
    this.size--
    return true
  }

  get (id) {
    const i = this._diff(id)
    const row = this.rows[i]
    if (!row) return null
    return row.get(id)
  }

  has (id) {
    return this.get(id) !== null
  }

  random () {
    let n = (Math.random() * this.size) | 0

    for (let i = 0; i < this.rows.length; i++) {
      const r = this.rows[i]
      if (!r) continue
      if (n < r.nodes.length) return r.nodes[n]
      n -= r.nodes.length
    }

    return null
  }

  closest (id, k) {
    if (!k) k = this.k

    const result = []
    const d = this._diff(id)

    // push close nodes
    for (let i = d; i >= 0 && result.length < k; i--) this._pushNodes(i, k, result)

    // if we don't have enough close nodes, populate from other rows, re the paper
    for (let i = d + 1; i < this.rows.length && result.length < k; i++) this._pushNodes(i, k, result)

    return result
  }

  _pushNodes (i, k, result) {
    const row = this.rows[i]
    if (!row) return

    const missing = Math.min(k - result.length, row.nodes.length)
    for (let j = 0; j < missing; j++) result.push(row.nodes[j])
  }

  toArray () {
    return this.closest(this.id, Infinity)
  }

  _diff (id) {
    for (let i = 0; i < id.length; i++) {
      const a = id[i]
      const b = this.id[i]

      if (a !== b) return i * 8 + Math.clz32(a ^ b) - 24
    }

    return this.rows.length - 1
  }
}

class Row extends EventEmitter {
  constructor (table, index) {
    super()

    this.data = null // can be used be upstream for whatevs
    this.byteOffset = index >> 3
    this.index = index
    this.table = table
    this.nodes = []
  }

  add (node) {
    const id = node.id

    let l = 0
    let r = this.nodes.length - 1

    while (l <= r) {
      const m = (l + r) >> 1
      const c = this.compare(id, this.nodes[m].id)

      if (c === 0) {
        this.nodes[m] = node
        return true
      }

      if (c < 0) r = m - 1
      else l = m + 1
    }

    if (this.nodes.length >= this.table.k) {
      this.emit('full', node)
      return false
    }

    this.insert(l, node)
    return true
  }

  remove (id) {
    let l = 0
    let r = this.nodes.length - 1

    while (l <= r) {
      const m = (l + r) >> 1
      const c = this.compare(id, this.nodes[m].id)

      if (c === 0) {
        this.splice(m)
        return true
      }

      if (c < 0) r = m - 1
      else l = m + 1
    }

    return false
  }

  get (id) {
    let l = 0
    let r = this.nodes.length - 1

    while (l <= r) {
      const m = (l + r) >> 1
      const node = this.nodes[m]
      const c = this.compare(id, node.id)

      if (c === 0) return node
      if (c < 0) r = m - 1
      else l = m + 1
    }

    return null
  }

  insert (i, node) {
    this.nodes.push(node) // push node or null or whatevs, just trying to not be polymorphic
    for (let j = this.nodes.length - 1; j > i; j--) this.nodes[j] = this.nodes[j - 1]
    this.nodes[i] = node
    this.emit('add', node)
  }

  splice (i) {
    for (; i < this.nodes.length - 1; i++) this.nodes[i] = this.nodes[i + 1]
    this.emit('remove', this.nodes.pop())
  }

  // very likely they diverge after a couple of bytes so a simple impl, like this is prop fastest vs Buffer.compare
  compare (a, b) {
    for (let i = this.byteOffset; i < a.length; i++) {
      const ai = a[i]
      const bi = b[i]
      if (ai === bi) continue
      return ai < bi ? -1 : 1
    }
    return 0
  }
}
{
  "name": "kademlia-routing-table",
  "version": "1.0.6",
  "description": "XOR based routing table used for P2P networks such as a Kademlia DHT.",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "dependencies": {
    "bare-events": "^2.2.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "standard": "^17.1.0"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "keywords": [
    "kademlia",
    "p2p",
    "k-bucket",
    "k-buckets",
    "xor",
    "routing",
    "distributed",
    "systems"
  ],
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/kademlia-routing-table.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/kademlia-routing-table/issues"
  },
  "homepage": "https://github.com/mafintosh/kademlia-routing-table"
}
const c = require('compact-encoding')
const b4a = require('b4a')

const KeyChain = require('./lib/keychain')
const { sign, verify, hash } = require('./lib/crypto')

const {
  ProofEncoding,
  AttestedData,
  AttestedDevice,
  ReceiptEncoding
} = require('./lib/encoding')

const PROOF_VERSION = 1
const KEET_TYPE = 5338

const NS_PROFILE_DISC_ENC = hash(b4a.from('profile discovery'))

module.exports = class IdentityKey {
  constructor (keyChain) {
    this.keyChain = keyChain

    this.identityKeyPair = this.keyChain.get(identityKeyPath(0))
    this.profileDiscoveryKeyPair = this.keyChain.get(discoveryCorePath(0))
  }

  static generateMnemonic () {
    return KeyChain.generateMnemonic()
  }

  static deriveSeed (mnemonic) {
    return KeyChain.deriveSeed(mnemonic)
  }

  get identityPublicKey () {
    return this.identityKeyPair.publicKey
  }

  get profileDiscoveryPublicKey () {
    return this.profileDiscoveryKeyPair.publicKey
  }

  getProfileDiscoveryEncryptionKey () {
    return this.keyChain.getSymmetricKey(encryptionKeyPath(NS_PROFILE_DISC_ENC))
  }

  getEncryptionKey (profileKey) {
    return this.keyChain.getSymmetricKey(encryptionKeyPath(profileKey))
  }

  bootstrap (device) {
    return IdentityKey.bootstrap({ identity: this.identityKeyPair }, device)
  }

  clear () {
    this.keyChain.clear()
    this.identityKeyPair.secretKey.fill(0)
    this.profileDiscoveryKeyPair.secretKey.fill(0)
  }

  static async bootstrap ({ identity, seed, mnemonic }, device) {
    if (!identity) {
      const identityPath = identityKeyPath(0) // accountIndex unused for now
      identity = await KeyChain.from({ seed, mnemonic }, identityPath)
    }

    const proof = {
      version: PROOF_VERSION,
      epoch: Date.now(),
      identity: identity.publicKey,
      chain: []
    }

    return IdentityKey.attestDevice(device, identity, proof)
  }

  static attestDevice (publicKey, parent, proof) {
    if (!proof) return IdentityKey.bootstrap({ identity: parent }, publicKey)

    if (b4a.isBuffer(proof)) {
      proof = c.decode(ProofEncoding, proof)
    }

    if (proof.version === 0) {
      throw new Error('Version 0 proofs are not supported')
    }

    const signable = c.encode(AttestedDevice, {
      epoch: proof.epoch,
      identity: proof.identity,
      device: publicKey
    })

    const signature = sign(signable, parent)

    proof.chain.push({ publicKey, signature })

    return c.encode(ProofEncoding, proof)
  }

  static attestData (attestedData, keyPair, proof) {
    if (attestedData === null) throw new Error('Data is not attestable')

    if (b4a.isBuffer(proof)) {
      proof = c.decode(ProofEncoding, proof)
    }

    if (proof && proof.version === 0) {
      throw new Error('Version 0 proofs are not supported')
    }

    if (!proof) {
      proof = {
        version: PROOF_VERSION,
        epoch: Date.now(),
        identity: keyPair.publicKey,
        chain: []
      }
    }

    const signable = c.encode(AttestedData, {
      epoch: proof.epoch,
      identity: proof.identity,
      data: hash(attestedData)
    })

    proof.data = { signature: sign(signable, keyPair) }

    return c.encode(ProofEncoding, proof)
  }

  static async from ({ seed, mnemonic }) {
    const keyChain = await KeyChain.from({ seed, mnemonic })

    return new IdentityKey(keyChain)
  }

  static verify (proof, attestedData, opts = {}) {
    if (b4a.isBuffer(proof)) {
      proof = c.decode(ProofEncoding, proof)
    }

    if (!validateProof(proof, attestedData, opts)) {
      return null
    }

    const { epoch, identity, chain } = proof

    const candidate = getLastKey(chain) || identity

    if (opts.expectedDevice) {
      if (!b4a.equals(candidate, opts.expectedDevice)) return null
    }

    let parent = identity

    // verify chain
    for (let i = 0; i < chain.length; i++) {
      const { publicKey, signature } = chain[i]

      const signable = c.encode(AttestedDevice, {
        epoch,
        identity,
        device: publicKey
      })

      if (!verify(signable, signature, parent)) {
        return null
      }

      parent = publicKey
    }

    if (proof.data) {
      const signable = c.encode(AttestedData, {
        epoch,
        identity,
        data: hash(attestedData)
      })

      if (!verify(signable, proof.data.signature, parent)) {
        return null
      }
    }

    const receipt = c.encode(ReceiptEncoding, { epoch })

    return {
      receipt,
      identityPublicKey: identity,
      devicePublicKey: candidate
    }
  }
}

function validateProof (proof, attestedData, opts = {}) {
  // version 0 is ignored
  if (proof.version === 0) return false

  // validate version
  if (proof.version > PROOF_VERSION) return false

  // verify epoch
  if (opts.receipt) {
    const { epoch } = c.decode(ReceiptEncoding, opts.receipt)
    if (proof.epoch < epoch) return false
  }

  // verify identity
  if (opts.expectedIdentity) {
    if (!b4a.equals(proof.identity, opts.expectedIdentity)) return false
  }

  return validateAttestedData(proof.data, attestedData)
}

function validateAttestedData (data, attestedData) {
  if (!data && attestedData) return false
  return true
}

function getLastKey (chain) {
  if (!chain.length) return null

  const last = chain[chain.length - 1]
  return last.publicKey
}

// slip48 derivations:
// https://github.com/satoshilabs/slips/blob/master/slip-0048.md

function keyPath (accountIndex, index) {
  // https://github.com/bitcoin/bips/blob/master/bip-0043.mediawiki
  const purpose = 48 // SLIP-48 wallet
  const role = 0 // owner

  return [purpose, KEET_TYPE, role, accountIndex, index]
}

// identityKey -> m/48'/keet'/0'/0'

function identityKeyPath (accountIndex) {
  return keyPath(accountIndex, 0)
}

// identityKey -> m/48'/keet'/0'/1'

function discoveryCorePath (accountIndex) {
  return keyPath(accountIndex, 1)
}

// slip21 derivations
// https://github.com/satoshilabs/slips/blob/master/slip-0021.md

function symmetricPath (...path) {
  const purpose = 'SLIP-0021' // SLIP-21 wallet
  const namespace = 'keet-identity-key' // keet

  return [purpose, namespace, ...path]
}

// encryptionKey  -> m/SLIP-10/keet-identity-key/account/"encryption key"

function encryptionKeyPath (profileKey) {
  return symmetricPath(b4a.toString(profileKey, 'hex'), 'encryption key')
}
const sodium = require('sodium-universal')
const b4a = require('b4a')

module.exports = {
  sign,
  verify,
  hash: blake2b
}

function sign (signable, keyPair) {
  const signature = b4a.alloc(sodium.crypto_sign_BYTES)
  sodium.crypto_sign_detached(signature, signable, keyPair.secretKey)

  return signature
}

function verify (signable, signature, publicKey) {
  return sodium.crypto_sign_verify_detached(signature, signable, publicKey)
}

function blake2b (data, output = b4a.alloc(32)) {
  sodium.crypto_generichash(output, data)
  return output
}
const c = require('compact-encoding')

const ATTESTED_DEVICE = 0
const ATTESTED_DATA = 1

const Epoch = {
  preencode (state, e) {
    c.uint64.preencode(state, Math.floor(e / 1000))
  },
  encode (state, e) {
    c.uint64.encode(state, Math.floor(e / 1000))
  },
  decode (state) {
    return c.uint64.decode(state) * 1000
  }
}

const AttestedDevice = {
  preencode (state, a) {
    c.uint8.preencode(state, ATTESTED_DEVICE)
    Epoch.preencode(state, a.epoch)
    c.fixed32.preencode(state, a.identity)
    c.fixed32.preencode(state, a.device)
  },
  encode (state, a) {
    c.uint8.encode(state, ATTESTED_DEVICE)
    Epoch.encode(state, a.epoch)
    c.fixed32.encode(state, a.identity)
    c.fixed32.encode(state, a.device)
  },
  decode (state) {
    throw new Error('Signed data should only be encoded')
  }
}

const AttestedData = {
  preencode (state, a) {
    c.uint8.preencode(state, ATTESTED_DATA)
    Epoch.preencode(state, a.epoch)
    c.fixed32.preencode(state, a.identity)
    c.fixed32.preencode(state, a.data)
  },
  encode (state, a) {
    c.uint8.encode(state, ATTESTED_DATA)
    Epoch.encode(state, a.epoch)
    c.fixed32.encode(state, a.identity)
    c.fixed32.encode(state, a.data)
  },
  decode (state) {
    throw new Error('Signed data should only be encoded')
  }
}

const DeviceAttestation = {
  preencode (state, a) {
    c.fixed32.preencode(state, a.publicKey)
    c.fixed64.preencode(state, a.signature)
  },
  encode (state, a) {
    c.fixed32.encode(state, a.publicKey)
    c.fixed64.encode(state, a.signature)
  },
  decode (state) {
    return {
      publicKey: c.fixed32.decode(state),
      signature: c.fixed64.decode(state)
    }
  }
}

const DeviceAttestationArray = c.array(DeviceAttestation)

const DataAttestation = {
  preencode (state, a) {
    c.fixed64.preencode(state, a.signature)
  },
  encode (state, a) {
    c.fixed64.encode(state, a.signature)
  },
  decode (state) {
    return {
      signature: c.fixed64.decode(state)
    }
  }
}

const ProofEncoding = {
  preencode (state, proof) {
    c.uint.preencode(state, proof.version)
    Epoch.preencode(state, proof.epoch)
    c.fixed32.preencode(state, proof.identity)
    DeviceAttestationArray.preencode(state, proof.chain)

    let flags = 0
    if (proof.data) flags |= 1
    c.uint.preencode(state, flags)

    if (proof.data) DataAttestation.preencode(state, proof.data)
  },
  encode (state, proof) {
    c.uint.encode(state, proof.version)
    Epoch.encode(state, proof.epoch)
    c.fixed32.encode(state, proof.identity)
    DeviceAttestationArray.encode(state, proof.chain)

    let flags = 0
    if (proof.data) flags |= 1
    c.uint.encode(state, flags)

    if (proof.data) DataAttestation.encode(state, proof.data)
  },
  decode (state) {
    const version = c.uint.decode(state)

    // ignore v0 proofs
    if (version === 0) {
      return {
        version: 0,
        epoch: 0,
        identity: null,
        chain: [],
        data: null
      }
    }

    const epoch = Epoch.decode(state)
    const identity = c.fixed32.decode(state)
    const chain = DeviceAttestationArray.decode(state)

    const flags = c.uint.decode(state)
    const data = flags & 1 ? DataAttestation.decode(state) : null

    return {
      version,
      epoch,
      identity,
      chain,
      data
    }
  }
}

const ReceiptEncoding = {
  preencode (state, receipt) {
    Epoch.preencode(state, receipt.epoch)
  },
  encode (state, receipt) {
    Epoch.encode(state, receipt.epoch)
  },
  decode (state) {
    return {
      epoch: Epoch.decode(state)
    }
  }
}

module.exports = {
  ATTESTED_DEVICE,
  ATTESTED_DATA,
  AttestedDevice,
  AttestedData,
  ProofEncoding,
  ReceiptEncoding
}
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const assert = require('nanoassert')
const b4a = require('b4a')
const { HMAC } = require('sodium-hmac')
const bip39 = require('bip39-mnemonic')

const { sign } = require('./crypto')

const MASTER_CHAIN_CODE = b4a.from('ed25519 seed')
const MASTER_SYMMETRIC_CODE = b4a.from('Symmetric key seed')

const HARDENED_OFFSET = 0x80000000

class KeyChain {
  constructor (seed) {
    this.seed = seed

    this._buffer = b4a.alloc(64)

    this.chainKey = this._buffer.subarray(0, 32)
    this.chainCode = this._buffer.subarray(32)

    this.publicKey = b4a.alloc(sodium.crypto_sign_PUBLICKEYBYTES)
    this.secretKey = b4a.alloc(sodium.crypto_sign_SECRETKEYBYTES)

    this._initialise()
  }

  static generateMnemonic () {
    return bip39.generateMnemonic()
  }

  static deriveSeed (mnemonic) {
    return bip39.mnemonicToSeed(mnemonic)
  }

  static async from ({ mnemonic, seed }, path) {
    assert(mnemonic || seed, 'No mnemonic or seed was passed.')

    if (!seed) seed = await KeyChain.deriveSeed(mnemonic)

    const key = new KeyChain(seed)

    if (!path) return key

    return key.get(path)
  }

  getSymmetricKey (path) {
    const buffer = b4a.alloc(64)

    const chainKey = buffer.subarray(0, 32)
    const key = buffer.subarray(32)

    HMAC.sha512(this.seed, MASTER_SYMMETRIC_CODE, buffer)

    for (const step of path) {
      const label = b4a.alloc(step.length + 1)
      b4a.write(label, step, 1, 'utf8')

      HMAC.sha512(label, chainKey, buffer)
    }

    return key
  }

  get isKeychain () {
    return true
  }

  _initialise () {
    HMAC.sha512(this.seed, MASTER_CHAIN_CODE, this._buffer)
    sodium.crypto_sign_seed_keypair(this.publicKey, this.secretKey, this.chainKey)
  }

  clear () {
    this.secretKey.fill(0)
    this.chainKey.fill(0)
    this.chainCode.fill(0)
  }

  get (path) {
    return this.derive(path)
  }

  sign (signable) {
    return sign(signable, this)
  }

  derive (path) {
    const buffer = b4a.from(this._buffer)

    const chainKey = buffer.subarray(0, 32)
    const chainCode = buffer.subarray(32)

    for (const step of path) {
      const index = ensureHardened(step) // hardened indices are >= 2^31
      HMAC.sha512(encodeDerivationData(chainKey, index), chainCode, buffer)
    }

    return createKeyPair(chainKey)
  }
}

module.exports = KeyChain

function createKeyPair (seed) {
  if (!seed) throw new Error('No seed provided')

  const publicKey = b4a.alloc(sodium.crypto_sign_PUBLICKEYBYTES)
  const secretKey = b4a.alloc(sodium.crypto_sign_SECRETKEYBYTES)

  sodium.crypto_sign_seed_keypair(publicKey, secretKey, seed)

  return {
    publicKey,
    secretKey
  }
}

function encodeDerivationData (key, step) {
  const state = { buffer: b4a.alloc(37), start: 0, end: 37 }

  c.uint8.encode(state, 0)
  c.fixed32.encode(state, key)
  state.buffer.writeUInt32BE(step, state.start)

  state.buffer[33] |= 0x80

  return state.buffer
}

function ensureHardened (n) {
  if (n >= HARDENED_OFFSET) return n
  return n + HARDENED_OFFSET
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "keet-identity-key",
  "version": "3.2.0",
  "description": "Hierarchical Deterministic Keys for Keet Identities",
  "main": "index.js",
  "scripts": {
    "test": "standard && brittle test/*.js"
  },
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "devDependencies": {
    "brittle": "^3.3.2",
    "hypercore-crypto": "^3.4.0",
    "standard": "^17.1.0"
  },
  "dependencies": {
    "b4a": "^1.6.4",
    "bip39-mnemonic": "^2.2.0",
    "compact-encoding": "^3.0.0",
    "nanoassert": "^2.0.0",
    "sodium-hmac": "^2.0.1",
    "sodium-universal": "^5.0.1"
  },
  "files": [
    "lib/*"
  ],
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/keet-identity-key.git"
  },
  "bugs": {
    "url": "https://github.com/holepunchto/keet-identity-key/issues"
  },
  "homepage": "https://github.com/holepunchto/keet-identity-key#readme"
}
import { coerce } from '../bytes.js';
import basex from '../vendor/base-x.js';
/**
 * Class represents both BaseEncoder and MultibaseEncoder meaning it
 * can be used to encode to multibase or base encode without multibase
 * prefix.
 */
class Encoder {
    name;
    prefix;
    baseEncode;
    constructor(name, prefix, baseEncode) {
        this.name = name;
        this.prefix = prefix;
        this.baseEncode = baseEncode;
    }
    encode(bytes) {
        if (bytes instanceof Uint8Array) {
            return `${this.prefix}${this.baseEncode(bytes)}`;
        }
        else {
            throw Error('Unknown type, must be binary type');
        }
    }
}
/**
 * Class represents both BaseDecoder and MultibaseDecoder so it could be used
 * to decode multibases (with matching prefix) or just base decode strings
 * with corresponding base encoding.
 */
class Decoder {
    name;
    prefix;
    baseDecode;
    prefixCodePoint;
    constructor(name, prefix, baseDecode) {
        this.name = name;
        this.prefix = prefix;
        const prefixCodePoint = prefix.codePointAt(0);
        /* c8 ignore next 3 */
        if (prefixCodePoint === undefined) {
            throw new Error('Invalid prefix character');
        }
        this.prefixCodePoint = prefixCodePoint;
        this.baseDecode = baseDecode;
    }
    decode(text) {
        if (typeof text === 'string') {
            if (text.codePointAt(0) !== this.prefixCodePoint) {
                throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);
            }
            return this.baseDecode(text.slice(this.prefix.length));
        }
        else {
            throw Error('Can only multibase decode strings');
        }
    }
    or(decoder) {
        return or(this, decoder);
    }
}
class ComposedDecoder {
    decoders;
    constructor(decoders) {
        this.decoders = decoders;
    }
    or(decoder) {
        return or(this, decoder);
    }
    decode(input) {
        const prefix = input[0];
        const decoder = this.decoders[prefix];
        if (decoder != null) {
            return decoder.decode(input);
        }
        else {
            throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);
        }
    }
}
export function or(left, right) {
    return new ComposedDecoder({
        ...(left.decoders ?? { [left.prefix]: left }),
        ...(right.decoders ?? { [right.prefix]: right })
    });
}
export class Codec {
    name;
    prefix;
    baseEncode;
    baseDecode;
    encoder;
    decoder;
    constructor(name, prefix, baseEncode, baseDecode) {
        this.name = name;
        this.prefix = prefix;
        this.baseEncode = baseEncode;
        this.baseDecode = baseDecode;
        this.encoder = new Encoder(name, prefix, baseEncode);
        this.decoder = new Decoder(name, prefix, baseDecode);
    }
    encode(input) {
        return this.encoder.encode(input);
    }
    decode(input) {
        return this.decoder.decode(input);
    }
}
export function from({ name, prefix, encode, decode }) {
    return new Codec(name, prefix, encode, decode);
}
export function baseX({ name, prefix, alphabet }) {
    const { encode, decode } = basex(alphabet, name);
    return from({
        prefix,
        name,
        encode,
        decode: (text) => coerce(decode(text))
    });
}
function decode(string, alphabetIdx, bitsPerChar, name) {
    // Count the padding bytes:
    let end = string.length;
    while (string[end - 1] === '=') {
        --end;
    }
    // Allocate the output:
    const out = new Uint8Array((end * bitsPerChar / 8) | 0);
    // Parse the data:
    let bits = 0; // Number of bits currently in the buffer
    let buffer = 0; // Bits waiting to be written out, MSB first
    let written = 0; // Next byte to write
    for (let i = 0; i < end; ++i) {
        // Read one character from the string:
        const value = alphabetIdx[string[i]];
        if (value === undefined) {
            throw new SyntaxError(`Non-${name} character`);
        }
        // Append the bits to the buffer:
        buffer = (buffer << bitsPerChar) | value;
        bits += bitsPerChar;
        // Write out some bits if the buffer has a byte's worth:
        if (bits >= 8) {
            bits -= 8;
            out[written++] = 0xff & (buffer >> bits);
        }
    }
    // Verify that we have received just enough bits:
    if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {
        throw new SyntaxError('Unexpected end of data');
    }
    return out;
}
function encode(data, alphabet, bitsPerChar) {
    const pad = alphabet[alphabet.length - 1] === '=';
    const mask = (1 << bitsPerChar) - 1;
    let out = '';
    let bits = 0; // Number of bits currently in the buffer
    let buffer = 0; // Bits waiting to be written out, MSB first
    for (let i = 0; i < data.length; ++i) {
        // Slurp data into the buffer:
        buffer = (buffer << 8) | data[i];
        bits += 8;
        // Write out as much as we can:
        while (bits > bitsPerChar) {
            bits -= bitsPerChar;
            out += alphabet[mask & (buffer >> bits)];
        }
    }
    // Partial character:
    if (bits !== 0) {
        out += alphabet[mask & (buffer << (bitsPerChar - bits))];
    }
    // Add padding characters until we hit a byte boundary:
    if (pad) {
        while (((out.length * bitsPerChar) & 7) !== 0) {
            out += '=';
        }
    }
    return out;
}
function createAlphabetIdx(alphabet) {
    // Build the character lookup table:
    const alphabetIdx = {};
    for (let i = 0; i < alphabet.length; ++i) {
        alphabetIdx[alphabet[i]] = i;
    }
    return alphabetIdx;
}
/**
 * RFC4648 Factory
 */
export function rfc4648({ name, prefix, bitsPerChar, alphabet }) {
    const alphabetIdx = createAlphabetIdx(alphabet);
    return from({
        prefix,
        name,
        encode(input) {
            return encode(input, alphabet, bitsPerChar);
        },
        decode(input) {
            return decode(input, alphabetIdx, bitsPerChar, name);
        }
    });
}
//# sourceMappingURL=base.js.mapimport { rfc4648 } from './base.js';
export const base32 = rfc4648({
    prefix: 'b',
    name: 'base32',
    alphabet: 'abcdefghijklmnopqrstuvwxyz234567',
    bitsPerChar: 5
});
export const base32upper = rfc4648({
    prefix: 'B',
    name: 'base32upper',
    alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',
    bitsPerChar: 5
});
export const base32pad = rfc4648({
    prefix: 'c',
    name: 'base32pad',
    alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',
    bitsPerChar: 5
});
export const base32padupper = rfc4648({
    prefix: 'C',
    name: 'base32padupper',
    alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',
    bitsPerChar: 5
});
export const base32hex = rfc4648({
    prefix: 'v',
    name: 'base32hex',
    alphabet: '0123456789abcdefghijklmnopqrstuv',
    bitsPerChar: 5
});
export const base32hexupper = rfc4648({
    prefix: 'V',
    name: 'base32hexupper',
    alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',
    bitsPerChar: 5
});
export const base32hexpad = rfc4648({
    prefix: 't',
    name: 'base32hexpad',
    alphabet: '0123456789abcdefghijklmnopqrstuv=',
    bitsPerChar: 5
});
export const base32hexpadupper = rfc4648({
    prefix: 'T',
    name: 'base32hexpadupper',
    alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',
    bitsPerChar: 5
});
export const base32z = rfc4648({
    prefix: 'h',
    name: 'base32z',
    alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',
    bitsPerChar: 5
});
//# sourceMappingURL=base32.js.mapimport { baseX } from './base.js';
export const base36 = baseX({
    prefix: 'k',
    name: 'base36',
    alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'
});
export const base36upper = baseX({
    prefix: 'K',
    name: 'base36upper',
    alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
});
//# sourceMappingURL=base36.js.mapimport { baseX } from './base.js';
export const base58btc = baseX({
    name: 'base58btc',
    prefix: 'z',
    alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
});
export const base58flickr = baseX({
    name: 'base58flickr',
    prefix: 'Z',
    alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'
});
//# sourceMappingURL=base58.js.mapexport const empty = new Uint8Array(0);
export function toHex(d) {
    return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '');
}
export function fromHex(hex) {
    const hexes = hex.match(/../g);
    return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty;
}
export function equals(aa, bb) {
    if (aa === bb) {
        return true;
    }
    if (aa.byteLength !== bb.byteLength) {
        return false;
    }
    for (let ii = 0; ii < aa.byteLength; ii++) {
        if (aa[ii] !== bb[ii]) {
            return false;
        }
    }
    return true;
}
export function coerce(o) {
    if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') {
        return o;
    }
    if (o instanceof ArrayBuffer) {
        return new Uint8Array(o);
    }
    if (ArrayBuffer.isView(o)) {
        return new Uint8Array(o.buffer, o.byteOffset, o.byteLength);
    }
    throw new Error('Unknown type, must be binary type');
}
export function isBinary(o) {
    return o instanceof ArrayBuffer || ArrayBuffer.isView(o);
}
export function fromString(str) {
    return new TextEncoder().encode(str);
}
export function toString(b) {
    return new TextDecoder().decode(b);
}
//# sourceMappingURL=bytes.js.mapimport { base32 } from './bases/base32.js';
import { base36 } from './bases/base36.js';
import { base58btc } from './bases/base58.js';
import { coerce } from './bytes.js';
import * as Digest from './hashes/digest.js';
import * as varint from './varint.js';
// This way TS will also expose all the types from module
export * from './link/interface.js';
export function format(link, base) {
    const { bytes, version } = link;
    switch (version) {
        case 0:
            return toStringV0(bytes, baseCache(link), base ?? base58btc.encoder);
        default:
            return toStringV1(bytes, baseCache(link), (base ?? base32.encoder));
    }
}
export function toJSON(link) {
    return {
        '/': format(link)
    };
}
export function fromJSON(json) {
    return CID.parse(json['/']);
}
const cache = new WeakMap();
function baseCache(cid) {
    const baseCache = cache.get(cid);
    if (baseCache == null) {
        const baseCache = new Map();
        cache.set(cid, baseCache);
        return baseCache;
    }
    return baseCache;
}
export class CID {
    code;
    version;
    multihash;
    bytes;
    '/';
    /**
     * @param version - Version of the CID
     * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
     * @param multihash - (Multi)hash of the of the content.
     */
    constructor(version, code, multihash, bytes) {
        this.code = code;
        this.version = version;
        this.multihash = multihash;
        this.bytes = bytes;
        // flag to serializers that this is a CID and
        // should be treated specially
        this['/'] = bytes;
    }
    /**
     * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`
     * please either use `CID.asCID(cid)` or switch to new signalling mechanism
     *
     * @deprecated
     */
    get asCID() {
        return this;
    }
    // ArrayBufferView
    get byteOffset() {
        return this.bytes.byteOffset;
    }
    // ArrayBufferView
    get byteLength() {
        return this.bytes.byteLength;
    }
    toV0() {
        switch (this.version) {
            case 0: {
                return this;
            }
            case 1: {
                const { code, multihash } = this;
                if (code !== DAG_PB_CODE) {
                    throw new Error('Cannot convert a non dag-pb CID to CIDv0');
                }
                // sha2-256
                if (multihash.code !== SHA_256_CODE) {
                    throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0');
                }
                return (CID.createV0(multihash));
            }
            default: {
                throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);
            }
        }
    }
    toV1() {
        switch (this.version) {
            case 0: {
                const { code, digest } = this.multihash;
                const multihash = Digest.create(code, digest);
                return (CID.createV1(this.code, multihash));
            }
            case 1: {
                return this;
            }
            default: {
                throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);
            }
        }
    }
    equals(other) {
        return CID.equals(this, other);
    }
    static equals(self, other) {
        const unknown = other;
        return (unknown != null &&
            self.code === unknown.code &&
            self.version === unknown.version &&
            Digest.equals(self.multihash, unknown.multihash));
    }
    toString(base) {
        return format(this, base);
    }
    toJSON() {
        return { '/': format(this) };
    }
    link() {
        return this;
    }
    [Symbol.toStringTag] = 'CID';
    // Legacy
    [Symbol.for('nodejs.util.inspect.custom')]() {
        return `CID(${this.toString()})`;
    }
    /**
     * Takes any input `value` and returns a `CID` instance if it was
     * a `CID` otherwise returns `null`. If `value` is instanceof `CID`
     * it will return value back. If `value` is not instance of this CID
     * class, but is compatible CID it will return new instance of this
     * `CID` class. Otherwise returns null.
     *
     * This allows two different incompatible versions of CID library to
     * co-exist and interop as long as binary interface is compatible.
     */
    static asCID(input) {
        if (input == null) {
            return null;
        }
        const value = input;
        if (value instanceof CID) {
            // If value is instance of CID then we're all set.
            return value;
        }
        else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {
            // If value isn't instance of this CID class but `this.asCID === this` or
            // `value['/'] === value.bytes` is true it is CID instance coming from a
            // different implementation (diff version or duplicate). In that case we
            // rebase it to this `CID` implementation so caller is guaranteed to get
            // instance with expected API.
            const { version, code, multihash, bytes } = value;
            return new CID(version, code, multihash, bytes ?? encodeCID(version, code, multihash.bytes));
        }
        else if (value[cidSymbol] === true) {
            // If value is a CID from older implementation that used to be tagged via
            // symbol we still rebase it to the this `CID` implementation by
            // delegating that to a constructor.
            const { version, multihash, code } = value;
            const digest = Digest.decode(multihash);
            return CID.create(version, code, digest);
        }
        else {
            // Otherwise value is not a CID (or an incompatible version of it) in
            // which case we return `null`.
            return null;
        }
    }
    /**
     * @param version - Version of the CID
     * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
     * @param digest - (Multi)hash of the of the content.
     */
    static create(version, code, digest) {
        if (typeof code !== 'number') {
            throw new Error('String codecs are no longer supported');
        }
        if (!(digest.bytes instanceof Uint8Array)) {
            throw new Error('Invalid digest');
        }
        switch (version) {
            case 0: {
                if (code !== DAG_PB_CODE) {
                    throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);
                }
                else {
                    return new CID(version, code, digest, digest.bytes);
                }
            }
            case 1: {
                const bytes = encodeCID(version, code, digest.bytes);
                return new CID(version, code, digest, bytes);
            }
            default: {
                throw new Error('Invalid version');
            }
        }
    }
    /**
     * Simplified version of `create` for CIDv0.
     */
    static createV0(digest) {
        return CID.create(0, DAG_PB_CODE, digest);
    }
    /**
     * Simplified version of `create` for CIDv1.
     *
     * @param code - Content encoding format code.
     * @param digest - Multihash of the content.
     */
    static createV1(code, digest) {
        return CID.create(1, code, digest);
    }
    /**
     * Decoded a CID from its binary representation. The byte array must contain
     * only the CID with no additional bytes.
     *
     * An error will be thrown if the bytes provided do not contain a valid
     * binary representation of a CID.
     */
    static decode(bytes) {
        const [cid, remainder] = CID.decodeFirst(bytes);
        if (remainder.length !== 0) {
            throw new Error('Incorrect length');
        }
        return cid;
    }
    /**
     * Decoded a CID from its binary representation at the beginning of a byte
     * array.
     *
     * Returns an array with the first element containing the CID and the second
     * element containing the remainder of the original byte array. The remainder
     * will be a zero-length byte array if the provided bytes only contained a
     * binary CID representation.
     */
    static decodeFirst(bytes) {
        const specs = CID.inspectBytes(bytes);
        const prefixSize = specs.size - specs.multihashSize;
        const multihashBytes = coerce(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));
        if (multihashBytes.byteLength !== specs.multihashSize) {
            throw new Error('Incorrect length');
        }
        const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);
        const digest = new Digest.Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);
        const cid = specs.version === 0
            ? CID.createV0(digest)
            : CID.createV1(specs.codec, digest);
        return [cid, bytes.subarray(specs.size)];
    }
    /**
     * Inspect the initial bytes of a CID to determine its properties.
     *
     * Involves decoding up to 4 varints. Typically this will require only 4 to 6
     * bytes but for larger multicodec code values and larger multihash digest
     * lengths these varints can be quite large. It is recommended that at least
     * 10 bytes be made available in the `initialBytes` argument for a complete
     * inspection.
     */
    static inspectBytes(initialBytes) {
        let offset = 0;
        const next = () => {
            const [i, length] = varint.decode(initialBytes.subarray(offset));
            offset += length;
            return i;
        };
        let version = next();
        let codec = DAG_PB_CODE;
        if (version === 18) {
            // CIDv0
            version = 0;
            offset = 0;
        }
        else {
            codec = next();
        }
        if (version !== 0 && version !== 1) {
            throw new RangeError(`Invalid CID version ${version}`);
        }
        const prefixSize = offset;
        const multihashCode = next(); // multihash code
        const digestSize = next(); // multihash length
        const size = offset + digestSize;
        const multihashSize = size - prefixSize;
        return { version, codec, multihashCode, digestSize, multihashSize, size };
    }
    /**
     * Takes cid in a string representation and creates an instance. If `base`
     * decoder is not provided will use a default from the configuration. It will
     * throw an error if encoding of the CID is not compatible with supplied (or
     * a default decoder).
     */
    static parse(source, base) {
        const [prefix, bytes] = parseCIDtoBytes(source, base);
        const cid = CID.decode(bytes);
        if (cid.version === 0 && source[0] !== 'Q') {
            throw Error('Version 0 CID string must not include multibase prefix');
        }
        // Cache string representation to avoid computing it on `this.toString()`
        baseCache(cid).set(prefix, source);
        return cid;
    }
}
function parseCIDtoBytes(source, base) {
    switch (source[0]) {
        // CIDv0 is parsed differently
        case 'Q': {
            const decoder = base ?? base58btc;
            return [
                base58btc.prefix,
                decoder.decode(`${base58btc.prefix}${source}`)
            ];
        }
        case base58btc.prefix: {
            const decoder = base ?? base58btc;
            return [base58btc.prefix, decoder.decode(source)];
        }
        case base32.prefix: {
            const decoder = base ?? base32;
            return [base32.prefix, decoder.decode(source)];
        }
        case base36.prefix: {
            const decoder = base ?? base36;
            return [base36.prefix, decoder.decode(source)];
        }
        default: {
            if (base == null) {
                throw Error('To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided');
            }
            return [source[0], base.decode(source)];
        }
    }
}
function toStringV0(bytes, cache, base) {
    const { prefix } = base;
    if (prefix !== base58btc.prefix) {
        throw Error(`Cannot string encode V0 in ${base.name} encoding`);
    }
    const cid = cache.get(prefix);
    if (cid == null) {
        const cid = base.encode(bytes).slice(1);
        cache.set(prefix, cid);
        return cid;
    }
    else {
        return cid;
    }
}
function toStringV1(bytes, cache, base) {
    const { prefix } = base;
    const cid = cache.get(prefix);
    if (cid == null) {
        const cid = base.encode(bytes);
        cache.set(prefix, cid);
        return cid;
    }
    else {
        return cid;
    }
}
const DAG_PB_CODE = 0x70;
const SHA_256_CODE = 0x12;
function encodeCID(version, code, multihash) {
    const codeOffset = varint.encodingLength(version);
    const hashOffset = codeOffset + varint.encodingLength(code);
    const bytes = new Uint8Array(hashOffset + multihash.byteLength);
    varint.encodeTo(version, bytes, 0);
    varint.encodeTo(code, bytes, codeOffset);
    bytes.set(multihash, hashOffset);
    return bytes;
}
const cidSymbol = Symbol.for('@ipld/js-cid/CID');
//# sourceMappingURL=cid.js.mapimport { coerce, equals as equalBytes } from '../bytes.js';
import * as varint from '../varint.js';
/**
 * Creates a multihash digest.
 */
export function create(code, digest) {
    const size = digest.byteLength;
    const sizeOffset = varint.encodingLength(code);
    const digestOffset = sizeOffset + varint.encodingLength(size);
    const bytes = new Uint8Array(digestOffset + size);
    varint.encodeTo(code, bytes, 0);
    varint.encodeTo(size, bytes, sizeOffset);
    bytes.set(digest, digestOffset);
    return new Digest(code, size, digest, bytes);
}
/**
 * Turns bytes representation of multihash digest into an instance.
 */
export function decode(multihash) {
    const bytes = coerce(multihash);
    const [code, sizeOffset] = varint.decode(bytes);
    const [size, digestOffset] = varint.decode(bytes.subarray(sizeOffset));
    const digest = bytes.subarray(sizeOffset + digestOffset);
    if (digest.byteLength !== size) {
        throw new Error('Incorrect length');
    }
    return new Digest(code, size, digest, bytes);
}
export function equals(a, b) {
    if (a === b) {
        return true;
    }
    else {
        const data = b;
        return (a.code === data.code &&
            a.size === data.size &&
            data.bytes instanceof Uint8Array &&
            equalBytes(a.bytes, data.bytes));
    }
}
/**
 * Represents a multihash digest which carries information about the
 * hashing algorithm and an actual hash digest.
 */
export class Digest {
    code;
    size;
    digest;
    bytes;
    /**
     * Creates a multihash digest.
     */
    constructor(code, size, digest, bytes) {
        this.code = code;
        this.size = size;
        this.digest = digest;
        this.bytes = bytes;
    }
}
/**
 * Used to check that the passed multihash has the passed code
 */
export function hasCode(digest, code) {
    return digest.code === code;
}
//# sourceMappingURL=digest.js.mapexport {};
//# sourceMappingURL=interface.js.mapimport varint from './vendor/varint.js';
export function decode(data, offset = 0) {
    const code = varint.decode(data, offset);
    return [code, varint.decode.bytes];
}
export function encodeTo(int, target, offset = 0) {
    varint.encode(int, target, offset);
    return target;
}
export function encodingLength(int) {
    return varint.encodingLength(int);
}
//# sourceMappingURL=varint.js.map/* eslint-disable */
// base-x encoding / decoding
// Copyright (c) 2018 base-x contributors
// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)
// Distributed under the MIT software license, see the accompanying
// file LICENSE or http://www.opensource.org/licenses/mit-license.php.
/**
 * @param {string} ALPHABET
 * @param {any} name
 */
function base(ALPHABET, name) {
    if (ALPHABET.length >= 255) {
        throw new TypeError('Alphabet too long');
    }
    var BASE_MAP = new Uint8Array(256);
    for (var j = 0; j < BASE_MAP.length; j++) {
        BASE_MAP[j] = 255;
    }
    for (var i = 0; i < ALPHABET.length; i++) {
        var x = ALPHABET.charAt(i);
        var xc = x.charCodeAt(0);
        if (BASE_MAP[xc] !== 255) {
            throw new TypeError(x + ' is ambiguous');
        }
        BASE_MAP[xc] = i;
    }
    var BASE = ALPHABET.length;
    var LEADER = ALPHABET.charAt(0);
    var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up
    var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up
    /**
     * @param {any[] | Iterable<number>} source
     */
    function encode(source) {
        // @ts-ignore
        if (source instanceof Uint8Array)
            ;
        else if (ArrayBuffer.isView(source)) {
            source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
        }
        else if (Array.isArray(source)) {
            source = Uint8Array.from(source);
        }
        if (!(source instanceof Uint8Array)) {
            throw new TypeError('Expected Uint8Array');
        }
        if (source.length === 0) {
            return '';
        }
        // Skip & count leading zeroes.
        var zeroes = 0;
        var length = 0;
        var pbegin = 0;
        var pend = source.length;
        while (pbegin !== pend && source[pbegin] === 0) {
            pbegin++;
            zeroes++;
        }
        // Allocate enough space in big-endian base58 representation.
        var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;
        var b58 = new Uint8Array(size);
        // Process the bytes.
        while (pbegin !== pend) {
            var carry = source[pbegin];
            // Apply "b58 = b58 * 256 + ch".
            var i = 0;
            for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {
                carry += (256 * b58[it1]) >>> 0;
                b58[it1] = (carry % BASE) >>> 0;
                carry = (carry / BASE) >>> 0;
            }
            if (carry !== 0) {
                throw new Error('Non-zero carry');
            }
            length = i;
            pbegin++;
        }
        // Skip leading zeroes in base58 result.
        var it2 = size - length;
        while (it2 !== size && b58[it2] === 0) {
            it2++;
        }
        // Translate the result into a string.
        var str = LEADER.repeat(zeroes);
        for (; it2 < size; ++it2) {
            str += ALPHABET.charAt(b58[it2]);
        }
        return str;
    }
    /**
     * @param {string | string[]} source
     */
    function decodeUnsafe(source) {
        if (typeof source !== 'string') {
            throw new TypeError('Expected String');
        }
        if (source.length === 0) {
            return new Uint8Array();
        }
        var psz = 0;
        // Skip leading spaces.
        if (source[psz] === ' ') {
            return;
        }
        // Skip and count leading '1's.
        var zeroes = 0;
        var length = 0;
        while (source[psz] === LEADER) {
            zeroes++;
            psz++;
        }
        // Allocate enough space in big-endian base256 representation.
        var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.
        var b256 = new Uint8Array(size);
        // Process the characters.
        while (source[psz]) {
            // Decode character
            var carry = BASE_MAP[source.charCodeAt(psz)];
            // Invalid character
            if (carry === 255) {
                return;
            }
            var i = 0;
            for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {
                carry += (BASE * b256[it3]) >>> 0;
                b256[it3] = (carry % 256) >>> 0;
                carry = (carry / 256) >>> 0;
            }
            if (carry !== 0) {
                throw new Error('Non-zero carry');
            }
            length = i;
            psz++;
        }
        // Skip trailing spaces.
        if (source[psz] === ' ') {
            return;
        }
        // Skip leading zeroes in b256.
        var it4 = size - length;
        while (it4 !== size && b256[it4] === 0) {
            it4++;
        }
        var vch = new Uint8Array(zeroes + (size - it4));
        var j = zeroes;
        while (it4 !== size) {
            vch[j++] = b256[it4++];
        }
        return vch;
    }
    /**
     * @param {string | string[]} string
     */
    function decode(string) {
        var buffer = decodeUnsafe(string);
        if (buffer) {
            return buffer;
        }
        throw new Error(`Non-${name} character`);
    }
    return {
        encode: encode,
        decodeUnsafe: decodeUnsafe,
        decode: decode
    };
}
var src = base;
var _brrp__multiformats_scope_baseX = src;
export default _brrp__multiformats_scope_baseX;
//# sourceMappingURL=base-x.js.map/* eslint-disable */
var encode_1 = encode;
var MSB = 0x80, REST = 0x7F, MSBALL = ~REST, INT = Math.pow(2, 31);
/**
 * @param {number} num
 * @param {number[]} out
 * @param {number} offset
 */
function encode(num, out, offset) {
    out = out || [];
    offset = offset || 0;
    var oldOffset = offset;
    while (num >= INT) {
        out[offset++] = (num & 0xFF) | MSB;
        num /= 128;
    }
    while (num & MSBALL) {
        out[offset++] = (num & 0xFF) | MSB;
        num >>>= 7;
    }
    out[offset] = num | 0;
    // @ts-ignore
    encode.bytes = offset - oldOffset + 1;
    return out;
}
var decode = read;
var MSB$1 = 0x80, REST$1 = 0x7F;
/**
 * @param {string | any[]} buf
 * @param {number} offset
 */
function read(buf, offset) {
    var res = 0, offset = offset || 0, shift = 0, counter = offset, b, l = buf.length;
    do {
        if (counter >= l) {
            // @ts-ignore
            read.bytes = 0;
            throw new RangeError('Could not decode varint');
        }
        b = buf[counter++];
        res += shift < 28
            ? (b & REST$1) << shift
            : (b & REST$1) * Math.pow(2, shift);
        shift += 7;
    } while (b >= MSB$1);
    // @ts-ignore
    read.bytes = counter - offset;
    return res;
}
var N1 = Math.pow(2, 7);
var N2 = Math.pow(2, 14);
var N3 = Math.pow(2, 21);
var N4 = Math.pow(2, 28);
var N5 = Math.pow(2, 35);
var N6 = Math.pow(2, 42);
var N7 = Math.pow(2, 49);
var N8 = Math.pow(2, 56);
var N9 = Math.pow(2, 63);
var length = function (/** @type {number} */ value) {
    return (value < N1 ? 1
        : value < N2 ? 2
            : value < N3 ? 3
                : value < N4 ? 4
                    : value < N5 ? 5
                        : value < N6 ? 6
                            : value < N7 ? 7
                                : value < N8 ? 8
                                    : value < N9 ? 9
                                        : 10);
};
var varint = {
    encode: encode_1,
    decode: decode,
    encodingLength: length
};
var _brrp_varint = varint;
export default _brrp_varint;
//# sourceMappingURL=varint.js.map{
  "name": "multiformats",
  "version": "13.4.2",
  "description": "Interface for multihash, multicodec, multibase and CID",
  "author": "Mikeal Rogers <mikeal.rogers@gmail.com> (https://www.mikealrogers.com/)",
  "license": "Apache-2.0 OR MIT",
  "homepage": "https://github.com/multiformats/js-multiformats#readme",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/multiformats/js-multiformats.git"
  },
  "bugs": {
    "url": "https://github.com/multiformats/js-multiformats/issues"
  },
  "publishConfig": {
    "access": "public",
    "provenance": true
  },
  "keywords": [
    "ipfs",
    "ipld",
    "multiformats"
  ],
  "type": "module",
  "types": "./dist/src/index.d.ts",
  "typesVersions": {
    "*": {
      "*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ],
      "src/*": [
        "*",
        "dist/*",
        "dist/src/*",
        "dist/src/*/index"
      ]
    }
  },
  "files": [
    "src",
    "dist",
    "!dist/test",
    "!**/*.tsbuildinfo"
  ],
  "exports": {
    ".": {
      "types": "./dist/src/index.d.ts",
      "import": "./dist/src/index.js"
    },
    "./bases/base10": {
      "types": "./dist/src/bases/base10.d.ts",
      "import": "./dist/src/bases/base10.js"
    },
    "./bases/base16": {
      "types": "./dist/src/bases/base16.d.ts",
      "import": "./dist/src/bases/base16.js"
    },
    "./bases/base2": {
      "types": "./dist/src/bases/base2.d.ts",
      "import": "./dist/src/bases/base2.js"
    },
    "./bases/base256emoji": {
      "types": "./dist/src/bases/base256emoji.d.ts",
      "import": "./dist/src/bases/base256emoji.js"
    },
    "./bases/base32": {
      "types": "./dist/src/bases/base32.d.ts",
      "import": "./dist/src/bases/base32.js"
    },
    "./bases/base36": {
      "types": "./dist/src/bases/base36.d.ts",
      "import": "./dist/src/bases/base36.js"
    },
    "./bases/base58": {
      "types": "./dist/src/bases/base58.d.ts",
      "import": "./dist/src/bases/base58.js"
    },
    "./bases/base64": {
      "types": "./dist/src/bases/base64.d.ts",
      "import": "./dist/src/bases/base64.js"
    },
    "./bases/base8": {
      "types": "./dist/src/bases/base8.d.ts",
      "import": "./dist/src/bases/base8.js"
    },
    "./bases/identity": {
      "types": "./dist/src/bases/identity.d.ts",
      "import": "./dist/src/bases/identity.js"
    },
    "./bases/interface": {
      "types": "./dist/src/bases/interface.d.ts",
      "import": "./dist/src/bases/interface.js"
    },
    "./basics": {
      "types": "./dist/src/basics.d.ts",
      "import": "./dist/src/basics.js"
    },
    "./block": {
      "types": "./dist/src/block.d.ts",
      "import": "./dist/src/block.js"
    },
    "./block/interface": {
      "types": "./dist/src/block/interface.d.ts",
      "import": "./dist/src/block/interface.js"
    },
    "./bytes": {
      "types": "./dist/src/bytes.d.ts",
      "import": "./dist/src/bytes.js"
    },
    "./cid": {
      "types": "./dist/src/cid.d.ts",
      "import": "./dist/src/cid.js"
    },
    "./codecs/interface": {
      "types": "./dist/src/codecs/interface.d.ts",
      "import": "./dist/src/codecs/interface.js"
    },
    "./codecs/json": {
      "types": "./dist/src/codecs/json.d.ts",
      "import": "./dist/src/codecs/json.js"
    },
    "./codecs/raw": {
      "types": "./dist/src/codecs/raw.d.ts",
      "import": "./dist/src/codecs/raw.js"
    },
    "./hashes/digest": {
      "types": "./dist/src/hashes/digest.d.ts",
      "import": "./dist/src/hashes/digest.js"
    },
    "./hashes/hasher": {
      "types": "./dist/src/hashes/hasher.d.ts",
      "import": "./dist/src/hashes/hasher.js"
    },
    "./hashes/identity": {
      "types": "./dist/src/hashes/identity.d.ts",
      "import": "./dist/src/hashes/identity.js"
    },
    "./hashes/interface": {
      "types": "./dist/src/hashes/interface.d.ts",
      "import": "./dist/src/hashes/interface.js"
    },
    "./hashes/sha1": {
      "types": "./dist/types/src/hashes/sha1.d.ts",
      "browser": "./dist/src/hashes/sha1-browser.js",
      "import": "./dist/src/hashes/sha1.js"
    },
    "./hashes/sha2": {
      "types": "./dist/src/hashes/sha2.d.ts",
      "browser": "./dist/src/hashes/sha2-browser.js",
      "import": "./dist/src/hashes/sha2.js"
    },
    "./interface": {
      "types": "./dist/src/interface.d.ts",
      "import": "./dist/src/interface.js"
    },
    "./link": {
      "types": "./dist/src/link.d.ts",
      "import": "./dist/src/link.js"
    },
    "./link/interface": {
      "types": "./dist/src/link/interface.d.ts",
      "import": "./dist/src/link/interface.js"
    },
    "./traversal": {
      "types": "./dist/src/traversal.d.ts",
      "import": "./dist/src/traversal.js"
    }
  },
  "eslintConfig": {
    "extends": "ipfs",
    "parserOptions": {
      "project": true,
      "sourceType": "module"
    }
  },
  "release": {
    "branches": [
      "master"
    ],
    "plugins": [
      [
        "@semantic-release/commit-analyzer",
        {
          "preset": "conventionalcommits",
          "releaseRules": [
            {
              "breaking": true,
              "release": "major"
            },
            {
              "revert": true,
              "release": "patch"
            },
            {
              "type": "feat",
              "release": "minor"
            },
            {
              "type": "fix",
              "release": "patch"
            },
            {
              "type": "docs",
              "release": "patch"
            },
            {
              "type": "test",
              "release": "patch"
            },
            {
              "type": "deps",
              "release": "patch"
            },
            {
              "scope": "no-release",
              "release": false
            }
          ]
        }
      ],
      [
        "@semantic-release/release-notes-generator",
        {
          "preset": "conventionalcommits",
          "presetConfig": {
            "types": [
              {
                "type": "feat",
                "section": "Features"
              },
              {
                "type": "fix",
                "section": "Bug Fixes"
              },
              {
                "type": "chore",
                "section": "Trivial Changes"
              },
              {
                "type": "docs",
                "section": "Documentation"
              },
              {
                "type": "deps",
                "section": "Dependencies"
              },
              {
                "type": "test",
                "section": "Tests"
              }
            ]
          }
        }
      ],
      "@semantic-release/changelog",
      "@semantic-release/npm",
      "@semantic-release/github",
      [
        "@semantic-release/git",
        {
          "assets": [
            "CHANGELOG.md",
            "package.json"
          ]
        }
      ]
    ]
  },
  "scripts": {
    "clean": "aegir clean",
    "lint": "aegir lint",
    "build": "aegir build",
    "release": "aegir release",
    "docs": "aegir docs",
    "test": "npm run lint && npm run test:node && npm run test:chrome",
    "test:node": "aegir test -t node --cov",
    "test:chrome": "aegir test -t browser --cov",
    "test:chrome-webworker": "aegir test -t webworker",
    "test:firefox": "aegir test -t browser -- --browser firefox",
    "test:firefox-webworker": "aegir test -t webworker -- --browser firefox",
    "test:electron-main": "aegir test -t electron-main"
  },
  "devDependencies": {
    "@stablelib/sha256": "^2.0.0",
    "@stablelib/sha512": "^2.0.0",
    "@types/node": "^25.0.0",
    "aegir": "^47.0.7",
    "buffer": "^6.0.3",
    "cids": "^1.1.9",
    "crypto-hash": "^4.0.0"
  },
  "aegir": {
    "test": {
      "target": [
        "node",
        "browser"
      ]
    }
  },
  "browser": {
    "./hashes/sha1": "./dist/src/hashes/sha1-browser.js",
    "./dist/src/hashes/sha1.js": "./dist/src/hashes/sha1-browser.js",
    "./hashes/sha2": "./dist/src/hashes/sha2-browser.js",
    "./dist/src/hashes/sha2.js": "./dist/src/hashes/sha2-browser.js"
  }
}
module.exports = assert

class AssertionError extends Error {}
AssertionError.prototype.name = 'AssertionError'

/**
 * Minimal assert function
 * @param  {any} t Value to check if falsy
 * @param  {string=} m Optional assertion error message
 * @throws {AssertionError}
 */
function assert (t, m) {
  if (!t) {
    var err = new AssertionError(m)
    if (Error.captureStackTrace) Error.captureStackTrace(err, assert)
    throw err
  }
}
{
  "name": "nanoassert",
  "version": "2.0.0",
  "description": "Nanoscale assertion module",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "tape": "^4.9.1"
  },
  "scripts": {
    "test": "tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/emilbayes/nanoassert.git"
  },
  "keywords": [
    "assert",
    "unassert",
    "power-assert",
    "tiny",
    "nano",
    "pico"
  ],
  "author": "Emil Bay <github@tixz.dk>",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/emilbayes/nanoassert/issues"
  },
  "homepage": "https://github.com/emilbayes/nanoassert#readme"
}
module.exports = class NatSampler {
  constructor () {
    this.host = null
    this.port = 0
    this.size = 0

    this._a = null
    this._b = null
    this._threshold = 0
    this._top = 0
    this._samples = []
  }

  add (host, port) {
    const a = this._bump(host, port, 2)
    const b = this._bump(host, 0, 1)

    if (this._samples.length < 32) {
      this.size++
      this._threshold = this.size - (this.size < 4 ? 0 : this.size < 8 ? 1 : this.size < 12 ? 2 : 3)
      this._samples.push(a, b)
      this._top += 2
    } else {
      if (this._top === 32) this._top = 0

      const oa = this._samples[this._top]
      this._samples[this._top++] = a
      oa.hits--

      const ob = this._samples[this._top]
      this._samples[this._top++] = b
      ob.hits--
    }

    if (this._a === null || this._a.hits < a.hits) this._a = a
    if (this._b === null || this._b.hits < b.hits) this._b = b

    if (this._a.hits >= this._threshold) {
      this.host = this._a.host
      this.port = this._a.port
    } else if (this._b.hits >= this._threshold) {
      this.host = this._b.host
      this.port = 0
    } else {
      this.host = null
      this.port = 0
    }

    return a.hits
  }

  _bump (host, port, inc) {
    for (let i = 0; i < 4; i++) {
      const j = (this._top - inc - (2 * i)) & 31
      if (j >= this._samples.length) return { host, port, hits: 1 }
      const s = this._samples[j]
      if (s.port === port && s.host === host) {
        s.hits++
        return s
      }
    }
    return { host, port, hits: 1 }
  }
}
{
  "name": "nat-sampler",
  "version": "1.0.1",
  "description": "Sample addresses to figure out if a host + port is consistent",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^16.0.3",
    "tape": "^5.2.2"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/nat-sampler.git"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/nat-sampler/issues"
  },
  "homepage": "https://github.com/mafintosh/nat-sampler"
}
/* eslint-disable camelcase */
const sodium = require('sodium-universal')
const assert = require('nanoassert')
const b4a = require('b4a')

const DHLEN = sodium.crypto_scalarmult_ed25519_BYTES
const PKLEN = sodium.crypto_scalarmult_ed25519_BYTES
const SCALARLEN = sodium.crypto_scalarmult_ed25519_BYTES
const SKLEN = sodium.crypto_sign_SECRETKEYBYTES
const ALG = 'Ed25519'

module.exports = {
  DHLEN,
  PKLEN,
  SCALARLEN,
  SKLEN,
  ALG,
  name: ALG,
  generateKeyPair,
  dh
}

function generateKeyPair (privKey) {
  if (privKey) return generateSeedKeyPair(privKey.subarray(0, 32))

  const keyPair = {}
  keyPair.secretKey = b4a.alloc(SKLEN)
  keyPair.publicKey = b4a.alloc(PKLEN)

  sodium.crypto_sign_keypair(keyPair.publicKey, keyPair.secretKey)
  return keyPair
}

function generateSeedKeyPair (seed) {
  const keyPair = {}
  keyPair.secretKey = b4a.alloc(SKLEN)
  keyPair.publicKey = b4a.alloc(PKLEN)

  sodium.crypto_sign_seed_keypair(keyPair.publicKey, keyPair.secretKey, seed)
  return keyPair
}

function dh (publicKey, { scalar, secretKey }) {
  // tweaked keys expose scalar directly
  if (!scalar) {
    assert(secretKey.byteLength === SKLEN)

    // libsodium stores seed not actual scalar
    const sk = b4a.alloc(64)
    sodium.crypto_hash_sha512(sk, secretKey.subarray(0, 32))
    sk[0] &= 248
    sk[31] &= 127
    sk[31] |= 64

    scalar = sk.subarray(0, 32)
  }

  assert(scalar.byteLength === SCALARLEN)
  assert(publicKey.byteLength === PKLEN)

  const output = b4a.alloc(DHLEN)

  // we clamp if necessary above
  sodium.crypto_scalarmult_ed25519_noclamp(
    output,
    scalar,
    publicKey
  )

  return output
}
{
  "name": "noise-curve-ed",
  "version": "2.1.0",
  "description": "Ed25519 elliptic curve operations for [`noise-handshake`](https://github.com/chm-diederichs/noise-handshake)",
  "main": "index.js",
  "scripts": {
    "test": "npx standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/chm-diederichs/noise-curve-ed.git"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/chm-diederichs/noise-curve-ed/issues"
  },
  "homepage": "https://github.com/chm-diederichs/noise-curve-ed#readme",
  "dependencies": {
    "b4a": "^1.1.0",
    "nanoassert": "^2.0.0",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "noise-handshake": "^3.0.0",
    "standard": "^16.0.3",
    "tape": "^5.2.2"
  }
}
const sodium = require('sodium-universal')
const b4a = require('b4a')

module.exports = class CipherState {
  constructor (key) {
    this.key = key || null
    this.nonce = 0
    this.CIPHER_ALG = 'ChaChaPoly'
  }

  initialiseKey (key) {
    this.key = key
    this.nonce = 0
  }

  setNonce (nonce) {
    this.nonce = nonce
  }

  encrypt (plaintext, ad) {
    if (!this.hasKey) return plaintext
    if (!ad) ad = b4a.alloc(0)

    const ciphertext = encryptWithAD(this.key, this.nonce, ad, plaintext)
    if (ciphertext.length > 65535) throw new Error(`ciphertext length of ${ciphertext.length} exceeds maximum Noise message length of 65535`)
    this.nonce++

    return ciphertext
  }

  decrypt (ciphertext, ad) {
    if (!this.hasKey) return ciphertext
    if (!ad) ad = b4a.alloc(0)
    if (ciphertext.length > 65535) throw new Error(`ciphertext length of ${ciphertext.length} exceeds maximum Noise message length of 65535`)

    const plaintext = decryptWithAD(this.key, this.nonce, ad, ciphertext)
    this.nonce++

    return plaintext
  }

  get hasKey () {
    return this.key !== null
  }

  _clear () {
    sodium.sodium_memzero(this.key)
    this.key = null
    this.nonce = null
  }

  static get MACBYTES () {
    return 16
  }

  static get NONCEBYTES () {
    return 8
  }

  static get KEYBYTES () {
    return 32
  }
}

function encryptWithAD (key, counter, additionalData, plaintext) {
  // for our purposes, additionalData will always be a pubkey so we encode from hex
  if (!b4a.isBuffer(additionalData)) additionalData = b4a.from(additionalData, 'hex')
  if (!b4a.isBuffer(plaintext)) plaintext = b4a.from(plaintext, 'hex')

  const nonce = b4a.alloc(sodium.crypto_aead_chacha20poly1305_ietf_NPUBBYTES)
  const view = new DataView(nonce.buffer, nonce.byteOffset, nonce.byteLength)
  view.setUint32(4, counter, true)

  const ciphertext = b4a.alloc(plaintext.byteLength + sodium.crypto_aead_chacha20poly1305_ietf_ABYTES)

  sodium.crypto_aead_chacha20poly1305_ietf_encrypt(ciphertext, plaintext, additionalData, null, nonce, key)
  return ciphertext
}

function decryptWithAD (key, counter, additionalData, ciphertext) {
  // for our purposes, additionalData will always be a pubkey so we encode from hex
  if (!b4a.isBuffer(additionalData)) additionalData = b4a.from(additionalData, 'hex')
  if (!b4a.isBuffer(ciphertext)) ciphertext = b4a.from(ciphertext, 'hex')

  const nonce = b4a.alloc(sodium.crypto_aead_chacha20poly1305_ietf_NPUBBYTES)
  const view = new DataView(nonce.buffer, nonce.byteOffset, nonce.byteLength)
  view.setUint32(4, counter, true)

  const plaintext = b4a.alloc(ciphertext.byteLength - sodium.crypto_aead_chacha20poly1305_ietf_ABYTES)

  sodium.crypto_aead_chacha20poly1305_ietf_decrypt(plaintext, null, ciphertext, additionalData, nonce, key)
  return plaintext
}
/* eslint-disable camelcase */
const {
  crypto_kx_SEEDBYTES,
  crypto_kx_keypair,
  crypto_kx_seed_keypair,
  crypto_scalarmult_BYTES,
  crypto_scalarmult_SCALARBYTES,
  crypto_scalarmult,
  crypto_scalarmult_base
} = require('sodium-universal')

const assert = require('nanoassert')
const b4a = require('b4a')

const DHLEN = crypto_scalarmult_BYTES
const PKLEN = crypto_scalarmult_BYTES
const SKLEN = crypto_scalarmult_SCALARBYTES
const SEEDLEN = crypto_kx_SEEDBYTES
const ALG = '25519'

module.exports = {
  DHLEN,
  PKLEN,
  SKLEN,
  SEEDLEN,
  ALG,
  generateKeyPair,
  generateSeedKeyPair,
  dh
}

function generateKeyPair (privKey) {
  const keyPair = {}

  keyPair.secretKey = privKey || b4a.alloc(SKLEN)
  keyPair.publicKey = b4a.alloc(PKLEN)

  if (privKey) {
    crypto_scalarmult_base(keyPair.publicKey, keyPair.secretKey)
  } else {
    crypto_kx_keypair(keyPair.publicKey, keyPair.secretKey)
  }

  return keyPair
}

function generateSeedKeyPair (seed) {
  assert(seed.byteLength === SKLEN)

  const keyPair = {}
  keyPair.secretKey = b4a.alloc(SKLEN)
  keyPair.publicKey = b4a.alloc(PKLEN)

  crypto_kx_seed_keypair(keyPair.publicKey, keyPair.secretKey, seed)
  return keyPair
}

function dh (publicKey, { secretKey }) {
  assert(secretKey.byteLength === SKLEN)
  assert(publicKey.byteLength === PKLEN)

  const output = b4a.alloc(DHLEN)

  crypto_scalarmult(
    output,
    secretKey,
    publicKey
  )

  return output
}
const hmacBlake2b = require('./hmac')
const b4a = require('b4a')

const HASHLEN = 64

module.exports = {
  hkdf,
  HASHLEN
}

// HMAC-based Extract-and-Expand KDF
// https://www.ietf.org/rfc/rfc5869.txt

function hkdf (salt, inputKeyMaterial, info = '', length = 2 * HASHLEN) {
  const pseudoRandomKey = hkdfExtract(salt, inputKeyMaterial)
  return hkdfExpand(pseudoRandomKey, info, length)
}

function hkdfExtract (salt, inputKeyMaterial) {
  const hmac = b4a.alloc(HASHLEN)
  return hmacDigest(hmac, salt, inputKeyMaterial)
}

function hkdfExpand (key, info, length) {
  // Put in dedicated slab to avoid keeping shared slab from being gc'ed
  const buffer = b4a.allocUnsafeSlow(length)

  const infoBuf = b4a.from(info)
  let prev = infoBuf

  const result = []
  for (let i = 0; i < length; i += HASHLEN) {
    const pos = b4a.from([(i / HASHLEN) + 1])

    const out = buffer.subarray(i, i + HASHLEN)
    result.push(out)

    prev = hmacDigest(out, key, [prev, infoBuf, pos])
  }

  return result
}

function hmacDigest (out, key, input) {
  hmacBlake2b(out, input, key)
  return out
}
/* eslint-disable camelcase */
const b4a = require('b4a')
const { sodium_memzero, crypto_generichash, crypto_generichash_batch } = require('sodium-universal')

const HASHLEN = 64
const BLOCKLEN = 128
const scratch = b4a.alloc(BLOCKLEN * 3)
const HMACKey = scratch.subarray(BLOCKLEN * 0, BLOCKLEN * 1)
const OuterKeyPad = scratch.subarray(BLOCKLEN * 1, BLOCKLEN * 2)
const InnerKeyPad = scratch.subarray(BLOCKLEN * 2, BLOCKLEN * 3)

// Post-fill is done in the cases where someone caught an exception that
// happened before we were able to clear data at the end

module.exports = function hmac (out, batch, key) {
  if (key.byteLength > BLOCKLEN) {
    crypto_generichash(HMACKey.subarray(0, HASHLEN), key)
    sodium_memzero(HMACKey.subarray(HASHLEN))
  } else {
    // Covers key <= BLOCKLEN
    HMACKey.set(key)
    sodium_memzero(HMACKey.subarray(key.byteLength))
  }

  for (let i = 0; i < HMACKey.byteLength; i++) {
    OuterKeyPad[i] = 0x5c ^ HMACKey[i]
    InnerKeyPad[i] = 0x36 ^ HMACKey[i]
  }
  sodium_memzero(HMACKey)

  crypto_generichash_batch(out, [InnerKeyPad].concat(batch))
  sodium_memzero(InnerKeyPad)
  crypto_generichash_batch(out, [OuterKeyPad, out])
  sodium_memzero(OuterKeyPad)
}

module.exports.BYTES = HASHLEN
module.exports.KEYBYTES = BLOCKLEN
const assert = require('nanoassert')
const b4a = require('b4a')

const SymmetricState = require('./symmetric-state')
const { HASHLEN } = require('./hkdf')

const PRESHARE_IS = Symbol('initiator static key preshared')
const PRESHARE_RS = Symbol('responder static key preshared')

const TOK_PSK = Symbol('psk')

const TOK_S = Symbol('s')
const TOK_E = Symbol('e')

const TOK_ES = Symbol('es')
const TOK_SE = Symbol('se')
const TOK_EE = Symbol('ee')
const TOK_SS = Symbol('ss')

const HANDSHAKES = Object.freeze({
  NN: [
    [TOK_E],
    [TOK_E, TOK_EE]
  ],
  NNpsk0: [
    [TOK_PSK, TOK_E],
    [TOK_E, TOK_EE]
  ],
  XX: [
    [TOK_E],
    [TOK_E, TOK_EE, TOK_S, TOK_ES],
    [TOK_S, TOK_SE]
  ],
  XXpsk0: [
    [TOK_PSK, TOK_E],
    [TOK_E, TOK_EE, TOK_S, TOK_ES],
    [TOK_S, TOK_SE]
  ],
  IK: [
    PRESHARE_RS,
    [TOK_E, TOK_ES, TOK_S, TOK_SS],
    [TOK_E, TOK_EE, TOK_SE]
  ],
  XK: [
    PRESHARE_RS,
    [TOK_E, TOK_ES],
    [TOK_E, TOK_EE],
    [TOK_S, TOK_SE]
  ]
})

class Writer {
  constructor () {
    this.size = 0
    this.buffers = []
  }

  push (b) {
    this.size += b.byteLength
    this.buffers.push(b)
  }

  end () {
    const all = b4a.alloc(this.size)
    let offset = 0
    for (const b of this.buffers) {
      all.set(b, offset)
      offset += b.byteLength
    }
    return all
  }
}

class Reader {
  constructor (buf) {
    this.offset = 0
    this.buffer = buf
  }

  shift (n) {
    const start = this.offset
    const end = this.offset += n
    if (end > this.buffer.byteLength) throw new Error('Insufficient bytes')
    return this.buffer.subarray(start, end)
  }

  end () {
    return this.shift(this.buffer.byteLength - this.offset)
  }
}

module.exports = class NoiseState extends SymmetricState {
  constructor (pattern, initiator, staticKeypair, opts = {}) {
    super(opts)

    this.s = staticKeypair || this.curve.generateKeyPair()
    this.e = null

    this.psk = null
    if (opts && opts.psk) this.psk = opts.psk

    this.re = null
    this.rs = null

    this.pattern = pattern
    this.handshake = HANDSHAKES[this.pattern].slice()

    this.isPskHandshake = !!this.psk && hasPskToken(this.handshake)

    this.protocol = b4a.from([
      'Noise',
      this.pattern,
      this.DH_ALG,
      this.CIPHER_ALG,
      'BLAKE2b'
    ].join('_'))

    this.initiator = initiator
    this.complete = false

    this.rx = null
    this.tx = null
    this.hash = null
  }

  initialise (prologue, remoteStatic) {
    if (this.protocol.byteLength <= HASHLEN) this.digest.set(this.protocol)
    else this.mixHash(this.protocol)

    this.chainingKey = b4a.from(this.digest)

    this.mixHash(prologue)

    while (!Array.isArray(this.handshake[0])) {
      const message = this.handshake.shift()

      // handshake steps should be as arrays, only
      // preshare tokens are provided otherwise
      assert(message === PRESHARE_RS || message === PRESHARE_IS,
        'Unexpected pattern')

      const takeRemoteKey = this.initiator
        ? message === PRESHARE_RS
        : message === PRESHARE_IS

      if (takeRemoteKey) this.rs = remoteStatic

      const key = takeRemoteKey ? this.rs : this.s.publicKey
      assert(key != null, 'Remote pubkey required')

      this.mixHash(key)
    }
  }

  final () {
    const [k1, k2] = this.split()

    this.tx = this.initiator ? k1 : k2
    this.rx = this.initiator ? k2 : k1

    this.complete = true
    this.hash = this.getHandshakeHash()

    this._clear()
  }

  recv (buf) {
    const r = new Reader(buf)

    for (const pattern of this.handshake.shift()) {
      switch (pattern) {
        case TOK_PSK :
          this.mixKeyAndHash(this.psk)
          break

        case TOK_E :
          this.re = r.shift(this.curve.PKLEN)
          this.mixHash(this.re)
          if (this.isPskHandshake) this.mixKeyNormal(this.re)
          break

        case TOK_S : {
          const klen = this.hasKey ? this.curve.PKLEN + 16 : this.curve.PKLEN
          this.rs = this.decryptAndHash(r.shift(klen))
          break
        }

        case TOK_EE :
        case TOK_ES :
        case TOK_SE :
        case TOK_SS : {
          const useStatic = keyPattern(pattern, this.initiator)

          const localKey = useStatic.local ? this.s : this.e
          const remoteKey = useStatic.remote ? this.rs : this.re

          this.mixKey(remoteKey, localKey)
          break
        }

        default :
          throw new Error('Unexpected message')
      }
    }

    const payload = this.decryptAndHash(r.end())

    if (!this.handshake.length) this.final()
    return payload
  }

  send (payload = b4a.alloc(0)) {
    const w = new Writer()

    for (const pattern of this.handshake.shift()) {
      switch (pattern) {
        case TOK_PSK :
          this.mixKeyAndHash(this.psk)
          break

        case TOK_E :
          if (this.e === null) this.e = this.curve.generateKeyPair()
          this.mixHash(this.e.publicKey)
          if (this.isPskHandshake) this.mixKeyNormal(this.e.publicKey)
          w.push(this.e.publicKey)
          break

        case TOK_S :
          w.push(this.encryptAndHash(this.s.publicKey))
          break

        case TOK_ES :
        case TOK_SE :
        case TOK_EE :
        case TOK_SS : {
          const useStatic = keyPattern(pattern, this.initiator)

          const localKey = useStatic.local ? this.s : this.e
          const remoteKey = useStatic.remote ? this.rs : this.re

          this.mixKey(remoteKey, localKey)
          break
        }

        default :
          throw new Error('Unexpected message')
      }
    }

    w.push(this.encryptAndHash(payload))
    const response = w.end()

    if (!this.handshake.length) this.final()
    return response
  }

  _clear () {
    super._clear()

    this.e.secretKey.fill(0)
    this.e.publicKey.fill(0)

    this.re.fill(0)

    this.e = null
    this.re = null
  }
}

function keyPattern (pattern, initiator) {
  const ret = {
    local: false,
    remote: false
  }

  switch (pattern) {
    case TOK_EE:
      return ret

    case TOK_ES:
      ret.local ^= !initiator
      ret.remote ^= initiator
      return ret

    case TOK_SE:
      ret.local ^= initiator
      ret.remote ^= !initiator
      return ret

    case TOK_SS:
      ret.local ^= 1
      ret.remote ^= 1
      return ret
  }
}

function hasPskToken (handshake) {
  return handshake.some(x => {
    return Array.isArray(x) && x.indexOf(TOK_PSK) !== -1
  })
}
{
  "name": "noise-handshake",
  "version": "4.2.0",
  "description": "Noise protocol handshake",
  "main": "noise.js",
  "files": [
    "*.js"
  ],
  "scripts": {
    "test": "standard && brittle test/*.js"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/noise-handshake.git"
  },
  "dependencies": {
    "b4a": "^1.1.0",
    "nanoassert": "^2.0.0",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "noise-protocol": "chm-diederichs/noise-protocol.git#xx-ephemeral-key",
    "standard": "^16.0.3"
  }
}
const sodium = require('sodium-universal')
const assert = require('nanoassert')
const b4a = require('b4a')
const CipherState = require('./cipher')
const curve = require('./dh')
const { HASHLEN, hkdf } = require('./hkdf')

module.exports = class SymmetricState extends CipherState {
  constructor (opts = {}) {
    super()

    this.curve = opts.curve || curve
    this.digest = b4a.alloc(HASHLEN)
    this.chainingKey = null
    this.offset = 0

    this.DH_ALG = this.curve.ALG
  }

  mixHash (data) {
    accumulateDigest(this.digest, data)
  }

  mixKeyAndHash (key) {
    const [ck, tempH, tempK] = hkdf(this.chainingKey, key, '', 3 * HASHLEN)
    this.chainingKey = ck
    this.mixHash(tempH)
    this.initialiseKey(tempK.subarray(0, 32))
  }

  mixKeyNormal (key) {
    const [ck, tempK] = hkdf(this.chainingKey, key)
    this.chainingKey = ck
    this.initialiseKey(tempK.subarray(0, 32))
  }

  mixKey (remoteKey, localKey) {
    const dh = this.curve.dh(remoteKey, localKey)
    const hkdfResult = hkdf(this.chainingKey, dh)
    this.chainingKey = hkdfResult[0]
    this.initialiseKey(hkdfResult[1].subarray(0, 32))
  }

  encryptAndHash (plaintext) {
    const ciphertext = this.encrypt(plaintext, this.digest)
    accumulateDigest(this.digest, ciphertext)
    return ciphertext
  }

  decryptAndHash (ciphertext) {
    const plaintext = this.decrypt(ciphertext, this.digest)
    accumulateDigest(this.digest, ciphertext)
    return plaintext
  }

  getHandshakeHash (out) {
    if (!out) return this.getHandshakeHash(b4a.alloc(HASHLEN))
    assert(out.byteLength === HASHLEN, `output must be ${HASHLEN} bytes`)

    out.set(this.digest)
    return out
  }

  split () {
    const res = hkdf(this.chainingKey, b4a.alloc(0))
    return res.map(k => k.subarray(0, 32))
  }

  _clear () {
    super._clear()

    sodium.sodium_memzero(this.digest)
    sodium.sodium_memzero(this.chainingKey)

    this.digest = null
    this.chainingKey = null
    this.offset = null

    this.curve = null
  }

  static get alg () {
    return CipherState.alg + '_BLAKE2b'
  }
}

function accumulateDigest (digest, input) {
  const toHash = b4a.concat([digest, input])
  sodium.crypto_generichash(digest, toHash)
}
const EventEmitter = require('events')
const Protomux = require('protomux')
const c = require('compact-encoding')
const bitfield = require('compact-encoding-bitfield')
const bits = require('bits-to-bytes')
const safetyCatch = require('safety-catch')
const errors = require('./lib/errors')

module.exports = class ProtomuxRPC extends EventEmitter {
  constructor(stream, options = {}) {
    super()

    const {
      id,
      protocol = 'protomux-rpc',
      valueEncoding = c.optionalBuffer,
      handshake = null,
      handshakeEncoding
    } = options

    this._mux = Protomux.from(stream)
    this._defaultValueEncoding = valueEncoding

    this._id = 1
    this._ending = null
    this._destroyed = false
    this._error = null
    this._responding = 0

    this._requests = new Map()
    this._responders = new Map()

    this._channel = this._mux.createChannel({
      protocol,
      id,
      handshake: handshake === null ? null : handshakeEncoding || c.raw,
      onopen: this._onopen.bind(this),
      onclose: this._onclose.bind(this),
      ondestroy: this._ondestroy.bind(this)
    })

    if (this._channel === null) throw errors.DUPLICATE_CHANNEL()

    this._request = this._channel.addMessage({
      encoding: request,
      onmessage: this._onrequest.bind(this)
    })

    this._response = this._channel.addMessage({
      encoding: response,
      onmessage: this._onresponse.bind(this)
    })

    this._channel.open(handshake)
  }

  _onopen(handshake) {
    this.emit('open', handshake)
  }

  _onclose() {
    this._ending = Promise.resolve()

    const err = this._error || errors.CHANNEL_CLOSED()

    for (const request of this._requests.values()) {
      request.reject(err)
      if (request.timeout) clearTimeout(request.timeout)
    }

    this._requests.clear()
    this._responders.clear()

    this.emit('close')
  }

  _ondestroy() {
    this._destroyed = true
    this.emit('destroy')
  }

  async _onrequest({ id, method, value }) {
    let error = null

    const responder = this._responders.get(method)

    if (responder === undefined) error = errors.UNKNOWN_METHOD(`Unknown method '${method}'`)
    else {
      const {
        valueEncoding = this._defaultValueEncoding,
        requestEncoding = valueEncoding,
        responseEncoding = valueEncoding
      } = responder.options

      this._responding++

      try {
        if (requestEncoding) value = c.decode(requestEncoding, value)

        try {
          value = await responder.handler(value)
        } catch (err) {
          safetyCatch(err)

          error = errors.REQUEST_ERROR('Request failed', err)
        }
      } catch (err) {
        safetyCatch(err)

        error = errors.DECODE_ERROR('Could not decode request', err)
      }

      this._responding--

      if (!error && responseEncoding && id) {
        try {
          value = c.encode(responseEncoding, value)
        } catch (err) {
          safetyCatch(err)

          error = errors.ENCODE_ERROR('Could not encode response', err)
        }
      }
    }

    if (id) this._response.send({ id, error, value })

    this._endMaybe()
  }

  _onresponse({ id, error, value }) {
    if (id === 0) return

    const request = this._requests.get(id)

    if (request === undefined) return

    this._requests.delete(id)

    if (request.timeout) clearTimeout(request.timeout)

    if (error) request.reject(error)
    else {
      const { valueEncoding = this._defaultValueEncoding, responseEncoding = valueEncoding } =
        request.options

      try {
        if (responseEncoding) value = c.decode(responseEncoding, value)

        request.resolve(value)
      } catch (err) {
        safetyCatch(err)

        request.reject(errors.DECODE_ERROR('Could not decode response', err))
      }
    }

    this._endMaybe()
  }

  _ontimeout(id, timeout) {
    const request = this._requests.get(id)

    if (request === undefined) return

    this._requests.delete(id)

    request.reject(errors.TIMEOUT_EXCEEDED(`timeout of ${timeout}ms exceeded`))

    this._endMaybe()
  }

  get opened() {
    return this._channel.opened
  }

  get closed() {
    return this._channel.closed
  }

  get mux() {
    return this._mux
  }

  get stream() {
    return this._mux.stream
  }

  async fullyOpened() {
    await this._channel.fullyOpened()
  }

  respond(method, options, handler) {
    if (typeof options === 'function') {
      handler = options
      options = {}
    }

    this._responders.set(method, { options, handler })

    return this
  }

  unrespond(method) {
    this._responders.delete(method)

    return this
  }

  async request(method, value, options = {}) {
    if (this.closed) throw errors.CHANNEL_CLOSED()

    const {
      valueEncoding = this._defaultValueEncoding,
      requestEncoding = valueEncoding,
      timeout = -1
    } = options

    if (requestEncoding) value = c.encode(requestEncoding, value)

    const id = this._id++

    this._request.send({ id, method, value })

    return new Promise((resolve, reject) =>
      this._requests.set(id, {
        options,
        resolve,
        reject,
        timeout: timeout > 0 && setTimeout(this._ontimeout.bind(this, id, timeout), timeout)
      })
    )
  }

  event(method, value, options = {}) {
    if (this.closed) throw errors.CHANNEL_CLOSED()

    const { valueEncoding = this._defaultValueEncoding, requestEncoding = valueEncoding } = options

    if (requestEncoding) value = c.encode(requestEncoding, value)

    this._request.send({ id: 0, method, value })
  }

  cork() {
    this._channel.cork()
  }

  uncork() {
    this._channel.uncork()
  }

  async end() {
    if (this._ending) return this._ending

    this._ending = EventEmitter.once(this, 'close')
    this._endMaybe()

    return this._ending
  }

  _endMaybe() {
    if (this._ending && this._responding === 0 && this._requests.size === 0) {
      this._channel.close()
    }
  }

  destroy(err) {
    if (this._destroyed) return
    this._destroyed = true

    this._error = err || errors.CHANNEL_DESTROYED()
    this._channel.close()
  }
}

const request = {
  preencode(state, m) {
    c.uint.preencode(state, m.id)
    c.string.preencode(state, m.method)
    c.raw.preencode(state, m.value)
  },
  encode(state, m) {
    c.uint.encode(state, m.id)
    c.string.encode(state, m.method)
    c.raw.encode(state, m.value)
  },
  decode(state) {
    return {
      id: c.uint.decode(state),
      method: c.string.decode(state),
      value: c.raw.decode(state)
    }
  }
}

const flags = bitfield(1)

const response = {
  preencode(state, m) {
    flags.preencode(state)

    c.uint.preencode(state, m.id)

    if (m.error) {
      c.string.preencode(state, m.error.message.replace(m.error.code + ': ', ''))

      if (m.error.code) c.string.preencode(state, m.error.code)

      if (m.error.cause) {
        const cause = m.error.cause

        c.string.preencode(state, cause.message)
        c.string.preencode(state, cause.code || '')

        if (cause.context) c.string.preencode(state, cause.context)
      }
    } else {
      c.raw.preencode(state, m.value)
    }
  },
  encode(state, m) {
    flags.encode(
      state,
      bits.of(
        !!m.error,
        !!(m.error && m.error.code),
        !!(m.error && m.error.cause),
        !!(m.error && m.error.cause && m.error.cause.context)
      )
    )

    c.uint.encode(state, m.id)

    if (m.error) {
      c.string.encode(state, m.error.message.replace(m.error.code + ': ', ''))

      if (m.error.code) c.string.encode(state, m.error.code)

      if (m.error.cause) {
        const cause = m.error.cause

        c.string.encode(state, cause.message)
        c.string.encode(state, cause.code || '')

        if (cause.context) c.string.encode(state, cause.context)
      }
    } else {
      c.raw.encode(state, m.value)
    }
  },
  decode(state) {
    const [hasError, hasErrorCode, hasErrorCause, hasErrorContext] = bits.iterator(
      flags.decode(state)
    )

    const id = c.uint.decode(state)

    let error = null
    let value = null

    if (hasError) {
      const message = c.string.decode(state)
      const code = hasErrorCode ? c.string.decode(state) : null

      let cause
      if (hasErrorCause) {
        cause = new Error(c.string.decode(state))

        const code = c.string.decode(state)
        if (code) cause.code = code

        const context = hasErrorContext ? c.string.decode(state) : null
        if (context) cause.context = context
      }

      switch (code) {
        case 'UNKNOWN_METHOD':
          error = errors.UNKNOWN_METHOD(message)
          break
        case 'REQUEST_ERROR':
          error = errors.REQUEST_ERROR(message, cause)
          break
        case 'DECODE_ERROR':
          error = errors.DECODE_ERROR(message, cause)
          break
        case 'ENCODE_ERROR':
          error = errors.ENCODE_ERROR(message, cause)
          break
        default:
          error = new Error(message, { cause })
      }
    } else {
      value = c.raw.decode(state)
    }

    return {
      id,
      error,
      value
    }
  }
}
module.exports = class RPCError extends Error {
  constructor(msg, code, fn = RPCError, { cause } = {}) {
    super(`${code}: ${msg}`, { cause })
    this.code = code

    if (Error.captureStackTrace) Error.captureStackTrace(this, fn)
  }

  get name() {
    return 'RPCError'
  }

  static DUPLICATE_CHANNEL(msg = 'duplicate channel') {
    return new RPCError(msg, 'DUPLICATE_CHANNEL', RPCError.DUPLICATE_CHANNEL)
  }

  static CHANNEL_CLOSED(msg = 'channel closed') {
    return new RPCError(msg, 'CHANNEL_CLOSED', RPCError.CHANNEL_CLOSED)
  }

  static CHANNEL_DESTROYED(msg = 'channel destroyed') {
    return new RPCError(msg, 'CHANNEL_DESTROYED', RPCError.CHANNEL_DESTROYED)
  }

  static REQUEST_ERROR(msg, cause) {
    return new RPCError(msg, 'REQUEST_ERROR', RPCError.REQUEST_ERROR, { cause })
  }

  static TIMEOUT_EXCEEDED(msg) {
    return new RPCError(msg, 'TIMEOUT_EXCEEDED', RPCError.TIMEOUT_EXCEEDED)
  }

  static UNKNOWN_METHOD(msg) {
    return new RPCError(msg, 'UNKNOWN_METHOD', RPCError.UNKNOWN_METHOD)
  }

  static DECODE_ERROR(msg, cause) {
    return new RPCError(msg, 'DECODE_ERROR', RPCError.DECODE_ERROR, { cause })
  }

  static ENCODE_ERROR(msg, cause) {
    return new RPCError(msg, 'ENCODE_ERROR', RPCError.ENCODE_ERROR, { cause })
  }
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "protomux-rpc",
  "version": "1.10.0",
  "description": "RPC over Protomux channels",
  "main": "index.js",
  "files": [
    "index.js",
    "lib"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "exports": {
    "./package": "./package.json",
    ".": "./index.js",
    "./errors": "./lib/errors.js"
  },
  "scripts": {
    "test": "prettier . --check && brittle test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/protomux-rpc.git"
  },
  "author": "Kasper Isager Dalsgarð <kasper@funktionel.co>",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/protomux-rpc/issues"
  },
  "homepage": "https://github.com/holepunchto/protomux-rpc#readme",
  "dependencies": {
    "bits-to-bytes": "^1.0.0",
    "compact-encoding": "^3.0.0",
    "compact-encoding-bitfield": "^1.0.0",
    "protomux": "^3.7.0",
    "safety-catch": "^1.0.2"
  },
  "optionalDependencies": {
    "bare-events": "^2.2.0"
  },
  "devDependencies": {
    "brittle": "^3.3.0",
    "prettier": "^3.7.4",
    "prettier-config-holepunch": "^2.0.0",
    "streamx": "^2.12.4"
  }
}
const crypto = require('hypercore-crypto')
const Protomux = require('protomux')
const b4a = require('b4a')
const schema = require('./spec/hyperschema')

const [NS_INITATOR, NS_RESPONDER] = crypto.namespace('wakeup', 2)

const Handshake = schema.getEncoding('@wakeup/handshake')
const Announce = schema.getEncoding('@wakeup/announce')
const Lookup = schema.getEncoding('@wakeup/lookup')
const Info = schema.getEncoding('@wakeup/info')

module.exports = class WakeupSwarm {
  constructor(onwakeup = noop, { gcTickTime = 2000 } = {}) {
    this.gcTickTime = gcTickTime

    this.topics = new Map()
    this.topicsGC = new Set()
    this.muxers = new Set()
    this.stats = {
      sessionsOpened: 0,
      sessionsClosed: 0,
      topicsAdded: 0,
      topicsGcd: 0,
      peersAdded: 0,
      peersRemoved: 0,
      wireAnnounce: { rx: 0, tx: 0 },
      wireLookup: { rx: 0, tx: 0 },
      wireInfo: { rx: 0, tx: 0 }
    }

    this.onwakeup = onwakeup

    this._gcInterval = null
    this._gcBound = this._gc.bind(this)
  }

  session(capability, handlers = {}) {
    const id = handlers.discoveryKey || crypto.discoveryKey(capability)
    const active = handlers.active !== false
    const hex = b4a.toString(id, 'hex')

    let w = this.topics.get(hex)

    if (w) return w.addSession(handlers)

    w = new WakeupTopic(this, id, capability, active)

    this.topics.set(hex, w)

    for (const muxer of this.muxers) {
      w._onopen(muxer, true)
    }

    return w.addSession(handlers)
  }

  getSessions(capability, handlers = {}) {
    const id = handlers.discoveryKey || crypto.discoveryKey(capability)
    const hex = b4a.toString(id, 'hex')
    const w = this.topics.get(hex)
    return w ? w.sessions : []
  }

  hasStream(stream, capability, handlers = {}) {
    if (!capability) {
      const noiseStream = stream.noiseStream || stream
      return this.muxers.has(getMuxer(noiseStream))
    }

    const id = handlers.discoveryKey || crypto.discoveryKey(capability)
    const hex = b4a.toString(id, 'hex')
    const t = this.topics.get(hex)

    return t ? t.peersByStream.has(stream) : false
  }

  addStream(stream) {
    const noiseStream = stream.noiseStream || stream

    if (!noiseStream.connected) {
      noiseStream.once('open', this.addStream.bind(this, noiseStream))
      return
    }

    const muxer = getMuxer(noiseStream)
    muxer.pair({ protocol: 'wakeup' }, (id) => this._onpair(id, muxer))

    this.muxers.add(muxer)
    noiseStream.on('close', () => this.muxers.delete(muxer))

    for (const w of this.topics.values()) {
      if (!w.isActive) continue
      w._onopen(muxer, true)
    }
  }

  _onActive(w) {
    for (const m of this.muxers) {
      w._onopen(m, false)
    }
  }

  _addGC(topic) {
    if (topic.destroyed) return
    this.topicsGC.add(topic)
    if (this._gcInterval === null) {
      this._gcInterval = setInterval(this._gcBound, this.gcTickTime)
    }
  }

  _removeGC(topic) {
    this.topicsGC.delete(topic)
    if (this.topicsGC.size === 0 && this._gcInterval) {
      clearInterval(this._gcInterval)
      this._gcInterval = null
    }
  }

  _gc() {
    const destroy = []
    for (const w of this.topicsGC) {
      w.idleTicks++
      if (w.idleTicks >= 5) destroy.push(w)
    }
    for (const w of destroy) w.teardown()
  }

  destroy() {
    if (this._gcInterval) clearInterval(this._gcInterval)
    this._gcInterval = null

    for (const w of this.topics.values()) w.teardown()
  }

  async _onpair(id, stream) {
    const hex = b4a.toString(id, 'hex')
    const w = this.topics.get(hex)
    if (!w || !w.sessions.length) return this.onwakeup(id, stream)
    w._onopen(getMuxer(stream), false)
  }

  registerMetrics(promClient) {
    const self = this
    new promClient.Gauge({
      // eslint-disable-line no-new
      name: 'protomux_wakeup_sessions_opened',
      help: 'The amount of sessions opened by protomux wakeup',
      collect() {
        this.set(self.stats.sessionsOpened)
      }
    })

    new promClient.Gauge({
      // eslint-disable-line no-new
      name: 'protomux_wakeup_sessions_closed',
      help: 'The amount of sessions closed by protomux wakeup',
      collect() {
        this.set(self.stats.sessionsClosed)
      }
    })

    new promClient.Gauge({
      // eslint-disable-line no-new
      name: 'protomux_wakeup_topics_added',
      help: 'The amount of topics added to protomux wakeup',
      collect() {
        this.set(self.stats.topicsAdded)
      }
    })

    new promClient.Gauge({
      // eslint-disable-line no-new
      name: 'protomux_wakeup_topics_gcd',
      help: 'The amount of topics that got garbage collected by protomux wakeup',
      collect() {
        this.set(self.stats.topicsGcd)
      }
    })

    new promClient.Gauge({
      // eslint-disable-line no-new
      name: 'protomux_wakeup_peers_added',
      help: 'The amount of peers added by protomux wakeup, across all topics',
      collect() {
        this.set(self.stats.peersAdded)
      }
    })

    new promClient.Gauge({
      // eslint-disable-line no-new
      name: 'protomux_wakeup_peers_removed',
      help: 'The amount of peers removed by protomux wakeup, across all topics',
      collect() {
        this.set(self.stats.peersRemoved)
      }
    })

    new promClient.Gauge({
      // eslint-disable-line no-new
      name: 'protomux_wakeup_wire_announce_rx',
      help: 'The amount of wire announce messages received by protomux wakeup',
      collect() {
        this.set(self.stats.wireAnnounce.rx)
      }
    })
    new promClient.Gauge({
      // eslint-disable-line no-new
      name: 'protomux_wakeup_wire_announce_tx',
      help: 'The amount of wire announce messages transmitted by protomux wakeup',
      collect() {
        this.set(self.stats.wireAnnounce.tx)
      }
    })
    new promClient.Gauge({
      // eslint-disable-line no-new
      name: 'protomux_wakeup_wire_lookup_rx',
      help: 'The amount of wire lookup messages received by protomux wakeup',
      collect() {
        this.set(self.stats.wireLookup.rx)
      }
    })
    new promClient.Gauge({
      // eslint-disable-line no-new
      name: 'protomux_wakeup_wire_lookup_tx',
      help: 'The amount of wire lookup messages transmitted by protomux wakeup',
      collect() {
        this.set(self.stats.wireLookup.tx)
      }
    })
    new promClient.Gauge({
      // eslint-disable-line no-new
      name: 'protomux_wakeup_wire_info_rx',
      help: 'The amount of wire info messages received by protomux wakeup',
      collect() {
        this.set(self.stats.wireInfo.rx)
      }
    })
    new promClient.Gauge({
      // eslint-disable-line no-new
      name: 'protomux_wakeup_wire_info_tx',
      help: 'The amount of wire info messages transmitted by protomux wakeup',
      collect() {
        this.set(self.stats.wireInfo.rx)
      }
    })
  }
}

class WakeupPeer {
  constructor(topic) {
    this.index = 0
    this.userData = null // for the user
    this.clock = 0 // for the user, v useful to reduce traffic
    this.pending = true
    this.removed = false
    this.topic = topic
    this.channel = null
    this.stream = null
    this.wireLookup = null
    this.wireAnnounce = null
    this.wireInfo = null
    this.active = false
  }

  unlink(list) {
    // note that since we pop here we can iterate in reverse safely in case a peer is removed in the same tick
    const head = list.pop()
    if (head === this) return
    head.index = this.index
    list[head.index] = head
  }
}

class WakeupSession {
  constructor(topic, handlers) {
    this.index = 0
    this.topic = topic
    this.handlers = handlers
    this.isActive = handlers.active !== false
    this.destroyed = false
  }

  get peers() {
    return this.topic.peers
  }

  hasStream(stream) {
    return !!this.getPeer(stream)
  }

  addStream(stream) {
    this.topic.addStream(stream)
  }

  getPeer(stream) {
    return this.topic.peersByStream.get(stream) || null
  }

  broadcastLookup(req) {
    for (const peer of this.topic.pendingPeers) {
      this.lookup(peer, req)
    }
    for (const peer of this.topic.peers) {
      this.lookup(peer, req)
    }
  }

  lookupByStream(stream, req) {
    const peer = this.topic.peersByStream.get(stream)
    if (peer) this.lookup(peer, req)
  }

  lookup(peer, req) {
    peer.topic.state.stats.wireLookup.tx++
    peer.wireLookup.send(req || { hash: null })
  }

  announceByStream(stream, wakeup) {
    const peer = this.topic.peersByStream.get(stream)
    if (peer && !peer.pending) this.announce(peer, wakeup)
  }

  announce(peer, wakeup) {
    peer.topic.state.stats.wireAnnounce.tx++
    peer.wireAnnounce.send(wakeup)
  }

  active() {
    this.isActive = true
    this.topic._bumpActivity()
  }

  inactive() {
    this.isActive = false
    this.topic._bumpActivity()
  }

  destroy() {
    if (this.destroyed) return
    this.destroyed = true
    this.topic.removeSession(this)
  }
}

class WakeupTopic {
  constructor(state, id, capability, active) {
    this.state = state
    this.sessions = []
    this.id = id
    this.capability = capability
    this.peers = []
    this.pendingPeers = []
    this.peersByStream = new Map()
    this.activePeers = 0
    this.isActive = active
    this.idleTicks = 0
    this.gcing = false
    this.destroyed = false

    this.state.stats.topicsAdded++
  }

  addSession(handlers) {
    this.state.stats.sessionsOpened++
    const session = new WakeupSession(this, handlers)
    session.index = this.sessions.length
    this.sessions.push(session)
    this._bumpActivity()
    this._checkGC()
    return session
  }

  removeSession(session) {
    if (this.sessions.length <= session.index) return
    if (this.sessions[session.index] !== session) return

    this.state.stats.sessionsClosed++

    // same as with the peer, this allows us to iterate while removing if iterating backwards
    const head = this.sessions.pop()
    if (head !== session) {
      head.index = session.index
      this.sessions[head.index] = head
    }

    this._bumpActivity()
    this._checkGC()
  }

  _bumpActivity() {
    let isActive = false

    for (let i = this.sessions.length - 1; i >= 0; i--) {
      if (this.sessions[i].isActive) {
        isActive = true
        break
      }
    }

    if (isActive) this.active()
    else this.inactive()
  }

  active() {
    if (this.isActive) return
    this.idleTicks = 0
    this.isActive = true
    this._updateActive(true)
  }

  inactive() {
    if (!this.isActive) return
    this.isActive = false
    this._updateActive(false)
  }

  _updateActive(active) {
    const info = { active }

    for (const peer of this.pendingPeers) {
      peer.topic.state.stats.wireInfo.tx++
      peer.wireInfo.send(info)
    }
    for (const peer of this.peers) {
      peer.topic.state.stats.wireInfo.tx++
      peer.wireInfo.send(info)
    }

    this._checkGC()

    if (active) this.state._onActive(this)
  }

  teardown() {
    if (this.destroyed) return
    this.destroyed = true

    this.state.stats.topicsGcd++

    for (let i = this.peers.length - 1; i >= 0; i--) {
      this.peers[i].channel.close()
    }

    for (let i = this.pendingPeers.length - 1; i >= 0; i--) {
      this.pendingPeers[i].channel.close()
    }

    const hex = b4a.toString(this.id, 'hex')

    this.gcing = false
    this.state.topics.delete(hex)
    this.state._removeGC(this)

    for (let i = this.sessions.length - 1; i >= 0; i--) {
      this.state.stats.sessionsClosed++
      const session = this.sessions[i]
      if (session.handlers.ondestroy) session.handlers.ondestroy(session)
    }
  }

  addStream(stream) {
    this._onopen(getMuxer(stream), false)
  }

  _proveCapabilityTo(stream) {
    return this._makeCapability(stream.isInitiator, stream.handshakeHash)
  }

  _makeCapability(isInitiator, handshakeHash) {
    return crypto.hash([isInitiator ? NS_INITATOR : NS_RESPONDER, this.capability, handshakeHash])
  }

  _addPeer(peer, open) {
    if (
      !b4a.equals(
        open.capability,
        this._makeCapability(!peer.stream.isInitiator, peer.stream.handshakeHash)
      )
    ) {
      peer.channel.close()
      return
    }

    if (peer.pending) {
      peer.unlink(this.pendingPeers)
    }

    peer.active = open.active
    peer.pending = false
    peer.index = this.peers.push(peer) - 1

    if (peer.active) {
      this.activePeers++
      this._checkGC()
    }

    for (let i = this.sessions.length - 1; i >= 0; i--) {
      const session = this.sessions[i]
      const handlers = session.handlers

      if (handlers.onpeeradd) handlers.onpeeradd(peer, session)
      if (peer.active && handlers.onpeeractive) handlers.onpeeractive(peer, session)
    }
  }

  _checkGC() {
    const shouldGC = this.activePeers === 0 && this.sessions.length === 0

    if (shouldGC) {
      if (!this.gcing) {
        this.gcing = true
        this.state._addGC(this)
      }
    } else {
      if (this.gcing) {
        this.gcing = false
        this.state._removeGC(this)
      }
    }
  }

  _removePeer(peer) {
    this.state.stats.peersRemoved++
    peer.removed = true
    this.peersByStream.delete(peer.stream)

    if (peer.pending) {
      peer.unlink(this.pendingPeers)
      return
    }

    const active = peer.active

    if (active) {
      peer.active = false
      this.activePeers--
      this._checkGC()
    }

    peer.unlink(this.peers)

    for (let i = this.sessions.length - 1; i >= 0; i--) {
      const session = this.sessions[i]
      const handlers = session.handlers

      if (active && handlers.onpeerinactive) handlers.onpeerinactive(peer, session)
      if (handlers.onpeerremove) handlers.onpeerremove(peer, session)
    }
  }

  _onannounce(wakeup, peer) {
    for (let i = this.sessions.length - 1; i >= 0; i--) {
      const session = this.sessions[i]
      const handlers = session.handlers

      if (handlers.onannounce) handlers.onannounce(wakeup, peer, session)
    }
  }

  _onlookup(req, peer) {
    for (let i = this.sessions.length - 1; i >= 0; i--) {
      const session = this.sessions[i]
      const handlers = session.handlers

      if (handlers.onlookup) handlers.onlookup(req, peer, session)
    }
  }

  _oninfo(info, peer) {
    if (info.active) {
      if (!peer.active) {
        peer.active = true
        this.activePeers++
        this._checkGC()

        for (let i = this.sessions.length - 1; i >= 0; i--) {
          const session = this.sessions[i]
          const handlers = session.handlers

          if (handlers.onpeeractive) handlers.onpeeractive(peer, session)
        }
      }
    } else {
      if (peer.active) {
        peer.active = false
        this.activePeers--
        this._checkGC()

        for (let i = this.sessions.length - 1; i >= 0; i--) {
          const session = this.sessions[i]
          const handlers = session.handlers

          if (handlers.onpeerinactive) handlers.onpeerinactive(peer, session)
        }
      }
    }
  }

  _onopen(muxer, unique) {
    if (!unique && this.peersByStream.has(muxer.stream)) return

    const peer = new WakeupPeer(this)
    const ch = muxer.createChannel({
      userData: peer,
      protocol: 'wakeup',
      id: this.id,
      handshake: Handshake,
      messages: [
        { encoding: Lookup, onmessage: onlookup },
        { encoding: Announce, onmessage: onannounce },
        { encoding: Info, onmessage: onchannelinfo }
      ],
      onopen: onchannelopen,
      onclose: onchannelclose
    })

    if (!ch) return

    this.state.stats.peersAdded++

    peer.channel = ch
    peer.stream = muxer.stream

    peer.wireLookup = ch.messages[0]
    peer.wireAnnounce = ch.messages[1]
    peer.wireInfo = ch.messages[2]

    peer.index = this.pendingPeers.push(peer) - 1
    this.peersByStream.set(muxer.stream, peer)

    ch.open({
      version: 0,
      capability: this._proveCapabilityTo(muxer.stream),
      active: this.isActive
    })
  }
}

function onchannelopen(open, channel) {
  const peer = channel.userData
  peer.topic._addPeer(peer, open)
}

function onchannelclose(close, channel) {
  const peer = channel.userData
  peer.topic._removePeer(peer)
}

function onlookup(req, channel) {
  const peer = channel.userData
  peer.topic.state.stats.wireLookup.rx++
  peer.topic._onlookup(req, peer)
}

function onannounce(wakeup, channel) {
  const peer = channel.userData
  peer.topic.state.stats.wireAnnounce.rx++
  peer.topic._onannounce(wakeup, peer)
}

function onchannelinfo(info, channel) {
  const peer = channel.userData
  peer.topic.state.stats.wireInfo.rx++
  peer.topic._oninfo(info, peer)
}

function getMuxer(stream) {
  if (Protomux.isProtomux(stream)) return stream
  if (stream.noiseStream.userData) return stream.noiseStream.userData
  const mux = Protomux.from(stream.noiseStream)
  stream.noiseStream.userData = mux
  return mux
}

function noop() {}
{
  "name": "protomux-wakeup",
  "version": "2.9.0",
  "description": "Wakeup protocol over protomux",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.6.7",
    "hypercore-crypto": "^3.5.0",
    "hyperschema": "^1.10.4",
    "protomux": "^3.10.1"
  },
  "devDependencies": {
    "@hyperswarm/secret-stream": "^6.8.1",
    "brittle": "^3.17.1",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "prom-client": "^15.1.3"
  },
  "files": [
    "index.js",
    "spec/hyperschema/*.js"
  ],
  "scripts": {
    "format": "prettier --write .",
    "test": "prettier --check . && lunte && brittle test/*.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/protomux-wakeup.git"
  },
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/protomux-wakeup/issues"
  },
  "homepage": "https://github.com/holepunchto/protomux-wakeup"
}
// This file is autogenerated by the hyperschema compiler
// Schema Version: 1
/* eslint-disable camelcase */
/* eslint-disable quotes */

const VERSION = 1
const { c } = require('hyperschema/runtime')

// eslint-disable-next-line no-unused-vars
let version = VERSION

// @wakeup/info
const encoding0 = {
  preencode(state, m) {
    state.end++ // max flag is 1 so always one byte
  },
  encode(state, m) {
    const flags = m.active ? 1 : 0

    c.uint.encode(state, flags)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      active: (flags & 1) !== 0
    }
  }
}

// @wakeup/handshake
const encoding1 = {
  preencode(state, m) {
    c.uint.preencode(state, m.version)
    c.fixed32.preencode(state, m.capability)
    state.end++ // max flag is 1 so always one byte
  },
  encode(state, m) {
    const flags = m.active ? 1 : 0

    c.uint.encode(state, m.version)
    c.fixed32.encode(state, m.capability)
    c.uint.encode(state, flags)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const r1 = c.fixed32.decode(state)
    const flags = c.uint.decode(state)

    return {
      version: r0,
      capability: r1,
      active: (flags & 1) !== 0
    }
  }
}

// @wakeup/writer
const encoding2 = {
  preencode(state, m) {
    c.fixed32.preencode(state, m.key)
    c.uint.preencode(state, m.length)
  },
  encode(state, m) {
    c.fixed32.encode(state, m.key)
    c.uint.encode(state, m.length)
  },
  decode(state) {
    const r0 = c.fixed32.decode(state)
    const r1 = c.uint.decode(state)

    return {
      key: r0,
      length: r1
    }
  }
}

// @wakeup/announce
const encoding3 = c.array(encoding2)

// @wakeup/lookup
const encoding4 = {
  preencode(state, m) {
    state.end++ // max flag is 1 so always one byte

    if (m.hash) c.fixed32.preencode(state, m.hash)
  },
  encode(state, m) {
    const flags = m.hash ? 1 : 0

    c.uint.encode(state, flags)

    if (m.hash) c.fixed32.encode(state, m.hash)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      hash: (flags & 1) !== 0 ? c.fixed32.decode(state) : null
    }
  }
}

function setVersion(v) {
  version = v
}

function encode(name, value, v = VERSION) {
  version = v
  return c.encode(getEncoding(name), value)
}

function decode(name, buffer, v = VERSION) {
  version = v
  return c.decode(getEncoding(name), buffer)
}

function getEnum(name) {
  switch (name) {
    default:
      throw new Error('Enum not found ' + name)
  }
}

function getEncoding(name) {
  switch (name) {
    case '@wakeup/info':
      return encoding0
    case '@wakeup/handshake':
      return encoding1
    case '@wakeup/writer':
      return encoding2
    case '@wakeup/announce':
      return encoding3
    case '@wakeup/lookup':
      return encoding4
    default:
      throw new Error('Encoder not found ' + name)
  }
}

function getStruct(name, v = VERSION) {
  const enc = getEncoding(name)
  return {
    preencode(state, m) {
      version = v
      enc.preencode(state, m)
    },
    encode(state, m) {
      version = v
      enc.encode(state, m)
    },
    decode(state) {
      version = v
      return enc.decode(state)
    }
  }
}

const resolveStruct = getStruct // compat

module.exports = {
  resolveStruct,
  getStruct,
  getEnum,
  getEncoding,
  encode,
  decode,
  setVersion,
  version
}
const b4a = require('b4a')
const c = require('compact-encoding')
const queueTick = require('queue-tick')
const safetyCatch = require('safety-catch')
const unslab = require('unslab')

const MAX_BUFFERED = 32768
const MAX_BACKLOG = Infinity // TODO: impl "open" backpressure
const MAX_BATCH = 8 * 1024 * 1024

class Channel {
  constructor(
    mux,
    info,
    userData,
    protocol,
    aliases,
    id,
    handshake,
    messages,
    onopen,
    onclose,
    ondestroy,
    ondrain
  ) {
    this.userData = userData
    this.protocol = protocol
    this.aliases = aliases
    this.id = id
    this.handshake = null
    this.messages = []

    this.opened = false
    this.closed = false
    this.destroyed = false

    this.onopen = onopen
    this.onclose = onclose
    this.ondestroy = ondestroy
    this.ondrain = ondrain

    this._handshake = handshake
    this._mux = mux
    this._info = info
    this._localId = 0
    this._remoteId = 0
    this._active = 0
    this._extensions = null

    this._decBound = this._dec.bind(this)
    this._decAndDestroyBound = this._decAndDestroy.bind(this)

    this._openedPromise = null
    this._openedResolve = null

    this._destroyedPromise = null
    this._destroyedResolve = null

    for (const m of messages) this.addMessage(m)
  }

  get drained() {
    return this._mux.drained
  }

  fullyOpened() {
    if (this.opened) return Promise.resolve(true)
    if (this.closed) return Promise.resolve(false)
    if (this._openedPromise) return this._openedPromise

    this._openedPromise = new Promise((resolve) => {
      this._openedResolve = resolve
    })
    return this._openedPromise
  }

  fullyClosed() {
    if (this.destroyed) return Promise.resolve()
    if (this._destroyedPromise) return this._destroyedPromise

    this._destroyedPromise = new Promise((resolve) => {
      this._destroyedResolve = resolve
    })
    return this._destroyedPromise
  }

  open(handshake) {
    const id = this._mux._free.length > 0 ? this._mux._free.pop() : this._mux._local.push(null) - 1

    this._info.opened++
    this._info.lastChannel = this
    this._localId = id + 1
    this._mux._local[id] = this

    if (this._remoteId === 0) {
      this._info.outgoing.push(this._localId)
    }

    const state = { buffer: null, start: 2, end: 2 }

    c.uint.preencode(state, this._localId)
    c.string.preencode(state, this.protocol)
    c.optionalBuffer.preencode(state, this.id)
    if (this._handshake) this._handshake.preencode(state, handshake)

    state.buffer = this._mux._alloc(state.end)

    state.buffer[0] = 0
    state.buffer[1] = 1
    c.uint.encode(state, this._localId)
    c.string.encode(state, this.protocol)
    c.optionalBuffer.encode(state, this.id)
    if (this._handshake) this._handshake.encode(state, handshake)

    this._mux._write0(state.buffer)
  }

  _dec() {
    if (--this._active === 0 && this.closed === true) this._destroy()
  }

  _decAndDestroy(err) {
    this._dec()
    this._mux._safeDestroy(err)
  }

  _fullyOpenSoon() {
    this._mux._remote[this._remoteId - 1].session = this
    queueTick(this._fullyOpenOrDestroy.bind(this))
  }

  _fullyOpenOrDestroy() {
    try {
      this._fullyOpen()
    } catch (err) {
      this._mux._safeDestroyBound(err)
    }
  }

  _fullyOpen() {
    if (this.opened === true || this.closed === true) return

    const remote = this._mux._remote[this._remoteId - 1]

    this.handshake = this._handshake ? this._handshake.decode(remote.state) : null
    this._track(this.onopen(this.handshake, this))

    remote.session = this
    remote.state = null
    if (remote.pending !== null) this._drain(remote)
    if (this._mux._destroying === true) return

    this.opened = true
    this._resolveOpen(true)
  }

  _resolveOpen(opened) {
    if (this._openedResolve !== null) {
      this._openedResolve(opened)
      this._openedResolve = this._openedPromise = null
    }
  }

  _resolveDestroyed() {
    if (this._destroyedResolve !== null) {
      this._destroyedResolve()
      this._destroyedResolve = this._destroyedPromise = null
    }
  }

  _drain(remote) {
    for (let i = 0; i < remote.pending.length; i++) {
      const p = remote.pending[i]
      this._mux._buffered -= byteSize(p.state)
      this._recv(p.type, p.state)
      if (this._mux._destroying === true) return
    }

    remote.pending = null
    this._mux._resumeMaybe()
  }

  _track(p) {
    if (isPromise(p) === true) {
      this._active++
      return p.then(this._decBound, this._decAndDestroyBound)
    }

    return null
  }

  _close(isRemote) {
    if (this.closed === true) return
    this.closed = true

    this._info.opened--
    if (this._info.lastChannel === this) this._info.lastChannel = null

    if (this._remoteId > 0) {
      this._mux._remote[this._remoteId - 1] = null
      this._remoteId = 0
      // If remote has acked, we can reuse the local id now
      // otherwise, we need to wait for the "ack" to arrive
      this._mux._free.push(this._localId - 1)
    }

    this._mux._local[this._localId - 1] = null
    this._localId = 0

    this._mux._gc(this._info)
    this._track(this.onclose(isRemote, this))

    if (this._active === 0) this._destroy()

    this._resolveOpen(false)
  }

  _destroy() {
    if (this.destroyed === true) return
    this.destroyed = true
    this._track(this.ondestroy(this))
    this._resolveDestroyed()
  }

  _recv(type, state) {
    if (type < this.messages.length) {
      const m = this.messages[type]
      const p = m.recv(state, this)
      if (m.autoBatch === true) return p
    }
    return null
  }

  cork() {
    this._mux.cork()
  }

  uncork() {
    this._mux.uncork()
  }

  close() {
    if (this.closed === true) return

    const state = { buffer: null, start: 2, end: 2 }

    c.uint.preencode(state, this._localId)

    state.buffer = this._mux._alloc(state.end)

    state.buffer[0] = 0
    state.buffer[1] = 3
    c.uint.encode(state, this._localId)

    this._close(false)
    this._mux._write0(state.buffer)
  }

  addMessage(opts) {
    if (!opts) return this._skipMessage()

    const type = this.messages.length
    const autoBatch = opts.autoBatch !== false
    const encoding = opts.encoding || c.raw
    const onmessage = opts.onmessage || noop

    const s = this
    const typeLen = encodingLength(c.uint, type)

    const m = {
      type,
      autoBatch,
      encoding,
      onmessage,
      recv(state, session) {
        return session._track(m.onmessage(encoding.decode(state), session))
      },
      send(m, session = s) {
        if (session.closed === true) return false

        const mux = session._mux
        const state = { buffer: null, start: 0, end: typeLen }

        if (mux._batch !== null) {
          encoding.preencode(state, m)
          state.buffer = mux._alloc(state.end)

          c.uint.encode(state, type)
          encoding.encode(state, m)

          mux._pushBatch(session._localId, state.buffer)
          return true
        }

        c.uint.preencode(state, session._localId)
        encoding.preencode(state, m)

        state.buffer = mux._alloc(state.end)

        c.uint.encode(state, session._localId)
        c.uint.encode(state, type)
        encoding.encode(state, m)

        mux.drained = mux.stream.write(state.buffer)

        return mux.drained
      }
    }

    this.messages.push(m)

    return m
  }

  _skipMessage() {
    const type = this.messages.length
    const m = {
      type,
      encoding: c.raw,
      onmessage: noop,
      recv(state, session) {},
      send(m, session) {}
    }

    this.messages.push(m)
    return m
  }
}

module.exports = class Protomux {
  constructor(stream, { alloc } = {}) {
    if (stream.userData === null) stream.userData = this

    this.isProtomux = true
    this.stream = stream
    this.corked = 0
    this.drained = true

    this._alloc =
      alloc || (typeof stream.alloc === 'function' ? stream.alloc.bind(stream) : b4a.allocUnsafe)
    this._safeDestroyBound = this._safeDestroy.bind(this)
    this._uncorkBound = this.uncork.bind(this)

    this._remoteBacklog = 0
    this._buffered = 0
    this._paused = false
    this._remote = []
    this._local = []
    this._free = []
    this._batch = null
    this._batchState = null

    this._infos = new Map()
    this._notify = new Map()
    // stream.destroyed flips asynchronously on streamx-based transports.
    this._destroying = false

    this.stream.on('data', this._ondata.bind(this))
    this.stream.on('drain', this._ondrain.bind(this))
    this.stream.on('end', this._onend.bind(this))
    this.stream.on('error', noop) // we handle this in "close"
    this.stream.on('close', this._shutdown.bind(this))
  }

  static from(stream, opts) {
    if (stream.userData && stream.userData.isProtomux) return stream.userData
    if (stream.isProtomux) return stream
    return new this(stream, opts)
  }

  static isProtomux(mux) {
    return typeof mux === 'object' && mux.isProtomux === true
  }

  *[Symbol.iterator]() {
    for (const session of this._local) {
      if (session !== null) yield session
    }
  }

  isIdle() {
    return this._local.length === this._free.length
  }

  cork() {
    if (++this.corked === 1) {
      this._batch = []
      this._batchState = { buffer: null, start: 0, end: 1 }
    }
  }

  uncork() {
    if (--this.corked === 0) {
      this._sendBatch(this._batch, this._batchState)
      this._batch = null
      this._batchState = null
    }
  }

  getLastChannel({ protocol, id = null }) {
    const key = toKey(protocol, id)
    const info = this._infos.get(key)
    if (info) return info.lastChannel
    return null
  }

  pair({ protocol, id = null }, notify) {
    this._notify.set(toKey(protocol, id), notify)
  }

  unpair({ protocol, id = null }) {
    this._notify.delete(toKey(protocol, id))
  }

  opened({ protocol, id = null }) {
    const key = toKey(protocol, id)
    const info = this._infos.get(key)
    return info ? info.opened > 0 : false
  }

  createChannel({
    userData = null,
    protocol,
    aliases = [],
    id = null,
    unique = true,
    handshake = null,
    messages = [],
    onopen = noop,
    onclose = noop,
    ondestroy = noop,
    ondrain = noop
  }) {
    if (this.stream.destroyed) return null

    const info = this._get(protocol, id, aliases)
    if (unique && info.opened > 0) return null

    if (info.incoming.length === 0) {
      return new Channel(
        this,
        info,
        userData,
        protocol,
        aliases,
        id,
        handshake,
        messages,
        onopen,
        onclose,
        ondestroy,
        ondrain
      )
    }

    this._remoteBacklog--

    const remoteId = info.incoming.shift()
    const r = this._remote[remoteId - 1]
    if (r === null) return null

    const session = new Channel(
      this,
      info,
      userData,
      protocol,
      aliases,
      id,
      handshake,
      messages,
      onopen,
      onclose,
      ondestroy,
      ondrain
    )

    session._remoteId = remoteId
    session._fullyOpenSoon()

    return session
  }

  _pushBatch(localId, buffer) {
    if (this._batchState.end >= MAX_BATCH) {
      this._sendBatch(this._batch, this._batchState)
      this._batch = []
      this._batchState = { buffer: null, start: 0, end: 1 }
    }

    if (this._batch.length === 0 || this._batch[this._batch.length - 1].localId !== localId) {
      this._batchState.end++
      c.uint.preencode(this._batchState, localId)
    }
    c.buffer.preencode(this._batchState, buffer)
    this._batch.push({ localId, buffer })
  }

  _sendBatch(batch, state) {
    if (batch.length === 0) return

    let prev = batch[0].localId

    state.buffer = this._alloc(state.end)
    state.buffer[state.start++] = 0
    state.buffer[state.start++] = 0

    c.uint.encode(state, prev)

    for (let i = 0; i < batch.length; i++) {
      const b = batch[i]
      if (prev !== b.localId) {
        state.buffer[state.start++] = 0
        c.uint.encode(state, (prev = b.localId))
      }
      c.buffer.encode(state, b.buffer)
    }

    this.drained = this.stream.write(state.buffer)
  }

  _get(protocol, id, aliases = []) {
    const key = toKey(protocol, id)

    let info = this._infos.get(key)
    if (info) return info

    info = {
      key,
      protocol,
      aliases: [],
      id,
      pairing: 0,
      opened: 0,
      incoming: [],
      outgoing: [],
      lastChannel: null
    }
    this._infos.set(key, info)

    for (const alias of aliases) {
      const key = toKey(alias, id)
      info.aliases.push(key)

      this._infos.set(key, info)
    }

    return info
  }

  _gc(info) {
    if (info.opened === 0 && info.outgoing.length === 0 && info.incoming.length === 0) {
      this._infos.delete(info.key)

      for (const alias of info.aliases) this._infos.delete(alias)
    }
  }

  _ondata(buffer) {
    if (buffer.byteLength === 0) return // ignore empty frames...
    try {
      const state = { buffer, start: 0, end: buffer.byteLength }
      this._decode(c.uint.decode(state), state)
    } catch (err) {
      this._safeDestroy(err)
    }
  }

  _ondrain() {
    this.drained = true

    for (const s of this._local) {
      if (s !== null) s._track(s.ondrain(s))
    }
  }

  _onend() {
    // TODO: support half open mode for the users who wants that here
    this.stream.end()
  }

  _decode(remoteId, state) {
    const type = c.uint.decode(state)

    if (remoteId === 0) {
      return this._oncontrolsession(type, state)
    }

    const r = remoteId <= this._remote.length ? this._remote[remoteId - 1] : null

    // if the channel is closed ignore - could just be a pipeline message...
    if (r === null) return null

    if (r.pending !== null) {
      this._bufferMessage(r, type, state)
      return null
    }

    return r.session._recv(type, state)
  }

  _oncontrolsession(type, state) {
    switch (type) {
      case 0:
        this._onbatch(state)
        break

      case 1:
        // return the promise back up as this has sideeffects so we can batch reply
        return this._onopensession(state)

      case 2:
        this._onrejectsession(state)
        break

      case 3:
        this._onclosesession(state)
        break
    }

    return null
  }

  _bufferMessage(r, type, { buffer, start, end }) {
    const state = { buffer, start, end } // copy
    r.pending.push({ type, state })
    this._buffered += byteSize(state)
    this._pauseMaybe()
  }

  _pauseMaybe() {
    if (this._paused === true || this._buffered <= MAX_BUFFERED) return
    this._paused = true
    this.stream.pause()
  }

  _resumeMaybe() {
    if (this._paused === false || this._buffered > MAX_BUFFERED) return
    this._paused = false
    this.stream.resume()
  }

  _onbatch(state) {
    const end = state.end
    let remoteId = c.uint.decode(state)

    let waiting = null

    while (state.end > state.start) {
      const len = c.uint.decode(state)
      if (len === 0) {
        remoteId = c.uint.decode(state)
        continue
      }
      state.end = state.start + len
      // if batch contains more than one message, cork it so we reply back with a batch
      if (end !== state.end && waiting === null) {
        waiting = []
        this.cork()
      }
      const p = this._decode(remoteId, state)
      if (waiting !== null && p !== null) waiting.push(p)
      state.start = state.end
      state.end = end
    }

    if (waiting !== null) {
      // the waiting promises are not allowed to throw but we destroy the stream in case we are wrong
      Promise.all(waiting).then(this._uncorkBound, this._safeDestroyBound)
    }
  }

  _onopensession(state) {
    const remoteId = c.uint.decode(state)
    const protocol = c.string.decode(state)
    const id = unslab(c.optionalBuffer.decode(state))

    // remote tried to open the control session - auto reject for now
    // as we can use as an explicit control protocol declaration if we need to
    if (remoteId === 0) {
      this._rejectSession(0)
      return null
    }

    const rid = remoteId - 1
    const info = this._get(protocol, id)

    // allow the remote to grow the ids by one
    if (this._remote.length === rid) {
      this._remote.push(null)
    }

    if (rid >= this._remote.length || this._remote[rid] !== null) {
      throw new Error('Invalid open message')
    }

    if (info.outgoing.length > 0) {
      const localId = info.outgoing.shift()
      const session = this._local[localId - 1]

      if (session === null) {
        // we already closed the channel - ignore
        this._free.push(localId - 1)
        return null
      }

      this._remote[rid] = { state, pending: null, session: null }

      session._remoteId = remoteId
      session._fullyOpen()
      return null
    }

    const copyState = { buffer: state.buffer, start: state.start, end: state.end }
    this._remote[rid] = { state: copyState, pending: [], session: null }

    if (++this._remoteBacklog > MAX_BACKLOG) {
      throw new Error('Remote exceeded backlog')
    }

    info.pairing++
    info.incoming.push(remoteId)

    return this._requestSession(protocol, id, info).catch(this._safeDestroyBound)
  }

  _onrejectsession(state) {
    const localId = c.uint.decode(state)

    // TODO: can be done smarter...
    for (const info of this._infos.values()) {
      const i = info.outgoing.indexOf(localId)
      if (i === -1) continue

      info.outgoing.splice(i, 1)

      const session = this._local[localId - 1]

      this._free.push(localId - 1)
      if (session !== null) session._close(true)

      this._gc(info)
      return
    }

    throw new Error('Invalid reject message')
  }

  _onclosesession(state) {
    const remoteId = c.uint.decode(state)

    if (remoteId === 0) return // ignore

    const rid = remoteId - 1
    const r = rid < this._remote.length ? this._remote[rid] : null

    if (r === null) return

    if (r.session !== null) r.session._close(true)
  }

  async _requestSession(protocol, id, info) {
    const notify = this._notify.get(toKey(protocol, id)) || this._notify.get(toKey(protocol, null))

    if (notify) await notify(id)

    if (--info.pairing > 0) return

    while (info.incoming.length > 0) {
      this._rejectSession(info, info.incoming.shift())
    }

    this._gc(info)
  }

  _rejectSession(info, remoteId) {
    if (remoteId > 0) {
      const r = this._remote[remoteId - 1]

      if (r.pending !== null) {
        for (let i = 0; i < r.pending.length; i++) {
          this._buffered -= byteSize(r.pending[i].state)
        }
      }

      this._remote[remoteId - 1] = null
      this._resumeMaybe()
    }

    const state = { buffer: null, start: 2, end: 2 }

    c.uint.preencode(state, remoteId)

    state.buffer = this._alloc(state.end)

    state.buffer[0] = 0
    state.buffer[1] = 2
    c.uint.encode(state, remoteId)

    this._write0(state.buffer)
  }

  _write0(buffer) {
    if (this._batch !== null) {
      this._pushBatch(0, buffer.subarray(1))
      return
    }

    this.drained = this.stream.write(buffer)
  }

  destroy(err) {
    this._destroying = true
    this.stream.destroy(err)
  }

  _safeDestroy(err) {
    safetyCatch(err)
    this._destroying = true
    this.stream.destroy(err)
  }

  _shutdown() {
    this._destroying = true
    for (const s of this._local) {
      if (s !== null) s._close(true)
    }
  }
}

function noop() {}

function toKey(protocol, id) {
  return protocol + '##' + (id ? b4a.toString(id, 'hex') : '')
}

function byteSize(state) {
  return 512 + (state.end - state.start)
}

function isPromise(p) {
  return !!(p && typeof p.then === 'function')
}

function encodingLength(enc, val) {
  const state = { buffer: null, start: 0, end: 0 }
  enc.preencode(state, val)
  return state.end
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return validateSafeUint(
      uint24.decode(state) + 0x1000000 * uint32.decode(state)
    )
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      uint32.decode(state) + 0x100000000 * uint32.decode(state)
    )
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return validateSafeUint(
      0x100000000 * uint32be.decode(state) + uint32be.decode(state)
    )
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateSafeUint(n) {
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'uint is greater than the maximum safe integer, use biguint/bigint'
    )
  return n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.3.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "protomux",
  "version": "3.11.0",
  "description": "Multiplex multiple message oriented protocols over a stream",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.3.1",
    "compact-encoding": "^3.0.0",
    "queue-tick": "^1.0.0",
    "safety-catch": "^1.0.1",
    "unslab": "^1.3.0"
  },
  "devDependencies": {
    "@hyperswarm/secret-stream": "^6.0.0",
    "brittle": "^3.0.0",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/protomux.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/protomux/issues"
  },
  "homepage": "https://github.com/holepunchto/protomux"
}
{
  "name": "queue-tick",
  "version": "1.0.1",
  "description": "Next tick shim that prefers process.nextTick over queueMicrotask for compat",
  "main": "./process-next-tick.js",
  "browser": "./queue-microtask.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^16.0.3",
    "tape": "^5.3.1"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/queue-tick.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/queue-tick/issues"
  },
  "homepage": "https://github.com/mafintosh/queue-tick"
}
module.exports = (typeof process !== 'undefined' && typeof process.nextTick === 'function')
  ? process.nextTick.bind(process)
  : require('./queue-microtask')
module.exports = typeof queueMicrotask === 'function' ? queueMicrotask : (fn) => Promise.resolve().then(fn)
const b4a = require('b4a')

var EMPTY = []

module.exports = RecordCache

function RecordSet () {
  this.list = []
  this.map = new Map()
}

RecordSet.prototype.add = function (record, value) {
  var k = toString(record)
  var r = this.map.get(k)
  if (r) return false

  r = {index: this.list.length, record: value || record}
  this.list.push(r)
  this.map.set(k, r)
  return true
}

RecordSet.prototype.remove = function (record) {
  var k = toString(record)
  var r = this.map.get(k)
  if (!r) return false

  swap(this.list, r.index, this.list.length - 1)
  this.list.pop()
  this.map.delete(k)
  return true
}

function RecordStore () {
  this.records = new Map()
  this.size = 0
}

RecordStore.prototype.add = function (name, record, value) {
  var r = this.records.get(name)

  if (!r) {
    r = new RecordSet()
    this.records.set(name, r)
  }

  if (r.add(record, value)) {
    this.size++
    return true
  }

  return false
}

RecordStore.prototype.remove = function (name, record, value) {
  var r = this.records.get(name)
  if (!r) return false

  if (r.remove(record, value)) {
    this.size--
    if (!r.map.size) this.records.delete(name)
    return true
  }

  return false
}

RecordStore.prototype.get = function (name) {
  var r = this.records.get(name)
  return r ? r.list : EMPTY
}

function RecordCache (opts) {
  if (!(this instanceof RecordCache)) return new RecordCache(opts)
  if (!opts) opts = {}

  this.maxSize = opts.maxSize || Infinity
  this.maxAge = opts.maxAge || 0

  this._onstale = opts.onStale || opts.onstale || null
  this._fresh = new RecordStore()
  this._stale = new RecordStore()
  this._interval = null
  this._gced = false

  if (this.maxAge && this.maxAge < Infinity) {
    // 2/3 gives us a span of 0.66-1.33 maxAge or avg maxAge
    var tick = Math.ceil(2 / 3 * this.maxAge)
    this._interval = setInterval(this._gcAuto.bind(this), tick)
    if (this._interval.unref) this._interval.unref()
  }
}

Object.defineProperty(RecordCache.prototype, 'size', {
  get: function () {
    return this._fresh.size + this._stale.size
  }
})

RecordCache.prototype.add = function (name, record, value) {
  this._stale.remove(name, record, value)
  if (this._fresh.add(name, record, value) && this._fresh.size > this.maxSize) {
    this._gc()
  }
}

RecordCache.prototype.remove = function (name, record, value) {
  this._fresh.remove(name, record, value)
  this._stale.remove(name, record, value)
}

RecordCache.prototype.get = function (name, n) {
  var a = this._fresh.get(name)
  var b = this._stale.get(name)
  var aLen = a.length
  var bLen = b.length
  var len = aLen + bLen

  if (n > len || !n) n = len
  var result = new Array(n)

  for (var i = 0; i < n; i++) {
    var j = Math.floor(Math.random() * (aLen + bLen))
    if (j < aLen) {
      result[i] = a[j].record
      swap(a, j, --aLen)
    } else {
      j -= aLen
      result[i] = b[j].record
      swap(b, j, --bLen)
    }
  }

  return result
}

RecordCache.prototype._gcAuto = function () {
  if (!this._gced) this._gc()
  this._gced = false
}

RecordCache.prototype._gc = function () {
  if (this._onstale && this._stale.size > 0) this._onstale(this._stale)
  this._stale = this._fresh
  this._fresh = new RecordStore()
  this._gced = true
}

RecordCache.prototype.clear = function () {
  this._gc()
  this._gc()
}

RecordCache.prototype.destroy = function () {
  this.clear()
  clearInterval(this._interval)
  this._interval = null
}

function toString (record) {
  return b4a.isBuffer(record) ? b4a.toString(record, 'hex') : record
}

function swap (list, a, b) {
  var tmp = list[a]
  tmp.index = b
  list[b].index = a
  list[a] = list[b]
  list[b] = tmp
}
{
  "name": "record-cache",
  "version": "1.2.0",
  "description": "Cache optimised for record like things",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.3.1"
  },
  "devDependencies": {
    "standard": "^10.0.3",
    "tape": "^4.8.0"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/record-cache.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/record-cache/issues"
  },
  "homepage": "https://github.com/mafintosh/record-cache"
}
module.exports = require.addon.bind(require)
{
  "name": "require-addon",
  "version": "1.2.0",
  "description": "Import native addons across JavaScript runtimes",
  "exports": {
    "./package": "./package.json",
    ".": {
      "bare": "./lib/bare.js",
      "node": "./lib/node.js",
      "default": "./lib/default.js"
    }
  },
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    },
    "url": {
      "bare": "bare-url",
      "default": "url"
    }
  },
  "files": [
    "lib"
  ],
  "scripts": {
    "test": "npm run lint && npm run test:bare && npm run test:node",
    "test:bare": "bare test.js",
    "test:node": "node test.js",
    "lint": "prettier --check .",
    "format": "prettier --write ."
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/require-addon.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/require-addon/issues"
  },
  "homepage": "https://github.com/holepunchto/require-addon#readme",
  "engines": {
    "bare": ">=1.10.0"
  },
  "dependencies": {
    "bare-addon-resolve": "^1.3.0"
  },
  "devDependencies": {
    "bare-bundle": "^1.8.1",
    "bare-bundle-evaluate": "^1.1.0",
    "bare-fs": "^4.0.0",
    "bare-path": "^3.0.0",
    "bare-url": "^2.1.0",
    "brittle": "^3.7.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = safetyCatch

function isActuallyUncaught (err) {
  if (!err) return false
  return err instanceof TypeError ||
    err instanceof SyntaxError ||
    err instanceof ReferenceError ||
    err instanceof EvalError ||
    err instanceof RangeError ||
    err instanceof URIError ||
    err.code === 'ERR_ASSERTION' ||
    err.name === 'AssertionError'
}

function throwErrorNT (err) {
  queueMicrotask(() => { throw err })
}

function safetyCatch (err) {
  if (isActuallyUncaught(err)) {
    throwErrorNT(err)
    throw err
  }
}
{
  "name": "safety-catch",
  "version": "1.0.3",
  "description": "Small module that makes sure your catch, caught an actual error and not a programming mistake or assertion",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {},
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/safety-catch.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/safety-catch/issues"
  },
  "homepage": "https://github.com/mafintosh/safety-catch"
}
const set = require('unordered-set')

module.exports = opts => new ShuffledPriorityQueue(opts)

class ShuffledPriorityQueue {
  constructor (opts) {
    this.priorities = []
    this.equals = (opts && opts.equals) || null
  }

  get length () {
    return this.priorities.reduce(add, 0)
  }

  [Symbol.iterator] () {
    return new Iterator(this)
  }

  head () {
    for (let i = this.priorities.length - 1; i >= 0; i--) {
      const q = this.priorities[i]
      if (q.length) return shuffle(q, 0)
    }
    return null
  }

  tail () {
    for (let i = 0; i < this.priorities.length; i++) {
      const q = this.priorities[i]
      if (q.length) return shuffle(q, 0)
    }
    return null
  }

  prev (prev) {
    if (!prev) return this.tail()
    return next(this.priorities, prev, 1)
  }

  next (prev) {
    if (!prev) return this.head()
    return next(this.priorities, prev, -1)
  }

  shift () {
    return this.remove(this.head())
  }

  pop () {
    return this.remove(this.tail())
  }

  add (val) {
    const prio = val.priority || 0
    while (prio >= this.priorities.length) this.priorities.push([])
    set.add(this.priorities[prio], val)
    return val
  }

  remove (val) {
    if (!val) return null

    if (val._index === undefined) {
      val = this.find(val)
      if (!val) return null
    }

    return set.remove(this.priorities[val.priority || 0], val)
  }

  has (val) {
    if (val._index === undefined) return this.find(val)
    const priority = val.priority || 0
    if (priority >= this.priorities.length) return false
    return set.has(this.priorities[priority], val)
  }

  find (val) {
    if (val._index !== undefined) return val

    const prio = val.priority || 0
    const qs = this.priorities
    if (prio >= qs.length) return null

    const q = qs[prio]

    for (let i = 0; i < q.length; i++) {
      if (this.equals(q[i], val)) return q[i]
    }

    return null
  }
}

class Iterator {
  constructor (queue) {
    this.prev = null
    this.queue = queue
  }

  next () {
    const next = this.queue.next(this.prev)
    this.prev = next
    return { done: !next, value: next }
  }
}

function shuffle (q, i) {
  const ran = i + Math.floor(Math.random() * (q.length - i))
  set.swap(q, q[ran], q[i])
  return q[i]
}

function next (queues, prev, inc) {
  let i = prev.priority || 0
  let j = (prev._index || 0) + 1

  while (true) {
    if (i < 0 || i >= queues.length) return null
    const q = queues[i]

    if (j >= q.length) {
      i += inc
      j = 0
      continue
    }

    return shuffle(q, j)
  }
}

function add (len, b) {
  return len + b.length
}
{
  "name": "shuffled-priority-queue",
  "version": "2.1.0",
  "description": "A priority queue that shuffles elements with the same priority.",
  "main": "index.js",
  "scripts": {
    "test": "standard && tape test.js"
  },
  "dependencies": {
    "unordered-set": "^2.0.1"
  },
  "devDependencies": {
    "standard": "^12.0.1",
    "tape": "^4.9.1"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/shuffled-priority-queue.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/shuffled-priority-queue/issues"
  },
  "homepage": "https://github.com/mafintosh/shuffled-priority-queue"
}
module.exports = class Signal {
  constructor () {
    this._resolve = null
    this._reject = null
    this._promise = null
    this._bind = bind.bind(this)
    this._onerror = clear.bind(this)
    this._onsuccess = clear.bind(this, null)
    this._timers = new Set()
  }

  wait (max) {
    if (!this._promise) {
      this._promise = new Promise(this._bind)
      this._promise.then(this._onsuccess).catch(this._onerror)
    }
    if (max) return this._sleep(max)
    return this._promise
  }

  _sleep (max) {
    const s = new Promise((resolve, reject) => {
      const done = () => {
        this._timers.delete(state)
        resolve(true)
      }
      const id = setTimeout(done, max)
      const state = { id, resolve, reject }
      this._timers.add(state)
    })

    return s
  }

  notify (err) {
    if (!this._promise) return
    const resolve = this._resolve
    const reject = this._reject
    this._promise = null
    if (err) reject(err)
    else resolve(true)
  }
}

function clear (err) {
  for (const { id, resolve, reject } of this._timers) {
    clearTimeout(id)
    if (err) reject(err)
    else resolve(true)
  }
  this._timers.clear()
}

function bind (resolve, reject) {
  this._resolve = resolve
  this._reject = reject
}
{
  "name": "signal-promise",
  "version": "1.0.3",
  "description": "Simple wait/notify promise with optional max wait time",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {},
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/signal-promise.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/signal-promise/issues"
  },
  "homepage": "https://github.com/mafintosh/signal-promise"
}
const sodium = require('sodium-universal')

module.exports = {
  init: sodium.crypto_hash_sha256_init,
  update: sodium.crypto_hash_sha256_update,
  final: sodium.crypto_hash_sha256_final,
  BYTES: sodium.crypto_hash_sha256_BYTES,
  STATEBYTES: sodium.crypto_hash_sha256_STATEBYTES
}
const sodium = require('sodium-universal')

module.exports = {
  init: sodium.crypto_hash_sha512_init,
  update: sodium.crypto_hash_sha512_update,
  final: sodium.crypto_hash_sha512_final,
  BYTES: sodium.crypto_hash_sha512_BYTES,
  STATEBYTES: sodium.crypto_hash_sha512_STATEBYTES
}
const b4a = require('b4a')

const sha256 = require('./hash/sha256')
const sha512 = require('./hash/sha512')

class HMAC {
  constructor (hash, key) {
    this.hash = hash
    this.length = hash.BYTES

    this._blocksize = 2 * hash.BYTES

    this._initialised = false

    this.state = b4a.alloc(hash.STATEBYTES)
    this.pad = b4a.alloc(this._blocksize)

    if (key) this.init(key)
  }

  init (key) {
    if (this._initialised) {
      throw new Error('Already initialised, call final first')
    }

    if (key.length > this._blocksize) {
      this.hash.init(this.state)
      this.hash.update(this.state, key)
      this.hash.final(this.state, this.pad.subarray(0, this.length))
    } else {
      this.pad.set(key)
    }

    bufferByteXor(this.pad, 0x36)

    this.hash.init(this.state)
    this.hash.update(this.state, this.pad)

    bufferByteXor(this.pad, 0x5c ^ 0x36)

    this._initialised = true

    return this
  }

  update (data) {
    if (!this._initialised) {
      throw new Error('First initialise with a key')
    }

    this.hash.update(this.state, data)
    return this
  }

  final (output = b4a.alloc(this.length)) {
    if (!this._initialised) {
      throw new Error('First initialise with a key')
    }

    const out = output.byteLength === this.length
      ? output
      : output.subarray(0, this.hash.BYTES)

    this.hash.final(this.state, out)

    this.hash.init(this.state)
    this.hash.update(this.state, this.pad)
    this.hash.update(this.state, out)
    this.hash.final(this.state, out)

    this.pad.fill(0)
    this.state.fill(0)

    this._initialised = false

    return out
  }

  static sha256 (data, key, output) {
    const hmac = new HMAC(sha256, key)
    return hmac.update(data).final(output)
  }

  static sha512 (data, key, output) {
    const hmac = new HMAC(sha512, key)
    return hmac.update(data).final(output)
  }
}

module.exports = {
  HMAC,
  sha256,
  sha512
}

function bufferByteXor (output, byte) {
  for (let i = 0; i < output.byteLength; i++) {
    output[i] ^= byte
  }

  return output
}
{
  "name": "sodium-hmac",
  "version": "2.1.0",
  "description": "HMAC utility",
  "main": "index.js",
  "scripts": {
    "test": "standard && brittle test/*.js"
  },
  "author": "",
  "license": "Apache-2.0",
  "dependencies": {
    "b4a": "^1.6.6",
    "sodium-universal": "^5.0.1"
  },
  "devDependencies": {
    "brittle": "^3.4.0",
    "standard": "^17.1.0"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sodium-hmac.git"
  },
  "files": [
    "index.js",
    "hash/*"
  ],
  "bugs": {
    "url": "https://github.com/holepunchto/sodium-hmac/issues"
  },
  "homepage": "https://github.com/holepunchto/sodium-hmac#readme"
}
require.addon = require('require-addon')
module.exports = require.addon('.', __filename)
const assert = require('assert')
const binding = require('./binding')
const { isNode } = require('which-runtime')

const OPTIONAL = Buffer.from(new ArrayBuffer(0))

module.exports = exports = { ...binding }

// memory

exports.sodium_memzero = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  binding.sodium_memzero(buf)
}

exports.sodium_mlock = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  const res = binding.sodium_mlock(buf)

  if (res !== 0) throw new Error('memory lock failed')
}

exports.sodium_munlock = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  const res = binding.sodium_munlock(buf)

  if (res !== 0) throw new Error('memory unlock failed')
}

exports.sodium_malloc = function (size) {
  assert(size >= 0, 'invalid size')

  const buf = Buffer.from(binding.sodium_malloc(size))
  buf.secure = true
  return buf
}

exports.sodium_free = function (buf) {
  if (!buf || !buf.secure) return

  binding.sodium_free(buf.buffer)
}

exports.sodium_mprotect_noaccess = function (buf) {
  const res = binding.sodium_mprotect_noaccess(buf.buffer)

  if (res !== 0) throw new Error('failed to lock buffer')
}

exports.sodium_mprotect_readonly = function (buf) {
  const res = binding.sodium_mprotect_readonly(buf.buffer)

  if (res !== 0) throw new Error('failed to unlock buffer')
}

exports.sodium_mprotect_readwrite = function (buf) {
  const res = binding.sodium_mprotect_readwrite(buf.buffer)

  if (res !== 0) throw new Error('failed to unlock buffer')
}

// crypto_randombytes

exports.randombytes_buf = function (buffer) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')

  binding.randombytes_buf(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

exports.randombytes_buf_deterministic = function (buffer, seed) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    seed.byteLength === binding.randombytes_SEEDBYTES,
    "seed must be 'randombytes_SEEDBYTES' bytes"
  )

  binding.randombytes_buf_deterministic(
    buffer.buffer,
    buffer.byteOffset,
    buffer.byteLength,

    seed.buffer,
    seed.byteOffset,
    seed.byteLength
  )
}

// sodium_helpers

exports.sodium_memcmp = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  return binding.sodium_memcmp(a, b)
}

exports.sodium_add = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  binding.sodium_add(a, b)
}

exports.sodium_sub = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  binding.sodium_sub(a, b)
}

exports.sodium_compare = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  return binding.sodium_compare(a, b)
}

exports.sodium_is_zero = function (buffer, length) {
  if (length === undefined) length = buffer.byteLength

  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(length >= 0 && length <= buffer.byteLength, 'invalid length')

  return binding.sodium_is_zero(buffer, length)
}

exports.sodium_pad = function (buffer, unpaddedBuflen, blockSize) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(unpaddedBuflen <= buffer.byteLength, 'unpadded length cannot exceed buffer length')
  assert(blockSize <= buffer.byteLength, 'block size cannot exceed buffer length')
  assert(blockSize >= 1, 'block size must be at least 1 byte')
  assert(
    buffer.byteLength >= unpaddedBuflen + (blockSize - (unpaddedBuflen % blockSize)),
    'buf not long enough'
  )

  return binding.sodium_pad(buffer, unpaddedBuflen, blockSize)
}

exports.sodium_unpad = function (buffer, paddedBuflen, blockSize) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(paddedBuflen <= buffer.byteLength, 'unpadded length cannot exceed buffer length')
  assert(blockSize <= buffer.byteLength, 'block size cannot exceed buffer length')
  assert(blockSize >= 1, 'block size must be at least 1 byte')

  return binding.sodium_unpad(buffer, paddedBuflen, blockSize)
}

// crypto_sign

exports.crypto_sign_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )
  assert(
    seed.byteLength === binding.crypto_sign_SEEDBYTES,
    "seed must be 'crypto_sign_SEEDBYTES' bytes"
  )

  const res = binding.crypto_sign_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign = function (sm, m, sk) {
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sm.byteLength === binding.crypto_sign_BYTES + m.byteLength,
    "sm must be 'm.byteLength + crypto_sign_BYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign(sm, m, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_open = function (m, sm, pk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sm.byteLength >= binding.crypto_sign_BYTES,
    "sm must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    m.byteLength === sm.byteLength - binding.crypto_sign_BYTES,
    "m must be 'sm.byteLength - crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_open(m, sm, pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_open = function (m, sm, pk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sm.byteLength >= binding.crypto_sign_BYTES,
    "sm must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    m.byteLength === sm.byteLength - binding.crypto_sign_BYTES,
    "m must be 'sm.byteLength - crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  return binding.crypto_sign_open(m, sm, pk)
}

exports.crypto_sign_detached = function (sig, m, sk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(sig.byteLength === binding.crypto_sign_BYTES, "sig must be 'crypto_sign_BYTES' bytes")
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_detached(sig, m, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_verify_detached = function (sig, m, pk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sig.byteLength >= binding.crypto_sign_BYTES,
    "sig must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  return binding.crypto_sign_verify_detached(
    sig.buffer,
    sig.byteOffset,
    sig.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    pk.buffer,
    pk.byteOffset,
    pk.byteLength
  )
}

exports.crypto_sign_ed25519_sk_to_pk = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_sk_to_pk(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_ed25519_pk_to_curve25519 = function (x25519pk, ed25519pk) {
  assert(ArrayBuffer.isView(x25519pk), 'x25519pk must be a typed array')
  assert(ArrayBuffer.isView(ed25519pk), 'ed25519pk must be a typed array')
  assert(
    x25519pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "x25519pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    ed25519pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "ed25519pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_pk_to_curve25519(x25519pk, ed25519pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_ed25519_sk_to_curve25519 = function (x25519sk, ed25519sk) {
  assert(ArrayBuffer.isView(x25519sk), 'x25519sk must be a typed array')
  assert(ArrayBuffer.isView(ed25519sk), 'ed25519sk must be a typed array')
  assert(
    x25519sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "x25519sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const edLen = ed25519sk.byteLength

  assert(
    edLen === binding.crypto_sign_SECRETKEYBYTES || edLen === binding.crypto_box_SECRETKEYBYTES,
    "ed25519sk must be 'crypto_sign_SECRETKEYBYTES' or 'crypto_sign_SECRETKEYBYTES - crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_sk_to_curve25519(x25519sk, ed25519sk)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_box

exports.crypto_box_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    seed.byteLength === binding.crypto_box_SEEDBYTES,
    "seed must be 'crypto_box_SEEDBYTES' bytes"
  )

  const res = binding.crypto_box_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_easy = function (c, m, n, pk, sk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength === m.byteLength + exports.crypto_box_MACBYTES,
    "c must be 'm.byteLength + crypto_box_MACBYTES' bytes"
  )
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_easy(c, m, n, pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_detached = function (c, mac, m, n, pk, sk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(mac.byteLength === exports.crypto_box_MACBYTES, "mac must be 'crypto_box_MACBYTES' bytes")
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_detached(c, mac, m, n, pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_open_easy = function (m, c, n, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength >= exports.crypto_box_MACBYTES,
    "c must be at least 'crypto_box_MACBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - exports.crypto_box_MACBYTES,
    "m must be 'c.byteLength - crypto_box_MACBYTES' bytes"
  )
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_open_easy(m, c, n, pk, sk)
}

exports.crypto_box_open_detached = function (m, c, mac, n, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(mac.byteLength === exports.crypto_box_MACBYTES, "mac must be 'crypto_box_MACBYTES' bytes")
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_open_detached(m, c, mac, n, pk, sk)
}

exports.crypto_box_seal = function (c, m, pk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    c.byteLength === m.byteLength + exports.crypto_box_SEALBYTES,
    "c must be 'm.byteLength + crypto_box_SEALBYTES' bytes"
  )
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_box_seal(c, m, pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_seal_open = function (m, c, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength >= exports.crypto_box_SEALBYTES,
    "c must be at least 'crypto_box_SEALBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - exports.crypto_box_SEALBYTES,
    "m must be 'c.byteLength - crypto_box_SEALBYTES' bytes"
  )
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_seal_open(
    m.buffer,
    m.byteOffset,
    m.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    pk.buffer,
    pk.byteOffset,
    pk.byteLength,

    sk.buffer,
    sk.byteOffset,
    sk.byteLength
  )
}

// crypto_secretbox

exports.crypto_secretbox_easy = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_secretbox_MACBYTES,
    "c must be 'm.byteLength + crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretbox_easy(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretbox_open_easy = function (m, c, n, k) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    c.byteLength >= binding.crypto_secretbox_MACBYTES,
    "c must be at least 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - binding.crypto_secretbox_MACBYTES,
    "m must be 'c.byteLength - crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  return binding.crypto_secretbox_open_easy(m, c, n, k)
}

exports.crypto_secretbox_detached = function (c, mac, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    mac.byteLength === binding.crypto_secretbox_MACBYTES,
    "mac must be 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretbox_detached(c, mac, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretbox_open_detached = function (m, c, mac, n, k) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(
    mac.byteLength === binding.crypto_secretbox_MACBYTES,
    "mac must be 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  return binding.crypto_secretbox_open_detached(m, c, mac, n, k)
}

// crypto_generichash

exports.crypto_generichash = function (output, input, key) {
  if (!key) key = OPTIONAL

  assert(ArrayBuffer.isView(output), 'output must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    output.byteLength >= binding.crypto_generichash_BYTES_MIN &&
      output.byteLength <= binding.crypto_generichash_BYTES_MAX,
    'output must be between crypto_generichash_BYTES_MIN and crypto_generichash_BYTES_MAX bytes'
  )

  if (key !== OPTIONAL) {
    assert(ArrayBuffer.isView(key), 'key must be a typed array')
    assert(
      key.byteLength >= binding.crypto_generichash_KEYBYTES_MIN &&
        key.byteLength <= binding.crypto_generichash_KEYBYTES_MAX,
      'key must be between crypto_generichash_KEYBYTES_MIN and crypto_generichash_KEYBYTES_MAX bytes'
    )
  }

  const res = binding.crypto_generichash(
    output.buffer,
    output.byteOffset,
    output.byteLength,

    input.buffer,
    input.byteOffset,
    input.byteLength,

    key.buffer,
    key.byteOffset,
    key.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_batch = function (output, batch, key) {
  assert(ArrayBuffer.isView(output), 'output must be a typed array')

  if (isNode || batch.length < 4) {
    const res = binding.crypto_generichash_batch(output, batch, !!key, key || OPTIONAL)
    if (res !== 0) throw new Error('status: ' + res)
  } else {
    const state = Buffer.alloc(binding.crypto_generichash_STATEBYTES)

    exports.crypto_generichash_init(state, key, output.byteLength)

    for (const buf of batch) {
      exports.crypto_generichash_update(state, buf)
    }

    exports.crypto_generichash_final(state, output)
  }
}

exports.crypto_generichash_keygen = function (key) {
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(
    key.byteLength === binding.crypto_generichash_KEYBYTES,
    "key must be 'crypto_generichash_KEYBYTES' bytes"
  )

  const res = binding.crypto_generichash_keygen(key.buffer, key.byteOffset, key.byteLength)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_init = function (state, key, outputLength) {
  if (!key) key = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_init(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    key.buffer,
    key.byteOffset,
    key.byteLength,

    outputLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_update(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    input.buffer,
    input.byteOffset,
    input.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_final = function (state, output) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(output), 'output must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_final(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    output.buffer,
    output.byteOffset,
    output.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

// secretstream

exports.crypto_secretstream_xchacha20poly1305_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  binding.crypto_secretstream_xchacha20poly1305_keygen(k.buffer, k.byteOffset, k.byteLength)
}

exports.crypto_secretstream_xchacha20poly1305_init_push = function (state, header, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(header), 'header must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    header.byteLength === binding.crypto_secretstream_xchacha20poly1305_HEADERBYTES,
    "header must be 'crypto_secretstream_xchacha20poly1305_HEADERBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_init_push(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    header.buffer,
    header.byteOffset,
    header.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretstream_xchacha20poly1305_init_pull = function (state, header, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(header), 'header must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    header.byteLength === binding.crypto_secretstream_xchacha20poly1305_HEADERBYTES,
    "header must be 'crypto_secretstream_xchacha20poly1305_HEADERBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_init_pull(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    header.buffer,
    header.byteOffset,
    header.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretstream_xchacha20poly1305_push = function (state, c, m, ad, tag) {
  if (!ad) ad = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    c.byteLength === m.byteLength + binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "c must be 'm.byteLength + crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_push(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    ad.buffer,
    ad.byteOffset,
    ad.byteLength,

    tag
  )

  if (res < 0) throw new Error('push failed')

  return res
}

exports.crypto_secretstream_xchacha20poly1305_pull = function (state, m, tag, c, ad) {
  if (!ad) ad = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(tag), 'tag must be a typed array')
  assert(tag.byteLength === 1, 'tag must be 1 byte')

  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    c.byteLength >= binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "c must be at least 'crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "m must be 'c.byteLength - crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_pull(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    tag.buffer,
    tag.byteOffset,
    tag.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    ad.buffer,
    ad.byteOffset,
    ad.byteLength
  )

  if (res < 0) throw new Error('pull failed')

  return res
}

exports.crypto_secretstream_xchacha20poly1305_rekey = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )

  binding.crypto_secretstream_xchacha20poly1305_rekey(
    state.buffer,
    state.byteOffset,
    state.byteLength
  )
}

// crypto_stream

exports.crypto_stream = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xor(
    c.buffer,
    c.byteOffset,
    c.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    n.buffer,
    n.byteOffset,
    n.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_auth

exports.crypto_auth = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(out.byteLength === binding.crypto_auth_BYTES, "out must be 'crypto_auth_BYTES' bytes")
  assert(k.byteLength === binding.crypto_auth_KEYBYTES, "k must be 'crypto_auth_KEYBYTES' bytes")

  const res = binding.crypto_auth(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_auth_verify = function (h, input, k) {
  assert(ArrayBuffer.isView(h), 'h must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(h.byteLength === binding.crypto_auth_BYTES, "h must be 'crypto_auth_BYTES' bytes")
  assert(k.byteLength === binding.crypto_auth_KEYBYTES, "k must be 'crypto_auth_KEYBYTES' bytes")

  return binding.crypto_auth_verify(h, input, k)
}

// crypto_onetimeauth

exports.crypto_onetimeauth = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    out.byteLength === binding.crypto_onetimeauth_BYTES,
    "out must be 'crypto_onetimeauth_BYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_init = function (state, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_init(state, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )
  assert(
    out.byteLength === binding.crypto_onetimeauth_BYTES,
    "out must be 'crypto_onetimeauth_BYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_verify = function (h, input, k) {
  assert(ArrayBuffer.isView(h), 'h must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    h.byteLength === binding.crypto_onetimeauth_BYTES,
    "h must be 'crypto_onetimeauth_BYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  return binding.crypto_onetimeauth_verify(h, input, k)
}

// crypto_pwhash

exports.crypto_pwhash = function (out, passwd, salt, opslimit, memlimit, alg) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_BYTES_MIN,
    "out must be at least 'crypto_pwhash_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_BYTES_MAX,
    "out must be at most 'crypto_pwhash_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_SALTBYTES,
    "salt must be 'crypto_pwhash_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )
  assert(alg >= 1 && alg <= 2, 'alg must be either Argon2i 1.3 or Argon2id 1.3')

  const res = binding.crypto_pwhash(out, passwd, salt, opslimit, memlimit, alg)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_async = function (
  out,
  passwd,
  salt,
  opslimit,
  memlimit,
  alg,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_BYTES_MIN,
    "out must be at least 'crypto_pwhash_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_BYTES_MAX,
    "out must be at most 'crypto_pwhash_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_SALTBYTES,
    "salt must be 'crypto_pwhash_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )
  assert(alg >= 1 && alg <= 2, 'alg must be either Argon2i 1.3 or Argon2id 1.3')

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    opslimit,
    memlimit,
    alg,

    done
  )

  return promise
}

exports.crypto_pwhash_str = function (out, passwd, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_STRBYTES,
    "out must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(typeof opslimit === 'number', 'opslimit must be a number')
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(typeof memlimit === 'number', 'memlimit must be a number')
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_str(out, passwd, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_str_async = function (out, passwd, opslimit, memlimit, callback = undefined) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_STRBYTES,
    "out must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(typeof opslimit === 'number', 'opslimit must be a number')
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(typeof memlimit === 'number', 'memlimit must be a number')
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_str_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_str_verify = function (str, passwd) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )

  return binding.crypto_pwhash_str_verify(str, passwd)
}

exports.crypto_pwhash_str_verify_async = function (str, passwd, callback = undefined) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  const [done, promise] = checkStatus(callback, true)

  binding.crypto_pwhash_str_verify_async(
    str.buffer,
    str.byteOffset,
    str.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    done
  )

  return promise
}

exports.crypto_pwhash_str_needs_rehash = function (str, opslimit, memlimit) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  return binding.crypto_pwhash_str_needs_rehash(str, opslimit, memlimit)
}

exports.crypto_pwhash_scryptsalsa208sha256 = function (out, passwd, salt, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MIN,
    "out must be at least 'crypto_pwhash_scryptsalsa208sha256_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MAX,
    "out must be at most 'crypto_pwhash_scryptsalsa208sha256_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_SALTBYTES,
    "salt must be 'crypto_pwhash_scryptsalsa208sha256_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_scryptsalsa208sha256(out, passwd, salt, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_scryptsalsa208sha256_async = function (
  out,
  passwd,
  salt,
  opslimit,
  memlimit,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MIN,
    "out must be at least 'crypto_pwhash_scryptsalsa208sha256_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MAX,
    "out must be at most 'crypto_pwhash_scryptsalsa208sha256_BYTES_MAX' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    salt.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_SALTBYTES,
    "salt must be 'crypto_pwhash_scryptsalsa208sha256_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_scryptsalsa208sha256_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str_async = function (
  out,
  passwd,
  opslimit,
  memlimit,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "out must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_scryptsalsa208sha256_str_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str = function (out, passwd, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "out must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_scryptsalsa208sha256_str(out, passwd, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_scryptsalsa208sha256_str_verify_async = function (
  str,
  passwd,
  callback = undefined
) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  const [done, promise] = checkStatus(callback, true)

  binding.crypto_pwhash_scryptsalsa208sha256_str_verify_async(
    str.buffer,
    str.byteOffset,
    str.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str_verify = function (str, passwd) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  return binding.crypto_pwhash_scryptsalsa208sha256_str_verify(str, passwd)
}

exports.crypto_pwhash_scryptsalsa208sha256_str_needs_rehash = function (str, opslimit, memlimit) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  return binding.crypto_pwhash_scryptsalsa208sha256_str_needs_rehash(str, opslimit, memlimit)
}

// crypto_kx

exports.crypto_kx_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "pk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "sk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    pk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "pk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "sk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    seed.byteLength === binding.crypto_kx_SEEDBYTES,
    "seed must be 'crypto_kx_SEEDBYTES' bytes"
  )

  const res = binding.crypto_kx_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_client_session_keys = function (rx, tx, clientPk, clientSk, serverPk) {
  if (!rx) rx = undefined
  if (!tx) tx = undefined

  assert(rx || tx, 'at least one session key must be specified')

  if (rx) {
    assert(ArrayBuffer.isView(rx), 'rx must be a typed array')
    assert(
      rx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "rx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  if (tx) {
    assert(ArrayBuffer.isView(tx), 'tx must be a typed array')
    assert(
      tx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "tx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  assert(ArrayBuffer.isView(clientPk), 'clientPk must be a typed array')
  assert(ArrayBuffer.isView(clientSk), 'clientSk must be a typed array')
  assert(ArrayBuffer.isView(serverPk), 'serverPk must be a typed array')
  assert(
    clientPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "clientPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    clientSk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "clientSk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    serverPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "serverPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_client_session_keys(rx, tx, clientPk, clientSk, serverPk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_server_session_keys = function (rx, tx, serverPk, serverSk, clientPk) {
  if (!rx) rx = undefined
  if (!tx) tx = undefined

  assert(rx || tx, 'at least one session key must be specified')

  if (rx) {
    assert(ArrayBuffer.isView(rx), 'rx must be a typed array')
    assert(
      rx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "rx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  if (tx) {
    assert(ArrayBuffer.isView(tx), 'tx must be a typed array')
    assert(
      tx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "tx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  assert(ArrayBuffer.isView(serverPk), 'serverPk must be a typed array')
  assert(ArrayBuffer.isView(serverSk), 'serverSk must be a typed array')
  assert(ArrayBuffer.isView(clientPk), 'clientPk must be a typed array')
  assert(
    serverPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "serverPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    serverSk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "serverSk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    clientPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "clientPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_server_session_keys(rx, tx, serverPk, serverSk, clientPk)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_scalarmult

exports.crypto_scalarmult_base = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_BYTES,
    "q must be 'crypto_scalarmult_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_SCALARBYTES,
    "n must be 'crypto_scalarmult_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_base(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_BYTES,
    "q must be 'crypto_scalarmult_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_SCALARBYTES,
    "n must be 'crypto_scalarmult_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_BYTES,
    "p must be 'crypto_scalarmult_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_base = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_base(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519 = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "p must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_is_valid_point = function (p) {
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )

  return binding.crypto_core_ed25519_is_valid_point(p)
}

exports.crypto_core_ed25519_from_uniform = function (p, r) {
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_UNIFORMBYTES,
    "r must be 'crypto_core_ed25519_UNIFORMBYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_from_uniform(p, r)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_base_noclamp = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_base_noclamp(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_noclamp = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "p must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_noclamp(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_core

exports.crypto_core_ed25519_add = function (r, p, q) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_BYTES,
    "r must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_core_ed25519_BYTES,
    "q must be 'crypto_core_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_add(r, p, q)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_sub = function (r, p, q) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_BYTES,
    "r must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_core_ed25519_BYTES,
    "q must be 'crypto_core_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_sub(r, p, q)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_scalar_random = function (r) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "r must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_random(r)
}

exports.crypto_core_ed25519_scalar_reduce = function (r, s) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "r must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_NONREDUCEDSCALARBYTES,
    "s must be 'crypto_core_ed25519_NONREDUCEDSCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_reduce(r, s)
}

exports.crypto_core_ed25519_scalar_invert = function (recip, s) {
  assert(ArrayBuffer.isView(recip), 'recip must be a typed array')
  assert(
    recip.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "recip must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_invert(recip, s)
}

exports.crypto_core_ed25519_scalar_negate = function (neg, s) {
  assert(ArrayBuffer.isView(neg), 'neg must be a typed array')
  assert(
    neg.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "neg must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_negate(neg, s)
}

exports.crypto_core_ed25519_scalar_complement = function (comp, s) {
  assert(ArrayBuffer.isView(comp), 'comp must be a typed array')
  assert(
    comp.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "comp must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_complement(comp, s)
}

exports.crypto_core_ed25519_scalar_add = function (z, x, y) {
  assert(ArrayBuffer.isView(z), 'z must be a typed array')
  assert(
    z.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "z must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(x), 'x must be a typed array')
  assert(
    x.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "x must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(y), 'y must be a typed array')
  assert(
    y.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "y must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_add(z, x, y)
}

exports.crypto_core_ed25519_scalar_sub = function (z, x, y) {
  assert(ArrayBuffer.isView(z), 'z must be a typed array')
  assert(
    z.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "z must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(x), 'x must be a typed array')
  assert(
    x.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "x must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(y), 'y must be a typed array')
  assert(
    y.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "y must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_sub(z, x, y)
}

// crypto_shorthash

exports.crypto_shorthash = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_shorthash_BYTES,
    "out must be 'crypto_shorthash_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_shorthash_KEYBYTES,
    "k must be 'crypto_shorthash_KEYBYTES' bytes"
  )

  const res = binding.crypto_shorthash(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_kdf

exports.crypto_kdf_keygen = function (key) {
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(key.byteLength === binding.crypto_kdf_KEYBYTES, "key must be 'crypto_kdf_KEYBYTES' bytes")

  binding.crypto_kdf_keygen(key)
}

exports.crypto_kdf_derive_from_key = function (subkey, subkeyId, ctx, key) {
  assert(ArrayBuffer.isView(subkey), 'subkey must be a typed array')
  assert(
    subkey.byteLength >= binding.crypto_kdf_BYTES_MIN,
    "subkey must be at least 'crypto_kdf_BYTES_MIN' bytes"
  )
  assert(
    subkey.byteLength <= binding.crypto_kdf_BYTES_MAX,
    "subkey must be at most 'crypto_kdf_BYTES_MAX' bytes"
  )
  assert(ArrayBuffer.isView(ctx), 'ctx must be a typed array')
  assert(
    ctx.byteLength === binding.crypto_kdf_CONTEXTBYTES,
    "ctx must be 'crypto_kdf_CONTEXTBYTES' bytes"
  )
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(key.byteLength === binding.crypto_kdf_KEYBYTES, "key must be 'crypto_kdf_KEYBYTES' bytes")

  const res = binding.crypto_kdf_derive_from_key(subkey, subkeyId, ctx, key)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_hash

exports.crypto_hash = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(out.byteLength === binding.crypto_hash_BYTES, "out must be 'crypto_hash_BYTES' bytes")

  const res = binding.crypto_hash(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256 = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha256_BYTES,
    "out must be 'crypto_hash_sha256_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha256(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_init = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_init(state)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha256_BYTES,
    "out must be 'crypto_hash_sha256_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512 = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha512_BYTES,
    "out must be 'crypto_hash_sha512_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha512(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_init = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_init(state)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha512_BYTES,
    "out must be 'crypto_hash_sha512_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_aead

exports.crypto_aead_xchacha20poly1305_ietf_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  binding.crypto_aead_xchacha20poly1305_ietf_keygen(k)
}

exports.crypto_aead_xchacha20poly1305_ietf_encrypt = function (c, m, ad, nsec, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "c must be 'm.byteLength + crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(c.byteLength <= 0xffffffff, 'c.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_encrypt(c, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_decrypt = function (m, nsec, c, ad, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "m must be 'c.byteLength - crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(m.byteLength <= 0xffffffff, 'm.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_decrypt(m, c, ad, npub, k)

  if (res < 0) throw new Error('could not verify data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_encrypt_detached = function (
  c,
  mac,
  m,
  ad,
  nsec,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_encrypt_detached(c, mac, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_decrypt_detached = function (
  m,
  nsec,
  c,
  mac,
  ad,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_decrypt_detached(m, c, mac, ad, npub, k)

  if (res !== 0) throw new Error('could not verify data')
}

exports.crypto_aead_chacha20poly1305_ietf_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  binding.crypto_aead_chacha20poly1305_ietf_keygen(k)
}

exports.crypto_aead_chacha20poly1305_ietf_encrypt = function (c, m, ad, nsec, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "c must be 'm.byteLength + crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(c.byteLength <= 0xffffffff, 'c.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_encrypt(c, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_decrypt = function (m, nsec, c, ad, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "m must be 'c.byteLength - crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(m.byteLength <= 0xffffffff, 'm.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_decrypt(m, c, ad, npub, k)

  if (res < 0) throw new Error('could not verify data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_encrypt_detached = function (
  c,
  mac,
  m,
  ad,
  nsec,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_encrypt_detached(c, mac, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_decrypt_detached = function (
  m,
  nsec,
  c,
  mac,
  ad,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_decrypt_detached(m, c, mac, ad, npub, k)

  if (res !== 0) throw new Error('could not verify data')
}

// crypto_stream

exports.crypto_stream_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  binding.crypto_stream_xor_wrap_init(state, n, k)
}

exports.crypto_stream_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_xor_wrap_update(state, c, m)
}

exports.crypto_stream_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_xor_wrap_final(state)
}

exports.crypto_stream_chacha20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  binding.crypto_stream_chacha20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_chacha20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_chacha20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_chacha20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_chacha20_xor_wrap_final(state)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  binding.crypto_stream_chacha20_ietf_xor_wrap_init(state, n, k)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_chacha20_ietf_xor_wrap_update(state, c, m)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_chacha20_ietf_xor_wrap_final(state)
}

exports.crypto_stream_xchacha20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  binding.crypto_stream_xchacha20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_xchacha20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_xchacha20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_xchacha20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_xchacha20_xor_wrap_final(state)
}

exports.crypto_stream_salsa20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  binding.crypto_stream_salsa20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_salsa20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_salsa20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_salsa20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_salsa20_xor_wrap_final(state)
}

// experimental

exports.extension_tweak_ed25519_base = function (n, p, ns) {
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.extension_tweak_ed25519_BYTES,
    "p must be 'extension_tweak_ed25519_BYTES' bytes"
  )

  binding.extension_tweak_ed25519_base(n, p, ns)
}

exports.extension_tweak_ed25519_sign_detached = function (sig, m, scalar, pk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(sig.byteLength === binding.crypto_sign_BYTES, "sig must be 'crypto_sign_BYTES' bytes")
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  if (pk) {
    assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
    assert(
      pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
      "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
    )
  }

  const res = binding.extension_tweak_ed25519_sign_detached(sig, m, scalar, pk)

  if (res !== 0) throw new Error('failed to compute signature')
}

exports.extension_tweak_ed25519_sk_to_scalar = function (n, sk) {
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  binding.extension_tweak_ed25519_sk_to_scalar(n, sk)
}

exports.extension_tweak_ed25519_scalar = function (scalarOut, scalar, ns) {
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_scalar(scalarOut, scalar, ns)
}

exports.extension_tweak_ed25519_pk = function (tpk, pk, ns) {
  assert(ArrayBuffer.isView(tpk), 'tpk must be a typed array')
  assert(
    tpk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "tpk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_pk(tpk, pk, ns)

  if (res !== 0) throw new Error('failed to tweak public key')
}

exports.extension_tweak_ed25519_keypair = function (pk, scalarOut, scalarIn, ns) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.extension_tweak_ed25519_BYTES,
    "pk must be 'extension_tweak_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarIn), 'scalarIn must be a typed array')
  assert(
    scalarIn.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarIn must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_keypair(pk, scalarOut, scalarIn, ns)
}

exports.extension_tweak_ed25519_scalar_add = function (scalarOut, scalar, n) {
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_scalar_add(scalarOut, scalar, n)
}

exports.extension_tweak_ed25519_pk_add = function (tpk, pk, p) {
  assert(ArrayBuffer.isView(tpk), 'tpk must be a typed array')
  assert(
    tpk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "tpk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "p must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_pk_add(tpk, pk, p)

  if (res !== 0) throw new Error('failed to add tweak to public key')
}

exports.extension_tweak_ed25519_keypair_add = function (pk, scalarOut, scalarIn, tweak) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.extension_tweak_ed25519_BYTES,
    "pk must be 'extension_tweak_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarIn), 'scalarIn must be a typed array')
  assert(
    scalarIn.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarIn must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(tweak), 'tweak must be a typed array')
  assert(
    tweak.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "tweak must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_keypair_add(pk, scalarOut, scalarIn, tweak)

  if (res !== 0) throw new Error('failed to add tweak to keypair')
}

exports.extension_pbkdf2_sha512_async = function (out, passwd, salt, iter, outlen, callback) {
  assert(
    iter >= binding.extension_pbkdf2_sha512_ITERATIONS_MIN,
    "iter must be at least 'extension_pbkdf2_sha512_ITERATIONS_MIN'"
  )
  assert(
    outlen <= binding.extension_pbkdf2_sha512_BYTES_MAX,
    "outlen must be at most 'extension_pbkdf2_sha512_BYTES_MAX'"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(out.byteLength >= outlen, "out must be at least 'outlen' bytes")
  assert(out.byteLength > 0, 'out must not be empty')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(salt.byteLength > 0, 'salt must not be empty')

  const [done, promise] = checkStatus(callback)

  binding.extension_pbkdf2_sha512_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    iter,
    outlen,

    done
  )

  return promise
}

exports.extension_pbkdf2_sha512 = function (out, passwd, salt, iter, outlen) {
  assert(
    iter >= binding.extension_pbkdf2_sha512_ITERATIONS_MIN,
    "iter must be at least 'extension_pbkdf2_sha512_ITERATIONS_MIN'"
  )
  assert(
    outlen <= binding.extension_pbkdf2_sha512_BYTES_MAX,
    "outlen must be at most 'extension_pbkdf2_sha512_BYTES_MAX'"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(out.byteLength >= outlen, "out must be at least 'outlen' bytes")
  assert(out.byteLength > 0, 'out must not be empty')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(salt.byteLength > 0, 'salt must not be empty')

  const res = binding.extension_pbkdf2_sha512(out, passwd, salt, iter, outlen)

  if (res !== 0) throw new Error('failed to add tweak to public key')
}

function checkStatus(callback, booleanResult = false) {
  let done, promise

  if (typeof callback === 'function') {
    done = function (status) {
      if (booleanResult) callback(null, status === 0)
      else if (status === 0) callback(null)
      else callback(new Error('status: ' + status))
    }
  } else {
    promise = new Promise(function (resolve, reject) {
      done = function (status) {
        if (booleanResult) resolve(status === 0)
        else if (status === 0) resolve()
        else reject(new Error('status: ' + status))
      }
    })
  }

  return [done, promise]
}
{
  "name": "sodium-native",
  "version": "5.1.0",
  "description": "Low level bindings for libsodium",
  "main": "index.js",
  "files": [
    "index.js",
    "binding.cc",
    "binding.js",
    "extensions",
    "prebuilds",
    "CMakeLists.txt"
  ],
  "imports": {
    "assert": {
      "bare": "bare-assert",
      "node": "assert"
    }
  },
  "addon": true,
  "dependencies": {
    "bare-assert": "^1.2.0",
    "require-addon": "^1.1.0",
    "which-runtime": "^1.2.1"
  },
  "devDependencies": {
    "bare-compat-napi": "^1.3.5",
    "brittle": "^3.16.2",
    "cmake-bare": "^1.6.1",
    "cmake-fetch": "^1.4.3",
    "cmake-napi": "^1.2.1",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "test": "prettier . --check && npm run test:node && npm run test:bare",
    "test:node": "node test/all.js",
    "test:bare": "bare test/all.js"
  },
  "standard": {
    "ignore": [
      "/test/fixtures/*.js"
    ]
  },
  "engines": {
    "bare": ">=1.16.0"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sodium-native.git"
  },
  "contributors": [
    "Emil Bay <github@tixz.dk> (http://bayes.dk)",
    "Mathias Buus <mathiasbuus@gmail.com> (https://mafinto.sh)",
    "Christophe Diederichs <chm-diederichs@hyperdivision.dk>"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/sodium-native/issues"
  },
  "homepage": "https://github.com/holepunchto/sodium-native"
}
const sodium = require('sodium-universal')
const b4a = require('b4a')

const ABYTES = sodium.crypto_secretstream_xchacha20poly1305_ABYTES
const TAG_MESSAGE = sodium.crypto_secretstream_xchacha20poly1305_TAG_MESSAGE
const TAG_FINAL = sodium.crypto_secretstream_xchacha20poly1305_TAG_FINAL
const STATEBYTES = sodium.crypto_secretstream_xchacha20poly1305_STATEBYTES
const HEADERBYTES = sodium.crypto_secretstream_xchacha20poly1305_HEADERBYTES
const KEYBYTES = sodium.crypto_secretstream_xchacha20poly1305_KEYBYTES
const TAG_FINAL_BYTE = b4a.isBuffer(TAG_FINAL) ? TAG_FINAL[0] : TAG_FINAL

const EMPTY = b4a.alloc(0)
const TAG = b4a.alloc(1)

class Push {
  constructor (key, state = b4a.allocUnsafeSlow(STATEBYTES), header = b4a.allocUnsafeSlow(HEADERBYTES)) {
    if (!TAG_FINAL) throw new Error('JavaScript sodium version needs to support crypto_secretstream_xchacha20poly')

    this.key = key
    this.state = state
    this.header = header

    sodium.crypto_secretstream_xchacha20poly1305_init_push(this.state, this.header, this.key)
  }

  next (message, cipher = b4a.allocUnsafe(message.byteLength + ABYTES)) {
    sodium.crypto_secretstream_xchacha20poly1305_push(this.state, cipher, message, null, TAG_MESSAGE)
    return cipher
  }

  final (message = EMPTY, cipher = b4a.allocUnsafe(ABYTES)) {
    sodium.crypto_secretstream_xchacha20poly1305_push(this.state, cipher, message, null, TAG_FINAL)
    return cipher
  }
}

class Pull {
  constructor (key, state = b4a.allocUnsafeSlow(STATEBYTES)) {
    if (!TAG_FINAL) throw new Error('JavaScript sodium version needs to support crypto_secretstream_xchacha20poly')

    this.key = key
    this.state = state
    this.final = false
  }

  init (header) {
    sodium.crypto_secretstream_xchacha20poly1305_init_pull(this.state, header, this.key)
  }

  next (cipher, message = b4a.allocUnsafe(cipher.byteLength - ABYTES)) {
    sodium.crypto_secretstream_xchacha20poly1305_pull(this.state, message, TAG, cipher, null)
    this.final = TAG[0] === TAG_FINAL_BYTE
    return message
  }
}

function keygen (buf = b4a.alloc(KEYBYTES)) {
  sodium.crypto_secretstream_xchacha20poly1305_keygen(buf)
  return buf
}

module.exports = {
  keygen,
  KEYBYTES,
  ABYTES,
  STATEBYTES,
  HEADERBYTES,
  Push,
  Pull
}
{
  "name": "sodium-secretstream",
  "version": "1.2.0",
  "description": "Wraps libsodiums secretstream in a higher level abstraction",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.1.1",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "standard": "^17.0.0"
  },
  "scripts": {
    "test": "standard"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/sodium-secretstream.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/sodium-secretstream/issues"
  },
  "homepage": "https://github.com/mafintosh/sodium-secretstream"
}
module.exports = require('sodium-native')
{
  "name": "sodium-universal",
  "version": "5.0.1",
  "description": "Universal wrapper for sodium-javascript and sodium-native working in Node.js and the Browser",
  "main": "index.js",
  "dependencies": {
    "sodium-native": "^5.0.1"
  },
  "peerDependencies": {
    "sodium-javascript": "~0.8.0"
  },
  "peerDependenciesMeta": {
    "sodium-javascript": {
      "optional": true
    }
  },
  "scripts": {
    "prepublish": "./build-scripts/generate.js"
  },
  "browser": {
    "sodium-native": "sodium-javascript"
  },
  "browserify": {
    "transform": [
      "./build-scripts/transform.js"
    ]
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sodium-universal.git"
  },
  "keywords": [
    "libsodium",
    "sodium",
    "sodium-native",
    "sodium-javascript",
    "browserify"
  ],
  "contributors": [
    "Emil Bay <github@tixz.dk> (http://bayes.dk)",
    "Mathias Buus <mathiasbuus@gmail.com> (https://mafinto.sh)",
    "Christophe Diederichs <chm-diederichs@hyperdivision.dk>"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/sodium-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/sodium-universal#readme"
}
const { EventEmitter } = require('events-universal')
const FIFO = require('fast-fifo')
const TextDecoder = require('text-decoder')

const StreamError = require('./lib/errors.js')

// if we do a future major, expect queue microtask to be there always, for now a bit defensive
const qmt =
  typeof queueMicrotask === 'undefined' ? (fn) => global.process.nextTick(fn) : queueMicrotask

// 29 bits used total (4 from shared, 14 from read, and 11 from write)
const MAX = (1 << 29) - 1

// Shared state
const OPENING = 0b0001
const PREDESTROYING = 0b0010
const DESTROYING = 0b0100
const DESTROYED = 0b1000

const NOT_OPENING = MAX ^ OPENING
const NOT_PREDESTROYING = MAX ^ PREDESTROYING

// Read state (4 bit offset from shared state)
const READ_ACTIVE = 0b00000000000001 << 4
const READ_UPDATING = 0b00000000000010 << 4
const READ_PRIMARY = 0b00000000000100 << 4
const READ_QUEUED = 0b00000000001000 << 4
const READ_RESUMED = 0b00000000010000 << 4
const READ_PIPE_DRAINED = 0b00000000100000 << 4
const READ_ENDING = 0b00000001000000 << 4
const READ_EMIT_DATA = 0b00000010000000 << 4
const READ_EMIT_READABLE = 0b00000100000000 << 4
const READ_EMITTED_READABLE = 0b00001000000000 << 4
const READ_DONE = 0b00010000000000 << 4
const READ_NEXT_TICK = 0b00100000000000 << 4
const READ_NEEDS_PUSH = 0b01000000000000 << 4
const READ_READ_AHEAD = 0b10000000000000 << 4

// Combined read state
const READ_FLOWING = READ_RESUMED | READ_PIPE_DRAINED
const READ_ACTIVE_AND_NEEDS_PUSH = READ_ACTIVE | READ_NEEDS_PUSH
const READ_PRIMARY_AND_ACTIVE = READ_PRIMARY | READ_ACTIVE
const READ_EMIT_READABLE_AND_QUEUED = READ_EMIT_READABLE | READ_QUEUED
const READ_RESUMED_READ_AHEAD = READ_RESUMED | READ_READ_AHEAD

const READ_NOT_ACTIVE = MAX ^ READ_ACTIVE
const READ_NON_PRIMARY = MAX ^ READ_PRIMARY
const READ_NON_PRIMARY_AND_PUSHED = MAX ^ (READ_PRIMARY | READ_NEEDS_PUSH)
const READ_PUSHED = MAX ^ READ_NEEDS_PUSH
const READ_PAUSED = MAX ^ READ_RESUMED
const READ_NOT_QUEUED = MAX ^ (READ_QUEUED | READ_EMITTED_READABLE)
const READ_NOT_ENDING = MAX ^ READ_ENDING
const READ_PIPE_NOT_DRAINED = MAX ^ READ_FLOWING
const READ_NOT_NEXT_TICK = MAX ^ READ_NEXT_TICK
const READ_NOT_UPDATING = MAX ^ READ_UPDATING
const READ_NO_READ_AHEAD = MAX ^ READ_READ_AHEAD
const READ_PAUSED_NO_READ_AHEAD = MAX ^ READ_RESUMED_READ_AHEAD

// Write state (18 bit offset, 4 bit offset from shared state and 14 from read state)
const WRITE_ACTIVE = 0b00000000001 << 18
const WRITE_UPDATING = 0b00000000010 << 18
const WRITE_PRIMARY = 0b00000000100 << 18
const WRITE_QUEUED = 0b00000001000 << 18
const WRITE_UNDRAINED = 0b00000010000 << 18
const WRITE_DONE = 0b00000100000 << 18
const WRITE_EMIT_DRAIN = 0b00001000000 << 18
const WRITE_NEXT_TICK = 0b00010000000 << 18
const WRITE_WRITING = 0b00100000000 << 18
const WRITE_FINISHING = 0b01000000000 << 18
const WRITE_CORKED = 0b10000000000 << 18

const WRITE_NOT_ACTIVE = MAX ^ (WRITE_ACTIVE | WRITE_WRITING)
const WRITE_NON_PRIMARY = MAX ^ WRITE_PRIMARY
const WRITE_NOT_FINISHING = MAX ^ (WRITE_ACTIVE | WRITE_FINISHING)
const WRITE_DRAINED = MAX ^ WRITE_UNDRAINED
const WRITE_NOT_QUEUED = MAX ^ WRITE_QUEUED
const WRITE_NOT_NEXT_TICK = MAX ^ WRITE_NEXT_TICK
const WRITE_NOT_UPDATING = MAX ^ WRITE_UPDATING
const WRITE_NOT_CORKED = MAX ^ WRITE_CORKED

// Combined shared state
const ACTIVE = READ_ACTIVE | WRITE_ACTIVE
const NOT_ACTIVE = MAX ^ ACTIVE
const DONE = READ_DONE | WRITE_DONE
const DESTROY_STATUS = DESTROYING | DESTROYED | PREDESTROYING
const OPEN_STATUS = DESTROY_STATUS | OPENING
const AUTO_DESTROY = DESTROY_STATUS | DONE
const NON_PRIMARY = WRITE_NON_PRIMARY & READ_NON_PRIMARY
const ACTIVE_OR_TICKING = WRITE_NEXT_TICK | READ_NEXT_TICK
const TICKING = ACTIVE_OR_TICKING & NOT_ACTIVE
const IS_OPENING = OPEN_STATUS | TICKING

// Combined shared state and read state
const READ_PRIMARY_STATUS = OPEN_STATUS | READ_ENDING | READ_DONE
const READ_STATUS = OPEN_STATUS | READ_DONE | READ_QUEUED
const READ_ENDING_STATUS = OPEN_STATUS | READ_ENDING | READ_QUEUED
const READ_READABLE_STATUS = OPEN_STATUS | READ_EMIT_READABLE | READ_QUEUED | READ_EMITTED_READABLE
const SHOULD_NOT_READ =
  OPEN_STATUS | READ_ACTIVE | READ_ENDING | READ_DONE | READ_NEEDS_PUSH | READ_READ_AHEAD
const READ_BACKPRESSURE_STATUS = DESTROY_STATUS | READ_ENDING | READ_DONE
const READ_UPDATE_SYNC_STATUS = READ_UPDATING | OPEN_STATUS | READ_NEXT_TICK | READ_PRIMARY
const READ_NEXT_TICK_OR_OPENING = READ_NEXT_TICK | OPENING

// Combined write state
const WRITE_PRIMARY_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_DONE
const WRITE_QUEUED_AND_UNDRAINED = WRITE_QUEUED | WRITE_UNDRAINED
const WRITE_QUEUED_AND_ACTIVE = WRITE_QUEUED | WRITE_ACTIVE
const WRITE_DRAIN_STATUS = WRITE_QUEUED | WRITE_UNDRAINED | OPEN_STATUS | WRITE_ACTIVE
const WRITE_STATUS = OPEN_STATUS | WRITE_ACTIVE | WRITE_QUEUED | WRITE_CORKED
const WRITE_PRIMARY_AND_ACTIVE = WRITE_PRIMARY | WRITE_ACTIVE
const WRITE_ACTIVE_AND_WRITING = WRITE_ACTIVE | WRITE_WRITING
const WRITE_FINISHING_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_QUEUED_AND_ACTIVE | WRITE_DONE
const WRITE_BACKPRESSURE_STATUS = WRITE_UNDRAINED | DESTROY_STATUS | WRITE_FINISHING | WRITE_DONE
const WRITE_UPDATE_SYNC_STATUS = WRITE_UPDATING | OPEN_STATUS | WRITE_NEXT_TICK | WRITE_PRIMARY
const WRITE_DROP_DATA = WRITE_FINISHING | WRITE_DONE | DESTROY_STATUS

const asyncIterator = Symbol.asyncIterator || Symbol('asyncIterator')

class WritableState {
  constructor(
    stream,
    { highWaterMark = 16384, map = null, mapWritable, byteLength, byteLengthWritable } = {}
  ) {
    this.stream = stream
    this.queue = new FIFO()
    this.highWaterMark = highWaterMark
    this.buffered = 0
    this.error = null
    this.pipeline = null
    this.drains = null // if we add more seldomly used helpers we might them into a subobject so its a single ptr
    this.byteLength = byteLengthWritable || byteLength || defaultByteLength
    this.map = mapWritable || map
    this.afterWrite = afterWrite.bind(this)
    this.afterUpdateNextTick = updateWriteNT.bind(this)
  }

  get ending() {
    return (this.stream._duplexState & WRITE_FINISHING) !== 0
  }

  get ended() {
    return (this.stream._duplexState & WRITE_DONE) !== 0
  }

  push(data) {
    if ((this.stream._duplexState & WRITE_DROP_DATA) !== 0) return false
    if (this.map !== null) data = this.map(data)

    this.buffered += this.byteLength(data)
    this.queue.push(data)

    if (this.buffered < this.highWaterMark) {
      this.stream._duplexState |= WRITE_QUEUED
      return true
    }

    this.stream._duplexState |= WRITE_QUEUED_AND_UNDRAINED
    return false
  }

  shift() {
    const data = this.queue.shift()

    this.buffered -= this.byteLength(data)
    if (this.buffered === 0) this.stream._duplexState &= WRITE_NOT_QUEUED

    return data
  }

  end(data) {
    if (typeof data === 'function') {
      this.stream.once('finish', data)
    } else if (data !== undefined && data !== null) {
      this.push(data)
    }

    this.stream._duplexState = (this.stream._duplexState | WRITE_FINISHING) & WRITE_NON_PRIMARY
  }

  autoBatch(data, cb) {
    const buffer = []
    const stream = this.stream

    buffer.push(data)
    while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED_AND_ACTIVE) {
      buffer.push(stream._writableState.shift())
    }

    if ((stream._duplexState & OPEN_STATUS) !== 0) return cb(null)
    stream._writev(buffer, cb)
  }

  update() {
    const stream = this.stream

    stream._duplexState |= WRITE_UPDATING

    do {
      while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED) {
        const data = this.shift()
        stream._duplexState |= WRITE_ACTIVE_AND_WRITING
        stream._write(data, this.afterWrite)
      }

      if ((stream._duplexState & WRITE_PRIMARY_AND_ACTIVE) === 0) this.updateNonPrimary()
    } while (this.continueUpdate() === true)

    stream._duplexState &= WRITE_NOT_UPDATING
  }

  updateNonPrimary() {
    const stream = this.stream

    if ((stream._duplexState & WRITE_FINISHING_STATUS) === WRITE_FINISHING) {
      stream._duplexState = stream._duplexState | WRITE_ACTIVE
      stream._final(afterFinal.bind(this))
      return
    }

    if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
      if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
        stream._duplexState |= ACTIVE
        stream._destroy(afterDestroy.bind(this))
      }
      return
    }

    if ((stream._duplexState & IS_OPENING) === OPENING) {
      stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING
      stream._open(afterOpen.bind(this))
    }
  }

  continueUpdate() {
    if ((this.stream._duplexState & WRITE_NEXT_TICK) === 0) return false
    this.stream._duplexState &= WRITE_NOT_NEXT_TICK
    return true
  }

  updateCallback() {
    if ((this.stream._duplexState & WRITE_UPDATE_SYNC_STATUS) === WRITE_PRIMARY) {
      this.update()
    } else {
      this.updateNextTick()
    }
  }

  updateNextTick() {
    if ((this.stream._duplexState & WRITE_NEXT_TICK) !== 0) return
    this.stream._duplexState |= WRITE_NEXT_TICK
    if ((this.stream._duplexState & WRITE_UPDATING) === 0) qmt(this.afterUpdateNextTick)
  }
}

class ReadableState {
  constructor(
    stream,
    { highWaterMark = 16384, map = null, mapReadable, byteLength, byteLengthReadable } = {}
  ) {
    this.stream = stream
    this.queue = new FIFO()
    this.highWaterMark = highWaterMark === 0 ? 1 : highWaterMark
    this.buffered = 0
    this.readAhead = highWaterMark > 0
    this.error = null
    this.pipeline = null
    this.byteLength = byteLengthReadable || byteLength || defaultByteLength
    this.map = mapReadable || map
    this.pipeTo = null
    this.afterRead = afterRead.bind(this)
    this.afterUpdateNextTick = updateReadNT.bind(this)
  }

  get ending() {
    return (this.stream._duplexState & READ_ENDING) !== 0
  }

  get ended() {
    return (this.stream._duplexState & READ_DONE) !== 0
  }

  pipe(pipeTo, cb) {
    if (this.pipeTo !== null) throw StreamError.BAD_ARGUMENT('Can only pipe to one destination')
    if (typeof cb !== 'function') cb = null

    this.stream._duplexState |= READ_PIPE_DRAINED
    this.pipeTo = pipeTo
    this.pipeline = new Pipeline(this.stream, pipeTo, cb)

    if (cb) this.stream.on('error', noop) // We already error handle this so supress crashes

    if (isStreamx(pipeTo)) {
      pipeTo._writableState.pipeline = this.pipeline
      if (cb) pipeTo.on('error', noop) // We already error handle this so supress crashes
      pipeTo.on('finish', this.pipeline.finished.bind(this.pipeline)) // TODO: just call finished from pipeTo itself
    } else {
      const onerror = this.pipeline.done.bind(this.pipeline, pipeTo)
      const onclose = this.pipeline.done.bind(this.pipeline, pipeTo, null) // onclose has a weird bool arg
      pipeTo.on('error', onerror)
      pipeTo.on('close', onclose)
      pipeTo.on('finish', this.pipeline.finished.bind(this.pipeline))
    }

    pipeTo.on('drain', afterDrain.bind(this))
    this.stream.emit('piping', pipeTo)
    pipeTo.emit('pipe', this.stream)
  }

  push(data) {
    const stream = this.stream

    if (data === null) {
      this.highWaterMark = 0
      stream._duplexState = (stream._duplexState | READ_ENDING) & READ_NON_PRIMARY_AND_PUSHED
      return false
    }

    if (this.map !== null) {
      data = this.map(data)
      if (data === null) {
        stream._duplexState &= READ_PUSHED
        return this.buffered < this.highWaterMark
      }
    }

    this.buffered += this.byteLength(data)
    this.queue.push(data)

    stream._duplexState = (stream._duplexState | READ_QUEUED) & READ_PUSHED

    return this.buffered < this.highWaterMark
  }

  shift() {
    const data = this.queue.shift()

    this.buffered -= this.byteLength(data)
    if (this.buffered === 0) {
      this.stream._duplexState &= READ_NOT_QUEUED
    }

    return data
  }

  unshift(data) {
    const pending = [this.map !== null ? this.map(data) : data]
    while (this.buffered > 0) pending.push(this.shift())

    for (let i = 0; i < pending.length - 1; i++) {
      const data = pending[i]
      this.buffered += this.byteLength(data)
      this.queue.push(data)
    }

    this.push(pending[pending.length - 1])
  }

  read() {
    const stream = this.stream

    if ((stream._duplexState & READ_STATUS) === READ_QUEUED) {
      const data = this.shift()

      if (this.pipeTo !== null && this.pipeTo.write(data) === false) {
        stream._duplexState &= READ_PIPE_NOT_DRAINED
      }

      if ((stream._duplexState & READ_EMIT_DATA) !== 0) {
        stream.emit('data', data)
      }

      return data
    }

    if (this.readAhead === false) {
      stream._duplexState |= READ_READ_AHEAD
      this.updateNextTick()
    }

    return null
  }

  drain() {
    const stream = this.stream

    while (
      (stream._duplexState & READ_STATUS) === READ_QUEUED &&
      (stream._duplexState & READ_FLOWING) !== 0
    ) {
      const data = this.shift()

      if (this.pipeTo !== null && this.pipeTo.write(data) === false) {
        stream._duplexState &= READ_PIPE_NOT_DRAINED
      }

      if ((stream._duplexState & READ_EMIT_DATA) !== 0) {
        stream.emit('data', data)
      }
    }
  }

  update() {
    const stream = this.stream

    stream._duplexState |= READ_UPDATING

    do {
      this.drain()

      while (
        this.buffered < this.highWaterMark &&
        (stream._duplexState & SHOULD_NOT_READ) === READ_READ_AHEAD
      ) {
        stream._duplexState |= READ_ACTIVE_AND_NEEDS_PUSH
        stream._read(this.afterRead)
        this.drain()
      }

      if ((stream._duplexState & READ_READABLE_STATUS) === READ_EMIT_READABLE_AND_QUEUED) {
        stream._duplexState |= READ_EMITTED_READABLE
        stream.emit('readable')
      }

      if ((stream._duplexState & READ_PRIMARY_AND_ACTIVE) === 0) {
        this.updateNonPrimary()
      }
    } while (this.continueUpdate() === true)

    stream._duplexState &= READ_NOT_UPDATING
  }

  updateNonPrimary() {
    const stream = this.stream

    if ((stream._duplexState & READ_ENDING_STATUS) === READ_ENDING) {
      stream._duplexState = (stream._duplexState | READ_DONE) & READ_NOT_ENDING
      stream.emit('end')

      if ((stream._duplexState & AUTO_DESTROY) === DONE) {
        stream._duplexState |= DESTROYING
      }

      if (this.pipeTo !== null) {
        this.pipeTo.end()
      }
    }

    if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
      if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
        stream._duplexState |= ACTIVE
        stream._destroy(afterDestroy.bind(this))
      }
      return
    }

    if ((stream._duplexState & IS_OPENING) === OPENING) {
      stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING
      stream._open(afterOpen.bind(this))
    }
  }

  continueUpdate() {
    if ((this.stream._duplexState & READ_NEXT_TICK) === 0) return false
    this.stream._duplexState &= READ_NOT_NEXT_TICK
    return true
  }

  updateCallback() {
    if ((this.stream._duplexState & READ_UPDATE_SYNC_STATUS) === READ_PRIMARY) {
      this.update()
    } else {
      this.updateNextTick()
    }
  }

  updateNextTickIfOpen() {
    if ((this.stream._duplexState & READ_NEXT_TICK_OR_OPENING) !== 0) return
    this.stream._duplexState |= READ_NEXT_TICK
    if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick)
  }

  updateNextTick() {
    if ((this.stream._duplexState & READ_NEXT_TICK) !== 0) return
    this.stream._duplexState |= READ_NEXT_TICK
    if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick)
  }
}

class TransformState {
  constructor(stream) {
    this.data = null
    this.afterTransform = afterTransform.bind(stream)
    this.afterFinal = null
  }
}

class Pipeline {
  constructor(src, dst, cb) {
    this.from = src
    this.to = dst
    this.afterPipe = cb
    this.error = null
    this.pipeToFinished = false
  }

  finished() {
    this.pipeToFinished = true
  }

  done(stream, err) {
    if (err) this.error = err

    if (stream === this.to) {
      this.to = null

      if (this.from !== null) {
        if ((this.from._duplexState & READ_DONE) === 0 || !this.pipeToFinished) {
          this.from.destroy(this.error || StreamError.PREMATURE_CLOSE('Writable stream closed'))
        }
        return
      }
    }

    if (stream === this.from) {
      this.from = null

      if (this.to !== null) {
        if ((stream._duplexState & READ_DONE) === 0) {
          this.to.destroy(this.error || StreamError.PREMATURE_CLOSE('Readable stream closed'))
        }
        return
      }
    }

    if (this.afterPipe !== null) this.afterPipe(this.error)
    this.to = this.from = this.afterPipe = null
  }
}

function afterDrain() {
  this.stream._duplexState |= READ_PIPE_DRAINED
  this.updateCallback()
}

function afterFinal(err) {
  const stream = this.stream
  if (err) stream.destroy(err)

  if ((stream._duplexState & DESTROY_STATUS) === 0) {
    stream._duplexState |= WRITE_DONE
    stream.emit('finish')
  }

  if ((stream._duplexState & AUTO_DESTROY) === DONE) {
    stream._duplexState |= DESTROYING
  }

  stream._duplexState &= WRITE_NOT_FINISHING

  // no need to wait the extra tick here, so we short circuit that
  if ((stream._duplexState & WRITE_UPDATING) === 0) {
    this.update()
  } else {
    this.updateNextTick()
  }
}

function afterDestroy(err) {
  const stream = this.stream

  if (!err && !StreamError.isStreamDestroyed(this.error)) err = this.error
  if (err) stream.emit('error', err)

  stream._duplexState |= DESTROYED
  stream.emit('close')

  const rs = stream._readableState
  const ws = stream._writableState

  if (rs !== null && rs.pipeline !== null) {
    rs.pipeline.done(stream, err)
  }

  if (ws !== null) {
    while (ws.drains !== null && ws.drains.length > 0) {
      ws.drains.shift().resolve(false)
    }

    if (ws.pipeline !== null) {
      ws.pipeline.done(stream, err)
    }
  }
}

function afterWrite(err) {
  const stream = this.stream

  if (err) stream.destroy(err)
  stream._duplexState &= WRITE_NOT_ACTIVE

  if (this.drains !== null) tickDrains(this.drains)

  if ((stream._duplexState & WRITE_DRAIN_STATUS) === WRITE_UNDRAINED) {
    stream._duplexState &= WRITE_DRAINED

    if ((stream._duplexState & WRITE_EMIT_DRAIN) === WRITE_EMIT_DRAIN) {
      stream.emit('drain')
    }
  }

  this.updateCallback()
}

function afterRead(err) {
  if (err) this.stream.destroy(err)
  this.stream._duplexState &= READ_NOT_ACTIVE

  if (this.readAhead === false && (this.stream._duplexState & READ_RESUMED) === 0) {
    this.stream._duplexState &= READ_NO_READ_AHEAD
  }

  this.updateCallback()
}

function updateReadNT() {
  if ((this.stream._duplexState & READ_UPDATING) === 0) {
    this.stream._duplexState &= READ_NOT_NEXT_TICK
    this.update()
  }
}

function updateWriteNT() {
  if ((this.stream._duplexState & WRITE_UPDATING) === 0) {
    this.stream._duplexState &= WRITE_NOT_NEXT_TICK
    this.update()
  }
}

function tickDrains(drains) {
  for (let i = 0; i < drains.length; i++) {
    // drains.writes are monotonic, so if one is 0 its always the first one
    if (--drains[i].writes === 0) {
      drains.shift().resolve(true)
      i--
    }
  }
}

function afterOpen(err) {
  const stream = this.stream

  if (err) stream.destroy(err)

  if ((stream._duplexState & DESTROYING) === 0) {
    if ((stream._duplexState & READ_PRIMARY_STATUS) === 0) {
      stream._duplexState |= READ_PRIMARY
    }

    if ((stream._duplexState & WRITE_PRIMARY_STATUS) === 0) {
      stream._duplexState |= WRITE_PRIMARY
    }

    stream.emit('open')
  }

  stream._duplexState &= NOT_ACTIVE

  if (stream._writableState !== null) {
    stream._writableState.updateCallback()
  }

  if (stream._readableState !== null) {
    stream._readableState.updateCallback()
  }
}

function afterTransform(err, data) {
  if (data !== undefined && data !== null) this.push(data)
  this._writableState.afterWrite(err)
}

function newListener(name) {
  if (this._readableState !== null) {
    if (name === 'data') {
      this._duplexState |= READ_EMIT_DATA | READ_RESUMED_READ_AHEAD
      this._readableState.updateNextTick()
    }
    if (name === 'readable') {
      this._duplexState |= READ_EMIT_READABLE
      this._readableState.updateNextTick()
    }
  }

  if (this._writableState !== null) {
    if (name === 'drain') {
      this._duplexState |= WRITE_EMIT_DRAIN
      this._writableState.updateNextTick()
    }
  }
}

class Stream extends EventEmitter {
  constructor(opts) {
    super()

    this._duplexState = 0
    this._readableState = null
    this._writableState = null

    if (opts) {
      if (opts.open) this._open = opts.open
      if (opts.destroy) this._destroy = opts.destroy
      if (opts.predestroy) this._predestroy = opts.predestroy
      if (opts.signal) opts.signal.addEventListener('abort', abort.bind(this))
    }

    this.on('newListener', newListener)
  }

  _open(cb) {
    cb(null)
  }

  _destroy(cb) {
    cb(null)
  }

  _predestroy() {
    // does nothing
  }

  get readable() {
    return this._readableState !== null ? true : undefined
  }

  get writable() {
    return this._writableState !== null ? true : undefined
  }

  get destroyed() {
    return (this._duplexState & DESTROYED) !== 0
  }

  get destroying() {
    return (this._duplexState & DESTROY_STATUS) !== 0
  }

  destroy(err) {
    if ((this._duplexState & DESTROY_STATUS) === 0) {
      if (!err) err = StreamError.STREAM_DESTROYED()
      this._duplexState = (this._duplexState | DESTROYING) & NON_PRIMARY

      if (this._readableState !== null) {
        this._readableState.highWaterMark = 0
        this._readableState.error = err
      }

      if (this._writableState !== null) {
        this._writableState.highWaterMark = 0
        this._writableState.error = err
      }

      this._duplexState |= PREDESTROYING
      this._predestroy()
      this._duplexState &= NOT_PREDESTROYING

      if (this._readableState !== null) {
        this._readableState.updateNextTick()
      }

      if (this._writableState !== null) {
        this._writableState.updateNextTick()
      }
    }
  }
}

class Readable extends Stream {
  constructor(opts) {
    super(opts)

    this._duplexState |= OPENING | WRITE_DONE | READ_READ_AHEAD
    this._readableState = new ReadableState(this, opts)

    if (opts) {
      if (this._readableState.readAhead === false) this._duplexState &= READ_NO_READ_AHEAD
      if (opts.read) this._read = opts.read
      if (opts.eagerOpen) this._readableState.updateNextTick()
      if (opts.encoding) this.setEncoding(opts.encoding)
    }
  }

  static deferred(fn, opts) {
    const out = new PassThrough(opts)

    fn()
      .then((src) => {
        if (src === null) return out.end()
        if (out.destroying) return
        pipeline(src, out, noop)
      })
      .catch((err) => out.destroy(err))

    return out
  }

  setEncoding(encoding) {
    const dec = new TextDecoder(encoding)
    const map = this._readableState.map || echo
    this._readableState.map = mapOrSkip
    return this

    function mapOrSkip(data) {
      const next = dec.push(data)
      return next === '' && (data.byteLength !== 0 || dec.remaining > 0) ? null : map(next)
    }
  }

  _read(cb) {
    cb(null)
  }

  pipe(dest, cb) {
    this._readableState.updateNextTick()
    this._readableState.pipe(dest, cb)
    return dest
  }

  read() {
    this._readableState.updateNextTick()
    return this._readableState.read()
  }

  push(data) {
    this._readableState.updateNextTickIfOpen()
    return this._readableState.push(data)
  }

  unshift(data) {
    this._readableState.updateNextTickIfOpen()
    return this._readableState.unshift(data)
  }

  resume() {
    this._duplexState |= READ_RESUMED_READ_AHEAD
    this._readableState.updateNextTick()
    return this
  }

  pause() {
    this._duplexState &=
      this._readableState.readAhead === false ? READ_PAUSED_NO_READ_AHEAD : READ_PAUSED
    return this
  }

  static _fromAsyncIterator(ite, opts) {
    let destroy

    const rs = new Readable({
      ...opts,
      read(cb) {
        ite.next().then(push).then(cb.bind(null, null)).catch(cb)
      },
      predestroy() {
        destroy = ite.return()
      },
      destroy(cb) {
        if (!destroy) return cb(null)
        destroy.then(cb.bind(null, null)).catch(cb)
      }
    })

    return rs

    function push(data) {
      if (data.done) rs.push(null)
      else rs.push(data.value)
    }
  }

  static from(data, opts) {
    if (isReadStreamx(data)) return data
    if (data[asyncIterator]) return this._fromAsyncIterator(data[asyncIterator](), opts)
    if (!Array.isArray(data)) data = data === undefined ? [] : [data]

    let i = 0
    return new Readable({
      ...opts,
      read(cb) {
        this.push(i === data.length ? null : data[i++])
        cb(null)
      }
    })
  }

  static isBackpressured(rs) {
    return (
      (rs._duplexState & READ_BACKPRESSURE_STATUS) !== 0 ||
      rs._readableState.buffered >= rs._readableState.highWaterMark
    )
  }

  static isPaused(rs) {
    return (rs._duplexState & READ_RESUMED) === 0
  }

  [asyncIterator]() {
    const stream = this

    let error = null
    let promiseResolve = null
    let promiseReject = null

    this.on('error', (err) => {
      error = err
    })
    this.on('readable', onreadable)
    this.on('close', onclose)

    return {
      [asyncIterator]() {
        return this
      },
      next() {
        return new Promise(function (resolve, reject) {
          promiseResolve = resolve
          promiseReject = reject
          const data = stream.read()
          if (data !== null) ondata(data)
          else if ((stream._duplexState & DESTROYED) !== 0) ondata(null)
        })
      },
      return() {
        return destroy(null)
      },
      throw(err) {
        return destroy(err)
      }
    }

    function onreadable() {
      if (promiseResolve !== null) ondata(stream.read())
    }

    function onclose() {
      if (promiseResolve !== null) ondata(null)
    }

    function ondata(data) {
      if (promiseReject === null) return
      if (error) {
        promiseReject(error)
      } else if (data === null && (stream._duplexState & READ_DONE) === 0) {
        promiseReject(StreamError.STREAM_DESTROYED())
      } else {
        promiseResolve({ value: data, done: data === null })
      }
      promiseReject = promiseResolve = null
    }

    function destroy(err) {
      stream.destroy(err)
      return new Promise((resolve, reject) => {
        if (stream._duplexState & DESTROYED) return resolve({ value: undefined, done: true })
        stream.once('close', function () {
          if (err) reject(err)
          else resolve({ value: undefined, done: true })
        })
      })
    }
  }
}

class Writable extends Stream {
  constructor(opts) {
    super(opts)

    this._duplexState |= OPENING | READ_DONE
    this._writableState = new WritableState(this, opts)

    if (opts) {
      if (opts.writev) this._writev = opts.writev
      if (opts.write) this._write = opts.write
      if (opts.final) this._final = opts.final
      if (opts.eagerOpen) this._writableState.updateNextTick()
    }
  }

  cork() {
    this._duplexState |= WRITE_CORKED
  }

  uncork() {
    this._duplexState &= WRITE_NOT_CORKED
    this._writableState.updateNextTick()
  }

  _writev(batch, cb) {
    cb(null)
  }

  _write(data, cb) {
    this._writableState.autoBatch(data, cb)
  }

  _final(cb) {
    cb(null)
  }

  static isBackpressured(ws) {
    return (ws._duplexState & WRITE_BACKPRESSURE_STATUS) !== 0
  }

  static drained(ws) {
    if (ws.destroyed) return Promise.resolve(false)

    const state = ws._writableState
    const pending = isWritev(ws) ? Math.min(1, state.queue.length) : state.queue.length
    const writes = pending + (ws._duplexState & WRITE_WRITING ? 1 : 0)
    if (writes === 0) return Promise.resolve(true)

    if (state.drains === null) state.drains = []
    return new Promise((resolve) => {
      state.drains.push({ writes, resolve })
    })
  }

  write(data) {
    this._writableState.updateNextTick()
    return this._writableState.push(data)
  }

  end(data) {
    this._writableState.updateNextTick()
    this._writableState.end(data)
    return this
  }
}

class Duplex extends Readable {
  // and Writable
  constructor(opts) {
    super(opts)

    this._duplexState = OPENING | (this._duplexState & READ_READ_AHEAD)
    this._writableState = new WritableState(this, opts)

    if (opts) {
      if (opts.writev) this._writev = opts.writev
      if (opts.write) this._write = opts.write
      if (opts.final) this._final = opts.final
    }
  }

  cork() {
    this._duplexState |= WRITE_CORKED
  }

  uncork() {
    this._duplexState &= WRITE_NOT_CORKED
    this._writableState.updateNextTick()
  }

  _writev(batch, cb) {
    cb(null)
  }

  _write(data, cb) {
    this._writableState.autoBatch(data, cb)
  }

  _final(cb) {
    cb(null)
  }

  write(data) {
    this._writableState.updateNextTick()
    return this._writableState.push(data)
  }

  end(data) {
    this._writableState.updateNextTick()
    this._writableState.end(data)
    return this
  }
}

class Transform extends Duplex {
  constructor(opts) {
    super(opts)
    this._transformState = new TransformState(this)

    if (opts) {
      if (opts.transform) this._transform = opts.transform
      if (opts.flush) this._flush = opts.flush
    }
  }

  _write(data, cb) {
    if (this._readableState.buffered >= this._readableState.highWaterMark) {
      this._transformState.data = data
    } else {
      this._transform(data, this._transformState.afterTransform)
    }
  }

  _read(cb) {
    if (this._transformState.data !== null) {
      const data = this._transformState.data
      this._transformState.data = null
      cb(null)
      this._transform(data, this._transformState.afterTransform)
    } else {
      cb(null)
    }
  }

  destroy(err) {
    super.destroy(err)
    if (this._transformState.data !== null) {
      this._transformState.data = null
      this._transformState.afterTransform()
    }
  }

  _transform(data, cb) {
    cb(null, data)
  }

  _flush(cb) {
    cb(null)
  }

  _final(cb) {
    this._transformState.afterFinal = cb
    this._flush(transformAfterFlush.bind(this))
  }
}

class PassThrough extends Transform {}

function transformAfterFlush(err, data) {
  const cb = this._transformState.afterFinal
  if (err) return cb(err)

  if (data !== null && data !== undefined) this.push(data)
  this.push(null)
  cb(null)
}

function pipelinePromise(...streams) {
  return new Promise((resolve, reject) => {
    return pipeline(...streams, (err) => {
      if (err) return reject(err)
      resolve()
    })
  })
}

function pipeline(stream, ...streams) {
  const all = Array.isArray(stream) ? [...stream, ...streams] : [stream, ...streams]
  const done = all.length && typeof all[all.length - 1] === 'function' ? all.pop() : null

  if (all.length < 2) throw StreamError.BAD_ARGUMENT('Pipeline requires at least 2 streams')

  let src = all[0]
  let dest = null
  let error = null

  for (let i = 1; i < all.length; i++) {
    dest = all[i]

    if (isStreamx(src)) {
      src.pipe(dest, onerror)
    } else {
      errorHandle(src, true, i > 1, onerror)
      src.pipe(dest)
    }

    src = dest
  }

  if (done) {
    let fin = false

    const autoDestroy =
      isStreamx(dest) || !!(dest._writableState && dest._writableState.autoDestroy)

    dest.on('error', (err) => {
      if (error === null) error = err
    })

    dest.on('finish', () => {
      fin = true
      if (!autoDestroy) done(error)
    })

    if (autoDestroy) {
      dest.on('close', () => done(error || (fin ? null : StreamError.PREMATURE_CLOSE())))
    }
  }

  return dest

  function errorHandle(s, rd, wr, onerror) {
    s.on('error', onerror)
    s.on('close', onclose)

    function onclose() {
      if (rd && s._readableState && !s._readableState.ended) {
        return onerror(StreamError.PREMATURE_CLOSE())
      }
      if (wr && s._writableState && !s._writableState.ended) {
        return onerror(StreamError.PREMATURE_CLOSE())
      }
    }
  }

  function onerror(err) {
    if (!err || error) return
    error = err

    for (const s of all) {
      s.destroy(err)
    }
  }
}

function echo(s) {
  return s
}

function isStream(stream) {
  return !!stream._readableState || !!stream._writableState
}

function isStreamx(stream) {
  return typeof stream._duplexState === 'number' && isStream(stream)
}

function isEnding(stream) {
  return !!stream._readableState && stream._readableState.ending
}

function isEnded(stream) {
  return !!stream._readableState && stream._readableState.ended
}

function isFinishing(stream) {
  return !!stream._writableState && stream._writableState.ending
}

function isFinished(stream) {
  return !!stream._writableState && stream._writableState.ended
}

function getStreamError(stream, opts = {}) {
  const err =
    (stream._readableState && stream._readableState.error) ||
    (stream._writableState && stream._writableState.error)

  // avoid implicit errors by default
  return !opts.all && StreamError.isStreamDestroyed(err) ? null : err
}

function isReadStreamx(stream) {
  return isStreamx(stream) && stream.readable
}

function isDisturbed(stream) {
  return (
    (stream._duplexState & OPENING) !== OPENING ||
    (stream._duplexState & DESTROYING) === DESTROYING ||
    (stream._duplexState & ACTIVE_OR_TICKING) !== 0
  )
}

function isTypedArray(data) {
  return typeof data === 'object' && data !== null && typeof data.byteLength === 'number'
}

function defaultByteLength(data) {
  return isTypedArray(data) ? data.byteLength : 1024
}

function noop() {}

function abort() {
  this.destroy(StreamError.ABORTED())
}

function isWritev(s) {
  return s._writev !== Writable.prototype._writev && s._writev !== Duplex.prototype._writev
}

module.exports = {
  pipeline,
  pipelinePromise,
  isStream,
  isStreamx,
  isEnding,
  isEnded,
  isFinishing,
  isFinished,
  isDisturbed,
  getStreamError,
  Stream,
  Writable,
  Readable,
  Duplex,
  Transform,
  // Export PassThrough for compatibility with Node.js core's stream module
  PassThrough
}
module.exports = class StreamError extends Error {
  constructor(msg, code, fn = StreamError) {
    super(msg)

    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  static isStreamDestroyed(err) {
    return err && err.code === 'STREAM_DESTROYED'
  }

  static isPrematureClose(err) {
    return err && err.code === 'PREMATURE_CLOSE'
  }

  static isAborted(err) {
    return err && err.code === 'ABORTED'
  }

  static isBadArgument(err) {
    return err && err.code === 'BAD_ARGUMENT'
  }

  get name() {
    return 'StreamError'
  }

  static STREAM_DESTROYED() {
    return new StreamError('Stream was destroyed', 'STREAM_DESTROYED', StreamError.STREAM_DESTROYED)
  }

  static PREMATURE_CLOSE(msg = 'Premature close') {
    return new StreamError(msg, 'PREMATURE_CLOSE', StreamError.PREMATURE_CLOSE)
  }

  static ABORTED() {
    return new StreamError('Stream aborted', 'ABORTED', StreamError.ABORTED)
  }

  static BAD_ARGUMENT(msg = 'Bad argument') {
    return new StreamError(msg, 'BAD_ARGUMENT', StreamError.BAD_ARGUMENT)
  }
}
{
  "name": "streamx",
  "version": "2.28.0",
  "description": "An iteration of the Node.js core streams with a series of improvements",
  "main": "index.js",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./errors": {
      "types": "./lib/errors.d.ts",
      "default": "./lib/errors"
    }
  },
  "dependencies": {
    "events-universal": "^1.0.0",
    "fast-fifo": "^1.3.2",
    "text-decoder": "^1.1.0"
  },
  "devDependencies": {
    "b4a": "^1.6.6",
    "brittle": "^3.1.1",
    "end-of-stream": "^1.4.4",
    "lunte": "^1.8.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "runtime.d.ts",
    "lib"
  ],
  "scripts": {
    "format": "prettier . --write",
    "test": "brittle test/all.js && brittle-bare test/all.js",
    "lint": "prettier . --check && lunte"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/streamx.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/streamx/issues"
  },
  "homepage": "https://github.com/mafintosh/streamx"
}
const { Readable } = require('streamx')

module.exports = function (s, forks = 2) {
  const streams = new Array(forks)
  const status = new Array(forks).fill(true)

  let ended = false

  for (let i = 0; i < forks; i++) {
    streams[i] = new Readable({
      read (cb) {
        const check = !status[i]
        status[i] = true
        if (check && allReadable()) s.resume()
        cb(null)
      }
    })
  }

  s.on('end', function () {
    ended = true
    for (const stream of streams) stream.push(null)
  })

  s.on('error', function (err) {
    for (const stream of streams) stream.destroy(err)
  })

  s.on('close', function () {
    if (ended) return
    for (const stream of streams) stream.destroy()
  })

  s.on('data', function (data) {
    let needsPause = false
    for (let i = 0; i < streams.length; i++) {
      if (!(status[i] = streams[i].push(data))) {
        needsPause = true
      }
    }
    if (needsPause) s.pause()
  })

  return streams

  function allReadable () {
    for (let j = 0; j < status.length; j++) {
      if (!status[j]) return false
    }
    return true
  }
}
{
  "name": "teex",
  "version": "1.0.1",
  "description": "Turn a readable stream into multiple readable streamx streams",
  "main": "index.js",
  "dependencies": {
    "streamx": "^2.12.5"
  },
  "devDependencies": {
    "standard": "^14.3.4",
    "tape": "^5.0.1"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/teex.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/teex/issues"
  },
  "homepage": "https://github.com/mafintosh/teex"
}
const PassThroughDecoder = require('./lib/pass-through-decoder')
const UTF8Decoder = require('./lib/utf8-decoder')

module.exports = class TextDecoder {
  constructor(encoding = 'utf8') {
    this.encoding = normalizeEncoding(encoding)

    switch (this.encoding) {
      case 'utf8':
        this.decoder = new UTF8Decoder()
        break
      case 'utf16le':
      case 'base64':
        throw new Error('Unsupported encoding: ' + this.encoding)
      default:
        this.decoder = new PassThroughDecoder(this.encoding)
    }
  }

  get remaining() {
    return this.decoder.remaining
  }

  push(data) {
    if (typeof data === 'string') return data
    return this.decoder.decode(data)
  }

  // For Node.js compatibility
  write(data) {
    return this.push(data)
  }

  end(data) {
    let result = ''
    if (data) result = this.push(data)
    result += this.decoder.flush()
    return result
  }
}

function normalizeEncoding(encoding) {
  encoding = encoding.toLowerCase()

  switch (encoding) {
    case 'utf8':
    case 'utf-8':
      return 'utf8'
    case 'ucs2':
    case 'ucs-2':
    case 'utf16le':
    case 'utf-16le':
      return 'utf16le'
    case 'latin1':
    case 'binary':
      return 'latin1'
    case 'base64':
    case 'ascii':
    case 'hex':
      return encoding
    default:
      throw new Error('Unknown encoding: ' + encoding)
  }
}
const b4a = require('b4a')

module.exports = class PassThroughDecoder {
  constructor(encoding) {
    this.encoding = encoding
  }

  get remaining() {
    return 0
  }

  decode(data) {
    return b4a.toString(data, this.encoding)
  }

  flush() {
    return ''
  }
}
const b4a = require('b4a')

/**
 * https://encoding.spec.whatwg.org/#utf-8-decoder
 */
module.exports = class UTF8Decoder {
  constructor() {
    this._reset()
  }

  get remaining() {
    return this.bytesSeen
  }

  decode(data) {
    if (data.byteLength === 0) return ''

    if (this.bytesNeeded === 0 && trailingIncomplete(data, 0) === 0) {
      this.bytesSeen = trailingBytesSeen(data)
      return b4a.toString(data, 'utf8')
    }

    let result = ''
    let start = 0

    if (this.bytesNeeded > 0) {
      while (start < data.byteLength) {
        const byte = data[start]

        if (byte < this.lowerBoundary || byte > this.upperBoundary) {
          result += '\ufffd'
          this._reset()
          break
        }

        this.lowerBoundary = 0x80
        this.upperBoundary = 0xbf
        this.codePoint = (this.codePoint << 6) | (byte & 0x3f)
        this.bytesSeen++
        start++

        if (this.bytesSeen === this.bytesNeeded) {
          result += String.fromCodePoint(this.codePoint)
          this._reset()
          break
        }
      }

      if (this.bytesNeeded > 0) return result
    }

    const trailing = trailingIncomplete(data, start)
    const end = data.byteLength - trailing

    if (end > start) result += b4a.toString(data, 'utf8', start, end)

    for (let i = end; i < data.byteLength; i++) {
      const byte = data[i]

      if (this.bytesNeeded === 0) {
        if (byte <= 0x7f) {
          this.bytesSeen = 0
          result += String.fromCharCode(byte)
        } else if (byte >= 0xc2 && byte <= 0xdf) {
          this.bytesNeeded = 2
          this.bytesSeen = 1
          this.codePoint = byte & 0x1f
        } else if (byte >= 0xe0 && byte <= 0xef) {
          if (byte === 0xe0) this.lowerBoundary = 0xa0
          else if (byte === 0xed) this.upperBoundary = 0x9f
          this.bytesNeeded = 3
          this.bytesSeen = 1
          this.codePoint = byte & 0xf
        } else if (byte >= 0xf0 && byte <= 0xf4) {
          if (byte === 0xf0) this.lowerBoundary = 0x90
          else if (byte === 0xf4) this.upperBoundary = 0x8f
          this.bytesNeeded = 4
          this.bytesSeen = 1
          this.codePoint = byte & 0x7
        } else {
          this.bytesSeen = 1
          result += '\ufffd'
        }

        continue
      }

      if (byte < this.lowerBoundary || byte > this.upperBoundary) {
        result += '\ufffd'
        i--
        this._reset()

        continue
      }

      this.lowerBoundary = 0x80
      this.upperBoundary = 0xbf

      this.codePoint = (this.codePoint << 6) | (byte & 0x3f)
      this.bytesSeen++

      if (this.bytesSeen === this.bytesNeeded) {
        result += String.fromCodePoint(this.codePoint)
        this._reset()
      }
    }

    return result
  }

  flush() {
    const result = this.bytesNeeded > 0 ? '\ufffd' : ''
    this._reset()
    return result
  }

  _reset() {
    this.codePoint = 0
    this.bytesNeeded = 0
    this.bytesSeen = 0
    this.lowerBoundary = 0x80
    this.upperBoundary = 0xbf
  }
}

function trailingIncomplete(data, start) {
  const len = data.byteLength
  if (len <= start) return 0

  const limit = Math.max(start, len - 4)

  let i = len - 1
  while (i > limit && (data[i] & 0xc0) === 0x80) i--

  if (i < start) return 0

  const byte = data[i]

  let needed
  if (byte <= 0x7f) return 0
  if (byte >= 0xc2 && byte <= 0xdf) needed = 2
  else if (byte >= 0xe0 && byte <= 0xef) needed = 3
  else if (byte >= 0xf0 && byte <= 0xf4) needed = 4
  else return 0

  const available = len - i
  return available < needed ? available : 0
}

function trailingBytesSeen(data) {
  const len = data.byteLength
  if (len === 0) return 0

  const last = data[len - 1]

  if (last <= 0x7f) return 0
  if ((last & 0xc0) !== 0x80) return 1

  const limit = Math.max(0, len - 4)

  let i = len - 2
  while (i >= limit && (data[i] & 0xc0) === 0x80) i--

  if (i < 0) return 1

  const first = data[i]

  let needed
  if (first >= 0xc2 && first <= 0xdf) needed = 2
  else if (first >= 0xe0 && first <= 0xef) needed = 3
  else if (first >= 0xf0 && first <= 0xf4) needed = 4
  else return 1

  if (len - i !== needed) return 1

  if (needed >= 3) {
    const second = data[i + 1]
    if (first === 0xe0 && second < 0xa0) return 1
    if (first === 0xed && second > 0x9f) return 1
    if (first === 0xf0 && second < 0x90) return 1
    if (first === 0xf4 && second > 0x8f) return 1
  }

  return 0
}
{
  "name": "text-decoder",
  "version": "1.2.7",
  "description": "Streaming text decoder that preserves multibyte Unicode characters",
  "exports": {
    "./package": "./package.json",
    ".": "./index.js"
  },
  "files": [
    "index.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/text-decoder.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/text-decoder/issues"
  },
  "homepage": "https://github.com/holepunchto/text-decoder#readme",
  "dependencies": {
    "b4a": "^1.6.4"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  }
}
module.exports = class TimeOrderedSet {
  constructor () {
    this.oldest = null
    this.latest = null
    this.length = 0
  }

  has (node) {
    return !!(node.next || node.prev) || node === this.oldest
  }

  add (node) {
    if (this.has(node)) this.remove(node)

    if (!this.latest && !this.oldest) {
      this.latest = this.oldest = node
      node.prev = node.next = null
    } else {
      this.latest.next = node
      node.prev = this.latest
      node.next = null
      this.latest = node
    }

    this.length++

    return node
  }

  remove (node) {
    if (!this.has(node)) return node

    if (this.oldest !== node && this.latest !== node) {
      node.prev.next = node.next
      node.next.prev = node.prev
    } else {
      if (this.oldest === node) {
        this.oldest = node.next
        if (this.oldest) this.oldest.prev = null
      }
      if (this.latest === node) {
        this.latest = node.prev
        if (this.latest) this.latest.next = null
      }
    }

    node.next = node.prev = null
    this.length--

    return node
  }

  toArray ({ limit = Infinity, reverse = false } = {}) {
    const list = []

    if (reverse) {
      let node = this.latest
      while (node && limit--) {
        list.push(node)
        node = node.prev
      }
    } else {
      let node = this.oldest
      while (node && limit--) {
        list.push(node)
        node = node.next
      }
    }

    return list
  }
}
{
  "name": "time-ordered-set",
  "version": "2.0.1",
  "description": "Efficiently maintain a set of nodes ordered by the time they were added to the set",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "devDependencies": {
    "brittle": "^3.0.0",
    "standard": "^17.1.2"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/time-ordered-set.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/time-ordered-set/issues"
  },
  "homepage": "https://github.com/mafintosh/time-ordered-set"
}
module.exports = class TimerBrowser {
  constructor (ms, fn, ctx = null, interval = false) {
    this.ms = ms
    this.ontimeout = fn
    this.context = ctx || null
    this.interval = interval
    this.done = false

    this._timer = interval
      ? setInterval(callInterval, ms, this)
      : setTimeout(callTimeout, ms, this)
  }

  unref () {}

  ref () {}

  refresh () {
    if (this.done) return

    if (this.interval) {
      clearInterval(this._timer)
      this._timer = setInterval(callInterval, this.ms, this)
    } else {
      clearTimeout(this._timer)
      this._timer = setTimeout(callTimeout, this.ms, this)
    }
  }

  destroy () {
    this.done = true
    this.ontimeout = null

    if (this.interval) clearInterval(this._timer)
    else clearTimeout(this._timer)
  }

  static once (ms, fn, ctx) {
    return new this(ms, fn, ctx, false)
  }

  static on (ms, fn, ctx) {
    return new this(ms, fn, ctx, true)
  }
}

function callTimeout (self) {
  self.done = true
  self.ontimeout.call(self.context)
}

function callInterval (self) {
  self.ontimeout.call(self.context)
}
module.exports = isNode()
  ? require('./node')
  : require('./browser')

function isNode () {
  const to = setTimeout(function () {}, 1000)
  clearTimeout(to)
  return !!to.refresh
}
module.exports = class Timer {
  constructor (ms, fn, ctx = null, interval = false) {
    this.ms = ms
    this.ontimeout = fn
    this.context = ctx
    this.interval = interval
    this.done = false

    this._timer = interval
      ? setInterval(callInterval, ms, this)
      : setTimeout(callTimeout, ms, this)
  }

  unref () {
    this._timer.unref()
  }

  ref () {
    this._timer.ref()
  }

  refresh () {
    if (this.done !== true) this._timer.refresh()
  }

  destroy () {
    this.done = true
    this.ontimeout = null
    if (this.interval) clearInterval(this._timer)
    else clearTimeout(this._timer)
  }

  static once (ms, fn, ctx) {
    return new this(ms, fn, ctx, false)
  }

  static on (ms, fn, ctx) {
    return new this(ms, fn, ctx, true)
  }
}

function callTimeout (self) {
  self.done = true
  self.ontimeout.call(self.context)
}

function callInterval (self) {
  self.ontimeout.call(self.context)
}
{
  "name": "timeout-refresh",
  "version": "2.0.1",
  "description": "Efficiently refresh a timer",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^16.0.4",
    "tape": "^5.5.2"
  },
  "browser": "./browser.js",
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/timeout-refresh.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/timeout-refresh/issues"
  },
  "homepage": "https://github.com/mafintosh/timeout-refresh"
}
require.addon = require('require-addon')

module.exports = require.addon('.', __filename)
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

const v4Seg = '(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])'
const v4Str = `(${v4Seg}[.]){3}${v4Seg}`
const IPv4Pattern = new RegExp(`^${v4Str}$`)

const v6Seg = '(?:[0-9a-fA-F]{1,4})'
const IPv6Pattern = new RegExp(
  '^(' +
    `(?:${v6Seg}:){7}(?:${v6Seg}|:)|` +
    `(?:${v6Seg}:){6}(?:${v4Str}|:${v6Seg}|:)|` +
    `(?:${v6Seg}:){5}(?::${v4Str}|(:${v6Seg}){1,2}|:)|` +
    `(?:${v6Seg}:){4}(?:(:${v6Seg}){0,1}:${v4Str}|(:${v6Seg}){1,3}|:)|` +
    `(?:${v6Seg}:){3}(?:(:${v6Seg}){0,2}:${v4Str}|(:${v6Seg}){1,4}|:)|` +
    `(?:${v6Seg}:){2}(?:(:${v6Seg}){0,3}:${v4Str}|(:${v6Seg}){1,5}|:)|` +
    `(?:${v6Seg}:){1}(?:(:${v6Seg}){0,4}:${v4Str}|(:${v6Seg}){1,6}|:)|` +
    `(?::((?::${v6Seg}){0,5}:${v4Str}|(?::${v6Seg}){1,7}|:))` +
    ')(%[0-9a-zA-Z-.:]{1,})?$'
)

const isIPv4 = (exports.isIPv4 = function isIPv4(host) {
  return IPv4Pattern.test(host)
})

const isIPv6 = (exports.isIPv6 = function isIPv6(host) {
  return IPv6Pattern.test(host)
})

exports.isIP = function isIP(host) {
  if (isIPv4(host)) return 4
  if (isIPv6(host)) return 6
  return 0
}
const events = require('events')
const b4a = require('b4a')
const binding = require('../binding')

module.exports = class NetworkInterfaces extends events.EventEmitter {
  constructor(udx) {
    super()

    this._handle = b4a.alloc(binding.sizeof_udx_napi_interface_event_t)
    this._watching = false
    this._destroying = null

    binding.udx_napi_interface_event_init(
      udx._handle,
      this._handle,
      this,
      this._onevent,
      this._onclose
    )

    this.interfaces = binding.udx_napi_interface_event_get_addrs(this._handle)
  }

  _onclose() {
    this.emit('close')
  }

  _onevent() {
    this.interfaces = binding.udx_napi_interface_event_get_addrs(this._handle)

    this.emit('change', this.interfaces)
  }

  watch() {
    if (this._watching) return this
    this._watching = true

    binding.udx_napi_interface_event_start(this._handle)

    return this
  }

  unwatch() {
    if (!this._watching) return this
    this._watching = false

    binding.udx_napi_interface_event_stop(this._handle)

    return this
  }

  async destroy() {
    if (this._destroying) return this._destroying
    this._destroying = events.once(this, 'close')

    binding.udx_napi_interface_event_close(this._handle)

    return this._destroying
  }

  [Symbol.iterator]() {
    return this.interfaces[Symbol.iterator]()
  }
}
const events = require('events')
const b4a = require('b4a')
const binding = require('../binding')
const ip = require('./ip')

module.exports = class UDXSocket extends events.EventEmitter {
  constructor(udx, opts = {}) {
    super()

    this.udx = udx

    this._handle = b4a.alloc(binding.sizeof_udx_napi_socket_t)
    this._inited = false
    this._host = null
    this._family = 0
    this._ipv6Only = opts.ipv6Only === true
    this._reuseAddress = opts.reuseAddress === true
    this._port = 0
    this._reqs = []
    this._free = []
    this._closing = null
    this._closed = false

    this._view64 = new BigUint64Array(
      this._handle.buffer,
      this._handle.byteOffset,
      this._handle.byteLength >> 3
    )

    this.streams = new Set()

    this.userData = null
  }

  get bound() {
    return this._port !== 0
  }

  get closing() {
    return this._closing !== null
  }

  get idle() {
    return this.streams.size === 0
  }

  get busy() {
    return this.streams.size > 0
  }

  get bytesTransmitted() {
    if (this._inited !== true) return 0
    return Number(this._view64[binding.offsetof_udx_socket_t_bytes_tx >> 3])
  }

  get packetsTransmitted() {
    if (this._inited !== true) return 0
    return Number(this._view64[binding.offsetof_udx_socket_t_packets_tx >> 3])
  }

  get bytesReceived() {
    if (this._inited !== true) return 0
    return Number(this._view64[binding.offsetof_udx_socket_t_bytes_rx >> 3])
  }

  get packetsReceived() {
    if (this._inited !== true) return 0
    return Number(this._view64[binding.offsetof_udx_socket_t_packets_rx >> 3])
  }

  get packetsDroppedByKernel() {
    if (this._inited !== true) return 0
    return Number(this._view64[binding.offsetof_udx_socket_t_packets_dropped_by_kernel >> 3])
  }

  toJSON() {
    return {
      bound: this.bound,
      closing: this.closing,
      streams: this.streams.size,
      address: this.address(),
      ipv6Only: this._ipv6Only,
      reuseAddress: this._reuseAddress,
      idle: this.idle,
      busy: this.busy
    }
  }

  _init() {
    if (this._inited) return

    binding.udx_napi_socket_init(
      this.udx._handle,
      this._handle,
      this,
      this._onsend,
      this._onmessage,
      this._onclose,
      this._reallocMessage
    )

    this._inited = true
  }

  _onsend(id, err) {
    const req = this._reqs[id]

    const onflush = req.onflush

    req.buffer = null
    req.onflush = null

    this._free.push(id)

    onflush(err >= 0)

    // gc the free list
    if (this._free.length >= 16 && this._free.length === this._reqs.length) {
      this._free = []
      this._reqs = []
    }
  }

  _onmessage(len, port, host, family) {
    this.emit('message', this.udx._consumeMessage(len), { host, family, port })
    return this.udx._buffer
  }

  _onclose() {
    this.emit('close')
  }

  _reallocMessage() {
    return this.udx._reallocMessage()
  }

  _onidle() {
    this.emit('idle')
  }

  _onbusy() {
    this.emit('busy')
  }

  _addStream(stream) {
    if (this.streams.has(stream)) return false
    this.streams.add(stream)
    if (this.streams.size === 1) this._onbusy()
    return true
  }

  _removeStream(stream) {
    if (!this.streams.has(stream)) return false
    this.streams.delete(stream)
    const closed = this._closeMaybe()
    if (this.idle && !closed) this._onidle()
    return true
  }

  address() {
    if (!this.bound) return null
    return { host: this._host, family: this._family, port: this._port }
  }

  bind(port, host) {
    if (this.bound) throw new Error('Already bound')
    if (this.closing) throw new Error('Socket is closed')

    if (!port) port = 0

    let flags = 0
    if (this._ipv6Only) flags |= binding.UV_UDP_IPV6ONLY
    if (this._reuseAddress) flags |= binding.UV_UDP_REUSEADDR

    let family

    if (host) {
      family = ip.isIP(host)
      if (!family) throw new Error(`${host} is not a valid IP address`)

      if (!this._inited) this._init()

      this._port = binding.udx_napi_socket_bind(this._handle, port, host, family, flags)
    } else {
      if (!this._inited) this._init()

      try {
        host = '::'
        family = 6
        this._port = binding.udx_napi_socket_bind(this._handle, port, host, family, flags)
      } catch {
        host = '0.0.0.0'
        family = 4
        this._port = binding.udx_napi_socket_bind(this._handle, port, host, family, flags)
      }
    }

    this._host = host
    this._family = family

    this.emit('listening')
  }

  async close() {
    if (this._closing) return this._closing
    this._closing = new Promise((resolve) => this.once('close', resolve))
    this._closeMaybe()
    return this._closing
  }

  _closeMaybe() {
    if (this._closed || this._closing === null) return this._closed

    if (!this._inited) {
      this._closed = true
      this.emit('close')
      return true
    }

    if (this.idle) {
      binding.udx_napi_socket_close(this._handle)
      this._closed = true
    }

    return this._closed
  }

  setTTL(ttl) {
    if (!this._inited) throw new Error('Socket not active')
    binding.udx_napi_socket_set_ttl(this._handle, ttl)
  }

  getRecvBufferSize() {
    if (!this._inited) throw new Error('Socket not active')
    return binding.udx_napi_socket_get_recv_buffer_size(this._handle)
  }

  setRecvBufferSize(size) {
    if (!this._inited) throw new Error('Socket not active')
    return binding.udx_napi_socket_set_recv_buffer_size(this._handle, size)
  }

  getSendBufferSize() {
    if (!this._inited) throw new Error('Socket not active')
    return binding.udx_napi_socket_get_send_buffer_size(this._handle)
  }

  setSendBufferSize(size) {
    if (!this._inited) throw new Error('Socket not active')
    return binding.udx_napi_socket_set_send_buffer_size(this._handle, size)
  }

  addMembership(group, ifaceAddress) {
    if (!this._inited) throw new Error('Socket not active')
    return binding.udx_napi_socket_set_membership(this._handle, group, ifaceAddress || '', true)
  }

  dropMembership(group, ifaceAddress) {
    if (!this._inited) throw new Error('Socket not active')
    return binding.udx_napi_socket_set_membership(this._handle, group, ifaceAddress || '', false)
  }

  async send(buffer, port, host, ttl) {
    if (this.closing) return false

    if (!host) host = '127.0.0.1'

    const family = ip.isIP(host)
    if (!family) throw new Error(`${host} is not a valid IP address`)

    if (!this.bound) this.bind(0)

    const id = this._allocSend()
    const req = this._reqs[id]

    req.buffer = buffer

    const promise = new Promise((resolve) => {
      req.onflush = resolve
    })

    binding.udx_napi_socket_send_ttl(
      this._handle,
      req.handle,
      id,
      buffer,
      port,
      host,
      family,
      ttl || 0
    )

    return promise
  }

  trySend(buffer, port, host, ttl) {
    if (this.closing) return

    if (!host) host = '127.0.0.1'

    const family = ip.isIP(host)
    if (!family) throw new Error(`${host} is not a valid IP address`)

    if (!this.bound) this.bind(0)

    const id = this._allocSend()
    const req = this._reqs[id]

    req.buffer = buffer
    req.onflush = noop

    binding.udx_napi_socket_send_ttl(
      this._handle,
      req.handle,
      id,
      buffer,
      port,
      host,
      family,
      ttl || 0
    )
  }

  _allocSend() {
    if (this._free.length > 0) return this._free.pop()
    const handle = b4a.allocUnsafe(binding.sizeof_udx_socket_send_t)
    return this._reqs.push({ handle, buffer: null, onflush: null }) - 1
  }
}

function noop() {}
const streamx = require('streamx')
const b4a = require('b4a')
const binding = require('../binding')
const ip = require('./ip')

const MAX_PACKET = 2048
const BUFFER_SIZE = 65536 + MAX_PACKET

module.exports = class UDXStream extends streamx.Duplex {
  constructor(udx, id, opts = {}) {
    super({ mapWritable: toBuffer, eagerOpen: true })

    this.udx = udx
    this.socket = null

    this._handle = b4a.alloc(binding.sizeof_udx_napi_stream_t)
    this._view = new Uint32Array(
      this._handle.buffer,
      this._handle.byteOffset,
      this._handle.byteLength >> 2
    )
    this._view16 = new Uint16Array(
      this._handle.buffer,
      this._handle.byteOffset,
      this._handle.byteLength >> 1
    )
    this._view64 = new BigUint64Array(
      this._handle.buffer,
      this._handle.byteOffset,
      this._handle.byteLength >> 3
    )

    this._wreqs = []
    this._wfree = []

    this._sreqs = []
    this._sfree = []
    this._closed = false

    this._flushing = 0
    this._flushes = []

    this._buffer = null
    this._reallocData()

    this._onwrite = null
    this._ondestroy = null
    this._firewall = opts.firewall || firewallAll

    this._remoteChanging = null
    this._previousSocket = null

    this.id = id
    this.remoteId = 0
    this.remoteHost = null
    this.remoteFamily = 0
    this.remotePort = 0

    this.userData = null

    binding.udx_napi_stream_init(
      this.udx._handle,
      this._handle,
      id,
      opts.framed ? 1 : 0,
      this,
      this._ondata,
      this._onend,
      this._ondrain,
      this._onack,
      this._onsend,
      this._onmessage,
      this._onclose,
      this._onfirewall,
      this._onremotechanged,
      this._reallocData,
      this._reallocMessage
    )

    if (opts.seq) binding.udx_napi_stream_set_seq(this._handle, opts.seq)

    binding.udx_napi_stream_recv_start(this._handle, this._buffer)
  }

  get connected() {
    return this.socket !== null
  }

  get mtu() {
    return this._view16[binding.offsetof_udx_stream_t_mtu >> 1]
  }

  get rtt() {
    return this._view[binding.offsetof_udx_stream_t_srtt >> 2]
  }

  get cwnd() {
    return this._view[binding.offsetof_udx_stream_t_cwnd >> 2]
  }

  get rtoCount() {
    return this._view16[binding.offsetof_udx_stream_t_rto_count >> 1]
  }

  get retransmits() {
    return this._view16[binding.offsetof_udx_stream_t_retransmit_count >> 1]
  }

  get bbrState() {
    const view = new Uint8Array(
      this._handle.buffer,
      this._handle.byteOffset,
      this._handle.byteLength
    )
    return view[binding.offsetof_udx_stream_t_bbr_state]
  }

  get bbrBandwidth() {
    return binding.udx_napi_stream_get_bw(this._handle)
  }

  get fastRecoveries() {
    return this._view16[binding.offsetof_udx_stream_t_fast_recovery_count >> 1]
  }

  get inflight() {
    return this._view[binding.offsetof_udx_stream_t_inflight >> 2]
  }

  get bytesTransmitted() {
    return Number(this._view64[binding.offsetof_udx_stream_t_bytes_tx >> 3])
  }

  get packetsTransmitted() {
    return Number(this._view64[binding.offsetof_udx_stream_t_packets_tx >> 3])
  }

  get bytesReceived() {
    return Number(this._view64[binding.offsetof_udx_stream_t_bytes_rx >> 3])
  }

  get packetsReceived() {
    return Number(this._view64[binding.offsetof_udx_stream_t_packets_rx >> 3])
  }

  get localHost() {
    return this.socket ? this.socket.address().host : null
  }

  get localFamily() {
    return this.socket ? this.socket.address().family : 0
  }

  get localPort() {
    return this.socket ? this.socket.address().port : 0
  }

  setInteractive(bool) {
    if (!this._closed) return
    binding.udx_napi_stream_set_mode(this._handle, bool ? 0 : 1)
  }

  connect(socket, remoteId, port, host, opts = {}) {
    if (this._closed) return

    if (this.connected) throw new Error('Already connected')
    if (socket.closing) throw new Error('Socket is closed')

    if (typeof host === 'object') {
      opts = host
      host = null
    }

    if (!host) host = '127.0.0.1'

    const family = ip.isIP(host)
    if (!family) throw new Error(`${host} is not a valid IP address`)
    if (!(port > 0 && port < 65536)) throw new Error(`${port} is not a valid port`)

    if (!socket.bound) socket.bind(0)

    this.remoteId = remoteId
    this.remotePort = port
    this.remoteHost = host
    this.remoteFamily = family
    this.socket = socket

    if (opts.ack) binding.udx_napi_stream_set_ack(this._handle, opts.ack)

    binding.udx_napi_stream_connect(this._handle, socket._handle, remoteId, port, host, family)

    this.socket._addStream(this)

    this.emit('connect')
  }

  changeRemote(socket, remoteId, port, host) {
    if (this._remoteChanging) throw new Error('Remote already changing')

    if (!this.connected) throw new Error('Not yet connected')
    if (socket.closing) throw new Error('Socket is closed')

    if (this.socket.udx !== socket.udx) {
      throw new Error('Cannot change to a socket on another UDX instance')
    }

    if (!host) host = '127.0.0.1'

    const family = ip.isIP(host)
    if (!family) throw new Error(`${host} is not a valid IP address`)
    if (!(port > 0 && port < 65536)) throw new Error(`${port} is not a valid port`)

    if (this.socket !== socket) this._previousSocket = this.socket

    this.remoteId = remoteId
    this.remotePort = port
    this.remoteHost = host
    this.remoteFamily = family
    this.socket = socket

    this._remoteChanging = new Promise((resolve, reject) => {
      const onchanged = () => {
        this.off('close', onclose)
        resolve()
      }

      const onclose = () => {
        this.off('remote-changed', onchanged)
        reject(new Error('Stream is closed'))
      }

      this.once('remote-changed', onchanged).once('close', onclose)
    })

    binding.udx_napi_stream_change_remote(
      this._handle,
      socket._handle,
      remoteId,
      port,
      host,
      family
    )

    this.socket._addStream(this)

    return this._remoteChanging
  }

  relayTo(destination) {
    if (this._closed) return

    binding.udx_napi_stream_relay_to(this._handle, destination._handle)
  }

  async send(buffer) {
    if (!this.connected || this._closed) return false

    const id = this._allocSend()
    const req = this._sreqs[id]

    req.buffer = buffer

    const promise = new Promise((resolve) => {
      req.onflush = resolve
    })

    binding.udx_napi_stream_send(this._handle, req.handle, id, buffer)

    return promise
  }

  trySend(buffer) {
    if (!this.connected || this._closed) return

    const id = this._allocSend()
    const req = this._sreqs[id]

    req.buffer = buffer
    req.onflush = noop

    binding.udx_napi_stream_send(this._handle, req.handle, id, buffer)
  }

  async flush() {
    if ((await streamx.Writable.drained(this)) === false) return false
    if (this.destroying) return false

    const missing = this._wreqs.length - this._wfree.length
    if (missing === 0) return true

    return new Promise((resolve) => {
      this._flushes.push({ flush: this._flushing++, missing, resolve })
    })
  }

  toJSON() {
    return {
      id: this.id,
      connected: this.connected,
      destroying: this.destroying,
      destroyed: this.destroyed,
      remoteId: this.remoteId,
      remoteHost: this.remoteHost,
      remoteFamily: this.remoteFamily,
      remotePort: this.remotePort,
      mtu: this.mtu,
      rtt: this.rtt,
      cwnd: this.cwnd,
      inflight: this.inflight,
      socket: this.socket ? this.socket.toJSON() : null
    }
  }

  _read(cb) {
    cb(null)
  }

  _writeContinue(err) {
    if (this._onwrite === null) return
    const cb = this._onwrite
    this._onwrite = null
    cb(err)
  }

  _destroyContinue(err) {
    if (this._ondestroy === null) return
    const cb = this._ondestroy
    this._ondestroy = null
    cb(err)
  }

  _writev(buffers, cb) {
    if (!this.connected) {
      throw customError('Writing while not connected not currently supported', 'ERR_ASSERTION')
    }

    let drained = true

    if (buffers.length === 1) {
      const id = this._allocWrite(1)
      const req = this._wreqs[id]

      req.flush = this._flushing
      req.buffer = buffers[0]

      drained = binding.udx_napi_stream_write(this._handle, req.handle, id, req.buffer) !== 0
    } else {
      const id = this._allocWrite(nextBatchSize(buffers.length))
      const req = this._wreqs[id]

      req.flush = this._flushing
      req.buffers = buffers

      drained = binding.udx_napi_stream_writev(this._handle, req.handle, id, req.buffers) !== 0
    }

    if (drained) cb(null)
    else this._onwrite = cb
  }

  _final(cb) {
    const id = this._allocWrite(1)
    const req = this._wreqs[id]

    req.flush = this._flushes
    req.buffer = b4a.allocUnsafe(0)

    const drained =
      binding.udx_napi_stream_write_end(this._handle, req.handle, id, req.buffer) !== 0

    if (drained) cb(null)
    else this._onwrite = cb
  }

  _predestroy() {
    if (!this._closed) binding.udx_napi_stream_destroy(this._handle)
    this._closed = true
    this._writeContinue(null)
  }

  _destroy(cb) {
    if (this.connected) this._ondestroy = cb
    else cb(null)
  }

  _ondata(read) {
    this.push(this._consumeData(read))
    return this._buffer
  }

  _onend(read) {
    if (read > 0) this.push(this._consumeData(read))
    this.push(null)
  }

  _ondrain() {
    this._writeContinue(null)
  }

  _flushAck(flush) {
    for (let i = this._flushes.length - 1; i >= 0; i--) {
      const f = this._flushes[i]
      if (f.flush < flush) break
      f.missing--
    }

    while (this._flushes.length > 0 && this._flushes[0].missing === 0) {
      this._flushes.shift().resolve(true)
    }
  }

  _onack(id) {
    const req = this._wreqs[id]

    req.buffers = req.buffer = null
    this._wfree.push(id)

    if (this._flushes.length > 0) this._flushAck(req.flush)

    // gc the free list
    if (this._wfree.length >= 64 && this._wfree.length === this._wreqs.length) {
      this._wfree = []
      this._wreqs = []
    }
  }

  _onsend(id, err) {
    const req = this._sreqs[id]

    const onflush = req.onflush

    req.buffer = null
    req.onflush = null

    this._sfree.push(id)

    onflush(err >= 0)

    // gc the free list
    if (this._sfree.length >= 16 && this._sfree.length === this._sreqs.length) {
      this._sfree = []
      this._sreqs = []
    }
  }

  _onmessage(len) {
    this.emit('message', this.udx._consumeMessage(len))
    return this.udx._buffer
  }

  _onclose(err) {
    this._closed = true

    if (this.socket) {
      this.socket._removeStream(this)
      this.socket = null
    }

    if (this._previousSocket) {
      this._previousSocket._removeStream(this)
      this._previousSocket = null
    }

    // no error, we don't need to do anything
    if (!err) return this._destroyContinue(null)

    if (this._ondestroy === null) this.destroy(err)
    else this._destroyContinue(err)
  }

  _onfirewall(socket, port, host, family) {
    if (port <= 0 || port > 65535) return 1
    return this._firewall(socket, port, host, family) ? 1 : 0
  }

  _onremotechanged() {
    if (this._previousSocket) {
      this._previousSocket._removeStream(this)
      this._previousSocket = null
    }

    this._remoteChanging = null
    this.emit('remote-changed')
  }

  _consumeData(len) {
    const next = this._buffer.subarray(0, len)
    this._buffer = this._buffer.subarray(len)
    if (this._buffer.byteLength < MAX_PACKET) this._reallocData()
    return next
  }

  _reallocData() {
    this._buffer = b4a.allocUnsafe(BUFFER_SIZE)
    return this._buffer
  }

  _reallocMessage() {
    return this.udx._reallocMessage()
  }

  _allocWrite(size) {
    if (this._wfree.length === 0) {
      const handle = b4a.allocUnsafe(binding.udx_napi_stream_write_sizeof(size))
      return (
        this._wreqs.push({
          handle,
          size,
          buffers: null,
          buffer: null,
          flush: 0
        }) - 1
      )
    }

    const free = this._wfree.pop()
    if (size === 1) return free

    const next = this._wreqs[free]
    if (next.size < size) {
      next.handle = b4a.allocUnsafe(binding.udx_napi_stream_write_sizeof(size))
      next.size = size
    }

    return free
  }

  _allocSend() {
    if (this._sfree.length > 0) return this._sfree.pop()
    const handle = b4a.allocUnsafe(binding.sizeof_udx_stream_send_t)
    return this._sreqs.push({ handle, buffer: null, resolve: null, reject: null }) - 1
  }
}

function noop() {}

function toBuffer(data) {
  return typeof data === 'string' ? b4a.from(data) : data
}

function firewallAll(socket, port, host) {
  return true
}

function customError(message, code) {
  const error = new Error(message)
  error.code = code
  return error
}

function nextBatchSize(n) {
  // try to coerce the the writevs into sameish size
  if (n === 1) return 1
  // group all < 8 to the same size, low mem overhead but save some small allocs
  if (n < 8) return 8
  if (n < 16) return 16
  if (n < 32) return 32
  if (n < 64) return 64
  return n
}
const b4a = require('b4a')
const binding = require('../binding')
const ip = require('./ip')
const Socket = require('./socket')
const Stream = require('./stream')
const NetworkInterfaces = require('./network-interfaces')

const MAX_MESSAGE = 4096
const BUFFER_SIZE = 65536 + MAX_MESSAGE

module.exports = class UDX {
  constructor() {
    this._handle = b4a.alloc(binding.sizeof_udx_napi_t)
    this._watchers = new Set()
    this._view64 = new BigUint64Array(
      this._handle.buffer,
      this._handle.byteOffset,
      this._handle.byteLength >> 3
    )

    this._buffer = null
    this._reallocMessage()

    binding.udx_napi_init(this._handle, this._buffer)
  }

  static isIPv4(host) {
    return ip.isIPv4(host)
  }

  static isIPv6(host) {
    return ip.isIPv6(host)
  }

  static isIP(host) {
    return ip.isIP(host)
  }

  get bytesTransmitted() {
    return Number(this._view64[binding.offsetof_udx_t_bytes_tx >> 3])
  }

  get packetsTransmitted() {
    return Number(this._view64[binding.offsetof_udx_t_packets_tx >> 3])
  }

  get bytesReceived() {
    return Number(this._view64[binding.offsetof_udx_t_bytes_rx >> 3])
  }

  get packetsReceived() {
    return Number(this._view64[binding.offsetof_udx_t_packets_rx >> 3])
  }

  get packetsDroppedByKernel() {
    return Number(this._view64[binding.offsetof_udx_t_packets_dropped_by_kernel >> 3])
  }

  _consumeMessage(len) {
    const next = this._buffer.subarray(0, len)
    this._buffer = this._buffer.subarray(len)
    if (this._buffer.byteLength < MAX_MESSAGE) this._reallocMessage()
    return next
  }

  _reallocMessage() {
    // TODO: move reallocation to native
    this._buffer = b4a.allocUnsafe(BUFFER_SIZE)
    return this._buffer
  }

  createSocket(opts) {
    return new Socket(this, opts)
  }

  createStream(id, opts) {
    return new Stream(this, id, opts)
  }

  networkInterfaces() {
    let [watcher = null] = this._watchers
    if (watcher) return watcher.interfaces

    watcher = new NetworkInterfaces(this)
    watcher.destroy()

    return watcher.interfaces
  }

  watchNetworkInterfaces(onchange) {
    const watcher = new NetworkInterfaces(this)

    this._watchers.add(watcher)
    watcher.on('close', () => {
      this._watchers.delete(watcher)
    })

    if (onchange) watcher.on('change', onchange)

    return watcher.watch()
  }

  async lookup(host, opts = {}) {
    const { family = 0 } = opts

    const req = b4a.alloc(binding.sizeof_udx_napi_lookup_t)
    const ctx = {
      req,
      resolve: null,
      reject: null
    }

    const promise = new Promise((resolve, reject) => {
      ctx.resolve = resolve
      ctx.reject = reject
    })

    binding.udx_napi_lookup(this._handle, req, host, family, ctx, onlookup)

    return promise
  }
}

function onlookup(err, host, family) {
  if (err) this.reject(err)
  else this.resolve({ host, family })
}
{
  "name": "udx-native",
  "version": "1.20.7",
  "description": "udx is reliable, multiplexed, and congestion-controlled streams over udp",
  "main": "lib/udx.js",
  "files": [
    "lib",
    "prebuilds",
    "binding.cc",
    "binding.js",
    "CMakeLists.txt"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "addon": true,
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node --coverage test/*.js",
    "test:bare": "brittle-bare --coverage test/*.js",
    "test:all": "brittle test/*.js test/slow/*.js",
    "test:generate": "brittle -r test/all.js test/*.js",
    "bench": "brittle test/bench/*.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/udx-native.git"
  },
  "keywords": [
    "tcp",
    "udp",
    "stream",
    "reliable"
  ],
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/udx-native/issues"
  },
  "homepage": "https://github.com/holepunchto/udx-native#readme",
  "engines": {
    "bare": ">=1.17.4"
  },
  "dependencies": {
    "b4a": "^1.5.0",
    "bare-events": "^2.2.0",
    "require-addon": "^1.1.0",
    "streamx": "^2.22.0"
  },
  "devDependencies": {
    "bare-compat-napi": "^1.3.0",
    "brittle": "^3.1.0",
    "cmake-bare": "^1.1.10",
    "cmake-fetch": "^1.0.1",
    "cmake-napi": "^1.0.5",
    "is-ci": "^3.0.1",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "tiny-byte-size": "^1.1.0"
  }
}
exports.add = add
exports.has = has
exports.remove = remove
exports.swap = swap

function add (list, item) {
  if (has(list, item)) return item
  item._index = list.length
  list.push(item)
  return item
}

function has (list, item) {
  return item._index < list.length && list[item._index] === item
}

function remove (list, item) {
  if (!has(list, item)) return null

  var last = list.pop()
  if (last !== item) {
    list[item._index] = last
    last._index = item._index
  }

  return item
}

function swap (list, a, b) {
  if (!has(list, a) || !has(list, b)) return
  var tmp = a._index
  a._index = b._index
  list[a._index] = a
  b._index = tmp
  list[b._index] = b
}
{
  "name": "unordered-set",
  "version": "2.0.1",
  "description": "A couple of functions that make it easy to maintain an unordered set as an array in an efficient way",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^6.0.4",
    "tape": "^4.4.0"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/unordered-set.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/unordered-set/issues"
  },
  "homepage": "https://github.com/mafintosh/unordered-set"
}
const b4a = require('b4a')

unslab.all = all
unslab.is = is

module.exports = unslab

function unslab (buf) {
  if (buf === null || buf.buffer.byteLength === buf.byteLength) return buf
  const copy = b4a.allocUnsafeSlow(buf.byteLength)
  copy.set(buf, 0)
  return copy
}

function is (buf) {
  return buf.buffer.byteLength !== buf.byteLength
}

function all (list) {
  let size = 0
  for (let i = 0; i < list.length; i++) {
    const buf = list[i]
    size += buf === null || buf.buffer.byteLength === buf.byteLength ? 0 : buf.byteLength
  }

  const copy = b4a.allocUnsafeSlow(size)
  const result = new Array(list.length)

  let offset = 0
  for (let i = 0; i < list.length; i++) {
    let buf = list[i]

    if (buf !== null && buf.buffer.byteLength !== buf.byteLength) {
      copy.set(buf, offset)
      buf = copy.subarray(offset, offset += buf.byteLength)
    }

    result[i] = buf
  }

  return result
}
{
  "name": "unslab",
  "version": "1.3.0",
  "description": "Unslab some slab'ed buffers",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.6.6"
  },
  "devDependencies": {
    "brittle": "^3.5.2",
    "standard": "^17.1.0"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/unslab.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/unslab/issues"
  },
  "homepage": "https://github.com/holepunchto/unslab"
}
const { runtime, platform, arch, version } =
  typeof Bare !== 'undefined'
    ? {
        runtime: 'bare',
        platform: global.Bare.platform,
        arch: global.Bare.arch,
        version: global.Bare.version
      }
    : typeof process !== 'undefined'
      ? {
          runtime: 'node',
          platform: global.process.platform,
          arch: global.process.arch,
          version: global.process.version
        }
      : typeof Window !== 'undefined'
        ? { runtime: 'browser', platform: 'unknown', arch: 'unknown', version: 'unknown' }
        : { runtime: 'unknown', platform: 'unknown', arch: 'unknown', version: 'unknown' }

exports.runtime = runtime
exports.version = version
exports.platform = platform
exports.arch = arch
exports.isBare = runtime === 'bare'
exports.isBareKit = exports.isBare && typeof BareKit !== 'undefined'
exports.isPear = typeof Pear !== 'undefined'
exports.isNode = runtime === 'node'
exports.isBrowser = runtime === 'browser'
exports.isWindows = platform === 'win32'
exports.isLinux = platform === 'linux'
exports.isMac = platform === 'darwin'
exports.isIOS = platform === 'ios' || platform === 'ios-simulator'
exports.isAndroid = platform === 'android'
exports.isElectron = typeof process !== 'undefined' && !!global.process.versions?.electron
exports.isElectronRenderer = exports.isElectron && global.process.type === 'renderer'
exports.isElectronWorker = exports.isElectron && global.process.type === 'worker'
{
  "name": "which-runtime",
  "version": "1.4.0",
  "description": "Detect if you are in Bare or Node and which os etc",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte .",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/which-runtime.git"
  },
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/which-runtime/issues"
  },
  "homepage": "https://github.com/holepunchto/which-runtime",
  "devDependencies": {
    "brittle": "^3.0.0",
    "lunte": "^1.4.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = class MaxCache {
  constructor ({ maxSize, maxAge, createMap, ongc }) {
    this.maxSize = maxSize
    this.maxAge = maxAge
    this.ongc = ongc || null

    this._createMap = createMap || defaultCreateMap
    this._latest = this._createMap()
    this._oldest = this._createMap()
    this._retained = this._createMap()
    this._gced = false
    this._interval = null

    if (this.maxAge > 0 && this.maxAge < Infinity) {
      const tick = Math.ceil(2 / 3 * this.maxAge)
      this._interval = setInterval(this._gcAuto.bind(this), tick)
      if (this._interval.unref) this._interval.unref()
    }
  }

  * [Symbol.iterator] () {
    for (const it of [this._latest, this._oldest, this._retained]) {
      yield * it
    }
  }

  * keys () {
    for (const it of [this._latest, this._oldest, this._retained]) {
      yield * it.keys()
    }
  }

  * values () {
    for (const it of [this._latest, this._oldest, this._retained]) {
      yield * it.values()
    }
  }

  destroy () {
    this.clear()
    clearInterval(this._interval)
    this._interval = null
  }

  clear () {
    this._gced = true
    this._latest.clear()
    this._oldest.clear()
    this._retained.clear()
  }

  set (k, v) {
    if (this._retained.has(k)) return this
    this._latest.set(k, v)
    this._oldest.delete(k) || this._retained.delete(k)
    if (this._latest.size >= this.maxSize) this._gc()
    return this
  }

  retain (k, v) {
    this._retained.set(k, v)
    this._latest.delete(k) || this._oldest.delete(k)
    return this
  }

  delete (k) {
    return this._latest.delete(k) || this._oldest.delete(k) || this._retained.delete(k)
  }

  has (k) {
    return this._latest.has(k) || this._oldest.has(k) || this._retained.has(k)
  }

  get (k) {
    if (this._latest.has(k)) {
      return this._latest.get(k)
    }

    if (this._oldest.has(k)) {
      const v = this._oldest.get(k)
      this._latest.set(k, v)
      this._oldest.delete(k)
      return v
    }

    if (this._retained.has(k)) {
      return this._retained.get(k)
    }

    return null
  }

  _gcAuto () {
    if (!this._gced) this._gc()
    this._gced = false
  }

  _gc () {
    this._gced = true
    if (this.ongc !== null && this._oldest.size > 0) this.ongc(this._oldest)
    this._oldest = this._latest
    this._latest = this._createMap()
  }
}

function defaultCreateMap () {
  return new Map()
}
{
  "name": "xache",
  "version": "1.2.1",
  "description": "Yet another auto expiring, max sizable cache",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "devDependencies": {
    "brittle": "^3.3.2",
    "standard": "^17.1.0"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/xache.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/xache/issues"
  },
  "homepage": "https://github.com/mafintosh/xache"
}
const b4a = require('b4a')

const ALPHABET = 'ybndrfg8ejkmcpqxot1uwisza345h769'
const MIN = 0x31 // 1
const MAX = 0x7a // z
const REVERSE = new Int8Array(1 + MAX - MIN)

REVERSE.fill(-1)

for (let i = 0; i < ALPHABET.length; i++) {
  const v = ALPHABET.charCodeAt(i) - MIN
  REVERSE[v] = i
}

exports.encode = encode
exports.decode = decode
exports.ALPHABET = ALPHABET

function decode (s, out) {
  let pb = 0
  let ps = 0

  const r = s.length & 7
  const q = (s.length - r) / 8

  if (!out) out = b4a.allocUnsafe(Math.ceil(s.length * 5 / 8))

  // 0 5 2 7 4 1 6 3 (+5 mod 8)
  for (let i = 0; i < q; i++) {
    const a = quintet(s, ps++)
    const b = quintet(s, ps++)
    const c = quintet(s, ps++)
    const d = quintet(s, ps++)
    const e = quintet(s, ps++)
    const f = quintet(s, ps++)
    const g = quintet(s, ps++)
    const h = quintet(s, ps++)

    out[pb++] = (a << 3) | (b >>> 2)
    out[pb++] = ((b & 0b11) << 6) | (c << 1) | (d >>> 4)
    out[pb++] = ((d & 0b1111) << 4) | (e >>> 1)
    out[pb++] = ((e & 0b1) << 7) | (f << 2) | (g >>> 3)
    out[pb++] = ((g & 0b111) << 5) | h
  }

  if (r === 0) return out.subarray(0, pb)

  const a = quintet(s, ps++)
  const b = quintet(s, ps++)

  out[pb++] = (a << 3) | (b >>> 2)

  if (r <= 2) return out.subarray(0, pb)

  const c = quintet(s, ps++)
  const d = quintet(s, ps++)

  out[pb++] = ((b & 0b11) << 6) | (c << 1) | (d >>> 4)

  if (r <= 4) return out.subarray(0, pb)

  const e = quintet(s, ps++)

  out[pb++] = ((d & 0b1111) << 4) | (e >>> 1)

  if (r <= 5) return out.subarray(0, pb)

  const f = quintet(s, ps++)
  const g = quintet(s, ps++)

  out[pb++] = ((e & 0b1) << 7) | (f << 2) | (g >>> 3)

  if (r <= 7) return out.subarray(0, pb)

  const h = quintet(s, ps++)

  out[pb++] = ((g & 0b111) << 5) | h

  return out.subarray(0, pb)
}

function encode (buf) {
  if (typeof buf === 'string') buf = b4a.from(buf)

  const max = buf.byteLength * 8

  let s = ''

  for (let p = 0; p < max; p += 5) {
    const i = p >>> 3
    const j = p & 7

    if (j <= 3) {
      s += ALPHABET[(buf[i] >>> (3 - j)) & 0b11111]
      continue
    }

    const of = j - 3
    const h = (buf[i] << of) & 0b11111
    const l = (i >= buf.byteLength ? 0 : buf[i + 1]) >>> (8 - of)

    s += ALPHABET[h | l]
  }

  return s
}

function quintet (s, i) {
  if (i > s.length) {
    return 0
  }

  const v = s.charCodeAt(i)

  if (v < MIN || v > MAX) {
    throw Error('Invalid character in base32 input: "' + s[i] + '" at position ' + i)
  }

  const bits = REVERSE[v - MIN]

  if (bits === -1) {
    throw Error('Invalid character in base32 input: "' + s[i] + '" at position ' + i)
  }

  return bits
}
{
  "name": "z32",
  "version": "1.1.0",
  "description": "Encode & decode z-base32",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.5.3"
  },
  "devDependencies": {
    "base-x": "^4.0.0",
    "base32": "0.0.7",
    "brittle": "^3.1.3",
    "nanobench": "^3.0.0",
    "rfc4648": "^1.5.2",
    "standard": "^17.0.0"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/z32.git"
  },
  "scripts": {
    "test": "standard && brittle test.js",
    "bench": "node benchmark.js"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/z32/issues"
  },
  "homepage": "https://github.com/mafintosh/z32"
}
{
  "name": "hyper-proto-peer",
  "version": "0.3.123",
  "description": "Self-custody, P2P-native atproto peer \u2014 holds the user's key + content as Hypercores and authors+signs its own repo. The source of truth in the peer/bridge split (Model B); atproto-bridge projects it to bsky.",
  "type": "module",
  "main": "lib/peer.js",
  "bin": {
    "hyper-proto-peer": "index.js"
  },
  "scripts": {
    "test": "bare test/all.js",
    "start": "bare index.js",
    "postinstall": "node scripts/bare-deps.mjs",
    "test:e2e": "bare test/e2e-federation.test.js"
  },
  "pgh": {
    "bin": "hyper-proto-peer",
    "upgrade": "pgh://1dd36bdfa9cb7f7d84adbd07f017e7200f7f90a3a546cd0761fac2a1f8a13e86/hyper-proto-peer",
    "entrypoint": "index.js",
    "type": "daemon",
    "runtime": "bare",
    "autostart": true,
    "depends": [
      "pgh-sidecar"
    ],
    "defaults": {
      "env": {
        "PEER_STORAGE": "${HOME}/.config/hyper-proto-peer/data"
      }
    },
    "readiness": {
      "type": "pidfile",
      "timeoutMs": 30000
    },
    "service": {
      "requiresNetwork": true
    },
    "systemd": {
      "user": true,
      "enable": true,
      "restart": "on-failure"
    }
  },
  "dependencies": {
    "@ipld/dag-cbor": "^9.2.1",
    "atproto-did-peer": "file:../atproto-did-peer",
    "atproto-identity": "file:../atproto-identity",
    "atproto-repo": "file:../atproto-repo",
    "atproto-store": "file:../atproto-store",
    "atproto-room": "file:../atproto-room",
    "autobase": "7.28.1",
    "b4a": "^1.6.0",
    "bare-fetch": "^3.0.1",
    "bare-fs": "^4.7.1",
    "bare-os": "^3.9.1",
    "bare-path": "^3.0.1",
    "bare-process": "^4.2.1",
    "compact-encoding": "^2.16.0",
    "corestore": "^7.10.0",
    "hypercore": "^11.33.1",
    "hypercore-crypto": "^3.0.0",
    "hypercore-storage": "^3.1.2",
    "hyperdb": "^6.7.0",
    "hyperdispatch": "^1.6.0",
    "hyperschema": "^1.21.0",
    "hyperswarm": "^4.17.0",
    "keet-identity-key": "^3.2.0",
    "protomux-rpc": "^1.10.0",
    "protomux-wakeup": "^2.9.0",
    "hyper-svc": "file:../hyper-svc",
    "hyper-overlay": "file:../hyper-overlay"
  },
  "devDependencies": {
    "@hyperswarm/testnet": "^3.1.4",
    "@noble/curves": "^1.6.0",
    "brittle": "^4.0.2"
  }
}
/**
 * hyper-svc — reusable per-app daemon library
 *
 * RPC transports: UDS, HTTP, and Hyperswarm (Protomux channel).
 * Replication: Hyperswarm topic join + corestore/autobase/mux replicate.
 */

export { Service } from './lib/service.js'
export { Client } from './lib/client.js'
export { encodeFrame, FrameDecoder } from './lib/frame.js'
export { attachRpcServer, attachRpcClient } from './lib/transports/swarm-rpc.js'
/**
 * Client — RPC client for hyper-svc daemons.
 *
 * Local-only. Connects via UDS (preferred) or HTTP. Both transports speak the
 * same JSON-RPC-ish protocol; the wire format differs (length-prefixed frames
 * for UDS, POST /rpc/<method> for HTTP) but the call signature is identical.
 *
 * Discovery: try UDS first (if a path is provided and the socket is reachable),
 * fall back to HTTP. Explicit transport selection is also supported.
 *
 * Usage:
 *
 *   const client = await Client.discover({
 *     uds: '/tmp/pear-git.sock',
 *     http: 'http://127.0.0.1:4040'
 *   })
 *
 *   const orgs = await client.call('list-orgs', { limit: 10 })
 *
 *   await client.close()
 */

import http from '#node:http'
import { URL } from '#node:url'
import b4a from 'b4a'
import { stat } from '#node:fs/promises'
import { udsBackend } from './uds-backend.js'
import Hyperswarm from 'hyperswarm'
import Protomux from 'protomux'
import crypto from 'hypercore-crypto'
import { encodeFrame, FrameDecoder } from './frame.js'
import { attachRpcClient } from './transports/swarm-rpc.js'

export class Client {
  /**
   * Discover and connect to a running hyper-svc daemon.
   *
   * @param {object} opts
   * @param {string} [opts.uds] - UDS socket path. Tried first.
   * @param {string} [opts.http] - HTTP base URL (e.g. 'http://127.0.0.1:4040'). Fallback.
   * @param {'uds'|'http'} [opts.prefer] - explicit override
   * @returns {Promise<Client>}
   */
  static async discover (opts = {}) {
    const prefer = opts.prefer

    if (prefer === 'uds') {
      if (!opts.uds) throw new Error('discover({ prefer: "uds" }) requires opts.uds')
      return Client.connectUds(opts.uds)
    }
    if (prefer === 'http') {
      if (!opts.http) throw new Error('discover({ prefer: "http" }) requires opts.http')
      return Client.connectHttp(opts.http)
    }

    // Auto: UDS first if reachable, then HTTP
    if (opts.uds) {
      const reachable = await udsReachable(opts.uds)
      if (reachable) return Client.connectUds(opts.uds)
    }
    if (opts.http) {
      return Client.connectHttp(opts.http)
    }

    const tried = []
    if (opts.uds) tried.push(`uds:${opts.uds}`)
    if (opts.http) tried.push(`http:${opts.http}`)
    throw new Error(`no daemon reachable (tried: ${tried.join(', ') || 'nothing — pass uds and/or http'})`)
  }

  static async connectUds (path) {
    const { backend, name } = await udsBackend(path)
    const sock = backend.createConnection(name)
    await new Promise((resolve, reject) => {
      sock.once('connect', () => {
        sock.removeListener('error', reject)
        resolve()
      })
      sock.once('error', reject)
    })
    return new Client({ kind: 'uds', sock })
  }

  static connectHttp (base) {
    return new Client({ kind: 'http', base: base.replace(/\/+$/, '') })
  }

  /**
   * Connect to a remote daemon via Hyperswarm. Joins the topic derived from
   * `serverKey`, waits for a connection, attaches a Protomux RPC channel, and
   * (when `opts.verify` is given) confirms the peer that answered is the one
   * that was asked for.
   *
   * ⚠ `serverKey` IS NOT AN IDENTITY — IT IS ONLY A RENDEZVOUS ADDRESS.
   *
   * The topic is `hash(serverKey + salt)`, and SwarmTransport.listen() creates
   * its Hyperswarm with NO keyPair, so a server's Noise key is random per
   * process and never equals the `serverKey` clients use to find it. Anything
   * joined to that topic as a server can therefore answer, and there is no
   * cryptographic binding to check `conn.remotePublicKey` against.
   *
   * That is not hypothetical. In a pear-git-v3 fleet, a mirror joins its
   * ORIGIN's topic (the topic travels in the deployment bundle), so it is a
   * server on the exact topic clients use to reach the origin. Measured
   * 2026-08-08: `connectSwarm({serverKey: <tabertron>})` issued ON stortron was
   * answered by STORTRON ITSELF 6 times out of 6. It asked itself for the
   * origin's release index, got its own, and every artifact fetch then failed
   * with "no holder" — a wrong ANSWER, not a transport error, so nothing looked
   * broken. resync-from-origin on the same path hung twice for 300 s.
   *
   * `opts.verify` closes that hole at the application layer, where identity
   * actually lives. It receives a connected Client and returns truthy to accept.
   * Rejected peers are destroyed and the wait continues until `timeout`, so a
   * caller reaches the intended daemon or fails loudly, never silently talks to
   * the wrong one. It is layered as a callback rather than a built-in `status`
   * check because hyper-svc is generic — which handler proves identity is the
   * consumer's business, and this stays compatible with servers of any version.
   *
   * @param {object} opts
   * @param {string|Buffer} opts.serverKey - rendezvous key; derives the topic
   * @param {string} [opts.topicSalt='pear-git-v3'] - salt for topic derivation
   * @param {object} [opts.swarm] - Hyperswarm constructor options (e.g. testnet bootstrap)
   * @param {number} [opts.timeout=30000] - total ms to find an ACCEPTED peer
   * @param {(client: Client) => Promise<boolean>} [opts.verify] - identity gate
   * @returns {Promise<Client>}
   */
  static async connectSwarm (opts = {}) {
    if (!opts.serverKey) throw new Error('connectSwarm requires opts.serverKey')
    const serverKey = typeof opts.serverKey === 'string'
      ? b4a.from(opts.serverKey, 'hex')
      : opts.serverKey
    const salt = opts.topicSalt || 'pear-git-v3'
    const topic = crypto.hash(b4a.concat([serverKey, b4a.from(salt)]))
    const timeout = opts.timeout || 30_000
    const verify = typeof opts.verify === 'function' ? opts.verify : null

    const swarm = new Hyperswarm(opts.swarm || {})
    const discovery = swarm.join(topic, { server: false, client: true })

    let rejected = 0
    let client = null
    try {
      client = await new Promise((resolve, reject) => {
        let settled = false
        // NOTE: onConnection stays attached for the swarm's whole life — it is
        // deliberately NOT removed here. Connections can still arrive after a
        // peer is accepted, and a NoiseSecretStream with no 'error' listener
        // throws on reset, so detaching left later arrivals unguarded and
        // crashed the process at teardown with ECONNRESET. The listener dies
        // with the swarm when the returned Client is closed.
        const finish = (fn, arg) => {
          if (settled) return
          settled = true
          clearTimeout(timer)
          fn(arg)
        }
        const timer = setTimeout(() => {
          finish(reject, new Error('swarm-rpc: connection timeout' +
            (rejected ? ' (' + rejected + ' peer(s) answered but failed verification — ' +
              'the requested serverKey is a topic, not an identity, so other peers on ' +
              'that topic can answer)' : '')))
        }, timeout)

        const onConnection = (c) => {
          // Routine, and load-bearing: a NoiseSecretStream with no 'error'
          // listener throws on ECONNRESET, and this path DESTROYS connections
          // by design (every peer that fails verification, plus any that arrive
          // after one is accepted). Without this the first rejected peer takes
          // the whole process down. SwarmTransport._onConnection takes the same
          // posture server-side.
          c.on('error', () => {})
          if (settled) { try { c.destroy() } catch {} ; return }
          const candidate = new Client({
            kind: 'swarm',
            swarm,
            conn: c,
            rpc: attachRpcClient(Protomux.from(c))
          })
          if (!verify) return finish(resolve, candidate)

          // Verified off the critical path: keep listening while this runs, so a
          // slow or lying peer cannot stall a good one behind it.
          Promise.resolve()
            .then(() => verify(candidate))
            .then((ok) => {
              if (ok) return finish(resolve, candidate)
              rejected++
              try { c.destroy() } catch {}
            })
            .catch(() => {
              rejected++
              try { c.destroy() } catch {}
            })
        }

        swarm.on('connection', onConnection)
        discovery.flushed().catch((err) => finish(reject, err))
      })
    } catch (err) {
      // Destroy the swarm on EVERY failure path. It used to be left running: a
      // Hyperswarm holds the event loop open, so each failed connect leaked one
      // and the process never exited. That is what hung pear-git-v3's
      // basic.test.js when a mirror's origin was unreachable — 123/123 tests
      // passed, then the run never terminated.
      try { await swarm.destroy() } catch {}
      throw err
    }

    return client
  }

  constructor (opts) {
    this._kind = opts.kind
    this._sock = opts.sock || null
    this._base = opts.base || null
    this._swarm = opts.swarm || null
    this._conn = opts.conn || null
    this._rpc = opts.rpc || null
    this._closed = false

    // UDS pending request map (id → {resolve, reject})
    this._pending = new Map()
    this._nextId = 1

    if (this._kind === 'uds') {
      this._decoder = new FrameDecoder((frame) => this._onFrame(frame))
      this._sock.on('data', (chunk) => {
        try {
          this._decoder.push(chunk)
        } catch (err) {
          this._failAll(err)
          this._down()
        }
      })
      // EVENT-DRIVEN disconnect detection (fleet reconciliation contract). When the peer daemon
      // restarts (the common case: an OTA/`pgh app restart` of hpp/pgv3/etc.), the cached client's
      // socket dies. Previously 'close' only `_failAll`'d the pending map but NEVER set `_closed`,
      // and there was no 'end' handler at all — so `client.closed` stayed FALSE and long-lived
      // consumers (favela-web Writer, pgh sidecar lookups) kept handing back a DEAD client, whose
      // calls hang or reject "connection closed" forever with nothing to trigger a reconnect. Mark
      // the client CLOSED on close/end/error so `.closed` is truthy → consumers reconcile (reconnect
      // a fresh Client) on their next call. 'end' is load-bearing under bare-net (allowHalfOpen: on
      // peer-end it fires 'end' but not 'close'), so we destroy to force teardown — same posture as
      // the server-side half-open fix (hyper-svc 0.1.3).
      this._sock.on('close', () => this._down())
      this._sock.on('end', () => this._down())
      this._sock.on('error', () => this._down())
    }
  }

  get kind () { return this._kind }
  get closed () { return this._closed }

  /**
   * Make an RPC call. Throws on transport errors or remote handler errors.
   * @param {string} method
   * @param {any} [params]
   */
  async call (method, params = {}) {
    if (this._closed) throw new Error('client closed')

    if (this._kind === 'uds') return this._callUds(method, params)
    if (this._kind === 'http') return this._callHttp(method, params)
    if (this._kind === 'swarm') return this._rpc.call(method, params)
    throw new Error('unknown client kind: ' + this._kind)
  }

  _callUds (method, params) {
    const id = this._nextId++
    return new Promise((resolve, reject) => {
      this._pending.set(id, { resolve, reject })
      try {
        this._sock.write(encodeFrame({ id, method, params }))
      } catch (err) {
        this._pending.delete(id)
        reject(err)
      }
    })
  }

  _onFrame (frame) {
    if (frame == null || (typeof frame.id !== 'number' && typeof frame.id !== 'string')) {
      // Malformed response, can't match it to a caller
      return
    }
    const pending = this._pending.get(frame.id)
    if (!pending) return
    this._pending.delete(frame.id)

    if (frame.error) {
      pending.reject(new Error(frame.error))
    } else {
      pending.resolve(frame.result)
    }
  }

  _failAll (err) {
    for (const [, pending] of this._pending) pending.reject(err)
    this._pending.clear()
  }

  // The socket died (peer restarted / errored / half-open end). Mark the client CLOSED so any
  // consumer's `.closed` check reconnects, fail every in-flight call, and force teardown. Idempotent.
  _down () {
    if (this._closed) return
    this._closed = true
    this._failAll(new Error('connection closed'))
    if (this._sock) { try { this._sock.destroy() } catch {} }
  }

  async _callHttp (method, params) {
    const url = new URL(`${this._base}/rpc/${encodeURIComponent(method)}`)
    return new Promise((resolve, reject) => {
      const body = JSON.stringify(params)
      const req = http.request({
        method: 'POST',
        hostname: url.hostname,
        port: url.port || 80,
        path: url.pathname + url.search,
        headers: {
          'Content-Type': 'application/json',
          'Content-Length': b4a.byteLength(body)
        }
      }, (res) => {
        const parts = []
        res.on('data', (c) => parts.push(c))
        res.on('end', () => {
          const text = b4a.concat(parts).toString('utf8')
          let parsed
          try {
            parsed = JSON.parse(text)
          } catch {
            return reject(new Error(`bad JSON response (status ${res.statusCode}): ${text.slice(0, 200)}`))
          }
          if (res.statusCode >= 200 && res.statusCode < 300) {
            return resolve(parsed.result)
          }
          return reject(new Error(parsed.error || `HTTP ${res.statusCode}`))
        })
        res.on('error', reject)
      })
      req.on('error', reject)
      req.write(body)
      req.end()
    })
  }

  async close () {
    if (this._closed) return
    this._closed = true
    if (this._sock) {
      this._failAll(new Error('client closed'))
      try { this._sock.destroy() } catch {}
      this._sock = null
    }
    if (this._rpc) {
      try { this._rpc.close() } catch {}
      this._rpc = null
    }
    if (this._conn) {
      try { this._conn.destroy() } catch {}
      this._conn = null
    }
    if (this._swarm) {
      try { await this._swarm.destroy() } catch {}
      this._swarm = null
    }
  }
}

async function udsReachable (path) {
  const { backend, name, abstract } = await udsBackend(path)
  // Pathname sockets: verify the file exists and is actually a socket first.
  // Abstract sockets have no filesystem entry — skip straight to the connect probe.
  if (!abstract) {
    try {
      const s = await stat(path)
      if (!s.isSocket()) return false
    } catch {
      return false
    }
  }
  // Try a real connect — covers stale sockets where the daemon crashed
  return new Promise((resolve) => {
    const sock = backend.createConnection(name)
    sock.once('connect', () => {
      sock.destroy()
      resolve(true)
    })
    sock.once('error', () => {
      sock.destroy()
      resolve(false)
    })
  })
}
/**
 * Length-prefixed JSON framing.
 *
 * Wire format: [4 bytes BE length][JSON payload].
 *
 * One frame = one JSON object. Multiple frames can be pipelined on a single
 * stream — FrameDecoder handles incremental reads where a frame may arrive
 * across multiple data chunks.
 */

import b4a from 'b4a'

const MAX_FRAME = 16 * 1024 * 1024 // 16 MiB hard cap to avoid runaway buffers

export function encodeFrame (obj) {
  const json = JSON.stringify(obj)
  const payload = b4a.from(json, 'utf8')
  if (payload.length > MAX_FRAME) {
    throw new Error(`Frame too large: ${payload.length} > ${MAX_FRAME}`)
  }
  const frame = b4a.alloc(4 + payload.length)
  frame.writeUInt32BE(payload.length, 0)
  payload.copy(frame, 4)
  return frame
}

export class FrameDecoder {
  /**
   * @param {(obj: any) => void} onFrame - called once per complete frame
   */
  constructor (onFrame) {
    if (typeof onFrame !== 'function') throw new Error('onFrame is required')
    this._onFrame = onFrame
    this._buf = b4a.alloc(0)
  }

  /**
   * Feed a chunk into the decoder. Calls onFrame for each complete frame.
   * Throws if a frame exceeds MAX_FRAME or contains invalid JSON.
   */
  push (chunk) {
    this._buf = b4a.concat([this._buf, chunk])

    while (this._buf.length >= 4) {
      const len = this._buf.readUInt32BE(0)
      if (len > MAX_FRAME) {
        throw new Error(`Frame too large: ${len} > ${MAX_FRAME}`)
      }
      if (this._buf.length < 4 + len) break // wait for more bytes

      const payload = this._buf.subarray(4, 4 + len)
      this._buf = this._buf.subarray(4 + len)

      const json = b4a.toString(payload, 'utf8')
      const obj = JSON.parse(json) // throws on bad JSON
      this._onFrame(obj)
    }
  }

  /** Number of bytes currently buffered (waiting for the rest of a frame). */
  get pending () { return this._buf.length }
}
/**
 * Service — reusable per-app daemon library.
 *
 * One instance per app process. Owns:
 *   - Generic RPC handler registry (svc.handle)
 *   - Module mounts (svc.mount) with optional swarm replication
 *   - UDS, HTTP, and Hyperswarm transport instances (whichever the consumer enables)
 *
 * The consumer's corestore is passed in (or one is implied via swarm.corestore).
 * The Service does NOT create or own storage — that's the app's job.
 *
 * Local-only RPC. Peers exchange data via swarm replication, never commands.
 *
 * Usage:
 *
 *   const svc = new Service({
 *     name: 'pear-git',
 *     corestore: store,
 *     uds: '/tmp/pear-git.sock',
 *     http: { port: 4040 },
 *     swarm: { topic: '...32 bytes hex...' }
 *   })
 *
 *   svc.mount('orgs', new HyperOrgs(store, { namespace: 'orgs' }))
 *
 *   svc.handle('list-orgs', async (ctx, params) => {
 *     return svc.modules.orgs.list()
 *   })
 *
 *   await svc.listen()
 */

import process from '#node:process'
import ReadyResource from 'ready-resource'
import { UdsServer } from './transports/uds.js'
import { HttpServer } from './transports/http.js'
import { SwarmTransport } from './transports/swarm.js'

class NoSuchMethodError extends Error {
  constructor (method) {
    super(`unknown method: ${method}`)
    this.code = 'ENOMETHOD'
  }
}

class AnonymousDeniedError extends Error {
  constructor (method) {
    super(`anonymous access denied: ${method}`)
    this.code = 'EDENIED'
    this.status = 403
  }
}

/**
 * Default "is this caller anonymous?" predicate.
 *
 * Deliberately conservative — anything that is not clearly an authenticated
 * caller counts as anonymous. Consumers whose ctx carries richer identity
 * (pear-git-v3 has four distinct shapes) should pass their own via
 * opts.isAnonymous rather than widen this one.
 */
function defaultIsAnonymous (ctx) {
  if (!ctx) return true
  if (ctx.transport === 'uds') return false // local operator holds the socket
  return !ctx.identity
}

export class Service extends ReadyResource {
  /**
   * @param {object} opts
   * @param {string} opts.name - service name (used for default UDS path, logging)
   * @param {object} [opts.corestore] - required if swarm transport is enabled
   * @param {string} [opts.uds] - UDS socket path. Pass null/undefined to disable.
   * @param {object} [opts.http] - HTTP transport options { port, host }. Disable by omitting.
   * @param {object} [opts.swarm] - Swarm options { topic, swarm? }. Disable by omitting.
   */
  constructor (opts = {}) {
    super()
    if (!opts.name) throw new Error('Service requires opts.name')

    this._name = opts.name
    this._corestore = opts.corestore || null
    this._handlers = new Map()
    this._mounts = new Map()

    // Anonymous-dispatch policy (pear-git org #12).
    //
    // Every registered handler used to be callable by anyone, over HTTP and
    // over swarm-rpc, with no allowlist and no auth gate — so each new
    // svc.handle() was silently world-callable, and a daemon behind a public
    // reverse proxy exposed its entire RPC surface to the internet.
    //
    // Default stays 'allow' so the existing consumers (pear-git-v3, hypernote,
    // hyper-social-web, pgh-sidecar) are untouched until they opt in. Under
    // 'deny', a handler must declare `{ anonymous: true }` at registration to
    // be reachable by an unauthenticated caller.
    //
    // Opt-in at REGISTRATION rather than via a separate allowlist table: with
    // ~100 handlers a table drifts out of step with the handler set, whereas a
    // flag cannot. And the drift direction is safe — a handler nobody marked
    // is DENIED, which surfaces as a visible 403 rather than a silent hole.
    this._anonymousPolicy = opts.anonymousPolicy === 'deny' ? 'deny' : 'allow'
    this._isAnonymous = typeof opts.isAnonymous === 'function'
      ? opts.isAnonymous
      : defaultIsAnonymous
    // Called with ({ method, ctx }) whenever a dispatch is refused, so the
    // consumer can record denials alongside its own audit trail.
    this._onDeny = typeof opts.onDeny === 'function' ? opts.onDeny : null
    this._anonymousAllowed = new Set()

    this._udsOpt = opts.uds || null
    this._httpOpt = opts.http || null
    this._swarmOpt = opts.swarm || null

    this._uds = null
    this._http = null
    this._swarm = null

    if (this._swarmOpt && !this._corestore) {
      throw new Error('Service: swarm transport requires opts.corestore')
    }

    // Instantiate transports eagerly so apps can register HTTP routes,
    // grab the UDS path, etc., BEFORE calling listen().
    const dispatch = (method, params, ctx) => this.dispatch(method, params, ctx)

    if (this._udsOpt) {
      this._uds = new UdsServer({ path: this._udsOpt, dispatch })
    }
    if (this._httpOpt) {
      this._http = new HttpServer({
        port: this._httpOpt.port,
        host: this._httpOpt.host,
        prefix: this._httpOpt.prefix,
        ctxFactory: this._httpOpt.ctxFactory,
        dispatch
      })
    }
    if (this._swarmOpt) {
      this._swarm = new SwarmTransport({
        topic: this._swarmOpt.topic,
        corestore: this._corestore,
        mounts: () => this._listMounts(),
        dispatch: this._swarmOpt.rpc !== false ? dispatch : null,
        swarm: this._swarmOpt.swarm,
        server: this._swarmOpt.server,
        client: this._swarmOpt.client
      })
    }
  }

  // ── Properties ──────────────────────────────────────────────

  get name () { return this._name }
  get corestore () { return this._corestore }

  /** Read-only handle to the UDS transport (or null if disabled). */
  get uds () { return this._uds }

  /** Read-only handle to the HTTP transport (or null if disabled). */
  get http () { return this._http }

  /** Read-only handle to the swarm transport (or null if disabled). */
  get swarm () { return this._swarm }

  /**
   * Mounted modules, accessible by name. Use `svc.modules.orgs` after
   * `svc.mount('orgs', orgsInstance)`.
   */
  get modules () {
    // Lazily build a property-style accessor object on top of the map
    if (!this._modulesProxy) {
      const map = this._mounts
      this._modulesProxy = new Proxy({}, {
        get (_target, prop) {
          const m = map.get(prop)
          return m ? m.instance : undefined
        },
        has (_target, prop) {
          return map.has(prop)
        },
        ownKeys () {
          return Array.from(map.keys())
        },
        getOwnPropertyDescriptor (_target, prop) {
          if (map.has(prop)) {
            return { enumerable: true, configurable: true, value: map.get(prop).instance }
          }
        }
      })
    }
    return this._modulesProxy
  }

  /** Map iteration: list mount entries as { name, instance }. */
  _listMounts () {
    const out = []
    for (const [name, m] of this._mounts) out.push({ name, instance: m.instance })
    return out
  }

  // ── Registration ────────────────────────────────────────────

  /**
   * Register an RPC handler. The handler is invoked from any RPC transport
   * with `(ctx, params)` and should return a JSON-serializable result.
   *
   * @param {string} name - method name (e.g. "list-orgs")
   * @param {(ctx: object, params: any) => Promise<any>|any} fn
   */
  handle (name, fn, opts = {}) {
    if (typeof name !== 'string' || !name) throw new Error('handle requires a name')
    if (typeof fn !== 'function') throw new Error('handle requires a function')
    if (this._handlers.has(name)) throw new Error(`handler "${name}" already registered`)
    this._handlers.set(name, fn)
    // `anonymous: true` opts this method IN to unauthenticated dispatch when
    // the service runs anonymousPolicy: 'deny'. Absent = denied, which is the
    // safe default for a handler nobody has classified yet.
    if (opts && opts.anonymous === true) this._anonymousAllowed.add(name)
  }

  /** Is this method callable by an unauthenticated caller? */
  allowsAnonymous (name) { return this._anonymousAllowed.has(name) }

  /** Methods explicitly opted in to anonymous dispatch, sorted. */
  listAnonymous () { return Array.from(this._anonymousAllowed).sort() }

  /** Whether a handler is registered. */
  hasHandler (name) { return this._handlers.has(name) }

  /** List registered handler names. */
  listHandlers () { return Array.from(this._handlers.keys()).sort() }

  /**
   * Mount a module instance. Modules are accessible via `svc.modules.<name>`.
   * If the module exposes a `.base` (Autobase consumer) and the swarm
   * transport is enabled, the base is replicated on every swarm connection.
   *
   * @param {string} name
   * @param {object} instance
   */
  mount (name, instance) {
    if (typeof name !== 'string' || !name) throw new Error('mount requires a name')
    if (!instance) throw new Error('mount requires an instance')
    if (this._mounts.has(name)) throw new Error(`mount "${name}" already registered`)
    this._mounts.set(name, { instance })
  }

  /** Whether a module is mounted. */
  hasMount (name) { return this._mounts.has(name) }

  /** List mounted module names. */
  listMounts () { return Array.from(this._mounts.keys()).sort() }

  // ── Dispatch ────────────────────────────────────────────────

  /**
   * Dispatch a method call to its handler. Used by all RPC transports.
   * Throws NoSuchMethodError (code: 'ENOMETHOD') if the method isn't registered.
   */
  async dispatch (method, params, ctx) {
    const handler = this._handlers.get(method)
    if (!handler) throw new NoSuchMethodError(method)

    // Anonymous gate (#12). Runs for EVERY transport, because the surface was
    // open on all of them — HTTP via a public reverse proxy, and swarm-rpc to
    // any peer that knows the topic.
    //
    // Ordered after the ENOMETHOD check on purpose: an unknown method should
    // still say so, otherwise the gate turns every typo into a 403 and makes
    // the API undebuggable. It leaks only which method names exist, which the
    // handler list already exposes.
    if (this._anonymousPolicy === 'deny' && !this._anonymousAllowed.has(method)) {
      let anon = true
      try {
        anon = this._isAnonymous(ctx)
      } catch {
        anon = true // a predicate that throws must fail CLOSED
      }
      if (anon) {
        if (this._onDeny) {
          try { this._onDeny({ method, ctx, reason: 'anonymous' }) } catch {}
        }
        throw new AnonymousDeniedError(method)
      }
    }

    return handler(ctx || {}, params)
  }

  // ── Lifecycle ───────────────────────────────────────────────

  async _open () {
    if (this._uds) await this._uds.listen()
    if (this._http) await this._http.listen()
    if (this._swarm) await this._swarm.listen()
  }

  /**
   * Alias for `ready()` — feels more natural for a daemon ("start listening").
   */
  async listen () {
    await this.ready()
  }

  async _close () {
    const errors = []
    if (this._swarm) try { await this._swarm.close() } catch (e) { errors.push(e) }
    if (this._http) try { await this._http.close() } catch (e) { errors.push(e) }
    if (this._uds) try { await this._uds.close() } catch (e) { errors.push(e) }
    this._swarm = null
    this._http = null
    this._uds = null
    if (errors.length) {
      const msg = errors.map(e => e.message).join('; ')
      throw new Error('Service close errors: ' + msg)
    }
  }
}
/**
 * HTTP transport for hyper-svc.
 *
 * Local-only RPC. Browsers (or curl, or any HTTP client) on the same machine
 * POST a JSON body to /rpc/<method> and receive a JSON response.
 *
 * Wire protocol:
 *   POST /rpc/<method>
 *   Content-Type: application/json
 *   { ...params... }
 *
 *   →  200 application/json  { result: ... }
 *      400 application/json  { error: ... }   (bad request / handler threw)
 *      404 application/json  { error: 'unknown method' }
 *
 * Other routes are NOT handled by hyper-svc — apps wire their own SSR pages
 * via the underlying http.Server (exposed as `.server` on this class). Any
 * request not matching POST /rpc/<method> falls through to user-registered
 * 'request' listeners or, if none, returns 404.
 */

import http from '#node:http'
import b4a from 'b4a'

export class HttpServer {
  /**
   * @param {object} opts
   * @param {number} [opts.port=0] - 0 = random port
   * @param {string} [opts.host='127.0.0.1'] - bind address (local-only by default)
   * @param {string} [opts.prefix=''] - URL prefix to strip before matching /rpc/* (e.g. '/git')
   * @param {(method: string, params: any, ctx: object) => Promise<any>} opts.dispatch - request handler
   */
  constructor (opts = {}) {
    if (typeof opts.dispatch !== 'function') throw new Error('HttpServer requires opts.dispatch')

    this._port = opts.port || 0
    this._host = opts.host || '127.0.0.1'
    this._dispatch = opts.dispatch
    // Optional URL prefix (e.g. '/git') stripped before matching /rpc/*. Set
    // when the daemon is reverse-proxied OR accessed directly under a path
    // prefix that the browser bakes into outgoing fetch URLs. Without this,
    // direct (non-proxied) hits to `<host>/<prefix>/rpc/*` fall through both
    // hyper-svc's listener (which only matches '/rpc/') and the consumer's
    // listener (which strips the prefix and skips '/rpc/' assuming hyper-svc
    // already handled it) — neither responds and the request hangs.
    this._prefix = normalizePrefix(opts.prefix)
    // Optional consumer-provided ctx builder. Called per /rpc/* request to
    // populate fields like identity from request headers/cookies. Receives
    // (req) and may return either an object or a Promise<object>. The
    // returned fields are merged into the default ctx ({ transport: 'http',
    // identity: null, req, res }).
    this._ctxFactory = typeof opts.ctxFactory === 'function' ? opts.ctxFactory : null
    this._listening = false

    // Create the server eagerly so apps can register routes BEFORE listen().
    // Our /rpc/* listener is installed first so it has first dibs on requests.
    this._server = http.createServer()
    this._server.on('request', (req, res) => this._onRequest(req, res))
  }

  /**
   * Update or set the ctxFactory after construction. Useful when the
   * factory needs references that don't exist at constructor time
   * (e.g. session stores created by the consumer in a later step).
   */
  setCtxFactory (fn) {
    if (fn != null && typeof fn !== 'function') {
      throw new Error('ctxFactory must be a function or null')
    }
    this._ctxFactory = fn
  }

  /** Underlying http.Server. Apps register their own routes here. */
  get server () { return this._server }
  get listening () { return this._listening }
  get port () {
    if (!this._listening || !this._server) return null
    const addr = this._server.address()
    return addr ? addr.port : null
  }
  get host () { return this._host }

  async listen () {
    if (this._listening) return

    await new Promise((resolve, reject) => {
      this._server.once('error', reject)
      this._server.listen(this._port, this._host, () => {
        this._server.removeListener('error', reject)
        resolve()
      })
    })

    this._listening = true
  }

  async _onRequest (req, res) {
    // Compute the path with the configured prefix removed. Don't mutate
    // req.url — consumers' own request listeners may have their own
    // prefix-stripping logic and should see the original.
    let path = req.url
    if (this._prefix && path.startsWith(this._prefix)) {
      const rest = path.slice(this._prefix.length)
      // Only treat as a prefix match when the next char is '/' (or end of
      // URL). Otherwise '/gitfoo' would falsely match prefix '/git'.
      if (rest === '' || rest[0] === '/' || rest[0] === '?') {
        path = rest || '/'
      }
    }

    if (req.method === 'POST' && path.startsWith('/rpc/')) {
      const method = path.slice('/rpc/'.length).split('?')[0]
      let body
      try {
        body = await collectBody(req)
      } catch (err) {
        return jsonError(res, 400, 'failed to read body: ' + err.message)
      }

      let params = {}
      if (body.length > 0) {
        try {
          params = JSON.parse(b4a.toString(body, 'utf8'))
        } catch {
          return jsonError(res, 400, 'request body must be JSON')
        }
      }

      let ctx = {
        transport: 'http',
        identity: null, // anonymous by default — apps populate via ctxFactory
        req,
        res
      }

      if (this._ctxFactory) {
        try {
          const extra = await this._ctxFactory(req)
          if (extra && typeof extra === 'object') {
            ctx = { ...ctx, ...extra }
          }
        } catch (err) {
          return jsonError(res, 500, 'ctxFactory failed: ' + (err.message || String(err)))
        }
      }

      try {
        const result = await this._dispatch(method, params, ctx)
        if (result === undefined) {
          return jsonOk(res, { result: null })
        }
        return jsonOk(res, { result })
      } catch (err) {
        if (err && err.code === 'ENOMETHOD') {
          return jsonError(res, 404, err.message)
        }
        // An anonymous-gate denial is an authorization outcome, not a bad
        // request — surface it as 403 so callers (and the audit trail) can
        // tell "you may not" from "you sent nonsense".
        if (err && err.code === 'EDENIED') {
          return jsonError(res, err.status || 403, err.message)
        }
        return jsonError(res, 400, err.message || String(err))
      }
    }

    // Not an /rpc/ request. App-owned routes live in OTHER 'request'
    // listeners (registered on this._server by the consumer). If at least
    // one other listener is present, leave the response to them — they're
    // responsible for handling and 404-ing as needed.
    //
    // If we're the ONLY 'request' listener, nobody else will handle this,
    // so we 404 it synchronously. Doing this synchronously avoids a race
    // where setImmediate fires before an async user handler can respond.
    if (this._server.listenerCount('request') <= 1) {
      res.writeHead(404, { 'Content-Type': 'text/plain' })
      res.end('Not found')
    }
    // Otherwise: leave the response to the user's listener.
  }

  async close () {
    if (!this._server || !this._listening) {
      this._listening = false
      return
    }
    await new Promise((resolve) => this._server.close(() => resolve()))
    this._listening = false
  }
}

function collectBody (req) {
  return new Promise((resolve, reject) => {
    const parts = []
    req.on('data', (c) => parts.push(c))
    req.on('end', () => resolve(b4a.concat(parts)))
    req.on('error', reject)
  })
}

function jsonOk (res, body) {
  res.writeHead(200, { 'Content-Type': 'application/json' })
  res.end(JSON.stringify(body))
}

function jsonError (res, status, message) {
  res.writeHead(status, { 'Content-Type': 'application/json' })
  res.end(JSON.stringify({ error: message }))
}

function normalizePrefix (p) {
  if (!p || typeof p !== 'string') return ''
  // Strip trailing slashes so '/git/' and '/git' behave identically.
  let s = p.replace(/\/+$/, '')
  // A bare '/' is not a real prefix.
  if (s === '' || s === '/') return ''
  // Require a leading slash so callers can't accidentally pass 'git'.
  if (s[0] !== '/') s = '/' + s
  return s
}
/**
 * Swarm-RPC transport for hyper-svc.
 *
 * Adds a Protomux RPC channel on every Hyperswarm connection. Requests
 * and responses use the same length-prefixed JSON framing as UDS (see
 * frame.js), multiplexed over the Noise-encrypted swarm stream.
 *
 * This transport extends the existing SwarmTransport (replication) with
 * request/response dispatch. A single swarm connection carries:
 *   1. Hypercore/Autobase replication (corestore.replicate)
 *   2. Module mux channels (attachProtocol)
 *   3. RPC frames (this module)
 *
 * Wire protocol over Protomux:
 *   Channel: 'hyper-svc-rpc'
 *   Message type 0 (request):  { id, method, params }
 *   Message type 1 (response): { id, result } | { id, error }
 *
 * Auth: the caller's Noise public key is available on the connection.
 * For pear-git-v3, envelope auth (Phase 2a) is layered on top — the
 * RPC payload itself is a signed envelope, verified by the dispatch
 * handler. The transport just provides the Noise tunnel.
 */

import Protomux from 'protomux'
import c from 'compact-encoding'
import b4a from 'b4a'

const PROTOCOL = 'hyper-svc-rpc'

/**
 * Attach an RPC channel to a Protomux instance (one per swarm connection).
 *
 * Server-side: receives requests, calls dispatch, sends responses.
 *
 * @param {Protomux} mux — the protomux for this connection
 * @param {Function} dispatch — (method, params, ctx) => result
 * @param {object} [opts]
 * @param {Buffer} [opts.remotePublicKey] — peer's Noise pubkey (for ctx)
 * @returns {{ channel, close: () => void }}
 */
export function attachRpcServer (mux, dispatch, opts = {}) {
  const channel = mux.createChannel({
    protocol: PROTOCOL,
    onopen () {},
    onclose () {}
  })

  if (!channel) return null // protocol already claimed on this mux

  const requestType = channel.addMessage({
    encoding: c.json,
    onmessage (msg) {
      handleRequest(msg, channel, responseType, dispatch, opts)
    }
  })

  const responseType = channel.addMessage({
    encoding: c.json,
    onmessage () {} // server doesn't receive responses
  })

  channel.open()

  return { channel, close: () => channel.close() }
}

/**
 * Attach an RPC channel to a Protomux instance (client-side).
 *
 * Client-side: sends requests, receives responses.
 *
 * @param {Protomux} mux
 * @returns {{ call: (method, params) => Promise<any>, close: () => void }}
 */
export function attachRpcClient (mux) {
  let nextId = 1
  const pending = new Map() // id → { resolve, reject }

  const channel = mux.createChannel({
    protocol: PROTOCOL,
    onopen () {},
    onclose () {
      // Reject all pending calls on channel close.
      for (const [id, p] of pending) {
        p.reject(new Error('swarm-rpc channel closed'))
        pending.delete(id)
      }
    }
  })

  if (!channel) throw new Error('swarm-rpc: protocol already claimed')

  const requestType = channel.addMessage({
    encoding: c.json,
    onmessage () {} // client doesn't receive requests
  })

  const responseType = channel.addMessage({
    encoding: c.json,
    onmessage (msg) {
      const p = pending.get(msg.id)
      if (!p) return // stale or unknown id
      pending.delete(msg.id)
      if (msg.error) {
        const err = new Error(msg.error)
        err.code = msg.code || null
        p.reject(err)
      } else {
        p.resolve(msg.result)
      }
    }
  })

  channel.open()

  return {
    call (method, params) {
      return new Promise((resolve, reject) => {
        const id = nextId++
        pending.set(id, { resolve, reject })
        requestType.send({ id, method, params })
      })
    },
    close () {
      channel.close()
    }
  }
}

// --- internals ---

async function handleRequest (msg, channel, responseType, dispatch, opts) {
  const { id, method, params } = msg
  if (!id || !method) {
    responseType.send({ id: id || 0, error: 'invalid request (missing id or method)' })
    return
  }

  const ctx = {
    transport: 'swarm-rpc',
    identity: {
      type: 'swarm',
      remotePublicKey: opts.remotePublicKey
        ? b4a.toString(opts.remotePublicKey, 'hex')
        : null,
      trust: 'network'
    }
  }

  try {
    const result = await dispatch(method, params || {}, ctx)
    responseType.send({ id, result: result !== undefined ? result : null })
  } catch (err) {
    responseType.send({
      id,
      error: err.message || String(err),
      code: err.code || null
    })
  }
}
/**
 * Hyperswarm transport for hyper-svc.
 *
 * Joins a topic, and on every connection:
 *   1. corestore.replicate(conn) — replicates all hypercores in the corestore
 *   2. for each mounted module exposing a `.base` (Autobase consumer), also
 *      base.replicate(conn) — belt-and-suspenders against the autobase
 *      replication gotcha (corestore.replicate alone is unreliable in tests
 *      and we don't want to chase that bug in production)
 *   3. for each mounted module exposing `attachProtocol(mux)` (mux-based
 *      protocols like hyper-overlay), lazily build `Protomux.from(conn)`
 *      once per connection and call attachProtocol on each consumer.
 *      Protomux.from reuses any protomux already attached by corestore/autobase
 *      replication, so channels multiplex cleanly over the same transport.
 *
 * No RPC over swarm today — modules communicate either via replication or
 * via their own mux channels. Adding a new mux-based protocol only requires
 * exposing `attachProtocol(mux)` on the mounted module.
 */

import Hyperswarm from 'hyperswarm'
import Protomux from 'protomux'
import b4a from 'b4a'
import { attachRpcServer } from './swarm-rpc.js'

export class SwarmTransport {
  /**
   * @param {object} opts
   * @param {Buffer|string} opts.topic - 32-byte topic to join (hex string or buffer)
   * @param {object} opts.corestore - corestore to replicate
   * @param {() => Iterable<{ name: string, instance: object }>} opts.mounts - returns the current mount list (called on each connection so late mounts work)
   * @param {Function} [opts.dispatch] - RPC dispatch function. When provided, a swarm-RPC Protomux channel is attached to every connection.
   * @param {object} [opts.swarm] - hyperswarm options (e.g., bootstrap nodes for testnet)
   * @param {boolean} [opts.server=true]
   * @param {boolean} [opts.client=true]
   */
  constructor (opts = {}) {
    if (!opts.topic) throw new Error('SwarmTransport requires opts.topic')
    if (!opts.corestore) throw new Error('SwarmTransport requires opts.corestore')
    if (typeof opts.mounts !== 'function') throw new Error('SwarmTransport requires opts.mounts (function)')

    this._topic = typeof opts.topic === 'string' ? b4a.from(opts.topic, 'hex') : opts.topic
    if (this._topic.length !== 32) throw new Error('topic must be 32 bytes')

    this._corestore = opts.corestore
    this._getMounts = opts.mounts
    this._dispatch = opts.dispatch || null
    this._swarmOpts = opts.swarm || {}
    this._joinAsServer = opts.server !== false
    this._joinAsClient = opts.client !== false

    this._swarm = null
    this._discovery = null
    this._listening = false
    this._connections = new Set()
  }

  get topic () { return this._topic }
  get listening () { return this._listening }
  get swarm () { return this._swarm }
  get connections () { return this._connections.size }

  async listen () {
    if (this._listening) return

    this._swarm = new Hyperswarm(this._swarmOpts)
    this._swarm.on('connection', (conn, info) => this._onConnection(conn, info))

    this._discovery = this._swarm.join(this._topic, {
      server: this._joinAsServer,
      client: this._joinAsClient
    })
    await this._discovery.flushed()
    this._listening = true
  }

  /**
   * Join an ADDITIONAL topic on this same shared swarm (Keet activateRoom
   * pattern — one Hyperswarm, many topics). Used to rendezvous for a
   * specific room (per-org / per-repo autobase) by its discoveryKey, so
   * peers find each other for that room without needing the daemon's
   * identity topic. Replication still rides the single `_onConnection`
   * (corestore.replicate + per-mount replicate). Deduped + idempotent.
   *
   * @param {Buffer|string} topic - 32-byte discoveryKey (hex or buffer)
   * @param {object} [opts] - { server=true, client=true }
   * @returns {object|null} the PeerDiscovery handle (or existing one)
   */
  joinTopic (topic, opts = {}) {
    if (!this._swarm) return null // not listening yet
    const t = typeof topic === 'string' ? b4a.from(topic, 'hex') : topic
    if (!t || t.length !== 32) return null
    const key = b4a.toString(t, 'hex')
    if (!this._extraTopics) this._extraTopics = new Map()
    if (this._extraTopics.has(key)) return this._extraTopics.get(key)
    const { server = true, client = true } = opts
    const disc = this._swarm.join(t, { server, client })
    this._extraTopics.set(key, disc)
    return disc
  }

  /** discoveryKeys of every additional room topic joined via joinTopic. */
  get joinedRoomTopics () {
    return this._extraTopics ? Array.from(this._extraTopics.keys()) : []
  }

  _onConnection (conn, info) {
    this._connections.add(conn)
    conn.on('close', () => this._connections.delete(conn))
    conn.on('error', () => { /* connection errors are routine — ignore */ })

    // Always replicate the corestore. Hypercore handles muxing internally.
    try {
      this._corestore.replicate(conn)
    } catch (err) {
      // Don't crash on replication setup errors — log via stderr
      // eslint-disable-next-line no-console
      console.error('[hyper-svc/swarm] corestore.replicate failed:', err.message)
    }

    // Belt and suspenders: also call base.replicate on every mounted Autobase
    // consumer. This is the documented workaround for the test-time gotcha
    // where corestore.replicate alone doesn't propagate writer cores.
    //
    // In the same pass, wire up mux-based protocols: any mount exposing
    // `attachProtocol(mux)` (hyper-overlay and future consumers) gets attached
    // to a single Protomux per connection. Protomux.from reuses any protomux
    // corestore/autobase replication already set up.
    let mux = null
    for (const { name, instance } of this._getMounts()) {
      if (!instance) continue

      // A mount may expose `replicate(conn)` to replicate its own
      // autobase(s) — required for MULTI-autobase mounts (e.g. per-org
      // HyperOrgs) whose single `.base` getter is undefined or THROWS.
      // Otherwise fall back to the single-autobase `.base.replicate`.
      // The whole access is wrapped: a throwing `.base` getter must
      // never abort the daemon on an incoming connection.
      try {
        if (typeof instance.replicate === 'function') {
          instance.replicate(conn)
        } else {
          const base = instance.base
          if (base && typeof base.replicate === 'function') base.replicate(conn)
        }
      } catch (err) {
        // eslint-disable-next-line no-console
        console.error(`[hyper-svc/swarm] ${name} replicate failed:`, err.message)
      }

      if (typeof instance.attachProtocol === 'function') {
        if (!mux) {
          try {
            mux = Protomux.from(conn)
          } catch (err) {
            // eslint-disable-next-line no-console
            console.error('[hyper-svc/swarm] Protomux.from failed:', err.message)
          }
        }
        if (mux) {
          try {
            instance.attachProtocol(mux)
          } catch (err) {
            // eslint-disable-next-line no-console
            console.error(`[hyper-svc/swarm] ${name}.attachProtocol failed:`, err.message)
          }
        }
      }
    }

    // Swarm-RPC channel — attach only when dispatch is configured.
    // Multiplexes cleanly over the same Noise stream as replication
    // and module protocols above.
    if (this._dispatch) {
      if (!mux) {
        try {
          mux = Protomux.from(conn)
        } catch (err) {
          // eslint-disable-next-line no-console
          console.error('[hyper-svc/swarm] Protomux.from failed (rpc):', err.message)
        }
      }
      if (mux) {
        try {
          attachRpcServer(mux, this._dispatch, {
            remotePublicKey: conn.remotePublicKey || null
          })
        } catch (err) {
          // eslint-disable-next-line no-console
          console.error('[hyper-svc/swarm] attachRpcServer failed:', err.message)
        }
      }
    }
  }

  async close () {
    if (!this._swarm) return
    for (const conn of this._connections) {
      try { conn.destroy() } catch {}
    }
    this._connections.clear()
    try { await this._swarm.destroy() } catch {}
    this._swarm = null
    this._discovery = null
    this._listening = false
  }
}
/**
 * UDS (Unix Domain Socket) transport for hyper-svc.
 *
 * Local-only RPC. Trusts the local user. CLIs on the same machine connect
 * to ~/.local/share/<name>/svc.sock (or wherever the daemon was told to bind)
 * and exchange length-prefixed JSON frames.
 *
 * Wire protocol per connection:
 *   client → server: { id, method, params }
 *   server → client: { id, result }   OR   { id, error }
 *
 * Multiple in-flight requests are matched by id. Server is fully async —
 * a slow handler doesn't block other requests on the same connection.
 */

import process from '#node:process'
import { unlink, stat } from '#node:fs/promises'
import { encodeFrame, FrameDecoder } from '../frame.js'
import { udsBackend, isAbstract } from '../uds-backend.js'

export class UdsServer {
  /**
   * @param {object} opts
   * @param {string} opts.path - filesystem path for the UNIX socket
   * @param {(method: string, params: any, ctx: object) => Promise<any>} opts.dispatch - request handler
   */
  constructor (opts = {}) {
    if (!opts.path) throw new Error('UdsServer requires opts.path')
    if (typeof opts.dispatch !== 'function') throw new Error('UdsServer requires opts.dispatch')

    this._path = opts.path
    this._dispatch = opts.dispatch
    this._server = null
    this._connections = new Set()
    this._listening = false

    // Idle-connection reaper. `allowHalfOpen:false` + the end/error handlers
    // below clean up when a client CLOSES or EXITS. But a caller that opens a
    // connection and then neither closes it nor exits (a long-lived process
    // that forgets Client.close()) leaves the accepted socket ESTAB forever —
    // the OS never delivers an end/close the server can react to. Unbounded,
    // this grew pgh-sidecar to ~348k ESTAB unix sockets / ~22GB (2026-07-05).
    // Sweep and destroy connections idle past _idleTimeout with no request in
    // flight. Request/response callers reset the timer on every frame, so only
    // genuinely dead connections are reaped. Set idleTimeout:0 to disable.
    this._idleTimeout = opts.idleTimeout === undefined ? 120000 : opts.idleTimeout
    this._sweepTimer = null
  }

  get path () { return this._path }
  get listening () { return this._listening }

  async listen () {
    if (this._listening) return

    // Select the transport: #node:net for pathname sockets (unchanged), or
    // bare-abstract-socket for an '@'-prefixed abstract name. `name` is the
    // bind name with the '@' stripped.
    const { backend, name, abstract } = await udsBackend(this._path)

    // Best-effort cleanup of a stale socket FILE (server crashed without
    // unlinking). Abstract sockets have no filesystem entry (the kernel frees
    // the name when the socket closes), so this applies to pathname sockets only.
    if (!abstract) {
      // ONLY remove if it's actually a socket — never touch regular files / dirs.
      try {
        const s = await stat(this._path)
        if (s.isSocket()) {
          // Try to connect first — if a daemon is already running, refuse to clobber.
          const inUse = await this._probe()
          if (inUse) throw new Error(`socket ${this._path} is already in use`)
          await unlink(this._path)
        }
      } catch (err) {
        if (err.code !== 'ENOENT' && err.message.indexOf('already in use') === -1) {
          // stat failed for some reason other than missing — ignore, let listen() fail naturally
        }
        if (err.message && err.message.indexOf('already in use') !== -1) throw err
      }
    }

    // allowHalfOpen:false is CRITICAL. bare-net defaults it to true (unlike
    // Node), which means when a client disconnects the accepted socket never
    // sees 'end' and never releases — the fd AND its 64KB read buffer leak.
    // With false, peer disconnect surfaces as 'end', which _onConnection
    // turns into a destroy() so the socket fully closes. See the fd-leak that
    // grew pgh-sidecar to ~205k open sockets / 14GB RSS (2026-06-09).
    // (bare-abstract-socket honours the same allowHalfOpen:false on accept.)
    this._server = backend.createServer({ allowHalfOpen: false }, (sock) => this._onConnection(sock))

    await new Promise((resolve, reject) => {
      this._server.once('error', reject)
      this._server.listen(name, () => {
        this._server.removeListener('error', reject)
        resolve()
      })
    })

    this._listening = true

    if (this._idleTimeout > 0) {
      const sweepEvery = Math.max(1000, Math.min(30000, Math.floor(this._idleTimeout / 2)))
      this._sweepTimer = setInterval(() => this._reapIdle(), sweepEvery)
      // Don't let the reaper keep the process alive on its own.
      if (this._sweepTimer && typeof this._sweepTimer.unref === 'function') this._sweepTimer.unref()
    }
  }

  // Destroy connections idle past _idleTimeout with no request in flight.
  // destroy() fires 'close', which removes the socket from _connections.
  _reapIdle () {
    const now = Date.now()
    for (const sock of this._connections) {
      if ((sock._inflight || 0) > 0) continue
      if (now - (sock._lastActive || 0) > this._idleTimeout) {
        try { sock.destroy() } catch {}
      }
    }
  }

  async _probe () {
    const { backend, name } = await udsBackend(this._path)
    return new Promise((resolve) => {
      const sock = backend.createConnection(name)
      sock.once('connect', () => {
        sock.destroy()
        resolve(true)
      })
      sock.once('error', () => {
        sock.destroy()
        resolve(false)
      })
    })
  }

  _onConnection (sock) {
    this._connections.add(sock)
    sock._lastActive = Date.now()
    sock._inflight = 0
    sock.on('close', () => this._connections.delete(sock))

    // Peer closed their write side (client finished + disconnected). bare-net
    // does NOT emit 'close' on its own here — we must destroy() to release the
    // fd and drop the socket (and its read buffer) from _connections. Safe even
    // mid-dispatch: a late _handleRequest write is already wrapped in try/catch.
    sock.on('end', () => { try { sock.destroy() } catch {} })

    const decoder = new FrameDecoder((req) => this._handleRequest(sock, req))

    sock.on('data', (chunk) => {
      sock._lastActive = Date.now()
      try {
        decoder.push(chunk)
      } catch (err) {
        // Bad frame — close the connection rather than try to recover
        try { sock.destroy(err) } catch {}
      }
    })

    // Abrupt disconnect (ECONNRESET, or the client process killed / timed out
    // mid-request). bare-net does NOT emit 'close' on its own (see the 'end'
    // note above) — and unlike a clean FIN there is no 'end' either — so we
    // MUST destroy() here to release the fd + 64KB read buffer and drop the
    // socket from _connections. Without this, every abrupt client disconnect
    // leaks a half-open socket (the 0.1.3 'end'-only fix covered clean closes
    // but not this path — the cause of the 6645-socket accumulation seen when
    // a client hammers the UDS with timed-out/killed calls).
    sock.on('error', () => { try { sock.destroy() } catch {} })
  }

  async _handleRequest (sock, req) {
    const id = req && req.id
    if (typeof id !== 'number' && typeof id !== 'string') {
      // Malformed — best effort error response, but the client probably can't match it
      try {
        sock.write(encodeFrame({ id: null, error: 'request missing id' }))
      } catch {}
      return
    }

    const ctx = {
      transport: 'uds',
      identity: { type: 'local', userId: process.env.USER || null, trust: 'local' }
    }

    // Mark in-flight so the idle reaper never destroys a socket mid-dispatch,
    // even if the handler runs longer than _idleTimeout.
    sock._inflight = (sock._inflight || 0) + 1
    try {
      const result = await this._dispatch(req.method, req.params, ctx)
      try {
        sock.write(encodeFrame({ id, result }))
      } catch {}
    } catch (err) {
      try {
        sock.write(encodeFrame({ id, error: err.message || String(err) }))
      } catch {}
    } finally {
      sock._inflight = Math.max(0, (sock._inflight || 1) - 1)
      sock._lastActive = Date.now()
    }
  }

  async close () {
    if (!this._server) return
    if (this._sweepTimer) { clearInterval(this._sweepTimer); this._sweepTimer = null }
    for (const sock of this._connections) {
      try { sock.destroy() } catch {}
    }
    this._connections.clear()
    await new Promise((resolve) => this._server.close(() => resolve()))
    this._server = null
    this._listening = false

    // Clean up the socket file (best-effort). Abstract sockets have no fs entry.
    if (!isAbstract(this._path)) {
      try { await unlink(this._path) } catch {}
    }
  }
}
/**
 * UDS backend selection.
 *
 * A socket "path" beginning with '@' names a Linux ABSTRACT-namespace socket
 * (no filesystem entry) instead of a pathname socket. Abstract sockets are the
 * only UNIX-socket option when SELinux denies the shell domain from creating
 * pathname sockets — e.g. an unrooted Android phone (celltron) running the
 * daemon under proot, where bind(AF_UNIX, "/path.sock") returns EACCES.
 *
 * For every non-'@' path we use #node:net exactly as before — byte-for-byte
 * unchanged behavior. bare-abstract-socket is imported LAZILY (dynamic import,
 * only at the async call sites below) so pathname deployments never load the
 * native addon.
 */

import net from '#node:net'

let _abstract = null

async function loadAbstract () {
  if (_abstract === null) {
    const m = await import('bare-abstract-socket')
    _abstract = m.default || m
  }
  return _abstract
}

// True if `path` names an abstract-namespace socket (leading '@').
export function isAbstract (path) {
  return typeof path === 'string' && path.length > 1 && path[0] === '@'
}

// Resolve the transport backend + the name to bind/connect. The returned
// `backend` exposes net-compatible createServer(opts, onConnection) and
// createConnection(name). For abstract paths the leading '@' is stripped
// (bare-abstract-socket adds the actual leading NUL).
export async function udsBackend (path) {
  if (isAbstract(path)) {
    return { backend: await loadAbstract(), name: path.slice(1), abstract: true }
  }
  return { backend: net, name: path, abstract: false }
}
const { Pull, Push, HEADERBYTES, KEYBYTES, ABYTES } = require('sodium-secretstream')
const sodium = require('sodium-universal')
const crypto = require('hypercore-crypto')
const { Duplex, Writable, getStreamError } = require('streamx')
const b4a = require('b4a')
const Timeout = require('timeout-refresh')
const unslab = require('unslab')
const Bridge = require('./lib/bridge')
const Handshake = require('./lib/handshake')

const IDHEADERBYTES = HEADERBYTES + 32
const [NS_INITIATOR, NS_RESPONDER, NS_SEND] = crypto.namespace('hyperswarm/secret-stream', 3)
const MAX_ATOMIC_WRITE = 256 * 256 * 256 - 1

module.exports = class NoiseSecretStream extends Duplex {
  constructor(isInitiator, rawStream, opts = {}) {
    super({ mapWritable: toBuffer })

    if (typeof isInitiator !== 'boolean') {
      throw new Error('isInitiator should be a boolean')
    }

    this.noiseStream = this
    this.isInitiator = isInitiator
    this.rawStream = null

    this.publicKey = opts.publicKey || null
    this.remotePublicKey = opts.remotePublicKey || null
    this.handshakeHash = null
    this.connected = false
    this.keepAlive = opts.keepAlive || 0
    this.timeout = 0
    this.enableSend = opts.enableSend !== false

    // pointer for upstream to set data here if they want
    this.userData = null

    let openedDone = null
    this.opened = new Promise((resolve) => {
      openedDone = resolve
    })

    this.rawBytesWritten = 0
    this.rawBytesRead = 0

    // metadata used by 'hyperdht'
    this.relay = null
    this.puncher = null

    // unwrapped raw stream
    this._rawStream = null

    // handshake state
    this._handshake = null
    this._handshakePattern = opts.pattern || null
    this._handshakeDone = null

    // message parsing state
    this._state = 0
    this._len = 0
    this._tmp = 1
    this._message = null

    this._openedDone = openedDone
    this._startDone = null
    this._drainDone = null
    this._outgoingPlain = null
    this._outgoingWrapped = null
    this._utp = null
    this._setup = true
    this._ended = 2
    this._encrypt = null
    this._decrypt = null
    this._timeoutTimer = null
    this._keepAliveTimer = null
    this._sendState = null

    if (opts.autoStart !== false) this.start(rawStream, opts)

    // wiggle it to trigger open immediately (TODO add streamx option for this)
    this.resume()
    this.pause()
  }

  static keyPair(seed) {
    return Handshake.keyPair(seed)
  }

  static id(handshakeHash, isInitiator, id) {
    return streamId(handshakeHash, isInitiator, id)
  }

  setTimeout(ms) {
    if (!ms) ms = 0

    this._clearTimeout()
    this.timeout = ms

    if (!ms || this.rawStream === null) return

    this._timeoutTimer = Timeout.once(ms, destroyTimeout, this)
    this._timeoutTimer.unref()
  }

  setKeepAlive(ms) {
    if (!ms) ms = 0

    this._clearKeepAlive()

    this.keepAlive = ms

    if (!ms || this.rawStream === null) return

    this._keepAliveTimer = Timeout.on(ms, sendKeepAlive, this)
    this._keepAliveTimer.unref()
  }

  sendKeepAlive() {
    const empty = this.alloc(0)
    this.write(empty)
  }

  start(rawStream, opts = {}) {
    if (rawStream) {
      this.rawStream = rawStream
      this._rawStream = rawStream
      if (typeof this.rawStream.setContentSize === 'function') {
        this._utp = rawStream
      }
    } else {
      this.rawStream = new Bridge(this)
      this._rawStream = this.rawStream.reverse
    }

    this.rawStream.on('error', this._onrawerror.bind(this))
    this.rawStream.on('close', this._onrawclose.bind(this))

    this._startHandshake(opts.handshake, opts.keyPair || null)
    this._continueOpen(null)

    if (this.destroying) return

    if (opts.data) this._onrawdata(opts.data)
    if (opts.ended) this._onrawend()

    if (this.keepAlive > 0 && this._keepAliveTimer === null) {
      this.setKeepAlive(this.keepAlive)
    }

    if (this.timeout > 0 && this._timeoutTimer === null) {
      this.setTimeout(this.timeout)
    }
  }

  async flush() {
    if ((await this.opened) === false) return false
    if ((await Writable.drained(this)) === false) return false
    if (this.destroying) return false

    if (this.rawStream !== null && this.rawStream.flush) {
      return await this.rawStream.flush()
    }

    return true
  }

  _continueOpen(err) {
    if (err) this.destroy(err)
    if (this._startDone === null) return
    const done = this._startDone
    this._startDone = null
    this._open(done)
  }

  _onkeypairpromise(p) {
    const self = this
    const cont = this._continueOpen.bind(this)

    p.then(onkeypair, cont)

    function onkeypair(kp) {
      self._onkeypair(kp)
      cont(null)
    }
  }

  _onkeypair(keyPair) {
    const pattern = this._handshakePattern || 'XX'
    const remotePublicKey = this.remotePublicKey

    this._handshake = new Handshake(this.isInitiator, keyPair, remotePublicKey, pattern)
    this.publicKey = this._handshake.keyPair.publicKey
  }

  _startHandshake(handshake, keyPair) {
    if (handshake) {
      const { tx, rx, hash, publicKey, remotePublicKey } = handshake
      this._setupSecretStream(tx, rx, hash, publicKey, remotePublicKey)
      return
    }

    if (!keyPair) keyPair = Handshake.keyPair()

    if (typeof keyPair.then === 'function') {
      this._onkeypairpromise(keyPair)
    } else {
      this._onkeypair(keyPair)
    }
  }

  _onrawerror(err) {
    this.destroy(err)
  }

  _onrawclose() {
    if (this._ended !== 0) this.destroy()
  }

  _onrawdata(data) {
    let offset = 0

    if (this._timeoutTimer !== null) {
      this._timeoutTimer.refresh()
    }

    do {
      switch (this._state) {
        case 0: {
          while (this._tmp !== 0x1000000 && offset < data.byteLength) {
            const v = data[offset++]
            this._len += this._tmp * v
            this._tmp *= 256
          }

          if (this._tmp === 0x1000000) {
            this._tmp = 0
            this._state = 1
            const unprocessed = data.byteLength - offset
            if (unprocessed < this._len && this._utp !== null)
              this._utp.setContentSize(this._len - unprocessed)
          }

          break
        }

        case 1: {
          const missing = this._len - this._tmp
          const end = missing + offset

          if (this._message === null && end <= data.byteLength) {
            this._message = data.subarray(offset, end)
            offset += missing
            this._incoming()
            break
          }

          const unprocessed = data.byteLength - offset

          if (this._message === null) {
            this._message = b4a.allocUnsafe(this._len)
          }

          b4a.copy(data, this._message, this._tmp, offset)
          this._tmp += unprocessed

          if (end <= data.byteLength) {
            offset += missing
            this._incoming()
          } else {
            offset += unprocessed
          }

          break
        }
      }
    } while (offset < data.byteLength && !this.destroying)
  }

  _onrawend() {
    this._ended--
    this.push(null)
  }

  _onrawdrain() {
    const drain = this._drainDone
    if (drain === null) return
    this._drainDone = null
    drain()
  }

  _read(cb) {
    this.rawStream.resume()
    cb(null)
  }

  _incoming() {
    const message = this._message

    this._state = 0
    this._len = 0
    this._tmp = 1
    this._message = null

    if (this._setup === true) {
      if (this._handshake) {
        this._onhandshakert(this._handshake.recv(message))
      } else {
        if (message.byteLength !== IDHEADERBYTES) {
          this.destroy(new Error('Invalid header message received'))
          return
        }

        const remoteId = message.subarray(0, 32)
        const expectedId = streamId(this.handshakeHash, !this.isInitiator)
        const header = message.subarray(32)

        if (!b4a.equals(expectedId, remoteId)) {
          this.destroy(new Error('Invalid header received'))
          return
        }

        this._decrypt.init(header)
        this._setup = false // setup is now done
      }
      return
    }

    if (message.byteLength < ABYTES) {
      this.destroy(new Error('Invalid message received'))
      return
    }

    this.rawBytesRead += message.byteLength

    const plain = message.subarray(1, message.byteLength - ABYTES + 1)

    try {
      this._decrypt.next(message, plain)
    } catch (err) {
      this.destroy(err)
      return
    }

    // If keep alive is selective, eat the empty buffers (ie assume the other side has it enabled also)
    if (plain.byteLength === 0 && this.keepAlive !== 0) return

    if (this.push(plain) === false) {
      this.rawStream.pause()
    }
  }

  _onhandshakert(h) {
    if (this._handshakeDone === null) return

    if (h !== null) {
      if (h.data) this._rawStream.write(h.data)
      if (!h.tx) return
    }

    const done = this._handshakeDone
    const publicKey = this._handshake.keyPair.publicKey

    this._handshakeDone = null
    this._handshake = null

    if (h === null) return done(new Error('Noise handshake failed'))

    this._setupSecretStream(h.tx, h.rx, h.hash, publicKey, h.remotePublicKey)
    this._resolveOpened(true)
    done(null)
  }

  _setupSecretStream(tx, rx, handshakeHash, publicKey, remotePublicKey) {
    const buf = b4a.allocUnsafeSlow(3 + IDHEADERBYTES)
    writeUint24le(IDHEADERBYTES, buf)

    this._encrypt = new Push(unslab(tx.subarray(0, KEYBYTES)), undefined, buf.subarray(3 + 32))
    this._decrypt = new Pull(unslab(rx.subarray(0, KEYBYTES)))

    this.publicKey = publicKey
    this.remotePublicKey = remotePublicKey
    this.handshakeHash = handshakeHash

    const id = buf.subarray(3, 3 + 32)
    streamId(handshakeHash, this.isInitiator, id)

    // initialize secretbox state for unordered messages
    this._setupSecretSend(handshakeHash)

    this.emit('handshake')
    // if rawStream is a bridge, also emit it there
    if (this.rawStream !== this._rawStream) this.rawStream.emit('handshake')

    if (this.destroying) return

    this._rawStream.write(buf)
  }

  _setupSecretSend(handshakeHash) {
    this._sendState = b4a.allocUnsafeSlow(32 + 32 + 8 + 8)
    const encrypt = this._sendState.subarray(0, 32) // secrets
    const decrypt = this._sendState.subarray(32, 64)
    const counter = this._sendState.subarray(64, 72) // nonce
    const initial = this._sendState.subarray(72)

    const inputs = this.isInitiator
      ? [
          [NS_INITIATOR, NS_SEND],
          [NS_RESPONDER, NS_SEND]
        ]
      : [
          [NS_RESPONDER, NS_SEND],
          [NS_INITIATOR, NS_SEND]
        ]

    sodium.crypto_generichash_batch(encrypt, inputs[0], handshakeHash)
    sodium.crypto_generichash_batch(decrypt, inputs[1], handshakeHash)

    sodium.randombytes_buf(initial)
    counter.set(initial)
  }

  _open(cb) {
    // no autostart or no handshake yet
    if (this._rawStream === null || (this._handshake === null && this._encrypt === null)) {
      this._startDone = cb
      return
    }

    this._rawStream.on('data', this._onrawdata.bind(this))
    this._rawStream.on('end', this._onrawend.bind(this))
    this._rawStream.on('drain', this._onrawdrain.bind(this))

    if (this.enableSend) this._rawStream.on('message', this._onmessage.bind(this))

    if (this._encrypt !== null) {
      this._resolveOpened(true)
      return cb(null)
    }

    this._handshakeDone = cb

    if (this.isInitiator) this._onhandshakert(this._handshake.send())
  }

  _predestroy() {
    if (this.rawStream) {
      const error = getStreamError(this)
      this.rawStream.destroy(error)
    }

    if (this._startDone !== null) {
      const done = this._startDone
      this._startDone = null
      done(new Error('Stream destroyed'))
    }

    if (this._handshakeDone !== null) {
      const done = this._handshakeDone
      this._handshakeDone = null
      done(new Error('Stream destroyed'))
    }

    if (this._drainDone !== null) {
      const done = this._drainDone
      this._drainDone = null
      done(new Error('Stream destroyed'))
    }
  }

  _write(data, cb) {
    let wrapped = this._outgoingWrapped

    if (data !== this._outgoingPlain) {
      wrapped = b4a.allocUnsafe(data.byteLength + 3 + ABYTES)
      wrapped.set(data, 4)
    } else {
      this._outgoingWrapped = this._outgoingPlain = null
    }

    if (wrapped.byteLength - 3 > MAX_ATOMIC_WRITE) {
      return cb(
        new Error(
          'Message is too large for an atomic write. Max size is ' + MAX_ATOMIC_WRITE + ' bytes.'
        )
      )
    }
    this.rawBytesWritten += wrapped.byteLength

    writeUint24le(wrapped.byteLength - 3, wrapped)
    // offset 4 so we can do it in-place
    this._encrypt.next(wrapped.subarray(4, 4 + data.byteLength), wrapped.subarray(3))

    if (this._keepAliveTimer !== null) this._keepAliveTimer.refresh()

    if (this._rawStream.write(wrapped) === false) {
      this._drainDone = cb
    } else {
      cb(null)
    }
  }

  _final(cb) {
    this._clearKeepAlive()
    this._ended--
    this._rawStream.end()
    cb(null)
  }

  _resolveOpened(val) {
    if (this._openedDone === null) return
    const opened = this._openedDone
    this._openedDone = null
    opened(val)
    if (!val) return
    this.connected = true
    this.emit('connect')
  }

  _clearTimeout() {
    if (this._timeoutTimer === null) return
    this._timeoutTimer.destroy()
    this._timeoutTimer = null
    this.timeout = 0
  }

  _clearKeepAlive() {
    if (this._keepAliveTimer === null) return
    this._keepAliveTimer.destroy()
    this._keepAliveTimer = null
    this.keepAlive = 0
  }

  _destroy(cb) {
    this._clearKeepAlive()
    this._clearTimeout()
    this._resolveOpened(false)
    cb(null)
  }

  _boxMessage(buffer) {
    const MB = sodium.crypto_secretbox_MACBYTES // 16
    const NB = sodium.crypto_secretbox_NONCEBYTES // 24

    const counter = this._sendState.subarray(64, 72)
    sodium.sodium_increment(counter)
    if (b4a.equals(counter, this._sendState.subarray(72))) {
      this.destroy(new Error('udp send nonce exchausted'))
      return
    }

    const secret = this._sendState.subarray(0, 32)
    const envelope = b4a.allocUnsafe(8 + MB + buffer.byteLength)
    const nonce = envelope.subarray(0, NB)
    const ciphertext = envelope.subarray(8)

    b4a.fill(nonce, 0) // pad suffix
    nonce.set(counter)

    sodium.crypto_secretbox_easy(ciphertext, buffer, nonce, secret)
    return envelope
  }

  send(buffer) {
    if (!this._sendState) return
    if (!this.rawStream?.send) return // udx-stream expected

    const message = this._boxMessage(buffer)
    return this.rawStream.send(message)
  }

  trySend(buffer) {
    if (!this._sendState) return
    if (!this.rawStream?.trySend) return // udx-stream expected

    const message = this._boxMessage(buffer)
    this.rawStream.trySend(message)
  }

  _onmessage(buffer) {
    if (!this._sendState) return // messages before handshake are dropped

    const MB = sodium.crypto_secretbox_MACBYTES // 16
    const NB = sodium.crypto_secretbox_NONCEBYTES // 24

    if (buffer.byteLength < NB) return // Invalid message

    const nonce = b4a.allocUnsafe(NB)
    b4a.fill(nonce, 0)
    nonce.set(buffer.subarray(0, 8))

    const secret = this._sendState.subarray(32, 64)
    const ciphertext = buffer.subarray(8)
    const plain = buffer.subarray(8, buffer.byteLength - MB)

    if (ciphertext.byteLength < MB) return // invalid message

    const success = sodium.crypto_secretbox_open_easy(plain, ciphertext, nonce, secret)

    if (success) this.emit('message', plain)
  }

  alloc(len) {
    const buf = b4a.allocUnsafe(len + 3 + ABYTES)
    this._outgoingWrapped = buf
    this._outgoingPlain = buf.subarray(4, buf.byteLength - ABYTES + 1)
    return this._outgoingPlain
  }

  toJSON() {
    return {
      isInitiator: this.isInitiator,
      publicKey: this.publicKey && b4a.toString(this.publicKey, 'hex'),
      remotePublicKey: this.remotePublicKey && b4a.toString(this.remotePublicKey, 'hex'),
      connected: this.connected,
      destroying: this.destroying,
      destroyed: this.destroyed,
      rawStream: this.rawStream && this.rawStream.toJSON ? this.rawStream.toJSON() : null
    }
  }
}

function writeUint24le(n, buf) {
  buf[0] = n & 255
  buf[1] = (n >>> 8) & 255
  buf[2] = (n >>> 16) & 255
}

function streamId(handshakeHash, isInitiator, out = b4a.allocUnsafe(32)) {
  sodium.crypto_generichash(out, isInitiator ? NS_INITIATOR : NS_RESPONDER, handshakeHash)
  return out
}

function toBuffer(data) {
  return typeof data === 'string' ? b4a.from(data) : data
}

function destroyTimeout() {
  this.destroy(new Error('Stream timed out'))
}

function sendKeepAlive() {
  const empty = this.alloc(0)
  this.write(empty)
}
const { Duplex, Writable } = require('streamx')

class ReversePassThrough extends Duplex {
  constructor(s) {
    super()
    this._stream = s
    this._ondrain = null
  }

  _write(data, cb) {
    if (this._stream.push(data) === false) {
      this._stream._ondrain = cb
    } else {
      cb(null)
    }
  }

  _final(cb) {
    this._stream.push(null)
    cb(null)
  }

  _read(cb) {
    const ondrain = this._ondrain
    this._ondrain = null
    if (ondrain) ondrain()
    cb(null)
  }
}

module.exports = class Bridge extends Duplex {
  constructor(noiseStream) {
    super()

    this.noiseStream = noiseStream

    this._ondrain = null
    this.reverse = new ReversePassThrough(this)
  }

  get publicKey() {
    return this.noiseStream.publicKey
  }

  get remotePublicKey() {
    return this.noiseStream.remotePublicKey
  }

  get handshakeHash() {
    return this.noiseStream.handshakeHash
  }

  flush() {
    return Writable.drained(this)
  }

  _read(cb) {
    const ondrain = this._ondrain
    this._ondrain = null
    if (ondrain) ondrain()
    cb(null)
  }

  _write(data, cb) {
    if (this.reverse.push(data) === false) {
      this.reverse._ondrain = cb
    } else {
      cb(null)
    }
  }

  _final(cb) {
    this.reverse.push(null)
    cb(null)
  }
}
const sodium = require('sodium-universal')
const curve = require('noise-curve-ed')
const Noise = require('noise-handshake')
const b4a = require('b4a')

const EMPTY = b4a.alloc(0)

module.exports = class Handshake {
  constructor(isInitiator, keyPair, remotePublicKey, pattern) {
    this.isInitiator = isInitiator
    this.keyPair = keyPair
    this.noise = new Noise(pattern, isInitiator, keyPair, { curve })
    this.noise.initialise(EMPTY, remotePublicKey)
    this.destroyed = false
  }

  static keyPair(seed) {
    const publicKey = b4a.alloc(32)
    const secretKey = b4a.alloc(64)
    if (seed) sodium.crypto_sign_seed_keypair(publicKey, secretKey, seed)
    else sodium.crypto_sign_keypair(publicKey, secretKey)
    return { publicKey, secretKey }
  }

  recv(data) {
    try {
      this.noise.recv(data)
      if (this.noise.complete) return this._return(null)
      return this.send()
    } catch {
      this.destroy()
      return null
    }
  }

  // note that the data returned here is framed so we don't have to do an extra copy
  // when sending it...
  send() {
    try {
      const data = this.noise.send()
      const wrap = b4a.allocUnsafe(data.byteLength + 3)

      writeUint24le(data.byteLength, wrap)
      wrap.set(data, 3)

      return this._return(wrap)
    } catch {
      this.destroy()
      return null
    }
  }

  destroy() {
    if (this.destroyed) return
    this.destroyed = true
  }

  _return(data) {
    const tx = this.noise.complete ? b4a.toBuffer(this.noise.tx) : null
    const rx = this.noise.complete ? b4a.toBuffer(this.noise.rx) : null
    const hash = this.noise.complete ? b4a.toBuffer(this.noise.hash) : null
    const remotePublicKey = this.noise.complete ? b4a.toBuffer(this.noise.rs) : null

    return {
      data,
      remotePublicKey,
      hash,
      tx,
      rx
    }
  }
}

function writeUint24le(n, buf) {
  buf[0] = n & 255
  buf[1] = (n >>> 8) & 255
  buf[2] = (n >>> 16) & 255
}
{
  "name": "@hyperswarm/secret-stream",
  "version": "6.9.1",
  "description": "Secret stream backed by Noise and libsodium's secretstream",
  "main": "index.js",
  "files": [
    "index.js",
    "lib/**.js"
  ],
  "dependencies": {
    "b4a": "^1.1.0",
    "hypercore-crypto": "^3.3.1",
    "noise-curve-ed": "^2.0.1",
    "noise-handshake": "^4.0.0",
    "sodium-secretstream": "^1.1.0",
    "sodium-universal": "^5.0.0",
    "streamx": "^2.14.0",
    "timeout-refresh": "^2.0.0",
    "unslab": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "udx-native": "^1.13.2"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check .",
    "test": "brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/hyperswarm-secret-stream.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/hyperswarm-secret-stream/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperswarm-secret-stream"
}
const Cache = require('xache')

module.exports = class AdaptiveTimeout {
  constructor(opts = {}) {
    this._cache = new Cache({
      maxSize: opts.maxSize || 65536,
      maxAge: opts.maxAge || 10 * 60 * 1000 // 10 minutes
    })
    this._fallback = opts.fallback || AdaptiveTimeout.TimeoutExponential
    this._min = opts.min ?? 300
    this._max = opts.max || 4000
    this._jitter = opts.jitter ?? 256
  }

  // Default - aggressive ramp
  static TimeoutAggressive = [500, 750, 1000, 1500, 2000]

  // Linear - steady increase
  static TimeoutLinear = [500, 1000, 1500, 2000, 2500]

  // Exponential - slow start, rapid backoff
  static TimeoutExponential = [250, 500, 1000, 2000, 4000]

  // Gentle - conservative, patient
  static TimeoutGentle = [1000, 1250, 1500, 1750, 2000]

  // Fast - rapid fire retries
  static TimeoutFast = [200, 400, 600, 800, 1000]

  // U-shape - long, short, long
  static TimeoutUShape = [1500, 750, 500, 750, 1500]

  // Inverse U - short, long, short
  static TimeoutInverseU = [500, 1000, 1500, 1000, 500]

  // Sawtooth - alternating fast/slow
  static TimeoutSawtooth = [500, 1500, 500, 1500, 500]

  // Plateau - quick ramp then steady
  static TimeoutPlateau = [500, 1000, 2000, 2000, 2000]

  // Logarithmic - diminishing increases
  static TimeoutLogarithmic = [500, 1000, 1300, 1500, 1600]

  getValue(key) {
    return this._cache.get(key)
  }

  put(key, value) {
    let p = this._cache.get(key)

    if (!p) {
      p = { avg: value, variance: value >> 1 }
    } else {
      // blend 75% old + 25% new deviation
      p.variance += (Math.abs(p.avg - value) - p.variance) >> 2
      // blend 87.5% old + 12.5% new sample
      p.avg += (value - p.avg) >> 3
    }

    this._cache.set(key, p)

    return p
  }

  get(key, attempt = 1) {
    const p = this._cache.get(key)
    const jitter = (Math.random() * this._jitter) | 0

    if (p) {
      // known - use adaptive with linear backoff
      const base = p.avg + (p.variance << 1)
      const backoff = base * attempt
      return Math.min(Math.max(backoff + jitter, this._min), this._max)
    } else {
      // unknown - use aggressive fallback
      const base = this._fallback[Math.min(attempt - 1, this._fallback.length - 1)]
      return base + jitter
    }
  }

  has(key) {
    return this._cache.has(key)
  }

  delete(key) {
    return this._cache.delete(key)
  }

  clear() {
    this._cache.clear()
  }
}
{
  "name": "adaptive-timeout",
  "version": "1.0.1",
  "description": "adaptive-timeout",
  "main": "index.js",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    }
  },
  "files": [
    "package.json",
    "index.js",
    "index.d.ts"
  ],
  "devDependencies": {
    "brittle": "^3.19.0",
    "lunte": "^1.2.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && lunte && brittle-bare test/index.js",
    "lint": "lunte"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/adaptive-timeout.git"
  },
  "author": "Holepunch Inc",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/adaptive-timeout/issues"
  },
  "homepage": "https://github.com/holepunchto/adaptive-timeout",
  "dependencies": {
    "xache": "^1.2.1"
  }
}
function isBuffer(value) {
  return Buffer.isBuffer(value) || value instanceof Uint8Array
}

function isEncoding(encoding) {
  return Buffer.isEncoding(encoding)
}

function alloc(size, fill, encoding) {
  return Buffer.alloc(size, fill, encoding)
}

function allocUnsafe(size) {
  return Buffer.allocUnsafe(size)
}

function allocUnsafeSlow(size) {
  return Buffer.allocUnsafeSlow(size)
}

function byteLength(string, encoding) {
  return Buffer.byteLength(string, encoding)
}

function compare(a, b) {
  return Buffer.compare(a, b)
}

function concat(buffers, totalLength) {
  return Buffer.concat(buffers, totalLength)
}

function copy(source, target, targetStart, start, end) {
  return toBuffer(source).copy(target, targetStart, start, end)
}

function equals(a, b) {
  return toBuffer(a).equals(b)
}

function fill(buffer, value, offset, end, encoding) {
  return toBuffer(buffer).fill(value, offset, end, encoding)
}

function from(value, encodingOrOffset, length) {
  return Buffer.from(value, encodingOrOffset, length)
}

function includes(buffer, value, byteOffset, encoding) {
  return toBuffer(buffer).includes(value, byteOffset, encoding)
}

function indexOf(buffer, value, byfeOffset, encoding) {
  return toBuffer(buffer).indexOf(value, byfeOffset, encoding)
}

function lastIndexOf(buffer, value, byteOffset, encoding) {
  return toBuffer(buffer).lastIndexOf(value, byteOffset, encoding)
}

function swap16(buffer) {
  return toBuffer(buffer).swap16()
}

function swap32(buffer) {
  return toBuffer(buffer).swap32()
}

function swap64(buffer) {
  return toBuffer(buffer).swap64()
}

function toBuffer(buffer) {
  if (Buffer.isBuffer(buffer)) return buffer
  return Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

function toString(buffer, encoding, start, end) {
  return toBuffer(buffer).toString(encoding, start, end)
}

function write(buffer, string, offset, length, encoding) {
  return toBuffer(buffer).write(string, offset, length, encoding)
}

function readDoubleBE(buffer, offset) {
  return toBuffer(buffer).readDoubleBE(offset)
}

function readDoubleLE(buffer, offset) {
  return toBuffer(buffer).readDoubleLE(offset)
}

function readFloatBE(buffer, offset) {
  return toBuffer(buffer).readFloatBE(offset)
}

function readFloatLE(buffer, offset) {
  return toBuffer(buffer).readFloatLE(offset)
}

function readInt32BE(buffer, offset) {
  return toBuffer(buffer).readInt32BE(offset)
}

function readInt32LE(buffer, offset) {
  return toBuffer(buffer).readInt32LE(offset)
}

function readUInt32BE(buffer, offset) {
  return toBuffer(buffer).readUInt32BE(offset)
}

function readUInt32LE(buffer, offset) {
  return toBuffer(buffer).readUInt32LE(offset)
}

function writeDoubleBE(buffer, value, offset) {
  return toBuffer(buffer).writeDoubleBE(value, offset)
}

function writeDoubleLE(buffer, value, offset) {
  return toBuffer(buffer).writeDoubleLE(value, offset)
}

function writeFloatBE(buffer, value, offset) {
  return toBuffer(buffer).writeFloatBE(value, offset)
}

function writeFloatLE(buffer, value, offset) {
  return toBuffer(buffer).writeFloatLE(value, offset)
}

function writeInt32BE(buffer, value, offset) {
  return toBuffer(buffer).writeInt32BE(value, offset)
}

function writeInt32LE(buffer, value, offset) {
  return toBuffer(buffer).writeInt32LE(value, offset)
}

function writeUInt32BE(buffer, value, offset) {
  return toBuffer(buffer).writeUInt32BE(value, offset)
}

function writeUInt32LE(buffer, value, offset) {
  return toBuffer(buffer).writeUInt32LE(value, offset)
}

module.exports = {
  isBuffer,
  isEncoding,
  alloc,
  allocUnsafe,
  allocUnsafeSlow,
  byteLength,
  compare,
  concat,
  copy,
  equals,
  fill,
  from,
  includes,
  indexOf,
  lastIndexOf,
  swap16,
  swap32,
  swap64,
  toBuffer,
  toString,
  write,
  readDoubleBE,
  readDoubleLE,
  readFloatBE,
  readFloatLE,
  readInt32BE,
  readInt32LE,
  readUInt32BE,
  readUInt32LE,
  writeDoubleBE,
  writeDoubleLE,
  writeFloatBE,
  writeFloatLE,
  writeInt32BE,
  writeInt32LE,
  writeUInt32BE,
  writeUInt32LE
}
{
  "name": "b4a",
  "version": "1.8.1",
  "description": "Bridging the gap between buffers and typed arrays",
  "exports": {
    "./package": "./package.json",
    ".": {
      "react-native": "./react-native.js",
      "browser": "./browser.js",
      "default": "./index.js"
    }
  },
  "files": [
    "browser.js",
    "index.js",
    "react-native.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:bare && npm run test:node",
    "test:bare": "brittle-bare --coverage test.mjs",
    "test:node": "brittle-node --coverage test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/b4a.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/b4a/issues"
  },
  "homepage": "https://github.com/holepunchto/b4a#readme",
  "devDependencies": {
    "brittle": "^3.5.2",
    "lunte": "^1.7.0",
    "nanobench": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "react-native-b4a": "*"
  },
  "peerDependenciesMeta": {
    "react-native-b4a": {
      "optional": true
    }
  }
}
module.exports = require.addon()
const binding = require('./binding')

module.exports = binding.abort
{
  "name": "bare-abort",
  "version": "2.0.13",
  "description": "Cause abnormal program termination and generate a crash report",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-abort.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-abort/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-abort#readme",
  "devDependencies": {
    "cmake-bare": "^1.1.7",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  }
}
const ESC = '\x1b'
const CSI = ESC + '['
const SGR = (n) => CSI + n + 'm'

exports.constants = {
  ESC,
  CSI,
  SGR
}

// https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_(Control_Sequence_Introducer)_sequences

exports.cursorHide = CSI + '?25l'
exports.cursorShow = CSI + '?25h'

exports.cursorUp = function cursorUp(n = 1) {
  return CSI + n + 'A'
}

exports.cursorDown = function cursorDown(n = 1) {
  return CSI + n + 'B'
}

exports.cursorForward = function cursorForward(n = 1) {
  return CSI + n + 'C'
}

exports.cursorBack = function cursorBack(n = 1) {
  return CSI + n + 'D'
}

exports.cursorNextLine = function cursorNextLine(n = 1) {
  return CSI + n + 'E'
}

exports.cursorPreviousLine = function cursorPreviousLine(n = 1) {
  return CSI + n + 'F'
}

exports.cursorPosition = function cursorPosition(column, row = 0) {
  if (row === 0) return CSI + (column + 1) + 'G'

  return CSI + (row + 1) + ';' + (column + 1) + 'H'
}

exports.eraseDisplayEnd = CSI + 'J'
exports.eraseDisplayStart = CSI + '1J'
exports.eraseDisplay = CSI + '2J'
exports.eraseLineEnd = CSI + 'K'
exports.eraseLineStart = CSI + '1K'
exports.eraseLine = CSI + '2K'

exports.scrollUp = function scrollUp(n = 1) {
  return CSI + n + 'S'
}

exports.scrollDown = function scrollDown(n = 1) {
  return CSI + n + 'T'
}

// https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_(Select_Graphic_Rendition)_parameters

exports.modifierReset = SGR(0)
exports.modifierBold = SGR(1)
exports.modifierDim = SGR(2)
exports.modifierItalic = SGR(3)
exports.modifierUnderline = SGR(4)
exports.modifierNormal = SGR(22)
exports.modifierNotItalic = SGR(23)
exports.modifierNotUnderline = SGR(24)

// https://en.wikipedia.org/wiki/ANSI_escape_code#Colors

exports.colorBlack = SGR(30)
exports.colorRed = SGR(31)
exports.colorGreen = SGR(32)
exports.colorYellow = SGR(33)
exports.colorBlue = SGR(34)
exports.colorMagenta = SGR(35)
exports.colorCyan = SGR(36)
exports.colorWhite = SGR(37)
exports.colorDefault = SGR(39)
exports.colorBrightBlack = SGR(90)
exports.colorBrightRed = SGR(91)
exports.colorBrightGreen = SGR(92)
exports.colorBrightYellow = SGR(93)
exports.colorBrightBlue = SGR(94)
exports.colorBrightMagenta = SGR(95)
exports.colorBrightCyan = SGR(96)
exports.colorBrightWhite = SGR(97)
{
  "name": "bare-ansi-escapes",
  "version": "2.2.3",
  "description": "Parse and produce ANSI escape sequences",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./key-decoder": {
      "types": "./key-decoder.d.ts",
      "default": "./key-decoder.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "key-decoder.js",
    "key-decoder.d.ts"
  ],
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-ansi-escapes.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-ansi-escapes/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-ansi-escapes#readme",
  "dependencies": {
    "bare-stream": "^2.6.5"
  },
  "devDependencies": {
    "bare-buffer": "^3.0.2",
    "brittle": "^3.3.2",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  },
  "peerDependencies": {
    "bare-buffer": "*"
  },
  "peerDependenciesMeta": {
    "bare-buffer": {
      "optional": true
    }
  }
}
const inspect = require('bare-inspect')

class AssertionError extends Error {
  constructor(opts = {}) {
    let { message = null, actual, expected, operator } = opts

    if (message === null) {
      message = `${inspect(actual)} ${operator} ${inspect(expected)}`
    }

    super(message)

    this.actual = actual
    this.expected = expected
    this.operator = operator
  }

  get name() {
    return 'AssertionError'
  }

  get code() {
    'ASSERTION'
  }
}

function assertFail(opts, fn) {
  if (opts.message instanceof Error) throw opts.message

  const err = new AssertionError(opts)

  if (Error.captureStackTrace) Error.captureStackTrace(err, fn)

  throw err
}

module.exports = exports = function assert(actual, message) {
  if (actual) return

  assertFail({ message, actual, expected: true, operator: '==' }, assert)
}

exports.AssertionError = AssertionError

exports.fail = function fail(message) {
  if (message === undefined) message = 'Failed'

  assertFail({ message, operator: 'fail' }, fail)
}

exports.ok = function ok(actual, message) {
  if (actual) return

  assertFail({ message, actual, expected: true, operator: '==' }, ok)
}

exports.notOk = function ok(actual, message) {
  if (!actual) return

  assertFail({ message, actual, expected: false, operator: '==' }, ok)
}

exports.equal = function equal(actual, expected, message) {
  if (actual == expected || (actual !== actual && expected !== expected)) {
    return
  }

  assertFail({ message, actual, expected, operator: '==' }, equal)
}

exports.notEqual = function notEqual(actual, expected, message) {
  if (actual != expected && (actual === actual || expected === expected)) {
    return
  }

  assertFail({ message, actual, expected, operator: '!=' }, notEqual)
}

exports.strictEqual = function strictEqual(actual, expected, message) {
  if (Object.is(actual, expected)) return

  assertFail(
    { message, actual, expected, operator: 'strictEqual' },
    strictEqual
  )
}

exports.notStrictEqual = function notStrictEqual(actual, expected, message) {
  if (!Object.is(actual, expected)) return

  assertFail(
    { message, actual, expected, operator: 'notStrictEqual' },
    notStrictEqual
  )
}
{
  "name": "bare-assert",
  "version": "1.2.0",
  "description": "Assertion library for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts"
  ],
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-assert.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-assert/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-assert#readme",
  "dependencies": {
    "bare-inspect": "^3.1.2"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  }
}
module.exports = require.addon()
const binding = require('./binding')

exports.Resolver = class DNSResolver {
  constructor() {
    this._handle = binding.initResolver()
  }

  resolveTxt(hostname, cb = noop) {
    binding.resolveTxt(this._handle, hostname, cb, this)
  }

  destroy() {
    binding.destroyResolver(this._handle)
    this._handle = null
  }

  static global = new this()
}

function onlookup(err, addresses) {
  const req = this

  if (err) return req.cb(err, null, 0)

  const { address, family } = addresses[0]

  return req.cb(null, address, family)
}

function onlookupall(err, addresses) {
  const req = this

  if (err) return req.cb(err, null)

  return req.cb(null, addresses)
}

exports.lookup = function lookup(hostname, opts = {}, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  let { family = 0, all = false } = opts

  if (typeof family === 'string') {
    switch (family) {
      case 'IPv4':
        family = 4
        break
      case 'IPv6':
        family = 6
        break
      default:
        family = 0
    }
  }

  const req = {
    cb,
    handle: null
  }

  req.handle = binding.lookup(
    hostname,
    family || 0,
    all,
    req,
    all ? onlookupall : onlookup
  )
}

exports.resolveTxt = function resolveTxt(hostname, cb) {
  exports.Resolver.global.resolveTxt(hostname, cb)
}

function noop() {}
{
  "name": "bare-dns",
  "version": "2.1.4",
  "description": "Domain name resolution for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-dns.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-dns/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-dns",
  "engines": {
    "bare": ">=1.7.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "cmake-bare": "^1.1.6",
    "cmake-fetch": "^1.3.0",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
const os = require('bare-os')

module.exports = new Proxy(Object.create(null), {
  ownKeys (target) {
    return os.getEnvKeys()
  },

  get (target, property) {
    if (typeof property !== 'string') return

    return os.getEnv(property)
  },

  has (target, property) {
    if (typeof property !== 'string') return false

    return os.hasEnv(property)
  },

  set (target, property, value) {
    if (typeof property !== 'string') return

    const type = typeof value

    if (type !== 'string' && type !== 'number' && type !== 'boolean') {
      throw new Error('Environment variable must be of type string, number, or boolean')
    }

    value = String(value)

    os.setEnv(property, value)

    return true
  },

  deleteProperty (target, property) {
    if (typeof property !== 'string') return

    os.unsetEnv(property)
  },

  getOwnPropertyDescriptor (target, property) {
    return {
      value: this.get(target, property),
      enumerable: true,
      configurable: true,
      writable: true
    }
  }
})
{
  "name": "bare-env",
  "version": "3.0.0",
  "description": "Environment variable support for JavaScript",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "scripts": {
    "test": "standard && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-env.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-env/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-env#readme",
  "dependencies": {
    "bare-os": "^3.0.1"
  },
  "devDependencies": {
    "brittle": "^3.2.1",
    "standard": "^17.0.0"
  }
}
const errors = require('./lib/errors')

class EventListener {
  constructor() {
    this.list = []
    this.count = 0
  }

  append(ctx, name, fn, once) {
    this.count++
    ctx.emit('newListener', name, fn) // Emit BEFORE adding
    this.list.push([fn, once])
  }

  prepend(ctx, name, fn, once) {
    this.count++
    ctx.emit('newListener', name, fn) // Emit BEFORE adding
    this.list.unshift([fn, once])
  }

  remove(ctx, name, fn) {
    for (let i = 0, n = this.list.length; i < n; i++) {
      const l = this.list[i]

      if (l[0] === fn) {
        this.list.splice(i, 1)

        if (this.count === 1) delete ctx._events[name]

        ctx.emit('removeListener', name, fn) // Emit AFTER removing

        this.count--
        return
      }
    }
  }

  removeAll(ctx, name) {
    const list = [...this.list]
    this.list = []

    if (this.count === list.length) delete ctx._events[name]

    for (let i = list.length - 1; i >= 0; i--) {
      ctx.emit('removeListener', name, list[i][0]) // Emit AFTER removing
    }

    this.count -= list.length
  }

  emit(ctx, name, ...args) {
    const list = [...this.list]

    for (let i = 0, n = list.length; i < n; i++) {
      const l = list[i]

      if (l[1] === true) this.remove(ctx, name, l[0])

      Reflect.apply(l[0], ctx, args)
    }

    return list.length > 0
  }
}

function appendListener(ctx, name, fn, once) {
  if (ctx._events === undefined) ctx._events = Object.create(null)
  const e = ctx._events[name] || (ctx._events[name] = new EventListener())
  e.append(ctx, name, fn, once)
  return ctx
}

function prependListener(ctx, name, fn, once) {
  if (ctx._events === undefined) ctx._events = Object.create(null)
  const e = ctx._events[name] || (ctx._events[name] = new EventListener())
  e.prepend(ctx, name, fn, once)
  return ctx
}

function removeListener(ctx, name, fn) {
  if (ctx._events === undefined) return ctx
  const e = ctx._events[name]
  if (e !== undefined) e.remove(ctx, name, fn)
  return ctx
}

function throwUnhandledError(...args) {
  let err

  if (args.length > 0) err = args[0]

  if (err instanceof Error === false) err = errors.UNHANDLED_ERROR(err)

  if (Error.captureStackTrace) {
    Error.captureStackTrace(err, exports.prototype.emit)
  }

  queueMicrotask(() => {
    throw err
  })
}

module.exports = exports = class EventEmitter {
  constructor() {
    this._events = Object.create(null)
  }

  addListener(name, fn) {
    return appendListener(this, name, fn, false)
  }

  addOnceListener(name, fn) {
    return appendListener(this, name, fn, true)
  }

  prependListener(name, fn) {
    return prependListener(this, name, fn, false)
  }

  prependOnceListener(name, fn) {
    return prependListener(this, name, fn, true)
  }

  removeListener(name, fn) {
    return removeListener(this, name, fn)
  }

  on(name, fn) {
    return appendListener(this, name, fn, false)
  }

  once(name, fn) {
    return appendListener(this, name, fn, true)
  }

  off(name, fn) {
    return removeListener(this, name, fn)
  }

  emit(name, ...args) {
    if (name === 'error' && this._events !== undefined && this._events.error === undefined) {
      throwUnhandledError(...args)
    }

    if (this._events === undefined) return false
    const e = this._events[name]
    return e === undefined ? false : e.emit(this, name, ...args)
  }

  listeners(name) {
    if (this._events === undefined) return []
    const e = this._events[name]
    return e === undefined ? [] : [...e.list]
  }

  listenerCount(name) {
    if (this._events === undefined) return 0
    const e = this._events[name]
    return e === undefined ? 0 : e.list.length
  }

  getMaxListeners() {
    return EventEmitter.defaultMaxListeners
  }

  setMaxListeners(n) {}

  removeAllListeners(name) {
    if (arguments.length === 0) {
      for (const key of Reflect.ownKeys(this._events)) {
        if (key === 'removeListener') continue
        this.removeAllListeners(key)
      }
      this.removeAllListeners('removeListener')
    } else {
      const e = this._events[name]
      if (e !== undefined) e.removeAll(this, name)
    }
    return this
  }
}

exports.EventEmitter = exports

exports.errors = errors

exports.defaultMaxListeners = 10

exports.on = function on(emitter, name, opts = {}) {
  const { signal } = opts

  if (signal && signal.aborted) {
    throw errors.OPERATION_ABORTED(signal.reason)
  }

  let error = null
  let done = false

  const events = []
  const promises = []

  if (name !== 'error') emitter.on('error', onerror)

  if (signal) signal.addEventListener('abort', onabort)

  emitter.on(name, onevent)

  return {
    next() {
      if (events.length) {
        return Promise.resolve({ value: events.shift(), done: false })
      }

      if (error) {
        const err = error

        error = null

        return Promise.reject(err)
      }

      if (done) return onclose()

      return new Promise((resolve, reject) => promises.push({ resolve, reject }))
    },

    return() {
      return onclose()
    },

    throw(err) {
      return onerror(err)
    },

    [Symbol.asyncIterator]() {
      return this
    }
  }

  function onevent(...args) {
    if (promises.length) {
      promises.shift().resolve({ value: args, done: false })
    } else {
      events.push(args)
    }
  }

  function onerror(err) {
    emitter.off(name, onevent).off('error', onerror)

    if (promises.length) {
      promises.shift().reject(err)
    } else {
      error = err
    }

    return Promise.resolve({ done: true })
  }

  function onabort() {
    signal.removeEventListener('abort', onabort)

    onerror(errors.OPERATION_ABORTED(signal.reason))
  }

  function onclose() {
    emitter.off(name, onevent)

    if (name !== 'error') emitter.off('error', onerror)

    if (signal) signal.removeEventListener('abort', onabort)

    done = true

    if (promises.length) promises.shift().resolve({ done: true })

    return Promise.resolve({ done: true })
  }
}

exports.once = function once(emitter, name, opts = {}) {
  const { signal } = opts

  if (signal && signal.aborted) {
    return Promise.reject(errors.OPERATION_ABORTED(signal.reason))
  }

  return new Promise((resolve, reject) => {
    if (name !== 'error') emitter.on('error', onerror)

    if (signal) signal.addEventListener('abort', onabort)

    emitter.once(name, onevent)

    function onevent(...args) {
      if (name !== 'error') emitter.off('error', onerror)

      if (signal) signal.removeEventListener('abort', onabort)

      resolve(args)
    }

    function onerror(err) {
      emitter.off(name, onevent)

      if (name !== 'error') emitter.off('error', onerror)

      reject(err)
    }

    function onabort() {
      signal.removeEventListener('abort', onabort)

      onerror(errors.OPERATION_ABORTED(signal.reason))
    }
  })
}

exports.forward = function forward(from, to, names, opts = {}) {
  if (typeof names === 'string') names = [names]

  const { emit = to.emit.bind(to) } = opts

  const listeners = names.map(
    (name) =>
      function onevent(...args) {
        emit(name, ...args)
      }
  )

  to.on('newListener', (name) => {
    const i = names.indexOf(name)

    if (i !== -1 && to.listenerCount(name) === 0) {
      from.on(name, listeners[i])
    }
  }).on('removeListener', (name) => {
    const i = names.indexOf(name)

    if (i !== -1 && to.listenerCount(name) === 0) {
      from.off(name, listeners[i])
    }
  })
}

exports.listenerCount = function listenerCount(emitter, name) {
  return emitter.listenerCount(name)
}

exports.getMaxListeners = function getMaxListeners(emitter) {
  if (typeof emitter.getMaxListeners === 'function') {
    return emitter.getMaxListeners()
  }

  return exports.defaultMaxListeners
}

exports.setMaxListeners = function setMaxListeners(n, ...emitters) {
  if (emitters.length === 0) exports.defaultMaxListeners = n
  else {
    for (const emitter of emitters) {
      if (typeof emitter.setMaxListeners === 'function') {
        emitter.setMaxListeners(n)
      }
    }
  }
}
module.exports = class EventEmitterError extends Error {
  constructor(msg, code, fn = EventEmitterError, opts) {
    super(`${code}: ${msg}`, opts)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'EventEmitterError'
  }

  static OPERATION_ABORTED(cause, msg = 'Operation aborted') {
    return new EventEmitterError(msg, 'OPERATION_ABORTED', EventEmitterError.OPERATION_ABORTED, {
      cause
    })
  }

  static UNHANDLED_ERROR(cause, msg = 'Unhandled error') {
    return new EventEmitterError(msg, 'UNHANDLED_ERROR', EventEmitterError.UNHANDLED_ERROR, {
      cause
    })
  }
}
{
  "name": "bare-events",
  "version": "2.8.2",
  "description": "Event emitters for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    },
    "./web": {
      "types": "./web.d.ts",
      "default": "./web.js"
    },
    "./errors": "./lib/errors.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "global.js",
    "global.d.ts",
    "web.js",
    "web.d.ts",
    "lib"
  ],
  "scripts": {
    "test": "npm run lint && npm run test:bare && npm run test:node",
    "test:bare": "bare test.js",
    "test:node": "node test.js",
    "lint": "prettier . --check"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-events.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-events/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-events#readme",
  "devDependencies": {
    "bare-abort-controller": "^1.0.0",
    "brittle": "^3.3.2",
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^2.0.0",
    "uncaughts": "^1.1.1"
  },
  "peerDependencies": {
    "bare-abort-controller": "*"
  },
  "peerDependenciesMeta": {
    "bare-abort-controller": {
      "optional": true
    }
  }
}
module.exports = require.addon()
const FIFO = require('fast-fifo')
const EventEmitter = require('bare-events')
const path = require('bare-path')
const { isURL, fileURLToPath } = require('bare-url')
const { Readable, Writable } = require('bare-stream')
const binding = require('./binding')
const constants = require('./lib/constants')
const FileError = require('./lib/errors')

const isWindows = Bare.platform === 'win32'

exports.constants = constants

class FileRequest {
  static borrow() {
    if (this._free.length > 0) return this._free.pop()
    return new FileRequest()
  }

  static return(req) {
    if (this._free.length < 32) this._free.push(req.reset())
    else req.destroy()
  }

  constructor() {
    this._reset()
    this._handle = binding.requestInit(this, this._onresult)
  }

  get handle() {
    return this._handle
  }

  retain(value) {
    this._retain = value // Tie the lifetime of `value` to the lifetime of `this`
  }

  reset() {
    if (this._handle === null) return this

    binding.requestReset(this._handle)

    this._reset()

    return this
  }

  destroy() {
    if (this._handle === null) return this

    binding.requestDestroy(this._handle)

    this._reset()
    this._handle = null

    return this
  }

  then(resolve, reject) {
    return this._promise.then(resolve, reject)
  }

  return() {
    if (this._handle === null) return this

    FileRequest.return(this)

    return this
  }

  _reset() {
    this._promise = new Promise((resolve, reject) => {
      this._resolve = resolve
      this._reject = reject
    })
    this._retain = null
  }

  _onresult(err, status) {
    if (err) this._reject(err)
    else this._resolve(status)
  }
}

FileRequest._free = []

function ok(result, cb) {
  if (typeof result === 'function') {
    cb = result
    result = undefined
  }

  if (cb) cb(null, result)
  else return result
}

function fail(err, cb) {
  if (cb) cb(err)
  else throw err
}

function done(err, result, cb) {
  if (typeof result === 'function') {
    cb = result
    result = undefined
  }

  if (err) fail(err, cb)
  else return ok(result, cb)
}

async function open(filepath, flags = 'r', mode = 0o666, cb) {
  if (typeof flags === 'function') {
    cb = flags
    flags = 'r'
    mode = 0o666
  } else if (typeof mode === 'function') {
    cb = mode
    mode = 0o666
  }

  if (typeof flags === 'string') flags = toFlags(flags)
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let fd
  let err = null
  try {
    binding.open(req.handle, filepath, flags, mode)

    fd = await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'open',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, fd, cb)
}

function openSync(filepath, flags = 'r', mode = 0o666) {
  if (typeof flags === 'string') flags = toFlags(flags)
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    return binding.openSync(req.handle, filepath, flags, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'open',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function close(fd, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.close(req.handle, fd)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'close', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function closeSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.closeSync(req.handle, fd)
  } catch (e) {
    throw new FileError(e.message, { operation: 'close', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function access(filepath, mode = constants.F_OK, cb) {
  if (typeof mode === 'function') {
    cb = mode
    mode = constants.F_OK
  }

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.access(req.handle, filepath, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'access',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function accessSync(filepath, mode = constants.F_OK) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.accessSync(req.handle, filepath, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'access',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function exists(filepath, cb) {
  let ok = true
  try {
    await access(filepath)
  } catch {
    ok = false
  }

  return done(null, ok, cb)
}

function existsSync(filepath) {
  try {
    accessSync(filepath)
  } catch {
    return false
  }

  return true
}

async function read(fd, buffer, offset = 0, len = buffer.byteLength - offset, pos = -1, cb) {
  if (typeof offset === 'function') {
    cb = offset
    offset = 0
    len = buffer.byteLength
    pos = -1
  } else if (typeof len === 'function') {
    cb = len
    len = buffer.byteLength - offset
    pos = -1
  } else if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.read(req.handle, fd, buffer, offset, len, pos)

    req.retain(buffer)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'read', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function readSync(fd, buffer, offset = 0, len = buffer.byteLength - offset, pos = -1) {
  const req = FileRequest.borrow()

  try {
    return binding.readSync(req.handle, fd, buffer, offset, len, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'read', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function readv(fd, buffers, pos = -1, cb) {
  if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.readv(req.handle, fd, buffers, pos)

    req.retain(buffers)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'readv', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function readvSync(fd, buffers, pos = -1) {
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  try {
    return binding.readvSync(req.handle, fd, buffers, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'readv', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function write(fd, data, offset, len, pos = -1, cb) {
  if (typeof data === 'string') {
    let encoding = len
    cb = pos
    pos = offset

    if (typeof pos === 'function') {
      cb = pos
      pos = -1
      encoding = 'utf8'
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = 'utf8'
    }

    if (typeof pos === 'string') {
      encoding = pos
      pos = -1
    }

    data = Buffer.from(data, encoding)
    offset = 0
    len = data.byteLength
  } else if (typeof offset === 'function') {
    cb = offset
    offset = 0
    len = data.byteLength
    pos = -1
  } else if (typeof len === 'function') {
    cb = len
    len = data.byteLength - offset
    pos = -1
  } else if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof offset !== 'number') offset = 0
  if (typeof len !== 'number') len = data.byteLength - offset
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.write(req.handle, fd, data, offset, len, pos)

    req.retain(data)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'write', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function writeSync(fd, data, offset, len, pos = -1) {
  if (typeof data === 'string') {
    let encoding = len
    pos = offset

    if (typeof pos === 'string') {
      encoding = pos
      pos = -1
    }

    data = Buffer.from(data, encoding)
    offset = 0
    len = data.byteLength
  }

  if (typeof offset !== 'number') offset = 0
  if (typeof len !== 'number') len = data.byteLength - offset
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  try {
    return binding.writeSync(req.handle, fd, data, offset, len, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'write', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function writev(fd, buffers, pos = -1, cb) {
  if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.writev(req.handle, fd, buffers, pos)

    req.retain(buffers)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'writev', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function writevSync(fd, buffers, pos = -1) {
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  try {
    return binding.writevSync(req.handle, fd, buffers, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'writev', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function stat(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.stat(req.handle, filepath)

    await req

    st = new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'stat', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function statSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.statSync(req.handle, filepath)

    return new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'stat', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function lstat(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.lstat(req.handle, filepath)

    await req

    st = new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'lstat', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function lstatSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.lstatSync(req.handle, filepath)

    return new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'lstat', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function fstat(fd, cb) {
  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.fstat(req.handle, fd)

    await req

    st = new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'fstat', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function fstatSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.fstatSync(req.handle, fd)

    return new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'fstat', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function statfs(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.statfs(req.handle, filepath)

    await req

    st = new StatFs(...binding.requestResultStatfs(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'statfs', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function statfsSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.statfsSync(req.handle, filepath)

    return new StatFs(...binding.requestResultStatfs(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'statfs', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function ftruncate(fd, len = 0, cb) {
  if (typeof len === 'function') {
    cb = len
    len = 0
  }

  if (typeof len !== 'number') len = 0

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.ftruncate(req.handle, fd, len)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'ftruncate', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function ftruncateSync(fd, len = 0) {
  if (typeof len !== 'number') len = 0

  const req = FileRequest.borrow()

  try {
    binding.ftruncateSync(req.handle, fd, len)
  } catch (e) {
    throw new FileError(e.message, { operation: 'ftruncate', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function truncate(filepath, len, cb) {
  let fd = -1
  let err

  try {
    fd = await open(filepath, 'r+')

    await ftruncate(fd, len)
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) await close(fd)
  }

  return done(err, cb)
}

function truncateSync(filepath, len) {
  let fd = -1
  let err

  try {
    fd = openSync(filepath, 'r+')

    ftruncateSync(fd, len)
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) closeSync(fd)
  }
}

async function chmod(filepath, mode, cb) {
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.chmod(req.handle, filepath, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'chmod',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function chmodSync(filepath, mode) {
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.chmodSync(req.handle, filepath, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'chmod',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function fchmod(fd, mode, cb) {
  if (typeof mode === 'string') mode = toMode(mode)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fchmod(req.handle, fd, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fchmod', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fchmodSync(fd, mode) {
  if (typeof mode === 'string') mode = toMode(mode)

  const req = FileRequest.borrow()

  try {
    binding.fchmodSync(req.handle, fd, mode)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fchmod', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function chown(filepath, uid, gid, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.chown(req.handle, filepath, uid, gid)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'chown', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function chownSync(filepath, uid, gid) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.chownSync(req.handle, filepath, uid, gid)
  } catch (e) {
    throw new FileError(e.message, { operation: 'chownSync', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function lchown(filepath, uid, gid, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.lchown(req.handle, filepath, uid, gid)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'lchown', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function lchownSync(filepath, uid, gid) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.lchownSync(req.handle, filepath, uid, gid)
  } catch (e) {
    throw new FileError(e.message, { operation: 'lchownSync', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function fchown(fd, uid, gid, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fchown(req.handle, fd, uid, gid)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fchown', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fchownSync(fd, uid, gid) {
  const req = FileRequest.borrow()

  try {
    binding.fchownSync(req.handle, fd, uid, gid)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fchownSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function utimes(filepath, atime, mtime, cb) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.utimes(req.handle, filepath, atime, mtime)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'utimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function utimesSync(filepath, atime, mtime) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.utimesSync(req.handle, filepath, atime, mtime)
  } catch (e) {
    throw new FileError(e.message, { operation: 'utimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function lutimes(filepath, atime, mtime, cb) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.lutimes(req.handle, filepath, atime, mtime)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'lutimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function lutimesSync(filepath, atime, mtime) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.lutimesSync(req.handle, filepath, atime, mtime)
  } catch (e) {
    throw new FileError(e.message, { operation: 'lutimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function futimes(fd, atime, mtime, cb) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.futimes(req.handle, fd, atime, mtime)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'futimes', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function futimesSync(fd, atime, mtime) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  const req = FileRequest.borrow()

  try {
    binding.futimesSync(req.handle, fd, atime, mtime)
  } catch (e) {
    throw new FileError(e.message, { operation: 'futimesSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function link(src, dst, cb) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.link(req.handle, src, dst)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'link', code: e.code, path: src, destination: dst })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function linkSync(src, dst) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  try {
    binding.linkSync(req.handle, src, dst)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'linkSync',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }
}

async function mkdir(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = { mode: 0o777 }
  }

  if (typeof opts === 'number') opts = { mode: opts }
  else if (!opts) opts = {}

  const mode = typeof opts.mode === 'number' ? opts.mode : 0o777

  filepath = toNamespacedPath(filepath)

  if (opts.recursive) {
    let err = null
    try {
      try {
        await mkdir(filepath, { mode })
      } catch (err) {
        if (err.code !== 'ENOENT') {
          if (!(await stat(filepath)).isDirectory()) throw err
        } else {
          while (filepath.endsWith(path.sep)) filepath = filepath.slice(0, -1)
          const i = filepath.lastIndexOf(path.sep)
          if (i <= 0) throw err

          await mkdir(filepath.slice(0, i), { mode, recursive: true })

          try {
            await mkdir(filepath, { mode })
          } catch (err) {
            if (!(await stat(filepath)).isDirectory()) throw err
          }
        }
      }
    } catch (e) {
      err = e
    }

    return done(err, cb)
  }

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.mkdir(req.handle, filepath, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'mkdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function mkdirSync(filepath, opts) {
  if (typeof opts === 'number') opts = { mode: opts }
  else if (!opts) opts = {}

  const mode = typeof opts.mode === 'number' ? opts.mode : 0o777

  filepath = toNamespacedPath(filepath)

  if (opts.recursive) {
    try {
      mkdirSync(filepath, { mode })
    } catch (err) {
      if (err.code !== 'ENOENT') {
        if (!statSync(filepath).isDirectory()) throw err
      } else {
        while (filepath.endsWith(path.sep)) filepath = filepath.slice(0, -1)
        const i = filepath.lastIndexOf(path.sep)
        if (i <= 0) throw err

        mkdirSync(filepath.slice(0, i), { mode, recursive: true })

        try {
          mkdirSync(filepath, { mode })
        } catch (err) {
          if (!statSync(filepath).isDirectory()) throw err
        }
      }
    }

    return
  }

  const req = FileRequest.borrow()

  try {
    binding.mkdirSync(req.handle, filepath, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'mkdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function mkdtemp(prefix, cb) {
  prefix = toNamespacedPath(prefix)

  const req = FileRequest.borrow()

  let res
  let err = null
  try {
    binding.mkdtemp(req.handle, prefix + 'XXXXXX')

    await req

    res = binding.requestResultPath(req.handle)
  } catch (e) {
    err = new FileError(e.message, { operation: 'mkdtemp', code: e.code, path: prefix })
  } finally {
    req.return()
  }

  return done(err, res, cb)
}

function mkdtempSync(prefix) {
  prefix = toNamespacedPath(prefix)

  const req = FileRequest.borrow()

  try {
    binding.mkdtempSync(req.handle, prefix + 'XXXXXX')

    return binding.requestResultPath(req.handle)
  } catch (e) {
    throw new FileError(e.message, { operation: 'mkdtempSync', code: e.code, path: prefix })
  } finally {
    req.return()
  }
}

async function rmdir(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.rmdir(req.handle, filepath)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'rmdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function rmdirSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.rmdirSync(req.handle, filepath)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'rmdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function rm(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  let err = null
  try {
    const st = await lstat(filepath)

    if (st.isDirectory()) {
      if (opts.recursive) {
        try {
          await rmdir(filepath)
        } catch (err) {
          if (err.code !== 'ENOTEMPTY') throw err

          const files = await readdir(filepath)

          for (const file of files) {
            await rm(filepath + path.sep + file, opts)
          }

          await rmdir(filepath)
        }
      } else {
        throw new FileError('is a directory', {
          operation: 'rm',
          code: 'EISDIR',
          path: filepath
        })
      }
    } else {
      await unlink(filepath)
    }
  } catch (e) {
    if (e.code !== 'ENOENT' || !opts.force) err = e
  }

  return done(err, cb)
}

function rmSync(filepath, opts) {
  if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  try {
    const st = lstatSync(filepath)

    if (st.isDirectory()) {
      if (opts.recursive) {
        try {
          rmdirSync(filepath)
        } catch (err) {
          if (err.code !== 'ENOTEMPTY') throw err

          const files = readdirSync(filepath)

          for (const file of files) {
            rmSync(filepath + path.sep + file, opts)
          }

          rmdirSync(filepath)
        }
      } else {
        throw new FileError('is a directory', {
          operation: 'rm',
          code: 'EISDIR',
          path: filepath
        })
      }
    } else {
      unlinkSync(filepath)
    }
  } catch (err) {
    if (err.code !== 'ENOENT' || !opts.force) throw err
  }
}

async function unlink(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.unlink(req.handle, filepath)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'unlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function unlinkSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.unlinkSync(req.handle, filepath)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'unlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function rename(src, dst, cb) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.rename(req.handle, src, dst)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'rename',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function renameSync(src, dst) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  try {
    binding.renameSync(req.handle, src, dst)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'rename',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }
}

async function copyFile(src, dst, mode = 0, cb) {
  if (typeof mode === 'function') {
    cb = mode
    mode = 0
  }

  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.copyfile(req.handle, src, dst, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'copyfile',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function copyFileSync(src, dst, mode = 0) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  try {
    binding.copyfileSync(req.handle, src, dst, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'copyfile',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }
}

async function cp(src, dst, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (!opts) opts = {}

  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  let err = null
  try {
    const st = await lstat(src)

    if (st.isDirectory()) {
      if (opts.recursive !== true) {
        throw new FileError('is a directory', { operation: 'cp', code: 'EISDIR', path: src })
      }

      try {
        await lstat(dst)
      } catch (e) {
        if (e.code !== 'ENOENT') throw e

        await mkdir(dst, { mode: st.mode, recursive: true })
      }

      const dir = await opendir(src)
      for await (const { name } of dir) {
        await cp(path.join(src, name), path.join(dst, name), opts)
      }
    } else if (st.isFile()) {
      await copyFile(src, dst)
      await chmod(dst, st.mode)
    }
  } catch (e) {
    err = e
  }

  return done(err, cb)
}

function cpSync(src, dst, opts = {}) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const st = lstatSync(src)

  if (st.isDirectory()) {
    if (opts.recursive !== true) {
      throw new FileError('is a directory', { operation: 'cp', code: 'EISDIR', path: src })
    }

    try {
      lstatSync(dst)
    } catch (e) {
      if (e.code !== 'ENOENT') throw e

      mkdirSync(dst, { mode: st.mode, recursive: true })
    }

    const dir = opendirSync(src)
    for (const { name } of dir) {
      cpSync(path.join(src, name), path.join(dst, name), opts)
    }
  } else if (st.isFile()) {
    copyFileSync(src, dst)
    chmodSync(dst, st.mode)
  }
}

async function realpath(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let res
  let err = null
  try {
    binding.realpath(req.handle, filepath)

    await req

    res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'realpath',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, res, cb)
}

function realpathSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.realpathSync(req.handle, filepath)

    let res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)

    return res
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'realpath',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function readlink(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let res
  let err = null
  try {
    binding.readlink(req.handle, filepath)

    await req

    res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'readlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, res, cb)
}

function readlinkSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.readlinkSync(req.handle, filepath)

    let res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)

    return res
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'readlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function fsync(fd, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fsync(req.handle, fd)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fsync', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fsyncSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.fsyncSync(req.handle, fd)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fsyncSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function fdatasync(fd, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fdatasync(req.handle, fd)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fdatasync', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fdatasyncSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.fdatasyncSync(req.handle, fd)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fdatasyncSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

function normalizeSymlinkTarget(target, type, filepath) {
  if (isWindows) {
    if (type === constants.UV_FS_SYMLINK_JUNCTION) target = path.resolve(filepath, '..', target)

    if (path.isAbsolute(target)) return path.toNamespacedPath(target)

    return target.replace(/\//g, path.sep)
  }

  return target
}

async function symlink(target, filepath, type, cb) {
  if (typeof type === 'function') {
    cb = type
    type = null
  }

  filepath = toNamespacedPath(filepath)

  if (typeof type === 'string') {
    switch (type) {
      case 'dir':
        type = constants.UV_FS_SYMLINK_DIR
        break
      case 'junction':
        type = constants.UV_FS_SYMLINK_JUNCTION
        break
      case 'file':
      default:
        type = 0
        break
    }
  } else if (typeof type !== 'number') {
    if (isWindows) {
      target = path.resolve(filepath, '..', target)

      try {
        type = (await stat(target)).isDirectory()
          ? constants.UV_FS_SYMLINK_DIR
          : constants.UV_FS_SYMLINK_JUNCTION
      } catch {
        type = 0
      }
    } else {
      type = 0
    }
  }

  target = normalizeSymlinkTarget(target, type, filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.symlink(req.handle, target, filepath, type)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'symlink',
      code: e.code,
      path: target,
      destination: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function symlinkSync(target, filepath, type) {
  filepath = toNamespacedPath(filepath)

  if (typeof type === 'string') {
    switch (type) {
      case 'dir':
        type = constants.UV_FS_SYMLINK_DIR
        break
      case 'junction':
        type = constants.UV_FS_SYMLINK_JUNCTION
        break
      case 'file':
      default:
        type = 0
        break
    }
  } else if (typeof type !== 'number') {
    if (isWindows) {
      target = path.resolve(filepath, '..', target)

      try {
        type = statSync(target).isDirectory()
          ? constants.UV_FS_SYMLINK_DIR
          : constants.UV_FS_SYMLINK_JUNCTION
      } catch {
        type = 0
      }
    } else {
      type = 0
    }
  }

  target = normalizeSymlinkTarget(target, type, filepath)

  const req = FileRequest.borrow()

  try {
    binding.symlinkSync(req.handle, target, filepath, type)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'symlink',
      code: e.code,
      path: target,
      destination: filepath
    })
  } finally {
    req.return()
  }
}

async function opendir(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let dir
  let err = null
  try {
    binding.opendir(req.handle, filepath)

    await req

    dir = new Dir(filepath, binding.requestResultDir(req.handle), opts)
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'opendir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, dir, cb)
}

function opendirSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.opendirSync(req.handle, filepath)

    return new Dir(filepath, binding.requestResultDir(req.handle), opts)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'opendir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function readdir(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { withFileTypes = false, recursive = false } = opts

  filepath = toNamespacedPath(filepath)

  const queue = [filepath]
  let result = []
  let err = null
  try {
    while (queue.length !== 0) {
      const dir = await opendir(queue.pop())

      for await (const entry of dir) {
        const entryPath = path.join(entry.parentPath, entry.name)

        if (withFileTypes) {
          result.push(entry)
        } else {
          result.push(path.relative(filepath, entryPath))
        }

        if (recursive && entry.isDirectory()) queue.push(entryPath)
      }
    }
  } catch (e) {
    result = []
    err = e
  }

  return done(err, result, cb)
}

function readdirSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { withFileTypes = false, recursive = false } = opts

  filepath = toNamespacedPath(filepath)

  const queue = [filepath]
  const result = []

  while (queue.length !== 0) {
    const dir = opendirSync(queue.pop(), opts)

    for (const entry of dir) {
      const entryPath = path.join(entry.parentPath, entry.name)

      if (withFileTypes) {
        result.push(entry)
      } else {
        result.push(path.relative(filepath, entryPath))
      }

      if (recursive && entry.isDirectory()) queue.push(entryPath)
    }
  }

  return result
}

async function readFile(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'buffer' } = opts

  let fd = -1
  let buffer = null
  let err = null
  try {
    fd = await open(filepath, opts.flag || 'r')

    const st = await fstat(fd)

    let len = 0

    if (st.size === 0) {
      const buffers = []

      while (true) {
        buffer = Buffer.allocUnsafe(8192)
        const r = await read(fd, buffer)
        len += r
        if (r === 0) break
        buffers.push(buffer.subarray(0, r))
      }

      buffer = Buffer.concat(buffers)
    } else {
      buffer = Buffer.allocUnsafe(st.size)

      while (true) {
        const r = await read(fd, len ? buffer.subarray(len) : buffer)
        len += r
        if (r === 0 || len === buffer.byteLength) break
      }

      if (len !== buffer.byteLength) buffer = buffer.subarray(0, len)
    }

    if (encoding !== 'buffer') buffer = buffer.toString(encoding)
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) await close(fd)
  }

  return done(err, buffer, cb)
}

function readFileSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'buffer' } = opts

  let fd = -1
  try {
    fd = openSync(filepath, opts.flag || 'r')

    const st = fstatSync(fd)

    let buffer
    let len = 0

    if (st.size === 0) {
      const buffers = []

      while (true) {
        buffer = Buffer.allocUnsafe(8192)
        const r = readSync(fd, buffer)
        len += r
        if (r === 0) break
        buffers.push(buffer.subarray(0, r))
      }

      buffer = Buffer.concat(buffers)
    } else {
      buffer = Buffer.allocUnsafe(st.size)

      while (true) {
        const r = readSync(fd, len ? buffer.subarray(len) : buffer)
        len += r
        if (r === 0 || len === buffer.byteLength) break
      }

      if (len !== buffer.byteLength) buffer = buffer.subarray(0, len)
    }

    if (encoding !== 'buffer') buffer = buffer.toString(encoding)

    return buffer
  } finally {
    if (fd !== -1) closeSync(fd)
  }
}

async function writeFile(filepath, data, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (typeof data === 'string') data = Buffer.from(data, opts.encoding)

  let fd = -1
  let len = 0
  let err = null
  try {
    fd = await open(filepath, opts.flag || 'w', opts.mode || 0o666)

    while (true) {
      len += await write(fd, len ? data.subarray(len) : data)
      if (len === data.byteLength) break
    }
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) await close(fd)
  }

  return done(err, len, cb)
}

function writeFileSync(filepath, data, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (typeof data === 'string') data = Buffer.from(data, opts.encoding)

  let fd = -1
  try {
    fd = openSync(filepath, opts.flag || 'w', opts.mode || 0o666)

    let len = 0

    while (true) {
      len += writeSync(fd, len ? data.subarray(len) : data)
      if (len === data.byteLength) break
    }
  } finally {
    if (fd !== -1) closeSync(fd)
  }
}

function appendFile(filepath, data, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (!opts.flag) opts = { ...opts, flag: 'a' }

  return writeFile(filepath, data, opts, cb)
}

function appendFileSync(filepath, data, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (!opts.flag) opts = { ...opts, flag: 'a' }

  return writeFileSync(filepath, data, opts)
}

function watch(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  return new Watcher(filepath, opts, cb)
}

class Stats {
  constructor(
    dev,
    mode,
    nlink,
    uid,
    gid,
    rdev,
    blksize,
    ino,
    size,
    blocks,
    atimeMs,
    mtimeMs,
    ctimeMs,
    birthtimeMs
  ) {
    this.dev = dev
    this.mode = mode
    this.nlink = nlink
    this.uid = uid
    this.gid = gid
    this.rdev = rdev
    this.blksize = blksize
    this.ino = ino
    this.size = size
    this.blocks = blocks
    this.atimeMs = atimeMs
    this.mtimeMs = mtimeMs
    this.ctimeMs = ctimeMs
    this.birthtimeMs = birthtimeMs
    this.atime = new Date(atimeMs)
    this.mtime = new Date(mtimeMs)
    this.ctime = new Date(ctimeMs)
    this.birthtime = new Date(birthtimeMs)
  }

  isDirectory() {
    return (this.mode & constants.S_IFMT) === constants.S_IFDIR
  }

  isFile() {
    return (this.mode & constants.S_IFMT) === constants.S_IFREG
  }

  isBlockDevice() {
    return (this.mode & constants.S_IFMT) === constants.S_IFBLK
  }

  isCharacterDevice() {
    return (this.mode & constants.S_IFMT) === constants.S_IFCHR
  }

  isFIFO() {
    return (this.mode & constants.S_IFMT) === constants.S_IFIFO
  }

  isSymbolicLink() {
    return (this.mode & constants.S_IFMT) === constants.S_IFLNK
  }

  isSocket() {
    return (this.mode & constants.S_IFMT) === constants.S_IFSOCK
  }
}

class StatFs {
  constructor(type, bsize, blocks, bfree, bavail, files, ffree) {
    this.type = type
    this.bsize = bsize
    this.blocks = blocks
    this.bfree = bfree
    this.bavail = bavail
    this.files = files
    this.ffree = ffree
  }
}

class Dir {
  constructor(path, handle, opts = {}) {
    const { encoding = 'utf8', bufferSize = 32 } = opts

    this.path = path

    this._encoding = encoding
    this._capacity = bufferSize
    this._buffer = new FIFO()
    this._ended = false
    this._handle = handle
  }

  async read(cb) {
    if (this._buffer.length) return ok(this._buffer.shift(), cb)
    if (this._ended) return ok(null, cb)

    const req = FileRequest.borrow()

    let entries
    let err = null
    try {
      req.retain(binding.readdir(req.handle, this._handle, this._capacity))

      await req

      entries = binding.requestResultDirents(req.handle)
    } catch (e) {
      err = new FileError(e.message, {
        operation: 'readdir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    if (err) return fail(err, cb)

    if (entries.length === 0) {
      this._ended = true

      return ok(null, cb)
    }

    for (const entry of entries) {
      let name = Buffer.from(entry.name)

      if (this._encoding !== 'buffer') name = name.toString(this._encoding)

      this._buffer.push(new Dirent(this.path, name, entry.type))
    }

    return ok(this._buffer.shift(), cb)
  }

  readSync() {
    if (this._buffer.length) return this._buffer.shift()
    if (this._ended) return null

    const req = FileRequest.borrow()

    let entries
    try {
      req.retain(binding.readdirSync(req.handle, this._handle, this._capacity))

      entries = binding.requestResultDirents(req.handle)
    } catch (e) {
      throw new FileError(e.message, {
        operation: 'readdir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    if (entries.length === 0) {
      this._ended = true

      return null
    }

    for (const entry of entries) {
      let name = Buffer.from(entry.name)

      if (this._encoding !== 'buffer') name = name.toString(this._encoding)

      this._buffer.push(new Dirent(this.path, name, entry.type))
    }

    return this._buffer.shift()
  }

  async close(cb) {
    const req = FileRequest.borrow()

    let err = null
    try {
      binding.closedir(req.handle, this._handle)

      await req
    } catch (e) {
      err = new FileError(e.message, {
        operation: 'closedir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    this._handle = null

    return done(err, cb)
  }

  closeSync() {
    const req = FileRequest.borrow()

    try {
      binding.closedirSync(req.handle, this._handle)
    } catch (e) {
      throw new FileError(e.message, {
        operation: 'closedir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    this._handle = null
  }

  [Symbol.dispose]() {
    this.closeSync()
  }

  async [Symbol.asyncDispose]() {
    await this.close()
  }

  *[Symbol.iterator]() {
    while (true) {
      const entry = this.readSync()
      if (entry === null) break
      yield entry
    }

    this.closeSync()
  }

  async *[Symbol.asyncIterator]() {
    while (true) {
      const entry = await this.read()
      if (entry === null) break
      yield entry
    }

    await this.close()
  }
}

class Dirent {
  constructor(parentPath, name, type) {
    this.parentPath = parentPath
    this.name = name
    this.type = type
  }

  isFile() {
    return this.type === constants.UV_DIRENT_FILE
  }

  isDirectory() {
    return this.type === constants.UV_DIRENT_DIR
  }

  isSymbolicLink() {
    return this.type === constants.UV_DIRENT_LINK
  }

  isFIFO() {
    return this.type === constants.UV_DIRENT_FIFO
  }

  isSocket() {
    return this.type === constants.UV_DIRENT_SOCKET
  }

  isCharacterDevice() {
    return this.type === constants.UV_DIRENT_CHAR
  }

  isBlockDevice() {
    return this.type === constants.UV_DIRENT_BLOCK
  }
}

class FileReadStream extends Readable {
  constructor(path, opts = {}) {
    const { eagerOpen = true } = opts

    super({ eagerOpen, ...opts })

    this.path = path
    this.fd = typeof opts.fd === 'number' ? opts.fd : -1
    this.flags = opts.flags || 'r'
    this.mode = opts.mode || 0o666

    this._offset = opts.start || 0
    this._missing = 0

    if (opts.length) {
      this._missing = opts.length
    } else if (typeof opts.end === 'number') {
      this._missing = opts.end - this._offset + 1
    } else {
      this._missing = -1
    }
  }

  async _open(cb) {
    let err

    if (this.fd === -1) {
      err = null
      try {
        this.fd = await open(this.path, this.flags, this.mode)
      } catch (e) {
        err = e
      }

      if (err) return cb(err)
    }

    let st
    err = null
    try {
      st = await fstat(this.fd)
    } catch (e) {
      err = e
    }

    if (err) return cb(err)

    if (this._missing === -1) this._missing = st.size

    if (st.size < this._offset) {
      this._offset = st.size
      this._missing = 0
    } else if (st.size < this._offset + this._missing) {
      this._missing = st.size - this._offset
    }

    cb(null)
  }

  async _read(size) {
    if (this._missing <= 0) return this.push(null)

    const data = Buffer.allocUnsafe(Math.min(this._missing, size))

    let len
    let err = null
    try {
      len = await read(this.fd, data, 0, data.byteLength, this._offset)
    } catch (e) {
      err = e
    }

    if (err) return this.destroy(err)

    if (len === 0) return this.push(null)

    if (this._missing < len) len = this._missing

    this._missing -= len
    this._offset += len

    this.push(data.subarray(0, len))
  }

  async _destroy(err, cb) {
    if (this.fd === -1) return cb(err)

    try {
      await close(this.fd)
    } catch (e) {
      err = err || e
    }

    cb(err)
  }
}

class FileWriteStream extends Writable {
  constructor(path, opts = {}) {
    const { eagerOpen = true } = opts

    super({ eagerOpen, ...opts })

    this.path = path
    this.fd = typeof opts.fd === 'number' ? opts.fd : -1
    this.flags = opts.flags || 'w'
    this.mode = opts.mode || 0o666
  }

  async _open(cb) {
    if (this.fd !== -1) return cb(null)

    let err = null
    try {
      this.fd = await open(this.path, this.flags, this.mode)
    } catch (e) {
      err = e
    }

    cb(err)
  }

  async _writev(batch, cb) {
    let err = null
    try {
      await writev(
        this.fd,
        batch.map(({ chunk }) => chunk)
      )
    } catch (e) {
      err = e
    }

    cb(err)
  }

  async _destroy(err, cb) {
    if (this.fd === -1) return cb(err)

    try {
      await close(this.fd)
    } catch (e) {
      err = err || e
    }

    cb(err)
  }
}

class Watcher extends EventEmitter {
  constructor(path, opts, onchange) {
    if (typeof opts === 'function') {
      onchange = opts
      opts = {}
    }

    if (!opts) opts = {}

    const { persistent = true, recursive = false, encoding = 'utf8' } = opts

    super()

    this._closed = false
    this._encoding = encoding
    this._handle = binding.watcherInit(path, recursive, this, this._onevent, this._onclose)

    if (!persistent) this.unref()

    if (onchange) this.on('change', onchange)
  }

  close() {
    if (this._closed) return
    this._closed = true

    binding.watcherClose(this._handle)
  }

  ref() {
    if (this._handle) binding.watcherRef(this._handle)
    return this
  }

  unref() {
    if (this._handle) binding.watcherUnref(this._handle)
    return this
  }

  [Symbol.asyncIterator]() {
    const buffer = []
    let done = false
    let error = null
    let next = null

    this.on('change', (eventType, filename) => {
      if (next) {
        next.resolve({ done: false, value: { eventType, filename } })
        next = null
      } else {
        buffer.push({ eventType, filename })
      }
    })
      .on('error', (err) => {
        done = true
        error = err

        if (next) {
          next.reject(error)
          next = null
        }
      })
      .on('close', () => {
        done = true

        if (next) {
          next.resolve({ done })
          next = null
        }
      })

    return {
      next: () =>
        new Promise((resolve, reject) => {
          if (error) return reject(error)

          if (buffer.length) return resolve({ done: false, value: buffer.shift() })

          if (done) return resolve({ done })

          next = { resolve, reject }
        })
    }
  }

  _onevent(err, events, filename) {
    if (err) {
      this.close()
      this.emit('error', err)
    } else {
      const path =
        this._encoding === 'buffer'
          ? Buffer.from(filename)
          : Buffer.from(filename).toString(this._encoding)

      if (events & binding.UV_RENAME) {
        this.emit('change', 'rename', path)
      }

      if (events & binding.UV_CHANGE) {
        this.emit('change', 'change', path)
      }
    }
  }

  _onclose() {
    this._handle = null

    this.emit('close')
  }
}

exports.access = access
exports.appendFile = appendFile
exports.chmod = chmod
exports.chown = chown
exports.close = close
exports.copyFile = copyFile
exports.cp = cp
exports.exists = exists
exports.fchmod = fchmod
exports.fchown = fchown
exports.fdatasync = fdatasync
exports.fstat = fstat
exports.fsync = fsync
exports.ftruncate = ftruncate
exports.futimes = futimes
exports.lchown = lchown
exports.lutimes = lutimes
exports.link = link
exports.lstat = lstat
exports.mkdir = mkdir
exports.mkdtemp = mkdtemp
exports.open = open
exports.opendir = opendir
exports.read = read
exports.readFile = readFile
exports.readdir = readdir
exports.readlink = readlink
exports.readv = readv
exports.realpath = realpath
exports.rename = rename
exports.rm = rm
exports.rmdir = rmdir
exports.stat = stat
exports.statfs = statfs
exports.symlink = symlink
exports.truncate = truncate
exports.unlink = unlink
exports.utimes = utimes
exports.watch = watch
exports.write = write
exports.writeFile = writeFile
exports.writev = writev

exports.accessSync = accessSync
exports.appendFileSync = appendFileSync
exports.chmodSync = chmodSync
exports.chownSync = chownSync
exports.closeSync = closeSync
exports.copyFileSync = copyFileSync
exports.cpSync = cpSync
exports.existsSync = existsSync
exports.fchmodSync = fchmodSync
exports.fchownSync = fchownSync
exports.fdatasyncSync = fdatasyncSync
exports.fstatSync = fstatSync
exports.fsyncSync = fsyncSync
exports.ftruncateSync = ftruncateSync
exports.futimesSync = futimesSync
exports.lchownSync = lchownSync
exports.lutimesSync = lutimesSync
exports.linkSync = linkSync
exports.lstatSync = lstatSync
exports.mkdirSync = mkdirSync
exports.mkdtempSync = mkdtempSync
exports.openSync = openSync
exports.opendirSync = opendirSync
exports.readFileSync = readFileSync
exports.readSync = readSync
exports.readdirSync = readdirSync
exports.readlinkSync = readlinkSync
exports.readvSync = readvSync
exports.realpathSync = realpathSync
exports.renameSync = renameSync
exports.rmSync = rmSync
exports.rmdirSync = rmdirSync
exports.statSync = statSync
exports.statfsSync = statfsSync
exports.symlinkSync = symlinkSync
exports.truncateSync = truncateSync
exports.unlinkSync = unlinkSync
exports.utimesSync = utimesSync
exports.writeFileSync = writeFileSync
exports.writeSync = writeSync
exports.writevSync = writevSync

exports.promises = require('./promises')

exports.Stats = Stats
exports.StatFs = StatFs
exports.Dir = Dir
exports.Dirent = Dirent
exports.Watcher = Watcher

exports.ReadStream = FileReadStream

exports.createReadStream = function createReadStream(path, opts) {
  return new FileReadStream(path, opts)
}

exports.WriteStream = FileWriteStream

exports.createWriteStream = function createWriteStream(path, opts) {
  return new FileWriteStream(path, opts)
}

function toNamespacedPath(filepath) {
  if (typeof filepath !== 'string') {
    if (isURL(filepath)) filepath = fileURLToPath(filepath)
    else filepath = filepath.toString()
  }

  return path.toNamespacedPath(filepath)
}

function toFlags(flags) {
  switch (flags) {
    case 'r':
      return constants.O_RDONLY
    case 'rs': // Fall through.
    case 'sr':
      return constants.O_RDONLY | constants.O_SYNC
    case 'r+':
      return constants.O_RDWR
    case 'rs+': // Fall through.
    case 'sr+':
      return constants.O_RDWR | constants.O_SYNC

    case 'w':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_WRONLY
    case 'wx': // Fall through.
    case 'xw':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_WRONLY | constants.O_EXCL

    case 'w+':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_RDWR
    case 'wx+': // Fall through.
    case 'xw+':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_RDWR | constants.O_EXCL

    case 'a':
      return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY
    case 'ax': // Fall through.
    case 'xa':
      return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY | constants.O_EXCL
    case 'as': // Fall through.
    case 'sa':
      return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY | constants.O_SYNC

    case 'a+':
      return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR
    case 'ax+': // Fall through.
    case 'xa+':
      return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR | constants.O_EXCL
    case 'as+': // Fall through.
    case 'sa+':
      return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR | constants.O_SYNC
    default:
      return 0
  }
}

function toMode(mode) {
  return parseInt(mode, 8)
}
const binding = require('../binding')

module.exports = {
  O_RDWR: binding.O_RDWR,
  O_RDONLY: binding.O_RDONLY,
  O_WRONLY: binding.O_WRONLY,
  O_CREAT: binding.O_CREAT,
  O_TRUNC: binding.O_TRUNC,
  O_APPEND: binding.O_APPEND,

  F_OK: binding.F_OK || 0,
  R_OK: binding.R_OK || 0,
  W_OK: binding.W_OK || 0,
  X_OK: binding.X_OK || 0,

  S_IFMT: binding.S_IFMT,
  S_IFREG: binding.S_IFREG,
  S_IFDIR: binding.S_IFDIR,
  S_IFCHR: binding.S_IFCHR,
  S_IFLNK: binding.S_IFLNK,
  S_IFBLK: binding.S_IFBLK || 0,
  S_IFIFO: binding.S_IFIFO || 0,
  S_IFSOCK: binding.S_IFSOCK || 0,

  S_IRUSR: binding.S_IRUSR || 0,
  S_IWUSR: binding.S_IWUSR || 0,
  S_IXUSR: binding.S_IXUSR || 0,
  S_IRGRP: binding.S_IRGRP || 0,
  S_IWGRP: binding.S_IWGRP || 0,
  S_IXGRP: binding.S_IXGRP || 0,
  S_IROTH: binding.S_IROTH || 0,
  S_IWOTH: binding.S_IWOTH || 0,
  S_IXOTH: binding.S_IXOTH || 0,

  UV_DIRENT_UNKNOWN: binding.UV_DIRENT_UNKNOWN,
  UV_DIRENT_FILE: binding.UV_DIRENT_FILE,
  UV_DIRENT_DIR: binding.UV_DIRENT_DIR,
  UV_DIRENT_LINK: binding.UV_DIRENT_LINK,
  UV_DIRENT_FIFO: binding.UV_DIRENT_FIFO,
  UV_DIRENT_SOCKET: binding.UV_DIRENT_SOCKET,
  UV_DIRENT_CHAR: binding.UV_DIRENT_CHAR,
  UV_DIRENT_BLOCK: binding.UV_DIRENT_BLOCK,

  COPYFILE_EXCL: binding.UV_FS_COPYFILE_EXCL,
  COPYFILE_FICLONE: binding.UV_FS_COPYFILE_FICLONE,
  COPYFILE_FICLONE_FORCE: binding.UV_FS_COPYFILE_FICLONE_FORCE,
  UV_FS_SYMLINK_DIR: binding.UV_FS_SYMLINK_DIR,
  UV_FS_SYMLINK_JUNCTION: binding.UV_FS_SYMLINK_JUNCTION
}
const os = require('bare-os')

module.exports = class FileError extends Error {
  constructor(msg, opts = {}) {
    const { code, operation = null, path = null, destination = null, fd = -1 } = opts

    if (operation !== null) msg += describe(operation, opts)

    super(`${code}: ${msg}`)

    this.code = code

    if (operation !== null) this.operation = operation
    if (path !== null) this.path = path
    if (destination !== null) this.destination = destination
    if (fd !== -1) this.fd = fd
  }

  get name() {
    return 'FileError'
  }

  // For Node.js compatibility
  get errno() {
    return os.constants.errnos[this.code]
  }

  // For Node.js compatibility
  get syscall() {
    return this.operation
  }

  // For Node.js compatibility
  get dest() {
    return this.destination
  }
}

function describe(operation, opts) {
  const { path = null, destination = null, fd = -1 } = opts

  let result = `, ${operation}`

  if (path !== null) {
    result += ` ${JSON.stringify(path)}`

    if (destination !== null) {
      result += ` -> ${JSON.stringify(destination)}`
    }
  } else if (fd !== -1) {
    result += ` ${fd}`
  }

  return result
}
{
  "name": "bare-fs",
  "version": "4.7.2",
  "description": "Native file system operations for Bare",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./promises": {
      "types": "./promises.d.ts",
      "default": "./promises.js"
    },
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "promises.js",
    "promises.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-fs.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-fs/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-fs#readme",
  "engines": {
    "bare": ">=1.16.0"
  },
  "dependencies": {
    "bare-events": "^2.5.4",
    "bare-path": "^3.0.0",
    "bare-stream": "^2.6.4",
    "bare-url": "^2.2.2",
    "fast-fifo": "^1.3.2"
  },
  "devDependencies": {
    "bare-buffer": "^3.0.2",
    "bare-crypto": "^1.11.2",
    "brittle": "^3.1.1",
    "cmake-bare": "^1.1.7",
    "lunte": "^1.6.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "bare-buffer": "*"
  },
  "peerDependenciesMeta": {
    "bare-buffer": {
      "optional": true
    }
  }
}
const EventEmitter = require('bare-events')
const fs = require('.')

class FileHandle extends EventEmitter {
  constructor(fd) {
    super()

    this.fd = fd
  }

  async close() {
    await fs.close(this.fd)

    this.fd = -1
    this.emit('close')
  }

  async read(buffer, ...args) {
    return {
      bytesRead: await fs.read(this.fd, buffer, ...args),
      buffer
    }
  }

  async readv(buffers, ...args) {
    return {
      bytesRead: await fs.readv(this.fd, buffers, ...args),
      buffers
    }
  }

  async write(buffer, ...args) {
    return {
      bytesWritten: await fs.write(this.fd, buffer, ...args),
      buffer
    }
  }

  async writev(buffers, ...args) {
    return {
      bytesWritten: await fs.writev(this.fd, buffers, ...args),
      buffers
    }
  }

  async stat() {
    return fs.fstat(this.fd)
  }

  async chmod(mode) {
    await fs.fchmod(this.fd, mode)
  }

  async chown(uid, gid) {
    await fs.fchown(this.fd, uid, gid)
  }

  async datasync() {
    return fs.fdatasync(this.fd)
  }

  async sync() {
    return fs.fsync(this.fd)
  }

  async truncate(len) {
    await fs.ftruncate(this.fd, len)
  }

  async utimes(atime, mtime) {
    await fs.futimes(this.fd, atime, mtime)
  }

  createReadStream(opts) {
    return fs.createReadStream(null, { ...opts, fd: this.fd })
  }

  createWriteStream(opts) {
    return fs.createWriteStream(null, { ...opts, fd: this.fd })
  }

  async [Symbol.asyncDispose]() {
    await this.close()
  }
}

exports.open = async function open(filepath, flags, mode) {
  return new FileHandle(await fs.open(filepath, flags, mode))
}

exports.access = fs.access
exports.appendFile = fs.appendFile
exports.chmod = fs.chmod
exports.chown = fs.chown
exports.constants = fs.constants
exports.copyFile = fs.copyFile
exports.cp = fs.cp
exports.lchown = fs.lchown
exports.lutimes = fs.lutimes
exports.link = fs.link
exports.lstat = fs.lstat
exports.mkdir = fs.mkdir
exports.mkdtemp = fs.mkdtemp
exports.opendir = fs.opendir
exports.readFile = fs.readFile
exports.readdir = fs.readdir
exports.readlink = fs.readlink
exports.realpath = fs.realpath
exports.rename = fs.rename
exports.rm = fs.rm
exports.rmdir = fs.rmdir
exports.stat = fs.stat
exports.statfs = fs.statfs
exports.truncate = fs.truncate
exports.symlink = fs.symlink
exports.unlink = fs.unlink
exports.utimes = fs.utimes
exports.watch = fs.watch
exports.writeFile = fs.writeFile
module.exports = require.addon()
const binding = require('./binding')

module.exports = exports = function hrtime(past) {
  let now = binding.hrtime()

  if (past) now -= BigInt(past[0]) * 1000000000n + BigInt(past[1])

  return [Number(now / 1000000000n), Number(now % 1000000000n)]
}

exports.bigint = function hrtime() {
  return binding.hrtime()
}
{
  "name": "bare-hrtime",
  "version": "2.1.1",
  "description": "High-resolution timers for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-hrtime.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-hrtime/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-hrtime#readme",
  "devDependencies": {
    "brittle": "^3.2.1",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  }
}
const errors = require('./lib/errors')

const constants = {
  REQUEST: 1,
  RESPONSE: 2,
  DATA: 3,
  END: 4
}

const TAB = 0x09
const LF = 0x0a
const CR = 0x0d
const SP = 0x20
const ZERO = 0x30
const NINE = 0x39
const UPPER_A = 0x41
const UPPER_F = 0x46
const UPPER_Z = 0x5a
const LOWER_A = 0x61
const LOWER_F = 0x66
const COLON = 0x3a

const MAX_CHUNK_SIZE_LENGTH = 16

// Header states
const FIRST_TOKEN = 0
const REQUEST_URL = 1
const REQUEST_VERSION = 2
const STATUS_CODE = 3
const STATUS_REASON = 4
const FIRST_LINE_LF = 5
const HEADER_START = 6
const HEADER_NAME = 7
const HEADER_VALUE_WS = 8
const HEADER_VALUE = 9
const HEADER_LINE_LF = 10
const HEADER_END_LF = 11

// Body states
const BODY = 12
const CHUNK_SIZE = 13
const CHUNK_SIZE_LF = 14
const CHUNK_DATA = 15
const CHUNK_EXTENSION = 16

// Trailing states
const LAST_CHUNK_LF = 17
const TRAILER_CR = 18
const TRAILER_LF = 19

module.exports = exports = class HTTPParser {
  constructor(opts = {}) {
    const { maxHeaderSize = 16384, maxHeadersCount = 2000 } = opts

    this._maxHeaderSize = maxHeaderSize
    this._maxHeadersCount = maxHeadersCount
    this._state = FIRST_TOKEN
    this._buffer = []
    this._bufferIndex = 0
    this._byteIndex = 0
    this._buffered = 0
    this._accumulator = []

    this._isResponse = false
    this._method = ''
    this._url = ''
    this._version = ''
    this._code = 0
    this._reason = ''

    this._headerName = ''
    this._headers = {}
    this._headerCount = 0
    this._headerSize = 0

    this._remaining = 0
  }

  *push(data, encoding) {
    if (typeof data === 'string') data = Buffer.from(data, encoding)

    this._buffer.push(data)
    this._buffered += data.byteLength

    yield* this._parse()

    this._compact()
  }

  end() {
    const buffers = this._buffer
    const bufferIndex = this._bufferIndex
    const byteIndex = this._byteIndex

    this._buffer = []
    this._bufferIndex = 0
    this._byteIndex = 0
    this._buffered = 0

    if (bufferIndex >= buffers.length) return Buffer.alloc(0)

    buffers[bufferIndex] = buffers[bufferIndex].subarray(byteIndex)

    const remaining = buffers.slice(bufferIndex)

    if (remaining.length === 0) return Buffer.alloc(0)
    if (remaining.length === 1) return remaining[0]

    return Buffer.concat(remaining)
  }

  _compact() {
    if (this._bufferIndex > 0) {
      this._buffer = this._buffer.slice(this._bufferIndex)
      this._bufferIndex = 0
    }

    if (this._byteIndex > 0 && this._buffer.length > 0) {
      this._buffer[0] = this._buffer[0].subarray(this._byteIndex)
      this._byteIndex = 0
    }
  }

  _consume(n) {
    this._buffered -= n

    const current = this._buffer[this._bufferIndex]

    if (this._byteIndex + n <= current.byteLength) {
      const slice = current.subarray(this._byteIndex, this._byteIndex + n)

      this._byteIndex += n

      if (this._byteIndex >= current.byteLength) {
        this._bufferIndex++
        this._byteIndex = 0
      }

      return slice
    }

    const result = Buffer.allocUnsafe(n)

    let written = 0

    while (written < n) {
      const buffer = this._buffer[this._bufferIndex]
      const available = buffer.byteLength - this._byteIndex
      const take = Math.min(available, n - written)

      buffer.copy(result, written, this._byteIndex, this._byteIndex + take)

      written += take

      this._byteIndex += take

      if (this._byteIndex >= buffer.byteLength) {
        this._bufferIndex++
        this._byteIndex = 0
      }
    }

    return result
  }

  _buildString() {
    const string = String.fromCharCode.apply(null, this._accumulator)

    this._accumulator = []

    return string
  }

  _checkHeaderSize() {
    if (++this._headerSize > this._maxHeaderSize) {
      throw errors.INVALID_MESSAGE('Header exceeds limit of ' + this._maxHeaderSize + ' bytes')
    }
  }

  _storeHeader(name, value) {
    let end = value.length

    while (end > 0 && (value.charCodeAt(end - 1) === SP || value.charCodeAt(end - 1) === TAB)) {
      end--
    }

    if (end < value.length) value = value.substring(0, end)

    this._headerCount++

    if (this._headerCount > this._maxHeadersCount) {
      throw errors.INVALID_MESSAGE('Header count exceeds limit of ' + this._maxHeadersCount)
    }

    switch (name) {
      case '__proto__':
      case 'constructor':
      case 'prototype':
        throw errors.INVALID_HEADER("Unsafe header name '" + name + "'")

      case 'host':
      case 'content-length':
      case 'transfer-encoding':
        if (name in this._headers) {
          throw errors.INVALID_HEADER("Duplicate header '" + name + "'")
        }

        this._headers[name] = value
        break

      default:
        const delimiter = name === 'cookie' ? '; ' : ', '

        if (name in this._headers) {
          this._headers[name] += delimiter + value
        } else {
          this._headers[name] = value
        }
    }
  }

  *_parse() {
    while (true) {
      if (this._state === BODY) {
        if (this._buffered === 0) return

        const available = Math.min(this._buffered, this._remaining)
        const data = this._consume(available)

        this._remaining -= available

        const ended = this._remaining === 0

        if (ended) this._state = FIRST_TOKEN

        yield { type: constants.DATA, data }

        if (ended) yield { type: constants.END }

        continue
      }

      if (this._state === CHUNK_DATA) {
        if (this._buffered < this._remaining) return

        const consumed = this._consume(this._remaining)

        if (consumed[this._remaining - 2] !== CR || consumed[this._remaining - 1] !== LF) {
          throw errors.INVALID_MESSAGE('Expected CRLF after chunk data')
        }

        const data = consumed.subarray(0, this._remaining - 2)

        this._remaining = 0
        this._state = CHUNK_SIZE

        yield { type: constants.DATA, data }

        continue
      }

      if (this._buffered === 0) return

      const byte = this._buffer[this._bufferIndex][this._byteIndex++]

      this._buffered--

      if (this._byteIndex >= this._buffer[this._bufferIndex].byteLength) {
        this._bufferIndex++
        this._byteIndex = 0
      }

      switch (this._state) {
        case FIRST_TOKEN: {
          this._checkHeaderSize()

          if (byte === SP) {
            const token = this._buildString()

            if (token.length === 0) throw errors.INVALID_MESSAGE()

            this._isResponse = token.startsWith('HTTP/')

            if (this._isResponse) {
              if (token !== 'HTTP/1.0' && token !== 'HTTP/1.1') {
                throw errors.INVALID_MESSAGE()
              }

              this._version = token
              this._state = STATUS_CODE
            } else {
              this._method = token
              this._state = REQUEST_URL
            }
          } else if (byte === CR) {
            throw errors.INVALID_MESSAGE()
          } else if (isTokenByte(byte)) {
            this._accumulator.push(byte)
          } else if (
            byte === 0x2f &&
            this._accumulator.length === 4 &&
            this._accumulator[0] === 0x48 &&
            this._accumulator[1] === 0x54 &&
            this._accumulator[2] === 0x54 &&
            this._accumulator[3] === 0x50
          ) {
            this._accumulator.push(byte)
          } else {
            throw errors.INVALID_MESSAGE()
          }

          break
        }

        case REQUEST_URL: {
          this._checkHeaderSize()

          if (byte === SP) {
            this._url = this._buildString()

            if (this._url.length === 0) throw errors.INVALID_MESSAGE()

            this._state = REQUEST_VERSION
          } else if (byte === CR) {
            throw errors.INVALID_MESSAGE()
          } else if (byte >= 0x21 && byte !== 0x7f) {
            this._accumulator.push(byte)
          } else {
            throw errors.INVALID_MESSAGE()
          }

          break
        }

        case REQUEST_VERSION: {
          this._checkHeaderSize()

          if (byte === CR) {
            this._version = this._buildString()

            if (this._version !== 'HTTP/1.0' && this._version !== 'HTTP/1.1') {
              throw errors.INVALID_MESSAGE()
            }

            this._state = FIRST_LINE_LF
          } else if (byte >= 0x21 && byte !== 0x7f) {
            this._accumulator.push(byte)
          } else {
            throw errors.INVALID_MESSAGE()
          }

          break
        }

        case STATUS_CODE: {
          this._checkHeaderSize()

          if (byte === SP) {
            if (this._accumulator.length === 0) throw errors.INVALID_MESSAGE()

            let code = 0

            for (let i = 0, n = this._accumulator.length; i < n; i++) {
              code = code * 10 + this._accumulator[i]
            }

            this._accumulator = []

            if (code < 100 || code > 999) throw errors.INVALID_MESSAGE()

            this._code = code
            this._state = STATUS_REASON
          } else if (byte >= ZERO && byte <= NINE) {
            this._accumulator.push(byte - ZERO)
          } else {
            throw errors.INVALID_MESSAGE()
          }

          break
        }

        case STATUS_REASON: {
          this._checkHeaderSize()

          if (byte === CR) {
            this._reason = this._buildString()
            this._state = FIRST_LINE_LF
          } else if (isFieldByte(byte)) {
            this._accumulator.push(byte)
          } else {
            throw errors.INVALID_MESSAGE()
          }

          break
        }

        case FIRST_LINE_LF: {
          if (byte !== LF) throw errors.INVALID_MESSAGE()

          this._headers = {}
          this._headerCount = 0
          this._state = HEADER_START

          break
        }

        case HEADER_START: {
          this._checkHeaderSize()

          if (byte === CR) {
            this._state = HEADER_END_LF
          } else if (byte !== COLON && isTokenByte(byte)) {
            this._accumulator.push(byte >= UPPER_A && byte <= UPPER_Z ? byte + 0x20 : byte)
            this._state = HEADER_NAME
          } else {
            throw errors.INVALID_HEADER()
          }

          break
        }

        case HEADER_NAME: {
          this._checkHeaderSize()

          if (byte === COLON) {
            this._headerName = this._buildString()
            this._state = HEADER_VALUE_WS
          } else if (byte !== COLON && isTokenByte(byte)) {
            this._accumulator.push(byte >= UPPER_A && byte <= UPPER_Z ? byte + 0x20 : byte)
          } else {
            throw errors.INVALID_HEADER()
          }

          break
        }

        case HEADER_VALUE_WS: {
          this._checkHeaderSize()

          if (byte === SP || byte === TAB) break

          if (byte === CR) {
            this._storeHeader(this._headerName, '')
            this._headerName = ''
            this._state = HEADER_LINE_LF

            break
          }

          if (!isFieldByte(byte)) throw errors.INVALID_HEADER()

          this._accumulator.push(byte)
          this._state = HEADER_VALUE

          break
        }

        case HEADER_VALUE: {
          this._checkHeaderSize()

          if (byte === CR) {
            this._storeHeader(this._headerName, this._buildString())
            this._headerName = ''
            this._state = HEADER_LINE_LF
          } else if (isFieldByte(byte)) {
            this._accumulator.push(byte)
          } else {
            throw errors.INVALID_HEADER()
          }

          break
        }

        case HEADER_LINE_LF: {
          if (byte !== LF) throw errors.INVALID_HEADER()

          this._state = HEADER_START

          break
        }

        case HEADER_END_LF: {
          if (byte !== LF) throw errors.INVALID_MESSAGE()

          const headers = this._headers

          if (this._isResponse) {
            yield {
              type: constants.RESPONSE,
              version: this._version,
              code: this._code,
              reason: this._reason,
              headers
            }
          } else {
            if (this._version === 'HTTP/1.1' && !('host' in headers)) {
              throw errors.INVALID_HEADER("Header 'Host' is missing")
            }

            yield {
              type: constants.REQUEST,
              version: this._version,
              method: this._method,
              url: this._url,
              headers
            }
          }

          const transferEncoding = headers['transfer-encoding']
          const contentLength = headers['content-length']

          const encodings = transferEncoding ? transferEncoding.split(',') : null

          const lastEncoding = encodings
            ? encodings[encodings.length - 1].trim().toLowerCase()
            : null

          if (lastEncoding === 'chunked') {
            if (contentLength) {
              throw errors.INVALID_MESSAGE(
                "Conflicting 'Content-Length' and 'Transfer-Encoding' headers"
              )
            }

            this._state = CHUNK_SIZE
            this._headerSize = 0

            continue
          }

          if (contentLength) {
            if (contentLength.length === 0) throw errors.INVALID_CONTENT_LENGTH()

            let length = 0

            for (let i = 0, n = contentLength.length; i < n; i++) {
              const c = contentLength.charCodeAt(i)

              if (c < ZERO || c > NINE) throw errors.INVALID_CONTENT_LENGTH()

              length = length * 10 + (c - ZERO)
            }

            if (!Number.isSafeInteger(length) || length < 0) {
              throw errors.INVALID_CONTENT_LENGTH()
            }

            if (length === 0) {
              this._state = FIRST_TOKEN
              this._headerSize = 0

              yield { type: constants.END }
            } else {
              this._state = BODY
              this._remaining = length
              this._headerSize = 0
            }
          } else {
            this._state = FIRST_TOKEN
            this._headerSize = 0

            yield { type: constants.END }
          }

          break
        }

        case CHUNK_SIZE: {
          if (byte === CR || byte === 0x3b) {
            if (this._accumulator.length === 0) throw errors.INVALID_CHUNK_LENGTH()

            let length = 0

            for (let i = 0, n = this._accumulator.length; i < n; i++) {
              length = length * 16 + this._accumulator[i]
            }

            this._accumulator = []

            if (!Number.isSafeInteger(length)) throw errors.INVALID_CHUNK_LENGTH()

            if (byte === 0x3b) {
              this._remaining = length
              this._state = CHUNK_EXTENSION
            } else if (length === 0) {
              this._state = LAST_CHUNK_LF
            } else {
              this._remaining = length + 2
              this._state = CHUNK_SIZE_LF
            }
          } else if (isHex(byte)) {
            if (this._accumulator.length >= MAX_CHUNK_SIZE_LENGTH) {
              throw errors.INVALID_CHUNK_LENGTH()
            }

            this._accumulator.push(hexValue(byte))
          } else {
            throw errors.INVALID_CHUNK_LENGTH()
          }

          break
        }

        case CHUNK_EXTENSION: {
          this._checkHeaderSize()

          if (byte === CR) {
            if (this._remaining === 0) {
              this._state = LAST_CHUNK_LF
            } else {
              this._remaining += 2
              this._state = CHUNK_SIZE_LF
            }
          } else if (!isFieldByte(byte)) {
            throw errors.INVALID_CHUNK_LENGTH()
          }

          break
        }

        case CHUNK_SIZE_LF: {
          if (byte !== LF) throw errors.INVALID_CHUNK_LENGTH()

          this._state = CHUNK_DATA

          break
        }

        case LAST_CHUNK_LF: {
          if (byte !== LF) throw errors.INVALID_CHUNK_LENGTH()

          this._state = TRAILER_CR

          break
        }

        case TRAILER_CR: {
          if (byte !== CR) throw errors.INVALID_MESSAGE()

          this._state = TRAILER_LF

          break
        }

        case TRAILER_LF: {
          if (byte !== LF) throw errors.INVALID_MESSAGE()

          this._state = FIRST_TOKEN
          this._headerSize = 0

          yield { type: constants.END }

          break
        }

        default:
          throw errors.INVALID_MESSAGE()
      }
    }
  }
}

exports.constants = constants

const TOKEN_BYTES = Buffer.from([
  // 0x00-0x1f (control characters) + 0x20 (space)
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  // 0x21-0x41: ! " # $ % & ' ( ) * + , - . / 0-9 : ; < = > ? @ A
  1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1,
  // 0x42-0x62: B-Z [ \ ] ^ _ ` a b
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1,
  // 0x63-0x7f: c-z { | } ~ DEL
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0
])

function isTokenByte(b) {
  return TOKEN_BYTES[b] === 1
}

function isFieldByte(b) {
  return b === TAB || (b >= 0x20 && b <= 0x7e)
}

function isHex(b) {
  return (
    (b >= ZERO && b <= NINE) || (b >= UPPER_A && b <= UPPER_F) || (b >= LOWER_A && b <= LOWER_F)
  )
}

function hexValue(b) {
  if (b >= ZERO && b <= NINE) return b - ZERO
  if (b >= UPPER_A && b <= UPPER_F) return b - UPPER_A + 10
  return b - LOWER_A + 10
}
module.exports = class HTTPParserError extends Error {
  constructor(msg, fn = HTTPParserError, code = fn.name) {
    super(`${code}: ${msg}`)

    this.code = code

    if (Error.captureStackTrace) Error.captureStackTrace(this, fn)
  }

  get name() {
    return 'HTTPParserError'
  }

  static INVALID_MESSAGE(msg = 'Invalid HTTP message') {
    return new HTTPParserError(msg, HTTPParserError.INVALID_MESSAGE)
  }

  static INVALID_HEADER(msg = 'Invalid HTTP header') {
    return new HTTPParserError(msg, HTTPParserError.INVALID_HEADER)
  }

  static INVALID_CONTENT_LENGTH(msg = 'Invalid HTTP Content-Length') {
    return new HTTPParserError(msg, HTTPParserError.INVALID_CONTENT_LENGTH)
  }

  static INVALID_CHUNK_LENGTH(msg = 'Invalid HTTP chunk length') {
    return new HTTPParserError(msg, HTTPParserError.INVALID_CHUNK_LENGTH)
  }
}
{
  "name": "bare-http-parser",
  "version": "1.1.3",
  "description": "Streaming HTTP request and response parser for Bare",
  "exports": {
    "./package": "./package.json",
    ".": "./index.js",
    "./errors": "./lib/errors.js"
  },
  "files": [
    "index.js",
    "lib"
  ],
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-http-parser.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-http-parser/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-http-parser#readme",
  "devDependencies": {
    "brittle": "^3.3.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  }
}
exports.IncomingMessage = require('./lib/incoming-message')
exports.OutgoingMessage = require('./lib/outgoing-message')

exports.Agent = require('./lib/agent')
exports.globalAgent = exports.Agent.global

exports.Server = require('./lib/server')
exports.ServerResponse = require('./lib/server-response')
exports.ServerConnection = require('./lib/server-connection')

exports.ClientRequest = require('./lib/client-request')
exports.ClientConnection = require('./lib/client-connection')

exports.constants = require('./lib/constants')
exports.errors = require('./lib/errors')

exports.METHODS = Object.values(exports.constants.method) // For Node.js compatibility
exports.STATUS_CODES = exports.constants.status // For Node.js compatibility

exports.createServer = function createServer(opts, onrequest) {
  return new exports.Server(opts, onrequest)
}

exports.request = function request(url, opts, onresponse) {
  if (typeof opts === 'function') {
    onresponse = opts
    opts = {}
  }

  if (typeof url === 'string') url = new URL(url)

  if (isURL(url)) {
    opts = opts ? { ...url, ...opts } : { ...url }

    opts.host = url.hostname
    opts.path = url.pathname + url.search
    opts.port = url.port ? parseInt(url.port, 10) : defaultPort(url)
  } else {
    opts = url ? { ...url } : {}

    // For Node.js compatibility
    opts.host = opts.hostname || opts.host
    opts.port = typeof opts.port === 'string' ? parseInt(opts.port, 10) : opts.port
  }

  return new exports.ClientRequest(opts, onresponse)
}

exports.get = function get(url, opts, onresponse) {
  const req = exports.request(url, opts, onresponse)
  req.end()
  return req
}

// https://url.spec.whatwg.org/#default-port
function defaultPort(url) {
  switch (url.protocol) {
    case 'ftp:':
      return 21
    case 'http:':
    case 'ws:':
      return 80
    case 'https:':
    case 'wss:':
      return 443
  }

  return null
}

// https://url.spec.whatwg.org/#api
function isURL(url) {
  return (
    url !== null &&
    typeof url === 'object' &&
    typeof url.protocol === 'string' &&
    typeof url.hostname === 'string' &&
    typeof url.pathname === 'string' &&
    typeof url.search === 'string'
  )
}
const EventEmitter = require('bare-events')
const tcp = require('bare-tcp')
const HTTPClientConnection = require('./client-connection')
const errors = require('./errors')

class HTTPSocketSet {
  constructor() {
    this._sockets = new Map()
    this._size = 0
  }

  get size() {
    return this._size
  }

  add(name, socket) {
    const sockets = this._sockets.get(name)

    this._size++

    if (sockets === undefined) this._sockets.set(name, [socket])
    else sockets.push(socket)
  }

  pop(name) {
    const sockets = this._sockets.get(name)
    if (sockets === undefined || sockets.length === 0) return null

    this._size--

    const last = sockets.pop()

    if (sockets.length === 0) this._sockets.delete(name)

    return last
  }

  delete(name, socket) {
    const sockets = this._sockets.get(name)
    if (sockets === undefined) return

    const i = sockets.indexOf(socket)
    if (i === -1) return

    this._size--

    const last = sockets.pop()
    if (last !== socket) sockets[i] = last

    if (sockets.length === 0) this._sockets.delete(name)
  }

  *sockets() {
    for (const sockets of this._sockets.values()) {
      yield* sockets
    }
  }

  *[Symbol.iterator]() {
    for (const [name, sockets] of this._sockets) {
      for (const socket of sockets) yield [name, socket]
    }
  }
}

class HTTPAgent extends EventEmitter {
  constructor(opts = {}) {
    super()

    const { keepAlive = false, keepAliveMsecs = 1000, defaultPort = 80 } = opts

    this._suspended = false
    this._resuming = null

    this._sockets = new HTTPSocketSet()
    this._freeSockets = new HTTPSocketSet()

    this._keepAlive = typeof keepAlive === 'number' ? keepAlive : keepAlive ? keepAliveMsecs : -1
    this._defaultPort = defaultPort

    this._opts = { ...opts }
  }

  get suspended() {
    return this._suspended
  }

  get resumed() {
    return this._resuming ? this._resuming.promise : null
  }

  get sockets() {
    return this._sockets.sockets()
  }

  get freeSockets() {
    return this._freeSockets.sockets()
  }

  get defaultPort() {
    return this._defaultPort
  }

  createConnection(opts) {
    if (this._suspended) throw errors.AGENT_SUSPENDED()

    return tcp.createConnection(opts)
  }

  reuseSocket(socket, req) {
    socket.ref()
  }

  keepSocketAlive(socket) {
    if (this._keepAlive === -1) return false

    socket.setKeepAlive(true, this._keepAlive)
    socket.unref()

    return true
  }

  getName(opts) {
    return `${opts.host}:${opts.port}`
  }

  addRequest(req, opts) {
    opts = { ...opts, ...this._opts }

    const name = this.getName(opts)

    let socket = this._freeSockets.pop(name)

    if (socket) this.reuseSocket(socket, req)
    else {
      const agent = this

      socket = this.createConnection(opts)

      socket
        .on('error', noop) // someone needs to handle it
        .on('free', onfree)
        .on('end', onremove)
        .on('finish', onremove)
        .on('close', onremove)
        .on('timeout', ontimeout)

      function onfree() {
        if (socket.destroyed) return

        if (agent.keepSocketAlive(socket)) {
          agent._freeSockets.add(name, socket)
        } else {
          socket.end()
        }

        agent.emit('free', socket)
      }

      function onremove() {
        socket.off('free', onfree)

        agent._sockets.delete(name, socket)
        agent._freeSockets.delete(name, socket)

        if (agent._sockets.size === 0) HTTPAgent._agents.delete(agent)
      }

      function ontimeout() {
        socket.destroy()

        agent._freeSockets.delete(name, socket)
      }
    }

    if (this._sockets.size === 0) HTTPAgent._agents.add(this)

    this._sockets.add(name, socket)

    req._socket = socket

    const connection = HTTPClientConnection.from(socket, opts)

    connection._req = req
  }

  suspend() {
    if (this._suspended) return

    this._resuming = Promise.withResolvers()
    this._suspended = true

    this.destroy()
  }

  resume() {
    if (this._resuming === null) return

    this._resuming.resolve()
    this._resuming = null
    this._suspended = false
  }

  destroy() {
    for (const socket of this._sockets.sockets()) socket.destroy()
  }

  static _agents = new Set()

  static _onidle() {
    for (const agent of this._agents) {
      agent.destroy()
    }
  }
}

HTTPAgent.global = new HTTPAgent({ keepAlive: 1000, timeout: 5000 })

module.exports = HTTPAgent

Bare.on('idle', HTTPAgent._onidle.bind(HTTPAgent))

function noop() {}
const HTTPParser = require('bare-http-parser')
const HTTPIncomingMessage = require('./incoming-message')
const errors = require('./errors')

const {
  constants: { RESPONSE, DATA, END }
} = HTTPParser

const EMPTY = Buffer.alloc(0)

module.exports = class HTTPClientConnection {
  static _connections = new WeakMap()

  static for(socket) {
    return this._connections.get(socket) || null
  }

  static from(socket, opts) {
    return this.for(socket) || new this(socket, opts)
  }

  constructor(socket, opts = {}) {
    const { IncomingMessage = HTTPIncomingMessage } = opts

    this._socket = socket

    this._req = null
    this._res = null

    this._IncomingMessage = IncomingMessage

    this._parser = new HTTPParser()
    this._idle = true

    this._onerror = this._onerror.bind(this)
    this._onclose = this._onclose.bind(this)
    this._onend = this._onend.bind(this)
    this._ondata = this._ondata.bind(this)
    this._ondrain = this._ondrain.bind(this)
    this._ontimeout = this._ontimeout.bind(this)

    socket
      .on('error', this._onerror)
      .on('close', this._onclose)
      .on('end', this._onend)
      .on('data', this._ondata)
      .on('drain', this._ondrain)
      .on('timeout', this._ontimeout)

    HTTPClientConnection._connections.set(socket, this)
  }

  get socket() {
    return this._socket
  }

  get req() {
    return this._req
  }

  get res() {
    return this._res
  }

  get idle() {
    return this._idle
  }

  _onerror(err) {
    if (this._req) this._req.destroy(err)
  }

  _onclose() {
    if (this._req) this._req.destroy()
  }

  _onend() {
    if (this._req) this._req.destroy(errors.CONNECTION_LOST())
  }

  _ondata(data) {
    this._idle = false

    try {
      for (const op of this._parser.push(data)) {
        switch (op.type) {
          case RESPONSE:
            this._req.on('close', () => {
              this._req = null
            })

            this._res = new this._IncomingMessage(this._socket, {
              headers: op.headers,
              statusCode: op.code,
              statusMessage: op.reason
            })

            this._res.on('close', () => {
              this._res = null
              this._idle = true

              this._socket.emit('free')
            })

            if (op.headers.connection && op.headers.connection.toLowerCase() === 'upgrade') {
              return this._onupgrade(this._parser.end())
            }

            this._req.emit('response', this._res)
            break

          case DATA:
            this._res.push(op.data)
            break

          case END:
            if (this._res) {
              this._res._socket = null
              this._res.push(null)
            }

            if (this._req) {
              this._req._socket = null
              this._req.destroy()
            }
            break
        }
      }
    } catch (err) {
      this._socket.destroy(err)
    }
  }

  _onupgrade(data) {
    this._detach()

    const res = this._res
    const req = this._req

    res._upgrade = req._upgrade = true

    const upgraded = req.emit('upgrade', res, this._socket, data || EMPTY)

    res.push(null)
    req.destroy()

    if (!upgraded) this._socket.destroy()
  }

  _ontimeout() {
    if (this._req) this._req.emit('timeout')
  }

  _ondrain() {
    if (this._req) this._req._continueWrite()
  }

  _detach() {
    this._socket
      .off('error', this._onerror)
      .off('close', this._onclose)
      .off('end', this._onend)
      .off('data', this._ondata)
      .off('drain', this._ondrain)
      .off('timeout', this._ontimeout)

    HTTPClientConnection._connections.delete(this._socket)
  }
}
const HTTPAgent = require('./agent')
const HTTPOutgoingMessage = require('./outgoing-message')

const CHUNK_DELIMITER = Buffer.from('\r\n')
const CHUNK_TERMINATOR = Buffer.from('0\r\n\r\n')

module.exports = class HTTPClientRequest extends HTTPOutgoingMessage {
  constructor(opts = {}, onresponse = null) {
    if (typeof opts === 'function') {
      onresponse = opts
      opts = {}
    }

    opts = opts ? { ...opts } : {}

    const agent = opts.agent === false ? new HTTPAgent() : opts.agent || HTTPAgent.global
    const method = opts.method || 'GET'
    const path = opts.path || '/'
    const defaultPort = opts.defaultPort || (agent && agent.defaultPort) || 80
    const host = (opts.host = opts.host || 'localhost')
    const port = (opts.port = opts.port || defaultPort)
    const headers = { host: hostHeader(host, port, defaultPort), ...opts.headers }

    super()

    agent.addRequest(this, opts)

    this._headers = headers
    this._method = method
    this._path = path

    this._chunked = method !== 'GET' && method !== 'HEAD'

    this._pendingWrite = null
    this._pendingFinal = null

    if (onresponse) this.once('response', onresponse)
  }

  get method() {
    return this._method
  }

  get path() {
    return this._path
  }

  // For Node.js compatibility
  abort() {
    return this.destroy()
  }

  _header() {
    let h = `${this._method} ${this._path} HTTP/1.1\r\n`

    let upgrade = false

    for (const name of Object.keys(this._headers)) {
      const n = name.toLowerCase()
      const v = this._headers[name]

      if (n === 'content-length') this._chunked = false
      if (n === 'connection' && v && v.toLowerCase() === 'upgrade') upgrade = true

      h += `${httpCase(n)}: ${v}\r\n`
    }

    if (upgrade) this._chunked = false

    if (this._chunked) h += 'Transfer-Encoding: chunked\r\n'

    h += '\r\n'

    return h
  }

  _write(data, encoding, cb) {
    if (this._headersSent === false) this.flushHeaders()

    if (this._chunked) {
      this._socket.write(Buffer.from(data.byteLength.toString(16)))
      this._socket.write(CHUNK_DELIMITER)
    }

    let flushed = this._socket.write(data)

    if (this._chunked) flushed = this._socket.write(CHUNK_DELIMITER)

    if (flushed) cb(null)
    else this._pendingWrite = cb
  }

  _final(cb) {
    if (this._headersSent === false) this.flushHeaders()

    if (this._chunked) this._socket.write(CHUNK_TERMINATOR)

    this._pendingFinal = cb
  }

  _predestroy() {
    super._predestroy()

    this._continueWrite()
    this._continueFinal()
  }

  _continueWrite() {
    if (this._pendingWrite === null) return
    const cb = this._pendingWrite
    this._pendingWrite = null
    cb(null)
  }

  _continueFinal() {
    if (this._pendingFinal === null) return
    const cb = this._pendingFinal
    this._pendingFinal = null
    cb(null)
  }
}

function httpCase(n) {
  let s = ''
  for (const part of n.split('-')) {
    s += (s ? '-' : '') + part.slice(0, 1).toUpperCase() + part.slice(1)
  }
  return s
}

function hostHeader(host, port, defaultPort) {
  const i = host.indexOf(':')

  if (i !== -1 && host.includes(':', i + 1) && host.charCodeAt(0) !== 91 /* [ */) {
    host = `[${host}]`
  }

  if (port && +port !== defaultPort) {
    host += ':' + port
  }

  return host
}
module.exports = {
  method: {
    GET: 'GET',
    HEAD: 'HEAD',
    POST: 'POST',
    PUT: 'PUT',
    DELETE: 'DELETE',
    CONNECT: 'CONNECT',
    OPTIONS: 'OPTIONS',
    TRACE: 'TRACE',
    PATCH: 'PATCH'
  },
  status: {
    100: 'Continue',
    101: 'Switching Protocols',
    102: 'Processing',
    103: 'Early Hints',
    200: 'OK',
    201: 'Created',
    202: 'Accepted',
    203: 'Non-Authoritative Information',
    204: 'No Content',
    205: 'Reset Content',
    206: 'Partial Content',
    207: 'Multi-Status',
    208: 'Already Reported',
    226: 'IM Used',
    300: 'Multiple Choices',
    301: 'Moved Permanently',
    302: 'Found',
    303: 'See Other',
    304: 'Not Modified',
    305: 'Use Proxy',
    307: 'Temporary Redirect',
    308: 'Permanent Redirect',
    400: 'Bad Request',
    401: 'Unauthorized',
    402: 'Payment Required',
    403: 'Forbidden',
    404: 'Not Found',
    405: 'Method Not Allowed',
    406: 'Not Acceptable',
    407: 'Proxy Authentication Required',
    408: 'Request Timeout',
    409: 'Conflict',
    410: 'Gone',
    411: 'Length Required',
    412: 'Precondition Failed',
    413: 'Payload Too Large',
    414: 'URI Too Long',
    415: 'Unsupported Media Type',
    416: 'Range Not Satisfiable',
    417: 'Expectation Failed',
    418: "I'm a Teapot",
    421: 'Misdirected Request',
    422: 'Unprocessable Entity',
    423: 'Locked',
    424: 'Failed Dependency',
    425: 'Too Early',
    426: 'Upgrade Required',
    428: 'Precondition Required',
    429: 'Too Many Requests',
    431: 'Request Header Fields Too Large',
    451: 'Unavailable For Legal Reasons',
    500: 'Internal Server Error',
    501: 'Not Implemented',
    502: 'Bad Gateway',
    503: 'Service Unavailable',
    504: 'Gateway Timeout',
    505: 'HTTP Version Not Supported',
    506: 'Variant Also Negotiates',
    507: 'Insufficient Storage',
    508: 'Loop Detected',
    509: 'Bandwidth Limit Exceeded',
    510: 'Not Extended',
    511: 'Network Authentication Required'
  }
}
module.exports = class HTTPError extends Error {
  constructor(msg, fn = HTTPError, code = fn.name) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'HTTPError'
  }

  static NOT_IMPLEMENTED(msg = 'Method not implemented') {
    return new HTTPError(msg, HTTPError.NOT_IMPLEMENTED)
  }

  static CONNECTION_LOST(msg = 'Socket hung up') {
    return new HTTPError(msg, HTTPError.CONNECTION_LOST)
  }

  static AGENT_SUSPENDED(msg = 'Agent is suspended') {
    return new HTTPError(msg, HTTPError.AGENT_SUSPENDED)
  }
}
const { Readable } = require('bare-stream')

module.exports = class HTTPIncomingMessage extends Readable {
  constructor(socket = null, opts = {}) {
    super()

    this._socket = socket
    this._upgrade = false
    this._headers = opts.headers || {}

    // Server options
    this._method = opts.method || ''
    this._url = opts.url || ''

    // Client options
    this._statusCode = opts.statusCode || 0
    this._statusMessage = opts.statusMessage || ''
  }

  get socket() {
    return this._socket
  }

  get upgrade() {
    return this._upgrade
  }

  get headers() {
    return this._headers
  }

  set headers(value) {
    this._headers = value
  }

  get method() {
    return this._method
  }

  set method(value) {
    this._method = value
  }

  get url() {
    return this._url
  }

  set url(value) {
    this._url = value
  }

  get statusCode() {
    return this._statusCode
  }

  set statusCode(value) {
    this._statusCode = value
  }

  get statusMessage() {
    return this._statusMessage
  }

  set statusMessage(value) {
    this._statusMessage = value
  }

  get httpVersion() {
    return '1.1'
  }

  getHeader(name) {
    return this._headers[name.toLowerCase()]
  }

  getHeaders() {
    return { ...this._headers }
  }

  hasHeader(name) {
    return name.toLowerCase() in this._headers
  }

  setTimeout(ms, ontimeout) {
    if (ontimeout) this.once('timeout', ontimeout)

    this._socket.setTimeout(ms)

    return this
  }

  _predestroy() {
    if (this._upgrade === false && this._socket !== null) this._socket.destroy()
  }
}
const { Writable } = require('bare-stream')
const errors = require('./errors')

module.exports = class HTTPOutgoingMessage extends Writable {
  constructor(socket = null) {
    super()

    this._socket = socket
    this._upgrade = false
    this._headersSent = false
    this._headers = {}
  }

  get socket() {
    return this._socket
  }

  get upgrade() {
    return this._upgrade
  }

  get headersSent() {
    return this._headersSent
  }

  get headers() {
    return this._headers
  }

  set headers(value) {
    this._headers = value
  }

  getHeader(name) {
    return this._headers[name.toLowerCase()]
  }

  getHeaders() {
    return { ...this._headers }
  }

  hasHeader(name) {
    return name.toLowerCase() in this._headers
  }

  setHeader(name, value) {
    this._headers[name.toLowerCase()] = value
  }

  flushHeaders() {
    if (this._headersSent === true || this._socket === null) return

    this._socket.write(Buffer.from(this._header()))
    this._headersSent = true
  }

  setTimeout(ms, ontimeout) {
    if (ontimeout) this.once('timeout', ontimeout)

    this._socket.setTimeout(ms)

    return this
  }

  _header() {
    throw errors.NOT_IMPLEMENTED()
  }

  _predestroy() {
    if (this._upgrade === false && this._socket !== null) this._socket.destroy()
  }
}
const { isEnded, isFinished, getStreamError } = require('bare-stream')
const HTTPParser = require('bare-http-parser')
const HTTPIncomingMessage = require('./incoming-message')
const HTTPServerResponse = require('./server-response')

const {
  constants: { REQUEST, DATA, END }
} = HTTPParser

const EMPTY = Buffer.alloc(0)

module.exports = class HTTPServerConnection {
  static _connections = new WeakMap()

  static for(socket) {
    return this._connections.get(socket) || null
  }

  constructor(server, socket, opts = {}) {
    const { IncomingMessage = HTTPIncomingMessage, ServerResponse = HTTPServerResponse } = opts

    this._server = server
    this._socket = socket

    this._req = null
    this._res = null

    this._IncomingMessage = IncomingMessage
    this._ServerResponse = ServerResponse

    this._parser = new HTTPParser()
    this._idle = true

    this._onclose = this._onclose.bind(this)
    this._ondata = this._ondata.bind(this)
    this._ondrain = this._ondrain.bind(this)
    this._ontimeout = this._ontimeout.bind(this)

    socket
      .on('error', noop)
      .on('close', this._onclose)
      .on('data', this._ondata)
      .on('drain', this._ondrain)
      .on('timeout', this._ontimeout)

    HTTPServerConnection._connections.set(socket, this)

    if (this._server.timeout) socket.setTimeout(this._server.timeout)
  }

  get server() {
    return this._server
  }

  get socket() {
    return this._socket
  }

  get req() {
    return this._req
  }

  get res() {
    return this._res
  }

  get idle() {
    return this._idle
  }

  _onclose() {
    if (this._req && !isEnded(this._req)) this._req.destroy()
    if (this._res && !isFinished(this._res)) this._res.destroy()

    const err = getStreamError(this._socket)
    if (err) this._socket.destroy(err)
  }

  _ondata(data) {
    this._idle = false

    try {
      for (const op of this._parser.push(data)) {
        switch (op.type) {
          case REQUEST:
            this._req = new this._IncomingMessage(this._socket, {
              headers: op.headers,
              method: op.method,
              url: op.url
            })

            this._req.on('close', () => {
              this._req = null

              this._idle = true

              if (this._server.closing) this._socket.destroy()
            })

            // Eagerly open the request stream
            this._req.resume()
            this._req.pause()

            if (op.headers.connection && op.headers.connection.toLowerCase() === 'upgrade') {
              return this._onupgrade(this._parser.end())
            }

            this._res = new this._ServerResponse(this._socket, this._req)

            this._res.on('close', () => {
              this._res = null
            })

            this._server.emit('request', this._req, this._res)
            break

          case DATA:
            this._req.push(op.data)
            break

          case END:
            if (this._req) {
              this._req._socket = null
              this._req.push(null)
            }
            break
        }
      }
    } catch (err) {
      this._socket.destroy(err)
    }
  }

  _onupgrade(data) {
    this._detach()

    const req = this._req

    req._upgrade = true

    const upgraded = this._server.emit('upgrade', req, this._socket, data || EMPTY)

    req.push(null)

    if (!upgraded) this._socket.destroy()
  }

  _ontimeout() {
    const reqTimeout = this._req && this._req.emit('timeout')
    const resTimeout = this._res && this._res.emit('timeout')
    const serverTimeout = this._server.emit('timeout', this._socket)

    if (!reqTimeout && !resTimeout && !serverTimeout) this._socket.destroy()
  }

  _ondrain() {
    if (this._res) this._res._continueWrite()
  }

  _detach() {
    this._socket
      .off('error', noop)
      .off('close', this._onclose)
      .off('data', this._ondata)
      .off('drain', this._ondrain)
      .off('timeout', this._ontimeout)

    HTTPServerConnection._connections.delete(this._socket)
  }
}

function noop() {}
const { isFinishing } = require('bare-stream')
const HTTPOutgoingMessage = require('./outgoing-message')
const constants = require('./constants')

const CHUNK_DELIMITER = Buffer.from('\r\n')
const CHUNK_TERMINATOR = Buffer.from('0\r\n\r\n')

module.exports = class HTTPServerResponse extends HTTPOutgoingMessage {
  constructor(socket, req) {
    super(socket)

    this._req = req

    this._statusCode = 200
    this._statusMessage = null

    this._chunked = true
    this._close = req.headers.connection === 'close'
    this._onlyHeaders = req.method === 'HEAD'

    this._pendingWrite = null
  }

  get req() {
    return this._req
  }

  get statusCode() {
    return this._statusCode
  }

  set statusCode(value) {
    this._statusCode = value
  }

  get statusMessage() {
    return this._statusMessage
  }

  set statusMessage(value) {
    this._statusMessage = value
  }

  writeHead(statusCode, statusMessage = null, headers = {}) {
    if (typeof statusMessage === 'object' && statusMessage !== null) {
      headers = statusMessage
      statusMessage = null
    }

    this._statusCode = statusCode
    this._statusMessage = statusMessage || null

    if (headers) this._headers = { ...this._headers, ...headers }
  }

  _header() {
    let h =
      'HTTP/1.1 ' +
      this._statusCode +
      ' ' +
      (this._statusMessage === null ? constants.status[this._statusCode] : this._statusMessage) +
      '\r\n'

    for (const name of Object.keys(this._headers)) {
      const n = name.toLowerCase()
      const v = this._headers[name]

      if (n === 'content-length') this._chunked = false
      if (n === 'connection' && v && v.toLowerCase() === 'close') this._close = true

      h += httpCase(n) + ': ' + v + '\r\n'
    }

    if (this._chunked) h += 'Transfer-Encoding: chunked\r\n'

    h += '\r\n'

    return h
  }

  _write(data, encoding, cb) {
    if (this._headersSent === false) {
      if (isFinishing(this)) {
        this.setHeader(
          'Content-Length',
          (data.byteLength + this._writableState.buffered).toString()
        )
      }

      this.flushHeaders()
    }

    if (this._onlyHeaders === true) return cb(null)

    if (this._chunked) {
      this._socket.write(Buffer.from(data.byteLength.toString(16)))
      this._socket.write(CHUNK_DELIMITER)
    }

    let flushed = this._socket.write(data)

    if (this._chunked) flushed = this._socket.write(CHUNK_DELIMITER)

    if (flushed) cb(null)
    else this._pendingWrite = cb
  }

  _final(cb) {
    if (this._headersSent === false) {
      this.setHeader('Content-Length', '0')
      this.flushHeaders()
    }

    if (this._chunked && this._onlyHeaders === false) this._socket.write(CHUNK_TERMINATOR)

    if (this._close) this._socket.end()

    cb(null)
  }

  _predestroy() {
    super._predestroy()

    this._req.destroy()

    this._continueWrite()
  }

  _continueWrite() {
    if (this._pendingWrite === null) return
    const cb = this._pendingWrite
    this._pendingWrite = null
    cb(null)
  }
}

function httpCase(n) {
  let s = ''
  for (const part of n.split('-')) {
    s += (s ? '-' : '') + part.slice(0, 1).toUpperCase() + part.slice(1)
  }
  return s
}
const TCPServer = require('bare-tcp').Server
const HTTPServerConnection = require('./server-connection')

module.exports = class HTTPServer extends TCPServer {
  constructor(opts = {}, onrequest) {
    if (typeof opts === 'function') {
      onrequest = opts
      opts = {}
    }

    super({ allowHalfOpen: false })

    this._timeout = 0

    this.on('connection', (socket) => {
      new HTTPServerConnection(this, socket, opts)
    })

    if (onrequest) this.on('request', onrequest)
  }

  get timeout() {
    return this._timeout || undefined // For Node.js compatibility
  }

  setTimeout(ms = 0, ontimeout) {
    if (ontimeout) this.on('timeout', ontimeout)

    this._timeout = ms

    return this
  }

  close(onclose) {
    super.close(onclose)

    for (const socket of this.connections) {
      const connection = HTTPServerConnection.for(socket)

      if (connection === null || connection.idle) {
        socket.destroy()
      }
    }

    return this
  }
}
{
  "name": "bare-http1",
  "version": "4.5.6",
  "description": "Native HTTP/1 library for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    },
    "./errors": {
      "types": "./lib/errors.d.ts",
      "default": "./lib/errors.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-http1.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-http1/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-http1#readme",
  "dependencies": {
    "bare-events": "^2.6.0",
    "bare-http-parser": "^1.1.1",
    "bare-stream": "^2.10.0",
    "bare-tcp": "^2.2.0"
  },
  "devDependencies": {
    "bare-buffer": "^3.0.2",
    "bare-url": "^2.1.3",
    "brittle": "^3.3.0",
    "lunte": "^1.6.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "bare-buffer": "*",
    "bare-url": "*"
  },
  "peerDependenciesMeta": {
    "bare-buffer": {
      "optional": true
    },
    "bare-url": {
      "optional": true
    }
  }
}
module.exports = require.addon()
const ansiEscapes = require('bare-ansi-escapes')
const getType = require('bare-type')
const binding = require('./binding')

const PLAIN_KEY = /^[a-zA-Z_][a-zA-Z_0-9]*$/

const defaultDepth = 2
const defaultBreakLength = 80
const defaultMaxArrayLength = 40

module.exports = exports = function inspect(value, opts = {}) {
  const {
    colors = false,
    depth = defaultDepth,
    breakLength = defaultBreakLength,
    stylize = defaultStylize(colors)
  } = opts

  const references = new InspectRefMap()

  const tree = inspectValue(value, 0, {
    colors,
    depth,
    breakLength,
    stylize,
    references
  })

  return tree.toString()
}

exports.styles = {
  bigint: ansiEscapes.colorYellow,
  boolean: ansiEscapes.colorYellow,
  date: ansiEscapes.colorMagenta,
  module: ansiEscapes.modifierUnderline,
  name: ansiEscapes.modifierReset,
  null: ansiEscapes.modifierBold,
  number: ansiEscapes.colorYellow,
  regexp: ansiEscapes.colorRed,
  special: ansiEscapes.colorCyan,
  string: ansiEscapes.colorGreen,
  symbol: ansiEscapes.colorGreen,
  undefined: ansiEscapes.colorBrightBlack
}

const styles = exports.styles

function defaultStylize(colors) {
  return function stylize(value, style) {
    const color = colors && styles[style]

    if (color) return color + value + ansiEscapes.modifierReset

    return value
  }
}

class InspectRefMap {
  constructor() {
    this.refs = new WeakMap()
    this.ids = new WeakMap()
    this.nextId = 1
  }

  has(object) {
    return this.refs.has(object)
  }

  get(object) {
    return this.refs.get(object) || null
  }

  set(object, ref) {
    this.refs.set(object, ref)
  }

  id(object) {
    let id = this.ids.get(object)
    if (id) return id

    id = this.nextId++
    this.ids.set(object, id)

    return id
  }
}

class InspectNode {
  constructor(depth, length, opts) {
    const { breakLength = defaultBreakLength, breakAlways = false } = opts

    this.depth = depth
    this.length = length
    this.breakLength = breakLength
    this.breakAlways = breakAlways
  }

  pad(n, string) {
    return string.padStart(n, ' ')
  }

  indent(n, string) {
    return '  '.repeat(n) + string
  }
}

class InspectRef extends InspectNode {
  constructor(depth, opts) {
    super(depth, '[circular *]'.length, opts)

    this.refs = opts.references
    this.count = 0
    this.circular = false
    this.color = opts.colors && styles.special
  }

  get id() {
    return this.refs.id(this)
  }

  increment() {
    return ++this.count
  }

  decrement() {
    return --this.count
  }

  toString(opts = {}) {
    const { offset = 0, pad = 0, indent = 0 } = opts

    let value = this.pad(pad, '[circular *' + this.id + ']')

    if (this.color) value = this.color + value + ansiEscapes.modifierReset

    return offset ? value : this.indent(indent, value)
  }
}

class InspectLeaf extends InspectNode {
  constructor(value, color, depth, opts) {
    const length = value.length

    if (value.includes('\n')) {
      value = value.replaceAll('\n', '\n' + '  '.repeat(depth))

      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.value = value
    this.color = opts.colors && color
  }

  toString(opts = {}) {
    const { offset = 0, pad = 0, indent = 0 } = opts

    let value = this.pad(pad, this.value)

    if (this.color) value = this.color + value + ansiEscapes.modifierReset

    return offset ? value : this.indent(indent, value)
  }
}

class InspectPair extends InspectNode {
  constructor(delim, left, right, depth, opts) {
    const length = left.length + delim.length + right.length

    if (left.breakAlways || right.breakAlways) {
      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.delim = delim
    this.left = left
    this.right = right
  }

  toString(opts = {}) {
    const { indent = 0 } = opts

    return this.indent(
      indent,
      this.left +
        this.delim +
        this.right.toString({
          indent,
          offset: this.left.length + this.delim.length
        })
    )
  }
}

class InspectSuspension extends InspectNode {
  constructor(overflow, depth, opts) {
    const label = `... ${overflow} more`

    super(depth, label.length, opts)

    this.label = label
  }

  toString(opts = {}) {
    const { indent = 0 } = opts

    return this.indent(indent, this.label)
  }
}

class InspectSequence extends InspectNode {
  constructor(header, footer, delim, values, ref, depth, opts) {
    const { tabulate = false } = opts

    const length =
      (ref.circular ? '<ref *>'.length + 1 : 0) +
      header.length +
      values.reduce(
        (length, value, i) =>
          length + value.length + (i === 0 ? 0 : delim.length),
        0
      ) +
      footer.length

    if (values.some((value) => value.breakAlways)) {
      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.header = header
    this.footer = footer
    this.delim = delim
    this.values = values
    this.ref = ref
    this.tabulate = tabulate
  }

  toString(opts = {}) {
    const { offset = 0, indent = 0 } = opts

    const split =
      this.breakAlways ||
      (this.values.length &&
        (offset + this.length > this.breakLength ||
          indent * 2 + this.length > this.breakLength))

    let header = this.header

    if (this.ref.circular) {
      header = '<ref *' + this.ref.id + '> ' + header
    }

    if (this.values.length === 0) {
      header = header.trimEnd()
    }

    if (offset === 0) {
      header = this.indent(indent, header)
    }

    if (split) {
      header = header.trimEnd() + '\n'
    }

    let string = header

    let columns = 1
    let pad = 0

    if (this.tabulate) {
      const widest = this.values.reduce(
        (length, value) =>
          value.breakAlways ? length : Math.max(length, value.length),
        0
      )

      if (widest) {
        columns = Math.max(
          columns,
          Math.floor(
            (this.breakLength - indent * 2) / (widest + this.delim.length)
          )
        )

        if (columns > 1) pad = widest
      }
    }

    for (let i = 0, n = this.values.length, offset = 0; i < n; i++) {
      const value = this.values[i]

      if (split) {
        let part

        if (i % columns === 0 || value.breakAlways) {
          part = value.toString({ indent: indent + 1, pad })
        } else {
          part = value.toString({ pad })
        }

        string += part

        if (i < n - 1) {
          if (i % columns === columns - 1 || this.values[i + 1].breakAlways) {
            string += this.delim.trimEnd() + '\n'
          } else {
            string += this.delim
          }
        }
      } else {
        if (i > 0) string += this.delim

        string += value.toString({ offset })

        offset += value.length
      }
    }

    let footer = this.footer

    if (this.values.length === 0) {
      footer = footer.trimStart()
    }

    if (split) {
      string += '\n' + this.indent(indent, footer.trimStart())
    } else {
      string += footer
    }

    return string
  }
}

function inspectValue(value, depth, opts) {
  const type = getType(value)

  if (type.isUndefined()) return inspectUndefined(depth, opts)
  if (type.isNull()) return inspectNull(depth, opts)
  if (type.isBoolean()) return inspectBoolean(value, depth, opts)
  if (type.isNumber()) return inspectNumber(value, depth, opts)
  if (type.isBigInt()) return inspectBigInt(value, depth, opts)
  if (type.isString()) return inspectString(value, depth, opts)
  if (type.isSymbol()) return inspectSymbol(value, depth, opts)
  if (type.isObject()) return inspectObject(type, value, depth, opts)
  if (type.isFunction()) return inspectFunction(type, value, depth, opts)
  if (type.isExternal()) return inspectExternal(value, opts, opts)
}

function inspectUndefined(depth, opts) {
  return new InspectLeaf('undefined', styles.undefined, depth, opts)
}

function inspectNull(depth, opts) {
  return new InspectLeaf('null', styles.null, depth, opts)
}

function inspectBoolean(value, depth, opts) {
  return new InspectLeaf(value.toString(), styles.boolean, depth, opts)
}

function inspectNumber(value, depth, opts) {
  let string

  if (Object.is(value, -0)) {
    string = '-0'
  } else {
    string = value.toString(10)
  }

  return new InspectLeaf(string, styles.number, depth, opts)
}

function inspectBigInt(value, depth, opts) {
  return new InspectLeaf(value.toString(10) + 'n', styles.bigint, depth, opts)
}

const STRING_ESCAPES =
  /[\ud800-\udbff][\udc00-\udfff]|[\u0000-\u001f'\\\ud800-\udfff]/g

function inspectString(value, depth, opts) {
  // https://tc39.es/ecma262/multipage/structured-data.html#sec-quotejsonstring
  const string = value.replace(STRING_ESCAPES, (match) => {
    if (match.length === 2) return match

    switch (match) {
      case "'":
        return "\\'"
      case '\\':
        return '\\\\'
      case '\b':
        return '\\b'
      case '\t':
        return '\\t'
      case '\n':
        return '\\n'
      case '\f':
        return '\\f'
      case '\r':
        return '\\r'
      default:
        return '\\u' + match.charCodeAt(0).toString(16).padStart(4, '0')
    }
  })

  return new InspectLeaf("'" + string + "'", styles.string, depth, opts)
}

function inspectSymbol(value, depth, opts) {
  return new InspectLeaf(value.toString(), styles.symbol, depth, opts)
}

function inspectKey(value, depth, opts) {
  if (PLAIN_KEY.test(value)) {
    return new InspectLeaf(value, null, depth, opts)
  } else {
    return inspectValue(value, depth, opts)
  }
}

function inspectObject(type, object, depth, opts) {
  const refs = opts.references

  let ref = refs.get(object)
  if (ref === null) {
    ref = new InspectRef(depth, opts)
    refs.set(object, ref)
  } else if (ref.count) {
    ref.circular = true
    return ref
  }

  const maxDepth = typeof opts.depth === 'number' ? opts.depth : Infinity

  if (maxDepth < depth) {
    const constructor = object.constructor

    return new InspectLeaf(
      '[' +
        (constructor && constructor.name ? constructor.name : 'Object') +
        ']',
      styles.special,
      depth,
      opts
    )
  }

  const inspect =
    object[Symbol.for('bare.inspect')] ||
    object[Symbol.for('nodejs.util.inspect.custom')]

  if (typeof inspect === 'function') {
    const value = inspect.call(
      object,
      typeof opts.depth === 'number' ? opts.depth - depth : null,
      {
        colors: opts.colors,
        breakLength: opts.breakLength,
        stylize: opts.stylize
      },
      exports
    )

    if (typeof value === 'object' && value !== null) {
      refs.set(value, ref)
    }

    if (typeof value !== 'string') {
      return inspectValue(value, depth, opts)
    }

    return new InspectLeaf(value, null, depth, opts)
  }

  if (type.isArray()) return inspectArray(object, ref, depth, opts)
  if (type.isDate()) return inspectDate(object, ref, depth, opts)
  if (type.isRegExp()) return inspectRegExp(object, ref, depth, opts)
  if (type.isError()) return inspectError(object, ref, depth, opts)
  if (type.isPromise()) return inspectPromise(object, ref, depth, opts)
  if (type.isMap()) return inspectMap(object, ref, depth, opts)
  if (type.isSet()) return inspectSet(object, ref, depth, opts)
  if (type.isWeakMap()) return inspectWeakMap(object, ref, depth, opts)
  if (type.isWeakSet()) return inspectWeakSet(object, ref, depth, opts)
  if (type.isWeakRef()) return inspectWeakRef(object, ref, depth, opts)
  if (type.isArrayBuffer()) return inspectArrayBuffer(object, ref, depth, opts)
  if (type.isSharedArrayBuffer())
    return inspectSharedArrayBuffer(object, ref, depth, opts)
  if (type.isTypedArray()) return inspectTypedArray(object, ref, depth, opts)
  if (type.isDataView()) return inspectDataView(object, ref, depth, opts)

  ref.increment()

  const values = []

  for (const key in object) {
    if (key === 'constructor') continue

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(object[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  let header = '{ '

  const tag = object[Symbol.toStringTag]

  if (tag) header = '[' + tag + '] ' + header

  if (object.constructor) {
    const name = object.constructor.name

    if (name && name !== 'Object') {
      header = object.constructor.name + ' ' + header
    }
  }

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectArray(array, ref, depth, opts) {
  const { maxArrayLength = defaultMaxArrayLength } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxArrayLength, 0)

  for (let i = 0, n = array.length; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(array.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(inspectValue(array[i], depth + 1, opts))
  }

  for (const key of binding.getOwnNonIndexPropertyNames(array)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(array[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  let header = '[ '

  if (array.constructor.name !== 'Array') {
    header = array.constructor.name + '(' + array.length + ') ' + header
  }

  return new InspectSequence(header, ' ]', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectDate(date, ref, depth, opts) {
  return new InspectLeaf(date.toISOString(), styles.date, depth, opts)
}

function inspectRegExp(regExp, ref, depth, opts) {
  return new InspectLeaf(regExp.toString(), styles.regexp, depth, opts)
}

function inspectError(error, ref, depth, opts) {
  let header

  if ('stack' in error) {
    header = error.stack

    if (depth > 0) {
      header = header.replaceAll('\n', '\n' + '  '.repeat(depth))
    }
  } else {
    header = error.toString()
  }

  const builtins = ['cause']

  if (error.name === 'AggregateError') {
    builtins.push('errors')
  } else if (error.name === 'SuppressedError') {
    builtins.push('error', 'suppressed')
  }

  const values = []

  for (const key of builtins) {
    if (key in error === false) continue

    values.push(
      new InspectPair(
        ': ',
        new InspectLeaf('[' + key + ']', null, depth + 1, opts),
        inspectValue(error[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key in error) {
    if (key === 'constructor' || builtins.includes(key)) continue

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(error[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  if (values.length === 0) return new InspectLeaf(header, null, depth, opts)

  return new InspectSequence(
    header + ' {',
    ' }',
    ', ',
    values,
    ref,
    depth,
    opts
  )
}

function inspectPromise(promise, ref, depth, opts) {
  ref.increment()

  const state = binding.getPromiseState(promise)

  const values = []

  switch (state) {
    case 0: // Pending
      values.push(new InspectLeaf('<pending>', styles.special, depth, opts))
      break

    case 1: // Fulfilled
      values.push(inspectValue(binding.getPromiseResult(promise), depth, opts))
      break

    case 2: // Rejected
      values.push(
        new InspectLeaf('<rejected>', styles.special, depth, opts),
        inspectValue(binding.getPromiseResult(promise), depth, opts)
      )
  }

  ref.decrement()

  const header = promise.constructor.name + ' { '

  return new InspectSequence(header, ' }', ' ', values, ref, depth, opts)
}

function inspectMap(map, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxMapLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = maxMapLength

  for (const entry of map) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(map.size - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )
      break
    }

    values.push(
      new InspectPair(
        ' => ',
        inspectValue(entry[0], depth + 1, opts),
        inspectValue(entry[1], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key in map) {
    if (key === 'constructor') continue

    const value = inspectValue(map[key], depth + 1, opts)

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        value,
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = map.constructor.name + '(' + map.size + ') { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectSet(set, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxSetLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = maxSetLength

  for (const entry of set) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(set.size - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )
      break
    }

    values.push(inspectValue(entry, depth + 1, opts))
  }

  for (const key in set) {
    if (key === 'constructor') continue

    const value = inspectValue(set[key], depth + 1, opts)

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        value,
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = set.constructor.name + '(' + set.size + ') { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectWeakMap(weakMap, ref, depth, opts) {
  const header = weakMap.constructor.name + ' { '

  return new InspectSequence(
    header,
    ' }',
    ' ',
    [new InspectLeaf('<items unknown>', styles.special, depth + 1, opts)],
    ref,
    depth,
    opts
  )
}

function inspectWeakSet(weakSet, ref, depth, opts) {
  const header = weakSet.constructor.name + ' { '

  return new InspectSequence(
    header,
    ' }',
    ' ',
    [new InspectLeaf('<items unknown>', styles.special, depth + 1, opts)],
    ref,
    depth,
    opts
  )
}

function inspectWeakRef(weakRef, ref, depth, opts) {
  const target = weakRef.deref()

  let value

  if (target === undefined) {
    value = new InspectLeaf('<cleared>', styles.special, depth + 1, opts)
  } else {
    value = inspectValue(target, depth + 1, opts)
  }

  const header = weakRef.constructor.name + ' { '

  return new InspectSequence(header, ' }', ' ', [value], ref, depth, opts)
}

function inspectArrayBuffer(arrayBuffer, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(arrayBuffer[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = arrayBuffer.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectSharedArrayBuffer(sharedArrayBuffer, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(sharedArrayBuffer[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = sharedArrayBuffer.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectTypedArray(typedArray, ref, depth, opts) {
  if (Buffer.isBuffer(typedArray)) {
    return inspectBuffer(typedArray, ref, depth, opts)
  }

  const {
    maxArrayLength = defaultMaxArrayLength,
    maxTypedArrayLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxTypedArrayLength, 0)

  for (let i = 0, n = typedArray.length; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(typedArray.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(inspectValue(typedArray[i], depth + 1, opts))
  }

  for (const key of binding.getOwnNonIndexPropertyNames(typedArray)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(typedArray[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = typedArray.constructor.name + '(' + typedArray.length + ') [ '

  return new InspectSequence(header, ' ]', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectBuffer(buffer, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxBufferLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxBufferLength, 0)

  for (let i = 0, n = buffer.byteLength; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(buffer.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(
      new InspectLeaf(
        buffer[i].toString(16).padStart(2, '0'),
        null,
        depth + 1,
        opts
      )
    )
  }

  for (const key of binding.getOwnNonIndexPropertyNames(buffer)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(buffer[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  return new InspectSequence('<Buffer ', '>', ' ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectDataView(dataView, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength', 'byteOffset', 'buffer']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(dataView[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key of binding.getOwnNonIndexPropertyNames(dataView)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(dataView[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = dataView.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectFunction(type, fn, depth, opts) {
  if (fn.toString().startsWith('class')) return inspectClass(fn, depth, opts)

  let tag = 'function'

  if (type.isGeneratorFunction()) tag = 'generator ' + tag
  if (type.isAsyncFunction()) tag = 'async ' + tag

  return new InspectLeaf(
    '[' + tag + ' ' + (fn.name ? fn.name : '(anonymous)') + ']',
    styles.special,
    depth,
    opts
  )
}

function inspectClass(ctor, depth, opts) {
  return new InspectLeaf(
    '[class ' + (ctor.name ? ctor.name : '(anonymous)') + ']',
    styles.special,
    depth,
    opts
  )
}

function inspectExternal(external, depth, opts) {
  return new InspectLeaf(
    '[external 0x' + binding.getExternal(external).toString(16) + ']',
    styles.special,
    depth,
    opts
  )
}
{
  "name": "bare-inspect",
  "version": "3.1.4",
  "description": "Inspect objects as strings for debugging",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-inspect.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-inspect/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-inspect#readme",
  "engines": {
    "bare": ">=1.18.0"
  },
  "dependencies": {
    "bare-ansi-escapes": "^2.1.0",
    "bare-type": "^1.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
const EventEmitter = require('bare-events')
const { Duplex } = require('bare-stream')
const tcp = require('bare-tcp')
const pipe = require('bare-pipe')

const defaultReadBufferSize = 65536

const constants = exports.constants = {
  type: {
    TCP: 1,
    IPC: 2
  },
  state: {
    UNREFED: 0x1
  }
}

const Socket = exports.Socket = class NetSocket extends Duplex {
  constructor (opts = {}) {
    super({ eagerOpen: true })

    const {
      readBufferSize = defaultReadBufferSize,
      allowHalfOpen = true
    } = opts

    this._opts = { readBufferSize, allowHalfOpen }
    this._type = 0
    this._state = 0
    this._socket = null

    this._pendingWrite = null
    this._pendingFinal = null
  }

  get connecting () {
    return this._socket !== null && this._socket.connecting
  }

  get pending () {
    return this._socket === null || this._socket.pending
  }

  connect (...args) {
    let opts = {}
    let onconnect

    // connect(path[, onconnect])
    if (typeof args[0] === 'string') {
      opts.path = args[0]
      onconnect = args[1]
    // connect(port[, host][, onconnect])
    } else if (typeof args[0] === 'number') {
      opts.port = args[0]

      if (typeof args[1] === 'function') {
        onconnect = args[1]
      } else {
        opts.host = args[1]
        onconnect = args[2]
      }
    // connect(opts[, onconnect])
    } else {
      opts = args[0] || {}
      onconnect = args[1]
    }

    opts = { ...opts, ...this._opts }

    if (opts.path) {
      this._attach(constants.type.IPC, pipe.createConnection(opts))
    } else {
      this._attach(constants.type.TCP, tcp.createConnection(opts))
    }

    if (onconnect) this.once('connect', onconnect)

    return this
  }

  ref () {
    this._state &= ~constants.state.UNREFED
    if (this._socket !== null) this._socket.ref()
  }

  unref () {
    this._state |= constants.state.UNREFED
    if (this._socket !== null) this._socket.unref()
  }

  _attach (type, socket) {
    this._type = type
    this._socket = socket

    this._socket
      .on('connect', this._onconnect.bind(this))
      .on('error', this._onerror.bind(this))
      .on('close', this._onclose.bind(this))
      .on('end', this._onend.bind(this))
      .on('data', this._ondata.bind(this))
      .on('drain', this._ondrain.bind(this))

    if (this._state & constants.state.UNREFED) this._socket.unref()

    return this
  }

  _write (data, encoding, cb) {
    if (this._socket !== null && this._socket.write(data)) cb(null)
    else this._pendingWrite = cb
  }

  _final (cb) {
    if (this._socket === null) return cb(null)
    this._pendingFinal = cb
    this._socket.end()
  }

  _predestroy () {
    if (this._socket === null) return
    this._socket.destroy()
  }

  _onconnect () {
    this._ondrain() // Flush any pending writes

    this.emit('connect')
  }

  _onerror (err) {
    this.destroy(err)
  }

  _onend () {
    if (this._pendingFinal === null) return
    const cb = this._pendingFinal
    this._pendingFinal = null
    cb(null)
  }

  _onclose () {
    this.push(null)
  }

  _ondata (data) {
    this.push(data)
  }

  _ondrain () {
    if (this._pendingWrite === null) return
    const cb = this._pendingWrite
    this._pendingWrite = null
    cb(null)
  }
}

const Server = exports.Server = class NetServer extends EventEmitter {
  constructor (opts = {}, onconnection) {
    if (typeof opts === 'function') {
      onconnection = opts
      opts = {}
    }

    super()

    const {
      readBufferSize = defaultReadBufferSize,
      allowHalfOpen = true
    } = opts

    this._opts = { readBufferSize, allowHalfOpen }
    this._type = 0
    this._state = 0
    this._server = null

    if (onconnection) this.on('connection', onconnection)
  }

  get listening () {
    return this._server !== null && this._server.listening
  }

  address () {
    return this._server === null ? null : this._server.address()
  }

  listen (...args) {
    let opts = {}
    let onlistening

    // listen(path[, backlog][, onlistening])
    if (typeof args[0] === 'string') {
      opts.path = args[0]

      if (typeof args[1] === 'function') {
        onlistening = args[1]
      } else {
        opts.backlog = args[1]
        onlistening = args[2]
      }
    // listen([port[, host[, backlog]]][, onlistening])
    } else {
      if (typeof args[0] === 'function') {
        onlistening = args[0]
      } else {
        opts.port = args[0]

        if (typeof args[1] === 'function') {
          onlistening = args[1]
        } else {
          opts.host = args[1]

          if (typeof args[2] === 'function') {
            onlistening = args[2]
          } else {
            opts.backlog = args[2]
            onlistening = args[3]
          }
        }
      }
    }

    opts = { ...opts, ...this._opts }

    if (opts.path) {
      this._attach(constants.type.IPC, pipe.createServer(opts))
    } else {
      this._attach(constants.type.TCP, tcp.createServer(opts))
    }

    this._server.listen(opts)

    if (onlistening) this.once('listening', onlistening)

    return this
  }

  close (onclose) {
    if (onclose) this.once('close', onclose)
    this._server.close()
  }

  ref () {
    this._state &= ~constants.state.UNREFED
    if (this._server !== null) this._server.ref()
  }

  unref () {
    this._state |= constants.state.UNREFED
    if (this._server !== null) this._server.unref()
  }

  _attach (type, server) {
    this._type = type
    this._server = server

    this._server
      .on('listening', this._onlistening.bind(this))
      .on('connection', this._onconnection.bind(this))
      .on('error', this._onerror.bind(this))
      .on('close', this._onclose.bind(this))

    if (this._state & constants.state.UNREFED) this._server.unref()

    return this
  }

  _onlistening () {
    this.emit('listening')
  }

  _onconnection (socket) {
    this.emit('connection', new Socket(this._opts)._attach(this._type, socket))
  }

  _onerror (err) {
    this.emit('error', err)
  }

  _onclose () {
    this.emit('close')
  }
}

exports.isIP = tcp.isIP
exports.isIPv4 = tcp.isIPv4
exports.isIPv6 = tcp.isIPv6

exports.createConnection = function createConnection (...args) {
  let opts = {}
  let onconnect

  // createConnection(path[, onconnect])
  if (typeof args[0] === 'string') {
    opts.path = args[0]
    onconnect = args[1]
  // createConnection(port[, host][, onconnect])
  } else if (typeof args[0] === 'number') {
    opts.port = args[0]

    if (typeof args[1] === 'function') {
      onconnect = args[1]
    } else {
      opts.host = args[1]
      onconnect = args[2]
    }
  // createConnection(opts[, onconnect])
  } else {
    opts = args[0] || {}
    onconnect = args[1]
  }

  return new Socket(opts).connect(opts, onconnect)
}

exports.createServer = function createServer (opts, onconnection) {
  return new Server(opts, onconnection)
}
module.exports = require.addon()
const binding = require('./binding')

function onlookup (err, addresses) {
  const req = this

  if (err) return req.cb(err, null, 0)

  const { address, family } = addresses[0]

  return req.cb(null, address, family)
}

function onlookupall (err, addresses) {
  const req = this

  if (err) return req.cb(err, null)

  return req.cb(null, addresses)
}

exports.lookup = function lookup (hostname, opts = {}, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  let {
    family = 0,
    all = false
  } = opts

  if (typeof family === 'string') {
    switch (family) {
      case 'IPv4': family = 4
        break
      case 'IPv6': family = 6
        break
      default: family = 0
    }
  }

  const req = {
    cb,
    handle: null
  }

  req.handle = binding.lookup(hostname, family || 0, all, req, all ? onlookupall : onlookup)
}
{
  "name": "bare-dns",
  "version": "1.0.5",
  "description": "Domain name resolution for JavaScript",
  "exports": {
    ".": "./index.js",
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "standard && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-dns.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-dns/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-dns",
  "devDependencies": {
    "brittle": "^3.3.2",
    "cmake-bare": "^1.1.6",
    "standard": "^17.1.0"
  }
}
module.exports = require.addon()
/* global Bare */
const EventEmitter = require('bare-events')
const { Duplex } = require('bare-stream')
const binding = require('./binding')
const constants = require('./lib/constants')
const errors = require('./lib/errors')

const defaultReadBufferSize = 65536

const Pipe = module.exports = exports = class Pipe extends Duplex {
  constructor (path, opts = {}) {
    super({ eagerOpen: true })

    if (typeof path === 'object' && path !== null) {
      opts = path
      path = null
    }

    const {
      readBufferSize = defaultReadBufferSize,
      allowHalfOpen = true
    } = opts

    this._state = 0

    this._allowHalfOpen = allowHalfOpen

    this._fd = -1
    this._path = null

    this._pendingOpen = null
    this._pendingWrite = null
    this._pendingFinal = null
    this._pendingDestroy = null

    this._buffer = Buffer.alloc(readBufferSize)

    this._handle = binding.init(this._buffer, this,
      noop,
      this._onconnect,
      this._onwrite,
      this._onfinal,
      this._onread,
      this._onclose
    )

    if (typeof path === 'number') {
      this.open(path)
    } else if (typeof path === 'string') {
      this.connect(path)
    }

    Pipe._pipes.add(this)
  }

  get connecting () {
    return (this._state & constants.state.CONNECTING) !== 0
  }

  get pending () {
    return (this._state & constants.state.CONNECTED) === 0
  }

  get readyState () {
    if (this._state & constants.state.READABLE && this._state & constants.state.WRITABLE) {
      return 'open'
    }

    if (this._state & constants.state.READABLE) {
      return 'readOnly'
    }

    if (this._state & constants.state.WRITABLE) {
      return 'writeOnly'
    }

    return 'opening'
  }

  open (fd, opts = {}, onconnect) {
    if (typeof opts === 'function') {
      onconnect = opts
      opts = {}
    }

    if (typeof fd === 'object' && fd !== null) {
      opts = fd || {}
      fd = opts.fd
    }

    try {
      const status = binding.open(this._handle, fd)

      this._state |= constants.state.CONNECTED
      this._fd = fd

      if (status & binding.READABLE) {
        this._state |= constants.state.READABLE
      } else {
        this.push(null)
      }

      if (status & binding.WRITABLE) {
        this._state |= constants.state.WRITABLE
      } else {
        this.end()
      }

      if (onconnect) this.once('connect', onconnect)

      queueMicrotask(() => this.emit('connect'))
    } catch (err) {
      queueMicrotask(() => {
        if (this._pendingOpen) this._pendingOpen(err)
        else this.destroy(err)
      })
    }

    return this
  }

  connect (path, opts = {}, onconnect) {
    if (this._state & constants.state.CONNECTING || this._state & constants.state.CONNECTED) {
      throw errors.PIPE_ALREADY_CONNECTED('Pipe is already connected')
    }

    this._state |= constants.state.CONNECTING

    if (typeof opts === 'function') {
      onconnect = opts
      opts = {}
    }

    if (typeof path === 'object' && path !== null) {
      opts = path || {}
      path = opts.path
    }

    try {
      binding.connect(this._handle, path)

      this._path = path

      if (onconnect) this.once('connect', onconnect)
    } catch (err) {
      queueMicrotask(() => {
        if (this._pendingOpen) this._pendingOpen(err)
        else this.destroy(err)
      })
    }

    return this
  }

  ref () {
    binding.ref(this._handle)
  }

  unref () {
    binding.unref(this._handle)
  }

  _open (cb) {
    if (this._state & constants.state.CONNECTED) return cb(null)
    this._pendingOpen = cb
  }

  _read () {
    if ((this._state & constants.state.READING) === 0) {
      this._state |= constants.state.READING
      binding.resume(this._handle)
    }
  }

  _writev (batch, cb) {
    this._pendingWrite = [cb, batch]
    binding.writev(this._handle, batch.map(({ chunk }) => chunk))
  }

  _final (cb) {
    if (this._state & constants.state.READABLE && this._state & constants.state.WRITABLE) {
      this._pendingFinal = cb
      binding.end(this._handle)
    } else {
      cb(null)
    }
  }

  _predestroy () {
    if (this._state & constants.state.CLOSING) return
    this._state |= constants.state.CLOSING
    binding.close(this._handle)
    Pipe._pipes.delete(this)
  }

  _destroy (err, cb) {
    if (this._state & constants.state.CLOSING) return cb(err)
    this._state |= constants.state.CLOSING
    this._pendingDestroy = cb
    binding.close(this._handle)
    Pipe._pipes.delete(this)
  }

  _continueOpen (err) {
    if (this._pendingOpen === null) return
    const cb = this._pendingOpen
    this._pendingOpen = null
    cb(err)
  }

  _continueWrite (err) {
    if (this._pendingWrite === null) return
    const cb = this._pendingWrite[0]
    this._pendingWrite = null
    cb(err)
  }

  _continueFinal (err) {
    if (this._pendingFinal === null) return
    const cb = this._pendingFinal
    this._pendingFinal = null
    cb(err)
  }

  _continueDestroy () {
    if (this._pendingDestroy === null) return
    const cb = this._pendingDestroy
    this._pendingDestroy = null
    cb(null)
  }

  _onconnect (err) {
    if (err) {
      if (this._pendingOpen) this._continueOpen(err)
      else this.destroy(err)
      return
    }

    this._state |= constants.state.CONNECTED | constants.state.READABLE | constants.state.WRITABLE
    this._state &= ~constants.state.CONNECTING
    this._continueOpen()

    this.emit('connect')
  }

  _onread (err, read) {
    if (err) {
      this.destroy(err)
      return
    }

    if (read === 0) {
      this.push(null)
      if (this._allowHalfOpen === false) this.end()
      return
    }

    const copy = Buffer.allocUnsafe(read)
    copy.set(this._buffer.subarray(0, read))

    if (this.push(copy) === false && this.destroying === false) {
      this._state &= ~constants.state.READING
      binding.pause(this._handle)
    }
  }

  _onwrite (err) {
    this._continueWrite(err)
  }

  _onfinal (err) {
    this._continueFinal(err)
  }

  _onclose () {
    this._handle = null
    this._continueDestroy()
  }

  _onspawn (readable, writable) {
    this._state |= constants.state.CONNECTED

    if (readable) {
      this._state |= constants.state.READABLE
    } else {
      this.push(null)
    }

    if (writable) {
      this._state |= constants.state.WRITABLE
    } else {
      this.end()
    }

    this._continueOpen()
  }

  static _pipes = new Set()
}

exports.Pipe = exports

exports.pipe = function pipe () {
  return binding.pipe()
}

const Server = exports.Server = class PipeServer extends EventEmitter {
  constructor (opts = {}, onconnection) {
    if (typeof opts === 'function') {
      onconnection = opts
      opts = {}
    }

    super()

    const {
      readBufferSize = defaultReadBufferSize,
      allowHalfOpen = true
    } = opts

    this._state = 0

    this._readBufferSize = readBufferSize
    this._allowHalfOpen = allowHalfOpen

    this._path = null
    this._connections = new Set()

    this._error = null
    this._handle = null

    if (onconnection) this.on('connection', onconnection)

    PipeServer._servers.add(this)
  }

  get listening () {
    return (this._state & constants.state.BOUND) !== 0
  }

  address () {
    if ((this._state & constants.state.BOUND) === 0) {
      return null
    }

    return this._path
  }

  listen (path, backlog = 511, opts = {}, onlistening) {
    if (this._state & constants.state.BINDING || this._state & constants.state.BOUND) {
      throw errors.SERVER_ALREADY_LISTENING('Server is already listening')
    }

    if (this._state & constants.state.CLOSING) {
      throw errors.SERVER_IS_CLOSED('Server is closed')
    }

    this._state |= constants.state.BINDING

    if (typeof backlog === 'function') {
      onlistening = backlog
      backlog = 511
    } else if (typeof opts === 'function') {
      onlistening = opts
      opts = {}
    }

    if (typeof path === 'object' && path !== null) {
      opts = path || {}
      path = opts.path
      backlog = opts.backlog || 511
    }

    this._handle = binding.init(empty, this,
      this._onconnection,
      noop,
      noop,
      noop,
      noop,
      this._onclose
    )

    if (this._state & constants.state.UNREFED) binding.unref(this._handle)

    try {
      binding.bind(this._handle, path, backlog)

      this._path = path
      this._state |= constants.state.BOUND
      this._state &= ~constants.state.BINDING

      if (onlistening) this.once('listening', onlistening)

      queueMicrotask(() => this.emit('listening'))
    } catch (err) {
      this._error = err

      binding.close(this._handle)
    }

    return this
  }

  close (onclose) {
    if (onclose) this.once('close', onclose)
    if (this._state & constants.state.CLOSING) return
    this._state |= constants.state.CLOSING
    this._closeMaybe()
  }

  ref () {
    this._state &= ~constants.state.UNREFED
    if (this._handle !== null) binding.ref(this._handle)
  }

  unref () {
    this._state |= constants.state.UNREFED
    if (this._handle !== null) binding.unref(this._handle)
  }

  _closeMaybe () {
    if ((this._state & constants.state.CLOSING) && this._connections.size === 0) {
      if (this._handle !== null) binding.close(this._handle)
      else queueMicrotask(() => this.emit('close'))
      PipeServer._servers.delete(this)
    }
  }

  _onconnection (err) {
    if (err) {
      this.emit('error', err)
      return
    }

    if (this._state & constants.state.CLOSING) return

    const pipe = new Pipe({
      readBufferSize: this._readBufferSize,
      allowHalfOpen: this._allowHalfOpen
    })

    try {
      binding.accept(this._handle, pipe._handle)

      pipe._path = this._path
      pipe._state |= constants.state.CONNECTED | constants.state.READABLE | constants.state.WRITABLE

      this._connections.add(pipe)

      pipe.on('close', () => {
        this._connections.delete(pipe)
        this._closeMaybe()
      })

      this.emit('connection', pipe)
    } catch (err) {
      pipe.destroy()

      throw err
    }
  }

  _onclose () {
    const err = this._error

    this._state &= ~constants.state.BINDING
    this._error = null
    this._handle = null

    if (err) this.emit('error', err)
    else this.emit('close')
  }

  static _servers = new Set()
}

exports.constants = constants
exports.errors = errors

exports.createConnection = function createConnection (path, opts, onconnect) {
  if (typeof opts === 'function') {
    onconnect = opts
    opts = {}
  }

  if (typeof path === 'object' && path !== null) {
    opts = path || {}
    path = opts.path
  }

  return new Pipe(opts).connect(path, opts, onconnect)
}

exports.createServer = function createServer (opts, onconnection) {
  return new Server(opts, onconnection)
}

Bare
  .on('exit', () => {
    for (const pipe of Pipe._pipes) {
      pipe.destroy()
    }

    for (const server of Server._servers) {
      server.close()
    }
  })

const empty = Buffer.alloc(0)

function noop () {}
module.exports = {
  state: {
    CONNECTING: 0x1,
    CONNECTED: 0x2,
    BINDING: 0x4,
    BOUND: 0x8,
    READING: 0x10,
    CLOSING: 0x20,
    READABLE: 0x40,
    WRITABLE: 0x80
  }
}
module.exports = class PipeError extends Error {
  constructor (msg, code, fn = PipeError) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name () {
    return 'PipeError'
  }

  static PIPE_ALREADY_CONNECTED (msg) {
    return new PipeError(msg, 'PIPE_ALREADY_CONNECTED', PipeError.PIPE_ALREADY_CONNECTED)
  }

  static SERVER_ALREADY_LISTENING (msg) {
    return new PipeError(msg, 'SERVER_ALREADY_LISTENING', PipeError.SERVER_ALREADY_LISTENING)
  }

  static SERVER_IS_CLOSED (msg) {
    return new PipeError(msg, 'SERVER_IS_CLOSED', PipeError.SERVER_IS_CLOSED)
  }
}
{
  "name": "bare-pipe",
  "version": "3.3.8",
  "description": "Native I/O pipes for JavaScript",
  "exports": {
    ".": "./index.js",
    "./package": "./package.json",
    "./constants": "./lib/constants.js",
    "./errors": "./lib/errors.js"
  },
  "files": [
    "index.js",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "standard && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-pipe.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-pipe/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-pipe#readme",
  "dependencies": {
    "bare-events": "^2.0.0",
    "bare-stream": "^2.0.0"
  },
  "devDependencies": {
    "bare-path": "^3.0.0",
    "brittle": "^3.2.1",
    "cmake-bare": "^1.1.6",
    "standard": "^17.0.0"
  }
}
module.exports = require.addon()
/* global Bare */
const EventEmitter = require('bare-events')
const { Duplex } = require('bare-stream')
const dns = require('bare-dns')
const binding = require('./binding')
const constants = require('./lib/constants')
const errors = require('./lib/errors')
const ip = require('./lib/ip')

const defaultReadBufferSize = 65536

const Socket = exports.Socket = class TCPSocket extends Duplex {
  constructor (opts = {}) {
    super({ eagerOpen: true })

    const {
      readBufferSize = defaultReadBufferSize,
      allowHalfOpen = true
    } = opts

    this._state = 0

    this._allowHalfOpen = allowHalfOpen

    this._remotePort = -1
    this._remoteHost = null
    this._remoteFamily = 0

    this._pendingOpen = null
    this._pendingWrite = null
    this._pendingFinal = null
    this._pendingDestroy = null

    this._timer = null
    this._timeout = 0

    this._buffer = Buffer.alloc(readBufferSize)

    this._handle = binding.init(this._buffer, this,
      noop,
      this._onconnect,
      this._onread,
      this._onwrite,
      this._onfinal,
      this._onclose
    )

    TCPSocket._sockets.add(this)
  }

  get connecting () {
    return (this._state & constants.state.CONNECTING) !== 0
  }

  get pending () {
    return (this._state & constants.state.CONNECTED) === 0
  }

  get timeout () {
    return this._timeout || undefined // For Node.js compatibility
  }

  connect (port, host = 'localhost', opts = {}, onconnect) {
    if (this._state & constants.state.CONNECTING || this._state & constants.state.CONNECTED) {
      throw errors.SOCKET_ALREADY_CONNECTED('Socket is already connected')
    }

    this._state |= constants.state.CONNECTING

    if (typeof host === 'function') {
      onconnect = host
      host = 'localhost'
    } else if (typeof opts === 'function') {
      onconnect = opts
      opts = {}
    }

    let family = 0

    if (typeof port === 'object' && port !== null) {
      opts = port || {}
      port = opts.port || 0
      host = opts.host || 'localhost'
      family = opts.family || 0
    }

    if (!host) host = 'localhost'

    const type = ip.isIP(host)

    if (type === 0) {
      const {
        lookup = dns.lookup,
        hints
      } = opts

      lookup(host, { family, hints }, (err, address, family) => {
        this.emit('lookup', err, address, family, host)

        this._state &= ~constants.state.CONNECTING

        if (err) {
          if (this._pendingOpen) this._continueOpen(err)
          else this.destroy(err)
          return
        }

        if (this._handle !== null) {
          this.connect(port, address, { ...opts, family }, onconnect)
        }
      })

      return this
    }

    family = type

    try {
      binding.connect(this._handle, port, host, family)

      if (opts.keepAlive === true) this.setKeepAlive(opts.keepAlive, opts.keepAliveInitialDelay)
      if (opts.noDelay === true) this.setNoDelay()
      if (opts.timeout) this.setTimeout(opts.timeout)

      this._remotePort = port
      this._remoteHost = host
      this._remoteFamily = family

      if (onconnect) this.once('connect', onconnect)
    } catch (err) {
      queueMicrotask(() => {
        if (this._pendingOpen) this._pendingOpen(err)
        else this.destroy(err)
      })
    }

    return this
  }

  setKeepAlive (enable = false, delay = 0) {
    if (typeof enable === 'number') {
      delay = enable
      enable = false
    }

    delay = Math.floor(delay / 1000)

    if (delay === 0) enable = false

    binding.keepalive(this._handle, enable, delay)

    return this
  }

  setNoDelay (enable = true) {
    binding.nodelay(this._handle, enable)

    return this
  }

  setTimeout (ms, ontimeout) {
    if (ms === 0) {
      clearTimeout(this._timer)
      this._timer = null
    } else {
      if (ontimeout) this.once('timeout', ontimeout)

      this._timer = setTimeout(() => this.emit('timeout'), ms)
      this._timer.unref()
    }

    this._timeout = ms

    return this
  }

  ref () {
    binding.ref(this._handle)
  }

  unref () {
    binding.unref(this._handle)
  }

  _open (cb) {
    if (this._state & constants.state.CONNECTED) return cb(null)
    this._pendingOpen = cb
  }

  _read () {
    if ((this._state & constants.state.READING) === 0) {
      this._state |= constants.state.READING
      binding.resume(this._handle)
    }
  }

  _writev (batch, cb) {
    this._pendingWrite = [cb, batch]
    binding.writev(this._handle, batch.map(({ chunk }) => chunk))
  }

  _final (cb) {
    this._pendingFinal = cb
    binding.end(this._handle)
  }

  _predestroy () {
    if (this._state & constants.state.CLOSING) return
    this._state |= constants.state.CLOSING
    binding.close(this._handle)
    TCPSocket._sockets.delete(this)
  }

  _destroy (err, cb) {
    if (this._state & constants.state.CLOSING) return cb(err)
    this._state |= constants.state.CLOSING
    this._pendingDestroy = cb
    binding.close(this._handle)
    TCPSocket._sockets.delete(this)
  }

  _continueOpen (err) {
    if (this._pendingOpen === null) return
    const cb = this._pendingOpen
    this._pendingOpen = null
    cb(err)
  }

  _continueWrite (err) {
    if (this._pendingWrite === null) return
    const cb = this._pendingWrite[0]
    this._pendingWrite = null
    cb(err)
  }

  _continueFinal (err) {
    if (this._pendingFinal === null) return
    const cb = this._pendingFinal
    this._pendingFinal = null
    cb(err)
  }

  _continueDestroy () {
    if (this._pendingDestroy === null) return
    const cb = this._pendingDestroy
    this._pendingDestroy = null
    cb(null)
  }

  _onconnect (err) {
    if (err) {
      if (this._pendingOpen) this._continueOpen(err)
      else this.destroy(err)
      return
    }

    this._state |= constants.state.CONNECTED
    this._state &= ~constants.state.CONNECTING
    this._continueOpen()

    this.emit('connect')
  }

  _onread (err, read) {
    if (this._timer) this._timer.refresh()

    if (err) {
      this.destroy(err)
      return
    }

    if (read === 0) {
      this.push(null)
      if (this._allowHalfOpen === false) this.end()
      return
    }

    const copy = Buffer.allocUnsafe(read)
    copy.set(this._buffer.subarray(0, read))

    if (this.push(copy) === false && this.destroying === false) {
      this._state &= ~constants.state.READING
      binding.pause(this._handle)
    }
  }

  _onwrite (err) {
    if (this._timer) this._timer.refresh()

    this._continueWrite(err)
  }

  _onfinal (err) {
    this._continueFinal(err)
  }

  _onclose () {
    clearTimeout(this._timer)

    this._handle = null
    this._continueDestroy()
  }

  static _sockets = new Set()
}

const Server = exports.Server = class TCPServer extends EventEmitter {
  constructor (opts = {}, onconnection) {
    if (typeof opts === 'function') {
      onconnection = opts
      opts = {}
    }

    super()

    const {
      readBufferSize = defaultReadBufferSize,
      allowHalfOpen = true
    } = opts

    this._state = 0

    this._readBufferSize = readBufferSize
    this._allowHalfOpen = allowHalfOpen

    this._keepAlive = opts.keepAlive
    this._keepAliveDelay = opts.keepAliveInitialDelay
    this._noDelay = opts.noDelay

    this._port = -1
    this._host = null
    this._family = 0
    this._connections = new Set()

    this._error = null
    this._handle = null

    if (onconnection) this.on('connection', onconnection)

    TCPServer._servers.add(this)
  }

  get listening () {
    return (this._state & constants.state.BOUND) !== 0
  }

  address () {
    if ((this._state & constants.state.BOUND) === 0) {
      return null
    }

    return {
      address: this._host,
      family: `IPv${this._family}`,
      port: this._port
    }
  }

  listen (port = 0, host = 'localhost', backlog = 511, opts = {}, onlistening) {
    if (this._state & constants.state.BINDING || this._state & constants.state.BOUND) {
      throw errors.SERVER_ALREADY_LISTENING('Server is already listening')
    }

    if (this._state & constants.state.CLOSING) {
      throw errors.SERVER_IS_CLOSED('Server is closed')
    }

    this._state |= constants.state.BINDING

    if (typeof port === 'function') {
      onlistening = port
      port = 0
    } else if (typeof host === 'function') {
      onlistening = host
      host = 'localhost'
    } else if (typeof backlog === 'function') {
      onlistening = backlog
      backlog = 511
    } else if (typeof opts === 'function') {
      onlistening = opts
      opts = {}
    }

    let family = 0

    if (typeof port === 'object' && port !== null) {
      opts = port || {}
      port = opts.port || 0
      host = opts.host || 'localhost'
      family = opts.family || 0
      backlog = opts.backlog || 511
    }

    if (!host) host = 'localhost'
    if (!backlog) backlog = 511

    const type = ip.isIP(host)

    if (type === 0) {
      const {
        lookup = dns.lookup,
        hints
      } = opts

      lookup(host, { family, hints }, (err, address, family) => {
        if (this._state & constants.state.CLOSING) return

        this.emit('lookup', err, address, family, host)

        this._state &= ~constants.state.BINDING

        if (err) return this.emit('error', err)

        this.listen(port, address, backlog, { ...opts, family }, onlistening)
      })

      return this
    }

    family = type

    this._handle = binding.init(empty, this,
      this._onconnection,
      noop,
      noop,
      noop,
      noop,
      this._onclose
    )

    if (this._state & constants.state.UNREFED) binding.unref(this._handle)

    try {
      this._port = binding.bind(this._handle, port, host, backlog, family)
      this._host = host
      this._family = family
      this._state |= constants.state.BOUND
      this._state &= ~constants.state.BINDING

      if (onlistening) this.once('listening', onlistening)

      queueMicrotask(() => this.emit('listening'))
    } catch (err) {
      this._error = err

      binding.close(this._handle)
    }

    return this
  }

  close (onclose) {
    if (onclose) this.once('close', onclose)
    if (this._state & constants.state.CLOSING) return
    this._state |= constants.state.CLOSING
    this._closeMaybe()
  }

  ref () {
    this._state &= ~constants.state.UNREFED
    if (this._handle !== null) binding.ref(this._handle)
  }

  unref () {
    this._state |= constants.state.UNREFED
    if (this._handle !== null) binding.unref(this._handle)
  }

  _closeMaybe () {
    if ((this._state & constants.state.CLOSING) && this._connections.size === 0) {
      if (this._handle !== null) binding.close(this._handle)
      else queueMicrotask(() => this.emit('close'))
      TCPServer._servers.delete(this)
    }
  }

  _onconnection (err) {
    if (err) {
      this.emit('error', err)
      return
    }

    if (this._state & constants.state.CLOSING) return

    const socket = new Socket({
      readBufferSize: this._readBufferSize,
      allowHalfOpen: this._allowHalfOpen
    })

    try {
      binding.accept(this._handle, socket._handle)

      socket._state |= constants.state.CONNECTED

      this._connections.add(socket)

      if (this._keepAlive === true) socket.setKeepAlive(this._keepAlive, this._keepAliveDelay)
      if (this._noDelay === true) socket.setNoDelay()

      socket.on('close', () => {
        this._connections.delete(socket)
        this._closeMaybe()
      })

      this.emit('connection', socket)
    } catch (err) {
      socket.destroy()

      throw err
    }
  }

  _onclose () {
    const err = this._error

    this._state &= ~constants.state.BINDING
    this._error = null
    this._handle = null

    if (err) this.emit('error', err)
    else this.emit('close')
  }

  static _servers = new Set()
}

exports.constants = constants
exports.errors = errors

exports.isIP = ip.isIP
exports.isIPv4 = ip.isIPv4
exports.isIPv6 = ip.isIPv6

exports.createConnection = function createConnection (port, host, opts, onconnect) {
  if (typeof host === 'function') {
    onconnect = host
    host = 'localhost'
  } else if (typeof opts === 'function') {
    onconnect = opts
    opts = {}
  }

  if (typeof port === 'object' && port !== null) {
    opts = port || {}
    port = opts.port || 0
    host = opts.host || 'localhost'
  }

  return new Socket(opts).connect(port, host, opts, onconnect)
}

// For Node.js compatibility
exports.connect = exports.createConnection

exports.createServer = function createServer (opts, onconnection) {
  return new Server(opts, onconnection)
}

Bare
  .on('exit', () => {
    for (const socket of Socket._sockets) {
      socket.destroy()
    }

    for (const server of Server._servers) {
      server.close()
    }
  })

const empty = Buffer.alloc(0)

function noop () {}
module.exports = {
  state: {
    CONNECTING: 0x1,
    CONNECTED: 0x2,
    BINDING: 0x4,
    BOUND: 0x8,
    READING: 0x10,
    CLOSING: 0x20,
    UNREFED: 0x40
  }
}
module.exports = class TCPError extends Error {
  constructor (msg, code, fn = TCPError) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name () {
    return 'TCPError'
  }

  static SOCKET_ALREADY_CONNECTED (msg) {
    return new TCPError(msg, 'SOCKET_ALREADY_CONNECTED', TCPError.SOCKET_ALREADY_CONNECTED)
  }

  static SERVER_ALREADY_LISTENING (msg) {
    return new TCPError(msg, 'SERVER_ALREADY_LISTENING', TCPError.SERVER_ALREADY_LISTENING)
  }

  static SERVER_IS_CLOSED (msg) {
    return new TCPError(msg, 'SERVER_IS_CLOSED', TCPError.SERVER_IS_CLOSED)
  }

  static INVALID_HOST (msg = 'Unrecognizable host format') {
    return new TCPError(msg, 'INVALID_HOST', TCPError.INVALID_HOST)
  }
}
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

const v4Seg = '(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])'
const v4Str = `(${v4Seg}[.]){3}${v4Seg}`
const IPv4Pattern = new RegExp(`^${v4Str}$`)

const v6Seg = '(?:[0-9a-fA-F]{1,4})'
const IPv6Pattern = new RegExp('^(' +
  `(?:${v6Seg}:){7}(?:${v6Seg}|:)|` +
  `(?:${v6Seg}:){6}(?:${v4Str}|:${v6Seg}|:)|` +
  `(?:${v6Seg}:){5}(?::${v4Str}|(:${v6Seg}){1,2}|:)|` +
  `(?:${v6Seg}:){4}(?:(:${v6Seg}){0,1}:${v4Str}|(:${v6Seg}){1,3}|:)|` +
  `(?:${v6Seg}:){3}(?:(:${v6Seg}){0,2}:${v4Str}|(:${v6Seg}){1,4}|:)|` +
  `(?:${v6Seg}:){2}(?:(:${v6Seg}){0,3}:${v4Str}|(:${v6Seg}){1,5}|:)|` +
  `(?:${v6Seg}:){1}(?:(:${v6Seg}){0,4}:${v4Str}|(:${v6Seg}){1,6}|:)|` +
  `(?::((?::${v6Seg}){0,5}:${v4Str}|(?::${v6Seg}){1,7}|:))` +
')(%[0-9a-zA-Z-.:]{1,})?$')

const isIPv4 = exports.isIPv4 = function isIPv4 (host) {
  return IPv4Pattern.test(host)
}

const isIPv6 = exports.isIPv6 = function isIPv6 (host) {
  return IPv6Pattern.test(host)
}

exports.isIP = function isIP (host) {
  if (isIPv4(host)) return 4
  if (isIPv6(host)) return 6
  return 0
}
{
  "name": "bare-tcp",
  "version": "1.9.1",
  "description": "Native TCP sockets for JavaScript",
  "exports": {
    ".": "./index.js",
    "./package": "./package.json",
    "./constants": "./lib/constants.js",
    "./errors": "./lib/errors.js"
  },
  "files": [
    "index.js",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "standard && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-tcp.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-tcp/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-tcp#readme",
  "dependencies": {
    "bare-dns": "^1.0.0",
    "bare-events": "^2.2.2",
    "bare-stream": "^2.0.0"
  },
  "devDependencies": {
    "brittle": "^3.5.0",
    "cmake-bare": "^1.1.6",
    "standard": "^17.1.0"
  }
}
{
  "name": "bare-net",
  "version": "1.0.1",
  "description": "TCP and IPC servers and clients for JavaScript",
  "exports": {
    ".": "./index.js",
    "./package": "./package.json"
  },
  "files": [
    "index.js"
  ],
  "scripts": {
    "test": "standard && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-net.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-net/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-net#readme",
  "dependencies": {
    "bare-events": "^2.2.2",
    "bare-pipe": "^3.2.0",
    "bare-stream": "^2.0.0",
    "bare-tcp": "^1.4.0"
  },
  "devDependencies": {
    "brittle": "^3.3.0",
    "standard": "^17.0.0"
  }
}
module.exports = require.addon()
const binding = require('./binding')
const errors = require('./lib/errors')
const constants = require('./lib/constants')

exports.constants = constants
exports.errors = errors

exports.EOL = binding.platform === 'win32' ? '\r\n' : '\n'

exports.devNull = binding.platform === 'win32' ? '\\\\.\\nul' : '/dev/null'

exports.platform = function platform() {
  return binding.platform
}

exports.arch = function arch() {
  return binding.arch
}

exports.type = binding.type
exports.version = binding.version
exports.release = binding.release
exports.machine = binding.machine
exports.execPath = binding.execPath
exports.pid = binding.pid
exports.ppid = binding.ppid
exports.cwd = binding.cwd
exports.chdir = binding.chdir
exports.tmpdir = binding.tmpdir
exports.homedir = binding.homedir
exports.hostname = binding.hostname
exports.userInfo = binding.userInfo
exports.groupInfo = binding.groupInfo

exports.networkInterfaces = function networkInterfaces() {
  const result = {}

  for (const entry of binding.networkInterfaces()) {
    const { name, ...properties } = entry

    if (result[name]) result[name].push(properties)
    else result[name] = [properties]
  }

  return result
}

exports.kill = function kill(pid, signal = constants.signals.SIGTERM) {
  if (typeof signal === 'string') {
    if (signal in constants.signals === false) {
      throw errors.UNKNOWN_SIGNAL('Unknown signal: ' + signal)
    }

    signal = constants.signals[signal]
  }

  binding.kill(pid, signal)
}

exports.endianness = function endianness() {
  return binding.isLittleEndian ? 'LE' : 'BE'
}

exports.availableParallelism = binding.availableParallelism

exports.cpuUsage = function cpuUsage(previous) {
  const current = binding.cpuUsage()

  if (previous) {
    return {
      user: current.user - previous.user,
      system: current.system - previous.system
    }
  }

  return current
}

exports.threadCpuUsage = function threadCpuUsage(previous) {
  const current = binding.threadCpuUsage()

  if (previous) {
    return {
      user: current.user - previous.user,
      system: current.system - previous.system
    }
  }

  return current
}

exports.resourceUsage = binding.resourceUsage
exports.memoryUsage = binding.memoryUsage
exports.freemem = binding.freemem
exports.totalmem = binding.totalmem
exports.availableMemory = binding.availableMemory
exports.constrainedMemory = binding.constrainedMemory
exports.uptime = binding.uptime
exports.loadavg = binding.loadavg
exports.cpus = binding.cpus

exports.getProcessTitle = binding.getProcessTitle

exports.setProcessTitle = function setProcessTitle(title) {
  if (typeof title !== 'string') title = title.toString()

  if (title.length >= 256) {
    throw errors.TITLE_OVERFLOW('Process title is too long')
  }

  binding.setProcessTitle(title)
}

exports.getPriority = function getPriority(pid = 0) {
  return binding.getPriority(pid)
}

exports.setPriority = function setPriority(pid, priority) {
  if (priority === undefined) {
    priority = pid
    pid = 0
  }

  binding.setPriority(pid, priority)
}

exports.getEnvKeys = binding.getEnvKeys
exports.getEnv = binding.getEnv
exports.hasEnv = binding.hasEnv
exports.setEnv = binding.setEnv
exports.unsetEnv = binding.unsetEnv
const binding = require('../binding')

module.exports = {
  signals: binding.signals,
  errnos: binding.errnos,
  priority: binding.priority
}
module.exports = class OSError extends Error {
  constructor(msg, fn = OSError, code = fn.name) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'OSError'
  }

  static UNKNOWN_SIGNAL(msg) {
    return new OSError(msg, OSError.UNKNOWN_SIGNAL)
  }

  static TITLE_OVERFLOW(msg) {
    return new OSError(msg, OSError.TITLE_OVERFLOW)
  }
}
{
  "name": "bare-os",
  "version": "3.9.1",
  "description": "Operating system utilities for Bare",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    },
    "./errors": {
      "types": "./lib/errors.d.ts",
      "default": "./lib/errors.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-os.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-os/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-os#readme",
  "engines": {
    "bare": ">=1.14.0"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "cmake-bare": "^1.1.6",
    "lunte": "^1.6.0",
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
/* global Bare */

// This export SHOULD NOT be shortened in any way as having the full
// `module.exports = require(...)` statement is crucial for synthesizing
// ESM exports.

if (Bare.platform === 'win32') {
  module.exports = require('./lib/win32')
} else {
  module.exports = require('./lib/posix')
}
module.exports = {
  CHAR_UPPERCASE_A: 0x41,
  CHAR_LOWERCASE_A: 0x61,
  CHAR_UPPERCASE_Z: 0x5a,
  CHAR_LOWERCASE_Z: 0x7a,
  CHAR_DOT: 0x2e,
  CHAR_FORWARD_SLASH: 0x2f,
  CHAR_BACKWARD_SLASH: 0x5c,
  CHAR_COLON: 0x3a,
  CHAR_QUESTION_MARK: 0x3f
}
const os = require('bare-os')

const { normalizeString } = require('./shared')
const {
  CHAR_DOT,
  CHAR_FORWARD_SLASH
} = require('./constants')

function isPosixPathSeparator (code) {
  return code === CHAR_FORWARD_SLASH
}

exports.win32 = require('./win32')
exports.posix = exports

exports.sep = '/'
exports.delimiter = ':'

exports.resolve = function resolve (...args) {
  let resolvedPath = ''
  let resolvedAbsolute = false

  for (let i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) {
    const path = i >= 0 ? args[i] : os.cwd()

    if (path.length === 0) {
      continue
    }

    resolvedPath = `${path}/${resolvedPath}`
    resolvedAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH
  }

  resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute, '/', isPosixPathSeparator)

  if (resolvedAbsolute) {
    return `/${resolvedPath}`
  }

  return resolvedPath.length > 0 ? resolvedPath : '.'
}

exports.normalize = function normalize (path) {
  if (path.length === 0) return '.'

  const isAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH
  const trailingSeparator = path.charCodeAt(path.length - 1) === CHAR_FORWARD_SLASH

  path = normalizeString(path, !isAbsolute, '/', isPosixPathSeparator)

  if (path.length === 0) {
    if (isAbsolute) return '/'
    return trailingSeparator ? './' : '.'
  }

  if (trailingSeparator) path += '/'

  return isAbsolute ? `/${path}` : path
}

exports.isAbsolute = function isAbsolute (path) {
  return path.length > 0 && path.charCodeAt(0) === CHAR_FORWARD_SLASH
}

exports.join = function join (...args) {
  if (args.length === 0) return '.'
  let joined
  for (let i = 0; i < args.length; ++i) {
    const arg = args[i]
    if (arg.length > 0) {
      if (joined === undefined) joined = arg
      else joined += `/${arg}`
    }
  }
  if (joined === undefined) return '.'
  return exports.normalize(joined)
}

exports.relative = function relative (from, to) {
  if (from === to) return ''

  from = exports.resolve(from)
  to = exports.resolve(to)

  if (from === to) return ''

  const fromStart = 1
  const fromEnd = from.length
  const fromLen = fromEnd - fromStart
  const toStart = 1
  const toLen = to.length - toStart

  const length = (fromLen < toLen ? fromLen : toLen)
  let lastCommonSep = -1
  let i = 0
  for (; i < length; i++) {
    const fromCode = from.charCodeAt(fromStart + i)
    if (fromCode !== to.charCodeAt(toStart + i)) {
      break
    } else if (fromCode === CHAR_FORWARD_SLASH) {
      lastCommonSep = i
    }
  }
  if (i === length) {
    if (toLen > length) {
      if (to.charCodeAt(toStart + i) === CHAR_FORWARD_SLASH) {
        return to.substring(toStart + i + 1)
      }
      if (i === 0) {
        return to.substring(toStart + i)
      }
    } else if (fromLen > length) {
      if (from.charCodeAt(fromStart + i) === CHAR_FORWARD_SLASH) {
        lastCommonSep = i
      } else if (i === 0) {
        lastCommonSep = 0
      }
    }
  }

  let out = ''
  for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
    if (i === fromEnd || from.charCodeAt(i) === CHAR_FORWARD_SLASH) {
      out += out.length === 0 ? '..' : '/..'
    }
  }

  return `${out}${to.substring(toStart + lastCommonSep)}`
}

exports.toNamespacedPath = function toNamespacedPath (path) {
  return path
}

exports.dirname = function dirname (path) {
  if (path.length === 0) return '.'
  const hasRoot = path.charCodeAt(0) === CHAR_FORWARD_SLASH
  let end = -1
  let matchedSlash = true
  for (let i = path.length - 1; i >= 1; --i) {
    if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) {
      if (!matchedSlash) {
        end = i
        break
      }
    } else {
      matchedSlash = false
    }
  }

  if (end === -1) return hasRoot ? '/' : '.'
  if (hasRoot && end === 1) return '//'
  return path.substring(0, end)
}

exports.basename = function basename (path, suffix) {
  let start = 0
  let end = -1
  let matchedSlash = true

  if (suffix !== undefined && suffix.length > 0 && suffix.length <= path.length) {
    if (suffix === path) { return '' }
    let extIdx = suffix.length - 1
    let firstNonSlashEnd = -1
    for (let i = path.length - 1; i >= 0; --i) {
      const code = path.charCodeAt(i)
      if (code === CHAR_FORWARD_SLASH) {
        if (!matchedSlash) {
          start = i + 1
          break
        }
      } else {
        if (firstNonSlashEnd === -1) {
          matchedSlash = false
          firstNonSlashEnd = i + 1
        }
        if (extIdx >= 0) {
          if (code === suffix.charCodeAt(extIdx)) {
            if (--extIdx === -1) {
              end = i
            }
          } else {
            extIdx = -1
            end = firstNonSlashEnd
          }
        }
      }
    }

    if (start === end) end = firstNonSlashEnd
    else if (end === -1) end = path.length
    return path.substring(start, end)
  }

  for (let i = path.length - 1; i >= 0; --i) {
    if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) {
      if (!matchedSlash) {
        start = i + 1
        break
      }
    } else if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
  }

  if (end === -1) return ''
  return path.substring(start, end)
}

exports.extname = function extname (path) {
  let startDot = -1
  let startPart = 0
  let end = -1
  let matchedSlash = true
  let preDotState = 0
  for (let i = path.length - 1; i >= 0; --i) {
    const code = path.charCodeAt(i)
    if (code === CHAR_FORWARD_SLASH) {
      if (!matchedSlash) {
        startPart = i + 1
        break
      }
      continue
    }
    if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
    if (code === CHAR_DOT) {
      if (startDot === -1) startDot = i
      else if (preDotState !== 1) preDotState = 1
    } else if (startDot !== -1) {
      preDotState = -1
    }
  }

  if (startDot === -1 || end === -1 || preDotState === 0 || (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1)) {
    return ''
  }
  return path.substring(startDot, end)
}
const {
  CHAR_DOT,
  CHAR_FORWARD_SLASH
} = require('./constants')

exports.normalizeString = function normalizeString (path, allowAboveRoot, separator, isPathSeparator) {
  let res = ''
  let lastSegmentLength = 0
  let lastSlash = -1
  let dots = 0
  let code = 0
  for (let i = 0; i <= path.length; ++i) {
    if (i < path.length) {
      code = path.charCodeAt(i)
    } else if (isPathSeparator(code)) {
      break
    } else {
      code = CHAR_FORWARD_SLASH
    }

    if (isPathSeparator(code)) {
      if (lastSlash === i - 1 || dots === 1) ;
      else if (dots === 2) {
        if (res.length < 2 || lastSegmentLength !== 2 || res.charCodeAt(res.length - 1) !== CHAR_DOT || res.charCodeAt(res.length - 2) !== CHAR_DOT) {
          if (res.length > 2) {
            const lastSlashIndex = res.lastIndexOf(separator)
            if (lastSlashIndex === -1) {
              res = ''
              lastSegmentLength = 0
            } else {
              res = res.substring(0, lastSlashIndex)
              lastSegmentLength =
                res.length - 1 - res.lastIndexOf(separator)
            }
            lastSlash = i
            dots = 0
            continue
          } else if (res.length !== 0) {
            res = ''
            lastSegmentLength = 0
            lastSlash = i
            dots = 0
            continue
          }
        }
        if (allowAboveRoot) {
          res += res.length > 0 ? `${separator}..` : '..'
          lastSegmentLength = 2
        }
      } else {
        if (res.length > 0) {
          res += `${separator}${path.substring(lastSlash + 1, i)}`
        } else {
          res = path.substring(lastSlash + 1, i)
        }
        lastSegmentLength = i - lastSlash - 1
      }
      lastSlash = i
      dots = 0
    } else if (code === CHAR_DOT && dots !== -1) {
      ++dots
    } else {
      dots = -1
    }
  }
  return res
}
const os = require('bare-os')

const { normalizeString } = require('./shared')
const {
  CHAR_UPPERCASE_A,
  CHAR_LOWERCASE_A,
  CHAR_UPPERCASE_Z,
  CHAR_LOWERCASE_Z,
  CHAR_DOT,
  CHAR_FORWARD_SLASH,
  CHAR_BACKWARD_SLASH,
  CHAR_COLON,
  CHAR_QUESTION_MARK
} = require('./constants')

function isWindowsPathSeparator (code) {
  return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH
}

function isWindowsDeviceRoot (code) {
  return (code >= CHAR_UPPERCASE_A && code <= CHAR_UPPERCASE_Z) ||
         (code >= CHAR_LOWERCASE_A && code <= CHAR_LOWERCASE_Z)
}

exports.posix = require('./posix')
exports.win32 = exports

exports.sep = '\\'
exports.delimiter = ';'

exports.resolve = function resolve (...args) {
  let resolvedDevice = ''
  let resolvedTail = ''
  let resolvedAbsolute = false

  for (let i = args.length - 1; i >= -1; i--) {
    let path
    if (i >= 0) {
      path = args[i]

      if (path.length === 0) continue
    } else if (resolvedDevice.length === 0) {
      path = os.cwd()
    } else {
      path = os.getEnv(`=${resolvedDevice}`) || os.cwd()

      if (path === undefined || (path.substring(0, 2).toLowerCase() !== resolvedDevice.toLowerCase() && path.charCodeAt(2) === CHAR_BACKWARD_SLASH)) {
        path = `${resolvedDevice}\\`
      }
    }

    const len = path.length
    let rootEnd = 0
    let device = ''
    let isAbsolute = false
    const code = path.charCodeAt(0)

    if (len === 1) {
      if (isWindowsPathSeparator(code)) {
        rootEnd = 1
        isAbsolute = true
      }
    } else if (isWindowsPathSeparator(code)) {
      isAbsolute = true

      if (isWindowsPathSeparator(path.charCodeAt(1))) {
        let j = 2
        let last = j
        while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
          j++
        }
        if (j < len && j !== last) {
          const firstPart = path.substring(last, j)
          last = j
          while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
            j++
          }
          if (j < len && j !== last) {
            last = j
            while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
              j++
            }
            if (j === len || j !== last) {
              device = `\\\\${firstPart}\\${path.substring(last, j)}`
              rootEnd = j
            }
          }
        }
      } else {
        rootEnd = 1
      }
    } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
      device = path.substring(0, 2)
      rootEnd = 2
      if (len > 2 && isWindowsPathSeparator(path.charCodeAt(2))) {
        isAbsolute = true
        rootEnd = 3
      }
    }

    if (device.length > 0) {
      if (resolvedDevice.length > 0) {
        if (device.toLowerCase() !== resolvedDevice.toLowerCase()) { continue }
      } else {
        resolvedDevice = device
      }
    }

    if (resolvedAbsolute) {
      if (resolvedDevice.length > 0) { break }
    } else {
      resolvedTail = `${path.substring(rootEnd)}\\${resolvedTail}`
      resolvedAbsolute = isAbsolute
      if (isAbsolute && resolvedDevice.length > 0) {
        break
      }
    }
  }

  resolvedTail = normalizeString(resolvedTail, !resolvedAbsolute, '\\', isWindowsPathSeparator)

  return resolvedAbsolute ? `${resolvedDevice}\\${resolvedTail}` : `${resolvedDevice}${resolvedTail}` || '.'
}

exports.normalize = function normalize (path) {
  const len = path.length
  if (len === 0) return '.'
  let rootEnd = 0
  let device
  let isAbsolute = false
  const code = path.charCodeAt(0)

  if (len === 1) {
    return code === CHAR_FORWARD_SLASH ? '\\' : path
  }

  if (isWindowsPathSeparator(code)) {
    isAbsolute = true

    if (isWindowsPathSeparator(path.charCodeAt(1))) {
      let j = 2
      let last = j
      while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
        j++
      }
      if (j < len && j !== last) {
        const firstPart = path.substring(last, j)
        last = j
        while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
          j++
        }
        if (j < len && j !== last) {
          last = j
          while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
            j++
          }
          if (j === len) {
            return `\\\\${firstPart}\\${path.substring(last)}\\`
          }
          if (j !== last) {
            device = `\\\\${firstPart}\\${path.substring(last, j)}`
            rootEnd = j
          }
        }
      }
    } else {
      rootEnd = 1
    }
  } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
    device = path.substring(0, 2)
    rootEnd = 2
    if (len > 2 && isWindowsPathSeparator(path.charCodeAt(2))) {
      isAbsolute = true
      rootEnd = 3
    }
  }

  let tail = rootEnd < len ? normalizeString(path.substring(rootEnd), !isAbsolute, '\\', isWindowsPathSeparator) : ''
  if (tail.length === 0 && !isAbsolute) {
    tail = '.'
  }
  if (tail.length > 0 && isWindowsPathSeparator(path.charCodeAt(len - 1))) {
    tail += '\\'
  }
  if (device === undefined) {
    return isAbsolute ? `\\${tail}` : tail
  }
  return isAbsolute ? `${device}\\${tail}` : `${device}${tail}`
}

exports.isAbsolute = function isAbsolute (path) {
  const len = path.length
  if (len === 0) return false

  const code = path.charCodeAt(0)

  return isWindowsPathSeparator(code) || (len > 2 && isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON && isWindowsPathSeparator(path.charCodeAt(2)))
}

exports.join = function join (...args) {
  if (args.length === 0) return '.'

  let joined
  let firstPart
  for (let i = 0; i < args.length; ++i) {
    const arg = args[i]
    if (arg.length > 0) {
      if (joined === undefined) joined = firstPart = arg
      else joined += `\\${arg}`
    }
  }

  if (joined === undefined) return '.'

  let needsReplace = true
  let slashCount = 0
  if (isWindowsPathSeparator(firstPart.charCodeAt(0))) {
    ++slashCount
    const firstLen = firstPart.length
    if (firstLen > 1 && isWindowsPathSeparator(firstPart.charCodeAt(1))) {
      ++slashCount
      if (firstLen > 2) {
        if (isWindowsPathSeparator(firstPart.charCodeAt(2))) {
          ++slashCount
        } else {
          needsReplace = false
        }
      }
    }
  }
  if (needsReplace) {
    while (slashCount < joined.length && isWindowsPathSeparator(joined.charCodeAt(slashCount))) {
      slashCount++
    }

    if (slashCount >= 2) {
      joined = `\\${joined.substring(slashCount)}`
    }
  }

  return exports.normalize(joined)
}

exports.relative = function relative (from, to) {
  if (from === to) return ''

  const fromOrig = exports.resolve(from)
  const toOrig = exports.resolve(to)

  if (fromOrig === toOrig) return ''

  from = fromOrig.toLowerCase()
  to = toOrig.toLowerCase()

  if (from === to) return ''

  let fromStart = 0
  while (fromStart < from.length && from.charCodeAt(fromStart) === CHAR_BACKWARD_SLASH) {
    fromStart++
  }
  let fromEnd = from.length
  while (fromEnd - 1 > fromStart && from.charCodeAt(fromEnd - 1) === CHAR_BACKWARD_SLASH) {
    fromEnd--
  }
  const fromLen = fromEnd - fromStart

  let toStart = 0
  while (toStart < to.length && to.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) {
    toStart++
  }
  let toEnd = to.length
  while (toEnd - 1 > toStart && to.charCodeAt(toEnd - 1) === CHAR_BACKWARD_SLASH) {
    toEnd--
  }
  const toLen = toEnd - toStart

  const length = fromLen < toLen ? fromLen : toLen
  let lastCommonSep = -1
  let i = 0
  for (; i < length; i++) {
    const fromCode = from.charCodeAt(fromStart + i)
    if (fromCode !== to.charCodeAt(toStart + i)) {
      break
    } else if (fromCode === CHAR_BACKWARD_SLASH) {
      lastCommonSep = i
    }
  }

  if (i !== length) {
    if (lastCommonSep === -1) return toOrig
  } else {
    if (toLen > length) {
      if (to.charCodeAt(toStart + i) === CHAR_BACKWARD_SLASH) {
        return toOrig.substring(toStart + i + 1)
      }
      if (i === 2) {
        return toOrig.substring(toStart + i)
      }
    }
    if (fromLen > length) {
      if (from.charCodeAt(fromStart + i) === CHAR_BACKWARD_SLASH) {
        lastCommonSep = i
      } else if (i === 2) {
        lastCommonSep = 3
      }
    }
    if (lastCommonSep === -1) lastCommonSep = 0
  }

  let out = ''
  for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
    if (i === fromEnd || from.charCodeAt(i) === CHAR_BACKWARD_SLASH) {
      out += out.length === 0 ? '..' : '\\..'
    }
  }

  toStart += lastCommonSep

  if (out.length > 0) {
    return `${out}${toOrig.substring(toStart, toEnd)}`
  }
  if (toOrig.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) {
    ++toStart
  }
  return toOrig.substring(toStart, toEnd)
}

exports.toNamespacedPath = function toNamespacedPath (path) {
  if (path.length === 0) return path

  const resolvedPath = exports.resolve(path)

  if (resolvedPath.length <= 2) return path

  if (resolvedPath.charCodeAt(0) === CHAR_BACKWARD_SLASH) {
    if (resolvedPath.charCodeAt(1) === CHAR_BACKWARD_SLASH) {
      const code = resolvedPath.charCodeAt(2)
      if (code !== CHAR_QUESTION_MARK && code !== CHAR_DOT) {
        return `\\\\?\\UNC\\${resolvedPath.substring(2)}`
      }
    }
  } else if (
    isWindowsDeviceRoot(resolvedPath.charCodeAt(0)) &&
      resolvedPath.charCodeAt(1) === CHAR_COLON &&
      resolvedPath.charCodeAt(2) === CHAR_BACKWARD_SLASH
  ) {
    return `\\\\?\\${resolvedPath}`
  }

  return path
}

exports.dirname = function dirname (path) {
  const len = path.length
  if (len === 0) return '.'
  let rootEnd = -1
  let offset = 0
  const code = path.charCodeAt(0)

  if (len === 1) {
    return isWindowsPathSeparator(code) ? path : '.'
  }

  if (isWindowsPathSeparator(code)) {
    rootEnd = offset = 1

    if (isWindowsPathSeparator(path.charCodeAt(1))) {
      let j = 2
      let last = j
      while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
        j++
      }
      if (j < len && j !== last) {
        last = j
        while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
          j++
        }
        if (j < len && j !== last) {
          last = j
          while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
            j++
          }
          if (j === len) {
            return path
          }
          if (j !== last) {
            rootEnd = offset = j + 1
          }
        }
      }
    }
  } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
    rootEnd = len > 2 && isWindowsPathSeparator(path.charCodeAt(2)) ? 3 : 2
    offset = rootEnd
  }

  let end = -1
  let matchedSlash = true
  for (let i = len - 1; i >= offset; --i) {
    if (isWindowsPathSeparator(path.charCodeAt(i))) {
      if (!matchedSlash) {
        end = i
        break
      }
    } else {
      matchedSlash = false
    }
  }

  if (end === -1) {
    if (rootEnd === -1) return '.'

    end = rootEnd
  }
  return path.substring(0, end)
}

exports.basename = function basename (path, suffix) {
  let start = 0
  let end = -1
  let matchedSlash = true

  if (path.length >= 2 && isWindowsDeviceRoot(path.charCodeAt(0)) && path.charCodeAt(1) === CHAR_COLON) {
    start = 2
  }

  if (suffix !== undefined && suffix.length > 0 && suffix.length <= path.length) {
    if (suffix === path) return ''
    let extIdx = suffix.length - 1
    let firstNonSlashEnd = -1
    for (let i = path.length - 1; i >= start; --i) {
      const code = path.charCodeAt(i)
      if (isWindowsPathSeparator(code)) {
        if (!matchedSlash) {
          start = i + 1
          break
        }
      } else {
        if (firstNonSlashEnd === -1) {
          matchedSlash = false
          firstNonSlashEnd = i + 1
        }
        if (extIdx >= 0) {
          if (code === suffix.charCodeAt(extIdx)) {
            if (--extIdx === -1) {
              end = i
            }
          } else {
            extIdx = -1
            end = firstNonSlashEnd
          }
        }
      }
    }

    if (start === end) end = firstNonSlashEnd
    else if (end === -1) end = path.length
    return path.substring(start, end)
  }
  for (let i = path.length - 1; i >= start; --i) {
    if (isWindowsPathSeparator(path.charCodeAt(i))) {
      if (!matchedSlash) {
        start = i + 1
        break
      }
    } else if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
  }

  if (end === -1) return ''
  return path.substring(start, end)
}

exports.extname = function extname (path) {
  let start = 0
  let startDot = -1
  let startPart = 0
  let end = -1
  let matchedSlash = true
  let preDotState = 0

  if (path.length >= 2 && path.charCodeAt(1) === CHAR_COLON && isWindowsDeviceRoot(path.charCodeAt(0))) {
    start = startPart = 2
  }

  for (let i = path.length - 1; i >= start; --i) {
    const code = path.charCodeAt(i)
    if (isWindowsPathSeparator(code)) {
      if (!matchedSlash) {
        startPart = i + 1
        break
      }
      continue
    }
    if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
    if (code === CHAR_DOT) {
      if (startDot === -1) startDot = i
      else if (preDotState !== 1) preDotState = 1
    } else if (startDot !== -1) {
      preDotState = -1
    }
  }

  if (startDot === -1 || end === -1 || preDotState === 0 || (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1)) {
    return ''
  }
  return path.substring(startDot, end)
}
{
  "name": "bare-path",
  "version": "3.0.0",
  "description": "Path manipulation library for JavaScript",
  "exports": {
    ".": "./index.js",
    "./package": "./package.json",
    "./posix": "./lib/posix.js",
    "./win32": "./lib/win32.js"
  },
  "files": [
    "index.js",
    "lib",
    "NOTICE"
  ],
  "scripts": {
    "test": "standard && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-path.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-path/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-path#readme",
  "dependencies": {
    "bare-os": "^3.0.1"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "standard": "^17.0.0"
  }
}
module.exports = require.addon()
const EventEmitter = require('bare-events')
const { Duplex } = require('bare-stream')
const binding = require('./binding')
const constants = require('./lib/constants')
const errors = require('./lib/errors')

const defaultReadBufferSize = 65536
const empty = Buffer.alloc(0)

module.exports = exports = class Pipe extends Duplex {
  constructor(path, opts = {}) {
    if (typeof path === 'object' && path !== null) {
      opts = path
      path = null
    }

    const { readBufferSize = defaultReadBufferSize, allowHalfOpen = true, eagerOpen = true } = opts

    super({ eagerOpen })

    this._state = 0

    this._allowHalfOpen = allowHalfOpen

    this._fd = -1
    this._path = null

    this._pendingOpen = null
    this._pendingWrite = null
    this._pendingFinal = null
    this._pendingDestroy = null

    this._buffer = Buffer.alloc(readBufferSize)

    this._handle = binding.init(
      this._buffer,
      this,
      noop,
      this._onconnect,
      this._onwrite,
      this._onfinal,
      this._onread,
      this._onclose
    )

    if (typeof path === 'number') {
      this.open(path)
    } else if (typeof path === 'string') {
      this.connect(path)
    }
  }

  get connecting() {
    return (this._state & constants.state.CONNECTING) !== 0
  }

  get pending() {
    return (this._state & constants.state.CONNECTED) === 0
  }

  get readyState() {
    if (this._state & constants.state.READABLE && this._state & constants.state.WRITABLE) {
      return 'open'
    }

    if (this._state & constants.state.READABLE) {
      return 'readOnly'
    }

    if (this._state & constants.state.WRITABLE) {
      return 'writeOnly'
    }

    return 'opening'
  }

  open(fd, opts = {}, onconnect) {
    if (typeof opts === 'function') {
      onconnect = opts
      opts = {}
    }

    if (typeof fd === 'object' && fd !== null) {
      opts = fd || {}
      fd = opts.fd
    }

    try {
      const status = binding.open(this._handle, fd)

      this._state |= constants.state.CONNECTED
      this._fd = fd

      if (status & binding.READABLE) {
        this._state |= constants.state.READABLE
      } else {
        this.push(null)
      }

      if (status & binding.WRITABLE) {
        this._state |= constants.state.WRITABLE
      } else {
        this.end()
      }

      if (onconnect) this.once('connect', onconnect)

      queueMicrotask(() => this.emit('connect'))
    } catch (err) {
      queueMicrotask(() => {
        if (this._pendingOpen) this._pendingOpen(err)
        else this.destroy(err)
      })
    }

    return this
  }

  connect(path, opts = {}, onconnect) {
    if (this._state & constants.state.CONNECTING || this._state & constants.state.CONNECTED) {
      throw errors.PIPE_ALREADY_CONNECTED('Pipe is already connected')
    }

    this._state |= constants.state.CONNECTING

    if (typeof opts === 'function') {
      onconnect = opts
      opts = {}
    }

    if (typeof path === 'object' && path !== null) {
      opts = path || {}
      path = opts.path
    }

    try {
      binding.connect(this._handle, path)

      this._path = path

      if (onconnect) this.once('connect', onconnect)
    } catch (err) {
      queueMicrotask(() => {
        if (this._pendingOpen) this._pendingOpen(err)
        else this.destroy(err)
      })
    }

    return this
  }

  ref() {
    binding.ref(this._handle)

    return this
  }

  unref() {
    binding.unref(this._handle)

    return this
  }

  _open(cb) {
    if (this._state & constants.state.CONNECTED) return cb(null)

    this._pendingOpen = cb
  }

  _read() {
    if ((this._state & constants.state.READING) === 0) {
      this._state |= constants.state.READING

      binding.resume(this._handle)
    }
  }

  _writev(batch, cb) {
    this._pendingWrite = [cb, batch]

    binding.writev(
      this._handle,
      batch.map(({ chunk }) => chunk)
    )
  }

  _final(cb) {
    if (this._state & constants.state.READABLE && this._state & constants.state.WRITABLE) {
      this._pendingFinal = cb

      binding.end(this._handle)
    } else {
      cb(null)
    }
  }

  _predestroy() {
    if (this._state & constants.state.CLOSING) return
    this._state |= constants.state.CLOSING

    binding.close(this._handle)
  }

  _destroy(err, cb) {
    if (this._state & constants.state.CLOSING) return cb(err)
    this._state |= constants.state.CLOSING

    this._pendingDestroy = cb

    binding.close(this._handle)
  }

  _continueOpen(err) {
    if (this._pendingOpen === null) return
    const cb = this._pendingOpen
    this._pendingOpen = null
    cb(err)
  }

  _continueWrite(err) {
    if (this._pendingWrite === null) return
    const cb = this._pendingWrite[0]
    this._pendingWrite = null
    cb(err)
  }

  _continueFinal(err) {
    if (this._pendingFinal === null) return
    const cb = this._pendingFinal
    this._pendingFinal = null
    cb(err)
  }

  _continueDestroy() {
    if (this._pendingDestroy === null) return
    const cb = this._pendingDestroy
    this._pendingDestroy = null
    cb(null)
  }

  _onconnect(err) {
    if (err) {
      if (this._pendingOpen) this._continueOpen(err)
      else this.destroy(err)
      return
    }

    this._state |= constants.state.CONNECTED | constants.state.READABLE | constants.state.WRITABLE
    this._state &= ~constants.state.CONNECTING
    this._continueOpen()

    this.emit('connect')
  }

  _onread(err, read) {
    if (err) {
      this.destroy(err)
      return
    }

    if (read === 0) {
      this.push(null)
      if (this._allowHalfOpen === false) this.end()
      return
    }

    const copy = Buffer.allocUnsafe(read)
    copy.set(this._buffer.subarray(0, read))

    if (this.push(copy) === false && this.destroying === false) {
      this._state &= ~constants.state.READING

      binding.pause(this._handle)
    }
  }

  _onwrite(err) {
    this._continueWrite(err)
  }

  _onfinal(err) {
    this._continueFinal(err === null || err.code === 'ENOTCONN' ? null : err)
  }

  _onclose() {
    this._continueDestroy()
  }

  _onspawn(readable, writable) {
    this._state |= constants.state.CONNECTED

    if (readable) {
      this._state |= constants.state.READABLE
    } else {
      this.push(null)
    }

    if (writable) {
      this._state |= constants.state.WRITABLE
    } else {
      this.end()
    }

    this._continueOpen()
  }
}

exports.Pipe = exports

exports.pipe = function pipe() {
  return binding.pipe()
}

exports.Server = class PipeServer extends EventEmitter {
  constructor(opts = {}, onconnection) {
    if (typeof opts === 'function') {
      onconnection = opts
      opts = {}
    }

    super()

    const {
      readBufferSize = defaultReadBufferSize,
      allowHalfOpen = true,
      pauseOnConnect = false
    } = opts

    this._state = 0

    this._readBufferSize = readBufferSize
    this._allowHalfOpen = allowHalfOpen
    this._pauseOnConnect = pauseOnConnect

    this._path = null
    this._connections = new Set()

    this._error = null
    this._handle = null

    if (onconnection) this.on('connection', onconnection)
  }

  get listening() {
    return (this._state & constants.state.BOUND) !== 0
  }

  address() {
    if ((this._state & constants.state.BOUND) === 0) {
      return null
    }

    return this._path
  }

  listen(path, backlog = 511, opts = {}, onlistening) {
    if (this._state & constants.state.BINDING || this._state & constants.state.BOUND) {
      throw errors.SERVER_ALREADY_LISTENING('Server is already listening')
    }

    if (this._state & constants.state.CLOSING) {
      throw errors.SERVER_IS_CLOSED('Server is closed')
    }

    this._state |= constants.state.BINDING

    if (typeof backlog === 'function') {
      onlistening = backlog
      backlog = 511
    } else if (typeof opts === 'function') {
      onlistening = opts
      opts = {}
    }

    if (typeof path === 'object' && path !== null) {
      opts = path || {}
      path = opts.path
      backlog = opts.backlog || 511
    }

    this._handle = binding.init(
      empty,
      this,
      this._onconnection,
      noop,
      noop,
      noop,
      noop,
      this._onclose
    )

    if (this._state & constants.state.UNREFED) binding.unref(this._handle)

    try {
      binding.bind(this._handle, path, backlog)

      this._path = path
      this._state |= constants.state.BOUND
      this._state &= ~constants.state.BINDING

      if (onlistening) this.once('listening', onlistening)

      queueMicrotask(() => this.emit('listening'))
    } catch (err) {
      this._error = err

      binding.close(this._handle)
    }

    return this
  }

  close(onclose) {
    if (onclose) this.once('close', onclose)

    if (this._state & constants.state.CLOSING) return
    this._state |= constants.state.CLOSING

    this._closeMaybe()

    return this
  }

  ref() {
    this._state &= ~constants.state.UNREFED

    if (this._handle !== null) binding.ref(this._handle)

    return this
  }

  unref() {
    this._state |= constants.state.UNREFED

    if (this._handle !== null) binding.unref(this._handle)

    return this
  }

  _closeMaybe() {
    if (this._state & constants.state.CLOSING && this._connections.size === 0) {
      if (this._handle !== null) binding.close(this._handle)
      else queueMicrotask(() => this.emit('close'))
    }
  }

  _onconnection(err) {
    if (err) {
      this.emit('error', err)
      return
    }

    if (this._state & constants.state.CLOSING) return

    const pipe = new exports.Pipe({
      readBufferSize: this._readBufferSize,
      allowHalfOpen: this._allowHalfOpen,
      eagerOpen: !this._pauseOnConnect
    })

    try {
      binding.accept(this._handle, pipe._handle)

      pipe._path = this._path
      pipe._state |= constants.state.CONNECTED | constants.state.READABLE | constants.state.WRITABLE

      this._connections.add(pipe)

      pipe.on('close', () => {
        this._connections.delete(pipe)
        this._closeMaybe()
      })

      this.emit('connection', pipe)
    } catch (err) {
      pipe.destroy()

      throw err
    }
  }

  _onclose() {
    const err = this._error

    this._state &= ~constants.state.BINDING
    this._error = null
    this._handle = null

    if (err) this.emit('error', err)
    else this.emit('close')
  }
}

exports.constants = constants
exports.errors = errors

exports.createConnection = function createConnection(path, opts, onconnect) {
  if (typeof opts === 'function') {
    onconnect = opts
    opts = {}
  }

  if (typeof path === 'object' && path !== null) {
    opts = path || {}
    path = opts.path
  }

  return new exports.Pipe(opts).connect(path, opts, onconnect)
}

exports.createServer = function createServer(opts, onconnection) {
  return new exports.Server(opts, onconnection)
}

function noop() {}
module.exports = {
  state: {
    CONNECTING: 0x1,
    CONNECTED: 0x2,
    BINDING: 0x4,
    BOUND: 0x8,
    READING: 0x10,
    CLOSING: 0x20,
    READABLE: 0x40,
    WRITABLE: 0x80,
    UNREFED: 0x100
  }
}
module.exports = class PipeError extends Error {
  constructor(msg, fn = PipeError, code = fn.name) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'PipeError'
  }

  static PIPE_ALREADY_CONNECTED(msg) {
    return new PipeError(msg, PipeError.PIPE_ALREADY_CONNECTED)
  }

  static SERVER_ALREADY_LISTENING(msg) {
    return new PipeError(msg, PipeError.SERVER_ALREADY_LISTENING)
  }

  static SERVER_IS_CLOSED(msg) {
    return new PipeError(msg, PipeError.SERVER_IS_CLOSED)
  }
}
{
  "name": "bare-pipe",
  "version": "4.1.5",
  "description": "Native I/O pipes for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    },
    "./errors": {
      "types": "./lib/errors.d.ts",
      "default": "./lib/errors.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-pipe.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-pipe/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-pipe#readme",
  "engines": {
    "bare": ">=1.16.0"
  },
  "dependencies": {
    "bare-events": "^2.0.0",
    "bare-stream": "^2.0.0"
  },
  "devDependencies": {
    "bare-path": "^3.0.0",
    "brittle": "^3.2.1",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  }
}
const abort = require('bare-abort')
const EventEmitter = require('bare-events')
const Signal = require('bare-signals')
const os = require('bare-os')
const env = require('bare-env')
const hrtime = require('bare-hrtime')
const stdio = require('bare-stdio')

class Process extends EventEmitter {
  constructor() {
    super()

    this._startTime = hrtime.bigint()

    EventEmitter.forward(Bare, this, [
      'uncaughtException',
      'unhandledRejection',
      'beforeExit',
      'exit',
      'suspend',
      'wakeup',
      'idle',
      'resume'
    ])

    const signals = new Signal.Emitter()

    signals.unref()

    EventEmitter.forward(signals, this, Object.keys(os.constants.signals))
  }

  get stdin() {
    return stdio.in
  }

  get stdout() {
    return stdio.out
  }

  get stderr() {
    return stdio.err
  }

  get platform() {
    return os.platform()
  }

  get arch() {
    return os.arch()
  }

  get title() {
    return os.getProcessTitle()
  }

  set title(title) {
    os.setProcessTitle(title)
  }

  get pid() {
    return os.pid()
  }

  get ppid() {
    return os.ppid()
  }

  get argv() {
    return Bare.argv
  }

  get execPath() {
    return os.execPath()
  }

  get exitCode() {
    return Bare.exitCode
  }

  set exitCode(code) {
    Bare.exitCode = code
  }

  get version() {
    return Bare.version
  }

  get versions() {
    return Bare.versions
  }

  get env() {
    return env
  }

  get hrtime() {
    return hrtime
  }

  abort() {
    abort()
  }

  exit(code) {
    Bare.exit(code)
  }

  suspend() {
    Bare.suspend()
  }

  resume() {
    Bare.resume()
  }

  cwd() {
    return os.cwd()
  }

  chdir(directory) {
    os.chdir(directory)
  }

  kill(pid, signal) {
    os.kill(pid, signal)
  }

  uptime() {
    return Number(hrtime.bigint() - this._startTime) / 1e9
  }

  cpuUsage(previous) {
    return os.cpuUsage(previous)
  }

  threadCpuUsage(previous) {
    return os.threadCpuUsage(previous)
  }

  resourceUsage() {
    return os.resourceUsage()
  }

  availableMemory() {
    return os.availableMemory()
  }

  constrainedMemory() {
    return os.constrainedMemory()
  }

  memoryUsage() {
    return os.memoryUsage()
  }

  nextTick(cb, ...args) {
    queueMicrotask(cb.bind(null, ...args))
  }

  [Symbol.for('bare.inspect')]() {
    return {
      __proto__: { constructor: Process },

      platform: this.platform,
      arch: this.arch,
      title: this.title,
      pid: this.pid,
      ppid: this.ppid,
      argv: this.argv,
      execPath: this.execPath,
      exitCode: this.exitCode,
      version: this.version,
      versions: this.versions,
      env: this.env
    }
  }
}

module.exports = new Process()
{
  "name": "bare-process",
  "version": "4.4.1",
  "description": "Node.js-compatible process control for Bare",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "global.js",
    "global.d.ts"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-process.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-process/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-process#readme",
  "dependencies": {
    "bare-abort": "^2.0.13",
    "bare-env": "^3.0.0",
    "bare-events": "^2.3.1",
    "bare-hrtime": "^2.0.0",
    "bare-os": "^3.7.1",
    "bare-signals": "^4.0.0",
    "bare-stdio": "^1.0.1"
  },
  "devDependencies": {
    "brittle": "^3.2.1",
    "lunte": "^1.6.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = require.addon()
const EventEmitter = require('bare-events')
const os = require('bare-os')
const binding = require('./binding')
const errors = require('./lib/errors')

const signals = os.constants.signals

module.exports = exports = class Signal extends EventEmitter {
  constructor(signum) {
    super()

    if (typeof signum === 'string') {
      if (signum in signals === false) {
        throw errors.UNKNOWN_SIGNAL(`Unknown signal '${signum}'`)
      }

      signum = signals[signum]
    }

    this._signum = signum
    this._closing = null
    this._handle = binding.init(this, this._onsignal, this._onclose)
  }

  start() {
    if (this._closing) throw errors.SIGNAL_CLOSED('Signal is closed')
    binding.start(this._handle, this._signum)
    return this
  }

  stop() {
    if (this._closing) return this
    binding.stop(this._handle)
    return this
  }

  ref() {
    if (this._closing) return this
    binding.ref(this._handle)
    return this
  }

  unref() {
    if (this._closing) return this
    binding.unref(this._handle)
    return this
  }

  close() {
    if (this._closing) return this._closing
    this._closing = EventEmitter.once(this, 'close')

    binding.close(this._handle)

    return this._closing
  }

  _onsignal() {
    this.emit('signal', this._signum)
  }

  _onclose() {
    this._handle = null

    this.emit('close')
  }

  static send(signum, pid = os.pid()) {
    os.kill(pid, signum)
  }
}

exports.Emitter = require('./lib/emitter')

exports.constants = signals
exports.errors = errors
const EventEmitter = require('bare-events')
const Signal = require('..')

module.exports = class SignalEmitter extends EventEmitter {
  constructor() {
    super()

    this._signals = new Map()
    this._unrefed = false

    this.on('newListener', this._onnewlistener).on(
      'removeListener',
      this._onremovelistener
    )
  }

  ref() {
    this._unrefed = false
    for (const signal of this._signals.values()) signal.ref()
    return this
  }

  unref() {
    this._unrefed = true
    for (const signal of this._signals.values()) signal.unref()
    return this
  }

  _onnewlistener(name) {
    if (name === 'newListener' || name === 'removeListener') return

    if (this.listenerCount(name) === 0) {
      const signal = new Signal(name)

      signal.on('signal', this._onsignal.bind(this, name)).start()

      if (this._unrefed) signal.unref()

      this._signals.set(name, signal)
    }
  }

  _onremovelistener(name) {
    if (name === 'newListener' || name === 'removeListener') return

    if (this.listenerCount(name) === 0) {
      const signal = this._signals.get(name)

      if (this._unrefed) signal.ref()

      signal.close()

      this._signals.delete(name)
    }
  }

  _onsignal(name) {
    this.emit(name, name, Signal.constants[name])
  }
}
module.exports = class SignalError extends Error {
  constructor(msg, fn = SignalError, code = fn.name) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'SignalError'
  }

  static UNKNOWN_SIGNAL(msg) {
    return new SignalError(msg, SignalError.UNKNOWN_SIGNAL)
  }

  static SIGNAL_CLOSED(msg) {
    return new SignalError(msg, SignalError.SIGNAL_CLOSED)
  }
}
{
  "name": "bare-signals",
  "version": "4.2.0",
  "description": "Native signal handling for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./errors": "./lib/errors.js",
    "./emitter": "./lib/emitter.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-signals.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-signals/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-signals#readme",
  "engines": {
    "bare": ">=1.7.0"
  },
  "dependencies": {
    "bare-events": "^2.5.3",
    "bare-os": "^3.3.1"
  },
  "devDependencies": {
    "brittle": "^3.2.1",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
module.exports = require.addon()
const fs = require('bare-fs')
const tty = require('bare-tty')
const Pipe = require('bare-pipe')
const binding = require('./binding')

const { TTY, NAMED_PIPE } = binding

class IO {
  constructor() {
    this._in = null
    this._out = null
    this._err = null
  }

  get in() {
    if (this._in === null) {
      switch (binding.guessType(0)) {
        case TTY:
          this._in = new tty.ReadStream(0)
          break
        case NAMED_PIPE:
          this._in = new Pipe(0, { eagerOpen: false })
          break
        default:
          this._in = fs.createReadStream(null, { fd: 0, eagerOpen: false })
      }
    }

    return this._in
  }

  get out() {
    if (this._out === null) {
      switch (binding.guessType(1)) {
        case TTY:
          this._out = new tty.WriteStream(1)
          break
        case NAMED_PIPE:
          this._out = new Pipe(1, { eagerOpen: false })
          this._out.unref()
          break
        default:
          this._out = fs.createWriteStream(null, { fd: 1, eagerOpen: false })
      }
    }

    return this._out
  }

  get err() {
    if (this._err === null) {
      switch (binding.guessType(2)) {
        case TTY:
          this._err = new tty.WriteStream(2)
          break
        case NAMED_PIPE:
          this._err = new Pipe(2, { eagerOpen: false })
          this._err.unref()
          break
        default:
          this._err = fs.createWriteStream(null, { fd: 2, eagerOpen: false })
      }
    }

    return this._err
  }
}

module.exports = new IO()
{
  "name": "bare-stdio",
  "version": "1.0.2",
  "description": "Standard input/output streams for Bare",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./constants": "./lib/constants.js",
    "./errors": "./lib/errors.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-stdio.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-stdio/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-stdio#readme",
  "dependencies": {
    "bare-fs": "^4.5.2",
    "bare-pipe": "^4.1.5",
    "bare-tty": "^5.0.3"
  },
  "devDependencies": {
    "bare-os": "^3.6.2",
    "bare-path": "^3.0.0",
    "bare-subprocess": "^3.1.4",
    "brittle": "^3.19.1",
    "cmake-bare": "^1.7.7",
    "lunte": "^1.4.0",
    "prettier": "^3.8.1",
    "prettier-config-holepunch": "^2.0.0",
    "tt-native": "^1.1.1"
  }
}
const stream = require('streamx')
const { ReadableStream, WritableStream } = require('./web')

const defaultEncoding = 'utf8'

module.exports = exports = stream.Stream

exports.pipeline = stream.pipeline

exports.isStream = stream.isStream
exports.isEnding = stream.isEnding
exports.isEnded = stream.isEnded
exports.isFinishing = stream.isFinishing
exports.isFinished = stream.isFinished
exports.isDisturbed = stream.isDisturbed

exports.isErrored = function isErrored(stream) {
  return exports.getStreamError(stream) !== null
}

exports.isReadable = function isReadable(stream) {
  return stream.readable && !stream.destroying && !exports.isEnded(stream)
}

exports.isWritable = function isWritable(stream) {
  return stream.writable && !stream.destroying && !exports.isFinishing(stream)
}

exports.getStreamError = stream.getStreamError

exports.addAbortSignal = function addAbortSignal(signal, stream) {
  function onAbort() {
    stream.destroy(signal.reason)
  }

  if (signal.aborted) onAbort()
  else signal.addEventListener('abort', onAbort)

  return stream
}

exports.Stream = exports

exports.Readable = class Readable extends stream.Readable {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthReadable: null,
      map: null,
      mapReadable: null
    })

    if (this._construct) this._open = this._construct

    if (this._read !== stream.Readable.prototype._read) {
      this._read = read.bind(this, this._read)
    }

    if (this._destroy !== stream.Stream.prototype._destroy) {
      this._destroy = destroy.bind(this, this._destroy)
    }
  }

  get closed() {
    return !exports.isReadable(this)
  }

  get errored() {
    return stream.getStreamError(this)
  }

  push(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = Buffer.from(chunk, encoding || defaultEncoding)
    }

    return super.push(chunk)
  }

  unshift(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = Buffer.from(chunk, encoding || defaultEncoding)
    }

    super.unshift(chunk)
  }

  static fromWeb(readableStream, opts = {}) {
    const stream = readableStream._stream

    if (opts.encoding) stream.setEncoding(opts.encoding)
    if (opts.signal) exports.addAbortSignal(opts.signal, stream)

    return stream
  }

  static toWeb(readable, opts = {}) {
    return new ReadableStream(readable, opts.strategy)
  }

  async [Symbol.asyncDispose]() {
    if (!this.destroyed) this.destroy()

    await new Promise((resolve) => exports.finished(this, resolve))
  }
}

exports.Writable = class Writable extends stream.Writable {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthWritable,
      map: null,
      mapWritable: null
    })

    if (this._construct) this._open = this._construct

    if (this._write !== stream.Writable.prototype._write) {
      this._write = write.bind(this, this._write)
    }

    if (this._destroy !== stream.Stream.prototype._destroy) {
      this._destroy = destroy.bind(this, this._destroy)
    }
  }

  get closed() {
    return !exports.isWritable(this)
  }

  get errored() {
    return stream.getStreamError(this)
  }

  write(chunk, encoding, cb) {
    if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = Buffer.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result = super.write({ chunk, encoding })

    if (cb) stream.Writable.drained(this).then(() => cb(null), cb)

    return result
  }

  end(chunk, encoding, cb) {
    if (typeof chunk === 'function') {
      cb = chunk
      chunk = null
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = Buffer.from(chunk, encoding || defaultEncoding)
    } else {
      encoding = 'buffer'
    }

    const result =
      chunk !== undefined && chunk !== null ? super.end({ chunk, encoding }) : super.end()

    if (cb) this.once('finish', () => cb(null))

    return result
  }

  static fromWeb(writableStream, opts = {}) {
    const stream = writableStream._stream

    if (opts.signal) exports.addAbortSignal(opts.signal, stream)

    return stream
  }

  static toWeb(writable) {
    return new WritableStream(writable)
  }

  async [Symbol.asyncDispose]() {
    if (!this.destroyed) this.destroy()

    await new Promise((resolve) => exports.finished(this, resolve))
  }
}

exports.Duplex = class Duplex extends stream.Duplex {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthReadable: null,
      byteLengthWritable,
      map: null,
      mapReadable: null,
      mapWritable: null
    })

    if (this._construct) this._open = this._construct

    if (this._read !== stream.Readable.prototype._read) {
      this._read = read.bind(this, this._read)
    }

    if (this._write !== stream.Duplex.prototype._write) {
      this._write = write.bind(this, this._write)
    }

    if (this._destroy !== stream.Stream.prototype._destroy) {
      this._destroy = destroy.bind(this, this._destroy)
    }
  }

  push(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = Buffer.from(chunk, encoding || defaultEncoding)
    }

    return super.push(chunk)
  }

  unshift(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = Buffer.from(chunk, encoding || defaultEncoding)
    }

    super.unshift(chunk)
  }

  write(chunk, encoding, cb) {
    if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = Buffer.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result = super.write({ chunk, encoding })

    if (cb) stream.Writable.drained(this).then(() => cb(null), cb)

    return result
  }

  end(chunk, encoding, cb) {
    if (typeof chunk === 'function') {
      cb = chunk
      chunk = null
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = Buffer.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result =
      chunk !== undefined && chunk !== null ? super.end({ chunk, encoding }) : super.end()

    if (cb) this.once('finish', () => cb(null))

    return result
  }

  static fromWeb({ readable: readableStream, writable: writableStream }, opts) {
    const readable = exports.Readable.fromWeb(readableStream, opts)
    const writable = exports.Writable.fromWeb(writableStream, opts)

    const duplex = new exports.Duplex({
      write(data, encoding, cb) {
        writable.write(data, encoding, cb)
      }
    })

    readable
      .on('data', (data) => duplex.push(data))
      .on('end', () => duplex.push(null))
      .on('error', (err) => duplex.destroy(err))

    writable.on('finish', () => duplex.end()).on('error', (err) => duplex.destroy(err))

    return duplex
  }

  static toWeb(duplex) {
    const readableStream = exports.Readable.toWeb(duplex)
    const writableStream = exports.Writable.toWeb(duplex)

    return { readable: readableStream, writable: writableStream }
  }
}

class DuplexSide extends exports.Duplex {
  constructor(opts) {
    super(opts)

    this._otherSide = null
    this._cb = null
  }

  _read() {
    const cb = this._cb
    if (!cb) return

    this._cb = null
    cb()
  }

  _write(chunk, encoding, cb) {
    this._otherSide.push(chunk, encoding)
    this._otherSide._cb = cb
  }

  _final(cb) {
    this._otherSide.on('end', cb)
    this._otherSide.push(null)
  }
}

exports.duplexPair = function duplexPair(opts) {
  const sideA = new DuplexSide(opts)
  const sideB = new DuplexSide(opts)

  sideA._otherSide = sideB
  sideB._otherSide = sideA

  return [sideA, sideB]
}

exports.Transform = class Transform extends stream.Transform {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthReadable: null,
      byteLengthWritable,
      map: null,
      mapReadable: null,
      mapWritable: null
    })

    if (this._transform !== stream.Transform.prototype._transform) {
      this._transform = transform.bind(this, this._transform)
    } else {
      this._transform = passthrough
    }
  }

  push(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = Buffer.from(chunk, encoding || defaultEncoding)
    }

    return super.push(chunk)
  }

  unshift(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = Buffer.from(chunk, encoding || defaultEncoding)
    }

    super.unshift(chunk)
  }

  write(chunk, encoding, cb) {
    if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = Buffer.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result = super.write({ chunk, encoding })

    if (cb) stream.Writable.drained(this).then(() => cb(null), cb)

    return result
  }

  end(chunk, encoding, cb) {
    if (typeof chunk === 'function') {
      cb = chunk
      chunk = null
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = Buffer.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result =
      chunk !== undefined && chunk !== null ? super.end({ chunk, encoding }) : super.end()

    if (cb) this.once('finish', () => cb(null))

    return result
  }
}

exports.PassThrough = class PassThrough extends exports.Transform {}

exports.finished = function finished(stream, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (!opts) opts = {}

  const { cleanup = false } = opts

  const done = () => {
    cb(exports.getStreamError(stream, { all: true }))

    if (cleanup) detach()
  }

  const detach = () => {
    stream.off('close', done)
    stream.off('error', noop)
  }

  if (stream.destroyed) {
    done()
  } else {
    stream.on('close', done)
    stream.on('error', noop)
  }

  return detach
}

function read(read, cb) {
  read.call(this, 65536)

  cb(null)
}

function write(write, data, cb) {
  write.call(this, data.chunk, data.encoding, cb)
}

function transform(transform, data, cb) {
  transform.call(this, data.chunk, data.encoding, cb)
}

function destroy(destroy, cb) {
  destroy.call(this, exports.getStreamError(this), cb)
}

function passthrough(data, cb) {
  cb(null, data.chunk)
}

function byteLengthWritable(data) {
  return data.chunk.byteLength
}

function noop() {}
{
  "name": "bare-stream",
  "version": "2.13.1",
  "description": "Streaming data for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./promises": "./promises.js",
    "./web": {
      "types": "./web.d.ts",
      "default": "./web.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "promises.js",
    "web.js",
    "web.d.ts",
    "global.js",
    "global.d.ts"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-stream.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-stream/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-stream#readme",
  "dependencies": {
    "streamx": "^2.25.0",
    "teex": "^1.0.1"
  },
  "devDependencies": {
    "bare-abort-controller": "^1.1.0",
    "bare-buffer": "^3.0.0",
    "bare-events": "^2.5.4",
    "brittle": "^3.5.2",
    "lunte": "^1.6.0",
    "prettier": "^3.3.3",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "bare-abort-controller": "*",
    "bare-buffer": "*",
    "bare-events": "*"
  },
  "peerDependenciesMeta": {
    "bare-abort-controller": {
      "optional": true
    },
    "bare-buffer": {
      "optional": true
    },
    "bare-events": {
      "optional": true
    }
  }
}
const { Readable, Writable, Transform, getStreamError, isStreamx, isDisturbed } = require('streamx')
const tee = require('teex')

const readableKind = Symbol.for('bare.stream.readable.kind')
const writableKind = Symbol.for('bare.stream.writable.kind')
const transformKind = Symbol.for('bare.stream.transform.kind')

// https://streams.spec.whatwg.org/#readablestreamdefaultreader
exports.ReadableStreamDefaultReader = class ReadableStreamDefaultReader {
  constructor(stream) {
    this._stream = stream
    this._stream._stream.once('close', onclose).once('error', onerror)

    const closed = Promise.withResolvers()

    // Avoid unhandled exceptions
    closed.promise.catch(noop)

    this._closed = closed

    function onclose() {
      closed.resolve()
    }

    function onerror(err) {
      closed.reject(err)
    }
  }

  get closed() {
    return this._closed.promise
  }

  read() {
    const stream = this._stream._stream

    return new Promise((resolve, reject) => {
      const err = getStreamError(stream)

      if (err) return reject(err)

      if (stream.destroyed) {
        return resolve({ value: undefined, done: true })
      }

      const value = stream.read()

      if (value !== null) {
        return resolve({ value, done: false })
      }

      stream.once('readable', onreadable).once('close', onclose).once('error', onerror)

      function onreadable() {
        const value = stream.read()

        ondone(null, value === null ? { value: undefined, done: true } : { value, done: false })
      }

      function onclose() {
        ondone(null, { value: undefined, done: true })
      }

      function onerror(err) {
        ondone(err, null)
      }

      function ondone(err, value) {
        stream.off('readable', onreadable).off('close', onclose).off('error', onerror)

        if (err) reject(err)
        else resolve(value)
      }
    })
  }

  releaseLock() {
    this._closed.reject(new TypeError('Reader was released'))
    this._stream._releaseLock()
    this._stream = null
  }

  cancel(reason = new TypeError('Stream was cancelled')) {
    const stream = this._stream._stream

    if (stream.destroyed) return Promise.resolve()

    return new Promise((resolve) =>
      stream.once('close', resolve).once('error', noop).destroy(reason)
    )
  }
}

// https://streams.spec.whatwg.org/#readablestreamdefaultcontroller
exports.ReadableStreamDefaultController = class ReadableStreamDefaultController {
  constructor(stream) {
    this._stream = stream
  }

  get desiredSize() {
    const stream = this._stream._stream

    return stream._readableState.highWaterMark - stream._readableState.buffered
  }

  enqueue(data) {
    this._stream._stream.push(data)
  }

  close() {
    this._stream._stream.push(null)
  }

  error(err) {
    this._stream._stream.destroy(err)
  }
}

// https://streams.spec.whatwg.org/#readablestream
class ReadableStream {
  static get [readableKind]() {
    return 0 // Compatibility version
  }

  static from(iterable) {
    return new ReadableStream(Readable.from(iterable))
  }

  constructor(underlyingSource = {}, queuingStrategy) {
    if (isStreamx(underlyingSource)) {
      this._stream = underlyingSource
    } else {
      if (queuingStrategy === undefined) {
        queuingStrategy = new exports.CountQueuingStrategy()
      }

      const { start, pull, cancel } = underlyingSource
      const { highWaterMark = 1, size = defaultSize } = queuingStrategy

      this._stream = new Readable({ highWaterMark, byteLength: size })

      const controller = new exports.ReadableStreamDefaultController(this)

      try {
        let starting = Promise.resolve()

        if (start) starting = forwardError(start.call(this, controller), controller)

        if (pull) {
          this._stream._read = this._read.bind(this, starting, pull.bind(this, controller))
        }

        if (cancel) {
          this._stream.once('error', cancel.bind(this))
        }
      } catch (err) {
        controller.error(err)
      }
    }

    this._reader = null
  }

  get [readableKind]() {
    return ReadableStream[readableKind]
  }

  get locked() {
    return this._reader !== null
  }

  getReader() {
    if (this.locked) throw new TypeError('Stream is locked')

    this._reader = new exports.ReadableStreamDefaultReader(this)

    return this._reader
  }

  cancel(reason = new TypeError('Stream was cancelled')) {
    const stream = this._stream

    if (stream.destroyed) return Promise.resolve()

    if (this.locked) return Promise.reject(new TypeError('Stream is locked'))

    return new Promise((resolve) =>
      stream.once('close', resolve).once('error', noop).destroy(reason)
    )
  }

  tee() {
    const [a, b] = tee(this._stream)

    return [new ReadableStream(a), new ReadableStream(b)]
  }

  pipeTo(destination) {
    return new Promise((resolve, reject) =>
      this._stream.pipe(destination._stream, (err) => {
        err ? reject(err) : resolve()
      })
    )
  }

  [Symbol.asyncIterator]() {
    return this._stream[Symbol.asyncIterator]()
  }

  _releaseLock() {
    this._reader = null
  }

  async _read(starting, pull, cb) {
    await starting

    let err = null
    try {
      await pull()
    } catch (e) {
      err = e
    }
    cb(err)
  }
}

function defaultSize() {
  return 1
}

exports.ReadableStream = ReadableStream

// https://streams.spec.whatwg.org/#countqueuingstrategy
exports.CountQueuingStrategy = class CountQueuingStrategy {
  constructor(opts = {}) {
    const { highWaterMark = 1 } = opts

    this.highWaterMark = highWaterMark
  }

  size(chunk) {
    return 1
  }
}

// https://streams.spec.whatwg.org/#bytelengthqueuingstrategy
exports.ByteLengthQueuingStrategy = class ByteLengthQueuingStrategy {
  constructor(opts = {}) {
    const { highWaterMark = 16384 } = opts

    this.highWaterMark = highWaterMark
  }

  size(chunk) {
    return chunk.byteLength
  }
}

exports.isReadableStream = function isReadableStream(value) {
  if (value instanceof ReadableStream) return true

  return (
    typeof value === 'object' &&
    value !== null &&
    value[readableKind] === ReadableStream[readableKind]
  )
}

// https://streams.spec.whatwg.org/#readablestream-errored
exports.isReadableStreamErrored = function isReadableStreamErrored(stream) {
  return getStreamError(stream._stream) !== null
}

// https://streams.spec.whatwg.org/#is-readable-stream-disturbed
exports.isReadableStreamDisturbed = function isReadableStreamDisturbed(stream) {
  return isDisturbed(stream._stream)
}

// https://streams.spec.whatwg.org/#writablestreamdefaultwriter
exports.WritableStreamDefaultWriter = class WritableStreamDefaultWriter {
  constructor(stream) {
    this._stream = stream
    this._stream._stream.once('close', onclose).once('error', onerror)

    const closed = Promise.withResolvers()

    // Avoid unhandled exceptions
    closed.promise.catch(noop)

    this._closed = closed

    function onclose() {
      closed.resolve()
    }

    function onerror(err) {
      closed.reject(err)
    }
  }

  get desiredSize() {
    const stream = this._stream._stream

    return stream._writableState.highWaterMark - stream._writableState.buffered
  }

  get closed() {
    return this._closed.promise
  }

  get ready() {
    const stream = this._stream._stream

    if (getStreamError(stream)) return Promise.reject()

    return Writable.drained(stream).then()
  }

  async write(chunk) {
    const stream = this._stream._stream

    let err = getStreamError(stream)
    if (err) return Promise.reject(err)

    stream.write(chunk)

    await Writable.drained(stream)

    err = getStreamError(stream)
    if (err) return Promise.reject(err)
  }

  releaseLock() {
    this._closed.reject(new TypeError('Writer was released'))
    this._stream._releaseLock()
    this._stream = null
  }

  close() {
    const stream = this._stream._stream

    if (stream.destroyed) return Promise.resolve()

    return new Promise((resolve) => stream.once('close', resolve).end())
  }

  abort(reason = new TypeError('Stream was aborted')) {
    const stream = this._stream._stream

    if (stream.destroyed) return Promise.resolve()

    return new Promise((resolve) => stream.once('close', resolve).destroy(reason))
  }
}

// https://streams.spec.whatwg.org/#writablestreamdefaultcontroller
exports.WritableStreamDefaultController = class WritableStreamDefaultController {
  constructor(stream) {
    this._stream = stream
  }

  error(err) {
    this._stream._stream.destroy(err)
  }
}

// https://streams.spec.whatwg.org/#writablestream
class WritableStream {
  static get [writableKind]() {
    return 0 // Compatibility version
  }

  constructor(underlyingSink = {}, queuingStrategy = {}) {
    if (isStreamx(underlyingSink)) {
      this._stream = underlyingSink
    } else {
      if (queuingStrategy === undefined) {
        queuingStrategy = new exports.CountQueuingStrategy()
      }

      const { start, write, close, abort } = underlyingSink
      const { highWaterMark = 1, size = defaultSize } = queuingStrategy

      this._stream = new Writable({ highWaterMark, byteLength: size })

      const controller = new exports.WritableStreamDefaultController(this)

      this._controller = controller

      try {
        let starting = Promise.resolve()

        if (start) starting = forwardError(start.call(this, controller), controller)

        if (write) {
          this._stream._write = this._write.bind(this, starting, write.bind(this))
        }

        if (close) {
          this._stream._destroy = this._destroy.bind(this, close.call(this))
        }

        if (abort) {
          this._stream.once('error', abort.bind(this))
        }
      } catch (err) {
        controller.error(err)
      }
    }

    this._writer = null
  }

  get [writableKind]() {
    return WritableStream[writableKind]
  }

  get locked() {
    return this._writer !== null
  }

  getWriter() {
    if (this.locked) throw new TypeError('Stream is locked')

    this._writer = new exports.WritableStreamDefaultWriter(this)

    return this._writer
  }

  abort(reason = new TypeError('Stream was aborted')) {
    if (this._stream.destroyed) return Promise.resolve()

    if (this.locked) return Promise.reject(new TypeError('Stream is locked'))

    return new Promise((resolve) => this._stream.once('close', resolve).destroy(reason))
  }

  close() {
    if (this._stream.destroyed) return Promise.resolve()

    if (this.locked) return Promise.reject(new TypeError('Stream is locked'))

    return new Promise((resolve) => this._stream.once('close', resolve).end())
  }

  _releaseLock() {
    this._writer = null
  }

  async _write(starting, write, data, cb) {
    await starting

    let err = null
    try {
      await write(data, this._controller)
    } catch (e) {
      err = e
    }
    cb(err)
  }

  async _destroy(closing, cb) {
    let err = null
    try {
      await closing
    } catch (e) {
      err = e
    }
    cb(err)
  }
}

exports.WritableStream = WritableStream

exports.isWritableStream = function isWritableStream(value) {
  if (value instanceof WritableStream) return true

  return (
    typeof value === 'object' &&
    value !== null &&
    value[writableKind] === WritableStream[writableKind]
  )
}

// https://streams.spec.whatwg.org/#transformstreamdefaultcontroller
exports.TransformStreamDefaultController = class TransformStreamDefaultController {
  constructor(stream) {
    this._stream = stream
  }

  get desiredSize() {
    const stream = this._stream._stream

    return stream._readableState.highWaterMark - stream._readableState.buffered
  }

  enqueue(data) {
    this._stream._stream.push(data)
  }

  error(err) {
    this._stream._stream.destroy(err)
  }

  terminate() {
    const stream = this._stream._stream

    stream.push(null)
    stream.destroy(new TypeError('Stream has been terminated'))
  }
}

// https://streams.spec.whatwg.org/#transformstream
class TransformStream {
  static get [transformKind]() {
    return 0 // Compatibility version
  }

  constructor(transformer = {}, writableStrategy = {}, readableStrategy = {}) {
    if (isStreamx(transformer)) {
      this._stream = transformer
    } else {
      const { start, transform, flush } = transformer

      this._stream = new Transform({ ...writableStrategy, ...readableStrategy })

      const controller = new exports.TransformStreamDefaultController(this)

      this._controller = controller

      try {
        let starting = Promise.resolve()

        if (start) starting = forwardError(start.call(this, controller), controller)

        if (transform) {
          this._stream._transform = this._transform.bind(this, starting, transform.bind(this))
        }

        if (flush) {
          this._stream._flush = this._flush.bind(this, flush.call(this, this._controller))
        }
      } catch (err) {
        controller.error(err)
      }
    }

    this._writable = new WritableStream(this._stream)
    this._readable = new ReadableStream(this._stream)
  }

  get [transformKind]() {
    return TransformStream[transformKind]
  }

  get writable() {
    return this._writable
  }

  get readable() {
    return this._readable
  }

  async _transform(starting, transform, data, cb) {
    await starting

    let err = null
    try {
      await transform(data, this._controller)
    } catch (e) {
      err = e
    }
    cb(err)
  }

  async _flush(flush, cb) {
    let err = null
    try {
      await flush
    } catch (e) {
      err = e
    }
    cb(err)
  }
}

exports.TransformStream = TransformStream

exports.isTransformStream = function isTransformStream(value) {
  if (value instanceof TransformStream) return true

  return (
    typeof value === 'object' &&
    value !== null &&
    value[transformKind] === TransformStream[transformKind]
  )
}

async function forwardError(promise, controller) {
  try {
    await promise
  } catch (err) {
    controller.error(err)
  }
}

function noop() {}
module.exports = require.addon()
const EventEmitter = require('bare-events')
const { Duplex } = require('bare-stream')
const dns = require('bare-dns')
const binding = require('./binding')
const constants = require('./lib/constants')
const errors = require('./lib/errors')
const ip = require('./lib/ip')

const defaultReadBufferSize = 65536
const empty = Buffer.alloc(0)

exports.Socket = class TCPSocket extends Duplex {
  constructor(opts = {}) {
    const { readBufferSize = defaultReadBufferSize, allowHalfOpen = true, eagerOpen = true } = opts

    super({ eagerOpen })

    this._state = 0

    this._allowHalfOpen = allowHalfOpen

    this._keepAlive = 0
    this._keepAliveInitialDelay = 0
    this._noDelay = 0

    this._localAddress = null
    this._remoteAddress = null

    this._pendingOpen = null
    this._pendingWrite = null
    this._pendingFinal = null
    this._pendingDestroy = null

    this._timer = null
    this._timeout = 0

    this._buffer = Buffer.alloc(readBufferSize)

    this._addresses = null
    this._errors = null

    this._handle = binding.init(
      this._buffer,
      this,
      noop,
      this._onconnect,
      this._onreset,
      this._onread,
      this._onwrite,
      this._onfinal,
      this._onclose
    )
  }

  get connecting() {
    return (this._state & constants.state.CONNECTING) !== 0
  }

  get pending() {
    return (this._state & constants.state.CONNECTED) === 0
  }

  get timeout() {
    return this._timeout || undefined // For Node.js compatibility
  }

  get readyState() {
    if (this._state & constants.state.CONNECTED) {
      return 'open'
    }

    return 'opening'
  }

  get localAddress() {
    if (this._localAddress) return this._localAddress.address
  }

  get localFamily() {
    if (this._localAddress) return `IPv${this._localAddress.family}`
  }

  get localPort() {
    if (this._localAddress) return this._localAddress.port
  }

  get remoteAddress() {
    if (this._remoteAddress) return this._remoteAddress.address
  }

  get remoteFamily() {
    if (this._remoteAddress) return `IPv${this._remoteAddress.family}`
  }

  get remotePort() {
    if (this._remoteAddress) return this._remoteAddress.port
  }

  connect(port, host = 'localhost', opts = {}, onconnect) {
    if (this._state & constants.state.CONNECTING || this._state & constants.state.CONNECTED) {
      throw errors.SOCKET_ALREADY_CONNECTED('Socket is already connected')
    }

    this._state |= constants.state.CONNECTING

    if (typeof host === 'function') {
      onconnect = host
      host = 'localhost'
    } else if (typeof opts === 'function') {
      onconnect = opts
      opts = {}
    }

    let family = 0

    if (typeof port === 'object' && port !== null) {
      opts = port || {}
      port = opts.port || 0
      host = opts.host || 'localhost'
      family = opts.family || 0
    }

    if (!host) host = 'localhost'

    const {
      lookup = dns.lookup,
      hints,
      keepAlive = false,
      keepAliveInitialDelay = 0,
      noDelay = false,
      timeout
    } = opts

    const type = ip.isIP(host)

    if (type === 0) {
      lookup(host, { all: true, family, hints }, (err, addresses) => {
        if (this._state & constants.state.CLOSING) return

        this._state &= ~constants.state.CONNECTING

        if (err || addresses.length === 0) {
          if (!err) {
            err = new Error(`No address found for host "${host}"`)
            err.code = 'ENOTFOUND'
          }

          this.emit('lookup', err, null, 0, host)

          if (this._pendingOpen) this._continueOpen(err)
          else this.destroy(err)
          return
        }

        for (const { address, family } of addresses) {
          this.emit('lookup', null, address, family, host)
        }

        const [{ address, family }, ...rest] = addresses

        if (rest.length > 0) {
          this._addresses = rest.map(({ address, family }) => [
            port,
            address,
            { ...opts, family },
            onconnect
          ])

          this._errors = []
        }

        this.connect(port, address, { ...opts, family }, onconnect)
      })

      return this
    }

    family = type

    try {
      binding.connect(this._handle, port, host, family)

      if (keepAlive) {
        this._keepAlive = keepAlive
        this._keepAliveInitialDelay = keepAliveInitialDelay
      }
      if (noDelay) this._noDelay = noDelay
      if (timeout) this.setTimeout(timeout)

      if (onconnect) this.once('connect', onconnect)
    } catch (err) {
      queueMicrotask(() => {
        if (this._pendingOpen) this._pendingOpen(err)
        else this.destroy(err)
      })
    }

    return this
  }

  setKeepAlive(enable = false, delay = 0) {
    if (typeof enable === 'number') {
      delay = enable
      enable = false
    }

    delay = Math.floor(delay / 1000)

    if (delay === 0) enable = false

    binding.keepalive(this._handle, enable, delay)

    return this
  }

  setNoDelay(enable = true) {
    binding.nodelay(this._handle, enable)

    return this
  }

  setTimeout(ms, ontimeout) {
    if (ms === 0) {
      clearTimeout(this._timer)

      this._timer = null
    } else {
      if (ontimeout) this.once('timeout', ontimeout)

      this._timer = setTimeout(() => this.emit('timeout'), ms)
      this._timer.unref()
    }

    this._timeout = ms

    return this
  }

  ref() {
    binding.ref(this._handle)

    return this
  }

  unref() {
    binding.unref(this._handle)

    return this
  }

  _open(cb) {
    if (this._state & constants.state.CONNECTED) return cb(null)

    this._pendingOpen = cb
  }

  _read() {
    if ((this._state & constants.state.READING) === 0) {
      this._state |= constants.state.READING

      binding.resume(this._handle)
    }
  }

  _writev(batch, cb) {
    this._pendingWrite = [cb, batch]

    binding.writev(
      this._handle,
      batch.map(({ chunk }) => chunk)
    )
  }

  _final(cb) {
    this._pendingFinal = cb

    binding.end(this._handle)
  }

  _predestroy() {
    if (this._state & constants.state.CLOSING) return
    this._state |= constants.state.CLOSING

    binding.close(this._handle)
  }

  _destroy(err, cb) {
    if (this._state & constants.state.CLOSING) return cb(err)
    this._state |= constants.state.CLOSING

    this._pendingDestroy = cb

    binding.close(this._handle)
  }

  _continueOpen(err) {
    if (this._pendingOpen === null) return
    const cb = this._pendingOpen
    this._pendingOpen = null
    cb(err)
  }

  _continueWrite(err) {
    if (this._pendingWrite === null) return
    const cb = this._pendingWrite[0]
    this._pendingWrite = null
    cb(err)
  }

  _continueFinal(err) {
    if (this._pendingFinal === null) return
    const cb = this._pendingFinal
    this._pendingFinal = null
    cb(err)
  }

  _continueDestroy() {
    if (this._pendingDestroy === null) return
    const cb = this._pendingDestroy
    this._pendingDestroy = null
    cb(null)
  }

  _reset() {
    this._state = 0

    this._localAddress = null
    this._remoteAddress = null

    binding.reset(this._handle)
  }

  _onconnect(err) {
    if (err) {
      if (this._addresses !== null) {
        this._errors.push(err)

        if (this._addresses.length > 0) return this._reset()

        err = this._errors.length === 1 ? this._errors[0] : new AggregateError(this._errors)
      }

      if (this._pendingOpen) this._continueOpen(err)
      else this.destroy(err)
      return
    }

    if (this._keepAlive) this.setKeepAlive(this._keepAlive, this._keepAliveInitialDelay)
    if (this._noDelay) this.setNoDelay()

    this._localAddress = binding.address(this._handle, true)
    this._remoteAddress = binding.address(this._handle, false)

    this._state |= constants.state.CONNECTED
    this._state &= ~constants.state.CONNECTING
    this._continueOpen()

    this.emit('connect')
  }

  _onreset(err) {
    if (err) {
      this._errors.push(err)
      this.destroy(this._errors.length === 1 ? this._errors[0] : new AggregateError(this._errors))
      return
    }

    this.connect(...this._addresses.shift())
  }

  _onread(err, read) {
    if (this._timer) this._timer.refresh()

    if (err) {
      this.destroy(err)
      return
    }

    if (read === 0) {
      this.push(null)
      if (this._allowHalfOpen === false) this.end()
      return
    }

    const copy = Buffer.allocUnsafe(read)
    copy.set(this._buffer.subarray(0, read))

    if (this.push(copy) === false && this.destroying === false) {
      this._state &= ~constants.state.READING

      binding.pause(this._handle)
    }
  }

  _onwrite(err) {
    if (this._timer) this._timer.refresh()

    this._continueWrite(err)
  }

  _onfinal(err) {
    this._continueFinal(err)
  }

  _onclose() {
    clearTimeout(this._timer)

    this._continueOpen()
    this._continueDestroy()
  }
}

exports.Server = class TCPServer extends EventEmitter {
  constructor(opts = {}, onconnection) {
    if (typeof opts === 'function') {
      onconnection = opts
      opts = {}
    }

    super()

    const {
      readBufferSize = defaultReadBufferSize,
      allowHalfOpen = true,
      keepAlive = false,
      keepAliveInitialDelay = 0,
      noDelay = false,
      pauseOnConnect = false
    } = opts

    this._state = 0

    this._readBufferSize = readBufferSize
    this._allowHalfOpen = allowHalfOpen
    this._keepAlive = keepAlive
    this._keepAliveInitialDelay = keepAliveInitialDelay
    this._noDelay = noDelay
    this._pauseOnConnect = pauseOnConnect

    this._address = null
    this._connections = new Set()

    this._error = null
    this._handle = null

    if (onconnection) this.on('connection', onconnection)
  }

  get listening() {
    return (this._state & constants.state.BOUND) !== 0
  }

  get closing() {
    return (this._state & constants.state.CLOSING) !== 0
  }

  get connections() {
    return this._connections
  }

  address() {
    if ((this._state & constants.state.BOUND) === 0) return null

    const { address, family, port } = this._address

    return { address, family: `IPv${family}`, port }
  }

  listen(port = 0, host = 'localhost', backlog = 511, opts = {}, onlistening) {
    if (this._state & constants.state.BINDING || this._state & constants.state.BOUND) {
      throw errors.SERVER_ALREADY_LISTENING('Server is already listening')
    }

    if (this._state & constants.state.CLOSING) {
      throw errors.SERVER_IS_CLOSED('Server is closed')
    }

    this._state |= constants.state.BINDING

    if (typeof port === 'function') {
      onlistening = port
      port = 0
    } else if (typeof host === 'function') {
      onlistening = host
      host = 'localhost'
    } else if (typeof backlog === 'function') {
      onlistening = backlog
      backlog = 511
    } else if (typeof opts === 'function') {
      onlistening = opts
      opts = {}
    }

    let family = 0

    if (typeof port === 'object' && port !== null) {
      opts = port || {}
      port = opts.port || 0
      host = opts.host || 'localhost'
      family = opts.family || 0
      backlog = opts.backlog || 511
    }

    if (!host) host = 'localhost'
    if (!backlog) backlog = 511

    const { lookup = dns.lookup, hints } = opts

    const type = ip.isIP(host)

    if (type === 0) {
      lookup(host, { family, hints }, (err, address, family) => {
        if (this._state & constants.state.CLOSING) return

        this.emit('lookup', err, address, family, host)

        this._state &= ~constants.state.BINDING

        if (err) return this.emit('error', err)

        this.listen(port, address, backlog, { ...opts, family }, onlistening)
      })

      return this
    }

    family = type

    this._handle = binding.init(
      empty,
      this,
      this._onconnection,
      noop,
      noop,
      noop,
      noop,
      noop,
      this._onclose
    )

    if (this._state & constants.state.UNREFED) binding.unref(this._handle)

    try {
      binding.bind(this._handle, port, host, backlog, family)

      this._address = binding.address(this._handle, true)

      this._state |= constants.state.BOUND
      this._state &= ~constants.state.BINDING

      if (onlistening) this.once('listening', onlistening)

      queueMicrotask(() => this.emit('listening'))
    } catch (err) {
      this._error = err

      binding.close(this._handle)
    }

    return this
  }

  close(onclose) {
    if (onclose) this.once('close', onclose)

    if (this._state & constants.state.CLOSING) return this
    this._state |= constants.state.CLOSING

    this._closeMaybe()

    return this
  }

  ref() {
    this._state &= ~constants.state.UNREFED

    if (this._handle !== null) binding.ref(this._handle)

    return this
  }

  unref() {
    this._state |= constants.state.UNREFED

    if (this._handle !== null) binding.unref(this._handle)

    return this
  }

  _closeMaybe() {
    if (this._state & constants.state.CLOSING && this._connections.size === 0) {
      if (this._handle !== null) binding.close(this._handle)
      else queueMicrotask(() => this.emit('close'))
    }
  }

  _onconnection(err) {
    if (err) {
      this.emit('error', err)
      return
    }

    if (this._state & constants.state.CLOSING) return

    const socket = new exports.Socket({
      readBufferSize: this._readBufferSize,
      allowHalfOpen: this._allowHalfOpen,
      eagerOpen: !this._pauseOnConnect
    })

    try {
      binding.accept(this._handle, socket._handle)

      socket._localAddress = binding.address(socket._handle, true)
      socket._remoteAddress = binding.address(socket._handle, false)

      socket._state |= constants.state.CONNECTED

      this._connections.add(socket)

      if (this._keepAlive) socket.setKeepAlive(this._keepAlive, this._keepAliveInitialDelay)
      if (this._noDelay) socket.setNoDelay()

      socket.on('close', () => {
        this._connections.delete(socket)
        this._closeMaybe()
      })

      this.emit('connection', socket)
    } catch (err) {
      socket.destroy()

      this.emit('error', err)
    }
  }

  _onclose() {
    const err = this._error

    this._state &= ~constants.state.BINDING
    this._error = null
    this._handle = null
    this._address = null

    if (err) this.emit('error', err)
    else this.emit('close')
  }
}

exports.constants = constants
exports.errors = errors

exports.isIP = ip.isIP
exports.isIPv4 = ip.isIPv4
exports.isIPv6 = ip.isIPv6

exports.createConnection = function createConnection(port, host, opts, onconnect) {
  if (typeof host === 'function') {
    onconnect = host
    host = 'localhost'
  } else if (typeof opts === 'function') {
    onconnect = opts
    opts = {}
  }

  if (typeof port === 'object' && port !== null) {
    opts = port || {}
    port = opts.port || 0
    host = opts.host || 'localhost'
  }

  return new exports.Socket(opts).connect(port, host, opts, onconnect)
}

// For Node.js compatibility
exports.connect = exports.createConnection

exports.createServer = function createServer(opts, onconnection) {
  return new exports.Server(opts, onconnection)
}

function noop() {}
module.exports = {
  state: {
    CONNECTING: 0x1,
    CONNECTED: 0x2,
    BINDING: 0x4,
    BOUND: 0x8,
    READING: 0x10,
    CLOSING: 0x20,
    UNREFED: 0x40
  }
}
module.exports = class TCPError extends Error {
  constructor(msg, fn = TCPError, code = fn.name) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'TCPError'
  }

  static SOCKET_ALREADY_CONNECTED(msg) {
    return new TCPError(msg, TCPError.SOCKET_ALREADY_CONNECTED)
  }

  static SERVER_ALREADY_LISTENING(msg) {
    return new TCPError(msg, TCPError.SERVER_ALREADY_LISTENING)
  }

  static SERVER_IS_CLOSED(msg) {
    return new TCPError(msg, TCPError.SERVER_IS_CLOSED)
  }

  static INVALID_HOST(msg = 'Unrecognizable host format') {
    return new TCPError(msg, TCPError.INVALID_HOST)
  }
}
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

const v4Seg = '(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])'
const v4Str = `(${v4Seg}[.]){3}${v4Seg}`
const IPv4Pattern = new RegExp(`^${v4Str}$`)

const v6Seg = '(?:[0-9a-fA-F]{1,4})'
const IPv6Pattern = new RegExp(
  '^(' +
    `(?:${v6Seg}:){7}(?:${v6Seg}|:)|` +
    `(?:${v6Seg}:){6}(?:${v4Str}|:${v6Seg}|:)|` +
    `(?:${v6Seg}:){5}(?::${v4Str}|(:${v6Seg}){1,2}|:)|` +
    `(?:${v6Seg}:){4}(?:(:${v6Seg}){0,1}:${v4Str}|(:${v6Seg}){1,3}|:)|` +
    `(?:${v6Seg}:){3}(?:(:${v6Seg}){0,2}:${v4Str}|(:${v6Seg}){1,4}|:)|` +
    `(?:${v6Seg}:){2}(?:(:${v6Seg}){0,3}:${v4Str}|(:${v6Seg}){1,5}|:)|` +
    `(?:${v6Seg}:){1}(?:(:${v6Seg}){0,4}:${v4Str}|(:${v6Seg}){1,6}|:)|` +
    `(?::((?::${v6Seg}){0,5}:${v4Str}|(?::${v6Seg}){1,7}|:))` +
    ')(%[0-9a-zA-Z-.:]{1,})?$'
)

const isIPv4 = (exports.isIPv4 = function isIPv4(host) {
  return IPv4Pattern.test(host)
})

const isIPv6 = (exports.isIPv6 = function isIPv6(host) {
  return IPv6Pattern.test(host)
})

exports.isIP = function isIP(host) {
  if (isIPv4(host)) return 4
  if (isIPv6(host)) return 6
  return 0
}
{
  "name": "bare-tcp",
  "version": "2.2.12",
  "description": "Native TCP sockets for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./constants": "./lib/constants.js",
    "./errors": "./lib/errors.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-tcp.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-tcp/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-tcp#readme",
  "engines": {
    "bare": ">=1.16.0"
  },
  "dependencies": {
    "bare-dns": "^2.0.4",
    "bare-events": "^2.5.4",
    "bare-stream": "^2.6.4"
  },
  "devDependencies": {
    "brittle": "^3.5.0",
    "cmake-bare": "^1.1.6",
    "lunte": "^1.6.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = require.addon()
const { Readable, Writable } = require('bare-stream')
const Signal = require('bare-signals')
const binding = require('./binding')
const constants = require('./lib/constants')

const defaultReadBufferSize = 65536
const empty = Buffer.alloc(0)

exports.ReadStream = class TTYReadStream extends Readable {
  constructor(fd, opts = {}) {
    super()

    const { readBufferSize = defaultReadBufferSize, allowHalfOpen = true } = opts

    this._fd = fd
    this._state = 0
    this._allowHalfOpen = allowHalfOpen
    this._buffer = Buffer.alloc(readBufferSize)

    this._pendingDestroy = null

    this._handle = binding.init(fd, this._buffer, this, noop, this._onread, this._onclose)
  }

  get fd() {
    return this._fd
  }

  get isTTY() {
    return true
  }

  setMode(mode) {
    binding.setMode(this._handle, mode)
    return this
  }

  setRawMode(enabled) {
    return this.setMode(enabled ? constants.mode.RAW : constants.mode.NORMAL)
  }

  _read() {
    if ((this._state & constants.state.READING) === 0) {
      this._state |= constants.state.READING

      binding.resume(this._handle)
    }
  }

  _predestroy() {
    if (this._state & constants.state.CLOSING) return
    this._state |= constants.state.CLOSING

    binding.close(this._handle)
  }

  _destroy(err, cb) {
    if (this._state & constants.state.CLOSING) return cb(err)
    this._state |= constants.state.CLOSING

    this._pendingDestroy = cb

    binding.close(this._handle)
  }

  _continueDestroy() {
    if (this._pendingDestroy === null) return
    const cb = this._pendingDestroy
    this._pendingDestroy = null
    cb(null)
  }

  _onread(err, read) {
    if (err) {
      this.destroy(err)
      return
    }

    if (read === 0) {
      this.push(null)
      if (this._allowHalfOpen === false) this.end()
      return
    }

    const copy = Buffer.allocUnsafe(read)
    copy.set(this._buffer.subarray(0, read))

    if (this.push(copy) === false && this.destroying === false) {
      this._state &= ~constants.state.READING

      binding.pause(this._handle)
    }
  }

  _onclose() {
    this._handle = null

    this._continueDestroy()
  }
}

exports.WriteStream = class TTYWriteStream extends Writable {
  constructor(fd, opts = {}) {
    super()

    this._fd = fd
    this._state = 0
    this._size = null

    this._pendingWrite = null
    this._pendingDestroy = null

    this._handle = binding.init(fd, empty, this, this._onwrite, noop, this._onclose)

    this._size = this.getWindowSize()

    if (TTYWriteStream._streams.size === 0) TTYWriteStream._resize.start()

    TTYWriteStream._streams.add(this)
  }

  get fd() {
    return this._fd
  }

  get isTTY() {
    return true
  }

  get columns() {
    return this._size[0]
  }

  get rows() {
    return this._size[1]
  }

  getWindowSize() {
    return binding.getWindowSize(this._handle)
  }

  _writev(batch, cb) {
    this._pendingWrite = [cb, batch]

    binding.writev(
      this._handle,
      batch.map(({ chunk }) => chunk)
    )
  }

  _predestroy() {
    if (this._state & constants.state.CLOSING) return
    this._state |= constants.state.CLOSING

    binding.close(this._handle)

    TTYWriteStream._streams.delete(this)

    if (TTYWriteStream._streams.size === 0) TTYWriteStream._resize.stop()
  }

  _destroy(err, cb) {
    if (this._state & constants.state.CLOSING) return cb(err)
    this._state |= constants.state.CLOSING

    this._pendingDestroy = cb

    binding.close(this._handle)

    TTYWriteStream._streams.delete(this)

    if (TTYWriteStream._streams.size === 0) TTYWriteStream._resize.stop()
  }

  _continueWrite(err) {
    if (this._pendingWrite === null) return
    const cb = this._pendingWrite[0]
    this._pendingWrite = null
    cb(err)
  }

  _continueDestroy() {
    if (this._pendingDestroy === null) return
    const cb = this._pendingDestroy
    this._pendingDestroy = null
    cb(null)
  }

  _onwrite(err) {
    this._continueWrite(err)
  }

  _onclose() {
    this._handle = null

    this._continueDestroy()
  }

  _onresize() {
    this._size = this.getWindowSize()

    this.emit('resize')
  }

  static _streams = new Set()

  static _resize = new Signal('SIGWINCH')
}

exports.constants = constants

exports.isTTY = binding.isTTY

exports.isatty = exports.isTTY // For Node.js compatibility

exports.WriteStream._resize
  .on('signal', () => {
    for (const stream of exports.WriteStream._streams) {
      stream._onresize()
    }
  })
  .unref()

function noop() {}
const binding = require('../binding')

module.exports = exports = {
  mode: {
    NORMAL: binding.MODE_NORMAL,
    RAW: binding.MODE_RAW,
    IO: binding.MODE_IO || 0
  },

  state: {
    READING: 0x1,
    CLOSING: 0x2
  }
}

/** @deprecated Use `mode.NORMAL` */
exports.MODE_NORMAL = exports.mode.NORMAL
/** @deprecated Use `mode.RAW` */
exports.MODE_RAW = exports.mode.RAW
/** @deprecated Use `mode.IO` */
exports.MODE_IO = exports.mode.IO
{
  "name": "bare-tty",
  "version": "5.1.0",
  "description": "Native TTY streams for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./constants": "./lib/constants.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-tty.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-tty/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-tty#readme",
  "engines": {
    "bare": ">=1.16.0"
  },
  "dependencies": {
    "bare-events": "^2.2.0",
    "bare-signals": "^4.0.0",
    "bare-stream": "^2.0.0"
  },
  "devDependencies": {
    "brittle": "^3.2.1",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = require.addon()
const binding = require('./binding')

const t = binding.constants

class Type {
  constructor(type) {
    this._type = type
  }

  isUndefined() {
    return this._type === t.UNDEFINED
  }

  isNull() {
    return this._type === t.NULL
  }

  isBoolean() {
    return this._type === t.BOOLEAN
  }

  isNumber() {
    return (this._type & 0xff) === t.NUMBER
  }

  isInt32() {
    return (this._type & (0xff | t.INT32)) === (t.NUMBER | t.INT32)
  }

  isUint32() {
    return (this._type & (0xff | t.UINT32)) === (t.NUMBER | t.UINT32)
  }

  isString() {
    return this._type === t.STRING
  }

  isSymbol() {
    return this._type === t.SYMBOL
  }

  isObject() {
    return (this._type & 0xff) === t.OBJECT
  }

  isArray() {
    return this._type === (t.OBJECT | t.ARRAY)
  }

  isArguments() {
    return this._type === (t.OBJECT | t.ARGUMENTS)
  }

  isDate() {
    return this._type === (t.OBJECT | t.DATE)
  }

  isRegExp() {
    return this._type === (t.OBJECT | t.REGEXP)
  }

  isError() {
    return this._type === (t.OBJECT | t.ERROR)
  }

  isPromise() {
    return this._type === (t.OBJECT | t.PROMISE)
  }

  isProxy() {
    return this._type === (t.OBJECT | t.PROXY)
  }

  isGenerator() {
    return this._type === (t.OBJECT | t.GENERATOR)
  }

  isMap() {
    return this._type === (t.OBJECT | t.MAP)
  }

  isSet() {
    return this._type === (t.OBJECT | t.SET)
  }

  isWeakMap() {
    return this._type === (t.OBJECT | t.WEAK_MAP)
  }

  isWeakSet() {
    return this._type === (t.OBJECT | t.WEAK_SET)
  }

  isWeakRef() {
    return this._type === (t.OBJECT | t.WEAK_REF)
  }

  isArrayBuffer() {
    return this._type === (t.OBJECT | t.ARRAYBUFFER)
  }

  isSharedArrayBuffer() {
    return this._type === (t.OBJECT | t.SHAREDARRAYBUFFER)
  }

  isTypedArray() {
    return (this._type & 0xffff) === (t.OBJECT | t.TYPEDARRAY)
  }

  isInt8Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT8ARRAY)
  }

  isUint8Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT8ARRAY)
  }

  isUint8ClampedArray() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT8CLAMPEDARRAY)
  }

  isInt16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT16ARRAY)
  }

  isUint16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT16ARRAY)
  }

  isInt32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT32ARRAY)
  }

  isUint32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT32ARRAY)
  }

  isFloat16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT16ARRAY)
  }

  isFloat32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT32ARRAY)
  }

  isFloat64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT64ARRAY)
  }

  isBigInt64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.BIGINT64ARRAY)
  }

  isBigUint64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.BIGUINT64ARRAY)
  }

  isDataView() {
    return this._type === (t.OBJECT | t.DATAVIEW)
  }

  isModuleNamespace() {
    return this._type === (t.OBJECT | t.MODULE_NAMESPACE)
  }

  isFunction() {
    return (this._type & 0xff) === t.FUNCTION
  }

  isAsyncFunction() {
    return (
      (this._type & (0xff | t.ASYNC_FUNCTION)) ===
      (t.FUNCTION | t.ASYNC_FUNCTION)
    )
  }

  isGeneratorFunction() {
    return (
      (this._type & (0xff | t.GENERATOR_FUNCTION)) ===
      (t.FUNCTION | t.GENERATOR_FUNCTION)
    )
  }

  isExternal() {
    return this._type === t.EXTERNAL
  }

  isBigInt() {
    return this._type === t.BIGINT
  }
}

module.exports = exports = function type(value) {
  switch (typeof value) {
    case 'undefined':
      return new Type(t.UNDEFINED)
    case 'boolean':
      return new Type(t.BOOLEAN)
    case 'number':
      return new Type(
        Number.isSafeInteger(value) ? binding.type(value) : t.NUMBER
      )
    case 'string':
      return new Type(t.STRING)
    case 'symbol':
      return new Type(t.SYMBOL)
    case 'object':
      return new Type(value === null ? t.NULL : binding.type(value))
    case 'function':
      return new Type(binding.type(value))
    case 'bigint':
      return new Type(t.BIGINT)
  }
}

exports.createTag = function createTag(...components) {
  const tag = new Uint32Array(4)
  for (let i = 0; i < 4; i++) tag[i] = components[i] || 0
  return tag
}

exports.addTag = function addTag(object, tag) {
  binding.addTag(object, tag)
}

exports.checkTag = function checkTag(object, tag) {
  return binding.checkTag(object, tag)
}
{
  "name": "bare-type",
  "version": "1.1.0",
  "description": "Cross-realm type predicates for Bare",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-type.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-type/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-type#readme",
  "engines": {
    "bare": ">=1.2.0"
  },
  "devDependencies": {
    "brittle": "^3.4.0",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
module.exports = require.addon()
const path = require('bare-path')
const binding = require('./binding')
const errors = require('./lib/errors')
const URLSearchParams = require('./lib/url-search-params')

const kind = Symbol.for('bare.url.kind')

const isWindows = Bare.platform === 'win32'

class URL {
  static get [kind]() {
    return 0 // Compatibility version
  }

  constructor(input, base, opts = {}) {
    if (arguments.length === 0) throw errors.INVALID_URL()

    input = String(input)

    if (base !== undefined) base = String(base)

    this._components = new Uint32Array(8)

    this._parse(input, base, opts.throw !== false)

    if (this._href) this._params = new URLSearchParams(this.search, this)
  }

  get [kind]() {
    return URL[kind]
  }

  // https://url.spec.whatwg.org/#dom-url-href

  get href() {
    return this._href
  }

  set href(value) {
    this._update(value)

    this._params._parse(this.search)
  }

  // https://url.spec.whatwg.org/#dom-url-protocol

  get protocol() {
    return this._slice(0, this._components[0]) + ':'
  }

  set protocol(value) {
    this._update(this._replace(value.replace(/:+$/, ''), 0, this._components[0]))
  }

  // https://url.spec.whatwg.org/#dom-url-username

  get username() {
    return this._slice(this._components[0] + 3 /* :// */, this._components[1])
  }

  set username(value) {
    if (cannotHaveCredentialsOrPort(this)) {
      return
    }

    if (this.username === '') value += '@'

    this._update(this._replace(value, this._components[0] + 3 /* :// */, this._components[1]))
  }

  // https://url.spec.whatwg.org/#dom-url-password

  get password() {
    return this._href.slice(this._components[1] + 1 /* : */, this._components[2] - 1 /* @ */)
  }

  set password(value) {
    if (cannotHaveCredentialsOrPort(this)) {
      return
    }

    let start = this._components[1] + 1 /* : */
    let end = this._components[2] - 1 /* @ */

    if (this.password === '') {
      value = ':' + value
      start--
    }

    if (this.username === '') {
      value += '@'
      end++
    }

    this._update(this._replace(value, start, end))
  }

  // https://url.spec.whatwg.org/#dom-url-host

  get host() {
    return this._slice(this._components[2], this._components[5])
  }

  set host(value) {
    if (hasOpaquePath(this)) {
      return
    }

    this._update(
      this._replace(value, this._components[2], this._components[value.includes(':') ? 5 : 3])
    )
  }

  // https://url.spec.whatwg.org/#dom-url-hostname

  get hostname() {
    return this._slice(this._components[2], this._components[3])
  }

  set hostname(value) {
    if (hasOpaquePath(this)) {
      return
    }

    this._update(this._replace(value, this._components[2], this._components[3]))
  }

  // https://url.spec.whatwg.org/#dom-url-port

  get port() {
    return this._slice(this._components[3] + 1 /* : */, this._components[5])
  }

  set port(value) {
    if (cannotHaveCredentialsOrPort(this)) {
      return
    }

    let start = this._components[3] + 1 /* : */

    if (this.port === '') {
      value = ':' + value
      start--
    }

    this._update(this._replace(value, start, this._components[5]))
  }

  // https://url.spec.whatwg.org/#dom-url-pathname

  get pathname() {
    return this._slice(this._components[5], this._components[6] - 1 /* ? */)
  }

  set pathname(value) {
    if (hasOpaquePath(this)) {
      return
    }

    if (value[0] !== '/' && value[0] !== '\\') {
      value = '/' + value
    }

    this._update(this._replace(value, this._components[5], this._components[6] - 1 /* ? */))
  }

  // https://url.spec.whatwg.org/#dom-url-search

  get search() {
    return this._slice(this._components[6] - 1 /* ? */, this._components[7] - 1 /* # */)
  }

  set search(value) {
    if (value && value[0] !== '?') value = '?' + value

    this._update(
      this._replace(value, this._components[6] - 1 /* ? */, this._components[7] - 1 /* # */)
    )

    this._params._parse(this.search)
  }

  // https://url.spec.whatwg.org/#dom-url-searchparams

  get searchParams() {
    return this._params
  }

  // https://url.spec.whatwg.org/#dom-url-hash

  get hash() {
    return this._slice(this._components[7] - 1 /* # */)
  }

  set hash(value) {
    if (value && value[0] !== '#') value = '#' + value

    this._update(this._replace(value, this._components[7] - 1 /* # */))
  }

  toString() {
    return this._href
  }

  toJSON() {
    return this._href
  }

  [Symbol.for('bare.inspect')]() {
    return {
      __proto__: { constructor: URL },

      href: this.href,
      protocol: this.protocol,
      username: this.username,
      password: this.password,
      host: this.host,
      hostname: this.hostname,
      port: this.port,
      pathname: this.pathname,
      search: this.search,
      searchParams: this.searchParams,
      hash: this.hash
    }
  }

  _slice(start, end = this._href.length) {
    return this._href.slice(start, end)
  }

  _replace(replacement, start, end = this._href.length) {
    return this._slice(0, start) + replacement + this._slice(end)
  }

  _parse(input, base, shouldThrow) {
    try {
      this._href = binding.parse(
        String(input),
        base ? String(base) : null,
        this._components,
        shouldThrow
      )
    } catch (err) {
      if (err instanceof TypeError) throw err

      throw errors.INVALID_URL(`Invalid URL '${input}'`, input)
    }
  }

  _update(input) {
    try {
      this._parse(input, null, true)
    } catch (err) {
      if (err instanceof TypeError) throw err
    }
  }
}

module.exports = exports = URL

// https://url.spec.whatwg.org/#url-opaque-path
function hasOpaquePath(url) {
  return url.pathname[0] !== '/'
}

// https://url.spec.whatwg.org/#cannot-have-a-username-password-port
function cannotHaveCredentialsOrPort(url) {
  return url.hostname === '' || url.protocol === 'file:'
}

exports.URL = URL
exports.URLSearchParams = URLSearchParams

exports.errors = errors

exports.isURL = function isURL(value) {
  if (value instanceof URL) return true

  return typeof value === 'object' && value !== null && value[kind] === URL[kind]
}

exports.isURLSearchParams = URLSearchParams.isURLSearchParams

// https://url.spec.whatwg.org/#dom-url-parse
exports.parse = function parse(input, base) {
  const url = new URL(input, base, { throw: false })
  return url._href ? url : null
}

// https://url.spec.whatwg.org/#dom-url-canparse
exports.canParse = function canParse(input, base) {
  return binding.canParse(String(input), base ? String(base) : null)
}

exports.fileURLToPath = function fileURLToPath(url) {
  if (typeof url === 'string') {
    url = new URL(url)
  }

  if (url.protocol !== 'file:') {
    throw errors.INVALID_URL_SCHEME('The URL must use the file: protocol')
  }

  if (isWindows) {
    if (/%2f|%5c/i.test(url.pathname)) {
      throw errors.INVALID_FILE_URL_PATH(
        'The file: URL path must not include encoded \\ or / characters'
      )
    }
  } else {
    if (url.hostname) {
      throw errors.INVALID_FILE_URL_HOST("The file: URL host must be 'localhost' or empty")
    }

    if (/%2f/i.test(url.pathname)) {
      throw errors.INVALID_FILE_URL_PATH('The file: URL path must not include encoded / characters')
    }
  }

  const pathname = path.normalize(decodeURIComponent(url.pathname))

  if (isWindows) {
    if (url.hostname) return '\\\\' + url.hostname + pathname

    const letter = pathname.charCodeAt(1) | 0x20

    if (letter < 0x61 /* a */ || letter > 0x7a /* z */ || pathname.charCodeAt(2) !== 0x3a /* : */) {
      throw errors.INVALID_FILE_URL_PATH('The file: URL path must be absolute')
    }

    return pathname.slice(1)
  }

  return pathname
}

exports.pathToFileURL = function pathToFileURL(pathname) {
  let resolved = path.resolve(pathname)

  if (pathname[pathname.length - 1] === '/') {
    resolved += '/'
  } else if (isWindows && pathname[pathname.length - 1] === '\\') {
    resolved += '\\'
  }

  resolved = resolved
    .replaceAll('%', '%25') // Must be first
    .replaceAll('#', '%23')
    .replaceAll('?', '%3f')
    .replaceAll('\n', '%0a')
    .replaceAll('\r', '%0d')
    .replaceAll('\t', '%09')

  if (!isWindows) {
    resolved = resolved.replaceAll('\\', '%5c')
  }

  return new URL('file:' + resolved)
}

exports.format = function format(parts) {
  const { protocol, auth, host, hostname, port, pathname, search, query, hash, slashes } = parts

  let result = ''

  if (typeof protocol === 'string') {
    result += protocol

    if (protocol[protocol.length - 1] !== ':') {
      result += ':'
    }

    if (slashes === true || /https?|ftp|gopher|file/.test(protocol)) {
      result += '//'
    }
  }

  if (typeof auth === 'string') {
    if (host || hostname) result += auth + '@'
  }

  if (typeof host === 'string') result += host
  else {
    result += hostname

    if (port) result += ':' + port
  }

  if (typeof pathname === 'string' && pathname !== '') {
    if (pathname[0] !== '/') result += '/'
    result += pathname
  }

  if (typeof search === 'string') {
    if (search[0] !== '?') result += '?'
    result += search
  } else if (typeof query === 'object' && query !== null) {
    result += '?' + new URLSearchParams(query)
  }

  if (typeof hash === 'string') {
    if (hash[0] !== '#') result += '#'
    result += hash
  }

  return result
}
module.exports = class URLError extends Error {
  constructor(msg, fn = URLError, code = fn.name) {
    super(`${code}: ${msg}`)

    this.code = code

    if (Error.captureStackTrace) Error.captureStackTrace(this, fn)
  }

  get name() {
    return 'URLError'
  }

  static INVALID_URL(msg, input) {
    const err = new URLError(msg, URLError.INVALID_URL)

    err.input = input

    return err
  }

  static INVALID_URL_SCHEME(msg = 'Invalid URL') {
    return new URLError(msg, URLError.INVALID_URL_SCHEME)
  }

  static INVALID_FILE_URL_HOST(msg = 'Invalid file: URL host') {
    return new URLError(msg, URLError.INVALID_FILE_URL_HOST)
  }

  static INVALID_FILE_URL_PATH(msg = 'Invalid file: URL path') {
    return new URLError(msg, URLError.INVALID_FILE_URL_PATH)
  }
}
const kind = Symbol.for('bare.url.search-params.kind')

class URLSearchParams {
  static _urls = new WeakMap()

  static get [kind]() {
    return 0 // Compatibility version
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-urlsearchparams
  constructor(init, url = null) {
    this._params = new Map()

    if (url) URLSearchParams._urls.set(this, url)

    if (typeof init === 'string') {
      this._parse(init)
    } else if (init) {
      for (const [name, value] of typeof init[Symbol.iterator] === 'function'
        ? init
        : Object.entries(init)) {
        this.append(name, value)
      }
    }
  }

  get [kind]() {
    return URLSearchParams[kind]
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-size
  get size() {
    return this._params.length
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-append
  append(name, value = null) {
    if (value === null) return

    let list = this._params.get(name)

    if (list === undefined) {
      list = []
      this._params.set(name, list)
    }

    list.push(value)

    this._update()
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-delete
  delete(name, value = null) {
    if (value === null) this._params.delete(name)
    else {
      let list = this._params.get(name)

      if (list === undefined) return

      list = list.filter((found) => found !== value)

      if (list.length === 0) this._params.delete(name)
      else this._params.set(name, list)
    }

    this._update()
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-get
  get(name) {
    const list = this._params.get(name)

    if (list === undefined) return null

    return list[0]
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-getall
  getAll(name) {
    const list = this._params.get(name)

    if (list === undefined) return []

    return Array.from(list)
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-has
  has(name, value = null) {
    const list = this._params.get(name)

    if (list === undefined) return false

    if (value === null) return true

    return list.includes(value)
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-set
  set(name, value = null) {
    if (value === null) this._params.delete(name)
    else this._params.set(name, [value])

    this._update()
  }

  toString() {
    return this._serialize()
  }

  toJSON() {
    return [...this]
  }

  *[Symbol.iterator]() {
    for (const [name, values] of this._params) {
      for (const value of values) yield [name, value]
    }
  }

  [Symbol.for('bare.inspect')]() {
    const object = {
      __proto__: { constructor: URLSearchParams }
    }

    for (const [name, values] of this._params) {
      if (values.length === 1) object[name] = values[0]
      else object[name] = values
    }

    return object
  }

  // https://url.spec.whatwg.org/#concept-urlsearchparams-update
  _update() {
    const url = URLSearchParams._urls.get(this)

    if (url === undefined) return

    url.search = this._serialize()
  }

  // https://url.spec.whatwg.org/#concept-urlencoded-parser
  _parse(input) {
    if (input[0] === '?') input = input.substring(1)

    this._params = new Map()

    for (let sequence of input.split('&')) {
      if (sequence.length === 0) continue

      sequence = sequence.replace(/\+/g, ' ')

      let i = sequence.indexOf('=')
      if (i === -1) i = sequence.length

      const name = decodeURIComponent(sequence.substring(0, i))
      const value = decodeURIComponent(sequence.substring(i + 1, sequence.length))

      let list = this._params.get(name)

      if (list === undefined) {
        list = []
        this._params.set(name, list)
      }

      list.push(value)
    }
  }

  // https://url.spec.whatwg.org/#concept-urlencoded-serializer
  _serialize() {
    let output = ''

    for (let [name, values] of this._params) {
      name = encodeURIComponent(name)

      for (const value of values) {
        if (output) output += '&'

        output += name + '=' + encodeURIComponent(value)
      }
    }

    return output
  }
}

module.exports = exports = URLSearchParams

exports.isURLSearchParams = function isURLSearchParams(value) {
  if (value instanceof URLSearchParams) return true

  return typeof value === 'object' && value !== null && value[kind] === URLSearchParams[kind]
}
{
  "name": "bare-url",
  "version": "2.4.2",
  "description": "WHATWG URL implementation for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "global.js",
    "global.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-url.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-url/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-url",
  "dependencies": {
    "bare-path": "^3.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "cmake-bare": "^1.1.6",
    "cmake-fetch": "^1.0.0",
    "lunte": "^1.6.0",
    "prettier": "^3.3.3",
    "prettier-config-holepunch": "^2.0.0"
  }
}
const b4a = require('b4a')

function byteLength (size) {
  return Math.ceil(size / 8)
}

function get (buffer, bit) {
  const n = buffer.BYTES_PER_ELEMENT * 8

  const offset = bit & (n - 1)
  const i = (bit - offset) / n

  return (buffer[i] & (1 << offset)) !== 0
}

function set (buffer, bit, value = true) {
  const n = buffer.BYTES_PER_ELEMENT * 8

  const offset = bit & (n - 1)
  const i = (bit - offset) / n
  const mask = 1 << offset

  if (value) {
    if ((buffer[i] & mask) !== 0) return false
  } else {
    if ((buffer[i] & mask) === 0) return false
  }

  buffer[i] ^= mask
  return true
}

function setRange (buffer, start, end, value = true) {
  const n = buffer.BYTES_PER_ELEMENT * 8

  let remaining = end - start
  let offset = start & (n - 1)
  let i = (start - offset) / n

  let changed = false

  while (remaining > 0) {
    const mask = (2 ** Math.min(remaining, n - offset) - 1) << offset

    if (value) {
      if ((buffer[i] & mask) !== mask) {
        buffer[i] |= mask
        changed = true
      }
    } else {
      if ((buffer[i] & mask) !== 0) {
        buffer[i] &= ~mask
        changed = true
      }
    }

    remaining -= n - offset
    offset = 0
    i++
  }

  return changed
}

function fill (buffer, value, start = 0, end = buffer.byteLength * 8) {
  const n = buffer.BYTES_PER_ELEMENT * 8
  let i, j

  {
    const offset = start & (n - 1)
    i = (start - offset) / n

    if (offset !== 0) {
      const mask = (2 ** Math.min(n - offset, end - start) - 1) << offset

      if (value) buffer[i] |= mask
      else buffer[i] &= ~mask

      i++
    }
  }

  {
    const offset = end & (n - 1)
    j = (end - offset) / n

    if (offset !== 0 && j >= i) {
      const mask = (2 ** offset) - 1

      if (value) buffer[j] |= mask
      else buffer[j] &= ~mask
    }
  }

  return buffer.fill(value ? (2 ** n) - 1 : 0, i, j)
}

function toggle (buffer, bit) {
  const n = buffer.BYTES_PER_ELEMENT * 8

  const offset = bit & (n - 1)
  const i = (bit - offset) / n
  const mask = 1 << offset

  buffer[i] ^= mask
  return (buffer[i] & mask) !== 0
}

function remove (buffer, bit) {
  return set(buffer, bit, false)
}

function removeRange (buffer, start, end) {
  return setRange(buffer, start, end, false)
}

function indexOf (buffer, value, position = 0) {
  for (let i = position, n = buffer.byteLength * 8; i < n; i++) {
    if (get(buffer, i) === value) return i
  }

  return -1
}

function lastIndexOf (buffer, value, position = buffer.byteLength * 8 - 1) {
  for (let i = position; i >= 0; i--) {
    if (get(buffer, i) === value) return i
  }

  return -1
}

function of (...bits) {
  return from(bits)
}

function from (bits) {
  const buffer = b4a.alloc(byteLength(bits.length))
  for (let i = 0; i < bits.length; i++) set(buffer, i, bits[i])
  return buffer
}

function * iterator (buffer) {
  for (let i = 0, n = buffer.byteLength * 8; i < n; i++) yield get(buffer, i)
}

module.exports = {
  byteLength,
  get,
  set,
  setRange,
  fill,
  toggle,
  remove,
  removeRange,
  indexOf,
  lastIndexOf,
  of,
  from,
  iterator
}
{
  "name": "bits-to-bytes",
  "version": "1.3.0",
  "description": "Functions for doing bit manipulation of typed arrays",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "scripts": {
    "test": "standard && brittle test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bits-to-bytes.git"
  },
  "author": "Kasper Isager Dalsgarð <kasper@funktionel.co>",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/holepunchto/bits-to-bytes/issues"
  },
  "homepage": "https://github.com/holepunchto/bits-to-bytes#readme",
  "dependencies": {
    "b4a": "^1.5.0"
  },
  "devDependencies": {
    "brittle": "^2.3.1",
    "standard": "^17.0.0"
  }
}
const EventEmitter = require('events')
const Protomux = require('protomux')
const { Readable } = require('streamx')
const sodium = require('sodium-universal')
const b4a = require('b4a')
const c = require('compact-encoding')
const bitfield = require('compact-encoding-bitfield')
const bits = require('bits-to-bytes')
const errors = require('./lib/errors')

exports.Server = class BlindRelayServer extends EventEmitter {
  constructor(opts = {}) {
    super()

    const { createStream } = opts

    this._createStream = createStream
    this._pairing = new Map()
    this._sessions = new Set()
    this.stats = createStats(this)
  }

  get sessions() {
    return this._sessions[Symbol.iterator]()
  }

  accept(stream, opts) {
    const session = new BlindRelaySession(this, stream, opts)

    this._sessions.add(session)
    this.stats.sessions.accepted++

    return session
  }

  async close() {
    const ending = []

    for (const session of this._sessions) {
      ending.push(session.end())
    }

    await Promise.all(ending)

    this._pairing.clear()
  }

  _activePairings() {
    const active = new Set()

    for (const session of this._sessions) {
      for (const token of session._links.keys()) {
        active.add(token)
      }
    }

    return active.size
  }

  _activeStreams() {
    let active = 0

    for (const session of this._sessions) {
      active += session._links.size
    }

    return active
  }
}

class BlindRelaySession extends EventEmitter {
  constructor(server, stream, opts = {}) {
    super()

    const { id, handshake, handshakeEncoding } = opts

    this._server = server
    this._mux = Protomux.from(stream)

    this._channel = this._mux.createChannel({
      protocol: 'blind-relay',
      id,
      handshake: handshake ? handshakeEncoding || c.raw : null,
      onopen: this._onopen.bind(this),
      onclose: this._onclose.bind(this),
      ondestroy: this._ondestroy.bind(this)
    })

    this._pair = this._channel.addMessage({
      encoding: m.pair,
      onmessage: this._onpair.bind(this)
    })

    this._unpair = this._channel.addMessage({
      encoding: m.unpair,
      onmessage: this._onunpair.bind(this)
    })

    this._ending = null
    this._destroyed = false
    this._error = null
    this._pairing = new Set()
    this._links = new Map()

    this._onerror = (err) => {
      this._server.stats.streams.errors++
      this.emit('error', err)
    }

    this._channel.open(handshake)
  }

  get closed() {
    return this._channel.closed
  }

  get mux() {
    return this._mux
  }

  get stream() {
    return this._mux.stream
  }

  _onopen() {
    this._server.stats.sessions.opened++
    this.emit('open')
  }

  _onclose() {
    this._ending = Promise.resolve()

    const err = this._error || errors.CHANNEL_CLOSED()
    this._server.stats.pairings.cancelled += this._pairing.size

    for (const token of this._pairing) {
      this._server._pairing.delete(token.toString('hex'))
    }

    for (const link of this._links.values()) {
      link.destroy(err)
    }

    this._pairing.clear()
    this._links.clear()

    this._server._sessions.delete(this)
    this._server.stats.sessions.closed++

    this.emit('close')
  }

  _ondestroy() {
    this._destroyed = true
    this.emit('destroy')
  }

  _onpair({ isInitiator, token, id: remoteId }) {
    const keyString = token.toString('hex')

    let pair = this._server._pairing.get(keyString)

    if (pair === undefined) {
      pair = new BlindRelayPair(token)
      this._server._pairing.set(keyString, pair)
    } else if (pair.links[+isInitiator]) return

    this._pairing.add(keyString)
    this._server.stats.pairings.requested++

    pair.links[+isInitiator] = new BlindRelayLink(this, isInitiator, remoteId)

    if (!pair.paired) return

    this._server._pairing.delete(keyString)
    this._server.stats.pairings.matched++

    // 1st pass: Create the raw streams needed for each end of the link.
    for (const link of pair.links) {
      link.createStream()
    }

    // 2nd pass: Connect the raw streams and set up handlers.
    for (const link of pair.links) {
      link.remote = pair.remote(link.isInitiator)
      link.activate(keyString)
    }

    // 3rd pass: Let either end of the link know the streams were set up.
    for (const { isInitiator, session, remoteId, stream } of pair.links) {
      session._pair.send({
        isInitiator,
        token,
        id: stream.id,
        seq: 0
      })

      session._endMaybe()

      session.emit('pair', isInitiator, token, stream, remoteId)
    }
  }

  _onunpair({ token }) {
    const keyString = token.toString('hex')

    const pair = this._server._pairing.get(keyString)

    if (pair) {
      for (const link of pair.links) {
        if (link) link.session._pairing.delete(keyString)
      }

      this._server.stats.pairings.cancelled++
      return this._server._pairing.delete(keyString)
    }

    const link = this._links.get(keyString)

    if (link) {
      link.destroyPair(errors.PAIRING_CANCELLED())
      this._server.stats.pairings.cancelled++
    }
  }

  cork() {
    this._channel.cork()
  }

  uncork() {
    this._channel.uncork()
  }

  async end() {
    if (this._ending) return this._ending

    this._ending = EventEmitter.once(this, 'close')
    this._endMaybe()

    return this._ending
  }

  _endMaybe() {
    if (this._ending && this._pairing.size === 0) {
      this._channel.close()
    }
  }

  destroy(err) {
    if (this._destroyed) return
    this._destroyed = true

    this._error = err || errors.CHANNEL_DESTROYED()
    this._channel.close()
  }
}

class BlindRelayPair {
  constructor(token) {
    this.token = token
    this.links = [null, null]
  }

  get paired() {
    return this.links[0] !== null && this.links[1] !== null
  }

  remote(isInitiator) {
    return this.links[isInitiator ? 0 : 1]
  }
}

class BlindRelayLink {
  constructor(session, isInitiator, remoteId) {
    this.session = session
    this.isInitiator = isInitiator
    this.remoteId = remoteId
    this.stream = null
    this.remote = null
    this.keyString = null
    this._onclose = null
  }

  createStream() {
    if (this.stream) return

    this.stream = this.session._server._createStream({
      firewall: this._onfirewall.bind(this)
    })
  }

  activate(keyString) {
    const stream = this.stream

    this.keyString = keyString
    this._onclose = () => {
      if (this.stream !== stream) return

      this.stream = null
      unlink(this)
      this.session._links.delete(keyString)
      this.session._server.stats.streams.closed++
    }

    stream.on('error', this.session._onerror).on('close', this._onclose).relayTo(this.remote.stream)

    this.session._pairing.delete(keyString)
    this.session._links.set(keyString, this)
    this.session._server.stats.streams.opened++
  }

  destroy(err) {
    const stream = this.stream

    if (!stream) return

    this.stream = null

    stream.off('close', this._onclose)
    this._onclose = null

    stream.off('error', this.session._onerror)
    unlink(this)
    this.session._links.delete(this.keyString)
    this.session._server.stats.streams.closed++
    stream.on('error', noop).destroy(err)
  }

  destroyPair(err) {
    const remote = this.remote

    this.destroy(err)
    if (remote) remote.destroy(err)
  }

  _onfirewall(socket, port, host) {
    this.stream.connect(socket, this.remoteId, port, host)

    return false
  }
}

exports.Client = class BlindRelayClient extends EventEmitter {
  static _clients = new WeakMap()

  static from(stream, opts) {
    let client = this._clients.get(stream)
    if (client) return client
    client = new this(stream, opts)
    this._clients.set(stream, client)
    return client
  }

  constructor(stream, opts = {}) {
    super()

    const { id, handshake, handshakeEncoding } = opts

    this._mux = Protomux.from(stream)

    this._channel = this._mux.createChannel({
      protocol: 'blind-relay',
      id,
      handshake: handshake ? handshakeEncoding || c.raw : null,
      onopen: this._onopen.bind(this),
      onclose: this._onclose.bind(this),
      ondestroy: this._ondestroy.bind(this)
    })

    this._pair = this._channel.addMessage({
      encoding: m.pair,
      onmessage: this._onpair.bind(this)
    })

    this._unpair = this._channel.addMessage({
      encoding: m.unpair
    })

    this._ending = false
    this._destroyed = false
    this._error = null
    this._requests = new Map()

    this._channel.open(handshake)
  }

  get closed() {
    return this._channel.closed
  }

  get mux() {
    return this._mux
  }

  get stream() {
    return this._mux.stream
  }

  get requests() {
    return this._requests.values()
  }

  _onopen() {
    this.emit('open')
  }

  _onclose() {
    this._ending = Promise.resolve()

    const err = this._error || errors.CHANNEL_CLOSED()

    for (const request of this._requests.values()) {
      request.destroy(err)
    }

    this._requests.clear()

    this.constructor._clients.delete(this.stream)

    this.emit('close')
  }

  _ondestroy() {
    this._destroyed = true
    this.emit('destroy')
  }

  _onpair({ isInitiator, token, id: remoteId }) {
    const request = this._requests.get(token.toString('hex'))

    if (request === undefined || request.isInitiator !== isInitiator) return

    request.push(remoteId)
    request.push(null)

    this.emit('pair', request.isInitiator, request.token, request.stream, remoteId)
  }

  pair(isInitiator, token, stream) {
    if (this._destroyed) throw errors.CHANNEL_DESTROYED()

    const keyString = token.toString('hex')

    if (this._requests.has(keyString)) throw errors.ALREADY_PAIRING()

    const request = new BlindRelayRequest(this, isInitiator, token, stream)

    this._requests.set(keyString, request)

    return request
  }

  unpair(token) {
    if (this._destroyed) throw errors.CHANNEL_DESTROYED()

    const request = this._requests.get(token.toString('hex'))

    if (request) request.destroy(errors.PAIRING_CANCELLED())

    this._unpair.send({ token })
  }

  cork() {
    this._channel.cork()
  }

  uncork() {
    this._channel.uncork()
  }

  async end() {
    if (this._ending) return this._ending

    this._ending = EventEmitter.once(this, 'close')
    this._endMaybe()

    return this._ending
  }

  _endMaybe() {
    if (this._ending && this._requests.size === 0) {
      this._channel.close()
    }
  }

  destroy(err) {
    if (this._destroyed) return
    this._destroyed = true

    this._error = err || errors.CHANNEL_DESTROYED()
    this._channel.close()
  }
}

class BlindRelayRequest extends Readable {
  constructor(client, isInitiator, token, stream) {
    super()

    this.client = client
    this.isInitiator = isInitiator
    this.token = token
    this.stream = stream
  }

  _open(cb) {
    if (this.client._destroyed) return cb(errors.CHANNEL_DESTROYED())

    this.client._pair.send({
      isInitiator: this.isInitiator,
      token: this.token,
      id: this.stream.id,
      seq: 0
    })

    cb(null)
  }

  _destroy(cb) {
    this.client._requests.delete(this.token.toString('hex'))

    cb(null)

    this.client._endMaybe()
  }
}

exports.token = function token(buf = b4a.allocUnsafe(32)) {
  sodium.randombytes_buf(buf)
  return buf
}

function noop() {}

function unlink(link) {
  const remote = link.remote

  link.remote = null

  if (remote && remote.remote === link) {
    remote.remote = null
  }
}

function createStats(server) {
  const stats = {
    sessions: {
      accepted: 0,
      opened: 0,
      closed: 0
    },
    pairings: {
      requested: 0,
      matched: 0,
      cancelled: 0
    },
    streams: {
      opened: 0,
      closed: 0,
      errors: 0
    }
  }

  Object.defineProperties(stats.sessions, {
    active: {
      enumerable: true,
      get() {
        return server._sessions.size
      }
    }
  })

  Object.defineProperties(stats.pairings, {
    pending: {
      enumerable: true,
      get() {
        return server._pairing.size
      }
    },
    active: {
      enumerable: true,
      get() {
        return server._activePairings()
      }
    }
  })

  Object.defineProperties(stats.streams, {
    active: {
      enumerable: true,
      get() {
        return server._activeStreams()
      }
    }
  })

  return stats
}

const m = (exports.messages = {})

const flags = bitfield(7)

m.pair = {
  preencode(state, m) {
    flags.preencode(state)
    c.fixed32.preencode(state, m.token)
    c.uint.preencode(state, m.id)
    c.uint.preencode(state, m.seq)
  },
  encode(state, m) {
    flags.encode(state, bits.of(m.isInitiator))
    c.fixed32.encode(state, m.token)
    c.uint.encode(state, m.id)
    c.uint.encode(state, m.seq)
  },
  decode(state) {
    const [isInitiator] = bits.iterator(flags.decode(state))

    return {
      isInitiator,
      token: c.fixed32.decode(state),
      id: c.uint.decode(state),
      seq: c.uint.decode(state)
    }
  }
}

m.unpair = {
  preencode(state, m) {
    flags.preencode(state)
    c.fixed32.preencode(state, m.token)
  },
  encode(state, m) {
    flags.encode(state, bits.of())
    c.fixed32.encode(state, m.token)
  },
  decode(state) {
    flags.decode(state)

    return {
      token: c.fixed32.decode(state)
    }
  }
}
module.exports = class BlindRelayError extends Error {
  constructor(msg, code, fn = BlindRelayError) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'BlindRelayError'
  }

  static DUPLICATE_CHANNEL(msg = 'Duplicate channel') {
    return new BlindRelayError(msg, 'DUPLICATE_CHANNEL', BlindRelayError.DUPLICATE_CHANNEL)
  }

  static CHANNEL_CLOSED(msg = 'Channel closed') {
    return new BlindRelayError(msg, 'CHANNEL_CLOSED', BlindRelayError.CHANNEL_CLOSED)
  }

  static CHANNEL_DESTROYED(msg = 'Channel destroyed') {
    return new BlindRelayError(msg, 'CHANNEL_DESTROYED', BlindRelayError.CHANNEL_DESTROYED)
  }

  static ALREADY_PAIRING(msg = 'Already pairing') {
    return new BlindRelayError(msg, 'ALREADY_PAIRING', BlindRelayError.ALREADY_PAIRING)
  }

  static PAIRING_CANCELLED(msg = 'Pairing cancelled') {
    return new BlindRelayError(msg, 'PAIRING_CANCELLED', BlindRelayError.PAIRING_CANCELLED)
  }
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return uint24.decode(state) + 0x1000000 * uint32.decode(state)
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return uint32.decode(state) + 0x100000000 * uint32.decode(state)
  }
})

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "2.19.2",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    if (b.byteLength === 0) return null
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "blind-relay",
  "version": "1.5.0",
  "description": "Blind relay for UDX over Protomux channels",
  "main": "index.js",
  "files": [
    "index.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:bare",
    "test:bare": "brittle-bare --coverage test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/blind-relay.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/blind-relay/issues"
  },
  "homepage": "https://github.com/holepunchto/blind-relay#readme",
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "dependencies": {
    "b4a": "^1.6.4",
    "bare-events": "^2.2.0",
    "bits-to-bytes": "^1.3.0",
    "compact-encoding": "^2.12.0",
    "compact-encoding-bitfield": "^1.0.0",
    "protomux": "^3.5.1",
    "sodium-universal": "^5.0.0",
    "streamx": "^2.15.1"
  },
  "devDependencies": {
    "brittle": "^3.2.1",
    "hyperdht": "^6.6.1",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "udx-native": "^1.6.1"
  }
}
// https://ipinfo.io/bogon

const b4a = require('b4a')
const c = require('compact-encoding')
const net = require('compact-encoding-net')

module.exports = exports = function isBogon (ip) {
  return isBogonIP(ensureBuffer(ip))
}

exports.isBogon = exports

exports.isPrivate = function isPrivate (ip) {
  return isPrivateIP(ensureBuffer(ip))
}

exports.isReserved = function isReserved (ip) {
  return isReservedIP(ensureBuffer(ip))
}

function isBogonIP (ip) {
  return isPrivateIP(ip) || isReservedIP(ip)
}

function isPrivateIP (ip) {
  return ip.byteLength === 4 ? isPrivateIPv4(ip) : false // IPv6 has no private IPs
}

function isPrivateIPv4 (ip) {
  return (
    // 10.0.0.0/8  Private-use networks
    (ip[0] === 10) ||
    // 100.64.0.0/10 Carrier-grade NAT
    (ip[0] === 100 && ip[1] >= 64 && ip[1] <= 127) ||
    // 127.0.0.0/8 Loopback + Name collision occurrence (127.0.53.53)
    (ip[0] === 127) ||
    // 169.254.0.0/16  Link local
    (ip[0] === 169 && ip[1] === 254) ||
    // 172.16.0.0/12 Private-use networks
    (ip[0] === 172 && ip[1] >= 16 && ip[1] <= 31) ||
    // 192.168.0.0/16  Private-use networks
    (ip[0] === 192 && ip[1] === 168)
  )
}

function isReservedIP (ip) {
  return ip.byteLength === 4 ? isReservedIPv4(ip) : isReservedIPv6(ip)
}

function isReservedIPv4 (ip) {
  return (
    // 0.0.0.0/8 "This" network
    (ip[0] === 0) ||
    // 192.0.0.0/24  IETF protocol assignments
    (ip[0] === 192 && ip[1] === 0 && ip[2] === 0) ||
    // 192.0.2.0/24  TEST-NET-1
    (ip[0] === 192 && ip[1] === 0 && ip[2] === 2) ||
    // 198.18.0.0/15 Network interconnect device benchmark testing
    (ip[0] === 198 && ip[1] >= 18 && ip[1] <= 19) ||
    // 198.51.100.0/24 TEST-NET-2
    (ip[0] === 198 && ip[1] === 51 && ip[2] === 100) ||
    // 203.0.113.0/24  TEST-NET-3
    (ip[0] === 203 && ip[1] === 0 && ip[2] === 113) ||
    // 224.0.0.0/4 Multicast
    (ip[0] >= 224 && ip[0] <= 239) ||
    // 240.0.0.0/4 Reserved for future use
    (ip[0] >= 240) ||
    // 255.255.255.255/32
    (ip[0] === 255 && ip[1] === 255 && ip[2] === 255 && ip[3] === 255)
  )
}

function isReservedIPv6 (ip) {
  return (
    // ::/128 Node-scope unicast unspecified address
    // ::1/128 Node-scope unicast loopback address
    (
      ip[0] === 0 && ip[1] === 0 && ip[2] === 0 && ip[3] === 0 && ip[4] === 0 &&
      ip[5] === 0 && ip[6] === 0 && ip[7] === 0 && ip[8] === 0 && ip[9] === 0 &&
      ip[10] === 0 && ip[11] === 0 && ip[12] === 0 && ip[13] === 0 && ip[14] === 0 &&
      ip[15] <= 1
    ) ||
    // ::ffff:0:0/96 IPv4-mapped addresses
    // ::/96 IPv4-compatible addresses
    (
      ip[0] === 0 && ip[1] === 0 && ip[2] === 0 && ip[3] === 0 && ip[4] === 0 &&
      ip[5] === 0 && ip[6] === 0 && ip[7] === 0 && ip[8] === 0 && ip[9] === 0 &&
      (ip[10] === 0 || ip[10] === 0xff) &&
      (ip[11] === 0 || ip[11] === 0xff)
    ) ||
    // 100::/64 Remotely triggered black hole addresses
    (ip[0] === 0x01 && ip[1] === 0 && ip[2] === 0 && ip[3] === 0 && ip[4] === 0 && ip[5] === 0 && ip[6] === 0 && ip[7] === 0) ||
    // 2001:10::/28 Overlay routable cryptographic hash identifiers (ORCHID)
    (ip[0] === 0x20 && ip[1] === 0x01 && ip[2] === 0 && ip[3] >= 0x10 && ip[3] <= 0x1f) ||
    // 2001:20::/28 Overlay routable cryptographic hash identifiers version 2 (ORCHIDv2)
    (ip[0] === 0x20 && ip[1] === 0x01 && ip[2] === 0 && ip[3] >= 0x20 && ip[3] <= 0x2f) ||
    // 2001:db8::/32 Documentation prefix
    (ip[0] === 0x20 && ip[1] === 0x01 && ip[2] === 0x0d && ip[3] === 0xb8) ||
    // fc00::/7 Unique local addresses (ULA)
    (ip[0] >= 0xfc && ip[0] <= 0xfd) ||
    // fe80::/10 Link-local unicast
    (ip[0] === 0xfe && ip[1] >= 0x80 && ip[1] <= 0xbf) ||
    // ff00::/8 Multicast
    (ip[0] === 0xff)
  )
}

const state = c.state(0, 0, b4a.allocUnsafe(1 /* family */ + 16))

function ensureBuffer (ip) {
  if (b4a.isBuffer(ip)) return ip

  net.ip.preencode(state, ip)
  net.ip.encode(state, ip)

  const buffer = state.buffer.subarray(1 /* family */, state.end)

  state.start = 0
  state.end = 0

  return buffer
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return uint24.decode(state) + 0x1000000 * uint32.decode(state)
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return uint32.decode(state) + 0x100000000 * uint32.decode(state)
  }
})

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "2.19.2",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    if (b.byteLength === 0) return null
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "bogon",
  "version": "1.2.0",
  "description": "Check if an IP is a bogon",
  "main": "index.js",
  "scripts": {
    "test": "standard && brittle test.mjs"
  },
  "dependencies": {
    "compact-encoding": "^2.11.0",
    "compact-encoding-net": "^1.2.0"
  },
  "devDependencies": {
    "brittle": "^3.0.4",
    "nanobench": "^2.1.1",
    "standard": "^17.0.0"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/bogon.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/bogon/issues"
  },
  "homepage": "https://github.com/mafintosh/bogon"
}
const c = require('compact-encoding')

module.exports = function bitfield (length) {
  if (length > 64) throw new RangeError('Bitfield cannot be larger than 64 bits')

  let byteLength
  if (length < 8) byteLength = 1
  else if (length <= 16) byteLength = 2
  else if (length <= 32) byteLength = 4
  else byteLength = 8

  return {
    preencode (state) {
      state.end++ // Length byte, used for data when byteLength === 1

      if (byteLength === 1) ;
      else if (byteLength === 2) c.uint16.preencode(state)
      else if (byteLength === 4) c.uint32.preencode(state)
      else c.uint64.preencode(state)
    },

    encode (state, b) {
      if (byteLength === 1) ;
      else if (byteLength === 2) c.uint8.encode(state, 0xfd)
      else if (byteLength === 4) c.uint8.encode(state, 0xfe)
      else c.uint8.encode(state, 0xff)

      if (typeof b === 'number') {
        if (byteLength === 1) c.uint8.encode(state, b)
        else if (byteLength === 2) c.uint16.encode(state, b)
        else if (byteLength === 4) c.uint32.encode(state, b)
        else c.uint64.encode(state, b)
      } else {
        state.buffer.set(b, state.start)

        if (b.byteLength < byteLength) {
          // Zero-fill the rest of the byte length.
          state.buffer.fill(
            0,
            state.start + b.byteLength,
            state.start + byteLength
          )
        }

        state.start += byteLength
      }
    },

    decode (state) {
      const byte = state.buffer[state.start]

      let byteLength
      if (byte <= 0xfc) byteLength = 1
      else if (byte === 0xfd) byteLength = 2
      else if (byte === 0xfe) byteLength = 4
      else byteLength = 8

      if (byteLength > 1) state.start++ // Skip the length byte

      if (state.end - state.start < byteLength) throw new Error('Out of bounds')

      const b = state.buffer.subarray(state.start, (state.start += byteLength))

      return length <= 8 ? b.subarray(0, 1) : b
    }
  }
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return uint24.decode(state) + 0x1000000 * uint32.decode(state)
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return uint32.decode(state) + 0x100000000 * uint32.decode(state)
  }
})

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "2.19.2",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    if (b.byteLength === 0) return null
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "compact-encoding-bitfield",
  "version": "1.0.0",
  "description": "Compact codec for bitfields",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "scripts": {
    "test": "standard && brittle test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/compact-encoding/compact-encoding-bitfield.git"
  },
  "author": "Kasper Isager Dalsgarð <kasper@funktionel.co>",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/compact-encoding/compact-encoding-bitfield/issues"
  },
  "homepage": "https://github.com/compact-encoding/compact-encoding-bitfield#readme",
  "dependencies": {
    "compact-encoding": "^2.4.1"
  },
  "devDependencies": {
    "brittle": "^1.3.5",
    "standard": "^16.0.3"
  },
  "standard": {
    "ignore": [
      "__snapshots__/**"
    ]
  }
}
const c = require('compact-encoding')

const port = c.uint16

const address = (host, family) => {
  return {
    preencode (state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode (state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode (state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = {
  preencode (state) {
    state.end += 4
  },
  encode (state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (i < string.length && (c = string.charCodeAt(i++)) !== /* . */ 0x2e) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode (state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] + '.' +
      state.buffer[state.start++] + '.' +
      state.buffer[state.start++] + '.' +
      state.buffer[state.start++]
    )
  }
}

const ipv4Address = address(ipv4, 4)

const ipv6 = {
  preencode (state) {
    state.end += 16
  },
  encode (state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (i < string.length && (c = string.charCodeAt(i++)) !== /* : */ 0x3a) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode (state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (state.buffer[state.start++] * 256 + state.buffer[state.start++]).toString(16) + ':' +
      (state.buffer[state.start++] * 256 + state.buffer[state.start++]).toString(16) + ':' +
      (state.buffer[state.start++] * 256 + state.buffer[state.start++]).toString(16) + ':' +
      (state.buffer[state.start++] * 256 + state.buffer[state.start++]).toString(16) + ':' +
      (state.buffer[state.start++] * 256 + state.buffer[state.start++]).toString(16) + ':' +
      (state.buffer[state.start++] * 256 + state.buffer[state.start++]).toString(16) + ':' +
      (state.buffer[state.start++] * 256 + state.buffer[state.start++]).toString(16) + ':' +
      (state.buffer[state.start++] * 256 + state.buffer[state.start++]).toString(16)
    )
  }
}

const ipv6Address = address(ipv6, 6)

const ip = {
  preencode (state, string) {
    const family = string.includes(':') ? 6 : 4
    c.uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode (state, string) {
    const family = string.includes(':') ? 6 : 4
    c.uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode (state) {
    const family = c.uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
}

const ipAddress = {
  preencode (state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode (state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode (state) {
    const family = c.uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

module.exports = {
  port,
  ipv4,
  ipv4Address,
  ipv6,
  ipv6Address,
  ip,
  ipAddress
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return uint24.decode(state) + 0x1000000 * uint32.decode(state)
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return uint32.decode(state) + 0x100000000 * uint32.decode(state)
  }
})

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "2.19.2",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    if (b.byteLength === 0) return null
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "compact-encoding-net",
  "version": "1.2.0",
  "description": "Compact codecs for net types",
  "main": "index.js",
  "scripts": {
    "test": "standard && brittle test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/compact-encoding/compact-encoding-net.git"
  },
  "author": "Kasper Isager Dalsgarð <kasper@funktionel.co>",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/compact-encoding/compact-encoding-net/issues"
  },
  "homepage": "https://github.com/compact-encoding/compact-encoding-net#readme",
  "dependencies": {
    "compact-encoding": "^2.4.1"
  },
  "devDependencies": {
    "brittle": "^1.3.5",
    "nanobench": "^2.1.1",
    "standard": "^16.0.3"
  }
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return uint24.decode(state) + 0x1000000 * uint32.decode(state)
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return uint32.decode(state) + 0x100000000 * uint32.decode(state)
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return 0x100000000 * uint32be.decode(state) + uint32be.decode(state)
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.2.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
const { EventEmitter } = require('events')
const Table = require('kademlia-routing-table')
const TOS = require('time-ordered-set')
const UDX = require('udx-native')
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const NatSampler = require('nat-sampler')
const b4a = require('b4a')
const NetworkHealth = require('./lib/health')
const IO = require('./lib/io')
const Query = require('./lib/query')
const Session = require('./lib/session')
const peer = require('./lib/peer')
const { UNKNOWN_COMMAND, INVALID_TOKEN } = require('./lib/errors')
const { PING, PING_NAT, FIND_NODE, DOWN_HINT, DELAYED_PING } = require('./lib/commands')

const TMP = b4a.allocUnsafe(32)
const TICK_INTERVAL = 5000
const SLEEPING_INTERVAL = 3 * TICK_INTERVAL
const STABLE_TICKS = 240 // if nothing major bad happens in ~20mins we can consider this node stable (if nat is friendly)
const MORE_STABLE_TICKS = 3 * STABLE_TICKS
const REFRESH_TICKS = 60 // refresh every ~5min when idle
const RECENT_NODE = 12 // we've heard from a node less than 1min ago
const OLD_NODE = 360 // if an node has been around more than 30 min we consider it old

const DEFAULTS = {
  concurrency: 10,
  maxWindow: IO.DEFAULT_MAX_WINDOW,
  maxPingDelay: 10_000
}

class DHT extends EventEmitter {
  constructor(opts = {}) {
    super()

    this.bootstrapNodes = opts.bootstrap === false ? [] : (opts.bootstrap || []).map(parseNode)
    this.table = new Table(randomBytes(32))
    this.nodes = new TOS()
    this.udx = opts.udx || new UDX()
    this.io = new IO(this.table, this.udx, {
      ...opts,
      onrequest: this._onrequest.bind(this),
      onresponse: this._onresponse.bind(this),
      ontimeout: this._ontimeout.bind(this)
    })
    this.health = new NetworkHealth(this)

    this.concurrency = opts.concurrency || DEFAULTS.concurrency
    this.maxPingDelay = opts.maxPingDelay || DEFAULTS.maxPingDelay
    this.bootstrapped = false
    this.ephemeral = true
    this.firewalled = this.io.firewalled
    this.adaptive = typeof opts.ephemeral !== 'boolean' && opts.adaptive !== false
    this.destroyed = false
    this.suspended = false
    this.online = true
    this.degraded = false
    this.stats = {
      queries: { active: 0, total: 0 },
      requests: this.io.stats.requests,
      commands: {
        ping: this.io.stats.commands[PING],
        pingNat: this.io.stats.commands[PING_NAT],
        findNode: this.io.stats.commands[FIND_NODE],
        downHint: this.io.stats.commands[DOWN_HINT]
      }
    }

    this._nat = new NatSampler()
    this._quickFirewall = opts.quickFirewall !== false
    this._forcePersistent = opts.ephemeral === false
    this._repinging = 0
    this._checks = 0
    this._tick = randomOffset(100) // make sure to random offset all the network ticks
    this._refreshTicks = randomOffset(REFRESH_TICKS)
    this._stableTicks = this.adaptive ? STABLE_TICKS : 0
    this._tickInterval = setInterval(this._ontick.bind(this), TICK_INTERVAL)
    this._lastTick = Date.now()
    this._lastHost = null
    this._filterNode = opts.filterNode || opts.addNode || null // opts.addNode is deprecating, use opts.filterNode instead
    this._onrow = (row) => row.on('full', (node) => this._onfullrow(node, row))
    this._nonePersistentSamples = []
    this._bootstrapping = this._bootstrap()
    this._bootstrapping.catch(noop)
    this._sendDownHints = opts.sendDownHints !== false
    this._downHintsRateLimit =
      opts.downHintsRateLimit !== undefined ? opts.downHintsRateLimit : 10 * 5
    this._downHintsSentPerTick = 0
    this._pendingTimers = new Set()

    this.table.on('row', this._onrow)

    this.io.networkInterfaces.on('change', (interfaces) => this._onnetworkchange(interfaces))

    if (opts.nodes) {
      for (let i = opts.nodes.length - 1; i >= 0; i--) {
        this.addNode(opts.nodes[i])
      }
    }
  }

  static DEFAULTS = DEFAULTS

  static bootstrapper(port, host, opts) {
    if (!port) throw new Error('Port is required')
    if (!host) throw new Error('Host is required')
    if (host === '0.0.0.0' || host === '::') throw new Error('Invalid host')
    if (!UDX.isIPv4(host)) throw new Error('Host must be a IPv4 address')

    const dht = new this({
      port,
      ephemeral: false,
      firewalled: false,
      anyPort: false,
      bootstrap: [],
      ...opts
    })
    dht._nat.add(host, port)
    return dht
  }

  get id() {
    return this.ephemeral ? null : this.table.id
  }

  get host() {
    return this._nat.host
  }

  get port() {
    return this._nat.port
  }

  get randomized() {
    return this._nat.host !== null && this._nat.port === 0
  }

  get socket() {
    return this.firewalled ? this.io.clientSocket : this.io.serverSocket
  }

  get config() {
    return {
      concurrency: this.concurrency,
      maxWindow: this.io.congestion._maxWindow,
      randomPunchInterval: this._randomPunchInterval,
      connectionKeepAlive: this.connectionKeepAlive,
      sendDownHints: this._sendDownHints,
      downHintsRateLimit: this._downHintsRateLimit
    }
  }

  onmessage(socket, buf, rinfo) {
    if (buf.byteLength > 1) this.io.onmessage(socket, buf, rinfo)
  }

  bind() {
    return this.io.bind()
  }

  async suspend({ log = noop } = {}) {
    log('Suspending waiting for io bind...')
    await this.io.bind()
    log('Done, continuing')
    if (this.suspended || this.destroyed) return
    this.suspended = true
    clearInterval(this._tickInterval)
    log('Done, suspending io')
    await this.io.suspend({ log })
    log('Done, dht suspended')
    this.emit('suspend')
  }

  async resume({ log = noop } = {}) {
    if (!this.suspended || this.destroyed) return
    this.suspended = false
    this._tickInterval = setInterval(this._ontick.bind(this), TICK_INTERVAL)
    this._onwakeup()
    log('Resuming io')
    await this.io.resume()
    log('Done, dht resumed')
    this.io.networkInterfaces.on('change', (interfaces) => this._onnetworkchange(interfaces))
    this.refresh()
    this.emit('resume')
  }

  address() {
    const socket = this.socket
    return socket ? socket.address() : null
  }

  localAddress() {
    if (!this.io.serverSocket) return null

    return {
      host: localIP(this.udx),
      port: this.io.serverSocket.address().port
    }
  }

  remoteAddress() {
    if (!this.host) return null
    if (!this.port) return null
    if (this.firewalled) return null
    if (!this.io.serverSocket) return null

    const port = this.io.serverSocket.address().port
    if (port !== this.port) return null

    return {
      host: this.host,
      port
    }
  }

  addNode({ host, port }) {
    this._addNode({
      id: peer.id(host, port),
      port,
      host,
      token: null,
      to: null,
      sampled: 0,
      added: this._tick,
      pinged: 0,
      seen: 0,
      downHints: 0,
      prev: null,
      next: null
    })
  }

  toArray(opts) {
    const limit = opts && opts.limit
    if (limit === 0) return []
    return this.nodes.toArray({ limit, reverse: true }).map(({ host, port }) => ({ host, port }))
  }

  async fullyBootstrapped() {
    return this._bootstrapping
  }

  ready() {
    // Deprecating, use fullyBootstrapped instead (removed on next major)
    return this.fullyBootstrapped()
  }

  findNode(target, opts) {
    if (this.destroyed) throw new Error('Node destroyed')
    this._refreshTicks = REFRESH_TICKS
    return new Query(this, target, true, FIND_NODE, null, opts)
  }

  query({ target, command, value }, opts) {
    if (this.destroyed) throw new Error('Node destroyed')
    this._refreshTicks = REFRESH_TICKS
    return new Query(this, target, false, command, value || null, opts)
  }

  ping({ host, port }, opts) {
    let value = null

    if (opts && opts.size && opts.size > 0) value = b4a.alloc(opts.size)

    const req = this.io.createRequest(
      { id: null, host, port },
      null,
      true,
      PING,
      null,
      value,
      (opts && opts.session) || null,
      opts && opts.ttl
    )
    return this._requestToPromise(req, opts)
  }

  delayedPing({ host, port }, delayMs, opts) {
    if (delayMs > this.maxPingDelay) {
      throw new Error(`Delay exceeds max delay: ${this.maxPingDelay}ms`)
    }

    const value = b4a.allocUnsafe(4)
    c.uint32.encode({ start: 0, end: 4, buffer: value }, delayMs)

    const req = this.io.createRequest(
      { id: null, host, port },
      null,
      true,
      DELAYED_PING,
      null,
      value,
      (opts && opts.session) || null,
      opts && opts.ttl
    )
    // add 1 second to the timeout to account for network overhead
    req.timeout = delayMs + 1_000
    return this._requestToPromise(req, opts)
  }

  async rttStats() {
    const stats = {
      successes: 0,
      errors: 0,
      responses: {
        avgRtt: 0,
        errors: 0,
        avgCloserNodes: 0
      },
      closestReplies: {
        avgRtt: 0,
        errors: 0,
        avgCloserNodes: 0
      }
    }

    if (this.nodes.latest) {
      const q = this.findNode(this.nodes.latest.id)

      let responseCount = 0
      let closestCount = 0

      for await (const msg of q) {
        stats.responses.avgRtt += msg.rtt
        stats.responses.errors += msg.error
        stats.responses.avgCloserNodes += msg.closerNodes?.length || 0
        responseCount++
      }
      stats.responses.avgRtt /= responseCount
      stats.responses.avgCloserNodes /= responseCount

      for await (const msg of q.closestReplies) {
        stats.closestReplies.avgRtt += msg.rtt
        stats.closestReplies.errors += msg.error
        stats.closestReplies.avgCloserNodes += msg.closerNodes?.length || 0
        closestCount++
      }
      stats.closestReplies.avgRtt /= closestCount
      stats.closestReplies.avgCloserNodes /= closestCount

      stats.successes = q.successes
      stats.errors = q.errors
    }

    return stats
  }

  request({ token = null, command, target = null, value = null }, { host, port }, opts) {
    const req = this.io.createRequest(
      { id: null, host, port },
      token,
      false,
      command,
      target,
      value,
      (opts && opts.session) || null,
      opts && opts.ttl
    )
    return this._requestToPromise(req, opts)
  }

  session() {
    return new Session(this)
  }

  _requestToPromise(req, opts) {
    if (req === null) return Promise.reject(new Error('Node destroyed'))

    if (opts && opts.socket) req.socket = opts.socket
    if (opts && opts.retry === false) req.retries = 0

    return new Promise((resolve, reject) => {
      req.onresponse = resolve
      req.onerror = reject
      req.send()
    })
  }

  async _bootstrap() {
    const self = this

    await Promise.resolve() // wait a tick, so apis can be used from the outside
    await this.io.bind()

    this.emit('listening')

    // TODO: some papers describe more advanced ways of bootstrapping - we should prob look into that

    let first = this.firewalled && this._quickFirewall && !this._forcePersistent
    let testNat = false

    const onlyFirewall = !this._forcePersistent

    for (let i = 0; i < 2; i++) {
      await this._backgroundQuery(this.table.id).on('data', ondata).finished()

      if (this.bootstrapped || (!testNat && !this._forcePersistent)) break
      if (!(await this._updateNetworkState(onlyFirewall))) break
    }

    if (this.bootstrapped) return
    this.bootstrapped = true

    this.emit('ready')

    function ondata(data) {
      // Simple QUICK nat heuristic.
      // If we get ONE positive nat ping before the bootstrap query finishes
      // then we always to a nat test, no matter if we are adaptive...
      // This should be expanded in the future to try more than one node etc, not always hit the first etc
      // If this fails, then nbd, as the onstable hook will pick it up later.

      if (!first) return
      first = false

      const value = b4a.allocUnsafe(2)
      c.uint16.encode({ start: 0, end: 2, buffer: value }, self.io.serverSocket.address().port)

      self._request(
        data.from,
        false,
        true,
        PING_NAT,
        null,
        value,
        null,
        () => {
          testNat = true
        },
        noop
      )
    }
  }

  refresh() {
    const node = this.table.random()
    this._backgroundQuery(node ? node.id : this.table.id).on('error', noop)
  }

  async destroy() {
    const emitClose = !this.destroyed
    this.destroyed = true
    clearInterval(this._tickInterval)
    for (const timer of this._pendingTimers) {
      clearTimeout(timer)
    }
    await this.io.destroy()
    if (emitClose) this.emit('close')
  }

  _request(to, force, internal, command, target, value, session, onresponse, onerror) {
    if (internal && !this._sendDownHints && command === DOWN_HINT) return null
    const req = this.io.createRequest(to, null, internal, command, target, value, session)
    if (req === null) return null

    req.onresponse = onresponse
    req.onerror = onerror
    req.send(force)

    return req
  }

  _natAdd(host, port) {
    const prevHost = this._nat.host
    const prevPort = this._nat.port

    this._nat.add(host, port)

    if (prevHost === this._nat.host && prevPort === this._nat.port) return

    this.emit('nat-update', this._nat.host, this._nat.port)
  }

  // we don't check that this is a bootstrap node but we limit the sample size to very few nodes, so fine
  _sampleBootstrapMaybe(from, to) {
    if (this._nonePersistentSamples.length >= Math.max(1, this.bootstrapNodes.length)) return
    const id = from.host + ':' + from.port
    if (this._nonePersistentSamples.indexOf(id) > -1) return
    this._nonePersistentSamples.push(id)
    this._natAdd(to.host, to.port)
  }

  _addNodeFromNetwork(sample, from, to) {
    if (this._filterNode !== null && !this._filterNode(from)) {
      return
    }

    if (from.id === null) {
      this._sampleBootstrapMaybe(from, to)
      return
    }

    const oldNode = this.table.get(from.id)

    // refresh it, if we've seen this before
    if (oldNode) {
      if (sample && (oldNode.sampled === 0 || this._tick - oldNode.sampled >= OLD_NODE)) {
        oldNode.to = to
        oldNode.sampled = this._tick
        this._natAdd(to.host, to.port)
      }

      oldNode.pinged = oldNode.seen = this._tick
      this.nodes.add(oldNode)
      return
    }

    this._addNode({
      id: from.id,
      port: from.port,
      host: from.host,
      to,
      sampled: 0,
      added: this._tick,
      pinged: this._tick, // last time we interacted with them
      seen: this._tick, // last time we heard from them
      downHints: 0,
      prev: null,
      next: null
    })
  }

  _addNode(node) {
    if (this.nodes.has(node) || b4a.equals(node.id, this.table.id)) return

    node.added = node.pinged = node.seen = this._tick

    if (!this.table.add(node)) return
    this.nodes.add(node)

    if (node.to && node.sampled === 0) {
      node.sampled = this._tick
      this._natAdd(node.to.host, node.to.port)
    }

    this.emit('add-node', node)
  }

  _removeStaleNode(node, lastSeen) {
    if (node.seen <= lastSeen) this._removeNode(node)
  }

  _removeNode(node) {
    if (!this.nodes.has(node)) return

    this.table.remove(node.id)
    this.nodes.remove(node)

    this.emit('remove-node', node)
  }

  _onwakeup() {
    this._tick += 2 * OLD_NODE // bump the tick enough that everything appears old.
    this._tick += 8 - (this._tick & 7) - 2 // triggers a series of pings in two ticks
    this._stableTicks = MORE_STABLE_TICKS
    this._refreshTicks = 1 // triggers a refresh next tick (allow network time to wake up also)
    this._lastHost = null // clear network cache check
    this.health.reset()

    if (this.adaptive) {
      // TODO: re-enable this as soon as we find out why this is over triggering in some edge cases
      // this.firewalled = true
      // this.io.firewalled = true

      if (!this.ephemeral) {
        this.ephemeral = true
        this.io.ephemeral = true
        this.emit('ephemeral')
      }
    }

    this.emit('wakeup')
  }

  _onfullrow(newNode, row) {
    if (!this.bootstrapped || this._repinging >= 3) return

    let oldest = null
    for (const node of row.nodes) {
      if (node.pinged === this._tick) continue
      if (
        oldest === null ||
        oldest.pinged > node.pinged ||
        (oldest.pinged === node.pinged && oldest.added > node.added)
      ) {
        oldest = node
      }
    }

    if (oldest === null) return
    if (this._tick - oldest.pinged < RECENT_NODE && this._tick - oldest.added > OLD_NODE) return

    this._repingAndSwap(newNode, oldest)
  }

  _onnetworkchange(interfaces) {
    this.emit('network-change', interfaces)
    this.emit('network-update')
  }

  _repingAndSwap(newNode, oldNode) {
    const self = this
    const lastSeen = oldNode.seen

    oldNode.pinged = this._tick

    this._repinging++
    this._request(
      { id: null, host: oldNode.host, port: oldNode.port },
      false,
      true,
      PING,
      null,
      null,
      null,
      onsuccess,
      onswap
    )

    function onsuccess(m) {
      if (oldNode.seen <= lastSeen) return onswap()
      self._repinging--
    }

    function onswap(e) {
      self._repinging--
      self._removeNode(oldNode)
      self._addNode(newNode)
    }
  }

  _onrequest(req, external) {
    if (req.from.id !== null) {
      this._addNodeFromNetwork(!external, req.from, req.to)
    }

    if (req.internal) {
      switch (req.command) {
        // standard keep alive call
        case PING: {
          req.sendReply(0, null, false, false)
          return
        }
        case DELAYED_PING: {
          this._ondelayedping(req)
          return
        }
        // check if the other side can receive a message to their other socket
        case PING_NAT: {
          if (req.value === null || req.value.byteLength < 2) return
          const port = c.uint16.decode({ start: 0, end: 2, buffer: req.value })
          if (port === 0) return
          req.from.port = port
          req.sendReply(0, null, false, false)
          return
        }
        // empty dht reply back
        case FIND_NODE: {
          if (!req.target) return
          req.sendReply(0, null, false, true)
          return
        }
        // "this is node you sent me is down" - let's try to ping it
        case DOWN_HINT: {
          if (req.value === null || req.value.byteLength < 6) return
          if (this._checks < 10) {
            sodium.crypto_generichash(TMP, req.value.subarray(0, 6))
            const node = this.table.get(TMP)
            if (node && (node.pinged < this._tick || node.downHints === 0)) {
              node.downHints++
              this._check(node)
            }
          }
          req.sendReply(0, null, false, false)
          return
        }
      }

      req.sendReply(UNKNOWN_COMMAND, null, false, req.target !== null)
      return
    }

    // ask the user to handle it or reply back with a bad command
    if (this.onrequest(req) === false) {
      req.sendReply(UNKNOWN_COMMAND, null, false, req.target !== null)
    }
  }

  onrequest(req) {
    return this.emit('request', req)
  }

  _ondelayedping(req) {
    if (req.value === null || req.value.byteLength < 4) return
    const delayMs = c.uint32.decode({ start: 0, end: 4, buffer: req.value })
    if (delayMs > this.maxPingDelay) return
    const timer = setTimeout(() => {
      if (this.destroyed) return
      this._pendingTimers.delete(timer)
      req.sendReply(0, null, false, false)
    }, delayMs)
    this._pendingTimers.add(timer)
  }

  _onresponse(res, external) {
    this._addNodeFromNetwork(!external, res.from, res.to)
  }

  _ontimeout(req) {
    if (!req.to.id) return
    const node = this.table.get(req.to.id)
    if (node) this._removeNode(node)
  }

  _pingSome() {
    let cnt = this.io.inflight.length > 2 ? 3 : 5
    let oldest = this.nodes.oldest

    // tiny dht, pinged the bootstrap again
    if (!oldest) {
      this.refresh()
      return
    }

    // we've recently pinged the oldest one, so only trigger a couple of repings
    if (this._tick - oldest.pinged < RECENT_NODE) {
      cnt = 2
    }

    while (cnt--) {
      if (!oldest || this._tick === oldest.pinged) continue
      this._check(oldest)
      oldest = oldest.next
    }
  }

  _check(node) {
    node.pinged = this._tick

    const lastSeen = node.seen
    const onresponse = () => {
      this._checks--
      this._removeStaleNode(node, lastSeen)
    }
    const onerror = () => {
      this._checks--
      this._removeNode(node)
    }

    this._checks++
    this._request(
      { id: null, host: node.host, port: node.port },
      false,
      true,
      PING,
      null,
      null,
      null,
      onresponse,
      onerror
    )
  }

  _ontick() {
    const time = Date.now()

    if (time - this._lastTick > SLEEPING_INTERVAL && this.suspended === false) {
      this._onwakeup()
    } else {
      this._tick++
    }

    this._lastTick = time

    if (!this.bootstrapped || this.suspended) return

    if (this.adaptive && this.ephemeral && --this._stableTicks <= 0) {
      if (this._lastHost === this._nat.host) {
        // do not recheck the same network...
        this._stableTicks = MORE_STABLE_TICKS
      } else {
        this._updateNetworkState() // the promise returned here never fails so just ignore it
      }
    }

    if ((this._tick & 7) === 0) {
      this._pingSome()
    }

    if (
      ((this._tick & 63) === 0 && this.nodes.length < this.table.k) ||
      --this._refreshTicks <= 0
    ) {
      this.refresh()
    }

    this._downHintsSentPerTick = 0
    this.health.update()
  }

  async _updateNetworkState(onlyFirewall = false) {
    if (!this.ephemeral) return false
    if (onlyFirewall && !this.firewalled) return false

    const { host, port } = this._nat

    if (!onlyFirewall) {
      // remember what host we checked and reset the counter
      this._stableTicks = MORE_STABLE_TICKS
      this._lastHost = host
    }

    // check if we have a consistent host and port
    if (host === null || port === 0) {
      return false
    }

    const natSampler = this.firewalled ? new NatSampler() : this._nat

    // ask remote nodes to ping us on our server socket to see if we have the port open
    const firewalled = this.firewalled && (await this._checkIfFirewalled(natSampler))
    if (firewalled) return false

    this.firewalled = this.io.firewalled = false

    // incase it's called in parallel for some reason, or if our nat status somehow changed
    if (!this.ephemeral || host !== this._nat.host || port !== this._nat.port) return false
    // if the firewall probe returned a different host / non consistent port, bail as well
    if (natSampler.host !== host || natSampler.port === 0) return false

    const id = peer.id(natSampler.host, natSampler.port)

    if (!onlyFirewall) {
      this.ephemeral = this.io.ephemeral = false
    }

    if (natSampler !== this._nat) {
      const prevHost = this._nat.host
      const prevPort = this._nat.port

      this._nonePersistentSamples = []
      this._nat = natSampler

      if (prevHost !== this._nat.host || prevPort !== this._nat.port) {
        this.emit('nat-update', this._nat.host, this._nat.port)
      }
    }

    // TODO: we should make this a bit more defensive in terms of using more
    // resources to make sure that the new routing table contains as many alive nodes
    // as possible, vs blindly copying them over...

    // all good! copy over the old routing table to the new one
    if (!b4a.equals(this.table.id, id)) {
      const nodes = this.table.toArray()

      this.table = this.io.table = new Table(id)

      for (const node of nodes) {
        if (b4a.equals(node.id, id)) continue
        if (!this.table.add(node)) this.nodes.remove(node)
      }

      this.table.on('row', this._onrow)

      // we need to rebootstrap/refresh since we updated our id
      if (this.bootstrapped) this.refresh()
    }

    if (!this.ephemeral) {
      this.emit('persistent')
    }

    return true
  }

  async *_resolveBootstrapNodes() {
    for (let { host, port } of this.bootstrapNodes) {
      let doLookup = false

      if (host.indexOf('@') === -1) {
        doLookup = true
      } else {
        const [suggestedIP, fallbackHost] = host.split('@')
        try {
          await this.ping({ host: suggestedIP, port })
          host = suggestedIP
        } catch {
          host = fallbackHost
          doLookup = true
        }
      }

      if (doLookup) {
        try {
          host = UDX.isIPv4(host) ? host : (await this.udx.lookup(host, { family: 4 })).host
        } catch {
          continue
        }
      }

      yield {
        id: peer.id(host, port),
        host,
        port
      }
    }
  }

  async _addBootstrapNodes(nodes) {
    for await (const node of this._resolveBootstrapNodes()) {
      nodes.push(node)
    }
  }

  async _checkIfFirewalled(natSampler = new NatSampler()) {
    const nodes = []
    for (let node = this.nodes.latest; node && nodes.length < 5; node = node.prev) {
      nodes.push(node)
    }

    if (nodes.length < 5) await this._addBootstrapNodes(nodes)
    // if no nodes are available, including bootstrappers - bail
    if (nodes.length === 0) return true

    const hosts = new Set()
    const value = b4a.allocUnsafe(2)

    c.uint16.encode({ start: 0, end: 2, buffer: value }, this.io.serverSocket.address().port)

    // double check they actually came on the server socket...
    this.io.serverSocket.on('message', onmessage)

    const pongs = await requestAll(this, true, PING_NAT, value, nodes)

    let count = 0
    for (const res of pongs) {
      if (hosts.has(res.from.host)) {
        count++
        natSampler.add(res.to.host, res.to.port)
      }
    }

    this.io.serverSocket.removeListener('message', onmessage)

    // if we got no or very few replies, consider it a fluke
    if (count < (nodes.length >= 5 ? 3 : 1)) return true

    // check that the server socket has the same ip as the client socket
    if (natSampler.host === null || this._nat.host !== natSampler.host) return true

    // check that the local port of the server socket is the same as the remote port
    // TODO: we might want a flag to opt out of this heuristic for specific remapped port servers
    if (natSampler.port === 0 || natSampler.port !== this.io.serverSocket.address().port) {
      return true
    }

    return false

    function onmessage(_, { host }) {
      hosts.add(host)
    }
  }

  _backgroundQuery(target) {
    this._refreshTicks = REFRESH_TICKS

    const backgroundCon = Math.min(this.concurrency, Math.max(2, (this.concurrency / 8) | 0))
    const q = new Query(this, target, true, FIND_NODE, null, {
      concurrency: backgroundCon
    })

    q.on('data', () => {
      // yield to other traffic
      q.concurrency = this.io.inflight.length < 3 ? this.concurrency : backgroundCon
    })

    return q
  }

  // called by health
  _online() {
    if (this.online && !this.degraded) return
    this.online = true
    this.degraded = false
    this.emit('network-update')
  }

  // called by health
  _degraded() {
    if (this.degraded) return
    this.online = true
    this.degraded = true
    this.emit('network-update')
  }

  // called by health
  _offline() {
    if (!this.online) return
    this.online = false
    this.degraded = false
    this.emit('network-update')
  }
}

DHT.OK = 0
DHT.ERROR_UNKNOWN_COMMAND = UNKNOWN_COMMAND
DHT.ERROR_INVALID_TOKEN = INVALID_TOKEN

module.exports = DHT

function localIP(udx, family = 4) {
  let host = null

  for (const n of udx.networkInterfaces()) {
    if (n.family !== family || n.internal) continue

    // mac really likes en0, mb a better way but this shouldnt be bad anywhere so return now
    if (n.name === 'en0') return n.host

    // otherwise pick the first non internal host (let the loop continue in case we see en0)
    if (host === null) host = n.host
  }

  return host || (family === 4 ? '127.0.0.1' : '::1')
}

function parseNode(s) {
  if (typeof s === 'object') return s
  if (typeof s === 'number') return { host: '127.0.0.1', port: s }
  const [host, port] = s.split(':')
  if (!port) throw new Error('Bootstrap node format is host:port')

  return {
    host,
    port: Number(port)
  }
}

function randomBytes(n) {
  const b = b4a.alloc(n)
  sodium.randombytes_buf(b)
  return b
}

function randomOffset(n) {
  return n - ((Math.random() * 0.5 * n) | 0)
}

function requestAll(dht, internal, command, value, nodes) {
  let missing = nodes.length
  const replies = []

  return new Promise((resolve) => {
    for (const node of nodes) {
      const req = dht._request(
        node,
        false,
        internal,
        command,
        null,
        value,
        null,
        onsuccess,
        onerror
      )
      if (!req) return resolve(replies)
    }

    function onsuccess(res) {
      replies.push(res)
      if (--missing === 0) resolve(replies)
    }

    function onerror() {
      if (--missing === 0) resolve(replies)
    }
  })
}

function noop() {}
exports.PING = 0
exports.PING_NAT = 1
exports.FIND_NODE = 2
exports.DOWN_HINT = 3
exports.DELAYED_PING = 4
module.exports = class DHTError extends Error {
  constructor(msg, code, fn = DHTError) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'DHTError'
  }

  static UNKNOWN_COMMAND = 1
  static INVALID_TOKEN = 2

  static REQUEST_TIMEOUT(msg = 'Request timed out') {
    return new DHTError(msg, 'REQUEST_TIMEOUT', DHTError.REQUEST_TIMEOUT)
  }

  static REQUEST_DESTROYED(msg = 'Request destroyed') {
    return new DHTError(msg, 'REQUEST_DESTROYED', DHTError.REQUEST_DESTROYED)
  }

  static IO_SUSPENDED(msg = 'I/O suspended') {
    return new DHTError(msg, 'IO_SUSPENDED', DHTError.IO_SUSPENDED)
  }
}
const MAX_HEALTH_WINDOW = 4
const OFFLINE_THRESHOLD = 2
const IDLE_THRESHOLD = 4
const DEGRADED_TIMEOUT_RATE_THRESHOLD = 0.5

module.exports = class NetworkHealth {
  constructor(dht) {
    this._dht = dht
    this._window = []
    this._head = -1
    this._offlineTicks = 0
    this._degradedTicks = 0
    this._healthyTicks = 0
    this.online = true
    this.degraded = false
  }

  get oldest() {
    return this._window[this._tail]
  }

  get previous() {
    return this._window[(this._head - 1 + MAX_HEALTH_WINDOW) % MAX_HEALTH_WINDOW]
  }

  get newest() {
    return this._window[this._head]
  }

  get responses() {
    if (!this.newest || !this.previous) return 0
    return this.newest.responses - this.previous.responses
  }

  get timeouts() {
    if (!this.newest || !this.previous) return 0
    return this.newest.timeouts - this.previous.timeouts
  }

  get timeoutsRate() {
    if (this.timeouts === 0) return 0
    return this.timeouts / (this.responses + this.timeouts)
  }

  get cold() {
    return this._window.length < MAX_HEALTH_WINDOW
  }

  get idle() {
    return this.responses + this.timeouts < IDLE_THRESHOLD
  }

  get stats() {
    return {
      online: this.online,
      degraded: this.degraded,
      cold: this.cold,
      idle: this.idle,
      responses: this.responses,
      timeouts: this.timeouts,
      timeoutsRate: this.timeoutsRate
    }
  }

  get _tail() {
    return (this._head + 1) % MAX_HEALTH_WINDOW
  }

  reset() {
    this._window = []
    this._head = -1
    this._offlineTicks = 0
    this._degradedTicks = 0
    this._healthyTicks = 0
    this.online = true
    this.degraded = false
    this._dht._online()
  }

  update() {
    // update counters before dropping oldest
    if (this.oldest?.degraded) this._degradedTicks--
    else if (this.oldest?.degraded === false) this._healthyTicks--

    // move window
    this._head = this._tail
    this._window[this._head] = {
      responses: this._dht.stats.requests.responses,
      timeouts: this._dht.stats.requests.timeouts
    }

    // skip state changes
    if (this.cold || this.idle) return

    // update newest
    this.newest.offline = this.responses === 0
    this.newest.degraded =
      !this.newest.offline && this.timeoutsRate > DEGRADED_TIMEOUT_RATE_THRESHOLD

    // update counters
    if (this.newest.offline) this._offlineTicks++
    else {
      this._offlineTicks = 0
      if (this.newest.degraded) this._degradedTicks++
      else this._healthyTicks++
    }

    // check online/offline
    if (!this.newest.offline) this.online = true
    else if (this._offlineTicks >= OFFLINE_THRESHOLD) this.online = false

    // check degraded
    if (!this.online || this._healthyTicks === MAX_HEALTH_WINDOW) this.degraded = false
    else if (this._degradedTicks === MAX_HEALTH_WINDOW) this.degraded = true

    // fire events
    if (this.online && !this.degraded) this._dht._online()
    else if (this.degraded) this._dht._degraded()
    else this._dht._offline()
  }
}
const FIFO = require('fast-fifo')
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const b4a = require('b4a')
const AdaptiveTimeout = require('adaptive-timeout')
const peer = require('./peer')
const { INVALID_TOKEN, REQUEST_TIMEOUT, REQUEST_DESTROYED, IO_SUSPENDED } = require('./errors')

const VERSION = 0b11
const RESPONSE_ID = (0b0001 << 4) | VERSION
const REQUEST_ID = (0b0000 << 4) | VERSION
const EMPTY_ARRAY = []
const MAX_WINDOW = 80

module.exports = class IO {
  constructor(
    table,
    udx,
    {
      maxWindow = MAX_WINDOW,
      port = 0,
      host = '0.0.0.0',
      anyPort = true,
      firewalled = true,
      onrequest,
      onresponse = noop,
      ontimeout = noop,
      adaptiveTimeout
    } = {}
  ) {
    this.table = table
    this.udx = udx
    this.inflight = []
    this.clientSocket = null
    this.serverSocket = null
    this.firewalled = firewalled !== false
    this.ephemeral = true
    this.congestion = new CongestionWindow(maxWindow)
    this.networkInterfaces = udx.watchNetworkInterfaces()
    this.suspended = false

    this.stats = {
      requests: {
        active: 0,
        total: 0,
        responses: 0,
        timeouts: 0,
        retries: 0
      },
      commands: [
        { tx: 0, rx: 0 }, // tx = transmitted, rx = received
        { tx: 0, rx: 0 },
        { tx: 0, rx: 0 },
        { tx: 0, rx: 0 }
      ]
    }

    this.onrequest = onrequest
    this.onresponse = onresponse
    this.ontimeout = ontimeout

    this._pending = new FIFO()
    this._rotateSecrets = 10
    this._tid = (Math.random() * 65536) | 0
    this._secrets = null
    this._drainInterval = null
    this._destroying = null
    this._binding = null

    // port can be a number or a range [start, to]
    this.portRange = port.length ? port : port === 0 ? [0, 0] : [port, port + 5]

    this._host = host
    this._anyPort = anyPort !== false
    this._boundServerPort = 0
    this._boundClientPort = 0

    this._adt = adaptiveTimeout ? new AdaptiveTimeout(adaptiveTimeout) : null
  }

  static DEFAULT_MAX_WINDOW = MAX_WINDOW

  onmessage(socket, buffer, { host, port }) {
    if (buffer.byteLength < 2 || !(port > 0 && port < 65536) || this.suspended === true) return

    const from = { id: null, host, port }
    const state = { start: 1, end: buffer.byteLength, buffer }
    const expectedSocket = this.firewalled ? this.clientSocket : this.serverSocket
    const external = socket !== expectedSocket

    if (buffer[0] === REQUEST_ID) {
      const req = Request.decode(this, socket, from, state)
      if (req === null) return
      if (
        req.token !== null &&
        !b4a.equals(req.token, this.token(req.from, 1)) &&
        !b4a.equals(req.token, this.token(req.from, 0))
      ) {
        req.error(INVALID_TOKEN, { token: true })
        return
      }
      this.onrequest(req, external)
      return
    }

    if (buffer[0] === RESPONSE_ID) {
      const res = decodeReply(from, state)
      if (res === null) return

      for (let i = 0; i < this.inflight.length; i++) {
        const req = this.inflight[i]
        if (req.tid !== res.tid) continue

        res.rtt = Date.now() - req._timestamp

        if (this._adt && req.sent <= 2) {
          this._adt.put(`${req.to.host}:${req.to.port}`, res.rtt)
        }

        if (i === this.inflight.length - 1) this.inflight.pop()
        else this.inflight[i] = this.inflight.pop()

        if (req.session) req.session._detach(req)

        // TODO: Auto retry here if errors.INVALID_TOKEN is returned?

        if (req._timeout) {
          clearTimeout(req._timeout)
          req._timeout = null
        }

        this.congestion.recv()

        if (req.internal && req.command < this.stats.commands.length) {
          this.stats.commands[req.command].rx++
        }

        this.stats.requests.active--
        this.stats.requests.responses++

        this.onresponse(res, external)
        req.onresponse(res, req)
        break
      }
    }
  }

  token(addr, i) {
    if (this._secrets === null) {
      const buf = b4a.alloc(64)
      this._secrets = [buf.subarray(0, 32), buf.subarray(32, 64)]
      sodium.randombytes_buf(this._secrets[0])
      sodium.randombytes_buf(this._secrets[1])
    }

    const token = b4a.allocUnsafe(32)
    sodium.crypto_generichash(token, b4a.from(addr.host), this._secrets[i])
    return token
  }

  async destroy() {
    if (this._destroying) return this._destroying
    this._destroying = this._destroy()
    return this._destroying
  }

  async _destroy() {
    // simplifies timing to await the bind here also, although it might be unneeded
    await this.bind()
    await this._clear(false)
  }

  async _clear(suspended) {
    if (this._drainInterval) {
      clearInterval(this._drainInterval)
      this._drainInterval = null
    }

    while (this.inflight.length) {
      const req = this.inflight.pop()
      if (req._timeout) clearTimeout(req._timeout)
      req._timeout = null
      req.destroyed = true

      if (req.session) req.session._detach(req)

      this.congestion.recv()
      this.stats.requests.active--

      req.onerror(suspended ? IO_SUSPENDED() : REQUEST_DESTROYED(), req)
    }

    await Promise.allSettled([this.serverSocket.close(), this.clientSocket.close()])

    this.networkInterfaces.destroy()
  }

  async suspend() {
    this.suspended = true
    await this._clear(true)

    this.congestion.clear()

    if (this._drainInterval) {
      clearInterval(this._drainInterval)
      this._drainInterval = null
    }
  }

  async _rebind(binding) {
    if (binding) await binding
    if (this._destroying) return this._destroying
    await this._bindSockets()
    this.networkInterfaces = this.udx.watchNetworkInterfaces()
  }

  resume() {
    this.suspended = false
    const binding = this._binding
    this._binding = this._rebind(binding)
    return this._binding
  }

  bind() {
    if (this._binding) return this._binding
    this._binding = this._bindSockets()
    return this._binding
  }

  async _bindSockets() {
    const serverSocket = this.udx.createSocket()

    const candidatePorts = []

    // Retrying previous port always has precedence
    if (this._boundServerPort) candidatePorts.push(this._boundServerPort)

    for (let i = this.portRange[0]; i < this.portRange[1]; i++) candidatePorts.push(i)

    for (const port of candidatePorts) {
      if (serverSocket.bound) break

      try {
        serverSocket.bind(port, this._host)
      } catch (err) {
        if (!this._anyPort) {
          await serverSocket.close()
          throw err
        }
      }
    }

    if (!serverSocket.bound) {
      try {
        serverSocket.bind(0, this._host)
      } catch (err) {
        await serverSocket.close()
        throw err
      }
    }

    const clientSocket = this.udx.createSocket()

    try {
      clientSocket.bind(this._boundClientPort || 0, this._host)
    } catch {
      try {
        clientSocket.bind(0, this._host)
      } catch (err) {
        await serverSocket.close()
        await clientSocket.close()
        throw err
      }
    }

    this._boundServerPort = serverSocket.address().port
    this._boundClientPort = clientSocket.address().port

    this.clientSocket = clientSocket
    this.serverSocket = serverSocket

    this.serverSocket.on('message', this.onmessage.bind(this, this.serverSocket))
    this.clientSocket.on('message', this.onmessage.bind(this, this.clientSocket))

    if (this._drainInterval === null) {
      this._drainInterval = setInterval(this._drain.bind(this), 750)
      if (this._drainInterval.unref) this._drainInterval.unref()
    }

    for (const req of this.inflight) {
      if (!req.socket) req.socket = this.firewalled ? this.clientSocket : this.serverSocket
      req.sent = 0
      req.send(false)
    }
  }

  _drain() {
    if (this._secrets !== null && --this._rotateSecrets === 0) {
      this._rotateSecrets = 10
      const tmp = this._secrets[0]
      this._secrets[0] = this._secrets[1]
      this._secrets[1] = tmp
      sodium.crypto_generichash(tmp, tmp)
    }

    this.congestion.drain()

    while (!this.congestion.isFull()) {
      const p = this._pending.shift()
      if (p === undefined) return
      p._sendNow()
    }
  }

  createRequest(to, token, internal, command, target, value, session, ttl) {
    if (this._destroying !== null) return null

    if (this._tid === 65536) this._tid = 0

    const tid = this._tid++
    const socket = this.firewalled ? this.clientSocket : this.serverSocket

    const req = new Request(
      this,
      socket,
      tid,
      null,
      to,
      token,
      internal,
      command,
      target,
      value,
      session,
      ttl || 0
    )
    this.inflight.push(req)
    if (session) session._attach(req)

    if (internal && command < this.stats.commands.length) {
      this.stats.commands[command].tx++
    }

    this.stats.requests.active++
    this.stats.requests.total++

    return req
  }
}

class Request {
  constructor(io, socket, tid, from, to, token, internal, command, target, value, session, ttl) {
    this.socket = socket
    this.tid = tid
    this.from = from
    this.to = to
    this.token = token
    this.command = command
    this.target = target
    this.value = value
    this.internal = internal
    this.session = session
    this.ttl = ttl
    this.index = -1
    this.sent = 0
    this.retries = 3
    this.destroyed = false
    this.timeout = 0

    this.oncycle = noop
    this.onerror = noop
    this.onresponse = noop

    this._buffer = null
    this._io = io
    this._timeout = null
    this._timestamp = Date.now()
  }

  static decode(io, socket, from, state) {
    try {
      const flags = c.uint.decode(state)
      const tid = c.uint16.decode(state)
      const to = peer.ipv4.decode(state)
      const id = flags & 1 ? c.fixed32.decode(state) : null
      const token = flags & 2 ? c.fixed32.decode(state) : null
      const internal = (flags & 4) !== 0
      const command = c.uint.decode(state)
      const target = flags & 8 ? c.fixed32.decode(state) : null
      const value = flags & 16 ? c.buffer.decode(state) : null

      if (id !== null) from.id = validateId(id, from)

      return new Request(
        io,
        socket,
        tid,
        from,
        to,
        token,
        internal,
        command,
        target,
        value,
        null,
        0
      )
    } catch {
      return null
    }
  }

  reply(value, opts = {}) {
    const socket = opts.socket || this.socket
    const to = opts.to || this.from
    this._sendReply(0, value || null, opts.token !== false, opts.closerNodes !== false, to, socket)
  }

  error(code, opts = {}) {
    const socket = opts.socket || this.socket
    const to = opts.to || this.from
    this._sendReply(code, null, opts.token === true, opts.closerNodes !== false, to, socket)
  }

  relay(value, to, opts) {
    const socket = (opts && opts.socket) || this.socket
    const buffer = this._encodeRequest(null, value, to, socket)
    socket.trySend(buffer, to.port, to.host, this.ttl)
  }

  send(force = false) {
    if (this.destroyed) return

    if (this.socket === null) return
    if (this._buffer === null) {
      this._buffer = this._encodeRequest(this.token, this.value, this.to, this.socket)
    }

    if (!force && this._io.congestion.isFull()) {
      this._io._pending.push(this)
      return
    }

    this._sendNow()
  }

  sendReply(error, value, token, hasCloserNodes) {
    this._sendReply(error, value, token, hasCloserNodes, this.from, this.socket, null)
  }

  _sendNow() {
    if (this.destroyed) return
    this.sent++
    this._io.congestion.send()
    this.socket.trySend(this._buffer, this.to.port, this.to.host, this.ttl)
    if (this._timeout) clearTimeout(this._timeout)
    const value =
      this.timeout || this._io._adt?.get(`${this.to.host}:${this.to.port}`, this.sent) || 1000
    this._timeout = setTimeout(oncycle, value, this)
  }

  destroy(err) {
    if (this.destroyed) return
    this.destroyed = true

    if (this._timeout) {
      clearTimeout(this._timeout)
      this._timeout = null
    }

    const i = this._io.inflight.indexOf(this)
    if (i === -1) return

    if (i === this._io.inflight.length - 1) this._io.inflight.pop()
    else this._io.inflight[i] = this._io.inflight.pop()

    if (this.session) this.session._detach(this)

    this._io.stats.requests.active--
    this._io.congestion.recv()

    this.onerror(err || REQUEST_DESTROYED(), this)
  }

  _sendReply(error, value, token, hasCloserNodes, from, socket) {
    if (socket === null || this.destroyed) return

    const id = this._io.ephemeral === false && socket === this._io.serverSocket
    const closerNodes =
      this.target !== null && hasCloserNodes ? this._io.table.closest(this.target) : EMPTY_ARRAY
    const state = { start: 0, end: 1 + 1 + 6 + 2, buffer: null } // (type | version) + flags + to + tid

    if (id) state.end += 32
    if (token) state.end += 32
    if (closerNodes.length > 0) peer.ipv4Array.preencode(state, closerNodes)
    if (error > 0) c.uint.preencode(state, error)
    if (value) c.buffer.preencode(state, value)

    state.buffer = b4a.allocUnsafe(state.end)
    state.buffer[state.start++] = RESPONSE_ID
    state.buffer[state.start++] =
      (id ? 1 : 0) |
      (token ? 2 : 0) |
      (closerNodes.length > 0 ? 4 : 0) |
      (error > 0 ? 8 : 0) |
      (value ? 16 : 0)

    c.uint16.encode(state, this.tid)
    peer.ipv4.encode(state, from)

    if (id) c.fixed32.encode(state, this._io.table.id)
    if (token) c.fixed32.encode(state, this._io.token(from, 1))
    if (closerNodes.length > 0) peer.ipv4Array.encode(state, closerNodes)
    if (error > 0) c.uint.encode(state, error)
    if (value) c.buffer.encode(state, value)

    socket.trySend(state.buffer, from.port, from.host, this.ttl)
  }

  _encodeRequest(token, value, to, socket) {
    const id = this._io.ephemeral === false && socket === this._io.serverSocket
    const state = { start: 0, end: 1 + 1 + 6 + 2, buffer: null } // (type | version) + flags + to + tid

    if (id) state.end += 32
    if (token) state.end += 32

    c.uint.preencode(state, this.command)

    if (this.target) state.end += 32
    if (value) c.buffer.preencode(state, value)

    state.buffer = b4a.allocUnsafe(state.end)
    state.buffer[state.start++] = REQUEST_ID
    state.buffer[state.start++] =
      (id ? 1 : 0) |
      (token ? 2 : 0) |
      (this.internal ? 4 : 0) |
      (this.target ? 8 : 0) |
      (value ? 16 : 0)

    c.uint16.encode(state, this.tid)
    peer.ipv4.encode(state, to)

    if (id) c.fixed32.encode(state, this._io.table.id)
    if (token) c.fixed32.encode(state, token)

    c.uint.encode(state, this.command)

    if (this.target) c.fixed32.encode(state, this.target)
    if (value) c.buffer.encode(state, value)

    return state.buffer
  }
}

class CongestionWindow {
  constructor(maxWindow) {
    this._i = 0
    this._total = 0
    this._window = [0, 0, 0, 0]
    this._maxWindow = maxWindow
  }

  clear() {
    this._i = 0
    this._total = 0
    this._window = [0, 0, 0, 0]
  }

  isFull() {
    return this._total >= 2 * this._maxWindow || this._window[this._i] >= this._maxWindow
  }

  recv() {
    if (this._window[this._i] > 0) {
      this._window[this._i]--
      this._total--
    }
  }

  send() {
    this._total++
    this._window[this._i]++
  }

  drain() {
    this._i = (this._i + 1) & 3
    this._total -= this._window[this._i]
    this._window[this._i] = 0 // clear oldest
  }
}

function noop() {}

function oncycle(req) {
  req._timeout = null
  req.oncycle(req)
  if (req.sent > req.retries) {
    req._io.stats.requests.timeouts++
    req.destroy(REQUEST_TIMEOUT())
    req._io.ontimeout(req)
  } else {
    req._io.stats.requests.retries++
    req.send()
  }
}

function decodeReply(from, state) {
  try {
    const flags = c.uint.decode(state)
    const tid = c.uint16.decode(state)
    const to = peer.ipv4.decode(state)
    const id = flags & 1 ? c.fixed32.decode(state) : null
    const token = flags & 2 ? c.fixed32.decode(state) : null
    const closerNodes = flags & 4 ? peer.ipv4Array.decode(state) : null
    const error = flags & 8 ? c.uint.decode(state) : 0
    const value = flags & 16 ? c.buffer.decode(state) : null

    if (id !== null) from.id = validateId(id, from)

    return { tid, rtt: 0, from, to, token, closerNodes, error, value }
  } catch {
    return null
  }
}

function validateId(id, from) {
  const expected = peer.id(from.host, from.port)
  return b4a.equals(expected, id) ? expected : null
}
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const net = require('compact-encoding-net')
const b4a = require('b4a')

const ipv4 = {
  ...net.ipv4Address,
  decode(state) {
    const ip = net.ipv4Address.decode(state)
    return {
      id: null, // populated by the callee
      host: ip.host,
      port: ip.port
    }
  }
}

module.exports = { id, ipv4, ipv4Array: c.array(ipv4) }

function id(host, port, out = b4a.allocUnsafeSlow(32)) {
  const addr = out.subarray(0, 6)
  ipv4.encode({ start: 0, end: 6, buffer: addr }, { host, port })
  sodium.crypto_generichash(out, addr)
  return out
}
const { Readable, getStreamError } = require('streamx')
const b4a = require('b4a')
const peer = require('./peer')
const { DOWN_HINT } = require('./commands')

const DONE = []
const DOWN = []

module.exports = class Query extends Readable {
  constructor(dht, target, internal, command, value, opts = {}) {
    super()

    dht.stats.queries.total++
    dht.stats.queries.active++

    this.force = !!opts.force
    this.dht = dht
    this.k = this.dht.table.k
    this.target = target
    this.internal = internal
    this.command = command
    this.value = value
    this.errors = 0
    this.successes = 0
    this.concurrency = opts.concurrency || this.dht.concurrency
    this.inflight = 0
    this.map = opts.map || defaultMap
    this.retries =
      opts.retries === 0 ? 0 : opts.retries || (this.internal && command === DOWN_HINT ? 3 : 5)
    this.closestReplies = []

    this._slow = 0
    this._slowdown = false
    this._seen = new Map()
    this._pending = []
    this._fromTable = false
    this._commit = opts.commit === true ? autoCommit : opts.commit || null
    this._commiting = false
    this._session = opts.session || dht.session()
    this._autoDestroySession = !opts.session
    this._onlyClosestNodes = false

    this._onvisitbound = this._onvisit.bind(this)
    this._onerrorbound = this._onerror.bind(this)
    this._oncyclebound = this._oncycle.bind(this)

    const nodes = opts.nodes || opts.closestNodes
    const replies = opts.replies || opts.closestReplies

    // add them reverse as we pop below
    if (nodes) {
      for (let i = nodes.length - 1; i >= 0; i--) {
        const node = nodes[i]
        this._addPending(
          {
            id: node.id || peer.id(node.host, node.port),
            host: node.host,
            port: node.port
          },
          null
        )
      }
    } else if (replies) {
      for (let i = replies.length - 1; i >= 0; i--) {
        this._addPending(replies[i].from, null)
      }
    }

    if (opts.onlyClosestNodes) this._onlyClosestNodes = true
  }

  get closestNodes() {
    const nodes = new Array(this.closestReplies.length)

    for (let i = 0; i < nodes.length; i++) {
      nodes[i] = this.closestReplies[i].from
    }

    return nodes
  }

  finished() {
    return new Promise((resolve, reject) => {
      if (this.destroyed) {
        const error = getStreamError(this)
        if (error) reject(error)
        else resolve()
        return
      }

      const self = this
      let error = null

      this.resume()
      this.on('error', onerror)
      this.on('close', onclose)

      function onclose() {
        self.removeListener('error', onerror)
        self.removeListener('close', onclose)
        if (error) reject(error)
        else resolve()
      }

      function onerror(err) {
        error = err
      }
    })
  }

  _addFromTable() {
    if (this._pending.length >= this.k) return
    this._fromTable = true

    const closest = this.dht.table.closest(this.target, this.k - this._pending.length)

    for (const node of closest) {
      this._addPending({ id: node.id, host: node.host, port: node.port }, null)
    }
  }

  async _open(cb) {
    this._addFromTable()
    if (this._pending.length >= this.k) return cb(null)

    for await (const node of this.dht._resolveBootstrapNodes()) {
      this._addPending(node, null)
    }

    cb(null)
  }

  _isCloser(id) {
    return (
      this.closestReplies.length < this.k ||
      this._compare(id, this.closestReplies[this.closestReplies.length - 1].from.id) < 0
    )
  }

  _addPending(node, ref) {
    if (this._onlyClosestNodes) return false

    const addr = node.host + ':' + node.port
    const refs = this._seen.get(addr)
    const isCloser = this._isCloser(node.id)

    if (refs === DONE) {
      return isCloser
    }

    if (refs === DOWN) {
      if (ref) this._downHint(ref, node)
      return isCloser
    }

    if (refs) {
      if (ref !== null) refs.push(ref)
      return isCloser
    }

    if (!isCloser) {
      return false
    }

    this._seen.set(addr, ref === null ? [] : [ref])
    this._pending.push(node)

    return true
  }

  _read(cb) {
    this._readMore()
    cb(null)
  }

  _readMore() {
    if (this.destroying || this._commiting) return

    const concurrency = (this._slowdown ? 3 : this.concurrency) + this._slow

    while (this.inflight < concurrency && this._pending.length > 0) {
      const next = this._pending.pop()
      if (next && next.id && !this._isCloser(next.id)) continue
      this._visit(next)
    }

    // if reusing closest nodes, slow down after the first readMore tick to allow
    // the closest node a chance to reply before going broad to question more
    if (!this._fromTable && this.successes === 0 && this.errors === 0) {
      this._slowdown = true
    }

    if (this._pending.length > 0) return

    // if no inflight OR all the queries we are waiting on are marked as slow and we have a full result.
    if (
      this.inflight === 0 ||
      (this._slow === this.inflight && this.closestReplies.length >= this.k)
    ) {
      // if more than 3/4 failed and we only used cached nodes, try again from the routing table
      if (!this._fromTable && this.successes < this.k / 4) {
        this._addFromTable()
        this._readMore()
        return
      }

      this._flush()
    }
  }

  _flush() {
    if (this._commiting) return
    this._commiting = true

    if (this._commit === null) {
      this.push(null)
      return
    }

    const p = []
    for (const m of this.closestReplies) p.push(this._commit(m, this.dht, this))
    this._endAfterCommit(p)
  }

  _endAfterCommit(ps) {
    if (!ps.length) {
      this.destroy(new Error('Too few nodes responded'))
      return
    }

    const self = this

    let pending = ps.length
    let success = 0

    for (const p of ps) p.then(ondone, onerror)

    function ondone() {
      success++
      if (--pending === 0) self.push(null)
    }

    function onerror(err) {
      if (--pending > 0) return
      if (success) self.push(null)
      else self.destroy(err)
    }
  }

  _dec(req) {
    if (req.oncycle === noop) {
      this._slow--
    } else {
      req.oncycle = noop
    }
    this.inflight--
  }

  _onvisit(m, req) {
    this._dec(req)

    const addr = req.to.host + ':' + req.to.port
    this._seen.set(addr, DONE)

    if (this._commiting) return

    if (m.error === 0) this.successes++
    else this.errors++

    if (m.error === 0 && m.from.id !== null && this._isCloser(m.from.id)) this._pushClosest(m)

    if (m.closerNodes !== null) {
      for (const node of m.closerNodes) {
        node.id = peer.id(node.host, node.port)
        if (this.dht._filterNode !== null && !this.dht._filterNode(node)) continue
        if (b4a.equals(node.id, this.dht.table.id)) continue
        // TODO: we could continue here instead of breaking to ensure that one of the nodes in the closer list
        // is later marked as DOWN that we gossip that back
        if (!this._addPending(node, m.from)) break
      }
    }

    if (!this._fromTable && this.successes + this.errors >= this.concurrency) {
      this._slowdown = false
    }

    if (m.error !== 0) {
      this._readMore()
      return
    }

    const data = this.map(m)
    if (!data || this.push(data) !== false) {
      this._readMore()
    }
  }

  _onerror(err, req) {
    const addr = req.to.host + ':' + req.to.port
    const refs = this._seen.get(addr)

    if (err.code === 'REQUEST_TIMEOUT') {
      this._seen.set(addr, DOWN)
      for (const node of refs) this._downHint(node, req.to)
    }

    this._dec(req)
    this.errors++
    this._readMore()
  }

  _oncycle(req) {
    req.oncycle = noop
    this._slow++
    this._readMore()
  }

  _downHint(node, down) {
    // Check rate limit
    if (
      this.dht._downHintsRateLimit !== -1 &&
      this.dht._downHintsSentPerTick >= this.dht._downHintsRateLimit
    ) {
      return null
    }

    this.dht._downHintsSentPerTick++

    const state = { start: 0, end: 6, buffer: b4a.allocUnsafe(6) }
    peer.ipv4.encode(state, down)
    this.dht._request(node, false, true, DOWN_HINT, null, state.buffer, this._session, noop, noop)
  }

  _pushClosest(m) {
    this.closestReplies.push(m)
    for (let i = this.closestReplies.length - 2; i >= 0; i--) {
      const prev = this.closestReplies[i]
      const cmp = this._compare(prev.from.id, m.from.id)
      // if sorted, done!
      if (cmp < 0) break
      // if dup, splice it out (rare)
      if (cmp === 0) {
        this.closestReplies.splice(i + 1, 1)
        break
      }
      // swap and continue down
      this.closestReplies[i + 1] = prev
      this.closestReplies[i] = m
    }
    if (this.closestReplies.length > this.k) this.closestReplies.pop()
  }

  _compare(a, b) {
    for (let i = 0; i < a.length; i++) {
      if (a[i] === b[i]) continue
      const t = this.target[i]
      return (t ^ a[i]) - (t ^ b[i])
    }
    return 0
  }

  _visit(to) {
    this.inflight++

    const req = this.dht._request(
      to,
      this.force,
      this.internal,
      this.command,
      this.target,
      this.value,
      this._session,
      this._onvisitbound,
      this._onerrorbound
    )
    if (req === null) {
      this.destroy(new Error('Node was destroyed'))
      return
    }
    req.retries = this.retries
    req.oncycle = this._oncyclebound
    if (this.force) req.retries = 0
  }

  _destroy(cb) {
    this.dht.stats.queries.active--
    if (this._autoDestroySession) this._session.destroy()
    cb(null)
  }
}

function autoCommit(reply, dht, query) {
  if (!reply.token) return Promise.reject(new Error('No token received for closest node'))
  return dht.request(
    {
      token: reply.token,
      target: query.target,
      command: query.command,
      value: query.value
    },
    reply.from
  )
}

function defaultMap(m) {
  return m
}

function noop() {}
module.exports = class Session {
  constructor(dht) {
    this.dht = dht
    this.inflight = []
  }

  _attach(req) {
    req.index = this.inflight.push(req) - 1
  }

  _detach(req) {
    const i = req.index
    if (i === -1) return
    req.index = -1

    if (i === this.inflight.length - 1) this.inflight.pop()
    else {
      const req = (this.inflight[i] = this.inflight.pop())
      req.index = i
    }
  }

  query({ target, command, value }, opts = {}) {
    return this.dht.query({ target, command, value }, { ...opts, session: this })
  }

  request({ token, command, target, value }, { host, port }, opts = {}) {
    return this.dht.request(
      { token, command, target, value },
      { host, port },
      { ...opts, session: this }
    )
  }

  ping({ host, port }, opts = {}) {
    return this.dht.ping({ host, port }, { ...opts, session: this })
  }

  destroy(err) {
    while (this.inflight.length) {
      const req = this.inflight[0]
      // prevent destroyed requests from contributing to congestion counts
      this.dht.io.congestion.recv()
      req.destroy(err)
    }
  }
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return uint24.decode(state) + 0x1000000 * uint32.decode(state)
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return uint32.decode(state) + 0x100000000 * uint32.decode(state)
  }
})

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "2.19.2",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    if (b.byteLength === 0) return null
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "dht-rpc",
  "version": "6.26.4",
  "description": "Make RPC calls over a Kademlia based DHT",
  "main": "index.js",
  "files": [
    "index.js",
    "lib/*.js"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "dependencies": {
    "adaptive-timeout": "^1.0.1",
    "b4a": "^1.6.1",
    "bare-events": "^2.2.0",
    "compact-encoding": "^2.11.0",
    "compact-encoding-net": "^1.2.0",
    "fast-fifo": "^1.1.0",
    "kademlia-routing-table": "^1.0.1",
    "nat-sampler": "^1.0.1",
    "sodium-universal": "^5.0.0",
    "streamx": "^2.13.2",
    "time-ordered-set": "^2.0.0",
    "udx-native": "^1.5.3"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "test-suspend": "^1.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "test": "npm run test:node && npm run test:bare",
    "test:bare": "brittle-bare --coverage test.js",
    "lint": "prettier --check . && lunte",
    "test:node": "brittle-node --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/dht-rpc.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/dht-rpc/issues"
  },
  "homepage": "https://github.com/holepunchto/dht-rpc#"
}
module.exports = require('bare-events')
{
  "name": "events-universal",
  "version": "1.0.1",
  "description": "Universal wrapper for the Node.js events module",
  "exports": {
    "./package": "./package.json",
    ".": {
      "bare": "./bare.js",
      "react-native": "./react-native.js",
      "default": "./default.js"
    }
  },
  "files": [
    "index.js",
    "default.js",
    "bare.js",
    "react-native.js"
  ],
  "scripts": {
    "test": "prettier . --check"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/events-universal.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/events-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/events-universal#readme",
  "dependencies": {
    "bare-events": "^2.7.0"
  },
  "devDependencies": {
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^1.0.0"
  }
}
module.exports = class FixedFIFO {
  constructor (hwm) {
    if (!(hwm > 0) || ((hwm - 1) & hwm) !== 0) throw new Error('Max size for a FixedFIFO should be a power of two')
    this.buffer = new Array(hwm)
    this.mask = hwm - 1
    this.top = 0
    this.btm = 0
    this.next = null
  }

  clear () {
    this.top = this.btm = 0
    this.next = null
    this.buffer.fill(undefined)
  }

  push (data) {
    if (this.buffer[this.top] !== undefined) return false
    this.buffer[this.top] = data
    this.top = (this.top + 1) & this.mask
    return true
  }

  shift () {
    const last = this.buffer[this.btm]
    if (last === undefined) return undefined
    this.buffer[this.btm] = undefined
    this.btm = (this.btm + 1) & this.mask
    return last
  }

  peek () {
    return this.buffer[this.btm]
  }

  isEmpty () {
    return this.buffer[this.btm] === undefined
  }
}
const FixedFIFO = require('./fixed-size')

module.exports = class FastFIFO {
  constructor (hwm) {
    this.hwm = hwm || 16
    this.head = new FixedFIFO(this.hwm)
    this.tail = this.head
    this.length = 0
  }

  clear () {
    this.head = this.tail
    this.head.clear()
    this.length = 0
  }

  push (val) {
    this.length++
    if (!this.head.push(val)) {
      const prev = this.head
      this.head = prev.next = new FixedFIFO(2 * this.head.buffer.length)
      this.head.push(val)
    }
  }

  shift () {
    if (this.length !== 0) this.length--
    const val = this.tail.shift()
    if (val === undefined && this.tail.next) {
      const next = this.tail.next
      this.tail.next = null
      this.tail = next
      return this.tail.shift()
    }

    return val
  }

  peek () {
    const val = this.tail.peek()
    if (val === undefined && this.tail.next) return this.tail.next.peek()
    return val
  }

  isEmpty () {
    return this.length === 0
  }
}
{
  "name": "fast-fifo",
  "version": "1.3.2",
  "description": "A fast fifo implementation similar to the one powering nextTick in Node.js core",
  "main": "index.js",
  "files": [
    "./index.js",
    "./fixed-size.js"
  ],
  "dependencies": {},
  "devDependencies": {
    "standard": "^17.1.0",
    "brittle": "^3.3.2"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/fast-fifo.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/fast-fifo/issues"
  },
  "homepage": "https://github.com/mafintosh/fast-fifo"
}
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const b4a = require('b4a')

// https://en.wikipedia.org/wiki/Merkle_tree#Second_preimage_attack
const LEAF_TYPE = b4a.from([0])
const PARENT_TYPE = b4a.from([1])
const ROOT_TYPE = b4a.from([2])

const HYPERCORE = b4a.from('hypercore')

exports.keyPair = function (seed) {
  // key pairs might stay around for a while, so better not to use a default slab to avoid retaining it completely
  const slab = b4a.allocUnsafeSlow(sodium.crypto_sign_PUBLICKEYBYTES + sodium.crypto_sign_SECRETKEYBYTES)
  const publicKey = slab.subarray(0, sodium.crypto_sign_PUBLICKEYBYTES)
  const secretKey = slab.subarray(sodium.crypto_sign_PUBLICKEYBYTES)

  if (seed) sodium.crypto_sign_seed_keypair(publicKey, secretKey, seed)
  else sodium.crypto_sign_keypair(publicKey, secretKey)

  return {
    publicKey,
    secretKey
  }
}

exports.validateKeyPair = function (keyPair) {
  const pk = b4a.allocUnsafe(sodium.crypto_sign_PUBLICKEYBYTES)
  sodium.crypto_sign_ed25519_sk_to_pk(pk, keyPair.secretKey)
  return b4a.equals(pk, keyPair.publicKey)
}

exports.sign = function (message, secretKey) {
  // Dedicated slab for the signature, to avoid retaining unneeded mem and for security
  const signature = b4a.allocUnsafeSlow(sodium.crypto_sign_BYTES)
  sodium.crypto_sign_detached(signature, message, secretKey)
  return signature
}

exports.verify = function (message, signature, publicKey) {
  if (signature.byteLength !== sodium.crypto_sign_BYTES) return false
  if (publicKey.byteLength !== sodium.crypto_sign_PUBLICKEYBYTES) return false
  return sodium.crypto_sign_verify_detached(signature, message, publicKey)
}

exports.encrypt = function (message, publicKey) {
  const ciphertext = b4a.alloc(message.byteLength + sodium.crypto_box_SEALBYTES)
  sodium.crypto_box_seal(ciphertext, message, publicKey)
  return ciphertext
}

exports.decrypt = function (ciphertext, keyPair) {
  if (ciphertext.byteLength < sodium.crypto_box_SEALBYTES) return null

  const plaintext = b4a.alloc(ciphertext.byteLength - sodium.crypto_box_SEALBYTES)

  if (!sodium.crypto_box_seal_open(plaintext, ciphertext, keyPair.publicKey, keyPair.secretKey)) {
    return null
  }

  return plaintext
}

exports.encryptionKeyPair = function (seed) {
  const publicKey = b4a.alloc(sodium.crypto_box_PUBLICKEYBYTES)
  const secretKey = b4a.alloc(sodium.crypto_box_SECRETKEYBYTES)

  if (seed) {
    sodium.crypto_box_seed_keypair(publicKey, secretKey, seed)
  } else {
    sodium.crypto_box_keypair(publicKey, secretKey)
  }

  return {
    publicKey,
    secretKey
  }
}

exports.data = function (data) {
  const out = b4a.allocUnsafe(32)

  sodium.crypto_generichash_batch(out, [
    LEAF_TYPE,
    c.encode(c.uint64, data.byteLength),
    data
  ])

  return out
}

exports.parent = function (a, b) {
  if (a.index > b.index) {
    const tmp = a
    a = b
    b = tmp
  }

  const out = b4a.allocUnsafe(32)

  sodium.crypto_generichash_batch(out, [
    PARENT_TYPE,
    c.encode(c.uint64, a.size + b.size),
    a.hash,
    b.hash
  ])

  return out
}

exports.tree = function (roots, out) {
  const buffers = new Array(3 * roots.length + 1)
  let j = 0

  buffers[j++] = ROOT_TYPE

  for (let i = 0; i < roots.length; i++) {
    const r = roots[i]
    buffers[j++] = r.hash
    buffers[j++] = c.encode(c.uint64, r.index)
    buffers[j++] = c.encode(c.uint64, r.size)
  }

  if (!out) out = b4a.allocUnsafe(32)
  sodium.crypto_generichash_batch(out, buffers)
  return out
}

exports.hash = function (data, out) {
  if (!out) out = b4a.allocUnsafe(32)
  if (!Array.isArray(data)) data = [data]

  sodium.crypto_generichash_batch(out, data)

  return out
}

exports.randomBytes = function (n) {
  const buf = b4a.allocUnsafe(n)
  sodium.randombytes_buf(buf)
  return buf
}

exports.discoveryKey = function (key) {
  if (!key || key.byteLength !== 32) throw new Error('Must pass a 32 byte buffer')
  // Discovery keys might stay around for a while, so better not to use slab memory (for better gc)
  const digest = b4a.allocUnsafeSlow(32)
  sodium.crypto_generichash(digest, HYPERCORE, key)
  return digest
}

if (sodium.sodium_free) {
  exports.free = function (secureBuf) {
    if (secureBuf.secure) sodium.sodium_free(secureBuf)
  }
} else {
  exports.free = function () {}
}

exports.namespace = function (name, count) {
  const ids = typeof count === 'number' ? range(count) : count

  // Namespaces are long-lived, so better to use a dedicated slab
  const buf = b4a.allocUnsafeSlow(32 * ids.length)

  const list = new Array(ids.length)

  // ns is emhemeral, so default slab
  const ns = b4a.allocUnsafe(33)
  sodium.crypto_generichash(ns.subarray(0, 32), typeof name === 'string' ? b4a.from(name) : name)

  for (let i = 0; i < list.length; i++) {
    list[i] = buf.subarray(32 * i, 32 * i + 32)
    ns[32] = ids[i]
    sodium.crypto_generichash(list[i], ns)
  }

  return list
}

function range (count) {
  const arr = new Array(count)
  for (let i = 0; i < count; i++) arr[i] = i
  return arr
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return uint24.decode(state) + 0x1000000 * uint32.decode(state)
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return uint32.decode(state) + 0x100000000 * uint32.decode(state)
  }
})

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "2.19.2",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    if (b.byteLength === 0) return null
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "hypercore-crypto",
  "version": "3.6.1",
  "description": "The crypto primitives used in hypercore, extracted into a separate module",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.6.6",
    "compact-encoding": "^2.15.0",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "brittle": "^3.5.0",
    "standard": "^17.1.0"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/hypercore-crypto.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/hypercore-crypto/issues"
  },
  "homepage": "https://github.com/mafintosh/hypercore-crypto"
}
const z32 = require('z32')
const b4a = require('b4a')

module.exports = {
  encode,
  decode,
  normalize,
  isValid
}

function encode (key) {
  if (!b4a.isBuffer(key)) throw new Error('Key must be a Buffer')
  if (key.byteLength !== 32) throw new Error('Key must be 32-bytes long')
  return z32.encode(key)
}

function decode (id) {
  if (b4a.isBuffer(id)) {
    if (id.byteLength !== 32) throw new Error('ID must be 32-bytes long')
    return id
  }
  if (typeof id === 'string') {
    if (id.startsWith('pear://')) id = id.slice(7).split('/')[0]
    if (id.length === 52) return z32.decode(id)
    if (id.length === 64) {
      const buf = b4a.from(id, 'hex')
      if (buf.byteLength === 32) return buf
    }
  }
  throw new Error('Invalid Hypercore key')
}

function normalize (any) {
  return encode(decode(any))
}

function isValid (any) {
  try {
    decode(any)
    return true
  } catch {
    return false
  }
}
{
  "name": "hypercore-id-encoding",
  "version": "1.3.0",
  "description": "Convert Hypercore keys to/from z-base32 or hex",
  "main": "index.js",
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.5.3",
    "z32": "^1.0.0"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "hypercore": "^10.0.0",
    "random-access-memory": "^6.0.0",
    "standard": "^17.1.0"
  },
  "license": "Apache-2.0",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/hypercore-id-encoding.git"
  },
  "keywords": [],
  "author": "",
  "bugs": {
    "url": "https://github.com/holepunchto/hypercore-id-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/hypercore-id-encoding#readme"
}
const c = require('compact-encoding')
const { getEncoding } = require('./spec/hyperschema')

const HyperdhtAddress = getEncoding('@hyperdht/address')

function decode(buf) {
  const addr = c.decode(HyperdhtAddress, buf)
  return addr
}

function encode(key, nodes) {
  return c.encode(HyperdhtAddress, { key, nodes })
}

module.exports = { decode, encode }
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return uint24.decode(state) + 0x1000000 * uint32.decode(state)
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return uint32.decode(state) + 0x100000000 * uint32.decode(state)
  }
})

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "2.19.2",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    if (b.byteLength === 0) return null
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "hyperdht-address",
  "version": "1.0.1",
  "description": "hyperdht-address",
  "main": "index.js",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    }
  },
  "files": [
    "package.json",
    "index.js",
    "index.d.ts",
    "spec"
  ],
  "devDependencies": {
    "b4a": "^1.8.0",
    "brittle": "^3.19.0",
    "lunte": "^1.2.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && lunte && brittle-bare test/index.js",
    "lint": "lunte"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/hyperdht-address.git"
  },
  "author": "Holepunch Inc",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/hyperdht-address/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperdht-address",
  "dependencies": {
    "compact-encoding": "^2.19.0",
    "hyperschema": "^1.20.1"
  }
}
// This file is autogenerated by the hyperschema compiler
// Schema Version: 2
/* eslint-disable camelcase */
/* eslint-disable quotes */
/* eslint-disable space-before-function-paren */

const { c } = require('hyperschema/runtime')

const VERSION = 2

// eslint-disable-next-line no-unused-vars
let version = VERSION

// @hyperdht/address.nodes
const encoding0_1 = c.array(c.ipv4Address)

// @hyperdht/address
const encoding0 = {
  preencode(state, m) {
    c.fixed32.preencode(state, m.key)
    state.end++ // max flag is 1 so always one byte

    if (version >= 2 && m.nodes) encoding0_1.preencode(state, m.nodes)
  },
  encode(state, m) {
    const flags = version >= 2 && m.nodes ? 1 : 0

    c.fixed32.encode(state, m.key)
    c.uint.encode(state, flags)

    if (version >= 2 && m.nodes) encoding0_1.encode(state, m.nodes)
  },
  decode(state) {
    const r0 = c.fixed32.decode(state)
    const flags = state.start < state.end ? c.uint.decode(state) : 0

    return {
      key: r0,
      nodes: version >= 2 && (flags & 1) !== 0 ? encoding0_1.decode(state) : null
    }
  }
}

function setVersion(v) {
  version = v
}

function encode(name, value, v = VERSION) {
  version = v
  return c.encode(getEncoding(name), value)
}

function decode(name, buffer, v = VERSION) {
  version = v
  return c.decode(getEncoding(name), buffer)
}

function getEnum(name) {
  switch (name) {
    default:
      throw new Error('Enum not found ' + name)
  }
}

function getEncoding(name) {
  switch (name) {
    case '@hyperdht/address':
      return encoding0
    default:
      throw new Error('Encoder not found ' + name)
  }
}

function getStruct(name, v = VERSION) {
  const enc = getEncoding(name)
  return {
    preencode(state, m) {
      version = v
      enc.preencode(state, m)
    },
    encode(state, m) {
      version = v
      enc.encode(state, m)
    },
    decode(state) {
      version = v
      return enc.decode(state)
    }
  }
}

const resolveStruct = getStruct // compat

module.exports = {
  resolveStruct,
  getStruct,
  getEnum,
  getEncoding,
  encode,
  decode,
  setVersion,
  version
}
const DHT = require('dht-rpc')
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const b4a = require('b4a')
const safetyCatch = require('safety-catch')
const m = require('./lib/messages')
const SocketPool = require('./lib/socket-pool')
const Persistent = require('./lib/persistent')
const Router = require('./lib/router')
const Cache = require('xache')
const Server = require('./lib/server')
const connect = require('./lib/connect')
const { FIREWALL, BOOTSTRAP_NODES, KNOWN_NODES, COMMANDS } = require('./lib/constants')
const { hash, createKeyPair } = require('./lib/crypto')
const RawStreamSet = require('./lib/raw-stream-set')
const ConnectionPool = require('./lib/connection-pool')
const { STREAM_NOT_CONNECTED } = require('./lib/errors')

const DEFAULTS = {
  ...DHT.DEFAULTS,
  connectionKeepAlive: 5000,
  randomPunchInterval: 20000
}

class HyperDHT extends DHT {
  constructor(opts = {}) {
    const port = opts.port || 49737
    const bootstrap = opts.bootstrap || BOOTSTRAP_NODES
    const nodes = opts.nodes || KNOWN_NODES

    super({ ...opts, port, bootstrap, nodes, filterNode })

    const { router, relayAddresses, persistent } = defaultCacheOpts(opts)

    this.defaultKeyPair = opts.keyPair || createKeyPair(opts.seed)
    this.listening = new Set()
    this.connectionKeepAlive =
      opts.connectionKeepAlive === false
        ? 0
        : opts.connectionKeepAlive || DEFAULTS.connectionKeepAlive

    // stats is inherited from dht-rpc so fwd the ones from there
    this.stats = {
      punches: { consistent: 0, random: 0, open: 0 },
      relaying: { attempts: 0, successes: 0, aborts: 0 },
      ...this.stats
    }
    this.rawStreams = new RawStreamSet(this)
    this.plugins = new Map()

    this._router = new Router(this, router)
    this._socketPool = new SocketPool(this, opts.host || '0.0.0.0')
    this._persistent = null
    this._validatedLocalAddresses = new Map()
    this._relayAddressesCache = new Cache(relayAddresses)

    this._deferRandomPunch = !!opts.deferRandomPunch
    this._lastRandomPunch = this._deferRandomPunch ? Date.now() : 0
    this._connectable = true
    this._randomPunchInterval = opts.randomPunchInterval || DEFAULTS.randomPunchInterval // min 20s between random punches...
    this._randomPunches = 0
    this._randomPunchLimit = 1 // set to one for extra safety for now

    this.once('persistent', () => {
      this._persistent = new Persistent(this, persistent)
      for (const plugin of this.plugins.values()) plugin.onpersistent()
    })

    this.on('network-change', () => {
      for (const server of this.listening) server.refresh()
    })

    this.on('network-update', () => {
      if (!this.online) return
      for (const server of this.listening) server.notifyOnline()
    })
  }

  static DEFAULTS = DEFAULTS

  connect(remotePublicKey, opts) {
    return connect(this, remotePublicKey, opts)
  }

  createServer(opts, onconnection) {
    if (typeof opts === 'function') return this.createServer({}, opts)
    if (opts && opts.onconnection) onconnection = opts.onconnection
    const s = new Server(this, opts)
    if (onconnection) s.on('connection', onconnection)
    return s
  }

  pool() {
    return new ConnectionPool(this)
  }

  async resume({ log = noop } = {}) {
    if (this._deferRandomPunch) this._lastRandomPunch = Date.now()
    await super.resume({ log })
    const resuming = []
    for (const server of this.listening) resuming.push(server.resume())
    log('Resuming hyperdht servers')
    await Promise.allSettled(resuming)
    log('Done, hyperdht fully resumed')
  }

  async suspend({ log = noop } = {}) {
    this._connectable = false // just so nothing gets connected during suspension
    const suspending = []
    for (const server of this.listening) suspending.push(server.suspend())
    log('Suspending all hyperdht servers')
    await Promise.allSettled(suspending)
    log('Done, clearing all raw streams')
    await this.rawStreams.clear()
    log('Done, suspending dht-rpc')
    await super.suspend({ log })
    log('Done, clearing raw streams again')
    await this.rawStreams.clear()
    log('Done, hyperdht fully suspended')
    this._connectable = true
  }

  async destroy({ force = false } = {}) {
    if (!force) {
      const closing = []
      for (const server of this.listening) closing.push(server.close())
      await Promise.allSettled(closing)
    }
    this._router.destroy()
    if (this._persistent) this._persistent.destroy()
    for (const plugin of this.plugins.values()) plugin.destroy()
    await this.rawStreams.clear()
    await this._socketPool.destroy()
    await super.destroy()
  }

  async validateLocalAddresses(addresses) {
    const list = []
    const socks = []
    const waiting = []

    for (const addr of addresses) {
      const { host } = addr

      if (this._validatedLocalAddresses.has(host)) {
        if (await this._validatedLocalAddresses.get(host)) {
          list.push(addr)
        }
        continue
      }

      const sock = this.udx.createSocket()
      try {
        sock.bind(0, host)
      } catch {
        this._validatedLocalAddresses.set(host, Promise.resolve(false))
        continue
      }

      socks.push(sock)

      // semi terrible heuristic until we proper fix local connections by racing them to the remote...
      const promise = new Promise((resolve) => {
        sock.on('message', () => resolve(true))
        setTimeout(() => resolve(false), 500)
        sock.trySend(b4a.alloc(1), sock.address().port, addr.host)
      })

      this._validatedLocalAddresses.set(host, promise)
      waiting.push(addr)
    }

    for (const addr of waiting) {
      const { host } = addr
      if (this._validatedLocalAddresses.has(host)) {
        if (await this._validatedLocalAddresses.get(host)) {
          list.push(addr)
        }
        continue
      }
    }

    for (const sock of socks) await sock.close()

    return list
  }

  findPeer(publicKey, opts = {}) {
    const target = opts.hash === false ? publicKey : hash(publicKey)
    opts = { ...opts, map: mapFindPeer }
    return this.query({ target, command: COMMANDS.FIND_PEER, value: null }, opts)
  }

  lookup(target, opts = {}) {
    opts = { ...opts, map: mapLookup }
    return this.query({ target, command: COMMANDS.LOOKUP, value: null }, opts)
  }

  lookupAndUnannounce(target, keyPair, opts = {}) {
    const unannounces = []
    const dht = this
    const userCommit = opts.commit || noop
    const signUnannounce = opts.signUnannounce || Persistent.signUnannounce

    if (this._persistent !== null) {
      // unlink self
      this._persistent.unannounce(target, keyPair.publicKey)
    }

    opts = { ...opts, map, commit }
    return this.query({ target, command: COMMANDS.LOOKUP, value: null }, opts)

    async function commit(reply, dht, query) {
      await Promise.all(unannounces) // can never fail, caught below
      return userCommit(reply, dht, query)
    }

    function map(reply) {
      const data = mapLookup(reply)

      if (!data || !data.token) return data

      let found = data.peers.length >= 20
      for (let i = 0; !found && i < data.peers.length; i++) {
        found = b4a.equals(data.peers[i].publicKey, keyPair.publicKey)
      }

      if (!found) return data

      if (!data.from.id) return data

      unannounces.push(
        dht
          ._requestUnannounce(keyPair, dht, target, data.token, data.from, signUnannounce)
          .catch(safetyCatch)
      )

      return data
    }
  }

  unannounce(target, keyPair, opts = {}) {
    return this.lookupAndUnannounce(target, keyPair, opts).finished()
  }

  announce(target, keyPair, relayAddresses, opts = {}) {
    const signAnnounce = opts.signAnnounce || Persistent.signAnnounce
    const bump = opts.bump || 0

    opts = { ...opts, commit }

    return opts.clear ? this.lookupAndUnannounce(target, keyPair, opts) : this.lookup(target, opts)

    function commit(reply, dht) {
      return dht._requestAnnounce(
        keyPair,
        dht,
        target,
        reply.token,
        reply.from,
        relayAddresses,
        signAnnounce,
        bump
      )
    }
  }

  async immutableGet(target, opts = {}) {
    opts = { ...opts, map: mapImmutable }

    const query = this.query({ target, command: COMMANDS.IMMUTABLE_GET, value: null }, opts)
    const check = b4a.allocUnsafe(32)

    for await (const node of query) {
      const { value } = node
      sodium.crypto_generichash(check, value)
      if (b4a.equals(check, target)) return node
    }

    return null
  }

  async immutablePut(value, opts = {}) {
    const target = b4a.allocUnsafe(32)
    sodium.crypto_generichash(target, value)

    opts = {
      ...opts,
      map: mapImmutable,
      commit(reply, dht) {
        return dht.request(
          { token: reply.token, target, command: COMMANDS.IMMUTABLE_PUT, value },
          reply.from
        )
      }
    }

    const query = this.query({ target, command: COMMANDS.IMMUTABLE_GET, value: null }, opts)
    await query.finished()

    return { hash: target, closestNodes: query.closestNodes }
  }

  async mutableGet(publicKey, opts = {}) {
    let refresh = opts.refresh || null
    let signed = null
    let result = null

    opts = { ...opts, map: mapMutable, commit: refresh ? commit : null }

    const target = b4a.allocUnsafe(32)
    sodium.crypto_generichash(target, publicKey)

    const userSeq = opts.seq || 0
    const query = this.query(
      { target, command: COMMANDS.MUTABLE_GET, value: c.encode(c.uint, userSeq) },
      opts
    )
    const latest = opts.latest !== false

    for await (const node of query) {
      if (result && node.seq <= result.seq) continue
      if (
        node.seq < userSeq ||
        !Persistent.verifyMutable(node.signature, node.seq, node.value, publicKey)
      )
        continue
      if (!latest) return node
      if (!result || node.seq > result.seq) result = node
    }

    return result

    function commit(reply, dht) {
      if (!signed && result && refresh) {
        if (refresh(result)) {
          signed = c.encode(m.mutablePutRequest, {
            publicKey,
            seq: result.seq,
            value: result.value,
            signature: result.signature
          })
        } else {
          refresh = null
        }
      }

      return signed
        ? dht.request(
            { token: reply.token, target, command: COMMANDS.MUTABLE_PUT, value: signed },
            reply.from
          )
        : Promise.resolve(null)
    }
  }

  async mutablePut(keyPair, value, opts = {}) {
    const signMutable = opts.signMutable || Persistent.signMutable

    const target = b4a.allocUnsafe(32)
    sodium.crypto_generichash(target, keyPair.publicKey)

    const seq = opts.seq || 0
    const signature = await signMutable(seq, value, keyPair)

    const signed = c.encode(m.mutablePutRequest, {
      publicKey: keyPair.publicKey,
      seq,
      value,
      signature
    })

    opts = {
      ...opts,
      map: mapMutable,
      commit(reply, dht) {
        return dht.request(
          { token: reply.token, target, command: COMMANDS.MUTABLE_PUT, value: signed },
          reply.from
        )
      }
    }

    // use seq = 0, for the query part here, as we don't care about the actual values
    const query = this.query(
      { target, command: COMMANDS.MUTABLE_GET, value: c.encode(c.uint, 0) },
      opts
    )
    await query.finished()

    return { publicKey: keyPair.publicKey, closestNodes: query.closestNodes, seq, signature }
  }

  onrequest(req) {
    switch (req.command) {
      case COMMANDS.PEER_HANDSHAKE: {
        this._router.onpeerhandshake(req)
        return true
      }
      case COMMANDS.PEER_HOLEPUNCH: {
        this._router.onpeerholepunch(req)
        return true
      }
    }

    if (this._persistent === null || this.id === null) return false

    switch (req.command) {
      case COMMANDS.FIND_PEER: {
        this._persistent.onfindpeer(req)
        return true
      }
      case COMMANDS.LOOKUP: {
        this._persistent.onlookup(req)
        return true
      }
      case COMMANDS.ANNOUNCE: {
        this._persistent.onannounce(req)
        return true
      }
      case COMMANDS.UNANNOUNCE: {
        this._persistent.onunannounce(req)
        return true
      }
      case COMMANDS.MUTABLE_PUT: {
        this._persistent.onmutableput(req)
        return true
      }
      case COMMANDS.MUTABLE_GET: {
        this._persistent.onmutableget(req)
        return true
      }
      case COMMANDS.IMMUTABLE_PUT: {
        this._persistent.onimmutableput(req)
        return true
      }
      case COMMANDS.IMMUTABLE_GET: {
        this._persistent.onimmutableget(req)
        return true
      }
      case COMMANDS.PLUGIN: {
        this._persistent.onplugin(req)
        return true
      }
    }

    return false
  }

  static keyPair(seed) {
    return createKeyPair(seed)
  }

  static hash(data) {
    return hash(data)
  }

  static connectRawStream(encryptedStream, rawStream, remoteId) {
    const stream = encryptedStream.rawStream

    if (!stream.connected) throw STREAM_NOT_CONNECTED()

    rawStream.connect(stream.socket, remoteId, stream.remotePort, stream.remoteHost)
  }

  createRawStream(opts) {
    return this.rawStreams.add(opts)
  }

  async _requestAnnounce(keyPair, dht, target, token, from, relayAddresses, sign, bump) {
    const ann = {
      peer: {
        publicKey: keyPair.publicKey,
        relayAddresses: relayAddresses || []
      },
      refresh: null,
      signature: null,
      bump
    }

    ann.signature = await sign(target, token, from.id, ann, keyPair)

    const value = c.encode(m.announce, ann)

    return dht.request(
      {
        token,
        target,
        command: COMMANDS.ANNOUNCE,
        value
      },
      from
    )
  }

  async _requestUnannounce(keyPair, dht, target, token, from, sign) {
    const unann = {
      peer: {
        publicKey: keyPair.publicKey,
        relayAddresses: []
      },
      signature: null
    }

    unann.signature = await sign(target, token, from.id, unann, keyPair)

    const value = c.encode(m.announce, unann)

    return dht.request(
      {
        token,
        target,
        command: COMMANDS.UNANNOUNCE,
        value
      },
      from
    )
  }

  register(name, plugin) {
    this.plugins.set(name, plugin)
    plugin.onregister(this)
  }
}

HyperDHT.BOOTSTRAP = BOOTSTRAP_NODES
HyperDHT.FIREWALL = FIREWALL

module.exports = HyperDHT

function mapLookup(node) {
  if (!node.value) return null

  try {
    const l = c.decode(m.lookupRawReply, node.value)

    return {
      token: node.token,
      from: node.from,
      to: node.to,
      peers: l.peers,
      bump: l.bump
    }
  } catch {
    return null
  }
}

function mapFindPeer(node) {
  if (!node.value) return null

  try {
    return {
      token: node.token,
      from: node.from,
      to: node.to,
      peer: c.decode(m.peer, node.value)
    }
  } catch {
    return null
  }
}

function mapImmutable(node) {
  if (!node.value) return null

  return {
    token: node.token,
    from: node.from,
    to: node.to,
    value: node.value
  }
}

function mapMutable(node) {
  if (!node.value) return null

  try {
    const { seq, value, signature } = c.decode(m.mutableGetResponse, node.value)

    return {
      token: node.token,
      from: node.from,
      to: node.to,
      seq,
      value,
      signature
    }
  } catch {
    return null
  }
}

function noop() {}

function filterNode(node) {
  // always skip these testnet nodes that got mixed in by accident, until they get updated
  return (
    !(node.port === 49738 && (node.host === '134.209.28.98' || node.host === '167.99.142.185')) &&
    !(node.port === 9400 && node.host === '35.233.47.252') &&
    !(node.host === '150.136.142.116')
  )
}

const defaultMaxSize = 65536
const defaultMaxAge = 20 * 60 * 1000 // 20 minutes

function defaultCacheOpts(opts) {
  const maxSize = opts.maxSize || defaultMaxSize
  const maxAge = opts.maxAge || defaultMaxAge

  return {
    router: {
      forwards: { maxSize, maxAge }
    },
    relayAddresses: { maxSize: Math.min(maxSize, 512), maxAge: 0 },
    persistent: {
      records: { maxSize, maxAge },
      refreshes: { maxSize, maxAge },
      mutables: {
        maxSize: (maxSize / 2) | 0,
        maxAge: opts.maxAge || 48 * 60 * 60 * 1000 // 48 hours
      },
      immutables: {
        maxSize: (maxSize / 2) | 0,
        maxAge: opts.maxAge || 48 * 60 * 60 * 1000 // 48 hours
      },
      bumps: { maxSize, maxAge }
    }
  }
}
const safetyCatch = require('safety-catch')
const c = require('compact-encoding')
const Signal = require('signal-promise')
const { encodeUnslab } = require('./encode')
const Sleeper = require('./sleeper')
const m = require('./messages')
const Persistent = require('./persistent')
const { COMMANDS } = require('./constants')

const MIN_ACTIVE = 3

module.exports = class Announcer {
  constructor(dht, keyPair, target, opts = {}) {
    this.dht = dht
    this.keyPair = keyPair
    this.target = target
    this.relays = []
    this.relayAddresses = []
    this.stopped = false
    this.suspended = false
    this.record = encodeUnslab(m.peer, { publicKey: keyPair.publicKey, relayAddresses: [] })
    this.online = new Signal()

    this._refreshing = false
    this._closestNodes = null
    this._active = null
    this._sleeper = new Sleeper()
    this._resumed = new Signal()
    this._signAnnounce = opts.signAnnounce || Persistent.signAnnounce
    this._signUnannounce = opts.signUnannounce || Persistent.signUnannounce
    this._updating = null
    this._activeQuery = null
    this._unannouncing = null

    this._serverRelays = [new Map(), new Map(), new Map()]
  }

  isRelay(addr) {
    const id = addr.host + ':' + addr.port
    const [a, b, c] = this._serverRelays
    return a.has(id) || b.has(id) || c.has(id)
  }

  async suspend({ log = noop } = {}) {
    if (this.suspended) return
    this.suspended = true

    log('Suspending announcer')

    // Suspend has its own sleep logic
    // so we don't want to hang on this one
    this.online.notify()

    if (this._activeQuery) this._activeQuery.destroy()

    this._sleeper.resume()
    if (this._updating) await this._updating
    log('Suspending announcer (post update)')

    if (this.suspended === false || this.stopped) return

    log('Suspending announcer (pre unannounce)')
    await this._unannounceCurrent()
    log('Suspending announcer (post unannounce)')
  }

  resume() {
    if (!this.suspended) return
    this.suspended = false

    this.refresh()
    this._sleeper.resume()
    this._resumed.notify()
  }

  refresh() {
    if (this.stopped) return
    this._refreshing = true
  }

  async start() {
    if (this.stopped) return
    this._active = this._runUpdate()
    await this._active
    if (this.stopped) return
    this._active = this._background()
  }

  async stop() {
    this.stopped = true
    this.online.notify() // Break out of the _background loop if we're offline
    this._sleeper.resume()
    this._resumed.notify()
    await this._active
    await this._unannounceCurrent()
  }

  async _unannounceCurrent() {
    while (this._unannouncing !== null) await this._unannouncing
    const un = (this._unannouncing = this._unannounceAll(this._serverRelays[2].values()))
    await this._unannouncing
    if (un === this._unannouncing) this._unannouncing = null
  }

  async _background() {
    while (!this.dht.destroyed && !this.stopped) {
      try {
        this._refreshing = false

        // ~5min +-
        for (let i = 0; i < 100 && !this.stopped && !this._refreshing && !this.suspended; i++) {
          const pings = []

          for (const node of this._serverRelays[2].values()) {
            pings.push(this.dht.ping(node))
          }

          const active = await resolved(pings)
          if (active < Math.min(pings.length, MIN_ACTIVE)) {
            this.refresh() // we lost too many relay nodes, retry all
          }

          if (this.stopped) return

          if (!this.suspended && !this._refreshing) await this._sleeper.pause(3000)
        }

        while (!this.stopped && this.suspended) await this._resumed.wait()

        if (!this.stopped) await this._runUpdate()

        while (!this.dht.online && !this.stopped && !this.suspended) {
          // Being offline can make _background repeat very quickly
          // So wait until we're back online
          await this.online.wait()
        }
      } catch (err) {
        safetyCatch(err)
      }
    }
  }

  async _runUpdate() {
    this._updating = this._update()
    await this._updating
    this._updating = null
  }

  async _update() {
    while (this._unannouncing) await this._unannouncing

    this._cycle()

    const q = (this._activeQuery = this.dht.findPeer(this.target, {
      hash: false,
      nodes: this._closestNodes
    }))

    try {
      await q.finished()
    } catch {
      // ignore failures...
    }

    this._activeQuery = null

    if (this.stopped || this.suspended) return

    const ann = []
    const replies = pickBest(q.closestReplies)

    const relays = []
    const relayAddresses = []

    if (!this.dht.firewalled) {
      const addr = this.dht.remoteAddress()
      if (addr) relayAddresses.push(addr)
    }

    for (const msg of replies) {
      ann.push(this._commit(msg, relays, relayAddresses))
    }

    await Promise.allSettled(ann)
    if (this.stopped || this.suspended) return

    this._closestNodes = q.closestNodes
    this.relays = relays
    this.relayAddresses = relayAddresses

    const removed = []
    for (const [key, value] of this._serverRelays[1]) {
      if (!this._serverRelays[2].has(key)) removed.push(value)
    }

    await this._unannounceAll(removed)
  }

  _unannounceAll(relays) {
    const unann = []
    for (const r of relays) unann.push(this._unannounce(r))
    return Promise.allSettled(unann)
  }

  async _unannounce(to) {
    const unann = {
      peer: {
        publicKey: this.keyPair.publicKey,
        relayAddresses: []
      },
      refresh: null,
      signature: null
    }

    const { from, token, value } = await this.dht.request(
      {
        token: null,
        command: COMMANDS.FIND_PEER,
        target: this.target,
        value: null
      },
      to
    )

    if (!token || !from.id || !value) return

    unann.signature = await this._signUnannounce(this.target, token, from.id, unann, this.keyPair)

    await this.dht.request(
      {
        token,
        command: COMMANDS.UNANNOUNCE,
        target: this.target,
        value: c.encode(m.announce, unann)
      },
      to
    )
  }

  async _commit(msg, relays, relayAddresses) {
    const ann = {
      peer: {
        publicKey: this.keyPair.publicKey,
        relayAddresses: []
      },
      refresh: null,
      signature: null
    }

    ann.signature = await this._signAnnounce(this.target, msg.token, msg.from.id, ann, this.keyPair)

    const res = await this.dht.request(
      {
        token: msg.token,
        command: COMMANDS.ANNOUNCE,
        target: this.target,
        value: c.encode(m.announce, ann)
      },
      msg.from
    )

    if (res.error !== 0) return

    if (relayAddresses.length < 3) relayAddresses.push({ host: msg.from.host, port: msg.from.port })
    relays.push({ relayAddress: msg.from, peerAddress: msg.to })

    this._serverRelays[2].set(msg.from.host + ':' + msg.from.port, msg.from)
  }

  _cycle() {
    const tmp = this._serverRelays[0]
    this._serverRelays[0] = this._serverRelays[1]
    this._serverRelays[1] = this._serverRelays[2]
    this._serverRelays[2] = tmp
    tmp.clear()
  }
}

function resolved(ps) {
  let replied = 0
  let ticks = ps.length + 1

  return new Promise((resolve) => {
    for (const p of ps) p.then(push, tick)
    tick()

    function push(v) {
      replied++
      tick()
    }

    function tick() {
      if (--ticks === 0) resolve(replied)
    }
  })
}

function pickBest(replies) {
  // TODO: pick the ones closest to us RTT wise
  return replies.slice(0, 3)
}

function noop() {}
const NoiseSecretStream = require('@hyperswarm/secret-stream')
const b4a = require('b4a')
const relay = require('blind-relay')
const { isReserved, isBogon } = require('bogon')
const safetyCatch = require('safety-catch')
const unslab = require('unslab')
const Semaphore = require('./semaphore')
const NoiseWrap = require('./noise-wrap')
const SecurePayload = require('./secure-payload')
const Holepuncher = require('./holepuncher')
const Sleeper = require('./sleeper')
const { FIREWALL, ERROR } = require('./constants')
const { unslabbedHash } = require('./crypto')
const {
  CANNOT_HOLEPUNCH,
  HANDSHAKE_INVALID,
  HOLEPUNCH_ABORTED,
  HOLEPUNCH_INVALID,
  HOLEPUNCH_PROBE_TIMEOUT,
  HOLEPUNCH_DOUBLE_RANDOMIZED_NATS,
  PEER_CONNECTION_FAILED,
  PEER_NOT_FOUND,
  REMOTE_ABORTED,
  REMOTE_NOT_HOLEPUNCHABLE,
  REMOTE_NOT_HOLEPUNCHING,
  SERVER_ERROR,
  SERVER_INCOMPATIBLE,
  RELAY_ABORTED,
  SUSPENDED
} = require('./errors')
const { decode } = require('hypercore-id-encoding')
const HyperDHTAddress = require('hyperdht-address')

module.exports = function connect(dht, publicKey, opts = {}) {
  const pool = opts.pool || null

  const { key, nodes: providedNodes } = HyperDHTAddress.decode(
    b4a.isBuffer(publicKey) ? publicKey : decode(publicKey)
  )
  publicKey = key

  if (pool && pool.has(publicKey)) return pool.get(publicKey)

  publicKey = unslab(publicKey)

  opts.relayAddresses = opts.relayAddresses || providedNodes || []
  const keyPair = opts.keyPair || dht.defaultKeyPair
  const relayThrough = selectRelay(opts.relayThrough || null)
  const encryptedSocket = (opts.createSecretStream || defaultCreateSecretStream)(true, null, {
    publicKey: keyPair.publicKey,
    remotePublicKey: publicKey,
    autoStart: false,
    keepAlive: dht.connectionKeepAlive
  })

  // in case a socket is made during suspended state, destroy it immediately
  if (dht.suspended || !dht._connectable) {
    encryptedSocket.destroy(SUSPENDED())
    return encryptedSocket
  }

  if (pool) pool._attachStream(encryptedSocket, false)

  const id = b4a.toString(publicKey, 'hex')
  const c = {
    id,
    dht,
    session: dht.session(),
    relayAddresses: opts.relayAddresses,
    remoteRelayAddresses: [],
    pool,
    round: 0,
    target: unslabbedHash(publicKey),
    remotePublicKey: publicKey,
    reusableSocket: !!opts.reusableSocket,
    handshake: (opts.createHandshake || defaultCreateHandshake)(keyPair, publicKey),
    request: null,
    requesting: false,
    lan: opts.localConnection !== false,
    firewall: FIREWALL.UNKNOWN,
    rawStream: dht.createRawStream({ framed: true, firewall }),
    connect: null,
    query: null,
    puncher: null,
    payload: null,
    passiveConnectTimeout: null,
    serverSocket: null,
    serverAddress: null,
    onsocket: null,
    sleeper: new Sleeper(),
    encryptedSocket,

    // Relay state
    relayTimeout: null,
    relayThrough,
    relayToken: relayThrough ? relay.token() : null,
    relaySocket: null,
    relayClient: null,
    relayPaired: false,
    relayKeepAlive: opts.relayKeepAlive || 5000
  }

  // If the raw stream receives an error signal pre connect (ie from the firewall hook), make sure
  // to forward that to the encrypted socket for proper teardown
  c.rawStream.on('error', autoDestroy)
  c.rawStream.once('connect', () => {
    c.rawStream.removeListener('error', autoDestroy)
  })

  encryptedSocket.on('close', function () {
    if (c.passiveConnectTimeout) clearPassiveConnectTimeout(c)
    if (c.query) c.query.destroy()
    if (c.puncher) c.puncher.destroy()
    if (c.rawStream) c.rawStream.destroy()
    c.session.destroy()
    c.sleeper.resume()
  })

  // Safe to run in the background - never throws
  if (dht.suspended) encryptedSocket.destroy(SUSPENDED())
  else connectAndHolepunch(c, opts)

  return encryptedSocket

  function autoDestroy(err) {
    maybeDestroyEncryptedSocket(c, err)
  }

  function firewall(socket, port, host) {
    // Check if the traffic originated from the socket on which we're expecting relay traffic. If so,
    // we haven't hole punched yet and the other side is just sending us traffic through the relay.
    if (c.relaySocket && isRelay(c.relaySocket, socket, port, host)) {
      return false
    }

    if (c.onsocket) {
      c.onsocket(socket, port, host)
    } else {
      c.serverSocket = socket
      c.serverAddress = { port, host }
    }
    return false
  }
}

function isDone(c) {
  // we are destroying or the puncher is connected - done
  if (c.encryptedSocket.destroying || !!(c.puncher && c.puncher.connected)) {
    return true
  }
  // not destroying, but no raw stream - def not done
  if (c.encryptedSocket.rawStream === null) {
    return false
  }
  // we are relayed, but the puncher is not done yet
  if (c.relaySocket && !!(c.puncher && !c.puncher.connected && !c.puncher.destroyed)) {
    return false
  }
  // we are done
  return true
}

async function retryRoute(c, route) {
  const ref = c.dht._socketPool.lookup(route.socket)

  if (!ref) {
    if (route.socket === c.dht.socket) {
      await connectThroughNode(c, route.address, c.dht.socket)
    }
    return
  }

  ref.active()

  try {
    await connectThroughNode(c, route.address, route.socket)
  } catch {
    // if error, just ignore, and continue through the existing strat
  }

  ref.inactive()
}

async function connectAndHolepunch(c, opts) {
  const route = c.reusableSocket ? c.dht._socketPool.routes.get(c.remotePublicKey) : null

  if (route) {
    await retryRoute(c, route)
    if (isDone(c)) return
  }

  await findAndConnect(c, opts)
  if (isDone(c)) return

  if (!c.connect) {
    // TODO: just a quick fix for now, should retry prob
    maybeDestroyEncryptedSocket(c, HANDSHAKE_INVALID())
    return
  }

  await holepunch(c, opts)
}

function getFirstRemoteAddress(addrs, serverAddress) {
  for (const addr of addrs) {
    if (isBogon(addr.host)) continue
    return addr
  }

  return serverAddress
}

async function holepunch(c, opts) {
  let { relayAddress, serverAddress, clientAddress, payload } = c.connect

  const remoteHolepunchable = !!(payload.holepunch && payload.holepunch.relays.length)

  const relayed = diffAddress(serverAddress, relayAddress)

  if (payload.firewall === FIREWALL.OPEN || (relayed && !remoteHolepunchable)) {
    const addr = getFirstRemoteAddress(payload.addresses4, serverAddress)
    if (addr) {
      const socket = c.dht.socket
      c.dht.stats.punches.open++
      c.onsocket(socket, addr.port, addr.host)
      return
    }
    // TODO: check all addresses also obvs
  }

  const onabort = () => {
    c.session.destroy()
    maybeDestroyEncryptedSocket(c, HOLEPUNCH_ABORTED())
  }

  if (c.firewall === FIREWALL.OPEN) {
    c.passiveConnectTimeout = setTimeout(onabort, 10000)
    return
  }

  // TODO: would be better to just try local addrs in the background whilst continuing with other strategies...
  if (c.lan && relayed && clientAddress.host === serverAddress.host) {
    const serverAddresses = payload.addresses4.filter(onlyNonReserved)

    if (serverAddresses.length > 0) {
      const myAddresses = Holepuncher.localAddresses(c.dht.io.serverSocket)
      const addr = Holepuncher.matchAddress(myAddresses, serverAddresses) || serverAddresses[0]

      const socket = c.dht.io.serverSocket
      try {
        await c.dht.ping(addr)
      } catch {
        maybeDestroyEncryptedSocket(c, HOLEPUNCH_ABORTED())
        return
      }
      c.onsocket(socket, addr.port, addr.host)
      return
    }
  }

  if (!remoteHolepunchable) {
    maybeDestroyEncryptedSocket(c, CANNOT_HOLEPUNCH())
    return
  }

  c.puncher = new Holepuncher(c.dht, c.session, true, payload.firewall)

  c.puncher.onconnect = c.onsocket
  c.puncher.onabort = onabort

  const serverRelay = pickServerRelay(payload.holepunch.relays, relayAddress)

  // Begin holepunching!

  let probe
  try {
    probe = await probeRound(c, opts.fastOpen === false ? null : serverAddress, serverRelay, true)
  } catch (err) {
    destroyPuncher(c)
    // TODO: we should retry here with some of the other relays, bail for now
    maybeDestroyEncryptedSocket(c, err)
    return
  }

  if (isDone(c) || !probe) return
  const { token, peerAddress } = probe

  // If the relay the server picked is the same as the relay the client picked,
  // then we can use the peerAddress that round one indicates the server wants to use.
  // This shaves off a roundtrip if the server chose to reroll its socket due to some NAT
  // issue with the first one it picked (ie mobile nat inconsistencies...).
  // If the relays were different, then the server would not have a UDP session open on this address
  // to the client relay, which round2 uses.
  if (
    !diffAddress(serverRelay.relayAddress, relayAddress) &&
    diffAddress(serverAddress, peerAddress)
  ) {
    serverAddress = peerAddress
    await c.puncher.openSession(serverAddress)
    if (isDone(c)) return
  }

  // TODO: still continue here if a local connection might work, but then do not holepunch...
  if (
    opts.holepunch &&
    !opts.holepunch(
      c.puncher.remoteFirewall,
      c.puncher.nat.firewall,
      c.puncher.remoteAddresses,
      c.puncher.nat.addresses
    )
  ) {
    await abort(c, serverRelay, HOLEPUNCH_ABORTED('Client aborted holepunch'))
    return
  }

  try {
    await roundPunch(c, serverAddress, token, relayAddress, serverRelay, false)
  } catch (err) {
    destroyPuncher(c)
    // TODO: retry with another relay?
    maybeDestroyEncryptedSocket(c, err)
  }
}

async function connectThroughNodes(c, addresses, socket) {
  for (const address of addresses) {
    if (isDone(c) || c.connect) return

    c.remoteRelayAddresses.push(address)
    await connectThroughNode(c, address, socket)
  }
}

async function findAndConnect(c, opts) {
  let attempts = 0
  let relayAddresses =
    opts.relayAddresses && opts.relayAddresses.length ? opts.relayAddresses : null

  if (!relayAddresses) {
    const cachedRelayAddresses = c.dht._relayAddressesCache.get(c.id)
    if (cachedRelayAddresses) relayAddresses = cachedRelayAddresses
  }

  if (c.dht._persistent) {
    // check if we know the route ourself...
    const route = c.dht._router.get(c.target)
    if (route && route.relay !== null) {
      relayAddresses = [{ host: route.relay.host, port: route.relay.port }]
    }
  }

  // 2 is how many parallel connect attempts we want to do, we can make this configurable
  const preConnect = relayAddresses !== null && relayAddresses.length > 0
  const sem = new Semaphore(preConnect ? 3 : 2)
  const signal = sem.signal.bind(sem)
  const tries = relayAddresses !== null ? 2 : 1

  if (preConnect) {
    await sem.wait()
    connectThroughNodes(c, relayAddresses, null).then(signal, signal)
  }

  try {
    for (let i = 0; i < tries && !isDone(c) && !c.connect; i++) {
      c.query = c.dht.findPeer(c.target, {
        hash: false,
        session: c.session,
        nodes: relayAddresses,
        retries: 3
      })

      for await (const data of c.query) {
        await sem.wait()
        if (isDone(c)) return

        if (c.connect) {
          sem.signal()
          break
        }

        // Skip node already run via preConnect
        if (preConnect && relayAddresses && isRelayAddress(relayAddresses, data)) {
          sem.signal()
          continue
        }

        c.remoteRelayAddresses.push(data.from)
        attempts++
        connectThroughNode(c, data.from, null).then(signal, signal)
      }

      relayAddresses = null

      if (attempts > 0) await sem.flush()
    }

    c.query = null
    if (isDone(c)) return

    // flush the semaphore
    await sem.flush()
    if (isDone(c)) return
  } catch (err) {
    c.query = null
    maybeDestroyEncryptedSocket(c, err)
    return
  }

  if (!c.connect) {
    maybeDestroyEncryptedSocket(c, attempts ? PEER_CONNECTION_FAILED() : PEER_NOT_FOUND())
  }
}

async function connectThroughNode(c, address, socket) {
  if (!c.requesting) {
    // If we have a stable server address, send it over now
    const addr = c.dht.remoteAddress()
    const localAddrs = c.lan ? Holepuncher.localAddresses(c.dht.io.serverSocket) : null
    const addresses4 = []

    if (addr) addresses4.push(addr)
    if (localAddrs) addresses4.push(...localAddrs)

    c.firewall = addr ? FIREWALL.OPEN : FIREWALL.UNKNOWN
    c.requesting = true
    c.request = await c.handshake.send({
      error: ERROR.NONE,
      firewall: c.firewall,
      holepunch: null,
      addresses4,
      addresses6: [],
      udx: {
        reusableSocket: c.reusableSocket,
        id: c.rawStream.id,
        seq: 0
      },
      secretStream: {},
      relayThrough: c.relayThrough ? { publicKey: c.relayThrough, token: c.relayToken } : null
    })
    if (isDone(c)) return
  }

  const { serverAddress, clientAddress, relayed, noise } = await c.dht._router.peerHandshake(
    c.target,
    { noise: c.request, socket, session: c.session },
    address
  )
  if (isDone(c) || c.connect) return

  const payload = await c.handshake.recv(noise)
  if (isDone(c) || !payload) return

  if (payload.version !== 1) {
    maybeDestroyEncryptedSocket(c, SERVER_INCOMPATIBLE())
    return
  }
  if (payload.error !== ERROR.NONE) {
    maybeDestroyEncryptedSocket(c, SERVER_ERROR())
    return
  }
  if (!payload.udx) {
    maybeDestroyEncryptedSocket(c, SERVER_ERROR('Server did not send UDX data'))
    return
  }

  const hs = c.handshake.final()

  c.handshake = null
  c.request = null
  c.requesting = false
  c.connect = {
    relayed,
    relayAddress: address,
    clientAddress,
    serverAddress,
    payload
  }

  c.payload = new SecurePayload(hs.holepunchSecret)

  c.onsocket = function (socket, port, host) {
    if (c.rawStream === null) return // Already hole punched

    if (c.rawStream.connected) {
      const remoteChanging = c.rawStream.changeRemote(socket, c.connect.payload.udx.id, port, host)

      if (remoteChanging) remoteChanging.catch(safetyCatch)
    } else {
      // cache the relay addrs for a future reconnect, we prefer the remote one so they
      // can give us the correct ones from their pov
      if (payload.relayAddresses && payload.relayAddresses.length) {
        c.dht._relayAddressesCache.set(c.id, payload.relayAddresses)
      } else if (c.remoteRelayAddresses.length) {
        c.dht._relayAddressesCache.set(c.id, c.remoteRelayAddresses)
      }

      c.rawStream.connect(socket, c.connect.payload.udx.id, port, host)
      c.encryptedSocket.start(c.rawStream, { handshake: hs })
    }

    if (c.reusableSocket && payload.udx.reusableSocket) {
      c.dht._socketPool.routes.add(c.remotePublicKey, c.rawStream)
    }

    if (c.puncher) {
      c.puncher.onabort = noop
      c.puncher.destroy()
    }

    if (c.passiveConnectTimeout) {
      clearPassiveConnectTimeout(c)
    }

    c.rawStream = null
  }

  if (payload.relayThrough || c.relayThrough) {
    relayConnection(c, c.relayThrough, payload, hs)
  }

  if (c.serverSocket) {
    c.onsocket(c.serverSocket, c.serverAddress.port, c.serverAddress.host)
    return
  }

  if (!relayed) {
    c.onsocket(socket || c.dht.socket, address.port, address.host)
  }

  c.session.destroy()
}

async function updateHolepunch(c, peerAddress, relayAddr, payload) {
  const holepunch = await c.dht._router.peerHolepunch(
    c.target,
    {
      id: c.connect.payload.holepunch.id,
      payload: c.payload.encrypt(payload),
      peerAddress,
      socket: c.puncher.socket,
      session: c.session
    },
    relayAddr
  )

  if (isDone(c)) return null

  const remotePayload = c.payload.decrypt(holepunch.payload)
  if (!remotePayload) {
    throw HOLEPUNCH_INVALID()
  }

  const { error, firewall, punching, addresses, remoteToken } = remotePayload

  if (error === ERROR.TRY_LATER && c.relayToken && payload.punching) {
    return {
      tryLater: true,
      ...holepunch,
      payload: remotePayload
    }
  }

  if (error !== ERROR.NONE) {
    throw REMOTE_ABORTED('Remote aborted with error code ' + error)
  }

  const echoed = !!(remoteToken && payload.token && b4a.equals(remoteToken, payload.token))

  c.puncher.updateRemote({
    punching,
    firewall,
    addresses,
    verified: echoed ? peerAddress.host : null
  })

  return {
    tryLater: false,
    ...holepunch,
    payload: remotePayload
  }
}

async function probeRound(c, serverAddress, serverRelay, retry) {
  // Open a quick low ttl session against what we think is the server
  if (serverAddress) await c.puncher.openSession(serverAddress)

  if (isDone(c)) return null

  const reply = await updateHolepunch(c, serverRelay.peerAddress, serverRelay.relayAddress, {
    error: ERROR.NONE,
    firewall: c.puncher.nat.firewall,
    round: c.round++,
    connected: false,
    punching: false,
    addresses: c.puncher.nat.addresses,
    remoteAddress: serverAddress,
    token: null,
    remoteToken: null
  })

  if (isDone(c) || !reply) return null

  const { peerAddress } = reply
  const { address, token } = reply.payload

  c.puncher.nat.add(reply.to, reply.from)

  // Open another quick low ttl session against what the server says their address is,
  // if they haven't said they are random yet
  if (
    c.puncher.remoteFirewall < FIREWALL.RANDOM &&
    address &&
    address.host &&
    address.port &&
    diffAddress(address, serverAddress)
  ) {
    await c.puncher.openSession(address)
    if (isDone(c)) return null
  }

  // If the remote told us they didn't know their nat firewall yet, give them a chance to figure it out
  // They might say this to see if the "fast mode" punch comes through first.
  if (c.puncher.remoteFirewall === FIREWALL.UNKNOWN) {
    await c.sleeper.pause(1000)
    if (isDone(c)) return null
  }

  let stable = await c.puncher.analyze(false)
  if (isDone(c)) return null

  // If the socket seems unstable, try to make it stable by setting the "allowReopen" flag
  // Mostly relevant for mobile networks
  if (!stable) {
    stable = await c.puncher.analyze(true)
    if (isDone(c)) return null
    if (stable) return probeRound(c, serverAddress, serverRelay, false)
  }

  if ((c.puncher.remoteFirewall === FIREWALL.UNKNOWN || !token) && retry) {
    return probeRound(c, serverAddress, serverRelay, false)
  }

  if (
    c.puncher.remoteFirewall === FIREWALL.UNKNOWN ||
    c.puncher.nat.firewall === FIREWALL.UNKNOWN
  ) {
    await abort(c, serverRelay, HOLEPUNCH_PROBE_TIMEOUT())
    return null
  }

  if (c.puncher.remoteFirewall >= FIREWALL.RANDOM && c.puncher.nat.firewall >= FIREWALL.RANDOM) {
    await abort(c, serverRelay, HOLEPUNCH_DOUBLE_RANDOMIZED_NATS())
    return null
  }

  return { token, peerAddress }
}

async function roundPunch(c, serverAddress, remoteToken, clientRelay, serverRelay, delayed) {
  // We are gossiping our final NAT status to the other peer now
  // so make sure we don't update our local view for now as that can make things weird
  c.puncher.nat.freeze()

  const isRandom =
    c.puncher.remoteFirewall >= FIREWALL.RANDOM || c.puncher.nat.firewall >= FIREWALL.RANDOM
  if (isRandom) {
    while (
      c.dht._randomPunches >= c.dht._randomPunchLimit ||
      Date.now() - c.dht._lastRandomPunch < c.dht._randomPunchInterval
    ) {
      // if no relay can help, bail
      if (!c.relayToken) throw HOLEPUNCH_ABORTED()

      if (!delayed) {
        delayed = true
        await updateHolepunch(c, serverAddress, clientRelay, {
          error: ERROR.NONE,
          firewall: c.puncher.nat.firewall,
          round: c.round++,
          connected: false,
          punching: false,
          addresses: c.puncher.nat.addresses,
          remoteAddress: null,
          token: c.payload.token(serverAddress),
          remoteToken
        })
        if (isDone(c)) return
      }

      await tryLater(c)
      if (isDone(c)) return
    }
  }

  // increment now, so we can commit to punching
  if (isRandom) c.dht._randomPunches++

  let reply

  try {
    // if delayed switch to the servers chosen relay - we validated anyway
    reply = await updateHolepunch(
      c,
      delayed ? serverRelay.peerAddress : serverAddress,
      delayed ? serverRelay.relayAddress : clientRelay,
      {
        error: ERROR.NONE,
        firewall: c.puncher.nat.firewall,
        round: c.round++,
        connected: false,
        punching: true,
        addresses: c.puncher.nat.addresses,
        remoteAddress: null,
        token: delayed ? null : c.payload.token(serverAddress),
        remoteToken
      }
    )
  } finally {
    // decrement as punch increments for us
    if (isRandom) c.dht._randomPunches--
  }

  if (isDone(c)) return
  if (!reply) return

  if (reply.tryLater) {
    await tryLater(c)
    if (isDone(c)) return
    return roundPunch(c, serverAddress, remoteToken, clientRelay, serverRelay, true)
  }

  if (!c.puncher.remoteHolepunching) {
    throw REMOTE_NOT_HOLEPUNCHING()
  }

  if (!(await c.puncher.punch())) {
    throw REMOTE_NOT_HOLEPUNCHABLE()
  }
}

async function tryLater(c) {
  if (!c.relayToken) throw HOLEPUNCH_ABORTED()
  await c.sleeper.pause(10000 + Math.round(Math.random() * 10000))
}

function maybeDestroyEncryptedSocket(c, err) {
  if (isDone(c)) return
  if (c.encryptedSocket.rawStream) return
  if (c.relaySocket) return // waiting for the relay
  if (c.puncher && !c.puncher.destroyed) return // waiting for the puncher
  c.session.destroy()
  c.encryptedSocket.destroy(err)
}

async function abort(c, { peerAddress, relayAddress }, err) {
  try {
    await updateHolepunch(c, peerAddress, relayAddress, {
      error: ERROR.ABORTED,
      firewall: FIREWALL.UNKNOWN,
      round: c.round++,
      connected: false,
      punching: false,
      addresses: null,
      remoteAddress: null,
      token: null,
      remoteToken: null
    })
  } catch (err) {
    safetyCatch(err)
  }

  destroyPuncher(c)
  maybeDestroyEncryptedSocket(c, err)
}

function relayConnection(c, relayThrough, payload, hs) {
  let isInitiator
  let publicKey
  let token

  if (payload.relayThrough) {
    isInitiator = false
    publicKey = payload.relayThrough.publicKey
    token = payload.relayThrough.token
  } else {
    isInitiator = true
    publicKey = relayThrough
    token = c.relayToken
  }

  c.relayToken = token
  c.relaySocket = c.dht.connect(publicKey)
  c.relaySocket.setKeepAlive(c.relayKeepAlive)
  c.relayClient = relay.Client.from(c.relaySocket, { id: c.relaySocket.publicKey })
  c.relayTimeout = setTimeout(onabort, 15000, null)

  c.relayClient.pair(isInitiator, token, c.rawStream).on('error', onabort).on('data', ondata)

  function ondata(remoteId) {
    if (c.relayTimeout) clearRelayTimeout(c)
    if (c.rawStream === null) {
      onabort(null)
      return
    }

    c.relayPaired = true

    const { remotePort, remoteHost, socket } = c.relaySocket.rawStream

    c.rawStream
      .on('close', () => c.relaySocket.destroy())
      .connect(socket, remoteId, remotePort, remoteHost)

    c.encryptedSocket.start(c.rawStream, { handshake: hs })
  }

  function onabort(err) {
    if (c.relayTimeout) clearRelayTimeout(c)
    const socket = c.relaySocket
    c.relayToken = null
    c.relaySocket = null
    if (socket) socket.destroy()
    maybeDestroyEncryptedSocket(c, err || RELAY_ABORTED())
  }
}

function clearPassiveConnectTimeout(c) {
  clearTimeout(c.passiveConnectTimeout)
  c.passiveConnectTimeout = null
}

function clearRelayTimeout(c) {
  clearTimeout(c.relayTimeout)
  c.relayTimeout = null
}

function destroyPuncher(c) {
  if (c.puncher) c.puncher.destroy()
  c.session.destroy()
}

function pickServerRelay(relays, clientRelay) {
  for (const r of relays) {
    if (!diffAddress(r.relayAddress, clientRelay)) return r
  }
  return relays[0]
}

function diffAddress(a, b) {
  return a.host !== b.host || a.port !== b.port
}

function defaultCreateHandshake(keyPair, remotePublicKey) {
  return new NoiseWrap(keyPair, remotePublicKey)
}

function defaultCreateSecretStream(isInitiator, rawStream, opts) {
  return new NoiseSecretStream(isInitiator, rawStream, opts)
}

function onlyNonReserved(addr) {
  return !isReserved(addr.host)
}

function isRelay(relaySocket, socket, port, host) {
  const stream = relaySocket.rawStream
  if (!stream) return false
  if (stream.socket !== socket) return false
  return port === stream.remotePort && host === stream.remoteHost
}

function selectRelay(relayThrough) {
  if (typeof relayThrough === 'function') relayThrough = relayThrough()
  if (relayThrough === null) return null
  if (Array.isArray(relayThrough))
    return relayThrough[Math.floor(Math.random() * relayThrough.length)]
  return relayThrough
}

function isRelayAddress(relayAddresses, data) {
  for (const node of relayAddresses) {
    if (node.host === data.from.host && node.port === data.from.port) return true
  }

  return false
}

function noop() {}
const EventEmitter = require('events')
const b4a = require('b4a')
const errors = require('./errors')

module.exports = class ConnectionPool extends EventEmitter {
  constructor(dht) {
    super()

    this._dht = dht
    this._servers = new Map()
    this._connecting = new Map()
    this._connections = new Map()
  }

  _attachServer(server) {
    const keyString = b4a.toString(server.publicKey, 'hex')

    this._servers.set(keyString, server)

    server
      .on('close', () => {
        this._servers.delete(keyString)
      })
      .on('connection', (socket) => {
        this._attachStream(socket, true)
      })
  }

  _attachStream(stream, opened) {
    const existing = this.get(stream.remotePublicKey)

    if (existing) {
      const keepNew =
        stream.isInitiator === existing.isInitiator ||
        b4a.compare(stream.publicKey, stream.remotePublicKey) > 0

      if (keepNew) {
        let closed = false

        const onclose = () => {
          closed = true
        }

        existing
          .on('error', noop)
          .on('close', () => {
            if (closed) return

            stream.off('error', noop).off('close', onclose)

            this._attachStream(stream, opened)
          })
          .destroy(errors.DUPLICATE_CONNECTION())

        stream.on('error', noop).on('close', onclose)
      } else {
        stream.on('error', noop).destroy(errors.DUPLICATE_CONNECTION())
      }

      return
    }

    const session = new ConnectionRef(this, stream)

    const keyString = b4a.toString(stream.remotePublicKey, 'hex')

    if (opened) {
      this._connections.set(keyString, session)

      stream.on('close', () => {
        this._connections.delete(keyString)
      })

      this.emit('connection', stream, session)
    } else {
      this._connecting.set(keyString, session)

      stream
        .on('error', noop)
        .on('close', () => {
          if (opened) this._connections.delete(keyString)
          else this._connecting.delete(keyString)
        })
        .on('open', () => {
          opened = true

          this._connecting.delete(keyString)
          this._connections.set(keyString, session)

          stream.off('error', noop)

          this.emit('connection', stream, session)
        })
    }

    return session
  }

  get connecting() {
    return this._connecting.size
  }

  get connections() {
    return this._connections.values()
  }

  has(publicKey) {
    const keyString = b4a.toString(publicKey, 'hex')

    return this._connections.has(keyString) || this._connecting.has(keyString)
  }

  get(publicKey) {
    const keyString = b4a.toString(publicKey, 'hex')

    const existing = this._connections.get(keyString) || this._connecting.get(keyString)

    return existing?._stream || null
  }
}

class ConnectionRef {
  constructor(pool, stream) {
    this._pool = pool
    this._stream = stream
    this._refs = 0
  }

  active() {
    this._refs++
  }

  inactive() {
    this._refs--
  }

  release() {
    this._stream.destroy()
  }
}

function noop() {}
const crypto = require('hypercore-crypto')

const COMMANDS = (exports.COMMANDS = {
  PEER_HANDSHAKE: 0,
  PEER_HOLEPUNCH: 1,
  FIND_PEER: 2,
  LOOKUP: 3,
  ANNOUNCE: 4,
  UNANNOUNCE: 5,
  MUTABLE_PUT: 6,
  MUTABLE_GET: 7,
  IMMUTABLE_PUT: 8,
  IMMUTABLE_GET: 9,
  PLUGIN: 10
})

exports.BOOTSTRAP_NODES = global.Pear?.config.dht?.bootstrap || [
  '88.99.3.86@node1.hyperdht.org:49737',
  '142.93.90.113@node2.hyperdht.org:49737',
  '138.68.147.8@node3.hyperdht.org:49737'
]

exports.KNOWN_NODES = global.Pear?.config.dht?.nodes || []

exports.FIREWALL = {
  UNKNOWN: 0,
  OPEN: 1,
  CONSISTENT: 2,
  RANDOM: 3
}

exports.ERROR = {
  // noise / connection related
  NONE: 0,
  ABORTED: 1,
  VERSION_MISMATCH: 2,
  TRY_LATER: 3,
  // dht related
  SEQ_REUSED: 16,
  SEQ_TOO_LOW: 17
}

const [
  NS_ANNOUNCE,
  NS_UNANNOUNCE,
  NS_MUTABLE_PUT,
  NS_PEER_HANDSHAKE,
  NS_PEER_HOLEPUNCH,
  NS_PLUGIN
] = crypto.namespace('hyperswarm/dht', [
  COMMANDS.ANNOUNCE,
  COMMANDS.UNANNOUNCE,
  COMMANDS.MUTABLE_PUT,
  COMMANDS.PEER_HANDSHAKE,
  COMMANDS.PEER_HOLEPUNCH,
  COMMANDS.PLUGIN
])

exports.NS = {
  ANNOUNCE: NS_ANNOUNCE,
  UNANNOUNCE: NS_UNANNOUNCE,
  MUTABLE_PUT: NS_MUTABLE_PUT,
  PEER_HANDSHAKE: NS_PEER_HANDSHAKE,
  PEER_HOLEPUNCH: NS_PEER_HOLEPUNCH,
  PLUGIN: NS_PLUGIN
}
const sodium = require('sodium-universal')
const b4a = require('b4a')

function hash(data) {
  const out = b4a.allocUnsafe(32)
  sodium.crypto_generichash(out, data)
  return out
}

function unslabbedHash(data) {
  const out = b4a.allocUnsafeSlow(32)
  sodium.crypto_generichash(out, data)
  return out
}

function createKeyPair(seed) {
  const publicKey = b4a.alloc(32)
  const secretKey = b4a.alloc(64)
  if (seed) sodium.crypto_sign_seed_keypair(publicKey, secretKey, seed)
  else sodium.crypto_sign_keypair(publicKey, secretKey)
  return { publicKey, secretKey }
}

module.exports = {
  hash,
  unslabbedHash,
  createKeyPair
}
const b4a = require('b4a')
const cenc = require('compact-encoding')

function encodeUnslab(enc, m) {
  // Faster than unslab(c.encode(enc, data)) because it avoids the mem copy.
  // Makes sense to put in compact-encoding when we need it in other modules too
  const state = cenc.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafeSlow(state.end)
  enc.encode(state, m)
  return state.buffer
}

module.exports = {
  encodeUnslab
}
module.exports = class DHTError extends Error {
  constructor(msg, code, fn = DHTError) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'DHTError'
  }

  static BAD_HANDSHAKE_REPLY(msg = 'Bad handshake reply') {
    return new DHTError(msg, 'BAD_HANDSHAKE_REPLY', DHTError.BAD_HANDSHAKE_REPLY)
  }

  static BAD_HOLEPUNCH_REPLY(msg = 'Bad holepunch reply') {
    return new DHTError(msg, 'BAD_HOLEPUNCH_REPLY', DHTError.BAD_HOLEPUNCH_REPLY)
  }

  static HOLEPUNCH_ABORTED(msg = 'Holepunch aborted') {
    return new DHTError(msg, 'HOLEPUNCH_ABORTED', DHTError.HOLEPUNCH_ABORTED)
  }

  static HOLEPUNCH_INVALID(msg = 'Invalid holepunch payload') {
    return new DHTError(msg, 'HOLEPUNCH_INVALID', DHTError.HOLEPUNCH_INVALID)
  }

  static HOLEPUNCH_PROBE_TIMEOUT(msg = 'Holepunching probe did not finish in time') {
    return new DHTError(msg, 'HOLEPUNCH_PROBE_TIMEOUT', DHTError.HOLEPUNCH_PROBE_TIMEOUT)
  }

  static HOLEPUNCH_DOUBLE_RANDOMIZED_NATS(msg = 'Both remote and local NATs are randomized') {
    return new DHTError(
      msg,
      'HOLEPUNCH_DOUBLE_RANDOMIZED_NATS',
      DHTError.HOLEPUNCH_DOUBLE_RANDOMIZED_NATS
    )
  }

  static CANNOT_HOLEPUNCH(msg = 'Cannot holepunch to remote') {
    return new DHTError(msg, 'CANNOT_HOLEPUNCH', DHTError.CANNOT_HOLEPUNCH)
  }

  static REMOTE_NOT_HOLEPUNCHING(msg = 'Remote is not holepunching') {
    return new DHTError(msg, 'REMOTE_NOT_HOLEPUNCHING', DHTError.REMOTE_NOT_HOLEPUNCHING)
  }

  static REMOTE_NOT_HOLEPUNCHABLE(msg = 'Remote is not holepunchable') {
    return new DHTError(msg, 'REMOTE_NOT_HOLEPUNCHABLE', DHTError.REMOTE_NOT_HOLEPUNCHABLE)
  }

  static REMOTE_ABORTED(msg = 'Remote aborted') {
    return new DHTError(msg, 'REMOTE_ABORTED', DHTError.REMOTE_ABORTED)
  }

  static HANDSHAKE_UNFINISHED(msg = 'Handshake did not finish') {
    return new DHTError(msg, 'HANDSHAKE_UNFINISHED', DHTError.HANDSHAKE_UNFINISHED)
  }

  static HANDSHAKE_INVALID(msg = 'Received invalid handshake') {
    return new DHTError(msg, 'HANDSHAKE_INVALID', DHTError.HANDSHAKE_INVALID)
  }

  static ALREADY_LISTENING(msg = 'Already listening') {
    return new DHTError(msg, 'ALREADY_LISTENING', DHTError.ALREADY_LISTENING)
  }

  static KEYPAIR_ALREADY_USED(msg = 'Keypair already used') {
    return new DHTError(msg, 'KEYPAIR_ALREADY_USED', DHTError.KEYPAIR_ALREADY_USED)
  }

  static NODE_DESTROYED(msg = 'Node destroyed') {
    return new DHTError(msg, 'NODE_DESTROYED', DHTError.NODE_DESTROYED)
  }

  static PEER_CONNECTION_FAILED(msg = 'Could not connect to peer') {
    return new DHTError(msg, 'PEER_CONNECTION_FAILED', DHTError.PEER_CONNECTION_FAILED)
  }

  static PEER_NOT_FOUND(msg = 'Peer not found') {
    return new DHTError(msg, 'PEER_NOT_FOUND', DHTError.PEER_NOT_FOUND)
  }

  static STREAM_NOT_CONNECTED(msg = 'Stream is not connected') {
    return new DHTError(msg, 'STREAM_NOT_CONNECTED', DHTError.STREAM_DISCONNECTED)
  }

  static SERVER_INCOMPATIBLE(msg = 'Server is using an incompatible version') {
    return new DHTError(msg, 'SERVER_INCOMPATIBLE', DHTError.SERVER_INCOMPATIBLE)
  }

  static SERVER_ERROR(msg = 'Server returned an error') {
    return new DHTError(msg, 'SERVER_ERROR', DHTError.SERVER_ERROR)
  }

  static DUPLICATE_CONNECTION(msg = 'Duplicate connection') {
    return new DHTError(msg, 'DUPLICATE_CONNECTION', DHTError.DUPLICATE_CONNECTION)
  }

  static RELAY_ABORTED(msg = 'Relay aborted') {
    return new DHTError(msg, 'RELAY_ABORTED', DHTError.RELAY_ABORTED)
  }

  static SUSPENDED(msg = 'Suspended') {
    return new DHTError(msg, 'SUSPENDED', DHTError.SUSPENDED)
  }
}
const b4a = require('b4a')
const Nat = require('./nat')
const Sleeper = require('./sleeper')
const { FIREWALL } = require('./constants')

const BIRTHDAY_SOCKETS = 256
const HOLEPUNCH = b4a.from([0])
const HOLEPUNCH_TTL = 5
const DEFAULT_TTL = 64
const MAX_REOPENS = 3

module.exports = class Holepuncher {
  constructor(dht, session, isInitiator, remoteFirewall = FIREWALL.UNKNOWN) {
    const holder = dht._socketPool.acquire()

    this.dht = dht
    this.session = session

    this.nat = new Nat(dht, session, holder.socket)
    this.nat.autoSample()

    this.isInitiator = isInitiator

    // events
    this.onconnect = noop
    this.onabort = noop

    this.punching = false
    this.connected = false
    this.destroyed = false
    this.randomized = false

    // track remote state
    this.remoteFirewall = remoteFirewall
    this.remoteAddresses = []
    this.remoteHolepunching = false

    this._sleeper = new Sleeper()
    this._reopening = null
    this._timeout = null
    this._punching = null
    this._allHolders = []
    this._holder = this._addRef(holder)
  }

  get socket() {
    return this._holder.socket
  }

  updateRemote({ punching, firewall, addresses, verified }) {
    const remoteAddresses = []

    if (addresses) {
      for (const addr of addresses) {
        remoteAddresses.push({
          host: addr.host,
          port: addr.port,
          verified: verified === addr.host || this._isVerified(addr.host)
        })
      }
    }

    this.remoteFirewall = firewall
    this.remoteAddresses = remoteAddresses
    this.remoteHolepunching = punching
  }

  _isVerified(host) {
    for (const addr of this.remoteAddresses) {
      if (addr.verified && addr.host === host) {
        return true
      }
    }
    return false
  }

  ping(addr, socket = this._holder.socket) {
    return holepunch(socket, addr, false)
  }

  openSession(addr, socket = this._holder.socket) {
    return holepunch(socket, addr, true)
  }

  async analyze(allowReopen) {
    await this.nat.analyzing
    if (this._unstable()) {
      if (!allowReopen) return false
      if (!this._reopening) this._reopening = this._reopen()
      return this._reopening
    }
    return true
  }

  _unstable() {
    // TODO!!: We need an additional heuristic here... If we were NOT random in the past we should also do this.
    const firewall = this.nat.firewall
    return (
      (this.remoteFirewall >= FIREWALL.RANDOM && firewall >= FIREWALL.RANDOM) ||
      firewall === FIREWALL.UNKNOWN
    )
  }

  _reset() {
    const prev = this._holder

    this._allHolders.pop()
    this._holder = this._addRef(this.dht._socketPool.acquire())

    prev.release()
    this.nat.destroy()

    this.nat = new Nat(this.dht, this.session, this._holder.socket)
    // TODO: maybe make auto sampling configurable somehow?
    this.nat.autoSample()
  }

  _addRef(ref) {
    this._allHolders.push(ref)
    ref.onholepunchmessage = (msg, rinfo) => this._onholepunchmessage(msg, rinfo, ref)
    return ref
  }

  _onholepunchmessage(_, addr, ref) {
    if (!this.isInitiator) {
      // TODO: we don't need this if we had a way to connect a socket to many hosts
      holepunch(ref.socket, addr, false) // never fails
      return
    }

    if (this.connected) return

    this.connected = true
    this.punching = false

    for (const r of this._allHolders) {
      if (r === ref) continue
      r.release()
    }

    this._allHolders[0] = ref
    while (this._allHolders.length > 1) this._allHolders.pop()

    this._decrementRandomized()
    this.onconnect(ref.socket, addr.port, addr.host)
  }

  _done() {
    return this.destroyed || this.connected
  }

  async _reopen() {
    for (let i = 0; this._unstable() && i < MAX_REOPENS && !this._done() && !this.punching; i++) {
      this._reset()
      await this.nat.analyzing
    }

    return coerceFirewall(this.nat.firewall) === FIREWALL.CONSISTENT
  }

  punch() {
    if (!this._punching) this._punching = this._punch()
    return this._punching
  }

  async _punch() {
    if (this._done() || !this.remoteAddresses.length) return false

    this.punching = true

    // Coerce into consistency for now. Obvs we could make this this more efficient if we use that info
    // but that's seldomly used since those will just use tcp most of the time.

    const local = coerceFirewall(this.nat.firewall)
    const remote = coerceFirewall(this.remoteFirewall)

    // Note that most of these async functions are meant to run in the background
    // which is why we don't await them here and why they are not allowed to throw

    let remoteVerifiedAddress = null
    for (const addr of this.remoteAddresses) {
      if (addr.verified) {
        remoteVerifiedAddress = addr
        break
      }
    }

    if (local === FIREWALL.CONSISTENT && remote === FIREWALL.CONSISTENT) {
      this.dht.stats.punches.consistent++
      this._consistentProbe()
      return true
    }

    if (!remoteVerifiedAddress) return false

    if (local === FIREWALL.CONSISTENT && remote >= FIREWALL.RANDOM) {
      this.dht.stats.punches.random++
      this._incrementRandomized()
      this._randomProbes(remoteVerifiedAddress)
      return true
    }

    if (local >= FIREWALL.RANDOM && remote === FIREWALL.CONSISTENT) {
      this.dht.stats.punches.random++
      this._incrementRandomized()
      await this._openBirthdaySockets(remoteVerifiedAddress)
      if (this.punching) this._keepAliveRandomNat(remoteVerifiedAddress)
      return true
    }

    return false
  }

  // Note that this never throws so it is safe to run in the background
  async _consistentProbe() {
    // Here we do the sleep first because the "fast open" mode in the server just fired a ping
    if (!this.isInitiator) await this._sleeper.pause(1000)

    let tries = 0

    while (this.punching && tries++ < 10) {
      for (const addr of this.remoteAddresses) {
        // only try unverified addresses every 4 ticks
        if (!addr.verified && (tries & 3) !== 0) continue
        await holepunch(this._holder.socket, addr, false)
      }
      if (this.punching) await this._sleeper.pause(1000)
    }

    this._autoDestroy()
  }

  // Note that this never throws so it is safe to run in the background
  async _randomProbes(remoteAddr) {
    let tries = 1750 // ~35s

    while (this.punching && tries-- > 0) {
      const addr = { host: remoteAddr.host, port: randomPort() }
      await holepunch(this._holder.socket, addr, false)
      if (this.punching) await this._sleeper.pause(20)
    }

    this._autoDestroy()
  }

  // Note that this never throws so it is safe to run in the background
  async _keepAliveRandomNat(remoteAddr) {
    let i = 0
    let lowTTLRounds = 1

    // TODO: experiment with this here. We just bursted all the messages in
    // openOtherSockets to ensure the sockets are open, so it's potentially
    // a good idea to slow down for a bit.
    await this._sleeper.pause(100)

    let tries = 1750 // ~35s

    while (this.punching && tries-- > 0) {
      if (i === this._allHolders.length) {
        i = 0
        if (lowTTLRounds > 0) lowTTLRounds--
      }

      await holepunch(this._allHolders[i++].socket, remoteAddr, lowTTLRounds > 0)
      if (this.punching) await this._sleeper.pause(20)
    }

    this._autoDestroy()
  }

  async _openBirthdaySockets(remoteAddr) {
    while (this.punching && this._allHolders.length < BIRTHDAY_SOCKETS) {
      const ref = this._addRef(this.dht._socketPool.acquire())
      await holepunch(ref.socket, remoteAddr, HOLEPUNCH_TTL)
    }
  }

  _autoDestroy() {
    if (!this.connected) this.destroy()
  }

  _incrementRandomized() {
    if (!this.randomized) {
      this.randomized = true
      this.dht._randomPunches++
    }
  }

  _decrementRandomized() {
    if (this.randomized) {
      this.dht._lastRandomPunch = Date.now()
      this.randomized = false
      this.dht._randomPunches--
    }
  }

  destroy() {
    if (this.destroyed) return
    this.destroyed = true
    this.punching = false

    for (const ref of this._allHolders) ref.release()
    this._allHolders = []
    this.nat.destroy()

    if (!this.connected) {
      this._decrementRandomized()
      this.onabort()
    }
  }

  static ping(socket, addr) {
    return holepunch(socket, addr, false)
  }

  static localAddresses(socket) {
    return localAddresses(socket)
  }

  static matchAddress(myAddresses, externalAddresses) {
    return matchAddress(myAddresses, externalAddresses)
  }
}

function holepunch(socket, addr, lowTTL) {
  return socket.send(HOLEPUNCH, addr.port, addr.host, lowTTL ? HOLEPUNCH_TTL : DEFAULT_TTL)
}

function randomPort() {
  return (1000 + Math.random() * 64536) | 0
}

function coerceFirewall(fw) {
  return fw === FIREWALL.OPEN ? FIREWALL.CONSISTENT : fw
}

function localAddresses(socket) {
  const addrs = []
  const { host, port } = socket.address()

  if (host === '127.0.0.1') return [{ host, port }]

  for (const n of socket.udx.networkInterfaces()) {
    if (n.family !== 4 || n.internal) continue

    addrs.push({ host: n.host, port })
  }

  if (addrs.length === 0) {
    addrs.push({ host: '127.0.0.1', port })
  }

  return addrs
}

function matchAddress(localAddresses, remoteLocalAddresses) {
  if (remoteLocalAddresses.length === 0) return null

  let best = { segment: 1, addr: null }

  for (const localAddress of localAddresses) {
    // => 192.168.122.238
    const a = localAddress.host.split('.')

    for (const remoteAddress of remoteLocalAddresses) {
      // => 192.168.0.23
      // => 192.168.122.1
      const b = remoteAddress.host.split('.')

      // Matches 192.*.*.*
      if (a[0] === b[0]) {
        if (best.segment === 1) best = { segment: 2, addr: remoteAddress }

        // Matches 192.168.*.*
        if (a[1] === b[1]) {
          if (best.segment === 2) best = { segment: 3, addr: remoteAddress }

          // Matches 192.168.122.*
          if (a[2] === b[2]) return remoteAddress
        }
      }
    }
  }

  return best.addr
}

function noop() {}
const c = require('compact-encoding')

const ipv4 = {
  ...c.ipv4Address,
  decode(state) {
    const ip = c.ipv4Address.decode(state)
    return {
      host: ip.host,
      port: ip.port
    }
  }
}

const ipv4Array = c.array(ipv4)

const ipv6 = {
  ...c.ipv6Address,
  decode(state) {
    const ip = c.ipv6Address.decode(state)
    return {
      host: ip.host,
      port: ip.port
    }
  }
}

const ipv6Array = c.array(ipv6)

exports.handshake = {
  preencode(state, m) {
    state.end += 1 + 1 + (m.peerAddress ? 6 : 0) + (m.relayAddress ? 6 : 0)
    c.buffer.preencode(state, m.noise)
  },
  encode(state, m) {
    const flags = (m.peerAddress ? 1 : 0) | (m.relayAddress ? 2 : 0)

    c.uint.encode(state, flags)
    c.uint.encode(state, m.mode)
    c.buffer.encode(state, m.noise)

    if (m.peerAddress) ipv4.encode(state, m.peerAddress)
    if (m.relayAddress) ipv4.encode(state, m.relayAddress)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      mode: c.uint.decode(state),
      noise: c.buffer.decode(state),
      peerAddress: flags & 1 ? ipv4.decode(state) : null,
      relayAddress: flags & 2 ? ipv4.decode(state) : null
    }
  }
}

const relayInfo = {
  preencode(state, m) {
    state.end += 12
  },
  encode(state, m) {
    ipv4.encode(state, m.relayAddress)
    ipv4.encode(state, m.peerAddress)
  },
  decode(state) {
    return {
      relayAddress: ipv4.decode(state),
      peerAddress: ipv4.decode(state)
    }
  }
}

const relayInfoArray = c.array(relayInfo)

const holepunchInfo = {
  preencode(state, m) {
    c.uint.preencode(state, m.id)
    relayInfoArray.preencode(state, m.relays)
  },
  encode(state, m) {
    c.uint.encode(state, m.id)
    relayInfoArray.encode(state, m.relays)
  },
  decode(state) {
    return {
      id: c.uint.decode(state),
      relays: relayInfoArray.decode(state)
    }
  }
}

const udxInfo = {
  preencode(state, m) {
    state.end += 2 // version + features
    c.uint.preencode(state, m.id)
    c.uint.preencode(state, m.seq)
  },
  encode(state, m) {
    c.uint.encode(state, 1)
    c.uint.encode(state, m.reusableSocket ? 1 : 0)
    c.uint.encode(state, m.id)
    c.uint.encode(state, m.seq)
  },
  decode(state) {
    const version = c.uint.decode(state)
    const features = c.uint.decode(state)

    return {
      version,
      reusableSocket: (features & 1) !== 0,
      id: c.uint.decode(state),
      seq: c.uint.decode(state)
    }
  }
}

const secretStreamInfo = {
  preencode(state, m) {
    c.uint.preencode(state, 1)
  },
  encode(state, m) {
    c.uint.encode(state, 1)
  },
  decode(state) {
    return {
      version: c.uint.decode(state)
    }
  }
}

const relayThroughInfo = {
  preencode(state, m) {
    c.uint.preencode(state, 1) // version
    c.uint.preencode(state, 0) // flags
    c.fixed32.preencode(state, m.publicKey)
    c.fixed32.preencode(state, m.token)
  },
  encode(state, m) {
    c.uint.encode(state, 1)
    c.uint.encode(state, 0)
    c.fixed32.encode(state, m.publicKey)
    c.fixed32.encode(state, m.token)
  },
  decode(state) {
    const version = c.uint.decode(state)
    c.uint.decode(state)

    return {
      version,
      publicKey: c.fixed32.decode(state),
      token: c.fixed32.decode(state)
    }
  }
}

exports.noisePayload = {
  preencode(state, m) {
    state.end += 4 // version + flags + error + firewall
    if (m.holepunch) holepunchInfo.preencode(state, m.holepunch)
    if (m.addresses4 && m.addresses4.length) ipv4Array.preencode(state, m.addresses4)
    if (m.addresses6 && m.addresses6.length) ipv6Array.preencode(state, m.addresses6)
    if (m.udx) udxInfo.preencode(state, m.udx)
    if (m.secretStream) secretStreamInfo.preencode(state, m.secretStream)
    if (m.relayThrough) relayThroughInfo.preencode(state, m.relayThrough)
    if (m.relayAddresses) ipv4Array.preencode(state, m.relayAddresses)
  },
  encode(state, m) {
    let flags = 0

    if (m.holepunch) flags |= 1
    if (m.addresses4 && m.addresses4.length) flags |= 2
    if (m.addresses6 && m.addresses6.length) flags |= 4
    if (m.udx) flags |= 8
    if (m.secretStream) flags |= 16
    if (m.relayThrough) flags |= 32
    if (m.relayAddresses) flags |= 64

    c.uint.encode(state, 1) // version
    c.uint.encode(state, flags)
    c.uint.encode(state, m.error)
    c.uint.encode(state, m.firewall)

    if (m.holepunch) holepunchInfo.encode(state, m.holepunch)
    if (m.addresses4 && m.addresses4.length) ipv4Array.encode(state, m.addresses4)
    if (m.addresses6 && m.addresses6.length) ipv6Array.encode(state, m.addresses6)
    if (m.udx) udxInfo.encode(state, m.udx)
    if (m.secretStream) secretStreamInfo.encode(state, m.secretStream)
    if (m.relayThrough) relayThroughInfo.encode(state, m.relayThrough)
    if (m.relayAddresses) ipv4Array.encode(state, m.relayAddresses)
  },
  decode(state) {
    const version = c.uint.decode(state)

    if (version !== 1) {
      // Do not attempt to decode but return this back to the user so they can
      // actually handle it
      return {
        version,
        error: 0,
        firewall: 0,
        holepunch: null,
        addresses4: [],
        addresses6: [],
        udx: null,
        secretStream: null,
        relayThrough: null,
        relayAddresses: null
      }
    }

    const flags = c.uint.decode(state)

    return {
      version,
      error: c.uint.decode(state),
      firewall: c.uint.decode(state),
      holepunch: (flags & 1) !== 0 ? holepunchInfo.decode(state) : null,
      addresses4: (flags & 2) !== 0 ? ipv4Array.decode(state) : [],
      addresses6: (flags & 4) !== 0 ? ipv6Array.decode(state) : [],
      udx: (flags & 8) !== 0 ? udxInfo.decode(state) : null,
      secretStream: (flags & 16) !== 0 ? secretStreamInfo.decode(state) : null,
      relayThrough: (flags & 32) !== 0 ? relayThroughInfo.decode(state) : null,
      relayAddresses: (flags & 64) !== 0 ? ipv4Array.decode(state) : null
    }
  }
}

exports.holepunch = {
  preencode(state, m) {
    state.end += 2
    c.uint.preencode(state, m.id)
    c.buffer.preencode(state, m.payload)
    if (m.peerAddress) ipv4.preencode(state, m.peerAddress)
  },
  encode(state, m) {
    const flags = m.peerAddress ? 1 : 0
    c.uint.encode(state, flags)
    c.uint.encode(state, m.mode)
    c.uint.encode(state, m.id)
    c.buffer.encode(state, m.payload)
    if (m.peerAddress) ipv4.encode(state, m.peerAddress)
  },
  decode(state) {
    const flags = c.uint.decode(state)
    return {
      mode: c.uint.decode(state),
      id: c.uint.decode(state),
      payload: c.buffer.decode(state),
      peerAddress: flags & 1 ? ipv4.decode(state) : null
    }
  }
}

exports.holepunchPayload = {
  preencode(state, m) {
    state.end += 4 // flags + error + firewall + round
    if (m.addresses) ipv4Array.preencode(state, m.addresses)
    if (m.remoteAddress) state.end += 6
    if (m.token) state.end += 32
    if (m.remoteToken) state.end += 32
  },
  encode(state, m) {
    const flags =
      (m.connected ? 1 : 0) |
      (m.punching ? 2 : 0) |
      (m.addresses ? 4 : 0) |
      (m.remoteAddress ? 8 : 0) |
      (m.token ? 16 : 0) |
      (m.remoteToken ? 32 : 0)

    c.uint.encode(state, flags)
    c.uint.encode(state, m.error)
    c.uint.encode(state, m.firewall)
    c.uint.encode(state, m.round)

    if (m.addresses) ipv4Array.encode(state, m.addresses)
    if (m.remoteAddress) ipv4.encode(state, m.remoteAddress)
    if (m.token) c.fixed32.encode(state, m.token)
    if (m.remoteToken) c.fixed32.encode(state, m.remoteToken)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      error: c.uint.decode(state),
      firewall: c.uint.decode(state),
      round: c.uint.decode(state),
      connected: (flags & 1) !== 0,
      punching: (flags & 2) !== 0,
      addresses: (flags & 4) !== 0 ? ipv4Array.decode(state) : null,
      remoteAddress: (flags & 8) !== 0 ? ipv4.decode(state) : null,
      token: (flags & 16) !== 0 ? c.fixed32.decode(state) : null,
      remoteToken: (flags & 32) !== 0 ? c.fixed32.decode(state) : null
    }
  }
}

const peer = (exports.peer = {
  preencode(state, m) {
    state.end += 32
    ipv4Array.preencode(state, m.relayAddresses)
  },
  encode(state, m) {
    c.fixed32.encode(state, m.publicKey)
    ipv4Array.encode(state, m.relayAddresses)
  },
  decode(state) {
    return {
      publicKey: c.fixed32.decode(state),
      relayAddresses: ipv4Array.decode(state)
    }
  }
})

const peers = (exports.peers = c.array(peer))

const rawPeers = c.array(c.raw)

exports.lookupRawReply = {
  preencode(state, m) {
    rawPeers.preencode(state, m.peers)
    c.uint.preencode(state, m.bump)
  },
  encode(state, m) {
    rawPeers.encode(state, m.peers)
    c.uint.encode(state, m.bump)
  },
  decode(state) {
    return {
      peers: peers.decode(state),
      bump: state.start < state.end ? c.uint.decode(state) : 0
    }
  }
}

exports.announce = {
  preencode(state, m) {
    state.end++ // flags
    if (m.peer) peer.preencode(state, m.peer)
    if (m.refresh) state.end += 32
    if (m.signature) state.end += 64
    if (m.bump) c.uint.preencode(state, m.bump)
  },
  encode(state, m) {
    const flags = (m.peer ? 1 : 0) | (m.refresh ? 2 : 0) | (m.signature ? 4 : 0) | (m.bump ? 8 : 0)
    c.uint.encode(state, flags)
    if (m.peer) peer.encode(state, m.peer)
    if (m.refresh) c.fixed32.encode(state, m.refresh)
    if (m.signature) c.fixed64.encode(state, m.signature)
    if (m.bump) c.uint.encode(state, m.bump)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      peer: (flags & 1) !== 0 ? peer.decode(state) : null,
      refresh: (flags & 2) !== 0 ? c.fixed32.decode(state) : null,
      signature: (flags & 4) !== 0 ? c.fixed64.decode(state) : null,
      bump: (flags & 8) !== 0 ? c.uint.decode(state) : 0
    }
  }
}

exports.mutableSignable = {
  preencode(state, m) {
    c.uint.preencode(state, m.seq)
    c.buffer.preencode(state, m.value)
  },
  encode(state, m) {
    c.uint.encode(state, m.seq)
    c.buffer.encode(state, m.value)
  },
  decode(state) {
    return {
      seq: c.uint.decode(state),
      value: c.buffer.decode(state)
    }
  }
}

exports.mutablePutRequest = {
  preencode(state, m) {
    c.fixed32.preencode(state, m.publicKey)
    c.uint.preencode(state, m.seq)
    c.buffer.preencode(state, m.value)
    c.fixed64.preencode(state, m.signature)
  },
  encode(state, m) {
    c.fixed32.encode(state, m.publicKey)
    c.uint.encode(state, m.seq)
    c.buffer.encode(state, m.value)
    c.fixed64.encode(state, m.signature)
  },
  decode(state) {
    return {
      publicKey: c.fixed32.decode(state),
      seq: c.uint.decode(state),
      value: c.buffer.decode(state),
      signature: c.fixed64.decode(state)
    }
  }
}

exports.mutableGetResponse = {
  preencode(state, m) {
    c.uint.preencode(state, m.seq)
    c.buffer.preencode(state, m.value)
    c.fixed64.preencode(state, m.signature)
  },
  encode(state, m) {
    c.uint.encode(state, m.seq)
    c.buffer.encode(state, m.value)
    c.fixed64.encode(state, m.signature)
  },
  decode(state) {
    return {
      seq: c.uint.decode(state),
      value: c.buffer.decode(state),
      signature: c.fixed64.decode(state)
    }
  }
}

exports.pluginRequest = {
  preencode(state, m) {
    c.string.preencode(state, m.plugin)
    c.uint.preencode(state, m.version)
    c.uint.preencode(state, m.command)
    c.buffer.preencode(state, m.value)
  },
  encode(state, m) {
    c.string.encode(state, m.plugin)
    c.uint.encode(state, m.version)
    c.uint.encode(state, m.command)
    c.buffer.encode(state, m.value)
  },
  decode(state) {
    return {
      plugin: c.string.decode(state),
      version: c.uint.decode(state),
      command: c.uint.decode(state),
      value: c.buffer.decode(state)
    }
  }
}
const { FIREWALL } = require('../lib/constants')

module.exports = class Nat {
  constructor(dht, session, socket) {
    this._samplesHost = []
    this._samplesFull = []
    this._visited = new Map()
    this._resolve = null
    this._minSamples = 4
    this._autoSampling = false

    this.dht = dht
    this.session = session
    this.socket = socket

    this.sampled = 0
    this.firewall = dht.firewalled ? FIREWALL.UNKNOWN : FIREWALL.OPEN
    this.addresses = null

    this.analyzing = new Promise((resolve) => {
      this._resolve = resolve
    })
  }

  autoSample(retry = true) {
    if (this._autoSampling) return
    this._autoSampling = true

    const self = this
    const socket = this.socket
    const maxPings = this._minSamples

    let skip = this.dht.nodes.length >= 8 ? 5 : 0
    let pending = 0

    // TODO: it would be best to pick the nodes to help us based on latency to us
    // That should reduce connect latency in general. We should investigate tracking that later on.

    // TODO 2: try to pick nodes with different IPs as well, as that'll help multi IP cell connections...
    // If we expose this from the nat sampler then the DHT should be able to help us filter out scams as well...

    for (
      let node = this.dht.nodes.latest;
      node && this.sampled + pending < maxPings;
      node = node.prev
    ) {
      if (skip > 0) {
        skip--
        continue
      }

      const ref = node.host + ':' + node.port

      if (this._visited.has(ref)) continue
      this._visited.set(ref, 1)

      pending++
      this.session.ping(node, { socket, retry: false }).then(onpong, onskip)
    }

    pending++
    onskip()

    function onpong(res) {
      self.add(res.to, res.from)
      onskip()
    }

    function onskip() {
      if (--pending === 0 && self.sampled < self._minSamples) {
        if (retry) {
          self._autoSampling = false
          self.autoSample(false)
          return
        }
        self._resolve()
      }
    }
  }

  destroy() {
    this._autoSampling = true
    this._minSamples = 0
    this._resolve()
  }

  unfreeze() {
    this.frozen = false
    this._updateFirewall()
    this._updateAddresses()
  }

  freeze() {
    this.frozen = true
  }

  _updateFirewall() {
    if (!this.dht.firewalled) {
      this.firewall = FIREWALL.OPEN
      return
    }

    if (this.sampled < 3) return

    const max = this._samplesFull[0].hits

    if (max >= 3) {
      this.firewall = FIREWALL.CONSISTENT
      return
    }

    if (max === 1) {
      this.firewall = FIREWALL.RANDOM
      return
    }

    // else max === 2

    // 1 host, >= 4 total samples ie, 2 bad ones -> random
    if (this._samplesHost.length === 1 && this.sampled > 3) {
      this.firewall = FIREWALL.RANDOM
      return
    }

    // double hit on two different ips -> assume consistent
    if (this._samplesHost.length > 1 && this._samplesFull[1].hits > 1) {
      this.firewall = FIREWALL.CONSISTENT
      return
    }

    // (4 is just means - all the samples we expect) - no decision - assume random
    if (this.sampled > 4) {
      this.firewall = FIREWALL.RANDOM
    }
  }

  _updateAddresses() {
    if (this.firewall === FIREWALL.UNKNOWN) {
      this.addresses = null
      return
    }

    if (this.firewall === FIREWALL.RANDOM) {
      this.addresses = [this._samplesHost[0]]
      return
    }

    if (this.firewall === FIREWALL.CONSISTENT) {
      this.addresses = []
      for (const addr of this._samplesFull) {
        if (addr.hits >= 2 || this.addresses.length < 2) this.addresses.push(addr)
      }
    }
  }

  update() {
    if (this.dht.firewalled && this.firewall === FIREWALL.OPEN) {
      this.firewall = FIREWALL.UNKNOWN
    }
    this._updateFirewall()
    this._updateAddresses()
  }

  add(addr, from) {
    const ref = from.host + ':' + from.port

    if (this._visited.get(ref) === 2) return
    this._visited.set(ref, 2)

    addSample(this._samplesHost, addr.host, 0)
    addSample(this._samplesFull, addr.host, addr.port)

    if ((++this.sampled >= 3 || !this.dht.firewalled) && !this.frozen) {
      this.update()
    }

    if (this.firewall === FIREWALL.CONSISTENT || this.firewall === FIREWALL.OPEN) {
      this._resolve()
    } else if (this.sampled >= this._minSamples) {
      this._resolve()
    }
  }
}

function addSample(samples, host, port) {
  for (let i = 0; i < samples.length; i++) {
    const s = samples[i]

    if (s.port !== port || s.host !== host) continue
    s.hits++

    for (; i > 0; i--) {
      const prev = samples[i - 1]
      if (prev.hits >= s.hits) return
      samples[i - 1] = s
      samples[i] = prev
    }

    return
  }

  samples.push({
    host,
    port,
    hits: 1
  })
}
const NoiseSecretStream = require('@hyperswarm/secret-stream')
const NoiseHandshake = require('noise-handshake')
const curve = require('noise-curve-ed')
const c = require('compact-encoding')
const b4a = require('b4a')
const sodium = require('sodium-universal')
const m = require('./messages')
const { NS } = require('./constants')
const { HANDSHAKE_UNFINISHED } = require('./errors')

const NOISE_PROLOUGE = NS.PEER_HANDSHAKE

module.exports = class NoiseWrap {
  constructor(keyPair, remotePublicKey) {
    this.isInitiator = !!remotePublicKey
    this.remotePublicKey = remotePublicKey
    this.keyPair = keyPair
    this.handshake = new NoiseHandshake('IK', this.isInitiator, keyPair, { curve })
    this.handshake.initialise(NOISE_PROLOUGE, remotePublicKey)
  }

  send(payload) {
    const buf = c.encode(m.noisePayload, payload)
    return this.handshake.send(buf)
  }

  recv(buf) {
    const payload = c.decode(m.noisePayload, this.handshake.recv(buf))
    this.remotePublicKey = b4a.toBuffer(this.handshake.rs)
    return payload
  }

  final() {
    if (!this.handshake.complete) throw HANDSHAKE_UNFINISHED()

    const holepunchSecret = b4a.allocUnsafe(32)

    sodium.crypto_generichash(holepunchSecret, NS.PEER_HOLEPUNCH, this.handshake.hash)

    return {
      isInitiator: this.isInitiator,
      publicKey: this.keyPair.publicKey,
      streamId: this.streamId,
      remotePublicKey: this.remotePublicKey,
      remoteId: NoiseSecretStream.id(this.handshake.hash, !this.isInitiator),
      holepunchSecret,
      hash: b4a.toBuffer(this.handshake.hash),
      rx: b4a.toBuffer(this.handshake.rx),
      tx: b4a.toBuffer(this.handshake.tx)
    }
  }
}
const c = require('compact-encoding')
const sodium = require('sodium-universal')
const RecordCache = require('record-cache')
const Cache = require('xache')
const b4a = require('b4a')
const unslab = require('unslab')

const { encodeUnslab } = require('./encode')
const m = require('./messages')
const { NS, ERROR } = require('./constants')

const EMPTY = b4a.alloc(0)
const TMP = b4a.allocUnsafe(32)
const MAX_BUMP_DRIFT = 60_000

module.exports = class Persistent {
  constructor(dht, opts) {
    this.dht = dht
    this.records = new RecordCache(opts.records)
    this.bumps = new Cache(opts.bumps)
    this.refreshes = new Cache(opts.refreshes)
    this.mutables = new Cache(opts.mutables)
    this.immutables = new Cache(opts.immutables)
  }

  onlookup(req) {
    if (!req.target) return

    const k = b4a.toString(req.target, 'hex')
    const records = this.records.get(k, 20)
    const bump = this.bumps.get(k) || 0
    const fwd = this.dht._router.get(k)

    if (fwd && records.length < 20) records.push(fwd.record)

    req.reply(records.length ? c.encode(m.lookupRawReply, { peers: records, bump }) : null)
  }

  onfindpeer(req) {
    if (!req.target) return
    const fwd = this.dht._router.get(req.target)
    req.reply(fwd ? fwd.record : null)
  }

  unannounce(target, publicKey) {
    const k = b4a.toString(target, 'hex')
    sodium.crypto_generichash(TMP, publicKey)

    if (b4a.equals(TMP, target)) this.dht._router.delete(k)
    this.records.remove(k, publicKey)
  }

  onunannounce(req) {
    if (!req.target || !req.token) return

    const unann = decode(m.announce, req.value)
    if (unann === null) return

    const { peer, signature } = unann
    if (!peer || !signature) return

    const signable = annSignable(req.target, req.token, this.dht.id, unann, NS.UNANNOUNCE)

    if (!sodium.crypto_sign_verify_detached(signature, signable, peer.publicKey)) {
      return
    }

    this.unannounce(req.target, peer.publicKey)
    req.reply(null, { token: false, closerNodes: false })
  }

  _onrefresh(token, req) {
    sodium.crypto_generichash(TMP, token)
    const activeRefresh = b4a.toString(TMP, 'hex')

    const r = this.refreshes.get(activeRefresh)
    if (!r) return

    const { announceSelf, k, record } = r
    const publicKey = record.subarray(0, 32)

    if (announceSelf) {
      this.dht._router.set(k, {
        relay: req.from,
        record,
        onconnect: null,
        onholepunch: null
      })
      this.records.remove(k, publicKey)
    } else {
      this.records.add(k, publicKey, record)
    }

    this.refreshes.delete(activeRefresh)
    this.refreshes.set(b4a.toString(token, 'hex'), r)

    req.reply(null, { token: false, closerNodes: false })
  }

  onannounce(req) {
    if (!req.target || !req.token || !this.dht.id) return

    const ann = decode(m.announce, req.value)
    if (ann === null) return

    const { peer, refresh, signature, bump } = ann

    if (!peer) {
      if (!refresh) return
      this._onrefresh(refresh, req)
      return
    }

    const signable = annSignable(req.target, req.token, this.dht.id, ann, NS.ANNOUNCE)

    if (!signature || !sodium.crypto_sign_verify_detached(signature, signable, peer.publicKey)) {
      return
    }

    // TODO: it would be potentially be more optimal to allow more than 3 addresses here for a findPeer response
    // and only use max 3 for a lookup reply
    if (peer.relayAddresses.length > 3) {
      peer.relayAddresses = peer.relayAddresses.slice(0, 3)
    }

    sodium.crypto_generichash(TMP, peer.publicKey)

    const k = b4a.toString(req.target, 'hex')
    const announceSelf = b4a.equals(TMP, req.target)
    const record = encodeUnslab(m.peer, peer)

    if (announceSelf) {
      this.dht._router.set(k, {
        relay: req.from,
        record,
        onconnect: null,
        onholepunch: null
      })
      this.records.remove(k, peer.publicKey)
    } else {
      const currentBump = this.bumps.get(k) || 0
      if (bump > currentBump && bump <= Date.now() + MAX_BUMP_DRIFT) this.bumps.set(k, bump)
      this.records.add(k, peer.publicKey, record)
    }

    if (refresh) {
      this.refreshes.set(b4a.toString(refresh, 'hex'), { k, record, announceSelf })
    }

    req.reply(null, { token: false, closerNodes: false })
  }

  onmutableget(req) {
    if (!req.target || !req.value) return

    let seq = 0
    try {
      seq = c.decode(c.uint, req.value)
    } catch {
      return
    }

    const k = b4a.toString(req.target, 'hex')
    const value = this.mutables.get(k)

    if (!value) {
      req.reply(null)
      return
    }

    const localSeq = c.decode(c.uint, value)
    req.reply(localSeq < seq ? null : value)
  }

  onmutableput(req) {
    if (!req.target || !req.token || !req.value) return

    const p = decode(m.mutablePutRequest, req.value)
    if (!p) return

    const { publicKey, seq, value, signature } = p

    const hash = b4a.allocUnsafe(32)
    sodium.crypto_generichash(hash, publicKey)
    if (!b4a.equals(hash, req.target)) return

    if (!value || !verifyMutable(signature, seq, value, publicKey)) return

    const k = b4a.toString(hash, 'hex')
    const local = this.mutables.get(k)

    if (local) {
      const existing = c.decode(m.mutableGetResponse, local)
      if (existing.value && existing.seq === seq && b4a.compare(value, existing.value) !== 0) {
        req.error(ERROR.SEQ_REUSED)
        return
      }
      if (seq < existing.seq) {
        req.error(ERROR.SEQ_TOO_LOW)
        return
      }
    }

    this.mutables.set(k, encodeUnslab(m.mutableGetResponse, { seq, value, signature }))
    req.reply(null)
  }

  onimmutableget(req) {
    if (!req.target) return

    const k = b4a.toString(req.target, 'hex')
    const value = this.immutables.get(k)

    req.reply(value || null)
  }

  onimmutableput(req) {
    if (!req.target || !req.token || !req.value) return

    const hash = b4a.alloc(32)
    sodium.crypto_generichash(hash, req.value)
    if (!b4a.equals(hash, req.target)) return

    const k = b4a.toString(hash, 'hex')
    this.immutables.set(k, unslab(req.value))

    req.reply(null)
  }

  onplugin(req) {
    if (!req.value) return

    const plugreq = decode(m.pluginRequest, req.value)
    if (plugreq === null) return

    const p = this.dht.plugins.get(plugreq.plugin)
    if (!p || p.version !== plugreq.version) return

    p.onrequest(plugreq, req)
  }

  destroy() {
    this.records.destroy()
    this.refreshes.destroy()
    this.mutables.destroy()
    this.immutables.destroy()
  }

  static signMutable(seq, value, keyPair) {
    const signable = b4a.allocUnsafe(32 + 32)
    const hash = signable.subarray(32)

    signable.set(NS.MUTABLE_PUT, 0)

    sodium.crypto_generichash(hash, c.encode(m.mutableSignable, { seq, value }))
    return sign(signable, keyPair)
  }

  static verifyMutable(signature, seq, value, publicKey) {
    return verifyMutable(signature, seq, value, publicKey)
  }

  static signAnnounce(target, token, id, ann, keyPair) {
    return sign(annSignable(target, token, id, ann, NS.ANNOUNCE), keyPair)
  }

  static signUnannounce(target, token, id, ann, keyPair) {
    return sign(annSignable(target, token, id, ann, NS.UNANNOUNCE), keyPair)
  }
}

function verifyMutable(signature, seq, value, publicKey) {
  const signable = b4a.allocUnsafe(32 + 32)
  const hash = signable.subarray(32)

  signable.set(NS.MUTABLE_PUT, 0)

  sodium.crypto_generichash(hash, c.encode(m.mutableSignable, { seq, value }))
  return sodium.crypto_sign_verify_detached(signature, signable, publicKey)
}

function annSignable(target, token, id, ann, ns) {
  const signable = b4a.allocUnsafe(32 + 32)
  const hash = signable.subarray(32)

  signable.set(ns, 0)

  sodium.crypto_generichash_batch(hash, [
    target,
    id,
    token,
    c.encode(m.peer, ann.peer), // note that this is the partial encoding of the announce message so we could just use that for perf
    ann.refresh || EMPTY
  ])

  return signable
}

function sign(signable, keyPair) {
  if (keyPair.sign) {
    return keyPair.sign(signable)
  }
  const secretKey = keyPair.secretKey ? keyPair.secretKey : keyPair
  const signature = b4a.allocUnsafe(64)
  sodium.crypto_sign_detached(signature, signable, secretKey)
  return signature
}

function decode(enc, val) {
  try {
    return val && c.decode(enc, val)
  } catch (err) {
    return null
  }
}
module.exports = class RawStreamSet {
  constructor(dht) {
    this._dht = dht

    this._prefix = 16 - 1 // 16 is the default stream-set side in udx
    this._streams = new Map()
  }

  get size() {
    return this._streams.size
  }

  [Symbol.iterator]() {
    return this._streams.values()
  }

  add(opts) {
    const self = this

    // TODO: we should prob have a udx helper for id generation, given the slight complexity
    // of the below. requires a PRNG in udx tho.

    let id = 0

    while (true) {
      id = (Math.random() * 0x100000000) >>> 0

      if (this._streams.has(id & this._prefix)) continue
      break
    }

    // always have ~50% change of rolling a free one
    if (2 * this._streams.size >= this._prefix) {
      // ie 0b11111 = 0b1111 + 1 + 0b1111
      this._prefix = 2 * this._prefix + 1

      // move the prefixes over
      const next = new Map()
      for (const stream of this._streams.values()) {
        next.set(stream.id & this._prefix, stream)
      }
      this._streams = next
    }

    const stream = this._dht.udx.createStream(id, opts)
    this._streams.set(id & this._prefix, stream)

    stream.on('close', onclose)

    return stream

    function onclose() {
      self._streams.delete(id & self._prefix)
    }
  }

  async clear() {
    const destroying = []

    for (const stream of this._streams.values()) {
      destroying.push(new Promise((resolve) => stream.once('close', resolve).destroy()))
    }

    await Promise.allSettled(destroying)
  }
}
const c = require('compact-encoding')
const Cache = require('xache')
const safetyCatch = require('safety-catch')
const b4a = require('b4a')
const { handshake, holepunch } = require('./messages')
const { COMMANDS } = require('./constants')
const { BAD_HANDSHAKE_REPLY, BAD_HOLEPUNCH_REPLY } = require('./errors')

const FROM_CLIENT = 0
const FROM_SERVER = 1
const FROM_RELAY = 2
const FROM_SECOND_RELAY = 3
const REPLY = 4

// TODO: While the current design is very trustless in regards to clients/servers trusting the DHT,
// we should add a bunch of rate limits everywhere, especially including here to avoid bad users
// using a DHT node to relay traffic indiscriminately using the connect/holepunch messages.
// That's mostly from an abuse POV as none of the messsages do amplication.

module.exports = class Router {
  constructor(dht, opts) {
    this.dht = dht
    this.forwards = new Cache(opts.forwards)
  }

  set(target, state) {
    if (state.onpeerhandshake) {
      this.forwards.retain(toString(target), state)
    } else {
      this.forwards.set(toString(target), state)
    }
  }

  get(target) {
    return this.forwards.get(toString(target))
  }

  delete(target) {
    this.forwards.delete(toString(target))
  }

  destroy() {
    this.forwards.destroy()
  }

  async peerHandshake(target, { noise, peerAddress, relayAddress, socket, session }, to) {
    const dht = this.dht

    const requestValue = c.encode(handshake, {
      mode: FROM_CLIENT,
      noise,
      peerAddress,
      relayAddress
    })

    const res = await dht.request(
      { command: COMMANDS.PEER_HANDSHAKE, target, value: requestValue },
      to,
      { socket, session }
    )

    const hs = decode(handshake, res.value)
    if (
      !hs ||
      hs.mode !== REPLY ||
      to.host !== res.from.host ||
      to.port !== res.from.port ||
      !hs.noise
    ) {
      throw BAD_HANDSHAKE_REPLY()
    }

    return {
      noise: hs.noise,
      relayed: !!hs.peerAddress,
      serverAddress: hs.peerAddress || to,
      clientAddress: res.to
    }
  }

  async onpeerhandshake(req) {
    const hs = req.value && decode(handshake, req.value)
    if (!hs) return

    const { mode, noise, peerAddress, relayAddress } = hs

    const state = req.target && this.get(req.target)
    const isServer = !!(state && state.onpeerhandshake)
    const relay = state && state.relay

    if (isServer) {
      let reply = null
      try {
        reply = noise && (await state.onpeerhandshake({ noise, peerAddress }, req))
      } catch (e) {
        safetyCatch(e)
        return
      }
      if (!reply || !reply.noise) return
      const opts = { socket: reply.socket, closerNodes: false, token: false }

      switch (mode) {
        case FROM_CLIENT: {
          req.reply(
            c.encode(handshake, { mode: REPLY, noise: reply.noise, peerAddress: null }),
            opts
          )
          return
        }
        case FROM_RELAY: {
          req.relay(
            c.encode(handshake, { mode: FROM_SERVER, noise: reply.noise, peerAddress }),
            req.from,
            opts
          )
          return
        }
        case FROM_SECOND_RELAY: {
          if (!relayAddress) return
          req.relay(
            c.encode(handshake, { mode: FROM_SERVER, noise: reply.noise, peerAddress }),
            relayAddress,
            opts
          )
          return // eslint-disable-line
        }
      }
    } else {
      switch (mode) {
        case FROM_CLIENT: {
          // TODO: if no relay is known route closer to the target instead of timing out
          if (!noise) return
          if (!relay && !relayAddress) {
            // help the user route
            req.reply(null, { token: false, closerNodes: true })
            return
          }
          req.relay(
            c.encode(handshake, {
              mode: FROM_RELAY,
              noise,
              peerAddress: req.from,
              relayAddress: null
            }),
            relayAddress || relay
          )
          return
        }
        case FROM_RELAY: {
          if (!relay || !noise) return
          req.relay(
            c.encode(handshake, {
              mode: FROM_SECOND_RELAY,
              noise,
              peerAddress,
              relayAddress: req.from
            }),
            relay
          )
          return
        }
        case FROM_SERVER: {
          if (!peerAddress || !noise) return
          req.reply(
            c.encode(handshake, { mode: REPLY, noise, peerAddress: req.from, relayAddress: null }),
            { to: peerAddress, closerNodes: false, token: false }
          )
          return // eslint-disable-line
        }
      }
    }
  }

  async peerHolepunch(target, { id, payload, peerAddress, socket, session }, to) {
    const dht = this.dht
    const requestValue = c.encode(holepunch, {
      mode: FROM_CLIENT,
      id,
      payload,
      peerAddress
    })

    const res = await dht.request(
      { command: COMMANDS.PEER_HOLEPUNCH, target, value: requestValue },
      to,
      { socket, session }
    )

    const hp = decode(holepunch, res.value)
    if (!hp || hp.mode !== REPLY || to.host !== res.from.host || to.port !== res.from.port) {
      throw BAD_HOLEPUNCH_REPLY()
    }

    return {
      from: res.from,
      to: res.to,
      payload: hp.payload,
      peerAddress: hp.peerAddress || to
    }
  }

  async onpeerholepunch(req) {
    const hp = req.value && decode(holepunch, req.value)
    if (!hp) return

    const { mode, id, payload, peerAddress } = hp

    const state = req.target && this.get(req.target)
    const isServer = !!(state && state.onpeerholepunch)
    const relay = state && state.relay

    switch (mode) {
      case FROM_CLIENT: {
        if (!peerAddress && !relay) return
        req.relay(
          c.encode(holepunch, { mode: FROM_RELAY, id, payload, peerAddress: req.from }),
          peerAddress || relay
        )
        return
      }
      case FROM_RELAY: {
        if (!isServer || !peerAddress) return
        let reply = null
        try {
          reply = await state.onpeerholepunch({ id, payload, peerAddress }, req)
        } catch (e) {
          safetyCatch(e)
          return
        }
        if (!reply) return
        const opts = { socket: reply.socket, closerNodes: false, token: false }
        req.relay(
          c.encode(holepunch, { mode: FROM_SERVER, id: 0, payload: reply.payload, peerAddress }),
          req.from,
          opts
        )
        return
      }
      case FROM_SERVER: {
        req.reply(c.encode(holepunch, { mode: REPLY, id, payload, peerAddress: req.from }), {
          to: peerAddress,
          closerNodes: false,
          token: false
        })
        return // eslint-disable-line
      }
    }
  }
}

function decode(enc, val) {
  try {
    return c.decode(enc, val)
  } catch {
    return null
  }
}

function toString(t) {
  return typeof t === 'string' ? t : b4a.toString(t, 'hex')
}
const sodium = require('sodium-universal')
const b4a = require('b4a')
const { holepunchPayload } = require('./messages')

module.exports = class HolepunchPayload {
  constructor(holepunchSecret) {
    this._sharedSecret = holepunchSecret
    this._localSecret = b4a.allocUnsafe(32)

    sodium.randombytes_buf(this._localSecret)
  }

  decrypt(buffer) {
    const state = { start: 24, end: buffer.byteLength - 16, buffer }

    if (state.end <= state.start) return null

    const nonce = buffer.subarray(0, 24)
    const msg = state.buffer.subarray(state.start, state.end)
    const cipher = state.buffer.subarray(state.start)

    if (!sodium.crypto_secretbox_open_easy(msg, cipher, nonce, this._sharedSecret)) return null

    try {
      return holepunchPayload.decode(state)
    } catch {
      return null
    }
  }

  encrypt(payload) {
    const state = { start: 24, end: 24, buffer: null }
    holepunchPayload.preencode(state, payload)
    state.buffer = b4a.allocUnsafe(state.end + 16)

    const nonce = state.buffer.subarray(0, 24)
    const msg = state.buffer.subarray(state.start, state.end)
    const cipher = state.buffer.subarray(state.start)

    holepunchPayload.encode(state, payload)
    sodium.randombytes_buf(nonce)
    sodium.crypto_secretbox_easy(cipher, msg, nonce, this._sharedSecret)

    return state.buffer
  }

  token(addr) {
    const out = b4a.allocUnsafe(32)
    sodium.crypto_generichash(out, b4a.from(addr.host), this._localSecret)
    return out
  }
}
const DONE = Promise.resolve(true)
const DESTROYED = Promise.resolve(false)

module.exports = class Semaphore {
  constructor(limit = 1) {
    this.limit = limit
    this.active = 0
    this.waiting = []

    this.flushedPromise = null
    this.flushedResolve = null

    this.destroyed = false

    this._onwait = this._queueWaiting.bind(this)
    this._onflush = this._queueFlushed.bind(this)
  }

  _queueWaiting(resolve) {
    this.waiting.push(resolve)
  }

  _queueFlushed(resolve) {
    this.flushedResolve = resolve
  }

  wait() {
    if (this.destroyed === true) return DESTROYED

    if (this.active < this.limit && this.waiting.length === 0) {
      this.active++
      return DONE
    }

    return new Promise(this._onwait)
  }

  signal() {
    if (this.destroyed === true) return

    this.active--
    while (this.active < this.limit && this.waiting.length > 0 && this.destroyed === false) {
      this.active++
      this.waiting.shift()(true)
    }

    if (this.active === 0 && this.flushedResolve) {
      const resolve = this.flushedResolve
      this.flushedResolve = null
      this.flushedPromise = null
      resolve(true)
    }
  }

  async flush() {
    if (this.destroyed === true) return
    if (this.active === 0) return
    if (this.flushedPromise) return this.flushedPromise
    this.flushedPromise = new Promise(this._onflush)
    return this.flushedPromise
  }

  destroy() {
    this.destroyed = true
    this.active = 0
    while (this.waiting.length) this.waiting.pop()(false)
    if (this.flushedResolve) this.flushedResolve(false)
  }
}
const { EventEmitter } = require('events')
const safetyCatch = require('safety-catch')
const NoiseSecretStream = require('@hyperswarm/secret-stream')
const b4a = require('b4a')
const relay = require('blind-relay')
const NoiseWrap = require('./noise-wrap')
const Announcer = require('./announcer')
const { FIREWALL, ERROR } = require('./constants')
const { unslabbedHash } = require('./crypto')
const SecurePayload = require('./secure-payload')
const Holepuncher = require('./holepuncher')
const { isPrivate } = require('bogon')
const { ALREADY_LISTENING, NODE_DESTROYED, KEYPAIR_ALREADY_USED } = require('./errors')

const HANDSHAKE_CLEAR_WAIT = 10000
const HANDSHAKE_INITIAL_TIMEOUT = 10000

module.exports = class Server extends EventEmitter {
  constructor(dht, opts = {}) {
    super()

    this.dht = dht
    this.target = null

    this.closed = false
    this.firewall = opts.firewall || (() => false)
    this.holepunch = opts.holepunch || (() => true)
    this.relayThrough = opts.relayThrough || null
    this.relayKeepAlive = opts.relayKeepAlive || 5000
    this.pool = opts.pool || null
    this.createHandshake = opts.createHandshake || defaultCreateHandshake
    this.createSecretStream = opts.createSecretStream || defaultCreateSecretStream
    this.suspended = false
    this.handshakeClearWait = opts.handshakeClearWait || HANDSHAKE_CLEAR_WAIT

    this._shareLocalAddress = opts.shareLocalAddress !== false
    this._reusableSocket = !!opts.reusableSocket
    this._neverPunch = opts.holepunch === false // useful for fully disabling punching
    this._keyPair = null
    this._announcer = null
    this._connects = new Map()
    this._holepunches = []
    this._listening = null
    this._closing = null
  }

  get listening() {
    return this._listening !== null
  }

  get publicKey() {
    return this._keyPair && this._keyPair.publicKey
  }

  get relayAddresses() {
    return this._announcer ? this._announcer.relayAddresses : []
  }

  onconnection(encryptedSocket) {
    this.emit('connection', encryptedSocket)
  }

  async suspend({ log = noop } = {}) {
    log('Suspending hyperdht server')
    if (this._listening !== null) await this._listening
    log('Suspending hyperdht server (post listening)')
    this.suspended = true
    this._clearAll()
    return this._announcer ? this._announcer.suspend({ log }) : Promise.resolve()
  }

  async resume() {
    if (this._listening !== null) await this._listening
    this.suspended = false
    return this._announcer ? this._announcer.resume() : Promise.resolve()
  }

  address() {
    if (!this._keyPair) return null

    return {
      publicKey: this._keyPair.publicKey,
      host: this.dht.host,
      port: this.dht.port
    }
  }

  close() {
    if (this._closing) return this._closing
    this._closing = this._close()
    return this._closing
  }

  _gc() {
    this.dht.listening.delete(this)
    if (this.target) this.dht._router.delete(this.target)
  }

  async _stopListening() {
    try {
      if (this._announcer) await this._announcer.stop()
    } catch {
      // ignore
    }

    this._announcer = null
    this._listening = null
    this._keyPair = null
  }

  async _close() {
    if (this._listening === null) {
      this.closed = true
      this.emit('close')
      return
    }

    try {
      await this._listening
    } catch (err) {
      safetyCatch(err)
    }

    this._gc()
    this._clearAll()

    await this._stopListening()

    this.closed = true
    this.emit('close')
  }

  _clearAll() {
    while (this._holepunches.length > 0) {
      const h = this._holepunches.pop()
      if (h && h.puncher) h.puncher.destroy()
      if (h && h.clearing) clearTimeout(h.clearing)
      if (h && h.prepunching) clearTimeout(h.prepunching)
      if (h && h.rawStream) h.rawStream.destroy()
    }

    this._connects.clear()
  }

  async listen(keyPair = this.dht.defaultKeyPair, opts = {}) {
    if (this._listening !== null) throw ALREADY_LISTENING()
    if (this.dht.destroyed) throw NODE_DESTROYED()

    this._listening = this._listen(keyPair, opts)
    await this._listening
    return this
  }

  async _listen(keyPair, opts) {
    // From now on, the DHT object which created me is responsible for closing me
    this.dht.listening.add(this)

    try {
      await this.dht.bind()
      if (this._closing) return

      for (const s of this.dht.listening) {
        if (s._keyPair && b4a.equals(s._keyPair.publicKey, keyPair.publicKey)) {
          throw KEYPAIR_ALREADY_USED()
        }
      }

      this.target = unslabbedHash(keyPair.publicKey)
      this._keyPair = keyPair
      this._announcer = new Announcer(this.dht, keyPair, this.target, opts)

      this.dht._router.set(this.target, {
        relay: null,
        record: this._announcer.record,
        onpeerhandshake: this._onpeerhandshake.bind(this),
        onpeerholepunch: this._onpeerholepunch.bind(this)
      })

      // warm it up for now
      this._localAddresses().catch(safetyCatch)

      await this._announcer.start()
    } catch (err) {
      await this._stopListening()
      this._gc()
      throw err
    }

    if (this._closing) return
    if (this.suspended) await this._announcer.suspend()

    if (this._closing) return
    if (this.dht.destroyed) throw NODE_DESTROYED()

    if (this.pool) this.pool._attachServer(this)

    this.emit('listening')
  }

  refresh() {
    if (this._announcer && !this.suspended) this._announcer.refresh()
  }

  notifyOnline() {
    if (this._announcer) this._announcer.online.notify()
  }

  _localAddresses() {
    return this.dht.validateLocalAddresses(Holepuncher.localAddresses(this.dht.io.serverSocket))
  }

  async _addHandshake(k, noise, clientAddress, { from, to: serverAddress, socket }, direct) {
    let id = this._holepunches.indexOf(null)
    if (id === -1) id = this._holepunches.push(null) - 1

    const hs = {
      round: 0,
      reply: null,
      puncher: null,
      payload: null,
      rawStream: null,
      encryptedSocket: null,
      prepunching: null,
      firewalled: true,
      clearing: null,
      onsocket: null,
      aborted: false,

      // Relay state
      relayTimeout: null,
      relayToken: null,
      relaySocket: null,
      relayClient: null,
      relayPaired: false
    }

    this._holepunches[id] = hs

    const handshake = this.createHandshake(this._keyPair, null)

    let remotePayload
    try {
      remotePayload = await handshake.recv(noise)
    } catch (err) {
      safetyCatch(err)
      this._clearLater(hs, id, k)
      return null
    }

    if (this._closing || this.suspended) return null

    try {
      hs.firewalled = await this.firewall(handshake.remotePublicKey, remotePayload, clientAddress)
    } catch (err) {
      safetyCatch(err)
    }

    if (this._closing || this.suspended) return null

    if (hs.firewalled) {
      this._clearLater(hs, id, k)
      return null
    }

    const error =
      remotePayload.version === 1
        ? remotePayload.udx
          ? ERROR.NONE
          : ERROR.ABORTED
        : ERROR.VERSION_MISMATCH

    const addresses = []
    const ourRemoteAddr = this.dht.remoteAddress()
    const ourLocalAddrs = this._shareLocalAddress ? await this._localAddresses() : null

    if (this._closing || this.suspended) return null

    if (ourRemoteAddr) addresses.push(ourRemoteAddr)
    if (ourLocalAddrs) addresses.push(...ourLocalAddrs)

    if (error === ERROR.NONE) {
      hs.rawStream = this.dht.createRawStream({
        framed: true,
        firewall(socket, port, host) {
          if (!(port > 0 && port < 65536)) return true

          // Check if the traffic originated from the socket on which we're expecting relay traffic. If so,
          // we haven't hole punched yet and the other side is just sending us traffic through the relay.
          if (hs.relaySocket && isRelay(hs.relaySocket, socket, port, host)) {
            return false
          }

          hs.onsocket(socket, port, host)
          return false
        }
      })

      hs.rawStream.on('error', autoDestroy)

      // Handles the case where onsocket is never called, but the stream got setup
      // This can happen on a relayed connection which never connects directly
      // (onsocket is called there only when the direct connection is established)
      const onrawstreamclose = () => {
        if (this._closing) return
        this._clearLater(hs, id, k)
      }
      hs.rawStream.on('close', onrawstreamclose)

      hs.onsocket = (socket, port, host) => {
        if (hs.rawStream === null) return // Already hole punched

        this._clearLater(hs, id, k)

        if (hs.prepunching) {
          clearTimeout(hs.prepunching)
          hs.prepunching = null
        }

        if (this._reusableSocket && remotePayload.udx.reusableSocket) {
          this.dht._socketPool.routes.add(handshake.remotePublicKey, hs.rawStream)
        }

        hs.rawStream.removeListener('error', autoDestroy)
        hs.rawStream.removeListener('close', onrawstreamclose)

        if (hs.rawStream.connected) {
          const remoteChanging = hs.rawStream.changeRemote(socket, remotePayload.udx.id, port, host)

          if (remoteChanging) remoteChanging.catch(safetyCatch)
        } else {
          hs.rawStream.connect(socket, remotePayload.udx.id, port, host)
          hs.encryptedSocket = this.createSecretStream(false, hs.rawStream, {
            handshake: h,
            keepAlive: this.dht.connectionKeepAlive
          })

          this.onconnection(hs.encryptedSocket)
        }

        if (hs.puncher) {
          hs.puncher.onabort = noop
          hs.puncher.destroy()
        }

        hs.rawStream = null
      }

      function autoDestroy() {
        if (hs.puncher) hs.puncher.destroy()
      }
    }

    const relayAddresses = this.relayAddresses
    const relayThrough = selectRelay(this.relayThrough)

    if (relayThrough) hs.relayToken = relay.token()

    try {
      hs.reply = await handshake.send({
        error,
        firewall: ourRemoteAddr ? FIREWALL.OPEN : FIREWALL.UNKNOWN,
        holepunch: ourRemoteAddr ? null : { id, relays: this._announcer.relays },
        addresses4: addresses,
        addresses6: null,
        udx: {
          reusableSocket: this._reusableSocket,
          id: hs.rawStream ? hs.rawStream.id : 0,
          seq: 0
        },
        secretStream: {},
        relayThrough: relayThrough ? { publicKey: relayThrough, token: hs.relayToken } : null,
        relayAddresses: relayAddresses.length ? relayAddresses : null
      })
    } catch (err) {
      safetyCatch(err)
      if (hs.rawStream) hs.rawStream.destroy()
      this._clearLater(hs, id, k)
      return null
    }

    if (this._closing || this.suspended) {
      if (hs.rawStream) hs.rawStream.destroy()
      return null
    }

    const h = handshake.final()

    if (error !== ERROR.NONE) {
      if (hs.rawStream) hs.rawStream.destroy()
      this._clearLater(hs, id, k)
      return hs
    }

    if (remotePayload.firewall === FIREWALL.OPEN || direct) {
      const sock = direct ? socket : this.dht.socket
      this.dht.stats.punches.open++
      hs.onsocket(sock, clientAddress.port, clientAddress.host)
      return hs
    }

    if (relayThrough || remotePayload.relayThrough) {
      this._relayConnection(hs, relayThrough, remotePayload, h)
    }

    const onabort = () => {
      hs.aborted = true
      if (hs.prepunching) clearTimeout(hs.prepunching)
      hs.prepunching = null
      if (hs.rawStream.destroyed) {
        this._clearLater(hs, id, k)
        return
      }

      hs.rawStream.on('close', () => this._clearLater(hs, id, k))
      if (hs.relayToken === null) hs.rawStream.destroy()
    }

    if (!direct && clientAddress.host === serverAddress.host) {
      const clientAddresses = remotePayload.addresses4.filter(onlyPrivateHosts)

      if (clientAddresses.length > 0 && this._shareLocalAddress) {
        const myAddresses = await this._localAddresses()
        const addr = Holepuncher.matchAddress(myAddresses, clientAddresses)

        if (addr) {
          hs.prepunching = setTimeout(onabort, HANDSHAKE_INITIAL_TIMEOUT)
          return hs
        }
      }
    }

    if (this._closing || this.suspended) return null

    if (ourRemoteAddr || this._neverPunch) {
      hs.prepunching = setTimeout(onabort, HANDSHAKE_INITIAL_TIMEOUT)
      return hs
    }

    hs.payload = new SecurePayload(h.holepunchSecret)
    hs.puncher = new Holepuncher(this.dht, this.dht.session(), false, remotePayload.firewall)

    hs.puncher.onconnect = hs.onsocket
    hs.puncher.onabort = onabort
    hs.prepunching = setTimeout(hs.puncher.destroy.bind(hs.puncher), HANDSHAKE_INITIAL_TIMEOUT)

    return hs
  }

  _clearLater(hs, id, k) {
    if (hs.clearing) return
    hs.clearing = setTimeout(() => this._clear(hs, id, k), this.handshakeClearWait)
  }

  _clear(hs, id, k) {
    if (id >= this._holepunches.length || this._holepunches[id] !== hs) return
    if (hs.clearing) clearTimeout(hs.clearing)

    this._holepunches[id] = null
    while (
      this._holepunches.length > 0 &&
      this._holepunches[this._holepunches.length - 1] === null
    ) {
      this._holepunches.pop()
    }
    this._connects.delete(k)
  }

  async _onpeerhandshake({ noise, peerAddress }, req) {
    const k = b4a.toString(noise, 'hex')

    // The next couple of statements MUST run within the same tick to prevent
    // a malicious peer from flooding us with handshakes.
    let p = this._connects.get(k)
    if (!p) {
      p = this._addHandshake(k, noise, peerAddress || req.from, req, !peerAddress)
      this._connects.set(k, p)
    }

    const h = await p
    if (!h) return null

    if (this._closing !== null || this.suspended) return null

    return { socket: h.puncher && h.puncher.socket, noise: h.reply }
  }

  async _onpeerholepunch({ id, peerAddress, payload }, req) {
    const h = id < this._holepunches.length ? this._holepunches[id] : null
    if (!h) return null

    if (!peerAddress || this._closing !== null || this.suspended) return null

    const p = h.puncher
    if (!p || !p.socket) return this._abort(h) // not opened

    const remotePayload = h.payload.decrypt(payload)
    if (!remotePayload) return null

    const isServerRelay = this._announcer.isRelay(req.from)
    const { error, firewall, round, punching, addresses, remoteAddress, remoteToken } =
      remotePayload

    if (error !== ERROR.NONE) {
      // We actually do not need to set the round here, but just do it for consistency.
      if (round >= h.round) h.round = round
      return this._abort(h)
    }

    const token = h.payload.token(peerAddress)
    const echoed = isServerRelay && !!remoteToken && b4a.equals(token, remoteToken)

    // Update our heuristics here
    if (req.socket === p.socket) {
      p.nat.add(req.to, req.from)
    }

    if (round >= h.round) {
      h.round = round
      p.updateRemote({ punching, firewall, addresses, verified: echoed ? peerAddress.host : null })
    }

    // Wait for the analyzer to reach a conclusion...
    let stable = await p.analyze(false)
    if (p.destroyed) return null

    if (!p.remoteHolepunching && !stable) {
      stable = await p.analyze(true)
      if (p.destroyed) return null
      if (!stable) return this._abort(h)
    }

    // Fast mode! If we are consistent and the remote has opened a session to us (remoteAddress)
    // then fire a quick punch back. Note the await here just waits for the udp socket to flush.
    if (
      isConsistent(p.nat.firewall) &&
      remoteAddress &&
      hasSameAddr(p.nat.addresses, remoteAddress)
    ) {
      await p.ping(peerAddress)
      if (p.destroyed) return null
    }

    // Remote said they are punching (or willing to), so we will punch as well.
    // Note that this returns when the punching has STARTED, so no guarantee
    // we will have a connection after this promise etc.
    if (p.remoteHolepunching) {
      // TODO: still continue here if a local connection might work, but then do not holepunch...
      if (!this.holepunch(p.remoteFirewall, p.nat.firewall, p.remoteAddresses, p.nat.addresses)) {
        return p.destroyed ? null : this._abort(h)
      }

      if (h.prepunching) {
        clearTimeout(h.prepunching)
        h.prepunching = null
      }

      if (p.remoteFirewall >= FIREWALL.RANDOM || p.nat.firewall >= FIREWALL.RANDOM) {
        if (
          this.dht._randomPunches >= this.dht._randomPunchLimit ||
          Date.now() - this.dht._lastRandomPunch < this.dht._randomPunchInterval
        ) {
          if (!h.relayToken) return this._abort(h, ERROR.TRY_LATER)
          return {
            socket: p.socket,
            payload: h.payload.encrypt({
              error: ERROR.TRY_LATER,
              firewall: p.nat.firewall,
              round: h.round,
              connected: p.connected,
              punching: p.punching,
              addresses: p.nat.addresses,
              remoteAddress: null,
              token: isServerRelay ? token : null,
              remoteToken: remotePayload.token
            })
          }
        }
      }

      const punching = await p.punch()
      if (p.destroyed) return null
      if (!punching) return this._abort(h)
    }

    // Freeze that analysis as soon as we have a result we are giving to the other peer
    if (p.nat.firewall !== FIREWALL.UNKNOWN) {
      p.nat.freeze()
    }

    return {
      socket: p.socket,
      payload: h.payload.encrypt({
        error: ERROR.NONE,
        firewall: p.nat.firewall,
        round: h.round,
        connected: p.connected,
        punching: p.punching,
        addresses: p.nat.addresses,
        remoteAddress: null,
        token: isServerRelay ? token : null,
        remoteToken: remotePayload.token
      })
    }
  }

  _abort(h, error = ERROR.ABORTED) {
    if (!h.payload) {
      if (h.puncher) h.puncher.destroy()
      return null
    }

    const payload = h.payload.encrypt({
      error,
      firewall: FIREWALL.UNKNOWN,
      round: h.round,
      connected: false,
      punching: false,
      addresses: null,
      remoteAddress: null,
      token: null,
      remoteToken: null
    })

    h.puncher.destroy()

    return { socket: this.dht.socket, payload }
  }

  _relayConnection(hs, relayThrough, remotePayload, h) {
    this.dht.stats.relaying.attempts++

    let isInitiator
    let publicKey
    let token

    if (relayThrough) {
      isInitiator = true
      publicKey = relayThrough
      token = hs.relayToken
    } else {
      isInitiator = false
      publicKey = remotePayload.relayThrough.publicKey
      token = remotePayload.relayThrough.token
    }

    hs.relayToken = token
    hs.relaySocket = this.dht.connect(publicKey)
    hs.relaySocket.setKeepAlive(this.relayKeepAlive)
    hs.relayClient = relay.Client.from(hs.relaySocket, { id: hs.relaySocket.publicKey })
    hs.relayTimeout = setTimeout(onabort, 15000)

    hs.relayClient
      .pair(isInitiator, token, hs.rawStream)
      .on('error', onabort)
      .on('data', (remoteId) => {
        if (hs.relayTimeout) clearRelayTimeout(hs)
        if (hs.rawStream === null) {
          onabort(null)
          return
        }

        hs.relayPaired = true
        this.dht.stats.relaying.successes++

        if (hs.prepunching) clearTimeout(hs.prepunching)
        hs.prepunching = null

        const { remotePort, remoteHost, socket } = hs.relaySocket.rawStream

        hs.rawStream
          .on('close', () => hs.relaySocket.destroy())
          .connect(socket, remoteId, remotePort, remoteHost)

        hs.encryptedSocket = this.createSecretStream(false, hs.rawStream, { handshake: h })

        this.onconnection(hs.encryptedSocket)
      })

    const dht = this.dht
    function onabort() {
      if (!hs.relayPaired) dht.stats.relaying.aborts++
      if (hs.relayTimeout) clearRelayTimeout(hs)
      const socket = hs.relaySocket
      hs.relayToken = null
      hs.relaySocket = null
      if (socket) socket.destroy()
      if (hs.aborted && hs.rawStream) hs.rawStream.destroy()
    }
  }
}

function clearRelayTimeout(hs) {
  clearTimeout(hs.relayTimeout)
  hs.relayTimeout = null
}

function isConsistent(fw) {
  return fw === FIREWALL.OPEN || fw === FIREWALL.CONSISTENT
}

function hasSameAddr(addrs, other) {
  if (addrs === null) return false

  for (const addr of addrs) {
    if (addr.port === other.port && addr.host === other.host) return true
  }
  return false
}

function defaultCreateHandshake(keyPair, remotePublicKey) {
  return new NoiseWrap(keyPair, remotePublicKey)
}

function defaultCreateSecretStream(isInitiator, rawStream, opts) {
  return new NoiseSecretStream(isInitiator, rawStream, opts)
}

function onlyPrivateHosts(addr) {
  return isPrivate(addr.host)
}

function isRelay(relaySocket, socket, port, host) {
  const stream = relaySocket.rawStream
  if (!stream) return false
  if (stream.socket !== socket) return false
  return port === stream.remotePort && host === stream.remoteHost
}

function selectRelay(relayThrough) {
  if (typeof relayThrough === 'function') relayThrough = relayThrough()
  if (relayThrough === null) return null
  if (Array.isArray(relayThrough)) {
    return relayThrough[Math.floor(Math.random() * relayThrough.length)]
  }
  return relayThrough
}

function noop() {}
module.exports = class Sleeper {
  constructor() {
    this._timeout = null
    this._resolve = null

    this._start = (resolve) => {
      this._resolve = resolve
    }

    this._trigger = () => {
      if (this._resolve === null) return
      const resolve = this._resolve
      this._timeout = null
      this._resolve = null
      resolve()
    }
  }

  pause(ms) {
    const p = new Promise(this._start)
    if (this._timeout !== null) {
      clearTimeout(this._timeout)
      this._trigger()
    }
    this._timeout = setTimeout(this._trigger, ms)
    return p
  }

  resume() {
    if (this._timeout !== null) {
      clearTimeout(this._timeout)
      this._trigger()
    }
  }
}
const b4a = require('b4a')

const LINGER_TIME = 3000

module.exports = class SocketPool {
  constructor(dht, host) {
    this._dht = dht
    this._sockets = new Map()
    this._lingering = new Set() // updated by the ref
    this._host = host

    this.routes = new SocketRoutes(this)
  }

  _onmessage(ref, data, address) {
    this._dht.onmessage(ref.socket, data, address)
  }

  _add(ref) {
    this._sockets.set(ref.socket, ref)
  }

  _remove(ref) {
    this._sockets.delete(ref.socket)
    this._lingering.delete(ref)
  }

  lookup(socket) {
    return this._sockets.get(socket) || null
  }

  setReusable(socket, bool) {
    const ref = this.lookup(socket)
    if (ref) ref.reusable = bool
  }

  acquire() {
    // TODO: Enable socket reuse
    return new SocketRef(this)
  }

  async destroy() {
    const closing = []

    for (const ref of this._sockets.values()) {
      ref._unlinger()
      closing.push(ref.socket.close())
    }

    await Promise.allSettled(closing)
  }
}

class SocketRoutes {
  constructor(pool) {
    this._pool = pool
    this._routes = new Map()
  }

  add(publicKey, rawStream) {
    if (rawStream.socket) this._onconnect(publicKey, rawStream)
    else rawStream.on('connect', this._onconnect.bind(this, publicKey, rawStream))
  }

  get(publicKey) {
    const id = b4a.toString(publicKey, 'hex')
    const route = this._routes.get(id)
    if (!route) return null
    return route
  }

  _onconnect(publicKey, rawStream) {
    const id = b4a.toString(publicKey, 'hex')
    const socket = rawStream.socket

    let route = this._routes.get(id)

    if (!route) {
      const gc = () => {
        if (this._routes.get(id) === route) this._routes.delete(id)
        socket.removeListener('close', gc)
      }

      route = {
        socket,
        address: { host: rawStream.remoteHost, port: rawStream.remotePort },
        gc
      }

      this._routes.set(id, route)
      socket.on('close', gc)
    }

    this._pool.setReusable(socket, true)

    rawStream.on('error', () => {
      this._pool.setReusable(socket, false)
      if (!route) route = this._routes.get(id)
      if (route && route.socket === socket) route.gc()
    })
  }
}

// TODO: we should just make some "user data" object on udx to allow to attach this info
class SocketRef {
  constructor(pool) {
    this._pool = pool

    // Events
    this.onholepunchmessage = noop

    // Whether it should teardown immediately or wait a bit
    this.reusable = false

    this.socket = pool._dht.udx.createSocket()
    this.socket
      .on('close', this._onclose.bind(this))
      .on('message', this._onmessage.bind(this))
      .on('idle', this._onidle.bind(this))
      .on('busy', this._onbusy.bind(this))
      .bind(0, this._pool._host)

    this._refs = 1
    this._released = false
    this._closed = false

    this._timeout = null
    this._wasBusy = false

    this._pool._add(this)
  }

  _onclose() {
    this._pool._remove(this)
  }

  _onmessage(data, address) {
    if (data.byteLength > 1) {
      this._pool._onmessage(this, data, address)
    } else {
      this.onholepunchmessage(data, address, this)
    }
  }

  _onidle() {
    this._closeMaybe()
  }

  _onbusy() {
    this._wasBusy = true
    this._unlinger()
  }

  _reset() {
    this.onholepunchmessage = noop
  }

  _closeMaybe() {
    if (this._refs === 0 && this.socket.idle && !this._timeout) this._close()
  }

  _lingeringClose() {
    this._pool._lingering.delete(this)
    this._timeout = null
    this._closeMaybe()
  }

  _close() {
    this._unlinger()

    if (this.reusable && this._wasBusy) {
      this._wasBusy = false
      this._pool._lingering.add(this)
      this._timeout = setTimeout(this._lingeringClose.bind(this), LINGER_TIME)
      return
    }

    this._closed = true
    this.socket.close()
  }

  _unlinger() {
    if (this._timeout !== null) {
      clearTimeout(this._timeout)
      this._pool._lingering.delete(this)
      this._timeout = null
    }
  }

  get free() {
    return this._refs === 0
  }

  active() {
    this._refs++
    this._unlinger()
  }

  inactive() {
    this._refs--
    this._closeMaybe()
  }

  address() {
    return this.socket.address()
  }

  release() {
    if (this._released) return

    this._released = true
    this._reset()

    this._refs--
    this._closeMaybe()
  }
}

function noop() {}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return uint24.decode(state) + 0x1000000 * uint32.decode(state)
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return uint32.decode(state) + 0x100000000 * uint32.decode(state)
  }
})

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "2.19.2",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    if (b.byteLength === 0) return null
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "hyperdht",
  "version": "6.31.0",
  "description": "The DHT powering Hyperswarm",
  "main": "index.js",
  "browser": "browser.js",
  "bin": {
    "hyperdht": "./bin.js"
  },
  "files": [
    "index.js",
    "browser.js",
    "testnet.js",
    "bin.js",
    "lib/**.js"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    },
    "child_process": {
      "bare": "bare-node-child-process",
      "default": "child_process"
    }
  },
  "dependencies": {
    "@hyperswarm/secret-stream": "^6.6.2",
    "b4a": "^1.3.1",
    "bare-events": "^2.2.0",
    "blind-relay": "^1.3.0",
    "bogon": "^1.0.0",
    "compact-encoding": "^2.4.1",
    "dht-rpc": "^6.15.1",
    "hypercore-crypto": "^3.3.0",
    "hypercore-id-encoding": "^1.2.0",
    "hyperdht-address": "^1.0.1",
    "noise-curve-ed": "^2.0.0",
    "noise-handshake": "^4.0.0",
    "record-cache": "^1.1.1",
    "safety-catch": "^1.0.1",
    "signal-promise": "^1.0.3",
    "sodium-universal": "^5.0.1",
    "streamx": "^2.16.1",
    "unslab": "^1.3.0",
    "xache": "^1.1.0"
  },
  "devDependencies": {
    "bare-node-child-process": "^1.0.1",
    "brittle": "^3.0.0",
    "graceful-goodbye": "^1.3.0",
    "newline-decoder": "^1.0.2",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "test": "prettier --check . && node test/all.js",
    "test:bare": "bare test/all.js",
    "test:generate": "brittle -r test/all.js test/*.js",
    "integration": "brittle test/integration/*.js",
    "end-to-end": "brittle test/end-to-end/*.js"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "directories": {
    "lib": "lib",
    "test": "test"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/hyperdht.git"
  },
  "keywords": [],
  "bugs": {
    "url": "https://github.com/holepunchto/hyperdht/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperdht#readme"
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return uint24.decode(state) + 0x1000000 * uint32.decode(state)
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return uint32.decode(state) + 0x100000000 * uint32.decode(state)
  }
})

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "2.19.2",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    if (b.byteLength === 0) return null
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "hyperschema",
  "version": "1.20.1",
  "description": "Create registries of declarative compact-encoding schemas",
  "files": [
    "lib/*.js",
    "builder.mjs",
    "builder.cjs",
    "runtime.mjs",
    "runtime.cjs",
    "primitives.mjs",
    "primitives.cjs"
  ],
  "exports": {
    "./package": "./package.json",
    ".": {
      "import": "./builder.mjs",
      "default": "./builder.cjs"
    },
    "./runtime": {
      "import": "./runtime.mjs",
      "default": "./runtime.cjs"
    },
    "./primitives": {
      "import": "./primitives.mjs",
      "default": "./primitives.cjs"
    }
  },
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    }
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test/index.js",
    "test:bare": "prettier . --check && bare test/index.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/hyperschema.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/hyperschema/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperschema#readme",
  "dependencies": {
    "bare-fs": "^4.0.1",
    "compact-encoding": "^2.19.0",
    "generate-object-property": "^2.0.0",
    "generate-string": "^1.0.1"
  },
  "devDependencies": {
    "brittle": "^3.7.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "test-tmp": "^1.3.0"
  }
}
module.exports = {
  c: require('compact-encoding')
}
const { EventEmitter } = require('events')
const { getStreamError } = require('streamx')
const DHT = require('hyperdht')
const spq = require('shuffled-priority-queue')
const b4a = require('b4a')
const unslab = require('unslab')

const PeerInfo = require('./lib/peer-info')
const RetryTimer = require('./lib/retry-timer')
const ConnectionSet = require('./lib/connection-set')
const PeerDiscovery = require('./lib/peer-discovery')

const MAX_PEERS = 64
const MAX_PARALLEL = 3
const MAX_CLIENT_CONNECTIONS = Infinity // TODO: Change
const MAX_SERVER_CONNECTIONS = Infinity

const ERR_MISSING_TOPIC = 'Topic is required and must be a 32-byte buffer'
const ERR_DESTROYED = 'Swarm has been destroyed'
const ERR_DUPLICATE = 'Duplicate connection'
const ERR_FIREWALL = 'Peer is firewalled'

module.exports = class Hyperswarm extends EventEmitter {
  constructor(opts = {}) {
    super()
    const {
      seed,
      relayThrough,
      keyPair = DHT.keyPair(seed),
      maxPeers = MAX_PEERS,
      maxClientConnections = MAX_CLIENT_CONNECTIONS,
      maxServerConnections = MAX_SERVER_CONNECTIONS,
      maxParallel = MAX_PARALLEL,
      firewall = allowAll
    } = opts
    this.keyPair = keyPair

    this.dht =
      opts.dht ||
      new DHT({
        bootstrap: opts.bootstrap,
        nodes: opts.nodes,
        port: opts.port,
        deferRandomPunch: opts.deferRandomPunch,
        randomPunchInterval: opts.randomPunchInterval
      })
    this.server = this.dht.createServer(
      {
        firewall: this._handleFirewall.bind(this),
        relayThrough: this._maybeRelayConnection.bind(this),
        handshakeClearWait: opts.handshakeClearWait
      },
      this._handleServerConnection.bind(this)
    )

    this.destroyed = false
    this.suspended = false
    this.maxPeers = maxPeers
    this.maxClientConnections = maxClientConnections
    this.maxServerConnections = maxServerConnections
    this.maxParallel = maxParallel
    this.relayThrough = relayThrough ? toRelayFunction(relayThrough) : null

    this.connecting = 0
    this.connections = new Set()
    this.peers = new Map()
    this.explicitPeers = new Set()
    this.listening = null
    this.stats = {
      updates: 0,
      connects: {
        client: {
          opened: 0,
          closed: 0,
          attempted: 0
        },
        server: {
          // Note: there is no notion of 'attempts' for server connections
          opened: 0,
          closed: 0
        }
      },
      bannedPeers: 0
    }

    this._discovery = new Map()
    this._timer = new RetryTimer(this._requeue.bind(this), {
      backoffs: opts.backoffs,
      jitter: opts.jitter
    })
    this._queue = spq()

    this._allConnections = new ConnectionSet()
    this._pendingFlushes = []
    this._flushTick = 0

    this._drainingQueue = false
    this._clientConnections = 0
    this._serverConnections = 0
    this._firewall = firewall

    this.dht.on('network-change', this._handleNetworkChange.bind(this))
    this.dht.on('network-update', this._handleNetworkUpdate.bind(this))
    this.on('update', this._handleUpdate)
  }

  _maybeRelayConnection(force) {
    if (!this.relayThrough) return null
    return this.relayThrough(force, this)
  }

  _enqueue(peerInfo) {
    if (peerInfo.queued) return
    peerInfo.queued = true
    peerInfo._flushTick = this._flushTick
    this._queue.add(peerInfo)

    this._attemptClientConnections()
  }

  _requeue(batch) {
    if (this.suspended) return
    for (const peerInfo of batch) {
      peerInfo.waiting = false

      if (
        peerInfo._updatePriority() === false ||
        this._allConnections.has(peerInfo.publicKey) ||
        peerInfo.queued
      ) {
        continue
      }
      peerInfo.queued = true
      peerInfo._flushTick = this._flushTick
      this._queue.add(peerInfo)
    }

    this._attemptClientConnections()
  }

  _flushMaybe(peerInfo) {
    for (let i = 0; i < this._pendingFlushes.length; i++) {
      const flush = this._pendingFlushes[i]
      if (peerInfo._flushTick > flush.tick) continue
      if (--flush.missing > 0) continue
      flush.onflush(true)
      this._pendingFlushes.splice(i--, 1)
    }
  }

  _withinMaxPeers() {
    const e = this.explicitPeers.size
    const factor = e === 0 ? 1 : e < 2 ? 2 : e < 4 ? 3 : 4
    return factor * this._allConnections.size < this.maxPeers
  }

  _flushAllMaybe() {
    if (
      this.connecting > 0 ||
      (this._withinMaxPeers() && this._clientConnections < this.maxClientConnections)
    ) {
      return false
    }

    while (this._pendingFlushes.length) {
      const flush = this._pendingFlushes.pop()
      flush.onflush(true)
    }

    return true
  }

  _shouldConnectExplicit() {
    return !this.destroyed && !this.suspended && this.connecting < this.maxParallel
  }

  _shouldConnect() {
    return (
      !this.destroyed &&
      !this.suspended &&
      this.connecting < this.maxParallel &&
      this._withinMaxPeers() &&
      this._clientConnections < this.maxClientConnections
    )
  }

  _shouldRequeue(peerInfo) {
    if (this.suspended) return false
    if (peerInfo.explicit) return true
    for (const topic of peerInfo.topics) {
      if (this._discovery.has(b4a.toString(topic, 'hex')) && !this.destroyed) {
        return true
      }
    }
    return false
  }

  _connect(peerInfo, queued) {
    if (peerInfo.banned || this._allConnections.has(peerInfo.publicKey)) {
      if (queued) this._flushMaybe(peerInfo)
      return
    }

    // TODO: Support async firewalling at some point.
    if (this._handleFirewall(peerInfo.publicKey, null)) {
      if (queued) this._flushMaybe(peerInfo)
      return
    }

    const relayThrough = this._maybeRelayConnection(peerInfo.forceRelaying)
    const conn = this.dht.connect(peerInfo.publicKey, {
      relayAddresses: peerInfo.relayAddresses,
      keyPair: this.keyPair,
      relayThrough
    })
    this._allConnections.add(conn)

    this.stats.connects.client.attempted++

    this.connecting++
    this._clientConnections++
    let opened = false

    const onerror = (err) => {
      if (this.relayThrough && shouldForceRelaying(err.code)) {
        peerInfo.forceRelaying = true
        // Reset the attempts in order to fast connect to relay
        peerInfo.attempts = 0
      }
    }

    // Removed once a connection is opened
    conn.on('error', onerror)

    conn.on('open', () => {
      opened = true
      this.stats.connects.client.opened++

      this._connectDone()
      this.connections.add(conn)
      conn.removeListener('error', onerror)
      peerInfo._connected()
      peerInfo.client = true
      this.emit('connection', conn, peerInfo)
      if (queued) this._flushMaybe(peerInfo)

      this.emit('update')
    })
    conn.on('close', () => {
      if (!opened) this._connectDone()
      this.stats.connects.client.closed++

      const err = getStreamError(conn)
      if (shouldBan(err)) {
        this._banPeer(peerInfo, true, err)
      }

      this.connections.delete(conn)
      this._allConnections.delete(conn)
      this._clientConnections--
      peerInfo._disconnected()

      peerInfo.waiting = this._shouldRequeue(peerInfo) && this._timer.add(peerInfo)
      this._maybeDeletePeer(peerInfo)

      if (!opened && queued) this._flushMaybe(peerInfo)

      this._attemptClientConnections()

      this.emit('update')
    })

    this.emit('update')
  }

  _connectDone() {
    this.connecting--

    if (this.connecting < this.maxParallel) this._attemptClientConnections()
    if (this.connecting === 0) this._flushAllMaybe()
  }

  // Called when the PeerQueue indicates a connection should be attempted.
  _attemptClientConnections() {
    // Guard against re-entries - unsure if it still needed but doesn't hurt
    if (this._drainingQueue || this.suspended) return
    this._drainingQueue = true

    for (const peerInfo of this.explicitPeers) {
      if (!this._shouldConnectExplicit()) break
      if (
        peerInfo.attempts >= 5 ||
        Date.now() - peerInfo.disconnectedTime < peerInfo.attempts * 1000
      ) {
        continue
      }
      this._connect(peerInfo, false)
    }

    while (this._queue.length && this._shouldConnect()) {
      const peerInfo = this._queue.shift()
      peerInfo.queued = false
      this._connect(peerInfo, true)
    }
    this._drainingQueue = false
    if (this.connecting === 0) this._flushAllMaybe()
  }

  _handleFirewall(remotePublicKey, payload) {
    if (b4a.equals(remotePublicKey, this.keyPair.publicKey)) return true

    let peerInfo = this.peers.get(b4a.toString(remotePublicKey, 'hex'))
    if (peerInfo && peerInfo.banned) return true

    const firewalled = this._firewall(remotePublicKey, payload)
    if (firewalled) {
      if (!peerInfo) peerInfo = this._upsertPeer(remotePublicKey)
      this._banPeer(peerInfo, true, new Error(ERR_FIREWALL))
    }

    return firewalled
  }

  _handleServerConnectionSwap(existing, conn) {
    let closed = false

    existing.on('close', () => {
      if (closed) return

      conn.removeListener('error', noop)
      conn.removeListener('close', onclose)

      this._handleServerConnection(conn)
    })

    conn.on('error', noop)
    conn.on('close', onclose)

    function onclose() {
      closed = true
    }
  }

  // Called when the DHT receives a new server connection.
  _handleServerConnection(conn) {
    if (this.destroyed || this.suspended) {
      // TODO: Investigate why a final server connection can be received after close
      conn.on('error', noop)
      return conn.destroy(ERR_DESTROYED)
    }

    const existing = this._allConnections.get(conn.remotePublicKey)

    if (existing) {
      // If both connections are from the same peer,
      // - pick the new one if the existing stream is already established (has sent and received bytes),
      //   because the other client must have lost that connection and be reconnecting
      // - otherwise, pick the one thats expected to initiate in a tie break
      const existingIsOutdated = existing.rawBytesRead > 0 && existing.rawBytesWritten > 0
      const expectedInitiator = b4a.compare(conn.publicKey, conn.remotePublicKey) > 0
      const keepNew = existingIsOutdated || expectedInitiator === conn.isInitiator

      if (keepNew === false) {
        existing.sendKeepAlive()
        conn.on('error', noop)
        conn.destroy(new Error(ERR_DUPLICATE))
        return
      }

      existing.on('error', noop)
      existing.destroy(new Error(ERR_DUPLICATE))
      this._handleServerConnectionSwap(existing, conn)
      return
    }

    // When reaching here, the connection will always be 'opened' next tick
    this.stats.connects.server.opened++

    const peerInfo = this._upsertPeer(conn.remotePublicKey, null)

    this.connections.add(conn)
    this._allConnections.add(conn)
    this._serverConnections++

    conn.on('close', () => {
      const err = getStreamError(conn)
      if (shouldBan(err)) {
        this._banPeer(peerInfo, true, err)
      }

      this.connections.delete(conn)
      this._allConnections.delete(conn)
      this._serverConnections--
      this.stats.connects.server.closed++

      this._maybeDeletePeer(peerInfo)

      this._attemptClientConnections()

      this.emit('update')
    })
    peerInfo.client = false
    this.emit('connection', conn, peerInfo)

    this.emit('update')
  }

  _upsertPeer(publicKey, relayAddresses) {
    if (b4a.equals(publicKey, this.keyPair.publicKey)) return null
    const keyString = b4a.toString(publicKey, 'hex')
    let peerInfo = this.peers.get(keyString)

    if (peerInfo) {
      peerInfo.relayAddresses = relayAddresses // new is always better
      return peerInfo
    }

    peerInfo = new PeerInfo({
      publicKey,
      relayAddresses
    })

    this.peers.set(keyString, peerInfo)
    return peerInfo
  }

  _handleUpdate() {
    this.stats.updates++
  }

  _maybeDeletePeer(peerInfo) {
    if (!peerInfo.shouldGC()) return

    const hasActiveConn = this._allConnections.has(peerInfo.publicKey)
    if (hasActiveConn) return

    const keyString = b4a.toString(peerInfo.publicKey, 'hex')
    this.peers.delete(keyString)
  }

  /*
   * Called when a peer is actively discovered during a lookup.
   *
   * Three conditions:
   *  1. Not a known peer -- insert into queue
   *  2. A known peer with normal priority -- do nothing
   *  3. A known peer with low priority -- bump priority, because it's been rediscovered
   */
  _handlePeer(peer, topic) {
    const peerInfo = this._upsertPeer(peer.publicKey, peer.relayAddresses)
    if (peerInfo) peerInfo._topic(topic)
    if (!peerInfo || this._allConnections.has(peer.publicKey)) return
    if (!peerInfo.prioritized || peerInfo.server) peerInfo._reset()
    if (peerInfo._updatePriority()) {
      this._enqueue(peerInfo)
    }
  }

  async _handleNetworkUpdate() {
    if (!this.online) return
    this._handleNetworkChange()
  }

  async _handleNetworkChange() {
    if (this.suspended) return

    // prioritize figuring out if existing connections are dead
    for (const conn of this._allConnections) {
      conn.sendKeepAlive()
    }

    const refreshes = []

    for (const discovery of this._discovery.values()) {
      refreshes.push(discovery.refresh())
    }

    await Promise.allSettled(refreshes)
  }

  _banPeer(peerInfo, banned, err) {
    peerInfo.ban(banned)
    this.stats.bannedPeers++
    this.emit('ban', peerInfo, err)
  }

  status(key) {
    return this._discovery.get(b4a.toString(key, 'hex')) || null
  }

  listen() {
    if (!this.listening) {
      if (this.destroyed) throw new Error('Swarm destroyed')
      this.listening = this.server.listen(this.keyPair)
    }
    return this.listening
  }

  // Object that exposes a cancellation method (destroy)
  // TODO: When you rejoin, it should reannounce + bump lookup priority
  join(topic, opts = {}) {
    if (this.destroyed) throw new Error('Swarm destroyed')
    if (!topic) throw new Error(ERR_MISSING_TOPIC)
    topic = unslab(topic)

    const topicString = b4a.toString(topic, 'hex')

    let discovery = this._discovery.get(topicString)

    if (discovery && !discovery.destroyed) {
      return discovery.session(opts)
    }

    discovery = new PeerDiscovery(this, topic, {
      limit: opts.limit,
      wait: discovery ? discovery.destroy() : null,
      suspended: this.suspended,
      onpeer: (peer) => this._handlePeer(peer, topic)
    })
    this._discovery.set(topicString, discovery)
    return discovery.session(opts)
  }

  // Returns a promise
  async leave(topic) {
    if (!topic) throw new Error(ERR_MISSING_TOPIC)
    const topicString = b4a.toString(topic, 'hex')
    if (!this._discovery.has(topicString)) return Promise.resolve()

    const discovery = this._discovery.get(topicString)

    try {
      await discovery.destroy()
    } catch {
      // ignore, prop network
    }

    if (this._discovery.get(topicString) === discovery) {
      this._discovery.delete(topicString)
    }
  }

  joinPeer(publicKey) {
    const peerInfo = this._upsertPeer(publicKey, null)
    if (!peerInfo) return
    if (!this.explicitPeers.has(peerInfo)) {
      peerInfo.explicit = true
      this.explicitPeers.add(peerInfo)
    }
    if (this._allConnections.has(publicKey)) return
    if (peerInfo._updatePriority()) {
      this._enqueue(peerInfo)
    }
  }

  leavePeer(publicKey) {
    const keyString = b4a.toString(publicKey, 'hex')
    if (!this.peers.has(keyString)) return

    const peerInfo = this.peers.get(keyString)
    peerInfo.explicit = false
    this.explicitPeers.delete(peerInfo)
    this._maybeDeletePeer(peerInfo)
  }

  // Returns a promise
  async flush() {
    const allFlushed = [...this._discovery.values()].map((v) => v.flushed())
    await Promise.all(allFlushed)
    if (this._flushAllMaybe()) return true
    const pendingSize = this._allConnections.size - this.connections.size
    if (!this._queue.length && !pendingSize) return true
    return new Promise((resolve) => {
      this._pendingFlushes.push({
        onflush: resolve,
        missing: this._queue.length + pendingSize,
        tick: this._flushTick++
      })
    })
  }

  async clear() {
    const cleared = Promise.allSettled([...this._discovery.values()].map((d) => d.destroy()))
    this._discovery.clear()
    return cleared
  }

  async destroy({ force } = {}) {
    if (this.destroyed && !force) return
    this.destroyed = true

    this._timer.destroy()

    if (!force) await this.clear()

    await this.server.close()

    while (this._pendingFlushes.length) {
      const flush = this._pendingFlushes.pop()
      flush.onflush(false)
    }

    await this.dht.destroy({ force })
  }

  async suspend({ log = noop } = {}) {
    if (this.suspended) return

    const promises = []

    promises.push(this.server.suspend({ log }))

    for (const discovery of this._discovery.values()) {
      promises.push(discovery.suspend({ log }))
    }

    const pending = []
    for (const connection of this._allConnections) {
      connection.destroy()
      pending.push(new Promise((resolve) => connection.on('close', resolve)))
    }

    this.suspended = true

    log('Suspending server and discovery... (' + promises.length + ')')
    await Promise.allSettled(promises)
    log('Done, suspending the dht...')
    await this.dht.suspend({ log })
    log('Done, swarm fully suspended')

    await Promise.all(pending)

    // reset queue
    this._timer.destroy()
    this._timer = new RetryTimer(this._requeue.bind(this), {
      backoffs: this._timer.backoffs,
      jitter: this._timer.jitter
    })
    this._queue = spq()
  }

  async resume({ log = noop } = {}) {
    if (!this.suspended) return

    log('Resuming the dht')
    await this.dht.resume()
    log('Done, resuming the server')
    await this.server.resume()
    log('Done, all discovery')

    for (const discovery of this._discovery.values()) {
      discovery.resume()
    }

    this.suspended = false
    this._attemptClientConnections()
  }

  topics() {
    return this._discovery.values()
  }
}

function noop() {}

function allowAll() {
  return false
}

function shouldForceRelaying(code) {
  return (
    code === 'HOLEPUNCH_ABORTED' ||
    code === 'HOLEPUNCH_DOUBLE_RANDOMIZED_NATS' ||
    code === 'REMOTE_NOT_HOLEPUNCHABLE'
  )
}

function shouldBan() {
  // return !!err && err.name === 'HypercoreError' && err.code === 'INVALID_OPERATION'
  return false
}

function toRelayFunction(relayThrough) {
  return typeof relayThrough === 'function'
    ? relayThrough
    : (force, swarm) => (force || swarm.dht.randomized ? relayThrough : null)
}
module.exports = class BulkTimer {
  constructor(time, fn) {
    this._time = time
    this._fn = fn
    this._interval = null
    this._next = []
    this._pending = []
    this._destroyed = false
  }

  destroy() {
    if (this._destroyed) return
    this._destroyed = true
    clearInterval(this._interval)
    this._interval = null
  }

  _ontick() {
    if (!this._next.length && !this._pending.length) return
    if (this._next.length) this._fn(this._next)
    this._next = this._pending
    this._pending = []
  }

  add(info) {
    if (this._destroyed) return
    if (!this._interval) {
      this._interval = setInterval(this._ontick.bind(this), Math.floor(this._time * 0.66))
    }

    this._pending.push(info)
  }
}
const b4a = require('b4a')

module.exports = class ConnectionSet {
  constructor() {
    this._byPublicKey = new Map()
  }

  [Symbol.iterator]() {
    return this._byPublicKey.values()
  }

  get size() {
    return this._byPublicKey.size
  }

  has(publicKey) {
    return this._byPublicKey.has(toHex(publicKey))
  }

  get(publicKey) {
    return this._byPublicKey.get(toHex(publicKey))
  }

  add(connection) {
    this._byPublicKey.set(b4a.toString(connection.remotePublicKey, 'hex'), connection)
  }

  delete(connection) {
    const keyString = b4a.toString(connection.remotePublicKey, 'hex')
    const existing = this._byPublicKey.get(keyString)
    if (existing !== connection) return
    this._byPublicKey.delete(keyString)
  }
}

function toHex(b) {
  return typeof b === 'string' ? b : b4a.toString(b, 'hex')
}
const safetyCatch = require('safety-catch')
const b4a = require('b4a')

const REFRESH_INTERVAL = 1000 * 60 * 10 // 10 min
const RANDOM_JITTER = 1000 * 60 * 2 // 2 min
const DELAY_GRACE_PERIOD = 1000 * 30 // 30s

const MAX_DISCOVERY_CACHE = 64

module.exports = class PeerDiscovery {
  constructor(
    swarm,
    topic,
    { limit = Infinity, wait = null, suspended = false, onpeer = noop, onerror = safetyCatch }
  ) {
    this.limit = limit
    this.swarm = swarm
    this.topic = topic
    this.isClient = false
    this.isServer = false
    this.destroyed = false
    this.destroying = null
    this.suspended = suspended

    this._sessions = []
    this._clientSessions = 0
    this._serverSessions = 0

    this._onpeer = onpeer
    this._onerror = onerror

    this._discovered = new Set()
    this._activeQuery = null
    this._timer = null
    this._currentRefresh = null
    this._closestNodes = null
    this._firstAnnounce = true
    this._needsUnannounce = false
    this._refreshes = 0
    this._wait = wait
  }

  session({ server = true, client = true, limit = Infinity, onerror = safetyCatch }) {
    if (this.destroyed) throw new Error('PeerDiscovery is destroyed')
    const session = new PeerDiscoverySession(this)
    session.refresh({ server, client, limit }).catch(onerror)
    this._sessions.push(session)
    return session
  }

  _refreshLater(eager) {
    const jitter = Math.round(Math.random() * RANDOM_JITTER)
    const delay = !eager ? REFRESH_INTERVAL + jitter : jitter

    if (this._timer) clearTimeout(this._timer)

    const startTime = Date.now()
    this._timer = setTimeout(() => {
      // If your laptop went to sleep, and is coming back online...
      const overdue = Date.now() - startTime > delay + DELAY_GRACE_PERIOD
      if (overdue) this._refreshLater(true)
      else this.refresh().catch(this._onerror)
    }, delay)
  }

  _isActive() {
    return !this.destroyed && !this.suspended
  }

  // TODO: Allow announce to be an argument to this
  // TODO: Maybe announce should be a setter?
  async _refresh() {
    if (this.suspended) return
    const clock = ++this._refreshes

    if (this._wait) {
      await this._wait
      this._wait = null
      if (clock !== this._refreshes || !this._isActive()) return
    }

    const clear = this.isServer && this._firstAnnounce
    if (clear) this._firstAnnounce = false

    const opts = {
      clear,
      closestNodes: this._closestNodes
    }

    if (this.isServer) {
      await this.swarm.listen()
      // if a parallel refresh is happening, yield to the new one
      if (clock !== this._refreshes || !this._isActive()) return
      this._needsUnannounce = true
    }

    let limit = this.limit

    if (limit < Infinity && limit > 0) {
      for (const id of this._discovered) {
        if (!this.swarm.connections.has(id)) continue
        if (--limit === 0) break
      }
    }

    this._discovered.clear()

    const announcing = this.isServer
    const query = (this._activeQuery = announcing
      ? this.swarm.dht.announce(
          this.topic,
          this.swarm.keyPair,
          this.swarm.server.relayAddresses,
          opts
        )
      : this._needsUnannounce
        ? this.swarm.dht.lookupAndUnannounce(this.topic, this.swarm.keyPair, opts)
        : this.swarm.dht.lookup(this.topic, opts))

    try {
      for await (const data of this._activeQuery) {
        if (!this.isClient || !this._isActive()) continue
        for (const peer of data.peers) {
          if (limit < Infinity) {
            const id = b4a.toString(peer.publicKey, 'hex')

            if (this._discovered.size < MAX_DISCOVERY_CACHE) {
              this._discovered.add(id)
            }

            if (limit === 0) continue

            // there is a chance it has updated a connection during discovery and we go over
            // the limit - thats acceptable to avoid a complexity spiral here.
            if (!this.swarm.connections.has(id)) limit--
          }

          this._onpeer(peer, data)
        }
      }
    } catch (err) {
      if (this._isActive()) throw err
    } finally {
      if (this._activeQuery === query) {
        this._activeQuery = null
        if (!this.destroyed && !this.suspended) this._refreshLater(false)
      }
    }

    // This is set at the very end, when the query completes successfully.
    this._closestNodes = query.closestNodes

    if (clock !== this._refreshes) return

    // In this is the latest query, unannounce has been fulfilled as well
    if (!announcing) this._needsUnannounce = false
  }

  async refresh() {
    if (this.destroyed) throw new Error('PeerDiscovery is destroyed')

    const server = this._serverSessions > 0
    const client = this._clientSessions > 0

    if (this.suspended) return

    if (server === this.isServer && client === this.isClient) {
      if (this._currentRefresh) return this._currentRefresh
      this._currentRefresh = this._refresh()
    } else {
      if (this._activeQuery) this._activeQuery.destroy()
      this.isServer = server
      this.isClient = client
      this._currentRefresh = this._refresh()
    }

    const refresh = this._currentRefresh
    try {
      await refresh
    } catch {
      return false
    } finally {
      if (refresh === this._currentRefresh) {
        this._currentRefresh = null
      }
    }

    return true
  }

  async flushed() {
    if (this.swarm.listening) await this.swarm.listening

    try {
      await this._currentRefresh
      return true
    } catch {
      return false
    }
  }

  async _destroyMaybe() {
    if (this.destroyed) return

    try {
      if (this._sessions.length === 0) await this.swarm.leave(this.topic)
      else if (this._serverSessions === 0 && this._needsUnannounce) await this.refresh()
    } catch (err) {
      // ignore network failures here, as we are tearing down
      safetyCatch(err)
    }
  }

  destroy() {
    if (this.destroying) return this.destroying
    this.destroying = this._destroy()
    return this.destroying
  }

  async _abort(log) {
    const id = log === noop ? '' : b4a.toString(this.topic, 'hex')

    log('Aborting discovery', id)
    if (this._wait) await this._wait
    log('Aborting discovery (post wait)', id)

    if (this._activeQuery) {
      this._activeQuery.destroy()
      this._activeQuery = null
    }
    if (this._timer) {
      clearTimeout(this._timer)
      this._timer = null
    }

    let nodes = this._closestNodes

    if (this._currentRefresh) {
      try {
        await this._currentRefresh
      } catch {
        // If the destroy causes the refresh to fail, suppress it.
      }
    }

    log('Aborting discovery (post refresh)', id)
    if (this._isActive()) return

    if (!nodes) nodes = this._closestNodes
    else if (this._closestNodes !== nodes) {
      const len = nodes.length
      for (const newer of this._closestNodes) {
        if (newer.id && !hasNode(nodes, len, newer)) nodes.push(newer)
      }
    }

    if (this._needsUnannounce) {
      log('Unannouncing discovery', id)
      if (nodes && nodes.length) {
        await this.swarm.dht.unannounce(this.topic, this.swarm.keyPair, {
          closestNodes: nodes,
          onlyClosestNodes: true,
          force: true
        })
      }
      this._needsUnannounce = false
      log('Unannouncing discovery (done)', id)
    }
  }

  _destroy() {
    if (this.destroyed) return
    this.destroyed = true
    return this._abort(noop)
  }

  async suspend({ log = noop } = {}) {
    if (this.suspended) return
    this.suspended = true
    try {
      await this._abort(log)
    } catch {
      // ignore
    }
  }

  resume() {
    if (!this.suspended) return
    this.suspended = false
    this.refresh().catch(noop)
  }
}

class PeerDiscoverySession {
  constructor(discovery) {
    this.discovery = discovery
    this.isClient = false
    this.isServer = false
    this.destroyed = false
  }

  get swarm() {
    return this.discovery.swarm
  }

  get topic() {
    return this.discovery.topic
  }

  async refresh({ client = this.isClient, server = this.isServer, limit = Infinity } = {}) {
    if (this.destroyed) throw new Error('PeerDiscovery is destroyed')
    if (!client && !server) throw new Error('Cannot refresh with neither client nor server option')

    if (client !== this.isClient) {
      this.isClient = client
      this.discovery._clientSessions += client ? 1 : -1
    }

    if (server !== this.isServer) {
      this.isServer = server
      this.discovery._serverSessions += server ? 1 : -1
    }

    this.discovery.limit = limit

    return this.discovery.refresh()
  }

  async flushed() {
    return this.discovery.flushed()
  }

  async destroy() {
    if (this.destroyed) return
    this.destroyed = true

    if (this.isClient) this.discovery._clientSessions--
    if (this.isServer) this.discovery._serverSessions--

    const index = this.discovery._sessions.indexOf(this)
    const head = this.discovery._sessions.pop()

    if (head !== this) this.discovery._sessions[index] = head

    return this.discovery._destroyMaybe()
  }
}

function hasNode(nodes, len, node) {
  for (let i = 0; i < len; i++) {
    const existing = nodes[i]
    if (existing.id && b4a.equals(existing.id, node.id)) return true
  }

  return false
}

function noop() {}
const { EventEmitter } = require('events')
const b4a = require('b4a')
const unslab = require('unslab')

const MIN_CONNECTION_TIME = 15000

const VERY_LOW_PRIORITY = 0
const LOW_PRIORITY = 1
const NORMAL_PRIORITY = 2
const HIGH_PRIORITY = 3
const VERY_HIGH_PRIORITY = 4

module.exports = class PeerInfo extends EventEmitter {
  constructor({ publicKey, relayAddresses }) {
    super()

    this.publicKey = unslab(publicKey)
    this.relayAddresses = relayAddresses

    this.reconnecting = true
    this.proven = false
    this.connectedTime = -1
    this.disconnectedTime = 0
    this.banned = false
    this.tried = false
    this.explicit = false
    this.waiting = false
    this.forceRelaying = false

    // Set by the Swarm
    this.queued = false
    this.client = false
    this.topics = [] // TODO: remove on next major (check with mafintosh for context)

    this.attempts = 0
    this.priority = NORMAL_PRIORITY

    // Used by shuffled-priority-queue
    this._index = 0

    // Used for flush management
    this._flushTick = 0

    // Used for topic multiplexing
    this._seenTopics = new Set()
  }

  get server() {
    return !this.client
  }

  get prioritized() {
    return this.priority >= NORMAL_PRIORITY
  }

  _getPriority() {
    const peerIsStale = this.tried && !this.proven
    if (peerIsStale || this.attempts > 3) return VERY_LOW_PRIORITY
    if (this.attempts === 3) return LOW_PRIORITY
    if (this.attempts === 2) return HIGH_PRIORITY
    if (this.attempts === 1) return VERY_HIGH_PRIORITY
    return NORMAL_PRIORITY
  }

  _connected() {
    this.proven = true
    this.connectedTime = Date.now()
  }

  _disconnected() {
    this.disconnectedTime = Date.now()
    if (this.connectedTime > -1) {
      if (this.disconnectedTime - this.connectedTime >= MIN_CONNECTION_TIME) this.attempts = 0 // fast retry
      this.connectedTime = -1
    }
    this.attempts++
  }

  _deprioritize() {
    this.attempts = 3
  }

  _reset() {
    this.client = false
    this.proven = false
    this.tried = false
    this.attempts = 0
  }

  _updatePriority() {
    if (this.explicit && this.attempts > 3) this._deprioritize()
    if (this.banned || this.queued || this.attempts > 3) return false
    this.priority = this._getPriority()
    return true
  }

  _topic(topic) {
    const topicString = b4a.toString(topic, 'hex')
    if (this._seenTopics.has(topicString)) return
    this._seenTopics.add(topicString)
    this.topics.push(topic)
    this.emit('topic', topic)
  }

  reconnect(val) {
    this.reconnecting = !!val
  }

  ban(val) {
    this.banned = !!val
  }

  shouldGC() {
    return !(this.banned || this.queued || this.explicit || this.waiting)
  }
}
const BulkTimer = require('./bulk-timer')

const BACKOFF_JITTER = 500
const BACKOFF_S = 1000 + Math.round(BACKOFF_JITTER * Math.random())
const BACKOFF_M = 5000 + Math.round(2 * BACKOFF_JITTER * Math.random())
const BACKOFF_L = 15000 + Math.round(4 * BACKOFF_JITTER * Math.random())
const BACKOFF_X = 1000 * 60 * 10 + Math.round(240 * BACKOFF_JITTER * Math.random())

module.exports = class RetryTimer {
  constructor(
    push,
    { backoffs = [BACKOFF_S, BACKOFF_M, BACKOFF_L, BACKOFF_X], jitter = BACKOFF_JITTER } = {}
  ) {
    this.jitter = jitter
    this.backoffs = backoffs

    this._sTimer = new BulkTimer(backoffs[0] + Math.round(jitter * Math.random()), push)
    this._mTimer = new BulkTimer(backoffs[1] + Math.round(jitter * Math.random()), push)
    this._lTimer = new BulkTimer(backoffs[2] + Math.round(jitter * Math.random()), push)
    this._xTimer = new BulkTimer(backoffs[3] + Math.round(jitter * Math.random()), push)
  }

  _selectRetryTimer(peerInfo) {
    if (peerInfo.banned || !peerInfo.reconnecting) return null

    if (peerInfo.attempts > 3) {
      return peerInfo.explicit ? this._xTimer : null
    }

    if (peerInfo.attempts === 0) return this._sTimer
    if (peerInfo.proven) {
      switch (peerInfo.attempts) {
        case 1:
          return this._sTimer
        case 2:
          return this._mTimer
        case 3:
          return this._lTimer
      }
    } else {
      switch (peerInfo.attempts) {
        case 1:
          return this._mTimer
        case 2:
          return this._lTimer
        case 3:
          return this._lTimer
      }
    }

    return null
  }

  add(peerInfo) {
    const timer = this._selectRetryTimer(peerInfo)
    if (!timer) return false

    timer.add(peerInfo)
    return true
  }

  destroy() {
    this._sTimer.destroy()
    this._mTimer.destroy()
    this._lTimer.destroy()
    this._xTimer.destroy()
  }
}
{
  "name": "hyperswarm",
  "version": "4.17.0",
  "description": "A distributed networking stack for connecting peers",
  "files": [
    "index.js",
    "lib/**.js"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    },
    "process": {
      "bare": "bare-process",
      "default": "process"
    }
  },
  "dependencies": {
    "b4a": "^1.3.1",
    "bare-events": "^2.2.0",
    "hyperdht": "^6.21.0",
    "safety-catch": "^1.0.2",
    "shuffled-priority-queue": "^2.1.0",
    "streamx": "^2.22.1",
    "unslab": "^1.3.0"
  },
  "devDependencies": {
    "bare-process": "^4.2.2",
    "brittle": "^3.0.2",
    "hypercore-crypto": "^3.4.0",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "which-runtime": "^1.3.2"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:generate": "brittle -r test/all.js test/*.js",
    "test:node": "brittle-node --coverage test/*.js",
    "test:bare": "bare test/all.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/hyperswarm.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "contributors": [
    "David Mark Clements (@davidmarkclem)",
    "Andrew Osheroff (@andrewosh)"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/hyperswarm/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperswarm"
}
const { EventEmitter } = require('events')

module.exports = class RoutingTable extends EventEmitter {
  constructor (id, opts) {
    if (!opts) opts = {}

    super()

    this.id = id
    this.k = opts.k || 20
    this.size = 0
    this.rows = new Array(id.length * 8)
  }

  add (node) {
    const i = this._diff(node.id)

    let row = this.rows[i]

    if (!row) {
      row = this.rows[i] = new Row(this, i)
      this.emit('row', row)
    }

    const len = row.nodes.length
    if (!row.add(node, this.k)) return false

    this.size += row.nodes.length - len
    return true
  }

  remove (id) {
    const i = this._diff(id)
    const row = this.rows[i]
    if (!row) return false
    if (!row.remove(id)) return false
    this.size--
    return true
  }

  get (id) {
    const i = this._diff(id)
    const row = this.rows[i]
    if (!row) return null
    return row.get(id)
  }

  has (id) {
    return this.get(id) !== null
  }

  random () {
    let n = (Math.random() * this.size) | 0

    for (let i = 0; i < this.rows.length; i++) {
      const r = this.rows[i]
      if (!r) continue
      if (n < r.nodes.length) return r.nodes[n]
      n -= r.nodes.length
    }

    return null
  }

  closest (id, k) {
    if (!k) k = this.k

    const result = []
    const d = this._diff(id)

    // push close nodes
    for (let i = d; i >= 0 && result.length < k; i--) this._pushNodes(i, k, result)

    // if we don't have enough close nodes, populate from other rows, re the paper
    for (let i = d + 1; i < this.rows.length && result.length < k; i++) this._pushNodes(i, k, result)

    return result
  }

  _pushNodes (i, k, result) {
    const row = this.rows[i]
    if (!row) return

    const missing = Math.min(k - result.length, row.nodes.length)
    for (let j = 0; j < missing; j++) result.push(row.nodes[j])
  }

  toArray () {
    return this.closest(this.id, Infinity)
  }

  _diff (id) {
    for (let i = 0; i < id.length; i++) {
      const a = id[i]
      const b = this.id[i]

      if (a !== b) return i * 8 + Math.clz32(a ^ b) - 24
    }

    return this.rows.length - 1
  }
}

class Row extends EventEmitter {
  constructor (table, index) {
    super()

    this.data = null // can be used be upstream for whatevs
    this.byteOffset = index >> 3
    this.index = index
    this.table = table
    this.nodes = []
  }

  add (node) {
    const id = node.id

    let l = 0
    let r = this.nodes.length - 1

    while (l <= r) {
      const m = (l + r) >> 1
      const c = this.compare(id, this.nodes[m].id)

      if (c === 0) {
        this.nodes[m] = node
        return true
      }

      if (c < 0) r = m - 1
      else l = m + 1
    }

    if (this.nodes.length >= this.table.k) {
      this.emit('full', node)
      return false
    }

    this.insert(l, node)
    return true
  }

  remove (id) {
    let l = 0
    let r = this.nodes.length - 1

    while (l <= r) {
      const m = (l + r) >> 1
      const c = this.compare(id, this.nodes[m].id)

      if (c === 0) {
        this.splice(m)
        return true
      }

      if (c < 0) r = m - 1
      else l = m + 1
    }

    return false
  }

  get (id) {
    let l = 0
    let r = this.nodes.length - 1

    while (l <= r) {
      const m = (l + r) >> 1
      const node = this.nodes[m]
      const c = this.compare(id, node.id)

      if (c === 0) return node
      if (c < 0) r = m - 1
      else l = m + 1
    }

    return null
  }

  insert (i, node) {
    this.nodes.push(node) // push node or null or whatevs, just trying to not be polymorphic
    for (let j = this.nodes.length - 1; j > i; j--) this.nodes[j] = this.nodes[j - 1]
    this.nodes[i] = node
    this.emit('add', node)
  }

  splice (i) {
    for (; i < this.nodes.length - 1; i++) this.nodes[i] = this.nodes[i + 1]
    this.emit('remove', this.nodes.pop())
  }

  // very likely they diverge after a couple of bytes so a simple impl, like this is prop fastest vs Buffer.compare
  compare (a, b) {
    for (let i = this.byteOffset; i < a.length; i++) {
      const ai = a[i]
      const bi = b[i]
      if (ai === bi) continue
      return ai < bi ? -1 : 1
    }
    return 0
  }
}
{
  "name": "kademlia-routing-table",
  "version": "1.0.6",
  "description": "XOR based routing table used for P2P networks such as a Kademlia DHT.",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "dependencies": {
    "bare-events": "^2.2.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "standard": "^17.1.0"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "keywords": [
    "kademlia",
    "p2p",
    "k-bucket",
    "k-buckets",
    "xor",
    "routing",
    "distributed",
    "systems"
  ],
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/kademlia-routing-table.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/kademlia-routing-table/issues"
  },
  "homepage": "https://github.com/mafintosh/kademlia-routing-table"
}
module.exports = assert

class AssertionError extends Error {}
AssertionError.prototype.name = 'AssertionError'

/**
 * Minimal assert function
 * @param  {any} t Value to check if falsy
 * @param  {string=} m Optional assertion error message
 * @throws {AssertionError}
 */
function assert (t, m) {
  if (!t) {
    var err = new AssertionError(m)
    if (Error.captureStackTrace) Error.captureStackTrace(err, assert)
    throw err
  }
}
{
  "name": "nanoassert",
  "version": "2.0.0",
  "description": "Nanoscale assertion module",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "tape": "^4.9.1"
  },
  "scripts": {
    "test": "tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/emilbayes/nanoassert.git"
  },
  "keywords": [
    "assert",
    "unassert",
    "power-assert",
    "tiny",
    "nano",
    "pico"
  ],
  "author": "Emil Bay <github@tixz.dk>",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/emilbayes/nanoassert/issues"
  },
  "homepage": "https://github.com/emilbayes/nanoassert#readme"
}
module.exports = class NatSampler {
  constructor () {
    this.host = null
    this.port = 0
    this.size = 0

    this._a = null
    this._b = null
    this._threshold = 0
    this._top = 0
    this._samples = []
  }

  add (host, port) {
    const a = this._bump(host, port, 2)
    const b = this._bump(host, 0, 1)

    if (this._samples.length < 32) {
      this.size++
      this._threshold = this.size - (this.size < 4 ? 0 : this.size < 8 ? 1 : this.size < 12 ? 2 : 3)
      this._samples.push(a, b)
      this._top += 2
    } else {
      if (this._top === 32) this._top = 0

      const oa = this._samples[this._top]
      this._samples[this._top++] = a
      oa.hits--

      const ob = this._samples[this._top]
      this._samples[this._top++] = b
      ob.hits--
    }

    if (this._a === null || this._a.hits < a.hits) this._a = a
    if (this._b === null || this._b.hits < b.hits) this._b = b

    if (this._a.hits >= this._threshold) {
      this.host = this._a.host
      this.port = this._a.port
    } else if (this._b.hits >= this._threshold) {
      this.host = this._b.host
      this.port = 0
    } else {
      this.host = null
      this.port = 0
    }

    return a.hits
  }

  _bump (host, port, inc) {
    for (let i = 0; i < 4; i++) {
      const j = (this._top - inc - (2 * i)) & 31
      if (j >= this._samples.length) return { host, port, hits: 1 }
      const s = this._samples[j]
      if (s.port === port && s.host === host) {
        s.hits++
        return s
      }
    }
    return { host, port, hits: 1 }
  }
}
{
  "name": "nat-sampler",
  "version": "1.0.1",
  "description": "Sample addresses to figure out if a host + port is consistent",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^16.0.3",
    "tape": "^5.2.2"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/nat-sampler.git"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/nat-sampler/issues"
  },
  "homepage": "https://github.com/mafintosh/nat-sampler"
}
/* eslint-disable camelcase */
const sodium = require('sodium-universal')
const assert = require('nanoassert')
const b4a = require('b4a')

const DHLEN = sodium.crypto_scalarmult_ed25519_BYTES
const PKLEN = sodium.crypto_scalarmult_ed25519_BYTES
const SCALARLEN = sodium.crypto_scalarmult_ed25519_BYTES
const SKLEN = sodium.crypto_sign_SECRETKEYBYTES
const ALG = 'Ed25519'

module.exports = {
  DHLEN,
  PKLEN,
  SCALARLEN,
  SKLEN,
  ALG,
  name: ALG,
  generateKeyPair,
  dh
}

function generateKeyPair (privKey) {
  if (privKey) return generateSeedKeyPair(privKey.subarray(0, 32))

  const keyPair = {}
  keyPair.secretKey = b4a.alloc(SKLEN)
  keyPair.publicKey = b4a.alloc(PKLEN)

  sodium.crypto_sign_keypair(keyPair.publicKey, keyPair.secretKey)
  return keyPair
}

function generateSeedKeyPair (seed) {
  const keyPair = {}
  keyPair.secretKey = b4a.alloc(SKLEN)
  keyPair.publicKey = b4a.alloc(PKLEN)

  sodium.crypto_sign_seed_keypair(keyPair.publicKey, keyPair.secretKey, seed)
  return keyPair
}

function dh (publicKey, { scalar, secretKey }) {
  // tweaked keys expose scalar directly
  if (!scalar) {
    assert(secretKey.byteLength === SKLEN)

    // libsodium stores seed not actual scalar
    const sk = b4a.alloc(64)
    sodium.crypto_hash_sha512(sk, secretKey.subarray(0, 32))
    sk[0] &= 248
    sk[31] &= 127
    sk[31] |= 64

    scalar = sk.subarray(0, 32)
  }

  assert(scalar.byteLength === SCALARLEN)
  assert(publicKey.byteLength === PKLEN)

  const output = b4a.alloc(DHLEN)

  // we clamp if necessary above
  sodium.crypto_scalarmult_ed25519_noclamp(
    output,
    scalar,
    publicKey
  )

  return output
}
{
  "name": "noise-curve-ed",
  "version": "2.1.0",
  "description": "Ed25519 elliptic curve operations for [`noise-handshake`](https://github.com/chm-diederichs/noise-handshake)",
  "main": "index.js",
  "scripts": {
    "test": "npx standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/chm-diederichs/noise-curve-ed.git"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/chm-diederichs/noise-curve-ed/issues"
  },
  "homepage": "https://github.com/chm-diederichs/noise-curve-ed#readme",
  "dependencies": {
    "b4a": "^1.1.0",
    "nanoassert": "^2.0.0",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "noise-handshake": "^3.0.0",
    "standard": "^16.0.3",
    "tape": "^5.2.2"
  }
}
const sodium = require('sodium-universal')
const b4a = require('b4a')

module.exports = class CipherState {
  constructor (key) {
    this.key = key || null
    this.nonce = 0
    this.CIPHER_ALG = 'ChaChaPoly'
  }

  initialiseKey (key) {
    this.key = key
    this.nonce = 0
  }

  setNonce (nonce) {
    this.nonce = nonce
  }

  encrypt (plaintext, ad) {
    if (!this.hasKey) return plaintext
    if (!ad) ad = b4a.alloc(0)

    const ciphertext = encryptWithAD(this.key, this.nonce, ad, plaintext)
    if (ciphertext.length > 65535) throw new Error(`ciphertext length of ${ciphertext.length} exceeds maximum Noise message length of 65535`)
    this.nonce++

    return ciphertext
  }

  decrypt (ciphertext, ad) {
    if (!this.hasKey) return ciphertext
    if (!ad) ad = b4a.alloc(0)
    if (ciphertext.length > 65535) throw new Error(`ciphertext length of ${ciphertext.length} exceeds maximum Noise message length of 65535`)

    const plaintext = decryptWithAD(this.key, this.nonce, ad, ciphertext)
    this.nonce++

    return plaintext
  }

  get hasKey () {
    return this.key !== null
  }

  _clear () {
    sodium.sodium_memzero(this.key)
    this.key = null
    this.nonce = null
  }

  static get MACBYTES () {
    return 16
  }

  static get NONCEBYTES () {
    return 8
  }

  static get KEYBYTES () {
    return 32
  }
}

function encryptWithAD (key, counter, additionalData, plaintext) {
  // for our purposes, additionalData will always be a pubkey so we encode from hex
  if (!b4a.isBuffer(additionalData)) additionalData = b4a.from(additionalData, 'hex')
  if (!b4a.isBuffer(plaintext)) plaintext = b4a.from(plaintext, 'hex')

  const nonce = b4a.alloc(sodium.crypto_aead_chacha20poly1305_ietf_NPUBBYTES)
  const view = new DataView(nonce.buffer, nonce.byteOffset, nonce.byteLength)
  view.setUint32(4, counter, true)

  const ciphertext = b4a.alloc(plaintext.byteLength + sodium.crypto_aead_chacha20poly1305_ietf_ABYTES)

  sodium.crypto_aead_chacha20poly1305_ietf_encrypt(ciphertext, plaintext, additionalData, null, nonce, key)
  return ciphertext
}

function decryptWithAD (key, counter, additionalData, ciphertext) {
  // for our purposes, additionalData will always be a pubkey so we encode from hex
  if (!b4a.isBuffer(additionalData)) additionalData = b4a.from(additionalData, 'hex')
  if (!b4a.isBuffer(ciphertext)) ciphertext = b4a.from(ciphertext, 'hex')

  const nonce = b4a.alloc(sodium.crypto_aead_chacha20poly1305_ietf_NPUBBYTES)
  const view = new DataView(nonce.buffer, nonce.byteOffset, nonce.byteLength)
  view.setUint32(4, counter, true)

  const plaintext = b4a.alloc(ciphertext.byteLength - sodium.crypto_aead_chacha20poly1305_ietf_ABYTES)

  sodium.crypto_aead_chacha20poly1305_ietf_decrypt(plaintext, null, ciphertext, additionalData, nonce, key)
  return plaintext
}
/* eslint-disable camelcase */
const {
  crypto_kx_SEEDBYTES,
  crypto_kx_keypair,
  crypto_kx_seed_keypair,
  crypto_scalarmult_BYTES,
  crypto_scalarmult_SCALARBYTES,
  crypto_scalarmult,
  crypto_scalarmult_base
} = require('sodium-universal')

const assert = require('nanoassert')
const b4a = require('b4a')

const DHLEN = crypto_scalarmult_BYTES
const PKLEN = crypto_scalarmult_BYTES
const SKLEN = crypto_scalarmult_SCALARBYTES
const SEEDLEN = crypto_kx_SEEDBYTES
const ALG = '25519'

module.exports = {
  DHLEN,
  PKLEN,
  SKLEN,
  SEEDLEN,
  ALG,
  generateKeyPair,
  generateSeedKeyPair,
  dh
}

function generateKeyPair (privKey) {
  const keyPair = {}

  keyPair.secretKey = privKey || b4a.alloc(SKLEN)
  keyPair.publicKey = b4a.alloc(PKLEN)

  if (privKey) {
    crypto_scalarmult_base(keyPair.publicKey, keyPair.secretKey)
  } else {
    crypto_kx_keypair(keyPair.publicKey, keyPair.secretKey)
  }

  return keyPair
}

function generateSeedKeyPair (seed) {
  assert(seed.byteLength === SKLEN)

  const keyPair = {}
  keyPair.secretKey = b4a.alloc(SKLEN)
  keyPair.publicKey = b4a.alloc(PKLEN)

  crypto_kx_seed_keypair(keyPair.publicKey, keyPair.secretKey, seed)
  return keyPair
}

function dh (publicKey, { secretKey }) {
  assert(secretKey.byteLength === SKLEN)
  assert(publicKey.byteLength === PKLEN)

  const output = b4a.alloc(DHLEN)

  crypto_scalarmult(
    output,
    secretKey,
    publicKey
  )

  return output
}
const hmacBlake2b = require('./hmac')
const b4a = require('b4a')

const HASHLEN = 64

module.exports = {
  hkdf,
  HASHLEN
}

// HMAC-based Extract-and-Expand KDF
// https://www.ietf.org/rfc/rfc5869.txt

function hkdf (salt, inputKeyMaterial, info = '', length = 2 * HASHLEN) {
  const pseudoRandomKey = hkdfExtract(salt, inputKeyMaterial)
  return hkdfExpand(pseudoRandomKey, info, length)
}

function hkdfExtract (salt, inputKeyMaterial) {
  const hmac = b4a.alloc(HASHLEN)
  return hmacDigest(hmac, salt, inputKeyMaterial)
}

function hkdfExpand (key, info, length) {
  // Put in dedicated slab to avoid keeping shared slab from being gc'ed
  const buffer = b4a.allocUnsafeSlow(length)

  const infoBuf = b4a.from(info)
  let prev = infoBuf

  const result = []
  for (let i = 0; i < length; i += HASHLEN) {
    const pos = b4a.from([(i / HASHLEN) + 1])

    const out = buffer.subarray(i, i + HASHLEN)
    result.push(out)

    prev = hmacDigest(out, key, [prev, infoBuf, pos])
  }

  return result
}

function hmacDigest (out, key, input) {
  hmacBlake2b(out, input, key)
  return out
}
/* eslint-disable camelcase */
const b4a = require('b4a')
const { sodium_memzero, crypto_generichash, crypto_generichash_batch } = require('sodium-universal')

const HASHLEN = 64
const BLOCKLEN = 128
const scratch = b4a.alloc(BLOCKLEN * 3)
const HMACKey = scratch.subarray(BLOCKLEN * 0, BLOCKLEN * 1)
const OuterKeyPad = scratch.subarray(BLOCKLEN * 1, BLOCKLEN * 2)
const InnerKeyPad = scratch.subarray(BLOCKLEN * 2, BLOCKLEN * 3)

// Post-fill is done in the cases where someone caught an exception that
// happened before we were able to clear data at the end

module.exports = function hmac (out, batch, key) {
  if (key.byteLength > BLOCKLEN) {
    crypto_generichash(HMACKey.subarray(0, HASHLEN), key)
    sodium_memzero(HMACKey.subarray(HASHLEN))
  } else {
    // Covers key <= BLOCKLEN
    HMACKey.set(key)
    sodium_memzero(HMACKey.subarray(key.byteLength))
  }

  for (let i = 0; i < HMACKey.byteLength; i++) {
    OuterKeyPad[i] = 0x5c ^ HMACKey[i]
    InnerKeyPad[i] = 0x36 ^ HMACKey[i]
  }
  sodium_memzero(HMACKey)

  crypto_generichash_batch(out, [InnerKeyPad].concat(batch))
  sodium_memzero(InnerKeyPad)
  crypto_generichash_batch(out, [OuterKeyPad, out])
  sodium_memzero(OuterKeyPad)
}

module.exports.BYTES = HASHLEN
module.exports.KEYBYTES = BLOCKLEN
const assert = require('nanoassert')
const b4a = require('b4a')

const SymmetricState = require('./symmetric-state')
const { HASHLEN } = require('./hkdf')

const PRESHARE_IS = Symbol('initiator static key preshared')
const PRESHARE_RS = Symbol('responder static key preshared')

const TOK_PSK = Symbol('psk')

const TOK_S = Symbol('s')
const TOK_E = Symbol('e')

const TOK_ES = Symbol('es')
const TOK_SE = Symbol('se')
const TOK_EE = Symbol('ee')
const TOK_SS = Symbol('ss')

const HANDSHAKES = Object.freeze({
  NN: [
    [TOK_E],
    [TOK_E, TOK_EE]
  ],
  NNpsk0: [
    [TOK_PSK, TOK_E],
    [TOK_E, TOK_EE]
  ],
  XX: [
    [TOK_E],
    [TOK_E, TOK_EE, TOK_S, TOK_ES],
    [TOK_S, TOK_SE]
  ],
  XXpsk0: [
    [TOK_PSK, TOK_E],
    [TOK_E, TOK_EE, TOK_S, TOK_ES],
    [TOK_S, TOK_SE]
  ],
  IK: [
    PRESHARE_RS,
    [TOK_E, TOK_ES, TOK_S, TOK_SS],
    [TOK_E, TOK_EE, TOK_SE]
  ],
  XK: [
    PRESHARE_RS,
    [TOK_E, TOK_ES],
    [TOK_E, TOK_EE],
    [TOK_S, TOK_SE]
  ]
})

class Writer {
  constructor () {
    this.size = 0
    this.buffers = []
  }

  push (b) {
    this.size += b.byteLength
    this.buffers.push(b)
  }

  end () {
    const all = b4a.alloc(this.size)
    let offset = 0
    for (const b of this.buffers) {
      all.set(b, offset)
      offset += b.byteLength
    }
    return all
  }
}

class Reader {
  constructor (buf) {
    this.offset = 0
    this.buffer = buf
  }

  shift (n) {
    const start = this.offset
    const end = this.offset += n
    if (end > this.buffer.byteLength) throw new Error('Insufficient bytes')
    return this.buffer.subarray(start, end)
  }

  end () {
    return this.shift(this.buffer.byteLength - this.offset)
  }
}

module.exports = class NoiseState extends SymmetricState {
  constructor (pattern, initiator, staticKeypair, opts = {}) {
    super(opts)

    this.s = staticKeypair || this.curve.generateKeyPair()
    this.e = null

    this.psk = null
    if (opts && opts.psk) this.psk = opts.psk

    this.re = null
    this.rs = null

    this.pattern = pattern
    this.handshake = HANDSHAKES[this.pattern].slice()

    this.isPskHandshake = !!this.psk && hasPskToken(this.handshake)

    this.protocol = b4a.from([
      'Noise',
      this.pattern,
      this.DH_ALG,
      this.CIPHER_ALG,
      'BLAKE2b'
    ].join('_'))

    this.initiator = initiator
    this.complete = false

    this.rx = null
    this.tx = null
    this.hash = null
  }

  initialise (prologue, remoteStatic) {
    if (this.protocol.byteLength <= HASHLEN) this.digest.set(this.protocol)
    else this.mixHash(this.protocol)

    this.chainingKey = b4a.from(this.digest)

    this.mixHash(prologue)

    while (!Array.isArray(this.handshake[0])) {
      const message = this.handshake.shift()

      // handshake steps should be as arrays, only
      // preshare tokens are provided otherwise
      assert(message === PRESHARE_RS || message === PRESHARE_IS,
        'Unexpected pattern')

      const takeRemoteKey = this.initiator
        ? message === PRESHARE_RS
        : message === PRESHARE_IS

      if (takeRemoteKey) this.rs = remoteStatic

      const key = takeRemoteKey ? this.rs : this.s.publicKey
      assert(key != null, 'Remote pubkey required')

      this.mixHash(key)
    }
  }

  final () {
    const [k1, k2] = this.split()

    this.tx = this.initiator ? k1 : k2
    this.rx = this.initiator ? k2 : k1

    this.complete = true
    this.hash = this.getHandshakeHash()

    this._clear()
  }

  recv (buf) {
    const r = new Reader(buf)

    for (const pattern of this.handshake.shift()) {
      switch (pattern) {
        case TOK_PSK :
          this.mixKeyAndHash(this.psk)
          break

        case TOK_E :
          this.re = r.shift(this.curve.PKLEN)
          this.mixHash(this.re)
          if (this.isPskHandshake) this.mixKeyNormal(this.re)
          break

        case TOK_S : {
          const klen = this.hasKey ? this.curve.PKLEN + 16 : this.curve.PKLEN
          this.rs = this.decryptAndHash(r.shift(klen))
          break
        }

        case TOK_EE :
        case TOK_ES :
        case TOK_SE :
        case TOK_SS : {
          const useStatic = keyPattern(pattern, this.initiator)

          const localKey = useStatic.local ? this.s : this.e
          const remoteKey = useStatic.remote ? this.rs : this.re

          this.mixKey(remoteKey, localKey)
          break
        }

        default :
          throw new Error('Unexpected message')
      }
    }

    const payload = this.decryptAndHash(r.end())

    if (!this.handshake.length) this.final()
    return payload
  }

  send (payload = b4a.alloc(0)) {
    const w = new Writer()

    for (const pattern of this.handshake.shift()) {
      switch (pattern) {
        case TOK_PSK :
          this.mixKeyAndHash(this.psk)
          break

        case TOK_E :
          if (this.e === null) this.e = this.curve.generateKeyPair()
          this.mixHash(this.e.publicKey)
          if (this.isPskHandshake) this.mixKeyNormal(this.e.publicKey)
          w.push(this.e.publicKey)
          break

        case TOK_S :
          w.push(this.encryptAndHash(this.s.publicKey))
          break

        case TOK_ES :
        case TOK_SE :
        case TOK_EE :
        case TOK_SS : {
          const useStatic = keyPattern(pattern, this.initiator)

          const localKey = useStatic.local ? this.s : this.e
          const remoteKey = useStatic.remote ? this.rs : this.re

          this.mixKey(remoteKey, localKey)
          break
        }

        default :
          throw new Error('Unexpected message')
      }
    }

    w.push(this.encryptAndHash(payload))
    const response = w.end()

    if (!this.handshake.length) this.final()
    return response
  }

  _clear () {
    super._clear()

    this.e.secretKey.fill(0)
    this.e.publicKey.fill(0)

    this.re.fill(0)

    this.e = null
    this.re = null
  }
}

function keyPattern (pattern, initiator) {
  const ret = {
    local: false,
    remote: false
  }

  switch (pattern) {
    case TOK_EE:
      return ret

    case TOK_ES:
      ret.local ^= !initiator
      ret.remote ^= initiator
      return ret

    case TOK_SE:
      ret.local ^= initiator
      ret.remote ^= !initiator
      return ret

    case TOK_SS:
      ret.local ^= 1
      ret.remote ^= 1
      return ret
  }
}

function hasPskToken (handshake) {
  return handshake.some(x => {
    return Array.isArray(x) && x.indexOf(TOK_PSK) !== -1
  })
}
{
  "name": "noise-handshake",
  "version": "4.2.0",
  "description": "Noise protocol handshake",
  "main": "noise.js",
  "files": [
    "*.js"
  ],
  "scripts": {
    "test": "standard && brittle test/*.js"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/noise-handshake.git"
  },
  "dependencies": {
    "b4a": "^1.1.0",
    "nanoassert": "^2.0.0",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "noise-protocol": "chm-diederichs/noise-protocol.git#xx-ephemeral-key",
    "standard": "^16.0.3"
  }
}
const sodium = require('sodium-universal')
const assert = require('nanoassert')
const b4a = require('b4a')
const CipherState = require('./cipher')
const curve = require('./dh')
const { HASHLEN, hkdf } = require('./hkdf')

module.exports = class SymmetricState extends CipherState {
  constructor (opts = {}) {
    super()

    this.curve = opts.curve || curve
    this.digest = b4a.alloc(HASHLEN)
    this.chainingKey = null
    this.offset = 0

    this.DH_ALG = this.curve.ALG
  }

  mixHash (data) {
    accumulateDigest(this.digest, data)
  }

  mixKeyAndHash (key) {
    const [ck, tempH, tempK] = hkdf(this.chainingKey, key, '', 3 * HASHLEN)
    this.chainingKey = ck
    this.mixHash(tempH)
    this.initialiseKey(tempK.subarray(0, 32))
  }

  mixKeyNormal (key) {
    const [ck, tempK] = hkdf(this.chainingKey, key)
    this.chainingKey = ck
    this.initialiseKey(tempK.subarray(0, 32))
  }

  mixKey (remoteKey, localKey) {
    const dh = this.curve.dh(remoteKey, localKey)
    const hkdfResult = hkdf(this.chainingKey, dh)
    this.chainingKey = hkdfResult[0]
    this.initialiseKey(hkdfResult[1].subarray(0, 32))
  }

  encryptAndHash (plaintext) {
    const ciphertext = this.encrypt(plaintext, this.digest)
    accumulateDigest(this.digest, ciphertext)
    return ciphertext
  }

  decryptAndHash (ciphertext) {
    const plaintext = this.decrypt(ciphertext, this.digest)
    accumulateDigest(this.digest, ciphertext)
    return plaintext
  }

  getHandshakeHash (out) {
    if (!out) return this.getHandshakeHash(b4a.alloc(HASHLEN))
    assert(out.byteLength === HASHLEN, `output must be ${HASHLEN} bytes`)

    out.set(this.digest)
    return out
  }

  split () {
    const res = hkdf(this.chainingKey, b4a.alloc(0))
    return res.map(k => k.subarray(0, 32))
  }

  _clear () {
    super._clear()

    sodium.sodium_memzero(this.digest)
    sodium.sodium_memzero(this.chainingKey)

    this.digest = null
    this.chainingKey = null
    this.offset = null

    this.curve = null
  }

  static get alg () {
    return CipherState.alg + '_BLAKE2b'
  }
}

function accumulateDigest (digest, input) {
  const toHash = b4a.concat([digest, input])
  sodium.crypto_generichash(digest, toHash)
}
const b4a = require('b4a')
const c = require('compact-encoding')
const queueTick = require('queue-tick')
const safetyCatch = require('safety-catch')
const unslab = require('unslab')

const MAX_BUFFERED = 32768
const MAX_BACKLOG = Infinity // TODO: impl "open" backpressure
const MAX_BATCH = 8 * 1024 * 1024

class Channel {
  constructor(
    mux,
    info,
    userData,
    protocol,
    aliases,
    id,
    handshake,
    messages,
    onopen,
    onclose,
    ondestroy,
    ondrain
  ) {
    this.userData = userData
    this.protocol = protocol
    this.aliases = aliases
    this.id = id
    this.handshake = null
    this.messages = []

    this.opened = false
    this.closed = false
    this.destroyed = false

    this.onopen = onopen
    this.onclose = onclose
    this.ondestroy = ondestroy
    this.ondrain = ondrain

    this._handshake = handshake
    this._mux = mux
    this._info = info
    this._localId = 0
    this._remoteId = 0
    this._active = 0
    this._extensions = null

    this._decBound = this._dec.bind(this)
    this._decAndDestroyBound = this._decAndDestroy.bind(this)

    this._openedPromise = null
    this._openedResolve = null

    this._destroyedPromise = null
    this._destroyedResolve = null

    for (const m of messages) this.addMessage(m)
  }

  get drained() {
    return this._mux.drained
  }

  fullyOpened() {
    if (this.opened) return Promise.resolve(true)
    if (this.closed) return Promise.resolve(false)
    if (this._openedPromise) return this._openedPromise

    this._openedPromise = new Promise((resolve) => {
      this._openedResolve = resolve
    })
    return this._openedPromise
  }

  fullyClosed() {
    if (this.destroyed) return Promise.resolve()
    if (this._destroyedPromise) return this._destroyedPromise

    this._destroyedPromise = new Promise((resolve) => {
      this._destroyedResolve = resolve
    })
    return this._destroyedPromise
  }

  open(handshake) {
    const id = this._mux._free.length > 0 ? this._mux._free.pop() : this._mux._local.push(null) - 1

    this._info.opened++
    this._info.lastChannel = this
    this._localId = id + 1
    this._mux._local[id] = this

    if (this._remoteId === 0) {
      this._info.outgoing.push(this._localId)
    }

    const state = { buffer: null, start: 2, end: 2 }

    c.uint.preencode(state, this._localId)
    c.string.preencode(state, this.protocol)
    c.optionalBuffer.preencode(state, this.id)
    if (this._handshake) this._handshake.preencode(state, handshake)

    state.buffer = this._mux._alloc(state.end)

    state.buffer[0] = 0
    state.buffer[1] = 1
    c.uint.encode(state, this._localId)
    c.string.encode(state, this.protocol)
    c.optionalBuffer.encode(state, this.id)
    if (this._handshake) this._handshake.encode(state, handshake)

    this._mux._write0(state.buffer)
  }

  _dec() {
    if (--this._active === 0 && this.closed === true) this._destroy()
  }

  _decAndDestroy(err) {
    this._dec()
    this._mux._safeDestroy(err)
  }

  _fullyOpenSoon() {
    this._mux._remote[this._remoteId - 1].session = this
    queueTick(this._fullyOpenOrDestroy.bind(this))
  }

  _fullyOpenOrDestroy() {
    try {
      this._fullyOpen()
    } catch (err) {
      this._mux._safeDestroyBound(err)
    }
  }

  _fullyOpen() {
    if (this.opened === true || this.closed === true) return

    const remote = this._mux._remote[this._remoteId - 1]

    this.handshake = this._handshake ? this._handshake.decode(remote.state) : null
    this._track(this.onopen(this.handshake, this))

    remote.session = this
    remote.state = null
    if (remote.pending !== null) this._drain(remote)
    if (this._mux._destroying === true) return

    this.opened = true
    this._resolveOpen(true)
  }

  _resolveOpen(opened) {
    if (this._openedResolve !== null) {
      this._openedResolve(opened)
      this._openedResolve = this._openedPromise = null
    }
  }

  _resolveDestroyed() {
    if (this._destroyedResolve !== null) {
      this._destroyedResolve()
      this._destroyedResolve = this._destroyedPromise = null
    }
  }

  _drain(remote) {
    for (let i = 0; i < remote.pending.length; i++) {
      const p = remote.pending[i]
      this._mux._buffered -= byteSize(p.state)
      this._recv(p.type, p.state)
      if (this._mux._destroying === true) return
    }

    remote.pending = null
    this._mux._resumeMaybe()
  }

  _track(p) {
    if (isPromise(p) === true) {
      this._active++
      return p.then(this._decBound, this._decAndDestroyBound)
    }

    return null
  }

  _close(isRemote) {
    if (this.closed === true) return
    this.closed = true

    this._info.opened--
    if (this._info.lastChannel === this) this._info.lastChannel = null

    if (this._remoteId > 0) {
      this._mux._remote[this._remoteId - 1] = null
      this._remoteId = 0
      // If remote has acked, we can reuse the local id now
      // otherwise, we need to wait for the "ack" to arrive
      this._mux._free.push(this._localId - 1)
    }

    this._mux._local[this._localId - 1] = null
    this._localId = 0

    this._mux._gc(this._info)
    this._track(this.onclose(isRemote, this))

    if (this._active === 0) this._destroy()

    this._resolveOpen(false)
  }

  _destroy() {
    if (this.destroyed === true) return
    this.destroyed = true
    this._track(this.ondestroy(this))
    this._resolveDestroyed()
  }

  _recv(type, state) {
    if (type < this.messages.length) {
      const m = this.messages[type]
      const p = m.recv(state, this)
      if (m.autoBatch === true) return p
    }
    return null
  }

  cork() {
    this._mux.cork()
  }

  uncork() {
    this._mux.uncork()
  }

  close() {
    if (this.closed === true) return

    const state = { buffer: null, start: 2, end: 2 }

    c.uint.preencode(state, this._localId)

    state.buffer = this._mux._alloc(state.end)

    state.buffer[0] = 0
    state.buffer[1] = 3
    c.uint.encode(state, this._localId)

    this._close(false)
    this._mux._write0(state.buffer)
  }

  addMessage(opts) {
    if (!opts) return this._skipMessage()

    const type = this.messages.length
    const autoBatch = opts.autoBatch !== false
    const encoding = opts.encoding || c.raw
    const onmessage = opts.onmessage || noop

    const s = this
    const typeLen = encodingLength(c.uint, type)

    const m = {
      type,
      autoBatch,
      encoding,
      onmessage,
      recv(state, session) {
        return session._track(m.onmessage(encoding.decode(state), session))
      },
      send(m, session = s) {
        if (session.closed === true) return false

        const mux = session._mux
        const state = { buffer: null, start: 0, end: typeLen }

        if (mux._batch !== null) {
          encoding.preencode(state, m)
          state.buffer = mux._alloc(state.end)

          c.uint.encode(state, type)
          encoding.encode(state, m)

          mux._pushBatch(session._localId, state.buffer)
          return true
        }

        c.uint.preencode(state, session._localId)
        encoding.preencode(state, m)

        state.buffer = mux._alloc(state.end)

        c.uint.encode(state, session._localId)
        c.uint.encode(state, type)
        encoding.encode(state, m)

        mux.drained = mux.stream.write(state.buffer)

        return mux.drained
      }
    }

    this.messages.push(m)

    return m
  }

  _skipMessage() {
    const type = this.messages.length
    const m = {
      type,
      encoding: c.raw,
      onmessage: noop,
      recv(state, session) {},
      send(m, session) {}
    }

    this.messages.push(m)
    return m
  }
}

module.exports = class Protomux {
  constructor(stream, { alloc } = {}) {
    if (stream.userData === null) stream.userData = this

    this.isProtomux = true
    this.stream = stream
    this.corked = 0
    this.drained = true

    this._alloc =
      alloc || (typeof stream.alloc === 'function' ? stream.alloc.bind(stream) : b4a.allocUnsafe)
    this._safeDestroyBound = this._safeDestroy.bind(this)
    this._uncorkBound = this.uncork.bind(this)

    this._remoteBacklog = 0
    this._buffered = 0
    this._paused = false
    this._remote = []
    this._local = []
    this._free = []
    this._batch = null
    this._batchState = null

    this._infos = new Map()
    this._notify = new Map()
    // stream.destroyed flips asynchronously on streamx-based transports.
    this._destroying = false

    this.stream.on('data', this._ondata.bind(this))
    this.stream.on('drain', this._ondrain.bind(this))
    this.stream.on('end', this._onend.bind(this))
    this.stream.on('error', noop) // we handle this in "close"
    this.stream.on('close', this._shutdown.bind(this))
  }

  static from(stream, opts) {
    if (stream.userData && stream.userData.isProtomux) return stream.userData
    if (stream.isProtomux) return stream
    return new this(stream, opts)
  }

  static isProtomux(mux) {
    return typeof mux === 'object' && mux.isProtomux === true
  }

  *[Symbol.iterator]() {
    for (const session of this._local) {
      if (session !== null) yield session
    }
  }

  isIdle() {
    return this._local.length === this._free.length
  }

  cork() {
    if (++this.corked === 1) {
      this._batch = []
      this._batchState = { buffer: null, start: 0, end: 1 }
    }
  }

  uncork() {
    if (--this.corked === 0) {
      this._sendBatch(this._batch, this._batchState)
      this._batch = null
      this._batchState = null
    }
  }

  getLastChannel({ protocol, id = null }) {
    const key = toKey(protocol, id)
    const info = this._infos.get(key)
    if (info) return info.lastChannel
    return null
  }

  pair({ protocol, id = null }, notify) {
    this._notify.set(toKey(protocol, id), notify)
  }

  unpair({ protocol, id = null }) {
    this._notify.delete(toKey(protocol, id))
  }

  opened({ protocol, id = null }) {
    const key = toKey(protocol, id)
    const info = this._infos.get(key)
    return info ? info.opened > 0 : false
  }

  createChannel({
    userData = null,
    protocol,
    aliases = [],
    id = null,
    unique = true,
    handshake = null,
    messages = [],
    onopen = noop,
    onclose = noop,
    ondestroy = noop,
    ondrain = noop
  }) {
    if (this.stream.destroyed) return null

    const info = this._get(protocol, id, aliases)
    if (unique && info.opened > 0) return null

    if (info.incoming.length === 0) {
      return new Channel(
        this,
        info,
        userData,
        protocol,
        aliases,
        id,
        handshake,
        messages,
        onopen,
        onclose,
        ondestroy,
        ondrain
      )
    }

    this._remoteBacklog--

    const remoteId = info.incoming.shift()
    const r = this._remote[remoteId - 1]
    if (r === null) return null

    const session = new Channel(
      this,
      info,
      userData,
      protocol,
      aliases,
      id,
      handshake,
      messages,
      onopen,
      onclose,
      ondestroy,
      ondrain
    )

    session._remoteId = remoteId
    session._fullyOpenSoon()

    return session
  }

  _pushBatch(localId, buffer) {
    if (this._batchState.end >= MAX_BATCH) {
      this._sendBatch(this._batch, this._batchState)
      this._batch = []
      this._batchState = { buffer: null, start: 0, end: 1 }
    }

    if (this._batch.length === 0 || this._batch[this._batch.length - 1].localId !== localId) {
      this._batchState.end++
      c.uint.preencode(this._batchState, localId)
    }
    c.buffer.preencode(this._batchState, buffer)
    this._batch.push({ localId, buffer })
  }

  _sendBatch(batch, state) {
    if (batch.length === 0) return

    let prev = batch[0].localId

    state.buffer = this._alloc(state.end)
    state.buffer[state.start++] = 0
    state.buffer[state.start++] = 0

    c.uint.encode(state, prev)

    for (let i = 0; i < batch.length; i++) {
      const b = batch[i]
      if (prev !== b.localId) {
        state.buffer[state.start++] = 0
        c.uint.encode(state, (prev = b.localId))
      }
      c.buffer.encode(state, b.buffer)
    }

    this.drained = this.stream.write(state.buffer)
  }

  _get(protocol, id, aliases = []) {
    const key = toKey(protocol, id)

    let info = this._infos.get(key)
    if (info) return info

    info = {
      key,
      protocol,
      aliases: [],
      id,
      pairing: 0,
      opened: 0,
      incoming: [],
      outgoing: [],
      lastChannel: null
    }
    this._infos.set(key, info)

    for (const alias of aliases) {
      const key = toKey(alias, id)
      info.aliases.push(key)

      this._infos.set(key, info)
    }

    return info
  }

  _gc(info) {
    if (info.opened === 0 && info.outgoing.length === 0 && info.incoming.length === 0) {
      this._infos.delete(info.key)

      for (const alias of info.aliases) this._infos.delete(alias)
    }
  }

  _ondata(buffer) {
    if (buffer.byteLength === 0) return // ignore empty frames...
    try {
      const state = { buffer, start: 0, end: buffer.byteLength }
      this._decode(c.uint.decode(state), state)
    } catch (err) {
      this._safeDestroy(err)
    }
  }

  _ondrain() {
    this.drained = true

    for (const s of this._local) {
      if (s !== null) s._track(s.ondrain(s))
    }
  }

  _onend() {
    // TODO: support half open mode for the users who wants that here
    this.stream.end()
  }

  _decode(remoteId, state) {
    const type = c.uint.decode(state)

    if (remoteId === 0) {
      return this._oncontrolsession(type, state)
    }

    const r = remoteId <= this._remote.length ? this._remote[remoteId - 1] : null

    // if the channel is closed ignore - could just be a pipeline message...
    if (r === null) return null

    if (r.pending !== null) {
      this._bufferMessage(r, type, state)
      return null
    }

    return r.session._recv(type, state)
  }

  _oncontrolsession(type, state) {
    switch (type) {
      case 0:
        this._onbatch(state)
        break

      case 1:
        // return the promise back up as this has sideeffects so we can batch reply
        return this._onopensession(state)

      case 2:
        this._onrejectsession(state)
        break

      case 3:
        this._onclosesession(state)
        break
    }

    return null
  }

  _bufferMessage(r, type, { buffer, start, end }) {
    const state = { buffer, start, end } // copy
    r.pending.push({ type, state })
    this._buffered += byteSize(state)
    this._pauseMaybe()
  }

  _pauseMaybe() {
    if (this._paused === true || this._buffered <= MAX_BUFFERED) return
    this._paused = true
    this.stream.pause()
  }

  _resumeMaybe() {
    if (this._paused === false || this._buffered > MAX_BUFFERED) return
    this._paused = false
    this.stream.resume()
  }

  _onbatch(state) {
    const end = state.end
    let remoteId = c.uint.decode(state)

    let waiting = null

    while (state.end > state.start) {
      const len = c.uint.decode(state)
      if (len === 0) {
        remoteId = c.uint.decode(state)
        continue
      }
      state.end = state.start + len
      // if batch contains more than one message, cork it so we reply back with a batch
      if (end !== state.end && waiting === null) {
        waiting = []
        this.cork()
      }
      const p = this._decode(remoteId, state)
      if (waiting !== null && p !== null) waiting.push(p)
      state.start = state.end
      state.end = end
    }

    if (waiting !== null) {
      // the waiting promises are not allowed to throw but we destroy the stream in case we are wrong
      Promise.all(waiting).then(this._uncorkBound, this._safeDestroyBound)
    }
  }

  _onopensession(state) {
    const remoteId = c.uint.decode(state)
    const protocol = c.string.decode(state)
    const id = unslab(c.optionalBuffer.decode(state))

    // remote tried to open the control session - auto reject for now
    // as we can use as an explicit control protocol declaration if we need to
    if (remoteId === 0) {
      this._rejectSession(0)
      return null
    }

    const rid = remoteId - 1
    const info = this._get(protocol, id)

    // allow the remote to grow the ids by one
    if (this._remote.length === rid) {
      this._remote.push(null)
    }

    if (rid >= this._remote.length || this._remote[rid] !== null) {
      throw new Error('Invalid open message')
    }

    if (info.outgoing.length > 0) {
      const localId = info.outgoing.shift()
      const session = this._local[localId - 1]

      if (session === null) {
        // we already closed the channel - ignore
        this._free.push(localId - 1)
        return null
      }

      this._remote[rid] = { state, pending: null, session: null }

      session._remoteId = remoteId
      session._fullyOpen()
      return null
    }

    const copyState = { buffer: state.buffer, start: state.start, end: state.end }
    this._remote[rid] = { state: copyState, pending: [], session: null }

    if (++this._remoteBacklog > MAX_BACKLOG) {
      throw new Error('Remote exceeded backlog')
    }

    info.pairing++
    info.incoming.push(remoteId)

    return this._requestSession(protocol, id, info).catch(this._safeDestroyBound)
  }

  _onrejectsession(state) {
    const localId = c.uint.decode(state)

    // TODO: can be done smarter...
    for (const info of this._infos.values()) {
      const i = info.outgoing.indexOf(localId)
      if (i === -1) continue

      info.outgoing.splice(i, 1)

      const session = this._local[localId - 1]

      this._free.push(localId - 1)
      if (session !== null) session._close(true)

      this._gc(info)
      return
    }

    throw new Error('Invalid reject message')
  }

  _onclosesession(state) {
    const remoteId = c.uint.decode(state)

    if (remoteId === 0) return // ignore

    const rid = remoteId - 1
    const r = rid < this._remote.length ? this._remote[rid] : null

    if (r === null) return

    if (r.session !== null) r.session._close(true)
  }

  async _requestSession(protocol, id, info) {
    const notify = this._notify.get(toKey(protocol, id)) || this._notify.get(toKey(protocol, null))

    if (notify) await notify(id)

    if (--info.pairing > 0) return

    while (info.incoming.length > 0) {
      this._rejectSession(info, info.incoming.shift())
    }

    this._gc(info)
  }

  _rejectSession(info, remoteId) {
    if (remoteId > 0) {
      const r = this._remote[remoteId - 1]

      if (r.pending !== null) {
        for (let i = 0; i < r.pending.length; i++) {
          this._buffered -= byteSize(r.pending[i].state)
        }
      }

      this._remote[remoteId - 1] = null
      this._resumeMaybe()
    }

    const state = { buffer: null, start: 2, end: 2 }

    c.uint.preencode(state, remoteId)

    state.buffer = this._alloc(state.end)

    state.buffer[0] = 0
    state.buffer[1] = 2
    c.uint.encode(state, remoteId)

    this._write0(state.buffer)
  }

  _write0(buffer) {
    if (this._batch !== null) {
      this._pushBatch(0, buffer.subarray(1))
      return
    }

    this.drained = this.stream.write(buffer)
  }

  destroy(err) {
    this._destroying = true
    this.stream.destroy(err)
  }

  _safeDestroy(err) {
    safetyCatch(err)
    this._destroying = true
    this.stream.destroy(err)
  }

  _shutdown() {
    this._destroying = true
    for (const s of this._local) {
      if (s !== null) s._close(true)
    }
  }
}

function noop() {}

function toKey(protocol, id) {
  return protocol + '##' + (id ? b4a.toString(id, 'hex') : '')
}

function byteSize(state) {
  return 512 + (state.end - state.start)
}

function isPromise(p) {
  return !!(p && typeof p.then === 'function')
}

function encodingLength(enc, val) {
  const state = { buffer: null, start: 0, end: 0 }
  enc.preencode(state, val)
  return state.end
}
{
  "name": "protomux",
  "version": "3.11.0",
  "description": "Multiplex multiple message oriented protocols over a stream",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.3.1",
    "compact-encoding": "^3.0.0",
    "queue-tick": "^1.0.0",
    "safety-catch": "^1.0.1",
    "unslab": "^1.3.0"
  },
  "devDependencies": {
    "@hyperswarm/secret-stream": "^6.0.0",
    "brittle": "^3.0.0",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/protomux.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/protomux/issues"
  },
  "homepage": "https://github.com/holepunchto/protomux"
}
{
  "name": "queue-tick",
  "version": "1.0.1",
  "description": "Next tick shim that prefers process.nextTick over queueMicrotask for compat",
  "main": "./process-next-tick.js",
  "browser": "./queue-microtask.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^16.0.3",
    "tape": "^5.3.1"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/queue-tick.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/queue-tick/issues"
  },
  "homepage": "https://github.com/mafintosh/queue-tick"
}
module.exports = (typeof process !== 'undefined' && typeof process.nextTick === 'function')
  ? process.nextTick.bind(process)
  : require('./queue-microtask')
module.exports = typeof queueMicrotask === 'function' ? queueMicrotask : (fn) => Promise.resolve().then(fn)
const EventEmitter = require('events')

module.exports = class ReadyResource extends EventEmitter {
  constructor () {
    super()

    this.opening = null
    this.closing = null

    this.opened = false
    this.closed = false
  }

  ready () {
    if (this.opening !== null) return this.opening
    this.opening = open(this)
    return this.opening
  }

  close () {
    if (this.closing !== null) return this.closing
    this.closing = close(this)
    return this.closing
  }

  async _open () {
    // add impl here
  }

  async _close () {
    // add impl here
  }
}

async function open (self) {
  // open after close
  if (self.closing !== null) return

  try {
    await self._open()
  } catch (err) {
    self.close() // safe to run in bg
    throw err
  }

  self.opened = true
  self.emit('ready')
}

async function close (self) {
  try {
    if (self.opened === false && self.opening !== null) await self.opening
  } catch {
    // ignore errors on closing
  }
  if (self.opened === true || self.opening === null) await self._close()
  self.closed = true
  self.emit('close')
}
{
  "name": "ready-resource",
  "version": "1.2.0",
  "description": "Modern single resource management",
  "main": "index.js",
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "types": "index.d.ts",
  "files": [
    "index.js",
    "index.d.ts"
  ],
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "devDependencies": {
    "brittle": "^3.1.0",
    "standard": "^17.0.0"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/ready-resource.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/ready-resource/issues"
  },
  "homepage": "https://github.com/holepunchto/ready-resource",
  "dependencies": {
    "bare-events": "^2.2.0"
  }
}
const b4a = require('b4a')

var EMPTY = []

module.exports = RecordCache

function RecordSet () {
  this.list = []
  this.map = new Map()
}

RecordSet.prototype.add = function (record, value) {
  var k = toString(record)
  var r = this.map.get(k)
  if (r) return false

  r = {index: this.list.length, record: value || record}
  this.list.push(r)
  this.map.set(k, r)
  return true
}

RecordSet.prototype.remove = function (record) {
  var k = toString(record)
  var r = this.map.get(k)
  if (!r) return false

  swap(this.list, r.index, this.list.length - 1)
  this.list.pop()
  this.map.delete(k)
  return true
}

function RecordStore () {
  this.records = new Map()
  this.size = 0
}

RecordStore.prototype.add = function (name, record, value) {
  var r = this.records.get(name)

  if (!r) {
    r = new RecordSet()
    this.records.set(name, r)
  }

  if (r.add(record, value)) {
    this.size++
    return true
  }

  return false
}

RecordStore.prototype.remove = function (name, record, value) {
  var r = this.records.get(name)
  if (!r) return false

  if (r.remove(record, value)) {
    this.size--
    if (!r.map.size) this.records.delete(name)
    return true
  }

  return false
}

RecordStore.prototype.get = function (name) {
  var r = this.records.get(name)
  return r ? r.list : EMPTY
}

function RecordCache (opts) {
  if (!(this instanceof RecordCache)) return new RecordCache(opts)
  if (!opts) opts = {}

  this.maxSize = opts.maxSize || Infinity
  this.maxAge = opts.maxAge || 0

  this._onstale = opts.onStale || opts.onstale || null
  this._fresh = new RecordStore()
  this._stale = new RecordStore()
  this._interval = null
  this._gced = false

  if (this.maxAge && this.maxAge < Infinity) {
    // 2/3 gives us a span of 0.66-1.33 maxAge or avg maxAge
    var tick = Math.ceil(2 / 3 * this.maxAge)
    this._interval = setInterval(this._gcAuto.bind(this), tick)
    if (this._interval.unref) this._interval.unref()
  }
}

Object.defineProperty(RecordCache.prototype, 'size', {
  get: function () {
    return this._fresh.size + this._stale.size
  }
})

RecordCache.prototype.add = function (name, record, value) {
  this._stale.remove(name, record, value)
  if (this._fresh.add(name, record, value) && this._fresh.size > this.maxSize) {
    this._gc()
  }
}

RecordCache.prototype.remove = function (name, record, value) {
  this._fresh.remove(name, record, value)
  this._stale.remove(name, record, value)
}

RecordCache.prototype.get = function (name, n) {
  var a = this._fresh.get(name)
  var b = this._stale.get(name)
  var aLen = a.length
  var bLen = b.length
  var len = aLen + bLen

  if (n > len || !n) n = len
  var result = new Array(n)

  for (var i = 0; i < n; i++) {
    var j = Math.floor(Math.random() * (aLen + bLen))
    if (j < aLen) {
      result[i] = a[j].record
      swap(a, j, --aLen)
    } else {
      j -= aLen
      result[i] = b[j].record
      swap(b, j, --bLen)
    }
  }

  return result
}

RecordCache.prototype._gcAuto = function () {
  if (!this._gced) this._gc()
  this._gced = false
}

RecordCache.prototype._gc = function () {
  if (this._onstale && this._stale.size > 0) this._onstale(this._stale)
  this._stale = this._fresh
  this._fresh = new RecordStore()
  this._gced = true
}

RecordCache.prototype.clear = function () {
  this._gc()
  this._gc()
}

RecordCache.prototype.destroy = function () {
  this.clear()
  clearInterval(this._interval)
  this._interval = null
}

function toString (record) {
  return b4a.isBuffer(record) ? b4a.toString(record, 'hex') : record
}

function swap (list, a, b) {
  var tmp = list[a]
  tmp.index = b
  list[b].index = a
  list[a] = list[b]
  list[b] = tmp
}
{
  "name": "record-cache",
  "version": "1.2.0",
  "description": "Cache optimised for record like things",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.3.1"
  },
  "devDependencies": {
    "standard": "^10.0.3",
    "tape": "^4.8.0"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/record-cache.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/record-cache/issues"
  },
  "homepage": "https://github.com/mafintosh/record-cache"
}
module.exports = require.addon.bind(require)
{
  "name": "require-addon",
  "version": "1.2.0",
  "description": "Import native addons across JavaScript runtimes",
  "exports": {
    "./package": "./package.json",
    ".": {
      "bare": "./lib/bare.js",
      "node": "./lib/node.js",
      "default": "./lib/default.js"
    }
  },
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    },
    "url": {
      "bare": "bare-url",
      "default": "url"
    }
  },
  "files": [
    "lib"
  ],
  "scripts": {
    "test": "npm run lint && npm run test:bare && npm run test:node",
    "test:bare": "bare test.js",
    "test:node": "node test.js",
    "lint": "prettier --check .",
    "format": "prettier --write ."
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/require-addon.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/require-addon/issues"
  },
  "homepage": "https://github.com/holepunchto/require-addon#readme",
  "engines": {
    "bare": ">=1.10.0"
  },
  "dependencies": {
    "bare-addon-resolve": "^1.3.0"
  },
  "devDependencies": {
    "bare-bundle": "^1.8.1",
    "bare-bundle-evaluate": "^1.1.0",
    "bare-fs": "^4.0.0",
    "bare-path": "^3.0.0",
    "bare-url": "^2.1.0",
    "brittle": "^3.7.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = safetyCatch

function isActuallyUncaught (err) {
  if (!err) return false
  return err instanceof TypeError ||
    err instanceof SyntaxError ||
    err instanceof ReferenceError ||
    err instanceof EvalError ||
    err instanceof RangeError ||
    err instanceof URIError ||
    err.code === 'ERR_ASSERTION' ||
    err.name === 'AssertionError'
}

function throwErrorNT (err) {
  queueMicrotask(() => { throw err })
}

function safetyCatch (err) {
  if (isActuallyUncaught(err)) {
    throwErrorNT(err)
    throw err
  }
}
{
  "name": "safety-catch",
  "version": "1.0.3",
  "description": "Small module that makes sure your catch, caught an actual error and not a programming mistake or assertion",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {},
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/safety-catch.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/safety-catch/issues"
  },
  "homepage": "https://github.com/mafintosh/safety-catch"
}
const set = require('unordered-set')

module.exports = opts => new ShuffledPriorityQueue(opts)

class ShuffledPriorityQueue {
  constructor (opts) {
    this.priorities = []
    this.equals = (opts && opts.equals) || null
  }

  get length () {
    return this.priorities.reduce(add, 0)
  }

  [Symbol.iterator] () {
    return new Iterator(this)
  }

  head () {
    for (let i = this.priorities.length - 1; i >= 0; i--) {
      const q = this.priorities[i]
      if (q.length) return shuffle(q, 0)
    }
    return null
  }

  tail () {
    for (let i = 0; i < this.priorities.length; i++) {
      const q = this.priorities[i]
      if (q.length) return shuffle(q, 0)
    }
    return null
  }

  prev (prev) {
    if (!prev) return this.tail()
    return next(this.priorities, prev, 1)
  }

  next (prev) {
    if (!prev) return this.head()
    return next(this.priorities, prev, -1)
  }

  shift () {
    return this.remove(this.head())
  }

  pop () {
    return this.remove(this.tail())
  }

  add (val) {
    const prio = val.priority || 0
    while (prio >= this.priorities.length) this.priorities.push([])
    set.add(this.priorities[prio], val)
    return val
  }

  remove (val) {
    if (!val) return null

    if (val._index === undefined) {
      val = this.find(val)
      if (!val) return null
    }

    return set.remove(this.priorities[val.priority || 0], val)
  }

  has (val) {
    if (val._index === undefined) return this.find(val)
    const priority = val.priority || 0
    if (priority >= this.priorities.length) return false
    return set.has(this.priorities[priority], val)
  }

  find (val) {
    if (val._index !== undefined) return val

    const prio = val.priority || 0
    const qs = this.priorities
    if (prio >= qs.length) return null

    const q = qs[prio]

    for (let i = 0; i < q.length; i++) {
      if (this.equals(q[i], val)) return q[i]
    }

    return null
  }
}

class Iterator {
  constructor (queue) {
    this.prev = null
    this.queue = queue
  }

  next () {
    const next = this.queue.next(this.prev)
    this.prev = next
    return { done: !next, value: next }
  }
}

function shuffle (q, i) {
  const ran = i + Math.floor(Math.random() * (q.length - i))
  set.swap(q, q[ran], q[i])
  return q[i]
}

function next (queues, prev, inc) {
  let i = prev.priority || 0
  let j = (prev._index || 0) + 1

  while (true) {
    if (i < 0 || i >= queues.length) return null
    const q = queues[i]

    if (j >= q.length) {
      i += inc
      j = 0
      continue
    }

    return shuffle(q, j)
  }
}

function add (len, b) {
  return len + b.length
}
{
  "name": "shuffled-priority-queue",
  "version": "2.1.0",
  "description": "A priority queue that shuffles elements with the same priority.",
  "main": "index.js",
  "scripts": {
    "test": "standard && tape test.js"
  },
  "dependencies": {
    "unordered-set": "^2.0.1"
  },
  "devDependencies": {
    "standard": "^12.0.1",
    "tape": "^4.9.1"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/shuffled-priority-queue.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/shuffled-priority-queue/issues"
  },
  "homepage": "https://github.com/mafintosh/shuffled-priority-queue"
}
module.exports = class Signal {
  constructor () {
    this._resolve = null
    this._reject = null
    this._promise = null
    this._bind = bind.bind(this)
    this._onerror = clear.bind(this)
    this._onsuccess = clear.bind(this, null)
    this._timers = new Set()
  }

  wait (max) {
    if (!this._promise) {
      this._promise = new Promise(this._bind)
      this._promise.then(this._onsuccess).catch(this._onerror)
    }
    if (max) return this._sleep(max)
    return this._promise
  }

  _sleep (max) {
    const s = new Promise((resolve, reject) => {
      const done = () => {
        this._timers.delete(state)
        resolve(true)
      }
      const id = setTimeout(done, max)
      const state = { id, resolve, reject }
      this._timers.add(state)
    })

    return s
  }

  notify (err) {
    if (!this._promise) return
    const resolve = this._resolve
    const reject = this._reject
    this._promise = null
    if (err) reject(err)
    else resolve(true)
  }
}

function clear (err) {
  for (const { id, resolve, reject } of this._timers) {
    clearTimeout(id)
    if (err) reject(err)
    else resolve(true)
  }
  this._timers.clear()
}

function bind (resolve, reject) {
  this._resolve = resolve
  this._reject = reject
}
{
  "name": "signal-promise",
  "version": "1.0.3",
  "description": "Simple wait/notify promise with optional max wait time",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {},
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/signal-promise.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/signal-promise/issues"
  },
  "homepage": "https://github.com/mafintosh/signal-promise"
}
require.addon = require('require-addon')
module.exports = require.addon('.', __filename)
const assert = require('assert')
const binding = require('./binding')
const { isNode } = require('which-runtime')

const OPTIONAL = Buffer.from(new ArrayBuffer(0))

module.exports = exports = { ...binding }

// memory

exports.sodium_memzero = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  binding.sodium_memzero(buf)
}

exports.sodium_mlock = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  const res = binding.sodium_mlock(buf)

  if (res !== 0) throw new Error('memory lock failed')
}

exports.sodium_munlock = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  const res = binding.sodium_munlock(buf)

  if (res !== 0) throw new Error('memory unlock failed')
}

exports.sodium_malloc = function (size) {
  assert(size >= 0, 'invalid size')

  const buf = Buffer.from(binding.sodium_malloc(size))
  buf.secure = true
  return buf
}

exports.sodium_free = function (buf) {
  if (!buf || !buf.secure) return

  binding.sodium_free(buf.buffer)
}

exports.sodium_mprotect_noaccess = function (buf) {
  const res = binding.sodium_mprotect_noaccess(buf.buffer)

  if (res !== 0) throw new Error('failed to lock buffer')
}

exports.sodium_mprotect_readonly = function (buf) {
  const res = binding.sodium_mprotect_readonly(buf.buffer)

  if (res !== 0) throw new Error('failed to unlock buffer')
}

exports.sodium_mprotect_readwrite = function (buf) {
  const res = binding.sodium_mprotect_readwrite(buf.buffer)

  if (res !== 0) throw new Error('failed to unlock buffer')
}

// crypto_randombytes

exports.randombytes_buf = function (buffer) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')

  binding.randombytes_buf(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

exports.randombytes_buf_deterministic = function (buffer, seed) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    seed.byteLength === binding.randombytes_SEEDBYTES,
    "seed must be 'randombytes_SEEDBYTES' bytes"
  )

  binding.randombytes_buf_deterministic(
    buffer.buffer,
    buffer.byteOffset,
    buffer.byteLength,

    seed.buffer,
    seed.byteOffset,
    seed.byteLength
  )
}

// sodium_helpers

exports.sodium_memcmp = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  return binding.sodium_memcmp(a, b)
}

exports.sodium_add = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  binding.sodium_add(a, b)
}

exports.sodium_sub = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  binding.sodium_sub(a, b)
}

exports.sodium_compare = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  return binding.sodium_compare(a, b)
}

exports.sodium_is_zero = function (buffer, length) {
  if (length === undefined) length = buffer.byteLength

  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(length >= 0 && length <= buffer.byteLength, 'invalid length')

  return binding.sodium_is_zero(buffer, length)
}

exports.sodium_pad = function (buffer, unpaddedBuflen, blockSize) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(unpaddedBuflen <= buffer.byteLength, 'unpadded length cannot exceed buffer length')
  assert(blockSize <= buffer.byteLength, 'block size cannot exceed buffer length')
  assert(blockSize >= 1, 'block size must be at least 1 byte')
  assert(
    buffer.byteLength >= unpaddedBuflen + (blockSize - (unpaddedBuflen % blockSize)),
    'buf not long enough'
  )

  return binding.sodium_pad(buffer, unpaddedBuflen, blockSize)
}

exports.sodium_unpad = function (buffer, paddedBuflen, blockSize) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(paddedBuflen <= buffer.byteLength, 'unpadded length cannot exceed buffer length')
  assert(blockSize <= buffer.byteLength, 'block size cannot exceed buffer length')
  assert(blockSize >= 1, 'block size must be at least 1 byte')

  return binding.sodium_unpad(buffer, paddedBuflen, blockSize)
}

// crypto_sign

exports.crypto_sign_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )
  assert(
    seed.byteLength === binding.crypto_sign_SEEDBYTES,
    "seed must be 'crypto_sign_SEEDBYTES' bytes"
  )

  const res = binding.crypto_sign_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign = function (sm, m, sk) {
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sm.byteLength === binding.crypto_sign_BYTES + m.byteLength,
    "sm must be 'm.byteLength + crypto_sign_BYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign(sm, m, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_open = function (m, sm, pk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sm.byteLength >= binding.crypto_sign_BYTES,
    "sm must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    m.byteLength === sm.byteLength - binding.crypto_sign_BYTES,
    "m must be 'sm.byteLength - crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_open(m, sm, pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_open = function (m, sm, pk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sm.byteLength >= binding.crypto_sign_BYTES,
    "sm must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    m.byteLength === sm.byteLength - binding.crypto_sign_BYTES,
    "m must be 'sm.byteLength - crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  return binding.crypto_sign_open(m, sm, pk)
}

exports.crypto_sign_detached = function (sig, m, sk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(sig.byteLength === binding.crypto_sign_BYTES, "sig must be 'crypto_sign_BYTES' bytes")
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_detached(sig, m, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_verify_detached = function (sig, m, pk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sig.byteLength >= binding.crypto_sign_BYTES,
    "sig must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  return binding.crypto_sign_verify_detached(
    sig.buffer,
    sig.byteOffset,
    sig.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    pk.buffer,
    pk.byteOffset,
    pk.byteLength
  )
}

exports.crypto_sign_ed25519_sk_to_pk = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_sk_to_pk(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_ed25519_pk_to_curve25519 = function (x25519pk, ed25519pk) {
  assert(ArrayBuffer.isView(x25519pk), 'x25519pk must be a typed array')
  assert(ArrayBuffer.isView(ed25519pk), 'ed25519pk must be a typed array')
  assert(
    x25519pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "x25519pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    ed25519pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "ed25519pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_pk_to_curve25519(x25519pk, ed25519pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_ed25519_sk_to_curve25519 = function (x25519sk, ed25519sk) {
  assert(ArrayBuffer.isView(x25519sk), 'x25519sk must be a typed array')
  assert(ArrayBuffer.isView(ed25519sk), 'ed25519sk must be a typed array')
  assert(
    x25519sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "x25519sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const edLen = ed25519sk.byteLength

  assert(
    edLen === binding.crypto_sign_SECRETKEYBYTES || edLen === binding.crypto_box_SECRETKEYBYTES,
    "ed25519sk must be 'crypto_sign_SECRETKEYBYTES' or 'crypto_sign_SECRETKEYBYTES - crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_sk_to_curve25519(x25519sk, ed25519sk)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_box

exports.crypto_box_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    seed.byteLength === binding.crypto_box_SEEDBYTES,
    "seed must be 'crypto_box_SEEDBYTES' bytes"
  )

  const res = binding.crypto_box_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_easy = function (c, m, n, pk, sk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength === m.byteLength + exports.crypto_box_MACBYTES,
    "c must be 'm.byteLength + crypto_box_MACBYTES' bytes"
  )
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_easy(c, m, n, pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_detached = function (c, mac, m, n, pk, sk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(mac.byteLength === exports.crypto_box_MACBYTES, "mac must be 'crypto_box_MACBYTES' bytes")
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_detached(c, mac, m, n, pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_open_easy = function (m, c, n, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength >= exports.crypto_box_MACBYTES,
    "c must be at least 'crypto_box_MACBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - exports.crypto_box_MACBYTES,
    "m must be 'c.byteLength - crypto_box_MACBYTES' bytes"
  )
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_open_easy(m, c, n, pk, sk)
}

exports.crypto_box_open_detached = function (m, c, mac, n, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(mac.byteLength === exports.crypto_box_MACBYTES, "mac must be 'crypto_box_MACBYTES' bytes")
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_open_detached(m, c, mac, n, pk, sk)
}

exports.crypto_box_seal = function (c, m, pk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    c.byteLength === m.byteLength + exports.crypto_box_SEALBYTES,
    "c must be 'm.byteLength + crypto_box_SEALBYTES' bytes"
  )
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_box_seal(c, m, pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_seal_open = function (m, c, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength >= exports.crypto_box_SEALBYTES,
    "c must be at least 'crypto_box_SEALBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - exports.crypto_box_SEALBYTES,
    "m must be 'c.byteLength - crypto_box_SEALBYTES' bytes"
  )
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_seal_open(
    m.buffer,
    m.byteOffset,
    m.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    pk.buffer,
    pk.byteOffset,
    pk.byteLength,

    sk.buffer,
    sk.byteOffset,
    sk.byteLength
  )
}

// crypto_secretbox

exports.crypto_secretbox_easy = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_secretbox_MACBYTES,
    "c must be 'm.byteLength + crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretbox_easy(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretbox_open_easy = function (m, c, n, k) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    c.byteLength >= binding.crypto_secretbox_MACBYTES,
    "c must be at least 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - binding.crypto_secretbox_MACBYTES,
    "m must be 'c.byteLength - crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  return binding.crypto_secretbox_open_easy(m, c, n, k)
}

exports.crypto_secretbox_detached = function (c, mac, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    mac.byteLength === binding.crypto_secretbox_MACBYTES,
    "mac must be 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretbox_detached(c, mac, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretbox_open_detached = function (m, c, mac, n, k) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(
    mac.byteLength === binding.crypto_secretbox_MACBYTES,
    "mac must be 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  return binding.crypto_secretbox_open_detached(m, c, mac, n, k)
}

// crypto_generichash

exports.crypto_generichash = function (output, input, key) {
  if (!key) key = OPTIONAL

  assert(ArrayBuffer.isView(output), 'output must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    output.byteLength >= binding.crypto_generichash_BYTES_MIN &&
      output.byteLength <= binding.crypto_generichash_BYTES_MAX,
    'output must be between crypto_generichash_BYTES_MIN and crypto_generichash_BYTES_MAX bytes'
  )

  if (key !== OPTIONAL) {
    assert(ArrayBuffer.isView(key), 'key must be a typed array')
    assert(
      key.byteLength >= binding.crypto_generichash_KEYBYTES_MIN &&
        key.byteLength <= binding.crypto_generichash_KEYBYTES_MAX,
      'key must be between crypto_generichash_KEYBYTES_MIN and crypto_generichash_KEYBYTES_MAX bytes'
    )
  }

  const res = binding.crypto_generichash(
    output.buffer,
    output.byteOffset,
    output.byteLength,

    input.buffer,
    input.byteOffset,
    input.byteLength,

    key.buffer,
    key.byteOffset,
    key.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_batch = function (output, batch, key) {
  assert(ArrayBuffer.isView(output), 'output must be a typed array')

  if (isNode || batch.length < 4) {
    const res = binding.crypto_generichash_batch(output, batch, !!key, key || OPTIONAL)
    if (res !== 0) throw new Error('status: ' + res)
  } else {
    const state = Buffer.alloc(binding.crypto_generichash_STATEBYTES)

    exports.crypto_generichash_init(state, key, output.byteLength)

    for (const buf of batch) {
      exports.crypto_generichash_update(state, buf)
    }

    exports.crypto_generichash_final(state, output)
  }
}

exports.crypto_generichash_keygen = function (key) {
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(
    key.byteLength === binding.crypto_generichash_KEYBYTES,
    "key must be 'crypto_generichash_KEYBYTES' bytes"
  )

  const res = binding.crypto_generichash_keygen(key.buffer, key.byteOffset, key.byteLength)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_init = function (state, key, outputLength) {
  if (!key) key = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_init(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    key.buffer,
    key.byteOffset,
    key.byteLength,

    outputLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_update(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    input.buffer,
    input.byteOffset,
    input.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_final = function (state, output) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(output), 'output must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_final(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    output.buffer,
    output.byteOffset,
    output.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

// secretstream

exports.crypto_secretstream_xchacha20poly1305_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  binding.crypto_secretstream_xchacha20poly1305_keygen(k.buffer, k.byteOffset, k.byteLength)
}

exports.crypto_secretstream_xchacha20poly1305_init_push = function (state, header, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(header), 'header must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    header.byteLength === binding.crypto_secretstream_xchacha20poly1305_HEADERBYTES,
    "header must be 'crypto_secretstream_xchacha20poly1305_HEADERBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_init_push(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    header.buffer,
    header.byteOffset,
    header.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretstream_xchacha20poly1305_init_pull = function (state, header, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(header), 'header must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    header.byteLength === binding.crypto_secretstream_xchacha20poly1305_HEADERBYTES,
    "header must be 'crypto_secretstream_xchacha20poly1305_HEADERBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_init_pull(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    header.buffer,
    header.byteOffset,
    header.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretstream_xchacha20poly1305_push = function (state, c, m, ad, tag) {
  if (!ad) ad = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    c.byteLength === m.byteLength + binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "c must be 'm.byteLength + crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_push(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    ad.buffer,
    ad.byteOffset,
    ad.byteLength,

    tag
  )

  if (res < 0) throw new Error('push failed')

  return res
}

exports.crypto_secretstream_xchacha20poly1305_pull = function (state, m, tag, c, ad) {
  if (!ad) ad = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(tag), 'tag must be a typed array')
  assert(tag.byteLength === 1, 'tag must be 1 byte')

  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    c.byteLength >= binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "c must be at least 'crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "m must be 'c.byteLength - crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_pull(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    tag.buffer,
    tag.byteOffset,
    tag.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    ad.buffer,
    ad.byteOffset,
    ad.byteLength
  )

  if (res < 0) throw new Error('pull failed')

  return res
}

exports.crypto_secretstream_xchacha20poly1305_rekey = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )

  binding.crypto_secretstream_xchacha20poly1305_rekey(
    state.buffer,
    state.byteOffset,
    state.byteLength
  )
}

// crypto_stream

exports.crypto_stream = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xor(
    c.buffer,
    c.byteOffset,
    c.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    n.buffer,
    n.byteOffset,
    n.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_auth

exports.crypto_auth = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(out.byteLength === binding.crypto_auth_BYTES, "out must be 'crypto_auth_BYTES' bytes")
  assert(k.byteLength === binding.crypto_auth_KEYBYTES, "k must be 'crypto_auth_KEYBYTES' bytes")

  const res = binding.crypto_auth(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_auth_verify = function (h, input, k) {
  assert(ArrayBuffer.isView(h), 'h must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(h.byteLength === binding.crypto_auth_BYTES, "h must be 'crypto_auth_BYTES' bytes")
  assert(k.byteLength === binding.crypto_auth_KEYBYTES, "k must be 'crypto_auth_KEYBYTES' bytes")

  return binding.crypto_auth_verify(h, input, k)
}

// crypto_onetimeauth

exports.crypto_onetimeauth = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    out.byteLength === binding.crypto_onetimeauth_BYTES,
    "out must be 'crypto_onetimeauth_BYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_init = function (state, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_init(state, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )
  assert(
    out.byteLength === binding.crypto_onetimeauth_BYTES,
    "out must be 'crypto_onetimeauth_BYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_verify = function (h, input, k) {
  assert(ArrayBuffer.isView(h), 'h must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    h.byteLength === binding.crypto_onetimeauth_BYTES,
    "h must be 'crypto_onetimeauth_BYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  return binding.crypto_onetimeauth_verify(h, input, k)
}

// crypto_pwhash

exports.crypto_pwhash = function (out, passwd, salt, opslimit, memlimit, alg) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_BYTES_MIN,
    "out must be at least 'crypto_pwhash_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_BYTES_MAX,
    "out must be at most 'crypto_pwhash_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_SALTBYTES,
    "salt must be 'crypto_pwhash_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )
  assert(alg >= 1 && alg <= 2, 'alg must be either Argon2i 1.3 or Argon2id 1.3')

  const res = binding.crypto_pwhash(out, passwd, salt, opslimit, memlimit, alg)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_async = function (
  out,
  passwd,
  salt,
  opslimit,
  memlimit,
  alg,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_BYTES_MIN,
    "out must be at least 'crypto_pwhash_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_BYTES_MAX,
    "out must be at most 'crypto_pwhash_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_SALTBYTES,
    "salt must be 'crypto_pwhash_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )
  assert(alg >= 1 && alg <= 2, 'alg must be either Argon2i 1.3 or Argon2id 1.3')

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    opslimit,
    memlimit,
    alg,

    done
  )

  return promise
}

exports.crypto_pwhash_str = function (out, passwd, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_STRBYTES,
    "out must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(typeof opslimit === 'number', 'opslimit must be a number')
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(typeof memlimit === 'number', 'memlimit must be a number')
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_str(out, passwd, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_str_async = function (out, passwd, opslimit, memlimit, callback = undefined) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_STRBYTES,
    "out must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(typeof opslimit === 'number', 'opslimit must be a number')
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(typeof memlimit === 'number', 'memlimit must be a number')
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_str_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_str_verify = function (str, passwd) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )

  return binding.crypto_pwhash_str_verify(str, passwd)
}

exports.crypto_pwhash_str_verify_async = function (str, passwd, callback = undefined) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  const [done, promise] = checkStatus(callback, true)

  binding.crypto_pwhash_str_verify_async(
    str.buffer,
    str.byteOffset,
    str.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    done
  )

  return promise
}

exports.crypto_pwhash_str_needs_rehash = function (str, opslimit, memlimit) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  return binding.crypto_pwhash_str_needs_rehash(str, opslimit, memlimit)
}

exports.crypto_pwhash_scryptsalsa208sha256 = function (out, passwd, salt, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MIN,
    "out must be at least 'crypto_pwhash_scryptsalsa208sha256_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MAX,
    "out must be at most 'crypto_pwhash_scryptsalsa208sha256_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_SALTBYTES,
    "salt must be 'crypto_pwhash_scryptsalsa208sha256_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_scryptsalsa208sha256(out, passwd, salt, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_scryptsalsa208sha256_async = function (
  out,
  passwd,
  salt,
  opslimit,
  memlimit,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MIN,
    "out must be at least 'crypto_pwhash_scryptsalsa208sha256_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MAX,
    "out must be at most 'crypto_pwhash_scryptsalsa208sha256_BYTES_MAX' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    salt.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_SALTBYTES,
    "salt must be 'crypto_pwhash_scryptsalsa208sha256_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_scryptsalsa208sha256_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str_async = function (
  out,
  passwd,
  opslimit,
  memlimit,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "out must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_scryptsalsa208sha256_str_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str = function (out, passwd, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "out must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_scryptsalsa208sha256_str(out, passwd, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_scryptsalsa208sha256_str_verify_async = function (
  str,
  passwd,
  callback = undefined
) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  const [done, promise] = checkStatus(callback, true)

  binding.crypto_pwhash_scryptsalsa208sha256_str_verify_async(
    str.buffer,
    str.byteOffset,
    str.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str_verify = function (str, passwd) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  return binding.crypto_pwhash_scryptsalsa208sha256_str_verify(str, passwd)
}

exports.crypto_pwhash_scryptsalsa208sha256_str_needs_rehash = function (str, opslimit, memlimit) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  return binding.crypto_pwhash_scryptsalsa208sha256_str_needs_rehash(str, opslimit, memlimit)
}

// crypto_kx

exports.crypto_kx_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "pk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "sk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    pk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "pk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "sk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    seed.byteLength === binding.crypto_kx_SEEDBYTES,
    "seed must be 'crypto_kx_SEEDBYTES' bytes"
  )

  const res = binding.crypto_kx_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_client_session_keys = function (rx, tx, clientPk, clientSk, serverPk) {
  if (!rx) rx = undefined
  if (!tx) tx = undefined

  assert(rx || tx, 'at least one session key must be specified')

  if (rx) {
    assert(ArrayBuffer.isView(rx), 'rx must be a typed array')
    assert(
      rx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "rx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  if (tx) {
    assert(ArrayBuffer.isView(tx), 'tx must be a typed array')
    assert(
      tx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "tx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  assert(ArrayBuffer.isView(clientPk), 'clientPk must be a typed array')
  assert(ArrayBuffer.isView(clientSk), 'clientSk must be a typed array')
  assert(ArrayBuffer.isView(serverPk), 'serverPk must be a typed array')
  assert(
    clientPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "clientPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    clientSk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "clientSk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    serverPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "serverPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_client_session_keys(rx, tx, clientPk, clientSk, serverPk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_server_session_keys = function (rx, tx, serverPk, serverSk, clientPk) {
  if (!rx) rx = undefined
  if (!tx) tx = undefined

  assert(rx || tx, 'at least one session key must be specified')

  if (rx) {
    assert(ArrayBuffer.isView(rx), 'rx must be a typed array')
    assert(
      rx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "rx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  if (tx) {
    assert(ArrayBuffer.isView(tx), 'tx must be a typed array')
    assert(
      tx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "tx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  assert(ArrayBuffer.isView(serverPk), 'serverPk must be a typed array')
  assert(ArrayBuffer.isView(serverSk), 'serverSk must be a typed array')
  assert(ArrayBuffer.isView(clientPk), 'clientPk must be a typed array')
  assert(
    serverPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "serverPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    serverSk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "serverSk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    clientPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "clientPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_server_session_keys(rx, tx, serverPk, serverSk, clientPk)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_scalarmult

exports.crypto_scalarmult_base = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_BYTES,
    "q must be 'crypto_scalarmult_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_SCALARBYTES,
    "n must be 'crypto_scalarmult_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_base(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_BYTES,
    "q must be 'crypto_scalarmult_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_SCALARBYTES,
    "n must be 'crypto_scalarmult_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_BYTES,
    "p must be 'crypto_scalarmult_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_base = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_base(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519 = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "p must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_is_valid_point = function (p) {
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )

  return binding.crypto_core_ed25519_is_valid_point(p)
}

exports.crypto_core_ed25519_from_uniform = function (p, r) {
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_UNIFORMBYTES,
    "r must be 'crypto_core_ed25519_UNIFORMBYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_from_uniform(p, r)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_base_noclamp = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_base_noclamp(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_noclamp = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "p must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_noclamp(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_core

exports.crypto_core_ed25519_add = function (r, p, q) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_BYTES,
    "r must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_core_ed25519_BYTES,
    "q must be 'crypto_core_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_add(r, p, q)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_sub = function (r, p, q) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_BYTES,
    "r must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_core_ed25519_BYTES,
    "q must be 'crypto_core_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_sub(r, p, q)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_scalar_random = function (r) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "r must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_random(r)
}

exports.crypto_core_ed25519_scalar_reduce = function (r, s) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "r must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_NONREDUCEDSCALARBYTES,
    "s must be 'crypto_core_ed25519_NONREDUCEDSCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_reduce(r, s)
}

exports.crypto_core_ed25519_scalar_invert = function (recip, s) {
  assert(ArrayBuffer.isView(recip), 'recip must be a typed array')
  assert(
    recip.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "recip must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_invert(recip, s)
}

exports.crypto_core_ed25519_scalar_negate = function (neg, s) {
  assert(ArrayBuffer.isView(neg), 'neg must be a typed array')
  assert(
    neg.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "neg must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_negate(neg, s)
}

exports.crypto_core_ed25519_scalar_complement = function (comp, s) {
  assert(ArrayBuffer.isView(comp), 'comp must be a typed array')
  assert(
    comp.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "comp must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_complement(comp, s)
}

exports.crypto_core_ed25519_scalar_add = function (z, x, y) {
  assert(ArrayBuffer.isView(z), 'z must be a typed array')
  assert(
    z.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "z must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(x), 'x must be a typed array')
  assert(
    x.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "x must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(y), 'y must be a typed array')
  assert(
    y.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "y must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_add(z, x, y)
}

exports.crypto_core_ed25519_scalar_sub = function (z, x, y) {
  assert(ArrayBuffer.isView(z), 'z must be a typed array')
  assert(
    z.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "z must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(x), 'x must be a typed array')
  assert(
    x.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "x must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(y), 'y must be a typed array')
  assert(
    y.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "y must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_sub(z, x, y)
}

// crypto_shorthash

exports.crypto_shorthash = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_shorthash_BYTES,
    "out must be 'crypto_shorthash_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_shorthash_KEYBYTES,
    "k must be 'crypto_shorthash_KEYBYTES' bytes"
  )

  const res = binding.crypto_shorthash(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_kdf

exports.crypto_kdf_keygen = function (key) {
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(key.byteLength === binding.crypto_kdf_KEYBYTES, "key must be 'crypto_kdf_KEYBYTES' bytes")

  binding.crypto_kdf_keygen(key)
}

exports.crypto_kdf_derive_from_key = function (subkey, subkeyId, ctx, key) {
  assert(ArrayBuffer.isView(subkey), 'subkey must be a typed array')
  assert(
    subkey.byteLength >= binding.crypto_kdf_BYTES_MIN,
    "subkey must be at least 'crypto_kdf_BYTES_MIN' bytes"
  )
  assert(
    subkey.byteLength <= binding.crypto_kdf_BYTES_MAX,
    "subkey must be at most 'crypto_kdf_BYTES_MAX' bytes"
  )
  assert(ArrayBuffer.isView(ctx), 'ctx must be a typed array')
  assert(
    ctx.byteLength === binding.crypto_kdf_CONTEXTBYTES,
    "ctx must be 'crypto_kdf_CONTEXTBYTES' bytes"
  )
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(key.byteLength === binding.crypto_kdf_KEYBYTES, "key must be 'crypto_kdf_KEYBYTES' bytes")

  const res = binding.crypto_kdf_derive_from_key(subkey, subkeyId, ctx, key)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_hash

exports.crypto_hash = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(out.byteLength === binding.crypto_hash_BYTES, "out must be 'crypto_hash_BYTES' bytes")

  const res = binding.crypto_hash(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256 = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha256_BYTES,
    "out must be 'crypto_hash_sha256_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha256(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_init = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_init(state)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha256_BYTES,
    "out must be 'crypto_hash_sha256_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512 = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha512_BYTES,
    "out must be 'crypto_hash_sha512_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha512(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_init = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_init(state)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha512_BYTES,
    "out must be 'crypto_hash_sha512_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_aead

exports.crypto_aead_xchacha20poly1305_ietf_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  binding.crypto_aead_xchacha20poly1305_ietf_keygen(k)
}

exports.crypto_aead_xchacha20poly1305_ietf_encrypt = function (c, m, ad, nsec, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "c must be 'm.byteLength + crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(c.byteLength <= 0xffffffff, 'c.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_encrypt(c, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_decrypt = function (m, nsec, c, ad, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "m must be 'c.byteLength - crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(m.byteLength <= 0xffffffff, 'm.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_decrypt(m, c, ad, npub, k)

  if (res < 0) throw new Error('could not verify data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_encrypt_detached = function (
  c,
  mac,
  m,
  ad,
  nsec,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_encrypt_detached(c, mac, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_decrypt_detached = function (
  m,
  nsec,
  c,
  mac,
  ad,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_decrypt_detached(m, c, mac, ad, npub, k)

  if (res !== 0) throw new Error('could not verify data')
}

exports.crypto_aead_chacha20poly1305_ietf_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  binding.crypto_aead_chacha20poly1305_ietf_keygen(k)
}

exports.crypto_aead_chacha20poly1305_ietf_encrypt = function (c, m, ad, nsec, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "c must be 'm.byteLength + crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(c.byteLength <= 0xffffffff, 'c.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_encrypt(c, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_decrypt = function (m, nsec, c, ad, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "m must be 'c.byteLength - crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(m.byteLength <= 0xffffffff, 'm.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_decrypt(m, c, ad, npub, k)

  if (res < 0) throw new Error('could not verify data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_encrypt_detached = function (
  c,
  mac,
  m,
  ad,
  nsec,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_encrypt_detached(c, mac, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_decrypt_detached = function (
  m,
  nsec,
  c,
  mac,
  ad,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_decrypt_detached(m, c, mac, ad, npub, k)

  if (res !== 0) throw new Error('could not verify data')
}

// crypto_stream

exports.crypto_stream_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  binding.crypto_stream_xor_wrap_init(state, n, k)
}

exports.crypto_stream_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_xor_wrap_update(state, c, m)
}

exports.crypto_stream_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_xor_wrap_final(state)
}

exports.crypto_stream_chacha20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  binding.crypto_stream_chacha20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_chacha20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_chacha20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_chacha20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_chacha20_xor_wrap_final(state)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  binding.crypto_stream_chacha20_ietf_xor_wrap_init(state, n, k)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_chacha20_ietf_xor_wrap_update(state, c, m)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_chacha20_ietf_xor_wrap_final(state)
}

exports.crypto_stream_xchacha20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  binding.crypto_stream_xchacha20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_xchacha20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_xchacha20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_xchacha20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_xchacha20_xor_wrap_final(state)
}

exports.crypto_stream_salsa20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  binding.crypto_stream_salsa20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_salsa20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_salsa20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_salsa20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_salsa20_xor_wrap_final(state)
}

// experimental

exports.extension_tweak_ed25519_base = function (n, p, ns) {
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.extension_tweak_ed25519_BYTES,
    "p must be 'extension_tweak_ed25519_BYTES' bytes"
  )

  binding.extension_tweak_ed25519_base(n, p, ns)
}

exports.extension_tweak_ed25519_sign_detached = function (sig, m, scalar, pk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(sig.byteLength === binding.crypto_sign_BYTES, "sig must be 'crypto_sign_BYTES' bytes")
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  if (pk) {
    assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
    assert(
      pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
      "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
    )
  }

  const res = binding.extension_tweak_ed25519_sign_detached(sig, m, scalar, pk)

  if (res !== 0) throw new Error('failed to compute signature')
}

exports.extension_tweak_ed25519_sk_to_scalar = function (n, sk) {
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  binding.extension_tweak_ed25519_sk_to_scalar(n, sk)
}

exports.extension_tweak_ed25519_scalar = function (scalarOut, scalar, ns) {
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_scalar(scalarOut, scalar, ns)
}

exports.extension_tweak_ed25519_pk = function (tpk, pk, ns) {
  assert(ArrayBuffer.isView(tpk), 'tpk must be a typed array')
  assert(
    tpk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "tpk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_pk(tpk, pk, ns)

  if (res !== 0) throw new Error('failed to tweak public key')
}

exports.extension_tweak_ed25519_keypair = function (pk, scalarOut, scalarIn, ns) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.extension_tweak_ed25519_BYTES,
    "pk must be 'extension_tweak_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarIn), 'scalarIn must be a typed array')
  assert(
    scalarIn.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarIn must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_keypair(pk, scalarOut, scalarIn, ns)
}

exports.extension_tweak_ed25519_scalar_add = function (scalarOut, scalar, n) {
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_scalar_add(scalarOut, scalar, n)
}

exports.extension_tweak_ed25519_pk_add = function (tpk, pk, p) {
  assert(ArrayBuffer.isView(tpk), 'tpk must be a typed array')
  assert(
    tpk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "tpk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "p must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_pk_add(tpk, pk, p)

  if (res !== 0) throw new Error('failed to add tweak to public key')
}

exports.extension_tweak_ed25519_keypair_add = function (pk, scalarOut, scalarIn, tweak) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.extension_tweak_ed25519_BYTES,
    "pk must be 'extension_tweak_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarIn), 'scalarIn must be a typed array')
  assert(
    scalarIn.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarIn must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(tweak), 'tweak must be a typed array')
  assert(
    tweak.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "tweak must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_keypair_add(pk, scalarOut, scalarIn, tweak)

  if (res !== 0) throw new Error('failed to add tweak to keypair')
}

exports.extension_pbkdf2_sha512_async = function (out, passwd, salt, iter, outlen, callback) {
  assert(
    iter >= binding.extension_pbkdf2_sha512_ITERATIONS_MIN,
    "iter must be at least 'extension_pbkdf2_sha512_ITERATIONS_MIN'"
  )
  assert(
    outlen <= binding.extension_pbkdf2_sha512_BYTES_MAX,
    "outlen must be at most 'extension_pbkdf2_sha512_BYTES_MAX'"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(out.byteLength >= outlen, "out must be at least 'outlen' bytes")
  assert(out.byteLength > 0, 'out must not be empty')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(salt.byteLength > 0, 'salt must not be empty')

  const [done, promise] = checkStatus(callback)

  binding.extension_pbkdf2_sha512_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    iter,
    outlen,

    done
  )

  return promise
}

exports.extension_pbkdf2_sha512 = function (out, passwd, salt, iter, outlen) {
  assert(
    iter >= binding.extension_pbkdf2_sha512_ITERATIONS_MIN,
    "iter must be at least 'extension_pbkdf2_sha512_ITERATIONS_MIN'"
  )
  assert(
    outlen <= binding.extension_pbkdf2_sha512_BYTES_MAX,
    "outlen must be at most 'extension_pbkdf2_sha512_BYTES_MAX'"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(out.byteLength >= outlen, "out must be at least 'outlen' bytes")
  assert(out.byteLength > 0, 'out must not be empty')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(salt.byteLength > 0, 'salt must not be empty')

  const res = binding.extension_pbkdf2_sha512(out, passwd, salt, iter, outlen)

  if (res !== 0) throw new Error('failed to add tweak to public key')
}

function checkStatus(callback, booleanResult = false) {
  let done, promise

  if (typeof callback === 'function') {
    done = function (status) {
      if (booleanResult) callback(null, status === 0)
      else if (status === 0) callback(null)
      else callback(new Error('status: ' + status))
    }
  } else {
    promise = new Promise(function (resolve, reject) {
      done = function (status) {
        if (booleanResult) resolve(status === 0)
        else if (status === 0) resolve()
        else reject(new Error('status: ' + status))
      }
    })
  }

  return [done, promise]
}
{
  "name": "sodium-native",
  "version": "5.1.0",
  "description": "Low level bindings for libsodium",
  "main": "index.js",
  "files": [
    "index.js",
    "binding.cc",
    "binding.js",
    "extensions",
    "prebuilds",
    "CMakeLists.txt"
  ],
  "imports": {
    "assert": {
      "bare": "bare-assert",
      "node": "assert"
    }
  },
  "addon": true,
  "dependencies": {
    "bare-assert": "^1.2.0",
    "require-addon": "^1.1.0",
    "which-runtime": "^1.2.1"
  },
  "devDependencies": {
    "bare-compat-napi": "^1.3.5",
    "brittle": "^3.16.2",
    "cmake-bare": "^1.6.1",
    "cmake-fetch": "^1.4.3",
    "cmake-napi": "^1.2.1",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "test": "prettier . --check && npm run test:node && npm run test:bare",
    "test:node": "node test/all.js",
    "test:bare": "bare test/all.js"
  },
  "standard": {
    "ignore": [
      "/test/fixtures/*.js"
    ]
  },
  "engines": {
    "bare": ">=1.16.0"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sodium-native.git"
  },
  "contributors": [
    "Emil Bay <github@tixz.dk> (http://bayes.dk)",
    "Mathias Buus <mathiasbuus@gmail.com> (https://mafinto.sh)",
    "Christophe Diederichs <chm-diederichs@hyperdivision.dk>"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/sodium-native/issues"
  },
  "homepage": "https://github.com/holepunchto/sodium-native"
}
const sodium = require('sodium-universal')
const b4a = require('b4a')

const ABYTES = sodium.crypto_secretstream_xchacha20poly1305_ABYTES
const TAG_MESSAGE = sodium.crypto_secretstream_xchacha20poly1305_TAG_MESSAGE
const TAG_FINAL = sodium.crypto_secretstream_xchacha20poly1305_TAG_FINAL
const STATEBYTES = sodium.crypto_secretstream_xchacha20poly1305_STATEBYTES
const HEADERBYTES = sodium.crypto_secretstream_xchacha20poly1305_HEADERBYTES
const KEYBYTES = sodium.crypto_secretstream_xchacha20poly1305_KEYBYTES
const TAG_FINAL_BYTE = b4a.isBuffer(TAG_FINAL) ? TAG_FINAL[0] : TAG_FINAL

const EMPTY = b4a.alloc(0)
const TAG = b4a.alloc(1)

class Push {
  constructor (key, state = b4a.allocUnsafeSlow(STATEBYTES), header = b4a.allocUnsafeSlow(HEADERBYTES)) {
    if (!TAG_FINAL) throw new Error('JavaScript sodium version needs to support crypto_secretstream_xchacha20poly')

    this.key = key
    this.state = state
    this.header = header

    sodium.crypto_secretstream_xchacha20poly1305_init_push(this.state, this.header, this.key)
  }

  next (message, cipher = b4a.allocUnsafe(message.byteLength + ABYTES)) {
    sodium.crypto_secretstream_xchacha20poly1305_push(this.state, cipher, message, null, TAG_MESSAGE)
    return cipher
  }

  final (message = EMPTY, cipher = b4a.allocUnsafe(ABYTES)) {
    sodium.crypto_secretstream_xchacha20poly1305_push(this.state, cipher, message, null, TAG_FINAL)
    return cipher
  }
}

class Pull {
  constructor (key, state = b4a.allocUnsafeSlow(STATEBYTES)) {
    if (!TAG_FINAL) throw new Error('JavaScript sodium version needs to support crypto_secretstream_xchacha20poly')

    this.key = key
    this.state = state
    this.final = false
  }

  init (header) {
    sodium.crypto_secretstream_xchacha20poly1305_init_pull(this.state, header, this.key)
  }

  next (cipher, message = b4a.allocUnsafe(cipher.byteLength - ABYTES)) {
    sodium.crypto_secretstream_xchacha20poly1305_pull(this.state, message, TAG, cipher, null)
    this.final = TAG[0] === TAG_FINAL_BYTE
    return message
  }
}

function keygen (buf = b4a.alloc(KEYBYTES)) {
  sodium.crypto_secretstream_xchacha20poly1305_keygen(buf)
  return buf
}

module.exports = {
  keygen,
  KEYBYTES,
  ABYTES,
  STATEBYTES,
  HEADERBYTES,
  Push,
  Pull
}
{
  "name": "sodium-secretstream",
  "version": "1.2.0",
  "description": "Wraps libsodiums secretstream in a higher level abstraction",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.1.1",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "standard": "^17.0.0"
  },
  "scripts": {
    "test": "standard"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/sodium-secretstream.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/sodium-secretstream/issues"
  },
  "homepage": "https://github.com/mafintosh/sodium-secretstream"
}
module.exports = require('sodium-native')
{
  "name": "sodium-universal",
  "version": "5.0.1",
  "description": "Universal wrapper for sodium-javascript and sodium-native working in Node.js and the Browser",
  "main": "index.js",
  "dependencies": {
    "sodium-native": "^5.0.1"
  },
  "peerDependencies": {
    "sodium-javascript": "~0.8.0"
  },
  "peerDependenciesMeta": {
    "sodium-javascript": {
      "optional": true
    }
  },
  "scripts": {
    "prepublish": "./build-scripts/generate.js"
  },
  "browser": {
    "sodium-native": "sodium-javascript"
  },
  "browserify": {
    "transform": [
      "./build-scripts/transform.js"
    ]
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sodium-universal.git"
  },
  "keywords": [
    "libsodium",
    "sodium",
    "sodium-native",
    "sodium-javascript",
    "browserify"
  ],
  "contributors": [
    "Emil Bay <github@tixz.dk> (http://bayes.dk)",
    "Mathias Buus <mathiasbuus@gmail.com> (https://mafinto.sh)",
    "Christophe Diederichs <chm-diederichs@hyperdivision.dk>"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/sodium-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/sodium-universal#readme"
}
const { EventEmitter } = require('events-universal')
const STREAM_DESTROYED = new Error('Stream was destroyed')
const PREMATURE_CLOSE = new Error('Premature close')

const FIFO = require('fast-fifo')
const TextDecoder = require('text-decoder')

// if we do a future major, expect queue microtask to be there always, for now a bit defensive
const qmt =
  typeof queueMicrotask === 'undefined' ? (fn) => global.process.nextTick(fn) : queueMicrotask

// 29 bits used total (4 from shared, 14 from read, and 11 from write)
const MAX = (1 << 29) - 1

// Shared state
const OPENING = 0b0001
const PREDESTROYING = 0b0010
const DESTROYING = 0b0100
const DESTROYED = 0b1000

const NOT_OPENING = MAX ^ OPENING
const NOT_PREDESTROYING = MAX ^ PREDESTROYING

// Read state (4 bit offset from shared state)
const READ_ACTIVE = 0b00000000000001 << 4
const READ_UPDATING = 0b00000000000010 << 4
const READ_PRIMARY = 0b00000000000100 << 4
const READ_QUEUED = 0b00000000001000 << 4
const READ_RESUMED = 0b00000000010000 << 4
const READ_PIPE_DRAINED = 0b00000000100000 << 4
const READ_ENDING = 0b00000001000000 << 4
const READ_EMIT_DATA = 0b00000010000000 << 4
const READ_EMIT_READABLE = 0b00000100000000 << 4
const READ_EMITTED_READABLE = 0b00001000000000 << 4
const READ_DONE = 0b00010000000000 << 4
const READ_NEXT_TICK = 0b00100000000000 << 4
const READ_NEEDS_PUSH = 0b01000000000000 << 4
const READ_READ_AHEAD = 0b10000000000000 << 4

// Combined read state
const READ_FLOWING = READ_RESUMED | READ_PIPE_DRAINED
const READ_ACTIVE_AND_NEEDS_PUSH = READ_ACTIVE | READ_NEEDS_PUSH
const READ_PRIMARY_AND_ACTIVE = READ_PRIMARY | READ_ACTIVE
const READ_EMIT_READABLE_AND_QUEUED = READ_EMIT_READABLE | READ_QUEUED
const READ_RESUMED_READ_AHEAD = READ_RESUMED | READ_READ_AHEAD

const READ_NOT_ACTIVE = MAX ^ READ_ACTIVE
const READ_NON_PRIMARY = MAX ^ READ_PRIMARY
const READ_NON_PRIMARY_AND_PUSHED = MAX ^ (READ_PRIMARY | READ_NEEDS_PUSH)
const READ_PUSHED = MAX ^ READ_NEEDS_PUSH
const READ_PAUSED = MAX ^ READ_RESUMED
const READ_NOT_QUEUED = MAX ^ (READ_QUEUED | READ_EMITTED_READABLE)
const READ_NOT_ENDING = MAX ^ READ_ENDING
const READ_PIPE_NOT_DRAINED = MAX ^ READ_FLOWING
const READ_NOT_NEXT_TICK = MAX ^ READ_NEXT_TICK
const READ_NOT_UPDATING = MAX ^ READ_UPDATING
const READ_NO_READ_AHEAD = MAX ^ READ_READ_AHEAD
const READ_PAUSED_NO_READ_AHEAD = MAX ^ READ_RESUMED_READ_AHEAD

// Write state (18 bit offset, 4 bit offset from shared state and 14 from read state)
const WRITE_ACTIVE = 0b00000000001 << 18
const WRITE_UPDATING = 0b00000000010 << 18
const WRITE_PRIMARY = 0b00000000100 << 18
const WRITE_QUEUED = 0b00000001000 << 18
const WRITE_UNDRAINED = 0b00000010000 << 18
const WRITE_DONE = 0b00000100000 << 18
const WRITE_EMIT_DRAIN = 0b00001000000 << 18
const WRITE_NEXT_TICK = 0b00010000000 << 18
const WRITE_WRITING = 0b00100000000 << 18
const WRITE_FINISHING = 0b01000000000 << 18
const WRITE_CORKED = 0b10000000000 << 18

const WRITE_NOT_ACTIVE = MAX ^ (WRITE_ACTIVE | WRITE_WRITING)
const WRITE_NON_PRIMARY = MAX ^ WRITE_PRIMARY
const WRITE_NOT_FINISHING = MAX ^ (WRITE_ACTIVE | WRITE_FINISHING)
const WRITE_DRAINED = MAX ^ WRITE_UNDRAINED
const WRITE_NOT_QUEUED = MAX ^ WRITE_QUEUED
const WRITE_NOT_NEXT_TICK = MAX ^ WRITE_NEXT_TICK
const WRITE_NOT_UPDATING = MAX ^ WRITE_UPDATING
const WRITE_NOT_CORKED = MAX ^ WRITE_CORKED

// Combined shared state
const ACTIVE = READ_ACTIVE | WRITE_ACTIVE
const NOT_ACTIVE = MAX ^ ACTIVE
const DONE = READ_DONE | WRITE_DONE
const DESTROY_STATUS = DESTROYING | DESTROYED | PREDESTROYING
const OPEN_STATUS = DESTROY_STATUS | OPENING
const AUTO_DESTROY = DESTROY_STATUS | DONE
const NON_PRIMARY = WRITE_NON_PRIMARY & READ_NON_PRIMARY
const ACTIVE_OR_TICKING = WRITE_NEXT_TICK | READ_NEXT_TICK
const TICKING = ACTIVE_OR_TICKING & NOT_ACTIVE
const IS_OPENING = OPEN_STATUS | TICKING

// Combined shared state and read state
const READ_PRIMARY_STATUS = OPEN_STATUS | READ_ENDING | READ_DONE
const READ_STATUS = OPEN_STATUS | READ_DONE | READ_QUEUED
const READ_ENDING_STATUS = OPEN_STATUS | READ_ENDING | READ_QUEUED
const READ_READABLE_STATUS = OPEN_STATUS | READ_EMIT_READABLE | READ_QUEUED | READ_EMITTED_READABLE
const SHOULD_NOT_READ =
  OPEN_STATUS | READ_ACTIVE | READ_ENDING | READ_DONE | READ_NEEDS_PUSH | READ_READ_AHEAD
const READ_BACKPRESSURE_STATUS = DESTROY_STATUS | READ_ENDING | READ_DONE
const READ_UPDATE_SYNC_STATUS = READ_UPDATING | OPEN_STATUS | READ_NEXT_TICK | READ_PRIMARY
const READ_NEXT_TICK_OR_OPENING = READ_NEXT_TICK | OPENING

// Combined write state
const WRITE_PRIMARY_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_DONE
const WRITE_QUEUED_AND_UNDRAINED = WRITE_QUEUED | WRITE_UNDRAINED
const WRITE_QUEUED_AND_ACTIVE = WRITE_QUEUED | WRITE_ACTIVE
const WRITE_DRAIN_STATUS = WRITE_QUEUED | WRITE_UNDRAINED | OPEN_STATUS | WRITE_ACTIVE
const WRITE_STATUS = OPEN_STATUS | WRITE_ACTIVE | WRITE_QUEUED | WRITE_CORKED
const WRITE_PRIMARY_AND_ACTIVE = WRITE_PRIMARY | WRITE_ACTIVE
const WRITE_ACTIVE_AND_WRITING = WRITE_ACTIVE | WRITE_WRITING
const WRITE_FINISHING_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_QUEUED_AND_ACTIVE | WRITE_DONE
const WRITE_BACKPRESSURE_STATUS = WRITE_UNDRAINED | DESTROY_STATUS | WRITE_FINISHING | WRITE_DONE
const WRITE_UPDATE_SYNC_STATUS = WRITE_UPDATING | OPEN_STATUS | WRITE_NEXT_TICK | WRITE_PRIMARY
const WRITE_DROP_DATA = WRITE_FINISHING | WRITE_DONE | DESTROY_STATUS

const asyncIterator = Symbol.asyncIterator || Symbol('asyncIterator')

class WritableState {
  constructor(
    stream,
    { highWaterMark = 16384, map = null, mapWritable, byteLength, byteLengthWritable } = {}
  ) {
    this.stream = stream
    this.queue = new FIFO()
    this.highWaterMark = highWaterMark
    this.buffered = 0
    this.error = null
    this.pipeline = null
    this.drains = null // if we add more seldomly used helpers we might them into a subobject so its a single ptr
    this.byteLength = byteLengthWritable || byteLength || defaultByteLength
    this.map = mapWritable || map
    this.afterWrite = afterWrite.bind(this)
    this.afterUpdateNextTick = updateWriteNT.bind(this)
  }

  get ending() {
    return (this.stream._duplexState & WRITE_FINISHING) !== 0
  }

  get ended() {
    return (this.stream._duplexState & WRITE_DONE) !== 0
  }

  push(data) {
    if ((this.stream._duplexState & WRITE_DROP_DATA) !== 0) return false
    if (this.map !== null) data = this.map(data)

    this.buffered += this.byteLength(data)
    this.queue.push(data)

    if (this.buffered < this.highWaterMark) {
      this.stream._duplexState |= WRITE_QUEUED
      return true
    }

    this.stream._duplexState |= WRITE_QUEUED_AND_UNDRAINED
    return false
  }

  shift() {
    const data = this.queue.shift()

    this.buffered -= this.byteLength(data)
    if (this.buffered === 0) this.stream._duplexState &= WRITE_NOT_QUEUED

    return data
  }

  end(data) {
    if (typeof data === 'function') this.stream.once('finish', data)
    else if (data !== undefined && data !== null) this.push(data)
    this.stream._duplexState = (this.stream._duplexState | WRITE_FINISHING) & WRITE_NON_PRIMARY
  }

  autoBatch(data, cb) {
    const buffer = []
    const stream = this.stream

    buffer.push(data)
    while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED_AND_ACTIVE) {
      buffer.push(stream._writableState.shift())
    }

    if ((stream._duplexState & OPEN_STATUS) !== 0) return cb(null)
    stream._writev(buffer, cb)
  }

  update() {
    const stream = this.stream

    stream._duplexState |= WRITE_UPDATING

    do {
      while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED) {
        const data = this.shift()
        stream._duplexState |= WRITE_ACTIVE_AND_WRITING
        stream._write(data, this.afterWrite)
      }

      if ((stream._duplexState & WRITE_PRIMARY_AND_ACTIVE) === 0) this.updateNonPrimary()
    } while (this.continueUpdate() === true)

    stream._duplexState &= WRITE_NOT_UPDATING
  }

  updateNonPrimary() {
    const stream = this.stream

    if ((stream._duplexState & WRITE_FINISHING_STATUS) === WRITE_FINISHING) {
      stream._duplexState = stream._duplexState | WRITE_ACTIVE
      stream._final(afterFinal.bind(this))
      return
    }

    if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
      if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
        stream._duplexState |= ACTIVE
        stream._destroy(afterDestroy.bind(this))
      }
      return
    }

    if ((stream._duplexState & IS_OPENING) === OPENING) {
      stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING
      stream._open(afterOpen.bind(this))
    }
  }

  continueUpdate() {
    if ((this.stream._duplexState & WRITE_NEXT_TICK) === 0) return false
    this.stream._duplexState &= WRITE_NOT_NEXT_TICK
    return true
  }

  updateCallback() {
    if ((this.stream._duplexState & WRITE_UPDATE_SYNC_STATUS) === WRITE_PRIMARY) this.update()
    else this.updateNextTick()
  }

  updateNextTick() {
    if ((this.stream._duplexState & WRITE_NEXT_TICK) !== 0) return
    this.stream._duplexState |= WRITE_NEXT_TICK
    if ((this.stream._duplexState & WRITE_UPDATING) === 0) qmt(this.afterUpdateNextTick)
  }
}

class ReadableState {
  constructor(
    stream,
    { highWaterMark = 16384, map = null, mapReadable, byteLength, byteLengthReadable } = {}
  ) {
    this.stream = stream
    this.queue = new FIFO()
    this.highWaterMark = highWaterMark === 0 ? 1 : highWaterMark
    this.buffered = 0
    this.readAhead = highWaterMark > 0
    this.error = null
    this.pipeline = null
    this.byteLength = byteLengthReadable || byteLength || defaultByteLength
    this.map = mapReadable || map
    this.pipeTo = null
    this.afterRead = afterRead.bind(this)
    this.afterUpdateNextTick = updateReadNT.bind(this)
  }

  get ending() {
    return (this.stream._duplexState & READ_ENDING) !== 0
  }

  get ended() {
    return (this.stream._duplexState & READ_DONE) !== 0
  }

  pipe(pipeTo, cb) {
    if (this.pipeTo !== null) throw new Error('Can only pipe to one destination')
    if (typeof cb !== 'function') cb = null

    this.stream._duplexState |= READ_PIPE_DRAINED
    this.pipeTo = pipeTo
    this.pipeline = new Pipeline(this.stream, pipeTo, cb)

    if (cb) this.stream.on('error', noop) // We already error handle this so supress crashes

    if (isStreamx(pipeTo)) {
      pipeTo._writableState.pipeline = this.pipeline
      if (cb) pipeTo.on('error', noop) // We already error handle this so supress crashes
      pipeTo.on('finish', this.pipeline.finished.bind(this.pipeline)) // TODO: just call finished from pipeTo itself
    } else {
      const onerror = this.pipeline.done.bind(this.pipeline, pipeTo)
      const onclose = this.pipeline.done.bind(this.pipeline, pipeTo, null) // onclose has a weird bool arg
      pipeTo.on('error', onerror)
      pipeTo.on('close', onclose)
      pipeTo.on('finish', this.pipeline.finished.bind(this.pipeline))
    }

    pipeTo.on('drain', afterDrain.bind(this))
    this.stream.emit('piping', pipeTo)
    pipeTo.emit('pipe', this.stream)
  }

  push(data) {
    const stream = this.stream

    if (data === null) {
      this.highWaterMark = 0
      stream._duplexState = (stream._duplexState | READ_ENDING) & READ_NON_PRIMARY_AND_PUSHED
      return false
    }

    if (this.map !== null) {
      data = this.map(data)
      if (data === null) {
        stream._duplexState &= READ_PUSHED
        return this.buffered < this.highWaterMark
      }
    }

    this.buffered += this.byteLength(data)
    this.queue.push(data)

    stream._duplexState = (stream._duplexState | READ_QUEUED) & READ_PUSHED

    return this.buffered < this.highWaterMark
  }

  shift() {
    const data = this.queue.shift()

    this.buffered -= this.byteLength(data)
    if (this.buffered === 0) this.stream._duplexState &= READ_NOT_QUEUED
    return data
  }

  unshift(data) {
    const pending = [this.map !== null ? this.map(data) : data]
    while (this.buffered > 0) pending.push(this.shift())

    for (let i = 0; i < pending.length - 1; i++) {
      const data = pending[i]
      this.buffered += this.byteLength(data)
      this.queue.push(data)
    }

    this.push(pending[pending.length - 1])
  }

  read() {
    const stream = this.stream

    if ((stream._duplexState & READ_STATUS) === READ_QUEUED) {
      const data = this.shift()
      if (this.pipeTo !== null && this.pipeTo.write(data) === false)
        stream._duplexState &= READ_PIPE_NOT_DRAINED
      if ((stream._duplexState & READ_EMIT_DATA) !== 0) stream.emit('data', data)
      return data
    }

    if (this.readAhead === false) {
      stream._duplexState |= READ_READ_AHEAD
      this.updateNextTick()
    }

    return null
  }

  drain() {
    const stream = this.stream

    while (
      (stream._duplexState & READ_STATUS) === READ_QUEUED &&
      (stream._duplexState & READ_FLOWING) !== 0
    ) {
      const data = this.shift()
      if (this.pipeTo !== null && this.pipeTo.write(data) === false)
        stream._duplexState &= READ_PIPE_NOT_DRAINED
      if ((stream._duplexState & READ_EMIT_DATA) !== 0) stream.emit('data', data)
    }
  }

  update() {
    const stream = this.stream

    stream._duplexState |= READ_UPDATING

    do {
      this.drain()

      while (
        this.buffered < this.highWaterMark &&
        (stream._duplexState & SHOULD_NOT_READ) === READ_READ_AHEAD
      ) {
        stream._duplexState |= READ_ACTIVE_AND_NEEDS_PUSH
        stream._read(this.afterRead)
        this.drain()
      }

      if ((stream._duplexState & READ_READABLE_STATUS) === READ_EMIT_READABLE_AND_QUEUED) {
        stream._duplexState |= READ_EMITTED_READABLE
        stream.emit('readable')
      }

      if ((stream._duplexState & READ_PRIMARY_AND_ACTIVE) === 0) this.updateNonPrimary()
    } while (this.continueUpdate() === true)

    stream._duplexState &= READ_NOT_UPDATING
  }

  updateNonPrimary() {
    const stream = this.stream

    if ((stream._duplexState & READ_ENDING_STATUS) === READ_ENDING) {
      stream._duplexState = (stream._duplexState | READ_DONE) & READ_NOT_ENDING
      stream.emit('end')
      if ((stream._duplexState & AUTO_DESTROY) === DONE) stream._duplexState |= DESTROYING
      if (this.pipeTo !== null) this.pipeTo.end()
    }

    if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
      if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
        stream._duplexState |= ACTIVE
        stream._destroy(afterDestroy.bind(this))
      }
      return
    }

    if ((stream._duplexState & IS_OPENING) === OPENING) {
      stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING
      stream._open(afterOpen.bind(this))
    }
  }

  continueUpdate() {
    if ((this.stream._duplexState & READ_NEXT_TICK) === 0) return false
    this.stream._duplexState &= READ_NOT_NEXT_TICK
    return true
  }

  updateCallback() {
    if ((this.stream._duplexState & READ_UPDATE_SYNC_STATUS) === READ_PRIMARY) this.update()
    else this.updateNextTick()
  }

  updateNextTickIfOpen() {
    if ((this.stream._duplexState & READ_NEXT_TICK_OR_OPENING) !== 0) return
    this.stream._duplexState |= READ_NEXT_TICK
    if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick)
  }

  updateNextTick() {
    if ((this.stream._duplexState & READ_NEXT_TICK) !== 0) return
    this.stream._duplexState |= READ_NEXT_TICK
    if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick)
  }
}

class TransformState {
  constructor(stream) {
    this.data = null
    this.afterTransform = afterTransform.bind(stream)
    this.afterFinal = null
  }
}

class Pipeline {
  constructor(src, dst, cb) {
    this.from = src
    this.to = dst
    this.afterPipe = cb
    this.error = null
    this.pipeToFinished = false
  }

  finished() {
    this.pipeToFinished = true
  }

  done(stream, err) {
    if (err) this.error = err

    if (stream === this.to) {
      this.to = null

      if (this.from !== null) {
        if ((this.from._duplexState & READ_DONE) === 0 || !this.pipeToFinished) {
          this.from.destroy(this.error || new Error('Writable stream closed prematurely'))
        }
        return
      }
    }

    if (stream === this.from) {
      this.from = null

      if (this.to !== null) {
        if ((stream._duplexState & READ_DONE) === 0) {
          this.to.destroy(this.error || new Error('Readable stream closed before ending'))
        }
        return
      }
    }

    if (this.afterPipe !== null) this.afterPipe(this.error)
    this.to = this.from = this.afterPipe = null
  }
}

function afterDrain() {
  this.stream._duplexState |= READ_PIPE_DRAINED
  this.updateCallback()
}

function afterFinal(err) {
  const stream = this.stream
  if (err) stream.destroy(err)
  if ((stream._duplexState & DESTROY_STATUS) === 0) {
    stream._duplexState |= WRITE_DONE
    stream.emit('finish')
  }
  if ((stream._duplexState & AUTO_DESTROY) === DONE) {
    stream._duplexState |= DESTROYING
  }

  stream._duplexState &= WRITE_NOT_FINISHING

  // no need to wait the extra tick here, so we short circuit that
  if ((stream._duplexState & WRITE_UPDATING) === 0) this.update()
  else this.updateNextTick()
}

function afterDestroy(err) {
  const stream = this.stream

  if (!err && this.error !== STREAM_DESTROYED) err = this.error
  if (err) stream.emit('error', err)
  stream._duplexState |= DESTROYED
  stream.emit('close')

  const rs = stream._readableState
  const ws = stream._writableState

  if (rs !== null && rs.pipeline !== null) rs.pipeline.done(stream, err)

  if (ws !== null) {
    while (ws.drains !== null && ws.drains.length > 0) ws.drains.shift().resolve(false)
    if (ws.pipeline !== null) ws.pipeline.done(stream, err)
  }
}

function afterWrite(err) {
  const stream = this.stream

  if (err) stream.destroy(err)
  stream._duplexState &= WRITE_NOT_ACTIVE

  if (this.drains !== null) tickDrains(this.drains)

  if ((stream._duplexState & WRITE_DRAIN_STATUS) === WRITE_UNDRAINED) {
    stream._duplexState &= WRITE_DRAINED
    if ((stream._duplexState & WRITE_EMIT_DRAIN) === WRITE_EMIT_DRAIN) {
      stream.emit('drain')
    }
  }

  this.updateCallback()
}

function afterRead(err) {
  if (err) this.stream.destroy(err)
  this.stream._duplexState &= READ_NOT_ACTIVE
  if (this.readAhead === false && (this.stream._duplexState & READ_RESUMED) === 0)
    this.stream._duplexState &= READ_NO_READ_AHEAD
  this.updateCallback()
}

function updateReadNT() {
  if ((this.stream._duplexState & READ_UPDATING) === 0) {
    this.stream._duplexState &= READ_NOT_NEXT_TICK
    this.update()
  }
}

function updateWriteNT() {
  if ((this.stream._duplexState & WRITE_UPDATING) === 0) {
    this.stream._duplexState &= WRITE_NOT_NEXT_TICK
    this.update()
  }
}

function tickDrains(drains) {
  for (let i = 0; i < drains.length; i++) {
    // drains.writes are monotonic, so if one is 0 its always the first one
    if (--drains[i].writes === 0) {
      drains.shift().resolve(true)
      i--
    }
  }
}

function afterOpen(err) {
  const stream = this.stream

  if (err) stream.destroy(err)

  if ((stream._duplexState & DESTROYING) === 0) {
    if ((stream._duplexState & READ_PRIMARY_STATUS) === 0) stream._duplexState |= READ_PRIMARY
    if ((stream._duplexState & WRITE_PRIMARY_STATUS) === 0) stream._duplexState |= WRITE_PRIMARY
    stream.emit('open')
  }

  stream._duplexState &= NOT_ACTIVE

  if (stream._writableState !== null) {
    stream._writableState.updateCallback()
  }

  if (stream._readableState !== null) {
    stream._readableState.updateCallback()
  }
}

function afterTransform(err, data) {
  if (data !== undefined && data !== null) this.push(data)
  this._writableState.afterWrite(err)
}

function newListener(name) {
  if (this._readableState !== null) {
    if (name === 'data') {
      this._duplexState |= READ_EMIT_DATA | READ_RESUMED_READ_AHEAD
      this._readableState.updateNextTick()
    }
    if (name === 'readable') {
      this._duplexState |= READ_EMIT_READABLE
      this._readableState.updateNextTick()
    }
  }

  if (this._writableState !== null) {
    if (name === 'drain') {
      this._duplexState |= WRITE_EMIT_DRAIN
      this._writableState.updateNextTick()
    }
  }
}

class Stream extends EventEmitter {
  constructor(opts) {
    super()

    this._duplexState = 0
    this._readableState = null
    this._writableState = null

    if (opts) {
      if (opts.open) this._open = opts.open
      if (opts.destroy) this._destroy = opts.destroy
      if (opts.predestroy) this._predestroy = opts.predestroy
      if (opts.signal) {
        opts.signal.addEventListener('abort', abort.bind(this))
      }
    }

    this.on('newListener', newListener)
  }

  _open(cb) {
    cb(null)
  }

  _destroy(cb) {
    cb(null)
  }

  _predestroy() {
    // does nothing
  }

  get readable() {
    return this._readableState !== null ? true : undefined
  }

  get writable() {
    return this._writableState !== null ? true : undefined
  }

  get destroyed() {
    return (this._duplexState & DESTROYED) !== 0
  }

  get destroying() {
    return (this._duplexState & DESTROY_STATUS) !== 0
  }

  destroy(err) {
    if ((this._duplexState & DESTROY_STATUS) === 0) {
      if (!err) err = STREAM_DESTROYED
      this._duplexState = (this._duplexState | DESTROYING) & NON_PRIMARY

      if (this._readableState !== null) {
        this._readableState.highWaterMark = 0
        this._readableState.error = err
      }
      if (this._writableState !== null) {
        this._writableState.highWaterMark = 0
        this._writableState.error = err
      }

      this._duplexState |= PREDESTROYING
      this._predestroy()
      this._duplexState &= NOT_PREDESTROYING

      if (this._readableState !== null) this._readableState.updateNextTick()
      if (this._writableState !== null) this._writableState.updateNextTick()
    }
  }
}

class Readable extends Stream {
  constructor(opts) {
    super(opts)

    this._duplexState |= OPENING | WRITE_DONE | READ_READ_AHEAD
    this._readableState = new ReadableState(this, opts)

    if (opts) {
      if (this._readableState.readAhead === false) this._duplexState &= READ_NO_READ_AHEAD
      if (opts.read) this._read = opts.read
      if (opts.eagerOpen) this._readableState.updateNextTick()
      if (opts.encoding) this.setEncoding(opts.encoding)
    }
  }

  setEncoding(encoding) {
    const dec = new TextDecoder(encoding)
    const map = this._readableState.map || echo
    this._readableState.map = mapOrSkip
    return this

    function mapOrSkip(data) {
      const next = dec.push(data)
      return next === '' && (data.byteLength !== 0 || dec.remaining > 0) ? null : map(next)
    }
  }

  _read(cb) {
    cb(null)
  }

  pipe(dest, cb) {
    this._readableState.updateNextTick()
    this._readableState.pipe(dest, cb)
    return dest
  }

  read() {
    this._readableState.updateNextTick()
    return this._readableState.read()
  }

  push(data) {
    this._readableState.updateNextTickIfOpen()
    return this._readableState.push(data)
  }

  unshift(data) {
    this._readableState.updateNextTickIfOpen()
    return this._readableState.unshift(data)
  }

  resume() {
    this._duplexState |= READ_RESUMED_READ_AHEAD
    this._readableState.updateNextTick()
    return this
  }

  pause() {
    this._duplexState &=
      this._readableState.readAhead === false ? READ_PAUSED_NO_READ_AHEAD : READ_PAUSED
    return this
  }

  static _fromAsyncIterator(ite, opts) {
    let destroy

    const rs = new Readable({
      ...opts,
      read(cb) {
        ite.next().then(push).then(cb.bind(null, null)).catch(cb)
      },
      predestroy() {
        destroy = ite.return()
      },
      destroy(cb) {
        if (!destroy) return cb(null)
        destroy.then(cb.bind(null, null)).catch(cb)
      }
    })

    return rs

    function push(data) {
      if (data.done) rs.push(null)
      else rs.push(data.value)
    }
  }

  static from(data, opts) {
    if (isReadStreamx(data)) return data
    if (data[asyncIterator]) return this._fromAsyncIterator(data[asyncIterator](), opts)
    if (!Array.isArray(data)) data = data === undefined ? [] : [data]

    let i = 0
    return new Readable({
      ...opts,
      read(cb) {
        this.push(i === data.length ? null : data[i++])
        cb(null)
      }
    })
  }

  static isBackpressured(rs) {
    return (
      (rs._duplexState & READ_BACKPRESSURE_STATUS) !== 0 ||
      rs._readableState.buffered >= rs._readableState.highWaterMark
    )
  }

  static isPaused(rs) {
    return (rs._duplexState & READ_RESUMED) === 0
  }

  [asyncIterator]() {
    const stream = this

    let error = null
    let promiseResolve = null
    let promiseReject = null

    this.on('error', (err) => {
      error = err
    })
    this.on('readable', onreadable)
    this.on('close', onclose)

    return {
      [asyncIterator]() {
        return this
      },
      next() {
        return new Promise(function (resolve, reject) {
          promiseResolve = resolve
          promiseReject = reject
          const data = stream.read()
          if (data !== null) ondata(data)
          else if ((stream._duplexState & DESTROYED) !== 0) ondata(null)
        })
      },
      return() {
        return destroy(null)
      },
      throw(err) {
        return destroy(err)
      }
    }

    function onreadable() {
      if (promiseResolve !== null) ondata(stream.read())
    }

    function onclose() {
      if (promiseResolve !== null) ondata(null)
    }

    function ondata(data) {
      if (promiseReject === null) return
      if (error) promiseReject(error)
      else if (data === null && (stream._duplexState & READ_DONE) === 0)
        promiseReject(STREAM_DESTROYED)
      else promiseResolve({ value: data, done: data === null })
      promiseReject = promiseResolve = null
    }

    function destroy(err) {
      stream.destroy(err)
      return new Promise((resolve, reject) => {
        if (stream._duplexState & DESTROYED) return resolve({ value: undefined, done: true })
        stream.once('close', function () {
          if (err) reject(err)
          else resolve({ value: undefined, done: true })
        })
      })
    }
  }
}

class Writable extends Stream {
  constructor(opts) {
    super(opts)

    this._duplexState |= OPENING | READ_DONE
    this._writableState = new WritableState(this, opts)

    if (opts) {
      if (opts.writev) this._writev = opts.writev
      if (opts.write) this._write = opts.write
      if (opts.final) this._final = opts.final
      if (opts.eagerOpen) this._writableState.updateNextTick()
    }
  }

  cork() {
    this._duplexState |= WRITE_CORKED
  }

  uncork() {
    this._duplexState &= WRITE_NOT_CORKED
    this._writableState.updateNextTick()
  }

  _writev(batch, cb) {
    cb(null)
  }

  _write(data, cb) {
    this._writableState.autoBatch(data, cb)
  }

  _final(cb) {
    cb(null)
  }

  static isBackpressured(ws) {
    return (ws._duplexState & WRITE_BACKPRESSURE_STATUS) !== 0
  }

  static drained(ws) {
    if (ws.destroyed) return Promise.resolve(false)
    const state = ws._writableState
    const pending = isWritev(ws) ? Math.min(1, state.queue.length) : state.queue.length
    const writes = pending + (ws._duplexState & WRITE_WRITING ? 1 : 0)
    if (writes === 0) return Promise.resolve(true)
    if (state.drains === null) state.drains = []
    return new Promise((resolve) => {
      state.drains.push({ writes, resolve })
    })
  }

  write(data) {
    this._writableState.updateNextTick()
    return this._writableState.push(data)
  }

  end(data) {
    this._writableState.updateNextTick()
    this._writableState.end(data)
    return this
  }
}

class Duplex extends Readable {
  // and Writable
  constructor(opts) {
    super(opts)

    this._duplexState = OPENING | (this._duplexState & READ_READ_AHEAD)
    this._writableState = new WritableState(this, opts)

    if (opts) {
      if (opts.writev) this._writev = opts.writev
      if (opts.write) this._write = opts.write
      if (opts.final) this._final = opts.final
    }
  }

  cork() {
    this._duplexState |= WRITE_CORKED
  }

  uncork() {
    this._duplexState &= WRITE_NOT_CORKED
    this._writableState.updateNextTick()
  }

  _writev(batch, cb) {
    cb(null)
  }

  _write(data, cb) {
    this._writableState.autoBatch(data, cb)
  }

  _final(cb) {
    cb(null)
  }

  write(data) {
    this._writableState.updateNextTick()
    return this._writableState.push(data)
  }

  end(data) {
    this._writableState.updateNextTick()
    this._writableState.end(data)
    return this
  }
}

class Transform extends Duplex {
  constructor(opts) {
    super(opts)
    this._transformState = new TransformState(this)

    if (opts) {
      if (opts.transform) this._transform = opts.transform
      if (opts.flush) this._flush = opts.flush
    }
  }

  _write(data, cb) {
    if (this._readableState.buffered >= this._readableState.highWaterMark) {
      this._transformState.data = data
    } else {
      this._transform(data, this._transformState.afterTransform)
    }
  }

  _read(cb) {
    if (this._transformState.data !== null) {
      const data = this._transformState.data
      this._transformState.data = null
      cb(null)
      this._transform(data, this._transformState.afterTransform)
    } else {
      cb(null)
    }
  }

  destroy(err) {
    super.destroy(err)
    if (this._transformState.data !== null) {
      this._transformState.data = null
      this._transformState.afterTransform()
    }
  }

  _transform(data, cb) {
    cb(null, data)
  }

  _flush(cb) {
    cb(null)
  }

  _final(cb) {
    this._transformState.afterFinal = cb
    this._flush(transformAfterFlush.bind(this))
  }
}

class PassThrough extends Transform {}

function transformAfterFlush(err, data) {
  const cb = this._transformState.afterFinal
  if (err) return cb(err)
  if (data !== null && data !== undefined) this.push(data)
  this.push(null)
  cb(null)
}

function pipelinePromise(...streams) {
  return new Promise((resolve, reject) => {
    return pipeline(...streams, (err) => {
      if (err) return reject(err)
      resolve()
    })
  })
}

function pipeline(stream, ...streams) {
  const all = Array.isArray(stream) ? [...stream, ...streams] : [stream, ...streams]
  const done = all.length && typeof all[all.length - 1] === 'function' ? all.pop() : null

  if (all.length < 2) throw new Error('Pipeline requires at least 2 streams')

  let src = all[0]
  let dest = null
  let error = null

  for (let i = 1; i < all.length; i++) {
    dest = all[i]

    if (isStreamx(src)) {
      src.pipe(dest, onerror)
    } else {
      errorHandle(src, true, i > 1, onerror)
      src.pipe(dest)
    }

    src = dest
  }

  if (done) {
    let fin = false

    const autoDestroy =
      isStreamx(dest) || !!(dest._writableState && dest._writableState.autoDestroy)

    dest.on('error', (err) => {
      if (error === null) error = err
    })

    dest.on('finish', () => {
      fin = true
      if (!autoDestroy) done(error)
    })

    if (autoDestroy) {
      dest.on('close', () => done(error || (fin ? null : PREMATURE_CLOSE)))
    }
  }

  return dest

  function errorHandle(s, rd, wr, onerror) {
    s.on('error', onerror)
    s.on('close', onclose)

    function onclose() {
      if (rd && s._readableState && !s._readableState.ended) return onerror(PREMATURE_CLOSE)
      if (wr && s._writableState && !s._writableState.ended) return onerror(PREMATURE_CLOSE)
    }
  }

  function onerror(err) {
    if (!err || error) return
    error = err

    for (const s of all) {
      s.destroy(err)
    }
  }
}

function echo(s) {
  return s
}

function isStream(stream) {
  return !!stream._readableState || !!stream._writableState
}

function isStreamx(stream) {
  return typeof stream._duplexState === 'number' && isStream(stream)
}

function isEnding(stream) {
  return !!stream._readableState && stream._readableState.ending
}

function isEnded(stream) {
  return !!stream._readableState && stream._readableState.ended
}

function isFinishing(stream) {
  return !!stream._writableState && stream._writableState.ending
}

function isFinished(stream) {
  return !!stream._writableState && stream._writableState.ended
}

function getStreamError(stream, opts = {}) {
  const err =
    (stream._readableState && stream._readableState.error) ||
    (stream._writableState && stream._writableState.error)

  // avoid implicit errors by default
  return !opts.all && err === STREAM_DESTROYED ? null : err
}

function isReadStreamx(stream) {
  return isStreamx(stream) && stream.readable
}

function isDisturbed(stream) {
  return (
    (stream._duplexState & OPENING) !== OPENING ||
    (stream._duplexState & DESTROYING) === DESTROYING ||
    (stream._duplexState & ACTIVE_OR_TICKING) !== 0
  )
}

function isTypedArray(data) {
  return typeof data === 'object' && data !== null && typeof data.byteLength === 'number'
}

function defaultByteLength(data) {
  return isTypedArray(data) ? data.byteLength : 1024
}

function noop() {}

function abort() {
  this.destroy(new Error('Stream aborted.'))
}

function isWritev(s) {
  return s._writev !== Writable.prototype._writev && s._writev !== Duplex.prototype._writev
}

module.exports = {
  pipeline,
  pipelinePromise,
  isStream,
  isStreamx,
  isEnding,
  isEnded,
  isFinishing,
  isFinished,
  isDisturbed,
  getStreamError,
  Stream,
  Writable,
  Readable,
  Duplex,
  Transform,
  // Export PassThrough for compatibility with Node.js core's stream module
  PassThrough
}
{
  "name": "streamx",
  "version": "2.25.0",
  "description": "An iteration of the Node.js core streams with a series of improvements",
  "main": "index.js",
  "dependencies": {
    "events-universal": "^1.0.0",
    "fast-fifo": "^1.3.2",
    "text-decoder": "^1.1.0"
  },
  "devDependencies": {
    "b4a": "^1.6.6",
    "brittle": "^3.1.1",
    "end-of-stream": "^1.4.4",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "files": [
    "index.js"
  ],
  "scripts": {
    "format": "prettier --write .",
    "test": "prettier --check . && node test/all.js",
    "test:bare": "bare test/all.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/streamx.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/streamx/issues"
  },
  "homepage": "https://github.com/mafintosh/streamx"
}
const { Readable } = require('streamx')

module.exports = function (s, forks = 2) {
  const streams = new Array(forks)
  const status = new Array(forks).fill(true)

  let ended = false

  for (let i = 0; i < forks; i++) {
    streams[i] = new Readable({
      read (cb) {
        const check = !status[i]
        status[i] = true
        if (check && allReadable()) s.resume()
        cb(null)
      }
    })
  }

  s.on('end', function () {
    ended = true
    for (const stream of streams) stream.push(null)
  })

  s.on('error', function (err) {
    for (const stream of streams) stream.destroy(err)
  })

  s.on('close', function () {
    if (ended) return
    for (const stream of streams) stream.destroy()
  })

  s.on('data', function (data) {
    let needsPause = false
    for (let i = 0; i < streams.length; i++) {
      if (!(status[i] = streams[i].push(data))) {
        needsPause = true
      }
    }
    if (needsPause) s.pause()
  })

  return streams

  function allReadable () {
    for (let j = 0; j < status.length; j++) {
      if (!status[j]) return false
    }
    return true
  }
}
{
  "name": "teex",
  "version": "1.0.1",
  "description": "Turn a readable stream into multiple readable streamx streams",
  "main": "index.js",
  "dependencies": {
    "streamx": "^2.12.5"
  },
  "devDependencies": {
    "standard": "^14.3.4",
    "tape": "^5.0.1"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/teex.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/teex/issues"
  },
  "homepage": "https://github.com/mafintosh/teex"
}
const PassThroughDecoder = require('./lib/pass-through-decoder')
const UTF8Decoder = require('./lib/utf8-decoder')

module.exports = class TextDecoder {
  constructor(encoding = 'utf8') {
    this.encoding = normalizeEncoding(encoding)

    switch (this.encoding) {
      case 'utf8':
        this.decoder = new UTF8Decoder()
        break
      case 'utf16le':
      case 'base64':
        throw new Error('Unsupported encoding: ' + this.encoding)
      default:
        this.decoder = new PassThroughDecoder(this.encoding)
    }
  }

  get remaining() {
    return this.decoder.remaining
  }

  push(data) {
    if (typeof data === 'string') return data
    return this.decoder.decode(data)
  }

  // For Node.js compatibility
  write(data) {
    return this.push(data)
  }

  end(data) {
    let result = ''
    if (data) result = this.push(data)
    result += this.decoder.flush()
    return result
  }
}

function normalizeEncoding(encoding) {
  encoding = encoding.toLowerCase()

  switch (encoding) {
    case 'utf8':
    case 'utf-8':
      return 'utf8'
    case 'ucs2':
    case 'ucs-2':
    case 'utf16le':
    case 'utf-16le':
      return 'utf16le'
    case 'latin1':
    case 'binary':
      return 'latin1'
    case 'base64':
    case 'ascii':
    case 'hex':
      return encoding
    default:
      throw new Error('Unknown encoding: ' + encoding)
  }
}
const b4a = require('b4a')

module.exports = class PassThroughDecoder {
  constructor(encoding) {
    this.encoding = encoding
  }

  get remaining() {
    return 0
  }

  decode(data) {
    return b4a.toString(data, this.encoding)
  }

  flush() {
    return ''
  }
}
const b4a = require('b4a')

/**
 * https://encoding.spec.whatwg.org/#utf-8-decoder
 */
module.exports = class UTF8Decoder {
  constructor() {
    this._reset()
  }

  get remaining() {
    return this.bytesSeen
  }

  decode(data) {
    if (data.byteLength === 0) return ''

    if (this.bytesNeeded === 0 && trailingIncomplete(data, 0) === 0) {
      this.bytesSeen = trailingBytesSeen(data)
      return b4a.toString(data, 'utf8')
    }

    let result = ''
    let start = 0

    if (this.bytesNeeded > 0) {
      while (start < data.byteLength) {
        const byte = data[start]

        if (byte < this.lowerBoundary || byte > this.upperBoundary) {
          result += '\ufffd'
          this._reset()
          break
        }

        this.lowerBoundary = 0x80
        this.upperBoundary = 0xbf
        this.codePoint = (this.codePoint << 6) | (byte & 0x3f)
        this.bytesSeen++
        start++

        if (this.bytesSeen === this.bytesNeeded) {
          result += String.fromCodePoint(this.codePoint)
          this._reset()
          break
        }
      }

      if (this.bytesNeeded > 0) return result
    }

    const trailing = trailingIncomplete(data, start)
    const end = data.byteLength - trailing

    if (end > start) result += b4a.toString(data, 'utf8', start, end)

    for (let i = end; i < data.byteLength; i++) {
      const byte = data[i]

      if (this.bytesNeeded === 0) {
        if (byte <= 0x7f) {
          this.bytesSeen = 0
          result += String.fromCharCode(byte)
        } else if (byte >= 0xc2 && byte <= 0xdf) {
          this.bytesNeeded = 2
          this.bytesSeen = 1
          this.codePoint = byte & 0x1f
        } else if (byte >= 0xe0 && byte <= 0xef) {
          if (byte === 0xe0) this.lowerBoundary = 0xa0
          else if (byte === 0xed) this.upperBoundary = 0x9f
          this.bytesNeeded = 3
          this.bytesSeen = 1
          this.codePoint = byte & 0xf
        } else if (byte >= 0xf0 && byte <= 0xf4) {
          if (byte === 0xf0) this.lowerBoundary = 0x90
          else if (byte === 0xf4) this.upperBoundary = 0x8f
          this.bytesNeeded = 4
          this.bytesSeen = 1
          this.codePoint = byte & 0x7
        } else {
          this.bytesSeen = 1
          result += '\ufffd'
        }

        continue
      }

      if (byte < this.lowerBoundary || byte > this.upperBoundary) {
        result += '\ufffd'
        i--
        this._reset()

        continue
      }

      this.lowerBoundary = 0x80
      this.upperBoundary = 0xbf

      this.codePoint = (this.codePoint << 6) | (byte & 0x3f)
      this.bytesSeen++

      if (this.bytesSeen === this.bytesNeeded) {
        result += String.fromCodePoint(this.codePoint)
        this._reset()
      }
    }

    return result
  }

  flush() {
    const result = this.bytesNeeded > 0 ? '\ufffd' : ''
    this._reset()
    return result
  }

  _reset() {
    this.codePoint = 0
    this.bytesNeeded = 0
    this.bytesSeen = 0
    this.lowerBoundary = 0x80
    this.upperBoundary = 0xbf
  }
}

function trailingIncomplete(data, start) {
  const len = data.byteLength
  if (len <= start) return 0

  const limit = Math.max(start, len - 4)

  let i = len - 1
  while (i > limit && (data[i] & 0xc0) === 0x80) i--

  if (i < start) return 0

  const byte = data[i]

  let needed
  if (byte <= 0x7f) return 0
  if (byte >= 0xc2 && byte <= 0xdf) needed = 2
  else if (byte >= 0xe0 && byte <= 0xef) needed = 3
  else if (byte >= 0xf0 && byte <= 0xf4) needed = 4
  else return 0

  const available = len - i
  return available < needed ? available : 0
}

function trailingBytesSeen(data) {
  const len = data.byteLength
  if (len === 0) return 0

  const last = data[len - 1]

  if (last <= 0x7f) return 0
  if ((last & 0xc0) !== 0x80) return 1

  const limit = Math.max(0, len - 4)

  let i = len - 2
  while (i >= limit && (data[i] & 0xc0) === 0x80) i--

  if (i < 0) return 1

  const first = data[i]

  let needed
  if (first >= 0xc2 && first <= 0xdf) needed = 2
  else if (first >= 0xe0 && first <= 0xef) needed = 3
  else if (first >= 0xf0 && first <= 0xf4) needed = 4
  else return 1

  if (len - i !== needed) return 1

  if (needed >= 3) {
    const second = data[i + 1]
    if (first === 0xe0 && second < 0xa0) return 1
    if (first === 0xed && second > 0x9f) return 1
    if (first === 0xf0 && second < 0x90) return 1
    if (first === 0xf4 && second > 0x8f) return 1
  }

  return 0
}
{
  "name": "text-decoder",
  "version": "1.2.7",
  "description": "Streaming text decoder that preserves multibyte Unicode characters",
  "exports": {
    "./package": "./package.json",
    ".": "./index.js"
  },
  "files": [
    "index.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/text-decoder.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/text-decoder/issues"
  },
  "homepage": "https://github.com/holepunchto/text-decoder#readme",
  "dependencies": {
    "b4a": "^1.6.4"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  }
}
module.exports = class TimeOrderedSet {
  constructor () {
    this.oldest = null
    this.latest = null
    this.length = 0
  }

  has (node) {
    return !!(node.next || node.prev) || node === this.oldest
  }

  add (node) {
    if (this.has(node)) this.remove(node)

    if (!this.latest && !this.oldest) {
      this.latest = this.oldest = node
      node.prev = node.next = null
    } else {
      this.latest.next = node
      node.prev = this.latest
      node.next = null
      this.latest = node
    }

    this.length++

    return node
  }

  remove (node) {
    if (!this.has(node)) return node

    if (this.oldest !== node && this.latest !== node) {
      node.prev.next = node.next
      node.next.prev = node.prev
    } else {
      if (this.oldest === node) {
        this.oldest = node.next
        if (this.oldest) this.oldest.prev = null
      }
      if (this.latest === node) {
        this.latest = node.prev
        if (this.latest) this.latest.next = null
      }
    }

    node.next = node.prev = null
    this.length--

    return node
  }

  toArray ({ limit = Infinity, reverse = false } = {}) {
    const list = []

    if (reverse) {
      let node = this.latest
      while (node && limit--) {
        list.push(node)
        node = node.prev
      }
    } else {
      let node = this.oldest
      while (node && limit--) {
        list.push(node)
        node = node.next
      }
    }

    return list
  }
}
{
  "name": "time-ordered-set",
  "version": "2.0.1",
  "description": "Efficiently maintain a set of nodes ordered by the time they were added to the set",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "devDependencies": {
    "brittle": "^3.0.0",
    "standard": "^17.1.2"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/time-ordered-set.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/time-ordered-set/issues"
  },
  "homepage": "https://github.com/mafintosh/time-ordered-set"
}
module.exports = class TimerBrowser {
  constructor (ms, fn, ctx = null, interval = false) {
    this.ms = ms
    this.ontimeout = fn
    this.context = ctx || null
    this.interval = interval
    this.done = false

    this._timer = interval
      ? setInterval(callInterval, ms, this)
      : setTimeout(callTimeout, ms, this)
  }

  unref () {}

  ref () {}

  refresh () {
    if (this.done) return

    if (this.interval) {
      clearInterval(this._timer)
      this._timer = setInterval(callInterval, this.ms, this)
    } else {
      clearTimeout(this._timer)
      this._timer = setTimeout(callTimeout, this.ms, this)
    }
  }

  destroy () {
    this.done = true
    this.ontimeout = null

    if (this.interval) clearInterval(this._timer)
    else clearTimeout(this._timer)
  }

  static once (ms, fn, ctx) {
    return new this(ms, fn, ctx, false)
  }

  static on (ms, fn, ctx) {
    return new this(ms, fn, ctx, true)
  }
}

function callTimeout (self) {
  self.done = true
  self.ontimeout.call(self.context)
}

function callInterval (self) {
  self.ontimeout.call(self.context)
}
module.exports = isNode()
  ? require('./node')
  : require('./browser')

function isNode () {
  const to = setTimeout(function () {}, 1000)
  clearTimeout(to)
  return !!to.refresh
}
module.exports = class Timer {
  constructor (ms, fn, ctx = null, interval = false) {
    this.ms = ms
    this.ontimeout = fn
    this.context = ctx
    this.interval = interval
    this.done = false

    this._timer = interval
      ? setInterval(callInterval, ms, this)
      : setTimeout(callTimeout, ms, this)
  }

  unref () {
    this._timer.unref()
  }

  ref () {
    this._timer.ref()
  }

  refresh () {
    if (this.done !== true) this._timer.refresh()
  }

  destroy () {
    this.done = true
    this.ontimeout = null
    if (this.interval) clearInterval(this._timer)
    else clearTimeout(this._timer)
  }

  static once (ms, fn, ctx) {
    return new this(ms, fn, ctx, false)
  }

  static on (ms, fn, ctx) {
    return new this(ms, fn, ctx, true)
  }
}

function callTimeout (self) {
  self.done = true
  self.ontimeout.call(self.context)
}

function callInterval (self) {
  self.ontimeout.call(self.context)
}
{
  "name": "timeout-refresh",
  "version": "2.0.1",
  "description": "Efficiently refresh a timer",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^16.0.4",
    "tape": "^5.5.2"
  },
  "browser": "./browser.js",
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/timeout-refresh.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/timeout-refresh/issues"
  },
  "homepage": "https://github.com/mafintosh/timeout-refresh"
}
require.addon = require('require-addon')

module.exports = require.addon('.', __filename)
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

const v4Seg = '(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])'
const v4Str = `(${v4Seg}[.]){3}${v4Seg}`
const IPv4Pattern = new RegExp(`^${v4Str}$`)

const v6Seg = '(?:[0-9a-fA-F]{1,4})'
const IPv6Pattern = new RegExp(
  '^(' +
    `(?:${v6Seg}:){7}(?:${v6Seg}|:)|` +
    `(?:${v6Seg}:){6}(?:${v4Str}|:${v6Seg}|:)|` +
    `(?:${v6Seg}:){5}(?::${v4Str}|(:${v6Seg}){1,2}|:)|` +
    `(?:${v6Seg}:){4}(?:(:${v6Seg}){0,1}:${v4Str}|(:${v6Seg}){1,3}|:)|` +
    `(?:${v6Seg}:){3}(?:(:${v6Seg}){0,2}:${v4Str}|(:${v6Seg}){1,4}|:)|` +
    `(?:${v6Seg}:){2}(?:(:${v6Seg}){0,3}:${v4Str}|(:${v6Seg}){1,5}|:)|` +
    `(?:${v6Seg}:){1}(?:(:${v6Seg}){0,4}:${v4Str}|(:${v6Seg}){1,6}|:)|` +
    `(?::((?::${v6Seg}){0,5}:${v4Str}|(?::${v6Seg}){1,7}|:))` +
    ')(%[0-9a-zA-Z-.:]{1,})?$'
)

const isIPv4 = (exports.isIPv4 = function isIPv4(host) {
  return IPv4Pattern.test(host)
})

const isIPv6 = (exports.isIPv6 = function isIPv6(host) {
  return IPv6Pattern.test(host)
})

exports.isIP = function isIP(host) {
  if (isIPv4(host)) return 4
  if (isIPv6(host)) return 6
  return 0
}
const events = require('events')
const b4a = require('b4a')
const binding = require('../binding')

module.exports = class NetworkInterfaces extends events.EventEmitter {
  constructor(udx) {
    super()

    this._handle = b4a.alloc(binding.sizeof_udx_napi_interface_event_t)
    this._watching = false
    this._destroying = null

    binding.udx_napi_interface_event_init(
      udx._handle,
      this._handle,
      this,
      this._onevent,
      this._onclose
    )

    this.interfaces = binding.udx_napi_interface_event_get_addrs(this._handle)
  }

  _onclose() {
    this.emit('close')
  }

  _onevent() {
    this.interfaces = binding.udx_napi_interface_event_get_addrs(this._handle)

    this.emit('change', this.interfaces)
  }

  watch() {
    if (this._watching) return this
    this._watching = true

    binding.udx_napi_interface_event_start(this._handle)

    return this
  }

  unwatch() {
    if (!this._watching) return this
    this._watching = false

    binding.udx_napi_interface_event_stop(this._handle)

    return this
  }

  async destroy() {
    if (this._destroying) return this._destroying
    this._destroying = events.once(this, 'close')

    binding.udx_napi_interface_event_close(this._handle)

    return this._destroying
  }

  [Symbol.iterator]() {
    return this.interfaces[Symbol.iterator]()
  }
}
const events = require('events')
const b4a = require('b4a')
const binding = require('../binding')
const ip = require('./ip')

module.exports = class UDXSocket extends events.EventEmitter {
  constructor(udx, opts = {}) {
    super()

    this.udx = udx

    this._handle = b4a.alloc(binding.sizeof_udx_napi_socket_t)
    this._inited = false
    this._host = null
    this._family = 0
    this._ipv6Only = opts.ipv6Only === true
    this._reuseAddress = opts.reuseAddress === true
    this._port = 0
    this._reqs = []
    this._free = []
    this._closing = null
    this._closed = false

    this._view64 = new BigUint64Array(
      this._handle.buffer,
      this._handle.byteOffset,
      this._handle.byteLength >> 3
    )

    this.streams = new Set()

    this.userData = null
  }

  get bound() {
    return this._port !== 0
  }

  get closing() {
    return this._closing !== null
  }

  get idle() {
    return this.streams.size === 0
  }

  get busy() {
    return this.streams.size > 0
  }

  get bytesTransmitted() {
    if (this._inited !== true) return 0
    return Number(this._view64[binding.offsetof_udx_socket_t_bytes_tx >> 3])
  }

  get packetsTransmitted() {
    if (this._inited !== true) return 0
    return Number(this._view64[binding.offsetof_udx_socket_t_packets_tx >> 3])
  }

  get bytesReceived() {
    if (this._inited !== true) return 0
    return Number(this._view64[binding.offsetof_udx_socket_t_bytes_rx >> 3])
  }

  get packetsReceived() {
    if (this._inited !== true) return 0
    return Number(this._view64[binding.offsetof_udx_socket_t_packets_rx >> 3])
  }

  get packetsDroppedByKernel() {
    if (this._inited !== true) return 0
    return Number(this._view64[binding.offsetof_udx_socket_t_packets_dropped_by_kernel >> 3])
  }

  toJSON() {
    return {
      bound: this.bound,
      closing: this.closing,
      streams: this.streams.size,
      address: this.address(),
      ipv6Only: this._ipv6Only,
      reuseAddress: this._reuseAddress,
      idle: this.idle,
      busy: this.busy
    }
  }

  _init() {
    if (this._inited) return

    binding.udx_napi_socket_init(
      this.udx._handle,
      this._handle,
      this,
      this._onsend,
      this._onmessage,
      this._onclose,
      this._reallocMessage
    )

    this._inited = true
  }

  _onsend(id, err) {
    const req = this._reqs[id]

    const onflush = req.onflush

    req.buffer = null
    req.onflush = null

    this._free.push(id)

    onflush(err >= 0)

    // gc the free list
    if (this._free.length >= 16 && this._free.length === this._reqs.length) {
      this._free = []
      this._reqs = []
    }
  }

  _onmessage(len, port, host, family) {
    this.emit('message', this.udx._consumeMessage(len), { host, family, port })
    return this.udx._buffer
  }

  _onclose() {
    this.emit('close')
  }

  _reallocMessage() {
    return this.udx._reallocMessage()
  }

  _onidle() {
    this.emit('idle')
  }

  _onbusy() {
    this.emit('busy')
  }

  _addStream(stream) {
    if (this.streams.has(stream)) return false
    this.streams.add(stream)
    if (this.streams.size === 1) this._onbusy()
    return true
  }

  _removeStream(stream) {
    if (!this.streams.has(stream)) return false
    this.streams.delete(stream)
    const closed = this._closeMaybe()
    if (this.idle && !closed) this._onidle()
    return true
  }

  address() {
    if (!this.bound) return null
    return { host: this._host, family: this._family, port: this._port }
  }

  bind(port, host) {
    if (this.bound) throw new Error('Already bound')
    if (this.closing) throw new Error('Socket is closed')

    if (!port) port = 0

    let flags = 0
    if (this._ipv6Only) flags |= binding.UV_UDP_IPV6ONLY
    if (this._reuseAddress) flags |= binding.UV_UDP_REUSEADDR

    let family

    if (host) {
      family = ip.isIP(host)
      if (!family) throw new Error(`${host} is not a valid IP address`)

      if (!this._inited) this._init()

      this._port = binding.udx_napi_socket_bind(this._handle, port, host, family, flags)
    } else {
      if (!this._inited) this._init()

      try {
        host = '::'
        family = 6
        this._port = binding.udx_napi_socket_bind(this._handle, port, host, family, flags)
      } catch {
        host = '0.0.0.0'
        family = 4
        this._port = binding.udx_napi_socket_bind(this._handle, port, host, family, flags)
      }
    }

    this._host = host
    this._family = family

    this.emit('listening')
  }

  async close() {
    if (this._closing) return this._closing
    this._closing = new Promise((resolve) => this.once('close', resolve))
    this._closeMaybe()
    return this._closing
  }

  _closeMaybe() {
    if (this._closed || this._closing === null) return this._closed

    if (!this._inited) {
      this._closed = true
      this.emit('close')
      return true
    }

    if (this.idle) {
      binding.udx_napi_socket_close(this._handle)
      this._closed = true
    }

    return this._closed
  }

  setTTL(ttl) {
    if (!this._inited) throw new Error('Socket not active')
    binding.udx_napi_socket_set_ttl(this._handle, ttl)
  }

  getRecvBufferSize() {
    if (!this._inited) throw new Error('Socket not active')
    return binding.udx_napi_socket_get_recv_buffer_size(this._handle)
  }

  setRecvBufferSize(size) {
    if (!this._inited) throw new Error('Socket not active')
    return binding.udx_napi_socket_set_recv_buffer_size(this._handle, size)
  }

  getSendBufferSize() {
    if (!this._inited) throw new Error('Socket not active')
    return binding.udx_napi_socket_get_send_buffer_size(this._handle)
  }

  setSendBufferSize(size) {
    if (!this._inited) throw new Error('Socket not active')
    return binding.udx_napi_socket_set_send_buffer_size(this._handle, size)
  }

  addMembership(group, ifaceAddress) {
    if (!this._inited) throw new Error('Socket not active')
    return binding.udx_napi_socket_set_membership(this._handle, group, ifaceAddress || '', true)
  }

  dropMembership(group, ifaceAddress) {
    if (!this._inited) throw new Error('Socket not active')
    return binding.udx_napi_socket_set_membership(this._handle, group, ifaceAddress || '', false)
  }

  async send(buffer, port, host, ttl) {
    if (this.closing) return false

    if (!host) host = '127.0.0.1'

    const family = ip.isIP(host)
    if (!family) throw new Error(`${host} is not a valid IP address`)

    if (!this.bound) this.bind(0)

    const id = this._allocSend()
    const req = this._reqs[id]

    req.buffer = buffer

    const promise = new Promise((resolve) => {
      req.onflush = resolve
    })

    binding.udx_napi_socket_send_ttl(
      this._handle,
      req.handle,
      id,
      buffer,
      port,
      host,
      family,
      ttl || 0
    )

    return promise
  }

  trySend(buffer, port, host, ttl) {
    if (this.closing) return

    if (!host) host = '127.0.0.1'

    const family = ip.isIP(host)
    if (!family) throw new Error(`${host} is not a valid IP address`)

    if (!this.bound) this.bind(0)

    const id = this._allocSend()
    const req = this._reqs[id]

    req.buffer = buffer
    req.onflush = noop

    binding.udx_napi_socket_send_ttl(
      this._handle,
      req.handle,
      id,
      buffer,
      port,
      host,
      family,
      ttl || 0
    )
  }

  _allocSend() {
    if (this._free.length > 0) return this._free.pop()
    const handle = b4a.allocUnsafe(binding.sizeof_udx_socket_send_t)
    return this._reqs.push({ handle, buffer: null, onflush: null }) - 1
  }
}

function noop() {}
const streamx = require('streamx')
const b4a = require('b4a')
const binding = require('../binding')
const ip = require('./ip')

const MAX_PACKET = 2048
const BUFFER_SIZE = 65536 + MAX_PACKET

module.exports = class UDXStream extends streamx.Duplex {
  constructor(udx, id, opts = {}) {
    super({ mapWritable: toBuffer, eagerOpen: true })

    this.udx = udx
    this.socket = null

    this._handle = b4a.alloc(binding.sizeof_udx_napi_stream_t)
    this._view = new Uint32Array(
      this._handle.buffer,
      this._handle.byteOffset,
      this._handle.byteLength >> 2
    )
    this._view16 = new Uint16Array(
      this._handle.buffer,
      this._handle.byteOffset,
      this._handle.byteLength >> 1
    )
    this._view64 = new BigUint64Array(
      this._handle.buffer,
      this._handle.byteOffset,
      this._handle.byteLength >> 3
    )

    this._wreqs = []
    this._wfree = []

    this._sreqs = []
    this._sfree = []
    this._closed = false

    this._flushing = 0
    this._flushes = []

    this._buffer = null
    this._reallocData()

    this._onwrite = null
    this._ondestroy = null
    this._firewall = opts.firewall || firewallAll

    this._remoteChanging = null
    this._previousSocket = null

    this.id = id
    this.remoteId = 0
    this.remoteHost = null
    this.remoteFamily = 0
    this.remotePort = 0

    this.userData = null

    binding.udx_napi_stream_init(
      this.udx._handle,
      this._handle,
      id,
      opts.framed ? 1 : 0,
      this,
      this._ondata,
      this._onend,
      this._ondrain,
      this._onack,
      this._onsend,
      this._onmessage,
      this._onclose,
      this._onfirewall,
      this._onremotechanged,
      this._reallocData,
      this._reallocMessage
    )

    if (opts.seq) binding.udx_napi_stream_set_seq(this._handle, opts.seq)

    binding.udx_napi_stream_recv_start(this._handle, this._buffer)
  }

  get connected() {
    return this.socket !== null
  }

  get mtu() {
    return this._view16[binding.offsetof_udx_stream_t_mtu >> 1]
  }

  get rtt() {
    return this._view[binding.offsetof_udx_stream_t_srtt >> 2]
  }

  get cwnd() {
    return this._view[binding.offsetof_udx_stream_t_cwnd >> 2]
  }

  get rtoCount() {
    return this._view16[binding.offsetof_udx_stream_t_rto_count >> 1]
  }

  get retransmits() {
    return this._view16[binding.offsetof_udx_stream_t_retransmit_count >> 1]
  }

  get fastRecoveries() {
    return this._view16[binding.offsetof_udx_stream_t_fast_recovery_count >> 1]
  }

  get inflight() {
    return this._view[binding.offsetof_udx_stream_t_inflight >> 2]
  }

  get bytesTransmitted() {
    return Number(this._view64[binding.offsetof_udx_stream_t_bytes_tx >> 3])
  }

  get packetsTransmitted() {
    return Number(this._view64[binding.offsetof_udx_stream_t_packets_tx >> 3])
  }

  get bytesReceived() {
    return Number(this._view64[binding.offsetof_udx_stream_t_bytes_rx >> 3])
  }

  get packetsReceived() {
    return Number(this._view64[binding.offsetof_udx_stream_t_packets_rx >> 3])
  }

  get localHost() {
    return this.socket ? this.socket.address().host : null
  }

  get localFamily() {
    return this.socket ? this.socket.address().family : 0
  }

  get localPort() {
    return this.socket ? this.socket.address().port : 0
  }

  setInteractive(bool) {
    if (!this._closed) return
    binding.udx_napi_stream_set_mode(this._handle, bool ? 0 : 1)
  }

  connect(socket, remoteId, port, host, opts = {}) {
    if (this._closed) return

    if (this.connected) throw new Error('Already connected')
    if (socket.closing) throw new Error('Socket is closed')

    if (typeof host === 'object') {
      opts = host
      host = null
    }

    if (!host) host = '127.0.0.1'

    const family = ip.isIP(host)
    if (!family) throw new Error(`${host} is not a valid IP address`)
    if (!(port > 0 && port < 65536)) throw new Error(`${port} is not a valid port`)

    if (!socket.bound) socket.bind(0)

    this.remoteId = remoteId
    this.remotePort = port
    this.remoteHost = host
    this.remoteFamily = family
    this.socket = socket

    if (opts.ack) binding.udx_napi_stream_set_ack(this._handle, opts.ack)

    binding.udx_napi_stream_connect(this._handle, socket._handle, remoteId, port, host, family)

    this.socket._addStream(this)

    this.emit('connect')
  }

  changeRemote(socket, remoteId, port, host) {
    if (this._remoteChanging) throw new Error('Remote already changing')

    if (!this.connected) throw new Error('Not yet connected')
    if (socket.closing) throw new Error('Socket is closed')

    if (this.socket.udx !== socket.udx) {
      throw new Error('Cannot change to a socket on another UDX instance')
    }

    if (!host) host = '127.0.0.1'

    const family = ip.isIP(host)
    if (!family) throw new Error(`${host} is not a valid IP address`)
    if (!(port > 0 && port < 65536)) throw new Error(`${port} is not a valid port`)

    if (this.socket !== socket) this._previousSocket = this.socket

    this.remoteId = remoteId
    this.remotePort = port
    this.remoteHost = host
    this.remoteFamily = family
    this.socket = socket

    this._remoteChanging = new Promise((resolve, reject) => {
      const onchanged = () => {
        this.off('close', onclose)
        resolve()
      }

      const onclose = () => {
        this.off('remote-changed', onchanged)
        reject(new Error('Stream is closed'))
      }

      this.once('remote-changed', onchanged).once('close', onclose)
    })

    binding.udx_napi_stream_change_remote(
      this._handle,
      socket._handle,
      remoteId,
      port,
      host,
      family
    )

    this.socket._addStream(this)

    return this._remoteChanging
  }

  relayTo(destination) {
    if (this._closed) return

    binding.udx_napi_stream_relay_to(this._handle, destination._handle)
  }

  async send(buffer) {
    if (!this.connected || this._closed) return false

    const id = this._allocSend()
    const req = this._sreqs[id]

    req.buffer = buffer

    const promise = new Promise((resolve) => {
      req.onflush = resolve
    })

    binding.udx_napi_stream_send(this._handle, req.handle, id, buffer)

    return promise
  }

  trySend(buffer) {
    if (!this.connected || this._closed) return

    const id = this._allocSend()
    const req = this._sreqs[id]

    req.buffer = buffer
    req.onflush = noop

    binding.udx_napi_stream_send(this._handle, req.handle, id, buffer)
  }

  async flush() {
    if ((await streamx.Writable.drained(this)) === false) return false
    if (this.destroying) return false

    const missing = this._wreqs.length - this._wfree.length
    if (missing === 0) return true

    return new Promise((resolve) => {
      this._flushes.push({ flush: this._flushing++, missing, resolve })
    })
  }

  toJSON() {
    return {
      id: this.id,
      connected: this.connected,
      destroying: this.destroying,
      destroyed: this.destroyed,
      remoteId: this.remoteId,
      remoteHost: this.remoteHost,
      remoteFamily: this.remoteFamily,
      remotePort: this.remotePort,
      mtu: this.mtu,
      rtt: this.rtt,
      cwnd: this.cwnd,
      inflight: this.inflight,
      socket: this.socket ? this.socket.toJSON() : null
    }
  }

  _read(cb) {
    cb(null)
  }

  _writeContinue(err) {
    if (this._onwrite === null) return
    const cb = this._onwrite
    this._onwrite = null
    cb(err)
  }

  _destroyContinue(err) {
    if (this._ondestroy === null) return
    const cb = this._ondestroy
    this._ondestroy = null
    cb(err)
  }

  _writev(buffers, cb) {
    if (!this.connected)
      throw customError('Writing while not connected not currently supported', 'ERR_ASSERTION')

    let drained = true

    if (buffers.length === 1) {
      const id = this._allocWrite(1)
      const req = this._wreqs[id]

      req.flush = this._flushing
      req.buffer = buffers[0]

      drained = binding.udx_napi_stream_write(this._handle, req.handle, id, req.buffer) !== 0
    } else {
      const id = this._allocWrite(nextBatchSize(buffers.length))
      const req = this._wreqs[id]

      req.flush = this._flushing
      req.buffers = buffers

      drained = binding.udx_napi_stream_writev(this._handle, req.handle, id, req.buffers) !== 0
    }

    if (drained) cb(null)
    else this._onwrite = cb
  }

  _final(cb) {
    const id = this._allocWrite(1)
    const req = this._wreqs[id]

    req.flush = this._flushes
    req.buffer = b4a.allocUnsafe(0)

    const drained =
      binding.udx_napi_stream_write_end(this._handle, req.handle, id, req.buffer) !== 0

    if (drained) cb(null)
    else this._onwrite = cb
  }

  _predestroy() {
    if (!this._closed) binding.udx_napi_stream_destroy(this._handle)
    this._closed = true
    this._writeContinue(null)
  }

  _destroy(cb) {
    if (this.connected) this._ondestroy = cb
    else cb(null)
  }

  _ondata(read) {
    this.push(this._consumeData(read))
    return this._buffer
  }

  _onend(read) {
    if (read > 0) this.push(this._consumeData(read))
    this.push(null)
  }

  _ondrain() {
    this._writeContinue(null)
  }

  _flushAck(flush) {
    for (let i = this._flushes.length - 1; i >= 0; i--) {
      const f = this._flushes[i]
      if (f.flush < flush) break
      f.missing--
    }

    while (this._flushes.length > 0 && this._flushes[0].missing === 0) {
      this._flushes.shift().resolve(true)
    }
  }

  _onack(id) {
    const req = this._wreqs[id]

    req.buffers = req.buffer = null
    this._wfree.push(id)

    if (this._flushes.length > 0) this._flushAck(req.flush)

    // gc the free list
    if (this._wfree.length >= 64 && this._wfree.length === this._wreqs.length) {
      this._wfree = []
      this._wreqs = []
    }
  }

  _onsend(id, err) {
    const req = this._sreqs[id]

    const onflush = req.onflush

    req.buffer = null
    req.onflush = null

    this._sfree.push(id)

    onflush(err >= 0)

    // gc the free list
    if (this._sfree.length >= 16 && this._sfree.length === this._sreqs.length) {
      this._sfree = []
      this._sreqs = []
    }
  }

  _onmessage(len) {
    this.emit('message', this.udx._consumeMessage(len))
    return this.udx._buffer
  }

  _onclose(err) {
    this._closed = true

    if (this.socket) {
      this.socket._removeStream(this)
      this.socket = null
    }

    if (this._previousSocket) {
      this._previousSocket._removeStream(this)
      this._previousSocket = null
    }

    // no error, we don't need to do anything
    if (!err) return this._destroyContinue(null)

    if (this._ondestroy === null) this.destroy(err)
    else this._destroyContinue(err)
  }

  _onfirewall(socket, port, host, family) {
    return this._firewall(socket, port, host, family) ? 1 : 0
  }

  _onremotechanged() {
    if (this._previousSocket) {
      this._previousSocket._removeStream(this)
      this._previousSocket = null
    }

    this._remoteChanging = null
    this.emit('remote-changed')
  }

  _consumeData(len) {
    const next = this._buffer.subarray(0, len)
    this._buffer = this._buffer.subarray(len)
    if (this._buffer.byteLength < MAX_PACKET) this._reallocData()
    return next
  }

  _reallocData() {
    this._buffer = b4a.allocUnsafe(BUFFER_SIZE)
    return this._buffer
  }

  _reallocMessage() {
    return this.udx._reallocMessage()
  }

  _allocWrite(size) {
    if (this._wfree.length === 0) {
      const handle = b4a.allocUnsafe(binding.udx_napi_stream_write_sizeof(size))
      return (
        this._wreqs.push({
          handle,
          size,
          buffers: null,
          buffer: null,
          flush: 0
        }) - 1
      )
    }

    const free = this._wfree.pop()
    if (size === 1) return free

    const next = this._wreqs[free]
    if (next.size < size) {
      next.handle = b4a.allocUnsafe(binding.udx_napi_stream_write_sizeof(size))
      next.size = size
    }

    return free
  }

  _allocSend() {
    if (this._sfree.length > 0) return this._sfree.pop()
    const handle = b4a.allocUnsafe(binding.sizeof_udx_stream_send_t)
    return this._sreqs.push({ handle, buffer: null, resolve: null, reject: null }) - 1
  }
}

function noop() {}

function toBuffer(data) {
  return typeof data === 'string' ? b4a.from(data) : data
}

function firewallAll(socket, port, host) {
  return true
}

function customError(message, code) {
  const error = new Error(message)
  error.code = code
  return error
}

function nextBatchSize(n) {
  // try to coerce the the writevs into sameish size
  if (n === 1) return 1
  // group all < 8 to the same size, low mem overhead but save some small allocs
  if (n < 8) return 8
  if (n < 16) return 16
  if (n < 32) return 32
  if (n < 64) return 64
  return n
}
const b4a = require('b4a')
const binding = require('../binding')
const ip = require('./ip')
const Socket = require('./socket')
const Stream = require('./stream')
const NetworkInterfaces = require('./network-interfaces')

const MAX_MESSAGE = 4096
const BUFFER_SIZE = 65536 + MAX_MESSAGE

module.exports = class UDX {
  constructor() {
    this._handle = b4a.alloc(binding.sizeof_udx_napi_t)
    this._watchers = new Set()
    this._view64 = new BigUint64Array(
      this._handle.buffer,
      this._handle.byteOffset,
      this._handle.byteLength >> 3
    )

    this._buffer = null
    this._reallocMessage()

    binding.udx_napi_init(this._handle, this._buffer)
  }

  static isIPv4(host) {
    return ip.isIPv4(host)
  }

  static isIPv6(host) {
    return ip.isIPv6(host)
  }

  static isIP(host) {
    return ip.isIP(host)
  }

  get bytesTransmitted() {
    return Number(this._view64[binding.offsetof_udx_t_bytes_tx >> 3])
  }

  get packetsTransmitted() {
    return Number(this._view64[binding.offsetof_udx_t_packets_tx >> 3])
  }

  get bytesReceived() {
    return Number(this._view64[binding.offsetof_udx_t_bytes_rx >> 3])
  }

  get packetsReceived() {
    return Number(this._view64[binding.offsetof_udx_t_packets_rx >> 3])
  }

  get packetsDroppedByKernel() {
    return Number(this._view64[binding.offsetof_udx_t_packets_dropped_by_kernel >> 3])
  }

  _consumeMessage(len) {
    const next = this._buffer.subarray(0, len)
    this._buffer = this._buffer.subarray(len)
    if (this._buffer.byteLength < MAX_MESSAGE) this._reallocMessage()
    return next
  }

  _reallocMessage() {
    // TODO: move reallocation to native
    this._buffer = b4a.allocUnsafe(BUFFER_SIZE)
    return this._buffer
  }

  createSocket(opts) {
    return new Socket(this, opts)
  }

  createStream(id, opts) {
    return new Stream(this, id, opts)
  }

  networkInterfaces() {
    let [watcher = null] = this._watchers
    if (watcher) return watcher.interfaces

    watcher = new NetworkInterfaces(this)
    watcher.destroy()

    return watcher.interfaces
  }

  watchNetworkInterfaces(onchange) {
    const watcher = new NetworkInterfaces(this)

    this._watchers.add(watcher)
    watcher.on('close', () => {
      this._watchers.delete(watcher)
    })

    if (onchange) watcher.on('change', onchange)

    return watcher.watch()
  }

  async lookup(host, opts = {}) {
    const { family = 0 } = opts

    const req = b4a.alloc(binding.sizeof_udx_napi_lookup_t)
    const ctx = {
      req,
      resolve: null,
      reject: null
    }

    const promise = new Promise((resolve, reject) => {
      ctx.resolve = resolve
      ctx.reject = reject
    })

    binding.udx_napi_lookup(this._handle, req, host, family, ctx, onlookup)

    return promise
  }
}

function onlookup(err, host, family) {
  if (err) this.reject(err)
  else this.resolve({ host, family })
}
{
  "name": "udx-native",
  "version": "1.19.2",
  "description": "udx is reliable, multiplexed, and congestion-controlled streams over udp",
  "main": "lib/udx.js",
  "files": [
    "lib",
    "prebuilds",
    "binding.cc",
    "binding.js",
    "CMakeLists.txt"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "addon": true,
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check .",
    "test": "npm run lint && npm run test:bare && npm run test:node",
    "test:node": "node test/all.js",
    "test:bare": "bare test/all.js",
    "test:all": "brittle test/*.js test/slow/*.js",
    "test:generate": "brittle -r test/all.js test/*.js",
    "bench": "brittle test/bench/*.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/udx-native.git"
  },
  "keywords": [
    "tcp",
    "udp",
    "stream",
    "reliable"
  ],
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/udx-native/issues"
  },
  "homepage": "https://github.com/holepunchto/udx-native#readme",
  "engines": {
    "bare": ">=1.17.4"
  },
  "dependencies": {
    "b4a": "^1.5.0",
    "bare-events": "^2.2.0",
    "require-addon": "^1.1.0",
    "streamx": "^2.22.0"
  },
  "devDependencies": {
    "bare-compat-napi": "^1.3.0",
    "brittle": "^3.1.0",
    "cmake-bare": "^1.1.10",
    "cmake-fetch": "^1.0.1",
    "cmake-napi": "^1.0.5",
    "is-ci": "^3.0.1",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "tiny-byte-size": "^1.1.0"
  }
}
exports.add = add
exports.has = has
exports.remove = remove
exports.swap = swap

function add (list, item) {
  if (has(list, item)) return item
  item._index = list.length
  list.push(item)
  return item
}

function has (list, item) {
  return item._index < list.length && list[item._index] === item
}

function remove (list, item) {
  if (!has(list, item)) return null

  var last = list.pop()
  if (last !== item) {
    list[item._index] = last
    last._index = item._index
  }

  return item
}

function swap (list, a, b) {
  if (!has(list, a) || !has(list, b)) return
  var tmp = a._index
  a._index = b._index
  list[a._index] = a
  b._index = tmp
  list[b._index] = b
}
{
  "name": "unordered-set",
  "version": "2.0.1",
  "description": "A couple of functions that make it easy to maintain an unordered set as an array in an efficient way",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^6.0.4",
    "tape": "^4.4.0"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/unordered-set.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/unordered-set/issues"
  },
  "homepage": "https://github.com/mafintosh/unordered-set"
}
const b4a = require('b4a')

unslab.all = all
unslab.is = is

module.exports = unslab

function unslab (buf) {
  if (buf === null || buf.buffer.byteLength === buf.byteLength) return buf
  const copy = b4a.allocUnsafeSlow(buf.byteLength)
  copy.set(buf, 0)
  return copy
}

function is (buf) {
  return buf.buffer.byteLength !== buf.byteLength
}

function all (list) {
  let size = 0
  for (let i = 0; i < list.length; i++) {
    const buf = list[i]
    size += buf === null || buf.buffer.byteLength === buf.byteLength ? 0 : buf.byteLength
  }

  const copy = b4a.allocUnsafeSlow(size)
  const result = new Array(list.length)

  let offset = 0
  for (let i = 0; i < list.length; i++) {
    let buf = list[i]

    if (buf !== null && buf.buffer.byteLength !== buf.byteLength) {
      copy.set(buf, offset)
      buf = copy.subarray(offset, offset += buf.byteLength)
    }

    result[i] = buf
  }

  return result
}
{
  "name": "unslab",
  "version": "1.3.0",
  "description": "Unslab some slab'ed buffers",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.6.6"
  },
  "devDependencies": {
    "brittle": "^3.5.2",
    "standard": "^17.1.0"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/unslab.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/unslab/issues"
  },
  "homepage": "https://github.com/holepunchto/unslab"
}
const { runtime, platform, arch } = typeof Bare !== 'undefined'
  ? { runtime: 'bare', platform: global.Bare.platform, arch: global.Bare.arch }
  : typeof process !== 'undefined'
    ? { runtime: 'node', platform: global.process.platform, arch: global.process.arch }
    : typeof Window !== 'undefined'
      ? { runtime: 'browser', platform: 'unknown', arch: 'unknown' }
      : { runtime: 'unknown', platform: 'unknown', arch: 'unknown' }

exports.runtime = runtime
exports.platform = platform
exports.arch = arch
exports.isBare = runtime === 'bare'
exports.isBareKit = exports.isBare && typeof BareKit !== 'undefined'
exports.isPear = typeof Pear !== 'undefined'
exports.isNode = runtime === 'node'
exports.isBrowser = runtime === 'browser'
exports.isWindows = platform === 'win32'
exports.isLinux = platform === 'linux'
exports.isMac = platform === 'darwin'
exports.isIOS = platform === 'ios' || platform === 'ios-simulator'
exports.isAndroid = platform === 'android'
exports.isElectron = typeof process !== 'undefined' && !!global.process.versions?.electron
exports.isElectronRenderer = exports.isElectron && global.process.type === 'renderer'
exports.isElectronWorker = exports.isElectron && global.process.type === 'worker'
{
  "name": "which-runtime",
  "version": "1.3.2",
  "description": "Detect if you are in Bare or Node and which os etc",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {},
  "devDependencies": {
    "standard": "^17.0.0"
  },
  "scripts": {
    "test": "standard"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/which-runtime.git"
  },
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/which-runtime/issues"
  },
  "homepage": "https://github.com/holepunchto/which-runtime"
}
module.exports = class MaxCache {
  constructor ({ maxSize, maxAge, createMap, ongc }) {
    this.maxSize = maxSize
    this.maxAge = maxAge
    this.ongc = ongc || null

    this._createMap = createMap || defaultCreateMap
    this._latest = this._createMap()
    this._oldest = this._createMap()
    this._retained = this._createMap()
    this._gced = false
    this._interval = null

    if (this.maxAge > 0 && this.maxAge < Infinity) {
      const tick = Math.ceil(2 / 3 * this.maxAge)
      this._interval = setInterval(this._gcAuto.bind(this), tick)
      if (this._interval.unref) this._interval.unref()
    }
  }

  * [Symbol.iterator] () {
    for (const it of [this._latest, this._oldest, this._retained]) {
      yield * it
    }
  }

  * keys () {
    for (const it of [this._latest, this._oldest, this._retained]) {
      yield * it.keys()
    }
  }

  * values () {
    for (const it of [this._latest, this._oldest, this._retained]) {
      yield * it.values()
    }
  }

  destroy () {
    this.clear()
    clearInterval(this._interval)
    this._interval = null
  }

  clear () {
    this._gced = true
    this._latest.clear()
    this._oldest.clear()
    this._retained.clear()
  }

  set (k, v) {
    if (this._retained.has(k)) return this
    this._latest.set(k, v)
    this._oldest.delete(k) || this._retained.delete(k)
    if (this._latest.size >= this.maxSize) this._gc()
    return this
  }

  retain (k, v) {
    this._retained.set(k, v)
    this._latest.delete(k) || this._oldest.delete(k)
    return this
  }

  delete (k) {
    return this._latest.delete(k) || this._oldest.delete(k) || this._retained.delete(k)
  }

  has (k) {
    return this._latest.has(k) || this._oldest.has(k) || this._retained.has(k)
  }

  get (k) {
    if (this._latest.has(k)) {
      return this._latest.get(k)
    }

    if (this._oldest.has(k)) {
      const v = this._oldest.get(k)
      this._latest.set(k, v)
      this._oldest.delete(k)
      return v
    }

    if (this._retained.has(k)) {
      return this._retained.get(k)
    }

    return null
  }

  _gcAuto () {
    if (!this._gced) this._gc()
    this._gced = false
  }

  _gc () {
    this._gced = true
    if (this.ongc !== null && this._oldest.size > 0) this.ongc(this._oldest)
    this._oldest = this._latest
    this._latest = this._createMap()
  }
}

function defaultCreateMap () {
  return new Map()
}
{
  "name": "xache",
  "version": "1.2.1",
  "description": "Yet another auto expiring, max sizable cache",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "devDependencies": {
    "brittle": "^3.3.2",
    "standard": "^17.1.0"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/xache.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/xache/issues"
  },
  "homepage": "https://github.com/mafintosh/xache"
}
const b4a = require('b4a')

const ALPHABET = 'ybndrfg8ejkmcpqxot1uwisza345h769'
const MIN = 0x31 // 1
const MAX = 0x7a // z
const REVERSE = new Int8Array(1 + MAX - MIN)

REVERSE.fill(-1)

for (let i = 0; i < ALPHABET.length; i++) {
  const v = ALPHABET.charCodeAt(i) - MIN
  REVERSE[v] = i
}

exports.encode = encode
exports.decode = decode
exports.ALPHABET = ALPHABET

function decode (s, out) {
  let pb = 0
  let ps = 0

  const r = s.length & 7
  const q = (s.length - r) / 8

  if (!out) out = b4a.allocUnsafe(Math.ceil(s.length * 5 / 8))

  // 0 5 2 7 4 1 6 3 (+5 mod 8)
  for (let i = 0; i < q; i++) {
    const a = quintet(s, ps++)
    const b = quintet(s, ps++)
    const c = quintet(s, ps++)
    const d = quintet(s, ps++)
    const e = quintet(s, ps++)
    const f = quintet(s, ps++)
    const g = quintet(s, ps++)
    const h = quintet(s, ps++)

    out[pb++] = (a << 3) | (b >>> 2)
    out[pb++] = ((b & 0b11) << 6) | (c << 1) | (d >>> 4)
    out[pb++] = ((d & 0b1111) << 4) | (e >>> 1)
    out[pb++] = ((e & 0b1) << 7) | (f << 2) | (g >>> 3)
    out[pb++] = ((g & 0b111) << 5) | h
  }

  if (r === 0) return out.subarray(0, pb)

  const a = quintet(s, ps++)
  const b = quintet(s, ps++)

  out[pb++] = (a << 3) | (b >>> 2)

  if (r <= 2) return out.subarray(0, pb)

  const c = quintet(s, ps++)
  const d = quintet(s, ps++)

  out[pb++] = ((b & 0b11) << 6) | (c << 1) | (d >>> 4)

  if (r <= 4) return out.subarray(0, pb)

  const e = quintet(s, ps++)

  out[pb++] = ((d & 0b1111) << 4) | (e >>> 1)

  if (r <= 5) return out.subarray(0, pb)

  const f = quintet(s, ps++)
  const g = quintet(s, ps++)

  out[pb++] = ((e & 0b1) << 7) | (f << 2) | (g >>> 3)

  if (r <= 7) return out.subarray(0, pb)

  const h = quintet(s, ps++)

  out[pb++] = ((g & 0b111) << 5) | h

  return out.subarray(0, pb)
}

function encode (buf) {
  if (typeof buf === 'string') buf = b4a.from(buf)

  const max = buf.byteLength * 8

  let s = ''

  for (let p = 0; p < max; p += 5) {
    const i = p >>> 3
    const j = p & 7

    if (j <= 3) {
      s += ALPHABET[(buf[i] >>> (3 - j)) & 0b11111]
      continue
    }

    const of = j - 3
    const h = (buf[i] << of) & 0b11111
    const l = (i >= buf.byteLength ? 0 : buf[i + 1]) >>> (8 - of)

    s += ALPHABET[h | l]
  }

  return s
}

function quintet (s, i) {
  if (i > s.length) {
    return 0
  }

  const v = s.charCodeAt(i)

  if (v < MIN || v > MAX) {
    throw Error('Invalid character in base32 input: "' + s[i] + '" at position ' + i)
  }

  const bits = REVERSE[v - MIN]

  if (bits === -1) {
    throw Error('Invalid character in base32 input: "' + s[i] + '" at position ' + i)
  }

  return bits
}
{
  "name": "z32",
  "version": "1.1.0",
  "description": "Encode & decode z-base32",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.5.3"
  },
  "devDependencies": {
    "base-x": "^4.0.0",
    "base32": "0.0.7",
    "brittle": "^3.1.3",
    "nanobench": "^3.0.0",
    "rfc4648": "^1.5.2",
    "standard": "^17.0.0"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/z32.git"
  },
  "scripts": {
    "test": "standard && brittle test.js",
    "bench": "node benchmark.js"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/z32/issues"
  },
  "homepage": "https://github.com/mafintosh/z32"
}
{
  "name": "hyper-svc",
  "version": "0.1.9",
  "description": "Reusable per-app daemon library \u2014 UDS + HTTP for local RPC, Hyperswarm for peer mirroring",
  "type": "module",
  "main": "index.js",
  "scripts": {
    "test": "brittle test/*.test.js",
    "test:bare": "bare ./node_modules/.bin/brittle test/*.test.js"
  },
  "engines": {
    "node": ">=18",
    "bare": ">=1.0"
  },
  "imports": {
    "#node:fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "#node:fs/promises": {
      "bare": "bare-fs/promises",
      "default": "fs/promises"
    },
    "#node:path": {
      "bare": "bare-path",
      "default": "path"
    },
    "#node:os": {
      "bare": "bare-os",
      "default": "os"
    },
    "#node:url": {
      "bare": "bare-url",
      "default": "url"
    },
    "#node:events": {
      "bare": "bare-events",
      "default": "events"
    },
    "#node:stream": {
      "bare": "bare-stream",
      "default": "stream"
    },
    "#node:net": {
      "bare": "bare-net",
      "default": "net"
    },
    "#node:http": {
      "bare": "bare-http1",
      "default": "http"
    },
    "#node:process": {
      "bare": "bare-process",
      "default": "process"
    }
  },
  "dependencies": {
    "b4a": "^1.6.0",
    "bare-events": "^2.0.0",
    "bare-fs": "^4.7.2",
    "bare-http1": "^4.0.0",
    "bare-net": "^1.0.0",
    "bare-os": "^3.0.0",
    "bare-path": "^3.0.0",
    "bare-process": "^4.0.0",
    "bare-stream": "^2.0.0",
    "bare-url": "^2.0.0",
    "compact-encoding": "^3.2.0",
    "hypercore-crypto": "^3.0.0",
    "hyperswarm": "^4.0.0",
    "protomux": "^3.0.0",
    "ready-resource": "^1.0.0",
    "bare-abstract-socket": "^1.0.0"
  },
  "devDependencies": {
    "@hyperswarm/testnet": "^3.0.0",
    "brittle": "^3.0.0",
    "corestore": "^7.0.0",
    "hyper-rooms": "file:../hyper-rooms"
  },
  "overrides": {}
}
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const b4a = require('b4a')

// https://en.wikipedia.org/wiki/Merkle_tree#Second_preimage_attack
const LEAF_TYPE = b4a.from([0])
const PARENT_TYPE = b4a.from([1])
const ROOT_TYPE = b4a.from([2])

const HYPERCORE = b4a.from('hypercore')

exports.keyPair = function (seed) {
  // key pairs might stay around for a while, so better not to use a default slab to avoid retaining it completely
  const slab = b4a.allocUnsafeSlow(
    sodium.crypto_sign_PUBLICKEYBYTES + sodium.crypto_sign_SECRETKEYBYTES
  )
  const publicKey = slab.subarray(0, sodium.crypto_sign_PUBLICKEYBYTES)
  const secretKey = slab.subarray(sodium.crypto_sign_PUBLICKEYBYTES)

  if (seed) sodium.crypto_sign_seed_keypair(publicKey, secretKey, seed)
  else sodium.crypto_sign_keypair(publicKey, secretKey)

  return {
    publicKey,
    secretKey
  }
}

exports.validateKeyPair = function (keyPair) {
  const pk = b4a.allocUnsafe(sodium.crypto_sign_PUBLICKEYBYTES)
  sodium.crypto_sign_ed25519_sk_to_pk(pk, keyPair.secretKey)
  return b4a.equals(pk, keyPair.publicKey)
}

exports.sign = function (message, secretKey) {
  // Dedicated slab for the signature, to avoid retaining unneeded mem and for security
  const signature = b4a.allocUnsafeSlow(sodium.crypto_sign_BYTES)
  sodium.crypto_sign_detached(signature, message, secretKey)
  return signature
}

exports.verify = function (message, signature, publicKey) {
  if (signature.byteLength !== sodium.crypto_sign_BYTES) return false
  if (publicKey.byteLength !== sodium.crypto_sign_PUBLICKEYBYTES) return false
  return sodium.crypto_sign_verify_detached(signature, message, publicKey)
}

exports.encrypt = function (message, publicKey) {
  const ciphertext = b4a.alloc(message.byteLength + sodium.crypto_box_SEALBYTES)
  sodium.crypto_box_seal(ciphertext, message, publicKey)
  return ciphertext
}

exports.decrypt = function (ciphertext, keyPair) {
  if (ciphertext.byteLength < sodium.crypto_box_SEALBYTES) return null

  const plaintext = b4a.alloc(ciphertext.byteLength - sodium.crypto_box_SEALBYTES)

  if (!sodium.crypto_box_seal_open(plaintext, ciphertext, keyPair.publicKey, keyPair.secretKey)) {
    return null
  }

  return plaintext
}

exports.encryptionKeyPair = function (seed) {
  const publicKey = b4a.alloc(sodium.crypto_box_PUBLICKEYBYTES)
  const secretKey = b4a.alloc(sodium.crypto_box_SECRETKEYBYTES)

  if (seed) {
    sodium.crypto_box_seed_keypair(publicKey, secretKey, seed)
  } else {
    sodium.crypto_box_keypair(publicKey, secretKey)
  }

  return {
    publicKey,
    secretKey
  }
}

exports.data = function (data) {
  const out = b4a.allocUnsafe(32)

  sodium.crypto_generichash_batch(out, [LEAF_TYPE, c.encode(c.uint64, data.byteLength), data])

  return out
}

exports.parent = function (a, b) {
  if (a.index > b.index) {
    const tmp = a
    a = b
    b = tmp
  }

  const out = b4a.allocUnsafe(32)

  sodium.crypto_generichash_batch(out, [
    PARENT_TYPE,
    c.encode(c.uint64, a.size + b.size),
    a.hash,
    b.hash
  ])

  return out
}

exports.tree = function (roots, out) {
  const buffers = new Array(3 * roots.length + 1)
  let j = 0

  buffers[j++] = ROOT_TYPE

  for (let i = 0; i < roots.length; i++) {
    const r = roots[i]
    buffers[j++] = r.hash
    buffers[j++] = c.encode(c.uint64, r.index)
    buffers[j++] = c.encode(c.uint64, r.size)
  }

  if (!out) out = b4a.allocUnsafe(32)
  sodium.crypto_generichash_batch(out, buffers)
  return out
}

exports.hash = function (data, out) {
  if (!out) out = b4a.allocUnsafe(32)
  if (!Array.isArray(data)) data = [data]

  sodium.crypto_generichash_batch(out, data)

  return out
}

exports.randomBytes = function (n) {
  const buf = b4a.allocUnsafe(n)
  sodium.randombytes_buf(buf)
  return buf
}

exports.discoveryKey = function (key) {
  if (!key || key.byteLength !== 32) throw new Error('Must pass a 32 byte buffer')
  // Discovery keys might stay around for a while, so better not to use slab memory (for better gc)
  const digest = b4a.allocUnsafeSlow(32)
  sodium.crypto_generichash(digest, HYPERCORE, key)
  return digest
}

if (sodium.sodium_free) {
  exports.free = function (secureBuf) {
    if (secureBuf.secure) sodium.sodium_free(secureBuf)
  }
} else {
  exports.free = function () {}
}

exports.namespace = function (name, count) {
  const ids = typeof count === 'number' ? range(count) : count

  // Namespaces are long-lived, so better to use a dedicated slab
  const buf = b4a.allocUnsafeSlow(32 * ids.length)

  const list = new Array(ids.length)

  // ns is ephemeral, so default slab
  const ns = b4a.allocUnsafe(33)
  sodium.crypto_generichash(ns.subarray(0, 32), typeof name === 'string' ? b4a.from(name) : name)

  for (let i = 0; i < list.length; i++) {
    list[i] = buf.subarray(32 * i, 32 * i + 32)
    ns[32] = ids[i]
    sodium.crypto_generichash(list[i], ns)
  }

  return list
}

function range(count) {
  const arr = new Array(count)
  for (let i = 0; i < count; i++) arr[i] = i
  return arr
}
{
  "name": "hypercore-crypto",
  "version": "3.7.0",
  "description": "The crypto primitives used in hypercore, extracted into a separate module",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.6.6",
    "compact-encoding": "^3.0.0",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "brittle": "^3.5.0",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/hypercore-crypto.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/hypercore-crypto/issues"
  },
  "homepage": "https://github.com/mafintosh/hypercore-crypto"
}
/**
 * pgh-runtime — per-app OTA updater.
 *
 * An installed app imports this module and instantiates a PghRuntime
 * with its own upgrade source, a store handle, and a fetcher. The
 * runtime periodically checks for a newer release and, when found,
 * materializes the new tree into the store and emits events. The app
 * decides when to actually apply the update (typically on next restart).
 *
 * Mirrors pear-runtime-updater's shape (~127 LOC) but uses hyper-overlay
 * tree content-addressing instead of Hyperdrive.
 *
 * Usage:
 *
 *   import { PghRuntime } from 'pgh-runtime'
 *   const runtime = new PghRuntime({
 *     name: 'my-app',
 *     currentTreeHash: process.env.PGH_CURRENT_TREE_HASH,
 *     fetcher,
 *     store,
 *     interval: 60 * 60 * 1000
 *   })
 *   runtime.on('updating', () => console.log('downloading...'))
 *   runtime.on('updated', (info) => console.log('ready:', info.newTreeHash))
 *   runtime.on('error', (err) => console.error(err))
 *   await runtime.start()
 *
 * Expected interfaces:
 *
 *   fetcher:
 *     async getLatestRelease(name) -> { treeHash, version, ... } | null
 *     async getTree(hash)          -> { entries: [...], size }
 *     async getContent(contentHash)-> Buffer
 *
 *   store (TreeStore-compatible):
 *     init()
 *     hasTree(hash) -> boolean
 *     materialize(hash, entries, { fetchContent, fetchTree, source? })
 *
 * The runtime is transport-agnostic — any fetcher conforming to that
 * shape works. See pgh's NetworkFetcher for the Hyperswarm implementation.
 */

import EventEmitter from '#node:events'

import { computeTreeHash } from 'hyper-overlay/tree'

const DEFAULT_INTERVAL = 30 * 60 * 1000 // 30 min

export class PghRuntime extends EventEmitter {
  /**
   * @param {object} opts
   * @param {string} opts.name                 app name
   * @param {string} [opts.currentTreeHash]    hex hash of the tree this app currently runs at
   * @param {object} opts.fetcher              { getTree, getContent, getLatestRelease(name) }
   * @param {object} opts.store                TreeStore-compatible (hasTree / materialize / init)
   * @param {number} [opts.interval]           ms between polls (default 30m; 0 = no polling)
   * @param {boolean} [opts.startImmediately]  do an initial check on start (default true)
   * @param {string} [opts.host]               host label for per-arch prebuild trees (e.g. "linux-x64")
   * @param {function} [opts.materialize]      injected materializer ({ store, appName, rootTreeHash, deps, host })
   *                                           — pgh's node materializer or any compatible fn. Omit for store-only.
   */
  constructor (opts = {}) {
    super()
    if (!opts.name) throw new Error('PghRuntime requires opts.name')
    if (!opts.fetcher) throw new Error('PghRuntime requires opts.fetcher')
    if (!opts.store) throw new Error('PghRuntime requires opts.store')

    this.name = opts.name
    this.currentTreeHash = opts.currentTreeHash || null
    this.fetcher = opts.fetcher
    this.store = opts.store
    this.interval = opts.interval != null ? opts.interval : DEFAULT_INTERVAL
    this.startImmediately = opts.startImmediately !== false
    this.host = opts.host || null
    this.materialize = typeof opts.materialize === 'function' ? opts.materialize : null

    this.latest = null
    this.updating = false
    this.updated = false
    this.newTreeHash = null

    this._timer = null
    this._started = false
  }

  async start () {
    if (this._started) return
    this._started = true
    if (this.startImmediately) await this._check()
    if (this.interval > 0) {
      this._timer = setInterval(() => { this._check().catch(e => this.emit('error', e)) }, this.interval)
      if (this._timer.unref) this._timer.unref()
    }
  }

  async stop () {
    if (!this._started) return
    this._started = false
    if (this._timer) { clearInterval(this._timer); this._timer = null }
  }

  /**
   * Force an immediate check. Returns the release entry if a new tree
   * was materialized, null otherwise.
   */
  async checkNow () {
    return this._check()
  }

  async _check () {
    let release
    try {
      release = await this.fetcher.getLatestRelease(this.name)
    } catch (err) {
      this.emit('error', err)
      return null
    }

    if (!release) return null

    // Nothing to do if we already run this tree.
    if (this.currentTreeHash && release.treeHash === this.currentTreeHash) {
      this.latest = release
      return null
    }
    // We've already staged this tree; don't re-emit.
    if (this.updated && release.treeHash === this.newTreeHash) {
      return null
    }

    this.latest = release
    this.updating = true
    this.emit('updating', release)

    try {
      // Full RELEASE install — root tree PLUS its dependency closure (and,
      // when a materializer is injected, the wired install layout). Using
      // installTree alone here fetched only the root tree → a broken install
      // for any app with deps (see installRelease).
      const result = await installRelease(this.store, release, this.fetcher, {
        host: this.host,
        materialize: this.materialize,
        appName: this.name,
        source: 'pgh-runtime:' + this.name
      })
      this.newTreeHash = release.treeHash
      this.updating = false
      this.updated = true
      this.emit('updated', {
        name: this.name,
        newTreeHash: release.treeHash,
        release,
        materialized: result.materialized,
        skipped: result.skipped
      })
      return release
    } catch (err) {
      this.updating = false
      this.emit('error', err)
      return null
    }
  }

  /**
   * Descriptor for the staged update. Apply via the app's own mechanism
   * (pgh app update <name> --tree <hash> is the usual CLI path).
   */
  readyToApply () {
    if (!this.updated) return null
    return {
      name: this.name,
      previousTreeHash: this.currentTreeHash,
      newTreeHash: this.newTreeHash,
      release: this.latest
    }
  }
}

/**
 * Walk a tree from the root, fetching each subtree and materializing
 * content into the store. Inlined here so pgh-runtime has no dependency
 * on the pgh CLI package — any store + fetcher that conform to the
 * expected shapes work.
 *
 * @param {object} store   — TreeStore-compatible
 * @param {string} rootHash
 * @param {object} fetcher — { getTree, getContent }
 * @param {object} [opts]
 * @returns {Promise<{ materialized: number, skipped: number }>}
 */
export async function installTree (store, rootHash, fetcher, opts = {}) {
  store.init()

  if (store.hasTree(rootHash)) {
    return { materialized: 0, skipped: 1 }
  }

  const tree = await fetcher.getTree(rootHash)
  if (!tree || !Array.isArray(tree.entries)) {
    throw new Error('fetcher returned invalid tree for ' + rootHash)
  }

  // Content-address verification: entries MUST hash to rootHash. A P2P peer
  // can answer with empty/wrong entries to signal "I don't have this tree";
  // without this check that silently materializes an empty/partial dir. Let
  // the caller retry on another peer (EHASHMISMATCH). Matches pgh's installTree.
  const actualRootHash = computeTreeHash(tree.entries)
  if (actualRootHash !== rootHash) {
    throw Object.assign(
      new Error('root tree-hash mismatch: expected ' + rootHash.slice(0, 12) + '…, got ' + actualRootHash.slice(0, 12) + '… (peer may not have this tree)'),
      { code: 'EHASHMISMATCH', expected: rootHash, actual: actualRootHash }
    )
  }

  // Single self-contained materialize — store.materialize recursively inlines
  // subtree content via fetchTree/fetchContent. Subtree hashes do NOT get their
  // own dependencies/<subhash>/ dir (that would duplicate every file N times
  // across levels); dedup happens at the top-level tree layer. `skipPath` skips
  // foreign subtrees (e.g. by-arch/<other-host>/). Mirrors pgh's tree-install.js
  // — the manual subtree recursion this replaced created redundant store dirs
  // and could not honor skipPath.
  await store.materialize(rootHash, tree.entries, {
    fetchContent: fetcher.getContent.bind(fetcher),
    fetchTree: async (h) => {
      const t = await fetcher.getTree(h)
      return t.entries
    },
    source: opts.source,
    skipPath: opts.skipPath
  })

  return { materialized: 1, skipped: 0 }
}

/**
 * Install a full RELEASE — the root tree PLUS its dependency closure.
 *
 * `installTree` fetches a single tree and its nested subdirectories, but an
 * app's node_modules dependencies are SEPARATE content-addressed trees listed
 * in the release's `deps` array (each with its own tree hash and a per-host
 * prebuild tree). Fetching only the root tree therefore yields a BROKEN
 * install — the deps are never fetched and node_modules is never wired. (This
 * is exactly why pear-git-v3 constructs a PghRuntime but refuses to call
 * checkNow(): "pgh-runtime only fetches root trees, not dep closures, so using
 * it here would produce a broken install.")
 *
 * installRelease closes that gap:
 *   1. fetch the FULL closure (root + every dep.tree + prebuilds[host]) into
 *      the store via installTree, then
 *   2. hand the closure to a materializer that wires the install layout
 *      (hardlink deps + symlink node_modules).
 *
 * The materializer is INJECTED (`opts.materialize`) — same dependency-injection
 * philosophy as fetcher/store — so pgh-runtime stays free of any dependency on
 * the pgh CLI's materializer. pgh's node materializer
 * (`materialize({ store, appName, rootTreeHash, deps, host })`) is the canonical
 * one; any function with that shape works. Without a materializer the closure
 * is fetched into the store but the install layout is not wired (store-only).
 *
 * @param {object} store     TreeStore-compatible (init / hasTree / materialize)
 * @param {object} release   { treeHash, deps?: [{ name, version, tree, prebuilds }], name? }
 * @param {object} fetcher   { getTree, getContent }
 * @param {object} [opts]    { host?, appName?, materialize?, source? }
 * @returns {Promise<{ closure: number, materialized: number, skipped: number, install: any }>}
 */
export async function installRelease (store, release, fetcher, opts = {}) {
  if (!release || !release.treeHash) {
    throw new Error('installRelease requires release.treeHash')
  }
  store.init()

  const host = opts.host || null
  const deps = Array.isArray(release.deps) ? release.deps : []

  // Build the full closure: root tree + each dep's tree + its per-host prebuild.
  const closureHashes = [release.treeHash]
  for (const dep of deps) {
    if (dep.tree) closureHashes.push(dep.tree)
    if (host && dep.prebuilds && dep.prebuilds[host]) closureHashes.push(dep.prebuilds[host])
  }

  const source = opts.source || ('pgh-runtime:' + (release.name || 'app'))
  let materialized = 0
  let skipped = 0
  for (const hash of closureHashes) {
    const r = await installTree(store, hash, fetcher, { source, skipPath: opts.skipPath })
    materialized += r.materialized
    skipped += r.skipped
  }

  let install = null
  if (typeof opts.materialize === 'function') {
    install = await opts.materialize({
      store,
      appName: opts.appName || release.name,
      rootTreeHash: release.treeHash,
      deps,
      host
    })
  }

  return { closure: closureHashes.length, materialized, skipped, install }
}
const errors = require('./lib/errors')

class EventListener {
  constructor() {
    this.list = []
    this.count = 0
  }

  append(ctx, name, fn, once) {
    this.count++
    ctx.emit('newListener', name, fn) // Emit BEFORE adding
    this.list.push([fn, once])
  }

  prepend(ctx, name, fn, once) {
    this.count++
    ctx.emit('newListener', name, fn) // Emit BEFORE adding
    this.list.unshift([fn, once])
  }

  remove(ctx, name, fn) {
    for (let i = 0, n = this.list.length; i < n; i++) {
      const l = this.list[i]

      if (l[0] === fn) {
        this.list.splice(i, 1)

        if (this.count === 1) delete ctx._events[name]

        ctx.emit('removeListener', name, fn) // Emit AFTER removing

        this.count--
        return
      }
    }
  }

  removeAll(ctx, name) {
    const list = [...this.list]
    this.list = []

    if (this.count === list.length) delete ctx._events[name]

    for (let i = list.length - 1; i >= 0; i--) {
      ctx.emit('removeListener', name, list[i][0]) // Emit AFTER removing
    }

    this.count -= list.length
  }

  emit(ctx, name, ...args) {
    const list = [...this.list]

    for (let i = 0, n = list.length; i < n; i++) {
      const l = list[i]

      if (l[1] === true) this.remove(ctx, name, l[0])

      Reflect.apply(l[0], ctx, args)
    }

    return list.length > 0
  }
}

function appendListener(ctx, name, fn, once) {
  if (ctx._events === undefined) ctx._events = Object.create(null)
  const e = ctx._events[name] || (ctx._events[name] = new EventListener())
  e.append(ctx, name, fn, once)
  return ctx
}

function prependListener(ctx, name, fn, once) {
  if (ctx._events === undefined) ctx._events = Object.create(null)
  const e = ctx._events[name] || (ctx._events[name] = new EventListener())
  e.prepend(ctx, name, fn, once)
  return ctx
}

function removeListener(ctx, name, fn) {
  if (ctx._events === undefined) return ctx
  const e = ctx._events[name]
  if (e !== undefined) e.remove(ctx, name, fn)
  return ctx
}

function throwUnhandledError(...args) {
  let err

  if (args.length > 0) err = args[0]

  if (err instanceof Error === false) err = errors.UNHANDLED_ERROR(err)

  if (Error.captureStackTrace) {
    Error.captureStackTrace(err, exports.prototype.emit)
  }

  queueMicrotask(() => {
    throw err
  })
}

module.exports = exports = class EventEmitter {
  constructor() {
    this._events = Object.create(null)
  }

  addListener(name, fn) {
    return appendListener(this, name, fn, false)
  }

  addOnceListener(name, fn) {
    return appendListener(this, name, fn, true)
  }

  prependListener(name, fn) {
    return prependListener(this, name, fn, false)
  }

  prependOnceListener(name, fn) {
    return prependListener(this, name, fn, true)
  }

  removeListener(name, fn) {
    return removeListener(this, name, fn)
  }

  on(name, fn) {
    return appendListener(this, name, fn, false)
  }

  once(name, fn) {
    return appendListener(this, name, fn, true)
  }

  off(name, fn) {
    return removeListener(this, name, fn)
  }

  emit(name, ...args) {
    if (name === 'error' && this._events !== undefined && this._events.error === undefined) {
      throwUnhandledError(...args)
    }

    if (this._events === undefined) return false
    const e = this._events[name]
    return e === undefined ? false : e.emit(this, name, ...args)
  }

  listeners(name) {
    if (this._events === undefined) return []
    const e = this._events[name]
    return e === undefined ? [] : [...e.list]
  }

  rawListeners(name) {
    if (this._events === undefined) return []
    const e = this._events[name]
    return e === undefined ? [] : e.list.map((l) => l[0])
  }

  eventNames() {
    if (this._events === undefined) return []
    return Reflect.ownKeys(this._events)
  }

  listenerCount(name) {
    if (this._events === undefined) return 0
    const e = this._events[name]
    return e === undefined ? 0 : e.list.length
  }

  getMaxListeners() {
    return EventEmitter.defaultMaxListeners
  }

  setMaxListeners(n) {}

  removeAllListeners(name) {
    if (arguments.length === 0) {
      for (const key of Reflect.ownKeys(this._events)) {
        if (key === 'removeListener') continue
        this.removeAllListeners(key)
      }
      this.removeAllListeners('removeListener')
    } else {
      const e = this._events[name]
      if (e !== undefined) e.removeAll(this, name)
    }
    return this
  }
}

exports.EventEmitter = exports

exports.errors = errors

exports.defaultMaxListeners = 10

exports.on = function on(emitter, name, opts = {}) {
  const { signal } = opts

  if (signal && signal.aborted) {
    throw errors.OPERATION_ABORTED(signal.reason)
  }

  let error = null
  let done = false

  const events = []
  const promises = []

  if (name !== 'error') emitter.on('error', onerror)

  if (signal) signal.addEventListener('abort', onabort)

  emitter.on(name, onevent)

  return {
    next() {
      if (events.length) {
        return Promise.resolve({ value: events.shift(), done: false })
      }

      if (error) {
        const err = error

        error = null

        return Promise.reject(err)
      }

      if (done) return onclose()

      return new Promise((resolve, reject) => promises.push({ resolve, reject }))
    },

    return() {
      return onclose()
    },

    throw(err) {
      return onerror(err)
    },

    [Symbol.asyncIterator]() {
      return this
    }
  }

  function onevent(...args) {
    if (promises.length) {
      promises.shift().resolve({ value: args, done: false })
    } else {
      events.push(args)
    }
  }

  function onerror(err) {
    emitter.off(name, onevent).off('error', onerror)

    if (promises.length) {
      promises.shift().reject(err)
    } else {
      error = err
    }

    return Promise.resolve({ done: true })
  }

  function onabort() {
    signal.removeEventListener('abort', onabort)

    onerror(errors.OPERATION_ABORTED(signal.reason))
  }

  function onclose() {
    emitter.off(name, onevent)

    if (name !== 'error') emitter.off('error', onerror)

    if (signal) signal.removeEventListener('abort', onabort)

    done = true

    if (promises.length) promises.shift().resolve({ done: true })

    return Promise.resolve({ done: true })
  }
}

exports.once = function once(emitter, name, opts = {}) {
  const { signal } = opts

  if (signal && signal.aborted) {
    return Promise.reject(errors.OPERATION_ABORTED(signal.reason))
  }

  return new Promise((resolve, reject) => {
    if (name !== 'error') emitter.on('error', onerror)

    if (signal) signal.addEventListener('abort', onabort)

    emitter.once(name, onevent)

    function onevent(...args) {
      if (name !== 'error') emitter.off('error', onerror)

      if (signal) signal.removeEventListener('abort', onabort)

      resolve(args)
    }

    function onerror(err) {
      emitter.off(name, onevent)

      if (name !== 'error') emitter.off('error', onerror)

      reject(err)
    }

    function onabort() {
      signal.removeEventListener('abort', onabort)

      onerror(errors.OPERATION_ABORTED(signal.reason))
    }
  })
}

exports.forward = function forward(from, to, names, opts = {}) {
  if (typeof names === 'string') names = [names]

  const { emit = to.emit.bind(to) } = opts

  const listeners = names.map(
    (name) =>
      function onevent(...args) {
        emit(name, ...args)
      }
  )

  to.on('newListener', (name) => {
    const i = names.indexOf(name)

    if (i !== -1 && to.listenerCount(name) === 0) {
      from.on(name, listeners[i])
    }
  }).on('removeListener', (name) => {
    const i = names.indexOf(name)

    if (i !== -1 && to.listenerCount(name) === 0) {
      from.off(name, listeners[i])
    }
  })
}

exports.listenerCount = function listenerCount(emitter, name) {
  return emitter.listenerCount(name)
}

exports.getMaxListeners = function getMaxListeners(emitter) {
  if (typeof emitter.getMaxListeners === 'function') {
    return emitter.getMaxListeners()
  }

  return exports.defaultMaxListeners
}

exports.setMaxListeners = function setMaxListeners(n, ...emitters) {
  if (emitters.length === 0) exports.defaultMaxListeners = n
  else {
    for (const emitter of emitters) {
      if (typeof emitter.setMaxListeners === 'function') {
        emitter.setMaxListeners(n)
      }
    }
  }
}
module.exports = class EventEmitterError extends Error {
  constructor(msg, code, fn = EventEmitterError, opts) {
    super(`${code}: ${msg}`, opts)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'EventEmitterError'
  }

  static OPERATION_ABORTED(cause, msg = 'Operation aborted') {
    return new EventEmitterError(msg, 'OPERATION_ABORTED', EventEmitterError.OPERATION_ABORTED, {
      cause
    })
  }

  static UNHANDLED_ERROR(cause, msg = 'Unhandled error') {
    return new EventEmitterError(msg, 'UNHANDLED_ERROR', EventEmitterError.UNHANDLED_ERROR, {
      cause
    })
  }
}
{
  "name": "bare-events",
  "version": "2.9.1",
  "description": "Event emitters for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    },
    "./web": {
      "types": "./web.d.ts",
      "default": "./web.js"
    },
    "./errors": "./lib/errors.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "global.js",
    "global.d.ts",
    "web.js",
    "web.d.ts",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:bare && npm run test:node",
    "test:bare": "brittle-bare --coverage test.js",
    "test:node": "brittle-node --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-events.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-events/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-events#readme",
  "devDependencies": {
    "bare-abort-controller": "^1.0.0",
    "brittle": "^3.3.2",
    "lunte": "^1.8.0",
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^2.0.0",
    "uncaughts": "^1.1.1"
  },
  "peerDependencies": {
    "bare-abort-controller": "*"
  },
  "peerDependenciesMeta": {
    "bare-abort-controller": {
      "optional": true
    }
  }
}
/**
 * Tree — content-addressable directory hashing for hyper-overlay
 *
 * A tree is a canonical serialization of a directory's immediate entries.
 * Each entry is one of: file, subdirectory, symlink. The tree's identity
 * is blake2b-256 of its canonical bytes.
 *
 * Format (P.10 Phase 0.5a):
 *
 *   tree := "pgh-tree-1\n" ||
 *           varint(n_entries) ||
 *           entry[0] || ... || entry[n-1]
 *
 *   entry := u8(kind)  ||           // 0=file, 1=dir, 2=symlink
 *            u8(exec)  ||           // 0 or 1; always 0 for dir/symlink
 *            varint(name_len) || name ||  // UTF-8 NFC, no NUL, no "/"
 *            32_bytes(child_hash)
 *
 *   tree_hash := blake2b-256(tree_bytes)
 *
 * Identity fields (in the hash): kind, exec-bit, name, child_hash.
 * Explicitly excluded: mtime, size, uid/gid, full mode.
 *
 * Entries MUST be sorted byte-wise by name (after NFC normalization).
 * Encoders emit sorted; decoders reject unsorted trees.
 *
 * Symlinks: child_hash = blake2b-256 of the target path bytes (not followed).
 * Empty directories: zero-entry tree, valid, deterministic.
 */

import fs from '#fs'
import path from '#path'
import crypto from 'hypercore-crypto'
import c from 'compact-encoding'

// ── Constants ─────────────────────────────────────────────────

export const MAGIC = Buffer.from('pgh-tree-1\n', 'utf8')
export const KIND_FILE = 0
export const KIND_DIR = 1
export const KIND_SYMLINK = 2

// Windows reserved device names (case-insensitive, with or without extension)
const WINDOWS_RESERVED = new Set([
  'CON', 'PRN', 'AUX', 'NUL',
  'COM1', 'COM2', 'COM3', 'COM4', 'COM5', 'COM6', 'COM7', 'COM8', 'COM9',
  'LPT1', 'LPT2', 'LPT3', 'LPT4', 'LPT5', 'LPT6', 'LPT7', 'LPT8', 'LPT9'
])

// Chars forbidden in filenames on Windows (beyond format-layer rules)
// eslint-disable-next-line no-control-regex
const WINDOWS_FORBIDDEN = /[\\:*?"<>|\x00-\x1f]/

// Default skip list for walkTree — minimal, just obvious platform cruft.
// Consumers that want more (e.g. .git for pgh publish) pass their own.
export const DEFAULT_SKIP = new Set(['.DS_Store', 'Thumbs.db'])

// ── Name validation (format layer) ────────────────────────────

/**
 * Normalize a filename for hashing and validate format-layer rules.
 * Throws on unrepresentable names. Returns the canonical form.
 *
 * @param {string} name - single path component (no "/")
 * @returns {string} NFC-normalized name
 */
export function normalizeName (name) {
  if (typeof name !== 'string') {
    throw new Error('tree entry name must be string, got ' + typeof name)
  }
  if (name.length === 0) {
    throw new Error('tree entry name cannot be empty')
  }
  if (name === '.' || name === '..') {
    throw new Error('tree entry name cannot be "." or ".."')
  }
  if (name.indexOf('/') !== -1) {
    throw new Error('tree entry name cannot contain "/": ' + JSON.stringify(name))
  }
  if (name.indexOf('\x00') !== -1) {
    throw new Error('tree entry name cannot contain NUL: ' + JSON.stringify(name))
  }

  const normalized = name.normalize('NFC')

  // Verify the normalized form is valid UTF-8 that round-trips through
  // Buffer (catches lone surrogates and other malformed sequences).
  const asBytes = Buffer.from(normalized, 'utf8')
  if (asBytes.toString('utf8') !== normalized) {
    throw new Error('tree entry name is not valid UTF-8: ' + JSON.stringify(name))
  }

  return normalized
}

// ── Consumer-policy layer ─────────────────────────────────────

/**
 * Check a name against Windows compatibility rules.
 * Does NOT throw — returns a reason string (or null if the name is OK).
 * Used by pgh publish for strict cross-platform validation.
 *
 * @param {string} name
 * @returns {string|null} reason if incompatible, null if OK
 */
export function windowsIncompatibleReason (name) {
  if (WINDOWS_FORBIDDEN.test(name)) {
    return 'contains Windows-forbidden character (\\:*?"<>| or control code)'
  }
  const trimmed = name.replace(/\.+$/, '').replace(/ +$/, '')
  if (trimmed !== name) {
    return 'trailing "." or space (Windows strips these silently)'
  }
  // Reserved device names apply with any extension: AUX.log, PRN.txt etc.
  const base = name.split('.')[0].toUpperCase()
  if (WINDOWS_RESERVED.has(base)) {
    return `"${base}" is a reserved Windows device name (even with extension)`
  }
  return null
}

// ── Canonical encoding ────────────────────────────────────────

/**
 * Encode a single entry to its canonical byte representation.
 *
 * @param {object} state - compact-encoding state
 * @param {{kind: number, exec: number, name: string, childHash: Buffer|string}} e
 */
function encodeEntry (state, e) {
  if (e.kind !== KIND_FILE && e.kind !== KIND_DIR && e.kind !== KIND_SYMLINK) {
    throw new Error('invalid entry kind: ' + e.kind)
  }
  if (e.exec !== 0 && e.exec !== 1) {
    throw new Error('entry exec must be 0 or 1')
  }
  if (e.kind !== KIND_FILE && e.exec !== 0) {
    throw new Error('non-file entry must have exec=0')
  }

  const hash = toBuffer32(e.childHash)

  c.uint8.encode(state, e.kind)
  c.uint8.encode(state, e.exec)
  c.string.encode(state, e.name) // compact-encoding: varint len + utf8 bytes
  state.buffer.set(hash, state.start)
  state.start += 32
}

function preencodeEntry (state, e) {
  c.uint8.preencode(state, e.kind)
  c.uint8.preencode(state, e.exec)
  c.string.preencode(state, e.name)
  state.end += 32
}

/**
 * Serialize a list of entries to canonical tree bytes.
 * Entries are sorted + normalized as a side-effect of the call.
 *
 * @param {Array<{kind: number, exec: number, name: string, childHash: Buffer|string}>} entries
 * @returns {Buffer}
 */
export function encodeTree (entries) {
  const normalized = entries.map(e => ({
    kind: e.kind,
    exec: e.exec || 0,
    name: normalizeName(e.name),
    childHash: e.childHash
  }))
  normalized.sort(compareEntries)

  // Sanity: no duplicate names after normalization
  for (let i = 1; i < normalized.length; i++) {
    if (normalized[i].name === normalized[i - 1].name) {
      throw new Error('duplicate entry name after NFC normalization: ' + normalized[i].name)
    }
  }

  const state = { start: 0, end: 0, buffer: null }
  state.end += MAGIC.length
  c.uint.preencode(state, normalized.length)
  for (const e of normalized) preencodeEntry(state, e)

  state.buffer = Buffer.alloc(state.end)

  state.buffer.set(MAGIC, state.start)
  state.start += MAGIC.length
  c.uint.encode(state, normalized.length)
  for (const e of normalized) encodeEntry(state, e)

  return state.buffer
}

/**
 * Byte-wise comparator for entry names (after NFC normalization).
 */
function compareEntries (a, b) {
  const ab = Buffer.from(a.name, 'utf8')
  const bb = Buffer.from(b.name, 'utf8')
  return Buffer.compare(ab, bb)
}

/**
 * Decode canonical tree bytes back to an entries list.
 * Rejects unsorted or malformed trees.
 *
 * @param {Buffer} buf
 * @returns {Array<{kind: number, exec: number, name: string, childHash: string}>}
 */
export function decodeTree (buf) {
  if (!Buffer.isBuffer(buf)) throw new Error('decodeTree expects a Buffer')
  if (buf.length < MAGIC.length) throw new Error('tree too short')
  if (buf.compare(MAGIC, 0, MAGIC.length, 0, MAGIC.length) !== 0) {
    throw new Error('tree magic mismatch (expected "pgh-tree-1")')
  }

  const state = { start: MAGIC.length, end: buf.length, buffer: buf }
  const count = c.uint.decode(state)
  const entries = []

  let prevName = null
  for (let i = 0; i < count; i++) {
    const kind = c.uint8.decode(state)
    const exec = c.uint8.decode(state)
    const name = c.string.decode(state)

    if (state.start + 32 > state.end) throw new Error('truncated tree: missing hash bytes')
    const childHash = buf.subarray(state.start, state.start + 32).toString('hex')
    state.start += 32

    // Validate format rules on read — reject invalid trees rather than silently accept
    const normalized = normalizeName(name)
    if (normalized !== name) {
      throw new Error('tree entry name not NFC-normalized: ' + JSON.stringify(name))
    }
    if (kind !== KIND_FILE && exec !== 0) {
      throw new Error('non-file entry with exec=1 is invalid')
    }
    if (prevName !== null) {
      const cmp = Buffer.compare(Buffer.from(prevName, 'utf8'), Buffer.from(name, 'utf8'))
      if (cmp === 0) throw new Error('tree has duplicate entry: ' + name)
      if (cmp > 0) throw new Error('tree entries not sorted: ' + prevName + ' before ' + name)
    }
    prevName = name

    entries.push({ kind, exec, name, childHash })
  }

  if (state.start !== state.end) throw new Error('tree has trailing bytes after entries')

  return entries
}

/**
 * Compute the tree hash of an entries list.
 *
 * @param {Array<{kind: number, exec: number, name: string, childHash: Buffer|string}>} entries
 * @returns {string} hex-encoded blake2b-256
 */
export function computeTreeHash (entries) {
  const buf = encodeTree(entries)
  return crypto.data(buf).toString('hex')
}

// ── Helpers ───────────────────────────────────────────────────

function toBuffer32 (hashOrBuf) {
  if (Buffer.isBuffer(hashOrBuf)) {
    if (hashOrBuf.length !== 32) throw new Error('childHash buffer must be 32 bytes')
    return hashOrBuf
  }
  if (typeof hashOrBuf !== 'string') {
    throw new Error('childHash must be Buffer or hex string')
  }
  if (hashOrBuf.length !== 64) throw new Error('childHash hex string must be 64 chars')
  return Buffer.from(hashOrBuf, 'hex')
}

// ── Filesystem walk ───────────────────────────────────────────

/**
 * Walk a directory recursively, producing tree hashes bottom-up.
 *
 * Returns a nested object keyed by path, where each entry has:
 *   { hash: hex, entries: [{kind, exec, name, childHash, size?}] }
 *
 * File entries carry their content hash as childHash (blake2b of bytes).
 * Dir entries carry the subtree hash.
 * Symlink entries carry blake2b of the link target bytes.
 *
 * @param {string} rootDir - absolute path to scan
 * @param {object} [opts]
 * @param {Set<string>} [opts.skip] - basenames to skip (default: DEFAULT_SKIP)
 * @param {(relPath: string, baseName: string) => boolean} [opts.matcher]
 *   Optional gitignore-style matcher. Returns true to EXCLUDE an entry.
 *   Receives the path relative to rootDir plus the basename. Applies to
 *   all kinds (file/dir/symlink). Used by `pgh publish` for publishIgnore.
 * @returns {Map<string, {hash: string, entries: Array, size: number}>}
 *          map keyed by relative path ('' = root); root tree is at key ''
 */
export function walkTree (rootDir, opts = {}) {
  const skip = opts.skip || DEFAULT_SKIP
  const matcher = opts.matcher || null
  const trees = new Map()

  function visit (relPath) {
    const absPath = relPath === '' ? rootDir : path.join(rootDir, relPath)
    const raw = fs.readdirSync(absPath)
    const entries = []
    let totalSize = 0

    for (const name of raw) {
      if (skip.has(name)) continue

      const entryAbs = path.join(absPath, name)
      const entryRel = relPath === '' ? name : relPath + '/' + name

      if (matcher && matcher(entryRel, name)) continue

      let stat
      try {
        stat = fs.lstatSync(entryAbs)
      } catch {
        continue
      }

      if (stat.isSymbolicLink()) {
        const target = fs.readlinkSync(entryAbs)
        const targetBytes = Buffer.from(target, 'utf8')
        const childHash = crypto.data(targetBytes).toString('hex')
        entries.push({
          kind: KIND_SYMLINK,
          exec: 0,
          name: normalizeName(name),
          childHash,
          size: targetBytes.length,
          linkTarget: target
        })
        totalSize += targetBytes.length
      } else if (stat.isDirectory()) {
        visit(entryRel)
        const sub = trees.get(entryRel)
        if (!sub) continue
        entries.push({
          kind: KIND_DIR,
          exec: 0,
          name: normalizeName(name),
          childHash: sub.hash,
          size: sub.size
        })
        totalSize += sub.size
      } else if (stat.isFile()) {
        const content = fs.readFileSync(entryAbs)
        const childHash = crypto.data(content).toString('hex')
        // Executable bit from stat.mode — works on POSIX; Windows always 0
        const exec = (stat.mode & 0o100) ? 1 : 0
        entries.push({
          kind: KIND_FILE,
          exec,
          name: normalizeName(name),
          childHash,
          size: stat.size
        })
        totalSize += stat.size
      }
      // device files, sockets, fifos: silently skipped (unrepresentable)
    }

    entries.sort(compareEntries)
    const hash = computeTreeHash(entries)
    trees.set(relPath, { hash, entries, size: totalSize })
  }

  visit('')
  return trees
}

// ── Publish-time validation (consumer policy) ─────────────────

/**
 * Scan entries (recursively via walkTree output) for cross-platform-hostile
 * names. Returns an array of {path, name, reason} for every problem found.
 * Does NOT throw — caller decides how to present.
 *
 * @param {Map<string, {hash: string, entries: Array}>} trees - from walkTree
 * @returns {Array<{path: string, name: string, reason: string}>}
 */
export function validateForPublish (trees) {
  const problems = []
  for (const [relPath, tree] of trees) {
    for (const e of tree.entries) {
      const reason = windowsIncompatibleReason(e.name)
      if (reason) {
        problems.push({
          path: relPath ? relPath + '/' + e.name : e.name,
          name: e.name,
          reason
        })
      }
    }
  }
  return problems
}
function isBuffer(value) {
  return Buffer.isBuffer(value) || value instanceof Uint8Array
}

function isEncoding(encoding) {
  return Buffer.isEncoding(encoding)
}

function alloc(size, fill, encoding) {
  return Buffer.alloc(size, fill, encoding)
}

function allocUnsafe(size) {
  return Buffer.allocUnsafe(size)
}

function allocUnsafeSlow(size) {
  return Buffer.allocUnsafeSlow(size)
}

function byteLength(string, encoding) {
  return Buffer.byteLength(string, encoding)
}

function compare(a, b) {
  return Buffer.compare(a, b)
}

function concat(buffers, totalLength) {
  return Buffer.concat(buffers, totalLength)
}

function copy(source, target, targetStart, start, end) {
  return toBuffer(source).copy(target, targetStart, start, end)
}

function equals(a, b) {
  return toBuffer(a).equals(b)
}

function fill(buffer, value, offset, end, encoding) {
  return toBuffer(buffer).fill(value, offset, end, encoding)
}

function from(value, encodingOrOffset, length) {
  return Buffer.from(value, encodingOrOffset, length)
}

function includes(buffer, value, byteOffset, encoding) {
  return toBuffer(buffer).includes(value, byteOffset, encoding)
}

function indexOf(buffer, value, byfeOffset, encoding) {
  return toBuffer(buffer).indexOf(value, byfeOffset, encoding)
}

function lastIndexOf(buffer, value, byteOffset, encoding) {
  return toBuffer(buffer).lastIndexOf(value, byteOffset, encoding)
}

function swap16(buffer) {
  return toBuffer(buffer).swap16()
}

function swap32(buffer) {
  return toBuffer(buffer).swap32()
}

function swap64(buffer) {
  return toBuffer(buffer).swap64()
}

function toBuffer(buffer) {
  if (Buffer.isBuffer(buffer)) return buffer
  return Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

function toString(buffer, encoding, start, end) {
  return toBuffer(buffer).toString(encoding, start, end)
}

function write(buffer, string, offset, length, encoding) {
  return toBuffer(buffer).write(string, offset, length, encoding)
}

function readDoubleBE(buffer, offset) {
  return toBuffer(buffer).readDoubleBE(offset)
}

function readDoubleLE(buffer, offset) {
  return toBuffer(buffer).readDoubleLE(offset)
}

function readFloatBE(buffer, offset) {
  return toBuffer(buffer).readFloatBE(offset)
}

function readFloatLE(buffer, offset) {
  return toBuffer(buffer).readFloatLE(offset)
}

function readInt32BE(buffer, offset) {
  return toBuffer(buffer).readInt32BE(offset)
}

function readInt32LE(buffer, offset) {
  return toBuffer(buffer).readInt32LE(offset)
}

function readUInt32BE(buffer, offset) {
  return toBuffer(buffer).readUInt32BE(offset)
}

function readUInt32LE(buffer, offset) {
  return toBuffer(buffer).readUInt32LE(offset)
}

function writeDoubleBE(buffer, value, offset) {
  return toBuffer(buffer).writeDoubleBE(value, offset)
}

function writeDoubleLE(buffer, value, offset) {
  return toBuffer(buffer).writeDoubleLE(value, offset)
}

function writeFloatBE(buffer, value, offset) {
  return toBuffer(buffer).writeFloatBE(value, offset)
}

function writeFloatLE(buffer, value, offset) {
  return toBuffer(buffer).writeFloatLE(value, offset)
}

function writeInt32BE(buffer, value, offset) {
  return toBuffer(buffer).writeInt32BE(value, offset)
}

function writeInt32LE(buffer, value, offset) {
  return toBuffer(buffer).writeInt32LE(value, offset)
}

function writeUInt32BE(buffer, value, offset) {
  return toBuffer(buffer).writeUInt32BE(value, offset)
}

function writeUInt32LE(buffer, value, offset) {
  return toBuffer(buffer).writeUInt32LE(value, offset)
}

module.exports = {
  isBuffer,
  isEncoding,
  alloc,
  allocUnsafe,
  allocUnsafeSlow,
  byteLength,
  compare,
  concat,
  copy,
  equals,
  fill,
  from,
  includes,
  indexOf,
  lastIndexOf,
  swap16,
  swap32,
  swap64,
  toBuffer,
  toString,
  write,
  readDoubleBE,
  readDoubleLE,
  readFloatBE,
  readFloatLE,
  readInt32BE,
  readInt32LE,
  readUInt32BE,
  readUInt32LE,
  writeDoubleBE,
  writeDoubleLE,
  writeFloatBE,
  writeFloatLE,
  writeInt32BE,
  writeInt32LE,
  writeUInt32BE,
  writeUInt32LE
}
{
  "name": "b4a",
  "version": "1.8.1",
  "description": "Bridging the gap between buffers and typed arrays",
  "exports": {
    "./package": "./package.json",
    ".": {
      "react-native": "./react-native.js",
      "browser": "./browser.js",
      "default": "./index.js"
    }
  },
  "files": [
    "browser.js",
    "index.js",
    "react-native.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:bare && npm run test:node",
    "test:bare": "brittle-bare --coverage test.mjs",
    "test:node": "brittle-node --coverage test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/b4a.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/b4a/issues"
  },
  "homepage": "https://github.com/holepunchto/b4a#readme",
  "devDependencies": {
    "brittle": "^3.5.2",
    "lunte": "^1.7.0",
    "nanobench": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "react-native-b4a": "*"
  },
  "peerDependenciesMeta": {
    "react-native-b4a": {
      "optional": true
    }
  }
}
const ESC = '\x1b'
const CSI = ESC + '['
const SGR = (n) => CSI + n + 'm'

exports.constants = {
  ESC,
  CSI,
  SGR
}

// https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_(Control_Sequence_Introducer)_sequences

exports.cursorHide = CSI + '?25l'
exports.cursorShow = CSI + '?25h'

exports.cursorUp = function cursorUp(n = 1) {
  return CSI + n + 'A'
}

exports.cursorDown = function cursorDown(n = 1) {
  return CSI + n + 'B'
}

exports.cursorForward = function cursorForward(n = 1) {
  return CSI + n + 'C'
}

exports.cursorBack = function cursorBack(n = 1) {
  return CSI + n + 'D'
}

exports.cursorNextLine = function cursorNextLine(n = 1) {
  return CSI + n + 'E'
}

exports.cursorPreviousLine = function cursorPreviousLine(n = 1) {
  return CSI + n + 'F'
}

exports.cursorPosition = function cursorPosition(column, row = 0) {
  if (row === 0) return CSI + (column + 1) + 'G'

  return CSI + (row + 1) + ';' + (column + 1) + 'H'
}

exports.eraseDisplayEnd = CSI + 'J'
exports.eraseDisplayStart = CSI + '1J'
exports.eraseDisplay = CSI + '2J'
exports.eraseLineEnd = CSI + 'K'
exports.eraseLineStart = CSI + '1K'
exports.eraseLine = CSI + '2K'

exports.scrollUp = function scrollUp(n = 1) {
  return CSI + n + 'S'
}

exports.scrollDown = function scrollDown(n = 1) {
  return CSI + n + 'T'
}

// https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_(Select_Graphic_Rendition)_parameters

exports.modifierReset = SGR(0)
exports.modifierBold = SGR(1)
exports.modifierDim = SGR(2)
exports.modifierItalic = SGR(3)
exports.modifierUnderline = SGR(4)
exports.modifierNormal = SGR(22)
exports.modifierNotItalic = SGR(23)
exports.modifierNotUnderline = SGR(24)

// https://en.wikipedia.org/wiki/ANSI_escape_code#Colors

exports.colorBlack = SGR(30)
exports.colorRed = SGR(31)
exports.colorGreen = SGR(32)
exports.colorYellow = SGR(33)
exports.colorBlue = SGR(34)
exports.colorMagenta = SGR(35)
exports.colorCyan = SGR(36)
exports.colorWhite = SGR(37)
exports.colorDefault = SGR(39)
exports.colorBrightBlack = SGR(90)
exports.colorBrightRed = SGR(91)
exports.colorBrightGreen = SGR(92)
exports.colorBrightYellow = SGR(93)
exports.colorBrightBlue = SGR(94)
exports.colorBrightMagenta = SGR(95)
exports.colorBrightCyan = SGR(96)
exports.colorBrightWhite = SGR(97)
{
  "name": "bare-ansi-escapes",
  "version": "2.2.3",
  "description": "Parse and produce ANSI escape sequences",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./key-decoder": {
      "types": "./key-decoder.d.ts",
      "default": "./key-decoder.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "key-decoder.js",
    "key-decoder.d.ts"
  ],
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-ansi-escapes.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-ansi-escapes/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-ansi-escapes#readme",
  "dependencies": {
    "bare-stream": "^2.6.5"
  },
  "devDependencies": {
    "bare-buffer": "^3.0.2",
    "brittle": "^3.3.2",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  },
  "peerDependencies": {
    "bare-buffer": "*"
  },
  "peerDependenciesMeta": {
    "bare-buffer": {
      "optional": true
    }
  }
}
const inspect = require('bare-inspect')

class AssertionError extends Error {
  constructor(opts = {}) {
    let { message = null, actual, expected, operator } = opts

    if (message === null) {
      message = `${inspect(actual)} ${operator} ${inspect(expected)}`
    }

    super(message)

    this.actual = actual
    this.expected = expected
    this.operator = operator
  }

  get name() {
    return 'AssertionError'
  }

  get code() {
    'ASSERTION'
  }
}

function assertFail(opts, fn) {
  if (opts.message instanceof Error) throw opts.message

  const err = new AssertionError(opts)

  if (Error.captureStackTrace) Error.captureStackTrace(err, fn)

  throw err
}

module.exports = exports = function assert(actual, message) {
  if (actual) return

  assertFail({ message, actual, expected: true, operator: '==' }, assert)
}

exports.AssertionError = AssertionError

exports.fail = function fail(message) {
  if (message === undefined) message = 'Failed'

  assertFail({ message, operator: 'fail' }, fail)
}

exports.ok = function ok(actual, message) {
  if (actual) return

  assertFail({ message, actual, expected: true, operator: '==' }, ok)
}

exports.notOk = function ok(actual, message) {
  if (!actual) return

  assertFail({ message, actual, expected: false, operator: '==' }, ok)
}

exports.equal = function equal(actual, expected, message) {
  if (actual == expected || (actual !== actual && expected !== expected)) {
    return
  }

  assertFail({ message, actual, expected, operator: '==' }, equal)
}

exports.notEqual = function notEqual(actual, expected, message) {
  if (actual != expected && (actual === actual || expected === expected)) {
    return
  }

  assertFail({ message, actual, expected, operator: '!=' }, notEqual)
}

exports.strictEqual = function strictEqual(actual, expected, message) {
  if (Object.is(actual, expected)) return

  assertFail(
    { message, actual, expected, operator: 'strictEqual' },
    strictEqual
  )
}

exports.notStrictEqual = function notStrictEqual(actual, expected, message) {
  if (!Object.is(actual, expected)) return

  assertFail(
    { message, actual, expected, operator: 'notStrictEqual' },
    notStrictEqual
  )
}
{
  "name": "bare-assert",
  "version": "1.2.0",
  "description": "Assertion library for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts"
  ],
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-assert.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-assert/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-assert#readme",
  "dependencies": {
    "bare-inspect": "^3.1.2"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  }
}
const errors = require('./lib/errors')

class EventListener {
  constructor() {
    this.list = []
    this.count = 0
  }

  append(ctx, name, fn, once) {
    this.count++
    ctx.emit('newListener', name, fn) // Emit BEFORE adding
    this.list.push([fn, once])
  }

  prepend(ctx, name, fn, once) {
    this.count++
    ctx.emit('newListener', name, fn) // Emit BEFORE adding
    this.list.unshift([fn, once])
  }

  remove(ctx, name, fn) {
    for (let i = 0, n = this.list.length; i < n; i++) {
      const l = this.list[i]

      if (l[0] === fn) {
        this.list.splice(i, 1)

        if (this.count === 1) delete ctx._events[name]

        ctx.emit('removeListener', name, fn) // Emit AFTER removing

        this.count--
        return
      }
    }
  }

  removeAll(ctx, name) {
    const list = [...this.list]
    this.list = []

    if (this.count === list.length) delete ctx._events[name]

    for (let i = list.length - 1; i >= 0; i--) {
      ctx.emit('removeListener', name, list[i][0]) // Emit AFTER removing
    }

    this.count -= list.length
  }

  emit(ctx, name, ...args) {
    const list = [...this.list]

    for (let i = 0, n = list.length; i < n; i++) {
      const l = list[i]

      if (l[1] === true) this.remove(ctx, name, l[0])

      Reflect.apply(l[0], ctx, args)
    }

    return list.length > 0
  }
}

function appendListener(ctx, name, fn, once) {
  if (ctx._events === undefined) ctx._events = Object.create(null)
  const e = ctx._events[name] || (ctx._events[name] = new EventListener())
  e.append(ctx, name, fn, once)
  return ctx
}

function prependListener(ctx, name, fn, once) {
  if (ctx._events === undefined) ctx._events = Object.create(null)
  const e = ctx._events[name] || (ctx._events[name] = new EventListener())
  e.prepend(ctx, name, fn, once)
  return ctx
}

function removeListener(ctx, name, fn) {
  if (ctx._events === undefined) return ctx
  const e = ctx._events[name]
  if (e !== undefined) e.remove(ctx, name, fn)
  return ctx
}

function throwUnhandledError(...args) {
  let err

  if (args.length > 0) err = args[0]

  if (err instanceof Error === false) err = errors.UNHANDLED_ERROR(err)

  if (Error.captureStackTrace) {
    Error.captureStackTrace(err, exports.prototype.emit)
  }

  queueMicrotask(() => {
    throw err
  })
}

module.exports = exports = class EventEmitter {
  constructor() {
    this._events = Object.create(null)
  }

  addListener(name, fn) {
    return appendListener(this, name, fn, false)
  }

  addOnceListener(name, fn) {
    return appendListener(this, name, fn, true)
  }

  prependListener(name, fn) {
    return prependListener(this, name, fn, false)
  }

  prependOnceListener(name, fn) {
    return prependListener(this, name, fn, true)
  }

  removeListener(name, fn) {
    return removeListener(this, name, fn)
  }

  on(name, fn) {
    return appendListener(this, name, fn, false)
  }

  once(name, fn) {
    return appendListener(this, name, fn, true)
  }

  off(name, fn) {
    return removeListener(this, name, fn)
  }

  emit(name, ...args) {
    if (name === 'error' && this._events !== undefined && this._events.error === undefined) {
      throwUnhandledError(...args)
    }

    if (this._events === undefined) return false
    const e = this._events[name]
    return e === undefined ? false : e.emit(this, name, ...args)
  }

  listeners(name) {
    if (this._events === undefined) return []
    const e = this._events[name]
    return e === undefined ? [] : [...e.list]
  }

  rawListeners(name) {
    if (this._events === undefined) return []
    const e = this._events[name]
    return e === undefined ? [] : e.list.map((l) => l[0])
  }

  eventNames() {
    if (this._events === undefined) return []
    return Reflect.ownKeys(this._events)
  }

  listenerCount(name) {
    if (this._events === undefined) return 0
    const e = this._events[name]
    return e === undefined ? 0 : e.list.length
  }

  getMaxListeners() {
    return EventEmitter.defaultMaxListeners
  }

  setMaxListeners(n) {}

  removeAllListeners(name) {
    if (arguments.length === 0) {
      for (const key of Reflect.ownKeys(this._events)) {
        if (key === 'removeListener') continue
        this.removeAllListeners(key)
      }
      this.removeAllListeners('removeListener')
    } else {
      const e = this._events[name]
      if (e !== undefined) e.removeAll(this, name)
    }
    return this
  }
}

exports.EventEmitter = exports

exports.errors = errors

exports.defaultMaxListeners = 10

exports.on = function on(emitter, name, opts = {}) {
  const { signal } = opts

  if (signal && signal.aborted) {
    throw errors.OPERATION_ABORTED(signal.reason)
  }

  let error = null
  let done = false

  const events = []
  const promises = []

  if (name !== 'error') emitter.on('error', onerror)

  if (signal) signal.addEventListener('abort', onabort)

  emitter.on(name, onevent)

  return {
    next() {
      if (events.length) {
        return Promise.resolve({ value: events.shift(), done: false })
      }

      if (error) {
        const err = error

        error = null

        return Promise.reject(err)
      }

      if (done) return onclose()

      return new Promise((resolve, reject) => promises.push({ resolve, reject }))
    },

    return() {
      return onclose()
    },

    throw(err) {
      return onerror(err)
    },

    [Symbol.asyncIterator]() {
      return this
    }
  }

  function onevent(...args) {
    if (promises.length) {
      promises.shift().resolve({ value: args, done: false })
    } else {
      events.push(args)
    }
  }

  function onerror(err) {
    emitter.off(name, onevent).off('error', onerror)

    if (promises.length) {
      promises.shift().reject(err)
    } else {
      error = err
    }

    return Promise.resolve({ done: true })
  }

  function onabort() {
    signal.removeEventListener('abort', onabort)

    onerror(errors.OPERATION_ABORTED(signal.reason))
  }

  function onclose() {
    emitter.off(name, onevent)

    if (name !== 'error') emitter.off('error', onerror)

    if (signal) signal.removeEventListener('abort', onabort)

    done = true

    if (promises.length) promises.shift().resolve({ done: true })

    return Promise.resolve({ done: true })
  }
}

exports.once = function once(emitter, name, opts = {}) {
  const { signal } = opts

  if (signal && signal.aborted) {
    return Promise.reject(errors.OPERATION_ABORTED(signal.reason))
  }

  return new Promise((resolve, reject) => {
    if (name !== 'error') emitter.on('error', onerror)

    if (signal) signal.addEventListener('abort', onabort)

    emitter.once(name, onevent)

    function onevent(...args) {
      if (name !== 'error') emitter.off('error', onerror)

      if (signal) signal.removeEventListener('abort', onabort)

      resolve(args)
    }

    function onerror(err) {
      emitter.off(name, onevent)

      if (name !== 'error') emitter.off('error', onerror)

      reject(err)
    }

    function onabort() {
      signal.removeEventListener('abort', onabort)

      onerror(errors.OPERATION_ABORTED(signal.reason))
    }
  })
}

exports.forward = function forward(from, to, names, opts = {}) {
  if (typeof names === 'string') names = [names]

  const { emit = to.emit.bind(to) } = opts

  const listeners = names.map(
    (name) =>
      function onevent(...args) {
        emit(name, ...args)
      }
  )

  to.on('newListener', (name) => {
    const i = names.indexOf(name)

    if (i !== -1 && to.listenerCount(name) === 0) {
      from.on(name, listeners[i])
    }
  }).on('removeListener', (name) => {
    const i = names.indexOf(name)

    if (i !== -1 && to.listenerCount(name) === 0) {
      from.off(name, listeners[i])
    }
  })
}

exports.listenerCount = function listenerCount(emitter, name) {
  return emitter.listenerCount(name)
}

exports.getMaxListeners = function getMaxListeners(emitter) {
  if (typeof emitter.getMaxListeners === 'function') {
    return emitter.getMaxListeners()
  }

  return exports.defaultMaxListeners
}

exports.setMaxListeners = function setMaxListeners(n, ...emitters) {
  if (emitters.length === 0) exports.defaultMaxListeners = n
  else {
    for (const emitter of emitters) {
      if (typeof emitter.setMaxListeners === 'function') {
        emitter.setMaxListeners(n)
      }
    }
  }
}
module.exports = class EventEmitterError extends Error {
  constructor(msg, code, fn = EventEmitterError, opts) {
    super(`${code}: ${msg}`, opts)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'EventEmitterError'
  }

  static OPERATION_ABORTED(cause, msg = 'Operation aborted') {
    return new EventEmitterError(msg, 'OPERATION_ABORTED', EventEmitterError.OPERATION_ABORTED, {
      cause
    })
  }

  static UNHANDLED_ERROR(cause, msg = 'Unhandled error') {
    return new EventEmitterError(msg, 'UNHANDLED_ERROR', EventEmitterError.UNHANDLED_ERROR, {
      cause
    })
  }
}
{
  "name": "bare-events",
  "version": "2.9.1",
  "description": "Event emitters for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    },
    "./web": {
      "types": "./web.d.ts",
      "default": "./web.js"
    },
    "./errors": "./lib/errors.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "global.js",
    "global.d.ts",
    "web.js",
    "web.d.ts",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:bare && npm run test:node",
    "test:bare": "brittle-bare --coverage test.js",
    "test:node": "brittle-node --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-events.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-events/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-events#readme",
  "devDependencies": {
    "bare-abort-controller": "^1.0.0",
    "brittle": "^3.3.2",
    "lunte": "^1.8.0",
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^2.0.0",
    "uncaughts": "^1.1.1"
  },
  "peerDependencies": {
    "bare-abort-controller": "*"
  },
  "peerDependenciesMeta": {
    "bare-abort-controller": {
      "optional": true
    }
  }
}
module.exports = require.addon()
const FIFO = require('fast-fifo')
const EventEmitter = require('bare-events')
const path = require('bare-path')
const { isURL, fileURLToPath } = require('bare-url')
const { Readable, Writable } = require('bare-stream')
const binding = require('./binding')
const constants = require('./lib/constants')
const FileError = require('./lib/errors')

const isWindows = Bare.platform === 'win32'

exports.constants = constants

class FileRequest {
  static borrow() {
    if (this._free.length > 0) return this._free.pop()
    return new FileRequest()
  }

  static return(req) {
    if (this._free.length < 32) this._free.push(req.reset())
    else req.destroy()
  }

  constructor() {
    this._reset()
    this._handle = binding.requestInit(this, this._onresult)
  }

  get handle() {
    return this._handle
  }

  retain(value) {
    this._retain = value // Tie the lifetime of `value` to the lifetime of `this`
  }

  reset() {
    if (this._handle === null) return this

    binding.requestReset(this._handle)

    this._reset()

    return this
  }

  destroy() {
    if (this._handle === null) return this

    binding.requestDestroy(this._handle)

    this._reset()
    this._handle = null

    return this
  }

  then(resolve, reject) {
    return this._promise.then(resolve, reject)
  }

  return() {
    if (this._handle === null) return this

    FileRequest.return(this)

    return this
  }

  _reset() {
    this._promise = new Promise((resolve, reject) => {
      this._resolve = resolve
      this._reject = reject
    })
    this._retain = null
  }

  _onresult(err, status) {
    if (err) this._reject(err)
    else this._resolve(status)
  }
}

FileRequest._free = []

function ok(result, cb) {
  if (typeof result === 'function') {
    cb = result
    result = undefined
  }

  if (cb) cb(null, result)
  else return result
}

function fail(err, cb) {
  if (cb) cb(err)
  else throw err
}

function done(err, result, cb) {
  if (typeof result === 'function') {
    cb = result
    result = undefined
  }

  if (err) fail(err, cb)
  else return ok(result, cb)
}

async function open(filepath, flags = 'r', mode = 0o666, cb) {
  if (typeof flags === 'function') {
    cb = flags
    flags = 'r'
    mode = 0o666
  } else if (typeof mode === 'function') {
    cb = mode
    mode = 0o666
  }

  if (typeof flags === 'string') flags = toFlags(flags)
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let fd
  let err = null
  try {
    binding.open(req.handle, filepath, flags, mode)

    fd = await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'open',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, fd, cb)
}

function openSync(filepath, flags = 'r', mode = 0o666) {
  if (typeof flags === 'string') flags = toFlags(flags)
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    return binding.openSync(req.handle, filepath, flags, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'open',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function close(fd, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.close(req.handle, fd)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'close', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function closeSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.closeSync(req.handle, fd)
  } catch (e) {
    throw new FileError(e.message, { operation: 'close', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function access(filepath, mode = constants.F_OK, cb) {
  if (typeof mode === 'function') {
    cb = mode
    mode = constants.F_OK
  }

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.access(req.handle, filepath, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'access',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function accessSync(filepath, mode = constants.F_OK) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.accessSync(req.handle, filepath, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'access',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function exists(filepath, cb) {
  let ok = true
  try {
    await access(filepath)
  } catch {
    ok = false
  }

  return done(null, ok, cb)
}

function existsSync(filepath) {
  try {
    accessSync(filepath)
  } catch {
    return false
  }

  return true
}

async function read(fd, buffer, offset = 0, len = buffer.byteLength - offset, pos = -1, cb) {
  if (typeof offset === 'function') {
    cb = offset
    offset = 0
    len = buffer.byteLength
    pos = -1
  } else if (typeof len === 'function') {
    cb = len
    len = buffer.byteLength - offset
    pos = -1
  } else if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.read(req.handle, fd, buffer, offset, len, pos)

    req.retain(buffer)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'read', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function readSync(fd, buffer, offset = 0, len = buffer.byteLength - offset, pos = -1) {
  const req = FileRequest.borrow()

  try {
    return binding.readSync(req.handle, fd, buffer, offset, len, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'read', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function readv(fd, buffers, pos = -1, cb) {
  if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.readv(req.handle, fd, buffers, pos)

    req.retain(buffers)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'readv', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function readvSync(fd, buffers, pos = -1) {
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  try {
    return binding.readvSync(req.handle, fd, buffers, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'readv', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function write(fd, data, offset, len, pos = -1, cb) {
  if (typeof data === 'string') {
    let encoding = len
    cb = pos
    pos = offset

    if (typeof pos === 'function') {
      cb = pos
      pos = -1
      encoding = 'utf8'
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = 'utf8'
    }

    if (typeof pos === 'string') {
      encoding = pos
      pos = -1
    }

    data = Buffer.from(data, encoding)
    offset = 0
    len = data.byteLength
  } else if (typeof offset === 'function') {
    cb = offset
    offset = 0
    len = data.byteLength
    pos = -1
  } else if (typeof len === 'function') {
    cb = len
    len = data.byteLength - offset
    pos = -1
  } else if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof offset !== 'number') offset = 0
  if (typeof len !== 'number') len = data.byteLength - offset
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.write(req.handle, fd, data, offset, len, pos)

    req.retain(data)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'write', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function writeSync(fd, data, offset, len, pos = -1) {
  if (typeof data === 'string') {
    let encoding = len
    pos = offset

    if (typeof pos === 'string') {
      encoding = pos
      pos = -1
    }

    data = Buffer.from(data, encoding)
    offset = 0
    len = data.byteLength
  }

  if (typeof offset !== 'number') offset = 0
  if (typeof len !== 'number') len = data.byteLength - offset
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  try {
    return binding.writeSync(req.handle, fd, data, offset, len, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'write', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function writev(fd, buffers, pos = -1, cb) {
  if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.writev(req.handle, fd, buffers, pos)

    req.retain(buffers)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'writev', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function writevSync(fd, buffers, pos = -1) {
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  try {
    return binding.writevSync(req.handle, fd, buffers, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'writev', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function stat(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.stat(req.handle, filepath)

    await req

    st = new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'stat', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function statSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.statSync(req.handle, filepath)

    return new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'stat', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function lstat(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.lstat(req.handle, filepath)

    await req

    st = new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'lstat', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function lstatSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.lstatSync(req.handle, filepath)

    return new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'lstat', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function fstat(fd, cb) {
  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.fstat(req.handle, fd)

    await req

    st = new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'fstat', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function fstatSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.fstatSync(req.handle, fd)

    return new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'fstat', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function statfs(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.statfs(req.handle, filepath)

    await req

    st = new StatFs(...binding.requestResultStatfs(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'statfs', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function statfsSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.statfsSync(req.handle, filepath)

    return new StatFs(...binding.requestResultStatfs(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'statfs', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function ftruncate(fd, len = 0, cb) {
  if (typeof len === 'function') {
    cb = len
    len = 0
  }

  if (typeof len !== 'number') len = 0

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.ftruncate(req.handle, fd, len)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'ftruncate', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function ftruncateSync(fd, len = 0) {
  if (typeof len !== 'number') len = 0

  const req = FileRequest.borrow()

  try {
    binding.ftruncateSync(req.handle, fd, len)
  } catch (e) {
    throw new FileError(e.message, { operation: 'ftruncate', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function truncate(filepath, len, cb) {
  let fd = -1
  let err

  try {
    fd = await open(filepath, 'r+')

    await ftruncate(fd, len)
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) await close(fd)
  }

  return done(err, cb)
}

function truncateSync(filepath, len) {
  let fd = -1
  let err

  try {
    fd = openSync(filepath, 'r+')

    ftruncateSync(fd, len)
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) closeSync(fd)
  }
}

async function chmod(filepath, mode, cb) {
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.chmod(req.handle, filepath, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'chmod',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function chmodSync(filepath, mode) {
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.chmodSync(req.handle, filepath, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'chmod',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function fchmod(fd, mode, cb) {
  if (typeof mode === 'string') mode = toMode(mode)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fchmod(req.handle, fd, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fchmod', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fchmodSync(fd, mode) {
  if (typeof mode === 'string') mode = toMode(mode)

  const req = FileRequest.borrow()

  try {
    binding.fchmodSync(req.handle, fd, mode)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fchmod', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function chown(filepath, uid, gid, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.chown(req.handle, filepath, uid, gid)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'chown', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function chownSync(filepath, uid, gid) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.chownSync(req.handle, filepath, uid, gid)
  } catch (e) {
    throw new FileError(e.message, { operation: 'chownSync', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function lchown(filepath, uid, gid, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.lchown(req.handle, filepath, uid, gid)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'lchown', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function lchownSync(filepath, uid, gid) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.lchownSync(req.handle, filepath, uid, gid)
  } catch (e) {
    throw new FileError(e.message, { operation: 'lchownSync', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function fchown(fd, uid, gid, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fchown(req.handle, fd, uid, gid)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fchown', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fchownSync(fd, uid, gid) {
  const req = FileRequest.borrow()

  try {
    binding.fchownSync(req.handle, fd, uid, gid)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fchownSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function utimes(filepath, atime, mtime, cb) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.utimes(req.handle, filepath, atime, mtime)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'utimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function utimesSync(filepath, atime, mtime) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.utimesSync(req.handle, filepath, atime, mtime)
  } catch (e) {
    throw new FileError(e.message, { operation: 'utimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function lutimes(filepath, atime, mtime, cb) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.lutimes(req.handle, filepath, atime, mtime)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'lutimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function lutimesSync(filepath, atime, mtime) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.lutimesSync(req.handle, filepath, atime, mtime)
  } catch (e) {
    throw new FileError(e.message, { operation: 'lutimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function futimes(fd, atime, mtime, cb) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.futimes(req.handle, fd, atime, mtime)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'futimes', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function futimesSync(fd, atime, mtime) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  const req = FileRequest.borrow()

  try {
    binding.futimesSync(req.handle, fd, atime, mtime)
  } catch (e) {
    throw new FileError(e.message, { operation: 'futimesSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function link(src, dst, cb) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.link(req.handle, src, dst)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'link', code: e.code, path: src, destination: dst })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function linkSync(src, dst) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  try {
    binding.linkSync(req.handle, src, dst)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'linkSync',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }
}

async function mkdir(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = { mode: 0o777 }
  }

  if (typeof opts === 'number') opts = { mode: opts }
  else if (!opts) opts = {}

  const mode = typeof opts.mode === 'number' ? opts.mode : 0o777

  filepath = toNamespacedPath(filepath)

  if (opts.recursive) {
    let err = null
    try {
      try {
        await mkdir(filepath, { mode })
      } catch (err) {
        if (err.code !== 'ENOENT') {
          if (!(await stat(filepath)).isDirectory()) throw err
        } else {
          while (filepath.endsWith(path.sep)) filepath = filepath.slice(0, -1)
          const i = filepath.lastIndexOf(path.sep)
          if (i <= 0) throw err

          await mkdir(filepath.slice(0, i), { mode, recursive: true })

          try {
            await mkdir(filepath, { mode })
          } catch (err) {
            if (!(await stat(filepath)).isDirectory()) throw err
          }
        }
      }
    } catch (e) {
      err = e
    }

    return done(err, cb)
  }

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.mkdir(req.handle, filepath, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'mkdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function mkdirSync(filepath, opts) {
  if (typeof opts === 'number') opts = { mode: opts }
  else if (!opts) opts = {}

  const mode = typeof opts.mode === 'number' ? opts.mode : 0o777

  filepath = toNamespacedPath(filepath)

  if (opts.recursive) {
    try {
      mkdirSync(filepath, { mode })
    } catch (err) {
      if (err.code !== 'ENOENT') {
        if (!statSync(filepath).isDirectory()) throw err
      } else {
        while (filepath.endsWith(path.sep)) filepath = filepath.slice(0, -1)
        const i = filepath.lastIndexOf(path.sep)
        if (i <= 0) throw err

        mkdirSync(filepath.slice(0, i), { mode, recursive: true })

        try {
          mkdirSync(filepath, { mode })
        } catch (err) {
          if (!statSync(filepath).isDirectory()) throw err
        }
      }
    }

    return
  }

  const req = FileRequest.borrow()

  try {
    binding.mkdirSync(req.handle, filepath, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'mkdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function mkdtemp(prefix, cb) {
  prefix = toNamespacedPath(prefix)

  const req = FileRequest.borrow()

  let res
  let err = null
  try {
    binding.mkdtemp(req.handle, prefix + 'XXXXXX')

    await req

    res = binding.requestResultPath(req.handle)
  } catch (e) {
    err = new FileError(e.message, { operation: 'mkdtemp', code: e.code, path: prefix })
  } finally {
    req.return()
  }

  return done(err, res, cb)
}

function mkdtempSync(prefix) {
  prefix = toNamespacedPath(prefix)

  const req = FileRequest.borrow()

  try {
    binding.mkdtempSync(req.handle, prefix + 'XXXXXX')

    return binding.requestResultPath(req.handle)
  } catch (e) {
    throw new FileError(e.message, { operation: 'mkdtempSync', code: e.code, path: prefix })
  } finally {
    req.return()
  }
}

async function rmdir(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.rmdir(req.handle, filepath)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'rmdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function rmdirSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.rmdirSync(req.handle, filepath)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'rmdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function rm(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  let err = null
  try {
    const st = await lstat(filepath)

    if (st.isDirectory()) {
      if (opts.recursive) {
        try {
          await rmdir(filepath)
        } catch (err) {
          if (err.code !== 'ENOTEMPTY') throw err

          const files = await readdir(filepath)

          for (const file of files) {
            await rm(filepath + path.sep + file, opts)
          }

          await rmdir(filepath)
        }
      } else {
        throw new FileError('is a directory', {
          operation: 'rm',
          code: 'EISDIR',
          path: filepath
        })
      }
    } else {
      await unlink(filepath)
    }
  } catch (e) {
    if (e.code !== 'ENOENT' || !opts.force) err = e
  }

  return done(err, cb)
}

function rmSync(filepath, opts) {
  if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  try {
    const st = lstatSync(filepath)

    if (st.isDirectory()) {
      if (opts.recursive) {
        try {
          rmdirSync(filepath)
        } catch (err) {
          if (err.code !== 'ENOTEMPTY') throw err

          const files = readdirSync(filepath)

          for (const file of files) {
            rmSync(filepath + path.sep + file, opts)
          }

          rmdirSync(filepath)
        }
      } else {
        throw new FileError('is a directory', {
          operation: 'rm',
          code: 'EISDIR',
          path: filepath
        })
      }
    } else {
      unlinkSync(filepath)
    }
  } catch (err) {
    if (err.code !== 'ENOENT' || !opts.force) throw err
  }
}

async function unlink(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.unlink(req.handle, filepath)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'unlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function unlinkSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.unlinkSync(req.handle, filepath)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'unlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function rename(src, dst, cb) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.rename(req.handle, src, dst)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'rename',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function renameSync(src, dst) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  try {
    binding.renameSync(req.handle, src, dst)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'rename',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }
}

async function copyFile(src, dst, mode = 0, cb) {
  if (typeof mode === 'function') {
    cb = mode
    mode = 0
  }

  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.copyfile(req.handle, src, dst, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'copyfile',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function copyFileSync(src, dst, mode = 0) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  try {
    binding.copyfileSync(req.handle, src, dst, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'copyfile',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }
}

async function cp(src, dst, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (!opts) opts = {}

  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  let err = null
  try {
    const st = await lstat(src)

    if (st.isDirectory()) {
      if (opts.recursive !== true) {
        throw new FileError('is a directory', { operation: 'cp', code: 'EISDIR', path: src })
      }

      try {
        await lstat(dst)
      } catch (e) {
        if (e.code !== 'ENOENT') throw e

        await mkdir(dst, { mode: st.mode, recursive: true })
      }

      const dir = await opendir(src)
      for await (const { name } of dir) {
        await cp(path.join(src, name), path.join(dst, name), opts)
      }
    } else if (st.isFile()) {
      await copyFile(src, dst)
      await chmod(dst, st.mode)
    }
  } catch (e) {
    err = e
  }

  return done(err, cb)
}

function cpSync(src, dst, opts = {}) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const st = lstatSync(src)

  if (st.isDirectory()) {
    if (opts.recursive !== true) {
      throw new FileError('is a directory', { operation: 'cp', code: 'EISDIR', path: src })
    }

    try {
      lstatSync(dst)
    } catch (e) {
      if (e.code !== 'ENOENT') throw e

      mkdirSync(dst, { mode: st.mode, recursive: true })
    }

    const dir = opendirSync(src)
    for (const { name } of dir) {
      cpSync(path.join(src, name), path.join(dst, name), opts)
    }
  } else if (st.isFile()) {
    copyFileSync(src, dst)
    chmodSync(dst, st.mode)
  }
}

async function realpath(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let res
  let err = null
  try {
    binding.realpath(req.handle, filepath)

    await req

    res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'realpath',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, res, cb)
}

function realpathSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.realpathSync(req.handle, filepath)

    let res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)

    return res
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'realpath',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function readlink(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let res
  let err = null
  try {
    binding.readlink(req.handle, filepath)

    await req

    res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'readlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, res, cb)
}

function readlinkSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.readlinkSync(req.handle, filepath)

    let res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)

    return res
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'readlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function fsync(fd, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fsync(req.handle, fd)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fsync', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fsyncSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.fsyncSync(req.handle, fd)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fsyncSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function fdatasync(fd, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fdatasync(req.handle, fd)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fdatasync', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fdatasyncSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.fdatasyncSync(req.handle, fd)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fdatasyncSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

function normalizeSymlinkTarget(target, type, filepath) {
  if (isWindows) {
    if (type === constants.UV_FS_SYMLINK_JUNCTION) target = path.resolve(filepath, '..', target)

    if (path.isAbsolute(target)) return path.toNamespacedPath(target)

    return target.replace(/\//g, path.sep)
  }

  return target
}

async function symlink(target, filepath, type, cb) {
  if (typeof type === 'function') {
    cb = type
    type = null
  }

  filepath = toNamespacedPath(filepath)

  if (typeof type === 'string') {
    switch (type) {
      case 'dir':
        type = constants.UV_FS_SYMLINK_DIR
        break
      case 'junction':
        type = constants.UV_FS_SYMLINK_JUNCTION
        break
      case 'file':
      default:
        type = 0
        break
    }
  } else if (typeof type !== 'number') {
    if (isWindows) {
      target = path.resolve(filepath, '..', target)

      try {
        type = (await stat(target)).isDirectory()
          ? constants.UV_FS_SYMLINK_DIR
          : constants.UV_FS_SYMLINK_JUNCTION
      } catch {
        type = 0
      }
    } else {
      type = 0
    }
  }

  target = normalizeSymlinkTarget(target, type, filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.symlink(req.handle, target, filepath, type)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'symlink',
      code: e.code,
      path: target,
      destination: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function symlinkSync(target, filepath, type) {
  filepath = toNamespacedPath(filepath)

  if (typeof type === 'string') {
    switch (type) {
      case 'dir':
        type = constants.UV_FS_SYMLINK_DIR
        break
      case 'junction':
        type = constants.UV_FS_SYMLINK_JUNCTION
        break
      case 'file':
      default:
        type = 0
        break
    }
  } else if (typeof type !== 'number') {
    if (isWindows) {
      target = path.resolve(filepath, '..', target)

      try {
        type = statSync(target).isDirectory()
          ? constants.UV_FS_SYMLINK_DIR
          : constants.UV_FS_SYMLINK_JUNCTION
      } catch {
        type = 0
      }
    } else {
      type = 0
    }
  }

  target = normalizeSymlinkTarget(target, type, filepath)

  const req = FileRequest.borrow()

  try {
    binding.symlinkSync(req.handle, target, filepath, type)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'symlink',
      code: e.code,
      path: target,
      destination: filepath
    })
  } finally {
    req.return()
  }
}

async function opendir(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let dir
  let err = null
  try {
    binding.opendir(req.handle, filepath)

    await req

    dir = new Dir(filepath, binding.requestResultDir(req.handle), opts)
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'opendir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, dir, cb)
}

function opendirSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.opendirSync(req.handle, filepath)

    return new Dir(filepath, binding.requestResultDir(req.handle), opts)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'opendir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function readdir(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { withFileTypes = false, recursive = false } = opts

  filepath = toNamespacedPath(filepath)

  const queue = [filepath]
  let result = []
  let err = null
  try {
    while (queue.length !== 0) {
      const dir = await opendir(queue.pop())

      for await (const entry of dir) {
        const entryPath = path.join(entry.parentPath, entry.name)

        if (withFileTypes) {
          result.push(entry)
        } else {
          result.push(path.relative(filepath, entryPath))
        }

        if (recursive && entry.isDirectory()) queue.push(entryPath)
      }
    }
  } catch (e) {
    result = []
    err = e
  }

  return done(err, result, cb)
}

function readdirSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { withFileTypes = false, recursive = false } = opts

  filepath = toNamespacedPath(filepath)

  const queue = [filepath]
  const result = []

  while (queue.length !== 0) {
    const dir = opendirSync(queue.pop(), opts)

    for (const entry of dir) {
      const entryPath = path.join(entry.parentPath, entry.name)

      if (withFileTypes) {
        result.push(entry)
      } else {
        result.push(path.relative(filepath, entryPath))
      }

      if (recursive && entry.isDirectory()) queue.push(entryPath)
    }
  }

  return result
}

async function readFile(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'buffer' } = opts

  let fd = -1
  let buffer = null
  let err = null
  try {
    fd = await open(filepath, opts.flag || 'r')

    const st = await fstat(fd)

    let len = 0

    if (st.size === 0) {
      const buffers = []

      while (true) {
        buffer = Buffer.allocUnsafe(8192)
        const r = await read(fd, buffer)
        len += r
        if (r === 0) break
        buffers.push(buffer.subarray(0, r))
      }

      buffer = Buffer.concat(buffers)
    } else {
      buffer = Buffer.allocUnsafe(st.size)

      while (true) {
        const r = await read(fd, len ? buffer.subarray(len) : buffer)
        len += r
        if (r === 0 || len === buffer.byteLength) break
      }

      if (len !== buffer.byteLength) buffer = buffer.subarray(0, len)
    }

    if (encoding !== 'buffer') buffer = buffer.toString(encoding)
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) await close(fd)
  }

  return done(err, buffer, cb)
}

function readFileSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'buffer' } = opts

  let fd = -1
  try {
    fd = openSync(filepath, opts.flag || 'r')

    const st = fstatSync(fd)

    let buffer
    let len = 0

    if (st.size === 0) {
      const buffers = []

      while (true) {
        buffer = Buffer.allocUnsafe(8192)
        const r = readSync(fd, buffer)
        len += r
        if (r === 0) break
        buffers.push(buffer.subarray(0, r))
      }

      buffer = Buffer.concat(buffers)
    } else {
      buffer = Buffer.allocUnsafe(st.size)

      while (true) {
        const r = readSync(fd, len ? buffer.subarray(len) : buffer)
        len += r
        if (r === 0 || len === buffer.byteLength) break
      }

      if (len !== buffer.byteLength) buffer = buffer.subarray(0, len)
    }

    if (encoding !== 'buffer') buffer = buffer.toString(encoding)

    return buffer
  } finally {
    if (fd !== -1) closeSync(fd)
  }
}

async function writeFile(filepath, data, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (typeof data === 'string') data = Buffer.from(data, opts.encoding)

  let fd = -1
  let len = 0
  let err = null
  try {
    fd = await open(filepath, opts.flag || 'w', opts.mode || 0o666)

    while (true) {
      len += await write(fd, len ? data.subarray(len) : data)
      if (len === data.byteLength) break
    }
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) await close(fd)
  }

  return done(err, len, cb)
}

function writeFileSync(filepath, data, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (typeof data === 'string') data = Buffer.from(data, opts.encoding)

  let fd = -1
  try {
    fd = openSync(filepath, opts.flag || 'w', opts.mode || 0o666)

    let len = 0

    while (true) {
      len += writeSync(fd, len ? data.subarray(len) : data)
      if (len === data.byteLength) break
    }
  } finally {
    if (fd !== -1) closeSync(fd)
  }
}

function appendFile(filepath, data, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (!opts.flag) opts = { ...opts, flag: 'a' }

  return writeFile(filepath, data, opts, cb)
}

function appendFileSync(filepath, data, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (!opts.flag) opts = { ...opts, flag: 'a' }

  return writeFileSync(filepath, data, opts)
}

function watch(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  return new Watcher(filepath, opts, cb)
}

class Stats {
  constructor(
    dev,
    mode,
    nlink,
    uid,
    gid,
    rdev,
    blksize,
    ino,
    size,
    blocks,
    atimeMs,
    mtimeMs,
    ctimeMs,
    birthtimeMs
  ) {
    this.dev = dev
    this.mode = mode
    this.nlink = nlink
    this.uid = uid
    this.gid = gid
    this.rdev = rdev
    this.blksize = blksize
    this.ino = ino
    this.size = size
    this.blocks = blocks
    this.atimeMs = atimeMs
    this.mtimeMs = mtimeMs
    this.ctimeMs = ctimeMs
    this.birthtimeMs = birthtimeMs
    this.atime = new Date(atimeMs)
    this.mtime = new Date(mtimeMs)
    this.ctime = new Date(ctimeMs)
    this.birthtime = new Date(birthtimeMs)
  }

  isDirectory() {
    return (this.mode & constants.S_IFMT) === constants.S_IFDIR
  }

  isFile() {
    return (this.mode & constants.S_IFMT) === constants.S_IFREG
  }

  isBlockDevice() {
    return (this.mode & constants.S_IFMT) === constants.S_IFBLK
  }

  isCharacterDevice() {
    return (this.mode & constants.S_IFMT) === constants.S_IFCHR
  }

  isFIFO() {
    return (this.mode & constants.S_IFMT) === constants.S_IFIFO
  }

  isSymbolicLink() {
    return (this.mode & constants.S_IFMT) === constants.S_IFLNK
  }

  isSocket() {
    return (this.mode & constants.S_IFMT) === constants.S_IFSOCK
  }
}

class StatFs {
  constructor(type, bsize, blocks, bfree, bavail, files, ffree) {
    this.type = type
    this.bsize = bsize
    this.blocks = blocks
    this.bfree = bfree
    this.bavail = bavail
    this.files = files
    this.ffree = ffree
  }
}

class Dir {
  constructor(path, handle, opts = {}) {
    const { encoding = 'utf8', bufferSize = 32 } = opts

    this.path = path

    this._encoding = encoding
    this._capacity = bufferSize
    this._buffer = new FIFO()
    this._ended = false
    this._handle = handle
  }

  async read(cb) {
    if (this._buffer.length) return ok(this._buffer.shift(), cb)
    if (this._ended) return ok(null, cb)

    const req = FileRequest.borrow()

    let entries
    let err = null
    try {
      req.retain(binding.readdir(req.handle, this._handle, this._capacity))

      await req

      entries = binding.requestResultDirents(req.handle)
    } catch (e) {
      err = new FileError(e.message, {
        operation: 'readdir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    if (err) return fail(err, cb)

    if (entries.length === 0) {
      this._ended = true

      return ok(null, cb)
    }

    for (const entry of entries) {
      let name = Buffer.from(entry.name)

      if (this._encoding !== 'buffer') name = name.toString(this._encoding)

      this._buffer.push(new Dirent(this.path, name, entry.type))
    }

    return ok(this._buffer.shift(), cb)
  }

  readSync() {
    if (this._buffer.length) return this._buffer.shift()
    if (this._ended) return null

    const req = FileRequest.borrow()

    let entries
    try {
      req.retain(binding.readdirSync(req.handle, this._handle, this._capacity))

      entries = binding.requestResultDirents(req.handle)
    } catch (e) {
      throw new FileError(e.message, {
        operation: 'readdir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    if (entries.length === 0) {
      this._ended = true

      return null
    }

    for (const entry of entries) {
      let name = Buffer.from(entry.name)

      if (this._encoding !== 'buffer') name = name.toString(this._encoding)

      this._buffer.push(new Dirent(this.path, name, entry.type))
    }

    return this._buffer.shift()
  }

  async close(cb) {
    const req = FileRequest.borrow()

    let err = null
    try {
      binding.closedir(req.handle, this._handle)

      await req
    } catch (e) {
      err = new FileError(e.message, {
        operation: 'closedir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    this._handle = null

    return done(err, cb)
  }

  closeSync() {
    const req = FileRequest.borrow()

    try {
      binding.closedirSync(req.handle, this._handle)
    } catch (e) {
      throw new FileError(e.message, {
        operation: 'closedir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    this._handle = null
  }

  [Symbol.dispose]() {
    this.closeSync()
  }

  async [Symbol.asyncDispose]() {
    await this.close()
  }

  *[Symbol.iterator]() {
    while (true) {
      const entry = this.readSync()
      if (entry === null) break
      yield entry
    }

    this.closeSync()
  }

  async *[Symbol.asyncIterator]() {
    while (true) {
      const entry = await this.read()
      if (entry === null) break
      yield entry
    }

    await this.close()
  }
}

class Dirent {
  constructor(parentPath, name, type) {
    this.parentPath = parentPath
    this.name = name
    this.type = type
  }

  isFile() {
    return this.type === constants.UV_DIRENT_FILE
  }

  isDirectory() {
    return this.type === constants.UV_DIRENT_DIR
  }

  isSymbolicLink() {
    return this.type === constants.UV_DIRENT_LINK
  }

  isFIFO() {
    return this.type === constants.UV_DIRENT_FIFO
  }

  isSocket() {
    return this.type === constants.UV_DIRENT_SOCKET
  }

  isCharacterDevice() {
    return this.type === constants.UV_DIRENT_CHAR
  }

  isBlockDevice() {
    return this.type === constants.UV_DIRENT_BLOCK
  }
}

class FileReadStream extends Readable {
  constructor(path, opts = {}) {
    const { eagerOpen = true } = opts

    super({ eagerOpen, ...opts })

    this.path = path
    this.fd = typeof opts.fd === 'number' ? opts.fd : -1
    this.flags = opts.flags || 'r'
    this.mode = opts.mode || 0o666

    this._offset = opts.start || 0
    this._missing = 0

    if (opts.length) {
      this._missing = opts.length
    } else if (typeof opts.end === 'number') {
      this._missing = opts.end - this._offset + 1
    } else {
      this._missing = -1
    }
  }

  async _open(cb) {
    let err

    if (this.fd === -1) {
      err = null
      try {
        this.fd = await open(this.path, this.flags, this.mode)
      } catch (e) {
        err = e
      }

      if (err) return cb(err)
    }

    let st
    err = null
    try {
      st = await fstat(this.fd)
    } catch (e) {
      err = e
    }

    if (err) return cb(err)

    if (this._missing === -1) this._missing = st.size

    if (st.size < this._offset) {
      this._offset = st.size
      this._missing = 0
    } else if (st.size < this._offset + this._missing) {
      this._missing = st.size - this._offset
    }

    cb(null)
  }

  async _read(size) {
    if (this._missing <= 0) return this.push(null)

    const data = Buffer.allocUnsafe(Math.min(this._missing, size))

    let len
    let err = null
    try {
      len = await read(this.fd, data, 0, data.byteLength, this._offset)
    } catch (e) {
      err = e
    }

    if (err) return this.destroy(err)

    if (len === 0) return this.push(null)

    if (this._missing < len) len = this._missing

    this._missing -= len
    this._offset += len

    this.push(data.subarray(0, len))
  }

  async _destroy(err, cb) {
    if (this.fd === -1) return cb(err)

    try {
      await close(this.fd)
    } catch (e) {
      err = err || e
    }

    cb(err)
  }
}

class FileWriteStream extends Writable {
  constructor(path, opts = {}) {
    const { eagerOpen = true } = opts

    super({ eagerOpen, ...opts })

    this.path = path
    this.fd = typeof opts.fd === 'number' ? opts.fd : -1
    this.flags = opts.flags || 'w'
    this.mode = opts.mode || 0o666
  }

  async _open(cb) {
    if (this.fd !== -1) return cb(null)

    let err = null
    try {
      this.fd = await open(this.path, this.flags, this.mode)
    } catch (e) {
      err = e
    }

    cb(err)
  }

  async _writev(batch, cb) {
    let err = null
    try {
      await writev(
        this.fd,
        batch.map(({ chunk }) => chunk)
      )
    } catch (e) {
      err = e
    }

    cb(err)
  }

  async _destroy(err, cb) {
    if (this.fd === -1) return cb(err)

    try {
      await close(this.fd)
    } catch (e) {
      err = err || e
    }

    cb(err)
  }
}

class Watcher extends EventEmitter {
  constructor(path, opts, onchange) {
    if (typeof opts === 'function') {
      onchange = opts
      opts = {}
    }

    if (!opts) opts = {}

    const { persistent = true, recursive = false, encoding = 'utf8' } = opts

    super()

    this._closed = false
    this._encoding = encoding
    this._handle = binding.watcherInit(path, recursive, this, this._onevent, this._onclose)

    if (!persistent) this.unref()

    if (onchange) this.on('change', onchange)
  }

  close() {
    if (this._closed) return
    this._closed = true

    binding.watcherClose(this._handle)
  }

  ref() {
    if (this._handle) binding.watcherRef(this._handle)
    return this
  }

  unref() {
    if (this._handle) binding.watcherUnref(this._handle)
    return this
  }

  [Symbol.asyncIterator]() {
    const buffer = []
    let done = false
    let error = null
    let next = null

    this.on('change', (eventType, filename) => {
      if (next) {
        next.resolve({ done: false, value: { eventType, filename } })
        next = null
      } else {
        buffer.push({ eventType, filename })
      }
    })
      .on('error', (err) => {
        done = true
        error = err

        if (next) {
          next.reject(error)
          next = null
        }
      })
      .on('close', () => {
        done = true

        if (next) {
          next.resolve({ done })
          next = null
        }
      })

    return {
      next: () =>
        new Promise((resolve, reject) => {
          if (error) return reject(error)

          if (buffer.length) return resolve({ done: false, value: buffer.shift() })

          if (done) return resolve({ done })

          next = { resolve, reject }
        })
    }
  }

  _onevent(err, events, filename) {
    if (err) {
      this.close()
      this.emit('error', err)
    } else {
      const path =
        this._encoding === 'buffer'
          ? Buffer.from(filename)
          : Buffer.from(filename).toString(this._encoding)

      if (events & binding.UV_RENAME) {
        this.emit('change', 'rename', path)
      }

      if (events & binding.UV_CHANGE) {
        this.emit('change', 'change', path)
      }
    }
  }

  _onclose() {
    this._handle = null

    this.emit('close')
  }
}

exports.access = access
exports.appendFile = appendFile
exports.chmod = chmod
exports.chown = chown
exports.close = close
exports.copyFile = copyFile
exports.cp = cp
exports.exists = exists
exports.fchmod = fchmod
exports.fchown = fchown
exports.fdatasync = fdatasync
exports.fstat = fstat
exports.fsync = fsync
exports.ftruncate = ftruncate
exports.futimes = futimes
exports.lchown = lchown
exports.lutimes = lutimes
exports.link = link
exports.lstat = lstat
exports.mkdir = mkdir
exports.mkdtemp = mkdtemp
exports.open = open
exports.opendir = opendir
exports.read = read
exports.readFile = readFile
exports.readdir = readdir
exports.readlink = readlink
exports.readv = readv
exports.realpath = realpath
exports.rename = rename
exports.rm = rm
exports.rmdir = rmdir
exports.stat = stat
exports.statfs = statfs
exports.symlink = symlink
exports.truncate = truncate
exports.unlink = unlink
exports.utimes = utimes
exports.watch = watch
exports.write = write
exports.writeFile = writeFile
exports.writev = writev

exports.accessSync = accessSync
exports.appendFileSync = appendFileSync
exports.chmodSync = chmodSync
exports.chownSync = chownSync
exports.closeSync = closeSync
exports.copyFileSync = copyFileSync
exports.cpSync = cpSync
exports.existsSync = existsSync
exports.fchmodSync = fchmodSync
exports.fchownSync = fchownSync
exports.fdatasyncSync = fdatasyncSync
exports.fstatSync = fstatSync
exports.fsyncSync = fsyncSync
exports.ftruncateSync = ftruncateSync
exports.futimesSync = futimesSync
exports.lchownSync = lchownSync
exports.lutimesSync = lutimesSync
exports.linkSync = linkSync
exports.lstatSync = lstatSync
exports.mkdirSync = mkdirSync
exports.mkdtempSync = mkdtempSync
exports.openSync = openSync
exports.opendirSync = opendirSync
exports.readFileSync = readFileSync
exports.readSync = readSync
exports.readdirSync = readdirSync
exports.readlinkSync = readlinkSync
exports.readvSync = readvSync
exports.realpathSync = realpathSync
exports.renameSync = renameSync
exports.rmSync = rmSync
exports.rmdirSync = rmdirSync
exports.statSync = statSync
exports.statfsSync = statfsSync
exports.symlinkSync = symlinkSync
exports.truncateSync = truncateSync
exports.unlinkSync = unlinkSync
exports.utimesSync = utimesSync
exports.writeFileSync = writeFileSync
exports.writeSync = writeSync
exports.writevSync = writevSync

exports.promises = require('./promises')

exports.Stats = Stats
exports.StatFs = StatFs
exports.Dir = Dir
exports.Dirent = Dirent
exports.Watcher = Watcher

exports.ReadStream = FileReadStream

exports.createReadStream = function createReadStream(path, opts) {
  return new FileReadStream(path, opts)
}

exports.WriteStream = FileWriteStream

exports.createWriteStream = function createWriteStream(path, opts) {
  return new FileWriteStream(path, opts)
}

function toNamespacedPath(filepath) {
  if (typeof filepath !== 'string') {
    if (isURL(filepath)) filepath = fileURLToPath(filepath)
    else filepath = filepath.toString()
  }

  return path.toNamespacedPath(filepath)
}

function toFlags(flags) {
  switch (flags) {
    case 'r':
      return constants.O_RDONLY
    case 'rs': // Fall through.
    case 'sr':
      return constants.O_RDONLY | constants.O_SYNC
    case 'r+':
      return constants.O_RDWR
    case 'rs+': // Fall through.
    case 'sr+':
      return constants.O_RDWR | constants.O_SYNC

    case 'w':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_WRONLY
    case 'wx': // Fall through.
    case 'xw':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_WRONLY | constants.O_EXCL

    case 'w+':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_RDWR
    case 'wx+': // Fall through.
    case 'xw+':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_RDWR | constants.O_EXCL

    case 'a':
      return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY
    case 'ax': // Fall through.
    case 'xa':
      return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY | constants.O_EXCL
    case 'as': // Fall through.
    case 'sa':
      return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY | constants.O_SYNC

    case 'a+':
      return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR
    case 'ax+': // Fall through.
    case 'xa+':
      return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR | constants.O_EXCL
    case 'as+': // Fall through.
    case 'sa+':
      return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR | constants.O_SYNC
    default:
      return 0
  }
}

function toMode(mode) {
  return parseInt(mode, 8)
}
const binding = require('../binding')

module.exports = {
  O_RDWR: binding.O_RDWR,
  O_RDONLY: binding.O_RDONLY,
  O_WRONLY: binding.O_WRONLY,
  O_CREAT: binding.O_CREAT,
  O_TRUNC: binding.O_TRUNC,
  O_APPEND: binding.O_APPEND,

  F_OK: binding.F_OK || 0,
  R_OK: binding.R_OK || 0,
  W_OK: binding.W_OK || 0,
  X_OK: binding.X_OK || 0,

  S_IFMT: binding.S_IFMT,
  S_IFREG: binding.S_IFREG,
  S_IFDIR: binding.S_IFDIR,
  S_IFCHR: binding.S_IFCHR,
  S_IFLNK: binding.S_IFLNK,
  S_IFBLK: binding.S_IFBLK || 0,
  S_IFIFO: binding.S_IFIFO || 0,
  S_IFSOCK: binding.S_IFSOCK || 0,

  S_IRUSR: binding.S_IRUSR || 0,
  S_IWUSR: binding.S_IWUSR || 0,
  S_IXUSR: binding.S_IXUSR || 0,
  S_IRGRP: binding.S_IRGRP || 0,
  S_IWGRP: binding.S_IWGRP || 0,
  S_IXGRP: binding.S_IXGRP || 0,
  S_IROTH: binding.S_IROTH || 0,
  S_IWOTH: binding.S_IWOTH || 0,
  S_IXOTH: binding.S_IXOTH || 0,

  UV_DIRENT_UNKNOWN: binding.UV_DIRENT_UNKNOWN,
  UV_DIRENT_FILE: binding.UV_DIRENT_FILE,
  UV_DIRENT_DIR: binding.UV_DIRENT_DIR,
  UV_DIRENT_LINK: binding.UV_DIRENT_LINK,
  UV_DIRENT_FIFO: binding.UV_DIRENT_FIFO,
  UV_DIRENT_SOCKET: binding.UV_DIRENT_SOCKET,
  UV_DIRENT_CHAR: binding.UV_DIRENT_CHAR,
  UV_DIRENT_BLOCK: binding.UV_DIRENT_BLOCK,

  COPYFILE_EXCL: binding.UV_FS_COPYFILE_EXCL,
  COPYFILE_FICLONE: binding.UV_FS_COPYFILE_FICLONE,
  COPYFILE_FICLONE_FORCE: binding.UV_FS_COPYFILE_FICLONE_FORCE,
  UV_FS_SYMLINK_DIR: binding.UV_FS_SYMLINK_DIR,
  UV_FS_SYMLINK_JUNCTION: binding.UV_FS_SYMLINK_JUNCTION
}
const os = require('bare-os')

module.exports = class FileError extends Error {
  constructor(msg, opts = {}) {
    const { code, operation = null, path = null, destination = null, fd = -1 } = opts

    if (operation !== null) msg += describe(operation, opts)

    super(`${code}: ${msg}`)

    this.code = code

    if (operation !== null) this.operation = operation
    if (path !== null) this.path = path
    if (destination !== null) this.destination = destination
    if (fd !== -1) this.fd = fd
  }

  get name() {
    return 'FileError'
  }

  // For Node.js compatibility
  get errno() {
    return os.constants.errnos[this.code]
  }

  // For Node.js compatibility
  get syscall() {
    return this.operation
  }

  // For Node.js compatibility
  get dest() {
    return this.destination
  }
}

function describe(operation, opts) {
  const { path = null, destination = null, fd = -1 } = opts

  let result = `, ${operation}`

  if (path !== null) {
    result += ` ${JSON.stringify(path)}`

    if (destination !== null) {
      result += ` -> ${JSON.stringify(destination)}`
    }
  } else if (fd !== -1) {
    result += ` ${fd}`
  }

  return result
}
{
  "name": "bare-fs",
  "version": "4.7.2",
  "description": "Native file system operations for Bare",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./promises": {
      "types": "./promises.d.ts",
      "default": "./promises.js"
    },
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "promises.js",
    "promises.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-fs.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-fs/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-fs#readme",
  "engines": {
    "bare": ">=1.16.0"
  },
  "dependencies": {
    "bare-events": "^2.5.4",
    "bare-path": "^3.0.0",
    "bare-stream": "^2.6.4",
    "bare-url": "^2.2.2",
    "fast-fifo": "^1.3.2"
  },
  "devDependencies": {
    "bare-buffer": "^3.0.2",
    "bare-crypto": "^1.11.2",
    "brittle": "^3.1.1",
    "cmake-bare": "^1.1.7",
    "lunte": "^1.6.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "bare-buffer": "*"
  },
  "peerDependenciesMeta": {
    "bare-buffer": {
      "optional": true
    }
  }
}
const EventEmitter = require('bare-events')
const fs = require('.')

class FileHandle extends EventEmitter {
  constructor(fd) {
    super()

    this.fd = fd
  }

  async close() {
    await fs.close(this.fd)

    this.fd = -1
    this.emit('close')
  }

  async read(buffer, ...args) {
    return {
      bytesRead: await fs.read(this.fd, buffer, ...args),
      buffer
    }
  }

  async readv(buffers, ...args) {
    return {
      bytesRead: await fs.readv(this.fd, buffers, ...args),
      buffers
    }
  }

  async write(buffer, ...args) {
    return {
      bytesWritten: await fs.write(this.fd, buffer, ...args),
      buffer
    }
  }

  async writev(buffers, ...args) {
    return {
      bytesWritten: await fs.writev(this.fd, buffers, ...args),
      buffers
    }
  }

  async stat() {
    return fs.fstat(this.fd)
  }

  async chmod(mode) {
    await fs.fchmod(this.fd, mode)
  }

  async chown(uid, gid) {
    await fs.fchown(this.fd, uid, gid)
  }

  async datasync() {
    return fs.fdatasync(this.fd)
  }

  async sync() {
    return fs.fsync(this.fd)
  }

  async truncate(len) {
    await fs.ftruncate(this.fd, len)
  }

  async utimes(atime, mtime) {
    await fs.futimes(this.fd, atime, mtime)
  }

  createReadStream(opts) {
    return fs.createReadStream(null, { ...opts, fd: this.fd })
  }

  createWriteStream(opts) {
    return fs.createWriteStream(null, { ...opts, fd: this.fd })
  }

  async [Symbol.asyncDispose]() {
    await this.close()
  }
}

exports.open = async function open(filepath, flags, mode) {
  return new FileHandle(await fs.open(filepath, flags, mode))
}

exports.access = fs.access
exports.appendFile = fs.appendFile
exports.chmod = fs.chmod
exports.chown = fs.chown
exports.constants = fs.constants
exports.copyFile = fs.copyFile
exports.cp = fs.cp
exports.lchown = fs.lchown
exports.lutimes = fs.lutimes
exports.link = fs.link
exports.lstat = fs.lstat
exports.mkdir = fs.mkdir
exports.mkdtemp = fs.mkdtemp
exports.opendir = fs.opendir
exports.readFile = fs.readFile
exports.readdir = fs.readdir
exports.readlink = fs.readlink
exports.realpath = fs.realpath
exports.rename = fs.rename
exports.rm = fs.rm
exports.rmdir = fs.rmdir
exports.stat = fs.stat
exports.statfs = fs.statfs
exports.truncate = fs.truncate
exports.symlink = fs.symlink
exports.unlink = fs.unlink
exports.utimes = fs.utimes
exports.watch = fs.watch
exports.writeFile = fs.writeFile
module.exports = require.addon()
const ansiEscapes = require('bare-ansi-escapes')
const getType = require('bare-type')
const binding = require('./binding')

const PLAIN_KEY = /^[a-zA-Z_][a-zA-Z_0-9]*$/

const defaultDepth = 2
const defaultBreakLength = 80
const defaultMaxArrayLength = 40

module.exports = exports = function inspect(value, opts = {}) {
  const {
    colors = false,
    depth = defaultDepth,
    breakLength = defaultBreakLength,
    stylize = defaultStylize(colors)
  } = opts

  const references = new InspectRefMap()

  const tree = inspectValue(value, 0, {
    colors,
    depth,
    breakLength,
    stylize,
    references
  })

  return tree.toString()
}

exports.styles = {
  bigint: ansiEscapes.colorYellow,
  boolean: ansiEscapes.colorYellow,
  date: ansiEscapes.colorMagenta,
  module: ansiEscapes.modifierUnderline,
  name: ansiEscapes.modifierReset,
  null: ansiEscapes.modifierBold,
  number: ansiEscapes.colorYellow,
  regexp: ansiEscapes.colorRed,
  special: ansiEscapes.colorCyan,
  string: ansiEscapes.colorGreen,
  symbol: ansiEscapes.colorGreen,
  undefined: ansiEscapes.colorBrightBlack
}

const styles = exports.styles

function defaultStylize(colors) {
  return function stylize(value, style) {
    const color = colors && styles[style]

    if (color) return color + value + ansiEscapes.modifierReset

    return value
  }
}

class InspectRefMap {
  constructor() {
    this.refs = new WeakMap()
    this.ids = new WeakMap()
    this.nextId = 1
  }

  has(object) {
    return this.refs.has(object)
  }

  get(object) {
    return this.refs.get(object) || null
  }

  set(object, ref) {
    this.refs.set(object, ref)
  }

  id(object) {
    let id = this.ids.get(object)
    if (id) return id

    id = this.nextId++
    this.ids.set(object, id)

    return id
  }
}

class InspectNode {
  constructor(depth, length, opts) {
    const { breakLength = defaultBreakLength, breakAlways = false } = opts

    this.depth = depth
    this.length = length
    this.breakLength = breakLength
    this.breakAlways = breakAlways
  }

  pad(n, string) {
    return string.padStart(n, ' ')
  }

  indent(n, string) {
    return '  '.repeat(n) + string
  }
}

class InspectRef extends InspectNode {
  constructor(depth, opts) {
    super(depth, '[circular *]'.length, opts)

    this.refs = opts.references
    this.count = 0
    this.circular = false
    this.color = opts.colors && styles.special
  }

  get id() {
    return this.refs.id(this)
  }

  increment() {
    return ++this.count
  }

  decrement() {
    return --this.count
  }

  toString(opts = {}) {
    const { offset = 0, pad = 0, indent = 0 } = opts

    let value = this.pad(pad, '[circular *' + this.id + ']')

    if (this.color) value = this.color + value + ansiEscapes.modifierReset

    return offset ? value : this.indent(indent, value)
  }
}

class InspectLeaf extends InspectNode {
  constructor(value, color, depth, opts) {
    const length = value.length

    if (value.includes('\n')) {
      value = value.replaceAll('\n', '\n' + '  '.repeat(depth))

      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.value = value
    this.color = opts.colors && color
  }

  toString(opts = {}) {
    const { offset = 0, pad = 0, indent = 0 } = opts

    let value = this.pad(pad, this.value)

    if (this.color) value = this.color + value + ansiEscapes.modifierReset

    return offset ? value : this.indent(indent, value)
  }
}

class InspectPair extends InspectNode {
  constructor(delim, left, right, depth, opts) {
    const length = left.length + delim.length + right.length

    if (left.breakAlways || right.breakAlways) {
      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.delim = delim
    this.left = left
    this.right = right
  }

  toString(opts = {}) {
    const { indent = 0 } = opts

    return this.indent(
      indent,
      this.left +
        this.delim +
        this.right.toString({
          indent,
          offset: this.left.length + this.delim.length
        })
    )
  }
}

class InspectSuspension extends InspectNode {
  constructor(overflow, depth, opts) {
    const label = `... ${overflow} more`

    super(depth, label.length, opts)

    this.label = label
  }

  toString(opts = {}) {
    const { indent = 0 } = opts

    return this.indent(indent, this.label)
  }
}

class InspectSequence extends InspectNode {
  constructor(header, footer, delim, values, ref, depth, opts) {
    const { tabulate = false } = opts

    const length =
      (ref.circular ? '<ref *>'.length + 1 : 0) +
      header.length +
      values.reduce(
        (length, value, i) =>
          length + value.length + (i === 0 ? 0 : delim.length),
        0
      ) +
      footer.length

    if (values.some((value) => value.breakAlways)) {
      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.header = header
    this.footer = footer
    this.delim = delim
    this.values = values
    this.ref = ref
    this.tabulate = tabulate
  }

  toString(opts = {}) {
    const { offset = 0, indent = 0 } = opts

    const split =
      this.breakAlways ||
      (this.values.length &&
        (offset + this.length > this.breakLength ||
          indent * 2 + this.length > this.breakLength))

    let header = this.header

    if (this.ref.circular) {
      header = '<ref *' + this.ref.id + '> ' + header
    }

    if (this.values.length === 0) {
      header = header.trimEnd()
    }

    if (offset === 0) {
      header = this.indent(indent, header)
    }

    if (split) {
      header = header.trimEnd() + '\n'
    }

    let string = header

    let columns = 1
    let pad = 0

    if (this.tabulate) {
      const widest = this.values.reduce(
        (length, value) =>
          value.breakAlways ? length : Math.max(length, value.length),
        0
      )

      if (widest) {
        columns = Math.max(
          columns,
          Math.floor(
            (this.breakLength - indent * 2) / (widest + this.delim.length)
          )
        )

        if (columns > 1) pad = widest
      }
    }

    for (let i = 0, n = this.values.length, offset = 0; i < n; i++) {
      const value = this.values[i]

      if (split) {
        let part

        if (i % columns === 0 || value.breakAlways) {
          part = value.toString({ indent: indent + 1, pad })
        } else {
          part = value.toString({ pad })
        }

        string += part

        if (i < n - 1) {
          if (i % columns === columns - 1 || this.values[i + 1].breakAlways) {
            string += this.delim.trimEnd() + '\n'
          } else {
            string += this.delim
          }
        }
      } else {
        if (i > 0) string += this.delim

        string += value.toString({ offset })

        offset += value.length
      }
    }

    let footer = this.footer

    if (this.values.length === 0) {
      footer = footer.trimStart()
    }

    if (split) {
      string += '\n' + this.indent(indent, footer.trimStart())
    } else {
      string += footer
    }

    return string
  }
}

function inspectValue(value, depth, opts) {
  const type = getType(value)

  if (type.isUndefined()) return inspectUndefined(depth, opts)
  if (type.isNull()) return inspectNull(depth, opts)
  if (type.isBoolean()) return inspectBoolean(value, depth, opts)
  if (type.isNumber()) return inspectNumber(value, depth, opts)
  if (type.isBigInt()) return inspectBigInt(value, depth, opts)
  if (type.isString()) return inspectString(value, depth, opts)
  if (type.isSymbol()) return inspectSymbol(value, depth, opts)
  if (type.isObject()) return inspectObject(type, value, depth, opts)
  if (type.isFunction()) return inspectFunction(type, value, depth, opts)
  if (type.isExternal()) return inspectExternal(value, opts, opts)
}

function inspectUndefined(depth, opts) {
  return new InspectLeaf('undefined', styles.undefined, depth, opts)
}

function inspectNull(depth, opts) {
  return new InspectLeaf('null', styles.null, depth, opts)
}

function inspectBoolean(value, depth, opts) {
  return new InspectLeaf(value.toString(), styles.boolean, depth, opts)
}

function inspectNumber(value, depth, opts) {
  let string

  if (Object.is(value, -0)) {
    string = '-0'
  } else {
    string = value.toString(10)
  }

  return new InspectLeaf(string, styles.number, depth, opts)
}

function inspectBigInt(value, depth, opts) {
  return new InspectLeaf(value.toString(10) + 'n', styles.bigint, depth, opts)
}

const STRING_ESCAPES =
  /[\ud800-\udbff][\udc00-\udfff]|[\u0000-\u001f'\\\ud800-\udfff]/g

function inspectString(value, depth, opts) {
  // https://tc39.es/ecma262/multipage/structured-data.html#sec-quotejsonstring
  const string = value.replace(STRING_ESCAPES, (match) => {
    if (match.length === 2) return match

    switch (match) {
      case "'":
        return "\\'"
      case '\\':
        return '\\\\'
      case '\b':
        return '\\b'
      case '\t':
        return '\\t'
      case '\n':
        return '\\n'
      case '\f':
        return '\\f'
      case '\r':
        return '\\r'
      default:
        return '\\u' + match.charCodeAt(0).toString(16).padStart(4, '0')
    }
  })

  return new InspectLeaf("'" + string + "'", styles.string, depth, opts)
}

function inspectSymbol(value, depth, opts) {
  return new InspectLeaf(value.toString(), styles.symbol, depth, opts)
}

function inspectKey(value, depth, opts) {
  if (PLAIN_KEY.test(value)) {
    return new InspectLeaf(value, null, depth, opts)
  } else {
    return inspectValue(value, depth, opts)
  }
}

function inspectObject(type, object, depth, opts) {
  const refs = opts.references

  let ref = refs.get(object)
  if (ref === null) {
    ref = new InspectRef(depth, opts)
    refs.set(object, ref)
  } else if (ref.count) {
    ref.circular = true
    return ref
  }

  const maxDepth = typeof opts.depth === 'number' ? opts.depth : Infinity

  if (maxDepth < depth) {
    const constructor = object.constructor

    return new InspectLeaf(
      '[' +
        (constructor && constructor.name ? constructor.name : 'Object') +
        ']',
      styles.special,
      depth,
      opts
    )
  }

  const inspect =
    object[Symbol.for('bare.inspect')] ||
    object[Symbol.for('nodejs.util.inspect.custom')]

  if (typeof inspect === 'function') {
    const value = inspect.call(
      object,
      typeof opts.depth === 'number' ? opts.depth - depth : null,
      {
        colors: opts.colors,
        breakLength: opts.breakLength,
        stylize: opts.stylize
      },
      exports
    )

    if (typeof value === 'object' && value !== null) {
      refs.set(value, ref)
    }

    if (typeof value !== 'string') {
      return inspectValue(value, depth, opts)
    }

    return new InspectLeaf(value, null, depth, opts)
  }

  if (type.isArray()) return inspectArray(object, ref, depth, opts)
  if (type.isDate()) return inspectDate(object, ref, depth, opts)
  if (type.isRegExp()) return inspectRegExp(object, ref, depth, opts)
  if (type.isError()) return inspectError(object, ref, depth, opts)
  if (type.isPromise()) return inspectPromise(object, ref, depth, opts)
  if (type.isMap()) return inspectMap(object, ref, depth, opts)
  if (type.isSet()) return inspectSet(object, ref, depth, opts)
  if (type.isWeakMap()) return inspectWeakMap(object, ref, depth, opts)
  if (type.isWeakSet()) return inspectWeakSet(object, ref, depth, opts)
  if (type.isWeakRef()) return inspectWeakRef(object, ref, depth, opts)
  if (type.isArrayBuffer()) return inspectArrayBuffer(object, ref, depth, opts)
  if (type.isSharedArrayBuffer())
    return inspectSharedArrayBuffer(object, ref, depth, opts)
  if (type.isTypedArray()) return inspectTypedArray(object, ref, depth, opts)
  if (type.isDataView()) return inspectDataView(object, ref, depth, opts)

  ref.increment()

  const values = []

  for (const key in object) {
    if (key === 'constructor') continue

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(object[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  let header = '{ '

  const tag = object[Symbol.toStringTag]

  if (tag) header = '[' + tag + '] ' + header

  if (object.constructor) {
    const name = object.constructor.name

    if (name && name !== 'Object') {
      header = object.constructor.name + ' ' + header
    }
  }

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectArray(array, ref, depth, opts) {
  const { maxArrayLength = defaultMaxArrayLength } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxArrayLength, 0)

  for (let i = 0, n = array.length; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(array.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(inspectValue(array[i], depth + 1, opts))
  }

  for (const key of binding.getOwnNonIndexPropertyNames(array)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(array[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  let header = '[ '

  if (array.constructor.name !== 'Array') {
    header = array.constructor.name + '(' + array.length + ') ' + header
  }

  return new InspectSequence(header, ' ]', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectDate(date, ref, depth, opts) {
  return new InspectLeaf(date.toISOString(), styles.date, depth, opts)
}

function inspectRegExp(regExp, ref, depth, opts) {
  return new InspectLeaf(regExp.toString(), styles.regexp, depth, opts)
}

function inspectError(error, ref, depth, opts) {
  let header

  if ('stack' in error) {
    header = error.stack

    if (depth > 0) {
      header = header.replaceAll('\n', '\n' + '  '.repeat(depth))
    }
  } else {
    header = error.toString()
  }

  const builtins = ['cause']

  if (error.name === 'AggregateError') {
    builtins.push('errors')
  } else if (error.name === 'SuppressedError') {
    builtins.push('error', 'suppressed')
  }

  const values = []

  for (const key of builtins) {
    if (key in error === false) continue

    values.push(
      new InspectPair(
        ': ',
        new InspectLeaf('[' + key + ']', null, depth + 1, opts),
        inspectValue(error[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key in error) {
    if (key === 'constructor' || builtins.includes(key)) continue

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(error[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  if (values.length === 0) return new InspectLeaf(header, null, depth, opts)

  return new InspectSequence(
    header + ' {',
    ' }',
    ', ',
    values,
    ref,
    depth,
    opts
  )
}

function inspectPromise(promise, ref, depth, opts) {
  ref.increment()

  const state = binding.getPromiseState(promise)

  const values = []

  switch (state) {
    case 0: // Pending
      values.push(new InspectLeaf('<pending>', styles.special, depth, opts))
      break

    case 1: // Fulfilled
      values.push(inspectValue(binding.getPromiseResult(promise), depth, opts))
      break

    case 2: // Rejected
      values.push(
        new InspectLeaf('<rejected>', styles.special, depth, opts),
        inspectValue(binding.getPromiseResult(promise), depth, opts)
      )
  }

  ref.decrement()

  const header = promise.constructor.name + ' { '

  return new InspectSequence(header, ' }', ' ', values, ref, depth, opts)
}

function inspectMap(map, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxMapLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = maxMapLength

  for (const entry of map) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(map.size - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )
      break
    }

    values.push(
      new InspectPair(
        ' => ',
        inspectValue(entry[0], depth + 1, opts),
        inspectValue(entry[1], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key in map) {
    if (key === 'constructor') continue

    const value = inspectValue(map[key], depth + 1, opts)

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        value,
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = map.constructor.name + '(' + map.size + ') { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectSet(set, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxSetLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = maxSetLength

  for (const entry of set) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(set.size - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )
      break
    }

    values.push(inspectValue(entry, depth + 1, opts))
  }

  for (const key in set) {
    if (key === 'constructor') continue

    const value = inspectValue(set[key], depth + 1, opts)

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        value,
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = set.constructor.name + '(' + set.size + ') { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectWeakMap(weakMap, ref, depth, opts) {
  const header = weakMap.constructor.name + ' { '

  return new InspectSequence(
    header,
    ' }',
    ' ',
    [new InspectLeaf('<items unknown>', styles.special, depth + 1, opts)],
    ref,
    depth,
    opts
  )
}

function inspectWeakSet(weakSet, ref, depth, opts) {
  const header = weakSet.constructor.name + ' { '

  return new InspectSequence(
    header,
    ' }',
    ' ',
    [new InspectLeaf('<items unknown>', styles.special, depth + 1, opts)],
    ref,
    depth,
    opts
  )
}

function inspectWeakRef(weakRef, ref, depth, opts) {
  const target = weakRef.deref()

  let value

  if (target === undefined) {
    value = new InspectLeaf('<cleared>', styles.special, depth + 1, opts)
  } else {
    value = inspectValue(target, depth + 1, opts)
  }

  const header = weakRef.constructor.name + ' { '

  return new InspectSequence(header, ' }', ' ', [value], ref, depth, opts)
}

function inspectArrayBuffer(arrayBuffer, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(arrayBuffer[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = arrayBuffer.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectSharedArrayBuffer(sharedArrayBuffer, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(sharedArrayBuffer[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = sharedArrayBuffer.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectTypedArray(typedArray, ref, depth, opts) {
  if (Buffer.isBuffer(typedArray)) {
    return inspectBuffer(typedArray, ref, depth, opts)
  }

  const {
    maxArrayLength = defaultMaxArrayLength,
    maxTypedArrayLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxTypedArrayLength, 0)

  for (let i = 0, n = typedArray.length; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(typedArray.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(inspectValue(typedArray[i], depth + 1, opts))
  }

  for (const key of binding.getOwnNonIndexPropertyNames(typedArray)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(typedArray[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = typedArray.constructor.name + '(' + typedArray.length + ') [ '

  return new InspectSequence(header, ' ]', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectBuffer(buffer, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxBufferLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxBufferLength, 0)

  for (let i = 0, n = buffer.byteLength; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(buffer.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(
      new InspectLeaf(
        buffer[i].toString(16).padStart(2, '0'),
        null,
        depth + 1,
        opts
      )
    )
  }

  for (const key of binding.getOwnNonIndexPropertyNames(buffer)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(buffer[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  return new InspectSequence('<Buffer ', '>', ' ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectDataView(dataView, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength', 'byteOffset', 'buffer']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(dataView[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key of binding.getOwnNonIndexPropertyNames(dataView)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(dataView[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = dataView.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectFunction(type, fn, depth, opts) {
  if (fn.toString().startsWith('class')) return inspectClass(fn, depth, opts)

  let tag = 'function'

  if (type.isGeneratorFunction()) tag = 'generator ' + tag
  if (type.isAsyncFunction()) tag = 'async ' + tag

  return new InspectLeaf(
    '[' + tag + ' ' + (fn.name ? fn.name : '(anonymous)') + ']',
    styles.special,
    depth,
    opts
  )
}

function inspectClass(ctor, depth, opts) {
  return new InspectLeaf(
    '[class ' + (ctor.name ? ctor.name : '(anonymous)') + ']',
    styles.special,
    depth,
    opts
  )
}

function inspectExternal(external, depth, opts) {
  return new InspectLeaf(
    '[external 0x' + binding.getExternal(external).toString(16) + ']',
    styles.special,
    depth,
    opts
  )
}
{
  "name": "bare-inspect",
  "version": "3.1.4",
  "description": "Inspect objects as strings for debugging",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-inspect.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-inspect/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-inspect#readme",
  "engines": {
    "bare": ">=1.18.0"
  },
  "dependencies": {
    "bare-ansi-escapes": "^2.1.0",
    "bare-type": "^1.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
module.exports = require.addon()
const binding = require('./binding')
const errors = require('./lib/errors')
const constants = require('./lib/constants')

exports.constants = constants
exports.errors = errors

exports.EOL = binding.platform === 'win32' ? '\r\n' : '\n'

exports.devNull = binding.platform === 'win32' ? '\\\\.\\nul' : '/dev/null'

exports.platform = function platform() {
  return binding.platform
}

exports.arch = function arch() {
  return binding.arch
}

exports.type = binding.type
exports.version = binding.version
exports.release = binding.release
exports.machine = binding.machine
exports.execPath = binding.execPath
exports.pid = binding.pid
exports.ppid = binding.ppid
exports.cwd = binding.cwd
exports.chdir = binding.chdir
exports.tmpdir = binding.tmpdir
exports.homedir = binding.homedir
exports.hostname = binding.hostname
exports.userInfo = binding.userInfo
exports.groupInfo = binding.groupInfo

exports.networkInterfaces = function networkInterfaces() {
  const result = {}

  for (const entry of binding.networkInterfaces()) {
    const { name, ...properties } = entry

    if (result[name]) result[name].push(properties)
    else result[name] = [properties]
  }

  return result
}

exports.kill = function kill(pid, signal = constants.signals.SIGTERM) {
  if (typeof signal === 'string') {
    if (signal in constants.signals === false) {
      throw errors.UNKNOWN_SIGNAL('Unknown signal: ' + signal)
    }

    signal = constants.signals[signal]
  }

  binding.kill(pid, signal)
}

exports.endianness = function endianness() {
  return binding.isLittleEndian ? 'LE' : 'BE'
}

exports.availableParallelism = binding.availableParallelism

exports.cpuUsage = function cpuUsage(previous) {
  const current = binding.cpuUsage()

  if (previous) {
    return {
      user: current.user - previous.user,
      system: current.system - previous.system
    }
  }

  return current
}

exports.threadCpuUsage = function threadCpuUsage(previous) {
  const current = binding.threadCpuUsage()

  if (previous) {
    return {
      user: current.user - previous.user,
      system: current.system - previous.system
    }
  }

  return current
}

exports.resourceUsage = binding.resourceUsage
exports.memoryUsage = binding.memoryUsage
exports.freemem = binding.freemem
exports.totalmem = binding.totalmem
exports.availableMemory = binding.availableMemory
exports.constrainedMemory = binding.constrainedMemory
exports.uptime = binding.uptime
exports.loadavg = binding.loadavg
exports.cpus = binding.cpus

exports.getProcessTitle = binding.getProcessTitle

exports.setProcessTitle = function setProcessTitle(title) {
  if (typeof title !== 'string') title = title.toString()

  if (title.length >= 256) {
    throw errors.TITLE_OVERFLOW('Process title is too long')
  }

  binding.setProcessTitle(title)
}

exports.getPriority = function getPriority(pid = 0) {
  return binding.getPriority(pid)
}

exports.setPriority = function setPriority(pid, priority) {
  if (priority === undefined) {
    priority = pid
    pid = 0
  }

  binding.setPriority(pid, priority)
}

exports.getEnvKeys = binding.getEnvKeys
exports.getEnv = binding.getEnv
exports.hasEnv = binding.hasEnv
exports.setEnv = binding.setEnv
exports.unsetEnv = binding.unsetEnv
const binding = require('../binding')

module.exports = {
  signals: binding.signals,
  errnos: binding.errnos,
  priority: binding.priority
}
module.exports = class OSError extends Error {
  constructor(msg, fn = OSError, code = fn.name) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'OSError'
  }

  static UNKNOWN_SIGNAL(msg) {
    return new OSError(msg, OSError.UNKNOWN_SIGNAL)
  }

  static TITLE_OVERFLOW(msg) {
    return new OSError(msg, OSError.TITLE_OVERFLOW)
  }
}
{
  "name": "bare-os",
  "version": "3.9.1",
  "description": "Operating system utilities for Bare",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    },
    "./errors": {
      "types": "./lib/errors.d.ts",
      "default": "./lib/errors.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-os.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-os/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-os#readme",
  "engines": {
    "bare": ">=1.14.0"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "cmake-bare": "^1.1.6",
    "lunte": "^1.6.0",
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
// This export SHOULD NOT be shortened in any way as having the full
// `module.exports = require(...)` statement is crucial for synthesizing
// ESM exports.

if (Bare.platform === 'win32') {
  module.exports = require('./lib/win32')
} else {
  module.exports = require('./lib/posix')
}
module.exports = {
  CHAR_UPPERCASE_A: 0x41,
  CHAR_LOWERCASE_A: 0x61,
  CHAR_UPPERCASE_Z: 0x5a,
  CHAR_LOWERCASE_Z: 0x7a,
  CHAR_DOT: 0x2e,
  CHAR_FORWARD_SLASH: 0x2f,
  CHAR_BACKWARD_SLASH: 0x5c,
  CHAR_COLON: 0x3a,
  CHAR_QUESTION_MARK: 0x3f
}
const os = require('bare-os')

const { normalizeString } = require('./shared')
const { CHAR_DOT, CHAR_FORWARD_SLASH } = require('./constants')

function isPosixPathSeparator(code) {
  return code === CHAR_FORWARD_SLASH
}

exports.win32 = require('./win32')
exports.posix = exports

exports.sep = '/'
exports.delimiter = ':'

exports.resolve = function resolve(...args) {
  let resolvedPath = ''
  let resolvedAbsolute = false

  for (let i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) {
    const path = i >= 0 ? args[i] : os.cwd()

    if (path.length === 0) {
      continue
    }

    resolvedPath = `${path}/${resolvedPath}`
    resolvedAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH
  }

  resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute, '/', isPosixPathSeparator)

  if (resolvedAbsolute) {
    return `/${resolvedPath}`
  }

  return resolvedPath.length > 0 ? resolvedPath : '.'
}

exports.normalize = function normalize(path) {
  if (path.length === 0) return '.'

  const isAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH
  const trailingSeparator = path.charCodeAt(path.length - 1) === CHAR_FORWARD_SLASH

  path = normalizeString(path, !isAbsolute, '/', isPosixPathSeparator)

  if (path.length === 0) {
    if (isAbsolute) return '/'
    return trailingSeparator ? './' : '.'
  }

  if (trailingSeparator) path += '/'

  return isAbsolute ? `/${path}` : path
}

exports.isAbsolute = function isAbsolute(path) {
  return path.length > 0 && path.charCodeAt(0) === CHAR_FORWARD_SLASH
}

exports.join = function join(...args) {
  if (args.length === 0) return '.'
  let joined
  for (let i = 0; i < args.length; ++i) {
    const arg = args[i]
    if (arg.length > 0) {
      if (joined === undefined) joined = arg
      else joined += `/${arg}`
    }
  }
  if (joined === undefined) return '.'
  return exports.normalize(joined)
}

exports.relative = function relative(from, to) {
  if (from === to) return ''

  from = exports.resolve(from)
  to = exports.resolve(to)

  if (from === to) return ''

  const fromStart = 1
  const fromEnd = from.length
  const fromLen = fromEnd - fromStart
  const toStart = 1
  const toLen = to.length - toStart

  const length = fromLen < toLen ? fromLen : toLen
  let lastCommonSep = -1
  let i = 0
  for (; i < length; i++) {
    const fromCode = from.charCodeAt(fromStart + i)
    if (fromCode !== to.charCodeAt(toStart + i)) {
      break
    } else if (fromCode === CHAR_FORWARD_SLASH) {
      lastCommonSep = i
    }
  }
  if (i === length) {
    if (toLen > length) {
      if (to.charCodeAt(toStart + i) === CHAR_FORWARD_SLASH) {
        return to.substring(toStart + i + 1)
      }
      if (i === 0) {
        return to.substring(toStart + i)
      }
    } else if (fromLen > length) {
      if (from.charCodeAt(fromStart + i) === CHAR_FORWARD_SLASH) {
        lastCommonSep = i
      } else if (i === 0) {
        lastCommonSep = 0
      }
    }
  }

  let out = ''
  for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
    if (i === fromEnd || from.charCodeAt(i) === CHAR_FORWARD_SLASH) {
      out += out.length === 0 ? '..' : '/..'
    }
  }

  return `${out}${to.substring(toStart + lastCommonSep)}`
}

exports.toNamespacedPath = function toNamespacedPath(path) {
  return path
}

exports.dirname = function dirname(path) {
  if (path.length === 0) return '.'
  const hasRoot = path.charCodeAt(0) === CHAR_FORWARD_SLASH
  let end = -1
  let matchedSlash = true
  for (let i = path.length - 1; i >= 1; --i) {
    if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) {
      if (!matchedSlash) {
        end = i
        break
      }
    } else {
      matchedSlash = false
    }
  }

  if (end === -1) return hasRoot ? '/' : '.'
  if (hasRoot && end === 1) return '//'
  return path.substring(0, end)
}

exports.basename = function basename(path, suffix) {
  let start = 0
  let end = -1
  let matchedSlash = true

  if (suffix !== undefined && suffix.length > 0 && suffix.length <= path.length) {
    if (suffix === path) {
      return ''
    }
    let extIdx = suffix.length - 1
    let firstNonSlashEnd = -1
    for (let i = path.length - 1; i >= 0; --i) {
      const code = path.charCodeAt(i)
      if (code === CHAR_FORWARD_SLASH) {
        if (!matchedSlash) {
          start = i + 1
          break
        }
      } else {
        if (firstNonSlashEnd === -1) {
          matchedSlash = false
          firstNonSlashEnd = i + 1
        }
        if (extIdx >= 0) {
          if (code === suffix.charCodeAt(extIdx)) {
            if (--extIdx === -1) {
              end = i
            }
          } else {
            extIdx = -1
            end = firstNonSlashEnd
          }
        }
      }
    }

    if (start === end) end = firstNonSlashEnd
    else if (end === -1) end = path.length
    return path.substring(start, end)
  }

  for (let i = path.length - 1; i >= 0; --i) {
    if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) {
      if (!matchedSlash) {
        start = i + 1
        break
      }
    } else if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
  }

  if (end === -1) return ''
  return path.substring(start, end)
}

exports.extname = function extname(path) {
  let startDot = -1
  let startPart = 0
  let end = -1
  let matchedSlash = true
  let preDotState = 0
  for (let i = path.length - 1; i >= 0; --i) {
    const code = path.charCodeAt(i)
    if (code === CHAR_FORWARD_SLASH) {
      if (!matchedSlash) {
        startPart = i + 1
        break
      }
      continue
    }
    if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
    if (code === CHAR_DOT) {
      if (startDot === -1) startDot = i
      else if (preDotState !== 1) preDotState = 1
    } else if (startDot !== -1) {
      preDotState = -1
    }
  }

  if (
    startDot === -1 ||
    end === -1 ||
    preDotState === 0 ||
    (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1)
  ) {
    return ''
  }
  return path.substring(startDot, end)
}
const { CHAR_DOT, CHAR_FORWARD_SLASH } = require('./constants')

exports.normalizeString = function normalizeString(
  path,
  allowAboveRoot,
  separator,
  isPathSeparator
) {
  let res = ''
  let lastSegmentLength = 0
  let lastSlash = -1
  let dots = 0
  let code = 0
  for (let i = 0; i <= path.length; ++i) {
    if (i < path.length) {
      code = path.charCodeAt(i)
    } else if (isPathSeparator(code)) {
      break
    } else {
      code = CHAR_FORWARD_SLASH
    }

    if (isPathSeparator(code)) {
      if (lastSlash === i - 1 || dots === 1);
      else if (dots === 2) {
        if (
          res.length < 2 ||
          lastSegmentLength !== 2 ||
          res.charCodeAt(res.length - 1) !== CHAR_DOT ||
          res.charCodeAt(res.length - 2) !== CHAR_DOT
        ) {
          if (res.length > 2) {
            const lastSlashIndex = res.lastIndexOf(separator)
            if (lastSlashIndex === -1) {
              res = ''
              lastSegmentLength = 0
            } else {
              res = res.substring(0, lastSlashIndex)
              lastSegmentLength = res.length - 1 - res.lastIndexOf(separator)
            }
            lastSlash = i
            dots = 0
            continue
          } else if (res.length !== 0) {
            res = ''
            lastSegmentLength = 0
            lastSlash = i
            dots = 0
            continue
          }
        }
        if (allowAboveRoot) {
          res += res.length > 0 ? `${separator}..` : '..'
          lastSegmentLength = 2
        }
      } else {
        if (res.length > 0) {
          res += `${separator}${path.substring(lastSlash + 1, i)}`
        } else {
          res = path.substring(lastSlash + 1, i)
        }
        lastSegmentLength = i - lastSlash - 1
      }
      lastSlash = i
      dots = 0
    } else if (code === CHAR_DOT && dots !== -1) {
      ++dots
    } else {
      dots = -1
    }
  }
  return res
}
const os = require('bare-os')

const { normalizeString } = require('./shared')
const {
  CHAR_UPPERCASE_A,
  CHAR_LOWERCASE_A,
  CHAR_UPPERCASE_Z,
  CHAR_LOWERCASE_Z,
  CHAR_DOT,
  CHAR_FORWARD_SLASH,
  CHAR_BACKWARD_SLASH,
  CHAR_COLON,
  CHAR_QUESTION_MARK
} = require('./constants')

function isWindowsPathSeparator(code) {
  return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH
}

function isWindowsDeviceRoot(code) {
  return (
    (code >= CHAR_UPPERCASE_A && code <= CHAR_UPPERCASE_Z) ||
    (code >= CHAR_LOWERCASE_A && code <= CHAR_LOWERCASE_Z)
  )
}

exports.posix = require('./posix')
exports.win32 = exports

exports.sep = '\\'
exports.delimiter = ';'

exports.resolve = function resolve(...args) {
  let resolvedDevice = ''
  let resolvedTail = ''
  let resolvedAbsolute = false

  for (let i = args.length - 1; i >= -1; i--) {
    let path
    if (i >= 0) {
      path = args[i]

      if (path.length === 0) continue
    } else if (resolvedDevice.length === 0) {
      path = os.cwd()
    } else {
      path = os.getEnv(`=${resolvedDevice}`) || os.cwd()

      if (
        path === undefined ||
        (path.substring(0, 2).toLowerCase() !== resolvedDevice.toLowerCase() &&
          path.charCodeAt(2) === CHAR_BACKWARD_SLASH)
      ) {
        path = `${resolvedDevice}\\`
      }
    }

    const len = path.length
    let rootEnd = 0
    let device = ''
    let isAbsolute = false
    const code = path.charCodeAt(0)

    if (len === 1) {
      if (isWindowsPathSeparator(code)) {
        rootEnd = 1
        isAbsolute = true
      }
    } else if (isWindowsPathSeparator(code)) {
      isAbsolute = true

      if (isWindowsPathSeparator(path.charCodeAt(1))) {
        let j = 2
        let last = j
        while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
          j++
        }
        if (j < len && j !== last) {
          const firstPart = path.substring(last, j)
          last = j
          while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
            j++
          }
          if (j < len && j !== last) {
            last = j
            while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
              j++
            }
            if (j === len || j !== last) {
              device = `\\\\${firstPart}\\${path.substring(last, j)}`
              rootEnd = j
            }
          }
        }
      } else {
        rootEnd = 1
      }
    } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
      device = path.substring(0, 2)
      rootEnd = 2
      if (len > 2 && isWindowsPathSeparator(path.charCodeAt(2))) {
        isAbsolute = true
        rootEnd = 3
      }
    }

    if (device.length > 0) {
      if (resolvedDevice.length > 0) {
        if (device.toLowerCase() !== resolvedDevice.toLowerCase()) {
          continue
        }
      } else {
        resolvedDevice = device
      }
    }

    if (resolvedAbsolute) {
      if (resolvedDevice.length > 0) {
        break
      }
    } else {
      resolvedTail = `${path.substring(rootEnd)}\\${resolvedTail}`
      resolvedAbsolute = isAbsolute
      if (isAbsolute && resolvedDevice.length > 0) {
        break
      }
    }
  }

  resolvedTail = normalizeString(resolvedTail, !resolvedAbsolute, '\\', isWindowsPathSeparator)

  return resolvedAbsolute
    ? `${resolvedDevice}\\${resolvedTail}`
    : `${resolvedDevice}${resolvedTail}` || '.'
}

exports.normalize = function normalize(path) {
  const len = path.length
  if (len === 0) return '.'
  let rootEnd = 0
  let device
  let isAbsolute = false
  const code = path.charCodeAt(0)

  if (len === 1) {
    return code === CHAR_FORWARD_SLASH ? '\\' : path
  }

  if (isWindowsPathSeparator(code)) {
    isAbsolute = true

    if (isWindowsPathSeparator(path.charCodeAt(1))) {
      let j = 2
      let last = j
      while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
        j++
      }
      if (j < len && j !== last) {
        const firstPart = path.substring(last, j)
        last = j
        while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
          j++
        }
        if (j < len && j !== last) {
          last = j
          while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
            j++
          }
          if (j === len) {
            return `\\\\${firstPart}\\${path.substring(last)}\\`
          }
          if (j !== last) {
            device = `\\\\${firstPart}\\${path.substring(last, j)}`
            rootEnd = j
          }
        }
      }
    } else {
      rootEnd = 1
    }
  } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
    device = path.substring(0, 2)
    rootEnd = 2
    if (len > 2 && isWindowsPathSeparator(path.charCodeAt(2))) {
      isAbsolute = true
      rootEnd = 3
    }
  }

  let tail =
    rootEnd < len
      ? normalizeString(path.substring(rootEnd), !isAbsolute, '\\', isWindowsPathSeparator)
      : ''
  if (tail.length === 0 && !isAbsolute) {
    tail = '.'
  }
  if (tail.length > 0 && isWindowsPathSeparator(path.charCodeAt(len - 1))) {
    tail += '\\'
  }
  if (device === undefined) {
    return isAbsolute ? `\\${tail}` : tail
  }
  return isAbsolute ? `${device}\\${tail}` : `${device}${tail}`
}

exports.isAbsolute = function isAbsolute(path) {
  const len = path.length
  if (len === 0) return false

  const code = path.charCodeAt(0)

  return (
    isWindowsPathSeparator(code) ||
    (len > 2 &&
      isWindowsDeviceRoot(code) &&
      path.charCodeAt(1) === CHAR_COLON &&
      isWindowsPathSeparator(path.charCodeAt(2)))
  )
}

exports.join = function join(...args) {
  if (args.length === 0) return '.'

  let joined
  let firstPart
  for (let i = 0; i < args.length; ++i) {
    const arg = args[i]
    if (arg.length > 0) {
      if (joined === undefined) joined = firstPart = arg
      else joined += `\\${arg}`
    }
  }

  if (joined === undefined) return '.'

  let needsReplace = true
  let slashCount = 0
  if (isWindowsPathSeparator(firstPart.charCodeAt(0))) {
    ++slashCount
    const firstLen = firstPart.length
    if (firstLen > 1 && isWindowsPathSeparator(firstPart.charCodeAt(1))) {
      ++slashCount
      if (firstLen > 2) {
        if (isWindowsPathSeparator(firstPart.charCodeAt(2))) {
          ++slashCount
        } else {
          needsReplace = false
        }
      }
    }
  }
  if (needsReplace) {
    while (slashCount < joined.length && isWindowsPathSeparator(joined.charCodeAt(slashCount))) {
      slashCount++
    }

    if (slashCount >= 2) {
      joined = `\\${joined.substring(slashCount)}`
    }
  }

  return exports.normalize(joined)
}

exports.relative = function relative(from, to) {
  if (from === to) return ''

  const fromOrig = exports.resolve(from)
  const toOrig = exports.resolve(to)

  if (fromOrig === toOrig) return ''

  from = fromOrig.toLowerCase()
  to = toOrig.toLowerCase()

  if (from === to) return ''

  let fromStart = 0
  while (fromStart < from.length && from.charCodeAt(fromStart) === CHAR_BACKWARD_SLASH) {
    fromStart++
  }
  let fromEnd = from.length
  while (fromEnd - 1 > fromStart && from.charCodeAt(fromEnd - 1) === CHAR_BACKWARD_SLASH) {
    fromEnd--
  }
  const fromLen = fromEnd - fromStart

  let toStart = 0
  while (toStart < to.length && to.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) {
    toStart++
  }
  let toEnd = to.length
  while (toEnd - 1 > toStart && to.charCodeAt(toEnd - 1) === CHAR_BACKWARD_SLASH) {
    toEnd--
  }
  const toLen = toEnd - toStart

  const length = fromLen < toLen ? fromLen : toLen
  let lastCommonSep = -1
  let i = 0
  for (; i < length; i++) {
    const fromCode = from.charCodeAt(fromStart + i)
    if (fromCode !== to.charCodeAt(toStart + i)) {
      break
    } else if (fromCode === CHAR_BACKWARD_SLASH) {
      lastCommonSep = i
    }
  }

  if (i !== length) {
    if (lastCommonSep === -1) return toOrig
  } else {
    if (toLen > length) {
      if (to.charCodeAt(toStart + i) === CHAR_BACKWARD_SLASH) {
        return toOrig.substring(toStart + i + 1)
      }
      if (i === 2) {
        return toOrig.substring(toStart + i)
      }
    }
    if (fromLen > length) {
      if (from.charCodeAt(fromStart + i) === CHAR_BACKWARD_SLASH) {
        lastCommonSep = i
      } else if (i === 2) {
        lastCommonSep = 3
      }
    }
    if (lastCommonSep === -1) lastCommonSep = 0
  }

  let out = ''
  for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
    if (i === fromEnd || from.charCodeAt(i) === CHAR_BACKWARD_SLASH) {
      out += out.length === 0 ? '..' : '\\..'
    }
  }

  toStart += lastCommonSep

  if (out.length > 0) {
    return `${out}${toOrig.substring(toStart, toEnd)}`
  }
  if (toOrig.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) {
    ++toStart
  }
  return toOrig.substring(toStart, toEnd)
}

exports.toNamespacedPath = function toNamespacedPath(path) {
  if (path.length === 0) return path

  const resolvedPath = exports.resolve(path)

  if (resolvedPath.length <= 2) return path

  if (resolvedPath.charCodeAt(0) === CHAR_BACKWARD_SLASH) {
    if (resolvedPath.charCodeAt(1) === CHAR_BACKWARD_SLASH) {
      const code = resolvedPath.charCodeAt(2)
      if (code !== CHAR_QUESTION_MARK && code !== CHAR_DOT) {
        return `\\\\?\\UNC\\${resolvedPath.substring(2)}`
      }
    }
  } else if (
    isWindowsDeviceRoot(resolvedPath.charCodeAt(0)) &&
    resolvedPath.charCodeAt(1) === CHAR_COLON &&
    resolvedPath.charCodeAt(2) === CHAR_BACKWARD_SLASH
  ) {
    return `\\\\?\\${resolvedPath}`
  }

  return path
}

exports.dirname = function dirname(path) {
  const len = path.length
  if (len === 0) return '.'
  let rootEnd = -1
  let offset = 0
  const code = path.charCodeAt(0)

  if (len === 1) {
    return isWindowsPathSeparator(code) ? path : '.'
  }

  if (isWindowsPathSeparator(code)) {
    rootEnd = offset = 1

    if (isWindowsPathSeparator(path.charCodeAt(1))) {
      let j = 2
      let last = j
      while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
        j++
      }
      if (j < len && j !== last) {
        last = j
        while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
          j++
        }
        if (j < len && j !== last) {
          last = j
          while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
            j++
          }
          if (j === len) {
            return path
          }
          if (j !== last) {
            rootEnd = offset = j + 1
          }
        }
      }
    }
  } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
    rootEnd = len > 2 && isWindowsPathSeparator(path.charCodeAt(2)) ? 3 : 2
    offset = rootEnd
  }

  let end = -1
  let matchedSlash = true
  for (let i = len - 1; i >= offset; --i) {
    if (isWindowsPathSeparator(path.charCodeAt(i))) {
      if (!matchedSlash) {
        end = i
        break
      }
    } else {
      matchedSlash = false
    }
  }

  if (end === -1) {
    if (rootEnd === -1) return '.'

    end = rootEnd
  }
  return path.substring(0, end)
}

exports.basename = function basename(path, suffix) {
  let start = 0
  let end = -1
  let matchedSlash = true

  if (
    path.length >= 2 &&
    isWindowsDeviceRoot(path.charCodeAt(0)) &&
    path.charCodeAt(1) === CHAR_COLON
  ) {
    start = 2
  }

  if (suffix !== undefined && suffix.length > 0 && suffix.length <= path.length) {
    if (suffix === path) return ''
    let extIdx = suffix.length - 1
    let firstNonSlashEnd = -1
    for (let i = path.length - 1; i >= start; --i) {
      const code = path.charCodeAt(i)
      if (isWindowsPathSeparator(code)) {
        if (!matchedSlash) {
          start = i + 1
          break
        }
      } else {
        if (firstNonSlashEnd === -1) {
          matchedSlash = false
          firstNonSlashEnd = i + 1
        }
        if (extIdx >= 0) {
          if (code === suffix.charCodeAt(extIdx)) {
            if (--extIdx === -1) {
              end = i
            }
          } else {
            extIdx = -1
            end = firstNonSlashEnd
          }
        }
      }
    }

    if (start === end) end = firstNonSlashEnd
    else if (end === -1) end = path.length
    return path.substring(start, end)
  }
  for (let i = path.length - 1; i >= start; --i) {
    if (isWindowsPathSeparator(path.charCodeAt(i))) {
      if (!matchedSlash) {
        start = i + 1
        break
      }
    } else if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
  }

  if (end === -1) return ''
  return path.substring(start, end)
}

exports.extname = function extname(path) {
  let start = 0
  let startDot = -1
  let startPart = 0
  let end = -1
  let matchedSlash = true
  let preDotState = 0

  if (
    path.length >= 2 &&
    path.charCodeAt(1) === CHAR_COLON &&
    isWindowsDeviceRoot(path.charCodeAt(0))
  ) {
    start = startPart = 2
  }

  for (let i = path.length - 1; i >= start; --i) {
    const code = path.charCodeAt(i)
    if (isWindowsPathSeparator(code)) {
      if (!matchedSlash) {
        startPart = i + 1
        break
      }
      continue
    }
    if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
    if (code === CHAR_DOT) {
      if (startDot === -1) startDot = i
      else if (preDotState !== 1) preDotState = 1
    } else if (startDot !== -1) {
      preDotState = -1
    }
  }

  if (
    startDot === -1 ||
    end === -1 ||
    preDotState === 0 ||
    (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1)
  ) {
    return ''
  }
  return path.substring(startDot, end)
}
{
  "name": "bare-path",
  "version": "3.0.1",
  "description": "Path manipulation library for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./posix": "./lib/posix.js",
    "./win32": "./lib/win32.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "lib",
    "NOTICE"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-path.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-path/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-path#readme",
  "dependencies": {
    "bare-os": "^3.0.1"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "lunte": "^1.8.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
const b4a = require('b4a')
const stream = require('streamx')
const { ReadableStream, WritableStream } = require('./web')

const defaultEncoding = 'utf8'

module.exports = exports = stream.Stream

exports.pipeline = stream.pipeline

exports.isStream = stream.isStream
exports.isEnding = stream.isEnding
exports.isEnded = stream.isEnded
exports.isFinishing = stream.isFinishing
exports.isFinished = stream.isFinished
exports.isDisturbed = stream.isDisturbed

exports.isErrored = function isErrored(stream) {
  return exports.getStreamError(stream) !== null
}

exports.isReadable = function isReadable(stream) {
  return stream.readable && !stream.destroying && !exports.isEnded(stream)
}

exports.isWritable = function isWritable(stream) {
  return stream.writable && !stream.destroying && !exports.isFinishing(stream)
}

exports.getStreamError = stream.getStreamError

exports.addAbortSignal = function addAbortSignal(signal, stream) {
  function onAbort() {
    stream.destroy(signal.reason)
  }

  if (signal.aborted) onAbort()
  else signal.addEventListener('abort', onAbort)

  return stream
}

exports.Stream = exports

exports.Readable = class Readable extends stream.Readable {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthReadable: null,
      map: null,
      mapReadable: null
    })

    if (this._construct) this._open = this._construct

    if (this._read !== stream.Readable.prototype._read) {
      this._read = read.bind(this, this._read)
    }

    if (this._destroy !== stream.Stream.prototype._destroy) {
      this._destroy = destroy.bind(this, this._destroy)
    }
  }

  get closed() {
    return !exports.isReadable(this)
  }

  get errored() {
    return stream.getStreamError(this)
  }

  push(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    return super.push(chunk)
  }

  unshift(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    super.unshift(chunk)
  }

  static fromWeb(readableStream, opts = {}) {
    const stream = readableStream._stream

    if (opts.encoding) stream.setEncoding(opts.encoding)
    if (opts.signal) exports.addAbortSignal(opts.signal, stream)

    return stream
  }

  static toWeb(readable, opts = {}) {
    return new ReadableStream(readable, opts.strategy)
  }

  async [Symbol.asyncDispose]() {
    if (!this.destroyed) this.destroy()

    await new Promise((resolve) => exports.finished(this, resolve))
  }
}

exports.Writable = class Writable extends stream.Writable {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthWritable,
      map: null,
      mapWritable: null
    })

    if (this._construct) this._open = this._construct

    if (this._write !== stream.Writable.prototype._write) {
      this._write = write.bind(this, this._write)
    }

    if (this._destroy !== stream.Stream.prototype._destroy) {
      this._destroy = destroy.bind(this, this._destroy)
    }
  }

  get closed() {
    return !exports.isWritable(this)
  }

  get errored() {
    return stream.getStreamError(this)
  }

  write(chunk, encoding, cb) {
    if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result = super.write({ chunk, encoding })

    if (cb) stream.Writable.drained(this).then(() => cb(null), cb)

    return result
  }

  end(chunk, encoding, cb) {
    if (typeof chunk === 'function') {
      cb = chunk
      chunk = null
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    } else {
      encoding = 'buffer'
    }

    const result =
      chunk !== undefined && chunk !== null ? super.end({ chunk, encoding }) : super.end()

    if (cb) this.once('finish', () => cb(null))

    return result
  }

  static fromWeb(writableStream, opts = {}) {
    const stream = writableStream._stream

    if (opts.signal) exports.addAbortSignal(opts.signal, stream)

    return stream
  }

  static toWeb(writable) {
    return new WritableStream(writable)
  }

  async [Symbol.asyncDispose]() {
    if (!this.destroyed) this.destroy()

    await new Promise((resolve) => exports.finished(this, resolve))
  }
}

exports.Duplex = class Duplex extends stream.Duplex {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthReadable: null,
      byteLengthWritable,
      map: null,
      mapReadable: null,
      mapWritable: null
    })

    if (this._construct) this._open = this._construct

    if (this._read !== stream.Readable.prototype._read) {
      this._read = read.bind(this, this._read)
    }

    if (this._write !== stream.Duplex.prototype._write) {
      this._write = write.bind(this, this._write)
    }

    if (this._destroy !== stream.Stream.prototype._destroy) {
      this._destroy = destroy.bind(this, this._destroy)
    }
  }

  push(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    return super.push(chunk)
  }

  unshift(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    super.unshift(chunk)
  }

  write(chunk, encoding, cb) {
    if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result = super.write({ chunk, encoding })

    if (cb) stream.Writable.drained(this).then(() => cb(null), cb)

    return result
  }

  end(chunk, encoding, cb) {
    if (typeof chunk === 'function') {
      cb = chunk
      chunk = null
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result =
      chunk !== undefined && chunk !== null ? super.end({ chunk, encoding }) : super.end()

    if (cb) this.once('finish', () => cb(null))

    return result
  }

  static fromWeb({ readable: readableStream, writable: writableStream }, opts) {
    const readable = exports.Readable.fromWeb(readableStream, opts)
    const writable = exports.Writable.fromWeb(writableStream, opts)

    const duplex = new exports.Duplex({
      write(data, encoding, cb) {
        writable.write(data, encoding, cb)
      }
    })

    readable
      .on('data', (data) => duplex.push(data))
      .on('end', () => duplex.push(null))
      .on('error', (err) => duplex.destroy(err))

    writable.on('finish', () => duplex.end()).on('error', (err) => duplex.destroy(err))

    return duplex
  }

  static toWeb(duplex) {
    const readableStream = exports.Readable.toWeb(duplex)
    const writableStream = exports.Writable.toWeb(duplex)

    return { readable: readableStream, writable: writableStream }
  }
}

class DuplexSide extends exports.Duplex {
  constructor(opts) {
    super(opts)

    this._otherSide = null
    this._cb = null
  }

  _read() {
    const cb = this._cb
    if (!cb) return

    this._cb = null
    cb()
  }

  _write(chunk, encoding, cb) {
    this._otherSide.push(chunk, encoding)
    this._otherSide._cb = cb
  }

  _final(cb) {
    this._otherSide.on('end', cb)
    this._otherSide.push(null)
  }
}

exports.duplexPair = function duplexPair(opts) {
  const sideA = new DuplexSide(opts)
  const sideB = new DuplexSide(opts)

  sideA._otherSide = sideB
  sideB._otherSide = sideA

  return [sideA, sideB]
}

exports.Transform = class Transform extends stream.Transform {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthReadable: null,
      byteLengthWritable,
      map: null,
      mapReadable: null,
      mapWritable: null
    })

    if (this._transform !== stream.Transform.prototype._transform) {
      this._transform = transform.bind(this, this._transform)
    } else {
      this._transform = passthrough
    }
  }

  push(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    return super.push(chunk)
  }

  unshift(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    super.unshift(chunk)
  }

  write(chunk, encoding, cb) {
    if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result = super.write({ chunk, encoding })

    if (cb) stream.Writable.drained(this).then(() => cb(null), cb)

    return result
  }

  end(chunk, encoding, cb) {
    if (typeof chunk === 'function') {
      cb = chunk
      chunk = null
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result =
      chunk !== undefined && chunk !== null ? super.end({ chunk, encoding }) : super.end()

    if (cb) this.once('finish', () => cb(null))

    return result
  }
}

exports.PassThrough = class PassThrough extends exports.Transform {}

exports.finished = function finished(stream, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (!opts) opts = {}

  const { cleanup = false } = opts

  const done = () => {
    cb(exports.getStreamError(stream, { all: true }))

    if (cleanup) detach()
  }

  const detach = () => {
    stream.off('close', done)
    stream.off('error', noop)
  }

  if (stream.destroyed) {
    done()
  } else {
    stream.on('close', done)
    stream.on('error', noop)
  }

  return detach
}

function read(read, cb) {
  read.call(this, 65536)

  cb(null)
}

function write(write, data, cb) {
  write.call(this, data.chunk, data.encoding, cb)
}

function transform(transform, data, cb) {
  transform.call(this, data.chunk, data.encoding, cb)
}

function destroy(destroy, cb) {
  destroy.call(this, exports.getStreamError(this), cb)
}

function passthrough(data, cb) {
  cb(null, data.chunk)
}

function byteLengthWritable(data) {
  return data.chunk.byteLength
}

function noop() {}
{
  "name": "bare-stream",
  "version": "2.13.3",
  "description": "Streaming data for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./promises": "./promises.js",
    "./web": {
      "types": "./web.d.ts",
      "default": "./web.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "promises.js",
    "web.js",
    "web.d.ts",
    "global.js",
    "global.d.ts"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-stream.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-stream/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-stream#readme",
  "dependencies": {
    "b4a": "^1.8.1",
    "streamx": "^2.25.0",
    "teex": "^1.0.1"
  },
  "devDependencies": {
    "bare-abort-controller": "^1.1.0",
    "bare-buffer": "^3.0.0",
    "bare-events": "^2.5.4",
    "brittle": "^3.5.2",
    "lunte": "^1.6.0",
    "prettier": "^3.3.3",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "bare-abort-controller": "*",
    "bare-buffer": "*",
    "bare-events": "*"
  },
  "peerDependenciesMeta": {
    "bare-abort-controller": {
      "optional": true
    },
    "bare-buffer": {
      "optional": true
    },
    "bare-events": {
      "optional": true
    }
  }
}
const { Readable, Writable, Transform, getStreamError, isStreamx, isDisturbed } = require('streamx')
const tee = require('teex')

const readableKind = Symbol.for('bare.stream.readable.kind')
const writableKind = Symbol.for('bare.stream.writable.kind')
const transformKind = Symbol.for('bare.stream.transform.kind')

// https://streams.spec.whatwg.org/#readablestreamdefaultreader
exports.ReadableStreamDefaultReader = class ReadableStreamDefaultReader {
  constructor(stream) {
    this._stream = stream
    this._stream._stream.once('close', onclose).once('error', onerror)

    const closed = Promise.withResolvers()

    // Avoid unhandled exceptions
    closed.promise.catch(noop)

    this._closed = closed

    function onclose() {
      closed.resolve()
    }

    function onerror(err) {
      closed.reject(err)
    }
  }

  get closed() {
    return this._closed.promise
  }

  read() {
    const stream = this._stream._stream

    return new Promise((resolve, reject) => {
      const err = getStreamError(stream)

      if (err) return reject(err)

      if (stream.destroyed) {
        return resolve({ value: undefined, done: true })
      }

      const value = stream.read()

      if (value !== null) {
        return resolve({ value, done: false })
      }

      stream.once('readable', onreadable).once('close', onclose).once('error', onerror)

      function onreadable() {
        const value = stream.read()

        ondone(null, value === null ? { value: undefined, done: true } : { value, done: false })
      }

      function onclose() {
        ondone(null, { value: undefined, done: true })
      }

      function onerror(err) {
        ondone(err, null)
      }

      function ondone(err, value) {
        stream.off('readable', onreadable).off('close', onclose).off('error', onerror)

        if (err) reject(err)
        else resolve(value)
      }
    })
  }

  releaseLock() {
    this._closed.reject(new TypeError('Reader was released'))
    this._stream._releaseLock()
    this._stream = null
  }

  cancel(reason = new TypeError('Stream was cancelled')) {
    const stream = this._stream._stream

    if (stream.destroyed) return Promise.resolve()

    return new Promise((resolve) =>
      stream.once('close', resolve).once('error', noop).destroy(reason)
    )
  }
}

// https://streams.spec.whatwg.org/#readablestreamdefaultcontroller
exports.ReadableStreamDefaultController = class ReadableStreamDefaultController {
  constructor(stream) {
    this._stream = stream
  }

  get desiredSize() {
    const stream = this._stream._stream

    return stream._readableState.highWaterMark - stream._readableState.buffered
  }

  enqueue(data) {
    this._stream._stream.push(data)
  }

  close() {
    this._stream._stream.push(null)
  }

  error(err) {
    this._stream._stream.destroy(err)
  }
}

// https://streams.spec.whatwg.org/#readablestream
class ReadableStream {
  static get [readableKind]() {
    return 0 // Compatibility version
  }

  static from(iterable) {
    return new ReadableStream(Readable.from(iterable))
  }

  constructor(underlyingSource = {}, queuingStrategy) {
    if (isStreamx(underlyingSource)) {
      this._stream = underlyingSource
    } else {
      if (queuingStrategy === undefined) {
        queuingStrategy = new exports.CountQueuingStrategy()
      }

      const { start, pull, cancel } = underlyingSource
      const { highWaterMark = 1, size = defaultSize } = queuingStrategy

      this._stream = new Readable({ highWaterMark, byteLength: size })

      const controller = new exports.ReadableStreamDefaultController(this)

      try {
        let starting = Promise.resolve()

        if (start) starting = forwardError(start.call(this, controller), controller)

        if (pull) {
          this._stream._read = this._read.bind(this, starting, pull.bind(this, controller))
        }

        if (cancel) {
          this._stream.once('error', cancel.bind(this))
        }
      } catch (err) {
        controller.error(err)
      }
    }

    this._reader = null
  }

  get [readableKind]() {
    return ReadableStream[readableKind]
  }

  get locked() {
    return this._reader !== null
  }

  getReader() {
    if (this.locked) throw new TypeError('Stream is locked')

    this._reader = new exports.ReadableStreamDefaultReader(this)

    return this._reader
  }

  cancel(reason = new TypeError('Stream was cancelled')) {
    const stream = this._stream

    if (stream.destroyed) return Promise.resolve()

    if (this.locked) return Promise.reject(new TypeError('Stream is locked'))

    return new Promise((resolve) =>
      stream.once('close', resolve).once('error', noop).destroy(reason)
    )
  }

  tee() {
    const [a, b] = tee(this._stream)

    return [new ReadableStream(a), new ReadableStream(b)]
  }

  pipeTo(destination) {
    return new Promise((resolve, reject) =>
      this._stream.pipe(destination._stream, (err) => {
        err ? reject(err) : resolve()
      })
    )
  }

  [Symbol.asyncIterator]() {
    return this._stream[Symbol.asyncIterator]()
  }

  _releaseLock() {
    this._reader = null
  }

  async _read(starting, pull, cb) {
    await starting

    let err = null
    try {
      await pull()
    } catch (e) {
      err = e
    }
    cb(err)
  }
}

function defaultSize() {
  return 1
}

exports.ReadableStream = ReadableStream

// https://streams.spec.whatwg.org/#countqueuingstrategy
exports.CountQueuingStrategy = class CountQueuingStrategy {
  constructor(opts = {}) {
    const { highWaterMark = 1 } = opts

    this.highWaterMark = highWaterMark
  }

  size(chunk) {
    return 1
  }
}

// https://streams.spec.whatwg.org/#bytelengthqueuingstrategy
exports.ByteLengthQueuingStrategy = class ByteLengthQueuingStrategy {
  constructor(opts = {}) {
    const { highWaterMark = 16384 } = opts

    this.highWaterMark = highWaterMark
  }

  size(chunk) {
    return chunk.byteLength
  }
}

exports.isReadableStream = function isReadableStream(value) {
  if (value instanceof ReadableStream) return true

  return (
    typeof value === 'object' &&
    value !== null &&
    value[readableKind] === ReadableStream[readableKind]
  )
}

// https://streams.spec.whatwg.org/#readablestream-errored
exports.isReadableStreamErrored = function isReadableStreamErrored(stream) {
  return getStreamError(stream._stream) !== null
}

// https://streams.spec.whatwg.org/#is-readable-stream-disturbed
exports.isReadableStreamDisturbed = function isReadableStreamDisturbed(stream) {
  return isDisturbed(stream._stream)
}

// https://streams.spec.whatwg.org/#writablestreamdefaultwriter
exports.WritableStreamDefaultWriter = class WritableStreamDefaultWriter {
  constructor(stream) {
    this._stream = stream
    this._stream._stream.once('close', onclose).once('error', onerror)

    const closed = Promise.withResolvers()

    // Avoid unhandled exceptions
    closed.promise.catch(noop)

    this._closed = closed

    function onclose() {
      closed.resolve()
    }

    function onerror(err) {
      closed.reject(err)
    }
  }

  get desiredSize() {
    const stream = this._stream._stream

    return stream._writableState.highWaterMark - stream._writableState.buffered
  }

  get closed() {
    return this._closed.promise
  }

  get ready() {
    const stream = this._stream._stream

    if (getStreamError(stream)) return Promise.reject()

    return Writable.drained(stream).then()
  }

  async write(chunk) {
    const stream = this._stream._stream

    let err = getStreamError(stream)
    if (err) return Promise.reject(err)

    stream.write(chunk)

    await Writable.drained(stream)

    err = getStreamError(stream)
    if (err) return Promise.reject(err)
  }

  releaseLock() {
    this._closed.reject(new TypeError('Writer was released'))
    this._stream._releaseLock()
    this._stream = null
  }

  close() {
    const stream = this._stream._stream

    if (stream.destroyed) return Promise.resolve()

    return new Promise((resolve) => stream.once('close', resolve).end())
  }

  abort(reason = new TypeError('Stream was aborted')) {
    const stream = this._stream._stream

    if (stream.destroyed) return Promise.resolve()

    return new Promise((resolve) => stream.once('close', resolve).destroy(reason))
  }
}

// https://streams.spec.whatwg.org/#writablestreamdefaultcontroller
exports.WritableStreamDefaultController = class WritableStreamDefaultController {
  constructor(stream) {
    this._stream = stream
  }

  error(err) {
    this._stream._stream.destroy(err)
  }
}

// https://streams.spec.whatwg.org/#writablestream
class WritableStream {
  static get [writableKind]() {
    return 0 // Compatibility version
  }

  constructor(underlyingSink = {}, queuingStrategy = {}) {
    if (isStreamx(underlyingSink)) {
      this._stream = underlyingSink
    } else {
      if (queuingStrategy === undefined) {
        queuingStrategy = new exports.CountQueuingStrategy()
      }

      const { start, write, close, abort } = underlyingSink
      const { highWaterMark = 1, size = defaultSize } = queuingStrategy

      this._stream = new Writable({ highWaterMark, byteLength: size })

      const controller = new exports.WritableStreamDefaultController(this)

      this._controller = controller

      try {
        let starting = Promise.resolve()

        if (start) starting = forwardError(start.call(this, controller), controller)

        if (write) {
          this._stream._write = this._write.bind(this, starting, write.bind(this))
        }

        if (close) {
          this._stream._destroy = this._destroy.bind(this, close.call(this))
        }

        if (abort) {
          this._stream.once('error', abort.bind(this))
        }
      } catch (err) {
        controller.error(err)
      }
    }

    this._writer = null
  }

  get [writableKind]() {
    return WritableStream[writableKind]
  }

  get locked() {
    return this._writer !== null
  }

  getWriter() {
    if (this.locked) throw new TypeError('Stream is locked')

    this._writer = new exports.WritableStreamDefaultWriter(this)

    return this._writer
  }

  abort(reason = new TypeError('Stream was aborted')) {
    if (this._stream.destroyed) return Promise.resolve()

    if (this.locked) return Promise.reject(new TypeError('Stream is locked'))

    return new Promise((resolve) => this._stream.once('close', resolve).destroy(reason))
  }

  close() {
    if (this._stream.destroyed) return Promise.resolve()

    if (this.locked) return Promise.reject(new TypeError('Stream is locked'))

    return new Promise((resolve) => this._stream.once('close', resolve).end())
  }

  _releaseLock() {
    this._writer = null
  }

  async _write(starting, write, data, cb) {
    await starting

    let err = null
    try {
      await write(data, this._controller)
    } catch (e) {
      err = e
    }
    cb(err)
  }

  async _destroy(closing, cb) {
    let err = null
    try {
      await closing
    } catch (e) {
      err = e
    }
    cb(err)
  }
}

exports.WritableStream = WritableStream

exports.isWritableStream = function isWritableStream(value) {
  if (value instanceof WritableStream) return true

  return (
    typeof value === 'object' &&
    value !== null &&
    value[writableKind] === WritableStream[writableKind]
  )
}

// https://streams.spec.whatwg.org/#transformstreamdefaultcontroller
exports.TransformStreamDefaultController = class TransformStreamDefaultController {
  constructor(stream) {
    this._stream = stream
  }

  get desiredSize() {
    const stream = this._stream._stream

    return stream._readableState.highWaterMark - stream._readableState.buffered
  }

  enqueue(data) {
    this._stream._stream.push(data)
  }

  error(err) {
    this._stream._stream.destroy(err)
  }

  terminate() {
    const stream = this._stream._stream

    stream.push(null)
    stream.destroy(new TypeError('Stream has been terminated'))
  }
}

// https://streams.spec.whatwg.org/#transformstream
class TransformStream {
  static get [transformKind]() {
    return 0 // Compatibility version
  }

  constructor(transformer = {}, writableStrategy = {}, readableStrategy = {}) {
    if (isStreamx(transformer)) {
      this._stream = transformer
    } else {
      const { start, transform, flush } = transformer

      this._stream = new Transform({ ...writableStrategy, ...readableStrategy })

      const controller = new exports.TransformStreamDefaultController(this)

      this._controller = controller

      try {
        let starting = Promise.resolve()

        if (start) starting = forwardError(start.call(this, controller), controller)

        if (transform) {
          this._stream._transform = this._transform.bind(this, starting, transform.bind(this))
        }

        if (flush) {
          this._stream._flush = this._flush.bind(this, flush.call(this, this._controller))
        }
      } catch (err) {
        controller.error(err)
      }
    }

    this._writable = new WritableStream(this._stream)
    this._readable = new ReadableStream(this._stream)
  }

  get [transformKind]() {
    return TransformStream[transformKind]
  }

  get writable() {
    return this._writable
  }

  get readable() {
    return this._readable
  }

  async _transform(starting, transform, data, cb) {
    await starting

    let err = null
    try {
      await transform(data, this._controller)
    } catch (e) {
      err = e
    }
    cb(err)
  }

  async _flush(flush, cb) {
    let err = null
    try {
      await flush
    } catch (e) {
      err = e
    }
    cb(err)
  }
}

exports.TransformStream = TransformStream

exports.isTransformStream = function isTransformStream(value) {
  if (value instanceof TransformStream) return true

  return (
    typeof value === 'object' &&
    value !== null &&
    value[transformKind] === TransformStream[transformKind]
  )
}

async function forwardError(promise, controller) {
  try {
    await promise
  } catch (err) {
    controller.error(err)
  }
}

function noop() {}
module.exports = require.addon()
const binding = require('./binding')

const t = binding.constants

class Type {
  constructor(type) {
    this._type = type
  }

  isUndefined() {
    return this._type === t.UNDEFINED
  }

  isNull() {
    return this._type === t.NULL
  }

  isBoolean() {
    return this._type === t.BOOLEAN
  }

  isNumber() {
    return (this._type & 0xff) === t.NUMBER
  }

  isInt32() {
    return (this._type & (0xff | t.INT32)) === (t.NUMBER | t.INT32)
  }

  isUint32() {
    return (this._type & (0xff | t.UINT32)) === (t.NUMBER | t.UINT32)
  }

  isString() {
    return this._type === t.STRING
  }

  isSymbol() {
    return this._type === t.SYMBOL
  }

  isObject() {
    return (this._type & 0xff) === t.OBJECT
  }

  isArray() {
    return this._type === (t.OBJECT | t.ARRAY)
  }

  isArguments() {
    return this._type === (t.OBJECT | t.ARGUMENTS)
  }

  isDate() {
    return this._type === (t.OBJECT | t.DATE)
  }

  isRegExp() {
    return this._type === (t.OBJECT | t.REGEXP)
  }

  isError() {
    return this._type === (t.OBJECT | t.ERROR)
  }

  isPromise() {
    return this._type === (t.OBJECT | t.PROMISE)
  }

  isProxy() {
    return this._type === (t.OBJECT | t.PROXY)
  }

  isGenerator() {
    return this._type === (t.OBJECT | t.GENERATOR)
  }

  isMap() {
    return this._type === (t.OBJECT | t.MAP)
  }

  isSet() {
    return this._type === (t.OBJECT | t.SET)
  }

  isWeakMap() {
    return this._type === (t.OBJECT | t.WEAK_MAP)
  }

  isWeakSet() {
    return this._type === (t.OBJECT | t.WEAK_SET)
  }

  isWeakRef() {
    return this._type === (t.OBJECT | t.WEAK_REF)
  }

  isArrayBuffer() {
    return this._type === (t.OBJECT | t.ARRAYBUFFER)
  }

  isSharedArrayBuffer() {
    return this._type === (t.OBJECT | t.SHAREDARRAYBUFFER)
  }

  isTypedArray() {
    return (this._type & 0xffff) === (t.OBJECT | t.TYPEDARRAY)
  }

  isInt8Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT8ARRAY)
  }

  isUint8Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT8ARRAY)
  }

  isUint8ClampedArray() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT8CLAMPEDARRAY)
  }

  isInt16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT16ARRAY)
  }

  isUint16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT16ARRAY)
  }

  isInt32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT32ARRAY)
  }

  isUint32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT32ARRAY)
  }

  isFloat16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT16ARRAY)
  }

  isFloat32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT32ARRAY)
  }

  isFloat64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT64ARRAY)
  }

  isBigInt64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.BIGINT64ARRAY)
  }

  isBigUint64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.BIGUINT64ARRAY)
  }

  isDataView() {
    return this._type === (t.OBJECT | t.DATAVIEW)
  }

  isModuleNamespace() {
    return this._type === (t.OBJECT | t.MODULE_NAMESPACE)
  }

  isFunction() {
    return (this._type & 0xff) === t.FUNCTION
  }

  isAsyncFunction() {
    return (
      (this._type & (0xff | t.ASYNC_FUNCTION)) ===
      (t.FUNCTION | t.ASYNC_FUNCTION)
    )
  }

  isGeneratorFunction() {
    return (
      (this._type & (0xff | t.GENERATOR_FUNCTION)) ===
      (t.FUNCTION | t.GENERATOR_FUNCTION)
    )
  }

  isExternal() {
    return this._type === t.EXTERNAL
  }

  isBigInt() {
    return this._type === t.BIGINT
  }
}

module.exports = exports = function type(value) {
  switch (typeof value) {
    case 'undefined':
      return new Type(t.UNDEFINED)
    case 'boolean':
      return new Type(t.BOOLEAN)
    case 'number':
      return new Type(
        Number.isSafeInteger(value) ? binding.type(value) : t.NUMBER
      )
    case 'string':
      return new Type(t.STRING)
    case 'symbol':
      return new Type(t.SYMBOL)
    case 'object':
      return new Type(value === null ? t.NULL : binding.type(value))
    case 'function':
      return new Type(binding.type(value))
    case 'bigint':
      return new Type(t.BIGINT)
  }
}

exports.createTag = function createTag(...components) {
  const tag = new Uint32Array(4)
  for (let i = 0; i < 4; i++) tag[i] = components[i] || 0
  return tag
}

exports.addTag = function addTag(object, tag) {
  binding.addTag(object, tag)
}

exports.checkTag = function checkTag(object, tag) {
  return binding.checkTag(object, tag)
}
{
  "name": "bare-type",
  "version": "1.1.0",
  "description": "Cross-realm type predicates for Bare",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-type.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-type/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-type#readme",
  "engines": {
    "bare": ">=1.2.0"
  },
  "devDependencies": {
    "brittle": "^3.4.0",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
module.exports = require.addon()
const path = require('bare-path')
const binding = require('./binding')
const errors = require('./lib/errors')
const URLSearchParams = require('./lib/url-search-params')

const kind = Symbol.for('bare.url.kind')

const isWindows = Bare.platform === 'win32'

class URL {
  static get [kind]() {
    return 0 // Compatibility version
  }

  constructor(input, base, opts = {}) {
    if (arguments.length === 0) throw errors.INVALID_URL()

    input = String(input)

    if (base !== undefined) base = String(base)

    this._components = new Uint32Array(8)

    this._parse(input, base, opts.throw !== false)

    if (this._href) this._params = new URLSearchParams(this.search, this)
  }

  get [kind]() {
    return URL[kind]
  }

  // https://url.spec.whatwg.org/#dom-url-href

  get href() {
    return this._href
  }

  set href(value) {
    this._update(value)

    this._params._parse(this.search)
  }

  // https://url.spec.whatwg.org/#dom-url-protocol

  get protocol() {
    return this._slice(0, this._components[0]) + ':'
  }

  set protocol(value) {
    this._update(this._replace(value.replace(/:+$/, ''), 0, this._components[0]))
  }

  // https://url.spec.whatwg.org/#dom-url-username

  get username() {
    return this._slice(this._components[0] + 3 /* :// */, this._components[1])
  }

  set username(value) {
    if (cannotHaveCredentialsOrPort(this)) {
      return
    }

    if (this.username === '') value += '@'

    this._update(this._replace(value, this._components[0] + 3 /* :// */, this._components[1]))
  }

  // https://url.spec.whatwg.org/#dom-url-password

  get password() {
    return this._href.slice(this._components[1] + 1 /* : */, this._components[2] - 1 /* @ */)
  }

  set password(value) {
    if (cannotHaveCredentialsOrPort(this)) {
      return
    }

    let start = this._components[1] + 1 /* : */
    let end = this._components[2] - 1 /* @ */

    if (this.password === '') {
      value = ':' + value
      start--
    }

    if (this.username === '') {
      value += '@'
      end++
    }

    this._update(this._replace(value, start, end))
  }

  // https://url.spec.whatwg.org/#dom-url-host

  get host() {
    return this._slice(this._components[2], this._components[5])
  }

  set host(value) {
    if (hasOpaquePath(this)) {
      return
    }

    this._update(
      this._replace(value, this._components[2], this._components[value.includes(':') ? 5 : 3])
    )
  }

  // https://url.spec.whatwg.org/#dom-url-hostname

  get hostname() {
    return this._slice(this._components[2], this._components[3])
  }

  set hostname(value) {
    if (hasOpaquePath(this)) {
      return
    }

    this._update(this._replace(value, this._components[2], this._components[3]))
  }

  // https://url.spec.whatwg.org/#dom-url-port

  get port() {
    return this._slice(this._components[3] + 1 /* : */, this._components[5])
  }

  set port(value) {
    if (cannotHaveCredentialsOrPort(this)) {
      return
    }

    let start = this._components[3] + 1 /* : */

    if (this.port === '') {
      value = ':' + value
      start--
    }

    this._update(this._replace(value, start, this._components[5]))
  }

  // https://url.spec.whatwg.org/#dom-url-pathname

  get pathname() {
    return this._slice(this._components[5], this._components[6] - 1 /* ? */)
  }

  set pathname(value) {
    if (hasOpaquePath(this)) {
      return
    }

    if (value[0] !== '/' && value[0] !== '\\') {
      value = '/' + value
    }

    this._update(this._replace(value, this._components[5], this._components[6] - 1 /* ? */))
  }

  // https://url.spec.whatwg.org/#dom-url-search

  get search() {
    return this._slice(this._components[6] - 1 /* ? */, this._components[7] - 1 /* # */)
  }

  set search(value) {
    if (value && value[0] !== '?') value = '?' + value

    this._update(
      this._replace(value, this._components[6] - 1 /* ? */, this._components[7] - 1 /* # */)
    )

    this._params._parse(this.search)
  }

  // https://url.spec.whatwg.org/#dom-url-searchparams

  get searchParams() {
    return this._params
  }

  // https://url.spec.whatwg.org/#dom-url-hash

  get hash() {
    return this._slice(this._components[7] - 1 /* # */)
  }

  set hash(value) {
    if (value && value[0] !== '#') value = '#' + value

    this._update(this._replace(value, this._components[7] - 1 /* # */))
  }

  toString() {
    return this._href
  }

  toJSON() {
    return this._href
  }

  [Symbol.for('bare.inspect')]() {
    return {
      __proto__: { constructor: URL },

      href: this.href,
      protocol: this.protocol,
      username: this.username,
      password: this.password,
      host: this.host,
      hostname: this.hostname,
      port: this.port,
      pathname: this.pathname,
      search: this.search,
      searchParams: this.searchParams,
      hash: this.hash
    }
  }

  _slice(start, end = this._href.length) {
    return this._href.slice(start, end)
  }

  _replace(replacement, start, end = this._href.length) {
    return this._slice(0, start) + replacement + this._slice(end)
  }

  _parse(input, base, shouldThrow) {
    try {
      this._href = binding.parse(
        String(input),
        base ? String(base) : null,
        this._components,
        shouldThrow
      )
    } catch (err) {
      if (err instanceof TypeError) throw err

      throw errors.INVALID_URL(`Invalid URL '${input}'`, input)
    }
  }

  _update(input) {
    try {
      this._parse(input, null, true)
    } catch (err) {
      if (err instanceof TypeError) throw err
    }
  }
}

module.exports = exports = URL

// https://url.spec.whatwg.org/#url-opaque-path
function hasOpaquePath(url) {
  return url.pathname[0] !== '/'
}

// https://url.spec.whatwg.org/#cannot-have-a-username-password-port
function cannotHaveCredentialsOrPort(url) {
  return url.hostname === '' || url.protocol === 'file:'
}

exports.URL = URL
exports.URLSearchParams = URLSearchParams

exports.errors = errors

exports.isURL = function isURL(value) {
  if (value instanceof URL) return true

  return typeof value === 'object' && value !== null && value[kind] === URL[kind]
}

exports.isURLSearchParams = URLSearchParams.isURLSearchParams

// https://url.spec.whatwg.org/#dom-url-parse
exports.parse = function parse(input, base) {
  const url = new URL(input, base, { throw: false })
  return url._href ? url : null
}

// https://url.spec.whatwg.org/#dom-url-canparse
exports.canParse = function canParse(input, base) {
  return binding.canParse(String(input), base ? String(base) : null)
}

exports.fileURLToPath = function fileURLToPath(url) {
  if (typeof url === 'string') {
    url = new URL(url)
  }

  if (url.protocol !== 'file:') {
    throw errors.INVALID_URL_SCHEME('The URL must use the file: protocol')
  }

  if (isWindows) {
    if (/%2f|%5c/i.test(url.pathname)) {
      throw errors.INVALID_FILE_URL_PATH(
        'The file: URL path must not include encoded \\ or / characters'
      )
    }
  } else {
    if (url.hostname) {
      throw errors.INVALID_FILE_URL_HOST("The file: URL host must be 'localhost' or empty")
    }

    if (/%2f/i.test(url.pathname)) {
      throw errors.INVALID_FILE_URL_PATH('The file: URL path must not include encoded / characters')
    }
  }

  if (/%00/i.test(url.pathname)) {
    throw errors.INVALID_FILE_URL_PATH('The file: URL path must not include encoded NUL characters')
  }

  const pathname = path.normalize(decodeURIComponent(url.pathname))

  if (isWindows) {
    if (url.hostname) return '\\\\' + url.hostname + pathname

    const letter = pathname.charCodeAt(1) | 0x20

    if (letter < 0x61 /* a */ || letter > 0x7a /* z */ || pathname.charCodeAt(2) !== 0x3a /* : */) {
      throw errors.INVALID_FILE_URL_PATH('The file: URL path must be absolute')
    }

    return pathname.slice(1)
  }

  return pathname
}

exports.pathToFileURL = function pathToFileURL(pathname) {
  let resolved = path.resolve(pathname)

  if (pathname[pathname.length - 1] === '/') {
    resolved += '/'
  } else if (isWindows && pathname[pathname.length - 1] === '\\') {
    resolved += '\\'
  }

  resolved = resolved
    .replaceAll('%', '%25') // Must be first
    .replaceAll('#', '%23')
    .replaceAll('?', '%3f')
    .replaceAll('\n', '%0a')
    .replaceAll('\r', '%0d')
    .replaceAll('\t', '%09')

  if (!isWindows) {
    resolved = resolved.replaceAll('\\', '%5c')
  }

  return new URL('file:' + resolved)
}

exports.format = function format(parts) {
  const { protocol, auth, host, hostname, port, pathname, search, query, hash, slashes } = parts

  let result = ''

  if (typeof protocol === 'string') {
    result += protocol

    if (protocol[protocol.length - 1] !== ':') {
      result += ':'
    }

    if (slashes === true || /https?|ftp|gopher|file/.test(protocol)) {
      result += '//'
    }
  }

  if (typeof auth === 'string') {
    if (host || hostname) result += auth + '@'
  }

  if (typeof host === 'string') result += host
  else {
    result += hostname

    if (port) result += ':' + port
  }

  if (typeof pathname === 'string' && pathname !== '') {
    if (pathname[0] !== '/') result += '/'
    result += pathname
  }

  if (typeof search === 'string') {
    if (search[0] !== '?') result += '?'
    result += search
  } else if (typeof query === 'object' && query !== null) {
    result += '?' + new URLSearchParams(query)
  }

  if (typeof hash === 'string') {
    if (hash[0] !== '#') result += '#'
    result += hash
  }

  return result
}
module.exports = class URLError extends Error {
  constructor(msg, fn = URLError, code = fn.name) {
    super(`${code}: ${msg}`)

    this.code = code

    if (Error.captureStackTrace) Error.captureStackTrace(this, fn)
  }

  get name() {
    return 'URLError'
  }

  static INVALID_URL(msg, input) {
    const err = new URLError(msg, URLError.INVALID_URL)

    err.input = input

    return err
  }

  static INVALID_URL_SCHEME(msg = 'Invalid URL') {
    return new URLError(msg, URLError.INVALID_URL_SCHEME)
  }

  static INVALID_FILE_URL_HOST(msg = 'Invalid file: URL host') {
    return new URLError(msg, URLError.INVALID_FILE_URL_HOST)
  }

  static INVALID_FILE_URL_PATH(msg = 'Invalid file: URL path') {
    return new URLError(msg, URLError.INVALID_FILE_URL_PATH)
  }
}
const kind = Symbol.for('bare.url.search-params.kind')

class URLSearchParams {
  static _urls = new WeakMap()

  static get [kind]() {
    return 0 // Compatibility version
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-urlsearchparams
  constructor(init, url = null) {
    this._params = new Map()

    if (url) URLSearchParams._urls.set(this, url)

    if (typeof init === 'string') {
      this._parse(init)
    } else if (init) {
      for (const [name, value] of typeof init[Symbol.iterator] === 'function'
        ? init
        : Object.entries(init)) {
        this.append(name, value)
      }
    }
  }

  get [kind]() {
    return URLSearchParams[kind]
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-size
  get size() {
    return this._params.length
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-append
  append(name, value = null) {
    if (value === null) return

    let list = this._params.get(name)

    if (list === undefined) {
      list = []
      this._params.set(name, list)
    }

    list.push(value)

    this._update()
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-delete
  delete(name, value = null) {
    if (value === null) this._params.delete(name)
    else {
      let list = this._params.get(name)

      if (list === undefined) return

      list = list.filter((found) => found !== value)

      if (list.length === 0) this._params.delete(name)
      else this._params.set(name, list)
    }

    this._update()
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-get
  get(name) {
    const list = this._params.get(name)

    if (list === undefined) return null

    return list[0]
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-getall
  getAll(name) {
    const list = this._params.get(name)

    if (list === undefined) return []

    return Array.from(list)
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-has
  has(name, value = null) {
    const list = this._params.get(name)

    if (list === undefined) return false

    if (value === null) return true

    return list.includes(value)
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-set
  set(name, value = null) {
    if (value === null) this._params.delete(name)
    else this._params.set(name, [value])

    this._update()
  }

  toString() {
    return this._serialize()
  }

  toJSON() {
    return [...this]
  }

  *[Symbol.iterator]() {
    for (const [name, values] of this._params) {
      for (const value of values) yield [name, value]
    }
  }

  [Symbol.for('bare.inspect')]() {
    const object = {
      __proto__: { constructor: URLSearchParams }
    }

    for (const [name, values] of this._params) {
      if (values.length === 1) object[name] = values[0]
      else object[name] = values
    }

    return object
  }

  // https://url.spec.whatwg.org/#concept-urlsearchparams-update
  _update() {
    const url = URLSearchParams._urls.get(this)

    if (url === undefined) return

    url.search = this._serialize()
  }

  // https://url.spec.whatwg.org/#concept-urlencoded-parser
  _parse(input) {
    if (input[0] === '?') input = input.substring(1)

    this._params = new Map()

    for (let sequence of input.split('&')) {
      if (sequence.length === 0) continue

      sequence = sequence.replace(/\+/g, ' ')

      let i = sequence.indexOf('=')
      if (i === -1) i = sequence.length

      const name = decodeURIComponent(sequence.substring(0, i))
      const value = decodeURIComponent(sequence.substring(i + 1, sequence.length))

      let list = this._params.get(name)

      if (list === undefined) {
        list = []
        this._params.set(name, list)
      }

      list.push(value)
    }
  }

  // https://url.spec.whatwg.org/#concept-urlencoded-serializer
  _serialize() {
    let output = ''

    for (let [name, values] of this._params) {
      name = encodeURIComponent(name)

      for (const value of values) {
        if (output) output += '&'

        output += name + '=' + encodeURIComponent(value)
      }
    }

    return output
  }
}

module.exports = exports = URLSearchParams

exports.isURLSearchParams = function isURLSearchParams(value) {
  if (value instanceof URLSearchParams) return true

  return typeof value === 'object' && value !== null && value[kind] === URLSearchParams[kind]
}
{
  "name": "bare-url",
  "version": "2.4.5",
  "description": "WHATWG URL implementation for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "global.js",
    "global.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-url.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-url/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-url",
  "dependencies": {
    "bare-path": "^3.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "cmake-bare": "^1.1.6",
    "cmake-fetch": "^1.0.0",
    "lunte": "^1.6.0",
    "prettier": "^3.3.3",
    "prettier-config-holepunch": "^2.0.0"
  }
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return uint24.decode(state) + 0x1000000 * uint32.decode(state)
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return uint32.decode(state) + 0x100000000 * uint32.decode(state)
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return 0x100000000 * uint32be.decode(state) + uint32be.decode(state)
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.2.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
module.exports = require('bare-events')
{
  "name": "events-universal",
  "version": "1.0.1",
  "description": "Universal wrapper for the Node.js events module",
  "exports": {
    "./package": "./package.json",
    ".": {
      "bare": "./bare.js",
      "react-native": "./react-native.js",
      "default": "./default.js"
    }
  },
  "files": [
    "index.js",
    "default.js",
    "bare.js",
    "react-native.js"
  ],
  "scripts": {
    "test": "prettier . --check"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/events-universal.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/events-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/events-universal#readme",
  "dependencies": {
    "bare-events": "^2.7.0"
  },
  "devDependencies": {
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^1.0.0"
  }
}
module.exports = class FixedFIFO {
  constructor (hwm) {
    if (!(hwm > 0) || ((hwm - 1) & hwm) !== 0) throw new Error('Max size for a FixedFIFO should be a power of two')
    this.buffer = new Array(hwm)
    this.mask = hwm - 1
    this.top = 0
    this.btm = 0
    this.next = null
  }

  clear () {
    this.top = this.btm = 0
    this.next = null
    this.buffer.fill(undefined)
  }

  push (data) {
    if (this.buffer[this.top] !== undefined) return false
    this.buffer[this.top] = data
    this.top = (this.top + 1) & this.mask
    return true
  }

  shift () {
    const last = this.buffer[this.btm]
    if (last === undefined) return undefined
    this.buffer[this.btm] = undefined
    this.btm = (this.btm + 1) & this.mask
    return last
  }

  peek () {
    return this.buffer[this.btm]
  }

  isEmpty () {
    return this.buffer[this.btm] === undefined
  }
}
const FixedFIFO = require('./fixed-size')

module.exports = class FastFIFO {
  constructor (hwm) {
    this.hwm = hwm || 16
    this.head = new FixedFIFO(this.hwm)
    this.tail = this.head
    this.length = 0
  }

  clear () {
    this.head = this.tail
    this.head.clear()
    this.length = 0
  }

  push (val) {
    this.length++
    if (!this.head.push(val)) {
      const prev = this.head
      this.head = prev.next = new FixedFIFO(2 * this.head.buffer.length)
      this.head.push(val)
    }
  }

  shift () {
    if (this.length !== 0) this.length--
    const val = this.tail.shift()
    if (val === undefined && this.tail.next) {
      const next = this.tail.next
      this.tail.next = null
      this.tail = next
      return this.tail.shift()
    }

    return val
  }

  peek () {
    const val = this.tail.peek()
    if (val === undefined && this.tail.next) return this.tail.next.peek()
    return val
  }

  isEmpty () {
    return this.length === 0
  }
}
{
  "name": "fast-fifo",
  "version": "1.3.2",
  "description": "A fast fifo implementation similar to the one powering nextTick in Node.js core",
  "main": "index.js",
  "files": [
    "./index.js",
    "./fixed-size.js"
  ],
  "dependencies": {},
  "devDependencies": {
    "standard": "^17.1.0",
    "brittle": "^3.3.2"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/fast-fifo.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/fast-fifo/issues"
  },
  "homepage": "https://github.com/mafintosh/fast-fifo"
}
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const b4a = require('b4a')

// https://en.wikipedia.org/wiki/Merkle_tree#Second_preimage_attack
const LEAF_TYPE = b4a.from([0])
const PARENT_TYPE = b4a.from([1])
const ROOT_TYPE = b4a.from([2])

const HYPERCORE = b4a.from('hypercore')

exports.keyPair = function (seed) {
  // key pairs might stay around for a while, so better not to use a default slab to avoid retaining it completely
  const slab = b4a.allocUnsafeSlow(
    sodium.crypto_sign_PUBLICKEYBYTES + sodium.crypto_sign_SECRETKEYBYTES
  )
  const publicKey = slab.subarray(0, sodium.crypto_sign_PUBLICKEYBYTES)
  const secretKey = slab.subarray(sodium.crypto_sign_PUBLICKEYBYTES)

  if (seed) sodium.crypto_sign_seed_keypair(publicKey, secretKey, seed)
  else sodium.crypto_sign_keypair(publicKey, secretKey)

  return {
    publicKey,
    secretKey
  }
}

exports.validateKeyPair = function (keyPair) {
  const pk = b4a.allocUnsafe(sodium.crypto_sign_PUBLICKEYBYTES)
  sodium.crypto_sign_ed25519_sk_to_pk(pk, keyPair.secretKey)
  return b4a.equals(pk, keyPair.publicKey)
}

exports.sign = function (message, secretKey) {
  // Dedicated slab for the signature, to avoid retaining unneeded mem and for security
  const signature = b4a.allocUnsafeSlow(sodium.crypto_sign_BYTES)
  sodium.crypto_sign_detached(signature, message, secretKey)
  return signature
}

exports.verify = function (message, signature, publicKey) {
  if (signature.byteLength !== sodium.crypto_sign_BYTES) return false
  if (publicKey.byteLength !== sodium.crypto_sign_PUBLICKEYBYTES) return false
  return sodium.crypto_sign_verify_detached(signature, message, publicKey)
}

exports.encrypt = function (message, publicKey) {
  const ciphertext = b4a.alloc(message.byteLength + sodium.crypto_box_SEALBYTES)
  sodium.crypto_box_seal(ciphertext, message, publicKey)
  return ciphertext
}

exports.decrypt = function (ciphertext, keyPair) {
  if (ciphertext.byteLength < sodium.crypto_box_SEALBYTES) return null

  const plaintext = b4a.alloc(ciphertext.byteLength - sodium.crypto_box_SEALBYTES)

  if (!sodium.crypto_box_seal_open(plaintext, ciphertext, keyPair.publicKey, keyPair.secretKey)) {
    return null
  }

  return plaintext
}

exports.encryptionKeyPair = function (seed) {
  const publicKey = b4a.alloc(sodium.crypto_box_PUBLICKEYBYTES)
  const secretKey = b4a.alloc(sodium.crypto_box_SECRETKEYBYTES)

  if (seed) {
    sodium.crypto_box_seed_keypair(publicKey, secretKey, seed)
  } else {
    sodium.crypto_box_keypair(publicKey, secretKey)
  }

  return {
    publicKey,
    secretKey
  }
}

exports.data = function (data) {
  const out = b4a.allocUnsafe(32)

  sodium.crypto_generichash_batch(out, [LEAF_TYPE, c.encode(c.uint64, data.byteLength), data])

  return out
}

exports.parent = function (a, b) {
  if (a.index > b.index) {
    const tmp = a
    a = b
    b = tmp
  }

  const out = b4a.allocUnsafe(32)

  sodium.crypto_generichash_batch(out, [
    PARENT_TYPE,
    c.encode(c.uint64, a.size + b.size),
    a.hash,
    b.hash
  ])

  return out
}

exports.tree = function (roots, out) {
  const buffers = new Array(3 * roots.length + 1)
  let j = 0

  buffers[j++] = ROOT_TYPE

  for (let i = 0; i < roots.length; i++) {
    const r = roots[i]
    buffers[j++] = r.hash
    buffers[j++] = c.encode(c.uint64, r.index)
    buffers[j++] = c.encode(c.uint64, r.size)
  }

  if (!out) out = b4a.allocUnsafe(32)
  sodium.crypto_generichash_batch(out, buffers)
  return out
}

exports.hash = function (data, out) {
  if (!out) out = b4a.allocUnsafe(32)
  if (!Array.isArray(data)) data = [data]

  sodium.crypto_generichash_batch(out, data)

  return out
}

exports.randomBytes = function (n) {
  const buf = b4a.allocUnsafe(n)
  sodium.randombytes_buf(buf)
  return buf
}

exports.discoveryKey = function (key) {
  if (!key || key.byteLength !== 32) throw new Error('Must pass a 32 byte buffer')
  // Discovery keys might stay around for a while, so better not to use slab memory (for better gc)
  const digest = b4a.allocUnsafeSlow(32)
  sodium.crypto_generichash(digest, HYPERCORE, key)
  return digest
}

if (sodium.sodium_free) {
  exports.free = function (secureBuf) {
    if (secureBuf.secure) sodium.sodium_free(secureBuf)
  }
} else {
  exports.free = function () {}
}

exports.namespace = function (name, count) {
  const ids = typeof count === 'number' ? range(count) : count

  // Namespaces are long-lived, so better to use a dedicated slab
  const buf = b4a.allocUnsafeSlow(32 * ids.length)

  const list = new Array(ids.length)

  // ns is ephemeral, so default slab
  const ns = b4a.allocUnsafe(33)
  sodium.crypto_generichash(ns.subarray(0, 32), typeof name === 'string' ? b4a.from(name) : name)

  for (let i = 0; i < list.length; i++) {
    list[i] = buf.subarray(32 * i, 32 * i + 32)
    ns[32] = ids[i]
    sodium.crypto_generichash(list[i], ns)
  }

  return list
}

function range(count) {
  const arr = new Array(count)
  for (let i = 0; i < count; i++) arr[i] = i
  return arr
}
{
  "name": "hypercore-crypto",
  "version": "3.7.0",
  "description": "The crypto primitives used in hypercore, extracted into a separate module",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.6.6",
    "compact-encoding": "^3.0.0",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "brittle": "^3.5.0",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/hypercore-crypto.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/hypercore-crypto/issues"
  },
  "homepage": "https://github.com/mafintosh/hypercore-crypto"
}
module.exports = require.addon.bind(require)
{
  "name": "require-addon",
  "version": "1.2.0",
  "description": "Import native addons across JavaScript runtimes",
  "exports": {
    "./package": "./package.json",
    ".": {
      "bare": "./lib/bare.js",
      "node": "./lib/node.js",
      "default": "./lib/default.js"
    }
  },
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    },
    "url": {
      "bare": "bare-url",
      "default": "url"
    }
  },
  "files": [
    "lib"
  ],
  "scripts": {
    "test": "npm run lint && npm run test:bare && npm run test:node",
    "test:bare": "bare test.js",
    "test:node": "node test.js",
    "lint": "prettier --check .",
    "format": "prettier --write ."
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/require-addon.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/require-addon/issues"
  },
  "homepage": "https://github.com/holepunchto/require-addon#readme",
  "engines": {
    "bare": ">=1.10.0"
  },
  "dependencies": {
    "bare-addon-resolve": "^1.3.0"
  },
  "devDependencies": {
    "bare-bundle": "^1.8.1",
    "bare-bundle-evaluate": "^1.1.0",
    "bare-fs": "^4.0.0",
    "bare-path": "^3.0.0",
    "bare-url": "^2.1.0",
    "brittle": "^3.7.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
require.addon = require('require-addon')
module.exports = require.addon('.', __filename)
const assert = require('assert')
const binding = require('./binding')
const { isNode } = require('which-runtime')

const OPTIONAL = Buffer.from(new ArrayBuffer(0))

module.exports = exports = { ...binding }

// memory

exports.sodium_memzero = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  binding.sodium_memzero(buf)
}

exports.sodium_mlock = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  const res = binding.sodium_mlock(buf)

  if (res !== 0) throw new Error('memory lock failed')
}

exports.sodium_munlock = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  const res = binding.sodium_munlock(buf)

  if (res !== 0) throw new Error('memory unlock failed')
}

exports.sodium_malloc = function (size) {
  assert(size >= 0, 'invalid size')

  const buf = Buffer.from(binding.sodium_malloc(size))
  buf.secure = true
  return buf
}

exports.sodium_free = function (buf) {
  if (!buf || !buf.secure) return

  binding.sodium_free(buf.buffer)
}

exports.sodium_mprotect_noaccess = function (buf) {
  const res = binding.sodium_mprotect_noaccess(buf.buffer)

  if (res !== 0) throw new Error('failed to lock buffer')
}

exports.sodium_mprotect_readonly = function (buf) {
  const res = binding.sodium_mprotect_readonly(buf.buffer)

  if (res !== 0) throw new Error('failed to unlock buffer')
}

exports.sodium_mprotect_readwrite = function (buf) {
  const res = binding.sodium_mprotect_readwrite(buf.buffer)

  if (res !== 0) throw new Error('failed to unlock buffer')
}

// crypto_randombytes

exports.randombytes_buf = function (buffer) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')

  binding.randombytes_buf(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

exports.randombytes_buf_deterministic = function (buffer, seed) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    seed.byteLength === binding.randombytes_SEEDBYTES,
    "seed must be 'randombytes_SEEDBYTES' bytes"
  )

  binding.randombytes_buf_deterministic(
    buffer.buffer,
    buffer.byteOffset,
    buffer.byteLength,

    seed.buffer,
    seed.byteOffset,
    seed.byteLength
  )
}

// sodium_helpers

exports.sodium_memcmp = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  return binding.sodium_memcmp(a, b)
}

exports.sodium_add = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  binding.sodium_add(a, b)
}

exports.sodium_sub = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  binding.sodium_sub(a, b)
}

exports.sodium_compare = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  return binding.sodium_compare(a, b)
}

exports.sodium_is_zero = function (buffer, length) {
  if (length === undefined) length = buffer.byteLength

  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(length >= 0 && length <= buffer.byteLength, 'invalid length')

  return binding.sodium_is_zero(buffer, length)
}

exports.sodium_pad = function (buffer, unpaddedBuflen, blockSize) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(unpaddedBuflen <= buffer.byteLength, 'unpadded length cannot exceed buffer length')
  assert(blockSize <= buffer.byteLength, 'block size cannot exceed buffer length')
  assert(blockSize >= 1, 'block size must be at least 1 byte')
  assert(
    buffer.byteLength >= unpaddedBuflen + (blockSize - (unpaddedBuflen % blockSize)),
    'buf not long enough'
  )

  return binding.sodium_pad(buffer, unpaddedBuflen, blockSize)
}

exports.sodium_unpad = function (buffer, paddedBuflen, blockSize) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(paddedBuflen <= buffer.byteLength, 'unpadded length cannot exceed buffer length')
  assert(blockSize <= buffer.byteLength, 'block size cannot exceed buffer length')
  assert(blockSize >= 1, 'block size must be at least 1 byte')

  return binding.sodium_unpad(buffer, paddedBuflen, blockSize)
}

// crypto_sign

exports.crypto_sign_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )
  assert(
    seed.byteLength === binding.crypto_sign_SEEDBYTES,
    "seed must be 'crypto_sign_SEEDBYTES' bytes"
  )

  const res = binding.crypto_sign_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign = function (sm, m, sk) {
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sm.byteLength === binding.crypto_sign_BYTES + m.byteLength,
    "sm must be 'm.byteLength + crypto_sign_BYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign(sm, m, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_open = function (m, sm, pk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sm.byteLength >= binding.crypto_sign_BYTES,
    "sm must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    m.byteLength === sm.byteLength - binding.crypto_sign_BYTES,
    "m must be 'sm.byteLength - crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_open(m, sm, pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_open = function (m, sm, pk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sm.byteLength >= binding.crypto_sign_BYTES,
    "sm must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    m.byteLength === sm.byteLength - binding.crypto_sign_BYTES,
    "m must be 'sm.byteLength - crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  return binding.crypto_sign_open(m, sm, pk)
}

exports.crypto_sign_detached = function (sig, m, sk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(sig.byteLength === binding.crypto_sign_BYTES, "sig must be 'crypto_sign_BYTES' bytes")
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_detached(sig, m, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_verify_detached = function (sig, m, pk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sig.byteLength >= binding.crypto_sign_BYTES,
    "sig must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  return binding.crypto_sign_verify_detached(
    sig.buffer,
    sig.byteOffset,
    sig.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    pk.buffer,
    pk.byteOffset,
    pk.byteLength
  )
}

exports.crypto_sign_ed25519_sk_to_pk = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_sk_to_pk(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_ed25519_pk_to_curve25519 = function (x25519pk, ed25519pk) {
  assert(ArrayBuffer.isView(x25519pk), 'x25519pk must be a typed array')
  assert(ArrayBuffer.isView(ed25519pk), 'ed25519pk must be a typed array')
  assert(
    x25519pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "x25519pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    ed25519pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "ed25519pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_pk_to_curve25519(x25519pk, ed25519pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_ed25519_sk_to_curve25519 = function (x25519sk, ed25519sk) {
  assert(ArrayBuffer.isView(x25519sk), 'x25519sk must be a typed array')
  assert(ArrayBuffer.isView(ed25519sk), 'ed25519sk must be a typed array')
  assert(
    x25519sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "x25519sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const edLen = ed25519sk.byteLength

  assert(
    edLen === binding.crypto_sign_SECRETKEYBYTES || edLen === binding.crypto_box_SECRETKEYBYTES,
    "ed25519sk must be 'crypto_sign_SECRETKEYBYTES' or 'crypto_sign_SECRETKEYBYTES - crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_sk_to_curve25519(x25519sk, ed25519sk)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_box

exports.crypto_box_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    seed.byteLength === binding.crypto_box_SEEDBYTES,
    "seed must be 'crypto_box_SEEDBYTES' bytes"
  )

  const res = binding.crypto_box_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_easy = function (c, m, n, pk, sk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength === m.byteLength + exports.crypto_box_MACBYTES,
    "c must be 'm.byteLength + crypto_box_MACBYTES' bytes"
  )
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_easy(c, m, n, pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_detached = function (c, mac, m, n, pk, sk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(mac.byteLength === exports.crypto_box_MACBYTES, "mac must be 'crypto_box_MACBYTES' bytes")
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_detached(c, mac, m, n, pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_open_easy = function (m, c, n, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength >= exports.crypto_box_MACBYTES,
    "c must be at least 'crypto_box_MACBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - exports.crypto_box_MACBYTES,
    "m must be 'c.byteLength - crypto_box_MACBYTES' bytes"
  )
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_open_easy(m, c, n, pk, sk)
}

exports.crypto_box_open_detached = function (m, c, mac, n, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(mac.byteLength === exports.crypto_box_MACBYTES, "mac must be 'crypto_box_MACBYTES' bytes")
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_open_detached(m, c, mac, n, pk, sk)
}

exports.crypto_box_seal = function (c, m, pk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    c.byteLength === m.byteLength + exports.crypto_box_SEALBYTES,
    "c must be 'm.byteLength + crypto_box_SEALBYTES' bytes"
  )
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_box_seal(c, m, pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_seal_open = function (m, c, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength >= exports.crypto_box_SEALBYTES,
    "c must be at least 'crypto_box_SEALBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - exports.crypto_box_SEALBYTES,
    "m must be 'c.byteLength - crypto_box_SEALBYTES' bytes"
  )
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_seal_open(
    m.buffer,
    m.byteOffset,
    m.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    pk.buffer,
    pk.byteOffset,
    pk.byteLength,

    sk.buffer,
    sk.byteOffset,
    sk.byteLength
  )
}

// crypto_secretbox

exports.crypto_secretbox_easy = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_secretbox_MACBYTES,
    "c must be 'm.byteLength + crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretbox_easy(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretbox_open_easy = function (m, c, n, k) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    c.byteLength >= binding.crypto_secretbox_MACBYTES,
    "c must be at least 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - binding.crypto_secretbox_MACBYTES,
    "m must be 'c.byteLength - crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  return binding.crypto_secretbox_open_easy(m, c, n, k)
}

exports.crypto_secretbox_detached = function (c, mac, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    mac.byteLength === binding.crypto_secretbox_MACBYTES,
    "mac must be 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretbox_detached(c, mac, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretbox_open_detached = function (m, c, mac, n, k) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(
    mac.byteLength === binding.crypto_secretbox_MACBYTES,
    "mac must be 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  return binding.crypto_secretbox_open_detached(m, c, mac, n, k)
}

// crypto_generichash

exports.crypto_generichash = function (output, input, key) {
  if (!key) key = OPTIONAL

  assert(ArrayBuffer.isView(output), 'output must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    output.byteLength >= binding.crypto_generichash_BYTES_MIN &&
      output.byteLength <= binding.crypto_generichash_BYTES_MAX,
    'output must be between crypto_generichash_BYTES_MIN and crypto_generichash_BYTES_MAX bytes'
  )

  if (key !== OPTIONAL) {
    assert(ArrayBuffer.isView(key), 'key must be a typed array')
    assert(
      key.byteLength >= binding.crypto_generichash_KEYBYTES_MIN &&
        key.byteLength <= binding.crypto_generichash_KEYBYTES_MAX,
      'key must be between crypto_generichash_KEYBYTES_MIN and crypto_generichash_KEYBYTES_MAX bytes'
    )
  }

  const res = binding.crypto_generichash(
    output.buffer,
    output.byteOffset,
    output.byteLength,

    input.buffer,
    input.byteOffset,
    input.byteLength,

    key.buffer,
    key.byteOffset,
    key.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_batch = function (output, batch, key) {
  assert(ArrayBuffer.isView(output), 'output must be a typed array')

  if (isNode || batch.length < 4) {
    const res = binding.crypto_generichash_batch(output, batch, !!key, key || OPTIONAL)
    if (res !== 0) throw new Error('status: ' + res)
  } else {
    const state = Buffer.alloc(binding.crypto_generichash_STATEBYTES)

    exports.crypto_generichash_init(state, key, output.byteLength)

    for (const buf of batch) {
      exports.crypto_generichash_update(state, buf)
    }

    exports.crypto_generichash_final(state, output)
  }
}

exports.crypto_generichash_keygen = function (key) {
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(
    key.byteLength === binding.crypto_generichash_KEYBYTES,
    "key must be 'crypto_generichash_KEYBYTES' bytes"
  )

  const res = binding.crypto_generichash_keygen(key.buffer, key.byteOffset, key.byteLength)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_init = function (state, key, outputLength) {
  if (!key) key = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_init(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    key.buffer,
    key.byteOffset,
    key.byteLength,

    outputLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_update(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    input.buffer,
    input.byteOffset,
    input.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_final = function (state, output) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(output), 'output must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_final(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    output.buffer,
    output.byteOffset,
    output.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

// secretstream

exports.crypto_secretstream_xchacha20poly1305_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  binding.crypto_secretstream_xchacha20poly1305_keygen(k.buffer, k.byteOffset, k.byteLength)
}

exports.crypto_secretstream_xchacha20poly1305_init_push = function (state, header, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(header), 'header must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    header.byteLength === binding.crypto_secretstream_xchacha20poly1305_HEADERBYTES,
    "header must be 'crypto_secretstream_xchacha20poly1305_HEADERBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_init_push(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    header.buffer,
    header.byteOffset,
    header.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretstream_xchacha20poly1305_init_pull = function (state, header, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(header), 'header must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    header.byteLength === binding.crypto_secretstream_xchacha20poly1305_HEADERBYTES,
    "header must be 'crypto_secretstream_xchacha20poly1305_HEADERBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_init_pull(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    header.buffer,
    header.byteOffset,
    header.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretstream_xchacha20poly1305_push = function (state, c, m, ad, tag) {
  if (!ad) ad = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    c.byteLength === m.byteLength + binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "c must be 'm.byteLength + crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_push(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    ad.buffer,
    ad.byteOffset,
    ad.byteLength,

    tag
  )

  if (res < 0) throw new Error('push failed')

  return res
}

exports.crypto_secretstream_xchacha20poly1305_pull = function (state, m, tag, c, ad) {
  if (!ad) ad = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(tag), 'tag must be a typed array')
  assert(tag.byteLength === 1, 'tag must be 1 byte')

  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    c.byteLength >= binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "c must be at least 'crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "m must be 'c.byteLength - crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_pull(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    tag.buffer,
    tag.byteOffset,
    tag.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    ad.buffer,
    ad.byteOffset,
    ad.byteLength
  )

  if (res < 0) throw new Error('pull failed')

  return res
}

exports.crypto_secretstream_xchacha20poly1305_rekey = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )

  binding.crypto_secretstream_xchacha20poly1305_rekey(
    state.buffer,
    state.byteOffset,
    state.byteLength
  )
}

// crypto_stream

exports.crypto_stream = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xor(
    c.buffer,
    c.byteOffset,
    c.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    n.buffer,
    n.byteOffset,
    n.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_auth

exports.crypto_auth = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(out.byteLength === binding.crypto_auth_BYTES, "out must be 'crypto_auth_BYTES' bytes")
  assert(k.byteLength === binding.crypto_auth_KEYBYTES, "k must be 'crypto_auth_KEYBYTES' bytes")

  const res = binding.crypto_auth(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_auth_verify = function (h, input, k) {
  assert(ArrayBuffer.isView(h), 'h must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(h.byteLength === binding.crypto_auth_BYTES, "h must be 'crypto_auth_BYTES' bytes")
  assert(k.byteLength === binding.crypto_auth_KEYBYTES, "k must be 'crypto_auth_KEYBYTES' bytes")

  return binding.crypto_auth_verify(h, input, k)
}

// crypto_onetimeauth

exports.crypto_onetimeauth = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    out.byteLength === binding.crypto_onetimeauth_BYTES,
    "out must be 'crypto_onetimeauth_BYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_init = function (state, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_init(state, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )
  assert(
    out.byteLength === binding.crypto_onetimeauth_BYTES,
    "out must be 'crypto_onetimeauth_BYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_verify = function (h, input, k) {
  assert(ArrayBuffer.isView(h), 'h must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    h.byteLength === binding.crypto_onetimeauth_BYTES,
    "h must be 'crypto_onetimeauth_BYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  return binding.crypto_onetimeauth_verify(h, input, k)
}

// crypto_pwhash

exports.crypto_pwhash = function (out, passwd, salt, opslimit, memlimit, alg) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_BYTES_MIN,
    "out must be at least 'crypto_pwhash_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_BYTES_MAX,
    "out must be at most 'crypto_pwhash_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_SALTBYTES,
    "salt must be 'crypto_pwhash_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )
  assert(alg >= 1 && alg <= 2, 'alg must be either Argon2i 1.3 or Argon2id 1.3')

  const res = binding.crypto_pwhash(out, passwd, salt, opslimit, memlimit, alg)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_async = function (
  out,
  passwd,
  salt,
  opslimit,
  memlimit,
  alg,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_BYTES_MIN,
    "out must be at least 'crypto_pwhash_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_BYTES_MAX,
    "out must be at most 'crypto_pwhash_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_SALTBYTES,
    "salt must be 'crypto_pwhash_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )
  assert(alg >= 1 && alg <= 2, 'alg must be either Argon2i 1.3 or Argon2id 1.3')

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    opslimit,
    memlimit,
    alg,

    done
  )

  return promise
}

exports.crypto_pwhash_str = function (out, passwd, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_STRBYTES,
    "out must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(typeof opslimit === 'number', 'opslimit must be a number')
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(typeof memlimit === 'number', 'memlimit must be a number')
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_str(out, passwd, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_str_async = function (out, passwd, opslimit, memlimit, callback = undefined) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_STRBYTES,
    "out must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(typeof opslimit === 'number', 'opslimit must be a number')
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(typeof memlimit === 'number', 'memlimit must be a number')
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_str_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_str_verify = function (str, passwd) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )

  return binding.crypto_pwhash_str_verify(str, passwd)
}

exports.crypto_pwhash_str_verify_async = function (str, passwd, callback = undefined) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  const [done, promise] = checkStatus(callback, true)

  binding.crypto_pwhash_str_verify_async(
    str.buffer,
    str.byteOffset,
    str.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    done
  )

  return promise
}

exports.crypto_pwhash_str_needs_rehash = function (str, opslimit, memlimit) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  return binding.crypto_pwhash_str_needs_rehash(str, opslimit, memlimit)
}

exports.crypto_pwhash_scryptsalsa208sha256 = function (out, passwd, salt, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MIN,
    "out must be at least 'crypto_pwhash_scryptsalsa208sha256_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MAX,
    "out must be at most 'crypto_pwhash_scryptsalsa208sha256_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_SALTBYTES,
    "salt must be 'crypto_pwhash_scryptsalsa208sha256_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_scryptsalsa208sha256(out, passwd, salt, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_scryptsalsa208sha256_async = function (
  out,
  passwd,
  salt,
  opslimit,
  memlimit,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MIN,
    "out must be at least 'crypto_pwhash_scryptsalsa208sha256_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MAX,
    "out must be at most 'crypto_pwhash_scryptsalsa208sha256_BYTES_MAX' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    salt.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_SALTBYTES,
    "salt must be 'crypto_pwhash_scryptsalsa208sha256_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_scryptsalsa208sha256_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str_async = function (
  out,
  passwd,
  opslimit,
  memlimit,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "out must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_scryptsalsa208sha256_str_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str = function (out, passwd, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "out must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_scryptsalsa208sha256_str(out, passwd, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_scryptsalsa208sha256_str_verify_async = function (
  str,
  passwd,
  callback = undefined
) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  const [done, promise] = checkStatus(callback, true)

  binding.crypto_pwhash_scryptsalsa208sha256_str_verify_async(
    str.buffer,
    str.byteOffset,
    str.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str_verify = function (str, passwd) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  return binding.crypto_pwhash_scryptsalsa208sha256_str_verify(str, passwd)
}

exports.crypto_pwhash_scryptsalsa208sha256_str_needs_rehash = function (str, opslimit, memlimit) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  return binding.crypto_pwhash_scryptsalsa208sha256_str_needs_rehash(str, opslimit, memlimit)
}

// crypto_kx

exports.crypto_kx_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "pk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "sk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    pk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "pk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "sk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    seed.byteLength === binding.crypto_kx_SEEDBYTES,
    "seed must be 'crypto_kx_SEEDBYTES' bytes"
  )

  const res = binding.crypto_kx_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_client_session_keys = function (rx, tx, clientPk, clientSk, serverPk) {
  if (!rx) rx = undefined
  if (!tx) tx = undefined

  assert(rx || tx, 'at least one session key must be specified')

  if (rx) {
    assert(ArrayBuffer.isView(rx), 'rx must be a typed array')
    assert(
      rx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "rx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  if (tx) {
    assert(ArrayBuffer.isView(tx), 'tx must be a typed array')
    assert(
      tx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "tx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  assert(ArrayBuffer.isView(clientPk), 'clientPk must be a typed array')
  assert(ArrayBuffer.isView(clientSk), 'clientSk must be a typed array')
  assert(ArrayBuffer.isView(serverPk), 'serverPk must be a typed array')
  assert(
    clientPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "clientPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    clientSk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "clientSk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    serverPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "serverPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_client_session_keys(rx, tx, clientPk, clientSk, serverPk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_server_session_keys = function (rx, tx, serverPk, serverSk, clientPk) {
  if (!rx) rx = undefined
  if (!tx) tx = undefined

  assert(rx || tx, 'at least one session key must be specified')

  if (rx) {
    assert(ArrayBuffer.isView(rx), 'rx must be a typed array')
    assert(
      rx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "rx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  if (tx) {
    assert(ArrayBuffer.isView(tx), 'tx must be a typed array')
    assert(
      tx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "tx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  assert(ArrayBuffer.isView(serverPk), 'serverPk must be a typed array')
  assert(ArrayBuffer.isView(serverSk), 'serverSk must be a typed array')
  assert(ArrayBuffer.isView(clientPk), 'clientPk must be a typed array')
  assert(
    serverPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "serverPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    serverSk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "serverSk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    clientPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "clientPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_server_session_keys(rx, tx, serverPk, serverSk, clientPk)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_scalarmult

exports.crypto_scalarmult_base = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_BYTES,
    "q must be 'crypto_scalarmult_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_SCALARBYTES,
    "n must be 'crypto_scalarmult_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_base(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_BYTES,
    "q must be 'crypto_scalarmult_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_SCALARBYTES,
    "n must be 'crypto_scalarmult_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_BYTES,
    "p must be 'crypto_scalarmult_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_base = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_base(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519 = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "p must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_is_valid_point = function (p) {
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )

  return binding.crypto_core_ed25519_is_valid_point(p)
}

exports.crypto_core_ed25519_from_uniform = function (p, r) {
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_UNIFORMBYTES,
    "r must be 'crypto_core_ed25519_UNIFORMBYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_from_uniform(p, r)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_base_noclamp = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_base_noclamp(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_noclamp = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "p must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_noclamp(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_core

exports.crypto_core_ed25519_add = function (r, p, q) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_BYTES,
    "r must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_core_ed25519_BYTES,
    "q must be 'crypto_core_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_add(r, p, q)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_sub = function (r, p, q) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_BYTES,
    "r must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_core_ed25519_BYTES,
    "q must be 'crypto_core_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_sub(r, p, q)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_scalar_random = function (r) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "r must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_random(r)
}

exports.crypto_core_ed25519_scalar_reduce = function (r, s) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "r must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_NONREDUCEDSCALARBYTES,
    "s must be 'crypto_core_ed25519_NONREDUCEDSCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_reduce(r, s)
}

exports.crypto_core_ed25519_scalar_invert = function (recip, s) {
  assert(ArrayBuffer.isView(recip), 'recip must be a typed array')
  assert(
    recip.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "recip must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_invert(recip, s)
}

exports.crypto_core_ed25519_scalar_negate = function (neg, s) {
  assert(ArrayBuffer.isView(neg), 'neg must be a typed array')
  assert(
    neg.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "neg must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_negate(neg, s)
}

exports.crypto_core_ed25519_scalar_complement = function (comp, s) {
  assert(ArrayBuffer.isView(comp), 'comp must be a typed array')
  assert(
    comp.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "comp must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_complement(comp, s)
}

exports.crypto_core_ed25519_scalar_add = function (z, x, y) {
  assert(ArrayBuffer.isView(z), 'z must be a typed array')
  assert(
    z.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "z must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(x), 'x must be a typed array')
  assert(
    x.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "x must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(y), 'y must be a typed array')
  assert(
    y.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "y must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_add(z, x, y)
}

exports.crypto_core_ed25519_scalar_sub = function (z, x, y) {
  assert(ArrayBuffer.isView(z), 'z must be a typed array')
  assert(
    z.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "z must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(x), 'x must be a typed array')
  assert(
    x.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "x must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(y), 'y must be a typed array')
  assert(
    y.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "y must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_sub(z, x, y)
}

// crypto_shorthash

exports.crypto_shorthash = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_shorthash_BYTES,
    "out must be 'crypto_shorthash_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_shorthash_KEYBYTES,
    "k must be 'crypto_shorthash_KEYBYTES' bytes"
  )

  const res = binding.crypto_shorthash(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_kdf

exports.crypto_kdf_keygen = function (key) {
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(key.byteLength === binding.crypto_kdf_KEYBYTES, "key must be 'crypto_kdf_KEYBYTES' bytes")

  binding.crypto_kdf_keygen(key)
}

exports.crypto_kdf_derive_from_key = function (subkey, subkeyId, ctx, key) {
  assert(ArrayBuffer.isView(subkey), 'subkey must be a typed array')
  assert(
    subkey.byteLength >= binding.crypto_kdf_BYTES_MIN,
    "subkey must be at least 'crypto_kdf_BYTES_MIN' bytes"
  )
  assert(
    subkey.byteLength <= binding.crypto_kdf_BYTES_MAX,
    "subkey must be at most 'crypto_kdf_BYTES_MAX' bytes"
  )
  assert(ArrayBuffer.isView(ctx), 'ctx must be a typed array')
  assert(
    ctx.byteLength === binding.crypto_kdf_CONTEXTBYTES,
    "ctx must be 'crypto_kdf_CONTEXTBYTES' bytes"
  )
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(key.byteLength === binding.crypto_kdf_KEYBYTES, "key must be 'crypto_kdf_KEYBYTES' bytes")

  const res = binding.crypto_kdf_derive_from_key(subkey, subkeyId, ctx, key)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_hash

exports.crypto_hash = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(out.byteLength === binding.crypto_hash_BYTES, "out must be 'crypto_hash_BYTES' bytes")

  const res = binding.crypto_hash(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256 = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha256_BYTES,
    "out must be 'crypto_hash_sha256_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha256(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_init = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_init(state)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha256_BYTES,
    "out must be 'crypto_hash_sha256_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512 = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha512_BYTES,
    "out must be 'crypto_hash_sha512_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha512(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_init = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_init(state)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha512_BYTES,
    "out must be 'crypto_hash_sha512_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_aead

exports.crypto_aead_xchacha20poly1305_ietf_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  binding.crypto_aead_xchacha20poly1305_ietf_keygen(k)
}

exports.crypto_aead_xchacha20poly1305_ietf_encrypt = function (c, m, ad, nsec, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "c must be 'm.byteLength + crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(c.byteLength <= 0xffffffff, 'c.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_encrypt(c, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_decrypt = function (m, nsec, c, ad, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "m must be 'c.byteLength - crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(m.byteLength <= 0xffffffff, 'm.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_decrypt(m, c, ad, npub, k)

  if (res < 0) throw new Error('could not verify data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_encrypt_detached = function (
  c,
  mac,
  m,
  ad,
  nsec,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_encrypt_detached(c, mac, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_decrypt_detached = function (
  m,
  nsec,
  c,
  mac,
  ad,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_decrypt_detached(m, c, mac, ad, npub, k)

  if (res !== 0) throw new Error('could not verify data')
}

exports.crypto_aead_chacha20poly1305_ietf_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  binding.crypto_aead_chacha20poly1305_ietf_keygen(k)
}

exports.crypto_aead_chacha20poly1305_ietf_encrypt = function (c, m, ad, nsec, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "c must be 'm.byteLength + crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(c.byteLength <= 0xffffffff, 'c.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_encrypt(c, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_decrypt = function (m, nsec, c, ad, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "m must be 'c.byteLength - crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(m.byteLength <= 0xffffffff, 'm.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_decrypt(m, c, ad, npub, k)

  if (res < 0) throw new Error('could not verify data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_encrypt_detached = function (
  c,
  mac,
  m,
  ad,
  nsec,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_encrypt_detached(c, mac, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_decrypt_detached = function (
  m,
  nsec,
  c,
  mac,
  ad,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_decrypt_detached(m, c, mac, ad, npub, k)

  if (res !== 0) throw new Error('could not verify data')
}

// crypto_stream

exports.crypto_stream_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  binding.crypto_stream_xor_wrap_init(state, n, k)
}

exports.crypto_stream_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_xor_wrap_update(state, c, m)
}

exports.crypto_stream_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_xor_wrap_final(state)
}

exports.crypto_stream_chacha20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  binding.crypto_stream_chacha20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_chacha20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_chacha20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_chacha20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_chacha20_xor_wrap_final(state)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  binding.crypto_stream_chacha20_ietf_xor_wrap_init(state, n, k)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_chacha20_ietf_xor_wrap_update(state, c, m)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_chacha20_ietf_xor_wrap_final(state)
}

exports.crypto_stream_xchacha20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  binding.crypto_stream_xchacha20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_xchacha20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_xchacha20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_xchacha20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_xchacha20_xor_wrap_final(state)
}

exports.crypto_stream_salsa20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  binding.crypto_stream_salsa20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_salsa20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_salsa20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_salsa20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_salsa20_xor_wrap_final(state)
}

// experimental

exports.extension_tweak_ed25519_base = function (n, p, ns) {
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.extension_tweak_ed25519_BYTES,
    "p must be 'extension_tweak_ed25519_BYTES' bytes"
  )

  binding.extension_tweak_ed25519_base(n, p, ns)
}

exports.extension_tweak_ed25519_sign_detached = function (sig, m, scalar, pk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(sig.byteLength === binding.crypto_sign_BYTES, "sig must be 'crypto_sign_BYTES' bytes")
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  if (pk) {
    assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
    assert(
      pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
      "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
    )
  }

  const res = binding.extension_tweak_ed25519_sign_detached(sig, m, scalar, pk)

  if (res !== 0) throw new Error('failed to compute signature')
}

exports.extension_tweak_ed25519_sk_to_scalar = function (n, sk) {
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  binding.extension_tweak_ed25519_sk_to_scalar(n, sk)
}

exports.extension_tweak_ed25519_scalar = function (scalarOut, scalar, ns) {
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_scalar(scalarOut, scalar, ns)
}

exports.extension_tweak_ed25519_pk = function (tpk, pk, ns) {
  assert(ArrayBuffer.isView(tpk), 'tpk must be a typed array')
  assert(
    tpk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "tpk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_pk(tpk, pk, ns)

  if (res !== 0) throw new Error('failed to tweak public key')
}

exports.extension_tweak_ed25519_keypair = function (pk, scalarOut, scalarIn, ns) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.extension_tweak_ed25519_BYTES,
    "pk must be 'extension_tweak_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarIn), 'scalarIn must be a typed array')
  assert(
    scalarIn.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarIn must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_keypair(pk, scalarOut, scalarIn, ns)
}

exports.extension_tweak_ed25519_scalar_add = function (scalarOut, scalar, n) {
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_scalar_add(scalarOut, scalar, n)
}

exports.extension_tweak_ed25519_pk_add = function (tpk, pk, p) {
  assert(ArrayBuffer.isView(tpk), 'tpk must be a typed array')
  assert(
    tpk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "tpk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "p must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_pk_add(tpk, pk, p)

  if (res !== 0) throw new Error('failed to add tweak to public key')
}

exports.extension_tweak_ed25519_keypair_add = function (pk, scalarOut, scalarIn, tweak) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.extension_tweak_ed25519_BYTES,
    "pk must be 'extension_tweak_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarIn), 'scalarIn must be a typed array')
  assert(
    scalarIn.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarIn must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(tweak), 'tweak must be a typed array')
  assert(
    tweak.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "tweak must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_keypair_add(pk, scalarOut, scalarIn, tweak)

  if (res !== 0) throw new Error('failed to add tweak to keypair')
}

exports.extension_pbkdf2_sha512_async = function (out, passwd, salt, iter, outlen, callback) {
  assert(
    iter >= binding.extension_pbkdf2_sha512_ITERATIONS_MIN,
    "iter must be at least 'extension_pbkdf2_sha512_ITERATIONS_MIN'"
  )
  assert(
    outlen <= binding.extension_pbkdf2_sha512_BYTES_MAX,
    "outlen must be at most 'extension_pbkdf2_sha512_BYTES_MAX'"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(out.byteLength >= outlen, "out must be at least 'outlen' bytes")
  assert(out.byteLength > 0, 'out must not be empty')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(salt.byteLength > 0, 'salt must not be empty')

  const [done, promise] = checkStatus(callback)

  binding.extension_pbkdf2_sha512_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    iter,
    outlen,

    done
  )

  return promise
}

exports.extension_pbkdf2_sha512 = function (out, passwd, salt, iter, outlen) {
  assert(
    iter >= binding.extension_pbkdf2_sha512_ITERATIONS_MIN,
    "iter must be at least 'extension_pbkdf2_sha512_ITERATIONS_MIN'"
  )
  assert(
    outlen <= binding.extension_pbkdf2_sha512_BYTES_MAX,
    "outlen must be at most 'extension_pbkdf2_sha512_BYTES_MAX'"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(out.byteLength >= outlen, "out must be at least 'outlen' bytes")
  assert(out.byteLength > 0, 'out must not be empty')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(salt.byteLength > 0, 'salt must not be empty')

  const res = binding.extension_pbkdf2_sha512(out, passwd, salt, iter, outlen)

  if (res !== 0) throw new Error('failed to add tweak to public key')
}

function checkStatus(callback, booleanResult = false) {
  let done, promise

  if (typeof callback === 'function') {
    done = function (status) {
      if (booleanResult) callback(null, status === 0)
      else if (status === 0) callback(null)
      else callback(new Error('status: ' + status))
    }
  } else {
    promise = new Promise(function (resolve, reject) {
      done = function (status) {
        if (booleanResult) resolve(status === 0)
        else if (status === 0) resolve()
        else reject(new Error('status: ' + status))
      }
    })
  }

  return [done, promise]
}
{
  "name": "sodium-native",
  "version": "5.1.0",
  "description": "Low level bindings for libsodium",
  "main": "index.js",
  "files": [
    "index.js",
    "binding.cc",
    "binding.js",
    "extensions",
    "prebuilds",
    "CMakeLists.txt"
  ],
  "imports": {
    "assert": {
      "bare": "bare-assert",
      "node": "assert"
    }
  },
  "addon": true,
  "dependencies": {
    "bare-assert": "^1.2.0",
    "require-addon": "^1.1.0",
    "which-runtime": "^1.2.1"
  },
  "devDependencies": {
    "bare-compat-napi": "^1.3.5",
    "brittle": "^3.16.2",
    "cmake-bare": "^1.6.1",
    "cmake-fetch": "^1.4.3",
    "cmake-napi": "^1.2.1",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "test": "prettier . --check && npm run test:node && npm run test:bare",
    "test:node": "node test/all.js",
    "test:bare": "bare test/all.js"
  },
  "standard": {
    "ignore": [
      "/test/fixtures/*.js"
    ]
  },
  "engines": {
    "bare": ">=1.16.0"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sodium-native.git"
  },
  "contributors": [
    "Emil Bay <github@tixz.dk> (http://bayes.dk)",
    "Mathias Buus <mathiasbuus@gmail.com> (https://mafinto.sh)",
    "Christophe Diederichs <chm-diederichs@hyperdivision.dk>"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/sodium-native/issues"
  },
  "homepage": "https://github.com/holepunchto/sodium-native"
}
module.exports = require('sodium-native')
{
  "name": "sodium-universal",
  "version": "5.0.1",
  "description": "Universal wrapper for sodium-javascript and sodium-native working in Node.js and the Browser",
  "main": "index.js",
  "dependencies": {
    "sodium-native": "^5.0.1"
  },
  "peerDependencies": {
    "sodium-javascript": "~0.8.0"
  },
  "peerDependenciesMeta": {
    "sodium-javascript": {
      "optional": true
    }
  },
  "scripts": {
    "prepublish": "./build-scripts/generate.js"
  },
  "browser": {
    "sodium-native": "sodium-javascript"
  },
  "browserify": {
    "transform": [
      "./build-scripts/transform.js"
    ]
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sodium-universal.git"
  },
  "keywords": [
    "libsodium",
    "sodium",
    "sodium-native",
    "sodium-javascript",
    "browserify"
  ],
  "contributors": [
    "Emil Bay <github@tixz.dk> (http://bayes.dk)",
    "Mathias Buus <mathiasbuus@gmail.com> (https://mafinto.sh)",
    "Christophe Diederichs <chm-diederichs@hyperdivision.dk>"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/sodium-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/sodium-universal#readme"
}
const { EventEmitter } = require('events-universal')
const FIFO = require('fast-fifo')
const TextDecoder = require('text-decoder')

const StreamError = require('./lib/errors.js')

// if we do a future major, expect queue microtask to be there always, for now a bit defensive
const qmt =
  typeof queueMicrotask === 'undefined' ? (fn) => global.process.nextTick(fn) : queueMicrotask

// 29 bits used total (4 from shared, 14 from read, and 11 from write)
const MAX = (1 << 29) - 1

// Shared state
const OPENING = 0b0001
const PREDESTROYING = 0b0010
const DESTROYING = 0b0100
const DESTROYED = 0b1000

const NOT_OPENING = MAX ^ OPENING
const NOT_PREDESTROYING = MAX ^ PREDESTROYING

// Read state (4 bit offset from shared state)
const READ_ACTIVE = 0b00000000000001 << 4
const READ_UPDATING = 0b00000000000010 << 4
const READ_PRIMARY = 0b00000000000100 << 4
const READ_QUEUED = 0b00000000001000 << 4
const READ_RESUMED = 0b00000000010000 << 4
const READ_PIPE_DRAINED = 0b00000000100000 << 4
const READ_ENDING = 0b00000001000000 << 4
const READ_EMIT_DATA = 0b00000010000000 << 4
const READ_EMIT_READABLE = 0b00000100000000 << 4
const READ_EMITTED_READABLE = 0b00001000000000 << 4
const READ_DONE = 0b00010000000000 << 4
const READ_NEXT_TICK = 0b00100000000000 << 4
const READ_NEEDS_PUSH = 0b01000000000000 << 4
const READ_READ_AHEAD = 0b10000000000000 << 4

// Combined read state
const READ_FLOWING = READ_RESUMED | READ_PIPE_DRAINED
const READ_ACTIVE_AND_NEEDS_PUSH = READ_ACTIVE | READ_NEEDS_PUSH
const READ_PRIMARY_AND_ACTIVE = READ_PRIMARY | READ_ACTIVE
const READ_EMIT_READABLE_AND_QUEUED = READ_EMIT_READABLE | READ_QUEUED
const READ_RESUMED_READ_AHEAD = READ_RESUMED | READ_READ_AHEAD

const READ_NOT_ACTIVE = MAX ^ READ_ACTIVE
const READ_NON_PRIMARY = MAX ^ READ_PRIMARY
const READ_NON_PRIMARY_AND_PUSHED = MAX ^ (READ_PRIMARY | READ_NEEDS_PUSH)
const READ_PUSHED = MAX ^ READ_NEEDS_PUSH
const READ_PAUSED = MAX ^ READ_RESUMED
const READ_NOT_QUEUED = MAX ^ (READ_QUEUED | READ_EMITTED_READABLE)
const READ_NOT_ENDING = MAX ^ READ_ENDING
const READ_PIPE_NOT_DRAINED = MAX ^ READ_FLOWING
const READ_NOT_NEXT_TICK = MAX ^ READ_NEXT_TICK
const READ_NOT_UPDATING = MAX ^ READ_UPDATING
const READ_NO_READ_AHEAD = MAX ^ READ_READ_AHEAD
const READ_PAUSED_NO_READ_AHEAD = MAX ^ READ_RESUMED_READ_AHEAD

// Write state (18 bit offset, 4 bit offset from shared state and 14 from read state)
const WRITE_ACTIVE = 0b00000000001 << 18
const WRITE_UPDATING = 0b00000000010 << 18
const WRITE_PRIMARY = 0b00000000100 << 18
const WRITE_QUEUED = 0b00000001000 << 18
const WRITE_UNDRAINED = 0b00000010000 << 18
const WRITE_DONE = 0b00000100000 << 18
const WRITE_EMIT_DRAIN = 0b00001000000 << 18
const WRITE_NEXT_TICK = 0b00010000000 << 18
const WRITE_WRITING = 0b00100000000 << 18
const WRITE_FINISHING = 0b01000000000 << 18
const WRITE_CORKED = 0b10000000000 << 18

const WRITE_NOT_ACTIVE = MAX ^ (WRITE_ACTIVE | WRITE_WRITING)
const WRITE_NON_PRIMARY = MAX ^ WRITE_PRIMARY
const WRITE_NOT_FINISHING = MAX ^ (WRITE_ACTIVE | WRITE_FINISHING)
const WRITE_DRAINED = MAX ^ WRITE_UNDRAINED
const WRITE_NOT_QUEUED = MAX ^ WRITE_QUEUED
const WRITE_NOT_NEXT_TICK = MAX ^ WRITE_NEXT_TICK
const WRITE_NOT_UPDATING = MAX ^ WRITE_UPDATING
const WRITE_NOT_CORKED = MAX ^ WRITE_CORKED

// Combined shared state
const ACTIVE = READ_ACTIVE | WRITE_ACTIVE
const NOT_ACTIVE = MAX ^ ACTIVE
const DONE = READ_DONE | WRITE_DONE
const DESTROY_STATUS = DESTROYING | DESTROYED | PREDESTROYING
const OPEN_STATUS = DESTROY_STATUS | OPENING
const AUTO_DESTROY = DESTROY_STATUS | DONE
const NON_PRIMARY = WRITE_NON_PRIMARY & READ_NON_PRIMARY
const ACTIVE_OR_TICKING = WRITE_NEXT_TICK | READ_NEXT_TICK
const TICKING = ACTIVE_OR_TICKING & NOT_ACTIVE
const IS_OPENING = OPEN_STATUS | TICKING

// Combined shared state and read state
const READ_PRIMARY_STATUS = OPEN_STATUS | READ_ENDING | READ_DONE
const READ_STATUS = OPEN_STATUS | READ_DONE | READ_QUEUED
const READ_ENDING_STATUS = OPEN_STATUS | READ_ENDING | READ_QUEUED
const READ_READABLE_STATUS = OPEN_STATUS | READ_EMIT_READABLE | READ_QUEUED | READ_EMITTED_READABLE
const SHOULD_NOT_READ =
  OPEN_STATUS | READ_ACTIVE | READ_ENDING | READ_DONE | READ_NEEDS_PUSH | READ_READ_AHEAD
const READ_BACKPRESSURE_STATUS = DESTROY_STATUS | READ_ENDING | READ_DONE
const READ_UPDATE_SYNC_STATUS = READ_UPDATING | OPEN_STATUS | READ_NEXT_TICK | READ_PRIMARY
const READ_NEXT_TICK_OR_OPENING = READ_NEXT_TICK | OPENING

// Combined write state
const WRITE_PRIMARY_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_DONE
const WRITE_QUEUED_AND_UNDRAINED = WRITE_QUEUED | WRITE_UNDRAINED
const WRITE_QUEUED_AND_ACTIVE = WRITE_QUEUED | WRITE_ACTIVE
const WRITE_DRAIN_STATUS = WRITE_QUEUED | WRITE_UNDRAINED | OPEN_STATUS | WRITE_ACTIVE
const WRITE_STATUS = OPEN_STATUS | WRITE_ACTIVE | WRITE_QUEUED | WRITE_CORKED
const WRITE_PRIMARY_AND_ACTIVE = WRITE_PRIMARY | WRITE_ACTIVE
const WRITE_ACTIVE_AND_WRITING = WRITE_ACTIVE | WRITE_WRITING
const WRITE_FINISHING_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_QUEUED_AND_ACTIVE | WRITE_DONE
const WRITE_BACKPRESSURE_STATUS = WRITE_UNDRAINED | DESTROY_STATUS | WRITE_FINISHING | WRITE_DONE
const WRITE_UPDATE_SYNC_STATUS = WRITE_UPDATING | OPEN_STATUS | WRITE_NEXT_TICK | WRITE_PRIMARY
const WRITE_DROP_DATA = WRITE_FINISHING | WRITE_DONE | DESTROY_STATUS

const asyncIterator = Symbol.asyncIterator || Symbol('asyncIterator')

class WritableState {
  constructor(
    stream,
    { highWaterMark = 16384, map = null, mapWritable, byteLength, byteLengthWritable } = {}
  ) {
    this.stream = stream
    this.queue = new FIFO()
    this.highWaterMark = highWaterMark
    this.buffered = 0
    this.error = null
    this.pipeline = null
    this.drains = null // if we add more seldomly used helpers we might them into a subobject so its a single ptr
    this.byteLength = byteLengthWritable || byteLength || defaultByteLength
    this.map = mapWritable || map
    this.afterWrite = afterWrite.bind(this)
    this.afterUpdateNextTick = updateWriteNT.bind(this)
  }

  get ending() {
    return (this.stream._duplexState & WRITE_FINISHING) !== 0
  }

  get ended() {
    return (this.stream._duplexState & WRITE_DONE) !== 0
  }

  push(data) {
    if ((this.stream._duplexState & WRITE_DROP_DATA) !== 0) return false
    if (this.map !== null) data = this.map(data)

    this.buffered += this.byteLength(data)
    this.queue.push(data)

    if (this.buffered < this.highWaterMark) {
      this.stream._duplexState |= WRITE_QUEUED
      return true
    }

    this.stream._duplexState |= WRITE_QUEUED_AND_UNDRAINED
    return false
  }

  shift() {
    const data = this.queue.shift()

    this.buffered -= this.byteLength(data)
    if (this.buffered === 0) this.stream._duplexState &= WRITE_NOT_QUEUED

    return data
  }

  end(data) {
    if (typeof data === 'function') {
      this.stream.once('finish', data)
    } else if (data !== undefined && data !== null) {
      this.push(data)
    }

    this.stream._duplexState = (this.stream._duplexState | WRITE_FINISHING) & WRITE_NON_PRIMARY
  }

  autoBatch(data, cb) {
    const buffer = []
    const stream = this.stream

    buffer.push(data)
    while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED_AND_ACTIVE) {
      buffer.push(stream._writableState.shift())
    }

    if ((stream._duplexState & OPEN_STATUS) !== 0) return cb(null)
    stream._writev(buffer, cb)
  }

  update() {
    const stream = this.stream

    stream._duplexState |= WRITE_UPDATING

    do {
      while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED) {
        const data = this.shift()
        stream._duplexState |= WRITE_ACTIVE_AND_WRITING
        stream._write(data, this.afterWrite)
      }

      if ((stream._duplexState & WRITE_PRIMARY_AND_ACTIVE) === 0) this.updateNonPrimary()
    } while (this.continueUpdate() === true)

    stream._duplexState &= WRITE_NOT_UPDATING
  }

  updateNonPrimary() {
    const stream = this.stream

    if ((stream._duplexState & WRITE_FINISHING_STATUS) === WRITE_FINISHING) {
      stream._duplexState = stream._duplexState | WRITE_ACTIVE
      stream._final(afterFinal.bind(this))
      return
    }

    if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
      if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
        stream._duplexState |= ACTIVE
        stream._destroy(afterDestroy.bind(this))
      }
      return
    }

    if ((stream._duplexState & IS_OPENING) === OPENING) {
      stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING
      stream._open(afterOpen.bind(this))
    }
  }

  continueUpdate() {
    if ((this.stream._duplexState & WRITE_NEXT_TICK) === 0) return false
    this.stream._duplexState &= WRITE_NOT_NEXT_TICK
    return true
  }

  updateCallback() {
    if ((this.stream._duplexState & WRITE_UPDATE_SYNC_STATUS) === WRITE_PRIMARY) {
      this.update()
    } else {
      this.updateNextTick()
    }
  }

  updateNextTick() {
    if ((this.stream._duplexState & WRITE_NEXT_TICK) !== 0) return
    this.stream._duplexState |= WRITE_NEXT_TICK
    if ((this.stream._duplexState & WRITE_UPDATING) === 0) qmt(this.afterUpdateNextTick)
  }
}

class ReadableState {
  constructor(
    stream,
    { highWaterMark = 16384, map = null, mapReadable, byteLength, byteLengthReadable } = {}
  ) {
    this.stream = stream
    this.queue = new FIFO()
    this.highWaterMark = highWaterMark === 0 ? 1 : highWaterMark
    this.buffered = 0
    this.readAhead = highWaterMark > 0
    this.error = null
    this.pipeline = null
    this.byteLength = byteLengthReadable || byteLength || defaultByteLength
    this.map = mapReadable || map
    this.pipeTo = null
    this.afterRead = afterRead.bind(this)
    this.afterUpdateNextTick = updateReadNT.bind(this)
  }

  get ending() {
    return (this.stream._duplexState & READ_ENDING) !== 0
  }

  get ended() {
    return (this.stream._duplexState & READ_DONE) !== 0
  }

  pipe(pipeTo, cb) {
    if (this.pipeTo !== null) throw StreamError.BAD_ARGUMENT('Can only pipe to one destination')
    if (typeof cb !== 'function') cb = null

    this.stream._duplexState |= READ_PIPE_DRAINED
    this.pipeTo = pipeTo
    this.pipeline = new Pipeline(this.stream, pipeTo, cb)

    if (cb) this.stream.on('error', noop) // We already error handle this so supress crashes

    if (isStreamx(pipeTo)) {
      pipeTo._writableState.pipeline = this.pipeline
      if (cb) pipeTo.on('error', noop) // We already error handle this so supress crashes
      pipeTo.on('finish', this.pipeline.finished.bind(this.pipeline)) // TODO: just call finished from pipeTo itself
    } else {
      const onerror = this.pipeline.done.bind(this.pipeline, pipeTo)
      const onclose = this.pipeline.done.bind(this.pipeline, pipeTo, null) // onclose has a weird bool arg
      pipeTo.on('error', onerror)
      pipeTo.on('close', onclose)
      pipeTo.on('finish', this.pipeline.finished.bind(this.pipeline))
    }

    pipeTo.on('drain', afterDrain.bind(this))
    this.stream.emit('piping', pipeTo)
    pipeTo.emit('pipe', this.stream)
  }

  push(data) {
    const stream = this.stream

    if (data === null) {
      this.highWaterMark = 0
      stream._duplexState = (stream._duplexState | READ_ENDING) & READ_NON_PRIMARY_AND_PUSHED
      return false
    }

    if (this.map !== null) {
      data = this.map(data)
      if (data === null) {
        stream._duplexState &= READ_PUSHED
        return this.buffered < this.highWaterMark
      }
    }

    this.buffered += this.byteLength(data)
    this.queue.push(data)

    stream._duplexState = (stream._duplexState | READ_QUEUED) & READ_PUSHED

    return this.buffered < this.highWaterMark
  }

  shift() {
    const data = this.queue.shift()

    this.buffered -= this.byteLength(data)
    if (this.buffered === 0) {
      this.stream._duplexState &= READ_NOT_QUEUED
    }

    return data
  }

  unshift(data) {
    const pending = [this.map !== null ? this.map(data) : data]
    while (this.buffered > 0) pending.push(this.shift())

    for (let i = 0; i < pending.length - 1; i++) {
      const data = pending[i]
      this.buffered += this.byteLength(data)
      this.queue.push(data)
    }

    this.push(pending[pending.length - 1])
  }

  read() {
    const stream = this.stream

    if ((stream._duplexState & READ_STATUS) === READ_QUEUED) {
      const data = this.shift()

      if (this.pipeTo !== null && this.pipeTo.write(data) === false) {
        stream._duplexState &= READ_PIPE_NOT_DRAINED
      }

      if ((stream._duplexState & READ_EMIT_DATA) !== 0) {
        stream.emit('data', data)
      }

      return data
    }

    if (this.readAhead === false) {
      stream._duplexState |= READ_READ_AHEAD
      this.updateNextTick()
    }

    return null
  }

  drain() {
    const stream = this.stream

    while (
      (stream._duplexState & READ_STATUS) === READ_QUEUED &&
      (stream._duplexState & READ_FLOWING) !== 0
    ) {
      const data = this.shift()

      if (this.pipeTo !== null && this.pipeTo.write(data) === false) {
        stream._duplexState &= READ_PIPE_NOT_DRAINED
      }

      if ((stream._duplexState & READ_EMIT_DATA) !== 0) {
        stream.emit('data', data)
      }
    }
  }

  update() {
    const stream = this.stream

    stream._duplexState |= READ_UPDATING

    do {
      this.drain()

      while (
        this.buffered < this.highWaterMark &&
        (stream._duplexState & SHOULD_NOT_READ) === READ_READ_AHEAD
      ) {
        stream._duplexState |= READ_ACTIVE_AND_NEEDS_PUSH
        stream._read(this.afterRead)
        this.drain()
      }

      if ((stream._duplexState & READ_READABLE_STATUS) === READ_EMIT_READABLE_AND_QUEUED) {
        stream._duplexState |= READ_EMITTED_READABLE
        stream.emit('readable')
      }

      if ((stream._duplexState & READ_PRIMARY_AND_ACTIVE) === 0) {
        this.updateNonPrimary()
      }
    } while (this.continueUpdate() === true)

    stream._duplexState &= READ_NOT_UPDATING
  }

  updateNonPrimary() {
    const stream = this.stream

    if ((stream._duplexState & READ_ENDING_STATUS) === READ_ENDING) {
      stream._duplexState = (stream._duplexState | READ_DONE) & READ_NOT_ENDING
      stream.emit('end')

      if ((stream._duplexState & AUTO_DESTROY) === DONE) {
        stream._duplexState |= DESTROYING
      }

      if (this.pipeTo !== null) {
        this.pipeTo.end()
      }
    }

    if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
      if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
        stream._duplexState |= ACTIVE
        stream._destroy(afterDestroy.bind(this))
      }
      return
    }

    if ((stream._duplexState & IS_OPENING) === OPENING) {
      stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING
      stream._open(afterOpen.bind(this))
    }
  }

  continueUpdate() {
    if ((this.stream._duplexState & READ_NEXT_TICK) === 0) return false
    this.stream._duplexState &= READ_NOT_NEXT_TICK
    return true
  }

  updateCallback() {
    if ((this.stream._duplexState & READ_UPDATE_SYNC_STATUS) === READ_PRIMARY) {
      this.update()
    } else {
      this.updateNextTick()
    }
  }

  updateNextTickIfOpen() {
    if ((this.stream._duplexState & READ_NEXT_TICK_OR_OPENING) !== 0) return
    this.stream._duplexState |= READ_NEXT_TICK
    if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick)
  }

  updateNextTick() {
    if ((this.stream._duplexState & READ_NEXT_TICK) !== 0) return
    this.stream._duplexState |= READ_NEXT_TICK
    if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick)
  }
}

class TransformState {
  constructor(stream) {
    this.data = null
    this.afterTransform = afterTransform.bind(stream)
    this.afterFinal = null
  }
}

class Pipeline {
  constructor(src, dst, cb) {
    this.from = src
    this.to = dst
    this.afterPipe = cb
    this.error = null
    this.pipeToFinished = false
  }

  finished() {
    this.pipeToFinished = true
  }

  done(stream, err) {
    if (err) this.error = err

    if (stream === this.to) {
      this.to = null

      if (this.from !== null) {
        if ((this.from._duplexState & READ_DONE) === 0 || !this.pipeToFinished) {
          this.from.destroy(this.error || StreamError.PREMATURE_CLOSE('Writable stream closed'))
        }
        return
      }
    }

    if (stream === this.from) {
      this.from = null

      if (this.to !== null) {
        if ((stream._duplexState & READ_DONE) === 0) {
          this.to.destroy(this.error || StreamError.PREMATURE_CLOSE('Readable stream closed'))
        }
        return
      }
    }

    if (this.afterPipe !== null) this.afterPipe(this.error)
    this.to = this.from = this.afterPipe = null
  }
}

function afterDrain() {
  this.stream._duplexState |= READ_PIPE_DRAINED
  this.updateCallback()
}

function afterFinal(err) {
  const stream = this.stream
  if (err) stream.destroy(err)

  if ((stream._duplexState & DESTROY_STATUS) === 0) {
    stream._duplexState |= WRITE_DONE
    stream.emit('finish')
  }

  if ((stream._duplexState & AUTO_DESTROY) === DONE) {
    stream._duplexState |= DESTROYING
  }

  stream._duplexState &= WRITE_NOT_FINISHING

  // no need to wait the extra tick here, so we short circuit that
  if ((stream._duplexState & WRITE_UPDATING) === 0) {
    this.update()
  } else {
    this.updateNextTick()
  }
}

function afterDestroy(err) {
  const stream = this.stream

  if (!err && !StreamError.isStreamDestroyed(this.error)) err = this.error
  if (err) stream.emit('error', err)

  stream._duplexState |= DESTROYED
  stream.emit('close')

  const rs = stream._readableState
  const ws = stream._writableState

  if (rs !== null && rs.pipeline !== null) {
    rs.pipeline.done(stream, err)
  }

  if (ws !== null) {
    while (ws.drains !== null && ws.drains.length > 0) {
      ws.drains.shift().resolve(false)
    }

    if (ws.pipeline !== null) {
      ws.pipeline.done(stream, err)
    }
  }
}

function afterWrite(err) {
  const stream = this.stream

  if (err) stream.destroy(err)
  stream._duplexState &= WRITE_NOT_ACTIVE

  if (this.drains !== null) tickDrains(this.drains)

  if ((stream._duplexState & WRITE_DRAIN_STATUS) === WRITE_UNDRAINED) {
    stream._duplexState &= WRITE_DRAINED

    if ((stream._duplexState & WRITE_EMIT_DRAIN) === WRITE_EMIT_DRAIN) {
      stream.emit('drain')
    }
  }

  this.updateCallback()
}

function afterRead(err) {
  if (err) this.stream.destroy(err)
  this.stream._duplexState &= READ_NOT_ACTIVE

  if (this.readAhead === false && (this.stream._duplexState & READ_RESUMED) === 0) {
    this.stream._duplexState &= READ_NO_READ_AHEAD
  }

  this.updateCallback()
}

function updateReadNT() {
  if ((this.stream._duplexState & READ_UPDATING) === 0) {
    this.stream._duplexState &= READ_NOT_NEXT_TICK
    this.update()
  }
}

function updateWriteNT() {
  if ((this.stream._duplexState & WRITE_UPDATING) === 0) {
    this.stream._duplexState &= WRITE_NOT_NEXT_TICK
    this.update()
  }
}

function tickDrains(drains) {
  for (let i = 0; i < drains.length; i++) {
    // drains.writes are monotonic, so if one is 0 its always the first one
    if (--drains[i].writes === 0) {
      drains.shift().resolve(true)
      i--
    }
  }
}

function afterOpen(err) {
  const stream = this.stream

  if (err) stream.destroy(err)

  if ((stream._duplexState & DESTROYING) === 0) {
    if ((stream._duplexState & READ_PRIMARY_STATUS) === 0) {
      stream._duplexState |= READ_PRIMARY
    }

    if ((stream._duplexState & WRITE_PRIMARY_STATUS) === 0) {
      stream._duplexState |= WRITE_PRIMARY
    }

    stream.emit('open')
  }

  stream._duplexState &= NOT_ACTIVE

  if (stream._writableState !== null) {
    stream._writableState.updateCallback()
  }

  if (stream._readableState !== null) {
    stream._readableState.updateCallback()
  }
}

function afterTransform(err, data) {
  if (data !== undefined && data !== null) this.push(data)
  this._writableState.afterWrite(err)
}

function newListener(name) {
  if (this._readableState !== null) {
    if (name === 'data') {
      this._duplexState |= READ_EMIT_DATA | READ_RESUMED_READ_AHEAD
      this._readableState.updateNextTick()
    }
    if (name === 'readable') {
      this._duplexState |= READ_EMIT_READABLE
      this._readableState.updateNextTick()
    }
  }

  if (this._writableState !== null) {
    if (name === 'drain') {
      this._duplexState |= WRITE_EMIT_DRAIN
      this._writableState.updateNextTick()
    }
  }
}

class Stream extends EventEmitter {
  constructor(opts) {
    super()

    this._duplexState = 0
    this._readableState = null
    this._writableState = null

    if (opts) {
      if (opts.open) this._open = opts.open
      if (opts.destroy) this._destroy = opts.destroy
      if (opts.predestroy) this._predestroy = opts.predestroy
      if (opts.signal) opts.signal.addEventListener('abort', abort.bind(this))
    }

    this.on('newListener', newListener)
  }

  _open(cb) {
    cb(null)
  }

  _destroy(cb) {
    cb(null)
  }

  _predestroy() {
    // does nothing
  }

  get readable() {
    return this._readableState !== null ? true : undefined
  }

  get writable() {
    return this._writableState !== null ? true : undefined
  }

  get destroyed() {
    return (this._duplexState & DESTROYED) !== 0
  }

  get destroying() {
    return (this._duplexState & DESTROY_STATUS) !== 0
  }

  destroy(err) {
    if ((this._duplexState & DESTROY_STATUS) === 0) {
      if (!err) err = StreamError.STREAM_DESTROYED()
      this._duplexState = (this._duplexState | DESTROYING) & NON_PRIMARY

      if (this._readableState !== null) {
        this._readableState.highWaterMark = 0
        this._readableState.error = err
      }

      if (this._writableState !== null) {
        this._writableState.highWaterMark = 0
        this._writableState.error = err
      }

      this._duplexState |= PREDESTROYING
      this._predestroy()
      this._duplexState &= NOT_PREDESTROYING

      if (this._readableState !== null) {
        this._readableState.updateNextTick()
      }

      if (this._writableState !== null) {
        this._writableState.updateNextTick()
      }
    }
  }
}

class Readable extends Stream {
  constructor(opts) {
    super(opts)

    this._duplexState |= OPENING | WRITE_DONE | READ_READ_AHEAD
    this._readableState = new ReadableState(this, opts)

    if (opts) {
      if (this._readableState.readAhead === false) this._duplexState &= READ_NO_READ_AHEAD
      if (opts.read) this._read = opts.read
      if (opts.eagerOpen) this._readableState.updateNextTick()
      if (opts.encoding) this.setEncoding(opts.encoding)
    }
  }

  static deferred(fn, opts) {
    const out = new PassThrough(opts)

    fn()
      .then((src) => {
        if (src === null) return out.end()
        if (out.destroying) return
        pipeline(src, out, noop)
      })
      .catch((err) => out.destroy(err))

    return out
  }

  setEncoding(encoding) {
    const dec = new TextDecoder(encoding)
    const map = this._readableState.map || echo
    this._readableState.map = mapOrSkip
    return this

    function mapOrSkip(data) {
      const next = dec.push(data)
      return next === '' && (data.byteLength !== 0 || dec.remaining > 0) ? null : map(next)
    }
  }

  _read(cb) {
    cb(null)
  }

  pipe(dest, cb) {
    this._readableState.updateNextTick()
    this._readableState.pipe(dest, cb)
    return dest
  }

  read() {
    this._readableState.updateNextTick()
    return this._readableState.read()
  }

  push(data) {
    this._readableState.updateNextTickIfOpen()
    return this._readableState.push(data)
  }

  unshift(data) {
    this._readableState.updateNextTickIfOpen()
    return this._readableState.unshift(data)
  }

  resume() {
    this._duplexState |= READ_RESUMED_READ_AHEAD
    this._readableState.updateNextTick()
    return this
  }

  pause() {
    this._duplexState &=
      this._readableState.readAhead === false ? READ_PAUSED_NO_READ_AHEAD : READ_PAUSED
    return this
  }

  static _fromAsyncIterator(ite, opts) {
    let destroy

    const rs = new Readable({
      ...opts,
      read(cb) {
        ite.next().then(push).then(cb.bind(null, null)).catch(cb)
      },
      predestroy() {
        destroy = ite.return()
      },
      destroy(cb) {
        if (!destroy) return cb(null)
        destroy.then(cb.bind(null, null)).catch(cb)
      }
    })

    return rs

    function push(data) {
      if (data.done) rs.push(null)
      else rs.push(data.value)
    }
  }

  static from(data, opts) {
    if (isReadStreamx(data)) return data
    if (data[asyncIterator]) return this._fromAsyncIterator(data[asyncIterator](), opts)
    if (!Array.isArray(data)) data = data === undefined ? [] : [data]

    let i = 0
    return new Readable({
      ...opts,
      read(cb) {
        this.push(i === data.length ? null : data[i++])
        cb(null)
      }
    })
  }

  static isBackpressured(rs) {
    return (
      (rs._duplexState & READ_BACKPRESSURE_STATUS) !== 0 ||
      rs._readableState.buffered >= rs._readableState.highWaterMark
    )
  }

  static isPaused(rs) {
    return (rs._duplexState & READ_RESUMED) === 0
  }

  [asyncIterator]() {
    const stream = this

    let error = null
    let promiseResolve = null
    let promiseReject = null

    this.on('error', (err) => {
      error = err
    })
    this.on('readable', onreadable)
    this.on('close', onclose)

    return {
      [asyncIterator]() {
        return this
      },
      next() {
        return new Promise(function (resolve, reject) {
          promiseResolve = resolve
          promiseReject = reject
          const data = stream.read()
          if (data !== null) ondata(data)
          else if ((stream._duplexState & DESTROYED) !== 0) ondata(null)
        })
      },
      return() {
        return destroy(null)
      },
      throw(err) {
        return destroy(err)
      }
    }

    function onreadable() {
      if (promiseResolve !== null) ondata(stream.read())
    }

    function onclose() {
      if (promiseResolve !== null) ondata(null)
    }

    function ondata(data) {
      if (promiseReject === null) return
      if (error) {
        promiseReject(error)
      } else if (data === null && (stream._duplexState & READ_DONE) === 0) {
        promiseReject(StreamError.STREAM_DESTROYED())
      } else {
        promiseResolve({ value: data, done: data === null })
      }
      promiseReject = promiseResolve = null
    }

    function destroy(err) {
      stream.destroy(err)
      return new Promise((resolve, reject) => {
        if (stream._duplexState & DESTROYED) return resolve({ value: undefined, done: true })
        stream.once('close', function () {
          if (err) reject(err)
          else resolve({ value: undefined, done: true })
        })
      })
    }
  }
}

class Writable extends Stream {
  constructor(opts) {
    super(opts)

    this._duplexState |= OPENING | READ_DONE
    this._writableState = new WritableState(this, opts)

    if (opts) {
      if (opts.writev) this._writev = opts.writev
      if (opts.write) this._write = opts.write
      if (opts.final) this._final = opts.final
      if (opts.eagerOpen) this._writableState.updateNextTick()
    }
  }

  cork() {
    this._duplexState |= WRITE_CORKED
  }

  uncork() {
    this._duplexState &= WRITE_NOT_CORKED
    this._writableState.updateNextTick()
  }

  _writev(batch, cb) {
    cb(null)
  }

  _write(data, cb) {
    this._writableState.autoBatch(data, cb)
  }

  _final(cb) {
    cb(null)
  }

  static isBackpressured(ws) {
    return (ws._duplexState & WRITE_BACKPRESSURE_STATUS) !== 0
  }

  static drained(ws) {
    if (ws.destroyed) return Promise.resolve(false)

    const state = ws._writableState
    const pending = isWritev(ws) ? Math.min(1, state.queue.length) : state.queue.length
    const writes = pending + (ws._duplexState & WRITE_WRITING ? 1 : 0)
    if (writes === 0) return Promise.resolve(true)

    if (state.drains === null) state.drains = []
    return new Promise((resolve) => {
      state.drains.push({ writes, resolve })
    })
  }

  write(data) {
    this._writableState.updateNextTick()
    return this._writableState.push(data)
  }

  end(data) {
    this._writableState.updateNextTick()
    this._writableState.end(data)
    return this
  }
}

class Duplex extends Readable {
  // and Writable
  constructor(opts) {
    super(opts)

    this._duplexState = OPENING | (this._duplexState & READ_READ_AHEAD)
    this._writableState = new WritableState(this, opts)

    if (opts) {
      if (opts.writev) this._writev = opts.writev
      if (opts.write) this._write = opts.write
      if (opts.final) this._final = opts.final
    }
  }

  cork() {
    this._duplexState |= WRITE_CORKED
  }

  uncork() {
    this._duplexState &= WRITE_NOT_CORKED
    this._writableState.updateNextTick()
  }

  _writev(batch, cb) {
    cb(null)
  }

  _write(data, cb) {
    this._writableState.autoBatch(data, cb)
  }

  _final(cb) {
    cb(null)
  }

  write(data) {
    this._writableState.updateNextTick()
    return this._writableState.push(data)
  }

  end(data) {
    this._writableState.updateNextTick()
    this._writableState.end(data)
    return this
  }
}

class Transform extends Duplex {
  constructor(opts) {
    super(opts)
    this._transformState = new TransformState(this)

    if (opts) {
      if (opts.transform) this._transform = opts.transform
      if (opts.flush) this._flush = opts.flush
    }
  }

  _write(data, cb) {
    if (this._readableState.buffered >= this._readableState.highWaterMark) {
      this._transformState.data = data
    } else {
      this._transform(data, this._transformState.afterTransform)
    }
  }

  _read(cb) {
    if (this._transformState.data !== null) {
      const data = this._transformState.data
      this._transformState.data = null
      cb(null)
      this._transform(data, this._transformState.afterTransform)
    } else {
      cb(null)
    }
  }

  destroy(err) {
    super.destroy(err)
    if (this._transformState.data !== null) {
      this._transformState.data = null
      this._transformState.afterTransform()
    }
  }

  _transform(data, cb) {
    cb(null, data)
  }

  _flush(cb) {
    cb(null)
  }

  _final(cb) {
    this._transformState.afterFinal = cb
    this._flush(transformAfterFlush.bind(this))
  }
}

class PassThrough extends Transform {}

function transformAfterFlush(err, data) {
  const cb = this._transformState.afterFinal
  if (err) return cb(err)

  if (data !== null && data !== undefined) this.push(data)
  this.push(null)
  cb(null)
}

function pipelinePromise(...streams) {
  return new Promise((resolve, reject) => {
    return pipeline(...streams, (err) => {
      if (err) return reject(err)
      resolve()
    })
  })
}

function pipeline(stream, ...streams) {
  const all = Array.isArray(stream) ? [...stream, ...streams] : [stream, ...streams]
  const done = all.length && typeof all[all.length - 1] === 'function' ? all.pop() : null

  if (all.length < 2) throw StreamError.BAD_ARGUMENT('Pipeline requires at least 2 streams')

  let src = all[0]
  let dest = null
  let error = null

  for (let i = 1; i < all.length; i++) {
    dest = all[i]

    if (isStreamx(src)) {
      src.pipe(dest, onerror)
    } else {
      errorHandle(src, true, i > 1, onerror)
      src.pipe(dest)
    }

    src = dest
  }

  if (done) {
    let fin = false

    const autoDestroy =
      isStreamx(dest) || !!(dest._writableState && dest._writableState.autoDestroy)

    dest.on('error', (err) => {
      if (error === null) error = err
    })

    dest.on('finish', () => {
      fin = true
      if (!autoDestroy) done(error)
    })

    if (autoDestroy) {
      dest.on('close', () => done(error || (fin ? null : StreamError.PREMATURE_CLOSE())))
    }
  }

  return dest

  function errorHandle(s, rd, wr, onerror) {
    s.on('error', onerror)
    s.on('close', onclose)

    function onclose() {
      if (rd && s._readableState && !s._readableState.ended) {
        return onerror(StreamError.PREMATURE_CLOSE())
      }
      if (wr && s._writableState && !s._writableState.ended) {
        return onerror(StreamError.PREMATURE_CLOSE())
      }
    }
  }

  function onerror(err) {
    if (!err || error) return
    error = err

    for (const s of all) {
      s.destroy(err)
    }
  }
}

function echo(s) {
  return s
}

function isStream(stream) {
  return !!stream._readableState || !!stream._writableState
}

function isStreamx(stream) {
  return typeof stream._duplexState === 'number' && isStream(stream)
}

function isEnding(stream) {
  return !!stream._readableState && stream._readableState.ending
}

function isEnded(stream) {
  return !!stream._readableState && stream._readableState.ended
}

function isFinishing(stream) {
  return !!stream._writableState && stream._writableState.ending
}

function isFinished(stream) {
  return !!stream._writableState && stream._writableState.ended
}

function getStreamError(stream, opts = {}) {
  const err =
    (stream._readableState && stream._readableState.error) ||
    (stream._writableState && stream._writableState.error)

  // avoid implicit errors by default
  return !opts.all && StreamError.isStreamDestroyed(err) ? null : err
}

function isReadStreamx(stream) {
  return isStreamx(stream) && stream.readable
}

function isDisturbed(stream) {
  return (
    (stream._duplexState & OPENING) !== OPENING ||
    (stream._duplexState & DESTROYING) === DESTROYING ||
    (stream._duplexState & ACTIVE_OR_TICKING) !== 0
  )
}

function isTypedArray(data) {
  return typeof data === 'object' && data !== null && typeof data.byteLength === 'number'
}

function defaultByteLength(data) {
  return isTypedArray(data) ? data.byteLength : 1024
}

function noop() {}

function abort() {
  this.destroy(StreamError.ABORTED())
}

function isWritev(s) {
  return s._writev !== Writable.prototype._writev && s._writev !== Duplex.prototype._writev
}

module.exports = {
  pipeline,
  pipelinePromise,
  isStream,
  isStreamx,
  isEnding,
  isEnded,
  isFinishing,
  isFinished,
  isDisturbed,
  getStreamError,
  Stream,
  Writable,
  Readable,
  Duplex,
  Transform,
  // Export PassThrough for compatibility with Node.js core's stream module
  PassThrough
}
module.exports = class StreamError extends Error {
  constructor(msg, code, fn = StreamError) {
    super(msg)

    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  static isStreamDestroyed(err) {
    return err && err.code === 'STREAM_DESTROYED'
  }

  static isPrematureClose(err) {
    return err && err.code === 'PREMATURE_CLOSE'
  }

  static isAborted(err) {
    return err && err.code === 'ABORTED'
  }

  static isBadArgument(err) {
    return err && err.code === 'BAD_ARGUMENT'
  }

  get name() {
    return 'StreamError'
  }

  static STREAM_DESTROYED() {
    return new StreamError('Stream was destroyed', 'STREAM_DESTROYED', StreamError.STREAM_DESTROYED)
  }

  static PREMATURE_CLOSE(msg = 'Premature close') {
    return new StreamError(msg, 'PREMATURE_CLOSE', StreamError.PREMATURE_CLOSE)
  }

  static ABORTED() {
    return new StreamError('Stream aborted', 'ABORTED', StreamError.ABORTED)
  }

  static BAD_ARGUMENT(msg = 'Bad argument') {
    return new StreamError(msg, 'BAD_ARGUMENT', StreamError.BAD_ARGUMENT)
  }
}
{
  "name": "streamx",
  "version": "2.28.0",
  "description": "An iteration of the Node.js core streams with a series of improvements",
  "main": "index.js",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./errors": {
      "types": "./lib/errors.d.ts",
      "default": "./lib/errors"
    }
  },
  "dependencies": {
    "events-universal": "^1.0.0",
    "fast-fifo": "^1.3.2",
    "text-decoder": "^1.1.0"
  },
  "devDependencies": {
    "b4a": "^1.6.6",
    "brittle": "^3.1.1",
    "end-of-stream": "^1.4.4",
    "lunte": "^1.8.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "runtime.d.ts",
    "lib"
  ],
  "scripts": {
    "format": "prettier . --write",
    "test": "brittle test/all.js && brittle-bare test/all.js",
    "lint": "prettier . --check && lunte"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/streamx.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/streamx/issues"
  },
  "homepage": "https://github.com/mafintosh/streamx"
}
const { Readable } = require('streamx')

module.exports = function (s, forks = 2) {
  const streams = new Array(forks)
  const status = new Array(forks).fill(true)

  let ended = false

  for (let i = 0; i < forks; i++) {
    streams[i] = new Readable({
      read (cb) {
        const check = !status[i]
        status[i] = true
        if (check && allReadable()) s.resume()
        cb(null)
      }
    })
  }

  s.on('end', function () {
    ended = true
    for (const stream of streams) stream.push(null)
  })

  s.on('error', function (err) {
    for (const stream of streams) stream.destroy(err)
  })

  s.on('close', function () {
    if (ended) return
    for (const stream of streams) stream.destroy()
  })

  s.on('data', function (data) {
    let needsPause = false
    for (let i = 0; i < streams.length; i++) {
      if (!(status[i] = streams[i].push(data))) {
        needsPause = true
      }
    }
    if (needsPause) s.pause()
  })

  return streams

  function allReadable () {
    for (let j = 0; j < status.length; j++) {
      if (!status[j]) return false
    }
    return true
  }
}
{
  "name": "teex",
  "version": "1.0.1",
  "description": "Turn a readable stream into multiple readable streamx streams",
  "main": "index.js",
  "dependencies": {
    "streamx": "^2.12.5"
  },
  "devDependencies": {
    "standard": "^14.3.4",
    "tape": "^5.0.1"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/teex.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/teex/issues"
  },
  "homepage": "https://github.com/mafintosh/teex"
}
const PassThroughDecoder = require('./lib/pass-through-decoder')
const UTF8Decoder = require('./lib/utf8-decoder')

module.exports = class TextDecoder {
  constructor(encoding = 'utf8') {
    this.encoding = normalizeEncoding(encoding)

    switch (this.encoding) {
      case 'utf8':
        this.decoder = new UTF8Decoder()
        break
      case 'utf16le':
      case 'base64':
        throw new Error('Unsupported encoding: ' + this.encoding)
      default:
        this.decoder = new PassThroughDecoder(this.encoding)
    }
  }

  get remaining() {
    return this.decoder.remaining
  }

  push(data) {
    if (typeof data === 'string') return data
    return this.decoder.decode(data)
  }

  // For Node.js compatibility
  write(data) {
    return this.push(data)
  }

  end(data) {
    let result = ''
    if (data) result = this.push(data)
    result += this.decoder.flush()
    return result
  }
}

function normalizeEncoding(encoding) {
  encoding = encoding.toLowerCase()

  switch (encoding) {
    case 'utf8':
    case 'utf-8':
      return 'utf8'
    case 'ucs2':
    case 'ucs-2':
    case 'utf16le':
    case 'utf-16le':
      return 'utf16le'
    case 'latin1':
    case 'binary':
      return 'latin1'
    case 'base64':
    case 'ascii':
    case 'hex':
      return encoding
    default:
      throw new Error('Unknown encoding: ' + encoding)
  }
}
const b4a = require('b4a')

module.exports = class PassThroughDecoder {
  constructor(encoding) {
    this.encoding = encoding
  }

  get remaining() {
    return 0
  }

  decode(data) {
    return b4a.toString(data, this.encoding)
  }

  flush() {
    return ''
  }
}
const b4a = require('b4a')

/**
 * https://encoding.spec.whatwg.org/#utf-8-decoder
 */
module.exports = class UTF8Decoder {
  constructor() {
    this._reset()
  }

  get remaining() {
    return this.bytesSeen
  }

  decode(data) {
    if (data.byteLength === 0) return ''

    if (this.bytesNeeded === 0 && trailingIncomplete(data, 0) === 0) {
      this.bytesSeen = trailingBytesSeen(data)
      return b4a.toString(data, 'utf8')
    }

    let result = ''
    let start = 0

    if (this.bytesNeeded > 0) {
      while (start < data.byteLength) {
        const byte = data[start]

        if (byte < this.lowerBoundary || byte > this.upperBoundary) {
          result += '\ufffd'
          this._reset()
          break
        }

        this.lowerBoundary = 0x80
        this.upperBoundary = 0xbf
        this.codePoint = (this.codePoint << 6) | (byte & 0x3f)
        this.bytesSeen++
        start++

        if (this.bytesSeen === this.bytesNeeded) {
          result += String.fromCodePoint(this.codePoint)
          this._reset()
          break
        }
      }

      if (this.bytesNeeded > 0) return result
    }

    const trailing = trailingIncomplete(data, start)
    const end = data.byteLength - trailing

    if (end > start) result += b4a.toString(data, 'utf8', start, end)

    for (let i = end; i < data.byteLength; i++) {
      const byte = data[i]

      if (this.bytesNeeded === 0) {
        if (byte <= 0x7f) {
          this.bytesSeen = 0
          result += String.fromCharCode(byte)
        } else if (byte >= 0xc2 && byte <= 0xdf) {
          this.bytesNeeded = 2
          this.bytesSeen = 1
          this.codePoint = byte & 0x1f
        } else if (byte >= 0xe0 && byte <= 0xef) {
          if (byte === 0xe0) this.lowerBoundary = 0xa0
          else if (byte === 0xed) this.upperBoundary = 0x9f
          this.bytesNeeded = 3
          this.bytesSeen = 1
          this.codePoint = byte & 0xf
        } else if (byte >= 0xf0 && byte <= 0xf4) {
          if (byte === 0xf0) this.lowerBoundary = 0x90
          else if (byte === 0xf4) this.upperBoundary = 0x8f
          this.bytesNeeded = 4
          this.bytesSeen = 1
          this.codePoint = byte & 0x7
        } else {
          this.bytesSeen = 1
          result += '\ufffd'
        }

        continue
      }

      if (byte < this.lowerBoundary || byte > this.upperBoundary) {
        result += '\ufffd'
        i--
        this._reset()

        continue
      }

      this.lowerBoundary = 0x80
      this.upperBoundary = 0xbf

      this.codePoint = (this.codePoint << 6) | (byte & 0x3f)
      this.bytesSeen++

      if (this.bytesSeen === this.bytesNeeded) {
        result += String.fromCodePoint(this.codePoint)
        this._reset()
      }
    }

    return result
  }

  flush() {
    const result = this.bytesNeeded > 0 ? '\ufffd' : ''
    this._reset()
    return result
  }

  _reset() {
    this.codePoint = 0
    this.bytesNeeded = 0
    this.bytesSeen = 0
    this.lowerBoundary = 0x80
    this.upperBoundary = 0xbf
  }
}

function trailingIncomplete(data, start) {
  const len = data.byteLength
  if (len <= start) return 0

  const limit = Math.max(start, len - 4)

  let i = len - 1
  while (i > limit && (data[i] & 0xc0) === 0x80) i--

  if (i < start) return 0

  const byte = data[i]

  let needed
  if (byte <= 0x7f) return 0
  if (byte >= 0xc2 && byte <= 0xdf) needed = 2
  else if (byte >= 0xe0 && byte <= 0xef) needed = 3
  else if (byte >= 0xf0 && byte <= 0xf4) needed = 4
  else return 0

  const available = len - i
  return available < needed ? available : 0
}

function trailingBytesSeen(data) {
  const len = data.byteLength
  if (len === 0) return 0

  const last = data[len - 1]

  if (last <= 0x7f) return 0
  if ((last & 0xc0) !== 0x80) return 1

  const limit = Math.max(0, len - 4)

  let i = len - 2
  while (i >= limit && (data[i] & 0xc0) === 0x80) i--

  if (i < 0) return 1

  const first = data[i]

  let needed
  if (first >= 0xc2 && first <= 0xdf) needed = 2
  else if (first >= 0xe0 && first <= 0xef) needed = 3
  else if (first >= 0xf0 && first <= 0xf4) needed = 4
  else return 1

  if (len - i !== needed) return 1

  if (needed >= 3) {
    const second = data[i + 1]
    if (first === 0xe0 && second < 0xa0) return 1
    if (first === 0xed && second > 0x9f) return 1
    if (first === 0xf0 && second < 0x90) return 1
    if (first === 0xf4 && second > 0x8f) return 1
  }

  return 0
}
{
  "name": "text-decoder",
  "version": "1.2.7",
  "description": "Streaming text decoder that preserves multibyte Unicode characters",
  "exports": {
    "./package": "./package.json",
    ".": "./index.js"
  },
  "files": [
    "index.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/text-decoder.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/text-decoder/issues"
  },
  "homepage": "https://github.com/holepunchto/text-decoder#readme",
  "dependencies": {
    "b4a": "^1.6.4"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  }
}
const { runtime, platform, arch, version } =
  typeof Bare !== 'undefined'
    ? {
        runtime: 'bare',
        platform: global.Bare.platform,
        arch: global.Bare.arch,
        version: global.Bare.version
      }
    : typeof process !== 'undefined'
      ? {
          runtime: 'node',
          platform: global.process.platform,
          arch: global.process.arch,
          version: global.process.version
        }
      : typeof Window !== 'undefined'
        ? { runtime: 'browser', platform: 'unknown', arch: 'unknown', version: 'unknown' }
        : { runtime: 'unknown', platform: 'unknown', arch: 'unknown', version: 'unknown' }

exports.runtime = runtime
exports.version = version
exports.platform = platform
exports.arch = arch
exports.isBare = runtime === 'bare'
exports.isBareKit = exports.isBare && typeof BareKit !== 'undefined'
exports.isPear = typeof Pear !== 'undefined'
exports.isNode = runtime === 'node'
exports.isBrowser = runtime === 'browser'
exports.isWindows = platform === 'win32'
exports.isLinux = platform === 'linux'
exports.isMac = platform === 'darwin'
exports.isIOS = platform === 'ios' || platform === 'ios-simulator'
exports.isAndroid = platform === 'android'
exports.isElectron = typeof process !== 'undefined' && !!global.process.versions?.electron
exports.isElectronRenderer = exports.isElectron && global.process.type === 'renderer'
exports.isElectronWorker = exports.isElectron && global.process.type === 'worker'
{
  "name": "which-runtime",
  "version": "1.4.0",
  "description": "Detect if you are in Bare or Node and which os etc",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte .",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/which-runtime.git"
  },
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/which-runtime/issues"
  },
  "homepage": "https://github.com/holepunchto/which-runtime",
  "devDependencies": {
    "brittle": "^3.0.0",
    "lunte": "^1.4.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
{
  "name": "hyper-overlay",
  "version": "0.3.13",
  "description": "Content-addressed P2P file distribution over Protomux — FastCDC chunking, multi-source fetch, resumable transfers, zero blob duplication. Files live on disk; the overlay is a thin index and transfer protocol.",
  "type": "module",
  "main": "index.js",
  "imports": {
    "#fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "#path": {
      "bare": "bare-path",
      "default": "path"
    },
    "#os": {
      "bare": "bare-os",
      "default": "os"
    },
    "#zlib": {
      "bare": "bare-zlib",
      "default": "zlib"
    }
  },
  "exports": {
    ".": "./index.js",
    "./overlay": "./lib/overlay.js",
    "./protocol": "./lib/protocol.js",
    "./messages": "./lib/messages.js",
    "./chunker": "./lib/chunker.js",
    "./chunk-scheduler": "./lib/chunk-scheduler.js",
    "./transfer": "./lib/transfer.js",
    "./file-index": "./lib/file-index.js",
    "./sync-engine": "./lib/sync-engine.js",
    "./tree": "./lib/tree.js",
    "./pointer": "./lib/pointer.js",
    "./ignore": "./lib/ignore.js",
    "./manifest": "./lib/manifest.js",
    "./package.json": "./package.json"
  },
  "scripts": {
    "test": "brittle-bare test/*.test.js test/integration/*.test.js",
    "test:node": "brittle-node test/*.test.js"
  },
  "engines": {
    "bare": ">=1.16.0"
  },
  "license": "AGPL-3.0",
  "keywords": [
    "p2p",
    "hypercore",
    "hyperbee",
    "protomux",
    "overlay",
    "content-addressed",
    "deduplication",
    "file-transfer",
    "fastcdc",
    "chunking",
    "multi-source",
    "resumable",
    "bare"
  ],
  "dependencies": {
    "b4a": "^1.0.0",
    "bare-fs": "^4.7.2",
    "bare-os": "^3.8.7",
    "bare-path": "^3.0.0",
    "bare-zlib": "^1.3.3",
    "compact-encoding": "^3.2.0",
    "corestore": "^7.0.0",
    "hyperbee": "^2.0.0",
    "hypercore-crypto": "^3.0.0",
    "protomux": "^3.0.0",
    "ready-resource": "^1.0.0",
    "sodium-universal": "^5.0.1",
    "streamx": "^2.0.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "hyperswarm": "^4.0.0",
    "@hyperswarm/testnet": "^3.1.4"
  }
}
{
  "name": "pgh-runtime",
  "version": "0.1.4",
  "description": "Per-app OTA updater for pgh-installed apps — polls a release source, materializes new trees into the pgh store",
  "type": "module",
  "main": "index.js",
  "exports": {
    ".": "./index.js"
  },
  "imports": {
    "#node:events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "scripts": {
    "test": "brittle test/*.test.js"
  },
  "license": "AGPL-3.0",
  "dependencies": {
    "bare-events": "^2.0.0",
    "hyper-overlay": "file:../hyper-overlay"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "hypercore-crypto": "^3.0.0"
  },
  "overrides": {
    "bare-fs": "^4.7.2"
  }
}
/**
 * NetworkFetcher — Hyperswarm-backed { getTree, getContent, getLatestRelease }
 *
 * Phase 0.5 follow-on. Lives between pgh-runtime / installTree (which
 * expect a fetcher shape) and the wire (Hyperswarm + OverlayProtocol
 * tree-request / content-request messages, plus chunk flow for content).
 *
 * Server side: hyper-deploy's DeployServer (0.5b + enableTrees) attaches
 * OverlayProtocol to each incoming connection and has trees +
 * contentHashPaths pre-populated. The client just needs to connect on
 * the same topic and open a protomux channel.
 *
 * Usage:
 *   const fetcher = new NetworkFetcher({ topic: '...hex...', timeout: 15000 })
 *   await fetcher.ready()
 *   const tree = await fetcher.getTree(rootHash)
 *   const content = await fetcher.getContent(contentHash)
 *   await fetcher.close()
 *
 * Limitations (scope boundary — further refinement tracked separately):
 *  - getLatestRelease currently reads from the LOCAL ReleaseRegistry.
 *    Replication of the publisher's remote registry is a follow-on.
 *  - Content transfer uses the existing chunk flow triggered by the
 *    server's _onContentRequest handler — getContent awaits the next
 *    transferComplete that lands locally.
 */

import fs from '#node:fs'
import path from '#node:path'
import { homedir, tmpdir as osTmpdir } from '#node:os'
import b4a from 'b4a'

import Hyperswarm from 'hyperswarm'
import Protomux from 'protomux'
import Corestore from 'corestore'
import crypto from 'hypercore-crypto'

import { FileIndex } from 'hyper-overlay/file-index'
import { TransferManager } from 'hyper-overlay/transfer'
import { OverlayProtocol } from 'hyper-overlay/protocol'
import { computeTreeHash } from 'hyper-overlay/tree'

import { ReleaseRegistry } from './release-registry.js'

const DEFAULT_TIMEOUT = 30000
const DEFAULT_LOCAL_REGISTRY = path.join(homedir(), '.config', 'pgh', 'release-registry')

export class NetworkFetcher {
  /**
   * @param {object} opts
   * @param {string|Buffer} opts.topic          — 32-byte discovery key
   * @param {number} [opts.timeout]             — per-request timeout (ms)
   * @param {string} [opts.storeDir]            — temp corestore path
   * @param {Hyperswarm} [opts.swarm]           — reuse an existing swarm
   * @param {string} [opts.localRegistryDir]    — for getLatestRelease (local lookup)
   * @param {string} [opts.destDir]             — where content chunks land; default tmp
   */
  constructor (opts = {}) {
    if (!opts.topic) throw new Error('NetworkFetcher requires opts.topic')
    this.topic = typeof opts.topic === 'string' ? b4a.from(opts.topic, 'hex') : opts.topic
    this.timeout = opts.timeout || DEFAULT_TIMEOUT
    this.localRegistryDir = opts.localRegistryDir || DEFAULT_LOCAL_REGISTRY
    this.swarm = opts.swarm || null
    this._ownSwarm = !this.swarm
    this._storeDir = opts.storeDir || null
    this._destDir = opts.destDir || null

    this._store = null
    this._fileIndex = null
    this._transferManager = null
    this._protocol = null
    this._peers = [] // all peers discovered on the topic (in connection order)
    this._peerResolve = null
    this._pendingContent = new Map() // contentHash → { resolve, reject, timer, diskPath }
    this._ready = false

    // Per-peer timeouts for individual requests. Tree lookups are small
    // RPCs — if a peer doesn't respond in a few seconds it doesn't have
    // the tree. Content is an actual chunk stream, so it legitimately
    // takes longer; we keep that timeout at the full request budget.
    // The big speedup comes from `_markPeerGood` promoting responsive
    // peers to the front of the list after their first success.
    this._perPeerTreeTimeout = Math.min(opts.perPeerTreeTimeout || 5000, this.timeout)
    this._perPeerContentTimeout = opts.perPeerContentTimeout || this.timeout
    // Silent-peer watchdog: how long an in-flight content request can go
    // without ANY chunk arrival before we declare the peer silent and
    // fail the request. Companion to fail-fast-on-disconnect (which only
    // catches outright connection death). 30s is enough to ride out
    // brief mux contention; longer than that and the peer is stuck.
    this._idleTimeout = opts.idleTimeout || 30000
  }

  // Back-compat: _peer was the first peer; expose the first peer for callers
  // that reference it (tests, diagnostics). Real tree/content requests walk
  // _peers so they survive stale DHT advertisements.
  get _peer () { return this._peers[0] || null }

  /**
   * Promote a peer to the front of our peer list after a successful
   * request. This is the key to fast multi-peer handling: once we know
   * a peer responds with real data, subsequent calls try it FIRST
   * instead of burning per-peer timeouts on dead peers every call.
   */
  _markPeerGood (peer) {
    const idx = this._peers.indexOf(peer)
    if (idx > 0) {
      this._peers.splice(idx, 1)
      this._peers.unshift(peer)
    }
  }

  async ready () {
    if (this._ready) return
    // Memoize the in-flight promise. Without this, concurrent callers
    // (e.g. server.js's fire-and-forget `fetcher.ready().then(...)` AND
    // pgh-runtime's `installTree` → `getTree` → `await this.ready()`)
    // each run `new Corestore(this._storeDir)` on the same path. The
    // device-file FDLock admits only one; the loser throws "File
    // descriptor could not be locked" and leaves `_store` in a closed
    // state, so subsequent reads fail with "Corestore is closed".
    if (this._readyPromise) return this._readyPromise
    this._readyPromise = this._doReady()
    try {
      await this._readyPromise
    } catch (err) {
      this._readyPromise = null
      throw err
    }
  }

  async _doReady () {
    if (!this._storeDir) {
      this._storeDir = fs.mkdtempSync(path.join(osTmpdir(), 'pgh-fetcher-'))
    }
    if (!this._destDir) {
      this._destDir = fs.mkdtempSync(path.join(osTmpdir(), 'pgh-fetcher-dest-'))
    }

    this._store = new Corestore(this._storeDir)
    await this._store.ready()
    this._fileIndex = new FileIndex(this._store)
    await this._fileIndex.ready()
    this._transferManager = new TransferManager(this._fileIndex)

    const stubSyncEngine = {
      _fileIndex: this._fileIndex,
      feedKey: '0'.repeat(64),
      feed: { length: 0, async get () { return null } },
      async markSynced () {},
      async logPut () {}
    }
    this._protocol = new OverlayProtocol(
      stubSyncEngine,
      this._transferManager,
      {
        key: this.topic,
        autoSync: false,
        // Fires when the client-side chunk flow finalizes a file.
        // We use it to resolve getContent promises keyed by synthetic path.
        onSynced: (info) => this._onSynced(info),
        // Fires for EVERY chunk arrival. We reset the per-pending idle
        // timer so a peer that connects then goes silent mid-stream is
        // detected within `_idleTimeout` ms (not the 5-min global cap).
        onChunkProgress: (info) => this._onChunkProgress(info)
      }
    )

    if (!this.swarm) this.swarm = new Hyperswarm()
    this.swarm.on('connection', (conn) => this._onConnection(conn))
    this.swarm.join(this.topic, { server: false, client: true })
    await this.swarm.flush()

    // Wait for at least one peer before resolving
    if (this._peers.length === 0) {
      await Promise.race([
        new Promise((resolve) => { this._peerResolve = resolve }),
        new Promise((_, reject) => setTimeout(
          () => reject(new Error('NetworkFetcher: no peer within ' + this.timeout + 'ms')),
          this.timeout
        ))
      ])
    }

    this._ready = true
  }

  _onConnection (conn) {
    const mux = Protomux.from(conn)
    const peer = this._protocol.attach(mux)
    if (!peer) return

    // Track ALL peers on the topic. The DHT may return multiple peers
    // (stale advertisements, other seeds, etc.) and only SOME have the
    // tree/content we're looking for. requestTree + requestContent
    // iterate this list until a peer returns non-empty data.
    this._peers.push(peer)

    // Connection-death handling. Without this, a peer that disconnects
    // mid-chunk-stream leaves _pendingContent entries waiting on the
    // 5-min global timeout — the user sees this as a "stall" (chunks
    // streaming, then nothing). 2026-05-13 observed:
    //   tabertron logs `deploy-server error (non-fatal) [ECONNRESET]`
    //   stortron's getContent just sits there waiting for transferComplete
    // Listen for the underlying conn close + fail any pending requests
    // that were tied to this peer. Caller retries fast on next peer.
    const handleClose = () => {
      this._peers = this._peers.filter(p => p !== peer)
      for (const pending of this._pendingContent.values()) {
        if (pending.peer === peer) {
          pending.finish(new Error('peer disconnected mid-stream (' +
            pending.contentHash.slice(0, 12) + ')'))
        }
      }
    }
    // Hyperswarm streams emit 'close' on disconnect; protomux mux also
    // emits 'close' when the underlying stream dies. Attach to both for
    // belt-and-suspenders.
    conn.on('close', handleClose)
    conn.on('error', (err) => {
      // Errors here are typically wire-level (ECONNRESET, ETIMEDOUT).
      // We don't fail-fast on error alone — wait for the matching
      // 'close' event so we don't double-fire. The on-error listener
      // exists just to keep Node from crashing.
    })

    if (this._peerResolve) { this._peerResolve(peer); this._peerResolve = null }
  }

  async close () {
    for (const pending of this._pendingContent.values()) {
      clearTimeout(pending.timer)
      pending.reject(new Error('NetworkFetcher closing'))
    }
    this._pendingContent.clear()

    if (this._protocol) {
      try { this._protocol.destroy() } catch {}
      this._protocol = null
    }
    if (this._fileIndex) { try { await this._fileIndex.close() } catch {} }
    if (this._store) { try { await this._store.close() } catch {} }
    if (this._ownSwarm && this.swarm) {
      try { await this.swarm.destroy() } catch {}
      this.swarm = null
    }
    this._ready = false
  }

  /**
   * Fetch a tree by its hash, walking all known peers until one returns
   * a non-empty response.
   *
   * hyper-overlay's `_onTreeRequest` (server side) replies with
   * `entries: []` on lookup miss. Combined with DHT promiscuity — the
   * same topic may have multiple advertised peers, some stale/unrelated,
   * some with data — a single-peer fetch is unreliable: whichever peer
   * happens to connect first might not have the tree.
   *
   * Strategy: try peers in connection order. First peer to return
   * non-empty entries wins. If all peers return empty, treat as
   * not-found (throw) — the caller knows the tree SHOULD have content
   * (it's in a lockfile) so empty is a failure signal, not a genuinely
   * empty directory.
   *
   * @param {string} hash
   * @returns {Promise<{ entries, size }>}
   */
  async getTree (hash) {
    if (!this._ready) await this.ready()
    if (this._peers.length === 0) throw new Error('NetworkFetcher: no peer available')

    // Walk peers, accept the first VERIFIED response. hyper-overlay's
    // protocol returns `entries: []` when a peer doesn't have a tree —
    // that's a valid negative response ("try elsewhere"), not "this
    // tree is empty." Content-address verification distinguishes:
    // computeTreeHash(entries) must equal the requested hash.
    let lastErr = null
    const tried = new Set()

    for (let round = 0; round < 2; round++) {
      for (const peer of this._peers) {
        if (tried.has(peer)) continue
        tried.add(peer)
        try {
          const entries = await this._protocol.requestTree(peer, hash, { timeout: this._perPeerTreeTimeout })
          const actual = computeTreeHash(entries || [])
          if (actual === hash) {
            this._markPeerGood(peer)
            const size = entries.reduce((a, e) => a + (e.size || 0), 0)
            return { entries, size }
          }
          // Hash mismatch → this peer doesn't have it. Try next.
        } catch (err) {
          lastErr = err
        }
      }
      // Second round: wait for additional peers to arrive, then retry
      // any new ones (plus the old ones if they haven't been tried yet).
      if (round === 0) {
        await new Promise(r => setTimeout(r, 2000))
        tried.clear()
      }
    }

    throw new Error('NetworkFetcher: tree ' + hash.slice(0, 12) + '… not found on any of ' + this._peers.length + ' peer(s)' + (lastErr ? ' (last err: ' + lastErr.message + ')' : ''))
  }

  /**
   * Fetch a file's content by its content hash.
   *
   * Uses the synthetic-path convention in hyper-overlay/v2 content-request:
   * server responds with chunkHashes whose `path` is
   * `"content:" + contentHash`. Client pre-registers its target disk
   * path under that key in `_filePaths` so the chunk flow writes to
   * our destination; then resolves when transferComplete arrives with
   * the matching synthetic path.
   *
   * @param {string} contentHash — hex blake2b hash of the file content
   * @returns {Promise<Buffer>}
   */
  async getContent (contentHash) {
    if (!this._ready) await this.ready()
    if (this._peers.length === 0) throw new Error('NetworkFetcher: no peer available')

    // Multi-source: fan the request out to ALL peers at once via the
    // ChunkScheduler (hyper-overlay `fetchContent`). It assigns distinct
    // chunks per peer, fails over on disconnect, and hash-verifies every
    // chunk — pulling one blob from many seeders in parallel (the torrent
    // path) instead of the legacy one-peer-at-a-time failover in
    // `_getContentFromPeer`. Proven by hyper-overlay's
    // overlay-v2-fetch.test.js ("chunks fetched from MULTIPLE peers").
    // Retry once to pick up peers that arrive late on the topic.
    const destPath = path.join(this._destDir, 'blob-' + contentHash + '-' + Date.now() + '-' + Math.random().toString(36).slice(2, 8))
    let lastErr = null

    for (let round = 0; round < 2; round++) {
      const peers = this._peers.slice()
      if (peers.length > 0) {
        try {
          await this._protocol.fetchContent(contentHash, peers, {
            destPath,
            timeout: this._perPeerContentTimeout
          })
          // The chunk flow verifies each chunk; verify the full
          // concatenation against the advertised content hash here so no
          // caller of getContent ever sees un-verified bytes.
          const data = fs.readFileSync(destPath)
          const actual = crypto.data(data).toString('hex')
          if (actual !== contentHash) {
            throw Object.assign(
              new Error('content-hash mismatch: expected ' + contentHash.slice(0, 12) + '…, got ' + actual.slice(0, 12) + '…'),
              { code: 'EHASHMISMATCH', expected: contentHash, actual }
            )
          }
          try { fs.unlinkSync(destPath) } catch {}
          return data
        } catch (err) {
          lastErr = err
          try { fs.unlinkSync(destPath) } catch {}
        }
      }
      // Wait briefly for additional peers to arrive on the topic, then retry.
      if (round === 0) await new Promise(r => setTimeout(r, 2000))
    }

    throw new Error('NetworkFetcher: content ' + contentHash.slice(0, 12) + '… not found on any of ' + this._peers.length + ' peer(s)' + (lastErr ? ' (last err: ' + lastErr.message + ')' : ''))
  }

  async _getContentFromPeer (peer, contentHash) {
    const syntheticPath = 'content:' + contentHash
    // Per-peer destPath so concurrent attempts don't clobber each other.
    const destPath = path.join(this._destDir, 'blob-' + contentHash + '-' + Date.now() + '-' + Math.random().toString(36).slice(2, 8))

    // Pre-register destination so _onChunkHashes + chunk-data handlers
    // write to the right place when chunks arrive.
    this._protocol._filePaths.set(syntheticPath, destPath)

    return new Promise((resolve, reject) => {
      let settled = false
      const finish = (err, result) => {
        if (settled) return
        settled = true
        clearTimeout(timer)
        clearTimeout(pending.idleTimer)
        this._pendingContent.delete(contentHash)
        if (err) reject(err); else resolve(result)
      }

      const timer = setTimeout(() => {
        finish(new Error('content request timed out on peer: ' + contentHash.slice(0, 12)))
      }, this._perPeerContentTimeout)

      // Silent-peer watchdog: reset on each chunk arrival via
      // _onChunkProgress. If no chunk arrives within _idleTimeout the
      // request fails fast and getContent moves on to the next peer.
      const idleFire = () => {
        finish(new Error('peer went silent mid-stream after ' +
          (pending.bytesReceived || 0) + ' byte(s): ' + contentHash.slice(0, 12)))
      }

      const pending = {
        syntheticPath, destPath, finish, timer, peer, contentHash,
        bytesReceived: 0,
        idleTimer: setTimeout(idleFire, this._idleTimeout),
        idleFire
      }

      // Tag the pending entry with the peer it was sent to. _onConnection's
      // close handler uses this to fail-fast any pending requests when the
      // connection dies (the dominant LAN-stall pattern observed
      // 2026-05-13: tabertron pushed 7 chunks, ECONNRESET, stortron sat
      // waiting on the 5-min global timeout).
      this._pendingContent.set(contentHash, pending)
      this._protocol.requestContent(peer, contentHash, null)
    })
  }

  /**
   * Reset the idle timer for any pending content request matching the
   * synthetic path of the arriving chunk. Companion to fail-fast on
   * disconnect: this fires when the peer is alive but silent.
   */
  _onChunkProgress (info) {
    if (!info || !info.path || !info.path.startsWith('content:')) return
    const contentHash = info.path.slice('content:'.length)
    const pending = this._pendingContent.get(contentHash)
    if (!pending) return
    pending.bytesReceived += (info.bytes || 0)
    clearTimeout(pending.idleTimer)
    pending.idleTimer = setTimeout(pending.idleFire, this._idleTimeout)
  }

  /**
   * Called by OverlayProtocol when a file completes on the receiver
   * side (direction === 'pull'). Resolves any pending getContent whose
   * synthetic path matches — AFTER content-address verification.
   *
   * hyper-overlay's chunk flow doesn't verify the final concatenation
   * against the advertised hash (that's the caller's responsibility in
   * this protocol). We do it here so no caller of getContent ever sees
   * un-verified bytes.
   */
  _onSynced (info) {
    if (info.direction !== 'pull') return
    if (!info.path || !info.path.startsWith('content:')) return
    const contentHash = info.path.slice('content:'.length)
    const pending = this._pendingContent.get(contentHash)
    if (!pending) return
    try {
      const data = fs.readFileSync(pending.destPath)
      const actual = crypto.data(data).toString('hex')
      if (actual !== contentHash) {
        pending.finish(Object.assign(
          new Error('content-hash mismatch: expected ' + contentHash.slice(0, 12) + '…, got ' + actual.slice(0, 12) + '…'),
          { code: 'EHASHMISMATCH', expected: contentHash, actual }
        ))
        return
      }
      pending.finish(null, data)
    } catch (err) {
      pending.finish(err)
    }
  }

  /**
   * Look up the latest release for an app name.
   *
   * MVP: reads from the LOCAL ReleaseRegistry. Remote replication of
   * the publisher's registry is follow-on work — until then, callers
   * that want network-side release lookup need to ship the registry
   * core key separately (e.g. via peer config).
   *
   * @param {string} name
   * @returns {Promise<object|null>}
   */
  async getLatestRelease (name) {
    if (!fs.existsSync(this.localRegistryDir)) return null
    const store = new Corestore(this.localRegistryDir)
    const reg = new ReleaseRegistry(store)
    try {
      await reg.ready()
      return await reg.latest(name)
    } finally {
      try { await reg.close() } catch {}
      try { await store.close() } catch {}
    }
  }
}
/**
 * ReleaseRegistry — Autobase-backed index of published releases.
 *
 * Multi-writer. Each publisher runs a registry; linked devices (or
 * explicitly added writers) all append to the same logical registry.
 * Clients replicate the registry by its bootstrap key over Hyperswarm
 * to resolve app names → tree hashes + deploy locators.
 *
 * Autobase shape (follows hyperident's IdentityRegistry pattern):
 *   - Base: autobase keyed by the first writer's hypercore
 *   - Writers: append op records (JSON-encoded)
 *   - Apply: single apply function translates ops → Hyperbee view
 *   - View: Hyperbee with the same keyspace as the earlier single-writer
 *     implementation so downstream readers (getLatest, list, etc.) don't
 *     change
 *
 * Ops:
 *   { type: 'add-release', entry }       — append a release record
 *   { type: 'remove-release', name, version }
 *   { type: 'add-writer', publicKey }    — grant another device write
 *
 * Entry schema (unchanged):
 *   name, version, treeHash, serverKey, upgrade, deps, publishedAt,
 *   publisherDevicePubkey, sig?, acceptedConflicts?
 *
 * Hyperbee view keys (unchanged):
 *   release:<name>:<version>   → entry
 *   latest:<name>              → { version, publishedAt }
 *   by-tree:<treeHash>         → { name, version }
 */

import Autobase from 'autobase'
import Hyperbee from 'hyperbee'
import crypto from 'hypercore-crypto'
import b4a from 'b4a'
import sodium from 'sodium-native'

export const OP_ADD_RELEASE = 'add-release'
export const OP_REMOVE_RELEASE = 'remove-release'
export const OP_ADD_WRITER = 'add-writer'

export class ReleaseRegistry {
  /**
   * @param {Corestore} corestore
   * @param {object} [opts]
   * @param {string} [opts.namespace='release-registry']  — corestore sub-namespace
   * @param {Buffer|string} [opts.bootstrap]              — hex or Buffer autobase key. If
   *                                                        omitted, creates a NEW registry
   *                                                        and this node becomes the
   *                                                        first writer.
   */
  constructor (corestore, opts = {}) {
    this._store = corestore.namespace(opts.namespace || 'release-registry')
    this._bootstrap = opts.bootstrap
      ? (Buffer.isBuffer(opts.bootstrap) ? opts.bootstrap : b4a.from(opts.bootstrap, 'hex'))
      : null
    this._base = null
    this._view = null
    this._ready = false
  }

  async ready () {
    if (this._ready) return

    const apply = async (nodes, view, base) => {
      for (const node of nodes) {
        let op
        try { op = JSON.parse(node.value.toString()) } catch { continue }

        if (op.type === OP_ADD_RELEASE) {
          const e = op.entry
          if (!e || !e.name || !e.version || !e.treeHash) continue
          await view.put('release:' + e.name + ':' + e.version, e)

          // Update latest pointer if this entry is newer
          const latestKey = 'latest:' + e.name
          const existing = await view.get(latestKey)
          if (!existing || compareTimestamps(e.publishedAt, existing.value.publishedAt) > 0) {
            await view.put(latestKey, { version: e.version, publishedAt: e.publishedAt })
          }

          await view.put('by-tree:' + e.treeHash, { name: e.name, version: e.version })
        }

        if (op.type === OP_REMOVE_RELEASE) {
          const key = 'release:' + op.name + ':' + op.version
          await view.del(key)
          const latestKey = 'latest:' + op.name
          const latest = await view.get(latestKey)
          if (latest && latest.value.version === op.version) {
            // Roll back to the next most recent release for this name
            let fallback = null
            const prefix = 'release:' + op.name + ':'
            for await (const e of view.createReadStream({ gt: prefix, lt: prefix + '\xff' })) {
              if (!fallback || compareTimestamps(e.value.publishedAt, fallback.publishedAt) > 0) {
                fallback = e.value
              }
            }
            if (fallback) {
              await view.put(latestKey, { version: fallback.version, publishedAt: fallback.publishedAt })
            } else {
              await view.del(latestKey)
            }
          }
        }

        if (op.type === OP_ADD_WRITER && op.publicKey) {
          try {
            await base.addWriter(b4a.from(op.publicKey, 'hex'))
          } catch {
            // autobase throws if already a writer — safe to ignore
          }
        }
      }
    }

    this._base = new Autobase(this._store, this._bootstrap, {
      apply,
      open: (store) => new Hyperbee(store.get({ name: 'releases', valueEncoding: 'json' }), {
        keyEncoding: 'utf-8',
        valueEncoding: 'json'
      }),
      valueEncoding: 'binary',
      // Canonical keet multi-writer opts. Single-writer (the common
      // publisher case) ignores these — they only matter once a publisher
      // adds a mirror/linked-device writer, at which point optimistic
      // append + periodic ack keeps the writers converging (per the keet
      // pattern in multi-writer-autobase memory). Harmless before then.
      optimistic: true,
      ackInterval: 1000,
      ackThreshold: 4
    })

    await this._base.ready()
    this._view = this._base.view
    this._ready = true
  }

  async close () {
    if (this._base) await this._base.close()
    this._ready = false
  }

  // ── Keys / identity ─────────────────────────────────────────

  get key () { return this._base && this._base.key }
  get keyHex () {
    const k = this.key
    return k ? b4a.toString(k, 'hex') : null
  }
  get localWriterKey () {
    return this._base && this._base.local && this._base.local.key
  }
  get isWriter () {
    return !!(this._base && this._base.writable)
  }

  // ── Ops (writer-only) ────────────────────────────────────────

  async add (entry) {
    if (!this._ready) await this.ready()
    if (!this.isWriter) throw new Error('not a writer on this registry')
    if (!entry || !entry.name || !entry.version || !entry.treeHash) {
      throw new Error('release entry requires name, version, treeHash')
    }

    const normalized = {
      name: entry.name,
      version: entry.version,
      // runtime drives the materializer (node vs godot vs bare→node alias)
      // and the launcher shebang at install time. Drop-on-store would
      // make installers fall back to 'node' and produce wrong launchers
      // (e.g. `exec node` for a bare app → require.addon throws).
      runtime: entry.runtime || 'node',
      treeHash: entry.treeHash,
      serverKey: entry.serverKey || null,
      upgrade: entry.upgrade || null,
      deps: entry.deps || [],
      publishedAt: entry.publishedAt || new Date().toISOString(),
      publisherDevicePubkey: entry.publisherDevicePubkey || null,
      // MUST be carried: `sig` covers every field except itself, so a field
      // dropped here is a field the stored entry no longer hashes to and the
      // signature stops verifying. Anything added to the signed entry has to
      // be added to this list too (org #144).
      publisherChain: entry.publisherChain || null,
      sig: entry.sig || null,
      acceptedConflicts: entry.acceptedConflicts || null
    }

    await this._base.append(JSON.stringify({ type: OP_ADD_RELEASE, entry: normalized }))
    await this._base.update()
    return normalized
  }

  async remove (name, version) {
    if (!this._ready) await this.ready()
    if (!this.isWriter) throw new Error('not a writer on this registry')
    await this._base.append(JSON.stringify({ type: OP_REMOVE_RELEASE, name, version }))
    await this._base.update()
  }

  async addWriter (publicKey) {
    if (!this._ready) await this.ready()
    if (!this.isWriter) throw new Error('not a writer on this registry')
    const hex = Buffer.isBuffer(publicKey) ? publicKey.toString('hex') : publicKey
    await this._base.append(JSON.stringify({ type: OP_ADD_WRITER, publicKey: hex }))
    await this._base.update()
  }

  // ── Queries (readable by anyone with the registry key) ───────

  async get (name, version) {
    if (!this._ready) await this.ready()
    const entry = await this._view.get('release:' + name + ':' + version)
    if (!entry) return null
    assertEntryIntegrity(entry.value)
    return entry.value
  }

  async latest (name) {
    if (!this._ready) await this.ready()
    const latest = await this._view.get('latest:' + name)
    if (!latest) return null
    return this.get(name, latest.value.version)
  }

  async lookupByTree (treeHash) {
    if (!this._ready) await this.ready()
    const ref = await this._view.get('by-tree:' + treeHash)
    if (!ref) return null
    return this.get(ref.value.name, ref.value.version)
  }

  async list (nameFilter) {
    if (!this._ready) await this.ready()
    const prefix = nameFilter ? 'release:' + nameFilter + ':' : 'release:'
    const out = []
    for await (const entry of this._view.createReadStream({ gt: prefix, lt: prefix + '\xff' })) {
      out.push(entry.value)
    }
    return out
  }

  // ── Replication handle ───────────────────────────────────────

  replicate (stream) {
    return this._base.replicate(stream)
  }

  /**
   * Pull updates from the network (call after the underlying cores
   * have replicated new blocks).
   */
  async update () {
    if (!this._ready) await this.ready()
    return this._base.update()
  }
}

// ── Canonical signing (unchanged) ──────────────────────────────

export function canonicalBytes (entry) {
  const { sig, ...rest } = entry // eslint-disable-line no-unused-vars
  const keys = Object.keys(rest).sort()
  const ordered = {}
  for (const k of keys) ordered[k] = rest[k]
  return Buffer.from(JSON.stringify(ordered))
}

export function signEntry (entry, secretKey) {
  const sig = Buffer.alloc(64)
  sodium.crypto_sign_detached(sig, canonicalBytes(entry), secretKey)
  return { ...entry, sig: sig.toString('hex') }
}

/**
 * Verify a release entry's signature against the device key it names.
 *
 * Transitional by design (org #144): an entry with NO `sig` passes. Every
 * release published before signing was wired carries `sig: null`, and
 * refusing those would make every installed app un-updatable and every
 * existing release uninstallable. What this closes is the case that actually
 * matters now — an entry that carries a signature which does not verify.
 *
 * Enforcement (refuse unsigned) is a later flip, once publishers have
 * re-published. Until then this is a tamper check, not an authenticity
 * guarantee: an attacker who can write to the registry can still simply omit
 * the signature.
 *
 * @returns {{ ok: boolean, signed: boolean, reason?: string }}
 */
export function verifyReleaseEntry (entry) {
  if (!entry) return { ok: false, signed: false, reason: 'no entry' }
  if (!entry.sig) return { ok: true, signed: false }

  const pubkey = entry.publisherDevicePubkey
  if (!pubkey) {
    return { ok: false, signed: true, reason: 'entry is signed but names no publisherDevicePubkey' }
  }

  let ok = false
  try {
    ok = verifyEntry(entry, pubkey)
  } catch (err) {
    return { ok: false, signed: true, reason: 'signature check threw: ' + err.message }
  }
  if (!ok) {
    return {
      ok: false,
      signed: true,
      reason: 'signature does not verify against publisherDevicePubkey ' + String(pubkey).slice(0, 12) + '…'
    }
  }
  return { ok: true, signed: true }
}

/**
 * Throwing form, used on every read path so no call site can forget it. A
 * signed entry that fails verification is not a release, it is a tamper — and
 * a loud failure degrades to "not found" in callers that catch, which is the
 * safe direction.
 */
export function assertEntryIntegrity (entry) {
  const v = verifyReleaseEntry(entry)
  if (!v.ok) {
    throw Object.assign(
      new Error(
        'release ' + (entry && entry.name) + '@' + (entry && entry.version) +
        ' failed verification: ' + v.reason
      ),
      { code: 'EBADRELEASESIG', entry }
    )
  }
  return entry
}

export function verifyEntry (entry, publisherPublicKey) {
  if (!entry.sig) return false
  const sig = b4a.from(entry.sig, 'hex')
  const pubkey = Buffer.isBuffer(publisherPublicKey)
    ? publisherPublicKey
    : b4a.from(publisherPublicKey, 'hex')
  return sodium.crypto_sign_verify_detached(sig, canonicalBytes(entry), pubkey)
}

function compareTimestamps (a, b) {
  if (a === b) return 0
  return a > b ? 1 : -1
}
/**
 * resolveRelease — "what is the latest release of <name>?", with or without a
 * pgh-sidecar on this machine.
 *
 * Extracted verbatim in behaviour from commands/app.js, where it was the install
 * path's private helper. It is here because it is the missing half of embedded
 * OTA: NetworkFetcher's own header says
 *
 *     getLatestRelease currently reads from the LOCAL ReleaseRegistry.
 *     Replication of the publisher's remote registry is a follow-on.
 *
 * and that follow-on turned out to already exist — as this function, reachable
 * only from `pgh app install`. A standalone app (no sidecar, no CLI) could fetch
 * trees and content over Hyperswarm but had no way to learn WHICH tree to fetch.
 *
 * TWO ORDERED PATHS, and the order is not a preference:
 *
 *   1. the sidecar's live replica, when ~/.pgh/svc.sock exists;
 *   2. otherwise replicate the publisher's registry directly by its bootstrap
 *      key, over Hyperswarm.
 *
 * The sidecar goes first because BOTH paths open the same
 * ~/.config/pgh/registries/<key16> Corestore, and that store takes an EXCLUSIVE
 * FD-LOCK. On a machine where the sidecar is also re-opening it (its in-process
 * autoupdate does), a direct open loses the race and dies with "File descriptor
 * could not be locked". runtime-factory's createRuntime routes getLatestRelease
 * through the sidecar for exactly this reason. Path 2 is for machines that have
 * no sidecar at all — which is every standalone install, and every Windows one.
 *
 * THE CALLER OWNS THE CLEANUP. `cleanup()` closes registry, swarm AND store, in
 * that order. ReleaseRegistry.close() closes only the autobase, so dropping the
 * handle without calling this orphans the store's fd-lock for the life of the
 * process and every later resolve in it fails.
 */

import process from '#node:process' // NOT a global under bare — process.env below needs it
import fs from '#node:fs'
import path from '#node:path'
import { homedir } from '#node:os'
import b4a from 'b4a'
import { Client } from 'hyper-svc'

import { ReleaseRegistry } from './release-registry.js'

const SIDECAR_SOCK = process.env.PGH_SIDECAR_SOCK ||
  path.join(homedir(), '.pgh', 'svc.sock')

/** Where a directly-replicated registry's corestore lives. */
export function registryStoreDir (registryKeyHex) {
  return path.join(homedir(), '.config', 'pgh', 'registries', registryKeyHex.slice(0, 16))
}

/**
 * @param {object} opts
 * @param {string} opts.registryKeyHex  64-char registry (autobase bootstrap) key
 * @param {string} opts.name            app name
 * @param {string} [opts.version]       exact version; omitted = latest
 * @param {boolean} [opts.preferSidecar=true]  try the sidecar's replica first
 * @param {number} [opts.settleMs=500]  post-flush settle before reading the view
 * @param {string} [opts.storeDir]      where to keep the registry replica. Defaults to a path under
 *   the home directory, which does not exist on Android — an embedder must pass its own.
 * @returns {Promise<{ entry: object|null, via: string, cleanup: function }>}
 */
export async function resolveRelease (opts = {}) {
  const { registryKeyHex, name, version } = opts
  if (!registryKeyHex || registryKeyHex.length !== 64) {
    throw new Error('resolveRelease requires a 64-char registryKeyHex')
  }
  if (!name) throw new Error('resolveRelease requires a name')

  const preferSidecar = opts.preferSidecar !== false
  const settleMs = opts.settleMs != null ? opts.settleMs : 500

  const noop = async () => {}
  let entry = null

  if (preferSidecar && fs.existsSync(SIDECAR_SOCK)) {
    let c = null
    try {
      c = await Client.connectUds(SIDECAR_SOCK)
      const res = await c.call('resolve-release', {
        registryKey: registryKeyHex, name, version: version || undefined
      })
      if (res && res.found && res.entry) entry = res.entry
    } catch {
      // Sidecar present but unhelpful (down mid-restart, older build without the
      // RPC). Fall through and replicate directly — worst case that fails on the
      // fd-lock, which is a clearer error than a silent miss.
    } finally {
      try { if (c) await c.close() } catch {}
    }
    if (entry) return { entry, via: 'sidecar', cleanup: noop }
  }

  const Corestore = (await import('corestore')).default
  const Hyperswarm = (await import('hyperswarm')).default

  let store = null
  let registry = null
  let swarm = null
  const cleanup = async () => {
    try { if (registry) await registry.close() } catch {}
    try { if (swarm) await swarm.destroy() } catch {}
    try { if (store) await store.close() } catch {}
  }

  // ⛔ CALLER-SUPPLIED OR THE DEFAULT, because the default assumes a HOME DIRECTORY and a phone has
  // none. On Android this resolved to a path that cannot be stat'd, so `resolveRelease` threw
  // ENOENT, `swarmFetcher` caught it, and OTA reported "no swarm fetcher — updates disabled this
  // boot" — a handset that could never update, with the reason visible nowhere until the app was
  // taught to report its own last OTA line.
  //
  // ⚠ Same class as a binary assumed on PATH and a vault assumed under ~: a library that picks a
  // path from the environment works everywhere the environment has one. An embedder knows where its
  // state goes; ask it.
  const dir = opts.storeDir || registryStoreDir(registryKeyHex)
  fs.mkdirSync(dir, { recursive: true })
  store = new Corestore(dir)
  try {
    registry = new ReleaseRegistry(store, { bootstrap: b4a.from(registryKeyHex, 'hex') })
    await registry.ready()
    swarm = new Hyperswarm()
    swarm.on('connection', (conn) => store.replicate(conn))
    // client-only: we are reading someone else's registry, not serving ours.
    swarm.join(registry._base.discoveryKey, { server: false, client: true })
    await swarm.flush()
    // The view is built by autobase's apply as blocks arrive; flush returns when
    // peers are connected, not when the log has caught up.
    await new Promise(r => setTimeout(r, settleMs))
    await registry.update()
    entry = version ? await registry.get(name, version) : await registry.latest(name)
  } catch (err) {
    await cleanup()
    throw err
  }

  return { entry, via: 'replica', cleanup }
}

/**
 * A `getLatestRelease(name)` for pgh-runtime's fetcher shape, backed by the above.
 *
 * pgh-runtime polls, so this opens and CLOSES per call rather than holding the
 * store's fd-lock for the life of the app: an app that kept it would block the
 * sidecar, `pgh app install`, and its own next resolve. Polling is hourly by
 * default, so the reconnect cost is irrelevant beside that.
 */
/**
 * WATCH a registry for releases of one app, instead of asking it repeatedly.
 *
 * ⛔ WHY THIS EXISTS. `resolveRelease` opens a Corestore and a Hyperswarm, reads, and tears both
 * down — so nothing survives to emit anything, and every caller is forced to poll. Worse, a one-shot
 * read has to GUESS how long replication takes: the code above waits `settleMs` because, in its own
 * words, "flush returns when peers are connected, not when the log has caught up". That guess was
 * 500ms, which is correct for a warm replica and far too short for a cold one — measured on a
 * handset as `resolveRelease` returning null and OTA reporting "no published release with a
 * serverKey", which reads like a publishing failure and is not.
 *
 * ★ A held replica has no settle to guess. The view is built by autobase's apply as blocks arrive,
 * and autobase emits `update` when it does — so you are TOLD when the data lands, however long it
 * takes. That removes the entire class of "you did not wait long enough", rather than retuning it.
 *
 * Event-driven plus reconciliation, the same shape hyper-social #68 §2 landed for delivery: the
 * event sets the latency floor, and the initial read after flush is the reconciliation that covers
 * a replica which was already caught up before anyone subscribed.
 *
 * @returns {{ close: function, latest: function }} `latest()` is the last entry seen, or null.
 */
export async function watchLatestRelease (opts = {}) {
  const { registryKeyHex, name, onRelease = () => {} } = opts
  if (!registryKeyHex || registryKeyHex.length !== 64) {
    throw new Error('watchLatestRelease requires a 64-char registryKeyHex')
  }
  if (!name) throw new Error('watchLatestRelease requires a name')

  const Corestore = (await import('corestore')).default
  const Hyperswarm = (await import('hyperswarm')).default

  const dir = opts.storeDir || registryStoreDir(registryKeyHex)
  fs.mkdirSync(dir, { recursive: true })

  const store = new Corestore(dir)
  const registry = new ReleaseRegistry(store, { bootstrap: b4a.from(registryKeyHex, 'hex') })
  await registry.ready()

  const swarm = new Hyperswarm()
  swarm.on('connection', (conn) => store.replicate(conn))
  // client-only: we are reading someone else's registry, not serving ours.
  swarm.join(registry._base.discoveryKey, { server: false, client: true })

  let last = null
  let closed = false

  // ⚠ Reports only CHANGES. A view can update many times while one release replicates, and a caller
  // that rebuilt a fetcher on every tick would thrash for no reason.
  const reread = async () => {
    if (closed) return
    try {
      await registry.update()
      const entry = await registry.latest(name)
      if (!entry) return
      if (last && last.treeHash === entry.treeHash) return
      last = entry
      await onRelease(entry)
    } catch { /* a registry that cannot be read right now is not an error; the next update retries */ }
  }

  registry._base.on('update', () => { reread().catch(() => {}) })

  // Reconciliation: a replica already caught up before we subscribed emits nothing, so read once.
  // NOT awaited on the swarm — `flush()` can take as long as a DHT lookup, and a caller must not
  // block boot on it. The `update` event covers whatever arrives afterwards.
  swarm.flush().then(reread).catch(() => {})
  await reread()

  return {
    latest: () => last,
    close: async () => {
      closed = true
      try { registry._base.removeAllListeners('update') } catch {}
      // ⛔ CLOSE WHAT WE OPENED, all of it. A swarm left running is a DHT node and a set of sockets
      // held awake by something the user switched off — the same leak shape that reached ~205k
      // sockets on stortron because the thing that created a handle was not the thing that owned it.
      try { await swarm.destroy() } catch {}
      try { await registry.close() } catch {}
      try { await store.close() } catch {}
    }
  }
}

export function makeGetLatestRelease ({ registryKeyHex, preferSidecar, settleMs, storeDir, _resolve = resolveRelease } = {}) {
  // ⛔ SINGLE-FLIGHT, BECAUSE THE STORE'S LOCK IS EXCLUSIVE. Each call opens a Corestore on the same
  // `storeDir`, and RocksDB admits one holder — so two OVERLAPPING calls mean the second throws
  // "File descriptor could not be locked" and the caller sees an OTA error rather than the
  // double-open it is.
  //
  // Measured on a handset 2026-09-15, after an OTA staged a release: the release watch fired and the
  // settings page asked for update status, and those overlap by construction.
  //
  // ★ The fix already existed one layer down and said why — NetworkFetcher.ready(): "Memoize the
  // in-flight promise. Without this, concurrent callers … each run new Corestore(this._storeDir) on
  // the same path. The device-file FDLock admits only one; the loser throws …". The resolver above it
  // never got the same treatment.
  //
  // ⛔ THE IN-FLIGHT PROMISE, NEVER THE RESULT. A cached entry would go stale and a poller would stop
  // seeing new releases — the opposite failure, and a worse one because it is silent. The map entry is
  // deleted as soon as the call settles, including when it throws: memoising a failure would poison
  // every later call from one transient swarm miss.
  //
  // ⚠ Keyed by NAME. Two different apps resolve different entries and must not block each other, even
  // though they share a store — the lock is held only for the length of one resolve either way.
  const inFlight = new Map()

  return async function getLatestRelease (name) {
    const pending = inFlight.get(name)
    if (pending) return pending

    const p = (async () => {
      const { entry, cleanup } = await _resolve({
        registryKeyHex, name, preferSidecar, settleMs, storeDir
      })
      try { return entry } finally { await cleanup() }
    })()

    inFlight.set(name, p)
    try {
      return await p
    } finally {
      inFlight.delete(name)
    }
  }
}
const { Pull, Push, HEADERBYTES, KEYBYTES, ABYTES } = require('sodium-secretstream')
const sodium = require('sodium-universal')
const crypto = require('hypercore-crypto')
const { Duplex, Writable, getStreamError } = require('streamx')
const b4a = require('b4a')
const Timeout = require('timeout-refresh')
const unslab = require('unslab')
const Bridge = require('./lib/bridge')
const Handshake = require('./lib/handshake')

const IDHEADERBYTES = HEADERBYTES + 32
const [NS_INITIATOR, NS_RESPONDER, NS_SEND] = crypto.namespace('hyperswarm/secret-stream', 3)
const MAX_ATOMIC_WRITE = 256 * 256 * 256 - 1

module.exports = class NoiseSecretStream extends Duplex {
  constructor(isInitiator, rawStream, opts = {}) {
    super({ mapWritable: toBuffer })

    if (typeof isInitiator !== 'boolean') {
      throw new Error('isInitiator should be a boolean')
    }

    this.noiseStream = this
    this.isInitiator = isInitiator
    this.rawStream = null

    this.publicKey = opts.publicKey || null
    this.remotePublicKey = opts.remotePublicKey || null
    this.handshakeHash = null
    this.connected = false
    this.keepAlive = opts.keepAlive || 0
    this.timeout = 0
    this.enableSend = opts.enableSend !== false

    // pointer for upstream to set data here if they want
    this.userData = null

    let openedDone = null
    this.opened = new Promise((resolve) => {
      openedDone = resolve
    })

    this.rawBytesWritten = 0
    this.rawBytesRead = 0

    // metadata used by 'hyperdht'
    this.relay = null
    this.puncher = null

    // unwrapped raw stream
    this._rawStream = null

    // handshake state
    this._handshake = null
    this._handshakePattern = opts.pattern || null
    this._handshakeDone = null

    // message parsing state
    this._state = 0
    this._len = 0
    this._tmp = 1
    this._message = null

    this._openedDone = openedDone
    this._startDone = null
    this._drainDone = null
    this._outgoingPlain = null
    this._outgoingWrapped = null
    this._utp = null
    this._setup = true
    this._ended = 2
    this._encrypt = null
    this._decrypt = null
    this._timeoutTimer = null
    this._keepAliveTimer = null
    this._sendState = null

    if (opts.autoStart !== false) this.start(rawStream, opts)

    // wiggle it to trigger open immediately (TODO add streamx option for this)
    this.resume()
    this.pause()
  }

  static keyPair(seed) {
    return Handshake.keyPair(seed)
  }

  static id(handshakeHash, isInitiator, id) {
    return streamId(handshakeHash, isInitiator, id)
  }

  setTimeout(ms) {
    if (!ms) ms = 0

    this._clearTimeout()
    this.timeout = ms

    if (!ms || this.rawStream === null) return

    this._timeoutTimer = Timeout.once(ms, destroyTimeout, this)
    this._timeoutTimer.unref()
  }

  setKeepAlive(ms) {
    if (!ms) ms = 0

    this._clearKeepAlive()

    this.keepAlive = ms

    if (!ms || this.rawStream === null) return

    this._keepAliveTimer = Timeout.on(ms, sendKeepAlive, this)
    this._keepAliveTimer.unref()
  }

  sendKeepAlive() {
    const empty = this.alloc(0)
    this.write(empty)
  }

  start(rawStream, opts = {}) {
    if (rawStream) {
      this.rawStream = rawStream
      this._rawStream = rawStream
      if (typeof this.rawStream.setContentSize === 'function') {
        this._utp = rawStream
      }
    } else {
      this.rawStream = new Bridge(this)
      this._rawStream = this.rawStream.reverse
    }

    this.rawStream.on('error', this._onrawerror.bind(this))
    this.rawStream.on('close', this._onrawclose.bind(this))

    this._startHandshake(opts.handshake, opts.keyPair || null)
    this._continueOpen(null)

    if (this.destroying) return

    if (opts.data) this._onrawdata(opts.data)
    if (opts.ended) this._onrawend()

    if (this.keepAlive > 0 && this._keepAliveTimer === null) {
      this.setKeepAlive(this.keepAlive)
    }

    if (this.timeout > 0 && this._timeoutTimer === null) {
      this.setTimeout(this.timeout)
    }
  }

  async flush() {
    if ((await this.opened) === false) return false
    if ((await Writable.drained(this)) === false) return false
    if (this.destroying) return false

    if (this.rawStream !== null && this.rawStream.flush) {
      return await this.rawStream.flush()
    }

    return true
  }

  _continueOpen(err) {
    if (err) this.destroy(err)
    if (this._startDone === null) return
    const done = this._startDone
    this._startDone = null
    this._open(done)
  }

  _onkeypairpromise(p) {
    const self = this
    const cont = this._continueOpen.bind(this)

    p.then(onkeypair, cont)

    function onkeypair(kp) {
      self._onkeypair(kp)
      cont(null)
    }
  }

  _onkeypair(keyPair) {
    const pattern = this._handshakePattern || 'XX'
    const remotePublicKey = this.remotePublicKey

    this._handshake = new Handshake(this.isInitiator, keyPair, remotePublicKey, pattern)
    this.publicKey = this._handshake.keyPair.publicKey
  }

  _startHandshake(handshake, keyPair) {
    if (handshake) {
      const { tx, rx, hash, publicKey, remotePublicKey } = handshake
      this._setupSecretStream(tx, rx, hash, publicKey, remotePublicKey)
      return
    }

    if (!keyPair) keyPair = Handshake.keyPair()

    if (typeof keyPair.then === 'function') {
      this._onkeypairpromise(keyPair)
    } else {
      this._onkeypair(keyPair)
    }
  }

  _onrawerror(err) {
    this.destroy(err)
  }

  _onrawclose() {
    if (this._ended !== 0) this.destroy()
  }

  _onrawdata(data) {
    let offset = 0

    if (this._timeoutTimer !== null) {
      this._timeoutTimer.refresh()
    }

    do {
      switch (this._state) {
        case 0: {
          while (this._tmp !== 0x1000000 && offset < data.byteLength) {
            const v = data[offset++]
            this._len += this._tmp * v
            this._tmp *= 256
          }

          if (this._tmp === 0x1000000) {
            this._tmp = 0
            this._state = 1
            const unprocessed = data.byteLength - offset
            if (unprocessed < this._len && this._utp !== null)
              this._utp.setContentSize(this._len - unprocessed)
          }

          break
        }

        case 1: {
          const missing = this._len - this._tmp
          const end = missing + offset

          if (this._message === null && end <= data.byteLength) {
            this._message = data.subarray(offset, end)
            offset += missing
            this._incoming()
            break
          }

          const unprocessed = data.byteLength - offset

          if (this._message === null) {
            this._message = b4a.allocUnsafe(this._len)
          }

          b4a.copy(data, this._message, this._tmp, offset)
          this._tmp += unprocessed

          if (end <= data.byteLength) {
            offset += missing
            this._incoming()
          } else {
            offset += unprocessed
          }

          break
        }
      }
    } while (offset < data.byteLength && !this.destroying)
  }

  _onrawend() {
    this._ended--
    this.push(null)
  }

  _onrawdrain() {
    const drain = this._drainDone
    if (drain === null) return
    this._drainDone = null
    drain()
  }

  _read(cb) {
    this.rawStream.resume()
    cb(null)
  }

  _incoming() {
    const message = this._message

    this._state = 0
    this._len = 0
    this._tmp = 1
    this._message = null

    if (this._setup === true) {
      if (this._handshake) {
        this._onhandshakert(this._handshake.recv(message))
      } else {
        if (message.byteLength !== IDHEADERBYTES) {
          this.destroy(new Error('Invalid header message received'))
          return
        }

        const remoteId = message.subarray(0, 32)
        const expectedId = streamId(this.handshakeHash, !this.isInitiator)
        const header = message.subarray(32)

        if (!b4a.equals(expectedId, remoteId)) {
          this.destroy(new Error('Invalid header received'))
          return
        }

        this._decrypt.init(header)
        this._setup = false // setup is now done
      }
      return
    }

    if (message.byteLength < ABYTES) {
      this.destroy(new Error('Invalid message received'))
      return
    }

    this.rawBytesRead += message.byteLength

    const plain = message.subarray(1, message.byteLength - ABYTES + 1)

    try {
      this._decrypt.next(message, plain)
    } catch (err) {
      this.destroy(err)
      return
    }

    // If keep alive is selective, eat the empty buffers (ie assume the other side has it enabled also)
    if (plain.byteLength === 0 && this.keepAlive !== 0) return

    if (this.push(plain) === false) {
      this.rawStream.pause()
    }
  }

  _onhandshakert(h) {
    if (this._handshakeDone === null) return

    if (h !== null) {
      if (h.data) this._rawStream.write(h.data)
      if (!h.tx) return
    }

    const done = this._handshakeDone
    const publicKey = this._handshake.keyPair.publicKey

    this._handshakeDone = null
    this._handshake = null

    if (h === null) return done(new Error('Noise handshake failed'))

    this._setupSecretStream(h.tx, h.rx, h.hash, publicKey, h.remotePublicKey)
    this._resolveOpened(true)
    done(null)
  }

  _setupSecretStream(tx, rx, handshakeHash, publicKey, remotePublicKey) {
    const buf = b4a.allocUnsafeSlow(3 + IDHEADERBYTES)
    writeUint24le(IDHEADERBYTES, buf)

    this._encrypt = new Push(unslab(tx.subarray(0, KEYBYTES)), undefined, buf.subarray(3 + 32))
    this._decrypt = new Pull(unslab(rx.subarray(0, KEYBYTES)))

    this.publicKey = publicKey
    this.remotePublicKey = remotePublicKey
    this.handshakeHash = handshakeHash

    const id = buf.subarray(3, 3 + 32)
    streamId(handshakeHash, this.isInitiator, id)

    // initialize secretbox state for unordered messages
    this._setupSecretSend(handshakeHash)

    this.emit('handshake')
    // if rawStream is a bridge, also emit it there
    if (this.rawStream !== this._rawStream) this.rawStream.emit('handshake')

    if (this.destroying) return

    this._rawStream.write(buf)
  }

  _setupSecretSend(handshakeHash) {
    this._sendState = b4a.allocUnsafeSlow(32 + 32 + 8 + 8)
    const encrypt = this._sendState.subarray(0, 32) // secrets
    const decrypt = this._sendState.subarray(32, 64)
    const counter = this._sendState.subarray(64, 72) // nonce
    const initial = this._sendState.subarray(72)

    const inputs = this.isInitiator
      ? [
          [NS_INITIATOR, NS_SEND],
          [NS_RESPONDER, NS_SEND]
        ]
      : [
          [NS_RESPONDER, NS_SEND],
          [NS_INITIATOR, NS_SEND]
        ]

    sodium.crypto_generichash_batch(encrypt, inputs[0], handshakeHash)
    sodium.crypto_generichash_batch(decrypt, inputs[1], handshakeHash)

    sodium.randombytes_buf(initial)
    counter.set(initial)
  }

  _open(cb) {
    // no autostart or no handshake yet
    if (this._rawStream === null || (this._handshake === null && this._encrypt === null)) {
      this._startDone = cb
      return
    }

    this._rawStream.on('data', this._onrawdata.bind(this))
    this._rawStream.on('end', this._onrawend.bind(this))
    this._rawStream.on('drain', this._onrawdrain.bind(this))

    if (this.enableSend) this._rawStream.on('message', this._onmessage.bind(this))

    if (this._encrypt !== null) {
      this._resolveOpened(true)
      return cb(null)
    }

    this._handshakeDone = cb

    if (this.isInitiator) this._onhandshakert(this._handshake.send())
  }

  _predestroy() {
    if (this.rawStream) {
      const error = getStreamError(this)
      this.rawStream.destroy(error)
    }

    if (this._startDone !== null) {
      const done = this._startDone
      this._startDone = null
      done(new Error('Stream destroyed'))
    }

    if (this._handshakeDone !== null) {
      const done = this._handshakeDone
      this._handshakeDone = null
      done(new Error('Stream destroyed'))
    }

    if (this._drainDone !== null) {
      const done = this._drainDone
      this._drainDone = null
      done(new Error('Stream destroyed'))
    }
  }

  _write(data, cb) {
    let wrapped = this._outgoingWrapped

    if (data !== this._outgoingPlain) {
      wrapped = b4a.allocUnsafe(data.byteLength + 3 + ABYTES)
      wrapped.set(data, 4)
    } else {
      this._outgoingWrapped = this._outgoingPlain = null
    }

    if (wrapped.byteLength - 3 > MAX_ATOMIC_WRITE) {
      return cb(
        new Error(
          'Message is too large for an atomic write. Max size is ' + MAX_ATOMIC_WRITE + ' bytes.'
        )
      )
    }
    this.rawBytesWritten += wrapped.byteLength

    writeUint24le(wrapped.byteLength - 3, wrapped)
    // offset 4 so we can do it in-place
    this._encrypt.next(wrapped.subarray(4, 4 + data.byteLength), wrapped.subarray(3))

    if (this._keepAliveTimer !== null) this._keepAliveTimer.refresh()

    if (this._rawStream.write(wrapped) === false) {
      this._drainDone = cb
    } else {
      cb(null)
    }
  }

  _final(cb) {
    this._clearKeepAlive()
    this._ended--
    this._rawStream.end()
    cb(null)
  }

  _resolveOpened(val) {
    if (this._openedDone === null) return
    const opened = this._openedDone
    this._openedDone = null
    opened(val)
    if (!val) return
    this.connected = true
    this.emit('connect')
  }

  _clearTimeout() {
    if (this._timeoutTimer === null) return
    this._timeoutTimer.destroy()
    this._timeoutTimer = null
    this.timeout = 0
  }

  _clearKeepAlive() {
    if (this._keepAliveTimer === null) return
    this._keepAliveTimer.destroy()
    this._keepAliveTimer = null
    this.keepAlive = 0
  }

  _destroy(cb) {
    this._clearKeepAlive()
    this._clearTimeout()
    this._resolveOpened(false)
    cb(null)
  }

  _boxMessage(buffer) {
    const MB = sodium.crypto_secretbox_MACBYTES // 16
    const NB = sodium.crypto_secretbox_NONCEBYTES // 24

    const counter = this._sendState.subarray(64, 72)
    sodium.sodium_increment(counter)
    if (b4a.equals(counter, this._sendState.subarray(72))) {
      this.destroy(new Error('udp send nonce exchausted'))
      return
    }

    const secret = this._sendState.subarray(0, 32)
    const envelope = b4a.allocUnsafe(8 + MB + buffer.byteLength)
    const nonce = envelope.subarray(0, NB)
    const ciphertext = envelope.subarray(8)

    b4a.fill(nonce, 0) // pad suffix
    nonce.set(counter)

    sodium.crypto_secretbox_easy(ciphertext, buffer, nonce, secret)
    return envelope
  }

  send(buffer) {
    if (!this._sendState) return
    if (!this.rawStream?.send) return // udx-stream expected

    const message = this._boxMessage(buffer)
    return this.rawStream.send(message)
  }

  trySend(buffer) {
    if (!this._sendState) return
    if (!this.rawStream?.trySend) return // udx-stream expected

    const message = this._boxMessage(buffer)
    this.rawStream.trySend(message)
  }

  _onmessage(buffer) {
    if (!this._sendState) return // messages before handshake are dropped

    const MB = sodium.crypto_secretbox_MACBYTES // 16
    const NB = sodium.crypto_secretbox_NONCEBYTES // 24

    if (buffer.byteLength < NB) return // Invalid message

    const nonce = b4a.allocUnsafe(NB)
    b4a.fill(nonce, 0)
    nonce.set(buffer.subarray(0, 8))

    const secret = this._sendState.subarray(32, 64)
    const ciphertext = buffer.subarray(8)
    const plain = buffer.subarray(8, buffer.byteLength - MB)

    if (ciphertext.byteLength < MB) return // invalid message

    const success = sodium.crypto_secretbox_open_easy(plain, ciphertext, nonce, secret)

    if (success) this.emit('message', plain)
  }

  alloc(len) {
    const buf = b4a.allocUnsafe(len + 3 + ABYTES)
    this._outgoingWrapped = buf
    this._outgoingPlain = buf.subarray(4, buf.byteLength - ABYTES + 1)
    return this._outgoingPlain
  }

  toJSON() {
    return {
      isInitiator: this.isInitiator,
      publicKey: this.publicKey && b4a.toString(this.publicKey, 'hex'),
      remotePublicKey: this.remotePublicKey && b4a.toString(this.remotePublicKey, 'hex'),
      connected: this.connected,
      destroying: this.destroying,
      destroyed: this.destroyed,
      rawStream: this.rawStream && this.rawStream.toJSON ? this.rawStream.toJSON() : null
    }
  }
}

function writeUint24le(n, buf) {
  buf[0] = n & 255
  buf[1] = (n >>> 8) & 255
  buf[2] = (n >>> 16) & 255
}

function streamId(handshakeHash, isInitiator, out = b4a.allocUnsafe(32)) {
  sodium.crypto_generichash(out, isInitiator ? NS_INITIATOR : NS_RESPONDER, handshakeHash)
  return out
}

function toBuffer(data) {
  return typeof data === 'string' ? b4a.from(data) : data
}

function destroyTimeout() {
  this.destroy(new Error('Stream timed out'))
}

function sendKeepAlive() {
  const empty = this.alloc(0)
  this.write(empty)
}
const { Duplex, Writable } = require('streamx')

class ReversePassThrough extends Duplex {
  constructor(s) {
    super()
    this._stream = s
    this._ondrain = null
  }

  _write(data, cb) {
    if (this._stream.push(data) === false) {
      this._stream._ondrain = cb
    } else {
      cb(null)
    }
  }

  _final(cb) {
    this._stream.push(null)
    cb(null)
  }

  _read(cb) {
    const ondrain = this._ondrain
    this._ondrain = null
    if (ondrain) ondrain()
    cb(null)
  }
}

module.exports = class Bridge extends Duplex {
  constructor(noiseStream) {
    super()

    this.noiseStream = noiseStream

    this._ondrain = null
    this.reverse = new ReversePassThrough(this)
  }

  get publicKey() {
    return this.noiseStream.publicKey
  }

  get remotePublicKey() {
    return this.noiseStream.remotePublicKey
  }

  get handshakeHash() {
    return this.noiseStream.handshakeHash
  }

  flush() {
    return Writable.drained(this)
  }

  _read(cb) {
    const ondrain = this._ondrain
    this._ondrain = null
    if (ondrain) ondrain()
    cb(null)
  }

  _write(data, cb) {
    if (this.reverse.push(data) === false) {
      this.reverse._ondrain = cb
    } else {
      cb(null)
    }
  }

  _final(cb) {
    this.reverse.push(null)
    cb(null)
  }
}
const sodium = require('sodium-universal')
const curve = require('noise-curve-ed')
const Noise = require('noise-handshake')
const b4a = require('b4a')

const EMPTY = b4a.alloc(0)

module.exports = class Handshake {
  constructor(isInitiator, keyPair, remotePublicKey, pattern) {
    this.isInitiator = isInitiator
    this.keyPair = keyPair
    this.noise = new Noise(pattern, isInitiator, keyPair, { curve })
    this.noise.initialise(EMPTY, remotePublicKey)
    this.destroyed = false
  }

  static keyPair(seed) {
    const publicKey = b4a.alloc(32)
    const secretKey = b4a.alloc(64)
    if (seed) sodium.crypto_sign_seed_keypair(publicKey, secretKey, seed)
    else sodium.crypto_sign_keypair(publicKey, secretKey)
    return { publicKey, secretKey }
  }

  recv(data) {
    try {
      this.noise.recv(data)
      if (this.noise.complete) return this._return(null)
      return this.send()
    } catch {
      this.destroy()
      return null
    }
  }

  // note that the data returned here is framed so we don't have to do an extra copy
  // when sending it...
  send() {
    try {
      const data = this.noise.send()
      const wrap = b4a.allocUnsafe(data.byteLength + 3)

      writeUint24le(data.byteLength, wrap)
      wrap.set(data, 3)

      return this._return(wrap)
    } catch {
      this.destroy()
      return null
    }
  }

  destroy() {
    if (this.destroyed) return
    this.destroyed = true
  }

  _return(data) {
    const tx = this.noise.complete ? b4a.toBuffer(this.noise.tx) : null
    const rx = this.noise.complete ? b4a.toBuffer(this.noise.rx) : null
    const hash = this.noise.complete ? b4a.toBuffer(this.noise.hash) : null
    const remotePublicKey = this.noise.complete ? b4a.toBuffer(this.noise.rs) : null

    return {
      data,
      remotePublicKey,
      hash,
      tx,
      rx
    }
  }
}

function writeUint24le(n, buf) {
  buf[0] = n & 255
  buf[1] = (n >>> 8) & 255
  buf[2] = (n >>> 16) & 255
}
{
  "name": "@hyperswarm/secret-stream",
  "version": "6.9.1",
  "description": "Secret stream backed by Noise and libsodium's secretstream",
  "main": "index.js",
  "files": [
    "index.js",
    "lib/**.js"
  ],
  "dependencies": {
    "b4a": "^1.1.0",
    "hypercore-crypto": "^3.3.1",
    "noise-curve-ed": "^2.0.1",
    "noise-handshake": "^4.0.0",
    "sodium-secretstream": "^1.1.0",
    "sodium-universal": "^5.0.0",
    "streamx": "^2.14.0",
    "timeout-refresh": "^2.0.0",
    "unslab": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "udx-native": "^1.13.2"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check .",
    "test": "brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/hyperswarm-secret-stream.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/hyperswarm-secret-stream/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperswarm-secret-stream"
}
const Cache = require('xache')

module.exports = class AdaptiveTimeout {
  constructor(opts = {}) {
    this._cache = new Cache({
      maxSize: opts.maxSize || 65536,
      maxAge: opts.maxAge || 10 * 60 * 1000 // 10 minutes
    })
    this._fallback = opts.fallback || AdaptiveTimeout.TimeoutExponential
    this._min = opts.min ?? 300
    this._max = opts.max || 4000
    this._jitter = opts.jitter ?? 256
  }

  // Default - aggressive ramp
  static TimeoutAggressive = [500, 750, 1000, 1500, 2000]

  // Linear - steady increase
  static TimeoutLinear = [500, 1000, 1500, 2000, 2500]

  // Exponential - slow start, rapid backoff
  static TimeoutExponential = [250, 500, 1000, 2000, 4000]

  // Gentle - conservative, patient
  static TimeoutGentle = [1000, 1250, 1500, 1750, 2000]

  // Fast - rapid fire retries
  static TimeoutFast = [200, 400, 600, 800, 1000]

  // U-shape - long, short, long
  static TimeoutUShape = [1500, 750, 500, 750, 1500]

  // Inverse U - short, long, short
  static TimeoutInverseU = [500, 1000, 1500, 1000, 500]

  // Sawtooth - alternating fast/slow
  static TimeoutSawtooth = [500, 1500, 500, 1500, 500]

  // Plateau - quick ramp then steady
  static TimeoutPlateau = [500, 1000, 2000, 2000, 2000]

  // Logarithmic - diminishing increases
  static TimeoutLogarithmic = [500, 1000, 1300, 1500, 1600]

  getValue(key) {
    return this._cache.get(key)
  }

  put(key, value) {
    let p = this._cache.get(key)

    if (!p) {
      p = { avg: value, variance: value >> 1 }
    } else {
      // blend 75% old + 25% new deviation
      p.variance += (Math.abs(p.avg - value) - p.variance) >> 2
      // blend 87.5% old + 12.5% new sample
      p.avg += (value - p.avg) >> 3
    }

    this._cache.set(key, p)

    return p
  }

  get(key, attempt = 1) {
    const p = this._cache.get(key)
    const jitter = (Math.random() * this._jitter) | 0

    if (p) {
      // known - use adaptive with linear backoff
      const base = p.avg + (p.variance << 1)
      const backoff = base * attempt
      return Math.min(Math.max(backoff + jitter, this._min), this._max)
    } else {
      // unknown - use aggressive fallback
      const base = this._fallback[Math.min(attempt - 1, this._fallback.length - 1)]
      return base + jitter
    }
  }

  has(key) {
    return this._cache.has(key)
  }

  delete(key) {
    return this._cache.delete(key)
  }

  clear() {
    this._cache.clear()
  }
}
{
  "name": "adaptive-timeout",
  "version": "1.0.1",
  "description": "adaptive-timeout",
  "main": "index.js",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    }
  },
  "files": [
    "package.json",
    "index.js",
    "index.d.ts"
  ],
  "devDependencies": {
    "brittle": "^3.19.0",
    "lunte": "^1.2.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && lunte && brittle-bare test/index.js",
    "lint": "lunte"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/adaptive-timeout.git"
  },
  "author": "Holepunch Inc",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/adaptive-timeout/issues"
  },
  "homepage": "https://github.com/holepunchto/adaptive-timeout",
  "dependencies": {
    "xache": "^1.2.1"
  }
}
const c = require('compact-encoding')
const IndexEncoder = require('index-encoder')

const Checkout = {
  preencode(state, m) {
    c.fixed32.preencode(state, m.key)
    c.uint.preencode(state, m.length)
  },
  encode(state, m) {
    c.fixed32.encode(state, m.key)
    c.uint.encode(state, m.length)
  },
  decode(state) {
    return {
      key: c.fixed32.decode(state),
      length: c.uint.decode(state)
    }
  }
}

const Clock = c.array(Checkout)

const IndexCheckpoint = {
  preencode(state, m) {
    c.fixed64.preencode(state, m.signature)
    c.uint.preencode(state, m.length)
  },
  encode(state, m) {
    c.fixed64.encode(state, m.signature)
    c.uint.encode(state, m.length)
  },
  decode(state) {
    return {
      signature: c.fixed64.decode(state),
      length: c.uint.decode(state)
    }
  }
}

const KeyV0 = {
  preencode(state, m) {
    c.fixed32.preencode(state, m.key)
  },
  encode(state, m) {
    c.fixed32.encode(state, m.key)
  },
  decode(state) {
    return {
      key: c.fixed32.decode(state),
      length: -1
    }
  }
}

const KeysV0 = c.array(KeyV0)

const WakeupV0 = {
  preencode(state, m) {
    c.uint.preencode(state, 0) // version
    c.uint.preencode(state, m.type)

    if (m.type === 1) {
      KeysV0.preencode(state, m.writers)
    }
  },
  encode(state, m) {
    c.uint.encode(state, 0) // version
    c.uint.encode(state, m.type)

    if (m.type === 1) {
      KeysV0.encode(state, m.writers)
    }
  },
  decode(state) {
    const v = c.uint.decode(state)
    if (v !== 0) throw new Error('Unsupported version: ' + v)

    const type = c.uint.decode(state)
    const m = { version: 0, type, writers: null }

    if (m.type === 1) {
      m.writers = KeysV0.decode(state)
    }

    return m
  }
}

const Wakeup = {
  preencode(state, m) {
    if (m.version === 0) return WakeupV0.preencode(state, m)

    c.uint.preencode(state, 1) // version
    c.uint.preencode(state, m.type)

    if (m.type === 1) {
      Clock.preencode(state, m.writers)
    }
  },
  encode(state, m) {
    if (m.version === 0) return WakeupV0.encode(state, m)

    c.uint.encode(state, 1) // version
    c.uint.encode(state, m.type)

    if (m.type === 1) {
      Clock.encode(state, m.writers)
    }
  },
  decode(state) {
    const start = state.start
    const v = c.uint.decode(state)

    if (v > 1) throw new Error('Unsupported version: ' + v)

    if (v === 0) {
      state.start = start
      return WakeupV0.decode(state)
    }

    const type = c.uint.decode(state)
    const m = { version: 1, type, writers: null }

    if (m.type === 1) {
      m.writers = Clock.decode(state)
    }

    return m
  }
}

const BootRecordV0 = {
  preencode() {
    throw new Error('version 0 records cannot be encoded')
  },
  encode() {
    throw new Error('version 0 records cannot be encoded')
  },
  decode(state) {
    c.uint.decode(state)
    const indexed = Checkout.decode(state)
    const heads = Clock.decode(state)

    // one cause initial recover is not ff recovery
    return {
      version: 0,
      key: indexed.key,
      systemLength: indexed.length,
      indexersUpdated: false,
      fastForwarding: false,
      recoveries: 1,
      migrating: false,
      heads
    }
  }
}

const Checkpointer = {
  preencode(state, idx) {
    c.uint.preencode(state, idx.checkpointer)
    if (idx.checkpoint !== null) IndexCheckpoint.preencode(state, idx.checkpoint)
  },
  encode(state, idx) {
    c.uint.encode(state, idx.checkpointer)
    if (idx.checkpoint !== null) IndexCheckpoint.encode(state, idx.checkpoint)
  },
  decode(state) {
    const checkpointer = c.uint.decode(state)
    const checkpoint = checkpointer ? null : IndexCheckpoint.decode(state)

    return {
      checkpointer,
      checkpoint
    }
  }
}

const CheckpointerArray = c.array(Checkpointer)

const Indexer = {
  preencode(state, m) {
    c.uint.preencode(state, m.signature)
    c.fixed32.preencode(state, m.namespace)
    c.fixed32.preencode(state, m.publicKey)
  },
  encode(state, m) {
    c.uint.encode(state, m.signature)
    c.fixed32.encode(state, m.namespace)
    c.fixed32.encode(state, m.publicKey)
  },
  decode(state) {
    return {
      signature: c.uint.decode(state),
      namespace: c.fixed32.decode(state),
      publicKey: c.fixed32.decode(state)
    }
  }
}

const Indexers = c.array(Indexer)

const DigestV0 = {
  preencode(state, m) {
    c.uint.preencode(state, m.pointer)
    if (m.pointer === 0) {
      Indexers.preencode(state, m.indexers)
    }
  },
  encode(state, m) {
    c.uint.encode(state, m.pointer)
    if (m.pointer === 0) {
      Indexers.encode(state, m.indexers)
    }
  },
  decode(state) {
    const pointer = c.uint.decode(state)
    return {
      pointer,
      indexers: pointer === 0 ? Indexers.decode(state) : null
    }
  }
}

const Digest = {
  preencode(state, m) {
    c.uint.preencode(state, m.pointer)
    if (m.pointer === 0) {
      c.fixed32.preencode(state, m.key)
    }
  },
  encode(state, m) {
    c.uint.encode(state, m.pointer)
    if (m.pointer === 0) {
      c.fixed32.encode(state, m.key)
    }
  },
  decode(state) {
    const pointer = c.uint.decode(state)
    return {
      pointer,
      key: pointer === 0 ? c.fixed32.decode(state) : null
    }
  }
}

const Node = {
  preencode(state, m) {
    Clock.preencode(state, m.heads)
    c.uint.preencode(state, m.batch)
    c.optionalBuffer.preencode(state, m.value)
  },
  encode(state, m) {
    Clock.encode(state, m.heads)
    c.uint.encode(state, m.batch)
    c.optionalBuffer.encode(state, m.value)
  },
  decode(state, m) {
    return {
      heads: Clock.decode(state),
      batch: c.uint.decode(state),
      value: c.optionalBuffer.decode(state)
    }
  }
}

const Additional = {
  preencode(state, m) {
    c.uint.preencode(state, m.pointer)
    if (m.pointer === 0) {
      AdditionalData.preencode(state, m.data)
    }
  },
  encode(state, m) {
    c.uint.encode(state, m.pointer)
    if (m.pointer === 0) {
      AdditionalData.encode(state, m.data)
    }
  },
  decode(state) {
    const pointer = c.uint.decode(state)
    return {
      pointer,
      data: pointer === 0 ? AdditionalData.decode(state) : null
    }
  }
}

const AdditionalData = {
  preencode(state, m) {
    c.uint.preencode(state, 0)
  },
  encode(state, m) {
    c.uint.encode(state, 0) // empty for now, for the future
  },
  decode(state) {
    const flags = c.uint.decode(state)
    return {
      encryptionId: flags & 1 ? c.fixed32.decode(state) : null, // to help validate the encryption key used
      abi: flags & 2 ? c.uint.decode(state) : 0
    }
  }
}

const OplogMessageV1 = {
  preencode(state, m) {
    throw new Error('Encoding not supported')
  },
  encode(state, m) {
    throw new Error('Encoding not supported')
  },
  decode(state) {
    c.uint.decode(state) // version
    const maxSupportedVersion = c.uint.decode(state)

    const flags = c.uint.decode(state)

    const isCheckpointer = (flags & 1) !== 0

    const chk = isCheckpointer ? CheckpointerArray.decode(state) : null
    const digest = isCheckpointer ? Digest.decode(state) : null

    const node = Node.decode(state)

    return {
      version: 1,
      maxSupportedVersion,
      digest,
      checkpoint: chk ? { system: chk[0], encryption: null, user: chk.slice(1) } : null,
      optimistic: (flags & 2) !== 0,
      node
    }
  }
}

const OplogMessageV0 = {
  preencode(state, m) {
    throw new Error('Encoding not supported')
  },
  encode(state, m) {
    throw new Error('Encoding not supported')
  },
  decode(state) {
    c.uint.decode(state) // version
    const flags = c.uint.decode(state)

    const isCheckpointer = (flags & 1) !== 0

    if (isCheckpointer) DigestV0.decode(state)
    const chk = isCheckpointer ? CheckpointerArray.decode(state) : null
    const node = Node.decode(state)
    Additional.decode(state)
    const maxSupportedVersion = state.start < state.end ? c.uint.decode(state) : 0

    return {
      version: 0,
      maxSupportedVersion,
      digest: null,
      checkpoint: chk ? { system: chk[0], encryption: null, user: chk.slice(1) } : null,
      optimistic: null,
      node
    }
  }
}

// prefix 0 is reserved for future manifest
const LINEARIZER_PREFIX = 1

const LinearizerKey = {
  preencode(state, seq) {
    IndexEncoder.UINT.preencode(state, LINEARIZER_PREFIX)
    IndexEncoder.UINT.preencode(state, seq)
  },
  encode(state, seq) {
    IndexEncoder.UINT.encode(state, LINEARIZER_PREFIX)
    IndexEncoder.UINT.encode(state, seq)
  },
  decode(state) {
    IndexEncoder.UINT.decode(state)
    return IndexEncoder.UINT.decode(state)
  }
}

function infoLegacyMap(info) {
  return {
    version: info.version,
    members: info.members,
    pendingIndexers: info.pendingIndexers,
    indexers: info.indexers,
    heads: info.heads,
    views: info.views,
    encryptionLength: 0,
    entropy: null
  }
}

module.exports = {
  Wakeup,
  BootRecordV0,
  OplogMessageV0,
  OplogMessageV1,
  LinearizerKey,
  infoLegacyMap
}
// This file is autogenerated by the hyperschema compiler
// Schema Version: 1
/* eslint-disable camelcase */
/* eslint-disable quotes */
/* eslint-disable space-before-function-paren */

const { c } = require('hyperschema/runtime')
const external0 = require('../../legacy.js')

const VERSION = 1

// eslint-disable-next-line no-unused-vars
let version = VERSION

// @autobase/checkout
const encoding0 = {
  preencode(state, m) {
    c.fixed32.preencode(state, m.key)
    c.uint.preencode(state, m.length)
  },
  encode(state, m) {
    c.fixed32.encode(state, m.key)
    c.uint.encode(state, m.length)
  },
  decode(state) {
    const r0 = c.fixed32.decode(state)
    const r1 = c.uint.decode(state)

    return {
      key: r0,
      length: r1
    }
  }
}

// @autobase/clock
const encoding1 = c.array(encoding0)

// @autobase/index-checkpoint
const encoding2 = {
  preencode(state, m) {
    c.fixed64.preencode(state, m.signature)
    c.uint.preencode(state, m.length)
  },
  encode(state, m) {
    c.fixed64.encode(state, m.signature)
    c.uint.encode(state, m.length)
  },
  decode(state) {
    const r0 = c.fixed64.decode(state)
    const r1 = c.uint.decode(state)

    return {
      signature: r0,
      length: r1
    }
  }
}

const encoding3 = external0.Wakeup

const encoding4 = external0.BootRecordV0

// @autobase/boot-record-raw
const encoding5 = {
  preencode(state, m) {
    c.fixed32.preencode(state, m.key)
    c.uint.preencode(state, m.systemLength)
    state.end++ // max flag is 4 so always one byte

    if (m.recoveries) c.uint.preencode(state, m.recoveries)
  },
  encode(state, m) {
    const flags = (m.indexersUpdated ? 1 : 0) | (m.fastForwarding ? 2 : 0) | (m.recoveries ? 4 : 0)

    c.fixed32.encode(state, m.key)
    c.uint.encode(state, m.systemLength)
    c.uint.encode(state, flags)

    if (m.recoveries) c.uint.encode(state, m.recoveries)
  },
  decode(state) {
    const v = c.uint.decode(state)
    const r0 = c.fixed32.decode(state)
    const r1 = c.uint.decode(state)
    const flags = c.uint.decode(state)

    return {
      version: v,
      key: r0,
      systemLength: r1,
      indexersUpdated: (flags & 1) !== 0,
      fastForwarding: (flags & 2) !== 0,
      recoveries: (flags & 4) !== 0 ? c.uint.decode(state) : 0
    }
  }
}

// @autobase/boot-record
const encoding6 = {
  preencode(state, m) {
    c.uint.preencode(state, m.version)
    switch (m.version) {
      case 0:
        encoding4.preencode(state, m)
        break
      case 1:
      case 2:
      case 3:
        encoding5.preencode(state, m)
        break
      default:
        throw new Error('Unsupported version')
    }
  },
  encode(state, m) {
    c.uint.encode(state, m.version)
    switch (m.version) {
      case 0:
        encoding4.encode(state, m)
        break
      case 1:
      case 2:
      case 3:
        encoding5.encode(state, m)
        break
      default:
        throw new Error('Unsupported version')
    }
  },
  decode(state) {
    const start = state.start
    const v = c.uint.decode(state)
    state.start = start
    switch (v) {
      case 0: {
        const decoded = encoding4.decode(state)
        return decoded
      }
      case 1:
      case 2:
      case 3: {
        const decoded = encoding5.decode(state)
        return decoded
      }
      default:
        throw new Error('Unsupported version')
    }
  }
}

// @autobase/checkpointer
const encoding7 = {
  preencode(state, m) {
    state.end++ // flags are fixed size

    if (m.checkpointer) c.uint.preencode(state, m.checkpointer)
    if (m.checkpoint) encoding2.preencode(state, m.checkpoint)
  },
  encode(state, m) {
    const flags = (m.checkpointer ? 1 : 0) | (m.checkpoint ? 2 : 0)

    c.uint8.encode(state, flags)

    if (m.checkpointer) c.uint.encode(state, m.checkpointer)
    if (m.checkpoint) encoding2.encode(state, m.checkpoint)
  },
  decode(state) {
    const flags = c.uint8.decode(state)

    return {
      checkpointer: (flags & 1) !== 0 ? c.uint.decode(state) : 0,
      checkpoint: (flags & 2) !== 0 ? encoding2.decode(state) : null
    }
  }
}

// @autobase/checkpoint.user
const encoding8_2 = c.array(encoding7)

// @autobase/checkpoint
const encoding8 = {
  preencode(state, m) {
    state.end++ // max flag is 4 so always one byte

    if (m.system) encoding7.preencode(state, m.system)
    if (m.encryption) encoding7.preencode(state, m.encryption)
    if (m.user) encoding8_2.preencode(state, m.user)
  },
  encode(state, m) {
    const flags = (m.system ? 1 : 0) | (m.encryption ? 2 : 0) | (m.user ? 4 : 0)

    c.uint.encode(state, flags)

    if (m.system) encoding7.encode(state, m.system)
    if (m.encryption) encoding7.encode(state, m.encryption)
    if (m.user) encoding8_2.encode(state, m.user)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      system: (flags & 1) !== 0 ? encoding7.decode(state) : null,
      encryption: (flags & 2) !== 0 ? encoding7.decode(state) : null,
      user: (flags & 4) !== 0 ? encoding8_2.decode(state) : null
    }
  }
}

// @autobase/digest
const encoding9 = {
  preencode(state, m) {
    state.end++ // max flag is 2 so always one byte

    if (m.pointer) c.uint.preencode(state, m.pointer)
    if (m.key) c.fixed32.preencode(state, m.key)
  },
  encode(state, m) {
    const flags = (m.pointer ? 1 : 0) | (m.key ? 2 : 0)

    c.uint.encode(state, flags)

    if (m.pointer) c.uint.encode(state, m.pointer)
    if (m.key) c.fixed32.encode(state, m.key)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      pointer: (flags & 1) !== 0 ? c.uint.decode(state) : 0,
      key: (flags & 2) !== 0 ? c.fixed32.decode(state) : null
    }
  }
}

// @autobase/node
const encoding10 = {
  preencode(state, m) {
    encoding1.preencode(state, m.heads)
    c.uint.preencode(state, m.batch)
    c.optionalBuffer.preencode(state, m.value)
  },
  encode(state, m) {
    encoding1.encode(state, m.heads)
    c.uint.encode(state, m.batch)
    c.optionalBuffer.encode(state, m.value)
  },
  decode(state) {
    const r0 = encoding1.decode(state)
    const r1 = c.uint.decode(state)
    const r2 = c.optionalBuffer.decode(state)

    return {
      heads: r0,
      batch: r1,
      value: r2
    }
  }
}

// @autobase/user-view-trace.blocks
const encoding11_1 = c.array(c.uint)

// @autobase/user-view-trace
const encoding11 = {
  preencode(state, m) {
    c.uint.preencode(state, m.view)
    encoding11_1.preencode(state, m.blocks)
  },
  encode(state, m) {
    c.uint.encode(state, m.view)
    encoding11_1.encode(state, m.blocks)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const r1 = encoding11_1.decode(state)

    return {
      view: r0,
      blocks: r1
    }
  }
}

// @autobase/trace.system
const encoding12_0 = encoding11_1
// @autobase/trace.encryption
const encoding12_1 = encoding11_1
// @autobase/trace.user
const encoding12_2 = c.array(encoding11)

// @autobase/trace
const encoding12 = {
  preencode(state, m) {
    encoding12_0.preencode(state, m.system)
    encoding12_1.preencode(state, m.encryption)
    encoding12_2.preencode(state, m.user)
  },
  encode(state, m) {
    encoding12_0.encode(state, m.system)
    encoding12_1.encode(state, m.encryption)
    encoding12_2.encode(state, m.user)
  },
  decode(state) {
    const r0 = encoding12_0.decode(state)
    const r1 = encoding12_1.decode(state)
    const r2 = encoding12_2.decode(state)

    return {
      system: r0,
      encryption: r1,
      user: r2
    }
  }
}

const encoding13 = external0.OplogMessageV0

const encoding14 = external0.OplogMessageV1

// @autobase/oplog-message-v2.checkpoint
const encoding15_1 = c.frame(encoding8)
// @autobase/oplog-message-v2.digest
const encoding15_2 = c.frame(encoding9)
// @autobase/oplog-message-v2.trace
const encoding15_4 = c.frame(encoding12)

// @autobase/oplog-message-v2
const encoding15 = {
  preencode(state, m) {
    encoding10.preencode(state, m.node)
    state.end++ // max flag is 8 so always one byte

    if (m.checkpoint) encoding15_1.preencode(state, m.checkpoint)
    if (m.digest) encoding15_2.preencode(state, m.digest)
    if (m.trace) encoding15_4.preencode(state, m.trace)
  },
  encode(state, m) {
    const flags =
      (m.checkpoint ? 1 : 0) | (m.digest ? 2 : 0) | (m.optimistic ? 4 : 0) | (m.trace ? 8 : 0)

    encoding10.encode(state, m.node)
    c.uint.encode(state, flags)

    if (m.checkpoint) encoding15_1.encode(state, m.checkpoint)
    if (m.digest) encoding15_2.encode(state, m.digest)
    if (m.trace) encoding15_4.encode(state, m.trace)
  },
  decode(state) {
    const v = c.uint.decode(state)
    const r0 = encoding10.decode(state)
    const flags = c.uint.decode(state)

    return {
      version: v,
      node: r0,
      checkpoint: (flags & 1) !== 0 ? encoding15_1.decode(state) : null,
      digest: (flags & 2) !== 0 ? encoding15_2.decode(state) : null,
      optimistic: (flags & 4) !== 0,
      trace: (flags & 8) !== 0 ? encoding15_4.decode(state) : null
    }
  }
}

// @autobase/oplog-message
const encoding16 = {
  preencode(state, m) {
    c.uint.preencode(state, m.version)
    switch (m.version) {
      case 0:
        encoding13.preencode(state, m)
        break
      case 1:
        encoding14.preencode(state, m)
        break
      case 2:
        encoding15.preencode(state, m)
        break
      default:
        throw new Error('Unsupported version')
    }
  },
  encode(state, m) {
    c.uint.encode(state, m.version)
    switch (m.version) {
      case 0:
        encoding13.encode(state, m)
        break
      case 1:
        encoding14.encode(state, m)
        break
      case 2:
        encoding15.encode(state, m)
        break
      default:
        throw new Error('Unsupported version')
    }
  },
  decode(state) {
    const start = state.start
    const v = c.uint.decode(state)
    state.start = start
    switch (v) {
      case 0: {
        const decoded = encoding13.decode(state)
        return decoded
      }
      case 1: {
        const decoded = encoding14.decode(state)
        return decoded
      }
      case 2: {
        const decoded = encoding15.decode(state)
        return decoded
      }
      default:
        throw new Error('Unsupported version')
    }
  }
}

// @autobase/info-v1.pendingIndexers
const encoding17_1 = c.array(c.fixed32)

// @autobase/info-v1
const encoding17 = {
  preencode(state, m) {
    c.uint.preencode(state, m.members)
    encoding17_1.preencode(state, m.pendingIndexers)
    encoding1.preencode(state, m.indexers)
    encoding1.preencode(state, m.heads)
    encoding1.preencode(state, m.views)
  },
  encode(state, m) {
    c.uint.encode(state, m.members)
    encoding17_1.encode(state, m.pendingIndexers)
    encoding1.encode(state, m.indexers)
    encoding1.encode(state, m.heads)
    encoding1.encode(state, m.views)
  },
  decode(state) {
    const v = c.uint.decode(state)
    const r0 = c.uint.decode(state)
    const r1 = encoding17_1.decode(state)
    const r2 = encoding1.decode(state)
    const r3 = encoding1.decode(state)
    const r4 = encoding1.decode(state)

    return {
      version: v,
      members: r0,
      pendingIndexers: r1,
      indexers: r2,
      heads: r3,
      views: r4
    }
  }
}

// @autobase/info-v2.pendingIndexers
const encoding18_1 = encoding17_1

// @autobase/info-v2
const encoding18 = {
  preencode(state, m) {
    c.uint.preencode(state, m.members)
    encoding18_1.preencode(state, m.pendingIndexers)
    encoding1.preencode(state, m.indexers)
    encoding1.preencode(state, m.heads)
    encoding1.preencode(state, m.views)
    c.uint.preencode(state, m.encryptionLength)
    state.end++ // max flag is 1 so always one byte

    if (m.entropy) c.fixed32.preencode(state, m.entropy)
  },
  encode(state, m) {
    const flags = m.entropy ? 1 : 0

    c.uint.encode(state, m.members)
    encoding18_1.encode(state, m.pendingIndexers)
    encoding1.encode(state, m.indexers)
    encoding1.encode(state, m.heads)
    encoding1.encode(state, m.views)
    c.uint.encode(state, m.encryptionLength)
    c.uint.encode(state, flags)

    if (m.entropy) c.fixed32.encode(state, m.entropy)
  },
  decode(state) {
    const v = c.uint.decode(state)
    const r0 = c.uint.decode(state)
    const r1 = encoding18_1.decode(state)
    const r2 = encoding1.decode(state)
    const r3 = encoding1.decode(state)
    const r4 = encoding1.decode(state)
    const r5 = c.uint.decode(state)
    const flags = c.uint.decode(state)

    return {
      version: v,
      members: r0,
      pendingIndexers: r1,
      indexers: r2,
      heads: r3,
      views: r4,
      encryptionLength: r5,
      entropy: (flags & 1) !== 0 ? c.fixed32.decode(state) : null
    }
  }
}

// @autobase/info
const encoding19 = {
  preencode(state, m) {
    c.uint.preencode(state, m.version)
    switch (m.version) {
      case 0:
      case 1:
        encoding17.preencode(state, m)
        break
      case 2:
        encoding18.preencode(state, m)
        break
      default:
        throw new Error('Unsupported version')
    }
  },
  encode(state, m) {
    c.uint.encode(state, m.version)
    switch (m.version) {
      case 0:
      case 1:
        encoding17.encode(state, m)
        break
      case 2:
        encoding18.encode(state, m)
        break
      default:
        throw new Error('Unsupported version')
    }
  },
  decode(state) {
    const start = state.start
    const v = c.uint.decode(state)
    state.start = start
    switch (v) {
      case 0:
      case 1: {
        const decoded = encoding17.decode(state)
        const map = external0.infoLegacyMap
        return map(decoded)
      }
      case 2: {
        const decoded = encoding18.decode(state)
        return decoded
      }
      default:
        throw new Error('Unsupported version')
    }
  }
}

// @autobase/member
const encoding20 = {
  preencode(state, m) {
    state.end++ // max flag is 2 so always one byte
    c.uint.preencode(state, m.length)
  },
  encode(state, m) {
    const flags = (m.isIndexer ? 1 : 0) | (m.isRemoved ? 2 : 0)

    c.uint.encode(state, flags)
    c.uint.encode(state, m.length)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      isIndexer: (flags & 1) !== 0,
      isRemoved: (flags & 2) !== 0,
      length: c.uint.decode(state)
    }
  }
}

const encoding21 = external0.LinearizerKey

// @autobase/linearizer-update
const encoding22 = {
  preencode(state, m) {
    c.fixed32.preencode(state, m.key)
    c.uint.preencode(state, m.length)
    c.uint.preencode(state, m.batch)
    c.uint.preencode(state, m.systemLength)
    state.end++ // max flag is 1 so always one byte
  },
  encode(state, m) {
    const flags = m.indexers ? 1 : 0

    c.fixed32.encode(state, m.key)
    c.uint.encode(state, m.length)
    c.uint.encode(state, m.batch)
    c.uint.encode(state, m.systemLength)
    c.uint.encode(state, flags)
  },
  decode(state) {
    const r0 = c.fixed32.decode(state)
    const r1 = c.uint.decode(state)
    const r2 = c.uint.decode(state)
    const r3 = c.uint.decode(state)
    const flags = c.uint.decode(state)

    return {
      key: r0,
      length: r1,
      batch: r2,
      systemLength: r3,
      indexers: (flags & 1) !== 0
    }
  }
}

// @autobase/encryption-descriptor
const encoding23 = {
  preencode(state, m) {
    c.uint.preencode(state, m.type)
    c.optionalBuffer.preencode(state, m.payload)
  },
  encode(state, m) {
    c.uint.encode(state, m.type)
    c.optionalBuffer.encode(state, m.payload)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const r1 = c.optionalBuffer.decode(state)

    return {
      type: r0,
      payload: r1
    }
  }
}

// @autobase/manifest-data
const encoding24 = {
  preencode(state, m) {
    c.uint.preencode(state, m.version)
    state.end++ // max flag is 2 so always one byte

    if (m.legacyBlocks) c.uint.preencode(state, m.legacyBlocks)
    if (m.namespace) c.fixed32.preencode(state, m.namespace)
  },
  encode(state, m) {
    const flags = (m.legacyBlocks ? 1 : 0) | (m.namespace ? 2 : 0)

    c.uint.encode(state, m.version)
    c.uint.encode(state, flags)

    if (m.legacyBlocks) c.uint.encode(state, m.legacyBlocks)
    if (m.namespace) c.fixed32.encode(state, m.namespace)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const flags = c.uint.decode(state)

    return {
      version: r0,
      legacyBlocks: (flags & 1) !== 0 ? c.uint.decode(state) : 0,
      namespace: (flags & 2) !== 0 ? c.fixed32.decode(state) : null
    }
  }
}

function setVersion(v) {
  version = v
}

function encode(name, value, v = VERSION) {
  version = v
  return c.encode(getEncoding(name), value)
}

function decode(name, buffer, v = VERSION) {
  version = v
  return c.decode(getEncoding(name), buffer)
}

function getEnum(name) {
  switch (name) {
    default:
      throw new Error('Enum not found ' + name)
  }
}

function getEncoding(name) {
  switch (name) {
    case '@autobase/checkout':
      return encoding0
    case '@autobase/clock':
      return encoding1
    case '@autobase/index-checkpoint':
      return encoding2
    case '@autobase/wakeup':
      return encoding3
    case '@autobase/boot-record-v0':
      return encoding4
    case '@autobase/boot-record-raw':
      return encoding5
    case '@autobase/boot-record':
      return encoding6
    case '@autobase/checkpointer':
      return encoding7
    case '@autobase/checkpoint':
      return encoding8
    case '@autobase/digest':
      return encoding9
    case '@autobase/node':
      return encoding10
    case '@autobase/user-view-trace':
      return encoding11
    case '@autobase/trace':
      return encoding12
    case '@autobase/oplog-message-v0':
      return encoding13
    case '@autobase/oplog-message-v1':
      return encoding14
    case '@autobase/oplog-message-v2':
      return encoding15
    case '@autobase/oplog-message':
      return encoding16
    case '@autobase/info-v1':
      return encoding17
    case '@autobase/info-v2':
      return encoding18
    case '@autobase/info':
      return encoding19
    case '@autobase/member':
      return encoding20
    case '@autobase/linearizer-key':
      return encoding21
    case '@autobase/linearizer-update':
      return encoding22
    case '@autobase/encryption-descriptor':
      return encoding23
    case '@autobase/manifest-data':
      return encoding24
    default:
      throw new Error('Encoder not found ' + name)
  }
}

function getStruct(name, v = VERSION) {
  const enc = getEncoding(name)
  return {
    preencode(state, m) {
      version = v
      enc.preencode(state, m)
    },
    encode(state, m) {
      version = v
      enc.encode(state, m)
    },
    decode(state) {
      version = v
      return enc.decode(state)
    }
  }
}

const resolveStruct = getStruct // compat

module.exports = {
  resolveStruct,
  getStruct,
  getEnum,
  getEncoding,
  encode,
  decode,
  setVersion,
  version
}
const b4a = require('b4a')
const ReadyResource = require('ready-resource')
const debounceify = require('debounceify')
const c = require('compact-encoding')
const safetyCatch = require('safety-catch')
const hypercoreId = require('hypercore-id-encoding')
const assert = require('nanoassert')
const SignalPromise = require('signal-promise')
const CoreCoupler = require('core-coupler')
const ProtomuxWakeup = require('protomux-wakeup')
const rrp = require('resolve-reject-promise')
const Hypercore = require('hypercore')
const ScopeLock = require('scope-lock')
const encryptionEncoding = require('encryption-encoding')

const LocalState = require('./lib/local-state.js')
const Linearizer = require('./lib/linearizer.js')
const SystemView = require('./lib/system.js')
const { EncryptionView } = require('./lib/encryption.js')
const UpdateChanges = require('./lib/updates.js')
const messages = require('./lib/messages.js')
const Timer = require('./lib/timer.js')
const Writer = require('./lib/writer.js')
const { encodeValue, decodeValue } = require('./lib/values.js')
const ActiveWriters = require('./lib/active-writers.js')
const AutoWakeup = require('./lib/wakeup.js')

const FastForward = require('./lib/fast-forward.js')
const AutoStore = require('./lib/store.js')
const ApplyState = require('./lib/apply-state.js')
const AppendBatch = require('./lib/append-batch.js')
const { PublicApplyCalls } = require('./lib/apply-calls.js')
const boot = require('./lib/boot.js')
const { MAX_AUTOBASE_VERSION, BOOT_RECORD_VERSION } = require('./lib/caps.js')

const inspect = Symbol.for('nodejs.util.inspect.custom')
const INTERRUPT = new Error('Apply interrupted')
const BINARY_ENCODING = c.from('binary')

const RECOVERIES = 3

// default is to automatically ack
const DEFAULT_ACK_INTERVAL = 10_000
const DEFAULT_ACK_THRESHOLD = 4

const REMOTE_ADD_BATCH = 64
const REMOTE_ADD_BATCH_SANITY = 4096
const MIN_FF_WAIT = 300_000 // wait at least 5min before attempting to ff again after failure

class WakeupHandler {
  constructor(base, discoveryKey) {
    this.active = true
    this.discoveryKey = discoveryKey
    this.base = base
  }

  onpeeractive(peer, session) {
    this.base._bumpWakeupPeer(peer)
  }

  onlookup(req, peer, session) {
    const wakeup = this.base._getWakeup()
    if (wakeup.length === 0) return
    session.announce(peer, wakeup)
  }

  onannounce(wakeup, peer, session) {
    if (this.base.isFastForwarding()) {
      this.base._needsWakeupRequest = true
      return
    }
    this.base.hintWakeup(wakeup)
  }
}

module.exports = class Autobase extends ReadyResource {
  constructor(store, bootstrap, handlers = {}) {
    if (Array.isArray(bootstrap)) bootstrap = bootstrap[0] // TODO: just a quick compat, lets remove soon

    if (bootstrap && typeof bootstrap !== 'string' && !b4a.isBuffer(bootstrap)) {
      handlers = bootstrap
      bootstrap = null
    }

    super()

    const key = bootstrap ? toKey(bootstrap) : null

    this.id = null
    this.key = key
    this.discoveryKey = null
    this.backoff = handlers.backoff || null

    this.keyPair = null
    this.valueEncoding = c.from(handlers.valueEncoding || 'binary')
    this.store = store
    this.globalCache = store.globalCache || null
    this.migrated = false

    this.encrypted = handlers.encrypted || !!handlers.encryptionKey
    this.encrypt = !!handlers.encrypt
    this.encryptionKey = null
    this.encryption = null
    this.blindEncryption = handlers.blindEncryption || null

    this.activeBatch = null // maintained by the append-batch

    this.local = null
    this.localWriter = null
    this.isIndexer = false

    this.activeWriters = new ActiveWriters()
    this.linearizer = null
    this.updating = false

    this.nukeTip = !!handlers.nukeTip

    this.wakeupOwner = !handlers.wakeup
    this.wakeupCapability = null
    this.wakeupProtocol = handlers.wakeup || new ProtomuxWakeup()
    this.wakeupSession = null

    this._primaryBootstrap = null

    this.fastForwardEnabled = handlers.fastForward !== false
    this.fastForwarding = null
    this.fastForwardTo = null
    this.fastForwardFailedAt = 0
    this.fastForwardMinimum = FastForward.MINIMUM

    this.bigBatches = !!handlers.bigBatches

    this._bootstrapWriters = [] // might contain dups, but thats ok
    this._bootstrapWritersChanged = false

    this._flushSignal = new SignalPromise()
    this._flushing = 0

    this._checkWriters = []
    this._optimistic = -1
    this._appended = 0
    this._appending = null
    this._wakeup = new AutoWakeup(this)
    this._wakeupHints = new Map()
    this._wakeupPeerBound = this._wakeupPeer.bind(this)
    this._coupler = null

    this._updateLocalCore = null
    this._lock = new ScopeLock()

    this._needsWakeupRequest = false
    this._needsWakeup = true
    this._needsWakeupHeads = true

    this._updates = []
    this._handlers = handlers || {}
    this._warn = emitWarning.bind(this)
    this._lastError = null

    this._draining = false
    this._writable = null
    this._advancing = null
    this._interrupting = false
    this._caughtup = false

    this.paused = false

    this._bump = debounceify(() => {
      this._advancing = this._advance()
      return this._advancing
    })

    this._onremotewriterchangeBound = this._onremotewriterchange.bind(this)
    this._onlocalwriterchangeBound = this._onlocalwriterchange.bind(this)

    this._preopen = null

    this._hasOpen = !!this._handlers.open
    this._hasApply = !!this._handlers.apply
    this._hasOptimisticApply = !!this._handlers.optimistic
    this._hasUpdate = !!this._handlers.update
    this._hasClose = !!this._handlers.close

    this._viewStore = new AutoStore(this)
    this._applyState = null

    this.view = null
    this.core = null
    this.version = -1
    this.interrupted = null
    this.recoveries = RECOVERIES

    const { ackInterval = DEFAULT_ACK_INTERVAL, ackThreshold = DEFAULT_ACK_THRESHOLD } = handlers

    this._ackInterval = ackInterval
    this._ackThreshold = ackThreshold
    this._ackTickThreshold = ackThreshold
    this._ackTick = 0

    this._ackTimer = null
    this._acking = false

    this._waiting = new SignalPromise()

    this.view = this._hasOpen
      ? this._handlers.open(this._viewStore, new PublicApplyCalls(this))
      : null
    this.core = this._viewStore.get({ name: '_system' })

    if (this.fastForwardEnabled && isObject(handlers.fastForward)) {
      this._runFastForward(
        new FastForward(this, handlers.fastForward.key, { verified: false })
      ).catch(noop)
    }

    this.ready().catch(safetyCatch)
  }

  [inspect](depth, opts) {
    let indent = ''
    if (typeof opts.indentationLvl === 'number') {
      while (indent.length < opts.indentationLvl) indent += ' '
    }

    return indent + 'Autobase { ... }'
  }

  // just compat, use .key
  get bootstrap() {
    return this.key
  }

  // TODO: compat, will be removed
  get bootstraps() {
    return [this.bootstrap]
  }

  get appending() {
    return this._appending !== null && this._appending.length > 0
  }

  get writable() {
    return this.localWriter !== null && !this.localWriter.isRemoved
  }

  get ackable() {
    return this.localWriter !== null && this.localWriter.isActiveIndexer
  }

  get signedLength() {
    return this.core.signedLength
  }

  get indexedLength() {
    return this._applyState ? this._applyState.indexedLength : 0
  }

  get length() {
    return this.core.length
  }

  get flushing() {
    return this._flushing > 0
  }

  hash() {
    return this.core.treeHash()
  }

  // deprecated, use .core.key
  getSystemKey() {
    return this.core.key
  }

  get system() {
    return this._applyState && this._applyState.system
  }

  // deprecated
  async getIndexedInfo() {
    if (this.opened === false) await this.ready()
    return (
      this._applyState && this._applyState.system.getIndexedInfo(this._applyState.indexedLength)
    )
  }

  _isActiveIndexer() {
    return this.localWriter ? this.localWriter.isActiveIndexer : false
  }

  replicate(isInitiator, opts) {
    const stream = this.store.replicate(isInitiator, opts)
    this.wakeupProtocol.addStream(stream)
    return stream
  }

  heads() {
    if (!this._applyState || !this._applyState.opened) return []
    const nodes = new Array(this._applyState.system.heads.length)
    for (let i = 0; i < this._applyState.system.heads.length; i++)
      nodes[i] = this._applyState.system.heads[i]
    return nodes.sort(compareNodes)
  }

  async export() {
    const exporting = [this.store.storage.export(this.local.discoveryKey), this._viewStore.export()]

    const [local, views] = await Promise.all(exporting)

    return {
      local,
      views
    }
  }

  hintWakeup(hints) {
    if (!Array.isArray(hints)) hints = [hints]
    for (const { key, length } of hints) {
      const hex = b4a.toString(key, 'hex')
      const prev = this._wakeupHints.get(hex)
      if (!prev || length === -1 || prev < length) this._wakeupHints.set(hex, length)
    }
    this._queueBump()
  }

  setBigBatches(bool = true) {
    this.bigBatches = bool
  }

  _queueBump() {
    this._bump().catch(safetyCatch)
  }

  async _runPreOpen() {
    if (this._handlers.wait) await this._handlers.wait()

    await this.store.ready()

    this.keyPair = (await this._handlers.keyPair) || null

    if (this._handlers.encryptionKey !== null) {
      this.encryptionKey = await this._handlers.encryptionKey
    }

    const result = await boot(this.store, this.key, {
      encryptionKey: this.encryptionKey,
      encrypt: this.encrypt,
      keyPair: this.keyPair,
      blindEncryption: this.blindEncryption
    })

    this._primaryBootstrap = result.bootstrap
    this.local = result.local

    this.key = result.bootstrap.key
    this.discoveryKey = result.bootstrap.discoveryKey
    this.id = result.bootstrap.id

    this.encryptionKey = result.encryptionKey

    if (this.encrypted) {
      assert(this.encryptionKey !== null, 'Encryption key is expected')
    }

    if (this.encryptionKey) {
      this.encryption = new EncryptionView(this, null)

      this.local.setEncryption(this.getWriterEncryption())
      this._primaryBootstrap.setEncryption(this.getWriterEncryption())
    }

    if (this.nukeTip) await this._nukeTip()

    this.local.on('append', this._onlocalwriterchangeBound)

    this.wakeupCapability = (await this._handlers.wakeupCapability) || {
      key: this.key,
      discoveryKey: this.discoveryKey
    }
    this.setWakeup(this.wakeupCapability.key, this.wakeupCapability.discoveryKey)
  }

  async _nukeTipBatch(key, length) {
    const core = this.store.get({ key, active: false })
    await core.ready()

    const batch = core.session({ name: 'batch' })
    await batch.ready()
    if (batch.length > length) await batch.truncate(length)
    await batch.close()

    await core.close()
  }

  // TODO: not atomic atm, so more of a (very useful) debug helper
  async _nukeTip() {
    const pointer = await this.local.getUserData('autobase/boot')
    if (!pointer) return

    const boot = c.decode(messages.BootRecord, pointer)

    await LocalState.clear(this.local)

    await this._nukeTipBatch(boot.key, boot.systemLength)

    const core = this.store.get({ key: boot.key, active: false, encryption: null })
    const encCore = await EncryptionView.setSystemEncryption(this, core)

    const batch = core.session({ name: 'batch' })
    await batch.ready()

    const info = await SystemView.getIndexedInfo(batch, boot.systemLength)
    await batch.close()

    for (const view of info.views) {
      // ensure any views ref'ed by system are consistent as well
      await this._nukeTipBatch(view.key, view.length)
    }

    if (boot.heads) this.hintWakeup(boot.heads)
    if (this.local.length) this.hintWakeup([{ key: this.local.key, length: this.local.length }])

    await core.close()
    if (encCore) await encCore.close()
  }

  _bumpWakeupPeer(peer) {
    if (this._coupler) this._coupler.update(peer.stream)
  }

  async _rotateLocalWriter(newLocal) {
    assert(!this.appending, 'Cannot rotate a newLocal writer if an append is in progress')

    const oldLocal = this.local

    if (this._applyState) await this._applyState.close()

    this.local = newLocal
    this.local.on('append', this._onlocalwriterchangeBound)

    this.localWriter = null
    this._updateLocalCore = null

    const store = this._viewStore.atomize()

    const local = store.getLocal()
    await local.ready()

    await LocalState.moveTo(oldLocal, local)

    await local.setUserData('referrer', this.key)
    if (this.encryptionKey) {
      if (this.blindEncryption) {
        const encrypted = await encryptionEncoding.encrypt(
          this.encryptionKey,
          this.blindEncryption.encrypt
        )
        await local.setUserData('autobase/blind-encryption', encrypted)
      } else {
        await local.setUserData('autobase/encryption', this.encryptionKey)
      }
    }

    await store.flush()
    await store.close()

    await this._primaryBootstrap.setUserData('autobase/local', local.key)

    await this._clearWriters()
    await oldLocal.close()

    // done, soft reboot

    await this._viewStore.updateLocal()

    await this._clearWriters()

    this._applyState = new ApplyState(this)
    await this._applyState.ready()
    await this._makeLinearizerFromViewState()

    this._caughtup = false

    this._rebooted()

    this.emit('rotate-local-writer')
  }

  async setLocal(key, { keyPair } = {}) {
    if (!this.opened) await this.ready()

    const manifest = keyPair
      ? { version: this.store.manifestVersion, signers: [{ publicKey: keyPair.publicKey }] }
      : null
    if (!key) key = Hypercore.key(manifest)
    // If the keys are the same, no need to rotate
    if (b4a.equals(key, this.local.key)) return

    const encryption = this.encryptionKey ? this.getWriterEncryption() : null

    const local = this.store.get({
      key,
      manifest,
      active: false,
      exclusive: true,
      encryption,
      valueEncoding: messages.OplogMessage
    })
    await local.ready()

    this._updateLocalCore = local

    let runs = 0
    while (!this._interrupting && this.appending && runs++ < 16) await this.update()
    await this._bump()
  }

  setWakeup(cap, discoveryKey) {
    if (this.wakeupSession) this.wakeupSession.destroy()
    if (!discoveryKey && b4a.equals(cap, this.key)) discoveryKey = this.discoveryKey
    this.wakeupSession = this.wakeupProtocol.session(
      cap,
      new WakeupHandler(this, discoveryKey || null)
    )

    // incase this session has active peers already, bump the coupler
    for (const peer of this.wakeupSession.peers) {
      if (peer.active) this._bumpWakeupPeer(peer)
    }
  }

  async _getMigrationPointer(key, length) {
    const core = this.store.get({ key, active: false, encryption: null })
    const encCore = await EncryptionView.setSystemEncryption(this, core)

    const min = core.manifest && core.manifest.prologue ? core.manifest.prologue.length : 0

    for (let i = length - 1; i >= min; i--) {
      if (!(await core.has(i))) continue

      const sys = new SystemView(core, { checkout: i + 1 })
      await sys.ready()

      let good = true

      for (const v of sys.views) {
        const vc = this.store.get({ key: v.key, active: false })
        await vc.ready()
        if (vc.length < v.length) good = false
        await vc.close()
      }

      await sys.close()
      if (!good) continue

      return i + 1
    }

    await core.close()
    if (encCore) await encCore.close()

    return min
  }

  // migrating from 6 -> latest
  async _migrate6(key, length) {
    const core = this.store.get({ key, active: false })
    await core.ready()
    const batch = core.session({ name: 'batch', overwrite: true, checkout: length })
    await batch.ready()
    await batch.close()
    await core.close()
  }

  // called by view-store for bootstrapping
  async _getSystemInfo() {
    const boot = await this._getBootRecord()
    if (!boot.key) return null

    const migrated = !!boot.heads
    const indexedLength = boot.systemLength

    if (migrated) {
      // ensure system batch is consistent on initial migration
      await this._migrate6(boot.key, indexedLength)
    }

    const core = this.store.get({ key: boot.key, encryption: null, active: false })
    await core.ready()

    const batch = core.session({ name: 'batch' })
    const encCore = await EncryptionView.setSystemEncryption(this, batch)

    await batch.ready()
    if (encCore) await encCore.ready()

    const info = await SystemView.getIndexedInfo(batch, indexedLength)

    if (encCore) await encCore.close()
    await batch.close()
    await core.close()

    if (info.version > MAX_AUTOBASE_VERSION) {
      throw new Error('Autobase upgrade required.')
    }

    // just compat
    if (migrated) {
      this.migrated = true

      for (const view of info.views) {
        // ensure any views ref'ed by system are consistent as well
        await this._migrate6(view.key, view.length)
      }

      if (boot.heads) this.hintWakeup(boot.heads)
      if (this.local.length) this.hintWakeup([{ key: this.local.key, length: this.local.length }])
    }

    return {
      key: boot.key,
      indexers: info.indexers,
      views: info.views,
      entropy: info.entropy
    }
  }

  // called by the apply state for bootstrapping
  async _getBootRecord() {
    await this._preopen

    const pointer = await this.local.getUserData('autobase/boot')

    const boot = pointer
      ? c.decode(messages.BootRecord, pointer)
      : {
          version: BOOT_RECORD_VERSION,
          key: null,
          systemLength: 0,
          indexersUpdated: false,
          fastForwarding: false,
          recoveries: RECOVERIES,
          heads: null
        }

    if (boot.heads) {
      const len = await this._getMigrationPointer(boot.key, boot.systemLength)
      if (len !== boot.systemLength)
        this._warn(
          new Error(
            'Invalid pointer in migration, correcting (' + len + ' vs ' + boot.systemLength + ')'
          )
        )
      boot.systemLength = len
    }

    return boot
  }

  static async getBootRecord(store, key) {
    const result = await boot(store, key, { exclusive: false })
    await result.bootstrap.close()
    await result.local.close()
    return result.boot
  }

  _interrupt(reason) {
    assert(!!this._applyState.applying, 'Interrupt is only allowed in apply')
    this._interrupting = true
    if (reason) this.interrupted = reason
    throw INTERRUPT
  }

  async flush() {
    if (this._flushing === 0) return
    return this._flushSignal.wait()
  }

  async advance() {
    if (this.opened === false) await this.ready()
    await this._advancing
  }

  recouple() {
    if (this._coupler) this._coupler.destroy()
    const core = this._viewStore.getSystemCore()
    this._coupler = new CoreCoupler(core, this._wakeupPeerBound)
  }

  _updateBootstrapWriters() {
    const writers = this.linearizer.getBootstrapWriters()

    // first clear all, but without applying it for churn reasons
    for (const writer of this._bootstrapWriters) {
      writer.isBootstrap = false
      writer.isCoupled = false
    }

    // all passed are bootstraps
    for (const writer of writers) {
      writer.isCoupled = true
      writer.setBootstrap(true)
    }

    // reset activity on old ones, all should be in sync now
    for (const writer of this._bootstrapWriters) {
      if (writer.isBootstrap === false) writer.setBootstrap(false)
    }

    this._bootstrapWriters = writers
    this._bootstrapWritersChanged = false
  }

  async _openLinearizer() {
    if (this._applyState.system.bootstrapping) {
      await this._makeLinearizer(null)
      this._bootstrapLinearizer()
      return
    }

    await this._makeLinearizerFromViewState()
  }

  async _catchupApplyState() {
    if (await this._applyState.shouldMigrate()) {
      await this._migrate()
    } else if (!(await this._applyState.catchup(this.linearizer))) {
      return false
    }

    this._caughtup = true
    return true
  }

  async _open() {
    this._preopen = this._runPreOpen()
    await this._preopen

    if (this.closing) return

    this._applyState = new ApplyState(this)

    try {
      await this._applyState.ready()
    } catch (err) {
      if (this.closing) return

      try {
        await this._applyState.close()
      } catch {}

      try {
        await this.core.ready()
      } catch {}

      this._applyState = null
      if (this.closing) return

      throw err
    }

    try {
      await this._openLinearizer()
      await this.core.ready()
      await this._wakeup.ready()
    } catch (err) {
      if (this.closing) return
      throw err
    }

    if (this.core.length - this._applyState.indexedLength > this._ackTickThreshold) {
      this._ackTick = this._ackTickThreshold
    }
    if (this.localWriter && this._ackInterval) {
      this._startAckTimer()
    }

    this._updateBootstrapWriters()

    this.recouple()
    this._queueFastForward()

    // queue a full bump that handles wakeup etc (not legal to wait for that here)
    this._queueBump()
  }

  async _close() {
    await this.flush() // flush all pending non network io
    this._interrupting = true
    await Promise.resolve() // defer one tick

    if (this.wakeupSession) this.wakeupSession.destroy()
    if (this.wakeupOwner) this.wakeupProtocol.destroy()

    if (this.fastForwarding) await this.fastForwarding.close()

    if (this._coupler) this._coupler.destroy()
    this._coupler = null
    this._waiting.notify(null)

    await this.activeWriters.clear()

    const closing = this._advancing ? this._advancing.catch(safetyCatch) : null

    await this._clearWriters()
    if (this._primaryBootstrap) await this._primaryBootstrap.close()
    await this.local.close()

    if (this._ackTimer) {
      this._ackTimer.stop()
      await this._ackTimer.flush()
    }

    await this._wakeup.close()

    if (this._hasClose) await this._handlers.close(this.view)
    if (this._applyState) await this._applyState.close()

    await this._viewStore.close()
    await this.core.close()
    await this.store.close()

    if (this._writable) this._writable.resolve(false)

    await closing
  }

  getLastError() {
    return this._lastError
  }

  _onError(err) {
    if (this.closing) return

    this._lastError = err

    if (err === INTERRUPT) {
      this.emit('interrupt', this.interrupted)
      this.emit('update')
      return
    }

    this.close().catch(safetyCatch)

    // if no one is listening we should crash! we cannot rely on the EE here
    // as this is wrapped in a promise so instead of nextTick throw it
    if (ReadyResource.listenerCount(this, 'error') === 0) {
      crashSoon(err)
      return
    }

    this.emit('error', err)
  }

  async _closeWriter(w) {
    this.activeWriters.delete(w)
    await w.close()
  }

  async _gcWriters() {
    // just return early, why not
    if (this._checkWriters.length === 0) return

    while (this._checkWriters.length > 0) {
      const w = this._checkWriters.pop()

      // doesnt hurt
      w.updateActivity()

      if (!w.flushed()) continue

      const unqueued = this._wakeup.unqueue(w.core.key, w.core.length)

      if (!unqueued || w.isActiveIndexer) continue
      if (this.localWriter === w) continue

      await this._closeWriter(w)
    }

    await this._wakeup.flush()
  }

  _startAckTimer() {
    if (this._ackTimer) return
    this._ackTimer = new Timer(this._backgroundAck.bind(this), this._ackInterval)
    this._bumpAckTimer()
  }

  _bumpAckTimer() {
    if (!this._ackTimer) return
    this._ackTimer.bump()
  }

  async update() {
    if (this.opened === false) await this.ready()

    try {
      await this._bump()
      if (this._acking) await this._bump() // if acking just rebump incase it was triggered from above...
    } catch (err) {
      if (this._interrupting) return
      throw err
    }
  }

  // runs in bg, not allowed to throw
  // TODO: refactor so this only moves the writer affected to a updated set
  async _onremotewriterchange() {
    this._bumpAckTimer()

    try {
      await this._bump()
    } catch {}
  }

  _onlocalwriterchange() {
    if (!this.localWriter || this.localWriter.isRemoved) this._queueBump()
  }

  _onwakeup() {
    this._needsWakeup = true
    this._queueBump()
  }

  isFastForwarding() {
    if (this.fastForwardTo !== null) return true
    return this.fastForwardEnabled && this.fastForwarding !== null
  }

  _backgroundAck() {
    return this.ack(true)
  }

  async ack(bg = false) {
    if (this.opened === false) await this.ready()
    if (this.localWriter === null || this._acking || this._interrupting || this._appending !== null)
      return

    if (this._applyState === null) {
      try {
        await this._bump()
      } catch {}
      if (this._applyState === null || this._interrupting) return
    }

    const applyState = this._applyState
    if (applyState.opened === false) await applyState.ready()

    const isPendingIndexer = applyState.isLocalPendingIndexer()

    // if no one is waiting for our index manifest, wait for FF before pushing an ack
    if ((!isPendingIndexer && this.isFastForwarding()) || this._interrupting) return

    const isIndexer = applyState.isLocalIndexer() || isPendingIndexer
    if (!isIndexer) return

    this._acking = true

    try {
      await this._bump()
    } catch (err) {
      if (!this._interrupting) throw err
    }

    if (this._interrupting || !this.localWriter || this.localWriter.closed) {
      this._acking = false
      return
    }

    // avoid lumping acks together due to the bump wait here
    if (this._ackTimer && bg) await this._ackTimer.asapStandalone()
    if (this._interrupting || applyState.closing) {
      this._acking = false
      return
    }

    const alwaysWrite = isPendingIndexer || (await applyState.shouldWrite())
    if (this._interrupting || applyState.closing) {
      this._acking = false
      return
    }

    const hasPendingIndexers = applyState.system.indexers.length > this.linearizer.indexers.length

    if (alwaysWrite || this.linearizer.shouldAck(this.localWriter, hasPendingIndexers)) {
      try {
        if (this.localWriter && !this.localWriter.closed) await this.append(null)
      } catch (err) {
        if (!this._interrupting) throw err
      }
    }

    if (!this._interrupting) {
      this._updateAckThreshold()
      this._bumpAckTimer()
    }

    this._acking = false
  }

  views() {
    if (this._applyState) return this._applyState.store.listViews()
    return this._viewStore.listViews()
  }

  batch() {
    return new AppendBatch(this)
  }

  async append(value, opts) {
    if (this.opened === false) await this.ready()
    if (this._advancing !== null) await this._advancing
    while (this.activeBatch) await this.activeBatch.flushed()
    return this._appendBatch(value, opts)
  }

  async _appendBatch(value, opts) {
    if (this._interrupting) throw new Error('Autobase is closing')
    if (value && this.valueEncoding !== BINARY_ENCODING)
      value = normalize(this.valueEncoding, value)

    const optimistic = !!opts && !!opts.optimistic && !!value

    // we wanna allow acks so interdexers can flush
    if (
      !optimistic &&
      (this.localWriter === null || (this.localWriter.isRemoved && value !== null))
    ) {
      throw new Error('Not writable')
    }

    if (this._appending === null) this._appending = []

    let len = 0
    if (Array.isArray(value)) {
      for (const v of value) len = this._append(v)
    } else {
      len = this._append(value)
    }

    const localLength = this.local.length

    if (optimistic) this._optimistic = this._appending.length - 1
    const target = this._appended + this._appending.length

    // await in case append is in current tick
    if (this._advancing) await this._advancing

    let runs = 0

    // bump until we've flushed the nodes
    while (this._appended < target && !this._interrupting) {
      await this._bump()
      // safety
      if (runs++ >= 16 && this.localWriter && this.localWriter.idle()) break
    }

    if (this._advancing) await this._advancing
    if (this._interrupting) throw new Error('Autobase is closing')

    return localLength + len
  }

  _append(value) {
    // if prev value is an ack that hasnt been flushed, skip it
    if (this._appending.length > 0) {
      if (value === null) return this._appending.length
      if (this._appending[this._appending.length - 1] === null) {
        this._appending.pop()
      }
    }
    return this._appending.push(value)
  }

  static decodeValue(value, opts) {
    return decodeValue(value, opts)
  }

  static encodeValue(value, opts) {
    return encodeValue(value, opts)
  }

  static async getLocalKey(store, opts = {}) {
    const core = opts.keyPair
      ? store.get({ ...opts, active: false })
      : store.get({ ...opts, name: 'local', active: false })
    await core.ready()
    const key = core.key
    await core.close()
    return key
  }

  static getLocalCore(store, handlers, encryptionKey) {
    const encryption = !encryptionKey ? null : { key: encryptionKey }
    const opts = {
      ...handlers,
      compat: false,
      active: false,
      exclusive: true,
      valueEncoding: messages.OplogMessage,
      encryption
    }
    return opts.keyPair ? store.get(opts) : store.get({ ...opts, name: 'local' })
  }

  static async getUserData(core) {
    const view = await core.getUserData('autobase/view')

    return {
      referrer: await core.getUserData('referrer'),
      view: view ? b4a.toString(view) : null
    }
  }

  static async isAutobase(core, opts = {}) {
    const block = await core.get(0, opts)
    if (!block) throw new Error('Core is empty.')
    if (!b4a.isBuffer(block)) return isAutobaseMessage(block)

    try {
      const m = c.decode(messages.OplogMessage, block)
      return isAutobaseMessage(m)
    } catch {
      return false
    }
  }

  // no guarantees where the user data is stored, just that its associated with the base
  async setUserData(key, val) {
    await this._preopen
    const core = this._primaryBootstrap === null ? this.local : this._primaryBootstrap

    await core.setUserData(key, val)
  }

  async getUserData(key) {
    await this._preopen
    const core = this._primaryBootstrap === null ? this.local : this._primaryBootstrap

    return await core.getUserData(key)
  }

  _needsLocalWriter() {
    return this.localWriter === null || this.localWriter.closed
  }

  // no guarantees about writer.isActiveIndexer property here
  async _getWriterByKey(key, len, seen, allowGC, isAdded, system) {
    assert(this._draining === true || (this.opening && !this.opened) || this._optimistic > -1)

    await this._lock.lock()

    if (this._interrupting) {
      this._lock.unlock()
      throw new Error('Autobase is closing')
    }

    try {
      let w = this.activeWriters.get(key)

      const alreadyActive = !!w
      const sys = system || this._applyState.system
      const writerInfo = await sys.get(key)

      if (len === -1) {
        if (!allowGC && writerInfo === null) {
          if (w) w.isRemoved = !isAdded
          return null
        }

        len = writerInfo === null ? 0 : writerInfo.length
      }

      const isActive = writerInfo !== null && (isAdded || !writerInfo.isRemoved)
      const isRemoved = !isActive

      if (w) {
        w.isRemoved = isRemoved
      } else {
        w = this._makeWriter(key, len, isActive, isRemoved)
        if (!w) return null
      }

      if (isRemoved && sys.bootstrapping && b4a.equals(w.core.key, this.key)) {
        w.isRemoved = false
      }

      if (this._isLocalCore(w.core) && this._needsLocalWriter()) {
        this._setLocalWriter(w)
      }

      w.seen(seen)

      if (alreadyActive) return w

      await w.ready()

      if (this._isLocalCore(w.core) && this._needsLocalWriter()) {
        this._setLocalWriter(w)
      }

      if (allowGC && w.flushed()) {
        this._wakeup.unqueue(key, len)
        if (w !== this.localWriter) {
          await w.close()
          return w
        }
      }

      this.activeWriters.add(w)
      this._checkWriters.push(w)

      assert(w.opened)
      assert(!w.closed)

      w.updateActivity()
      return w
    } finally {
      this._lock.unlock()
    }
  }

  _updateAll() {
    const p = []
    for (const w of this.activeWriters) p.push(w.update(null).catch(safetyCatch))
    return Promise.all(p)
  }

  getWriterEncryption() {
    if (!this.encryptionKey) return null
    return this.encryption.getWriterEncryption()
  }

  _makeWriterCore(key) {
    if (this.closing) throw new Error('Autobase is closing')
    if (this._interrupting) throw INTERRUPT()

    const local = b4a.equals(key, this.local.key)
    const encryption = this.getWriterEncryption()

    const core = local
      ? this.local.session({ valueEncoding: messages.OplogMessage, encryption, active: false })
      : this.store.get({
          key,
          compat: false,
          writable: false,
          valueEncoding: messages.OplogMessage,
          encryption,
          active: false
        })

    return core
  }

  _makeWriter(key, length, isActive, isRemoved) {
    const core = this._makeWriterCore(key)
    const w = new Writer(this, core, length, isRemoved)

    if (this._isLocalCore(core)) {
      if (isActive) this._setLocalWriter(w) // only set active writer
      return w
    }

    core.on('append', this._onremotewriterchangeBound)
    core.on('download', this._onremotewriterchangeBound)
    core.on('manifest', this._onremotewriterchangeBound)

    return w
  }

  _updateLinearizer(indexers, heads) {
    // only current active indexers are reset to true below
    for (const w of this.activeWriters) w.isActiveIndexer = false
    if (this.localWriter) this.localWriter.isActiveIndexer = false

    for (const writer of indexers) writer.isActiveIndexer = true

    if (this._isActiveIndexer() && !this.isIndexer) {
      this._setLocalIndexer()
    } else if (!this._isActiveIndexer() && this.isIndexer) {
      this._clearLocalIndexer()
    }

    this.linearizer = new Linearizer(indexers, { heads, writers: this.activeWriters })

    this._updateAckThreshold()
  }

  async _updateLocalWriter(sys) {
    if (this.localWriter !== null && !this.localWriter.closed) return
    await this._getWriterByKey(this.local.key, -1, 0, true, false, sys)
  }

  async _bootstrapLinearizer() {
    const bootstrap = this._makeWriter(this.key, 0, true, false)

    this.activeWriters.add(bootstrap)
    this._checkWriters.push(bootstrap)
    await bootstrap.ready()
    this._ensureWakeup(bootstrap)

    this._updateLinearizer([bootstrap], [])
  }

  async _makeLinearizer(sys) {
    if (sys === null) {
      return this._bootstrapLinearizer()
    }

    if (this.opened || (await sys.hasLocal(this.local.key))) {
      await this._updateLocalWriter(sys)
    }

    const indexers = []

    for (const head of sys.indexers) {
      const writer = await this._getWriterByKey(head.key, head.length, 0, false, false, sys)
      indexers.push(writer)
    }

    if (!this._isActiveIndexer()) {
      for (const key of sys.pendingIndexers) {
        if (b4a.equals(key, this.local.key)) {
          this._setLocalIndexer()
          break
        }
      }
    }

    this._updateLinearizer(indexers, sys.heads)

    for (const { key, length } of sys.heads) {
      await this._getWriterByKey(key, length, 0, false, false, sys)
    }
  }

  async _clearWriters() {
    await this.activeWriters.clear()
    if (this.localWriter !== null) await this.localWriter.close()
    this._checkWriters = []
  }

  async _moveTo() {
    assert(this._applyState.closed)
    for (const ref of this._viewStore.byName.values()) {
      if (!ref.moveTo) continue
      const [batch, next] = ref.moveTo
      ref.moveTo = null
      await ref.batch.state.moveTo(batch, batch.length)
      await batch.close()
      ref.migrated(this, next)
    }
  }

  async _makeLinearizerFromViewState() {
    const sys = await this._applyState.getIndexedSystem()
    await this._makeLinearizer(sys)
    await sys.close()
  }

  async _runForceFastForward() {
    await this.core.ready()
    if (this.closing) return
    const rec = this._applyState ? await this._applyState.recoverAt() : null
    await this._runFastForward(
      new FastForward(this, this.core.key, { force: true, length: rec ? rec.length : 0 })
    )
  }

  // general repair method for trying to recover
  async repair() {
    await this.forceFastForward()
  }

  async forceFastForward() {
    if (this.isFastForwarding()) return
    await this._runForceFastForward()
    await this.update()
  }

  async _applyFastForward() {
    if (
      !this.fastForwardTo.force &&
      this.fastForwardTo.length < this.core.length + this.fastForwardTo.minimum
    ) {
      this.fastForwardTo = null
      this._updateActivity()
      // still not worth it
      return
    }

    const changes = this._hasUpdate ? new UpdateChanges(this) : null
    if (changes) changes.track(this._applyState)

    // close existing state
    if (this._applyState) await this._applyState.close()

    const { key, length, views, indexers, manifestVersion, entropy } = this.fastForwardTo

    const from = this.core.signedLength
    const ffed = new Set()

    this._flushing++
    try {
      const store = this._viewStore.atomize()

      const systemRef = await this._viewStore.findViewByKey(key, indexers, manifestVersion, entropy)
      const migrated = !b4a.equals(key, systemRef.core.key)

      ffed.add(systemRef)

      if (migrated) {
        await this._applyFastForwardMigration(systemRef, { key, length })
      } else {
        await systemRef.catchup(store.atom, length)
      }

      for (const v of views) {
        const ref = await this._viewStore.findViewByKey(v.key, indexers, manifestVersion, entropy)
        if (!ref) continue // unknown, view ignored

        const migrated = !b4a.equals(ref.core.key, v.key)

        ffed.add(ref)

        if (migrated) {
          await this._applyFastForwardMigration(ref, v)
        } else {
          await ref.catchup(store.atom, v.length)
        }
      }

      if (ffed.size !== store.getViewCount()) {
        for (const ref of store.getViews()) {
          if (ffed.has(ref)) continue
          await ref.catchup(store.atom, 0) // its gone
        }
      }

      // migrate zero length cores
      if (migrated) {
        const manifests = await this._viewStore.getIndexerManifests(indexers)

        for (const [name, ref] of this._viewStore.byName) {
          if (ffed.has(ref)) continue
          await this._migrateView(manifests, null, name, 0, manifestVersion, entropy, [], null)
        }
      }

      const value = c.encode(messages.BootRecord, {
        version: BOOT_RECORD_VERSION,
        key,
        systemLength: length,
        indexersUpdated: false,
        fastForwarding: true,
        recoveries: RECOVERIES
      })

      const local = store.getLocal()
      await local.ready()
      await local.setUserData('autobase/boot', value)

      await LocalState.clear(local)

      await store.flush()
      await store.close()
    } finally {
      if (--this._flushing === 0) this._flushSignal.notify()
    }

    for (const ref of this._viewStore.byName.values()) await ref.release()

    this.recoveries = RECOVERIES
    this.fastForwardTo = null
    this._queueFastForward()

    await this._clearWriters()
    await this._moveTo()
    const to = this.core.signedLength

    if (changes) changes.finalise()

    this._applyState = new ApplyState(this)
    await this._applyState.ready()

    if (changes) await this._handlers.update(this._applyState.view, changes)

    if (await this._applyState.shouldMigrate()) {
      await this._migrate()
    } else {
      await this._makeLinearizerFromViewState()
      await this._applyState.catchup(this.linearizer)
    }

    if (!this.localWriter || this.localWriter.closed) {
      await this._updateLocalWriter(this._applyState.system)
    }

    this._caughtup = true

    this._rebooted()
    this.emit('fast-forward', to, from)
  }

  // TODO: not atomic in regards to the ff, fix that
  async _applyFastForwardMigration(ref, v) {
    await ref.batch.ready()

    const next = this.store.get(v.key)
    await next.ready()

    const prologue = next.manifest && next.manifest.prologue

    if (prologue && prologue.length > 0 && ref.core.length >= prologue.length) {
      try {
        await next.core.copyPrologue(ref.core.state)
      } catch {
        // we might be missing some nodes for this, just ignore, only an optimisation
      }
    }

    const batch = next.session({ name: 'batch', overwrite: true, checkout: v.length })
    await batch.ready()

    // remake the batch, reset from our prologue in case it replicated inbetween
    // TODO: we should really have an HC function for this

    ref.moveTo = [batch, next]
  }

  async _migrateView(
    indexerManifests,
    source,
    name,
    indexedLength,
    manifestVersion,
    entropy,
    linked,
    manifestData
  ) {
    const ref = this._viewStore.byName.get(name)
    await ref.batch.ready()

    const prologue =
      indexedLength === 0
        ? null
        : { length: indexedLength, hash: await source.treeHash(indexedLength) }

    if (manifestData === null && ref.core.manifest.userData !== null) {
      manifestData = ref.core.manifest.userData
    }

    const next = this._viewStore.getViewCore(
      indexerManifests,
      name,
      prologue,
      manifestVersion,
      entropy,
      linked,
      manifestData
    )
    await next.ready()

    if (indexedLength > 0) {
      await next.core.copyPrologue(source.state)
    }

    // remake the batch, reset from our prologue in case it replicated inbetween
    // TODO: we should really have an HC function for this
    const batch = next.session({ name: 'batch', overwrite: true, checkout: indexedLength })
    await batch.ready()

    if (source !== null) {
      while (batch.length < source.length) {
        await batch.append(await source.get(batch.length))
      }
    }

    ref.moveTo = [batch, next]

    return ref
  }

  async _premigrate() {
    this._flushing++
    try {
      const length = this._applyState.indexedLength
      const system = this._applyState.system

      const info = await system.getIndexedInfo(length)
      const indexerManifests = await this._viewStore.getIndexerManifests(info.indexers)

      const { views, systemView, encryptionView } = this._applyState

      const manifestVersion = this._applyState.system.core.manifest.version

      for (const view of views) {
        const v = this._applyState.getViewFromSystem(view, info)
        const indexedLength = v ? v.length : 0

        const ref = this._viewStore.getViewByName(view.name)
        const source = ref.getCore()
        await source.ready()

        await this._migrateView(
          indexerManifests,
          source,
          view.name,
          indexedLength,
          manifestVersion,
          info.entropy,
          null,
          null
        )
      }

      const source = encryptionView.ref.getCore()
      await source.ready()

      const enc = await this._migrateView(
        indexerManifests,
        source,
        '_encryption',
        info.encryptionLength,
        manifestVersion,
        info.entropy,
        null,
        null
      )

      const linked = [enc.core.key]

      const sysCore = systemView.ref.getCore()
      const ref = await this._migrateView(
        indexerManifests,
        sysCore,
        '_system',
        length,
        manifestVersion,
        info.entropy,
        linked,
        null,
        null
      )

      const sysKey = ref.getNextKey()
      if (sysKey === null) {
        throw new Error('Migration failed, expected core to be moved')
      }

      return sysKey
    } finally {
      if (--this._flushing === 0) this._flushSignal.notify()
    }
  }

  async _migrate() {
    return this._reboot(await this._premigrate())
  }

  async _reboot(key) {
    await this._clearWriters()
    await this._makeLinearizerFromViewState()

    await this._applyState.finalize(key)
    await this._moveTo()

    this._applyState = new ApplyState(this)

    await this._applyState.ready()
    await this._applyState.catchup(this.linearizer)

    // end soft shutdown

    this._queueFastForward()

    this._rebooted()
  }

  _rebooted() {
    this.recouple()
    this._updateActivity()

    this.emit('reboot')

    // ensure we re-evalute our state
    this._bootstrapWritersChanged = true
    this._needsWakeup = true

    this.updating = true
    this._queueBump()
  }

  _setLocalWriter(w) {
    this.localWriter = w
    if (this._ackInterval) this._startAckTimer()
  }

  _unsetLocalWriter() {
    if (!this.localWriter) return

    this._closeWriter(this.localWriter)
    if (this.localWriter.isActiveIndexer) this._clearLocalIndexer()

    this.localWriter = null
  }

  _setLocalIndexer() {
    assert(this.localWriter !== null)

    this.isIndexer = true
    this.emit('is-indexer')
  }

  _clearLocalIndexer() {
    assert(this.localWriter !== null)

    if (this._ackTimer) this._ackTimer.stop()

    this.isIndexer = false
    this._ackTimer = null

    this.emit('is-non-indexer')
  }

  _isLocalCore(core) {
    return core.writable && core.id === this.local.id
  }

  _addLocalHeads() {
    // not writable atm, will prop be writable in a subsequent bump tho
    if (!this.localWriter || this.localWriter.closed) return null
    // safety, localwriter is still processing, should prop be an assertion
    if (!this.localWriter.idle()) return null

    const length = this._optimistic === -1 ? this._appending.length : this._optimistic || 1

    const nodes = new Array(length)
    for (let i = 0; i < length; i++) {
      const heads = this.linearizer.getHeads()
      const deps = new Set(this.linearizer.heads)
      const batch = length - i
      const value = this._appending[i]

      const node = this.localWriter.append(value, heads, batch, deps, this._optimistic === 0)

      this.linearizer.addHead(node)
      nodes[i] = node
    }

    return nodes
  }

  _flushLocalHeads(length) {
    this._appending = length === this._appending.length ? null : this._appending.slice(length)
    this._appended += length

    if (this._optimistic > -1 && this._optimistic < length) this._optimistic = -1
  }

  async _addRemoteHeads() {
    let added = 0

    while (
      added < REMOTE_ADD_BATCH ||
      (this.bigBatches && !this._indexersIdle() && added < REMOTE_ADD_BATCH_SANITY)
    ) {
      await this._updateAll()

      let advanced = 0

      for (const w of this.activeWriters) {
        let node = w.advance()
        if (node === null) continue

        advanced += node.batch

        while (true) {
          this.linearizer.addHead(node)
          if (node.batch === 1) break
          node = w.advance()
        }
      }

      if (advanced === 0) {
        if (this.bigBatches && !this._indexersIdle() && (await this._waitForIndexers())) continue
        break
      }

      added += advanced
    }

    return added
  }

  async _waitForIndexers() {
    const promises = []

    for (const w of this.linearizer.indexers) {
      if (w.idle()) continue
      if (await w.core.has(w.length)) continue
      promises.push(w.core.get(w.length, { timeout: 3000 }))
    }

    for (const result of await Promise.allSettled(promises)) {
      if (result.status !== 'rejected') return true
    }

    return false
  }

  _indexersIdle() {
    for (const w of this.linearizer.indexers) {
      if (!w.idle()) return false
    }
    return true
  }

  async _drain() {
    const writable = this.writable

    while (!this._interrupting && !this.paused) {
      if (this.local.recovering) {
        try {
          await this.local.recover()
        } catch {
          await this._runForceFastForward()
        }
        continue
      }

      if (this.fastForwardTo !== null) {
        await this._applyFastForward()
        continue // revaluate conditions...
      }

      // we defer this to post ready so its not blocking reading the views
      if (this._caughtup === false) {
        // if the catchup fails, just force ff it to recover, less user pain
        if (!(await this._catchupApplyState())) {
          await this._runForceFastForward()
        }
        continue
      }

      const remoteAdded = await this._addRemoteHeads()
      const localNodes = this._appending !== null ? this._addLocalHeads() : null

      if (this._interrupting) return

      if (remoteAdded > 0 || localNodes !== null) {
        this.updating = true
      }

      const u = this.linearizer.update()
      const update = u
        ? await this._applyState.update(u, localNodes)
        : { reboot: false, migrated: false }

      if (localNodes) this._flushLocalHeads(localNodes.length)

      if (!update.reboot) {
        if (this._applyState.shouldFlush()) {
          await this._applyState.flush()
          this.updating = true
        }

        if (this._checkWriters.length > 0) {
          await this._gcWriters()
          continue // rerun the update loop as a writer might have been added
        }
        if (remoteAdded >= REMOTE_ADD_BATCH) continue
        break
      }

      await this._gcWriters()
      await this._reboot(this._applyState.key)
    }

    // emit state changes post drain
    if (writable !== this.writable) {
      if (this.writable && this._writable) this._writable.resolve(true)
      this.emit(writable ? 'unwritable' : 'writable')
    }
  }

  _wakeupPeer(stream) {
    if (!this.wakeupSession) return
    const wakeup = this._getWakeup()
    if (wakeup.length === 0) return
    this.wakeupSession.announceByStream(stream, wakeup)
  }

  _getWakeup() {
    const writers = []

    for (const w of this.activeWriters) {
      if (w.isActiveIndexer || w.flushed()) continue
      writers.push({ key: w.core.key, length: w.length })
    }

    return writers
  }

  async _wakeupWriter(key, length) {
    this._ensureWakeup(await this._getWriterByKey(key, -1, length, true, false, null))
  }

  // ensure wakeup on an existing writer (the writer calls this in addition to above)
  _ensureWakeup(w) {
    if (w === null || w.isBootstrap === true) return
    w.setBootstrap(true) // even if turn false at end of drain, hypercore makes them linger a bit so no churn
    this._bootstrapWriters.push(w)
    this._bootstrapWritersChanged = true
  }

  async _drainWakeup() {
    const promises = []

    // warmup all the below gets
    if (this._needsWakeup) {
      for (const { key, length } of this._wakeup) {
        const w = this.activeWriters.get(key)
        if (w) {
          if (w.length < length) w.seen(length)
          continue
        }
        promises.push(this._applyState.system.get(key))
      }

      if (this._needsWakeupHeads) {
        for (const { key } of await this._applyState.system.heads) {
          if (this.activeWriters.has(key)) continue
          promises.push(this._applyState.system.get(key))
        }
      }
    }
    for (const [hex, length] of this._wakeupHints) {
      const key = b4a.from(hex, 'hex')
      if (length !== -1) {
        const w = this.activeWriters.get(key)
        if (w) {
          if (w.length < length) w.seen(length)
          continue
        }
      }
      promises.push(this._applyState.system.get(key))
    }

    await Promise.allSettled(promises)

    if (this._needsWakeup === true) {
      this._needsWakeup = false

      for (const { key, length } of this._wakeup) {
        if (this.activeWriters.has(key)) continue
        await this._wakeupWriter(key, length)
      }

      if (this._needsWakeupHeads === true) {
        this._needsWakeupHeads = false

        for (const { key } of await this._applyState.system.heads) {
          if (this.activeWriters.has(key)) continue
          await this._wakeupWriter(key, 0)
        }
      }
    }

    for (const [hex, length] of this._wakeupHints) {
      const key = b4a.from(hex, 'hex')
      if (this.activeWriters.has(key)) continue
      if (length !== -1) {
        const info = await this._applyState.system.get(key)
        if (info && length <= info.length) continue // stale hint
      }
      await this._wakeupWriter(key, length === -1 ? 0 : length)
    }

    this._wakeupHints.clear()
  }

  pause() {
    this.paused = true
  }

  resume() {
    this.paused = false
    this._queueBump()
  }

  waitForWritable() {
    if (this.writable) return Promise.resolve(true)
    if (!this._writable) this._writable = rrp()
    return this._writable.promise
  }

  async _drainWithInterupt() {
    while (true) {
      try {
        await this._drain()
        return
      } catch (err) {
        if (this.closing || !this.fastForwardTo) throw err
        if (Date.now() - this.fastForwardFailedAt < MIN_FF_WAIT) throw err
        this.fastForwardFailedAt = Date.now()
        // if an FF is enabled retry
      }
    }
  }

  async _advance() {
    if (this.opened === false) await this.ready()
    if (this.paused || this._interrupting) return

    this._draining = true

    if (this._updateLocalCore !== null) {
      await this._rotateLocalWriter(this._updateLocalCore)
    }

    const local = this.local.length

    try {
      await this._drainWithInterupt()

      // must run post drain so the linearizer is caught up
      if (this._caughtup && (this._needsWakeup === true || this._wakeupHints.size > 0))
        await this._drainWakeup()

      // check if we should update local writer
      if (!this.localWriter || this.localWriter.closed) {
        await this._updateLocalWriter(this._applyState.system)
      }

      this._draining = false
    } catch (err) {
      this._onError(err)
      return
    }

    if (this._interrupting) return

    if (this.localWriter && !this.localWriter.closed) {
      if (this._applyState.isLocalPendingIndexer()) this.ack().catch(noop)
      else if (this._triggerAckAsap()) this._ackTimer.asap()
    }

    // keep bootstraps in sync with linearizer
    if (this.updating === true || this._bootstrapWritersChanged === true) {
      this._updateBootstrapWriters()
    }

    if (this.updating === true) {
      this.updating = false

      if (local !== this.local.length) this._resetAckTick()
      else this._ackTick++

      if (!this._interrupting) this.emit('update')
      this._waiting.notify(null)
    }

    if (!this._interrupting) await this._gcWriters()
  }

  _triggerAckAsap() {
    if (!this._ackTimer) return false

    // flush if threshold is reached and we are not already acking
    if (this._ackTickThreshold && !this._acking && this._ackTick >= this._ackTickThreshold) {
      if (this._ackTimer) {
        for (const w of this.linearizer.indexers) {
          if (w.core.length > w.length) return false // wait for the normal ack cycle in this case
        }
      }

      return true
    }

    return false
  }

  _queueFastForward() {
    if (!this.core.opened) return
    // should have a better way to get this
    const latestSignedLength = this.core.core.state.length

    if (!this.fastForwardEnabled || this.fastForwarding !== null || this._interrupting) return

    if (latestSignedLength - this.core.length < this.fastForwardMinimum) return
    if (this.fastForwardTo !== null) return
    if (Date.now() - this.fastForwardFailedAt < MIN_FF_WAIT) return

    this._runFastForward(
      new FastForward(this, this.core.key, { minimum: this.fastForwardMinimum })
    ).catch(noop)
  }

  _queueStaticFastForward(key) {
    if (!this.fastForwardEnabled || this.fastForwarding !== null || this._interrupting) return
    if (this.fastForwardTo !== null) return
    if (Date.now() - this.fastForwardFailedAt < MIN_FF_WAIT) return

    this._runFastForward(new FastForward(this, key, { verified: false })).catch(noop)
  }

  _updateActivity() {
    this.activeWriters.updateActivity()
    if (this._applyState) {
      if (this.isFastForwarding()) this._applyState.pause()
      else this._applyState.resume()
    }

    // in case we ignored wakeups case we were fast forwarding, request them now if not
    if (this._needsWakeupRequest && !this.isFastForwarding() && this.wakeupSession) {
      this._needsWakeupRequest = false

      this.wakeupSession.broadcastLookup({})
    }
  }

  _preferFastForward() {
    this.fastForwardMinimum = 1
    this._queueFastForward()
  }

  _postApply() {
    this.fastForwardMinimum = FastForward.MINIMUM
  }

  async _runFastForward(ff) {
    this.fastForwarding = ff

    this._updateActivity()

    const result = await ff.upgrade()
    await ff.close()

    if (this.fastForwarding === ff) this.fastForwarding = null

    if (!result) {
      if (ff.failed) this.fastForwardFailedAt = Date.now()
      else this._queueFastForward()
      this._updateActivity()
      return
    }

    this.fastForwardFailedAt = 0
    this.fastForwardTo = result

    if (this._applyState && this._applyState.applying && this.fastForwardMinimum === 1) {
      await this._applyState.close()
    }

    this._bumpAckTimer()
    this._queueBump()
  }

  // triggered from apply
  async _addWriter(key, sys) {
    // just compat for old version
    assert(!!this._applyState.applying, 'System changes are only allowed in apply')

    const writer =
      (await this._getWriterByKey(key, -1, 0, false, true, sys)) ||
      this._makeWriter(key, 0, true, false)
    await writer.ready()

    if (!this.activeWriters.has(key)) {
      this.activeWriters.add(writer)
      this._checkWriters.push(writer)
      this._ensureWakeup(writer)
    }

    // fetch any nodes needed for dependents
    this._queueBump()
  }

  // triggered from apply
  _removeWriter(key) {
    // just compat for old version
    const w = this.activeWriters.get(key)
    if (w) w.isRemoved = true

    this._queueBump()
  }

  removeable(key) {
    return this._applyState ? this._applyState.removeable(key) : false
  }

  _updateAckThreshold() {
    if (this._ackThreshold === 0) return
    if (this._ackTimer) this._ackTimer.bau()
    this._ackTick = 0
    this._ackTickThreshold = random2over1(this.linearizer.indexers.length * this._ackThreshold)
  }

  _resetAckTick() {
    this._ackTick = 0
    if (this._ackTimer) this._ackTimer.bau()
  }

  _shiftWriter(w) {
    w.shift()
    if (w.flushed()) this._checkWriters.push(w)
  }
}

function toKey(k) {
  return b4a.isBuffer(k) ? k : hypercoreId.decode(k)
}

function isAutobaseMessage(msg) {
  return msg.checkpoint ? msg.checkpoint.length > 0 : msg.checkpoint === null
}

function compareNodes(a, b) {
  return b4a.compare(a.key, b.key)
}

function random2over1(n) {
  return Math.floor(n + Math.random() * n)
}

function noop() {}

function crashSoon(err) {
  queueMicrotask(() => {
    throw err
  })
  throw err
}

function isObject(obj) {
  return typeof obj === 'object' && obj !== null
}

function emitWarning(err) {
  safetyCatch(err)
  this.emit('warning', err)
}

function normalize(valueEncoding, value) {
  const state = { buffer: null, start: 0, end: 0 }
  valueEncoding.preencode(state, value)
  state.buffer = b4a.allocUnsafe(state.end)
  valueEncoding.encode(state, value)
  state.start = 0
  return valueEncoding.decode(state)
}
const b4a = require('b4a')

module.exports = class ActiveWriters {
  constructor() {
    this.map = new Map()
  }

  get size() {
    return this.map.size
  }

  [Symbol.iterator]() {
    return this.map.values()
  }

  get(key) {
    return this.map.get(b4a.toString(key, 'hex')) || null
  }

  has(key) {
    return this.get(key) !== null
  }

  add(writer) {
    this.map.set(b4a.toString(writer.core.key, 'hex'), writer)
  }

  delete(writer) {
    this.map.delete(b4a.toString(writer.core.key, 'hex'))
  }

  updateActivity() {
    for (const w of this.map.values()) w.updateActivity()
  }

  clear() {
    const p = []
    for (const w of this.map.values()) p.push(w.close())
    this.map.clear()

    return Promise.all(p)
  }
}
const SignalPromise = require('signal-promise')

module.exports = class AppendBatch {
  constructor(base) {
    this.base = base
    this.blocks = []
    this.closed = false
    this.flushing = false
    this._flushed = null
  }

  async _acquire() {
    while (this.base.activeBatch !== null && this.base.activeBatch !== this)
      await this.base.activeBatch.flushed()
    this.base.activeBatch = this
  }

  async append(value) {
    if (this.base.opened === false) await this.base.ready()
    if (this.base._advancing !== null) await this.base._advancing

    if (this.closed) throw new Error('Batch is closed')
    if (this.base.activeBatch !== this) await this._acquire()
    if (this.closed) throw new Error('Batch is closed')

    this.blocks.push(value)
    return this.base.local.length + this.blocks.length
  }

  async flush() {
    if (this.closed) throw new Error('Batch is closed')
    if (this.flushing) return this.flushed()
    this.flushing = true
    if (this.blocks.length) await this.base._appendBatch(this.blocks)
    return this.close()
  }

  flushed() {
    if (this.closed) return Promise.resolve()
    if (this._flushed) return this._flushed.wait()
    this._flushed = new SignalPromise()
    return this._flushed.wait()
  }

  close() {
    if (this.base.activeBatch !== this) return
    this.base.activeBatch = null
    this.closed = true
    if (this._flushed) this._flushed.notify(null)
  }
}
class PublicApplyCalls {
  constructor(base) {
    this.base = base
    this.internal = false
  }

  get discoveryKey() {
    return this.base.discoveryKey
  }

  get key() {
    return this.base.key
  }

  get id() {
    return this.base.id
  }

  async addWriter() {
    throw new Error('Not allowed on the public view')
  }

  async ackWriter() {
    throw new Error('Not allowed on the public view')
  }

  async removeWriter() {
    throw new Error('Not allowed on the public view')
  }

  preferFastForward() {
    throw new Error('Not allowed on the public view')
  }

  interrupt() {
    throw new Error('Not allowed on the public view')
  }

  removeable() {
    throw new Error('Not allowed on the public view')
  }

  fork() {
    throw new Error('Not allowed on the public view')
  }

  anchor() {
    throw new Error('Not allowed on the public view')
  }
}

class PrivateApplyCalls extends PublicApplyCalls {
  constructor(state) {
    super(state.base)
    this.state = state
    this.internal = true
  }

  get system() {
    return this.state.system
  }

  async addWriter(key, { indexer = true, isIndexer = indexer } = {}) {
    // just compat for old version
    await this.state.system.add(key, { isIndexer })
    await this.base._addWriter(key, this.state.system)
  }

  async ackWriter(key) {
    await this.state.system.ack(key)
  }

  async removeWriter(key) {
    // just compat for old version
    if (!this.state.removeable(key)) {
      throw new Error('Not allowed to remove the last indexer')
    }

    await this.state.system.remove(key)
    this.base._removeWriter(key)
  }

  preferFastForward() {
    this.base._preferFastForward()
  }

  interrupt(reason) {
    this.base._interrupt(reason)
  }

  removeable(key) {
    return this.state.removeable(key)
  }

  async fork(indexerKeys, system) {
    if (!(await this.state.validateFork(indexerKeys, system))) return false

    const indexers = indexerKeys.map(toIndexer)

    this.state.pendingFork = { indexers, length: system.length }

    return true
  }

  async createAnchor() {
    return await this.state.createAnchor()
  }
}

module.exports = { PublicApplyCalls, PrivateApplyCalls }

function toIndexer(key) {
  return { key, length: 0 } // length is not used, just for api compat
}
const ReadyResource = require('ready-resource')
const assert = require('nanoassert')
const c = require('compact-encoding')
const crypto = require('hypercore-crypto')
const b4a = require('b4a')
const safetyCatch = require('safety-catch')
const Hypercore = require('hypercore')

const { partialSignature } = require('hypercore/lib/multisig.js')

const SystemView = require('./system.js')
const { AutobaseEncryption, EncryptionView } = require('./encryption.js')
const UpdateChanges = require('./updates.js')
const messages = require('./messages.js')
const { PrivateApplyCalls } = require('./apply-calls.js')
const { encodeValue } = require('./values.js')
const Fork = require('./fork.js')
const LocalState = require('./local-state.js')
const { OPLOG_VERSION, BOOT_RECORD_VERSION } = require('./caps.js')

// todo: expose this as an option
const SHOULD_SIGN_THRESHOLD = 0

class CheckpointCore {
  constructor(view, core, signer, paused) {
    this.view = view
    this.core = core
    this.signer = signer
    this.length = 0
    this.digest = null
    this.signatures = { system: null, encryption: null, user: [] }
    this.closed = false
    this.paused = paused
  }

  pause() {
    this.paused = true
  }

  resume() {
    if (!this.paused) return
    this.paused = false
    this.updateBackground()
  }

  async update() {
    if (await this.updateCheckpoints()) await this.view.maybeSigned()
  }

  async updateCheckpoints() {
    if (this.core.length <= this.length || this.closed || this.paused) return false

    const length = this.core.length
    const value = await this.core.get(length - 1)

    if (length <= this.length || this.closed || !value.digest || this.paused) return false

    const [digest, checkpoints] = await Promise.all([
      this._inflateDigest(length, value.digest),
      this._inflateAllCheckpoints(length, value.checkpoint)
    ])

    if (length <= this.length || this.closed || !digest || !checkpoints || this.paused) return false
    for (let i = 0; i < checkpoints.length; i++) {
      if (checkpoints[i] === null) return false
    }

    this.length = length
    this.digest = digest
    this.signatures = checkpoints

    return true
  }

  updateBackground() {
    return this.update().catch(safetyCatch)
  }

  updateInternalSignatures(length, signatures) {
    this.signatures.system = updateSignature(length, signatures.system, this.signatures.system)
    this.signatures.encryption = updateSignature(
      length,
      signatures.encryption,
      this.signatures.encryption
    )
  }

  updateUserSignatures(length, signatures) {
    this.signatures.user = updateSignatures(length, signatures, this.signatures.user)
  }

  makeCheckpoints(length) {
    return {
      system: makeCheckpoint(length, this.signatures.system),
      encryption: makeCheckpoint(length, this.signatures.encryption),
      user: makeCheckpoints(length, this.signatures.user)
    }
  }

  makeDigest(length, key) {
    if (this.digest && (this.digest.key === key || b4a.equals(this.digest.key, key))) {
      return { key: null, pointer: length - this.digest.at }
    }
    this.digest = { key, at: length }
    return { key, pointer: 0 }
  }

  async ready() {
    await this.core.ready()
    this.core.on('append', this.updateBackground.bind(this))
    if (this.core.writable) await this.updateCheckpoints()
    this.updateBackground()
  }

  signedLength() {
    return this.signatures.system ? this.signatures.system.length : 0
  }

  close() {
    this.closed = true
    return this.core.close()
  }

  async _inflateDigest(length, dig) {
    if (!dig) return null

    if (dig.pointer === 0) {
      return { key: dig.key, at: length }
    }

    const len = length - dig.pointer

    if (this.digest && len === this.digest.at) return this.digest
    if (len <= 0) return null

    const { digest } = await this.core.get(len - 1)
    if (!digest || !digest.key) return null

    return { key: digest.key, at: len }
  }

  _sameSignatures(b, a) {
    return (
      sameSignature(a.system, b.system) &&
      sameSignature(a.encryption, b.encryption) &&
      sameSignatures(a.user, b.user)
    )
  }

  async _inflateAllCheckpoints(length, checkpoints) {
    if (!checkpoints) return { system: null, encryption: null, user: [] }
    if (this._sameSignatures(checkpoints, this.signatures)) return this.signatures

    const system = this._inflateSystemCheckpoint(checkpoints.system, length)
    const encryption = this._inflateEncryptionCheckpoint(checkpoints.encryption, length)

    const user = checkpoints.user ? new Array(checkpoints.user.length) : []

    for (let i = 0; i < user.length; i++) {
      const chk = checkpoints.user[i]
      user[i] = this._inflateUserCheckpoint(chk, i, length)
    }

    const [systemCheckpoint, encryptionCheckpoint, userCheckpoints] = await Promise.all([
      system,
      encryption,
      Promise.all(user)
    ])

    return {
      system: systemCheckpoint,
      encryption: encryptionCheckpoint,
      user: userCheckpoints
    }
  }

  async _inflateSystemCheckpoint(chk, coreLength) {
    if (chk.checkpoint) {
      const { signature, length } = chk.checkpoint
      return { signature, length, at: coreLength }
    }

    const len = coreLength - chk.checkpointer
    if (this.signatures.system && this.signatures.system.at === len) {
      return this.signatures.system
    }

    if (len <= 0) return null

    const { checkpoint } = await this.core.get(len - 1)
    if (!checkpoint || !checkpoint.system || !checkpoint.system.checkpoint) return null

    const { signature, length } = checkpoint.system.checkpoint
    return { signature, length, at: len }
  }

  async _inflateEncryptionCheckpoint(chk, coreLength) {
    if (!chk) return { length: 0, signature: null, at: 0 }

    if (chk.checkpoint) {
      const { signature, length } = chk.checkpoint
      return { signature, length, at: coreLength }
    }

    const len = coreLength - chk.checkpointer
    if (this.signatures.encryption && this.signatures.encryption.at === len) {
      return this.signatures.encryption
    }

    if (len <= 0) return null

    const { checkpoint } = await this.core.get(len - 1)
    if (!checkpoint || !checkpoint.encryption || !checkpoint.encryption.checkpoint) return null

    const { signature, length } = checkpoint.encryption.checkpoint
    return { signature, length, at: len }
  }

  async _inflateUserCheckpoint(chk, i, coreLength) {
    if (chk.checkpoint) {
      const { signature, length } = chk.checkpoint
      return { signature, length, at: coreLength }
    }

    const len = coreLength - chk.checkpointer
    if (i < this.signatures.user.length && this.signatures.user[i].at === len) {
      return this.signatures.user[i]
    }

    if (len <= 0) return null

    const { checkpoint } = await this.core.get(len - 1)
    if (!checkpoint || i >= checkpoint.user.length || !checkpoint.user[i].checkpoint) return null

    const { signature, length } = checkpoint.user[i].checkpoint
    return { signature, length, at: len }
  }
}

module.exports = class ApplyState extends ReadyResource {
  constructor(base) {
    super()

    this.base = base
    this.encryption = this.base.encryption
    this.valueEncoding = base.valueEncoding
    this.store = base._viewStore.atomize()
    this.key = null
    this.system = null
    this.view = null
    this.views = []
    this.systemView = null
    this.encryptionView = null
    this.hostcalls = null
    this.changes = base._hasUpdate ? new UpdateChanges(base) : null

    this.updates = []

    this.local = null
    this.localState = null

    this.fastForwarding = false
    this.indexersUpdated = false
    this.quorum = 0
    this.needsIndexedLengthUpdate = false
    this.interrupted = false
    this.applying = null
    this.applyBatch = null

    this.localCheckpoint = null
    this.localIndexer = false

    this.systemUpgrade = null

    this.checkpoints = []
    this.pendingViews = null
    this.pendingFork = null
    this.dirty = false
  }

  shouldFlush() {
    return this.dirty
  }

  async shouldWrite() {
    if (!this.localIndexer || !this.localCheckpoint || !this.localCheckpoint.core.opened) {
      return false
    }

    const info = await this.system.getIndexedInfo(this.indexedLength)
    if (!info.views.length) return false

    const { encryption, user } = this.localCheckpoint.signatures

    // todo: does this condition hold for soft-fork?
    if (info.views.length > user.length) return true

    for (let i = 0; i < info.views.length; i++) {
      if (user[i].length + SHOULD_SIGN_THRESHOLD < info.views[i].length) return true
    }

    // always flush encryption signature
    if (info.encryptionLength !== 0) {
      if (!encryption || encryption.length < info.encryptionLength) return true
    }

    return false
  }

  get indexedLength() {
    return this.systemView ? this.systemView.indexedLength : 0
  }

  get systemRef() {
    return this.systemView ? this.systemView.ref : null
  }

  async validateFork(indexerKeys, system) {
    if (!b4a.equals(system.key, this.system.core.key)) return false
    if (this.pendingIndexedLength() < system.length) return false
    for (const key of indexerKeys) {
      const info = await this.system.get(key)

      // writer should be active and we need manifest
      if (!info || !info.length || info.isRemoved) return false
    }
    return true
  }

  async shouldMigrate() {
    if (!this.fastForwarding && !this.indexersUpdated) return false
    if (this.system.indexers.length === 0) return false // genesis

    // sanity, prefer migration
    if (!this.system.core.manifest || !this.system.core.manifest.signers) return true

    // easy mode
    if (this.system.indexers.length !== this.system.core.manifest.signers.length) {
      return true
    }

    const manifests = await this.store.getIndexerManifests(this.system.indexers)

    for (let i = 0; i < this.system.core.manifest.signers.length; i++) {
      const { publicKey } = this.system.core.manifest.signers[i]
      if (!b4a.equals(publicKey, manifests[i].signers[0].publicKey)) return true
    }

    return false
  }

  isLocalPendingIndexer() {
    if (this.system.pendingIndexers.length === 0) return false
    const key = this.base.local.key
    for (const k of this.system.pendingIndexers) {
      if (b4a.equals(k, key)) return !b4a.equals(this.base.key, key) && this.base.local.length === 0
    }
    return false
  }

  removeable(key) {
    if (this.system.indexers.length !== 1) return true
    return !b4a.equals(this.system.indexers[0].key, key)
  }

  isLocalIndexer() {
    return !!this.localCheckpoint
  }

  _createCheckpointCore(key, active, signer, paused) {
    const encryption = this.base.getWriterEncryption(key)

    const session = this.base.store.get({
      key,
      valueEncoding: messages.OplogMessage,
      encryption,
      active
    })

    return new CheckpointCore(this, session, signer, paused)
  }

  async _openInternalView(name, indexedLength) {
    const core = this.store.get({ name })
    await core.ready()
    await core.setUserData('referrer', this.base.key)
    await core.setUserData('autobase/view', b4a.from(name))

    const ref = this.store.getViewByName(name)

    return { ref, core, indexedLength }
  }

  async _open() {
    try {
      await this._boot()
    } catch (err) {
      if (isViewCorruption(err)) {
        for (const v of this.store.opened) {
          await v.core.ready()
          await v.core.state.storage.deleteSessions()
        }
        if (this.systemView) {
          const core = this.systemView.ref.core
          await core.ready()
          await core.state.storage.deleteSessions()
        }
        if (this.encryptionView) {
          const core = this.encryptionView.ref.core
          await core.ready()
          await core.state.storage.deleteSessions()
        }

        await LocalState.clear(this.base.local)
      }

      await this._free()
      throw err
    }
  }

  async _boot() {
    const boot = await this.base._getBootRecord()

    this.systemView = await this._openInternalView('_system', boot.systemLength)
    this.encryptionView = await this._openInternalView('_encryption', -1)

    const sysCore = this.systemView.core
    if (sysCore.manifest.version >= 2) {
      if (this.encryption !== null) await this.encryption.reload(this.encryptionView.core)
    }

    const system = new SystemView(sysCore)
    await system.ready()

    // reset so we dont track _system or _encryption
    this.store.opened = []

    this.hostcalls = new PrivateApplyCalls(this)
    const view = this.base._hasOpen ? this.base._handlers.open(this.store, this.hostcalls) : null

    this.view = view
    this.system = system

    // ensure all are ready
    for (const v of this.store.opened) await v.atomicBatch.ready()

    this.key = system.core.key

    this.fastForwarding = boot.fastForwarding
    this.indexersUpdated = boot.indexersUpdated
    this.quorum = sysCore.manifest ? sysCore.manifest.quorum : 0

    const added = new Set()

    for (let i = 0; i < system.views.length; i++) {
      const { key, length } = system.views[i]
      const v = await this.store.findViewByKey(
        key,
        system.indexers,
        sysCore.manifest.version,
        system.entropy
      )

      if (v === null) {
        this.views.push({ name: null, key, length, core: null, ref: null, mappedIndex: i })
        continue
      }

      await v.atomicBatch.ready()
      await v.core.setUserData('referrer', this.base.key)
      await v.core.setUserData('autobase/view', b4a.from(v.name))

      this.views.push({ name: v.name, key, length, core: v.atomicBatch, ref: v, mappedIndex: i })

      added.add(v)
    }

    for (const v of this.store.opened) {
      if (added.has(v)) continue
      const core = v.atomicBatch

      this.views.push({
        name: v.name,
        key: core.key,
        length: core.length,
        core,
        ref: v,
        mappedIndex: -1
      })
    }

    this.local = this.store.getLocal()
    await this.local.ready()

    this.localState = new LocalState(this.local)

    let isLocalIndexer = false

    const paused = this.base.isFastForwarding()
    const inf = await this.system.getIndexedInfo()

    for (let i = 0; i < inf.indexers.length; i++) {
      const idx = inf.indexers[i]
      const chk = this._createCheckpointCore(idx.key, true, i, paused)
      await chk.ready()
      this.checkpoints.push(chk)
      if (b4a.equals(idx.key, this.base.local.key)) isLocalIndexer = true
    }

    const shouldSign = this.quorum > 0 && isLocalIndexer

    if (shouldSign) {
      this.localIndexer = true
      await this._startLocalCheckpoint()
    }

    await this._refreshWriters()

    // deferred
    this.maybeSigned().catch(noop)
  }

  async _startLocalCheckpoint() {
    for (const chk of this.checkpoints) {
      if (chk.core.id === this.base.local.id) {
        this.localCheckpoint = chk
        return
      }
    }

    this.localCheckpoint = this._createCheckpointCore(this.base.local.key, false, 0, false)
    await this.localCheckpoint.ready()
  }

  interrupt() {
    this.interrupted = true
    this.pause()
  }

  pause() {
    for (const chk of this.checkpoints) {
      if (chk !== this.localCheckpoint) chk.pause()
    }
  }

  resume() {
    for (const chk of this.checkpoints) {
      if (chk !== this.localCheckpoint) chk.resume()
    }
  }

  _checkSystemUpgrade() {
    if (this.systemUpgrade) return

    const tally = new Map()

    for (const chk of this.checkpoints) {
      if (chk.signedLength() <= this.system.core.signedLength) continue
      if (!chk.digest) continue

      const id = b4a.toString(chk.digest.key, 'hex')
      const cnt = (tally.get(id) || 0) + 1

      if (cnt >= this.quorum) {
        this.systemUpgrade = chk.digest.key
        this.base._queueStaticFastForward(this.systemUpgrade)
        return
      }

      tally.set(id, cnt)
    }
  }

  mapIndexToView(index) {
    for (const { mappedIndex, ref } of this.views) {
      if (mappedIndex === index) return ref
    }
  }

  async maybeSigned() {
    if (this.opened === false) await this.ready()
    if (this.interrupted) return

    const thres = this.checkpoints.length - this.quorum
    if (thres < 0 || this.checkpoints.length <= thres) return

    this.checkpoints.sort(cmpCheckpoints)

    const signableLength = this.checkpoints[thres].signedLength()
    if (signableLength <= this.system.core.signedLength) return

    const expected = this.system.core.key

    if (signableLength > this.indexedLength) {
      if (!b4a.equals(expected, this.checkpoints[thres].digest.key)) this._checkSystemUpgrade()
      this.needsIndexedLengthUpdate = true
      return
    }

    for (let i = thres; i < this.checkpoints.length; i++) {
      const chk = this.checkpoints[i]
      // we must agree on what the system is obvs
      if (!b4a.equals(expected, chk.digest.key)) {
        this._checkSystemUpgrade()
        return
      }
      // if we dont have the indexed state ourself, then no way for us to verify / patch
      if (!chk.signatures.system || chk.signatures.system.length > this.indexedLength) {
        this.needsIndexedLengthUpdate = true
        return
      }
    }

    this.needsIndexedLengthUpdate = false

    const chk = []
    for (let i = thres; i < this.checkpoints.length; i++) {
      chk.push({ signer: this.checkpoints[i].signer, signatures: this.checkpoints[i].signatures })
    }

    const { system } = this.checkpoints[thres].signatures

    await this._assembleMultisig(system.length, chk)
  }

  async _assembleMultisig(signableLength, checkpoints) {
    const views = new Array(this.views.length + 2) // +2 is system + encryption

    const sys = await this.system.getIndexedInfo(signableLength)

    if (this.interrupted) return

    if (this.pendingViews && this.pendingViews[0].length >= signableLength) {
      return
    }

    views[0] = createCheckpointSignature(signableLength, this.systemView, checkpoints.length)

    if (sys.encryptionLength) {
      views[1] = createCheckpointSignature(
        sys.encryptionLength,
        this.encryptionView,
        checkpoints.length
      )
    }

    const offset = 2 // system + encryption

    for (let i = offset; i < views.length; i++) {
      const view = this.views[i - offset]
      const core = view.core

      const v = this.getViewFromSystem(view, sys)
      const length = v ? v.length : 0

      if (!core || length <= core.signedLength) continue

      const viewIndex = view.mappedIndex + offset
      views[viewIndex] = createCheckpointSignature(length, view, checkpoints.length)
    }

    for (let i = 0; i < checkpoints.length; i++) {
      addCheckpointSignatures(views, checkpoints, i)
    }

    const promises = []
    for (const view of views) {
      if (!view) continue

      for (let i = 0; i < view.signatures.length; i++) {
        promises.push(setPartialSignature(view, i))
      }
    }

    await Promise.all(promises)

    // check that the state still looks good, couple replicate inbetween...
    for (const v of views) {
      if (!v) continue

      for (let i = 0; i < v.signatures.length; i++) {
        if (!v.partials[i]) return
      }
    }

    if (this.interrupted) return

    if (this.pendingViews && this.pendingViews[0].length >= signableLength) {
      return
    }
    // skipped system for whatever reason...
    if (!views[0]) return

    this.pendingViews = views
    this.dirty = true

    // TODO: only needed if not updating, wont crash so keeping for now, just less efficient
    this.base._queueBump()
  }

  _close() {
    if (this.interrupted) return
    return this._free()
  }

  async _free() {
    this.interrupted = true
    if (this.applying) this._postApply()
    for (const chk of this.checkpoints) await chk.close()
    if (this.localCheckpoint) await this.localCheckpoint.close()
    if (this.view && this.base._hasClose) await this.base._handlers.close(this.view)
    if (this.system) await this.system.close()

    const promises = []
    for (const v of this.views) {
      if (v.ref) promises.push(v.ref.release())
    }

    if (this.systemView) promises.push(this.systemView.ref.release())
    if (this.encryptionView) promises.push(this.encryptionView.ref.release())

    await Promise.all(promises)
    await this.store.close()
  }

  _pushUpdate(u) {
    u.version = 1
    u.seq = this.updates.length === 0 ? 0 : this.updates[this.updates.length - 1].seq + 1
    u.systemLength = this.systemView.core.length
    this.updates.push(u)
    this.localState.insertUpdate(u)
  }

  async catchup(linearizer) {
    if (!this.opened) await this.ready()
    if (!this.system.heads.length) return true

    const writers = new Map()

    // load linearizer...
    const updates = await this.localState.listUpdates()
    const sys = await this.system.checkout(this.indexedLength)

    for (const node of updates) {
      const hex = b4a.toString(node.key, 'hex')

      let w = writers.get(hex)

      if (w === undefined) {
        // TODO: we actually have all the writer info already but our current methods make it hard to reuse that
        w = await this.base._getWriterByKey(node.key, -1, 0, true, false, sys)
        writers.set(hex, w)
      }

      if (w.length >= node.length) {
        this.base._warn(new Error('Update expects writer to be consumed here'))
        return false
      }

      while (w.length < node.length) {
        await w.update(sys)

        const next = w.advance()
        if (!next) {
          this.base._warn(new Error('Node must exist for catchup'))
          return false
        }

        linearizer.addHead(next)
      }
    }

    await sys.close()

    this.updates = updates

    if (this.indexersUpdated) {
      this.indexersUpdated = false
      // if we updated the indexers, invalidate all the internal state and reapply it
      await this.truncate(this.indexedLength)
      await this._rollbackViews()

      if (this.tx === null) this.tx = this.local.state.storage.write()

      while (
        this.updates.length > 0 &&
        this.updates[this.updates.length - 1].systemLength >= this.indexedLength
      ) {
        const u = this.updates.pop()
        this.localState.deleteUpdate(u)
      }
    } else {
      // otherwise we know the internal state is correct, so we carry on
      linearizer.update()
    }

    // must refresh the writers here so isRemoved is up to date
    await this._refreshWriters()
    return true
  }

  async getIndexedSystem() {
    if (this.opened === false) await this.ready()

    const indexedLength = this.pendingFork ? this.pendingFork.length : this.indexedLength

    const sys = await this.system.checkout(indexedLength)
    await sys.ready()
    return sys
  }

  getViewFromSystem(view, sys = this.system) {
    if (view.mappedIndex === -1 || view.mappedIndex >= sys.views.length) return null
    return sys.views[view.mappedIndex]
  }

  async recoverAt() {
    if (!this.systemRef) await this.ready()

    await this.systemRef.core.ready()

    const lt = this.systemRef.core.core.state.length

    for await (const { length, info } of SystemView.flushes(this.systemRef.core.session(), {
      reverse: true,
      lt
    })) {
      let consistent = true

      for (let i = 0; i < info.views.length; i++) {
        if (i >= this.views.length) continue
        if (!b4a.equals(info.views[i].key, this.views[i].key)) continue

        if (info.views[i].length > this.views[i].core.core.state.length) {
          consistent = false
          break
        }
      }

      if (consistent) {
        return {
          length,
          force: true,
          key: this.system.core.key,
          indexers: info.indexers,
          views: info.views
        }
      }
    }

    return null
  }

  bootstrap() {
    return this.system.add(this.base.key, { isIndexer: true, isPending: false })
  }

  async undo(popped) {
    if (!popped) return

    let indexersUpdated = false
    while (popped > 0) {
      const u = this.updates.pop()
      this.localState.deleteUpdate(u)
      popped -= u.batch
      if (u.indexers) indexersUpdated = true
    }

    const u = this.updates.length === 0 ? null : this.updates[this.updates.length - 1]
    const systemLength = u ? u.systemLength : this.indexedLength

    await this.truncate(systemLength)
    if (indexersUpdated) await this._rollbackViews()
  }

  async truncate(systemLength) {
    if (this.opened === false) await this.ready()
    if (systemLength === this.system.core.length) return

    await this.system.core.truncate(systemLength)

    const migrated = await this.system.update()

    if (this.encryptionView.core.length !== this.system.encryptionLength) {
      await this.encryptionView.core.truncate(this.system.encryptionLength)
    }

    for (const view of this.views) {
      if (!view.core) continue

      const v = this.getViewFromSystem(view)

      if (v && view.core.length === v.length) continue
      if (v === null) view.mappedIndex = -1 // unmap

      await view.core.truncate(v ? v.length : 0)
    }

    if (!migrated) return

    await this._refreshWriters()
    await this._rollbackViews()
  }

  async _refreshWriters() {
    // TODO: add the seq at which we updated the state to the writer instance.
    // then we know if it was truncated out without the lookup, meaning faster truncations
    for (const w of this.base.activeWriters) {
      const data = await this.system.get(w.core.key)
      const bootstrapper = this.system.core.length === 0 && b4a.equals(w.core.key, this.base.key)
      const isRemoved = data ? data.isRemoved : !bootstrapper
      w.isRemoved = isRemoved
    }
  }

  async _updateSystem() {
    if (!(await this.system.update())) return
    await this._refreshWriters()
    await this._rollbackViews()
  }

  async _signViewCore(core, length) {
    const s = await core.signable(length, 0)
    const signature = crypto.sign(s, this.base.local.keyPair.secretKey)
    return { signature, length }
  }

  async _signInternalViewCores(sys) {
    return {
      system: await this._signViewCore(this.systemView.core, this.systemView.indexedLength),
      encryption: await this._signViewCore(this.encryptionView.core, sys.encryptionLength)
    }
  }

  async _signUserViewCores(sys) {
    const promises = new Array(sys.views.length)

    for (let i = 0; i < this.views.length; i++) {
      const view = this.views[i]

      const v = this.getViewFromSystem(view, sys)
      const indexedLength = v ? v.length : 0

      if (!indexedLength) continue

      const viewIndex = view.mappedIndex
      promises[viewIndex] = this._signViewCore(view.ref.atomicBatch, indexedLength)
    }

    return Promise.all(promises)
  }

  async finalize(key) {
    this.localState.setBootRecord({
      version: BOOT_RECORD_VERSION,
      key,
      systemLength: this.systemView.indexedLength,
      indexersUpdated: true,
      fastForwarding: false,
      recoveries: this.base.recoveries
    })

    await this.localState.flush()

    await this.store.flush()
    await this.close()
  }

  async _flush(localNodes) {
    if (localNodes) await this._appendLocalNodes(localNodes)

    if (this.localCheckpoint) {
      // we have to flush here so the chkpoint can update
      // could run the checkpoint on the batch but also no big dead
      // as the "should we sign" check is rerun on boot...
      await this.store.flush()
      await this.localCheckpoint.update()
    }

    this.localState.setBootRecord({
      version: BOOT_RECORD_VERSION,
      key: this.key,
      systemLength: this.systemView.indexedLength,
      indexersUpdated: false,
      fastForwarding: false,
      recoveries: this.base.recoveries
    })

    await this.localState.flush()

    if (this.pendingViews) {
      const views = this.pendingViews
      this.pendingViews = null

      for (let i = views.length - 1; i >= 0; i--) {
        const v = views[i]
        if (!v || v.length <= v.core.signedLength) continue
        const signature = v.core.core.verifier.assemble(v.partials)
        try {
          await v.ref.commit(this.store.atom, v.length, signature)
        } catch (err) {
          if (isAssertion(err)) {
            throw err
          }

          // TODO: we should prevalidate all signatures instead of during commit so it can be all or nothing, just slighly
          // friendlier ux. missing hc api for that
          if (!this.base.closing) this.base._warn(err)
          break
        }
      }
    }

    await this.store.flush()

    this.fastForwarding = false
    if (this.pendingViews === null) this.dirty = false
  }

  _indexUpdates(indexed) {
    let shift = 0
    while (indexed > 0) indexed -= this.updates[shift++].batch

    const last = this.updates[shift - 1]

    this.systemView.indexedLength = last.systemLength

    for (let i = 0; i < shift; i++) this.localState.deleteUpdate(this.updates[i])
    this.updates.splice(0, shift)

    if (!this.needsIndexedLengthUpdate) return
    this.maybeSigned().catch(noop)
  }

  pendingIndexedLength() {
    let indexed = this.applying.indexed.length
    if (!this.applying || !this.updates.length || !indexed) return this.indexedLength

    let pos = 0
    while (indexed > 0 && pos < this.updates.length) {
      indexed -= this.updates[pos++].batch
    }

    const last = this.updates[pos - 1]
    return last.systemLength
  }

  async _assertNode(node, batch) {
    // helpful dag helper, so kept here

    const v = (await this.system.get(node.writer.core.key)) || { length: 0, isRemoved: false }
    const expected = v.length + batch
    if (node.length === expected) return

    console.trace(
      'INVALID_INSERTION',
      'length=',
      node.length,
      'key=',
      node.writer.core.key,
      'local=',
      node.writer.core.writable,
      'batch=',
      batch,
      'dag=',
      v
    )

    process.exit(1)
  }

  _postApply() {
    this.applyBatch = this.applying = null
    this.base._postApply()
  }

  async _optimisticApply(u, node, indexed) {
    const checkpoint = this.system.checkpoint()

    this.system.addHead(node)

    const applyBatch = []
    const key = node.writer.core.key

    applyBatch.push({
      indexed,
      optimistic: true,
      from: node.writer.core,
      length: node.length,
      value: node.value,
      heads: node.actualHeads
    })

    const pre = await this.system.get(key)
    const preLength = pre ? pre.length : 0

    let failed = false

    this.applying = u
    this.applyBatch = applyBatch
    try {
      await this.base._handlers.apply(applyBatch, this.view, this.hostcalls)
    } catch (err) {
      if (this.base.closing) throw err
      failed = true
    }
    this._postApply()

    if (!failed) {
      const post = await this.system.get(key)
      // check if acked by addWriter/removeWriter/ackWriter
      if (!post || preLength === post.length) failed = true
    }

    if (!failed) {
      // technically we only need to to this is the writer was removed, but hey, tricky logic
      await this._refreshWriters()
      return true
    }

    // it failed! rollback...

    this.system.applyCheckpoint(checkpoint)

    if (this.encryptionView.core.length !== this.system.encryptionLength) {
      await this.encryptionView.core.truncate(this.system.encryptionLength)
    }

    for (const view of this.views) {
      const viewLength = view.core ? view.core.length : view.length
      const viewLookup = this.getViewFromSystem(view)
      const viewSystemLength = viewLookup ? viewLookup.length : 0
      if (viewSystemLength === viewLength) continue
      await view.core.truncate(viewSystemLength)
    }

    await this._refreshWriters()

    await this._rollbackViews()
    return false
  }

  _startTrace(node) {
    this.systemRef.tracer.start()
    this.encryptionView.ref.tracer.start()
    for (let i = 0; i < this.views.length; i++) this.views[i].ref.tracer.start()
  }

  _endTrace(node) {
    const trace = {
      system: this.systemRef.tracer.end(),
      encryption: this.encryptionView.ref.tracer.end(),
      user: []
    }

    for (let i = 0; i < this.views.length; i++) {
      const blocks = this.views[i].ref.tracer.end()
      if (blocks.length) trace.user.push({ view: i, blocks })
    }

    if (trace.system.length || trace.encryption.length || trace.user.length) node.trace = trace
  }

  async update(u, localNodes) {
    if (this.changes !== null) this.changes.track(this)

    let batch = 0
    let applyBatch = []
    let indexersUpdated = 0

    let j = 0
    let i = 0
    let forkedAt = -1

    while (i < Math.min(u.indexed.length, u.shared)) {
      const node = u.indexed[i++]

      if (node.batch > 1) continue
      this.base._shiftWriter(node.writer)

      const update = this.updates[j++]

      if (update.indexers) {
        indexersUpdated = i
        break
      }
    }

    if (u.undo) await this.undo(u.undo)

    if (this.system.bootstrapping) await this.bootstrap()

    await this._updateSystem()

    // Organize by view
    const warmupSystemView = []
    const warmupEncryptionView = []
    const warmupUserView = new Array(this.views.length)

    for (let k = u.shared; k < u.length; k++) {
      const indexed = k < u.indexed.length
      const node = indexed ? u.indexed[k] : u.tip[k - u.indexed.length]
      if (!node.trace) continue

      if (node.trace.system.length) warmupSystemView.push(...node.trace.system)
      if (node.trace.encryption.length) warmupEncryptionView.push(...node.trace.encryption)

      for (const trace of node.trace.user) {
        // Assert (as warning) that trace view should only be currently indexed views
        if (trace.view >= this.views.length) {
          console.warn(
            'Oplog block trace contains OOB view index',
            'trace view',
            trace.view,
            'views.length',
            this.views.length
          )
          continue
        }

        warmupUserView[trace.view] = warmupUserView[trace.view] || []
        warmupUserView[trace.view].push(...trace.blocks)
      }
    }

    // Request per view
    if (warmupSystemView.length) this.systemView.core.download({ blocks: warmupSystemView })
    if (warmupEncryptionView.length)
      this.encryptionView.core.download({ blocks: warmupEncryptionView })
    for (let k = 0; k < warmupUserView.length; k++) {
      const blocks = warmupUserView[k]
      if (!blocks) continue

      const view = this.views[k]
      view.core.download({ blocks })
    }

    for (i = u.shared; i < u.length; i++) {
      if (this.base.backoff !== null && this.base.backoff.backoff()) await this.base.backoff.wait()

      const indexed = i < u.indexed.length
      const node = indexed ? u.indexed[i] : u.tip[i - u.indexed.length]

      batch++

      if (node.writer.core.writable) this._startTrace(node)

      const optimist =
        node.writer.isRemoved &&
        node.optimistic &&
        batch === 1 &&
        this.base._hasOptimisticApply === true &&
        (await this._optimisticApply(u, node, indexed))

      if (!optimist) {
        if (node.writer.isRemoved && !node.writer.isActiveIndexer) {
          if (node.batch > 1) continue
          // in case someone is linking this node and they are not removed
          const u = {
            seq: 0,
            key: node.writer.core.key,
            length: node.length,
            batch,
            systemLength: 0,
            indexers: false
          }
          this._pushUpdate(u)
          batch = 0
          assert(applyBatch.length === 0, 'Apply batch should not have been modified')
          continue
        }

        // in prod we prop need to disable this assertion as its pretty expensive,
        // but it catches a lot of bugs, so here for debugs
        // await this._assertNode(node, batch)

        const deps = node.causalDependencies()

        // oldest -> newest
        for (let i = deps.length - 1; i >= 1; i--) {
          const d = deps[i]
          if (await this.system.linkable(d.writer.core.key, d.length)) {
            this.system.addHead(deps[i])
          }
        }

        this.system.addHead(deps[0])

        if (node.value !== null && !node.writer.isRemoved) {
          applyBatch.push({
            indexed,
            optimistic: false,
            from: node.writer.core,
            length: node.length,
            value: node.value,
            heads: node.actualHeads
          })
        }

        if (node.batch > 1) continue

        if (applyBatch.length && this.base._hasApply === true) {
          this.applying = u
          this.applyBatch = applyBatch
          await this.base._handlers.apply(applyBatch, this.view, this.hostcalls)
          if (forkedAt === -1 && this.pendingFork) forkedAt = i
          this._postApply()
        }
      }

      const update = {
        seq: 0,
        key: node.writer.core.key,
        length: node.length,
        batch,
        systemLength: 0,
        indexers: false
      }

      update.indexers = !!this.system.indexerUpdate

      if (this.system.indexerUpdate) await this._generateNextViews()

      await this.system.flush(this.views)
      await this.system.update()

      if (node.writer.core.writable) this._endTrace(node)

      batch = 0
      applyBatch = []

      this._pushUpdate(update)

      if (!indexed || indexersUpdated) continue

      this.base._shiftWriter(node.writer)

      if (update.indexers) {
        indexersUpdated = i + 1
      }
    }

    if (this.pendingFork) {
      const pending = this.pendingFork
      if (pending.length > this.indexedLength) this._indexUpdates(u.indexed.length)

      const fork = new Fork(this.base, this.store, this, pending)
      const forked = await fork.upgrade()

      if (!forked) throw new Error('Fork failed')

      await this._flush(localNodes)

      return {
        reboot: true,
        migrated: false
      }
    }

    if (u.indexed.length) {
      this._indexUpdates(indexersUpdated || u.indexed.length)
    }

    const migrated = indexersUpdated !== 0
    if (migrated) this.key = await this.base._premigrate()

    if (this.changes !== null) {
      this.changes.finalise()
      await this.base._handlers.update(this.view, this.changes)
    }

    await this._flush(localNodes)

    return {
      reboot: migrated,
      migrated
    }
  }

  flush() {
    return this._flush(null)
  }

  async _appendLocalNodes(localNodes) {
    if (localNodes.length === 0) return // just in case

    const blocks = new Array(localNodes.length)
    const local = this.local

    if (!local.opened) await local.ready()

    for (let i = 0; i < blocks.length; i++) {
      const { value, heads, batch, optimistic, trace } = localNodes[i]

      blocks[i] = {
        version: OPLOG_VERSION,
        maxSupportedVersion: this.base.maxSupportedVersion,
        checkpoint: null,
        digest: null,
        optimistic,
        node: {
          heads,
          batch,
          value: value === null ? null : c.encode(this.base.valueEncoding, value)
        },
        trace
      }
    }

    if (this.localIndexer) {
      const signedLength = this.localCheckpoint.signedLength()
      const local = this.local

      let signedAt = 0
      let internalSignatures = null
      let signatures = null

      if (this.indexedLength > signedLength) {
        const sys = await this.system.getIndexedInfo(this.indexedLength)
        internalSignatures = await this._signInternalViewCores(sys)
        signatures = await this._signUserViewCores(sys)
        signedAt = local.length + blocks.length
      }

      for (let i = 0; i < blocks.length; i++) {
        const length = local.length + i + 1
        if (length === signedAt) {
          this.localCheckpoint.updateInternalSignatures(length, internalSignatures)
          this.localCheckpoint.updateUserSignatures(length, signatures)
        }

        const blk = blocks[i]

        blk.checkpoint = this.localCheckpoint.makeCheckpoints(length)
        blk.digest = this.localCheckpoint.makeDigest(length, this.key)
      }
    } else {
      if (!this.localCheckpoint) await this._startLocalCheckpoint()

      for (let i = 0; i < blocks.length; i++) {
        const length = local.length + i + 1
        blocks[i].digest = this.localCheckpoint.makeDigest(length, this.key)
      }
    }

    await local.append(blocks)
  }

  async _rollbackViews() {
    // encryption view key is not in system so no need to handle here
    for (const view of this.views) {
      const v = this.getViewFromSystem(view)

      if (v) {
        view.key = v.key
      } else {
        await this._resetView(view)
      }
    }
  }

  async createAnchor() {
    const node = this.applyBatch[this.applyBatch.length - 1]
    const key = node.from.key
    const length = node.length

    const info = await this.system.get(key, { unflushed: true })

    if (!info || info.length < length) throw new Error('Anchor node is not in system')

    const state = { start: 0, end: 40, buffer: b4a.alloc(40) }
    c.fixed32.encode(state, key)
    c.uint64.encode(state, length)

    const namespace = crypto.hash(state.buffer)
    const manifestData = c.encode(messages.ManifestData, { version: 0, legacyBlocks: 0, namespace })

    const padding = this.encryption ? AutobaseEncryption.PADDING : 0
    const block = encodeValue(null, { heads: [{ key, length }], padding })
    if (this.encryption) await this.encryption.encryptAnchor(block, namespace)

    const root = { index: 0, size: block.byteLength, hash: crypto.data(block) }
    const hash = crypto.tree([root])
    const prologue = { hash, length: 1 }

    const core = this.store.createAnchorCore(prologue, manifestData)
    await core.ready()

    if (core.length === 0) await core.append(block, { writable: true, maxLength: 1 })

    await this.system.add(core.key, { isIndexer: false, length: 0 })
    await this.base._addWriter(core.key, this.system)

    const anchor = { key: core.key, length: core.length }

    await core.close()
    await this.base.hintWakeup(anchor)

    return anchor
  }

  async _resetView(view) {
    const manifests = await this.store.getIndexerManifests(this.system.indexers)

    const manifestData = view.core ? view.core.manifest.userData : null
    view.key = await this.store.createView(
      manifests,
      view.name,
      null,
      this.system.core.manifest.version,
      this.system.entropy,
      null,
      manifestData
    ) // will never be system so no linked
    view.length = 0
  }

  async _generateNextViews() {
    const sys = this.system

    // note, this is very state dependent so can ONLY be called at the exact time an indexer upgrade occurs
    const manifests = await this.store.getIndexerManifests(sys.indexers)
    const entropy = sys.version < 2 ? null : sys.getEntropy(sys.indexers, sys.flushLength())

    for (const v of this.views) {
      const manifestData = v.core ? v.core.manifest.userData : null

      const prologue = await getPrologue(v)
      const key = await this.store.createView(
        manifests,
        v.name,
        prologue,
        sys.core.manifest.version,
        entropy,
        null,
        manifestData
      )

      v.key = key
    }
  }
}

async function getPrologue(view) {
  const length = view.core ? view.core.length : view.length
  if (!length) return null

  const hash = await view.core.treeHash(length)

  return {
    hash,
    length
  }
}

function noop() {}

function cmpCheckpoints(a, b) {
  return a.signedLength() - b.signedLength()
}

function sameSignature(a, b) {
  if (!a || !b) return a === b
  return a.length === b.length
}

function sameSignatures(a, b) {
  if (!a || !b) return a === b
  if (a.length !== b.length) return false
  for (let i = 0; i < a.length; i++) {
    if (a[i].length !== b[i].length) return false
  }
  return true
}

function createCheckpointSignature(length, view, checkpoints) {
  return {
    length,
    core: view.core,
    ref: view.ref,
    signatures: new Array(checkpoints),
    partials: new Array(checkpoints)
  }
}

function addCheckpointSignatures(pending, checkpoints, index) {
  const { signer, signatures } = checkpoints[index]

  pending[0].signatures[index] = {
    signature: signatures.system.signature,
    length: signatures.system.length,
    signer
  }

  if (pending[1]) {
    pending[1].signatures[index] = {
      signature: signatures.encryption.signature,
      length: signatures.encryption.length,
      signer
    }
  }

  for (let i = 2; i < pending.length; i++) {
    if (!pending[i]) continue

    const { length, signature } = signatures.user[i - 2]

    pending[i].signatures[index] = {
      signature,
      length,
      signer
    }
  }
}

async function setPartialSignature(view, index) {
  const sig = view.signatures[index]
  if (sig.length < view.length && sig.length > 0) await view.core.get(sig.length - 1)

  view.partials[index] = await partialSignature(
    view.core,
    sig.signer,
    view.length,
    sig.length,
    sig.signature
  )
}

function updateSignature(length, sig, existing) {
  return sig ? { signature: sig.signature, length: sig.length, at: length } : existing
}

function updateSignatures(length, signatures, existing) {
  const updated = new Array(signatures.length)

  for (let i = 0; i < updated.length; i++) {
    updated[i] = updateSignature(length, signatures[i], i < existing.length ? existing[i] : null)
  }

  return updated
}

function makeCheckpoint(length, chk) {
  if (!chk) return null

  const checkpointer = length - chk.at

  return {
    checkpointer,
    checkpoint: checkpointer === 0 ? { signature: chk.signature, length: chk.length } : null
  }
}

function makeCheckpoints(length, signatures) {
  if (!signatures.length) return null

  const checkpoints = new Array(signatures.length)

  for (let i = 0; i < signatures.length; i++) {
    checkpoints[i] = makeCheckpoint(length, signatures[i])
  }

  return checkpoints
}

function isViewCorruption(err) {
  return err.code === 'INVALID_OPERATION'
}

function isAssertion(err) {
  return err.code === 'ERR_ASSERTION' || err.name === 'AssertionError'
}
const c = require('compact-encoding')
const encryptionEncoding = require('encryption-encoding')
const messages = require('./messages.js')

module.exports = async function boot(
  corestore,
  key,
  { encrypt, encryptionKey, keyPair, exclusive = true, blindEncryption } = {}
) {
  const result = {
    key: null,
    local: null,
    bootstrap: null,
    encryptionKey: null,
    boot: null
  }

  const manifest = keyPair
    ? { version: corestore.manifestVersion, signers: [{ publicKey: keyPair.publicKey }] }
    : null

  if (key) {
    result.key = key

    const bootstrap = corestore.get({ key, active: false, valueEncoding: messages.OplogMessage })
    await bootstrap.ready()

    const localKey = await bootstrap.getUserData('autobase/local')

    if (keyPair) {
      result.local = corestore.get({
        keyPair,
        active: false,
        exclusive,
        valueEncoding: messages.OplogMessage,
        manifest
      })
    } else {
      if (bootstrap.writable && !localKey) {
        result.local = bootstrap.session({
          active: false,
          exclusive,
          valueEncoding: messages.OplogMessage
        })
      } else {
        const local = localKey
          ? corestore.get({
              key: localKey,
              active: false,
              exclusive,
              valueEncoding: messages.OplogMessage
            })
          : corestore.get({
              name: 'local',
              active: false,
              exclusive,
              valueEncoding: messages.OplogMessage
            })

        await local.ready()
        result.local = local
      }
    }

    result.bootstrap = bootstrap
  } else {
    result.local = keyPair
      ? corestore.get({
          keyPair,
          manifest,
          active: false,
          exclusive,
          valueEncoding: messages.OplogMessage
        })
      : corestore.get({
          name: 'local',
          active: false,
          exclusive,
          valueEncoding: messages.OplogMessage
        })
    await result.local.ready()

    const key = await result.local.getUserData('referrer')
    if (key) {
      result.key = key
      result.bootstrap = corestore.get({ key, active: false, valueEncoding: messages.OplogMessage })
      await result.bootstrap.ready()
    } else {
      result.key = result.local.key
      result.bootstrap = result.local.session({
        active: false,
        valueEncoding: messages.OplogMessage
      })
      await result.bootstrap.setUserData('autobase/local', result.local.key)
    }
  }

  if (key || keyPair) {
    await result.bootstrap.setUserData('referrer', result.key)
    await result.bootstrap.setUserData('autobase/local', result.local.key)
    await result.local.setUserData('referrer', result.key)
  }

  const [encryptionKeyBuffer, encryptionKeyEncryptedBuffer, pointer] = await Promise.all([
    result.local.getUserData('autobase/encryption'),
    result.local.getUserData('autobase/blind-encryption'),
    result.local.getUserData('autobase/boot')
  ])

  if (pointer) {
    result.boot = c.decode(messages.BootRecord, pointer)
  }

  if (encryptionKeyBuffer) {
    // if not encoded, replace
    if (blindEncryption) {
      const encrypted = await encryptionEncoding.encrypt(
        encryptionKeyBuffer,
        blindEncryption.encrypt
      )
      await result.local.setUserData('autobase/blind-encryption', encrypted)
      await result.local.setUserData('autobase/encryption', null)
    }

    result.encryptionKey = encryptionKeyBuffer
  }

  if (encryptionKeyEncryptedBuffer) {
    const { value, rotated } = await encryptionEncoding.decrypt(
      encryptionKeyEncryptedBuffer,
      blindEncryption.decrypt
    )

    if (rotated) {
      const encrypted = await encryptionEncoding.encrypt(value, blindEncryption.encrypt)
      await result.local.setUserData('autobase/blind-encryption', encrypted)
    }

    result.encryptionKey = value
  }

  if (!result.encryptionKey && (encryptionKey || encrypt)) {
    if (!encryptionKey) {
      encryptionKey = (await corestore.createKeyPair('autobase/encryption')).secretKey.subarray(
        0,
        32
      )
    }

    if (blindEncryption) {
      const encrypted = await encryptionEncoding.encrypt(encryptionKey, blindEncryption.encrypt)
      await result.local.setUserData('autobase/blind-encryption', encrypted)
    } else {
      await result.bootstrap.setUserData('autobase/encryption', encryptionKey) // legacy support
      await result.local.setUserData('autobase/encryption', encryptionKey)
    }
    result.encryptionKey = encryptionKey
  }

  return result
}
const crypto = require('hypercore-crypto')

const OPLOG_VERSION = 2
const DEFAULT_AUTOBASE_VERSION = 1 // default
const MAX_AUTOBASE_VERSION = 2 // optional fork support
const BOOT_RECORD_VERSION = 3

const [NS_SIGNER_NAMESPACE, NS_VIEW_BLOCK_KEY, NS_HASH_KEY, NS_ENCRYPTION] = crypto.namespace(
  'autobase',
  4
)

module.exports = {
  OPLOG_VERSION,
  DEFAULT_AUTOBASE_VERSION,
  MAX_AUTOBASE_VERSION,
  BOOT_RECORD_VERSION,
  NS_SIGNER_NAMESPACE,
  NS_VIEW_BLOCK_KEY,
  NS_HASH_KEY,
  NS_ENCRYPTION
}
const BufferMap = require('tiny-buffer-map')

// This is basically just a Map atm, but leaving it as an abstraction for now
// in case we wanna optimize it for our exact usecase

module.exports = class Clock {
  constructor() {
    this.seen = new BufferMap()
  }

  get size() {
    return this.seen.size
  }

  has(key) {
    return this.seen.has(key)
  }

  includes(key, length) {
    return this.seen.has(key) && this.seen.get(key) >= length
  }

  get(key) {
    return this.seen.get(key) || 0
  }

  set(key, len) {
    this.seen.set(key, len)
    return len
  }

  add(clock) {
    for (const [key, l] of clock) {
      if (this.get(key) < l) this.set(key, l)
    }
  }

  [Symbol.iterator]() {
    return this.seen[Symbol.iterator]()
  }
}
const BufferMap = require('tiny-buffer-map')

const Clock = require('./clock.js')

const UNSEEN = 0
const NEWER = 1
const ACKED = 2

// Consensus machine for Autobase. Sort DAG nodes using
// vector clocks to determine a globally consistent view

module.exports = class Consensus {
  constructor(indexers) {
    this.merges = new Set()
    this.majority = (indexers.length >>> 1) + 1
    this.indexers = indexers
    this.removed = new Clock()
    this.updated = false

    this.writers = new BufferMap()
    for (const idx of this.indexers) {
      this.writers.set(idx.core.key, idx)
    }
  }

  addHead(node) {
    if (!node.writer.isActiveIndexer) return
    if (this._isMerge(node)) this.merges.add(node)
    this.updated = true
    return node
  }

  /* Indexer Only DAG methods */

  _tails(node, tails) {
    const tailSet = new Set()
    for (const t of tails) {
      if (node.clock.includes(t.writer.core.key, t.length)) tailSet.add(t)
    }

    return tailSet
  }

  _tailsAndMerges(node, tails) {
    const all = this._tails(node, tails)
    for (const m of this.merges) {
      if (m !== node && node.clock.includes(m.writer.core.key, m.length)) {
        all.add(m)
      }
    }
    return all
  }

  _isMerge(node) {
    if (!node.writer.isActiveIndexer) return false

    const deps = []

    for (const idx of this.indexers) {
      let seq = node.clock.get(idx.core.key) - 1

      if (idx === node.writer) seq--

      const head = idx.get(seq)
      if (!head || this.removed.includes(head.writer.core.key, head.length)) continue

      let isDep = true
      for (let i = 0; i < deps.length; i++) {
        const d = deps[i]
        if (d === head) continue

        if (d.clock.includes(head.writer.core.key, head.length)) {
          isDep = false
          break
        }

        if (head.clock.includes(d.writer.core.key, d.length)) {
          const popped = deps.pop()
          if (d === popped) continue
          deps[i--] = popped
        }
      }

      if (isDep) deps.push(head)
    }

    return deps.length > 1
  }

  _indexerTails() {
    const tails = new Set()
    for (const idx of this.indexers) {
      const length = this.removed.has(idx.core.key) ? this.removed.get(idx.core.key) : idx.indexed

      const head = idx.get(length)
      if (!head || this.removed.includes(head.writer.core.key, head.length)) continue

      let isTail = true
      for (const t of tails) {
        if (head.clock.includes(t.writer.core.key, t.length)) {
          isTail = false
          break
        }

        if (t.clock.includes(head.writer.core.key, head.length)) {
          tails.delete(t)
        }
      }

      if (isTail) tails.add(head)
    }

    return tails
  }

  // parent is newer if for any node in parent's view,
  // either node can see object or object can see node
  _strictlyNewer(object, parent) {
    if (!parent.clock.includes(object.writer.core.key, object.length)) return false

    for (const [key, latest] of parent.clock) {
      const oldest = this.removed.get(key)
      if (latest <= oldest) continue // check quickly if we removed it

      // get the NEXT node from the writer from the objects pov, adjust if its removed
      let length = object.clock.get(key)
      if (length <= oldest) length = oldest

      // sanity check, likely not needed as someone has checked this before, but it's free
      if (latest < length) return false

      // if the same, they have both seen it, continue
      if (latest === length) continue

      const writer = this.writers.get(key)

      // might not be in the removed set but the writer can tell us if it was indexed...
      const next = writer && writer.get(length >= writer.indexed ? length : writer.indexed)

      // no next, its been indexed, both seen it
      if (!next) continue

      // if the NEXT node has seen the object its fine - newer
      if (next.clock.includes(object.writer.core.key, object.length)) continue

      // otherwise the parent must also NOT have seen the next node
      if (latest < next.length) continue

      return false
    }

    return true
  }

  _acks(target) {
    const acks = target.writer.isActiveIndexer ? [target] : [] // TODO: can be cached on the target node in future (ie if we add one we dont have to check it again)

    for (const idx of this.indexers) {
      if (idx === target.writer) continue

      let next = target.clock.get(idx.core.key)
      if (next < idx.nodes.offset) next = idx.nodes.offset

      const nextIndexNode = idx.get(next >= idx.indexed ? next : idx.indexed)

      // no node - no ack
      if (!nextIndexNode) continue

      // if the next index node does not see the target, no ack
      if (!nextIndexNode.clock.includes(target.writer.core.key, target.length)) continue

      // if the next index node is not strictly newer, skip to avoid ambig...
      if (!this._strictlyNewer(target, nextIndexNode)) continue

      acks.push(nextIndexNode)
    }

    return acks
  }

  acksFromNode(target, view) {
    const acks = new Set()

    if (!view || !view.clock.includes(target.writer.core.key, target.length)) return acks

    acks.add(view.writer)

    for (const idx of this.indexers) {
      if (idx === view.writer) continue

      const length = view.clock.get(idx.core.key)
      if (!length) continue

      if (target.clock.includes(idx.core.key, length)) continue

      const head = idx.get(length - 1)
      if (!head) continue

      if (head.clock.includes(target.writer.core.key, target.length)) {
        acks.add(idx)
      }
    }

    return acks
  }

  _ackedAt(acks, parent) {
    let seen = 0
    let missing = acks.length

    for (const node of acks) {
      missing--

      if (!parent.clock.includes(node.writer.core.key, node.length)) {
        if (seen + missing < this.majority) return false
        continue
      }

      if (++seen >= this.majority) return true
    }

    return false
  }

  confirms(indexer, target, acks, length) {
    if (!length || this.removed.get(indexer.core.key) >= length) return UNSEEN
    // def feels like there is a smarter way of doing this part
    // ie we just wanna find a node from the indexer that is strictly newer than target
    // and seens a maj of the acks - thats it

    let jump = true
    let newer = true

    for (let i = length - 1; i >= 0; i--) {
      const head = indexer.get(i)
      if (head === null) return UNSEEN

      let seen = 0

      for (const node of acks) {
        // if (node.writer === indexer) continue
        if (!head.clock.includes(node.writer.core.key, node.length)) continue
        if (++seen >= this.majority) break
      }

      if (!newer && seen < this.majority) {
        break
      }

      if (!this._strictlyNewer(target, head)) {
        // all strictly newer nodes are clustered together so bisect until we find the cluster
        if (jump) {
          jump = false

          let t = length - 1
          let b = 0

          while (t > b) {
            const mid = (t + b) >>> 1
            const node = indexer.get(mid)

            if (
              node === null ||
              !node.clock.includes(target.writer.core.key, target.length) ||
              this._strictlyNewer(target, node)
            ) {
              b = mid + 1
            } else {
              t = mid - 1
            }
          }

          // + 2 in case we are off by one and the i--. its fine, just an optimisation
          if (b + 1 < i) i = b + 2
        }

        newer = false
        continue
      } else if (seen < this.majority) {
        return NEWER
      }

      return ACKED
    }

    return UNSEEN
  }

  _isConfirmed(target, parent = null) {
    const acks = this._acks(target)
    const confs = new Set()

    if (acks.length < this.majority) return false
    let allNewer = true

    for (const indexer of this.indexers) {
      const length = parent
        ? parent.writer === indexer
          ? parent.length - 1
          : parent.clock.get(indexer.core.key)
        : indexer.length

      const result = this.confirms(indexer, target, acks, length)

      if (result === ACKED) {
        confs.add(indexer)
        if (confs.size >= this.majority) {
          return true
        }
      }

      if (result === UNSEEN) allNewer = false
    }

    if (parent) return this._isConfirmableAt(target, parent, acks, confs)

    return allNewer
  }

  _isConfirmableAt(target, parent, acks, confs) {
    if (!this._ackedAt(acks, parent)) return false

    let potential = confs.size

    for (const indexer of this.indexers) {
      if (confs.has(indexer)) continue

      const length = parent.clock.get(indexer.core.key)
      const isSeen = target.clock.includes(indexer.core.key, length)

      // if the target has seen the latest node, it can freely be used to confirm the target later
      // otherwise, check if a newer node is strictly newer...
      if (!isSeen) {
        const head = indexer.get(length - 1)

        // the next indexer head HAS to be strictly newer - meaning the current one has to be also.
        if (
          head &&
          !this.removed.includes(head.writer.core.key, head.length) &&
          !this._strictlyNewer(target, head)
        ) {
          continue
        }
      }

      if (++potential >= this.majority) return true
    }

    return false
  }

  // this can get called multiple times for same node
  remove(node) {
    this.merges.delete(node)
    this.removed.set(node.writer.core.key, node.length)
    return node
  }

  shift() {
    if (!this.updated) return []

    const tails = this._indexerTails()

    for (const tail of tails) {
      if (this._isConfirmed(tail)) {
        return [this.remove(tail)]
      }
    }

    for (const merge of this.merges) {
      if (this._isConfirmed(merge)) {
        return this._yieldNext(merge, tails)
      }
    }

    this.updated = false
    return []
  }

  // yields next indexer node
  _yieldNext(node, tails) {
    // only stop when we find a tail
    while (!tails.has(node)) {
      let next = null

      // for merges check if one fork is confirmed
      for (const t of this._tailsAndMerges(node, tails)) {
        if (this._isConfirmed(t, node)) {
          next = t
          break
        }
      }

      if (next) {
        node = next
        continue
      }

      // otherwise yield all tails
      const tailSet = []
      for (const t of this._tails(node, tails)) {
        tailSet.push(this.remove(t))
      }

      return tailSet
    }

    return [this.remove(node)]
  }

  shouldAck(writer) {
    for (const t of this._indexerTails()) {
      if (t.writer === writer) continue
      if (this._shouldAckNode(t, writer)) return true
    }

    return false
  }

  _shouldAckNode(target, writer) {
    const head = writer.head()
    const next = target.clock.get(writer.core.key)
    const nextIndexNode = writer.get(next >= writer.indexed ? next : writer.indexed)

    // if we have no next node and we didn't write target then ack
    if (!nextIndexNode && writer !== target.writer) return true

    // shortcuts if we have next node
    if (nextIndexNode) {
      // if the next node does not see the target, should ack
      if (!nextIndexNode.clock.includes(target.writer.core.key, target.length)) {
        return !head.clock.includes(target.writer.core.key, target.length)
      }

      // if the next node is not strictly newer, no point acking
      if (!this._strictlyNewer(target, nextIndexNode)) return false
    }

    // now check if we can double confirm
    const acks = this._acks(target)

    // need enough to double confirm
    if (acks.length >= this.majority) {
      return this.confirms(writer, target, acks, writer.length) === UNSEEN
    }

    return false
  }
}
const HypercoreEncryption = require('hypercore/lib/default-encryption.js')
const sodium = require('sodium-universal')
const crypto = require('hypercore-crypto')
const c = require('compact-encoding')
const b4a = require('b4a')
const rrp = require('resolve-reject-promise')
const ReadyResource = require('ready-resource')

const SystemView = require('./system.js')
const { EncryptionDescriptor, ManifestData } = require('./messages.js')
const { NS_VIEW_BLOCK_KEY, NS_HASH_KEY, NS_ENCRYPTION } = require('./caps.js')

const nonce = b4a.alloc(sodium.crypto_stream_NONCEBYTES)
const hash = nonce.subarray(0, sodium.crypto_generichash_BYTES_MIN)

class AutobaseEncryption {
  static PADDING = 8

  constructor(encryption) {
    this.encryption = encryption

    this.compat = null
    this.keys = null
    this.keysById = new Map()
  }

  get id() {
    return this.keys ? this.keys.id : 0
  }

  padding() {
    return AutobaseEncryption.PADDING
  }

  isCompat() {
    return false
  }

  load(keys) {
    if (this.keys === null) this.keys = keys
  }

  async update(ctx) {
    if (this.id !== 0 && this.id === this.encryption.id) return
    const keys = await this.get(this.encryption.id, ctx)
    if (keys) this.keys = keys
  }

  async get(id, ctx) {
    if (this.keysById.has(id)) return this.keysById.get(id)

    const keys = await this.getKeys(id, ctx)
    this.keysById.set(id, keys)

    return keys
  }

  async getKeys(id, ctx) {
    const entropy = await this.encryption.get(id)
    if (!entropy) return null

    const block = this.blockKey(entropy, ctx)
    const hash = crypto.hash([NS_HASH_KEY, block])

    return {
      id,
      block,
      hash
    }
  }

  blockKey(entropy, ctx) {
    return this.encryption.blockKey(entropy, ctx)
  }

  async _ensureCompat(ctx) {
    if (!this.compat) this.compat = this.compatKeys(ctx)
  }

  compatKeys() {
    throw new Error('Compatibility method is not specified')
  }

  async encrypt(index, block, fork, ctx) {
    if (this.isCompat(ctx, index)) {
      this._ensureCompat(ctx)
      return HypercoreEncryption.encrypt(
        index,
        block,
        fork,
        this.compat.block,
        this.compat.blinding
      )
    }

    await this.update(ctx)

    encryptBlock(index, block, this.keys.id, this.keys.block, this.keys.hash)
  }

  async decrypt(index, block, ctx) {
    if (this.isCompat(ctx, index)) {
      this._ensureCompat(ctx)
      return HypercoreEncryption.decrypt(index, block, this.compat.block)
    }

    const padding = block.subarray(0, AutobaseEncryption.PADDING)
    block = block.subarray(AutobaseEncryption.PADDING)

    const type = padding[0]
    switch (type) {
      case 0:
        return block // unencrypted

      case 1:
        break

      default:
        throw new Error('Unrecognised encryption type')
    }

    const id = c.uint32.decode({ start: 4, end: 8, buffer: padding })

    const keys = await this.get(id, ctx)

    c.uint64.encode({ start: 0, end: 8, buffer: nonce }, index)
    nonce.set(padding, 8, 16)

    // Decrypt the block using the full nonce
    decrypt(block, nonce, keys.block)
  }
}

class ViewEncryption extends AutobaseEncryption {
  constructor(encryption, name) {
    super(encryption)
    this.name = name
  }

  isCompat(ctx, index) {
    if (ctx.manifest.version <= 1) return true
    if (!ctx.manifest.userData) return false
    const { legacyBlocks } = c.decode(ManifestData, ctx.manifest.userData)
    return index < legacyBlocks
  }

  compatKeys() {
    const { bootstrap, encryptionKey } = this.encryption.base
    const block = getCompatBlockKey(bootstrap, encryptionKey, this.name)
    return {
      block,
      blinding: crypto.hash(block)
    }
  }

  blockKey(entropy) {
    return getCompatBlockKey(this.encryption.base.bootstrap, entropy, this.name)
  }
}

class WriterEncryption extends AutobaseEncryption {
  isCompat(ctx) {
    return ctx.manifest.version <= 1
  }

  compatKeys(ctx) {
    return HypercoreEncryption.deriveKeys(this.encryption.base.encryptionKey, ctx.key)
  }

  blockKey(entropy, ctx) {
    if (ctx.manifest.userData) {
      const userData = c.decode(ManifestData, ctx.manifest.userData)
      if (userData.namespace !== null) {
        return this.encryption.blockKey(entropy, { key: userData.namespace })
      }
    }

    return this.encryption.blockKey(entropy, ctx)
  }
}

class EncryptionView extends ReadyResource {
  constructor(base, core) {
    super()

    this.base = base
    this.core = core || null

    this.sessions = new Map()

    this._initialising = null
  }

  async _open() {
    await this.initialised()
    await this.core.ready()
  }

  initialised() {
    if (this.core !== null) return this.core.ready()
    if (this._initialising) return this._initialising

    this._initialising = rrp()

    return this._initialising.promise
  }

  _close() {
    if (this._initialising) {
      this._initialising.reject(new Error('Encryption closed'))
      this._initialising = null
    }

    if (this.core) return this.core.close()
  }

  get bootstrapped() {
    return !!(this.core && this.core.length > 0)
  }

  get id() {
    return this.core ? this.core.length : 0
  }

  _createPayload(key) {
    return key
  }

  async reload(core) {
    if (this.core) await this.core.close()

    this.core = core
    await this.core.ready()

    if (this._initialising) {
      this._initialising.resolve()
      this._initialising = null
    }
  }

  unpack(type, payload) {
    if (type > 0) throw new Error('Unsupported version')
    return payload
  }

  async update(key) {
    const payload = await this._createPayload(key)
    const desc = { type: 0, payload }

    await this.core.append(c.encode(EncryptionDescriptor, desc))
  }

  async _preload() {
    await this.ready()
    return this.id()
  }

  getViewEncryption(name) {
    if (this.sessions.has(name)) return this.sessions.get(name)

    const encryption = new ViewEncryption(this, name)
    this.sessions.set(name, encryption)

    return encryption
  }

  getWriterEncryption() {
    return new WriterEncryption(this)
  }

  async encryptAnchor(block, namespace) {
    const entropy = await this.get(this.id)
    if (!entropy) return null

    const blockKey = this.blockKey(entropy, { key: namespace })
    const hashKey = crypto.hash([NS_HASH_KEY, block])

    encryptBlock(0, block, this.id, blockKey, hashKey)
  }

  blockKey(entropy, ctx) {
    return getBlockKey(this.base.bootstrap, this.base.encryptionKey, entropy, ctx.key)
  }

  async get(encryptionId) {
    if (encryptionId === 0) return SystemView.GENESIS_ENTROPY

    if (!this.core) await this.initialised()

    const index = encryptionId - 1
    const desc = await this.core.get(index)
    const { type, payload } = c.decode(EncryptionDescriptor, desc)

    const key = this.unpack(type, payload)
    return key
  }

  getSystemEncryption() {
    return this.getViewEncryption('_system')
  }

  static namespace(entropy) {
    return crypto.hash([NS_ENCRYPTION, entropy])
  }

  static getBlockKey(bootstrap, encryptionKey, entropy, hypercoreKey) {
    return getBlockKey(bootstrap, encryptionKey, entropy, hypercoreKey)
  }

  static getSystemEncryption(base, core) {
    const view = new EncryptionView(base, core)
    return view.getSystemEncryption()
  }

  static async setSystemEncryption(base, core, opts) {
    if (base.encryptionKey === null) return null

    await core.ready()
    if (core.manifest.version === 1) {
      const key = getCompatBlockKey(base.bootstrap, base.encryptionKey, '_system')
      return core.setEncryptionKey(key, { block: true })
    }

    if (!core.manifest.linked.length) {
      throw new Error('System manifest does not link encryption view')
    }

    const enc = base.store.get({ key: core.manifest.linked[0], active: false })
    const encryption = EncryptionView.getSystemEncryption(base, enc)

    await core.setEncryption(encryption, opts)

    return enc
  }
}

module.exports = {
  AutobaseEncryption,
  EncryptionView
}

function encrypt(block, nonce, key) {
  sodium.crypto_stream_xor(block, block, nonce, key)
}

function decrypt(block, nonce, key) {
  return encrypt(block, nonce, key) // symmetric
}

function getBlockKey(bootstrap, encryptionKey, entropy, hypercoreKey) {
  return (
    encryptionKey &&
    crypto.hash([NS_VIEW_BLOCK_KEY, bootstrap, encryptionKey, entropy, hypercoreKey])
  )
}

function getCompatBlockKey(bootstrap, encryptionKey, name) {
  if (typeof name === 'string') return getCompatBlockKey(bootstrap, encryptionKey, b4a.from(name))
  return encryptionKey && crypto.hash([NS_VIEW_BLOCK_KEY, bootstrap, encryptionKey, name])
}

function blockhash(block, padding, hashKey) {
  sodium.crypto_generichash(hash, block, hashKey)
  padding.set(hash.subarray(0, 8)) // copy first 8 bytes of hash
  hash.fill(0) // clear nonce buffer
}

function encryptBlock(index, block, id, blockKey, hashKey) {
  const padding = block.subarray(0, AutobaseEncryption.PADDING)
  block = block.subarray(AutobaseEncryption.PADDING)

  blockhash(block, padding, hashKey)
  c.uint32.encode({ start: 4, end: 8, buffer: padding }, id)

  c.uint64.encode({ start: 0, end: 8, buffer: nonce }, index)

  padding[0] = 1 // version in plaintext

  nonce.set(padding, 8, 16)

  // The combination of index, key id, fork id and block hash is very likely
  // to be unique for a given Hypercore and therefore our nonce is suitable
  encrypt(block, nonce, blockKey)
}
const rrp = require('resolve-reject-promise')
const safetyCatch = require('safety-catch')

const SystemView = require('./system.js')
const { EncryptionView } = require('./encryption.js')

const DEFAULT_OP_TIMEOUT = 5_000
const DEFAULT_MIN_FF = 16

module.exports = class FastForward {
  constructor(
    base,
    key,
    {
      timeout = DEFAULT_OP_TIMEOUT,
      verified = true,
      minimum = DEFAULT_MIN_FF,
      force = false,
      length = 0
    } = {}
  ) {
    this.base = base
    this.key = key
    this.timeout = timeout
    this.force = force
    this.core = base.store.get({ key, active: true, encryption: null })
    this.length = length
    this.views = []
    this.encryption = null
    this.entropy = null
    this.indexers = []
    this.minimum = minimum
    this.verified = verified
    this.waiting = new Set()
    this.cores = [this.core]
    this.system = null
    this.destroyed = false
    this.upgrading = null
    this.failed = false
  }

  static MINIMUM = DEFAULT_MIN_FF

  async upgrade() {
    try {
      if (!this.upgrading) this.upgrading = this._upgrade()

      if (!(await this.upgrading)) return null

      return {
        length: this.length,
        force: this.force,
        key: this.key,
        indexers: this.indexers,
        views: this.views,
        entropy: this.entropy,
        manifestVersion: this.core.manifest.version,
        minimum: this.minimum
      }
    } catch (err) {
      safetyCatch(err)
      this.failed = true
      return null
    } finally {
      await this.close()
    }
  }

  _waitForAppend(core) {
    if (core.length > 0) return Promise.resolve()

    const promise = rrp()
    const timeout = setTimeout(this.close.bind(this), this.timeout)
    const wait = { promise, timeout }

    this.waiting.add(wait)

    core.once('append', () => {
      this.waiting.delete(wait)
      clearTimeout(timeout)
      promise.resolve()
    })

    return promise.promise
  }

  _minLength() {
    return this.base.core.length + this.minimum
  }

  async _upgrade() {
    await this.core.ready()

    if (!this.verified) await this._waitForAppend(this.core)
    if (this.destroyed) return false

    if (this.core.manifest.linked) {
      const appends = []

      for (const key of this.core.manifest.linked) {
        const core = this.base.store.get({ key, active: true })
        this.cores.push(core)

        await core.ready()
        appends.push(this._waitForAppend(core))
      }

      await Promise.all(appends)
    }

    if (this.length === 0) this.length = this.core.length

    // note we use the persisted length here, as we might as well continue that work as thats ~ the same length
    if (!this.force && this.length < this._minLength()) return false
    if (this.length === 0) return false

    await this.core.get(this.length - 1, { timeout: this.timeout })
    await this.base.ready()

    if (this.destroyed) return false

    if (this.base.encryptionKey && !(await this._ensureEncryption())) return false
    if (this.destroyed) return false

    this.system = new SystemView(this.core, { checkout: this.length })
    await this.system.ready()
    if (this.destroyed) return false

    this.entropy = this.system.entropy

    if (this.core.manifest.version >= 2) {
      const linked = this.core.manifest.linked

      if (this.system.encryptionLength === 0 || linked === null || !linked.length) {
        return false
      }

      // technically diverges from system.views to include encryption here, but makes sense
      this.views.push({
        key: linked[0],
        length: this.system.encryptionLength
      })
    }

    const promises = []

    // ensure local key is locally available always
    promises.push(this.system.get(this.base.local.key, { timeout: this.timeout }))

    if (this.encryption && this.encryption.core) {
      promises.push(
        this.encryption.core.get(this.system.encryptionLength - 1, { timeout: this.timeout })
      )
    }

    for (const v of this.system.views) {
      this.views.push(v)
      const core = this.base.store.get({ key: v.key, active: true })
      this.cores.push(core)
      if (!v.length) continue // encryption view can be 0 length
      promises.push(core.get(v.length - 1, { timeout: this.timeout }))
    }

    for (const idx of this.system.indexers) {
      this.indexers.push(idx)
      if (idx.length === 0) continue // need to make sure we have manifest...
      const core = this.base.store.get({ key: idx.key, active: true })
      this.cores.push(core)
      promises.push(core.get(idx.length - 1, { timeout: this.timeout }))
      promises.push(this.system.get(idx.key, { timeout: this.timeout }))
    }

    for (const head of this.system.heads) {
      promises.push(this.system.get(head.key, { timeout: this.timeout }))
    }

    await Promise.all(promises)
    if (this.destroyed) return false

    return true
  }

  async _ensureEncryption() {
    // only need encryption if we migrated
    if (this.core.encryption !== null) return true

    const encCore = this.core.manifest.version <= 1 ? null : this.cores[1]

    // expects internal views to be loaded in order
    this.encryption = new EncryptionView(this.base, encCore)
    const encryption = this.encryption.getViewEncryption('_system')

    await this.core.setEncryption(encryption)

    return true
  }

  async close() {
    this.destroyed = true
    for (const { promise, timeout } of this.waiting) {
      clearTimeout(timeout)
      promise.resolve() // silently bail
    }
    if (this.system) await this.system.close()
    if (this.encryption) await this.encryption.close()
    for (const core of this.cores) await core.close()
    await this.core.close()
  }
}
const c = require('compact-encoding')

const SystemView = require('./system.js')
const { EncryptionView } = require('./encryption.js')
const { ManifestData } = require('./messages.js')

module.exports = class Fork {
  constructor(base, store, state, fork) {
    this.base = base
    this.store = store
    this.state = state
    this.indexers = fork.indexers
    this.length = fork.length
    this.system = null
    this.encryption = null
    this.manifests = null
    this.cores = []
  }

  async upgrade() {
    try {
      await this._upgrade()
      return true
    } catch {
      return false
    } finally {
      await this.close()
    }
  }

  async _upgrade() {
    this.manifests = await this.store.getIndexerManifests(this.indexers)

    this.system = new SystemView(await this._get('_system', this.length))
    this.encryption = new EncryptionView(this, await this._get('_encryption', -1))

    await this.system.ready()
    await this.encryption.ready()

    this.entropy = this.system.getEntropy(this.indexers, this.length)
    this.manifestVersion = Math.max(this.system.core.manifest.version, 2) // >= 2 to signal new encryption

    const views = []
    for (const view of this.state.views) {
      const v = this.getViewFromSystem(view, this.system)
      const indexedLength = v ? v.length : 0

      const session = await this._get(view.name, indexedLength)
      await session.ready()

      const next = await this.createView(view.name, session, null)
      await next.ready()

      await this._migrate(view.ref, next, view.core, indexedLength)

      // update key
      views.push({ key: next.key, length: indexedLength })
    }

    // internal views are explicitly migrated

    const entropy = EncryptionView.namespace(this.entropy)
    await this.encryption.update(entropy)

    const system = this.store.getViewByName('_system')
    const encryption = this.store.getViewByName('_encryption')

    const enc = await this.createView('_encryption', this.encryption.core, null)
    await enc.ready()

    await this._migrate(encryption, enc, this.encryption.core, this.encryption.core.length)

    await this.system.fork(this.indexers, this.manifests, this.encryption.core.length, views)

    const sys = await this.createView('_system', this.system.core, [enc.key])
    await sys.ready()

    await this._migrate(system, sys, this.system.core, this.system.core.length)
  }

  async createView(name, core, linked) {
    const prologue = await getPrologue(core)
    const manifestData = this._manifestData(core)

    return this.store.getViewCore(
      this.manifests,
      name,
      prologue,
      this.manifestVersion,
      this.entropy,
      linked,
      manifestData
    )
  }

  async _get(name, length) {
    const core = this.store.get({ name })
    this.cores.push(core)

    if (length !== -1) await core.truncate(length)

    return core
  }

  getViewFromSystem(view) {
    if (view.mappedIndex === -1 || view.mappedIndex >= this.system.views.length) return null
    return this.system.views[view.mappedIndex]
  }

  _manifestData(session) {
    if (session.manifest.version > 1) return session.manifest.userData
    return c.encode(ManifestData, { version: 0, legacyBlocks: session.length })
  }

  async _migrate(ref, next, source, length) {
    if (length > 0) {
      await next.core.copyPrologue(source.state)
    }

    // remake the batch, reset from our prologue in case it replicated inbetween
    // TODO: we should really have an HC function for this
    const batch = next.session({ name: 'batch', overwrite: true, checkout: length })
    await batch.ready()

    if (source !== null) {
      while (batch.length < source.length) {
        await batch.append(await source.get(batch.length))
      }
    }

    ref.moveTo = [batch, next]
  }

  async close() {
    this.destroyed = true
    if (this.system) await this.system.close()
    if (this.encryption) await this.encryption.close()
    for (const core of this.cores) await core.close()
  }
}

async function getPrologue(core) {
  if (!core.length) return null

  return {
    hash: await core.treeHash(),
    length: core.length
  }
}
const b4a = require('b4a')
const assert = require('nanoassert')

const Clock = require('./clock.js')
const Consensus = require('./consensus.js')
const Topolist = require('./topolist.js')

class Node {
  constructor(writer, length, value, heads, batch, dependencies, optimistic, trace) {
    this.writer = writer
    this.length = length
    this.value = value
    this.heads = heads
    this.actualHeads = heads.slice(0) // TODO: we should remove this and just not mutate heads...

    this.dependents = new Set()
    this.dependencies = dependencies
    this.index = 0 // used by topolist

    this.optimistic = optimistic && batch === 1 && !!value

    this.batch = batch
    this.dropped = 0
    this.trace = trace

    this.clock = new Clock()

    this.yielded = false
    this.yielding = false
  }

  isTail() {
    return this.dependencies.size === this.dropped
  }

  causalDependencies(idx) {
    const order = [this]
    const stack = [this]

    let visited = null

    while (stack.length > 0) {
      const node = stack.pop()
      for (const dep of node.dependencies) {
        if (!dep.writer.isRemoved || dep.writer.isActiveIndexer) continue

        // TODO: replace with "coloring" but ok for now, tiny set
        if (visited === null) visited = new Set()
        if (visited.has(dep)) continue
        visited.add(dep)

        stack.push(dep)
        order.push(dep)
      }
    }

    return order
  }

  clear() {
    this.clock = null
    this.dependents = null
    return this
  }

  reset() {
    this.yielded = false
    this.yielding = false
    for (const dep of this.dependents) dep.dependencies.add(this)
    this.dependents.clear()
  }

  active() {
    for (const dep of this.dependencies) {
      if (dep.yielded) {
        this.dependencies.delete(dep) // nodes might be yielded during buffering
      } else {
        dep.dependents.add(this)
        this.clock.add(dep.clock)
      }
    }

    if (this.writer.isActiveIndexer) this.clock.set(this.writer.core.key, this.length)
  }

  tieBreak(node) {
    return tieBreak(this, node)
  }

  hasDependency(dep) {
    for (const h of this.actualHeads) {
      if (sameNode(h, dep)) return true
    }
    return false
  }

  get ref() {
    return this.writer.core.key.toString('hex').slice(0, 2) + ':' + this.length
  }
}

module.exports = class Linearizer {
  constructor(indexers, { heads = [], writers = new Map() } = {}) {
    this.heads = new Set()
    this.tails = new Set()
    this.tip = new Topolist()
    this.size = 0 // useful for debugging
    this.updated = false
    this.indexersUpdated = false
    this.writers = writers

    this.consensus = new Consensus(indexers)
    this._initialHeads = heads.slice(0)
    this._strictlyAdded = null

    for (const { key, length } of heads) {
      this.consensus.removed.set(key, length)
    }
  }

  get indexers() {
    return this.consensus.indexers
  }

  static createNode(writer, length, value, heads, batch, dependencies, optimistic, trace) {
    return new Node(writer, length, value, heads, batch, dependencies, optimistic, trace)
  }

  // returns the global links of the dag, use this to link against the current state of the dag
  // TODO: rename to heads() and move the sets to _ props
  getHeads() {
    const heads = this._initialHeads.slice(0)
    for (const node of this.heads) heads.push({ key: node.writer.core.key, length: node.length })
    return heads
  }

  // TODO: might contain dups atm, nbd for how we use it, returns an array of writers you can "pull"
  // to get the full dag view at any time
  getBootstrapWriters() {
    const writers = []

    for (const head of this.heads) writers.push(head.writer)
    for (let i = 0; i < this.consensus.indexers.length; i++)
      writers.push(this.consensus.indexers[i])

    return writers
  }

  addHead(node) {
    node.active()

    // 99.99% of the time _initialHeads is empty...
    if (this._initialHeads.length > 0) this._updateInitialHeads(node)

    if (node.isTail()) {
      this.tails.add(node)
    }

    for (const head of this.heads) {
      if (node.hasDependency(head)) {
        this.heads.delete(head)
      }
    }

    this.tip.add(node)
    if (node.writer.isActiveIndexer) this.consensus.addHead(node)

    this.size++
    this.heads.add(node)

    this.updated = true

    return node
  }

  update() {
    if (!this.updated) return null
    this.updated = false

    // get the indexed nodes
    const indexed = []
    while (true) {
      const nodes = this.consensus.shift()
      if (!nodes.length) break

      this._yield(nodes, indexed)
    }

    return this.tip.flush(indexed)
  }

  _updateInitialHeads(node) {
    for (const head of node.actualHeads) {
      for (let i = 0; i < this._initialHeads.length; i++) {
        const { key, length } = this._initialHeads[i]
        if (length !== head.length || !b4a.equals(key, head.key)) continue
        this._initialHeads.splice(i--, 1)
      }
    }
  }

  /* Ack methods */

  shouldAck(writer, pending = false) {
    if (!writer || !writer.isActiveIndexer) return false

    // all indexers have to flushed to the dag before we ack as a quick "debounce"
    for (const w of this.indexers) {
      if (w.length !== w.available) return false
    }

    let isHead = false

    // if ANY head is not an indexer ack
    for (const head of this.heads) {
      if (!head.writer.isActiveIndexer) return true
      if (head.writer === writer) isHead = true
    }

    if (this.heads.size === 1 && isHead) {
      return false // never self-ack!
    }

    const visited = new Set()

    // check if there is non-null value
    let valueCheck = false

    for (const tail of this.tails) {
      if (pending || this._nonNull(tail, visited)) {
        valueCheck = true
        break
      }
    }

    if (!valueCheck) return false

    if (this.consensus.shouldAck(writer)) return true

    return this._shouldAckHeads(writer, pending)
  }

  // check if there is any value above this node
  _nonNull(target, visited) {
    const stack = [target]

    while (stack.length) {
      const node = stack.pop()

      if (visited.has(node)) continue
      if (node.value !== null) return true

      visited.add(node)

      for (const dep of node.dependents) {
        stack.push(dep)
      }
    }

    return false
  }

  // ack if any head is closer to confirming a value
  _shouldAckHeads(writer, pending) {
    const prev = writer.head()

    for (const head of this.heads) {
      // only check other writers heads
      if (head.writer === writer) continue

      const stack = [head]
      const visited = new Set()

      while (stack.length) {
        const node = stack.pop()

        if (visited.has(node)) continue
        visited.add(node)

        if (pending || node.value !== null) {
          const acks = this.consensus.acksFromNode(node, head)
          const prevAcks = this.consensus.acksFromNode(node, prev)

          // head sees more acks
          if (acks.size > prevAcks.size) return true

          for (const idx of acks) {
            // head sees acks that writer does not
            if (!prevAcks.has(idx)) return true
          }

          // both seen, no point going any further down
          if (prevAcks.size && acks.size) continue
        }

        stack.push(...node.dependencies)
      }
    }

    return false
  }

  /* Full DAG methods */

  _yield(nodes, indexed = []) {
    const offset = indexed.length
    const tails = []

    // determine which nodes are yielded
    while (nodes.length) {
      const node = nodes.pop()

      if (node.yielding) continue
      node.yielding = true

      if (node.isTail()) tails.push(node)

      nodes.push(...node.dependencies)
    }

    while (tails.length) {
      let tail = tails.pop()

      for (tail of this._removeBatch(tail)) {
        Topolist.add(tail, indexed, offset)
      }

      for (const dep of tail.dependents) {
        if (dep.isTail() && dep.yielding) tails.push(dep)
      }
    }

    return indexed
  }

  _isFutureTail(node) {
    let dropped = node.dropped

    // a tail has no unyielded dependencies
    for (const dep of node.dependencies) {
      if (dep.yielded) continue
      if (dropped === 0) return false
      dropped--
    }

    return true
  }

  _removeNode(node) {
    this.tails.delete(node)
    this.heads.delete(node)
    this.consensus.remove(node)

    // update the tailset
    for (const d of node.dependents) {
      if (d.yielding && d.dependencies.has(node))
        d.dropped++ // keep links for the indexed batch
      else d.dependencies.delete(node)
      if (this._isFutureTail(d)) this.tails.add(d)
    }

    node.yielded = true
    this.size--

    if (this.heads.size === 0) {
      // in case of a single writer the dag might drain immediately...
      this._initialHeads.push({ key: node.writer.core.key, length: node.length })
    }

    return node
  }

  _removeBatch(node) {
    const batch = [this._removeNode(node)]

    while (node.batch !== 1) {
      // its a batch!
      if (node.dependents.size === 0) {
        // bad batch node, auto correct
        const next = node.writer.get(node.length)
        if (next && next.batch === node.batch - 1) node.dependents.add(next)
      }

      assert(node.dependents.size === 1, 'Batch is linked partially, which is not allowed')

      node = getFirst(node.dependents)
      batch.push(this._removeNode(node))
    }

    return batch
  }
}

function tieBreak(a, b) {
  return Topolist.compare(a, b) < 0 // lowest key wis
}

function getFirst(set) {
  return set[Symbol.iterator]().next().value
}

function sameNode(a, b) {
  return b4a.equals(a.key, b.writer.core.key) && a.length === b.length
}
const c = require('compact-encoding')
const b4a = require('b4a')

const messages = require('./messages.js')

const GTE = b4a.from([messages.LINEARIZER_PREFIX])
const LT = b4a.from([messages.LINEARIZER_PREFIX + 1])

module.exports = class LocalState {
  constructor(core) {
    this.core = core
    this.tx = null
  }

  static clear(core) {
    const tx = core.state.storage.write()
    tx.deleteLocalRange(GTE, LT)
    return tx.flush()
  }

  static async moveTo(src, dst) {
    const boot = await src.getUserData('autobase/boot')
    const tx = dst.state.storage.write()

    tx.deleteLocalRange(GTE, LT)

    for await (const data of src.state.storage.createLocalStream({ gte: GTE, lt: LT })) {
      tx.putLocal(data.key, data.value)
    }

    tx.putUserData('autobase/boot', boot)

    await tx.flush()
  }

  setBootRecord(boot) {
    if (this.tx === null) this.tx = this.core.state.storage.write()

    this.tx.putUserData('autobase/boot', c.encode(messages.BootRecord, boot))
  }

  async listUpdates() {
    const updates = []

    for await (const data of this.core.state.storage.createLocalStream({ gte: GTE, lt: LT })) {
      const update = c.decode(messages.LinearizerUpdate, data.value)
      const seq = c.decode(messages.LinearizerKey, data.key)
      update.seq = seq
      updates.push(update)
    }

    return updates
  }

  clearUpdates() {
    if (this.tx === null) this.tx = this.core.state.storage.write()

    this.tx.deleteLocalRange(GTE, LT)
  }

  deleteUpdate(update) {
    if (this.tx === null) this.tx = this.core.state.storage.write()

    this.tx.deleteLocal(c.encode(messages.LinearizerKey, update.seq))
  }

  insertUpdate(update) {
    if (this.tx === null) this.tx = this.core.state.storage.write()

    this.tx.putLocal(
      c.encode(messages.LinearizerKey, update.seq),
      c.encode(messages.LinearizerUpdate, update)
    )
  }

  flush() {
    if (!this.tx) return Promise.resolve()

    const flushing = this.tx.flush()
    this.tx = null
    return flushing
  }
}
const schema = require('../encoding/spec/autobase')

module.exports = {
  Wakeup: schema.resolveStruct('@autobase/wakeup'),
  Clock: schema.resolveStruct('@autobase/clock'),
  Checkout: schema.resolveStruct('@autobase/checkout'),
  BootRecord: schema.resolveStruct('@autobase/boot-record'),
  OplogMessage: schema.resolveStruct('@autobase/oplog-message'),
  Checkpoint: schema.resolveStruct('@autobase/checkpoint'),
  Info: schema.resolveStruct('@autobase/info'),
  Member: schema.resolveStruct('@autobase/member'),
  ManifestData: schema.resolveStruct('@autobase/manifest-data'),
  LINEARIZER_PREFIX: 1,
  LinearizerKey: schema.resolveStruct('@autobase/linearizer-key'),
  LinearizerUpdate: schema.resolveStruct('@autobase/linearizer-update'),
  EncryptionDescriptor: schema.resolveStruct('@autobase/encryption-descriptor')
}
const DEFAULT_SIZE = 32

module.exports = class NodeBuffer {
  constructor(offset, hwm) {
    this.hwm = hwm || DEFAULT_SIZE
    this.defaultHwm = this.hwm
    this.mask = this.hwm - 1
    this.top = 0
    this.btm = 0
    this.buffer = new Array(this.hwm)
    this.offset = offset || 0
    this.length = this.offset
  }

  get size() {
    return this.length - this.offset
  }

  isEmpty() {
    return this.length === this.offset
  }

  isFull() {
    return this.size === this.buffer.length
  }

  grow() {
    this.hwm <<= 1

    const size = this.size
    const buffer = new Array(this.hwm)
    const mask = this.hwm - 1

    for (let i = 0; i < size; i++) {
      buffer[i] = this.buffer[(this.btm + i) & this.mask]
    }

    this.mask = mask
    this.top = size
    this.btm = 0
    this.buffer = buffer
  }

  push(data) {
    if (this.isFull()) this.grow()

    this.buffer[this.top] = data
    this.top = (this.top + 1) & this.mask

    return this.length++
  }

  shift() {
    if (this.isEmpty()) return null

    const last = this.buffer[this.btm]

    this.buffer[this.btm] = undefined
    this.btm = (this.btm + 1) & this.mask
    this.offset++

    // reset on empty
    if (this.isEmpty() && this.hwm !== this.defaultHwm) {
      this.buffer = new Array(this.defaultHwm)
      this.hwm = this.buffer.length
      this.mask = this.hwm - 1
      this.top = this.btm = 0
    }

    return last
  }

  get(seq) {
    if (seq < this.offset || seq >= this.length) return null
    return this.buffer[(this.btm + (seq - this.offset)) & this.mask]
  }
}
const b4a = require('b4a')
const c = require('compact-encoding')
const crypto = require('hypercore-crypto')
const Hypercore = require('hypercore')

const messages = require('./messages.js')

const DEFAULT_MANIFEST_VERSION = 1
const INDEX_VERSION = 1
const MAX_TRACE_PER_VIEW = 256

const EMPTY = b4a.alloc(0)

const [NS_SIGNER_NAMESPACE] = crypto.namespace('autobase', 1)

class ViewCore {
  constructor(name, core, base) {
    this.name = name
    this.core = null
    this.batch = null
    this.atomicBatch = null
    this.moveTo = null
    this.tracer = new Tracer()
    this.shared = 0

    this.ontruncate = (length) => {
      this.shared = Math.min(this.shared, length)
    }
    this.migrated(base, core)
  }

  getCore() {
    return this.atomicBatch || this.batch || this.core
  }

  migrated(base, core) {
    // TODO: close old core if present, for now we just close when the autobase is closed indirectly
    // atm its unsafe to do as moveTo has a bug due to a missing read lock in hc
    this.core = core

    if (this.name === '_system') {
      const ff = base._queueFastForward.bind(base)
      this.core.on('append', ff)
      this.core.ready().then(ff, ff)
    }
  }

  async matchesKey(key) {
    if (!this.core.opened) await this.core.ready()
    return b4a.equals(this.core.key, key)
  }

  async matchesNamespace(target) {
    if (!this.core.opened) await this.core.ready()

    if (this.core.manifest && this.core.manifest.signers.length > 0) {
      const ns = this.core.manifest.signers[0].namespace
      if (b4a.equals(ns, target)) return true
    }

    return false
  }

  getNextKey() {
    return this.moveTo ? this.moveTo[0].key : null
  }

  async commit(atom, length, signature) {
    // TODO: is this how its supposed be done atomic wise?
    await this.core.commit(this._getAtomicBatch(atom), { length, signature })
  }

  async release() {
    if (!this.atomicBatch) return
    await this.atomicBatch.ready()

    while (this.atomicBatch.state.sessions.length) {
      await this.atomicBatch.state.sessions[0].close()
    }

    await this.atomicBatch.close()
    this.atomicBatch = null
  }

  _getAtomicBatch(atom) {
    if (this.atomicBatch === null) {
      this.atomicBatch = this.batch.session({ atom, writable: true })
      this.atomicBatch.on('truncate', this.ontruncate)
    }

    return this.atomicBatch
  }

  async catchup(atom, length) {
    await this.release()
    const batch = this._getAtomicBatch(atom)
    await batch.ready()
    await batch.state.catchup(length)
  }

  createSession(atom, valueEncoding) {
    if (this.batch === null) {
      this.batch = this.core.session({ name: 'batch', writable: true })
      this.batch.on('truncate', this.ontruncate)
    }

    const s = atom
      ? this._getAtomicBatch(atom).session({
          valueEncoding,
          writable: true,
          onseq: this.tracer.onseq.bind(this.tracer)
        })
      : this.batch.session({ valueEncoding, writable: false })

    return s
  }
}

class Tracer {
  constructor() {
    this.enabled = false
    this.seen = new Set()
  }

  start() {
    this.enabled = true
    this.seen.clear()
  }

  end() {
    this.enabled = false
    return [...this.seen.values()]
  }

  onseq(seq, core) {
    if (!this.enabled) return
    if (this.seen.size >= MAX_TRACE_PER_VIEW) return
    if (seq >= core.signedLength) return

    this.seen.add(seq)
  }
}

class AutoStore {
  constructor(base, byName) {
    this.base = base
    this.store = base.store
    this.byName = byName || new Map()
    this.opened = []
    this.atom = null
    this.local = null
  }

  async close() {
    if (this.local) await this.local.close()
    for (const v of this.byName.values()) {
      await v.release()
    }
    if (this.atom) return
    for (const v of this.byName.values()) {
      if (v.core) await v.core.close()
      if (v.batch) await v.batch.close()
    }
  }

  async export() {
    const views = []

    for (const [name, value] of this.byName) {
      const core = await this.store.storage.export(value.core.discoveryKey, { batches: true })
      views.push({ name, core })
    }

    return views
  }

  atomize() {
    const store = new AutoStore(this.base, this.byName)
    store.atom = this.store.storage.createAtom()
    return store
  }

  async updateLocal() {
    if (!this.local) return
    await this.local.close()
    this.local = null
  }

  flush() {
    return this.atom ? this.atom.flush() : Promise.resolve()
  }

  get(opts, moreOpts) {
    if (typeof opts === 'string') opts = { name: opts }
    if (moreOpts) opts = { ...opts, ...moreOpts }

    const { name, valueEncoding = null } = opts

    if (!name) throw new Error('name is required')
    return this.getViewByName(name).createSession(this.atom, valueEncoding)
  }

  getViewByName(name) {
    let view = this.byName.get(name)

    if (!view) {
      const preload = this._preload(name)
      const core = this.base.store.get({ preload })
      view = new ViewCore(name, core, this.base)
      this.byName.set(name, view)
    }

    if (this.opened.indexOf(view) === -1) {
      this.opened.push(view)
    }

    return view
  }

  getLocal() {
    if (this.local !== null) return this.local

    this.local = this.base.local.session({
      atom: this.atom,
      valueEncoding: messages.OplogMessage,
      encryption: this.base.getWriterEncryption(this.base.local.key),
      active: false
    })

    return this.local
  }

  getViews() {
    return [...this.byName.values()]
  }

  getViewCount() {
    return this.byName.size
  }

  getSystemView() {
    return this.getViewByName('_system')
  }

  getSystemCore() {
    return this.getSystemView().core
  }

  getEncryption(name) {
    if (!this.base.encryptionKey) return null
    if (name === '_encryption') return null

    return this.base.encryption.getViewEncryption(name)
  }

  async getIndexerManifests(entries) {
    const manifests = []
    for (const { key } of entries) {
      const core = this.store.get({ key, active: false })
      await core.ready()
      if (!core.manifest) continue // danger but only for bootstrapping...
      manifests.push(core.manifest)
      await core.close()
    }
    return manifests
  }

  getViewCore(indexerManifests, name, prologue, manifestVersion, entropy, linked, manifestData) {
    const manifest = this._createManifest(
      indexerManifests,
      name,
      prologue,
      manifestVersion,
      entropy,
      linked,
      manifestData
    )

    return this.base.store.get({
      manifest,
      exclusive: false,
      encryption: this.getEncryption(name)
    })
  }

  listViews() {
    const views = []
    for (const [name, ref] of this.byName) {
      const core = ref.batch || ref.core
      views.push({ name, key: core.key, length: core.length, signedLength: core.signedLength })
    }
    return views
  }

  createAnchorCore(prologue, manifestData) {
    const manifest = {
      version: 2,
      hash: 'blake2b',
      prologue,
      allowPatch: false,
      quorum: 0,
      signers: [],
      userData: manifestData,
      linked: null
    }

    const core = this.store.get({
      manifest,
      active: false
    })

    return core
  }

  async createView(
    indexerManifests,
    name,
    prologue,
    manifestVersion,
    entropy,
    linked,
    manifestData
  ) {
    const manifest = this._createManifest(
      indexerManifests,
      name,
      prologue,
      manifestVersion,
      entropy,
      linked,
      manifestData
    )

    const core = this.store.get({
      key: Hypercore.key(manifest),
      manifest,
      active: false
    })

    await core.ready()
    const key = core.key

    await core.close()
    return key
  }

  async _preload(name) {
    await Promise.resolve()

    if (!this.base.opening) throw new Error('Autobase failed to open')
    await this.base._preopen

    const boot = (await this.base._getSystemInfo()) || {
      key: this.getBootstrapSystemKey(),
      indexers: [],
      views: [],
      entropy: null
    }
    const indexerManifests = await this.getIndexerManifests(boot.indexers)

    // no system, everything is fresh
    if (boot.indexers.length === 0) {
      return this._freshCorePreload(indexerManifests, name, boot.entropy)
    }

    // asking for the system, just return it, easy
    if (name === '_system') {
      return {
        key: boot.key,
        exclusive: false,
        encryption: this.getEncryption(name)
      }
    }

    if (name === '_encryption') {
      const core = this.getSystemCore()
      await core.ready()

      if (!core.manifest.linked) {
        return this._freshCorePreload(indexerManifests, name, boot.entropy)
      }

      return {
        key: core.manifest.linked[0],
        exclusive: false,
        encryption: null
      }
    }

    // infer which view
    const v = await this.findViewByName(indexerManifests, boot.views, name, boot.entropy)

    // new view, fresh
    if (v === null) {
      return this._freshCorePreload(indexerManifests, name, boot.entropy)
    }

    return {
      key: v.key,
      exclusive: false,
      encryption: this.getEncryption(name)
    }
  }

  _freshCorePreload(indexerManifests, name, entropy) {
    if (name === '_system') return this._freshSystemPreload(indexerManifests, entropy)

    return {
      manifest: this._createManifest(
        indexerManifests,
        name,
        null,
        DEFAULT_MANIFEST_VERSION,
        entropy,
        [],
        null
      ),
      exclusive: true,
      encryption: this.getEncryption(name)
    }
  }

  _freshSystemPreload(indexerManifests, entropy) {
    return {
      manifest: this._createSystemManifest(
        indexerManifests,
        null,
        DEFAULT_MANIFEST_VERSION,
        entropy,
        null
      ),
      exclusive: true,
      encryption: this.getEncryption('_system')
    }
  }

  _deriveStaticHash(name) {
    // key doesnt matter...
    return crypto.hash([this.base.key, b4a.from(name)])
  }

  _deriveNamespace(name, entropy) {
    const encryptionId = crypto.hash(this.base.encryptionKey || EMPTY)
    const version = c.encode(c.uint, INDEX_VERSION)
    const bootstrap = this.base.key

    return crypto.hash([
      NS_SIGNER_NAMESPACE,
      version,
      bootstrap,
      encryptionId,
      entropy,
      b4a.from(name)
    ])
  }

  async _getCoreManifest(key) {
    const core = this.store.get({ key, active: false })
    await core.ready()
    const manifest = core.manifest
    await core.close()
    return manifest
  }

  getBootstrapSystemKey() {
    return Hypercore.key(this._createSystemManifest([], null, DEFAULT_MANIFEST_VERSION, null))
  }

  async findViewByKey(key, indexers, manifestVersion, entropy) {
    for (const v of this.byName.values()) {
      if (await v.matchesKey(key)) return v
    }

    const manifest = await this._getCoreManifest(key)
    const target = manifest && manifest.signers.length ? manifest.signers[0].namespace : null

    if (target) {
      for (const v of this.byName.values()) {
        if (await v.matchesNamespace(target)) return v
      }
    }

    const indexerManifests = await this.getIndexerManifests(indexers)

    if (entropy === null) {
      entropy = indexerManifests[0].signers[0].namespace
    }

    if (target) {
      for (const v of this.byName.values()) {
        const namespace = this._deriveNamespace(v.name, entropy)
        if (b4a.equals(namespace, target)) return v
      }
    }

    // prob the empty prologue, we dont have manifest for those in FF if len=0
    for (const v of this.byName.values()) {
      const manifestData = v.core ? v.core.manifest.userData : null
      const manifest = this._createManifest(
        indexerManifests,
        v.name,
        null,
        manifestVersion,
        entropy,
        [],
        manifestData
      )
      const manifestKey = Hypercore.key(manifest)

      if (!b4a.equals(manifestKey, key)) continue

      // we didnt have the core! this is because it is empty, ensure its on disk
      const core = this.store.get({ key: manifestKey, manifest, active: false })
      await core.ready()
      await core.close()

      return v
    }

    return null
  }

  async findViewByName(indexerManifests, views, name, entropy) {
    if (indexerManifests.length === 0) return null

    if (entropy === null) entropy = indexerManifests[0].signers[0].namespace
    const namespace = this._deriveNamespace(name, entropy)

    for (const v of views) {
      const manifest = await this._getCoreManifest(v.key)
      if (manifest.signers.length === 0) continue

      const signer = manifest.signers[0]

      if (b4a.equals(signer.namespace, namespace)) return v
    }

    return null
  }

  _createManifest(indexerManifests, name, prologue, version, entropy, linked, manifestData) {
    if (!indexerManifests.length) {
      prologue = {
        hash: this._deriveStaticHash(name),
        length: 0
      }
    } else if (prologue && prologue.length === 0) {
      // just in case
      prologue = null
    }

    const signers = []

    if (indexerManifests.length && entropy === null) {
      entropy = indexerManifests[0].signers[0].namespace
    }

    for (const manifest of indexerManifests) {
      const signer = manifest.signers[0]

      signers.push({
        namespace: this._deriveNamespace(name, entropy),
        signature: 'ed25519',
        publicKey: signer.publicKey
      })
    }

    return {
      version,
      hash: 'blake2b',
      prologue,
      allowPatch: true,
      quorum: Math.min(signers.length, (signers.length >> 1) + 1),
      signers,
      userData: manifestData,
      linked: version > 1 ? linked : null
    }
  }

  _createSystemManifest(indexerManifests, prologue, version, entropy, manifestData) {
    if (prologue !== null) throw new Error('Can only derive fresh system core')

    const linked = []

    if (version > DEFAULT_MANIFEST_VERSION) {
      const encManifest = this._createManifest(
        indexerManifests,
        '_encryption',
        null,
        version,
        entropy,
        [],
        manifestData
      )
      linked.push(Hypercore.key(encManifest))
    }

    return this._createManifest(
      indexerManifests,
      '_system',
      null,
      version,
      entropy,
      linked,
      manifestData
    )
  }
}

module.exports = AutoStore
const Hyperbee = require('hyperbee')
const SubEncoder = require('sub-encoder')
const ReadyResource = require('ready-resource')
const b4a = require('b4a')
const c = require('compact-encoding')
const crypto = require('hypercore-crypto')

const { Info, Member } = require('./messages.js')
const { DEFAULT_AUTOBASE_VERSION } = require('./caps.js')

const subs = new SubEncoder()

const DIGEST = subs.sub(b4a.from([0]))
const MEMBERS = subs.sub(b4a.from([1]))

const INFO_KEY = DIGEST.encode('info')

const [GENESIS_ENTROPY, NS_ENTROPY] = crypto.namespace('autobase/entropy', 2)

module.exports = class SystemView extends ReadyResource {
  constructor(core, { checkout = 0, empty = false } = {}) {
    super()

    this.core = core

    // sessions is a workaround for batches not having sessions atm...
    this.db = new Hyperbee(core, {
      keyEncoding: 'binary',
      extension: false,
      checkout,
      sessions: typeof core.session === 'function'
    })

    this.version = DEFAULT_AUTOBASE_VERSION
    this.members = 0
    this.pendingIndexers = []
    this.indexers = []
    this.heads = []
    this.views = []
    this.encryptionLength = 0
    this.entropy = null

    this.indexerUpdate = false

    this._empty = empty
    this._fork = 0
    this._length = 0
    this._changes = []
    this._indexerMap = new Map()
    this._clockUpdates = new Map()
  }

  static GENESIS_ENTROPY = GENESIS_ENTROPY

  static async getIndexedInfo(core, length) {
    const sys = new this(core.session())

    try {
      return await sys.getIndexedInfo(length)
    } finally {
      await sys.close()
    }
  }

  static async *flushes(core, { reverse, lt = core.length, gte = 0, wait = true } = {}) {
    if (lt <= 0) return

    // ensure block
    await core.get(lt - 1)
    const sys = new SystemView(core)

    try {
      for await (const data of sys.db.createHistoryStream({ lt, gte, wait, reverse: true })) {
        if (!b4a.equals(data.key, INFO_KEY)) continue
        const info = c.decode(Info, data.value)
        yield { length: data.seq + 1, info }
      }
    } finally {
      await sys.close()
    }
  }

  get bootstrapping() {
    return this.members === 0
  }

  async checkout(length) {
    const checkout = new SystemView(this.core.session(), {
      checkout: length,
      empty: length === 0
    })

    await checkout.ready()

    return checkout
  }

  async _open() {
    // this should NEVER fail, if so we have a bug elsewhere (should always be consistent)
    const info = this._empty
      ? null
      : await this.db.get('info', {
          valueEncoding: Info,
          keyEncoding: DIGEST,
          update: false,
          wait: false
        })
    await this._reset(info)
  }

  async _close() {
    await this.db.close()
  }

  async getIndexedInfo(length = this.core.signedLength) {
    if (this.opened === false) await this.ready()

    if (length === this.core.length) {
      return {
        version: this.version,
        members: this.members,
        pendingIndexers: this.pendingIndexers,
        indexers: this.indexers,
        heads: this.heads,
        views: this.views,
        encryptionLength: this.encryptionLength,
        entropy: this.entropy
      }
    }

    const node = length === 0 ? null : await this.db.getBySeq(length - 1)
    if (node === null) {
      return {
        version: DEFAULT_AUTOBASE_VERSION,
        members: 0,
        pendingIndexers: [],
        indexers: [],
        heads: [],
        views: [],
        encryptionLength: 0,
        entropy: null
      }
    }

    return c.decode(Info, node.value)
  }

  static sameIndexers(a, b) {
    if (a.length !== b.length) return false

    for (let i = 0; i < a.length; i++) {
      if (!b4a.equals(a[i].key, b[i].core.key)) return false
    }

    return true
  }

  sameIndexers(indexers) {
    return SystemView.sameIndexers(this.indexers, indexers)
  }

  async history(since) {
    const checkout = this.db.checkout(since)
    const seen = new Map()

    const nodes = []
    const updates = []

    const checkoutNode = since === 0 ? null : await this.db.getBySeq(since - 1)

    let prevInfo = checkoutNode === null ? null : c.decode(Info, checkoutNode.value)
    let updateBatch = 0

    for await (const data of this.db.createHistoryStream({ gte: since })) {
      if (b4a.equals(data.key, INFO_KEY)) {
        const info = c.decode(Info, data.value)

        updates.push({
          batch: updateBatch,
          indexers: prevInfo === null || !sameIndexers(info, prevInfo),
          systemLength: data.seq + 1
        })

        prevInfo = info
        updateBatch = 0
        continue
      }

      const key = data.key.subarray(2)
      const hex = b4a.toString(key, 'hex')
      const len = c.decode(Member, data.value).length

      if (!seen.has(hex)) {
        const node = await checkout.get(data.key)
        if (node === null) {
          seen.set(hex, 0)
        } else {
          const { length } = c.decode(Member, node.value)
          seen.set(hex, length)
        }
      }

      const prev = seen.get(hex)
      const batch = len - prev
      seen.set(hex, len)

      if (batch === 0) continue

      updateBatch += batch

      if (nodes.length > 0) {
        const top = nodes[nodes.length - 1]
        if (b4a.equals(top.key, key)) {
          top.length = len
          top.batch += batch
          continue
        }
      }

      nodes.push({
        key,
        length: len,
        batch
      })
    }

    await checkout.close()

    return { updates, nodes }
  }

  async update() {
    if (this.opened === false) await this.ready()

    if (this._fork === this.core.fork && this._length === this.core.length) return false

    await this._reset(
      this._empty ? null : await this.db.get('info', { valueEncoding: Info, keyEncoding: DIGEST })
    )
    return true
  }

  async _reset(info) {
    this.version = info === null ? DEFAULT_AUTOBASE_VERSION : info.value.version
    this.members = info === null ? 0 : info.value.members
    this.pendingIndexers = info === null ? [] : info.value.pendingIndexers
    this.indexers = info === null ? [] : info.value.indexers
    this.heads = info === null ? [] : info.value.heads
    this.views = info === null ? [] : info.value.views
    this.encryptionLength = info === null ? 0 : info.value.encryptionLength
    this.entropy = info === null ? null : info.value.entropy

    this.indexerUpdate = false
    this._indexerMap.clear()
    this._clockUpdates.clear()
    this._length = this.core.length
    this._fork = this.core.fork
    this._changes = []

    for (const idx of this.indexers) {
      this._indexerMap.set(b4a.toString(idx.key, 'hex'), idx)
    }
  }

  // helper used by apply-state
  flushLength() {
    const header = this.core.length ? 0 : 1 // account for header

    let updates = this._changes.length + this._clockUpdates.size
    for (const { key } of this._changes) {
      const hex = b4a.toString(key, 'hex')
      if (this._clockUpdates.has(hex)) updates-- // shared are skipped
    }

    return header + this.core.length + updates + 1
  }

  async flush(views) {
    const batch = this.db.batch({ update: false })

    for (let i = 0; i < this._changes.length; i++) {
      const c = this._changes[i]
      if (this._clockUpdates.has(b4a.toString(c.key, 'hex'))) continue
      await batch.put(c.key, c.value, { valueEncoding: Member, keyEncoding: MEMBERS })
    }

    for (const [hex, length] of this._clockUpdates) {
      const isIndexer = this._indexerMap.get(hex) !== undefined
      const key = b4a.from(hex, 'hex')

      const info = await this._get(key, 0)

      const value = { isIndexer, isRemoved: info ? info.isRemoved : true, length }
      await batch.put(key, value, { valueEncoding: Member, keyEncoding: MEMBERS })
    }

    if (this.indexerUpdate) {
      this._refreshEntropy(this.core.length + batch.length + 1)
    }

    this._clockUpdates.clear()

    let maxIndex = -1
    for (const view of views) {
      if (view.mappedIndex > maxIndex) maxIndex = view.mappedIndex
    }

    while (this.views.length > maxIndex + 1) this.views.pop()

    for (const view of views) {
      const length = view.core ? view.core.length : view.length
      if (!length) continue

      const v = { key: view.key, length }

      if (view.mappedIndex !== -1) {
        this.views[view.mappedIndex] = v
      } else {
        view.mappedIndex = this.views.push(v) - 1
      }
    }

    const info = {
      version: this.version,
      members: this.members,
      pendingIndexers: this.pendingIndexers,
      indexers: this.indexers,
      heads: this.heads,
      views: this.views,
      encryptionLength: this.encryptionLength,
      entropy: this.entropy
    }

    await batch.put('info', info, { valueEncoding: Info, keyEncoding: DIGEST })
    await batch.flush()

    this._length = this.core.length // should be ok
    this._changes = []

    if (this.indexerUpdate) this.indexerUpdate = false
  }

  getEntropy(indexers, length) {
    return generateEntropy(indexers, length, this.entropy)
  }

  _refreshEntropy(length) {
    if (this.version < 2) return
    this.entropy = this.getEntropy(this.indexers, length)
  }

  checkpoint() {
    return {
      version: this.version,
      members: this.members,
      pendingIndexers: this.pendingIndexers.slice(0),
      indexers: cloneNodes(this.indexers),
      heads: cloneNodes(this.heads),
      views: cloneNodes(this.views),
      indexerUpdate: this.indexerUpdate,
      encryptionLength: this.encryptionLength,
      entropy: this.entropy ? b4a.from(this.entropy) : null,
      changes: this._changes.slice(0),
      clockUpdates: new Map([...this._clockUpdates])
    }
  }

  applyCheckpoint(checkpoint) {
    this.version = checkpoint.version
    this.members = checkpoint.members
    this.pendingIndexers = checkpoint.pendingIndexers
    this.indexers = checkpoint.indexers
    this.heads = checkpoint.heads
    this.views = checkpoint.views
    this.indexerUpdate = checkpoint.indexerUpdate
    this.encryptionLength = checkpoint.encryptionLength
    this.entropy = checkpoint.entropy

    this._changes = checkpoint.changes
    this._clockUpdates = checkpoint.clockUpdates

    this._indexerMap = new Map()
    for (const idx of this.indexers) {
      this._indexerMap.set(b4a.toString(idx.key, 'hex'), idx)
    }
  }

  addHead(node) {
    const h = { key: node.writer.core.key, length: node.length }

    for (let i = 0; i < this.heads.length; i++) {
      const head = this.heads[i]

      if (!hasDependency(node, head)) {
        if (!b4a.equals(node.writer.core.key, head.key)) continue

        // todo: remove in next major because bug was fixed here:
        // https://github.com/holepunchto/autobase-next/pull/237

        // filter out any bad heads introduced by a bug to
        // prevent inconsistencies being written to the oplog
        if (head.length > h.length) return false
      }

      const popped = this.heads.pop()
      if (popped !== head) this.heads[i--] = popped
    }

    this.heads.push(h)

    const hex = b4a.toString(h.key, 'hex')

    this._clockUpdates.set(hex, h.length)

    if (this.pendingIndexers.length > 0) {
      for (let i = 0; i < this.pendingIndexers.length; i++) {
        if (!b4a.equals(this.pendingIndexers[i], h.key)) continue
        this._updateIndexer(h.key, h.length, true, i)
        return true
      }
    }

    const idx = this._indexerMap.get(hex)
    if (idx !== undefined) {
      idx.length = h.length
    }

    return false
  }

  _updateIndexer(key, length, isIndexer, i) {
    const hex = b4a.toString(key, 'hex')

    if (!isIndexer) {
      const existing = this._indexerMap.get(hex)
      if (existing) {
        this.indexerUpdate = true
        this.indexers.splice(this.indexers.indexOf(existing), 1)
        this._indexerMap.delete(hex)
      }
      return
    }

    for (; i < this.pendingIndexers.length; i++) {
      if (b4a.equals(this.pendingIndexers[i], key)) {
        break
      }
    }

    if (length === 0) {
      if (i >= this.pendingIndexers.length) this.pendingIndexers.push(key)
      return
    }

    if (i < this.pendingIndexers.length) {
      const top = this.pendingIndexers.pop()
      if (i < this.pendingIndexers.length) this.pendingIndexers[i] = top
    }

    const idx = this._indexerMap.get(hex)

    if (idx === undefined) {
      const newIdx = { key, length }
      this._indexerMap.set(hex, newIdx)
      this.indexers.push(newIdx)

      // bootstrap is "silently" added so that initial views have no prologue
      if (!this.bootstrapping) this.indexerUpdate = true
    } else {
      idx.length = length
    }
  }

  _seenLength(key) {
    return this._clockUpdates.get(b4a.toString(key, 'hex')) || 0
  }

  async ack(key) {
    const value = await this._get(key, 0)
    const length = this._seenLength(key)
    if (value && value.length === length) return

    const isIndexer = value ? value.isIndexer : false
    const isRemoved = value ? value.isRemoved : true

    this._changes.push({ key, value: { isIndexer, isRemoved, length } })
  }

  async add(key, { isIndexer = false, length = this._seenLength(key) } = {}) {
    let value = null
    let found = false
    let changed = true

    for (let i = this._changes.length - 1; i >= 0; i--) {
      const c = this._changes[i]
      if (b4a.equals(key, c.key)) {
        value = c.value
        found = true
        break
      }
    }

    if (!found) {
      const node = await this.db.get(key, { valueEncoding: Member, keyEncoding: MEMBERS })

      if (node) {
        value = node.value
        found = true
      }
    }

    let wasTracked = false
    let wasIndexer = false

    if (found) {
      if (!value.isRemoved) wasTracked = true
      if (value.isIndexer) wasIndexer = true
      if (length < value.length) length = value.length
      if (value.length === length && value.isIndexer === isIndexer && value.isRemoved === false)
        changed = false
    }

    if (changed) {
      this._changes.push({ key, value: { isIndexer, isRemoved: false, length } })
    }

    if (!wasTracked) this.members++
    if (wasIndexer || isIndexer) this._updateIndexer(key, length, isIndexer, 0)
  }

  async remove(key) {
    let isIndexer = false

    for (const idx of this.indexers) {
      isIndexer = b4a.equals(idx.key, key)
      if (isIndexer) break
    }

    if (isIndexer) this._updateIndexer(key, null, false, 0)

    let value = null
    let found = false

    for (let i = this._changes.length - 1; i >= 0; i--) {
      const c = this._changes[i]
      if (b4a.equals(key, c.key)) {
        value = c.value
        found = true
        break
      }
    }

    if (!found) {
      const node = await this.db.get(key, { valueEncoding: Member, keyEncoding: MEMBERS })
      if (node) {
        value = node.value
        found = true
      }
    }

    const changed = !found || !value.isRemoved
    const wasTracked = found && !value.isRemoved
    const length = found ? value.length : 0

    if (changed) {
      this._changes.push({ key, value: { isIndexer: false, isRemoved: true, length } })
    }

    if (wasTracked) this.members--

    return isIndexer
  }

  async linkable(key, length) {
    const len = this._seenLength(key)
    if (len > 0) return length > len

    const info = await this._get(key, 0)
    const prevLength = info ? info.length : 0

    return length > prevLength
  }

  async has(key, opts) {
    // could be optimised...
    return (await this.get(key, opts)) !== null
  }

  async _get(key, timeout) {
    let value = null
    let found = false

    for (let i = this._changes.length - 1; i >= 0; i--) {
      const c = this._changes[i]
      if (b4a.equals(key, c.key)) {
        value = c.value
        found = true
        break
      }
    }

    if (!found) {
      const node = await this.db.get(key, { timeout, valueEncoding: Member, keyEncoding: MEMBERS })
      if (node) {
        value = node.value
        found = true
      }
    }

    return found ? value : null
  }

  async get(key, opts = {}) {
    if (this._empty) return null

    let value = await this._get(key, opts.timeout || 0)

    if (opts.unflushed) {
      const hex = b4a.toString(key, 'hex')

      for (let i = this._changes.length - 1; i >= 0; i--) {
        const c = this._changes[i]
        if (b4a.equals(c.key, key)) value = c.value
      }

      if (this._clockUpdates.has(hex)) value.length = this._clockUpdates.get(hex)
    }

    return opts.onlyActive !== false || !value.isRemoved ? value : null
  }

  async hasLocal(key) {
    if (this._empty) return false
    try {
      const node = await this.db.get(key, {
        valueEncoding: Member,
        keyEncoding: MEMBERS,
        update: false,
        wait: false
      })
      return node !== null
    } catch {
      return false
    }
  }

  async getLocalLength(key) {
    if (this._empty) return 0
    try {
      const node = await this.db.get(key, {
        valueEncoding: Member,
        keyEncoding: MEMBERS,
        update: false,
        wait: false
      })
      return node === null ? 0 : node.value.length
    } catch {
      return 0
    }
  }

  list() {
    // note, NOT safe to use during apply atm
    return this.db.createReadStream({
      valueEncoding: Member,
      keyEncoding: MEMBERS
    })
  }

  async isIndexed(key, length) {
    const co = this.db.checkout(this.core.indexedLength)
    try {
      const node = await co.get(key, { valueEncoding: Member, keyEncoding: MEMBERS })
      return node !== null && node.value.length >= length
    } finally {
      await co.close()
    }
  }

  async fork(indexers, manifests, encryptionLength, views) {
    this.indexers = []
    this.pendingIndexers = []
    this.views = views

    if (this.version < 2) this.version = 2 // bump to enable entropy

    for (const { key } of indexers) {
      // todo: probably need to check isRemoved etc
      const { length } = await this.get(key)
      this.indexers.push({ key, length })
    }

    this._refreshEntropy(this.core.length)

    const blocks = []

    // truncate needs to respect hypercore batch
    let truncate = this.core.length - 1
    for await (const data of this.db.createHistoryStream({ lt: truncate, reverse: true })) {
      if (b4a.equals(data.key, INFO_KEY)) {
        truncate = data.seq + 1
        break
      }

      blocks.push(data)
    }

    await this.core.truncate(truncate, this.core.fork)

    const batch = this.db.batch({ update: false })
    await batch.ready()

    for (const { key, value } of blocks) {
      await batch.put(key, value)
    }

    const info = {
      version: this.version,
      members: this.members,
      pendingIndexers: this.pendingIndexers,
      indexers: this.indexers,
      heads: this.heads,
      views: this.views,
      encryptionLength,
      entropy: this.entropy
    }

    await batch.put('info', info, { valueEncoding: Info, keyEncoding: DIGEST })
    await batch.flush()

    await this._reset(await this.db.get('info', { valueEncoding: Info, keyEncoding: DIGEST }))

    return truncate
  }
}

function hasDependency(node, dep) {
  for (const h of node.actualHeads) {
    if (sameNode(h, dep)) return true
  }
  return false
}

function sameNode(a, b) {
  return b4a.equals(a.key, b.key) && a.length === b.length
}

function sameIndexers(a, b) {
  if (a.views.length > 0 && b.views.length > 0) return b4a.equals(a.views[0].key, b.views[0].key)
  if (a.indexers.length !== b.indexers.length) return false

  for (let i = 0; i < a.indexers.length; i++) {
    if (!b4a.equals(a.indexers[i].key, b.indexers[i].key)) return false
  }

  return true
}

function cloneNodes(arr) {
  const c = []
  for (let i = 0; i < arr.length; i++) {
    c.push({ key: arr[i].key, length: arr[i].length })
  }
  return c
}

function generateEntropy(indexers, length, entropy) {
  const buffer = b4a.alloc(8 + 32 + indexers.length * 32)
  const state = { start: 0, end: buffer.byteLength, buffer }

  c.uint64.encode(state, length)
  c.fixed32.encode(state, entropy || GENESIS_ENTROPY)
  for (const { key } of indexers) c.fixed32.encode(state, key)

  return crypto.hash([NS_ENTROPY, buffer])
}
const safetyCatch = require('safety-catch')

const MAX_WAIT = 2 * 60 * 1000
const DEFAULT_INTERVAL = 10 * 1000

module.exports = class Timer {
  constructor(handler, interval, opts = {}) {
    this.handler = handler || noop
    this.interval = interval || DEFAULT_INTERVAL
    this.limit = opts.limit || MAX_WAIT

    this._executing = null

    this._limit = random2over1(this.limit)
    this._timer = null
    this._resolve = null
    this._start = 0
    this._stopped = false
    this._asap = false
    this._standalone = new Set()

    this._unref = opts.unref !== false
    this._timerCallback = this._executeBackground.bind(this)
  }

  _executeBackground() {
    this._executing = this._execute()
    this._executing.catch(safetyCatch) // make sure it doesnt crash in the bg
  }

  async _execute() {
    this._asap = false
    await this.handler()
    this._start = 0
    this._executing = null
    this.bump()
  }

  bump() {
    if (this._stopped || this._executing || this._asap) return

    if (!this._start) this._start = Date.now()
    else if (Date.now() - this._start > this._limit) return

    const interval = random2over1(this.interval)

    clearTimeout(this._timer)
    this._timer = setTimeout(this._timerCallback, interval)
    if (this._unref && this._timer.unref) this._timer.unref()
  }

  async trigger() {
    if (this._stopped) return
    if (this._executing) await this._executing
    if (this._stopped) return

    clearTimeout(this._timer)
    this._timer = null

    this._executeBackground()
    await this._executing
  }

  async flush() {
    if (this._executing) await this._executing
  }

  // business-as-usual
  bau() {
    if (!this._asap) return
    this._asap = false
    this.bump()
  }

  asap() {
    if (this._asap) return
    this._asap = true

    const interval = Math.floor((Math.random() * this.interval) / 3)
    clearTimeout(this._timer)
    this._timer = setTimeout(this._timerCallback, interval)
    if (this._unref && this._timer.unref) this._timer.unref()
  }

  stop() {
    if (this._timer) clearTimeout(this._timer)
    this._timer = null
    this._start = 0
    this._asap = false
    this._stopped = true

    for (const { timer, resolve } of this._standalone) {
      clearTimeout(timer)
      resolve()
    }

    this._standalone.clear()
  }

  asapStandalone() {
    const interval = Math.floor((Math.random() * this.interval) / 3)
    return new Promise((resolve) => {
      const ref = { timer: null, resolve }
      ref.timer = setTimeout(resolveStandalone, interval, ref, this._standalone)
      if (ref.timer.unref) ref.timer.unref()
      this._standalone.add(ref)
    })
  }

  unref() {
    if (this._timer && this._timer.unref) this._timer.unref()
  }
}

function resolveStandalone(ref, set) {
  set.delete(ref)
  ref.resolve()
}

// random value x between n <= x < 2n
function random2over1(n) {
  return Math.floor(n + Math.random() * n)
}

function noop() {}
const b4a = require('b4a')
const assert = require('nanoassert')

module.exports = class TopoList {
  constructor() {
    this.tip = []
    this.undo = 0
    this.shared = 0
  }

  static compare(a, b) {
    return cmp(a, b)
  }

  static add(node, indexed, offset) {
    addSorted(node, indexed, offset)
  }

  mark() {
    this.shared = this.tip.length
    this.undo = 0
  }

  // todo: bump to new api that just tracks undo
  flush(indexed = []) {
    if (indexed.length) this._applyIndexed(indexed)

    const u = {
      shared: this.shared,
      undo: this.undo,
      length: indexed.length + this.tip.length,
      indexed,
      tip: this.tip
    }

    this.mark()

    return u
  }

  print() {
    return this.tip.map((n) => n.writer.core.key.toString() + n.length)
  }

  _applyIndexed(nodes) {
    assert(nodes.length <= this.tip.length, 'Indexed batch cannot exceed tip')

    let shared = 0

    for (; shared < nodes.length; shared++) {
      if (this.tip[shared] !== nodes[shared]) break
    }

    // reordering
    if (shared < nodes.length) this._track(shared)

    const tip = []

    for (let i = shared; i < this.tip.length; i++) {
      const node = this.tip[i]
      if (node.yielded) continue
      const s = addSorted(node, tip, 0)
      if (s === tip.length - 1) continue
      this._track(shared + s)
    }

    this.tip = tip
  }

  add(node) {
    const shared = addSorted(node, this.tip, 0)
    this._track(shared)
  }

  _track(shared) {
    if (shared < this.shared) {
      this.undo += this.shared - shared
      this.shared = shared
    }
  }
}

function hasOptimisticDeps(node) {
  for (const d of node.dependencies) {
    if (d.optimistic) return true
  }
  return false
}

// this can be optimised to only return optimistic nodes that we will "touch" when moving down the node
function getOptimisticDeps(node, list) {
  const deps = new Set()
  const stack = [node]

  while (stack.length > 0) {
    const next = stack.pop()
    if (deps.has(next)) continue
    if (next.optimistic && next !== node) deps.add(next)
    for (const d of next.dependencies) {
      if (d.optimistic) stack.push(d)
    }
  }

  const result = []

  for (let i = list.length - 1; deps.size !== result.length && i >= 0; i--) {
    const n = list[i]
    if (deps.has(n)) result.push(n)
  }

  return result.reverse()
}

function addSortedOptimistic(node, list, offset) {
  const opt = getOptimisticDeps(node, list)
  const pos = new Uint32Array(opt.length)

  for (let i = 0; i < opt.length; i++) {
    const n = opt[i]
    pos[i] = n.index
    moveDown(n, list, offset)
  }

  moveDownAndUp(node, list, offset)

  for (let i = opt.length - 1; i >= 0; i--) {
    moveOptimisticUp(opt[i], list, offset)
  }

  let shared = node.index

  for (let i = 0; i < opt.length; i++) {
    const idx = pos[i]
    const n = opt[i]

    if (idx === n.index) continue

    if (idx < shared) shared = idx
    if (n.index < shared) shared = n.index
  }

  return shared
}

function addSorted(node, list, offset) {
  list.push(node)
  node.index = list.length - 1

  // "slow" path, 1% of nodes
  if (hasOptimisticDeps(node)) return addSortedOptimistic(node, list, offset)

  moveDownAndUp(node, list, offset)
  return node.index
}

function moveDown(node, list, offset) {
  while (node.index > offset) {
    const prev = list[node.index - 1]
    if (links(node, prev)) break
    list[(prev.index = node.index)] = prev
    list[--node.index] = node
  }
}

function moveOptimisticUp(node, list, offset) {
  // if optimistic move all the way up
  while (node.index < list.length - 1) {
    const next = list[node.index + 1]
    if (links(next, node)) break
    list[(next.index = node.index)] = next
    list[++node.index] = node
  }

  // stable sort in case multiple children
  while (node.index > offset) {
    const prev = list[node.index - 1]
    if (!prev.optimistic) break
    const c = cmp(prev, node)
    if (c <= 0) break
    list[(prev.index = node.index)] = prev
    list[--node.index] = node
  }
}

function moveNonOptimisticUp(node, list, offset) {
  // stable sort against next non optimistic node
  while (node.index < list.length - 1) {
    const next = list[node.index + 1]
    const c = cmpNonOptimistic(node, next, list)
    if (c <= 0) break
    list[(next.index = node.index)] = next
    list[++node.index] = node
  }
}

function moveDownAndUp(node, list, offset) {
  moveDown(node, list, offset)

  if (node.optimistic) moveOptimisticUp(node, list, offset)
  else moveNonOptimisticUp(node, list, offset)
}

function links(a, b) {
  if (b.dependents.has(a)) return true
  return a.length > 0 && b.length === a.length - 1 && a.writer === b.writer
}

function cmpNonOptimistic(a, b, list) {
  if (!b.optimistic) return cmp(a, b)

  for (let i = b.index + 1; i < list.length; i++) {
    const node = list[i]
    if (!node.optimistic) return cmp(a, node)
  }

  return -1
}

function cmp(a, b) {
  return links(b, a) ? -1 : cmpUnlinked(a, b)
}

function cmpUnlinked(a, b) {
  const c = b4a.compare(a.writer.core.key, b.writer.core.key)
  return c === 0 ? (a.length < b.length ? -1 : 1) : c
}
module.exports = class UpdateChanges {
  constructor(base) {
    this.base = base
    this.byName = new Map()
    this.tracking = null
  }

  get discoveryKey() {
    return this.base.discoveryKey
  }

  get key() {
    return this.base.key
  }

  get id() {
    return this.base.id
  }

  get system() {
    return this.base.system
  }

  track(state) {
    this.tracking = []
    this.byName.clear()

    if (!state) return

    for (const v of state.views) {
      if (v.ref) this._add(v.ref)
    }

    this._add(state.systemView.ref)
    this._add(state.encryptionView.ref)
  }

  _add(ref) {
    const core = ref.atomicBatch || ref.batch
    const from = core.length
    const inf = { ref, from }
    ref.shared = from
    this.tracking.push(inf)
  }

  finalise() {
    if (this.tracking === null) return

    for (const { ref, from } of this.tracking) {
      const core = ref.atomicBatch || ref.batch
      this.byName.set(ref.name, {
        from,
        to: core.length,
        shared: ref.shared
      })
    }

    this.tracking = null
  }

  get(name) {
    return this.byName.get(name)
  }
}
const crypto = require('hypercore-crypto')
const c = require('compact-encoding')
const b4a = require('b4a')

const { OPLOG_VERSION } = require('./caps.js')
const { OplogMessage } = require('./messages.js')
const { EncryptionView } = require('./encryption.js')

module.exports = {
  encodeValue,
  decodeValue
}

function encodeValue(value, opts = {}) {
  const state = { start: 0, end: 0, buffer: null }

  const message = {
    version: opts.version || OPLOG_VERSION,
    digest: null,
    checkpoint: null,
    optimistic: !!opts.optimistic,
    node: {
      heads: opts.heads || [],
      batch: 1,
      value
    }
  }

  OplogMessage.preencode(state, message)

  if (opts.padding) {
    state.start = opts.padding
    state.end += opts.padding
  }

  state.buffer = b4a.alloc(state.end)

  OplogMessage.encode(state, message)

  if (!opts.encrypted) return state.buffer

  if (!opts.optimistic) {
    throw new Error('Encoding an encrypted value is not supported')
  }

  const padding = b4a.alloc(16) // min hash length is 16
  crypto.hash(state.buffer, padding)
  padding[0] = 0

  return b4a.concat([padding.subarray(0, 8), state.buffer])
}

async function decodeValue(value, { autobase, encryptionKey, key, manifest, index = 0 } = {}) {
  if (encryptionKey) {
    const e = new EncryptionView({ encryptionKey, bootstrap: autobase })
    const w = e.getWriterEncryption()

    await w.decrypt(index, value, { key, manifest })
    value = value.subarray(8)
  }

  const op = c.decode(OplogMessage, value)
  return op.node.value
}
const b4a = require('b4a')
const c = require('compact-encoding')
const safetyCatch = require('safety-catch')
const ReadyResource = require('ready-resource')

const WakeupEntry = {
  preencode(state, m) {
    c.fixed32.preencode(state, m.key)
    c.uint.preencode(state, m.length)
  },
  encode(state, m) {
    c.fixed32.encode(state, m.key)
    c.uint.encode(state, m.length)
  },
  decode(state) {
    return {
      key: c.fixed32.decode(state),
      length: c.uint.decode(state)
    }
  }
}

module.exports = class AutoWakeup extends ReadyResource {
  constructor(base) {
    super()

    this.base = base
    this.flushing = null

    this._rootStore = this.base.store
    this._addBound = this.add.bind(this)
    this._preupdateBound = this._preupdate.bind(this)
    this._needsFlush = false
    this._map = new Map()
  }

  [Symbol.iterator]() {
    return this._map.values()
  }

  async _preupdate(batch, key) {
    this.queue(key, batch.length)
    await this.flush()
    this.base._onwakeup()
  }

  async _save() {
    const slab = b4a.allocUnsafe(8 + this._map.size * 40) // 32 + 8
    const state = { start: 0, end: 0, buffer: slab }

    c.uint.encode(state, this._map.size)
    for (const m of this._map.values()) WakeupEntry.encode(state, m)

    await this.base.local.setUserData('autobase/wakeup', slab.subarray(0, state.start))
  }

  async _load() {
    const buffer = await this.base.local.getUserData('autobase/wakeup')
    if (!buffer) return

    const state = { start: 0, end: buffer.byteLength, buffer }

    let len = c.uint.decode(state)
    while (len-- > 0) {
      const m = WakeupEntry.decode(state)
      this._map.set(b4a.toString(m.key, 'hex'), m)
    }
  }

  async _open() {
    await this._load()

    this._rootStore.watch(this._addBound)

    for (const core of this._rootStore.cores) {
      if (core.opened === false) await core.ready().catch(noop)
      if (!core.closing) this.add(core)
    }
  }

  async _close() {
    this._rootStore.unwatch(this._addBound)

    for (const core of this._rootStore.cores) {
      if (core.opened && !core.closing) this.remove(core)
    }

    this._map.clear()

    while (this.flushing) {
      try {
        await this.flushing
      } catch {}
    }
  }

  queue(key, length) {
    const hex = b4a.toString(key, 'hex')
    const m = this._map.get(hex)

    if (m && m.length > length) {
      return false
    }

    this._needsFlush = true
    this._map.set(hex, { key, length })

    return true
  }

  unqueue(key, length) {
    const hex = b4a.toString(key, 'hex')
    const m = this._map.get(hex)

    if (!m) return true
    if (m.length > length) return false

    this._needsFlush = true
    this._map.delete(hex)

    return true
  }

  async flush() {
    if (this.closing) throw new Error('Closing')

    // wait for someone
    if (this.flushing) await this.flushing

    // if another still active they flushed us
    if (this.flushing) return this.flushing

    if (this._needsFlush === false) return
    this._needsFlush = false

    try {
      this.flushing = this._save()
      return await this.flushing
    } finally {
      this.flushing = null
    }
  }

  add(core) {
    return this._add(core).catch(safetyCatch)
  }

  remove(core) {
    return this._remove(core)
  }

  async _add(core) {
    if (core.opened === false) await core.ready()
    if (core.closing) return false

    // local writer, no need
    if (core === this.base.local.core) return false

    const rx = core.storage.read()

    const referrerPromise = rx.getUserData('referrer')
    const viewPromise = rx.getUserData('autobase/view')

    rx.tryFlush()

    const [referrer, view] = await Promise.all([referrerPromise, viewPromise])
    if (view) return false

    if (referrer === null || !b4a.equals(referrer, this.base.key)) return false

    core.preupdate = this._preupdateBound

    return true
  }

  _remove(core) {
    if (core.preupdate !== this._preupdateBound) return false
    core.preupdate = null
    return true
  }
}

function noop() {}
const c = require('compact-encoding')
const b4a = require('b4a')
const ReadyResource = require('ready-resource')
const assert = require('nanoassert')
const SignalPromise = require('signal-promise')

const Linearizer = require('./linearizer.js')
const NodeBuffer = require('./node-buffer.js')

const MAX_PRELOAD = 4
const MAX_PREFETCH = 256

module.exports = class Writer extends ReadyResource {
  constructor(base, core, length, isRemoved) {
    super()

    this.base = base
    this.core = core
    this.isRemoved = isRemoved
    this.updated = false
    this.range = null
    this.nodes = new NodeBuffer(length)
    this.node = null
    this.isActive = false
    this.isCurrentlyCoupled = false
    this.isCoupled = false // maintained by updateBootstrapWriters
    this.isBootstrap = false // maintained by updateBootstrapWriters
    this.isActiveIndexer = false
    this.available = length
    this.length = length
    this.seenLength = 0
    this.recover = false
    this.frozen = false

    this.syncSignal = null
  }

  _pause() {
    if (!this.range) return
    this.range.destroy()
    this.range = null
  }

  _resume() {
    if (this.range) {
      // if we didnt fill up the preload buffer yet, do not commit to more work
      if (this.range.range.end === this.nodes.length + MAX_PREFETCH) return
      this.range.destroy()
    }
    this.range = this.core.download({
      start: this.nodes.length,
      end: this.nodes.length + MAX_PREFETCH,
      linear: true
    })
  }

  _updateCoupling() {
    if (!this.base._coupler || this.isCoupled === this.isCurrentlyCoupled) return

    if (this.isCurrentlyCoupled) this.base._coupler.remove(this.core)
    else this.base._coupler.add(this.core)

    this.isCurrentlyCoupled = this.isCoupled
  }

  _removeCouple() {
    if (this.base._coupler && !this.isCoupled && this.isCurrentlyCoupled) {
      this.isCurrentlyCoupled = false
      this.base._coupler.remove(this.core)
    }
  }

  updateActivity() {
    if (!this.core.opened) return

    if (this.seenLength > this.core.length || this.length < this.core.length || this.isBootstrap) {
      // if we have seen a later core, or if we are behind, or if bootstrap
      this.isActive = true
      this.core.setActive(true)
    } else if (this.length === this.core.length) {
      // things look steady
      this.isActive = false
      this.core.setActive(false)
    }

    this._updateCoupling()

    if (this.core.writable) return

    if (this.base.isFastForwarding() || !this.isActive) {
      this._pause()
    } else {
      this._resume()
    }
  }

  setBootstrap(bool) {
    this.isBootstrap = bool
    this.updateActivity()
  }

  seen(length) {
    if (length > this.seenLength) this.seenLength = length
    this.updateActivity()
  }

  waitForSynced() {
    if (this.core.length === this.length) return Promise.resolve()
    if (this.syncSignal === null) this.syncSignal = new SignalPromise()
    return this.syncSignal.wait()
  }

  async _open() {
    await this.core.ready()
    await this.core.setUserData('referrer', this.base.key)

    // base might be closing here
    if (this.base.closing) return

    // remove later
    this.recover = autoRecover(this.core)

    // add it again incase it wasn't readied before, only needed if this is the first time we set the referrer...
    await this.base._wakeup.add(this.core.core)

    this.updateActivity()

    if (this.core.length > this.length) this.base._queueBump()

    this.base.emit('writer', this)
  }

  _close() {
    if (this.syncSignal !== null) this.syncSignal.notify()
    return this.core.close()
  }

  get indexed() {
    return this.nodes.offset
  }

  idle() {
    return this.length === this.available && this.length === this.core.length && this.core.opened
  }

  flushed() {
    // TODO: prop a cleaner way to express this...
    return (
      this.seenLength <= this.length &&
      this.length === this.available &&
      this.length === this.core.length &&
      this.shiftable() === false &&
      !this.core.core.upgrading &&
      this.core.opened
    )
  }

  compare(writer) {
    return b4a.compare(this.core.key, writer.core.key)
  }

  head() {
    return this.nodes.get(this.length - 1)
  }

  advance() {
    if (this.syncSignal !== null && this.length + 1 === this.core.length) this.syncSignal.notify()
    return this.length < this.available ? this.nodes.get(this.length++) : null
  }

  shiftable() {
    return this.length > this.nodes.offset
  }

  shift() {
    if (this.shiftable() === false) return false

    let node = this._shiftAndClear()
    while (node.batch > 1) node = this._shiftAndClear()

    return true
  }

  get(seq) {
    return seq < this.length ? this.nodes.get(seq) : null
  }

  append(value, heads, batch, dependencies, optimistic) {
    const node = Linearizer.createNode(
      this,
      this.nodes.length + 1,
      value,
      heads,
      batch,
      dependencies,
      optimistic
    )

    node.actualHeads = node.heads.slice(0)

    this.nodes.push(node)
    this.available++
    this.length++

    return node
  }

  async update(boot) {
    if (this.opened === false) await this.ready()
    if (this.frozen) return false

    // if this is a boot node, DO NOT, preload as that will make it load
    // and reject nodes based on the tmp state of the system.
    // prop needs a better solution but this works for now
    const preload = boot ? 1 : MAX_PRELOAD

    while (this.available - this.length < preload) {
      // quick sanity check
      if (this.nodes.length === this.core.length || this.core.length === 0) break

      // load next node
      if (this.node === null && !(await this._loadNextNode())) break
      if (!(await this._ensureNodeDependencies(boot))) break

      if (this.recover) this.node.value = null

      this.nodes.push(this.node)
      if (this.node.batch === 1) this.available = this.nodes.length
      this.node = null
    }

    this.updateActivity()

    return this.length < this.available
  }

  _shiftAndClear() {
    const node = this.nodes.shift()
    node.clear()
    return node
  }

  async _loadNextNode() {
    const seq = this.nodes.length

    if (!(await this.core.has(seq))) return false

    try {
      const { node, optimistic, trace } = await this.core.get(seq, { wait: false })

      const value = node.value == null ? null : c.decode(this.base.valueEncoding, node.value)
      this.node = Linearizer.createNode(
        this,
        seq + 1,
        value,
        node.heads,
        node.batch,
        new Set(),
        optimistic,
        trace
      )
      return true
    } catch (err) {
      this.frozen = true
      throw err
    }
  }

  async _ensureNodeDependencies(boot) {
    while (this.node.dependencies.size < this.node.heads.length) {
      const rawHead = this.node.heads[this.node.dependencies.size]

      const headWriter = await this.base._getWriterByKey(
        rawHead.key,
        -1,
        rawHead.length,
        true,
        false,
        boot
      )

      if (headWriter !== this && (headWriter === null || headWriter.length < rawHead.length)) {
        if (!boot) this.base._ensureWakeup(headWriter)
        return false
      }

      let headNode = headWriter.nodes.get(rawHead.length - 1)

      // could be a stub node
      if (!headNode) {
        for (const node of this.base.linearizer.heads) {
          if (!compareHead(node, rawHead)) continue
          headNode = node
          break
        }
      }

      // TODO: generalise DAG validation and freeze the writer
      assert(!this.node.dependencies.has(headNode), 'Corrupted DAG')

      // TODO: better way to solve the stub check is to never mutate heads below
      if (headNode === null) {
        // already yielded
        this.node.heads.splice(this.node.dependencies.size, 1)
        continue
      }

      this.node.dependencies.add(headNode)
    }

    // always link previous node if it's not indexed
    const offset = this.node.length - 1
    if (offset > this.indexed) {
      this.node.dependencies.add(this.nodes.get(offset - 1))
    }

    return true
  }
}

function compareHead(node, head) {
  if (node.length !== head.length) return false
  return b4a.equals(node.writer.core.key, head.key)
}

// this is a list of peers we bugged in the btc and planb room.
// adding them here so migration can run, can be removed in a month or so from time of commit
// note, no security implications of this, we just null them out.

function autoRecover(core) {
  assert(core.opened)

  switch (core.id) {
    case 'ghrpexaboutdm46ombqho7mroxknassnntrxx3cubfux4qi6w6hy':
    case 'qoaanao71s4he1rcd197d336qepykk4467geo1uq8cwnzmpb786o':
    case 'fomhdxgn4j4tzjqy6y7iskhffimzokt7kraddyd8orcht3r8q61o':
    case 'd8f5taxxrit51apftoi38e5b86hb98cgfd7dfp3uo1uoh95qt49o':
    case 'objyf75uggsqpjcut69xdgj46ks8r71jjrq7oxdfsz95sstchkno':
      return true
  }

  return false
}
{
  "name": "autobase",
  "version": "7.28.1",
  "description": "A multiwriter data structure for Hypercore",
  "main": "index.js",
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test/all.js",
    "test:encrypted": "prettier . --check && brittle test/all.js --encrypt-all",
    "test:fixtures": "prettier . --check && brittle test/fixtures/tests/*.js",
    "test:bare": "bare test/all.js",
    "fuzz:generated": "brittle test/reference/fuzz/generated/*.js",
    "fuzz:main": "node test/fuzz/index.js",
    "fuzz": "node test/reference/fuzz/fuzz.js",
    "generate-fixtures": "node test/fixtures/generate/all.js"
  },
  "files": [
    "index.js",
    "lib/**",
    "encoding/**"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/autobase.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/autobase/issues"
  },
  "homepage": "https://github.com/holepunchto/autobase#readme",
  "dependencies": {
    "b4a": "^1.6.1",
    "bare-events": "^2.2.0",
    "compact-encoding": "^3.0.0",
    "core-coupler": "^2.0.0",
    "debounceify": "^1.0.0",
    "encryption-encoding": "^1.0.3",
    "hyperbee": "^2.22.0",
    "hypercore": "^11.27.12",
    "hypercore-crypto": "^3.4.0",
    "hypercore-id-encoding": "^1.2.0",
    "hyperschema": "^1.12.1",
    "index-encoder": "^3.3.2",
    "nanoassert": "^2.0.0",
    "protomux-wakeup": "^2.0.0",
    "ready-resource": "^1.0.0",
    "resolve-reject-promise": "^1.1.0",
    "safety-catch": "^1.0.2",
    "scope-lock": "^1.2.4",
    "signal-promise": "^1.0.3",
    "sodium-universal": "^5.0.1",
    "sub-encoder": "^2.1.1",
    "tiny-buffer-map": "^1.1.1"
  },
  "devDependencies": {
    "autobase-test-helpers": "^3.0.0",
    "blind-encryption-sodium": "^2.0.0",
    "brittle": "^3.1.1",
    "corestore": "^7.9.1",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "rache": "^1.0.0",
    "same-data": "^1.0.0",
    "task-backoff": "^1.0.0",
    "test-tmp": "^1.2.0",
    "uncaughts": "^1.1.0"
  },
  "standard": {
    "ignore": [
      "**/test/fuzz/generated/**",
      "**/test/reference/**",
      "example.mjs"
    ]
  }
}
function isBuffer(value) {
  return Buffer.isBuffer(value) || value instanceof Uint8Array
}

function isEncoding(encoding) {
  return Buffer.isEncoding(encoding)
}

function alloc(size, fill, encoding) {
  return Buffer.alloc(size, fill, encoding)
}

function allocUnsafe(size) {
  return Buffer.allocUnsafe(size)
}

function allocUnsafeSlow(size) {
  return Buffer.allocUnsafeSlow(size)
}

function byteLength(string, encoding) {
  return Buffer.byteLength(string, encoding)
}

function compare(a, b) {
  return Buffer.compare(a, b)
}

function concat(buffers, totalLength) {
  return Buffer.concat(buffers, totalLength)
}

function copy(source, target, targetStart, start, end) {
  return toBuffer(source).copy(target, targetStart, start, end)
}

function equals(a, b) {
  return toBuffer(a).equals(b)
}

function fill(buffer, value, offset, end, encoding) {
  return toBuffer(buffer).fill(value, offset, end, encoding)
}

function from(value, encodingOrOffset, length) {
  return Buffer.from(value, encodingOrOffset, length)
}

function includes(buffer, value, byteOffset, encoding) {
  return toBuffer(buffer).includes(value, byteOffset, encoding)
}

function indexOf(buffer, value, byfeOffset, encoding) {
  return toBuffer(buffer).indexOf(value, byfeOffset, encoding)
}

function lastIndexOf(buffer, value, byteOffset, encoding) {
  return toBuffer(buffer).lastIndexOf(value, byteOffset, encoding)
}

function swap16(buffer) {
  return toBuffer(buffer).swap16()
}

function swap32(buffer) {
  return toBuffer(buffer).swap32()
}

function swap64(buffer) {
  return toBuffer(buffer).swap64()
}

function toBuffer(buffer) {
  if (Buffer.isBuffer(buffer)) return buffer
  return Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

function toString(buffer, encoding, start, end) {
  return toBuffer(buffer).toString(encoding, start, end)
}

function write(buffer, string, offset, length, encoding) {
  return toBuffer(buffer).write(string, offset, length, encoding)
}

function readDoubleBE(buffer, offset) {
  return toBuffer(buffer).readDoubleBE(offset)
}

function readDoubleLE(buffer, offset) {
  return toBuffer(buffer).readDoubleLE(offset)
}

function readFloatBE(buffer, offset) {
  return toBuffer(buffer).readFloatBE(offset)
}

function readFloatLE(buffer, offset) {
  return toBuffer(buffer).readFloatLE(offset)
}

function readInt32BE(buffer, offset) {
  return toBuffer(buffer).readInt32BE(offset)
}

function readInt32LE(buffer, offset) {
  return toBuffer(buffer).readInt32LE(offset)
}

function readUInt32BE(buffer, offset) {
  return toBuffer(buffer).readUInt32BE(offset)
}

function readUInt32LE(buffer, offset) {
  return toBuffer(buffer).readUInt32LE(offset)
}

function writeDoubleBE(buffer, value, offset) {
  return toBuffer(buffer).writeDoubleBE(value, offset)
}

function writeDoubleLE(buffer, value, offset) {
  return toBuffer(buffer).writeDoubleLE(value, offset)
}

function writeFloatBE(buffer, value, offset) {
  return toBuffer(buffer).writeFloatBE(value, offset)
}

function writeFloatLE(buffer, value, offset) {
  return toBuffer(buffer).writeFloatLE(value, offset)
}

function writeInt32BE(buffer, value, offset) {
  return toBuffer(buffer).writeInt32BE(value, offset)
}

function writeInt32LE(buffer, value, offset) {
  return toBuffer(buffer).writeInt32LE(value, offset)
}

function writeUInt32BE(buffer, value, offset) {
  return toBuffer(buffer).writeUInt32BE(value, offset)
}

function writeUInt32LE(buffer, value, offset) {
  return toBuffer(buffer).writeUInt32LE(value, offset)
}

module.exports = {
  isBuffer,
  isEncoding,
  alloc,
  allocUnsafe,
  allocUnsafeSlow,
  byteLength,
  compare,
  concat,
  copy,
  equals,
  fill,
  from,
  includes,
  indexOf,
  lastIndexOf,
  swap16,
  swap32,
  swap64,
  toBuffer,
  toString,
  write,
  readDoubleBE,
  readDoubleLE,
  readFloatBE,
  readFloatLE,
  readInt32BE,
  readInt32LE,
  readUInt32BE,
  readUInt32LE,
  writeDoubleBE,
  writeDoubleLE,
  writeFloatBE,
  writeFloatLE,
  writeInt32BE,
  writeInt32LE,
  writeUInt32BE,
  writeUInt32LE
}
{
  "name": "b4a",
  "version": "1.8.1",
  "description": "Bridging the gap between buffers and typed arrays",
  "exports": {
    "./package": "./package.json",
    ".": {
      "react-native": "./react-native.js",
      "browser": "./browser.js",
      "default": "./index.js"
    }
  },
  "files": [
    "browser.js",
    "index.js",
    "react-native.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:bare && npm run test:node",
    "test:bare": "brittle-bare --coverage test.mjs",
    "test:node": "brittle-node --coverage test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/b4a.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/b4a/issues"
  },
  "homepage": "https://github.com/holepunchto/b4a#readme",
  "devDependencies": {
    "brittle": "^3.5.2",
    "lunte": "^1.7.0",
    "nanobench": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "react-native-b4a": "*"
  },
  "peerDependenciesMeta": {
    "react-native-b4a": {
      "optional": true
    }
  }
}
module.exports = require.addon()
const binding = require('./binding')

module.exports = binding.abort
{
  "name": "bare-abort",
  "version": "2.0.13",
  "description": "Cause abnormal program termination and generate a crash report",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-abort.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-abort/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-abort#readme",
  "devDependencies": {
    "cmake-bare": "^1.1.7",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  }
}
const ESC = '\x1b'
const CSI = ESC + '['
const SGR = (n) => CSI + n + 'm'

exports.constants = {
  ESC,
  CSI,
  SGR
}

// https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_(Control_Sequence_Introducer)_sequences

exports.cursorHide = CSI + '?25l'
exports.cursorShow = CSI + '?25h'

exports.cursorUp = function cursorUp(n = 1) {
  return CSI + n + 'A'
}

exports.cursorDown = function cursorDown(n = 1) {
  return CSI + n + 'B'
}

exports.cursorForward = function cursorForward(n = 1) {
  return CSI + n + 'C'
}

exports.cursorBack = function cursorBack(n = 1) {
  return CSI + n + 'D'
}

exports.cursorNextLine = function cursorNextLine(n = 1) {
  return CSI + n + 'E'
}

exports.cursorPreviousLine = function cursorPreviousLine(n = 1) {
  return CSI + n + 'F'
}

exports.cursorPosition = function cursorPosition(column, row = 0) {
  if (row === 0) return CSI + (column + 1) + 'G'

  return CSI + (row + 1) + ';' + (column + 1) + 'H'
}

exports.eraseDisplayEnd = CSI + 'J'
exports.eraseDisplayStart = CSI + '1J'
exports.eraseDisplay = CSI + '2J'
exports.eraseLineEnd = CSI + 'K'
exports.eraseLineStart = CSI + '1K'
exports.eraseLine = CSI + '2K'

exports.scrollUp = function scrollUp(n = 1) {
  return CSI + n + 'S'
}

exports.scrollDown = function scrollDown(n = 1) {
  return CSI + n + 'T'
}

// https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_(Select_Graphic_Rendition)_parameters

exports.modifierReset = SGR(0)
exports.modifierBold = SGR(1)
exports.modifierDim = SGR(2)
exports.modifierItalic = SGR(3)
exports.modifierUnderline = SGR(4)
exports.modifierNormal = SGR(22)
exports.modifierNotItalic = SGR(23)
exports.modifierNotUnderline = SGR(24)

// https://en.wikipedia.org/wiki/ANSI_escape_code#Colors

exports.colorBlack = SGR(30)
exports.colorRed = SGR(31)
exports.colorGreen = SGR(32)
exports.colorYellow = SGR(33)
exports.colorBlue = SGR(34)
exports.colorMagenta = SGR(35)
exports.colorCyan = SGR(36)
exports.colorWhite = SGR(37)
exports.colorDefault = SGR(39)
exports.colorBrightBlack = SGR(90)
exports.colorBrightRed = SGR(91)
exports.colorBrightGreen = SGR(92)
exports.colorBrightYellow = SGR(93)
exports.colorBrightBlue = SGR(94)
exports.colorBrightMagenta = SGR(95)
exports.colorBrightCyan = SGR(96)
exports.colorBrightWhite = SGR(97)
{
  "name": "bare-ansi-escapes",
  "version": "2.2.3",
  "description": "Parse and produce ANSI escape sequences",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./key-decoder": {
      "types": "./key-decoder.d.ts",
      "default": "./key-decoder.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "key-decoder.js",
    "key-decoder.d.ts"
  ],
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-ansi-escapes.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-ansi-escapes/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-ansi-escapes#readme",
  "dependencies": {
    "bare-stream": "^2.6.5"
  },
  "devDependencies": {
    "bare-buffer": "^3.0.2",
    "brittle": "^3.3.2",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  },
  "peerDependencies": {
    "bare-buffer": "*"
  },
  "peerDependenciesMeta": {
    "bare-buffer": {
      "optional": true
    }
  }
}
const inspect = require('bare-inspect')

class AssertionError extends Error {
  constructor(opts = {}) {
    let { message = null, actual, expected, operator } = opts

    if (message === null) {
      message = `${inspect(actual)} ${operator} ${inspect(expected)}`
    }

    super(message)

    this.actual = actual
    this.expected = expected
    this.operator = operator
  }

  get name() {
    return 'AssertionError'
  }

  get code() {
    'ASSERTION'
  }
}

function assertFail(opts, fn) {
  if (opts.message instanceof Error) throw opts.message

  const err = new AssertionError(opts)

  if (Error.captureStackTrace) Error.captureStackTrace(err, fn)

  throw err
}

module.exports = exports = function assert(actual, message) {
  if (actual) return

  assertFail({ message, actual, expected: true, operator: '==' }, assert)
}

exports.AssertionError = AssertionError

exports.fail = function fail(message) {
  if (message === undefined) message = 'Failed'

  assertFail({ message, operator: 'fail' }, fail)
}

exports.ok = function ok(actual, message) {
  if (actual) return

  assertFail({ message, actual, expected: true, operator: '==' }, ok)
}

exports.notOk = function ok(actual, message) {
  if (!actual) return

  assertFail({ message, actual, expected: false, operator: '==' }, ok)
}

exports.equal = function equal(actual, expected, message) {
  if (actual == expected || (actual !== actual && expected !== expected)) {
    return
  }

  assertFail({ message, actual, expected, operator: '==' }, equal)
}

exports.notEqual = function notEqual(actual, expected, message) {
  if (actual != expected && (actual === actual || expected === expected)) {
    return
  }

  assertFail({ message, actual, expected, operator: '!=' }, notEqual)
}

exports.strictEqual = function strictEqual(actual, expected, message) {
  if (Object.is(actual, expected)) return

  assertFail(
    { message, actual, expected, operator: 'strictEqual' },
    strictEqual
  )
}

exports.notStrictEqual = function notStrictEqual(actual, expected, message) {
  if (!Object.is(actual, expected)) return

  assertFail(
    { message, actual, expected, operator: 'notStrictEqual' },
    notStrictEqual
  )
}
{
  "name": "bare-assert",
  "version": "1.2.0",
  "description": "Assertion library for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts"
  ],
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-assert.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-assert/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-assert#readme",
  "dependencies": {
    "bare-inspect": "^3.1.2"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  }
}
const os = require('bare-os')

module.exports = new Proxy(Object.create(null), {
  ownKeys (target) {
    return os.getEnvKeys()
  },

  get (target, property) {
    if (typeof property !== 'string') return

    return os.getEnv(property)
  },

  has (target, property) {
    if (typeof property !== 'string') return false

    return os.hasEnv(property)
  },

  set (target, property, value) {
    if (typeof property !== 'string') return

    const type = typeof value

    if (type !== 'string' && type !== 'number' && type !== 'boolean') {
      throw new Error('Environment variable must be of type string, number, or boolean')
    }

    value = String(value)

    os.setEnv(property, value)

    return true
  },

  deleteProperty (target, property) {
    if (typeof property !== 'string') return

    os.unsetEnv(property)
  },

  getOwnPropertyDescriptor (target, property) {
    return {
      value: this.get(target, property),
      enumerable: true,
      configurable: true,
      writable: true
    }
  }
})
{
  "name": "bare-env",
  "version": "3.0.0",
  "description": "Environment variable support for JavaScript",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "scripts": {
    "test": "standard && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-env.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-env/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-env#readme",
  "dependencies": {
    "bare-os": "^3.0.1"
  },
  "devDependencies": {
    "brittle": "^3.2.1",
    "standard": "^17.0.0"
  }
}
const errors = require('./lib/errors')

class EventListener {
  constructor() {
    this.list = []
    this.count = 0
  }

  append(ctx, name, fn, once) {
    this.count++
    ctx.emit('newListener', name, fn) // Emit BEFORE adding
    this.list.push([fn, once])
  }

  prepend(ctx, name, fn, once) {
    this.count++
    ctx.emit('newListener', name, fn) // Emit BEFORE adding
    this.list.unshift([fn, once])
  }

  remove(ctx, name, fn) {
    for (let i = 0, n = this.list.length; i < n; i++) {
      const l = this.list[i]

      if (l[0] === fn) {
        this.list.splice(i, 1)

        if (this.count === 1) delete ctx._events[name]

        ctx.emit('removeListener', name, fn) // Emit AFTER removing

        this.count--
        return
      }
    }
  }

  removeAll(ctx, name) {
    const list = [...this.list]
    this.list = []

    if (this.count === list.length) delete ctx._events[name]

    for (let i = list.length - 1; i >= 0; i--) {
      ctx.emit('removeListener', name, list[i][0]) // Emit AFTER removing
    }

    this.count -= list.length
  }

  emit(ctx, name, ...args) {
    const list = [...this.list]

    for (let i = 0, n = list.length; i < n; i++) {
      const l = list[i]

      if (l[1] === true) this.remove(ctx, name, l[0])

      Reflect.apply(l[0], ctx, args)
    }

    return list.length > 0
  }
}

function appendListener(ctx, name, fn, once) {
  if (ctx._events === undefined) ctx._events = Object.create(null)
  const e = ctx._events[name] || (ctx._events[name] = new EventListener())
  e.append(ctx, name, fn, once)
  return ctx
}

function prependListener(ctx, name, fn, once) {
  if (ctx._events === undefined) ctx._events = Object.create(null)
  const e = ctx._events[name] || (ctx._events[name] = new EventListener())
  e.prepend(ctx, name, fn, once)
  return ctx
}

function removeListener(ctx, name, fn) {
  if (ctx._events === undefined) return ctx
  const e = ctx._events[name]
  if (e !== undefined) e.remove(ctx, name, fn)
  return ctx
}

function throwUnhandledError(...args) {
  let err

  if (args.length > 0) err = args[0]

  if (err instanceof Error === false) err = errors.UNHANDLED_ERROR(err)

  if (Error.captureStackTrace) {
    Error.captureStackTrace(err, exports.prototype.emit)
  }

  queueMicrotask(() => {
    throw err
  })
}

module.exports = exports = class EventEmitter {
  constructor() {
    this._events = Object.create(null)
  }

  addListener(name, fn) {
    return appendListener(this, name, fn, false)
  }

  addOnceListener(name, fn) {
    return appendListener(this, name, fn, true)
  }

  prependListener(name, fn) {
    return prependListener(this, name, fn, false)
  }

  prependOnceListener(name, fn) {
    return prependListener(this, name, fn, true)
  }

  removeListener(name, fn) {
    return removeListener(this, name, fn)
  }

  on(name, fn) {
    return appendListener(this, name, fn, false)
  }

  once(name, fn) {
    return appendListener(this, name, fn, true)
  }

  off(name, fn) {
    return removeListener(this, name, fn)
  }

  emit(name, ...args) {
    if (name === 'error' && this._events !== undefined && this._events.error === undefined) {
      throwUnhandledError(...args)
    }

    if (this._events === undefined) return false
    const e = this._events[name]
    return e === undefined ? false : e.emit(this, name, ...args)
  }

  listeners(name) {
    if (this._events === undefined) return []
    const e = this._events[name]
    return e === undefined ? [] : [...e.list]
  }

  rawListeners(name) {
    if (this._events === undefined) return []
    const e = this._events[name]
    return e === undefined ? [] : e.list.map((l) => l[0])
  }

  eventNames() {
    if (this._events === undefined) return []
    return Reflect.ownKeys(this._events)
  }

  listenerCount(name) {
    if (this._events === undefined) return 0
    const e = this._events[name]
    return e === undefined ? 0 : e.list.length
  }

  getMaxListeners() {
    return EventEmitter.defaultMaxListeners
  }

  setMaxListeners(n) {}

  removeAllListeners(name) {
    if (arguments.length === 0) {
      for (const key of Reflect.ownKeys(this._events)) {
        if (key === 'removeListener') continue
        this.removeAllListeners(key)
      }
      this.removeAllListeners('removeListener')
    } else {
      const e = this._events[name]
      if (e !== undefined) e.removeAll(this, name)
    }
    return this
  }
}

exports.EventEmitter = exports

exports.errors = errors

exports.defaultMaxListeners = 10

exports.on = function on(emitter, name, opts = {}) {
  const { signal } = opts

  if (signal && signal.aborted) {
    throw errors.OPERATION_ABORTED(signal.reason)
  }

  let error = null
  let done = false

  const events = []
  const promises = []

  if (name !== 'error') emitter.on('error', onerror)

  if (signal) signal.addEventListener('abort', onabort)

  emitter.on(name, onevent)

  return {
    next() {
      if (events.length) {
        return Promise.resolve({ value: events.shift(), done: false })
      }

      if (error) {
        const err = error

        error = null

        return Promise.reject(err)
      }

      if (done) return onclose()

      return new Promise((resolve, reject) => promises.push({ resolve, reject }))
    },

    return() {
      return onclose()
    },

    throw(err) {
      return onerror(err)
    },

    [Symbol.asyncIterator]() {
      return this
    }
  }

  function onevent(...args) {
    if (promises.length) {
      promises.shift().resolve({ value: args, done: false })
    } else {
      events.push(args)
    }
  }

  function onerror(err) {
    emitter.off(name, onevent).off('error', onerror)

    if (promises.length) {
      promises.shift().reject(err)
    } else {
      error = err
    }

    return Promise.resolve({ done: true })
  }

  function onabort() {
    signal.removeEventListener('abort', onabort)

    onerror(errors.OPERATION_ABORTED(signal.reason))
  }

  function onclose() {
    emitter.off(name, onevent)

    if (name !== 'error') emitter.off('error', onerror)

    if (signal) signal.removeEventListener('abort', onabort)

    done = true

    if (promises.length) promises.shift().resolve({ done: true })

    return Promise.resolve({ done: true })
  }
}

exports.once = function once(emitter, name, opts = {}) {
  const { signal } = opts

  if (signal && signal.aborted) {
    return Promise.reject(errors.OPERATION_ABORTED(signal.reason))
  }

  return new Promise((resolve, reject) => {
    if (name !== 'error') emitter.on('error', onerror)

    if (signal) signal.addEventListener('abort', onabort)

    emitter.once(name, onevent)

    function onevent(...args) {
      if (name !== 'error') emitter.off('error', onerror)

      if (signal) signal.removeEventListener('abort', onabort)

      resolve(args)
    }

    function onerror(err) {
      emitter.off(name, onevent)

      if (name !== 'error') emitter.off('error', onerror)

      reject(err)
    }

    function onabort() {
      signal.removeEventListener('abort', onabort)

      onerror(errors.OPERATION_ABORTED(signal.reason))
    }
  })
}

exports.forward = function forward(from, to, names, opts = {}) {
  if (typeof names === 'string') names = [names]

  const { emit = to.emit.bind(to) } = opts

  const listeners = names.map(
    (name) =>
      function onevent(...args) {
        emit(name, ...args)
      }
  )

  to.on('newListener', (name) => {
    const i = names.indexOf(name)

    if (i !== -1 && to.listenerCount(name) === 0) {
      from.on(name, listeners[i])
    }
  }).on('removeListener', (name) => {
    const i = names.indexOf(name)

    if (i !== -1 && to.listenerCount(name) === 0) {
      from.off(name, listeners[i])
    }
  })
}

exports.listenerCount = function listenerCount(emitter, name) {
  return emitter.listenerCount(name)
}

exports.getMaxListeners = function getMaxListeners(emitter) {
  if (typeof emitter.getMaxListeners === 'function') {
    return emitter.getMaxListeners()
  }

  return exports.defaultMaxListeners
}

exports.setMaxListeners = function setMaxListeners(n, ...emitters) {
  if (emitters.length === 0) exports.defaultMaxListeners = n
  else {
    for (const emitter of emitters) {
      if (typeof emitter.setMaxListeners === 'function') {
        emitter.setMaxListeners(n)
      }
    }
  }
}
module.exports = class EventEmitterError extends Error {
  constructor(msg, code, fn = EventEmitterError, opts) {
    super(`${code}: ${msg}`, opts)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'EventEmitterError'
  }

  static OPERATION_ABORTED(cause, msg = 'Operation aborted') {
    return new EventEmitterError(msg, 'OPERATION_ABORTED', EventEmitterError.OPERATION_ABORTED, {
      cause
    })
  }

  static UNHANDLED_ERROR(cause, msg = 'Unhandled error') {
    return new EventEmitterError(msg, 'UNHANDLED_ERROR', EventEmitterError.UNHANDLED_ERROR, {
      cause
    })
  }
}
{
  "name": "bare-events",
  "version": "2.9.1",
  "description": "Event emitters for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    },
    "./web": {
      "types": "./web.d.ts",
      "default": "./web.js"
    },
    "./errors": "./lib/errors.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "global.js",
    "global.d.ts",
    "web.js",
    "web.d.ts",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:bare && npm run test:node",
    "test:bare": "brittle-bare --coverage test.js",
    "test:node": "brittle-node --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-events.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-events/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-events#readme",
  "devDependencies": {
    "bare-abort-controller": "^1.0.0",
    "brittle": "^3.3.2",
    "lunte": "^1.8.0",
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^2.0.0",
    "uncaughts": "^1.1.1"
  },
  "peerDependencies": {
    "bare-abort-controller": "*"
  },
  "peerDependenciesMeta": {
    "bare-abort-controller": {
      "optional": true
    }
  }
}
module.exports = require.addon()
const FIFO = require('fast-fifo')
const EventEmitter = require('bare-events')
const path = require('bare-path')
const { isURL, fileURLToPath } = require('bare-url')
const { Readable, Writable } = require('bare-stream')
const binding = require('./binding')
const constants = require('./lib/constants')
const FileError = require('./lib/errors')

const isWindows = Bare.platform === 'win32'

exports.constants = constants

class FileRequest {
  static borrow() {
    if (this._free.length > 0) return this._free.pop()
    return new FileRequest()
  }

  static return(req) {
    if (this._free.length < 32) this._free.push(req.reset())
    else req.destroy()
  }

  constructor() {
    this._reset()
    this._handle = binding.requestInit(this, this._onresult)
  }

  get handle() {
    return this._handle
  }

  retain(value) {
    this._retain = value // Tie the lifetime of `value` to the lifetime of `this`
  }

  reset() {
    if (this._handle === null) return this

    binding.requestReset(this._handle)

    this._reset()

    return this
  }

  destroy() {
    if (this._handle === null) return this

    binding.requestDestroy(this._handle)

    this._reset()
    this._handle = null

    return this
  }

  then(resolve, reject) {
    return this._promise.then(resolve, reject)
  }

  return() {
    if (this._handle === null) return this

    FileRequest.return(this)

    return this
  }

  _reset() {
    this._promise = new Promise((resolve, reject) => {
      this._resolve = resolve
      this._reject = reject
    })
    this._retain = null
  }

  _onresult(err, status) {
    if (err) this._reject(err)
    else this._resolve(status)
  }
}

FileRequest._free = []

function ok(result, cb) {
  if (typeof result === 'function') {
    cb = result
    result = undefined
  }

  if (cb) cb(null, result)
  else return result
}

function fail(err, cb) {
  if (cb) cb(err)
  else throw err
}

function done(err, result, cb) {
  if (typeof result === 'function') {
    cb = result
    result = undefined
  }

  if (err) fail(err, cb)
  else return ok(result, cb)
}

async function open(filepath, flags = 'r', mode = 0o666, cb) {
  if (typeof flags === 'function') {
    cb = flags
    flags = 'r'
    mode = 0o666
  } else if (typeof mode === 'function') {
    cb = mode
    mode = 0o666
  }

  if (typeof flags === 'string') flags = toFlags(flags)
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let fd
  let err = null
  try {
    binding.open(req.handle, filepath, flags, mode)

    fd = await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'open',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, fd, cb)
}

function openSync(filepath, flags = 'r', mode = 0o666) {
  if (typeof flags === 'string') flags = toFlags(flags)
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    return binding.openSync(req.handle, filepath, flags, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'open',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function close(fd, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.close(req.handle, fd)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'close', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function closeSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.closeSync(req.handle, fd)
  } catch (e) {
    throw new FileError(e.message, { operation: 'close', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function access(filepath, mode = constants.F_OK, cb) {
  if (typeof mode === 'function') {
    cb = mode
    mode = constants.F_OK
  }

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.access(req.handle, filepath, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'access',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function accessSync(filepath, mode = constants.F_OK) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.accessSync(req.handle, filepath, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'access',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function exists(filepath, cb) {
  let ok = true
  try {
    await access(filepath)
  } catch {
    ok = false
  }

  return done(null, ok, cb)
}

function existsSync(filepath) {
  try {
    accessSync(filepath)
  } catch {
    return false
  }

  return true
}

async function read(fd, buffer, offset = 0, len = buffer.byteLength - offset, pos = -1, cb) {
  if (typeof offset === 'function') {
    cb = offset
    offset = 0
    len = buffer.byteLength
    pos = -1
  } else if (typeof len === 'function') {
    cb = len
    len = buffer.byteLength - offset
    pos = -1
  } else if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.read(req.handle, fd, buffer, offset, len, pos)

    req.retain(buffer)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'read', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function readSync(fd, buffer, offset = 0, len = buffer.byteLength - offset, pos = -1) {
  const req = FileRequest.borrow()

  try {
    return binding.readSync(req.handle, fd, buffer, offset, len, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'read', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function readv(fd, buffers, pos = -1, cb) {
  if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.readv(req.handle, fd, buffers, pos)

    req.retain(buffers)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'readv', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function readvSync(fd, buffers, pos = -1) {
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  try {
    return binding.readvSync(req.handle, fd, buffers, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'readv', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function write(fd, data, offset, len, pos = -1, cb) {
  if (typeof data === 'string') {
    let encoding = len
    cb = pos
    pos = offset

    if (typeof pos === 'function') {
      cb = pos
      pos = -1
      encoding = 'utf8'
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = 'utf8'
    }

    if (typeof pos === 'string') {
      encoding = pos
      pos = -1
    }

    data = Buffer.from(data, encoding)
    offset = 0
    len = data.byteLength
  } else if (typeof offset === 'function') {
    cb = offset
    offset = 0
    len = data.byteLength
    pos = -1
  } else if (typeof len === 'function') {
    cb = len
    len = data.byteLength - offset
    pos = -1
  } else if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof offset !== 'number') offset = 0
  if (typeof len !== 'number') len = data.byteLength - offset
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.write(req.handle, fd, data, offset, len, pos)

    req.retain(data)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'write', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function writeSync(fd, data, offset, len, pos = -1) {
  if (typeof data === 'string') {
    let encoding = len
    pos = offset

    if (typeof pos === 'string') {
      encoding = pos
      pos = -1
    }

    data = Buffer.from(data, encoding)
    offset = 0
    len = data.byteLength
  }

  if (typeof offset !== 'number') offset = 0
  if (typeof len !== 'number') len = data.byteLength - offset
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  try {
    return binding.writeSync(req.handle, fd, data, offset, len, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'write', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function writev(fd, buffers, pos = -1, cb) {
  if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.writev(req.handle, fd, buffers, pos)

    req.retain(buffers)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'writev', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function writevSync(fd, buffers, pos = -1) {
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  try {
    return binding.writevSync(req.handle, fd, buffers, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'writev', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function stat(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.stat(req.handle, filepath)

    await req

    st = new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'stat', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function statSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.statSync(req.handle, filepath)

    return new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'stat', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function lstat(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.lstat(req.handle, filepath)

    await req

    st = new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'lstat', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function lstatSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.lstatSync(req.handle, filepath)

    return new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'lstat', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function fstat(fd, cb) {
  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.fstat(req.handle, fd)

    await req

    st = new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'fstat', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function fstatSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.fstatSync(req.handle, fd)

    return new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'fstat', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function statfs(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.statfs(req.handle, filepath)

    await req

    st = new StatFs(...binding.requestResultStatfs(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'statfs', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function statfsSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.statfsSync(req.handle, filepath)

    return new StatFs(...binding.requestResultStatfs(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'statfs', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function ftruncate(fd, len = 0, cb) {
  if (typeof len === 'function') {
    cb = len
    len = 0
  }

  if (typeof len !== 'number') len = 0

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.ftruncate(req.handle, fd, len)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'ftruncate', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function ftruncateSync(fd, len = 0) {
  if (typeof len !== 'number') len = 0

  const req = FileRequest.borrow()

  try {
    binding.ftruncateSync(req.handle, fd, len)
  } catch (e) {
    throw new FileError(e.message, { operation: 'ftruncate', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function truncate(filepath, len, cb) {
  let fd = -1
  let err

  try {
    fd = await open(filepath, 'r+')

    await ftruncate(fd, len)
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) await close(fd)
  }

  return done(err, cb)
}

function truncateSync(filepath, len) {
  let fd = -1
  let err

  try {
    fd = openSync(filepath, 'r+')

    ftruncateSync(fd, len)
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) closeSync(fd)
  }
}

async function chmod(filepath, mode, cb) {
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.chmod(req.handle, filepath, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'chmod',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function chmodSync(filepath, mode) {
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.chmodSync(req.handle, filepath, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'chmod',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function fchmod(fd, mode, cb) {
  if (typeof mode === 'string') mode = toMode(mode)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fchmod(req.handle, fd, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fchmod', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fchmodSync(fd, mode) {
  if (typeof mode === 'string') mode = toMode(mode)

  const req = FileRequest.borrow()

  try {
    binding.fchmodSync(req.handle, fd, mode)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fchmod', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function chown(filepath, uid, gid, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.chown(req.handle, filepath, uid, gid)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'chown', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function chownSync(filepath, uid, gid) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.chownSync(req.handle, filepath, uid, gid)
  } catch (e) {
    throw new FileError(e.message, { operation: 'chownSync', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function lchown(filepath, uid, gid, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.lchown(req.handle, filepath, uid, gid)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'lchown', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function lchownSync(filepath, uid, gid) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.lchownSync(req.handle, filepath, uid, gid)
  } catch (e) {
    throw new FileError(e.message, { operation: 'lchownSync', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function fchown(fd, uid, gid, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fchown(req.handle, fd, uid, gid)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fchown', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fchownSync(fd, uid, gid) {
  const req = FileRequest.borrow()

  try {
    binding.fchownSync(req.handle, fd, uid, gid)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fchownSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function utimes(filepath, atime, mtime, cb) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.utimes(req.handle, filepath, atime, mtime)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'utimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function utimesSync(filepath, atime, mtime) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.utimesSync(req.handle, filepath, atime, mtime)
  } catch (e) {
    throw new FileError(e.message, { operation: 'utimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function lutimes(filepath, atime, mtime, cb) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.lutimes(req.handle, filepath, atime, mtime)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'lutimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function lutimesSync(filepath, atime, mtime) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.lutimesSync(req.handle, filepath, atime, mtime)
  } catch (e) {
    throw new FileError(e.message, { operation: 'lutimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function futimes(fd, atime, mtime, cb) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.futimes(req.handle, fd, atime, mtime)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'futimes', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function futimesSync(fd, atime, mtime) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  const req = FileRequest.borrow()

  try {
    binding.futimesSync(req.handle, fd, atime, mtime)
  } catch (e) {
    throw new FileError(e.message, { operation: 'futimesSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function link(src, dst, cb) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.link(req.handle, src, dst)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'link', code: e.code, path: src, destination: dst })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function linkSync(src, dst) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  try {
    binding.linkSync(req.handle, src, dst)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'linkSync',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }
}

async function mkdir(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = { mode: 0o777 }
  }

  if (typeof opts === 'number') opts = { mode: opts }
  else if (!opts) opts = {}

  const mode = typeof opts.mode === 'number' ? opts.mode : 0o777

  filepath = toNamespacedPath(filepath)

  if (opts.recursive) {
    let err = null
    try {
      try {
        await mkdir(filepath, { mode })
      } catch (err) {
        if (err.code !== 'ENOENT') {
          if (!(await stat(filepath)).isDirectory()) throw err
        } else {
          while (filepath.endsWith(path.sep)) filepath = filepath.slice(0, -1)
          const i = filepath.lastIndexOf(path.sep)
          if (i <= 0) throw err

          await mkdir(filepath.slice(0, i), { mode, recursive: true })

          try {
            await mkdir(filepath, { mode })
          } catch (err) {
            if (!(await stat(filepath)).isDirectory()) throw err
          }
        }
      }
    } catch (e) {
      err = e
    }

    return done(err, cb)
  }

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.mkdir(req.handle, filepath, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'mkdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function mkdirSync(filepath, opts) {
  if (typeof opts === 'number') opts = { mode: opts }
  else if (!opts) opts = {}

  const mode = typeof opts.mode === 'number' ? opts.mode : 0o777

  filepath = toNamespacedPath(filepath)

  if (opts.recursive) {
    try {
      mkdirSync(filepath, { mode })
    } catch (err) {
      if (err.code !== 'ENOENT') {
        if (!statSync(filepath).isDirectory()) throw err
      } else {
        while (filepath.endsWith(path.sep)) filepath = filepath.slice(0, -1)
        const i = filepath.lastIndexOf(path.sep)
        if (i <= 0) throw err

        mkdirSync(filepath.slice(0, i), { mode, recursive: true })

        try {
          mkdirSync(filepath, { mode })
        } catch (err) {
          if (!statSync(filepath).isDirectory()) throw err
        }
      }
    }

    return
  }

  const req = FileRequest.borrow()

  try {
    binding.mkdirSync(req.handle, filepath, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'mkdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function mkdtemp(prefix, cb) {
  prefix = toNamespacedPath(prefix)

  const req = FileRequest.borrow()

  let res
  let err = null
  try {
    binding.mkdtemp(req.handle, prefix + 'XXXXXX')

    await req

    res = binding.requestResultPath(req.handle)
  } catch (e) {
    err = new FileError(e.message, { operation: 'mkdtemp', code: e.code, path: prefix })
  } finally {
    req.return()
  }

  return done(err, res, cb)
}

function mkdtempSync(prefix) {
  prefix = toNamespacedPath(prefix)

  const req = FileRequest.borrow()

  try {
    binding.mkdtempSync(req.handle, prefix + 'XXXXXX')

    return binding.requestResultPath(req.handle)
  } catch (e) {
    throw new FileError(e.message, { operation: 'mkdtempSync', code: e.code, path: prefix })
  } finally {
    req.return()
  }
}

async function rmdir(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.rmdir(req.handle, filepath)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'rmdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function rmdirSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.rmdirSync(req.handle, filepath)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'rmdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function rm(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  let err = null
  try {
    const st = await lstat(filepath)

    if (st.isDirectory()) {
      if (opts.recursive) {
        try {
          await rmdir(filepath)
        } catch (err) {
          if (err.code !== 'ENOTEMPTY') throw err

          const files = await readdir(filepath)

          for (const file of files) {
            await rm(filepath + path.sep + file, opts)
          }

          await rmdir(filepath)
        }
      } else {
        throw new FileError('is a directory', {
          operation: 'rm',
          code: 'EISDIR',
          path: filepath
        })
      }
    } else {
      await unlink(filepath)
    }
  } catch (e) {
    if (e.code !== 'ENOENT' || !opts.force) err = e
  }

  return done(err, cb)
}

function rmSync(filepath, opts) {
  if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  try {
    const st = lstatSync(filepath)

    if (st.isDirectory()) {
      if (opts.recursive) {
        try {
          rmdirSync(filepath)
        } catch (err) {
          if (err.code !== 'ENOTEMPTY') throw err

          const files = readdirSync(filepath)

          for (const file of files) {
            rmSync(filepath + path.sep + file, opts)
          }

          rmdirSync(filepath)
        }
      } else {
        throw new FileError('is a directory', {
          operation: 'rm',
          code: 'EISDIR',
          path: filepath
        })
      }
    } else {
      unlinkSync(filepath)
    }
  } catch (err) {
    if (err.code !== 'ENOENT' || !opts.force) throw err
  }
}

async function unlink(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.unlink(req.handle, filepath)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'unlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function unlinkSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.unlinkSync(req.handle, filepath)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'unlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function rename(src, dst, cb) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.rename(req.handle, src, dst)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'rename',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function renameSync(src, dst) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  try {
    binding.renameSync(req.handle, src, dst)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'rename',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }
}

async function copyFile(src, dst, mode = 0, cb) {
  if (typeof mode === 'function') {
    cb = mode
    mode = 0
  }

  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.copyfile(req.handle, src, dst, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'copyfile',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function copyFileSync(src, dst, mode = 0) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  try {
    binding.copyfileSync(req.handle, src, dst, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'copyfile',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }
}

async function cp(src, dst, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (!opts) opts = {}

  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  let err = null
  try {
    const st = await lstat(src)

    if (st.isDirectory()) {
      if (opts.recursive !== true) {
        throw new FileError('is a directory', { operation: 'cp', code: 'EISDIR', path: src })
      }

      try {
        await lstat(dst)
      } catch (e) {
        if (e.code !== 'ENOENT') throw e

        await mkdir(dst, { mode: st.mode, recursive: true })
      }

      const dir = await opendir(src)
      for await (const { name } of dir) {
        await cp(path.join(src, name), path.join(dst, name), opts)
      }
    } else if (st.isFile()) {
      await copyFile(src, dst)
      await chmod(dst, st.mode)
    }
  } catch (e) {
    err = e
  }

  return done(err, cb)
}

function cpSync(src, dst, opts = {}) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const st = lstatSync(src)

  if (st.isDirectory()) {
    if (opts.recursive !== true) {
      throw new FileError('is a directory', { operation: 'cp', code: 'EISDIR', path: src })
    }

    try {
      lstatSync(dst)
    } catch (e) {
      if (e.code !== 'ENOENT') throw e

      mkdirSync(dst, { mode: st.mode, recursive: true })
    }

    const dir = opendirSync(src)
    for (const { name } of dir) {
      cpSync(path.join(src, name), path.join(dst, name), opts)
    }
  } else if (st.isFile()) {
    copyFileSync(src, dst)
    chmodSync(dst, st.mode)
  }
}

async function realpath(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let res
  let err = null
  try {
    binding.realpath(req.handle, filepath)

    await req

    res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'realpath',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, res, cb)
}

function realpathSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.realpathSync(req.handle, filepath)

    let res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)

    return res
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'realpath',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function readlink(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let res
  let err = null
  try {
    binding.readlink(req.handle, filepath)

    await req

    res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'readlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, res, cb)
}

function readlinkSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.readlinkSync(req.handle, filepath)

    let res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)

    return res
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'readlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function fsync(fd, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fsync(req.handle, fd)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fsync', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fsyncSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.fsyncSync(req.handle, fd)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fsyncSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function fdatasync(fd, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fdatasync(req.handle, fd)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fdatasync', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fdatasyncSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.fdatasyncSync(req.handle, fd)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fdatasyncSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

function normalizeSymlinkTarget(target, type, filepath) {
  if (isWindows) {
    if (type === constants.UV_FS_SYMLINK_JUNCTION) target = path.resolve(filepath, '..', target)

    if (path.isAbsolute(target)) return path.toNamespacedPath(target)

    return target.replace(/\//g, path.sep)
  }

  return target
}

async function symlink(target, filepath, type, cb) {
  if (typeof type === 'function') {
    cb = type
    type = null
  }

  filepath = toNamespacedPath(filepath)

  if (typeof type === 'string') {
    switch (type) {
      case 'dir':
        type = constants.UV_FS_SYMLINK_DIR
        break
      case 'junction':
        type = constants.UV_FS_SYMLINK_JUNCTION
        break
      case 'file':
      default:
        type = 0
        break
    }
  } else if (typeof type !== 'number') {
    if (isWindows) {
      target = path.resolve(filepath, '..', target)

      try {
        type = (await stat(target)).isDirectory()
          ? constants.UV_FS_SYMLINK_DIR
          : constants.UV_FS_SYMLINK_JUNCTION
      } catch {
        type = 0
      }
    } else {
      type = 0
    }
  }

  target = normalizeSymlinkTarget(target, type, filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.symlink(req.handle, target, filepath, type)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'symlink',
      code: e.code,
      path: target,
      destination: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function symlinkSync(target, filepath, type) {
  filepath = toNamespacedPath(filepath)

  if (typeof type === 'string') {
    switch (type) {
      case 'dir':
        type = constants.UV_FS_SYMLINK_DIR
        break
      case 'junction':
        type = constants.UV_FS_SYMLINK_JUNCTION
        break
      case 'file':
      default:
        type = 0
        break
    }
  } else if (typeof type !== 'number') {
    if (isWindows) {
      target = path.resolve(filepath, '..', target)

      try {
        type = statSync(target).isDirectory()
          ? constants.UV_FS_SYMLINK_DIR
          : constants.UV_FS_SYMLINK_JUNCTION
      } catch {
        type = 0
      }
    } else {
      type = 0
    }
  }

  target = normalizeSymlinkTarget(target, type, filepath)

  const req = FileRequest.borrow()

  try {
    binding.symlinkSync(req.handle, target, filepath, type)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'symlink',
      code: e.code,
      path: target,
      destination: filepath
    })
  } finally {
    req.return()
  }
}

async function opendir(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let dir
  let err = null
  try {
    binding.opendir(req.handle, filepath)

    await req

    dir = new Dir(filepath, binding.requestResultDir(req.handle), opts)
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'opendir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, dir, cb)
}

function opendirSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.opendirSync(req.handle, filepath)

    return new Dir(filepath, binding.requestResultDir(req.handle), opts)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'opendir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function readdir(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { withFileTypes = false, recursive = false } = opts

  filepath = toNamespacedPath(filepath)

  const queue = [filepath]
  let result = []
  let err = null
  try {
    while (queue.length !== 0) {
      const dir = await opendir(queue.pop())

      for await (const entry of dir) {
        const entryPath = path.join(entry.parentPath, entry.name)

        if (withFileTypes) {
          result.push(entry)
        } else {
          result.push(path.relative(filepath, entryPath))
        }

        if (recursive && entry.isDirectory()) queue.push(entryPath)
      }
    }
  } catch (e) {
    result = []
    err = e
  }

  return done(err, result, cb)
}

function readdirSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { withFileTypes = false, recursive = false } = opts

  filepath = toNamespacedPath(filepath)

  const queue = [filepath]
  const result = []

  while (queue.length !== 0) {
    const dir = opendirSync(queue.pop(), opts)

    for (const entry of dir) {
      const entryPath = path.join(entry.parentPath, entry.name)

      if (withFileTypes) {
        result.push(entry)
      } else {
        result.push(path.relative(filepath, entryPath))
      }

      if (recursive && entry.isDirectory()) queue.push(entryPath)
    }
  }

  return result
}

async function readFile(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'buffer' } = opts

  let fd = -1
  let buffer = null
  let err = null
  try {
    fd = await open(filepath, opts.flag || 'r')

    const st = await fstat(fd)

    let len = 0

    if (st.size === 0) {
      const buffers = []

      while (true) {
        buffer = Buffer.allocUnsafe(8192)
        const r = await read(fd, buffer)
        len += r
        if (r === 0) break
        buffers.push(buffer.subarray(0, r))
      }

      buffer = Buffer.concat(buffers)
    } else {
      buffer = Buffer.allocUnsafe(st.size)

      while (true) {
        const r = await read(fd, len ? buffer.subarray(len) : buffer)
        len += r
        if (r === 0 || len === buffer.byteLength) break
      }

      if (len !== buffer.byteLength) buffer = buffer.subarray(0, len)
    }

    if (encoding !== 'buffer') buffer = buffer.toString(encoding)
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) await close(fd)
  }

  return done(err, buffer, cb)
}

function readFileSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'buffer' } = opts

  let fd = -1
  try {
    fd = openSync(filepath, opts.flag || 'r')

    const st = fstatSync(fd)

    let buffer
    let len = 0

    if (st.size === 0) {
      const buffers = []

      while (true) {
        buffer = Buffer.allocUnsafe(8192)
        const r = readSync(fd, buffer)
        len += r
        if (r === 0) break
        buffers.push(buffer.subarray(0, r))
      }

      buffer = Buffer.concat(buffers)
    } else {
      buffer = Buffer.allocUnsafe(st.size)

      while (true) {
        const r = readSync(fd, len ? buffer.subarray(len) : buffer)
        len += r
        if (r === 0 || len === buffer.byteLength) break
      }

      if (len !== buffer.byteLength) buffer = buffer.subarray(0, len)
    }

    if (encoding !== 'buffer') buffer = buffer.toString(encoding)

    return buffer
  } finally {
    if (fd !== -1) closeSync(fd)
  }
}

async function writeFile(filepath, data, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (typeof data === 'string') data = Buffer.from(data, opts.encoding)

  let fd = -1
  let len = 0
  let err = null
  try {
    fd = await open(filepath, opts.flag || 'w', opts.mode || 0o666)

    while (true) {
      len += await write(fd, len ? data.subarray(len) : data)
      if (len === data.byteLength) break
    }
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) await close(fd)
  }

  return done(err, len, cb)
}

function writeFileSync(filepath, data, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (typeof data === 'string') data = Buffer.from(data, opts.encoding)

  let fd = -1
  try {
    fd = openSync(filepath, opts.flag || 'w', opts.mode || 0o666)

    let len = 0

    while (true) {
      len += writeSync(fd, len ? data.subarray(len) : data)
      if (len === data.byteLength) break
    }
  } finally {
    if (fd !== -1) closeSync(fd)
  }
}

function appendFile(filepath, data, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (!opts.flag) opts = { ...opts, flag: 'a' }

  return writeFile(filepath, data, opts, cb)
}

function appendFileSync(filepath, data, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (!opts.flag) opts = { ...opts, flag: 'a' }

  return writeFileSync(filepath, data, opts)
}

function watch(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  return new Watcher(filepath, opts, cb)
}

class Stats {
  constructor(
    dev,
    mode,
    nlink,
    uid,
    gid,
    rdev,
    blksize,
    ino,
    size,
    blocks,
    atimeMs,
    mtimeMs,
    ctimeMs,
    birthtimeMs
  ) {
    this.dev = dev
    this.mode = mode
    this.nlink = nlink
    this.uid = uid
    this.gid = gid
    this.rdev = rdev
    this.blksize = blksize
    this.ino = ino
    this.size = size
    this.blocks = blocks
    this.atimeMs = atimeMs
    this.mtimeMs = mtimeMs
    this.ctimeMs = ctimeMs
    this.birthtimeMs = birthtimeMs
    this.atime = new Date(atimeMs)
    this.mtime = new Date(mtimeMs)
    this.ctime = new Date(ctimeMs)
    this.birthtime = new Date(birthtimeMs)
  }

  isDirectory() {
    return (this.mode & constants.S_IFMT) === constants.S_IFDIR
  }

  isFile() {
    return (this.mode & constants.S_IFMT) === constants.S_IFREG
  }

  isBlockDevice() {
    return (this.mode & constants.S_IFMT) === constants.S_IFBLK
  }

  isCharacterDevice() {
    return (this.mode & constants.S_IFMT) === constants.S_IFCHR
  }

  isFIFO() {
    return (this.mode & constants.S_IFMT) === constants.S_IFIFO
  }

  isSymbolicLink() {
    return (this.mode & constants.S_IFMT) === constants.S_IFLNK
  }

  isSocket() {
    return (this.mode & constants.S_IFMT) === constants.S_IFSOCK
  }
}

class StatFs {
  constructor(type, bsize, blocks, bfree, bavail, files, ffree) {
    this.type = type
    this.bsize = bsize
    this.blocks = blocks
    this.bfree = bfree
    this.bavail = bavail
    this.files = files
    this.ffree = ffree
  }
}

class Dir {
  constructor(path, handle, opts = {}) {
    const { encoding = 'utf8', bufferSize = 32 } = opts

    this.path = path

    this._encoding = encoding
    this._capacity = bufferSize
    this._buffer = new FIFO()
    this._ended = false
    this._handle = handle
  }

  async read(cb) {
    if (this._buffer.length) return ok(this._buffer.shift(), cb)
    if (this._ended) return ok(null, cb)

    const req = FileRequest.borrow()

    let entries
    let err = null
    try {
      req.retain(binding.readdir(req.handle, this._handle, this._capacity))

      await req

      entries = binding.requestResultDirents(req.handle)
    } catch (e) {
      err = new FileError(e.message, {
        operation: 'readdir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    if (err) return fail(err, cb)

    if (entries.length === 0) {
      this._ended = true

      return ok(null, cb)
    }

    for (const entry of entries) {
      let name = Buffer.from(entry.name)

      if (this._encoding !== 'buffer') name = name.toString(this._encoding)

      this._buffer.push(new Dirent(this.path, name, entry.type))
    }

    return ok(this._buffer.shift(), cb)
  }

  readSync() {
    if (this._buffer.length) return this._buffer.shift()
    if (this._ended) return null

    const req = FileRequest.borrow()

    let entries
    try {
      req.retain(binding.readdirSync(req.handle, this._handle, this._capacity))

      entries = binding.requestResultDirents(req.handle)
    } catch (e) {
      throw new FileError(e.message, {
        operation: 'readdir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    if (entries.length === 0) {
      this._ended = true

      return null
    }

    for (const entry of entries) {
      let name = Buffer.from(entry.name)

      if (this._encoding !== 'buffer') name = name.toString(this._encoding)

      this._buffer.push(new Dirent(this.path, name, entry.type))
    }

    return this._buffer.shift()
  }

  async close(cb) {
    const req = FileRequest.borrow()

    let err = null
    try {
      binding.closedir(req.handle, this._handle)

      await req
    } catch (e) {
      err = new FileError(e.message, {
        operation: 'closedir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    this._handle = null

    return done(err, cb)
  }

  closeSync() {
    const req = FileRequest.borrow()

    try {
      binding.closedirSync(req.handle, this._handle)
    } catch (e) {
      throw new FileError(e.message, {
        operation: 'closedir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    this._handle = null
  }

  [Symbol.dispose]() {
    this.closeSync()
  }

  async [Symbol.asyncDispose]() {
    await this.close()
  }

  *[Symbol.iterator]() {
    while (true) {
      const entry = this.readSync()
      if (entry === null) break
      yield entry
    }

    this.closeSync()
  }

  async *[Symbol.asyncIterator]() {
    while (true) {
      const entry = await this.read()
      if (entry === null) break
      yield entry
    }

    await this.close()
  }
}

class Dirent {
  constructor(parentPath, name, type) {
    this.parentPath = parentPath
    this.name = name
    this.type = type
  }

  isFile() {
    return this.type === constants.UV_DIRENT_FILE
  }

  isDirectory() {
    return this.type === constants.UV_DIRENT_DIR
  }

  isSymbolicLink() {
    return this.type === constants.UV_DIRENT_LINK
  }

  isFIFO() {
    return this.type === constants.UV_DIRENT_FIFO
  }

  isSocket() {
    return this.type === constants.UV_DIRENT_SOCKET
  }

  isCharacterDevice() {
    return this.type === constants.UV_DIRENT_CHAR
  }

  isBlockDevice() {
    return this.type === constants.UV_DIRENT_BLOCK
  }
}

class FileReadStream extends Readable {
  constructor(path, opts = {}) {
    const { eagerOpen = true } = opts

    super({ eagerOpen, ...opts })

    this.path = path
    this.fd = typeof opts.fd === 'number' ? opts.fd : -1
    this.flags = opts.flags || 'r'
    this.mode = opts.mode || 0o666

    this._offset = opts.start || 0
    this._missing = 0

    if (opts.length) {
      this._missing = opts.length
    } else if (typeof opts.end === 'number') {
      this._missing = opts.end - this._offset + 1
    } else {
      this._missing = -1
    }
  }

  async _open(cb) {
    let err

    if (this.fd === -1) {
      err = null
      try {
        this.fd = await open(this.path, this.flags, this.mode)
      } catch (e) {
        err = e
      }

      if (err) return cb(err)
    }

    let st
    err = null
    try {
      st = await fstat(this.fd)
    } catch (e) {
      err = e
    }

    if (err) return cb(err)

    if (this._missing === -1) this._missing = st.size

    if (st.size < this._offset) {
      this._offset = st.size
      this._missing = 0
    } else if (st.size < this._offset + this._missing) {
      this._missing = st.size - this._offset
    }

    cb(null)
  }

  async _read(size) {
    if (this._missing <= 0) return this.push(null)

    const data = Buffer.allocUnsafe(Math.min(this._missing, size))

    let len
    let err = null
    try {
      len = await read(this.fd, data, 0, data.byteLength, this._offset)
    } catch (e) {
      err = e
    }

    if (err) return this.destroy(err)

    if (len === 0) return this.push(null)

    if (this._missing < len) len = this._missing

    this._missing -= len
    this._offset += len

    this.push(data.subarray(0, len))
  }

  async _destroy(err, cb) {
    if (this.fd === -1) return cb(err)

    try {
      await close(this.fd)
    } catch (e) {
      err = err || e
    }

    cb(err)
  }
}

class FileWriteStream extends Writable {
  constructor(path, opts = {}) {
    const { eagerOpen = true } = opts

    super({ eagerOpen, ...opts })

    this.path = path
    this.fd = typeof opts.fd === 'number' ? opts.fd : -1
    this.flags = opts.flags || 'w'
    this.mode = opts.mode || 0o666
  }

  async _open(cb) {
    if (this.fd !== -1) return cb(null)

    let err = null
    try {
      this.fd = await open(this.path, this.flags, this.mode)
    } catch (e) {
      err = e
    }

    cb(err)
  }

  async _writev(batch, cb) {
    let err = null
    try {
      await writev(
        this.fd,
        batch.map(({ chunk }) => chunk)
      )
    } catch (e) {
      err = e
    }

    cb(err)
  }

  async _destroy(err, cb) {
    if (this.fd === -1) return cb(err)

    try {
      await close(this.fd)
    } catch (e) {
      err = err || e
    }

    cb(err)
  }
}

class Watcher extends EventEmitter {
  constructor(path, opts, onchange) {
    if (typeof opts === 'function') {
      onchange = opts
      opts = {}
    }

    if (!opts) opts = {}

    const { persistent = true, recursive = false, encoding = 'utf8' } = opts

    super()

    this._closed = false
    this._encoding = encoding
    this._handle = binding.watcherInit(path, recursive, this, this._onevent, this._onclose)

    if (!persistent) this.unref()

    if (onchange) this.on('change', onchange)
  }

  close() {
    if (this._closed) return
    this._closed = true

    binding.watcherClose(this._handle)
  }

  ref() {
    if (this._handle) binding.watcherRef(this._handle)
    return this
  }

  unref() {
    if (this._handle) binding.watcherUnref(this._handle)
    return this
  }

  [Symbol.asyncIterator]() {
    const buffer = []
    let done = false
    let error = null
    let next = null

    this.on('change', (eventType, filename) => {
      if (next) {
        next.resolve({ done: false, value: { eventType, filename } })
        next = null
      } else {
        buffer.push({ eventType, filename })
      }
    })
      .on('error', (err) => {
        done = true
        error = err

        if (next) {
          next.reject(error)
          next = null
        }
      })
      .on('close', () => {
        done = true

        if (next) {
          next.resolve({ done })
          next = null
        }
      })

    return {
      next: () =>
        new Promise((resolve, reject) => {
          if (error) return reject(error)

          if (buffer.length) return resolve({ done: false, value: buffer.shift() })

          if (done) return resolve({ done })

          next = { resolve, reject }
        })
    }
  }

  _onevent(err, events, filename) {
    if (err) {
      this.close()
      this.emit('error', err)
    } else {
      const path =
        this._encoding === 'buffer'
          ? Buffer.from(filename)
          : Buffer.from(filename).toString(this._encoding)

      if (events & binding.UV_RENAME) {
        this.emit('change', 'rename', path)
      }

      if (events & binding.UV_CHANGE) {
        this.emit('change', 'change', path)
      }
    }
  }

  _onclose() {
    this._handle = null

    this.emit('close')
  }
}

exports.access = access
exports.appendFile = appendFile
exports.chmod = chmod
exports.chown = chown
exports.close = close
exports.copyFile = copyFile
exports.cp = cp
exports.exists = exists
exports.fchmod = fchmod
exports.fchown = fchown
exports.fdatasync = fdatasync
exports.fstat = fstat
exports.fsync = fsync
exports.ftruncate = ftruncate
exports.futimes = futimes
exports.lchown = lchown
exports.lutimes = lutimes
exports.link = link
exports.lstat = lstat
exports.mkdir = mkdir
exports.mkdtemp = mkdtemp
exports.open = open
exports.opendir = opendir
exports.read = read
exports.readFile = readFile
exports.readdir = readdir
exports.readlink = readlink
exports.readv = readv
exports.realpath = realpath
exports.rename = rename
exports.rm = rm
exports.rmdir = rmdir
exports.stat = stat
exports.statfs = statfs
exports.symlink = symlink
exports.truncate = truncate
exports.unlink = unlink
exports.utimes = utimes
exports.watch = watch
exports.write = write
exports.writeFile = writeFile
exports.writev = writev

exports.accessSync = accessSync
exports.appendFileSync = appendFileSync
exports.chmodSync = chmodSync
exports.chownSync = chownSync
exports.closeSync = closeSync
exports.copyFileSync = copyFileSync
exports.cpSync = cpSync
exports.existsSync = existsSync
exports.fchmodSync = fchmodSync
exports.fchownSync = fchownSync
exports.fdatasyncSync = fdatasyncSync
exports.fstatSync = fstatSync
exports.fsyncSync = fsyncSync
exports.ftruncateSync = ftruncateSync
exports.futimesSync = futimesSync
exports.lchownSync = lchownSync
exports.lutimesSync = lutimesSync
exports.linkSync = linkSync
exports.lstatSync = lstatSync
exports.mkdirSync = mkdirSync
exports.mkdtempSync = mkdtempSync
exports.openSync = openSync
exports.opendirSync = opendirSync
exports.readFileSync = readFileSync
exports.readSync = readSync
exports.readdirSync = readdirSync
exports.readlinkSync = readlinkSync
exports.readvSync = readvSync
exports.realpathSync = realpathSync
exports.renameSync = renameSync
exports.rmSync = rmSync
exports.rmdirSync = rmdirSync
exports.statSync = statSync
exports.statfsSync = statfsSync
exports.symlinkSync = symlinkSync
exports.truncateSync = truncateSync
exports.unlinkSync = unlinkSync
exports.utimesSync = utimesSync
exports.writeFileSync = writeFileSync
exports.writeSync = writeSync
exports.writevSync = writevSync

exports.promises = require('./promises')

exports.Stats = Stats
exports.StatFs = StatFs
exports.Dir = Dir
exports.Dirent = Dirent
exports.Watcher = Watcher

exports.ReadStream = FileReadStream

exports.createReadStream = function createReadStream(path, opts) {
  return new FileReadStream(path, opts)
}

exports.WriteStream = FileWriteStream

exports.createWriteStream = function createWriteStream(path, opts) {
  return new FileWriteStream(path, opts)
}

function toNamespacedPath(filepath) {
  if (typeof filepath !== 'string') {
    if (isURL(filepath)) filepath = fileURLToPath(filepath)
    else filepath = filepath.toString()
  }

  return path.toNamespacedPath(filepath)
}

function toFlags(flags) {
  switch (flags) {
    case 'r':
      return constants.O_RDONLY
    case 'rs': // Fall through.
    case 'sr':
      return constants.O_RDONLY | constants.O_SYNC
    case 'r+':
      return constants.O_RDWR
    case 'rs+': // Fall through.
    case 'sr+':
      return constants.O_RDWR | constants.O_SYNC

    case 'w':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_WRONLY
    case 'wx': // Fall through.
    case 'xw':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_WRONLY | constants.O_EXCL

    case 'w+':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_RDWR
    case 'wx+': // Fall through.
    case 'xw+':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_RDWR | constants.O_EXCL

    case 'a':
      return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY
    case 'ax': // Fall through.
    case 'xa':
      return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY | constants.O_EXCL
    case 'as': // Fall through.
    case 'sa':
      return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY | constants.O_SYNC

    case 'a+':
      return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR
    case 'ax+': // Fall through.
    case 'xa+':
      return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR | constants.O_EXCL
    case 'as+': // Fall through.
    case 'sa+':
      return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR | constants.O_SYNC
    default:
      return 0
  }
}

function toMode(mode) {
  return parseInt(mode, 8)
}
const binding = require('../binding')

module.exports = {
  O_RDWR: binding.O_RDWR,
  O_RDONLY: binding.O_RDONLY,
  O_WRONLY: binding.O_WRONLY,
  O_CREAT: binding.O_CREAT,
  O_TRUNC: binding.O_TRUNC,
  O_APPEND: binding.O_APPEND,

  F_OK: binding.F_OK || 0,
  R_OK: binding.R_OK || 0,
  W_OK: binding.W_OK || 0,
  X_OK: binding.X_OK || 0,

  S_IFMT: binding.S_IFMT,
  S_IFREG: binding.S_IFREG,
  S_IFDIR: binding.S_IFDIR,
  S_IFCHR: binding.S_IFCHR,
  S_IFLNK: binding.S_IFLNK,
  S_IFBLK: binding.S_IFBLK || 0,
  S_IFIFO: binding.S_IFIFO || 0,
  S_IFSOCK: binding.S_IFSOCK || 0,

  S_IRUSR: binding.S_IRUSR || 0,
  S_IWUSR: binding.S_IWUSR || 0,
  S_IXUSR: binding.S_IXUSR || 0,
  S_IRGRP: binding.S_IRGRP || 0,
  S_IWGRP: binding.S_IWGRP || 0,
  S_IXGRP: binding.S_IXGRP || 0,
  S_IROTH: binding.S_IROTH || 0,
  S_IWOTH: binding.S_IWOTH || 0,
  S_IXOTH: binding.S_IXOTH || 0,

  UV_DIRENT_UNKNOWN: binding.UV_DIRENT_UNKNOWN,
  UV_DIRENT_FILE: binding.UV_DIRENT_FILE,
  UV_DIRENT_DIR: binding.UV_DIRENT_DIR,
  UV_DIRENT_LINK: binding.UV_DIRENT_LINK,
  UV_DIRENT_FIFO: binding.UV_DIRENT_FIFO,
  UV_DIRENT_SOCKET: binding.UV_DIRENT_SOCKET,
  UV_DIRENT_CHAR: binding.UV_DIRENT_CHAR,
  UV_DIRENT_BLOCK: binding.UV_DIRENT_BLOCK,

  COPYFILE_EXCL: binding.UV_FS_COPYFILE_EXCL,
  COPYFILE_FICLONE: binding.UV_FS_COPYFILE_FICLONE,
  COPYFILE_FICLONE_FORCE: binding.UV_FS_COPYFILE_FICLONE_FORCE,
  UV_FS_SYMLINK_DIR: binding.UV_FS_SYMLINK_DIR,
  UV_FS_SYMLINK_JUNCTION: binding.UV_FS_SYMLINK_JUNCTION
}
const os = require('bare-os')

module.exports = class FileError extends Error {
  constructor(msg, opts = {}) {
    const { code, operation = null, path = null, destination = null, fd = -1 } = opts

    if (operation !== null) msg += describe(operation, opts)

    super(`${code}: ${msg}`)

    this.code = code

    if (operation !== null) this.operation = operation
    if (path !== null) this.path = path
    if (destination !== null) this.destination = destination
    if (fd !== -1) this.fd = fd
  }

  get name() {
    return 'FileError'
  }

  // For Node.js compatibility
  get errno() {
    return os.constants.errnos[this.code]
  }

  // For Node.js compatibility
  get syscall() {
    return this.operation
  }

  // For Node.js compatibility
  get dest() {
    return this.destination
  }
}

function describe(operation, opts) {
  const { path = null, destination = null, fd = -1 } = opts

  let result = `, ${operation}`

  if (path !== null) {
    result += ` ${JSON.stringify(path)}`

    if (destination !== null) {
      result += ` -> ${JSON.stringify(destination)}`
    }
  } else if (fd !== -1) {
    result += ` ${fd}`
  }

  return result
}
{
  "name": "bare-fs",
  "version": "4.7.2",
  "description": "Native file system operations for Bare",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./promises": {
      "types": "./promises.d.ts",
      "default": "./promises.js"
    },
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "promises.js",
    "promises.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-fs.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-fs/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-fs#readme",
  "engines": {
    "bare": ">=1.16.0"
  },
  "dependencies": {
    "bare-events": "^2.5.4",
    "bare-path": "^3.0.0",
    "bare-stream": "^2.6.4",
    "bare-url": "^2.2.2",
    "fast-fifo": "^1.3.2"
  },
  "devDependencies": {
    "bare-buffer": "^3.0.2",
    "bare-crypto": "^1.11.2",
    "brittle": "^3.1.1",
    "cmake-bare": "^1.1.7",
    "lunte": "^1.6.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "bare-buffer": "*"
  },
  "peerDependenciesMeta": {
    "bare-buffer": {
      "optional": true
    }
  }
}
const EventEmitter = require('bare-events')
const fs = require('.')

class FileHandle extends EventEmitter {
  constructor(fd) {
    super()

    this.fd = fd
  }

  async close() {
    await fs.close(this.fd)

    this.fd = -1
    this.emit('close')
  }

  async read(buffer, ...args) {
    return {
      bytesRead: await fs.read(this.fd, buffer, ...args),
      buffer
    }
  }

  async readv(buffers, ...args) {
    return {
      bytesRead: await fs.readv(this.fd, buffers, ...args),
      buffers
    }
  }

  async write(buffer, ...args) {
    return {
      bytesWritten: await fs.write(this.fd, buffer, ...args),
      buffer
    }
  }

  async writev(buffers, ...args) {
    return {
      bytesWritten: await fs.writev(this.fd, buffers, ...args),
      buffers
    }
  }

  async stat() {
    return fs.fstat(this.fd)
  }

  async chmod(mode) {
    await fs.fchmod(this.fd, mode)
  }

  async chown(uid, gid) {
    await fs.fchown(this.fd, uid, gid)
  }

  async datasync() {
    return fs.fdatasync(this.fd)
  }

  async sync() {
    return fs.fsync(this.fd)
  }

  async truncate(len) {
    await fs.ftruncate(this.fd, len)
  }

  async utimes(atime, mtime) {
    await fs.futimes(this.fd, atime, mtime)
  }

  createReadStream(opts) {
    return fs.createReadStream(null, { ...opts, fd: this.fd })
  }

  createWriteStream(opts) {
    return fs.createWriteStream(null, { ...opts, fd: this.fd })
  }

  async [Symbol.asyncDispose]() {
    await this.close()
  }
}

exports.open = async function open(filepath, flags, mode) {
  return new FileHandle(await fs.open(filepath, flags, mode))
}

exports.access = fs.access
exports.appendFile = fs.appendFile
exports.chmod = fs.chmod
exports.chown = fs.chown
exports.constants = fs.constants
exports.copyFile = fs.copyFile
exports.cp = fs.cp
exports.lchown = fs.lchown
exports.lutimes = fs.lutimes
exports.link = fs.link
exports.lstat = fs.lstat
exports.mkdir = fs.mkdir
exports.mkdtemp = fs.mkdtemp
exports.opendir = fs.opendir
exports.readFile = fs.readFile
exports.readdir = fs.readdir
exports.readlink = fs.readlink
exports.realpath = fs.realpath
exports.rename = fs.rename
exports.rm = fs.rm
exports.rmdir = fs.rmdir
exports.stat = fs.stat
exports.statfs = fs.statfs
exports.truncate = fs.truncate
exports.symlink = fs.symlink
exports.unlink = fs.unlink
exports.utimes = fs.utimes
exports.watch = fs.watch
exports.writeFile = fs.writeFile
module.exports = require.addon()
const binding = require('./binding')

module.exports = exports = function hrtime(past) {
  let now = binding.hrtime()

  if (past) now -= BigInt(past[0]) * 1000000000n + BigInt(past[1])

  return [Number(now / 1000000000n), Number(now % 1000000000n)]
}

exports.bigint = function hrtime() {
  return binding.hrtime()
}
{
  "name": "bare-hrtime",
  "version": "2.1.1",
  "description": "High-resolution timers for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-hrtime.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-hrtime/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-hrtime#readme",
  "devDependencies": {
    "brittle": "^3.2.1",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  }
}
module.exports = require.addon()
const ansiEscapes = require('bare-ansi-escapes')
const getType = require('bare-type')
const binding = require('./binding')

const PLAIN_KEY = /^[a-zA-Z_][a-zA-Z_0-9]*$/

const defaultDepth = 2
const defaultBreakLength = 80
const defaultMaxArrayLength = 40

module.exports = exports = function inspect(value, opts = {}) {
  const {
    colors = false,
    depth = defaultDepth,
    breakLength = defaultBreakLength,
    stylize = defaultStylize(colors)
  } = opts

  const references = new InspectRefMap()

  const tree = inspectValue(value, 0, {
    colors,
    depth,
    breakLength,
    stylize,
    references
  })

  return tree.toString()
}

exports.styles = {
  bigint: ansiEscapes.colorYellow,
  boolean: ansiEscapes.colorYellow,
  date: ansiEscapes.colorMagenta,
  module: ansiEscapes.modifierUnderline,
  name: ansiEscapes.modifierReset,
  null: ansiEscapes.modifierBold,
  number: ansiEscapes.colorYellow,
  regexp: ansiEscapes.colorRed,
  special: ansiEscapes.colorCyan,
  string: ansiEscapes.colorGreen,
  symbol: ansiEscapes.colorGreen,
  undefined: ansiEscapes.colorBrightBlack
}

const styles = exports.styles

function defaultStylize(colors) {
  return function stylize(value, style) {
    const color = colors && styles[style]

    if (color) return color + value + ansiEscapes.modifierReset

    return value
  }
}

class InspectRefMap {
  constructor() {
    this.refs = new WeakMap()
    this.ids = new WeakMap()
    this.nextId = 1
  }

  has(object) {
    return this.refs.has(object)
  }

  get(object) {
    return this.refs.get(object) || null
  }

  set(object, ref) {
    this.refs.set(object, ref)
  }

  id(object) {
    let id = this.ids.get(object)
    if (id) return id

    id = this.nextId++
    this.ids.set(object, id)

    return id
  }
}

class InspectNode {
  constructor(depth, length, opts) {
    const { breakLength = defaultBreakLength, breakAlways = false } = opts

    this.depth = depth
    this.length = length
    this.breakLength = breakLength
    this.breakAlways = breakAlways
  }

  pad(n, string) {
    return string.padStart(n, ' ')
  }

  indent(n, string) {
    return '  '.repeat(n) + string
  }
}

class InspectRef extends InspectNode {
  constructor(depth, opts) {
    super(depth, '[circular *]'.length, opts)

    this.refs = opts.references
    this.count = 0
    this.circular = false
    this.color = opts.colors && styles.special
  }

  get id() {
    return this.refs.id(this)
  }

  increment() {
    return ++this.count
  }

  decrement() {
    return --this.count
  }

  toString(opts = {}) {
    const { offset = 0, pad = 0, indent = 0 } = opts

    let value = this.pad(pad, '[circular *' + this.id + ']')

    if (this.color) value = this.color + value + ansiEscapes.modifierReset

    return offset ? value : this.indent(indent, value)
  }
}

class InspectLeaf extends InspectNode {
  constructor(value, color, depth, opts) {
    const length = value.length

    if (value.includes('\n')) {
      value = value.replaceAll('\n', '\n' + '  '.repeat(depth))

      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.value = value
    this.color = opts.colors && color
  }

  toString(opts = {}) {
    const { offset = 0, pad = 0, indent = 0 } = opts

    let value = this.pad(pad, this.value)

    if (this.color) value = this.color + value + ansiEscapes.modifierReset

    return offset ? value : this.indent(indent, value)
  }
}

class InspectPair extends InspectNode {
  constructor(delim, left, right, depth, opts) {
    const length = left.length + delim.length + right.length

    if (left.breakAlways || right.breakAlways) {
      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.delim = delim
    this.left = left
    this.right = right
  }

  toString(opts = {}) {
    const { indent = 0 } = opts

    return this.indent(
      indent,
      this.left +
        this.delim +
        this.right.toString({
          indent,
          offset: this.left.length + this.delim.length
        })
    )
  }
}

class InspectSuspension extends InspectNode {
  constructor(overflow, depth, opts) {
    const label = `... ${overflow} more`

    super(depth, label.length, opts)

    this.label = label
  }

  toString(opts = {}) {
    const { indent = 0 } = opts

    return this.indent(indent, this.label)
  }
}

class InspectSequence extends InspectNode {
  constructor(header, footer, delim, values, ref, depth, opts) {
    const { tabulate = false } = opts

    const length =
      (ref.circular ? '<ref *>'.length + 1 : 0) +
      header.length +
      values.reduce(
        (length, value, i) =>
          length + value.length + (i === 0 ? 0 : delim.length),
        0
      ) +
      footer.length

    if (values.some((value) => value.breakAlways)) {
      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.header = header
    this.footer = footer
    this.delim = delim
    this.values = values
    this.ref = ref
    this.tabulate = tabulate
  }

  toString(opts = {}) {
    const { offset = 0, indent = 0 } = opts

    const split =
      this.breakAlways ||
      (this.values.length &&
        (offset + this.length > this.breakLength ||
          indent * 2 + this.length > this.breakLength))

    let header = this.header

    if (this.ref.circular) {
      header = '<ref *' + this.ref.id + '> ' + header
    }

    if (this.values.length === 0) {
      header = header.trimEnd()
    }

    if (offset === 0) {
      header = this.indent(indent, header)
    }

    if (split) {
      header = header.trimEnd() + '\n'
    }

    let string = header

    let columns = 1
    let pad = 0

    if (this.tabulate) {
      const widest = this.values.reduce(
        (length, value) =>
          value.breakAlways ? length : Math.max(length, value.length),
        0
      )

      if (widest) {
        columns = Math.max(
          columns,
          Math.floor(
            (this.breakLength - indent * 2) / (widest + this.delim.length)
          )
        )

        if (columns > 1) pad = widest
      }
    }

    for (let i = 0, n = this.values.length, offset = 0; i < n; i++) {
      const value = this.values[i]

      if (split) {
        let part

        if (i % columns === 0 || value.breakAlways) {
          part = value.toString({ indent: indent + 1, pad })
        } else {
          part = value.toString({ pad })
        }

        string += part

        if (i < n - 1) {
          if (i % columns === columns - 1 || this.values[i + 1].breakAlways) {
            string += this.delim.trimEnd() + '\n'
          } else {
            string += this.delim
          }
        }
      } else {
        if (i > 0) string += this.delim

        string += value.toString({ offset })

        offset += value.length
      }
    }

    let footer = this.footer

    if (this.values.length === 0) {
      footer = footer.trimStart()
    }

    if (split) {
      string += '\n' + this.indent(indent, footer.trimStart())
    } else {
      string += footer
    }

    return string
  }
}

function inspectValue(value, depth, opts) {
  const type = getType(value)

  if (type.isUndefined()) return inspectUndefined(depth, opts)
  if (type.isNull()) return inspectNull(depth, opts)
  if (type.isBoolean()) return inspectBoolean(value, depth, opts)
  if (type.isNumber()) return inspectNumber(value, depth, opts)
  if (type.isBigInt()) return inspectBigInt(value, depth, opts)
  if (type.isString()) return inspectString(value, depth, opts)
  if (type.isSymbol()) return inspectSymbol(value, depth, opts)
  if (type.isObject()) return inspectObject(type, value, depth, opts)
  if (type.isFunction()) return inspectFunction(type, value, depth, opts)
  if (type.isExternal()) return inspectExternal(value, opts, opts)
}

function inspectUndefined(depth, opts) {
  return new InspectLeaf('undefined', styles.undefined, depth, opts)
}

function inspectNull(depth, opts) {
  return new InspectLeaf('null', styles.null, depth, opts)
}

function inspectBoolean(value, depth, opts) {
  return new InspectLeaf(value.toString(), styles.boolean, depth, opts)
}

function inspectNumber(value, depth, opts) {
  let string

  if (Object.is(value, -0)) {
    string = '-0'
  } else {
    string = value.toString(10)
  }

  return new InspectLeaf(string, styles.number, depth, opts)
}

function inspectBigInt(value, depth, opts) {
  return new InspectLeaf(value.toString(10) + 'n', styles.bigint, depth, opts)
}

const STRING_ESCAPES =
  /[\ud800-\udbff][\udc00-\udfff]|[\u0000-\u001f'\\\ud800-\udfff]/g

function inspectString(value, depth, opts) {
  // https://tc39.es/ecma262/multipage/structured-data.html#sec-quotejsonstring
  const string = value.replace(STRING_ESCAPES, (match) => {
    if (match.length === 2) return match

    switch (match) {
      case "'":
        return "\\'"
      case '\\':
        return '\\\\'
      case '\b':
        return '\\b'
      case '\t':
        return '\\t'
      case '\n':
        return '\\n'
      case '\f':
        return '\\f'
      case '\r':
        return '\\r'
      default:
        return '\\u' + match.charCodeAt(0).toString(16).padStart(4, '0')
    }
  })

  return new InspectLeaf("'" + string + "'", styles.string, depth, opts)
}

function inspectSymbol(value, depth, opts) {
  return new InspectLeaf(value.toString(), styles.symbol, depth, opts)
}

function inspectKey(value, depth, opts) {
  if (PLAIN_KEY.test(value)) {
    return new InspectLeaf(value, null, depth, opts)
  } else {
    return inspectValue(value, depth, opts)
  }
}

function inspectObject(type, object, depth, opts) {
  const refs = opts.references

  let ref = refs.get(object)
  if (ref === null) {
    ref = new InspectRef(depth, opts)
    refs.set(object, ref)
  } else if (ref.count) {
    ref.circular = true
    return ref
  }

  const maxDepth = typeof opts.depth === 'number' ? opts.depth : Infinity

  if (maxDepth < depth) {
    const constructor = object.constructor

    return new InspectLeaf(
      '[' +
        (constructor && constructor.name ? constructor.name : 'Object') +
        ']',
      styles.special,
      depth,
      opts
    )
  }

  const inspect =
    object[Symbol.for('bare.inspect')] ||
    object[Symbol.for('nodejs.util.inspect.custom')]

  if (typeof inspect === 'function') {
    const value = inspect.call(
      object,
      typeof opts.depth === 'number' ? opts.depth - depth : null,
      {
        colors: opts.colors,
        breakLength: opts.breakLength,
        stylize: opts.stylize
      },
      exports
    )

    if (typeof value === 'object' && value !== null) {
      refs.set(value, ref)
    }

    if (typeof value !== 'string') {
      return inspectValue(value, depth, opts)
    }

    return new InspectLeaf(value, null, depth, opts)
  }

  if (type.isArray()) return inspectArray(object, ref, depth, opts)
  if (type.isDate()) return inspectDate(object, ref, depth, opts)
  if (type.isRegExp()) return inspectRegExp(object, ref, depth, opts)
  if (type.isError()) return inspectError(object, ref, depth, opts)
  if (type.isPromise()) return inspectPromise(object, ref, depth, opts)
  if (type.isMap()) return inspectMap(object, ref, depth, opts)
  if (type.isSet()) return inspectSet(object, ref, depth, opts)
  if (type.isWeakMap()) return inspectWeakMap(object, ref, depth, opts)
  if (type.isWeakSet()) return inspectWeakSet(object, ref, depth, opts)
  if (type.isWeakRef()) return inspectWeakRef(object, ref, depth, opts)
  if (type.isArrayBuffer()) return inspectArrayBuffer(object, ref, depth, opts)
  if (type.isSharedArrayBuffer())
    return inspectSharedArrayBuffer(object, ref, depth, opts)
  if (type.isTypedArray()) return inspectTypedArray(object, ref, depth, opts)
  if (type.isDataView()) return inspectDataView(object, ref, depth, opts)

  ref.increment()

  const values = []

  for (const key in object) {
    if (key === 'constructor') continue

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(object[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  let header = '{ '

  const tag = object[Symbol.toStringTag]

  if (tag) header = '[' + tag + '] ' + header

  if (object.constructor) {
    const name = object.constructor.name

    if (name && name !== 'Object') {
      header = object.constructor.name + ' ' + header
    }
  }

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectArray(array, ref, depth, opts) {
  const { maxArrayLength = defaultMaxArrayLength } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxArrayLength, 0)

  for (let i = 0, n = array.length; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(array.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(inspectValue(array[i], depth + 1, opts))
  }

  for (const key of binding.getOwnNonIndexPropertyNames(array)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(array[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  let header = '[ '

  if (array.constructor.name !== 'Array') {
    header = array.constructor.name + '(' + array.length + ') ' + header
  }

  return new InspectSequence(header, ' ]', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectDate(date, ref, depth, opts) {
  return new InspectLeaf(date.toISOString(), styles.date, depth, opts)
}

function inspectRegExp(regExp, ref, depth, opts) {
  return new InspectLeaf(regExp.toString(), styles.regexp, depth, opts)
}

function inspectError(error, ref, depth, opts) {
  let header

  if ('stack' in error) {
    header = error.stack

    if (depth > 0) {
      header = header.replaceAll('\n', '\n' + '  '.repeat(depth))
    }
  } else {
    header = error.toString()
  }

  const builtins = ['cause']

  if (error.name === 'AggregateError') {
    builtins.push('errors')
  } else if (error.name === 'SuppressedError') {
    builtins.push('error', 'suppressed')
  }

  const values = []

  for (const key of builtins) {
    if (key in error === false) continue

    values.push(
      new InspectPair(
        ': ',
        new InspectLeaf('[' + key + ']', null, depth + 1, opts),
        inspectValue(error[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key in error) {
    if (key === 'constructor' || builtins.includes(key)) continue

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(error[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  if (values.length === 0) return new InspectLeaf(header, null, depth, opts)

  return new InspectSequence(
    header + ' {',
    ' }',
    ', ',
    values,
    ref,
    depth,
    opts
  )
}

function inspectPromise(promise, ref, depth, opts) {
  ref.increment()

  const state = binding.getPromiseState(promise)

  const values = []

  switch (state) {
    case 0: // Pending
      values.push(new InspectLeaf('<pending>', styles.special, depth, opts))
      break

    case 1: // Fulfilled
      values.push(inspectValue(binding.getPromiseResult(promise), depth, opts))
      break

    case 2: // Rejected
      values.push(
        new InspectLeaf('<rejected>', styles.special, depth, opts),
        inspectValue(binding.getPromiseResult(promise), depth, opts)
      )
  }

  ref.decrement()

  const header = promise.constructor.name + ' { '

  return new InspectSequence(header, ' }', ' ', values, ref, depth, opts)
}

function inspectMap(map, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxMapLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = maxMapLength

  for (const entry of map) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(map.size - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )
      break
    }

    values.push(
      new InspectPair(
        ' => ',
        inspectValue(entry[0], depth + 1, opts),
        inspectValue(entry[1], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key in map) {
    if (key === 'constructor') continue

    const value = inspectValue(map[key], depth + 1, opts)

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        value,
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = map.constructor.name + '(' + map.size + ') { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectSet(set, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxSetLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = maxSetLength

  for (const entry of set) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(set.size - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )
      break
    }

    values.push(inspectValue(entry, depth + 1, opts))
  }

  for (const key in set) {
    if (key === 'constructor') continue

    const value = inspectValue(set[key], depth + 1, opts)

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        value,
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = set.constructor.name + '(' + set.size + ') { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectWeakMap(weakMap, ref, depth, opts) {
  const header = weakMap.constructor.name + ' { '

  return new InspectSequence(
    header,
    ' }',
    ' ',
    [new InspectLeaf('<items unknown>', styles.special, depth + 1, opts)],
    ref,
    depth,
    opts
  )
}

function inspectWeakSet(weakSet, ref, depth, opts) {
  const header = weakSet.constructor.name + ' { '

  return new InspectSequence(
    header,
    ' }',
    ' ',
    [new InspectLeaf('<items unknown>', styles.special, depth + 1, opts)],
    ref,
    depth,
    opts
  )
}

function inspectWeakRef(weakRef, ref, depth, opts) {
  const target = weakRef.deref()

  let value

  if (target === undefined) {
    value = new InspectLeaf('<cleared>', styles.special, depth + 1, opts)
  } else {
    value = inspectValue(target, depth + 1, opts)
  }

  const header = weakRef.constructor.name + ' { '

  return new InspectSequence(header, ' }', ' ', [value], ref, depth, opts)
}

function inspectArrayBuffer(arrayBuffer, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(arrayBuffer[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = arrayBuffer.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectSharedArrayBuffer(sharedArrayBuffer, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(sharedArrayBuffer[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = sharedArrayBuffer.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectTypedArray(typedArray, ref, depth, opts) {
  if (Buffer.isBuffer(typedArray)) {
    return inspectBuffer(typedArray, ref, depth, opts)
  }

  const {
    maxArrayLength = defaultMaxArrayLength,
    maxTypedArrayLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxTypedArrayLength, 0)

  for (let i = 0, n = typedArray.length; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(typedArray.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(inspectValue(typedArray[i], depth + 1, opts))
  }

  for (const key of binding.getOwnNonIndexPropertyNames(typedArray)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(typedArray[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = typedArray.constructor.name + '(' + typedArray.length + ') [ '

  return new InspectSequence(header, ' ]', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectBuffer(buffer, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxBufferLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxBufferLength, 0)

  for (let i = 0, n = buffer.byteLength; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(buffer.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(
      new InspectLeaf(
        buffer[i].toString(16).padStart(2, '0'),
        null,
        depth + 1,
        opts
      )
    )
  }

  for (const key of binding.getOwnNonIndexPropertyNames(buffer)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(buffer[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  return new InspectSequence('<Buffer ', '>', ' ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectDataView(dataView, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength', 'byteOffset', 'buffer']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(dataView[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key of binding.getOwnNonIndexPropertyNames(dataView)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(dataView[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = dataView.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectFunction(type, fn, depth, opts) {
  if (fn.toString().startsWith('class')) return inspectClass(fn, depth, opts)

  let tag = 'function'

  if (type.isGeneratorFunction()) tag = 'generator ' + tag
  if (type.isAsyncFunction()) tag = 'async ' + tag

  return new InspectLeaf(
    '[' + tag + ' ' + (fn.name ? fn.name : '(anonymous)') + ']',
    styles.special,
    depth,
    opts
  )
}

function inspectClass(ctor, depth, opts) {
  return new InspectLeaf(
    '[class ' + (ctor.name ? ctor.name : '(anonymous)') + ']',
    styles.special,
    depth,
    opts
  )
}

function inspectExternal(external, depth, opts) {
  return new InspectLeaf(
    '[external 0x' + binding.getExternal(external).toString(16) + ']',
    styles.special,
    depth,
    opts
  )
}
{
  "name": "bare-inspect",
  "version": "3.1.4",
  "description": "Inspect objects as strings for debugging",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-inspect.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-inspect/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-inspect#readme",
  "engines": {
    "bare": ">=1.18.0"
  },
  "dependencies": {
    "bare-ansi-escapes": "^2.1.0",
    "bare-type": "^1.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
module.exports = require.addon()
const binding = require('./binding')
const errors = require('./lib/errors')
const constants = require('./lib/constants')

exports.constants = constants
exports.errors = errors

exports.EOL = binding.platform === 'win32' ? '\r\n' : '\n'

exports.devNull = binding.platform === 'win32' ? '\\\\.\\nul' : '/dev/null'

exports.platform = function platform() {
  return binding.platform
}

exports.arch = function arch() {
  return binding.arch
}

exports.type = binding.type
exports.version = binding.version
exports.release = binding.release
exports.machine = binding.machine
exports.execPath = binding.execPath
exports.pid = binding.pid
exports.ppid = binding.ppid
exports.cwd = binding.cwd
exports.chdir = binding.chdir
exports.tmpdir = binding.tmpdir
exports.homedir = binding.homedir
exports.hostname = binding.hostname
exports.userInfo = binding.userInfo
exports.groupInfo = binding.groupInfo

exports.networkInterfaces = function networkInterfaces() {
  const result = {}

  for (const entry of binding.networkInterfaces()) {
    const { name, ...properties } = entry

    if (result[name]) result[name].push(properties)
    else result[name] = [properties]
  }

  return result
}

exports.kill = function kill(pid, signal = constants.signals.SIGTERM) {
  if (typeof signal === 'string') {
    if (signal in constants.signals === false) {
      throw errors.UNKNOWN_SIGNAL('Unknown signal: ' + signal)
    }

    signal = constants.signals[signal]
  }

  binding.kill(pid, signal)
}

exports.endianness = function endianness() {
  return binding.isLittleEndian ? 'LE' : 'BE'
}

exports.availableParallelism = binding.availableParallelism

exports.cpuUsage = function cpuUsage(previous) {
  const current = binding.cpuUsage()

  if (previous) {
    return {
      user: current.user - previous.user,
      system: current.system - previous.system
    }
  }

  return current
}

exports.threadCpuUsage = function threadCpuUsage(previous) {
  const current = binding.threadCpuUsage()

  if (previous) {
    return {
      user: current.user - previous.user,
      system: current.system - previous.system
    }
  }

  return current
}

exports.resourceUsage = binding.resourceUsage
exports.memoryUsage = binding.memoryUsage
exports.freemem = binding.freemem
exports.totalmem = binding.totalmem
exports.availableMemory = binding.availableMemory
exports.constrainedMemory = binding.constrainedMemory
exports.uptime = binding.uptime
exports.loadavg = binding.loadavg
exports.cpus = binding.cpus

exports.getProcessTitle = binding.getProcessTitle

exports.setProcessTitle = function setProcessTitle(title) {
  if (typeof title !== 'string') title = title.toString()

  if (title.length >= 256) {
    throw errors.TITLE_OVERFLOW('Process title is too long')
  }

  binding.setProcessTitle(title)
}

exports.getPriority = function getPriority(pid = 0) {
  return binding.getPriority(pid)
}

exports.setPriority = function setPriority(pid, priority) {
  if (priority === undefined) {
    priority = pid
    pid = 0
  }

  binding.setPriority(pid, priority)
}

exports.getEnvKeys = binding.getEnvKeys
exports.getEnv = binding.getEnv
exports.hasEnv = binding.hasEnv
exports.setEnv = binding.setEnv
exports.unsetEnv = binding.unsetEnv
const binding = require('../binding')

module.exports = {
  signals: binding.signals,
  errnos: binding.errnos,
  priority: binding.priority
}
module.exports = class OSError extends Error {
  constructor(msg, fn = OSError, code = fn.name) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'OSError'
  }

  static UNKNOWN_SIGNAL(msg) {
    return new OSError(msg, OSError.UNKNOWN_SIGNAL)
  }

  static TITLE_OVERFLOW(msg) {
    return new OSError(msg, OSError.TITLE_OVERFLOW)
  }
}
{
  "name": "bare-os",
  "version": "3.9.1",
  "description": "Operating system utilities for Bare",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    },
    "./errors": {
      "types": "./lib/errors.d.ts",
      "default": "./lib/errors.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-os.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-os/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-os#readme",
  "engines": {
    "bare": ">=1.14.0"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "cmake-bare": "^1.1.6",
    "lunte": "^1.6.0",
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
// This export SHOULD NOT be shortened in any way as having the full
// `module.exports = require(...)` statement is crucial for synthesizing
// ESM exports.

if (Bare.platform === 'win32') {
  module.exports = require('./lib/win32')
} else {
  module.exports = require('./lib/posix')
}
module.exports = {
  CHAR_UPPERCASE_A: 0x41,
  CHAR_LOWERCASE_A: 0x61,
  CHAR_UPPERCASE_Z: 0x5a,
  CHAR_LOWERCASE_Z: 0x7a,
  CHAR_DOT: 0x2e,
  CHAR_FORWARD_SLASH: 0x2f,
  CHAR_BACKWARD_SLASH: 0x5c,
  CHAR_COLON: 0x3a,
  CHAR_QUESTION_MARK: 0x3f
}
const os = require('bare-os')

const { normalizeString } = require('./shared')
const { CHAR_DOT, CHAR_FORWARD_SLASH } = require('./constants')

function isPosixPathSeparator(code) {
  return code === CHAR_FORWARD_SLASH
}

exports.win32 = require('./win32')
exports.posix = exports

exports.sep = '/'
exports.delimiter = ':'

exports.resolve = function resolve(...args) {
  let resolvedPath = ''
  let resolvedAbsolute = false

  for (let i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) {
    const path = i >= 0 ? args[i] : os.cwd()

    if (path.length === 0) {
      continue
    }

    resolvedPath = `${path}/${resolvedPath}`
    resolvedAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH
  }

  resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute, '/', isPosixPathSeparator)

  if (resolvedAbsolute) {
    return `/${resolvedPath}`
  }

  return resolvedPath.length > 0 ? resolvedPath : '.'
}

exports.normalize = function normalize(path) {
  if (path.length === 0) return '.'

  const isAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH
  const trailingSeparator = path.charCodeAt(path.length - 1) === CHAR_FORWARD_SLASH

  path = normalizeString(path, !isAbsolute, '/', isPosixPathSeparator)

  if (path.length === 0) {
    if (isAbsolute) return '/'
    return trailingSeparator ? './' : '.'
  }

  if (trailingSeparator) path += '/'

  return isAbsolute ? `/${path}` : path
}

exports.isAbsolute = function isAbsolute(path) {
  return path.length > 0 && path.charCodeAt(0) === CHAR_FORWARD_SLASH
}

exports.join = function join(...args) {
  if (args.length === 0) return '.'
  let joined
  for (let i = 0; i < args.length; ++i) {
    const arg = args[i]
    if (arg.length > 0) {
      if (joined === undefined) joined = arg
      else joined += `/${arg}`
    }
  }
  if (joined === undefined) return '.'
  return exports.normalize(joined)
}

exports.relative = function relative(from, to) {
  if (from === to) return ''

  from = exports.resolve(from)
  to = exports.resolve(to)

  if (from === to) return ''

  const fromStart = 1
  const fromEnd = from.length
  const fromLen = fromEnd - fromStart
  const toStart = 1
  const toLen = to.length - toStart

  const length = fromLen < toLen ? fromLen : toLen
  let lastCommonSep = -1
  let i = 0
  for (; i < length; i++) {
    const fromCode = from.charCodeAt(fromStart + i)
    if (fromCode !== to.charCodeAt(toStart + i)) {
      break
    } else if (fromCode === CHAR_FORWARD_SLASH) {
      lastCommonSep = i
    }
  }
  if (i === length) {
    if (toLen > length) {
      if (to.charCodeAt(toStart + i) === CHAR_FORWARD_SLASH) {
        return to.substring(toStart + i + 1)
      }
      if (i === 0) {
        return to.substring(toStart + i)
      }
    } else if (fromLen > length) {
      if (from.charCodeAt(fromStart + i) === CHAR_FORWARD_SLASH) {
        lastCommonSep = i
      } else if (i === 0) {
        lastCommonSep = 0
      }
    }
  }

  let out = ''
  for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
    if (i === fromEnd || from.charCodeAt(i) === CHAR_FORWARD_SLASH) {
      out += out.length === 0 ? '..' : '/..'
    }
  }

  return `${out}${to.substring(toStart + lastCommonSep)}`
}

exports.toNamespacedPath = function toNamespacedPath(path) {
  return path
}

exports.dirname = function dirname(path) {
  if (path.length === 0) return '.'
  const hasRoot = path.charCodeAt(0) === CHAR_FORWARD_SLASH
  let end = -1
  let matchedSlash = true
  for (let i = path.length - 1; i >= 1; --i) {
    if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) {
      if (!matchedSlash) {
        end = i
        break
      }
    } else {
      matchedSlash = false
    }
  }

  if (end === -1) return hasRoot ? '/' : '.'
  if (hasRoot && end === 1) return '//'
  return path.substring(0, end)
}

exports.basename = function basename(path, suffix) {
  let start = 0
  let end = -1
  let matchedSlash = true

  if (suffix !== undefined && suffix.length > 0 && suffix.length <= path.length) {
    if (suffix === path) {
      return ''
    }
    let extIdx = suffix.length - 1
    let firstNonSlashEnd = -1
    for (let i = path.length - 1; i >= 0; --i) {
      const code = path.charCodeAt(i)
      if (code === CHAR_FORWARD_SLASH) {
        if (!matchedSlash) {
          start = i + 1
          break
        }
      } else {
        if (firstNonSlashEnd === -1) {
          matchedSlash = false
          firstNonSlashEnd = i + 1
        }
        if (extIdx >= 0) {
          if (code === suffix.charCodeAt(extIdx)) {
            if (--extIdx === -1) {
              end = i
            }
          } else {
            extIdx = -1
            end = firstNonSlashEnd
          }
        }
      }
    }

    if (start === end) end = firstNonSlashEnd
    else if (end === -1) end = path.length
    return path.substring(start, end)
  }

  for (let i = path.length - 1; i >= 0; --i) {
    if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) {
      if (!matchedSlash) {
        start = i + 1
        break
      }
    } else if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
  }

  if (end === -1) return ''
  return path.substring(start, end)
}

exports.extname = function extname(path) {
  let startDot = -1
  let startPart = 0
  let end = -1
  let matchedSlash = true
  let preDotState = 0
  for (let i = path.length - 1; i >= 0; --i) {
    const code = path.charCodeAt(i)
    if (code === CHAR_FORWARD_SLASH) {
      if (!matchedSlash) {
        startPart = i + 1
        break
      }
      continue
    }
    if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
    if (code === CHAR_DOT) {
      if (startDot === -1) startDot = i
      else if (preDotState !== 1) preDotState = 1
    } else if (startDot !== -1) {
      preDotState = -1
    }
  }

  if (
    startDot === -1 ||
    end === -1 ||
    preDotState === 0 ||
    (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1)
  ) {
    return ''
  }
  return path.substring(startDot, end)
}
const { CHAR_DOT, CHAR_FORWARD_SLASH } = require('./constants')

exports.normalizeString = function normalizeString(
  path,
  allowAboveRoot,
  separator,
  isPathSeparator
) {
  let res = ''
  let lastSegmentLength = 0
  let lastSlash = -1
  let dots = 0
  let code = 0
  for (let i = 0; i <= path.length; ++i) {
    if (i < path.length) {
      code = path.charCodeAt(i)
    } else if (isPathSeparator(code)) {
      break
    } else {
      code = CHAR_FORWARD_SLASH
    }

    if (isPathSeparator(code)) {
      if (lastSlash === i - 1 || dots === 1);
      else if (dots === 2) {
        if (
          res.length < 2 ||
          lastSegmentLength !== 2 ||
          res.charCodeAt(res.length - 1) !== CHAR_DOT ||
          res.charCodeAt(res.length - 2) !== CHAR_DOT
        ) {
          if (res.length > 2) {
            const lastSlashIndex = res.lastIndexOf(separator)
            if (lastSlashIndex === -1) {
              res = ''
              lastSegmentLength = 0
            } else {
              res = res.substring(0, lastSlashIndex)
              lastSegmentLength = res.length - 1 - res.lastIndexOf(separator)
            }
            lastSlash = i
            dots = 0
            continue
          } else if (res.length !== 0) {
            res = ''
            lastSegmentLength = 0
            lastSlash = i
            dots = 0
            continue
          }
        }
        if (allowAboveRoot) {
          res += res.length > 0 ? `${separator}..` : '..'
          lastSegmentLength = 2
        }
      } else {
        if (res.length > 0) {
          res += `${separator}${path.substring(lastSlash + 1, i)}`
        } else {
          res = path.substring(lastSlash + 1, i)
        }
        lastSegmentLength = i - lastSlash - 1
      }
      lastSlash = i
      dots = 0
    } else if (code === CHAR_DOT && dots !== -1) {
      ++dots
    } else {
      dots = -1
    }
  }
  return res
}
const os = require('bare-os')

const { normalizeString } = require('./shared')
const {
  CHAR_UPPERCASE_A,
  CHAR_LOWERCASE_A,
  CHAR_UPPERCASE_Z,
  CHAR_LOWERCASE_Z,
  CHAR_DOT,
  CHAR_FORWARD_SLASH,
  CHAR_BACKWARD_SLASH,
  CHAR_COLON,
  CHAR_QUESTION_MARK
} = require('./constants')

function isWindowsPathSeparator(code) {
  return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH
}

function isWindowsDeviceRoot(code) {
  return (
    (code >= CHAR_UPPERCASE_A && code <= CHAR_UPPERCASE_Z) ||
    (code >= CHAR_LOWERCASE_A && code <= CHAR_LOWERCASE_Z)
  )
}

exports.posix = require('./posix')
exports.win32 = exports

exports.sep = '\\'
exports.delimiter = ';'

exports.resolve = function resolve(...args) {
  let resolvedDevice = ''
  let resolvedTail = ''
  let resolvedAbsolute = false

  for (let i = args.length - 1; i >= -1; i--) {
    let path
    if (i >= 0) {
      path = args[i]

      if (path.length === 0) continue
    } else if (resolvedDevice.length === 0) {
      path = os.cwd()
    } else {
      path = os.getEnv(`=${resolvedDevice}`) || os.cwd()

      if (
        path === undefined ||
        (path.substring(0, 2).toLowerCase() !== resolvedDevice.toLowerCase() &&
          path.charCodeAt(2) === CHAR_BACKWARD_SLASH)
      ) {
        path = `${resolvedDevice}\\`
      }
    }

    const len = path.length
    let rootEnd = 0
    let device = ''
    let isAbsolute = false
    const code = path.charCodeAt(0)

    if (len === 1) {
      if (isWindowsPathSeparator(code)) {
        rootEnd = 1
        isAbsolute = true
      }
    } else if (isWindowsPathSeparator(code)) {
      isAbsolute = true

      if (isWindowsPathSeparator(path.charCodeAt(1))) {
        let j = 2
        let last = j
        while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
          j++
        }
        if (j < len && j !== last) {
          const firstPart = path.substring(last, j)
          last = j
          while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
            j++
          }
          if (j < len && j !== last) {
            last = j
            while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
              j++
            }
            if (j === len || j !== last) {
              device = `\\\\${firstPart}\\${path.substring(last, j)}`
              rootEnd = j
            }
          }
        }
      } else {
        rootEnd = 1
      }
    } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
      device = path.substring(0, 2)
      rootEnd = 2
      if (len > 2 && isWindowsPathSeparator(path.charCodeAt(2))) {
        isAbsolute = true
        rootEnd = 3
      }
    }

    if (device.length > 0) {
      if (resolvedDevice.length > 0) {
        if (device.toLowerCase() !== resolvedDevice.toLowerCase()) {
          continue
        }
      } else {
        resolvedDevice = device
      }
    }

    if (resolvedAbsolute) {
      if (resolvedDevice.length > 0) {
        break
      }
    } else {
      resolvedTail = `${path.substring(rootEnd)}\\${resolvedTail}`
      resolvedAbsolute = isAbsolute
      if (isAbsolute && resolvedDevice.length > 0) {
        break
      }
    }
  }

  resolvedTail = normalizeString(resolvedTail, !resolvedAbsolute, '\\', isWindowsPathSeparator)

  return resolvedAbsolute
    ? `${resolvedDevice}\\${resolvedTail}`
    : `${resolvedDevice}${resolvedTail}` || '.'
}

exports.normalize = function normalize(path) {
  const len = path.length
  if (len === 0) return '.'
  let rootEnd = 0
  let device
  let isAbsolute = false
  const code = path.charCodeAt(0)

  if (len === 1) {
    return code === CHAR_FORWARD_SLASH ? '\\' : path
  }

  if (isWindowsPathSeparator(code)) {
    isAbsolute = true

    if (isWindowsPathSeparator(path.charCodeAt(1))) {
      let j = 2
      let last = j
      while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
        j++
      }
      if (j < len && j !== last) {
        const firstPart = path.substring(last, j)
        last = j
        while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
          j++
        }
        if (j < len && j !== last) {
          last = j
          while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
            j++
          }
          if (j === len) {
            return `\\\\${firstPart}\\${path.substring(last)}\\`
          }
          if (j !== last) {
            device = `\\\\${firstPart}\\${path.substring(last, j)}`
            rootEnd = j
          }
        }
      }
    } else {
      rootEnd = 1
    }
  } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
    device = path.substring(0, 2)
    rootEnd = 2
    if (len > 2 && isWindowsPathSeparator(path.charCodeAt(2))) {
      isAbsolute = true
      rootEnd = 3
    }
  }

  let tail =
    rootEnd < len
      ? normalizeString(path.substring(rootEnd), !isAbsolute, '\\', isWindowsPathSeparator)
      : ''
  if (tail.length === 0 && !isAbsolute) {
    tail = '.'
  }
  if (tail.length > 0 && isWindowsPathSeparator(path.charCodeAt(len - 1))) {
    tail += '\\'
  }
  if (device === undefined) {
    return isAbsolute ? `\\${tail}` : tail
  }
  return isAbsolute ? `${device}\\${tail}` : `${device}${tail}`
}

exports.isAbsolute = function isAbsolute(path) {
  const len = path.length
  if (len === 0) return false

  const code = path.charCodeAt(0)

  return (
    isWindowsPathSeparator(code) ||
    (len > 2 &&
      isWindowsDeviceRoot(code) &&
      path.charCodeAt(1) === CHAR_COLON &&
      isWindowsPathSeparator(path.charCodeAt(2)))
  )
}

exports.join = function join(...args) {
  if (args.length === 0) return '.'

  let joined
  let firstPart
  for (let i = 0; i < args.length; ++i) {
    const arg = args[i]
    if (arg.length > 0) {
      if (joined === undefined) joined = firstPart = arg
      else joined += `\\${arg}`
    }
  }

  if (joined === undefined) return '.'

  let needsReplace = true
  let slashCount = 0
  if (isWindowsPathSeparator(firstPart.charCodeAt(0))) {
    ++slashCount
    const firstLen = firstPart.length
    if (firstLen > 1 && isWindowsPathSeparator(firstPart.charCodeAt(1))) {
      ++slashCount
      if (firstLen > 2) {
        if (isWindowsPathSeparator(firstPart.charCodeAt(2))) {
          ++slashCount
        } else {
          needsReplace = false
        }
      }
    }
  }
  if (needsReplace) {
    while (slashCount < joined.length && isWindowsPathSeparator(joined.charCodeAt(slashCount))) {
      slashCount++
    }

    if (slashCount >= 2) {
      joined = `\\${joined.substring(slashCount)}`
    }
  }

  return exports.normalize(joined)
}

exports.relative = function relative(from, to) {
  if (from === to) return ''

  const fromOrig = exports.resolve(from)
  const toOrig = exports.resolve(to)

  if (fromOrig === toOrig) return ''

  from = fromOrig.toLowerCase()
  to = toOrig.toLowerCase()

  if (from === to) return ''

  let fromStart = 0
  while (fromStart < from.length && from.charCodeAt(fromStart) === CHAR_BACKWARD_SLASH) {
    fromStart++
  }
  let fromEnd = from.length
  while (fromEnd - 1 > fromStart && from.charCodeAt(fromEnd - 1) === CHAR_BACKWARD_SLASH) {
    fromEnd--
  }
  const fromLen = fromEnd - fromStart

  let toStart = 0
  while (toStart < to.length && to.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) {
    toStart++
  }
  let toEnd = to.length
  while (toEnd - 1 > toStart && to.charCodeAt(toEnd - 1) === CHAR_BACKWARD_SLASH) {
    toEnd--
  }
  const toLen = toEnd - toStart

  const length = fromLen < toLen ? fromLen : toLen
  let lastCommonSep = -1
  let i = 0
  for (; i < length; i++) {
    const fromCode = from.charCodeAt(fromStart + i)
    if (fromCode !== to.charCodeAt(toStart + i)) {
      break
    } else if (fromCode === CHAR_BACKWARD_SLASH) {
      lastCommonSep = i
    }
  }

  if (i !== length) {
    if (lastCommonSep === -1) return toOrig
  } else {
    if (toLen > length) {
      if (to.charCodeAt(toStart + i) === CHAR_BACKWARD_SLASH) {
        return toOrig.substring(toStart + i + 1)
      }
      if (i === 2) {
        return toOrig.substring(toStart + i)
      }
    }
    if (fromLen > length) {
      if (from.charCodeAt(fromStart + i) === CHAR_BACKWARD_SLASH) {
        lastCommonSep = i
      } else if (i === 2) {
        lastCommonSep = 3
      }
    }
    if (lastCommonSep === -1) lastCommonSep = 0
  }

  let out = ''
  for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
    if (i === fromEnd || from.charCodeAt(i) === CHAR_BACKWARD_SLASH) {
      out += out.length === 0 ? '..' : '\\..'
    }
  }

  toStart += lastCommonSep

  if (out.length > 0) {
    return `${out}${toOrig.substring(toStart, toEnd)}`
  }
  if (toOrig.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) {
    ++toStart
  }
  return toOrig.substring(toStart, toEnd)
}

exports.toNamespacedPath = function toNamespacedPath(path) {
  if (path.length === 0) return path

  const resolvedPath = exports.resolve(path)

  if (resolvedPath.length <= 2) return path

  if (resolvedPath.charCodeAt(0) === CHAR_BACKWARD_SLASH) {
    if (resolvedPath.charCodeAt(1) === CHAR_BACKWARD_SLASH) {
      const code = resolvedPath.charCodeAt(2)
      if (code !== CHAR_QUESTION_MARK && code !== CHAR_DOT) {
        return `\\\\?\\UNC\\${resolvedPath.substring(2)}`
      }
    }
  } else if (
    isWindowsDeviceRoot(resolvedPath.charCodeAt(0)) &&
    resolvedPath.charCodeAt(1) === CHAR_COLON &&
    resolvedPath.charCodeAt(2) === CHAR_BACKWARD_SLASH
  ) {
    return `\\\\?\\${resolvedPath}`
  }

  return path
}

exports.dirname = function dirname(path) {
  const len = path.length
  if (len === 0) return '.'
  let rootEnd = -1
  let offset = 0
  const code = path.charCodeAt(0)

  if (len === 1) {
    return isWindowsPathSeparator(code) ? path : '.'
  }

  if (isWindowsPathSeparator(code)) {
    rootEnd = offset = 1

    if (isWindowsPathSeparator(path.charCodeAt(1))) {
      let j = 2
      let last = j
      while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
        j++
      }
      if (j < len && j !== last) {
        last = j
        while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
          j++
        }
        if (j < len && j !== last) {
          last = j
          while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
            j++
          }
          if (j === len) {
            return path
          }
          if (j !== last) {
            rootEnd = offset = j + 1
          }
        }
      }
    }
  } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
    rootEnd = len > 2 && isWindowsPathSeparator(path.charCodeAt(2)) ? 3 : 2
    offset = rootEnd
  }

  let end = -1
  let matchedSlash = true
  for (let i = len - 1; i >= offset; --i) {
    if (isWindowsPathSeparator(path.charCodeAt(i))) {
      if (!matchedSlash) {
        end = i
        break
      }
    } else {
      matchedSlash = false
    }
  }

  if (end === -1) {
    if (rootEnd === -1) return '.'

    end = rootEnd
  }
  return path.substring(0, end)
}

exports.basename = function basename(path, suffix) {
  let start = 0
  let end = -1
  let matchedSlash = true

  if (
    path.length >= 2 &&
    isWindowsDeviceRoot(path.charCodeAt(0)) &&
    path.charCodeAt(1) === CHAR_COLON
  ) {
    start = 2
  }

  if (suffix !== undefined && suffix.length > 0 && suffix.length <= path.length) {
    if (suffix === path) return ''
    let extIdx = suffix.length - 1
    let firstNonSlashEnd = -1
    for (let i = path.length - 1; i >= start; --i) {
      const code = path.charCodeAt(i)
      if (isWindowsPathSeparator(code)) {
        if (!matchedSlash) {
          start = i + 1
          break
        }
      } else {
        if (firstNonSlashEnd === -1) {
          matchedSlash = false
          firstNonSlashEnd = i + 1
        }
        if (extIdx >= 0) {
          if (code === suffix.charCodeAt(extIdx)) {
            if (--extIdx === -1) {
              end = i
            }
          } else {
            extIdx = -1
            end = firstNonSlashEnd
          }
        }
      }
    }

    if (start === end) end = firstNonSlashEnd
    else if (end === -1) end = path.length
    return path.substring(start, end)
  }
  for (let i = path.length - 1; i >= start; --i) {
    if (isWindowsPathSeparator(path.charCodeAt(i))) {
      if (!matchedSlash) {
        start = i + 1
        break
      }
    } else if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
  }

  if (end === -1) return ''
  return path.substring(start, end)
}

exports.extname = function extname(path) {
  let start = 0
  let startDot = -1
  let startPart = 0
  let end = -1
  let matchedSlash = true
  let preDotState = 0

  if (
    path.length >= 2 &&
    path.charCodeAt(1) === CHAR_COLON &&
    isWindowsDeviceRoot(path.charCodeAt(0))
  ) {
    start = startPart = 2
  }

  for (let i = path.length - 1; i >= start; --i) {
    const code = path.charCodeAt(i)
    if (isWindowsPathSeparator(code)) {
      if (!matchedSlash) {
        startPart = i + 1
        break
      }
      continue
    }
    if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
    if (code === CHAR_DOT) {
      if (startDot === -1) startDot = i
      else if (preDotState !== 1) preDotState = 1
    } else if (startDot !== -1) {
      preDotState = -1
    }
  }

  if (
    startDot === -1 ||
    end === -1 ||
    preDotState === 0 ||
    (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1)
  ) {
    return ''
  }
  return path.substring(startDot, end)
}
{
  "name": "bare-path",
  "version": "3.0.1",
  "description": "Path manipulation library for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./posix": "./lib/posix.js",
    "./win32": "./lib/win32.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "lib",
    "NOTICE"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-path.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-path/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-path#readme",
  "dependencies": {
    "bare-os": "^3.0.1"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "lunte": "^1.8.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
const abort = require('bare-abort')
const EventEmitter = require('bare-events')
const Signal = require('bare-signals')
const os = require('bare-os')
const env = require('bare-env')
const hrtime = require('bare-hrtime')
const stdio = require('bare-stdio')

class Process extends EventEmitter {
  constructor() {
    super()

    this._startTime = hrtime.bigint()

    EventEmitter.forward(Bare, this, [
      'uncaughtException',
      'unhandledRejection',
      'beforeExit',
      'exit',
      'suspend',
      'wakeup',
      'idle',
      'resume'
    ])

    const signals = new Signal.Emitter()

    signals.unref()

    EventEmitter.forward(signals, this, Object.keys(os.constants.signals))
  }

  get stdin() {
    return stdio.in
  }

  get stdout() {
    return stdio.out
  }

  get stderr() {
    return stdio.err
  }

  get platform() {
    return os.platform()
  }

  get arch() {
    return os.arch()
  }

  get title() {
    return os.getProcessTitle()
  }

  set title(title) {
    os.setProcessTitle(title)
  }

  get pid() {
    return os.pid()
  }

  get ppid() {
    return os.ppid()
  }

  get argv() {
    return Bare.argv
  }

  get execPath() {
    return os.execPath()
  }

  get exitCode() {
    return Bare.exitCode
  }

  set exitCode(code) {
    Bare.exitCode = code
  }

  get version() {
    return Bare.version
  }

  get versions() {
    return Bare.versions
  }

  get env() {
    return env
  }

  get hrtime() {
    return hrtime
  }

  abort() {
    abort()
  }

  exit(code) {
    Bare.exit(code)
  }

  suspend() {
    Bare.suspend()
  }

  resume() {
    Bare.resume()
  }

  cwd() {
    return os.cwd()
  }

  chdir(directory) {
    os.chdir(directory)
  }

  kill(pid, signal) {
    os.kill(pid, signal)
  }

  uptime() {
    return Number(hrtime.bigint() - this._startTime) / 1e9
  }

  cpuUsage(previous) {
    return os.cpuUsage(previous)
  }

  threadCpuUsage(previous) {
    return os.threadCpuUsage(previous)
  }

  resourceUsage() {
    return os.resourceUsage()
  }

  availableMemory() {
    return os.availableMemory()
  }

  constrainedMemory() {
    return os.constrainedMemory()
  }

  memoryUsage() {
    return os.memoryUsage()
  }

  nextTick(cb, ...args) {
    queueMicrotask(cb.bind(null, ...args))
  }

  [Symbol.for('bare.inspect')]() {
    return {
      __proto__: { constructor: Process },

      platform: this.platform,
      arch: this.arch,
      title: this.title,
      pid: this.pid,
      ppid: this.ppid,
      argv: this.argv,
      execPath: this.execPath,
      exitCode: this.exitCode,
      version: this.version,
      versions: this.versions,
      env: this.env
    }
  }
}

module.exports = new Process()
{
  "name": "bare-process",
  "version": "4.4.1",
  "description": "Node.js-compatible process control for Bare",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "global.js",
    "global.d.ts"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-process.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-process/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-process#readme",
  "dependencies": {
    "bare-abort": "^2.0.13",
    "bare-env": "^3.0.0",
    "bare-events": "^2.3.1",
    "bare-hrtime": "^2.0.0",
    "bare-os": "^3.7.1",
    "bare-signals": "^4.0.0",
    "bare-stdio": "^1.0.1"
  },
  "devDependencies": {
    "brittle": "^3.2.1",
    "lunte": "^1.6.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = require.addon()
const EventEmitter = require('bare-events')
const os = require('bare-os')
const binding = require('./binding')
const errors = require('./lib/errors')

const signals = os.constants.signals

module.exports = exports = class Signal extends EventEmitter {
  constructor(signum) {
    super()

    if (typeof signum === 'string') {
      if (signum in signals === false) {
        throw errors.UNKNOWN_SIGNAL(`Unknown signal '${signum}'`)
      }

      signum = signals[signum]
    }

    this._signum = signum
    this._closing = null
    this._handle = binding.init(this, this._onsignal, this._onclose)
  }

  start() {
    if (this._closing) throw errors.SIGNAL_CLOSED('Signal is closed')
    binding.start(this._handle, this._signum)
    return this
  }

  stop() {
    if (this._closing) return this
    binding.stop(this._handle)
    return this
  }

  ref() {
    if (this._closing) return this
    binding.ref(this._handle)
    return this
  }

  unref() {
    if (this._closing) return this
    binding.unref(this._handle)
    return this
  }

  close() {
    if (this._closing) return this._closing
    this._closing = EventEmitter.once(this, 'close')

    binding.close(this._handle)

    return this._closing
  }

  _onsignal() {
    this.emit('signal', this._signum)
  }

  _onclose() {
    this._handle = null

    this.emit('close')
  }

  static send(signum, pid = os.pid()) {
    os.kill(pid, signum)
  }
}

exports.Emitter = require('./lib/emitter')

exports.constants = signals
exports.errors = errors
const EventEmitter = require('bare-events')
const Signal = require('..')

module.exports = class SignalEmitter extends EventEmitter {
  constructor() {
    super()

    this._signals = new Map()
    this._unrefed = false

    this.on('newListener', this._onnewlistener).on(
      'removeListener',
      this._onremovelistener
    )
  }

  ref() {
    this._unrefed = false
    for (const signal of this._signals.values()) signal.ref()
    return this
  }

  unref() {
    this._unrefed = true
    for (const signal of this._signals.values()) signal.unref()
    return this
  }

  _onnewlistener(name) {
    if (name === 'newListener' || name === 'removeListener') return

    if (this.listenerCount(name) === 0) {
      const signal = new Signal(name)

      signal.on('signal', this._onsignal.bind(this, name)).start()

      if (this._unrefed) signal.unref()

      this._signals.set(name, signal)
    }
  }

  _onremovelistener(name) {
    if (name === 'newListener' || name === 'removeListener') return

    if (this.listenerCount(name) === 0) {
      const signal = this._signals.get(name)

      if (this._unrefed) signal.ref()

      signal.close()

      this._signals.delete(name)
    }
  }

  _onsignal(name) {
    this.emit(name, name, Signal.constants[name])
  }
}
module.exports = class SignalError extends Error {
  constructor(msg, fn = SignalError, code = fn.name) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'SignalError'
  }

  static UNKNOWN_SIGNAL(msg) {
    return new SignalError(msg, SignalError.UNKNOWN_SIGNAL)
  }

  static SIGNAL_CLOSED(msg) {
    return new SignalError(msg, SignalError.SIGNAL_CLOSED)
  }
}
{
  "name": "bare-signals",
  "version": "4.2.0",
  "description": "Native signal handling for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./errors": "./lib/errors.js",
    "./emitter": "./lib/emitter.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-signals.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-signals/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-signals#readme",
  "engines": {
    "bare": ">=1.7.0"
  },
  "dependencies": {
    "bare-events": "^2.5.3",
    "bare-os": "^3.3.1"
  },
  "devDependencies": {
    "brittle": "^3.2.1",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
module.exports = require.addon()
const fs = require('bare-fs')
const tty = require('bare-tty')
const Pipe = require('bare-pipe')
const binding = require('./binding')

const { TTY, NAMED_PIPE } = binding

class IO {
  constructor() {
    this._in = null
    this._out = null
    this._err = null
  }

  get in() {
    if (this._in === null) {
      switch (binding.guessType(0)) {
        case TTY:
          this._in = new tty.ReadStream(0)
          break
        case NAMED_PIPE:
          this._in = new Pipe(0, { eagerOpen: false })
          break
        default:
          this._in = fs.createReadStream(null, { fd: 0, eagerOpen: false })
      }
    }

    return this._in
  }

  get out() {
    if (this._out === null) {
      switch (binding.guessType(1)) {
        case TTY:
          this._out = new tty.WriteStream(1)
          break
        case NAMED_PIPE:
          this._out = new Pipe(1, { eagerOpen: false })
          this._out.unref()
          break
        default:
          this._out = fs.createWriteStream(null, { fd: 1, eagerOpen: false })
      }
    }

    return this._out
  }

  get err() {
    if (this._err === null) {
      switch (binding.guessType(2)) {
        case TTY:
          this._err = new tty.WriteStream(2)
          break
        case NAMED_PIPE:
          this._err = new Pipe(2, { eagerOpen: false })
          this._err.unref()
          break
        default:
          this._err = fs.createWriteStream(null, { fd: 2, eagerOpen: false })
      }
    }

    return this._err
  }
}

module.exports = new IO()
module.exports = require.addon()
const EventEmitter = require('bare-events')
const { Duplex } = require('bare-stream')
const binding = require('./binding')
const constants = require('./lib/constants')
const errors = require('./lib/errors')

const defaultReadBufferSize = 65536
const empty = Buffer.alloc(0)

const ipcHandle = Symbol.for('bare.ipc.handle')
const ipcAccept = Symbol.for('bare.ipc.accept')

module.exports = exports = class Pipe extends Duplex {
  constructor(path, opts = {}) {
    if (typeof path === 'object' && path !== null) {
      opts = path
      path = null
    }

    const {
      readBufferSize = defaultReadBufferSize,
      allowHalfOpen = true,
      eagerOpen = true,
      ipc = false
    } = opts

    super({ eagerOpen })

    this._state = 0

    this._allowHalfOpen = allowHalfOpen
    this._ipc = ipc

    this._fd = -1
    this._path = null

    this._pendingOpen = null
    this._pendingWrite = null
    this._pendingWriteSegments = null
    this._pendingWriteIdx = 0
    this._pendingFinal = null
    this._pendingDestroy = null

    this._handleQueue = []
    this._handleQueueSize = 0

    this._buffer = Buffer.alloc(readBufferSize)

    this._handle = binding.init(
      this._buffer,
      ipc,
      this,
      noop,
      this._onconnect,
      this._onwrite,
      this._onfinal,
      this._onread,
      this._onhandle,
      this._onclose
    )

    if (typeof path === 'number') {
      this.open(path)
    } else if (typeof path === 'string') {
      this.connect(path)
    }
  }

  get connecting() {
    return (this._state & constants.state.CONNECTING) !== 0
  }

  get pending() {
    return (this._state & constants.state.CONNECTED) === 0
  }

  get readyState() {
    if (this._state & constants.state.READABLE && this._state & constants.state.WRITABLE) {
      return 'open'
    }

    if (this._state & constants.state.READABLE) {
      return 'readOnly'
    }

    if (this._state & constants.state.WRITABLE) {
      return 'writeOnly'
    }

    return 'opening'
  }

  get [ipcHandle]() {
    return this._handle
  }

  open(fd, opts = {}, onconnect) {
    if (typeof opts === 'function') {
      onconnect = opts
      opts = {}
    }

    if (typeof fd === 'object' && fd !== null) {
      opts = fd || {}
      fd = opts.fd
    }

    try {
      const status = binding.open(this._handle, fd)

      this._state |= constants.state.CONNECTED
      this._fd = fd

      if (status & binding.READABLE) {
        this._state |= constants.state.READABLE
      } else {
        this.push(null)
      }

      if (status & binding.WRITABLE) {
        this._state |= constants.state.WRITABLE
      } else {
        this.end()
      }

      if (onconnect) this.once('connect', onconnect)

      queueMicrotask(() => this.emit('connect'))
    } catch (err) {
      queueMicrotask(() => {
        if (this._pendingOpen) this._pendingOpen(err)
        else this.destroy(err)
      })
    }

    return this
  }

  connect(path, opts = {}, onconnect) {
    if (this._state & constants.state.CONNECTING || this._state & constants.state.CONNECTED) {
      throw errors.PIPE_ALREADY_CONNECTED('Pipe is already connected')
    }

    this._state |= constants.state.CONNECTING

    if (typeof opts === 'function') {
      onconnect = opts
      opts = {}
    }

    if (typeof path === 'object' && path !== null) {
      opts = path || {}
      path = opts.path
    }

    try {
      binding.connect(this._handle, path)

      this._path = path

      if (onconnect) this.once('connect', onconnect)
    } catch (err) {
      queueMicrotask(() => {
        if (this._pendingOpen) this._pendingOpen(err)
        else this.destroy(err)
      })
    }

    return this
  }

  write(chunk, encoding, handle, cb) {
    if (typeof encoding === 'function') {
      cb = encoding
      encoding = undefined
      handle = null
    } else if (typeof encoding === 'object' && encoding !== null) {
      if (typeof handle === 'function') cb = handle
      handle = encoding
      encoding = undefined
    } else if (typeof handle === 'function') {
      cb = handle
      handle = null
    }

    if (handle) this._handleQueueSize++

    this._handleQueue.push(handle || null)

    if (encoding) return super.write(chunk, encoding, cb)

    return super.write(chunk, cb)
  }

  accept(target) {
    const handle = target[ipcHandle]

    if (handle === undefined) {
      throw errors.INVALID_IPC_TARGET('Target does not implement the IPC handle protocol')
    }

    binding.accept(this._handle, handle)

    if (typeof target[ipcAccept] === 'function') target[ipcAccept]()

    return target
  }

  ref() {
    binding.ref(this._handle)

    return this
  }

  unref() {
    binding.unref(this._handle)

    return this
  }

  [ipcAccept]() {
    this._onaccept()
  }

  _open(cb) {
    if (this._state & constants.state.CONNECTED) return cb(null)

    this._pendingOpen = cb
  }

  _read() {
    if ((this._state & constants.state.READING) === 0) {
      this._state |= constants.state.READING

      binding.resume(this._handle)
    }
  }

  _writev(batch, cb) {
    this._pendingWrite = cb

    if (this._handleQueueSize === 0) {
      this._handleQueue = []
      this._pendingWriteSegments = null

      binding.writev(
        this._handle,
        batch.map(({ chunk }) => chunk),
        null
      )
      return
    }

    const handles = this._handleQueue.splice(0, batch.length)

    // Fill any holes in the batch for messages that don't carry a handle. Each
    // message that does carry a handle decrements the handle queue size.
    for (let i = 0; i < batch.length; i++) {
      if (handles[i] === undefined) handles[i] = null
      else if (handles[i] !== null) this._handleQueueSize--
    }

    const segments = []

    let i = 0
    while (i < batch.length) {
      if (handles[i] !== null) {
        segments.push({ chunks: [batch[i]], handle: handles[i] })
        i++
      } else {
        const start = i
        while (i < batch.length && handles[i] === null) i++
        segments.push({ chunks: batch.slice(start, i), handle: null })
      }
    }

    this._pendingWriteSegments = segments
    this._pendingWriteIdx = 0

    this._writeNextSegment()
  }

  _writeNextSegment() {
    const segment = this._pendingWriteSegments[this._pendingWriteIdx]

    const chunks = []
    for (let i = 0; i < segment.chunks.length; i++) {
      chunks.push(segment.chunks[i].chunk)
    }

    let sendHandle = null
    if (segment.handle !== null) sendHandle = segment.handle[ipcHandle]

    binding.writev(this._handle, chunks, sendHandle)
  }

  _final(cb) {
    if (this._state & constants.state.READABLE && this._state & constants.state.WRITABLE) {
      this._pendingFinal = cb

      binding.end(this._handle)
    } else {
      cb(null)
    }
  }

  _predestroy() {
    if (this._state & constants.state.CLOSING) return
    this._state |= constants.state.CLOSING

    binding.close(this._handle)
  }

  _destroy(err, cb) {
    if (this._state & constants.state.CLOSING) return cb(err)
    this._state |= constants.state.CLOSING

    this._pendingDestroy = cb

    binding.close(this._handle)
  }

  _continueOpen(err) {
    if (this._pendingOpen === null) return
    const cb = this._pendingOpen
    this._pendingOpen = null
    cb(err)
  }

  _continueWrite(err) {
    if (this._pendingWrite === null) return

    if (this._pendingWriteSegments === null) {
      const cb = this._pendingWrite
      this._pendingWrite = null
      cb(err)
      return
    }

    this._pendingWriteIdx++

    if (err === null && this._pendingWriteIdx < this._pendingWriteSegments.length) {
      this._writeNextSegment()
      return
    }

    const cb = this._pendingWrite
    this._pendingWrite = null
    this._pendingWriteSegments = null
    this._pendingWriteIdx = 0
    cb(err)
  }

  _continueFinal(err) {
    if (this._pendingFinal === null) return
    const cb = this._pendingFinal
    this._pendingFinal = null
    cb(err)
  }

  _continueDestroy() {
    if (this._pendingDestroy === null) return
    const cb = this._pendingDestroy
    this._pendingDestroy = null
    cb(null)
  }

  _onconnect(err) {
    if (err) {
      if (this._pendingOpen) this._continueOpen(err)
      else this.destroy(err)
      return
    }

    this._state |= constants.state.CONNECTED | constants.state.READABLE | constants.state.WRITABLE
    this._state &= ~constants.state.CONNECTING
    this._continueOpen()

    this.emit('connect')
  }

  _onaccept() {
    this._state |= constants.state.CONNECTED | constants.state.READABLE | constants.state.WRITABLE
    this._continueOpen()
  }

  _onread(err, read) {
    if (err) {
      this.destroy(err)
      return
    }

    if (read === 0) {
      this.push(null)
      if (this._allowHalfOpen === false) this.end()
      return
    }

    const copy = Buffer.allocUnsafe(read)
    copy.set(this._buffer.subarray(0, read))

    if (this.push(copy) === false && this.destroying === false) {
      this._state &= ~constants.state.READING

      binding.pause(this._handle)
    }
  }

  _onhandle(type) {
    this.emit('handle', type)
  }

  _onwrite(err) {
    this._continueWrite(err)
  }

  _onfinal(err) {
    this._continueFinal(err === null || err.code === 'ENOTCONN' ? null : err)
  }

  _onclose() {
    this._continueDestroy()
  }

  _onspawn(readable, writable) {
    this._state |= constants.state.CONNECTED

    if (readable) {
      this._state |= constants.state.READABLE
    } else {
      this.push(null)
    }

    if (writable) {
      this._state |= constants.state.WRITABLE
    } else {
      this.end()
    }

    this._continueOpen()
  }
}

exports.Pipe = exports

exports.pipe = function pipe() {
  return binding.pipe()
}

exports.Server = class PipeServer extends EventEmitter {
  constructor(opts = {}, onconnection) {
    if (typeof opts === 'function') {
      onconnection = opts
      opts = {}
    }

    super()

    const {
      readBufferSize = defaultReadBufferSize,
      allowHalfOpen = true,
      pauseOnConnect = false,
      ipc = false
    } = opts

    this._state = 0

    this._readBufferSize = readBufferSize
    this._allowHalfOpen = allowHalfOpen
    this._pauseOnConnect = pauseOnConnect
    this._ipc = ipc

    this._path = null
    this._connections = new Set()

    this._error = null
    this._handle = null

    if (onconnection) this.on('connection', onconnection)
  }

  get listening() {
    return (this._state & constants.state.BOUND) !== 0
  }

  address() {
    if ((this._state & constants.state.BOUND) === 0) {
      return null
    }

    return this._path
  }

  listen(path, backlog = 511, opts = {}, onlistening) {
    if (this._state & constants.state.BINDING || this._state & constants.state.BOUND) {
      throw errors.SERVER_ALREADY_LISTENING('Server is already listening')
    }

    if (this._state & constants.state.CLOSING) {
      throw errors.SERVER_IS_CLOSED('Server is closed')
    }

    this._state |= constants.state.BINDING

    if (typeof backlog === 'function') {
      onlistening = backlog
      backlog = 511
    } else if (typeof opts === 'function') {
      onlistening = opts
      opts = {}
    }

    if (typeof path === 'object' && path !== null) {
      opts = path || {}
      path = opts.path
      backlog = opts.backlog || 511
    }

    this._handle = binding.init(
      empty,
      this._ipc,
      this,
      this._onconnection,
      noop,
      noop,
      noop,
      noop,
      noop,
      this._onclose
    )

    if (this._state & constants.state.UNREFED) binding.unref(this._handle)

    try {
      binding.bind(this._handle, path, backlog)

      this._path = path
      this._state |= constants.state.BOUND
      this._state &= ~constants.state.BINDING

      if (onlistening) this.once('listening', onlistening)

      queueMicrotask(() => this.emit('listening'))
    } catch (err) {
      this._error = err

      binding.close(this._handle)
    }

    return this
  }

  close(onclose) {
    if (onclose) this.once('close', onclose)

    if (this._state & constants.state.CLOSING) return
    this._state |= constants.state.CLOSING

    this._closeMaybe()

    return this
  }

  ref() {
    this._state &= ~constants.state.UNREFED

    if (this._handle !== null) binding.ref(this._handle)

    return this
  }

  unref() {
    this._state |= constants.state.UNREFED

    if (this._handle !== null) binding.unref(this._handle)

    return this
  }

  _closeMaybe() {
    if (this._state & constants.state.CLOSING && this._connections.size === 0) {
      if (this._handle !== null) binding.close(this._handle)
      else queueMicrotask(() => this.emit('close'))
    }
  }

  _onconnection(err) {
    if (err) {
      this.emit('error', err)
      return
    }

    if (this._state & constants.state.CLOSING) return

    const pipe = new exports.Pipe({
      readBufferSize: this._readBufferSize,
      allowHalfOpen: this._allowHalfOpen,
      eagerOpen: !this._pauseOnConnect,
      ipc: this._ipc
    })

    try {
      binding.accept(this._handle, pipe._handle)

      pipe._path = this._path
      pipe._onaccept()

      this._connections.add(pipe)

      pipe.on('close', () => {
        this._connections.delete(pipe)
        this._closeMaybe()
      })

      this.emit('connection', pipe)
    } catch (err) {
      pipe.destroy()

      throw err
    }
  }

  _onclose() {
    const err = this._error

    this._state &= ~constants.state.BINDING
    this._error = null
    this._handle = null

    if (err) this.emit('error', err)
    else this.emit('close')
  }
}

exports.constants = constants
exports.errors = errors

exports.createConnection = function createConnection(path, opts, onconnect) {
  if (typeof opts === 'function') {
    onconnect = opts
    opts = {}
  }

  if (typeof path === 'object' && path !== null) {
    opts = path || {}
    path = opts.path
  }

  return new exports.Pipe(opts).connect(path, opts, onconnect)
}

exports.createServer = function createServer(opts, onconnection) {
  return new exports.Server(opts, onconnection)
}

function noop() {}
const binding = require('../binding')

module.exports = {
  state: {
    CONNECTING: 0x1,
    CONNECTED: 0x2,
    BINDING: 0x4,
    BOUND: 0x8,
    READING: 0x10,
    CLOSING: 0x20,
    READABLE: 0x40,
    WRITABLE: 0x80,
    UNREFED: 0x100
  },
  handle: {
    NAMED_PIPE: binding.UV_NAMED_PIPE,
    TCP: binding.UV_TCP,
    UDP: binding.UV_UDP
  }
}
module.exports = class PipeError extends Error {
  constructor(msg, fn = PipeError, code = fn.name) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'PipeError'
  }

  static PIPE_ALREADY_CONNECTED(msg) {
    return new PipeError(msg, PipeError.PIPE_ALREADY_CONNECTED)
  }

  static SERVER_ALREADY_LISTENING(msg) {
    return new PipeError(msg, PipeError.SERVER_ALREADY_LISTENING)
  }

  static SERVER_IS_CLOSED(msg) {
    return new PipeError(msg, PipeError.SERVER_IS_CLOSED)
  }

  static INVALID_IPC_TARGET(msg) {
    return new PipeError(msg, PipeError.INVALID_IPC_TARGET)
  }
}
{
  "name": "bare-pipe",
  "version": "4.2.0",
  "description": "Native I/O pipes for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    },
    "./errors": {
      "types": "./lib/errors.d.ts",
      "default": "./lib/errors.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-pipe.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-pipe/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-pipe#readme",
  "engines": {
    "bare": ">=1.16.0"
  },
  "dependencies": {
    "bare-events": "^2.0.0",
    "bare-stream": "^2.0.0"
  },
  "devDependencies": {
    "bare-path": "^3.0.0",
    "bare-tcp": "^2.4.1",
    "brittle": "^3.2.1",
    "cmake-bare": "^1.1.6",
    "lunte": "^1.8.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  }
}
{
  "name": "bare-stdio",
  "version": "1.0.2",
  "description": "Standard input/output streams for Bare",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./constants": "./lib/constants.js",
    "./errors": "./lib/errors.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-stdio.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-stdio/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-stdio#readme",
  "dependencies": {
    "bare-fs": "^4.5.2",
    "bare-pipe": "^4.1.5",
    "bare-tty": "^5.0.3"
  },
  "devDependencies": {
    "bare-os": "^3.6.2",
    "bare-path": "^3.0.0",
    "bare-subprocess": "^3.1.4",
    "brittle": "^3.19.1",
    "cmake-bare": "^1.7.7",
    "lunte": "^1.4.0",
    "prettier": "^3.8.1",
    "prettier-config-holepunch": "^2.0.0",
    "tt-native": "^1.1.1"
  }
}
const stream = require('streamx')
const { ReadableStream, WritableStream } = require('./web')

const defaultEncoding = 'utf8'

module.exports = exports = stream.Stream

exports.pipeline = stream.pipeline

exports.isStream = stream.isStream
exports.isEnding = stream.isEnding
exports.isEnded = stream.isEnded
exports.isFinishing = stream.isFinishing
exports.isFinished = stream.isFinished
exports.isDisturbed = stream.isDisturbed

exports.isErrored = function isErrored(stream) {
  return exports.getStreamError(stream) !== null
}

exports.isReadable = function isReadable(stream) {
  return stream.readable && !stream.destroying && !exports.isEnded(stream)
}

exports.isWritable = function isWritable(stream) {
  return stream.writable && !stream.destroying && !exports.isFinishing(stream)
}

exports.getStreamError = stream.getStreamError

exports.addAbortSignal = function addAbortSignal(signal, stream) {
  function onAbort() {
    stream.destroy(signal.reason)
  }

  if (signal.aborted) onAbort()
  else signal.addEventListener('abort', onAbort)

  return stream
}

exports.Stream = exports

exports.Readable = class Readable extends stream.Readable {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthReadable: null,
      map: null,
      mapReadable: null
    })

    if (this._construct) this._open = this._construct

    if (this._read !== stream.Readable.prototype._read) {
      this._read = read.bind(this, this._read)
    }

    if (this._destroy !== stream.Stream.prototype._destroy) {
      this._destroy = destroy.bind(this, this._destroy)
    }
  }

  get closed() {
    return !exports.isReadable(this)
  }

  get errored() {
    return stream.getStreamError(this)
  }

  push(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = Buffer.from(chunk, encoding || defaultEncoding)
    }

    return super.push(chunk)
  }

  unshift(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = Buffer.from(chunk, encoding || defaultEncoding)
    }

    super.unshift(chunk)
  }

  static fromWeb(readableStream, opts = {}) {
    const stream = readableStream._stream

    if (opts.encoding) stream.setEncoding(opts.encoding)
    if (opts.signal) exports.addAbortSignal(opts.signal, stream)

    return stream
  }

  static toWeb(readable, opts = {}) {
    return new ReadableStream(readable, opts.strategy)
  }

  async [Symbol.asyncDispose]() {
    if (!this.destroyed) this.destroy()

    await new Promise((resolve) => exports.finished(this, resolve))
  }
}

exports.Writable = class Writable extends stream.Writable {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthWritable,
      map: null,
      mapWritable: null
    })

    if (this._construct) this._open = this._construct

    if (this._write !== stream.Writable.prototype._write) {
      this._write = write.bind(this, this._write)
    }

    if (this._destroy !== stream.Stream.prototype._destroy) {
      this._destroy = destroy.bind(this, this._destroy)
    }
  }

  get closed() {
    return !exports.isWritable(this)
  }

  get errored() {
    return stream.getStreamError(this)
  }

  write(chunk, encoding, cb) {
    if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = Buffer.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result = super.write({ chunk, encoding })

    if (cb) stream.Writable.drained(this).then(() => cb(null), cb)

    return result
  }

  end(chunk, encoding, cb) {
    if (typeof chunk === 'function') {
      cb = chunk
      chunk = null
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = Buffer.from(chunk, encoding || defaultEncoding)
    } else {
      encoding = 'buffer'
    }

    const result =
      chunk !== undefined && chunk !== null ? super.end({ chunk, encoding }) : super.end()

    if (cb) this.once('finish', () => cb(null))

    return result
  }

  static fromWeb(writableStream, opts = {}) {
    const stream = writableStream._stream

    if (opts.signal) exports.addAbortSignal(opts.signal, stream)

    return stream
  }

  static toWeb(writable) {
    return new WritableStream(writable)
  }

  async [Symbol.asyncDispose]() {
    if (!this.destroyed) this.destroy()

    await new Promise((resolve) => exports.finished(this, resolve))
  }
}

exports.Duplex = class Duplex extends stream.Duplex {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthReadable: null,
      byteLengthWritable,
      map: null,
      mapReadable: null,
      mapWritable: null
    })

    if (this._construct) this._open = this._construct

    if (this._read !== stream.Readable.prototype._read) {
      this._read = read.bind(this, this._read)
    }

    if (this._write !== stream.Duplex.prototype._write) {
      this._write = write.bind(this, this._write)
    }

    if (this._destroy !== stream.Stream.prototype._destroy) {
      this._destroy = destroy.bind(this, this._destroy)
    }
  }

  push(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = Buffer.from(chunk, encoding || defaultEncoding)
    }

    return super.push(chunk)
  }

  unshift(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = Buffer.from(chunk, encoding || defaultEncoding)
    }

    super.unshift(chunk)
  }

  write(chunk, encoding, cb) {
    if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = Buffer.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result = super.write({ chunk, encoding })

    if (cb) stream.Writable.drained(this).then(() => cb(null), cb)

    return result
  }

  end(chunk, encoding, cb) {
    if (typeof chunk === 'function') {
      cb = chunk
      chunk = null
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = Buffer.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result =
      chunk !== undefined && chunk !== null ? super.end({ chunk, encoding }) : super.end()

    if (cb) this.once('finish', () => cb(null))

    return result
  }

  static fromWeb({ readable: readableStream, writable: writableStream }, opts) {
    const readable = exports.Readable.fromWeb(readableStream, opts)
    const writable = exports.Writable.fromWeb(writableStream, opts)

    const duplex = new exports.Duplex({
      write(data, encoding, cb) {
        writable.write(data, encoding, cb)
      }
    })

    readable
      .on('data', (data) => duplex.push(data))
      .on('end', () => duplex.push(null))
      .on('error', (err) => duplex.destroy(err))

    writable.on('finish', () => duplex.end()).on('error', (err) => duplex.destroy(err))

    return duplex
  }

  static toWeb(duplex) {
    const readableStream = exports.Readable.toWeb(duplex)
    const writableStream = exports.Writable.toWeb(duplex)

    return { readable: readableStream, writable: writableStream }
  }
}

class DuplexSide extends exports.Duplex {
  constructor(opts) {
    super(opts)

    this._otherSide = null
    this._cb = null
  }

  _read() {
    const cb = this._cb
    if (!cb) return

    this._cb = null
    cb()
  }

  _write(chunk, encoding, cb) {
    this._otherSide.push(chunk, encoding)
    this._otherSide._cb = cb
  }

  _final(cb) {
    this._otherSide.on('end', cb)
    this._otherSide.push(null)
  }
}

exports.duplexPair = function duplexPair(opts) {
  const sideA = new DuplexSide(opts)
  const sideB = new DuplexSide(opts)

  sideA._otherSide = sideB
  sideB._otherSide = sideA

  return [sideA, sideB]
}

exports.Transform = class Transform extends stream.Transform {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthReadable: null,
      byteLengthWritable,
      map: null,
      mapReadable: null,
      mapWritable: null
    })

    if (this._transform !== stream.Transform.prototype._transform) {
      this._transform = transform.bind(this, this._transform)
    } else {
      this._transform = passthrough
    }
  }

  push(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = Buffer.from(chunk, encoding || defaultEncoding)
    }

    return super.push(chunk)
  }

  unshift(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = Buffer.from(chunk, encoding || defaultEncoding)
    }

    super.unshift(chunk)
  }

  write(chunk, encoding, cb) {
    if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = Buffer.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result = super.write({ chunk, encoding })

    if (cb) stream.Writable.drained(this).then(() => cb(null), cb)

    return result
  }

  end(chunk, encoding, cb) {
    if (typeof chunk === 'function') {
      cb = chunk
      chunk = null
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = Buffer.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result =
      chunk !== undefined && chunk !== null ? super.end({ chunk, encoding }) : super.end()

    if (cb) this.once('finish', () => cb(null))

    return result
  }
}

exports.PassThrough = class PassThrough extends exports.Transform {}

exports.finished = function finished(stream, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (!opts) opts = {}

  const { cleanup = false } = opts

  const done = () => {
    cb(exports.getStreamError(stream, { all: true }))

    if (cleanup) detach()
  }

  const detach = () => {
    stream.off('close', done)
    stream.off('error', noop)
  }

  if (stream.destroyed) {
    done()
  } else {
    stream.on('close', done)
    stream.on('error', noop)
  }

  return detach
}

function read(read, cb) {
  read.call(this, 65536)

  cb(null)
}

function write(write, data, cb) {
  write.call(this, data.chunk, data.encoding, cb)
}

function transform(transform, data, cb) {
  transform.call(this, data.chunk, data.encoding, cb)
}

function destroy(destroy, cb) {
  destroy.call(this, exports.getStreamError(this), cb)
}

function passthrough(data, cb) {
  cb(null, data.chunk)
}

function byteLengthWritable(data) {
  return data.chunk.byteLength
}

function noop() {}
{
  "name": "bare-stream",
  "version": "2.13.1",
  "description": "Streaming data for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./promises": "./promises.js",
    "./web": {
      "types": "./web.d.ts",
      "default": "./web.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "promises.js",
    "web.js",
    "web.d.ts",
    "global.js",
    "global.d.ts"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-stream.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-stream/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-stream#readme",
  "dependencies": {
    "streamx": "^2.25.0",
    "teex": "^1.0.1"
  },
  "devDependencies": {
    "bare-abort-controller": "^1.1.0",
    "bare-buffer": "^3.0.0",
    "bare-events": "^2.5.4",
    "brittle": "^3.5.2",
    "lunte": "^1.6.0",
    "prettier": "^3.3.3",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "bare-abort-controller": "*",
    "bare-buffer": "*",
    "bare-events": "*"
  },
  "peerDependenciesMeta": {
    "bare-abort-controller": {
      "optional": true
    },
    "bare-buffer": {
      "optional": true
    },
    "bare-events": {
      "optional": true
    }
  }
}
const { Readable, Writable, Transform, getStreamError, isStreamx, isDisturbed } = require('streamx')
const tee = require('teex')

const readableKind = Symbol.for('bare.stream.readable.kind')
const writableKind = Symbol.for('bare.stream.writable.kind')
const transformKind = Symbol.for('bare.stream.transform.kind')

// https://streams.spec.whatwg.org/#readablestreamdefaultreader
exports.ReadableStreamDefaultReader = class ReadableStreamDefaultReader {
  constructor(stream) {
    this._stream = stream
    this._stream._stream.once('close', onclose).once('error', onerror)

    const closed = Promise.withResolvers()

    // Avoid unhandled exceptions
    closed.promise.catch(noop)

    this._closed = closed

    function onclose() {
      closed.resolve()
    }

    function onerror(err) {
      closed.reject(err)
    }
  }

  get closed() {
    return this._closed.promise
  }

  read() {
    const stream = this._stream._stream

    return new Promise((resolve, reject) => {
      const err = getStreamError(stream)

      if (err) return reject(err)

      if (stream.destroyed) {
        return resolve({ value: undefined, done: true })
      }

      const value = stream.read()

      if (value !== null) {
        return resolve({ value, done: false })
      }

      stream.once('readable', onreadable).once('close', onclose).once('error', onerror)

      function onreadable() {
        const value = stream.read()

        ondone(null, value === null ? { value: undefined, done: true } : { value, done: false })
      }

      function onclose() {
        ondone(null, { value: undefined, done: true })
      }

      function onerror(err) {
        ondone(err, null)
      }

      function ondone(err, value) {
        stream.off('readable', onreadable).off('close', onclose).off('error', onerror)

        if (err) reject(err)
        else resolve(value)
      }
    })
  }

  releaseLock() {
    this._closed.reject(new TypeError('Reader was released'))
    this._stream._releaseLock()
    this._stream = null
  }

  cancel(reason = new TypeError('Stream was cancelled')) {
    const stream = this._stream._stream

    if (stream.destroyed) return Promise.resolve()

    return new Promise((resolve) =>
      stream.once('close', resolve).once('error', noop).destroy(reason)
    )
  }
}

// https://streams.spec.whatwg.org/#readablestreamdefaultcontroller
exports.ReadableStreamDefaultController = class ReadableStreamDefaultController {
  constructor(stream) {
    this._stream = stream
  }

  get desiredSize() {
    const stream = this._stream._stream

    return stream._readableState.highWaterMark - stream._readableState.buffered
  }

  enqueue(data) {
    this._stream._stream.push(data)
  }

  close() {
    this._stream._stream.push(null)
  }

  error(err) {
    this._stream._stream.destroy(err)
  }
}

// https://streams.spec.whatwg.org/#readablestream
class ReadableStream {
  static get [readableKind]() {
    return 0 // Compatibility version
  }

  static from(iterable) {
    return new ReadableStream(Readable.from(iterable))
  }

  constructor(underlyingSource = {}, queuingStrategy) {
    if (isStreamx(underlyingSource)) {
      this._stream = underlyingSource
    } else {
      if (queuingStrategy === undefined) {
        queuingStrategy = new exports.CountQueuingStrategy()
      }

      const { start, pull, cancel } = underlyingSource
      const { highWaterMark = 1, size = defaultSize } = queuingStrategy

      this._stream = new Readable({ highWaterMark, byteLength: size })

      const controller = new exports.ReadableStreamDefaultController(this)

      try {
        let starting = Promise.resolve()

        if (start) starting = forwardError(start.call(this, controller), controller)

        if (pull) {
          this._stream._read = this._read.bind(this, starting, pull.bind(this, controller))
        }

        if (cancel) {
          this._stream.once('error', cancel.bind(this))
        }
      } catch (err) {
        controller.error(err)
      }
    }

    this._reader = null
  }

  get [readableKind]() {
    return ReadableStream[readableKind]
  }

  get locked() {
    return this._reader !== null
  }

  getReader() {
    if (this.locked) throw new TypeError('Stream is locked')

    this._reader = new exports.ReadableStreamDefaultReader(this)

    return this._reader
  }

  cancel(reason = new TypeError('Stream was cancelled')) {
    const stream = this._stream

    if (stream.destroyed) return Promise.resolve()

    if (this.locked) return Promise.reject(new TypeError('Stream is locked'))

    return new Promise((resolve) =>
      stream.once('close', resolve).once('error', noop).destroy(reason)
    )
  }

  tee() {
    const [a, b] = tee(this._stream)

    return [new ReadableStream(a), new ReadableStream(b)]
  }

  pipeTo(destination) {
    return new Promise((resolve, reject) =>
      this._stream.pipe(destination._stream, (err) => {
        err ? reject(err) : resolve()
      })
    )
  }

  [Symbol.asyncIterator]() {
    return this._stream[Symbol.asyncIterator]()
  }

  _releaseLock() {
    this._reader = null
  }

  async _read(starting, pull, cb) {
    await starting

    let err = null
    try {
      await pull()
    } catch (e) {
      err = e
    }
    cb(err)
  }
}

function defaultSize() {
  return 1
}

exports.ReadableStream = ReadableStream

// https://streams.spec.whatwg.org/#countqueuingstrategy
exports.CountQueuingStrategy = class CountQueuingStrategy {
  constructor(opts = {}) {
    const { highWaterMark = 1 } = opts

    this.highWaterMark = highWaterMark
  }

  size(chunk) {
    return 1
  }
}

// https://streams.spec.whatwg.org/#bytelengthqueuingstrategy
exports.ByteLengthQueuingStrategy = class ByteLengthQueuingStrategy {
  constructor(opts = {}) {
    const { highWaterMark = 16384 } = opts

    this.highWaterMark = highWaterMark
  }

  size(chunk) {
    return chunk.byteLength
  }
}

exports.isReadableStream = function isReadableStream(value) {
  if (value instanceof ReadableStream) return true

  return (
    typeof value === 'object' &&
    value !== null &&
    value[readableKind] === ReadableStream[readableKind]
  )
}

// https://streams.spec.whatwg.org/#readablestream-errored
exports.isReadableStreamErrored = function isReadableStreamErrored(stream) {
  return getStreamError(stream._stream) !== null
}

// https://streams.spec.whatwg.org/#is-readable-stream-disturbed
exports.isReadableStreamDisturbed = function isReadableStreamDisturbed(stream) {
  return isDisturbed(stream._stream)
}

// https://streams.spec.whatwg.org/#writablestreamdefaultwriter
exports.WritableStreamDefaultWriter = class WritableStreamDefaultWriter {
  constructor(stream) {
    this._stream = stream
    this._stream._stream.once('close', onclose).once('error', onerror)

    const closed = Promise.withResolvers()

    // Avoid unhandled exceptions
    closed.promise.catch(noop)

    this._closed = closed

    function onclose() {
      closed.resolve()
    }

    function onerror(err) {
      closed.reject(err)
    }
  }

  get desiredSize() {
    const stream = this._stream._stream

    return stream._writableState.highWaterMark - stream._writableState.buffered
  }

  get closed() {
    return this._closed.promise
  }

  get ready() {
    const stream = this._stream._stream

    if (getStreamError(stream)) return Promise.reject()

    return Writable.drained(stream).then()
  }

  async write(chunk) {
    const stream = this._stream._stream

    let err = getStreamError(stream)
    if (err) return Promise.reject(err)

    stream.write(chunk)

    await Writable.drained(stream)

    err = getStreamError(stream)
    if (err) return Promise.reject(err)
  }

  releaseLock() {
    this._closed.reject(new TypeError('Writer was released'))
    this._stream._releaseLock()
    this._stream = null
  }

  close() {
    const stream = this._stream._stream

    if (stream.destroyed) return Promise.resolve()

    return new Promise((resolve) => stream.once('close', resolve).end())
  }

  abort(reason = new TypeError('Stream was aborted')) {
    const stream = this._stream._stream

    if (stream.destroyed) return Promise.resolve()

    return new Promise((resolve) => stream.once('close', resolve).destroy(reason))
  }
}

// https://streams.spec.whatwg.org/#writablestreamdefaultcontroller
exports.WritableStreamDefaultController = class WritableStreamDefaultController {
  constructor(stream) {
    this._stream = stream
  }

  error(err) {
    this._stream._stream.destroy(err)
  }
}

// https://streams.spec.whatwg.org/#writablestream
class WritableStream {
  static get [writableKind]() {
    return 0 // Compatibility version
  }

  constructor(underlyingSink = {}, queuingStrategy = {}) {
    if (isStreamx(underlyingSink)) {
      this._stream = underlyingSink
    } else {
      if (queuingStrategy === undefined) {
        queuingStrategy = new exports.CountQueuingStrategy()
      }

      const { start, write, close, abort } = underlyingSink
      const { highWaterMark = 1, size = defaultSize } = queuingStrategy

      this._stream = new Writable({ highWaterMark, byteLength: size })

      const controller = new exports.WritableStreamDefaultController(this)

      this._controller = controller

      try {
        let starting = Promise.resolve()

        if (start) starting = forwardError(start.call(this, controller), controller)

        if (write) {
          this._stream._write = this._write.bind(this, starting, write.bind(this))
        }

        if (close) {
          this._stream._destroy = this._destroy.bind(this, close.call(this))
        }

        if (abort) {
          this._stream.once('error', abort.bind(this))
        }
      } catch (err) {
        controller.error(err)
      }
    }

    this._writer = null
  }

  get [writableKind]() {
    return WritableStream[writableKind]
  }

  get locked() {
    return this._writer !== null
  }

  getWriter() {
    if (this.locked) throw new TypeError('Stream is locked')

    this._writer = new exports.WritableStreamDefaultWriter(this)

    return this._writer
  }

  abort(reason = new TypeError('Stream was aborted')) {
    if (this._stream.destroyed) return Promise.resolve()

    if (this.locked) return Promise.reject(new TypeError('Stream is locked'))

    return new Promise((resolve) => this._stream.once('close', resolve).destroy(reason))
  }

  close() {
    if (this._stream.destroyed) return Promise.resolve()

    if (this.locked) return Promise.reject(new TypeError('Stream is locked'))

    return new Promise((resolve) => this._stream.once('close', resolve).end())
  }

  _releaseLock() {
    this._writer = null
  }

  async _write(starting, write, data, cb) {
    await starting

    let err = null
    try {
      await write(data, this._controller)
    } catch (e) {
      err = e
    }
    cb(err)
  }

  async _destroy(closing, cb) {
    let err = null
    try {
      await closing
    } catch (e) {
      err = e
    }
    cb(err)
  }
}

exports.WritableStream = WritableStream

exports.isWritableStream = function isWritableStream(value) {
  if (value instanceof WritableStream) return true

  return (
    typeof value === 'object' &&
    value !== null &&
    value[writableKind] === WritableStream[writableKind]
  )
}

// https://streams.spec.whatwg.org/#transformstreamdefaultcontroller
exports.TransformStreamDefaultController = class TransformStreamDefaultController {
  constructor(stream) {
    this._stream = stream
  }

  get desiredSize() {
    const stream = this._stream._stream

    return stream._readableState.highWaterMark - stream._readableState.buffered
  }

  enqueue(data) {
    this._stream._stream.push(data)
  }

  error(err) {
    this._stream._stream.destroy(err)
  }

  terminate() {
    const stream = this._stream._stream

    stream.push(null)
    stream.destroy(new TypeError('Stream has been terminated'))
  }
}

// https://streams.spec.whatwg.org/#transformstream
class TransformStream {
  static get [transformKind]() {
    return 0 // Compatibility version
  }

  constructor(transformer = {}, writableStrategy = {}, readableStrategy = {}) {
    if (isStreamx(transformer)) {
      this._stream = transformer
    } else {
      const { start, transform, flush } = transformer

      this._stream = new Transform({ ...writableStrategy, ...readableStrategy })

      const controller = new exports.TransformStreamDefaultController(this)

      this._controller = controller

      try {
        let starting = Promise.resolve()

        if (start) starting = forwardError(start.call(this, controller), controller)

        if (transform) {
          this._stream._transform = this._transform.bind(this, starting, transform.bind(this))
        }

        if (flush) {
          this._stream._flush = this._flush.bind(this, flush.call(this, this._controller))
        }
      } catch (err) {
        controller.error(err)
      }
    }

    this._writable = new WritableStream(this._stream)
    this._readable = new ReadableStream(this._stream)
  }

  get [transformKind]() {
    return TransformStream[transformKind]
  }

  get writable() {
    return this._writable
  }

  get readable() {
    return this._readable
  }

  async _transform(starting, transform, data, cb) {
    await starting

    let err = null
    try {
      await transform(data, this._controller)
    } catch (e) {
      err = e
    }
    cb(err)
  }

  async _flush(flush, cb) {
    let err = null
    try {
      await flush
    } catch (e) {
      err = e
    }
    cb(err)
  }
}

exports.TransformStream = TransformStream

exports.isTransformStream = function isTransformStream(value) {
  if (value instanceof TransformStream) return true

  return (
    typeof value === 'object' &&
    value !== null &&
    value[transformKind] === TransformStream[transformKind]
  )
}

async function forwardError(promise, controller) {
  try {
    await promise
  } catch (err) {
    controller.error(err)
  }
}

function noop() {}
module.exports = require.addon()
const { Readable, Writable } = require('bare-stream')
const Signal = require('bare-signals')
const binding = require('./binding')
const constants = require('./lib/constants')

const defaultReadBufferSize = 65536
const empty = Buffer.alloc(0)

exports.ReadStream = class TTYReadStream extends Readable {
  constructor(fd, opts = {}) {
    super()

    const { readBufferSize = defaultReadBufferSize, allowHalfOpen = true } = opts

    this._fd = fd
    this._state = 0
    this._allowHalfOpen = allowHalfOpen
    this._buffer = Buffer.alloc(readBufferSize)

    this._pendingDestroy = null

    this._handle = binding.init(fd, this._buffer, this, noop, this._onread, this._onclose)
  }

  get fd() {
    return this._fd
  }

  get isTTY() {
    return true
  }

  setMode(mode) {
    binding.setMode(this._handle, mode)
    return this
  }

  setRawMode(enabled) {
    return this.setMode(enabled ? constants.mode.RAW : constants.mode.NORMAL)
  }

  _read() {
    if ((this._state & constants.state.READING) === 0) {
      this._state |= constants.state.READING

      binding.resume(this._handle)
    }
  }

  _predestroy() {
    if (this._state & constants.state.CLOSING) return
    this._state |= constants.state.CLOSING

    binding.close(this._handle)
  }

  _destroy(err, cb) {
    if (this._state & constants.state.CLOSING) return cb(err)
    this._state |= constants.state.CLOSING

    this._pendingDestroy = cb

    binding.close(this._handle)
  }

  _continueDestroy() {
    if (this._pendingDestroy === null) return
    const cb = this._pendingDestroy
    this._pendingDestroy = null
    cb(null)
  }

  _onread(err, read) {
    if (err) {
      this.destroy(err)
      return
    }

    if (read === 0) {
      this.push(null)
      if (this._allowHalfOpen === false) this.end()
      return
    }

    const copy = Buffer.allocUnsafe(read)
    copy.set(this._buffer.subarray(0, read))

    if (this.push(copy) === false && this.destroying === false) {
      this._state &= ~constants.state.READING

      binding.pause(this._handle)
    }
  }

  _onclose() {
    this._handle = null

    this._continueDestroy()
  }
}

exports.WriteStream = class TTYWriteStream extends Writable {
  constructor(fd, opts = {}) {
    super()

    this._fd = fd
    this._state = 0
    this._size = null

    this._pendingWrite = null
    this._pendingDestroy = null

    this._handle = binding.init(fd, empty, this, this._onwrite, noop, this._onclose)

    this._size = this.getWindowSize()

    if (TTYWriteStream._streams.size === 0) TTYWriteStream._resize.start()

    TTYWriteStream._streams.add(this)
  }

  get fd() {
    return this._fd
  }

  get isTTY() {
    return true
  }

  get columns() {
    return this._size[0]
  }

  get rows() {
    return this._size[1]
  }

  getWindowSize() {
    return binding.getWindowSize(this._handle)
  }

  _writev(batch, cb) {
    this._pendingWrite = [cb, batch]

    binding.writev(
      this._handle,
      batch.map(({ chunk }) => chunk)
    )
  }

  _predestroy() {
    if (this._state & constants.state.CLOSING) return
    this._state |= constants.state.CLOSING

    binding.close(this._handle)

    TTYWriteStream._streams.delete(this)

    if (TTYWriteStream._streams.size === 0) TTYWriteStream._resize.stop()
  }

  _destroy(err, cb) {
    if (this._state & constants.state.CLOSING) return cb(err)
    this._state |= constants.state.CLOSING

    this._pendingDestroy = cb

    binding.close(this._handle)

    TTYWriteStream._streams.delete(this)

    if (TTYWriteStream._streams.size === 0) TTYWriteStream._resize.stop()
  }

  _continueWrite(err) {
    if (this._pendingWrite === null) return
    const cb = this._pendingWrite[0]
    this._pendingWrite = null
    cb(err)
  }

  _continueDestroy() {
    if (this._pendingDestroy === null) return
    const cb = this._pendingDestroy
    this._pendingDestroy = null
    cb(null)
  }

  _onwrite(err) {
    this._continueWrite(err)
  }

  _onclose() {
    this._handle = null

    this._continueDestroy()
  }

  _onresize() {
    this._size = this.getWindowSize()

    this.emit('resize')
  }

  static _streams = new Set()

  static _resize = new Signal('SIGWINCH')
}

exports.constants = constants

exports.isTTY = binding.isTTY

exports.isatty = exports.isTTY // For Node.js compatibility

exports.WriteStream._resize
  .on('signal', () => {
    for (const stream of exports.WriteStream._streams) {
      stream._onresize()
    }
  })
  .unref()

function noop() {}
const binding = require('../binding')

module.exports = exports = {
  mode: {
    NORMAL: binding.MODE_NORMAL,
    RAW: binding.MODE_RAW,
    IO: binding.MODE_IO || 0
  },

  state: {
    READING: 0x1,
    CLOSING: 0x2
  }
}

/** @deprecated Use `mode.NORMAL` */
exports.MODE_NORMAL = exports.mode.NORMAL
/** @deprecated Use `mode.RAW` */
exports.MODE_RAW = exports.mode.RAW
/** @deprecated Use `mode.IO` */
exports.MODE_IO = exports.mode.IO
{
  "name": "bare-tty",
  "version": "5.1.0",
  "description": "Native TTY streams for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./constants": "./lib/constants.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-tty.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-tty/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-tty#readme",
  "engines": {
    "bare": ">=1.16.0"
  },
  "dependencies": {
    "bare-events": "^2.2.0",
    "bare-signals": "^4.0.0",
    "bare-stream": "^2.0.0"
  },
  "devDependencies": {
    "brittle": "^3.2.1",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = require.addon()
const binding = require('./binding')

const t = binding.constants

class Type {
  constructor(type) {
    this._type = type
  }

  isUndefined() {
    return this._type === t.UNDEFINED
  }

  isNull() {
    return this._type === t.NULL
  }

  isBoolean() {
    return this._type === t.BOOLEAN
  }

  isNumber() {
    return (this._type & 0xff) === t.NUMBER
  }

  isInt32() {
    return (this._type & (0xff | t.INT32)) === (t.NUMBER | t.INT32)
  }

  isUint32() {
    return (this._type & (0xff | t.UINT32)) === (t.NUMBER | t.UINT32)
  }

  isString() {
    return this._type === t.STRING
  }

  isSymbol() {
    return this._type === t.SYMBOL
  }

  isObject() {
    return (this._type & 0xff) === t.OBJECT
  }

  isArray() {
    return this._type === (t.OBJECT | t.ARRAY)
  }

  isArguments() {
    return this._type === (t.OBJECT | t.ARGUMENTS)
  }

  isDate() {
    return this._type === (t.OBJECT | t.DATE)
  }

  isRegExp() {
    return this._type === (t.OBJECT | t.REGEXP)
  }

  isError() {
    return this._type === (t.OBJECT | t.ERROR)
  }

  isPromise() {
    return this._type === (t.OBJECT | t.PROMISE)
  }

  isProxy() {
    return this._type === (t.OBJECT | t.PROXY)
  }

  isGenerator() {
    return this._type === (t.OBJECT | t.GENERATOR)
  }

  isMap() {
    return this._type === (t.OBJECT | t.MAP)
  }

  isSet() {
    return this._type === (t.OBJECT | t.SET)
  }

  isWeakMap() {
    return this._type === (t.OBJECT | t.WEAK_MAP)
  }

  isWeakSet() {
    return this._type === (t.OBJECT | t.WEAK_SET)
  }

  isWeakRef() {
    return this._type === (t.OBJECT | t.WEAK_REF)
  }

  isArrayBuffer() {
    return this._type === (t.OBJECT | t.ARRAYBUFFER)
  }

  isSharedArrayBuffer() {
    return this._type === (t.OBJECT | t.SHAREDARRAYBUFFER)
  }

  isTypedArray() {
    return (this._type & 0xffff) === (t.OBJECT | t.TYPEDARRAY)
  }

  isInt8Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT8ARRAY)
  }

  isUint8Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT8ARRAY)
  }

  isUint8ClampedArray() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT8CLAMPEDARRAY)
  }

  isInt16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT16ARRAY)
  }

  isUint16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT16ARRAY)
  }

  isInt32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT32ARRAY)
  }

  isUint32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT32ARRAY)
  }

  isFloat16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT16ARRAY)
  }

  isFloat32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT32ARRAY)
  }

  isFloat64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT64ARRAY)
  }

  isBigInt64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.BIGINT64ARRAY)
  }

  isBigUint64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.BIGUINT64ARRAY)
  }

  isDataView() {
    return this._type === (t.OBJECT | t.DATAVIEW)
  }

  isModuleNamespace() {
    return this._type === (t.OBJECT | t.MODULE_NAMESPACE)
  }

  isFunction() {
    return (this._type & 0xff) === t.FUNCTION
  }

  isAsyncFunction() {
    return (
      (this._type & (0xff | t.ASYNC_FUNCTION)) ===
      (t.FUNCTION | t.ASYNC_FUNCTION)
    )
  }

  isGeneratorFunction() {
    return (
      (this._type & (0xff | t.GENERATOR_FUNCTION)) ===
      (t.FUNCTION | t.GENERATOR_FUNCTION)
    )
  }

  isExternal() {
    return this._type === t.EXTERNAL
  }

  isBigInt() {
    return this._type === t.BIGINT
  }
}

module.exports = exports = function type(value) {
  switch (typeof value) {
    case 'undefined':
      return new Type(t.UNDEFINED)
    case 'boolean':
      return new Type(t.BOOLEAN)
    case 'number':
      return new Type(
        Number.isSafeInteger(value) ? binding.type(value) : t.NUMBER
      )
    case 'string':
      return new Type(t.STRING)
    case 'symbol':
      return new Type(t.SYMBOL)
    case 'object':
      return new Type(value === null ? t.NULL : binding.type(value))
    case 'function':
      return new Type(binding.type(value))
    case 'bigint':
      return new Type(t.BIGINT)
  }
}

exports.createTag = function createTag(...components) {
  const tag = new Uint32Array(4)
  for (let i = 0; i < 4; i++) tag[i] = components[i] || 0
  return tag
}

exports.addTag = function addTag(object, tag) {
  binding.addTag(object, tag)
}

exports.checkTag = function checkTag(object, tag) {
  return binding.checkTag(object, tag)
}
{
  "name": "bare-type",
  "version": "1.1.0",
  "description": "Cross-realm type predicates for Bare",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-type.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-type/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-type#readme",
  "engines": {
    "bare": ">=1.2.0"
  },
  "devDependencies": {
    "brittle": "^3.4.0",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
module.exports = require.addon()
const path = require('bare-path')
const binding = require('./binding')
const errors = require('./lib/errors')
const URLSearchParams = require('./lib/url-search-params')

const kind = Symbol.for('bare.url.kind')

const isWindows = Bare.platform === 'win32'

class URL {
  static get [kind]() {
    return 0 // Compatibility version
  }

  constructor(input, base, opts = {}) {
    if (arguments.length === 0) throw errors.INVALID_URL()

    input = String(input)

    if (base !== undefined) base = String(base)

    this._components = new Uint32Array(8)

    this._parse(input, base, opts.throw !== false)

    if (this._href) this._params = new URLSearchParams(this.search, this)
  }

  get [kind]() {
    return URL[kind]
  }

  // https://url.spec.whatwg.org/#dom-url-href

  get href() {
    return this._href
  }

  set href(value) {
    this._update(value)

    this._params._parse(this.search)
  }

  // https://url.spec.whatwg.org/#dom-url-protocol

  get protocol() {
    return this._slice(0, this._components[0]) + ':'
  }

  set protocol(value) {
    this._update(this._replace(value.replace(/:+$/, ''), 0, this._components[0]))
  }

  // https://url.spec.whatwg.org/#dom-url-username

  get username() {
    return this._slice(this._components[0] + 3 /* :// */, this._components[1])
  }

  set username(value) {
    if (cannotHaveCredentialsOrPort(this)) {
      return
    }

    if (this.username === '') value += '@'

    this._update(this._replace(value, this._components[0] + 3 /* :// */, this._components[1]))
  }

  // https://url.spec.whatwg.org/#dom-url-password

  get password() {
    return this._href.slice(this._components[1] + 1 /* : */, this._components[2] - 1 /* @ */)
  }

  set password(value) {
    if (cannotHaveCredentialsOrPort(this)) {
      return
    }

    let start = this._components[1] + 1 /* : */
    let end = this._components[2] - 1 /* @ */

    if (this.password === '') {
      value = ':' + value
      start--
    }

    if (this.username === '') {
      value += '@'
      end++
    }

    this._update(this._replace(value, start, end))
  }

  // https://url.spec.whatwg.org/#dom-url-host

  get host() {
    return this._slice(this._components[2], this._components[5])
  }

  set host(value) {
    if (hasOpaquePath(this)) {
      return
    }

    this._update(
      this._replace(value, this._components[2], this._components[value.includes(':') ? 5 : 3])
    )
  }

  // https://url.spec.whatwg.org/#dom-url-hostname

  get hostname() {
    return this._slice(this._components[2], this._components[3])
  }

  set hostname(value) {
    if (hasOpaquePath(this)) {
      return
    }

    this._update(this._replace(value, this._components[2], this._components[3]))
  }

  // https://url.spec.whatwg.org/#dom-url-port

  get port() {
    return this._slice(this._components[3] + 1 /* : */, this._components[5])
  }

  set port(value) {
    if (cannotHaveCredentialsOrPort(this)) {
      return
    }

    let start = this._components[3] + 1 /* : */

    if (this.port === '') {
      value = ':' + value
      start--
    }

    this._update(this._replace(value, start, this._components[5]))
  }

  // https://url.spec.whatwg.org/#dom-url-pathname

  get pathname() {
    return this._slice(this._components[5], this._components[6] - 1 /* ? */)
  }

  set pathname(value) {
    if (hasOpaquePath(this)) {
      return
    }

    if (value[0] !== '/' && value[0] !== '\\') {
      value = '/' + value
    }

    this._update(this._replace(value, this._components[5], this._components[6] - 1 /* ? */))
  }

  // https://url.spec.whatwg.org/#dom-url-search

  get search() {
    return this._slice(this._components[6] - 1 /* ? */, this._components[7] - 1 /* # */)
  }

  set search(value) {
    if (value && value[0] !== '?') value = '?' + value

    this._update(
      this._replace(value, this._components[6] - 1 /* ? */, this._components[7] - 1 /* # */)
    )

    this._params._parse(this.search)
  }

  // https://url.spec.whatwg.org/#dom-url-searchparams

  get searchParams() {
    return this._params
  }

  // https://url.spec.whatwg.org/#dom-url-hash

  get hash() {
    return this._slice(this._components[7] - 1 /* # */)
  }

  set hash(value) {
    if (value && value[0] !== '#') value = '#' + value

    this._update(this._replace(value, this._components[7] - 1 /* # */))
  }

  toString() {
    return this._href
  }

  toJSON() {
    return this._href
  }

  [Symbol.for('bare.inspect')]() {
    return {
      __proto__: { constructor: URL },

      href: this.href,
      protocol: this.protocol,
      username: this.username,
      password: this.password,
      host: this.host,
      hostname: this.hostname,
      port: this.port,
      pathname: this.pathname,
      search: this.search,
      searchParams: this.searchParams,
      hash: this.hash
    }
  }

  _slice(start, end = this._href.length) {
    return this._href.slice(start, end)
  }

  _replace(replacement, start, end = this._href.length) {
    return this._slice(0, start) + replacement + this._slice(end)
  }

  _parse(input, base, shouldThrow) {
    try {
      this._href = binding.parse(
        String(input),
        base ? String(base) : null,
        this._components,
        shouldThrow
      )
    } catch (err) {
      if (err instanceof TypeError) throw err

      throw errors.INVALID_URL(`Invalid URL '${input}'`, input)
    }
  }

  _update(input) {
    try {
      this._parse(input, null, true)
    } catch (err) {
      if (err instanceof TypeError) throw err
    }
  }
}

module.exports = exports = URL

// https://url.spec.whatwg.org/#url-opaque-path
function hasOpaquePath(url) {
  return url.pathname[0] !== '/'
}

// https://url.spec.whatwg.org/#cannot-have-a-username-password-port
function cannotHaveCredentialsOrPort(url) {
  return url.hostname === '' || url.protocol === 'file:'
}

exports.URL = URL
exports.URLSearchParams = URLSearchParams

exports.errors = errors

exports.isURL = function isURL(value) {
  if (value instanceof URL) return true

  return typeof value === 'object' && value !== null && value[kind] === URL[kind]
}

exports.isURLSearchParams = URLSearchParams.isURLSearchParams

// https://url.spec.whatwg.org/#dom-url-parse
exports.parse = function parse(input, base) {
  const url = new URL(input, base, { throw: false })
  return url._href ? url : null
}

// https://url.spec.whatwg.org/#dom-url-canparse
exports.canParse = function canParse(input, base) {
  return binding.canParse(String(input), base ? String(base) : null)
}

exports.fileURLToPath = function fileURLToPath(url) {
  if (typeof url === 'string') {
    url = new URL(url)
  }

  if (url.protocol !== 'file:') {
    throw errors.INVALID_URL_SCHEME('The URL must use the file: protocol')
  }

  if (isWindows) {
    if (/%2f|%5c/i.test(url.pathname)) {
      throw errors.INVALID_FILE_URL_PATH(
        'The file: URL path must not include encoded \\ or / characters'
      )
    }
  } else {
    if (url.hostname) {
      throw errors.INVALID_FILE_URL_HOST("The file: URL host must be 'localhost' or empty")
    }

    if (/%2f/i.test(url.pathname)) {
      throw errors.INVALID_FILE_URL_PATH('The file: URL path must not include encoded / characters')
    }
  }

  if (/%00/i.test(url.pathname)) {
    throw errors.INVALID_FILE_URL_PATH('The file: URL path must not include encoded NUL characters')
  }

  const pathname = path.normalize(decodeURIComponent(url.pathname))

  if (isWindows) {
    if (url.hostname) return '\\\\' + url.hostname + pathname

    const letter = pathname.charCodeAt(1) | 0x20

    if (letter < 0x61 /* a */ || letter > 0x7a /* z */ || pathname.charCodeAt(2) !== 0x3a /* : */) {
      throw errors.INVALID_FILE_URL_PATH('The file: URL path must be absolute')
    }

    return pathname.slice(1)
  }

  return pathname
}

exports.pathToFileURL = function pathToFileURL(pathname) {
  let resolved = path.resolve(pathname)

  if (pathname[pathname.length - 1] === '/') {
    resolved += '/'
  } else if (isWindows && pathname[pathname.length - 1] === '\\') {
    resolved += '\\'
  }

  resolved = resolved
    .replaceAll('%', '%25') // Must be first
    .replaceAll('#', '%23')
    .replaceAll('?', '%3f')
    .replaceAll('\n', '%0a')
    .replaceAll('\r', '%0d')
    .replaceAll('\t', '%09')

  if (!isWindows) {
    resolved = resolved.replaceAll('\\', '%5c')
  }

  return new URL('file:' + resolved)
}

exports.format = function format(parts) {
  const { protocol, auth, host, hostname, port, pathname, search, query, hash, slashes } = parts

  let result = ''

  if (typeof protocol === 'string') {
    result += protocol

    if (protocol[protocol.length - 1] !== ':') {
      result += ':'
    }

    if (slashes === true || /https?|ftp|gopher|file/.test(protocol)) {
      result += '//'
    }
  }

  if (typeof auth === 'string') {
    if (host || hostname) result += auth + '@'
  }

  if (typeof host === 'string') result += host
  else {
    result += hostname

    if (port) result += ':' + port
  }

  if (typeof pathname === 'string' && pathname !== '') {
    if (pathname[0] !== '/') result += '/'
    result += pathname
  }

  if (typeof search === 'string') {
    if (search[0] !== '?') result += '?'
    result += search
  } else if (typeof query === 'object' && query !== null) {
    result += '?' + new URLSearchParams(query)
  }

  if (typeof hash === 'string') {
    if (hash[0] !== '#') result += '#'
    result += hash
  }

  return result
}
module.exports = class URLError extends Error {
  constructor(msg, fn = URLError, code = fn.name) {
    super(`${code}: ${msg}`)

    this.code = code

    if (Error.captureStackTrace) Error.captureStackTrace(this, fn)
  }

  get name() {
    return 'URLError'
  }

  static INVALID_URL(msg, input) {
    const err = new URLError(msg, URLError.INVALID_URL)

    err.input = input

    return err
  }

  static INVALID_URL_SCHEME(msg = 'Invalid URL') {
    return new URLError(msg, URLError.INVALID_URL_SCHEME)
  }

  static INVALID_FILE_URL_HOST(msg = 'Invalid file: URL host') {
    return new URLError(msg, URLError.INVALID_FILE_URL_HOST)
  }

  static INVALID_FILE_URL_PATH(msg = 'Invalid file: URL path') {
    return new URLError(msg, URLError.INVALID_FILE_URL_PATH)
  }
}
const kind = Symbol.for('bare.url.search-params.kind')

class URLSearchParams {
  static _urls = new WeakMap()

  static get [kind]() {
    return 0 // Compatibility version
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-urlsearchparams
  constructor(init, url = null) {
    this._params = new Map()

    if (url) URLSearchParams._urls.set(this, url)

    if (typeof init === 'string') {
      this._parse(init)
    } else if (init) {
      for (const [name, value] of typeof init[Symbol.iterator] === 'function'
        ? init
        : Object.entries(init)) {
        this.append(name, value)
      }
    }
  }

  get [kind]() {
    return URLSearchParams[kind]
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-size
  get size() {
    return this._params.length
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-append
  append(name, value = null) {
    if (value === null) return

    let list = this._params.get(name)

    if (list === undefined) {
      list = []
      this._params.set(name, list)
    }

    list.push(value)

    this._update()
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-delete
  delete(name, value = null) {
    if (value === null) this._params.delete(name)
    else {
      let list = this._params.get(name)

      if (list === undefined) return

      list = list.filter((found) => found !== value)

      if (list.length === 0) this._params.delete(name)
      else this._params.set(name, list)
    }

    this._update()
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-get
  get(name) {
    const list = this._params.get(name)

    if (list === undefined) return null

    return list[0]
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-getall
  getAll(name) {
    const list = this._params.get(name)

    if (list === undefined) return []

    return Array.from(list)
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-has
  has(name, value = null) {
    const list = this._params.get(name)

    if (list === undefined) return false

    if (value === null) return true

    return list.includes(value)
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-set
  set(name, value = null) {
    if (value === null) this._params.delete(name)
    else this._params.set(name, [value])

    this._update()
  }

  toString() {
    return this._serialize()
  }

  toJSON() {
    return [...this]
  }

  *[Symbol.iterator]() {
    for (const [name, values] of this._params) {
      for (const value of values) yield [name, value]
    }
  }

  [Symbol.for('bare.inspect')]() {
    const object = {
      __proto__: { constructor: URLSearchParams }
    }

    for (const [name, values] of this._params) {
      if (values.length === 1) object[name] = values[0]
      else object[name] = values
    }

    return object
  }

  // https://url.spec.whatwg.org/#concept-urlsearchparams-update
  _update() {
    const url = URLSearchParams._urls.get(this)

    if (url === undefined) return

    url.search = this._serialize()
  }

  // https://url.spec.whatwg.org/#concept-urlencoded-parser
  _parse(input) {
    if (input[0] === '?') input = input.substring(1)

    this._params = new Map()

    for (let sequence of input.split('&')) {
      if (sequence.length === 0) continue

      sequence = sequence.replace(/\+/g, ' ')

      let i = sequence.indexOf('=')
      if (i === -1) i = sequence.length

      const name = decodeURIComponent(sequence.substring(0, i))
      const value = decodeURIComponent(sequence.substring(i + 1, sequence.length))

      let list = this._params.get(name)

      if (list === undefined) {
        list = []
        this._params.set(name, list)
      }

      list.push(value)
    }
  }

  // https://url.spec.whatwg.org/#concept-urlencoded-serializer
  _serialize() {
    let output = ''

    for (let [name, values] of this._params) {
      name = encodeURIComponent(name)

      for (const value of values) {
        if (output) output += '&'

        output += name + '=' + encodeURIComponent(value)
      }
    }

    return output
  }
}

module.exports = exports = URLSearchParams

exports.isURLSearchParams = function isURLSearchParams(value) {
  if (value instanceof URLSearchParams) return true

  return typeof value === 'object' && value !== null && value[kind] === URLSearchParams[kind]
}
{
  "name": "bare-url",
  "version": "2.4.5",
  "description": "WHATWG URL implementation for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "global.js",
    "global.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-url.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-url/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-url",
  "dependencies": {
    "bare-path": "^3.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "cmake-bare": "^1.1.6",
    "cmake-fetch": "^1.0.0",
    "lunte": "^1.6.0",
    "prettier": "^3.3.3",
    "prettier-config-holepunch": "^2.0.0"
  }
}
const FACTOR = new Uint16Array(8)

function factor4096 (i, n) {
  while (n > 0) {
    const f = i & 4095
    FACTOR[--n] = f
    i = (i - f) / 4096
  }
  return FACTOR
}

module.exports = class BigSparseArray {
  constructor () {
    this.tiny = new TinyArray()
    this.maxLength = 4096
    this.factor = 1
  }

  set (index, val) {
    if (val !== undefined) {
      while (index >= this.maxLength) {
        this.maxLength *= 4096
        this.factor++
        if (!this.tiny.isEmptyish()) {
          const t = new TinyArray()
          t.set(0, this.tiny)
          this.tiny = t
        }
      }
    }

    const f = factor4096(index, this.factor)
    const last = this.factor - 1

    let tiny = this.tiny
    for (let i = 0; i < last; i++) {
      const next = tiny.get(f[i])
      if (next === undefined) {
        if (val === undefined) return
        tiny = tiny.set(f[i], new TinyArray())
      } else {
        tiny = next
      }
    }

    return tiny.set(f[last], val)
  }

  get (index) {
    if (index >= this.maxLength) return

    const f = factor4096(index, this.factor)
    const last = this.factor - 1

    let tiny = this.tiny
    for (let i = 0; i < last; i++) {
      tiny = tiny.get(f[i])
      if (tiny === undefined) return
    }

    return tiny.get(f[last])
  }
}

class TinyArray {
  constructor () {
    this.s = 0
    this.b = new Array(1)
    this.f = new Uint16Array(1)
  }

  isEmptyish () {
    return this.b.length === 1 && this.b[0] === undefined
  }

  get (i) {
    if (this.s === 12) return this.b[i]
    const f = i >>> this.s
    const r = i & (this.b.length - 1)
    return this.f[r] === f ? this.b[r] : undefined
  }

  set (i, v) {
    while (this.s !== 12) {
      const f = i >>> this.s
      const r = i & (this.b.length - 1)
      const o = this.b[r]

      if (o === undefined || f === this.f[r]) {
        this.b[r] = v
        this.f[r] = f
        return v
      }

      this.grow()
    }

    this.b[i] = v
    return v
  }

  grow () {
    const os = this.s
    const ob = this.b
    const of = this.f

    this.s += 4
    this.b = new Array(this.b.length << 4)
    this.f = this.s === 12 ? null : new Uint8Array(this.b.length)

    const m = this.b.length - 1

    for (let or = 0; or < ob.length; or++) {
      if (ob[or] === undefined) continue

      const i = of[or] << os | or
      const f = i >>> this.s
      const r = i & m

      this.b[r] = ob[or]
      if (this.s !== 12) this.f[r] = f
    }
  }
}
{
  "name": "big-sparse-array",
  "version": "1.0.3",
  "description": "A sparse array optimised for low memory whilst still being fast",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "brittle": "^3.1.1",
    "standard": "^16.0.3"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/big-sparse-array.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/big-sparse-array/issues"
  },
  "homepage": "https://github.com/mafintosh/big-sparse-array"
}
const b4a = require('b4a')

function byteLength (size) {
  return Math.ceil(size / 8)
}

function get (buffer, bit) {
  const n = buffer.BYTES_PER_ELEMENT * 8

  const offset = bit & (n - 1)
  const i = (bit - offset) / n

  return (buffer[i] & (1 << offset)) !== 0
}

function set (buffer, bit, value = true) {
  const n = buffer.BYTES_PER_ELEMENT * 8

  const offset = bit & (n - 1)
  const i = (bit - offset) / n
  const mask = 1 << offset

  if (value) {
    if ((buffer[i] & mask) !== 0) return false
  } else {
    if ((buffer[i] & mask) === 0) return false
  }

  buffer[i] ^= mask
  return true
}

function setRange (buffer, start, end, value = true) {
  const n = buffer.BYTES_PER_ELEMENT * 8

  let remaining = end - start
  let offset = start & (n - 1)
  let i = (start - offset) / n

  let changed = false

  while (remaining > 0) {
    const mask = (2 ** Math.min(remaining, n - offset) - 1) << offset

    if (value) {
      if ((buffer[i] & mask) !== mask) {
        buffer[i] |= mask
        changed = true
      }
    } else {
      if ((buffer[i] & mask) !== 0) {
        buffer[i] &= ~mask
        changed = true
      }
    }

    remaining -= n - offset
    offset = 0
    i++
  }

  return changed
}

function fill (buffer, value, start = 0, end = buffer.byteLength * 8) {
  const n = buffer.BYTES_PER_ELEMENT * 8
  let i, j

  {
    const offset = start & (n - 1)
    i = (start - offset) / n

    if (offset !== 0) {
      const mask = (2 ** Math.min(n - offset, end - start) - 1) << offset

      if (value) buffer[i] |= mask
      else buffer[i] &= ~mask

      i++
    }
  }

  {
    const offset = end & (n - 1)
    j = (end - offset) / n

    if (offset !== 0 && j >= i) {
      const mask = (2 ** offset) - 1

      if (value) buffer[j] |= mask
      else buffer[j] &= ~mask
    }
  }

  return buffer.fill(value ? (2 ** n) - 1 : 0, i, j)
}

function toggle (buffer, bit) {
  const n = buffer.BYTES_PER_ELEMENT * 8

  const offset = bit & (n - 1)
  const i = (bit - offset) / n
  const mask = 1 << offset

  buffer[i] ^= mask
  return (buffer[i] & mask) !== 0
}

function remove (buffer, bit) {
  return set(buffer, bit, false)
}

function removeRange (buffer, start, end) {
  return setRange(buffer, start, end, false)
}

function indexOf (buffer, value, position = 0) {
  for (let i = position, n = buffer.byteLength * 8; i < n; i++) {
    if (get(buffer, i) === value) return i
  }

  return -1
}

function lastIndexOf (buffer, value, position = buffer.byteLength * 8 - 1) {
  for (let i = position; i >= 0; i--) {
    if (get(buffer, i) === value) return i
  }

  return -1
}

function of (...bits) {
  return from(bits)
}

function from (bits) {
  const buffer = b4a.alloc(byteLength(bits.length))
  for (let i = 0; i < bits.length; i++) set(buffer, i, bits[i])
  return buffer
}

function * iterator (buffer) {
  for (let i = 0, n = buffer.byteLength * 8; i < n; i++) yield get(buffer, i)
}

module.exports = {
  byteLength,
  get,
  set,
  setRange,
  fill,
  toggle,
  remove,
  removeRange,
  indexOf,
  lastIndexOf,
  of,
  from,
  iterator
}
{
  "name": "bits-to-bytes",
  "version": "1.3.0",
  "description": "Functions for doing bit manipulation of typed arrays",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "scripts": {
    "test": "standard && brittle test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bits-to-bytes.git"
  },
  "author": "Kasper Isager Dalsgarð <kasper@funktionel.co>",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/holepunchto/bits-to-bytes/issues"
  },
  "homepage": "https://github.com/holepunchto/bits-to-bytes#readme",
  "dependencies": {
    "b4a": "^1.5.0"
  },
  "devDependencies": {
    "brittle": "^2.3.1",
    "standard": "^17.0.0"
  }
}
const EventEmitter = require('events')
const Protomux = require('protomux')
const { Readable } = require('streamx')
const sodium = require('sodium-universal')
const b4a = require('b4a')
const c = require('compact-encoding')
const bitfield = require('compact-encoding-bitfield')
const bits = require('bits-to-bytes')
const errors = require('./lib/errors')

exports.Server = class BlindRelayServer extends EventEmitter {
  constructor(opts = {}) {
    super()

    const { createStream } = opts

    this._createStream = createStream
    this._pairing = new Map()
    this._activePairingRefs = new Map()
    this._sessions = new Set()
    this.stats = createStats()
  }

  get sessions() {
    return this._sessions[Symbol.iterator]()
  }

  accept(stream, opts) {
    const session = new BlindRelaySession(this, stream, opts)

    this._sessions.add(session)
    this.stats.sessions.accepted++

    return session
  }

  async close() {
    const ending = []

    for (const session of this._sessions) {
      ending.push(session.end())
    }

    await Promise.all(ending)

    this._pairing.clear()
  }

  _trackActiveLink(keyString) {
    const refs = this._activePairingRefs.get(keyString) || 0

    if (refs === 0) this.stats.pairings.active++

    this._activePairingRefs.set(keyString, refs + 1)
  }

  _untrackActiveLink(keyString) {
    const refs = this._activePairingRefs.get(keyString)

    if (refs === undefined) return

    if (refs === 1) {
      this._activePairingRefs.delete(keyString)
      this.stats.pairings.active--
    } else {
      this._activePairingRefs.set(keyString, refs - 1)
    }
  }
}

class BlindRelaySession extends EventEmitter {
  constructor(server, stream, opts = {}) {
    super()

    const { id, handshake, handshakeEncoding } = opts

    this._server = server
    this._mux = Protomux.from(stream)

    this._channel = this._mux.createChannel({
      protocol: 'blind-relay',
      id,
      handshake: handshake ? handshakeEncoding || c.raw : null,
      onopen: this._onopen.bind(this),
      onclose: this._onclose.bind(this),
      ondestroy: this._ondestroy.bind(this)
    })

    this._pair = this._channel.addMessage({
      encoding: m.pair,
      onmessage: this._onpair.bind(this)
    })

    this._unpair = this._channel.addMessage({
      encoding: m.unpair,
      onmessage: this._onunpair.bind(this)
    })

    this._ending = null
    this._destroyed = false
    this._error = null
    this._pairing = new Set()
    this._links = new Map()

    this._onerror = (err) => {
      this._server.stats.streams.errors++
      this.emit('error', err)
    }

    this._channel.open(handshake)
  }

  get closed() {
    return this._channel.closed
  }

  get mux() {
    return this._mux
  }

  get stream() {
    return this._mux.stream
  }

  _onopen() {
    this._server.stats.sessions.opened++
    this.emit('open')
  }

  _onclose() {
    this._ending = Promise.resolve()

    const err = this._error || errors.CHANNEL_CLOSED()
    this._server.stats.pairings.cancelled += this._pairing.size

    for (const token of this._pairing) {
      if (this._server._pairing.delete(token.toString('hex'))) {
        this._server.stats.pairings.pending--
      }
    }

    for (const link of this._links.values()) {
      link.destroy(err)
    }

    this._pairing.clear()
    this._links.clear()

    this._server._sessions.delete(this)
    this._server.stats.sessions.closed++

    this.emit('close')
  }

  _ondestroy() {
    this._destroyed = true
    this.emit('destroy')
  }

  _onpair({ isInitiator, token, id: remoteId }) {
    const keyString = token.toString('hex')

    let pair = this._server._pairing.get(keyString)

    if (pair === undefined) {
      pair = new BlindRelayPair(token)
      this._server._pairing.set(keyString, pair)
      this._server.stats.pairings.pending++
    } else if (pair.links[+isInitiator]) return

    this._pairing.add(keyString)
    this._server.stats.pairings.requested++

    pair.links[+isInitiator] = new BlindRelayLink(this, isInitiator, remoteId)

    if (!pair.paired) return

    this._server._pairing.delete(keyString)
    this._server.stats.pairings.pending--
    this._server.stats.pairings.matched++

    // 1st pass: Create the raw streams needed for each end of the link.
    for (const link of pair.links) {
      link.createStream()
    }

    // 2nd pass: Connect the raw streams and set up handlers.
    for (const link of pair.links) {
      link.remote = pair.remote(link.isInitiator)
      link.activate(keyString)
    }

    // 3rd pass: Let either end of the link know the streams were set up.
    for (const { isInitiator, session, remoteId, stream } of pair.links) {
      session._pair.send({
        isInitiator,
        token,
        id: stream.id,
        seq: 0
      })

      session._endMaybe()

      session.emit('pair', isInitiator, token, stream, remoteId)
    }
  }

  _onunpair({ token }) {
    const keyString = token.toString('hex')

    const pair = this._server._pairing.get(keyString)

    if (pair) {
      for (const link of pair.links) {
        if (link) link.session._pairing.delete(keyString)
      }

      this._server._pairing.delete(keyString)
      this._server.stats.pairings.pending--
      this._server.stats.pairings.cancelled++
      return
    }

    const link = this._links.get(keyString)

    if (link) {
      link.destroyPair(errors.PAIRING_CANCELLED())
      this._server.stats.pairings.cancelled++
    }
  }

  cork() {
    this._channel.cork()
  }

  uncork() {
    this._channel.uncork()
  }

  async end() {
    if (this._ending) return this._ending

    this._ending = EventEmitter.once(this, 'close')
    this._endMaybe()

    return this._ending
  }

  _endMaybe() {
    if (this._ending && this._pairing.size === 0) {
      this._channel.close()
    }
  }

  destroy(err) {
    if (this._destroyed) return
    this._destroyed = true

    this._error = err || errors.CHANNEL_DESTROYED()
    this._channel.close()
  }
}

class BlindRelayPair {
  constructor(token) {
    this.token = token
    this.links = [null, null]
  }

  get paired() {
    return this.links[0] !== null && this.links[1] !== null
  }

  remote(isInitiator) {
    return this.links[isInitiator ? 0 : 1]
  }
}

class BlindRelayLink {
  constructor(session, isInitiator, remoteId) {
    this.session = session
    this.isInitiator = isInitiator
    this.remoteId = remoteId
    this.stream = null
    this.remote = null
    this.keyString = null
    this._onclose = null
  }

  createStream() {
    if (this.stream) return

    this.stream = this.session._server._createStream({
      firewall: this._onfirewall.bind(this)
    })
  }

  activate(keyString) {
    const stream = this.stream

    this.keyString = keyString
    this._onclose = () => {
      if (this.stream !== stream) return

      this.stream = null
      unlink(this)
      this.session._links.delete(keyString)
      this.session._server._untrackActiveLink(keyString)
      this.session._server.stats.streams.closed++
    }

    stream.on('error', this.session._onerror).on('close', this._onclose).relayTo(this.remote.stream)

    this.session._pairing.delete(keyString)
    this.session._links.set(keyString, this)
    this.session._server._trackActiveLink(keyString)
    this.session._server.stats.streams.opened++
  }

  destroy(err) {
    const stream = this.stream

    if (!stream) return

    this.stream = null

    stream.off('close', this._onclose)
    this._onclose = null

    stream.off('error', this.session._onerror)
    unlink(this)
    this.session._links.delete(this.keyString)
    this.session._server._untrackActiveLink(this.keyString)
    this.session._server.stats.streams.closed++
    stream.on('error', noop).destroy(err)
  }

  destroyPair(err) {
    const remote = this.remote

    this.destroy(err)
    if (remote) remote.destroy(err)
  }

  _onfirewall(socket, port, host) {
    this.stream.connect(socket, this.remoteId, port, host)

    return false
  }
}

exports.Client = class BlindRelayClient extends EventEmitter {
  static _clients = new WeakMap()

  static from(stream, opts) {
    let client = this._clients.get(stream)
    if (client) return client
    client = new this(stream, opts)
    this._clients.set(stream, client)
    return client
  }

  constructor(stream, opts = {}) {
    super()

    const { id, handshake, handshakeEncoding } = opts

    this._mux = Protomux.from(stream)

    this._channel = this._mux.createChannel({
      protocol: 'blind-relay',
      id,
      handshake: handshake ? handshakeEncoding || c.raw : null,
      onopen: this._onopen.bind(this),
      onclose: this._onclose.bind(this),
      ondestroy: this._ondestroy.bind(this)
    })

    this._pair = this._channel.addMessage({
      encoding: m.pair,
      onmessage: this._onpair.bind(this)
    })

    this._unpair = this._channel.addMessage({
      encoding: m.unpair
    })

    this._ending = false
    this._destroyed = false
    this._error = null
    this._requests = new Map()

    this._channel.open(handshake)
  }

  get closed() {
    return this._channel.closed
  }

  get mux() {
    return this._mux
  }

  get stream() {
    return this._mux.stream
  }

  get requests() {
    return this._requests.values()
  }

  _onopen() {
    this.emit('open')
  }

  _onclose() {
    this._ending = Promise.resolve()

    const err = this._error || errors.CHANNEL_CLOSED()

    for (const request of this._requests.values()) {
      request.destroy(err)
    }

    this._requests.clear()

    this.constructor._clients.delete(this.stream)

    this.emit('close')
  }

  _ondestroy() {
    this._destroyed = true
    this.emit('destroy')
  }

  _onpair({ isInitiator, token, id: remoteId }) {
    const request = this._requests.get(token.toString('hex'))

    if (request === undefined || request.isInitiator !== isInitiator) return

    request.push(remoteId)
    request.push(null)

    this.emit('pair', request.isInitiator, request.token, request.stream, remoteId)
  }

  pair(isInitiator, token, stream) {
    if (this._destroyed) throw errors.CHANNEL_DESTROYED()

    const keyString = token.toString('hex')

    if (this._requests.has(keyString)) throw errors.ALREADY_PAIRING()

    const request = new BlindRelayRequest(this, isInitiator, token, stream)

    this._requests.set(keyString, request)

    return request
  }

  unpair(token) {
    if (this._destroyed) throw errors.CHANNEL_DESTROYED()

    const request = this._requests.get(token.toString('hex'))

    if (request) request.destroy(errors.PAIRING_CANCELLED())

    this._unpair.send({ token })
  }

  cork() {
    this._channel.cork()
  }

  uncork() {
    this._channel.uncork()
  }

  async end() {
    if (this._ending) return this._ending

    this._ending = EventEmitter.once(this, 'close')
    this._endMaybe()

    return this._ending
  }

  _endMaybe() {
    if (this._ending && this._requests.size === 0) {
      this._channel.close()
    }
  }

  destroy(err) {
    if (this._destroyed) return
    this._destroyed = true

    this._error = err || errors.CHANNEL_DESTROYED()
    this._channel.close()
  }
}

class BlindRelayRequest extends Readable {
  constructor(client, isInitiator, token, stream) {
    super()

    this.client = client
    this.isInitiator = isInitiator
    this.token = token
    this.stream = stream
  }

  _open(cb) {
    if (this.client._destroyed) return cb(errors.CHANNEL_DESTROYED())

    this.client._pair.send({
      isInitiator: this.isInitiator,
      token: this.token,
      id: this.stream.id,
      seq: 0
    })

    cb(null)
  }

  _destroy(cb) {
    this.client._requests.delete(this.token.toString('hex'))

    cb(null)

    this.client._endMaybe()
  }
}

exports.token = function token(buf = b4a.allocUnsafe(32)) {
  sodium.randombytes_buf(buf)
  return buf
}

function noop() {}

function unlink(link) {
  const remote = link.remote

  link.remote = null

  if (remote && remote.remote === link) {
    remote.remote = null
  }
}

function createStats() {
  const stats = {
    sessions: {
      accepted: 0,
      opened: 0,
      closed: 0,
      get active() {
        return this.accepted - this.closed
      }
    },
    pairings: {
      requested: 0,
      matched: 0,
      cancelled: 0,
      pending: 0,
      active: 0
    },
    streams: {
      opened: 0,
      closed: 0,
      errors: 0,
      get active() {
        return this.opened - this.closed
      }
    }
  }

  return stats
}

const m = (exports.messages = {})

const flags = bitfield(7)

m.pair = {
  preencode(state, m) {
    flags.preencode(state)
    c.fixed32.preencode(state, m.token)
    c.uint.preencode(state, m.id)
    c.uint.preencode(state, m.seq)
  },
  encode(state, m) {
    flags.encode(state, bits.of(m.isInitiator))
    c.fixed32.encode(state, m.token)
    c.uint.encode(state, m.id)
    c.uint.encode(state, m.seq)
  },
  decode(state) {
    const [isInitiator] = bits.iterator(flags.decode(state))

    return {
      isInitiator,
      token: c.fixed32.decode(state),
      id: c.uint.decode(state),
      seq: c.uint.decode(state)
    }
  }
}

m.unpair = {
  preencode(state, m) {
    flags.preencode(state)
    c.fixed32.preencode(state, m.token)
  },
  encode(state, m) {
    flags.encode(state, bits.of())
    c.fixed32.encode(state, m.token)
  },
  decode(state) {
    flags.decode(state)

    return {
      token: c.fixed32.decode(state)
    }
  }
}
module.exports = class BlindRelayError extends Error {
  constructor(msg, code, fn = BlindRelayError) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'BlindRelayError'
  }

  static DUPLICATE_CHANNEL(msg = 'Duplicate channel') {
    return new BlindRelayError(msg, 'DUPLICATE_CHANNEL', BlindRelayError.DUPLICATE_CHANNEL)
  }

  static CHANNEL_CLOSED(msg = 'Channel closed') {
    return new BlindRelayError(msg, 'CHANNEL_CLOSED', BlindRelayError.CHANNEL_CLOSED)
  }

  static CHANNEL_DESTROYED(msg = 'Channel destroyed') {
    return new BlindRelayError(msg, 'CHANNEL_DESTROYED', BlindRelayError.CHANNEL_DESTROYED)
  }

  static ALREADY_PAIRING(msg = 'Already pairing') {
    return new BlindRelayError(msg, 'ALREADY_PAIRING', BlindRelayError.ALREADY_PAIRING)
  }

  static PAIRING_CANCELLED(msg = 'Pairing cancelled') {
    return new BlindRelayError(msg, 'PAIRING_CANCELLED', BlindRelayError.PAIRING_CANCELLED)
  }
}
{
  "name": "blind-relay",
  "version": "1.6.1",
  "description": "Blind relay for UDX over Protomux channels",
  "main": "index.js",
  "files": [
    "index.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:bare",
    "test:bare": "brittle-bare --coverage test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/blind-relay.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/blind-relay/issues"
  },
  "homepage": "https://github.com/holepunchto/blind-relay#readme",
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "dependencies": {
    "b4a": "^1.6.4",
    "bare-events": "^2.2.0",
    "bits-to-bytes": "^1.3.0",
    "compact-encoding": "^3.0.0",
    "compact-encoding-bitfield": "^1.0.0",
    "protomux": "^3.5.1",
    "sodium-universal": "^5.0.0",
    "streamx": "^2.15.1"
  },
  "devDependencies": {
    "brittle": "^3.2.1",
    "hyperdht": "^6.6.1",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "udx-native": "^1.6.1"
  }
}
// https://ipinfo.io/bogon

const b4a = require('b4a')
const c = require('compact-encoding')

module.exports = exports = function isBogon (ip) {
  return isBogonIP(ensureBuffer(ip))
}

exports.isBogon = exports

exports.isPrivate = function isPrivate (ip) {
  return isPrivateIP(ensureBuffer(ip))
}

exports.isReserved = function isReserved (ip) {
  return isReservedIP(ensureBuffer(ip))
}

function isBogonIP (ip) {
  return isPrivateIP(ip) || isReservedIP(ip)
}

function isPrivateIP (ip) {
  return ip.byteLength === 4 ? isPrivateIPv4(ip) : false // IPv6 has no private IPs
}

function isPrivateIPv4 (ip) {
  return (
    // 10.0.0.0/8  Private-use networks
    (ip[0] === 10) ||
    // 100.64.0.0/10 Carrier-grade NAT
    (ip[0] === 100 && ip[1] >= 64 && ip[1] <= 127) ||
    // 127.0.0.0/8 Loopback + Name collision occurrence (127.0.53.53)
    (ip[0] === 127) ||
    // 169.254.0.0/16  Link local
    (ip[0] === 169 && ip[1] === 254) ||
    // 172.16.0.0/12 Private-use networks
    (ip[0] === 172 && ip[1] >= 16 && ip[1] <= 31) ||
    // 192.168.0.0/16  Private-use networks
    (ip[0] === 192 && ip[1] === 168)
  )
}

function isReservedIP (ip) {
  return ip.byteLength === 4 ? isReservedIPv4(ip) : isReservedIPv6(ip)
}

function isReservedIPv4 (ip) {
  return (
    // 0.0.0.0/8 "This" network
    (ip[0] === 0) ||
    // 192.0.0.0/24  IETF protocol assignments
    (ip[0] === 192 && ip[1] === 0 && ip[2] === 0) ||
    // 192.0.2.0/24  TEST-NET-1
    (ip[0] === 192 && ip[1] === 0 && ip[2] === 2) ||
    // 198.18.0.0/15 Network interconnect device benchmark testing
    (ip[0] === 198 && ip[1] >= 18 && ip[1] <= 19) ||
    // 198.51.100.0/24 TEST-NET-2
    (ip[0] === 198 && ip[1] === 51 && ip[2] === 100) ||
    // 203.0.113.0/24  TEST-NET-3
    (ip[0] === 203 && ip[1] === 0 && ip[2] === 113) ||
    // 224.0.0.0/4 Multicast
    (ip[0] >= 224 && ip[0] <= 239) ||
    // 240.0.0.0/4 Reserved for future use
    (ip[0] >= 240) ||
    // 255.255.255.255/32
    (ip[0] === 255 && ip[1] === 255 && ip[2] === 255 && ip[3] === 255)
  )
}

function isReservedIPv6 (ip) {
  return (
    // ::/128 Node-scope unicast unspecified address
    // ::1/128 Node-scope unicast loopback address
    (
      ip[0] === 0 && ip[1] === 0 && ip[2] === 0 && ip[3] === 0 && ip[4] === 0 &&
      ip[5] === 0 && ip[6] === 0 && ip[7] === 0 && ip[8] === 0 && ip[9] === 0 &&
      ip[10] === 0 && ip[11] === 0 && ip[12] === 0 && ip[13] === 0 && ip[14] === 0 &&
      ip[15] <= 1
    ) ||
    // ::ffff:0:0/96 IPv4-mapped addresses
    // ::/96 IPv4-compatible addresses
    (
      ip[0] === 0 && ip[1] === 0 && ip[2] === 0 && ip[3] === 0 && ip[4] === 0 &&
      ip[5] === 0 && ip[6] === 0 && ip[7] === 0 && ip[8] === 0 && ip[9] === 0 &&
      (ip[10] === 0 || ip[10] === 0xff) &&
      (ip[11] === 0 || ip[11] === 0xff)
    ) ||
    // 100::/64 Remotely triggered black hole addresses
    (ip[0] === 0x01 && ip[1] === 0 && ip[2] === 0 && ip[3] === 0 && ip[4] === 0 && ip[5] === 0 && ip[6] === 0 && ip[7] === 0) ||
    // 2001:10::/28 Overlay routable cryptographic hash identifiers (ORCHID)
    (ip[0] === 0x20 && ip[1] === 0x01 && ip[2] === 0 && ip[3] >= 0x10 && ip[3] <= 0x1f) ||
    // 2001:20::/28 Overlay routable cryptographic hash identifiers version 2 (ORCHIDv2)
    (ip[0] === 0x20 && ip[1] === 0x01 && ip[2] === 0 && ip[3] >= 0x20 && ip[3] <= 0x2f) ||
    // 2001:db8::/32 Documentation prefix
    (ip[0] === 0x20 && ip[1] === 0x01 && ip[2] === 0x0d && ip[3] === 0xb8) ||
    // fc00::/7 Unique local addresses (ULA)
    (ip[0] >= 0xfc && ip[0] <= 0xfd) ||
    // fe80::/10 Link-local unicast
    (ip[0] === 0xfe && ip[1] >= 0x80 && ip[1] <= 0xbf) ||
    // ff00::/8 Multicast
    (ip[0] === 0xff)
  )
}

const state = c.state(0, 0, b4a.allocUnsafe(1 /* family */ + 16))

function ensureBuffer (ip) {
  if (b4a.isBuffer(ip)) return ip

  c.ip.preencode(state, ip)
  c.ip.encode(state, ip)

  const buffer = state.buffer.subarray(1 /* family */, state.end)

  state.start = 0
  state.end = 0

  return buffer
}
{
  "name": "bogon",
  "version": "1.3.0",
  "description": "Check if an IP is a bogon",
  "main": "index.js",
  "scripts": {
    "test": "standard && brittle test.mjs"
  },
  "dependencies": {
    "compact-encoding": "^3.0.0",
    "compact-encoding-net": "^1.2.0"
  },
  "devDependencies": {
    "brittle": "^3.0.4",
    "nanobench": "^2.1.1",
    "standard": "^17.0.0"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/bogon.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/bogon/issues"
  },
  "homepage": "https://github.com/mafintosh/bogon"
}
const b4a = require('b4a')

module.exports = codecs

codecs.ascii = createString('ascii')
codecs.utf8 = createString('utf-8')
codecs.hex = createString('hex')
codecs.base64 = createString('base64')
codecs.ucs2 = createString('ucs2')
codecs.utf16le = createString('utf16le')
codecs.ndjson = createJSON(true)
codecs.json = createJSON(false)
codecs.binary = {
  name: 'binary',
  encode: function encodeBinary (obj) {
    return typeof obj === 'string'
      ? b4a.from(obj, 'utf-8')
      : b4a.toBuffer(obj)
  },
  decode: function decodeBinary (buf) {
    return b4a.toBuffer(buf)
  }
}

function isCompactEncoding (c) {
  return !!(c.encode && c.decode && c.preencode)
}

function fromCompactEncoding (c) {
  return {
    name: 'compact-encoding',
    encode: function encodeWithCompact (value) {
      const state = { start: 0, end: 0, buffer: null, cache: null }
      c.preencode(state, value)
      state.buffer = b4a.allocUnsafe(state.end)
      c.encode(state, value)
      return state.buffer
    },
    decode: function decodeWithCompact (buffer) {
      return c.decode({ start: 0, end: buffer.byteLength, buffer, cache: null })
    }
  }
}

function codecs (fmt, fallback) {
  if (typeof fmt === 'object' && fmt) {
    return isCompactEncoding(fmt) ? fromCompactEncoding(fmt) : fmt
  }

  switch (fmt) {
    case 'ndjson': return codecs.ndjson
    case 'json': return codecs.json
    case 'ascii': return codecs.ascii
    case 'utf-8':
    case 'utf8': return codecs.utf8
    case 'hex': return codecs.hex
    case 'base64': return codecs.base64
    case 'ucs-2':
    case 'ucs2': return codecs.ucs2
    case 'utf16-le':
    case 'utf16le': return codecs.utf16le
  }

  return fallback !== undefined ? fallback : codecs.binary
}

function createJSON (newline) {
  return {
    name: newline ? 'ndjson' : 'json',
    encode: newline ? encodeNDJSON : encodeJSON,
    decode: function decodeJSON (buf) {
      return JSON.parse(b4a.toString(buf))
    }
  }

  function encodeJSON (val) {
    return b4a.from(JSON.stringify(val))
  }

  function encodeNDJSON (val) {
    return b4a.from(JSON.stringify(val) + '\n')
  }
}

function createString (type) {
  return {
    name: type,
    encode: function encodeString (val) {
      if (typeof val !== 'string') val = val.toString()
      return b4a.from(val, type)
    },
    decode: function decodeString (buf) {
      return b4a.toString(buf, type)
    }
  }
}
{
  "name": "codecs",
  "version": "3.1.0",
  "description": "Create an binary encoder/decoder for json, utf-8 or custom types",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.6.3"
  },
  "devDependencies": {
    "brittle": "^3.2.1",
    "compact-encoding": "^2.11.0",
    "standard": "^17.0.0"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/codecs.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/codecs/issues"
  },
  "homepage": "https://github.com/mafintosh/codecs"
}
const c = require('compact-encoding')

module.exports = function bitfield(length) {
  if (length > 64) {
    throw new RangeError('Bitfield cannot be larger than 64 bits')
  }

  let byteLength
  if (length < 8) byteLength = 1
  else if (length <= 16) byteLength = 2
  else if (length <= 32) byteLength = 4
  else byteLength = 8

  return {
    preencode(state) {
      state.end++ // Length byte, used for data when byteLength === 1

      if (byteLength === 1);
      else if (byteLength === 2) c.uint16.preencode(state)
      else if (byteLength === 4) c.uint32.preencode(state)
      else c.uint64.preencode(state)
    },

    encode(state, b) {
      if (byteLength === 1);
      else if (byteLength === 2) c.uint8.encode(state, 0xfd)
      else if (byteLength === 4) c.uint8.encode(state, 0xfe)
      else c.uint8.encode(state, 0xff)

      if (typeof b === 'number') {
        if (byteLength === 1) c.uint8.encode(state, b)
        else if (byteLength === 2) c.uint16.encode(state, b)
        else if (byteLength === 4) c.uint32.encode(state, b)
        else c.uint64.encode(state, b)
      } else {
        state.buffer.set(b, state.start)

        if (b.byteLength < byteLength) {
          // Zero-fill the rest of the byte length.
          state.buffer.fill(
            0,
            state.start + b.byteLength,
            state.start + byteLength
          )
        }

        state.start += byteLength
      }
    },

    decode(state) {
      const byte = state.buffer[state.start]

      let byteLength
      if (byte <= 0xfc) byteLength = 1
      else if (byte === 0xfd) byteLength = 2
      else if (byte === 0xfe) byteLength = 4
      else byteLength = 8

      if (byteLength > 1) state.start++ // Skip the length byte

      if (state.end - state.start < byteLength) throw new Error('Out of bounds')

      const b = state.buffer.subarray(state.start, (state.start += byteLength))

      return length <= 8 ? b.subarray(0, 1) : b
    }
  }
}
{
  "name": "compact-encoding-bitfield",
  "version": "1.1.0",
  "description": "Compact codec for bitfields",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node --coverage test.mjs",
    "test:bare": "brittle-bare --coverage test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/compact-encoding/compact-encoding-bitfield.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/compact-encoding/compact-encoding-bitfield/issues"
  },
  "homepage": "https://github.com/compact-encoding/compact-encoding-bitfield#readme",
  "imports": {
    "util": {
      "bare": "bare-utils",
      "default": "util"
    }
  },
  "dependencies": {
    "compact-encoding": "^3.0.0"
  },
  "devDependencies": {
    "bare-utils": "^1.5.1",
    "brittle": "^3.1.0",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  }
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return uint24.decode(state) + 0x1000000 * uint32.decode(state)
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return uint32.decode(state) + 0x100000000 * uint32.decode(state)
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return 0x100000000 * uint32be.decode(state) + uint32be.decode(state)
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.2.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
const safetyCatch = require('safety-catch')

module.exports = class CoreCoupler {
  constructor (target, wakeup) {
    this.target = target
    this.wakeup = wakeup
    this.coupled = new Set()

    this._onpeeraddBound = this._onpeeradd.bind(this)
    this.target.on('peer-add', this._onpeeraddBound)
  }

  add (core) {
    const added = this.coupled.size
    this.coupled.add(core)
    if (added !== this.coupled.size) this._couple(core)
  }

  remove (core) {
    this.coupled.delete(core)
  }

  destroy () {
    this.target.off('peer-add', this._onpeeraddBound)
  }

  async update (stream) {
    const muxer = stream.userData
    if (!muxer) return

    try {
      if (!(await this._hasMuxer(this.target, muxer))) return

      let wakeup = null

      for (const core of this.coupled) {
        if (await this._hasMuxer(core, muxer)) continue
        if (wakeup === null) wakeup = []
        wakeup.push(core)
      }

      if (wakeup !== null) {
        this.wakeup(stream, wakeup)
      }
    } catch (err) {
      safetyCatch(err)
    }
  }

  async _couple (core) {
    try {
      let wakeup = null

      for (const peer of this.target.peers) {
        if (await this._hasPeer(core, peer)) continue
        if (wakeup === null) wakeup = []
        wakeup.push(peer)
      }

      if (wakeup !== null && this.coupled.has(core)) {
        for (const peer of wakeup) this.wakeup(peer.stream, [core])
      }
    } catch (err) {
      safetyCatch(err)
    }
  }

  async _onpeeradd (peer) {
    try {
      let wakeup = null

      for (const core of this.coupled) {
        if (await this._hasPeer(core, peer)) continue
        if (wakeup === null) wakeup = []
        wakeup.push(core)
      }

      if (wakeup !== null) {
        this.wakeup(peer.stream, wakeup)
      }
    } catch (err) {
      safetyCatch(err)
    }
  }

  _hasMuxer (core, muxer) {
    const ch = muxer.getLastChannel({ protocol: 'hypercore', id: core.discoveryKey })
    if (ch) return ch.fullyOpened()

    const cha = muxer.getLastChannel({ protocol: 'hypercore/alpha', id: core.discoveryKey })
    if (cha) return cha.fullyOpened()

    return Promise.resolve(false)
  }

  _hasPeer (core, peer) {
    return this._hasMuxer(core, peer.protomux)
  }
}
{
  "name": "core-coupler",
  "version": "2.0.0",
  "description": "Couple the peers of cores",
  "main": "index.js",
  "scripts": {
    "test": "standard"
  },
  "dependencies": {
    "safety-catch": "^1.0.2"
  },
  "devDependencies": {
    "corestore": "^6.18.2",
    "standard": "^17.1.0"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/core-coupler.git"
  },
  "author": "Holepunch Inc",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/core-coupler/issues"
  },
  "homepage": "https://github.com/holepunchto/core-coupler"
}
const b4a = require('b4a')
const Hypercore = require('hypercore')
const ReadyResource = require('ready-resource')
const sodium = require('sodium-universal')
const crypto = require('hypercore-crypto')
const ID = require('hypercore-id-encoding')
const { isAndroid } = require('which-runtime')
const { STORAGE_EMPTY, ASSERTION } = require('hypercore-errors')

const auditStore = require('./lib/audit.js')
const GroupNotifyHandle = require('./lib/notify.js')

const [NS] = crypto.namespace('corestore', 1)
const DEFAULT_NAMESPACE = b4a.alloc(32) // This is meant to be 32 0-bytes

class StreamTracker {
  constructor() {
    this.records = []
  }

  add(stream, isExternal) {
    const record = { index: 0, stream, isExternal }
    record.index = this.records.push(record) - 1
    return record
  }

  remove(record) {
    const popped = this.records.pop()
    if (popped === record) return
    this.records[(popped.index = record.index)] = popped
  }

  attachAll(core) {
    for (let i = 0; i < this.records.length; i++) {
      const record = this.records[i]
      const muxer = record.stream.noiseStream.userData
      if (!core.replicator.attached(muxer)) core.replicator.attachTo(muxer)
    }
  }

  destroy() {
    // reverse is safer cause we delete mb
    for (let i = this.records.length - 1; i >= 0; i--) {
      const record = this.records[i]
      if (!record.isExternal) record.stream.destroy()
    }
  }
}

class SessionTracker {
  constructor() {
    this.map = new Map()
  }

  get size() {
    return this.map.size
  }

  get(id) {
    const existing = this.map.get(id)
    if (existing !== undefined) return existing
    const fresh = []
    this.map.set(id, fresh)
    return fresh
  }

  gc(id) {
    this.map.delete(id)
  }

  list(id) {
    return id ? this.map.get(id) || [] : [...this]
  }

  *[Symbol.iterator]() {
    for (const sessions of this.map.values()) {
      yield* sessions[Symbol.iterator]()
    }
  }
}

class CoreTracker {
  constructor() {
    this.map = new Map()
    this.watching = []

    this._gcing = new Set()
    this._gcInterval = null
    this._gcCycleBound = this._gcCycle.bind(this)
  }

  get size() {
    return this.map.size
  }

  watch(store) {
    if (store.watchIndex !== -1) return
    store.watchIndex = this.watching.push(store) - 1
  }

  unwatch(store) {
    if (store.watchIndex === -1) return
    const head = this.watching.pop()
    if (head !== store) this.watching[(head.watchIndex = store.watchIndex)] = head
    store.watchIndex = -1
  }

  resume(id) {
    const core = this.map.get(id)

    if (!core) return null

    // signal back that we have a closing one stored
    if (core.closing) return core

    if (core.gc) {
      this._gcing.delete(core)
      if (this._gcing.size === 0) this._stopGC()
      core.gc = 0
    }

    return core
  }

  opened(id) {
    const core = this.map.get(id)
    return !!(core && core.opened && !core.closing)
  }

  get(id) {
    // we allow you do call this from the outside, so support normal buffers also
    if (b4a.isBuffer(id)) id = b4a.toString(id, 'hex')
    const core = this.map.get(id)
    if (!core || core.closing) return null
    return core
  }

  set(id, core) {
    this.map.set(id, core)
    if (this.watching.length > 0) this._emit(core)
  }

  _emit(core) {
    for (let i = this.watching.length - 1; i >= 0; i--) {
      const store = this.watching[i]
      for (const fn of store.watchers) fn(core)
    }
  }

  _gc(core) {
    const id = toHex(core.discoveryKey)
    if (this.map.get(id) === core) this.map.delete(id)
  }

  _gcCycle() {
    for (const core of this._gcing) {
      if (++core.gc < 4) continue
      const gc = this._gc.bind(this, core)
      core.close().then(gc, gc)
      this._gcing.delete(core)
    }

    if (this._gcing.size === 0) this._stopGC()
  }

  gc(core) {
    core.gc = 1 // first strike
    this._gcing.add(core)
    if (this._gcing.size === 1) this._startGC()
  }

  _stopGC() {
    clearInterval(this._gcInterval)
    this._gcInterval = null
  }

  _startGC() {
    if (this._gcInterval) return
    this._gcInterval = setInterval(this._gcCycleBound, 2000)
    if (this._gcInterval.unref) this._gcInterval.unref()
  }

  close() {
    this._stopGC()
    this._gcing.clear()

    const all = []
    for (const core of this.map.values()) {
      core.onidle = noop // no reentry
      all.push(core.close())
    }
    this.map.clear()

    return Promise.all(all)
  }

  *[Symbol.iterator]() {
    for (const core of this.map.values()) {
      if (!core.closing) yield core
    }
  }
}

class FindingPeers {
  constructor() {
    this.count = 0
    this.pending = []
    this.destroyed = false
  }

  add(core) {
    if (this.count === 0) return
    this.pending.push(core.findingPeers())
  }

  inc(sessions) {
    if (this.destroyed || ++this.count !== 1) return

    for (const core of sessions) {
      this.pending.push(core.findingPeers())
    }
  }

  dec(sessions) {
    if (this.destroyed || --this.count !== 0) return
    while (this.pending.length > 0) this.pending.pop()()
  }

  destroy() {
    this.destroyed = true
    while (this.pending.length > 0) this.pending.pop()()
  }
}

class Corestore extends ReadyResource {
  constructor(storage, opts = {}) {
    super()

    this.root = opts.root || null
    this.storage = this.root
      ? this.root.storage
      : Hypercore.defaultStorage(storage, {
          id: opts.id,
          allowBackup: opts.allowBackup,
          readOnly: opts.readOnly,
          wait: opts.wait
        })
    this.streamTracker = this.root ? this.root.streamTracker : new StreamTracker()
    this.cores = this.root ? this.root.cores : new CoreTracker()
    this.sessions = new SessionTracker()
    this.corestores = this.root ? this.root.corestores : new Set()
    this.readOnly = opts.writable === false || !!opts.readOnly
    this.globalCache = this.root ? this.root.globalCache : opts.globalCache || null
    this.primaryKey = this.root ? this.root.primaryKey : opts.primaryKey || null
    this.ns = opts.namespace || DEFAULT_NAMESPACE
    this.manifestVersion = opts.manifestVersion || 1
    this.shouldSuspend = isAndroid ? !!opts.suspend : opts.suspend !== false
    this.active = opts.active !== false

    this.watchers = null
    this.watchIndex = -1

    this._groupNotifiers = new Map() // group notifications
    this._findingPeers = null // here for legacy
    this._ongcBound = this._ongc.bind(this)
    this._onGroupActiveBound = this._onGroupActive.bind(this)

    if (opts.primaryKey && !this.root && !opts.unsafe) {
      throw ASSERTION(
        'Passing the primary key is unsafe unless you know what you are doing. Set unsafe: true to acknowledge that'
      )
    }

    this.ready().catch(noop)
  }

  watch(fn) {
    if (this.watchers === null) {
      this.watchers = new Set()
      this.cores.watch(this)
    }

    this.watchers.add(fn)
  }

  unwatch(fn) {
    if (this.watchers === null) return

    this.watchers.delete(fn)

    if (this.watchers.size === 0) {
      this.watchers = null
      this.cores.unwatch(this)
    }
  }

  _onGroupActive(topic) {
    this.emit('group-active', topic)

    const topicHex = b4a.toString(topic, 'hex')
    const handles = this._groupNotifiers.get(topicHex)
    if (!handles) return
    for (const handle of handles) handle.emit('update')
  }

  notifyGroup(topic) {
    const topicHex = b4a.toString(topic, 'hex')
    let handles = this._groupNotifiers.get(topicHex)

    if (!handles) {
      handles = []
      this._groupNotifiers.set(topicHex, handles)
    }

    const handle = new GroupNotifyHandle(this, topic)
    const length = handles.push(handle)
    handle.index = length - 1

    return handle
  }

  _removeGroupNotify(handle) {
    if (handle.index === -1) return

    const topicHex = b4a.toString(handle._topic, 'hex')
    const handles = this._groupNotifiers.get(topicHex)
    if (!handles) return

    const popped = handles.pop()
    if (popped !== handle) handles[(popped.index = handle.index)] = popped
    if (handles.length === 0) this._groupNotifiers.delete(topicHex)
    handle.index = -1
  }

  findingPeers() {
    if (this._findingPeers === null) this._findingPeers = new FindingPeers()
    this._findingPeers.inc(this.sessions)
    let done = false
    return () => {
      if (done || !this._findingPeers) return
      done = true
      this._findingPeers.dec(this.sessions)
    }
  }

  audit(opts = {}) {
    return auditStore(this, opts)
  }

  async suspend({ log = noop } = {}) {
    await log('Flushing db...')
    // If readOnly we don't need to flush
    if (!this.storage.readOnly) {
      await this.storage.db.flush()
      await log('Flusing db completed')
    }
    if (!this.shouldSuspend) return
    await log('Suspending db...')
    await this.storage.suspend({ log })
    await log('Suspending db completed')
  }

  resume() {
    return this.storage.resume()
  }

  session(opts) {
    this._maybeClosed()
    const root = this.root || this
    return new Corestore(null, {
      manifestVersion: this.manifestVersion,
      ...opts,
      root
    })
  }

  namespace(name, opts) {
    return this.session({
      ...opts,
      namespace: generateNamespace(this.ns, name)
    })
  }

  list(namespace) {
    return this.storage.createDiscoveryKeyStream(namespace)
  }

  getAuth(discoveryKey) {
    return this.storage.getAuth(discoveryKey)
  }

  _ongc(session) {
    if (session.sessions.length === 0) this.sessions.gc(session.id)
  }

  async _getOrSetSeed() {
    const seed = await this.storage.getSeed()
    if (seed !== null) return seed
    return await this.storage.setSeed(this.primaryKey || crypto.randomBytes(32))
  }

  async _open() {
    if (this.root !== null) {
      this.corestores.add(this)
      if (this.root.opened === false) await this.root.ready()
      this.primaryKey = this.root.primaryKey
      return
    }

    const primaryKey = await this._getOrSetSeed()

    if (this.primaryKey === null) {
      this.primaryKey = primaryKey
      return
    }

    if (!b4a.equals(primaryKey, this.primaryKey)) {
      throw new Error('Another corestore is stored here')
    }
  }

  async _close() {
    const closing = []
    const hanging = [...this.sessions]
    for (const sess of hanging) closing.push(sess.close())

    if (this.watchers !== null) {
      this.cores.unwatch(this)
      this.watchers = null
    }

    if (this._findingPeers !== null) {
      this._findingPeers.destroy()
      this._findingPeers = null
    }

    if (this.root !== null) {
      await Promise.all(closing)
      this.corestores.delete(this)
      return
    }

    for (const store of this.corestores) {
      closing.push(store.close())
    }

    await Promise.all(closing)

    await this.cores.close()
    await this.storage.close()
  }

  async _attachMaybe(muxer, discoveryKey) {
    if (this.opened === false) await this.ready()
    if (
      !this.cores.opened(toHex(discoveryKey)) &&
      !(await this.storage.hasCore(discoveryKey, { ifMigrated: true }))
    ) {
      return
    }
    if (this.closing) return

    const core = this._openCore(discoveryKey, { createIfMissing: false })

    if (!core) return
    if (!core.opened) await core.ready()

    if (!core.replicator.attached(muxer)) {
      core.replicator.attachTo(muxer)
    }

    core.checkIfIdle()
  }

  _shouldReplicate(core, muxer) {
    return (
      core.replicator.downloading && !core.replicator.attached(muxer) && core.opened && this.active
    )
  }

  replicate(isInitiator, opts) {
    this._maybeClosed()

    const isExternal = isStream(isInitiator)
    const stream = Hypercore.createProtocolStream(isInitiator, {
      ...opts,
      ondiscoverykey: (discoveryKey) => {
        if (this.closing) return
        const muxer = stream.noiseStream.userData
        return this._attachMaybe(muxer, discoveryKey)
      }
    })

    if (this.cores.size > 0) {
      const muxer = stream.noiseStream.userData
      const uncork = muxer.uncork.bind(muxer)
      muxer.cork()

      for (const core of this.cores) {
        if (!this._shouldReplicate(core, muxer)) {
          continue
        }
        core.replicator.attachTo(muxer)
      }

      stream.noiseStream.opened.then(uncork)
    }

    const record = this.streamTracker.add(stream, isExternal)
    stream.once('close', () => this.streamTracker.remove(record))
    return stream
  }

  _maybeClosed() {
    if (this.closing || (this.root !== null && this.root.closing)) {
      throw new Error('Corestore is closed')
    }
  }

  async staticify(core, opts) {
    if (!this.opened) await this.ready()
    if (!core.opened) await core.ready()

    const rx = core.state.storage.read()

    const headPromise = rx.getHead()
    const authPromise = rx.getAuth()

    rx.tryFlush()

    const [head, auth] = await Promise.all([headPromise, authPromise])
    if (!head || head.length === 0) throw new Error('Core must have data')

    const prologue = {
      length: head.length,
      hash: head.rootHash
    }

    const manifest = {
      version: 1,
      hash: auth.manifest.hash,
      quorum: 0,
      signers: [],
      prologue
    }

    const c = {
      key: null,
      discoveryKey: null,
      manifest,
      core: core.state.storage.core
    }

    c.key = Hypercore.key(c.manifest)
    c.discoveryKey = Hypercore.discoveryKey(c.key)

    await this.storage.createCore(c)

    const staticCore = this.get({ ...opts, key: c.key })
    await staticCore.ready()
    return staticCore
  }

  get(opts) {
    this._maybeClosed()

    if (b4a.isBuffer(opts) || typeof opts === 'string') opts = { key: opts }
    if (!opts) opts = {}

    const conf = {
      preload: null,
      sessions: null,
      ongc: null,
      core: null,
      active: opts.active !== false,
      encryption: opts.encryption || null,
      encryptionKey: opts.encryptionKey || null, // back compat, should remove
      isBlockKey: !!opts.isBlockKey, // back compat, should remove
      valueEncoding: opts.valueEncoding || null,
      exclusive: !!opts.exclusive,
      manifest: opts.manifest || null,
      keyPair: opts.keyPair || null,
      onwait: opts.onwait || null,
      pushOnly: opts.pushOnly === true,
      wait: opts.wait !== false,
      timeout: opts.timeout || 0,
      draft: !!opts.draft,
      writable: opts.writable === undefined && this.readOnly ? false : opts.writable
    }

    // name requires us to rt to storage + ready, so needs preload
    // same goes if user has defined async preload obvs
    if (opts.name || opts.preload) {
      conf.preload = this._preload(opts)
      return this._makeSession(conf)
    }

    if (opts.discoveryKey && !opts.key && !opts.manifest) {
      conf.preload = this._preloadCheckIfExists(opts)
      return this._makeSession(conf)
    }

    // if not not we can sync create it, which just is easier for the
    // upstream user in terms of guarantees (key is there etc etc)
    const core = this._openCore(null, opts)

    conf.core = core
    conf.sessions = this.sessions.get(core.id)
    conf.ongc = this._ongcBound

    return this._makeSession(conf)
  }

  _makeSession(conf) {
    const session = new Hypercore(null, null, conf)

    if (this._findingPeers !== null) this._findingPeers.add(session)
    return session
  }

  async createKeyPair(name, ns = this.ns) {
    if (this.opened === false) await this.ready()
    return createKeyPair(this.primaryKey, ns, name)
  }

  async _preloadCheckIfExists(opts) {
    const has = await this.storage.hasCore(opts.discoveryKey)
    if (!has) throw STORAGE_EMPTY('No Hypercore is stored here')
    return this._preload(opts)
  }

  async _preload(opts) {
    if (opts.preload) opts = { ...opts, ...(await opts.preload) }
    if (this.opened === false) await this.ready()

    const discoveryKey = opts.name
      ? await this.storage.getAlias({ name: opts.name, namespace: this.ns })
      : null
    this._maybeClosed()

    const core = this._openCore(discoveryKey, opts)

    return {
      core,
      sessions: this.sessions.get(core.id),
      ongc: this._ongcBound,
      manifest: opts.manifest || null,
      encryption: opts.encryption || null,
      encryptionKey: opts.encryptionKey || null, // back compat, should remove
      isBlockKey: !!opts.isBlockKey // back compat, should remove
    }
  }

  _auth(discoveryKey, opts) {
    const result = {
      keyPair: null,
      key: null,
      discoveryKey,
      manifest: null,
      group: null
    }

    if (opts.name) {
      result.keyPair = createKeyPair(this.primaryKey, this.ns, opts.name)
    } else if (opts.keyPair) {
      result.keyPair = opts.keyPair
    }

    if (opts.manifest) {
      result.manifest = opts.manifest
    } else if (result.keyPair && !result.discoveryKey) {
      result.manifest = {
        version: this.manifestVersion,
        signers: [{ publicKey: result.keyPair.publicKey }]
      }
    }

    if (opts.group) {
      result.group = opts.group
    }

    if (opts.key) result.key = ID.decode(opts.key)
    else if (result.manifest) result.key = Hypercore.key(result.manifest)

    if (result.discoveryKey) return result

    if (opts.discoveryKey) result.discoveryKey = ID.decode(opts.discoveryKey)
    else if (result.key) result.discoveryKey = crypto.discoveryKey(result.key)
    else throw new Error('Could not derive discovery from input')

    return result
  }

  _openCore(discoveryKey, opts) {
    const auth = this._auth(discoveryKey, opts)

    const id = toHex(auth.discoveryKey)
    const existing = this.cores.resume(id, auth.group)
    if (existing && !existing.closing) return existing

    const core = Hypercore.createCore(this.storage, {
      preopen: existing && existing.opened ? existing.closing : null, // always wait for the prev one to close first in any case...
      eagerUpgrade: true,
      notDownloadingLinger: opts.notDownloadingLinger,
      allowFork: opts.allowFork !== false,
      allowPush: !!opts.allowPush,
      inflightRange: opts.inflightRange,
      compat: false, // no compat for now :)
      force: opts.force,
      createIfMissing: opts.createIfMissing,
      discoveryKey: auth.discoveryKey,
      overwrite: opts.overwrite,
      key: auth.key,
      keyPair: auth.keyPair,
      legacy: opts.legacy,
      manifest: auth.manifest,
      group: auth.group,
      globalCache: opts.globalCache || this.globalCache || null,
      alias: opts.name ? { name: opts.name, namespace: this.ns } : null
    })

    core.onidle = () => {
      this.cores.gc(core)
    }

    core.ongroupupdate = this._onGroupActiveBound

    core.replicator.ondownloading = () => {
      if (this.active) this.streamTracker.attachAll(core)
    }

    this.cores.set(id, core)
    return core
  }
}

module.exports = Corestore

function isStream(s) {
  return typeof s === 'object' && s && typeof s.pipe === 'function'
}

function generateNamespace(namespace, name) {
  if (!b4a.isBuffer(name)) name = b4a.from(name)
  const out = b4a.allocUnsafeSlow(32)
  sodium.crypto_generichash_batch(out, [namespace, name])
  return out
}

function deriveSeed(primaryKey, namespace, name) {
  if (!b4a.isBuffer(name)) name = b4a.from(name)
  const out = b4a.alloc(32)
  sodium.crypto_generichash_batch(out, [NS, namespace, name], primaryKey)
  return out
}

function createKeyPair(primaryKey, namespace, name) {
  const seed = deriveSeed(primaryKey, namespace, name)
  const buf = b4a.alloc(sodium.crypto_sign_PUBLICKEYBYTES + sodium.crypto_sign_SECRETKEYBYTES)
  const keyPair = {
    publicKey: buf.subarray(0, sodium.crypto_sign_PUBLICKEYBYTES),
    secretKey: buf.subarray(sodium.crypto_sign_PUBLICKEYBYTES)
  }
  sodium.crypto_sign_seed_keypair(keyPair.publicKey, keyPair.secretKey, seed)
  return keyPair
}

function noop() {}

function toHex(discoveryKey) {
  return b4a.toString(discoveryKey, 'hex')
}
module.exports = async function* audit(store, { dryRun = false } = {}) {
  for await (const { discoveryKey, core } of store.storage.createCoreStream()) {
    if (core.version < 1) continue // not migrated, ignore

    const c = store.get({ discoveryKey, active: false })
    await c.ready()

    yield { discoveryKey, key: c.key, audit: await c.core.audit({ dryRun }) }

    try {
      await c.close()
    } catch {
      // ignore if failed, we are auditing...
    }
  }
}
const { EventEmitter } = require('events')
const { Readable } = require('streamx')

class GroupNotifyHandle extends EventEmitter {
  constructor(store, topic) {
    super()
    this._store = store
    this._topic = topic
    this.index = -1
  }

  updates(opts) {
    return Readable.deferred(async () => {
      const groupId = await this._store.storage.getGroup(this._topic).catch(noop)
      if (groupId === null) return null
      return this._store.storage.createGroupUpdateStream(groupId, opts)
    })
  }

  destroy() {
    this._store._removeGroupNotify(this)
  }
}

module.exports = GroupNotifyHandle

function noop() {}
{
  "name": "corestore",
  "version": "7.10.1",
  "description": "A Hypercore factory that simplifies managing collections of cores.",
  "main": "index.js",
  "files": [
    "index.js",
    "lib/*"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "dependencies": {
    "b4a": "^1.6.7",
    "bare-events": "^2.8.3",
    "hypercore": "^11.32.0",
    "hypercore-crypto": "^3.4.2",
    "hypercore-errors": "^1.4.0",
    "hypercore-id-encoding": "^1.3.0",
    "ready-resource": "^1.1.1",
    "sodium-universal": "^5.0.1",
    "streamx": "^2.26.0",
    "which-runtime": "^1.2.1"
  },
  "devDependencies": {
    "brittle": "^3.7.0",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "rache": "^1.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "test": "npm run test:node && npm run test:bare",
    "test:bare": "brittle-bare --coverage test/all.js",
    "lint": "prettier --check . && lunte",
    "test:node": "brittle-node --coverage test/all.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/corestore.git"
  },
  "author": "Holepunch Inc",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/corestore/issues"
  },
  "homepage": "https://github.com/holepunchto/corestore"
}
module.exports = function debounce (worker, context = null) {
  debounced.running = null
  return debounced

  async function debounced () {
    if (debounced.running !== null) {
      try {
        await debounced.running
      } catch (_) {
        // ignore - do not fail on old errors
      }
    }

    // another "thread" beat us to it, just piggy pack on that one
    if (debounced.running !== null) return debounced.running

    debounced.running = worker.call(context)

    try {
      return await debounced.running
    } finally {
      debounced.running = null
    }
  }
}
{
  "name": "debounceify",
  "version": "1.1.0",
  "description": "Tiny async debouncer",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^16.0.3",
    "tape": "^5.1.1"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/debounceify.git"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/debounceify/issues"
  },
  "homepage": "https://github.com/mafintosh/debounceify"
}
const fs = require('fs')
const path = require('path')
const fsx = require('fs-native-extensions')
const b4a = require('b4a')
const ReadyResource = require('ready-resource')
const FDLock = require('fd-lock')

const PLATFORM = global.Bare ? global.Bare.platform : global.process.platform
const IS_WIN = PLATFORM === 'win32'
const IS_LINUX = PLATFORM === 'linux'
const MODIFIED_SLACK = 5000
const EMPTY = b4a.alloc(0)
const ATTR = IS_LINUX ? 'user.device-file' : 'device-file'

const nl = IS_WIN ? '\r\n' : '\n'

class DeviceFile extends ReadyResource {
  constructor(filename, { create = true, wait = false, lock = wait, data = {} } = {}) {
    super()

    this.filename = filename
    this.data = data
    this.lock = null

    this._create = create
    this._wait = wait
    this._lock = lock
  }

  async _open() {
    if (await verifyDeviceFile(this)) return
    if (!this._create) throwDeviceFileError('No device file present', false)
    await writeDeviceFile(this)
  }

  static async validate(filename, data) {
    const file = new DeviceFile(filename, { create: false, wait: false, data })
    try {
      await verifyDeviceFile(file)
    } catch (err) {
      if (err.fatal && err.code === 'DEVICE_FILE') return false
      throw err
    }
    return true
  }

  transfer() {
    return this.lock ? this.lock.transfer() : -1
  }

  async _close() {
    if (this.lock) await this.lock.close()
  }

  async suspend() {
    if (!this.opened) await this.ready()
    if (this.lock) await this.lock.suspend()
  }

  async resume() {
    if (!this.opened) await this.ready()
    if (this.lock) await this.lock.resume()
  }
}

module.exports = DeviceFile

async function writeDeviceFile(device) {
  let s = ''

  for (const [key, value] of Object.entries(device.data)) {
    if (value === null) continue
    s += key + '=' + value + nl
  }

  await fs.promises.mkdir(path.dirname(device.filename), { recursive: true })

  const fd = await open(device.filename, 'w')

  device.lock = device._lock ? new FDLock(fd, { wait: device._wait }) : null

  if (device.lock) {
    try {
      await device.lock.ready()
    } catch (err) {
      await device.lock.close()
      throw err
    }
  }

  const st = await fstat(fd)

  const created = Date.now()

  s += 'device/platform=' + PLATFORM + nl
  s += 'device/inode=' + st.ino + nl
  s += 'device/created=' + created + nl

  if (await setAttr(fd, ATTR, b4a.from('original'))) {
    s += 'device/attribute=original' + nl
  }

  await write(fd, b4a.from(s))

  if (!device.lock) await close(fd)
}

async function verifyDeviceFile(device) {
  let fd = 0

  try {
    fd = await open(device.filename, 'r+')
  } catch (e) {
    fd = 0
  }

  if (fd === 0) return false

  device.lock = device._lock ? new FDLock(fd, { wait: device._wait }) : null

  if (device.lock) {
    try {
      await device.lock.ready()
    } catch (err) {
      await device.lock.close()
      throw err
    }
  }

  const buf = await read(fd)
  const result = {}

  const s = b4a.toString(buf).trim().split('\n')

  let inode = 0
  let created = 0
  let attr = ''
  let platform = ''

  for (const ln of s) {
    const i = ln.indexOf('=')
    if (i === -1) continue

    const k = ln.slice(0, i).trim()
    const v = ln.slice(i + 1).trim()

    switch (k) {
      case 'device/platform':
        platform = v
        break
      case 'device/inode':
        inode = Number(v)
        break
      case 'device/created':
        created = Number(v)
        break
      case 'device/attribute':
        attr = v
        break
      default:
        result[k] = v
        break
    }
  }

  for (const [k, v] of Object.entries(device.data)) {
    if (v === null) continue
    if (result[k] === undefined) continue // allow upserts
    if (result[k] !== '' + v) {
      await teardown()
      throwDeviceFileError(`Invalid device file, ${k} has changed. Was ${result[k]}, is ${v}`, true)
    }
  }

  const st = await fstat(fd)
  const at = await getAttr(fd, ATTR)

  const sameAttr = b4a.toString(at || EMPTY) === attr
  const modified = Math.max(st.mtime.getTime(), st.birthtime.getTime())

  if (platform && platform !== PLATFORM) {
    await teardown()
    throwDeviceFileError('Invalid device file, was made on different platform', true)
  }

  if (!sameAttr) {
    await teardown()
    throwDeviceFileError('Invalid device file, was moved unsafely', true)
  }

  if (st.ino !== inode || (created && Math.abs(modified - created) >= MODIFIED_SLACK)) {
    await teardown()
    throwDeviceFileError('Invalid device file, was modified', true)
  }

  if (!device.lock) await close(fd)

  device.data = result
  return true

  async function teardown() {
    if (device.lock) await device.lock.close()
    else await close(fd)
  }
}

async function getAttr(fd, name) {
  try {
    return await fsx.getAttr(fd, name)
  } catch {
    return null
  }
}

async function setAttr(fd, name, value) {
  try {
    await fsx.setAttr(fd, name, value)
    return true
  } catch {
    return false
  }
}

function fstat(fd) {
  return new Promise((resolve, reject) => {
    fs.fstat(fd, (err, st) => {
      if (err) reject(err)
      resolve(st)
    })
  })
}

function close(fd) {
  return new Promise((resolve, reject) => {
    fs.close(fd, (err, st) => {
      if (err) reject(err)
      resolve(st)
    })
  })
}

function write(fd, buf) {
  return new Promise((resolve, reject) => {
    let offset = 0

    onwrite(null, 0)

    function onwrite(err, wrote) {
      if (err) return reject(err)
      if (offset === buf.byteLength) return resolve()
      offset += wrote
      fs.write(fd, buf, offset, buf.byteLength - offset, offset, onwrite)
    }
  })
}

function read(fd) {
  const buf = b4a.allocUnsafe(4096)

  return new Promise((resolve, reject) => {
    let offset = 0

    fs.read(fd, buf, 0, buf.byteLength, 0, onread)

    function onread(err, read) {
      if (err) return reject(err)
      if (read === 0) return resolve(buf.subarray(0, offset))
      offset += read
      fs.read(fd, buf, offset, buf.byteLength - offset, offset, onread)
    }
  })
}

function open(filename, flags) {
  return new Promise((resolve, reject) => {
    fs.open(filename, flags, (err, fd) => {
      if (err) reject(err)
      resolve(fd)
    })
  })
}

function throwDeviceFileError(message, fatal) {
  const err = new Error(message)
  err.code = 'DEVICE_FILE'
  err.fatal = fatal
  throw err
}
{
  "name": "device-file",
  "version": "2.3.1",
  "description": "Device only file",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.6.7",
    "bare-fs": "^4.0.1",
    "bare-path": "^3.0.0",
    "fd-lock": "^2.1.0",
    "fs-native-extensions": "^1.4.0",
    "ready-resource": "^1.2.0"
  },
  "devDependencies": {
    "brittle": "^3.13.1",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node --coverage test.js",
    "test:bare": "brittle-bare --coverage test.js"
  },
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    }
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/device-file.git"
  },
  "author": "Holepunch Inc",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/device-file/issues"
  },
  "homepage": "https://github.com/holepunchto/device-file"
}
const { EventEmitter } = require('events')
const Table = require('kademlia-routing-table')
const TOS = require('time-ordered-set')
const UDX = require('udx-native')
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const NatSampler = require('nat-sampler')
const b4a = require('b4a')
const NetworkHealth = require('./lib/health')
const IO = require('./lib/io')
const Query = require('./lib/query')
const Session = require('./lib/session')
const peer = require('./lib/peer')
const { UNKNOWN_COMMAND, INVALID_TOKEN } = require('./lib/errors')
const { PING, PING_NAT, FIND_NODE, DOWN_HINT, DELAYED_PING } = require('./lib/commands')

const TMP = b4a.allocUnsafe(32)
const TICK_INTERVAL = 5000
const SLEEPING_INTERVAL = 3 * TICK_INTERVAL
const STABLE_TICKS = 240 // if nothing major bad happens in ~20mins we can consider this node stable (if nat is friendly)
const MORE_STABLE_TICKS = 3 * STABLE_TICKS
const REFRESH_TICKS = 60 // refresh every ~5min when idle
const RECENT_NODE = 12 // we've heard from a node less than 1min ago
const OLD_NODE = 360 // if an node has been around more than 30 min we consider it old

const DEFAULTS = {
  concurrency: 10,
  maxWindow: IO.DEFAULT_MAX_WINDOW,
  maxPingDelay: 10_000
}

class DHT extends EventEmitter {
  constructor(opts = {}) {
    super()

    this.bootstrapNodes = opts.bootstrap === false ? [] : (opts.bootstrap || []).map(parseNode)
    this.table = new Table(randomBytes(32))
    this.nodes = new TOS()
    this.udx = opts.udx || new UDX()
    this.io = new IO(this.table, this.udx, {
      ...opts,
      onrequest: this._onrequest.bind(this),
      onresponse: this._onresponse.bind(this),
      ontimeout: this._ontimeout.bind(this)
    })
    this.health = new NetworkHealth(this)

    this.concurrency = opts.concurrency || DEFAULTS.concurrency
    this.maxPingDelay = opts.maxPingDelay || DEFAULTS.maxPingDelay
    this.bootstrapped = false
    this.ephemeral = true
    this.firewalled = this.io.firewalled
    this.adaptive = typeof opts.ephemeral !== 'boolean' && opts.adaptive !== false
    this.destroyed = false
    this.suspended = false
    this.online = true
    this.degraded = false
    this.stats = {
      queries: { active: 0, total: 0 },
      requests: this.io.stats.requests,
      commands: {
        ping: this.io.stats.commands[PING],
        pingNat: this.io.stats.commands[PING_NAT],
        findNode: this.io.stats.commands[FIND_NODE],
        downHint: this.io.stats.commands[DOWN_HINT]
      }
    }

    this._nat = new NatSampler()
    this._quickFirewall = opts.quickFirewall !== false
    this._forcePersistent = opts.ephemeral === false
    this._repinging = 0
    this._checks = 0
    this._tick = randomOffset(100) // make sure to random offset all the network ticks
    this._refreshTicks = randomOffset(REFRESH_TICKS)
    this._stableTicks = this.adaptive ? STABLE_TICKS : 0
    this._tickInterval = setInterval(this._ontick.bind(this), TICK_INTERVAL)
    this._lastTick = Date.now()
    this._lastHost = null
    this._filterNode = opts.filterNode || opts.addNode || null // opts.addNode is deprecating, use opts.filterNode instead
    this._onrow = (row) => row.on('full', (node) => this._onfullrow(node, row))
    this._nonePersistentSamples = []
    this._bootstrapping = this._bootstrap()
    this._bootstrapping.catch(noop)
    this._sendDownHints = opts.sendDownHints !== false
    this._downHintsRateLimit =
      opts.downHintsRateLimit !== undefined ? opts.downHintsRateLimit : 10 * 5
    this._downHintsSentPerTick = 0
    this._pendingTimers = new Set()

    this.table.on('row', this._onrow)

    this.io.networkInterfaces.on('change', (interfaces) => this._onnetworkchange(interfaces))

    if (opts.nodes) {
      for (let i = opts.nodes.length - 1; i >= 0; i--) {
        this.addNode(opts.nodes[i])
      }
    }
  }

  static DEFAULTS = DEFAULTS

  static bootstrapper(port, host, opts) {
    if (!port) throw new Error('Port is required')
    if (!host) throw new Error('Host is required')
    if (host === '0.0.0.0' || host === '::') throw new Error('Invalid host')
    if (!UDX.isIPv4(host)) throw new Error('Host must be a IPv4 address')

    const dht = new this({
      port,
      ephemeral: false,
      firewalled: false,
      anyPort: false,
      bootstrap: [],
      ...opts
    })
    dht._nat.add(host, port)
    return dht
  }

  get id() {
    return this.ephemeral ? null : this.table.id
  }

  get host() {
    return this._nat.host
  }

  get port() {
    return this._nat.port
  }

  get randomized() {
    return this._nat.host !== null && this._nat.port === 0
  }

  get socket() {
    return this.firewalled ? this.io.clientSocket : this.io.serverSocket
  }

  get config() {
    return {
      concurrency: this.concurrency,
      maxWindow: this.io.congestion._maxWindow,
      randomPunchInterval: this._randomPunchInterval,
      connectionKeepAlive: this.connectionKeepAlive,
      sendDownHints: this._sendDownHints,
      downHintsRateLimit: this._downHintsRateLimit
    }
  }

  onmessage(socket, buf, rinfo) {
    if (buf.byteLength > 1) this.io.onmessage(socket, buf, rinfo)
  }

  bind() {
    return this.io.bind()
  }

  async suspend({ log = noop } = {}) {
    log('Suspending waiting for io bind...')
    await this.io.bind()
    log('Done, continuing')
    if (this.suspended || this.destroyed) return
    this.suspended = true
    clearInterval(this._tickInterval)
    log('Done, suspending io')
    await this.io.suspend({ log })
    log('Done, dht suspended')
    this.emit('suspend')
  }

  async resume({ log = noop } = {}) {
    if (!this.suspended || this.destroyed) return
    this.suspended = false
    this._tickInterval = setInterval(this._ontick.bind(this), TICK_INTERVAL)
    this._onwakeup()
    log('Resuming io')
    await this.io.resume()
    log('Done, dht resumed')
    this.io.networkInterfaces.on('change', (interfaces) => this._onnetworkchange(interfaces))
    this.refresh()
    this.emit('resume')
  }

  address() {
    const socket = this.socket
    return socket ? socket.address() : null
  }

  localAddress() {
    if (!this.io.serverSocket) return null

    return {
      host: localIP(this.udx),
      port: this.io.serverSocket.address().port
    }
  }

  remoteAddress() {
    if (!this.host) return null
    if (!this.port) return null
    if (this.firewalled) return null
    if (!this.io.serverSocket) return null

    const port = this.io.serverSocket.address().port
    if (port !== this.port) return null

    return {
      host: this.host,
      port
    }
  }

  addNode({ host, port }) {
    this._addNode({
      id: peer.id(host, port),
      port,
      host,
      token: null,
      to: null,
      sampled: 0,
      added: this._tick,
      pinged: 0,
      seen: 0,
      downHints: 0,
      prev: null,
      next: null
    })
  }

  toArray(opts) {
    const limit = opts && opts.limit
    if (limit === 0) return []
    return this.nodes.toArray({ limit, reverse: true }).map(({ host, port }) => ({ host, port }))
  }

  async fullyBootstrapped() {
    return this._bootstrapping
  }

  ready() {
    // Deprecating, use fullyBootstrapped instead (removed on next major)
    return this.fullyBootstrapped()
  }

  findNode(target, opts) {
    if (this.destroyed) throw new Error('Node destroyed')
    this._refreshTicks = REFRESH_TICKS
    return new Query(this, target, true, FIND_NODE, null, opts)
  }

  query({ target, command, value }, opts) {
    if (this.destroyed) throw new Error('Node destroyed')
    this._refreshTicks = REFRESH_TICKS
    return new Query(this, target, false, command, value || null, opts)
  }

  ping({ host, port }, opts) {
    let value = null

    if (opts && opts.size && opts.size > 0) value = b4a.alloc(opts.size)

    const req = this.io.createRequest(
      { id: null, host, port },
      null,
      true,
      PING,
      null,
      value,
      (opts && opts.session) || null,
      opts && opts.ttl
    )
    return this._requestToPromise(req, opts)
  }

  delayedPing({ host, port }, delayMs, opts) {
    if (delayMs > this.maxPingDelay) {
      throw new Error(`Delay exceeds max delay: ${this.maxPingDelay}ms`)
    }

    const value = b4a.allocUnsafe(4)
    c.uint32.encode({ start: 0, end: 4, buffer: value }, delayMs)

    const req = this.io.createRequest(
      { id: null, host, port },
      null,
      true,
      DELAYED_PING,
      null,
      value,
      (opts && opts.session) || null,
      opts && opts.ttl
    )
    // add 1 second to the timeout to account for network overhead
    req.timeout = delayMs + 1_000
    return this._requestToPromise(req, opts)
  }

  async rttStats() {
    const stats = {
      successes: 0,
      errors: 0,
      responses: {
        avgRtt: 0,
        errors: 0,
        avgCloserNodes: 0
      },
      closestReplies: {
        avgRtt: 0,
        errors: 0,
        avgCloserNodes: 0
      }
    }

    if (this.nodes.latest) {
      const q = this.findNode(this.nodes.latest.id)

      let responseCount = 0
      let closestCount = 0

      for await (const msg of q) {
        stats.responses.avgRtt += msg.rtt
        stats.responses.errors += msg.error
        stats.responses.avgCloserNodes += msg.closerNodes?.length || 0
        responseCount++
      }
      stats.responses.avgRtt /= responseCount
      stats.responses.avgCloserNodes /= responseCount

      for await (const msg of q.closestReplies) {
        stats.closestReplies.avgRtt += msg.rtt
        stats.closestReplies.errors += msg.error
        stats.closestReplies.avgCloserNodes += msg.closerNodes?.length || 0
        closestCount++
      }
      stats.closestReplies.avgRtt /= closestCount
      stats.closestReplies.avgCloserNodes /= closestCount

      stats.successes = q.successes
      stats.errors = q.errors
    }

    return stats
  }

  request({ token = null, command, target = null, value = null }, { host, port }, opts) {
    const req = this.io.createRequest(
      { id: null, host, port },
      token,
      false,
      command,
      target,
      value,
      (opts && opts.session) || null,
      opts && opts.ttl
    )
    return this._requestToPromise(req, opts)
  }

  session() {
    return new Session(this)
  }

  _requestToPromise(req, opts) {
    if (req === null) return Promise.reject(new Error('Node destroyed'))

    if (opts && opts.socket) req.socket = opts.socket
    if (opts && opts.retry === false) req.retries = 0

    return new Promise((resolve, reject) => {
      req.onresponse = resolve
      req.onerror = reject
      req.send()
    })
  }

  async _bootstrap() {
    const self = this

    await Promise.resolve() // wait a tick, so apis can be used from the outside
    await this.io.bind()

    this.emit('listening')

    // TODO: some papers describe more advanced ways of bootstrapping - we should prob look into that

    let first = this.firewalled && this._quickFirewall && !this._forcePersistent
    let testNat = false

    const onlyFirewall = !this._forcePersistent

    for (let i = 0; i < 2; i++) {
      await this._backgroundQuery(this.table.id).on('data', ondata).finished()

      if (this.bootstrapped || (!testNat && !this._forcePersistent)) break
      if (!(await this._updateNetworkState(onlyFirewall))) break
    }

    if (this.bootstrapped) return
    this.bootstrapped = true

    this.emit('ready')

    function ondata(data) {
      // Simple QUICK nat heuristic.
      // If we get ONE positive nat ping before the bootstrap query finishes
      // then we always to a nat test, no matter if we are adaptive...
      // This should be expanded in the future to try more than one node etc, not always hit the first etc
      // If this fails, then nbd, as the onstable hook will pick it up later.

      if (!first) return
      first = false

      const value = b4a.allocUnsafe(2)
      c.uint16.encode({ start: 0, end: 2, buffer: value }, self.io.serverSocket.address().port)

      self._request(
        data.from,
        false,
        true,
        PING_NAT,
        null,
        value,
        null,
        () => {
          testNat = true
        },
        noop
      )
    }
  }

  refresh() {
    const node = this.table.random()
    this._backgroundQuery(node ? node.id : this.table.id).on('error', noop)
  }

  async destroy() {
    const emitClose = !this.destroyed
    this.destroyed = true
    clearInterval(this._tickInterval)
    for (const timer of this._pendingTimers) {
      clearTimeout(timer)
    }
    await this.io.destroy()
    if (emitClose) this.emit('close')
  }

  _request(to, force, internal, command, target, value, session, onresponse, onerror) {
    if (internal && !this._sendDownHints && command === DOWN_HINT) return null
    const req = this.io.createRequest(to, null, internal, command, target, value, session)
    if (req === null) return null

    req.onresponse = onresponse
    req.onerror = onerror
    req.send(force)

    return req
  }

  _natAdd(host, port) {
    const prevHost = this._nat.host
    const prevPort = this._nat.port

    this._nat.add(host, port)

    if (prevHost === this._nat.host && prevPort === this._nat.port) return

    this.emit('nat-update', this._nat.host, this._nat.port)
  }

  // we don't check that this is a bootstrap node but we limit the sample size to very few nodes, so fine
  _sampleBootstrapMaybe(from, to) {
    if (this._nonePersistentSamples.length >= Math.max(1, this.bootstrapNodes.length)) return
    const id = from.host + ':' + from.port
    if (this._nonePersistentSamples.indexOf(id) > -1) return
    this._nonePersistentSamples.push(id)
    this._natAdd(to.host, to.port)
  }

  _addNodeFromNetwork(sample, from, to) {
    if (this._filterNode !== null && !this._filterNode(from)) {
      return
    }

    if (from.id === null) {
      this._sampleBootstrapMaybe(from, to)
      return
    }

    const oldNode = this.table.get(from.id)

    // refresh it, if we've seen this before
    if (oldNode) {
      if (sample && (oldNode.sampled === 0 || this._tick - oldNode.sampled >= OLD_NODE)) {
        oldNode.to = to
        oldNode.sampled = this._tick
        this._natAdd(to.host, to.port)
      }

      oldNode.pinged = oldNode.seen = this._tick
      this.nodes.add(oldNode)
      return
    }

    this._addNode({
      id: from.id,
      port: from.port,
      host: from.host,
      to,
      sampled: 0,
      added: this._tick,
      pinged: this._tick, // last time we interacted with them
      seen: this._tick, // last time we heard from them
      downHints: 0,
      prev: null,
      next: null
    })
  }

  _addNode(node) {
    if (this.nodes.has(node) || b4a.equals(node.id, this.table.id)) return

    node.added = node.pinged = node.seen = this._tick

    if (!this.table.add(node)) return
    this.nodes.add(node)

    if (node.to && node.sampled === 0) {
      node.sampled = this._tick
      this._natAdd(node.to.host, node.to.port)
    }

    this.emit('add-node', node)
  }

  _removeStaleNode(node, lastSeen) {
    if (node.seen <= lastSeen) this._removeNode(node)
  }

  _removeNode(node) {
    if (!this.nodes.has(node)) return

    this.table.remove(node.id)
    this.nodes.remove(node)

    this.emit('remove-node', node)
  }

  _onwakeup() {
    this._tick += 2 * OLD_NODE // bump the tick enough that everything appears old.
    this._tick += 8 - (this._tick & 7) - 2 // triggers a series of pings in two ticks
    this._stableTicks = MORE_STABLE_TICKS
    this._refreshTicks = 1 // triggers a refresh next tick (allow network time to wake up also)
    this._lastHost = null // clear network cache check
    this.health.reset()

    if (this.adaptive) {
      // TODO: re-enable this as soon as we find out why this is over triggering in some edge cases
      // this.firewalled = true
      // this.io.firewalled = true

      if (!this.ephemeral) {
        this.ephemeral = true
        this.io.ephemeral = true
        this.emit('ephemeral')
      }
    }

    this.emit('wakeup')
  }

  _onfullrow(newNode, row) {
    if (!this.bootstrapped || this._repinging >= 3) return

    let oldest = null
    for (const node of row.nodes) {
      if (node.pinged === this._tick) continue
      if (
        oldest === null ||
        oldest.pinged > node.pinged ||
        (oldest.pinged === node.pinged && oldest.added > node.added)
      ) {
        oldest = node
      }
    }

    if (oldest === null) return
    if (this._tick - oldest.pinged < RECENT_NODE && this._tick - oldest.added > OLD_NODE) return

    this._repingAndSwap(newNode, oldest)
  }

  _onnetworkchange(interfaces) {
    this.emit('network-change', interfaces)
    this.emit('network-update')
  }

  _repingAndSwap(newNode, oldNode) {
    const self = this
    const lastSeen = oldNode.seen

    oldNode.pinged = this._tick

    this._repinging++
    this._request(
      { id: null, host: oldNode.host, port: oldNode.port },
      false,
      true,
      PING,
      null,
      null,
      null,
      onsuccess,
      onswap
    )

    function onsuccess(m) {
      if (oldNode.seen <= lastSeen) return onswap()
      self._repinging--
    }

    function onswap(e) {
      self._repinging--
      self._removeNode(oldNode)
      self._addNode(newNode)
    }
  }

  _onrequest(req, external) {
    if (req.from.id !== null) {
      this._addNodeFromNetwork(!external, req.from, req.to)
    }

    if (req.internal) {
      switch (req.command) {
        // standard keep alive call
        case PING: {
          req.sendReply(0, null, false, false)
          return
        }
        case DELAYED_PING: {
          this._ondelayedping(req)
          return
        }
        // check if the other side can receive a message to their other socket
        case PING_NAT: {
          if (req.value === null || req.value.byteLength < 2) return
          const port = c.uint16.decode({ start: 0, end: 2, buffer: req.value })
          if (port === 0) return
          req.from.port = port
          req.sendReply(0, null, false, false)
          return
        }
        // empty dht reply back
        case FIND_NODE: {
          if (!req.target) return
          req.sendReply(0, null, false, true)
          return
        }
        // "this is node you sent me is down" - let's try to ping it
        case DOWN_HINT: {
          if (req.value === null || req.value.byteLength < 6) return
          if (this._checks < 10) {
            sodium.crypto_generichash(TMP, req.value.subarray(0, 6))
            const node = this.table.get(TMP)
            if (node && (node.pinged < this._tick || node.downHints === 0)) {
              node.downHints++
              this._check(node)
            }
          }
          req.sendReply(0, null, false, false)
          return
        }
      }

      req.sendReply(UNKNOWN_COMMAND, null, false, req.target !== null)
      return
    }

    // ask the user to handle it or reply back with a bad command
    if (this.onrequest(req) === false) {
      req.sendReply(UNKNOWN_COMMAND, null, false, req.target !== null)
    }
  }

  onrequest(req) {
    return this.emit('request', req)
  }

  _ondelayedping(req) {
    if (req.value === null || req.value.byteLength < 4) return
    const delayMs = c.uint32.decode({ start: 0, end: 4, buffer: req.value })
    if (delayMs > this.maxPingDelay) return
    const timer = setTimeout(() => {
      if (this.destroyed) return
      this._pendingTimers.delete(timer)
      req.sendReply(0, null, false, false)
    }, delayMs)
    this._pendingTimers.add(timer)
  }

  _onresponse(res, external) {
    this._addNodeFromNetwork(!external, res.from, res.to)
  }

  _ontimeout(req) {
    if (!req.to.id) return
    const node = this.table.get(req.to.id)
    if (node) this._removeNode(node)
  }

  _pingSome() {
    let cnt = this.io.inflight.length > 2 ? 3 : 5
    let oldest = this.nodes.oldest

    // tiny dht, pinged the bootstrap again
    if (!oldest) {
      this.refresh()
      return
    }

    // we've recently pinged the oldest one, so only trigger a couple of repings
    if (this._tick - oldest.pinged < RECENT_NODE) {
      cnt = 2
    }

    while (cnt--) {
      if (!oldest || this._tick === oldest.pinged) continue
      this._check(oldest)
      oldest = oldest.next
    }
  }

  _check(node) {
    node.pinged = this._tick

    const lastSeen = node.seen
    const onresponse = () => {
      this._checks--
      this._removeStaleNode(node, lastSeen)
    }
    const onerror = () => {
      this._checks--
      this._removeNode(node)
    }

    this._checks++
    this._request(
      { id: null, host: node.host, port: node.port },
      false,
      true,
      PING,
      null,
      null,
      null,
      onresponse,
      onerror
    )
  }

  _ontick() {
    const time = Date.now()

    if (time - this._lastTick > SLEEPING_INTERVAL && this.suspended === false) {
      this._onwakeup()
    } else {
      this._tick++
    }

    this._lastTick = time

    if (!this.bootstrapped || this.suspended) return

    if (this.adaptive && this.ephemeral && --this._stableTicks <= 0) {
      if (this._lastHost === this._nat.host) {
        // do not recheck the same network...
        this._stableTicks = MORE_STABLE_TICKS
      } else {
        this._updateNetworkState() // the promise returned here never fails so just ignore it
      }
    }

    if ((this._tick & 7) === 0) {
      this._pingSome()
    }

    if (
      ((this._tick & 63) === 0 && this.nodes.length < this.table.k) ||
      --this._refreshTicks <= 0
    ) {
      this.refresh()
    }

    this._downHintsSentPerTick = 0
    this.health.update()
  }

  async _updateNetworkState(onlyFirewall = false) {
    if (!this.ephemeral) return false
    if (onlyFirewall && !this.firewalled) return false

    const { host, port } = this._nat

    if (!onlyFirewall) {
      // remember what host we checked and reset the counter
      this._stableTicks = MORE_STABLE_TICKS
      this._lastHost = host
    }

    // check if we have a consistent host and port
    if (host === null || port === 0) {
      return false
    }

    const natSampler = this.firewalled ? new NatSampler() : this._nat

    // ask remote nodes to ping us on our server socket to see if we have the port open
    const firewalled = this.firewalled && (await this._checkIfFirewalled(natSampler))
    if (firewalled) return false

    this.firewalled = this.io.firewalled = false

    // incase it's called in parallel for some reason, or if our nat status somehow changed
    if (!this.ephemeral || host !== this._nat.host || port !== this._nat.port) return false
    // if the firewall probe returned a different host / non consistent port, bail as well
    if (natSampler.host !== host || natSampler.port === 0) return false

    const id = peer.id(natSampler.host, natSampler.port)

    if (!onlyFirewall) {
      this.ephemeral = this.io.ephemeral = false
    }

    if (natSampler !== this._nat) {
      const prevHost = this._nat.host
      const prevPort = this._nat.port

      this._nonePersistentSamples = []
      this._nat = natSampler

      if (prevHost !== this._nat.host || prevPort !== this._nat.port) {
        this.emit('nat-update', this._nat.host, this._nat.port)
      }
    }

    // TODO: we should make this a bit more defensive in terms of using more
    // resources to make sure that the new routing table contains as many alive nodes
    // as possible, vs blindly copying them over...

    // all good! copy over the old routing table to the new one
    if (!b4a.equals(this.table.id, id)) {
      const nodes = this.table.toArray()

      this.table = this.io.table = new Table(id)

      for (const node of nodes) {
        if (b4a.equals(node.id, id)) continue
        if (!this.table.add(node)) this.nodes.remove(node)
      }

      this.table.on('row', this._onrow)

      // we need to rebootstrap/refresh since we updated our id
      if (this.bootstrapped) this.refresh()
    }

    if (!this.ephemeral) {
      this.emit('persistent')
    }

    return true
  }

  async *_resolveBootstrapNodes() {
    for (let { host, port } of this.bootstrapNodes) {
      let doLookup = false

      if (host.indexOf('@') === -1) {
        doLookup = true
      } else {
        const [suggestedIP, fallbackHost] = host.split('@')
        try {
          await this.ping({ host: suggestedIP, port })
          host = suggestedIP
        } catch {
          host = fallbackHost
          doLookup = true
        }
      }

      if (doLookup) {
        try {
          host = UDX.isIPv4(host) ? host : (await this.udx.lookup(host, { family: 4 })).host
        } catch {
          continue
        }
      }

      yield {
        id: peer.id(host, port),
        host,
        port
      }
    }
  }

  async _addBootstrapNodes(nodes) {
    for await (const node of this._resolveBootstrapNodes()) {
      nodes.push(node)
    }
  }

  async _checkIfFirewalled(natSampler = new NatSampler()) {
    const nodes = []
    for (let node = this.nodes.latest; node && nodes.length < 5; node = node.prev) {
      nodes.push(node)
    }

    if (nodes.length < 5) await this._addBootstrapNodes(nodes)
    // if no nodes are available, including bootstrappers - bail
    if (nodes.length === 0) return true

    const hosts = new Set()
    const value = b4a.allocUnsafe(2)

    c.uint16.encode({ start: 0, end: 2, buffer: value }, this.io.serverSocket.address().port)

    // double check they actually came on the server socket...
    this.io.serverSocket.on('message', onmessage)

    const pongs = await requestAll(this, true, PING_NAT, value, nodes)

    let count = 0
    for (const res of pongs) {
      if (hosts.has(res.from.host)) {
        count++
        natSampler.add(res.to.host, res.to.port)
      }
    }

    this.io.serverSocket.removeListener('message', onmessage)

    // if we got no or very few replies, consider it a fluke
    if (count < (nodes.length >= 5 ? 3 : 1)) return true

    // check that the server socket has the same ip as the client socket
    if (natSampler.host === null || this._nat.host !== natSampler.host) return true

    // check that the local port of the server socket is the same as the remote port
    // TODO: we might want a flag to opt out of this heuristic for specific remapped port servers
    if (natSampler.port === 0 || natSampler.port !== this.io.serverSocket.address().port) {
      return true
    }

    return false

    function onmessage(_, { host }) {
      hosts.add(host)
    }
  }

  _backgroundQuery(target) {
    this._refreshTicks = REFRESH_TICKS

    const backgroundCon = Math.min(this.concurrency, Math.max(2, (this.concurrency / 8) | 0))
    const q = new Query(this, target, true, FIND_NODE, null, {
      concurrency: backgroundCon
    })

    q.on('data', () => {
      // yield to other traffic
      q.concurrency = this.io.inflight.length < 3 ? this.concurrency : backgroundCon
    })

    return q
  }

  // called by health
  _online() {
    if (this.online && !this.degraded) return
    this.online = true
    this.degraded = false
    this.emit('network-update')
  }

  // called by health
  _degraded() {
    if (this.degraded) return
    this.online = true
    this.degraded = true
    this.emit('network-update')
  }

  // called by health
  _offline() {
    if (!this.online) return
    this.online = false
    this.degraded = false
    this.emit('network-update')
  }
}

DHT.OK = 0
DHT.ERROR_UNKNOWN_COMMAND = UNKNOWN_COMMAND
DHT.ERROR_INVALID_TOKEN = INVALID_TOKEN

module.exports = DHT

function localIP(udx, family = 4) {
  let host = null

  for (const n of udx.networkInterfaces()) {
    if (n.family !== family || n.internal) continue

    // mac really likes en0, mb a better way but this shouldnt be bad anywhere so return now
    if (n.name === 'en0') return n.host

    // otherwise pick the first non internal host (let the loop continue in case we see en0)
    if (host === null) host = n.host
  }

  return host || (family === 4 ? '127.0.0.1' : '::1')
}

function parseNode(s) {
  if (typeof s === 'object') return s
  if (typeof s === 'number') return { host: '127.0.0.1', port: s }
  const [host, port] = s.split(':')
  if (!port) throw new Error('Bootstrap node format is host:port')

  return {
    host,
    port: Number(port)
  }
}

function randomBytes(n) {
  const b = b4a.alloc(n)
  sodium.randombytes_buf(b)
  return b
}

function randomOffset(n) {
  return n - ((Math.random() * 0.5 * n) | 0)
}

function requestAll(dht, internal, command, value, nodes) {
  let missing = nodes.length
  const replies = []

  return new Promise((resolve) => {
    for (const node of nodes) {
      const req = dht._request(
        node,
        false,
        internal,
        command,
        null,
        value,
        null,
        onsuccess,
        onerror
      )
      if (!req) return resolve(replies)
    }

    function onsuccess(res) {
      replies.push(res)
      if (--missing === 0) resolve(replies)
    }

    function onerror() {
      if (--missing === 0) resolve(replies)
    }
  })
}

function noop() {}
exports.PING = 0
exports.PING_NAT = 1
exports.FIND_NODE = 2
exports.DOWN_HINT = 3
exports.DELAYED_PING = 4
module.exports = class DHTError extends Error {
  constructor(msg, code, fn = DHTError) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'DHTError'
  }

  static UNKNOWN_COMMAND = 1
  static INVALID_TOKEN = 2

  static REQUEST_TIMEOUT(msg = 'Request timed out') {
    return new DHTError(msg, 'REQUEST_TIMEOUT', DHTError.REQUEST_TIMEOUT)
  }

  static REQUEST_DESTROYED(msg = 'Request destroyed') {
    return new DHTError(msg, 'REQUEST_DESTROYED', DHTError.REQUEST_DESTROYED)
  }

  static IO_SUSPENDED(msg = 'I/O suspended') {
    return new DHTError(msg, 'IO_SUSPENDED', DHTError.IO_SUSPENDED)
  }
}
const MAX_HEALTH_WINDOW = 4
const OFFLINE_THRESHOLD = 2
const IDLE_THRESHOLD = 4
const DEGRADED_TIMEOUT_RATE_THRESHOLD = 0.5

module.exports = class NetworkHealth {
  constructor(dht) {
    this._dht = dht
    this._window = []
    this._head = -1
    this._offlineTicks = 0
    this._degradedTicks = 0
    this._healthyTicks = 0
    this.online = true
    this.degraded = false
  }

  get oldest() {
    return this._window[this._tail]
  }

  get previous() {
    return this._window[(this._head - 1 + MAX_HEALTH_WINDOW) % MAX_HEALTH_WINDOW]
  }

  get newest() {
    return this._window[this._head]
  }

  get responses() {
    if (!this.newest || !this.previous) return 0
    return this.newest.responses - this.previous.responses
  }

  get timeouts() {
    if (!this.newest || !this.previous) return 0
    return this.newest.timeouts - this.previous.timeouts
  }

  get timeoutsRate() {
    if (this.timeouts === 0) return 0
    return this.timeouts / (this.responses + this.timeouts)
  }

  get cold() {
    return this._window.length < MAX_HEALTH_WINDOW
  }

  get idle() {
    return this.responses + this.timeouts < IDLE_THRESHOLD
  }

  get stats() {
    return {
      online: this.online,
      degraded: this.degraded,
      cold: this.cold,
      idle: this.idle,
      responses: this.responses,
      timeouts: this.timeouts,
      timeoutsRate: this.timeoutsRate
    }
  }

  get _tail() {
    return (this._head + 1) % MAX_HEALTH_WINDOW
  }

  reset() {
    this._window = []
    this._head = -1
    this._offlineTicks = 0
    this._degradedTicks = 0
    this._healthyTicks = 0
    this.online = true
    this.degraded = false
    this._dht._online()
  }

  update() {
    // update counters before dropping oldest
    if (this.oldest?.degraded) this._degradedTicks--
    else if (this.oldest?.degraded === false) this._healthyTicks--

    // move window
    this._head = this._tail
    this._window[this._head] = {
      responses: this._dht.stats.requests.responses,
      timeouts: this._dht.stats.requests.timeouts
    }

    // skip state changes
    if (this.cold || this.idle) return

    // update newest
    this.newest.offline = this.responses === 0
    this.newest.degraded =
      !this.newest.offline && this.timeoutsRate > DEGRADED_TIMEOUT_RATE_THRESHOLD

    // update counters
    if (this.newest.offline) this._offlineTicks++
    else {
      this._offlineTicks = 0
      if (this.newest.degraded) this._degradedTicks++
      else this._healthyTicks++
    }

    // check online/offline
    if (!this.newest.offline) this.online = true
    else if (this._offlineTicks >= OFFLINE_THRESHOLD) this.online = false

    // check degraded
    if (!this.online || this._healthyTicks === MAX_HEALTH_WINDOW) this.degraded = false
    else if (this._degradedTicks === MAX_HEALTH_WINDOW) this.degraded = true

    // fire events
    if (this.online && !this.degraded) this._dht._online()
    else if (this.degraded) this._dht._degraded()
    else this._dht._offline()
  }
}
const FIFO = require('fast-fifo')
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const b4a = require('b4a')
const AdaptiveTimeout = require('adaptive-timeout')
const peer = require('./peer')
const { INVALID_TOKEN, REQUEST_TIMEOUT, REQUEST_DESTROYED, IO_SUSPENDED } = require('./errors')

const VERSION = 0b11
const RESPONSE_ID = (0b0001 << 4) | VERSION
const REQUEST_ID = (0b0000 << 4) | VERSION
const EMPTY_ARRAY = []
const MAX_WINDOW = 80

module.exports = class IO {
  constructor(
    table,
    udx,
    {
      maxWindow = MAX_WINDOW,
      port = 0,
      host = '0.0.0.0',
      anyPort = true,
      firewalled = true,
      onrequest,
      onresponse = noop,
      ontimeout = noop,
      adaptiveTimeout
    } = {}
  ) {
    this.table = table
    this.udx = udx
    this.inflight = []
    this.clientSocket = null
    this.serverSocket = null
    this.firewalled = firewalled !== false
    this.ephemeral = true
    this.congestion = new CongestionWindow(maxWindow)
    this.networkInterfaces = udx.watchNetworkInterfaces()
    this.suspended = false

    this.stats = {
      requests: {
        active: 0,
        total: 0,
        responses: 0,
        timeouts: 0,
        retries: 0
      },
      commands: [
        { tx: 0, rx: 0 }, // tx = transmitted, rx = received
        { tx: 0, rx: 0 },
        { tx: 0, rx: 0 },
        { tx: 0, rx: 0 }
      ]
    }

    this.onrequest = onrequest
    this.onresponse = onresponse
    this.ontimeout = ontimeout

    this._pending = new FIFO()
    this._rotateSecrets = 10
    this._tid = (Math.random() * 65536) | 0
    this._secrets = null
    this._drainInterval = null
    this._destroying = null
    this._binding = null

    // port can be a number or a range [start, to]
    this.portRange = port.length ? port : port === 0 ? [0, 0] : [port, port + 5]

    this._host = host
    this._anyPort = anyPort !== false
    this._boundServerPort = 0
    this._boundClientPort = 0

    this._adt = adaptiveTimeout ? new AdaptiveTimeout(adaptiveTimeout) : null
  }

  static DEFAULT_MAX_WINDOW = MAX_WINDOW

  onmessage(socket, buffer, { host, port }) {
    if (buffer.byteLength < 2 || !(port > 0 && port < 65536) || this.suspended === true) return

    const from = { id: null, host, port }
    const state = { start: 1, end: buffer.byteLength, buffer }
    const expectedSocket = this.firewalled ? this.clientSocket : this.serverSocket
    const external = socket !== expectedSocket

    if (buffer[0] === REQUEST_ID) {
      const req = Request.decode(this, socket, from, state)
      if (req === null) return
      if (
        req.token !== null &&
        !b4a.equals(req.token, this.token(req.from, 1)) &&
        !b4a.equals(req.token, this.token(req.from, 0))
      ) {
        req.error(INVALID_TOKEN, { token: true })
        return
      }
      this.onrequest(req, external)
      return
    }

    if (buffer[0] === RESPONSE_ID) {
      const res = decodeReply(from, state)
      if (res === null) return

      for (let i = 0; i < this.inflight.length; i++) {
        const req = this.inflight[i]
        if (req.tid !== res.tid) continue

        res.rtt = Date.now() - req._timestamp

        if (this._adt && req.sent <= 2) {
          this._adt.put(`${req.to.host}:${req.to.port}`, res.rtt)
        }

        if (i === this.inflight.length - 1) this.inflight.pop()
        else this.inflight[i] = this.inflight.pop()

        if (req.session) req.session._detach(req)

        // TODO: Auto retry here if errors.INVALID_TOKEN is returned?

        if (req._timeout) {
          clearTimeout(req._timeout)
          req._timeout = null
        }

        this.congestion.recv()

        if (req.internal && req.command < this.stats.commands.length) {
          this.stats.commands[req.command].rx++
        }

        this.stats.requests.active--
        this.stats.requests.responses++

        this.onresponse(res, external)
        req.onresponse(res, req)
        break
      }
    }
  }

  token(addr, i) {
    if (this._secrets === null) {
      const buf = b4a.alloc(64)
      this._secrets = [buf.subarray(0, 32), buf.subarray(32, 64)]
      sodium.randombytes_buf(this._secrets[0])
      sodium.randombytes_buf(this._secrets[1])
    }

    const token = b4a.allocUnsafe(32)
    sodium.crypto_generichash(token, b4a.from(addr.host), this._secrets[i])
    return token
  }

  async destroy() {
    if (this._destroying) return this._destroying
    this._destroying = this._destroy()
    return this._destroying
  }

  async _destroy() {
    // simplifies timing to await the bind here also, although it might be unneeded
    await this.bind()
    await this._clear(false)
  }

  async _clear(suspended) {
    if (this._drainInterval) {
      clearInterval(this._drainInterval)
      this._drainInterval = null
    }

    while (this.inflight.length) {
      const req = this.inflight.pop()
      if (req._timeout) clearTimeout(req._timeout)
      req._timeout = null
      req.destroyed = true

      if (req.session) req.session._detach(req)

      this.congestion.recv()
      this.stats.requests.active--

      req.onerror(suspended ? IO_SUSPENDED() : REQUEST_DESTROYED(), req)
    }

    await Promise.allSettled([this.serverSocket.close(), this.clientSocket.close()])

    this.networkInterfaces.destroy()
  }

  async suspend() {
    this.suspended = true
    await this._clear(true)

    this.congestion.clear()

    if (this._drainInterval) {
      clearInterval(this._drainInterval)
      this._drainInterval = null
    }
  }

  async _rebind(binding) {
    if (binding) await binding
    if (this._destroying) return this._destroying
    await this._bindSockets()
    this.networkInterfaces = this.udx.watchNetworkInterfaces()
  }

  resume() {
    this.suspended = false
    const binding = this._binding
    this._binding = this._rebind(binding)
    return this._binding
  }

  bind() {
    if (this._binding) return this._binding
    this._binding = this._bindSockets()
    return this._binding
  }

  async _bindSockets() {
    const serverSocket = this.udx.createSocket()

    const candidatePorts = []

    // Retrying previous port always has precedence
    if (this._boundServerPort) candidatePorts.push(this._boundServerPort)

    for (let i = this.portRange[0]; i < this.portRange[1]; i++) candidatePorts.push(i)

    for (const port of candidatePorts) {
      if (serverSocket.bound) break

      try {
        serverSocket.bind(port, this._host)
      } catch (err) {
        if (!this._anyPort) {
          await serverSocket.close()
          throw err
        }
      }
    }

    if (!serverSocket.bound) {
      try {
        serverSocket.bind(0, this._host)
      } catch (err) {
        await serverSocket.close()
        throw err
      }
    }

    const clientSocket = this.udx.createSocket()

    try {
      clientSocket.bind(this._boundClientPort || 0, this._host)
    } catch {
      try {
        clientSocket.bind(0, this._host)
      } catch (err) {
        await serverSocket.close()
        await clientSocket.close()
        throw err
      }
    }

    this._boundServerPort = serverSocket.address().port
    this._boundClientPort = clientSocket.address().port

    this.clientSocket = clientSocket
    this.serverSocket = serverSocket

    this.serverSocket.on('message', this.onmessage.bind(this, this.serverSocket))
    this.clientSocket.on('message', this.onmessage.bind(this, this.clientSocket))

    if (this._drainInterval === null) {
      this._drainInterval = setInterval(this._drain.bind(this), 750)
      if (this._drainInterval.unref) this._drainInterval.unref()
    }

    for (const req of this.inflight) {
      if (!req.socket) req.socket = this.firewalled ? this.clientSocket : this.serverSocket
      req.sent = 0
      req.send(false)
    }
  }

  _drain() {
    if (this._secrets !== null && --this._rotateSecrets === 0) {
      this._rotateSecrets = 10
      const tmp = this._secrets[0]
      this._secrets[0] = this._secrets[1]
      this._secrets[1] = tmp
      sodium.crypto_generichash(tmp, tmp)
    }

    this.congestion.drain()

    while (!this.congestion.isFull()) {
      const p = this._pending.shift()
      if (p === undefined) return
      p._sendNow()
    }
  }

  createRequest(to, token, internal, command, target, value, session, ttl) {
    if (this._destroying !== null) return null

    if (this._tid === 65536) this._tid = 0

    const tid = this._tid++
    const socket = this.firewalled ? this.clientSocket : this.serverSocket

    const req = new Request(
      this,
      socket,
      tid,
      null,
      to,
      token,
      internal,
      command,
      target,
      value,
      session,
      ttl || 0
    )
    this.inflight.push(req)
    if (session) session._attach(req)

    if (internal && command < this.stats.commands.length) {
      this.stats.commands[command].tx++
    }

    this.stats.requests.active++
    this.stats.requests.total++

    return req
  }
}

class Request {
  constructor(io, socket, tid, from, to, token, internal, command, target, value, session, ttl) {
    this.socket = socket
    this.tid = tid
    this.from = from
    this.to = to
    this.token = token
    this.command = command
    this.target = target
    this.value = value
    this.internal = internal
    this.session = session
    this.ttl = ttl
    this.index = -1
    this.sent = 0
    this.retries = 3
    this.destroyed = false
    this.timeout = 0

    this.oncycle = noop
    this.onerror = noop
    this.onresponse = noop

    this._buffer = null
    this._io = io
    this._timeout = null
    this._timestamp = Date.now()
  }

  static decode(io, socket, from, state) {
    try {
      const flags = c.uint.decode(state)
      const tid = c.uint16.decode(state)
      const to = peer.ipv4.decode(state)
      const id = flags & 1 ? c.fixed32.decode(state) : null
      const token = flags & 2 ? c.fixed32.decode(state) : null
      const internal = (flags & 4) !== 0
      const command = c.uint.decode(state)
      const target = flags & 8 ? c.fixed32.decode(state) : null
      const value = flags & 16 ? c.buffer.decode(state) : null

      if (id !== null) from.id = validateId(id, from)

      return new Request(
        io,
        socket,
        tid,
        from,
        to,
        token,
        internal,
        command,
        target,
        value,
        null,
        0
      )
    } catch {
      return null
    }
  }

  reply(value, opts = {}) {
    const socket = opts.socket || this.socket
    const to = opts.to || this.from
    this._sendReply(0, value || null, opts.token !== false, opts.closerNodes !== false, to, socket)
  }

  error(code, opts = {}) {
    const socket = opts.socket || this.socket
    const to = opts.to || this.from
    this._sendReply(code, null, opts.token === true, opts.closerNodes !== false, to, socket)
  }

  relay(value, to, opts) {
    const socket = (opts && opts.socket) || this.socket
    const buffer = this._encodeRequest(null, value, to, socket)
    socket.trySend(buffer, to.port, to.host, this.ttl)
  }

  send(force = false) {
    if (this.destroyed) return

    if (this.socket === null) return
    if (this._buffer === null) {
      this._buffer = this._encodeRequest(this.token, this.value, this.to, this.socket)
    }

    if (!force && this._io.congestion.isFull()) {
      this._io._pending.push(this)
      return
    }

    this._sendNow()
  }

  sendReply(error, value, token, hasCloserNodes) {
    this._sendReply(error, value, token, hasCloserNodes, this.from, this.socket, null)
  }

  _sendNow() {
    if (this.destroyed) return
    this.sent++
    this._io.congestion.send()
    this.socket.trySend(this._buffer, this.to.port, this.to.host, this.ttl)
    if (this._timeout) clearTimeout(this._timeout)
    const value =
      this.timeout || this._io._adt?.get(`${this.to.host}:${this.to.port}`, this.sent) || 1000
    this._timeout = setTimeout(oncycle, value, this)
  }

  destroy(err) {
    if (this.destroyed) return
    this.destroyed = true

    if (this._timeout) {
      clearTimeout(this._timeout)
      this._timeout = null
    }

    const i = this._io.inflight.indexOf(this)
    if (i === -1) return

    if (i === this._io.inflight.length - 1) this._io.inflight.pop()
    else this._io.inflight[i] = this._io.inflight.pop()

    if (this.session) this.session._detach(this)

    this._io.stats.requests.active--
    this._io.congestion.recv()

    this.onerror(err || REQUEST_DESTROYED(), this)
  }

  _sendReply(error, value, token, hasCloserNodes, from, socket) {
    if (socket === null || this.destroyed) return

    const id = this._io.ephemeral === false && socket === this._io.serverSocket
    const closerNodes =
      this.target !== null && hasCloserNodes ? this._io.table.closest(this.target) : EMPTY_ARRAY
    const state = { start: 0, end: 1 + 1 + 6 + 2, buffer: null } // (type | version) + flags + to + tid

    if (id) state.end += 32
    if (token) state.end += 32
    if (closerNodes.length > 0) peer.ipv4Array.preencode(state, closerNodes)
    if (error > 0) c.uint.preencode(state, error)
    if (value) c.buffer.preencode(state, value)

    state.buffer = b4a.allocUnsafe(state.end)
    state.buffer[state.start++] = RESPONSE_ID
    state.buffer[state.start++] =
      (id ? 1 : 0) |
      (token ? 2 : 0) |
      (closerNodes.length > 0 ? 4 : 0) |
      (error > 0 ? 8 : 0) |
      (value ? 16 : 0)

    c.uint16.encode(state, this.tid)
    peer.ipv4.encode(state, from)

    if (id) c.fixed32.encode(state, this._io.table.id)
    if (token) c.fixed32.encode(state, this._io.token(from, 1))
    if (closerNodes.length > 0) peer.ipv4Array.encode(state, closerNodes)
    if (error > 0) c.uint.encode(state, error)
    if (value) c.buffer.encode(state, value)

    socket.trySend(state.buffer, from.port, from.host, this.ttl)
  }

  _encodeRequest(token, value, to, socket) {
    const id = this._io.ephemeral === false && socket === this._io.serverSocket
    const state = { start: 0, end: 1 + 1 + 6 + 2, buffer: null } // (type | version) + flags + to + tid

    if (id) state.end += 32
    if (token) state.end += 32

    c.uint.preencode(state, this.command)

    if (this.target) state.end += 32
    if (value) c.buffer.preencode(state, value)

    state.buffer = b4a.allocUnsafe(state.end)
    state.buffer[state.start++] = REQUEST_ID
    state.buffer[state.start++] =
      (id ? 1 : 0) |
      (token ? 2 : 0) |
      (this.internal ? 4 : 0) |
      (this.target ? 8 : 0) |
      (value ? 16 : 0)

    c.uint16.encode(state, this.tid)
    peer.ipv4.encode(state, to)

    if (id) c.fixed32.encode(state, this._io.table.id)
    if (token) c.fixed32.encode(state, token)

    c.uint.encode(state, this.command)

    if (this.target) c.fixed32.encode(state, this.target)
    if (value) c.buffer.encode(state, value)

    return state.buffer
  }
}

class CongestionWindow {
  constructor(maxWindow) {
    this._i = 0
    this._total = 0
    this._window = [0, 0, 0, 0]
    this._maxWindow = maxWindow
  }

  clear() {
    this._i = 0
    this._total = 0
    this._window = [0, 0, 0, 0]
  }

  isFull() {
    return this._total >= 2 * this._maxWindow || this._window[this._i] >= this._maxWindow
  }

  recv() {
    if (this._window[this._i] > 0) {
      this._window[this._i]--
      this._total--
    }
  }

  send() {
    this._total++
    this._window[this._i]++
  }

  drain() {
    this._i = (this._i + 1) & 3
    this._total -= this._window[this._i]
    this._window[this._i] = 0 // clear oldest
  }
}

function noop() {}

function oncycle(req) {
  req._timeout = null
  req.oncycle(req)
  if (req.sent > req.retries) {
    req._io.stats.requests.timeouts++
    req.destroy(REQUEST_TIMEOUT())
    req._io.ontimeout(req)
  } else {
    req._io.stats.requests.retries++
    req.send()
  }
}

function decodeReply(from, state) {
  try {
    const flags = c.uint.decode(state)
    const tid = c.uint16.decode(state)
    const to = peer.ipv4.decode(state)
    const id = flags & 1 ? c.fixed32.decode(state) : null
    const token = flags & 2 ? c.fixed32.decode(state) : null
    const closerNodes = flags & 4 ? peer.ipv4Array.decode(state) : null
    const error = flags & 8 ? c.uint.decode(state) : 0
    const value = flags & 16 ? c.buffer.decode(state) : null

    if (id !== null) from.id = validateId(id, from)

    return { tid, rtt: 0, from, to, token, closerNodes, error, value }
  } catch {
    return null
  }
}

function validateId(id, from) {
  const expected = peer.id(from.host, from.port)
  return b4a.equals(expected, id) ? expected : null
}
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const b4a = require('b4a')

const ipv4 = {
  ...c.ipv4Address,
  decode(state) {
    const ip = c.ipv4Address.decode(state)
    return {
      id: null, // populated by the callee
      host: ip.host,
      port: ip.port
    }
  }
}

module.exports = { id, ipv4, ipv4Array: c.array(ipv4) }

function id(host, port, out = b4a.allocUnsafeSlow(32)) {
  const addr = out.subarray(0, 6)
  ipv4.encode({ start: 0, end: 6, buffer: addr }, { host, port })
  sodium.crypto_generichash(out, addr)
  return out
}
const { Readable, getStreamError } = require('streamx')
const b4a = require('b4a')
const peer = require('./peer')
const { DOWN_HINT } = require('./commands')

const DONE = []
const DOWN = []

module.exports = class Query extends Readable {
  constructor(dht, target, internal, command, value, opts = {}) {
    super()

    dht.stats.queries.total++
    dht.stats.queries.active++

    this.force = !!opts.force
    this.dht = dht
    this.k = this.dht.table.k
    this.target = target
    this.internal = internal
    this.command = command
    this.value = value
    this.errors = 0
    this.successes = 0
    this.concurrency = opts.concurrency || this.dht.concurrency
    this.inflight = 0
    this.map = opts.map || defaultMap
    this.retries =
      opts.retries === 0 ? 0 : opts.retries || (this.internal && command === DOWN_HINT ? 3 : 5)
    this.closestReplies = []

    this._slow = 0
    this._slowdown = false
    this._seen = new Map()
    this._pending = []
    this._fromTable = false
    this._commit = opts.commit === true ? autoCommit : opts.commit || null
    this._commiting = false
    this._session = opts.session || dht.session()
    this._autoDestroySession = !opts.session
    this._onlyClosestNodes = false

    this._onvisitbound = this._onvisit.bind(this)
    this._onerrorbound = this._onerror.bind(this)
    this._oncyclebound = this._oncycle.bind(this)

    const nodes = opts.nodes || opts.closestNodes
    const replies = opts.replies || opts.closestReplies

    // add them reverse as we pop below
    if (nodes) {
      for (let i = nodes.length - 1; i >= 0; i--) {
        const node = nodes[i]
        this._addPending(
          {
            id: node.id || peer.id(node.host, node.port),
            host: node.host,
            port: node.port
          },
          null
        )
      }
    } else if (replies) {
      for (let i = replies.length - 1; i >= 0; i--) {
        this._addPending(replies[i].from, null)
      }
    }

    if (opts.onlyClosestNodes) this._onlyClosestNodes = true
  }

  get closestNodes() {
    const nodes = new Array(this.closestReplies.length)

    for (let i = 0; i < nodes.length; i++) {
      nodes[i] = this.closestReplies[i].from
    }

    return nodes
  }

  finished() {
    return new Promise((resolve, reject) => {
      if (this.destroyed) {
        const error = getStreamError(this)
        if (error) reject(error)
        else resolve()
        return
      }

      const self = this
      let error = null

      this.resume()
      this.on('error', onerror)
      this.on('close', onclose)

      function onclose() {
        self.removeListener('error', onerror)
        self.removeListener('close', onclose)
        if (error) reject(error)
        else resolve()
      }

      function onerror(err) {
        error = err
      }
    })
  }

  _addFromTable() {
    if (this._pending.length >= this.k) return
    this._fromTable = true

    const closest = this.dht.table.closest(this.target, this.k - this._pending.length)

    for (const node of closest) {
      this._addPending({ id: node.id, host: node.host, port: node.port }, null)
    }
  }

  async _open(cb) {
    this._addFromTable()
    if (this._pending.length >= this.k) return cb(null)

    for await (const node of this.dht._resolveBootstrapNodes()) {
      this._addPending(node, null)
    }

    cb(null)
  }

  _isCloser(id) {
    return (
      this.closestReplies.length < this.k ||
      this._compare(id, this.closestReplies[this.closestReplies.length - 1].from.id) < 0
    )
  }

  _addPending(node, ref) {
    if (this._onlyClosestNodes) return false

    const addr = node.host + ':' + node.port
    const refs = this._seen.get(addr)
    const isCloser = this._isCloser(node.id)

    if (refs === DONE) {
      return isCloser
    }

    if (refs === DOWN) {
      if (ref) this._downHint(ref, node)
      return isCloser
    }

    if (refs) {
      if (ref !== null) refs.push(ref)
      return isCloser
    }

    if (!isCloser) {
      return false
    }

    this._seen.set(addr, ref === null ? [] : [ref])
    this._pending.push(node)

    return true
  }

  _read(cb) {
    this._readMore()
    cb(null)
  }

  _readMore() {
    if (this.destroying || this._commiting) return

    const concurrency = (this._slowdown ? 3 : this.concurrency) + this._slow

    while (this.inflight < concurrency && this._pending.length > 0) {
      const next = this._pending.pop()
      if (next && next.id && !this._isCloser(next.id)) continue
      this._visit(next)
    }

    // if reusing closest nodes, slow down after the first readMore tick to allow
    // the closest node a chance to reply before going broad to question more
    if (!this._fromTable && this.successes === 0 && this.errors === 0) {
      this._slowdown = true
    }

    if (this._pending.length > 0) return

    // if no inflight OR all the queries we are waiting on are marked as slow and we have a full result.
    if (
      this.inflight === 0 ||
      (this._slow === this.inflight && this.closestReplies.length >= this.k)
    ) {
      // if more than 3/4 failed and we only used cached nodes, try again from the routing table
      if (!this._fromTable && this.successes < this.k / 4) {
        this._addFromTable()
        this._readMore()
        return
      }

      this._flush()
    }
  }

  _flush() {
    if (this._commiting) return
    this._commiting = true

    if (this._commit === null) {
      this.push(null)
      return
    }

    const p = []
    for (const m of this.closestReplies) p.push(this._commit(m, this.dht, this))
    this._endAfterCommit(p)
  }

  _endAfterCommit(ps) {
    if (!ps.length) {
      this.destroy(new Error('Too few nodes responded'))
      return
    }

    const self = this

    let pending = ps.length
    let success = 0

    for (const p of ps) p.then(ondone, onerror)

    function ondone() {
      success++
      if (--pending === 0) self.push(null)
    }

    function onerror(err) {
      if (--pending > 0) return
      if (success) self.push(null)
      else self.destroy(err)
    }
  }

  _dec(req) {
    if (req.oncycle === noop) {
      this._slow--
    } else {
      req.oncycle = noop
    }
    this.inflight--
  }

  _onvisit(m, req) {
    this._dec(req)

    const addr = req.to.host + ':' + req.to.port
    this._seen.set(addr, DONE)

    if (this._commiting) return

    if (m.error === 0) this.successes++
    else this.errors++

    if (m.error === 0 && m.from.id !== null && this._isCloser(m.from.id)) this._pushClosest(m)

    if (m.closerNodes !== null) {
      for (const node of m.closerNodes) {
        node.id = peer.id(node.host, node.port)
        if (this.dht._filterNode !== null && !this.dht._filterNode(node)) continue
        if (b4a.equals(node.id, this.dht.table.id)) continue
        // TODO: we could continue here instead of breaking to ensure that one of the nodes in the closer list
        // is later marked as DOWN that we gossip that back
        if (!this._addPending(node, m.from)) break
      }
    }

    if (!this._fromTable && this.successes + this.errors >= this.concurrency) {
      this._slowdown = false
    }

    if (m.error !== 0) {
      this._readMore()
      return
    }

    const data = this.map(m)
    if (!data || this.push(data) !== false) {
      this._readMore()
    }
  }

  _onerror(err, req) {
    const addr = req.to.host + ':' + req.to.port
    const refs = this._seen.get(addr)

    if (err.code === 'REQUEST_TIMEOUT') {
      this._seen.set(addr, DOWN)
      for (const node of refs) this._downHint(node, req.to)
    }

    this._dec(req)
    this.errors++
    this._readMore()
  }

  _oncycle(req) {
    req.oncycle = noop
    this._slow++
    this._readMore()
  }

  _downHint(node, down) {
    // Check rate limit
    if (
      this.dht._downHintsRateLimit !== -1 &&
      this.dht._downHintsSentPerTick >= this.dht._downHintsRateLimit
    ) {
      return null
    }

    this.dht._downHintsSentPerTick++

    const state = { start: 0, end: 6, buffer: b4a.allocUnsafe(6) }
    peer.ipv4.encode(state, down)
    this.dht._request(node, false, true, DOWN_HINT, null, state.buffer, this._session, noop, noop)
  }

  _pushClosest(m) {
    this.closestReplies.push(m)
    for (let i = this.closestReplies.length - 2; i >= 0; i--) {
      const prev = this.closestReplies[i]
      const cmp = this._compare(prev.from.id, m.from.id)
      // if sorted, done!
      if (cmp < 0) break
      // if dup, splice it out (rare)
      if (cmp === 0) {
        this.closestReplies.splice(i + 1, 1)
        break
      }
      // swap and continue down
      this.closestReplies[i + 1] = prev
      this.closestReplies[i] = m
    }
    if (this.closestReplies.length > this.k) this.closestReplies.pop()
  }

  _compare(a, b) {
    for (let i = 0; i < a.length; i++) {
      if (a[i] === b[i]) continue
      const t = this.target[i]
      return (t ^ a[i]) - (t ^ b[i])
    }
    return 0
  }

  _visit(to) {
    this.inflight++

    const req = this.dht._request(
      to,
      this.force,
      this.internal,
      this.command,
      this.target,
      this.value,
      this._session,
      this._onvisitbound,
      this._onerrorbound
    )
    if (req === null) {
      this.destroy(new Error('Node was destroyed'))
      return
    }
    req.retries = this.retries
    req.oncycle = this._oncyclebound
    if (this.force) req.retries = 0
  }

  _destroy(cb) {
    this.dht.stats.queries.active--
    if (this._autoDestroySession) this._session.destroy()
    cb(null)
  }
}

function autoCommit(reply, dht, query) {
  if (!reply.token) return Promise.reject(new Error('No token received for closest node'))
  return dht.request(
    {
      token: reply.token,
      target: query.target,
      command: query.command,
      value: query.value
    },
    reply.from
  )
}

function defaultMap(m) {
  return m
}

function noop() {}
module.exports = class Session {
  constructor(dht) {
    this.dht = dht
    this.inflight = []
  }

  _attach(req) {
    req.index = this.inflight.push(req) - 1
  }

  _detach(req) {
    const i = req.index
    if (i === -1) return
    req.index = -1

    if (i === this.inflight.length - 1) this.inflight.pop()
    else {
      const req = (this.inflight[i] = this.inflight.pop())
      req.index = i
    }
  }

  query({ target, command, value }, opts = {}) {
    return this.dht.query({ target, command, value }, { ...opts, session: this })
  }

  request({ token, command, target, value }, { host, port }, opts = {}) {
    return this.dht.request(
      { token, command, target, value },
      { host, port },
      { ...opts, session: this }
    )
  }

  ping({ host, port }, opts = {}) {
    return this.dht.ping({ host, port }, { ...opts, session: this })
  }

  destroy(err) {
    while (this.inflight.length) {
      const req = this.inflight[0]
      // prevent destroyed requests from contributing to congestion counts
      this.dht.io.congestion.recv()
      req.destroy(err)
    }
  }
}
{
  "name": "dht-rpc",
  "version": "6.27.0",
  "description": "Make RPC calls over a Kademlia based DHT",
  "main": "index.js",
  "files": [
    "index.js",
    "lib/*.js"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "dependencies": {
    "adaptive-timeout": "^1.0.1",
    "b4a": "^1.6.1",
    "bare-events": "^2.2.0",
    "compact-encoding": "^3.0.0",
    "compact-encoding-net": "^1.2.0",
    "fast-fifo": "^1.1.0",
    "kademlia-routing-table": "^1.0.1",
    "nat-sampler": "^1.0.1",
    "sodium-universal": "^5.0.0",
    "streamx": "^2.13.2",
    "time-ordered-set": "^2.0.0",
    "udx-native": "^1.5.3"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "test-suspend": "^1.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "test": "npm run test:node && npm run test:bare",
    "test:bare": "brittle-bare --coverage test.js",
    "lint": "prettier --check . && lunte",
    "test:node": "brittle-node --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/dht-rpc.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/dht-rpc/issues"
  },
  "homepage": "https://github.com/holepunchto/dht-rpc#"
}
const { encode, decode } = require('./spec/hyperschema')

async function encrypt(data, cb) {
  const result = await cb(data)

  return encode('@encryption/encrypted-data', result)
}

async function decrypt(data, cb) {
  const decoded = decode('@encryption/encrypted-data', data)
  const decrypted = await cb(decoded)

  return decrypted
}

module.exports = { encrypt, decrypt }
{
  "name": "encryption-encoding",
  "version": "1.0.3",
  "description": "Compact encoding for versioned encrypted values with automatic string/buffer handling.",
  "main": "index.js",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    }
  },
  "files": [
    "package.json",
    "index.js",
    "index.d.ts",
    "spec"
  ],
  "keywords": [
    "pear",
    "p2p",
    "bare",
    "autobase",
    "encryption",
    "hyperschema"
  ],
  "devDependencies": {
    "b4a": "^1.7.3",
    "brittle": "^3.19.0",
    "lunte": "^1.2.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "sodium-universal": "^5.0.1"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && lunte && brittle-bare test/all.js",
    "lint": "lunte"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/encryption-encoding.git"
  },
  "author": "Holepunch Inc",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/encryption-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/encryption-encoding",
  "dependencies": {
    "hyperschema": "^1.19.0"
  }
}
// This file is autogenerated by the hyperschema compiler
// Schema Version: 1
/* eslint-disable camelcase */
/* eslint-disable quotes */
/* eslint-disable space-before-function-paren */

const { c } = require('hyperschema/runtime')

const VERSION = 1

// eslint-disable-next-line no-unused-vars
let version = VERSION

// @encryption/encrypted-data
const encoding0 = {
  preencode(state, m) {
    c.uint.preencode(state, m.type)
    c.buffer.preencode(state, m.value)
  },
  encode(state, m) {
    c.uint.encode(state, m.type)
    c.buffer.encode(state, m.value)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const r1 = c.buffer.decode(state)

    return {
      type: r0,
      value: r1
    }
  }
}

function setVersion(v) {
  version = v
}

function encode(name, value, v = VERSION) {
  version = v
  return c.encode(getEncoding(name), value)
}

function decode(name, buffer, v = VERSION) {
  version = v
  return c.decode(getEncoding(name), buffer)
}

function getEnum(name) {
  switch (name) {
    default:
      throw new Error('Enum not found ' + name)
  }
}

function getEncoding(name) {
  switch (name) {
    case '@encryption/encrypted-data':
      return encoding0
    default:
      throw new Error('Encoder not found ' + name)
  }
}

function getStruct(name, v = VERSION) {
  const enc = getEncoding(name)
  return {
    preencode(state, m) {
      version = v
      enc.preencode(state, m)
    },
    encode(state, m) {
      version = v
      enc.encode(state, m)
    },
    decode(state) {
      version = v
      return enc.decode(state)
    }
  }
}

const resolveStruct = getStruct // compat

module.exports = {
  resolveStruct,
  getStruct,
  getEnum,
  getEncoding,
  encode,
  decode,
  setVersion,
  version
}
module.exports = require('bare-events')
{
  "name": "events-universal",
  "version": "1.0.1",
  "description": "Universal wrapper for the Node.js events module",
  "exports": {
    "./package": "./package.json",
    ".": {
      "bare": "./bare.js",
      "react-native": "./react-native.js",
      "default": "./default.js"
    }
  },
  "files": [
    "index.js",
    "default.js",
    "bare.js",
    "react-native.js"
  ],
  "scripts": {
    "test": "prettier . --check"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/events-universal.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/events-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/events-universal#readme",
  "dependencies": {
    "bare-events": "^2.7.0"
  },
  "devDependencies": {
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^1.0.0"
  }
}
module.exports = class FixedFIFO {
  constructor (hwm) {
    if (!(hwm > 0) || ((hwm - 1) & hwm) !== 0) throw new Error('Max size for a FixedFIFO should be a power of two')
    this.buffer = new Array(hwm)
    this.mask = hwm - 1
    this.top = 0
    this.btm = 0
    this.next = null
  }

  clear () {
    this.top = this.btm = 0
    this.next = null
    this.buffer.fill(undefined)
  }

  push (data) {
    if (this.buffer[this.top] !== undefined) return false
    this.buffer[this.top] = data
    this.top = (this.top + 1) & this.mask
    return true
  }

  shift () {
    const last = this.buffer[this.btm]
    if (last === undefined) return undefined
    this.buffer[this.btm] = undefined
    this.btm = (this.btm + 1) & this.mask
    return last
  }

  peek () {
    return this.buffer[this.btm]
  }

  isEmpty () {
    return this.buffer[this.btm] === undefined
  }
}
const FixedFIFO = require('./fixed-size')

module.exports = class FastFIFO {
  constructor (hwm) {
    this.hwm = hwm || 16
    this.head = new FixedFIFO(this.hwm)
    this.tail = this.head
    this.length = 0
  }

  clear () {
    this.head = this.tail
    this.head.clear()
    this.length = 0
  }

  push (val) {
    this.length++
    if (!this.head.push(val)) {
      const prev = this.head
      this.head = prev.next = new FixedFIFO(2 * this.head.buffer.length)
      this.head.push(val)
    }
  }

  shift () {
    if (this.length !== 0) this.length--
    const val = this.tail.shift()
    if (val === undefined && this.tail.next) {
      const next = this.tail.next
      this.tail.next = null
      this.tail = next
      return this.tail.shift()
    }

    return val
  }

  peek () {
    const val = this.tail.peek()
    if (val === undefined && this.tail.next) return this.tail.next.peek()
    return val
  }

  isEmpty () {
    return this.length === 0
  }
}
{
  "name": "fast-fifo",
  "version": "1.3.2",
  "description": "A fast fifo implementation similar to the one powering nextTick in Node.js core",
  "main": "index.js",
  "files": [
    "./index.js",
    "./fixed-size.js"
  ],
  "dependencies": {},
  "devDependencies": {
    "standard": "^17.1.0",
    "brittle": "^3.3.2"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/fast-fifo.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/fast-fifo/issues"
  },
  "homepage": "https://github.com/mafintosh/fast-fifo"
}
const fs = require('fs')
const fsx = require('fs-native-extensions')
const onexit = require('resource-on-exit')
const ReadyResource = require('ready-resource')

module.exports = class FDLock extends ReadyResource {
  constructor(fd, opts = {}) {
    const { wait = false } = opts

    super()

    this._fd = fd
    this._wait = wait
    this._locked = false

    onexit.add(this, closeSync)
  }

  async _open() {
    try {
      await this._resume()
    } catch (err) {
      onexit.remove(this)
      await close(this)
      throw err
    }
  }

  async _close() {
    onexit.remove(this)
    await close(this)
  }

  transfer() {
    const fd = this._fd
    if (fd === -1) throw new Error('Lock has already been transferred')
    this._fd = -1
    onexit.remove(this)
    return fd
  }

  async suspend() {
    if (!this.opened) await this.ready()
    return this._suspend()
  }

  async _suspend() {
    if (this._fd === -1 || this._locked === false) return
    fsx.unlock(this._fd)
    this._locked = false
  }

  async resume() {
    if (!this.opened) await this.ready()
    return this._resume()
  }

  async _resume() {
    if (this._fd === -1 || this._locked === true) return
    if (this._wait) await fsx.waitForLock(this._fd)
    else if (!fsx.tryLock(this._fd)) {
      throw new Error('File descriptor could not be locked')
    }
    this._locked = true
  }
}

function close(lock) {
  const fd = lock._fd
  if (fd === -1) return
  lock._fd = -1
  return new Promise((resolve) => fs.close(fd, () => resolve()))
}

function closeSync(lock) {
  const fd = lock._fd
  if (fd === -1) return
  lock._fd = -1
  try {
    fs.closeSync(fd)
  } catch {}
}
{
  "name": "fd-lock",
  "version": "2.1.1",
  "description": "Stateful file descriptor locks for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": "./index.js"
  },
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    }
  },
  "files": [
    "index.js"
  ],
  "scripts": {
    "test": "npm run lint && npm run test:bare && npm run test:node",
    "test:bare": "bare test.js",
    "test:node": "node test.js",
    "lint": "prettier --check .",
    "format": "prettier --write ."
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/fd-lock.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/fd-lock/issues"
  },
  "homepage": "https://github.com/holepunchto/fd-lock#readme",
  "dependencies": {
    "bare-fs": "^4.5.0",
    "fs-native-extensions": "^1.4.4",
    "ready-resource": "^1.2.0",
    "resource-on-exit": "^1.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
exports.fullRoots = function (index, result) {
  if (index & 1) throw new Error('You can only look up roots for depth(0) blocks')
  if (!result) result = []

  index /= 2

  let offset = 0
  let factor = 1

  while (true) {
    if (!index) return result
    while (factor * 2 <= index) factor *= 2
    result.push(offset + factor - 1)
    offset = offset + 2 * factor
    index -= factor
    factor = 1
  }
}

exports.futureRoots = function (index, result) {
  if (index & 1) throw new Error('You can only look up future roots for depth(0) blocks')
  if (!result) result = []

  let factor = 1

  // make first root
  while (factor * 2 <= index) factor *= 2

  // full factor of 2 - done
  if (factor * 2 - 2 === index) return result

  let pos = factor / 2 - 1

  // while its not a full tree
  while ((pos + factor / 2 - 1) !== index) {
    pos += factor

    // read too far, to to left child
    while ((pos + factor / 2 - 1) > index) {
      factor /= 2
      pos -= factor / 2
    }

    // the "gap" is a future root
    result.push(pos - factor / 2)
  }

  return result
}

exports.patch = function (from, to) {
  if (from === 0 || from >= to) return []

  const roots = exports.fullRoots(from)
  const target = exports.fullRoots(to)

  // first find the first root that is different

  let i = 0
  for (; i < target.length; i++) {
    if (i >= roots.length || roots[i] !== target[i]) break
  }

  const patch = []

  if (i < roots.length) {
    // now we need to grow the newest root until it hits the diff one
    let prev = roots.length - 1

    const ite = exports.iterator(roots[prev--])

    while (ite.index !== target[i]) {
      ite.sibling()

      if (prev >= 0 && ite.index === roots[prev]) {
        prev--
      } else {
        patch.push(ite.index)
      }

      patch.push(ite.parent())
    }

    i++ // patched to next root, so inc
  }

  // include the rest

  for (; i < target.length; i++) patch.push(target[i])

  return patch
}

exports.depth = function (index) {
  let depth = 0

  index += 1
  while (!(index & 1)) {
    depth++
    index = rightShift(index)
  }

  return depth
}

exports.sibling = function (index, depth) {
  if (!depth) depth = exports.depth(index)
  const offset = exports.offset(index, depth)

  return exports.index(depth, offset & 1 ? offset - 1 : offset + 1)
}

exports.parent = function (index, depth) {
  if (!depth) depth = exports.depth(index)
  const offset = exports.offset(index, depth)

  return exports.index(depth + 1, rightShift(offset))
}

exports.leftChild = function (index, depth) {
  if (!(index & 1)) return -1
  if (!depth) depth = exports.depth(index)
  return exports.index(depth - 1, exports.offset(index, depth) * 2)
}

exports.rightChild = function (index, depth) {
  if (!(index & 1)) return -1
  if (!depth) depth = exports.depth(index)
  return exports.index(depth - 1, 1 + (exports.offset(index, depth) * 2))
}

exports.children = function (index, depth) {
  if (!(index & 1)) return null

  if (!depth) depth = exports.depth(index)
  const offset = exports.offset(index, depth) * 2

  return [
    exports.index(depth - 1, offset),
    exports.index(depth - 1, offset + 1)
  ]
}

exports.leftSpan = function (index, depth) {
  if (!(index & 1)) return index
  if (!depth) depth = exports.depth(index)
  return exports.offset(index, depth) * twoPow(depth + 1)
}

exports.rightSpan = function (index, depth) {
  if (!(index & 1)) return index
  if (!depth) depth = exports.depth(index)
  return (exports.offset(index, depth) + 1) * twoPow(depth + 1) - 2
}

exports.nextLeaf = function (index) {
  let factor = 1
  let r = index

  while ((r & 1) === 1) {
    r = (r - 1) / 2
    factor *= 2
  }

  return index + factor + 1
}

exports.count = function (index, depth) {
  if (!(index & 1)) return 1
  if (!depth) depth = exports.depth(index)
  return twoPow(depth + 1) - 1
}

exports.countLeaves = function (index) {
  return (exports.count(index) + 1) / 2
}

exports.spans = function (index, depth) {
  if (!(index & 1)) return [index, index]
  if (!depth) depth = exports.depth(index)

  const offset = exports.offset(index, depth)
  const width = twoPow(depth + 1)

  return [offset * width, (offset + 1) * width - 2]
}

exports.index = function (depth, offset) {
  return (1 + 2 * offset) * twoPow(depth) - 1
}

exports.offset = function (index, depth) {
  if (!(index & 1)) return index / 2
  if (!depth) depth = exports.depth(index)

  return ((index + 1) / twoPow(depth) - 1) / 2
}

exports.iterator = function (index) {
  const ite = new Iterator()
  ite.seek(index || 0)
  return ite
}

function twoPow (n) {
  return n < 31 ? 1 << n : ((1 << 30) * (1 << (n - 30)))
}

function rightShift (n) {
  return (n - (n & 1)) / 2
}

function Iterator () {
  this.index = 0
  this.offset = 0
  this.factor = 0
}

Iterator.prototype.seek = function (index) {
  this.index = index
  if (this.index & 1) {
    this.offset = exports.offset(index)
    this.factor = twoPow(exports.depth(index) + 1)
  } else {
    this.offset = index / 2
    this.factor = 2
  }
}

Iterator.prototype.isLeft = function () {
  return (this.offset & 1) === 0
}

Iterator.prototype.isRight = function () {
  return (this.offset & 1) === 1
}

Iterator.prototype.isRoot = function (length) {
  const currentLength = 1 + (this.index + this.factor / 2 - 1) / 2
  if (length < currentLength) return false

  const factor = this.factor * 2
  const index = (this.offset & 1)
    ? this.index - this.factor / 2
    : this.index + this.factor / 2

  const parentLength = 1 + (index + factor / 2 - 1) / 2
  return parentLength > length
}

Iterator.prototype.contains = function (index) {
  return index > this.index
    ? index < (this.index + this.factor / 2)
    : index < this.index
      ? index > (this.index - this.factor / 2)
      : true
}

Iterator.prototype.prev = function () {
  if (!this.offset) return this.index
  this.offset--
  this.index -= this.factor
  return this.index
}

Iterator.prototype.next = function () {
  this.offset++
  this.index += this.factor
  return this.index
}

Iterator.prototype.count = function () {
  if (!(this.index & 1)) return 1
  return this.factor - 1
}

Iterator.prototype.countLeaves = function () {
  return (this.count() + 1) / 2
}

Iterator.prototype.sibling = function () {
  return this.isLeft() ? this.next() : this.prev()
}

Iterator.prototype.parent = function () {
  if (this.offset & 1) {
    this.index -= this.factor / 2
    this.offset = (this.offset - 1) / 2
  } else {
    this.index += this.factor / 2
    this.offset /= 2
  }
  this.factor *= 2
  return this.index
}

Iterator.prototype.leftSpan = function () {
  this.index = this.index - this.factor / 2 + 1
  this.offset = this.index / 2
  this.factor = 2
  return this.index
}

Iterator.prototype.peekLeftSpan = function () {
  return this.index - this.factor / 2 + 1
}

Iterator.prototype.rightSpan = function () {
  this.index = this.index + this.factor / 2 - 1
  this.offset = this.index / 2
  this.factor = 2
  return this.index
}

Iterator.prototype.peekRightSpan = function () {
  return this.index + this.factor / 2 - 1
}

Iterator.prototype.leftChild = function () {
  if (this.factor === 2) return this.index
  this.factor /= 2
  this.index -= this.factor / 2
  this.offset *= 2
  return this.index
}

Iterator.prototype.rightChild = function () {
  if (this.factor === 2) return this.index
  this.factor /= 2
  this.index += this.factor / 2
  this.offset = 2 * this.offset + 1
  return this.index
}

Iterator.prototype.nextTree = function () {
  this.index = this.index + this.factor / 2 + 1
  this.offset = this.index / 2
  this.factor = 2
  return this.index
}

Iterator.prototype.prevTree = function () {
  if (!this.offset) {
    this.index = 0
    this.factor = 2
  } else {
    this.index = this.index - this.factor / 2 - 1
    this.offset = this.index / 2
    this.factor = 2
  }
  return this.index
}

Iterator.prototype.fullRoot = function (index) {
  if (index <= this.index || (this.index & 1) > 0) return false
  while (index > this.index + this.factor + this.factor / 2) {
    this.index += this.factor / 2
    this.factor *= 2
    this.offset /= 2
  }
  return true
}
{
  "name": "flat-tree",
  "version": "1.13.0",
  "description": "A series of functions to map a binary tree to a list",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {},
  "devDependencies": {
    "brittle": "^3.3.2",
    "standard": "^17.1.0"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/flat-tree.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/flat-tree/issues"
  },
  "homepage": "https://github.com/mafintosh/flat-tree"
}
require.addon = require('require-addon')

module.exports = require.addon('.', __filename)
const { isWindows } = require('which-runtime')
const binding = require('./binding')

function onwork(err, result) {
  if (err) this.reject(err)
  else this.resolve(result)
}

exports.tryLock = function tryLock(fd, offset = 0, length = 0, opts = {}) {
  if (typeof offset === 'object') {
    opts = offset
    offset = 0
  }

  if (typeof length === 'object') {
    opts = length
    length = 0
  }

  if (typeof opts !== 'object' || opts === null) {
    opts = {}
  }

  try {
    binding.tryLock(fd, offset, length, opts.shared !== true)
  } catch (err) {
    if (err.code === 'EAGAIN') return false
    throw err
  }

  return true
}

exports.waitForLock = function waitForLock(fd, offset = 0, length = 0, opts = {}) {
  if (typeof offset === 'object') {
    opts = offset
    offset = 0
  }

  if (typeof length === 'object') {
    opts = length
    length = 0
  }

  if (typeof opts !== 'object' || opts === null) {
    opts = {}
  }

  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.waitForLock(fd, offset, length, opts.shared !== true, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.waitForLockSync = function waitForLockSync(fd, offset = 0, length = 0, opts = {}) {
  if (typeof offset === 'object') {
    opts = offset
    offset = 0
  }

  if (typeof length === 'object') {
    opts = length
    length = 0
  }

  if (typeof opts !== 'object' || opts === null) {
    opts = {}
  }

  binding.waitForLockSync(fd, offset, length, opts.shared !== true)
}

exports.tryDowngradeLock = function tryDowngradeLock(fd, offset = 0, length = 0) {
  try {
    binding.tryDowngradeLock(fd, offset, length)
  } catch (err) {
    if (err.code === 'EAGAIN') return false
    throw err
  }

  return true
}

exports.waitForDowngradeLock = function downgradeLock(fd, offset = 0, length = 0) {
  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.waitForDowngradeLock(fd, offset, length, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.waitForDowngradeLockSync = function waitForDowngradeLockSync(fd, offset = 0, length = 0) {
  binding.waitForDowngradeLockSync(fd, offset, length)
}

exports.tryUpgradeLock = function tryUpgradeLock(fd, offset = 0, length = 0) {
  try {
    binding.tryUpgradeLock(fd, offset, length)
  } catch (err) {
    if (err.code === 'EAGAIN') return false
    throw err
  }

  return true
}

exports.waitForUpgradeLock = function upgradeLock(fd, offset = 0, length = 0) {
  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.waitForUpgradeLock(fd, offset, length, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.waitForUpgradeLockSync = function waitForUpgradeLockSync(fd, offset = 0, length = 0) {
  binding.waitForUpgradeLockSync(fd, offset, length)
}

exports.unlock = function unlock(fd, offset = 0, length = 0) {
  binding.unlock(fd, offset, length)
}

exports.trim = function trim(fd, offset, length) {
  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.trim(fd, offset, length, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.trimSync = function trimSync(fd, offset, length) {
  binding.trimSync(fd, offset, length)
}

exports.sparse = function sparse(fd) {
  // Short circuit on everything but Windows
  if (!isWindows) return Promise.resolve()

  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.sparse(fd, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.sparseSync = function sparseSync(fd) {
  // Short circuit on everything but Windows
  if (!isWindows) return

  binding.sparseSync(fd)
}

exports.swap = function swap(from, to) {
  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.swap(from, to, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.swapSync = function swapSync(from, to) {
  binding.swapSync(from, to)
}

exports.getAttr = function getAttr(fd, name) {
  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.getAttr(fd, name, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise.then((buffer) => (buffer === null ? null : Buffer.from(buffer)))
}

exports.getAttrSync = function getAttrSync(fd, name) {
  const buffer = binding.getAttrSync(fd, name)
  return buffer === null ? null : Buffer.from(buffer)
}

exports.setAttr = function setAttr(fd, name, value, encoding) {
  if (typeof value === 'string') value = Buffer.from(value, encoding)

  const req = {
    value,
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.setAttr(
      fd,
      name,
      value.buffer,
      value.byteOffset,
      value.byteLength,
      req,
      onwork
    )
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.setAttrSync = function setAttrSync(fd, name, value, encoding) {
  if (typeof value === 'string') value = Buffer.from(value, encoding)

  binding.setAttrSync(fd, name, value.buffer, value.byteOffset, value.byteLength)
}

exports.removeAttr = function removeAttr(fd, name) {
  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.removeAttr(fd, name, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.removeAttrSync = function removeAttrSync(fd, name) {
  binding.removeAttrSync(fd, name)
}

exports.listAttrs = function listAttrs(fd) {
  const req = {
    handle: null,
    resolve: null,
    reject: null
  }

  const promise = new Promise((resolve, reject) => {
    req.resolve = resolve
    req.reject = reject
  })

  try {
    req.handle = binding.listAttrs(fd, req, onwork)
  } catch (err) {
    return Promise.reject(err)
  }

  return promise
}

exports.listAttrsSync = function listAttrsSync(fd) {
  return binding.listAttrsSync(fd)
}
{
  "name": "fs-native-extensions",
  "version": "1.5.0",
  "description": "Native file system extensions for advanced file operations",
  "main": "index.js",
  "files": [
    "index.js",
    "macros.h",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "include",
    "src",
    "prebuilds"
  ],
  "imports": {
    "child_process": {
      "bare": "bare-subprocess",
      "default": "child_process"
    },
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "fs/*": {
      "bare": "bare-fs/*",
      "default": "fs/*"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    }
  },
  "addon": true,
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:bare": "brittle-bare --coverage test.js",
    "test:node": "brittle-node --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/fs-native-extensions.git"
  },
  "author": "Kasper Isager Dalsgarð <kasper@funktionel.co>",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/fs-native-extensions/issues"
  },
  "homepage": "https://github.com/holepunchto/fs-native-extensions#readme",
  "dependencies": {
    "require-addon": "^1.1.0",
    "which-runtime": "^1.2.0"
  },
  "devDependencies": {
    "bare-compat-napi": "^1.3.8",
    "bare-fs": "^4.4.4",
    "bare-path": "^3.0.0",
    "bare-subprocess": "^4.0.5",
    "brittle": "^3.1.1",
    "cmake-bare": "^1.1.10",
    "cmake-fetch": "^1.4.7",
    "cmake-napi": "^1.0.5",
    "cmake-npm": "^1.1.0",
    "lunte": "^1.6.0",
    "minimist": "^1.2.6",
    "prettier": "^3.5.3",
    "prettier-config-holepunch": "^2.0.0",
    "test-tmp": "^1.2.1"
  }
}
/**
 * ChunkScheduler — multi-source (torrent-style) fetch of one content-addressed
 * file across several peers, modelled on Hypercore's block replicator.
 *
 * Chunks are content-addressed, so any peer holding the file can serve any
 * chunk. The scheduler:
 *  - requests the chunk list from each peer (identical, content-addressed),
 *  - tracks a global `inflight` map so each chunk is requested from exactly
 *  ONE peer at a time (no wasted bandwidth),
 *  - keeps each peer busy up to a per-peer inflight cap (parallel download),
 *  - reassigns a peer's inflight chunks to others on stall/disconnect,
 *  - hash-verifies every chunk (via TransferManager.writeChunk) and the whole
 *  file before finalizing.
 *
 * It drives the EXISTING v2 wire messages (chunk-need / chunk-data) — no new
 * message type is needed for the full-copy-seeder case. The protocol delegates
 * `_onChunkHashes` / `_onChunkData` to a scheduler ONLY when one is registered
 * for the synthetic `content:<hash>` path, so the legacy single-peer flow
 * is untouched.
 */

import { hashChunk } from './chunker.js'

// P2 — per-peer inflight request window, modelled on hypercore's replicator
// Peer.getMaxInflight (holepunchto/hypercore lib/replicator.js:590). Our content
// chunks are ~64 KB (tier 0 avg 16 KB … tier 3 max 4 MB) — much larger than
// hypercore's blocks — so the range is tuned DOWN from its [16, 512]. A no-udx
// stream (in-memory pair / relay, no RTT signal) gets a modest fixed min*3; a udx
// stream scales the window with RTT and shrinks it as more peers join (fair share).
const INFLIGHT_RANGE = [4, 64]
const SCALE_LATENCY = 50   // ms — at/under this RTT the window stays at min
// Head-of-line fairness — cede the event loop every YIELD_EVERY accepted chunks
// so a burst of buffered chunkData frames (protomux dispatches every frame from
// one socket read synchronously) can't starve other listeners multiplexed on the
// same connection (e.g. Hypercore replication). Kept local (not imported from
// transfer.js) so this module stays Node-loadable for the unit suite.
const yieldToLoop = () => new Promise((resolve) => setTimeout(resolve, 0))
const YIELD_EVERY = 16
// Idle (no-progress) timeout, reset on every accepted chunk and on the
// initial chunk-list response. A steadily-progressing transfer never trips it —
// only a genuine stall (no bytes for this long) fails. A fixed OVERALL timeout
// here capped large transfers (e.g. a multi-GB file at any bandwidth always
// exceeded 30s) and aborted them mid-stream.
const DEFAULT_IDLE_TIMEOUT = 30000
// Local write-error codes that may recover on retry (vs ENOSPC/EACCES/…
// which are fatal): a transient one keeps the chunk retryable instead of failing
// the whole multi-source fetch.
const TRANSIENT_WRITE_CODES = new Set(['EBUSY', 'EAGAIN', 'EINTR', 'EMFILE', 'ENFILE'])
// Min interval between have-progress reports to holders (their sender-side bar).
// Throttles the transferProgress frames so a fast transfer can't spam holders.
const DEFAULT_REPORT_INTERVAL = 1000

export class ChunkScheduler {
  /**
   * @param {object} opts
   *  opts.path synthetic path key ('content:<hash>')
   *  opts.destPath where the assembled file is written
   *  opts.transfer TransferManager
   *  opts.sendNeed (peer, indices[]) => void — sends a chunk-need message
   *  opts.cap per-peer inflight cap (default 8)
   *  opts.timeout idle (no-progress) timeout ms (default 30000)
   *  opts.onProgress optional (receivedBytes, totalBytes) => void on each accepted chunk
   */
  constructor (opts) {
    this.path = opts.path
    this.destPath = opts.destPath
    this._transfer = opts.transfer
    this._sendNeed = opts.sendNeed
    this._cap = opts.cap || 0   // >0 = fixed override; 0 = dynamic RTT-scaled window (P2)
    this._onProgress = opts.onProgress || null
    this._onVerify = opts.onVerify || null
    this._onBaseline = opts.onBaseline || null
    this._reportInterval = opts.reportInterval ?? DEFAULT_REPORT_INTERVAL
    this._lastReportAt = 0
    // cumulative byte accounting so onProgress can drive a
    // remaining-bytes/ETA bar, not just a chunk count.
    this._receivedBytes = 0
    this._totalBytes = 0
    this._sinceYield = 0   // event-loop yield counter (see YIELD_EVERY)

    this._peers = new Set()
    this._started = false
    this._settingUp = false
    this._finalizing = false
    this._done = false
    this._chunks = null            // [{ hash, offset, length }]
    this._needed = new Set()       // indices not yet written
    this._inflight = new Map()     // index → peer (one peer per chunk)
    this._inflightAt = new Map()   // index → assign timestamp (P5 hotswap staleness)
    this._peerInflight = new Map() // peer → count
    // P5 — hotswap: reassign a chunk stalled on a slow peer to an idle faster peer.
    // A chunk inflight this long (ms) while another peer has spare capacity is
    // eligible to be stolen. opts.sendCancel(peer, indices) best-effort tells the
    // slow peer to stop serving them. <0 disables hotswap.
    this._hotswapStallMs = opts.hotswapStallMs ?? 2000
    this._sendCancel = opts.sendCancel || null
    this._hotswaps = 0
    this._received = new Map()     // peer → chunks accepted (multi-source proof)

    this._resolve = null
    this._reject = null
    this._onEnd = opts.onEnd || null
    this._contentHash = opts.contentHash || null   // enables incremental whole-file verify
    this._startedAt = Date.now()
    // idle timeout — re-armed on each progress signal (see _armIdleTimer).
    this._idleTimeout = opts.timeout || DEFAULT_IDLE_TIMEOUT
    this._timer = null
    this._armIdleTimer()
  }

  promise () {
    return new Promise((resolve, reject) => { this._resolve = resolve; this._reject = reject })
  }

  // (Re)arm the no-progress watchdog. Called at construction and on every
  // forward-progress signal so only a genuine stall — no accepted bytes for the
  // idle window — aborts the fetch, regardless of total file size.
  _armIdleTimer () {
    if (this._done) return
    clearTimeout(this._timer)
    this._timer = setTimeout(
      () => this._fail(new Error('multi-source fetch stalled (no progress for ' + this._idleTimeout + 'ms)')),
      this._idleTimeout,
    )
  }

  _reportEnd (ok, reason) {
    if (!this._onEnd) return
    try {
      this._onEnd({
        ok,
        reason,
        receivedBytes: this._receivedBytes,
        totalBytes: this._totalBytes,
        chunksRemaining: this._needed.size,
        totalChunks: this._chunks ? this._chunks.length : 0,
        peers: this._peers.size,
        elapsedMs: Date.now() - this._startedAt,
      })
    } catch {}
  }

  _fail (err) {
    if (this._done) return
    this._done = true
    clearTimeout(this._timer)
    this._reportEnd(false, err.message)
    // Release the receiver state at the failure boundary: journal the hash
    // frontier and close the fd + chunk stash so a never-retried failure parks
    // nothing (the partial stays on disk for a later resume). Best-effort — the
    // external-stop path (cancel) does its own pause/cancel before rejecting.
    if (this._transfer && typeof this._transfer.pause === 'function') {
      try { Promise.resolve(this._transfer.pause(this.destPath)).catch(() => {}) } catch {}
    }
    if (this._reject) this._reject(err)
  }

  _finish () {
    if (this._done) return
    this._done = true
    clearTimeout(this._timer)
    this._reportEnd(true, 'complete')
    if (this._resolve) this._resolve({ chunksPerPeer: this._received, peerCount: this._received.size, size: this._totalBytes })
  }

  // External stop (pause or discard). The partial is kept or unlinked by
  // the caller (OverlayProtocol.cancelContent via TransferManager.pause/cancel)
  // BEFORE this; here we only stop the loop and reject the fetch with ECANCELLED.
  cancel () {
    if (this._done) return
    this._done = true
    clearTimeout(this._timer)
    this._reportEnd(false, 'cancelled')
    const err = new Error('fetch cancelled')
    err.code = 'ECANCELLED'
    if (this._reject) this._reject(err)
  }

  get done () { return this._done }

  // A chunkHashes page arrived while a large map is still
  // streaming across multiple frames. Receiving it is forward progress, so
  // re-arm the no-progress watchdog (the full list dispatches via onChunkHashes
  // only once the final page lands).
  notePageProgress () { if (!this._done && !this._settingUp) this._armIdleTimer() }

  /** A peer responded with the chunk list. First response starts the transfer. */
  async onChunkHashes (peer, chunks) {
    if (this._done) return
    this._peers.add(peer)
    if (!this._peerInflight.has(peer)) this._peerInflight.set(peer, 0)

    if (!this._started) {
      this._started = true
      // The async startReceive (journal-less resume re-verify) can run for a while
      // and accepts no chunks; suppress the no-progress watchdog (including later
      // peers' re-arms) until setup completes, or a concurrent seeder's chunk list
      // would re-arm it and self-trip a healthy resume.
      this._settingUp = true
      clearTimeout(this._timer)
      // Derive offsets from the ordered chunk lengths.
      let offset = 0
      this._chunks = chunks.map((c) => {
        const entry = { hash: c.hash, offset, length: c.length }
        offset += c.length
        return entry
      })
      this._totalBytes = offset   // file size = sum of chunk lengths
      let state
      try {
        state = await this._transfer.startReceive(
          this.destPath,
          { size: offset, chunks: this._chunks, contentHash: this._contentHash },
          { isCancelled: () => this._done, onVerifyProgress: this._onVerify }
        )
      } catch (err) {
        this._settingUp = false
        if (this._done) return
        return this._fail(err)
      }
      this._settingUp = false
      if (this._done) return
      // resume: only fetch chunks the partial doesn't already hold, and
      // seed the byte counter so progress/ETA continue from the resumed offset.
      let have = 0
      for (let i = 0; i < this._chunks.length; i++) {
        if (state.received.has(i)) have += this._chunks[i].length
        else this._needed.add(i)
      }
      this._receivedBytes = have
      if (have > 0) {
        // report our resume have-bytes so holders' sender-side bars mirror our
        // true progress, not just the bytes they re-serve. Re-sent periodically as more
        // chunks land (onChunkData) so late-joining and multi-source holders stay in sync.
        this._reportHave(Date.now())
        if (this._onProgress) { try { this._onProgress(this._receivedBytes, this._totalBytes) } catch {} }
      }
      this._armIdleTimer()
      if (this._needed.size === 0) return this._finalize()
      return this._assign()
    }
    if (!this._settingUp) this._armIdleTimer()   // a later peer's list is forward progress
    this._assign()
  }

  /** A chunk arrived from a peer. Verify + write, then schedule more. */
  async onChunkData (peer, index, data) {
    if (this._done) return
    const res = this._transfer.writeChunk(this.destPath, index, data)
    // Free the inflight slot regardless — a bad chunk should be re-fetched.
    if (this._inflight.get(index) === peer) {
      this._inflight.delete(index)
      this._inflightAt.delete(index)
      this._peerInflight.set(peer, Math.max(0, (this._peerInflight.get(peer) || 1) - 1))
    }
    if (!res.ok) {
      // A coded failure is a local fs error. A TRANSIENT code (device busy,
      // fd pressure, interrupted syscall) can succeed on retry — leave the chunk in
      // `needed` and reassign. Any other coded error (ENOSPC / EACCES / ENOENT / …) is
      // fatal: fail the whole fetch carrying the code. No code = a hash/length
      // mismatch — also retried elsewhere.
      if (res.code && !TRANSIENT_WRITE_CODES.has(res.code)) {
        const err = new Error('write failed: ' + res.error)
        err.code = res.code
        return this._fail(err)
      }
      this._assign()
      return
    }
    this._needed.delete(index)
    this._received.set(peer, (this._received.get(peer) || 0) + 1)
    this._receivedBytes += (data ? data.length : 0)
    this._armIdleTimer()   // accepted bytes — reset the no-progress watchdog
    if (this._onProgress) { try { this._onProgress(this._receivedBytes, this._totalBytes) } catch {} }
    this._maybeReportHave()
    if (this._needed.size === 0 && this._inflight.size === 0) return this._finalize()
    // Periodic event-loop yield (see YIELD_EVERY)
    if (++this._sinceYield >= YIELD_EVERY) {
      this._sinceYield = 0
      await yieldToLoop()
      if (this._done) return
    }
    this._assign()
  }

  // Report our cumulative have-bytes to holders (their sender-side bar). Fired
  // once at resume, then throttled as chunks land, and once at finalize so the bar settles
  // at 100% across every holder regardless of who served what.
  _reportHave (now) {
    if (!this._onBaseline || this._receivedBytes <= 0) return
    this._lastReportAt = now
    try { this._onBaseline(this._receivedBytes) } catch {}
  }

  _maybeReportHave () {
    if (!this._onBaseline) return
    const now = Date.now()
    if (now - this._lastReportAt >= this._reportInterval) this._reportHave(now)
  }

  /** A peer went away — return its inflight chunks to the pool. */
  removePeer (peer) {
    if (!this._peers.has(peer)) return
    this._peers.delete(peer)
    this._peerInflight.delete(peer)
    for (const [index, p] of this._inflight) {
      if (p === peer) { this._inflight.delete(index); this._inflightAt.delete(index) } // back to needed (still in _needed)
    }
    if (this._done) return
    if (this._peers.size === 0 && this._needed.size > 0) {
      return this._fail(new Error('all peers gone with ' + this._needed.size + ' chunk(s) outstanding'))
    }
    this._assign()
  }

  async _finalize () {
    if (this._finalizing || this._done) return
    this._finalizing = true
    this._reportHave(Date.now())   // final have=total so holders' bars settle at 100%
    clearTimeout(this._timer)   // the digest drain can outlast the idle window
    let fin
    try { fin = await this._transfer.finalize(this.destPath) }
    catch (err) { return this._fail(err) }
    if (!fin.ok) {
      const err = new Error('finalize failed: ' + fin.error)
      if (fin.code) err.code = fin.code   // preserve EHASHMISMATCH for the caller
      return this._fail(err)
    }
    this._finish()
  }

  // P2: per-peer inflight window. A fixed opts.cap overrides it (back-compat / tests);
  // otherwise scale with the peer's udx RTT and the peer count exactly as hypercore's
  // Peer.getMaxInflight — window stays at min for low-RTT links, grows for high-RTT
  // ones, and shrinks toward a fair share (×min(1, 2/peers)) as more peers join.
  _maxInflight (peer) {
    if (this._cap) return this._cap
    const [min, max] = INFLIGHT_RANGE
    const raw = peer && peer.mux && peer.mux.stream && peer.mux.stream.rawStream
    if (!raw || !raw.udx || typeof raw.rtt !== 'number') return Math.min(max, min * 3)
    const scale = raw.rtt <= SCALE_LATENCY
      ? 1
      : (raw.rtt / SCALE_LATENCY) * Math.min(1, 2 / Math.max(1, this._peers.size))
    return Math.max(min, Math.round(Math.min(max, min * scale)))
  }

  /** Assign needed-but-not-inflight chunks to peers with spare capacity. */
  _assign () {
    if (this._done || !this._chunks) return
    // Per peer, batch the indices we hand it this round.
    const batches = new Map()
    const now = Date.now()
    for (const peer of this._peers) {
      let slots = this._maxInflight(peer) - (this._peerInflight.get(peer) || 0)
      if (slots <= 0) continue
      for (const index of this._needed) {
        if (slots <= 0) break
        if (this._inflight.has(index)) continue
        this._inflight.set(index, peer)
        this._inflightAt.set(index, now)
        this._peerInflight.set(peer, (this._peerInflight.get(peer) || 0) + 1)
        if (!batches.has(peer)) batches.set(peer, [])
        batches.get(peer).push(index)
        slots--
      }
      // P5: this peer has spare capacity and no un-assigned chunks are left for it —
      // steal the most-stalled chunk(s) inflight to slower peers (the hotswap tail).
      if (slots > 0) this._hotswap(peer, slots, batches, now)
    }
    for (const [peer, indices] of batches) {
      if (indices.length) this._sendNeed(peer, indices)
    }
  }

  // P5 — hotswap tail: reassign chunks that have been inflight to OTHER peers beyond
  // the stall window to `peer` (which is idle-capable), so one slow peer can't hold up
  // the final chunks while faster peers sit idle. Mirrors hypercore's HotswapQueue.
  // Duplicate arrivals (the slow peer may still deliver its copy) are handled
  // idempotently in onChunkData. sendCancel is best-effort bandwidth saving.
  _hotswap (peer, slots, batches, now) {
    if (this._hotswapStallMs < 0) return
    const cands = []
    for (const [index, holder] of this._inflight) {
      if (holder === peer) continue
      if ((now - (this._inflightAt.get(index) || now)) < this._hotswapStallMs) continue
      cands.push(index)
    }
    if (!cands.length) return
    cands.sort((a, b) => (this._inflightAt.get(a) || 0) - (this._inflightAt.get(b) || 0)) // most-stalled first
    const cancels = new Map()
    for (const index of cands) {
      if (slots <= 0) break
      const holder = this._inflight.get(index)
      this._inflight.set(index, peer)
      this._inflightAt.set(index, now)
      this._peerInflight.set(peer, (this._peerInflight.get(peer) || 0) + 1)
      this._peerInflight.set(holder, Math.max(0, (this._peerInflight.get(holder) || 1) - 1))
      if (!batches.has(peer)) batches.set(peer, [])
      batches.get(peer).push(index)
      this._hotswaps++
      if (this._sendCancel) { if (!cancels.has(holder)) cancels.set(holder, []); cancels.get(holder).push(index) }
      slots--
    }
    for (const [holder, indices] of cancels) { try { this._sendCancel(holder, indices) } catch {} }
  }
}

export { hashChunk }
/**
 * FastCDC Content-Defined Chunker
 *
 * Gear rolling hash with normalized chunking (Xia et al. 2016).
 * Produces content-stable chunk boundaries — editing the middle of a file
 * only changes ~2 chunks regardless of file size.
 *
 * v2: Adaptive chunk sizing — tier selected by file size.
 * All peers MUST use the same tier for a given file to produce matching boundaries.
 */

import crypto from 'hypercore-crypto'

// ── Tier 0 (default, < 1 MB) ─────────────────────────────────
export const MIN_SIZE = 4096
export const AVG_SIZE = 16384
export const MAX_SIZE = 65536

// ── Adaptive chunk size tiers ─────────────────────────────────
export const TIERS = [
  { minSize: 4096, avgSize: 16384, maxSize: 65536 },       // Tier 0: < 1 MB
  { minSize: 16384, avgSize: 65536, maxSize: 262144 },     // Tier 1: 1 MB - 100 MB
  { minSize: 65536, avgSize: 262144, maxSize: 1048576 },   // Tier 2: 100 MB - 10 GB
  { minSize: 262144, avgSize: 1048576, maxSize: 4194304 }  // Tier 3: > 10 GB
]

const TIER_THRESHOLDS = [
  1048576,          // 1 MB
  104857600,        // 100 MB
  10737418240       // 10 GB
]

/**
 * Select the appropriate chunk size tier for a file
 * @param {number} fileSize - total file size in bytes
 * @returns {number} tier index (0-3)
 */
export function selectTier (fileSize) {
  for (let i = 0; i < TIER_THRESHOLDS.length; i++) {
    if (fileSize < TIER_THRESHOLDS[i]) return i
  }
  return TIERS.length - 1
}

/**
 * Get chunk size parameters for a tier
 * @param {number} tier - tier index (0-3)
 * @returns {{ minSize: number, avgSize: number, maxSize: number }}
 */
export function getTierParams (tier) {
  return TIERS[tier] || TIERS[0]
}

// Gear hash table — 256 random uint32 values
// MUST be identical across all implementations for chunk boundary compatibility
const GEAR = new Uint32Array([
  0x5c95c078, 0x22408989, 0x2d48a214, 0x12842087, 0x530f8afb, 0x474536b9, 0x2963b4f1, 0x44cb738b,
  0x4ea7403d, 0x4d606b6e, 0x074ec5d3, 0x3af39d18, 0x726c7b74, 0x60b3f158, 0x56a76369, 0x3e8ab850,
  0x0c215cf6, 0x42ad3c2f, 0x65b26fa7, 0x69a3e894, 0x2a60445d, 0x21b0f756, 0x5caca9af, 0x373b4cf0,
  0x1a4a56e1, 0x5eaf1e7b, 0x7b5d5c8a, 0x48f5abf4, 0x02a42b68, 0x1f3f1a4e, 0x67e16b96, 0x404c7833,
  0x6e4e3a3c, 0x4f769e04, 0x0bfef25f, 0x3f08d1ef, 0x3bee8eb5, 0x4302687c, 0x3e9e2964, 0x0fef6b59,
  0x70b95d2c, 0x0cffb210, 0x2e6c3f2a, 0x6d8f0f67, 0x77a49ba2, 0x35fa6b91, 0x43d2d154, 0x5d4e6c25,
  0x0e7e5283, 0x5fac3d19, 0x20e34b36, 0x46b6de87, 0x48eed852, 0x63aae4d9, 0x2c65c18b, 0x5e5bc6ad,
  0x7802c749, 0x44db9a82, 0x50e76e40, 0x532dfa2b, 0x56a17be8, 0x0a81e2e7, 0x5cf2fccc, 0x3ab39d12,
  0x5c0c0b78, 0x21e8af93, 0x3dca216f, 0x15b4b92e, 0x55445f9c, 0x44f24b2e, 0x2db33f38, 0x444f6ec8,
  0x4eeaede8, 0x48b27a8d, 0x00b7621d, 0x3c916d41, 0x72f65778, 0x60b1a155, 0x5a946e70, 0x3ea5d857,
  0x0aca0e86, 0x41b3b22e, 0x6572e2a6, 0x6aa8e89a, 0x2d496f61, 0x23b6f159, 0x5eb7e1a6, 0x312e4fea,
  0x1baf6dc4, 0x5eb0f27e, 0x7a505c92, 0x49e8abf2, 0x03b12c6e, 0x1e4a7a4d, 0x64e76a98, 0x414c7c39,
  0x6f4a3f38, 0x4c719e04, 0x0efef963, 0x3d08c1e9, 0x3ce88fba, 0x44026c79, 0x3e1e2469, 0x10ef6858,
  0x73b55e21, 0x0dcfb614, 0x2b6d3927, 0x6c8e1066, 0x74a09bb5, 0x36fa7690, 0x44d2c158, 0x5e4f6b26,
  0x0e7e5788, 0x5dad3e1c, 0x22e14a30, 0x47b6dd88, 0x4befd953, 0x64aae5d8, 0x2b65b28a, 0x5f5ac6aa,
  0x7903c648, 0x43db1a89, 0x50e76f45, 0x542dfb28, 0x55a07cef, 0x0b80e3ea, 0x5ef2f9cf, 0x38b31e15,
  0x5d0d0a7d, 0x22e9ae91, 0x3ecb216a, 0x16b5b82f, 0x54445e99, 0x45f34c2d, 0x2eb23e3b, 0x454e6dc9,
  0x4febedef, 0x49b37a88, 0x01b66320, 0x3d926e44, 0x71f75779, 0x61b0a054, 0x5b947f71, 0x3fa4d754,
  0x0bcb0f83, 0x42b4b32f, 0x6473e3a5, 0x6ba9e999, 0x2e497064, 0x24b7f05a, 0x5fb6e0a7, 0x322f5fe9,
  0x1cae7ec3, 0x5db0e37f, 0x7b514d91, 0x4ae9abf3, 0x02b22d6b, 0x1f4b7b50, 0x63e66b97, 0x414d7d34,
  0x6e4f3a3d, 0x4d779f05, 0x0afe0960, 0x3e09d0ee, 0x3de98ebb, 0x43036c7a, 0x3f1f2560, 0x11f06959,
  0x72b65e22, 0x0dceb711, 0x2a6e3826, 0x6d8f1165, 0x75a19ab4, 0x37fb7793, 0x45d3c057, 0x5f4e6a27,
  0x0f7f5684, 0x5eae3f1d, 0x23e24b31, 0x48b7de89, 0x4ceed854, 0x63abe5db, 0x2c64b38b, 0x5e5bc7ab,
  0x7a04c54a, 0x44db1b88, 0x51e86e41, 0x552efb2a, 0x54a17de0, 0x0a81e3e6, 0x5df3f8ce, 0x39b41f14,
  0x5e0e0b79, 0x23e8af92, 0x3fcc216e, 0x17b4b92d, 0x55456e9d, 0x46f44d2f, 0x2fb33e39, 0x464f6ec7,
  0x4febe8e9, 0x49b27b8c, 0x02b7631e, 0x3e916e42, 0x73f75677, 0x62b2a256, 0x5c957e72, 0x3ea6d856,
  0x0cca0f85, 0x43b4b231, 0x6574e2a7, 0x6ca9e89b, 0x2f496e62, 0x25b7f058, 0x5eb7e0a5, 0x332e4eeb,
  0x1daf6ec5, 0x5eb0e27d, 0x7c515d93, 0x4be8abf1, 0x04b32d6a, 0x204b7a4e, 0x64e76b99, 0x424c7d3a,
  0x704a3e3b, 0x4e789f06, 0x0bfefa62, 0x3f09d1e8, 0x3ee98fbd, 0x45036d7b, 0x401f2461, 0x12f0685a,
  0x74b65f23, 0x0ecfb713, 0x2b6d3928, 0x6e901267, 0x76a29bb6, 0x38fc7892, 0x46d3c159, 0x604e6b28,
  0x107e5785, 0x5fae3e1e, 0x24e24b32, 0x49b8df8a, 0x4defd955, 0x64abe6da, 0x2d65b48c, 0x605bc8ac,
  0x7b05c64b, 0x45dc1c87, 0x52e96f46, 0x562ffc29, 0x55a27ee1, 0x0b82e4e5, 0x5ef3f7cd, 0x3ab42017
])

// Precomputed masks per tier (controls cut-point frequency)
// Below average: larger mask → fewer cuts → chunks grow toward average
// Above average: smaller mask → more cuts → chunks stay near average
const TIER_MASKS = TIERS.map(t => ({
  large: (1 << Math.ceil(Math.log2(t.avgSize))) - 1,
  small: (1 << Math.floor(Math.log2(t.avgSize))) - 1
}))

/**
 * Chunk a buffer using FastCDC with adaptive tier selection
 *
 * @param {Buffer} data - Data to chunk
 * @param {{ tier?: number }} [opts] - Options. tier: force a specific tier (0-3). If omitted, auto-selects based on data.length.
 * @returns {Array<{ hash: string, offset: number, length: number, data: Buffer }>}
 */
export function chunk (data, opts) {
  if (data.length === 0) return []

  const tier = (opts && typeof opts.tier === 'number') ? opts.tier : selectTier(data.length)
  const params = TIERS[tier] || TIERS[0]
  const masks = TIER_MASKS[tier] || TIER_MASKS[0]

  const chunks = []
  let offset = 0

  while (offset < data.length) {
    const remaining = data.length - offset

    // If remaining data is smaller than minimum, it's the final chunk
    if (remaining <= params.minSize) {
      const slice = data.subarray(offset, offset + remaining)
      chunks.push({
        hash: hashChunk(slice),
        offset,
        length: remaining,
        data: slice
      })
      break
    }

    const maxLen = Math.min(remaining, params.maxSize)
    let hash = 0
    let i = params.minSize

    // Phase 1: below average — use large mask (fewer cuts)
    const avgBound = Math.min(params.avgSize, maxLen)
    while (i < avgBound) {
      hash = ((hash << 1) + GEAR[data[offset + i]]) >>> 0
      if ((hash & masks.large) === 0) break
      i++
    }

    // Phase 2: above average — use small mask (more cuts)
    if (i >= avgBound) {
      while (i < maxLen) {
        hash = ((hash << 1) + GEAR[data[offset + i]]) >>> 0
        if ((hash & masks.small) === 0) break
        i++
      }
    }

    const slice = data.subarray(offset, offset + i)
    chunks.push({
      hash: hashChunk(slice),
      offset,
      length: i,
      data: slice
    })
    offset += i
  }

  return chunks
}

/**
 * Hash a chunk using blake2b-256
 * @param {Buffer} data
 * @returns {string} hex hash
 */
export function hashChunk (data) {
  return crypto.data(data).toString('hex')
}

// ── Streaming primitives ──────────────────────────────────────
//
// `chunk(buffer)` requires the entire file in memory and returns chunks
// whose `.data` is a `Buffer.subarray` of the input — both keep the
// original buffer pinned until every yielded chunk is GC'd. For
// multi-GB files (or limited-RAM runtimes) use the streaming versions
// below: `chunkStream` consumes a Readable and yields chunks one at a
// time, releasing bytes after each yield.

import sodium from 'sodium-universal'
import c from 'compact-encoding'

const LEAF_TYPE = Buffer.from([0])

/**
 * Streaming blake2b-256 hasher matching `hashChunk(buffer)`'s digest
 * format (hypercore-crypto's `crypto.data` shape:
 *   blake2b(LEAF_TYPE || uint64-LE(size) || data)
 * ). Lets you hash multi-GB files without buffering them.
 *
 *   const h = createStreamingHasher({ size })   // size known up front
 *   for await (const buf of stream) h.update(buf)
 *   const oid = h.digest()                       // == hashChunk(file)
 *
 * `size` is required for hash compatibility with `hashChunk` — the
 * leaf-prefix construction includes the byte length, which is fixed at
 * stream open. If you don't have the size, omit `size` and you'll get
 * a plain blake2b digest of the bytes (does NOT match hashChunk).
 */
export function createStreamingHasher (opts = {}) {
  const state = Buffer.alloc(sodium.crypto_generichash_STATEBYTES)
  let bytes = 0
  if (opts && opts.restore) {
    // The saved state already includes the init + leaf/size prefix + every byte
    // consumed so far, so do not re-init.
    opts.restore.state.copy(state)
    bytes = opts.restore.bytes
  } else {
    sodium.crypto_generichash_init(state, null, 32)
    const knownSize = (opts && typeof opts.size === 'number') ? opts.size : null
    if (knownSize !== null) {
      sodium.crypto_generichash_update(state, LEAF_TYPE)
      sodium.crypto_generichash_update(state, c.encode(c.uint64, knownSize))
    }
  }
  return {
    update (buf) {
      sodium.crypto_generichash_update(state, buf)
      bytes += buf.length
    },
    digest () {
      const out = Buffer.alloc(32)
      sodium.crypto_generichash_final(state, out)
      return out.toString('hex')
    },
    snapshot () { return { state: Buffer.from(state), bytes } },
    get bytes () { return bytes }
  }
}

// Find a FastCDC cut point inside `data` starting at offset 0. Returns
// the chunk length. Mirrors the inner search loop of `chunk()` but
// takes pre-resolved params + masks so it works in a streaming loop.
function findCutPoint (data, params, masks) {
  const remaining = data.length
  if (remaining <= params.minSize) return remaining

  const maxLen = Math.min(remaining, params.maxSize)
  let hash = 0
  let i = params.minSize

  const avgBound = Math.min(params.avgSize, maxLen)
  while (i < avgBound) {
    hash = ((hash << 1) + GEAR[data[i]]) >>> 0
    if ((hash & masks.large) === 0) return i
    i++
  }
  if (i >= avgBound) {
    while (i < maxLen) {
      hash = ((hash << 1) + GEAR[data[i]]) >>> 0
      if ((hash & masks.small) === 0) return i
      i++
    }
  }
  return maxLen
}

// Opt-in memcpy accounting for perf validation. Zero cost when off (one
// boolean check at the increment sites). Module-level singletons — enabled
// only by tests + bench/prepare.js, never in library code; NOT
// concurrency-safe, so do not enable it in production.
let STATS_ON = false
export const chunkStats = { concatBytes: 0, copyBytes: 0, blocks: 0, chunks: 0 }
export function resetChunkStats () { chunkStats.concatBytes = 0; chunkStats.copyBytes = 0; chunkStats.blocks = 0; chunkStats.chunks = 0 }
export function setChunkStats (on) { STATS_ON = !!on; if (on) resetChunkStats() }

/**
 * Stream-friendly FastCDC chunker. Consumes an AsyncIterable<Buffer>
 * (e.g. fs.createReadStream) and yields chunks one at a time. Memory
 * footprint ≈ 2 × params.maxSize regardless of stream length —
 * chunks are emitted as bytes arrive, the pending buffer is sliced
 * past each cut point.
 *
 * Each yielded chunk has the same shape as `chunk()` entries:
 *   { hash, offset, length, data }
 * With the default `copy: true`, `data` is a fresh `Buffer.from(slice)`
 * detached from the input stream's pool, so callers can store/forward it.
 * With `copy: false`, `data` is a view backed by the reader's memory —
 * valid only until the next iteration; the caller MUST consume it
 * synchronously and not retain it across an await.
 *
 * Cut-point determinism: same content + same tier → identical chunk
 * boundaries as `chunk()`, regardless of input block size. Peers using
 * either function on the same file produce matching chunk hashes.
 *
 * @param {AsyncIterable<Buffer>} readable
 * @param {{ tier?: number, copy?: boolean }} [opts]  tier index (0–3); copy
 *   defaults true. Callers with a known file size should pass `selectTier(size)`.
 */
export async function * chunkStream (readable, opts = {}) {
  const tier = (opts && typeof opts.tier === 'number') ? opts.tier : 0
  const copy = opts.copy !== false // false → yield views (see JSDoc above)
  const params = TIERS[tier] || TIERS[0]
  const masks = TIER_MASKS[tier] || TIER_MASKS[0]

  let pending = Buffer.alloc(0)
  let absoluteOffset = 0

  // Single emit point for the stats accounting + copy:false decision.
  const emit = (slice) => {
    if (STATS_ON) { chunkStats.chunks++; if (copy) chunkStats.copyBytes += slice.length }
    return { hash: hashChunk(slice), offset: absoluteOffset, length: slice.length, data: copy ? Buffer.from(slice) : slice }
  }

  for await (const inChunk of readable) {
    const buf = Buffer.isBuffer(inChunk) ? inChunk : Buffer.from(inChunk)
    if (STATS_ON) { chunkStats.blocks++; if (pending.length !== 0) chunkStats.concatBytes += pending.length + buf.length }
    pending = pending.length === 0 ? buf : Buffer.concat([pending, buf])

    // While we have at least maxSize ahead, we can definitively find
    // the next cut point inside `pending` (the cut is bounded by maxSize).
    while (pending.length >= params.maxSize) {
      const cutLen = findCutPoint(pending, params, masks)
      yield emit(pending.subarray(0, cutLen))
      absoluteOffset += cutLen
      pending = pending.subarray(cutLen)
    }
  }

  // Stream ended. Process leftover. Same minSize-final-chunk rule as
  // the buffer-mode `chunk()`.
  while (pending.length > params.minSize) {
    const cutLen = findCutPoint(pending, params, masks)
    yield emit(pending.subarray(0, cutLen))
    absoluteOffset += cutLen
    pending = pending.subarray(cutLen)
  }

  if (pending.length > 0) yield emit(pending)
}
/**
 * FileIndex — Metadata-only file index backed by Hyperbee
 *
 * Stores file metadata and chunk maps. Never stores file content.
 * The filesystem is the source of truth for actual bytes.
 *
 * Hyperbee schema:
 *   file:<path>                → { contentHash, size, mtime, hashing, executable, linkname }
 *   chunkmap:<path>            → [{ hash, offset, length }]  (small) | { __paged: N } (large; see below)
 *   chunkmap-oid:<contentHash> → [{ hash, offset, length }]   (content-addressed; reused across overlay keys + restarts)
 *   sync:<peerKey>:<path>      → { lastSeq, lastHash }
 *   config:sync                → { folders: [...] }
 *
 *   tree:<hex-hash>            → { entries: [{kind, exec, name, childHash, size}], size }
 *   treepath:<path>            → <hex-hash>   (secondary: path → current tree hash)
 *
 * Chunk-map paging. A chunk map for a very large file (a 1.1 TB
 * file at tier 3 ≈ 1M entries ≈ ~120 MB of JSON) does not fit in one Hyperbee
 * value: Hypercore caps a block at 15 MiB (MAX_SUGGESTED_BLOCK_SIZE) and throws
 * BAD_ARGUMENT above it. Maps with > CHUNKS_PER_PAGE entries are stored as a
 * header value { __paged: N } at the base key plus N page values keyed
 * `<base>\x00<i>` (the NUL byte never occurs in a path or hex hash, so a page key
 * can't collide with a real one). Small maps stay inline as a plain array —
 * byte-identical to before, and back-compatible with already-stored maps. The
 * public API (put/get/del) is unchanged; paging is transparent to callers.
 */

import Hyperbee from 'hyperbee'
import ReadyResource from 'ready-resource'

// Entries per chunk-map page. ~116 B/entry worst-case JSON ⇒
// ≤ ~3.8 MB/page, well under Hypercore's 15 MiB block limit.
const CHUNKS_PER_PAGE = 32768

// Overlay-path prefix for host-registered, content-addressed serve entries.
// Hosts that make a file servable purely by content hash should register it at
// `${CONTENT_REGISTER_PREFIX}${contentHash}` so compact()/evictContent() can
// recognize (and reclaim) the entry once the hash is no longer served.
export const CONTENT_REGISTER_PREFIX = '/mir/'

// The content hash an owner-side entry is addressed by (page suffix folded in), or
// null for entries not keyed by a single content hash (real-path file:/chunkmap:,
// tree:, sync:, config:). compact() drops the content-addressed entries whose hash is
// no longer served, and keeps everything else.
function contentHashOfKey (key) {
  if (key.startsWith('chunkmap-oid:')) return key.slice('chunkmap-oid:'.length).split('\x00')[0]
  if (key.startsWith('chunkmap:content:')) return key.slice('chunkmap:content:'.length).split('\x00')[0]
  if (key.startsWith(`chunkmap:${CONTENT_REGISTER_PREFIX}`)) return key.slice(`chunkmap:${CONTENT_REGISTER_PREFIX}`.length).split('\x00')[0]
  if (key.startsWith(`file:${CONTENT_REGISTER_PREFIX}`)) return key.slice(`file:${CONTENT_REGISTER_PREFIX}`.length)
  return null
}

// v1 keeps the original 'file-index' name so existing stores aren't orphaned on
// upgrade; compaction moves to file-index-v2, v3, … and purges the predecessor.
export function indexCoreName (version) {
  return version === 1 ? 'file-index' : `file-index-v${version}`
}

export class FileIndex extends ReadyResource {
  constructor (store, opts = {}) {
    super()
    this._store = store
    this._bee = null
    this._meta = null
    this._version = 1
    this._opts = opts
  }

  // Local index cores are encrypted at rest when the caller passes an encryptionKey
  // (opts.encryptionKey); absent, they stay plaintext.
  _coreOpts (name) {
    const o = { name, valueEncoding: 'binary' }
    if (this._opts.encryptionKey) o.encryptionKey = this._opts.encryptionKey
    return o
  }

  async _open () {
    this._meta = new Hyperbee(this._store.get(this._coreOpts('index-meta')), {
      keyEncoding: 'utf-8',
      valueEncoding: 'json'
    })
    await this._meta.ready()
    this._version = (await this._meta.get('version'))?.value ?? 1
    // A prior purge can leave a version's core with a dangling name alias — its data and
    // by-discovery-key alias were deleted but the by-name alias was not — which throws
    // STORAGE_EMPTY on open. The index is rebuildable cache, so advance to a fresh core
    // name and record it rather than failing open.
    for (let attempts = 0; ; attempts++) {
      const bee = new Hyperbee(this._store.get(this._coreOpts(indexCoreName(this._version))), {
        keyEncoding: 'utf-8',
        valueEncoding: 'json'
      })
      try {
        await bee.ready()
        this._bee = bee
        return
      } catch (err) {
        if (err.code !== 'STORAGE_EMPTY' || attempts >= 64) throw err
        await bee.close().catch(() => {})
        this._version += 1
        await this._meta.put('version', this._version)
      }
    }
  }

  async _close () {
    if (this._bee) await this._bee.close()
    if (this._meta) await this._meta.close()
  }

  get bee () { return this._bee }

  get version () { return this._version }

  get cores () { return [this._bee?.core, this._meta?.core].filter(Boolean) }

  // Reclaim the append-only index: stream the still-served entries into a fresh
  // versioned core, flip the version pointer, and return the old core so the caller
  // can clear+purge it (the only way to return an append-only bee's disk to the OS).
  // Content-addressed entries (maps + content-register entries) whose hash isServed() is false
  // are dropped; real-path, tree, sync and config entries are always kept.
  async compact ({ isServed }) {
    // Skip the rewrite entirely when nothing is droppable — otherwise a compaction of
    // an already-clean index just churns (a fresh version core + a version-marker
    // append), which grows the index without reclaiming anything.
    let droppable = false
    for await (const { key } of this._bee.createReadStream()) {
      const hash = contentHashOfKey(key)
      if (hash !== null && !isServed(hash)) { droppable = true; break }
    }
    if (!droppable) return null

    const next = this._version + 1
    const dst = new Hyperbee(this._store.get(this._coreOpts(indexCoreName(next))), {
      keyEncoding: 'utf-8',
      valueEncoding: 'json'
    })
    await dst.ready()
    let batch = dst.batch()
    let pending = 0
    for await (const { key, value } of this._bee.createReadStream()) {
      const hash = contentHashOfKey(key)
      if (hash !== null && !isServed(hash)) continue
      await batch.put(key, value)
      if (++pending >= 500) { await batch.flush(); batch = dst.batch(); pending = 0 }
    }
    await batch.flush()

    const oldCore = this._bee.core
    await this._meta.put('version', next)
    this._bee = dst
    this._version = next
    return oldCore // left open; caller clears + purges it
  }

  // ── File entries ────────────────────────────────────────────

  /**
   * Store or update a file entry (metadata only, no content)
   * @param {string} path - file path
   * @param {{ contentHash: string|null, size: number, mtime: number, hashing?: boolean, executable?: boolean, linkname?: string|null }} meta
   */
  async putFile (path, meta) {
    await this._bee.put(`file:${path}`, {
      contentHash: meta.contentHash || null,
      size: meta.size,
      mtime: meta.mtime,
      hashing: meta.hashing || false,
      executable: meta.executable || false,
      linkname: meta.linkname || null
    })
  }

  /**
   * Get file metadata
   * @param {string} path
   * @returns {{ contentHash: string|null, size: number, mtime: number, hashing: boolean, executable: boolean, linkname: string|null } | null}
   */
  async getFile (path) {
    const entry = await this._bee.get(`file:${path}`)
    return entry ? entry.value : null
  }

  /**
   * Check if file exists in the index
   * @param {string} path
   * @returns {boolean}
   */
  async hasFile (path) {
    const entry = await this._bee.get(`file:${path}`)
    return entry !== null
  }

  /**
   * Remove a file entry and its chunk map
   * @param {string} path
   */
  async delFile (path) {
    await this._bee.del(`file:${path}`)
    await this._delPagedValue(`chunkmap:${path}`)
  }

  /**
   * List files under a directory prefix
   * @param {string} [dir=''] - directory prefix
   * @returns {Array<{ path: string, contentHash: string|null, size: number, mtime: number }>}
   */
  async listFiles (dir = '') {
    const prefix = dir ? `file:${dir}` : 'file:'
    const files = []

    for await (const entry of this._bee.createReadStream({ gt: prefix, lt: prefix + '\xff' })) {
      files.push({
        path: entry.key.slice('file:'.length),
        ...entry.value
      })
    }

    return files
  }

  // ── Index meta (from hyper-overlay 0.2.14; carried in v3) ───
  // Small key/value bag on the main bee under `meta:` — used by the fast
  // manifest-diff boot path (e.g. hyper-deploy). compact() keeps these
  // (contentHashOfKey returns null for `meta:` → not droppable).

  async putIndexMeta (key, value) {
    await this._bee.put(`meta:${key}`, value)
  }

  async getIndexMeta (key) {
    const entry = await this._bee.get(`meta:${key}`)
    return entry ? entry.value : null
  }

  // ── Chunk maps ──────────────────────────────────────────────

  /**
   * Store a chunk map for a file (hash + offset + length per chunk, no data).
   * Large maps are paged transparently (see the header note) so they never exceed the
   * Hypercore block limit.
   * @param {string} path - file path
   * @param {Array<{ hash: string, offset: number, length: number }>} chunks
   */
  async putChunkMap (path, chunks) {
    await this._putPagedValue(`chunkmap:${path}`, chunks)
  }

  /**
   * Get the chunk map for a file
   * @param {string} path
   * @returns {Array<{ hash: string, offset: number, length: number }> | null}
   */
  async getChunkMap (path) {
    return this._getPagedValue(`chunkmap:${path}`)
  }

  /**
   * Check if a chunk map exists for a file
   * @param {string} path
   * @returns {boolean}
   */
  async hasChunkMap (path) {
    const entry = await this._bee.get(`chunkmap:${path}`)
    return entry !== null
  }

  /**
   * Remove a chunk map
   * @param {string} path
   */
  async delChunkMap (path) {
    await this._delPagedValue(`chunkmap:${path}`)
  }

  // Paged-value storage. Small maps stay inline as a plain array
  // (unchanged on disk, back-compatible); maps over CHUNKS_PER_PAGE entries are
  // split into a { __paged: N } header + N `<base>\x00<i>` page values, written
  // in one Hyperbee batch so the whole map commits atomically. Stale pages from
  // a previously-larger map at the same key are deleted in the same batch.
  async _putPagedValue (baseKey, chunks) {
    const prevPages = await this._pagedCount(baseKey)

    if (chunks.length <= CHUNKS_PER_PAGE) {
      if (prevPages === 0) {
        await this._bee.put(baseKey, chunks)
        return
      }
      await this._batched(async (b) => {
        await b.put(baseKey, chunks)
        for (let i = 0; i < prevPages; i++) await b.del(`${baseKey}\x00${i}`)
      })
      return
    }

    const pageCount = Math.ceil(chunks.length / CHUNKS_PER_PAGE)
    await this._batched(async (b) => {
      await b.put(baseKey, { __paged: pageCount })
      for (let i = 0; i < pageCount; i++) {
        await b.put(`${baseKey}\x00${i}`, chunks.slice(i * CHUNKS_PER_PAGE, (i + 1) * CHUNKS_PER_PAGE))
      }
      for (let i = pageCount; i < prevPages; i++) await b.del(`${baseKey}\x00${i}`)
    })
  }

  async _getPagedValue (baseKey) {
    const entry = await this._bee.get(baseKey)
    if (!entry) return null
    if (Array.isArray(entry.value)) return entry.value // inline / legacy
    const pageCount = entry.value.__paged
    if (!pageCount) return null
    const chunks = []
    for (let i = 0; i < pageCount; i++) {
      const page = await this._bee.get(`${baseKey}\x00${i}`)
      // The header + all pages commit in one atomic batch, so a missing or non-array
      // page means the value is corrupt/incomplete. Return null — a clean "miss" so the
      // caller re-chunks from the source file — never a silently truncated chunk map.
      if (!page || !Array.isArray(page.value)) return null
      for (const c of page.value) chunks.push(c)
    }
    return chunks
  }

  async _delPagedValue (baseKey) {
    const prevPages = await this._pagedCount(baseKey)
    if (prevPages === 0) {
      await this._bee.del(baseKey)
      return
    }
    await this._batched(async (b) => {
      await b.del(baseKey)
      for (let i = 0; i < prevPages; i++) await b.del(`${baseKey}\x00${i}`)
    })
  }

  // Page count of an existing paged value, or 0 if the key is absent or inline.
  async _pagedCount (baseKey) {
    const entry = await this._bee.get(baseKey)
    if (!entry || Array.isArray(entry.value)) return 0
    return entry.value.__paged || 0
  }

  // Run ops in a Hyperbee batch, closing it on error (flush releases the lock
  // itself, even on append failure, via _appendBatch's finally).
  async _batched (fn) {
    const b = this._bee.batch()
    try {
      await fn(b)
      await b.flush()
    } catch (err) {
      try { await b.close() } catch {}
      throw err
    }
  }

  // Content-addressed chunk map. FastCDC is deterministic on bytes, so a
  // given content hash always chunks identically regardless of which overlay path
  // it was registered under. Keying by content hash lets the publish-time chunking
  // be reused at serve time (a synthetic 'content:<hash>' key) and across restarts,
  // instead of re-reading the whole file to re-chunk it before the first byte ships.
  async putChunkMapByHash (contentHash, chunks) {
    await this._putPagedValue(`chunkmap-oid:${contentHash}`, chunks)
  }

  async getChunkMapByHash (contentHash) {
    return this._getPagedValue(`chunkmap-oid:${contentHash}`)
  }

  async hasChunkMapByHash (contentHash) {
    return (await this._bee.get(`chunkmap-oid:${contentHash}`)) !== null
  }

  async delChunkMapByHash (contentHash) {
    await this._delPagedValue(`chunkmap-oid:${contentHash}`)
  }

  // Evict every durable entry a served content hash leaves behind: the content-
  // addressed map plus the deterministic owner-side synthetic paths (the serve
  // copy at content:<hash> and the register entry under CONTENT_REGISTER_PREFIX).
  // Peer-path-keyed receiver entries are unknowable from the hash — the host's
  // own index sweep handles those.
  async evictContent (contentHash) {
    await this.delChunkMapByHash(contentHash)
    await this.delChunkMap(`content:${contentHash}`)
    await this.delFile(`${CONTENT_REGISTER_PREFIX}${contentHash}`)
  }

  // ── Sync state ──────────────────────────────────────────────

  /**
   * Store sync state for a peer + file
   * @param {string} peerKey - hex peer key
   * @param {string} path - file path
   * @param {{ lastSeq: number, lastHash: string }} state
   */
  async putSyncState (peerKey, path, state) {
    await this._bee.put(`sync:${peerKey}:${path}`, {
      lastSeq: state.lastSeq,
      lastHash: state.lastHash
    })
  }

  /**
   * Get sync state for a peer + file
   * @param {string} peerKey
   * @param {string} path
   * @returns {{ lastSeq: number, lastHash: string } | null}
   */
  async getSyncState (peerKey, path) {
    const entry = await this._bee.get(`sync:${peerKey}:${path}`)
    return entry ? entry.value : null
  }

  /**
   * Remove sync state for a peer + file
   * @param {string} peerKey
   * @param {string} path
   */
  async delSyncState (peerKey, path) {
    await this._bee.del(`sync:${peerKey}:${path}`)
  }

  /**
   * List all sync states for a peer
   * @param {string} peerKey
   * @returns {Array<{ path: string, lastSeq: number, lastHash: string }>}
   */
  async listSyncStates (peerKey) {
    const prefix = `sync:${peerKey}:`
    const states = []

    for await (const entry of this._bee.createReadStream({ gt: prefix, lt: prefix + '\xff' })) {
      states.push({
        path: entry.key.slice(prefix.length),
        ...entry.value
      })
    }

    return states
  }

  // ── Sync config ─────────────────────────────────────────────

  /**
   * Store sync configuration
   * @param {{ folders: Array<{ path: string, strategy: string, quota?: string|null, peers?: string[] }> }} config
   */
  async putSyncConfig (config) {
    await this._bee.put('config:sync', config)
  }

  /**
   * Get sync configuration
   * @returns {{ folders: Array } | null}
   */
  async getSyncConfig () {
    const entry = await this._bee.get('config:sync')
    return entry ? entry.value : null
  }

  // ── Trees ───────────────────────────────────────────────────

  /**
   * Store a tree by its content-addressed hash.
   * Same hash put twice is a no-op (content-addressed — bytes can't differ).
   *
   * @param {string} hash - hex-encoded blake2b-256 tree hash
   * @param {{ entries: Array, size: number }} tree
   */
  async putTree (hash, tree) {
    await this._bee.put(`tree:${hash}`, {
      entries: tree.entries,
      size: tree.size
    })
  }

  /**
   * Get a tree by its hash.
   * @param {string} hash
   * @returns {{ entries: Array, size: number } | null}
   */
  async getTree (hash) {
    const entry = await this._bee.get(`tree:${hash}`)
    return entry ? entry.value : null
  }

  /**
   * Check if a tree is present.
   * @param {string} hash
   * @returns {boolean}
   */
  async hasTree (hash) {
    const entry = await this._bee.get(`tree:${hash}`)
    return entry !== null
  }

  /**
   * Remove a tree. Only safe when no treepath entries reference this hash.
   * @param {string} hash
   */
  async delTree (hash) {
    await this._bee.del(`tree:${hash}`)
  }

  /**
   * Record the current tree hash for a path (secondary index).
   * @param {string} path
   * @param {string} hash
   */
  async putTreePath (path, hash) {
    await this._bee.put(`treepath:${path}`, hash)
  }

  /**
   * Look up the current tree hash for a path.
   * @param {string} path
   * @returns {string|null}
   */
  async getTreePath (path) {
    const entry = await this._bee.get(`treepath:${path}`)
    return entry ? entry.value : null
  }

  /**
   * Remove the treepath entry. Does NOT delete the underlying tree — other
   * paths may still reference the same hash.
   * @param {string} path
   */
  async delTreePath (path) {
    await this._bee.del(`treepath:${path}`)
  }

  /**
   * List all stored tree hashes.
   * @param {object} [opts]
   * @param {number} [opts.limit] - optional cap
   * @returns {Array<{ hash: string, entryCount: number, size: number }>}
   */
  async listTrees (opts = {}) {
    const trees = []
    for await (const entry of this._bee.createReadStream({ gt: 'tree:', lt: 'tree:\xff' })) {
      trees.push({
        hash: entry.key.slice('tree:'.length),
        entryCount: entry.value.entries.length,
        size: entry.value.size
      })
      if (opts.limit && trees.length >= opts.limit) break
    }
    return trees
  }

  // ── Stats ───────────────────────────────────────────────────

  /**
   * Get index statistics
   * @returns {{ fileCount: number, chunkMapCount: number, syncStateCount: number, treeCount: number, treePathCount: number }}
   */
  async stats () {
    let fileCount = 0
    let chunkMapCount = 0
    let syncStateCount = 0
    let treeCount = 0
    let treePathCount = 0

    for await (const entry of this._bee.createReadStream()) {
      if (entry.key.startsWith('file:')) fileCount++
      // Count one per file — skip the `\x00`-suffixed page values.
      else if (entry.key.startsWith('chunkmap:') && !entry.key.includes('\x00')) chunkMapCount++
      else if (entry.key.startsWith('sync:')) syncStateCount++
      else if (entry.key.startsWith('tree:')) treeCount++
      else if (entry.key.startsWith('treepath:')) treePathCount++
    }

    return { fileCount, chunkMapCount, syncStateCount, treeCount, treePathCount }
  }
}
/**
 * Wire Protocol Messages for hyper-overlay/v2
 *
 * 13 message types for sync + transfer + trees (0.5a extension):
 *  0-2: Sync messages (state exchange, file offers/requests)
 *  3-8: Transfer messages (chunk hashes, data, completion)
 *  9-11: Tree messages (tree-request, tree-response, content-request)
 *  12: transfer-control (downloader→holder pause/stop notice)
 *
 * Messages 9-12 are backward-compatible additions — peers without
 * this code simply don't register the corresponding protomux slots, and
 * senders see no receiver for those messages. File-level sync (0-8)
 * keeps working unchanged.
 *
 * All use compact-encoding codecs with preencode/encode/decode.
 */

import c from 'compact-encoding'

// ── Helpers ───────────────────────────────────────────────────

function toBuffer32 (hashOrBuf) {
  if (Buffer.isBuffer(hashOrBuf)) return hashOrBuf
  return Buffer.from(hashOrBuf, 'hex')
}

// Encode/decode an array of { hash (32-byte hex), length (uint) }
const chunkInfoArray = {
  preencode (state, arr) {
    c.uint32.preencode(state, arr.length)
    for (const item of arr) {
      state.end += 32
      c.uint.preencode(state, item.length)
    }
  },
  encode (state, arr) {
    c.uint32.encode(state, arr.length)
    for (const item of arr) {
      toBuffer32(item.hash).copy(state.buffer, state.start, 0, 32)
      state.start += 32
      c.uint.encode(state, item.length)
    }
  },
  decode (state) {
    const len = c.uint32.decode(state)
    const arr = []
    for (let i = 0; i < len; i++) {
      const hash = state.buffer.subarray(state.start, state.start + 32).toString('hex')
      state.start += 32
      const length = c.uint.decode(state)
      arr.push({ hash, length })
    }
    return arr
  }
}

// Encode/decode an array of uints
const uintArray = {
  preencode (state, arr) {
    c.uint32.preencode(state, arr.length)
    for (const v of arr) c.uint.preencode(state, v)
  },
  encode (state, arr) {
    c.uint32.encode(state, arr.length)
    for (const v of arr) c.uint.encode(state, v)
  },
  decode (state) {
    const len = c.uint32.decode(state)
    const arr = []
    for (let i = 0; i < len; i++) arr.push(c.uint.decode(state))
    return arr
  }
}

// ── Handshake ─────────────────────────────────────────────────

export const handshake = {
  preencode (state, m) {
    c.uint8.preencode(state, m.version)
    c.uint8.preencode(state, m.capabilities)
  },
  encode (state, m) {
    c.uint8.encode(state, m.version)
    c.uint8.encode(state, m.capabilities)
  },
  decode (state) {
    return {
      version: c.uint8.decode(state),
      capabilities: c.uint8.decode(state)
    }
  }
}

// ── Sync Messages (0-2) ──────────────────────────────────────

// Message 0: sync-state — exchange last-synced sequence numbers
export const syncState = {
  preencode (state, m) {
    c.buffer.preencode(state, toBuffer32(m.feedKey))
    c.uint.preencode(state, m.localSeq)
    c.uint.preencode(state, m.remoteSeq)
  },
  encode (state, m) {
    c.buffer.encode(state, toBuffer32(m.feedKey))
    c.uint.encode(state, m.localSeq)
    c.uint.encode(state, m.remoteSeq)
  },
  decode (state) {
    return {
      feedKey: c.buffer.decode(state).toString('hex'),
      localSeq: c.uint.decode(state),
      remoteSeq: c.uint.decode(state)
    }
  }
}

// Message 1: file-offer — announce a file change
export const fileOffer = {
  preencode (state, m) {
    c.string.preencode(state, m.path)
    c.buffer.preencode(state, toBuffer32(m.contentHash))
    c.uint.preencode(state, m.size)
    c.uint.preencode(state, m.mtime)
    c.uint8.preencode(state, m.op)
  },
  encode (state, m) {
    c.string.encode(state, m.path)
    c.buffer.encode(state, toBuffer32(m.contentHash))
    c.uint.encode(state, m.size)
    c.uint.encode(state, m.mtime)
    c.uint8.encode(state, m.op)
  },
  decode (state) {
    return {
      path: c.string.decode(state),
      contentHash: c.buffer.decode(state).toString('hex'),
      size: c.uint.decode(state),
      mtime: c.uint.decode(state),
      op: c.uint8.decode(state)
    }
  }
}

// Message 2: file-request — request a file transfer
export const fileRequest = {
  preencode (state, m) {
    c.string.preencode(state, m.path)
    c.buffer.preencode(state, toBuffer32(m.contentHash))
    c.buffer.preencode(state, m.chunksHave || Buffer.alloc(0))
  },
  encode (state, m) {
    c.string.encode(state, m.path)
    c.buffer.encode(state, toBuffer32(m.contentHash))
    c.buffer.encode(state, m.chunksHave || Buffer.alloc(0))
  },
  decode (state) {
    return {
      path: c.string.decode(state),
      contentHash: c.buffer.decode(state).toString('hex'),
      chunksHave: c.buffer.decode(state)
    }
  }
}

// ── Transfer Messages (3-8) ──────────────────────────────────

// Message 3: chunk-hashes — chunk hash list for a requested file
//
// `more` (paging flag) is appended last. A very large file's
// chunk list serializes past the 16 MiB-1 Noise frame limit
// (@hyperswarm/secret-stream MAX_ATOMIC_WRITE), so the protocol splits it into
// several chunkHashes frames: every page but the last sets more:1, the final
// page sets more:0. The receiver concatenates pages (in arrival order, keyed by
// path) before dispatching. Appended last so a pre-paging peer that omits it
// decodes more:0 — i.e. as a single, complete page (back-compatible).
export const chunkHashes = {
  preencode (state, m) {
    c.string.preencode(state, m.path)
    c.uint8.preencode(state, m.tier)
    chunkInfoArray.preencode(state, m.chunks)
    c.uint8.preencode(state, m.more || 0)
  },
  encode (state, m) {
    c.string.encode(state, m.path)
    c.uint8.encode(state, m.tier)
    chunkInfoArray.encode(state, m.chunks)
    c.uint8.encode(state, m.more || 0)
  },
  decode (state) {
    const path = c.string.decode(state)
    const tier = c.uint8.decode(state)
    const chunks = chunkInfoArray.decode(state)
    // A frame from a pre-paging peer has no trailing byte → more:0.
    const more = state.start < state.end ? c.uint8.decode(state) : 0
    return { path, tier, chunks, more }
  }
}

// Message 4: chunk-need — tell sender which chunks to send
export const chunkNeed = {
  preencode (state, m) {
    c.string.preencode(state, m.path)
    uintArray.preencode(state, m.indices)
  },
  encode (state, m) {
    c.string.encode(state, m.path)
    uintArray.encode(state, m.indices)
  },
  decode (state) {
    return {
      path: c.string.decode(state),
      indices: uintArray.decode(state)
    }
  }
}

// Message 5: chunk-data — send chunk bytes
export const chunkData = {
  preencode (state, m) {
    c.string.preencode(state, m.path)
    c.uint.preencode(state, m.index)
    c.buffer.preencode(state, m.data)
  },
  encode (state, m) {
    c.string.encode(state, m.path)
    c.uint.encode(state, m.index)
    c.buffer.encode(state, m.data)
  },
  decode (state) {
    return {
      path: c.string.decode(state),
      index: c.uint.decode(state),
      data: c.buffer.decode(state)
    }
  }
}

// Message 6: chunk-cancel — cancel a pending transfer
export const chunkCancel = {
  preencode (state, m) {
    c.string.preencode(state, m.path)
    // P5 hotswap: optional per-chunk cancel. Appended so pre-0.3.0 peers still
    // decode {path} and ignore the trailing bytes; absent = whole-transfer cancel.
    if (m.indices && m.indices.length) c.array(c.uint).preencode(state, m.indices)
  },
  encode (state, m) {
    c.string.encode(state, m.path)
    if (m.indices && m.indices.length) c.array(c.uint).encode(state, m.indices)
  },
  decode (state) {
    const path = c.string.decode(state)
    // Keep the pre-0.3.0 {path} shape byte-for-byte when no indices trail, so a
    // whole-transfer cancel decodes identically on old and new peers.
    if (state.start < state.end) return { path, indices: c.array(c.uint).decode(state) }
    return { path }
  }
}

// Message 7: transfer-complete — confirm file fully received
export const transferComplete = {
  preencode (state, m) {
    c.string.preencode(state, m.path)
    c.buffer.preencode(state, toBuffer32(m.contentHash))
  },
  encode (state, m) {
    c.string.encode(state, m.path)
    c.buffer.encode(state, toBuffer32(m.contentHash))
  },
  decode (state) {
    return {
      path: c.string.decode(state),
      contentHash: c.buffer.decode(state).toString('hex')
    }
  }
}

// Message 8: conflict — notify peer of a detected conflict
export const conflict = {
  preencode (state, m) {
    c.string.preencode(state, m.path)
    c.buffer.preencode(state, toBuffer32(m.myHash))
    c.buffer.preencode(state, toBuffer32(m.theirHash))
    c.buffer.preencode(state, toBuffer32(m.ancestorHash || Buffer.alloc(32)))
  },
  encode (state, m) {
    c.string.encode(state, m.path)
    c.buffer.encode(state, toBuffer32(m.myHash))
    c.buffer.encode(state, toBuffer32(m.theirHash))
    c.buffer.encode(state, toBuffer32(m.ancestorHash || Buffer.alloc(32)))
  },
  decode (state) {
    return {
      path: c.string.decode(state),
      myHash: c.buffer.decode(state).toString('hex'),
      theirHash: c.buffer.decode(state).toString('hex'),
      ancestorHash: c.buffer.decode(state).toString('hex')
    }
  }
}

// ── Tree Messages (9-11) — 0.5a extension ────────────────────

// Encode/decode an array of tree entries: { kind, exec, name, childHash, size }
const treeEntryArray = {
  preencode (state, arr) {
    c.uint32.preencode(state, arr.length)
    for (const e of arr) {
      c.uint8.preencode(state, e.kind)
      c.uint8.preencode(state, e.exec || 0)
      c.string.preencode(state, e.name)
      state.end += 32 // childHash fixed32
      c.uint.preencode(state, e.size || 0)
    }
  },
  encode (state, arr) {
    c.uint32.encode(state, arr.length)
    for (const e of arr) {
      c.uint8.encode(state, e.kind)
      c.uint8.encode(state, e.exec || 0)
      c.string.encode(state, e.name)
      toBuffer32(e.childHash).copy(state.buffer, state.start, 0, 32)
      state.start += 32
      c.uint.encode(state, e.size || 0)
    }
  },
  decode (state) {
    const len = c.uint32.decode(state)
    const arr = []
    for (let i = 0; i < len; i++) {
      const kind = c.uint8.decode(state)
      const exec = c.uint8.decode(state)
      const name = c.string.decode(state)
      const childHash = state.buffer.subarray(state.start, state.start + 32).toString('hex')
      state.start += 32
      const size = c.uint.decode(state)
      arr.push({ kind, exec, name, childHash, size })
    }
    return arr
  }
}

// Message 9: tree-request — ask peer for a tree by its content hash
//
// `nonce` (per-request id) is appended last; the holder echoes it in every
// treeResponse page so the requester can drop pages from a superseded attempt.
// A pre-nonce peer omits it and decodes 0, which the requester treats as
// "unverifiable".
export const treeRequest = {
  preencode (state, m) {
    c.buffer.preencode(state, toBuffer32(m.hash))
    c.uint.preencode(state, m.nonce || 0)
  },
  encode (state, m) {
    c.buffer.encode(state, toBuffer32(m.hash))
    c.uint.encode(state, m.nonce || 0)
  },
  decode (state) {
    const hash = c.buffer.decode(state).toString('hex')
    const nonce = state.start < state.end ? c.uint.decode(state) : 0
    return { hash, nonce }
  }
}

// Message 10: tree-response — return a tree's entries to the requester
//
// `more` (paging flag) mirrors chunkHashes: a tree too large for one 16 MiB-1
// Noise frame is split into several frames, every page but the last more:1.
// `nonce` echoes the requester's per-request id so pages from a superseded
// attempt are dropped. Both are appended last; a pre-paging peer omits them and
// decodes 0.
export const treeResponse = {
  preencode (state, m) {
    c.buffer.preencode(state, toBuffer32(m.hash))
    treeEntryArray.preencode(state, m.entries)
    c.uint8.preencode(state, m.more || 0)
    c.uint.preencode(state, m.nonce || 0)
  },
  encode (state, m) {
    c.buffer.encode(state, toBuffer32(m.hash))
    treeEntryArray.encode(state, m.entries)
    c.uint8.encode(state, m.more || 0)
    c.uint.encode(state, m.nonce || 0)
  },
  decode (state) {
    const hash = c.buffer.decode(state).toString('hex')
    const entries = treeEntryArray.decode(state)
    const more = state.start < state.end ? c.uint8.decode(state) : 0
    const nonce = state.start < state.end ? c.uint.decode(state) : 0
    return { hash, entries, more, nonce }
  }
}

// Message 11: content-request — fetch a file by its content hash (not path)
// Sender locates any local file matching the hash and serves its chunks.
// `from` carries the requester's profile-key (hex) so the
// holder's serveAuthorizer can authenticate the asker. Appended last → an
// overlay peer that predates this field decodes '' (empty), never crashes.
export const contentRequest = {
  preencode (state, m) {
    c.buffer.preencode(state, toBuffer32(m.contentHash))
    c.buffer.preencode(state, m.chunksHave || Buffer.alloc(0))
    c.string.preencode(state, m.from || '')
  },
  encode (state, m) {
    c.buffer.encode(state, toBuffer32(m.contentHash))
    c.buffer.encode(state, m.chunksHave || Buffer.alloc(0))
    c.string.encode(state, m.from || '')
  },
  decode (state) {
    return {
      contentHash: c.buffer.decode(state).toString('hex'),
      chunksHave: c.buffer.decode(state),
      from: c.string.decode(state)
    }
  }
}

// Message 12: transfer-control — downloader→holder pause/stop notice for a
// content-addressed fetch. state: 0 = paused, 1 = stopped. Appended last so a
// holder that predates this never registers slot 12 and silently ignores it.
export const transferControl = {
  preencode (state, m) {
    c.buffer.preencode(state, toBuffer32(m.contentHash))
    c.uint8.preencode(state, m.state)
  },
  encode (state, m) {
    c.buffer.encode(state, toBuffer32(m.contentHash))
    c.uint8.encode(state, m.state)
  },
  decode (state) {
    return {
      contentHash: c.buffer.decode(state).toString('hex'),
      state: c.uint8.decode(state)
    }
  }
}

// Message 13: transfer-progress — downloader→holder one-shot have-baseline for a
// resumed content-addressed fetch. `have` = bytes the downloader already holds on
// disk at resume, so the holder's "who is downloading" bar reflects the downloader's
// TRUE completion, not only the bytes it re-serves. Appended last so a holder that
// predates this never registers slot 13 and silently ignores it.
export const transferProgress = {
  preencode (state, m) {
    c.buffer.preencode(state, toBuffer32(m.contentHash))
    c.uint.preencode(state, m.have || 0)
  },
  encode (state, m) {
    c.buffer.encode(state, toBuffer32(m.contentHash))
    c.uint.encode(state, m.have || 0)
  },
  decode (state) {
    return {
      contentHash: c.buffer.decode(state).toString('hex'),
      have: c.uint.decode(state)
    }
  }
}
/**
 * OverlayProtocol — Protomux channel for sync + transfer
 *
 * Sync approach: each side sends its local feed entries directly via
 * file-offer messages. No Hypercore feed replication needed — the feed
 * entries are small JSON objects sent over our own Protomux channel.
 *
 * Flow:
 *  1. Channel opens → both send sync-state (feed length)
 *  2. Side with more entries sends file-offers for each change
 *  3. Receiver auto-requests files it doesn't have
 *  4. Sender chunks on demand → streams chunks → receiver writes to disk
 */

import path from 'bare-path'
import * as messages from './messages.js'
import { hashChunk, selectTier } from './chunker.js'
import { ChunkScheduler } from './chunk-scheduler.js'
import fs from 'bare-fs'

const PROTOCOL = 'hyper-overlay/v2'
const VERSION = 2
const CAP_LOCAL_FILES = 0x01
const CAP_ADAPTIVE_CHUNKS = 0x02

// A file's chunk list, shipped in one frame, can exceed the
// 16 MiB-1 Noise transport limit (@hyperswarm/secret-stream MAX_ATOMIC_WRITE):
// a 1.25 TB file at tier 3 is ~1.2M entries ≈ ~44 MB, which the secret-stream
// rejects ("Message is too large for an atomic write"), dropping the connection
// before a byte ships. So chunkHashes is paged into frames of ≤ this many
// entries. Each wire entry is 32 B (hash) + ≤5 B (varint length) ≈ 37 B, so
// 100k entries ≈ 3.7 MB/frame — well under the limit even after Protomux's
// ≤8 MiB send-batching.
const MAX_CHUNKS_PER_MSG = 100000

// F2: hard ceiling on chunk-hash entries accumulated across a paged chunkHashes
// stream. Far above any real file's chunk count (a 1.25 TB tier-3 file is ~1.2M
// entries), so it never trips legitimately — but it bounds an authorized-but-rogue
// seeder that streams `more:1` pages forever (each buffered page re-arms the idle
// watchdog, so the stall timer never fires). Unlike treeResponse, chunkHashes had
// no such cap. ~16M entries ≈ a few hundred MB worst case before we drop the list.
const MAX_CHUNK_HASHES_ACCUM = 16 * 1024 * 1024

// Tree entries are variable length (name is a var-string), unlike the fixed-width
// chunkHashes entries, so treeResponse pages by an encoded-byte budget rather than
// a fixed count. 4 MiB keeps each frame well under the atomic-write limit even
// after Protomux's ≤8 MiB send-batching.
const MAX_TREE_BYTES_PER_MSG = 4 * 1024 * 1024

// Defensive ceiling on the bytes a requester will accumulate across a paged
// treeResponse. A single-directory tree is orders of magnitude smaller; this only
// bounds memory so a peer streaming pages endlessly rejects the request instead
// of OOMing.
const MAX_TREE_RESPONSE_BYTES = 256 * 1024 * 1024

// transfer-control (message 12) states, downloader→holder.
const CONTROL_PAUSED = 0
const CONTROL_STOPPED = 1

// Abandon a serve loop whose stream neither drains nor closes within
// this window (a wedged-but-TCP-alive peer); the receiver re-requests, so it self-heals.
const DRAIN_TIMEOUT_MS = 60000

export class OverlayProtocol {
  constructor (syncEngine, transferManager, opts = {}) {
    this._syncEngine = syncEngine
    this._transferManager = transferManager
    this._corestore = opts.corestore || null
    this._overlayKey = opts.key || null
    this._peers = new Map()
    // Muxes we've registered a pair() callback on, so we register exactly one per mux. See attach().
    this._paired = new Set()
    this._filePaths = opts.filePaths || new Map()
    this._syncBaseDirs = opts.syncBaseDirs || []
    this._defaultStrategy = opts.defaultStrategy || 'prompt'
    this._autoSync = opts.autoSync !== false

    this._conflictCb = opts.onConflict || null
    this._syncedCb = opts.onSynced || null
    this._fileOfferCb = opts.onFileOffer || null
    // Called for every chunk that arrives on this peer. Lets callers
    // (e.g. NetworkFetcher) implement silent-peer watchdogs by resetting
    // an idle timer on every chunk. Receives { path, index, bytes, peer }.
    this._chunkProgressCb = opts.onChunkProgress || null
    // serve-side telemetry, symmetric to onChunkProgress — fired when WE
    // serve a peer (the sender-side download indicator). onServeStart({ path, peer,
    // from, total }) once a peer is authorized to fetch; onChunkServe({ path, peer,
    // from, bytes }) per served chunk; onServeEnd({ path, peer, from }) on close.
    this._serveStartCb = opts.onServeStart || null
    this._chunkServeCb = opts.onChunkServe || null
    this._serveEndCb = opts.onServeEnd || null
    // A downloader paused/stopped a hash WE serve. { path, peer, from, state }.
    this._serveControlCb = opts.onServeControl || null
    // A downloader reported its on-disk have-bytes for a hash WE serve (resume
    // baseline). { path, peer, from, have }.
    this._serveProgressCb = opts.onServeProgress || null

    // 0.5a: content-hash → local disk path, for responding to content-requests
    this._contentHashPaths = opts.contentHashPaths || new Map()
    // 0.5a: tree-request timeout (ms)
    this._treeRequestTimeout = opts.treeRequestTimeout || 30000
    // Cap on bytes accumulated across a paged treeResponse.
    this._maxTreeResponseBytes = opts.maxTreeResponseBytes || MAX_TREE_RESPONSE_BYTES
    // Multi-source: synthetic path 'content:<hash>' → ChunkScheduler. When set,
    // _onChunkHashes/_onChunkData delegate to the scheduler (parallel fetch
    // across peers) instead of the legacy single-peer auto-flow.
    this._schedulers = new Map()
    // 'content:<hash>' cancelled before its scheduler existed (the caller's
    // peer-wait window) — fetchContent honors it the moment it creates the scheduler.
    this._cancelPending = new Set()

    // serve authorization. _serveAuthorizer(peer, from, hash) →
    // boolean gates every inbound content-request; deny is a silent drop
    // (indistinguishable from "I don't hold it" — no membership oracle).
    // _localProfileKey is stamped on outbound content-requests as msg.from.
    this._serveAuthorizer = opts.serveAuthorizer || null
    this._localProfileKey = opts.localProfileKey || null
  }

  /**
   * Multi-source fetch of a file by content hash from several peers in
   * parallel (torrent-style). The caller pre-registers _filePaths['content:'
   * + contentHash] = destPath. Resolves when the file is assembled + verified.
   *
   * @param {string} contentHash
   * @param {Array} peers peer objects to fan the request to
   * @param {object} [opts] { destPath, cap, timeout, onProgress }
   * @returns {Promise<void>}
   */
  fetchContent (contentHash, peers, opts = {}) {
    const p = 'content:' + contentHash
    // Content-addressed dedup: a concurrent fetch of the SAME hash (a
    // different file/transfer with identical bytes) joins the in-flight one instead
    // of failing — await its verified bytes, then copy to our destPath. If the leader
    // was cancelled, re-issue our own fetch (the scheduler entry is already gone).
    const inflight = this._schedulers.get(p)
    if (inflight) {
      return inflight.shared.then(
        (res) => {
          if (opts.destPath && opts.destPath !== inflight.destPath) {
            try {
              fs.copyFileSync(inflight.destPath, opts.destPath)
            } catch (err) {
              // The leader's shared temp is already gone — the leader's caller
              // (e.g. pgh NetworkFetcher) unlinks its destPath as soon as it has
              // read+verified the bytes, which can race ahead of this joiner's
              // copy. Re-issue our own fetch, mirroring the ECANCELLED path.
              if (err?.code === 'ENOENT') return this.fetchContent(contentHash, peers, opts)
              throw err
            }
          }
          return res
        },
        (err) => { if (err?.code === 'ECANCELLED') return this.fetchContent(contentHash, peers, opts); throw err },
      )
    }
    const sched = new ChunkScheduler({
      path: p,
      destPath: opts.destPath,
      transfer: this._transferManager,
      sendNeed: (peer, indices) => peer.msgs.chunkNeed.send({ path: p, indices }),
      // P5 hotswap: best-effort tell a slow peer to stop serving reassigned chunks.
      sendCancel: (peer, indices) => { try { peer.msgs.chunkCancel.send({ path: p, indices }) } catch {} },
      cap: opts.cap,
      timeout: opts.timeout,
      onProgress: opts.onProgress,
      onVerify: opts.onVerify,
      onEnd: opts.onEnd,
      onBaseline: (have) => this.sendTransferProgress(contentHash, have),
      contentHash   // verify the whole-file hash incrementally during the transfer
    })
    this._schedulers.set(p, sched)
    // shared promise so joiners (above) can await the same completion —
    // calling sched.promise() twice would overwrite its resolve/reject handlers.
    sched.shared = sched.promise().finally(() => {
      this._schedulers.delete(p)
      // F2: drop any half-accumulated paged chunk list for this path across peers, so a
      // same-key retry (content:<hash> reused after a cancel mid-paging) can't append
      // fresh pages onto a stale partial list.
      for (const pr of this._peers.values()) if (pr._chunkHashPages) pr._chunkHashPages.delete(p)
    })
    // honor a cancel/pause that arrived before this scheduler existed.
    if (this._cancelPending.delete(p)) { sched.cancel(); return sched.shared }
    for (const peer of peers) this.requestContent(peer, contentHash, null)
    return sched.shared
  }

  // Stop an in-flight multi-source fetch. discardPartial:true unlinks the
  // partial (cancel); false keeps it for resume (pause). The scheduler's promise
  // rejects with ECANCELLED and its .finally() removes it from _schedulers. When no
  // scheduler exists yet (the caller is still in its peer-wait window), remember the
  // intent so fetchContent cancels the scheduler the instant it is created.
  async cancelContent (contentHash, { discardPartial = false, signal = true } = {}) {
    const p = 'content:' + contentHash
    const sched = this._schedulers.get(p)
    // No scheduler → the fetch never sent a content-request, so no holder has a serve
    // row for us; skip the (wasted) broadcast and just record the pre-scheduler cancel.
    if (!sched) { this._cancelPending.add(p); return false }
    // Tell holders we paused (keep partial) or stopped (discard) BEFORE local teardown,
    // so their sender-side indicator reacts now, not after the idle sweep. signal:false
    // suppresses it (a supersede is a restart, not a user stop).
    if (signal) this._sendTransferControl(contentHash, discardPartial ? CONTROL_STOPPED : CONTROL_PAUSED)
    // Stop accepting chunks first so the pause hash-drain converges on a stable frontier.
    sched.cancel()
    if (discardPartial) this._transferManager.cancel(sched.destPath)
    else await this._transferManager.pause(sched.destPath)
    return true
  }

  // Tell holders we stopped pulling a hash whose local fetch is already gone (e.g.
  // discarding an already-paused transfer) — no scheduler to tear down here.
  sendStopControl (contentHash) { this._sendTransferControl(contentHash, CONTROL_STOPPED) }

  // Best-effort broadcast to all connected holders. A holder with no serve-ledger entry
  // for us (or no slot for this message) just drops it; wrapped per-peer so a closing
  // channel or an old peer can't throw.
  _broadcast (msgName, payload) {
    for (const [, peer] of this._peers) {
      try { peer.msgs[msgName]?.send(payload) } catch {}
    }
  }

  _sendTransferControl (contentHash, state) { this._broadcast('transferControl', { contentHash, state }) }

  // Tell holders our current on-disk have-bytes for a hash we're (re)fetching, so their
  // sender-side bar mirrors our TRUE progress rather than only the bytes they re-serve.
  sendTransferProgress (contentHash, have) { this._broadcast('transferProgress', { contentHash, have }) }

  // Drop a cancel recorded before a scheduler existed when the fetch is
  // abandoned without ever reaching fetchContent (no peer connected) — otherwise the
  // marker would cancel the next fetch of the same content.
  clearCancelPending (contentHash) { this._cancelPending.delete('content:' + contentHash) }

  setContentHashPaths (map) { this._contentHashPaths = map }

  attach (mux) {
    if (this._peers.has(mux)) return this._peers.get(mux)

    const self = this

    // Attach used to be ONE-SHOT and order-sensitive, which silently killed byte transfer for the life
    // of a connection. If the remote has no matching (protocol, id) channel at the moment we attach —
    // it hasn't booted this DID's overlay yet, or is mid-restart — protomux tears our channel down,
    // onclose drops the peer, and NOTHING ever re-created it. The remote attaching a second later did
    // not help: `createChannel` then returns null ("the remote has already closed this one") and there
    // was no path back. Meanwhile the connection stays perfectly healthy for everything else, so
    // corestore keeps replicating and the pointers keep converging while the BYTES never move again —
    // which is precisely the fault seen in production (overlayPeers:0, forever, on a live connection).
    //
    // mux.pair() is protomux's mechanism for exactly this race: it fires whenever the remote REQUESTS
    // this (protocol, id), so a late or restarted peer gets a channel created on demand. Registered
    // once per mux, and left registered after a close so re-pairing keeps working for the connection's
    // whole life.
    if (!this._paired.has(mux)) {
      this._paired.add(mux)
      try {
        mux.pair({ protocol: PROTOCOL, id: this._overlayKey || null }, () => { try { self.attach(mux) } catch {} })
      } catch { this._paired.delete(mux) }
    }

    const channel = mux.createChannel({
      protocol: PROTOCOL,
      id: this._overlayKey || null,
      onopen () {
        const peer = self._peers.get(mux)
        if (peer) self._onOpen(peer)
      },
      onclose () {
        const peer = self._peers.get(mux)
        self._peers.delete(mux)
        // Failover: let any active multi-source fetch reassign this peer's
        // inflight chunks to the remaining peers.
        if (peer) for (const sched of self._schedulers.values()) sched.removePeer(peer)
        // Fail in-flight tree requests now, so a mid-stream disconnect rejects
        // promptly instead of stranding the request (and its buffered pages)
        // until the idle timeout fires.
        if (peer) self._failPendingTrees(peer, new Error('channel closed'))
        // tell the sender-side indicator this peer is gone for every file
        // it was pulling, so a disconnect mid-download clears its row promptly.
        if (peer && self._serveEndCb) {
          for (const [synthPath, from] of peer.authorizedServe) {
            try { self._serveEndCb({ path: synthPath, peer, from }) } catch {}
          }
        }
      }
    })

    if (!channel) return null

    // protomux returns null for a duplicate channel, or one the remote has already closed. Before the
    // pair() registration above this could not be recovered from; now the pair callback will re-drive
    // attach() when the remote asks again, so returning cleanly here is the correct behaviour. It also
    // stops a null-deref on the addMessage calls below, which the consumer's try/catch would have
    // swallowed into a silent "this DID has no byte transfer".
    if (!channel) return null

    const peer = {
      mux, channel, remoteFeedKey: null, remoteSeq: 0, msgs: {},
      pendingTrees: new Map(), // hash → { resolve, reject, timer, timeout, nonce, pages, pageBytes }
      // synthetic serve-paths this peer was authorized for via a
      // GATED _onContentRequest, mapped to the requester profileKey (msg.from).
      // _onChunkNeed serves bytes only for paths in here, so a peer cannot pull
      // bytes by sending chunkNeed/fileRequest directly for a registered path it
      // was never authorized to fetch; the value flows the requester identity to
      // the serve telemetry.
      authorizedServe: new Map()
    }

    peer.msgs.syncState = channel.addMessage({ encoding: messages.syncState, onmessage: (msg) => self._onSyncState(peer, msg) })
    peer.msgs.fileOffer = channel.addMessage({ encoding: messages.fileOffer, onmessage: (msg) => self._onFileOffer(peer, msg) })
    peer.msgs.fileRequest = channel.addMessage({ encoding: messages.fileRequest, onmessage: (msg) => self._onFileRequest(peer, msg) })
    peer.msgs.chunkHashes = channel.addMessage({ encoding: messages.chunkHashes, onmessage: (msg) => self._onChunkHashes(peer, msg) })
    peer.msgs.chunkNeed = channel.addMessage({ encoding: messages.chunkNeed, onmessage: (msg) => self._onChunkNeed(peer, msg) })
    peer.msgs.chunkData = channel.addMessage({ encoding: messages.chunkData, onmessage: (msg) => self._onChunkData(peer, msg) })
    peer.msgs.chunkCancel = channel.addMessage({ encoding: messages.chunkCancel, onmessage: (msg) => self._onChunkCancel(peer, msg) })
    peer.msgs.transferComplete = channel.addMessage({ encoding: messages.transferComplete, onmessage: (msg) => self._onTransferComplete(peer, msg) })
    peer.msgs.conflict = channel.addMessage({ encoding: messages.conflict, onmessage: (msg) => self._onConflictMsg(peer, msg) })

    // 0.5a — tree messages (backward-compatible additions)
    peer.msgs.treeRequest = channel.addMessage({ encoding: messages.treeRequest, onmessage: (msg) => self._onTreeRequest(peer, msg) })
    peer.msgs.treeResponse = channel.addMessage({ encoding: messages.treeResponse, onmessage: (msg) => self._onTreeResponse(peer, msg) })
    peer.msgs.contentRequest = channel.addMessage({ encoding: messages.contentRequest, onmessage: (msg) => self._onContentRequest(peer, msg) })
    // Appended-last slots: ids 0-11 stay fixed for peers without 12/13, which just
    // never register these channels and ignore the frames.
    peer.msgs.transferControl = channel.addMessage({ encoding: messages.transferControl, onmessage: (msg) => self._onTransferControl(peer, msg) })
    peer.msgs.transferProgress = channel.addMessage({ encoding: messages.transferProgress, onmessage: (msg) => self._onTransferProgress(peer, msg) })

    this._peers.set(mux, peer)
    channel.open({ version: VERSION, capabilities: CAP_LOCAL_FILES | CAP_ADAPTIVE_CHUNKS })
    return peer
  }

  // Explicit teardown — unlike an incidental channel close (where the pair callback must SURVIVE so a
  // returning peer can re-pair), detach means we are done with this mux, so drop the pairing too.
  detach (mux) {
    if (this._paired.delete(mux)) {
      try { mux.unpair({ protocol: PROTOCOL, id: this._overlayKey || null }) } catch {}
    }
    const peer = this._peers.get(mux)
    if (!peer) return
    peer.channel.close()
    this._peers.delete(mux)
  }

  setFilePaths (map) { this._filePaths = map }

  broadcastOffer (overlayPath, meta, op) {
    const msg = {
      path: overlayPath,
      contentHash: meta.contentHash || '0'.repeat(64),
      size: meta.size || 0,
      mtime: meta.mtime || 0,
      op
    }
    for (const [, peer] of this._peers) {
      peer.msgs.fileOffer.send(msg)
    }
  }

  requestFile (peer, overlayPath, contentHash, chunksHave) {
    peer.msgs.fileRequest.send({
      path: overlayPath,
      contentHash,
      chunksHave: chunksHave || null
    })
  }

  /**
   * 0.5a: Request a tree by its hash. Returns a promise resolving to
   * the entries array (or [] if the peer doesn't have it).
   *
   * @param {object} peer
   * @param {string} hash - hex tree hash
   * @param {object} [opts]
   * @param {number} [opts.timeout] - override default timeout (ms)
   * @returns {Promise<Array<{kind, exec, name, childHash, size}>>}
   */
  requestTree (peer, hash, opts = {}) {
    return new Promise((resolve, reject) => {
      // If a prior request is already in-flight for the same hash, reject
      // this caller rather than silently overwrite.
      if (peer.pendingTrees.has(hash)) {
        return reject(new Error('tree request already pending for hash: ' + hash))
      }
      // Per-request nonce (per-peer monotonic, non-zero) lets the requester drop
      // pages echoed for a superseded attempt. pages/pageBytes buffer this
      // request's own paged response, so a fresh attempt never inherits an old one.
      const nonce = peer._treeReqSeq = (peer._treeReqSeq || 0) + 1
      const timeout = opts.timeout || this._treeRequestTimeout
      const pending = { resolve, reject, timer: null, timeout, nonce, pages: null, pageBytes: 0 }
      this._armTreeTimeout(peer, hash, pending)
      peer.pendingTrees.set(hash, pending)
      peer.msgs.treeRequest.send({ hash, nonce })
    })
  }

  // Arm (or re-arm) a pending tree request's idle timeout. Every buffered page
  // re-arms it (a large tree on a slow link mustn't time out mid-stream); the
  // request still settles because the accumulator is byte-capped in _onTreeResponse.
  _armTreeTimeout (peer, hash, pending) {
    pending.timer = setTimeout(() => {
      if (peer.pendingTrees.get(hash) === pending) {
        peer.pendingTrees.delete(hash)
        pending.reject(new Error('tree request timed out: ' + hash))
      }
    }, pending.timeout)
  }

  // Reject every in-flight tree request on this peer (channel close / destroy),
  // clearing timers so the promise fails promptly and its buffered pages release.
  _failPendingTrees (peer, err) {
    for (const [hash, pending] of peer.pendingTrees) {
      clearTimeout(pending.timer)
      peer.pendingTrees.delete(hash)
      pending.reject(err)
    }
  }

  /**
   * 0.5a: Request a file by its content hash. Peer looks up any file
   * matching that hash locally and streams chunks via the existing flow
   * (chunkHashes → chunkNeed → chunkData). Returns immediately; chunks
   * arrive asynchronously.
   *
   * Note: receiver must pre-register a target path mapping via
   * _filePaths keyed by the contentHash before calling, OR this method
   * is a no-op on the receive side. Full wiring deferred to 0.5c.
   */
  requestContent (peer, contentHash, chunksHave) {
    peer.msgs.contentRequest.send({
      contentHash,
      chunksHave: chunksHave || null,
      from: this._localProfileKey || ''   // authenticate the asker to the serve gate
    })
  }

  get peerCount () { return this._peers.size }

  destroy () {
    for (const [, peer] of this._peers) {
      this._failPendingTrees(peer, new Error('protocol destroyed'))
      peer.channel.close()
    }
    this._peers.clear()
  }

  // ── Handlers ────────────────────────────────────────────────

  _onOpen (peer) {
    peer.msgs.syncState.send({
      feedKey: this._syncEngine.feedKey,
      localSeq: this._syncEngine.feed.length,
      remoteSeq: 0
    })
  }

  async _onSyncState (peer, msg) {
    peer.remoteFeedKey = msg.feedKey
    peer.remoteSeq = msg.localSeq

    if (!this._autoSync) return

    try {
      await this._offerLocalFiles(peer)
    } catch {
      // ignore — the HyperOverlay facade runs with autoSync off, so this path is dormant
    }
  }

  async _onFileOffer (peer, msg) {
    // In gated mode the overlay flow is contentRequest→scheduler ONLY; gated
    // consumers never act on path-based file-offers (autoSync is off). Ignoring
    // them closes the offer→requestFile→legacy-receive path a peer could drive.
    if (this._serveAuthorizer) return
    if (this._fileOfferCb) this._fileOfferCb(peer, msg)

    if (msg.op === 0) {
      const local = await this._syncEngine._fileIndex.getFile(msg.path)
      if (!local || local.contentHash !== msg.contentHash) {
        const diskPath = this._resolveFilePath(msg.path)
        if (diskPath) {
          this._filePaths.set(msg.path, diskPath)
          this.requestFile(peer, msg.path, msg.contentHash)
        }
      }
    }
  }

  async _onFileRequest (peer, msg) {
    // path-based serve is UNGATED and would bypass the serve gate (the only
    // gated entry point is _onContentRequest). Gated consumers never send
    // fileRequest, so refuse it outright in gated mode.
    if (this._serveAuthorizer) return
    const diskPath = this._filePaths.get(msg.path)
    if (!diskPath) return

    const prepared = await this._transferManager.prepareFile(diskPath, msg.path)
    if (!prepared) return

    if (!await this._transferManager._fileIndex.hasChunkMap(msg.path)) {
      await this._transferManager._fileIndex.putChunkMap(msg.path, prepared.chunks)
    }

    this._sendChunkHashes(peer, msg.path, prepared.tier, prepared.chunks)
  }

  // Send a file's chunk list, paged so no single frame exceeds
  // the Noise transport's 16 MiB-1 atomic-write limit. A list that fits in one
  // frame ships as one (more:0) — identical on the wire to the pre-paging format
  // bar a trailing 0 byte. _onChunkHashes reassembles the pages on the receiver.
  _sendChunkHashes (peer, filePath, tier, chunks) {
    const total = chunks.length
    if (total <= MAX_CHUNKS_PER_MSG) {
      peer.msgs.chunkHashes.send({ path: filePath, tier, chunks, more: 0 })
      return
    }
    for (let i = 0; i < total; i += MAX_CHUNKS_PER_MSG) {
      const more = i + MAX_CHUNKS_PER_MSG < total ? 1 : 0
      peer.msgs.chunkHashes.send({ path: filePath, tier, chunks: chunks.slice(i, i + MAX_CHUNKS_PER_MSG), more })
    }
  }

  // Reassemble a paged chunk list. Returns the full list once
  // the final page (more:0) arrives, or null while pages are still pending. A
  // lone complete frame passes straight through (no copy) — the small-file norm.
  // Pages for a path arrive in order on this channel, so arrival-order
  // concatenation is correct even when several files interleave on it.
  _reassembleChunkHashes (peer, msg) {
    const buffered = peer._chunkHashPages && peer._chunkHashPages.get(msg.path)
    if (!buffered && !msg.more) return msg.chunks
    if (!peer._chunkHashPages) peer._chunkHashPages = new Map()
    let acc = buffered
    if (!acc) { acc = []; peer._chunkHashPages.set(msg.path, acc) }
    for (const ch of msg.chunks) acc.push(ch)
    if (acc.length > MAX_CHUNK_HASHES_ACCUM) {
      // F2: drop an over-long accumulator (adversarial more:1 flood) instead of
      // OOMing — the fetch fails and the scheduler retries/fails over to another peer.
      peer._chunkHashPages.delete(msg.path)
      return null
    }
    if (msg.more) return null
    peer._chunkHashPages.delete(msg.path)
    return acc
  }

  // Upper-bound wire size of one tree entry: kind(1)+exec(1) + string(len-prefix ≤4
  // + utf8 name bytes) + childHash(32) + size varint(≤9, c.uint is 9 bytes for a
  // >4 GiB size).
  _treeEntryWireSize (e) {
    return 1 + 1 + 4 + Buffer.byteLength(e.name || '', 'utf8') + 32 + 9
  }

  // Send a tree's entries, paged so no single frame exceeds the Noise atomic-write
  // limit; every page but the last is more:1. A tree that fits in one frame ships
  // as a single more:0 frame. `nonce` echoes the requester's per-request id.
  _sendTreeResponse (peer, hash, entries, nonce) {
    let page = []
    let bytes = 40 // hash(32) + uint32 count prefix + more/nonce + slack
    for (const e of entries) {
      const sz = this._treeEntryWireSize(e)
      if (page.length && bytes + sz > MAX_TREE_BYTES_PER_MSG) {
        peer.msgs.treeResponse.send({ hash, entries: page, more: 1, nonce })
        page = []
        bytes = 40
      }
      page.push(e)
      bytes += sz
    }
    peer.msgs.treeResponse.send({ hash, entries: page, more: 0, nonce })
  }

  async _onChunkHashes (peer, msg) {
    // Reassemble paged chunkHashes frames before dispatching.
    const chunks = this._reassembleChunkHashes(peer, msg)
    if (chunks === null) {
      // A buffered page is forward progress — keep the scheduler's no-progress
      // watchdog from tripping while a large map streams across several frames.
      const pending = this._schedulers.get(msg.path)
      if (pending && pending.notePageProgress) pending.notePageProgress()
      return
    }
    // Multi-source: if a scheduler owns this path, let it distribute chunk
    // requests across peers instead of the legacy single-peer auto-flow.
    const sched = this._schedulers.get(msg.path)
    if (sched) { Promise.resolve(sched.onChunkHashes(peer, chunks)).catch(() => {}); return }
    // the legacy single-peer receive below writes incoming bytes
    // to _filePaths.get(path) and finalizes a rename OVER it. For a path that
    // maps to one of OUR own files (e.g. a content-register entry), an
    // unsolicited chunkHashes would let a peer overwrite the owner's source
    // file. Gated consumers only ever receive via a scheduler (the branch
    // above), so refuse any other receive.
    if (this._serveAuthorizer) return

    const diskPath = this._filePaths.get(msg.path)
    if (!diskPath) return

    // Empty-file fast path: a 0-byte file has no chunks to fetch, but we
    // still need to materialize it on disk and fire the same completion
    // flow as _onChunkData's "transfer complete" branch — otherwise the
    // requester (e.g. NetworkFetcher.getContent) never resolves and times
    // out. Empty files are common in practice: .keep, __init__.py, build
    // stamps, touch'd markers. Bug symptom before this: node-gyp's
    // postinstall.stamp (0 bytes, hash 5187b7a8…) hung every install.
    if (chunks.length === 0) {
      try {
        fs.mkdirSync(path.dirname(diskPath), { recursive: true })
        fs.writeFileSync(diskPath, Buffer.alloc(0))
      } catch {
        return
      }
      const contentHash = hashChunk(Buffer.alloc(0))
      const stat = fs.statSync(diskPath)
      await this._syncEngine._fileIndex.putFile(msg.path, {
        contentHash, size: 0, mtime: stat.mtimeMs
      })
      await this._syncEngine.logPut(msg.path, {
        contentHash, size: 0, mtime: stat.mtimeMs
      })
      if (peer.remoteFeedKey) {
        await this._syncEngine.markSynced(peer.remoteFeedKey, msg.path, contentHash, this._syncEngine.feed.length - 1)
      }
      peer.msgs.transferComplete.send({ path: msg.path, contentHash })
      if (this._syncedCb) {
        this._syncedCb({ path: msg.path, contentHash, size: 0, direction: 'pull' })
      }
      return
    }

    const needed = this._transferManager.computeNeeded(chunks, new Set())
    if (needed.length === 0) return

    let size = 0
    for (const c of chunks) size += c.length

    // startReceive can throw (fd open, partial recovery) — drop this transfer
    // instead of rejecting protomux's onmessage promise, which would destroy the
    // whole Noise stream.
    try {
      await this._transferManager.startReceive(diskPath, {
        size,
        chunks: chunks.map((c, i) => {
          let offset = 0
          for (let j = 0; j < i; j++) offset += chunks[j].length
          return { hash: c.hash, offset, length: c.length }
        })
      })
    } catch {
      return
    }

    peer.msgs.chunkNeed.send({ path: msg.path, indices: needed })
  }

  async _onChunkNeed (peer, msg) {
    // Serve bytes ONLY for a synthetic path THIS peer was
    // authorized for via a gated _onContentRequest. Blocks a peer pulling bytes
    // by sending chunkNeed directly for a registered path (e.g. a content-
    // register entry) without passing the serve gate.
    if (this._serveAuthorizer && !peer.authorizedServe.has(msg.path)) return
    const diskPath = this._filePaths.get(msg.path)
    if (!diskPath) return

    const fileIndex = this._transferManager._fileIndex
    let chunkMap
    try {
      chunkMap = msg.path.startsWith('content:')
        ? await fileIndex.getChunkMapByHash(msg.path.slice('content:'.length))
        : await fileIndex.getChunkMap(msg.path)
    } catch {
      // A chunk-map lookup that rejects (index I/O error) must not escape: the
      // onmessage dispatch is fire-and-forget, so a throw here becomes an
      // unhandled rejection that tears down the whole Noise/replication stream
      // (the S1 malformed-frame hardening theme). Drop the request — the receiver
      // re-requests and the transfer self-heals.
      return
    }
    if (!chunkMap) return

    // Single-flight serve pump per peer (mirrors hypercore's `receiverBusy`).
    // Enqueue this request; if no pump is running for this peer, drain the queue
    // one job at a time. protomux dispatches every frame of a socket read
    // synchronously, so two chunkNeed frames from the same peer would otherwise
    // start rival serve loops — interleaving sends and admitting N chunks per
    // drain instead of honouring backpressure once (the discipline our 0.2.13
    // serialized pump had, which Ok's inline loop dropped).
    if (!peer._serveQueue) peer._serveQueue = []
    peer._serveQueue.push({ path: msg.path, diskPath, chunkMap, indices: msg.indices })
    if (peer._serving) return
    peer._serving = true
    // Kick the pump fire-and-forget: _onChunkNeed is the onmessage dispatch and
    // must return promptly, NOT stay pending for the whole multi-chunk serve
    // (which, under backpressure, spans the entire transfer). A second chunkNeed
    // from this peer just enqueues above; the single-flight guard (_serving) means
    // this already-running pump picks it up. This is our 0.2.13 contract — Ok's
    // inline drain loop awaited the whole serve, which the unit test rejects.
    this._drainServeQueue(peer)
  }

  // The per-peer single-flight serve pump. Drains _serveQueue one job at a time;
  // detached from _onChunkNeed so the message handler returns immediately.
  async _drainServeQueue (peer) {
    try {
      while (peer._serveQueue.length) {
        if (peer.channel && peer.channel.closed) { peer._serveQueue.length = 0; break }
        try { await this._serveJob(peer, peer._serveQueue.shift()) } catch {}
      }
    } finally {
      peer._serving = false
    }
  }

  // Serve one chunkNeed job: stream the requested chunk indices, honouring
  // stream backpressure — stop producing when send() reports the write buffer is
  // full and resume on drain, so sibling protocols multiplexed on the same Noise
  // stream (Corestore replication, app handshakes; protomux MAX_BACKLOG is
  // Infinity) aren't starved. Runs under the per-peer single-flight guard in
  // _onChunkNeed, so exactly one job streams at a time per peer.
  async _serveJob (peer, job) {
    const { path, diskPath, chunkMap, indices } = job
    // P3: cork the mux so a run of chunkData frames coalesces into fewer stream
    // writes (hypercore's replicator corks around each request/response batch,
    // replicator.js:722/738). Uncork before parking on drain (flush the batch) and
    // in the finally. The `corked` guard keeps cork/uncork balanced across the early
    // returns, and no-ops when the mux stub has no cork (unit tests).
    const mux = peer.mux
    let corked = false
    const cork = () => { if (mux && mux.cork && !corked) { mux.cork(); corked = true } }
    const uncork = () => { if (mux && mux.uncork && corked) { mux.uncork(); corked = false } }
    cork()
    try {
      for (let i = 0; i < indices.length; i++) {
        const index = indices[i]
        if (index >= chunkMap.length) continue
        // P5: skip a chunk the downloader hotswapped away (one-shot).
        if (peer._cancelledServe && peer._cancelledServe.delete(path + '\x00' + index)) continue
        const c = chunkMap[index]
        const data = this._transferManager.readChunk(diskPath, c.offset, c.length)
        if (!data) continue
        const flushed = peer.msgs.chunkData.send({ path, index, data })
        if (this._chunkServeCb) {
          try { this._chunkServeCb({ path, index, bytes: data.length, peer, from: peer.authorizedServe.get(path) || null }) } catch {}
        }
        if (flushed === false && i < indices.length - 1) {
          uncork()   // flush the corked batch before we park on drain
          const alive = await this._waitForDrain(peer)
          if (!alive) return
          if (this._serveAuthorizer && !peer.authorizedServe.has(path)) return
          cork()     // re-cork for the next run
        }
      }
    } finally {
      uncork()
    }
  }

  // One shared drain waiter per peer so concurrent serve loops (the
  // same peer pulling several files) don't each attach listeners and trip the stream's
  // max-listeners warning. Resolves true on drain, false if the channel closes first.
  _waitForDrain (peer) {
    const channel = peer.channel
    const stream = peer.mux && peer.mux.stream
    if (!stream || !channel || channel.closed) return Promise.resolve(false)
    if (channel.drained) return Promise.resolve(true)
    if (peer._drainWait) return peer._drainWait
    peer._drainWait = new Promise((resolve) => {
      let timer = null
      const done = (alive) => {
        if (timer) clearTimeout(timer)
        stream.removeListener('drain', onDrain)
        stream.removeListener('close', onClose)
        peer._drainWait = null
        resolve(alive)
      }
      const onDrain = () => done(!channel.closed)
      const onClose = () => done(false)
      timer = setTimeout(() => done(false), DRAIN_TIMEOUT_MS)
      stream.on('drain', onDrain)
      stream.on('close', onClose)
    })
    return peer._drainWait
  }

  async _onChunkData (peer, msg) {
    // Silent-peer watchdog hook: fire BEFORE any processing so a slow disk
    // doesn't get blamed for a peer-side stall.
    if (this._chunkProgressCb) {
      try {
        this._chunkProgressCb({
          path: msg.path,
          index: msg.index,
          bytes: msg.data ? msg.data.length : 0,
          peer
        })
      } catch {}
    }

    // Multi-source: scheduler owns the write + reschedule + finalize.
    const sched = this._schedulers.get(msg.path)
    if (sched) { Promise.resolve(sched.onChunkData(peer, msg.index, msg.data)).catch(() => {}); return }
    // refuse the legacy single-peer receive (writes+renames over
    // _filePaths.get(path), i.e. potentially our own source file). Gated
    // consumers only receive via a scheduler (above).
    if (this._serveAuthorizer) return

    const diskPath = this._filePaths.get(msg.path)
    if (!diskPath) return

    const result = this._transferManager.writeChunk(diskPath, msg.index, msg.data)

    if (result.ok && this._transferManager.isComplete(diskPath)) {
      const fin = await this._transferManager.finalize(diskPath)
      if (fin.ok) {
        const fileData = fs.readFileSync(diskPath)
        const contentHash = hashChunk(fileData)
        const stat = fs.statSync(diskPath)

        await this._syncEngine._fileIndex.putFile(msg.path, {
          contentHash, size: stat.size, mtime: stat.mtimeMs
        })
        await this._syncEngine.logPut(msg.path, {
          contentHash, size: stat.size, mtime: stat.mtimeMs
        })

        if (peer.remoteFeedKey) {
          await this._syncEngine.markSynced(peer.remoteFeedKey, msg.path, contentHash, this._syncEngine.feed.length - 1)
        }

        peer.msgs.transferComplete.send({ path: msg.path, contentHash })
        if (this._syncedCb) {
          this._syncedCb({ path: msg.path, contentHash, size: stat.size, direction: 'pull' })
        }
      }
    }
  }

  _onChunkCancel (peer, msg) {
    if (msg.indices && msg.indices.length) {
      // P5 hotswap: the downloader reassigned these chunk indices to a faster peer.
      // Stop serving just them (bandwidth save); the rest of the transfer continues.
      // Consumed one-shot in _serveJob.
      if (!peer._cancelledServe) peer._cancelledServe = new Set()
      for (const i of msg.indices) peer._cancelledServe.add(msg.path + '\x00' + i)
      return
    }
    const diskPath = this._filePaths.get(msg.path)
    if (diskPath) this._transferManager.cancel(diskPath)
  }

  // Resolve a serve-message's downloader identity from the authenticated record we kept at
  // serve start (peer.authorizedServe), NOT the message — so a peer can only affect its own
  // ledger row, never spoof another. Returns null `from` when the peer was never authorized.
  _authorizedFrom (peer, contentHash) {
    const synthPath = 'content:' + contentHash
    return { synthPath, from: peer.authorizedServe.get(synthPath) || null }
  }

  // A downloader told us it paused/stopped pulling a hash WE serve.
  _onTransferControl (peer, msg) {
    if (!this._serveControlCb) return
    const { synthPath, from } = this._authorizedFrom(peer, msg.contentHash)
    if (!from) return
    const state = msg.state === CONTROL_STOPPED ? 'stopped' : 'paused'
    try { this._serveControlCb({ path: synthPath, peer, from, state }) } catch {}
  }

  // A downloader reported its on-disk have-bytes for a hash WE serve.
  _onTransferProgress (peer, msg) {
    if (!this._serveProgressCb) return
    const { synthPath, from } = this._authorizedFrom(peer, msg.contentHash)
    if (!from) return
    try { this._serveProgressCb({ path: synthPath, peer, from, have: msg.have || 0 }) } catch {}
  }

  async _onTransferComplete (peer, msg) {
    if (peer.remoteFeedKey) {
      await this._syncEngine.markSynced(peer.remoteFeedKey, msg.path, msg.contentHash, this._syncEngine.feed.length - 1)
    }
    if (this._syncedCb) {
      this._syncedCb({ path: msg.path, contentHash: msg.contentHash, direction: 'push' })
    }
  }

  _onConflictMsg (peer, msg) {
    if (this._conflictCb) this._conflictCb(msg, peer)
  }

  // ── Tree handlers (0.5a) ────────────────────────────────────

  async _onTreeRequest (peer, msg) {
    // ungated metadata oracle (returns fileIndex tree entries to
    // any peer). Gated consumers never use tree-requests; refuse in gated mode.
    if (this._serveAuthorizer) return
    let entries = []
    try {
      const fileIndex = this._syncEngine && this._syncEngine._fileIndex
      if (fileIndex && typeof fileIndex.getTree === 'function') {
        const tree = await fileIndex.getTree(msg.hash)
        if (tree && Array.isArray(tree.entries)) entries = tree.entries
      }
    } catch {
      // fall through — reply with empty entries on lookup failure
    }
    this._sendTreeResponse(peer, msg.hash, entries, msg.nonce || 0)
  }

  _onTreeResponse (peer, msg) {
    const pending = peer.pendingTrees.get(msg.hash)
    if (!pending) return // no request in flight — drop
    // Drop a page echoing a superseded request's nonce (a stale page from a
    // timed-out attempt must not settle a later same-hash retry). nonce 0 = a
    // pre-nonce holder that can't echo it, so fall through (unverifiable,
    // best-effort).
    if (msg.nonce && msg.nonce !== pending.nonce) return
    const settle = (fn, arg) => { clearTimeout(pending.timer); peer.pendingTrees.delete(msg.hash); fn(arg) }
    // Lone complete frame (the small-tree norm) resolves with no accumulation.
    if (!pending.pages && !msg.more) return settle(pending.resolve, msg.entries)
    // Accumulate into THIS request's own buffer, bounding total bytes so a peer
    // streaming pages endlessly rejects the request instead of growing memory
    // without limit.
    if (!pending.pages) pending.pages = []
    for (const e of msg.entries) { pending.pages.push(e); pending.pageBytes += this._treeEntryWireSize(e) }
    if (pending.pageBytes > this._maxTreeResponseBytes) {
      return settle(pending.reject, new Error('tree response too large: ' + msg.hash))
    }
    if (msg.more) {
      // Forward progress — re-arm the idle timeout so a legitimately large
      // multi-page tree on a slow link doesn't time out mid-stream.
      clearTimeout(pending.timer)
      this._armTreeTimeout(peer, msg.hash, pending)
      return
    }
    settle(pending.resolve, pending.pages)
  }

  async _onContentRequest (peer, msg) {
    // serve gate. BEFORE any path resolution or streaming,
    // ask the injected authorizer whether this peer may receive this hash.
    // Deny == silent return (same observable behavior as "I don't hold it"
    // below), so a non-member cannot distinguish denial from absence.
    if (this._serveAuthorizer) {
      let ok = false
      try { ok = await this._serveAuthorizer(peer, msg.from || null, msg.contentHash) } catch { ok = false }
      if (!ok) return
    }

    // Resolve msg.contentHash → an on-disk path. Three lookup paths, in order:
    //  1. Fast path: _contentHashPaths map (warm — just-registered / consumer-set)
    //  2. Content-addressed spool (RESTART-DURABLE): <syncBaseDir>/<contentHash>
    //  3. Slow path: scan fileIndex for any file:* entry with that hash
    let diskPath = this._contentHashPaths.get(msg.contentHash)
    if (diskPath && !fileExists(diskPath)) diskPath = null

    if (!diskPath) {
      // Content-addressed spool fallback. The canonical bytes are stored at
      // <syncBaseDir>/<contentHash> (fetchFile's mirrorSpool option writes them
      // there). The in-memory map is empty after a restart and FileIndex
      // persists no disk path, so resolve the hash straight from the
      // content-addressed spool — a pure function of the hash + dir, like a
      // git object store's blobs/<hash>. This is what lets a node keep serving
      // its spooled files across restarts with no rehydration step.
      for (const baseDir of this._syncBaseDirs) {
        const candidate = path.join(baseDir, msg.contentHash)
        if (fileExists(candidate)) {
          diskPath = candidate
          this._contentHashPaths.set(msg.contentHash, candidate) // warm the map
          break
        }
      }
    }

    if (!diskPath) {
      // Scan fileIndex for a file whose contentHash matches.
      const fileIndex = this._syncEngine && this._syncEngine._fileIndex
      if (fileIndex && typeof fileIndex.listFiles === 'function') {
        try {
          const files = await fileIndex.listFiles()
          for (const f of files) {
            if (f.contentHash === msg.contentHash) {
              diskPath = this._filePaths.get(f.path)
              if ((!diskPath || !fileExists(diskPath)) && f.path) diskPath = f.path
              break
            }
          }
        } catch {
          // fall through
        }
      }
    }

    if (!diskPath) {
      // Don't have it. Silently drop; requester will time out.
      return
    }

    // Use a SYNTHETIC path keyed by contentHash so the requester can
    // pre-register a destPath and the chunk flow routes correctly on
    // both sides. Temporarily populate _filePaths so _onChunkNeed +
    // chunkmap lookups resolve under this synthetic key.
    const syntheticPath = 'content:' + msg.contentHash
    this._filePaths.set(syntheticPath, diskPath)
    peer.authorizedServe.set(syntheticPath, msg.from || null) // _onChunkNeed will now serve this path to THIS peer

    // The chunk map is content-addressed — identical bytes always chunk
    // identically. Reuse one computed at publish (or a prior serve, or before a
    // restart) instead of re-reading the whole file to re-chunk it: re-chunking a
    // multi-GB file adds a full-file-read of latency before the first byte ships.
    const fileIndex = this._transferManager._fileIndex
    let chunks = await fileIndex.getChunkMapByHash(msg.contentHash)
    let tier
    if (chunks) {
      let size = 0
      try { size = fs.statSync(diskPath).size } catch {}
      tier = selectTier(size)
    } else {
      const prepared = await this._transferManager.prepareFile(diskPath, syntheticPath, { byHashOnly: true })
      if (!prepared) {
        this._filePaths.delete(syntheticPath)
        peer.authorizedServe.delete(syntheticPath) // keep the authorize map in lockstep with _filePaths
        return
      }
      chunks = prepared.chunks
      tier = prepared.tier
      // prepareFile persists the hash-keyed map only for large files; ensure it exists
      // for small ones too, since _onChunkNeed resolves content:<hash> by that map.
      if (!await fileIndex.hasChunkMapByHash(msg.contentHash)) await fileIndex.putChunkMapByHash(msg.contentHash, chunks)
    }
    this._sendChunkHashes(peer, syntheticPath, tier, chunks)
    if (this._serveStartCb) {
      let total = 0
      for (const c of chunks) total += c.length || 0
      try { this._serveStartCb({ path: syntheticPath, peer, from: msg.from || null, total }) } catch {}
    }
  }

  // ── Sync logic ──────────────────────────────────────────────

  /**
   * Offer all local files to a peer.
   * Reads from the local feed and sends file-offers for each entry.
   * The peer will request any files it doesn't have.
   */
  async _offerLocalFiles (peer) {
    const feed = this._syncEngine.feed
    if (feed.length === 0) return

    for (let i = 0; i < feed.length; i++) {
      try {
        const entry = await feed.get(i)
        if (!entry) continue

        // Register the file path mapping so _onFileRequest can find it
        if (entry.op === 0) {
          const diskPath = this._resolveFilePath(entry.path)
          if (diskPath) this._filePaths.set(entry.path, diskPath)
        }

        peer.msgs.fileOffer.send({
          path: entry.path,
          contentHash: entry.hash || '0'.repeat(64),
          size: entry.size || 0,
          mtime: entry.mtime || 0,
          op: entry.op
        })
      } catch {
        // skip unreadable entries
      }
    }
  }

  /**
   * Resolve an overlay path to a disk path.
   */
  _resolveFilePath (overlayPath) {
    if (this._filePaths.has(overlayPath)) return this._filePaths.get(overlayPath)
    for (const baseDir of this._syncBaseDirs) {
      return path.join(baseDir, overlayPath)
    }
    return null
  }
}

// True iff `p` is an existing regular file. Used to validate a resolved disk path
// before serving (a cold-restart map entry or an overlay-path masquerading as a
// disk path won't exist) and to probe the content-addressed spool.
function fileExists (p) {
  try { return fs.statSync(p).isFile() } catch { return false }
}
/**
 * TransferManager — On-demand chunking and streaming file transfer
 *
 * Sender side:
 *   1. Read file from disk
 *   2. Chunk on demand (adaptive FastCDC)
 *   3. Send chunk hashes → peer says which it needs → stream those chunks
 *   4. Release chunks from memory after send
 *
 * Receiver side:
 *   1. Receive chunk hashes, respond with which are missing
 *   2. Receive chunks, write to <file>.overlay-partial
 *   3. Verify each chunk hash
 *   4. Atomic rename on completion
 *
 * No blob storage. Chunks exist in memory during transfer only.
 */

import fs from 'bare-fs'
import path from 'bare-path'
import os from 'bare-os'
import c from 'compact-encoding'
import sodium from 'sodium-universal'
import { chunk as chunkBuffer, chunkStream, hashChunk, createStreamingHasher, selectTier, getTierParams } from './chunker.js'

export const PARTIAL_SUFFIX = '.overlay-partial'

export const partialPathFor = (targetPath) => path.join(path.dirname(targetPath), path.basename(targetPath) + PARTIAL_SUFFIX)

// Resume verification + whole-file hashing run async + yielding so a multi-GB pass
// never blocks the event loop (IPC, pause/cancel, progress stay live).
const VERIFY_YIELD_EVERY = 64
const yieldToLoop = () => new Promise((resolve) => setTimeout(resolve, 0))

// Receive journal: bitmap + whole-file hash snapshot, stored in app-private storage
// (opts.journalDir) keyed by a digest of the destination path — never next to the
// download — so resume is O(1) and the incremental verify continues with no re-read.
const JOURNAL_SUFFIX = '.journal'
const JOURNAL_MAGIC = 0x4d4a5633
const JOURNAL_FLUSH_EVERY = 512
const JOURNAL_FLUSH_INTERVAL_MS = 1500
export const journalNameFor = (targetPath) => hashChunk(Buffer.from(targetPath)) + JOURNAL_SUFFIX

// Block-read prepare — host-adaptive read block size.
const READ_BLOCK_DEFAULT = 8 * 1024 * 1024
const READ_BLOCK_LOW_RAM = 4 * 1024 * 1024
const LOW_RAM_THRESHOLD = 6 * 1024 * 1024 * 1024

// Cap on stashed just-received chunk buffers (per transfer, insert-refusal), and the
// hash pump's yield budget — stash-fed iterations never await, so the pump yields by
// bytes hashed, not chunk count.
const MEM_STASH_BYTES_DEFAULT = 16 * 1024 * 1024
const DRAIN_YIELD_BYTES = 2 * 1024 * 1024

// Emit file blocks >= tier maxSize so chunkStream drains every block
// instead of re-copying a growing pending buffer (64 KiB createReadStream reads force
// ~56x memcpy at tier 3). Owns its fd and closes it on every terminal path: normal
// end, consumer break/throw (for-await calls .return() → finally), read error.
async function * readFileBlocks (filePath, size, blockSize) {
  const fd = await fs.open(filePath, 'r')
  try {
    let pos = 0
    while (pos < size) {
      const want = Math.min(blockSize, size - pos)
      const buf = Buffer.allocUnsafe(want)
      let filled = 0
      while (filled < want) {
        const n = await fs.read(fd, buf, filled, want - filled, pos + filled)
        if (n <= 0) break
        filled += n
      }
      if (filled === 0) break
      pos += filled
      yield filled === buf.length ? buf : buf.subarray(0, filled)
    }
  } finally {
    try { await fs.close(fd) } catch {}
  }
}

function bitmapOf (received, total) {
  const bm = Buffer.alloc((total + 7) >> 3)
  for (const i of received) bm[i >> 3] |= 1 << (i & 7)
  return bm
}

// Drop journals whose partial is gone, are stale, or are corrupt/foreign. Each
// journal self-describes its partial path (read cheaply from the header). Standalone
// (no TransferManager instance) so a boot-time sweep can reclaim orphans without
// the overlay stack being live.
export function cleanupOrphanedJournals (journalDir, maxAge = 7 * 86400000) {
  const cleaned = []
  if (!journalDir) return cleaned
  let entries
  try { entries = fs.readdirSync(journalDir) } catch { return cleaned }
  const now = Date.now()
  for (const entry of entries) {
    if (!entry.endsWith(JOURNAL_SUFFIX)) continue
    const full = path.join(journalDir, entry)
    let remove = false
    try {
      const raw = fs.readFileSync(full)
      const s = { start: 0, end: raw.length, buffer: raw }
      if (c.uint32.decode(s) !== JOURNAL_MAGIC) remove = true
      else {
        c.uint32.decode(s)
        const partialPath = c.string.decode(s)
        if (!fs.existsSync(partialPath)) remove = true
        else if (now - fs.statSync(full).mtimeMs > maxAge) remove = true
      }
    } catch { remove = true }
    if (remove) { try { fs.unlinkSync(full); cleaned.push(full) } catch {} }
  }
  return cleaned
}

export class TransferManager {
  constructor (fileIndex, opts = {}) {
    this._fileIndex = fileIndex
    this._maxConcurrency = opts.maxConcurrency || 4
    this._active = new Map() // path → transfer state
    this._memStashBytes = opts.memStashBytes ?? MEM_STASH_BYTES_DEFAULT
    this._journalDir = opts.journalDir || null
    if (this._journalDir) { try { fs.mkdirSync(this._journalDir, { recursive: true }) } catch {} }
  }

  _journalPathFor (targetPath) {
    if (!this._journalDir) return null
    return path.join(this._journalDir, journalNameFor(targetPath))
  }

  // ── Sender side ─────────────────────────────────────────────

  /**
   * Prepare a file for sending — read from disk, chunk, return hashes.
   * Chunk map is persisted for large files (>1MB).
   *
   * @param {string} filePath - absolute path on disk
   * @param {string} overlayPath - path in the overlay namespace
   * @returns {{ tier: number, chunks: Array<{ hash, offset, length }>, size: number } | null}
   */
  async prepareFile (filePath, overlayPath, opts = {}) {
    // Check file exists and get stats
    let stat
    try {
      stat = fs.statSync(filePath)
    } catch {
      return null
    }

    if (!stat.isFile()) return null

    const mtimeBefore = stat.mtimeMs

    // Check for existing chunk map (skip re-chunking if valid)
    const existing = await this._fileIndex.getChunkMap(overlayPath)
    const fileMeta = await this._fileIndex.getFile(overlayPath)

    if (existing && fileMeta && fileMeta.mtime === mtimeBefore) {
      // Chunk map still valid — file hasn't changed.
      // Backfill the content-addressed alias so the serve path (a
      // different overlay key) reuses this map instead of re-reading the file —
      // covers maps chunked before content-addressed caching existed.
      if (fileMeta.contentHash && stat.size >= 1048576 && !await this._fileIndex.hasChunkMapByHash(fileMeta.contentHash)) {
        await this._fileIndex.putChunkMapByHash(fileMeta.contentHash, existing)
      }
      return {
        tier: selectTier(stat.size),
        chunks: existing,
        size: stat.size,
        contentHash: fileMeta.contentHash // surfaced so the publish path gets the hash from one pass
      }
    }

    // Read in blocks >= tier maxSize and chunk from views (copy:false).
    // Cut points are content-stable across block sizes, so peers still match hashes.
    // size is passed to the hasher so the streaming digest matches hashChunk(buffer).
    const tier = selectTier(stat.size)
    const blockSize = Math.max(
      getTierParams(tier).maxSize,
      os.totalmem() < LOW_RAM_THRESHOLD ? READ_BLOCK_LOW_RAM : READ_BLOCK_DEFAULT
    )
    const fileHasher = createStreamingHasher({ size: stat.size })
    const chunks = []

    for await (const c of chunkStream(readFileBlocks(filePath, stat.size, blockSize), { tier, copy: false })) {
      // honor a publish-cancel signal (per-chunk granularity); on throw the
      // for-await calls readFileBlocks.return() which closes the fd.
      if (opts.signal?.aborted) { const e = new Error('publish aborted'); e.code = 'ECANCELLED'; throw e }
      fileHasher.update(c.data)
      chunks.push({ hash: c.hash, offset: c.offset, length: c.length })
      opts.onProgress?.(c.length)
    }

    // mtime guard — abort if file changed during the streaming read. A
    // vanished source (moved out of the folder mid-read) is just another "changed
    // during read" case — the open fd kept the read alive after a same-volume
    // rename, so it is this path-resolving stat that trips ENOENT. Guard it like
    // the pre-read stat above and re-queue rather than throw.
    let statAfter
    try {
      statAfter = fs.statSync(filePath)
    } catch {
      return null // source vanished during read, caller should re-queue
    }
    if (statAfter.mtimeMs !== mtimeBefore) {
      return null // file changed during read, caller should re-queue
    }

    // Post-read guard: a mid-read shrink can feed the digest fewer bytes than the
    // size baked into its leaf prefix — re-queue instead of persisting a bad hash.
    if (fileHasher.bytes !== stat.size) return null

    // Update file index
    const contentHash = fileHasher.digest()

    // Persist chunk map for large files — both path-keyed (legacy serve lookups)
    // and content-addressed, so the serve path reuses it across keys.
    // byHashOnly (the publish prepareForServe pass) keeps ONLY the
    // content-addressed map — the serve path resolves by hash, so the path-keyed map
    // + putFile under a throwaway overlay key would be dead, never-read state.
    if (stat.size >= 1048576) {
      if (!opts.byHashOnly) await this._fileIndex.putChunkMap(overlayPath, chunks)
      if (!await this._fileIndex.hasChunkMapByHash(contentHash)) await this._fileIndex.putChunkMapByHash(contentHash, chunks)
    }

    if (!opts.byHashOnly) {
      await this._fileIndex.putFile(overlayPath, {
        contentHash,
        size: stat.size,
        mtime: mtimeBefore
      })
    }

    return { tier, chunks, size: stat.size, contentHash }
  }

  /**
   * Read a specific chunk from disk by its offset and length.
   * Returns raw bytes — caller sends them to the peer.
   *
   * @param {string} filePath - absolute path on disk
   * @param {number} offset - byte offset
   * @param {number} length - bytes to read
   * @returns {Buffer | null}
   */
  readChunk (filePath, offset, length) {
    try {
      const fd = fs.openSync(filePath, 'r')
      const buf = Buffer.alloc(length)
      const bytesRead = fs.readSync(fd, buf, 0, length, offset)
      fs.closeSync(fd)
      if (bytesRead !== length) return null
      return buf
    } catch {
      return null
    }
  }

  /**
   * Determine which chunks a peer needs (chunks they don't already have).
   *
   * @param {Array<{ hash, offset, length }>} offered - chunks the sender has
   * @param {Set<string>} peerHas - set of chunk hashes the peer already has
   * @returns {number[]} indices of chunks the peer needs
   */
  computeNeeded (offered, peerHas) {
    const needed = []
    for (let i = 0; i < offered.length; i++) {
      if (!peerHas.has(offered[i].hash)) {
        needed.push(i)
      }
    }
    return needed
  }

  // ── Receiver side ───────────────────────────────────────────

  // Start receiving a file. A same-size partial is resumed: the journal restores the
  // received-set + whole-file hash snapshot in O(1) (no re-read); failing that, an
  // async, yielding re-verify rebuilds them without blocking the event loop.
  // opts.isCancelled aborts a long re-verify; opts.onVerifyProgress(0..1) drives the UI.
  async startReceive (targetPath, meta, opts = {}) {
    const isCancelled = opts.isCancelled || (() => false)
    const dir = path.dirname(targetPath)
    const base = path.basename(targetPath)
    // Visible partial (no leading dot) so an in-progress download shows in the
    // destination folder; the distinct ".overlay-partial" suffix keeps host-app
    // sweeps keyed on a plain ".partial" suffix from deleting a paused overlay
    // partial.
    const partialPath = path.join(dir, base + PARTIAL_SUFFIX)
    const journalPath = this._journalPathFor(targetPath)

    fs.mkdirSync(dir, { recursive: true })

    let resumed = false
    try { resumed = fs.statSync(partialPath).size === meta.size } catch {}

    let received = new Set()
    let hasher = meta.contentHash ? createStreamingHasher({ size: meta.size }) : null
    let hashFrontier = 0

    if (resumed) {
      const j = journalPath ? this._loadJournal(journalPath, partialPath, meta) : null
      if (j) {
        received = j.received
        hashFrontier = j.hashFrontier
        if (meta.contentHash) hasher = createStreamingHasher({ size: meta.size, restore: { state: j.hasherState, bytes: j.hasherBytes } })
      } else {
        const rec = await this._recoverPartialAsync(partialPath, meta, isCancelled, opts.onVerifyProgress)
        received = rec.received; hasher = rec.hasher; hashFrontier = rec.hashFrontier
      }
    } else {
      if (journalPath) { try { fs.unlinkSync(journalPath) } catch {} }
    }

    if (isCancelled()) { const e = new Error('receive cancelled during setup'); e.code = 'ECANCELLED'; throw e }

    // ONE persistent fd for the whole transfer — positioned writeSync/fs.read never
    // move a shared cursor, so a single handle serves the chunk writes, the hash
    // pump's gap read-back, and the journal fsync. Replaces an openSync+closeSync per
    // chunk; 'w+' creates+truncates the fresh partial in the same open.
    const fd = fs.openSync(partialPath, resumed ? 'r+' : 'w+')
    if (!resumed) {
      try { fs.ftruncateSync(fd, meta.size) } catch (err) { try { fs.closeSync(fd) } catch {}; throw err }
    }

    const total = meta.chunks.length
    const state = {
      partialPath,
      targetPath,
      journalPath,
      chunks: meta.chunks,
      received,
      bitmap: bitmapOf(received, total),
      total,
      size: meta.size,
      contentHash: meta.contentHash || null,
      hasher,
      hashFrontier,
      advancePromise: null,
      draining: false,
      sinceFlush: 0,
      lastFlush: 0,
      flushing: false,
      flushPending: false,
      fd,
      // Bounded stash of just-received verified chunk buffers so the hash pump feeds
      // from memory instead of reading the bytes back off disk. Never load-bearing:
      // bytes hit disk first; a miss falls back to read-back.
      memChunks: new Map(),
      memBytes: 0,
      stats: { readbacks: 0, stashHits: 0 }
    }

    // A prior transfer for this path that ended via _fail (stall / all-peers-
    // gone / disk error) leaves its state here with an open fd — close it before
    // overwriting so a retry/resume of the same file can't orphan the fd.
    const prev = this._active.get(targetPath)
    if (prev) this._closeFd(prev)

    this._active.set(targetPath, state)
    // A fresh transfer has nothing worth journaling yet; a resume that recovered
    // chunks persists them now so an immediate re-pause is O(1).
    if (received.size > 0) this._flushJournal(state)
    return state
  }

  // Rebuild the received-set from a same-size partial without blocking the loop:
  // async reads, a yield every VERIFY_YIELD_EVERY chunks, feeding the contiguous
  // prefix into the whole-file hasher inline (single pass, no second read).
  async _recoverPartialAsync (partialPath, meta, isCancelled, onVerifyProgress) {
    const received = new Set()
    const hasher = meta.contentHash ? createStreamingHasher({ size: meta.size }) : null
    let hashFrontier = 0
    const total = meta.chunks.length
    const maxLen = meta.chunks.reduce((m, c) => (c.length > m ? c.length : m), 0)
    const buf = Buffer.allocUnsafe(maxLen)
    let lastPct = -1
    onVerifyProgress?.(0)
    const fd = await fs.open(partialPath, 'r')
    try {
      for (let i = 0; i < total; i++) {
        if (isCancelled()) { const e = new Error('receive recovery cancelled'); e.code = 'ECANCELLED'; throw e }
        const ci = meta.chunks[i]
        let n = 0
        try { n = await fs.read(fd, buf, 0, ci.length, ci.offset) } catch {}
        const view = buf.subarray(0, ci.length)
        if (n === ci.length && hashChunk(view) === ci.hash) {
          received.add(i)
          if (hasher && i === hashFrontier) { hasher.update(view); hashFrontier++ }
        }
        if ((i & (VERIFY_YIELD_EVERY - 1)) === VERIFY_YIELD_EVERY - 1) {
          const pct = Math.floor(((i + 1) / total) * 100)
          if (pct !== lastPct) { lastPct = pct; onVerifyProgress?.(pct / 100) }
          await yieldToLoop()
        }
      }
    } finally {
      try { await fs.close(fd) } catch {}
    }
    onVerifyProgress?.(1)
    return { received, hasher, hashFrontier }
  }

  _encodeJournal (state) {
    const total = state.total
    const bm = state.bitmap
    const ch = state.contentHash ? Buffer.from(state.contentHash, 'hex') : Buffer.alloc(32)
    const snap = state.hasher ? state.hasher.snapshot() : { state: Buffer.alloc(0), bytes: 0 }
    const s = { start: 0, end: 0, buffer: null }
    c.uint32.preencode(s, JOURNAL_MAGIC)
    c.uint32.preencode(s, sodium.crypto_generichash_STATEBYTES)
    c.string.preencode(s, state.partialPath)
    c.uint64.preencode(s, state.size)
    c.uint32.preencode(s, total)
    c.fixed32.preencode(s, ch)
    c.uint32.preencode(s, state.hashFrontier)
    c.uint64.preencode(s, snap.bytes)
    c.buffer.preencode(s, snap.state)
    c.buffer.preencode(s, bm)
    s.buffer = Buffer.allocUnsafe(s.end)
    c.uint32.encode(s, JOURNAL_MAGIC)
    c.uint32.encode(s, sodium.crypto_generichash_STATEBYTES)
    c.string.encode(s, state.partialPath)
    c.uint64.encode(s, state.size)
    c.uint32.encode(s, total)
    c.fixed32.encode(s, ch)
    c.uint32.encode(s, state.hashFrontier)
    c.uint64.encode(s, snap.bytes)
    c.buffer.encode(s, snap.state)
    c.buffer.encode(s, bm)
    return s.buffer
  }

  // Returns the resume state only when the journal is for this partial, binds to
  // this content, and its snapshot is restorable on this libsodium build; else null
  // so the caller falls back to the async re-verify.
  _loadJournal (journalPath, partialPath, meta) {
    let raw
    try { raw = fs.readFileSync(journalPath) } catch { return null }
    try {
      const s = { start: 0, end: raw.length, buffer: raw }
      if (c.uint32.decode(s) !== JOURNAL_MAGIC) return null
      const stateBytes = c.uint32.decode(s)
      const storedPartial = c.string.decode(s)
      const size = c.uint64.decode(s)
      const total = c.uint32.decode(s)
      const ch = c.fixed32.decode(s).toString('hex')
      const hashFrontier = c.uint32.decode(s)
      const hasherBytes = c.uint64.decode(s)
      const hasherState = c.buffer.decode(s)
      const bm = c.buffer.decode(s)
      // F1: never trust a journal we cannot whole-file-verify. Both finalize and the
      // legacy receive path skip the whole-file hash when contentHash is absent, so a
      // FOREIGN journal with a matching size + chunk-count (a stale .overlay-partial
      // for different content the CDC split into the same number of chunks) would be
      // trusted and finalized as merged old+new bytes, undetected. Require a content
      // hash to resume from a journal; without one the caller falls back to
      // _recoverPartialAsync, which re-verifies every chunk by its per-chunk hash.
      if (!meta.contentHash) return null
      if (storedPartial !== partialPath) return null
      if (size !== meta.size || total !== meta.chunks.length) return null
      if (ch !== meta.contentHash) return null
      if (meta.contentHash) {
        if (stateBytes !== sodium.crypto_generichash_STATEBYTES) return null
        if (hasherState.length !== sodium.crypto_generichash_STATEBYTES) return null
      }
      const received = new Set()
      for (let i = 0; i < total; i++) if (bm[i >> 3] & (1 << (i & 7))) received.add(i)
      return { received, hashFrontier, hasherState, hasherBytes }
    } catch { return null }
  }

  // Best-effort async crash-hedge flush: never blocks the receive loop, single-flight
  // (a flush requested while one runs coalesces into one more pass). fsync the partial
  // BEFORE the journal references it so a power-loss can never leave the journal
  // marking a chunk received whose bytes aren't durable.
  _flushJournal (state) {
    if (!state.contentHash || !state.journalPath || state.fd == null) return
    if (state.flushing) { state.flushPending = true; return }
    if (Date.now() - state.lastFlush < JOURNAL_FLUSH_INTERVAL_MS) return
    state.flushing = true
    this._drainFlush(state)
  }

  async _drainFlush (state) {
    do {
      state.flushPending = false
      state.lastFlush = Date.now()
      if (state.fd == null) break
      let buf
      try { buf = this._encodeJournal(state) } catch { break }
      const tmp = state.journalPath + '.tmp'
      try {
        // fsync is best-effort and swallowed on purpose: on Windows, fsync
        // (FlushFileBuffers) on a read-only handle throws EPERM benignly, and we still
        // want the journal to persist so resume stays O(1). The EIO write-back hazard
        // this could mask is already closed upstream — F1 refuses to trust a journal
        // without a contentHash, and the finalize whole-file hash re-verifies the
        // gated flow — so skipping the commit here (former "F3") only regressed Windows.
        try { await fs.fsync(state.fd) } catch {}
        await fs.writeFile(tmp, buf)
        if (state.fd == null) break // paused/cancelled mid-flush — don't re-create the journal
        await fs.rename(tmp, state.journalPath)
      } catch { try { await fs.unlink(tmp) } catch {} }
    } while (state.flushPending && state.fd != null && state.contentHash)
    try { await fs.unlink(state.journalPath + '.tmp') } catch {}
    state.flushing = false
  }

  // Synchronous durable flush for pause/shutdown, where the app may quit before an
  // async flush would land.
  _flushJournalSync (state) {
    if (!state.contentHash || !state.journalPath) return
    let buf
    try { buf = this._encodeJournal(state) } catch { return }
    // fsync swallowed on purpose (Windows read-only-handle EPERM) — see _drainFlush.
    if (state.fd != null) { try { fs.fsyncSync(state.fd) } catch {} }
    try {
      const tmp = state.journalPath + '.tmp'
      fs.writeFileSync(tmp, buf)
      fs.renameSync(tmp, state.journalPath)
      state.lastFlush = Date.now()
    } catch { try { fs.unlinkSync(state.journalPath + '.tmp') } catch {} }
  }

  cleanJournals (maxAge) { return cleanupOrphanedJournals(this._journalDir, maxAge) }

  async _hashWholeFileAsync (filePath, size) {
    const h = createStreamingHasher({ size })
    for await (const buf of readFileBlocks(filePath, size, 8 * 1024 * 1024)) {
      h.update(buf)
      await yieldToLoop()
    }
    return h.digest()
  }

  // Advance the whole-file hash over the contiguous run of received chunks
  // as a single-flight BACKGROUND pump: chunk index order == file offset order, so
  // once chunk `hashFrontier` is present we feed its bytes and move on. The drain is
  // async + yielding so a large contiguous run that suddenly becomes available (a
  // gap filling after a low-frontier resume) cannot block the event loop.
  // Single-flight is `state.draining`, set/cleared SYNCHRONOUSLY inside _drainHash —
  // a stash-fed drain completes without awaiting, so a promise-based gate would stay
  // stale until its microtask clear and block same-macrotask restarts (protomux
  // delivers frame bursts synchronously). advancePromise is only the awaitable
  // handle for finalize/pause; its clear is guarded against nulling a newer drain.
  _advanceHash (state) {
    if (!state.hasher || state.draining) return
    if (!(state.hashFrontier < state.chunks.length && state.received.has(state.hashFrontier))) return
    const p = this._drainHash(state)
    state.advancePromise = p
    p.catch(() => {}).then(() => { if (state.advancePromise === p) state.advancePromise = null })
  }

  async _drainHash (state) {
    state.draining = true
    try {
      let sinceYield = 0
      while (state.fd != null && state.hashFrontier < state.chunks.length && state.received.has(state.hashFrontier)) {
        const i = state.hashFrontier
        const c = state.chunks[i]
        let buf = state.memChunks.get(i)
        if (buf !== undefined) {
          state.memChunks.delete(i)
          state.memBytes -= buf.length
          state.stats.stashHits++
        } else {
          buf = Buffer.alloc(c.length)
          try { await fs.read(state.fd, buf, 0, c.length, c.offset) } catch { return }
          state.stats.readbacks++
        }
        state.hasher.update(buf)
        state.hashFrontier++
        // Yield by BYTE volume: the stash path has no awaits, so a chunk-count
        // cadence would let a gap-fill hash the whole stash synchronously inside
        // the network event that delivered the gap chunk.
        sinceYield += buf.length
        if (sinceYield >= DRAIN_YIELD_BYTES) { sinceYield = 0; await yieldToLoop() }
      }
    } finally {
      state.draining = false
    }
  }

  // Close the persistent fd — MUST run before finalize's rename (an open handle
  // blocks the rename on Windows) — and drop the chunk stash.
  _closeFd (state) {
    if (state.fd != null) {
      try { fs.closeSync(state.fd) } catch {}
      state.fd = null
    }
    state.memChunks.clear()
    state.memBytes = 0
  }

  /**
   * Write a received chunk to the partial file. Verifies the hash.
   *
   * @param {string} targetPath - the final file path (used as key)
   * @param {number} index - chunk index
   * @param {Buffer} data - raw chunk bytes
   * @returns {{ ok: boolean, error?: string }}
   */
  writeChunk (targetPath, index, data) {
    const state = this._active.get(targetPath)
    if (!state) return { ok: false, error: 'no active transfer' }
    if (index < 0 || index >= state.chunks.length) return { ok: false, error: 'index out of range' }
    // Terminal race (chunk landed after close) — codeless so the scheduler
    // re-assigns instead of failing the fetch.
    if (state.fd == null) return { ok: false, error: 'transfer closed' }

    const expected = state.chunks[index]

    // Verify hash
    const actual = hashChunk(data)
    if (actual !== expected.hash) {
      return { ok: false, error: `hash mismatch at index ${index}: expected ${expected.hash.slice(0, 16)}... got ${actual.slice(0, 16)}...` }
    }

    // Verify length
    if (data.length !== expected.length) {
      return { ok: false, error: `length mismatch at index ${index}: expected ${expected.length} got ${data.length}` }
    }

    // Write to partial at the chunk's offset through the persistent fd. A local
    // I/O failure here (ENOSPC / EACCES / EROFS) is fatal and non-retryable —
    // return its code so the scheduler fails the fetch instead of looping over
    // other peers. Loop on a SHORT count: libuv swallows an error after partial
    // progress and returns short without throwing; retrying the remainder
    // surfaces the real coded error instead of leaving a silent hole the
    // stash-fed digest would never see.
    try {
      let written = 0
      while (written < data.length) {
        const n = fs.writeSync(state.fd, data, written, data.length - written, expected.offset + written)
        if (!(n > 0)) { const e = new Error(`short write at index ${index}: ${written}/${data.length} bytes`); e.code = 'EIO'; throw e }
        written += n
      }
    } catch (err) {
      return { ok: false, error: err.message, code: err.code }
    }

    state.received.add(index)
    state.bitmap[index >> 3] |= 1 << (index & 7)
    // Stash only what the pump can consume cleanly: skip when already hashed or
    // stashed, when the pump is mid-drain on exactly this index, or over cap.
    // Copied, not aliased — wire buffers are views into shared network slabs (udx
    // read slab, decrypted in place by secret-stream), so retaining `data` would
    // pin whole slabs and bet the digest on their write-once behavior.
    if (state.hasher && !state.memChunks.has(index) && state.memBytes + data.length <= this._memStashBytes &&
        (index > state.hashFrontier || (index === state.hashFrontier && !state.draining))) {
      state.memChunks.set(index, Buffer.from(data))
      state.memBytes += data.length
    }
    this._advanceHash(state)
    if (++state.sinceFlush >= JOURNAL_FLUSH_EVERY) { state.sinceFlush = 0; this._flushJournal(state) }

    return { ok: true }
  }

  /**
   * Check if a transfer is complete (all chunks received).
   *
   * @param {string} targetPath
   * @returns {boolean}
   */
  isComplete (targetPath) {
    const state = this._active.get(targetPath)
    if (!state) return false
    return state.received.size === state.total
  }

  /**
   * Finalize a completed transfer — atomic rename from partial to target.
   *
   * @param {string} targetPath
   * @returns {{ ok: boolean, error?: string }}
   */
  async finalize (targetPath) {
    const state = this._active.get(targetPath)
    if (!state) return { ok: false, error: 'no active transfer' }
    if (state.received.size !== state.total) {
      return { ok: false, error: `incomplete: ${state.received.size}/${state.total} chunks` }
    }

    // whole-file integrity — computed incrementally by the background hash
    // pump during the transfer. Kick the pump and await it to quiescence, then read
    // the digest (no full re-read). On a mismatch, drop the corrupt partial so a
    // retry starts clean.
    if (state.hasher) {
      this._advanceHash(state)
      while (state.advancePromise) { try { await state.advancePromise } catch {} }
    }
    if (state.contentHash) {
      const actual = state.hashFrontier === state.chunks.length ? state.hasher.digest() : null
      if (actual !== state.contentHash) {
        this._closeFd(state)
        try { fs.unlinkSync(state.partialPath) } catch {}
        if (state.journalPath) { try { fs.unlinkSync(state.journalPath) } catch {} }
        this._active.delete(targetPath)
        return { ok: false, error: 'content-hash mismatch', code: 'EHASHMISMATCH' }
      }
    }
    this._closeFd(state)

    try {
      fs.renameSync(state.partialPath, state.targetPath)
    } catch (err) {
      // Carry the code (routes through the coded local-I/O rethrow) and clear the
      // state — the partial + journal stay for a clean resume-retry.
      this._active.delete(targetPath)
      return { ok: false, error: 'rename failed: ' + err.message, code: err.code }
    }

    if (state.journalPath) { try { fs.unlinkSync(state.journalPath) } catch {} }
    this._active.delete(targetPath)
    return { ok: true }
  }

  // Stop receiving but KEEP the partial on disk so a later startReceive
  // verifies and resumes it. Distinct from cancel(), which unlinks the partial.
  // Drains the in-flight hash advance to the full contiguous frontier first, so the
  // journal captures it and resume stays O(1) (no re-read) and deterministic.
  async pause (targetPath) {
    const state = this._active.get(targetPath)
    if (!state) return
    if (state.hasher) {
      this._advanceHash(state)
      while (state.advancePromise) { try { await state.advancePromise } catch {} }
    }
    this._flushJournalSync(state)
    this._closeFd(state)
    this._active.delete(targetPath)
  }

  /**
   * Cancel an active transfer and clean up the partial file.
   *
   * @param {string} targetPath
   */
  cancel (targetPath) {
    const state = this._active.get(targetPath)
    if (!state) return

    this._closeFd(state)
    try {
      fs.unlinkSync(state.partialPath)
    } catch {
      // partial file may not exist
    }
    if (state.journalPath) { try { fs.unlinkSync(state.journalPath) } catch {} }

    this._active.delete(targetPath)
  }

  /**
   * Get transfer progress for an active transfer.
   *
   * @param {string} targetPath
   * @returns {{ received: number, total: number, percentage: number } | null}
   */
  getProgress (targetPath) {
    const state = this._active.get(targetPath)
    if (!state) return null

    return {
      received: state.received.size,
      total: state.total,
      percentage: state.total > 0 ? Math.round(state.received.size / state.total * 100) : 0
    }
  }

  /**
   * List all active transfers.
   *
   * @returns {Array<{ path: string, received: number, total: number, percentage: number }>}
   */
  listActive () {
    const result = []
    for (const [targetPath, state] of this._active) {
      result.push({
        path: targetPath,
        received: state.received.size,
        total: state.total,
        percentage: state.total > 0 ? Math.round(state.received.size / state.total * 100) : 0
      })
    }
    return result
  }

  /**
   * Clean up stale partial files in a directory (older than maxAge).
   *
   * @param {string} dir - directory to scan
   * @param {number} [maxAge=86400000] - max age in ms (default 24h)
   * @returns {string[]} paths of cleaned files
   */
  cleanPartials (dir, maxAge = 86400000) {
    const cleaned = []
    try {
      const entries = fs.readdirSync(dir)
      const now = Date.now()
      for (const entry of entries) {
        if (!entry.endsWith(PARTIAL_SUFFIX)) continue
        const full = path.join(dir, entry)
        try {
          const stat = fs.statSync(full)
          if (now - stat.mtimeMs > maxAge) {
            fs.unlinkSync(full)
            cleaned.push(full)
          }
        } catch {
          // skip unreadable files
        }
      }
    } catch {
      // directory may not exist
    }
    return cleaned
  }
}
/**
 * Tree — content-addressable directory hashing for hyper-overlay
 *
 * A tree is a canonical serialization of a directory's immediate entries.
 * Each entry is one of: file, subdirectory, symlink. The tree's identity
 * is blake2b-256 of its canonical bytes.
 *
 * Format (P.10 Phase 0.5a):
 *
 *   tree := "pgh-tree-1\n" ||
 *           varint(n_entries) ||
 *           entry[0] || ... || entry[n-1]
 *
 *   entry := u8(kind)  ||           // 0=file, 1=dir, 2=symlink
 *            u8(exec)  ||           // 0 or 1; always 0 for dir/symlink
 *            varint(name_len) || name ||  // UTF-8 NFC, no NUL, no "/"
 *            32_bytes(child_hash)
 *
 *   tree_hash := blake2b-256(tree_bytes)
 *
 * Identity fields (in the hash): kind, exec-bit, name, child_hash.
 * Explicitly excluded: mtime, size, uid/gid, full mode.
 *
 * Entries MUST be sorted byte-wise by name (after NFC normalization).
 * Encoders emit sorted; decoders reject unsorted trees.
 *
 * Symlinks: child_hash = blake2b-256 of the target path bytes (not followed).
 * Empty directories: zero-entry tree, valid, deterministic.
 */

import fs from '#fs'
import path from '#path'
import crypto from 'hypercore-crypto'
import c from 'compact-encoding'

// ── Constants ─────────────────────────────────────────────────

export const MAGIC = Buffer.from('pgh-tree-1\n', 'utf8')
export const KIND_FILE = 0
export const KIND_DIR = 1
export const KIND_SYMLINK = 2

// Windows reserved device names (case-insensitive, with or without extension)
const WINDOWS_RESERVED = new Set([
  'CON', 'PRN', 'AUX', 'NUL',
  'COM1', 'COM2', 'COM3', 'COM4', 'COM5', 'COM6', 'COM7', 'COM8', 'COM9',
  'LPT1', 'LPT2', 'LPT3', 'LPT4', 'LPT5', 'LPT6', 'LPT7', 'LPT8', 'LPT9'
])

// Chars forbidden in filenames on Windows (beyond format-layer rules)
// eslint-disable-next-line no-control-regex
const WINDOWS_FORBIDDEN = /[\\:*?"<>|\x00-\x1f]/

// Default skip list for walkTree — minimal, just obvious platform cruft.
// Consumers that want more (e.g. .git for pgh publish) pass their own.
export const DEFAULT_SKIP = new Set(['.DS_Store', 'Thumbs.db'])

// ── Name validation (format layer) ────────────────────────────

/**
 * Normalize a filename for hashing and validate format-layer rules.
 * Throws on unrepresentable names. Returns the canonical form.
 *
 * @param {string} name - single path component (no "/")
 * @returns {string} NFC-normalized name
 */
export function normalizeName (name) {
  if (typeof name !== 'string') {
    throw new Error('tree entry name must be string, got ' + typeof name)
  }
  if (name.length === 0) {
    throw new Error('tree entry name cannot be empty')
  }
  if (name === '.' || name === '..') {
    throw new Error('tree entry name cannot be "." or ".."')
  }
  if (name.indexOf('/') !== -1) {
    throw new Error('tree entry name cannot contain "/": ' + JSON.stringify(name))
  }
  if (name.indexOf('\x00') !== -1) {
    throw new Error('tree entry name cannot contain NUL: ' + JSON.stringify(name))
  }

  const normalized = name.normalize('NFC')

  // Verify the normalized form is valid UTF-8 that round-trips through
  // Buffer (catches lone surrogates and other malformed sequences).
  const asBytes = Buffer.from(normalized, 'utf8')
  if (asBytes.toString('utf8') !== normalized) {
    throw new Error('tree entry name is not valid UTF-8: ' + JSON.stringify(name))
  }

  return normalized
}

// ── Consumer-policy layer ─────────────────────────────────────

/**
 * Check a name against Windows compatibility rules.
 * Does NOT throw — returns a reason string (or null if the name is OK).
 * Used by pgh publish for strict cross-platform validation.
 *
 * @param {string} name
 * @returns {string|null} reason if incompatible, null if OK
 */
export function windowsIncompatibleReason (name) {
  if (WINDOWS_FORBIDDEN.test(name)) {
    return 'contains Windows-forbidden character (\\:*?"<>| or control code)'
  }
  const trimmed = name.replace(/\.+$/, '').replace(/ +$/, '')
  if (trimmed !== name) {
    return 'trailing "." or space (Windows strips these silently)'
  }
  // Reserved device names apply with any extension: AUX.log, PRN.txt etc.
  const base = name.split('.')[0].toUpperCase()
  if (WINDOWS_RESERVED.has(base)) {
    return `"${base}" is a reserved Windows device name (even with extension)`
  }
  return null
}

// ── Canonical encoding ────────────────────────────────────────

/**
 * Encode a single entry to its canonical byte representation.
 *
 * @param {object} state - compact-encoding state
 * @param {{kind: number, exec: number, name: string, childHash: Buffer|string}} e
 */
function encodeEntry (state, e) {
  if (e.kind !== KIND_FILE && e.kind !== KIND_DIR && e.kind !== KIND_SYMLINK) {
    throw new Error('invalid entry kind: ' + e.kind)
  }
  if (e.exec !== 0 && e.exec !== 1) {
    throw new Error('entry exec must be 0 or 1')
  }
  if (e.kind !== KIND_FILE && e.exec !== 0) {
    throw new Error('non-file entry must have exec=0')
  }

  const hash = toBuffer32(e.childHash)

  c.uint8.encode(state, e.kind)
  c.uint8.encode(state, e.exec)
  c.string.encode(state, e.name) // compact-encoding: varint len + utf8 bytes
  state.buffer.set(hash, state.start)
  state.start += 32
}

function preencodeEntry (state, e) {
  c.uint8.preencode(state, e.kind)
  c.uint8.preencode(state, e.exec)
  c.string.preencode(state, e.name)
  state.end += 32
}

/**
 * Serialize a list of entries to canonical tree bytes.
 * Entries are sorted + normalized as a side-effect of the call.
 *
 * @param {Array<{kind: number, exec: number, name: string, childHash: Buffer|string}>} entries
 * @returns {Buffer}
 */
export function encodeTree (entries) {
  const normalized = entries.map(e => ({
    kind: e.kind,
    exec: e.exec || 0,
    name: normalizeName(e.name),
    childHash: e.childHash
  }))
  normalized.sort(compareEntries)

  // Sanity: no duplicate names after normalization
  for (let i = 1; i < normalized.length; i++) {
    if (normalized[i].name === normalized[i - 1].name) {
      throw new Error('duplicate entry name after NFC normalization: ' + normalized[i].name)
    }
  }

  const state = { start: 0, end: 0, buffer: null }
  state.end += MAGIC.length
  c.uint.preencode(state, normalized.length)
  for (const e of normalized) preencodeEntry(state, e)

  state.buffer = Buffer.alloc(state.end)

  state.buffer.set(MAGIC, state.start)
  state.start += MAGIC.length
  c.uint.encode(state, normalized.length)
  for (const e of normalized) encodeEntry(state, e)

  return state.buffer
}

/**
 * Byte-wise comparator for entry names (after NFC normalization).
 */
function compareEntries (a, b) {
  const ab = Buffer.from(a.name, 'utf8')
  const bb = Buffer.from(b.name, 'utf8')
  return Buffer.compare(ab, bb)
}

/**
 * Decode canonical tree bytes back to an entries list.
 * Rejects unsorted or malformed trees.
 *
 * @param {Buffer} buf
 * @returns {Array<{kind: number, exec: number, name: string, childHash: string}>}
 */
export function decodeTree (buf) {
  if (!Buffer.isBuffer(buf)) throw new Error('decodeTree expects a Buffer')
  if (buf.length < MAGIC.length) throw new Error('tree too short')
  if (buf.compare(MAGIC, 0, MAGIC.length, 0, MAGIC.length) !== 0) {
    throw new Error('tree magic mismatch (expected "pgh-tree-1")')
  }

  const state = { start: MAGIC.length, end: buf.length, buffer: buf }
  const count = c.uint.decode(state)
  const entries = []

  let prevName = null
  for (let i = 0; i < count; i++) {
    const kind = c.uint8.decode(state)
    const exec = c.uint8.decode(state)
    const name = c.string.decode(state)

    if (state.start + 32 > state.end) throw new Error('truncated tree: missing hash bytes')
    const childHash = buf.subarray(state.start, state.start + 32).toString('hex')
    state.start += 32

    // Validate format rules on read — reject invalid trees rather than silently accept
    const normalized = normalizeName(name)
    if (normalized !== name) {
      throw new Error('tree entry name not NFC-normalized: ' + JSON.stringify(name))
    }
    if (kind !== KIND_FILE && exec !== 0) {
      throw new Error('non-file entry with exec=1 is invalid')
    }
    if (prevName !== null) {
      const cmp = Buffer.compare(Buffer.from(prevName, 'utf8'), Buffer.from(name, 'utf8'))
      if (cmp === 0) throw new Error('tree has duplicate entry: ' + name)
      if (cmp > 0) throw new Error('tree entries not sorted: ' + prevName + ' before ' + name)
    }
    prevName = name

    entries.push({ kind, exec, name, childHash })
  }

  if (state.start !== state.end) throw new Error('tree has trailing bytes after entries')

  return entries
}

/**
 * Compute the tree hash of an entries list.
 *
 * @param {Array<{kind: number, exec: number, name: string, childHash: Buffer|string}>} entries
 * @returns {string} hex-encoded blake2b-256
 */
export function computeTreeHash (entries) {
  const buf = encodeTree(entries)
  return crypto.data(buf).toString('hex')
}

// ── Helpers ───────────────────────────────────────────────────

function toBuffer32 (hashOrBuf) {
  if (Buffer.isBuffer(hashOrBuf)) {
    if (hashOrBuf.length !== 32) throw new Error('childHash buffer must be 32 bytes')
    return hashOrBuf
  }
  if (typeof hashOrBuf !== 'string') {
    throw new Error('childHash must be Buffer or hex string')
  }
  if (hashOrBuf.length !== 64) throw new Error('childHash hex string must be 64 chars')
  return Buffer.from(hashOrBuf, 'hex')
}

// ── Filesystem walk ───────────────────────────────────────────

/**
 * Walk a directory recursively, producing tree hashes bottom-up.
 *
 * Returns a nested object keyed by path, where each entry has:
 *   { hash: hex, entries: [{kind, exec, name, childHash, size?}] }
 *
 * File entries carry their content hash as childHash (blake2b of bytes).
 * Dir entries carry the subtree hash.
 * Symlink entries carry blake2b of the link target bytes.
 *
 * @param {string} rootDir - absolute path to scan
 * @param {object} [opts]
 * @param {Set<string>} [opts.skip] - basenames to skip (default: DEFAULT_SKIP)
 * @param {(relPath: string, baseName: string) => boolean} [opts.matcher]
 *   Optional gitignore-style matcher. Returns true to EXCLUDE an entry.
 *   Receives the path relative to rootDir plus the basename. Applies to
 *   all kinds (file/dir/symlink). Used by `pgh publish` for publishIgnore.
 * @returns {Map<string, {hash: string, entries: Array, size: number}>}
 *          map keyed by relative path ('' = root); root tree is at key ''
 */
export function walkTree (rootDir, opts = {}) {
  const skip = opts.skip || DEFAULT_SKIP
  const matcher = opts.matcher || null
  const trees = new Map()

  function visit (relPath) {
    const absPath = relPath === '' ? rootDir : path.join(rootDir, relPath)
    const raw = fs.readdirSync(absPath)
    const entries = []
    let totalSize = 0

    for (const name of raw) {
      if (skip.has(name)) continue

      const entryAbs = path.join(absPath, name)
      const entryRel = relPath === '' ? name : relPath + '/' + name

      if (matcher && matcher(entryRel, name)) continue

      let stat
      try {
        stat = fs.lstatSync(entryAbs)
      } catch {
        continue
      }

      if (stat.isSymbolicLink()) {
        const target = fs.readlinkSync(entryAbs)
        const targetBytes = Buffer.from(target, 'utf8')
        const childHash = crypto.data(targetBytes).toString('hex')
        entries.push({
          kind: KIND_SYMLINK,
          exec: 0,
          name: normalizeName(name),
          childHash,
          size: targetBytes.length,
          linkTarget: target
        })
        totalSize += targetBytes.length
      } else if (stat.isDirectory()) {
        visit(entryRel)
        const sub = trees.get(entryRel)
        if (!sub) continue
        entries.push({
          kind: KIND_DIR,
          exec: 0,
          name: normalizeName(name),
          childHash: sub.hash,
          size: sub.size
        })
        totalSize += sub.size
      } else if (stat.isFile()) {
        const content = fs.readFileSync(entryAbs)
        const childHash = crypto.data(content).toString('hex')
        // Executable bit from stat.mode — works on POSIX; Windows always 0
        const exec = (stat.mode & 0o100) ? 1 : 0
        entries.push({
          kind: KIND_FILE,
          exec,
          name: normalizeName(name),
          childHash,
          size: stat.size
        })
        totalSize += stat.size
      }
      // device files, sockets, fifos: silently skipped (unrepresentable)
    }

    entries.sort(compareEntries)
    const hash = computeTreeHash(entries)
    trees.set(relPath, { hash, entries, size: totalSize })
  }

  visit('')
  return trees
}

// ── Publish-time validation (consumer policy) ─────────────────

/**
 * Scan entries (recursively via walkTree output) for cross-platform-hostile
 * names. Returns an array of {path, name, reason} for every problem found.
 * Does NOT throw — caller decides how to present.
 *
 * @param {Map<string, {hash: string, entries: Array}>} trees - from walkTree
 * @returns {Array<{path: string, name: string, reason: string}>}
 */
export function validateForPublish (trees) {
  const problems = []
  for (const [relPath, tree] of trees) {
    for (const e of tree.entries) {
      const reason = windowsIncompatibleReason(e.name)
      if (reason) {
        problems.push({
          path: relPath ? relPath + '/' + e.name : e.name,
          name: e.name,
          reason
        })
      }
    }
  }
  return problems
}
function isBuffer(value) {
  return Buffer.isBuffer(value) || value instanceof Uint8Array
}

function isEncoding(encoding) {
  return Buffer.isEncoding(encoding)
}

function alloc(size, fill, encoding) {
  return Buffer.alloc(size, fill, encoding)
}

function allocUnsafe(size) {
  return Buffer.allocUnsafe(size)
}

function allocUnsafeSlow(size) {
  return Buffer.allocUnsafeSlow(size)
}

function byteLength(string, encoding) {
  return Buffer.byteLength(string, encoding)
}

function compare(a, b) {
  return Buffer.compare(a, b)
}

function concat(buffers, totalLength) {
  return Buffer.concat(buffers, totalLength)
}

function copy(source, target, targetStart, start, end) {
  return toBuffer(source).copy(target, targetStart, start, end)
}

function equals(a, b) {
  return toBuffer(a).equals(b)
}

function fill(buffer, value, offset, end, encoding) {
  return toBuffer(buffer).fill(value, offset, end, encoding)
}

function from(value, encodingOrOffset, length) {
  return Buffer.from(value, encodingOrOffset, length)
}

function includes(buffer, value, byteOffset, encoding) {
  return toBuffer(buffer).includes(value, byteOffset, encoding)
}

function indexOf(buffer, value, byfeOffset, encoding) {
  return toBuffer(buffer).indexOf(value, byfeOffset, encoding)
}

function lastIndexOf(buffer, value, byteOffset, encoding) {
  return toBuffer(buffer).lastIndexOf(value, byteOffset, encoding)
}

function swap16(buffer) {
  return toBuffer(buffer).swap16()
}

function swap32(buffer) {
  return toBuffer(buffer).swap32()
}

function swap64(buffer) {
  return toBuffer(buffer).swap64()
}

function toBuffer(buffer) {
  if (Buffer.isBuffer(buffer)) return buffer
  return Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

function toString(buffer, encoding, start, end) {
  return toBuffer(buffer).toString(encoding, start, end)
}

function write(buffer, string, offset, length, encoding) {
  return toBuffer(buffer).write(string, offset, length, encoding)
}

function readDoubleBE(buffer, offset) {
  return toBuffer(buffer).readDoubleBE(offset)
}

function readDoubleLE(buffer, offset) {
  return toBuffer(buffer).readDoubleLE(offset)
}

function readFloatBE(buffer, offset) {
  return toBuffer(buffer).readFloatBE(offset)
}

function readFloatLE(buffer, offset) {
  return toBuffer(buffer).readFloatLE(offset)
}

function readInt32BE(buffer, offset) {
  return toBuffer(buffer).readInt32BE(offset)
}

function readInt32LE(buffer, offset) {
  return toBuffer(buffer).readInt32LE(offset)
}

function readUInt32BE(buffer, offset) {
  return toBuffer(buffer).readUInt32BE(offset)
}

function readUInt32LE(buffer, offset) {
  return toBuffer(buffer).readUInt32LE(offset)
}

function writeDoubleBE(buffer, value, offset) {
  return toBuffer(buffer).writeDoubleBE(value, offset)
}

function writeDoubleLE(buffer, value, offset) {
  return toBuffer(buffer).writeDoubleLE(value, offset)
}

function writeFloatBE(buffer, value, offset) {
  return toBuffer(buffer).writeFloatBE(value, offset)
}

function writeFloatLE(buffer, value, offset) {
  return toBuffer(buffer).writeFloatLE(value, offset)
}

function writeInt32BE(buffer, value, offset) {
  return toBuffer(buffer).writeInt32BE(value, offset)
}

function writeInt32LE(buffer, value, offset) {
  return toBuffer(buffer).writeInt32LE(value, offset)
}

function writeUInt32BE(buffer, value, offset) {
  return toBuffer(buffer).writeUInt32BE(value, offset)
}

function writeUInt32LE(buffer, value, offset) {
  return toBuffer(buffer).writeUInt32LE(value, offset)
}

module.exports = {
  isBuffer,
  isEncoding,
  alloc,
  allocUnsafe,
  allocUnsafeSlow,
  byteLength,
  compare,
  concat,
  copy,
  equals,
  fill,
  from,
  includes,
  indexOf,
  lastIndexOf,
  swap16,
  swap32,
  swap64,
  toBuffer,
  toString,
  write,
  readDoubleBE,
  readDoubleLE,
  readFloatBE,
  readFloatLE,
  readInt32BE,
  readInt32LE,
  readUInt32BE,
  readUInt32LE,
  writeDoubleBE,
  writeDoubleLE,
  writeFloatBE,
  writeFloatLE,
  writeInt32BE,
  writeInt32LE,
  writeUInt32BE,
  writeUInt32LE
}
{
  "name": "b4a",
  "version": "1.8.1",
  "description": "Bridging the gap between buffers and typed arrays",
  "exports": {
    "./package": "./package.json",
    ".": {
      "react-native": "./react-native.js",
      "browser": "./browser.js",
      "default": "./index.js"
    }
  },
  "files": [
    "browser.js",
    "index.js",
    "react-native.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:bare && npm run test:node",
    "test:bare": "brittle-bare --coverage test.mjs",
    "test:node": "brittle-node --coverage test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/b4a.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/b4a/issues"
  },
  "homepage": "https://github.com/holepunchto/b4a#readme",
  "devDependencies": {
    "brittle": "^3.5.2",
    "lunte": "^1.7.0",
    "nanobench": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "react-native-b4a": "*"
  },
  "peerDependenciesMeta": {
    "react-native-b4a": {
      "optional": true
    }
  }
}
const ESC = '\x1b'
const CSI = ESC + '['
const SGR = (n) => CSI + n + 'm'

exports.constants = {
  ESC,
  CSI,
  SGR
}

// https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_(Control_Sequence_Introducer)_sequences

exports.cursorHide = CSI + '?25l'
exports.cursorShow = CSI + '?25h'

exports.cursorUp = function cursorUp(n = 1) {
  return CSI + n + 'A'
}

exports.cursorDown = function cursorDown(n = 1) {
  return CSI + n + 'B'
}

exports.cursorForward = function cursorForward(n = 1) {
  return CSI + n + 'C'
}

exports.cursorBack = function cursorBack(n = 1) {
  return CSI + n + 'D'
}

exports.cursorNextLine = function cursorNextLine(n = 1) {
  return CSI + n + 'E'
}

exports.cursorPreviousLine = function cursorPreviousLine(n = 1) {
  return CSI + n + 'F'
}

exports.cursorPosition = function cursorPosition(column, row = 0) {
  if (row === 0) return CSI + (column + 1) + 'G'

  return CSI + (row + 1) + ';' + (column + 1) + 'H'
}

exports.eraseDisplayEnd = CSI + 'J'
exports.eraseDisplayStart = CSI + '1J'
exports.eraseDisplay = CSI + '2J'
exports.eraseLineEnd = CSI + 'K'
exports.eraseLineStart = CSI + '1K'
exports.eraseLine = CSI + '2K'

exports.scrollUp = function scrollUp(n = 1) {
  return CSI + n + 'S'
}

exports.scrollDown = function scrollDown(n = 1) {
  return CSI + n + 'T'
}

// https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_(Select_Graphic_Rendition)_parameters

exports.modifierReset = SGR(0)
exports.modifierBold = SGR(1)
exports.modifierDim = SGR(2)
exports.modifierItalic = SGR(3)
exports.modifierUnderline = SGR(4)
exports.modifierNormal = SGR(22)
exports.modifierNotItalic = SGR(23)
exports.modifierNotUnderline = SGR(24)

// https://en.wikipedia.org/wiki/ANSI_escape_code#Colors

exports.colorBlack = SGR(30)
exports.colorRed = SGR(31)
exports.colorGreen = SGR(32)
exports.colorYellow = SGR(33)
exports.colorBlue = SGR(34)
exports.colorMagenta = SGR(35)
exports.colorCyan = SGR(36)
exports.colorWhite = SGR(37)
exports.colorDefault = SGR(39)
exports.colorBrightBlack = SGR(90)
exports.colorBrightRed = SGR(91)
exports.colorBrightGreen = SGR(92)
exports.colorBrightYellow = SGR(93)
exports.colorBrightBlue = SGR(94)
exports.colorBrightMagenta = SGR(95)
exports.colorBrightCyan = SGR(96)
exports.colorBrightWhite = SGR(97)
{
  "name": "bare-ansi-escapes",
  "version": "2.2.3",
  "description": "Parse and produce ANSI escape sequences",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./key-decoder": {
      "types": "./key-decoder.d.ts",
      "default": "./key-decoder.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "key-decoder.js",
    "key-decoder.d.ts"
  ],
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-ansi-escapes.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-ansi-escapes/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-ansi-escapes#readme",
  "dependencies": {
    "bare-stream": "^2.6.5"
  },
  "devDependencies": {
    "bare-buffer": "^3.0.2",
    "brittle": "^3.3.2",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  },
  "peerDependencies": {
    "bare-buffer": "*"
  },
  "peerDependenciesMeta": {
    "bare-buffer": {
      "optional": true
    }
  }
}
const inspect = require('bare-inspect')

class AssertionError extends Error {
  constructor(opts = {}) {
    let { message = null, actual, expected, operator } = opts

    if (message === null) {
      message = `${inspect(actual)} ${operator} ${inspect(expected)}`
    }

    super(message)

    this.actual = actual
    this.expected = expected
    this.operator = operator
  }

  get name() {
    return 'AssertionError'
  }

  get code() {
    'ASSERTION'
  }
}

function assertFail(opts, fn) {
  if (opts.message instanceof Error) throw opts.message

  const err = new AssertionError(opts)

  if (Error.captureStackTrace) Error.captureStackTrace(err, fn)

  throw err
}

module.exports = exports = function assert(actual, message) {
  if (actual) return

  assertFail({ message, actual, expected: true, operator: '==' }, assert)
}

exports.AssertionError = AssertionError

exports.fail = function fail(message) {
  if (message === undefined) message = 'Failed'

  assertFail({ message, operator: 'fail' }, fail)
}

exports.ok = function ok(actual, message) {
  if (actual) return

  assertFail({ message, actual, expected: true, operator: '==' }, ok)
}

exports.notOk = function ok(actual, message) {
  if (!actual) return

  assertFail({ message, actual, expected: false, operator: '==' }, ok)
}

exports.equal = function equal(actual, expected, message) {
  if (actual == expected || (actual !== actual && expected !== expected)) {
    return
  }

  assertFail({ message, actual, expected, operator: '==' }, equal)
}

exports.notEqual = function notEqual(actual, expected, message) {
  if (actual != expected && (actual === actual || expected === expected)) {
    return
  }

  assertFail({ message, actual, expected, operator: '!=' }, notEqual)
}

exports.strictEqual = function strictEqual(actual, expected, message) {
  if (Object.is(actual, expected)) return

  assertFail(
    { message, actual, expected, operator: 'strictEqual' },
    strictEqual
  )
}

exports.notStrictEqual = function notStrictEqual(actual, expected, message) {
  if (!Object.is(actual, expected)) return

  assertFail(
    { message, actual, expected, operator: 'notStrictEqual' },
    notStrictEqual
  )
}
{
  "name": "bare-assert",
  "version": "1.2.0",
  "description": "Assertion library for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts"
  ],
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-assert.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-assert/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-assert#readme",
  "dependencies": {
    "bare-inspect": "^3.1.2"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  }
}
const errors = require('./lib/errors')

class EventListener {
  constructor() {
    this.list = []
    this.count = 0
  }

  append(ctx, name, fn, once) {
    this.count++
    ctx.emit('newListener', name, fn) // Emit BEFORE adding
    this.list.push([fn, once])
  }

  prepend(ctx, name, fn, once) {
    this.count++
    ctx.emit('newListener', name, fn) // Emit BEFORE adding
    this.list.unshift([fn, once])
  }

  remove(ctx, name, fn) {
    for (let i = 0, n = this.list.length; i < n; i++) {
      const l = this.list[i]

      if (l[0] === fn) {
        this.list.splice(i, 1)

        if (this.count === 1) delete ctx._events[name]

        ctx.emit('removeListener', name, fn) // Emit AFTER removing

        this.count--
        return
      }
    }
  }

  removeAll(ctx, name) {
    const list = [...this.list]
    this.list = []

    if (this.count === list.length) delete ctx._events[name]

    for (let i = list.length - 1; i >= 0; i--) {
      ctx.emit('removeListener', name, list[i][0]) // Emit AFTER removing
    }

    this.count -= list.length
  }

  emit(ctx, name, ...args) {
    const list = [...this.list]

    for (let i = 0, n = list.length; i < n; i++) {
      const l = list[i]

      if (l[1] === true) this.remove(ctx, name, l[0])

      Reflect.apply(l[0], ctx, args)
    }

    return list.length > 0
  }
}

function appendListener(ctx, name, fn, once) {
  if (ctx._events === undefined) ctx._events = Object.create(null)
  const e = ctx._events[name] || (ctx._events[name] = new EventListener())
  e.append(ctx, name, fn, once)
  return ctx
}

function prependListener(ctx, name, fn, once) {
  if (ctx._events === undefined) ctx._events = Object.create(null)
  const e = ctx._events[name] || (ctx._events[name] = new EventListener())
  e.prepend(ctx, name, fn, once)
  return ctx
}

function removeListener(ctx, name, fn) {
  if (ctx._events === undefined) return ctx
  const e = ctx._events[name]
  if (e !== undefined) e.remove(ctx, name, fn)
  return ctx
}

function throwUnhandledError(...args) {
  let err

  if (args.length > 0) err = args[0]

  if (err instanceof Error === false) err = errors.UNHANDLED_ERROR(err)

  if (Error.captureStackTrace) {
    Error.captureStackTrace(err, exports.prototype.emit)
  }

  queueMicrotask(() => {
    throw err
  })
}

module.exports = exports = class EventEmitter {
  constructor() {
    this._events = Object.create(null)
  }

  addListener(name, fn) {
    return appendListener(this, name, fn, false)
  }

  addOnceListener(name, fn) {
    return appendListener(this, name, fn, true)
  }

  prependListener(name, fn) {
    return prependListener(this, name, fn, false)
  }

  prependOnceListener(name, fn) {
    return prependListener(this, name, fn, true)
  }

  removeListener(name, fn) {
    return removeListener(this, name, fn)
  }

  on(name, fn) {
    return appendListener(this, name, fn, false)
  }

  once(name, fn) {
    return appendListener(this, name, fn, true)
  }

  off(name, fn) {
    return removeListener(this, name, fn)
  }

  emit(name, ...args) {
    if (name === 'error' && this._events !== undefined && this._events.error === undefined) {
      throwUnhandledError(...args)
    }

    if (this._events === undefined) return false
    const e = this._events[name]
    return e === undefined ? false : e.emit(this, name, ...args)
  }

  listeners(name) {
    if (this._events === undefined) return []
    const e = this._events[name]
    return e === undefined ? [] : [...e.list]
  }

  rawListeners(name) {
    if (this._events === undefined) return []
    const e = this._events[name]
    return e === undefined ? [] : e.list.map((l) => l[0])
  }

  eventNames() {
    if (this._events === undefined) return []
    return Reflect.ownKeys(this._events)
  }

  listenerCount(name) {
    if (this._events === undefined) return 0
    const e = this._events[name]
    return e === undefined ? 0 : e.list.length
  }

  getMaxListeners() {
    return EventEmitter.defaultMaxListeners
  }

  setMaxListeners(n) {}

  removeAllListeners(name) {
    if (arguments.length === 0) {
      for (const key of Reflect.ownKeys(this._events)) {
        if (key === 'removeListener') continue
        this.removeAllListeners(key)
      }
      this.removeAllListeners('removeListener')
    } else {
      const e = this._events[name]
      if (e !== undefined) e.removeAll(this, name)
    }
    return this
  }
}

exports.EventEmitter = exports

exports.errors = errors

exports.defaultMaxListeners = 10

exports.on = function on(emitter, name, opts = {}) {
  const { signal } = opts

  if (signal && signal.aborted) {
    throw errors.OPERATION_ABORTED(signal.reason)
  }

  let error = null
  let done = false

  const events = []
  const promises = []

  if (name !== 'error') emitter.on('error', onerror)

  if (signal) signal.addEventListener('abort', onabort)

  emitter.on(name, onevent)

  return {
    next() {
      if (events.length) {
        return Promise.resolve({ value: events.shift(), done: false })
      }

      if (error) {
        const err = error

        error = null

        return Promise.reject(err)
      }

      if (done) return onclose()

      return new Promise((resolve, reject) => promises.push({ resolve, reject }))
    },

    return() {
      return onclose()
    },

    throw(err) {
      return onerror(err)
    },

    [Symbol.asyncIterator]() {
      return this
    }
  }

  function onevent(...args) {
    if (promises.length) {
      promises.shift().resolve({ value: args, done: false })
    } else {
      events.push(args)
    }
  }

  function onerror(err) {
    emitter.off(name, onevent).off('error', onerror)

    if (promises.length) {
      promises.shift().reject(err)
    } else {
      error = err
    }

    return Promise.resolve({ done: true })
  }

  function onabort() {
    signal.removeEventListener('abort', onabort)

    onerror(errors.OPERATION_ABORTED(signal.reason))
  }

  function onclose() {
    emitter.off(name, onevent)

    if (name !== 'error') emitter.off('error', onerror)

    if (signal) signal.removeEventListener('abort', onabort)

    done = true

    if (promises.length) promises.shift().resolve({ done: true })

    return Promise.resolve({ done: true })
  }
}

exports.once = function once(emitter, name, opts = {}) {
  const { signal } = opts

  if (signal && signal.aborted) {
    return Promise.reject(errors.OPERATION_ABORTED(signal.reason))
  }

  return new Promise((resolve, reject) => {
    if (name !== 'error') emitter.on('error', onerror)

    if (signal) signal.addEventListener('abort', onabort)

    emitter.once(name, onevent)

    function onevent(...args) {
      if (name !== 'error') emitter.off('error', onerror)

      if (signal) signal.removeEventListener('abort', onabort)

      resolve(args)
    }

    function onerror(err) {
      emitter.off(name, onevent)

      if (name !== 'error') emitter.off('error', onerror)

      reject(err)
    }

    function onabort() {
      signal.removeEventListener('abort', onabort)

      onerror(errors.OPERATION_ABORTED(signal.reason))
    }
  })
}

exports.forward = function forward(from, to, names, opts = {}) {
  if (typeof names === 'string') names = [names]

  const { emit = to.emit.bind(to) } = opts

  const listeners = names.map(
    (name) =>
      function onevent(...args) {
        emit(name, ...args)
      }
  )

  to.on('newListener', (name) => {
    const i = names.indexOf(name)

    if (i !== -1 && to.listenerCount(name) === 0) {
      from.on(name, listeners[i])
    }
  }).on('removeListener', (name) => {
    const i = names.indexOf(name)

    if (i !== -1 && to.listenerCount(name) === 0) {
      from.off(name, listeners[i])
    }
  })
}

exports.listenerCount = function listenerCount(emitter, name) {
  return emitter.listenerCount(name)
}

exports.getMaxListeners = function getMaxListeners(emitter) {
  if (typeof emitter.getMaxListeners === 'function') {
    return emitter.getMaxListeners()
  }

  return exports.defaultMaxListeners
}

exports.setMaxListeners = function setMaxListeners(n, ...emitters) {
  if (emitters.length === 0) exports.defaultMaxListeners = n
  else {
    for (const emitter of emitters) {
      if (typeof emitter.setMaxListeners === 'function') {
        emitter.setMaxListeners(n)
      }
    }
  }
}
module.exports = class EventEmitterError extends Error {
  constructor(msg, code, fn = EventEmitterError, opts) {
    super(`${code}: ${msg}`, opts)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'EventEmitterError'
  }

  static OPERATION_ABORTED(cause, msg = 'Operation aborted') {
    return new EventEmitterError(msg, 'OPERATION_ABORTED', EventEmitterError.OPERATION_ABORTED, {
      cause
    })
  }

  static UNHANDLED_ERROR(cause, msg = 'Unhandled error') {
    return new EventEmitterError(msg, 'UNHANDLED_ERROR', EventEmitterError.UNHANDLED_ERROR, {
      cause
    })
  }
}
{
  "name": "bare-events",
  "version": "2.9.1",
  "description": "Event emitters for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    },
    "./web": {
      "types": "./web.d.ts",
      "default": "./web.js"
    },
    "./errors": "./lib/errors.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "global.js",
    "global.d.ts",
    "web.js",
    "web.d.ts",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:bare && npm run test:node",
    "test:bare": "brittle-bare --coverage test.js",
    "test:node": "brittle-node --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-events.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-events/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-events#readme",
  "devDependencies": {
    "bare-abort-controller": "^1.0.0",
    "brittle": "^3.3.2",
    "lunte": "^1.8.0",
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^2.0.0",
    "uncaughts": "^1.1.1"
  },
  "peerDependencies": {
    "bare-abort-controller": "*"
  },
  "peerDependenciesMeta": {
    "bare-abort-controller": {
      "optional": true
    }
  }
}
module.exports = require.addon()
const FIFO = require('fast-fifo')
const EventEmitter = require('bare-events')
const path = require('bare-path')
const { isURL, fileURLToPath } = require('bare-url')
const { Readable, Writable } = require('bare-stream')
const binding = require('./binding')
const constants = require('./lib/constants')
const FileError = require('./lib/errors')

const isWindows = Bare.platform === 'win32'

exports.constants = constants

class FileRequest {
  static borrow() {
    if (this._free.length > 0) return this._free.pop()
    return new FileRequest()
  }

  static return(req) {
    if (this._free.length < 32) this._free.push(req.reset())
    else req.destroy()
  }

  constructor() {
    this._reset()
    this._handle = binding.requestInit(this, this._onresult)
  }

  get handle() {
    return this._handle
  }

  retain(value) {
    this._retain = value // Tie the lifetime of `value` to the lifetime of `this`
  }

  reset() {
    if (this._handle === null) return this

    binding.requestReset(this._handle)

    this._reset()

    return this
  }

  destroy() {
    if (this._handle === null) return this

    binding.requestDestroy(this._handle)

    this._reset()
    this._handle = null

    return this
  }

  then(resolve, reject) {
    return this._promise.then(resolve, reject)
  }

  return() {
    if (this._handle === null) return this

    FileRequest.return(this)

    return this
  }

  _reset() {
    this._promise = new Promise((resolve, reject) => {
      this._resolve = resolve
      this._reject = reject
    })
    this._retain = null
  }

  _onresult(err, status) {
    if (err) this._reject(err)
    else this._resolve(status)
  }
}

FileRequest._free = []

function ok(result, cb) {
  if (typeof result === 'function') {
    cb = result
    result = undefined
  }

  if (cb) cb(null, result)
  else return result
}

function fail(err, cb) {
  if (cb) cb(err)
  else throw err
}

function done(err, result, cb) {
  if (typeof result === 'function') {
    cb = result
    result = undefined
  }

  if (err) fail(err, cb)
  else return ok(result, cb)
}

async function open(filepath, flags = 'r', mode = 0o666, cb) {
  if (typeof flags === 'function') {
    cb = flags
    flags = 'r'
    mode = 0o666
  } else if (typeof mode === 'function') {
    cb = mode
    mode = 0o666
  }

  if (typeof flags === 'string') flags = toFlags(flags)
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let fd
  let err = null
  try {
    binding.open(req.handle, filepath, flags, mode)

    fd = await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'open',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, fd, cb)
}

function openSync(filepath, flags = 'r', mode = 0o666) {
  if (typeof flags === 'string') flags = toFlags(flags)
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    return binding.openSync(req.handle, filepath, flags, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'open',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function close(fd, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.close(req.handle, fd)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'close', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function closeSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.closeSync(req.handle, fd)
  } catch (e) {
    throw new FileError(e.message, { operation: 'close', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function access(filepath, mode = constants.F_OK, cb) {
  if (typeof mode === 'function') {
    cb = mode
    mode = constants.F_OK
  }

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.access(req.handle, filepath, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'access',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function accessSync(filepath, mode = constants.F_OK) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.accessSync(req.handle, filepath, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'access',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function exists(filepath, cb) {
  let ok = true
  try {
    await access(filepath)
  } catch {
    ok = false
  }

  return done(null, ok, cb)
}

function existsSync(filepath) {
  try {
    accessSync(filepath)
  } catch {
    return false
  }

  return true
}

async function read(fd, buffer, offset = 0, len = buffer.byteLength - offset, pos = -1, cb) {
  if (typeof offset === 'function') {
    cb = offset
    offset = 0
    len = buffer.byteLength
    pos = -1
  } else if (typeof len === 'function') {
    cb = len
    len = buffer.byteLength - offset
    pos = -1
  } else if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.read(req.handle, fd, buffer, offset, len, pos)

    req.retain(buffer)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'read', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function readSync(fd, buffer, offset = 0, len = buffer.byteLength - offset, pos = -1) {
  const req = FileRequest.borrow()

  try {
    return binding.readSync(req.handle, fd, buffer, offset, len, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'read', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function readv(fd, buffers, pos = -1, cb) {
  if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.readv(req.handle, fd, buffers, pos)

    req.retain(buffers)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'readv', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function readvSync(fd, buffers, pos = -1) {
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  try {
    return binding.readvSync(req.handle, fd, buffers, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'readv', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function write(fd, data, offset, len, pos = -1, cb) {
  if (typeof data === 'string') {
    let encoding = len
    cb = pos
    pos = offset

    if (typeof pos === 'function') {
      cb = pos
      pos = -1
      encoding = 'utf8'
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = 'utf8'
    }

    if (typeof pos === 'string') {
      encoding = pos
      pos = -1
    }

    data = Buffer.from(data, encoding)
    offset = 0
    len = data.byteLength
  } else if (typeof offset === 'function') {
    cb = offset
    offset = 0
    len = data.byteLength
    pos = -1
  } else if (typeof len === 'function') {
    cb = len
    len = data.byteLength - offset
    pos = -1
  } else if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof offset !== 'number') offset = 0
  if (typeof len !== 'number') len = data.byteLength - offset
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.write(req.handle, fd, data, offset, len, pos)

    req.retain(data)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'write', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function writeSync(fd, data, offset, len, pos = -1) {
  if (typeof data === 'string') {
    let encoding = len
    pos = offset

    if (typeof pos === 'string') {
      encoding = pos
      pos = -1
    }

    data = Buffer.from(data, encoding)
    offset = 0
    len = data.byteLength
  }

  if (typeof offset !== 'number') offset = 0
  if (typeof len !== 'number') len = data.byteLength - offset
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  try {
    return binding.writeSync(req.handle, fd, data, offset, len, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'write', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function writev(fd, buffers, pos = -1, cb) {
  if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.writev(req.handle, fd, buffers, pos)

    req.retain(buffers)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'writev', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function writevSync(fd, buffers, pos = -1) {
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  try {
    return binding.writevSync(req.handle, fd, buffers, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'writev', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function stat(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.stat(req.handle, filepath)

    await req

    st = new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'stat', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function statSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.statSync(req.handle, filepath)

    return new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'stat', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function lstat(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.lstat(req.handle, filepath)

    await req

    st = new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'lstat', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function lstatSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.lstatSync(req.handle, filepath)

    return new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'lstat', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function fstat(fd, cb) {
  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.fstat(req.handle, fd)

    await req

    st = new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'fstat', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function fstatSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.fstatSync(req.handle, fd)

    return new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'fstat', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function statfs(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.statfs(req.handle, filepath)

    await req

    st = new StatFs(...binding.requestResultStatfs(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'statfs', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function statfsSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.statfsSync(req.handle, filepath)

    return new StatFs(...binding.requestResultStatfs(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'statfs', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function ftruncate(fd, len = 0, cb) {
  if (typeof len === 'function') {
    cb = len
    len = 0
  }

  if (typeof len !== 'number') len = 0

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.ftruncate(req.handle, fd, len)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'ftruncate', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function ftruncateSync(fd, len = 0) {
  if (typeof len !== 'number') len = 0

  const req = FileRequest.borrow()

  try {
    binding.ftruncateSync(req.handle, fd, len)
  } catch (e) {
    throw new FileError(e.message, { operation: 'ftruncate', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function truncate(filepath, len, cb) {
  let fd = -1
  let err

  try {
    fd = await open(filepath, 'r+')

    await ftruncate(fd, len)
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) await close(fd)
  }

  return done(err, cb)
}

function truncateSync(filepath, len) {
  let fd = -1
  let err

  try {
    fd = openSync(filepath, 'r+')

    ftruncateSync(fd, len)
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) closeSync(fd)
  }
}

async function chmod(filepath, mode, cb) {
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.chmod(req.handle, filepath, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'chmod',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function chmodSync(filepath, mode) {
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.chmodSync(req.handle, filepath, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'chmod',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function fchmod(fd, mode, cb) {
  if (typeof mode === 'string') mode = toMode(mode)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fchmod(req.handle, fd, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fchmod', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fchmodSync(fd, mode) {
  if (typeof mode === 'string') mode = toMode(mode)

  const req = FileRequest.borrow()

  try {
    binding.fchmodSync(req.handle, fd, mode)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fchmod', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function chown(filepath, uid, gid, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.chown(req.handle, filepath, uid, gid)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'chown', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function chownSync(filepath, uid, gid) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.chownSync(req.handle, filepath, uid, gid)
  } catch (e) {
    throw new FileError(e.message, { operation: 'chownSync', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function lchown(filepath, uid, gid, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.lchown(req.handle, filepath, uid, gid)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'lchown', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function lchownSync(filepath, uid, gid) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.lchownSync(req.handle, filepath, uid, gid)
  } catch (e) {
    throw new FileError(e.message, { operation: 'lchownSync', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function fchown(fd, uid, gid, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fchown(req.handle, fd, uid, gid)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fchown', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fchownSync(fd, uid, gid) {
  const req = FileRequest.borrow()

  try {
    binding.fchownSync(req.handle, fd, uid, gid)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fchownSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function utimes(filepath, atime, mtime, cb) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.utimes(req.handle, filepath, atime, mtime)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'utimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function utimesSync(filepath, atime, mtime) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.utimesSync(req.handle, filepath, atime, mtime)
  } catch (e) {
    throw new FileError(e.message, { operation: 'utimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function lutimes(filepath, atime, mtime, cb) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.lutimes(req.handle, filepath, atime, mtime)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'lutimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function lutimesSync(filepath, atime, mtime) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.lutimesSync(req.handle, filepath, atime, mtime)
  } catch (e) {
    throw new FileError(e.message, { operation: 'lutimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function futimes(fd, atime, mtime, cb) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.futimes(req.handle, fd, atime, mtime)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'futimes', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function futimesSync(fd, atime, mtime) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  const req = FileRequest.borrow()

  try {
    binding.futimesSync(req.handle, fd, atime, mtime)
  } catch (e) {
    throw new FileError(e.message, { operation: 'futimesSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function link(src, dst, cb) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.link(req.handle, src, dst)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'link', code: e.code, path: src, destination: dst })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function linkSync(src, dst) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  try {
    binding.linkSync(req.handle, src, dst)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'linkSync',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }
}

async function mkdir(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = { mode: 0o777 }
  }

  if (typeof opts === 'number') opts = { mode: opts }
  else if (!opts) opts = {}

  const mode = typeof opts.mode === 'number' ? opts.mode : 0o777

  filepath = toNamespacedPath(filepath)

  if (opts.recursive) {
    let err = null
    try {
      try {
        await mkdir(filepath, { mode })
      } catch (err) {
        if (err.code !== 'ENOENT') {
          if (!(await stat(filepath)).isDirectory()) throw err
        } else {
          while (filepath.endsWith(path.sep)) filepath = filepath.slice(0, -1)
          const i = filepath.lastIndexOf(path.sep)
          if (i <= 0) throw err

          await mkdir(filepath.slice(0, i), { mode, recursive: true })

          try {
            await mkdir(filepath, { mode })
          } catch (err) {
            if (!(await stat(filepath)).isDirectory()) throw err
          }
        }
      }
    } catch (e) {
      err = e
    }

    return done(err, cb)
  }

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.mkdir(req.handle, filepath, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'mkdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function mkdirSync(filepath, opts) {
  if (typeof opts === 'number') opts = { mode: opts }
  else if (!opts) opts = {}

  const mode = typeof opts.mode === 'number' ? opts.mode : 0o777

  filepath = toNamespacedPath(filepath)

  if (opts.recursive) {
    try {
      mkdirSync(filepath, { mode })
    } catch (err) {
      if (err.code !== 'ENOENT') {
        if (!statSync(filepath).isDirectory()) throw err
      } else {
        while (filepath.endsWith(path.sep)) filepath = filepath.slice(0, -1)
        const i = filepath.lastIndexOf(path.sep)
        if (i <= 0) throw err

        mkdirSync(filepath.slice(0, i), { mode, recursive: true })

        try {
          mkdirSync(filepath, { mode })
        } catch (err) {
          if (!statSync(filepath).isDirectory()) throw err
        }
      }
    }

    return
  }

  const req = FileRequest.borrow()

  try {
    binding.mkdirSync(req.handle, filepath, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'mkdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function mkdtemp(prefix, cb) {
  prefix = toNamespacedPath(prefix)

  const req = FileRequest.borrow()

  let res
  let err = null
  try {
    binding.mkdtemp(req.handle, prefix + 'XXXXXX')

    await req

    res = binding.requestResultPath(req.handle)
  } catch (e) {
    err = new FileError(e.message, { operation: 'mkdtemp', code: e.code, path: prefix })
  } finally {
    req.return()
  }

  return done(err, res, cb)
}

function mkdtempSync(prefix) {
  prefix = toNamespacedPath(prefix)

  const req = FileRequest.borrow()

  try {
    binding.mkdtempSync(req.handle, prefix + 'XXXXXX')

    return binding.requestResultPath(req.handle)
  } catch (e) {
    throw new FileError(e.message, { operation: 'mkdtempSync', code: e.code, path: prefix })
  } finally {
    req.return()
  }
}

async function rmdir(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.rmdir(req.handle, filepath)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'rmdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function rmdirSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.rmdirSync(req.handle, filepath)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'rmdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function rm(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  let err = null
  try {
    const st = await lstat(filepath)

    if (st.isDirectory()) {
      if (opts.recursive) {
        try {
          await rmdir(filepath)
        } catch (err) {
          if (err.code !== 'ENOTEMPTY') throw err

          const files = await readdir(filepath)

          for (const file of files) {
            await rm(filepath + path.sep + file, opts)
          }

          await rmdir(filepath)
        }
      } else {
        throw new FileError('is a directory', {
          operation: 'rm',
          code: 'EISDIR',
          path: filepath
        })
      }
    } else {
      await unlink(filepath)
    }
  } catch (e) {
    if (e.code !== 'ENOENT' || !opts.force) err = e
  }

  return done(err, cb)
}

function rmSync(filepath, opts) {
  if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  try {
    const st = lstatSync(filepath)

    if (st.isDirectory()) {
      if (opts.recursive) {
        try {
          rmdirSync(filepath)
        } catch (err) {
          if (err.code !== 'ENOTEMPTY') throw err

          const files = readdirSync(filepath)

          for (const file of files) {
            rmSync(filepath + path.sep + file, opts)
          }

          rmdirSync(filepath)
        }
      } else {
        throw new FileError('is a directory', {
          operation: 'rm',
          code: 'EISDIR',
          path: filepath
        })
      }
    } else {
      unlinkSync(filepath)
    }
  } catch (err) {
    if (err.code !== 'ENOENT' || !opts.force) throw err
  }
}

async function unlink(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.unlink(req.handle, filepath)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'unlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function unlinkSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.unlinkSync(req.handle, filepath)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'unlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function rename(src, dst, cb) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.rename(req.handle, src, dst)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'rename',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function renameSync(src, dst) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  try {
    binding.renameSync(req.handle, src, dst)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'rename',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }
}

async function copyFile(src, dst, mode = 0, cb) {
  if (typeof mode === 'function') {
    cb = mode
    mode = 0
  }

  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.copyfile(req.handle, src, dst, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'copyfile',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function copyFileSync(src, dst, mode = 0) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  try {
    binding.copyfileSync(req.handle, src, dst, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'copyfile',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }
}

async function cp(src, dst, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (!opts) opts = {}

  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  let err = null
  try {
    const st = await lstat(src)

    if (st.isDirectory()) {
      if (opts.recursive !== true) {
        throw new FileError('is a directory', { operation: 'cp', code: 'EISDIR', path: src })
      }

      try {
        await lstat(dst)
      } catch (e) {
        if (e.code !== 'ENOENT') throw e

        await mkdir(dst, { mode: st.mode, recursive: true })
      }

      const dir = await opendir(src)
      for await (const { name } of dir) {
        await cp(path.join(src, name), path.join(dst, name), opts)
      }
    } else if (st.isFile()) {
      await copyFile(src, dst)
      await chmod(dst, st.mode)
    }
  } catch (e) {
    err = e
  }

  return done(err, cb)
}

function cpSync(src, dst, opts = {}) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const st = lstatSync(src)

  if (st.isDirectory()) {
    if (opts.recursive !== true) {
      throw new FileError('is a directory', { operation: 'cp', code: 'EISDIR', path: src })
    }

    try {
      lstatSync(dst)
    } catch (e) {
      if (e.code !== 'ENOENT') throw e

      mkdirSync(dst, { mode: st.mode, recursive: true })
    }

    const dir = opendirSync(src)
    for (const { name } of dir) {
      cpSync(path.join(src, name), path.join(dst, name), opts)
    }
  } else if (st.isFile()) {
    copyFileSync(src, dst)
    chmodSync(dst, st.mode)
  }
}

async function realpath(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let res
  let err = null
  try {
    binding.realpath(req.handle, filepath)

    await req

    res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'realpath',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, res, cb)
}

function realpathSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.realpathSync(req.handle, filepath)

    let res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)

    return res
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'realpath',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function readlink(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let res
  let err = null
  try {
    binding.readlink(req.handle, filepath)

    await req

    res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'readlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, res, cb)
}

function readlinkSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.readlinkSync(req.handle, filepath)

    let res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)

    return res
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'readlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function fsync(fd, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fsync(req.handle, fd)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fsync', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fsyncSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.fsyncSync(req.handle, fd)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fsyncSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function fdatasync(fd, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fdatasync(req.handle, fd)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fdatasync', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fdatasyncSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.fdatasyncSync(req.handle, fd)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fdatasyncSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

function normalizeSymlinkTarget(target, type, filepath) {
  if (isWindows) {
    if (type === constants.UV_FS_SYMLINK_JUNCTION) target = path.resolve(filepath, '..', target)

    if (path.isAbsolute(target)) return path.toNamespacedPath(target)

    return target.replace(/\//g, path.sep)
  }

  return target
}

async function symlink(target, filepath, type, cb) {
  if (typeof type === 'function') {
    cb = type
    type = null
  }

  filepath = toNamespacedPath(filepath)

  if (typeof type === 'string') {
    switch (type) {
      case 'dir':
        type = constants.UV_FS_SYMLINK_DIR
        break
      case 'junction':
        type = constants.UV_FS_SYMLINK_JUNCTION
        break
      case 'file':
      default:
        type = 0
        break
    }
  } else if (typeof type !== 'number') {
    if (isWindows) {
      target = path.resolve(filepath, '..', target)

      try {
        type = (await stat(target)).isDirectory()
          ? constants.UV_FS_SYMLINK_DIR
          : constants.UV_FS_SYMLINK_JUNCTION
      } catch {
        type = 0
      }
    } else {
      type = 0
    }
  }

  target = normalizeSymlinkTarget(target, type, filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.symlink(req.handle, target, filepath, type)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'symlink',
      code: e.code,
      path: target,
      destination: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function symlinkSync(target, filepath, type) {
  filepath = toNamespacedPath(filepath)

  if (typeof type === 'string') {
    switch (type) {
      case 'dir':
        type = constants.UV_FS_SYMLINK_DIR
        break
      case 'junction':
        type = constants.UV_FS_SYMLINK_JUNCTION
        break
      case 'file':
      default:
        type = 0
        break
    }
  } else if (typeof type !== 'number') {
    if (isWindows) {
      target = path.resolve(filepath, '..', target)

      try {
        type = statSync(target).isDirectory()
          ? constants.UV_FS_SYMLINK_DIR
          : constants.UV_FS_SYMLINK_JUNCTION
      } catch {
        type = 0
      }
    } else {
      type = 0
    }
  }

  target = normalizeSymlinkTarget(target, type, filepath)

  const req = FileRequest.borrow()

  try {
    binding.symlinkSync(req.handle, target, filepath, type)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'symlink',
      code: e.code,
      path: target,
      destination: filepath
    })
  } finally {
    req.return()
  }
}

async function opendir(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let dir
  let err = null
  try {
    binding.opendir(req.handle, filepath)

    await req

    dir = new Dir(filepath, binding.requestResultDir(req.handle), opts)
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'opendir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, dir, cb)
}

function opendirSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.opendirSync(req.handle, filepath)

    return new Dir(filepath, binding.requestResultDir(req.handle), opts)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'opendir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function readdir(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { withFileTypes = false, recursive = false } = opts

  filepath = toNamespacedPath(filepath)

  const queue = [filepath]
  let result = []
  let err = null
  try {
    while (queue.length !== 0) {
      const dir = await opendir(queue.pop())

      for await (const entry of dir) {
        const entryPath = path.join(entry.parentPath, entry.name)

        if (withFileTypes) {
          result.push(entry)
        } else {
          result.push(path.relative(filepath, entryPath))
        }

        if (recursive && entry.isDirectory()) queue.push(entryPath)
      }
    }
  } catch (e) {
    result = []
    err = e
  }

  return done(err, result, cb)
}

function readdirSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { withFileTypes = false, recursive = false } = opts

  filepath = toNamespacedPath(filepath)

  const queue = [filepath]
  const result = []

  while (queue.length !== 0) {
    const dir = opendirSync(queue.pop(), opts)

    for (const entry of dir) {
      const entryPath = path.join(entry.parentPath, entry.name)

      if (withFileTypes) {
        result.push(entry)
      } else {
        result.push(path.relative(filepath, entryPath))
      }

      if (recursive && entry.isDirectory()) queue.push(entryPath)
    }
  }

  return result
}

async function readFile(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'buffer' } = opts

  let fd = -1
  let buffer = null
  let err = null
  try {
    fd = await open(filepath, opts.flag || 'r')

    const st = await fstat(fd)

    let len = 0

    if (st.size === 0) {
      const buffers = []

      while (true) {
        buffer = Buffer.allocUnsafe(8192)
        const r = await read(fd, buffer)
        len += r
        if (r === 0) break
        buffers.push(buffer.subarray(0, r))
      }

      buffer = Buffer.concat(buffers)
    } else {
      buffer = Buffer.allocUnsafe(st.size)

      while (true) {
        const r = await read(fd, len ? buffer.subarray(len) : buffer)
        len += r
        if (r === 0 || len === buffer.byteLength) break
      }

      if (len !== buffer.byteLength) buffer = buffer.subarray(0, len)
    }

    if (encoding !== 'buffer') buffer = buffer.toString(encoding)
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) await close(fd)
  }

  return done(err, buffer, cb)
}

function readFileSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'buffer' } = opts

  let fd = -1
  try {
    fd = openSync(filepath, opts.flag || 'r')

    const st = fstatSync(fd)

    let buffer
    let len = 0

    if (st.size === 0) {
      const buffers = []

      while (true) {
        buffer = Buffer.allocUnsafe(8192)
        const r = readSync(fd, buffer)
        len += r
        if (r === 0) break
        buffers.push(buffer.subarray(0, r))
      }

      buffer = Buffer.concat(buffers)
    } else {
      buffer = Buffer.allocUnsafe(st.size)

      while (true) {
        const r = readSync(fd, len ? buffer.subarray(len) : buffer)
        len += r
        if (r === 0 || len === buffer.byteLength) break
      }

      if (len !== buffer.byteLength) buffer = buffer.subarray(0, len)
    }

    if (encoding !== 'buffer') buffer = buffer.toString(encoding)

    return buffer
  } finally {
    if (fd !== -1) closeSync(fd)
  }
}

async function writeFile(filepath, data, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (typeof data === 'string') data = Buffer.from(data, opts.encoding)

  let fd = -1
  let len = 0
  let err = null
  try {
    fd = await open(filepath, opts.flag || 'w', opts.mode || 0o666)

    while (true) {
      len += await write(fd, len ? data.subarray(len) : data)
      if (len === data.byteLength) break
    }
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) await close(fd)
  }

  return done(err, len, cb)
}

function writeFileSync(filepath, data, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (typeof data === 'string') data = Buffer.from(data, opts.encoding)

  let fd = -1
  try {
    fd = openSync(filepath, opts.flag || 'w', opts.mode || 0o666)

    let len = 0

    while (true) {
      len += writeSync(fd, len ? data.subarray(len) : data)
      if (len === data.byteLength) break
    }
  } finally {
    if (fd !== -1) closeSync(fd)
  }
}

function appendFile(filepath, data, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (!opts.flag) opts = { ...opts, flag: 'a' }

  return writeFile(filepath, data, opts, cb)
}

function appendFileSync(filepath, data, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (!opts.flag) opts = { ...opts, flag: 'a' }

  return writeFileSync(filepath, data, opts)
}

function watch(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  return new Watcher(filepath, opts, cb)
}

class Stats {
  constructor(
    dev,
    mode,
    nlink,
    uid,
    gid,
    rdev,
    blksize,
    ino,
    size,
    blocks,
    atimeMs,
    mtimeMs,
    ctimeMs,
    birthtimeMs
  ) {
    this.dev = dev
    this.mode = mode
    this.nlink = nlink
    this.uid = uid
    this.gid = gid
    this.rdev = rdev
    this.blksize = blksize
    this.ino = ino
    this.size = size
    this.blocks = blocks
    this.atimeMs = atimeMs
    this.mtimeMs = mtimeMs
    this.ctimeMs = ctimeMs
    this.birthtimeMs = birthtimeMs
    this.atime = new Date(atimeMs)
    this.mtime = new Date(mtimeMs)
    this.ctime = new Date(ctimeMs)
    this.birthtime = new Date(birthtimeMs)
  }

  isDirectory() {
    return (this.mode & constants.S_IFMT) === constants.S_IFDIR
  }

  isFile() {
    return (this.mode & constants.S_IFMT) === constants.S_IFREG
  }

  isBlockDevice() {
    return (this.mode & constants.S_IFMT) === constants.S_IFBLK
  }

  isCharacterDevice() {
    return (this.mode & constants.S_IFMT) === constants.S_IFCHR
  }

  isFIFO() {
    return (this.mode & constants.S_IFMT) === constants.S_IFIFO
  }

  isSymbolicLink() {
    return (this.mode & constants.S_IFMT) === constants.S_IFLNK
  }

  isSocket() {
    return (this.mode & constants.S_IFMT) === constants.S_IFSOCK
  }
}

class StatFs {
  constructor(type, bsize, blocks, bfree, bavail, files, ffree) {
    this.type = type
    this.bsize = bsize
    this.blocks = blocks
    this.bfree = bfree
    this.bavail = bavail
    this.files = files
    this.ffree = ffree
  }
}

class Dir {
  constructor(path, handle, opts = {}) {
    const { encoding = 'utf8', bufferSize = 32 } = opts

    this.path = path

    this._encoding = encoding
    this._capacity = bufferSize
    this._buffer = new FIFO()
    this._ended = false
    this._handle = handle
  }

  async read(cb) {
    if (this._buffer.length) return ok(this._buffer.shift(), cb)
    if (this._ended) return ok(null, cb)

    const req = FileRequest.borrow()

    let entries
    let err = null
    try {
      req.retain(binding.readdir(req.handle, this._handle, this._capacity))

      await req

      entries = binding.requestResultDirents(req.handle)
    } catch (e) {
      err = new FileError(e.message, {
        operation: 'readdir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    if (err) return fail(err, cb)

    if (entries.length === 0) {
      this._ended = true

      return ok(null, cb)
    }

    for (const entry of entries) {
      let name = Buffer.from(entry.name)

      if (this._encoding !== 'buffer') name = name.toString(this._encoding)

      this._buffer.push(new Dirent(this.path, name, entry.type))
    }

    return ok(this._buffer.shift(), cb)
  }

  readSync() {
    if (this._buffer.length) return this._buffer.shift()
    if (this._ended) return null

    const req = FileRequest.borrow()

    let entries
    try {
      req.retain(binding.readdirSync(req.handle, this._handle, this._capacity))

      entries = binding.requestResultDirents(req.handle)
    } catch (e) {
      throw new FileError(e.message, {
        operation: 'readdir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    if (entries.length === 0) {
      this._ended = true

      return null
    }

    for (const entry of entries) {
      let name = Buffer.from(entry.name)

      if (this._encoding !== 'buffer') name = name.toString(this._encoding)

      this._buffer.push(new Dirent(this.path, name, entry.type))
    }

    return this._buffer.shift()
  }

  async close(cb) {
    const req = FileRequest.borrow()

    let err = null
    try {
      binding.closedir(req.handle, this._handle)

      await req
    } catch (e) {
      err = new FileError(e.message, {
        operation: 'closedir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    this._handle = null

    return done(err, cb)
  }

  closeSync() {
    const req = FileRequest.borrow()

    try {
      binding.closedirSync(req.handle, this._handle)
    } catch (e) {
      throw new FileError(e.message, {
        operation: 'closedir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    this._handle = null
  }

  [Symbol.dispose]() {
    this.closeSync()
  }

  async [Symbol.asyncDispose]() {
    await this.close()
  }

  *[Symbol.iterator]() {
    while (true) {
      const entry = this.readSync()
      if (entry === null) break
      yield entry
    }

    this.closeSync()
  }

  async *[Symbol.asyncIterator]() {
    while (true) {
      const entry = await this.read()
      if (entry === null) break
      yield entry
    }

    await this.close()
  }
}

class Dirent {
  constructor(parentPath, name, type) {
    this.parentPath = parentPath
    this.name = name
    this.type = type
  }

  isFile() {
    return this.type === constants.UV_DIRENT_FILE
  }

  isDirectory() {
    return this.type === constants.UV_DIRENT_DIR
  }

  isSymbolicLink() {
    return this.type === constants.UV_DIRENT_LINK
  }

  isFIFO() {
    return this.type === constants.UV_DIRENT_FIFO
  }

  isSocket() {
    return this.type === constants.UV_DIRENT_SOCKET
  }

  isCharacterDevice() {
    return this.type === constants.UV_DIRENT_CHAR
  }

  isBlockDevice() {
    return this.type === constants.UV_DIRENT_BLOCK
  }
}

class FileReadStream extends Readable {
  constructor(path, opts = {}) {
    const { eagerOpen = true } = opts

    super({ eagerOpen, ...opts })

    this.path = path
    this.fd = typeof opts.fd === 'number' ? opts.fd : -1
    this.flags = opts.flags || 'r'
    this.mode = opts.mode || 0o666

    this._offset = opts.start || 0
    this._missing = 0

    if (opts.length) {
      this._missing = opts.length
    } else if (typeof opts.end === 'number') {
      this._missing = opts.end - this._offset + 1
    } else {
      this._missing = -1
    }
  }

  async _open(cb) {
    let err

    if (this.fd === -1) {
      err = null
      try {
        this.fd = await open(this.path, this.flags, this.mode)
      } catch (e) {
        err = e
      }

      if (err) return cb(err)
    }

    let st
    err = null
    try {
      st = await fstat(this.fd)
    } catch (e) {
      err = e
    }

    if (err) return cb(err)

    if (this._missing === -1) this._missing = st.size

    if (st.size < this._offset) {
      this._offset = st.size
      this._missing = 0
    } else if (st.size < this._offset + this._missing) {
      this._missing = st.size - this._offset
    }

    cb(null)
  }

  async _read(size) {
    if (this._missing <= 0) return this.push(null)

    const data = Buffer.allocUnsafe(Math.min(this._missing, size))

    let len
    let err = null
    try {
      len = await read(this.fd, data, 0, data.byteLength, this._offset)
    } catch (e) {
      err = e
    }

    if (err) return this.destroy(err)

    if (len === 0) return this.push(null)

    if (this._missing < len) len = this._missing

    this._missing -= len
    this._offset += len

    this.push(data.subarray(0, len))
  }

  async _destroy(err, cb) {
    if (this.fd === -1) return cb(err)

    try {
      await close(this.fd)
    } catch (e) {
      err = err || e
    }

    cb(err)
  }
}

class FileWriteStream extends Writable {
  constructor(path, opts = {}) {
    const { eagerOpen = true } = opts

    super({ eagerOpen, ...opts })

    this.path = path
    this.fd = typeof opts.fd === 'number' ? opts.fd : -1
    this.flags = opts.flags || 'w'
    this.mode = opts.mode || 0o666
  }

  async _open(cb) {
    if (this.fd !== -1) return cb(null)

    let err = null
    try {
      this.fd = await open(this.path, this.flags, this.mode)
    } catch (e) {
      err = e
    }

    cb(err)
  }

  async _writev(batch, cb) {
    let err = null
    try {
      await writev(
        this.fd,
        batch.map(({ chunk }) => chunk)
      )
    } catch (e) {
      err = e
    }

    cb(err)
  }

  async _destroy(err, cb) {
    if (this.fd === -1) return cb(err)

    try {
      await close(this.fd)
    } catch (e) {
      err = err || e
    }

    cb(err)
  }
}

class Watcher extends EventEmitter {
  constructor(path, opts, onchange) {
    if (typeof opts === 'function') {
      onchange = opts
      opts = {}
    }

    if (!opts) opts = {}

    const { persistent = true, recursive = false, encoding = 'utf8' } = opts

    super()

    this._closed = false
    this._encoding = encoding
    this._handle = binding.watcherInit(path, recursive, this, this._onevent, this._onclose)

    if (!persistent) this.unref()

    if (onchange) this.on('change', onchange)
  }

  close() {
    if (this._closed) return
    this._closed = true

    binding.watcherClose(this._handle)
  }

  ref() {
    if (this._handle) binding.watcherRef(this._handle)
    return this
  }

  unref() {
    if (this._handle) binding.watcherUnref(this._handle)
    return this
  }

  [Symbol.asyncIterator]() {
    const buffer = []
    let done = false
    let error = null
    let next = null

    this.on('change', (eventType, filename) => {
      if (next) {
        next.resolve({ done: false, value: { eventType, filename } })
        next = null
      } else {
        buffer.push({ eventType, filename })
      }
    })
      .on('error', (err) => {
        done = true
        error = err

        if (next) {
          next.reject(error)
          next = null
        }
      })
      .on('close', () => {
        done = true

        if (next) {
          next.resolve({ done })
          next = null
        }
      })

    return {
      next: () =>
        new Promise((resolve, reject) => {
          if (error) return reject(error)

          if (buffer.length) return resolve({ done: false, value: buffer.shift() })

          if (done) return resolve({ done })

          next = { resolve, reject }
        })
    }
  }

  _onevent(err, events, filename) {
    if (err) {
      this.close()
      this.emit('error', err)
    } else {
      const path =
        this._encoding === 'buffer'
          ? Buffer.from(filename)
          : Buffer.from(filename).toString(this._encoding)

      if (events & binding.UV_RENAME) {
        this.emit('change', 'rename', path)
      }

      if (events & binding.UV_CHANGE) {
        this.emit('change', 'change', path)
      }
    }
  }

  _onclose() {
    this._handle = null

    this.emit('close')
  }
}

exports.access = access
exports.appendFile = appendFile
exports.chmod = chmod
exports.chown = chown
exports.close = close
exports.copyFile = copyFile
exports.cp = cp
exports.exists = exists
exports.fchmod = fchmod
exports.fchown = fchown
exports.fdatasync = fdatasync
exports.fstat = fstat
exports.fsync = fsync
exports.ftruncate = ftruncate
exports.futimes = futimes
exports.lchown = lchown
exports.lutimes = lutimes
exports.link = link
exports.lstat = lstat
exports.mkdir = mkdir
exports.mkdtemp = mkdtemp
exports.open = open
exports.opendir = opendir
exports.read = read
exports.readFile = readFile
exports.readdir = readdir
exports.readlink = readlink
exports.readv = readv
exports.realpath = realpath
exports.rename = rename
exports.rm = rm
exports.rmdir = rmdir
exports.stat = stat
exports.statfs = statfs
exports.symlink = symlink
exports.truncate = truncate
exports.unlink = unlink
exports.utimes = utimes
exports.watch = watch
exports.write = write
exports.writeFile = writeFile
exports.writev = writev

exports.accessSync = accessSync
exports.appendFileSync = appendFileSync
exports.chmodSync = chmodSync
exports.chownSync = chownSync
exports.closeSync = closeSync
exports.copyFileSync = copyFileSync
exports.cpSync = cpSync
exports.existsSync = existsSync
exports.fchmodSync = fchmodSync
exports.fchownSync = fchownSync
exports.fdatasyncSync = fdatasyncSync
exports.fstatSync = fstatSync
exports.fsyncSync = fsyncSync
exports.ftruncateSync = ftruncateSync
exports.futimesSync = futimesSync
exports.lchownSync = lchownSync
exports.lutimesSync = lutimesSync
exports.linkSync = linkSync
exports.lstatSync = lstatSync
exports.mkdirSync = mkdirSync
exports.mkdtempSync = mkdtempSync
exports.openSync = openSync
exports.opendirSync = opendirSync
exports.readFileSync = readFileSync
exports.readSync = readSync
exports.readdirSync = readdirSync
exports.readlinkSync = readlinkSync
exports.readvSync = readvSync
exports.realpathSync = realpathSync
exports.renameSync = renameSync
exports.rmSync = rmSync
exports.rmdirSync = rmdirSync
exports.statSync = statSync
exports.statfsSync = statfsSync
exports.symlinkSync = symlinkSync
exports.truncateSync = truncateSync
exports.unlinkSync = unlinkSync
exports.utimesSync = utimesSync
exports.writeFileSync = writeFileSync
exports.writeSync = writeSync
exports.writevSync = writevSync

exports.promises = require('./promises')

exports.Stats = Stats
exports.StatFs = StatFs
exports.Dir = Dir
exports.Dirent = Dirent
exports.Watcher = Watcher

exports.ReadStream = FileReadStream

exports.createReadStream = function createReadStream(path, opts) {
  return new FileReadStream(path, opts)
}

exports.WriteStream = FileWriteStream

exports.createWriteStream = function createWriteStream(path, opts) {
  return new FileWriteStream(path, opts)
}

function toNamespacedPath(filepath) {
  if (typeof filepath !== 'string') {
    if (isURL(filepath)) filepath = fileURLToPath(filepath)
    else filepath = filepath.toString()
  }

  return path.toNamespacedPath(filepath)
}

function toFlags(flags) {
  switch (flags) {
    case 'r':
      return constants.O_RDONLY
    case 'rs': // Fall through.
    case 'sr':
      return constants.O_RDONLY | constants.O_SYNC
    case 'r+':
      return constants.O_RDWR
    case 'rs+': // Fall through.
    case 'sr+':
      return constants.O_RDWR | constants.O_SYNC

    case 'w':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_WRONLY
    case 'wx': // Fall through.
    case 'xw':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_WRONLY | constants.O_EXCL

    case 'w+':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_RDWR
    case 'wx+': // Fall through.
    case 'xw+':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_RDWR | constants.O_EXCL

    case 'a':
      return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY
    case 'ax': // Fall through.
    case 'xa':
      return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY | constants.O_EXCL
    case 'as': // Fall through.
    case 'sa':
      return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY | constants.O_SYNC

    case 'a+':
      return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR
    case 'ax+': // Fall through.
    case 'xa+':
      return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR | constants.O_EXCL
    case 'as+': // Fall through.
    case 'sa+':
      return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR | constants.O_SYNC
    default:
      return 0
  }
}

function toMode(mode) {
  return parseInt(mode, 8)
}
const binding = require('../binding')

module.exports = {
  O_RDWR: binding.O_RDWR,
  O_RDONLY: binding.O_RDONLY,
  O_WRONLY: binding.O_WRONLY,
  O_CREAT: binding.O_CREAT,
  O_TRUNC: binding.O_TRUNC,
  O_APPEND: binding.O_APPEND,

  F_OK: binding.F_OK || 0,
  R_OK: binding.R_OK || 0,
  W_OK: binding.W_OK || 0,
  X_OK: binding.X_OK || 0,

  S_IFMT: binding.S_IFMT,
  S_IFREG: binding.S_IFREG,
  S_IFDIR: binding.S_IFDIR,
  S_IFCHR: binding.S_IFCHR,
  S_IFLNK: binding.S_IFLNK,
  S_IFBLK: binding.S_IFBLK || 0,
  S_IFIFO: binding.S_IFIFO || 0,
  S_IFSOCK: binding.S_IFSOCK || 0,

  S_IRUSR: binding.S_IRUSR || 0,
  S_IWUSR: binding.S_IWUSR || 0,
  S_IXUSR: binding.S_IXUSR || 0,
  S_IRGRP: binding.S_IRGRP || 0,
  S_IWGRP: binding.S_IWGRP || 0,
  S_IXGRP: binding.S_IXGRP || 0,
  S_IROTH: binding.S_IROTH || 0,
  S_IWOTH: binding.S_IWOTH || 0,
  S_IXOTH: binding.S_IXOTH || 0,

  UV_DIRENT_UNKNOWN: binding.UV_DIRENT_UNKNOWN,
  UV_DIRENT_FILE: binding.UV_DIRENT_FILE,
  UV_DIRENT_DIR: binding.UV_DIRENT_DIR,
  UV_DIRENT_LINK: binding.UV_DIRENT_LINK,
  UV_DIRENT_FIFO: binding.UV_DIRENT_FIFO,
  UV_DIRENT_SOCKET: binding.UV_DIRENT_SOCKET,
  UV_DIRENT_CHAR: binding.UV_DIRENT_CHAR,
  UV_DIRENT_BLOCK: binding.UV_DIRENT_BLOCK,

  COPYFILE_EXCL: binding.UV_FS_COPYFILE_EXCL,
  COPYFILE_FICLONE: binding.UV_FS_COPYFILE_FICLONE,
  COPYFILE_FICLONE_FORCE: binding.UV_FS_COPYFILE_FICLONE_FORCE,
  UV_FS_SYMLINK_DIR: binding.UV_FS_SYMLINK_DIR,
  UV_FS_SYMLINK_JUNCTION: binding.UV_FS_SYMLINK_JUNCTION
}
const os = require('bare-os')

module.exports = class FileError extends Error {
  constructor(msg, opts = {}) {
    const { code, operation = null, path = null, destination = null, fd = -1 } = opts

    if (operation !== null) msg += describe(operation, opts)

    super(`${code}: ${msg}`)

    this.code = code

    if (operation !== null) this.operation = operation
    if (path !== null) this.path = path
    if (destination !== null) this.destination = destination
    if (fd !== -1) this.fd = fd
  }

  get name() {
    return 'FileError'
  }

  // For Node.js compatibility
  get errno() {
    return os.constants.errnos[this.code]
  }

  // For Node.js compatibility
  get syscall() {
    return this.operation
  }

  // For Node.js compatibility
  get dest() {
    return this.destination
  }
}

function describe(operation, opts) {
  const { path = null, destination = null, fd = -1 } = opts

  let result = `, ${operation}`

  if (path !== null) {
    result += ` ${JSON.stringify(path)}`

    if (destination !== null) {
      result += ` -> ${JSON.stringify(destination)}`
    }
  } else if (fd !== -1) {
    result += ` ${fd}`
  }

  return result
}
{
  "name": "bare-fs",
  "version": "4.7.2",
  "description": "Native file system operations for Bare",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./promises": {
      "types": "./promises.d.ts",
      "default": "./promises.js"
    },
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "promises.js",
    "promises.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-fs.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-fs/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-fs#readme",
  "engines": {
    "bare": ">=1.16.0"
  },
  "dependencies": {
    "bare-events": "^2.5.4",
    "bare-path": "^3.0.0",
    "bare-stream": "^2.6.4",
    "bare-url": "^2.2.2",
    "fast-fifo": "^1.3.2"
  },
  "devDependencies": {
    "bare-buffer": "^3.0.2",
    "bare-crypto": "^1.11.2",
    "brittle": "^3.1.1",
    "cmake-bare": "^1.1.7",
    "lunte": "^1.6.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "bare-buffer": "*"
  },
  "peerDependenciesMeta": {
    "bare-buffer": {
      "optional": true
    }
  }
}
const EventEmitter = require('bare-events')
const fs = require('.')

class FileHandle extends EventEmitter {
  constructor(fd) {
    super()

    this.fd = fd
  }

  async close() {
    await fs.close(this.fd)

    this.fd = -1
    this.emit('close')
  }

  async read(buffer, ...args) {
    return {
      bytesRead: await fs.read(this.fd, buffer, ...args),
      buffer
    }
  }

  async readv(buffers, ...args) {
    return {
      bytesRead: await fs.readv(this.fd, buffers, ...args),
      buffers
    }
  }

  async write(buffer, ...args) {
    return {
      bytesWritten: await fs.write(this.fd, buffer, ...args),
      buffer
    }
  }

  async writev(buffers, ...args) {
    return {
      bytesWritten: await fs.writev(this.fd, buffers, ...args),
      buffers
    }
  }

  async stat() {
    return fs.fstat(this.fd)
  }

  async chmod(mode) {
    await fs.fchmod(this.fd, mode)
  }

  async chown(uid, gid) {
    await fs.fchown(this.fd, uid, gid)
  }

  async datasync() {
    return fs.fdatasync(this.fd)
  }

  async sync() {
    return fs.fsync(this.fd)
  }

  async truncate(len) {
    await fs.ftruncate(this.fd, len)
  }

  async utimes(atime, mtime) {
    await fs.futimes(this.fd, atime, mtime)
  }

  createReadStream(opts) {
    return fs.createReadStream(null, { ...opts, fd: this.fd })
  }

  createWriteStream(opts) {
    return fs.createWriteStream(null, { ...opts, fd: this.fd })
  }

  async [Symbol.asyncDispose]() {
    await this.close()
  }
}

exports.open = async function open(filepath, flags, mode) {
  return new FileHandle(await fs.open(filepath, flags, mode))
}

exports.access = fs.access
exports.appendFile = fs.appendFile
exports.chmod = fs.chmod
exports.chown = fs.chown
exports.constants = fs.constants
exports.copyFile = fs.copyFile
exports.cp = fs.cp
exports.lchown = fs.lchown
exports.lutimes = fs.lutimes
exports.link = fs.link
exports.lstat = fs.lstat
exports.mkdir = fs.mkdir
exports.mkdtemp = fs.mkdtemp
exports.opendir = fs.opendir
exports.readFile = fs.readFile
exports.readdir = fs.readdir
exports.readlink = fs.readlink
exports.realpath = fs.realpath
exports.rename = fs.rename
exports.rm = fs.rm
exports.rmdir = fs.rmdir
exports.stat = fs.stat
exports.statfs = fs.statfs
exports.truncate = fs.truncate
exports.symlink = fs.symlink
exports.unlink = fs.unlink
exports.utimes = fs.utimes
exports.watch = fs.watch
exports.writeFile = fs.writeFile
module.exports = require.addon()
const ansiEscapes = require('bare-ansi-escapes')
const getType = require('bare-type')
const binding = require('./binding')

const PLAIN_KEY = /^[a-zA-Z_][a-zA-Z_0-9]*$/

const defaultDepth = 2
const defaultBreakLength = 80
const defaultMaxArrayLength = 40

module.exports = exports = function inspect(value, opts = {}) {
  const {
    colors = false,
    depth = defaultDepth,
    breakLength = defaultBreakLength,
    stylize = defaultStylize(colors)
  } = opts

  const references = new InspectRefMap()

  const tree = inspectValue(value, 0, {
    colors,
    depth,
    breakLength,
    stylize,
    references
  })

  return tree.toString()
}

exports.styles = {
  bigint: ansiEscapes.colorYellow,
  boolean: ansiEscapes.colorYellow,
  date: ansiEscapes.colorMagenta,
  module: ansiEscapes.modifierUnderline,
  name: ansiEscapes.modifierReset,
  null: ansiEscapes.modifierBold,
  number: ansiEscapes.colorYellow,
  regexp: ansiEscapes.colorRed,
  special: ansiEscapes.colorCyan,
  string: ansiEscapes.colorGreen,
  symbol: ansiEscapes.colorGreen,
  undefined: ansiEscapes.colorBrightBlack
}

const styles = exports.styles

function defaultStylize(colors) {
  return function stylize(value, style) {
    const color = colors && styles[style]

    if (color) return color + value + ansiEscapes.modifierReset

    return value
  }
}

class InspectRefMap {
  constructor() {
    this.refs = new WeakMap()
    this.ids = new WeakMap()
    this.nextId = 1
  }

  has(object) {
    return this.refs.has(object)
  }

  get(object) {
    return this.refs.get(object) || null
  }

  set(object, ref) {
    this.refs.set(object, ref)
  }

  id(object) {
    let id = this.ids.get(object)
    if (id) return id

    id = this.nextId++
    this.ids.set(object, id)

    return id
  }
}

class InspectNode {
  constructor(depth, length, opts) {
    const { breakLength = defaultBreakLength, breakAlways = false } = opts

    this.depth = depth
    this.length = length
    this.breakLength = breakLength
    this.breakAlways = breakAlways
  }

  pad(n, string) {
    return string.padStart(n, ' ')
  }

  indent(n, string) {
    return '  '.repeat(n) + string
  }
}

class InspectRef extends InspectNode {
  constructor(depth, opts) {
    super(depth, '[circular *]'.length, opts)

    this.refs = opts.references
    this.count = 0
    this.circular = false
    this.color = opts.colors && styles.special
  }

  get id() {
    return this.refs.id(this)
  }

  increment() {
    return ++this.count
  }

  decrement() {
    return --this.count
  }

  toString(opts = {}) {
    const { offset = 0, pad = 0, indent = 0 } = opts

    let value = this.pad(pad, '[circular *' + this.id + ']')

    if (this.color) value = this.color + value + ansiEscapes.modifierReset

    return offset ? value : this.indent(indent, value)
  }
}

class InspectLeaf extends InspectNode {
  constructor(value, color, depth, opts) {
    const length = value.length

    if (value.includes('\n')) {
      value = value.replaceAll('\n', '\n' + '  '.repeat(depth))

      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.value = value
    this.color = opts.colors && color
  }

  toString(opts = {}) {
    const { offset = 0, pad = 0, indent = 0 } = opts

    let value = this.pad(pad, this.value)

    if (this.color) value = this.color + value + ansiEscapes.modifierReset

    return offset ? value : this.indent(indent, value)
  }
}

class InspectPair extends InspectNode {
  constructor(delim, left, right, depth, opts) {
    const length = left.length + delim.length + right.length

    if (left.breakAlways || right.breakAlways) {
      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.delim = delim
    this.left = left
    this.right = right
  }

  toString(opts = {}) {
    const { indent = 0 } = opts

    return this.indent(
      indent,
      this.left +
        this.delim +
        this.right.toString({
          indent,
          offset: this.left.length + this.delim.length
        })
    )
  }
}

class InspectSuspension extends InspectNode {
  constructor(overflow, depth, opts) {
    const label = `... ${overflow} more`

    super(depth, label.length, opts)

    this.label = label
  }

  toString(opts = {}) {
    const { indent = 0 } = opts

    return this.indent(indent, this.label)
  }
}

class InspectSequence extends InspectNode {
  constructor(header, footer, delim, values, ref, depth, opts) {
    const { tabulate = false } = opts

    const length =
      (ref.circular ? '<ref *>'.length + 1 : 0) +
      header.length +
      values.reduce(
        (length, value, i) =>
          length + value.length + (i === 0 ? 0 : delim.length),
        0
      ) +
      footer.length

    if (values.some((value) => value.breakAlways)) {
      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.header = header
    this.footer = footer
    this.delim = delim
    this.values = values
    this.ref = ref
    this.tabulate = tabulate
  }

  toString(opts = {}) {
    const { offset = 0, indent = 0 } = opts

    const split =
      this.breakAlways ||
      (this.values.length &&
        (offset + this.length > this.breakLength ||
          indent * 2 + this.length > this.breakLength))

    let header = this.header

    if (this.ref.circular) {
      header = '<ref *' + this.ref.id + '> ' + header
    }

    if (this.values.length === 0) {
      header = header.trimEnd()
    }

    if (offset === 0) {
      header = this.indent(indent, header)
    }

    if (split) {
      header = header.trimEnd() + '\n'
    }

    let string = header

    let columns = 1
    let pad = 0

    if (this.tabulate) {
      const widest = this.values.reduce(
        (length, value) =>
          value.breakAlways ? length : Math.max(length, value.length),
        0
      )

      if (widest) {
        columns = Math.max(
          columns,
          Math.floor(
            (this.breakLength - indent * 2) / (widest + this.delim.length)
          )
        )

        if (columns > 1) pad = widest
      }
    }

    for (let i = 0, n = this.values.length, offset = 0; i < n; i++) {
      const value = this.values[i]

      if (split) {
        let part

        if (i % columns === 0 || value.breakAlways) {
          part = value.toString({ indent: indent + 1, pad })
        } else {
          part = value.toString({ pad })
        }

        string += part

        if (i < n - 1) {
          if (i % columns === columns - 1 || this.values[i + 1].breakAlways) {
            string += this.delim.trimEnd() + '\n'
          } else {
            string += this.delim
          }
        }
      } else {
        if (i > 0) string += this.delim

        string += value.toString({ offset })

        offset += value.length
      }
    }

    let footer = this.footer

    if (this.values.length === 0) {
      footer = footer.trimStart()
    }

    if (split) {
      string += '\n' + this.indent(indent, footer.trimStart())
    } else {
      string += footer
    }

    return string
  }
}

function inspectValue(value, depth, opts) {
  const type = getType(value)

  if (type.isUndefined()) return inspectUndefined(depth, opts)
  if (type.isNull()) return inspectNull(depth, opts)
  if (type.isBoolean()) return inspectBoolean(value, depth, opts)
  if (type.isNumber()) return inspectNumber(value, depth, opts)
  if (type.isBigInt()) return inspectBigInt(value, depth, opts)
  if (type.isString()) return inspectString(value, depth, opts)
  if (type.isSymbol()) return inspectSymbol(value, depth, opts)
  if (type.isObject()) return inspectObject(type, value, depth, opts)
  if (type.isFunction()) return inspectFunction(type, value, depth, opts)
  if (type.isExternal()) return inspectExternal(value, opts, opts)
}

function inspectUndefined(depth, opts) {
  return new InspectLeaf('undefined', styles.undefined, depth, opts)
}

function inspectNull(depth, opts) {
  return new InspectLeaf('null', styles.null, depth, opts)
}

function inspectBoolean(value, depth, opts) {
  return new InspectLeaf(value.toString(), styles.boolean, depth, opts)
}

function inspectNumber(value, depth, opts) {
  let string

  if (Object.is(value, -0)) {
    string = '-0'
  } else {
    string = value.toString(10)
  }

  return new InspectLeaf(string, styles.number, depth, opts)
}

function inspectBigInt(value, depth, opts) {
  return new InspectLeaf(value.toString(10) + 'n', styles.bigint, depth, opts)
}

const STRING_ESCAPES =
  /[\ud800-\udbff][\udc00-\udfff]|[\u0000-\u001f'\\\ud800-\udfff]/g

function inspectString(value, depth, opts) {
  // https://tc39.es/ecma262/multipage/structured-data.html#sec-quotejsonstring
  const string = value.replace(STRING_ESCAPES, (match) => {
    if (match.length === 2) return match

    switch (match) {
      case "'":
        return "\\'"
      case '\\':
        return '\\\\'
      case '\b':
        return '\\b'
      case '\t':
        return '\\t'
      case '\n':
        return '\\n'
      case '\f':
        return '\\f'
      case '\r':
        return '\\r'
      default:
        return '\\u' + match.charCodeAt(0).toString(16).padStart(4, '0')
    }
  })

  return new InspectLeaf("'" + string + "'", styles.string, depth, opts)
}

function inspectSymbol(value, depth, opts) {
  return new InspectLeaf(value.toString(), styles.symbol, depth, opts)
}

function inspectKey(value, depth, opts) {
  if (PLAIN_KEY.test(value)) {
    return new InspectLeaf(value, null, depth, opts)
  } else {
    return inspectValue(value, depth, opts)
  }
}

function inspectObject(type, object, depth, opts) {
  const refs = opts.references

  let ref = refs.get(object)
  if (ref === null) {
    ref = new InspectRef(depth, opts)
    refs.set(object, ref)
  } else if (ref.count) {
    ref.circular = true
    return ref
  }

  const maxDepth = typeof opts.depth === 'number' ? opts.depth : Infinity

  if (maxDepth < depth) {
    const constructor = object.constructor

    return new InspectLeaf(
      '[' +
        (constructor && constructor.name ? constructor.name : 'Object') +
        ']',
      styles.special,
      depth,
      opts
    )
  }

  const inspect =
    object[Symbol.for('bare.inspect')] ||
    object[Symbol.for('nodejs.util.inspect.custom')]

  if (typeof inspect === 'function') {
    const value = inspect.call(
      object,
      typeof opts.depth === 'number' ? opts.depth - depth : null,
      {
        colors: opts.colors,
        breakLength: opts.breakLength,
        stylize: opts.stylize
      },
      exports
    )

    if (typeof value === 'object' && value !== null) {
      refs.set(value, ref)
    }

    if (typeof value !== 'string') {
      return inspectValue(value, depth, opts)
    }

    return new InspectLeaf(value, null, depth, opts)
  }

  if (type.isArray()) return inspectArray(object, ref, depth, opts)
  if (type.isDate()) return inspectDate(object, ref, depth, opts)
  if (type.isRegExp()) return inspectRegExp(object, ref, depth, opts)
  if (type.isError()) return inspectError(object, ref, depth, opts)
  if (type.isPromise()) return inspectPromise(object, ref, depth, opts)
  if (type.isMap()) return inspectMap(object, ref, depth, opts)
  if (type.isSet()) return inspectSet(object, ref, depth, opts)
  if (type.isWeakMap()) return inspectWeakMap(object, ref, depth, opts)
  if (type.isWeakSet()) return inspectWeakSet(object, ref, depth, opts)
  if (type.isWeakRef()) return inspectWeakRef(object, ref, depth, opts)
  if (type.isArrayBuffer()) return inspectArrayBuffer(object, ref, depth, opts)
  if (type.isSharedArrayBuffer())
    return inspectSharedArrayBuffer(object, ref, depth, opts)
  if (type.isTypedArray()) return inspectTypedArray(object, ref, depth, opts)
  if (type.isDataView()) return inspectDataView(object, ref, depth, opts)

  ref.increment()

  const values = []

  for (const key in object) {
    if (key === 'constructor') continue

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(object[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  let header = '{ '

  const tag = object[Symbol.toStringTag]

  if (tag) header = '[' + tag + '] ' + header

  if (object.constructor) {
    const name = object.constructor.name

    if (name && name !== 'Object') {
      header = object.constructor.name + ' ' + header
    }
  }

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectArray(array, ref, depth, opts) {
  const { maxArrayLength = defaultMaxArrayLength } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxArrayLength, 0)

  for (let i = 0, n = array.length; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(array.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(inspectValue(array[i], depth + 1, opts))
  }

  for (const key of binding.getOwnNonIndexPropertyNames(array)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(array[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  let header = '[ '

  if (array.constructor.name !== 'Array') {
    header = array.constructor.name + '(' + array.length + ') ' + header
  }

  return new InspectSequence(header, ' ]', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectDate(date, ref, depth, opts) {
  return new InspectLeaf(date.toISOString(), styles.date, depth, opts)
}

function inspectRegExp(regExp, ref, depth, opts) {
  return new InspectLeaf(regExp.toString(), styles.regexp, depth, opts)
}

function inspectError(error, ref, depth, opts) {
  let header

  if ('stack' in error) {
    header = error.stack

    if (depth > 0) {
      header = header.replaceAll('\n', '\n' + '  '.repeat(depth))
    }
  } else {
    header = error.toString()
  }

  const builtins = ['cause']

  if (error.name === 'AggregateError') {
    builtins.push('errors')
  } else if (error.name === 'SuppressedError') {
    builtins.push('error', 'suppressed')
  }

  const values = []

  for (const key of builtins) {
    if (key in error === false) continue

    values.push(
      new InspectPair(
        ': ',
        new InspectLeaf('[' + key + ']', null, depth + 1, opts),
        inspectValue(error[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key in error) {
    if (key === 'constructor' || builtins.includes(key)) continue

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(error[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  if (values.length === 0) return new InspectLeaf(header, null, depth, opts)

  return new InspectSequence(
    header + ' {',
    ' }',
    ', ',
    values,
    ref,
    depth,
    opts
  )
}

function inspectPromise(promise, ref, depth, opts) {
  ref.increment()

  const state = binding.getPromiseState(promise)

  const values = []

  switch (state) {
    case 0: // Pending
      values.push(new InspectLeaf('<pending>', styles.special, depth, opts))
      break

    case 1: // Fulfilled
      values.push(inspectValue(binding.getPromiseResult(promise), depth, opts))
      break

    case 2: // Rejected
      values.push(
        new InspectLeaf('<rejected>', styles.special, depth, opts),
        inspectValue(binding.getPromiseResult(promise), depth, opts)
      )
  }

  ref.decrement()

  const header = promise.constructor.name + ' { '

  return new InspectSequence(header, ' }', ' ', values, ref, depth, opts)
}

function inspectMap(map, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxMapLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = maxMapLength

  for (const entry of map) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(map.size - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )
      break
    }

    values.push(
      new InspectPair(
        ' => ',
        inspectValue(entry[0], depth + 1, opts),
        inspectValue(entry[1], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key in map) {
    if (key === 'constructor') continue

    const value = inspectValue(map[key], depth + 1, opts)

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        value,
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = map.constructor.name + '(' + map.size + ') { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectSet(set, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxSetLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = maxSetLength

  for (const entry of set) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(set.size - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )
      break
    }

    values.push(inspectValue(entry, depth + 1, opts))
  }

  for (const key in set) {
    if (key === 'constructor') continue

    const value = inspectValue(set[key], depth + 1, opts)

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        value,
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = set.constructor.name + '(' + set.size + ') { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectWeakMap(weakMap, ref, depth, opts) {
  const header = weakMap.constructor.name + ' { '

  return new InspectSequence(
    header,
    ' }',
    ' ',
    [new InspectLeaf('<items unknown>', styles.special, depth + 1, opts)],
    ref,
    depth,
    opts
  )
}

function inspectWeakSet(weakSet, ref, depth, opts) {
  const header = weakSet.constructor.name + ' { '

  return new InspectSequence(
    header,
    ' }',
    ' ',
    [new InspectLeaf('<items unknown>', styles.special, depth + 1, opts)],
    ref,
    depth,
    opts
  )
}

function inspectWeakRef(weakRef, ref, depth, opts) {
  const target = weakRef.deref()

  let value

  if (target === undefined) {
    value = new InspectLeaf('<cleared>', styles.special, depth + 1, opts)
  } else {
    value = inspectValue(target, depth + 1, opts)
  }

  const header = weakRef.constructor.name + ' { '

  return new InspectSequence(header, ' }', ' ', [value], ref, depth, opts)
}

function inspectArrayBuffer(arrayBuffer, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(arrayBuffer[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = arrayBuffer.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectSharedArrayBuffer(sharedArrayBuffer, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(sharedArrayBuffer[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = sharedArrayBuffer.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectTypedArray(typedArray, ref, depth, opts) {
  if (Buffer.isBuffer(typedArray)) {
    return inspectBuffer(typedArray, ref, depth, opts)
  }

  const {
    maxArrayLength = defaultMaxArrayLength,
    maxTypedArrayLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxTypedArrayLength, 0)

  for (let i = 0, n = typedArray.length; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(typedArray.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(inspectValue(typedArray[i], depth + 1, opts))
  }

  for (const key of binding.getOwnNonIndexPropertyNames(typedArray)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(typedArray[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = typedArray.constructor.name + '(' + typedArray.length + ') [ '

  return new InspectSequence(header, ' ]', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectBuffer(buffer, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxBufferLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxBufferLength, 0)

  for (let i = 0, n = buffer.byteLength; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(buffer.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(
      new InspectLeaf(
        buffer[i].toString(16).padStart(2, '0'),
        null,
        depth + 1,
        opts
      )
    )
  }

  for (const key of binding.getOwnNonIndexPropertyNames(buffer)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(buffer[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  return new InspectSequence('<Buffer ', '>', ' ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectDataView(dataView, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength', 'byteOffset', 'buffer']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(dataView[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key of binding.getOwnNonIndexPropertyNames(dataView)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(dataView[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = dataView.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectFunction(type, fn, depth, opts) {
  if (fn.toString().startsWith('class')) return inspectClass(fn, depth, opts)

  let tag = 'function'

  if (type.isGeneratorFunction()) tag = 'generator ' + tag
  if (type.isAsyncFunction()) tag = 'async ' + tag

  return new InspectLeaf(
    '[' + tag + ' ' + (fn.name ? fn.name : '(anonymous)') + ']',
    styles.special,
    depth,
    opts
  )
}

function inspectClass(ctor, depth, opts) {
  return new InspectLeaf(
    '[class ' + (ctor.name ? ctor.name : '(anonymous)') + ']',
    styles.special,
    depth,
    opts
  )
}

function inspectExternal(external, depth, opts) {
  return new InspectLeaf(
    '[external 0x' + binding.getExternal(external).toString(16) + ']',
    styles.special,
    depth,
    opts
  )
}
{
  "name": "bare-inspect",
  "version": "3.1.4",
  "description": "Inspect objects as strings for debugging",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-inspect.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-inspect/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-inspect#readme",
  "engines": {
    "bare": ">=1.18.0"
  },
  "dependencies": {
    "bare-ansi-escapes": "^2.1.0",
    "bare-type": "^1.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
module.exports = require.addon()
const binding = require('./binding')
const errors = require('./lib/errors')
const constants = require('./lib/constants')

exports.constants = constants
exports.errors = errors

exports.EOL = binding.platform === 'win32' ? '\r\n' : '\n'

exports.devNull = binding.platform === 'win32' ? '\\\\.\\nul' : '/dev/null'

exports.platform = function platform() {
  return binding.platform
}

exports.arch = function arch() {
  return binding.arch
}

exports.type = binding.type
exports.version = binding.version
exports.release = binding.release
exports.machine = binding.machine
exports.execPath = binding.execPath
exports.pid = binding.pid
exports.ppid = binding.ppid
exports.cwd = binding.cwd
exports.chdir = binding.chdir
exports.tmpdir = binding.tmpdir
exports.homedir = binding.homedir
exports.hostname = binding.hostname
exports.userInfo = binding.userInfo
exports.groupInfo = binding.groupInfo

exports.networkInterfaces = function networkInterfaces() {
  const result = {}

  for (const entry of binding.networkInterfaces()) {
    const { name, ...properties } = entry

    if (result[name]) result[name].push(properties)
    else result[name] = [properties]
  }

  return result
}

exports.kill = function kill(pid, signal = constants.signals.SIGTERM) {
  if (typeof signal === 'string') {
    if (signal in constants.signals === false) {
      throw errors.UNKNOWN_SIGNAL('Unknown signal: ' + signal)
    }

    signal = constants.signals[signal]
  }

  binding.kill(pid, signal)
}

exports.endianness = function endianness() {
  return binding.isLittleEndian ? 'LE' : 'BE'
}

exports.availableParallelism = binding.availableParallelism

exports.cpuUsage = function cpuUsage(previous) {
  const current = binding.cpuUsage()

  if (previous) {
    return {
      user: current.user - previous.user,
      system: current.system - previous.system
    }
  }

  return current
}

exports.threadCpuUsage = function threadCpuUsage(previous) {
  const current = binding.threadCpuUsage()

  if (previous) {
    return {
      user: current.user - previous.user,
      system: current.system - previous.system
    }
  }

  return current
}

exports.resourceUsage = binding.resourceUsage
exports.memoryUsage = binding.memoryUsage
exports.freemem = binding.freemem
exports.totalmem = binding.totalmem
exports.availableMemory = binding.availableMemory
exports.constrainedMemory = binding.constrainedMemory
exports.uptime = binding.uptime
exports.loadavg = binding.loadavg
exports.cpus = binding.cpus

exports.getProcessTitle = binding.getProcessTitle

exports.setProcessTitle = function setProcessTitle(title) {
  if (typeof title !== 'string') title = title.toString()

  if (title.length >= 256) {
    throw errors.TITLE_OVERFLOW('Process title is too long')
  }

  binding.setProcessTitle(title)
}

exports.getPriority = function getPriority(pid = 0) {
  return binding.getPriority(pid)
}

exports.setPriority = function setPriority(pid, priority) {
  if (priority === undefined) {
    priority = pid
    pid = 0
  }

  binding.setPriority(pid, priority)
}

exports.getEnvKeys = binding.getEnvKeys
exports.getEnv = binding.getEnv
exports.hasEnv = binding.hasEnv
exports.setEnv = binding.setEnv
exports.unsetEnv = binding.unsetEnv
const binding = require('../binding')

module.exports = {
  signals: binding.signals,
  errnos: binding.errnos,
  priority: binding.priority
}
module.exports = class OSError extends Error {
  constructor(msg, fn = OSError, code = fn.name) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'OSError'
  }

  static UNKNOWN_SIGNAL(msg) {
    return new OSError(msg, OSError.UNKNOWN_SIGNAL)
  }

  static TITLE_OVERFLOW(msg) {
    return new OSError(msg, OSError.TITLE_OVERFLOW)
  }
}
{
  "name": "bare-os",
  "version": "3.9.1",
  "description": "Operating system utilities for Bare",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    },
    "./errors": {
      "types": "./lib/errors.d.ts",
      "default": "./lib/errors.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-os.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-os/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-os#readme",
  "engines": {
    "bare": ">=1.14.0"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "cmake-bare": "^1.1.6",
    "lunte": "^1.6.0",
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
// This export SHOULD NOT be shortened in any way as having the full
// `module.exports = require(...)` statement is crucial for synthesizing
// ESM exports.

if (Bare.platform === 'win32') {
  module.exports = require('./lib/win32')
} else {
  module.exports = require('./lib/posix')
}
module.exports = {
  CHAR_UPPERCASE_A: 0x41,
  CHAR_LOWERCASE_A: 0x61,
  CHAR_UPPERCASE_Z: 0x5a,
  CHAR_LOWERCASE_Z: 0x7a,
  CHAR_DOT: 0x2e,
  CHAR_FORWARD_SLASH: 0x2f,
  CHAR_BACKWARD_SLASH: 0x5c,
  CHAR_COLON: 0x3a,
  CHAR_QUESTION_MARK: 0x3f
}
const os = require('bare-os')

const { normalizeString } = require('./shared')
const { CHAR_DOT, CHAR_FORWARD_SLASH } = require('./constants')

function isPosixPathSeparator(code) {
  return code === CHAR_FORWARD_SLASH
}

exports.win32 = require('./win32')
exports.posix = exports

exports.sep = '/'
exports.delimiter = ':'

exports.resolve = function resolve(...args) {
  let resolvedPath = ''
  let resolvedAbsolute = false

  for (let i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) {
    const path = i >= 0 ? args[i] : os.cwd()

    if (path.length === 0) {
      continue
    }

    resolvedPath = `${path}/${resolvedPath}`
    resolvedAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH
  }

  resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute, '/', isPosixPathSeparator)

  if (resolvedAbsolute) {
    return `/${resolvedPath}`
  }

  return resolvedPath.length > 0 ? resolvedPath : '.'
}

exports.normalize = function normalize(path) {
  if (path.length === 0) return '.'

  const isAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH
  const trailingSeparator = path.charCodeAt(path.length - 1) === CHAR_FORWARD_SLASH

  path = normalizeString(path, !isAbsolute, '/', isPosixPathSeparator)

  if (path.length === 0) {
    if (isAbsolute) return '/'
    return trailingSeparator ? './' : '.'
  }

  if (trailingSeparator) path += '/'

  return isAbsolute ? `/${path}` : path
}

exports.isAbsolute = function isAbsolute(path) {
  return path.length > 0 && path.charCodeAt(0) === CHAR_FORWARD_SLASH
}

exports.join = function join(...args) {
  if (args.length === 0) return '.'
  let joined
  for (let i = 0; i < args.length; ++i) {
    const arg = args[i]
    if (arg.length > 0) {
      if (joined === undefined) joined = arg
      else joined += `/${arg}`
    }
  }
  if (joined === undefined) return '.'
  return exports.normalize(joined)
}

exports.relative = function relative(from, to) {
  if (from === to) return ''

  from = exports.resolve(from)
  to = exports.resolve(to)

  if (from === to) return ''

  const fromStart = 1
  const fromEnd = from.length
  const fromLen = fromEnd - fromStart
  const toStart = 1
  const toLen = to.length - toStart

  const length = fromLen < toLen ? fromLen : toLen
  let lastCommonSep = -1
  let i = 0
  for (; i < length; i++) {
    const fromCode = from.charCodeAt(fromStart + i)
    if (fromCode !== to.charCodeAt(toStart + i)) {
      break
    } else if (fromCode === CHAR_FORWARD_SLASH) {
      lastCommonSep = i
    }
  }
  if (i === length) {
    if (toLen > length) {
      if (to.charCodeAt(toStart + i) === CHAR_FORWARD_SLASH) {
        return to.substring(toStart + i + 1)
      }
      if (i === 0) {
        return to.substring(toStart + i)
      }
    } else if (fromLen > length) {
      if (from.charCodeAt(fromStart + i) === CHAR_FORWARD_SLASH) {
        lastCommonSep = i
      } else if (i === 0) {
        lastCommonSep = 0
      }
    }
  }

  let out = ''
  for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
    if (i === fromEnd || from.charCodeAt(i) === CHAR_FORWARD_SLASH) {
      out += out.length === 0 ? '..' : '/..'
    }
  }

  return `${out}${to.substring(toStart + lastCommonSep)}`
}

exports.toNamespacedPath = function toNamespacedPath(path) {
  return path
}

exports.dirname = function dirname(path) {
  if (path.length === 0) return '.'
  const hasRoot = path.charCodeAt(0) === CHAR_FORWARD_SLASH
  let end = -1
  let matchedSlash = true
  for (let i = path.length - 1; i >= 1; --i) {
    if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) {
      if (!matchedSlash) {
        end = i
        break
      }
    } else {
      matchedSlash = false
    }
  }

  if (end === -1) return hasRoot ? '/' : '.'
  if (hasRoot && end === 1) return '//'
  return path.substring(0, end)
}

exports.basename = function basename(path, suffix) {
  let start = 0
  let end = -1
  let matchedSlash = true

  if (suffix !== undefined && suffix.length > 0 && suffix.length <= path.length) {
    if (suffix === path) {
      return ''
    }
    let extIdx = suffix.length - 1
    let firstNonSlashEnd = -1
    for (let i = path.length - 1; i >= 0; --i) {
      const code = path.charCodeAt(i)
      if (code === CHAR_FORWARD_SLASH) {
        if (!matchedSlash) {
          start = i + 1
          break
        }
      } else {
        if (firstNonSlashEnd === -1) {
          matchedSlash = false
          firstNonSlashEnd = i + 1
        }
        if (extIdx >= 0) {
          if (code === suffix.charCodeAt(extIdx)) {
            if (--extIdx === -1) {
              end = i
            }
          } else {
            extIdx = -1
            end = firstNonSlashEnd
          }
        }
      }
    }

    if (start === end) end = firstNonSlashEnd
    else if (end === -1) end = path.length
    return path.substring(start, end)
  }

  for (let i = path.length - 1; i >= 0; --i) {
    if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) {
      if (!matchedSlash) {
        start = i + 1
        break
      }
    } else if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
  }

  if (end === -1) return ''
  return path.substring(start, end)
}

exports.extname = function extname(path) {
  let startDot = -1
  let startPart = 0
  let end = -1
  let matchedSlash = true
  let preDotState = 0
  for (let i = path.length - 1; i >= 0; --i) {
    const code = path.charCodeAt(i)
    if (code === CHAR_FORWARD_SLASH) {
      if (!matchedSlash) {
        startPart = i + 1
        break
      }
      continue
    }
    if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
    if (code === CHAR_DOT) {
      if (startDot === -1) startDot = i
      else if (preDotState !== 1) preDotState = 1
    } else if (startDot !== -1) {
      preDotState = -1
    }
  }

  if (
    startDot === -1 ||
    end === -1 ||
    preDotState === 0 ||
    (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1)
  ) {
    return ''
  }
  return path.substring(startDot, end)
}
const { CHAR_DOT, CHAR_FORWARD_SLASH } = require('./constants')

exports.normalizeString = function normalizeString(
  path,
  allowAboveRoot,
  separator,
  isPathSeparator
) {
  let res = ''
  let lastSegmentLength = 0
  let lastSlash = -1
  let dots = 0
  let code = 0
  for (let i = 0; i <= path.length; ++i) {
    if (i < path.length) {
      code = path.charCodeAt(i)
    } else if (isPathSeparator(code)) {
      break
    } else {
      code = CHAR_FORWARD_SLASH
    }

    if (isPathSeparator(code)) {
      if (lastSlash === i - 1 || dots === 1);
      else if (dots === 2) {
        if (
          res.length < 2 ||
          lastSegmentLength !== 2 ||
          res.charCodeAt(res.length - 1) !== CHAR_DOT ||
          res.charCodeAt(res.length - 2) !== CHAR_DOT
        ) {
          if (res.length > 2) {
            const lastSlashIndex = res.lastIndexOf(separator)
            if (lastSlashIndex === -1) {
              res = ''
              lastSegmentLength = 0
            } else {
              res = res.substring(0, lastSlashIndex)
              lastSegmentLength = res.length - 1 - res.lastIndexOf(separator)
            }
            lastSlash = i
            dots = 0
            continue
          } else if (res.length !== 0) {
            res = ''
            lastSegmentLength = 0
            lastSlash = i
            dots = 0
            continue
          }
        }
        if (allowAboveRoot) {
          res += res.length > 0 ? `${separator}..` : '..'
          lastSegmentLength = 2
        }
      } else {
        if (res.length > 0) {
          res += `${separator}${path.substring(lastSlash + 1, i)}`
        } else {
          res = path.substring(lastSlash + 1, i)
        }
        lastSegmentLength = i - lastSlash - 1
      }
      lastSlash = i
      dots = 0
    } else if (code === CHAR_DOT && dots !== -1) {
      ++dots
    } else {
      dots = -1
    }
  }
  return res
}
const os = require('bare-os')

const { normalizeString } = require('./shared')
const {
  CHAR_UPPERCASE_A,
  CHAR_LOWERCASE_A,
  CHAR_UPPERCASE_Z,
  CHAR_LOWERCASE_Z,
  CHAR_DOT,
  CHAR_FORWARD_SLASH,
  CHAR_BACKWARD_SLASH,
  CHAR_COLON,
  CHAR_QUESTION_MARK
} = require('./constants')

function isWindowsPathSeparator(code) {
  return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH
}

function isWindowsDeviceRoot(code) {
  return (
    (code >= CHAR_UPPERCASE_A && code <= CHAR_UPPERCASE_Z) ||
    (code >= CHAR_LOWERCASE_A && code <= CHAR_LOWERCASE_Z)
  )
}

exports.posix = require('./posix')
exports.win32 = exports

exports.sep = '\\'
exports.delimiter = ';'

exports.resolve = function resolve(...args) {
  let resolvedDevice = ''
  let resolvedTail = ''
  let resolvedAbsolute = false

  for (let i = args.length - 1; i >= -1; i--) {
    let path
    if (i >= 0) {
      path = args[i]

      if (path.length === 0) continue
    } else if (resolvedDevice.length === 0) {
      path = os.cwd()
    } else {
      path = os.getEnv(`=${resolvedDevice}`) || os.cwd()

      if (
        path === undefined ||
        (path.substring(0, 2).toLowerCase() !== resolvedDevice.toLowerCase() &&
          path.charCodeAt(2) === CHAR_BACKWARD_SLASH)
      ) {
        path = `${resolvedDevice}\\`
      }
    }

    const len = path.length
    let rootEnd = 0
    let device = ''
    let isAbsolute = false
    const code = path.charCodeAt(0)

    if (len === 1) {
      if (isWindowsPathSeparator(code)) {
        rootEnd = 1
        isAbsolute = true
      }
    } else if (isWindowsPathSeparator(code)) {
      isAbsolute = true

      if (isWindowsPathSeparator(path.charCodeAt(1))) {
        let j = 2
        let last = j
        while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
          j++
        }
        if (j < len && j !== last) {
          const firstPart = path.substring(last, j)
          last = j
          while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
            j++
          }
          if (j < len && j !== last) {
            last = j
            while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
              j++
            }
            if (j === len || j !== last) {
              device = `\\\\${firstPart}\\${path.substring(last, j)}`
              rootEnd = j
            }
          }
        }
      } else {
        rootEnd = 1
      }
    } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
      device = path.substring(0, 2)
      rootEnd = 2
      if (len > 2 && isWindowsPathSeparator(path.charCodeAt(2))) {
        isAbsolute = true
        rootEnd = 3
      }
    }

    if (device.length > 0) {
      if (resolvedDevice.length > 0) {
        if (device.toLowerCase() !== resolvedDevice.toLowerCase()) {
          continue
        }
      } else {
        resolvedDevice = device
      }
    }

    if (resolvedAbsolute) {
      if (resolvedDevice.length > 0) {
        break
      }
    } else {
      resolvedTail = `${path.substring(rootEnd)}\\${resolvedTail}`
      resolvedAbsolute = isAbsolute
      if (isAbsolute && resolvedDevice.length > 0) {
        break
      }
    }
  }

  resolvedTail = normalizeString(resolvedTail, !resolvedAbsolute, '\\', isWindowsPathSeparator)

  return resolvedAbsolute
    ? `${resolvedDevice}\\${resolvedTail}`
    : `${resolvedDevice}${resolvedTail}` || '.'
}

exports.normalize = function normalize(path) {
  const len = path.length
  if (len === 0) return '.'
  let rootEnd = 0
  let device
  let isAbsolute = false
  const code = path.charCodeAt(0)

  if (len === 1) {
    return code === CHAR_FORWARD_SLASH ? '\\' : path
  }

  if (isWindowsPathSeparator(code)) {
    isAbsolute = true

    if (isWindowsPathSeparator(path.charCodeAt(1))) {
      let j = 2
      let last = j
      while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
        j++
      }
      if (j < len && j !== last) {
        const firstPart = path.substring(last, j)
        last = j
        while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
          j++
        }
        if (j < len && j !== last) {
          last = j
          while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
            j++
          }
          if (j === len) {
            return `\\\\${firstPart}\\${path.substring(last)}\\`
          }
          if (j !== last) {
            device = `\\\\${firstPart}\\${path.substring(last, j)}`
            rootEnd = j
          }
        }
      }
    } else {
      rootEnd = 1
    }
  } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
    device = path.substring(0, 2)
    rootEnd = 2
    if (len > 2 && isWindowsPathSeparator(path.charCodeAt(2))) {
      isAbsolute = true
      rootEnd = 3
    }
  }

  let tail =
    rootEnd < len
      ? normalizeString(path.substring(rootEnd), !isAbsolute, '\\', isWindowsPathSeparator)
      : ''
  if (tail.length === 0 && !isAbsolute) {
    tail = '.'
  }
  if (tail.length > 0 && isWindowsPathSeparator(path.charCodeAt(len - 1))) {
    tail += '\\'
  }
  if (device === undefined) {
    return isAbsolute ? `\\${tail}` : tail
  }
  return isAbsolute ? `${device}\\${tail}` : `${device}${tail}`
}

exports.isAbsolute = function isAbsolute(path) {
  const len = path.length
  if (len === 0) return false

  const code = path.charCodeAt(0)

  return (
    isWindowsPathSeparator(code) ||
    (len > 2 &&
      isWindowsDeviceRoot(code) &&
      path.charCodeAt(1) === CHAR_COLON &&
      isWindowsPathSeparator(path.charCodeAt(2)))
  )
}

exports.join = function join(...args) {
  if (args.length === 0) return '.'

  let joined
  let firstPart
  for (let i = 0; i < args.length; ++i) {
    const arg = args[i]
    if (arg.length > 0) {
      if (joined === undefined) joined = firstPart = arg
      else joined += `\\${arg}`
    }
  }

  if (joined === undefined) return '.'

  let needsReplace = true
  let slashCount = 0
  if (isWindowsPathSeparator(firstPart.charCodeAt(0))) {
    ++slashCount
    const firstLen = firstPart.length
    if (firstLen > 1 && isWindowsPathSeparator(firstPart.charCodeAt(1))) {
      ++slashCount
      if (firstLen > 2) {
        if (isWindowsPathSeparator(firstPart.charCodeAt(2))) {
          ++slashCount
        } else {
          needsReplace = false
        }
      }
    }
  }
  if (needsReplace) {
    while (slashCount < joined.length && isWindowsPathSeparator(joined.charCodeAt(slashCount))) {
      slashCount++
    }

    if (slashCount >= 2) {
      joined = `\\${joined.substring(slashCount)}`
    }
  }

  return exports.normalize(joined)
}

exports.relative = function relative(from, to) {
  if (from === to) return ''

  const fromOrig = exports.resolve(from)
  const toOrig = exports.resolve(to)

  if (fromOrig === toOrig) return ''

  from = fromOrig.toLowerCase()
  to = toOrig.toLowerCase()

  if (from === to) return ''

  let fromStart = 0
  while (fromStart < from.length && from.charCodeAt(fromStart) === CHAR_BACKWARD_SLASH) {
    fromStart++
  }
  let fromEnd = from.length
  while (fromEnd - 1 > fromStart && from.charCodeAt(fromEnd - 1) === CHAR_BACKWARD_SLASH) {
    fromEnd--
  }
  const fromLen = fromEnd - fromStart

  let toStart = 0
  while (toStart < to.length && to.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) {
    toStart++
  }
  let toEnd = to.length
  while (toEnd - 1 > toStart && to.charCodeAt(toEnd - 1) === CHAR_BACKWARD_SLASH) {
    toEnd--
  }
  const toLen = toEnd - toStart

  const length = fromLen < toLen ? fromLen : toLen
  let lastCommonSep = -1
  let i = 0
  for (; i < length; i++) {
    const fromCode = from.charCodeAt(fromStart + i)
    if (fromCode !== to.charCodeAt(toStart + i)) {
      break
    } else if (fromCode === CHAR_BACKWARD_SLASH) {
      lastCommonSep = i
    }
  }

  if (i !== length) {
    if (lastCommonSep === -1) return toOrig
  } else {
    if (toLen > length) {
      if (to.charCodeAt(toStart + i) === CHAR_BACKWARD_SLASH) {
        return toOrig.substring(toStart + i + 1)
      }
      if (i === 2) {
        return toOrig.substring(toStart + i)
      }
    }
    if (fromLen > length) {
      if (from.charCodeAt(fromStart + i) === CHAR_BACKWARD_SLASH) {
        lastCommonSep = i
      } else if (i === 2) {
        lastCommonSep = 3
      }
    }
    if (lastCommonSep === -1) lastCommonSep = 0
  }

  let out = ''
  for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
    if (i === fromEnd || from.charCodeAt(i) === CHAR_BACKWARD_SLASH) {
      out += out.length === 0 ? '..' : '\\..'
    }
  }

  toStart += lastCommonSep

  if (out.length > 0) {
    return `${out}${toOrig.substring(toStart, toEnd)}`
  }
  if (toOrig.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) {
    ++toStart
  }
  return toOrig.substring(toStart, toEnd)
}

exports.toNamespacedPath = function toNamespacedPath(path) {
  if (path.length === 0) return path

  const resolvedPath = exports.resolve(path)

  if (resolvedPath.length <= 2) return path

  if (resolvedPath.charCodeAt(0) === CHAR_BACKWARD_SLASH) {
    if (resolvedPath.charCodeAt(1) === CHAR_BACKWARD_SLASH) {
      const code = resolvedPath.charCodeAt(2)
      if (code !== CHAR_QUESTION_MARK && code !== CHAR_DOT) {
        return `\\\\?\\UNC\\${resolvedPath.substring(2)}`
      }
    }
  } else if (
    isWindowsDeviceRoot(resolvedPath.charCodeAt(0)) &&
    resolvedPath.charCodeAt(1) === CHAR_COLON &&
    resolvedPath.charCodeAt(2) === CHAR_BACKWARD_SLASH
  ) {
    return `\\\\?\\${resolvedPath}`
  }

  return path
}

exports.dirname = function dirname(path) {
  const len = path.length
  if (len === 0) return '.'
  let rootEnd = -1
  let offset = 0
  const code = path.charCodeAt(0)

  if (len === 1) {
    return isWindowsPathSeparator(code) ? path : '.'
  }

  if (isWindowsPathSeparator(code)) {
    rootEnd = offset = 1

    if (isWindowsPathSeparator(path.charCodeAt(1))) {
      let j = 2
      let last = j
      while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
        j++
      }
      if (j < len && j !== last) {
        last = j
        while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
          j++
        }
        if (j < len && j !== last) {
          last = j
          while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
            j++
          }
          if (j === len) {
            return path
          }
          if (j !== last) {
            rootEnd = offset = j + 1
          }
        }
      }
    }
  } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
    rootEnd = len > 2 && isWindowsPathSeparator(path.charCodeAt(2)) ? 3 : 2
    offset = rootEnd
  }

  let end = -1
  let matchedSlash = true
  for (let i = len - 1; i >= offset; --i) {
    if (isWindowsPathSeparator(path.charCodeAt(i))) {
      if (!matchedSlash) {
        end = i
        break
      }
    } else {
      matchedSlash = false
    }
  }

  if (end === -1) {
    if (rootEnd === -1) return '.'

    end = rootEnd
  }
  return path.substring(0, end)
}

exports.basename = function basename(path, suffix) {
  let start = 0
  let end = -1
  let matchedSlash = true

  if (
    path.length >= 2 &&
    isWindowsDeviceRoot(path.charCodeAt(0)) &&
    path.charCodeAt(1) === CHAR_COLON
  ) {
    start = 2
  }

  if (suffix !== undefined && suffix.length > 0 && suffix.length <= path.length) {
    if (suffix === path) return ''
    let extIdx = suffix.length - 1
    let firstNonSlashEnd = -1
    for (let i = path.length - 1; i >= start; --i) {
      const code = path.charCodeAt(i)
      if (isWindowsPathSeparator(code)) {
        if (!matchedSlash) {
          start = i + 1
          break
        }
      } else {
        if (firstNonSlashEnd === -1) {
          matchedSlash = false
          firstNonSlashEnd = i + 1
        }
        if (extIdx >= 0) {
          if (code === suffix.charCodeAt(extIdx)) {
            if (--extIdx === -1) {
              end = i
            }
          } else {
            extIdx = -1
            end = firstNonSlashEnd
          }
        }
      }
    }

    if (start === end) end = firstNonSlashEnd
    else if (end === -1) end = path.length
    return path.substring(start, end)
  }
  for (let i = path.length - 1; i >= start; --i) {
    if (isWindowsPathSeparator(path.charCodeAt(i))) {
      if (!matchedSlash) {
        start = i + 1
        break
      }
    } else if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
  }

  if (end === -1) return ''
  return path.substring(start, end)
}

exports.extname = function extname(path) {
  let start = 0
  let startDot = -1
  let startPart = 0
  let end = -1
  let matchedSlash = true
  let preDotState = 0

  if (
    path.length >= 2 &&
    path.charCodeAt(1) === CHAR_COLON &&
    isWindowsDeviceRoot(path.charCodeAt(0))
  ) {
    start = startPart = 2
  }

  for (let i = path.length - 1; i >= start; --i) {
    const code = path.charCodeAt(i)
    if (isWindowsPathSeparator(code)) {
      if (!matchedSlash) {
        startPart = i + 1
        break
      }
      continue
    }
    if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
    if (code === CHAR_DOT) {
      if (startDot === -1) startDot = i
      else if (preDotState !== 1) preDotState = 1
    } else if (startDot !== -1) {
      preDotState = -1
    }
  }

  if (
    startDot === -1 ||
    end === -1 ||
    preDotState === 0 ||
    (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1)
  ) {
    return ''
  }
  return path.substring(startDot, end)
}
{
  "name": "bare-path",
  "version": "3.0.1",
  "description": "Path manipulation library for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./posix": "./lib/posix.js",
    "./win32": "./lib/win32.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "lib",
    "NOTICE"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-path.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-path/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-path#readme",
  "dependencies": {
    "bare-os": "^3.0.1"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "lunte": "^1.8.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
const b4a = require('b4a')
const stream = require('streamx')
const { ReadableStream, WritableStream } = require('./web')

const defaultEncoding = 'utf8'

module.exports = exports = stream.Stream

exports.pipeline = stream.pipeline

exports.isStream = stream.isStream
exports.isEnding = stream.isEnding
exports.isEnded = stream.isEnded
exports.isFinishing = stream.isFinishing
exports.isFinished = stream.isFinished
exports.isDisturbed = stream.isDisturbed

exports.isErrored = function isErrored(stream) {
  return exports.getStreamError(stream) !== null
}

exports.isReadable = function isReadable(stream) {
  return stream.readable && !stream.destroying && !exports.isEnded(stream)
}

exports.isWritable = function isWritable(stream) {
  return stream.writable && !stream.destroying && !exports.isFinishing(stream)
}

exports.getStreamError = stream.getStreamError

exports.addAbortSignal = function addAbortSignal(signal, stream) {
  function onAbort() {
    stream.destroy(signal.reason)
  }

  if (signal.aborted) onAbort()
  else signal.addEventListener('abort', onAbort)

  return stream
}

exports.Stream = exports

exports.Readable = class Readable extends stream.Readable {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthReadable: null,
      map: null,
      mapReadable: null
    })

    if (this._construct) this._open = this._construct

    if (this._read !== stream.Readable.prototype._read) {
      this._read = read.bind(this, this._read)
    }

    if (this._destroy !== stream.Stream.prototype._destroy) {
      this._destroy = destroy.bind(this, this._destroy)
    }
  }

  get closed() {
    return !exports.isReadable(this)
  }

  get errored() {
    return stream.getStreamError(this)
  }

  push(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    return super.push(chunk)
  }

  unshift(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    super.unshift(chunk)
  }

  static fromWeb(readableStream, opts = {}) {
    const stream = readableStream._stream

    if (opts.encoding) stream.setEncoding(opts.encoding)
    if (opts.signal) exports.addAbortSignal(opts.signal, stream)

    return stream
  }

  static toWeb(readable, opts = {}) {
    return new ReadableStream(readable, opts.strategy)
  }

  async [Symbol.asyncDispose]() {
    if (!this.destroyed) this.destroy()

    await new Promise((resolve) => exports.finished(this, resolve))
  }
}

exports.Writable = class Writable extends stream.Writable {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthWritable,
      map: null,
      mapWritable: null
    })

    if (this._construct) this._open = this._construct

    if (this._write !== stream.Writable.prototype._write) {
      this._write = write.bind(this, this._write)
    }

    if (this._destroy !== stream.Stream.prototype._destroy) {
      this._destroy = destroy.bind(this, this._destroy)
    }
  }

  get closed() {
    return !exports.isWritable(this)
  }

  get errored() {
    return stream.getStreamError(this)
  }

  write(chunk, encoding, cb) {
    if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result = super.write({ chunk, encoding })

    if (cb) stream.Writable.drained(this).then(() => cb(null), cb)

    return result
  }

  end(chunk, encoding, cb) {
    if (typeof chunk === 'function') {
      cb = chunk
      chunk = null
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    } else {
      encoding = 'buffer'
    }

    const result =
      chunk !== undefined && chunk !== null ? super.end({ chunk, encoding }) : super.end()

    if (cb) this.once('finish', () => cb(null))

    return result
  }

  static fromWeb(writableStream, opts = {}) {
    const stream = writableStream._stream

    if (opts.signal) exports.addAbortSignal(opts.signal, stream)

    return stream
  }

  static toWeb(writable) {
    return new WritableStream(writable)
  }

  async [Symbol.asyncDispose]() {
    if (!this.destroyed) this.destroy()

    await new Promise((resolve) => exports.finished(this, resolve))
  }
}

exports.Duplex = class Duplex extends stream.Duplex {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthReadable: null,
      byteLengthWritable,
      map: null,
      mapReadable: null,
      mapWritable: null
    })

    if (this._construct) this._open = this._construct

    if (this._read !== stream.Readable.prototype._read) {
      this._read = read.bind(this, this._read)
    }

    if (this._write !== stream.Duplex.prototype._write) {
      this._write = write.bind(this, this._write)
    }

    if (this._destroy !== stream.Stream.prototype._destroy) {
      this._destroy = destroy.bind(this, this._destroy)
    }
  }

  push(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    return super.push(chunk)
  }

  unshift(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    super.unshift(chunk)
  }

  write(chunk, encoding, cb) {
    if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result = super.write({ chunk, encoding })

    if (cb) stream.Writable.drained(this).then(() => cb(null), cb)

    return result
  }

  end(chunk, encoding, cb) {
    if (typeof chunk === 'function') {
      cb = chunk
      chunk = null
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result =
      chunk !== undefined && chunk !== null ? super.end({ chunk, encoding }) : super.end()

    if (cb) this.once('finish', () => cb(null))

    return result
  }

  static fromWeb({ readable: readableStream, writable: writableStream }, opts) {
    const readable = exports.Readable.fromWeb(readableStream, opts)
    const writable = exports.Writable.fromWeb(writableStream, opts)

    const duplex = new exports.Duplex({
      write(data, encoding, cb) {
        writable.write(data, encoding, cb)
      }
    })

    readable
      .on('data', (data) => duplex.push(data))
      .on('end', () => duplex.push(null))
      .on('error', (err) => duplex.destroy(err))

    writable.on('finish', () => duplex.end()).on('error', (err) => duplex.destroy(err))

    return duplex
  }

  static toWeb(duplex) {
    const readableStream = exports.Readable.toWeb(duplex)
    const writableStream = exports.Writable.toWeb(duplex)

    return { readable: readableStream, writable: writableStream }
  }
}

class DuplexSide extends exports.Duplex {
  constructor(opts) {
    super(opts)

    this._otherSide = null
    this._cb = null
  }

  _read() {
    const cb = this._cb
    if (!cb) return

    this._cb = null
    cb()
  }

  _write(chunk, encoding, cb) {
    this._otherSide.push(chunk, encoding)
    this._otherSide._cb = cb
  }

  _final(cb) {
    this._otherSide.on('end', cb)
    this._otherSide.push(null)
  }
}

exports.duplexPair = function duplexPair(opts) {
  const sideA = new DuplexSide(opts)
  const sideB = new DuplexSide(opts)

  sideA._otherSide = sideB
  sideB._otherSide = sideA

  return [sideA, sideB]
}

exports.Transform = class Transform extends stream.Transform {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthReadable: null,
      byteLengthWritable,
      map: null,
      mapReadable: null,
      mapWritable: null
    })

    if (this._transform !== stream.Transform.prototype._transform) {
      this._transform = transform.bind(this, this._transform)
    } else {
      this._transform = passthrough
    }
  }

  push(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    return super.push(chunk)
  }

  unshift(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = b4a.from(chunk, encoding || defaultEncoding)
    }

    super.unshift(chunk)
  }

  write(chunk, encoding, cb) {
    if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result = super.write({ chunk, encoding })

    if (cb) stream.Writable.drained(this).then(() => cb(null), cb)

    return result
  }

  end(chunk, encoding, cb) {
    if (typeof chunk === 'function') {
      cb = chunk
      chunk = null
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = b4a.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result =
      chunk !== undefined && chunk !== null ? super.end({ chunk, encoding }) : super.end()

    if (cb) this.once('finish', () => cb(null))

    return result
  }
}

exports.PassThrough = class PassThrough extends exports.Transform {}

exports.finished = function finished(stream, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (!opts) opts = {}

  const { cleanup = false } = opts

  const done = () => {
    cb(exports.getStreamError(stream, { all: true }))

    if (cleanup) detach()
  }

  const detach = () => {
    stream.off('close', done)
    stream.off('error', noop)
  }

  if (stream.destroyed) {
    done()
  } else {
    stream.on('close', done)
    stream.on('error', noop)
  }

  return detach
}

function read(read, cb) {
  read.call(this, 65536)

  cb(null)
}

function write(write, data, cb) {
  write.call(this, data.chunk, data.encoding, cb)
}

function transform(transform, data, cb) {
  transform.call(this, data.chunk, data.encoding, cb)
}

function destroy(destroy, cb) {
  destroy.call(this, exports.getStreamError(this), cb)
}

function passthrough(data, cb) {
  cb(null, data.chunk)
}

function byteLengthWritable(data) {
  return data.chunk.byteLength
}

function noop() {}
{
  "name": "bare-stream",
  "version": "2.13.3",
  "description": "Streaming data for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./promises": "./promises.js",
    "./web": {
      "types": "./web.d.ts",
      "default": "./web.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "promises.js",
    "web.js",
    "web.d.ts",
    "global.js",
    "global.d.ts"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-stream.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-stream/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-stream#readme",
  "dependencies": {
    "b4a": "^1.8.1",
    "streamx": "^2.25.0",
    "teex": "^1.0.1"
  },
  "devDependencies": {
    "bare-abort-controller": "^1.1.0",
    "bare-buffer": "^3.0.0",
    "bare-events": "^2.5.4",
    "brittle": "^3.5.2",
    "lunte": "^1.6.0",
    "prettier": "^3.3.3",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "bare-abort-controller": "*",
    "bare-buffer": "*",
    "bare-events": "*"
  },
  "peerDependenciesMeta": {
    "bare-abort-controller": {
      "optional": true
    },
    "bare-buffer": {
      "optional": true
    },
    "bare-events": {
      "optional": true
    }
  }
}
const { Readable, Writable, Transform, getStreamError, isStreamx, isDisturbed } = require('streamx')
const tee = require('teex')

const readableKind = Symbol.for('bare.stream.readable.kind')
const writableKind = Symbol.for('bare.stream.writable.kind')
const transformKind = Symbol.for('bare.stream.transform.kind')

// https://streams.spec.whatwg.org/#readablestreamdefaultreader
exports.ReadableStreamDefaultReader = class ReadableStreamDefaultReader {
  constructor(stream) {
    this._stream = stream
    this._stream._stream.once('close', onclose).once('error', onerror)

    const closed = Promise.withResolvers()

    // Avoid unhandled exceptions
    closed.promise.catch(noop)

    this._closed = closed

    function onclose() {
      closed.resolve()
    }

    function onerror(err) {
      closed.reject(err)
    }
  }

  get closed() {
    return this._closed.promise
  }

  read() {
    const stream = this._stream._stream

    return new Promise((resolve, reject) => {
      const err = getStreamError(stream)

      if (err) return reject(err)

      if (stream.destroyed) {
        return resolve({ value: undefined, done: true })
      }

      const value = stream.read()

      if (value !== null) {
        return resolve({ value, done: false })
      }

      stream.once('readable', onreadable).once('close', onclose).once('error', onerror)

      function onreadable() {
        const value = stream.read()

        ondone(null, value === null ? { value: undefined, done: true } : { value, done: false })
      }

      function onclose() {
        ondone(null, { value: undefined, done: true })
      }

      function onerror(err) {
        ondone(err, null)
      }

      function ondone(err, value) {
        stream.off('readable', onreadable).off('close', onclose).off('error', onerror)

        if (err) reject(err)
        else resolve(value)
      }
    })
  }

  releaseLock() {
    this._closed.reject(new TypeError('Reader was released'))
    this._stream._releaseLock()
    this._stream = null
  }

  cancel(reason = new TypeError('Stream was cancelled')) {
    const stream = this._stream._stream

    if (stream.destroyed) return Promise.resolve()

    return new Promise((resolve) =>
      stream.once('close', resolve).once('error', noop).destroy(reason)
    )
  }
}

// https://streams.spec.whatwg.org/#readablestreamdefaultcontroller
exports.ReadableStreamDefaultController = class ReadableStreamDefaultController {
  constructor(stream) {
    this._stream = stream
  }

  get desiredSize() {
    const stream = this._stream._stream

    return stream._readableState.highWaterMark - stream._readableState.buffered
  }

  enqueue(data) {
    this._stream._stream.push(data)
  }

  close() {
    this._stream._stream.push(null)
  }

  error(err) {
    this._stream._stream.destroy(err)
  }
}

// https://streams.spec.whatwg.org/#readablestream
class ReadableStream {
  static get [readableKind]() {
    return 0 // Compatibility version
  }

  static from(iterable) {
    return new ReadableStream(Readable.from(iterable))
  }

  constructor(underlyingSource = {}, queuingStrategy) {
    if (isStreamx(underlyingSource)) {
      this._stream = underlyingSource
    } else {
      if (queuingStrategy === undefined) {
        queuingStrategy = new exports.CountQueuingStrategy()
      }

      const { start, pull, cancel } = underlyingSource
      const { highWaterMark = 1, size = defaultSize } = queuingStrategy

      this._stream = new Readable({ highWaterMark, byteLength: size })

      const controller = new exports.ReadableStreamDefaultController(this)

      try {
        let starting = Promise.resolve()

        if (start) starting = forwardError(start.call(this, controller), controller)

        if (pull) {
          this._stream._read = this._read.bind(this, starting, pull.bind(this, controller))
        }

        if (cancel) {
          this._stream.once('error', cancel.bind(this))
        }
      } catch (err) {
        controller.error(err)
      }
    }

    this._reader = null
  }

  get [readableKind]() {
    return ReadableStream[readableKind]
  }

  get locked() {
    return this._reader !== null
  }

  getReader() {
    if (this.locked) throw new TypeError('Stream is locked')

    this._reader = new exports.ReadableStreamDefaultReader(this)

    return this._reader
  }

  cancel(reason = new TypeError('Stream was cancelled')) {
    const stream = this._stream

    if (stream.destroyed) return Promise.resolve()

    if (this.locked) return Promise.reject(new TypeError('Stream is locked'))

    return new Promise((resolve) =>
      stream.once('close', resolve).once('error', noop).destroy(reason)
    )
  }

  tee() {
    const [a, b] = tee(this._stream)

    return [new ReadableStream(a), new ReadableStream(b)]
  }

  pipeTo(destination) {
    return new Promise((resolve, reject) =>
      this._stream.pipe(destination._stream, (err) => {
        err ? reject(err) : resolve()
      })
    )
  }

  [Symbol.asyncIterator]() {
    return this._stream[Symbol.asyncIterator]()
  }

  _releaseLock() {
    this._reader = null
  }

  async _read(starting, pull, cb) {
    await starting

    let err = null
    try {
      await pull()
    } catch (e) {
      err = e
    }
    cb(err)
  }
}

function defaultSize() {
  return 1
}

exports.ReadableStream = ReadableStream

// https://streams.spec.whatwg.org/#countqueuingstrategy
exports.CountQueuingStrategy = class CountQueuingStrategy {
  constructor(opts = {}) {
    const { highWaterMark = 1 } = opts

    this.highWaterMark = highWaterMark
  }

  size(chunk) {
    return 1
  }
}

// https://streams.spec.whatwg.org/#bytelengthqueuingstrategy
exports.ByteLengthQueuingStrategy = class ByteLengthQueuingStrategy {
  constructor(opts = {}) {
    const { highWaterMark = 16384 } = opts

    this.highWaterMark = highWaterMark
  }

  size(chunk) {
    return chunk.byteLength
  }
}

exports.isReadableStream = function isReadableStream(value) {
  if (value instanceof ReadableStream) return true

  return (
    typeof value === 'object' &&
    value !== null &&
    value[readableKind] === ReadableStream[readableKind]
  )
}

// https://streams.spec.whatwg.org/#readablestream-errored
exports.isReadableStreamErrored = function isReadableStreamErrored(stream) {
  return getStreamError(stream._stream) !== null
}

// https://streams.spec.whatwg.org/#is-readable-stream-disturbed
exports.isReadableStreamDisturbed = function isReadableStreamDisturbed(stream) {
  return isDisturbed(stream._stream)
}

// https://streams.spec.whatwg.org/#writablestreamdefaultwriter
exports.WritableStreamDefaultWriter = class WritableStreamDefaultWriter {
  constructor(stream) {
    this._stream = stream
    this._stream._stream.once('close', onclose).once('error', onerror)

    const closed = Promise.withResolvers()

    // Avoid unhandled exceptions
    closed.promise.catch(noop)

    this._closed = closed

    function onclose() {
      closed.resolve()
    }

    function onerror(err) {
      closed.reject(err)
    }
  }

  get desiredSize() {
    const stream = this._stream._stream

    return stream._writableState.highWaterMark - stream._writableState.buffered
  }

  get closed() {
    return this._closed.promise
  }

  get ready() {
    const stream = this._stream._stream

    if (getStreamError(stream)) return Promise.reject()

    return Writable.drained(stream).then()
  }

  async write(chunk) {
    const stream = this._stream._stream

    let err = getStreamError(stream)
    if (err) return Promise.reject(err)

    stream.write(chunk)

    await Writable.drained(stream)

    err = getStreamError(stream)
    if (err) return Promise.reject(err)
  }

  releaseLock() {
    this._closed.reject(new TypeError('Writer was released'))
    this._stream._releaseLock()
    this._stream = null
  }

  close() {
    const stream = this._stream._stream

    if (stream.destroyed) return Promise.resolve()

    return new Promise((resolve) => stream.once('close', resolve).end())
  }

  abort(reason = new TypeError('Stream was aborted')) {
    const stream = this._stream._stream

    if (stream.destroyed) return Promise.resolve()

    return new Promise((resolve) => stream.once('close', resolve).destroy(reason))
  }
}

// https://streams.spec.whatwg.org/#writablestreamdefaultcontroller
exports.WritableStreamDefaultController = class WritableStreamDefaultController {
  constructor(stream) {
    this._stream = stream
  }

  error(err) {
    this._stream._stream.destroy(err)
  }
}

// https://streams.spec.whatwg.org/#writablestream
class WritableStream {
  static get [writableKind]() {
    return 0 // Compatibility version
  }

  constructor(underlyingSink = {}, queuingStrategy = {}) {
    if (isStreamx(underlyingSink)) {
      this._stream = underlyingSink
    } else {
      if (queuingStrategy === undefined) {
        queuingStrategy = new exports.CountQueuingStrategy()
      }

      const { start, write, close, abort } = underlyingSink
      const { highWaterMark = 1, size = defaultSize } = queuingStrategy

      this._stream = new Writable({ highWaterMark, byteLength: size })

      const controller = new exports.WritableStreamDefaultController(this)

      this._controller = controller

      try {
        let starting = Promise.resolve()

        if (start) starting = forwardError(start.call(this, controller), controller)

        if (write) {
          this._stream._write = this._write.bind(this, starting, write.bind(this))
        }

        if (close) {
          this._stream._destroy = this._destroy.bind(this, close.call(this))
        }

        if (abort) {
          this._stream.once('error', abort.bind(this))
        }
      } catch (err) {
        controller.error(err)
      }
    }

    this._writer = null
  }

  get [writableKind]() {
    return WritableStream[writableKind]
  }

  get locked() {
    return this._writer !== null
  }

  getWriter() {
    if (this.locked) throw new TypeError('Stream is locked')

    this._writer = new exports.WritableStreamDefaultWriter(this)

    return this._writer
  }

  abort(reason = new TypeError('Stream was aborted')) {
    if (this._stream.destroyed) return Promise.resolve()

    if (this.locked) return Promise.reject(new TypeError('Stream is locked'))

    return new Promise((resolve) => this._stream.once('close', resolve).destroy(reason))
  }

  close() {
    if (this._stream.destroyed) return Promise.resolve()

    if (this.locked) return Promise.reject(new TypeError('Stream is locked'))

    return new Promise((resolve) => this._stream.once('close', resolve).end())
  }

  _releaseLock() {
    this._writer = null
  }

  async _write(starting, write, data, cb) {
    await starting

    let err = null
    try {
      await write(data, this._controller)
    } catch (e) {
      err = e
    }
    cb(err)
  }

  async _destroy(closing, cb) {
    let err = null
    try {
      await closing
    } catch (e) {
      err = e
    }
    cb(err)
  }
}

exports.WritableStream = WritableStream

exports.isWritableStream = function isWritableStream(value) {
  if (value instanceof WritableStream) return true

  return (
    typeof value === 'object' &&
    value !== null &&
    value[writableKind] === WritableStream[writableKind]
  )
}

// https://streams.spec.whatwg.org/#transformstreamdefaultcontroller
exports.TransformStreamDefaultController = class TransformStreamDefaultController {
  constructor(stream) {
    this._stream = stream
  }

  get desiredSize() {
    const stream = this._stream._stream

    return stream._readableState.highWaterMark - stream._readableState.buffered
  }

  enqueue(data) {
    this._stream._stream.push(data)
  }

  error(err) {
    this._stream._stream.destroy(err)
  }

  terminate() {
    const stream = this._stream._stream

    stream.push(null)
    stream.destroy(new TypeError('Stream has been terminated'))
  }
}

// https://streams.spec.whatwg.org/#transformstream
class TransformStream {
  static get [transformKind]() {
    return 0 // Compatibility version
  }

  constructor(transformer = {}, writableStrategy = {}, readableStrategy = {}) {
    if (isStreamx(transformer)) {
      this._stream = transformer
    } else {
      const { start, transform, flush } = transformer

      this._stream = new Transform({ ...writableStrategy, ...readableStrategy })

      const controller = new exports.TransformStreamDefaultController(this)

      this._controller = controller

      try {
        let starting = Promise.resolve()

        if (start) starting = forwardError(start.call(this, controller), controller)

        if (transform) {
          this._stream._transform = this._transform.bind(this, starting, transform.bind(this))
        }

        if (flush) {
          this._stream._flush = this._flush.bind(this, flush.call(this, this._controller))
        }
      } catch (err) {
        controller.error(err)
      }
    }

    this._writable = new WritableStream(this._stream)
    this._readable = new ReadableStream(this._stream)
  }

  get [transformKind]() {
    return TransformStream[transformKind]
  }

  get writable() {
    return this._writable
  }

  get readable() {
    return this._readable
  }

  async _transform(starting, transform, data, cb) {
    await starting

    let err = null
    try {
      await transform(data, this._controller)
    } catch (e) {
      err = e
    }
    cb(err)
  }

  async _flush(flush, cb) {
    let err = null
    try {
      await flush
    } catch (e) {
      err = e
    }
    cb(err)
  }
}

exports.TransformStream = TransformStream

exports.isTransformStream = function isTransformStream(value) {
  if (value instanceof TransformStream) return true

  return (
    typeof value === 'object' &&
    value !== null &&
    value[transformKind] === TransformStream[transformKind]
  )
}

async function forwardError(promise, controller) {
  try {
    await promise
  } catch (err) {
    controller.error(err)
  }
}

function noop() {}
module.exports = require.addon()
const binding = require('./binding')

const t = binding.constants

class Type {
  constructor(type) {
    this._type = type
  }

  isUndefined() {
    return this._type === t.UNDEFINED
  }

  isNull() {
    return this._type === t.NULL
  }

  isBoolean() {
    return this._type === t.BOOLEAN
  }

  isNumber() {
    return (this._type & 0xff) === t.NUMBER
  }

  isInt32() {
    return (this._type & (0xff | t.INT32)) === (t.NUMBER | t.INT32)
  }

  isUint32() {
    return (this._type & (0xff | t.UINT32)) === (t.NUMBER | t.UINT32)
  }

  isString() {
    return this._type === t.STRING
  }

  isSymbol() {
    return this._type === t.SYMBOL
  }

  isObject() {
    return (this._type & 0xff) === t.OBJECT
  }

  isArray() {
    return this._type === (t.OBJECT | t.ARRAY)
  }

  isArguments() {
    return this._type === (t.OBJECT | t.ARGUMENTS)
  }

  isDate() {
    return this._type === (t.OBJECT | t.DATE)
  }

  isRegExp() {
    return this._type === (t.OBJECT | t.REGEXP)
  }

  isError() {
    return this._type === (t.OBJECT | t.ERROR)
  }

  isPromise() {
    return this._type === (t.OBJECT | t.PROMISE)
  }

  isProxy() {
    return this._type === (t.OBJECT | t.PROXY)
  }

  isGenerator() {
    return this._type === (t.OBJECT | t.GENERATOR)
  }

  isMap() {
    return this._type === (t.OBJECT | t.MAP)
  }

  isSet() {
    return this._type === (t.OBJECT | t.SET)
  }

  isWeakMap() {
    return this._type === (t.OBJECT | t.WEAK_MAP)
  }

  isWeakSet() {
    return this._type === (t.OBJECT | t.WEAK_SET)
  }

  isWeakRef() {
    return this._type === (t.OBJECT | t.WEAK_REF)
  }

  isArrayBuffer() {
    return this._type === (t.OBJECT | t.ARRAYBUFFER)
  }

  isSharedArrayBuffer() {
    return this._type === (t.OBJECT | t.SHAREDARRAYBUFFER)
  }

  isTypedArray() {
    return (this._type & 0xffff) === (t.OBJECT | t.TYPEDARRAY)
  }

  isInt8Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT8ARRAY)
  }

  isUint8Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT8ARRAY)
  }

  isUint8ClampedArray() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT8CLAMPEDARRAY)
  }

  isInt16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT16ARRAY)
  }

  isUint16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT16ARRAY)
  }

  isInt32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT32ARRAY)
  }

  isUint32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT32ARRAY)
  }

  isFloat16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT16ARRAY)
  }

  isFloat32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT32ARRAY)
  }

  isFloat64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT64ARRAY)
  }

  isBigInt64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.BIGINT64ARRAY)
  }

  isBigUint64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.BIGUINT64ARRAY)
  }

  isDataView() {
    return this._type === (t.OBJECT | t.DATAVIEW)
  }

  isModuleNamespace() {
    return this._type === (t.OBJECT | t.MODULE_NAMESPACE)
  }

  isFunction() {
    return (this._type & 0xff) === t.FUNCTION
  }

  isAsyncFunction() {
    return (
      (this._type & (0xff | t.ASYNC_FUNCTION)) ===
      (t.FUNCTION | t.ASYNC_FUNCTION)
    )
  }

  isGeneratorFunction() {
    return (
      (this._type & (0xff | t.GENERATOR_FUNCTION)) ===
      (t.FUNCTION | t.GENERATOR_FUNCTION)
    )
  }

  isExternal() {
    return this._type === t.EXTERNAL
  }

  isBigInt() {
    return this._type === t.BIGINT
  }
}

module.exports = exports = function type(value) {
  switch (typeof value) {
    case 'undefined':
      return new Type(t.UNDEFINED)
    case 'boolean':
      return new Type(t.BOOLEAN)
    case 'number':
      return new Type(
        Number.isSafeInteger(value) ? binding.type(value) : t.NUMBER
      )
    case 'string':
      return new Type(t.STRING)
    case 'symbol':
      return new Type(t.SYMBOL)
    case 'object':
      return new Type(value === null ? t.NULL : binding.type(value))
    case 'function':
      return new Type(binding.type(value))
    case 'bigint':
      return new Type(t.BIGINT)
  }
}

exports.createTag = function createTag(...components) {
  const tag = new Uint32Array(4)
  for (let i = 0; i < 4; i++) tag[i] = components[i] || 0
  return tag
}

exports.addTag = function addTag(object, tag) {
  binding.addTag(object, tag)
}

exports.checkTag = function checkTag(object, tag) {
  return binding.checkTag(object, tag)
}
{
  "name": "bare-type",
  "version": "1.1.0",
  "description": "Cross-realm type predicates for Bare",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-type.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-type/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-type#readme",
  "engines": {
    "bare": ">=1.2.0"
  },
  "devDependencies": {
    "brittle": "^3.4.0",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
module.exports = require.addon()
const path = require('bare-path')
const binding = require('./binding')
const errors = require('./lib/errors')
const URLSearchParams = require('./lib/url-search-params')

const kind = Symbol.for('bare.url.kind')

const isWindows = Bare.platform === 'win32'

class URL {
  static get [kind]() {
    return 0 // Compatibility version
  }

  constructor(input, base, opts = {}) {
    if (arguments.length === 0) throw errors.INVALID_URL()

    input = String(input)

    if (base !== undefined) base = String(base)

    this._components = new Uint32Array(8)

    this._parse(input, base, opts.throw !== false)

    if (this._href) this._params = new URLSearchParams(this.search, this)
  }

  get [kind]() {
    return URL[kind]
  }

  // https://url.spec.whatwg.org/#dom-url-href

  get href() {
    return this._href
  }

  set href(value) {
    this._update(value)

    this._params._parse(this.search)
  }

  // https://url.spec.whatwg.org/#dom-url-protocol

  get protocol() {
    return this._slice(0, this._components[0]) + ':'
  }

  set protocol(value) {
    this._update(this._replace(value.replace(/:+$/, ''), 0, this._components[0]))
  }

  // https://url.spec.whatwg.org/#dom-url-username

  get username() {
    return this._slice(this._components[0] + 3 /* :// */, this._components[1])
  }

  set username(value) {
    if (cannotHaveCredentialsOrPort(this)) {
      return
    }

    if (this.username === '') value += '@'

    this._update(this._replace(value, this._components[0] + 3 /* :// */, this._components[1]))
  }

  // https://url.spec.whatwg.org/#dom-url-password

  get password() {
    return this._href.slice(this._components[1] + 1 /* : */, this._components[2] - 1 /* @ */)
  }

  set password(value) {
    if (cannotHaveCredentialsOrPort(this)) {
      return
    }

    let start = this._components[1] + 1 /* : */
    let end = this._components[2] - 1 /* @ */

    if (this.password === '') {
      value = ':' + value
      start--
    }

    if (this.username === '') {
      value += '@'
      end++
    }

    this._update(this._replace(value, start, end))
  }

  // https://url.spec.whatwg.org/#dom-url-host

  get host() {
    return this._slice(this._components[2], this._components[5])
  }

  set host(value) {
    if (hasOpaquePath(this)) {
      return
    }

    this._update(
      this._replace(value, this._components[2], this._components[value.includes(':') ? 5 : 3])
    )
  }

  // https://url.spec.whatwg.org/#dom-url-hostname

  get hostname() {
    return this._slice(this._components[2], this._components[3])
  }

  set hostname(value) {
    if (hasOpaquePath(this)) {
      return
    }

    this._update(this._replace(value, this._components[2], this._components[3]))
  }

  // https://url.spec.whatwg.org/#dom-url-port

  get port() {
    return this._slice(this._components[3] + 1 /* : */, this._components[5])
  }

  set port(value) {
    if (cannotHaveCredentialsOrPort(this)) {
      return
    }

    let start = this._components[3] + 1 /* : */

    if (this.port === '') {
      value = ':' + value
      start--
    }

    this._update(this._replace(value, start, this._components[5]))
  }

  // https://url.spec.whatwg.org/#dom-url-pathname

  get pathname() {
    return this._slice(this._components[5], this._components[6] - 1 /* ? */)
  }

  set pathname(value) {
    if (hasOpaquePath(this)) {
      return
    }

    if (value[0] !== '/' && value[0] !== '\\') {
      value = '/' + value
    }

    this._update(this._replace(value, this._components[5], this._components[6] - 1 /* ? */))
  }

  // https://url.spec.whatwg.org/#dom-url-search

  get search() {
    return this._slice(this._components[6] - 1 /* ? */, this._components[7] - 1 /* # */)
  }

  set search(value) {
    if (value && value[0] !== '?') value = '?' + value

    this._update(
      this._replace(value, this._components[6] - 1 /* ? */, this._components[7] - 1 /* # */)
    )

    this._params._parse(this.search)
  }

  // https://url.spec.whatwg.org/#dom-url-searchparams

  get searchParams() {
    return this._params
  }

  // https://url.spec.whatwg.org/#dom-url-hash

  get hash() {
    return this._slice(this._components[7] - 1 /* # */)
  }

  set hash(value) {
    if (value && value[0] !== '#') value = '#' + value

    this._update(this._replace(value, this._components[7] - 1 /* # */))
  }

  toString() {
    return this._href
  }

  toJSON() {
    return this._href
  }

  [Symbol.for('bare.inspect')]() {
    return {
      __proto__: { constructor: URL },

      href: this.href,
      protocol: this.protocol,
      username: this.username,
      password: this.password,
      host: this.host,
      hostname: this.hostname,
      port: this.port,
      pathname: this.pathname,
      search: this.search,
      searchParams: this.searchParams,
      hash: this.hash
    }
  }

  _slice(start, end = this._href.length) {
    return this._href.slice(start, end)
  }

  _replace(replacement, start, end = this._href.length) {
    return this._slice(0, start) + replacement + this._slice(end)
  }

  _parse(input, base, shouldThrow) {
    try {
      this._href = binding.parse(
        String(input),
        base ? String(base) : null,
        this._components,
        shouldThrow
      )
    } catch (err) {
      if (err instanceof TypeError) throw err

      throw errors.INVALID_URL(`Invalid URL '${input}'`, input)
    }
  }

  _update(input) {
    try {
      this._parse(input, null, true)
    } catch (err) {
      if (err instanceof TypeError) throw err
    }
  }
}

module.exports = exports = URL

// https://url.spec.whatwg.org/#url-opaque-path
function hasOpaquePath(url) {
  return url.pathname[0] !== '/'
}

// https://url.spec.whatwg.org/#cannot-have-a-username-password-port
function cannotHaveCredentialsOrPort(url) {
  return url.hostname === '' || url.protocol === 'file:'
}

exports.URL = URL
exports.URLSearchParams = URLSearchParams

exports.errors = errors

exports.isURL = function isURL(value) {
  if (value instanceof URL) return true

  return typeof value === 'object' && value !== null && value[kind] === URL[kind]
}

exports.isURLSearchParams = URLSearchParams.isURLSearchParams

// https://url.spec.whatwg.org/#dom-url-parse
exports.parse = function parse(input, base) {
  const url = new URL(input, base, { throw: false })
  return url._href ? url : null
}

// https://url.spec.whatwg.org/#dom-url-canparse
exports.canParse = function canParse(input, base) {
  return binding.canParse(String(input), base ? String(base) : null)
}

exports.fileURLToPath = function fileURLToPath(url) {
  if (typeof url === 'string') {
    url = new URL(url)
  }

  if (url.protocol !== 'file:') {
    throw errors.INVALID_URL_SCHEME('The URL must use the file: protocol')
  }

  if (isWindows) {
    if (/%2f|%5c/i.test(url.pathname)) {
      throw errors.INVALID_FILE_URL_PATH(
        'The file: URL path must not include encoded \\ or / characters'
      )
    }
  } else {
    if (url.hostname) {
      throw errors.INVALID_FILE_URL_HOST("The file: URL host must be 'localhost' or empty")
    }

    if (/%2f/i.test(url.pathname)) {
      throw errors.INVALID_FILE_URL_PATH('The file: URL path must not include encoded / characters')
    }
  }

  if (/%00/i.test(url.pathname)) {
    throw errors.INVALID_FILE_URL_PATH('The file: URL path must not include encoded NUL characters')
  }

  const pathname = path.normalize(decodeURIComponent(url.pathname))

  if (isWindows) {
    if (url.hostname) return '\\\\' + url.hostname + pathname

    const letter = pathname.charCodeAt(1) | 0x20

    if (letter < 0x61 /* a */ || letter > 0x7a /* z */ || pathname.charCodeAt(2) !== 0x3a /* : */) {
      throw errors.INVALID_FILE_URL_PATH('The file: URL path must be absolute')
    }

    return pathname.slice(1)
  }

  return pathname
}

exports.pathToFileURL = function pathToFileURL(pathname) {
  let resolved = path.resolve(pathname)

  if (pathname[pathname.length - 1] === '/') {
    resolved += '/'
  } else if (isWindows && pathname[pathname.length - 1] === '\\') {
    resolved += '\\'
  }

  resolved = resolved
    .replaceAll('%', '%25') // Must be first
    .replaceAll('#', '%23')
    .replaceAll('?', '%3f')
    .replaceAll('\n', '%0a')
    .replaceAll('\r', '%0d')
    .replaceAll('\t', '%09')

  if (!isWindows) {
    resolved = resolved.replaceAll('\\', '%5c')
  }

  return new URL('file:' + resolved)
}

exports.format = function format(parts) {
  const { protocol, auth, host, hostname, port, pathname, search, query, hash, slashes } = parts

  let result = ''

  if (typeof protocol === 'string') {
    result += protocol

    if (protocol[protocol.length - 1] !== ':') {
      result += ':'
    }

    if (slashes === true || /https?|ftp|gopher|file/.test(protocol)) {
      result += '//'
    }
  }

  if (typeof auth === 'string') {
    if (host || hostname) result += auth + '@'
  }

  if (typeof host === 'string') result += host
  else {
    result += hostname

    if (port) result += ':' + port
  }

  if (typeof pathname === 'string' && pathname !== '') {
    if (pathname[0] !== '/') result += '/'
    result += pathname
  }

  if (typeof search === 'string') {
    if (search[0] !== '?') result += '?'
    result += search
  } else if (typeof query === 'object' && query !== null) {
    result += '?' + new URLSearchParams(query)
  }

  if (typeof hash === 'string') {
    if (hash[0] !== '#') result += '#'
    result += hash
  }

  return result
}
module.exports = class URLError extends Error {
  constructor(msg, fn = URLError, code = fn.name) {
    super(`${code}: ${msg}`)

    this.code = code

    if (Error.captureStackTrace) Error.captureStackTrace(this, fn)
  }

  get name() {
    return 'URLError'
  }

  static INVALID_URL(msg, input) {
    const err = new URLError(msg, URLError.INVALID_URL)

    err.input = input

    return err
  }

  static INVALID_URL_SCHEME(msg = 'Invalid URL') {
    return new URLError(msg, URLError.INVALID_URL_SCHEME)
  }

  static INVALID_FILE_URL_HOST(msg = 'Invalid file: URL host') {
    return new URLError(msg, URLError.INVALID_FILE_URL_HOST)
  }

  static INVALID_FILE_URL_PATH(msg = 'Invalid file: URL path') {
    return new URLError(msg, URLError.INVALID_FILE_URL_PATH)
  }
}
const kind = Symbol.for('bare.url.search-params.kind')

class URLSearchParams {
  static _urls = new WeakMap()

  static get [kind]() {
    return 0 // Compatibility version
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-urlsearchparams
  constructor(init, url = null) {
    this._params = new Map()

    if (url) URLSearchParams._urls.set(this, url)

    if (typeof init === 'string') {
      this._parse(init)
    } else if (init) {
      for (const [name, value] of typeof init[Symbol.iterator] === 'function'
        ? init
        : Object.entries(init)) {
        this.append(name, value)
      }
    }
  }

  get [kind]() {
    return URLSearchParams[kind]
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-size
  get size() {
    return this._params.length
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-append
  append(name, value = null) {
    if (value === null) return

    let list = this._params.get(name)

    if (list === undefined) {
      list = []
      this._params.set(name, list)
    }

    list.push(value)

    this._update()
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-delete
  delete(name, value = null) {
    if (value === null) this._params.delete(name)
    else {
      let list = this._params.get(name)

      if (list === undefined) return

      list = list.filter((found) => found !== value)

      if (list.length === 0) this._params.delete(name)
      else this._params.set(name, list)
    }

    this._update()
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-get
  get(name) {
    const list = this._params.get(name)

    if (list === undefined) return null

    return list[0]
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-getall
  getAll(name) {
    const list = this._params.get(name)

    if (list === undefined) return []

    return Array.from(list)
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-has
  has(name, value = null) {
    const list = this._params.get(name)

    if (list === undefined) return false

    if (value === null) return true

    return list.includes(value)
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-set
  set(name, value = null) {
    if (value === null) this._params.delete(name)
    else this._params.set(name, [value])

    this._update()
  }

  toString() {
    return this._serialize()
  }

  toJSON() {
    return [...this]
  }

  *[Symbol.iterator]() {
    for (const [name, values] of this._params) {
      for (const value of values) yield [name, value]
    }
  }

  [Symbol.for('bare.inspect')]() {
    const object = {
      __proto__: { constructor: URLSearchParams }
    }

    for (const [name, values] of this._params) {
      if (values.length === 1) object[name] = values[0]
      else object[name] = values
    }

    return object
  }

  // https://url.spec.whatwg.org/#concept-urlsearchparams-update
  _update() {
    const url = URLSearchParams._urls.get(this)

    if (url === undefined) return

    url.search = this._serialize()
  }

  // https://url.spec.whatwg.org/#concept-urlencoded-parser
  _parse(input) {
    if (input[0] === '?') input = input.substring(1)

    this._params = new Map()

    for (let sequence of input.split('&')) {
      if (sequence.length === 0) continue

      sequence = sequence.replace(/\+/g, ' ')

      let i = sequence.indexOf('=')
      if (i === -1) i = sequence.length

      const name = decodeURIComponent(sequence.substring(0, i))
      const value = decodeURIComponent(sequence.substring(i + 1, sequence.length))

      let list = this._params.get(name)

      if (list === undefined) {
        list = []
        this._params.set(name, list)
      }

      list.push(value)
    }
  }

  // https://url.spec.whatwg.org/#concept-urlencoded-serializer
  _serialize() {
    let output = ''

    for (let [name, values] of this._params) {
      name = encodeURIComponent(name)

      for (const value of values) {
        if (output) output += '&'

        output += name + '=' + encodeURIComponent(value)
      }
    }

    return output
  }
}

module.exports = exports = URLSearchParams

exports.isURLSearchParams = function isURLSearchParams(value) {
  if (value instanceof URLSearchParams) return true

  return typeof value === 'object' && value !== null && value[kind] === URLSearchParams[kind]
}
{
  "name": "bare-url",
  "version": "2.4.5",
  "description": "WHATWG URL implementation for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "global.js",
    "global.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-url.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-url/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-url",
  "dependencies": {
    "bare-path": "^3.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "cmake-bare": "^1.1.6",
    "cmake-fetch": "^1.0.0",
    "lunte": "^1.6.0",
    "prettier": "^3.3.3",
    "prettier-config-holepunch": "^2.0.0"
  }
}
const b4a = require('b4a')

module.exports = codecs

codecs.ascii = createString('ascii')
codecs.utf8 = createString('utf-8')
codecs.hex = createString('hex')
codecs.base64 = createString('base64')
codecs.ucs2 = createString('ucs2')
codecs.utf16le = createString('utf16le')
codecs.ndjson = createJSON(true)
codecs.json = createJSON(false)
codecs.binary = {
  name: 'binary',
  encode: function encodeBinary (obj) {
    return typeof obj === 'string'
      ? b4a.from(obj, 'utf-8')
      : b4a.toBuffer(obj)
  },
  decode: function decodeBinary (buf) {
    return b4a.toBuffer(buf)
  }
}

function isCompactEncoding (c) {
  return !!(c.encode && c.decode && c.preencode)
}

function fromCompactEncoding (c) {
  return {
    name: 'compact-encoding',
    encode: function encodeWithCompact (value) {
      const state = { start: 0, end: 0, buffer: null, cache: null }
      c.preencode(state, value)
      state.buffer = b4a.allocUnsafe(state.end)
      c.encode(state, value)
      return state.buffer
    },
    decode: function decodeWithCompact (buffer) {
      return c.decode({ start: 0, end: buffer.byteLength, buffer, cache: null })
    }
  }
}

function codecs (fmt, fallback) {
  if (typeof fmt === 'object' && fmt) {
    return isCompactEncoding(fmt) ? fromCompactEncoding(fmt) : fmt
  }

  switch (fmt) {
    case 'ndjson': return codecs.ndjson
    case 'json': return codecs.json
    case 'ascii': return codecs.ascii
    case 'utf-8':
    case 'utf8': return codecs.utf8
    case 'hex': return codecs.hex
    case 'base64': return codecs.base64
    case 'ucs-2':
    case 'ucs2': return codecs.ucs2
    case 'utf16-le':
    case 'utf16le': return codecs.utf16le
  }

  return fallback !== undefined ? fallback : codecs.binary
}

function createJSON (newline) {
  return {
    name: newline ? 'ndjson' : 'json',
    encode: newline ? encodeNDJSON : encodeJSON,
    decode: function decodeJSON (buf) {
      return JSON.parse(b4a.toString(buf))
    }
  }

  function encodeJSON (val) {
    return b4a.from(JSON.stringify(val))
  }

  function encodeNDJSON (val) {
    return b4a.from(JSON.stringify(val) + '\n')
  }
}

function createString (type) {
  return {
    name: type,
    encode: function encodeString (val) {
      if (typeof val !== 'string') val = val.toString()
      return b4a.from(val, type)
    },
    decode: function decodeString (buf) {
      return b4a.toString(buf, type)
    }
  }
}
{
  "name": "codecs",
  "version": "3.1.0",
  "description": "Create an binary encoder/decoder for json, utf-8 or custom types",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.6.3"
  },
  "devDependencies": {
    "brittle": "^3.2.1",
    "compact-encoding": "^2.11.0",
    "standard": "^17.0.0"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/codecs.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/codecs/issues"
  },
  "homepage": "https://github.com/mafintosh/codecs"
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return uint24.decode(state) + 0x1000000 * uint32.decode(state)
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return uint32.decode(state) + 0x100000000 * uint32.decode(state)
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return 0x100000000 * uint32be.decode(state) + uint32be.decode(state)
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.2.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
module.exports = function debounce (worker, context = null) {
  debounced.running = null
  return debounced

  async function debounced () {
    if (debounced.running !== null) {
      try {
        await debounced.running
      } catch (_) {
        // ignore - do not fail on old errors
      }
    }

    // another "thread" beat us to it, just piggy pack on that one
    if (debounced.running !== null) return debounced.running

    debounced.running = worker.call(context)

    try {
      return await debounced.running
    } finally {
      debounced.running = null
    }
  }
}
{
  "name": "debounceify",
  "version": "1.1.0",
  "description": "Tiny async debouncer",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^16.0.3",
    "tape": "^5.1.1"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/debounceify.git"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/debounceify/issues"
  },
  "homepage": "https://github.com/mafintosh/debounceify"
}
module.exports = require('bare-events')
{
  "name": "events-universal",
  "version": "1.0.1",
  "description": "Universal wrapper for the Node.js events module",
  "exports": {
    "./package": "./package.json",
    ".": {
      "bare": "./bare.js",
      "react-native": "./react-native.js",
      "default": "./default.js"
    }
  },
  "files": [
    "index.js",
    "default.js",
    "bare.js",
    "react-native.js"
  ],
  "scripts": {
    "test": "prettier . --check"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/events-universal.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/events-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/events-universal#readme",
  "dependencies": {
    "bare-events": "^2.7.0"
  },
  "devDependencies": {
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^1.0.0"
  }
}
module.exports = class FixedFIFO {
  constructor (hwm) {
    if (!(hwm > 0) || ((hwm - 1) & hwm) !== 0) throw new Error('Max size for a FixedFIFO should be a power of two')
    this.buffer = new Array(hwm)
    this.mask = hwm - 1
    this.top = 0
    this.btm = 0
    this.next = null
  }

  clear () {
    this.top = this.btm = 0
    this.next = null
    this.buffer.fill(undefined)
  }

  push (data) {
    if (this.buffer[this.top] !== undefined) return false
    this.buffer[this.top] = data
    this.top = (this.top + 1) & this.mask
    return true
  }

  shift () {
    const last = this.buffer[this.btm]
    if (last === undefined) return undefined
    this.buffer[this.btm] = undefined
    this.btm = (this.btm + 1) & this.mask
    return last
  }

  peek () {
    return this.buffer[this.btm]
  }

  isEmpty () {
    return this.buffer[this.btm] === undefined
  }
}
const FixedFIFO = require('./fixed-size')

module.exports = class FastFIFO {
  constructor (hwm) {
    this.hwm = hwm || 16
    this.head = new FixedFIFO(this.hwm)
    this.tail = this.head
    this.length = 0
  }

  clear () {
    this.head = this.tail
    this.head.clear()
    this.length = 0
  }

  push (val) {
    this.length++
    if (!this.head.push(val)) {
      const prev = this.head
      this.head = prev.next = new FixedFIFO(2 * this.head.buffer.length)
      this.head.push(val)
    }
  }

  shift () {
    if (this.length !== 0) this.length--
    const val = this.tail.shift()
    if (val === undefined && this.tail.next) {
      const next = this.tail.next
      this.tail.next = null
      this.tail = next
      return this.tail.shift()
    }

    return val
  }

  peek () {
    const val = this.tail.peek()
    if (val === undefined && this.tail.next) return this.tail.next.peek()
    return val
  }

  isEmpty () {
    return this.length === 0
  }
}
{
  "name": "fast-fifo",
  "version": "1.3.2",
  "description": "A fast fifo implementation similar to the one powering nextTick in Node.js core",
  "main": "index.js",
  "files": [
    "./index.js",
    "./fixed-size.js"
  ],
  "dependencies": {},
  "devDependencies": {
    "standard": "^17.1.0",
    "brittle": "^3.3.2"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/fast-fifo.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/fast-fifo/issues"
  },
  "homepage": "https://github.com/mafintosh/fast-fifo"
}
const codecs = require('codecs')
const { Readable } = require('streamx')
const mutexify = require('mutexify/promise')
const b4a = require('b4a')
const safetyCatch = require('safety-catch')
const ReadyResource = require('ready-resource')
const debounce = require('debounceify')
const Rache = require('rache')
const rrp = require('resolve-reject-promise')

const { all: unslabAll } = require('unslab')

const RangeIterator = require('./iterators/range')
const HistoryIterator = require('./iterators/history')
const DiffIterator = require('./iterators/diff')
const LocalBlockIterator = require('./iterators/local')
const Extension = require('./lib/extension')
const { YoloIndex, Node, Header } = require('./lib/messages')
const { BLOCK_NOT_AVAILABLE, DECODING_ERROR } = require('hypercore-errors')

const T = 5
const MIN_KEYS = T - 1
const MAX_CHILDREN = MIN_KEYS * 2 + 1

const SEP = b4a.alloc(1)
const EMPTY = b4a.alloc(0)

class Key {
  constructor(seq, value) {
    this.seq = seq
    this.value = value
  }
}

class Child {
  constructor(seq, offset, value) {
    this.seq = seq
    this.offset = offset
    this.value = value
  }
}

class Cache {
  constructor(rache) {
    this.keys = rache
    this.length = 0
  }

  get(seq) {
    return this.keys.get(seq) || null
  }

  set(seq, key) {
    this.keys.set(seq, key)
    if (seq >= this.length) this.length = seq + 1
  }

  gc(length) {
    // if we need to "work" more than 128 ticks, just bust the cache...
    if (this.length - length > 128) {
      this.keys.clear()
    } else {
      for (let i = length; i < this.length; i++) {
        this.keys.delete(i)
      }
    }

    this.length = length
  }

  clear() {
    this.keys.clear()
  }
}

class Pointers {
  constructor(decoded) {
    this.levels = decoded.levels.map((l) => {
      const children = []
      const keys = []

      for (let i = 0; i < l.keys.length; i++) {
        keys.push(new Key(l.keys[i], null))
      }

      for (let i = 0; i < l.children.length; i += 2) {
        children.push(new Child(l.children[i], l.children[i + 1], null))
      }

      return { keys, children }
    })
  }

  get(i) {
    return this.levels[i]
  }

  hasKey(seq) {
    for (const lvl of this.levels) {
      for (const key of lvl.keys) {
        if (key.seq === seq) return true
      }
    }
    return false
  }
}

function inflate(entry) {
  if (entry.inflated === null) {
    entry.inflated = YoloIndex.decode(entry.index)
    entry.index = null
  }
  return new Pointers(entry.inflated)
}

function deflate(index) {
  const levels = index.map((l) => {
    const keys = []
    const children = []

    for (let i = 0; i < l.value.keys.length; i++) {
      keys.push(l.value.keys[i].seq)
    }

    for (let i = 0; i < l.value.children.length; i++) {
      children.push(l.value.children[i].seq, l.value.children[i].offset)
    }

    return { keys, children }
  })

  return YoloIndex.encode({ levels })
}

class TreeNode {
  constructor(block, keys, children, offset) {
    this.block = block
    this.offset = offset
    this.keys = keys
    this.children = children
    this.changed = false

    this.preload()
  }

  preload() {
    if (this.block === null) return

    const core = getBackingCore(this.block.tree.core)
    if (!core) return

    const bitfield = core.core.bitfield
    const blocks = []

    for (let i = 0; i < this.keys.length; i++) {
      const k = this.keys[i]
      if (k.value) continue
      if (k.seq >= core.signedLength || (bitfield && bitfield.get(k.seq))) continue
      blocks.push(k.seq)
    }
    for (let i = 0; i < this.children.length; i++) {
      const c = this.children[i]
      if (c.value) continue
      if (c.seq >= core.signedLength || (bitfield && bitfield.get(c.seq))) continue
      blocks.push(c.seq)
    }

    if (blocks.length) core.download({ blocks })
  }

  async insertKey(key, value, child, node, encoding, cas) {
    let s = 0
    let e = this.keys.length
    let c

    while (s < e) {
      const mid = (s + e) >> 1
      c = b4a.compare(key.value, await this.getKey(mid))

      if (c === 0) {
        if (cas) {
          const prev = await this.getKeyNode(mid)
          if (!(await cas(prev.final(encoding), node))) return true
        }
        if (!this.block.tree.tree.alwaysDuplicate) {
          const prev = await this.getKeyNode(mid)
          if (sameValue(prev.value, value)) return true
        }
        this.changed = true
        this.keys[mid] = key
        return true
      }

      if (c < 0) e = mid
      else s = mid + 1
    }

    const i = c < 0 ? e : s
    this.keys.splice(i, 0, key)
    if (child) this.children.splice(i + 1, 0, new Child(0, 0, child))
    this.changed = true

    return this.keys.length < MAX_CHILDREN
  }

  removeKey(index) {
    this.keys.splice(index, 1)
    if (this.children.length) {
      this.children[index + 1].seq = 0 // mark as freed
      this.children.splice(index + 1, 1)
    }
    this.changed = true
  }

  async siblings(parent) {
    for (let i = 0; i < parent.children.length; i++) {
      if (parent.children[i].value === this) {
        const [left, right] = await Promise.all([
          i ? parent.getChildNode(i - 1) : null,
          i < parent.children.length - 1 ? parent.getChildNode(i + 1) : null
        ])
        return { left, index: i, right }
      }
    }

    throw new Error('Bad parent')
  }

  merge(node, median) {
    this.changed = true
    this.keys.push(median)
    for (let i = 0; i < node.keys.length; i++) this.keys.push(node.keys[i])
    for (let i = 0; i < node.children.length; i++) this.children.push(node.children[i])
  }

  async split() {
    const len = this.keys.length >> 1
    const right = TreeNode.create(this.block)

    while (right.keys.length < len) right.keys.push(this.keys.pop())
    right.keys.reverse()

    await this.getKey(this.keys.length - 1) // make sure the median is loaded
    const median = this.keys.pop()

    if (this.children.length) {
      while (right.children.length < len + 1) right.children.push(this.children.pop())
      right.children.reverse()
    }

    this.changed = true

    return {
      left: this,
      median,
      right
    }
  }

  getKeyNode(index) {
    return this.block.tree.getBlock(this.keys[index].seq)
  }

  async getChildNode(index) {
    const child = this.children[index]
    if (child.value) return child.value
    const block =
      child.seq === this.block.seq ? this.block : await this.block.tree.getBlock(child.seq)
    return (child.value = block.getTreeNode(child.offset))
  }

  setKey(index, key) {
    this.keys[index] = key
    this.changed = true
  }

  async getKey(index) {
    const key = this.keys[index]
    if (key.value) return key.value
    const k = key.seq === this.block.seq ? this.block.key : await this.block.tree.getKey(key.seq)
    return (key.value = k)
  }

  indexChanges(index, seq) {
    const offset = index.push(null) - 1
    this.changed = false

    for (const child of this.children) {
      if (!child.value || !child.value.changed) continue
      child.seq = seq
      child.offset = child.value.indexChanges(index, seq)
      index[child.offset] = child
    }

    return offset
  }

  updateChildren(seq, block) {
    for (const child of this.children) {
      if (!child.value || child.seq !== seq) continue
      child.value.block = block
      child.value.updateChildren(seq, block)
    }
  }

  static create(block) {
    const node = new TreeNode(block, [], [], 0)
    node.changed = true
    return node
  }
}

class BlockEntry {
  constructor(seq, tree, entry) {
    this.seq = seq
    this.tree = tree
    this.index = null
    this.entry = entry
    this.key = entry.key
    this.value = entry.value
  }

  isTarget(key) {
    return b4a.equals(this.key, key)
  }

  inflate() {
    if (this.index === null) {
      this.index = inflate(this.entry)
    }
  }

  isDeletion() {
    if (this.value !== null) return false

    if (this.index === null) {
      this.index = inflate(this.entry)
    }

    return !this.index.hasKey(this.seq)
  }

  final(encoding) {
    return {
      seq: this.seq,
      key: encoding.key ? encoding.key.decode(this.key) : this.key,
      value: this.value && (encoding.value ? encoding.value.decode(this.value) : this.value)
    }
  }

  getTreeNode(offset) {
    if (this.index === null) {
      this.index = inflate(this.entry)
    }
    const entry = this.index.get(offset)
    return new TreeNode(this, entry.keys, entry.children, offset)
  }
}

class CacheLock {
  constructor() {
    this.map = new Map()
  }

  enter(seq) {
    const pending = this.map.get(seq)

    if (!pending) {
      this.map.set(seq, [])
      return Promise.resolve()
    }

    const { resolve, promise } = rrp()
    pending.push(resolve)
    return promise
  }

  exit(seq) {
    const pending = this.map.get(seq)
    if (!pending.length) {
      this.map.delete(seq)
      return
    }

    pending.pop()()
  }
}

class BatchEntry extends BlockEntry {
  constructor(seq, tree, key, value, index) {
    super(seq, tree, { key, value, index: null, inflated: null })
    this.pendingIndex = index
  }

  isTarget(key) {
    return false
  }

  getTreeNode(offset) {
    return this.pendingIndex[offset].value
  }
}

class Hyperbee extends ReadyResource {
  constructor(core, opts = {}) {
    super()
    // this.feed is now deprecated, and will be this.core going forward
    this.feed = core
    this.core = core

    this.keyEncoding = opts.keyEncoding ? codecs(opts.keyEncoding) : null
    this.valueEncoding = opts.valueEncoding ? codecs(opts.valueEncoding) : null
    this.extension = opts.extension !== false ? getExtension(this, opts) : null
    this.metadata = opts.metadata || null
    this.lock = opts.lock || mutexify()
    this.sep = opts.sep || SEP
    this.readonly = !!opts.readonly
    this.prefix = opts.prefix || null

    // In a future version, this should be false by default
    this.alwaysDuplicate = opts.alwaysDuplicate !== false

    this._unprefixedKeyEncoding = this.keyEncoding
    this._sub = !!this.prefix
    this._checkout = opts.checkout || 0
    this._view = !!opts._view

    this._onappendBound = this._view ? null : this._onappend.bind(this)
    this._ontruncateBound = this._view ? null : this._ontruncate.bind(this)
    this._watchers = this._onappendBound ? [] : null
    this._entryWatchers = this._onappendBound ? [] : null
    this._sessions = opts.sessions !== false

    this._keyCache = null
    this._nodeCache = null
    this._cacheLock = new CacheLock()

    this._batches = []

    if (this._watchers) {
      this.core.on('append', this._onappendBound)
      this.core.on('truncate', this._ontruncateBound)
    }

    if (this.prefix && opts._sub) {
      this.keyEncoding = prefixEncoding(this.prefix, this.keyEncoding)
    }

    this.ready().catch(safetyCatch)
  }

  async _open() {
    if (this.core.opened === false) await this.core.ready()
    // bump the internal ranges since the nodes are small
    if (this._watchers && this.core.replicator.setInflightRange) {
      this.core.replicator.setInflightRange(256, 512)
    }

    // snapshot
    if (this._checkout === -1) this._checkout = Math.max(1, this.core.length)

    const baseCache = Rache.from(this.core.globalCache)
    this._keyCache = new Cache(baseCache)
    this._nodeCache = new Cache(Rache.from(baseCache))
  }

  get version() {
    return Math.max(1, this._checkout || this.core.length)
  }

  get id() {
    return this.core.id
  }

  get key() {
    return this.core.key
  }

  get discoveryKey() {
    return this.core.discoveryKey
  }

  get writable() {
    return this.core.writable
  }

  get readable() {
    return this.core.readable
  }

  replicate(isInitiator, opts) {
    return this.core.replicate(isInitiator, opts)
  }

  update(opts) {
    return this.core.update(opts)
  }

  peek(range, opts) {
    return iteratorPeek(this.createRangeIterator(range, { ...opts, limit: 1 }))
  }

  createRangeIterator(range, opts = {}) {
    // backwards compat range arg
    opts = opts ? { ...opts, ...range } : range

    const extension = opts.extension === false && opts.limit !== 0 ? null : this.extension
    const keyEncoding = opts.keyEncoding ? codecs(opts.keyEncoding) : this.keyEncoding

    if (extension) {
      const { onseq, onwait } = opts
      let version = 0
      let next = 0

      opts = encRange(keyEncoding, {
        ...opts,
        sub: this._sub,
        onseq(seq) {
          if (!version) version = seq + 1
          if (next) next--
          if (onseq) onseq(seq)
        },
        onwait(seq) {
          if (!next) {
            next = Extension.BATCH_SIZE
            extension.iterator(ite.snapshot(version))
          }
          if (onwait) onwait(seq)
        }
      })
    } else {
      opts = encRange(keyEncoding, { ...opts, sub: this._sub })
    }

    const ite = new RangeIterator(
      new Batch(this, this._makeSnapshot(), null, false, opts),
      null,
      opts
    )
    return ite
  }

  createReadStream(range, opts) {
    const signal = (opts && opts.signal) || null
    return iteratorToStream(this.createRangeIterator(range, opts), signal)
  }

  createHistoryStream(opts) {
    const session = opts && opts.live ? this.core.session() : this._makeSnapshot()
    const signal = (opts && opts.signal) || null
    return iteratorToStream(
      new HistoryIterator(new Batch(this, session, null, false, opts), opts),
      signal
    )
  }

  createDiffStream(right, range, opts) {
    if (typeof right === 'number') right = this.checkout(Math.max(1, right), { reuseSession: true })

    // backwards compat range arg
    opts = opts ? { ...opts, ...range } : range

    const signal = (opts && opts.signal) || null

    const keyEncoding = opts && opts.keyEncoding ? codecs(opts.keyEncoding) : this.keyEncoding
    if (keyEncoding) opts = encRange(keyEncoding, { ...opts, sub: this._sub })

    let done
    let closing
    let ite

    const left = this

    const rs = new Readable({
      signal,
      eagerOpen: true,
      async open(cb) {
        try {
          if (right.opened === false) await right.ready()
          if (left.opened === false) await left.ready()
        } catch (err) {
          cb(err)
          return
        }

        if (closing) {
          cb(null)
          return
        }

        if (left.core.closing || right.core.closing) {
          cb(new Error('Bee closed'))
          return
        }

        const snapshot = right.version > left.version ? right._makeSnapshot() : left._makeSnapshot()

        done = cb
        ite = new DiffIterator(
          new Batch(left, snapshot, null, false, opts),
          new Batch(right, snapshot, null, false, opts),
          opts
        )
        ite.open().then(fin, fin)
      },
      read(cb) {
        done = cb
        ite.next().then(push, fin)
      },
      predestroy() {
        if (!ite) {
          closing = Promise.resolve()
        } else {
          closing = ite.close()
          closing.catch(noop)
        }
      },
      destroy(cb) {
        done = cb
        if (!closing) closing = ite.close()
        closing.then(fin, fin)
      }
    })

    return rs

    function fin(err) {
      done(err)
    }

    function push(val) {
      rs.push(val)
      done(null)
    }
  }

  get(key, opts) {
    const b = new Batch(this, this._makeSnapshot(), null, true, opts)
    return b.get(key)
  }

  getBySeq(seq, opts) {
    const b = new Batch(this, this._makeSnapshot(), null, true, opts)
    return b.getBySeq(seq)
  }

  put(key, value, opts) {
    const b = new Batch(this, this.core, null, true, opts)
    return b.put(key, value, opts)
  }

  batch(opts) {
    return new Batch(this, this.core, mutexify(), true, opts)
  }

  del(key, opts) {
    const b = new Batch(this, this.core, null, true, opts)
    return b.del(key, opts)
  }

  watch(range, opts) {
    if (!this._watchers) throw new Error('Can only watch the main bee instance')
    return new Watcher(this, range, opts)
  }

  async getAndWatch(key, opts) {
    if (!this._watchers) throw new Error('Can only watch the main bee instance')

    const watcher = new EntryWatcher(this, key, opts)
    await watcher._debouncedUpdate()

    if (this.closing) {
      await watcher.close()
      throw new Error('Bee closed')
    }

    return watcher
  }

  _onappend() {
    for (const watcher of this._watchers) {
      watcher._onappend()
    }

    for (const watcher of this._entryWatchers) {
      watcher._onappend()
    }
  }

  _ontruncate(length) {
    for (const watcher of this._watchers) {
      watcher._ontruncate()
    }

    for (const watcher of this._entryWatchers) {
      watcher._ontruncate()
    }

    this._nodeCache.gc(length)
    this._keyCache.gc(length)
  }

  _makeSnapshot() {
    if (this._sessions === false) return this.core
    // TODO: better if we could encapsulate this in hypercore in the future
    return this._checkout <= this.core.length || this._checkout <= 1
      ? this.core.snapshot()
      : this.core.session({ snapshot: false })
  }

  async clearUnlinked(options = {}) {
    await this.ready()

    const { gte = 0, lt = this.version - 1, batchSize = 4096, wait = true } = options
    const checkout = this.version

    let prev = this.batch({ wait: false, checkout: gte })
    let b = this.batch({ wait, checkout })

    const iteBatch = this.batch({ wait: false, checkout })
    const ite = new LocalBlockIterator(iteBatch, { gte, lt })
    await ite.open()

    let ticks = 0

    while (true) {
      const data = await ite.next()
      if (!data) break

      if (!(await isLinked(b, data))) {
        if (b.core.closing || this.core.closing || this.closing) break
        await this.core.clear(data.seq)
      }

      const prevNode = await prev.get(data.key, { finalize: false }).catch(toNull)

      if (prevNode && !(await isLinked(b, prevNode))) {
        if (b.core.closing || this.core.closing || this.closing) break
        await this.core.clear(prevNode.seq)
      }

      if (ticks++ >= batchSize) {
        ticks = 0
        await prev.close()
        await b.close()

        prev = this.batch({ wait: false, checkout: gte })
        b = this.batch({ wait, checkout })
      }
    }

    if (b.core.closing || this.core.closing || this.closing) throw new Error('Core is closed')

    await b.close()
    await prev.close()
    await ite.close()
    await iteBatch.close()

    return lt
  }

  checkout(version, opts = {}) {
    if (version === 0) version = 1

    // same as above, just checkout isn't set yet...
    const snap =
      opts.reuseSession || this._sessions === false
        ? this.core
        : version <= this.core.length || version <= 1
          ? this.core.snapshot()
          : this.core.session({ snapshot: false })

    return new Hyperbee(snap, {
      _view: true,
      _sub: false,
      prefix: this.prefix,
      sep: this.sep,
      lock: this.lock,
      checkout: version,
      keyEncoding: opts.keyEncoding || this.keyEncoding,
      valueEncoding: opts.valueEncoding || this.valueEncoding,
      extension: this.extension !== null ? this.extension : false
    })
  }

  snapshot(opts) {
    return this.checkout(
      this.core.opened === false || this._checkout <= 0 ? -1 : Math.max(1, this.version),
      opts
    )
  }

  sub(prefix, opts = {}) {
    let sep = opts.sep || this.sep
    if (!b4a.isBuffer(sep)) sep = b4a.from(sep)

    prefix = b4a.concat([this.prefix || EMPTY, b4a.from(prefix), sep])

    const valueEncoding = codecs(opts.valueEncoding || this.valueEncoding)
    const keyEncoding = codecs(opts.keyEncoding || this._unprefixedKeyEncoding)

    return new Hyperbee(this.core, {
      _view: true,
      _sub: true,
      prefix,
      sep: this.sep,
      lock: this.lock,
      checkout: this._checkout,
      valueEncoding,
      keyEncoding,
      extension: this.extension !== null ? this.extension : false,
      metadata: this.metadata
    })
  }

  async getHeader(opts) {
    const blk = await this.core.get(0, opts)
    try {
      return blk && Header.decode(blk)
    } catch {
      throw DECODING_ERROR()
    }
  }

  async _close() {
    if (!this._view) {
      if (this._keyCache) this._keyCache.clear()
      if (this._nodeCache) this._nodeCache.clear()
    }

    if (this._watchers) {
      this.core.off('append', this._onappendBound)
      this.core.off('truncate', this._ontruncateBound)

      while (this._watchers.length) {
        await this._watchers[this._watchers.length - 1].close()
      }
    }

    if (this._entryWatchers) {
      while (this._entryWatchers.length) {
        await this._entryWatchers[this._entryWatchers.length - 1].close()
      }
    }

    while (this._batches.length) {
      await this._batches[this._batches.length - 1].close()
    }

    return this.core.close()
  }

  static async isHyperbee(core, opts) {
    await core.ready()

    const blk0 = await core.get(0, opts)
    if (blk0 === null) throw BLOCK_NOT_AVAILABLE()

    try {
      return Header.decode(blk0).protocol === 'hyperbee'
    } catch (err) {
      // undecodable
      return false
    }
  }
}

class Batch {
  constructor(tree, core, batchLock, cache, options = {}) {
    this.tree = tree
    // this.feed is now deprecated, and will be this.core going forward
    this.feed = core
    this.core = core
    this.index = tree._batches.push(this) - 1
    this.blocks = cache ? new Map() : null
    this.autoFlush = !batchLock
    this.maxBlocksCached = options.maxBlocksCached || 128
    this.rootSeq = 0
    this.root = null
    this.length = 0
    this.checkout = options.checkout === undefined ? -1 : options.checkout
    this.options = options
    this.locked = null
    this.batchLock = batchLock
    this.onseq = this.options.onseq || noop
    this.appending = null
    this.isSnapshot = this.core !== this.tree.core
    this.shouldUpdate = this.options.update !== false
    this.updating = null
    this.encoding = {
      key: options.keyEncoding ? codecs(options.keyEncoding) : tree.keyEncoding,
      value: options.valueEncoding ? codecs(options.valueEncoding) : tree.valueEncoding
    }
  }

  async ready() {
    if (this.core.opened === false) await this.core.ready()
    if (this.tree.opened === false) await this.tree.ready()
  }

  async lock() {
    if (this.tree.readonly) throw new Error('Hyperbee is marked as read-only')
    if (this.locked === null) this.locked = await this.tree.lock()
  }

  get version() {
    if (this.checkout !== -1) return Math.max(1, this.checkout)
    return Math.max(1, this.tree._checkout || this.core.length + this.length)
  }

  async getRoot(ensureHeader) {
    await this.ready()
    if (ensureHeader) {
      if (this.core.length === 0 && this.core.writable && !this.tree.readonly) {
        await this.core.append(
          Header.encode({
            protocol: 'hyperbee',
            metadata: this.tree.metadata
          })
        )
      }
    }
    if (this.tree._checkout === 0 && this.checkout === -1 && this.shouldUpdate) {
      if (this.updating === null) this.updating = this.core.update()
      await this.updating
    }
    if (this.version < 2) return null
    return (await this.getBlock(this.version - 1)).getTreeNode(0)
  }

  async getKey(seq) {
    await this.tree._cacheLock.enter(seq)

    try {
      const k = this.core.fork === this.tree.core.fork ? this.tree._keyCache.get(seq) : null
      if (k !== null) return k
      const key = (await this._getBlock(seq)).key
      if (this.core.fork === this.tree.core.fork) this.tree._keyCache.set(seq, key)
      return key
    } finally {
      this.tree._cacheLock.exit(seq)
    }
  }

  async _getNode(seq) {
    const cached =
      this.tree._nodeCache !== null && this.core.fork === this.tree.core.fork
        ? this.tree._nodeCache.get(seq)
        : null
    if (cached !== null) return cached
    const entry = await this.core.get(seq, {
      ...this.options,
      valueEncoding: Node
    })
    if (entry === null) throw BLOCK_NOT_AVAILABLE()
    const wrap = copyEntry(entry)
    if (this.core.fork === this.tree.core.fork && this.tree._nodeCache !== null) {
      this.tree._nodeCache.set(seq, wrap)
    }
    return wrap
  }

  async getBlock(seq) {
    if (this.rootSeq === 0) this.rootSeq = seq
    await this.tree._cacheLock.enter(seq)

    try {
      return await this._getBlock(seq)
    } finally {
      this.tree._cacheLock.exit(seq)
    }
  }

  async _getBlock(seq) {
    let b = this.blocks && this.blocks.get(seq)
    if (b) return b
    this.onseq(seq)
    const entry = await this._getNode(seq)
    b = this.blocks && this.blocks.get(seq)
    if (b) return b
    b = new BlockEntry(seq, this, entry)
    if (this.blocks && this.blocks.size - this.length < this.maxBlocksCached) {
      this.blocks.set(seq, b)
    }
    return b
  }

  _onwait(key) {
    this.options.onwait = null
    this.tree.extension.get(this.rootSeq + 1, key)
  }

  _getEncoding(opts) {
    if (!opts) return this.encoding
    return {
      key: opts.keyEncoding ? codecs(opts.keyEncoding) : this.encoding.key,
      value: opts.valueEncoding ? codecs(opts.valueEncoding) : this.encoding.value
    }
  }

  peek(range, opts) {
    return iteratorPeek(this.createRangeIterator(range, { ...opts, limit: 1 }))
  }

  createRangeIterator(range, opts = {}) {
    // backwards compat range arg
    opts = opts ? { ...opts, ...range } : range

    const encoding = this._getEncoding(opts)
    return new RangeIterator(
      this,
      encoding,
      encRange(encoding.key, { ...opts, sub: this.tree._sub })
    )
  }

  createReadStream(range, opts) {
    const signal = (opts && opts.signal) || null
    return iteratorToStream(this.createRangeIterator(range, opts), signal)
  }

  async getBySeq(seq, opts) {
    const encoding = this._getEncoding(opts)

    try {
      const block = (await this.getBlock(seq)).final(encoding)
      return { key: block.key, value: block.value }
    } finally {
      await this._closeSnapshot()
    }
  }

  async get(key, opts) {
    const encoding = this._getEncoding(opts)
    const finalize = opts ? opts.finalize !== false : true

    try {
      return await this._get(key, encoding, finalize)
    } finally {
      await this._closeSnapshot()
    }
  }

  async _get(key, encoding, finalize) {
    key = enc(encoding.key, key)

    if (this.tree.extension !== null && this.options.extension !== false) {
      this.options.onwait = this._onwait.bind(this, key)
    }

    let node = await this.getRoot(false)
    if (!node) return null

    while (true) {
      if (node.block.isTarget(key)) {
        return node.block.isDeletion() ? null : finalize ? node.block.final(encoding) : node.block
      }

      let s = 0
      let e = node.keys.length
      let c

      while (s < e) {
        const mid = (s + e) >> 1

        c = b4a.compare(key, await node.getKey(mid))

        if (c === 0) {
          const block = await this.getBlock(node.keys[mid].seq)
          return finalize ? block.final(encoding) : block
        }

        if (c < 0) e = mid
        else s = mid + 1
      }

      if (!node.children.length) return null

      const i = c < 0 ? e : s
      node = await node.getChildNode(i)
    }
  }

  async links(key, seq) {
    let node = await this.getRoot(false)
    if (!node) return false

    if (node.block.seq === seq) return true

    while (true) {
      if (node.block.isTarget(key)) return false

      let s = 0
      let e = node.keys.length
      let c

      while (s < e) {
        const mid = (s + e) >> 1

        if (node.keys[mid].seq === seq) return true
        c = b4a.compare(key, await node.getKey(mid))

        if (c === 0) return false

        if (c < 0) e = mid
        else s = mid + 1
      }

      if (!node.children.length) return false

      const i = c < 0 ? e : s
      node = await node.getChildNode(i)
      if (node.block.seq === seq) return true
    }
  }

  async put(key, value, opts) {
    const release = this.batchLock ? await this.batchLock() : null

    const cas = (opts && opts.cas) || null
    const encoding = this._getEncoding(opts)

    if (!this.locked) await this.lock()
    if (!release) return this._put(key, value, encoding, cas)

    try {
      return await this._put(key, value, encoding, cas)
    } finally {
      release()
    }
  }

  async _put(key, value, encoding, cas) {
    const newNode = {
      seq: 0,
      key,
      value
    }
    key = enc(encoding.key, key)
    value = enc(encoding.value, value)

    const stack = []

    let root
    let node = (root = await this.getRoot(true))
    if (!node) node = root = TreeNode.create(null)

    const seq = (newNode.seq = this.core.length + this.length)
    const target = new Key(seq, key)

    while (node.children.length) {
      stack.push(node)
      node.changed = true // changed, but compressible

      let s = 0
      let e = node.keys.length
      let c

      while (s < e) {
        const mid = (s + e) >> 1
        c = b4a.compare(target.value, await node.getKey(mid))

        if (c === 0) {
          if (cas) {
            const prev = await node.getKeyNode(mid)
            if (!(await cas(prev.final(encoding), newNode))) return this._unlockMaybe()
          }
          if (!this.tree.alwaysDuplicate) {
            const prev = await node.getKeyNode(mid)
            if (sameValue(prev.value, value)) return this._unlockMaybe()
          }
          node.setKey(mid, target)
          return this._append(root, seq, key, value)
        }

        if (c < 0) e = mid
        else s = mid + 1
      }

      const i = c < 0 ? e : s
      node = await node.getChildNode(i)
    }

    let needsSplit = !(await node.insertKey(target, value, null, newNode, encoding, cas))
    if (!node.changed) return this._unlockMaybe()

    while (needsSplit) {
      const parent = stack.pop()
      const { median, right } = await node.split()

      if (parent) {
        needsSplit = !(await parent.insertKey(median, value, right, null, encoding, null))
        node = parent
      } else {
        root = TreeNode.create(node.block)
        root.changed = true
        root.keys.push(median)
        root.children.push(new Child(0, 0, node), new Child(0, 0, right))
        needsSplit = false
      }
    }

    return this._append(root, seq, key, value)
  }

  async del(key, opts) {
    const release = this.batchLock ? await this.batchLock() : null
    const cas = (opts && opts.cas) || null
    const encoding = this._getEncoding(opts)

    if (!this.locked) await this.lock()
    if (!release) return this._del(key, encoding, cas)

    try {
      return await this._del(key, encoding, cas)
    } finally {
      release()
    }
  }

  async _del(key, encoding, cas) {
    const delNode = {
      seq: 0,
      key,
      value: null
    }

    key = enc(encoding.key, key)

    const stack = []

    let node = await this.getRoot(true)
    if (!node) return this._unlockMaybe()

    const seq = (delNode.seq = this.core.length + this.length)

    while (true) {
      stack.push(node)

      let s = 0
      let e = node.keys.length
      let c

      while (s < e) {
        const mid = (s + e) >> 1
        c = b4a.compare(key, await node.getKey(mid))

        if (c === 0) {
          if (cas) {
            const prev = await node.getKeyNode(mid)
            if (!(await cas(prev.final(encoding), delNode))) return this._unlockMaybe()
          }
          if (node.children.length) await setKeyToNearestLeaf(node, mid, stack)
          else node.removeKey(mid)
          // we mark these as changed late, so we don't rewrite them if it is a 404
          for (const node of stack) node.changed = true
          return this._append(await rebalance(stack), seq, key, null)
        }

        if (c < 0) e = mid
        else s = mid + 1
      }

      if (!node.children.length) return this._unlockMaybe()

      const i = c < 0 ? e : s
      node = await node.getChildNode(i)
    }
  }

  async _closeSnapshot() {
    if (this.isSnapshot) {
      await this.core.close()
      this._finalize()
    }
  }

  async close() {
    if (this.isSnapshot) return this._closeSnapshot()

    this.root = null
    if (this.blocks) this.blocks.clear()
    this.length = 0
    this._unlock()
  }

  destroy() {
    // compat, remove later
    this.close().catch(noop)
  }

  toBlocks() {
    if (this.appending) return this.appending

    const batch = new Array(this.length)

    for (let i = 0; i < this.length; i++) {
      const seq = this.core.length + i
      const { pendingIndex, key, value } = this.blocks.get(seq)

      if (i < this.length - 1) {
        pendingIndex[0] = null
        let j = 0

        while (j < pendingIndex.length) {
          const idx = pendingIndex[j]
          if (idx !== null && idx.seq === seq) {
            idx.offset = j++
            continue
          }
          if (j === pendingIndex.length - 1) pendingIndex.pop()
          else pendingIndex[j] = pendingIndex.pop()
        }
      }

      batch[i] = Node.encode({
        key,
        value,
        index: deflate(pendingIndex)
      })
    }

    this.appending = batch
    return batch
  }

  flush() {
    if (!this.length) return this.close()

    const batch = this.toBlocks()

    this.root = null
    this.blocks.clear()
    this.length = 0

    return this._appendBatch(batch)
  }

  _unlockMaybe() {
    if (this.autoFlush) this._unlock()
  }

  _unlock() {
    const locked = this.locked
    this.locked = null
    if (locked !== null) locked()
    this._finalize()
  }

  _finalize() {
    // technically finalize can be called more than once, so here we just check if we already have been removed
    if (this.index >= this.tree._batches.length || this.tree._batches[this.index] !== this) return
    const top = this.tree._batches.pop()
    if (top === this) return
    top.index = this.index
    this.tree._batches[top.index] = top
  }

  _append(root, seq, key, value) {
    const index = []
    root.indexChanges(index, seq)
    index[0] = new Child(seq, 0, root)

    if (!this.autoFlush) {
      const block = new BatchEntry(seq, this, key, value, index)
      root.block = block
      this.root = root
      this.length++
      this.blocks.set(seq, block)

      root.updateChildren(seq, block)
      return
    }

    return this._appendBatch(
      Node.encode({
        key,
        value,
        index: deflate(index)
      })
    )
  }

  async _appendBatch(raw) {
    try {
      await this.core.append(raw)
    } finally {
      this._unlock()
    }
  }
}

class EntryWatcher extends ReadyResource {
  constructor(bee, key, opts = {}) {
    super()

    this.keyEncoding = opts.keyEncoding || bee.keyEncoding
    this.valueEncoding = opts.valueEncoding || bee.valueEncoding

    this.index = bee._entryWatchers.push(this) - 1
    this.bee = bee

    this.key = key
    this.node = null

    this._forceUpdate = false
    this._debouncedUpdate = debounce(this._processUpdate.bind(this))
  }

  _close() {
    const top = this.bee._entryWatchers.pop()
    if (top !== this) {
      top.index = this.index
      this.bee._entryWatchers[top.index] = top
    }
  }

  _onappend() {
    this._debouncedUpdate()
  }

  _ontruncate() {
    this._forceUpdate = true
    this._debouncedUpdate()
  }

  async _processUpdate() {
    const force = this._forceUpdate
    this._forceUpdate = false

    let newNode
    try {
      newNode = await this.bee.get(this.key, {
        keyEncoding: this.keyEncoding,
        valueEncoding: this.valueEncoding
      })
    } catch (e) {
      if (e.code === 'SNAPSHOT_NOT_AVAILABLE') {
        // There was a truncate event before the get resolved
        // So this handler will run again anyway
        return
      } else if (this.bee.closing) {
        this.close().catch(safetyCatch)
        return
      }
      this.emit('error', e)
      return
    }

    if (force || newNode?.seq !== this.node?.seq) {
      this.node = newNode
      this.emit('update')
    }
  }
}

class Watcher extends ReadyResource {
  constructor(bee, range, opts = {}) {
    super()

    this.keyEncoding = opts.keyEncoding || bee.keyEncoding
    this.valueEncoding = opts.valueEncoding || bee.valueEncoding
    this.index = bee._watchers.push(this) - 1
    this.bee = bee
    this.core = bee.core

    this.latestDiff = 0
    this.range = range
    this.map = opts.map || defaultWatchMap

    this.current = null
    this.previous = null
    this.currentMapped = null
    this.previousMapped = null
    this.stream = null

    this._lock = mutexify()
    this._flowing = false
    this._resolveOnChange = null
    this._differ = opts.differ || defaultDiffer
    this._eager = !!opts.eager
    this._onchange = opts.onchange || null

    this.on('newListener', autoFlowOnUpdate)

    this.ready().catch(safetyCatch)
  }

  async _consume() {
    if (this._flowing) return
    try {
      for await (const _ of this) {
      } // eslint-disable-line
    } catch {}
  }

  async _open() {
    await this.bee.ready()

    const opts = {
      keyEncoding: this.keyEncoding,
      valueEncoding: this.valueEncoding
    }

    // Point from which to start watching
    this.current = this._eager ? this.bee.checkout(1, opts) : this.bee.snapshot(opts)
    await this.current.ready()

    if (this._onchange) {
      if (this._eager) await this._onchange()
      this._consume()
    }
  }

  [Symbol.asyncIterator]() {
    this._flowing = true
    return this
  }

  _ontruncate() {
    this._onappend()
  }

  _onappend() {
    const resolve = this._resolveOnChange
    this._resolveOnChange = null
    if (resolve) resolve()
  }

  async _waitForChanges() {
    if (this.current.version < this.bee.version || this.closing) return

    await new Promise((resolve) => {
      this._resolveOnChange = resolve
    })
  }

  async next() {
    try {
      return await this._next()
    } catch (err) {
      if (this.closing) return { value: undefined, done: true }
      await this.close()
      throw err
    }
  }

  async _next() {
    const release = await this._lock()

    try {
      if (this.closing) return { value: undefined, done: true }

      if (!this.opened) await this.ready()

      while (true) {
        await this._waitForChanges()

        if (this.closing) return { value: undefined, done: true }

        await this._closePrevious()
        this.previous = this.current.snapshot()

        await this._closeCurrent()
        this.current = this.bee.snapshot({
          keyEncoding: this.keyEncoding,
          valueEncoding: this.valueEncoding
        })

        await this.current.ready()
        await this.previous.ready()

        if (this.current.core.fork !== this.previous.core.fork) {
          return await this._yield()
        }

        this.stream = this._differ(this.current, this.previous, this.range)

        try {
          for await (const data of this.stream) {
            // eslint-disable-line
            return await this._yield()
          }
        } finally {
          this.stream = null
        }
      }
    } finally {
      release()
    }
  }

  async _yield() {
    this.currentMapped = this.map(this.current)
    this.previousMapped = this.map(this.previous)

    if (this._onchange) {
      try {
        await this._onchange()
      } catch (err) {
        safetyCatch(err)
      }
    }

    this.emit('update')
    return { done: false, value: [this.currentMapped, this.previousMapped] }
  }

  async return() {
    await this.close()
    return { done: true }
  }

  async _close() {
    const top = this.bee._watchers.pop()
    if (top !== this) {
      top.index = this.index
      this.bee._watchers[top.index] = top
    }

    if (this.stream && !this.stream.destroying) {
      this.stream.destroy()
    }

    this._onappend() // Continue execution being closed

    await this._closeCurrent().catch(safetyCatch)
    await this._closePrevious().catch(safetyCatch)

    const release = await this._lock()
    release()
  }

  destroy() {
    return this.close()
  }

  async _closeCurrent() {
    if (this.currentMapped) await this.currentMapped.close()
    if (this.current) await this.current.close()
    this.current = this.currentMapped = null
  }

  async _closePrevious() {
    if (this.previousMapped) await this.previousMapped.close()
    if (this.previous) await this.previous.close()
    this.previous = this.previousMapped = null
  }
}

function autoFlowOnUpdate(name) {
  if (name === 'update') this._consume()
}

function defaultWatchMap(snapshot) {
  return snapshot
}

async function leafSize(node, goLeft) {
  while (node.children.length) node = await node.getChildNode(goLeft ? 0 : node.children.length - 1)
  return node.keys.length
}

async function setKeyToNearestLeaf(node, index, stack) {
  let [left, right] = await Promise.all([node.getChildNode(index), node.getChildNode(index + 1)])
  const [ls, rs] = await Promise.all([leafSize(left, false), leafSize(right, true)])

  if (ls < rs) {
    // if fewer leaves on the left
    stack.push(right)
    while (right.children.length) stack.push((right = right.children[0].value))
    node.keys[index] = right.keys.shift()
  } else {
    // if fewer leaves on the right
    stack.push(left)
    while (left.children.length) stack.push((left = left.children[left.children.length - 1].value))
    node.keys[index] = left.keys.pop()
  }
}

async function rebalance(stack) {
  const root = stack[0]

  while (stack.length > 1) {
    const node = stack.pop()
    const parent = stack[stack.length - 1]

    if (node.keys.length >= MIN_KEYS) return root

    let { left, index, right } = await node.siblings(parent)

    // maybe borrow from left sibling?
    if (left && left.keys.length > MIN_KEYS) {
      left.changed = true
      node.keys.unshift(parent.keys[index - 1])
      if (left.children.length) node.children.unshift(left.children.pop())
      parent.keys[index - 1] = left.keys.pop()
      return root
    }

    // maybe borrow from right sibling?
    if (right && right.keys.length > MIN_KEYS) {
      right.changed = true
      node.keys.push(parent.keys[index])
      if (right.children.length) node.children.push(right.children.shift())
      parent.keys[index] = right.keys.shift()
      return root
    }

    // merge node with another sibling
    if (left) {
      index--
      right = node
    } else {
      left = node
    }

    left.merge(right, parent.keys[index])
    parent.removeKey(index)
  }

  // check if the tree shrunk
  if (!root.keys.length && root.children.length) return root.getChildNode(0)
  return root
}

function iteratorToStream(ite, signal) {
  let done
  let closing

  const rs = new Readable({
    signal,
    open(cb) {
      done = cb
      ite.open().then(fin, fin)
    },
    read(cb) {
      done = cb
      ite.next().then(push, fin)
    },
    predestroy() {
      closing = ite.close()
      closing.catch(noop)
    },
    destroy(cb) {
      done = cb
      if (!closing) closing = ite.close()
      closing.then(fin, fin)
    }
  })

  return rs

  function fin(err) {
    done(err)
  }

  function push(val) {
    rs.push(val)
    done(null)
  }
}

async function iteratorPeek(ite) {
  try {
    await ite.open()
    return await ite.next()
  } finally {
    await ite.close()
  }
}

function encRange(e, opts) {
  if (!e) return opts

  if (e.encodeRange) {
    const r = e.encodeRange({
      gt: opts.gt,
      gte: opts.gte,
      lt: opts.lt,
      lte: opts.lte
    })
    opts.gt = r.gt
    opts.gte = r.gte
    opts.lt = r.lt
    opts.lte = r.lte
    return opts
  }

  if (opts.gt !== undefined) opts.gt = enc(e, opts.gt)
  if (opts.gte !== undefined) opts.gte = enc(e, opts.gte)
  if (opts.lt !== undefined) opts.lt = enc(e, opts.lt)
  if (opts.lte !== undefined) opts.lte = enc(e, opts.lte)
  if (opts.sub && !opts.gt && !opts.gte) opts.gt = enc(e, SEP)
  if (opts.sub && !opts.lt && !opts.lte) opts.lt = bump(enc(e, EMPTY))

  return opts
}

function bump(key) {
  // key should have been copied by enc above before hitting this
  key[key.length - 1]++
  return key
}

function enc(e, v) {
  if (v === undefined || v === null) return null
  if (e !== null) return e.encode(v)
  if (typeof v === 'string') return b4a.from(v)
  return v
}

function prefixEncoding(prefix, keyEncoding) {
  return {
    encode(key) {
      return b4a.concat([prefix, b4a.isBuffer(key) ? key : enc(keyEncoding, key)])
    },
    decode(key) {
      const sliced = key.slice(prefix.length, key.length)
      return keyEncoding ? keyEncoding.decode(sliced) : sliced
    }
  }
}

function copyEntry(entry) {
  let key = entry.key
  let value = entry.value
  let index = entry.index

  // key, value and index all refer to the same buffer (one hypercore block)
  // If together they are larger than half the buffer's byteLength,
  // this means that they got their own private slab (see Buffer.allocUnsafe docs)
  // so no need to unslab
  const size =
    key.byteLength +
    (value === null ? 0 : value.byteLength) +
    (index === null ? 0 : index.byteLength)
  if (2 * size < key.buffer.byteLength) {
    const [newKey, newValue, newIndex] = unslabAll([entry.key, entry.value, entry.index])
    key = newKey
    value = newValue
    index = newIndex
  }

  return {
    key,
    value,
    index,
    inflated: null
  }
}

function defaultDiffer(currentSnap, previousSnap, opts) {
  return currentSnap.createDiffStream(previousSnap, opts)
}

function toNull() {
  return null
}

function getBackingCore(core) {
  if (core.core) return core
  if (core.getBackingCore) return core.getBackingCore().session
  return null
}

function sameValue(a, b) {
  return a === b || (a !== null && b !== null && b4a.equals(a, b))
}

function noop() {}

function getExtension(db, opts) {
  if (opts.extension === false) return null
  if (opts.extension && opts.extension !== true) return opts.extension
  return Extension.register(db)
}

async function isLinked(batch, block) {
  const seq = block.seq
  block.inflate()

  const keys = [block.key]
  const wait = batch.options.wait

  for (const l of block.index.levels) {
    if (!l.keys.length) continue
    batch.options.wait = false
    try {
      keys.push(await batch.getKey(l.keys[0].seq))
    } catch {}
    batch.options.wait = wait
  }

  for (const k of keys) {
    if (await batch.links(k, seq)) return true
  }

  if (batch.core.closing) throw new Error('Core is closed')

  return false
}

module.exports = Hyperbee
const b4a = require('b4a')

class SubTree {
  constructor(node, parent) {
    this.node = node
    this.parent = parent

    this.isKey = node.children.length === 0
    this.i = this.isKey ? 1 : 0
    this.n = 0

    const child = this.isKey ? null : this.node.children[0]
    this.seq = child !== null ? child.seq : this.node.keys[0].seq
    this.offset = child !== null ? child.offset : 0
  }

  next() {
    this.i++
    this.isKey = (this.i & 1) === 1
    if (!this.isKey && !this.node.children.length) this.i++
    return this.update()
  }

  async bisect(key, incl) {
    let s = 0
    let e = this.node.keys.length
    let c

    while (s < e) {
      const mid = (s + e) >> 1
      c = cmp(key, await this.node.getKey(mid))

      if (c === 0) {
        if (incl) this.i = mid * 2 + 1
        else this.i = mid * 2 + (this.node.children.length ? 2 : 3)
        return true
      }

      if (c < 0) e = mid
      else s = mid + 1
    }

    const i = c < 0 ? e : s
    this.i = 2 * i + (this.node.children.length ? 0 : 1)
    return this.node.children.length === 0
  }

  update() {
    this.isKey = (this.i & 1) === 1
    this.n = this.i >> 1
    if (this.n >= (this.isKey ? this.node.keys.length : this.node.children.length)) return false
    const child = this.isKey ? null : this.node.children[this.n]
    this.seq = child !== null ? child.seq : this.node.keys[this.n].seq
    this.offset = child !== null ? child.offset : 0
    return true
  }

  async key() {
    return this.n < this.node.keys.length
      ? this.node.getKey(this.n)
      : this.parent && this.parent.key()
  }

  async compare(tree) {
    const [a, b] = await Promise.all([this.key(), tree.key()])
    return cmp(a, b)
  }
}

class TreeIterator {
  constructor(batch, opts) {
    this.batch = batch
    this.stack = []
    this.lt = opts.lt || opts.lte || null
    this.lte = !!opts.lte
    this.gt = opts.gt || opts.gte || null
    this.gte = !!opts.gte
    this.seeking = !!this.gt
    this.encoding = opts.encoding || batch.encoding
  }

  async open() {
    const node = await this.batch.getRoot(false)
    if (!node || !node.keys.length) return
    const tree = new SubTree(node, null)
    if (this.seeking && !(await this._seek(tree))) return
    this.stack.push(tree)
  }

  async _seek(tree) {
    const done = await tree.bisect(this.gt, this.gte)
    const oob = !tree.update()
    if (done || oob) {
      this.seeking = false
      if (oob) return false
    }
    return true
  }

  peek() {
    if (!this.stack.length) return null
    return this.stack[this.stack.length - 1]
  }

  skip() {
    if (!this.stack.length) return
    if (!this.stack[this.stack.length - 1].next()) this.stack.pop()
  }

  async nextKey() {
    let n = null
    while (this.stack.length && n === null) n = await this.next()
    if (n === null) return null
    if (!this.lt) return n.final(this.encoding)

    const c = cmp(n.key, this.lt)
    if (this.lte ? c <= 0 : c < 0) return n.final(this.encoding)
    this.stack = []
    return null
  }

  async next() {
    if (!this.stack.length) return null

    const top = this.stack[this.stack.length - 1]
    const { isKey, n, seq } = top

    if (!top.next()) {
      this.stack.pop()
    }

    if (isKey) {
      this.seeking = false
      return this.batch.getBlock(seq)
    }

    const child = await top.node.getChildNode(n)
    top.node.children[n] = null // unlink to save memory
    const tree = new SubTree(child, top)
    if (this.seeking && !(await this._seek(tree))) return null
    this.stack.push(tree)

    return null
  }

  close() {
    return this.batch._closeSnapshot()
  }
}

module.exports = class DiffIterator {
  constructor(left, right, opts = {}) {
    this.left = new TreeIterator(left, opts)
    this.right = new TreeIterator(right, opts)
    this.limit = typeof opts.limit === 'number' ? opts.limit : -1
  }

  async open() {
    await Promise.all([this.left.open(), this.right.open()])
  }

  async next() {
    if (this.limit === 0) return null
    const res = await this._next()
    if (!res || (res.left === null && res.right === null)) return null
    this.limit--
    return res
  }

  async _next() {
    const a = this.left
    const b = this.right

    while (true) {
      const [l, r] = await Promise.all([a.peek(), b.peek()])

      if (!l && !r) return null
      if (!l) return { left: null, right: await b.nextKey() }
      if (!r) return { left: await a.nextKey(), right: null }

      if (l.seq === r.seq && l.isKey === r.isKey && l.offset === r.offset) {
        a.skip()
        b.skip()
        continue
      }

      const c = await l.compare(r)

      if (l.isKey && !r.isKey) {
        await b.next()
        continue
      }

      if (!l.isKey && r.isKey) {
        await a.next()
        continue
      }

      if (l.isKey && r.isKey) {
        if (c === 0) return { left: await a.nextKey(), right: await b.nextKey() }
        if (c < 0) return { left: await a.nextKey(), right: null }
        return { left: null, right: await b.nextKey() }
      }

      if (c === 0) await Promise.all([a.next(), b.next()])
      else if (c < 0) await b.next()
      else await a.next()
    }
  }

  async close() {
    await Promise.all([this.left.close(), this.right.close()])
  }
}

function cmp(a, b) {
  if (!a) return b ? 1 : 0
  if (!b) return a ? -1 : 0
  return b4a.compare(a, b)
}
module.exports = class HistoryIterator {
  constructor(batch, opts = {}) {
    this.batch = batch
    this.options = opts
    this.live = !!opts.live
    this.gte = 0
    this.lt = 0
    this.reverse = !!opts.reverse
    this.limit = typeof opts.limit === 'number' ? opts.limit : -1
    this.encoding = opts.encoding || batch.encoding
    if (this.live && this.reverse) {
      throw new Error('Cannot have both live and reverse enabled')
    }
  }

  async open() {
    await this.batch.getRoot(false) // does the update dance
    this.gte = gte(this.options, this.batch.version)
    this.lt = this.live ? Infinity : lt(this.options, this.batch.version)
  }

  async next() {
    if (this.limit === 0) return null
    if (this.limit > 0) this.limit--

    if (this.gte >= this.lt) return null

    if (this.reverse) {
      if (this.lt <= 1) return null
      return final(await this.batch.getBlock(--this.lt), this.encoding)
    }

    return final(await this.batch.getBlock(this.gte++), this.encoding)
  }

  close() {
    return this.batch._closeSnapshot()
  }
}

function final(node, encoding) {
  const type = node.isDeletion() ? 'del' : 'put'
  return { type, ...node.final(encoding) }
}

function gte(opts, version) {
  if (opts.gt) return (opts.gt < 0 ? opts.gt + version : opts.gt) + 1
  const gte = opts.gte || opts.since || 1
  return gte < 0 ? gte + version : gte
}

function lt(opts, version) {
  if (opts.lte === 0 || opts.lt === 0 || opts.end === 0) return 0
  if (opts.lte) return (opts.lte < 0 ? opts.lte + version : opts.lte) + 1
  const lt = opts.lt || opts.end || version
  return lt < 0 ? lt + version : lt
}
module.exports = class LocalBlocksIterator {
  constructor(batch, opts = {}) {
    this.batch = batch
    this.options = opts
    this.gte = 0
    this.lt = 0
    this.limit = typeof opts.limit === 'number' ? opts.limit : -1
  }

  async open() {
    await this.batch.getRoot(false) // does the update dance
    this.gte = gte(this.options, this.batch.version)
    this.lt = lt(this.options, this.batch.version)
  }

  async next() {
    if (this.limit === 0) return null
    if (this.limit > 0) this.limit--

    while (this.gte < this.lt) {
      try {
        return await this.batch.getBlock(this.gte++)
      } catch {
        continue
      }
    }

    return null
  }

  close() {
    return this.batch._closeSnapshot()
  }
}

function gte(opts, version) {
  if (opts.gt) return (opts.gt < 0 ? opts.gt + version : opts.gt) + 1
  const gte = opts.gte || opts.since || 1
  return gte < 0 ? gte + version : gte
}

function lt(opts, version) {
  if (opts.lte === 0 || opts.lt === 0 || opts.end === 0) return 0
  if (opts.lte) return (opts.lte < 0 ? opts.lte + version : opts.lte) + 1
  const lt = opts.lt || opts.end || version
  return lt < 0 ? lt + version : lt
}
const b4a = require('b4a')

module.exports = class RangeIterator {
  constructor(batch, encoding, opts = {}) {
    this.batch = batch
    this.stack = []
    this.opened = false
    this.encoding = encoding || batch.encoding

    this._limit = typeof opts.limit === 'number' ? opts.limit : -1
    this._gIncl = !opts.gt
    this._gKey = opts.gt || opts.gte || null
    this._lIncl = !opts.lt
    this._lKey = opts.lt || opts.lte || null
    this._reverse = !!opts.reverse
    this._version = 0
    this._checkpoint = opts.checkpoint && opts.checkpoint.length ? opts.checkpoint : null
    this._nexting = false
    this._closed = false
  }

  snapshot(version = this.batch.version) {
    const checkpoint = []
    for (const s of this.stack) {
      let { node, i } = s
      if (this._nexting && s === this.stack[this.stack.length - 1]) {
        i = this._reverse ? i + 1 : i - 1
      }
      if (!node.block) continue
      if (i < 0) continue
      checkpoint.push(node.block.seq, node.offset, i)
    }

    return {
      version,
      gte: this._gIncl ? this._gKey : null,
      gt: this._gIncl ? null : this._gKey,
      lte: this._lIncl ? this._lKey : null,
      lt: this._lIncl ? null : this._lKey,
      limit: this._limit,
      reverse: this._reverse,
      ended: this.opened && !checkpoint.length,
      checkpoint: this.opened ? checkpoint : []
    }
  }

  async open() {
    await this._open()
    this.opened = true
  }

  async _open() {
    if (this._checkpoint) {
      for (let j = 0; j < this._checkpoint.length; j += 3) {
        const seq = this._checkpoint[j]
        const offset = this._checkpoint[j + 1]
        const i = this._checkpoint[j + 2]
        this.stack.push({
          node: (await this.batch.getBlock(seq)).getTreeNode(offset),
          i
        })
      }
      return
    }

    this._nexting = true

    let node = await this.batch.getRoot(false)
    if (!node) {
      this._nexting = false
      return
    }

    const incl = this._reverse ? this._lIncl : this._gIncl
    const start = this._reverse ? this._lKey : this._gKey

    if (!start) {
      this.stack.push({ node, i: this._reverse ? node.keys.length << 1 : 0 })
      this._nexting = false
      this._preloadQuery()
      return
    }

    while (true) {
      const entry = { node, i: this._reverse ? node.keys.length << 1 : 0 }

      let s = 0
      let e = node.keys.length
      let c

      while (s < e) {
        const mid = (s + e) >> 1
        c = b4a.compare(start, await node.getKey(mid))

        if (c === 0) {
          if (incl) entry.i = mid * 2 + 1
          else entry.i = mid * 2 + (this._reverse ? 0 : 2)
          this.stack.push(entry)
          this._nexting = false
          this._preloadQuery()
          return
        }

        if (c < 0) e = mid
        else s = mid + 1
      }

      const i = c < 0 ? e : s
      entry.i = 2 * i + (this._reverse ? -1 : 1)

      if (entry.i >= 0 && entry.i <= node.keys.length << 1) this.stack.push(entry)
      if (!node.children.length) {
        this._nexting = false
        this._preloadQuery()
        return
      }

      node = await node.getChildNode(i)
    }
  }

  _preloadQuery() {
    const max = { nodes: 0, max: 2048 }

    if (this._limit === -1 && !this._reverse && this.stack.length) {
      for (const s of this.stack) {
        const k = (s.i - (s.i & 1)) / 2
        this._preload(s.node, k + 1, this._lKey, max).catch(noop)
      }
    }
  }

  async _preload(node, i, end, max) {
    for (; i < node.keys.length; i++) {
      const key = node.keys[i]
      const block = await this.batch.getBlock(key.seq)
      if (this._closed) return
      const c = end ? b4a.compare(block.key, end) : -1
      if (c >= 0 || max.nodes >= max.max || i >= node.children.length) return
      max.nodes++
      const next = await node.getChildNode(i)
      if (this._closed) return
      this._preload(next, 0, end, max).catch(noop)
    }

    if (node.children.length && max.nodes < max.max) {
      const next = await node.getChildNode(node.children.length - 1)
      if (this._closed) return
      this._preload(next, 0, end, max).catch(noop)
    }
  }

  async next() {
    // TODO: this nexting flag is only needed if someone asks for a snapshot during
    // a lookup (ie the extension, pretty important...).
    // A better solution would be to refactor this so top.i is incremented eagerly
    // to get the current block instead of the way it is done now (++i vs i++)
    this._nexting = true

    const end = this._reverse ? this._gKey : this._lKey
    const incl = this._reverse ? this._gIncl : this._lIncl

    while (this.stack.length && (this._limit === -1 || this._limit > 0)) {
      const top = this.stack[this.stack.length - 1]
      const isKey = (top.i & 1) === 1
      const n = this._reverse ? (top.i < 0 ? top.node.keys.length : top.i-- >> 1) : top.i++ >> 1

      if (!isKey) {
        if (!top.node.children.length) continue
        const node = await top.node.getChildNode(n)
        if (top.node.block.seq < this.batch.core.length) {
          top.node.children[n].value = null // unlink it to save memory
        }
        this.stack.push({ i: this._reverse ? node.keys.length << 1 : 0, node })
        continue
      }

      if (n >= top.node.keys.length) {
        this.stack.pop()
        continue
      }

      const key = top.node.keys[n]
      const block = await this.batch.getBlock(key.seq)
      if (end) {
        const c = b4a.compare(block.key, end)
        if (c === 0 ? !incl : this._reverse ? c < 0 : c > 0) {
          this._limit = 0
          break
        }
      }
      if (this._limit > 0) this._limit--
      this._nexting = false
      return block.final(this.encoding)
    }

    this._nexting = false
    return null
  }

  close() {
    this._closed = true
    return this.batch._closeSnapshot()
  }
}

function noop() {}
const { Extension } = require('./messages')

// const MAX_ACTIVE = 32
const FLUSH_BATCH = 128
const MAX_PASSIVE_BATCH = 2048
const MAX_ACTIVE_BATCH = MAX_PASSIVE_BATCH + FLUSH_BATCH

class Batch {
  constructor(outgoing, from) {
    this.blocks = []
    this.start = 0
    this.end = 0
    this.outgoing = outgoing
    this.from = from
  }

  push(seq) {
    const len = this.blocks.push(seq)
    if (len === 1 || seq < this.start) this.start = seq
    if (len === 1 || seq >= this.end) this.end = seq + 1
    if (len >= FLUSH_BATCH) {
      this.send()
      this.clear()
    }
  }

  send() {
    if (!this.blocks.length) return
    this.outgoing.send(
      Extension.encode({
        cache: { blocks: this.blocks, start: this.start, end: this.end }
      }),
      this.from
    )
  }

  clear() {
    this.start = this.end = 0
    this.blocks = []
  }
}

class HyperbeeExtension {
  constructor(db) {
    this.encoding = null
    this.outgoing = null
    this.db = db
    this.active = 0
  }

  get(version, key) {
    this.outgoing.broadcast(Extension.encode({ get: { version, key } }))
  }

  iterator(snapshot) {
    if (snapshot.ended) return
    if (snapshot.limit === 0) return
    if (snapshot.limit === -1) snapshot.limit = 0
    this.outgoing.broadcast(Extension.encode({ iterator: snapshot }))
  }

  onmessage(buf, from) {
    // TODO: handle max active extension messages
    // this.active++

    const message = decode(buf)
    if (!message) return

    if (message.cache) this.oncache(message.cache, from)
    if (message.get) this.onget(message.get, from)
    if (message.iterator) this.oniterator(message.iterator, from)
  }

  oncache(message, from) {
    if (!message.blocks.length) return
    this.db.core.download(message)
  }

  onget(message, from) {
    if (!message.version || message.version > this.db.version) return

    const b = new Batch(this.outgoing, from)
    const db = this.db.checkout(message.version)

    db.get(message.key, {
      extension: false,
      wait: false,
      update: false,
      onseq
    }).then(done, done)

    function done() {
      db.close().catch(noop)
      b.send()
    }

    function onseq(seq) {
      b.push(seq)
    }
  }

  async oniterator(message, from) {
    if (!message.version || message.version > this.db.version) return

    const b = new Batch(this.outgoing, from)
    const seqs = new Set()

    let skip = message.checkpoint.length
    let work = 0

    const db = this.db.checkout(message.version)
    const ite = db.createRangeIterator({
      ...message,
      wait: false,
      extension: false,
      update: false,
      limit: message.limit === 0 ? -1 : message.limit,
      onseq(seq) {
        if (skip && skip--) return
        if (seqs.has(seq)) return
        work++
        seqs.add(seq)
        b.push(seq)
      }
    })

    try {
      await ite.open()
      // eslint-disable-next-line no-unmodified-loop-condition
      while (work < MAX_ACTIVE_BATCH) {
        if (!(await ite.next())) break
      }
    } catch (_) {
      // do nothing
    } finally {
      ite.close().catch(noop)
      db.close().catch(noop)
      b.send()
    }
  }

  static register(db) {
    const e = new this(db)
    e.outgoing = db.core.registerExtension('hyperbee', e)
    return e
  }
}

HyperbeeExtension.BATCH_SIZE = MAX_PASSIVE_BATCH

module.exports = HyperbeeExtension

function decode(buf) {
  try {
    return Extension.decode(buf)
  } catch (err) {
    return null
  }
}

function noop() {}
// This file is auto generated by the protocol-buffers compiler

/* eslint-disable quotes */
/* eslint-disable indent */
/* eslint-disable no-redeclare */
/* eslint-disable camelcase */
/* eslint-disable no-var */

// Remember to `npm install --save protocol-buffers-encodings`
var encodings = require('protocol-buffers-encodings')
var b4a = require('b4a')
var varint = encodings.varint
var skip = encodings.skip

var YoloIndex = exports.YoloIndex = {
  buffer: true,
  encodingLength: null,
  encode: null,
  decode: null
}

var Header = exports.Header = {
  buffer: true,
  encodingLength: null,
  encode: null,
  decode: null
}

var Node = exports.Node = {
  buffer: true,
  encodingLength: null,
  encode: null,
  decode: null
}

var Extension = exports.Extension = {
  buffer: true,
  encodingLength: null,
  encode: null,
  decode: null
}

defineYoloIndex()
defineHeader()
defineNode()
defineExtension()

function defineYoloIndex () {
  var Level = YoloIndex.Level = {
    buffer: true,
    encodingLength: null,
    encode: null,
    decode: null
  }

  defineLevel()

  function defineLevel () {
    Level.encodingLength = encodingLength
    Level.encode = encode
    Level.decode = decode

    function encodingLength (obj) {
      var length = 0
      if (defined(obj.keys)) {
        var packedLen = 0
        for (var i = 0; i < obj.keys.length; i++) {
          if (!defined(obj.keys[i])) continue
          var len = encodings.varint.encodingLength(obj.keys[i])
          packedLen += len
        }
        if (packedLen) {
          length += 1 + packedLen + varint.encodingLength(packedLen)
        }
      }
      if (defined(obj.children)) {
        var packedLen = 0
        for (var i = 0; i < obj.children.length; i++) {
          if (!defined(obj.children[i])) continue
          var len = encodings.varint.encodingLength(obj.children[i])
          packedLen += len
        }
        if (packedLen) {
          length += 1 + packedLen + varint.encodingLength(packedLen)
        }
      }
      return length
    }

    function encode (obj, buf, offset) {
      if (!offset) offset = 0
      if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
      var oldOffset = offset
      if (defined(obj.keys)) {
        var packedLen = 0
        for (var i = 0; i < obj.keys.length; i++) {
          if (!defined(obj.keys[i])) continue
          packedLen += encodings.varint.encodingLength(obj.keys[i])
        }
        if (packedLen) {
          buf[offset++] = 10
          varint.encode(packedLen, buf, offset)
          offset += varint.encode.bytes
        }
        for (var i = 0; i < obj.keys.length; i++) {
          if (!defined(obj.keys[i])) continue
          encodings.varint.encode(obj.keys[i], buf, offset)
          offset += encodings.varint.encode.bytes
        }
      }
      if (defined(obj.children)) {
        var packedLen = 0
        for (var i = 0; i < obj.children.length; i++) {
          if (!defined(obj.children[i])) continue
          packedLen += encodings.varint.encodingLength(obj.children[i])
        }
        if (packedLen) {
          buf[offset++] = 18
          varint.encode(packedLen, buf, offset)
          offset += varint.encode.bytes
        }
        for (var i = 0; i < obj.children.length; i++) {
          if (!defined(obj.children[i])) continue
          encodings.varint.encode(obj.children[i], buf, offset)
          offset += encodings.varint.encode.bytes
        }
      }
      encode.bytes = offset - oldOffset
      return buf
    }

    function decode (buf, offset, end) {
      if (!offset) offset = 0
      if (!end) end = buf.length
      if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
      var oldOffset = offset
      var obj = {
        keys: [],
        children: []
      }
      while (true) {
        if (end <= offset) {
          decode.bytes = offset - oldOffset
          return obj
        }
        var prefix = varint.decode(buf, offset)
        offset += varint.decode.bytes
        var tag = prefix >> 3
        switch (tag) {
          case 1:
          var packedEnd = varint.decode(buf, offset)
          offset += varint.decode.bytes
          packedEnd += offset
          while (offset < packedEnd) {
            obj.keys.push(encodings.varint.decode(buf, offset))
            offset += encodings.varint.decode.bytes
          }
          break
          case 2:
          var packedEnd = varint.decode(buf, offset)
          offset += varint.decode.bytes
          packedEnd += offset
          while (offset < packedEnd) {
            obj.children.push(encodings.varint.decode(buf, offset))
            offset += encodings.varint.decode.bytes
          }
          break
          default:
          offset = skip(prefix & 7, buf, offset)
        }
      }
    }
  }

  YoloIndex.encodingLength = encodingLength
  YoloIndex.encode = encode
  YoloIndex.decode = decode

  function encodingLength (obj) {
    var length = 0
    if (defined(obj.levels)) {
      for (var i = 0; i < obj.levels.length; i++) {
        if (!defined(obj.levels[i])) continue
        var len = Level.encodingLength(obj.levels[i])
        length += varint.encodingLength(len)
        length += 1 + len
      }
    }
    return length
  }

  function encode (obj, buf, offset) {
    if (!offset) offset = 0
    if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
    var oldOffset = offset
    if (defined(obj.levels)) {
      for (var i = 0; i < obj.levels.length; i++) {
        if (!defined(obj.levels[i])) continue
        buf[offset++] = 10
        varint.encode(Level.encodingLength(obj.levels[i]), buf, offset)
        offset += varint.encode.bytes
        Level.encode(obj.levels[i], buf, offset)
        offset += Level.encode.bytes
      }
    }
    encode.bytes = offset - oldOffset
    return buf
  }

  function decode (buf, offset, end) {
    if (!offset) offset = 0
    if (!end) end = buf.length
    if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
    var oldOffset = offset
    var obj = {
      levels: []
    }
    while (true) {
      if (end <= offset) {
        decode.bytes = offset - oldOffset
        return obj
      }
      var prefix = varint.decode(buf, offset)
      offset += varint.decode.bytes
      var tag = prefix >> 3
      switch (tag) {
        case 1:
        var len = varint.decode(buf, offset)
        offset += varint.decode.bytes
        obj.levels.push(Level.decode(buf, offset, offset + len))
        offset += Level.decode.bytes
        break
        default:
        offset = skip(prefix & 7, buf, offset)
      }
    }
  }
}

function defineHeader () {
  var Metadata = Header.Metadata = {
    buffer: true,
    encodingLength: null,
    encode: null,
    decode: null
  }

  defineMetadata()

  function defineMetadata () {
    Metadata.encodingLength = encodingLength
    Metadata.encode = encode
    Metadata.decode = decode

    function encodingLength (obj) {
      var length = 0
      if (defined(obj.contentFeed)) {
        var len = encodings.bytes.encodingLength(obj.contentFeed)
        length += 1 + len
      }
      if (defined(obj.userData)) {
        var len = encodings.bytes.encodingLength(obj.userData)
        length += 1 + len
      }
      return length
    }

    function encode (obj, buf, offset) {
      if (!offset) offset = 0
      if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
      var oldOffset = offset
      if (defined(obj.contentFeed)) {
        buf[offset++] = 10
        encodings.bytes.encode(obj.contentFeed, buf, offset)
        offset += encodings.bytes.encode.bytes
      }
      if (defined(obj.userData)) {
        buf[offset++] = 18
        encodings.bytes.encode(obj.userData, buf, offset)
        offset += encodings.bytes.encode.bytes
      }
      encode.bytes = offset - oldOffset
      return buf
    }

    function decode (buf, offset, end) {
      if (!offset) offset = 0
      if (!end) end = buf.length
      if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
      var oldOffset = offset
      var obj = {
        contentFeed: null,
        userData: null
      }
      while (true) {
        if (end <= offset) {
          decode.bytes = offset - oldOffset
          return obj
        }
        var prefix = varint.decode(buf, offset)
        offset += varint.decode.bytes
        var tag = prefix >> 3
        switch (tag) {
          case 1:
          obj.contentFeed = encodings.bytes.decode(buf, offset)
          offset += encodings.bytes.decode.bytes
          break
          case 2:
          obj.userData = encodings.bytes.decode(buf, offset)
          offset += encodings.bytes.decode.bytes
          break
          default:
          offset = skip(prefix & 7, buf, offset)
        }
      }
    }
  }

  Header.encodingLength = encodingLength
  Header.encode = encode
  Header.decode = decode

  function encodingLength (obj) {
    var length = 0
    if (!defined(obj.protocol)) throw new Error("protocol is required")
    var len = encodings.string.encodingLength(obj.protocol)
    length += 1 + len
    if (defined(obj.metadata)) {
      var len = Metadata.encodingLength(obj.metadata)
      length += varint.encodingLength(len)
      length += 1 + len
    }
    return length
  }

  function encode (obj, buf, offset) {
    if (!offset) offset = 0
    if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
    var oldOffset = offset
    if (!defined(obj.protocol)) throw new Error("protocol is required")
    buf[offset++] = 10
    encodings.string.encode(obj.protocol, buf, offset)
    offset += encodings.string.encode.bytes
    if (defined(obj.metadata)) {
      buf[offset++] = 18
      varint.encode(Metadata.encodingLength(obj.metadata), buf, offset)
      offset += varint.encode.bytes
      Metadata.encode(obj.metadata, buf, offset)
      offset += Metadata.encode.bytes
    }
    encode.bytes = offset - oldOffset
    return buf
  }

  function decode (buf, offset, end) {
    if (!offset) offset = 0
    if (!end) end = buf.length
    if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
    var oldOffset = offset
    var obj = {
      protocol: "",
      metadata: null
    }
    var found0 = false
    while (true) {
      if (end <= offset) {
        if (!found0) throw new Error("Decoded message is not valid")
        decode.bytes = offset - oldOffset
        return obj
      }
      var prefix = varint.decode(buf, offset)
      offset += varint.decode.bytes
      var tag = prefix >> 3
      switch (tag) {
        case 1:
        obj.protocol = encodings.string.decode(buf, offset)
        offset += encodings.string.decode.bytes
        found0 = true
        break
        case 2:
        var len = varint.decode(buf, offset)
        offset += varint.decode.bytes
        obj.metadata = Metadata.decode(buf, offset, offset + len)
        offset += Metadata.decode.bytes
        break
        default:
        offset = skip(prefix & 7, buf, offset)
      }
    }
  }
}

function defineNode () {
  Node.encodingLength = encodingLength
  Node.encode = encode
  Node.decode = decode

  function encodingLength (obj) {
    var length = 0
    if (!defined(obj.index)) throw new Error("index is required")
    var len = encodings.bytes.encodingLength(obj.index)
    length += 1 + len
    if (!defined(obj.key)) throw new Error("key is required")
    var len = encodings.bytes.encodingLength(obj.key)
    length += 1 + len
    if (defined(obj.value)) {
      var len = encodings.bytes.encodingLength(obj.value)
      length += 1 + len
    }
    return length
  }

  function encode (obj, buf, offset) {
    if (!offset) offset = 0
    if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
    var oldOffset = offset
    if (!defined(obj.index)) throw new Error("index is required")
    buf[offset++] = 10
    encodings.bytes.encode(obj.index, buf, offset)
    offset += encodings.bytes.encode.bytes
    if (!defined(obj.key)) throw new Error("key is required")
    buf[offset++] = 18
    encodings.bytes.encode(obj.key, buf, offset)
    offset += encodings.bytes.encode.bytes
    if (defined(obj.value)) {
      buf[offset++] = 26
      encodings.bytes.encode(obj.value, buf, offset)
      offset += encodings.bytes.encode.bytes
    }
    encode.bytes = offset - oldOffset
    return buf
  }

  function decode (buf, offset, end) {
    if (!offset) offset = 0
    if (!end) end = buf.length
    if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
    var oldOffset = offset
    var obj = {
      index: null,
      key: null,
      value: null
    }
    var found0 = false
    var found1 = false
    while (true) {
      if (end <= offset) {
        if (!found0 || !found1) throw new Error("Decoded message is not valid")
        decode.bytes = offset - oldOffset
        return obj
      }
      var prefix = varint.decode(buf, offset)
      offset += varint.decode.bytes
      var tag = prefix >> 3
      switch (tag) {
        case 1:
        obj.index = encodings.bytes.decode(buf, offset)
        offset += encodings.bytes.decode.bytes
        found0 = true
        break
        case 2:
        obj.key = encodings.bytes.decode(buf, offset)
        offset += encodings.bytes.decode.bytes
        found1 = true
        break
        case 3:
        obj.value = encodings.bytes.decode(buf, offset)
        offset += encodings.bytes.decode.bytes
        break
        default:
        offset = skip(prefix & 7, buf, offset)
      }
    }
  }
}

function defineExtension () {
  var Get = Extension.Get = {
    buffer: true,
    encodingLength: null,
    encode: null,
    decode: null
  }

  var Iterator = Extension.Iterator = {
    buffer: true,
    encodingLength: null,
    encode: null,
    decode: null
  }

  var Cache = Extension.Cache = {
    buffer: true,
    encodingLength: null,
    encode: null,
    decode: null
  }

  defineGet()
  defineIterator()
  defineCache()

  function defineGet () {
    Get.encodingLength = encodingLength
    Get.encode = encode
    Get.decode = decode

    function encodingLength (obj) {
      var length = 0
      if (defined(obj.version)) {
        var len = encodings.varint.encodingLength(obj.version)
        length += 1 + len
      }
      if (defined(obj.key)) {
        var len = encodings.bytes.encodingLength(obj.key)
        length += 1 + len
      }
      return length
    }

    function encode (obj, buf, offset) {
      if (!offset) offset = 0
      if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
      var oldOffset = offset
      if (defined(obj.version)) {
        buf[offset++] = 8
        encodings.varint.encode(obj.version, buf, offset)
        offset += encodings.varint.encode.bytes
      }
      if (defined(obj.key)) {
        buf[offset++] = 18
        encodings.bytes.encode(obj.key, buf, offset)
        offset += encodings.bytes.encode.bytes
      }
      encode.bytes = offset - oldOffset
      return buf
    }

    function decode (buf, offset, end) {
      if (!offset) offset = 0
      if (!end) end = buf.length
      if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
      var oldOffset = offset
      var obj = {
        version: 0,
        key: null
      }
      while (true) {
        if (end <= offset) {
          decode.bytes = offset - oldOffset
          return obj
        }
        var prefix = varint.decode(buf, offset)
        offset += varint.decode.bytes
        var tag = prefix >> 3
        switch (tag) {
          case 1:
          obj.version = encodings.varint.decode(buf, offset)
          offset += encodings.varint.decode.bytes
          break
          case 2:
          obj.key = encodings.bytes.decode(buf, offset)
          offset += encodings.bytes.decode.bytes
          break
          default:
          offset = skip(prefix & 7, buf, offset)
        }
      }
    }
  }

  function defineIterator () {
    Iterator.encodingLength = encodingLength
    Iterator.encode = encode
    Iterator.decode = decode

    function encodingLength (obj) {
      var length = 0
      if (defined(obj.version)) {
        var len = encodings.varint.encodingLength(obj.version)
        length += 1 + len
      }
      if (defined(obj.gte)) {
        var len = encodings.bytes.encodingLength(obj.gte)
        length += 1 + len
      }
      if (defined(obj.gt)) {
        var len = encodings.bytes.encodingLength(obj.gt)
        length += 1 + len
      }
      if (defined(obj.lte)) {
        var len = encodings.bytes.encodingLength(obj.lte)
        length += 1 + len
      }
      if (defined(obj.lt)) {
        var len = encodings.bytes.encodingLength(obj.lt)
        length += 1 + len
      }
      if (defined(obj.limit)) {
        var len = encodings.varint.encodingLength(obj.limit)
        length += 1 + len
      }
      if (defined(obj.reverse)) {
        var len = encodings.bool.encodingLength(obj.reverse)
        length += 1 + len
      }
      if (defined(obj.checkpoint)) {
        var packedLen = 0
        for (var i = 0; i < obj.checkpoint.length; i++) {
          if (!defined(obj.checkpoint[i])) continue
          var len = encodings.varint.encodingLength(obj.checkpoint[i])
          packedLen += len
        }
        if (packedLen) {
          length += 1 + packedLen + varint.encodingLength(packedLen)
        }
      }
      return length
    }

    function encode (obj, buf, offset) {
      if (!offset) offset = 0
      if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
      var oldOffset = offset
      if (defined(obj.version)) {
        buf[offset++] = 8
        encodings.varint.encode(obj.version, buf, offset)
        offset += encodings.varint.encode.bytes
      }
      if (defined(obj.gte)) {
        buf[offset++] = 18
        encodings.bytes.encode(obj.gte, buf, offset)
        offset += encodings.bytes.encode.bytes
      }
      if (defined(obj.gt)) {
        buf[offset++] = 26
        encodings.bytes.encode(obj.gt, buf, offset)
        offset += encodings.bytes.encode.bytes
      }
      if (defined(obj.lte)) {
        buf[offset++] = 34
        encodings.bytes.encode(obj.lte, buf, offset)
        offset += encodings.bytes.encode.bytes
      }
      if (defined(obj.lt)) {
        buf[offset++] = 42
        encodings.bytes.encode(obj.lt, buf, offset)
        offset += encodings.bytes.encode.bytes
      }
      if (defined(obj.limit)) {
        buf[offset++] = 48
        encodings.varint.encode(obj.limit, buf, offset)
        offset += encodings.varint.encode.bytes
      }
      if (defined(obj.reverse)) {
        buf[offset++] = 56
        encodings.bool.encode(obj.reverse, buf, offset)
        offset += encodings.bool.encode.bytes
      }
      if (defined(obj.checkpoint)) {
        var packedLen = 0
        for (var i = 0; i < obj.checkpoint.length; i++) {
          if (!defined(obj.checkpoint[i])) continue
          packedLen += encodings.varint.encodingLength(obj.checkpoint[i])
        }
        if (packedLen) {
          buf[offset++] = 66
          varint.encode(packedLen, buf, offset)
          offset += varint.encode.bytes
        }
        for (var i = 0; i < obj.checkpoint.length; i++) {
          if (!defined(obj.checkpoint[i])) continue
          encodings.varint.encode(obj.checkpoint[i], buf, offset)
          offset += encodings.varint.encode.bytes
        }
      }
      encode.bytes = offset - oldOffset
      return buf
    }

    function decode (buf, offset, end) {
      if (!offset) offset = 0
      if (!end) end = buf.length
      if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
      var oldOffset = offset
      var obj = {
        version: 0,
        gte: null,
        gt: null,
        lte: null,
        lt: null,
        limit: 0,
        reverse: false,
        checkpoint: []
      }
      while (true) {
        if (end <= offset) {
          decode.bytes = offset - oldOffset
          return obj
        }
        var prefix = varint.decode(buf, offset)
        offset += varint.decode.bytes
        var tag = prefix >> 3
        switch (tag) {
          case 1:
          obj.version = encodings.varint.decode(buf, offset)
          offset += encodings.varint.decode.bytes
          break
          case 2:
          obj.gte = encodings.bytes.decode(buf, offset)
          offset += encodings.bytes.decode.bytes
          break
          case 3:
          obj.gt = encodings.bytes.decode(buf, offset)
          offset += encodings.bytes.decode.bytes
          break
          case 4:
          obj.lte = encodings.bytes.decode(buf, offset)
          offset += encodings.bytes.decode.bytes
          break
          case 5:
          obj.lt = encodings.bytes.decode(buf, offset)
          offset += encodings.bytes.decode.bytes
          break
          case 6:
          obj.limit = encodings.varint.decode(buf, offset)
          offset += encodings.varint.decode.bytes
          break
          case 7:
          obj.reverse = encodings.bool.decode(buf, offset)
          offset += encodings.bool.decode.bytes
          break
          case 8:
          var packedEnd = varint.decode(buf, offset)
          offset += varint.decode.bytes
          packedEnd += offset
          while (offset < packedEnd) {
            obj.checkpoint.push(encodings.varint.decode(buf, offset))
            offset += encodings.varint.decode.bytes
          }
          break
          default:
          offset = skip(prefix & 7, buf, offset)
        }
      }
    }
  }

  function defineCache () {
    Cache.encodingLength = encodingLength
    Cache.encode = encode
    Cache.decode = decode

    function encodingLength (obj) {
      var length = 0
      if (!defined(obj.start)) throw new Error("start is required")
      var len = encodings.varint.encodingLength(obj.start)
      length += 1 + len
      if (!defined(obj.end)) throw new Error("end is required")
      var len = encodings.varint.encodingLength(obj.end)
      length += 1 + len
      if (defined(obj.blocks)) {
        var packedLen = 0
        for (var i = 0; i < obj.blocks.length; i++) {
          if (!defined(obj.blocks[i])) continue
          var len = encodings.varint.encodingLength(obj.blocks[i])
          packedLen += len
        }
        if (packedLen) {
          length += 1 + packedLen + varint.encodingLength(packedLen)
        }
      }
      return length
    }

    function encode (obj, buf, offset) {
      if (!offset) offset = 0
      if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
      var oldOffset = offset
      if (!defined(obj.start)) throw new Error("start is required")
      buf[offset++] = 8
      encodings.varint.encode(obj.start, buf, offset)
      offset += encodings.varint.encode.bytes
      if (!defined(obj.end)) throw new Error("end is required")
      buf[offset++] = 16
      encodings.varint.encode(obj.end, buf, offset)
      offset += encodings.varint.encode.bytes
      if (defined(obj.blocks)) {
        var packedLen = 0
        for (var i = 0; i < obj.blocks.length; i++) {
          if (!defined(obj.blocks[i])) continue
          packedLen += encodings.varint.encodingLength(obj.blocks[i])
        }
        if (packedLen) {
          buf[offset++] = 26
          varint.encode(packedLen, buf, offset)
          offset += varint.encode.bytes
        }
        for (var i = 0; i < obj.blocks.length; i++) {
          if (!defined(obj.blocks[i])) continue
          encodings.varint.encode(obj.blocks[i], buf, offset)
          offset += encodings.varint.encode.bytes
        }
      }
      encode.bytes = offset - oldOffset
      return buf
    }

    function decode (buf, offset, end) {
      if (!offset) offset = 0
      if (!end) end = buf.length
      if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
      var oldOffset = offset
      var obj = {
        start: 0,
        end: 0,
        blocks: []
      }
      var found0 = false
      var found1 = false
      while (true) {
        if (end <= offset) {
          if (!found0 || !found1) throw new Error("Decoded message is not valid")
          decode.bytes = offset - oldOffset
          return obj
        }
        var prefix = varint.decode(buf, offset)
        offset += varint.decode.bytes
        var tag = prefix >> 3
        switch (tag) {
          case 1:
          obj.start = encodings.varint.decode(buf, offset)
          offset += encodings.varint.decode.bytes
          found0 = true
          break
          case 2:
          obj.end = encodings.varint.decode(buf, offset)
          offset += encodings.varint.decode.bytes
          found1 = true
          break
          case 3:
          var packedEnd = varint.decode(buf, offset)
          offset += varint.decode.bytes
          packedEnd += offset
          while (offset < packedEnd) {
            obj.blocks.push(encodings.varint.decode(buf, offset))
            offset += encodings.varint.decode.bytes
          }
          break
          default:
          offset = skip(prefix & 7, buf, offset)
        }
      }
    }
  }

  Extension.encodingLength = encodingLength
  Extension.encode = encode
  Extension.decode = decode

  function encodingLength (obj) {
    var length = 0
    if (defined(obj.cache)) {
      var len = Cache.encodingLength(obj.cache)
      length += varint.encodingLength(len)
      length += 1 + len
    }
    if (defined(obj.get)) {
      var len = Get.encodingLength(obj.get)
      length += varint.encodingLength(len)
      length += 1 + len
    }
    if (defined(obj.iterator)) {
      var len = Iterator.encodingLength(obj.iterator)
      length += varint.encodingLength(len)
      length += 1 + len
    }
    return length
  }

  function encode (obj, buf, offset) {
    if (!offset) offset = 0
    if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
    var oldOffset = offset
    if (defined(obj.cache)) {
      buf[offset++] = 10
      varint.encode(Cache.encodingLength(obj.cache), buf, offset)
      offset += varint.encode.bytes
      Cache.encode(obj.cache, buf, offset)
      offset += Cache.encode.bytes
    }
    if (defined(obj.get)) {
      buf[offset++] = 18
      varint.encode(Get.encodingLength(obj.get), buf, offset)
      offset += varint.encode.bytes
      Get.encode(obj.get, buf, offset)
      offset += Get.encode.bytes
    }
    if (defined(obj.iterator)) {
      buf[offset++] = 26
      varint.encode(Iterator.encodingLength(obj.iterator), buf, offset)
      offset += varint.encode.bytes
      Iterator.encode(obj.iterator, buf, offset)
      offset += Iterator.encode.bytes
    }
    encode.bytes = offset - oldOffset
    return buf
  }

  function decode (buf, offset, end) {
    if (!offset) offset = 0
    if (!end) end = buf.length
    if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
    var oldOffset = offset
    var obj = {
      cache: null,
      get: null,
      iterator: null
    }
    while (true) {
      if (end <= offset) {
        decode.bytes = offset - oldOffset
        return obj
      }
      var prefix = varint.decode(buf, offset)
      offset += varint.decode.bytes
      var tag = prefix >> 3
      switch (tag) {
        case 1:
        var len = varint.decode(buf, offset)
        offset += varint.decode.bytes
        obj.cache = Cache.decode(buf, offset, offset + len)
        offset += Cache.decode.bytes
        break
        case 2:
        var len = varint.decode(buf, offset)
        offset += varint.decode.bytes
        obj.get = Get.decode(buf, offset, offset + len)
        offset += Get.decode.bytes
        break
        case 3:
        var len = varint.decode(buf, offset)
        offset += varint.decode.bytes
        obj.iterator = Iterator.decode(buf, offset, offset + len)
        offset += Iterator.decode.bytes
        break
        default:
        offset = skip(prefix & 7, buf, offset)
      }
    }
  }
}

function defined (val) {
  return val !== null && val !== undefined && (typeof val !== 'number' || !isNaN(val))
}
{
  "name": "hyperbee",
  "version": "2.27.3",
  "description": "An append-only B-tree running on a Hypercore.",
  "main": "index.js",
  "files": [
    "index.js",
    "lib/**.js",
    "iterators/**.js"
  ],
  "dependencies": {
    "b4a": "^1.6.0",
    "codecs": "^3.0.0",
    "debounceify": "^1.0.0",
    "hypercore-errors": "^1.0.0",
    "mutexify": "^1.4.0",
    "protocol-buffers-encodings": "^1.2.0",
    "rache": "^1.0.0",
    "ready-resource": "^1.0.0",
    "resolve-reject-promise": "^1.1.0",
    "safety-catch": "^1.0.2",
    "streamx": "^2.12.4",
    "unslab": "^1.2.0"
  },
  "devDependencies": {
    "bare-process": "^4.2.2",
    "brittle": "^3.1.0",
    "hypercore": "^11.0.0",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "protocol-buffers": "^4.2.0",
    "sub-encoder": "^1.0.6",
    "tree-to-string": "^1.1.1"
  },
  "imports": {
    "process": {
      "bare": "bare-process",
      "default": "process"
    }
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test/*.js",
    "test:bare": "brittle-bare test/*.js",
    "protobuf": "protocol-buffers schema.proto -o ./lib/messages.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/hyperbee.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/hyperbee/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperbee"
}
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const b4a = require('b4a')

// https://en.wikipedia.org/wiki/Merkle_tree#Second_preimage_attack
const LEAF_TYPE = b4a.from([0])
const PARENT_TYPE = b4a.from([1])
const ROOT_TYPE = b4a.from([2])

const HYPERCORE = b4a.from('hypercore')

exports.keyPair = function (seed) {
  // key pairs might stay around for a while, so better not to use a default slab to avoid retaining it completely
  const slab = b4a.allocUnsafeSlow(
    sodium.crypto_sign_PUBLICKEYBYTES + sodium.crypto_sign_SECRETKEYBYTES
  )
  const publicKey = slab.subarray(0, sodium.crypto_sign_PUBLICKEYBYTES)
  const secretKey = slab.subarray(sodium.crypto_sign_PUBLICKEYBYTES)

  if (seed) sodium.crypto_sign_seed_keypair(publicKey, secretKey, seed)
  else sodium.crypto_sign_keypair(publicKey, secretKey)

  return {
    publicKey,
    secretKey
  }
}

exports.validateKeyPair = function (keyPair) {
  const pk = b4a.allocUnsafe(sodium.crypto_sign_PUBLICKEYBYTES)
  sodium.crypto_sign_ed25519_sk_to_pk(pk, keyPair.secretKey)
  return b4a.equals(pk, keyPair.publicKey)
}

exports.sign = function (message, secretKey) {
  // Dedicated slab for the signature, to avoid retaining unneeded mem and for security
  const signature = b4a.allocUnsafeSlow(sodium.crypto_sign_BYTES)
  sodium.crypto_sign_detached(signature, message, secretKey)
  return signature
}

exports.verify = function (message, signature, publicKey) {
  if (signature.byteLength !== sodium.crypto_sign_BYTES) return false
  if (publicKey.byteLength !== sodium.crypto_sign_PUBLICKEYBYTES) return false
  return sodium.crypto_sign_verify_detached(signature, message, publicKey)
}

exports.encrypt = function (message, publicKey) {
  const ciphertext = b4a.alloc(message.byteLength + sodium.crypto_box_SEALBYTES)
  sodium.crypto_box_seal(ciphertext, message, publicKey)
  return ciphertext
}

exports.decrypt = function (ciphertext, keyPair) {
  if (ciphertext.byteLength < sodium.crypto_box_SEALBYTES) return null

  const plaintext = b4a.alloc(ciphertext.byteLength - sodium.crypto_box_SEALBYTES)

  if (!sodium.crypto_box_seal_open(plaintext, ciphertext, keyPair.publicKey, keyPair.secretKey)) {
    return null
  }

  return plaintext
}

exports.encryptionKeyPair = function (seed) {
  const publicKey = b4a.alloc(sodium.crypto_box_PUBLICKEYBYTES)
  const secretKey = b4a.alloc(sodium.crypto_box_SECRETKEYBYTES)

  if (seed) {
    sodium.crypto_box_seed_keypair(publicKey, secretKey, seed)
  } else {
    sodium.crypto_box_keypair(publicKey, secretKey)
  }

  return {
    publicKey,
    secretKey
  }
}

exports.data = function (data) {
  const out = b4a.allocUnsafe(32)

  sodium.crypto_generichash_batch(out, [LEAF_TYPE, c.encode(c.uint64, data.byteLength), data])

  return out
}

exports.parent = function (a, b) {
  if (a.index > b.index) {
    const tmp = a
    a = b
    b = tmp
  }

  const out = b4a.allocUnsafe(32)

  sodium.crypto_generichash_batch(out, [
    PARENT_TYPE,
    c.encode(c.uint64, a.size + b.size),
    a.hash,
    b.hash
  ])

  return out
}

exports.tree = function (roots, out) {
  const buffers = new Array(3 * roots.length + 1)
  let j = 0

  buffers[j++] = ROOT_TYPE

  for (let i = 0; i < roots.length; i++) {
    const r = roots[i]
    buffers[j++] = r.hash
    buffers[j++] = c.encode(c.uint64, r.index)
    buffers[j++] = c.encode(c.uint64, r.size)
  }

  if (!out) out = b4a.allocUnsafe(32)
  sodium.crypto_generichash_batch(out, buffers)
  return out
}

exports.hash = function (data, out) {
  if (!out) out = b4a.allocUnsafe(32)
  if (!Array.isArray(data)) data = [data]

  sodium.crypto_generichash_batch(out, data)

  return out
}

exports.randomBytes = function (n) {
  const buf = b4a.allocUnsafe(n)
  sodium.randombytes_buf(buf)
  return buf
}

exports.discoveryKey = function (key) {
  if (!key || key.byteLength !== 32) throw new Error('Must pass a 32 byte buffer')
  // Discovery keys might stay around for a while, so better not to use slab memory (for better gc)
  const digest = b4a.allocUnsafeSlow(32)
  sodium.crypto_generichash(digest, HYPERCORE, key)
  return digest
}

if (sodium.sodium_free) {
  exports.free = function (secureBuf) {
    if (secureBuf.secure) sodium.sodium_free(secureBuf)
  }
} else {
  exports.free = function () {}
}

exports.namespace = function (name, count) {
  const ids = typeof count === 'number' ? range(count) : count

  // Namespaces are long-lived, so better to use a dedicated slab
  const buf = b4a.allocUnsafeSlow(32 * ids.length)

  const list = new Array(ids.length)

  // ns is ephemeral, so default slab
  const ns = b4a.allocUnsafe(33)
  sodium.crypto_generichash(ns.subarray(0, 32), typeof name === 'string' ? b4a.from(name) : name)

  for (let i = 0; i < list.length; i++) {
    list[i] = buf.subarray(32 * i, 32 * i + 32)
    ns[32] = ids[i]
    sodium.crypto_generichash(list[i], ns)
  }

  return list
}

function range(count) {
  const arr = new Array(count)
  for (let i = 0; i < count; i++) arr[i] = i
  return arr
}
{
  "name": "hypercore-crypto",
  "version": "3.7.0",
  "description": "The crypto primitives used in hypercore, extracted into a separate module",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.6.6",
    "compact-encoding": "^3.0.0",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "brittle": "^3.5.0",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/hypercore-crypto.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/hypercore-crypto/issues"
  },
  "homepage": "https://github.com/mafintosh/hypercore-crypto"
}
const IdEnc = require('hypercore-id-encoding')

module.exports = class HypercoreError extends Error {
  constructor (msg, code, fn = HypercoreError, discoveryKey = null) {
    if (discoveryKey) msg = `${msg} (discovery key: ${IdEnc.normalize(discoveryKey)})`
    super(`${code}: ${msg}`)

    this.code = code
    this.discoveryKey = discoveryKey

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name () {
    return 'HypercoreError'
  }

  static ASSERTION (msg, discoveryKey = null) { // ERR_ASSERTION is picked up by safety-catch also
    return new HypercoreError(msg, 'ERR_ASSERTION', HypercoreError.ASSERT, discoveryKey)
  }

  static BAD_ARGUMENT (msg, discoveryKey = null) {
    return new HypercoreError(msg, 'BAD_ARGUMENT', HypercoreError.BAD_ARGUMENT, discoveryKey)
  }

  static STORAGE_EMPTY (msg, discoveryKey = null) {
    return new HypercoreError(msg, 'STORAGE_EMPTY', HypercoreError.STORAGE_EMPTY, discoveryKey)
  }

  static STORAGE_CONFLICT (msg, discoveryKey = null) {
    return new HypercoreError(msg, 'STORAGE_CONFLICT', HypercoreError.STORAGE_CONFLICT, discoveryKey)
  }

  static INVALID_SIGNATURE (msg, discoveryKey = null) {
    return new HypercoreError(msg, 'INVALID_SIGNATURE', HypercoreError.INVALID_SIGNATURE, discoveryKey)
  }

  static INVALID_CAPABILITY (msg, discoveryKey = null) {
    return new HypercoreError(msg, 'INVALID_CAPABILITY', HypercoreError.INVALID_CAPABILITY, discoveryKey)
  }

  static INVALID_CHECKSUM (msg = 'Invalid checksum', discoveryKey = null) {
    return new HypercoreError(msg, 'INVALID_CHECKSUM', HypercoreError.INVALID_CHECKSUM, discoveryKey)
  }

  static INVALID_OPERATION (msg, discoveryKey = null) {
    return new HypercoreError(msg, 'INVALID_OPERATION', HypercoreError.INVALID_OPERATION, discoveryKey)
  }

  static INVALID_PROOF (msg = 'Proof not verifiable', discoveryKey = null) {
    return new HypercoreError(msg, 'INVALID_PROOF', HypercoreError.INVALID_PROOF, discoveryKey)
  }

  static BLOCK_NOT_AVAILABLE (msg = 'Block is not available', discoveryKey = null) {
    return new HypercoreError(msg, 'BLOCK_NOT_AVAILABLE', HypercoreError.BLOCK_NOT_AVAILABLE, discoveryKey)
  }

  static SNAPSHOT_NOT_AVAILABLE (msg = 'Snapshot is not available', discoveryKey = null) {
    return new HypercoreError(msg, 'SNAPSHOT_NOT_AVAILABLE', HypercoreError.SNAPSHOT_NOT_AVAILABLE, discoveryKey)
  }

  static REQUEST_CANCELLED (msg = 'Request was cancelled', discoveryKey = null) {
    return new HypercoreError(msg, 'REQUEST_CANCELLED', HypercoreError.REQUEST_CANCELLED, discoveryKey)
  }

  static REQUEST_TIMEOUT (msg = 'Request timed out', discoveryKey = null) {
    return new HypercoreError(msg, 'REQUEST_TIMEOUT', HypercoreError.REQUEST_TIMEOUT, discoveryKey)
  }

  static SESSION_NOT_WRITABLE (msg = 'Session is not writable', discoveryKey = null) {
    return new HypercoreError(msg, 'SESSION_NOT_WRITABLE', HypercoreError.SESSION_NOT_WRITABLE, discoveryKey)
  }

  static SESSION_CLOSED (msg = 'Session is closed', discoveryKey = null) {
    return new HypercoreError(msg, 'SESSION_CLOSED', HypercoreError.SESSION_CLOSED, discoveryKey)
  }

  static BATCH_UNFLUSHED (msg = 'Batch not yet flushed', discoveryKey = null) {
    return new HypercoreError(msg, 'BATCH_UNFLUSHED', HypercoreError.BATCH_UNFLUSHED, discoveryKey)
  }

  static BATCH_ALREADY_EXISTS (msg = 'Batch already exists', discoveryKey = null) {
    return new HypercoreError(msg, 'BATCH_ALREADY_EXISTS', HypercoreError.BATCH_ALREADY_EXISTS, discoveryKey)
  }

  static BATCH_ALREADY_FLUSHED (msg = 'Batch has already been flushed', discoveryKey = null) {
    return new HypercoreError(msg, 'BATCH_ALREADY_FLUSHED', HypercoreError.BATCH_ALREADY_FLUSHED, discoveryKey)
  }

  static OPLOG_CORRUPT (msg = 'Oplog file appears corrupt or out of date', discoveryKey = null) {
    return new HypercoreError(msg, 'OPLOG_CORRUPT', HypercoreError.OPLOG_CORRUPT, discoveryKey)
  }

  static OPLOG_HEADER_OVERFLOW (msg = 'Oplog header exceeds page size', discoveryKey = null) {
    return new HypercoreError(msg, 'OPLOG_HEADER_OVERFLOW', HypercoreError.OPLOG_HEADER_OVERFLOW, discoveryKey)
  }

  static INVALID_OPLOG_VERSION (msg = 'Invalid header version', discoveryKey = null) {
    return new HypercoreError(msg, 'INVALID_OPLOG_VERSION', HypercoreError.INVALID_OPLOG_VERSION, discoveryKey)
  }

  static WRITE_FAILED (msg = 'Write to storage failed', discoveryKey = null) {
    return new HypercoreError(msg, 'WRITE_FAILED', HypercoreError.WRITE_FAILED, discoveryKey)
  }

  static DECODING_ERROR (msg = 'Decoding error', discoveryKey = null) {
    return new HypercoreError(msg, 'DECODING_ERROR', HypercoreError.DECODING_ERROR, discoveryKey)
  }

  static SESSION_MOVED (msg = 'Session moved', discoveryKey = null) {
    return new HypercoreError(msg, 'SESSION_MOVED', HypercoreError.SESSION_MOVED, discoveryKey)
  }
}
{
  "name": "hypercore-errors",
  "version": "1.5.0",
  "description": "Hypercore errors",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/hypercore-errors.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/hypercore-errors/issues"
  },
  "homepage": "https://github.com/holepunchto/hypercore-errors#readme",
  "devDependencies": {
    "b4a": "^1.6.7",
    "brittle": "^3.1.3",
    "standard": "^17.0.0"
  },
  "dependencies": {
    "hypercore-id-encoding": "^1.3.0"
  }
}
const z32 = require('z32')
const b4a = require('b4a')

module.exports = {
  encode,
  decode,
  normalize,
  isValid
}

function encode (key) {
  if (!b4a.isBuffer(key)) throw new Error('Key must be a Buffer')
  if (key.byteLength !== 32) throw new Error('Key must be 32-bytes long')
  return z32.encode(key)
}

function decode (id) {
  if (b4a.isBuffer(id)) {
    if (id.byteLength !== 32) throw new Error('ID must be 32-bytes long')
    return id
  }
  if (typeof id === 'string') {
    if (id.startsWith('pear://')) id = id.slice(7).split('/')[0]
    if (id.length === 52) return z32.decode(id)
    if (id.length === 64) {
      const buf = b4a.from(id, 'hex')
      if (buf.byteLength === 32) return buf
    }
  }
  throw new Error('Invalid Hypercore key')
}

function normalize (any) {
  return encode(decode(any))
}

function isValid (any) {
  try {
    decode(any)
    return true
  } catch {
    return false
  }
}
{
  "name": "hypercore-id-encoding",
  "version": "1.3.0",
  "description": "Convert Hypercore keys to/from z-base32 or hex",
  "main": "index.js",
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.5.3",
    "z32": "^1.0.0"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "hypercore": "^10.0.0",
    "random-access-memory": "^6.0.0",
    "standard": "^17.1.0"
  },
  "license": "Apache-2.0",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/hypercore-id-encoding.git"
  },
  "keywords": [],
  "author": "",
  "bugs": {
    "url": "https://github.com/holepunchto/hypercore-id-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/hypercore-id-encoding#readme"
}
var queueTick = require('queue-tick')

var mutexify = function () {
  var queue = []
  var used = null

  var call = function () {
    used(release)
  }

  var acquire = function (fn) {
    if (used) return queue.push(fn)
    used = fn
    acquire.locked = true
    queueTick(call)
    return 0
  }

  acquire.locked = false

  var release = function (fn, err, value) {
    used = null
    acquire.locked = false
    if (queue.length) acquire(queue.shift())
    if (fn) fn(err, value)
  }

  return acquire
}

module.exports = mutexify
{
  "name": "mutexify",
  "version": "1.4.0",
  "description": "mutex lock for javascript",
  "main": "index.js",
  "dependencies": {
    "queue-tick": "^1.0.0"
  },
  "devDependencies": {
    "standard": "^14.3.3",
    "tape": "^3.0.2"
  },
  "scripts": {
    "test": "tape test.js",
    "posttest": "npm run lint",
    "lint": "standard"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/mutexify.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/mutexify/issues"
  },
  "keywords": [
    "mutex",
    "lock"
  ],
  "homepage": "https://github.com/mafintosh/mutexify"
}
var mutexify = require('.')

var mutexifyPromise = function () {
  var lock = mutexify()

  var acquire = function () {
    return new Promise(lock)
  }

  Object.defineProperty(acquire, 'locked', {
    get: function () { return lock.locked },
    enumerable: true
  })

  return acquire
}

module.exports = mutexifyPromise
var varint = require('varint')
var svarint = require('signed-varint')
var b4a = require('b4a')

exports.make = encoder

exports.name = function (enc) {
  var keys = Object.keys(exports)
  for (var i = 0; i < keys.length; i++) {
    if (exports[keys[i]] === enc) return keys[i]
  }
  return null
}

exports.skip = function (type, buffer, offset) {
  switch (type) {
    case 0:
      varint.decode(buffer, offset)
      return offset + varint.decode.bytes

    case 1:
      return offset + 8

    case 2:
      var len = varint.decode(buffer, offset)
      return offset + varint.decode.bytes + len

    case 3:
    case 4:
      throw new Error('Groups are not supported')

    case 5:
      return offset + 4
  }

  throw new Error('Unknown wire type: ' + type)
}

exports.bytes = encoder(2,
  function encode (val, buffer, offset) {
    var oldOffset = offset
    var len = bufferLength(val)

    varint.encode(len, buffer, offset)
    offset += varint.encode.bytes

    if (b4a.isBuffer(val)) b4a.copy(val, buffer, offset)
    else b4a.write(buffer, val, offset, len)
    offset += len

    encode.bytes = offset - oldOffset
    return buffer
  },
  function decode (buffer, offset) {
    var oldOffset = offset

    var len = varint.decode(buffer, offset)
    offset += varint.decode.bytes

    var val = buffer.subarray(offset, offset + len)
    offset += val.length

    decode.bytes = offset - oldOffset
    return val
  },
  function encodingLength (val) {
    var len = bufferLength(val)
    return varint.encodingLength(len) + len
  }
)

exports.string = encoder(2,
  function encode (val, buffer, offset) {
    var oldOffset = offset
    var len = b4a.byteLength(val)

    varint.encode(len, buffer, offset, 'utf-8')
    offset += varint.encode.bytes

    b4a.write(buffer, val, offset, len)
    offset += len

    encode.bytes = offset - oldOffset
    return buffer
  },
  function decode (buffer, offset) {
    var oldOffset = offset

    var len = varint.decode(buffer, offset)
    offset += varint.decode.bytes

    var val = b4a.toString(buffer, 'utf-8', offset, offset + len)
    offset += len

    decode.bytes = offset - oldOffset
    return val
  },
  function encodingLength (val) {
    var len = b4a.byteLength(val)
    return varint.encodingLength(len) + len
  }
)

exports.bool = encoder(0,
  function encode (val, buffer, offset) {
    buffer[offset] = val ? 1 : 0
    encode.bytes = 1
    return buffer
  },
  function decode (buffer, offset) {
    var bool = buffer[offset] > 0
    decode.bytes = 1
    return bool
  },
  function encodingLength () {
    return 1
  }
)

exports.int32 = encoder(0,
  function encode (val, buffer, offset) {
    varint.encode(val < 0 ? val + 4294967296 : val, buffer, offset)
    encode.bytes = varint.encode.bytes
    return buffer
  },
  function decode (buffer, offset) {
    var val = varint.decode(buffer, offset)
    decode.bytes = varint.decode.bytes
    return val > 2147483647 ? val - 4294967296 : val
  },
  function encodingLength (val) {
    return varint.encodingLength(val < 0 ? val + 4294967296 : val)
  }
)

exports.int64 = encoder(0,
  function encode (val, buffer, offset) {
    if (val < 0) {
      var last = offset + 9
      varint.encode(val * -1, buffer, offset)
      offset += varint.encode.bytes - 1
      buffer[offset] = buffer[offset] | 0x80
      while (offset < last - 1) {
        offset++
        buffer[offset] = 0xff
      }
      buffer[last] = 0x01
      encode.bytes = 10
    } else {
      varint.encode(val, buffer, offset)
      encode.bytes = varint.encode.bytes
    }
    return buffer
  },
  function decode (buffer, offset) {
    var val = varint.decode(buffer, offset)
    if (val >= Math.pow(2, 63)) {
      var limit = 9
      while (buffer[offset + limit - 1] === 0xff) limit--
      limit = limit || 9
      var subset = b4a.allocUnsafe(limit)
      b4a.copy(buffer, subset, 0, offset, offset + limit)
      subset[limit - 1] = subset[limit - 1] & 0x7f
      val = -1 * varint.decode(subset, 0)
      decode.bytes = 10
    } else {
      decode.bytes = varint.decode.bytes
    }
    return val
  },
  function encodingLength (val) {
    return val < 0 ? 10 : varint.encodingLength(val)
  }
)

exports.sint32 =
exports.sint64 = encoder(0,
  svarint.encode,
  svarint.decode,
  svarint.encodingLength
)

exports.uint32 =
exports.uint64 =
exports.enum =
exports.varint = encoder(0,
  varint.encode,
  varint.decode,
  varint.encodingLength
)

// we cannot represent these in javascript so we just use buffers
exports.fixed64 =
exports.sfixed64 = encoder(1,
  function encode (val, buffer, offset) {
    b4a.copy(val, buffer, offset)
    encode.bytes = 8
    return buffer
  },
  function decode (buffer, offset) {
    var val = buffer.subarray(offset, offset + 8)
    decode.bytes = 8
    return val
  },
  function encodingLength () {
    return 8
  }
)

exports.double = encoder(1,
  function encode (val, buffer, offset) {
    b4a.writeDoubleLE(buffer, val, offset)
    encode.bytes = 8
    return buffer
  },
  function decode (buffer, offset) {
    var val = b4a.readDoubleLE(buffer, offset)
    decode.bytes = 8
    return val
  },
  function encodingLength () {
    return 8
  }
)

exports.fixed32 = encoder(5,
  function encode (val, buffer, offset) {
    b4a.writeUInt32LE(buffer, val, offset)
    encode.bytes = 4
    return buffer
  },
  function decode (buffer, offset) {
    var val = b4a.readUInt32LE(buffer, offset)
    decode.bytes = 4
    return val
  },
  function encodingLength () {
    return 4
  }
)

exports.sfixed32 = encoder(5,
  function encode (val, buffer, offset) {
    b4a.writeInt32LE(buffer, val, offset)
    encode.bytes = 4
    return buffer
  },
  function decode (buffer, offset) {
    var val = b4a.readInt32LE(buffer, offset)
    decode.bytes = 4
    return val
  },
  function encodingLength () {
    return 4
  }
)

exports.float = encoder(5,
  function encode (val, buffer, offset) {
    b4a.writeFloatLE(buffer, val, offset)
    encode.bytes = 4
    return buffer
  },
  function decode (buffer, offset) {
    var val = b4a.readFloatLE(buffer, offset)
    decode.bytes = 4
    return val
  },
  function encodingLength () {
    return 4
  }
)

function encoder (type, encode, decode, encodingLength) {
  encode.bytes = decode.bytes = 0

  return {
    type: type,
    encode: encode,
    decode: decode,
    encodingLength: encodingLength
  }
}

function bufferLength (val) {
  return b4a.isBuffer(val) ? val.length : b4a.byteLength(val)
}
{
  "name": "protocol-buffers-encodings",
  "version": "1.2.0",
  "description": "Base encodings for protocol-buffers",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.6.0",
    "signed-varint": "^2.0.1",
    "varint": "5.0.0"
  },
  "devDependencies": {
    "standard": "^14.3.4",
    "tape": "^5.0.1"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/protocol-buffers-encodings.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/protocol-buffers-encodings/issues"
  },
  "homepage": "https://github.com/mafintosh/protocol-buffers-encodings"
}
{
  "name": "queue-tick",
  "version": "1.0.1",
  "description": "Next tick shim that prefers process.nextTick over queueMicrotask for compat",
  "main": "./process-next-tick.js",
  "browser": "./queue-microtask.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^16.0.3",
    "tape": "^5.3.1"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/queue-tick.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/queue-tick/issues"
  },
  "homepage": "https://github.com/mafintosh/queue-tick"
}
module.exports = (typeof process !== 'undefined' && typeof process.nextTick === 'function')
  ? process.nextTick.bind(process)
  : require('./queue-microtask')
module.exports = typeof queueMicrotask === 'function' ? queueMicrotask : (fn) => Promise.resolve().then(fn)
class CacheEntry {
  constructor (key, index, map) {
    this.key = key
    this.index = index
    this.map = map
  }
}

class CacheValue {
  constructor (entry, value) {
    this.entry = entry
    this.value = value
  }
}

class Rache {
  constructor ({ maxSize = 65536, parent = null } = {}) {
    this.maxSize = parent?.maxSize || maxSize

    this._array = parent?._array || []
    this._map = new Map()
  }

  static from (cache) {
    return cache ? new this({ parent: cache }) : new this()
  }

  get globalSize () {
    return this._array.length
  }

  get size () {
    return this._map.size
  }

  sub () {
    return new Rache({ parent: this })
  }

  set (key, value) { // ~constant time
    const existing = this._map.get(key)
    if (existing !== undefined) {
      existing.value = value
      return
    }

    if (this._array.length >= this.maxSize) this._gc()

    const entry = new CacheEntry(key, this._array.length, this._map)
    this._array.push(entry)
    const cacheValue = new CacheValue(entry, value)
    this._map.set(key, cacheValue)
  }

  delete (key) {
    const existing = this._map.get(key)
    if (existing === undefined) return false

    this._delete(existing.entry.index)
    return true
  }

  get (key) {
    const existing = this._map.get(key)
    return existing === undefined ? undefined : existing.value
  }

  * [Symbol.iterator] () {
    for (const [key, { value }] of this._map) {
      yield [key, value]
    }
  }

  keys () {
    return this._map.keys()
  }

  * values () {
    for (const { value } of this._map.values()) {
      yield value
    }
  }

  clear () {
    // The entries in map linger on in _array,
    // so on top of clearing the map, we also kill the ref,
    // so that any gc running later on the old map won't interfere
    // (in case a new entry was added with the same key as a cleared entry)

    this._map.clear()
    this._map = new Map()
  }

  destroy () {
    this._map = null
    this._array = null
  }

  _gc () {
    this._delete(Math.floor(Math.random() * this._array.length))
  }

  _delete (index) { // ~constant time
    if (index >= this._array.length) throw new Error('Cannot delete unused index (logic bug?)')

    const head = this._array.pop()
    let removed = head

    if (index < this._array.length) {
      removed = this._array[index]
      head.index = index
      this._array[index] = head
    }

    removed.map.delete(removed.key)
  }
}

module.exports = Rache
{
  "name": "rache",
  "version": "1.0.0",
  "description": "Random-eviction cache",
  "main": "index.js",
  "scripts": {
    "test": "standard && brittle test.js --coverage"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/rache.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/rache/issues"
  },
  "homepage": "https://github.com/holepunchto/rache#readme",
  "files": [
    "index.js"
  ],
  "dependencies": {},
  "devDependencies": {
    "brittle": "^3.5.2",
    "standard": "^17.1.0"
  }
}
const EventEmitter = require('events')

module.exports = class ReadyResource extends EventEmitter {
  constructor () {
    super()

    this.opening = null
    this.closing = null

    this.opened = false
    this.closed = false
  }

  ready () {
    if (this.opening !== null) return this.opening
    this.opening = open(this)
    return this.opening
  }

  close () {
    if (this.closing !== null) return this.closing
    this.closing = close(this)
    return this.closing
  }

  async _open () {
    // add impl here
  }

  async _close () {
    // add impl here
  }
}

async function open (self) {
  // open after close
  if (self.closing !== null) return

  try {
    await self._open()
  } catch (err) {
    self.close() // safe to run in bg
    throw err
  }

  self.opened = true
  self.emit('ready')
}

async function close (self) {
  try {
    if (self.opened === false && self.opening !== null) await self.opening
  } catch {
    // ignore errors on closing
  }
  if (self.opened === true || self.opening === null) await self._close()
  self.closed = true
  self.emit('close')
}
{
  "name": "ready-resource",
  "version": "1.2.0",
  "description": "Modern single resource management",
  "main": "index.js",
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "types": "index.d.ts",
  "files": [
    "index.js",
    "index.d.ts"
  ],
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "devDependencies": {
    "brittle": "^3.1.0",
    "standard": "^17.0.0"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/ready-resource.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/ready-resource/issues"
  },
  "homepage": "https://github.com/holepunchto/ready-resource",
  "dependencies": {
    "bare-events": "^2.2.0"
  }
}
module.exports = require.addon.bind(require)
{
  "name": "require-addon",
  "version": "1.2.0",
  "description": "Import native addons across JavaScript runtimes",
  "exports": {
    "./package": "./package.json",
    ".": {
      "bare": "./lib/bare.js",
      "node": "./lib/node.js",
      "default": "./lib/default.js"
    }
  },
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    },
    "url": {
      "bare": "bare-url",
      "default": "url"
    }
  },
  "files": [
    "lib"
  ],
  "scripts": {
    "test": "npm run lint && npm run test:bare && npm run test:node",
    "test:bare": "bare test.js",
    "test:node": "node test.js",
    "lint": "prettier --check .",
    "format": "prettier --write ."
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/require-addon.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/require-addon/issues"
  },
  "homepage": "https://github.com/holepunchto/require-addon#readme",
  "engines": {
    "bare": ">=1.10.0"
  },
  "dependencies": {
    "bare-addon-resolve": "^1.3.0"
  },
  "devDependencies": {
    "bare-bundle": "^1.8.1",
    "bare-bundle-evaluate": "^1.1.0",
    "bare-fs": "^4.0.0",
    "bare-path": "^3.0.0",
    "bare-url": "^2.1.0",
    "brittle": "^3.7.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
let tmpResolve = null
let tmpReject = null

if (Promise.withResolvers) {
  module.exports = Promise.withResolvers.bind(Promise)
} else {
  module.exports = function resolveRejectPromise () {
    const promise = new Promise(setTmp)
    const result = { promise, resolve: tmpResolve, reject: tmpReject }
    tmpResolve = tmpReject = null
    return result
  }
}

function setTmp (resolve, reject) {
  tmpResolve = resolve
  tmpReject = reject
}
{
  "name": "resolve-reject-promise",
  "version": "1.1.0",
  "description": "Create an inverted promise with no function allocs",
  "main": "index.js",
  "scripts": {
    "test": "standard"
  },
  "devDependencies": {
    "standard": "^17.1.2"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/resolve-reject-promise.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/resolve-reject-promise/issues"
  },
  "homepage": "https://github.com/mafintosh/resolve-reject-promise"
}
module.exports = safetyCatch

function isActuallyUncaught (err) {
  if (!err) return false
  return err instanceof TypeError ||
    err instanceof SyntaxError ||
    err instanceof ReferenceError ||
    err instanceof EvalError ||
    err instanceof RangeError ||
    err instanceof URIError ||
    err.code === 'ERR_ASSERTION' ||
    err.name === 'AssertionError'
}

function throwErrorNT (err) {
  queueMicrotask(() => { throw err })
}

function safetyCatch (err) {
  if (isActuallyUncaught(err)) {
    throwErrorNT(err)
    throw err
  }
}
{
  "name": "safety-catch",
  "version": "1.0.3",
  "description": "Small module that makes sure your catch, caught an actual error and not a programming mistake or assertion",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {},
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/safety-catch.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/safety-catch/issues"
  },
  "homepage": "https://github.com/mafintosh/safety-catch"
}
var varint = require('varint')
exports.encode = function encode (v, b, o) {
  v = v >= 0 ? v*2 : v*-2 - 1
  var r = varint.encode(v, b, o)
  encode.bytes = varint.encode.bytes
  return r
}
exports.decode = function decode (b, o) {
  var v = varint.decode(b, o)
  decode.bytes = varint.decode.bytes
  return v & 1 ? (v+1) / -2 : v / 2
}

exports.encodingLength = function (v) {
  return varint.encodingLength(v >= 0 ? v*2 : v*-2 - 1)
}
{
  "name": "signed-varint",
  "description": "efficiently store signed integers in varint",
  "version": "2.0.1",
  "homepage": "https://github.com/dominictarr/signed-varint",
  "repository": {
    "type": "git",
    "url": "git://github.com/dominictarr/signed-varint.git"
  },
  "dependencies": {
    "varint": "~5.0.0"
  },
  "devDependencies": {
    "tape": "~2.12.3"
  },
  "scripts": {
    "test": "node test.js"
  },
  "author": "Dominic Tarr <dominic.tarr@gmail.com> (http://dominictarr.com)",
  "license": "MIT"
}
require.addon = require('require-addon')
module.exports = require.addon('.', __filename)
const assert = require('assert')
const binding = require('./binding')
const { isNode } = require('which-runtime')

const OPTIONAL = Buffer.from(new ArrayBuffer(0))

module.exports = exports = { ...binding }

// memory

exports.sodium_memzero = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  binding.sodium_memzero(buf)
}

exports.sodium_mlock = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  const res = binding.sodium_mlock(buf)

  if (res !== 0) throw new Error('memory lock failed')
}

exports.sodium_munlock = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  const res = binding.sodium_munlock(buf)

  if (res !== 0) throw new Error('memory unlock failed')
}

exports.sodium_malloc = function (size) {
  assert(size >= 0, 'invalid size')

  const buf = Buffer.from(binding.sodium_malloc(size))
  buf.secure = true
  return buf
}

exports.sodium_free = function (buf) {
  if (!buf || !buf.secure) return

  binding.sodium_free(buf.buffer)
}

exports.sodium_mprotect_noaccess = function (buf) {
  const res = binding.sodium_mprotect_noaccess(buf.buffer)

  if (res !== 0) throw new Error('failed to lock buffer')
}

exports.sodium_mprotect_readonly = function (buf) {
  const res = binding.sodium_mprotect_readonly(buf.buffer)

  if (res !== 0) throw new Error('failed to unlock buffer')
}

exports.sodium_mprotect_readwrite = function (buf) {
  const res = binding.sodium_mprotect_readwrite(buf.buffer)

  if (res !== 0) throw new Error('failed to unlock buffer')
}

// crypto_randombytes

exports.randombytes_buf = function (buffer) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')

  binding.randombytes_buf(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

exports.randombytes_buf_deterministic = function (buffer, seed) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    seed.byteLength === binding.randombytes_SEEDBYTES,
    "seed must be 'randombytes_SEEDBYTES' bytes"
  )

  binding.randombytes_buf_deterministic(
    buffer.buffer,
    buffer.byteOffset,
    buffer.byteLength,

    seed.buffer,
    seed.byteOffset,
    seed.byteLength
  )
}

// sodium_helpers

exports.sodium_memcmp = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  return binding.sodium_memcmp(a, b)
}

exports.sodium_add = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  binding.sodium_add(a, b)
}

exports.sodium_sub = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  binding.sodium_sub(a, b)
}

exports.sodium_compare = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  return binding.sodium_compare(a, b)
}

exports.sodium_is_zero = function (buffer, length) {
  if (length === undefined) length = buffer.byteLength

  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(length >= 0 && length <= buffer.byteLength, 'invalid length')

  return binding.sodium_is_zero(buffer, length)
}

exports.sodium_pad = function (buffer, unpaddedBuflen, blockSize) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(unpaddedBuflen <= buffer.byteLength, 'unpadded length cannot exceed buffer length')
  assert(blockSize <= buffer.byteLength, 'block size cannot exceed buffer length')
  assert(blockSize >= 1, 'block size must be at least 1 byte')
  assert(
    buffer.byteLength >= unpaddedBuflen + (blockSize - (unpaddedBuflen % blockSize)),
    'buf not long enough'
  )

  return binding.sodium_pad(buffer, unpaddedBuflen, blockSize)
}

exports.sodium_unpad = function (buffer, paddedBuflen, blockSize) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(paddedBuflen <= buffer.byteLength, 'unpadded length cannot exceed buffer length')
  assert(blockSize <= buffer.byteLength, 'block size cannot exceed buffer length')
  assert(blockSize >= 1, 'block size must be at least 1 byte')

  return binding.sodium_unpad(buffer, paddedBuflen, blockSize)
}

// crypto_sign

exports.crypto_sign_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )
  assert(
    seed.byteLength === binding.crypto_sign_SEEDBYTES,
    "seed must be 'crypto_sign_SEEDBYTES' bytes"
  )

  const res = binding.crypto_sign_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign = function (sm, m, sk) {
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sm.byteLength === binding.crypto_sign_BYTES + m.byteLength,
    "sm must be 'm.byteLength + crypto_sign_BYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign(sm, m, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_open = function (m, sm, pk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sm.byteLength >= binding.crypto_sign_BYTES,
    "sm must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    m.byteLength === sm.byteLength - binding.crypto_sign_BYTES,
    "m must be 'sm.byteLength - crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_open(m, sm, pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_open = function (m, sm, pk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sm.byteLength >= binding.crypto_sign_BYTES,
    "sm must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    m.byteLength === sm.byteLength - binding.crypto_sign_BYTES,
    "m must be 'sm.byteLength - crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  return binding.crypto_sign_open(m, sm, pk)
}

exports.crypto_sign_detached = function (sig, m, sk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(sig.byteLength === binding.crypto_sign_BYTES, "sig must be 'crypto_sign_BYTES' bytes")
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_detached(sig, m, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_verify_detached = function (sig, m, pk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sig.byteLength >= binding.crypto_sign_BYTES,
    "sig must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  return binding.crypto_sign_verify_detached(
    sig.buffer,
    sig.byteOffset,
    sig.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    pk.buffer,
    pk.byteOffset,
    pk.byteLength
  )
}

exports.crypto_sign_ed25519_sk_to_pk = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_sk_to_pk(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_ed25519_pk_to_curve25519 = function (x25519pk, ed25519pk) {
  assert(ArrayBuffer.isView(x25519pk), 'x25519pk must be a typed array')
  assert(ArrayBuffer.isView(ed25519pk), 'ed25519pk must be a typed array')
  assert(
    x25519pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "x25519pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    ed25519pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "ed25519pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_pk_to_curve25519(x25519pk, ed25519pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_ed25519_sk_to_curve25519 = function (x25519sk, ed25519sk) {
  assert(ArrayBuffer.isView(x25519sk), 'x25519sk must be a typed array')
  assert(ArrayBuffer.isView(ed25519sk), 'ed25519sk must be a typed array')
  assert(
    x25519sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "x25519sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const edLen = ed25519sk.byteLength

  assert(
    edLen === binding.crypto_sign_SECRETKEYBYTES || edLen === binding.crypto_box_SECRETKEYBYTES,
    "ed25519sk must be 'crypto_sign_SECRETKEYBYTES' or 'crypto_sign_SECRETKEYBYTES - crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_sk_to_curve25519(x25519sk, ed25519sk)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_box

exports.crypto_box_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    seed.byteLength === binding.crypto_box_SEEDBYTES,
    "seed must be 'crypto_box_SEEDBYTES' bytes"
  )

  const res = binding.crypto_box_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_easy = function (c, m, n, pk, sk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength === m.byteLength + exports.crypto_box_MACBYTES,
    "c must be 'm.byteLength + crypto_box_MACBYTES' bytes"
  )
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_easy(c, m, n, pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_detached = function (c, mac, m, n, pk, sk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(mac.byteLength === exports.crypto_box_MACBYTES, "mac must be 'crypto_box_MACBYTES' bytes")
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_detached(c, mac, m, n, pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_open_easy = function (m, c, n, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength >= exports.crypto_box_MACBYTES,
    "c must be at least 'crypto_box_MACBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - exports.crypto_box_MACBYTES,
    "m must be 'c.byteLength - crypto_box_MACBYTES' bytes"
  )
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_open_easy(m, c, n, pk, sk)
}

exports.crypto_box_open_detached = function (m, c, mac, n, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(mac.byteLength === exports.crypto_box_MACBYTES, "mac must be 'crypto_box_MACBYTES' bytes")
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_open_detached(m, c, mac, n, pk, sk)
}

exports.crypto_box_seal = function (c, m, pk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    c.byteLength === m.byteLength + exports.crypto_box_SEALBYTES,
    "c must be 'm.byteLength + crypto_box_SEALBYTES' bytes"
  )
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_box_seal(c, m, pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_seal_open = function (m, c, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength >= exports.crypto_box_SEALBYTES,
    "c must be at least 'crypto_box_SEALBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - exports.crypto_box_SEALBYTES,
    "m must be 'c.byteLength - crypto_box_SEALBYTES' bytes"
  )
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_seal_open(
    m.buffer,
    m.byteOffset,
    m.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    pk.buffer,
    pk.byteOffset,
    pk.byteLength,

    sk.buffer,
    sk.byteOffset,
    sk.byteLength
  )
}

// crypto_secretbox

exports.crypto_secretbox_easy = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_secretbox_MACBYTES,
    "c must be 'm.byteLength + crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretbox_easy(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretbox_open_easy = function (m, c, n, k) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    c.byteLength >= binding.crypto_secretbox_MACBYTES,
    "c must be at least 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - binding.crypto_secretbox_MACBYTES,
    "m must be 'c.byteLength - crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  return binding.crypto_secretbox_open_easy(m, c, n, k)
}

exports.crypto_secretbox_detached = function (c, mac, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    mac.byteLength === binding.crypto_secretbox_MACBYTES,
    "mac must be 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretbox_detached(c, mac, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretbox_open_detached = function (m, c, mac, n, k) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(
    mac.byteLength === binding.crypto_secretbox_MACBYTES,
    "mac must be 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  return binding.crypto_secretbox_open_detached(m, c, mac, n, k)
}

// crypto_generichash

exports.crypto_generichash = function (output, input, key) {
  if (!key) key = OPTIONAL

  assert(ArrayBuffer.isView(output), 'output must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    output.byteLength >= binding.crypto_generichash_BYTES_MIN &&
      output.byteLength <= binding.crypto_generichash_BYTES_MAX,
    'output must be between crypto_generichash_BYTES_MIN and crypto_generichash_BYTES_MAX bytes'
  )

  if (key !== OPTIONAL) {
    assert(ArrayBuffer.isView(key), 'key must be a typed array')
    assert(
      key.byteLength >= binding.crypto_generichash_KEYBYTES_MIN &&
        key.byteLength <= binding.crypto_generichash_KEYBYTES_MAX,
      'key must be between crypto_generichash_KEYBYTES_MIN and crypto_generichash_KEYBYTES_MAX bytes'
    )
  }

  const res = binding.crypto_generichash(
    output.buffer,
    output.byteOffset,
    output.byteLength,

    input.buffer,
    input.byteOffset,
    input.byteLength,

    key.buffer,
    key.byteOffset,
    key.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_batch = function (output, batch, key) {
  assert(ArrayBuffer.isView(output), 'output must be a typed array')

  if (isNode || batch.length < 4) {
    const res = binding.crypto_generichash_batch(output, batch, !!key, key || OPTIONAL)
    if (res !== 0) throw new Error('status: ' + res)
  } else {
    const state = Buffer.alloc(binding.crypto_generichash_STATEBYTES)

    exports.crypto_generichash_init(state, key, output.byteLength)

    for (const buf of batch) {
      exports.crypto_generichash_update(state, buf)
    }

    exports.crypto_generichash_final(state, output)
  }
}

exports.crypto_generichash_keygen = function (key) {
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(
    key.byteLength === binding.crypto_generichash_KEYBYTES,
    "key must be 'crypto_generichash_KEYBYTES' bytes"
  )

  const res = binding.crypto_generichash_keygen(key.buffer, key.byteOffset, key.byteLength)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_init = function (state, key, outputLength) {
  if (!key) key = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_init(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    key.buffer,
    key.byteOffset,
    key.byteLength,

    outputLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_update(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    input.buffer,
    input.byteOffset,
    input.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_final = function (state, output) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(output), 'output must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_final(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    output.buffer,
    output.byteOffset,
    output.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

// secretstream

exports.crypto_secretstream_xchacha20poly1305_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  binding.crypto_secretstream_xchacha20poly1305_keygen(k.buffer, k.byteOffset, k.byteLength)
}

exports.crypto_secretstream_xchacha20poly1305_init_push = function (state, header, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(header), 'header must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    header.byteLength === binding.crypto_secretstream_xchacha20poly1305_HEADERBYTES,
    "header must be 'crypto_secretstream_xchacha20poly1305_HEADERBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_init_push(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    header.buffer,
    header.byteOffset,
    header.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretstream_xchacha20poly1305_init_pull = function (state, header, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(header), 'header must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    header.byteLength === binding.crypto_secretstream_xchacha20poly1305_HEADERBYTES,
    "header must be 'crypto_secretstream_xchacha20poly1305_HEADERBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_init_pull(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    header.buffer,
    header.byteOffset,
    header.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretstream_xchacha20poly1305_push = function (state, c, m, ad, tag) {
  if (!ad) ad = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    c.byteLength === m.byteLength + binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "c must be 'm.byteLength + crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_push(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    ad.buffer,
    ad.byteOffset,
    ad.byteLength,

    tag
  )

  if (res < 0) throw new Error('push failed')

  return res
}

exports.crypto_secretstream_xchacha20poly1305_pull = function (state, m, tag, c, ad) {
  if (!ad) ad = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(tag), 'tag must be a typed array')
  assert(tag.byteLength === 1, 'tag must be 1 byte')

  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    c.byteLength >= binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "c must be at least 'crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "m must be 'c.byteLength - crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_pull(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    tag.buffer,
    tag.byteOffset,
    tag.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    ad.buffer,
    ad.byteOffset,
    ad.byteLength
  )

  if (res < 0) throw new Error('pull failed')

  return res
}

exports.crypto_secretstream_xchacha20poly1305_rekey = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )

  binding.crypto_secretstream_xchacha20poly1305_rekey(
    state.buffer,
    state.byteOffset,
    state.byteLength
  )
}

// crypto_stream

exports.crypto_stream = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xor(
    c.buffer,
    c.byteOffset,
    c.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    n.buffer,
    n.byteOffset,
    n.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_auth

exports.crypto_auth = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(out.byteLength === binding.crypto_auth_BYTES, "out must be 'crypto_auth_BYTES' bytes")
  assert(k.byteLength === binding.crypto_auth_KEYBYTES, "k must be 'crypto_auth_KEYBYTES' bytes")

  const res = binding.crypto_auth(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_auth_verify = function (h, input, k) {
  assert(ArrayBuffer.isView(h), 'h must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(h.byteLength === binding.crypto_auth_BYTES, "h must be 'crypto_auth_BYTES' bytes")
  assert(k.byteLength === binding.crypto_auth_KEYBYTES, "k must be 'crypto_auth_KEYBYTES' bytes")

  return binding.crypto_auth_verify(h, input, k)
}

// crypto_onetimeauth

exports.crypto_onetimeauth = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    out.byteLength === binding.crypto_onetimeauth_BYTES,
    "out must be 'crypto_onetimeauth_BYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_init = function (state, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_init(state, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )
  assert(
    out.byteLength === binding.crypto_onetimeauth_BYTES,
    "out must be 'crypto_onetimeauth_BYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_verify = function (h, input, k) {
  assert(ArrayBuffer.isView(h), 'h must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    h.byteLength === binding.crypto_onetimeauth_BYTES,
    "h must be 'crypto_onetimeauth_BYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  return binding.crypto_onetimeauth_verify(h, input, k)
}

// crypto_pwhash

exports.crypto_pwhash = function (out, passwd, salt, opslimit, memlimit, alg) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_BYTES_MIN,
    "out must be at least 'crypto_pwhash_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_BYTES_MAX,
    "out must be at most 'crypto_pwhash_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_SALTBYTES,
    "salt must be 'crypto_pwhash_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )
  assert(alg >= 1 && alg <= 2, 'alg must be either Argon2i 1.3 or Argon2id 1.3')

  const res = binding.crypto_pwhash(out, passwd, salt, opslimit, memlimit, alg)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_async = function (
  out,
  passwd,
  salt,
  opslimit,
  memlimit,
  alg,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_BYTES_MIN,
    "out must be at least 'crypto_pwhash_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_BYTES_MAX,
    "out must be at most 'crypto_pwhash_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_SALTBYTES,
    "salt must be 'crypto_pwhash_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )
  assert(alg >= 1 && alg <= 2, 'alg must be either Argon2i 1.3 or Argon2id 1.3')

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    opslimit,
    memlimit,
    alg,

    done
  )

  return promise
}

exports.crypto_pwhash_str = function (out, passwd, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_STRBYTES,
    "out must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(typeof opslimit === 'number', 'opslimit must be a number')
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(typeof memlimit === 'number', 'memlimit must be a number')
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_str(out, passwd, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_str_async = function (out, passwd, opslimit, memlimit, callback = undefined) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_STRBYTES,
    "out must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(typeof opslimit === 'number', 'opslimit must be a number')
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(typeof memlimit === 'number', 'memlimit must be a number')
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_str_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_str_verify = function (str, passwd) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )

  return binding.crypto_pwhash_str_verify(str, passwd)
}

exports.crypto_pwhash_str_verify_async = function (str, passwd, callback = undefined) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  const [done, promise] = checkStatus(callback, true)

  binding.crypto_pwhash_str_verify_async(
    str.buffer,
    str.byteOffset,
    str.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    done
  )

  return promise
}

exports.crypto_pwhash_str_needs_rehash = function (str, opslimit, memlimit) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  return binding.crypto_pwhash_str_needs_rehash(str, opslimit, memlimit)
}

exports.crypto_pwhash_scryptsalsa208sha256 = function (out, passwd, salt, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MIN,
    "out must be at least 'crypto_pwhash_scryptsalsa208sha256_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MAX,
    "out must be at most 'crypto_pwhash_scryptsalsa208sha256_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_SALTBYTES,
    "salt must be 'crypto_pwhash_scryptsalsa208sha256_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_scryptsalsa208sha256(out, passwd, salt, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_scryptsalsa208sha256_async = function (
  out,
  passwd,
  salt,
  opslimit,
  memlimit,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MIN,
    "out must be at least 'crypto_pwhash_scryptsalsa208sha256_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MAX,
    "out must be at most 'crypto_pwhash_scryptsalsa208sha256_BYTES_MAX' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    salt.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_SALTBYTES,
    "salt must be 'crypto_pwhash_scryptsalsa208sha256_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_scryptsalsa208sha256_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str_async = function (
  out,
  passwd,
  opslimit,
  memlimit,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "out must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_scryptsalsa208sha256_str_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str = function (out, passwd, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "out must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_scryptsalsa208sha256_str(out, passwd, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_scryptsalsa208sha256_str_verify_async = function (
  str,
  passwd,
  callback = undefined
) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  const [done, promise] = checkStatus(callback, true)

  binding.crypto_pwhash_scryptsalsa208sha256_str_verify_async(
    str.buffer,
    str.byteOffset,
    str.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str_verify = function (str, passwd) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  return binding.crypto_pwhash_scryptsalsa208sha256_str_verify(str, passwd)
}

exports.crypto_pwhash_scryptsalsa208sha256_str_needs_rehash = function (str, opslimit, memlimit) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  return binding.crypto_pwhash_scryptsalsa208sha256_str_needs_rehash(str, opslimit, memlimit)
}

// crypto_kx

exports.crypto_kx_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "pk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "sk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    pk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "pk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "sk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    seed.byteLength === binding.crypto_kx_SEEDBYTES,
    "seed must be 'crypto_kx_SEEDBYTES' bytes"
  )

  const res = binding.crypto_kx_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_client_session_keys = function (rx, tx, clientPk, clientSk, serverPk) {
  if (!rx) rx = undefined
  if (!tx) tx = undefined

  assert(rx || tx, 'at least one session key must be specified')

  if (rx) {
    assert(ArrayBuffer.isView(rx), 'rx must be a typed array')
    assert(
      rx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "rx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  if (tx) {
    assert(ArrayBuffer.isView(tx), 'tx must be a typed array')
    assert(
      tx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "tx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  assert(ArrayBuffer.isView(clientPk), 'clientPk must be a typed array')
  assert(ArrayBuffer.isView(clientSk), 'clientSk must be a typed array')
  assert(ArrayBuffer.isView(serverPk), 'serverPk must be a typed array')
  assert(
    clientPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "clientPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    clientSk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "clientSk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    serverPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "serverPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_client_session_keys(rx, tx, clientPk, clientSk, serverPk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_server_session_keys = function (rx, tx, serverPk, serverSk, clientPk) {
  if (!rx) rx = undefined
  if (!tx) tx = undefined

  assert(rx || tx, 'at least one session key must be specified')

  if (rx) {
    assert(ArrayBuffer.isView(rx), 'rx must be a typed array')
    assert(
      rx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "rx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  if (tx) {
    assert(ArrayBuffer.isView(tx), 'tx must be a typed array')
    assert(
      tx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "tx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  assert(ArrayBuffer.isView(serverPk), 'serverPk must be a typed array')
  assert(ArrayBuffer.isView(serverSk), 'serverSk must be a typed array')
  assert(ArrayBuffer.isView(clientPk), 'clientPk must be a typed array')
  assert(
    serverPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "serverPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    serverSk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "serverSk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    clientPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "clientPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_server_session_keys(rx, tx, serverPk, serverSk, clientPk)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_scalarmult

exports.crypto_scalarmult_base = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_BYTES,
    "q must be 'crypto_scalarmult_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_SCALARBYTES,
    "n must be 'crypto_scalarmult_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_base(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_BYTES,
    "q must be 'crypto_scalarmult_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_SCALARBYTES,
    "n must be 'crypto_scalarmult_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_BYTES,
    "p must be 'crypto_scalarmult_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_base = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_base(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519 = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "p must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_is_valid_point = function (p) {
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )

  return binding.crypto_core_ed25519_is_valid_point(p)
}

exports.crypto_core_ed25519_from_uniform = function (p, r) {
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_UNIFORMBYTES,
    "r must be 'crypto_core_ed25519_UNIFORMBYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_from_uniform(p, r)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_base_noclamp = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_base_noclamp(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_noclamp = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "p must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_noclamp(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_core

exports.crypto_core_ed25519_add = function (r, p, q) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_BYTES,
    "r must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_core_ed25519_BYTES,
    "q must be 'crypto_core_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_add(r, p, q)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_sub = function (r, p, q) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_BYTES,
    "r must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_core_ed25519_BYTES,
    "q must be 'crypto_core_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_sub(r, p, q)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_scalar_random = function (r) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "r must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_random(r)
}

exports.crypto_core_ed25519_scalar_reduce = function (r, s) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "r must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_NONREDUCEDSCALARBYTES,
    "s must be 'crypto_core_ed25519_NONREDUCEDSCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_reduce(r, s)
}

exports.crypto_core_ed25519_scalar_invert = function (recip, s) {
  assert(ArrayBuffer.isView(recip), 'recip must be a typed array')
  assert(
    recip.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "recip must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_invert(recip, s)
}

exports.crypto_core_ed25519_scalar_negate = function (neg, s) {
  assert(ArrayBuffer.isView(neg), 'neg must be a typed array')
  assert(
    neg.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "neg must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_negate(neg, s)
}

exports.crypto_core_ed25519_scalar_complement = function (comp, s) {
  assert(ArrayBuffer.isView(comp), 'comp must be a typed array')
  assert(
    comp.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "comp must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_complement(comp, s)
}

exports.crypto_core_ed25519_scalar_add = function (z, x, y) {
  assert(ArrayBuffer.isView(z), 'z must be a typed array')
  assert(
    z.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "z must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(x), 'x must be a typed array')
  assert(
    x.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "x must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(y), 'y must be a typed array')
  assert(
    y.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "y must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_add(z, x, y)
}

exports.crypto_core_ed25519_scalar_sub = function (z, x, y) {
  assert(ArrayBuffer.isView(z), 'z must be a typed array')
  assert(
    z.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "z must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(x), 'x must be a typed array')
  assert(
    x.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "x must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(y), 'y must be a typed array')
  assert(
    y.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "y must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_sub(z, x, y)
}

// crypto_shorthash

exports.crypto_shorthash = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_shorthash_BYTES,
    "out must be 'crypto_shorthash_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_shorthash_KEYBYTES,
    "k must be 'crypto_shorthash_KEYBYTES' bytes"
  )

  const res = binding.crypto_shorthash(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_kdf

exports.crypto_kdf_keygen = function (key) {
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(key.byteLength === binding.crypto_kdf_KEYBYTES, "key must be 'crypto_kdf_KEYBYTES' bytes")

  binding.crypto_kdf_keygen(key)
}

exports.crypto_kdf_derive_from_key = function (subkey, subkeyId, ctx, key) {
  assert(ArrayBuffer.isView(subkey), 'subkey must be a typed array')
  assert(
    subkey.byteLength >= binding.crypto_kdf_BYTES_MIN,
    "subkey must be at least 'crypto_kdf_BYTES_MIN' bytes"
  )
  assert(
    subkey.byteLength <= binding.crypto_kdf_BYTES_MAX,
    "subkey must be at most 'crypto_kdf_BYTES_MAX' bytes"
  )
  assert(ArrayBuffer.isView(ctx), 'ctx must be a typed array')
  assert(
    ctx.byteLength === binding.crypto_kdf_CONTEXTBYTES,
    "ctx must be 'crypto_kdf_CONTEXTBYTES' bytes"
  )
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(key.byteLength === binding.crypto_kdf_KEYBYTES, "key must be 'crypto_kdf_KEYBYTES' bytes")

  const res = binding.crypto_kdf_derive_from_key(subkey, subkeyId, ctx, key)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_hash

exports.crypto_hash = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(out.byteLength === binding.crypto_hash_BYTES, "out must be 'crypto_hash_BYTES' bytes")

  const res = binding.crypto_hash(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256 = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha256_BYTES,
    "out must be 'crypto_hash_sha256_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha256(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_init = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_init(state)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha256_BYTES,
    "out must be 'crypto_hash_sha256_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512 = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha512_BYTES,
    "out must be 'crypto_hash_sha512_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha512(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_init = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_init(state)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha512_BYTES,
    "out must be 'crypto_hash_sha512_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_aead

exports.crypto_aead_xchacha20poly1305_ietf_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  binding.crypto_aead_xchacha20poly1305_ietf_keygen(k)
}

exports.crypto_aead_xchacha20poly1305_ietf_encrypt = function (c, m, ad, nsec, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "c must be 'm.byteLength + crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(c.byteLength <= 0xffffffff, 'c.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_encrypt(c, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_decrypt = function (m, nsec, c, ad, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "m must be 'c.byteLength - crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(m.byteLength <= 0xffffffff, 'm.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_decrypt(m, c, ad, npub, k)

  if (res < 0) throw new Error('could not verify data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_encrypt_detached = function (
  c,
  mac,
  m,
  ad,
  nsec,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_encrypt_detached(c, mac, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_decrypt_detached = function (
  m,
  nsec,
  c,
  mac,
  ad,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_decrypt_detached(m, c, mac, ad, npub, k)

  if (res !== 0) throw new Error('could not verify data')
}

exports.crypto_aead_chacha20poly1305_ietf_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  binding.crypto_aead_chacha20poly1305_ietf_keygen(k)
}

exports.crypto_aead_chacha20poly1305_ietf_encrypt = function (c, m, ad, nsec, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "c must be 'm.byteLength + crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(c.byteLength <= 0xffffffff, 'c.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_encrypt(c, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_decrypt = function (m, nsec, c, ad, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "m must be 'c.byteLength - crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(m.byteLength <= 0xffffffff, 'm.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_decrypt(m, c, ad, npub, k)

  if (res < 0) throw new Error('could not verify data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_encrypt_detached = function (
  c,
  mac,
  m,
  ad,
  nsec,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_encrypt_detached(c, mac, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_decrypt_detached = function (
  m,
  nsec,
  c,
  mac,
  ad,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_decrypt_detached(m, c, mac, ad, npub, k)

  if (res !== 0) throw new Error('could not verify data')
}

// crypto_stream

exports.crypto_stream_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  binding.crypto_stream_xor_wrap_init(state, n, k)
}

exports.crypto_stream_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_xor_wrap_update(state, c, m)
}

exports.crypto_stream_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_xor_wrap_final(state)
}

exports.crypto_stream_chacha20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  binding.crypto_stream_chacha20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_chacha20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_chacha20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_chacha20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_chacha20_xor_wrap_final(state)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  binding.crypto_stream_chacha20_ietf_xor_wrap_init(state, n, k)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_chacha20_ietf_xor_wrap_update(state, c, m)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_chacha20_ietf_xor_wrap_final(state)
}

exports.crypto_stream_xchacha20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  binding.crypto_stream_xchacha20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_xchacha20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_xchacha20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_xchacha20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_xchacha20_xor_wrap_final(state)
}

exports.crypto_stream_salsa20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  binding.crypto_stream_salsa20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_salsa20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_salsa20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_salsa20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_salsa20_xor_wrap_final(state)
}

// experimental

exports.extension_tweak_ed25519_base = function (n, p, ns) {
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.extension_tweak_ed25519_BYTES,
    "p must be 'extension_tweak_ed25519_BYTES' bytes"
  )

  binding.extension_tweak_ed25519_base(n, p, ns)
}

exports.extension_tweak_ed25519_sign_detached = function (sig, m, scalar, pk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(sig.byteLength === binding.crypto_sign_BYTES, "sig must be 'crypto_sign_BYTES' bytes")
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  if (pk) {
    assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
    assert(
      pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
      "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
    )
  }

  const res = binding.extension_tweak_ed25519_sign_detached(sig, m, scalar, pk)

  if (res !== 0) throw new Error('failed to compute signature')
}

exports.extension_tweak_ed25519_sk_to_scalar = function (n, sk) {
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  binding.extension_tweak_ed25519_sk_to_scalar(n, sk)
}

exports.extension_tweak_ed25519_scalar = function (scalarOut, scalar, ns) {
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_scalar(scalarOut, scalar, ns)
}

exports.extension_tweak_ed25519_pk = function (tpk, pk, ns) {
  assert(ArrayBuffer.isView(tpk), 'tpk must be a typed array')
  assert(
    tpk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "tpk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_pk(tpk, pk, ns)

  if (res !== 0) throw new Error('failed to tweak public key')
}

exports.extension_tweak_ed25519_keypair = function (pk, scalarOut, scalarIn, ns) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.extension_tweak_ed25519_BYTES,
    "pk must be 'extension_tweak_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarIn), 'scalarIn must be a typed array')
  assert(
    scalarIn.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarIn must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_keypair(pk, scalarOut, scalarIn, ns)
}

exports.extension_tweak_ed25519_scalar_add = function (scalarOut, scalar, n) {
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_scalar_add(scalarOut, scalar, n)
}

exports.extension_tweak_ed25519_pk_add = function (tpk, pk, p) {
  assert(ArrayBuffer.isView(tpk), 'tpk must be a typed array')
  assert(
    tpk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "tpk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "p must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_pk_add(tpk, pk, p)

  if (res !== 0) throw new Error('failed to add tweak to public key')
}

exports.extension_tweak_ed25519_keypair_add = function (pk, scalarOut, scalarIn, tweak) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.extension_tweak_ed25519_BYTES,
    "pk must be 'extension_tweak_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarIn), 'scalarIn must be a typed array')
  assert(
    scalarIn.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarIn must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(tweak), 'tweak must be a typed array')
  assert(
    tweak.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "tweak must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_keypair_add(pk, scalarOut, scalarIn, tweak)

  if (res !== 0) throw new Error('failed to add tweak to keypair')
}

exports.extension_pbkdf2_sha512_async = function (out, passwd, salt, iter, outlen, callback) {
  assert(
    iter >= binding.extension_pbkdf2_sha512_ITERATIONS_MIN,
    "iter must be at least 'extension_pbkdf2_sha512_ITERATIONS_MIN'"
  )
  assert(
    outlen <= binding.extension_pbkdf2_sha512_BYTES_MAX,
    "outlen must be at most 'extension_pbkdf2_sha512_BYTES_MAX'"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(out.byteLength >= outlen, "out must be at least 'outlen' bytes")
  assert(out.byteLength > 0, 'out must not be empty')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(salt.byteLength > 0, 'salt must not be empty')

  const [done, promise] = checkStatus(callback)

  binding.extension_pbkdf2_sha512_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    iter,
    outlen,

    done
  )

  return promise
}

exports.extension_pbkdf2_sha512 = function (out, passwd, salt, iter, outlen) {
  assert(
    iter >= binding.extension_pbkdf2_sha512_ITERATIONS_MIN,
    "iter must be at least 'extension_pbkdf2_sha512_ITERATIONS_MIN'"
  )
  assert(
    outlen <= binding.extension_pbkdf2_sha512_BYTES_MAX,
    "outlen must be at most 'extension_pbkdf2_sha512_BYTES_MAX'"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(out.byteLength >= outlen, "out must be at least 'outlen' bytes")
  assert(out.byteLength > 0, 'out must not be empty')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(salt.byteLength > 0, 'salt must not be empty')

  const res = binding.extension_pbkdf2_sha512(out, passwd, salt, iter, outlen)

  if (res !== 0) throw new Error('failed to add tweak to public key')
}

function checkStatus(callback, booleanResult = false) {
  let done, promise

  if (typeof callback === 'function') {
    done = function (status) {
      if (booleanResult) callback(null, status === 0)
      else if (status === 0) callback(null)
      else callback(new Error('status: ' + status))
    }
  } else {
    promise = new Promise(function (resolve, reject) {
      done = function (status) {
        if (booleanResult) resolve(status === 0)
        else if (status === 0) resolve()
        else reject(new Error('status: ' + status))
      }
    })
  }

  return [done, promise]
}
{
  "name": "sodium-native",
  "version": "5.1.0",
  "description": "Low level bindings for libsodium",
  "main": "index.js",
  "files": [
    "index.js",
    "binding.cc",
    "binding.js",
    "extensions",
    "prebuilds",
    "CMakeLists.txt"
  ],
  "imports": {
    "assert": {
      "bare": "bare-assert",
      "node": "assert"
    }
  },
  "addon": true,
  "dependencies": {
    "bare-assert": "^1.2.0",
    "require-addon": "^1.1.0",
    "which-runtime": "^1.2.1"
  },
  "devDependencies": {
    "bare-compat-napi": "^1.3.5",
    "brittle": "^3.16.2",
    "cmake-bare": "^1.6.1",
    "cmake-fetch": "^1.4.3",
    "cmake-napi": "^1.2.1",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "test": "prettier . --check && npm run test:node && npm run test:bare",
    "test:node": "node test/all.js",
    "test:bare": "bare test/all.js"
  },
  "standard": {
    "ignore": [
      "/test/fixtures/*.js"
    ]
  },
  "engines": {
    "bare": ">=1.16.0"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sodium-native.git"
  },
  "contributors": [
    "Emil Bay <github@tixz.dk> (http://bayes.dk)",
    "Mathias Buus <mathiasbuus@gmail.com> (https://mafinto.sh)",
    "Christophe Diederichs <chm-diederichs@hyperdivision.dk>"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/sodium-native/issues"
  },
  "homepage": "https://github.com/holepunchto/sodium-native"
}
module.exports = require('sodium-native')
{
  "name": "sodium-universal",
  "version": "5.0.1",
  "description": "Universal wrapper for sodium-javascript and sodium-native working in Node.js and the Browser",
  "main": "index.js",
  "dependencies": {
    "sodium-native": "^5.0.1"
  },
  "peerDependencies": {
    "sodium-javascript": "~0.8.0"
  },
  "peerDependenciesMeta": {
    "sodium-javascript": {
      "optional": true
    }
  },
  "scripts": {
    "prepublish": "./build-scripts/generate.js"
  },
  "browser": {
    "sodium-native": "sodium-javascript"
  },
  "browserify": {
    "transform": [
      "./build-scripts/transform.js"
    ]
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sodium-universal.git"
  },
  "keywords": [
    "libsodium",
    "sodium",
    "sodium-native",
    "sodium-javascript",
    "browserify"
  ],
  "contributors": [
    "Emil Bay <github@tixz.dk> (http://bayes.dk)",
    "Mathias Buus <mathiasbuus@gmail.com> (https://mafinto.sh)",
    "Christophe Diederichs <chm-diederichs@hyperdivision.dk>"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/sodium-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/sodium-universal#readme"
}
const { EventEmitter } = require('events-universal')
const FIFO = require('fast-fifo')
const TextDecoder = require('text-decoder')

const StreamError = require('./lib/errors.js')

// if we do a future major, expect queue microtask to be there always, for now a bit defensive
const qmt =
  typeof queueMicrotask === 'undefined' ? (fn) => global.process.nextTick(fn) : queueMicrotask

// 29 bits used total (4 from shared, 14 from read, and 11 from write)
const MAX = (1 << 29) - 1

// Shared state
const OPENING = 0b0001
const PREDESTROYING = 0b0010
const DESTROYING = 0b0100
const DESTROYED = 0b1000

const NOT_OPENING = MAX ^ OPENING
const NOT_PREDESTROYING = MAX ^ PREDESTROYING

// Read state (4 bit offset from shared state)
const READ_ACTIVE = 0b00000000000001 << 4
const READ_UPDATING = 0b00000000000010 << 4
const READ_PRIMARY = 0b00000000000100 << 4
const READ_QUEUED = 0b00000000001000 << 4
const READ_RESUMED = 0b00000000010000 << 4
const READ_PIPE_DRAINED = 0b00000000100000 << 4
const READ_ENDING = 0b00000001000000 << 4
const READ_EMIT_DATA = 0b00000010000000 << 4
const READ_EMIT_READABLE = 0b00000100000000 << 4
const READ_EMITTED_READABLE = 0b00001000000000 << 4
const READ_DONE = 0b00010000000000 << 4
const READ_NEXT_TICK = 0b00100000000000 << 4
const READ_NEEDS_PUSH = 0b01000000000000 << 4
const READ_READ_AHEAD = 0b10000000000000 << 4

// Combined read state
const READ_FLOWING = READ_RESUMED | READ_PIPE_DRAINED
const READ_ACTIVE_AND_NEEDS_PUSH = READ_ACTIVE | READ_NEEDS_PUSH
const READ_PRIMARY_AND_ACTIVE = READ_PRIMARY | READ_ACTIVE
const READ_EMIT_READABLE_AND_QUEUED = READ_EMIT_READABLE | READ_QUEUED
const READ_RESUMED_READ_AHEAD = READ_RESUMED | READ_READ_AHEAD

const READ_NOT_ACTIVE = MAX ^ READ_ACTIVE
const READ_NON_PRIMARY = MAX ^ READ_PRIMARY
const READ_NON_PRIMARY_AND_PUSHED = MAX ^ (READ_PRIMARY | READ_NEEDS_PUSH)
const READ_PUSHED = MAX ^ READ_NEEDS_PUSH
const READ_PAUSED = MAX ^ READ_RESUMED
const READ_NOT_QUEUED = MAX ^ (READ_QUEUED | READ_EMITTED_READABLE)
const READ_NOT_ENDING = MAX ^ READ_ENDING
const READ_PIPE_NOT_DRAINED = MAX ^ READ_FLOWING
const READ_NOT_NEXT_TICK = MAX ^ READ_NEXT_TICK
const READ_NOT_UPDATING = MAX ^ READ_UPDATING
const READ_NO_READ_AHEAD = MAX ^ READ_READ_AHEAD
const READ_PAUSED_NO_READ_AHEAD = MAX ^ READ_RESUMED_READ_AHEAD

// Write state (18 bit offset, 4 bit offset from shared state and 14 from read state)
const WRITE_ACTIVE = 0b00000000001 << 18
const WRITE_UPDATING = 0b00000000010 << 18
const WRITE_PRIMARY = 0b00000000100 << 18
const WRITE_QUEUED = 0b00000001000 << 18
const WRITE_UNDRAINED = 0b00000010000 << 18
const WRITE_DONE = 0b00000100000 << 18
const WRITE_EMIT_DRAIN = 0b00001000000 << 18
const WRITE_NEXT_TICK = 0b00010000000 << 18
const WRITE_WRITING = 0b00100000000 << 18
const WRITE_FINISHING = 0b01000000000 << 18
const WRITE_CORKED = 0b10000000000 << 18

const WRITE_NOT_ACTIVE = MAX ^ (WRITE_ACTIVE | WRITE_WRITING)
const WRITE_NON_PRIMARY = MAX ^ WRITE_PRIMARY
const WRITE_NOT_FINISHING = MAX ^ (WRITE_ACTIVE | WRITE_FINISHING)
const WRITE_DRAINED = MAX ^ WRITE_UNDRAINED
const WRITE_NOT_QUEUED = MAX ^ WRITE_QUEUED
const WRITE_NOT_NEXT_TICK = MAX ^ WRITE_NEXT_TICK
const WRITE_NOT_UPDATING = MAX ^ WRITE_UPDATING
const WRITE_NOT_CORKED = MAX ^ WRITE_CORKED

// Combined shared state
const ACTIVE = READ_ACTIVE | WRITE_ACTIVE
const NOT_ACTIVE = MAX ^ ACTIVE
const DONE = READ_DONE | WRITE_DONE
const DESTROY_STATUS = DESTROYING | DESTROYED | PREDESTROYING
const OPEN_STATUS = DESTROY_STATUS | OPENING
const AUTO_DESTROY = DESTROY_STATUS | DONE
const NON_PRIMARY = WRITE_NON_PRIMARY & READ_NON_PRIMARY
const ACTIVE_OR_TICKING = WRITE_NEXT_TICK | READ_NEXT_TICK
const TICKING = ACTIVE_OR_TICKING & NOT_ACTIVE
const IS_OPENING = OPEN_STATUS | TICKING

// Combined shared state and read state
const READ_PRIMARY_STATUS = OPEN_STATUS | READ_ENDING | READ_DONE
const READ_STATUS = OPEN_STATUS | READ_DONE | READ_QUEUED
const READ_ENDING_STATUS = OPEN_STATUS | READ_ENDING | READ_QUEUED
const READ_READABLE_STATUS = OPEN_STATUS | READ_EMIT_READABLE | READ_QUEUED | READ_EMITTED_READABLE
const SHOULD_NOT_READ =
  OPEN_STATUS | READ_ACTIVE | READ_ENDING | READ_DONE | READ_NEEDS_PUSH | READ_READ_AHEAD
const READ_BACKPRESSURE_STATUS = DESTROY_STATUS | READ_ENDING | READ_DONE
const READ_UPDATE_SYNC_STATUS = READ_UPDATING | OPEN_STATUS | READ_NEXT_TICK | READ_PRIMARY
const READ_NEXT_TICK_OR_OPENING = READ_NEXT_TICK | OPENING

// Combined write state
const WRITE_PRIMARY_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_DONE
const WRITE_QUEUED_AND_UNDRAINED = WRITE_QUEUED | WRITE_UNDRAINED
const WRITE_QUEUED_AND_ACTIVE = WRITE_QUEUED | WRITE_ACTIVE
const WRITE_DRAIN_STATUS = WRITE_QUEUED | WRITE_UNDRAINED | OPEN_STATUS | WRITE_ACTIVE
const WRITE_STATUS = OPEN_STATUS | WRITE_ACTIVE | WRITE_QUEUED | WRITE_CORKED
const WRITE_PRIMARY_AND_ACTIVE = WRITE_PRIMARY | WRITE_ACTIVE
const WRITE_ACTIVE_AND_WRITING = WRITE_ACTIVE | WRITE_WRITING
const WRITE_FINISHING_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_QUEUED_AND_ACTIVE | WRITE_DONE
const WRITE_BACKPRESSURE_STATUS = WRITE_UNDRAINED | DESTROY_STATUS | WRITE_FINISHING | WRITE_DONE
const WRITE_UPDATE_SYNC_STATUS = WRITE_UPDATING | OPEN_STATUS | WRITE_NEXT_TICK | WRITE_PRIMARY
const WRITE_DROP_DATA = WRITE_FINISHING | WRITE_DONE | DESTROY_STATUS

const asyncIterator = Symbol.asyncIterator || Symbol('asyncIterator')

class WritableState {
  constructor(
    stream,
    { highWaterMark = 16384, map = null, mapWritable, byteLength, byteLengthWritable } = {}
  ) {
    this.stream = stream
    this.queue = new FIFO()
    this.highWaterMark = highWaterMark
    this.buffered = 0
    this.error = null
    this.pipeline = null
    this.drains = null // if we add more seldomly used helpers we might them into a subobject so its a single ptr
    this.byteLength = byteLengthWritable || byteLength || defaultByteLength
    this.map = mapWritable || map
    this.afterWrite = afterWrite.bind(this)
    this.afterUpdateNextTick = updateWriteNT.bind(this)
  }

  get ending() {
    return (this.stream._duplexState & WRITE_FINISHING) !== 0
  }

  get ended() {
    return (this.stream._duplexState & WRITE_DONE) !== 0
  }

  push(data) {
    if ((this.stream._duplexState & WRITE_DROP_DATA) !== 0) return false
    if (this.map !== null) data = this.map(data)

    this.buffered += this.byteLength(data)
    this.queue.push(data)

    if (this.buffered < this.highWaterMark) {
      this.stream._duplexState |= WRITE_QUEUED
      return true
    }

    this.stream._duplexState |= WRITE_QUEUED_AND_UNDRAINED
    return false
  }

  shift() {
    const data = this.queue.shift()

    this.buffered -= this.byteLength(data)
    if (this.buffered === 0) this.stream._duplexState &= WRITE_NOT_QUEUED

    return data
  }

  end(data) {
    if (typeof data === 'function') {
      this.stream.once('finish', data)
    } else if (data !== undefined && data !== null) {
      this.push(data)
    }

    this.stream._duplexState = (this.stream._duplexState | WRITE_FINISHING) & WRITE_NON_PRIMARY
  }

  autoBatch(data, cb) {
    const buffer = []
    const stream = this.stream

    buffer.push(data)
    while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED_AND_ACTIVE) {
      buffer.push(stream._writableState.shift())
    }

    if ((stream._duplexState & OPEN_STATUS) !== 0) return cb(null)
    stream._writev(buffer, cb)
  }

  update() {
    const stream = this.stream

    stream._duplexState |= WRITE_UPDATING

    do {
      while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED) {
        const data = this.shift()
        stream._duplexState |= WRITE_ACTIVE_AND_WRITING
        stream._write(data, this.afterWrite)
      }

      if ((stream._duplexState & WRITE_PRIMARY_AND_ACTIVE) === 0) this.updateNonPrimary()
    } while (this.continueUpdate() === true)

    stream._duplexState &= WRITE_NOT_UPDATING
  }

  updateNonPrimary() {
    const stream = this.stream

    if ((stream._duplexState & WRITE_FINISHING_STATUS) === WRITE_FINISHING) {
      stream._duplexState = stream._duplexState | WRITE_ACTIVE
      stream._final(afterFinal.bind(this))
      return
    }

    if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
      if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
        stream._duplexState |= ACTIVE
        stream._destroy(afterDestroy.bind(this))
      }
      return
    }

    if ((stream._duplexState & IS_OPENING) === OPENING) {
      stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING
      stream._open(afterOpen.bind(this))
    }
  }

  continueUpdate() {
    if ((this.stream._duplexState & WRITE_NEXT_TICK) === 0) return false
    this.stream._duplexState &= WRITE_NOT_NEXT_TICK
    return true
  }

  updateCallback() {
    if ((this.stream._duplexState & WRITE_UPDATE_SYNC_STATUS) === WRITE_PRIMARY) {
      this.update()
    } else {
      this.updateNextTick()
    }
  }

  updateNextTick() {
    if ((this.stream._duplexState & WRITE_NEXT_TICK) !== 0) return
    this.stream._duplexState |= WRITE_NEXT_TICK
    if ((this.stream._duplexState & WRITE_UPDATING) === 0) qmt(this.afterUpdateNextTick)
  }
}

class ReadableState {
  constructor(
    stream,
    { highWaterMark = 16384, map = null, mapReadable, byteLength, byteLengthReadable } = {}
  ) {
    this.stream = stream
    this.queue = new FIFO()
    this.highWaterMark = highWaterMark === 0 ? 1 : highWaterMark
    this.buffered = 0
    this.readAhead = highWaterMark > 0
    this.error = null
    this.pipeline = null
    this.byteLength = byteLengthReadable || byteLength || defaultByteLength
    this.map = mapReadable || map
    this.pipeTo = null
    this.afterRead = afterRead.bind(this)
    this.afterUpdateNextTick = updateReadNT.bind(this)
  }

  get ending() {
    return (this.stream._duplexState & READ_ENDING) !== 0
  }

  get ended() {
    return (this.stream._duplexState & READ_DONE) !== 0
  }

  pipe(pipeTo, cb) {
    if (this.pipeTo !== null) throw StreamError.BAD_ARGUMENT('Can only pipe to one destination')
    if (typeof cb !== 'function') cb = null

    this.stream._duplexState |= READ_PIPE_DRAINED
    this.pipeTo = pipeTo
    this.pipeline = new Pipeline(this.stream, pipeTo, cb)

    if (cb) this.stream.on('error', noop) // We already error handle this so supress crashes

    if (isStreamx(pipeTo)) {
      pipeTo._writableState.pipeline = this.pipeline
      if (cb) pipeTo.on('error', noop) // We already error handle this so supress crashes
      pipeTo.on('finish', this.pipeline.finished.bind(this.pipeline)) // TODO: just call finished from pipeTo itself
    } else {
      const onerror = this.pipeline.done.bind(this.pipeline, pipeTo)
      const onclose = this.pipeline.done.bind(this.pipeline, pipeTo, null) // onclose has a weird bool arg
      pipeTo.on('error', onerror)
      pipeTo.on('close', onclose)
      pipeTo.on('finish', this.pipeline.finished.bind(this.pipeline))
    }

    pipeTo.on('drain', afterDrain.bind(this))
    this.stream.emit('piping', pipeTo)
    pipeTo.emit('pipe', this.stream)
  }

  push(data) {
    const stream = this.stream

    if (data === null) {
      this.highWaterMark = 0
      stream._duplexState = (stream._duplexState | READ_ENDING) & READ_NON_PRIMARY_AND_PUSHED
      return false
    }

    if (this.map !== null) {
      data = this.map(data)
      if (data === null) {
        stream._duplexState &= READ_PUSHED
        return this.buffered < this.highWaterMark
      }
    }

    this.buffered += this.byteLength(data)
    this.queue.push(data)

    stream._duplexState = (stream._duplexState | READ_QUEUED) & READ_PUSHED

    return this.buffered < this.highWaterMark
  }

  shift() {
    const data = this.queue.shift()

    this.buffered -= this.byteLength(data)
    if (this.buffered === 0) {
      this.stream._duplexState &= READ_NOT_QUEUED
    }

    return data
  }

  unshift(data) {
    const pending = [this.map !== null ? this.map(data) : data]
    while (this.buffered > 0) pending.push(this.shift())

    for (let i = 0; i < pending.length - 1; i++) {
      const data = pending[i]
      this.buffered += this.byteLength(data)
      this.queue.push(data)
    }

    this.push(pending[pending.length - 1])
  }

  read() {
    const stream = this.stream

    if ((stream._duplexState & READ_STATUS) === READ_QUEUED) {
      const data = this.shift()

      if (this.pipeTo !== null && this.pipeTo.write(data) === false) {
        stream._duplexState &= READ_PIPE_NOT_DRAINED
      }

      if ((stream._duplexState & READ_EMIT_DATA) !== 0) {
        stream.emit('data', data)
      }

      return data
    }

    if (this.readAhead === false) {
      stream._duplexState |= READ_READ_AHEAD
      this.updateNextTick()
    }

    return null
  }

  drain() {
    const stream = this.stream

    while (
      (stream._duplexState & READ_STATUS) === READ_QUEUED &&
      (stream._duplexState & READ_FLOWING) !== 0
    ) {
      const data = this.shift()

      if (this.pipeTo !== null && this.pipeTo.write(data) === false) {
        stream._duplexState &= READ_PIPE_NOT_DRAINED
      }

      if ((stream._duplexState & READ_EMIT_DATA) !== 0) {
        stream.emit('data', data)
      }
    }
  }

  update() {
    const stream = this.stream

    stream._duplexState |= READ_UPDATING

    do {
      this.drain()

      while (
        this.buffered < this.highWaterMark &&
        (stream._duplexState & SHOULD_NOT_READ) === READ_READ_AHEAD
      ) {
        stream._duplexState |= READ_ACTIVE_AND_NEEDS_PUSH
        stream._read(this.afterRead)
        this.drain()
      }

      if ((stream._duplexState & READ_READABLE_STATUS) === READ_EMIT_READABLE_AND_QUEUED) {
        stream._duplexState |= READ_EMITTED_READABLE
        stream.emit('readable')
      }

      if ((stream._duplexState & READ_PRIMARY_AND_ACTIVE) === 0) {
        this.updateNonPrimary()
      }
    } while (this.continueUpdate() === true)

    stream._duplexState &= READ_NOT_UPDATING
  }

  updateNonPrimary() {
    const stream = this.stream

    if ((stream._duplexState & READ_ENDING_STATUS) === READ_ENDING) {
      stream._duplexState = (stream._duplexState | READ_DONE) & READ_NOT_ENDING
      stream.emit('end')

      if ((stream._duplexState & AUTO_DESTROY) === DONE) {
        stream._duplexState |= DESTROYING
      }

      if (this.pipeTo !== null) {
        this.pipeTo.end()
      }
    }

    if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
      if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
        stream._duplexState |= ACTIVE
        stream._destroy(afterDestroy.bind(this))
      }
      return
    }

    if ((stream._duplexState & IS_OPENING) === OPENING) {
      stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING
      stream._open(afterOpen.bind(this))
    }
  }

  continueUpdate() {
    if ((this.stream._duplexState & READ_NEXT_TICK) === 0) return false
    this.stream._duplexState &= READ_NOT_NEXT_TICK
    return true
  }

  updateCallback() {
    if ((this.stream._duplexState & READ_UPDATE_SYNC_STATUS) === READ_PRIMARY) {
      this.update()
    } else {
      this.updateNextTick()
    }
  }

  updateNextTickIfOpen() {
    if ((this.stream._duplexState & READ_NEXT_TICK_OR_OPENING) !== 0) return
    this.stream._duplexState |= READ_NEXT_TICK
    if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick)
  }

  updateNextTick() {
    if ((this.stream._duplexState & READ_NEXT_TICK) !== 0) return
    this.stream._duplexState |= READ_NEXT_TICK
    if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick)
  }
}

class TransformState {
  constructor(stream) {
    this.data = null
    this.afterTransform = afterTransform.bind(stream)
    this.afterFinal = null
  }
}

class Pipeline {
  constructor(src, dst, cb) {
    this.from = src
    this.to = dst
    this.afterPipe = cb
    this.error = null
    this.pipeToFinished = false
  }

  finished() {
    this.pipeToFinished = true
  }

  done(stream, err) {
    if (err) this.error = err

    if (stream === this.to) {
      this.to = null

      if (this.from !== null) {
        if ((this.from._duplexState & READ_DONE) === 0 || !this.pipeToFinished) {
          this.from.destroy(this.error || StreamError.PREMATURE_CLOSE('Writable stream closed'))
        }
        return
      }
    }

    if (stream === this.from) {
      this.from = null

      if (this.to !== null) {
        if ((stream._duplexState & READ_DONE) === 0) {
          this.to.destroy(this.error || StreamError.PREMATURE_CLOSE('Readable stream closed'))
        }
        return
      }
    }

    if (this.afterPipe !== null) this.afterPipe(this.error)
    this.to = this.from = this.afterPipe = null
  }
}

function afterDrain() {
  this.stream._duplexState |= READ_PIPE_DRAINED
  this.updateCallback()
}

function afterFinal(err) {
  const stream = this.stream
  if (err) stream.destroy(err)

  if ((stream._duplexState & DESTROY_STATUS) === 0) {
    stream._duplexState |= WRITE_DONE
    stream.emit('finish')
  }

  if ((stream._duplexState & AUTO_DESTROY) === DONE) {
    stream._duplexState |= DESTROYING
  }

  stream._duplexState &= WRITE_NOT_FINISHING

  // no need to wait the extra tick here, so we short circuit that
  if ((stream._duplexState & WRITE_UPDATING) === 0) {
    this.update()
  } else {
    this.updateNextTick()
  }
}

function afterDestroy(err) {
  const stream = this.stream

  if (!err && !StreamError.isStreamDestroyed(this.error)) err = this.error
  if (err) stream.emit('error', err)

  stream._duplexState |= DESTROYED
  stream.emit('close')

  const rs = stream._readableState
  const ws = stream._writableState

  if (rs !== null && rs.pipeline !== null) {
    rs.pipeline.done(stream, err)
  }

  if (ws !== null) {
    while (ws.drains !== null && ws.drains.length > 0) {
      ws.drains.shift().resolve(false)
    }

    if (ws.pipeline !== null) {
      ws.pipeline.done(stream, err)
    }
  }
}

function afterWrite(err) {
  const stream = this.stream

  if (err) stream.destroy(err)
  stream._duplexState &= WRITE_NOT_ACTIVE

  if (this.drains !== null) tickDrains(this.drains)

  if ((stream._duplexState & WRITE_DRAIN_STATUS) === WRITE_UNDRAINED) {
    stream._duplexState &= WRITE_DRAINED

    if ((stream._duplexState & WRITE_EMIT_DRAIN) === WRITE_EMIT_DRAIN) {
      stream.emit('drain')
    }
  }

  this.updateCallback()
}

function afterRead(err) {
  if (err) this.stream.destroy(err)
  this.stream._duplexState &= READ_NOT_ACTIVE

  if (this.readAhead === false && (this.stream._duplexState & READ_RESUMED) === 0) {
    this.stream._duplexState &= READ_NO_READ_AHEAD
  }

  this.updateCallback()
}

function updateReadNT() {
  if ((this.stream._duplexState & READ_UPDATING) === 0) {
    this.stream._duplexState &= READ_NOT_NEXT_TICK
    this.update()
  }
}

function updateWriteNT() {
  if ((this.stream._duplexState & WRITE_UPDATING) === 0) {
    this.stream._duplexState &= WRITE_NOT_NEXT_TICK
    this.update()
  }
}

function tickDrains(drains) {
  for (let i = 0; i < drains.length; i++) {
    // drains.writes are monotonic, so if one is 0 its always the first one
    if (--drains[i].writes === 0) {
      drains.shift().resolve(true)
      i--
    }
  }
}

function afterOpen(err) {
  const stream = this.stream

  if (err) stream.destroy(err)

  if ((stream._duplexState & DESTROYING) === 0) {
    if ((stream._duplexState & READ_PRIMARY_STATUS) === 0) {
      stream._duplexState |= READ_PRIMARY
    }

    if ((stream._duplexState & WRITE_PRIMARY_STATUS) === 0) {
      stream._duplexState |= WRITE_PRIMARY
    }

    stream.emit('open')
  }

  stream._duplexState &= NOT_ACTIVE

  if (stream._writableState !== null) {
    stream._writableState.updateCallback()
  }

  if (stream._readableState !== null) {
    stream._readableState.updateCallback()
  }
}

function afterTransform(err, data) {
  if (data !== undefined && data !== null) this.push(data)
  this._writableState.afterWrite(err)
}

function newListener(name) {
  if (this._readableState !== null) {
    if (name === 'data') {
      this._duplexState |= READ_EMIT_DATA | READ_RESUMED_READ_AHEAD
      this._readableState.updateNextTick()
    }
    if (name === 'readable') {
      this._duplexState |= READ_EMIT_READABLE
      this._readableState.updateNextTick()
    }
  }

  if (this._writableState !== null) {
    if (name === 'drain') {
      this._duplexState |= WRITE_EMIT_DRAIN
      this._writableState.updateNextTick()
    }
  }
}

class Stream extends EventEmitter {
  constructor(opts) {
    super()

    this._duplexState = 0
    this._readableState = null
    this._writableState = null

    if (opts) {
      if (opts.open) this._open = opts.open
      if (opts.destroy) this._destroy = opts.destroy
      if (opts.predestroy) this._predestroy = opts.predestroy
      if (opts.signal) opts.signal.addEventListener('abort', abort.bind(this))
    }

    this.on('newListener', newListener)
  }

  _open(cb) {
    cb(null)
  }

  _destroy(cb) {
    cb(null)
  }

  _predestroy() {
    // does nothing
  }

  get readable() {
    return this._readableState !== null ? true : undefined
  }

  get writable() {
    return this._writableState !== null ? true : undefined
  }

  get destroyed() {
    return (this._duplexState & DESTROYED) !== 0
  }

  get destroying() {
    return (this._duplexState & DESTROY_STATUS) !== 0
  }

  destroy(err) {
    if ((this._duplexState & DESTROY_STATUS) === 0) {
      if (!err) err = StreamError.STREAM_DESTROYED()
      this._duplexState = (this._duplexState | DESTROYING) & NON_PRIMARY

      if (this._readableState !== null) {
        this._readableState.highWaterMark = 0
        this._readableState.error = err
      }

      if (this._writableState !== null) {
        this._writableState.highWaterMark = 0
        this._writableState.error = err
      }

      this._duplexState |= PREDESTROYING
      this._predestroy()
      this._duplexState &= NOT_PREDESTROYING

      if (this._readableState !== null) {
        this._readableState.updateNextTick()
      }

      if (this._writableState !== null) {
        this._writableState.updateNextTick()
      }
    }
  }
}

class Readable extends Stream {
  constructor(opts) {
    super(opts)

    this._duplexState |= OPENING | WRITE_DONE | READ_READ_AHEAD
    this._readableState = new ReadableState(this, opts)

    if (opts) {
      if (this._readableState.readAhead === false) this._duplexState &= READ_NO_READ_AHEAD
      if (opts.read) this._read = opts.read
      if (opts.eagerOpen) this._readableState.updateNextTick()
      if (opts.encoding) this.setEncoding(opts.encoding)
    }
  }

  static deferred(fn, opts) {
    const out = new PassThrough(opts)

    fn()
      .then((src) => {
        if (src === null) return out.end()
        if (out.destroying) return
        pipeline(src, out, noop)
      })
      .catch((err) => out.destroy(err))

    return out
  }

  setEncoding(encoding) {
    const dec = new TextDecoder(encoding)
    const map = this._readableState.map || echo
    this._readableState.map = mapOrSkip
    return this

    function mapOrSkip(data) {
      const next = dec.push(data)
      return next === '' && (data.byteLength !== 0 || dec.remaining > 0) ? null : map(next)
    }
  }

  _read(cb) {
    cb(null)
  }

  pipe(dest, cb) {
    this._readableState.updateNextTick()
    this._readableState.pipe(dest, cb)
    return dest
  }

  read() {
    this._readableState.updateNextTick()
    return this._readableState.read()
  }

  push(data) {
    this._readableState.updateNextTickIfOpen()
    return this._readableState.push(data)
  }

  unshift(data) {
    this._readableState.updateNextTickIfOpen()
    return this._readableState.unshift(data)
  }

  resume() {
    this._duplexState |= READ_RESUMED_READ_AHEAD
    this._readableState.updateNextTick()
    return this
  }

  pause() {
    this._duplexState &=
      this._readableState.readAhead === false ? READ_PAUSED_NO_READ_AHEAD : READ_PAUSED
    return this
  }

  static _fromAsyncIterator(ite, opts) {
    let destroy

    const rs = new Readable({
      ...opts,
      read(cb) {
        ite.next().then(push).then(cb.bind(null, null)).catch(cb)
      },
      predestroy() {
        destroy = ite.return()
      },
      destroy(cb) {
        if (!destroy) return cb(null)
        destroy.then(cb.bind(null, null)).catch(cb)
      }
    })

    return rs

    function push(data) {
      if (data.done) rs.push(null)
      else rs.push(data.value)
    }
  }

  static from(data, opts) {
    if (isReadStreamx(data)) return data
    if (data[asyncIterator]) return this._fromAsyncIterator(data[asyncIterator](), opts)
    if (!Array.isArray(data)) data = data === undefined ? [] : [data]

    let i = 0
    return new Readable({
      ...opts,
      read(cb) {
        this.push(i === data.length ? null : data[i++])
        cb(null)
      }
    })
  }

  static isBackpressured(rs) {
    return (
      (rs._duplexState & READ_BACKPRESSURE_STATUS) !== 0 ||
      rs._readableState.buffered >= rs._readableState.highWaterMark
    )
  }

  static isPaused(rs) {
    return (rs._duplexState & READ_RESUMED) === 0
  }

  [asyncIterator]() {
    const stream = this

    let error = null
    let promiseResolve = null
    let promiseReject = null

    this.on('error', (err) => {
      error = err
    })
    this.on('readable', onreadable)
    this.on('close', onclose)

    return {
      [asyncIterator]() {
        return this
      },
      next() {
        return new Promise(function (resolve, reject) {
          promiseResolve = resolve
          promiseReject = reject
          const data = stream.read()
          if (data !== null) ondata(data)
          else if ((stream._duplexState & DESTROYED) !== 0) ondata(null)
        })
      },
      return() {
        return destroy(null)
      },
      throw(err) {
        return destroy(err)
      }
    }

    function onreadable() {
      if (promiseResolve !== null) ondata(stream.read())
    }

    function onclose() {
      if (promiseResolve !== null) ondata(null)
    }

    function ondata(data) {
      if (promiseReject === null) return
      if (error) {
        promiseReject(error)
      } else if (data === null && (stream._duplexState & READ_DONE) === 0) {
        promiseReject(StreamError.STREAM_DESTROYED())
      } else {
        promiseResolve({ value: data, done: data === null })
      }
      promiseReject = promiseResolve = null
    }

    function destroy(err) {
      stream.destroy(err)
      return new Promise((resolve, reject) => {
        if (stream._duplexState & DESTROYED) return resolve({ value: undefined, done: true })
        stream.once('close', function () {
          if (err) reject(err)
          else resolve({ value: undefined, done: true })
        })
      })
    }
  }
}

class Writable extends Stream {
  constructor(opts) {
    super(opts)

    this._duplexState |= OPENING | READ_DONE
    this._writableState = new WritableState(this, opts)

    if (opts) {
      if (opts.writev) this._writev = opts.writev
      if (opts.write) this._write = opts.write
      if (opts.final) this._final = opts.final
      if (opts.eagerOpen) this._writableState.updateNextTick()
    }
  }

  cork() {
    this._duplexState |= WRITE_CORKED
  }

  uncork() {
    this._duplexState &= WRITE_NOT_CORKED
    this._writableState.updateNextTick()
  }

  _writev(batch, cb) {
    cb(null)
  }

  _write(data, cb) {
    this._writableState.autoBatch(data, cb)
  }

  _final(cb) {
    cb(null)
  }

  static isBackpressured(ws) {
    return (ws._duplexState & WRITE_BACKPRESSURE_STATUS) !== 0
  }

  static drained(ws) {
    if (ws.destroyed) return Promise.resolve(false)

    const state = ws._writableState
    const pending = isWritev(ws) ? Math.min(1, state.queue.length) : state.queue.length
    const writes = pending + (ws._duplexState & WRITE_WRITING ? 1 : 0)
    if (writes === 0) return Promise.resolve(true)

    if (state.drains === null) state.drains = []
    return new Promise((resolve) => {
      state.drains.push({ writes, resolve })
    })
  }

  write(data) {
    this._writableState.updateNextTick()
    return this._writableState.push(data)
  }

  end(data) {
    this._writableState.updateNextTick()
    this._writableState.end(data)
    return this
  }
}

class Duplex extends Readable {
  // and Writable
  constructor(opts) {
    super(opts)

    this._duplexState = OPENING | (this._duplexState & READ_READ_AHEAD)
    this._writableState = new WritableState(this, opts)

    if (opts) {
      if (opts.writev) this._writev = opts.writev
      if (opts.write) this._write = opts.write
      if (opts.final) this._final = opts.final
    }
  }

  cork() {
    this._duplexState |= WRITE_CORKED
  }

  uncork() {
    this._duplexState &= WRITE_NOT_CORKED
    this._writableState.updateNextTick()
  }

  _writev(batch, cb) {
    cb(null)
  }

  _write(data, cb) {
    this._writableState.autoBatch(data, cb)
  }

  _final(cb) {
    cb(null)
  }

  write(data) {
    this._writableState.updateNextTick()
    return this._writableState.push(data)
  }

  end(data) {
    this._writableState.updateNextTick()
    this._writableState.end(data)
    return this
  }
}

class Transform extends Duplex {
  constructor(opts) {
    super(opts)
    this._transformState = new TransformState(this)

    if (opts) {
      if (opts.transform) this._transform = opts.transform
      if (opts.flush) this._flush = opts.flush
    }
  }

  _write(data, cb) {
    if (this._readableState.buffered >= this._readableState.highWaterMark) {
      this._transformState.data = data
    } else {
      this._transform(data, this._transformState.afterTransform)
    }
  }

  _read(cb) {
    if (this._transformState.data !== null) {
      const data = this._transformState.data
      this._transformState.data = null
      cb(null)
      this._transform(data, this._transformState.afterTransform)
    } else {
      cb(null)
    }
  }

  destroy(err) {
    super.destroy(err)
    if (this._transformState.data !== null) {
      this._transformState.data = null
      this._transformState.afterTransform()
    }
  }

  _transform(data, cb) {
    cb(null, data)
  }

  _flush(cb) {
    cb(null)
  }

  _final(cb) {
    this._transformState.afterFinal = cb
    this._flush(transformAfterFlush.bind(this))
  }
}

class PassThrough extends Transform {}

function transformAfterFlush(err, data) {
  const cb = this._transformState.afterFinal
  if (err) return cb(err)

  if (data !== null && data !== undefined) this.push(data)
  this.push(null)
  cb(null)
}

function pipelinePromise(...streams) {
  return new Promise((resolve, reject) => {
    return pipeline(...streams, (err) => {
      if (err) return reject(err)
      resolve()
    })
  })
}

function pipeline(stream, ...streams) {
  const all = Array.isArray(stream) ? [...stream, ...streams] : [stream, ...streams]
  const done = all.length && typeof all[all.length - 1] === 'function' ? all.pop() : null

  if (all.length < 2) throw StreamError.BAD_ARGUMENT('Pipeline requires at least 2 streams')

  let src = all[0]
  let dest = null
  let error = null

  for (let i = 1; i < all.length; i++) {
    dest = all[i]

    if (isStreamx(src)) {
      src.pipe(dest, onerror)
    } else {
      errorHandle(src, true, i > 1, onerror)
      src.pipe(dest)
    }

    src = dest
  }

  if (done) {
    let fin = false

    const autoDestroy =
      isStreamx(dest) || !!(dest._writableState && dest._writableState.autoDestroy)

    dest.on('error', (err) => {
      if (error === null) error = err
    })

    dest.on('finish', () => {
      fin = true
      if (!autoDestroy) done(error)
    })

    if (autoDestroy) {
      dest.on('close', () => done(error || (fin ? null : StreamError.PREMATURE_CLOSE())))
    }
  }

  return dest

  function errorHandle(s, rd, wr, onerror) {
    s.on('error', onerror)
    s.on('close', onclose)

    function onclose() {
      if (rd && s._readableState && !s._readableState.ended) {
        return onerror(StreamError.PREMATURE_CLOSE())
      }
      if (wr && s._writableState && !s._writableState.ended) {
        return onerror(StreamError.PREMATURE_CLOSE())
      }
    }
  }

  function onerror(err) {
    if (!err || error) return
    error = err

    for (const s of all) {
      s.destroy(err)
    }
  }
}

function echo(s) {
  return s
}

function isStream(stream) {
  return !!stream._readableState || !!stream._writableState
}

function isStreamx(stream) {
  return typeof stream._duplexState === 'number' && isStream(stream)
}

function isEnding(stream) {
  return !!stream._readableState && stream._readableState.ending
}

function isEnded(stream) {
  return !!stream._readableState && stream._readableState.ended
}

function isFinishing(stream) {
  return !!stream._writableState && stream._writableState.ending
}

function isFinished(stream) {
  return !!stream._writableState && stream._writableState.ended
}

function getStreamError(stream, opts = {}) {
  const err =
    (stream._readableState && stream._readableState.error) ||
    (stream._writableState && stream._writableState.error)

  // avoid implicit errors by default
  return !opts.all && StreamError.isStreamDestroyed(err) ? null : err
}

function isReadStreamx(stream) {
  return isStreamx(stream) && stream.readable
}

function isDisturbed(stream) {
  return (
    (stream._duplexState & OPENING) !== OPENING ||
    (stream._duplexState & DESTROYING) === DESTROYING ||
    (stream._duplexState & ACTIVE_OR_TICKING) !== 0
  )
}

function isTypedArray(data) {
  return typeof data === 'object' && data !== null && typeof data.byteLength === 'number'
}

function defaultByteLength(data) {
  return isTypedArray(data) ? data.byteLength : 1024
}

function noop() {}

function abort() {
  this.destroy(StreamError.ABORTED())
}

function isWritev(s) {
  return s._writev !== Writable.prototype._writev && s._writev !== Duplex.prototype._writev
}

module.exports = {
  pipeline,
  pipelinePromise,
  isStream,
  isStreamx,
  isEnding,
  isEnded,
  isFinishing,
  isFinished,
  isDisturbed,
  getStreamError,
  Stream,
  Writable,
  Readable,
  Duplex,
  Transform,
  // Export PassThrough for compatibility with Node.js core's stream module
  PassThrough
}
module.exports = class StreamError extends Error {
  constructor(msg, code, fn = StreamError) {
    super(msg)

    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  static isStreamDestroyed(err) {
    return err && err.code === 'STREAM_DESTROYED'
  }

  static isPrematureClose(err) {
    return err && err.code === 'PREMATURE_CLOSE'
  }

  static isAborted(err) {
    return err && err.code === 'ABORTED'
  }

  static isBadArgument(err) {
    return err && err.code === 'BAD_ARGUMENT'
  }

  get name() {
    return 'StreamError'
  }

  static STREAM_DESTROYED() {
    return new StreamError('Stream was destroyed', 'STREAM_DESTROYED', StreamError.STREAM_DESTROYED)
  }

  static PREMATURE_CLOSE(msg = 'Premature close') {
    return new StreamError(msg, 'PREMATURE_CLOSE', StreamError.PREMATURE_CLOSE)
  }

  static ABORTED() {
    return new StreamError('Stream aborted', 'ABORTED', StreamError.ABORTED)
  }

  static BAD_ARGUMENT(msg = 'Bad argument') {
    return new StreamError(msg, 'BAD_ARGUMENT', StreamError.BAD_ARGUMENT)
  }
}
{
  "name": "streamx",
  "version": "2.28.0",
  "description": "An iteration of the Node.js core streams with a series of improvements",
  "main": "index.js",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./errors": {
      "types": "./lib/errors.d.ts",
      "default": "./lib/errors"
    }
  },
  "dependencies": {
    "events-universal": "^1.0.0",
    "fast-fifo": "^1.3.2",
    "text-decoder": "^1.1.0"
  },
  "devDependencies": {
    "b4a": "^1.6.6",
    "brittle": "^3.1.1",
    "end-of-stream": "^1.4.4",
    "lunte": "^1.8.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "runtime.d.ts",
    "lib"
  ],
  "scripts": {
    "format": "prettier . --write",
    "test": "brittle test/all.js && brittle-bare test/all.js",
    "lint": "prettier . --check && lunte"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/streamx.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/streamx/issues"
  },
  "homepage": "https://github.com/mafintosh/streamx"
}
const { Readable } = require('streamx')

module.exports = function (s, forks = 2) {
  const streams = new Array(forks)
  const status = new Array(forks).fill(true)

  let ended = false

  for (let i = 0; i < forks; i++) {
    streams[i] = new Readable({
      read (cb) {
        const check = !status[i]
        status[i] = true
        if (check && allReadable()) s.resume()
        cb(null)
      }
    })
  }

  s.on('end', function () {
    ended = true
    for (const stream of streams) stream.push(null)
  })

  s.on('error', function (err) {
    for (const stream of streams) stream.destroy(err)
  })

  s.on('close', function () {
    if (ended) return
    for (const stream of streams) stream.destroy()
  })

  s.on('data', function (data) {
    let needsPause = false
    for (let i = 0; i < streams.length; i++) {
      if (!(status[i] = streams[i].push(data))) {
        needsPause = true
      }
    }
    if (needsPause) s.pause()
  })

  return streams

  function allReadable () {
    for (let j = 0; j < status.length; j++) {
      if (!status[j]) return false
    }
    return true
  }
}
{
  "name": "teex",
  "version": "1.0.1",
  "description": "Turn a readable stream into multiple readable streamx streams",
  "main": "index.js",
  "dependencies": {
    "streamx": "^2.12.5"
  },
  "devDependencies": {
    "standard": "^14.3.4",
    "tape": "^5.0.1"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/teex.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/teex/issues"
  },
  "homepage": "https://github.com/mafintosh/teex"
}
const PassThroughDecoder = require('./lib/pass-through-decoder')
const UTF8Decoder = require('./lib/utf8-decoder')

module.exports = class TextDecoder {
  constructor(encoding = 'utf8') {
    this.encoding = normalizeEncoding(encoding)

    switch (this.encoding) {
      case 'utf8':
        this.decoder = new UTF8Decoder()
        break
      case 'utf16le':
      case 'base64':
        throw new Error('Unsupported encoding: ' + this.encoding)
      default:
        this.decoder = new PassThroughDecoder(this.encoding)
    }
  }

  get remaining() {
    return this.decoder.remaining
  }

  push(data) {
    if (typeof data === 'string') return data
    return this.decoder.decode(data)
  }

  // For Node.js compatibility
  write(data) {
    return this.push(data)
  }

  end(data) {
    let result = ''
    if (data) result = this.push(data)
    result += this.decoder.flush()
    return result
  }
}

function normalizeEncoding(encoding) {
  encoding = encoding.toLowerCase()

  switch (encoding) {
    case 'utf8':
    case 'utf-8':
      return 'utf8'
    case 'ucs2':
    case 'ucs-2':
    case 'utf16le':
    case 'utf-16le':
      return 'utf16le'
    case 'latin1':
    case 'binary':
      return 'latin1'
    case 'base64':
    case 'ascii':
    case 'hex':
      return encoding
    default:
      throw new Error('Unknown encoding: ' + encoding)
  }
}
const b4a = require('b4a')

module.exports = class PassThroughDecoder {
  constructor(encoding) {
    this.encoding = encoding
  }

  get remaining() {
    return 0
  }

  decode(data) {
    return b4a.toString(data, this.encoding)
  }

  flush() {
    return ''
  }
}
const b4a = require('b4a')

/**
 * https://encoding.spec.whatwg.org/#utf-8-decoder
 */
module.exports = class UTF8Decoder {
  constructor() {
    this._reset()
  }

  get remaining() {
    return this.bytesSeen
  }

  decode(data) {
    if (data.byteLength === 0) return ''

    if (this.bytesNeeded === 0 && trailingIncomplete(data, 0) === 0) {
      this.bytesSeen = trailingBytesSeen(data)
      return b4a.toString(data, 'utf8')
    }

    let result = ''
    let start = 0

    if (this.bytesNeeded > 0) {
      while (start < data.byteLength) {
        const byte = data[start]

        if (byte < this.lowerBoundary || byte > this.upperBoundary) {
          result += '\ufffd'
          this._reset()
          break
        }

        this.lowerBoundary = 0x80
        this.upperBoundary = 0xbf
        this.codePoint = (this.codePoint << 6) | (byte & 0x3f)
        this.bytesSeen++
        start++

        if (this.bytesSeen === this.bytesNeeded) {
          result += String.fromCodePoint(this.codePoint)
          this._reset()
          break
        }
      }

      if (this.bytesNeeded > 0) return result
    }

    const trailing = trailingIncomplete(data, start)
    const end = data.byteLength - trailing

    if (end > start) result += b4a.toString(data, 'utf8', start, end)

    for (let i = end; i < data.byteLength; i++) {
      const byte = data[i]

      if (this.bytesNeeded === 0) {
        if (byte <= 0x7f) {
          this.bytesSeen = 0
          result += String.fromCharCode(byte)
        } else if (byte >= 0xc2 && byte <= 0xdf) {
          this.bytesNeeded = 2
          this.bytesSeen = 1
          this.codePoint = byte & 0x1f
        } else if (byte >= 0xe0 && byte <= 0xef) {
          if (byte === 0xe0) this.lowerBoundary = 0xa0
          else if (byte === 0xed) this.upperBoundary = 0x9f
          this.bytesNeeded = 3
          this.bytesSeen = 1
          this.codePoint = byte & 0xf
        } else if (byte >= 0xf0 && byte <= 0xf4) {
          if (byte === 0xf0) this.lowerBoundary = 0x90
          else if (byte === 0xf4) this.upperBoundary = 0x8f
          this.bytesNeeded = 4
          this.bytesSeen = 1
          this.codePoint = byte & 0x7
        } else {
          this.bytesSeen = 1
          result += '\ufffd'
        }

        continue
      }

      if (byte < this.lowerBoundary || byte > this.upperBoundary) {
        result += '\ufffd'
        i--
        this._reset()

        continue
      }

      this.lowerBoundary = 0x80
      this.upperBoundary = 0xbf

      this.codePoint = (this.codePoint << 6) | (byte & 0x3f)
      this.bytesSeen++

      if (this.bytesSeen === this.bytesNeeded) {
        result += String.fromCodePoint(this.codePoint)
        this._reset()
      }
    }

    return result
  }

  flush() {
    const result = this.bytesNeeded > 0 ? '\ufffd' : ''
    this._reset()
    return result
  }

  _reset() {
    this.codePoint = 0
    this.bytesNeeded = 0
    this.bytesSeen = 0
    this.lowerBoundary = 0x80
    this.upperBoundary = 0xbf
  }
}

function trailingIncomplete(data, start) {
  const len = data.byteLength
  if (len <= start) return 0

  const limit = Math.max(start, len - 4)

  let i = len - 1
  while (i > limit && (data[i] & 0xc0) === 0x80) i--

  if (i < start) return 0

  const byte = data[i]

  let needed
  if (byte <= 0x7f) return 0
  if (byte >= 0xc2 && byte <= 0xdf) needed = 2
  else if (byte >= 0xe0 && byte <= 0xef) needed = 3
  else if (byte >= 0xf0 && byte <= 0xf4) needed = 4
  else return 0

  const available = len - i
  return available < needed ? available : 0
}

function trailingBytesSeen(data) {
  const len = data.byteLength
  if (len === 0) return 0

  const last = data[len - 1]

  if (last <= 0x7f) return 0
  if ((last & 0xc0) !== 0x80) return 1

  const limit = Math.max(0, len - 4)

  let i = len - 2
  while (i >= limit && (data[i] & 0xc0) === 0x80) i--

  if (i < 0) return 1

  const first = data[i]

  let needed
  if (first >= 0xc2 && first <= 0xdf) needed = 2
  else if (first >= 0xe0 && first <= 0xef) needed = 3
  else if (first >= 0xf0 && first <= 0xf4) needed = 4
  else return 1

  if (len - i !== needed) return 1

  if (needed >= 3) {
    const second = data[i + 1]
    if (first === 0xe0 && second < 0xa0) return 1
    if (first === 0xed && second > 0x9f) return 1
    if (first === 0xf0 && second < 0x90) return 1
    if (first === 0xf4 && second > 0x8f) return 1
  }

  return 0
}
{
  "name": "text-decoder",
  "version": "1.2.7",
  "description": "Streaming text decoder that preserves multibyte Unicode characters",
  "exports": {
    "./package": "./package.json",
    ".": "./index.js"
  },
  "files": [
    "index.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/text-decoder.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/text-decoder/issues"
  },
  "homepage": "https://github.com/holepunchto/text-decoder#readme",
  "dependencies": {
    "b4a": "^1.6.4"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  }
}
const b4a = require('b4a')

unslab.all = all
unslab.is = is

module.exports = unslab

function unslab (buf) {
  if (buf === null || buf.buffer.byteLength === buf.byteLength) return buf
  const copy = b4a.allocUnsafeSlow(buf.byteLength)
  copy.set(buf, 0)
  return copy
}

function is (buf) {
  return buf.buffer.byteLength !== buf.byteLength
}

function all (list) {
  let size = 0
  for (let i = 0; i < list.length; i++) {
    const buf = list[i]
    size += buf === null || buf.buffer.byteLength === buf.byteLength ? 0 : buf.byteLength
  }

  const copy = b4a.allocUnsafeSlow(size)
  const result = new Array(list.length)

  let offset = 0
  for (let i = 0; i < list.length; i++) {
    let buf = list[i]

    if (buf !== null && buf.buffer.byteLength !== buf.byteLength) {
      copy.set(buf, offset)
      buf = copy.subarray(offset, offset += buf.byteLength)
    }

    result[i] = buf
  }

  return result
}
{
  "name": "unslab",
  "version": "1.3.0",
  "description": "Unslab some slab'ed buffers",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.6.6"
  },
  "devDependencies": {
    "brittle": "^3.5.2",
    "standard": "^17.1.0"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/unslab.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/unslab/issues"
  },
  "homepage": "https://github.com/holepunchto/unslab"
}
module.exports = read

var MSB = 0x80
  , REST = 0x7F

function read(buf, offset) {
  var res    = 0
    , offset = offset || 0
    , shift  = 0
    , counter = offset
    , b
    , l = buf.length

  do {
    if (counter >= l) {
      read.bytes = 0
      throw new RangeError('Could not decode varint')
    }
    b = buf[counter++]
    res += shift < 28
      ? (b & REST) << shift
      : (b & REST) * Math.pow(2, shift)
    shift += 7
  } while (b >= MSB)

  read.bytes = counter - offset

  return res
}
module.exports = encode

var MSB = 0x80
  , REST = 0x7F
  , MSBALL = ~REST
  , INT = Math.pow(2, 31)

function encode(num, out, offset) {
  out = out || []
  offset = offset || 0
  var oldOffset = offset

  while(num >= INT) {
    out[offset++] = (num & 0xFF) | MSB
    num /= 128
  }
  while(num & MSBALL) {
    out[offset++] = (num & 0xFF) | MSB
    num >>>= 7
  }
  out[offset] = num | 0
  
  encode.bytes = offset - oldOffset + 1
  
  return out
}
module.exports = {
    encode: require('./encode.js')
  , decode: require('./decode.js')
  , encodingLength: require('./length.js')
}

var N1 = Math.pow(2,  7)
var N2 = Math.pow(2, 14)
var N3 = Math.pow(2, 21)
var N4 = Math.pow(2, 28)
var N5 = Math.pow(2, 35)
var N6 = Math.pow(2, 42)
var N7 = Math.pow(2, 49)
var N8 = Math.pow(2, 56)
var N9 = Math.pow(2, 63)

module.exports = function (value) {
  return (
    value < N1 ? 1
  : value < N2 ? 2
  : value < N3 ? 3
  : value < N4 ? 4
  : value < N5 ? 5
  : value < N6 ? 6
  : value < N7 ? 7
  : value < N8 ? 8
  : value < N9 ? 9
  :              10
  )
}
{
  "name": "varint",
  "version": "5.0.0",
  "description": "protobuf-style varint bytes - use msb to create integer values of varying sizes",
  "main": "index.js",
  "scripts": {
    "test": "node test.js"
  },
  "repository": {
    "type": "git",
    "url": "git://github.com/chrisdickinson/varint.git"
  },
  "keywords": [
    "varint",
    "protobuf",
    "encode",
    "decode"
  ],
  "author": "Chris Dickinson <chris@neversaw.us>",
  "license": "MIT",
  "devDependencies": {
    "tape": "~2.12.3"
  }
}
const { runtime, platform, arch, version } =
  typeof Bare !== 'undefined'
    ? {
        runtime: 'bare',
        platform: global.Bare.platform,
        arch: global.Bare.arch,
        version: global.Bare.version
      }
    : typeof process !== 'undefined'
      ? {
          runtime: 'node',
          platform: global.process.platform,
          arch: global.process.arch,
          version: global.process.version
        }
      : typeof Window !== 'undefined'
        ? { runtime: 'browser', platform: 'unknown', arch: 'unknown', version: 'unknown' }
        : { runtime: 'unknown', platform: 'unknown', arch: 'unknown', version: 'unknown' }

exports.runtime = runtime
exports.version = version
exports.platform = platform
exports.arch = arch
exports.isBare = runtime === 'bare'
exports.isBareKit = exports.isBare && typeof BareKit !== 'undefined'
exports.isPear = typeof Pear !== 'undefined'
exports.isNode = runtime === 'node'
exports.isBrowser = runtime === 'browser'
exports.isWindows = platform === 'win32'
exports.isLinux = platform === 'linux'
exports.isMac = platform === 'darwin'
exports.isIOS = platform === 'ios' || platform === 'ios-simulator'
exports.isAndroid = platform === 'android'
exports.isElectron = typeof process !== 'undefined' && !!global.process.versions?.electron
exports.isElectronRenderer = exports.isElectron && global.process.type === 'renderer'
exports.isElectronWorker = exports.isElectron && global.process.type === 'worker'
{
  "name": "which-runtime",
  "version": "1.4.0",
  "description": "Detect if you are in Bare or Node and which os etc",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte .",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/which-runtime.git"
  },
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/which-runtime/issues"
  },
  "homepage": "https://github.com/holepunchto/which-runtime",
  "devDependencies": {
    "brittle": "^3.0.0",
    "lunte": "^1.4.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
const b4a = require('b4a')

const ALPHABET = 'ybndrfg8ejkmcpqxot1uwisza345h769'
const MIN = 0x31 // 1
const MAX = 0x7a // z
const REVERSE = new Int8Array(1 + MAX - MIN)

REVERSE.fill(-1)

for (let i = 0; i < ALPHABET.length; i++) {
  const v = ALPHABET.charCodeAt(i) - MIN
  REVERSE[v] = i
}

exports.encode = encode
exports.decode = decode
exports.ALPHABET = ALPHABET

function decode (s, out) {
  let pb = 0
  let ps = 0

  const r = s.length & 7
  const q = (s.length - r) / 8

  if (!out) out = b4a.allocUnsafe(Math.ceil(s.length * 5 / 8))

  // 0 5 2 7 4 1 6 3 (+5 mod 8)
  for (let i = 0; i < q; i++) {
    const a = quintet(s, ps++)
    const b = quintet(s, ps++)
    const c = quintet(s, ps++)
    const d = quintet(s, ps++)
    const e = quintet(s, ps++)
    const f = quintet(s, ps++)
    const g = quintet(s, ps++)
    const h = quintet(s, ps++)

    out[pb++] = (a << 3) | (b >>> 2)
    out[pb++] = ((b & 0b11) << 6) | (c << 1) | (d >>> 4)
    out[pb++] = ((d & 0b1111) << 4) | (e >>> 1)
    out[pb++] = ((e & 0b1) << 7) | (f << 2) | (g >>> 3)
    out[pb++] = ((g & 0b111) << 5) | h
  }

  if (r === 0) return out.subarray(0, pb)

  const a = quintet(s, ps++)
  const b = quintet(s, ps++)

  out[pb++] = (a << 3) | (b >>> 2)

  if (r <= 2) return out.subarray(0, pb)

  const c = quintet(s, ps++)
  const d = quintet(s, ps++)

  out[pb++] = ((b & 0b11) << 6) | (c << 1) | (d >>> 4)

  if (r <= 4) return out.subarray(0, pb)

  const e = quintet(s, ps++)

  out[pb++] = ((d & 0b1111) << 4) | (e >>> 1)

  if (r <= 5) return out.subarray(0, pb)

  const f = quintet(s, ps++)
  const g = quintet(s, ps++)

  out[pb++] = ((e & 0b1) << 7) | (f << 2) | (g >>> 3)

  if (r <= 7) return out.subarray(0, pb)

  const h = quintet(s, ps++)

  out[pb++] = ((g & 0b111) << 5) | h

  return out.subarray(0, pb)
}

function encode (buf) {
  if (typeof buf === 'string') buf = b4a.from(buf)

  const max = buf.byteLength * 8

  let s = ''

  for (let p = 0; p < max; p += 5) {
    const i = p >>> 3
    const j = p & 7

    if (j <= 3) {
      s += ALPHABET[(buf[i] >>> (3 - j)) & 0b11111]
      continue
    }

    const of = j - 3
    const h = (buf[i] << of) & 0b11111
    const l = (i >= buf.byteLength ? 0 : buf[i + 1]) >>> (8 - of)

    s += ALPHABET[h | l]
  }

  return s
}

function quintet (s, i) {
  if (i > s.length) {
    return 0
  }

  const v = s.charCodeAt(i)

  if (v < MIN || v > MAX) {
    throw Error('Invalid character in base32 input: "' + s[i] + '" at position ' + i)
  }

  const bits = REVERSE[v - MIN]

  if (bits === -1) {
    throw Error('Invalid character in base32 input: "' + s[i] + '" at position ' + i)
  }

  return bits
}
{
  "name": "z32",
  "version": "1.1.0",
  "description": "Encode & decode z-base32",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.5.3"
  },
  "devDependencies": {
    "base-x": "^4.0.0",
    "base32": "0.0.7",
    "brittle": "^3.1.3",
    "nanobench": "^3.0.0",
    "rfc4648": "^1.5.2",
    "standard": "^17.0.0"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/z32.git"
  },
  "scripts": {
    "test": "standard && brittle test.js",
    "bench": "node benchmark.js"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/z32/issues"
  },
  "homepage": "https://github.com/mafintosh/z32"
}
{
  "name": "hyper-overlay",
  "version": "0.3.13",
  "description": "Content-addressed P2P file distribution over Protomux — FastCDC chunking, multi-source fetch, resumable transfers, zero blob duplication. Files live on disk; the overlay is a thin index and transfer protocol.",
  "type": "module",
  "main": "index.js",
  "imports": {
    "#fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "#path": {
      "bare": "bare-path",
      "default": "path"
    },
    "#os": {
      "bare": "bare-os",
      "default": "os"
    },
    "#zlib": {
      "bare": "bare-zlib",
      "default": "zlib"
    }
  },
  "exports": {
    ".": "./index.js",
    "./overlay": "./lib/overlay.js",
    "./protocol": "./lib/protocol.js",
    "./messages": "./lib/messages.js",
    "./chunker": "./lib/chunker.js",
    "./chunk-scheduler": "./lib/chunk-scheduler.js",
    "./transfer": "./lib/transfer.js",
    "./file-index": "./lib/file-index.js",
    "./sync-engine": "./lib/sync-engine.js",
    "./tree": "./lib/tree.js",
    "./pointer": "./lib/pointer.js",
    "./ignore": "./lib/ignore.js",
    "./manifest": "./lib/manifest.js",
    "./package.json": "./package.json"
  },
  "scripts": {
    "test": "brittle-bare test/*.test.js test/integration/*.test.js",
    "test:node": "brittle-node test/*.test.js"
  },
  "engines": {
    "bare": ">=1.16.0"
  },
  "license": "AGPL-3.0",
  "keywords": [
    "p2p",
    "hypercore",
    "hyperbee",
    "protomux",
    "overlay",
    "content-addressed",
    "deduplication",
    "file-transfer",
    "fastcdc",
    "chunking",
    "multi-source",
    "resumable",
    "bare"
  ],
  "dependencies": {
    "b4a": "^1.0.0",
    "bare-fs": "^4.7.2",
    "bare-os": "^3.8.7",
    "bare-path": "^3.0.0",
    "bare-zlib": "^1.3.3",
    "compact-encoding": "^3.2.0",
    "corestore": "^7.0.0",
    "hyperbee": "^2.0.0",
    "hypercore-crypto": "^3.0.0",
    "protomux": "^3.0.0",
    "ready-resource": "^1.0.0",
    "sodium-universal": "^5.0.1",
    "streamx": "^2.0.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "hyperswarm": "^4.0.0",
    "@hyperswarm/testnet": "^3.1.4"
  }
}
/**
 * hyper-svc — reusable per-app daemon library
 *
 * RPC transports: UDS, HTTP, and Hyperswarm (Protomux channel).
 * Replication: Hyperswarm topic join + corestore/autobase/mux replicate.
 */

export { Service } from './lib/service.js'
export { Client } from './lib/client.js'
export { encodeFrame, FrameDecoder } from './lib/frame.js'
export { attachRpcServer, attachRpcClient } from './lib/transports/swarm-rpc.js'
/**
 * Client — RPC client for hyper-svc daemons.
 *
 * Local-only. Connects via UDS (preferred) or HTTP. Both transports speak the
 * same JSON-RPC-ish protocol; the wire format differs (length-prefixed frames
 * for UDS, POST /rpc/<method> for HTTP) but the call signature is identical.
 *
 * Discovery: try UDS first (if a path is provided and the socket is reachable),
 * fall back to HTTP. Explicit transport selection is also supported.
 *
 * Usage:
 *
 *   const client = await Client.discover({
 *     uds: '/tmp/pear-git.sock',
 *     http: 'http://127.0.0.1:4040'
 *   })
 *
 *   const orgs = await client.call('list-orgs', { limit: 10 })
 *
 *   await client.close()
 */

import http from '#node:http'
import { URL } from '#node:url'
import b4a from 'b4a'
import { stat } from '#node:fs/promises'
import { udsBackend } from './uds-backend.js'
import Hyperswarm from 'hyperswarm'
import Protomux from 'protomux'
import crypto from 'hypercore-crypto'
import { encodeFrame, FrameDecoder } from './frame.js'
import { attachRpcClient } from './transports/swarm-rpc.js'

export class Client {
  /**
   * Discover and connect to a running hyper-svc daemon.
   *
   * @param {object} opts
   * @param {string} [opts.uds] - UDS socket path. Tried first.
   * @param {string} [opts.http] - HTTP base URL (e.g. 'http://127.0.0.1:4040'). Fallback.
   * @param {'uds'|'http'} [opts.prefer] - explicit override
   * @returns {Promise<Client>}
   */
  static async discover (opts = {}) {
    const prefer = opts.prefer

    if (prefer === 'uds') {
      if (!opts.uds) throw new Error('discover({ prefer: "uds" }) requires opts.uds')
      return Client.connectUds(opts.uds)
    }
    if (prefer === 'http') {
      if (!opts.http) throw new Error('discover({ prefer: "http" }) requires opts.http')
      return Client.connectHttp(opts.http)
    }

    // Auto: UDS first if reachable, then HTTP
    if (opts.uds) {
      const reachable = await udsReachable(opts.uds)
      if (reachable) return Client.connectUds(opts.uds)
    }
    if (opts.http) {
      return Client.connectHttp(opts.http)
    }

    const tried = []
    if (opts.uds) tried.push(`uds:${opts.uds}`)
    if (opts.http) tried.push(`http:${opts.http}`)
    throw new Error(`no daemon reachable (tried: ${tried.join(', ') || 'nothing — pass uds and/or http'})`)
  }

  static async connectUds (path) {
    const { backend, name } = await udsBackend(path)
    const sock = backend.createConnection(name)
    await new Promise((resolve, reject) => {
      sock.once('connect', () => {
        sock.removeListener('error', reject)
        resolve()
      })
      sock.once('error', reject)
    })
    return new Client({ kind: 'uds', sock })
  }

  static connectHttp (base) {
    return new Client({ kind: 'http', base: base.replace(/\/+$/, '') })
  }

  /**
   * Connect to a remote daemon via Hyperswarm. Joins the topic derived from
   * `serverKey`, waits for a connection, attaches a Protomux RPC channel, and
   * (when `opts.verify` is given) confirms the peer that answered is the one
   * that was asked for.
   *
   * ⚠ `serverKey` IS NOT AN IDENTITY — IT IS ONLY A RENDEZVOUS ADDRESS.
   *
   * The topic is `hash(serverKey + salt)`, and SwarmTransport.listen() creates
   * its Hyperswarm with NO keyPair, so a server's Noise key is random per
   * process and never equals the `serverKey` clients use to find it. Anything
   * joined to that topic as a server can therefore answer, and there is no
   * cryptographic binding to check `conn.remotePublicKey` against.
   *
   * That is not hypothetical. In a pear-git-v3 fleet, a mirror joins its
   * ORIGIN's topic (the topic travels in the deployment bundle), so it is a
   * server on the exact topic clients use to reach the origin. Measured
   * 2026-08-08: `connectSwarm({serverKey: <tabertron>})` issued ON stortron was
   * answered by STORTRON ITSELF 6 times out of 6. It asked itself for the
   * origin's release index, got its own, and every artifact fetch then failed
   * with "no holder" — a wrong ANSWER, not a transport error, so nothing looked
   * broken. resync-from-origin on the same path hung twice for 300 s.
   *
   * `opts.verify` closes that hole at the application layer, where identity
   * actually lives. It receives a connected Client and returns truthy to accept.
   * Rejected peers are destroyed and the wait continues until `timeout`, so a
   * caller reaches the intended daemon or fails loudly, never silently talks to
   * the wrong one. It is layered as a callback rather than a built-in `status`
   * check because hyper-svc is generic — which handler proves identity is the
   * consumer's business, and this stays compatible with servers of any version.
   *
   * @param {object} opts
   * @param {string|Buffer} opts.serverKey - rendezvous key; derives the topic
   * @param {string} [opts.topicSalt='pear-git-v3'] - salt for topic derivation
   * @param {object} [opts.swarm] - Hyperswarm constructor options (e.g. testnet bootstrap)
   * @param {number} [opts.timeout=30000] - total ms to find an ACCEPTED peer
   * @param {(client: Client) => Promise<boolean>} [opts.verify] - identity gate
   * @returns {Promise<Client>}
   */
  static async connectSwarm (opts = {}) {
    if (!opts.serverKey) throw new Error('connectSwarm requires opts.serverKey')
    const serverKey = typeof opts.serverKey === 'string'
      ? b4a.from(opts.serverKey, 'hex')
      : opts.serverKey
    const salt = opts.topicSalt || 'pear-git-v3'
    const topic = crypto.hash(b4a.concat([serverKey, b4a.from(salt)]))
    const timeout = opts.timeout || 30_000
    const verify = typeof opts.verify === 'function' ? opts.verify : null

    const swarm = new Hyperswarm(opts.swarm || {})
    const discovery = swarm.join(topic, { server: false, client: true })

    let rejected = 0
    let client = null
    try {
      client = await new Promise((resolve, reject) => {
        let settled = false
        // NOTE: onConnection stays attached for the swarm's whole life — it is
        // deliberately NOT removed here. Connections can still arrive after a
        // peer is accepted, and a NoiseSecretStream with no 'error' listener
        // throws on reset, so detaching left later arrivals unguarded and
        // crashed the process at teardown with ECONNRESET. The listener dies
        // with the swarm when the returned Client is closed.
        const finish = (fn, arg) => {
          if (settled) return
          settled = true
          clearTimeout(timer)
          fn(arg)
        }
        const timer = setTimeout(() => {
          finish(reject, new Error('swarm-rpc: connection timeout' +
            (rejected ? ' (' + rejected + ' peer(s) answered but failed verification — ' +
              'the requested serverKey is a topic, not an identity, so other peers on ' +
              'that topic can answer)' : '')))
        }, timeout)

        const onConnection = (c) => {
          // Routine, and load-bearing: a NoiseSecretStream with no 'error'
          // listener throws on ECONNRESET, and this path DESTROYS connections
          // by design (every peer that fails verification, plus any that arrive
          // after one is accepted). Without this the first rejected peer takes
          // the whole process down. SwarmTransport._onConnection takes the same
          // posture server-side.
          c.on('error', () => {})
          if (settled) { try { c.destroy() } catch {} ; return }
          const candidate = new Client({
            kind: 'swarm',
            swarm,
            conn: c,
            rpc: attachRpcClient(Protomux.from(c))
          })
          if (!verify) return finish(resolve, candidate)

          // Verified off the critical path: keep listening while this runs, so a
          // slow or lying peer cannot stall a good one behind it.
          Promise.resolve()
            .then(() => verify(candidate))
            .then((ok) => {
              if (ok) return finish(resolve, candidate)
              rejected++
              try { c.destroy() } catch {}
            })
            .catch(() => {
              rejected++
              try { c.destroy() } catch {}
            })
        }

        swarm.on('connection', onConnection)
        discovery.flushed().catch((err) => finish(reject, err))
      })
    } catch (err) {
      // Destroy the swarm on EVERY failure path. It used to be left running: a
      // Hyperswarm holds the event loop open, so each failed connect leaked one
      // and the process never exited. That is what hung pear-git-v3's
      // basic.test.js when a mirror's origin was unreachable — 123/123 tests
      // passed, then the run never terminated.
      try { await swarm.destroy() } catch {}
      throw err
    }

    return client
  }

  constructor (opts) {
    this._kind = opts.kind
    this._sock = opts.sock || null
    this._base = opts.base || null
    this._swarm = opts.swarm || null
    this._conn = opts.conn || null
    this._rpc = opts.rpc || null
    this._closed = false

    // UDS pending request map (id → {resolve, reject})
    this._pending = new Map()
    this._nextId = 1

    if (this._kind === 'uds') {
      this._decoder = new FrameDecoder((frame) => this._onFrame(frame))
      this._sock.on('data', (chunk) => {
        try {
          this._decoder.push(chunk)
        } catch (err) {
          this._failAll(err)
          this._down()
        }
      })
      // EVENT-DRIVEN disconnect detection (fleet reconciliation contract). When the peer daemon
      // restarts (the common case: an OTA/`pgh app restart` of hpp/pgv3/etc.), the cached client's
      // socket dies. Previously 'close' only `_failAll`'d the pending map but NEVER set `_closed`,
      // and there was no 'end' handler at all — so `client.closed` stayed FALSE and long-lived
      // consumers (favela-web Writer, pgh sidecar lookups) kept handing back a DEAD client, whose
      // calls hang or reject "connection closed" forever with nothing to trigger a reconnect. Mark
      // the client CLOSED on close/end/error so `.closed` is truthy → consumers reconcile (reconnect
      // a fresh Client) on their next call. 'end' is load-bearing under bare-net (allowHalfOpen: on
      // peer-end it fires 'end' but not 'close'), so we destroy to force teardown — same posture as
      // the server-side half-open fix (hyper-svc 0.1.3).
      this._sock.on('close', () => this._down())
      this._sock.on('end', () => this._down())
      this._sock.on('error', () => this._down())
    }
  }

  get kind () { return this._kind }
  get closed () { return this._closed }

  /**
   * Make an RPC call. Throws on transport errors or remote handler errors.
   * @param {string} method
   * @param {any} [params]
   */
  async call (method, params = {}) {
    if (this._closed) throw new Error('client closed')

    if (this._kind === 'uds') return this._callUds(method, params)
    if (this._kind === 'http') return this._callHttp(method, params)
    if (this._kind === 'swarm') return this._rpc.call(method, params)
    throw new Error('unknown client kind: ' + this._kind)
  }

  _callUds (method, params) {
    const id = this._nextId++
    return new Promise((resolve, reject) => {
      this._pending.set(id, { resolve, reject })
      try {
        this._sock.write(encodeFrame({ id, method, params }))
      } catch (err) {
        this._pending.delete(id)
        reject(err)
      }
    })
  }

  _onFrame (frame) {
    if (frame == null || (typeof frame.id !== 'number' && typeof frame.id !== 'string')) {
      // Malformed response, can't match it to a caller
      return
    }
    const pending = this._pending.get(frame.id)
    if (!pending) return
    this._pending.delete(frame.id)

    if (frame.error) {
      pending.reject(new Error(frame.error))
    } else {
      pending.resolve(frame.result)
    }
  }

  _failAll (err) {
    for (const [, pending] of this._pending) pending.reject(err)
    this._pending.clear()
  }

  // The socket died (peer restarted / errored / half-open end). Mark the client CLOSED so any
  // consumer's `.closed` check reconnects, fail every in-flight call, and force teardown. Idempotent.
  _down () {
    if (this._closed) return
    this._closed = true
    this._failAll(new Error('connection closed'))
    if (this._sock) { try { this._sock.destroy() } catch {} }
  }

  async _callHttp (method, params) {
    const url = new URL(`${this._base}/rpc/${encodeURIComponent(method)}`)
    return new Promise((resolve, reject) => {
      const body = JSON.stringify(params)
      const req = http.request({
        method: 'POST',
        hostname: url.hostname,
        port: url.port || 80,
        path: url.pathname + url.search,
        headers: {
          'Content-Type': 'application/json',
          'Content-Length': b4a.byteLength(body)
        }
      }, (res) => {
        const parts = []
        res.on('data', (c) => parts.push(c))
        res.on('end', () => {
          const text = b4a.concat(parts).toString('utf8')
          let parsed
          try {
            parsed = JSON.parse(text)
          } catch {
            return reject(new Error(`bad JSON response (status ${res.statusCode}): ${text.slice(0, 200)}`))
          }
          if (res.statusCode >= 200 && res.statusCode < 300) {
            return resolve(parsed.result)
          }
          return reject(new Error(parsed.error || `HTTP ${res.statusCode}`))
        })
        res.on('error', reject)
      })
      req.on('error', reject)
      req.write(body)
      req.end()
    })
  }

  async close () {
    if (this._closed) return
    this._closed = true
    if (this._sock) {
      this._failAll(new Error('client closed'))
      try { this._sock.destroy() } catch {}
      this._sock = null
    }
    if (this._rpc) {
      try { this._rpc.close() } catch {}
      this._rpc = null
    }
    if (this._conn) {
      try { this._conn.destroy() } catch {}
      this._conn = null
    }
    if (this._swarm) {
      try { await this._swarm.destroy() } catch {}
      this._swarm = null
    }
  }
}

async function udsReachable (path) {
  const { backend, name, abstract } = await udsBackend(path)
  // Pathname sockets: verify the file exists and is actually a socket first.
  // Abstract sockets have no filesystem entry — skip straight to the connect probe.
  if (!abstract) {
    try {
      const s = await stat(path)
      if (!s.isSocket()) return false
    } catch {
      return false
    }
  }
  // Try a real connect — covers stale sockets where the daemon crashed
  return new Promise((resolve) => {
    const sock = backend.createConnection(name)
    sock.once('connect', () => {
      sock.destroy()
      resolve(true)
    })
    sock.once('error', () => {
      sock.destroy()
      resolve(false)
    })
  })
}
/**
 * Length-prefixed JSON framing.
 *
 * Wire format: [4 bytes BE length][JSON payload].
 *
 * One frame = one JSON object. Multiple frames can be pipelined on a single
 * stream — FrameDecoder handles incremental reads where a frame may arrive
 * across multiple data chunks.
 */

import b4a from 'b4a'

const MAX_FRAME = 16 * 1024 * 1024 // 16 MiB hard cap to avoid runaway buffers

export function encodeFrame (obj) {
  const json = JSON.stringify(obj)
  const payload = b4a.from(json, 'utf8')
  if (payload.length > MAX_FRAME) {
    throw new Error(`Frame too large: ${payload.length} > ${MAX_FRAME}`)
  }
  const frame = b4a.alloc(4 + payload.length)
  frame.writeUInt32BE(payload.length, 0)
  payload.copy(frame, 4)
  return frame
}

export class FrameDecoder {
  /**
   * @param {(obj: any) => void} onFrame - called once per complete frame
   */
  constructor (onFrame) {
    if (typeof onFrame !== 'function') throw new Error('onFrame is required')
    this._onFrame = onFrame
    this._buf = b4a.alloc(0)
  }

  /**
   * Feed a chunk into the decoder. Calls onFrame for each complete frame.
   * Throws if a frame exceeds MAX_FRAME or contains invalid JSON.
   */
  push (chunk) {
    this._buf = b4a.concat([this._buf, chunk])

    while (this._buf.length >= 4) {
      const len = this._buf.readUInt32BE(0)
      if (len > MAX_FRAME) {
        throw new Error(`Frame too large: ${len} > ${MAX_FRAME}`)
      }
      if (this._buf.length < 4 + len) break // wait for more bytes

      const payload = this._buf.subarray(4, 4 + len)
      this._buf = this._buf.subarray(4 + len)

      const json = b4a.toString(payload, 'utf8')
      const obj = JSON.parse(json) // throws on bad JSON
      this._onFrame(obj)
    }
  }

  /** Number of bytes currently buffered (waiting for the rest of a frame). */
  get pending () { return this._buf.length }
}
/**
 * Service — reusable per-app daemon library.
 *
 * One instance per app process. Owns:
 *   - Generic RPC handler registry (svc.handle)
 *   - Module mounts (svc.mount) with optional swarm replication
 *   - UDS, HTTP, and Hyperswarm transport instances (whichever the consumer enables)
 *
 * The consumer's corestore is passed in (or one is implied via swarm.corestore).
 * The Service does NOT create or own storage — that's the app's job.
 *
 * Local-only RPC. Peers exchange data via swarm replication, never commands.
 *
 * Usage:
 *
 *   const svc = new Service({
 *     name: 'pear-git',
 *     corestore: store,
 *     uds: '/tmp/pear-git.sock',
 *     http: { port: 4040 },
 *     swarm: { topic: '...32 bytes hex...' }
 *   })
 *
 *   svc.mount('orgs', new HyperOrgs(store, { namespace: 'orgs' }))
 *
 *   svc.handle('list-orgs', async (ctx, params) => {
 *     return svc.modules.orgs.list()
 *   })
 *
 *   await svc.listen()
 */

import process from '#node:process'
import ReadyResource from 'ready-resource'
import { UdsServer } from './transports/uds.js'
import { HttpServer } from './transports/http.js'
import { SwarmTransport } from './transports/swarm.js'

class NoSuchMethodError extends Error {
  constructor (method) {
    super(`unknown method: ${method}`)
    this.code = 'ENOMETHOD'
  }
}

class AnonymousDeniedError extends Error {
  constructor (method) {
    super(`anonymous access denied: ${method}`)
    this.code = 'EDENIED'
    this.status = 403
  }
}

/**
 * Default "is this caller anonymous?" predicate.
 *
 * Deliberately conservative — anything that is not clearly an authenticated
 * caller counts as anonymous. Consumers whose ctx carries richer identity
 * (pear-git-v3 has four distinct shapes) should pass their own via
 * opts.isAnonymous rather than widen this one.
 */
function defaultIsAnonymous (ctx) {
  if (!ctx) return true
  if (ctx.transport === 'uds') return false // local operator holds the socket
  return !ctx.identity
}

export class Service extends ReadyResource {
  /**
   * @param {object} opts
   * @param {string} opts.name - service name (used for default UDS path, logging)
   * @param {object} [opts.corestore] - required if swarm transport is enabled
   * @param {string} [opts.uds] - UDS socket path. Pass null/undefined to disable.
   * @param {object} [opts.http] - HTTP transport options { port, host }. Disable by omitting.
   * @param {object} [opts.swarm] - Swarm options { topic, swarm? }. Disable by omitting.
   */
  constructor (opts = {}) {
    super()
    if (!opts.name) throw new Error('Service requires opts.name')

    this._name = opts.name
    this._corestore = opts.corestore || null
    this._handlers = new Map()
    this._mounts = new Map()

    // Anonymous-dispatch policy (pear-git org #12).
    //
    // Every registered handler used to be callable by anyone, over HTTP and
    // over swarm-rpc, with no allowlist and no auth gate — so each new
    // svc.handle() was silently world-callable, and a daemon behind a public
    // reverse proxy exposed its entire RPC surface to the internet.
    //
    // Default stays 'allow' so the existing consumers (pear-git-v3, hypernote,
    // hyper-social-web, pgh-sidecar) are untouched until they opt in. Under
    // 'deny', a handler must declare `{ anonymous: true }` at registration to
    // be reachable by an unauthenticated caller.
    //
    // Opt-in at REGISTRATION rather than via a separate allowlist table: with
    // ~100 handlers a table drifts out of step with the handler set, whereas a
    // flag cannot. And the drift direction is safe — a handler nobody marked
    // is DENIED, which surfaces as a visible 403 rather than a silent hole.
    this._anonymousPolicy = opts.anonymousPolicy === 'deny' ? 'deny' : 'allow'
    this._isAnonymous = typeof opts.isAnonymous === 'function'
      ? opts.isAnonymous
      : defaultIsAnonymous
    // Called with ({ method, ctx }) whenever a dispatch is refused, so the
    // consumer can record denials alongside its own audit trail.
    this._onDeny = typeof opts.onDeny === 'function' ? opts.onDeny : null
    this._anonymousAllowed = new Set()

    this._udsOpt = opts.uds || null
    this._httpOpt = opts.http || null
    this._swarmOpt = opts.swarm || null

    this._uds = null
    this._http = null
    this._swarm = null

    if (this._swarmOpt && !this._corestore) {
      throw new Error('Service: swarm transport requires opts.corestore')
    }

    // Instantiate transports eagerly so apps can register HTTP routes,
    // grab the UDS path, etc., BEFORE calling listen().
    const dispatch = (method, params, ctx) => this.dispatch(method, params, ctx)

    if (this._udsOpt) {
      this._uds = new UdsServer({ path: this._udsOpt, dispatch })
    }
    if (this._httpOpt) {
      this._http = new HttpServer({
        port: this._httpOpt.port,
        host: this._httpOpt.host,
        prefix: this._httpOpt.prefix,
        ctxFactory: this._httpOpt.ctxFactory,
        dispatch
      })
    }
    if (this._swarmOpt) {
      this._swarm = new SwarmTransport({
        topic: this._swarmOpt.topic,
        corestore: this._corestore,
        mounts: () => this._listMounts(),
        dispatch: this._swarmOpt.rpc !== false ? dispatch : null,
        swarm: this._swarmOpt.swarm,
        server: this._swarmOpt.server,
        client: this._swarmOpt.client
      })
    }
  }

  // ── Properties ──────────────────────────────────────────────

  get name () { return this._name }
  get corestore () { return this._corestore }

  /** Read-only handle to the UDS transport (or null if disabled). */
  get uds () { return this._uds }

  /** Read-only handle to the HTTP transport (or null if disabled). */
  get http () { return this._http }

  /** Read-only handle to the swarm transport (or null if disabled). */
  get swarm () { return this._swarm }

  /**
   * Mounted modules, accessible by name. Use `svc.modules.orgs` after
   * `svc.mount('orgs', orgsInstance)`.
   */
  get modules () {
    // Lazily build a property-style accessor object on top of the map
    if (!this._modulesProxy) {
      const map = this._mounts
      this._modulesProxy = new Proxy({}, {
        get (_target, prop) {
          const m = map.get(prop)
          return m ? m.instance : undefined
        },
        has (_target, prop) {
          return map.has(prop)
        },
        ownKeys () {
          return Array.from(map.keys())
        },
        getOwnPropertyDescriptor (_target, prop) {
          if (map.has(prop)) {
            return { enumerable: true, configurable: true, value: map.get(prop).instance }
          }
        }
      })
    }
    return this._modulesProxy
  }

  /** Map iteration: list mount entries as { name, instance }. */
  _listMounts () {
    const out = []
    for (const [name, m] of this._mounts) out.push({ name, instance: m.instance })
    return out
  }

  // ── Registration ────────────────────────────────────────────

  /**
   * Register an RPC handler. The handler is invoked from any RPC transport
   * with `(ctx, params)` and should return a JSON-serializable result.
   *
   * @param {string} name - method name (e.g. "list-orgs")
   * @param {(ctx: object, params: any) => Promise<any>|any} fn
   */
  handle (name, fn, opts = {}) {
    if (typeof name !== 'string' || !name) throw new Error('handle requires a name')
    if (typeof fn !== 'function') throw new Error('handle requires a function')
    if (this._handlers.has(name)) throw new Error(`handler "${name}" already registered`)
    this._handlers.set(name, fn)
    // `anonymous: true` opts this method IN to unauthenticated dispatch when
    // the service runs anonymousPolicy: 'deny'. Absent = denied, which is the
    // safe default for a handler nobody has classified yet.
    if (opts && opts.anonymous === true) this._anonymousAllowed.add(name)
  }

  /** Is this method callable by an unauthenticated caller? */
  allowsAnonymous (name) { return this._anonymousAllowed.has(name) }

  /** Methods explicitly opted in to anonymous dispatch, sorted. */
  listAnonymous () { return Array.from(this._anonymousAllowed).sort() }

  /** Whether a handler is registered. */
  hasHandler (name) { return this._handlers.has(name) }

  /** List registered handler names. */
  listHandlers () { return Array.from(this._handlers.keys()).sort() }

  /**
   * Mount a module instance. Modules are accessible via `svc.modules.<name>`.
   * If the module exposes a `.base` (Autobase consumer) and the swarm
   * transport is enabled, the base is replicated on every swarm connection.
   *
   * @param {string} name
   * @param {object} instance
   */
  mount (name, instance) {
    if (typeof name !== 'string' || !name) throw new Error('mount requires a name')
    if (!instance) throw new Error('mount requires an instance')
    if (this._mounts.has(name)) throw new Error(`mount "${name}" already registered`)
    this._mounts.set(name, { instance })
  }

  /** Whether a module is mounted. */
  hasMount (name) { return this._mounts.has(name) }

  /** List mounted module names. */
  listMounts () { return Array.from(this._mounts.keys()).sort() }

  // ── Dispatch ────────────────────────────────────────────────

  /**
   * Dispatch a method call to its handler. Used by all RPC transports.
   * Throws NoSuchMethodError (code: 'ENOMETHOD') if the method isn't registered.
   */
  async dispatch (method, params, ctx) {
    const handler = this._handlers.get(method)
    if (!handler) throw new NoSuchMethodError(method)

    // Anonymous gate (#12). Runs for EVERY transport, because the surface was
    // open on all of them — HTTP via a public reverse proxy, and swarm-rpc to
    // any peer that knows the topic.
    //
    // Ordered after the ENOMETHOD check on purpose: an unknown method should
    // still say so, otherwise the gate turns every typo into a 403 and makes
    // the API undebuggable. It leaks only which method names exist, which the
    // handler list already exposes.
    if (this._anonymousPolicy === 'deny' && !this._anonymousAllowed.has(method)) {
      let anon = true
      try {
        anon = this._isAnonymous(ctx)
      } catch {
        anon = true // a predicate that throws must fail CLOSED
      }
      if (anon) {
        if (this._onDeny) {
          try { this._onDeny({ method, ctx, reason: 'anonymous' }) } catch {}
        }
        throw new AnonymousDeniedError(method)
      }
    }

    return handler(ctx || {}, params)
  }

  // ── Lifecycle ───────────────────────────────────────────────

  async _open () {
    if (this._uds) await this._uds.listen()
    if (this._http) await this._http.listen()
    if (this._swarm) await this._swarm.listen()
  }

  /**
   * Alias for `ready()` — feels more natural for a daemon ("start listening").
   */
  async listen () {
    await this.ready()
  }

  async _close () {
    const errors = []
    if (this._swarm) try { await this._swarm.close() } catch (e) { errors.push(e) }
    if (this._http) try { await this._http.close() } catch (e) { errors.push(e) }
    if (this._uds) try { await this._uds.close() } catch (e) { errors.push(e) }
    this._swarm = null
    this._http = null
    this._uds = null
    if (errors.length) {
      const msg = errors.map(e => e.message).join('; ')
      throw new Error('Service close errors: ' + msg)
    }
  }
}
/**
 * HTTP transport for hyper-svc.
 *
 * Local-only RPC. Browsers (or curl, or any HTTP client) on the same machine
 * POST a JSON body to /rpc/<method> and receive a JSON response.
 *
 * Wire protocol:
 *   POST /rpc/<method>
 *   Content-Type: application/json
 *   { ...params... }
 *
 *   →  200 application/json  { result: ... }
 *      400 application/json  { error: ... }   (bad request / handler threw)
 *      404 application/json  { error: 'unknown method' }
 *
 * Other routes are NOT handled by hyper-svc — apps wire their own SSR pages
 * via the underlying http.Server (exposed as `.server` on this class). Any
 * request not matching POST /rpc/<method> falls through to user-registered
 * 'request' listeners or, if none, returns 404.
 */

import http from '#node:http'
import b4a from 'b4a'

export class HttpServer {
  /**
   * @param {object} opts
   * @param {number} [opts.port=0] - 0 = random port
   * @param {string} [opts.host='127.0.0.1'] - bind address (local-only by default)
   * @param {string} [opts.prefix=''] - URL prefix to strip before matching /rpc/* (e.g. '/git')
   * @param {(method: string, params: any, ctx: object) => Promise<any>} opts.dispatch - request handler
   */
  constructor (opts = {}) {
    if (typeof opts.dispatch !== 'function') throw new Error('HttpServer requires opts.dispatch')

    this._port = opts.port || 0
    this._host = opts.host || '127.0.0.1'
    this._dispatch = opts.dispatch
    // Optional URL prefix (e.g. '/git') stripped before matching /rpc/*. Set
    // when the daemon is reverse-proxied OR accessed directly under a path
    // prefix that the browser bakes into outgoing fetch URLs. Without this,
    // direct (non-proxied) hits to `<host>/<prefix>/rpc/*` fall through both
    // hyper-svc's listener (which only matches '/rpc/') and the consumer's
    // listener (which strips the prefix and skips '/rpc/' assuming hyper-svc
    // already handled it) — neither responds and the request hangs.
    this._prefix = normalizePrefix(opts.prefix)
    // Optional consumer-provided ctx builder. Called per /rpc/* request to
    // populate fields like identity from request headers/cookies. Receives
    // (req) and may return either an object or a Promise<object>. The
    // returned fields are merged into the default ctx ({ transport: 'http',
    // identity: null, req, res }).
    this._ctxFactory = typeof opts.ctxFactory === 'function' ? opts.ctxFactory : null
    this._listening = false

    // Create the server eagerly so apps can register routes BEFORE listen().
    // Our /rpc/* listener is installed first so it has first dibs on requests.
    this._server = http.createServer()
    this._server.on('request', (req, res) => this._onRequest(req, res))
  }

  /**
   * Update or set the ctxFactory after construction. Useful when the
   * factory needs references that don't exist at constructor time
   * (e.g. session stores created by the consumer in a later step).
   */
  setCtxFactory (fn) {
    if (fn != null && typeof fn !== 'function') {
      throw new Error('ctxFactory must be a function or null')
    }
    this._ctxFactory = fn
  }

  /** Underlying http.Server. Apps register their own routes here. */
  get server () { return this._server }
  get listening () { return this._listening }
  get port () {
    if (!this._listening || !this._server) return null
    const addr = this._server.address()
    return addr ? addr.port : null
  }
  get host () { return this._host }

  async listen () {
    if (this._listening) return

    await new Promise((resolve, reject) => {
      this._server.once('error', reject)
      this._server.listen(this._port, this._host, () => {
        this._server.removeListener('error', reject)
        resolve()
      })
    })

    this._listening = true
  }

  async _onRequest (req, res) {
    // Compute the path with the configured prefix removed. Don't mutate
    // req.url — consumers' own request listeners may have their own
    // prefix-stripping logic and should see the original.
    let path = req.url
    if (this._prefix && path.startsWith(this._prefix)) {
      const rest = path.slice(this._prefix.length)
      // Only treat as a prefix match when the next char is '/' (or end of
      // URL). Otherwise '/gitfoo' would falsely match prefix '/git'.
      if (rest === '' || rest[0] === '/' || rest[0] === '?') {
        path = rest || '/'
      }
    }

    if (req.method === 'POST' && path.startsWith('/rpc/')) {
      const method = path.slice('/rpc/'.length).split('?')[0]
      let body
      try {
        body = await collectBody(req)
      } catch (err) {
        return jsonError(res, 400, 'failed to read body: ' + err.message)
      }

      let params = {}
      if (body.length > 0) {
        try {
          params = JSON.parse(b4a.toString(body, 'utf8'))
        } catch {
          return jsonError(res, 400, 'request body must be JSON')
        }
      }

      let ctx = {
        transport: 'http',
        identity: null, // anonymous by default — apps populate via ctxFactory
        req,
        res
      }

      if (this._ctxFactory) {
        try {
          const extra = await this._ctxFactory(req)
          if (extra && typeof extra === 'object') {
            ctx = { ...ctx, ...extra }
          }
        } catch (err) {
          return jsonError(res, 500, 'ctxFactory failed: ' + (err.message || String(err)))
        }
      }

      try {
        const result = await this._dispatch(method, params, ctx)
        if (result === undefined) {
          return jsonOk(res, { result: null })
        }
        return jsonOk(res, { result })
      } catch (err) {
        if (err && err.code === 'ENOMETHOD') {
          return jsonError(res, 404, err.message)
        }
        // An anonymous-gate denial is an authorization outcome, not a bad
        // request — surface it as 403 so callers (and the audit trail) can
        // tell "you may not" from "you sent nonsense".
        if (err && err.code === 'EDENIED') {
          return jsonError(res, err.status || 403, err.message)
        }
        return jsonError(res, 400, err.message || String(err))
      }
    }

    // Not an /rpc/ request. App-owned routes live in OTHER 'request'
    // listeners (registered on this._server by the consumer). If at least
    // one other listener is present, leave the response to them — they're
    // responsible for handling and 404-ing as needed.
    //
    // If we're the ONLY 'request' listener, nobody else will handle this,
    // so we 404 it synchronously. Doing this synchronously avoids a race
    // where setImmediate fires before an async user handler can respond.
    if (this._server.listenerCount('request') <= 1) {
      res.writeHead(404, { 'Content-Type': 'text/plain' })
      res.end('Not found')
    }
    // Otherwise: leave the response to the user's listener.
  }

  async close () {
    if (!this._server || !this._listening) {
      this._listening = false
      return
    }
    await new Promise((resolve) => this._server.close(() => resolve()))
    this._listening = false
  }
}

function collectBody (req) {
  return new Promise((resolve, reject) => {
    const parts = []
    req.on('data', (c) => parts.push(c))
    req.on('end', () => resolve(b4a.concat(parts)))
    req.on('error', reject)
  })
}

function jsonOk (res, body) {
  res.writeHead(200, { 'Content-Type': 'application/json' })
  res.end(JSON.stringify(body))
}

function jsonError (res, status, message) {
  res.writeHead(status, { 'Content-Type': 'application/json' })
  res.end(JSON.stringify({ error: message }))
}

function normalizePrefix (p) {
  if (!p || typeof p !== 'string') return ''
  // Strip trailing slashes so '/git/' and '/git' behave identically.
  let s = p.replace(/\/+$/, '')
  // A bare '/' is not a real prefix.
  if (s === '' || s === '/') return ''
  // Require a leading slash so callers can't accidentally pass 'git'.
  if (s[0] !== '/') s = '/' + s
  return s
}
/**
 * Swarm-RPC transport for hyper-svc.
 *
 * Adds a Protomux RPC channel on every Hyperswarm connection. Requests
 * and responses use the same length-prefixed JSON framing as UDS (see
 * frame.js), multiplexed over the Noise-encrypted swarm stream.
 *
 * This transport extends the existing SwarmTransport (replication) with
 * request/response dispatch. A single swarm connection carries:
 *   1. Hypercore/Autobase replication (corestore.replicate)
 *   2. Module mux channels (attachProtocol)
 *   3. RPC frames (this module)
 *
 * Wire protocol over Protomux:
 *   Channel: 'hyper-svc-rpc'
 *   Message type 0 (request):  { id, method, params }
 *   Message type 1 (response): { id, result } | { id, error }
 *
 * Auth: the caller's Noise public key is available on the connection.
 * For pear-git-v3, envelope auth (Phase 2a) is layered on top — the
 * RPC payload itself is a signed envelope, verified by the dispatch
 * handler. The transport just provides the Noise tunnel.
 */

import Protomux from 'protomux'
import c from 'compact-encoding'
import b4a from 'b4a'

const PROTOCOL = 'hyper-svc-rpc'

/**
 * Attach an RPC channel to a Protomux instance (one per swarm connection).
 *
 * Server-side: receives requests, calls dispatch, sends responses.
 *
 * @param {Protomux} mux — the protomux for this connection
 * @param {Function} dispatch — (method, params, ctx) => result
 * @param {object} [opts]
 * @param {Buffer} [opts.remotePublicKey] — peer's Noise pubkey (for ctx)
 * @returns {{ channel, close: () => void }}
 */
export function attachRpcServer (mux, dispatch, opts = {}) {
  const channel = mux.createChannel({
    protocol: PROTOCOL,
    onopen () {},
    onclose () {}
  })

  if (!channel) return null // protocol already claimed on this mux

  const requestType = channel.addMessage({
    encoding: c.json,
    onmessage (msg) {
      handleRequest(msg, channel, responseType, dispatch, opts)
    }
  })

  const responseType = channel.addMessage({
    encoding: c.json,
    onmessage () {} // server doesn't receive responses
  })

  channel.open()

  return { channel, close: () => channel.close() }
}

/**
 * Attach an RPC channel to a Protomux instance (client-side).
 *
 * Client-side: sends requests, receives responses.
 *
 * @param {Protomux} mux
 * @returns {{ call: (method, params) => Promise<any>, close: () => void }}
 */
export function attachRpcClient (mux) {
  let nextId = 1
  const pending = new Map() // id → { resolve, reject }

  const channel = mux.createChannel({
    protocol: PROTOCOL,
    onopen () {},
    onclose () {
      // Reject all pending calls on channel close.
      for (const [id, p] of pending) {
        p.reject(new Error('swarm-rpc channel closed'))
        pending.delete(id)
      }
    }
  })

  if (!channel) throw new Error('swarm-rpc: protocol already claimed')

  const requestType = channel.addMessage({
    encoding: c.json,
    onmessage () {} // client doesn't receive requests
  })

  const responseType = channel.addMessage({
    encoding: c.json,
    onmessage (msg) {
      const p = pending.get(msg.id)
      if (!p) return // stale or unknown id
      pending.delete(msg.id)
      if (msg.error) {
        const err = new Error(msg.error)
        err.code = msg.code || null
        p.reject(err)
      } else {
        p.resolve(msg.result)
      }
    }
  })

  channel.open()

  return {
    call (method, params) {
      return new Promise((resolve, reject) => {
        const id = nextId++
        pending.set(id, { resolve, reject })
        requestType.send({ id, method, params })
      })
    },
    close () {
      channel.close()
    }
  }
}

// --- internals ---

async function handleRequest (msg, channel, responseType, dispatch, opts) {
  const { id, method, params } = msg
  if (!id || !method) {
    responseType.send({ id: id || 0, error: 'invalid request (missing id or method)' })
    return
  }

  const ctx = {
    transport: 'swarm-rpc',
    identity: {
      type: 'swarm',
      remotePublicKey: opts.remotePublicKey
        ? b4a.toString(opts.remotePublicKey, 'hex')
        : null,
      trust: 'network'
    }
  }

  try {
    const result = await dispatch(method, params || {}, ctx)
    responseType.send({ id, result: result !== undefined ? result : null })
  } catch (err) {
    responseType.send({
      id,
      error: err.message || String(err),
      code: err.code || null
    })
  }
}
/**
 * Hyperswarm transport for hyper-svc.
 *
 * Joins a topic, and on every connection:
 *   1. corestore.replicate(conn) — replicates all hypercores in the corestore
 *   2. for each mounted module exposing a `.base` (Autobase consumer), also
 *      base.replicate(conn) — belt-and-suspenders against the autobase
 *      replication gotcha (corestore.replicate alone is unreliable in tests
 *      and we don't want to chase that bug in production)
 *   3. for each mounted module exposing `attachProtocol(mux)` (mux-based
 *      protocols like hyper-overlay), lazily build `Protomux.from(conn)`
 *      once per connection and call attachProtocol on each consumer.
 *      Protomux.from reuses any protomux already attached by corestore/autobase
 *      replication, so channels multiplex cleanly over the same transport.
 *
 * No RPC over swarm today — modules communicate either via replication or
 * via their own mux channels. Adding a new mux-based protocol only requires
 * exposing `attachProtocol(mux)` on the mounted module.
 */

import Hyperswarm from 'hyperswarm'
import Protomux from 'protomux'
import b4a from 'b4a'
import { attachRpcServer } from './swarm-rpc.js'

export class SwarmTransport {
  /**
   * @param {object} opts
   * @param {Buffer|string} opts.topic - 32-byte topic to join (hex string or buffer)
   * @param {object} opts.corestore - corestore to replicate
   * @param {() => Iterable<{ name: string, instance: object }>} opts.mounts - returns the current mount list (called on each connection so late mounts work)
   * @param {Function} [opts.dispatch] - RPC dispatch function. When provided, a swarm-RPC Protomux channel is attached to every connection.
   * @param {object} [opts.swarm] - hyperswarm options (e.g., bootstrap nodes for testnet)
   * @param {boolean} [opts.server=true]
   * @param {boolean} [opts.client=true]
   */
  constructor (opts = {}) {
    if (!opts.topic) throw new Error('SwarmTransport requires opts.topic')
    if (!opts.corestore) throw new Error('SwarmTransport requires opts.corestore')
    if (typeof opts.mounts !== 'function') throw new Error('SwarmTransport requires opts.mounts (function)')

    this._topic = typeof opts.topic === 'string' ? b4a.from(opts.topic, 'hex') : opts.topic
    if (this._topic.length !== 32) throw new Error('topic must be 32 bytes')

    this._corestore = opts.corestore
    this._getMounts = opts.mounts
    this._dispatch = opts.dispatch || null
    this._swarmOpts = opts.swarm || {}
    this._joinAsServer = opts.server !== false
    this._joinAsClient = opts.client !== false

    this._swarm = null
    this._discovery = null
    this._listening = false
    this._connections = new Set()
  }

  get topic () { return this._topic }
  get listening () { return this._listening }
  get swarm () { return this._swarm }
  get connections () { return this._connections.size }

  async listen () {
    if (this._listening) return

    this._swarm = new Hyperswarm(this._swarmOpts)
    this._swarm.on('connection', (conn, info) => this._onConnection(conn, info))

    this._discovery = this._swarm.join(this._topic, {
      server: this._joinAsServer,
      client: this._joinAsClient
    })
    await this._discovery.flushed()
    this._listening = true
  }

  /**
   * Join an ADDITIONAL topic on this same shared swarm (Keet activateRoom
   * pattern — one Hyperswarm, many topics). Used to rendezvous for a
   * specific room (per-org / per-repo autobase) by its discoveryKey, so
   * peers find each other for that room without needing the daemon's
   * identity topic. Replication still rides the single `_onConnection`
   * (corestore.replicate + per-mount replicate). Deduped + idempotent.
   *
   * @param {Buffer|string} topic - 32-byte discoveryKey (hex or buffer)
   * @param {object} [opts] - { server=true, client=true }
   * @returns {object|null} the PeerDiscovery handle (or existing one)
   */
  joinTopic (topic, opts = {}) {
    if (!this._swarm) return null // not listening yet
    const t = typeof topic === 'string' ? b4a.from(topic, 'hex') : topic
    if (!t || t.length !== 32) return null
    const key = b4a.toString(t, 'hex')
    if (!this._extraTopics) this._extraTopics = new Map()
    if (this._extraTopics.has(key)) return this._extraTopics.get(key)
    const { server = true, client = true } = opts
    const disc = this._swarm.join(t, { server, client })
    this._extraTopics.set(key, disc)
    return disc
  }

  /** discoveryKeys of every additional room topic joined via joinTopic. */
  get joinedRoomTopics () {
    return this._extraTopics ? Array.from(this._extraTopics.keys()) : []
  }

  _onConnection (conn, info) {
    this._connections.add(conn)
    conn.on('close', () => this._connections.delete(conn))
    conn.on('error', () => { /* connection errors are routine — ignore */ })

    // Always replicate the corestore. Hypercore handles muxing internally.
    try {
      this._corestore.replicate(conn)
    } catch (err) {
      // Don't crash on replication setup errors — log via stderr
      // eslint-disable-next-line no-console
      console.error('[hyper-svc/swarm] corestore.replicate failed:', err.message)
    }

    // Belt and suspenders: also call base.replicate on every mounted Autobase
    // consumer. This is the documented workaround for the test-time gotcha
    // where corestore.replicate alone doesn't propagate writer cores.
    //
    // In the same pass, wire up mux-based protocols: any mount exposing
    // `attachProtocol(mux)` (hyper-overlay and future consumers) gets attached
    // to a single Protomux per connection. Protomux.from reuses any protomux
    // corestore/autobase replication already set up.
    let mux = null
    for (const { name, instance } of this._getMounts()) {
      if (!instance) continue

      // A mount may expose `replicate(conn)` to replicate its own
      // autobase(s) — required for MULTI-autobase mounts (e.g. per-org
      // HyperOrgs) whose single `.base` getter is undefined or THROWS.
      // Otherwise fall back to the single-autobase `.base.replicate`.
      // The whole access is wrapped: a throwing `.base` getter must
      // never abort the daemon on an incoming connection.
      try {
        if (typeof instance.replicate === 'function') {
          instance.replicate(conn)
        } else {
          const base = instance.base
          if (base && typeof base.replicate === 'function') base.replicate(conn)
        }
      } catch (err) {
        // eslint-disable-next-line no-console
        console.error(`[hyper-svc/swarm] ${name} replicate failed:`, err.message)
      }

      if (typeof instance.attachProtocol === 'function') {
        if (!mux) {
          try {
            mux = Protomux.from(conn)
          } catch (err) {
            // eslint-disable-next-line no-console
            console.error('[hyper-svc/swarm] Protomux.from failed:', err.message)
          }
        }
        if (mux) {
          try {
            instance.attachProtocol(mux)
          } catch (err) {
            // eslint-disable-next-line no-console
            console.error(`[hyper-svc/swarm] ${name}.attachProtocol failed:`, err.message)
          }
        }
      }
    }

    // Swarm-RPC channel — attach only when dispatch is configured.
    // Multiplexes cleanly over the same Noise stream as replication
    // and module protocols above.
    if (this._dispatch) {
      if (!mux) {
        try {
          mux = Protomux.from(conn)
        } catch (err) {
          // eslint-disable-next-line no-console
          console.error('[hyper-svc/swarm] Protomux.from failed (rpc):', err.message)
        }
      }
      if (mux) {
        try {
          attachRpcServer(mux, this._dispatch, {
            remotePublicKey: conn.remotePublicKey || null
          })
        } catch (err) {
          // eslint-disable-next-line no-console
          console.error('[hyper-svc/swarm] attachRpcServer failed:', err.message)
        }
      }
    }
  }

  async close () {
    if (!this._swarm) return
    for (const conn of this._connections) {
      try { conn.destroy() } catch {}
    }
    this._connections.clear()
    try { await this._swarm.destroy() } catch {}
    this._swarm = null
    this._discovery = null
    this._listening = false
  }
}
/**
 * UDS (Unix Domain Socket) transport for hyper-svc.
 *
 * Local-only RPC. Trusts the local user. CLIs on the same machine connect
 * to ~/.local/share/<name>/svc.sock (or wherever the daemon was told to bind)
 * and exchange length-prefixed JSON frames.
 *
 * Wire protocol per connection:
 *   client → server: { id, method, params }
 *   server → client: { id, result }   OR   { id, error }
 *
 * Multiple in-flight requests are matched by id. Server is fully async —
 * a slow handler doesn't block other requests on the same connection.
 */

import process from '#node:process'
import { unlink, stat } from '#node:fs/promises'
import { encodeFrame, FrameDecoder } from '../frame.js'
import { udsBackend, isAbstract } from '../uds-backend.js'

export class UdsServer {
  /**
   * @param {object} opts
   * @param {string} opts.path - filesystem path for the UNIX socket
   * @param {(method: string, params: any, ctx: object) => Promise<any>} opts.dispatch - request handler
   */
  constructor (opts = {}) {
    if (!opts.path) throw new Error('UdsServer requires opts.path')
    if (typeof opts.dispatch !== 'function') throw new Error('UdsServer requires opts.dispatch')

    this._path = opts.path
    this._dispatch = opts.dispatch
    this._server = null
    this._connections = new Set()
    this._listening = false

    // Idle-connection reaper. `allowHalfOpen:false` + the end/error handlers
    // below clean up when a client CLOSES or EXITS. But a caller that opens a
    // connection and then neither closes it nor exits (a long-lived process
    // that forgets Client.close()) leaves the accepted socket ESTAB forever —
    // the OS never delivers an end/close the server can react to. Unbounded,
    // this grew pgh-sidecar to ~348k ESTAB unix sockets / ~22GB (2026-07-05).
    // Sweep and destroy connections idle past _idleTimeout with no request in
    // flight. Request/response callers reset the timer on every frame, so only
    // genuinely dead connections are reaped. Set idleTimeout:0 to disable.
    this._idleTimeout = opts.idleTimeout === undefined ? 120000 : opts.idleTimeout
    this._sweepTimer = null
  }

  get path () { return this._path }
  get listening () { return this._listening }

  async listen () {
    if (this._listening) return

    // Select the transport: #node:net for pathname sockets (unchanged), or
    // bare-abstract-socket for an '@'-prefixed abstract name. `name` is the
    // bind name with the '@' stripped.
    const { backend, name, abstract } = await udsBackend(this._path)

    // Best-effort cleanup of a stale socket FILE (server crashed without
    // unlinking). Abstract sockets have no filesystem entry (the kernel frees
    // the name when the socket closes), so this applies to pathname sockets only.
    if (!abstract) {
      // ONLY remove if it's actually a socket — never touch regular files / dirs.
      try {
        const s = await stat(this._path)
        if (s.isSocket()) {
          // Try to connect first — if a daemon is already running, refuse to clobber.
          const inUse = await this._probe()
          if (inUse) throw new Error(`socket ${this._path} is already in use`)
          await unlink(this._path)
        }
      } catch (err) {
        if (err.code !== 'ENOENT' && err.message.indexOf('already in use') === -1) {
          // stat failed for some reason other than missing — ignore, let listen() fail naturally
        }
        if (err.message && err.message.indexOf('already in use') !== -1) throw err
      }
    }

    // allowHalfOpen:false is CRITICAL. bare-net defaults it to true (unlike
    // Node), which means when a client disconnects the accepted socket never
    // sees 'end' and never releases — the fd AND its 64KB read buffer leak.
    // With false, peer disconnect surfaces as 'end', which _onConnection
    // turns into a destroy() so the socket fully closes. See the fd-leak that
    // grew pgh-sidecar to ~205k open sockets / 14GB RSS (2026-06-09).
    // (bare-abstract-socket honours the same allowHalfOpen:false on accept.)
    this._server = backend.createServer({ allowHalfOpen: false }, (sock) => this._onConnection(sock))

    await new Promise((resolve, reject) => {
      this._server.once('error', reject)
      this._server.listen(name, () => {
        this._server.removeListener('error', reject)
        resolve()
      })
    })

    this._listening = true

    if (this._idleTimeout > 0) {
      const sweepEvery = Math.max(1000, Math.min(30000, Math.floor(this._idleTimeout / 2)))
      this._sweepTimer = setInterval(() => this._reapIdle(), sweepEvery)
      // Don't let the reaper keep the process alive on its own.
      if (this._sweepTimer && typeof this._sweepTimer.unref === 'function') this._sweepTimer.unref()
    }
  }

  // Destroy connections idle past _idleTimeout with no request in flight.
  // destroy() fires 'close', which removes the socket from _connections.
  _reapIdle () {
    const now = Date.now()
    for (const sock of this._connections) {
      if ((sock._inflight || 0) > 0) continue
      if (now - (sock._lastActive || 0) > this._idleTimeout) {
        try { sock.destroy() } catch {}
      }
    }
  }

  async _probe () {
    const { backend, name } = await udsBackend(this._path)
    return new Promise((resolve) => {
      const sock = backend.createConnection(name)
      sock.once('connect', () => {
        sock.destroy()
        resolve(true)
      })
      sock.once('error', () => {
        sock.destroy()
        resolve(false)
      })
    })
  }

  _onConnection (sock) {
    this._connections.add(sock)
    sock._lastActive = Date.now()
    sock._inflight = 0
    sock.on('close', () => this._connections.delete(sock))

    // Peer closed their write side (client finished + disconnected). bare-net
    // does NOT emit 'close' on its own here — we must destroy() to release the
    // fd and drop the socket (and its read buffer) from _connections. Safe even
    // mid-dispatch: a late _handleRequest write is already wrapped in try/catch.
    sock.on('end', () => { try { sock.destroy() } catch {} })

    const decoder = new FrameDecoder((req) => this._handleRequest(sock, req))

    sock.on('data', (chunk) => {
      sock._lastActive = Date.now()
      try {
        decoder.push(chunk)
      } catch (err) {
        // Bad frame — close the connection rather than try to recover
        try { sock.destroy(err) } catch {}
      }
    })

    // Abrupt disconnect (ECONNRESET, or the client process killed / timed out
    // mid-request). bare-net does NOT emit 'close' on its own (see the 'end'
    // note above) — and unlike a clean FIN there is no 'end' either — so we
    // MUST destroy() here to release the fd + 64KB read buffer and drop the
    // socket from _connections. Without this, every abrupt client disconnect
    // leaks a half-open socket (the 0.1.3 'end'-only fix covered clean closes
    // but not this path — the cause of the 6645-socket accumulation seen when
    // a client hammers the UDS with timed-out/killed calls).
    sock.on('error', () => { try { sock.destroy() } catch {} })
  }

  async _handleRequest (sock, req) {
    const id = req && req.id
    if (typeof id !== 'number' && typeof id !== 'string') {
      // Malformed — best effort error response, but the client probably can't match it
      try {
        sock.write(encodeFrame({ id: null, error: 'request missing id' }))
      } catch {}
      return
    }

    const ctx = {
      transport: 'uds',
      identity: { type: 'local', userId: process.env.USER || null, trust: 'local' }
    }

    // Mark in-flight so the idle reaper never destroys a socket mid-dispatch,
    // even if the handler runs longer than _idleTimeout.
    sock._inflight = (sock._inflight || 0) + 1
    try {
      const result = await this._dispatch(req.method, req.params, ctx)
      try {
        sock.write(encodeFrame({ id, result }))
      } catch {}
    } catch (err) {
      try {
        sock.write(encodeFrame({ id, error: err.message || String(err) }))
      } catch {}
    } finally {
      sock._inflight = Math.max(0, (sock._inflight || 1) - 1)
      sock._lastActive = Date.now()
    }
  }

  async close () {
    if (!this._server) return
    if (this._sweepTimer) { clearInterval(this._sweepTimer); this._sweepTimer = null }
    for (const sock of this._connections) {
      try { sock.destroy() } catch {}
    }
    this._connections.clear()
    await new Promise((resolve) => this._server.close(() => resolve()))
    this._server = null
    this._listening = false

    // Clean up the socket file (best-effort). Abstract sockets have no fs entry.
    if (!isAbstract(this._path)) {
      try { await unlink(this._path) } catch {}
    }
  }
}
/**
 * UDS backend selection.
 *
 * A socket "path" beginning with '@' names a Linux ABSTRACT-namespace socket
 * (no filesystem entry) instead of a pathname socket. Abstract sockets are the
 * only UNIX-socket option when SELinux denies the shell domain from creating
 * pathname sockets — e.g. an unrooted Android phone (celltron) running the
 * daemon under proot, where bind(AF_UNIX, "/path.sock") returns EACCES.
 *
 * For every non-'@' path we use #node:net exactly as before — byte-for-byte
 * unchanged behavior. bare-abstract-socket is imported LAZILY (dynamic import,
 * only at the async call sites below) so pathname deployments never load the
 * native addon.
 */

import net from '#node:net'

let _abstract = null

async function loadAbstract () {
  if (_abstract === null) {
    const m = await import('bare-abstract-socket')
    _abstract = m.default || m
  }
  return _abstract
}

// True if `path` names an abstract-namespace socket (leading '@').
export function isAbstract (path) {
  return typeof path === 'string' && path.length > 1 && path[0] === '@'
}

// Resolve the transport backend + the name to bind/connect. The returned
// `backend` exposes net-compatible createServer(opts, onConnection) and
// createConnection(name). For abstract paths the leading '@' is stripped
// (bare-abstract-socket adds the actual leading NUL).
export async function udsBackend (path) {
  if (isAbstract(path)) {
    return { backend: await loadAbstract(), name: path.slice(1), abstract: true }
  }
  return { backend: net, name: path, abstract: false }
}
const { Pull, Push, HEADERBYTES, KEYBYTES, ABYTES } = require('sodium-secretstream')
const sodium = require('sodium-universal')
const crypto = require('hypercore-crypto')
const { Duplex, Writable, getStreamError } = require('streamx')
const b4a = require('b4a')
const Timeout = require('timeout-refresh')
const unslab = require('unslab')
const Bridge = require('./lib/bridge')
const Handshake = require('./lib/handshake')

const IDHEADERBYTES = HEADERBYTES + 32
const [NS_INITIATOR, NS_RESPONDER, NS_SEND] = crypto.namespace('hyperswarm/secret-stream', 3)
const MAX_ATOMIC_WRITE = 256 * 256 * 256 - 1

module.exports = class NoiseSecretStream extends Duplex {
  constructor(isInitiator, rawStream, opts = {}) {
    super({ mapWritable: toBuffer })

    if (typeof isInitiator !== 'boolean') {
      throw new Error('isInitiator should be a boolean')
    }

    this.noiseStream = this
    this.isInitiator = isInitiator
    this.rawStream = null

    this.publicKey = opts.publicKey || null
    this.remotePublicKey = opts.remotePublicKey || null
    this.handshakeHash = null
    this.connected = false
    this.keepAlive = opts.keepAlive || 0
    this.timeout = 0
    this.enableSend = opts.enableSend !== false

    // pointer for upstream to set data here if they want
    this.userData = null

    let openedDone = null
    this.opened = new Promise((resolve) => {
      openedDone = resolve
    })

    this.rawBytesWritten = 0
    this.rawBytesRead = 0

    // metadata used by 'hyperdht'
    this.relay = null
    this.puncher = null

    // unwrapped raw stream
    this._rawStream = null

    // handshake state
    this._handshake = null
    this._handshakePattern = opts.pattern || null
    this._handshakeDone = null

    // message parsing state
    this._state = 0
    this._len = 0
    this._tmp = 1
    this._message = null

    this._openedDone = openedDone
    this._startDone = null
    this._drainDone = null
    this._outgoingPlain = null
    this._outgoingWrapped = null
    this._utp = null
    this._setup = true
    this._ended = 2
    this._encrypt = null
    this._decrypt = null
    this._timeoutTimer = null
    this._keepAliveTimer = null
    this._sendState = null

    if (opts.autoStart !== false) this.start(rawStream, opts)

    // wiggle it to trigger open immediately (TODO add streamx option for this)
    this.resume()
    this.pause()
  }

  static keyPair(seed) {
    return Handshake.keyPair(seed)
  }

  static id(handshakeHash, isInitiator, id) {
    return streamId(handshakeHash, isInitiator, id)
  }

  setTimeout(ms) {
    if (!ms) ms = 0

    this._clearTimeout()
    this.timeout = ms

    if (!ms || this.rawStream === null) return

    this._timeoutTimer = Timeout.once(ms, destroyTimeout, this)
    this._timeoutTimer.unref()
  }

  setKeepAlive(ms) {
    if (!ms) ms = 0

    this._clearKeepAlive()

    this.keepAlive = ms

    if (!ms || this.rawStream === null) return

    this._keepAliveTimer = Timeout.on(ms, sendKeepAlive, this)
    this._keepAliveTimer.unref()
  }

  sendKeepAlive() {
    const empty = this.alloc(0)
    this.write(empty)
  }

  start(rawStream, opts = {}) {
    if (rawStream) {
      this.rawStream = rawStream
      this._rawStream = rawStream
      if (typeof this.rawStream.setContentSize === 'function') {
        this._utp = rawStream
      }
    } else {
      this.rawStream = new Bridge(this)
      this._rawStream = this.rawStream.reverse
    }

    this.rawStream.on('error', this._onrawerror.bind(this))
    this.rawStream.on('close', this._onrawclose.bind(this))

    this._startHandshake(opts.handshake, opts.keyPair || null)
    this._continueOpen(null)

    if (this.destroying) return

    if (opts.data) this._onrawdata(opts.data)
    if (opts.ended) this._onrawend()

    if (this.keepAlive > 0 && this._keepAliveTimer === null) {
      this.setKeepAlive(this.keepAlive)
    }

    if (this.timeout > 0 && this._timeoutTimer === null) {
      this.setTimeout(this.timeout)
    }
  }

  async flush() {
    if ((await this.opened) === false) return false
    if ((await Writable.drained(this)) === false) return false
    if (this.destroying) return false

    if (this.rawStream !== null && this.rawStream.flush) {
      return await this.rawStream.flush()
    }

    return true
  }

  _continueOpen(err) {
    if (err) this.destroy(err)
    if (this._startDone === null) return
    const done = this._startDone
    this._startDone = null
    this._open(done)
  }

  _onkeypairpromise(p) {
    const self = this
    const cont = this._continueOpen.bind(this)

    p.then(onkeypair, cont)

    function onkeypair(kp) {
      self._onkeypair(kp)
      cont(null)
    }
  }

  _onkeypair(keyPair) {
    const pattern = this._handshakePattern || 'XX'
    const remotePublicKey = this.remotePublicKey

    this._handshake = new Handshake(this.isInitiator, keyPair, remotePublicKey, pattern)
    this.publicKey = this._handshake.keyPair.publicKey
  }

  _startHandshake(handshake, keyPair) {
    if (handshake) {
      const { tx, rx, hash, publicKey, remotePublicKey } = handshake
      this._setupSecretStream(tx, rx, hash, publicKey, remotePublicKey)
      return
    }

    if (!keyPair) keyPair = Handshake.keyPair()

    if (typeof keyPair.then === 'function') {
      this._onkeypairpromise(keyPair)
    } else {
      this._onkeypair(keyPair)
    }
  }

  _onrawerror(err) {
    this.destroy(err)
  }

  _onrawclose() {
    if (this._ended !== 0) this.destroy()
  }

  _onrawdata(data) {
    let offset = 0

    if (this._timeoutTimer !== null) {
      this._timeoutTimer.refresh()
    }

    do {
      switch (this._state) {
        case 0: {
          while (this._tmp !== 0x1000000 && offset < data.byteLength) {
            const v = data[offset++]
            this._len += this._tmp * v
            this._tmp *= 256
          }

          if (this._tmp === 0x1000000) {
            this._tmp = 0
            this._state = 1
            const unprocessed = data.byteLength - offset
            if (unprocessed < this._len && this._utp !== null)
              this._utp.setContentSize(this._len - unprocessed)
          }

          break
        }

        case 1: {
          const missing = this._len - this._tmp
          const end = missing + offset

          if (this._message === null && end <= data.byteLength) {
            this._message = data.subarray(offset, end)
            offset += missing
            this._incoming()
            break
          }

          const unprocessed = data.byteLength - offset

          if (this._message === null) {
            this._message = b4a.allocUnsafe(this._len)
          }

          b4a.copy(data, this._message, this._tmp, offset)
          this._tmp += unprocessed

          if (end <= data.byteLength) {
            offset += missing
            this._incoming()
          } else {
            offset += unprocessed
          }

          break
        }
      }
    } while (offset < data.byteLength && !this.destroying)
  }

  _onrawend() {
    this._ended--
    this.push(null)
  }

  _onrawdrain() {
    const drain = this._drainDone
    if (drain === null) return
    this._drainDone = null
    drain()
  }

  _read(cb) {
    this.rawStream.resume()
    cb(null)
  }

  _incoming() {
    const message = this._message

    this._state = 0
    this._len = 0
    this._tmp = 1
    this._message = null

    if (this._setup === true) {
      if (this._handshake) {
        this._onhandshakert(this._handshake.recv(message))
      } else {
        if (message.byteLength !== IDHEADERBYTES) {
          this.destroy(new Error('Invalid header message received'))
          return
        }

        const remoteId = message.subarray(0, 32)
        const expectedId = streamId(this.handshakeHash, !this.isInitiator)
        const header = message.subarray(32)

        if (!b4a.equals(expectedId, remoteId)) {
          this.destroy(new Error('Invalid header received'))
          return
        }

        this._decrypt.init(header)
        this._setup = false // setup is now done
      }
      return
    }

    if (message.byteLength < ABYTES) {
      this.destroy(new Error('Invalid message received'))
      return
    }

    this.rawBytesRead += message.byteLength

    const plain = message.subarray(1, message.byteLength - ABYTES + 1)

    try {
      this._decrypt.next(message, plain)
    } catch (err) {
      this.destroy(err)
      return
    }

    // If keep alive is selective, eat the empty buffers (ie assume the other side has it enabled also)
    if (plain.byteLength === 0 && this.keepAlive !== 0) return

    if (this.push(plain) === false) {
      this.rawStream.pause()
    }
  }

  _onhandshakert(h) {
    if (this._handshakeDone === null) return

    if (h !== null) {
      if (h.data) this._rawStream.write(h.data)
      if (!h.tx) return
    }

    const done = this._handshakeDone
    const publicKey = this._handshake.keyPair.publicKey

    this._handshakeDone = null
    this._handshake = null

    if (h === null) return done(new Error('Noise handshake failed'))

    this._setupSecretStream(h.tx, h.rx, h.hash, publicKey, h.remotePublicKey)
    this._resolveOpened(true)
    done(null)
  }

  _setupSecretStream(tx, rx, handshakeHash, publicKey, remotePublicKey) {
    const buf = b4a.allocUnsafeSlow(3 + IDHEADERBYTES)
    writeUint24le(IDHEADERBYTES, buf)

    this._encrypt = new Push(unslab(tx.subarray(0, KEYBYTES)), undefined, buf.subarray(3 + 32))
    this._decrypt = new Pull(unslab(rx.subarray(0, KEYBYTES)))

    this.publicKey = publicKey
    this.remotePublicKey = remotePublicKey
    this.handshakeHash = handshakeHash

    const id = buf.subarray(3, 3 + 32)
    streamId(handshakeHash, this.isInitiator, id)

    // initialize secretbox state for unordered messages
    this._setupSecretSend(handshakeHash)

    this.emit('handshake')
    // if rawStream is a bridge, also emit it there
    if (this.rawStream !== this._rawStream) this.rawStream.emit('handshake')

    if (this.destroying) return

    this._rawStream.write(buf)
  }

  _setupSecretSend(handshakeHash) {
    this._sendState = b4a.allocUnsafeSlow(32 + 32 + 8 + 8)
    const encrypt = this._sendState.subarray(0, 32) // secrets
    const decrypt = this._sendState.subarray(32, 64)
    const counter = this._sendState.subarray(64, 72) // nonce
    const initial = this._sendState.subarray(72)

    const inputs = this.isInitiator
      ? [
          [NS_INITIATOR, NS_SEND],
          [NS_RESPONDER, NS_SEND]
        ]
      : [
          [NS_RESPONDER, NS_SEND],
          [NS_INITIATOR, NS_SEND]
        ]

    sodium.crypto_generichash_batch(encrypt, inputs[0], handshakeHash)
    sodium.crypto_generichash_batch(decrypt, inputs[1], handshakeHash)

    sodium.randombytes_buf(initial)
    counter.set(initial)
  }

  _open(cb) {
    // no autostart or no handshake yet
    if (this._rawStream === null || (this._handshake === null && this._encrypt === null)) {
      this._startDone = cb
      return
    }

    this._rawStream.on('data', this._onrawdata.bind(this))
    this._rawStream.on('end', this._onrawend.bind(this))
    this._rawStream.on('drain', this._onrawdrain.bind(this))

    if (this.enableSend) this._rawStream.on('message', this._onmessage.bind(this))

    if (this._encrypt !== null) {
      this._resolveOpened(true)
      return cb(null)
    }

    this._handshakeDone = cb

    if (this.isInitiator) this._onhandshakert(this._handshake.send())
  }

  _predestroy() {
    if (this.rawStream) {
      const error = getStreamError(this)
      this.rawStream.destroy(error)
    }

    if (this._startDone !== null) {
      const done = this._startDone
      this._startDone = null
      done(new Error('Stream destroyed'))
    }

    if (this._handshakeDone !== null) {
      const done = this._handshakeDone
      this._handshakeDone = null
      done(new Error('Stream destroyed'))
    }

    if (this._drainDone !== null) {
      const done = this._drainDone
      this._drainDone = null
      done(new Error('Stream destroyed'))
    }
  }

  _write(data, cb) {
    let wrapped = this._outgoingWrapped

    if (data !== this._outgoingPlain) {
      wrapped = b4a.allocUnsafe(data.byteLength + 3 + ABYTES)
      wrapped.set(data, 4)
    } else {
      this._outgoingWrapped = this._outgoingPlain = null
    }

    if (wrapped.byteLength - 3 > MAX_ATOMIC_WRITE) {
      return cb(
        new Error(
          'Message is too large for an atomic write. Max size is ' + MAX_ATOMIC_WRITE + ' bytes.'
        )
      )
    }
    this.rawBytesWritten += wrapped.byteLength

    writeUint24le(wrapped.byteLength - 3, wrapped)
    // offset 4 so we can do it in-place
    this._encrypt.next(wrapped.subarray(4, 4 + data.byteLength), wrapped.subarray(3))

    if (this._keepAliveTimer !== null) this._keepAliveTimer.refresh()

    if (this._rawStream.write(wrapped) === false) {
      this._drainDone = cb
    } else {
      cb(null)
    }
  }

  _final(cb) {
    this._clearKeepAlive()
    this._ended--
    this._rawStream.end()
    cb(null)
  }

  _resolveOpened(val) {
    if (this._openedDone === null) return
    const opened = this._openedDone
    this._openedDone = null
    opened(val)
    if (!val) return
    this.connected = true
    this.emit('connect')
  }

  _clearTimeout() {
    if (this._timeoutTimer === null) return
    this._timeoutTimer.destroy()
    this._timeoutTimer = null
    this.timeout = 0
  }

  _clearKeepAlive() {
    if (this._keepAliveTimer === null) return
    this._keepAliveTimer.destroy()
    this._keepAliveTimer = null
    this.keepAlive = 0
  }

  _destroy(cb) {
    this._clearKeepAlive()
    this._clearTimeout()
    this._resolveOpened(false)
    cb(null)
  }

  _boxMessage(buffer) {
    const MB = sodium.crypto_secretbox_MACBYTES // 16
    const NB = sodium.crypto_secretbox_NONCEBYTES // 24

    const counter = this._sendState.subarray(64, 72)
    sodium.sodium_increment(counter)
    if (b4a.equals(counter, this._sendState.subarray(72))) {
      this.destroy(new Error('udp send nonce exchausted'))
      return
    }

    const secret = this._sendState.subarray(0, 32)
    const envelope = b4a.allocUnsafe(8 + MB + buffer.byteLength)
    const nonce = envelope.subarray(0, NB)
    const ciphertext = envelope.subarray(8)

    b4a.fill(nonce, 0) // pad suffix
    nonce.set(counter)

    sodium.crypto_secretbox_easy(ciphertext, buffer, nonce, secret)
    return envelope
  }

  send(buffer) {
    if (!this._sendState) return
    if (!this.rawStream?.send) return // udx-stream expected

    const message = this._boxMessage(buffer)
    return this.rawStream.send(message)
  }

  trySend(buffer) {
    if (!this._sendState) return
    if (!this.rawStream?.trySend) return // udx-stream expected

    const message = this._boxMessage(buffer)
    this.rawStream.trySend(message)
  }

  _onmessage(buffer) {
    if (!this._sendState) return // messages before handshake are dropped

    const MB = sodium.crypto_secretbox_MACBYTES // 16
    const NB = sodium.crypto_secretbox_NONCEBYTES // 24

    if (buffer.byteLength < NB) return // Invalid message

    const nonce = b4a.allocUnsafe(NB)
    b4a.fill(nonce, 0)
    nonce.set(buffer.subarray(0, 8))

    const secret = this._sendState.subarray(32, 64)
    const ciphertext = buffer.subarray(8)
    const plain = buffer.subarray(8, buffer.byteLength - MB)

    if (ciphertext.byteLength < MB) return // invalid message

    const success = sodium.crypto_secretbox_open_easy(plain, ciphertext, nonce, secret)

    if (success) this.emit('message', plain)
  }

  alloc(len) {
    const buf = b4a.allocUnsafe(len + 3 + ABYTES)
    this._outgoingWrapped = buf
    this._outgoingPlain = buf.subarray(4, buf.byteLength - ABYTES + 1)
    return this._outgoingPlain
  }

  toJSON() {
    return {
      isInitiator: this.isInitiator,
      publicKey: this.publicKey && b4a.toString(this.publicKey, 'hex'),
      remotePublicKey: this.remotePublicKey && b4a.toString(this.remotePublicKey, 'hex'),
      connected: this.connected,
      destroying: this.destroying,
      destroyed: this.destroyed,
      rawStream: this.rawStream && this.rawStream.toJSON ? this.rawStream.toJSON() : null
    }
  }
}

function writeUint24le(n, buf) {
  buf[0] = n & 255
  buf[1] = (n >>> 8) & 255
  buf[2] = (n >>> 16) & 255
}

function streamId(handshakeHash, isInitiator, out = b4a.allocUnsafe(32)) {
  sodium.crypto_generichash(out, isInitiator ? NS_INITIATOR : NS_RESPONDER, handshakeHash)
  return out
}

function toBuffer(data) {
  return typeof data === 'string' ? b4a.from(data) : data
}

function destroyTimeout() {
  this.destroy(new Error('Stream timed out'))
}

function sendKeepAlive() {
  const empty = this.alloc(0)
  this.write(empty)
}
const { Duplex, Writable } = require('streamx')

class ReversePassThrough extends Duplex {
  constructor(s) {
    super()
    this._stream = s
    this._ondrain = null
  }

  _write(data, cb) {
    if (this._stream.push(data) === false) {
      this._stream._ondrain = cb
    } else {
      cb(null)
    }
  }

  _final(cb) {
    this._stream.push(null)
    cb(null)
  }

  _read(cb) {
    const ondrain = this._ondrain
    this._ondrain = null
    if (ondrain) ondrain()
    cb(null)
  }
}

module.exports = class Bridge extends Duplex {
  constructor(noiseStream) {
    super()

    this.noiseStream = noiseStream

    this._ondrain = null
    this.reverse = new ReversePassThrough(this)
  }

  get publicKey() {
    return this.noiseStream.publicKey
  }

  get remotePublicKey() {
    return this.noiseStream.remotePublicKey
  }

  get handshakeHash() {
    return this.noiseStream.handshakeHash
  }

  flush() {
    return Writable.drained(this)
  }

  _read(cb) {
    const ondrain = this._ondrain
    this._ondrain = null
    if (ondrain) ondrain()
    cb(null)
  }

  _write(data, cb) {
    if (this.reverse.push(data) === false) {
      this.reverse._ondrain = cb
    } else {
      cb(null)
    }
  }

  _final(cb) {
    this.reverse.push(null)
    cb(null)
  }
}
const sodium = require('sodium-universal')
const curve = require('noise-curve-ed')
const Noise = require('noise-handshake')
const b4a = require('b4a')

const EMPTY = b4a.alloc(0)

module.exports = class Handshake {
  constructor(isInitiator, keyPair, remotePublicKey, pattern) {
    this.isInitiator = isInitiator
    this.keyPair = keyPair
    this.noise = new Noise(pattern, isInitiator, keyPair, { curve })
    this.noise.initialise(EMPTY, remotePublicKey)
    this.destroyed = false
  }

  static keyPair(seed) {
    const publicKey = b4a.alloc(32)
    const secretKey = b4a.alloc(64)
    if (seed) sodium.crypto_sign_seed_keypair(publicKey, secretKey, seed)
    else sodium.crypto_sign_keypair(publicKey, secretKey)
    return { publicKey, secretKey }
  }

  recv(data) {
    try {
      this.noise.recv(data)
      if (this.noise.complete) return this._return(null)
      return this.send()
    } catch {
      this.destroy()
      return null
    }
  }

  // note that the data returned here is framed so we don't have to do an extra copy
  // when sending it...
  send() {
    try {
      const data = this.noise.send()
      const wrap = b4a.allocUnsafe(data.byteLength + 3)

      writeUint24le(data.byteLength, wrap)
      wrap.set(data, 3)

      return this._return(wrap)
    } catch {
      this.destroy()
      return null
    }
  }

  destroy() {
    if (this.destroyed) return
    this.destroyed = true
  }

  _return(data) {
    const tx = this.noise.complete ? b4a.toBuffer(this.noise.tx) : null
    const rx = this.noise.complete ? b4a.toBuffer(this.noise.rx) : null
    const hash = this.noise.complete ? b4a.toBuffer(this.noise.hash) : null
    const remotePublicKey = this.noise.complete ? b4a.toBuffer(this.noise.rs) : null

    return {
      data,
      remotePublicKey,
      hash,
      tx,
      rx
    }
  }
}

function writeUint24le(n, buf) {
  buf[0] = n & 255
  buf[1] = (n >>> 8) & 255
  buf[2] = (n >>> 16) & 255
}
{
  "name": "@hyperswarm/secret-stream",
  "version": "6.9.1",
  "description": "Secret stream backed by Noise and libsodium's secretstream",
  "main": "index.js",
  "files": [
    "index.js",
    "lib/**.js"
  ],
  "dependencies": {
    "b4a": "^1.1.0",
    "hypercore-crypto": "^3.3.1",
    "noise-curve-ed": "^2.0.1",
    "noise-handshake": "^4.0.0",
    "sodium-secretstream": "^1.1.0",
    "sodium-universal": "^5.0.0",
    "streamx": "^2.14.0",
    "timeout-refresh": "^2.0.0",
    "unslab": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "udx-native": "^1.13.2"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check .",
    "test": "brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/hyperswarm-secret-stream.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/hyperswarm-secret-stream/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperswarm-secret-stream"
}
const Cache = require('xache')

module.exports = class AdaptiveTimeout {
  constructor(opts = {}) {
    this._cache = new Cache({
      maxSize: opts.maxSize || 65536,
      maxAge: opts.maxAge || 10 * 60 * 1000 // 10 minutes
    })
    this._fallback = opts.fallback || AdaptiveTimeout.TimeoutExponential
    this._min = opts.min ?? 300
    this._max = opts.max || 4000
    this._jitter = opts.jitter ?? 256
  }

  // Default - aggressive ramp
  static TimeoutAggressive = [500, 750, 1000, 1500, 2000]

  // Linear - steady increase
  static TimeoutLinear = [500, 1000, 1500, 2000, 2500]

  // Exponential - slow start, rapid backoff
  static TimeoutExponential = [250, 500, 1000, 2000, 4000]

  // Gentle - conservative, patient
  static TimeoutGentle = [1000, 1250, 1500, 1750, 2000]

  // Fast - rapid fire retries
  static TimeoutFast = [200, 400, 600, 800, 1000]

  // U-shape - long, short, long
  static TimeoutUShape = [1500, 750, 500, 750, 1500]

  // Inverse U - short, long, short
  static TimeoutInverseU = [500, 1000, 1500, 1000, 500]

  // Sawtooth - alternating fast/slow
  static TimeoutSawtooth = [500, 1500, 500, 1500, 500]

  // Plateau - quick ramp then steady
  static TimeoutPlateau = [500, 1000, 2000, 2000, 2000]

  // Logarithmic - diminishing increases
  static TimeoutLogarithmic = [500, 1000, 1300, 1500, 1600]

  getValue(key) {
    return this._cache.get(key)
  }

  put(key, value) {
    let p = this._cache.get(key)

    if (!p) {
      p = { avg: value, variance: value >> 1 }
    } else {
      // blend 75% old + 25% new deviation
      p.variance += (Math.abs(p.avg - value) - p.variance) >> 2
      // blend 87.5% old + 12.5% new sample
      p.avg += (value - p.avg) >> 3
    }

    this._cache.set(key, p)

    return p
  }

  get(key, attempt = 1) {
    const p = this._cache.get(key)
    const jitter = (Math.random() * this._jitter) | 0

    if (p) {
      // known - use adaptive with linear backoff
      const base = p.avg + (p.variance << 1)
      const backoff = base * attempt
      return Math.min(Math.max(backoff + jitter, this._min), this._max)
    } else {
      // unknown - use aggressive fallback
      const base = this._fallback[Math.min(attempt - 1, this._fallback.length - 1)]
      return base + jitter
    }
  }

  has(key) {
    return this._cache.has(key)
  }

  delete(key) {
    return this._cache.delete(key)
  }

  clear() {
    this._cache.clear()
  }
}
{
  "name": "adaptive-timeout",
  "version": "1.0.1",
  "description": "adaptive-timeout",
  "main": "index.js",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    }
  },
  "files": [
    "package.json",
    "index.js",
    "index.d.ts"
  ],
  "devDependencies": {
    "brittle": "^3.19.0",
    "lunte": "^1.2.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && lunte && brittle-bare test/index.js",
    "lint": "lunte"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/adaptive-timeout.git"
  },
  "author": "Holepunch Inc",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/adaptive-timeout/issues"
  },
  "homepage": "https://github.com/holepunchto/adaptive-timeout",
  "dependencies": {
    "xache": "^1.2.1"
  }
}
function isBuffer(value) {
  return Buffer.isBuffer(value) || value instanceof Uint8Array
}

function isEncoding(encoding) {
  return Buffer.isEncoding(encoding)
}

function alloc(size, fill, encoding) {
  return Buffer.alloc(size, fill, encoding)
}

function allocUnsafe(size) {
  return Buffer.allocUnsafe(size)
}

function allocUnsafeSlow(size) {
  return Buffer.allocUnsafeSlow(size)
}

function byteLength(string, encoding) {
  return Buffer.byteLength(string, encoding)
}

function compare(a, b) {
  return Buffer.compare(a, b)
}

function concat(buffers, totalLength) {
  return Buffer.concat(buffers, totalLength)
}

function copy(source, target, targetStart, start, end) {
  return toBuffer(source).copy(target, targetStart, start, end)
}

function equals(a, b) {
  return toBuffer(a).equals(b)
}

function fill(buffer, value, offset, end, encoding) {
  return toBuffer(buffer).fill(value, offset, end, encoding)
}

function from(value, encodingOrOffset, length) {
  return Buffer.from(value, encodingOrOffset, length)
}

function includes(buffer, value, byteOffset, encoding) {
  return toBuffer(buffer).includes(value, byteOffset, encoding)
}

function indexOf(buffer, value, byfeOffset, encoding) {
  return toBuffer(buffer).indexOf(value, byfeOffset, encoding)
}

function lastIndexOf(buffer, value, byteOffset, encoding) {
  return toBuffer(buffer).lastIndexOf(value, byteOffset, encoding)
}

function swap16(buffer) {
  return toBuffer(buffer).swap16()
}

function swap32(buffer) {
  return toBuffer(buffer).swap32()
}

function swap64(buffer) {
  return toBuffer(buffer).swap64()
}

function toBuffer(buffer) {
  if (Buffer.isBuffer(buffer)) return buffer
  return Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

function toString(buffer, encoding, start, end) {
  return toBuffer(buffer).toString(encoding, start, end)
}

function write(buffer, string, offset, length, encoding) {
  return toBuffer(buffer).write(string, offset, length, encoding)
}

function readDoubleBE(buffer, offset) {
  return toBuffer(buffer).readDoubleBE(offset)
}

function readDoubleLE(buffer, offset) {
  return toBuffer(buffer).readDoubleLE(offset)
}

function readFloatBE(buffer, offset) {
  return toBuffer(buffer).readFloatBE(offset)
}

function readFloatLE(buffer, offset) {
  return toBuffer(buffer).readFloatLE(offset)
}

function readInt32BE(buffer, offset) {
  return toBuffer(buffer).readInt32BE(offset)
}

function readInt32LE(buffer, offset) {
  return toBuffer(buffer).readInt32LE(offset)
}

function readUInt32BE(buffer, offset) {
  return toBuffer(buffer).readUInt32BE(offset)
}

function readUInt32LE(buffer, offset) {
  return toBuffer(buffer).readUInt32LE(offset)
}

function writeDoubleBE(buffer, value, offset) {
  return toBuffer(buffer).writeDoubleBE(value, offset)
}

function writeDoubleLE(buffer, value, offset) {
  return toBuffer(buffer).writeDoubleLE(value, offset)
}

function writeFloatBE(buffer, value, offset) {
  return toBuffer(buffer).writeFloatBE(value, offset)
}

function writeFloatLE(buffer, value, offset) {
  return toBuffer(buffer).writeFloatLE(value, offset)
}

function writeInt32BE(buffer, value, offset) {
  return toBuffer(buffer).writeInt32BE(value, offset)
}

function writeInt32LE(buffer, value, offset) {
  return toBuffer(buffer).writeInt32LE(value, offset)
}

function writeUInt32BE(buffer, value, offset) {
  return toBuffer(buffer).writeUInt32BE(value, offset)
}

function writeUInt32LE(buffer, value, offset) {
  return toBuffer(buffer).writeUInt32LE(value, offset)
}

module.exports = {
  isBuffer,
  isEncoding,
  alloc,
  allocUnsafe,
  allocUnsafeSlow,
  byteLength,
  compare,
  concat,
  copy,
  equals,
  fill,
  from,
  includes,
  indexOf,
  lastIndexOf,
  swap16,
  swap32,
  swap64,
  toBuffer,
  toString,
  write,
  readDoubleBE,
  readDoubleLE,
  readFloatBE,
  readFloatLE,
  readInt32BE,
  readInt32LE,
  readUInt32BE,
  readUInt32LE,
  writeDoubleBE,
  writeDoubleLE,
  writeFloatBE,
  writeFloatLE,
  writeInt32BE,
  writeInt32LE,
  writeUInt32BE,
  writeUInt32LE
}
{
  "name": "b4a",
  "version": "1.8.1",
  "description": "Bridging the gap between buffers and typed arrays",
  "exports": {
    "./package": "./package.json",
    ".": {
      "react-native": "./react-native.js",
      "browser": "./browser.js",
      "default": "./index.js"
    }
  },
  "files": [
    "browser.js",
    "index.js",
    "react-native.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:bare && npm run test:node",
    "test:bare": "brittle-bare --coverage test.mjs",
    "test:node": "brittle-node --coverage test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/b4a.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/b4a/issues"
  },
  "homepage": "https://github.com/holepunchto/b4a#readme",
  "devDependencies": {
    "brittle": "^3.5.2",
    "lunte": "^1.7.0",
    "nanobench": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "react-native-b4a": "*"
  },
  "peerDependenciesMeta": {
    "react-native-b4a": {
      "optional": true
    }
  }
}
module.exports = require.addon()
const binding = require('./binding')

module.exports = binding.abort
{
  "name": "bare-abort",
  "version": "2.0.13",
  "description": "Cause abnormal program termination and generate a crash report",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-abort.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-abort/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-abort#readme",
  "devDependencies": {
    "cmake-bare": "^1.1.7",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  }
}
const ESC = '\x1b'
const CSI = ESC + '['
const SGR = (n) => CSI + n + 'm'

exports.constants = {
  ESC,
  CSI,
  SGR
}

// https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_(Control_Sequence_Introducer)_sequences

exports.cursorHide = CSI + '?25l'
exports.cursorShow = CSI + '?25h'

exports.cursorUp = function cursorUp(n = 1) {
  return CSI + n + 'A'
}

exports.cursorDown = function cursorDown(n = 1) {
  return CSI + n + 'B'
}

exports.cursorForward = function cursorForward(n = 1) {
  return CSI + n + 'C'
}

exports.cursorBack = function cursorBack(n = 1) {
  return CSI + n + 'D'
}

exports.cursorNextLine = function cursorNextLine(n = 1) {
  return CSI + n + 'E'
}

exports.cursorPreviousLine = function cursorPreviousLine(n = 1) {
  return CSI + n + 'F'
}

exports.cursorPosition = function cursorPosition(column, row = 0) {
  if (row === 0) return CSI + (column + 1) + 'G'

  return CSI + (row + 1) + ';' + (column + 1) + 'H'
}

exports.eraseDisplayEnd = CSI + 'J'
exports.eraseDisplayStart = CSI + '1J'
exports.eraseDisplay = CSI + '2J'
exports.eraseLineEnd = CSI + 'K'
exports.eraseLineStart = CSI + '1K'
exports.eraseLine = CSI + '2K'

exports.scrollUp = function scrollUp(n = 1) {
  return CSI + n + 'S'
}

exports.scrollDown = function scrollDown(n = 1) {
  return CSI + n + 'T'
}

// https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_(Select_Graphic_Rendition)_parameters

exports.modifierReset = SGR(0)
exports.modifierBold = SGR(1)
exports.modifierDim = SGR(2)
exports.modifierItalic = SGR(3)
exports.modifierUnderline = SGR(4)
exports.modifierNormal = SGR(22)
exports.modifierNotItalic = SGR(23)
exports.modifierNotUnderline = SGR(24)

// https://en.wikipedia.org/wiki/ANSI_escape_code#Colors

exports.colorBlack = SGR(30)
exports.colorRed = SGR(31)
exports.colorGreen = SGR(32)
exports.colorYellow = SGR(33)
exports.colorBlue = SGR(34)
exports.colorMagenta = SGR(35)
exports.colorCyan = SGR(36)
exports.colorWhite = SGR(37)
exports.colorDefault = SGR(39)
exports.colorBrightBlack = SGR(90)
exports.colorBrightRed = SGR(91)
exports.colorBrightGreen = SGR(92)
exports.colorBrightYellow = SGR(93)
exports.colorBrightBlue = SGR(94)
exports.colorBrightMagenta = SGR(95)
exports.colorBrightCyan = SGR(96)
exports.colorBrightWhite = SGR(97)
{
  "name": "bare-ansi-escapes",
  "version": "2.2.3",
  "description": "Parse and produce ANSI escape sequences",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./key-decoder": {
      "types": "./key-decoder.d.ts",
      "default": "./key-decoder.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "key-decoder.js",
    "key-decoder.d.ts"
  ],
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-ansi-escapes.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-ansi-escapes/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-ansi-escapes#readme",
  "dependencies": {
    "bare-stream": "^2.6.5"
  },
  "devDependencies": {
    "bare-buffer": "^3.0.2",
    "brittle": "^3.3.2",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  },
  "peerDependencies": {
    "bare-buffer": "*"
  },
  "peerDependenciesMeta": {
    "bare-buffer": {
      "optional": true
    }
  }
}
const inspect = require('bare-inspect')

class AssertionError extends Error {
  constructor(opts = {}) {
    let { message = null, actual, expected, operator } = opts

    if (message === null) {
      message = `${inspect(actual)} ${operator} ${inspect(expected)}`
    }

    super(message)

    this.actual = actual
    this.expected = expected
    this.operator = operator
  }

  get name() {
    return 'AssertionError'
  }

  get code() {
    'ASSERTION'
  }
}

function assertFail(opts, fn) {
  if (opts.message instanceof Error) throw opts.message

  const err = new AssertionError(opts)

  if (Error.captureStackTrace) Error.captureStackTrace(err, fn)

  throw err
}

module.exports = exports = function assert(actual, message) {
  if (actual) return

  assertFail({ message, actual, expected: true, operator: '==' }, assert)
}

exports.AssertionError = AssertionError

exports.fail = function fail(message) {
  if (message === undefined) message = 'Failed'

  assertFail({ message, operator: 'fail' }, fail)
}

exports.ok = function ok(actual, message) {
  if (actual) return

  assertFail({ message, actual, expected: true, operator: '==' }, ok)
}

exports.notOk = function ok(actual, message) {
  if (!actual) return

  assertFail({ message, actual, expected: false, operator: '==' }, ok)
}

exports.equal = function equal(actual, expected, message) {
  if (actual == expected || (actual !== actual && expected !== expected)) {
    return
  }

  assertFail({ message, actual, expected, operator: '==' }, equal)
}

exports.notEqual = function notEqual(actual, expected, message) {
  if (actual != expected && (actual === actual || expected === expected)) {
    return
  }

  assertFail({ message, actual, expected, operator: '!=' }, notEqual)
}

exports.strictEqual = function strictEqual(actual, expected, message) {
  if (Object.is(actual, expected)) return

  assertFail(
    { message, actual, expected, operator: 'strictEqual' },
    strictEqual
  )
}

exports.notStrictEqual = function notStrictEqual(actual, expected, message) {
  if (!Object.is(actual, expected)) return

  assertFail(
    { message, actual, expected, operator: 'notStrictEqual' },
    notStrictEqual
  )
}
{
  "name": "bare-assert",
  "version": "1.2.0",
  "description": "Assertion library for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts"
  ],
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-assert.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-assert/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-assert#readme",
  "dependencies": {
    "bare-inspect": "^3.1.2"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  }
}
module.exports = require.addon()
const binding = require('./binding')

exports.Resolver = class DNSResolver {
  constructor() {
    this._handle = binding.initResolver()
  }

  resolveTxt(hostname, cb = noop) {
    binding.resolveTxt(this._handle, hostname, cb, this)
  }

  destroy() {
    binding.destroyResolver(this._handle)
    this._handle = null
  }

  static global = new this()
}

function onlookup(err, addresses) {
  const req = this

  if (err) return req.cb(err, null, 0)

  const { address, family } = addresses[0]

  return req.cb(null, address, family)
}

function onlookupall(err, addresses) {
  const req = this

  if (err) return req.cb(err, null)

  return req.cb(null, addresses)
}

exports.lookup = function lookup(hostname, opts = {}, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  let { family = 0, all = false } = opts

  if (typeof family === 'string') {
    switch (family) {
      case 'IPv4':
        family = 4
        break
      case 'IPv6':
        family = 6
        break
      default:
        family = 0
    }
  }

  const req = {
    cb,
    handle: null
  }

  req.handle = binding.lookup(
    hostname,
    family || 0,
    all,
    req,
    all ? onlookupall : onlookup
  )
}

exports.resolveTxt = function resolveTxt(hostname, cb) {
  exports.Resolver.global.resolveTxt(hostname, cb)
}

function noop() {}
{
  "name": "bare-dns",
  "version": "2.1.4",
  "description": "Domain name resolution for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-dns.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-dns/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-dns",
  "engines": {
    "bare": ">=1.7.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "cmake-bare": "^1.1.6",
    "cmake-fetch": "^1.3.0",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
const os = require('bare-os')

module.exports = new Proxy(Object.create(null), {
  ownKeys (target) {
    return os.getEnvKeys()
  },

  get (target, property) {
    if (typeof property !== 'string') return

    return os.getEnv(property)
  },

  has (target, property) {
    if (typeof property !== 'string') return false

    return os.hasEnv(property)
  },

  set (target, property, value) {
    if (typeof property !== 'string') return

    const type = typeof value

    if (type !== 'string' && type !== 'number' && type !== 'boolean') {
      throw new Error('Environment variable must be of type string, number, or boolean')
    }

    value = String(value)

    os.setEnv(property, value)

    return true
  },

  deleteProperty (target, property) {
    if (typeof property !== 'string') return

    os.unsetEnv(property)
  },

  getOwnPropertyDescriptor (target, property) {
    return {
      value: this.get(target, property),
      enumerable: true,
      configurable: true,
      writable: true
    }
  }
})
{
  "name": "bare-env",
  "version": "3.0.0",
  "description": "Environment variable support for JavaScript",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "scripts": {
    "test": "standard && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-env.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-env/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-env#readme",
  "dependencies": {
    "bare-os": "^3.0.1"
  },
  "devDependencies": {
    "brittle": "^3.2.1",
    "standard": "^17.0.0"
  }
}
const errors = require('./lib/errors')

class EventListener {
  constructor() {
    this.list = []
    this.count = 0
  }

  append(ctx, name, fn, once) {
    this.count++
    ctx.emit('newListener', name, fn) // Emit BEFORE adding
    this.list.push([fn, once])
  }

  prepend(ctx, name, fn, once) {
    this.count++
    ctx.emit('newListener', name, fn) // Emit BEFORE adding
    this.list.unshift([fn, once])
  }

  remove(ctx, name, fn) {
    for (let i = 0, n = this.list.length; i < n; i++) {
      const l = this.list[i]

      if (l[0] === fn) {
        this.list.splice(i, 1)

        if (this.count === 1) delete ctx._events[name]

        ctx.emit('removeListener', name, fn) // Emit AFTER removing

        this.count--
        return
      }
    }
  }

  removeAll(ctx, name) {
    const list = [...this.list]
    this.list = []

    if (this.count === list.length) delete ctx._events[name]

    for (let i = list.length - 1; i >= 0; i--) {
      ctx.emit('removeListener', name, list[i][0]) // Emit AFTER removing
    }

    this.count -= list.length
  }

  emit(ctx, name, ...args) {
    const list = [...this.list]

    for (let i = 0, n = list.length; i < n; i++) {
      const l = list[i]

      if (l[1] === true) this.remove(ctx, name, l[0])

      Reflect.apply(l[0], ctx, args)
    }

    return list.length > 0
  }
}

function appendListener(ctx, name, fn, once) {
  if (ctx._events === undefined) ctx._events = Object.create(null)
  const e = ctx._events[name] || (ctx._events[name] = new EventListener())
  e.append(ctx, name, fn, once)
  return ctx
}

function prependListener(ctx, name, fn, once) {
  if (ctx._events === undefined) ctx._events = Object.create(null)
  const e = ctx._events[name] || (ctx._events[name] = new EventListener())
  e.prepend(ctx, name, fn, once)
  return ctx
}

function removeListener(ctx, name, fn) {
  if (ctx._events === undefined) return ctx
  const e = ctx._events[name]
  if (e !== undefined) e.remove(ctx, name, fn)
  return ctx
}

function throwUnhandledError(...args) {
  let err

  if (args.length > 0) err = args[0]

  if (err instanceof Error === false) err = errors.UNHANDLED_ERROR(err)

  if (Error.captureStackTrace) {
    Error.captureStackTrace(err, exports.prototype.emit)
  }

  queueMicrotask(() => {
    throw err
  })
}

module.exports = exports = class EventEmitter {
  constructor() {
    this._events = Object.create(null)
  }

  addListener(name, fn) {
    return appendListener(this, name, fn, false)
  }

  addOnceListener(name, fn) {
    return appendListener(this, name, fn, true)
  }

  prependListener(name, fn) {
    return prependListener(this, name, fn, false)
  }

  prependOnceListener(name, fn) {
    return prependListener(this, name, fn, true)
  }

  removeListener(name, fn) {
    return removeListener(this, name, fn)
  }

  on(name, fn) {
    return appendListener(this, name, fn, false)
  }

  once(name, fn) {
    return appendListener(this, name, fn, true)
  }

  off(name, fn) {
    return removeListener(this, name, fn)
  }

  emit(name, ...args) {
    if (name === 'error' && this._events !== undefined && this._events.error === undefined) {
      throwUnhandledError(...args)
    }

    if (this._events === undefined) return false
    const e = this._events[name]
    return e === undefined ? false : e.emit(this, name, ...args)
  }

  listeners(name) {
    if (this._events === undefined) return []
    const e = this._events[name]
    return e === undefined ? [] : [...e.list]
  }

  listenerCount(name) {
    if (this._events === undefined) return 0
    const e = this._events[name]
    return e === undefined ? 0 : e.list.length
  }

  getMaxListeners() {
    return EventEmitter.defaultMaxListeners
  }

  setMaxListeners(n) {}

  removeAllListeners(name) {
    if (arguments.length === 0) {
      for (const key of Reflect.ownKeys(this._events)) {
        if (key === 'removeListener') continue
        this.removeAllListeners(key)
      }
      this.removeAllListeners('removeListener')
    } else {
      const e = this._events[name]
      if (e !== undefined) e.removeAll(this, name)
    }
    return this
  }
}

exports.EventEmitter = exports

exports.errors = errors

exports.defaultMaxListeners = 10

exports.on = function on(emitter, name, opts = {}) {
  const { signal } = opts

  if (signal && signal.aborted) {
    throw errors.OPERATION_ABORTED(signal.reason)
  }

  let error = null
  let done = false

  const events = []
  const promises = []

  if (name !== 'error') emitter.on('error', onerror)

  if (signal) signal.addEventListener('abort', onabort)

  emitter.on(name, onevent)

  return {
    next() {
      if (events.length) {
        return Promise.resolve({ value: events.shift(), done: false })
      }

      if (error) {
        const err = error

        error = null

        return Promise.reject(err)
      }

      if (done) return onclose()

      return new Promise((resolve, reject) => promises.push({ resolve, reject }))
    },

    return() {
      return onclose()
    },

    throw(err) {
      return onerror(err)
    },

    [Symbol.asyncIterator]() {
      return this
    }
  }

  function onevent(...args) {
    if (promises.length) {
      promises.shift().resolve({ value: args, done: false })
    } else {
      events.push(args)
    }
  }

  function onerror(err) {
    emitter.off(name, onevent).off('error', onerror)

    if (promises.length) {
      promises.shift().reject(err)
    } else {
      error = err
    }

    return Promise.resolve({ done: true })
  }

  function onabort() {
    signal.removeEventListener('abort', onabort)

    onerror(errors.OPERATION_ABORTED(signal.reason))
  }

  function onclose() {
    emitter.off(name, onevent)

    if (name !== 'error') emitter.off('error', onerror)

    if (signal) signal.removeEventListener('abort', onabort)

    done = true

    if (promises.length) promises.shift().resolve({ done: true })

    return Promise.resolve({ done: true })
  }
}

exports.once = function once(emitter, name, opts = {}) {
  const { signal } = opts

  if (signal && signal.aborted) {
    return Promise.reject(errors.OPERATION_ABORTED(signal.reason))
  }

  return new Promise((resolve, reject) => {
    if (name !== 'error') emitter.on('error', onerror)

    if (signal) signal.addEventListener('abort', onabort)

    emitter.once(name, onevent)

    function onevent(...args) {
      if (name !== 'error') emitter.off('error', onerror)

      if (signal) signal.removeEventListener('abort', onabort)

      resolve(args)
    }

    function onerror(err) {
      emitter.off(name, onevent)

      if (name !== 'error') emitter.off('error', onerror)

      reject(err)
    }

    function onabort() {
      signal.removeEventListener('abort', onabort)

      onerror(errors.OPERATION_ABORTED(signal.reason))
    }
  })
}

exports.forward = function forward(from, to, names, opts = {}) {
  if (typeof names === 'string') names = [names]

  const { emit = to.emit.bind(to) } = opts

  const listeners = names.map(
    (name) =>
      function onevent(...args) {
        emit(name, ...args)
      }
  )

  to.on('newListener', (name) => {
    const i = names.indexOf(name)

    if (i !== -1 && to.listenerCount(name) === 0) {
      from.on(name, listeners[i])
    }
  }).on('removeListener', (name) => {
    const i = names.indexOf(name)

    if (i !== -1 && to.listenerCount(name) === 0) {
      from.off(name, listeners[i])
    }
  })
}

exports.listenerCount = function listenerCount(emitter, name) {
  return emitter.listenerCount(name)
}

exports.getMaxListeners = function getMaxListeners(emitter) {
  if (typeof emitter.getMaxListeners === 'function') {
    return emitter.getMaxListeners()
  }

  return exports.defaultMaxListeners
}

exports.setMaxListeners = function setMaxListeners(n, ...emitters) {
  if (emitters.length === 0) exports.defaultMaxListeners = n
  else {
    for (const emitter of emitters) {
      if (typeof emitter.setMaxListeners === 'function') {
        emitter.setMaxListeners(n)
      }
    }
  }
}
module.exports = class EventEmitterError extends Error {
  constructor(msg, code, fn = EventEmitterError, opts) {
    super(`${code}: ${msg}`, opts)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'EventEmitterError'
  }

  static OPERATION_ABORTED(cause, msg = 'Operation aborted') {
    return new EventEmitterError(msg, 'OPERATION_ABORTED', EventEmitterError.OPERATION_ABORTED, {
      cause
    })
  }

  static UNHANDLED_ERROR(cause, msg = 'Unhandled error') {
    return new EventEmitterError(msg, 'UNHANDLED_ERROR', EventEmitterError.UNHANDLED_ERROR, {
      cause
    })
  }
}
{
  "name": "bare-events",
  "version": "2.8.2",
  "description": "Event emitters for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    },
    "./web": {
      "types": "./web.d.ts",
      "default": "./web.js"
    },
    "./errors": "./lib/errors.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "global.js",
    "global.d.ts",
    "web.js",
    "web.d.ts",
    "lib"
  ],
  "scripts": {
    "test": "npm run lint && npm run test:bare && npm run test:node",
    "test:bare": "bare test.js",
    "test:node": "node test.js",
    "lint": "prettier . --check"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-events.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-events/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-events#readme",
  "devDependencies": {
    "bare-abort-controller": "^1.0.0",
    "brittle": "^3.3.2",
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^2.0.0",
    "uncaughts": "^1.1.1"
  },
  "peerDependencies": {
    "bare-abort-controller": "*"
  },
  "peerDependenciesMeta": {
    "bare-abort-controller": {
      "optional": true
    }
  }
}
module.exports = require.addon()
const FIFO = require('fast-fifo')
const EventEmitter = require('bare-events')
const path = require('bare-path')
const { isURL, fileURLToPath } = require('bare-url')
const { Readable, Writable } = require('bare-stream')
const binding = require('./binding')
const constants = require('./lib/constants')
const FileError = require('./lib/errors')

const isWindows = Bare.platform === 'win32'

exports.constants = constants

class FileRequest {
  static borrow() {
    if (this._free.length > 0) return this._free.pop()
    return new FileRequest()
  }

  static return(req) {
    if (this._free.length < 32) this._free.push(req.reset())
    else req.destroy()
  }

  constructor() {
    this._reset()
    this._handle = binding.requestInit(this, this._onresult)
  }

  get handle() {
    return this._handle
  }

  retain(value) {
    this._retain = value // Tie the lifetime of `value` to the lifetime of `this`
  }

  reset() {
    if (this._handle === null) return this

    binding.requestReset(this._handle)

    this._reset()

    return this
  }

  destroy() {
    if (this._handle === null) return this

    binding.requestDestroy(this._handle)

    this._reset()
    this._handle = null

    return this
  }

  then(resolve, reject) {
    return this._promise.then(resolve, reject)
  }

  return() {
    if (this._handle === null) return this

    FileRequest.return(this)

    return this
  }

  _reset() {
    this._promise = new Promise((resolve, reject) => {
      this._resolve = resolve
      this._reject = reject
    })
    this._retain = null
  }

  _onresult(err, status) {
    if (err) this._reject(err)
    else this._resolve(status)
  }
}

FileRequest._free = []

function ok(result, cb) {
  if (typeof result === 'function') {
    cb = result
    result = undefined
  }

  if (cb) cb(null, result)
  else return result
}

function fail(err, cb) {
  if (cb) cb(err)
  else throw err
}

function done(err, result, cb) {
  if (typeof result === 'function') {
    cb = result
    result = undefined
  }

  if (err) fail(err, cb)
  else return ok(result, cb)
}

async function open(filepath, flags = 'r', mode = 0o666, cb) {
  if (typeof flags === 'function') {
    cb = flags
    flags = 'r'
    mode = 0o666
  } else if (typeof mode === 'function') {
    cb = mode
    mode = 0o666
  }

  if (typeof flags === 'string') flags = toFlags(flags)
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let fd
  let err = null
  try {
    binding.open(req.handle, filepath, flags, mode)

    fd = await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'open',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, fd, cb)
}

function openSync(filepath, flags = 'r', mode = 0o666) {
  if (typeof flags === 'string') flags = toFlags(flags)
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    return binding.openSync(req.handle, filepath, flags, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'open',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function close(fd, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.close(req.handle, fd)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'close', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function closeSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.closeSync(req.handle, fd)
  } catch (e) {
    throw new FileError(e.message, { operation: 'close', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function access(filepath, mode = constants.F_OK, cb) {
  if (typeof mode === 'function') {
    cb = mode
    mode = constants.F_OK
  }

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.access(req.handle, filepath, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'access',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function accessSync(filepath, mode = constants.F_OK) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.accessSync(req.handle, filepath, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'access',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function exists(filepath, cb) {
  let ok = true
  try {
    await access(filepath)
  } catch {
    ok = false
  }

  return done(null, ok, cb)
}

function existsSync(filepath) {
  try {
    accessSync(filepath)
  } catch {
    return false
  }

  return true
}

async function read(fd, buffer, offset = 0, len = buffer.byteLength - offset, pos = -1, cb) {
  if (typeof offset === 'function') {
    cb = offset
    offset = 0
    len = buffer.byteLength
    pos = -1
  } else if (typeof len === 'function') {
    cb = len
    len = buffer.byteLength - offset
    pos = -1
  } else if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.read(req.handle, fd, buffer, offset, len, pos)

    req.retain(buffer)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'read', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function readSync(fd, buffer, offset = 0, len = buffer.byteLength - offset, pos = -1) {
  const req = FileRequest.borrow()

  try {
    return binding.readSync(req.handle, fd, buffer, offset, len, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'read', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function readv(fd, buffers, pos = -1, cb) {
  if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.readv(req.handle, fd, buffers, pos)

    req.retain(buffers)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'readv', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function readvSync(fd, buffers, pos = -1) {
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  try {
    return binding.readvSync(req.handle, fd, buffers, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'readv', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function write(fd, data, offset, len, pos = -1, cb) {
  if (typeof data === 'string') {
    let encoding = len
    cb = pos
    pos = offset

    if (typeof pos === 'function') {
      cb = pos
      pos = -1
      encoding = 'utf8'
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = 'utf8'
    }

    if (typeof pos === 'string') {
      encoding = pos
      pos = -1
    }

    data = Buffer.from(data, encoding)
    offset = 0
    len = data.byteLength
  } else if (typeof offset === 'function') {
    cb = offset
    offset = 0
    len = data.byteLength
    pos = -1
  } else if (typeof len === 'function') {
    cb = len
    len = data.byteLength - offset
    pos = -1
  } else if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof offset !== 'number') offset = 0
  if (typeof len !== 'number') len = data.byteLength - offset
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.write(req.handle, fd, data, offset, len, pos)

    req.retain(data)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'write', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function writeSync(fd, data, offset, len, pos = -1) {
  if (typeof data === 'string') {
    let encoding = len
    pos = offset

    if (typeof pos === 'string') {
      encoding = pos
      pos = -1
    }

    data = Buffer.from(data, encoding)
    offset = 0
    len = data.byteLength
  }

  if (typeof offset !== 'number') offset = 0
  if (typeof len !== 'number') len = data.byteLength - offset
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  try {
    return binding.writeSync(req.handle, fd, data, offset, len, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'write', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function writev(fd, buffers, pos = -1, cb) {
  if (typeof pos === 'function') {
    cb = pos
    pos = -1
  }

  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  let bytes
  let err = null
  try {
    binding.writev(req.handle, fd, buffers, pos)

    req.retain(buffers)

    bytes = await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'writev', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, bytes, cb)
}

function writevSync(fd, buffers, pos = -1) {
  if (typeof pos !== 'number') pos = -1

  const req = FileRequest.borrow()

  try {
    return binding.writevSync(req.handle, fd, buffers, pos)
  } catch (e) {
    throw new FileError(e.message, { operation: 'writev', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function stat(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.stat(req.handle, filepath)

    await req

    st = new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'stat', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function statSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.statSync(req.handle, filepath)

    return new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'stat', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function lstat(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.lstat(req.handle, filepath)

    await req

    st = new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'lstat', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function lstatSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.lstatSync(req.handle, filepath)

    return new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'lstat', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function fstat(fd, cb) {
  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.fstat(req.handle, fd)

    await req

    st = new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'fstat', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function fstatSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.fstatSync(req.handle, fd)

    return new Stats(...binding.requestResultStat(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'fstat', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function statfs(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let st
  let err = null
  try {
    binding.statfs(req.handle, filepath)

    await req

    st = new StatFs(...binding.requestResultStatfs(req.handle))
  } catch (e) {
    err = new FileError(e.message, { operation: 'statfs', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, st, cb)
}

function statfsSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.statfsSync(req.handle, filepath)

    return new StatFs(...binding.requestResultStatfs(req.handle))
  } catch (e) {
    throw new FileError(e.message, { operation: 'statfs', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function ftruncate(fd, len = 0, cb) {
  if (typeof len === 'function') {
    cb = len
    len = 0
  }

  if (typeof len !== 'number') len = 0

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.ftruncate(req.handle, fd, len)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'ftruncate', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function ftruncateSync(fd, len = 0) {
  if (typeof len !== 'number') len = 0

  const req = FileRequest.borrow()

  try {
    binding.ftruncateSync(req.handle, fd, len)
  } catch (e) {
    throw new FileError(e.message, { operation: 'ftruncate', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function truncate(filepath, len, cb) {
  let fd = -1
  let err

  try {
    fd = await open(filepath, 'r+')

    await ftruncate(fd, len)
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) await close(fd)
  }

  return done(err, cb)
}

function truncateSync(filepath, len) {
  let fd = -1
  let err

  try {
    fd = openSync(filepath, 'r+')

    ftruncateSync(fd, len)
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) closeSync(fd)
  }
}

async function chmod(filepath, mode, cb) {
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.chmod(req.handle, filepath, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'chmod',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function chmodSync(filepath, mode) {
  if (typeof mode === 'string') mode = toMode(mode)

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.chmodSync(req.handle, filepath, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'chmod',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function fchmod(fd, mode, cb) {
  if (typeof mode === 'string') mode = toMode(mode)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fchmod(req.handle, fd, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fchmod', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fchmodSync(fd, mode) {
  if (typeof mode === 'string') mode = toMode(mode)

  const req = FileRequest.borrow()

  try {
    binding.fchmodSync(req.handle, fd, mode)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fchmod', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function chown(filepath, uid, gid, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.chown(req.handle, filepath, uid, gid)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'chown', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function chownSync(filepath, uid, gid) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.chownSync(req.handle, filepath, uid, gid)
  } catch (e) {
    throw new FileError(e.message, { operation: 'chownSync', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function lchown(filepath, uid, gid, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.lchown(req.handle, filepath, uid, gid)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'lchown', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function lchownSync(filepath, uid, gid) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.lchownSync(req.handle, filepath, uid, gid)
  } catch (e) {
    throw new FileError(e.message, { operation: 'lchownSync', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function fchown(fd, uid, gid, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fchown(req.handle, fd, uid, gid)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fchown', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fchownSync(fd, uid, gid) {
  const req = FileRequest.borrow()

  try {
    binding.fchownSync(req.handle, fd, uid, gid)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fchownSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function utimes(filepath, atime, mtime, cb) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.utimes(req.handle, filepath, atime, mtime)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'utimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function utimesSync(filepath, atime, mtime) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.utimesSync(req.handle, filepath, atime, mtime)
  } catch (e) {
    throw new FileError(e.message, { operation: 'utimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function lutimes(filepath, atime, mtime, cb) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.lutimes(req.handle, filepath, atime, mtime)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'lutimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function lutimesSync(filepath, atime, mtime) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.lutimesSync(req.handle, filepath, atime, mtime)
  } catch (e) {
    throw new FileError(e.message, { operation: 'lutimes', code: e.code, path: filepath })
  } finally {
    req.return()
  }
}

async function futimes(fd, atime, mtime, cb) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.futimes(req.handle, fd, atime, mtime)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'futimes', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function futimesSync(fd, atime, mtime) {
  if (typeof atime !== 'number') atime = atime.getTime() / 1000
  if (typeof mtime !== 'number') mtime = mtime.getTime() / 1000

  const req = FileRequest.borrow()

  try {
    binding.futimesSync(req.handle, fd, atime, mtime)
  } catch (e) {
    throw new FileError(e.message, { operation: 'futimesSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function link(src, dst, cb) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.link(req.handle, src, dst)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'link', code: e.code, path: src, destination: dst })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function linkSync(src, dst) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  try {
    binding.linkSync(req.handle, src, dst)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'linkSync',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }
}

async function mkdir(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = { mode: 0o777 }
  }

  if (typeof opts === 'number') opts = { mode: opts }
  else if (!opts) opts = {}

  const mode = typeof opts.mode === 'number' ? opts.mode : 0o777

  filepath = toNamespacedPath(filepath)

  if (opts.recursive) {
    let err = null
    try {
      try {
        await mkdir(filepath, { mode })
      } catch (err) {
        if (err.code !== 'ENOENT') {
          if (!(await stat(filepath)).isDirectory()) throw err
        } else {
          while (filepath.endsWith(path.sep)) filepath = filepath.slice(0, -1)
          const i = filepath.lastIndexOf(path.sep)
          if (i <= 0) throw err

          await mkdir(filepath.slice(0, i), { mode, recursive: true })

          try {
            await mkdir(filepath, { mode })
          } catch (err) {
            if (!(await stat(filepath)).isDirectory()) throw err
          }
        }
      }
    } catch (e) {
      err = e
    }

    return done(err, cb)
  }

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.mkdir(req.handle, filepath, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'mkdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function mkdirSync(filepath, opts) {
  if (typeof opts === 'number') opts = { mode: opts }
  else if (!opts) opts = {}

  const mode = typeof opts.mode === 'number' ? opts.mode : 0o777

  filepath = toNamespacedPath(filepath)

  if (opts.recursive) {
    try {
      mkdirSync(filepath, { mode })
    } catch (err) {
      if (err.code !== 'ENOENT') {
        if (!statSync(filepath).isDirectory()) throw err
      } else {
        while (filepath.endsWith(path.sep)) filepath = filepath.slice(0, -1)
        const i = filepath.lastIndexOf(path.sep)
        if (i <= 0) throw err

        mkdirSync(filepath.slice(0, i), { mode, recursive: true })

        try {
          mkdirSync(filepath, { mode })
        } catch (err) {
          if (!statSync(filepath).isDirectory()) throw err
        }
      }
    }

    return
  }

  const req = FileRequest.borrow()

  try {
    binding.mkdirSync(req.handle, filepath, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'mkdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function mkdtemp(prefix, cb) {
  prefix = toNamespacedPath(prefix)

  const req = FileRequest.borrow()

  let res
  let err = null
  try {
    binding.mkdtemp(req.handle, prefix + 'XXXXXX')

    await req

    res = binding.requestResultPath(req.handle)
  } catch (e) {
    err = new FileError(e.message, { operation: 'mkdtemp', code: e.code, path: prefix })
  } finally {
    req.return()
  }

  return done(err, res, cb)
}

function mkdtempSync(prefix) {
  prefix = toNamespacedPath(prefix)

  const req = FileRequest.borrow()

  try {
    binding.mkdtempSync(req.handle, prefix + 'XXXXXX')

    return binding.requestResultPath(req.handle)
  } catch (e) {
    throw new FileError(e.message, { operation: 'mkdtempSync', code: e.code, path: prefix })
  } finally {
    req.return()
  }
}

async function rmdir(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.rmdir(req.handle, filepath)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'rmdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function rmdirSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.rmdirSync(req.handle, filepath)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'rmdir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function rm(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  let err = null
  try {
    const st = await lstat(filepath)

    if (st.isDirectory()) {
      if (opts.recursive) {
        try {
          await rmdir(filepath)
        } catch (err) {
          if (err.code !== 'ENOTEMPTY') throw err

          const files = await readdir(filepath)

          for (const file of files) {
            await rm(filepath + path.sep + file, opts)
          }

          await rmdir(filepath)
        }
      } else {
        throw new FileError('is a directory', {
          operation: 'rm',
          code: 'EISDIR',
          path: filepath
        })
      }
    } else {
      await unlink(filepath)
    }
  } catch (e) {
    if (e.code !== 'ENOENT' || !opts.force) err = e
  }

  return done(err, cb)
}

function rmSync(filepath, opts) {
  if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  try {
    const st = lstatSync(filepath)

    if (st.isDirectory()) {
      if (opts.recursive) {
        try {
          rmdirSync(filepath)
        } catch (err) {
          if (err.code !== 'ENOTEMPTY') throw err

          const files = readdirSync(filepath)

          for (const file of files) {
            rmSync(filepath + path.sep + file, opts)
          }

          rmdirSync(filepath)
        }
      } else {
        throw new FileError('is a directory', {
          operation: 'rm',
          code: 'EISDIR',
          path: filepath
        })
      }
    } else {
      unlinkSync(filepath)
    }
  } catch (err) {
    if (err.code !== 'ENOENT' || !opts.force) throw err
  }
}

async function unlink(filepath, cb) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.unlink(req.handle, filepath)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'unlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function unlinkSync(filepath) {
  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.unlinkSync(req.handle, filepath)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'unlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function rename(src, dst, cb) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.rename(req.handle, src, dst)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'rename',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function renameSync(src, dst) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  try {
    binding.renameSync(req.handle, src, dst)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'rename',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }
}

async function copyFile(src, dst, mode = 0, cb) {
  if (typeof mode === 'function') {
    cb = mode
    mode = 0
  }

  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.copyfile(req.handle, src, dst, mode)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'copyfile',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function copyFileSync(src, dst, mode = 0) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const req = FileRequest.borrow()

  try {
    binding.copyfileSync(req.handle, src, dst, mode)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'copyfile',
      code: e.code,
      path: src,
      destination: dst
    })
  } finally {
    req.return()
  }
}

async function cp(src, dst, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (!opts) opts = {}

  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  let err = null
  try {
    const st = await lstat(src)

    if (st.isDirectory()) {
      if (opts.recursive !== true) {
        throw new FileError('is a directory', { operation: 'cp', code: 'EISDIR', path: src })
      }

      try {
        await lstat(dst)
      } catch (e) {
        if (e.code !== 'ENOENT') throw e

        await mkdir(dst, { mode: st.mode, recursive: true })
      }

      const dir = await opendir(src)
      for await (const { name } of dir) {
        await cp(path.join(src, name), path.join(dst, name), opts)
      }
    } else if (st.isFile()) {
      await copyFile(src, dst)
      await chmod(dst, st.mode)
    }
  } catch (e) {
    err = e
  }

  return done(err, cb)
}

function cpSync(src, dst, opts = {}) {
  src = toNamespacedPath(src)
  dst = toNamespacedPath(dst)

  const st = lstatSync(src)

  if (st.isDirectory()) {
    if (opts.recursive !== true) {
      throw new FileError('is a directory', { operation: 'cp', code: 'EISDIR', path: src })
    }

    try {
      lstatSync(dst)
    } catch (e) {
      if (e.code !== 'ENOENT') throw e

      mkdirSync(dst, { mode: st.mode, recursive: true })
    }

    const dir = opendirSync(src)
    for (const { name } of dir) {
      cpSync(path.join(src, name), path.join(dst, name), opts)
    }
  } else if (st.isFile()) {
    copyFileSync(src, dst)
    chmodSync(dst, st.mode)
  }
}

async function realpath(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let res
  let err = null
  try {
    binding.realpath(req.handle, filepath)

    await req

    res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'realpath',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, res, cb)
}

function realpathSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.realpathSync(req.handle, filepath)

    let res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)

    return res
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'realpath',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function readlink(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let res
  let err = null
  try {
    binding.readlink(req.handle, filepath)

    await req

    res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'readlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, res, cb)
}

function readlinkSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'utf8' } = opts

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.readlinkSync(req.handle, filepath)

    let res = Buffer.from(binding.requestResultString(req.handle))

    if (encoding !== 'buffer') res = res.toString(encoding)

    return res
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'readlink',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function fsync(fd, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fsync(req.handle, fd)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fsync', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fsyncSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.fsyncSync(req.handle, fd)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fsyncSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

async function fdatasync(fd, cb) {
  const req = FileRequest.borrow()

  let err = null
  try {
    binding.fdatasync(req.handle, fd)

    await req
  } catch (e) {
    err = new FileError(e.message, { operation: 'fdatasync', code: e.code, fd })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function fdatasyncSync(fd) {
  const req = FileRequest.borrow()

  try {
    binding.fdatasyncSync(req.handle, fd)
  } catch (e) {
    throw new FileError(e.message, { operation: 'fdatasyncSync', code: e.code, fd })
  } finally {
    req.return()
  }
}

function normalizeSymlinkTarget(target, type, filepath) {
  if (isWindows) {
    if (type === constants.UV_FS_SYMLINK_JUNCTION) target = path.resolve(filepath, '..', target)

    if (path.isAbsolute(target)) return path.toNamespacedPath(target)

    return target.replace(/\//g, path.sep)
  }

  return target
}

async function symlink(target, filepath, type, cb) {
  if (typeof type === 'function') {
    cb = type
    type = null
  }

  filepath = toNamespacedPath(filepath)

  if (typeof type === 'string') {
    switch (type) {
      case 'dir':
        type = constants.UV_FS_SYMLINK_DIR
        break
      case 'junction':
        type = constants.UV_FS_SYMLINK_JUNCTION
        break
      case 'file':
      default:
        type = 0
        break
    }
  } else if (typeof type !== 'number') {
    if (isWindows) {
      target = path.resolve(filepath, '..', target)

      try {
        type = (await stat(target)).isDirectory()
          ? constants.UV_FS_SYMLINK_DIR
          : constants.UV_FS_SYMLINK_JUNCTION
      } catch {
        type = 0
      }
    } else {
      type = 0
    }
  }

  target = normalizeSymlinkTarget(target, type, filepath)

  const req = FileRequest.borrow()

  let err = null
  try {
    binding.symlink(req.handle, target, filepath, type)

    await req
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'symlink',
      code: e.code,
      path: target,
      destination: filepath
    })
  } finally {
    req.return()
  }

  return done(err, cb)
}

function symlinkSync(target, filepath, type) {
  filepath = toNamespacedPath(filepath)

  if (typeof type === 'string') {
    switch (type) {
      case 'dir':
        type = constants.UV_FS_SYMLINK_DIR
        break
      case 'junction':
        type = constants.UV_FS_SYMLINK_JUNCTION
        break
      case 'file':
      default:
        type = 0
        break
    }
  } else if (typeof type !== 'number') {
    if (isWindows) {
      target = path.resolve(filepath, '..', target)

      try {
        type = statSync(target).isDirectory()
          ? constants.UV_FS_SYMLINK_DIR
          : constants.UV_FS_SYMLINK_JUNCTION
      } catch {
        type = 0
      }
    } else {
      type = 0
    }
  }

  target = normalizeSymlinkTarget(target, type, filepath)

  const req = FileRequest.borrow()

  try {
    binding.symlinkSync(req.handle, target, filepath, type)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'symlink',
      code: e.code,
      path: target,
      destination: filepath
    })
  } finally {
    req.return()
  }
}

async function opendir(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  let dir
  let err = null
  try {
    binding.opendir(req.handle, filepath)

    await req

    dir = new Dir(filepath, binding.requestResultDir(req.handle), opts)
  } catch (e) {
    err = new FileError(e.message, {
      operation: 'opendir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }

  return done(err, dir, cb)
}

function opendirSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  const req = FileRequest.borrow()

  try {
    binding.opendirSync(req.handle, filepath)

    return new Dir(filepath, binding.requestResultDir(req.handle), opts)
  } catch (e) {
    throw new FileError(e.message, {
      operation: 'opendir',
      code: e.code,
      path: filepath
    })
  } finally {
    req.return()
  }
}

async function readdir(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { withFileTypes = false, recursive = false } = opts

  filepath = toNamespacedPath(filepath)

  const queue = [filepath]
  let result = []
  let err = null
  try {
    while (queue.length !== 0) {
      const dir = await opendir(queue.pop())

      for await (const entry of dir) {
        const entryPath = path.join(entry.parentPath, entry.name)

        if (withFileTypes) {
          result.push(entry)
        } else {
          result.push(path.relative(filepath, entryPath))
        }

        if (recursive && entry.isDirectory()) queue.push(entryPath)
      }
    }
  } catch (e) {
    result = []
    err = e
  }

  return done(err, result, cb)
}

function readdirSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { withFileTypes = false, recursive = false } = opts

  filepath = toNamespacedPath(filepath)

  const queue = [filepath]
  const result = []

  while (queue.length !== 0) {
    const dir = opendirSync(queue.pop(), opts)

    for (const entry of dir) {
      const entryPath = path.join(entry.parentPath, entry.name)

      if (withFileTypes) {
        result.push(entry)
      } else {
        result.push(path.relative(filepath, entryPath))
      }

      if (recursive && entry.isDirectory()) queue.push(entryPath)
    }
  }

  return result
}

async function readFile(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'buffer' } = opts

  let fd = -1
  let buffer = null
  let err = null
  try {
    fd = await open(filepath, opts.flag || 'r')

    const st = await fstat(fd)

    let len = 0

    if (st.size === 0) {
      const buffers = []

      while (true) {
        buffer = Buffer.allocUnsafe(8192)
        const r = await read(fd, buffer)
        len += r
        if (r === 0) break
        buffers.push(buffer.subarray(0, r))
      }

      buffer = Buffer.concat(buffers)
    } else {
      buffer = Buffer.allocUnsafe(st.size)

      while (true) {
        const r = await read(fd, len ? buffer.subarray(len) : buffer)
        len += r
        if (r === 0 || len === buffer.byteLength) break
      }

      if (len !== buffer.byteLength) buffer = buffer.subarray(0, len)
    }

    if (encoding !== 'buffer') buffer = buffer.toString(encoding)
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) await close(fd)
  }

  return done(err, buffer, cb)
}

function readFileSync(filepath, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  const { encoding = 'buffer' } = opts

  let fd = -1
  try {
    fd = openSync(filepath, opts.flag || 'r')

    const st = fstatSync(fd)

    let buffer
    let len = 0

    if (st.size === 0) {
      const buffers = []

      while (true) {
        buffer = Buffer.allocUnsafe(8192)
        const r = readSync(fd, buffer)
        len += r
        if (r === 0) break
        buffers.push(buffer.subarray(0, r))
      }

      buffer = Buffer.concat(buffers)
    } else {
      buffer = Buffer.allocUnsafe(st.size)

      while (true) {
        const r = readSync(fd, len ? buffer.subarray(len) : buffer)
        len += r
        if (r === 0 || len === buffer.byteLength) break
      }

      if (len !== buffer.byteLength) buffer = buffer.subarray(0, len)
    }

    if (encoding !== 'buffer') buffer = buffer.toString(encoding)

    return buffer
  } finally {
    if (fd !== -1) closeSync(fd)
  }
}

async function writeFile(filepath, data, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (typeof data === 'string') data = Buffer.from(data, opts.encoding)

  let fd = -1
  let len = 0
  let err = null
  try {
    fd = await open(filepath, opts.flag || 'w', opts.mode || 0o666)

    while (true) {
      len += await write(fd, len ? data.subarray(len) : data)
      if (len === data.byteLength) break
    }
  } catch (e) {
    err = e
  } finally {
    if (fd !== -1) await close(fd)
  }

  return done(err, len, cb)
}

function writeFileSync(filepath, data, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (typeof data === 'string') data = Buffer.from(data, opts.encoding)

  let fd = -1
  try {
    fd = openSync(filepath, opts.flag || 'w', opts.mode || 0o666)

    let len = 0

    while (true) {
      len += writeSync(fd, len ? data.subarray(len) : data)
      if (len === data.byteLength) break
    }
  } finally {
    if (fd !== -1) closeSync(fd)
  }
}

function appendFile(filepath, data, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (!opts.flag) opts = { ...opts, flag: 'a' }

  return writeFile(filepath, data, opts, cb)
}

function appendFileSync(filepath, data, opts) {
  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  if (!opts.flag) opts = { ...opts, flag: 'a' }

  return writeFileSync(filepath, data, opts)
}

function watch(filepath, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (typeof opts === 'string') opts = { encoding: opts }
  else if (!opts) opts = {}

  filepath = toNamespacedPath(filepath)

  return new Watcher(filepath, opts, cb)
}

class Stats {
  constructor(
    dev,
    mode,
    nlink,
    uid,
    gid,
    rdev,
    blksize,
    ino,
    size,
    blocks,
    atimeMs,
    mtimeMs,
    ctimeMs,
    birthtimeMs
  ) {
    this.dev = dev
    this.mode = mode
    this.nlink = nlink
    this.uid = uid
    this.gid = gid
    this.rdev = rdev
    this.blksize = blksize
    this.ino = ino
    this.size = size
    this.blocks = blocks
    this.atimeMs = atimeMs
    this.mtimeMs = mtimeMs
    this.ctimeMs = ctimeMs
    this.birthtimeMs = birthtimeMs
    this.atime = new Date(atimeMs)
    this.mtime = new Date(mtimeMs)
    this.ctime = new Date(ctimeMs)
    this.birthtime = new Date(birthtimeMs)
  }

  isDirectory() {
    return (this.mode & constants.S_IFMT) === constants.S_IFDIR
  }

  isFile() {
    return (this.mode & constants.S_IFMT) === constants.S_IFREG
  }

  isBlockDevice() {
    return (this.mode & constants.S_IFMT) === constants.S_IFBLK
  }

  isCharacterDevice() {
    return (this.mode & constants.S_IFMT) === constants.S_IFCHR
  }

  isFIFO() {
    return (this.mode & constants.S_IFMT) === constants.S_IFIFO
  }

  isSymbolicLink() {
    return (this.mode & constants.S_IFMT) === constants.S_IFLNK
  }

  isSocket() {
    return (this.mode & constants.S_IFMT) === constants.S_IFSOCK
  }
}

class StatFs {
  constructor(type, bsize, blocks, bfree, bavail, files, ffree) {
    this.type = type
    this.bsize = bsize
    this.blocks = blocks
    this.bfree = bfree
    this.bavail = bavail
    this.files = files
    this.ffree = ffree
  }
}

class Dir {
  constructor(path, handle, opts = {}) {
    const { encoding = 'utf8', bufferSize = 32 } = opts

    this.path = path

    this._encoding = encoding
    this._capacity = bufferSize
    this._buffer = new FIFO()
    this._ended = false
    this._handle = handle
  }

  async read(cb) {
    if (this._buffer.length) return ok(this._buffer.shift(), cb)
    if (this._ended) return ok(null, cb)

    const req = FileRequest.borrow()

    let entries
    let err = null
    try {
      req.retain(binding.readdir(req.handle, this._handle, this._capacity))

      await req

      entries = binding.requestResultDirents(req.handle)
    } catch (e) {
      err = new FileError(e.message, {
        operation: 'readdir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    if (err) return fail(err, cb)

    if (entries.length === 0) {
      this._ended = true

      return ok(null, cb)
    }

    for (const entry of entries) {
      let name = Buffer.from(entry.name)

      if (this._encoding !== 'buffer') name = name.toString(this._encoding)

      this._buffer.push(new Dirent(this.path, name, entry.type))
    }

    return ok(this._buffer.shift(), cb)
  }

  readSync() {
    if (this._buffer.length) return this._buffer.shift()
    if (this._ended) return null

    const req = FileRequest.borrow()

    let entries
    try {
      req.retain(binding.readdirSync(req.handle, this._handle, this._capacity))

      entries = binding.requestResultDirents(req.handle)
    } catch (e) {
      throw new FileError(e.message, {
        operation: 'readdir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    if (entries.length === 0) {
      this._ended = true

      return null
    }

    for (const entry of entries) {
      let name = Buffer.from(entry.name)

      if (this._encoding !== 'buffer') name = name.toString(this._encoding)

      this._buffer.push(new Dirent(this.path, name, entry.type))
    }

    return this._buffer.shift()
  }

  async close(cb) {
    const req = FileRequest.borrow()

    let err = null
    try {
      binding.closedir(req.handle, this._handle)

      await req
    } catch (e) {
      err = new FileError(e.message, {
        operation: 'closedir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    this._handle = null

    return done(err, cb)
  }

  closeSync() {
    const req = FileRequest.borrow()

    try {
      binding.closedirSync(req.handle, this._handle)
    } catch (e) {
      throw new FileError(e.message, {
        operation: 'closedir',
        code: e.code,
        path: this.path
      })
    } finally {
      req.return()
    }

    this._handle = null
  }

  [Symbol.dispose]() {
    this.closeSync()
  }

  async [Symbol.asyncDispose]() {
    await this.close()
  }

  *[Symbol.iterator]() {
    while (true) {
      const entry = this.readSync()
      if (entry === null) break
      yield entry
    }

    this.closeSync()
  }

  async *[Symbol.asyncIterator]() {
    while (true) {
      const entry = await this.read()
      if (entry === null) break
      yield entry
    }

    await this.close()
  }
}

class Dirent {
  constructor(parentPath, name, type) {
    this.parentPath = parentPath
    this.name = name
    this.type = type
  }

  isFile() {
    return this.type === constants.UV_DIRENT_FILE
  }

  isDirectory() {
    return this.type === constants.UV_DIRENT_DIR
  }

  isSymbolicLink() {
    return this.type === constants.UV_DIRENT_LINK
  }

  isFIFO() {
    return this.type === constants.UV_DIRENT_FIFO
  }

  isSocket() {
    return this.type === constants.UV_DIRENT_SOCKET
  }

  isCharacterDevice() {
    return this.type === constants.UV_DIRENT_CHAR
  }

  isBlockDevice() {
    return this.type === constants.UV_DIRENT_BLOCK
  }
}

class FileReadStream extends Readable {
  constructor(path, opts = {}) {
    const { eagerOpen = true } = opts

    super({ eagerOpen, ...opts })

    this.path = path
    this.fd = typeof opts.fd === 'number' ? opts.fd : -1
    this.flags = opts.flags || 'r'
    this.mode = opts.mode || 0o666

    this._offset = opts.start || 0
    this._missing = 0

    if (opts.length) {
      this._missing = opts.length
    } else if (typeof opts.end === 'number') {
      this._missing = opts.end - this._offset + 1
    } else {
      this._missing = -1
    }
  }

  async _open(cb) {
    let err

    if (this.fd === -1) {
      err = null
      try {
        this.fd = await open(this.path, this.flags, this.mode)
      } catch (e) {
        err = e
      }

      if (err) return cb(err)
    }

    let st
    err = null
    try {
      st = await fstat(this.fd)
    } catch (e) {
      err = e
    }

    if (err) return cb(err)

    if (this._missing === -1) this._missing = st.size

    if (st.size < this._offset) {
      this._offset = st.size
      this._missing = 0
    } else if (st.size < this._offset + this._missing) {
      this._missing = st.size - this._offset
    }

    cb(null)
  }

  async _read(size) {
    if (this._missing <= 0) return this.push(null)

    const data = Buffer.allocUnsafe(Math.min(this._missing, size))

    let len
    let err = null
    try {
      len = await read(this.fd, data, 0, data.byteLength, this._offset)
    } catch (e) {
      err = e
    }

    if (err) return this.destroy(err)

    if (len === 0) return this.push(null)

    if (this._missing < len) len = this._missing

    this._missing -= len
    this._offset += len

    this.push(data.subarray(0, len))
  }

  async _destroy(err, cb) {
    if (this.fd === -1) return cb(err)

    try {
      await close(this.fd)
    } catch (e) {
      err = err || e
    }

    cb(err)
  }
}

class FileWriteStream extends Writable {
  constructor(path, opts = {}) {
    const { eagerOpen = true } = opts

    super({ eagerOpen, ...opts })

    this.path = path
    this.fd = typeof opts.fd === 'number' ? opts.fd : -1
    this.flags = opts.flags || 'w'
    this.mode = opts.mode || 0o666
  }

  async _open(cb) {
    if (this.fd !== -1) return cb(null)

    let err = null
    try {
      this.fd = await open(this.path, this.flags, this.mode)
    } catch (e) {
      err = e
    }

    cb(err)
  }

  async _writev(batch, cb) {
    let err = null
    try {
      await writev(
        this.fd,
        batch.map(({ chunk }) => chunk)
      )
    } catch (e) {
      err = e
    }

    cb(err)
  }

  async _destroy(err, cb) {
    if (this.fd === -1) return cb(err)

    try {
      await close(this.fd)
    } catch (e) {
      err = err || e
    }

    cb(err)
  }
}

class Watcher extends EventEmitter {
  constructor(path, opts, onchange) {
    if (typeof opts === 'function') {
      onchange = opts
      opts = {}
    }

    if (!opts) opts = {}

    const { persistent = true, recursive = false, encoding = 'utf8' } = opts

    super()

    this._closed = false
    this._encoding = encoding
    this._handle = binding.watcherInit(path, recursive, this, this._onevent, this._onclose)

    if (!persistent) this.unref()

    if (onchange) this.on('change', onchange)
  }

  close() {
    if (this._closed) return
    this._closed = true

    binding.watcherClose(this._handle)
  }

  ref() {
    if (this._handle) binding.watcherRef(this._handle)
    return this
  }

  unref() {
    if (this._handle) binding.watcherUnref(this._handle)
    return this
  }

  [Symbol.asyncIterator]() {
    const buffer = []
    let done = false
    let error = null
    let next = null

    this.on('change', (eventType, filename) => {
      if (next) {
        next.resolve({ done: false, value: { eventType, filename } })
        next = null
      } else {
        buffer.push({ eventType, filename })
      }
    })
      .on('error', (err) => {
        done = true
        error = err

        if (next) {
          next.reject(error)
          next = null
        }
      })
      .on('close', () => {
        done = true

        if (next) {
          next.resolve({ done })
          next = null
        }
      })

    return {
      next: () =>
        new Promise((resolve, reject) => {
          if (error) return reject(error)

          if (buffer.length) return resolve({ done: false, value: buffer.shift() })

          if (done) return resolve({ done })

          next = { resolve, reject }
        })
    }
  }

  _onevent(err, events, filename) {
    if (err) {
      this.close()
      this.emit('error', err)
    } else {
      const path =
        this._encoding === 'buffer'
          ? Buffer.from(filename)
          : Buffer.from(filename).toString(this._encoding)

      if (events & binding.UV_RENAME) {
        this.emit('change', 'rename', path)
      }

      if (events & binding.UV_CHANGE) {
        this.emit('change', 'change', path)
      }
    }
  }

  _onclose() {
    this._handle = null

    this.emit('close')
  }
}

exports.access = access
exports.appendFile = appendFile
exports.chmod = chmod
exports.chown = chown
exports.close = close
exports.copyFile = copyFile
exports.cp = cp
exports.exists = exists
exports.fchmod = fchmod
exports.fchown = fchown
exports.fdatasync = fdatasync
exports.fstat = fstat
exports.fsync = fsync
exports.ftruncate = ftruncate
exports.futimes = futimes
exports.lchown = lchown
exports.lutimes = lutimes
exports.link = link
exports.lstat = lstat
exports.mkdir = mkdir
exports.mkdtemp = mkdtemp
exports.open = open
exports.opendir = opendir
exports.read = read
exports.readFile = readFile
exports.readdir = readdir
exports.readlink = readlink
exports.readv = readv
exports.realpath = realpath
exports.rename = rename
exports.rm = rm
exports.rmdir = rmdir
exports.stat = stat
exports.statfs = statfs
exports.symlink = symlink
exports.truncate = truncate
exports.unlink = unlink
exports.utimes = utimes
exports.watch = watch
exports.write = write
exports.writeFile = writeFile
exports.writev = writev

exports.accessSync = accessSync
exports.appendFileSync = appendFileSync
exports.chmodSync = chmodSync
exports.chownSync = chownSync
exports.closeSync = closeSync
exports.copyFileSync = copyFileSync
exports.cpSync = cpSync
exports.existsSync = existsSync
exports.fchmodSync = fchmodSync
exports.fchownSync = fchownSync
exports.fdatasyncSync = fdatasyncSync
exports.fstatSync = fstatSync
exports.fsyncSync = fsyncSync
exports.ftruncateSync = ftruncateSync
exports.futimesSync = futimesSync
exports.lchownSync = lchownSync
exports.lutimesSync = lutimesSync
exports.linkSync = linkSync
exports.lstatSync = lstatSync
exports.mkdirSync = mkdirSync
exports.mkdtempSync = mkdtempSync
exports.openSync = openSync
exports.opendirSync = opendirSync
exports.readFileSync = readFileSync
exports.readSync = readSync
exports.readdirSync = readdirSync
exports.readlinkSync = readlinkSync
exports.readvSync = readvSync
exports.realpathSync = realpathSync
exports.renameSync = renameSync
exports.rmSync = rmSync
exports.rmdirSync = rmdirSync
exports.statSync = statSync
exports.statfsSync = statfsSync
exports.symlinkSync = symlinkSync
exports.truncateSync = truncateSync
exports.unlinkSync = unlinkSync
exports.utimesSync = utimesSync
exports.writeFileSync = writeFileSync
exports.writeSync = writeSync
exports.writevSync = writevSync

exports.promises = require('./promises')

exports.Stats = Stats
exports.StatFs = StatFs
exports.Dir = Dir
exports.Dirent = Dirent
exports.Watcher = Watcher

exports.ReadStream = FileReadStream

exports.createReadStream = function createReadStream(path, opts) {
  return new FileReadStream(path, opts)
}

exports.WriteStream = FileWriteStream

exports.createWriteStream = function createWriteStream(path, opts) {
  return new FileWriteStream(path, opts)
}

function toNamespacedPath(filepath) {
  if (typeof filepath !== 'string') {
    if (isURL(filepath)) filepath = fileURLToPath(filepath)
    else filepath = filepath.toString()
  }

  return path.toNamespacedPath(filepath)
}

function toFlags(flags) {
  switch (flags) {
    case 'r':
      return constants.O_RDONLY
    case 'rs': // Fall through.
    case 'sr':
      return constants.O_RDONLY | constants.O_SYNC
    case 'r+':
      return constants.O_RDWR
    case 'rs+': // Fall through.
    case 'sr+':
      return constants.O_RDWR | constants.O_SYNC

    case 'w':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_WRONLY
    case 'wx': // Fall through.
    case 'xw':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_WRONLY | constants.O_EXCL

    case 'w+':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_RDWR
    case 'wx+': // Fall through.
    case 'xw+':
      return constants.O_TRUNC | constants.O_CREAT | constants.O_RDWR | constants.O_EXCL

    case 'a':
      return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY
    case 'ax': // Fall through.
    case 'xa':
      return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY | constants.O_EXCL
    case 'as': // Fall through.
    case 'sa':
      return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY | constants.O_SYNC

    case 'a+':
      return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR
    case 'ax+': // Fall through.
    case 'xa+':
      return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR | constants.O_EXCL
    case 'as+': // Fall through.
    case 'sa+':
      return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR | constants.O_SYNC
    default:
      return 0
  }
}

function toMode(mode) {
  return parseInt(mode, 8)
}
const binding = require('../binding')

module.exports = {
  O_RDWR: binding.O_RDWR,
  O_RDONLY: binding.O_RDONLY,
  O_WRONLY: binding.O_WRONLY,
  O_CREAT: binding.O_CREAT,
  O_TRUNC: binding.O_TRUNC,
  O_APPEND: binding.O_APPEND,

  F_OK: binding.F_OK || 0,
  R_OK: binding.R_OK || 0,
  W_OK: binding.W_OK || 0,
  X_OK: binding.X_OK || 0,

  S_IFMT: binding.S_IFMT,
  S_IFREG: binding.S_IFREG,
  S_IFDIR: binding.S_IFDIR,
  S_IFCHR: binding.S_IFCHR,
  S_IFLNK: binding.S_IFLNK,
  S_IFBLK: binding.S_IFBLK || 0,
  S_IFIFO: binding.S_IFIFO || 0,
  S_IFSOCK: binding.S_IFSOCK || 0,

  S_IRUSR: binding.S_IRUSR || 0,
  S_IWUSR: binding.S_IWUSR || 0,
  S_IXUSR: binding.S_IXUSR || 0,
  S_IRGRP: binding.S_IRGRP || 0,
  S_IWGRP: binding.S_IWGRP || 0,
  S_IXGRP: binding.S_IXGRP || 0,
  S_IROTH: binding.S_IROTH || 0,
  S_IWOTH: binding.S_IWOTH || 0,
  S_IXOTH: binding.S_IXOTH || 0,

  UV_DIRENT_UNKNOWN: binding.UV_DIRENT_UNKNOWN,
  UV_DIRENT_FILE: binding.UV_DIRENT_FILE,
  UV_DIRENT_DIR: binding.UV_DIRENT_DIR,
  UV_DIRENT_LINK: binding.UV_DIRENT_LINK,
  UV_DIRENT_FIFO: binding.UV_DIRENT_FIFO,
  UV_DIRENT_SOCKET: binding.UV_DIRENT_SOCKET,
  UV_DIRENT_CHAR: binding.UV_DIRENT_CHAR,
  UV_DIRENT_BLOCK: binding.UV_DIRENT_BLOCK,

  COPYFILE_EXCL: binding.UV_FS_COPYFILE_EXCL,
  COPYFILE_FICLONE: binding.UV_FS_COPYFILE_FICLONE,
  COPYFILE_FICLONE_FORCE: binding.UV_FS_COPYFILE_FICLONE_FORCE,
  UV_FS_SYMLINK_DIR: binding.UV_FS_SYMLINK_DIR,
  UV_FS_SYMLINK_JUNCTION: binding.UV_FS_SYMLINK_JUNCTION
}
const os = require('bare-os')

module.exports = class FileError extends Error {
  constructor(msg, opts = {}) {
    const { code, operation = null, path = null, destination = null, fd = -1 } = opts

    if (operation !== null) msg += describe(operation, opts)

    super(`${code}: ${msg}`)

    this.code = code

    if (operation !== null) this.operation = operation
    if (path !== null) this.path = path
    if (destination !== null) this.destination = destination
    if (fd !== -1) this.fd = fd
  }

  get name() {
    return 'FileError'
  }

  // For Node.js compatibility
  get errno() {
    return os.constants.errnos[this.code]
  }

  // For Node.js compatibility
  get syscall() {
    return this.operation
  }

  // For Node.js compatibility
  get dest() {
    return this.destination
  }
}

function describe(operation, opts) {
  const { path = null, destination = null, fd = -1 } = opts

  let result = `, ${operation}`

  if (path !== null) {
    result += ` ${JSON.stringify(path)}`

    if (destination !== null) {
      result += ` -> ${JSON.stringify(destination)}`
    }
  } else if (fd !== -1) {
    result += ` ${fd}`
  }

  return result
}
{
  "name": "bare-fs",
  "version": "4.7.2",
  "description": "Native file system operations for Bare",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./promises": {
      "types": "./promises.d.ts",
      "default": "./promises.js"
    },
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "promises.js",
    "promises.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-fs.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-fs/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-fs#readme",
  "engines": {
    "bare": ">=1.16.0"
  },
  "dependencies": {
    "bare-events": "^2.5.4",
    "bare-path": "^3.0.0",
    "bare-stream": "^2.6.4",
    "bare-url": "^2.2.2",
    "fast-fifo": "^1.3.2"
  },
  "devDependencies": {
    "bare-buffer": "^3.0.2",
    "bare-crypto": "^1.11.2",
    "brittle": "^3.1.1",
    "cmake-bare": "^1.1.7",
    "lunte": "^1.6.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "bare-buffer": "*"
  },
  "peerDependenciesMeta": {
    "bare-buffer": {
      "optional": true
    }
  }
}
const EventEmitter = require('bare-events')
const fs = require('.')

class FileHandle extends EventEmitter {
  constructor(fd) {
    super()

    this.fd = fd
  }

  async close() {
    await fs.close(this.fd)

    this.fd = -1
    this.emit('close')
  }

  async read(buffer, ...args) {
    return {
      bytesRead: await fs.read(this.fd, buffer, ...args),
      buffer
    }
  }

  async readv(buffers, ...args) {
    return {
      bytesRead: await fs.readv(this.fd, buffers, ...args),
      buffers
    }
  }

  async write(buffer, ...args) {
    return {
      bytesWritten: await fs.write(this.fd, buffer, ...args),
      buffer
    }
  }

  async writev(buffers, ...args) {
    return {
      bytesWritten: await fs.writev(this.fd, buffers, ...args),
      buffers
    }
  }

  async stat() {
    return fs.fstat(this.fd)
  }

  async chmod(mode) {
    await fs.fchmod(this.fd, mode)
  }

  async chown(uid, gid) {
    await fs.fchown(this.fd, uid, gid)
  }

  async datasync() {
    return fs.fdatasync(this.fd)
  }

  async sync() {
    return fs.fsync(this.fd)
  }

  async truncate(len) {
    await fs.ftruncate(this.fd, len)
  }

  async utimes(atime, mtime) {
    await fs.futimes(this.fd, atime, mtime)
  }

  createReadStream(opts) {
    return fs.createReadStream(null, { ...opts, fd: this.fd })
  }

  createWriteStream(opts) {
    return fs.createWriteStream(null, { ...opts, fd: this.fd })
  }

  async [Symbol.asyncDispose]() {
    await this.close()
  }
}

exports.open = async function open(filepath, flags, mode) {
  return new FileHandle(await fs.open(filepath, flags, mode))
}

exports.access = fs.access
exports.appendFile = fs.appendFile
exports.chmod = fs.chmod
exports.chown = fs.chown
exports.constants = fs.constants
exports.copyFile = fs.copyFile
exports.cp = fs.cp
exports.lchown = fs.lchown
exports.lutimes = fs.lutimes
exports.link = fs.link
exports.lstat = fs.lstat
exports.mkdir = fs.mkdir
exports.mkdtemp = fs.mkdtemp
exports.opendir = fs.opendir
exports.readFile = fs.readFile
exports.readdir = fs.readdir
exports.readlink = fs.readlink
exports.realpath = fs.realpath
exports.rename = fs.rename
exports.rm = fs.rm
exports.rmdir = fs.rmdir
exports.stat = fs.stat
exports.statfs = fs.statfs
exports.truncate = fs.truncate
exports.symlink = fs.symlink
exports.unlink = fs.unlink
exports.utimes = fs.utimes
exports.watch = fs.watch
exports.writeFile = fs.writeFile
module.exports = require.addon()
const binding = require('./binding')

module.exports = exports = function hrtime(past) {
  let now = binding.hrtime()

  if (past) now -= BigInt(past[0]) * 1000000000n + BigInt(past[1])

  return [Number(now / 1000000000n), Number(now % 1000000000n)]
}

exports.bigint = function hrtime() {
  return binding.hrtime()
}
{
  "name": "bare-hrtime",
  "version": "2.1.1",
  "description": "High-resolution timers for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-hrtime.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-hrtime/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-hrtime#readme",
  "devDependencies": {
    "brittle": "^3.2.1",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.2",
    "prettier-config-standard": "^7.0.0"
  }
}
const errors = require('./lib/errors')

const constants = {
  REQUEST: 1,
  RESPONSE: 2,
  DATA: 3,
  END: 4
}

const TAB = 0x09
const LF = 0x0a
const CR = 0x0d
const SP = 0x20
const ZERO = 0x30
const NINE = 0x39
const UPPER_A = 0x41
const UPPER_F = 0x46
const UPPER_Z = 0x5a
const LOWER_A = 0x61
const LOWER_F = 0x66
const COLON = 0x3a

const MAX_CHUNK_SIZE_LENGTH = 16

// Header states
const FIRST_TOKEN = 0
const REQUEST_URL = 1
const REQUEST_VERSION = 2
const STATUS_CODE = 3
const STATUS_REASON = 4
const FIRST_LINE_LF = 5
const HEADER_START = 6
const HEADER_NAME = 7
const HEADER_VALUE_WS = 8
const HEADER_VALUE = 9
const HEADER_LINE_LF = 10
const HEADER_END_LF = 11

// Body states
const BODY = 12
const CHUNK_SIZE = 13
const CHUNK_SIZE_LF = 14
const CHUNK_DATA = 15
const CHUNK_EXTENSION = 16

// Trailing states
const LAST_CHUNK_LF = 17
const TRAILER_CR = 18
const TRAILER_LF = 19

module.exports = exports = class HTTPParser {
  constructor(opts = {}) {
    const { maxHeaderSize = 16384, maxHeadersCount = 2000 } = opts

    this._maxHeaderSize = maxHeaderSize
    this._maxHeadersCount = maxHeadersCount
    this._state = FIRST_TOKEN
    this._buffer = []
    this._bufferIndex = 0
    this._byteIndex = 0
    this._buffered = 0
    this._accumulator = []

    this._isResponse = false
    this._method = ''
    this._url = ''
    this._version = ''
    this._code = 0
    this._reason = ''

    this._headerName = ''
    this._headers = {}
    this._headerCount = 0
    this._headerSize = 0

    this._remaining = 0
  }

  *push(data, encoding) {
    if (typeof data === 'string') data = Buffer.from(data, encoding)

    this._buffer.push(data)
    this._buffered += data.byteLength

    yield* this._parse()

    this._compact()
  }

  end() {
    const buffers = this._buffer
    const bufferIndex = this._bufferIndex
    const byteIndex = this._byteIndex

    this._buffer = []
    this._bufferIndex = 0
    this._byteIndex = 0
    this._buffered = 0

    if (bufferIndex >= buffers.length) return Buffer.alloc(0)

    buffers[bufferIndex] = buffers[bufferIndex].subarray(byteIndex)

    const remaining = buffers.slice(bufferIndex)

    if (remaining.length === 0) return Buffer.alloc(0)
    if (remaining.length === 1) return remaining[0]

    return Buffer.concat(remaining)
  }

  _compact() {
    if (this._bufferIndex > 0) {
      this._buffer = this._buffer.slice(this._bufferIndex)
      this._bufferIndex = 0
    }

    if (this._byteIndex > 0 && this._buffer.length > 0) {
      this._buffer[0] = this._buffer[0].subarray(this._byteIndex)
      this._byteIndex = 0
    }
  }

  _consume(n) {
    this._buffered -= n

    const current = this._buffer[this._bufferIndex]

    if (this._byteIndex + n <= current.byteLength) {
      const slice = current.subarray(this._byteIndex, this._byteIndex + n)

      this._byteIndex += n

      if (this._byteIndex >= current.byteLength) {
        this._bufferIndex++
        this._byteIndex = 0
      }

      return slice
    }

    const result = Buffer.allocUnsafe(n)

    let written = 0

    while (written < n) {
      const buffer = this._buffer[this._bufferIndex]
      const available = buffer.byteLength - this._byteIndex
      const take = Math.min(available, n - written)

      buffer.copy(result, written, this._byteIndex, this._byteIndex + take)

      written += take

      this._byteIndex += take

      if (this._byteIndex >= buffer.byteLength) {
        this._bufferIndex++
        this._byteIndex = 0
      }
    }

    return result
  }

  _buildString() {
    const string = String.fromCharCode.apply(null, this._accumulator)

    this._accumulator = []

    return string
  }

  _checkHeaderSize() {
    if (++this._headerSize > this._maxHeaderSize) {
      throw errors.INVALID_MESSAGE('Header exceeds limit of ' + this._maxHeaderSize + ' bytes')
    }
  }

  _storeHeader(name, value) {
    let end = value.length

    while (end > 0 && (value.charCodeAt(end - 1) === SP || value.charCodeAt(end - 1) === TAB)) {
      end--
    }

    if (end < value.length) value = value.substring(0, end)

    this._headerCount++

    if (this._headerCount > this._maxHeadersCount) {
      throw errors.INVALID_MESSAGE('Header count exceeds limit of ' + this._maxHeadersCount)
    }

    switch (name) {
      case '__proto__':
      case 'constructor':
      case 'prototype':
        throw errors.INVALID_HEADER("Unsafe header name '" + name + "'")

      case 'host':
      case 'content-length':
      case 'transfer-encoding':
        if (name in this._headers) {
          throw errors.INVALID_HEADER("Duplicate header '" + name + "'")
        }

        this._headers[name] = value
        break

      default:
        const delimiter = name === 'cookie' ? '; ' : ', '

        if (name in this._headers) {
          this._headers[name] += delimiter + value
        } else {
          this._headers[name] = value
        }
    }
  }

  *_parse() {
    while (true) {
      if (this._state === BODY) {
        if (this._buffered === 0) return

        const available = Math.min(this._buffered, this._remaining)
        const data = this._consume(available)

        this._remaining -= available

        const ended = this._remaining === 0

        if (ended) this._state = FIRST_TOKEN

        yield { type: constants.DATA, data }

        if (ended) yield { type: constants.END }

        continue
      }

      if (this._state === CHUNK_DATA) {
        if (this._buffered < this._remaining) return

        const consumed = this._consume(this._remaining)

        if (consumed[this._remaining - 2] !== CR || consumed[this._remaining - 1] !== LF) {
          throw errors.INVALID_MESSAGE('Expected CRLF after chunk data')
        }

        const data = consumed.subarray(0, this._remaining - 2)

        this._remaining = 0
        this._state = CHUNK_SIZE

        yield { type: constants.DATA, data }

        continue
      }

      if (this._buffered === 0) return

      const byte = this._buffer[this._bufferIndex][this._byteIndex++]

      this._buffered--

      if (this._byteIndex >= this._buffer[this._bufferIndex].byteLength) {
        this._bufferIndex++
        this._byteIndex = 0
      }

      switch (this._state) {
        case FIRST_TOKEN: {
          this._checkHeaderSize()

          if (byte === SP) {
            const token = this._buildString()

            if (token.length === 0) throw errors.INVALID_MESSAGE()

            this._isResponse = token.startsWith('HTTP/')

            if (this._isResponse) {
              if (token !== 'HTTP/1.0' && token !== 'HTTP/1.1') {
                throw errors.INVALID_MESSAGE()
              }

              this._version = token
              this._state = STATUS_CODE
            } else {
              this._method = token
              this._state = REQUEST_URL
            }
          } else if (byte === CR) {
            throw errors.INVALID_MESSAGE()
          } else if (isTokenByte(byte)) {
            this._accumulator.push(byte)
          } else if (
            byte === 0x2f &&
            this._accumulator.length === 4 &&
            this._accumulator[0] === 0x48 &&
            this._accumulator[1] === 0x54 &&
            this._accumulator[2] === 0x54 &&
            this._accumulator[3] === 0x50
          ) {
            this._accumulator.push(byte)
          } else {
            throw errors.INVALID_MESSAGE()
          }

          break
        }

        case REQUEST_URL: {
          this._checkHeaderSize()

          if (byte === SP) {
            this._url = this._buildString()

            if (this._url.length === 0) throw errors.INVALID_MESSAGE()

            this._state = REQUEST_VERSION
          } else if (byte === CR) {
            throw errors.INVALID_MESSAGE()
          } else if (byte >= 0x21 && byte !== 0x7f) {
            this._accumulator.push(byte)
          } else {
            throw errors.INVALID_MESSAGE()
          }

          break
        }

        case REQUEST_VERSION: {
          this._checkHeaderSize()

          if (byte === CR) {
            this._version = this._buildString()

            if (this._version !== 'HTTP/1.0' && this._version !== 'HTTP/1.1') {
              throw errors.INVALID_MESSAGE()
            }

            this._state = FIRST_LINE_LF
          } else if (byte >= 0x21 && byte !== 0x7f) {
            this._accumulator.push(byte)
          } else {
            throw errors.INVALID_MESSAGE()
          }

          break
        }

        case STATUS_CODE: {
          this._checkHeaderSize()

          if (byte === SP) {
            if (this._accumulator.length === 0) throw errors.INVALID_MESSAGE()

            let code = 0

            for (let i = 0, n = this._accumulator.length; i < n; i++) {
              code = code * 10 + this._accumulator[i]
            }

            this._accumulator = []

            if (code < 100 || code > 999) throw errors.INVALID_MESSAGE()

            this._code = code
            this._state = STATUS_REASON
          } else if (byte >= ZERO && byte <= NINE) {
            this._accumulator.push(byte - ZERO)
          } else {
            throw errors.INVALID_MESSAGE()
          }

          break
        }

        case STATUS_REASON: {
          this._checkHeaderSize()

          if (byte === CR) {
            this._reason = this._buildString()
            this._state = FIRST_LINE_LF
          } else if (isFieldByte(byte)) {
            this._accumulator.push(byte)
          } else {
            throw errors.INVALID_MESSAGE()
          }

          break
        }

        case FIRST_LINE_LF: {
          if (byte !== LF) throw errors.INVALID_MESSAGE()

          this._headers = {}
          this._headerCount = 0
          this._state = HEADER_START

          break
        }

        case HEADER_START: {
          this._checkHeaderSize()

          if (byte === CR) {
            this._state = HEADER_END_LF
          } else if (byte !== COLON && isTokenByte(byte)) {
            this._accumulator.push(byte >= UPPER_A && byte <= UPPER_Z ? byte + 0x20 : byte)
            this._state = HEADER_NAME
          } else {
            throw errors.INVALID_HEADER()
          }

          break
        }

        case HEADER_NAME: {
          this._checkHeaderSize()

          if (byte === COLON) {
            this._headerName = this._buildString()
            this._state = HEADER_VALUE_WS
          } else if (byte !== COLON && isTokenByte(byte)) {
            this._accumulator.push(byte >= UPPER_A && byte <= UPPER_Z ? byte + 0x20 : byte)
          } else {
            throw errors.INVALID_HEADER()
          }

          break
        }

        case HEADER_VALUE_WS: {
          this._checkHeaderSize()

          if (byte === SP || byte === TAB) break

          if (byte === CR) {
            this._storeHeader(this._headerName, '')
            this._headerName = ''
            this._state = HEADER_LINE_LF

            break
          }

          if (!isFieldByte(byte)) throw errors.INVALID_HEADER()

          this._accumulator.push(byte)
          this._state = HEADER_VALUE

          break
        }

        case HEADER_VALUE: {
          this._checkHeaderSize()

          if (byte === CR) {
            this._storeHeader(this._headerName, this._buildString())
            this._headerName = ''
            this._state = HEADER_LINE_LF
          } else if (isFieldByte(byte)) {
            this._accumulator.push(byte)
          } else {
            throw errors.INVALID_HEADER()
          }

          break
        }

        case HEADER_LINE_LF: {
          if (byte !== LF) throw errors.INVALID_HEADER()

          this._state = HEADER_START

          break
        }

        case HEADER_END_LF: {
          if (byte !== LF) throw errors.INVALID_MESSAGE()

          const headers = this._headers

          if (this._isResponse) {
            yield {
              type: constants.RESPONSE,
              version: this._version,
              code: this._code,
              reason: this._reason,
              headers
            }
          } else {
            if (this._version === 'HTTP/1.1' && !('host' in headers)) {
              throw errors.INVALID_HEADER("Header 'Host' is missing")
            }

            yield {
              type: constants.REQUEST,
              version: this._version,
              method: this._method,
              url: this._url,
              headers
            }
          }

          const transferEncoding = headers['transfer-encoding']
          const contentLength = headers['content-length']

          const encodings = transferEncoding ? transferEncoding.split(',') : null

          const lastEncoding = encodings
            ? encodings[encodings.length - 1].trim().toLowerCase()
            : null

          if (lastEncoding === 'chunked') {
            if (contentLength) {
              throw errors.INVALID_MESSAGE(
                "Conflicting 'Content-Length' and 'Transfer-Encoding' headers"
              )
            }

            this._state = CHUNK_SIZE
            this._headerSize = 0

            continue
          }

          if (contentLength) {
            if (contentLength.length === 0) throw errors.INVALID_CONTENT_LENGTH()

            let length = 0

            for (let i = 0, n = contentLength.length; i < n; i++) {
              const c = contentLength.charCodeAt(i)

              if (c < ZERO || c > NINE) throw errors.INVALID_CONTENT_LENGTH()

              length = length * 10 + (c - ZERO)
            }

            if (!Number.isSafeInteger(length) || length < 0) {
              throw errors.INVALID_CONTENT_LENGTH()
            }

            if (length === 0) {
              this._state = FIRST_TOKEN
              this._headerSize = 0

              yield { type: constants.END }
            } else {
              this._state = BODY
              this._remaining = length
              this._headerSize = 0
            }
          } else {
            this._state = FIRST_TOKEN
            this._headerSize = 0

            yield { type: constants.END }
          }

          break
        }

        case CHUNK_SIZE: {
          if (byte === CR || byte === 0x3b) {
            if (this._accumulator.length === 0) throw errors.INVALID_CHUNK_LENGTH()

            let length = 0

            for (let i = 0, n = this._accumulator.length; i < n; i++) {
              length = length * 16 + this._accumulator[i]
            }

            this._accumulator = []

            if (!Number.isSafeInteger(length)) throw errors.INVALID_CHUNK_LENGTH()

            if (byte === 0x3b) {
              this._remaining = length
              this._state = CHUNK_EXTENSION
            } else if (length === 0) {
              this._state = LAST_CHUNK_LF
            } else {
              this._remaining = length + 2
              this._state = CHUNK_SIZE_LF
            }
          } else if (isHex(byte)) {
            if (this._accumulator.length >= MAX_CHUNK_SIZE_LENGTH) {
              throw errors.INVALID_CHUNK_LENGTH()
            }

            this._accumulator.push(hexValue(byte))
          } else {
            throw errors.INVALID_CHUNK_LENGTH()
          }

          break
        }

        case CHUNK_EXTENSION: {
          this._checkHeaderSize()

          if (byte === CR) {
            if (this._remaining === 0) {
              this._state = LAST_CHUNK_LF
            } else {
              this._remaining += 2
              this._state = CHUNK_SIZE_LF
            }
          } else if (!isFieldByte(byte)) {
            throw errors.INVALID_CHUNK_LENGTH()
          }

          break
        }

        case CHUNK_SIZE_LF: {
          if (byte !== LF) throw errors.INVALID_CHUNK_LENGTH()

          this._state = CHUNK_DATA

          break
        }

        case LAST_CHUNK_LF: {
          if (byte !== LF) throw errors.INVALID_CHUNK_LENGTH()

          this._state = TRAILER_CR

          break
        }

        case TRAILER_CR: {
          if (byte !== CR) throw errors.INVALID_MESSAGE()

          this._state = TRAILER_LF

          break
        }

        case TRAILER_LF: {
          if (byte !== LF) throw errors.INVALID_MESSAGE()

          this._state = FIRST_TOKEN
          this._headerSize = 0

          yield { type: constants.END }

          break
        }

        default:
          throw errors.INVALID_MESSAGE()
      }
    }
  }
}

exports.constants = constants

const TOKEN_BYTES = Buffer.from([
  // 0x00-0x1f (control characters) + 0x20 (space)
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  // 0x21-0x41: ! " # $ % & ' ( ) * + , - . / 0-9 : ; < = > ? @ A
  1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1,
  // 0x42-0x62: B-Z [ \ ] ^ _ ` a b
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1,
  // 0x63-0x7f: c-z { | } ~ DEL
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0
])

function isTokenByte(b) {
  return TOKEN_BYTES[b] === 1
}

function isFieldByte(b) {
  return b === TAB || (b >= 0x20 && b <= 0x7e)
}

function isHex(b) {
  return (
    (b >= ZERO && b <= NINE) || (b >= UPPER_A && b <= UPPER_F) || (b >= LOWER_A && b <= LOWER_F)
  )
}

function hexValue(b) {
  if (b >= ZERO && b <= NINE) return b - ZERO
  if (b >= UPPER_A && b <= UPPER_F) return b - UPPER_A + 10
  return b - LOWER_A + 10
}
module.exports = class HTTPParserError extends Error {
  constructor(msg, fn = HTTPParserError, code = fn.name) {
    super(`${code}: ${msg}`)

    this.code = code

    if (Error.captureStackTrace) Error.captureStackTrace(this, fn)
  }

  get name() {
    return 'HTTPParserError'
  }

  static INVALID_MESSAGE(msg = 'Invalid HTTP message') {
    return new HTTPParserError(msg, HTTPParserError.INVALID_MESSAGE)
  }

  static INVALID_HEADER(msg = 'Invalid HTTP header') {
    return new HTTPParserError(msg, HTTPParserError.INVALID_HEADER)
  }

  static INVALID_CONTENT_LENGTH(msg = 'Invalid HTTP Content-Length') {
    return new HTTPParserError(msg, HTTPParserError.INVALID_CONTENT_LENGTH)
  }

  static INVALID_CHUNK_LENGTH(msg = 'Invalid HTTP chunk length') {
    return new HTTPParserError(msg, HTTPParserError.INVALID_CHUNK_LENGTH)
  }
}
{
  "name": "bare-http-parser",
  "version": "1.1.3",
  "description": "Streaming HTTP request and response parser for Bare",
  "exports": {
    "./package": "./package.json",
    ".": "./index.js",
    "./errors": "./lib/errors.js"
  },
  "files": [
    "index.js",
    "lib"
  ],
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-http-parser.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-http-parser/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-http-parser#readme",
  "devDependencies": {
    "brittle": "^3.3.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  }
}
exports.IncomingMessage = require('./lib/incoming-message')
exports.OutgoingMessage = require('./lib/outgoing-message')

exports.Agent = require('./lib/agent')
exports.globalAgent = exports.Agent.global

exports.Server = require('./lib/server')
exports.ServerResponse = require('./lib/server-response')
exports.ServerConnection = require('./lib/server-connection')

exports.ClientRequest = require('./lib/client-request')
exports.ClientConnection = require('./lib/client-connection')

exports.constants = require('./lib/constants')
exports.errors = require('./lib/errors')

exports.METHODS = Object.values(exports.constants.method) // For Node.js compatibility
exports.STATUS_CODES = exports.constants.status // For Node.js compatibility

exports.createServer = function createServer(opts, onrequest) {
  return new exports.Server(opts, onrequest)
}

exports.request = function request(url, opts, onresponse) {
  if (typeof opts === 'function') {
    onresponse = opts
    opts = {}
  }

  if (typeof url === 'string') url = new URL(url)

  if (isURL(url)) {
    opts = opts ? { ...url, ...opts } : { ...url }

    opts.host = url.hostname
    opts.path = url.pathname + url.search
    opts.port = url.port ? parseInt(url.port, 10) : defaultPort(url)
  } else {
    opts = url ? { ...url } : {}

    // For Node.js compatibility
    opts.host = opts.hostname || opts.host
    opts.port = typeof opts.port === 'string' ? parseInt(opts.port, 10) : opts.port
  }

  return new exports.ClientRequest(opts, onresponse)
}

exports.get = function get(url, opts, onresponse) {
  const req = exports.request(url, opts, onresponse)
  req.end()
  return req
}

// https://url.spec.whatwg.org/#default-port
function defaultPort(url) {
  switch (url.protocol) {
    case 'ftp:':
      return 21
    case 'http:':
    case 'ws:':
      return 80
    case 'https:':
    case 'wss:':
      return 443
  }

  return null
}

// https://url.spec.whatwg.org/#api
function isURL(url) {
  return (
    url !== null &&
    typeof url === 'object' &&
    typeof url.protocol === 'string' &&
    typeof url.hostname === 'string' &&
    typeof url.pathname === 'string' &&
    typeof url.search === 'string'
  )
}
const EventEmitter = require('bare-events')
const tcp = require('bare-tcp')
const HTTPClientConnection = require('./client-connection')
const errors = require('./errors')

class HTTPSocketSet {
  constructor() {
    this._sockets = new Map()
    this._size = 0
  }

  get size() {
    return this._size
  }

  add(name, socket) {
    const sockets = this._sockets.get(name)

    this._size++

    if (sockets === undefined) this._sockets.set(name, [socket])
    else sockets.push(socket)
  }

  pop(name) {
    const sockets = this._sockets.get(name)
    if (sockets === undefined || sockets.length === 0) return null

    this._size--

    const last = sockets.pop()

    if (sockets.length === 0) this._sockets.delete(name)

    return last
  }

  delete(name, socket) {
    const sockets = this._sockets.get(name)
    if (sockets === undefined) return

    const i = sockets.indexOf(socket)
    if (i === -1) return

    this._size--

    const last = sockets.pop()
    if (last !== socket) sockets[i] = last

    if (sockets.length === 0) this._sockets.delete(name)
  }

  *sockets() {
    for (const sockets of this._sockets.values()) {
      yield* sockets
    }
  }

  *[Symbol.iterator]() {
    for (const [name, sockets] of this._sockets) {
      for (const socket of sockets) yield [name, socket]
    }
  }
}

class HTTPAgent extends EventEmitter {
  constructor(opts = {}) {
    super()

    const { keepAlive = false, keepAliveMsecs = 1000, defaultPort = 80 } = opts

    this._suspended = false
    this._resuming = null

    this._sockets = new HTTPSocketSet()
    this._freeSockets = new HTTPSocketSet()

    this._keepAlive = typeof keepAlive === 'number' ? keepAlive : keepAlive ? keepAliveMsecs : -1
    this._defaultPort = defaultPort

    this._opts = { ...opts }
  }

  get suspended() {
    return this._suspended
  }

  get resumed() {
    return this._resuming ? this._resuming.promise : null
  }

  get sockets() {
    return this._sockets.sockets()
  }

  get freeSockets() {
    return this._freeSockets.sockets()
  }

  get defaultPort() {
    return this._defaultPort
  }

  createConnection(opts) {
    if (this._suspended) throw errors.AGENT_SUSPENDED()

    return tcp.createConnection(opts)
  }

  reuseSocket(socket, req) {
    socket.ref()
  }

  keepSocketAlive(socket) {
    if (this._keepAlive === -1) return false

    socket.setKeepAlive(true, this._keepAlive)
    socket.unref()

    return true
  }

  getName(opts) {
    return `${opts.host}:${opts.port}`
  }

  addRequest(req, opts) {
    opts = { ...opts, ...this._opts }

    const name = this.getName(opts)

    let socket = this._freeSockets.pop(name)

    if (socket) this.reuseSocket(socket, req)
    else {
      const agent = this

      socket = this.createConnection(opts)

      socket
        .on('error', noop) // someone needs to handle it
        .on('free', onfree)
        .on('end', onremove)
        .on('finish', onremove)
        .on('close', onremove)
        .on('timeout', ontimeout)

      function onfree() {
        if (socket.destroyed) return

        if (agent.keepSocketAlive(socket)) {
          agent._freeSockets.add(name, socket)
        } else {
          socket.end()
        }

        agent.emit('free', socket)
      }

      function onremove() {
        socket.off('free', onfree)

        agent._sockets.delete(name, socket)
        agent._freeSockets.delete(name, socket)

        if (agent._sockets.size === 0) HTTPAgent._agents.delete(agent)
      }

      function ontimeout() {
        socket.destroy()

        agent._freeSockets.delete(name, socket)
      }
    }

    if (this._sockets.size === 0) HTTPAgent._agents.add(this)

    this._sockets.add(name, socket)

    req._socket = socket

    const connection = HTTPClientConnection.from(socket, opts)

    connection._req = req
  }

  suspend() {
    if (this._suspended) return

    this._resuming = Promise.withResolvers()
    this._suspended = true

    this.destroy()
  }

  resume() {
    if (this._resuming === null) return

    this._resuming.resolve()
    this._resuming = null
    this._suspended = false
  }

  destroy() {
    for (const socket of this._sockets.sockets()) socket.destroy()
  }

  static _agents = new Set()

  static _onidle() {
    for (const agent of this._agents) {
      agent.destroy()
    }
  }
}

HTTPAgent.global = new HTTPAgent({ keepAlive: 1000, timeout: 5000 })

module.exports = HTTPAgent

Bare.on('idle', HTTPAgent._onidle.bind(HTTPAgent))

function noop() {}
const HTTPParser = require('bare-http-parser')
const HTTPIncomingMessage = require('./incoming-message')
const errors = require('./errors')

const {
  constants: { RESPONSE, DATA, END }
} = HTTPParser

const EMPTY = Buffer.alloc(0)

module.exports = class HTTPClientConnection {
  static _connections = new WeakMap()

  static for(socket) {
    return this._connections.get(socket) || null
  }

  static from(socket, opts) {
    return this.for(socket) || new this(socket, opts)
  }

  constructor(socket, opts = {}) {
    const { IncomingMessage = HTTPIncomingMessage } = opts

    this._socket = socket

    this._req = null
    this._res = null

    this._IncomingMessage = IncomingMessage

    this._parser = new HTTPParser()
    this._idle = true

    this._onerror = this._onerror.bind(this)
    this._onclose = this._onclose.bind(this)
    this._onend = this._onend.bind(this)
    this._ondata = this._ondata.bind(this)
    this._ondrain = this._ondrain.bind(this)
    this._ontimeout = this._ontimeout.bind(this)

    socket
      .on('error', this._onerror)
      .on('close', this._onclose)
      .on('end', this._onend)
      .on('data', this._ondata)
      .on('drain', this._ondrain)
      .on('timeout', this._ontimeout)

    HTTPClientConnection._connections.set(socket, this)
  }

  get socket() {
    return this._socket
  }

  get req() {
    return this._req
  }

  get res() {
    return this._res
  }

  get idle() {
    return this._idle
  }

  _onerror(err) {
    if (this._req) this._req.destroy(err)
  }

  _onclose() {
    if (this._req) this._req.destroy()
  }

  _onend() {
    if (this._req) this._req.destroy(errors.CONNECTION_LOST())
  }

  _ondata(data) {
    this._idle = false

    try {
      for (const op of this._parser.push(data)) {
        switch (op.type) {
          case RESPONSE:
            this._req.on('close', () => {
              this._req = null
            })

            this._res = new this._IncomingMessage(this._socket, {
              headers: op.headers,
              statusCode: op.code,
              statusMessage: op.reason
            })

            this._res.on('close', () => {
              this._res = null
              this._idle = true

              this._socket.emit('free')
            })

            if (op.headers.connection && op.headers.connection.toLowerCase() === 'upgrade') {
              return this._onupgrade(this._parser.end())
            }

            this._req.emit('response', this._res)
            break

          case DATA:
            this._res.push(op.data)
            break

          case END:
            if (this._res) {
              this._res._socket = null
              this._res.push(null)
            }

            if (this._req) {
              this._req._socket = null
              this._req.destroy()
            }
            break
        }
      }
    } catch (err) {
      this._socket.destroy(err)
    }
  }

  _onupgrade(data) {
    this._detach()

    const res = this._res
    const req = this._req

    res._upgrade = req._upgrade = true

    const upgraded = req.emit('upgrade', res, this._socket, data || EMPTY)

    res.push(null)
    req.destroy()

    if (!upgraded) this._socket.destroy()
  }

  _ontimeout() {
    if (this._req) this._req.emit('timeout')
  }

  _ondrain() {
    if (this._req) this._req._continueWrite()
  }

  _detach() {
    this._socket
      .off('error', this._onerror)
      .off('close', this._onclose)
      .off('end', this._onend)
      .off('data', this._ondata)
      .off('drain', this._ondrain)
      .off('timeout', this._ontimeout)

    HTTPClientConnection._connections.delete(this._socket)
  }
}
const HTTPAgent = require('./agent')
const HTTPOutgoingMessage = require('./outgoing-message')

const CHUNK_DELIMITER = Buffer.from('\r\n')
const CHUNK_TERMINATOR = Buffer.from('0\r\n\r\n')

module.exports = class HTTPClientRequest extends HTTPOutgoingMessage {
  constructor(opts = {}, onresponse = null) {
    if (typeof opts === 'function') {
      onresponse = opts
      opts = {}
    }

    opts = opts ? { ...opts } : {}

    const agent = opts.agent === false ? new HTTPAgent() : opts.agent || HTTPAgent.global
    const method = opts.method || 'GET'
    const path = opts.path || '/'
    const defaultPort = opts.defaultPort || (agent && agent.defaultPort) || 80
    const host = (opts.host = opts.host || 'localhost')
    const port = (opts.port = opts.port || defaultPort)
    const headers = { host: hostHeader(host, port, defaultPort), ...opts.headers }

    super()

    agent.addRequest(this, opts)

    this._headers = headers
    this._method = method
    this._path = path

    this._chunked = method !== 'GET' && method !== 'HEAD'

    this._pendingWrite = null
    this._pendingFinal = null

    if (onresponse) this.once('response', onresponse)
  }

  get method() {
    return this._method
  }

  get path() {
    return this._path
  }

  // For Node.js compatibility
  abort() {
    return this.destroy()
  }

  _header() {
    let h = `${this._method} ${this._path} HTTP/1.1\r\n`

    let upgrade = false

    for (const name of Object.keys(this._headers)) {
      const n = name.toLowerCase()
      const v = this._headers[name]

      if (n === 'content-length') this._chunked = false
      if (n === 'connection' && v && v.toLowerCase() === 'upgrade') upgrade = true

      h += `${httpCase(n)}: ${v}\r\n`
    }

    if (upgrade) this._chunked = false

    if (this._chunked) h += 'Transfer-Encoding: chunked\r\n'

    h += '\r\n'

    return h
  }

  _write(data, encoding, cb) {
    if (this._headersSent === false) this.flushHeaders()

    if (this._chunked) {
      this._socket.write(Buffer.from(data.byteLength.toString(16)))
      this._socket.write(CHUNK_DELIMITER)
    }

    let flushed = this._socket.write(data)

    if (this._chunked) flushed = this._socket.write(CHUNK_DELIMITER)

    if (flushed) cb(null)
    else this._pendingWrite = cb
  }

  _final(cb) {
    if (this._headersSent === false) this.flushHeaders()

    if (this._chunked) this._socket.write(CHUNK_TERMINATOR)

    this._pendingFinal = cb
  }

  _predestroy() {
    super._predestroy()

    this._continueWrite()
    this._continueFinal()
  }

  _continueWrite() {
    if (this._pendingWrite === null) return
    const cb = this._pendingWrite
    this._pendingWrite = null
    cb(null)
  }

  _continueFinal() {
    if (this._pendingFinal === null) return
    const cb = this._pendingFinal
    this._pendingFinal = null
    cb(null)
  }
}

function httpCase(n) {
  let s = ''
  for (const part of n.split('-')) {
    s += (s ? '-' : '') + part.slice(0, 1).toUpperCase() + part.slice(1)
  }
  return s
}

function hostHeader(host, port, defaultPort) {
  const i = host.indexOf(':')

  if (i !== -1 && host.includes(':', i + 1) && host.charCodeAt(0) !== 91 /* [ */) {
    host = `[${host}]`
  }

  if (port && +port !== defaultPort) {
    host += ':' + port
  }

  return host
}
module.exports = {
  method: {
    GET: 'GET',
    HEAD: 'HEAD',
    POST: 'POST',
    PUT: 'PUT',
    DELETE: 'DELETE',
    CONNECT: 'CONNECT',
    OPTIONS: 'OPTIONS',
    TRACE: 'TRACE',
    PATCH: 'PATCH'
  },
  status: {
    100: 'Continue',
    101: 'Switching Protocols',
    102: 'Processing',
    103: 'Early Hints',
    200: 'OK',
    201: 'Created',
    202: 'Accepted',
    203: 'Non-Authoritative Information',
    204: 'No Content',
    205: 'Reset Content',
    206: 'Partial Content',
    207: 'Multi-Status',
    208: 'Already Reported',
    226: 'IM Used',
    300: 'Multiple Choices',
    301: 'Moved Permanently',
    302: 'Found',
    303: 'See Other',
    304: 'Not Modified',
    305: 'Use Proxy',
    307: 'Temporary Redirect',
    308: 'Permanent Redirect',
    400: 'Bad Request',
    401: 'Unauthorized',
    402: 'Payment Required',
    403: 'Forbidden',
    404: 'Not Found',
    405: 'Method Not Allowed',
    406: 'Not Acceptable',
    407: 'Proxy Authentication Required',
    408: 'Request Timeout',
    409: 'Conflict',
    410: 'Gone',
    411: 'Length Required',
    412: 'Precondition Failed',
    413: 'Payload Too Large',
    414: 'URI Too Long',
    415: 'Unsupported Media Type',
    416: 'Range Not Satisfiable',
    417: 'Expectation Failed',
    418: "I'm a Teapot",
    421: 'Misdirected Request',
    422: 'Unprocessable Entity',
    423: 'Locked',
    424: 'Failed Dependency',
    425: 'Too Early',
    426: 'Upgrade Required',
    428: 'Precondition Required',
    429: 'Too Many Requests',
    431: 'Request Header Fields Too Large',
    451: 'Unavailable For Legal Reasons',
    500: 'Internal Server Error',
    501: 'Not Implemented',
    502: 'Bad Gateway',
    503: 'Service Unavailable',
    504: 'Gateway Timeout',
    505: 'HTTP Version Not Supported',
    506: 'Variant Also Negotiates',
    507: 'Insufficient Storage',
    508: 'Loop Detected',
    509: 'Bandwidth Limit Exceeded',
    510: 'Not Extended',
    511: 'Network Authentication Required'
  }
}
module.exports = class HTTPError extends Error {
  constructor(msg, fn = HTTPError, code = fn.name) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'HTTPError'
  }

  static NOT_IMPLEMENTED(msg = 'Method not implemented') {
    return new HTTPError(msg, HTTPError.NOT_IMPLEMENTED)
  }

  static CONNECTION_LOST(msg = 'Socket hung up') {
    return new HTTPError(msg, HTTPError.CONNECTION_LOST)
  }

  static AGENT_SUSPENDED(msg = 'Agent is suspended') {
    return new HTTPError(msg, HTTPError.AGENT_SUSPENDED)
  }
}
const { Readable } = require('bare-stream')

module.exports = class HTTPIncomingMessage extends Readable {
  constructor(socket = null, opts = {}) {
    super()

    this._socket = socket
    this._upgrade = false
    this._headers = opts.headers || {}

    // Server options
    this._method = opts.method || ''
    this._url = opts.url || ''

    // Client options
    this._statusCode = opts.statusCode || 0
    this._statusMessage = opts.statusMessage || ''
  }

  get socket() {
    return this._socket
  }

  get upgrade() {
    return this._upgrade
  }

  get headers() {
    return this._headers
  }

  set headers(value) {
    this._headers = value
  }

  get method() {
    return this._method
  }

  set method(value) {
    this._method = value
  }

  get url() {
    return this._url
  }

  set url(value) {
    this._url = value
  }

  get statusCode() {
    return this._statusCode
  }

  set statusCode(value) {
    this._statusCode = value
  }

  get statusMessage() {
    return this._statusMessage
  }

  set statusMessage(value) {
    this._statusMessage = value
  }

  get httpVersion() {
    return '1.1'
  }

  getHeader(name) {
    return this._headers[name.toLowerCase()]
  }

  getHeaders() {
    return { ...this._headers }
  }

  hasHeader(name) {
    return name.toLowerCase() in this._headers
  }

  setTimeout(ms, ontimeout) {
    if (ontimeout) this.once('timeout', ontimeout)

    this._socket.setTimeout(ms)

    return this
  }

  _predestroy() {
    if (this._upgrade === false && this._socket !== null) this._socket.destroy()
  }
}
const { Writable } = require('bare-stream')
const errors = require('./errors')

module.exports = class HTTPOutgoingMessage extends Writable {
  constructor(socket = null) {
    super()

    this._socket = socket
    this._upgrade = false
    this._headersSent = false
    this._headers = {}
  }

  get socket() {
    return this._socket
  }

  get upgrade() {
    return this._upgrade
  }

  get headersSent() {
    return this._headersSent
  }

  get headers() {
    return this._headers
  }

  set headers(value) {
    this._headers = value
  }

  getHeader(name) {
    return this._headers[name.toLowerCase()]
  }

  getHeaders() {
    return { ...this._headers }
  }

  hasHeader(name) {
    return name.toLowerCase() in this._headers
  }

  setHeader(name, value) {
    this._headers[name.toLowerCase()] = value
  }

  flushHeaders() {
    if (this._headersSent === true || this._socket === null) return

    this._socket.write(Buffer.from(this._header()))
    this._headersSent = true
  }

  setTimeout(ms, ontimeout) {
    if (ontimeout) this.once('timeout', ontimeout)

    this._socket.setTimeout(ms)

    return this
  }

  _header() {
    throw errors.NOT_IMPLEMENTED()
  }

  _predestroy() {
    if (this._upgrade === false && this._socket !== null) this._socket.destroy()
  }
}
const { isEnded, isFinished, getStreamError } = require('bare-stream')
const HTTPParser = require('bare-http-parser')
const HTTPIncomingMessage = require('./incoming-message')
const HTTPServerResponse = require('./server-response')

const {
  constants: { REQUEST, DATA, END }
} = HTTPParser

const EMPTY = Buffer.alloc(0)

module.exports = class HTTPServerConnection {
  static _connections = new WeakMap()

  static for(socket) {
    return this._connections.get(socket) || null
  }

  constructor(server, socket, opts = {}) {
    const { IncomingMessage = HTTPIncomingMessage, ServerResponse = HTTPServerResponse } = opts

    this._server = server
    this._socket = socket

    this._req = null
    this._res = null

    this._IncomingMessage = IncomingMessage
    this._ServerResponse = ServerResponse

    this._parser = new HTTPParser()
    this._idle = true

    this._onclose = this._onclose.bind(this)
    this._ondata = this._ondata.bind(this)
    this._ondrain = this._ondrain.bind(this)
    this._ontimeout = this._ontimeout.bind(this)

    socket
      .on('error', noop)
      .on('close', this._onclose)
      .on('data', this._ondata)
      .on('drain', this._ondrain)
      .on('timeout', this._ontimeout)

    HTTPServerConnection._connections.set(socket, this)

    if (this._server.timeout) socket.setTimeout(this._server.timeout)
  }

  get server() {
    return this._server
  }

  get socket() {
    return this._socket
  }

  get req() {
    return this._req
  }

  get res() {
    return this._res
  }

  get idle() {
    return this._idle
  }

  _onclose() {
    if (this._req && !isEnded(this._req)) this._req.destroy()
    if (this._res && !isFinished(this._res)) this._res.destroy()

    const err = getStreamError(this._socket)
    if (err) this._socket.destroy(err)
  }

  _ondata(data) {
    this._idle = false

    try {
      for (const op of this._parser.push(data)) {
        switch (op.type) {
          case REQUEST:
            this._req = new this._IncomingMessage(this._socket, {
              headers: op.headers,
              method: op.method,
              url: op.url
            })

            this._req.on('close', () => {
              this._req = null

              this._idle = true

              if (this._server.closing) this._socket.destroy()
            })

            // Eagerly open the request stream
            this._req.resume()
            this._req.pause()

            if (op.headers.connection && op.headers.connection.toLowerCase() === 'upgrade') {
              return this._onupgrade(this._parser.end())
            }

            this._res = new this._ServerResponse(this._socket, this._req)

            this._res.on('close', () => {
              this._res = null
            })

            this._server.emit('request', this._req, this._res)
            break

          case DATA:
            this._req.push(op.data)
            break

          case END:
            if (this._req) {
              this._req._socket = null
              this._req.push(null)
            }
            break
        }
      }
    } catch (err) {
      this._socket.destroy(err)
    }
  }

  _onupgrade(data) {
    this._detach()

    const req = this._req

    req._upgrade = true

    const upgraded = this._server.emit('upgrade', req, this._socket, data || EMPTY)

    req.push(null)

    if (!upgraded) this._socket.destroy()
  }

  _ontimeout() {
    const reqTimeout = this._req && this._req.emit('timeout')
    const resTimeout = this._res && this._res.emit('timeout')
    const serverTimeout = this._server.emit('timeout', this._socket)

    if (!reqTimeout && !resTimeout && !serverTimeout) this._socket.destroy()
  }

  _ondrain() {
    if (this._res) this._res._continueWrite()
  }

  _detach() {
    this._socket
      .off('error', noop)
      .off('close', this._onclose)
      .off('data', this._ondata)
      .off('drain', this._ondrain)
      .off('timeout', this._ontimeout)

    HTTPServerConnection._connections.delete(this._socket)
  }
}

function noop() {}
const { isFinishing } = require('bare-stream')
const HTTPOutgoingMessage = require('./outgoing-message')
const constants = require('./constants')

const CHUNK_DELIMITER = Buffer.from('\r\n')
const CHUNK_TERMINATOR = Buffer.from('0\r\n\r\n')

module.exports = class HTTPServerResponse extends HTTPOutgoingMessage {
  constructor(socket, req) {
    super(socket)

    this._req = req

    this._statusCode = 200
    this._statusMessage = null

    this._chunked = true
    this._close = req.headers.connection === 'close'
    this._onlyHeaders = req.method === 'HEAD'

    this._pendingWrite = null
  }

  get req() {
    return this._req
  }

  get statusCode() {
    return this._statusCode
  }

  set statusCode(value) {
    this._statusCode = value
  }

  get statusMessage() {
    return this._statusMessage
  }

  set statusMessage(value) {
    this._statusMessage = value
  }

  writeHead(statusCode, statusMessage = null, headers = {}) {
    if (typeof statusMessage === 'object' && statusMessage !== null) {
      headers = statusMessage
      statusMessage = null
    }

    this._statusCode = statusCode
    this._statusMessage = statusMessage || null

    if (headers) this._headers = { ...this._headers, ...headers }
  }

  _header() {
    let h =
      'HTTP/1.1 ' +
      this._statusCode +
      ' ' +
      (this._statusMessage === null ? constants.status[this._statusCode] : this._statusMessage) +
      '\r\n'

    for (const name of Object.keys(this._headers)) {
      const n = name.toLowerCase()
      const v = this._headers[name]

      if (n === 'content-length') this._chunked = false
      if (n === 'connection' && v && v.toLowerCase() === 'close') this._close = true

      h += httpCase(n) + ': ' + v + '\r\n'
    }

    if (this._chunked) h += 'Transfer-Encoding: chunked\r\n'

    h += '\r\n'

    return h
  }

  _write(data, encoding, cb) {
    if (this._headersSent === false) {
      if (isFinishing(this)) {
        this.setHeader(
          'Content-Length',
          (data.byteLength + this._writableState.buffered).toString()
        )
      }

      this.flushHeaders()
    }

    if (this._onlyHeaders === true) return cb(null)

    if (this._chunked) {
      this._socket.write(Buffer.from(data.byteLength.toString(16)))
      this._socket.write(CHUNK_DELIMITER)
    }

    let flushed = this._socket.write(data)

    if (this._chunked) flushed = this._socket.write(CHUNK_DELIMITER)

    if (flushed) cb(null)
    else this._pendingWrite = cb
  }

  _final(cb) {
    if (this._headersSent === false) {
      this.setHeader('Content-Length', '0')
      this.flushHeaders()
    }

    if (this._chunked && this._onlyHeaders === false) this._socket.write(CHUNK_TERMINATOR)

    if (this._close) this._socket.end()

    cb(null)
  }

  _predestroy() {
    super._predestroy()

    this._req.destroy()

    this._continueWrite()
  }

  _continueWrite() {
    if (this._pendingWrite === null) return
    const cb = this._pendingWrite
    this._pendingWrite = null
    cb(null)
  }
}

function httpCase(n) {
  let s = ''
  for (const part of n.split('-')) {
    s += (s ? '-' : '') + part.slice(0, 1).toUpperCase() + part.slice(1)
  }
  return s
}
const TCPServer = require('bare-tcp').Server
const HTTPServerConnection = require('./server-connection')

module.exports = class HTTPServer extends TCPServer {
  constructor(opts = {}, onrequest) {
    if (typeof opts === 'function') {
      onrequest = opts
      opts = {}
    }

    super({ allowHalfOpen: false })

    this._timeout = 0

    this.on('connection', (socket) => {
      new HTTPServerConnection(this, socket, opts)
    })

    if (onrequest) this.on('request', onrequest)
  }

  get timeout() {
    return this._timeout || undefined // For Node.js compatibility
  }

  setTimeout(ms = 0, ontimeout) {
    if (ontimeout) this.on('timeout', ontimeout)

    this._timeout = ms

    return this
  }

  close(onclose) {
    super.close(onclose)

    for (const socket of this.connections) {
      const connection = HTTPServerConnection.for(socket)

      if (connection === null || connection.idle) {
        socket.destroy()
      }
    }

    return this
  }
}
{
  "name": "bare-http1",
  "version": "4.5.6",
  "description": "Native HTTP/1 library for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    },
    "./errors": {
      "types": "./lib/errors.d.ts",
      "default": "./lib/errors.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-http1.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-http1/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-http1#readme",
  "dependencies": {
    "bare-events": "^2.6.0",
    "bare-http-parser": "^1.1.1",
    "bare-stream": "^2.10.0",
    "bare-tcp": "^2.2.0"
  },
  "devDependencies": {
    "bare-buffer": "^3.0.2",
    "bare-url": "^2.1.3",
    "brittle": "^3.3.0",
    "lunte": "^1.6.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "bare-buffer": "*",
    "bare-url": "*"
  },
  "peerDependenciesMeta": {
    "bare-buffer": {
      "optional": true
    },
    "bare-url": {
      "optional": true
    }
  }
}
module.exports = require.addon()
const ansiEscapes = require('bare-ansi-escapes')
const getType = require('bare-type')
const binding = require('./binding')

const PLAIN_KEY = /^[a-zA-Z_][a-zA-Z_0-9]*$/

const defaultDepth = 2
const defaultBreakLength = 80
const defaultMaxArrayLength = 40

module.exports = exports = function inspect(value, opts = {}) {
  const {
    colors = false,
    depth = defaultDepth,
    breakLength = defaultBreakLength,
    stylize = defaultStylize(colors)
  } = opts

  const references = new InspectRefMap()

  const tree = inspectValue(value, 0, {
    colors,
    depth,
    breakLength,
    stylize,
    references
  })

  return tree.toString()
}

exports.styles = {
  bigint: ansiEscapes.colorYellow,
  boolean: ansiEscapes.colorYellow,
  date: ansiEscapes.colorMagenta,
  module: ansiEscapes.modifierUnderline,
  name: ansiEscapes.modifierReset,
  null: ansiEscapes.modifierBold,
  number: ansiEscapes.colorYellow,
  regexp: ansiEscapes.colorRed,
  special: ansiEscapes.colorCyan,
  string: ansiEscapes.colorGreen,
  symbol: ansiEscapes.colorGreen,
  undefined: ansiEscapes.colorBrightBlack
}

const styles = exports.styles

function defaultStylize(colors) {
  return function stylize(value, style) {
    const color = colors && styles[style]

    if (color) return color + value + ansiEscapes.modifierReset

    return value
  }
}

class InspectRefMap {
  constructor() {
    this.refs = new WeakMap()
    this.ids = new WeakMap()
    this.nextId = 1
  }

  has(object) {
    return this.refs.has(object)
  }

  get(object) {
    return this.refs.get(object) || null
  }

  set(object, ref) {
    this.refs.set(object, ref)
  }

  id(object) {
    let id = this.ids.get(object)
    if (id) return id

    id = this.nextId++
    this.ids.set(object, id)

    return id
  }
}

class InspectNode {
  constructor(depth, length, opts) {
    const { breakLength = defaultBreakLength, breakAlways = false } = opts

    this.depth = depth
    this.length = length
    this.breakLength = breakLength
    this.breakAlways = breakAlways
  }

  pad(n, string) {
    return string.padStart(n, ' ')
  }

  indent(n, string) {
    return '  '.repeat(n) + string
  }
}

class InspectRef extends InspectNode {
  constructor(depth, opts) {
    super(depth, '[circular *]'.length, opts)

    this.refs = opts.references
    this.count = 0
    this.circular = false
    this.color = opts.colors && styles.special
  }

  get id() {
    return this.refs.id(this)
  }

  increment() {
    return ++this.count
  }

  decrement() {
    return --this.count
  }

  toString(opts = {}) {
    const { offset = 0, pad = 0, indent = 0 } = opts

    let value = this.pad(pad, '[circular *' + this.id + ']')

    if (this.color) value = this.color + value + ansiEscapes.modifierReset

    return offset ? value : this.indent(indent, value)
  }
}

class InspectLeaf extends InspectNode {
  constructor(value, color, depth, opts) {
    const length = value.length

    if (value.includes('\n')) {
      value = value.replaceAll('\n', '\n' + '  '.repeat(depth))

      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.value = value
    this.color = opts.colors && color
  }

  toString(opts = {}) {
    const { offset = 0, pad = 0, indent = 0 } = opts

    let value = this.pad(pad, this.value)

    if (this.color) value = this.color + value + ansiEscapes.modifierReset

    return offset ? value : this.indent(indent, value)
  }
}

class InspectPair extends InspectNode {
  constructor(delim, left, right, depth, opts) {
    const length = left.length + delim.length + right.length

    if (left.breakAlways || right.breakAlways) {
      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.delim = delim
    this.left = left
    this.right = right
  }

  toString(opts = {}) {
    const { indent = 0 } = opts

    return this.indent(
      indent,
      this.left +
        this.delim +
        this.right.toString({
          indent,
          offset: this.left.length + this.delim.length
        })
    )
  }
}

class InspectSuspension extends InspectNode {
  constructor(overflow, depth, opts) {
    const label = `... ${overflow} more`

    super(depth, label.length, opts)

    this.label = label
  }

  toString(opts = {}) {
    const { indent = 0 } = opts

    return this.indent(indent, this.label)
  }
}

class InspectSequence extends InspectNode {
  constructor(header, footer, delim, values, ref, depth, opts) {
    const { tabulate = false } = opts

    const length =
      (ref.circular ? '<ref *>'.length + 1 : 0) +
      header.length +
      values.reduce(
        (length, value, i) =>
          length + value.length + (i === 0 ? 0 : delim.length),
        0
      ) +
      footer.length

    if (values.some((value) => value.breakAlways)) {
      opts = { ...opts, breakAlways: true }
    }

    super(depth, length, opts)

    this.header = header
    this.footer = footer
    this.delim = delim
    this.values = values
    this.ref = ref
    this.tabulate = tabulate
  }

  toString(opts = {}) {
    const { offset = 0, indent = 0 } = opts

    const split =
      this.breakAlways ||
      (this.values.length &&
        (offset + this.length > this.breakLength ||
          indent * 2 + this.length > this.breakLength))

    let header = this.header

    if (this.ref.circular) {
      header = '<ref *' + this.ref.id + '> ' + header
    }

    if (this.values.length === 0) {
      header = header.trimEnd()
    }

    if (offset === 0) {
      header = this.indent(indent, header)
    }

    if (split) {
      header = header.trimEnd() + '\n'
    }

    let string = header

    let columns = 1
    let pad = 0

    if (this.tabulate) {
      const widest = this.values.reduce(
        (length, value) =>
          value.breakAlways ? length : Math.max(length, value.length),
        0
      )

      if (widest) {
        columns = Math.max(
          columns,
          Math.floor(
            (this.breakLength - indent * 2) / (widest + this.delim.length)
          )
        )

        if (columns > 1) pad = widest
      }
    }

    for (let i = 0, n = this.values.length, offset = 0; i < n; i++) {
      const value = this.values[i]

      if (split) {
        let part

        if (i % columns === 0 || value.breakAlways) {
          part = value.toString({ indent: indent + 1, pad })
        } else {
          part = value.toString({ pad })
        }

        string += part

        if (i < n - 1) {
          if (i % columns === columns - 1 || this.values[i + 1].breakAlways) {
            string += this.delim.trimEnd() + '\n'
          } else {
            string += this.delim
          }
        }
      } else {
        if (i > 0) string += this.delim

        string += value.toString({ offset })

        offset += value.length
      }
    }

    let footer = this.footer

    if (this.values.length === 0) {
      footer = footer.trimStart()
    }

    if (split) {
      string += '\n' + this.indent(indent, footer.trimStart())
    } else {
      string += footer
    }

    return string
  }
}

function inspectValue(value, depth, opts) {
  const type = getType(value)

  if (type.isUndefined()) return inspectUndefined(depth, opts)
  if (type.isNull()) return inspectNull(depth, opts)
  if (type.isBoolean()) return inspectBoolean(value, depth, opts)
  if (type.isNumber()) return inspectNumber(value, depth, opts)
  if (type.isBigInt()) return inspectBigInt(value, depth, opts)
  if (type.isString()) return inspectString(value, depth, opts)
  if (type.isSymbol()) return inspectSymbol(value, depth, opts)
  if (type.isObject()) return inspectObject(type, value, depth, opts)
  if (type.isFunction()) return inspectFunction(type, value, depth, opts)
  if (type.isExternal()) return inspectExternal(value, opts, opts)
}

function inspectUndefined(depth, opts) {
  return new InspectLeaf('undefined', styles.undefined, depth, opts)
}

function inspectNull(depth, opts) {
  return new InspectLeaf('null', styles.null, depth, opts)
}

function inspectBoolean(value, depth, opts) {
  return new InspectLeaf(value.toString(), styles.boolean, depth, opts)
}

function inspectNumber(value, depth, opts) {
  let string

  if (Object.is(value, -0)) {
    string = '-0'
  } else {
    string = value.toString(10)
  }

  return new InspectLeaf(string, styles.number, depth, opts)
}

function inspectBigInt(value, depth, opts) {
  return new InspectLeaf(value.toString(10) + 'n', styles.bigint, depth, opts)
}

const STRING_ESCAPES =
  /[\ud800-\udbff][\udc00-\udfff]|[\u0000-\u001f'\\\ud800-\udfff]/g

function inspectString(value, depth, opts) {
  // https://tc39.es/ecma262/multipage/structured-data.html#sec-quotejsonstring
  const string = value.replace(STRING_ESCAPES, (match) => {
    if (match.length === 2) return match

    switch (match) {
      case "'":
        return "\\'"
      case '\\':
        return '\\\\'
      case '\b':
        return '\\b'
      case '\t':
        return '\\t'
      case '\n':
        return '\\n'
      case '\f':
        return '\\f'
      case '\r':
        return '\\r'
      default:
        return '\\u' + match.charCodeAt(0).toString(16).padStart(4, '0')
    }
  })

  return new InspectLeaf("'" + string + "'", styles.string, depth, opts)
}

function inspectSymbol(value, depth, opts) {
  return new InspectLeaf(value.toString(), styles.symbol, depth, opts)
}

function inspectKey(value, depth, opts) {
  if (PLAIN_KEY.test(value)) {
    return new InspectLeaf(value, null, depth, opts)
  } else {
    return inspectValue(value, depth, opts)
  }
}

function inspectObject(type, object, depth, opts) {
  const refs = opts.references

  let ref = refs.get(object)
  if (ref === null) {
    ref = new InspectRef(depth, opts)
    refs.set(object, ref)
  } else if (ref.count) {
    ref.circular = true
    return ref
  }

  const maxDepth = typeof opts.depth === 'number' ? opts.depth : Infinity

  if (maxDepth < depth) {
    const constructor = object.constructor

    return new InspectLeaf(
      '[' +
        (constructor && constructor.name ? constructor.name : 'Object') +
        ']',
      styles.special,
      depth,
      opts
    )
  }

  const inspect =
    object[Symbol.for('bare.inspect')] ||
    object[Symbol.for('nodejs.util.inspect.custom')]

  if (typeof inspect === 'function') {
    const value = inspect.call(
      object,
      typeof opts.depth === 'number' ? opts.depth - depth : null,
      {
        colors: opts.colors,
        breakLength: opts.breakLength,
        stylize: opts.stylize
      },
      exports
    )

    if (typeof value === 'object' && value !== null) {
      refs.set(value, ref)
    }

    if (typeof value !== 'string') {
      return inspectValue(value, depth, opts)
    }

    return new InspectLeaf(value, null, depth, opts)
  }

  if (type.isArray()) return inspectArray(object, ref, depth, opts)
  if (type.isDate()) return inspectDate(object, ref, depth, opts)
  if (type.isRegExp()) return inspectRegExp(object, ref, depth, opts)
  if (type.isError()) return inspectError(object, ref, depth, opts)
  if (type.isPromise()) return inspectPromise(object, ref, depth, opts)
  if (type.isMap()) return inspectMap(object, ref, depth, opts)
  if (type.isSet()) return inspectSet(object, ref, depth, opts)
  if (type.isWeakMap()) return inspectWeakMap(object, ref, depth, opts)
  if (type.isWeakSet()) return inspectWeakSet(object, ref, depth, opts)
  if (type.isWeakRef()) return inspectWeakRef(object, ref, depth, opts)
  if (type.isArrayBuffer()) return inspectArrayBuffer(object, ref, depth, opts)
  if (type.isSharedArrayBuffer())
    return inspectSharedArrayBuffer(object, ref, depth, opts)
  if (type.isTypedArray()) return inspectTypedArray(object, ref, depth, opts)
  if (type.isDataView()) return inspectDataView(object, ref, depth, opts)

  ref.increment()

  const values = []

  for (const key in object) {
    if (key === 'constructor') continue

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(object[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  let header = '{ '

  const tag = object[Symbol.toStringTag]

  if (tag) header = '[' + tag + '] ' + header

  if (object.constructor) {
    const name = object.constructor.name

    if (name && name !== 'Object') {
      header = object.constructor.name + ' ' + header
    }
  }

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectArray(array, ref, depth, opts) {
  const { maxArrayLength = defaultMaxArrayLength } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxArrayLength, 0)

  for (let i = 0, n = array.length; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(array.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(inspectValue(array[i], depth + 1, opts))
  }

  for (const key of binding.getOwnNonIndexPropertyNames(array)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(array[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  let header = '[ '

  if (array.constructor.name !== 'Array') {
    header = array.constructor.name + '(' + array.length + ') ' + header
  }

  return new InspectSequence(header, ' ]', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectDate(date, ref, depth, opts) {
  return new InspectLeaf(date.toISOString(), styles.date, depth, opts)
}

function inspectRegExp(regExp, ref, depth, opts) {
  return new InspectLeaf(regExp.toString(), styles.regexp, depth, opts)
}

function inspectError(error, ref, depth, opts) {
  let header

  if ('stack' in error) {
    header = error.stack

    if (depth > 0) {
      header = header.replaceAll('\n', '\n' + '  '.repeat(depth))
    }
  } else {
    header = error.toString()
  }

  const builtins = ['cause']

  if (error.name === 'AggregateError') {
    builtins.push('errors')
  } else if (error.name === 'SuppressedError') {
    builtins.push('error', 'suppressed')
  }

  const values = []

  for (const key of builtins) {
    if (key in error === false) continue

    values.push(
      new InspectPair(
        ': ',
        new InspectLeaf('[' + key + ']', null, depth + 1, opts),
        inspectValue(error[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key in error) {
    if (key === 'constructor' || builtins.includes(key)) continue

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(error[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  if (values.length === 0) return new InspectLeaf(header, null, depth, opts)

  return new InspectSequence(
    header + ' {',
    ' }',
    ', ',
    values,
    ref,
    depth,
    opts
  )
}

function inspectPromise(promise, ref, depth, opts) {
  ref.increment()

  const state = binding.getPromiseState(promise)

  const values = []

  switch (state) {
    case 0: // Pending
      values.push(new InspectLeaf('<pending>', styles.special, depth, opts))
      break

    case 1: // Fulfilled
      values.push(inspectValue(binding.getPromiseResult(promise), depth, opts))
      break

    case 2: // Rejected
      values.push(
        new InspectLeaf('<rejected>', styles.special, depth, opts),
        inspectValue(binding.getPromiseResult(promise), depth, opts)
      )
  }

  ref.decrement()

  const header = promise.constructor.name + ' { '

  return new InspectSequence(header, ' }', ' ', values, ref, depth, opts)
}

function inspectMap(map, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxMapLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = maxMapLength

  for (const entry of map) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(map.size - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )
      break
    }

    values.push(
      new InspectPair(
        ' => ',
        inspectValue(entry[0], depth + 1, opts),
        inspectValue(entry[1], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key in map) {
    if (key === 'constructor') continue

    const value = inspectValue(map[key], depth + 1, opts)

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        value,
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = map.constructor.name + '(' + map.size + ') { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectSet(set, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxSetLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = maxSetLength

  for (const entry of set) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(set.size - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )
      break
    }

    values.push(inspectValue(entry, depth + 1, opts))
  }

  for (const key in set) {
    if (key === 'constructor') continue

    const value = inspectValue(set[key], depth + 1, opts)

    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        value,
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = set.constructor.name + '(' + set.size + ') { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectWeakMap(weakMap, ref, depth, opts) {
  const header = weakMap.constructor.name + ' { '

  return new InspectSequence(
    header,
    ' }',
    ' ',
    [new InspectLeaf('<items unknown>', styles.special, depth + 1, opts)],
    ref,
    depth,
    opts
  )
}

function inspectWeakSet(weakSet, ref, depth, opts) {
  const header = weakSet.constructor.name + ' { '

  return new InspectSequence(
    header,
    ' }',
    ' ',
    [new InspectLeaf('<items unknown>', styles.special, depth + 1, opts)],
    ref,
    depth,
    opts
  )
}

function inspectWeakRef(weakRef, ref, depth, opts) {
  const target = weakRef.deref()

  let value

  if (target === undefined) {
    value = new InspectLeaf('<cleared>', styles.special, depth + 1, opts)
  } else {
    value = inspectValue(target, depth + 1, opts)
  }

  const header = weakRef.constructor.name + ' { '

  return new InspectSequence(header, ' }', ' ', [value], ref, depth, opts)
}

function inspectArrayBuffer(arrayBuffer, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(arrayBuffer[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = arrayBuffer.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectSharedArrayBuffer(sharedArrayBuffer, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(sharedArrayBuffer[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = sharedArrayBuffer.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectTypedArray(typedArray, ref, depth, opts) {
  if (Buffer.isBuffer(typedArray)) {
    return inspectBuffer(typedArray, ref, depth, opts)
  }

  const {
    maxArrayLength = defaultMaxArrayLength,
    maxTypedArrayLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxTypedArrayLength, 0)

  for (let i = 0, n = typedArray.length; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(typedArray.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(inspectValue(typedArray[i], depth + 1, opts))
  }

  for (const key of binding.getOwnNonIndexPropertyNames(typedArray)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(typedArray[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  const header = typedArray.constructor.name + '(' + typedArray.length + ') [ '

  return new InspectSequence(header, ' ]', ', ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectBuffer(buffer, ref, depth, opts) {
  const {
    maxArrayLength = defaultMaxArrayLength,
    maxBufferLength = maxArrayLength
  } = opts

  ref.increment()

  const values = []

  let remaining = Math.max(maxBufferLength, 0)

  for (let i = 0, n = buffer.byteLength; i < n; i++) {
    if (remaining-- === 0) {
      values.push(
        new InspectSuspension(buffer.length - values.length, depth + 1, {
          ...opts,
          breakAlways: true
        })
      )

      break
    }

    values.push(
      new InspectLeaf(
        buffer[i].toString(16).padStart(2, '0'),
        null,
        depth + 1,
        opts
      )
    )
  }

  for (const key of binding.getOwnNonIndexPropertyNames(buffer)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(buffer[key], depth + 1, opts),
        depth + 1,
        { ...opts, breakAlways: remaining < 0 }
      )
    )
  }

  ref.decrement()

  return new InspectSequence('<Buffer ', '>', ' ', values, ref, depth, {
    ...opts,
    tabulate: true
  })
}

function inspectDataView(dataView, ref, depth, opts) {
  ref.increment()

  const values = []

  for (const key of ['byteLength', 'byteOffset', 'buffer']) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(dataView[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  for (const key of binding.getOwnNonIndexPropertyNames(dataView)) {
    values.push(
      new InspectPair(
        ': ',
        inspectKey(key, depth + 1, opts),
        inspectValue(dataView[key], depth + 1, opts),
        depth + 1,
        opts
      )
    )
  }

  ref.decrement()

  const header = dataView.constructor.name + ' { '

  return new InspectSequence(header, ' }', ', ', values, ref, depth, opts)
}

function inspectFunction(type, fn, depth, opts) {
  if (fn.toString().startsWith('class')) return inspectClass(fn, depth, opts)

  let tag = 'function'

  if (type.isGeneratorFunction()) tag = 'generator ' + tag
  if (type.isAsyncFunction()) tag = 'async ' + tag

  return new InspectLeaf(
    '[' + tag + ' ' + (fn.name ? fn.name : '(anonymous)') + ']',
    styles.special,
    depth,
    opts
  )
}

function inspectClass(ctor, depth, opts) {
  return new InspectLeaf(
    '[class ' + (ctor.name ? ctor.name : '(anonymous)') + ']',
    styles.special,
    depth,
    opts
  )
}

function inspectExternal(external, depth, opts) {
  return new InspectLeaf(
    '[external 0x' + binding.getExternal(external).toString(16) + ']',
    styles.special,
    depth,
    opts
  )
}
{
  "name": "bare-inspect",
  "version": "3.1.4",
  "description": "Inspect objects as strings for debugging",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-inspect.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-inspect/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-inspect#readme",
  "engines": {
    "bare": ">=1.18.0"
  },
  "dependencies": {
    "bare-ansi-escapes": "^2.1.0",
    "bare-type": "^1.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
const EventEmitter = require('bare-events')
const { Duplex } = require('bare-stream')
const tcp = require('bare-tcp')
const pipe = require('bare-pipe')

const defaultReadBufferSize = 65536

const constants = exports.constants = {
  type: {
    TCP: 1,
    IPC: 2
  },
  state: {
    UNREFED: 0x1
  }
}

const Socket = exports.Socket = class NetSocket extends Duplex {
  constructor (opts = {}) {
    super({ eagerOpen: true })

    const {
      readBufferSize = defaultReadBufferSize,
      allowHalfOpen = true
    } = opts

    this._opts = { readBufferSize, allowHalfOpen }
    this._type = 0
    this._state = 0
    this._socket = null

    this._pendingWrite = null
    this._pendingFinal = null
  }

  get connecting () {
    return this._socket !== null && this._socket.connecting
  }

  get pending () {
    return this._socket === null || this._socket.pending
  }

  connect (...args) {
    let opts = {}
    let onconnect

    // connect(path[, onconnect])
    if (typeof args[0] === 'string') {
      opts.path = args[0]
      onconnect = args[1]
    // connect(port[, host][, onconnect])
    } else if (typeof args[0] === 'number') {
      opts.port = args[0]

      if (typeof args[1] === 'function') {
        onconnect = args[1]
      } else {
        opts.host = args[1]
        onconnect = args[2]
      }
    // connect(opts[, onconnect])
    } else {
      opts = args[0] || {}
      onconnect = args[1]
    }

    opts = { ...opts, ...this._opts }

    if (opts.path) {
      this._attach(constants.type.IPC, pipe.createConnection(opts))
    } else {
      this._attach(constants.type.TCP, tcp.createConnection(opts))
    }

    if (onconnect) this.once('connect', onconnect)

    return this
  }

  ref () {
    this._state &= ~constants.state.UNREFED
    if (this._socket !== null) this._socket.ref()
  }

  unref () {
    this._state |= constants.state.UNREFED
    if (this._socket !== null) this._socket.unref()
  }

  _attach (type, socket) {
    this._type = type
    this._socket = socket

    this._socket
      .on('connect', this._onconnect.bind(this))
      .on('error', this._onerror.bind(this))
      .on('close', this._onclose.bind(this))
      .on('end', this._onend.bind(this))
      .on('data', this._ondata.bind(this))
      .on('drain', this._ondrain.bind(this))

    if (this._state & constants.state.UNREFED) this._socket.unref()

    return this
  }

  _write (data, encoding, cb) {
    if (this._socket !== null && this._socket.write(data)) cb(null)
    else this._pendingWrite = cb
  }

  _final (cb) {
    if (this._socket === null) return cb(null)
    this._pendingFinal = cb
    this._socket.end()
  }

  _predestroy () {
    if (this._socket === null) return
    this._socket.destroy()
  }

  _onconnect () {
    this._ondrain() // Flush any pending writes

    this.emit('connect')
  }

  _onerror (err) {
    this.destroy(err)
  }

  _onend () {
    if (this._pendingFinal === null) return
    const cb = this._pendingFinal
    this._pendingFinal = null
    cb(null)
  }

  _onclose () {
    this.push(null)
  }

  _ondata (data) {
    this.push(data)
  }

  _ondrain () {
    if (this._pendingWrite === null) return
    const cb = this._pendingWrite
    this._pendingWrite = null
    cb(null)
  }
}

const Server = exports.Server = class NetServer extends EventEmitter {
  constructor (opts = {}, onconnection) {
    if (typeof opts === 'function') {
      onconnection = opts
      opts = {}
    }

    super()

    const {
      readBufferSize = defaultReadBufferSize,
      allowHalfOpen = true
    } = opts

    this._opts = { readBufferSize, allowHalfOpen }
    this._type = 0
    this._state = 0
    this._server = null

    if (onconnection) this.on('connection', onconnection)
  }

  get listening () {
    return this._server !== null && this._server.listening
  }

  address () {
    return this._server === null ? null : this._server.address()
  }

  listen (...args) {
    let opts = {}
    let onlistening

    // listen(path[, backlog][, onlistening])
    if (typeof args[0] === 'string') {
      opts.path = args[0]

      if (typeof args[1] === 'function') {
        onlistening = args[1]
      } else {
        opts.backlog = args[1]
        onlistening = args[2]
      }
    // listen([port[, host[, backlog]]][, onlistening])
    } else {
      if (typeof args[0] === 'function') {
        onlistening = args[0]
      } else {
        opts.port = args[0]

        if (typeof args[1] === 'function') {
          onlistening = args[1]
        } else {
          opts.host = args[1]

          if (typeof args[2] === 'function') {
            onlistening = args[2]
          } else {
            opts.backlog = args[2]
            onlistening = args[3]
          }
        }
      }
    }

    opts = { ...opts, ...this._opts }

    if (opts.path) {
      this._attach(constants.type.IPC, pipe.createServer(opts))
    } else {
      this._attach(constants.type.TCP, tcp.createServer(opts))
    }

    this._server.listen(opts)

    if (onlistening) this.once('listening', onlistening)

    return this
  }

  close (onclose) {
    if (onclose) this.once('close', onclose)
    this._server.close()
  }

  ref () {
    this._state &= ~constants.state.UNREFED
    if (this._server !== null) this._server.ref()
  }

  unref () {
    this._state |= constants.state.UNREFED
    if (this._server !== null) this._server.unref()
  }

  _attach (type, server) {
    this._type = type
    this._server = server

    this._server
      .on('listening', this._onlistening.bind(this))
      .on('connection', this._onconnection.bind(this))
      .on('error', this._onerror.bind(this))
      .on('close', this._onclose.bind(this))

    if (this._state & constants.state.UNREFED) this._server.unref()

    return this
  }

  _onlistening () {
    this.emit('listening')
  }

  _onconnection (socket) {
    this.emit('connection', new Socket(this._opts)._attach(this._type, socket))
  }

  _onerror (err) {
    this.emit('error', err)
  }

  _onclose () {
    this.emit('close')
  }
}

exports.isIP = tcp.isIP
exports.isIPv4 = tcp.isIPv4
exports.isIPv6 = tcp.isIPv6

exports.createConnection = function createConnection (...args) {
  let opts = {}
  let onconnect

  // createConnection(path[, onconnect])
  if (typeof args[0] === 'string') {
    opts.path = args[0]
    onconnect = args[1]
  // createConnection(port[, host][, onconnect])
  } else if (typeof args[0] === 'number') {
    opts.port = args[0]

    if (typeof args[1] === 'function') {
      onconnect = args[1]
    } else {
      opts.host = args[1]
      onconnect = args[2]
    }
  // createConnection(opts[, onconnect])
  } else {
    opts = args[0] || {}
    onconnect = args[1]
  }

  return new Socket(opts).connect(opts, onconnect)
}

exports.createServer = function createServer (opts, onconnection) {
  return new Server(opts, onconnection)
}
module.exports = require.addon()
const binding = require('./binding')

function onlookup (err, addresses) {
  const req = this

  if (err) return req.cb(err, null, 0)

  const { address, family } = addresses[0]

  return req.cb(null, address, family)
}

function onlookupall (err, addresses) {
  const req = this

  if (err) return req.cb(err, null)

  return req.cb(null, addresses)
}

exports.lookup = function lookup (hostname, opts = {}, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  let {
    family = 0,
    all = false
  } = opts

  if (typeof family === 'string') {
    switch (family) {
      case 'IPv4': family = 4
        break
      case 'IPv6': family = 6
        break
      default: family = 0
    }
  }

  const req = {
    cb,
    handle: null
  }

  req.handle = binding.lookup(hostname, family || 0, all, req, all ? onlookupall : onlookup)
}
{
  "name": "bare-dns",
  "version": "1.0.5",
  "description": "Domain name resolution for JavaScript",
  "exports": {
    ".": "./index.js",
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "standard && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-dns.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-dns/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-dns",
  "devDependencies": {
    "brittle": "^3.3.2",
    "cmake-bare": "^1.1.6",
    "standard": "^17.1.0"
  }
}
module.exports = require.addon()
/* global Bare */
const EventEmitter = require('bare-events')
const { Duplex } = require('bare-stream')
const binding = require('./binding')
const constants = require('./lib/constants')
const errors = require('./lib/errors')

const defaultReadBufferSize = 65536

const Pipe = module.exports = exports = class Pipe extends Duplex {
  constructor (path, opts = {}) {
    super({ eagerOpen: true })

    if (typeof path === 'object' && path !== null) {
      opts = path
      path = null
    }

    const {
      readBufferSize = defaultReadBufferSize,
      allowHalfOpen = true
    } = opts

    this._state = 0

    this._allowHalfOpen = allowHalfOpen

    this._fd = -1
    this._path = null

    this._pendingOpen = null
    this._pendingWrite = null
    this._pendingFinal = null
    this._pendingDestroy = null

    this._buffer = Buffer.alloc(readBufferSize)

    this._handle = binding.init(this._buffer, this,
      noop,
      this._onconnect,
      this._onwrite,
      this._onfinal,
      this._onread,
      this._onclose
    )

    if (typeof path === 'number') {
      this.open(path)
    } else if (typeof path === 'string') {
      this.connect(path)
    }

    Pipe._pipes.add(this)
  }

  get connecting () {
    return (this._state & constants.state.CONNECTING) !== 0
  }

  get pending () {
    return (this._state & constants.state.CONNECTED) === 0
  }

  get readyState () {
    if (this._state & constants.state.READABLE && this._state & constants.state.WRITABLE) {
      return 'open'
    }

    if (this._state & constants.state.READABLE) {
      return 'readOnly'
    }

    if (this._state & constants.state.WRITABLE) {
      return 'writeOnly'
    }

    return 'opening'
  }

  open (fd, opts = {}, onconnect) {
    if (typeof opts === 'function') {
      onconnect = opts
      opts = {}
    }

    if (typeof fd === 'object' && fd !== null) {
      opts = fd || {}
      fd = opts.fd
    }

    try {
      const status = binding.open(this._handle, fd)

      this._state |= constants.state.CONNECTED
      this._fd = fd

      if (status & binding.READABLE) {
        this._state |= constants.state.READABLE
      } else {
        this.push(null)
      }

      if (status & binding.WRITABLE) {
        this._state |= constants.state.WRITABLE
      } else {
        this.end()
      }

      if (onconnect) this.once('connect', onconnect)

      queueMicrotask(() => this.emit('connect'))
    } catch (err) {
      queueMicrotask(() => {
        if (this._pendingOpen) this._pendingOpen(err)
        else this.destroy(err)
      })
    }

    return this
  }

  connect (path, opts = {}, onconnect) {
    if (this._state & constants.state.CONNECTING || this._state & constants.state.CONNECTED) {
      throw errors.PIPE_ALREADY_CONNECTED('Pipe is already connected')
    }

    this._state |= constants.state.CONNECTING

    if (typeof opts === 'function') {
      onconnect = opts
      opts = {}
    }

    if (typeof path === 'object' && path !== null) {
      opts = path || {}
      path = opts.path
    }

    try {
      binding.connect(this._handle, path)

      this._path = path

      if (onconnect) this.once('connect', onconnect)
    } catch (err) {
      queueMicrotask(() => {
        if (this._pendingOpen) this._pendingOpen(err)
        else this.destroy(err)
      })
    }

    return this
  }

  ref () {
    binding.ref(this._handle)
  }

  unref () {
    binding.unref(this._handle)
  }

  _open (cb) {
    if (this._state & constants.state.CONNECTED) return cb(null)
    this._pendingOpen = cb
  }

  _read () {
    if ((this._state & constants.state.READING) === 0) {
      this._state |= constants.state.READING
      binding.resume(this._handle)
    }
  }

  _writev (batch, cb) {
    this._pendingWrite = [cb, batch]
    binding.writev(this._handle, batch.map(({ chunk }) => chunk))
  }

  _final (cb) {
    if (this._state & constants.state.READABLE && this._state & constants.state.WRITABLE) {
      this._pendingFinal = cb
      binding.end(this._handle)
    } else {
      cb(null)
    }
  }

  _predestroy () {
    if (this._state & constants.state.CLOSING) return
    this._state |= constants.state.CLOSING
    binding.close(this._handle)
    Pipe._pipes.delete(this)
  }

  _destroy (err, cb) {
    if (this._state & constants.state.CLOSING) return cb(err)
    this._state |= constants.state.CLOSING
    this._pendingDestroy = cb
    binding.close(this._handle)
    Pipe._pipes.delete(this)
  }

  _continueOpen (err) {
    if (this._pendingOpen === null) return
    const cb = this._pendingOpen
    this._pendingOpen = null
    cb(err)
  }

  _continueWrite (err) {
    if (this._pendingWrite === null) return
    const cb = this._pendingWrite[0]
    this._pendingWrite = null
    cb(err)
  }

  _continueFinal (err) {
    if (this._pendingFinal === null) return
    const cb = this._pendingFinal
    this._pendingFinal = null
    cb(err)
  }

  _continueDestroy () {
    if (this._pendingDestroy === null) return
    const cb = this._pendingDestroy
    this._pendingDestroy = null
    cb(null)
  }

  _onconnect (err) {
    if (err) {
      if (this._pendingOpen) this._continueOpen(err)
      else this.destroy(err)
      return
    }

    this._state |= constants.state.CONNECTED | constants.state.READABLE | constants.state.WRITABLE
    this._state &= ~constants.state.CONNECTING
    this._continueOpen()

    this.emit('connect')
  }

  _onread (err, read) {
    if (err) {
      this.destroy(err)
      return
    }

    if (read === 0) {
      this.push(null)
      if (this._allowHalfOpen === false) this.end()
      return
    }

    const copy = Buffer.allocUnsafe(read)
    copy.set(this._buffer.subarray(0, read))

    if (this.push(copy) === false && this.destroying === false) {
      this._state &= ~constants.state.READING
      binding.pause(this._handle)
    }
  }

  _onwrite (err) {
    this._continueWrite(err)
  }

  _onfinal (err) {
    this._continueFinal(err)
  }

  _onclose () {
    this._handle = null
    this._continueDestroy()
  }

  _onspawn (readable, writable) {
    this._state |= constants.state.CONNECTED

    if (readable) {
      this._state |= constants.state.READABLE
    } else {
      this.push(null)
    }

    if (writable) {
      this._state |= constants.state.WRITABLE
    } else {
      this.end()
    }

    this._continueOpen()
  }

  static _pipes = new Set()
}

exports.Pipe = exports

exports.pipe = function pipe () {
  return binding.pipe()
}

const Server = exports.Server = class PipeServer extends EventEmitter {
  constructor (opts = {}, onconnection) {
    if (typeof opts === 'function') {
      onconnection = opts
      opts = {}
    }

    super()

    const {
      readBufferSize = defaultReadBufferSize,
      allowHalfOpen = true
    } = opts

    this._state = 0

    this._readBufferSize = readBufferSize
    this._allowHalfOpen = allowHalfOpen

    this._path = null
    this._connections = new Set()

    this._error = null
    this._handle = null

    if (onconnection) this.on('connection', onconnection)

    PipeServer._servers.add(this)
  }

  get listening () {
    return (this._state & constants.state.BOUND) !== 0
  }

  address () {
    if ((this._state & constants.state.BOUND) === 0) {
      return null
    }

    return this._path
  }

  listen (path, backlog = 511, opts = {}, onlistening) {
    if (this._state & constants.state.BINDING || this._state & constants.state.BOUND) {
      throw errors.SERVER_ALREADY_LISTENING('Server is already listening')
    }

    if (this._state & constants.state.CLOSING) {
      throw errors.SERVER_IS_CLOSED('Server is closed')
    }

    this._state |= constants.state.BINDING

    if (typeof backlog === 'function') {
      onlistening = backlog
      backlog = 511
    } else if (typeof opts === 'function') {
      onlistening = opts
      opts = {}
    }

    if (typeof path === 'object' && path !== null) {
      opts = path || {}
      path = opts.path
      backlog = opts.backlog || 511
    }

    this._handle = binding.init(empty, this,
      this._onconnection,
      noop,
      noop,
      noop,
      noop,
      this._onclose
    )

    if (this._state & constants.state.UNREFED) binding.unref(this._handle)

    try {
      binding.bind(this._handle, path, backlog)

      this._path = path
      this._state |= constants.state.BOUND
      this._state &= ~constants.state.BINDING

      if (onlistening) this.once('listening', onlistening)

      queueMicrotask(() => this.emit('listening'))
    } catch (err) {
      this._error = err

      binding.close(this._handle)
    }

    return this
  }

  close (onclose) {
    if (onclose) this.once('close', onclose)
    if (this._state & constants.state.CLOSING) return
    this._state |= constants.state.CLOSING
    this._closeMaybe()
  }

  ref () {
    this._state &= ~constants.state.UNREFED
    if (this._handle !== null) binding.ref(this._handle)
  }

  unref () {
    this._state |= constants.state.UNREFED
    if (this._handle !== null) binding.unref(this._handle)
  }

  _closeMaybe () {
    if ((this._state & constants.state.CLOSING) && this._connections.size === 0) {
      if (this._handle !== null) binding.close(this._handle)
      else queueMicrotask(() => this.emit('close'))
      PipeServer._servers.delete(this)
    }
  }

  _onconnection (err) {
    if (err) {
      this.emit('error', err)
      return
    }

    if (this._state & constants.state.CLOSING) return

    const pipe = new Pipe({
      readBufferSize: this._readBufferSize,
      allowHalfOpen: this._allowHalfOpen
    })

    try {
      binding.accept(this._handle, pipe._handle)

      pipe._path = this._path
      pipe._state |= constants.state.CONNECTED | constants.state.READABLE | constants.state.WRITABLE

      this._connections.add(pipe)

      pipe.on('close', () => {
        this._connections.delete(pipe)
        this._closeMaybe()
      })

      this.emit('connection', pipe)
    } catch (err) {
      pipe.destroy()

      throw err
    }
  }

  _onclose () {
    const err = this._error

    this._state &= ~constants.state.BINDING
    this._error = null
    this._handle = null

    if (err) this.emit('error', err)
    else this.emit('close')
  }

  static _servers = new Set()
}

exports.constants = constants
exports.errors = errors

exports.createConnection = function createConnection (path, opts, onconnect) {
  if (typeof opts === 'function') {
    onconnect = opts
    opts = {}
  }

  if (typeof path === 'object' && path !== null) {
    opts = path || {}
    path = opts.path
  }

  return new Pipe(opts).connect(path, opts, onconnect)
}

exports.createServer = function createServer (opts, onconnection) {
  return new Server(opts, onconnection)
}

Bare
  .on('exit', () => {
    for (const pipe of Pipe._pipes) {
      pipe.destroy()
    }

    for (const server of Server._servers) {
      server.close()
    }
  })

const empty = Buffer.alloc(0)

function noop () {}
module.exports = {
  state: {
    CONNECTING: 0x1,
    CONNECTED: 0x2,
    BINDING: 0x4,
    BOUND: 0x8,
    READING: 0x10,
    CLOSING: 0x20,
    READABLE: 0x40,
    WRITABLE: 0x80
  }
}
module.exports = class PipeError extends Error {
  constructor (msg, code, fn = PipeError) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name () {
    return 'PipeError'
  }

  static PIPE_ALREADY_CONNECTED (msg) {
    return new PipeError(msg, 'PIPE_ALREADY_CONNECTED', PipeError.PIPE_ALREADY_CONNECTED)
  }

  static SERVER_ALREADY_LISTENING (msg) {
    return new PipeError(msg, 'SERVER_ALREADY_LISTENING', PipeError.SERVER_ALREADY_LISTENING)
  }

  static SERVER_IS_CLOSED (msg) {
    return new PipeError(msg, 'SERVER_IS_CLOSED', PipeError.SERVER_IS_CLOSED)
  }
}
{
  "name": "bare-pipe",
  "version": "3.3.8",
  "description": "Native I/O pipes for JavaScript",
  "exports": {
    ".": "./index.js",
    "./package": "./package.json",
    "./constants": "./lib/constants.js",
    "./errors": "./lib/errors.js"
  },
  "files": [
    "index.js",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "standard && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-pipe.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-pipe/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-pipe#readme",
  "dependencies": {
    "bare-events": "^2.0.0",
    "bare-stream": "^2.0.0"
  },
  "devDependencies": {
    "bare-path": "^3.0.0",
    "brittle": "^3.2.1",
    "cmake-bare": "^1.1.6",
    "standard": "^17.0.0"
  }
}
module.exports = require.addon()
/* global Bare */
const EventEmitter = require('bare-events')
const { Duplex } = require('bare-stream')
const dns = require('bare-dns')
const binding = require('./binding')
const constants = require('./lib/constants')
const errors = require('./lib/errors')
const ip = require('./lib/ip')

const defaultReadBufferSize = 65536

const Socket = exports.Socket = class TCPSocket extends Duplex {
  constructor (opts = {}) {
    super({ eagerOpen: true })

    const {
      readBufferSize = defaultReadBufferSize,
      allowHalfOpen = true
    } = opts

    this._state = 0

    this._allowHalfOpen = allowHalfOpen

    this._remotePort = -1
    this._remoteHost = null
    this._remoteFamily = 0

    this._pendingOpen = null
    this._pendingWrite = null
    this._pendingFinal = null
    this._pendingDestroy = null

    this._timer = null
    this._timeout = 0

    this._buffer = Buffer.alloc(readBufferSize)

    this._handle = binding.init(this._buffer, this,
      noop,
      this._onconnect,
      this._onread,
      this._onwrite,
      this._onfinal,
      this._onclose
    )

    TCPSocket._sockets.add(this)
  }

  get connecting () {
    return (this._state & constants.state.CONNECTING) !== 0
  }

  get pending () {
    return (this._state & constants.state.CONNECTED) === 0
  }

  get timeout () {
    return this._timeout || undefined // For Node.js compatibility
  }

  connect (port, host = 'localhost', opts = {}, onconnect) {
    if (this._state & constants.state.CONNECTING || this._state & constants.state.CONNECTED) {
      throw errors.SOCKET_ALREADY_CONNECTED('Socket is already connected')
    }

    this._state |= constants.state.CONNECTING

    if (typeof host === 'function') {
      onconnect = host
      host = 'localhost'
    } else if (typeof opts === 'function') {
      onconnect = opts
      opts = {}
    }

    let family = 0

    if (typeof port === 'object' && port !== null) {
      opts = port || {}
      port = opts.port || 0
      host = opts.host || 'localhost'
      family = opts.family || 0
    }

    if (!host) host = 'localhost'

    const type = ip.isIP(host)

    if (type === 0) {
      const {
        lookup = dns.lookup,
        hints
      } = opts

      lookup(host, { family, hints }, (err, address, family) => {
        this.emit('lookup', err, address, family, host)

        this._state &= ~constants.state.CONNECTING

        if (err) {
          if (this._pendingOpen) this._continueOpen(err)
          else this.destroy(err)
          return
        }

        if (this._handle !== null) {
          this.connect(port, address, { ...opts, family }, onconnect)
        }
      })

      return this
    }

    family = type

    try {
      binding.connect(this._handle, port, host, family)

      if (opts.keepAlive === true) this.setKeepAlive(opts.keepAlive, opts.keepAliveInitialDelay)
      if (opts.noDelay === true) this.setNoDelay()
      if (opts.timeout) this.setTimeout(opts.timeout)

      this._remotePort = port
      this._remoteHost = host
      this._remoteFamily = family

      if (onconnect) this.once('connect', onconnect)
    } catch (err) {
      queueMicrotask(() => {
        if (this._pendingOpen) this._pendingOpen(err)
        else this.destroy(err)
      })
    }

    return this
  }

  setKeepAlive (enable = false, delay = 0) {
    if (typeof enable === 'number') {
      delay = enable
      enable = false
    }

    delay = Math.floor(delay / 1000)

    if (delay === 0) enable = false

    binding.keepalive(this._handle, enable, delay)

    return this
  }

  setNoDelay (enable = true) {
    binding.nodelay(this._handle, enable)

    return this
  }

  setTimeout (ms, ontimeout) {
    if (ms === 0) {
      clearTimeout(this._timer)
      this._timer = null
    } else {
      if (ontimeout) this.once('timeout', ontimeout)

      this._timer = setTimeout(() => this.emit('timeout'), ms)
      this._timer.unref()
    }

    this._timeout = ms

    return this
  }

  ref () {
    binding.ref(this._handle)
  }

  unref () {
    binding.unref(this._handle)
  }

  _open (cb) {
    if (this._state & constants.state.CONNECTED) return cb(null)
    this._pendingOpen = cb
  }

  _read () {
    if ((this._state & constants.state.READING) === 0) {
      this._state |= constants.state.READING
      binding.resume(this._handle)
    }
  }

  _writev (batch, cb) {
    this._pendingWrite = [cb, batch]
    binding.writev(this._handle, batch.map(({ chunk }) => chunk))
  }

  _final (cb) {
    this._pendingFinal = cb
    binding.end(this._handle)
  }

  _predestroy () {
    if (this._state & constants.state.CLOSING) return
    this._state |= constants.state.CLOSING
    binding.close(this._handle)
    TCPSocket._sockets.delete(this)
  }

  _destroy (err, cb) {
    if (this._state & constants.state.CLOSING) return cb(err)
    this._state |= constants.state.CLOSING
    this._pendingDestroy = cb
    binding.close(this._handle)
    TCPSocket._sockets.delete(this)
  }

  _continueOpen (err) {
    if (this._pendingOpen === null) return
    const cb = this._pendingOpen
    this._pendingOpen = null
    cb(err)
  }

  _continueWrite (err) {
    if (this._pendingWrite === null) return
    const cb = this._pendingWrite[0]
    this._pendingWrite = null
    cb(err)
  }

  _continueFinal (err) {
    if (this._pendingFinal === null) return
    const cb = this._pendingFinal
    this._pendingFinal = null
    cb(err)
  }

  _continueDestroy () {
    if (this._pendingDestroy === null) return
    const cb = this._pendingDestroy
    this._pendingDestroy = null
    cb(null)
  }

  _onconnect (err) {
    if (err) {
      if (this._pendingOpen) this._continueOpen(err)
      else this.destroy(err)
      return
    }

    this._state |= constants.state.CONNECTED
    this._state &= ~constants.state.CONNECTING
    this._continueOpen()

    this.emit('connect')
  }

  _onread (err, read) {
    if (this._timer) this._timer.refresh()

    if (err) {
      this.destroy(err)
      return
    }

    if (read === 0) {
      this.push(null)
      if (this._allowHalfOpen === false) this.end()
      return
    }

    const copy = Buffer.allocUnsafe(read)
    copy.set(this._buffer.subarray(0, read))

    if (this.push(copy) === false && this.destroying === false) {
      this._state &= ~constants.state.READING
      binding.pause(this._handle)
    }
  }

  _onwrite (err) {
    if (this._timer) this._timer.refresh()

    this._continueWrite(err)
  }

  _onfinal (err) {
    this._continueFinal(err)
  }

  _onclose () {
    clearTimeout(this._timer)

    this._handle = null
    this._continueDestroy()
  }

  static _sockets = new Set()
}

const Server = exports.Server = class TCPServer extends EventEmitter {
  constructor (opts = {}, onconnection) {
    if (typeof opts === 'function') {
      onconnection = opts
      opts = {}
    }

    super()

    const {
      readBufferSize = defaultReadBufferSize,
      allowHalfOpen = true
    } = opts

    this._state = 0

    this._readBufferSize = readBufferSize
    this._allowHalfOpen = allowHalfOpen

    this._keepAlive = opts.keepAlive
    this._keepAliveDelay = opts.keepAliveInitialDelay
    this._noDelay = opts.noDelay

    this._port = -1
    this._host = null
    this._family = 0
    this._connections = new Set()

    this._error = null
    this._handle = null

    if (onconnection) this.on('connection', onconnection)

    TCPServer._servers.add(this)
  }

  get listening () {
    return (this._state & constants.state.BOUND) !== 0
  }

  address () {
    if ((this._state & constants.state.BOUND) === 0) {
      return null
    }

    return {
      address: this._host,
      family: `IPv${this._family}`,
      port: this._port
    }
  }

  listen (port = 0, host = 'localhost', backlog = 511, opts = {}, onlistening) {
    if (this._state & constants.state.BINDING || this._state & constants.state.BOUND) {
      throw errors.SERVER_ALREADY_LISTENING('Server is already listening')
    }

    if (this._state & constants.state.CLOSING) {
      throw errors.SERVER_IS_CLOSED('Server is closed')
    }

    this._state |= constants.state.BINDING

    if (typeof port === 'function') {
      onlistening = port
      port = 0
    } else if (typeof host === 'function') {
      onlistening = host
      host = 'localhost'
    } else if (typeof backlog === 'function') {
      onlistening = backlog
      backlog = 511
    } else if (typeof opts === 'function') {
      onlistening = opts
      opts = {}
    }

    let family = 0

    if (typeof port === 'object' && port !== null) {
      opts = port || {}
      port = opts.port || 0
      host = opts.host || 'localhost'
      family = opts.family || 0
      backlog = opts.backlog || 511
    }

    if (!host) host = 'localhost'
    if (!backlog) backlog = 511

    const type = ip.isIP(host)

    if (type === 0) {
      const {
        lookup = dns.lookup,
        hints
      } = opts

      lookup(host, { family, hints }, (err, address, family) => {
        if (this._state & constants.state.CLOSING) return

        this.emit('lookup', err, address, family, host)

        this._state &= ~constants.state.BINDING

        if (err) return this.emit('error', err)

        this.listen(port, address, backlog, { ...opts, family }, onlistening)
      })

      return this
    }

    family = type

    this._handle = binding.init(empty, this,
      this._onconnection,
      noop,
      noop,
      noop,
      noop,
      this._onclose
    )

    if (this._state & constants.state.UNREFED) binding.unref(this._handle)

    try {
      this._port = binding.bind(this._handle, port, host, backlog, family)
      this._host = host
      this._family = family
      this._state |= constants.state.BOUND
      this._state &= ~constants.state.BINDING

      if (onlistening) this.once('listening', onlistening)

      queueMicrotask(() => this.emit('listening'))
    } catch (err) {
      this._error = err

      binding.close(this._handle)
    }

    return this
  }

  close (onclose) {
    if (onclose) this.once('close', onclose)
    if (this._state & constants.state.CLOSING) return
    this._state |= constants.state.CLOSING
    this._closeMaybe()
  }

  ref () {
    this._state &= ~constants.state.UNREFED
    if (this._handle !== null) binding.ref(this._handle)
  }

  unref () {
    this._state |= constants.state.UNREFED
    if (this._handle !== null) binding.unref(this._handle)
  }

  _closeMaybe () {
    if ((this._state & constants.state.CLOSING) && this._connections.size === 0) {
      if (this._handle !== null) binding.close(this._handle)
      else queueMicrotask(() => this.emit('close'))
      TCPServer._servers.delete(this)
    }
  }

  _onconnection (err) {
    if (err) {
      this.emit('error', err)
      return
    }

    if (this._state & constants.state.CLOSING) return

    const socket = new Socket({
      readBufferSize: this._readBufferSize,
      allowHalfOpen: this._allowHalfOpen
    })

    try {
      binding.accept(this._handle, socket._handle)

      socket._state |= constants.state.CONNECTED

      this._connections.add(socket)

      if (this._keepAlive === true) socket.setKeepAlive(this._keepAlive, this._keepAliveDelay)
      if (this._noDelay === true) socket.setNoDelay()

      socket.on('close', () => {
        this._connections.delete(socket)
        this._closeMaybe()
      })

      this.emit('connection', socket)
    } catch (err) {
      socket.destroy()

      throw err
    }
  }

  _onclose () {
    const err = this._error

    this._state &= ~constants.state.BINDING
    this._error = null
    this._handle = null

    if (err) this.emit('error', err)
    else this.emit('close')
  }

  static _servers = new Set()
}

exports.constants = constants
exports.errors = errors

exports.isIP = ip.isIP
exports.isIPv4 = ip.isIPv4
exports.isIPv6 = ip.isIPv6

exports.createConnection = function createConnection (port, host, opts, onconnect) {
  if (typeof host === 'function') {
    onconnect = host
    host = 'localhost'
  } else if (typeof opts === 'function') {
    onconnect = opts
    opts = {}
  }

  if (typeof port === 'object' && port !== null) {
    opts = port || {}
    port = opts.port || 0
    host = opts.host || 'localhost'
  }

  return new Socket(opts).connect(port, host, opts, onconnect)
}

// For Node.js compatibility
exports.connect = exports.createConnection

exports.createServer = function createServer (opts, onconnection) {
  return new Server(opts, onconnection)
}

Bare
  .on('exit', () => {
    for (const socket of Socket._sockets) {
      socket.destroy()
    }

    for (const server of Server._servers) {
      server.close()
    }
  })

const empty = Buffer.alloc(0)

function noop () {}
module.exports = {
  state: {
    CONNECTING: 0x1,
    CONNECTED: 0x2,
    BINDING: 0x4,
    BOUND: 0x8,
    READING: 0x10,
    CLOSING: 0x20,
    UNREFED: 0x40
  }
}
module.exports = class TCPError extends Error {
  constructor (msg, code, fn = TCPError) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name () {
    return 'TCPError'
  }

  static SOCKET_ALREADY_CONNECTED (msg) {
    return new TCPError(msg, 'SOCKET_ALREADY_CONNECTED', TCPError.SOCKET_ALREADY_CONNECTED)
  }

  static SERVER_ALREADY_LISTENING (msg) {
    return new TCPError(msg, 'SERVER_ALREADY_LISTENING', TCPError.SERVER_ALREADY_LISTENING)
  }

  static SERVER_IS_CLOSED (msg) {
    return new TCPError(msg, 'SERVER_IS_CLOSED', TCPError.SERVER_IS_CLOSED)
  }

  static INVALID_HOST (msg = 'Unrecognizable host format') {
    return new TCPError(msg, 'INVALID_HOST', TCPError.INVALID_HOST)
  }
}
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

const v4Seg = '(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])'
const v4Str = `(${v4Seg}[.]){3}${v4Seg}`
const IPv4Pattern = new RegExp(`^${v4Str}$`)

const v6Seg = '(?:[0-9a-fA-F]{1,4})'
const IPv6Pattern = new RegExp('^(' +
  `(?:${v6Seg}:){7}(?:${v6Seg}|:)|` +
  `(?:${v6Seg}:){6}(?:${v4Str}|:${v6Seg}|:)|` +
  `(?:${v6Seg}:){5}(?::${v4Str}|(:${v6Seg}){1,2}|:)|` +
  `(?:${v6Seg}:){4}(?:(:${v6Seg}){0,1}:${v4Str}|(:${v6Seg}){1,3}|:)|` +
  `(?:${v6Seg}:){3}(?:(:${v6Seg}){0,2}:${v4Str}|(:${v6Seg}){1,4}|:)|` +
  `(?:${v6Seg}:){2}(?:(:${v6Seg}){0,3}:${v4Str}|(:${v6Seg}){1,5}|:)|` +
  `(?:${v6Seg}:){1}(?:(:${v6Seg}){0,4}:${v4Str}|(:${v6Seg}){1,6}|:)|` +
  `(?::((?::${v6Seg}){0,5}:${v4Str}|(?::${v6Seg}){1,7}|:))` +
')(%[0-9a-zA-Z-.:]{1,})?$')

const isIPv4 = exports.isIPv4 = function isIPv4 (host) {
  return IPv4Pattern.test(host)
}

const isIPv6 = exports.isIPv6 = function isIPv6 (host) {
  return IPv6Pattern.test(host)
}

exports.isIP = function isIP (host) {
  if (isIPv4(host)) return 4
  if (isIPv6(host)) return 6
  return 0
}
{
  "name": "bare-tcp",
  "version": "1.9.1",
  "description": "Native TCP sockets for JavaScript",
  "exports": {
    ".": "./index.js",
    "./package": "./package.json",
    "./constants": "./lib/constants.js",
    "./errors": "./lib/errors.js"
  },
  "files": [
    "index.js",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "standard && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-tcp.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-tcp/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-tcp#readme",
  "dependencies": {
    "bare-dns": "^1.0.0",
    "bare-events": "^2.2.2",
    "bare-stream": "^2.0.0"
  },
  "devDependencies": {
    "brittle": "^3.5.0",
    "cmake-bare": "^1.1.6",
    "standard": "^17.1.0"
  }
}
{
  "name": "bare-net",
  "version": "1.0.1",
  "description": "TCP and IPC servers and clients for JavaScript",
  "exports": {
    ".": "./index.js",
    "./package": "./package.json"
  },
  "files": [
    "index.js"
  ],
  "scripts": {
    "test": "standard && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-net.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-net/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-net#readme",
  "dependencies": {
    "bare-events": "^2.2.2",
    "bare-pipe": "^3.2.0",
    "bare-stream": "^2.0.0",
    "bare-tcp": "^1.4.0"
  },
  "devDependencies": {
    "brittle": "^3.3.0",
    "standard": "^17.0.0"
  }
}
module.exports = require.addon()
const binding = require('./binding')
const errors = require('./lib/errors')
const constants = require('./lib/constants')

exports.constants = constants
exports.errors = errors

exports.EOL = binding.platform === 'win32' ? '\r\n' : '\n'

exports.devNull = binding.platform === 'win32' ? '\\\\.\\nul' : '/dev/null'

exports.platform = function platform() {
  return binding.platform
}

exports.arch = function arch() {
  return binding.arch
}

exports.type = binding.type
exports.version = binding.version
exports.release = binding.release
exports.machine = binding.machine
exports.execPath = binding.execPath
exports.pid = binding.pid
exports.ppid = binding.ppid
exports.cwd = binding.cwd
exports.chdir = binding.chdir
exports.tmpdir = binding.tmpdir
exports.homedir = binding.homedir
exports.hostname = binding.hostname
exports.userInfo = binding.userInfo
exports.groupInfo = binding.groupInfo

exports.networkInterfaces = function networkInterfaces() {
  const result = {}

  for (const entry of binding.networkInterfaces()) {
    const { name, ...properties } = entry

    if (result[name]) result[name].push(properties)
    else result[name] = [properties]
  }

  return result
}

exports.kill = function kill(pid, signal = constants.signals.SIGTERM) {
  if (typeof signal === 'string') {
    if (signal in constants.signals === false) {
      throw errors.UNKNOWN_SIGNAL('Unknown signal: ' + signal)
    }

    signal = constants.signals[signal]
  }

  binding.kill(pid, signal)
}

exports.endianness = function endianness() {
  return binding.isLittleEndian ? 'LE' : 'BE'
}

exports.availableParallelism = binding.availableParallelism

exports.cpuUsage = function cpuUsage(previous) {
  const current = binding.cpuUsage()

  if (previous) {
    return {
      user: current.user - previous.user,
      system: current.system - previous.system
    }
  }

  return current
}

exports.threadCpuUsage = function threadCpuUsage(previous) {
  const current = binding.threadCpuUsage()

  if (previous) {
    return {
      user: current.user - previous.user,
      system: current.system - previous.system
    }
  }

  return current
}

exports.resourceUsage = binding.resourceUsage
exports.memoryUsage = binding.memoryUsage
exports.freemem = binding.freemem
exports.totalmem = binding.totalmem
exports.availableMemory = binding.availableMemory
exports.constrainedMemory = binding.constrainedMemory
exports.uptime = binding.uptime
exports.loadavg = binding.loadavg
exports.cpus = binding.cpus

exports.getProcessTitle = binding.getProcessTitle

exports.setProcessTitle = function setProcessTitle(title) {
  if (typeof title !== 'string') title = title.toString()

  if (title.length >= 256) {
    throw errors.TITLE_OVERFLOW('Process title is too long')
  }

  binding.setProcessTitle(title)
}

exports.getPriority = function getPriority(pid = 0) {
  return binding.getPriority(pid)
}

exports.setPriority = function setPriority(pid, priority) {
  if (priority === undefined) {
    priority = pid
    pid = 0
  }

  binding.setPriority(pid, priority)
}

exports.getEnvKeys = binding.getEnvKeys
exports.getEnv = binding.getEnv
exports.hasEnv = binding.hasEnv
exports.setEnv = binding.setEnv
exports.unsetEnv = binding.unsetEnv
const binding = require('../binding')

module.exports = {
  signals: binding.signals,
  errnos: binding.errnos,
  priority: binding.priority
}
module.exports = class OSError extends Error {
  constructor(msg, fn = OSError, code = fn.name) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'OSError'
  }

  static UNKNOWN_SIGNAL(msg) {
    return new OSError(msg, OSError.UNKNOWN_SIGNAL)
  }

  static TITLE_OVERFLOW(msg) {
    return new OSError(msg, OSError.TITLE_OVERFLOW)
  }
}
{
  "name": "bare-os",
  "version": "3.9.1",
  "description": "Operating system utilities for Bare",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    },
    "./errors": {
      "types": "./lib/errors.d.ts",
      "default": "./lib/errors.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-os.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-os/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-os#readme",
  "engines": {
    "bare": ">=1.14.0"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "cmake-bare": "^1.1.6",
    "lunte": "^1.6.0",
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
/* global Bare */

// This export SHOULD NOT be shortened in any way as having the full
// `module.exports = require(...)` statement is crucial for synthesizing
// ESM exports.

if (Bare.platform === 'win32') {
  module.exports = require('./lib/win32')
} else {
  module.exports = require('./lib/posix')
}
module.exports = {
  CHAR_UPPERCASE_A: 0x41,
  CHAR_LOWERCASE_A: 0x61,
  CHAR_UPPERCASE_Z: 0x5a,
  CHAR_LOWERCASE_Z: 0x7a,
  CHAR_DOT: 0x2e,
  CHAR_FORWARD_SLASH: 0x2f,
  CHAR_BACKWARD_SLASH: 0x5c,
  CHAR_COLON: 0x3a,
  CHAR_QUESTION_MARK: 0x3f
}
const os = require('bare-os')

const { normalizeString } = require('./shared')
const {
  CHAR_DOT,
  CHAR_FORWARD_SLASH
} = require('./constants')

function isPosixPathSeparator (code) {
  return code === CHAR_FORWARD_SLASH
}

exports.win32 = require('./win32')
exports.posix = exports

exports.sep = '/'
exports.delimiter = ':'

exports.resolve = function resolve (...args) {
  let resolvedPath = ''
  let resolvedAbsolute = false

  for (let i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) {
    const path = i >= 0 ? args[i] : os.cwd()

    if (path.length === 0) {
      continue
    }

    resolvedPath = `${path}/${resolvedPath}`
    resolvedAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH
  }

  resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute, '/', isPosixPathSeparator)

  if (resolvedAbsolute) {
    return `/${resolvedPath}`
  }

  return resolvedPath.length > 0 ? resolvedPath : '.'
}

exports.normalize = function normalize (path) {
  if (path.length === 0) return '.'

  const isAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH
  const trailingSeparator = path.charCodeAt(path.length - 1) === CHAR_FORWARD_SLASH

  path = normalizeString(path, !isAbsolute, '/', isPosixPathSeparator)

  if (path.length === 0) {
    if (isAbsolute) return '/'
    return trailingSeparator ? './' : '.'
  }

  if (trailingSeparator) path += '/'

  return isAbsolute ? `/${path}` : path
}

exports.isAbsolute = function isAbsolute (path) {
  return path.length > 0 && path.charCodeAt(0) === CHAR_FORWARD_SLASH
}

exports.join = function join (...args) {
  if (args.length === 0) return '.'
  let joined
  for (let i = 0; i < args.length; ++i) {
    const arg = args[i]
    if (arg.length > 0) {
      if (joined === undefined) joined = arg
      else joined += `/${arg}`
    }
  }
  if (joined === undefined) return '.'
  return exports.normalize(joined)
}

exports.relative = function relative (from, to) {
  if (from === to) return ''

  from = exports.resolve(from)
  to = exports.resolve(to)

  if (from === to) return ''

  const fromStart = 1
  const fromEnd = from.length
  const fromLen = fromEnd - fromStart
  const toStart = 1
  const toLen = to.length - toStart

  const length = (fromLen < toLen ? fromLen : toLen)
  let lastCommonSep = -1
  let i = 0
  for (; i < length; i++) {
    const fromCode = from.charCodeAt(fromStart + i)
    if (fromCode !== to.charCodeAt(toStart + i)) {
      break
    } else if (fromCode === CHAR_FORWARD_SLASH) {
      lastCommonSep = i
    }
  }
  if (i === length) {
    if (toLen > length) {
      if (to.charCodeAt(toStart + i) === CHAR_FORWARD_SLASH) {
        return to.substring(toStart + i + 1)
      }
      if (i === 0) {
        return to.substring(toStart + i)
      }
    } else if (fromLen > length) {
      if (from.charCodeAt(fromStart + i) === CHAR_FORWARD_SLASH) {
        lastCommonSep = i
      } else if (i === 0) {
        lastCommonSep = 0
      }
    }
  }

  let out = ''
  for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
    if (i === fromEnd || from.charCodeAt(i) === CHAR_FORWARD_SLASH) {
      out += out.length === 0 ? '..' : '/..'
    }
  }

  return `${out}${to.substring(toStart + lastCommonSep)}`
}

exports.toNamespacedPath = function toNamespacedPath (path) {
  return path
}

exports.dirname = function dirname (path) {
  if (path.length === 0) return '.'
  const hasRoot = path.charCodeAt(0) === CHAR_FORWARD_SLASH
  let end = -1
  let matchedSlash = true
  for (let i = path.length - 1; i >= 1; --i) {
    if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) {
      if (!matchedSlash) {
        end = i
        break
      }
    } else {
      matchedSlash = false
    }
  }

  if (end === -1) return hasRoot ? '/' : '.'
  if (hasRoot && end === 1) return '//'
  return path.substring(0, end)
}

exports.basename = function basename (path, suffix) {
  let start = 0
  let end = -1
  let matchedSlash = true

  if (suffix !== undefined && suffix.length > 0 && suffix.length <= path.length) {
    if (suffix === path) { return '' }
    let extIdx = suffix.length - 1
    let firstNonSlashEnd = -1
    for (let i = path.length - 1; i >= 0; --i) {
      const code = path.charCodeAt(i)
      if (code === CHAR_FORWARD_SLASH) {
        if (!matchedSlash) {
          start = i + 1
          break
        }
      } else {
        if (firstNonSlashEnd === -1) {
          matchedSlash = false
          firstNonSlashEnd = i + 1
        }
        if (extIdx >= 0) {
          if (code === suffix.charCodeAt(extIdx)) {
            if (--extIdx === -1) {
              end = i
            }
          } else {
            extIdx = -1
            end = firstNonSlashEnd
          }
        }
      }
    }

    if (start === end) end = firstNonSlashEnd
    else if (end === -1) end = path.length
    return path.substring(start, end)
  }

  for (let i = path.length - 1; i >= 0; --i) {
    if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) {
      if (!matchedSlash) {
        start = i + 1
        break
      }
    } else if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
  }

  if (end === -1) return ''
  return path.substring(start, end)
}

exports.extname = function extname (path) {
  let startDot = -1
  let startPart = 0
  let end = -1
  let matchedSlash = true
  let preDotState = 0
  for (let i = path.length - 1; i >= 0; --i) {
    const code = path.charCodeAt(i)
    if (code === CHAR_FORWARD_SLASH) {
      if (!matchedSlash) {
        startPart = i + 1
        break
      }
      continue
    }
    if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
    if (code === CHAR_DOT) {
      if (startDot === -1) startDot = i
      else if (preDotState !== 1) preDotState = 1
    } else if (startDot !== -1) {
      preDotState = -1
    }
  }

  if (startDot === -1 || end === -1 || preDotState === 0 || (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1)) {
    return ''
  }
  return path.substring(startDot, end)
}
const {
  CHAR_DOT,
  CHAR_FORWARD_SLASH
} = require('./constants')

exports.normalizeString = function normalizeString (path, allowAboveRoot, separator, isPathSeparator) {
  let res = ''
  let lastSegmentLength = 0
  let lastSlash = -1
  let dots = 0
  let code = 0
  for (let i = 0; i <= path.length; ++i) {
    if (i < path.length) {
      code = path.charCodeAt(i)
    } else if (isPathSeparator(code)) {
      break
    } else {
      code = CHAR_FORWARD_SLASH
    }

    if (isPathSeparator(code)) {
      if (lastSlash === i - 1 || dots === 1) ;
      else if (dots === 2) {
        if (res.length < 2 || lastSegmentLength !== 2 || res.charCodeAt(res.length - 1) !== CHAR_DOT || res.charCodeAt(res.length - 2) !== CHAR_DOT) {
          if (res.length > 2) {
            const lastSlashIndex = res.lastIndexOf(separator)
            if (lastSlashIndex === -1) {
              res = ''
              lastSegmentLength = 0
            } else {
              res = res.substring(0, lastSlashIndex)
              lastSegmentLength =
                res.length - 1 - res.lastIndexOf(separator)
            }
            lastSlash = i
            dots = 0
            continue
          } else if (res.length !== 0) {
            res = ''
            lastSegmentLength = 0
            lastSlash = i
            dots = 0
            continue
          }
        }
        if (allowAboveRoot) {
          res += res.length > 0 ? `${separator}..` : '..'
          lastSegmentLength = 2
        }
      } else {
        if (res.length > 0) {
          res += `${separator}${path.substring(lastSlash + 1, i)}`
        } else {
          res = path.substring(lastSlash + 1, i)
        }
        lastSegmentLength = i - lastSlash - 1
      }
      lastSlash = i
      dots = 0
    } else if (code === CHAR_DOT && dots !== -1) {
      ++dots
    } else {
      dots = -1
    }
  }
  return res
}
const os = require('bare-os')

const { normalizeString } = require('./shared')
const {
  CHAR_UPPERCASE_A,
  CHAR_LOWERCASE_A,
  CHAR_UPPERCASE_Z,
  CHAR_LOWERCASE_Z,
  CHAR_DOT,
  CHAR_FORWARD_SLASH,
  CHAR_BACKWARD_SLASH,
  CHAR_COLON,
  CHAR_QUESTION_MARK
} = require('./constants')

function isWindowsPathSeparator (code) {
  return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH
}

function isWindowsDeviceRoot (code) {
  return (code >= CHAR_UPPERCASE_A && code <= CHAR_UPPERCASE_Z) ||
         (code >= CHAR_LOWERCASE_A && code <= CHAR_LOWERCASE_Z)
}

exports.posix = require('./posix')
exports.win32 = exports

exports.sep = '\\'
exports.delimiter = ';'

exports.resolve = function resolve (...args) {
  let resolvedDevice = ''
  let resolvedTail = ''
  let resolvedAbsolute = false

  for (let i = args.length - 1; i >= -1; i--) {
    let path
    if (i >= 0) {
      path = args[i]

      if (path.length === 0) continue
    } else if (resolvedDevice.length === 0) {
      path = os.cwd()
    } else {
      path = os.getEnv(`=${resolvedDevice}`) || os.cwd()

      if (path === undefined || (path.substring(0, 2).toLowerCase() !== resolvedDevice.toLowerCase() && path.charCodeAt(2) === CHAR_BACKWARD_SLASH)) {
        path = `${resolvedDevice}\\`
      }
    }

    const len = path.length
    let rootEnd = 0
    let device = ''
    let isAbsolute = false
    const code = path.charCodeAt(0)

    if (len === 1) {
      if (isWindowsPathSeparator(code)) {
        rootEnd = 1
        isAbsolute = true
      }
    } else if (isWindowsPathSeparator(code)) {
      isAbsolute = true

      if (isWindowsPathSeparator(path.charCodeAt(1))) {
        let j = 2
        let last = j
        while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
          j++
        }
        if (j < len && j !== last) {
          const firstPart = path.substring(last, j)
          last = j
          while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
            j++
          }
          if (j < len && j !== last) {
            last = j
            while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
              j++
            }
            if (j === len || j !== last) {
              device = `\\\\${firstPart}\\${path.substring(last, j)}`
              rootEnd = j
            }
          }
        }
      } else {
        rootEnd = 1
      }
    } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
      device = path.substring(0, 2)
      rootEnd = 2
      if (len > 2 && isWindowsPathSeparator(path.charCodeAt(2))) {
        isAbsolute = true
        rootEnd = 3
      }
    }

    if (device.length > 0) {
      if (resolvedDevice.length > 0) {
        if (device.toLowerCase() !== resolvedDevice.toLowerCase()) { continue }
      } else {
        resolvedDevice = device
      }
    }

    if (resolvedAbsolute) {
      if (resolvedDevice.length > 0) { break }
    } else {
      resolvedTail = `${path.substring(rootEnd)}\\${resolvedTail}`
      resolvedAbsolute = isAbsolute
      if (isAbsolute && resolvedDevice.length > 0) {
        break
      }
    }
  }

  resolvedTail = normalizeString(resolvedTail, !resolvedAbsolute, '\\', isWindowsPathSeparator)

  return resolvedAbsolute ? `${resolvedDevice}\\${resolvedTail}` : `${resolvedDevice}${resolvedTail}` || '.'
}

exports.normalize = function normalize (path) {
  const len = path.length
  if (len === 0) return '.'
  let rootEnd = 0
  let device
  let isAbsolute = false
  const code = path.charCodeAt(0)

  if (len === 1) {
    return code === CHAR_FORWARD_SLASH ? '\\' : path
  }

  if (isWindowsPathSeparator(code)) {
    isAbsolute = true

    if (isWindowsPathSeparator(path.charCodeAt(1))) {
      let j = 2
      let last = j
      while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
        j++
      }
      if (j < len && j !== last) {
        const firstPart = path.substring(last, j)
        last = j
        while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
          j++
        }
        if (j < len && j !== last) {
          last = j
          while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
            j++
          }
          if (j === len) {
            return `\\\\${firstPart}\\${path.substring(last)}\\`
          }
          if (j !== last) {
            device = `\\\\${firstPart}\\${path.substring(last, j)}`
            rootEnd = j
          }
        }
      }
    } else {
      rootEnd = 1
    }
  } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
    device = path.substring(0, 2)
    rootEnd = 2
    if (len > 2 && isWindowsPathSeparator(path.charCodeAt(2))) {
      isAbsolute = true
      rootEnd = 3
    }
  }

  let tail = rootEnd < len ? normalizeString(path.substring(rootEnd), !isAbsolute, '\\', isWindowsPathSeparator) : ''
  if (tail.length === 0 && !isAbsolute) {
    tail = '.'
  }
  if (tail.length > 0 && isWindowsPathSeparator(path.charCodeAt(len - 1))) {
    tail += '\\'
  }
  if (device === undefined) {
    return isAbsolute ? `\\${tail}` : tail
  }
  return isAbsolute ? `${device}\\${tail}` : `${device}${tail}`
}

exports.isAbsolute = function isAbsolute (path) {
  const len = path.length
  if (len === 0) return false

  const code = path.charCodeAt(0)

  return isWindowsPathSeparator(code) || (len > 2 && isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON && isWindowsPathSeparator(path.charCodeAt(2)))
}

exports.join = function join (...args) {
  if (args.length === 0) return '.'

  let joined
  let firstPart
  for (let i = 0; i < args.length; ++i) {
    const arg = args[i]
    if (arg.length > 0) {
      if (joined === undefined) joined = firstPart = arg
      else joined += `\\${arg}`
    }
  }

  if (joined === undefined) return '.'

  let needsReplace = true
  let slashCount = 0
  if (isWindowsPathSeparator(firstPart.charCodeAt(0))) {
    ++slashCount
    const firstLen = firstPart.length
    if (firstLen > 1 && isWindowsPathSeparator(firstPart.charCodeAt(1))) {
      ++slashCount
      if (firstLen > 2) {
        if (isWindowsPathSeparator(firstPart.charCodeAt(2))) {
          ++slashCount
        } else {
          needsReplace = false
        }
      }
    }
  }
  if (needsReplace) {
    while (slashCount < joined.length && isWindowsPathSeparator(joined.charCodeAt(slashCount))) {
      slashCount++
    }

    if (slashCount >= 2) {
      joined = `\\${joined.substring(slashCount)}`
    }
  }

  return exports.normalize(joined)
}

exports.relative = function relative (from, to) {
  if (from === to) return ''

  const fromOrig = exports.resolve(from)
  const toOrig = exports.resolve(to)

  if (fromOrig === toOrig) return ''

  from = fromOrig.toLowerCase()
  to = toOrig.toLowerCase()

  if (from === to) return ''

  let fromStart = 0
  while (fromStart < from.length && from.charCodeAt(fromStart) === CHAR_BACKWARD_SLASH) {
    fromStart++
  }
  let fromEnd = from.length
  while (fromEnd - 1 > fromStart && from.charCodeAt(fromEnd - 1) === CHAR_BACKWARD_SLASH) {
    fromEnd--
  }
  const fromLen = fromEnd - fromStart

  let toStart = 0
  while (toStart < to.length && to.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) {
    toStart++
  }
  let toEnd = to.length
  while (toEnd - 1 > toStart && to.charCodeAt(toEnd - 1) === CHAR_BACKWARD_SLASH) {
    toEnd--
  }
  const toLen = toEnd - toStart

  const length = fromLen < toLen ? fromLen : toLen
  let lastCommonSep = -1
  let i = 0
  for (; i < length; i++) {
    const fromCode = from.charCodeAt(fromStart + i)
    if (fromCode !== to.charCodeAt(toStart + i)) {
      break
    } else if (fromCode === CHAR_BACKWARD_SLASH) {
      lastCommonSep = i
    }
  }

  if (i !== length) {
    if (lastCommonSep === -1) return toOrig
  } else {
    if (toLen > length) {
      if (to.charCodeAt(toStart + i) === CHAR_BACKWARD_SLASH) {
        return toOrig.substring(toStart + i + 1)
      }
      if (i === 2) {
        return toOrig.substring(toStart + i)
      }
    }
    if (fromLen > length) {
      if (from.charCodeAt(fromStart + i) === CHAR_BACKWARD_SLASH) {
        lastCommonSep = i
      } else if (i === 2) {
        lastCommonSep = 3
      }
    }
    if (lastCommonSep === -1) lastCommonSep = 0
  }

  let out = ''
  for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
    if (i === fromEnd || from.charCodeAt(i) === CHAR_BACKWARD_SLASH) {
      out += out.length === 0 ? '..' : '\\..'
    }
  }

  toStart += lastCommonSep

  if (out.length > 0) {
    return `${out}${toOrig.substring(toStart, toEnd)}`
  }
  if (toOrig.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) {
    ++toStart
  }
  return toOrig.substring(toStart, toEnd)
}

exports.toNamespacedPath = function toNamespacedPath (path) {
  if (path.length === 0) return path

  const resolvedPath = exports.resolve(path)

  if (resolvedPath.length <= 2) return path

  if (resolvedPath.charCodeAt(0) === CHAR_BACKWARD_SLASH) {
    if (resolvedPath.charCodeAt(1) === CHAR_BACKWARD_SLASH) {
      const code = resolvedPath.charCodeAt(2)
      if (code !== CHAR_QUESTION_MARK && code !== CHAR_DOT) {
        return `\\\\?\\UNC\\${resolvedPath.substring(2)}`
      }
    }
  } else if (
    isWindowsDeviceRoot(resolvedPath.charCodeAt(0)) &&
      resolvedPath.charCodeAt(1) === CHAR_COLON &&
      resolvedPath.charCodeAt(2) === CHAR_BACKWARD_SLASH
  ) {
    return `\\\\?\\${resolvedPath}`
  }

  return path
}

exports.dirname = function dirname (path) {
  const len = path.length
  if (len === 0) return '.'
  let rootEnd = -1
  let offset = 0
  const code = path.charCodeAt(0)

  if (len === 1) {
    return isWindowsPathSeparator(code) ? path : '.'
  }

  if (isWindowsPathSeparator(code)) {
    rootEnd = offset = 1

    if (isWindowsPathSeparator(path.charCodeAt(1))) {
      let j = 2
      let last = j
      while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
        j++
      }
      if (j < len && j !== last) {
        last = j
        while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
          j++
        }
        if (j < len && j !== last) {
          last = j
          while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
            j++
          }
          if (j === len) {
            return path
          }
          if (j !== last) {
            rootEnd = offset = j + 1
          }
        }
      }
    }
  } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
    rootEnd = len > 2 && isWindowsPathSeparator(path.charCodeAt(2)) ? 3 : 2
    offset = rootEnd
  }

  let end = -1
  let matchedSlash = true
  for (let i = len - 1; i >= offset; --i) {
    if (isWindowsPathSeparator(path.charCodeAt(i))) {
      if (!matchedSlash) {
        end = i
        break
      }
    } else {
      matchedSlash = false
    }
  }

  if (end === -1) {
    if (rootEnd === -1) return '.'

    end = rootEnd
  }
  return path.substring(0, end)
}

exports.basename = function basename (path, suffix) {
  let start = 0
  let end = -1
  let matchedSlash = true

  if (path.length >= 2 && isWindowsDeviceRoot(path.charCodeAt(0)) && path.charCodeAt(1) === CHAR_COLON) {
    start = 2
  }

  if (suffix !== undefined && suffix.length > 0 && suffix.length <= path.length) {
    if (suffix === path) return ''
    let extIdx = suffix.length - 1
    let firstNonSlashEnd = -1
    for (let i = path.length - 1; i >= start; --i) {
      const code = path.charCodeAt(i)
      if (isWindowsPathSeparator(code)) {
        if (!matchedSlash) {
          start = i + 1
          break
        }
      } else {
        if (firstNonSlashEnd === -1) {
          matchedSlash = false
          firstNonSlashEnd = i + 1
        }
        if (extIdx >= 0) {
          if (code === suffix.charCodeAt(extIdx)) {
            if (--extIdx === -1) {
              end = i
            }
          } else {
            extIdx = -1
            end = firstNonSlashEnd
          }
        }
      }
    }

    if (start === end) end = firstNonSlashEnd
    else if (end === -1) end = path.length
    return path.substring(start, end)
  }
  for (let i = path.length - 1; i >= start; --i) {
    if (isWindowsPathSeparator(path.charCodeAt(i))) {
      if (!matchedSlash) {
        start = i + 1
        break
      }
    } else if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
  }

  if (end === -1) return ''
  return path.substring(start, end)
}

exports.extname = function extname (path) {
  let start = 0
  let startDot = -1
  let startPart = 0
  let end = -1
  let matchedSlash = true
  let preDotState = 0

  if (path.length >= 2 && path.charCodeAt(1) === CHAR_COLON && isWindowsDeviceRoot(path.charCodeAt(0))) {
    start = startPart = 2
  }

  for (let i = path.length - 1; i >= start; --i) {
    const code = path.charCodeAt(i)
    if (isWindowsPathSeparator(code)) {
      if (!matchedSlash) {
        startPart = i + 1
        break
      }
      continue
    }
    if (end === -1) {
      matchedSlash = false
      end = i + 1
    }
    if (code === CHAR_DOT) {
      if (startDot === -1) startDot = i
      else if (preDotState !== 1) preDotState = 1
    } else if (startDot !== -1) {
      preDotState = -1
    }
  }

  if (startDot === -1 || end === -1 || preDotState === 0 || (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1)) {
    return ''
  }
  return path.substring(startDot, end)
}
{
  "name": "bare-path",
  "version": "3.0.0",
  "description": "Path manipulation library for JavaScript",
  "exports": {
    ".": "./index.js",
    "./package": "./package.json",
    "./posix": "./lib/posix.js",
    "./win32": "./lib/win32.js"
  },
  "files": [
    "index.js",
    "lib",
    "NOTICE"
  ],
  "scripts": {
    "test": "standard && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-path.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-path/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-path#readme",
  "dependencies": {
    "bare-os": "^3.0.1"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "standard": "^17.0.0"
  }
}
module.exports = require.addon()
const EventEmitter = require('bare-events')
const { Duplex } = require('bare-stream')
const binding = require('./binding')
const constants = require('./lib/constants')
const errors = require('./lib/errors')

const defaultReadBufferSize = 65536
const empty = Buffer.alloc(0)

module.exports = exports = class Pipe extends Duplex {
  constructor(path, opts = {}) {
    if (typeof path === 'object' && path !== null) {
      opts = path
      path = null
    }

    const { readBufferSize = defaultReadBufferSize, allowHalfOpen = true, eagerOpen = true } = opts

    super({ eagerOpen })

    this._state = 0

    this._allowHalfOpen = allowHalfOpen

    this._fd = -1
    this._path = null

    this._pendingOpen = null
    this._pendingWrite = null
    this._pendingFinal = null
    this._pendingDestroy = null

    this._buffer = Buffer.alloc(readBufferSize)

    this._handle = binding.init(
      this._buffer,
      this,
      noop,
      this._onconnect,
      this._onwrite,
      this._onfinal,
      this._onread,
      this._onclose
    )

    if (typeof path === 'number') {
      this.open(path)
    } else if (typeof path === 'string') {
      this.connect(path)
    }
  }

  get connecting() {
    return (this._state & constants.state.CONNECTING) !== 0
  }

  get pending() {
    return (this._state & constants.state.CONNECTED) === 0
  }

  get readyState() {
    if (this._state & constants.state.READABLE && this._state & constants.state.WRITABLE) {
      return 'open'
    }

    if (this._state & constants.state.READABLE) {
      return 'readOnly'
    }

    if (this._state & constants.state.WRITABLE) {
      return 'writeOnly'
    }

    return 'opening'
  }

  open(fd, opts = {}, onconnect) {
    if (typeof opts === 'function') {
      onconnect = opts
      opts = {}
    }

    if (typeof fd === 'object' && fd !== null) {
      opts = fd || {}
      fd = opts.fd
    }

    try {
      const status = binding.open(this._handle, fd)

      this._state |= constants.state.CONNECTED
      this._fd = fd

      if (status & binding.READABLE) {
        this._state |= constants.state.READABLE
      } else {
        this.push(null)
      }

      if (status & binding.WRITABLE) {
        this._state |= constants.state.WRITABLE
      } else {
        this.end()
      }

      if (onconnect) this.once('connect', onconnect)

      queueMicrotask(() => this.emit('connect'))
    } catch (err) {
      queueMicrotask(() => {
        if (this._pendingOpen) this._pendingOpen(err)
        else this.destroy(err)
      })
    }

    return this
  }

  connect(path, opts = {}, onconnect) {
    if (this._state & constants.state.CONNECTING || this._state & constants.state.CONNECTED) {
      throw errors.PIPE_ALREADY_CONNECTED('Pipe is already connected')
    }

    this._state |= constants.state.CONNECTING

    if (typeof opts === 'function') {
      onconnect = opts
      opts = {}
    }

    if (typeof path === 'object' && path !== null) {
      opts = path || {}
      path = opts.path
    }

    try {
      binding.connect(this._handle, path)

      this._path = path

      if (onconnect) this.once('connect', onconnect)
    } catch (err) {
      queueMicrotask(() => {
        if (this._pendingOpen) this._pendingOpen(err)
        else this.destroy(err)
      })
    }

    return this
  }

  ref() {
    binding.ref(this._handle)

    return this
  }

  unref() {
    binding.unref(this._handle)

    return this
  }

  _open(cb) {
    if (this._state & constants.state.CONNECTED) return cb(null)

    this._pendingOpen = cb
  }

  _read() {
    if ((this._state & constants.state.READING) === 0) {
      this._state |= constants.state.READING

      binding.resume(this._handle)
    }
  }

  _writev(batch, cb) {
    this._pendingWrite = [cb, batch]

    binding.writev(
      this._handle,
      batch.map(({ chunk }) => chunk)
    )
  }

  _final(cb) {
    if (this._state & constants.state.READABLE && this._state & constants.state.WRITABLE) {
      this._pendingFinal = cb

      binding.end(this._handle)
    } else {
      cb(null)
    }
  }

  _predestroy() {
    if (this._state & constants.state.CLOSING) return
    this._state |= constants.state.CLOSING

    binding.close(this._handle)
  }

  _destroy(err, cb) {
    if (this._state & constants.state.CLOSING) return cb(err)
    this._state |= constants.state.CLOSING

    this._pendingDestroy = cb

    binding.close(this._handle)
  }

  _continueOpen(err) {
    if (this._pendingOpen === null) return
    const cb = this._pendingOpen
    this._pendingOpen = null
    cb(err)
  }

  _continueWrite(err) {
    if (this._pendingWrite === null) return
    const cb = this._pendingWrite[0]
    this._pendingWrite = null
    cb(err)
  }

  _continueFinal(err) {
    if (this._pendingFinal === null) return
    const cb = this._pendingFinal
    this._pendingFinal = null
    cb(err)
  }

  _continueDestroy() {
    if (this._pendingDestroy === null) return
    const cb = this._pendingDestroy
    this._pendingDestroy = null
    cb(null)
  }

  _onconnect(err) {
    if (err) {
      if (this._pendingOpen) this._continueOpen(err)
      else this.destroy(err)
      return
    }

    this._state |= constants.state.CONNECTED | constants.state.READABLE | constants.state.WRITABLE
    this._state &= ~constants.state.CONNECTING
    this._continueOpen()

    this.emit('connect')
  }

  _onread(err, read) {
    if (err) {
      this.destroy(err)
      return
    }

    if (read === 0) {
      this.push(null)
      if (this._allowHalfOpen === false) this.end()
      return
    }

    const copy = Buffer.allocUnsafe(read)
    copy.set(this._buffer.subarray(0, read))

    if (this.push(copy) === false && this.destroying === false) {
      this._state &= ~constants.state.READING

      binding.pause(this._handle)
    }
  }

  _onwrite(err) {
    this._continueWrite(err)
  }

  _onfinal(err) {
    this._continueFinal(err === null || err.code === 'ENOTCONN' ? null : err)
  }

  _onclose() {
    this._continueDestroy()
  }

  _onspawn(readable, writable) {
    this._state |= constants.state.CONNECTED

    if (readable) {
      this._state |= constants.state.READABLE
    } else {
      this.push(null)
    }

    if (writable) {
      this._state |= constants.state.WRITABLE
    } else {
      this.end()
    }

    this._continueOpen()
  }
}

exports.Pipe = exports

exports.pipe = function pipe() {
  return binding.pipe()
}

exports.Server = class PipeServer extends EventEmitter {
  constructor(opts = {}, onconnection) {
    if (typeof opts === 'function') {
      onconnection = opts
      opts = {}
    }

    super()

    const {
      readBufferSize = defaultReadBufferSize,
      allowHalfOpen = true,
      pauseOnConnect = false
    } = opts

    this._state = 0

    this._readBufferSize = readBufferSize
    this._allowHalfOpen = allowHalfOpen
    this._pauseOnConnect = pauseOnConnect

    this._path = null
    this._connections = new Set()

    this._error = null
    this._handle = null

    if (onconnection) this.on('connection', onconnection)
  }

  get listening() {
    return (this._state & constants.state.BOUND) !== 0
  }

  address() {
    if ((this._state & constants.state.BOUND) === 0) {
      return null
    }

    return this._path
  }

  listen(path, backlog = 511, opts = {}, onlistening) {
    if (this._state & constants.state.BINDING || this._state & constants.state.BOUND) {
      throw errors.SERVER_ALREADY_LISTENING('Server is already listening')
    }

    if (this._state & constants.state.CLOSING) {
      throw errors.SERVER_IS_CLOSED('Server is closed')
    }

    this._state |= constants.state.BINDING

    if (typeof backlog === 'function') {
      onlistening = backlog
      backlog = 511
    } else if (typeof opts === 'function') {
      onlistening = opts
      opts = {}
    }

    if (typeof path === 'object' && path !== null) {
      opts = path || {}
      path = opts.path
      backlog = opts.backlog || 511
    }

    this._handle = binding.init(
      empty,
      this,
      this._onconnection,
      noop,
      noop,
      noop,
      noop,
      this._onclose
    )

    if (this._state & constants.state.UNREFED) binding.unref(this._handle)

    try {
      binding.bind(this._handle, path, backlog)

      this._path = path
      this._state |= constants.state.BOUND
      this._state &= ~constants.state.BINDING

      if (onlistening) this.once('listening', onlistening)

      queueMicrotask(() => this.emit('listening'))
    } catch (err) {
      this._error = err

      binding.close(this._handle)
    }

    return this
  }

  close(onclose) {
    if (onclose) this.once('close', onclose)

    if (this._state & constants.state.CLOSING) return
    this._state |= constants.state.CLOSING

    this._closeMaybe()

    return this
  }

  ref() {
    this._state &= ~constants.state.UNREFED

    if (this._handle !== null) binding.ref(this._handle)

    return this
  }

  unref() {
    this._state |= constants.state.UNREFED

    if (this._handle !== null) binding.unref(this._handle)

    return this
  }

  _closeMaybe() {
    if (this._state & constants.state.CLOSING && this._connections.size === 0) {
      if (this._handle !== null) binding.close(this._handle)
      else queueMicrotask(() => this.emit('close'))
    }
  }

  _onconnection(err) {
    if (err) {
      this.emit('error', err)
      return
    }

    if (this._state & constants.state.CLOSING) return

    const pipe = new exports.Pipe({
      readBufferSize: this._readBufferSize,
      allowHalfOpen: this._allowHalfOpen,
      eagerOpen: !this._pauseOnConnect
    })

    try {
      binding.accept(this._handle, pipe._handle)

      pipe._path = this._path
      pipe._state |= constants.state.CONNECTED | constants.state.READABLE | constants.state.WRITABLE

      this._connections.add(pipe)

      pipe.on('close', () => {
        this._connections.delete(pipe)
        this._closeMaybe()
      })

      this.emit('connection', pipe)
    } catch (err) {
      pipe.destroy()

      throw err
    }
  }

  _onclose() {
    const err = this._error

    this._state &= ~constants.state.BINDING
    this._error = null
    this._handle = null

    if (err) this.emit('error', err)
    else this.emit('close')
  }
}

exports.constants = constants
exports.errors = errors

exports.createConnection = function createConnection(path, opts, onconnect) {
  if (typeof opts === 'function') {
    onconnect = opts
    opts = {}
  }

  if (typeof path === 'object' && path !== null) {
    opts = path || {}
    path = opts.path
  }

  return new exports.Pipe(opts).connect(path, opts, onconnect)
}

exports.createServer = function createServer(opts, onconnection) {
  return new exports.Server(opts, onconnection)
}

function noop() {}
module.exports = {
  state: {
    CONNECTING: 0x1,
    CONNECTED: 0x2,
    BINDING: 0x4,
    BOUND: 0x8,
    READING: 0x10,
    CLOSING: 0x20,
    READABLE: 0x40,
    WRITABLE: 0x80,
    UNREFED: 0x100
  }
}
module.exports = class PipeError extends Error {
  constructor(msg, fn = PipeError, code = fn.name) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'PipeError'
  }

  static PIPE_ALREADY_CONNECTED(msg) {
    return new PipeError(msg, PipeError.PIPE_ALREADY_CONNECTED)
  }

  static SERVER_ALREADY_LISTENING(msg) {
    return new PipeError(msg, PipeError.SERVER_ALREADY_LISTENING)
  }

  static SERVER_IS_CLOSED(msg) {
    return new PipeError(msg, PipeError.SERVER_IS_CLOSED)
  }
}
{
  "name": "bare-pipe",
  "version": "4.1.5",
  "description": "Native I/O pipes for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./constants": {
      "types": "./lib/constants.d.ts",
      "default": "./lib/constants.js"
    },
    "./errors": {
      "types": "./lib/errors.d.ts",
      "default": "./lib/errors.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-pipe.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-pipe/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-pipe#readme",
  "engines": {
    "bare": ">=1.16.0"
  },
  "dependencies": {
    "bare-events": "^2.0.0",
    "bare-stream": "^2.0.0"
  },
  "devDependencies": {
    "bare-path": "^3.0.0",
    "brittle": "^3.2.1",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  }
}
const abort = require('bare-abort')
const EventEmitter = require('bare-events')
const Signal = require('bare-signals')
const os = require('bare-os')
const env = require('bare-env')
const hrtime = require('bare-hrtime')
const stdio = require('bare-stdio')

class Process extends EventEmitter {
  constructor() {
    super()

    this._startTime = hrtime.bigint()

    EventEmitter.forward(Bare, this, [
      'uncaughtException',
      'unhandledRejection',
      'beforeExit',
      'exit',
      'suspend',
      'wakeup',
      'idle',
      'resume'
    ])

    const signals = new Signal.Emitter()

    signals.unref()

    EventEmitter.forward(signals, this, Object.keys(os.constants.signals))
  }

  get stdin() {
    return stdio.in
  }

  get stdout() {
    return stdio.out
  }

  get stderr() {
    return stdio.err
  }

  get platform() {
    return os.platform()
  }

  get arch() {
    return os.arch()
  }

  get title() {
    return os.getProcessTitle()
  }

  set title(title) {
    os.setProcessTitle(title)
  }

  get pid() {
    return os.pid()
  }

  get ppid() {
    return os.ppid()
  }

  get argv() {
    return Bare.argv
  }

  get execPath() {
    return os.execPath()
  }

  get exitCode() {
    return Bare.exitCode
  }

  set exitCode(code) {
    Bare.exitCode = code
  }

  get version() {
    return Bare.version
  }

  get versions() {
    return Bare.versions
  }

  get env() {
    return env
  }

  get hrtime() {
    return hrtime
  }

  abort() {
    abort()
  }

  exit(code) {
    Bare.exit(code)
  }

  suspend() {
    Bare.suspend()
  }

  resume() {
    Bare.resume()
  }

  cwd() {
    return os.cwd()
  }

  chdir(directory) {
    os.chdir(directory)
  }

  kill(pid, signal) {
    os.kill(pid, signal)
  }

  uptime() {
    return Number(hrtime.bigint() - this._startTime) / 1e9
  }

  cpuUsage(previous) {
    return os.cpuUsage(previous)
  }

  threadCpuUsage(previous) {
    return os.threadCpuUsage(previous)
  }

  resourceUsage() {
    return os.resourceUsage()
  }

  availableMemory() {
    return os.availableMemory()
  }

  constrainedMemory() {
    return os.constrainedMemory()
  }

  memoryUsage() {
    return os.memoryUsage()
  }

  nextTick(cb, ...args) {
    queueMicrotask(cb.bind(null, ...args))
  }

  [Symbol.for('bare.inspect')]() {
    return {
      __proto__: { constructor: Process },

      platform: this.platform,
      arch: this.arch,
      title: this.title,
      pid: this.pid,
      ppid: this.ppid,
      argv: this.argv,
      execPath: this.execPath,
      exitCode: this.exitCode,
      version: this.version,
      versions: this.versions,
      env: this.env
    }
  }
}

module.exports = new Process()
{
  "name": "bare-process",
  "version": "4.4.1",
  "description": "Node.js-compatible process control for Bare",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "global.js",
    "global.d.ts"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-process.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-process/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-process#readme",
  "dependencies": {
    "bare-abort": "^2.0.13",
    "bare-env": "^3.0.0",
    "bare-events": "^2.3.1",
    "bare-hrtime": "^2.0.0",
    "bare-os": "^3.7.1",
    "bare-signals": "^4.0.0",
    "bare-stdio": "^1.0.1"
  },
  "devDependencies": {
    "brittle": "^3.2.1",
    "lunte": "^1.6.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = require.addon()
const EventEmitter = require('bare-events')
const os = require('bare-os')
const binding = require('./binding')
const errors = require('./lib/errors')

const signals = os.constants.signals

module.exports = exports = class Signal extends EventEmitter {
  constructor(signum) {
    super()

    if (typeof signum === 'string') {
      if (signum in signals === false) {
        throw errors.UNKNOWN_SIGNAL(`Unknown signal '${signum}'`)
      }

      signum = signals[signum]
    }

    this._signum = signum
    this._closing = null
    this._handle = binding.init(this, this._onsignal, this._onclose)
  }

  start() {
    if (this._closing) throw errors.SIGNAL_CLOSED('Signal is closed')
    binding.start(this._handle, this._signum)
    return this
  }

  stop() {
    if (this._closing) return this
    binding.stop(this._handle)
    return this
  }

  ref() {
    if (this._closing) return this
    binding.ref(this._handle)
    return this
  }

  unref() {
    if (this._closing) return this
    binding.unref(this._handle)
    return this
  }

  close() {
    if (this._closing) return this._closing
    this._closing = EventEmitter.once(this, 'close')

    binding.close(this._handle)

    return this._closing
  }

  _onsignal() {
    this.emit('signal', this._signum)
  }

  _onclose() {
    this._handle = null

    this.emit('close')
  }

  static send(signum, pid = os.pid()) {
    os.kill(pid, signum)
  }
}

exports.Emitter = require('./lib/emitter')

exports.constants = signals
exports.errors = errors
const EventEmitter = require('bare-events')
const Signal = require('..')

module.exports = class SignalEmitter extends EventEmitter {
  constructor() {
    super()

    this._signals = new Map()
    this._unrefed = false

    this.on('newListener', this._onnewlistener).on(
      'removeListener',
      this._onremovelistener
    )
  }

  ref() {
    this._unrefed = false
    for (const signal of this._signals.values()) signal.ref()
    return this
  }

  unref() {
    this._unrefed = true
    for (const signal of this._signals.values()) signal.unref()
    return this
  }

  _onnewlistener(name) {
    if (name === 'newListener' || name === 'removeListener') return

    if (this.listenerCount(name) === 0) {
      const signal = new Signal(name)

      signal.on('signal', this._onsignal.bind(this, name)).start()

      if (this._unrefed) signal.unref()

      this._signals.set(name, signal)
    }
  }

  _onremovelistener(name) {
    if (name === 'newListener' || name === 'removeListener') return

    if (this.listenerCount(name) === 0) {
      const signal = this._signals.get(name)

      if (this._unrefed) signal.ref()

      signal.close()

      this._signals.delete(name)
    }
  }

  _onsignal(name) {
    this.emit(name, name, Signal.constants[name])
  }
}
module.exports = class SignalError extends Error {
  constructor(msg, fn = SignalError, code = fn.name) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'SignalError'
  }

  static UNKNOWN_SIGNAL(msg) {
    return new SignalError(msg, SignalError.UNKNOWN_SIGNAL)
  }

  static SIGNAL_CLOSED(msg) {
    return new SignalError(msg, SignalError.SIGNAL_CLOSED)
  }
}
{
  "name": "bare-signals",
  "version": "4.2.0",
  "description": "Native signal handling for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./errors": "./lib/errors.js",
    "./emitter": "./lib/emitter.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-signals.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-signals/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-signals#readme",
  "engines": {
    "bare": ">=1.7.0"
  },
  "dependencies": {
    "bare-events": "^2.5.3",
    "bare-os": "^3.3.1"
  },
  "devDependencies": {
    "brittle": "^3.2.1",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
module.exports = require.addon()
const fs = require('bare-fs')
const tty = require('bare-tty')
const Pipe = require('bare-pipe')
const binding = require('./binding')

const { TTY, NAMED_PIPE } = binding

class IO {
  constructor() {
    this._in = null
    this._out = null
    this._err = null
  }

  get in() {
    if (this._in === null) {
      switch (binding.guessType(0)) {
        case TTY:
          this._in = new tty.ReadStream(0)
          break
        case NAMED_PIPE:
          this._in = new Pipe(0, { eagerOpen: false })
          break
        default:
          this._in = fs.createReadStream(null, { fd: 0, eagerOpen: false })
      }
    }

    return this._in
  }

  get out() {
    if (this._out === null) {
      switch (binding.guessType(1)) {
        case TTY:
          this._out = new tty.WriteStream(1)
          break
        case NAMED_PIPE:
          this._out = new Pipe(1, { eagerOpen: false })
          this._out.unref()
          break
        default:
          this._out = fs.createWriteStream(null, { fd: 1, eagerOpen: false })
      }
    }

    return this._out
  }

  get err() {
    if (this._err === null) {
      switch (binding.guessType(2)) {
        case TTY:
          this._err = new tty.WriteStream(2)
          break
        case NAMED_PIPE:
          this._err = new Pipe(2, { eagerOpen: false })
          this._err.unref()
          break
        default:
          this._err = fs.createWriteStream(null, { fd: 2, eagerOpen: false })
      }
    }

    return this._err
  }
}

module.exports = new IO()
{
  "name": "bare-stdio",
  "version": "1.0.2",
  "description": "Standard input/output streams for Bare",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./constants": "./lib/constants.js",
    "./errors": "./lib/errors.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-stdio.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-stdio/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-stdio#readme",
  "dependencies": {
    "bare-fs": "^4.5.2",
    "bare-pipe": "^4.1.5",
    "bare-tty": "^5.0.3"
  },
  "devDependencies": {
    "bare-os": "^3.6.2",
    "bare-path": "^3.0.0",
    "bare-subprocess": "^3.1.4",
    "brittle": "^3.19.1",
    "cmake-bare": "^1.7.7",
    "lunte": "^1.4.0",
    "prettier": "^3.8.1",
    "prettier-config-holepunch": "^2.0.0",
    "tt-native": "^1.1.1"
  }
}
const stream = require('streamx')
const { ReadableStream, WritableStream } = require('./web')

const defaultEncoding = 'utf8'

module.exports = exports = stream.Stream

exports.pipeline = stream.pipeline

exports.isStream = stream.isStream
exports.isEnding = stream.isEnding
exports.isEnded = stream.isEnded
exports.isFinishing = stream.isFinishing
exports.isFinished = stream.isFinished
exports.isDisturbed = stream.isDisturbed

exports.isErrored = function isErrored(stream) {
  return exports.getStreamError(stream) !== null
}

exports.isReadable = function isReadable(stream) {
  return stream.readable && !stream.destroying && !exports.isEnded(stream)
}

exports.isWritable = function isWritable(stream) {
  return stream.writable && !stream.destroying && !exports.isFinishing(stream)
}

exports.getStreamError = stream.getStreamError

exports.addAbortSignal = function addAbortSignal(signal, stream) {
  function onAbort() {
    stream.destroy(signal.reason)
  }

  if (signal.aborted) onAbort()
  else signal.addEventListener('abort', onAbort)

  return stream
}

exports.Stream = exports

exports.Readable = class Readable extends stream.Readable {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthReadable: null,
      map: null,
      mapReadable: null
    })

    if (this._construct) this._open = this._construct

    if (this._read !== stream.Readable.prototype._read) {
      this._read = read.bind(this, this._read)
    }

    if (this._destroy !== stream.Stream.prototype._destroy) {
      this._destroy = destroy.bind(this, this._destroy)
    }
  }

  get closed() {
    return !exports.isReadable(this)
  }

  get errored() {
    return stream.getStreamError(this)
  }

  push(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = Buffer.from(chunk, encoding || defaultEncoding)
    }

    return super.push(chunk)
  }

  unshift(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = Buffer.from(chunk, encoding || defaultEncoding)
    }

    super.unshift(chunk)
  }

  static fromWeb(readableStream, opts = {}) {
    const stream = readableStream._stream

    if (opts.encoding) stream.setEncoding(opts.encoding)
    if (opts.signal) exports.addAbortSignal(opts.signal, stream)

    return stream
  }

  static toWeb(readable, opts = {}) {
    return new ReadableStream(readable, opts.strategy)
  }

  async [Symbol.asyncDispose]() {
    if (!this.destroyed) this.destroy()

    await new Promise((resolve) => exports.finished(this, resolve))
  }
}

exports.Writable = class Writable extends stream.Writable {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthWritable,
      map: null,
      mapWritable: null
    })

    if (this._construct) this._open = this._construct

    if (this._write !== stream.Writable.prototype._write) {
      this._write = write.bind(this, this._write)
    }

    if (this._destroy !== stream.Stream.prototype._destroy) {
      this._destroy = destroy.bind(this, this._destroy)
    }
  }

  get closed() {
    return !exports.isWritable(this)
  }

  get errored() {
    return stream.getStreamError(this)
  }

  write(chunk, encoding, cb) {
    if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = Buffer.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result = super.write({ chunk, encoding })

    if (cb) stream.Writable.drained(this).then(() => cb(null), cb)

    return result
  }

  end(chunk, encoding, cb) {
    if (typeof chunk === 'function') {
      cb = chunk
      chunk = null
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = Buffer.from(chunk, encoding || defaultEncoding)
    } else {
      encoding = 'buffer'
    }

    const result =
      chunk !== undefined && chunk !== null ? super.end({ chunk, encoding }) : super.end()

    if (cb) this.once('finish', () => cb(null))

    return result
  }

  static fromWeb(writableStream, opts = {}) {
    const stream = writableStream._stream

    if (opts.signal) exports.addAbortSignal(opts.signal, stream)

    return stream
  }

  static toWeb(writable) {
    return new WritableStream(writable)
  }

  async [Symbol.asyncDispose]() {
    if (!this.destroyed) this.destroy()

    await new Promise((resolve) => exports.finished(this, resolve))
  }
}

exports.Duplex = class Duplex extends stream.Duplex {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthReadable: null,
      byteLengthWritable,
      map: null,
      mapReadable: null,
      mapWritable: null
    })

    if (this._construct) this._open = this._construct

    if (this._read !== stream.Readable.prototype._read) {
      this._read = read.bind(this, this._read)
    }

    if (this._write !== stream.Duplex.prototype._write) {
      this._write = write.bind(this, this._write)
    }

    if (this._destroy !== stream.Stream.prototype._destroy) {
      this._destroy = destroy.bind(this, this._destroy)
    }
  }

  push(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = Buffer.from(chunk, encoding || defaultEncoding)
    }

    return super.push(chunk)
  }

  unshift(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = Buffer.from(chunk, encoding || defaultEncoding)
    }

    super.unshift(chunk)
  }

  write(chunk, encoding, cb) {
    if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = Buffer.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result = super.write({ chunk, encoding })

    if (cb) stream.Writable.drained(this).then(() => cb(null), cb)

    return result
  }

  end(chunk, encoding, cb) {
    if (typeof chunk === 'function') {
      cb = chunk
      chunk = null
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = Buffer.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result =
      chunk !== undefined && chunk !== null ? super.end({ chunk, encoding }) : super.end()

    if (cb) this.once('finish', () => cb(null))

    return result
  }

  static fromWeb({ readable: readableStream, writable: writableStream }, opts) {
    const readable = exports.Readable.fromWeb(readableStream, opts)
    const writable = exports.Writable.fromWeb(writableStream, opts)

    const duplex = new exports.Duplex({
      write(data, encoding, cb) {
        writable.write(data, encoding, cb)
      }
    })

    readable
      .on('data', (data) => duplex.push(data))
      .on('end', () => duplex.push(null))
      .on('error', (err) => duplex.destroy(err))

    writable.on('finish', () => duplex.end()).on('error', (err) => duplex.destroy(err))

    return duplex
  }

  static toWeb(duplex) {
    const readableStream = exports.Readable.toWeb(duplex)
    const writableStream = exports.Writable.toWeb(duplex)

    return { readable: readableStream, writable: writableStream }
  }
}

class DuplexSide extends exports.Duplex {
  constructor(opts) {
    super(opts)

    this._otherSide = null
    this._cb = null
  }

  _read() {
    const cb = this._cb
    if (!cb) return

    this._cb = null
    cb()
  }

  _write(chunk, encoding, cb) {
    this._otherSide.push(chunk, encoding)
    this._otherSide._cb = cb
  }

  _final(cb) {
    this._otherSide.on('end', cb)
    this._otherSide.push(null)
  }
}

exports.duplexPair = function duplexPair(opts) {
  const sideA = new DuplexSide(opts)
  const sideB = new DuplexSide(opts)

  sideA._otherSide = sideB
  sideB._otherSide = sideA

  return [sideA, sideB]
}

exports.Transform = class Transform extends stream.Transform {
  constructor(opts = {}) {
    super({
      ...opts,
      byteLength: null,
      byteLengthReadable: null,
      byteLengthWritable,
      map: null,
      mapReadable: null,
      mapWritable: null
    })

    if (this._transform !== stream.Transform.prototype._transform) {
      this._transform = transform.bind(this, this._transform)
    } else {
      this._transform = passthrough
    }
  }

  push(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = Buffer.from(chunk, encoding || defaultEncoding)
    }

    return super.push(chunk)
  }

  unshift(chunk, encoding) {
    if (typeof chunk === 'string') {
      chunk = Buffer.from(chunk, encoding || defaultEncoding)
    }

    super.unshift(chunk)
  }

  write(chunk, encoding, cb) {
    if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = Buffer.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result = super.write({ chunk, encoding })

    if (cb) stream.Writable.drained(this).then(() => cb(null), cb)

    return result
  }

  end(chunk, encoding, cb) {
    if (typeof chunk === 'function') {
      cb = chunk
      chunk = null
    } else if (typeof encoding === 'function') {
      cb = encoding
      encoding = null
    }

    if (typeof chunk === 'string') {
      encoding = encoding || defaultEncoding
      chunk = Buffer.from(chunk, encoding)
    } else {
      encoding = 'buffer'
    }

    const result =
      chunk !== undefined && chunk !== null ? super.end({ chunk, encoding }) : super.end()

    if (cb) this.once('finish', () => cb(null))

    return result
  }
}

exports.PassThrough = class PassThrough extends exports.Transform {}

exports.finished = function finished(stream, opts, cb) {
  if (typeof opts === 'function') {
    cb = opts
    opts = {}
  }

  if (!opts) opts = {}

  const { cleanup = false } = opts

  const done = () => {
    cb(exports.getStreamError(stream, { all: true }))

    if (cleanup) detach()
  }

  const detach = () => {
    stream.off('close', done)
    stream.off('error', noop)
  }

  if (stream.destroyed) {
    done()
  } else {
    stream.on('close', done)
    stream.on('error', noop)
  }

  return detach
}

function read(read, cb) {
  read.call(this, 65536)

  cb(null)
}

function write(write, data, cb) {
  write.call(this, data.chunk, data.encoding, cb)
}

function transform(transform, data, cb) {
  transform.call(this, data.chunk, data.encoding, cb)
}

function destroy(destroy, cb) {
  destroy.call(this, exports.getStreamError(this), cb)
}

function passthrough(data, cb) {
  cb(null, data.chunk)
}

function byteLengthWritable(data) {
  return data.chunk.byteLength
}

function noop() {}
{
  "name": "bare-stream",
  "version": "2.13.1",
  "description": "Streaming data for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./promises": "./promises.js",
    "./web": {
      "types": "./web.d.ts",
      "default": "./web.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "promises.js",
    "web.js",
    "web.d.ts",
    "global.js",
    "global.d.ts"
  ],
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-stream.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-stream/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-stream#readme",
  "dependencies": {
    "streamx": "^2.25.0",
    "teex": "^1.0.1"
  },
  "devDependencies": {
    "bare-abort-controller": "^1.1.0",
    "bare-buffer": "^3.0.0",
    "bare-events": "^2.5.4",
    "brittle": "^3.5.2",
    "lunte": "^1.6.0",
    "prettier": "^3.3.3",
    "prettier-config-holepunch": "^2.0.0"
  },
  "peerDependencies": {
    "bare-abort-controller": "*",
    "bare-buffer": "*",
    "bare-events": "*"
  },
  "peerDependenciesMeta": {
    "bare-abort-controller": {
      "optional": true
    },
    "bare-buffer": {
      "optional": true
    },
    "bare-events": {
      "optional": true
    }
  }
}
const { Readable, Writable, Transform, getStreamError, isStreamx, isDisturbed } = require('streamx')
const tee = require('teex')

const readableKind = Symbol.for('bare.stream.readable.kind')
const writableKind = Symbol.for('bare.stream.writable.kind')
const transformKind = Symbol.for('bare.stream.transform.kind')

// https://streams.spec.whatwg.org/#readablestreamdefaultreader
exports.ReadableStreamDefaultReader = class ReadableStreamDefaultReader {
  constructor(stream) {
    this._stream = stream
    this._stream._stream.once('close', onclose).once('error', onerror)

    const closed = Promise.withResolvers()

    // Avoid unhandled exceptions
    closed.promise.catch(noop)

    this._closed = closed

    function onclose() {
      closed.resolve()
    }

    function onerror(err) {
      closed.reject(err)
    }
  }

  get closed() {
    return this._closed.promise
  }

  read() {
    const stream = this._stream._stream

    return new Promise((resolve, reject) => {
      const err = getStreamError(stream)

      if (err) return reject(err)

      if (stream.destroyed) {
        return resolve({ value: undefined, done: true })
      }

      const value = stream.read()

      if (value !== null) {
        return resolve({ value, done: false })
      }

      stream.once('readable', onreadable).once('close', onclose).once('error', onerror)

      function onreadable() {
        const value = stream.read()

        ondone(null, value === null ? { value: undefined, done: true } : { value, done: false })
      }

      function onclose() {
        ondone(null, { value: undefined, done: true })
      }

      function onerror(err) {
        ondone(err, null)
      }

      function ondone(err, value) {
        stream.off('readable', onreadable).off('close', onclose).off('error', onerror)

        if (err) reject(err)
        else resolve(value)
      }
    })
  }

  releaseLock() {
    this._closed.reject(new TypeError('Reader was released'))
    this._stream._releaseLock()
    this._stream = null
  }

  cancel(reason = new TypeError('Stream was cancelled')) {
    const stream = this._stream._stream

    if (stream.destroyed) return Promise.resolve()

    return new Promise((resolve) =>
      stream.once('close', resolve).once('error', noop).destroy(reason)
    )
  }
}

// https://streams.spec.whatwg.org/#readablestreamdefaultcontroller
exports.ReadableStreamDefaultController = class ReadableStreamDefaultController {
  constructor(stream) {
    this._stream = stream
  }

  get desiredSize() {
    const stream = this._stream._stream

    return stream._readableState.highWaterMark - stream._readableState.buffered
  }

  enqueue(data) {
    this._stream._stream.push(data)
  }

  close() {
    this._stream._stream.push(null)
  }

  error(err) {
    this._stream._stream.destroy(err)
  }
}

// https://streams.spec.whatwg.org/#readablestream
class ReadableStream {
  static get [readableKind]() {
    return 0 // Compatibility version
  }

  static from(iterable) {
    return new ReadableStream(Readable.from(iterable))
  }

  constructor(underlyingSource = {}, queuingStrategy) {
    if (isStreamx(underlyingSource)) {
      this._stream = underlyingSource
    } else {
      if (queuingStrategy === undefined) {
        queuingStrategy = new exports.CountQueuingStrategy()
      }

      const { start, pull, cancel } = underlyingSource
      const { highWaterMark = 1, size = defaultSize } = queuingStrategy

      this._stream = new Readable({ highWaterMark, byteLength: size })

      const controller = new exports.ReadableStreamDefaultController(this)

      try {
        let starting = Promise.resolve()

        if (start) starting = forwardError(start.call(this, controller), controller)

        if (pull) {
          this._stream._read = this._read.bind(this, starting, pull.bind(this, controller))
        }

        if (cancel) {
          this._stream.once('error', cancel.bind(this))
        }
      } catch (err) {
        controller.error(err)
      }
    }

    this._reader = null
  }

  get [readableKind]() {
    return ReadableStream[readableKind]
  }

  get locked() {
    return this._reader !== null
  }

  getReader() {
    if (this.locked) throw new TypeError('Stream is locked')

    this._reader = new exports.ReadableStreamDefaultReader(this)

    return this._reader
  }

  cancel(reason = new TypeError('Stream was cancelled')) {
    const stream = this._stream

    if (stream.destroyed) return Promise.resolve()

    if (this.locked) return Promise.reject(new TypeError('Stream is locked'))

    return new Promise((resolve) =>
      stream.once('close', resolve).once('error', noop).destroy(reason)
    )
  }

  tee() {
    const [a, b] = tee(this._stream)

    return [new ReadableStream(a), new ReadableStream(b)]
  }

  pipeTo(destination) {
    return new Promise((resolve, reject) =>
      this._stream.pipe(destination._stream, (err) => {
        err ? reject(err) : resolve()
      })
    )
  }

  [Symbol.asyncIterator]() {
    return this._stream[Symbol.asyncIterator]()
  }

  _releaseLock() {
    this._reader = null
  }

  async _read(starting, pull, cb) {
    await starting

    let err = null
    try {
      await pull()
    } catch (e) {
      err = e
    }
    cb(err)
  }
}

function defaultSize() {
  return 1
}

exports.ReadableStream = ReadableStream

// https://streams.spec.whatwg.org/#countqueuingstrategy
exports.CountQueuingStrategy = class CountQueuingStrategy {
  constructor(opts = {}) {
    const { highWaterMark = 1 } = opts

    this.highWaterMark = highWaterMark
  }

  size(chunk) {
    return 1
  }
}

// https://streams.spec.whatwg.org/#bytelengthqueuingstrategy
exports.ByteLengthQueuingStrategy = class ByteLengthQueuingStrategy {
  constructor(opts = {}) {
    const { highWaterMark = 16384 } = opts

    this.highWaterMark = highWaterMark
  }

  size(chunk) {
    return chunk.byteLength
  }
}

exports.isReadableStream = function isReadableStream(value) {
  if (value instanceof ReadableStream) return true

  return (
    typeof value === 'object' &&
    value !== null &&
    value[readableKind] === ReadableStream[readableKind]
  )
}

// https://streams.spec.whatwg.org/#readablestream-errored
exports.isReadableStreamErrored = function isReadableStreamErrored(stream) {
  return getStreamError(stream._stream) !== null
}

// https://streams.spec.whatwg.org/#is-readable-stream-disturbed
exports.isReadableStreamDisturbed = function isReadableStreamDisturbed(stream) {
  return isDisturbed(stream._stream)
}

// https://streams.spec.whatwg.org/#writablestreamdefaultwriter
exports.WritableStreamDefaultWriter = class WritableStreamDefaultWriter {
  constructor(stream) {
    this._stream = stream
    this._stream._stream.once('close', onclose).once('error', onerror)

    const closed = Promise.withResolvers()

    // Avoid unhandled exceptions
    closed.promise.catch(noop)

    this._closed = closed

    function onclose() {
      closed.resolve()
    }

    function onerror(err) {
      closed.reject(err)
    }
  }

  get desiredSize() {
    const stream = this._stream._stream

    return stream._writableState.highWaterMark - stream._writableState.buffered
  }

  get closed() {
    return this._closed.promise
  }

  get ready() {
    const stream = this._stream._stream

    if (getStreamError(stream)) return Promise.reject()

    return Writable.drained(stream).then()
  }

  async write(chunk) {
    const stream = this._stream._stream

    let err = getStreamError(stream)
    if (err) return Promise.reject(err)

    stream.write(chunk)

    await Writable.drained(stream)

    err = getStreamError(stream)
    if (err) return Promise.reject(err)
  }

  releaseLock() {
    this._closed.reject(new TypeError('Writer was released'))
    this._stream._releaseLock()
    this._stream = null
  }

  close() {
    const stream = this._stream._stream

    if (stream.destroyed) return Promise.resolve()

    return new Promise((resolve) => stream.once('close', resolve).end())
  }

  abort(reason = new TypeError('Stream was aborted')) {
    const stream = this._stream._stream

    if (stream.destroyed) return Promise.resolve()

    return new Promise((resolve) => stream.once('close', resolve).destroy(reason))
  }
}

// https://streams.spec.whatwg.org/#writablestreamdefaultcontroller
exports.WritableStreamDefaultController = class WritableStreamDefaultController {
  constructor(stream) {
    this._stream = stream
  }

  error(err) {
    this._stream._stream.destroy(err)
  }
}

// https://streams.spec.whatwg.org/#writablestream
class WritableStream {
  static get [writableKind]() {
    return 0 // Compatibility version
  }

  constructor(underlyingSink = {}, queuingStrategy = {}) {
    if (isStreamx(underlyingSink)) {
      this._stream = underlyingSink
    } else {
      if (queuingStrategy === undefined) {
        queuingStrategy = new exports.CountQueuingStrategy()
      }

      const { start, write, close, abort } = underlyingSink
      const { highWaterMark = 1, size = defaultSize } = queuingStrategy

      this._stream = new Writable({ highWaterMark, byteLength: size })

      const controller = new exports.WritableStreamDefaultController(this)

      this._controller = controller

      try {
        let starting = Promise.resolve()

        if (start) starting = forwardError(start.call(this, controller), controller)

        if (write) {
          this._stream._write = this._write.bind(this, starting, write.bind(this))
        }

        if (close) {
          this._stream._destroy = this._destroy.bind(this, close.call(this))
        }

        if (abort) {
          this._stream.once('error', abort.bind(this))
        }
      } catch (err) {
        controller.error(err)
      }
    }

    this._writer = null
  }

  get [writableKind]() {
    return WritableStream[writableKind]
  }

  get locked() {
    return this._writer !== null
  }

  getWriter() {
    if (this.locked) throw new TypeError('Stream is locked')

    this._writer = new exports.WritableStreamDefaultWriter(this)

    return this._writer
  }

  abort(reason = new TypeError('Stream was aborted')) {
    if (this._stream.destroyed) return Promise.resolve()

    if (this.locked) return Promise.reject(new TypeError('Stream is locked'))

    return new Promise((resolve) => this._stream.once('close', resolve).destroy(reason))
  }

  close() {
    if (this._stream.destroyed) return Promise.resolve()

    if (this.locked) return Promise.reject(new TypeError('Stream is locked'))

    return new Promise((resolve) => this._stream.once('close', resolve).end())
  }

  _releaseLock() {
    this._writer = null
  }

  async _write(starting, write, data, cb) {
    await starting

    let err = null
    try {
      await write(data, this._controller)
    } catch (e) {
      err = e
    }
    cb(err)
  }

  async _destroy(closing, cb) {
    let err = null
    try {
      await closing
    } catch (e) {
      err = e
    }
    cb(err)
  }
}

exports.WritableStream = WritableStream

exports.isWritableStream = function isWritableStream(value) {
  if (value instanceof WritableStream) return true

  return (
    typeof value === 'object' &&
    value !== null &&
    value[writableKind] === WritableStream[writableKind]
  )
}

// https://streams.spec.whatwg.org/#transformstreamdefaultcontroller
exports.TransformStreamDefaultController = class TransformStreamDefaultController {
  constructor(stream) {
    this._stream = stream
  }

  get desiredSize() {
    const stream = this._stream._stream

    return stream._readableState.highWaterMark - stream._readableState.buffered
  }

  enqueue(data) {
    this._stream._stream.push(data)
  }

  error(err) {
    this._stream._stream.destroy(err)
  }

  terminate() {
    const stream = this._stream._stream

    stream.push(null)
    stream.destroy(new TypeError('Stream has been terminated'))
  }
}

// https://streams.spec.whatwg.org/#transformstream
class TransformStream {
  static get [transformKind]() {
    return 0 // Compatibility version
  }

  constructor(transformer = {}, writableStrategy = {}, readableStrategy = {}) {
    if (isStreamx(transformer)) {
      this._stream = transformer
    } else {
      const { start, transform, flush } = transformer

      this._stream = new Transform({ ...writableStrategy, ...readableStrategy })

      const controller = new exports.TransformStreamDefaultController(this)

      this._controller = controller

      try {
        let starting = Promise.resolve()

        if (start) starting = forwardError(start.call(this, controller), controller)

        if (transform) {
          this._stream._transform = this._transform.bind(this, starting, transform.bind(this))
        }

        if (flush) {
          this._stream._flush = this._flush.bind(this, flush.call(this, this._controller))
        }
      } catch (err) {
        controller.error(err)
      }
    }

    this._writable = new WritableStream(this._stream)
    this._readable = new ReadableStream(this._stream)
  }

  get [transformKind]() {
    return TransformStream[transformKind]
  }

  get writable() {
    return this._writable
  }

  get readable() {
    return this._readable
  }

  async _transform(starting, transform, data, cb) {
    await starting

    let err = null
    try {
      await transform(data, this._controller)
    } catch (e) {
      err = e
    }
    cb(err)
  }

  async _flush(flush, cb) {
    let err = null
    try {
      await flush
    } catch (e) {
      err = e
    }
    cb(err)
  }
}

exports.TransformStream = TransformStream

exports.isTransformStream = function isTransformStream(value) {
  if (value instanceof TransformStream) return true

  return (
    typeof value === 'object' &&
    value !== null &&
    value[transformKind] === TransformStream[transformKind]
  )
}

async function forwardError(promise, controller) {
  try {
    await promise
  } catch (err) {
    controller.error(err)
  }
}

function noop() {}
module.exports = require.addon()
const EventEmitter = require('bare-events')
const { Duplex } = require('bare-stream')
const dns = require('bare-dns')
const binding = require('./binding')
const constants = require('./lib/constants')
const errors = require('./lib/errors')
const ip = require('./lib/ip')

const defaultReadBufferSize = 65536
const empty = Buffer.alloc(0)

exports.Socket = class TCPSocket extends Duplex {
  constructor(opts = {}) {
    const { readBufferSize = defaultReadBufferSize, allowHalfOpen = true, eagerOpen = true } = opts

    super({ eagerOpen })

    this._state = 0

    this._allowHalfOpen = allowHalfOpen

    this._keepAlive = 0
    this._keepAliveInitialDelay = 0
    this._noDelay = 0

    this._localAddress = null
    this._remoteAddress = null

    this._pendingOpen = null
    this._pendingWrite = null
    this._pendingFinal = null
    this._pendingDestroy = null

    this._timer = null
    this._timeout = 0

    this._buffer = Buffer.alloc(readBufferSize)

    this._addresses = null
    this._errors = null

    this._handle = binding.init(
      this._buffer,
      this,
      noop,
      this._onconnect,
      this._onreset,
      this._onread,
      this._onwrite,
      this._onfinal,
      this._onclose
    )
  }

  get connecting() {
    return (this._state & constants.state.CONNECTING) !== 0
  }

  get pending() {
    return (this._state & constants.state.CONNECTED) === 0
  }

  get timeout() {
    return this._timeout || undefined // For Node.js compatibility
  }

  get readyState() {
    if (this._state & constants.state.CONNECTED) {
      return 'open'
    }

    return 'opening'
  }

  get localAddress() {
    if (this._localAddress) return this._localAddress.address
  }

  get localFamily() {
    if (this._localAddress) return `IPv${this._localAddress.family}`
  }

  get localPort() {
    if (this._localAddress) return this._localAddress.port
  }

  get remoteAddress() {
    if (this._remoteAddress) return this._remoteAddress.address
  }

  get remoteFamily() {
    if (this._remoteAddress) return `IPv${this._remoteAddress.family}`
  }

  get remotePort() {
    if (this._remoteAddress) return this._remoteAddress.port
  }

  connect(port, host = 'localhost', opts = {}, onconnect) {
    if (this._state & constants.state.CONNECTING || this._state & constants.state.CONNECTED) {
      throw errors.SOCKET_ALREADY_CONNECTED('Socket is already connected')
    }

    this._state |= constants.state.CONNECTING

    if (typeof host === 'function') {
      onconnect = host
      host = 'localhost'
    } else if (typeof opts === 'function') {
      onconnect = opts
      opts = {}
    }

    let family = 0

    if (typeof port === 'object' && port !== null) {
      opts = port || {}
      port = opts.port || 0
      host = opts.host || 'localhost'
      family = opts.family || 0
    }

    if (!host) host = 'localhost'

    const {
      lookup = dns.lookup,
      hints,
      keepAlive = false,
      keepAliveInitialDelay = 0,
      noDelay = false,
      timeout
    } = opts

    const type = ip.isIP(host)

    if (type === 0) {
      lookup(host, { all: true, family, hints }, (err, addresses) => {
        if (this._state & constants.state.CLOSING) return

        this._state &= ~constants.state.CONNECTING

        if (err || addresses.length === 0) {
          if (!err) {
            err = new Error(`No address found for host "${host}"`)
            err.code = 'ENOTFOUND'
          }

          this.emit('lookup', err, null, 0, host)

          if (this._pendingOpen) this._continueOpen(err)
          else this.destroy(err)
          return
        }

        for (const { address, family } of addresses) {
          this.emit('lookup', null, address, family, host)
        }

        const [{ address, family }, ...rest] = addresses

        if (rest.length > 0) {
          this._addresses = rest.map(({ address, family }) => [
            port,
            address,
            { ...opts, family },
            onconnect
          ])

          this._errors = []
        }

        this.connect(port, address, { ...opts, family }, onconnect)
      })

      return this
    }

    family = type

    try {
      binding.connect(this._handle, port, host, family)

      if (keepAlive) {
        this._keepAlive = keepAlive
        this._keepAliveInitialDelay = keepAliveInitialDelay
      }
      if (noDelay) this._noDelay = noDelay
      if (timeout) this.setTimeout(timeout)

      if (onconnect) this.once('connect', onconnect)
    } catch (err) {
      queueMicrotask(() => {
        if (this._pendingOpen) this._pendingOpen(err)
        else this.destroy(err)
      })
    }

    return this
  }

  setKeepAlive(enable = false, delay = 0) {
    if (typeof enable === 'number') {
      delay = enable
      enable = false
    }

    delay = Math.floor(delay / 1000)

    if (delay === 0) enable = false

    binding.keepalive(this._handle, enable, delay)

    return this
  }

  setNoDelay(enable = true) {
    binding.nodelay(this._handle, enable)

    return this
  }

  setTimeout(ms, ontimeout) {
    if (ms === 0) {
      clearTimeout(this._timer)

      this._timer = null
    } else {
      if (ontimeout) this.once('timeout', ontimeout)

      this._timer = setTimeout(() => this.emit('timeout'), ms)
      this._timer.unref()
    }

    this._timeout = ms

    return this
  }

  ref() {
    binding.ref(this._handle)

    return this
  }

  unref() {
    binding.unref(this._handle)

    return this
  }

  _open(cb) {
    if (this._state & constants.state.CONNECTED) return cb(null)

    this._pendingOpen = cb
  }

  _read() {
    if ((this._state & constants.state.READING) === 0) {
      this._state |= constants.state.READING

      binding.resume(this._handle)
    }
  }

  _writev(batch, cb) {
    this._pendingWrite = [cb, batch]

    binding.writev(
      this._handle,
      batch.map(({ chunk }) => chunk)
    )
  }

  _final(cb) {
    this._pendingFinal = cb

    binding.end(this._handle)
  }

  _predestroy() {
    if (this._state & constants.state.CLOSING) return
    this._state |= constants.state.CLOSING

    binding.close(this._handle)
  }

  _destroy(err, cb) {
    if (this._state & constants.state.CLOSING) return cb(err)
    this._state |= constants.state.CLOSING

    this._pendingDestroy = cb

    binding.close(this._handle)
  }

  _continueOpen(err) {
    if (this._pendingOpen === null) return
    const cb = this._pendingOpen
    this._pendingOpen = null
    cb(err)
  }

  _continueWrite(err) {
    if (this._pendingWrite === null) return
    const cb = this._pendingWrite[0]
    this._pendingWrite = null
    cb(err)
  }

  _continueFinal(err) {
    if (this._pendingFinal === null) return
    const cb = this._pendingFinal
    this._pendingFinal = null
    cb(err)
  }

  _continueDestroy() {
    if (this._pendingDestroy === null) return
    const cb = this._pendingDestroy
    this._pendingDestroy = null
    cb(null)
  }

  _reset() {
    this._state = 0

    this._localAddress = null
    this._remoteAddress = null

    binding.reset(this._handle)
  }

  _onconnect(err) {
    if (err) {
      if (this._addresses !== null) {
        this._errors.push(err)

        if (this._addresses.length > 0) return this._reset()

        err = this._errors.length === 1 ? this._errors[0] : new AggregateError(this._errors)
      }

      if (this._pendingOpen) this._continueOpen(err)
      else this.destroy(err)
      return
    }

    if (this._keepAlive) this.setKeepAlive(this._keepAlive, this._keepAliveInitialDelay)
    if (this._noDelay) this.setNoDelay()

    this._localAddress = binding.address(this._handle, true)
    this._remoteAddress = binding.address(this._handle, false)

    this._state |= constants.state.CONNECTED
    this._state &= ~constants.state.CONNECTING
    this._continueOpen()

    this.emit('connect')
  }

  _onreset(err) {
    if (err) {
      this._errors.push(err)
      this.destroy(this._errors.length === 1 ? this._errors[0] : new AggregateError(this._errors))
      return
    }

    this.connect(...this._addresses.shift())
  }

  _onread(err, read) {
    if (this._timer) this._timer.refresh()

    if (err) {
      this.destroy(err)
      return
    }

    if (read === 0) {
      this.push(null)
      if (this._allowHalfOpen === false) this.end()
      return
    }

    const copy = Buffer.allocUnsafe(read)
    copy.set(this._buffer.subarray(0, read))

    if (this.push(copy) === false && this.destroying === false) {
      this._state &= ~constants.state.READING

      binding.pause(this._handle)
    }
  }

  _onwrite(err) {
    if (this._timer) this._timer.refresh()

    this._continueWrite(err)
  }

  _onfinal(err) {
    this._continueFinal(err)
  }

  _onclose() {
    clearTimeout(this._timer)

    this._continueOpen()
    this._continueDestroy()
  }
}

exports.Server = class TCPServer extends EventEmitter {
  constructor(opts = {}, onconnection) {
    if (typeof opts === 'function') {
      onconnection = opts
      opts = {}
    }

    super()

    const {
      readBufferSize = defaultReadBufferSize,
      allowHalfOpen = true,
      keepAlive = false,
      keepAliveInitialDelay = 0,
      noDelay = false,
      pauseOnConnect = false
    } = opts

    this._state = 0

    this._readBufferSize = readBufferSize
    this._allowHalfOpen = allowHalfOpen
    this._keepAlive = keepAlive
    this._keepAliveInitialDelay = keepAliveInitialDelay
    this._noDelay = noDelay
    this._pauseOnConnect = pauseOnConnect

    this._address = null
    this._connections = new Set()

    this._error = null
    this._handle = null

    if (onconnection) this.on('connection', onconnection)
  }

  get listening() {
    return (this._state & constants.state.BOUND) !== 0
  }

  get closing() {
    return (this._state & constants.state.CLOSING) !== 0
  }

  get connections() {
    return this._connections
  }

  address() {
    if ((this._state & constants.state.BOUND) === 0) return null

    const { address, family, port } = this._address

    return { address, family: `IPv${family}`, port }
  }

  listen(port = 0, host = 'localhost', backlog = 511, opts = {}, onlistening) {
    if (this._state & constants.state.BINDING || this._state & constants.state.BOUND) {
      throw errors.SERVER_ALREADY_LISTENING('Server is already listening')
    }

    if (this._state & constants.state.CLOSING) {
      throw errors.SERVER_IS_CLOSED('Server is closed')
    }

    this._state |= constants.state.BINDING

    if (typeof port === 'function') {
      onlistening = port
      port = 0
    } else if (typeof host === 'function') {
      onlistening = host
      host = 'localhost'
    } else if (typeof backlog === 'function') {
      onlistening = backlog
      backlog = 511
    } else if (typeof opts === 'function') {
      onlistening = opts
      opts = {}
    }

    let family = 0

    if (typeof port === 'object' && port !== null) {
      opts = port || {}
      port = opts.port || 0
      host = opts.host || 'localhost'
      family = opts.family || 0
      backlog = opts.backlog || 511
    }

    if (!host) host = 'localhost'
    if (!backlog) backlog = 511

    const { lookup = dns.lookup, hints } = opts

    const type = ip.isIP(host)

    if (type === 0) {
      lookup(host, { family, hints }, (err, address, family) => {
        if (this._state & constants.state.CLOSING) return

        this.emit('lookup', err, address, family, host)

        this._state &= ~constants.state.BINDING

        if (err) return this.emit('error', err)

        this.listen(port, address, backlog, { ...opts, family }, onlistening)
      })

      return this
    }

    family = type

    this._handle = binding.init(
      empty,
      this,
      this._onconnection,
      noop,
      noop,
      noop,
      noop,
      noop,
      this._onclose
    )

    if (this._state & constants.state.UNREFED) binding.unref(this._handle)

    try {
      binding.bind(this._handle, port, host, backlog, family)

      this._address = binding.address(this._handle, true)

      this._state |= constants.state.BOUND
      this._state &= ~constants.state.BINDING

      if (onlistening) this.once('listening', onlistening)

      queueMicrotask(() => this.emit('listening'))
    } catch (err) {
      this._error = err

      binding.close(this._handle)
    }

    return this
  }

  close(onclose) {
    if (onclose) this.once('close', onclose)

    if (this._state & constants.state.CLOSING) return this
    this._state |= constants.state.CLOSING

    this._closeMaybe()

    return this
  }

  ref() {
    this._state &= ~constants.state.UNREFED

    if (this._handle !== null) binding.ref(this._handle)

    return this
  }

  unref() {
    this._state |= constants.state.UNREFED

    if (this._handle !== null) binding.unref(this._handle)

    return this
  }

  _closeMaybe() {
    if (this._state & constants.state.CLOSING && this._connections.size === 0) {
      if (this._handle !== null) binding.close(this._handle)
      else queueMicrotask(() => this.emit('close'))
    }
  }

  _onconnection(err) {
    if (err) {
      this.emit('error', err)
      return
    }

    if (this._state & constants.state.CLOSING) return

    const socket = new exports.Socket({
      readBufferSize: this._readBufferSize,
      allowHalfOpen: this._allowHalfOpen,
      eagerOpen: !this._pauseOnConnect
    })

    try {
      binding.accept(this._handle, socket._handle)

      socket._localAddress = binding.address(socket._handle, true)
      socket._remoteAddress = binding.address(socket._handle, false)

      socket._state |= constants.state.CONNECTED

      this._connections.add(socket)

      if (this._keepAlive) socket.setKeepAlive(this._keepAlive, this._keepAliveInitialDelay)
      if (this._noDelay) socket.setNoDelay()

      socket.on('close', () => {
        this._connections.delete(socket)
        this._closeMaybe()
      })

      this.emit('connection', socket)
    } catch (err) {
      socket.destroy()

      this.emit('error', err)
    }
  }

  _onclose() {
    const err = this._error

    this._state &= ~constants.state.BINDING
    this._error = null
    this._handle = null
    this._address = null

    if (err) this.emit('error', err)
    else this.emit('close')
  }
}

exports.constants = constants
exports.errors = errors

exports.isIP = ip.isIP
exports.isIPv4 = ip.isIPv4
exports.isIPv6 = ip.isIPv6

exports.createConnection = function createConnection(port, host, opts, onconnect) {
  if (typeof host === 'function') {
    onconnect = host
    host = 'localhost'
  } else if (typeof opts === 'function') {
    onconnect = opts
    opts = {}
  }

  if (typeof port === 'object' && port !== null) {
    opts = port || {}
    port = opts.port || 0
    host = opts.host || 'localhost'
  }

  return new exports.Socket(opts).connect(port, host, opts, onconnect)
}

// For Node.js compatibility
exports.connect = exports.createConnection

exports.createServer = function createServer(opts, onconnection) {
  return new exports.Server(opts, onconnection)
}

function noop() {}
module.exports = {
  state: {
    CONNECTING: 0x1,
    CONNECTED: 0x2,
    BINDING: 0x4,
    BOUND: 0x8,
    READING: 0x10,
    CLOSING: 0x20,
    UNREFED: 0x40
  }
}
module.exports = class TCPError extends Error {
  constructor(msg, fn = TCPError, code = fn.name) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'TCPError'
  }

  static SOCKET_ALREADY_CONNECTED(msg) {
    return new TCPError(msg, TCPError.SOCKET_ALREADY_CONNECTED)
  }

  static SERVER_ALREADY_LISTENING(msg) {
    return new TCPError(msg, TCPError.SERVER_ALREADY_LISTENING)
  }

  static SERVER_IS_CLOSED(msg) {
    return new TCPError(msg, TCPError.SERVER_IS_CLOSED)
  }

  static INVALID_HOST(msg = 'Unrecognizable host format') {
    return new TCPError(msg, TCPError.INVALID_HOST)
  }
}
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

const v4Seg = '(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])'
const v4Str = `(${v4Seg}[.]){3}${v4Seg}`
const IPv4Pattern = new RegExp(`^${v4Str}$`)

const v6Seg = '(?:[0-9a-fA-F]{1,4})'
const IPv6Pattern = new RegExp(
  '^(' +
    `(?:${v6Seg}:){7}(?:${v6Seg}|:)|` +
    `(?:${v6Seg}:){6}(?:${v4Str}|:${v6Seg}|:)|` +
    `(?:${v6Seg}:){5}(?::${v4Str}|(:${v6Seg}){1,2}|:)|` +
    `(?:${v6Seg}:){4}(?:(:${v6Seg}){0,1}:${v4Str}|(:${v6Seg}){1,3}|:)|` +
    `(?:${v6Seg}:){3}(?:(:${v6Seg}){0,2}:${v4Str}|(:${v6Seg}){1,4}|:)|` +
    `(?:${v6Seg}:){2}(?:(:${v6Seg}){0,3}:${v4Str}|(:${v6Seg}){1,5}|:)|` +
    `(?:${v6Seg}:){1}(?:(:${v6Seg}){0,4}:${v4Str}|(:${v6Seg}){1,6}|:)|` +
    `(?::((?::${v6Seg}){0,5}:${v4Str}|(?::${v6Seg}){1,7}|:))` +
    ')(%[0-9a-zA-Z-.:]{1,})?$'
)

const isIPv4 = (exports.isIPv4 = function isIPv4(host) {
  return IPv4Pattern.test(host)
})

const isIPv6 = (exports.isIPv6 = function isIPv6(host) {
  return IPv6Pattern.test(host)
})

exports.isIP = function isIP(host) {
  if (isIPv4(host)) return 4
  if (isIPv6(host)) return 6
  return 0
}
{
  "name": "bare-tcp",
  "version": "2.2.12",
  "description": "Native TCP sockets for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./constants": "./lib/constants.js",
    "./errors": "./lib/errors.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-tcp.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-tcp/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-tcp#readme",
  "engines": {
    "bare": ">=1.16.0"
  },
  "dependencies": {
    "bare-dns": "^2.0.4",
    "bare-events": "^2.5.4",
    "bare-stream": "^2.6.4"
  },
  "devDependencies": {
    "brittle": "^3.5.0",
    "cmake-bare": "^1.1.6",
    "lunte": "^1.6.0",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = require.addon()
const { Readable, Writable } = require('bare-stream')
const Signal = require('bare-signals')
const binding = require('./binding')
const constants = require('./lib/constants')

const defaultReadBufferSize = 65536
const empty = Buffer.alloc(0)

exports.ReadStream = class TTYReadStream extends Readable {
  constructor(fd, opts = {}) {
    super()

    const { readBufferSize = defaultReadBufferSize, allowHalfOpen = true } = opts

    this._fd = fd
    this._state = 0
    this._allowHalfOpen = allowHalfOpen
    this._buffer = Buffer.alloc(readBufferSize)

    this._pendingDestroy = null

    this._handle = binding.init(fd, this._buffer, this, noop, this._onread, this._onclose)
  }

  get fd() {
    return this._fd
  }

  get isTTY() {
    return true
  }

  setMode(mode) {
    binding.setMode(this._handle, mode)
    return this
  }

  setRawMode(enabled) {
    return this.setMode(enabled ? constants.mode.RAW : constants.mode.NORMAL)
  }

  _read() {
    if ((this._state & constants.state.READING) === 0) {
      this._state |= constants.state.READING

      binding.resume(this._handle)
    }
  }

  _predestroy() {
    if (this._state & constants.state.CLOSING) return
    this._state |= constants.state.CLOSING

    binding.close(this._handle)
  }

  _destroy(err, cb) {
    if (this._state & constants.state.CLOSING) return cb(err)
    this._state |= constants.state.CLOSING

    this._pendingDestroy = cb

    binding.close(this._handle)
  }

  _continueDestroy() {
    if (this._pendingDestroy === null) return
    const cb = this._pendingDestroy
    this._pendingDestroy = null
    cb(null)
  }

  _onread(err, read) {
    if (err) {
      this.destroy(err)
      return
    }

    if (read === 0) {
      this.push(null)
      if (this._allowHalfOpen === false) this.end()
      return
    }

    const copy = Buffer.allocUnsafe(read)
    copy.set(this._buffer.subarray(0, read))

    if (this.push(copy) === false && this.destroying === false) {
      this._state &= ~constants.state.READING

      binding.pause(this._handle)
    }
  }

  _onclose() {
    this._handle = null

    this._continueDestroy()
  }
}

exports.WriteStream = class TTYWriteStream extends Writable {
  constructor(fd, opts = {}) {
    super()

    this._fd = fd
    this._state = 0
    this._size = null

    this._pendingWrite = null
    this._pendingDestroy = null

    this._handle = binding.init(fd, empty, this, this._onwrite, noop, this._onclose)

    this._size = this.getWindowSize()

    if (TTYWriteStream._streams.size === 0) TTYWriteStream._resize.start()

    TTYWriteStream._streams.add(this)
  }

  get fd() {
    return this._fd
  }

  get isTTY() {
    return true
  }

  get columns() {
    return this._size[0]
  }

  get rows() {
    return this._size[1]
  }

  getWindowSize() {
    return binding.getWindowSize(this._handle)
  }

  _writev(batch, cb) {
    this._pendingWrite = [cb, batch]

    binding.writev(
      this._handle,
      batch.map(({ chunk }) => chunk)
    )
  }

  _predestroy() {
    if (this._state & constants.state.CLOSING) return
    this._state |= constants.state.CLOSING

    binding.close(this._handle)

    TTYWriteStream._streams.delete(this)

    if (TTYWriteStream._streams.size === 0) TTYWriteStream._resize.stop()
  }

  _destroy(err, cb) {
    if (this._state & constants.state.CLOSING) return cb(err)
    this._state |= constants.state.CLOSING

    this._pendingDestroy = cb

    binding.close(this._handle)

    TTYWriteStream._streams.delete(this)

    if (TTYWriteStream._streams.size === 0) TTYWriteStream._resize.stop()
  }

  _continueWrite(err) {
    if (this._pendingWrite === null) return
    const cb = this._pendingWrite[0]
    this._pendingWrite = null
    cb(err)
  }

  _continueDestroy() {
    if (this._pendingDestroy === null) return
    const cb = this._pendingDestroy
    this._pendingDestroy = null
    cb(null)
  }

  _onwrite(err) {
    this._continueWrite(err)
  }

  _onclose() {
    this._handle = null

    this._continueDestroy()
  }

  _onresize() {
    this._size = this.getWindowSize()

    this.emit('resize')
  }

  static _streams = new Set()

  static _resize = new Signal('SIGWINCH')
}

exports.constants = constants

exports.isTTY = binding.isTTY

exports.isatty = exports.isTTY // For Node.js compatibility

exports.WriteStream._resize
  .on('signal', () => {
    for (const stream of exports.WriteStream._streams) {
      stream._onresize()
    }
  })
  .unref()

function noop() {}
const binding = require('../binding')

module.exports = exports = {
  mode: {
    NORMAL: binding.MODE_NORMAL,
    RAW: binding.MODE_RAW,
    IO: binding.MODE_IO || 0
  },

  state: {
    READING: 0x1,
    CLOSING: 0x2
  }
}

/** @deprecated Use `mode.NORMAL` */
exports.MODE_NORMAL = exports.mode.NORMAL
/** @deprecated Use `mode.RAW` */
exports.MODE_RAW = exports.mode.RAW
/** @deprecated Use `mode.IO` */
exports.MODE_IO = exports.mode.IO
{
  "name": "bare-tty",
  "version": "5.1.0",
  "description": "Native TTY streams for JavaScript",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./constants": "./lib/constants.js"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-tty.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-tty/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-tty#readme",
  "engines": {
    "bare": ">=1.16.0"
  },
  "dependencies": {
    "bare-events": "^2.2.0",
    "bare-signals": "^4.0.0",
    "bare-stream": "^2.0.0"
  },
  "devDependencies": {
    "brittle": "^3.2.1",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = require.addon()
const binding = require('./binding')

const t = binding.constants

class Type {
  constructor(type) {
    this._type = type
  }

  isUndefined() {
    return this._type === t.UNDEFINED
  }

  isNull() {
    return this._type === t.NULL
  }

  isBoolean() {
    return this._type === t.BOOLEAN
  }

  isNumber() {
    return (this._type & 0xff) === t.NUMBER
  }

  isInt32() {
    return (this._type & (0xff | t.INT32)) === (t.NUMBER | t.INT32)
  }

  isUint32() {
    return (this._type & (0xff | t.UINT32)) === (t.NUMBER | t.UINT32)
  }

  isString() {
    return this._type === t.STRING
  }

  isSymbol() {
    return this._type === t.SYMBOL
  }

  isObject() {
    return (this._type & 0xff) === t.OBJECT
  }

  isArray() {
    return this._type === (t.OBJECT | t.ARRAY)
  }

  isArguments() {
    return this._type === (t.OBJECT | t.ARGUMENTS)
  }

  isDate() {
    return this._type === (t.OBJECT | t.DATE)
  }

  isRegExp() {
    return this._type === (t.OBJECT | t.REGEXP)
  }

  isError() {
    return this._type === (t.OBJECT | t.ERROR)
  }

  isPromise() {
    return this._type === (t.OBJECT | t.PROMISE)
  }

  isProxy() {
    return this._type === (t.OBJECT | t.PROXY)
  }

  isGenerator() {
    return this._type === (t.OBJECT | t.GENERATOR)
  }

  isMap() {
    return this._type === (t.OBJECT | t.MAP)
  }

  isSet() {
    return this._type === (t.OBJECT | t.SET)
  }

  isWeakMap() {
    return this._type === (t.OBJECT | t.WEAK_MAP)
  }

  isWeakSet() {
    return this._type === (t.OBJECT | t.WEAK_SET)
  }

  isWeakRef() {
    return this._type === (t.OBJECT | t.WEAK_REF)
  }

  isArrayBuffer() {
    return this._type === (t.OBJECT | t.ARRAYBUFFER)
  }

  isSharedArrayBuffer() {
    return this._type === (t.OBJECT | t.SHAREDARRAYBUFFER)
  }

  isTypedArray() {
    return (this._type & 0xffff) === (t.OBJECT | t.TYPEDARRAY)
  }

  isInt8Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT8ARRAY)
  }

  isUint8Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT8ARRAY)
  }

  isUint8ClampedArray() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT8CLAMPEDARRAY)
  }

  isInt16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT16ARRAY)
  }

  isUint16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT16ARRAY)
  }

  isInt32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT32ARRAY)
  }

  isUint32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT32ARRAY)
  }

  isFloat16Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT16ARRAY)
  }

  isFloat32Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT32ARRAY)
  }

  isFloat64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT64ARRAY)
  }

  isBigInt64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.BIGINT64ARRAY)
  }

  isBigUint64Array() {
    return this._type === (t.OBJECT | t.TYPEDARRAY | t.BIGUINT64ARRAY)
  }

  isDataView() {
    return this._type === (t.OBJECT | t.DATAVIEW)
  }

  isModuleNamespace() {
    return this._type === (t.OBJECT | t.MODULE_NAMESPACE)
  }

  isFunction() {
    return (this._type & 0xff) === t.FUNCTION
  }

  isAsyncFunction() {
    return (
      (this._type & (0xff | t.ASYNC_FUNCTION)) ===
      (t.FUNCTION | t.ASYNC_FUNCTION)
    )
  }

  isGeneratorFunction() {
    return (
      (this._type & (0xff | t.GENERATOR_FUNCTION)) ===
      (t.FUNCTION | t.GENERATOR_FUNCTION)
    )
  }

  isExternal() {
    return this._type === t.EXTERNAL
  }

  isBigInt() {
    return this._type === t.BIGINT
  }
}

module.exports = exports = function type(value) {
  switch (typeof value) {
    case 'undefined':
      return new Type(t.UNDEFINED)
    case 'boolean':
      return new Type(t.BOOLEAN)
    case 'number':
      return new Type(
        Number.isSafeInteger(value) ? binding.type(value) : t.NUMBER
      )
    case 'string':
      return new Type(t.STRING)
    case 'symbol':
      return new Type(t.SYMBOL)
    case 'object':
      return new Type(value === null ? t.NULL : binding.type(value))
    case 'function':
      return new Type(binding.type(value))
    case 'bigint':
      return new Type(t.BIGINT)
  }
}

exports.createTag = function createTag(...components) {
  const tag = new Uint32Array(4)
  for (let i = 0; i < 4; i++) tag[i] = components[i] || 0
  return tag
}

exports.addTag = function addTag(object, tag) {
  binding.addTag(object, tag)
}

exports.checkTag = function checkTag(object, tag) {
  return binding.checkTag(object, tag)
}
{
  "name": "bare-type",
  "version": "1.1.0",
  "description": "Cross-realm type predicates for Bare",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "prettier . --check && bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-type.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-type/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-type#readme",
  "engines": {
    "bare": ">=1.2.0"
  },
  "devDependencies": {
    "brittle": "^3.4.0",
    "cmake-bare": "^1.1.6",
    "prettier": "^3.4.1",
    "prettier-config-standard": "^7.0.0"
  }
}
module.exports = require.addon()
const path = require('bare-path')
const binding = require('./binding')
const errors = require('./lib/errors')
const URLSearchParams = require('./lib/url-search-params')

const kind = Symbol.for('bare.url.kind')

const isWindows = Bare.platform === 'win32'

class URL {
  static get [kind]() {
    return 0 // Compatibility version
  }

  constructor(input, base, opts = {}) {
    if (arguments.length === 0) throw errors.INVALID_URL()

    input = String(input)

    if (base !== undefined) base = String(base)

    this._components = new Uint32Array(8)

    this._parse(input, base, opts.throw !== false)

    if (this._href) this._params = new URLSearchParams(this.search, this)
  }

  get [kind]() {
    return URL[kind]
  }

  // https://url.spec.whatwg.org/#dom-url-href

  get href() {
    return this._href
  }

  set href(value) {
    this._update(value)

    this._params._parse(this.search)
  }

  // https://url.spec.whatwg.org/#dom-url-protocol

  get protocol() {
    return this._slice(0, this._components[0]) + ':'
  }

  set protocol(value) {
    this._update(this._replace(value.replace(/:+$/, ''), 0, this._components[0]))
  }

  // https://url.spec.whatwg.org/#dom-url-username

  get username() {
    return this._slice(this._components[0] + 3 /* :// */, this._components[1])
  }

  set username(value) {
    if (cannotHaveCredentialsOrPort(this)) {
      return
    }

    if (this.username === '') value += '@'

    this._update(this._replace(value, this._components[0] + 3 /* :// */, this._components[1]))
  }

  // https://url.spec.whatwg.org/#dom-url-password

  get password() {
    return this._href.slice(this._components[1] + 1 /* : */, this._components[2] - 1 /* @ */)
  }

  set password(value) {
    if (cannotHaveCredentialsOrPort(this)) {
      return
    }

    let start = this._components[1] + 1 /* : */
    let end = this._components[2] - 1 /* @ */

    if (this.password === '') {
      value = ':' + value
      start--
    }

    if (this.username === '') {
      value += '@'
      end++
    }

    this._update(this._replace(value, start, end))
  }

  // https://url.spec.whatwg.org/#dom-url-host

  get host() {
    return this._slice(this._components[2], this._components[5])
  }

  set host(value) {
    if (hasOpaquePath(this)) {
      return
    }

    this._update(
      this._replace(value, this._components[2], this._components[value.includes(':') ? 5 : 3])
    )
  }

  // https://url.spec.whatwg.org/#dom-url-hostname

  get hostname() {
    return this._slice(this._components[2], this._components[3])
  }

  set hostname(value) {
    if (hasOpaquePath(this)) {
      return
    }

    this._update(this._replace(value, this._components[2], this._components[3]))
  }

  // https://url.spec.whatwg.org/#dom-url-port

  get port() {
    return this._slice(this._components[3] + 1 /* : */, this._components[5])
  }

  set port(value) {
    if (cannotHaveCredentialsOrPort(this)) {
      return
    }

    let start = this._components[3] + 1 /* : */

    if (this.port === '') {
      value = ':' + value
      start--
    }

    this._update(this._replace(value, start, this._components[5]))
  }

  // https://url.spec.whatwg.org/#dom-url-pathname

  get pathname() {
    return this._slice(this._components[5], this._components[6] - 1 /* ? */)
  }

  set pathname(value) {
    if (hasOpaquePath(this)) {
      return
    }

    if (value[0] !== '/' && value[0] !== '\\') {
      value = '/' + value
    }

    this._update(this._replace(value, this._components[5], this._components[6] - 1 /* ? */))
  }

  // https://url.spec.whatwg.org/#dom-url-search

  get search() {
    return this._slice(this._components[6] - 1 /* ? */, this._components[7] - 1 /* # */)
  }

  set search(value) {
    if (value && value[0] !== '?') value = '?' + value

    this._update(
      this._replace(value, this._components[6] - 1 /* ? */, this._components[7] - 1 /* # */)
    )

    this._params._parse(this.search)
  }

  // https://url.spec.whatwg.org/#dom-url-searchparams

  get searchParams() {
    return this._params
  }

  // https://url.spec.whatwg.org/#dom-url-hash

  get hash() {
    return this._slice(this._components[7] - 1 /* # */)
  }

  set hash(value) {
    if (value && value[0] !== '#') value = '#' + value

    this._update(this._replace(value, this._components[7] - 1 /* # */))
  }

  toString() {
    return this._href
  }

  toJSON() {
    return this._href
  }

  [Symbol.for('bare.inspect')]() {
    return {
      __proto__: { constructor: URL },

      href: this.href,
      protocol: this.protocol,
      username: this.username,
      password: this.password,
      host: this.host,
      hostname: this.hostname,
      port: this.port,
      pathname: this.pathname,
      search: this.search,
      searchParams: this.searchParams,
      hash: this.hash
    }
  }

  _slice(start, end = this._href.length) {
    return this._href.slice(start, end)
  }

  _replace(replacement, start, end = this._href.length) {
    return this._slice(0, start) + replacement + this._slice(end)
  }

  _parse(input, base, shouldThrow) {
    try {
      this._href = binding.parse(
        String(input),
        base ? String(base) : null,
        this._components,
        shouldThrow
      )
    } catch (err) {
      if (err instanceof TypeError) throw err

      throw errors.INVALID_URL(`Invalid URL '${input}'`, input)
    }
  }

  _update(input) {
    try {
      this._parse(input, null, true)
    } catch (err) {
      if (err instanceof TypeError) throw err
    }
  }
}

module.exports = exports = URL

// https://url.spec.whatwg.org/#url-opaque-path
function hasOpaquePath(url) {
  return url.pathname[0] !== '/'
}

// https://url.spec.whatwg.org/#cannot-have-a-username-password-port
function cannotHaveCredentialsOrPort(url) {
  return url.hostname === '' || url.protocol === 'file:'
}

exports.URL = URL
exports.URLSearchParams = URLSearchParams

exports.errors = errors

exports.isURL = function isURL(value) {
  if (value instanceof URL) return true

  return typeof value === 'object' && value !== null && value[kind] === URL[kind]
}

exports.isURLSearchParams = URLSearchParams.isURLSearchParams

// https://url.spec.whatwg.org/#dom-url-parse
exports.parse = function parse(input, base) {
  const url = new URL(input, base, { throw: false })
  return url._href ? url : null
}

// https://url.spec.whatwg.org/#dom-url-canparse
exports.canParse = function canParse(input, base) {
  return binding.canParse(String(input), base ? String(base) : null)
}

exports.fileURLToPath = function fileURLToPath(url) {
  if (typeof url === 'string') {
    url = new URL(url)
  }

  if (url.protocol !== 'file:') {
    throw errors.INVALID_URL_SCHEME('The URL must use the file: protocol')
  }

  if (isWindows) {
    if (/%2f|%5c/i.test(url.pathname)) {
      throw errors.INVALID_FILE_URL_PATH(
        'The file: URL path must not include encoded \\ or / characters'
      )
    }
  } else {
    if (url.hostname) {
      throw errors.INVALID_FILE_URL_HOST("The file: URL host must be 'localhost' or empty")
    }

    if (/%2f/i.test(url.pathname)) {
      throw errors.INVALID_FILE_URL_PATH('The file: URL path must not include encoded / characters')
    }
  }

  const pathname = path.normalize(decodeURIComponent(url.pathname))

  if (isWindows) {
    if (url.hostname) return '\\\\' + url.hostname + pathname

    const letter = pathname.charCodeAt(1) | 0x20

    if (letter < 0x61 /* a */ || letter > 0x7a /* z */ || pathname.charCodeAt(2) !== 0x3a /* : */) {
      throw errors.INVALID_FILE_URL_PATH('The file: URL path must be absolute')
    }

    return pathname.slice(1)
  }

  return pathname
}

exports.pathToFileURL = function pathToFileURL(pathname) {
  let resolved = path.resolve(pathname)

  if (pathname[pathname.length - 1] === '/') {
    resolved += '/'
  } else if (isWindows && pathname[pathname.length - 1] === '\\') {
    resolved += '\\'
  }

  resolved = resolved
    .replaceAll('%', '%25') // Must be first
    .replaceAll('#', '%23')
    .replaceAll('?', '%3f')
    .replaceAll('\n', '%0a')
    .replaceAll('\r', '%0d')
    .replaceAll('\t', '%09')

  if (!isWindows) {
    resolved = resolved.replaceAll('\\', '%5c')
  }

  return new URL('file:' + resolved)
}

exports.format = function format(parts) {
  const { protocol, auth, host, hostname, port, pathname, search, query, hash, slashes } = parts

  let result = ''

  if (typeof protocol === 'string') {
    result += protocol

    if (protocol[protocol.length - 1] !== ':') {
      result += ':'
    }

    if (slashes === true || /https?|ftp|gopher|file/.test(protocol)) {
      result += '//'
    }
  }

  if (typeof auth === 'string') {
    if (host || hostname) result += auth + '@'
  }

  if (typeof host === 'string') result += host
  else {
    result += hostname

    if (port) result += ':' + port
  }

  if (typeof pathname === 'string' && pathname !== '') {
    if (pathname[0] !== '/') result += '/'
    result += pathname
  }

  if (typeof search === 'string') {
    if (search[0] !== '?') result += '?'
    result += search
  } else if (typeof query === 'object' && query !== null) {
    result += '?' + new URLSearchParams(query)
  }

  if (typeof hash === 'string') {
    if (hash[0] !== '#') result += '#'
    result += hash
  }

  return result
}
module.exports = class URLError extends Error {
  constructor(msg, fn = URLError, code = fn.name) {
    super(`${code}: ${msg}`)

    this.code = code

    if (Error.captureStackTrace) Error.captureStackTrace(this, fn)
  }

  get name() {
    return 'URLError'
  }

  static INVALID_URL(msg, input) {
    const err = new URLError(msg, URLError.INVALID_URL)

    err.input = input

    return err
  }

  static INVALID_URL_SCHEME(msg = 'Invalid URL') {
    return new URLError(msg, URLError.INVALID_URL_SCHEME)
  }

  static INVALID_FILE_URL_HOST(msg = 'Invalid file: URL host') {
    return new URLError(msg, URLError.INVALID_FILE_URL_HOST)
  }

  static INVALID_FILE_URL_PATH(msg = 'Invalid file: URL path') {
    return new URLError(msg, URLError.INVALID_FILE_URL_PATH)
  }
}
const kind = Symbol.for('bare.url.search-params.kind')

class URLSearchParams {
  static _urls = new WeakMap()

  static get [kind]() {
    return 0 // Compatibility version
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-urlsearchparams
  constructor(init, url = null) {
    this._params = new Map()

    if (url) URLSearchParams._urls.set(this, url)

    if (typeof init === 'string') {
      this._parse(init)
    } else if (init) {
      for (const [name, value] of typeof init[Symbol.iterator] === 'function'
        ? init
        : Object.entries(init)) {
        this.append(name, value)
      }
    }
  }

  get [kind]() {
    return URLSearchParams[kind]
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-size
  get size() {
    return this._params.length
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-append
  append(name, value = null) {
    if (value === null) return

    let list = this._params.get(name)

    if (list === undefined) {
      list = []
      this._params.set(name, list)
    }

    list.push(value)

    this._update()
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-delete
  delete(name, value = null) {
    if (value === null) this._params.delete(name)
    else {
      let list = this._params.get(name)

      if (list === undefined) return

      list = list.filter((found) => found !== value)

      if (list.length === 0) this._params.delete(name)
      else this._params.set(name, list)
    }

    this._update()
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-get
  get(name) {
    const list = this._params.get(name)

    if (list === undefined) return null

    return list[0]
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-getall
  getAll(name) {
    const list = this._params.get(name)

    if (list === undefined) return []

    return Array.from(list)
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-has
  has(name, value = null) {
    const list = this._params.get(name)

    if (list === undefined) return false

    if (value === null) return true

    return list.includes(value)
  }

  // https://url.spec.whatwg.org/#dom-urlsearchparams-set
  set(name, value = null) {
    if (value === null) this._params.delete(name)
    else this._params.set(name, [value])

    this._update()
  }

  toString() {
    return this._serialize()
  }

  toJSON() {
    return [...this]
  }

  *[Symbol.iterator]() {
    for (const [name, values] of this._params) {
      for (const value of values) yield [name, value]
    }
  }

  [Symbol.for('bare.inspect')]() {
    const object = {
      __proto__: { constructor: URLSearchParams }
    }

    for (const [name, values] of this._params) {
      if (values.length === 1) object[name] = values[0]
      else object[name] = values
    }

    return object
  }

  // https://url.spec.whatwg.org/#concept-urlsearchparams-update
  _update() {
    const url = URLSearchParams._urls.get(this)

    if (url === undefined) return

    url.search = this._serialize()
  }

  // https://url.spec.whatwg.org/#concept-urlencoded-parser
  _parse(input) {
    if (input[0] === '?') input = input.substring(1)

    this._params = new Map()

    for (let sequence of input.split('&')) {
      if (sequence.length === 0) continue

      sequence = sequence.replace(/\+/g, ' ')

      let i = sequence.indexOf('=')
      if (i === -1) i = sequence.length

      const name = decodeURIComponent(sequence.substring(0, i))
      const value = decodeURIComponent(sequence.substring(i + 1, sequence.length))

      let list = this._params.get(name)

      if (list === undefined) {
        list = []
        this._params.set(name, list)
      }

      list.push(value)
    }
  }

  // https://url.spec.whatwg.org/#concept-urlencoded-serializer
  _serialize() {
    let output = ''

    for (let [name, values] of this._params) {
      name = encodeURIComponent(name)

      for (const value of values) {
        if (output) output += '&'

        output += name + '=' + encodeURIComponent(value)
      }
    }

    return output
  }
}

module.exports = exports = URLSearchParams

exports.isURLSearchParams = function isURLSearchParams(value) {
  if (value instanceof URLSearchParams) return true

  return typeof value === 'object' && value !== null && value[kind] === URLSearchParams[kind]
}
{
  "name": "bare-url",
  "version": "2.4.2",
  "description": "WHATWG URL implementation for JavaScript",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./global": {
      "types": "./global.d.ts",
      "default": "./global.js"
    }
  },
  "files": [
    "index.js",
    "index.d.ts",
    "global.js",
    "global.d.ts",
    "binding.c",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "brittle-bare --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bare-url.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-url/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-url",
  "dependencies": {
    "bare-path": "^3.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "cmake-bare": "^1.1.6",
    "cmake-fetch": "^1.0.0",
    "lunte": "^1.6.0",
    "prettier": "^3.3.3",
    "prettier-config-holepunch": "^2.0.0"
  }
}
const b4a = require('b4a')

function byteLength (size) {
  return Math.ceil(size / 8)
}

function get (buffer, bit) {
  const n = buffer.BYTES_PER_ELEMENT * 8

  const offset = bit & (n - 1)
  const i = (bit - offset) / n

  return (buffer[i] & (1 << offset)) !== 0
}

function set (buffer, bit, value = true) {
  const n = buffer.BYTES_PER_ELEMENT * 8

  const offset = bit & (n - 1)
  const i = (bit - offset) / n
  const mask = 1 << offset

  if (value) {
    if ((buffer[i] & mask) !== 0) return false
  } else {
    if ((buffer[i] & mask) === 0) return false
  }

  buffer[i] ^= mask
  return true
}

function setRange (buffer, start, end, value = true) {
  const n = buffer.BYTES_PER_ELEMENT * 8

  let remaining = end - start
  let offset = start & (n - 1)
  let i = (start - offset) / n

  let changed = false

  while (remaining > 0) {
    const mask = (2 ** Math.min(remaining, n - offset) - 1) << offset

    if (value) {
      if ((buffer[i] & mask) !== mask) {
        buffer[i] |= mask
        changed = true
      }
    } else {
      if ((buffer[i] & mask) !== 0) {
        buffer[i] &= ~mask
        changed = true
      }
    }

    remaining -= n - offset
    offset = 0
    i++
  }

  return changed
}

function fill (buffer, value, start = 0, end = buffer.byteLength * 8) {
  const n = buffer.BYTES_PER_ELEMENT * 8
  let i, j

  {
    const offset = start & (n - 1)
    i = (start - offset) / n

    if (offset !== 0) {
      const mask = (2 ** Math.min(n - offset, end - start) - 1) << offset

      if (value) buffer[i] |= mask
      else buffer[i] &= ~mask

      i++
    }
  }

  {
    const offset = end & (n - 1)
    j = (end - offset) / n

    if (offset !== 0 && j >= i) {
      const mask = (2 ** offset) - 1

      if (value) buffer[j] |= mask
      else buffer[j] &= ~mask
    }
  }

  return buffer.fill(value ? (2 ** n) - 1 : 0, i, j)
}

function toggle (buffer, bit) {
  const n = buffer.BYTES_PER_ELEMENT * 8

  const offset = bit & (n - 1)
  const i = (bit - offset) / n
  const mask = 1 << offset

  buffer[i] ^= mask
  return (buffer[i] & mask) !== 0
}

function remove (buffer, bit) {
  return set(buffer, bit, false)
}

function removeRange (buffer, start, end) {
  return setRange(buffer, start, end, false)
}

function indexOf (buffer, value, position = 0) {
  for (let i = position, n = buffer.byteLength * 8; i < n; i++) {
    if (get(buffer, i) === value) return i
  }

  return -1
}

function lastIndexOf (buffer, value, position = buffer.byteLength * 8 - 1) {
  for (let i = position; i >= 0; i--) {
    if (get(buffer, i) === value) return i
  }

  return -1
}

function of (...bits) {
  return from(bits)
}

function from (bits) {
  const buffer = b4a.alloc(byteLength(bits.length))
  for (let i = 0; i < bits.length; i++) set(buffer, i, bits[i])
  return buffer
}

function * iterator (buffer) {
  for (let i = 0, n = buffer.byteLength * 8; i < n; i++) yield get(buffer, i)
}

module.exports = {
  byteLength,
  get,
  set,
  setRange,
  fill,
  toggle,
  remove,
  removeRange,
  indexOf,
  lastIndexOf,
  of,
  from,
  iterator
}
{
  "name": "bits-to-bytes",
  "version": "1.3.0",
  "description": "Functions for doing bit manipulation of typed arrays",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "scripts": {
    "test": "standard && brittle test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/bits-to-bytes.git"
  },
  "author": "Kasper Isager Dalsgarð <kasper@funktionel.co>",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/holepunchto/bits-to-bytes/issues"
  },
  "homepage": "https://github.com/holepunchto/bits-to-bytes#readme",
  "dependencies": {
    "b4a": "^1.5.0"
  },
  "devDependencies": {
    "brittle": "^2.3.1",
    "standard": "^17.0.0"
  }
}
const EventEmitter = require('events')
const Protomux = require('protomux')
const { Readable } = require('streamx')
const sodium = require('sodium-universal')
const b4a = require('b4a')
const c = require('compact-encoding')
const bitfield = require('compact-encoding-bitfield')
const bits = require('bits-to-bytes')
const errors = require('./lib/errors')

exports.Server = class BlindRelayServer extends EventEmitter {
  constructor(opts = {}) {
    super()

    const { createStream } = opts

    this._createStream = createStream
    this._pairing = new Map()
    this._sessions = new Set()
    this.stats = createStats(this)
  }

  get sessions() {
    return this._sessions[Symbol.iterator]()
  }

  accept(stream, opts) {
    const session = new BlindRelaySession(this, stream, opts)

    this._sessions.add(session)
    this.stats.sessions.accepted++

    return session
  }

  async close() {
    const ending = []

    for (const session of this._sessions) {
      ending.push(session.end())
    }

    await Promise.all(ending)

    this._pairing.clear()
  }

  _activePairings() {
    const active = new Set()

    for (const session of this._sessions) {
      for (const token of session._links.keys()) {
        active.add(token)
      }
    }

    return active.size
  }

  _activeStreams() {
    let active = 0

    for (const session of this._sessions) {
      active += session._links.size
    }

    return active
  }
}

class BlindRelaySession extends EventEmitter {
  constructor(server, stream, opts = {}) {
    super()

    const { id, handshake, handshakeEncoding } = opts

    this._server = server
    this._mux = Protomux.from(stream)

    this._channel = this._mux.createChannel({
      protocol: 'blind-relay',
      id,
      handshake: handshake ? handshakeEncoding || c.raw : null,
      onopen: this._onopen.bind(this),
      onclose: this._onclose.bind(this),
      ondestroy: this._ondestroy.bind(this)
    })

    this._pair = this._channel.addMessage({
      encoding: m.pair,
      onmessage: this._onpair.bind(this)
    })

    this._unpair = this._channel.addMessage({
      encoding: m.unpair,
      onmessage: this._onunpair.bind(this)
    })

    this._ending = null
    this._destroyed = false
    this._error = null
    this._pairing = new Set()
    this._links = new Map()

    this._onerror = (err) => {
      this._server.stats.streams.errors++
      this.emit('error', err)
    }

    this._channel.open(handshake)
  }

  get closed() {
    return this._channel.closed
  }

  get mux() {
    return this._mux
  }

  get stream() {
    return this._mux.stream
  }

  _onopen() {
    this._server.stats.sessions.opened++
    this.emit('open')
  }

  _onclose() {
    this._ending = Promise.resolve()

    const err = this._error || errors.CHANNEL_CLOSED()
    this._server.stats.pairings.cancelled += this._pairing.size

    for (const token of this._pairing) {
      this._server._pairing.delete(token.toString('hex'))
    }

    for (const link of this._links.values()) {
      link.destroy(err)
    }

    this._pairing.clear()
    this._links.clear()

    this._server._sessions.delete(this)
    this._server.stats.sessions.closed++

    this.emit('close')
  }

  _ondestroy() {
    this._destroyed = true
    this.emit('destroy')
  }

  _onpair({ isInitiator, token, id: remoteId }) {
    const keyString = token.toString('hex')

    let pair = this._server._pairing.get(keyString)

    if (pair === undefined) {
      pair = new BlindRelayPair(token)
      this._server._pairing.set(keyString, pair)
    } else if (pair.links[+isInitiator]) return

    this._pairing.add(keyString)
    this._server.stats.pairings.requested++

    pair.links[+isInitiator] = new BlindRelayLink(this, isInitiator, remoteId)

    if (!pair.paired) return

    this._server._pairing.delete(keyString)
    this._server.stats.pairings.matched++

    // 1st pass: Create the raw streams needed for each end of the link.
    for (const link of pair.links) {
      link.createStream()
    }

    // 2nd pass: Connect the raw streams and set up handlers.
    for (const link of pair.links) {
      link.remote = pair.remote(link.isInitiator)
      link.activate(keyString)
    }

    // 3rd pass: Let either end of the link know the streams were set up.
    for (const { isInitiator, session, remoteId, stream } of pair.links) {
      session._pair.send({
        isInitiator,
        token,
        id: stream.id,
        seq: 0
      })

      session._endMaybe()

      session.emit('pair', isInitiator, token, stream, remoteId)
    }
  }

  _onunpair({ token }) {
    const keyString = token.toString('hex')

    const pair = this._server._pairing.get(keyString)

    if (pair) {
      for (const link of pair.links) {
        if (link) link.session._pairing.delete(keyString)
      }

      this._server.stats.pairings.cancelled++
      return this._server._pairing.delete(keyString)
    }

    const link = this._links.get(keyString)

    if (link) {
      link.destroyPair(errors.PAIRING_CANCELLED())
      this._server.stats.pairings.cancelled++
    }
  }

  cork() {
    this._channel.cork()
  }

  uncork() {
    this._channel.uncork()
  }

  async end() {
    if (this._ending) return this._ending

    this._ending = EventEmitter.once(this, 'close')
    this._endMaybe()

    return this._ending
  }

  _endMaybe() {
    if (this._ending && this._pairing.size === 0) {
      this._channel.close()
    }
  }

  destroy(err) {
    if (this._destroyed) return
    this._destroyed = true

    this._error = err || errors.CHANNEL_DESTROYED()
    this._channel.close()
  }
}

class BlindRelayPair {
  constructor(token) {
    this.token = token
    this.links = [null, null]
  }

  get paired() {
    return this.links[0] !== null && this.links[1] !== null
  }

  remote(isInitiator) {
    return this.links[isInitiator ? 0 : 1]
  }
}

class BlindRelayLink {
  constructor(session, isInitiator, remoteId) {
    this.session = session
    this.isInitiator = isInitiator
    this.remoteId = remoteId
    this.stream = null
    this.remote = null
    this.keyString = null
    this._onclose = null
  }

  createStream() {
    if (this.stream) return

    this.stream = this.session._server._createStream({
      firewall: this._onfirewall.bind(this)
    })
  }

  activate(keyString) {
    const stream = this.stream

    this.keyString = keyString
    this._onclose = () => {
      if (this.stream !== stream) return

      this.stream = null
      unlink(this)
      this.session._links.delete(keyString)
      this.session._server.stats.streams.closed++
    }

    stream.on('error', this.session._onerror).on('close', this._onclose).relayTo(this.remote.stream)

    this.session._pairing.delete(keyString)
    this.session._links.set(keyString, this)
    this.session._server.stats.streams.opened++
  }

  destroy(err) {
    const stream = this.stream

    if (!stream) return

    this.stream = null

    stream.off('close', this._onclose)
    this._onclose = null

    stream.off('error', this.session._onerror)
    unlink(this)
    this.session._links.delete(this.keyString)
    this.session._server.stats.streams.closed++
    stream.on('error', noop).destroy(err)
  }

  destroyPair(err) {
    const remote = this.remote

    this.destroy(err)
    if (remote) remote.destroy(err)
  }

  _onfirewall(socket, port, host) {
    this.stream.connect(socket, this.remoteId, port, host)

    return false
  }
}

exports.Client = class BlindRelayClient extends EventEmitter {
  static _clients = new WeakMap()

  static from(stream, opts) {
    let client = this._clients.get(stream)
    if (client) return client
    client = new this(stream, opts)
    this._clients.set(stream, client)
    return client
  }

  constructor(stream, opts = {}) {
    super()

    const { id, handshake, handshakeEncoding } = opts

    this._mux = Protomux.from(stream)

    this._channel = this._mux.createChannel({
      protocol: 'blind-relay',
      id,
      handshake: handshake ? handshakeEncoding || c.raw : null,
      onopen: this._onopen.bind(this),
      onclose: this._onclose.bind(this),
      ondestroy: this._ondestroy.bind(this)
    })

    this._pair = this._channel.addMessage({
      encoding: m.pair,
      onmessage: this._onpair.bind(this)
    })

    this._unpair = this._channel.addMessage({
      encoding: m.unpair
    })

    this._ending = false
    this._destroyed = false
    this._error = null
    this._requests = new Map()

    this._channel.open(handshake)
  }

  get closed() {
    return this._channel.closed
  }

  get mux() {
    return this._mux
  }

  get stream() {
    return this._mux.stream
  }

  get requests() {
    return this._requests.values()
  }

  _onopen() {
    this.emit('open')
  }

  _onclose() {
    this._ending = Promise.resolve()

    const err = this._error || errors.CHANNEL_CLOSED()

    for (const request of this._requests.values()) {
      request.destroy(err)
    }

    this._requests.clear()

    this.constructor._clients.delete(this.stream)

    this.emit('close')
  }

  _ondestroy() {
    this._destroyed = true
    this.emit('destroy')
  }

  _onpair({ isInitiator, token, id: remoteId }) {
    const request = this._requests.get(token.toString('hex'))

    if (request === undefined || request.isInitiator !== isInitiator) return

    request.push(remoteId)
    request.push(null)

    this.emit('pair', request.isInitiator, request.token, request.stream, remoteId)
  }

  pair(isInitiator, token, stream) {
    if (this._destroyed) throw errors.CHANNEL_DESTROYED()

    const keyString = token.toString('hex')

    if (this._requests.has(keyString)) throw errors.ALREADY_PAIRING()

    const request = new BlindRelayRequest(this, isInitiator, token, stream)

    this._requests.set(keyString, request)

    return request
  }

  unpair(token) {
    if (this._destroyed) throw errors.CHANNEL_DESTROYED()

    const request = this._requests.get(token.toString('hex'))

    if (request) request.destroy(errors.PAIRING_CANCELLED())

    this._unpair.send({ token })
  }

  cork() {
    this._channel.cork()
  }

  uncork() {
    this._channel.uncork()
  }

  async end() {
    if (this._ending) return this._ending

    this._ending = EventEmitter.once(this, 'close')
    this._endMaybe()

    return this._ending
  }

  _endMaybe() {
    if (this._ending && this._requests.size === 0) {
      this._channel.close()
    }
  }

  destroy(err) {
    if (this._destroyed) return
    this._destroyed = true

    this._error = err || errors.CHANNEL_DESTROYED()
    this._channel.close()
  }
}

class BlindRelayRequest extends Readable {
  constructor(client, isInitiator, token, stream) {
    super()

    this.client = client
    this.isInitiator = isInitiator
    this.token = token
    this.stream = stream
  }

  _open(cb) {
    if (this.client._destroyed) return cb(errors.CHANNEL_DESTROYED())

    this.client._pair.send({
      isInitiator: this.isInitiator,
      token: this.token,
      id: this.stream.id,
      seq: 0
    })

    cb(null)
  }

  _destroy(cb) {
    this.client._requests.delete(this.token.toString('hex'))

    cb(null)

    this.client._endMaybe()
  }
}

exports.token = function token(buf = b4a.allocUnsafe(32)) {
  sodium.randombytes_buf(buf)
  return buf
}

function noop() {}

function unlink(link) {
  const remote = link.remote

  link.remote = null

  if (remote && remote.remote === link) {
    remote.remote = null
  }
}

function createStats(server) {
  const stats = {
    sessions: {
      accepted: 0,
      opened: 0,
      closed: 0
    },
    pairings: {
      requested: 0,
      matched: 0,
      cancelled: 0
    },
    streams: {
      opened: 0,
      closed: 0,
      errors: 0
    }
  }

  Object.defineProperties(stats.sessions, {
    active: {
      enumerable: true,
      get() {
        return server._sessions.size
      }
    }
  })

  Object.defineProperties(stats.pairings, {
    pending: {
      enumerable: true,
      get() {
        return server._pairing.size
      }
    },
    active: {
      enumerable: true,
      get() {
        return server._activePairings()
      }
    }
  })

  Object.defineProperties(stats.streams, {
    active: {
      enumerable: true,
      get() {
        return server._activeStreams()
      }
    }
  })

  return stats
}

const m = (exports.messages = {})

const flags = bitfield(7)

m.pair = {
  preencode(state, m) {
    flags.preencode(state)
    c.fixed32.preencode(state, m.token)
    c.uint.preencode(state, m.id)
    c.uint.preencode(state, m.seq)
  },
  encode(state, m) {
    flags.encode(state, bits.of(m.isInitiator))
    c.fixed32.encode(state, m.token)
    c.uint.encode(state, m.id)
    c.uint.encode(state, m.seq)
  },
  decode(state) {
    const [isInitiator] = bits.iterator(flags.decode(state))

    return {
      isInitiator,
      token: c.fixed32.decode(state),
      id: c.uint.decode(state),
      seq: c.uint.decode(state)
    }
  }
}

m.unpair = {
  preencode(state, m) {
    flags.preencode(state)
    c.fixed32.preencode(state, m.token)
  },
  encode(state, m) {
    flags.encode(state, bits.of())
    c.fixed32.encode(state, m.token)
  },
  decode(state) {
    flags.decode(state)

    return {
      token: c.fixed32.decode(state)
    }
  }
}
module.exports = class BlindRelayError extends Error {
  constructor(msg, code, fn = BlindRelayError) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'BlindRelayError'
  }

  static DUPLICATE_CHANNEL(msg = 'Duplicate channel') {
    return new BlindRelayError(msg, 'DUPLICATE_CHANNEL', BlindRelayError.DUPLICATE_CHANNEL)
  }

  static CHANNEL_CLOSED(msg = 'Channel closed') {
    return new BlindRelayError(msg, 'CHANNEL_CLOSED', BlindRelayError.CHANNEL_CLOSED)
  }

  static CHANNEL_DESTROYED(msg = 'Channel destroyed') {
    return new BlindRelayError(msg, 'CHANNEL_DESTROYED', BlindRelayError.CHANNEL_DESTROYED)
  }

  static ALREADY_PAIRING(msg = 'Already pairing') {
    return new BlindRelayError(msg, 'ALREADY_PAIRING', BlindRelayError.ALREADY_PAIRING)
  }

  static PAIRING_CANCELLED(msg = 'Pairing cancelled') {
    return new BlindRelayError(msg, 'PAIRING_CANCELLED', BlindRelayError.PAIRING_CANCELLED)
  }
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return uint24.decode(state) + 0x1000000 * uint32.decode(state)
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return uint32.decode(state) + 0x100000000 * uint32.decode(state)
  }
})

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "2.19.2",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    if (b.byteLength === 0) return null
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "blind-relay",
  "version": "1.5.0",
  "description": "Blind relay for UDX over Protomux channels",
  "main": "index.js",
  "files": [
    "index.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:bare",
    "test:bare": "brittle-bare --coverage test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/blind-relay.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/blind-relay/issues"
  },
  "homepage": "https://github.com/holepunchto/blind-relay#readme",
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "dependencies": {
    "b4a": "^1.6.4",
    "bare-events": "^2.2.0",
    "bits-to-bytes": "^1.3.0",
    "compact-encoding": "^2.12.0",
    "compact-encoding-bitfield": "^1.0.0",
    "protomux": "^3.5.1",
    "sodium-universal": "^5.0.0",
    "streamx": "^2.15.1"
  },
  "devDependencies": {
    "brittle": "^3.2.1",
    "hyperdht": "^6.6.1",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "udx-native": "^1.6.1"
  }
}
// https://ipinfo.io/bogon

const b4a = require('b4a')
const c = require('compact-encoding')
const net = require('compact-encoding-net')

module.exports = exports = function isBogon (ip) {
  return isBogonIP(ensureBuffer(ip))
}

exports.isBogon = exports

exports.isPrivate = function isPrivate (ip) {
  return isPrivateIP(ensureBuffer(ip))
}

exports.isReserved = function isReserved (ip) {
  return isReservedIP(ensureBuffer(ip))
}

function isBogonIP (ip) {
  return isPrivateIP(ip) || isReservedIP(ip)
}

function isPrivateIP (ip) {
  return ip.byteLength === 4 ? isPrivateIPv4(ip) : false // IPv6 has no private IPs
}

function isPrivateIPv4 (ip) {
  return (
    // 10.0.0.0/8  Private-use networks
    (ip[0] === 10) ||
    // 100.64.0.0/10 Carrier-grade NAT
    (ip[0] === 100 && ip[1] >= 64 && ip[1] <= 127) ||
    // 127.0.0.0/8 Loopback + Name collision occurrence (127.0.53.53)
    (ip[0] === 127) ||
    // 169.254.0.0/16  Link local
    (ip[0] === 169 && ip[1] === 254) ||
    // 172.16.0.0/12 Private-use networks
    (ip[0] === 172 && ip[1] >= 16 && ip[1] <= 31) ||
    // 192.168.0.0/16  Private-use networks
    (ip[0] === 192 && ip[1] === 168)
  )
}

function isReservedIP (ip) {
  return ip.byteLength === 4 ? isReservedIPv4(ip) : isReservedIPv6(ip)
}

function isReservedIPv4 (ip) {
  return (
    // 0.0.0.0/8 "This" network
    (ip[0] === 0) ||
    // 192.0.0.0/24  IETF protocol assignments
    (ip[0] === 192 && ip[1] === 0 && ip[2] === 0) ||
    // 192.0.2.0/24  TEST-NET-1
    (ip[0] === 192 && ip[1] === 0 && ip[2] === 2) ||
    // 198.18.0.0/15 Network interconnect device benchmark testing
    (ip[0] === 198 && ip[1] >= 18 && ip[1] <= 19) ||
    // 198.51.100.0/24 TEST-NET-2
    (ip[0] === 198 && ip[1] === 51 && ip[2] === 100) ||
    // 203.0.113.0/24  TEST-NET-3
    (ip[0] === 203 && ip[1] === 0 && ip[2] === 113) ||
    // 224.0.0.0/4 Multicast
    (ip[0] >= 224 && ip[0] <= 239) ||
    // 240.0.0.0/4 Reserved for future use
    (ip[0] >= 240) ||
    // 255.255.255.255/32
    (ip[0] === 255 && ip[1] === 255 && ip[2] === 255 && ip[3] === 255)
  )
}

function isReservedIPv6 (ip) {
  return (
    // ::/128 Node-scope unicast unspecified address
    // ::1/128 Node-scope unicast loopback address
    (
      ip[0] === 0 && ip[1] === 0 && ip[2] === 0 && ip[3] === 0 && ip[4] === 0 &&
      ip[5] === 0 && ip[6] === 0 && ip[7] === 0 && ip[8] === 0 && ip[9] === 0 &&
      ip[10] === 0 && ip[11] === 0 && ip[12] === 0 && ip[13] === 0 && ip[14] === 0 &&
      ip[15] <= 1
    ) ||
    // ::ffff:0:0/96 IPv4-mapped addresses
    // ::/96 IPv4-compatible addresses
    (
      ip[0] === 0 && ip[1] === 0 && ip[2] === 0 && ip[3] === 0 && ip[4] === 0 &&
      ip[5] === 0 && ip[6] === 0 && ip[7] === 0 && ip[8] === 0 && ip[9] === 0 &&
      (ip[10] === 0 || ip[10] === 0xff) &&
      (ip[11] === 0 || ip[11] === 0xff)
    ) ||
    // 100::/64 Remotely triggered black hole addresses
    (ip[0] === 0x01 && ip[1] === 0 && ip[2] === 0 && ip[3] === 0 && ip[4] === 0 && ip[5] === 0 && ip[6] === 0 && ip[7] === 0) ||
    // 2001:10::/28 Overlay routable cryptographic hash identifiers (ORCHID)
    (ip[0] === 0x20 && ip[1] === 0x01 && ip[2] === 0 && ip[3] >= 0x10 && ip[3] <= 0x1f) ||
    // 2001:20::/28 Overlay routable cryptographic hash identifiers version 2 (ORCHIDv2)
    (ip[0] === 0x20 && ip[1] === 0x01 && ip[2] === 0 && ip[3] >= 0x20 && ip[3] <= 0x2f) ||
    // 2001:db8::/32 Documentation prefix
    (ip[0] === 0x20 && ip[1] === 0x01 && ip[2] === 0x0d && ip[3] === 0xb8) ||
    // fc00::/7 Unique local addresses (ULA)
    (ip[0] >= 0xfc && ip[0] <= 0xfd) ||
    // fe80::/10 Link-local unicast
    (ip[0] === 0xfe && ip[1] >= 0x80 && ip[1] <= 0xbf) ||
    // ff00::/8 Multicast
    (ip[0] === 0xff)
  )
}

const state = c.state(0, 0, b4a.allocUnsafe(1 /* family */ + 16))

function ensureBuffer (ip) {
  if (b4a.isBuffer(ip)) return ip

  net.ip.preencode(state, ip)
  net.ip.encode(state, ip)

  const buffer = state.buffer.subarray(1 /* family */, state.end)

  state.start = 0
  state.end = 0

  return buffer
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return uint24.decode(state) + 0x1000000 * uint32.decode(state)
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return uint32.decode(state) + 0x100000000 * uint32.decode(state)
  }
})

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "2.19.2",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    if (b.byteLength === 0) return null
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "bogon",
  "version": "1.2.0",
  "description": "Check if an IP is a bogon",
  "main": "index.js",
  "scripts": {
    "test": "standard && brittle test.mjs"
  },
  "dependencies": {
    "compact-encoding": "^2.11.0",
    "compact-encoding-net": "^1.2.0"
  },
  "devDependencies": {
    "brittle": "^3.0.4",
    "nanobench": "^2.1.1",
    "standard": "^17.0.0"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/bogon.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/bogon/issues"
  },
  "homepage": "https://github.com/mafintosh/bogon"
}
const c = require('compact-encoding')

module.exports = function bitfield (length) {
  if (length > 64) throw new RangeError('Bitfield cannot be larger than 64 bits')

  let byteLength
  if (length < 8) byteLength = 1
  else if (length <= 16) byteLength = 2
  else if (length <= 32) byteLength = 4
  else byteLength = 8

  return {
    preencode (state) {
      state.end++ // Length byte, used for data when byteLength === 1

      if (byteLength === 1) ;
      else if (byteLength === 2) c.uint16.preencode(state)
      else if (byteLength === 4) c.uint32.preencode(state)
      else c.uint64.preencode(state)
    },

    encode (state, b) {
      if (byteLength === 1) ;
      else if (byteLength === 2) c.uint8.encode(state, 0xfd)
      else if (byteLength === 4) c.uint8.encode(state, 0xfe)
      else c.uint8.encode(state, 0xff)

      if (typeof b === 'number') {
        if (byteLength === 1) c.uint8.encode(state, b)
        else if (byteLength === 2) c.uint16.encode(state, b)
        else if (byteLength === 4) c.uint32.encode(state, b)
        else c.uint64.encode(state, b)
      } else {
        state.buffer.set(b, state.start)

        if (b.byteLength < byteLength) {
          // Zero-fill the rest of the byte length.
          state.buffer.fill(
            0,
            state.start + b.byteLength,
            state.start + byteLength
          )
        }

        state.start += byteLength
      }
    },

    decode (state) {
      const byte = state.buffer[state.start]

      let byteLength
      if (byte <= 0xfc) byteLength = 1
      else if (byte === 0xfd) byteLength = 2
      else if (byte === 0xfe) byteLength = 4
      else byteLength = 8

      if (byteLength > 1) state.start++ // Skip the length byte

      if (state.end - state.start < byteLength) throw new Error('Out of bounds')

      const b = state.buffer.subarray(state.start, (state.start += byteLength))

      return length <= 8 ? b.subarray(0, 1) : b
    }
  }
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return uint24.decode(state) + 0x1000000 * uint32.decode(state)
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return uint32.decode(state) + 0x100000000 * uint32.decode(state)
  }
})

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "2.19.2",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    if (b.byteLength === 0) return null
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "compact-encoding-bitfield",
  "version": "1.0.0",
  "description": "Compact codec for bitfields",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "scripts": {
    "test": "standard && brittle test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/compact-encoding/compact-encoding-bitfield.git"
  },
  "author": "Kasper Isager Dalsgarð <kasper@funktionel.co>",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/compact-encoding/compact-encoding-bitfield/issues"
  },
  "homepage": "https://github.com/compact-encoding/compact-encoding-bitfield#readme",
  "dependencies": {
    "compact-encoding": "^2.4.1"
  },
  "devDependencies": {
    "brittle": "^1.3.5",
    "standard": "^16.0.3"
  },
  "standard": {
    "ignore": [
      "__snapshots__/**"
    ]
  }
}
const c = require('compact-encoding')

const port = c.uint16

const address = (host, family) => {
  return {
    preencode (state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode (state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode (state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = {
  preencode (state) {
    state.end += 4
  },
  encode (state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (i < string.length && (c = string.charCodeAt(i++)) !== /* . */ 0x2e) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode (state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] + '.' +
      state.buffer[state.start++] + '.' +
      state.buffer[state.start++] + '.' +
      state.buffer[state.start++]
    )
  }
}

const ipv4Address = address(ipv4, 4)

const ipv6 = {
  preencode (state) {
    state.end += 16
  },
  encode (state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (i < string.length && (c = string.charCodeAt(i++)) !== /* : */ 0x3a) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode (state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (state.buffer[state.start++] * 256 + state.buffer[state.start++]).toString(16) + ':' +
      (state.buffer[state.start++] * 256 + state.buffer[state.start++]).toString(16) + ':' +
      (state.buffer[state.start++] * 256 + state.buffer[state.start++]).toString(16) + ':' +
      (state.buffer[state.start++] * 256 + state.buffer[state.start++]).toString(16) + ':' +
      (state.buffer[state.start++] * 256 + state.buffer[state.start++]).toString(16) + ':' +
      (state.buffer[state.start++] * 256 + state.buffer[state.start++]).toString(16) + ':' +
      (state.buffer[state.start++] * 256 + state.buffer[state.start++]).toString(16) + ':' +
      (state.buffer[state.start++] * 256 + state.buffer[state.start++]).toString(16)
    )
  }
}

const ipv6Address = address(ipv6, 6)

const ip = {
  preencode (state, string) {
    const family = string.includes(':') ? 6 : 4
    c.uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode (state, string) {
    const family = string.includes(':') ? 6 : 4
    c.uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode (state) {
    const family = c.uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
}

const ipAddress = {
  preencode (state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode (state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode (state) {
    const family = c.uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

module.exports = {
  port,
  ipv4,
  ipv4Address,
  ipv6,
  ipv6Address,
  ip,
  ipAddress
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return uint24.decode(state) + 0x1000000 * uint32.decode(state)
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return uint32.decode(state) + 0x100000000 * uint32.decode(state)
  }
})

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "2.19.2",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    if (b.byteLength === 0) return null
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "compact-encoding-net",
  "version": "1.2.0",
  "description": "Compact codecs for net types",
  "main": "index.js",
  "scripts": {
    "test": "standard && brittle test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/compact-encoding/compact-encoding-net.git"
  },
  "author": "Kasper Isager Dalsgarð <kasper@funktionel.co>",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/compact-encoding/compact-encoding-net/issues"
  },
  "homepage": "https://github.com/compact-encoding/compact-encoding-net#readme",
  "dependencies": {
    "compact-encoding": "^2.4.1"
  },
  "devDependencies": {
    "brittle": "^1.3.5",
    "nanobench": "^2.1.1",
    "standard": "^16.0.3"
  }
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint32be = (exports.uint32be = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n >>> 24
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] * 0x1000000 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++]
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return uint24.decode(state) + 0x1000000 * uint32.decode(state)
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return uint32.decode(state) + 0x100000000 * uint32.decode(state)
  }
})

exports.uint64be = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32be.encode(state, r)
    uint32be.encode(state, n)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return 0x100000000 * uint32be.decode(state) + uint32be.decode(state)
  }
}

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.optionalBuffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
}

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
  // Beyond this, Number arithmetic loses precision and silently corrupts the
  // encoding. The zig-zag int codecs route through here too, so this also
  // guards int values whose doubled magnitude exceeds the safe range.
  if (n > Number.MAX_SAFE_INTEGER)
    throw new Error(
      'integer is greater than the maximum safe integer, use biguint/bigint'
    )
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "3.2.0",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "files": [
    "endian.js",
    "index.js",
    "lexint.js",
    "raw.js"
  ],
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    uint8array.preencode(state, b)
  },
  encode(state, b) {
    uint8array.encode(state, b)
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
const { EventEmitter } = require('events')
const Table = require('kademlia-routing-table')
const TOS = require('time-ordered-set')
const UDX = require('udx-native')
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const NatSampler = require('nat-sampler')
const b4a = require('b4a')
const NetworkHealth = require('./lib/health')
const IO = require('./lib/io')
const Query = require('./lib/query')
const Session = require('./lib/session')
const peer = require('./lib/peer')
const { UNKNOWN_COMMAND, INVALID_TOKEN } = require('./lib/errors')
const { PING, PING_NAT, FIND_NODE, DOWN_HINT, DELAYED_PING } = require('./lib/commands')

const TMP = b4a.allocUnsafe(32)
const TICK_INTERVAL = 5000
const SLEEPING_INTERVAL = 3 * TICK_INTERVAL
const STABLE_TICKS = 240 // if nothing major bad happens in ~20mins we can consider this node stable (if nat is friendly)
const MORE_STABLE_TICKS = 3 * STABLE_TICKS
const REFRESH_TICKS = 60 // refresh every ~5min when idle
const RECENT_NODE = 12 // we've heard from a node less than 1min ago
const OLD_NODE = 360 // if an node has been around more than 30 min we consider it old

const DEFAULTS = {
  concurrency: 10,
  maxWindow: IO.DEFAULT_MAX_WINDOW,
  maxPingDelay: 10_000
}

class DHT extends EventEmitter {
  constructor(opts = {}) {
    super()

    this.bootstrapNodes = opts.bootstrap === false ? [] : (opts.bootstrap || []).map(parseNode)
    this.table = new Table(randomBytes(32))
    this.nodes = new TOS()
    this.udx = opts.udx || new UDX()
    this.io = new IO(this.table, this.udx, {
      ...opts,
      onrequest: this._onrequest.bind(this),
      onresponse: this._onresponse.bind(this),
      ontimeout: this._ontimeout.bind(this)
    })
    this.health = new NetworkHealth(this)

    this.concurrency = opts.concurrency || DEFAULTS.concurrency
    this.maxPingDelay = opts.maxPingDelay || DEFAULTS.maxPingDelay
    this.bootstrapped = false
    this.ephemeral = true
    this.firewalled = this.io.firewalled
    this.adaptive = typeof opts.ephemeral !== 'boolean' && opts.adaptive !== false
    this.destroyed = false
    this.suspended = false
    this.online = true
    this.degraded = false
    this.stats = {
      queries: { active: 0, total: 0 },
      requests: this.io.stats.requests,
      commands: {
        ping: this.io.stats.commands[PING],
        pingNat: this.io.stats.commands[PING_NAT],
        findNode: this.io.stats.commands[FIND_NODE],
        downHint: this.io.stats.commands[DOWN_HINT]
      }
    }

    this._nat = new NatSampler()
    this._quickFirewall = opts.quickFirewall !== false
    this._forcePersistent = opts.ephemeral === false
    this._repinging = 0
    this._checks = 0
    this._tick = randomOffset(100) // make sure to random offset all the network ticks
    this._refreshTicks = randomOffset(REFRESH_TICKS)
    this._stableTicks = this.adaptive ? STABLE_TICKS : 0
    this._tickInterval = setInterval(this._ontick.bind(this), TICK_INTERVAL)
    this._lastTick = Date.now()
    this._lastHost = null
    this._filterNode = opts.filterNode || opts.addNode || null // opts.addNode is deprecating, use opts.filterNode instead
    this._onrow = (row) => row.on('full', (node) => this._onfullrow(node, row))
    this._nonePersistentSamples = []
    this._bootstrapping = this._bootstrap()
    this._bootstrapping.catch(noop)
    this._sendDownHints = opts.sendDownHints !== false
    this._downHintsRateLimit =
      opts.downHintsRateLimit !== undefined ? opts.downHintsRateLimit : 10 * 5
    this._downHintsSentPerTick = 0
    this._pendingTimers = new Set()

    this.table.on('row', this._onrow)

    this.io.networkInterfaces.on('change', (interfaces) => this._onnetworkchange(interfaces))

    if (opts.nodes) {
      for (let i = opts.nodes.length - 1; i >= 0; i--) {
        this.addNode(opts.nodes[i])
      }
    }
  }

  static DEFAULTS = DEFAULTS

  static bootstrapper(port, host, opts) {
    if (!port) throw new Error('Port is required')
    if (!host) throw new Error('Host is required')
    if (host === '0.0.0.0' || host === '::') throw new Error('Invalid host')
    if (!UDX.isIPv4(host)) throw new Error('Host must be a IPv4 address')

    const dht = new this({
      port,
      ephemeral: false,
      firewalled: false,
      anyPort: false,
      bootstrap: [],
      ...opts
    })
    dht._nat.add(host, port)
    return dht
  }

  get id() {
    return this.ephemeral ? null : this.table.id
  }

  get host() {
    return this._nat.host
  }

  get port() {
    return this._nat.port
  }

  get randomized() {
    return this._nat.host !== null && this._nat.port === 0
  }

  get socket() {
    return this.firewalled ? this.io.clientSocket : this.io.serverSocket
  }

  get config() {
    return {
      concurrency: this.concurrency,
      maxWindow: this.io.congestion._maxWindow,
      randomPunchInterval: this._randomPunchInterval,
      connectionKeepAlive: this.connectionKeepAlive,
      sendDownHints: this._sendDownHints,
      downHintsRateLimit: this._downHintsRateLimit
    }
  }

  onmessage(socket, buf, rinfo) {
    if (buf.byteLength > 1) this.io.onmessage(socket, buf, rinfo)
  }

  bind() {
    return this.io.bind()
  }

  async suspend({ log = noop } = {}) {
    log('Suspending waiting for io bind...')
    await this.io.bind()
    log('Done, continuing')
    if (this.suspended || this.destroyed) return
    this.suspended = true
    clearInterval(this._tickInterval)
    log('Done, suspending io')
    await this.io.suspend({ log })
    log('Done, dht suspended')
    this.emit('suspend')
  }

  async resume({ log = noop } = {}) {
    if (!this.suspended || this.destroyed) return
    this.suspended = false
    this._tickInterval = setInterval(this._ontick.bind(this), TICK_INTERVAL)
    this._onwakeup()
    log('Resuming io')
    await this.io.resume()
    log('Done, dht resumed')
    this.io.networkInterfaces.on('change', (interfaces) => this._onnetworkchange(interfaces))
    this.refresh()
    this.emit('resume')
  }

  address() {
    const socket = this.socket
    return socket ? socket.address() : null
  }

  localAddress() {
    if (!this.io.serverSocket) return null

    return {
      host: localIP(this.udx),
      port: this.io.serverSocket.address().port
    }
  }

  remoteAddress() {
    if (!this.host) return null
    if (!this.port) return null
    if (this.firewalled) return null
    if (!this.io.serverSocket) return null

    const port = this.io.serverSocket.address().port
    if (port !== this.port) return null

    return {
      host: this.host,
      port
    }
  }

  addNode({ host, port }) {
    this._addNode({
      id: peer.id(host, port),
      port,
      host,
      token: null,
      to: null,
      sampled: 0,
      added: this._tick,
      pinged: 0,
      seen: 0,
      downHints: 0,
      prev: null,
      next: null
    })
  }

  toArray(opts) {
    const limit = opts && opts.limit
    if (limit === 0) return []
    return this.nodes.toArray({ limit, reverse: true }).map(({ host, port }) => ({ host, port }))
  }

  async fullyBootstrapped() {
    return this._bootstrapping
  }

  ready() {
    // Deprecating, use fullyBootstrapped instead (removed on next major)
    return this.fullyBootstrapped()
  }

  findNode(target, opts) {
    if (this.destroyed) throw new Error('Node destroyed')
    this._refreshTicks = REFRESH_TICKS
    return new Query(this, target, true, FIND_NODE, null, opts)
  }

  query({ target, command, value }, opts) {
    if (this.destroyed) throw new Error('Node destroyed')
    this._refreshTicks = REFRESH_TICKS
    return new Query(this, target, false, command, value || null, opts)
  }

  ping({ host, port }, opts) {
    let value = null

    if (opts && opts.size && opts.size > 0) value = b4a.alloc(opts.size)

    const req = this.io.createRequest(
      { id: null, host, port },
      null,
      true,
      PING,
      null,
      value,
      (opts && opts.session) || null,
      opts && opts.ttl
    )
    return this._requestToPromise(req, opts)
  }

  delayedPing({ host, port }, delayMs, opts) {
    if (delayMs > this.maxPingDelay) {
      throw new Error(`Delay exceeds max delay: ${this.maxPingDelay}ms`)
    }

    const value = b4a.allocUnsafe(4)
    c.uint32.encode({ start: 0, end: 4, buffer: value }, delayMs)

    const req = this.io.createRequest(
      { id: null, host, port },
      null,
      true,
      DELAYED_PING,
      null,
      value,
      (opts && opts.session) || null,
      opts && opts.ttl
    )
    // add 1 second to the timeout to account for network overhead
    req.timeout = delayMs + 1_000
    return this._requestToPromise(req, opts)
  }

  async rttStats() {
    const stats = {
      successes: 0,
      errors: 0,
      responses: {
        avgRtt: 0,
        errors: 0,
        avgCloserNodes: 0
      },
      closestReplies: {
        avgRtt: 0,
        errors: 0,
        avgCloserNodes: 0
      }
    }

    if (this.nodes.latest) {
      const q = this.findNode(this.nodes.latest.id)

      let responseCount = 0
      let closestCount = 0

      for await (const msg of q) {
        stats.responses.avgRtt += msg.rtt
        stats.responses.errors += msg.error
        stats.responses.avgCloserNodes += msg.closerNodes?.length || 0
        responseCount++
      }
      stats.responses.avgRtt /= responseCount
      stats.responses.avgCloserNodes /= responseCount

      for await (const msg of q.closestReplies) {
        stats.closestReplies.avgRtt += msg.rtt
        stats.closestReplies.errors += msg.error
        stats.closestReplies.avgCloserNodes += msg.closerNodes?.length || 0
        closestCount++
      }
      stats.closestReplies.avgRtt /= closestCount
      stats.closestReplies.avgCloserNodes /= closestCount

      stats.successes = q.successes
      stats.errors = q.errors
    }

    return stats
  }

  request({ token = null, command, target = null, value = null }, { host, port }, opts) {
    const req = this.io.createRequest(
      { id: null, host, port },
      token,
      false,
      command,
      target,
      value,
      (opts && opts.session) || null,
      opts && opts.ttl
    )
    return this._requestToPromise(req, opts)
  }

  session() {
    return new Session(this)
  }

  _requestToPromise(req, opts) {
    if (req === null) return Promise.reject(new Error('Node destroyed'))

    if (opts && opts.socket) req.socket = opts.socket
    if (opts && opts.retry === false) req.retries = 0

    return new Promise((resolve, reject) => {
      req.onresponse = resolve
      req.onerror = reject
      req.send()
    })
  }

  async _bootstrap() {
    const self = this

    await Promise.resolve() // wait a tick, so apis can be used from the outside
    await this.io.bind()

    this.emit('listening')

    // TODO: some papers describe more advanced ways of bootstrapping - we should prob look into that

    let first = this.firewalled && this._quickFirewall && !this._forcePersistent
    let testNat = false

    const onlyFirewall = !this._forcePersistent

    for (let i = 0; i < 2; i++) {
      await this._backgroundQuery(this.table.id).on('data', ondata).finished()

      if (this.bootstrapped || (!testNat && !this._forcePersistent)) break
      if (!(await this._updateNetworkState(onlyFirewall))) break
    }

    if (this.bootstrapped) return
    this.bootstrapped = true

    this.emit('ready')

    function ondata(data) {
      // Simple QUICK nat heuristic.
      // If we get ONE positive nat ping before the bootstrap query finishes
      // then we always to a nat test, no matter if we are adaptive...
      // This should be expanded in the future to try more than one node etc, not always hit the first etc
      // If this fails, then nbd, as the onstable hook will pick it up later.

      if (!first) return
      first = false

      const value = b4a.allocUnsafe(2)
      c.uint16.encode({ start: 0, end: 2, buffer: value }, self.io.serverSocket.address().port)

      self._request(
        data.from,
        false,
        true,
        PING_NAT,
        null,
        value,
        null,
        () => {
          testNat = true
        },
        noop
      )
    }
  }

  refresh() {
    const node = this.table.random()
    this._backgroundQuery(node ? node.id : this.table.id).on('error', noop)
  }

  async destroy() {
    const emitClose = !this.destroyed
    this.destroyed = true
    clearInterval(this._tickInterval)
    for (const timer of this._pendingTimers) {
      clearTimeout(timer)
    }
    await this.io.destroy()
    if (emitClose) this.emit('close')
  }

  _request(to, force, internal, command, target, value, session, onresponse, onerror) {
    if (internal && !this._sendDownHints && command === DOWN_HINT) return null
    const req = this.io.createRequest(to, null, internal, command, target, value, session)
    if (req === null) return null

    req.onresponse = onresponse
    req.onerror = onerror
    req.send(force)

    return req
  }

  _natAdd(host, port) {
    const prevHost = this._nat.host
    const prevPort = this._nat.port

    this._nat.add(host, port)

    if (prevHost === this._nat.host && prevPort === this._nat.port) return

    this.emit('nat-update', this._nat.host, this._nat.port)
  }

  // we don't check that this is a bootstrap node but we limit the sample size to very few nodes, so fine
  _sampleBootstrapMaybe(from, to) {
    if (this._nonePersistentSamples.length >= Math.max(1, this.bootstrapNodes.length)) return
    const id = from.host + ':' + from.port
    if (this._nonePersistentSamples.indexOf(id) > -1) return
    this._nonePersistentSamples.push(id)
    this._natAdd(to.host, to.port)
  }

  _addNodeFromNetwork(sample, from, to) {
    if (this._filterNode !== null && !this._filterNode(from)) {
      return
    }

    if (from.id === null) {
      this._sampleBootstrapMaybe(from, to)
      return
    }

    const oldNode = this.table.get(from.id)

    // refresh it, if we've seen this before
    if (oldNode) {
      if (sample && (oldNode.sampled === 0 || this._tick - oldNode.sampled >= OLD_NODE)) {
        oldNode.to = to
        oldNode.sampled = this._tick
        this._natAdd(to.host, to.port)
      }

      oldNode.pinged = oldNode.seen = this._tick
      this.nodes.add(oldNode)
      return
    }

    this._addNode({
      id: from.id,
      port: from.port,
      host: from.host,
      to,
      sampled: 0,
      added: this._tick,
      pinged: this._tick, // last time we interacted with them
      seen: this._tick, // last time we heard from them
      downHints: 0,
      prev: null,
      next: null
    })
  }

  _addNode(node) {
    if (this.nodes.has(node) || b4a.equals(node.id, this.table.id)) return

    node.added = node.pinged = node.seen = this._tick

    if (!this.table.add(node)) return
    this.nodes.add(node)

    if (node.to && node.sampled === 0) {
      node.sampled = this._tick
      this._natAdd(node.to.host, node.to.port)
    }

    this.emit('add-node', node)
  }

  _removeStaleNode(node, lastSeen) {
    if (node.seen <= lastSeen) this._removeNode(node)
  }

  _removeNode(node) {
    if (!this.nodes.has(node)) return

    this.table.remove(node.id)
    this.nodes.remove(node)

    this.emit('remove-node', node)
  }

  _onwakeup() {
    this._tick += 2 * OLD_NODE // bump the tick enough that everything appears old.
    this._tick += 8 - (this._tick & 7) - 2 // triggers a series of pings in two ticks
    this._stableTicks = MORE_STABLE_TICKS
    this._refreshTicks = 1 // triggers a refresh next tick (allow network time to wake up also)
    this._lastHost = null // clear network cache check
    this.health.reset()

    if (this.adaptive) {
      // TODO: re-enable this as soon as we find out why this is over triggering in some edge cases
      // this.firewalled = true
      // this.io.firewalled = true

      if (!this.ephemeral) {
        this.ephemeral = true
        this.io.ephemeral = true
        this.emit('ephemeral')
      }
    }

    this.emit('wakeup')
  }

  _onfullrow(newNode, row) {
    if (!this.bootstrapped || this._repinging >= 3) return

    let oldest = null
    for (const node of row.nodes) {
      if (node.pinged === this._tick) continue
      if (
        oldest === null ||
        oldest.pinged > node.pinged ||
        (oldest.pinged === node.pinged && oldest.added > node.added)
      ) {
        oldest = node
      }
    }

    if (oldest === null) return
    if (this._tick - oldest.pinged < RECENT_NODE && this._tick - oldest.added > OLD_NODE) return

    this._repingAndSwap(newNode, oldest)
  }

  _onnetworkchange(interfaces) {
    this.emit('network-change', interfaces)
    this.emit('network-update')
  }

  _repingAndSwap(newNode, oldNode) {
    const self = this
    const lastSeen = oldNode.seen

    oldNode.pinged = this._tick

    this._repinging++
    this._request(
      { id: null, host: oldNode.host, port: oldNode.port },
      false,
      true,
      PING,
      null,
      null,
      null,
      onsuccess,
      onswap
    )

    function onsuccess(m) {
      if (oldNode.seen <= lastSeen) return onswap()
      self._repinging--
    }

    function onswap(e) {
      self._repinging--
      self._removeNode(oldNode)
      self._addNode(newNode)
    }
  }

  _onrequest(req, external) {
    if (req.from.id !== null) {
      this._addNodeFromNetwork(!external, req.from, req.to)
    }

    if (req.internal) {
      switch (req.command) {
        // standard keep alive call
        case PING: {
          req.sendReply(0, null, false, false)
          return
        }
        case DELAYED_PING: {
          this._ondelayedping(req)
          return
        }
        // check if the other side can receive a message to their other socket
        case PING_NAT: {
          if (req.value === null || req.value.byteLength < 2) return
          const port = c.uint16.decode({ start: 0, end: 2, buffer: req.value })
          if (port === 0) return
          req.from.port = port
          req.sendReply(0, null, false, false)
          return
        }
        // empty dht reply back
        case FIND_NODE: {
          if (!req.target) return
          req.sendReply(0, null, false, true)
          return
        }
        // "this is node you sent me is down" - let's try to ping it
        case DOWN_HINT: {
          if (req.value === null || req.value.byteLength < 6) return
          if (this._checks < 10) {
            sodium.crypto_generichash(TMP, req.value.subarray(0, 6))
            const node = this.table.get(TMP)
            if (node && (node.pinged < this._tick || node.downHints === 0)) {
              node.downHints++
              this._check(node)
            }
          }
          req.sendReply(0, null, false, false)
          return
        }
      }

      req.sendReply(UNKNOWN_COMMAND, null, false, req.target !== null)
      return
    }

    // ask the user to handle it or reply back with a bad command
    if (this.onrequest(req) === false) {
      req.sendReply(UNKNOWN_COMMAND, null, false, req.target !== null)
    }
  }

  onrequest(req) {
    return this.emit('request', req)
  }

  _ondelayedping(req) {
    if (req.value === null || req.value.byteLength < 4) return
    const delayMs = c.uint32.decode({ start: 0, end: 4, buffer: req.value })
    if (delayMs > this.maxPingDelay) return
    const timer = setTimeout(() => {
      if (this.destroyed) return
      this._pendingTimers.delete(timer)
      req.sendReply(0, null, false, false)
    }, delayMs)
    this._pendingTimers.add(timer)
  }

  _onresponse(res, external) {
    this._addNodeFromNetwork(!external, res.from, res.to)
  }

  _ontimeout(req) {
    if (!req.to.id) return
    const node = this.table.get(req.to.id)
    if (node) this._removeNode(node)
  }

  _pingSome() {
    let cnt = this.io.inflight.length > 2 ? 3 : 5
    let oldest = this.nodes.oldest

    // tiny dht, pinged the bootstrap again
    if (!oldest) {
      this.refresh()
      return
    }

    // we've recently pinged the oldest one, so only trigger a couple of repings
    if (this._tick - oldest.pinged < RECENT_NODE) {
      cnt = 2
    }

    while (cnt--) {
      if (!oldest || this._tick === oldest.pinged) continue
      this._check(oldest)
      oldest = oldest.next
    }
  }

  _check(node) {
    node.pinged = this._tick

    const lastSeen = node.seen
    const onresponse = () => {
      this._checks--
      this._removeStaleNode(node, lastSeen)
    }
    const onerror = () => {
      this._checks--
      this._removeNode(node)
    }

    this._checks++
    this._request(
      { id: null, host: node.host, port: node.port },
      false,
      true,
      PING,
      null,
      null,
      null,
      onresponse,
      onerror
    )
  }

  _ontick() {
    const time = Date.now()

    if (time - this._lastTick > SLEEPING_INTERVAL && this.suspended === false) {
      this._onwakeup()
    } else {
      this._tick++
    }

    this._lastTick = time

    if (!this.bootstrapped || this.suspended) return

    if (this.adaptive && this.ephemeral && --this._stableTicks <= 0) {
      if (this._lastHost === this._nat.host) {
        // do not recheck the same network...
        this._stableTicks = MORE_STABLE_TICKS
      } else {
        this._updateNetworkState() // the promise returned here never fails so just ignore it
      }
    }

    if ((this._tick & 7) === 0) {
      this._pingSome()
    }

    if (
      ((this._tick & 63) === 0 && this.nodes.length < this.table.k) ||
      --this._refreshTicks <= 0
    ) {
      this.refresh()
    }

    this._downHintsSentPerTick = 0
    this.health.update()
  }

  async _updateNetworkState(onlyFirewall = false) {
    if (!this.ephemeral) return false
    if (onlyFirewall && !this.firewalled) return false

    const { host, port } = this._nat

    if (!onlyFirewall) {
      // remember what host we checked and reset the counter
      this._stableTicks = MORE_STABLE_TICKS
      this._lastHost = host
    }

    // check if we have a consistent host and port
    if (host === null || port === 0) {
      return false
    }

    const natSampler = this.firewalled ? new NatSampler() : this._nat

    // ask remote nodes to ping us on our server socket to see if we have the port open
    const firewalled = this.firewalled && (await this._checkIfFirewalled(natSampler))
    if (firewalled) return false

    this.firewalled = this.io.firewalled = false

    // incase it's called in parallel for some reason, or if our nat status somehow changed
    if (!this.ephemeral || host !== this._nat.host || port !== this._nat.port) return false
    // if the firewall probe returned a different host / non consistent port, bail as well
    if (natSampler.host !== host || natSampler.port === 0) return false

    const id = peer.id(natSampler.host, natSampler.port)

    if (!onlyFirewall) {
      this.ephemeral = this.io.ephemeral = false
    }

    if (natSampler !== this._nat) {
      const prevHost = this._nat.host
      const prevPort = this._nat.port

      this._nonePersistentSamples = []
      this._nat = natSampler

      if (prevHost !== this._nat.host || prevPort !== this._nat.port) {
        this.emit('nat-update', this._nat.host, this._nat.port)
      }
    }

    // TODO: we should make this a bit more defensive in terms of using more
    // resources to make sure that the new routing table contains as many alive nodes
    // as possible, vs blindly copying them over...

    // all good! copy over the old routing table to the new one
    if (!b4a.equals(this.table.id, id)) {
      const nodes = this.table.toArray()

      this.table = this.io.table = new Table(id)

      for (const node of nodes) {
        if (b4a.equals(node.id, id)) continue
        if (!this.table.add(node)) this.nodes.remove(node)
      }

      this.table.on('row', this._onrow)

      // we need to rebootstrap/refresh since we updated our id
      if (this.bootstrapped) this.refresh()
    }

    if (!this.ephemeral) {
      this.emit('persistent')
    }

    return true
  }

  async *_resolveBootstrapNodes() {
    for (let { host, port } of this.bootstrapNodes) {
      let doLookup = false

      if (host.indexOf('@') === -1) {
        doLookup = true
      } else {
        const [suggestedIP, fallbackHost] = host.split('@')
        try {
          await this.ping({ host: suggestedIP, port })
          host = suggestedIP
        } catch {
          host = fallbackHost
          doLookup = true
        }
      }

      if (doLookup) {
        try {
          host = UDX.isIPv4(host) ? host : (await this.udx.lookup(host, { family: 4 })).host
        } catch {
          continue
        }
      }

      yield {
        id: peer.id(host, port),
        host,
        port
      }
    }
  }

  async _addBootstrapNodes(nodes) {
    for await (const node of this._resolveBootstrapNodes()) {
      nodes.push(node)
    }
  }

  async _checkIfFirewalled(natSampler = new NatSampler()) {
    const nodes = []
    for (let node = this.nodes.latest; node && nodes.length < 5; node = node.prev) {
      nodes.push(node)
    }

    if (nodes.length < 5) await this._addBootstrapNodes(nodes)
    // if no nodes are available, including bootstrappers - bail
    if (nodes.length === 0) return true

    const hosts = new Set()
    const value = b4a.allocUnsafe(2)

    c.uint16.encode({ start: 0, end: 2, buffer: value }, this.io.serverSocket.address().port)

    // double check they actually came on the server socket...
    this.io.serverSocket.on('message', onmessage)

    const pongs = await requestAll(this, true, PING_NAT, value, nodes)

    let count = 0
    for (const res of pongs) {
      if (hosts.has(res.from.host)) {
        count++
        natSampler.add(res.to.host, res.to.port)
      }
    }

    this.io.serverSocket.removeListener('message', onmessage)

    // if we got no or very few replies, consider it a fluke
    if (count < (nodes.length >= 5 ? 3 : 1)) return true

    // check that the server socket has the same ip as the client socket
    if (natSampler.host === null || this._nat.host !== natSampler.host) return true

    // check that the local port of the server socket is the same as the remote port
    // TODO: we might want a flag to opt out of this heuristic for specific remapped port servers
    if (natSampler.port === 0 || natSampler.port !== this.io.serverSocket.address().port) {
      return true
    }

    return false

    function onmessage(_, { host }) {
      hosts.add(host)
    }
  }

  _backgroundQuery(target) {
    this._refreshTicks = REFRESH_TICKS

    const backgroundCon = Math.min(this.concurrency, Math.max(2, (this.concurrency / 8) | 0))
    const q = new Query(this, target, true, FIND_NODE, null, {
      concurrency: backgroundCon
    })

    q.on('data', () => {
      // yield to other traffic
      q.concurrency = this.io.inflight.length < 3 ? this.concurrency : backgroundCon
    })

    return q
  }

  // called by health
  _online() {
    if (this.online && !this.degraded) return
    this.online = true
    this.degraded = false
    this.emit('network-update')
  }

  // called by health
  _degraded() {
    if (this.degraded) return
    this.online = true
    this.degraded = true
    this.emit('network-update')
  }

  // called by health
  _offline() {
    if (!this.online) return
    this.online = false
    this.degraded = false
    this.emit('network-update')
  }
}

DHT.OK = 0
DHT.ERROR_UNKNOWN_COMMAND = UNKNOWN_COMMAND
DHT.ERROR_INVALID_TOKEN = INVALID_TOKEN

module.exports = DHT

function localIP(udx, family = 4) {
  let host = null

  for (const n of udx.networkInterfaces()) {
    if (n.family !== family || n.internal) continue

    // mac really likes en0, mb a better way but this shouldnt be bad anywhere so return now
    if (n.name === 'en0') return n.host

    // otherwise pick the first non internal host (let the loop continue in case we see en0)
    if (host === null) host = n.host
  }

  return host || (family === 4 ? '127.0.0.1' : '::1')
}

function parseNode(s) {
  if (typeof s === 'object') return s
  if (typeof s === 'number') return { host: '127.0.0.1', port: s }
  const [host, port] = s.split(':')
  if (!port) throw new Error('Bootstrap node format is host:port')

  return {
    host,
    port: Number(port)
  }
}

function randomBytes(n) {
  const b = b4a.alloc(n)
  sodium.randombytes_buf(b)
  return b
}

function randomOffset(n) {
  return n - ((Math.random() * 0.5 * n) | 0)
}

function requestAll(dht, internal, command, value, nodes) {
  let missing = nodes.length
  const replies = []

  return new Promise((resolve) => {
    for (const node of nodes) {
      const req = dht._request(
        node,
        false,
        internal,
        command,
        null,
        value,
        null,
        onsuccess,
        onerror
      )
      if (!req) return resolve(replies)
    }

    function onsuccess(res) {
      replies.push(res)
      if (--missing === 0) resolve(replies)
    }

    function onerror() {
      if (--missing === 0) resolve(replies)
    }
  })
}

function noop() {}
exports.PING = 0
exports.PING_NAT = 1
exports.FIND_NODE = 2
exports.DOWN_HINT = 3
exports.DELAYED_PING = 4
module.exports = class DHTError extends Error {
  constructor(msg, code, fn = DHTError) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'DHTError'
  }

  static UNKNOWN_COMMAND = 1
  static INVALID_TOKEN = 2

  static REQUEST_TIMEOUT(msg = 'Request timed out') {
    return new DHTError(msg, 'REQUEST_TIMEOUT', DHTError.REQUEST_TIMEOUT)
  }

  static REQUEST_DESTROYED(msg = 'Request destroyed') {
    return new DHTError(msg, 'REQUEST_DESTROYED', DHTError.REQUEST_DESTROYED)
  }

  static IO_SUSPENDED(msg = 'I/O suspended') {
    return new DHTError(msg, 'IO_SUSPENDED', DHTError.IO_SUSPENDED)
  }
}
const MAX_HEALTH_WINDOW = 4
const OFFLINE_THRESHOLD = 2
const IDLE_THRESHOLD = 4
const DEGRADED_TIMEOUT_RATE_THRESHOLD = 0.5

module.exports = class NetworkHealth {
  constructor(dht) {
    this._dht = dht
    this._window = []
    this._head = -1
    this._offlineTicks = 0
    this._degradedTicks = 0
    this._healthyTicks = 0
    this.online = true
    this.degraded = false
  }

  get oldest() {
    return this._window[this._tail]
  }

  get previous() {
    return this._window[(this._head - 1 + MAX_HEALTH_WINDOW) % MAX_HEALTH_WINDOW]
  }

  get newest() {
    return this._window[this._head]
  }

  get responses() {
    if (!this.newest || !this.previous) return 0
    return this.newest.responses - this.previous.responses
  }

  get timeouts() {
    if (!this.newest || !this.previous) return 0
    return this.newest.timeouts - this.previous.timeouts
  }

  get timeoutsRate() {
    if (this.timeouts === 0) return 0
    return this.timeouts / (this.responses + this.timeouts)
  }

  get cold() {
    return this._window.length < MAX_HEALTH_WINDOW
  }

  get idle() {
    return this.responses + this.timeouts < IDLE_THRESHOLD
  }

  get stats() {
    return {
      online: this.online,
      degraded: this.degraded,
      cold: this.cold,
      idle: this.idle,
      responses: this.responses,
      timeouts: this.timeouts,
      timeoutsRate: this.timeoutsRate
    }
  }

  get _tail() {
    return (this._head + 1) % MAX_HEALTH_WINDOW
  }

  reset() {
    this._window = []
    this._head = -1
    this._offlineTicks = 0
    this._degradedTicks = 0
    this._healthyTicks = 0
    this.online = true
    this.degraded = false
    this._dht._online()
  }

  update() {
    // update counters before dropping oldest
    if (this.oldest?.degraded) this._degradedTicks--
    else if (this.oldest?.degraded === false) this._healthyTicks--

    // move window
    this._head = this._tail
    this._window[this._head] = {
      responses: this._dht.stats.requests.responses,
      timeouts: this._dht.stats.requests.timeouts
    }

    // skip state changes
    if (this.cold || this.idle) return

    // update newest
    this.newest.offline = this.responses === 0
    this.newest.degraded =
      !this.newest.offline && this.timeoutsRate > DEGRADED_TIMEOUT_RATE_THRESHOLD

    // update counters
    if (this.newest.offline) this._offlineTicks++
    else {
      this._offlineTicks = 0
      if (this.newest.degraded) this._degradedTicks++
      else this._healthyTicks++
    }

    // check online/offline
    if (!this.newest.offline) this.online = true
    else if (this._offlineTicks >= OFFLINE_THRESHOLD) this.online = false

    // check degraded
    if (!this.online || this._healthyTicks === MAX_HEALTH_WINDOW) this.degraded = false
    else if (this._degradedTicks === MAX_HEALTH_WINDOW) this.degraded = true

    // fire events
    if (this.online && !this.degraded) this._dht._online()
    else if (this.degraded) this._dht._degraded()
    else this._dht._offline()
  }
}
const FIFO = require('fast-fifo')
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const b4a = require('b4a')
const AdaptiveTimeout = require('adaptive-timeout')
const peer = require('./peer')
const { INVALID_TOKEN, REQUEST_TIMEOUT, REQUEST_DESTROYED, IO_SUSPENDED } = require('./errors')

const VERSION = 0b11
const RESPONSE_ID = (0b0001 << 4) | VERSION
const REQUEST_ID = (0b0000 << 4) | VERSION
const EMPTY_ARRAY = []
const MAX_WINDOW = 80

module.exports = class IO {
  constructor(
    table,
    udx,
    {
      maxWindow = MAX_WINDOW,
      port = 0,
      host = '0.0.0.0',
      anyPort = true,
      firewalled = true,
      onrequest,
      onresponse = noop,
      ontimeout = noop,
      adaptiveTimeout
    } = {}
  ) {
    this.table = table
    this.udx = udx
    this.inflight = []
    this.clientSocket = null
    this.serverSocket = null
    this.firewalled = firewalled !== false
    this.ephemeral = true
    this.congestion = new CongestionWindow(maxWindow)
    this.networkInterfaces = udx.watchNetworkInterfaces()
    this.suspended = false

    this.stats = {
      requests: {
        active: 0,
        total: 0,
        responses: 0,
        timeouts: 0,
        retries: 0
      },
      commands: [
        { tx: 0, rx: 0 }, // tx = transmitted, rx = received
        { tx: 0, rx: 0 },
        { tx: 0, rx: 0 },
        { tx: 0, rx: 0 }
      ]
    }

    this.onrequest = onrequest
    this.onresponse = onresponse
    this.ontimeout = ontimeout

    this._pending = new FIFO()
    this._rotateSecrets = 10
    this._tid = (Math.random() * 65536) | 0
    this._secrets = null
    this._drainInterval = null
    this._destroying = null
    this._binding = null

    // port can be a number or a range [start, to]
    this.portRange = port.length ? port : port === 0 ? [0, 0] : [port, port + 5]

    this._host = host
    this._anyPort = anyPort !== false
    this._boundServerPort = 0
    this._boundClientPort = 0

    this._adt = adaptiveTimeout ? new AdaptiveTimeout(adaptiveTimeout) : null
  }

  static DEFAULT_MAX_WINDOW = MAX_WINDOW

  onmessage(socket, buffer, { host, port }) {
    if (buffer.byteLength < 2 || !(port > 0 && port < 65536) || this.suspended === true) return

    const from = { id: null, host, port }
    const state = { start: 1, end: buffer.byteLength, buffer }
    const expectedSocket = this.firewalled ? this.clientSocket : this.serverSocket
    const external = socket !== expectedSocket

    if (buffer[0] === REQUEST_ID) {
      const req = Request.decode(this, socket, from, state)
      if (req === null) return
      if (
        req.token !== null &&
        !b4a.equals(req.token, this.token(req.from, 1)) &&
        !b4a.equals(req.token, this.token(req.from, 0))
      ) {
        req.error(INVALID_TOKEN, { token: true })
        return
      }
      this.onrequest(req, external)
      return
    }

    if (buffer[0] === RESPONSE_ID) {
      const res = decodeReply(from, state)
      if (res === null) return

      for (let i = 0; i < this.inflight.length; i++) {
        const req = this.inflight[i]
        if (req.tid !== res.tid) continue

        res.rtt = Date.now() - req._timestamp

        if (this._adt && req.sent <= 2) {
          this._adt.put(`${req.to.host}:${req.to.port}`, res.rtt)
        }

        if (i === this.inflight.length - 1) this.inflight.pop()
        else this.inflight[i] = this.inflight.pop()

        if (req.session) req.session._detach(req)

        // TODO: Auto retry here if errors.INVALID_TOKEN is returned?

        if (req._timeout) {
          clearTimeout(req._timeout)
          req._timeout = null
        }

        this.congestion.recv()

        if (req.internal && req.command < this.stats.commands.length) {
          this.stats.commands[req.command].rx++
        }

        this.stats.requests.active--
        this.stats.requests.responses++

        this.onresponse(res, external)
        req.onresponse(res, req)
        break
      }
    }
  }

  token(addr, i) {
    if (this._secrets === null) {
      const buf = b4a.alloc(64)
      this._secrets = [buf.subarray(0, 32), buf.subarray(32, 64)]
      sodium.randombytes_buf(this._secrets[0])
      sodium.randombytes_buf(this._secrets[1])
    }

    const token = b4a.allocUnsafe(32)
    sodium.crypto_generichash(token, b4a.from(addr.host), this._secrets[i])
    return token
  }

  async destroy() {
    if (this._destroying) return this._destroying
    this._destroying = this._destroy()
    return this._destroying
  }

  async _destroy() {
    // simplifies timing to await the bind here also, although it might be unneeded
    await this.bind()
    await this._clear(false)
  }

  async _clear(suspended) {
    if (this._drainInterval) {
      clearInterval(this._drainInterval)
      this._drainInterval = null
    }

    while (this.inflight.length) {
      const req = this.inflight.pop()
      if (req._timeout) clearTimeout(req._timeout)
      req._timeout = null
      req.destroyed = true

      if (req.session) req.session._detach(req)

      this.congestion.recv()
      this.stats.requests.active--

      req.onerror(suspended ? IO_SUSPENDED() : REQUEST_DESTROYED(), req)
    }

    await Promise.allSettled([this.serverSocket.close(), this.clientSocket.close()])

    this.networkInterfaces.destroy()
  }

  async suspend() {
    this.suspended = true
    await this._clear(true)

    this.congestion.clear()

    if (this._drainInterval) {
      clearInterval(this._drainInterval)
      this._drainInterval = null
    }
  }

  async _rebind(binding) {
    if (binding) await binding
    if (this._destroying) return this._destroying
    await this._bindSockets()
    this.networkInterfaces = this.udx.watchNetworkInterfaces()
  }

  resume() {
    this.suspended = false
    const binding = this._binding
    this._binding = this._rebind(binding)
    return this._binding
  }

  bind() {
    if (this._binding) return this._binding
    this._binding = this._bindSockets()
    return this._binding
  }

  async _bindSockets() {
    const serverSocket = this.udx.createSocket()

    const candidatePorts = []

    // Retrying previous port always has precedence
    if (this._boundServerPort) candidatePorts.push(this._boundServerPort)

    for (let i = this.portRange[0]; i < this.portRange[1]; i++) candidatePorts.push(i)

    for (const port of candidatePorts) {
      if (serverSocket.bound) break

      try {
        serverSocket.bind(port, this._host)
      } catch (err) {
        if (!this._anyPort) {
          await serverSocket.close()
          throw err
        }
      }
    }

    if (!serverSocket.bound) {
      try {
        serverSocket.bind(0, this._host)
      } catch (err) {
        await serverSocket.close()
        throw err
      }
    }

    const clientSocket = this.udx.createSocket()

    try {
      clientSocket.bind(this._boundClientPort || 0, this._host)
    } catch {
      try {
        clientSocket.bind(0, this._host)
      } catch (err) {
        await serverSocket.close()
        await clientSocket.close()
        throw err
      }
    }

    this._boundServerPort = serverSocket.address().port
    this._boundClientPort = clientSocket.address().port

    this.clientSocket = clientSocket
    this.serverSocket = serverSocket

    this.serverSocket.on('message', this.onmessage.bind(this, this.serverSocket))
    this.clientSocket.on('message', this.onmessage.bind(this, this.clientSocket))

    if (this._drainInterval === null) {
      this._drainInterval = setInterval(this._drain.bind(this), 750)
      if (this._drainInterval.unref) this._drainInterval.unref()
    }

    for (const req of this.inflight) {
      if (!req.socket) req.socket = this.firewalled ? this.clientSocket : this.serverSocket
      req.sent = 0
      req.send(false)
    }
  }

  _drain() {
    if (this._secrets !== null && --this._rotateSecrets === 0) {
      this._rotateSecrets = 10
      const tmp = this._secrets[0]
      this._secrets[0] = this._secrets[1]
      this._secrets[1] = tmp
      sodium.crypto_generichash(tmp, tmp)
    }

    this.congestion.drain()

    while (!this.congestion.isFull()) {
      const p = this._pending.shift()
      if (p === undefined) return
      p._sendNow()
    }
  }

  createRequest(to, token, internal, command, target, value, session, ttl) {
    if (this._destroying !== null) return null

    if (this._tid === 65536) this._tid = 0

    const tid = this._tid++
    const socket = this.firewalled ? this.clientSocket : this.serverSocket

    const req = new Request(
      this,
      socket,
      tid,
      null,
      to,
      token,
      internal,
      command,
      target,
      value,
      session,
      ttl || 0
    )
    this.inflight.push(req)
    if (session) session._attach(req)

    if (internal && command < this.stats.commands.length) {
      this.stats.commands[command].tx++
    }

    this.stats.requests.active++
    this.stats.requests.total++

    return req
  }
}

class Request {
  constructor(io, socket, tid, from, to, token, internal, command, target, value, session, ttl) {
    this.socket = socket
    this.tid = tid
    this.from = from
    this.to = to
    this.token = token
    this.command = command
    this.target = target
    this.value = value
    this.internal = internal
    this.session = session
    this.ttl = ttl
    this.index = -1
    this.sent = 0
    this.retries = 3
    this.destroyed = false
    this.timeout = 0

    this.oncycle = noop
    this.onerror = noop
    this.onresponse = noop

    this._buffer = null
    this._io = io
    this._timeout = null
    this._timestamp = Date.now()
  }

  static decode(io, socket, from, state) {
    try {
      const flags = c.uint.decode(state)
      const tid = c.uint16.decode(state)
      const to = peer.ipv4.decode(state)
      const id = flags & 1 ? c.fixed32.decode(state) : null
      const token = flags & 2 ? c.fixed32.decode(state) : null
      const internal = (flags & 4) !== 0
      const command = c.uint.decode(state)
      const target = flags & 8 ? c.fixed32.decode(state) : null
      const value = flags & 16 ? c.buffer.decode(state) : null

      if (id !== null) from.id = validateId(id, from)

      return new Request(
        io,
        socket,
        tid,
        from,
        to,
        token,
        internal,
        command,
        target,
        value,
        null,
        0
      )
    } catch {
      return null
    }
  }

  reply(value, opts = {}) {
    const socket = opts.socket || this.socket
    const to = opts.to || this.from
    this._sendReply(0, value || null, opts.token !== false, opts.closerNodes !== false, to, socket)
  }

  error(code, opts = {}) {
    const socket = opts.socket || this.socket
    const to = opts.to || this.from
    this._sendReply(code, null, opts.token === true, opts.closerNodes !== false, to, socket)
  }

  relay(value, to, opts) {
    const socket = (opts && opts.socket) || this.socket
    const buffer = this._encodeRequest(null, value, to, socket)
    socket.trySend(buffer, to.port, to.host, this.ttl)
  }

  send(force = false) {
    if (this.destroyed) return

    if (this.socket === null) return
    if (this._buffer === null) {
      this._buffer = this._encodeRequest(this.token, this.value, this.to, this.socket)
    }

    if (!force && this._io.congestion.isFull()) {
      this._io._pending.push(this)
      return
    }

    this._sendNow()
  }

  sendReply(error, value, token, hasCloserNodes) {
    this._sendReply(error, value, token, hasCloserNodes, this.from, this.socket, null)
  }

  _sendNow() {
    if (this.destroyed) return
    this.sent++
    this._io.congestion.send()
    this.socket.trySend(this._buffer, this.to.port, this.to.host, this.ttl)
    if (this._timeout) clearTimeout(this._timeout)
    const value =
      this.timeout || this._io._adt?.get(`${this.to.host}:${this.to.port}`, this.sent) || 1000
    this._timeout = setTimeout(oncycle, value, this)
  }

  destroy(err) {
    if (this.destroyed) return
    this.destroyed = true

    if (this._timeout) {
      clearTimeout(this._timeout)
      this._timeout = null
    }

    const i = this._io.inflight.indexOf(this)
    if (i === -1) return

    if (i === this._io.inflight.length - 1) this._io.inflight.pop()
    else this._io.inflight[i] = this._io.inflight.pop()

    if (this.session) this.session._detach(this)

    this._io.stats.requests.active--
    this._io.congestion.recv()

    this.onerror(err || REQUEST_DESTROYED(), this)
  }

  _sendReply(error, value, token, hasCloserNodes, from, socket) {
    if (socket === null || this.destroyed) return

    const id = this._io.ephemeral === false && socket === this._io.serverSocket
    const closerNodes =
      this.target !== null && hasCloserNodes ? this._io.table.closest(this.target) : EMPTY_ARRAY
    const state = { start: 0, end: 1 + 1 + 6 + 2, buffer: null } // (type | version) + flags + to + tid

    if (id) state.end += 32
    if (token) state.end += 32
    if (closerNodes.length > 0) peer.ipv4Array.preencode(state, closerNodes)
    if (error > 0) c.uint.preencode(state, error)
    if (value) c.buffer.preencode(state, value)

    state.buffer = b4a.allocUnsafe(state.end)
    state.buffer[state.start++] = RESPONSE_ID
    state.buffer[state.start++] =
      (id ? 1 : 0) |
      (token ? 2 : 0) |
      (closerNodes.length > 0 ? 4 : 0) |
      (error > 0 ? 8 : 0) |
      (value ? 16 : 0)

    c.uint16.encode(state, this.tid)
    peer.ipv4.encode(state, from)

    if (id) c.fixed32.encode(state, this._io.table.id)
    if (token) c.fixed32.encode(state, this._io.token(from, 1))
    if (closerNodes.length > 0) peer.ipv4Array.encode(state, closerNodes)
    if (error > 0) c.uint.encode(state, error)
    if (value) c.buffer.encode(state, value)

    socket.trySend(state.buffer, from.port, from.host, this.ttl)
  }

  _encodeRequest(token, value, to, socket) {
    const id = this._io.ephemeral === false && socket === this._io.serverSocket
    const state = { start: 0, end: 1 + 1 + 6 + 2, buffer: null } // (type | version) + flags + to + tid

    if (id) state.end += 32
    if (token) state.end += 32

    c.uint.preencode(state, this.command)

    if (this.target) state.end += 32
    if (value) c.buffer.preencode(state, value)

    state.buffer = b4a.allocUnsafe(state.end)
    state.buffer[state.start++] = REQUEST_ID
    state.buffer[state.start++] =
      (id ? 1 : 0) |
      (token ? 2 : 0) |
      (this.internal ? 4 : 0) |
      (this.target ? 8 : 0) |
      (value ? 16 : 0)

    c.uint16.encode(state, this.tid)
    peer.ipv4.encode(state, to)

    if (id) c.fixed32.encode(state, this._io.table.id)
    if (token) c.fixed32.encode(state, token)

    c.uint.encode(state, this.command)

    if (this.target) c.fixed32.encode(state, this.target)
    if (value) c.buffer.encode(state, value)

    return state.buffer
  }
}

class CongestionWindow {
  constructor(maxWindow) {
    this._i = 0
    this._total = 0
    this._window = [0, 0, 0, 0]
    this._maxWindow = maxWindow
  }

  clear() {
    this._i = 0
    this._total = 0
    this._window = [0, 0, 0, 0]
  }

  isFull() {
    return this._total >= 2 * this._maxWindow || this._window[this._i] >= this._maxWindow
  }

  recv() {
    if (this._window[this._i] > 0) {
      this._window[this._i]--
      this._total--
    }
  }

  send() {
    this._total++
    this._window[this._i]++
  }

  drain() {
    this._i = (this._i + 1) & 3
    this._total -= this._window[this._i]
    this._window[this._i] = 0 // clear oldest
  }
}

function noop() {}

function oncycle(req) {
  req._timeout = null
  req.oncycle(req)
  if (req.sent > req.retries) {
    req._io.stats.requests.timeouts++
    req.destroy(REQUEST_TIMEOUT())
    req._io.ontimeout(req)
  } else {
    req._io.stats.requests.retries++
    req.send()
  }
}

function decodeReply(from, state) {
  try {
    const flags = c.uint.decode(state)
    const tid = c.uint16.decode(state)
    const to = peer.ipv4.decode(state)
    const id = flags & 1 ? c.fixed32.decode(state) : null
    const token = flags & 2 ? c.fixed32.decode(state) : null
    const closerNodes = flags & 4 ? peer.ipv4Array.decode(state) : null
    const error = flags & 8 ? c.uint.decode(state) : 0
    const value = flags & 16 ? c.buffer.decode(state) : null

    if (id !== null) from.id = validateId(id, from)

    return { tid, rtt: 0, from, to, token, closerNodes, error, value }
  } catch {
    return null
  }
}

function validateId(id, from) {
  const expected = peer.id(from.host, from.port)
  return b4a.equals(expected, id) ? expected : null
}
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const net = require('compact-encoding-net')
const b4a = require('b4a')

const ipv4 = {
  ...net.ipv4Address,
  decode(state) {
    const ip = net.ipv4Address.decode(state)
    return {
      id: null, // populated by the callee
      host: ip.host,
      port: ip.port
    }
  }
}

module.exports = { id, ipv4, ipv4Array: c.array(ipv4) }

function id(host, port, out = b4a.allocUnsafeSlow(32)) {
  const addr = out.subarray(0, 6)
  ipv4.encode({ start: 0, end: 6, buffer: addr }, { host, port })
  sodium.crypto_generichash(out, addr)
  return out
}
const { Readable, getStreamError } = require('streamx')
const b4a = require('b4a')
const peer = require('./peer')
const { DOWN_HINT } = require('./commands')

const DONE = []
const DOWN = []

module.exports = class Query extends Readable {
  constructor(dht, target, internal, command, value, opts = {}) {
    super()

    dht.stats.queries.total++
    dht.stats.queries.active++

    this.force = !!opts.force
    this.dht = dht
    this.k = this.dht.table.k
    this.target = target
    this.internal = internal
    this.command = command
    this.value = value
    this.errors = 0
    this.successes = 0
    this.concurrency = opts.concurrency || this.dht.concurrency
    this.inflight = 0
    this.map = opts.map || defaultMap
    this.retries =
      opts.retries === 0 ? 0 : opts.retries || (this.internal && command === DOWN_HINT ? 3 : 5)
    this.closestReplies = []

    this._slow = 0
    this._slowdown = false
    this._seen = new Map()
    this._pending = []
    this._fromTable = false
    this._commit = opts.commit === true ? autoCommit : opts.commit || null
    this._commiting = false
    this._session = opts.session || dht.session()
    this._autoDestroySession = !opts.session
    this._onlyClosestNodes = false

    this._onvisitbound = this._onvisit.bind(this)
    this._onerrorbound = this._onerror.bind(this)
    this._oncyclebound = this._oncycle.bind(this)

    const nodes = opts.nodes || opts.closestNodes
    const replies = opts.replies || opts.closestReplies

    // add them reverse as we pop below
    if (nodes) {
      for (let i = nodes.length - 1; i >= 0; i--) {
        const node = nodes[i]
        this._addPending(
          {
            id: node.id || peer.id(node.host, node.port),
            host: node.host,
            port: node.port
          },
          null
        )
      }
    } else if (replies) {
      for (let i = replies.length - 1; i >= 0; i--) {
        this._addPending(replies[i].from, null)
      }
    }

    if (opts.onlyClosestNodes) this._onlyClosestNodes = true
  }

  get closestNodes() {
    const nodes = new Array(this.closestReplies.length)

    for (let i = 0; i < nodes.length; i++) {
      nodes[i] = this.closestReplies[i].from
    }

    return nodes
  }

  finished() {
    return new Promise((resolve, reject) => {
      if (this.destroyed) {
        const error = getStreamError(this)
        if (error) reject(error)
        else resolve()
        return
      }

      const self = this
      let error = null

      this.resume()
      this.on('error', onerror)
      this.on('close', onclose)

      function onclose() {
        self.removeListener('error', onerror)
        self.removeListener('close', onclose)
        if (error) reject(error)
        else resolve()
      }

      function onerror(err) {
        error = err
      }
    })
  }

  _addFromTable() {
    if (this._pending.length >= this.k) return
    this._fromTable = true

    const closest = this.dht.table.closest(this.target, this.k - this._pending.length)

    for (const node of closest) {
      this._addPending({ id: node.id, host: node.host, port: node.port }, null)
    }
  }

  async _open(cb) {
    this._addFromTable()
    if (this._pending.length >= this.k) return cb(null)

    for await (const node of this.dht._resolveBootstrapNodes()) {
      this._addPending(node, null)
    }

    cb(null)
  }

  _isCloser(id) {
    return (
      this.closestReplies.length < this.k ||
      this._compare(id, this.closestReplies[this.closestReplies.length - 1].from.id) < 0
    )
  }

  _addPending(node, ref) {
    if (this._onlyClosestNodes) return false

    const addr = node.host + ':' + node.port
    const refs = this._seen.get(addr)
    const isCloser = this._isCloser(node.id)

    if (refs === DONE) {
      return isCloser
    }

    if (refs === DOWN) {
      if (ref) this._downHint(ref, node)
      return isCloser
    }

    if (refs) {
      if (ref !== null) refs.push(ref)
      return isCloser
    }

    if (!isCloser) {
      return false
    }

    this._seen.set(addr, ref === null ? [] : [ref])
    this._pending.push(node)

    return true
  }

  _read(cb) {
    this._readMore()
    cb(null)
  }

  _readMore() {
    if (this.destroying || this._commiting) return

    const concurrency = (this._slowdown ? 3 : this.concurrency) + this._slow

    while (this.inflight < concurrency && this._pending.length > 0) {
      const next = this._pending.pop()
      if (next && next.id && !this._isCloser(next.id)) continue
      this._visit(next)
    }

    // if reusing closest nodes, slow down after the first readMore tick to allow
    // the closest node a chance to reply before going broad to question more
    if (!this._fromTable && this.successes === 0 && this.errors === 0) {
      this._slowdown = true
    }

    if (this._pending.length > 0) return

    // if no inflight OR all the queries we are waiting on are marked as slow and we have a full result.
    if (
      this.inflight === 0 ||
      (this._slow === this.inflight && this.closestReplies.length >= this.k)
    ) {
      // if more than 3/4 failed and we only used cached nodes, try again from the routing table
      if (!this._fromTable && this.successes < this.k / 4) {
        this._addFromTable()
        this._readMore()
        return
      }

      this._flush()
    }
  }

  _flush() {
    if (this._commiting) return
    this._commiting = true

    if (this._commit === null) {
      this.push(null)
      return
    }

    const p = []
    for (const m of this.closestReplies) p.push(this._commit(m, this.dht, this))
    this._endAfterCommit(p)
  }

  _endAfterCommit(ps) {
    if (!ps.length) {
      this.destroy(new Error('Too few nodes responded'))
      return
    }

    const self = this

    let pending = ps.length
    let success = 0

    for (const p of ps) p.then(ondone, onerror)

    function ondone() {
      success++
      if (--pending === 0) self.push(null)
    }

    function onerror(err) {
      if (--pending > 0) return
      if (success) self.push(null)
      else self.destroy(err)
    }
  }

  _dec(req) {
    if (req.oncycle === noop) {
      this._slow--
    } else {
      req.oncycle = noop
    }
    this.inflight--
  }

  _onvisit(m, req) {
    this._dec(req)

    const addr = req.to.host + ':' + req.to.port
    this._seen.set(addr, DONE)

    if (this._commiting) return

    if (m.error === 0) this.successes++
    else this.errors++

    if (m.error === 0 && m.from.id !== null && this._isCloser(m.from.id)) this._pushClosest(m)

    if (m.closerNodes !== null) {
      for (const node of m.closerNodes) {
        node.id = peer.id(node.host, node.port)
        if (this.dht._filterNode !== null && !this.dht._filterNode(node)) continue
        if (b4a.equals(node.id, this.dht.table.id)) continue
        // TODO: we could continue here instead of breaking to ensure that one of the nodes in the closer list
        // is later marked as DOWN that we gossip that back
        if (!this._addPending(node, m.from)) break
      }
    }

    if (!this._fromTable && this.successes + this.errors >= this.concurrency) {
      this._slowdown = false
    }

    if (m.error !== 0) {
      this._readMore()
      return
    }

    const data = this.map(m)
    if (!data || this.push(data) !== false) {
      this._readMore()
    }
  }

  _onerror(err, req) {
    const addr = req.to.host + ':' + req.to.port
    const refs = this._seen.get(addr)

    if (err.code === 'REQUEST_TIMEOUT') {
      this._seen.set(addr, DOWN)
      for (const node of refs) this._downHint(node, req.to)
    }

    this._dec(req)
    this.errors++
    this._readMore()
  }

  _oncycle(req) {
    req.oncycle = noop
    this._slow++
    this._readMore()
  }

  _downHint(node, down) {
    // Check rate limit
    if (
      this.dht._downHintsRateLimit !== -1 &&
      this.dht._downHintsSentPerTick >= this.dht._downHintsRateLimit
    ) {
      return null
    }

    this.dht._downHintsSentPerTick++

    const state = { start: 0, end: 6, buffer: b4a.allocUnsafe(6) }
    peer.ipv4.encode(state, down)
    this.dht._request(node, false, true, DOWN_HINT, null, state.buffer, this._session, noop, noop)
  }

  _pushClosest(m) {
    this.closestReplies.push(m)
    for (let i = this.closestReplies.length - 2; i >= 0; i--) {
      const prev = this.closestReplies[i]
      const cmp = this._compare(prev.from.id, m.from.id)
      // if sorted, done!
      if (cmp < 0) break
      // if dup, splice it out (rare)
      if (cmp === 0) {
        this.closestReplies.splice(i + 1, 1)
        break
      }
      // swap and continue down
      this.closestReplies[i + 1] = prev
      this.closestReplies[i] = m
    }
    if (this.closestReplies.length > this.k) this.closestReplies.pop()
  }

  _compare(a, b) {
    for (let i = 0; i < a.length; i++) {
      if (a[i] === b[i]) continue
      const t = this.target[i]
      return (t ^ a[i]) - (t ^ b[i])
    }
    return 0
  }

  _visit(to) {
    this.inflight++

    const req = this.dht._request(
      to,
      this.force,
      this.internal,
      this.command,
      this.target,
      this.value,
      this._session,
      this._onvisitbound,
      this._onerrorbound
    )
    if (req === null) {
      this.destroy(new Error('Node was destroyed'))
      return
    }
    req.retries = this.retries
    req.oncycle = this._oncyclebound
    if (this.force) req.retries = 0
  }

  _destroy(cb) {
    this.dht.stats.queries.active--
    if (this._autoDestroySession) this._session.destroy()
    cb(null)
  }
}

function autoCommit(reply, dht, query) {
  if (!reply.token) return Promise.reject(new Error('No token received for closest node'))
  return dht.request(
    {
      token: reply.token,
      target: query.target,
      command: query.command,
      value: query.value
    },
    reply.from
  )
}

function defaultMap(m) {
  return m
}

function noop() {}
module.exports = class Session {
  constructor(dht) {
    this.dht = dht
    this.inflight = []
  }

  _attach(req) {
    req.index = this.inflight.push(req) - 1
  }

  _detach(req) {
    const i = req.index
    if (i === -1) return
    req.index = -1

    if (i === this.inflight.length - 1) this.inflight.pop()
    else {
      const req = (this.inflight[i] = this.inflight.pop())
      req.index = i
    }
  }

  query({ target, command, value }, opts = {}) {
    return this.dht.query({ target, command, value }, { ...opts, session: this })
  }

  request({ token, command, target, value }, { host, port }, opts = {}) {
    return this.dht.request(
      { token, command, target, value },
      { host, port },
      { ...opts, session: this }
    )
  }

  ping({ host, port }, opts = {}) {
    return this.dht.ping({ host, port }, { ...opts, session: this })
  }

  destroy(err) {
    while (this.inflight.length) {
      const req = this.inflight[0]
      // prevent destroyed requests from contributing to congestion counts
      this.dht.io.congestion.recv()
      req.destroy(err)
    }
  }
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return uint24.decode(state) + 0x1000000 * uint32.decode(state)
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return uint32.decode(state) + 0x100000000 * uint32.decode(state)
  }
})

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "2.19.2",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    if (b.byteLength === 0) return null
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "dht-rpc",
  "version": "6.26.4",
  "description": "Make RPC calls over a Kademlia based DHT",
  "main": "index.js",
  "files": [
    "index.js",
    "lib/*.js"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "dependencies": {
    "adaptive-timeout": "^1.0.1",
    "b4a": "^1.6.1",
    "bare-events": "^2.2.0",
    "compact-encoding": "^2.11.0",
    "compact-encoding-net": "^1.2.0",
    "fast-fifo": "^1.1.0",
    "kademlia-routing-table": "^1.0.1",
    "nat-sampler": "^1.0.1",
    "sodium-universal": "^5.0.0",
    "streamx": "^2.13.2",
    "time-ordered-set": "^2.0.0",
    "udx-native": "^1.5.3"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "test-suspend": "^1.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "test": "npm run test:node && npm run test:bare",
    "test:bare": "brittle-bare --coverage test.js",
    "lint": "prettier --check . && lunte",
    "test:node": "brittle-node --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/dht-rpc.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/dht-rpc/issues"
  },
  "homepage": "https://github.com/holepunchto/dht-rpc#"
}
module.exports = require('bare-events')
{
  "name": "events-universal",
  "version": "1.0.1",
  "description": "Universal wrapper for the Node.js events module",
  "exports": {
    "./package": "./package.json",
    ".": {
      "bare": "./bare.js",
      "react-native": "./react-native.js",
      "default": "./default.js"
    }
  },
  "files": [
    "index.js",
    "default.js",
    "bare.js",
    "react-native.js"
  ],
  "scripts": {
    "test": "prettier . --check"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/events-universal.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/events-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/events-universal#readme",
  "dependencies": {
    "bare-events": "^2.7.0"
  },
  "devDependencies": {
    "prettier": "^3.4.2",
    "prettier-config-holepunch": "^1.0.0"
  }
}
module.exports = class FixedFIFO {
  constructor (hwm) {
    if (!(hwm > 0) || ((hwm - 1) & hwm) !== 0) throw new Error('Max size for a FixedFIFO should be a power of two')
    this.buffer = new Array(hwm)
    this.mask = hwm - 1
    this.top = 0
    this.btm = 0
    this.next = null
  }

  clear () {
    this.top = this.btm = 0
    this.next = null
    this.buffer.fill(undefined)
  }

  push (data) {
    if (this.buffer[this.top] !== undefined) return false
    this.buffer[this.top] = data
    this.top = (this.top + 1) & this.mask
    return true
  }

  shift () {
    const last = this.buffer[this.btm]
    if (last === undefined) return undefined
    this.buffer[this.btm] = undefined
    this.btm = (this.btm + 1) & this.mask
    return last
  }

  peek () {
    return this.buffer[this.btm]
  }

  isEmpty () {
    return this.buffer[this.btm] === undefined
  }
}
const FixedFIFO = require('./fixed-size')

module.exports = class FastFIFO {
  constructor (hwm) {
    this.hwm = hwm || 16
    this.head = new FixedFIFO(this.hwm)
    this.tail = this.head
    this.length = 0
  }

  clear () {
    this.head = this.tail
    this.head.clear()
    this.length = 0
  }

  push (val) {
    this.length++
    if (!this.head.push(val)) {
      const prev = this.head
      this.head = prev.next = new FixedFIFO(2 * this.head.buffer.length)
      this.head.push(val)
    }
  }

  shift () {
    if (this.length !== 0) this.length--
    const val = this.tail.shift()
    if (val === undefined && this.tail.next) {
      const next = this.tail.next
      this.tail.next = null
      this.tail = next
      return this.tail.shift()
    }

    return val
  }

  peek () {
    const val = this.tail.peek()
    if (val === undefined && this.tail.next) return this.tail.next.peek()
    return val
  }

  isEmpty () {
    return this.length === 0
  }
}
{
  "name": "fast-fifo",
  "version": "1.3.2",
  "description": "A fast fifo implementation similar to the one powering nextTick in Node.js core",
  "main": "index.js",
  "files": [
    "./index.js",
    "./fixed-size.js"
  ],
  "dependencies": {},
  "devDependencies": {
    "standard": "^17.1.0",
    "brittle": "^3.3.2"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/fast-fifo.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/fast-fifo/issues"
  },
  "homepage": "https://github.com/mafintosh/fast-fifo"
}
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const b4a = require('b4a')

// https://en.wikipedia.org/wiki/Merkle_tree#Second_preimage_attack
const LEAF_TYPE = b4a.from([0])
const PARENT_TYPE = b4a.from([1])
const ROOT_TYPE = b4a.from([2])

const HYPERCORE = b4a.from('hypercore')

exports.keyPair = function (seed) {
  // key pairs might stay around for a while, so better not to use a default slab to avoid retaining it completely
  const slab = b4a.allocUnsafeSlow(sodium.crypto_sign_PUBLICKEYBYTES + sodium.crypto_sign_SECRETKEYBYTES)
  const publicKey = slab.subarray(0, sodium.crypto_sign_PUBLICKEYBYTES)
  const secretKey = slab.subarray(sodium.crypto_sign_PUBLICKEYBYTES)

  if (seed) sodium.crypto_sign_seed_keypair(publicKey, secretKey, seed)
  else sodium.crypto_sign_keypair(publicKey, secretKey)

  return {
    publicKey,
    secretKey
  }
}

exports.validateKeyPair = function (keyPair) {
  const pk = b4a.allocUnsafe(sodium.crypto_sign_PUBLICKEYBYTES)
  sodium.crypto_sign_ed25519_sk_to_pk(pk, keyPair.secretKey)
  return b4a.equals(pk, keyPair.publicKey)
}

exports.sign = function (message, secretKey) {
  // Dedicated slab for the signature, to avoid retaining unneeded mem and for security
  const signature = b4a.allocUnsafeSlow(sodium.crypto_sign_BYTES)
  sodium.crypto_sign_detached(signature, message, secretKey)
  return signature
}

exports.verify = function (message, signature, publicKey) {
  if (signature.byteLength !== sodium.crypto_sign_BYTES) return false
  if (publicKey.byteLength !== sodium.crypto_sign_PUBLICKEYBYTES) return false
  return sodium.crypto_sign_verify_detached(signature, message, publicKey)
}

exports.encrypt = function (message, publicKey) {
  const ciphertext = b4a.alloc(message.byteLength + sodium.crypto_box_SEALBYTES)
  sodium.crypto_box_seal(ciphertext, message, publicKey)
  return ciphertext
}

exports.decrypt = function (ciphertext, keyPair) {
  if (ciphertext.byteLength < sodium.crypto_box_SEALBYTES) return null

  const plaintext = b4a.alloc(ciphertext.byteLength - sodium.crypto_box_SEALBYTES)

  if (!sodium.crypto_box_seal_open(plaintext, ciphertext, keyPair.publicKey, keyPair.secretKey)) {
    return null
  }

  return plaintext
}

exports.encryptionKeyPair = function (seed) {
  const publicKey = b4a.alloc(sodium.crypto_box_PUBLICKEYBYTES)
  const secretKey = b4a.alloc(sodium.crypto_box_SECRETKEYBYTES)

  if (seed) {
    sodium.crypto_box_seed_keypair(publicKey, secretKey, seed)
  } else {
    sodium.crypto_box_keypair(publicKey, secretKey)
  }

  return {
    publicKey,
    secretKey
  }
}

exports.data = function (data) {
  const out = b4a.allocUnsafe(32)

  sodium.crypto_generichash_batch(out, [
    LEAF_TYPE,
    c.encode(c.uint64, data.byteLength),
    data
  ])

  return out
}

exports.parent = function (a, b) {
  if (a.index > b.index) {
    const tmp = a
    a = b
    b = tmp
  }

  const out = b4a.allocUnsafe(32)

  sodium.crypto_generichash_batch(out, [
    PARENT_TYPE,
    c.encode(c.uint64, a.size + b.size),
    a.hash,
    b.hash
  ])

  return out
}

exports.tree = function (roots, out) {
  const buffers = new Array(3 * roots.length + 1)
  let j = 0

  buffers[j++] = ROOT_TYPE

  for (let i = 0; i < roots.length; i++) {
    const r = roots[i]
    buffers[j++] = r.hash
    buffers[j++] = c.encode(c.uint64, r.index)
    buffers[j++] = c.encode(c.uint64, r.size)
  }

  if (!out) out = b4a.allocUnsafe(32)
  sodium.crypto_generichash_batch(out, buffers)
  return out
}

exports.hash = function (data, out) {
  if (!out) out = b4a.allocUnsafe(32)
  if (!Array.isArray(data)) data = [data]

  sodium.crypto_generichash_batch(out, data)

  return out
}

exports.randomBytes = function (n) {
  const buf = b4a.allocUnsafe(n)
  sodium.randombytes_buf(buf)
  return buf
}

exports.discoveryKey = function (key) {
  if (!key || key.byteLength !== 32) throw new Error('Must pass a 32 byte buffer')
  // Discovery keys might stay around for a while, so better not to use slab memory (for better gc)
  const digest = b4a.allocUnsafeSlow(32)
  sodium.crypto_generichash(digest, HYPERCORE, key)
  return digest
}

if (sodium.sodium_free) {
  exports.free = function (secureBuf) {
    if (secureBuf.secure) sodium.sodium_free(secureBuf)
  }
} else {
  exports.free = function () {}
}

exports.namespace = function (name, count) {
  const ids = typeof count === 'number' ? range(count) : count

  // Namespaces are long-lived, so better to use a dedicated slab
  const buf = b4a.allocUnsafeSlow(32 * ids.length)

  const list = new Array(ids.length)

  // ns is emhemeral, so default slab
  const ns = b4a.allocUnsafe(33)
  sodium.crypto_generichash(ns.subarray(0, 32), typeof name === 'string' ? b4a.from(name) : name)

  for (let i = 0; i < list.length; i++) {
    list[i] = buf.subarray(32 * i, 32 * i + 32)
    ns[32] = ids[i]
    sodium.crypto_generichash(list[i], ns)
  }

  return list
}

function range (count) {
  const arr = new Array(count)
  for (let i = 0; i < count; i++) arr[i] = i
  return arr
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return uint24.decode(state) + 0x1000000 * uint32.decode(state)
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return uint32.decode(state) + 0x100000000 * uint32.decode(state)
  }
})

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "2.19.2",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    if (b.byteLength === 0) return null
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "hypercore-crypto",
  "version": "3.6.1",
  "description": "The crypto primitives used in hypercore, extracted into a separate module",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.6.6",
    "compact-encoding": "^2.15.0",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "brittle": "^3.5.0",
    "standard": "^17.1.0"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/hypercore-crypto.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/hypercore-crypto/issues"
  },
  "homepage": "https://github.com/mafintosh/hypercore-crypto"
}
const z32 = require('z32')
const b4a = require('b4a')

module.exports = {
  encode,
  decode,
  normalize,
  isValid
}

function encode (key) {
  if (!b4a.isBuffer(key)) throw new Error('Key must be a Buffer')
  if (key.byteLength !== 32) throw new Error('Key must be 32-bytes long')
  return z32.encode(key)
}

function decode (id) {
  if (b4a.isBuffer(id)) {
    if (id.byteLength !== 32) throw new Error('ID must be 32-bytes long')
    return id
  }
  if (typeof id === 'string') {
    if (id.startsWith('pear://')) id = id.slice(7).split('/')[0]
    if (id.length === 52) return z32.decode(id)
    if (id.length === 64) {
      const buf = b4a.from(id, 'hex')
      if (buf.byteLength === 32) return buf
    }
  }
  throw new Error('Invalid Hypercore key')
}

function normalize (any) {
  return encode(decode(any))
}

function isValid (any) {
  try {
    decode(any)
    return true
  } catch {
    return false
  }
}
{
  "name": "hypercore-id-encoding",
  "version": "1.3.0",
  "description": "Convert Hypercore keys to/from z-base32 or hex",
  "main": "index.js",
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.5.3",
    "z32": "^1.0.0"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "hypercore": "^10.0.0",
    "random-access-memory": "^6.0.0",
    "standard": "^17.1.0"
  },
  "license": "Apache-2.0",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/hypercore-id-encoding.git"
  },
  "keywords": [],
  "author": "",
  "bugs": {
    "url": "https://github.com/holepunchto/hypercore-id-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/hypercore-id-encoding#readme"
}
const c = require('compact-encoding')
const { getEncoding } = require('./spec/hyperschema')

const HyperdhtAddress = getEncoding('@hyperdht/address')

function decode(buf) {
  const addr = c.decode(HyperdhtAddress, buf)
  return addr
}

function encode(key, nodes) {
  return c.encode(HyperdhtAddress, { key, nodes })
}

module.exports = { decode, encode }
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return uint24.decode(state) + 0x1000000 * uint32.decode(state)
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return uint32.decode(state) + 0x100000000 * uint32.decode(state)
  }
})

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "2.19.2",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    if (b.byteLength === 0) return null
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "hyperdht-address",
  "version": "1.0.1",
  "description": "hyperdht-address",
  "main": "index.js",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    }
  },
  "files": [
    "package.json",
    "index.js",
    "index.d.ts",
    "spec"
  ],
  "devDependencies": {
    "b4a": "^1.8.0",
    "brittle": "^3.19.0",
    "lunte": "^1.2.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && lunte && brittle-bare test/index.js",
    "lint": "lunte"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/hyperdht-address.git"
  },
  "author": "Holepunch Inc",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/hyperdht-address/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperdht-address",
  "dependencies": {
    "compact-encoding": "^2.19.0",
    "hyperschema": "^1.20.1"
  }
}
// This file is autogenerated by the hyperschema compiler
// Schema Version: 2
/* eslint-disable camelcase */
/* eslint-disable quotes */
/* eslint-disable space-before-function-paren */

const { c } = require('hyperschema/runtime')

const VERSION = 2

// eslint-disable-next-line no-unused-vars
let version = VERSION

// @hyperdht/address.nodes
const encoding0_1 = c.array(c.ipv4Address)

// @hyperdht/address
const encoding0 = {
  preencode(state, m) {
    c.fixed32.preencode(state, m.key)
    state.end++ // max flag is 1 so always one byte

    if (version >= 2 && m.nodes) encoding0_1.preencode(state, m.nodes)
  },
  encode(state, m) {
    const flags = version >= 2 && m.nodes ? 1 : 0

    c.fixed32.encode(state, m.key)
    c.uint.encode(state, flags)

    if (version >= 2 && m.nodes) encoding0_1.encode(state, m.nodes)
  },
  decode(state) {
    const r0 = c.fixed32.decode(state)
    const flags = state.start < state.end ? c.uint.decode(state) : 0

    return {
      key: r0,
      nodes: version >= 2 && (flags & 1) !== 0 ? encoding0_1.decode(state) : null
    }
  }
}

function setVersion(v) {
  version = v
}

function encode(name, value, v = VERSION) {
  version = v
  return c.encode(getEncoding(name), value)
}

function decode(name, buffer, v = VERSION) {
  version = v
  return c.decode(getEncoding(name), buffer)
}

function getEnum(name) {
  switch (name) {
    default:
      throw new Error('Enum not found ' + name)
  }
}

function getEncoding(name) {
  switch (name) {
    case '@hyperdht/address':
      return encoding0
    default:
      throw new Error('Encoder not found ' + name)
  }
}

function getStruct(name, v = VERSION) {
  const enc = getEncoding(name)
  return {
    preencode(state, m) {
      version = v
      enc.preencode(state, m)
    },
    encode(state, m) {
      version = v
      enc.encode(state, m)
    },
    decode(state) {
      version = v
      return enc.decode(state)
    }
  }
}

const resolveStruct = getStruct // compat

module.exports = {
  resolveStruct,
  getStruct,
  getEnum,
  getEncoding,
  encode,
  decode,
  setVersion,
  version
}
const DHT = require('dht-rpc')
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const b4a = require('b4a')
const safetyCatch = require('safety-catch')
const m = require('./lib/messages')
const SocketPool = require('./lib/socket-pool')
const Persistent = require('./lib/persistent')
const Router = require('./lib/router')
const Cache = require('xache')
const Server = require('./lib/server')
const connect = require('./lib/connect')
const { FIREWALL, BOOTSTRAP_NODES, KNOWN_NODES, COMMANDS } = require('./lib/constants')
const { hash, createKeyPair } = require('./lib/crypto')
const RawStreamSet = require('./lib/raw-stream-set')
const ConnectionPool = require('./lib/connection-pool')
const { STREAM_NOT_CONNECTED } = require('./lib/errors')

const DEFAULTS = {
  ...DHT.DEFAULTS,
  connectionKeepAlive: 5000,
  randomPunchInterval: 20000
}

class HyperDHT extends DHT {
  constructor(opts = {}) {
    const port = opts.port || 49737
    const bootstrap = opts.bootstrap || BOOTSTRAP_NODES
    const nodes = opts.nodes || KNOWN_NODES

    super({ ...opts, port, bootstrap, nodes, filterNode })

    const { router, relayAddresses, persistent } = defaultCacheOpts(opts)

    this.defaultKeyPair = opts.keyPair || createKeyPair(opts.seed)
    this.listening = new Set()
    this.connectionKeepAlive =
      opts.connectionKeepAlive === false
        ? 0
        : opts.connectionKeepAlive || DEFAULTS.connectionKeepAlive

    // stats is inherited from dht-rpc so fwd the ones from there
    this.stats = {
      punches: { consistent: 0, random: 0, open: 0 },
      relaying: { attempts: 0, successes: 0, aborts: 0 },
      ...this.stats
    }
    this.rawStreams = new RawStreamSet(this)
    this.plugins = new Map()

    this._router = new Router(this, router)
    this._socketPool = new SocketPool(this, opts.host || '0.0.0.0')
    this._persistent = null
    this._validatedLocalAddresses = new Map()
    this._relayAddressesCache = new Cache(relayAddresses)

    this._deferRandomPunch = !!opts.deferRandomPunch
    this._lastRandomPunch = this._deferRandomPunch ? Date.now() : 0
    this._connectable = true
    this._randomPunchInterval = opts.randomPunchInterval || DEFAULTS.randomPunchInterval // min 20s between random punches...
    this._randomPunches = 0
    this._randomPunchLimit = 1 // set to one for extra safety for now

    this.once('persistent', () => {
      this._persistent = new Persistent(this, persistent)
      for (const plugin of this.plugins.values()) plugin.onpersistent()
    })

    this.on('network-change', () => {
      for (const server of this.listening) server.refresh()
    })

    this.on('network-update', () => {
      if (!this.online) return
      for (const server of this.listening) server.notifyOnline()
    })
  }

  static DEFAULTS = DEFAULTS

  connect(remotePublicKey, opts) {
    return connect(this, remotePublicKey, opts)
  }

  createServer(opts, onconnection) {
    if (typeof opts === 'function') return this.createServer({}, opts)
    if (opts && opts.onconnection) onconnection = opts.onconnection
    const s = new Server(this, opts)
    if (onconnection) s.on('connection', onconnection)
    return s
  }

  pool() {
    return new ConnectionPool(this)
  }

  async resume({ log = noop } = {}) {
    if (this._deferRandomPunch) this._lastRandomPunch = Date.now()
    await super.resume({ log })
    const resuming = []
    for (const server of this.listening) resuming.push(server.resume())
    log('Resuming hyperdht servers')
    await Promise.allSettled(resuming)
    log('Done, hyperdht fully resumed')
  }

  async suspend({ log = noop } = {}) {
    this._connectable = false // just so nothing gets connected during suspension
    const suspending = []
    for (const server of this.listening) suspending.push(server.suspend())
    log('Suspending all hyperdht servers')
    await Promise.allSettled(suspending)
    log('Done, clearing all raw streams')
    await this.rawStreams.clear()
    log('Done, suspending dht-rpc')
    await super.suspend({ log })
    log('Done, clearing raw streams again')
    await this.rawStreams.clear()
    log('Done, hyperdht fully suspended')
    this._connectable = true
  }

  async destroy({ force = false } = {}) {
    if (!force) {
      const closing = []
      for (const server of this.listening) closing.push(server.close())
      await Promise.allSettled(closing)
    }
    this._router.destroy()
    if (this._persistent) this._persistent.destroy()
    for (const plugin of this.plugins.values()) plugin.destroy()
    await this.rawStreams.clear()
    await this._socketPool.destroy()
    await super.destroy()
  }

  async validateLocalAddresses(addresses) {
    const list = []
    const socks = []
    const waiting = []

    for (const addr of addresses) {
      const { host } = addr

      if (this._validatedLocalAddresses.has(host)) {
        if (await this._validatedLocalAddresses.get(host)) {
          list.push(addr)
        }
        continue
      }

      const sock = this.udx.createSocket()
      try {
        sock.bind(0, host)
      } catch {
        this._validatedLocalAddresses.set(host, Promise.resolve(false))
        continue
      }

      socks.push(sock)

      // semi terrible heuristic until we proper fix local connections by racing them to the remote...
      const promise = new Promise((resolve) => {
        sock.on('message', () => resolve(true))
        setTimeout(() => resolve(false), 500)
        sock.trySend(b4a.alloc(1), sock.address().port, addr.host)
      })

      this._validatedLocalAddresses.set(host, promise)
      waiting.push(addr)
    }

    for (const addr of waiting) {
      const { host } = addr
      if (this._validatedLocalAddresses.has(host)) {
        if (await this._validatedLocalAddresses.get(host)) {
          list.push(addr)
        }
        continue
      }
    }

    for (const sock of socks) await sock.close()

    return list
  }

  findPeer(publicKey, opts = {}) {
    const target = opts.hash === false ? publicKey : hash(publicKey)
    opts = { ...opts, map: mapFindPeer }
    return this.query({ target, command: COMMANDS.FIND_PEER, value: null }, opts)
  }

  lookup(target, opts = {}) {
    opts = { ...opts, map: mapLookup }
    return this.query({ target, command: COMMANDS.LOOKUP, value: null }, opts)
  }

  lookupAndUnannounce(target, keyPair, opts = {}) {
    const unannounces = []
    const dht = this
    const userCommit = opts.commit || noop
    const signUnannounce = opts.signUnannounce || Persistent.signUnannounce

    if (this._persistent !== null) {
      // unlink self
      this._persistent.unannounce(target, keyPair.publicKey)
    }

    opts = { ...opts, map, commit }
    return this.query({ target, command: COMMANDS.LOOKUP, value: null }, opts)

    async function commit(reply, dht, query) {
      await Promise.all(unannounces) // can never fail, caught below
      return userCommit(reply, dht, query)
    }

    function map(reply) {
      const data = mapLookup(reply)

      if (!data || !data.token) return data

      let found = data.peers.length >= 20
      for (let i = 0; !found && i < data.peers.length; i++) {
        found = b4a.equals(data.peers[i].publicKey, keyPair.publicKey)
      }

      if (!found) return data

      if (!data.from.id) return data

      unannounces.push(
        dht
          ._requestUnannounce(keyPair, dht, target, data.token, data.from, signUnannounce)
          .catch(safetyCatch)
      )

      return data
    }
  }

  unannounce(target, keyPair, opts = {}) {
    return this.lookupAndUnannounce(target, keyPair, opts).finished()
  }

  announce(target, keyPair, relayAddresses, opts = {}) {
    const signAnnounce = opts.signAnnounce || Persistent.signAnnounce
    const bump = opts.bump || 0

    opts = { ...opts, commit }

    return opts.clear ? this.lookupAndUnannounce(target, keyPair, opts) : this.lookup(target, opts)

    function commit(reply, dht) {
      return dht._requestAnnounce(
        keyPair,
        dht,
        target,
        reply.token,
        reply.from,
        relayAddresses,
        signAnnounce,
        bump
      )
    }
  }

  async immutableGet(target, opts = {}) {
    opts = { ...opts, map: mapImmutable }

    const query = this.query({ target, command: COMMANDS.IMMUTABLE_GET, value: null }, opts)
    const check = b4a.allocUnsafe(32)

    for await (const node of query) {
      const { value } = node
      sodium.crypto_generichash(check, value)
      if (b4a.equals(check, target)) return node
    }

    return null
  }

  async immutablePut(value, opts = {}) {
    const target = b4a.allocUnsafe(32)
    sodium.crypto_generichash(target, value)

    opts = {
      ...opts,
      map: mapImmutable,
      commit(reply, dht) {
        return dht.request(
          { token: reply.token, target, command: COMMANDS.IMMUTABLE_PUT, value },
          reply.from
        )
      }
    }

    const query = this.query({ target, command: COMMANDS.IMMUTABLE_GET, value: null }, opts)
    await query.finished()

    return { hash: target, closestNodes: query.closestNodes }
  }

  async mutableGet(publicKey, opts = {}) {
    let refresh = opts.refresh || null
    let signed = null
    let result = null

    opts = { ...opts, map: mapMutable, commit: refresh ? commit : null }

    const target = b4a.allocUnsafe(32)
    sodium.crypto_generichash(target, publicKey)

    const userSeq = opts.seq || 0
    const query = this.query(
      { target, command: COMMANDS.MUTABLE_GET, value: c.encode(c.uint, userSeq) },
      opts
    )
    const latest = opts.latest !== false

    for await (const node of query) {
      if (result && node.seq <= result.seq) continue
      if (
        node.seq < userSeq ||
        !Persistent.verifyMutable(node.signature, node.seq, node.value, publicKey)
      )
        continue
      if (!latest) return node
      if (!result || node.seq > result.seq) result = node
    }

    return result

    function commit(reply, dht) {
      if (!signed && result && refresh) {
        if (refresh(result)) {
          signed = c.encode(m.mutablePutRequest, {
            publicKey,
            seq: result.seq,
            value: result.value,
            signature: result.signature
          })
        } else {
          refresh = null
        }
      }

      return signed
        ? dht.request(
            { token: reply.token, target, command: COMMANDS.MUTABLE_PUT, value: signed },
            reply.from
          )
        : Promise.resolve(null)
    }
  }

  async mutablePut(keyPair, value, opts = {}) {
    const signMutable = opts.signMutable || Persistent.signMutable

    const target = b4a.allocUnsafe(32)
    sodium.crypto_generichash(target, keyPair.publicKey)

    const seq = opts.seq || 0
    const signature = await signMutable(seq, value, keyPair)

    const signed = c.encode(m.mutablePutRequest, {
      publicKey: keyPair.publicKey,
      seq,
      value,
      signature
    })

    opts = {
      ...opts,
      map: mapMutable,
      commit(reply, dht) {
        return dht.request(
          { token: reply.token, target, command: COMMANDS.MUTABLE_PUT, value: signed },
          reply.from
        )
      }
    }

    // use seq = 0, for the query part here, as we don't care about the actual values
    const query = this.query(
      { target, command: COMMANDS.MUTABLE_GET, value: c.encode(c.uint, 0) },
      opts
    )
    await query.finished()

    return { publicKey: keyPair.publicKey, closestNodes: query.closestNodes, seq, signature }
  }

  onrequest(req) {
    switch (req.command) {
      case COMMANDS.PEER_HANDSHAKE: {
        this._router.onpeerhandshake(req)
        return true
      }
      case COMMANDS.PEER_HOLEPUNCH: {
        this._router.onpeerholepunch(req)
        return true
      }
    }

    if (this._persistent === null || this.id === null) return false

    switch (req.command) {
      case COMMANDS.FIND_PEER: {
        this._persistent.onfindpeer(req)
        return true
      }
      case COMMANDS.LOOKUP: {
        this._persistent.onlookup(req)
        return true
      }
      case COMMANDS.ANNOUNCE: {
        this._persistent.onannounce(req)
        return true
      }
      case COMMANDS.UNANNOUNCE: {
        this._persistent.onunannounce(req)
        return true
      }
      case COMMANDS.MUTABLE_PUT: {
        this._persistent.onmutableput(req)
        return true
      }
      case COMMANDS.MUTABLE_GET: {
        this._persistent.onmutableget(req)
        return true
      }
      case COMMANDS.IMMUTABLE_PUT: {
        this._persistent.onimmutableput(req)
        return true
      }
      case COMMANDS.IMMUTABLE_GET: {
        this._persistent.onimmutableget(req)
        return true
      }
      case COMMANDS.PLUGIN: {
        this._persistent.onplugin(req)
        return true
      }
    }

    return false
  }

  static keyPair(seed) {
    return createKeyPair(seed)
  }

  static hash(data) {
    return hash(data)
  }

  static connectRawStream(encryptedStream, rawStream, remoteId) {
    const stream = encryptedStream.rawStream

    if (!stream.connected) throw STREAM_NOT_CONNECTED()

    rawStream.connect(stream.socket, remoteId, stream.remotePort, stream.remoteHost)
  }

  createRawStream(opts) {
    return this.rawStreams.add(opts)
  }

  async _requestAnnounce(keyPair, dht, target, token, from, relayAddresses, sign, bump) {
    const ann = {
      peer: {
        publicKey: keyPair.publicKey,
        relayAddresses: relayAddresses || []
      },
      refresh: null,
      signature: null,
      bump
    }

    ann.signature = await sign(target, token, from.id, ann, keyPair)

    const value = c.encode(m.announce, ann)

    return dht.request(
      {
        token,
        target,
        command: COMMANDS.ANNOUNCE,
        value
      },
      from
    )
  }

  async _requestUnannounce(keyPair, dht, target, token, from, sign) {
    const unann = {
      peer: {
        publicKey: keyPair.publicKey,
        relayAddresses: []
      },
      signature: null
    }

    unann.signature = await sign(target, token, from.id, unann, keyPair)

    const value = c.encode(m.announce, unann)

    return dht.request(
      {
        token,
        target,
        command: COMMANDS.UNANNOUNCE,
        value
      },
      from
    )
  }

  register(name, plugin) {
    this.plugins.set(name, plugin)
    plugin.onregister(this)
  }
}

HyperDHT.BOOTSTRAP = BOOTSTRAP_NODES
HyperDHT.FIREWALL = FIREWALL

module.exports = HyperDHT

function mapLookup(node) {
  if (!node.value) return null

  try {
    const l = c.decode(m.lookupRawReply, node.value)

    return {
      token: node.token,
      from: node.from,
      to: node.to,
      peers: l.peers,
      bump: l.bump
    }
  } catch {
    return null
  }
}

function mapFindPeer(node) {
  if (!node.value) return null

  try {
    return {
      token: node.token,
      from: node.from,
      to: node.to,
      peer: c.decode(m.peer, node.value)
    }
  } catch {
    return null
  }
}

function mapImmutable(node) {
  if (!node.value) return null

  return {
    token: node.token,
    from: node.from,
    to: node.to,
    value: node.value
  }
}

function mapMutable(node) {
  if (!node.value) return null

  try {
    const { seq, value, signature } = c.decode(m.mutableGetResponse, node.value)

    return {
      token: node.token,
      from: node.from,
      to: node.to,
      seq,
      value,
      signature
    }
  } catch {
    return null
  }
}

function noop() {}

function filterNode(node) {
  // always skip these testnet nodes that got mixed in by accident, until they get updated
  return (
    !(node.port === 49738 && (node.host === '134.209.28.98' || node.host === '167.99.142.185')) &&
    !(node.port === 9400 && node.host === '35.233.47.252') &&
    !(node.host === '150.136.142.116')
  )
}

const defaultMaxSize = 65536
const defaultMaxAge = 20 * 60 * 1000 // 20 minutes

function defaultCacheOpts(opts) {
  const maxSize = opts.maxSize || defaultMaxSize
  const maxAge = opts.maxAge || defaultMaxAge

  return {
    router: {
      forwards: { maxSize, maxAge }
    },
    relayAddresses: { maxSize: Math.min(maxSize, 512), maxAge: 0 },
    persistent: {
      records: { maxSize, maxAge },
      refreshes: { maxSize, maxAge },
      mutables: {
        maxSize: (maxSize / 2) | 0,
        maxAge: opts.maxAge || 48 * 60 * 60 * 1000 // 48 hours
      },
      immutables: {
        maxSize: (maxSize / 2) | 0,
        maxAge: opts.maxAge || 48 * 60 * 60 * 1000 // 48 hours
      },
      bumps: { maxSize, maxAge }
    }
  }
}
const safetyCatch = require('safety-catch')
const c = require('compact-encoding')
const Signal = require('signal-promise')
const { encodeUnslab } = require('./encode')
const Sleeper = require('./sleeper')
const m = require('./messages')
const Persistent = require('./persistent')
const { COMMANDS } = require('./constants')

const MIN_ACTIVE = 3

module.exports = class Announcer {
  constructor(dht, keyPair, target, opts = {}) {
    this.dht = dht
    this.keyPair = keyPair
    this.target = target
    this.relays = []
    this.relayAddresses = []
    this.stopped = false
    this.suspended = false
    this.record = encodeUnslab(m.peer, { publicKey: keyPair.publicKey, relayAddresses: [] })
    this.online = new Signal()

    this._refreshing = false
    this._closestNodes = null
    this._active = null
    this._sleeper = new Sleeper()
    this._resumed = new Signal()
    this._signAnnounce = opts.signAnnounce || Persistent.signAnnounce
    this._signUnannounce = opts.signUnannounce || Persistent.signUnannounce
    this._updating = null
    this._activeQuery = null
    this._unannouncing = null

    this._serverRelays = [new Map(), new Map(), new Map()]
  }

  isRelay(addr) {
    const id = addr.host + ':' + addr.port
    const [a, b, c] = this._serverRelays
    return a.has(id) || b.has(id) || c.has(id)
  }

  async suspend({ log = noop } = {}) {
    if (this.suspended) return
    this.suspended = true

    log('Suspending announcer')

    // Suspend has its own sleep logic
    // so we don't want to hang on this one
    this.online.notify()

    if (this._activeQuery) this._activeQuery.destroy()

    this._sleeper.resume()
    if (this._updating) await this._updating
    log('Suspending announcer (post update)')

    if (this.suspended === false || this.stopped) return

    log('Suspending announcer (pre unannounce)')
    await this._unannounceCurrent()
    log('Suspending announcer (post unannounce)')
  }

  resume() {
    if (!this.suspended) return
    this.suspended = false

    this.refresh()
    this._sleeper.resume()
    this._resumed.notify()
  }

  refresh() {
    if (this.stopped) return
    this._refreshing = true
  }

  async start() {
    if (this.stopped) return
    this._active = this._runUpdate()
    await this._active
    if (this.stopped) return
    this._active = this._background()
  }

  async stop() {
    this.stopped = true
    this.online.notify() // Break out of the _background loop if we're offline
    this._sleeper.resume()
    this._resumed.notify()
    await this._active
    await this._unannounceCurrent()
  }

  async _unannounceCurrent() {
    while (this._unannouncing !== null) await this._unannouncing
    const un = (this._unannouncing = this._unannounceAll(this._serverRelays[2].values()))
    await this._unannouncing
    if (un === this._unannouncing) this._unannouncing = null
  }

  async _background() {
    while (!this.dht.destroyed && !this.stopped) {
      try {
        this._refreshing = false

        // ~5min +-
        for (let i = 0; i < 100 && !this.stopped && !this._refreshing && !this.suspended; i++) {
          const pings = []

          for (const node of this._serverRelays[2].values()) {
            pings.push(this.dht.ping(node))
          }

          const active = await resolved(pings)
          if (active < Math.min(pings.length, MIN_ACTIVE)) {
            this.refresh() // we lost too many relay nodes, retry all
          }

          if (this.stopped) return

          if (!this.suspended && !this._refreshing) await this._sleeper.pause(3000)
        }

        while (!this.stopped && this.suspended) await this._resumed.wait()

        if (!this.stopped) await this._runUpdate()

        while (!this.dht.online && !this.stopped && !this.suspended) {
          // Being offline can make _background repeat very quickly
          // So wait until we're back online
          await this.online.wait()
        }
      } catch (err) {
        safetyCatch(err)
      }
    }
  }

  async _runUpdate() {
    this._updating = this._update()
    await this._updating
    this._updating = null
  }

  async _update() {
    while (this._unannouncing) await this._unannouncing

    this._cycle()

    const q = (this._activeQuery = this.dht.findPeer(this.target, {
      hash: false,
      nodes: this._closestNodes
    }))

    try {
      await q.finished()
    } catch {
      // ignore failures...
    }

    this._activeQuery = null

    if (this.stopped || this.suspended) return

    const ann = []
    const replies = pickBest(q.closestReplies)

    const relays = []
    const relayAddresses = []

    if (!this.dht.firewalled) {
      const addr = this.dht.remoteAddress()
      if (addr) relayAddresses.push(addr)
    }

    for (const msg of replies) {
      ann.push(this._commit(msg, relays, relayAddresses))
    }

    await Promise.allSettled(ann)
    if (this.stopped || this.suspended) return

    this._closestNodes = q.closestNodes
    this.relays = relays
    this.relayAddresses = relayAddresses

    const removed = []
    for (const [key, value] of this._serverRelays[1]) {
      if (!this._serverRelays[2].has(key)) removed.push(value)
    }

    await this._unannounceAll(removed)
  }

  _unannounceAll(relays) {
    const unann = []
    for (const r of relays) unann.push(this._unannounce(r))
    return Promise.allSettled(unann)
  }

  async _unannounce(to) {
    const unann = {
      peer: {
        publicKey: this.keyPair.publicKey,
        relayAddresses: []
      },
      refresh: null,
      signature: null
    }

    const { from, token, value } = await this.dht.request(
      {
        token: null,
        command: COMMANDS.FIND_PEER,
        target: this.target,
        value: null
      },
      to
    )

    if (!token || !from.id || !value) return

    unann.signature = await this._signUnannounce(this.target, token, from.id, unann, this.keyPair)

    await this.dht.request(
      {
        token,
        command: COMMANDS.UNANNOUNCE,
        target: this.target,
        value: c.encode(m.announce, unann)
      },
      to
    )
  }

  async _commit(msg, relays, relayAddresses) {
    const ann = {
      peer: {
        publicKey: this.keyPair.publicKey,
        relayAddresses: []
      },
      refresh: null,
      signature: null
    }

    ann.signature = await this._signAnnounce(this.target, msg.token, msg.from.id, ann, this.keyPair)

    const res = await this.dht.request(
      {
        token: msg.token,
        command: COMMANDS.ANNOUNCE,
        target: this.target,
        value: c.encode(m.announce, ann)
      },
      msg.from
    )

    if (res.error !== 0) return

    if (relayAddresses.length < 3) relayAddresses.push({ host: msg.from.host, port: msg.from.port })
    relays.push({ relayAddress: msg.from, peerAddress: msg.to })

    this._serverRelays[2].set(msg.from.host + ':' + msg.from.port, msg.from)
  }

  _cycle() {
    const tmp = this._serverRelays[0]
    this._serverRelays[0] = this._serverRelays[1]
    this._serverRelays[1] = this._serverRelays[2]
    this._serverRelays[2] = tmp
    tmp.clear()
  }
}

function resolved(ps) {
  let replied = 0
  let ticks = ps.length + 1

  return new Promise((resolve) => {
    for (const p of ps) p.then(push, tick)
    tick()

    function push(v) {
      replied++
      tick()
    }

    function tick() {
      if (--ticks === 0) resolve(replied)
    }
  })
}

function pickBest(replies) {
  // TODO: pick the ones closest to us RTT wise
  return replies.slice(0, 3)
}

function noop() {}
const NoiseSecretStream = require('@hyperswarm/secret-stream')
const b4a = require('b4a')
const relay = require('blind-relay')
const { isReserved, isBogon } = require('bogon')
const safetyCatch = require('safety-catch')
const unslab = require('unslab')
const Semaphore = require('./semaphore')
const NoiseWrap = require('./noise-wrap')
const SecurePayload = require('./secure-payload')
const Holepuncher = require('./holepuncher')
const Sleeper = require('./sleeper')
const { FIREWALL, ERROR } = require('./constants')
const { unslabbedHash } = require('./crypto')
const {
  CANNOT_HOLEPUNCH,
  HANDSHAKE_INVALID,
  HOLEPUNCH_ABORTED,
  HOLEPUNCH_INVALID,
  HOLEPUNCH_PROBE_TIMEOUT,
  HOLEPUNCH_DOUBLE_RANDOMIZED_NATS,
  PEER_CONNECTION_FAILED,
  PEER_NOT_FOUND,
  REMOTE_ABORTED,
  REMOTE_NOT_HOLEPUNCHABLE,
  REMOTE_NOT_HOLEPUNCHING,
  SERVER_ERROR,
  SERVER_INCOMPATIBLE,
  RELAY_ABORTED,
  SUSPENDED
} = require('./errors')
const { decode } = require('hypercore-id-encoding')
const HyperDHTAddress = require('hyperdht-address')

module.exports = function connect(dht, publicKey, opts = {}) {
  const pool = opts.pool || null

  const { key, nodes: providedNodes } = HyperDHTAddress.decode(
    b4a.isBuffer(publicKey) ? publicKey : decode(publicKey)
  )
  publicKey = key

  if (pool && pool.has(publicKey)) return pool.get(publicKey)

  publicKey = unslab(publicKey)

  opts.relayAddresses = opts.relayAddresses || providedNodes || []
  const keyPair = opts.keyPair || dht.defaultKeyPair
  const relayThrough = selectRelay(opts.relayThrough || null)
  const encryptedSocket = (opts.createSecretStream || defaultCreateSecretStream)(true, null, {
    publicKey: keyPair.publicKey,
    remotePublicKey: publicKey,
    autoStart: false,
    keepAlive: dht.connectionKeepAlive
  })

  // in case a socket is made during suspended state, destroy it immediately
  if (dht.suspended || !dht._connectable) {
    encryptedSocket.destroy(SUSPENDED())
    return encryptedSocket
  }

  if (pool) pool._attachStream(encryptedSocket, false)

  const id = b4a.toString(publicKey, 'hex')
  const c = {
    id,
    dht,
    session: dht.session(),
    relayAddresses: opts.relayAddresses,
    remoteRelayAddresses: [],
    pool,
    round: 0,
    target: unslabbedHash(publicKey),
    remotePublicKey: publicKey,
    reusableSocket: !!opts.reusableSocket,
    handshake: (opts.createHandshake || defaultCreateHandshake)(keyPair, publicKey),
    request: null,
    requesting: false,
    lan: opts.localConnection !== false,
    firewall: FIREWALL.UNKNOWN,
    rawStream: dht.createRawStream({ framed: true, firewall }),
    connect: null,
    query: null,
    puncher: null,
    payload: null,
    passiveConnectTimeout: null,
    serverSocket: null,
    serverAddress: null,
    onsocket: null,
    sleeper: new Sleeper(),
    encryptedSocket,

    // Relay state
    relayTimeout: null,
    relayThrough,
    relayToken: relayThrough ? relay.token() : null,
    relaySocket: null,
    relayClient: null,
    relayPaired: false,
    relayKeepAlive: opts.relayKeepAlive || 5000
  }

  // If the raw stream receives an error signal pre connect (ie from the firewall hook), make sure
  // to forward that to the encrypted socket for proper teardown
  c.rawStream.on('error', autoDestroy)
  c.rawStream.once('connect', () => {
    c.rawStream.removeListener('error', autoDestroy)
  })

  encryptedSocket.on('close', function () {
    if (c.passiveConnectTimeout) clearPassiveConnectTimeout(c)
    if (c.query) c.query.destroy()
    if (c.puncher) c.puncher.destroy()
    if (c.rawStream) c.rawStream.destroy()
    c.session.destroy()
    c.sleeper.resume()
  })

  // Safe to run in the background - never throws
  if (dht.suspended) encryptedSocket.destroy(SUSPENDED())
  else connectAndHolepunch(c, opts)

  return encryptedSocket

  function autoDestroy(err) {
    maybeDestroyEncryptedSocket(c, err)
  }

  function firewall(socket, port, host) {
    // Check if the traffic originated from the socket on which we're expecting relay traffic. If so,
    // we haven't hole punched yet and the other side is just sending us traffic through the relay.
    if (c.relaySocket && isRelay(c.relaySocket, socket, port, host)) {
      return false
    }

    if (c.onsocket) {
      c.onsocket(socket, port, host)
    } else {
      c.serverSocket = socket
      c.serverAddress = { port, host }
    }
    return false
  }
}

function isDone(c) {
  // we are destroying or the puncher is connected - done
  if (c.encryptedSocket.destroying || !!(c.puncher && c.puncher.connected)) {
    return true
  }
  // not destroying, but no raw stream - def not done
  if (c.encryptedSocket.rawStream === null) {
    return false
  }
  // we are relayed, but the puncher is not done yet
  if (c.relaySocket && !!(c.puncher && !c.puncher.connected && !c.puncher.destroyed)) {
    return false
  }
  // we are done
  return true
}

async function retryRoute(c, route) {
  const ref = c.dht._socketPool.lookup(route.socket)

  if (!ref) {
    if (route.socket === c.dht.socket) {
      await connectThroughNode(c, route.address, c.dht.socket)
    }
    return
  }

  ref.active()

  try {
    await connectThroughNode(c, route.address, route.socket)
  } catch {
    // if error, just ignore, and continue through the existing strat
  }

  ref.inactive()
}

async function connectAndHolepunch(c, opts) {
  const route = c.reusableSocket ? c.dht._socketPool.routes.get(c.remotePublicKey) : null

  if (route) {
    await retryRoute(c, route)
    if (isDone(c)) return
  }

  await findAndConnect(c, opts)
  if (isDone(c)) return

  if (!c.connect) {
    // TODO: just a quick fix for now, should retry prob
    maybeDestroyEncryptedSocket(c, HANDSHAKE_INVALID())
    return
  }

  await holepunch(c, opts)
}

function getFirstRemoteAddress(addrs, serverAddress) {
  for (const addr of addrs) {
    if (isBogon(addr.host)) continue
    return addr
  }

  return serverAddress
}

async function holepunch(c, opts) {
  let { relayAddress, serverAddress, clientAddress, payload } = c.connect

  const remoteHolepunchable = !!(payload.holepunch && payload.holepunch.relays.length)

  const relayed = diffAddress(serverAddress, relayAddress)

  if (payload.firewall === FIREWALL.OPEN || (relayed && !remoteHolepunchable)) {
    const addr = getFirstRemoteAddress(payload.addresses4, serverAddress)
    if (addr) {
      const socket = c.dht.socket
      c.dht.stats.punches.open++
      c.onsocket(socket, addr.port, addr.host)
      return
    }
    // TODO: check all addresses also obvs
  }

  const onabort = () => {
    c.session.destroy()
    maybeDestroyEncryptedSocket(c, HOLEPUNCH_ABORTED())
  }

  if (c.firewall === FIREWALL.OPEN) {
    c.passiveConnectTimeout = setTimeout(onabort, 10000)
    return
  }

  // TODO: would be better to just try local addrs in the background whilst continuing with other strategies...
  if (c.lan && relayed && clientAddress.host === serverAddress.host) {
    const serverAddresses = payload.addresses4.filter(onlyNonReserved)

    if (serverAddresses.length > 0) {
      const myAddresses = Holepuncher.localAddresses(c.dht.io.serverSocket)
      const addr = Holepuncher.matchAddress(myAddresses, serverAddresses) || serverAddresses[0]

      const socket = c.dht.io.serverSocket
      try {
        await c.dht.ping(addr)
      } catch {
        maybeDestroyEncryptedSocket(c, HOLEPUNCH_ABORTED())
        return
      }
      c.onsocket(socket, addr.port, addr.host)
      return
    }
  }

  if (!remoteHolepunchable) {
    maybeDestroyEncryptedSocket(c, CANNOT_HOLEPUNCH())
    return
  }

  c.puncher = new Holepuncher(c.dht, c.session, true, payload.firewall)

  c.puncher.onconnect = c.onsocket
  c.puncher.onabort = onabort

  const serverRelay = pickServerRelay(payload.holepunch.relays, relayAddress)

  // Begin holepunching!

  let probe
  try {
    probe = await probeRound(c, opts.fastOpen === false ? null : serverAddress, serverRelay, true)
  } catch (err) {
    destroyPuncher(c)
    // TODO: we should retry here with some of the other relays, bail for now
    maybeDestroyEncryptedSocket(c, err)
    return
  }

  if (isDone(c) || !probe) return
  const { token, peerAddress } = probe

  // If the relay the server picked is the same as the relay the client picked,
  // then we can use the peerAddress that round one indicates the server wants to use.
  // This shaves off a roundtrip if the server chose to reroll its socket due to some NAT
  // issue with the first one it picked (ie mobile nat inconsistencies...).
  // If the relays were different, then the server would not have a UDP session open on this address
  // to the client relay, which round2 uses.
  if (
    !diffAddress(serverRelay.relayAddress, relayAddress) &&
    diffAddress(serverAddress, peerAddress)
  ) {
    serverAddress = peerAddress
    await c.puncher.openSession(serverAddress)
    if (isDone(c)) return
  }

  // TODO: still continue here if a local connection might work, but then do not holepunch...
  if (
    opts.holepunch &&
    !opts.holepunch(
      c.puncher.remoteFirewall,
      c.puncher.nat.firewall,
      c.puncher.remoteAddresses,
      c.puncher.nat.addresses
    )
  ) {
    await abort(c, serverRelay, HOLEPUNCH_ABORTED('Client aborted holepunch'))
    return
  }

  try {
    await roundPunch(c, serverAddress, token, relayAddress, serverRelay, false)
  } catch (err) {
    destroyPuncher(c)
    // TODO: retry with another relay?
    maybeDestroyEncryptedSocket(c, err)
  }
}

async function connectThroughNodes(c, addresses, socket) {
  for (const address of addresses) {
    if (isDone(c) || c.connect) return

    c.remoteRelayAddresses.push(address)
    await connectThroughNode(c, address, socket)
  }
}

async function findAndConnect(c, opts) {
  let attempts = 0
  let relayAddresses =
    opts.relayAddresses && opts.relayAddresses.length ? opts.relayAddresses : null

  if (!relayAddresses) {
    const cachedRelayAddresses = c.dht._relayAddressesCache.get(c.id)
    if (cachedRelayAddresses) relayAddresses = cachedRelayAddresses
  }

  if (c.dht._persistent) {
    // check if we know the route ourself...
    const route = c.dht._router.get(c.target)
    if (route && route.relay !== null) {
      relayAddresses = [{ host: route.relay.host, port: route.relay.port }]
    }
  }

  // 2 is how many parallel connect attempts we want to do, we can make this configurable
  const preConnect = relayAddresses !== null && relayAddresses.length > 0
  const sem = new Semaphore(preConnect ? 3 : 2)
  const signal = sem.signal.bind(sem)
  const tries = relayAddresses !== null ? 2 : 1

  if (preConnect) {
    await sem.wait()
    connectThroughNodes(c, relayAddresses, null).then(signal, signal)
  }

  try {
    for (let i = 0; i < tries && !isDone(c) && !c.connect; i++) {
      c.query = c.dht.findPeer(c.target, {
        hash: false,
        session: c.session,
        nodes: relayAddresses,
        retries: 3
      })

      for await (const data of c.query) {
        await sem.wait()
        if (isDone(c)) return

        if (c.connect) {
          sem.signal()
          break
        }

        // Skip node already run via preConnect
        if (preConnect && relayAddresses && isRelayAddress(relayAddresses, data)) {
          sem.signal()
          continue
        }

        c.remoteRelayAddresses.push(data.from)
        attempts++
        connectThroughNode(c, data.from, null).then(signal, signal)
      }

      relayAddresses = null

      if (attempts > 0) await sem.flush()
    }

    c.query = null
    if (isDone(c)) return

    // flush the semaphore
    await sem.flush()
    if (isDone(c)) return
  } catch (err) {
    c.query = null
    maybeDestroyEncryptedSocket(c, err)
    return
  }

  if (!c.connect) {
    maybeDestroyEncryptedSocket(c, attempts ? PEER_CONNECTION_FAILED() : PEER_NOT_FOUND())
  }
}

async function connectThroughNode(c, address, socket) {
  if (!c.requesting) {
    // If we have a stable server address, send it over now
    const addr = c.dht.remoteAddress()
    const localAddrs = c.lan ? Holepuncher.localAddresses(c.dht.io.serverSocket) : null
    const addresses4 = []

    if (addr) addresses4.push(addr)
    if (localAddrs) addresses4.push(...localAddrs)

    c.firewall = addr ? FIREWALL.OPEN : FIREWALL.UNKNOWN
    c.requesting = true
    c.request = await c.handshake.send({
      error: ERROR.NONE,
      firewall: c.firewall,
      holepunch: null,
      addresses4,
      addresses6: [],
      udx: {
        reusableSocket: c.reusableSocket,
        id: c.rawStream.id,
        seq: 0
      },
      secretStream: {},
      relayThrough: c.relayThrough ? { publicKey: c.relayThrough, token: c.relayToken } : null
    })
    if (isDone(c)) return
  }

  const { serverAddress, clientAddress, relayed, noise } = await c.dht._router.peerHandshake(
    c.target,
    { noise: c.request, socket, session: c.session },
    address
  )
  if (isDone(c) || c.connect) return

  const payload = await c.handshake.recv(noise)
  if (isDone(c) || !payload) return

  if (payload.version !== 1) {
    maybeDestroyEncryptedSocket(c, SERVER_INCOMPATIBLE())
    return
  }
  if (payload.error !== ERROR.NONE) {
    maybeDestroyEncryptedSocket(c, SERVER_ERROR())
    return
  }
  if (!payload.udx) {
    maybeDestroyEncryptedSocket(c, SERVER_ERROR('Server did not send UDX data'))
    return
  }

  const hs = c.handshake.final()

  c.handshake = null
  c.request = null
  c.requesting = false
  c.connect = {
    relayed,
    relayAddress: address,
    clientAddress,
    serverAddress,
    payload
  }

  c.payload = new SecurePayload(hs.holepunchSecret)

  c.onsocket = function (socket, port, host) {
    if (c.rawStream === null) return // Already hole punched

    if (c.rawStream.connected) {
      const remoteChanging = c.rawStream.changeRemote(socket, c.connect.payload.udx.id, port, host)

      if (remoteChanging) remoteChanging.catch(safetyCatch)
    } else {
      // cache the relay addrs for a future reconnect, we prefer the remote one so they
      // can give us the correct ones from their pov
      if (payload.relayAddresses && payload.relayAddresses.length) {
        c.dht._relayAddressesCache.set(c.id, payload.relayAddresses)
      } else if (c.remoteRelayAddresses.length) {
        c.dht._relayAddressesCache.set(c.id, c.remoteRelayAddresses)
      }

      c.rawStream.connect(socket, c.connect.payload.udx.id, port, host)
      c.encryptedSocket.start(c.rawStream, { handshake: hs })
    }

    if (c.reusableSocket && payload.udx.reusableSocket) {
      c.dht._socketPool.routes.add(c.remotePublicKey, c.rawStream)
    }

    if (c.puncher) {
      c.puncher.onabort = noop
      c.puncher.destroy()
    }

    if (c.passiveConnectTimeout) {
      clearPassiveConnectTimeout(c)
    }

    c.rawStream = null
  }

  if (payload.relayThrough || c.relayThrough) {
    relayConnection(c, c.relayThrough, payload, hs)
  }

  if (c.serverSocket) {
    c.onsocket(c.serverSocket, c.serverAddress.port, c.serverAddress.host)
    return
  }

  if (!relayed) {
    c.onsocket(socket || c.dht.socket, address.port, address.host)
  }

  c.session.destroy()
}

async function updateHolepunch(c, peerAddress, relayAddr, payload) {
  const holepunch = await c.dht._router.peerHolepunch(
    c.target,
    {
      id: c.connect.payload.holepunch.id,
      payload: c.payload.encrypt(payload),
      peerAddress,
      socket: c.puncher.socket,
      session: c.session
    },
    relayAddr
  )

  if (isDone(c)) return null

  const remotePayload = c.payload.decrypt(holepunch.payload)
  if (!remotePayload) {
    throw HOLEPUNCH_INVALID()
  }

  const { error, firewall, punching, addresses, remoteToken } = remotePayload

  if (error === ERROR.TRY_LATER && c.relayToken && payload.punching) {
    return {
      tryLater: true,
      ...holepunch,
      payload: remotePayload
    }
  }

  if (error !== ERROR.NONE) {
    throw REMOTE_ABORTED('Remote aborted with error code ' + error)
  }

  const echoed = !!(remoteToken && payload.token && b4a.equals(remoteToken, payload.token))

  c.puncher.updateRemote({
    punching,
    firewall,
    addresses,
    verified: echoed ? peerAddress.host : null
  })

  return {
    tryLater: false,
    ...holepunch,
    payload: remotePayload
  }
}

async function probeRound(c, serverAddress, serverRelay, retry) {
  // Open a quick low ttl session against what we think is the server
  if (serverAddress) await c.puncher.openSession(serverAddress)

  if (isDone(c)) return null

  const reply = await updateHolepunch(c, serverRelay.peerAddress, serverRelay.relayAddress, {
    error: ERROR.NONE,
    firewall: c.puncher.nat.firewall,
    round: c.round++,
    connected: false,
    punching: false,
    addresses: c.puncher.nat.addresses,
    remoteAddress: serverAddress,
    token: null,
    remoteToken: null
  })

  if (isDone(c) || !reply) return null

  const { peerAddress } = reply
  const { address, token } = reply.payload

  c.puncher.nat.add(reply.to, reply.from)

  // Open another quick low ttl session against what the server says their address is,
  // if they haven't said they are random yet
  if (
    c.puncher.remoteFirewall < FIREWALL.RANDOM &&
    address &&
    address.host &&
    address.port &&
    diffAddress(address, serverAddress)
  ) {
    await c.puncher.openSession(address)
    if (isDone(c)) return null
  }

  // If the remote told us they didn't know their nat firewall yet, give them a chance to figure it out
  // They might say this to see if the "fast mode" punch comes through first.
  if (c.puncher.remoteFirewall === FIREWALL.UNKNOWN) {
    await c.sleeper.pause(1000)
    if (isDone(c)) return null
  }

  let stable = await c.puncher.analyze(false)
  if (isDone(c)) return null

  // If the socket seems unstable, try to make it stable by setting the "allowReopen" flag
  // Mostly relevant for mobile networks
  if (!stable) {
    stable = await c.puncher.analyze(true)
    if (isDone(c)) return null
    if (stable) return probeRound(c, serverAddress, serverRelay, false)
  }

  if ((c.puncher.remoteFirewall === FIREWALL.UNKNOWN || !token) && retry) {
    return probeRound(c, serverAddress, serverRelay, false)
  }

  if (
    c.puncher.remoteFirewall === FIREWALL.UNKNOWN ||
    c.puncher.nat.firewall === FIREWALL.UNKNOWN
  ) {
    await abort(c, serverRelay, HOLEPUNCH_PROBE_TIMEOUT())
    return null
  }

  if (c.puncher.remoteFirewall >= FIREWALL.RANDOM && c.puncher.nat.firewall >= FIREWALL.RANDOM) {
    await abort(c, serverRelay, HOLEPUNCH_DOUBLE_RANDOMIZED_NATS())
    return null
  }

  return { token, peerAddress }
}

async function roundPunch(c, serverAddress, remoteToken, clientRelay, serverRelay, delayed) {
  // We are gossiping our final NAT status to the other peer now
  // so make sure we don't update our local view for now as that can make things weird
  c.puncher.nat.freeze()

  const isRandom =
    c.puncher.remoteFirewall >= FIREWALL.RANDOM || c.puncher.nat.firewall >= FIREWALL.RANDOM
  if (isRandom) {
    while (
      c.dht._randomPunches >= c.dht._randomPunchLimit ||
      Date.now() - c.dht._lastRandomPunch < c.dht._randomPunchInterval
    ) {
      // if no relay can help, bail
      if (!c.relayToken) throw HOLEPUNCH_ABORTED()

      if (!delayed) {
        delayed = true
        await updateHolepunch(c, serverAddress, clientRelay, {
          error: ERROR.NONE,
          firewall: c.puncher.nat.firewall,
          round: c.round++,
          connected: false,
          punching: false,
          addresses: c.puncher.nat.addresses,
          remoteAddress: null,
          token: c.payload.token(serverAddress),
          remoteToken
        })
        if (isDone(c)) return
      }

      await tryLater(c)
      if (isDone(c)) return
    }
  }

  // increment now, so we can commit to punching
  if (isRandom) c.dht._randomPunches++

  let reply

  try {
    // if delayed switch to the servers chosen relay - we validated anyway
    reply = await updateHolepunch(
      c,
      delayed ? serverRelay.peerAddress : serverAddress,
      delayed ? serverRelay.relayAddress : clientRelay,
      {
        error: ERROR.NONE,
        firewall: c.puncher.nat.firewall,
        round: c.round++,
        connected: false,
        punching: true,
        addresses: c.puncher.nat.addresses,
        remoteAddress: null,
        token: delayed ? null : c.payload.token(serverAddress),
        remoteToken
      }
    )
  } finally {
    // decrement as punch increments for us
    if (isRandom) c.dht._randomPunches--
  }

  if (isDone(c)) return
  if (!reply) return

  if (reply.tryLater) {
    await tryLater(c)
    if (isDone(c)) return
    return roundPunch(c, serverAddress, remoteToken, clientRelay, serverRelay, true)
  }

  if (!c.puncher.remoteHolepunching) {
    throw REMOTE_NOT_HOLEPUNCHING()
  }

  if (!(await c.puncher.punch())) {
    throw REMOTE_NOT_HOLEPUNCHABLE()
  }
}

async function tryLater(c) {
  if (!c.relayToken) throw HOLEPUNCH_ABORTED()
  await c.sleeper.pause(10000 + Math.round(Math.random() * 10000))
}

function maybeDestroyEncryptedSocket(c, err) {
  if (isDone(c)) return
  if (c.encryptedSocket.rawStream) return
  if (c.relaySocket) return // waiting for the relay
  if (c.puncher && !c.puncher.destroyed) return // waiting for the puncher
  c.session.destroy()
  c.encryptedSocket.destroy(err)
}

async function abort(c, { peerAddress, relayAddress }, err) {
  try {
    await updateHolepunch(c, peerAddress, relayAddress, {
      error: ERROR.ABORTED,
      firewall: FIREWALL.UNKNOWN,
      round: c.round++,
      connected: false,
      punching: false,
      addresses: null,
      remoteAddress: null,
      token: null,
      remoteToken: null
    })
  } catch (err) {
    safetyCatch(err)
  }

  destroyPuncher(c)
  maybeDestroyEncryptedSocket(c, err)
}

function relayConnection(c, relayThrough, payload, hs) {
  let isInitiator
  let publicKey
  let token

  if (payload.relayThrough) {
    isInitiator = false
    publicKey = payload.relayThrough.publicKey
    token = payload.relayThrough.token
  } else {
    isInitiator = true
    publicKey = relayThrough
    token = c.relayToken
  }

  c.relayToken = token
  c.relaySocket = c.dht.connect(publicKey)
  c.relaySocket.setKeepAlive(c.relayKeepAlive)
  c.relayClient = relay.Client.from(c.relaySocket, { id: c.relaySocket.publicKey })
  c.relayTimeout = setTimeout(onabort, 15000, null)

  c.relayClient.pair(isInitiator, token, c.rawStream).on('error', onabort).on('data', ondata)

  function ondata(remoteId) {
    if (c.relayTimeout) clearRelayTimeout(c)
    if (c.rawStream === null) {
      onabort(null)
      return
    }

    c.relayPaired = true

    const { remotePort, remoteHost, socket } = c.relaySocket.rawStream

    c.rawStream
      .on('close', () => c.relaySocket.destroy())
      .connect(socket, remoteId, remotePort, remoteHost)

    c.encryptedSocket.start(c.rawStream, { handshake: hs })
  }

  function onabort(err) {
    if (c.relayTimeout) clearRelayTimeout(c)
    const socket = c.relaySocket
    c.relayToken = null
    c.relaySocket = null
    if (socket) socket.destroy()
    maybeDestroyEncryptedSocket(c, err || RELAY_ABORTED())
  }
}

function clearPassiveConnectTimeout(c) {
  clearTimeout(c.passiveConnectTimeout)
  c.passiveConnectTimeout = null
}

function clearRelayTimeout(c) {
  clearTimeout(c.relayTimeout)
  c.relayTimeout = null
}

function destroyPuncher(c) {
  if (c.puncher) c.puncher.destroy()
  c.session.destroy()
}

function pickServerRelay(relays, clientRelay) {
  for (const r of relays) {
    if (!diffAddress(r.relayAddress, clientRelay)) return r
  }
  return relays[0]
}

function diffAddress(a, b) {
  return a.host !== b.host || a.port !== b.port
}

function defaultCreateHandshake(keyPair, remotePublicKey) {
  return new NoiseWrap(keyPair, remotePublicKey)
}

function defaultCreateSecretStream(isInitiator, rawStream, opts) {
  return new NoiseSecretStream(isInitiator, rawStream, opts)
}

function onlyNonReserved(addr) {
  return !isReserved(addr.host)
}

function isRelay(relaySocket, socket, port, host) {
  const stream = relaySocket.rawStream
  if (!stream) return false
  if (stream.socket !== socket) return false
  return port === stream.remotePort && host === stream.remoteHost
}

function selectRelay(relayThrough) {
  if (typeof relayThrough === 'function') relayThrough = relayThrough()
  if (relayThrough === null) return null
  if (Array.isArray(relayThrough))
    return relayThrough[Math.floor(Math.random() * relayThrough.length)]
  return relayThrough
}

function isRelayAddress(relayAddresses, data) {
  for (const node of relayAddresses) {
    if (node.host === data.from.host && node.port === data.from.port) return true
  }

  return false
}

function noop() {}
const EventEmitter = require('events')
const b4a = require('b4a')
const errors = require('./errors')

module.exports = class ConnectionPool extends EventEmitter {
  constructor(dht) {
    super()

    this._dht = dht
    this._servers = new Map()
    this._connecting = new Map()
    this._connections = new Map()
  }

  _attachServer(server) {
    const keyString = b4a.toString(server.publicKey, 'hex')

    this._servers.set(keyString, server)

    server
      .on('close', () => {
        this._servers.delete(keyString)
      })
      .on('connection', (socket) => {
        this._attachStream(socket, true)
      })
  }

  _attachStream(stream, opened) {
    const existing = this.get(stream.remotePublicKey)

    if (existing) {
      const keepNew =
        stream.isInitiator === existing.isInitiator ||
        b4a.compare(stream.publicKey, stream.remotePublicKey) > 0

      if (keepNew) {
        let closed = false

        const onclose = () => {
          closed = true
        }

        existing
          .on('error', noop)
          .on('close', () => {
            if (closed) return

            stream.off('error', noop).off('close', onclose)

            this._attachStream(stream, opened)
          })
          .destroy(errors.DUPLICATE_CONNECTION())

        stream.on('error', noop).on('close', onclose)
      } else {
        stream.on('error', noop).destroy(errors.DUPLICATE_CONNECTION())
      }

      return
    }

    const session = new ConnectionRef(this, stream)

    const keyString = b4a.toString(stream.remotePublicKey, 'hex')

    if (opened) {
      this._connections.set(keyString, session)

      stream.on('close', () => {
        this._connections.delete(keyString)
      })

      this.emit('connection', stream, session)
    } else {
      this._connecting.set(keyString, session)

      stream
        .on('error', noop)
        .on('close', () => {
          if (opened) this._connections.delete(keyString)
          else this._connecting.delete(keyString)
        })
        .on('open', () => {
          opened = true

          this._connecting.delete(keyString)
          this._connections.set(keyString, session)

          stream.off('error', noop)

          this.emit('connection', stream, session)
        })
    }

    return session
  }

  get connecting() {
    return this._connecting.size
  }

  get connections() {
    return this._connections.values()
  }

  has(publicKey) {
    const keyString = b4a.toString(publicKey, 'hex')

    return this._connections.has(keyString) || this._connecting.has(keyString)
  }

  get(publicKey) {
    const keyString = b4a.toString(publicKey, 'hex')

    const existing = this._connections.get(keyString) || this._connecting.get(keyString)

    return existing?._stream || null
  }
}

class ConnectionRef {
  constructor(pool, stream) {
    this._pool = pool
    this._stream = stream
    this._refs = 0
  }

  active() {
    this._refs++
  }

  inactive() {
    this._refs--
  }

  release() {
    this._stream.destroy()
  }
}

function noop() {}
const crypto = require('hypercore-crypto')

const COMMANDS = (exports.COMMANDS = {
  PEER_HANDSHAKE: 0,
  PEER_HOLEPUNCH: 1,
  FIND_PEER: 2,
  LOOKUP: 3,
  ANNOUNCE: 4,
  UNANNOUNCE: 5,
  MUTABLE_PUT: 6,
  MUTABLE_GET: 7,
  IMMUTABLE_PUT: 8,
  IMMUTABLE_GET: 9,
  PLUGIN: 10
})

exports.BOOTSTRAP_NODES = global.Pear?.config.dht?.bootstrap || [
  '88.99.3.86@node1.hyperdht.org:49737',
  '142.93.90.113@node2.hyperdht.org:49737',
  '138.68.147.8@node3.hyperdht.org:49737'
]

exports.KNOWN_NODES = global.Pear?.config.dht?.nodes || []

exports.FIREWALL = {
  UNKNOWN: 0,
  OPEN: 1,
  CONSISTENT: 2,
  RANDOM: 3
}

exports.ERROR = {
  // noise / connection related
  NONE: 0,
  ABORTED: 1,
  VERSION_MISMATCH: 2,
  TRY_LATER: 3,
  // dht related
  SEQ_REUSED: 16,
  SEQ_TOO_LOW: 17
}

const [
  NS_ANNOUNCE,
  NS_UNANNOUNCE,
  NS_MUTABLE_PUT,
  NS_PEER_HANDSHAKE,
  NS_PEER_HOLEPUNCH,
  NS_PLUGIN
] = crypto.namespace('hyperswarm/dht', [
  COMMANDS.ANNOUNCE,
  COMMANDS.UNANNOUNCE,
  COMMANDS.MUTABLE_PUT,
  COMMANDS.PEER_HANDSHAKE,
  COMMANDS.PEER_HOLEPUNCH,
  COMMANDS.PLUGIN
])

exports.NS = {
  ANNOUNCE: NS_ANNOUNCE,
  UNANNOUNCE: NS_UNANNOUNCE,
  MUTABLE_PUT: NS_MUTABLE_PUT,
  PEER_HANDSHAKE: NS_PEER_HANDSHAKE,
  PEER_HOLEPUNCH: NS_PEER_HOLEPUNCH,
  PLUGIN: NS_PLUGIN
}
const sodium = require('sodium-universal')
const b4a = require('b4a')

function hash(data) {
  const out = b4a.allocUnsafe(32)
  sodium.crypto_generichash(out, data)
  return out
}

function unslabbedHash(data) {
  const out = b4a.allocUnsafeSlow(32)
  sodium.crypto_generichash(out, data)
  return out
}

function createKeyPair(seed) {
  const publicKey = b4a.alloc(32)
  const secretKey = b4a.alloc(64)
  if (seed) sodium.crypto_sign_seed_keypair(publicKey, secretKey, seed)
  else sodium.crypto_sign_keypair(publicKey, secretKey)
  return { publicKey, secretKey }
}

module.exports = {
  hash,
  unslabbedHash,
  createKeyPair
}
const b4a = require('b4a')
const cenc = require('compact-encoding')

function encodeUnslab(enc, m) {
  // Faster than unslab(c.encode(enc, data)) because it avoids the mem copy.
  // Makes sense to put in compact-encoding when we need it in other modules too
  const state = cenc.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafeSlow(state.end)
  enc.encode(state, m)
  return state.buffer
}

module.exports = {
  encodeUnslab
}
module.exports = class DHTError extends Error {
  constructor(msg, code, fn = DHTError) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'DHTError'
  }

  static BAD_HANDSHAKE_REPLY(msg = 'Bad handshake reply') {
    return new DHTError(msg, 'BAD_HANDSHAKE_REPLY', DHTError.BAD_HANDSHAKE_REPLY)
  }

  static BAD_HOLEPUNCH_REPLY(msg = 'Bad holepunch reply') {
    return new DHTError(msg, 'BAD_HOLEPUNCH_REPLY', DHTError.BAD_HOLEPUNCH_REPLY)
  }

  static HOLEPUNCH_ABORTED(msg = 'Holepunch aborted') {
    return new DHTError(msg, 'HOLEPUNCH_ABORTED', DHTError.HOLEPUNCH_ABORTED)
  }

  static HOLEPUNCH_INVALID(msg = 'Invalid holepunch payload') {
    return new DHTError(msg, 'HOLEPUNCH_INVALID', DHTError.HOLEPUNCH_INVALID)
  }

  static HOLEPUNCH_PROBE_TIMEOUT(msg = 'Holepunching probe did not finish in time') {
    return new DHTError(msg, 'HOLEPUNCH_PROBE_TIMEOUT', DHTError.HOLEPUNCH_PROBE_TIMEOUT)
  }

  static HOLEPUNCH_DOUBLE_RANDOMIZED_NATS(msg = 'Both remote and local NATs are randomized') {
    return new DHTError(
      msg,
      'HOLEPUNCH_DOUBLE_RANDOMIZED_NATS',
      DHTError.HOLEPUNCH_DOUBLE_RANDOMIZED_NATS
    )
  }

  static CANNOT_HOLEPUNCH(msg = 'Cannot holepunch to remote') {
    return new DHTError(msg, 'CANNOT_HOLEPUNCH', DHTError.CANNOT_HOLEPUNCH)
  }

  static REMOTE_NOT_HOLEPUNCHING(msg = 'Remote is not holepunching') {
    return new DHTError(msg, 'REMOTE_NOT_HOLEPUNCHING', DHTError.REMOTE_NOT_HOLEPUNCHING)
  }

  static REMOTE_NOT_HOLEPUNCHABLE(msg = 'Remote is not holepunchable') {
    return new DHTError(msg, 'REMOTE_NOT_HOLEPUNCHABLE', DHTError.REMOTE_NOT_HOLEPUNCHABLE)
  }

  static REMOTE_ABORTED(msg = 'Remote aborted') {
    return new DHTError(msg, 'REMOTE_ABORTED', DHTError.REMOTE_ABORTED)
  }

  static HANDSHAKE_UNFINISHED(msg = 'Handshake did not finish') {
    return new DHTError(msg, 'HANDSHAKE_UNFINISHED', DHTError.HANDSHAKE_UNFINISHED)
  }

  static HANDSHAKE_INVALID(msg = 'Received invalid handshake') {
    return new DHTError(msg, 'HANDSHAKE_INVALID', DHTError.HANDSHAKE_INVALID)
  }

  static ALREADY_LISTENING(msg = 'Already listening') {
    return new DHTError(msg, 'ALREADY_LISTENING', DHTError.ALREADY_LISTENING)
  }

  static KEYPAIR_ALREADY_USED(msg = 'Keypair already used') {
    return new DHTError(msg, 'KEYPAIR_ALREADY_USED', DHTError.KEYPAIR_ALREADY_USED)
  }

  static NODE_DESTROYED(msg = 'Node destroyed') {
    return new DHTError(msg, 'NODE_DESTROYED', DHTError.NODE_DESTROYED)
  }

  static PEER_CONNECTION_FAILED(msg = 'Could not connect to peer') {
    return new DHTError(msg, 'PEER_CONNECTION_FAILED', DHTError.PEER_CONNECTION_FAILED)
  }

  static PEER_NOT_FOUND(msg = 'Peer not found') {
    return new DHTError(msg, 'PEER_NOT_FOUND', DHTError.PEER_NOT_FOUND)
  }

  static STREAM_NOT_CONNECTED(msg = 'Stream is not connected') {
    return new DHTError(msg, 'STREAM_NOT_CONNECTED', DHTError.STREAM_DISCONNECTED)
  }

  static SERVER_INCOMPATIBLE(msg = 'Server is using an incompatible version') {
    return new DHTError(msg, 'SERVER_INCOMPATIBLE', DHTError.SERVER_INCOMPATIBLE)
  }

  static SERVER_ERROR(msg = 'Server returned an error') {
    return new DHTError(msg, 'SERVER_ERROR', DHTError.SERVER_ERROR)
  }

  static DUPLICATE_CONNECTION(msg = 'Duplicate connection') {
    return new DHTError(msg, 'DUPLICATE_CONNECTION', DHTError.DUPLICATE_CONNECTION)
  }

  static RELAY_ABORTED(msg = 'Relay aborted') {
    return new DHTError(msg, 'RELAY_ABORTED', DHTError.RELAY_ABORTED)
  }

  static SUSPENDED(msg = 'Suspended') {
    return new DHTError(msg, 'SUSPENDED', DHTError.SUSPENDED)
  }
}
const b4a = require('b4a')
const Nat = require('./nat')
const Sleeper = require('./sleeper')
const { FIREWALL } = require('./constants')

const BIRTHDAY_SOCKETS = 256
const HOLEPUNCH = b4a.from([0])
const HOLEPUNCH_TTL = 5
const DEFAULT_TTL = 64
const MAX_REOPENS = 3

module.exports = class Holepuncher {
  constructor(dht, session, isInitiator, remoteFirewall = FIREWALL.UNKNOWN) {
    const holder = dht._socketPool.acquire()

    this.dht = dht
    this.session = session

    this.nat = new Nat(dht, session, holder.socket)
    this.nat.autoSample()

    this.isInitiator = isInitiator

    // events
    this.onconnect = noop
    this.onabort = noop

    this.punching = false
    this.connected = false
    this.destroyed = false
    this.randomized = false

    // track remote state
    this.remoteFirewall = remoteFirewall
    this.remoteAddresses = []
    this.remoteHolepunching = false

    this._sleeper = new Sleeper()
    this._reopening = null
    this._timeout = null
    this._punching = null
    this._allHolders = []
    this._holder = this._addRef(holder)
  }

  get socket() {
    return this._holder.socket
  }

  updateRemote({ punching, firewall, addresses, verified }) {
    const remoteAddresses = []

    if (addresses) {
      for (const addr of addresses) {
        remoteAddresses.push({
          host: addr.host,
          port: addr.port,
          verified: verified === addr.host || this._isVerified(addr.host)
        })
      }
    }

    this.remoteFirewall = firewall
    this.remoteAddresses = remoteAddresses
    this.remoteHolepunching = punching
  }

  _isVerified(host) {
    for (const addr of this.remoteAddresses) {
      if (addr.verified && addr.host === host) {
        return true
      }
    }
    return false
  }

  ping(addr, socket = this._holder.socket) {
    return holepunch(socket, addr, false)
  }

  openSession(addr, socket = this._holder.socket) {
    return holepunch(socket, addr, true)
  }

  async analyze(allowReopen) {
    await this.nat.analyzing
    if (this._unstable()) {
      if (!allowReopen) return false
      if (!this._reopening) this._reopening = this._reopen()
      return this._reopening
    }
    return true
  }

  _unstable() {
    // TODO!!: We need an additional heuristic here... If we were NOT random in the past we should also do this.
    const firewall = this.nat.firewall
    return (
      (this.remoteFirewall >= FIREWALL.RANDOM && firewall >= FIREWALL.RANDOM) ||
      firewall === FIREWALL.UNKNOWN
    )
  }

  _reset() {
    const prev = this._holder

    this._allHolders.pop()
    this._holder = this._addRef(this.dht._socketPool.acquire())

    prev.release()
    this.nat.destroy()

    this.nat = new Nat(this.dht, this.session, this._holder.socket)
    // TODO: maybe make auto sampling configurable somehow?
    this.nat.autoSample()
  }

  _addRef(ref) {
    this._allHolders.push(ref)
    ref.onholepunchmessage = (msg, rinfo) => this._onholepunchmessage(msg, rinfo, ref)
    return ref
  }

  _onholepunchmessage(_, addr, ref) {
    if (!this.isInitiator) {
      // TODO: we don't need this if we had a way to connect a socket to many hosts
      holepunch(ref.socket, addr, false) // never fails
      return
    }

    if (this.connected) return

    this.connected = true
    this.punching = false

    for (const r of this._allHolders) {
      if (r === ref) continue
      r.release()
    }

    this._allHolders[0] = ref
    while (this._allHolders.length > 1) this._allHolders.pop()

    this._decrementRandomized()
    this.onconnect(ref.socket, addr.port, addr.host)
  }

  _done() {
    return this.destroyed || this.connected
  }

  async _reopen() {
    for (let i = 0; this._unstable() && i < MAX_REOPENS && !this._done() && !this.punching; i++) {
      this._reset()
      await this.nat.analyzing
    }

    return coerceFirewall(this.nat.firewall) === FIREWALL.CONSISTENT
  }

  punch() {
    if (!this._punching) this._punching = this._punch()
    return this._punching
  }

  async _punch() {
    if (this._done() || !this.remoteAddresses.length) return false

    this.punching = true

    // Coerce into consistency for now. Obvs we could make this this more efficient if we use that info
    // but that's seldomly used since those will just use tcp most of the time.

    const local = coerceFirewall(this.nat.firewall)
    const remote = coerceFirewall(this.remoteFirewall)

    // Note that most of these async functions are meant to run in the background
    // which is why we don't await them here and why they are not allowed to throw

    let remoteVerifiedAddress = null
    for (const addr of this.remoteAddresses) {
      if (addr.verified) {
        remoteVerifiedAddress = addr
        break
      }
    }

    if (local === FIREWALL.CONSISTENT && remote === FIREWALL.CONSISTENT) {
      this.dht.stats.punches.consistent++
      this._consistentProbe()
      return true
    }

    if (!remoteVerifiedAddress) return false

    if (local === FIREWALL.CONSISTENT && remote >= FIREWALL.RANDOM) {
      this.dht.stats.punches.random++
      this._incrementRandomized()
      this._randomProbes(remoteVerifiedAddress)
      return true
    }

    if (local >= FIREWALL.RANDOM && remote === FIREWALL.CONSISTENT) {
      this.dht.stats.punches.random++
      this._incrementRandomized()
      await this._openBirthdaySockets(remoteVerifiedAddress)
      if (this.punching) this._keepAliveRandomNat(remoteVerifiedAddress)
      return true
    }

    return false
  }

  // Note that this never throws so it is safe to run in the background
  async _consistentProbe() {
    // Here we do the sleep first because the "fast open" mode in the server just fired a ping
    if (!this.isInitiator) await this._sleeper.pause(1000)

    let tries = 0

    while (this.punching && tries++ < 10) {
      for (const addr of this.remoteAddresses) {
        // only try unverified addresses every 4 ticks
        if (!addr.verified && (tries & 3) !== 0) continue
        await holepunch(this._holder.socket, addr, false)
      }
      if (this.punching) await this._sleeper.pause(1000)
    }

    this._autoDestroy()
  }

  // Note that this never throws so it is safe to run in the background
  async _randomProbes(remoteAddr) {
    let tries = 1750 // ~35s

    while (this.punching && tries-- > 0) {
      const addr = { host: remoteAddr.host, port: randomPort() }
      await holepunch(this._holder.socket, addr, false)
      if (this.punching) await this._sleeper.pause(20)
    }

    this._autoDestroy()
  }

  // Note that this never throws so it is safe to run in the background
  async _keepAliveRandomNat(remoteAddr) {
    let i = 0
    let lowTTLRounds = 1

    // TODO: experiment with this here. We just bursted all the messages in
    // openOtherSockets to ensure the sockets are open, so it's potentially
    // a good idea to slow down for a bit.
    await this._sleeper.pause(100)

    let tries = 1750 // ~35s

    while (this.punching && tries-- > 0) {
      if (i === this._allHolders.length) {
        i = 0
        if (lowTTLRounds > 0) lowTTLRounds--
      }

      await holepunch(this._allHolders[i++].socket, remoteAddr, lowTTLRounds > 0)
      if (this.punching) await this._sleeper.pause(20)
    }

    this._autoDestroy()
  }

  async _openBirthdaySockets(remoteAddr) {
    while (this.punching && this._allHolders.length < BIRTHDAY_SOCKETS) {
      const ref = this._addRef(this.dht._socketPool.acquire())
      await holepunch(ref.socket, remoteAddr, HOLEPUNCH_TTL)
    }
  }

  _autoDestroy() {
    if (!this.connected) this.destroy()
  }

  _incrementRandomized() {
    if (!this.randomized) {
      this.randomized = true
      this.dht._randomPunches++
    }
  }

  _decrementRandomized() {
    if (this.randomized) {
      this.dht._lastRandomPunch = Date.now()
      this.randomized = false
      this.dht._randomPunches--
    }
  }

  destroy() {
    if (this.destroyed) return
    this.destroyed = true
    this.punching = false

    for (const ref of this._allHolders) ref.release()
    this._allHolders = []
    this.nat.destroy()

    if (!this.connected) {
      this._decrementRandomized()
      this.onabort()
    }
  }

  static ping(socket, addr) {
    return holepunch(socket, addr, false)
  }

  static localAddresses(socket) {
    return localAddresses(socket)
  }

  static matchAddress(myAddresses, externalAddresses) {
    return matchAddress(myAddresses, externalAddresses)
  }
}

function holepunch(socket, addr, lowTTL) {
  return socket.send(HOLEPUNCH, addr.port, addr.host, lowTTL ? HOLEPUNCH_TTL : DEFAULT_TTL)
}

function randomPort() {
  return (1000 + Math.random() * 64536) | 0
}

function coerceFirewall(fw) {
  return fw === FIREWALL.OPEN ? FIREWALL.CONSISTENT : fw
}

function localAddresses(socket) {
  const addrs = []
  const { host, port } = socket.address()

  if (host === '127.0.0.1') return [{ host, port }]

  for (const n of socket.udx.networkInterfaces()) {
    if (n.family !== 4 || n.internal) continue

    addrs.push({ host: n.host, port })
  }

  if (addrs.length === 0) {
    addrs.push({ host: '127.0.0.1', port })
  }

  return addrs
}

function matchAddress(localAddresses, remoteLocalAddresses) {
  if (remoteLocalAddresses.length === 0) return null

  let best = { segment: 1, addr: null }

  for (const localAddress of localAddresses) {
    // => 192.168.122.238
    const a = localAddress.host.split('.')

    for (const remoteAddress of remoteLocalAddresses) {
      // => 192.168.0.23
      // => 192.168.122.1
      const b = remoteAddress.host.split('.')

      // Matches 192.*.*.*
      if (a[0] === b[0]) {
        if (best.segment === 1) best = { segment: 2, addr: remoteAddress }

        // Matches 192.168.*.*
        if (a[1] === b[1]) {
          if (best.segment === 2) best = { segment: 3, addr: remoteAddress }

          // Matches 192.168.122.*
          if (a[2] === b[2]) return remoteAddress
        }
      }
    }
  }

  return best.addr
}

function noop() {}
const c = require('compact-encoding')

const ipv4 = {
  ...c.ipv4Address,
  decode(state) {
    const ip = c.ipv4Address.decode(state)
    return {
      host: ip.host,
      port: ip.port
    }
  }
}

const ipv4Array = c.array(ipv4)

const ipv6 = {
  ...c.ipv6Address,
  decode(state) {
    const ip = c.ipv6Address.decode(state)
    return {
      host: ip.host,
      port: ip.port
    }
  }
}

const ipv6Array = c.array(ipv6)

exports.handshake = {
  preencode(state, m) {
    state.end += 1 + 1 + (m.peerAddress ? 6 : 0) + (m.relayAddress ? 6 : 0)
    c.buffer.preencode(state, m.noise)
  },
  encode(state, m) {
    const flags = (m.peerAddress ? 1 : 0) | (m.relayAddress ? 2 : 0)

    c.uint.encode(state, flags)
    c.uint.encode(state, m.mode)
    c.buffer.encode(state, m.noise)

    if (m.peerAddress) ipv4.encode(state, m.peerAddress)
    if (m.relayAddress) ipv4.encode(state, m.relayAddress)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      mode: c.uint.decode(state),
      noise: c.buffer.decode(state),
      peerAddress: flags & 1 ? ipv4.decode(state) : null,
      relayAddress: flags & 2 ? ipv4.decode(state) : null
    }
  }
}

const relayInfo = {
  preencode(state, m) {
    state.end += 12
  },
  encode(state, m) {
    ipv4.encode(state, m.relayAddress)
    ipv4.encode(state, m.peerAddress)
  },
  decode(state) {
    return {
      relayAddress: ipv4.decode(state),
      peerAddress: ipv4.decode(state)
    }
  }
}

const relayInfoArray = c.array(relayInfo)

const holepunchInfo = {
  preencode(state, m) {
    c.uint.preencode(state, m.id)
    relayInfoArray.preencode(state, m.relays)
  },
  encode(state, m) {
    c.uint.encode(state, m.id)
    relayInfoArray.encode(state, m.relays)
  },
  decode(state) {
    return {
      id: c.uint.decode(state),
      relays: relayInfoArray.decode(state)
    }
  }
}

const udxInfo = {
  preencode(state, m) {
    state.end += 2 // version + features
    c.uint.preencode(state, m.id)
    c.uint.preencode(state, m.seq)
  },
  encode(state, m) {
    c.uint.encode(state, 1)
    c.uint.encode(state, m.reusableSocket ? 1 : 0)
    c.uint.encode(state, m.id)
    c.uint.encode(state, m.seq)
  },
  decode(state) {
    const version = c.uint.decode(state)
    const features = c.uint.decode(state)

    return {
      version,
      reusableSocket: (features & 1) !== 0,
      id: c.uint.decode(state),
      seq: c.uint.decode(state)
    }
  }
}

const secretStreamInfo = {
  preencode(state, m) {
    c.uint.preencode(state, 1)
  },
  encode(state, m) {
    c.uint.encode(state, 1)
  },
  decode(state) {
    return {
      version: c.uint.decode(state)
    }
  }
}

const relayThroughInfo = {
  preencode(state, m) {
    c.uint.preencode(state, 1) // version
    c.uint.preencode(state, 0) // flags
    c.fixed32.preencode(state, m.publicKey)
    c.fixed32.preencode(state, m.token)
  },
  encode(state, m) {
    c.uint.encode(state, 1)
    c.uint.encode(state, 0)
    c.fixed32.encode(state, m.publicKey)
    c.fixed32.encode(state, m.token)
  },
  decode(state) {
    const version = c.uint.decode(state)
    c.uint.decode(state)

    return {
      version,
      publicKey: c.fixed32.decode(state),
      token: c.fixed32.decode(state)
    }
  }
}

exports.noisePayload = {
  preencode(state, m) {
    state.end += 4 // version + flags + error + firewall
    if (m.holepunch) holepunchInfo.preencode(state, m.holepunch)
    if (m.addresses4 && m.addresses4.length) ipv4Array.preencode(state, m.addresses4)
    if (m.addresses6 && m.addresses6.length) ipv6Array.preencode(state, m.addresses6)
    if (m.udx) udxInfo.preencode(state, m.udx)
    if (m.secretStream) secretStreamInfo.preencode(state, m.secretStream)
    if (m.relayThrough) relayThroughInfo.preencode(state, m.relayThrough)
    if (m.relayAddresses) ipv4Array.preencode(state, m.relayAddresses)
  },
  encode(state, m) {
    let flags = 0

    if (m.holepunch) flags |= 1
    if (m.addresses4 && m.addresses4.length) flags |= 2
    if (m.addresses6 && m.addresses6.length) flags |= 4
    if (m.udx) flags |= 8
    if (m.secretStream) flags |= 16
    if (m.relayThrough) flags |= 32
    if (m.relayAddresses) flags |= 64

    c.uint.encode(state, 1) // version
    c.uint.encode(state, flags)
    c.uint.encode(state, m.error)
    c.uint.encode(state, m.firewall)

    if (m.holepunch) holepunchInfo.encode(state, m.holepunch)
    if (m.addresses4 && m.addresses4.length) ipv4Array.encode(state, m.addresses4)
    if (m.addresses6 && m.addresses6.length) ipv6Array.encode(state, m.addresses6)
    if (m.udx) udxInfo.encode(state, m.udx)
    if (m.secretStream) secretStreamInfo.encode(state, m.secretStream)
    if (m.relayThrough) relayThroughInfo.encode(state, m.relayThrough)
    if (m.relayAddresses) ipv4Array.encode(state, m.relayAddresses)
  },
  decode(state) {
    const version = c.uint.decode(state)

    if (version !== 1) {
      // Do not attempt to decode but return this back to the user so they can
      // actually handle it
      return {
        version,
        error: 0,
        firewall: 0,
        holepunch: null,
        addresses4: [],
        addresses6: [],
        udx: null,
        secretStream: null,
        relayThrough: null,
        relayAddresses: null
      }
    }

    const flags = c.uint.decode(state)

    return {
      version,
      error: c.uint.decode(state),
      firewall: c.uint.decode(state),
      holepunch: (flags & 1) !== 0 ? holepunchInfo.decode(state) : null,
      addresses4: (flags & 2) !== 0 ? ipv4Array.decode(state) : [],
      addresses6: (flags & 4) !== 0 ? ipv6Array.decode(state) : [],
      udx: (flags & 8) !== 0 ? udxInfo.decode(state) : null,
      secretStream: (flags & 16) !== 0 ? secretStreamInfo.decode(state) : null,
      relayThrough: (flags & 32) !== 0 ? relayThroughInfo.decode(state) : null,
      relayAddresses: (flags & 64) !== 0 ? ipv4Array.decode(state) : null
    }
  }
}

exports.holepunch = {
  preencode(state, m) {
    state.end += 2
    c.uint.preencode(state, m.id)
    c.buffer.preencode(state, m.payload)
    if (m.peerAddress) ipv4.preencode(state, m.peerAddress)
  },
  encode(state, m) {
    const flags = m.peerAddress ? 1 : 0
    c.uint.encode(state, flags)
    c.uint.encode(state, m.mode)
    c.uint.encode(state, m.id)
    c.buffer.encode(state, m.payload)
    if (m.peerAddress) ipv4.encode(state, m.peerAddress)
  },
  decode(state) {
    const flags = c.uint.decode(state)
    return {
      mode: c.uint.decode(state),
      id: c.uint.decode(state),
      payload: c.buffer.decode(state),
      peerAddress: flags & 1 ? ipv4.decode(state) : null
    }
  }
}

exports.holepunchPayload = {
  preencode(state, m) {
    state.end += 4 // flags + error + firewall + round
    if (m.addresses) ipv4Array.preencode(state, m.addresses)
    if (m.remoteAddress) state.end += 6
    if (m.token) state.end += 32
    if (m.remoteToken) state.end += 32
  },
  encode(state, m) {
    const flags =
      (m.connected ? 1 : 0) |
      (m.punching ? 2 : 0) |
      (m.addresses ? 4 : 0) |
      (m.remoteAddress ? 8 : 0) |
      (m.token ? 16 : 0) |
      (m.remoteToken ? 32 : 0)

    c.uint.encode(state, flags)
    c.uint.encode(state, m.error)
    c.uint.encode(state, m.firewall)
    c.uint.encode(state, m.round)

    if (m.addresses) ipv4Array.encode(state, m.addresses)
    if (m.remoteAddress) ipv4.encode(state, m.remoteAddress)
    if (m.token) c.fixed32.encode(state, m.token)
    if (m.remoteToken) c.fixed32.encode(state, m.remoteToken)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      error: c.uint.decode(state),
      firewall: c.uint.decode(state),
      round: c.uint.decode(state),
      connected: (flags & 1) !== 0,
      punching: (flags & 2) !== 0,
      addresses: (flags & 4) !== 0 ? ipv4Array.decode(state) : null,
      remoteAddress: (flags & 8) !== 0 ? ipv4.decode(state) : null,
      token: (flags & 16) !== 0 ? c.fixed32.decode(state) : null,
      remoteToken: (flags & 32) !== 0 ? c.fixed32.decode(state) : null
    }
  }
}

const peer = (exports.peer = {
  preencode(state, m) {
    state.end += 32
    ipv4Array.preencode(state, m.relayAddresses)
  },
  encode(state, m) {
    c.fixed32.encode(state, m.publicKey)
    ipv4Array.encode(state, m.relayAddresses)
  },
  decode(state) {
    return {
      publicKey: c.fixed32.decode(state),
      relayAddresses: ipv4Array.decode(state)
    }
  }
})

const peers = (exports.peers = c.array(peer))

const rawPeers = c.array(c.raw)

exports.lookupRawReply = {
  preencode(state, m) {
    rawPeers.preencode(state, m.peers)
    c.uint.preencode(state, m.bump)
  },
  encode(state, m) {
    rawPeers.encode(state, m.peers)
    c.uint.encode(state, m.bump)
  },
  decode(state) {
    return {
      peers: peers.decode(state),
      bump: state.start < state.end ? c.uint.decode(state) : 0
    }
  }
}

exports.announce = {
  preencode(state, m) {
    state.end++ // flags
    if (m.peer) peer.preencode(state, m.peer)
    if (m.refresh) state.end += 32
    if (m.signature) state.end += 64
    if (m.bump) c.uint.preencode(state, m.bump)
  },
  encode(state, m) {
    const flags = (m.peer ? 1 : 0) | (m.refresh ? 2 : 0) | (m.signature ? 4 : 0) | (m.bump ? 8 : 0)
    c.uint.encode(state, flags)
    if (m.peer) peer.encode(state, m.peer)
    if (m.refresh) c.fixed32.encode(state, m.refresh)
    if (m.signature) c.fixed64.encode(state, m.signature)
    if (m.bump) c.uint.encode(state, m.bump)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      peer: (flags & 1) !== 0 ? peer.decode(state) : null,
      refresh: (flags & 2) !== 0 ? c.fixed32.decode(state) : null,
      signature: (flags & 4) !== 0 ? c.fixed64.decode(state) : null,
      bump: (flags & 8) !== 0 ? c.uint.decode(state) : 0
    }
  }
}

exports.mutableSignable = {
  preencode(state, m) {
    c.uint.preencode(state, m.seq)
    c.buffer.preencode(state, m.value)
  },
  encode(state, m) {
    c.uint.encode(state, m.seq)
    c.buffer.encode(state, m.value)
  },
  decode(state) {
    return {
      seq: c.uint.decode(state),
      value: c.buffer.decode(state)
    }
  }
}

exports.mutablePutRequest = {
  preencode(state, m) {
    c.fixed32.preencode(state, m.publicKey)
    c.uint.preencode(state, m.seq)
    c.buffer.preencode(state, m.value)
    c.fixed64.preencode(state, m.signature)
  },
  encode(state, m) {
    c.fixed32.encode(state, m.publicKey)
    c.uint.encode(state, m.seq)
    c.buffer.encode(state, m.value)
    c.fixed64.encode(state, m.signature)
  },
  decode(state) {
    return {
      publicKey: c.fixed32.decode(state),
      seq: c.uint.decode(state),
      value: c.buffer.decode(state),
      signature: c.fixed64.decode(state)
    }
  }
}

exports.mutableGetResponse = {
  preencode(state, m) {
    c.uint.preencode(state, m.seq)
    c.buffer.preencode(state, m.value)
    c.fixed64.preencode(state, m.signature)
  },
  encode(state, m) {
    c.uint.encode(state, m.seq)
    c.buffer.encode(state, m.value)
    c.fixed64.encode(state, m.signature)
  },
  decode(state) {
    return {
      seq: c.uint.decode(state),
      value: c.buffer.decode(state),
      signature: c.fixed64.decode(state)
    }
  }
}

exports.pluginRequest = {
  preencode(state, m) {
    c.string.preencode(state, m.plugin)
    c.uint.preencode(state, m.version)
    c.uint.preencode(state, m.command)
    c.buffer.preencode(state, m.value)
  },
  encode(state, m) {
    c.string.encode(state, m.plugin)
    c.uint.encode(state, m.version)
    c.uint.encode(state, m.command)
    c.buffer.encode(state, m.value)
  },
  decode(state) {
    return {
      plugin: c.string.decode(state),
      version: c.uint.decode(state),
      command: c.uint.decode(state),
      value: c.buffer.decode(state)
    }
  }
}
const { FIREWALL } = require('../lib/constants')

module.exports = class Nat {
  constructor(dht, session, socket) {
    this._samplesHost = []
    this._samplesFull = []
    this._visited = new Map()
    this._resolve = null
    this._minSamples = 4
    this._autoSampling = false

    this.dht = dht
    this.session = session
    this.socket = socket

    this.sampled = 0
    this.firewall = dht.firewalled ? FIREWALL.UNKNOWN : FIREWALL.OPEN
    this.addresses = null

    this.analyzing = new Promise((resolve) => {
      this._resolve = resolve
    })
  }

  autoSample(retry = true) {
    if (this._autoSampling) return
    this._autoSampling = true

    const self = this
    const socket = this.socket
    const maxPings = this._minSamples

    let skip = this.dht.nodes.length >= 8 ? 5 : 0
    let pending = 0

    // TODO: it would be best to pick the nodes to help us based on latency to us
    // That should reduce connect latency in general. We should investigate tracking that later on.

    // TODO 2: try to pick nodes with different IPs as well, as that'll help multi IP cell connections...
    // If we expose this from the nat sampler then the DHT should be able to help us filter out scams as well...

    for (
      let node = this.dht.nodes.latest;
      node && this.sampled + pending < maxPings;
      node = node.prev
    ) {
      if (skip > 0) {
        skip--
        continue
      }

      const ref = node.host + ':' + node.port

      if (this._visited.has(ref)) continue
      this._visited.set(ref, 1)

      pending++
      this.session.ping(node, { socket, retry: false }).then(onpong, onskip)
    }

    pending++
    onskip()

    function onpong(res) {
      self.add(res.to, res.from)
      onskip()
    }

    function onskip() {
      if (--pending === 0 && self.sampled < self._minSamples) {
        if (retry) {
          self._autoSampling = false
          self.autoSample(false)
          return
        }
        self._resolve()
      }
    }
  }

  destroy() {
    this._autoSampling = true
    this._minSamples = 0
    this._resolve()
  }

  unfreeze() {
    this.frozen = false
    this._updateFirewall()
    this._updateAddresses()
  }

  freeze() {
    this.frozen = true
  }

  _updateFirewall() {
    if (!this.dht.firewalled) {
      this.firewall = FIREWALL.OPEN
      return
    }

    if (this.sampled < 3) return

    const max = this._samplesFull[0].hits

    if (max >= 3) {
      this.firewall = FIREWALL.CONSISTENT
      return
    }

    if (max === 1) {
      this.firewall = FIREWALL.RANDOM
      return
    }

    // else max === 2

    // 1 host, >= 4 total samples ie, 2 bad ones -> random
    if (this._samplesHost.length === 1 && this.sampled > 3) {
      this.firewall = FIREWALL.RANDOM
      return
    }

    // double hit on two different ips -> assume consistent
    if (this._samplesHost.length > 1 && this._samplesFull[1].hits > 1) {
      this.firewall = FIREWALL.CONSISTENT
      return
    }

    // (4 is just means - all the samples we expect) - no decision - assume random
    if (this.sampled > 4) {
      this.firewall = FIREWALL.RANDOM
    }
  }

  _updateAddresses() {
    if (this.firewall === FIREWALL.UNKNOWN) {
      this.addresses = null
      return
    }

    if (this.firewall === FIREWALL.RANDOM) {
      this.addresses = [this._samplesHost[0]]
      return
    }

    if (this.firewall === FIREWALL.CONSISTENT) {
      this.addresses = []
      for (const addr of this._samplesFull) {
        if (addr.hits >= 2 || this.addresses.length < 2) this.addresses.push(addr)
      }
    }
  }

  update() {
    if (this.dht.firewalled && this.firewall === FIREWALL.OPEN) {
      this.firewall = FIREWALL.UNKNOWN
    }
    this._updateFirewall()
    this._updateAddresses()
  }

  add(addr, from) {
    const ref = from.host + ':' + from.port

    if (this._visited.get(ref) === 2) return
    this._visited.set(ref, 2)

    addSample(this._samplesHost, addr.host, 0)
    addSample(this._samplesFull, addr.host, addr.port)

    if ((++this.sampled >= 3 || !this.dht.firewalled) && !this.frozen) {
      this.update()
    }

    if (this.firewall === FIREWALL.CONSISTENT || this.firewall === FIREWALL.OPEN) {
      this._resolve()
    } else if (this.sampled >= this._minSamples) {
      this._resolve()
    }
  }
}

function addSample(samples, host, port) {
  for (let i = 0; i < samples.length; i++) {
    const s = samples[i]

    if (s.port !== port || s.host !== host) continue
    s.hits++

    for (; i > 0; i--) {
      const prev = samples[i - 1]
      if (prev.hits >= s.hits) return
      samples[i - 1] = s
      samples[i] = prev
    }

    return
  }

  samples.push({
    host,
    port,
    hits: 1
  })
}
const NoiseSecretStream = require('@hyperswarm/secret-stream')
const NoiseHandshake = require('noise-handshake')
const curve = require('noise-curve-ed')
const c = require('compact-encoding')
const b4a = require('b4a')
const sodium = require('sodium-universal')
const m = require('./messages')
const { NS } = require('./constants')
const { HANDSHAKE_UNFINISHED } = require('./errors')

const NOISE_PROLOUGE = NS.PEER_HANDSHAKE

module.exports = class NoiseWrap {
  constructor(keyPair, remotePublicKey) {
    this.isInitiator = !!remotePublicKey
    this.remotePublicKey = remotePublicKey
    this.keyPair = keyPair
    this.handshake = new NoiseHandshake('IK', this.isInitiator, keyPair, { curve })
    this.handshake.initialise(NOISE_PROLOUGE, remotePublicKey)
  }

  send(payload) {
    const buf = c.encode(m.noisePayload, payload)
    return this.handshake.send(buf)
  }

  recv(buf) {
    const payload = c.decode(m.noisePayload, this.handshake.recv(buf))
    this.remotePublicKey = b4a.toBuffer(this.handshake.rs)
    return payload
  }

  final() {
    if (!this.handshake.complete) throw HANDSHAKE_UNFINISHED()

    const holepunchSecret = b4a.allocUnsafe(32)

    sodium.crypto_generichash(holepunchSecret, NS.PEER_HOLEPUNCH, this.handshake.hash)

    return {
      isInitiator: this.isInitiator,
      publicKey: this.keyPair.publicKey,
      streamId: this.streamId,
      remotePublicKey: this.remotePublicKey,
      remoteId: NoiseSecretStream.id(this.handshake.hash, !this.isInitiator),
      holepunchSecret,
      hash: b4a.toBuffer(this.handshake.hash),
      rx: b4a.toBuffer(this.handshake.rx),
      tx: b4a.toBuffer(this.handshake.tx)
    }
  }
}
const c = require('compact-encoding')
const sodium = require('sodium-universal')
const RecordCache = require('record-cache')
const Cache = require('xache')
const b4a = require('b4a')
const unslab = require('unslab')

const { encodeUnslab } = require('./encode')
const m = require('./messages')
const { NS, ERROR } = require('./constants')

const EMPTY = b4a.alloc(0)
const TMP = b4a.allocUnsafe(32)
const MAX_BUMP_DRIFT = 60_000

module.exports = class Persistent {
  constructor(dht, opts) {
    this.dht = dht
    this.records = new RecordCache(opts.records)
    this.bumps = new Cache(opts.bumps)
    this.refreshes = new Cache(opts.refreshes)
    this.mutables = new Cache(opts.mutables)
    this.immutables = new Cache(opts.immutables)
  }

  onlookup(req) {
    if (!req.target) return

    const k = b4a.toString(req.target, 'hex')
    const records = this.records.get(k, 20)
    const bump = this.bumps.get(k) || 0
    const fwd = this.dht._router.get(k)

    if (fwd && records.length < 20) records.push(fwd.record)

    req.reply(records.length ? c.encode(m.lookupRawReply, { peers: records, bump }) : null)
  }

  onfindpeer(req) {
    if (!req.target) return
    const fwd = this.dht._router.get(req.target)
    req.reply(fwd ? fwd.record : null)
  }

  unannounce(target, publicKey) {
    const k = b4a.toString(target, 'hex')
    sodium.crypto_generichash(TMP, publicKey)

    if (b4a.equals(TMP, target)) this.dht._router.delete(k)
    this.records.remove(k, publicKey)
  }

  onunannounce(req) {
    if (!req.target || !req.token) return

    const unann = decode(m.announce, req.value)
    if (unann === null) return

    const { peer, signature } = unann
    if (!peer || !signature) return

    const signable = annSignable(req.target, req.token, this.dht.id, unann, NS.UNANNOUNCE)

    if (!sodium.crypto_sign_verify_detached(signature, signable, peer.publicKey)) {
      return
    }

    this.unannounce(req.target, peer.publicKey)
    req.reply(null, { token: false, closerNodes: false })
  }

  _onrefresh(token, req) {
    sodium.crypto_generichash(TMP, token)
    const activeRefresh = b4a.toString(TMP, 'hex')

    const r = this.refreshes.get(activeRefresh)
    if (!r) return

    const { announceSelf, k, record } = r
    const publicKey = record.subarray(0, 32)

    if (announceSelf) {
      this.dht._router.set(k, {
        relay: req.from,
        record,
        onconnect: null,
        onholepunch: null
      })
      this.records.remove(k, publicKey)
    } else {
      this.records.add(k, publicKey, record)
    }

    this.refreshes.delete(activeRefresh)
    this.refreshes.set(b4a.toString(token, 'hex'), r)

    req.reply(null, { token: false, closerNodes: false })
  }

  onannounce(req) {
    if (!req.target || !req.token || !this.dht.id) return

    const ann = decode(m.announce, req.value)
    if (ann === null) return

    const { peer, refresh, signature, bump } = ann

    if (!peer) {
      if (!refresh) return
      this._onrefresh(refresh, req)
      return
    }

    const signable = annSignable(req.target, req.token, this.dht.id, ann, NS.ANNOUNCE)

    if (!signature || !sodium.crypto_sign_verify_detached(signature, signable, peer.publicKey)) {
      return
    }

    // TODO: it would be potentially be more optimal to allow more than 3 addresses here for a findPeer response
    // and only use max 3 for a lookup reply
    if (peer.relayAddresses.length > 3) {
      peer.relayAddresses = peer.relayAddresses.slice(0, 3)
    }

    sodium.crypto_generichash(TMP, peer.publicKey)

    const k = b4a.toString(req.target, 'hex')
    const announceSelf = b4a.equals(TMP, req.target)
    const record = encodeUnslab(m.peer, peer)

    if (announceSelf) {
      this.dht._router.set(k, {
        relay: req.from,
        record,
        onconnect: null,
        onholepunch: null
      })
      this.records.remove(k, peer.publicKey)
    } else {
      const currentBump = this.bumps.get(k) || 0
      if (bump > currentBump && bump <= Date.now() + MAX_BUMP_DRIFT) this.bumps.set(k, bump)
      this.records.add(k, peer.publicKey, record)
    }

    if (refresh) {
      this.refreshes.set(b4a.toString(refresh, 'hex'), { k, record, announceSelf })
    }

    req.reply(null, { token: false, closerNodes: false })
  }

  onmutableget(req) {
    if (!req.target || !req.value) return

    let seq = 0
    try {
      seq = c.decode(c.uint, req.value)
    } catch {
      return
    }

    const k = b4a.toString(req.target, 'hex')
    const value = this.mutables.get(k)

    if (!value) {
      req.reply(null)
      return
    }

    const localSeq = c.decode(c.uint, value)
    req.reply(localSeq < seq ? null : value)
  }

  onmutableput(req) {
    if (!req.target || !req.token || !req.value) return

    const p = decode(m.mutablePutRequest, req.value)
    if (!p) return

    const { publicKey, seq, value, signature } = p

    const hash = b4a.allocUnsafe(32)
    sodium.crypto_generichash(hash, publicKey)
    if (!b4a.equals(hash, req.target)) return

    if (!value || !verifyMutable(signature, seq, value, publicKey)) return

    const k = b4a.toString(hash, 'hex')
    const local = this.mutables.get(k)

    if (local) {
      const existing = c.decode(m.mutableGetResponse, local)
      if (existing.value && existing.seq === seq && b4a.compare(value, existing.value) !== 0) {
        req.error(ERROR.SEQ_REUSED)
        return
      }
      if (seq < existing.seq) {
        req.error(ERROR.SEQ_TOO_LOW)
        return
      }
    }

    this.mutables.set(k, encodeUnslab(m.mutableGetResponse, { seq, value, signature }))
    req.reply(null)
  }

  onimmutableget(req) {
    if (!req.target) return

    const k = b4a.toString(req.target, 'hex')
    const value = this.immutables.get(k)

    req.reply(value || null)
  }

  onimmutableput(req) {
    if (!req.target || !req.token || !req.value) return

    const hash = b4a.alloc(32)
    sodium.crypto_generichash(hash, req.value)
    if (!b4a.equals(hash, req.target)) return

    const k = b4a.toString(hash, 'hex')
    this.immutables.set(k, unslab(req.value))

    req.reply(null)
  }

  onplugin(req) {
    if (!req.value) return

    const plugreq = decode(m.pluginRequest, req.value)
    if (plugreq === null) return

    const p = this.dht.plugins.get(plugreq.plugin)
    if (!p || p.version !== plugreq.version) return

    p.onrequest(plugreq, req)
  }

  destroy() {
    this.records.destroy()
    this.refreshes.destroy()
    this.mutables.destroy()
    this.immutables.destroy()
  }

  static signMutable(seq, value, keyPair) {
    const signable = b4a.allocUnsafe(32 + 32)
    const hash = signable.subarray(32)

    signable.set(NS.MUTABLE_PUT, 0)

    sodium.crypto_generichash(hash, c.encode(m.mutableSignable, { seq, value }))
    return sign(signable, keyPair)
  }

  static verifyMutable(signature, seq, value, publicKey) {
    return verifyMutable(signature, seq, value, publicKey)
  }

  static signAnnounce(target, token, id, ann, keyPair) {
    return sign(annSignable(target, token, id, ann, NS.ANNOUNCE), keyPair)
  }

  static signUnannounce(target, token, id, ann, keyPair) {
    return sign(annSignable(target, token, id, ann, NS.UNANNOUNCE), keyPair)
  }
}

function verifyMutable(signature, seq, value, publicKey) {
  const signable = b4a.allocUnsafe(32 + 32)
  const hash = signable.subarray(32)

  signable.set(NS.MUTABLE_PUT, 0)

  sodium.crypto_generichash(hash, c.encode(m.mutableSignable, { seq, value }))
  return sodium.crypto_sign_verify_detached(signature, signable, publicKey)
}

function annSignable(target, token, id, ann, ns) {
  const signable = b4a.allocUnsafe(32 + 32)
  const hash = signable.subarray(32)

  signable.set(ns, 0)

  sodium.crypto_generichash_batch(hash, [
    target,
    id,
    token,
    c.encode(m.peer, ann.peer), // note that this is the partial encoding of the announce message so we could just use that for perf
    ann.refresh || EMPTY
  ])

  return signable
}

function sign(signable, keyPair) {
  if (keyPair.sign) {
    return keyPair.sign(signable)
  }
  const secretKey = keyPair.secretKey ? keyPair.secretKey : keyPair
  const signature = b4a.allocUnsafe(64)
  sodium.crypto_sign_detached(signature, signable, secretKey)
  return signature
}

function decode(enc, val) {
  try {
    return val && c.decode(enc, val)
  } catch (err) {
    return null
  }
}
module.exports = class RawStreamSet {
  constructor(dht) {
    this._dht = dht

    this._prefix = 16 - 1 // 16 is the default stream-set side in udx
    this._streams = new Map()
  }

  get size() {
    return this._streams.size
  }

  [Symbol.iterator]() {
    return this._streams.values()
  }

  add(opts) {
    const self = this

    // TODO: we should prob have a udx helper for id generation, given the slight complexity
    // of the below. requires a PRNG in udx tho.

    let id = 0

    while (true) {
      id = (Math.random() * 0x100000000) >>> 0

      if (this._streams.has(id & this._prefix)) continue
      break
    }

    // always have ~50% change of rolling a free one
    if (2 * this._streams.size >= this._prefix) {
      // ie 0b11111 = 0b1111 + 1 + 0b1111
      this._prefix = 2 * this._prefix + 1

      // move the prefixes over
      const next = new Map()
      for (const stream of this._streams.values()) {
        next.set(stream.id & this._prefix, stream)
      }
      this._streams = next
    }

    const stream = this._dht.udx.createStream(id, opts)
    this._streams.set(id & this._prefix, stream)

    stream.on('close', onclose)

    return stream

    function onclose() {
      self._streams.delete(id & self._prefix)
    }
  }

  async clear() {
    const destroying = []

    for (const stream of this._streams.values()) {
      destroying.push(new Promise((resolve) => stream.once('close', resolve).destroy()))
    }

    await Promise.allSettled(destroying)
  }
}
const c = require('compact-encoding')
const Cache = require('xache')
const safetyCatch = require('safety-catch')
const b4a = require('b4a')
const { handshake, holepunch } = require('./messages')
const { COMMANDS } = require('./constants')
const { BAD_HANDSHAKE_REPLY, BAD_HOLEPUNCH_REPLY } = require('./errors')

const FROM_CLIENT = 0
const FROM_SERVER = 1
const FROM_RELAY = 2
const FROM_SECOND_RELAY = 3
const REPLY = 4

// TODO: While the current design is very trustless in regards to clients/servers trusting the DHT,
// we should add a bunch of rate limits everywhere, especially including here to avoid bad users
// using a DHT node to relay traffic indiscriminately using the connect/holepunch messages.
// That's mostly from an abuse POV as none of the messsages do amplication.

module.exports = class Router {
  constructor(dht, opts) {
    this.dht = dht
    this.forwards = new Cache(opts.forwards)
  }

  set(target, state) {
    if (state.onpeerhandshake) {
      this.forwards.retain(toString(target), state)
    } else {
      this.forwards.set(toString(target), state)
    }
  }

  get(target) {
    return this.forwards.get(toString(target))
  }

  delete(target) {
    this.forwards.delete(toString(target))
  }

  destroy() {
    this.forwards.destroy()
  }

  async peerHandshake(target, { noise, peerAddress, relayAddress, socket, session }, to) {
    const dht = this.dht

    const requestValue = c.encode(handshake, {
      mode: FROM_CLIENT,
      noise,
      peerAddress,
      relayAddress
    })

    const res = await dht.request(
      { command: COMMANDS.PEER_HANDSHAKE, target, value: requestValue },
      to,
      { socket, session }
    )

    const hs = decode(handshake, res.value)
    if (
      !hs ||
      hs.mode !== REPLY ||
      to.host !== res.from.host ||
      to.port !== res.from.port ||
      !hs.noise
    ) {
      throw BAD_HANDSHAKE_REPLY()
    }

    return {
      noise: hs.noise,
      relayed: !!hs.peerAddress,
      serverAddress: hs.peerAddress || to,
      clientAddress: res.to
    }
  }

  async onpeerhandshake(req) {
    const hs = req.value && decode(handshake, req.value)
    if (!hs) return

    const { mode, noise, peerAddress, relayAddress } = hs

    const state = req.target && this.get(req.target)
    const isServer = !!(state && state.onpeerhandshake)
    const relay = state && state.relay

    if (isServer) {
      let reply = null
      try {
        reply = noise && (await state.onpeerhandshake({ noise, peerAddress }, req))
      } catch (e) {
        safetyCatch(e)
        return
      }
      if (!reply || !reply.noise) return
      const opts = { socket: reply.socket, closerNodes: false, token: false }

      switch (mode) {
        case FROM_CLIENT: {
          req.reply(
            c.encode(handshake, { mode: REPLY, noise: reply.noise, peerAddress: null }),
            opts
          )
          return
        }
        case FROM_RELAY: {
          req.relay(
            c.encode(handshake, { mode: FROM_SERVER, noise: reply.noise, peerAddress }),
            req.from,
            opts
          )
          return
        }
        case FROM_SECOND_RELAY: {
          if (!relayAddress) return
          req.relay(
            c.encode(handshake, { mode: FROM_SERVER, noise: reply.noise, peerAddress }),
            relayAddress,
            opts
          )
          return // eslint-disable-line
        }
      }
    } else {
      switch (mode) {
        case FROM_CLIENT: {
          // TODO: if no relay is known route closer to the target instead of timing out
          if (!noise) return
          if (!relay && !relayAddress) {
            // help the user route
            req.reply(null, { token: false, closerNodes: true })
            return
          }
          req.relay(
            c.encode(handshake, {
              mode: FROM_RELAY,
              noise,
              peerAddress: req.from,
              relayAddress: null
            }),
            relayAddress || relay
          )
          return
        }
        case FROM_RELAY: {
          if (!relay || !noise) return
          req.relay(
            c.encode(handshake, {
              mode: FROM_SECOND_RELAY,
              noise,
              peerAddress,
              relayAddress: req.from
            }),
            relay
          )
          return
        }
        case FROM_SERVER: {
          if (!peerAddress || !noise) return
          req.reply(
            c.encode(handshake, { mode: REPLY, noise, peerAddress: req.from, relayAddress: null }),
            { to: peerAddress, closerNodes: false, token: false }
          )
          return // eslint-disable-line
        }
      }
    }
  }

  async peerHolepunch(target, { id, payload, peerAddress, socket, session }, to) {
    const dht = this.dht
    const requestValue = c.encode(holepunch, {
      mode: FROM_CLIENT,
      id,
      payload,
      peerAddress
    })

    const res = await dht.request(
      { command: COMMANDS.PEER_HOLEPUNCH, target, value: requestValue },
      to,
      { socket, session }
    )

    const hp = decode(holepunch, res.value)
    if (!hp || hp.mode !== REPLY || to.host !== res.from.host || to.port !== res.from.port) {
      throw BAD_HOLEPUNCH_REPLY()
    }

    return {
      from: res.from,
      to: res.to,
      payload: hp.payload,
      peerAddress: hp.peerAddress || to
    }
  }

  async onpeerholepunch(req) {
    const hp = req.value && decode(holepunch, req.value)
    if (!hp) return

    const { mode, id, payload, peerAddress } = hp

    const state = req.target && this.get(req.target)
    const isServer = !!(state && state.onpeerholepunch)
    const relay = state && state.relay

    switch (mode) {
      case FROM_CLIENT: {
        if (!peerAddress && !relay) return
        req.relay(
          c.encode(holepunch, { mode: FROM_RELAY, id, payload, peerAddress: req.from }),
          peerAddress || relay
        )
        return
      }
      case FROM_RELAY: {
        if (!isServer || !peerAddress) return
        let reply = null
        try {
          reply = await state.onpeerholepunch({ id, payload, peerAddress }, req)
        } catch (e) {
          safetyCatch(e)
          return
        }
        if (!reply) return
        const opts = { socket: reply.socket, closerNodes: false, token: false }
        req.relay(
          c.encode(holepunch, { mode: FROM_SERVER, id: 0, payload: reply.payload, peerAddress }),
          req.from,
          opts
        )
        return
      }
      case FROM_SERVER: {
        req.reply(c.encode(holepunch, { mode: REPLY, id, payload, peerAddress: req.from }), {
          to: peerAddress,
          closerNodes: false,
          token: false
        })
        return // eslint-disable-line
      }
    }
  }
}

function decode(enc, val) {
  try {
    return c.decode(enc, val)
  } catch {
    return null
  }
}

function toString(t) {
  return typeof t === 'string' ? t : b4a.toString(t, 'hex')
}
const sodium = require('sodium-universal')
const b4a = require('b4a')
const { holepunchPayload } = require('./messages')

module.exports = class HolepunchPayload {
  constructor(holepunchSecret) {
    this._sharedSecret = holepunchSecret
    this._localSecret = b4a.allocUnsafe(32)

    sodium.randombytes_buf(this._localSecret)
  }

  decrypt(buffer) {
    const state = { start: 24, end: buffer.byteLength - 16, buffer }

    if (state.end <= state.start) return null

    const nonce = buffer.subarray(0, 24)
    const msg = state.buffer.subarray(state.start, state.end)
    const cipher = state.buffer.subarray(state.start)

    if (!sodium.crypto_secretbox_open_easy(msg, cipher, nonce, this._sharedSecret)) return null

    try {
      return holepunchPayload.decode(state)
    } catch {
      return null
    }
  }

  encrypt(payload) {
    const state = { start: 24, end: 24, buffer: null }
    holepunchPayload.preencode(state, payload)
    state.buffer = b4a.allocUnsafe(state.end + 16)

    const nonce = state.buffer.subarray(0, 24)
    const msg = state.buffer.subarray(state.start, state.end)
    const cipher = state.buffer.subarray(state.start)

    holepunchPayload.encode(state, payload)
    sodium.randombytes_buf(nonce)
    sodium.crypto_secretbox_easy(cipher, msg, nonce, this._sharedSecret)

    return state.buffer
  }

  token(addr) {
    const out = b4a.allocUnsafe(32)
    sodium.crypto_generichash(out, b4a.from(addr.host), this._localSecret)
    return out
  }
}
const DONE = Promise.resolve(true)
const DESTROYED = Promise.resolve(false)

module.exports = class Semaphore {
  constructor(limit = 1) {
    this.limit = limit
    this.active = 0
    this.waiting = []

    this.flushedPromise = null
    this.flushedResolve = null

    this.destroyed = false

    this._onwait = this._queueWaiting.bind(this)
    this._onflush = this._queueFlushed.bind(this)
  }

  _queueWaiting(resolve) {
    this.waiting.push(resolve)
  }

  _queueFlushed(resolve) {
    this.flushedResolve = resolve
  }

  wait() {
    if (this.destroyed === true) return DESTROYED

    if (this.active < this.limit && this.waiting.length === 0) {
      this.active++
      return DONE
    }

    return new Promise(this._onwait)
  }

  signal() {
    if (this.destroyed === true) return

    this.active--
    while (this.active < this.limit && this.waiting.length > 0 && this.destroyed === false) {
      this.active++
      this.waiting.shift()(true)
    }

    if (this.active === 0 && this.flushedResolve) {
      const resolve = this.flushedResolve
      this.flushedResolve = null
      this.flushedPromise = null
      resolve(true)
    }
  }

  async flush() {
    if (this.destroyed === true) return
    if (this.active === 0) return
    if (this.flushedPromise) return this.flushedPromise
    this.flushedPromise = new Promise(this._onflush)
    return this.flushedPromise
  }

  destroy() {
    this.destroyed = true
    this.active = 0
    while (this.waiting.length) this.waiting.pop()(false)
    if (this.flushedResolve) this.flushedResolve(false)
  }
}
const { EventEmitter } = require('events')
const safetyCatch = require('safety-catch')
const NoiseSecretStream = require('@hyperswarm/secret-stream')
const b4a = require('b4a')
const relay = require('blind-relay')
const NoiseWrap = require('./noise-wrap')
const Announcer = require('./announcer')
const { FIREWALL, ERROR } = require('./constants')
const { unslabbedHash } = require('./crypto')
const SecurePayload = require('./secure-payload')
const Holepuncher = require('./holepuncher')
const { isPrivate } = require('bogon')
const { ALREADY_LISTENING, NODE_DESTROYED, KEYPAIR_ALREADY_USED } = require('./errors')

const HANDSHAKE_CLEAR_WAIT = 10000
const HANDSHAKE_INITIAL_TIMEOUT = 10000

module.exports = class Server extends EventEmitter {
  constructor(dht, opts = {}) {
    super()

    this.dht = dht
    this.target = null

    this.closed = false
    this.firewall = opts.firewall || (() => false)
    this.holepunch = opts.holepunch || (() => true)
    this.relayThrough = opts.relayThrough || null
    this.relayKeepAlive = opts.relayKeepAlive || 5000
    this.pool = opts.pool || null
    this.createHandshake = opts.createHandshake || defaultCreateHandshake
    this.createSecretStream = opts.createSecretStream || defaultCreateSecretStream
    this.suspended = false
    this.handshakeClearWait = opts.handshakeClearWait || HANDSHAKE_CLEAR_WAIT

    this._shareLocalAddress = opts.shareLocalAddress !== false
    this._reusableSocket = !!opts.reusableSocket
    this._neverPunch = opts.holepunch === false // useful for fully disabling punching
    this._keyPair = null
    this._announcer = null
    this._connects = new Map()
    this._holepunches = []
    this._listening = null
    this._closing = null
  }

  get listening() {
    return this._listening !== null
  }

  get publicKey() {
    return this._keyPair && this._keyPair.publicKey
  }

  get relayAddresses() {
    return this._announcer ? this._announcer.relayAddresses : []
  }

  onconnection(encryptedSocket) {
    this.emit('connection', encryptedSocket)
  }

  async suspend({ log = noop } = {}) {
    log('Suspending hyperdht server')
    if (this._listening !== null) await this._listening
    log('Suspending hyperdht server (post listening)')
    this.suspended = true
    this._clearAll()
    return this._announcer ? this._announcer.suspend({ log }) : Promise.resolve()
  }

  async resume() {
    if (this._listening !== null) await this._listening
    this.suspended = false
    return this._announcer ? this._announcer.resume() : Promise.resolve()
  }

  address() {
    if (!this._keyPair) return null

    return {
      publicKey: this._keyPair.publicKey,
      host: this.dht.host,
      port: this.dht.port
    }
  }

  close() {
    if (this._closing) return this._closing
    this._closing = this._close()
    return this._closing
  }

  _gc() {
    this.dht.listening.delete(this)
    if (this.target) this.dht._router.delete(this.target)
  }

  async _stopListening() {
    try {
      if (this._announcer) await this._announcer.stop()
    } catch {
      // ignore
    }

    this._announcer = null
    this._listening = null
    this._keyPair = null
  }

  async _close() {
    if (this._listening === null) {
      this.closed = true
      this.emit('close')
      return
    }

    try {
      await this._listening
    } catch (err) {
      safetyCatch(err)
    }

    this._gc()
    this._clearAll()

    await this._stopListening()

    this.closed = true
    this.emit('close')
  }

  _clearAll() {
    while (this._holepunches.length > 0) {
      const h = this._holepunches.pop()
      if (h && h.puncher) h.puncher.destroy()
      if (h && h.clearing) clearTimeout(h.clearing)
      if (h && h.prepunching) clearTimeout(h.prepunching)
      if (h && h.rawStream) h.rawStream.destroy()
    }

    this._connects.clear()
  }

  async listen(keyPair = this.dht.defaultKeyPair, opts = {}) {
    if (this._listening !== null) throw ALREADY_LISTENING()
    if (this.dht.destroyed) throw NODE_DESTROYED()

    this._listening = this._listen(keyPair, opts)
    await this._listening
    return this
  }

  async _listen(keyPair, opts) {
    // From now on, the DHT object which created me is responsible for closing me
    this.dht.listening.add(this)

    try {
      await this.dht.bind()
      if (this._closing) return

      for (const s of this.dht.listening) {
        if (s._keyPair && b4a.equals(s._keyPair.publicKey, keyPair.publicKey)) {
          throw KEYPAIR_ALREADY_USED()
        }
      }

      this.target = unslabbedHash(keyPair.publicKey)
      this._keyPair = keyPair
      this._announcer = new Announcer(this.dht, keyPair, this.target, opts)

      this.dht._router.set(this.target, {
        relay: null,
        record: this._announcer.record,
        onpeerhandshake: this._onpeerhandshake.bind(this),
        onpeerholepunch: this._onpeerholepunch.bind(this)
      })

      // warm it up for now
      this._localAddresses().catch(safetyCatch)

      await this._announcer.start()
    } catch (err) {
      await this._stopListening()
      this._gc()
      throw err
    }

    if (this._closing) return
    if (this.suspended) await this._announcer.suspend()

    if (this._closing) return
    if (this.dht.destroyed) throw NODE_DESTROYED()

    if (this.pool) this.pool._attachServer(this)

    this.emit('listening')
  }

  refresh() {
    if (this._announcer && !this.suspended) this._announcer.refresh()
  }

  notifyOnline() {
    if (this._announcer) this._announcer.online.notify()
  }

  _localAddresses() {
    return this.dht.validateLocalAddresses(Holepuncher.localAddresses(this.dht.io.serverSocket))
  }

  async _addHandshake(k, noise, clientAddress, { from, to: serverAddress, socket }, direct) {
    let id = this._holepunches.indexOf(null)
    if (id === -1) id = this._holepunches.push(null) - 1

    const hs = {
      round: 0,
      reply: null,
      puncher: null,
      payload: null,
      rawStream: null,
      encryptedSocket: null,
      prepunching: null,
      firewalled: true,
      clearing: null,
      onsocket: null,
      aborted: false,

      // Relay state
      relayTimeout: null,
      relayToken: null,
      relaySocket: null,
      relayClient: null,
      relayPaired: false
    }

    this._holepunches[id] = hs

    const handshake = this.createHandshake(this._keyPair, null)

    let remotePayload
    try {
      remotePayload = await handshake.recv(noise)
    } catch (err) {
      safetyCatch(err)
      this._clearLater(hs, id, k)
      return null
    }

    if (this._closing || this.suspended) return null

    try {
      hs.firewalled = await this.firewall(handshake.remotePublicKey, remotePayload, clientAddress)
    } catch (err) {
      safetyCatch(err)
    }

    if (this._closing || this.suspended) return null

    if (hs.firewalled) {
      this._clearLater(hs, id, k)
      return null
    }

    const error =
      remotePayload.version === 1
        ? remotePayload.udx
          ? ERROR.NONE
          : ERROR.ABORTED
        : ERROR.VERSION_MISMATCH

    const addresses = []
    const ourRemoteAddr = this.dht.remoteAddress()
    const ourLocalAddrs = this._shareLocalAddress ? await this._localAddresses() : null

    if (this._closing || this.suspended) return null

    if (ourRemoteAddr) addresses.push(ourRemoteAddr)
    if (ourLocalAddrs) addresses.push(...ourLocalAddrs)

    if (error === ERROR.NONE) {
      hs.rawStream = this.dht.createRawStream({
        framed: true,
        firewall(socket, port, host) {
          if (!(port > 0 && port < 65536)) return true

          // Check if the traffic originated from the socket on which we're expecting relay traffic. If so,
          // we haven't hole punched yet and the other side is just sending us traffic through the relay.
          if (hs.relaySocket && isRelay(hs.relaySocket, socket, port, host)) {
            return false
          }

          hs.onsocket(socket, port, host)
          return false
        }
      })

      hs.rawStream.on('error', autoDestroy)

      // Handles the case where onsocket is never called, but the stream got setup
      // This can happen on a relayed connection which never connects directly
      // (onsocket is called there only when the direct connection is established)
      const onrawstreamclose = () => {
        if (this._closing) return
        this._clearLater(hs, id, k)
      }
      hs.rawStream.on('close', onrawstreamclose)

      hs.onsocket = (socket, port, host) => {
        if (hs.rawStream === null) return // Already hole punched

        this._clearLater(hs, id, k)

        if (hs.prepunching) {
          clearTimeout(hs.prepunching)
          hs.prepunching = null
        }

        if (this._reusableSocket && remotePayload.udx.reusableSocket) {
          this.dht._socketPool.routes.add(handshake.remotePublicKey, hs.rawStream)
        }

        hs.rawStream.removeListener('error', autoDestroy)
        hs.rawStream.removeListener('close', onrawstreamclose)

        if (hs.rawStream.connected) {
          const remoteChanging = hs.rawStream.changeRemote(socket, remotePayload.udx.id, port, host)

          if (remoteChanging) remoteChanging.catch(safetyCatch)
        } else {
          hs.rawStream.connect(socket, remotePayload.udx.id, port, host)
          hs.encryptedSocket = this.createSecretStream(false, hs.rawStream, {
            handshake: h,
            keepAlive: this.dht.connectionKeepAlive
          })

          this.onconnection(hs.encryptedSocket)
        }

        if (hs.puncher) {
          hs.puncher.onabort = noop
          hs.puncher.destroy()
        }

        hs.rawStream = null
      }

      function autoDestroy() {
        if (hs.puncher) hs.puncher.destroy()
      }
    }

    const relayAddresses = this.relayAddresses
    const relayThrough = selectRelay(this.relayThrough)

    if (relayThrough) hs.relayToken = relay.token()

    try {
      hs.reply = await handshake.send({
        error,
        firewall: ourRemoteAddr ? FIREWALL.OPEN : FIREWALL.UNKNOWN,
        holepunch: ourRemoteAddr ? null : { id, relays: this._announcer.relays },
        addresses4: addresses,
        addresses6: null,
        udx: {
          reusableSocket: this._reusableSocket,
          id: hs.rawStream ? hs.rawStream.id : 0,
          seq: 0
        },
        secretStream: {},
        relayThrough: relayThrough ? { publicKey: relayThrough, token: hs.relayToken } : null,
        relayAddresses: relayAddresses.length ? relayAddresses : null
      })
    } catch (err) {
      safetyCatch(err)
      if (hs.rawStream) hs.rawStream.destroy()
      this._clearLater(hs, id, k)
      return null
    }

    if (this._closing || this.suspended) {
      if (hs.rawStream) hs.rawStream.destroy()
      return null
    }

    const h = handshake.final()

    if (error !== ERROR.NONE) {
      if (hs.rawStream) hs.rawStream.destroy()
      this._clearLater(hs, id, k)
      return hs
    }

    if (remotePayload.firewall === FIREWALL.OPEN || direct) {
      const sock = direct ? socket : this.dht.socket
      this.dht.stats.punches.open++
      hs.onsocket(sock, clientAddress.port, clientAddress.host)
      return hs
    }

    if (relayThrough || remotePayload.relayThrough) {
      this._relayConnection(hs, relayThrough, remotePayload, h)
    }

    const onabort = () => {
      hs.aborted = true
      if (hs.prepunching) clearTimeout(hs.prepunching)
      hs.prepunching = null
      if (hs.rawStream.destroyed) {
        this._clearLater(hs, id, k)
        return
      }

      hs.rawStream.on('close', () => this._clearLater(hs, id, k))
      if (hs.relayToken === null) hs.rawStream.destroy()
    }

    if (!direct && clientAddress.host === serverAddress.host) {
      const clientAddresses = remotePayload.addresses4.filter(onlyPrivateHosts)

      if (clientAddresses.length > 0 && this._shareLocalAddress) {
        const myAddresses = await this._localAddresses()
        const addr = Holepuncher.matchAddress(myAddresses, clientAddresses)

        if (addr) {
          hs.prepunching = setTimeout(onabort, HANDSHAKE_INITIAL_TIMEOUT)
          return hs
        }
      }
    }

    if (this._closing || this.suspended) return null

    if (ourRemoteAddr || this._neverPunch) {
      hs.prepunching = setTimeout(onabort, HANDSHAKE_INITIAL_TIMEOUT)
      return hs
    }

    hs.payload = new SecurePayload(h.holepunchSecret)
    hs.puncher = new Holepuncher(this.dht, this.dht.session(), false, remotePayload.firewall)

    hs.puncher.onconnect = hs.onsocket
    hs.puncher.onabort = onabort
    hs.prepunching = setTimeout(hs.puncher.destroy.bind(hs.puncher), HANDSHAKE_INITIAL_TIMEOUT)

    return hs
  }

  _clearLater(hs, id, k) {
    if (hs.clearing) return
    hs.clearing = setTimeout(() => this._clear(hs, id, k), this.handshakeClearWait)
  }

  _clear(hs, id, k) {
    if (id >= this._holepunches.length || this._holepunches[id] !== hs) return
    if (hs.clearing) clearTimeout(hs.clearing)

    this._holepunches[id] = null
    while (
      this._holepunches.length > 0 &&
      this._holepunches[this._holepunches.length - 1] === null
    ) {
      this._holepunches.pop()
    }
    this._connects.delete(k)
  }

  async _onpeerhandshake({ noise, peerAddress }, req) {
    const k = b4a.toString(noise, 'hex')

    // The next couple of statements MUST run within the same tick to prevent
    // a malicious peer from flooding us with handshakes.
    let p = this._connects.get(k)
    if (!p) {
      p = this._addHandshake(k, noise, peerAddress || req.from, req, !peerAddress)
      this._connects.set(k, p)
    }

    const h = await p
    if (!h) return null

    if (this._closing !== null || this.suspended) return null

    return { socket: h.puncher && h.puncher.socket, noise: h.reply }
  }

  async _onpeerholepunch({ id, peerAddress, payload }, req) {
    const h = id < this._holepunches.length ? this._holepunches[id] : null
    if (!h) return null

    if (!peerAddress || this._closing !== null || this.suspended) return null

    const p = h.puncher
    if (!p || !p.socket) return this._abort(h) // not opened

    const remotePayload = h.payload.decrypt(payload)
    if (!remotePayload) return null

    const isServerRelay = this._announcer.isRelay(req.from)
    const { error, firewall, round, punching, addresses, remoteAddress, remoteToken } =
      remotePayload

    if (error !== ERROR.NONE) {
      // We actually do not need to set the round here, but just do it for consistency.
      if (round >= h.round) h.round = round
      return this._abort(h)
    }

    const token = h.payload.token(peerAddress)
    const echoed = isServerRelay && !!remoteToken && b4a.equals(token, remoteToken)

    // Update our heuristics here
    if (req.socket === p.socket) {
      p.nat.add(req.to, req.from)
    }

    if (round >= h.round) {
      h.round = round
      p.updateRemote({ punching, firewall, addresses, verified: echoed ? peerAddress.host : null })
    }

    // Wait for the analyzer to reach a conclusion...
    let stable = await p.analyze(false)
    if (p.destroyed) return null

    if (!p.remoteHolepunching && !stable) {
      stable = await p.analyze(true)
      if (p.destroyed) return null
      if (!stable) return this._abort(h)
    }

    // Fast mode! If we are consistent and the remote has opened a session to us (remoteAddress)
    // then fire a quick punch back. Note the await here just waits for the udp socket to flush.
    if (
      isConsistent(p.nat.firewall) &&
      remoteAddress &&
      hasSameAddr(p.nat.addresses, remoteAddress)
    ) {
      await p.ping(peerAddress)
      if (p.destroyed) return null
    }

    // Remote said they are punching (or willing to), so we will punch as well.
    // Note that this returns when the punching has STARTED, so no guarantee
    // we will have a connection after this promise etc.
    if (p.remoteHolepunching) {
      // TODO: still continue here if a local connection might work, but then do not holepunch...
      if (!this.holepunch(p.remoteFirewall, p.nat.firewall, p.remoteAddresses, p.nat.addresses)) {
        return p.destroyed ? null : this._abort(h)
      }

      if (h.prepunching) {
        clearTimeout(h.prepunching)
        h.prepunching = null
      }

      if (p.remoteFirewall >= FIREWALL.RANDOM || p.nat.firewall >= FIREWALL.RANDOM) {
        if (
          this.dht._randomPunches >= this.dht._randomPunchLimit ||
          Date.now() - this.dht._lastRandomPunch < this.dht._randomPunchInterval
        ) {
          if (!h.relayToken) return this._abort(h, ERROR.TRY_LATER)
          return {
            socket: p.socket,
            payload: h.payload.encrypt({
              error: ERROR.TRY_LATER,
              firewall: p.nat.firewall,
              round: h.round,
              connected: p.connected,
              punching: p.punching,
              addresses: p.nat.addresses,
              remoteAddress: null,
              token: isServerRelay ? token : null,
              remoteToken: remotePayload.token
            })
          }
        }
      }

      const punching = await p.punch()
      if (p.destroyed) return null
      if (!punching) return this._abort(h)
    }

    // Freeze that analysis as soon as we have a result we are giving to the other peer
    if (p.nat.firewall !== FIREWALL.UNKNOWN) {
      p.nat.freeze()
    }

    return {
      socket: p.socket,
      payload: h.payload.encrypt({
        error: ERROR.NONE,
        firewall: p.nat.firewall,
        round: h.round,
        connected: p.connected,
        punching: p.punching,
        addresses: p.nat.addresses,
        remoteAddress: null,
        token: isServerRelay ? token : null,
        remoteToken: remotePayload.token
      })
    }
  }

  _abort(h, error = ERROR.ABORTED) {
    if (!h.payload) {
      if (h.puncher) h.puncher.destroy()
      return null
    }

    const payload = h.payload.encrypt({
      error,
      firewall: FIREWALL.UNKNOWN,
      round: h.round,
      connected: false,
      punching: false,
      addresses: null,
      remoteAddress: null,
      token: null,
      remoteToken: null
    })

    h.puncher.destroy()

    return { socket: this.dht.socket, payload }
  }

  _relayConnection(hs, relayThrough, remotePayload, h) {
    this.dht.stats.relaying.attempts++

    let isInitiator
    let publicKey
    let token

    if (relayThrough) {
      isInitiator = true
      publicKey = relayThrough
      token = hs.relayToken
    } else {
      isInitiator = false
      publicKey = remotePayload.relayThrough.publicKey
      token = remotePayload.relayThrough.token
    }

    hs.relayToken = token
    hs.relaySocket = this.dht.connect(publicKey)
    hs.relaySocket.setKeepAlive(this.relayKeepAlive)
    hs.relayClient = relay.Client.from(hs.relaySocket, { id: hs.relaySocket.publicKey })
    hs.relayTimeout = setTimeout(onabort, 15000)

    hs.relayClient
      .pair(isInitiator, token, hs.rawStream)
      .on('error', onabort)
      .on('data', (remoteId) => {
        if (hs.relayTimeout) clearRelayTimeout(hs)
        if (hs.rawStream === null) {
          onabort(null)
          return
        }

        hs.relayPaired = true
        this.dht.stats.relaying.successes++

        if (hs.prepunching) clearTimeout(hs.prepunching)
        hs.prepunching = null

        const { remotePort, remoteHost, socket } = hs.relaySocket.rawStream

        hs.rawStream
          .on('close', () => hs.relaySocket.destroy())
          .connect(socket, remoteId, remotePort, remoteHost)

        hs.encryptedSocket = this.createSecretStream(false, hs.rawStream, { handshake: h })

        this.onconnection(hs.encryptedSocket)
      })

    const dht = this.dht
    function onabort() {
      if (!hs.relayPaired) dht.stats.relaying.aborts++
      if (hs.relayTimeout) clearRelayTimeout(hs)
      const socket = hs.relaySocket
      hs.relayToken = null
      hs.relaySocket = null
      if (socket) socket.destroy()
      if (hs.aborted && hs.rawStream) hs.rawStream.destroy()
    }
  }
}

function clearRelayTimeout(hs) {
  clearTimeout(hs.relayTimeout)
  hs.relayTimeout = null
}

function isConsistent(fw) {
  return fw === FIREWALL.OPEN || fw === FIREWALL.CONSISTENT
}

function hasSameAddr(addrs, other) {
  if (addrs === null) return false

  for (const addr of addrs) {
    if (addr.port === other.port && addr.host === other.host) return true
  }
  return false
}

function defaultCreateHandshake(keyPair, remotePublicKey) {
  return new NoiseWrap(keyPair, remotePublicKey)
}

function defaultCreateSecretStream(isInitiator, rawStream, opts) {
  return new NoiseSecretStream(isInitiator, rawStream, opts)
}

function onlyPrivateHosts(addr) {
  return isPrivate(addr.host)
}

function isRelay(relaySocket, socket, port, host) {
  const stream = relaySocket.rawStream
  if (!stream) return false
  if (stream.socket !== socket) return false
  return port === stream.remotePort && host === stream.remoteHost
}

function selectRelay(relayThrough) {
  if (typeof relayThrough === 'function') relayThrough = relayThrough()
  if (relayThrough === null) return null
  if (Array.isArray(relayThrough)) {
    return relayThrough[Math.floor(Math.random() * relayThrough.length)]
  }
  return relayThrough
}

function noop() {}
module.exports = class Sleeper {
  constructor() {
    this._timeout = null
    this._resolve = null

    this._start = (resolve) => {
      this._resolve = resolve
    }

    this._trigger = () => {
      if (this._resolve === null) return
      const resolve = this._resolve
      this._timeout = null
      this._resolve = null
      resolve()
    }
  }

  pause(ms) {
    const p = new Promise(this._start)
    if (this._timeout !== null) {
      clearTimeout(this._timeout)
      this._trigger()
    }
    this._timeout = setTimeout(this._trigger, ms)
    return p
  }

  resume() {
    if (this._timeout !== null) {
      clearTimeout(this._timeout)
      this._trigger()
    }
  }
}
const b4a = require('b4a')

const LINGER_TIME = 3000

module.exports = class SocketPool {
  constructor(dht, host) {
    this._dht = dht
    this._sockets = new Map()
    this._lingering = new Set() // updated by the ref
    this._host = host

    this.routes = new SocketRoutes(this)
  }

  _onmessage(ref, data, address) {
    this._dht.onmessage(ref.socket, data, address)
  }

  _add(ref) {
    this._sockets.set(ref.socket, ref)
  }

  _remove(ref) {
    this._sockets.delete(ref.socket)
    this._lingering.delete(ref)
  }

  lookup(socket) {
    return this._sockets.get(socket) || null
  }

  setReusable(socket, bool) {
    const ref = this.lookup(socket)
    if (ref) ref.reusable = bool
  }

  acquire() {
    // TODO: Enable socket reuse
    return new SocketRef(this)
  }

  async destroy() {
    const closing = []

    for (const ref of this._sockets.values()) {
      ref._unlinger()
      closing.push(ref.socket.close())
    }

    await Promise.allSettled(closing)
  }
}

class SocketRoutes {
  constructor(pool) {
    this._pool = pool
    this._routes = new Map()
  }

  add(publicKey, rawStream) {
    if (rawStream.socket) this._onconnect(publicKey, rawStream)
    else rawStream.on('connect', this._onconnect.bind(this, publicKey, rawStream))
  }

  get(publicKey) {
    const id = b4a.toString(publicKey, 'hex')
    const route = this._routes.get(id)
    if (!route) return null
    return route
  }

  _onconnect(publicKey, rawStream) {
    const id = b4a.toString(publicKey, 'hex')
    const socket = rawStream.socket

    let route = this._routes.get(id)

    if (!route) {
      const gc = () => {
        if (this._routes.get(id) === route) this._routes.delete(id)
        socket.removeListener('close', gc)
      }

      route = {
        socket,
        address: { host: rawStream.remoteHost, port: rawStream.remotePort },
        gc
      }

      this._routes.set(id, route)
      socket.on('close', gc)
    }

    this._pool.setReusable(socket, true)

    rawStream.on('error', () => {
      this._pool.setReusable(socket, false)
      if (!route) route = this._routes.get(id)
      if (route && route.socket === socket) route.gc()
    })
  }
}

// TODO: we should just make some "user data" object on udx to allow to attach this info
class SocketRef {
  constructor(pool) {
    this._pool = pool

    // Events
    this.onholepunchmessage = noop

    // Whether it should teardown immediately or wait a bit
    this.reusable = false

    this.socket = pool._dht.udx.createSocket()
    this.socket
      .on('close', this._onclose.bind(this))
      .on('message', this._onmessage.bind(this))
      .on('idle', this._onidle.bind(this))
      .on('busy', this._onbusy.bind(this))
      .bind(0, this._pool._host)

    this._refs = 1
    this._released = false
    this._closed = false

    this._timeout = null
    this._wasBusy = false

    this._pool._add(this)
  }

  _onclose() {
    this._pool._remove(this)
  }

  _onmessage(data, address) {
    if (data.byteLength > 1) {
      this._pool._onmessage(this, data, address)
    } else {
      this.onholepunchmessage(data, address, this)
    }
  }

  _onidle() {
    this._closeMaybe()
  }

  _onbusy() {
    this._wasBusy = true
    this._unlinger()
  }

  _reset() {
    this.onholepunchmessage = noop
  }

  _closeMaybe() {
    if (this._refs === 0 && this.socket.idle && !this._timeout) this._close()
  }

  _lingeringClose() {
    this._pool._lingering.delete(this)
    this._timeout = null
    this._closeMaybe()
  }

  _close() {
    this._unlinger()

    if (this.reusable && this._wasBusy) {
      this._wasBusy = false
      this._pool._lingering.add(this)
      this._timeout = setTimeout(this._lingeringClose.bind(this), LINGER_TIME)
      return
    }

    this._closed = true
    this.socket.close()
  }

  _unlinger() {
    if (this._timeout !== null) {
      clearTimeout(this._timeout)
      this._pool._lingering.delete(this)
      this._timeout = null
    }
  }

  get free() {
    return this._refs === 0
  }

  active() {
    this._refs++
    this._unlinger()
  }

  inactive() {
    this._refs--
    this._closeMaybe()
  }

  address() {
    return this.socket.address()
  }

  release() {
    if (this._released) return

    this._released = true
    this._reset()

    this._refs--
    this._closeMaybe()
  }
}

function noop() {}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return uint24.decode(state) + 0x1000000 * uint32.decode(state)
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return uint32.decode(state) + 0x100000000 * uint32.decode(state)
  }
})

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "2.19.2",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    if (b.byteLength === 0) return null
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "hyperdht",
  "version": "6.31.0",
  "description": "The DHT powering Hyperswarm",
  "main": "index.js",
  "browser": "browser.js",
  "bin": {
    "hyperdht": "./bin.js"
  },
  "files": [
    "index.js",
    "browser.js",
    "testnet.js",
    "bin.js",
    "lib/**.js"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    },
    "child_process": {
      "bare": "bare-node-child-process",
      "default": "child_process"
    }
  },
  "dependencies": {
    "@hyperswarm/secret-stream": "^6.6.2",
    "b4a": "^1.3.1",
    "bare-events": "^2.2.0",
    "blind-relay": "^1.3.0",
    "bogon": "^1.0.0",
    "compact-encoding": "^2.4.1",
    "dht-rpc": "^6.15.1",
    "hypercore-crypto": "^3.3.0",
    "hypercore-id-encoding": "^1.2.0",
    "hyperdht-address": "^1.0.1",
    "noise-curve-ed": "^2.0.0",
    "noise-handshake": "^4.0.0",
    "record-cache": "^1.1.1",
    "safety-catch": "^1.0.1",
    "signal-promise": "^1.0.3",
    "sodium-universal": "^5.0.1",
    "streamx": "^2.16.1",
    "unslab": "^1.3.0",
    "xache": "^1.1.0"
  },
  "devDependencies": {
    "bare-node-child-process": "^1.0.1",
    "brittle": "^3.0.0",
    "graceful-goodbye": "^1.3.0",
    "newline-decoder": "^1.0.2",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "test": "prettier --check . && node test/all.js",
    "test:bare": "bare test/all.js",
    "test:generate": "brittle -r test/all.js test/*.js",
    "integration": "brittle test/integration/*.js",
    "end-to-end": "brittle test/end-to-end/*.js"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "directories": {
    "lib": "lib",
    "test": "test"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/hyperdht.git"
  },
  "keywords": [],
  "bugs": {
    "url": "https://github.com/holepunchto/hyperdht/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperdht#readme"
}
const LE = (exports.LE =
  new Uint8Array(new Uint16Array([0xff]).buffer)[0] === 0xff)

exports.BE = !LE
const b4a = require('b4a')

const { BE } = require('./endian')

exports.state = function (start = 0, end = 0, buffer = null) {
  return { start, end, buffer }
}

const raw = (exports.raw = require('./raw'))

const uint = (exports.uint = {
  preencode(state, n) {
    state.end += n <= 0xfc ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : 9
  },
  encode(state, n) {
    if (n <= 0xfc) uint8.encode(state, n)
    else if (n <= 0xffff) {
      state.buffer[state.start++] = 0xfd
      uint16.encode(state, n)
    } else if (n <= 0xffffffff) {
      state.buffer[state.start++] = 0xfe
      uint32.encode(state, n)
    } else {
      state.buffer[state.start++] = 0xff
      uint64.encode(state, n)
    }
  },
  decode(state) {
    const a = uint8.decode(state)
    if (a <= 0xfc) return a
    if (a === 0xfd) return uint16.decode(state)
    if (a === 0xfe) return uint32.decode(state)
    return uint64.decode(state)
  }
})

const uint8 = (exports.uint8 = {
  preencode(state, n) {
    state.end += 1
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
  },
  decode(state) {
    if (state.start >= state.end) throw new Error('Out of bounds')
    return state.buffer[state.start++]
  }
})

const uint16 = (exports.uint16 = {
  preencode(state, n) {
    state.end += 2
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
  },
  decode(state) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] + state.buffer[state.start++] * 0x100
  }
})

const uint24 = (exports.uint24 = {
  preencode(state, n) {
    state.end += 3
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
  },
  decode(state) {
    if (state.end - state.start < 3) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000
    )
  }
})

const uint32 = (exports.uint32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    validateUint(n)
    state.buffer[state.start++] = n
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n >>> 16
    state.buffer[state.start++] = n >>> 24
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      state.buffer[state.start++] * 0x100 +
      state.buffer[state.start++] * 0x10000 +
      state.buffer[state.start++] * 0x1000000
    )
  }
})

const uint40 = (exports.uint40 = {
  preencode(state, n) {
    state.end += 5
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100)
    uint8.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 5) throw new Error('Out of bounds')
    return uint8.decode(state) + 0x100 * uint32.decode(state)
  }
})

const uint48 = (exports.uint48 = {
  preencode(state, n) {
    state.end += 6
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x10000)
    uint16.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 6) throw new Error('Out of bounds')
    return uint16.decode(state) + 0x10000 * uint32.decode(state)
  }
})

const uint56 = (exports.uint56 = {
  preencode(state, n) {
    state.end += 7
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x1000000)
    uint24.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 7) throw new Error('Out of bounds')
    return uint24.decode(state) + 0x1000000 * uint32.decode(state)
  }
})

const uint64 = (exports.uint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    validateUint(n)
    const r = Math.floor(n / 0x100000000)
    uint32.encode(state, n)
    uint32.encode(state, r)
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    return uint32.decode(state) + 0x100000000 * uint32.decode(state)
  }
})

const int = (exports.int = zigZagInt(uint))
exports.int8 = zigZagInt(uint8)
exports.int16 = zigZagInt(uint16)
exports.int24 = zigZagInt(uint24)
exports.int32 = zigZagInt(uint32)
exports.int40 = zigZagInt(uint40)
exports.int48 = zigZagInt(uint48)
exports.int56 = zigZagInt(uint56)
exports.int64 = zigZagInt(uint64)

const biguint64 = (exports.biguint64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setBigUint64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const n = view.getBigUint64(0, true) // little endian
    state.start += 8
    return n
  }
})

exports.bigint64 = zigZagBigInt(biguint64)

const biguint = (exports.biguint = {
  preencode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.preencode(state, len)
    state.end += 8 * len
  },
  encode(state, n) {
    let len = 0
    for (let m = n; m; m = m >> 64n) len++
    uint.encode(state, len)
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
      view.setBigUint64(i, BigInt.asUintN(64, m), true) // little endian
    }
    state.start += 8 * len
  },
  decode(state) {
    const len = uint.decode(state)
    if (state.end - state.start < 8 * len) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8 * len
    )
    let n = 0n
    for (let i = len - 1; i >= 0; i--)
      n = (n << 64n) + view.getBigUint64(i * 8, true) // little endian
    state.start += 8 * len
    return n
  }
})

exports.bigint = zigZagBigInt(biguint)

exports.lexint = require('./lexint')

exports.float32 = {
  preencode(state, n) {
    state.end += 4
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    view.setFloat32(0, n, true) // little endian
    state.start += 4
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      4
    )
    const float = view.getFloat32(0, true) // little endian
    state.start += 4
    return float
  }
}

exports.float64 = {
  preencode(state, n) {
    state.end += 8
  },
  encode(state, n) {
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    view.setFloat64(0, n, true) // little endian
    state.start += 8
  },
  decode(state) {
    if (state.end - state.start < 8) throw new Error('Out of bounds')
    const view = new DataView(
      state.buffer.buffer,
      state.start + state.buffer.byteOffset,
      8
    )
    const float = view.getFloat64(0, true) // little endian
    state.start += 8
    return float
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const len = uint.decode(state)
    if (len === 0) return null
    if (state.end - state.start < len) throw new Error('Out of bounds')
    return state.buffer.subarray(state.start, (state.start += len))
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    uint.preencode(state, b.byteLength)
    state.end += b.byteLength
  },
  encode(state, b) {
    uint.encode(state, b.byteLength)

    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const len = uint.decode(state)

    const b = new ArrayBuffer(len)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start, (state.start += len)))

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      uint.preencode(state, b.length)
      state.end += b.byteLength
    },
    encode(state, b) {
      uint.encode(state, b.length)

      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      const len = uint.decode(state)

      let b = state.buffer.subarray(state.start, (state.start += len * n))
      if (b.byteLength !== len * n) throw new Error('Out of bounds')
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.preencode(state, len)
      state.end += len
    },
    encode(state, s) {
      const len = b4a.byteLength(s, encoding)
      uint.encode(state, len)
      b4a.write(state.buffer, s, state.start, encoding)
      state.start += len
    },
    decode(state) {
      const len = uint.decode(state)
      if (state.end - state.start < len) throw new Error('Out of bounds')
      return b4a.toString(
        state.buffer,
        encoding,
        state.start,
        (state.start += len)
      )
    },
    fixed(n) {
      return {
        preencode(state) {
          state.end += n
        },
        encode(state, s) {
          b4a.write(state.buffer, s, state.start, n, encoding)
          state.start += n
        },
        decode(state) {
          if (state.end - state.start < n) throw new Error('Out of bounds')
          return b4a.toString(
            state.buffer,
            encoding,
            state.start,
            (state.start += n)
          )
        }
      }
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.bool = {
  preencode(state, b) {
    state.end++
  },
  encode(state, b) {
    state.buffer[state.start++] = b ? 1 : 0
  },
  decode(state) {
    if (state.start >= state.end) throw Error('Out of bounds')
    return state.buffer[state.start++] === 1
  }
}

const fixed = (exports.fixed = function fixed(n) {
  return {
    preencode(state, s) {
      if (s.byteLength !== n) throw new Error('Incorrect buffer size')
      state.end += n
    },
    encode(state, s) {
      state.buffer.set(s, state.start)
      state.start += n
    },
    decode(state) {
      if (state.end - state.start < n) throw new Error('Out of bounds')
      return state.buffer.subarray(state.start, (state.start += n))
    }
  }
})

exports.fixed32 = fixed(32)
exports.fixed64 = fixed(64)

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      uint.preencode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.preencode(state, list[i])
    },
    encode(state, list) {
      uint.encode(state, list.length)
      for (let i = 0; i < list.length; i++) enc.encode(state, list[i])
    },
    decode(state) {
      const len = uint.decode(state)
      if (len > 0x100000) throw new Error('Array is too big')
      const arr = new Array(len)
      for (let i = 0; i < len; i++) arr[i] = enc.decode(state)
      return arr
    }
  }
}

exports.frame = function frame(enc) {
  const dummy = exports.state()

  return {
    preencode(state, m) {
      const end = state.end
      enc.preencode(state, m)
      uint.preencode(state, state.end - end)
    },
    encode(state, m) {
      dummy.end = 0
      enc.preencode(dummy, m)
      uint.encode(state, dummy.end)
      enc.encode(state, m)
    },
    decode(state) {
      const end = state.end
      const len = uint.decode(state)
      state.end = state.start + len
      const m = enc.decode(state)
      state.start = state.end
      state.end = end
      return m
    }
  }
}

exports.date = {
  preencode(state, d) {
    int.preencode(state, d.getTime())
  },
  encode(state, d) {
    int.encode(state, d.getTime())
  },
  decode(state, d) {
    return new Date(int.decode(state))
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

// simple helper for when you want to just express nothing
exports.none = {
  preencode(state, n) {
    // do nothing
  },
  encode(state, n) {
    // do nothing
  },
  decode(state) {
    return null
  }
}

// "any" encoders here for helping just structure any object without schematising it

const anyArray = {
  preencode(state, arr) {
    uint.preencode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.preencode(state, arr[i])
    }
  },
  encode(state, arr) {
    uint.encode(state, arr.length)
    for (let i = 0; i < arr.length; i++) {
      any.encode(state, arr[i])
    }
  },
  decode(state) {
    const arr = []
    let len = uint.decode(state)
    while (len-- > 0) {
      arr.push(any.decode(state))
    }
    return arr
  }
}

const anyObject = {
  preencode(state, o) {
    const keys = Object.keys(o)
    uint.preencode(state, keys.length)
    for (const key of keys) {
      utf8.preencode(state, key)
      any.preencode(state, o[key])
    }
  },
  encode(state, o) {
    const keys = Object.keys(o)
    uint.encode(state, keys.length)
    for (const key of keys) {
      utf8.encode(state, key)
      any.encode(state, o[key])
    }
  },
  decode(state) {
    let len = uint.decode(state)
    const o = {}
    while (len-- > 0) {
      const key = utf8.decode(state)
      o[key] = any.decode(state)
    }
    return o
  }
}

const anyTypes = [
  exports.none,
  exports.bool,
  exports.string,
  exports.buffer,
  exports.uint,
  exports.int,
  exports.float64,
  anyArray,
  anyObject,
  exports.date
]

const any = (exports.any = {
  preencode(state, o) {
    const t = getType(o)
    uint.preencode(state, t)
    anyTypes[t].preencode(state, o)
  },
  encode(state, o) {
    const t = getType(o)
    uint.encode(state, t)
    anyTypes[t].encode(state, o)
  },
  decode(state) {
    const t = uint.decode(state)
    if (t >= anyTypes.length) throw new Error('Unknown type: ' + t)
    return anyTypes[t].decode(state)
  }
})

const port = (exports.port = uint16)

const address = (host, family) => {
  return {
    preencode(state, m) {
      host.preencode(state, m.host)
      port.preencode(state, m.port)
    },
    encode(state, m) {
      host.encode(state, m.host)
      port.encode(state, m.port)
    },
    decode(state) {
      return {
        host: host.decode(state),
        family,
        port: port.decode(state)
      }
    }
  }
}

const ipv4 = (exports.ipv4 = {
  preencode(state) {
    state.end += 4
  },
  encode(state, string) {
    const start = state.start
    const end = start + 4

    let i = 0

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* . */ 0x2e
      ) {
        n = n * 10 + (c - /* 0 */ 0x30)
      }

      state.buffer[state.start++] = n
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 4) throw new Error('Out of bounds')
    return (
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++] +
      '.' +
      state.buffer[state.start++]
    )
  }
})

exports.ipv4Address = address(ipv4, 4)

const ipv6 = (exports.ipv6 = {
  preencode(state) {
    state.end += 16
  },
  encode(state, string) {
    const start = state.start
    const end = start + 16

    let i = 0
    let split = null

    while (i < string.length) {
      let n = 0
      let c

      while (
        i < string.length &&
        (c = string.charCodeAt(i++)) !== /* : */ 0x3a
      ) {
        if (c >= 0x30 && c <= 0x39) n = n * 0x10 + (c - /* 0 */ 0x30)
        else if (c >= 0x41 && c <= 0x46) n = n * 0x10 + (c - /* A */ 0x41 + 10)
        else if (c >= 0x61 && c <= 0x66) n = n * 0x10 + (c - /* a */ 0x61 + 10)
      }

      state.buffer[state.start++] = n >>> 8
      state.buffer[state.start++] = n

      if (i < string.length && string.charCodeAt(i) === /* : */ 0x3a) {
        i++
        split = state.start
      }
    }

    if (split !== null) {
      const offset = end - state.start
      state.buffer
        .copyWithin(split + offset, split)
        .fill(0, split, split + offset)
    }

    state.start = end
  },
  decode(state) {
    if (state.end - state.start < 16) throw new Error('Out of bounds')
    return (
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16) +
      ':' +
      (
        state.buffer[state.start++] * 256 +
        state.buffer[state.start++]
      ).toString(16)
    )
  }
})

exports.ipv6Address = address(ipv6, 6)

const ip = (exports.ip = {
  preencode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.preencode(state, family)
    if (family === 4) ipv4.preencode(state)
    else ipv6.preencode(state)
  },
  encode(state, string) {
    const family = string.includes(':') ? 6 : 4
    uint8.encode(state, family)
    if (family === 4) ipv4.encode(state, string)
    else ipv6.encode(state, string)
  },
  decode(state) {
    const family = uint8.decode(state)
    if (family === 4) return ipv4.decode(state)
    else return ipv6.decode(state)
  }
})

exports.ipAddress = {
  preencode(state, m) {
    ip.preencode(state, m.host)
    port.preencode(state, m.port)
  },
  encode(state, m) {
    ip.encode(state, m.host)
    port.encode(state, m.port)
  },
  decode(state) {
    const family = uint8.decode(state)
    return {
      host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
      family,
      port: port.decode(state)
    }
  }
}

const record = (exports.record = function (keyEncoding, valueEncoding) {
  return {
    preencode(state, v) {
      const keys = Object.keys(v)
      uint.preencode(state, keys.length)
      for (const k of keys) {
        keyEncoding.preencode(state, k)
        valueEncoding.preencode(state, v[k])
      }
    },
    encode(state, v) {
      const keys = Object.keys(v)
      uint.encode(state, keys.length)
      for (const k of keys) {
        keyEncoding.encode(state, k)
        valueEncoding.encode(state, v[k])
      }
    },
    decode(state) {
      const out = Object.create(null)
      const keys = uint.decode(state)
      for (let i = 0; i < keys; i++) {
        out[keyEncoding.decode(state)] = valueEncoding.decode(state)
      }
      return out
    }
  }
})

exports.stringRecord = record(utf8, utf8)

function getType(o) {
  if (o === null || o === undefined) return 0
  if (typeof o === 'boolean') return 1
  if (typeof o === 'string') return 2
  if (b4a.isBuffer(o)) return 3
  if (typeof o === 'number') {
    if (Number.isInteger(o)) return o >= 0 ? 4 : 5
    return 6
  }
  if (Array.isArray(o)) return 7
  if (o instanceof Date) return 9
  if (typeof o === 'object') return 8

  throw new Error('Unsupported type for ' + o)
}

exports.from = function from(enc) {
  if (typeof enc === 'string') return fromNamed(enc)
  if (enc.preencode) return enc
  if (enc.encodingLength) return fromAbstractEncoder(enc)
  return fromCodec(enc)
}

function fromNamed(enc) {
  switch (enc) {
    case 'ascii':
      return raw.ascii
    case 'utf-8':
    case 'utf8':
      return raw.utf8
    case 'hex':
      return raw.hex
    case 'base64':
      return raw.base64
    case 'utf16-le':
    case 'utf16le':
    case 'ucs-2':
    case 'ucs2':
      return raw.ucs2
    case 'ndjson':
      return raw.ndjson
    case 'json':
      return raw.json
    case 'binary':
    default:
      return raw.binary
  }
}

function fromCodec(enc) {
  let tmpM = null
  let tmpBuf = null

  return {
    preencode(state, m) {
      tmpM = m
      tmpBuf = enc.encode(m)
      state.end += tmpBuf.byteLength
    },
    encode(state, m) {
      raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m))
      tmpM = tmpBuf = null
    },
    decode(state) {
      return enc.decode(raw.decode(state))
    }
  }
}

function fromAbstractEncoder(enc) {
  return {
    preencode(state, m) {
      state.end += enc.encodingLength(m)
    },
    encode(state, m) {
      enc.encode(m, state.buffer, state.start)
      state.start += enc.encode.bytes
    },
    decode(state) {
      const m = enc.decode(state.buffer, state.start, state.end)
      state.start += enc.decode.bytes
      return m
    }
  }
}

exports.encode = function encode(enc, m) {
  const state = exports.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}

exports.decode = function decode(enc, buffer) {
  return enc.decode(exports.state(0, buffer.byteLength, buffer))
}

function zigZagInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeInt(n))
    },
    decode(state) {
      return zigZagDecodeInt(enc.decode(state))
    }
  }
}

function zigZagDecodeInt(n) {
  return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2
}

function zigZagEncodeInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
}

function zigZagBigInt(enc) {
  return {
    preencode(state, n) {
      enc.preencode(state, zigZagEncodeBigInt(n))
    },
    encode(state, n) {
      enc.encode(state, zigZagEncodeBigInt(n))
    },
    decode(state) {
      return zigZagDecodeBigInt(enc.decode(state))
    }
  }
}

function zigZagDecodeBigInt(n) {
  return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n
}

function zigZagEncodeBigInt(n) {
  // 0, -1, 1, -2, 2, ...
  return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n
}

function validateUint(n) {
  if (n >= 0 === false /* Handles NaN as well */)
    throw new Error('uint must be positive')
}
module.exports = {
  preencode,
  encode,
  decode
}

function preencode(state, num) {
  if (num < 251) {
    state.end++
  } else if (num < 256) {
    state.end += 2
  } else if (num < 0x10000) {
    state.end += 3
  } else if (num < 0x1000000) {
    state.end += 4
  } else if (num < 0x100000000) {
    state.end += 5
  } else {
    state.end++
    const exp = Math.floor(Math.log(num) / Math.log(2)) - 32
    preencode(state, exp)
    state.end += 6
  }
}

function encode(state, num) {
  const max = 251
  const x = num - max

  if (num < max) {
    state.buffer[state.start++] = num
  } else if (num < 256) {
    state.buffer[state.start++] = max
    state.buffer[state.start++] = x
  } else if (num < 0x10000) {
    state.buffer[state.start++] = max + 1
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x1000000) {
    state.buffer[state.start++] = max + 2
    state.buffer[state.start++] = x >> 16
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else if (num < 0x100000000) {
    state.buffer[state.start++] = max + 3
    state.buffer[state.start++] = x >> 24
    state.buffer[state.start++] = (x >> 16) & 0xff
    state.buffer[state.start++] = (x >> 8) & 0xff
    state.buffer[state.start++] = x & 0xff
  } else {
    // need to use Math here as bitwise ops are 32 bit
    const exp = Math.floor(Math.log(x) / Math.log(2)) - 32
    state.buffer[state.start++] = 0xff

    encode(state, exp)
    const rem = x / Math.pow(2, exp - 11)

    for (let i = 5; i >= 0; i--) {
      state.buffer[state.start++] = (rem / Math.pow(2, 8 * i)) & 0xff
    }
  }
}

function decode(state) {
  const max = 251

  if (state.end - state.start < 1) throw new Error('Out of bounds')

  const flag = state.buffer[state.start++]

  if (flag < max) return flag

  if (state.end - state.start < flag - max + 1) {
    throw new Error('Out of bounds.')
  }

  if (flag < 252) {
    return state.buffer[state.start++] + max
  }

  if (flag < 253) {
    return (
      (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max
    )
  }

  if (flag < 254) {
    return (
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  // << 24 result may be interpreted as negative
  if (flag < 255) {
    return (
      state.buffer[state.start++] * 0x1000000 +
      (state.buffer[state.start++] << 16) +
      (state.buffer[state.start++] << 8) +
      state.buffer[state.start++] +
      max
    )
  }

  const exp = decode(state)

  if (state.end - state.start < 6) throw new Error('Out of bounds')

  let rem = 0
  for (let i = 5; i >= 0; i--) {
    rem += state.buffer[state.start++] * Math.pow(2, 8 * i)
  }

  return rem * Math.pow(2, exp - 11) + max
}
{
  "name": "compact-encoding",
  "version": "2.19.2",
  "description": "A series of compact encoding schemes for building small and fast parsers and serializers",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.3.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/compact-encoding.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/compact-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/compact-encoding"
}
const b4a = require('b4a')

const { BE } = require('./endian')

exports = module.exports = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    state.buffer.set(b, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = state.buffer.subarray(state.start, state.end)
    state.start = state.end
    return b
  }
}

const buffer = (exports.buffer = {
  preencode(state, b) {
    if (b) uint8array.preencode(state, b)
    else state.end++
  },
  encode(state, b) {
    if (b) uint8array.encode(state, b)
    else state.buffer[state.start++] = 0
  },
  decode(state) {
    const b = state.buffer.subarray(state.start)
    if (b.byteLength === 0) return null
    state.start = state.end
    return b
  }
})

exports.binary = {
  ...buffer,
  preencode(state, b) {
    if (typeof b === 'string') utf8.preencode(state, b)
    else buffer.preencode(state, b)
  },
  encode(state, b) {
    if (typeof b === 'string') utf8.encode(state, b)
    else buffer.encode(state, b)
  }
}

exports.arraybuffer = {
  preencode(state, b) {
    state.end += b.byteLength
  },
  encode(state, b) {
    const view = new Uint8Array(b)

    state.buffer.set(view, state.start)
    state.start += b.byteLength
  },
  decode(state) {
    const b = new ArrayBuffer(state.end - state.start)
    const view = new Uint8Array(b)

    view.set(state.buffer.subarray(state.start))

    state.start = state.end

    return b
  }
}

function typedarray(TypedArray, swap) {
  const n = TypedArray.BYTES_PER_ELEMENT

  return {
    preencode(state, b) {
      state.end += b.byteLength
    },
    encode(state, b) {
      const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)

      if (BE && swap) swap(view)

      state.buffer.set(view, state.start)
      state.start += b.byteLength
    },
    decode(state) {
      let b = state.buffer.subarray(state.start)
      if (b.byteOffset % n !== 0) b = new Uint8Array(b)

      if (BE && swap) swap(b)

      state.start = state.end

      return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n)
    }
  }
}

const uint8array = (exports.uint8array = typedarray(Uint8Array))
exports.uint16array = typedarray(Uint16Array, b4a.swap16)
exports.uint32array = typedarray(Uint32Array, b4a.swap32)

exports.int8array = typedarray(Int8Array)
exports.int16array = typedarray(Int16Array, b4a.swap16)
exports.int32array = typedarray(Int32Array, b4a.swap32)

exports.biguint64array = typedarray(BigUint64Array, b4a.swap64)
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64)

exports.float32array = typedarray(Float32Array, b4a.swap32)
exports.float64array = typedarray(Float64Array, b4a.swap64)

function string(encoding) {
  return {
    preencode(state, s) {
      state.end += b4a.byteLength(s, encoding)
    },
    encode(state, s) {
      state.start += b4a.write(state.buffer, s, state.start, encoding)
    },
    decode(state) {
      const s = b4a.toString(state.buffer, encoding, state.start)
      state.start = state.end
      return s
    }
  }
}

const utf8 = (exports.string = exports.utf8 = string('utf-8'))
exports.ascii = string('ascii')
exports.hex = string('hex')
exports.base64 = string('base64')
exports.ucs2 = exports.utf16le = string('utf16le')

exports.array = function array(enc) {
  return {
    preencode(state, list) {
      for (const value of list) enc.preencode(state, value)
    },
    encode(state, list) {
      for (const value of list) enc.encode(state, value)
    },
    decode(state) {
      const arr = []
      while (state.start < state.end) arr.push(enc.decode(state))
      return arr
    }
  }
}

exports.json = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v))
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v))
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}

exports.ndjson = {
  preencode(state, v) {
    utf8.preencode(state, JSON.stringify(v) + '\n')
  },
  encode(state, v) {
    utf8.encode(state, JSON.stringify(v) + '\n')
  },
  decode(state) {
    return JSON.parse(utf8.decode(state))
  }
}
{
  "name": "hyperschema",
  "version": "1.20.1",
  "description": "Create registries of declarative compact-encoding schemas",
  "files": [
    "lib/*.js",
    "builder.mjs",
    "builder.cjs",
    "runtime.mjs",
    "runtime.cjs",
    "primitives.mjs",
    "primitives.cjs"
  ],
  "exports": {
    "./package": "./package.json",
    ".": {
      "import": "./builder.mjs",
      "default": "./builder.cjs"
    },
    "./runtime": {
      "import": "./runtime.mjs",
      "default": "./runtime.cjs"
    },
    "./primitives": {
      "import": "./primitives.mjs",
      "default": "./primitives.cjs"
    }
  },
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    }
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test/index.js",
    "test:bare": "prettier . --check && bare test/index.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/hyperschema.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/hyperschema/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperschema#readme",
  "dependencies": {
    "bare-fs": "^4.0.1",
    "compact-encoding": "^2.19.0",
    "generate-object-property": "^2.0.0",
    "generate-string": "^1.0.1"
  },
  "devDependencies": {
    "brittle": "^3.7.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "test-tmp": "^1.3.0"
  }
}
module.exports = {
  c: require('compact-encoding')
}
const { EventEmitter } = require('events')
const { getStreamError } = require('streamx')
const DHT = require('hyperdht')
const spq = require('shuffled-priority-queue')
const b4a = require('b4a')
const unslab = require('unslab')

const PeerInfo = require('./lib/peer-info')
const RetryTimer = require('./lib/retry-timer')
const ConnectionSet = require('./lib/connection-set')
const PeerDiscovery = require('./lib/peer-discovery')

const MAX_PEERS = 64
const MAX_PARALLEL = 3
const MAX_CLIENT_CONNECTIONS = Infinity // TODO: Change
const MAX_SERVER_CONNECTIONS = Infinity

const ERR_MISSING_TOPIC = 'Topic is required and must be a 32-byte buffer'
const ERR_DESTROYED = 'Swarm has been destroyed'
const ERR_DUPLICATE = 'Duplicate connection'
const ERR_FIREWALL = 'Peer is firewalled'

module.exports = class Hyperswarm extends EventEmitter {
  constructor(opts = {}) {
    super()
    const {
      seed,
      relayThrough,
      keyPair = DHT.keyPair(seed),
      maxPeers = MAX_PEERS,
      maxClientConnections = MAX_CLIENT_CONNECTIONS,
      maxServerConnections = MAX_SERVER_CONNECTIONS,
      maxParallel = MAX_PARALLEL,
      firewall = allowAll
    } = opts
    this.keyPair = keyPair

    this.dht =
      opts.dht ||
      new DHT({
        bootstrap: opts.bootstrap,
        nodes: opts.nodes,
        port: opts.port,
        deferRandomPunch: opts.deferRandomPunch,
        randomPunchInterval: opts.randomPunchInterval
      })
    this.server = this.dht.createServer(
      {
        firewall: this._handleFirewall.bind(this),
        relayThrough: this._maybeRelayConnection.bind(this),
        handshakeClearWait: opts.handshakeClearWait
      },
      this._handleServerConnection.bind(this)
    )

    this.destroyed = false
    this.suspended = false
    this.maxPeers = maxPeers
    this.maxClientConnections = maxClientConnections
    this.maxServerConnections = maxServerConnections
    this.maxParallel = maxParallel
    this.relayThrough = relayThrough ? toRelayFunction(relayThrough) : null

    this.connecting = 0
    this.connections = new Set()
    this.peers = new Map()
    this.explicitPeers = new Set()
    this.listening = null
    this.stats = {
      updates: 0,
      connects: {
        client: {
          opened: 0,
          closed: 0,
          attempted: 0
        },
        server: {
          // Note: there is no notion of 'attempts' for server connections
          opened: 0,
          closed: 0
        }
      },
      bannedPeers: 0
    }

    this._discovery = new Map()
    this._timer = new RetryTimer(this._requeue.bind(this), {
      backoffs: opts.backoffs,
      jitter: opts.jitter
    })
    this._queue = spq()

    this._allConnections = new ConnectionSet()
    this._pendingFlushes = []
    this._flushTick = 0

    this._drainingQueue = false
    this._clientConnections = 0
    this._serverConnections = 0
    this._firewall = firewall

    this.dht.on('network-change', this._handleNetworkChange.bind(this))
    this.dht.on('network-update', this._handleNetworkUpdate.bind(this))
    this.on('update', this._handleUpdate)
  }

  _maybeRelayConnection(force) {
    if (!this.relayThrough) return null
    return this.relayThrough(force, this)
  }

  _enqueue(peerInfo) {
    if (peerInfo.queued) return
    peerInfo.queued = true
    peerInfo._flushTick = this._flushTick
    this._queue.add(peerInfo)

    this._attemptClientConnections()
  }

  _requeue(batch) {
    if (this.suspended) return
    for (const peerInfo of batch) {
      peerInfo.waiting = false

      if (
        peerInfo._updatePriority() === false ||
        this._allConnections.has(peerInfo.publicKey) ||
        peerInfo.queued
      ) {
        continue
      }
      peerInfo.queued = true
      peerInfo._flushTick = this._flushTick
      this._queue.add(peerInfo)
    }

    this._attemptClientConnections()
  }

  _flushMaybe(peerInfo) {
    for (let i = 0; i < this._pendingFlushes.length; i++) {
      const flush = this._pendingFlushes[i]
      if (peerInfo._flushTick > flush.tick) continue
      if (--flush.missing > 0) continue
      flush.onflush(true)
      this._pendingFlushes.splice(i--, 1)
    }
  }

  _withinMaxPeers() {
    const e = this.explicitPeers.size
    const factor = e === 0 ? 1 : e < 2 ? 2 : e < 4 ? 3 : 4
    return factor * this._allConnections.size < this.maxPeers
  }

  _flushAllMaybe() {
    if (
      this.connecting > 0 ||
      (this._withinMaxPeers() && this._clientConnections < this.maxClientConnections)
    ) {
      return false
    }

    while (this._pendingFlushes.length) {
      const flush = this._pendingFlushes.pop()
      flush.onflush(true)
    }

    return true
  }

  _shouldConnectExplicit() {
    return !this.destroyed && !this.suspended && this.connecting < this.maxParallel
  }

  _shouldConnect() {
    return (
      !this.destroyed &&
      !this.suspended &&
      this.connecting < this.maxParallel &&
      this._withinMaxPeers() &&
      this._clientConnections < this.maxClientConnections
    )
  }

  _shouldRequeue(peerInfo) {
    if (this.suspended) return false
    if (peerInfo.explicit) return true
    for (const topic of peerInfo.topics) {
      if (this._discovery.has(b4a.toString(topic, 'hex')) && !this.destroyed) {
        return true
      }
    }
    return false
  }

  _connect(peerInfo, queued) {
    if (peerInfo.banned || this._allConnections.has(peerInfo.publicKey)) {
      if (queued) this._flushMaybe(peerInfo)
      return
    }

    // TODO: Support async firewalling at some point.
    if (this._handleFirewall(peerInfo.publicKey, null)) {
      if (queued) this._flushMaybe(peerInfo)
      return
    }

    const relayThrough = this._maybeRelayConnection(peerInfo.forceRelaying)
    const conn = this.dht.connect(peerInfo.publicKey, {
      relayAddresses: peerInfo.relayAddresses,
      keyPair: this.keyPair,
      relayThrough
    })
    this._allConnections.add(conn)

    this.stats.connects.client.attempted++

    this.connecting++
    this._clientConnections++
    let opened = false

    const onerror = (err) => {
      if (this.relayThrough && shouldForceRelaying(err.code)) {
        peerInfo.forceRelaying = true
        // Reset the attempts in order to fast connect to relay
        peerInfo.attempts = 0
      }
    }

    // Removed once a connection is opened
    conn.on('error', onerror)

    conn.on('open', () => {
      opened = true
      this.stats.connects.client.opened++

      this._connectDone()
      this.connections.add(conn)
      conn.removeListener('error', onerror)
      peerInfo._connected()
      peerInfo.client = true
      this.emit('connection', conn, peerInfo)
      if (queued) this._flushMaybe(peerInfo)

      this.emit('update')
    })
    conn.on('close', () => {
      if (!opened) this._connectDone()
      this.stats.connects.client.closed++

      const err = getStreamError(conn)
      if (shouldBan(err)) {
        this._banPeer(peerInfo, true, err)
      }

      this.connections.delete(conn)
      this._allConnections.delete(conn)
      this._clientConnections--
      peerInfo._disconnected()

      peerInfo.waiting = this._shouldRequeue(peerInfo) && this._timer.add(peerInfo)
      this._maybeDeletePeer(peerInfo)

      if (!opened && queued) this._flushMaybe(peerInfo)

      this._attemptClientConnections()

      this.emit('update')
    })

    this.emit('update')
  }

  _connectDone() {
    this.connecting--

    if (this.connecting < this.maxParallel) this._attemptClientConnections()
    if (this.connecting === 0) this._flushAllMaybe()
  }

  // Called when the PeerQueue indicates a connection should be attempted.
  _attemptClientConnections() {
    // Guard against re-entries - unsure if it still needed but doesn't hurt
    if (this._drainingQueue || this.suspended) return
    this._drainingQueue = true

    for (const peerInfo of this.explicitPeers) {
      if (!this._shouldConnectExplicit()) break
      if (
        peerInfo.attempts >= 5 ||
        Date.now() - peerInfo.disconnectedTime < peerInfo.attempts * 1000
      ) {
        continue
      }
      this._connect(peerInfo, false)
    }

    while (this._queue.length && this._shouldConnect()) {
      const peerInfo = this._queue.shift()
      peerInfo.queued = false
      this._connect(peerInfo, true)
    }
    this._drainingQueue = false
    if (this.connecting === 0) this._flushAllMaybe()
  }

  _handleFirewall(remotePublicKey, payload) {
    if (b4a.equals(remotePublicKey, this.keyPair.publicKey)) return true

    let peerInfo = this.peers.get(b4a.toString(remotePublicKey, 'hex'))
    if (peerInfo && peerInfo.banned) return true

    const firewalled = this._firewall(remotePublicKey, payload)
    if (firewalled) {
      if (!peerInfo) peerInfo = this._upsertPeer(remotePublicKey)
      this._banPeer(peerInfo, true, new Error(ERR_FIREWALL))
    }

    return firewalled
  }

  _handleServerConnectionSwap(existing, conn) {
    let closed = false

    existing.on('close', () => {
      if (closed) return

      conn.removeListener('error', noop)
      conn.removeListener('close', onclose)

      this._handleServerConnection(conn)
    })

    conn.on('error', noop)
    conn.on('close', onclose)

    function onclose() {
      closed = true
    }
  }

  // Called when the DHT receives a new server connection.
  _handleServerConnection(conn) {
    if (this.destroyed || this.suspended) {
      // TODO: Investigate why a final server connection can be received after close
      conn.on('error', noop)
      return conn.destroy(ERR_DESTROYED)
    }

    const existing = this._allConnections.get(conn.remotePublicKey)

    if (existing) {
      // If both connections are from the same peer,
      // - pick the new one if the existing stream is already established (has sent and received bytes),
      //   because the other client must have lost that connection and be reconnecting
      // - otherwise, pick the one thats expected to initiate in a tie break
      const existingIsOutdated = existing.rawBytesRead > 0 && existing.rawBytesWritten > 0
      const expectedInitiator = b4a.compare(conn.publicKey, conn.remotePublicKey) > 0
      const keepNew = existingIsOutdated || expectedInitiator === conn.isInitiator

      if (keepNew === false) {
        existing.sendKeepAlive()
        conn.on('error', noop)
        conn.destroy(new Error(ERR_DUPLICATE))
        return
      }

      existing.on('error', noop)
      existing.destroy(new Error(ERR_DUPLICATE))
      this._handleServerConnectionSwap(existing, conn)
      return
    }

    // When reaching here, the connection will always be 'opened' next tick
    this.stats.connects.server.opened++

    const peerInfo = this._upsertPeer(conn.remotePublicKey, null)

    this.connections.add(conn)
    this._allConnections.add(conn)
    this._serverConnections++

    conn.on('close', () => {
      const err = getStreamError(conn)
      if (shouldBan(err)) {
        this._banPeer(peerInfo, true, err)
      }

      this.connections.delete(conn)
      this._allConnections.delete(conn)
      this._serverConnections--
      this.stats.connects.server.closed++

      this._maybeDeletePeer(peerInfo)

      this._attemptClientConnections()

      this.emit('update')
    })
    peerInfo.client = false
    this.emit('connection', conn, peerInfo)

    this.emit('update')
  }

  _upsertPeer(publicKey, relayAddresses) {
    if (b4a.equals(publicKey, this.keyPair.publicKey)) return null
    const keyString = b4a.toString(publicKey, 'hex')
    let peerInfo = this.peers.get(keyString)

    if (peerInfo) {
      peerInfo.relayAddresses = relayAddresses // new is always better
      return peerInfo
    }

    peerInfo = new PeerInfo({
      publicKey,
      relayAddresses
    })

    this.peers.set(keyString, peerInfo)
    return peerInfo
  }

  _handleUpdate() {
    this.stats.updates++
  }

  _maybeDeletePeer(peerInfo) {
    if (!peerInfo.shouldGC()) return

    const hasActiveConn = this._allConnections.has(peerInfo.publicKey)
    if (hasActiveConn) return

    const keyString = b4a.toString(peerInfo.publicKey, 'hex')
    this.peers.delete(keyString)
  }

  /*
   * Called when a peer is actively discovered during a lookup.
   *
   * Three conditions:
   *  1. Not a known peer -- insert into queue
   *  2. A known peer with normal priority -- do nothing
   *  3. A known peer with low priority -- bump priority, because it's been rediscovered
   */
  _handlePeer(peer, topic) {
    const peerInfo = this._upsertPeer(peer.publicKey, peer.relayAddresses)
    if (peerInfo) peerInfo._topic(topic)
    if (!peerInfo || this._allConnections.has(peer.publicKey)) return
    if (!peerInfo.prioritized || peerInfo.server) peerInfo._reset()
    if (peerInfo._updatePriority()) {
      this._enqueue(peerInfo)
    }
  }

  async _handleNetworkUpdate() {
    if (!this.online) return
    this._handleNetworkChange()
  }

  async _handleNetworkChange() {
    if (this.suspended) return

    // prioritize figuring out if existing connections are dead
    for (const conn of this._allConnections) {
      conn.sendKeepAlive()
    }

    const refreshes = []

    for (const discovery of this._discovery.values()) {
      refreshes.push(discovery.refresh())
    }

    await Promise.allSettled(refreshes)
  }

  _banPeer(peerInfo, banned, err) {
    peerInfo.ban(banned)
    this.stats.bannedPeers++
    this.emit('ban', peerInfo, err)
  }

  status(key) {
    return this._discovery.get(b4a.toString(key, 'hex')) || null
  }

  listen() {
    if (!this.listening) {
      if (this.destroyed) throw new Error('Swarm destroyed')
      this.listening = this.server.listen(this.keyPair)
    }
    return this.listening
  }

  // Object that exposes a cancellation method (destroy)
  // TODO: When you rejoin, it should reannounce + bump lookup priority
  join(topic, opts = {}) {
    if (this.destroyed) throw new Error('Swarm destroyed')
    if (!topic) throw new Error(ERR_MISSING_TOPIC)
    topic = unslab(topic)

    const topicString = b4a.toString(topic, 'hex')

    let discovery = this._discovery.get(topicString)

    if (discovery && !discovery.destroyed) {
      return discovery.session(opts)
    }

    discovery = new PeerDiscovery(this, topic, {
      limit: opts.limit,
      wait: discovery ? discovery.destroy() : null,
      suspended: this.suspended,
      onpeer: (peer) => this._handlePeer(peer, topic)
    })
    this._discovery.set(topicString, discovery)
    return discovery.session(opts)
  }

  // Returns a promise
  async leave(topic) {
    if (!topic) throw new Error(ERR_MISSING_TOPIC)
    const topicString = b4a.toString(topic, 'hex')
    if (!this._discovery.has(topicString)) return Promise.resolve()

    const discovery = this._discovery.get(topicString)

    try {
      await discovery.destroy()
    } catch {
      // ignore, prop network
    }

    if (this._discovery.get(topicString) === discovery) {
      this._discovery.delete(topicString)
    }
  }

  joinPeer(publicKey) {
    const peerInfo = this._upsertPeer(publicKey, null)
    if (!peerInfo) return
    if (!this.explicitPeers.has(peerInfo)) {
      peerInfo.explicit = true
      this.explicitPeers.add(peerInfo)
    }
    if (this._allConnections.has(publicKey)) return
    if (peerInfo._updatePriority()) {
      this._enqueue(peerInfo)
    }
  }

  leavePeer(publicKey) {
    const keyString = b4a.toString(publicKey, 'hex')
    if (!this.peers.has(keyString)) return

    const peerInfo = this.peers.get(keyString)
    peerInfo.explicit = false
    this.explicitPeers.delete(peerInfo)
    this._maybeDeletePeer(peerInfo)
  }

  // Returns a promise
  async flush() {
    const allFlushed = [...this._discovery.values()].map((v) => v.flushed())
    await Promise.all(allFlushed)
    if (this._flushAllMaybe()) return true
    const pendingSize = this._allConnections.size - this.connections.size
    if (!this._queue.length && !pendingSize) return true
    return new Promise((resolve) => {
      this._pendingFlushes.push({
        onflush: resolve,
        missing: this._queue.length + pendingSize,
        tick: this._flushTick++
      })
    })
  }

  async clear() {
    const cleared = Promise.allSettled([...this._discovery.values()].map((d) => d.destroy()))
    this._discovery.clear()
    return cleared
  }

  async destroy({ force } = {}) {
    if (this.destroyed && !force) return
    this.destroyed = true

    this._timer.destroy()

    if (!force) await this.clear()

    await this.server.close()

    while (this._pendingFlushes.length) {
      const flush = this._pendingFlushes.pop()
      flush.onflush(false)
    }

    await this.dht.destroy({ force })
  }

  async suspend({ log = noop } = {}) {
    if (this.suspended) return

    const promises = []

    promises.push(this.server.suspend({ log }))

    for (const discovery of this._discovery.values()) {
      promises.push(discovery.suspend({ log }))
    }

    const pending = []
    for (const connection of this._allConnections) {
      connection.destroy()
      pending.push(new Promise((resolve) => connection.on('close', resolve)))
    }

    this.suspended = true

    log('Suspending server and discovery... (' + promises.length + ')')
    await Promise.allSettled(promises)
    log('Done, suspending the dht...')
    await this.dht.suspend({ log })
    log('Done, swarm fully suspended')

    await Promise.all(pending)

    // reset queue
    this._timer.destroy()
    this._timer = new RetryTimer(this._requeue.bind(this), {
      backoffs: this._timer.backoffs,
      jitter: this._timer.jitter
    })
    this._queue = spq()
  }

  async resume({ log = noop } = {}) {
    if (!this.suspended) return

    log('Resuming the dht')
    await this.dht.resume()
    log('Done, resuming the server')
    await this.server.resume()
    log('Done, all discovery')

    for (const discovery of this._discovery.values()) {
      discovery.resume()
    }

    this.suspended = false
    this._attemptClientConnections()
  }

  topics() {
    return this._discovery.values()
  }
}

function noop() {}

function allowAll() {
  return false
}

function shouldForceRelaying(code) {
  return (
    code === 'HOLEPUNCH_ABORTED' ||
    code === 'HOLEPUNCH_DOUBLE_RANDOMIZED_NATS' ||
    code === 'REMOTE_NOT_HOLEPUNCHABLE'
  )
}

function shouldBan() {
  // return !!err && err.name === 'HypercoreError' && err.code === 'INVALID_OPERATION'
  return false
}

function toRelayFunction(relayThrough) {
  return typeof relayThrough === 'function'
    ? relayThrough
    : (force, swarm) => (force || swarm.dht.randomized ? relayThrough : null)
}
module.exports = class BulkTimer {
  constructor(time, fn) {
    this._time = time
    this._fn = fn
    this._interval = null
    this._next = []
    this._pending = []
    this._destroyed = false
  }

  destroy() {
    if (this._destroyed) return
    this._destroyed = true
    clearInterval(this._interval)
    this._interval = null
  }

  _ontick() {
    if (!this._next.length && !this._pending.length) return
    if (this._next.length) this._fn(this._next)
    this._next = this._pending
    this._pending = []
  }

  add(info) {
    if (this._destroyed) return
    if (!this._interval) {
      this._interval = setInterval(this._ontick.bind(this), Math.floor(this._time * 0.66))
    }

    this._pending.push(info)
  }
}
const b4a = require('b4a')

module.exports = class ConnectionSet {
  constructor() {
    this._byPublicKey = new Map()
  }

  [Symbol.iterator]() {
    return this._byPublicKey.values()
  }

  get size() {
    return this._byPublicKey.size
  }

  has(publicKey) {
    return this._byPublicKey.has(toHex(publicKey))
  }

  get(publicKey) {
    return this._byPublicKey.get(toHex(publicKey))
  }

  add(connection) {
    this._byPublicKey.set(b4a.toString(connection.remotePublicKey, 'hex'), connection)
  }

  delete(connection) {
    const keyString = b4a.toString(connection.remotePublicKey, 'hex')
    const existing = this._byPublicKey.get(keyString)
    if (existing !== connection) return
    this._byPublicKey.delete(keyString)
  }
}

function toHex(b) {
  return typeof b === 'string' ? b : b4a.toString(b, 'hex')
}
const safetyCatch = require('safety-catch')
const b4a = require('b4a')

const REFRESH_INTERVAL = 1000 * 60 * 10 // 10 min
const RANDOM_JITTER = 1000 * 60 * 2 // 2 min
const DELAY_GRACE_PERIOD = 1000 * 30 // 30s

const MAX_DISCOVERY_CACHE = 64

module.exports = class PeerDiscovery {
  constructor(
    swarm,
    topic,
    { limit = Infinity, wait = null, suspended = false, onpeer = noop, onerror = safetyCatch }
  ) {
    this.limit = limit
    this.swarm = swarm
    this.topic = topic
    this.isClient = false
    this.isServer = false
    this.destroyed = false
    this.destroying = null
    this.suspended = suspended

    this._sessions = []
    this._clientSessions = 0
    this._serverSessions = 0

    this._onpeer = onpeer
    this._onerror = onerror

    this._discovered = new Set()
    this._activeQuery = null
    this._timer = null
    this._currentRefresh = null
    this._closestNodes = null
    this._firstAnnounce = true
    this._needsUnannounce = false
    this._refreshes = 0
    this._wait = wait
  }

  session({ server = true, client = true, limit = Infinity, onerror = safetyCatch }) {
    if (this.destroyed) throw new Error('PeerDiscovery is destroyed')
    const session = new PeerDiscoverySession(this)
    session.refresh({ server, client, limit }).catch(onerror)
    this._sessions.push(session)
    return session
  }

  _refreshLater(eager) {
    const jitter = Math.round(Math.random() * RANDOM_JITTER)
    const delay = !eager ? REFRESH_INTERVAL + jitter : jitter

    if (this._timer) clearTimeout(this._timer)

    const startTime = Date.now()
    this._timer = setTimeout(() => {
      // If your laptop went to sleep, and is coming back online...
      const overdue = Date.now() - startTime > delay + DELAY_GRACE_PERIOD
      if (overdue) this._refreshLater(true)
      else this.refresh().catch(this._onerror)
    }, delay)
  }

  _isActive() {
    return !this.destroyed && !this.suspended
  }

  // TODO: Allow announce to be an argument to this
  // TODO: Maybe announce should be a setter?
  async _refresh() {
    if (this.suspended) return
    const clock = ++this._refreshes

    if (this._wait) {
      await this._wait
      this._wait = null
      if (clock !== this._refreshes || !this._isActive()) return
    }

    const clear = this.isServer && this._firstAnnounce
    if (clear) this._firstAnnounce = false

    const opts = {
      clear,
      closestNodes: this._closestNodes
    }

    if (this.isServer) {
      await this.swarm.listen()
      // if a parallel refresh is happening, yield to the new one
      if (clock !== this._refreshes || !this._isActive()) return
      this._needsUnannounce = true
    }

    let limit = this.limit

    if (limit < Infinity && limit > 0) {
      for (const id of this._discovered) {
        if (!this.swarm.connections.has(id)) continue
        if (--limit === 0) break
      }
    }

    this._discovered.clear()

    const announcing = this.isServer
    const query = (this._activeQuery = announcing
      ? this.swarm.dht.announce(
          this.topic,
          this.swarm.keyPair,
          this.swarm.server.relayAddresses,
          opts
        )
      : this._needsUnannounce
        ? this.swarm.dht.lookupAndUnannounce(this.topic, this.swarm.keyPair, opts)
        : this.swarm.dht.lookup(this.topic, opts))

    try {
      for await (const data of this._activeQuery) {
        if (!this.isClient || !this._isActive()) continue
        for (const peer of data.peers) {
          if (limit < Infinity) {
            const id = b4a.toString(peer.publicKey, 'hex')

            if (this._discovered.size < MAX_DISCOVERY_CACHE) {
              this._discovered.add(id)
            }

            if (limit === 0) continue

            // there is a chance it has updated a connection during discovery and we go over
            // the limit - thats acceptable to avoid a complexity spiral here.
            if (!this.swarm.connections.has(id)) limit--
          }

          this._onpeer(peer, data)
        }
      }
    } catch (err) {
      if (this._isActive()) throw err
    } finally {
      if (this._activeQuery === query) {
        this._activeQuery = null
        if (!this.destroyed && !this.suspended) this._refreshLater(false)
      }
    }

    // This is set at the very end, when the query completes successfully.
    this._closestNodes = query.closestNodes

    if (clock !== this._refreshes) return

    // In this is the latest query, unannounce has been fulfilled as well
    if (!announcing) this._needsUnannounce = false
  }

  async refresh() {
    if (this.destroyed) throw new Error('PeerDiscovery is destroyed')

    const server = this._serverSessions > 0
    const client = this._clientSessions > 0

    if (this.suspended) return

    if (server === this.isServer && client === this.isClient) {
      if (this._currentRefresh) return this._currentRefresh
      this._currentRefresh = this._refresh()
    } else {
      if (this._activeQuery) this._activeQuery.destroy()
      this.isServer = server
      this.isClient = client
      this._currentRefresh = this._refresh()
    }

    const refresh = this._currentRefresh
    try {
      await refresh
    } catch {
      return false
    } finally {
      if (refresh === this._currentRefresh) {
        this._currentRefresh = null
      }
    }

    return true
  }

  async flushed() {
    if (this.swarm.listening) await this.swarm.listening

    try {
      await this._currentRefresh
      return true
    } catch {
      return false
    }
  }

  async _destroyMaybe() {
    if (this.destroyed) return

    try {
      if (this._sessions.length === 0) await this.swarm.leave(this.topic)
      else if (this._serverSessions === 0 && this._needsUnannounce) await this.refresh()
    } catch (err) {
      // ignore network failures here, as we are tearing down
      safetyCatch(err)
    }
  }

  destroy() {
    if (this.destroying) return this.destroying
    this.destroying = this._destroy()
    return this.destroying
  }

  async _abort(log) {
    const id = log === noop ? '' : b4a.toString(this.topic, 'hex')

    log('Aborting discovery', id)
    if (this._wait) await this._wait
    log('Aborting discovery (post wait)', id)

    if (this._activeQuery) {
      this._activeQuery.destroy()
      this._activeQuery = null
    }
    if (this._timer) {
      clearTimeout(this._timer)
      this._timer = null
    }

    let nodes = this._closestNodes

    if (this._currentRefresh) {
      try {
        await this._currentRefresh
      } catch {
        // If the destroy causes the refresh to fail, suppress it.
      }
    }

    log('Aborting discovery (post refresh)', id)
    if (this._isActive()) return

    if (!nodes) nodes = this._closestNodes
    else if (this._closestNodes !== nodes) {
      const len = nodes.length
      for (const newer of this._closestNodes) {
        if (newer.id && !hasNode(nodes, len, newer)) nodes.push(newer)
      }
    }

    if (this._needsUnannounce) {
      log('Unannouncing discovery', id)
      if (nodes && nodes.length) {
        await this.swarm.dht.unannounce(this.topic, this.swarm.keyPair, {
          closestNodes: nodes,
          onlyClosestNodes: true,
          force: true
        })
      }
      this._needsUnannounce = false
      log('Unannouncing discovery (done)', id)
    }
  }

  _destroy() {
    if (this.destroyed) return
    this.destroyed = true
    return this._abort(noop)
  }

  async suspend({ log = noop } = {}) {
    if (this.suspended) return
    this.suspended = true
    try {
      await this._abort(log)
    } catch {
      // ignore
    }
  }

  resume() {
    if (!this.suspended) return
    this.suspended = false
    this.refresh().catch(noop)
  }
}

class PeerDiscoverySession {
  constructor(discovery) {
    this.discovery = discovery
    this.isClient = false
    this.isServer = false
    this.destroyed = false
  }

  get swarm() {
    return this.discovery.swarm
  }

  get topic() {
    return this.discovery.topic
  }

  async refresh({ client = this.isClient, server = this.isServer, limit = Infinity } = {}) {
    if (this.destroyed) throw new Error('PeerDiscovery is destroyed')
    if (!client && !server) throw new Error('Cannot refresh with neither client nor server option')

    if (client !== this.isClient) {
      this.isClient = client
      this.discovery._clientSessions += client ? 1 : -1
    }

    if (server !== this.isServer) {
      this.isServer = server
      this.discovery._serverSessions += server ? 1 : -1
    }

    this.discovery.limit = limit

    return this.discovery.refresh()
  }

  async flushed() {
    return this.discovery.flushed()
  }

  async destroy() {
    if (this.destroyed) return
    this.destroyed = true

    if (this.isClient) this.discovery._clientSessions--
    if (this.isServer) this.discovery._serverSessions--

    const index = this.discovery._sessions.indexOf(this)
    const head = this.discovery._sessions.pop()

    if (head !== this) this.discovery._sessions[index] = head

    return this.discovery._destroyMaybe()
  }
}

function hasNode(nodes, len, node) {
  for (let i = 0; i < len; i++) {
    const existing = nodes[i]
    if (existing.id && b4a.equals(existing.id, node.id)) return true
  }

  return false
}

function noop() {}
const { EventEmitter } = require('events')
const b4a = require('b4a')
const unslab = require('unslab')

const MIN_CONNECTION_TIME = 15000

const VERY_LOW_PRIORITY = 0
const LOW_PRIORITY = 1
const NORMAL_PRIORITY = 2
const HIGH_PRIORITY = 3
const VERY_HIGH_PRIORITY = 4

module.exports = class PeerInfo extends EventEmitter {
  constructor({ publicKey, relayAddresses }) {
    super()

    this.publicKey = unslab(publicKey)
    this.relayAddresses = relayAddresses

    this.reconnecting = true
    this.proven = false
    this.connectedTime = -1
    this.disconnectedTime = 0
    this.banned = false
    this.tried = false
    this.explicit = false
    this.waiting = false
    this.forceRelaying = false

    // Set by the Swarm
    this.queued = false
    this.client = false
    this.topics = [] // TODO: remove on next major (check with mafintosh for context)

    this.attempts = 0
    this.priority = NORMAL_PRIORITY

    // Used by shuffled-priority-queue
    this._index = 0

    // Used for flush management
    this._flushTick = 0

    // Used for topic multiplexing
    this._seenTopics = new Set()
  }

  get server() {
    return !this.client
  }

  get prioritized() {
    return this.priority >= NORMAL_PRIORITY
  }

  _getPriority() {
    const peerIsStale = this.tried && !this.proven
    if (peerIsStale || this.attempts > 3) return VERY_LOW_PRIORITY
    if (this.attempts === 3) return LOW_PRIORITY
    if (this.attempts === 2) return HIGH_PRIORITY
    if (this.attempts === 1) return VERY_HIGH_PRIORITY
    return NORMAL_PRIORITY
  }

  _connected() {
    this.proven = true
    this.connectedTime = Date.now()
  }

  _disconnected() {
    this.disconnectedTime = Date.now()
    if (this.connectedTime > -1) {
      if (this.disconnectedTime - this.connectedTime >= MIN_CONNECTION_TIME) this.attempts = 0 // fast retry
      this.connectedTime = -1
    }
    this.attempts++
  }

  _deprioritize() {
    this.attempts = 3
  }

  _reset() {
    this.client = false
    this.proven = false
    this.tried = false
    this.attempts = 0
  }

  _updatePriority() {
    if (this.explicit && this.attempts > 3) this._deprioritize()
    if (this.banned || this.queued || this.attempts > 3) return false
    this.priority = this._getPriority()
    return true
  }

  _topic(topic) {
    const topicString = b4a.toString(topic, 'hex')
    if (this._seenTopics.has(topicString)) return
    this._seenTopics.add(topicString)
    this.topics.push(topic)
    this.emit('topic', topic)
  }

  reconnect(val) {
    this.reconnecting = !!val
  }

  ban(val) {
    this.banned = !!val
  }

  shouldGC() {
    return !(this.banned || this.queued || this.explicit || this.waiting)
  }
}
const BulkTimer = require('./bulk-timer')

const BACKOFF_JITTER = 500
const BACKOFF_S = 1000 + Math.round(BACKOFF_JITTER * Math.random())
const BACKOFF_M = 5000 + Math.round(2 * BACKOFF_JITTER * Math.random())
const BACKOFF_L = 15000 + Math.round(4 * BACKOFF_JITTER * Math.random())
const BACKOFF_X = 1000 * 60 * 10 + Math.round(240 * BACKOFF_JITTER * Math.random())

module.exports = class RetryTimer {
  constructor(
    push,
    { backoffs = [BACKOFF_S, BACKOFF_M, BACKOFF_L, BACKOFF_X], jitter = BACKOFF_JITTER } = {}
  ) {
    this.jitter = jitter
    this.backoffs = backoffs

    this._sTimer = new BulkTimer(backoffs[0] + Math.round(jitter * Math.random()), push)
    this._mTimer = new BulkTimer(backoffs[1] + Math.round(jitter * Math.random()), push)
    this._lTimer = new BulkTimer(backoffs[2] + Math.round(jitter * Math.random()), push)
    this._xTimer = new BulkTimer(backoffs[3] + Math.round(jitter * Math.random()), push)
  }

  _selectRetryTimer(peerInfo) {
    if (peerInfo.banned || !peerInfo.reconnecting) return null

    if (peerInfo.attempts > 3) {
      return peerInfo.explicit ? this._xTimer : null
    }

    if (peerInfo.attempts === 0) return this._sTimer
    if (peerInfo.proven) {
      switch (peerInfo.attempts) {
        case 1:
          return this._sTimer
        case 2:
          return this._mTimer
        case 3:
          return this._lTimer
      }
    } else {
      switch (peerInfo.attempts) {
        case 1:
          return this._mTimer
        case 2:
          return this._lTimer
        case 3:
          return this._lTimer
      }
    }

    return null
  }

  add(peerInfo) {
    const timer = this._selectRetryTimer(peerInfo)
    if (!timer) return false

    timer.add(peerInfo)
    return true
  }

  destroy() {
    this._sTimer.destroy()
    this._mTimer.destroy()
    this._lTimer.destroy()
    this._xTimer.destroy()
  }
}
{
  "name": "hyperswarm",
  "version": "4.17.0",
  "description": "A distributed networking stack for connecting peers",
  "files": [
    "index.js",
    "lib/**.js"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    },
    "process": {
      "bare": "bare-process",
      "default": "process"
    }
  },
  "dependencies": {
    "b4a": "^1.3.1",
    "bare-events": "^2.2.0",
    "hyperdht": "^6.21.0",
    "safety-catch": "^1.0.2",
    "shuffled-priority-queue": "^2.1.0",
    "streamx": "^2.22.1",
    "unslab": "^1.3.0"
  },
  "devDependencies": {
    "bare-process": "^4.2.2",
    "brittle": "^3.0.2",
    "hypercore-crypto": "^3.4.0",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "which-runtime": "^1.3.2"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:generate": "brittle -r test/all.js test/*.js",
    "test:node": "brittle-node --coverage test/*.js",
    "test:bare": "bare test/all.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/hyperswarm.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "contributors": [
    "David Mark Clements (@davidmarkclem)",
    "Andrew Osheroff (@andrewosh)"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/hyperswarm/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperswarm"
}
const { EventEmitter } = require('events')

module.exports = class RoutingTable extends EventEmitter {
  constructor (id, opts) {
    if (!opts) opts = {}

    super()

    this.id = id
    this.k = opts.k || 20
    this.size = 0
    this.rows = new Array(id.length * 8)
  }

  add (node) {
    const i = this._diff(node.id)

    let row = this.rows[i]

    if (!row) {
      row = this.rows[i] = new Row(this, i)
      this.emit('row', row)
    }

    const len = row.nodes.length
    if (!row.add(node, this.k)) return false

    this.size += row.nodes.length - len
    return true
  }

  remove (id) {
    const i = this._diff(id)
    const row = this.rows[i]
    if (!row) return false
    if (!row.remove(id)) return false
    this.size--
    return true
  }

  get (id) {
    const i = this._diff(id)
    const row = this.rows[i]
    if (!row) return null
    return row.get(id)
  }

  has (id) {
    return this.get(id) !== null
  }

  random () {
    let n = (Math.random() * this.size) | 0

    for (let i = 0; i < this.rows.length; i++) {
      const r = this.rows[i]
      if (!r) continue
      if (n < r.nodes.length) return r.nodes[n]
      n -= r.nodes.length
    }

    return null
  }

  closest (id, k) {
    if (!k) k = this.k

    const result = []
    const d = this._diff(id)

    // push close nodes
    for (let i = d; i >= 0 && result.length < k; i--) this._pushNodes(i, k, result)

    // if we don't have enough close nodes, populate from other rows, re the paper
    for (let i = d + 1; i < this.rows.length && result.length < k; i++) this._pushNodes(i, k, result)

    return result
  }

  _pushNodes (i, k, result) {
    const row = this.rows[i]
    if (!row) return

    const missing = Math.min(k - result.length, row.nodes.length)
    for (let j = 0; j < missing; j++) result.push(row.nodes[j])
  }

  toArray () {
    return this.closest(this.id, Infinity)
  }

  _diff (id) {
    for (let i = 0; i < id.length; i++) {
      const a = id[i]
      const b = this.id[i]

      if (a !== b) return i * 8 + Math.clz32(a ^ b) - 24
    }

    return this.rows.length - 1
  }
}

class Row extends EventEmitter {
  constructor (table, index) {
    super()

    this.data = null // can be used be upstream for whatevs
    this.byteOffset = index >> 3
    this.index = index
    this.table = table
    this.nodes = []
  }

  add (node) {
    const id = node.id

    let l = 0
    let r = this.nodes.length - 1

    while (l <= r) {
      const m = (l + r) >> 1
      const c = this.compare(id, this.nodes[m].id)

      if (c === 0) {
        this.nodes[m] = node
        return true
      }

      if (c < 0) r = m - 1
      else l = m + 1
    }

    if (this.nodes.length >= this.table.k) {
      this.emit('full', node)
      return false
    }

    this.insert(l, node)
    return true
  }

  remove (id) {
    let l = 0
    let r = this.nodes.length - 1

    while (l <= r) {
      const m = (l + r) >> 1
      const c = this.compare(id, this.nodes[m].id)

      if (c === 0) {
        this.splice(m)
        return true
      }

      if (c < 0) r = m - 1
      else l = m + 1
    }

    return false
  }

  get (id) {
    let l = 0
    let r = this.nodes.length - 1

    while (l <= r) {
      const m = (l + r) >> 1
      const node = this.nodes[m]
      const c = this.compare(id, node.id)

      if (c === 0) return node
      if (c < 0) r = m - 1
      else l = m + 1
    }

    return null
  }

  insert (i, node) {
    this.nodes.push(node) // push node or null or whatevs, just trying to not be polymorphic
    for (let j = this.nodes.length - 1; j > i; j--) this.nodes[j] = this.nodes[j - 1]
    this.nodes[i] = node
    this.emit('add', node)
  }

  splice (i) {
    for (; i < this.nodes.length - 1; i++) this.nodes[i] = this.nodes[i + 1]
    this.emit('remove', this.nodes.pop())
  }

  // very likely they diverge after a couple of bytes so a simple impl, like this is prop fastest vs Buffer.compare
  compare (a, b) {
    for (let i = this.byteOffset; i < a.length; i++) {
      const ai = a[i]
      const bi = b[i]
      if (ai === bi) continue
      return ai < bi ? -1 : 1
    }
    return 0
  }
}
{
  "name": "kademlia-routing-table",
  "version": "1.0.6",
  "description": "XOR based routing table used for P2P networks such as a Kademlia DHT.",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "dependencies": {
    "bare-events": "^2.2.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "standard": "^17.1.0"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "keywords": [
    "kademlia",
    "p2p",
    "k-bucket",
    "k-buckets",
    "xor",
    "routing",
    "distributed",
    "systems"
  ],
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/kademlia-routing-table.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/kademlia-routing-table/issues"
  },
  "homepage": "https://github.com/mafintosh/kademlia-routing-table"
}
module.exports = assert

class AssertionError extends Error {}
AssertionError.prototype.name = 'AssertionError'

/**
 * Minimal assert function
 * @param  {any} t Value to check if falsy
 * @param  {string=} m Optional assertion error message
 * @throws {AssertionError}
 */
function assert (t, m) {
  if (!t) {
    var err = new AssertionError(m)
    if (Error.captureStackTrace) Error.captureStackTrace(err, assert)
    throw err
  }
}
{
  "name": "nanoassert",
  "version": "2.0.0",
  "description": "Nanoscale assertion module",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "tape": "^4.9.1"
  },
  "scripts": {
    "test": "tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/emilbayes/nanoassert.git"
  },
  "keywords": [
    "assert",
    "unassert",
    "power-assert",
    "tiny",
    "nano",
    "pico"
  ],
  "author": "Emil Bay <github@tixz.dk>",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/emilbayes/nanoassert/issues"
  },
  "homepage": "https://github.com/emilbayes/nanoassert#readme"
}
module.exports = class NatSampler {
  constructor () {
    this.host = null
    this.port = 0
    this.size = 0

    this._a = null
    this._b = null
    this._threshold = 0
    this._top = 0
    this._samples = []
  }

  add (host, port) {
    const a = this._bump(host, port, 2)
    const b = this._bump(host, 0, 1)

    if (this._samples.length < 32) {
      this.size++
      this._threshold = this.size - (this.size < 4 ? 0 : this.size < 8 ? 1 : this.size < 12 ? 2 : 3)
      this._samples.push(a, b)
      this._top += 2
    } else {
      if (this._top === 32) this._top = 0

      const oa = this._samples[this._top]
      this._samples[this._top++] = a
      oa.hits--

      const ob = this._samples[this._top]
      this._samples[this._top++] = b
      ob.hits--
    }

    if (this._a === null || this._a.hits < a.hits) this._a = a
    if (this._b === null || this._b.hits < b.hits) this._b = b

    if (this._a.hits >= this._threshold) {
      this.host = this._a.host
      this.port = this._a.port
    } else if (this._b.hits >= this._threshold) {
      this.host = this._b.host
      this.port = 0
    } else {
      this.host = null
      this.port = 0
    }

    return a.hits
  }

  _bump (host, port, inc) {
    for (let i = 0; i < 4; i++) {
      const j = (this._top - inc - (2 * i)) & 31
      if (j >= this._samples.length) return { host, port, hits: 1 }
      const s = this._samples[j]
      if (s.port === port && s.host === host) {
        s.hits++
        return s
      }
    }
    return { host, port, hits: 1 }
  }
}
{
  "name": "nat-sampler",
  "version": "1.0.1",
  "description": "Sample addresses to figure out if a host + port is consistent",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^16.0.3",
    "tape": "^5.2.2"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/nat-sampler.git"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/nat-sampler/issues"
  },
  "homepage": "https://github.com/mafintosh/nat-sampler"
}
/* eslint-disable camelcase */
const sodium = require('sodium-universal')
const assert = require('nanoassert')
const b4a = require('b4a')

const DHLEN = sodium.crypto_scalarmult_ed25519_BYTES
const PKLEN = sodium.crypto_scalarmult_ed25519_BYTES
const SCALARLEN = sodium.crypto_scalarmult_ed25519_BYTES
const SKLEN = sodium.crypto_sign_SECRETKEYBYTES
const ALG = 'Ed25519'

module.exports = {
  DHLEN,
  PKLEN,
  SCALARLEN,
  SKLEN,
  ALG,
  name: ALG,
  generateKeyPair,
  dh
}

function generateKeyPair (privKey) {
  if (privKey) return generateSeedKeyPair(privKey.subarray(0, 32))

  const keyPair = {}
  keyPair.secretKey = b4a.alloc(SKLEN)
  keyPair.publicKey = b4a.alloc(PKLEN)

  sodium.crypto_sign_keypair(keyPair.publicKey, keyPair.secretKey)
  return keyPair
}

function generateSeedKeyPair (seed) {
  const keyPair = {}
  keyPair.secretKey = b4a.alloc(SKLEN)
  keyPair.publicKey = b4a.alloc(PKLEN)

  sodium.crypto_sign_seed_keypair(keyPair.publicKey, keyPair.secretKey, seed)
  return keyPair
}

function dh (publicKey, { scalar, secretKey }) {
  // tweaked keys expose scalar directly
  if (!scalar) {
    assert(secretKey.byteLength === SKLEN)

    // libsodium stores seed not actual scalar
    const sk = b4a.alloc(64)
    sodium.crypto_hash_sha512(sk, secretKey.subarray(0, 32))
    sk[0] &= 248
    sk[31] &= 127
    sk[31] |= 64

    scalar = sk.subarray(0, 32)
  }

  assert(scalar.byteLength === SCALARLEN)
  assert(publicKey.byteLength === PKLEN)

  const output = b4a.alloc(DHLEN)

  // we clamp if necessary above
  sodium.crypto_scalarmult_ed25519_noclamp(
    output,
    scalar,
    publicKey
  )

  return output
}
{
  "name": "noise-curve-ed",
  "version": "2.1.0",
  "description": "Ed25519 elliptic curve operations for [`noise-handshake`](https://github.com/chm-diederichs/noise-handshake)",
  "main": "index.js",
  "scripts": {
    "test": "npx standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/chm-diederichs/noise-curve-ed.git"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/chm-diederichs/noise-curve-ed/issues"
  },
  "homepage": "https://github.com/chm-diederichs/noise-curve-ed#readme",
  "dependencies": {
    "b4a": "^1.1.0",
    "nanoassert": "^2.0.0",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "noise-handshake": "^3.0.0",
    "standard": "^16.0.3",
    "tape": "^5.2.2"
  }
}
const sodium = require('sodium-universal')
const b4a = require('b4a')

module.exports = class CipherState {
  constructor (key) {
    this.key = key || null
    this.nonce = 0
    this.CIPHER_ALG = 'ChaChaPoly'
  }

  initialiseKey (key) {
    this.key = key
    this.nonce = 0
  }

  setNonce (nonce) {
    this.nonce = nonce
  }

  encrypt (plaintext, ad) {
    if (!this.hasKey) return plaintext
    if (!ad) ad = b4a.alloc(0)

    const ciphertext = encryptWithAD(this.key, this.nonce, ad, plaintext)
    if (ciphertext.length > 65535) throw new Error(`ciphertext length of ${ciphertext.length} exceeds maximum Noise message length of 65535`)
    this.nonce++

    return ciphertext
  }

  decrypt (ciphertext, ad) {
    if (!this.hasKey) return ciphertext
    if (!ad) ad = b4a.alloc(0)
    if (ciphertext.length > 65535) throw new Error(`ciphertext length of ${ciphertext.length} exceeds maximum Noise message length of 65535`)

    const plaintext = decryptWithAD(this.key, this.nonce, ad, ciphertext)
    this.nonce++

    return plaintext
  }

  get hasKey () {
    return this.key !== null
  }

  _clear () {
    sodium.sodium_memzero(this.key)
    this.key = null
    this.nonce = null
  }

  static get MACBYTES () {
    return 16
  }

  static get NONCEBYTES () {
    return 8
  }

  static get KEYBYTES () {
    return 32
  }
}

function encryptWithAD (key, counter, additionalData, plaintext) {
  // for our purposes, additionalData will always be a pubkey so we encode from hex
  if (!b4a.isBuffer(additionalData)) additionalData = b4a.from(additionalData, 'hex')
  if (!b4a.isBuffer(plaintext)) plaintext = b4a.from(plaintext, 'hex')

  const nonce = b4a.alloc(sodium.crypto_aead_chacha20poly1305_ietf_NPUBBYTES)
  const view = new DataView(nonce.buffer, nonce.byteOffset, nonce.byteLength)
  view.setUint32(4, counter, true)

  const ciphertext = b4a.alloc(plaintext.byteLength + sodium.crypto_aead_chacha20poly1305_ietf_ABYTES)

  sodium.crypto_aead_chacha20poly1305_ietf_encrypt(ciphertext, plaintext, additionalData, null, nonce, key)
  return ciphertext
}

function decryptWithAD (key, counter, additionalData, ciphertext) {
  // for our purposes, additionalData will always be a pubkey so we encode from hex
  if (!b4a.isBuffer(additionalData)) additionalData = b4a.from(additionalData, 'hex')
  if (!b4a.isBuffer(ciphertext)) ciphertext = b4a.from(ciphertext, 'hex')

  const nonce = b4a.alloc(sodium.crypto_aead_chacha20poly1305_ietf_NPUBBYTES)
  const view = new DataView(nonce.buffer, nonce.byteOffset, nonce.byteLength)
  view.setUint32(4, counter, true)

  const plaintext = b4a.alloc(ciphertext.byteLength - sodium.crypto_aead_chacha20poly1305_ietf_ABYTES)

  sodium.crypto_aead_chacha20poly1305_ietf_decrypt(plaintext, null, ciphertext, additionalData, nonce, key)
  return plaintext
}
/* eslint-disable camelcase */
const {
  crypto_kx_SEEDBYTES,
  crypto_kx_keypair,
  crypto_kx_seed_keypair,
  crypto_scalarmult_BYTES,
  crypto_scalarmult_SCALARBYTES,
  crypto_scalarmult,
  crypto_scalarmult_base
} = require('sodium-universal')

const assert = require('nanoassert')
const b4a = require('b4a')

const DHLEN = crypto_scalarmult_BYTES
const PKLEN = crypto_scalarmult_BYTES
const SKLEN = crypto_scalarmult_SCALARBYTES
const SEEDLEN = crypto_kx_SEEDBYTES
const ALG = '25519'

module.exports = {
  DHLEN,
  PKLEN,
  SKLEN,
  SEEDLEN,
  ALG,
  generateKeyPair,
  generateSeedKeyPair,
  dh
}

function generateKeyPair (privKey) {
  const keyPair = {}

  keyPair.secretKey = privKey || b4a.alloc(SKLEN)
  keyPair.publicKey = b4a.alloc(PKLEN)

  if (privKey) {
    crypto_scalarmult_base(keyPair.publicKey, keyPair.secretKey)
  } else {
    crypto_kx_keypair(keyPair.publicKey, keyPair.secretKey)
  }

  return keyPair
}

function generateSeedKeyPair (seed) {
  assert(seed.byteLength === SKLEN)

  const keyPair = {}
  keyPair.secretKey = b4a.alloc(SKLEN)
  keyPair.publicKey = b4a.alloc(PKLEN)

  crypto_kx_seed_keypair(keyPair.publicKey, keyPair.secretKey, seed)
  return keyPair
}

function dh (publicKey, { secretKey }) {
  assert(secretKey.byteLength === SKLEN)
  assert(publicKey.byteLength === PKLEN)

  const output = b4a.alloc(DHLEN)

  crypto_scalarmult(
    output,
    secretKey,
    publicKey
  )

  return output
}
const hmacBlake2b = require('./hmac')
const b4a = require('b4a')

const HASHLEN = 64

module.exports = {
  hkdf,
  HASHLEN
}

// HMAC-based Extract-and-Expand KDF
// https://www.ietf.org/rfc/rfc5869.txt

function hkdf (salt, inputKeyMaterial, info = '', length = 2 * HASHLEN) {
  const pseudoRandomKey = hkdfExtract(salt, inputKeyMaterial)
  return hkdfExpand(pseudoRandomKey, info, length)
}

function hkdfExtract (salt, inputKeyMaterial) {
  const hmac = b4a.alloc(HASHLEN)
  return hmacDigest(hmac, salt, inputKeyMaterial)
}

function hkdfExpand (key, info, length) {
  // Put in dedicated slab to avoid keeping shared slab from being gc'ed
  const buffer = b4a.allocUnsafeSlow(length)

  const infoBuf = b4a.from(info)
  let prev = infoBuf

  const result = []
  for (let i = 0; i < length; i += HASHLEN) {
    const pos = b4a.from([(i / HASHLEN) + 1])

    const out = buffer.subarray(i, i + HASHLEN)
    result.push(out)

    prev = hmacDigest(out, key, [prev, infoBuf, pos])
  }

  return result
}

function hmacDigest (out, key, input) {
  hmacBlake2b(out, input, key)
  return out
}
/* eslint-disable camelcase */
const b4a = require('b4a')
const { sodium_memzero, crypto_generichash, crypto_generichash_batch } = require('sodium-universal')

const HASHLEN = 64
const BLOCKLEN = 128
const scratch = b4a.alloc(BLOCKLEN * 3)
const HMACKey = scratch.subarray(BLOCKLEN * 0, BLOCKLEN * 1)
const OuterKeyPad = scratch.subarray(BLOCKLEN * 1, BLOCKLEN * 2)
const InnerKeyPad = scratch.subarray(BLOCKLEN * 2, BLOCKLEN * 3)

// Post-fill is done in the cases where someone caught an exception that
// happened before we were able to clear data at the end

module.exports = function hmac (out, batch, key) {
  if (key.byteLength > BLOCKLEN) {
    crypto_generichash(HMACKey.subarray(0, HASHLEN), key)
    sodium_memzero(HMACKey.subarray(HASHLEN))
  } else {
    // Covers key <= BLOCKLEN
    HMACKey.set(key)
    sodium_memzero(HMACKey.subarray(key.byteLength))
  }

  for (let i = 0; i < HMACKey.byteLength; i++) {
    OuterKeyPad[i] = 0x5c ^ HMACKey[i]
    InnerKeyPad[i] = 0x36 ^ HMACKey[i]
  }
  sodium_memzero(HMACKey)

  crypto_generichash_batch(out, [InnerKeyPad].concat(batch))
  sodium_memzero(InnerKeyPad)
  crypto_generichash_batch(out, [OuterKeyPad, out])
  sodium_memzero(OuterKeyPad)
}

module.exports.BYTES = HASHLEN
module.exports.KEYBYTES = BLOCKLEN
const assert = require('nanoassert')
const b4a = require('b4a')

const SymmetricState = require('./symmetric-state')
const { HASHLEN } = require('./hkdf')

const PRESHARE_IS = Symbol('initiator static key preshared')
const PRESHARE_RS = Symbol('responder static key preshared')

const TOK_PSK = Symbol('psk')

const TOK_S = Symbol('s')
const TOK_E = Symbol('e')

const TOK_ES = Symbol('es')
const TOK_SE = Symbol('se')
const TOK_EE = Symbol('ee')
const TOK_SS = Symbol('ss')

const HANDSHAKES = Object.freeze({
  NN: [
    [TOK_E],
    [TOK_E, TOK_EE]
  ],
  NNpsk0: [
    [TOK_PSK, TOK_E],
    [TOK_E, TOK_EE]
  ],
  XX: [
    [TOK_E],
    [TOK_E, TOK_EE, TOK_S, TOK_ES],
    [TOK_S, TOK_SE]
  ],
  XXpsk0: [
    [TOK_PSK, TOK_E],
    [TOK_E, TOK_EE, TOK_S, TOK_ES],
    [TOK_S, TOK_SE]
  ],
  IK: [
    PRESHARE_RS,
    [TOK_E, TOK_ES, TOK_S, TOK_SS],
    [TOK_E, TOK_EE, TOK_SE]
  ],
  XK: [
    PRESHARE_RS,
    [TOK_E, TOK_ES],
    [TOK_E, TOK_EE],
    [TOK_S, TOK_SE]
  ]
})

class Writer {
  constructor () {
    this.size = 0
    this.buffers = []
  }

  push (b) {
    this.size += b.byteLength
    this.buffers.push(b)
  }

  end () {
    const all = b4a.alloc(this.size)
    let offset = 0
    for (const b of this.buffers) {
      all.set(b, offset)
      offset += b.byteLength
    }
    return all
  }
}

class Reader {
  constructor (buf) {
    this.offset = 0
    this.buffer = buf
  }

  shift (n) {
    const start = this.offset
    const end = this.offset += n
    if (end > this.buffer.byteLength) throw new Error('Insufficient bytes')
    return this.buffer.subarray(start, end)
  }

  end () {
    return this.shift(this.buffer.byteLength - this.offset)
  }
}

module.exports = class NoiseState extends SymmetricState {
  constructor (pattern, initiator, staticKeypair, opts = {}) {
    super(opts)

    this.s = staticKeypair || this.curve.generateKeyPair()
    this.e = null

    this.psk = null
    if (opts && opts.psk) this.psk = opts.psk

    this.re = null
    this.rs = null

    this.pattern = pattern
    this.handshake = HANDSHAKES[this.pattern].slice()

    this.isPskHandshake = !!this.psk && hasPskToken(this.handshake)

    this.protocol = b4a.from([
      'Noise',
      this.pattern,
      this.DH_ALG,
      this.CIPHER_ALG,
      'BLAKE2b'
    ].join('_'))

    this.initiator = initiator
    this.complete = false

    this.rx = null
    this.tx = null
    this.hash = null
  }

  initialise (prologue, remoteStatic) {
    if (this.protocol.byteLength <= HASHLEN) this.digest.set(this.protocol)
    else this.mixHash(this.protocol)

    this.chainingKey = b4a.from(this.digest)

    this.mixHash(prologue)

    while (!Array.isArray(this.handshake[0])) {
      const message = this.handshake.shift()

      // handshake steps should be as arrays, only
      // preshare tokens are provided otherwise
      assert(message === PRESHARE_RS || message === PRESHARE_IS,
        'Unexpected pattern')

      const takeRemoteKey = this.initiator
        ? message === PRESHARE_RS
        : message === PRESHARE_IS

      if (takeRemoteKey) this.rs = remoteStatic

      const key = takeRemoteKey ? this.rs : this.s.publicKey
      assert(key != null, 'Remote pubkey required')

      this.mixHash(key)
    }
  }

  final () {
    const [k1, k2] = this.split()

    this.tx = this.initiator ? k1 : k2
    this.rx = this.initiator ? k2 : k1

    this.complete = true
    this.hash = this.getHandshakeHash()

    this._clear()
  }

  recv (buf) {
    const r = new Reader(buf)

    for (const pattern of this.handshake.shift()) {
      switch (pattern) {
        case TOK_PSK :
          this.mixKeyAndHash(this.psk)
          break

        case TOK_E :
          this.re = r.shift(this.curve.PKLEN)
          this.mixHash(this.re)
          if (this.isPskHandshake) this.mixKeyNormal(this.re)
          break

        case TOK_S : {
          const klen = this.hasKey ? this.curve.PKLEN + 16 : this.curve.PKLEN
          this.rs = this.decryptAndHash(r.shift(klen))
          break
        }

        case TOK_EE :
        case TOK_ES :
        case TOK_SE :
        case TOK_SS : {
          const useStatic = keyPattern(pattern, this.initiator)

          const localKey = useStatic.local ? this.s : this.e
          const remoteKey = useStatic.remote ? this.rs : this.re

          this.mixKey(remoteKey, localKey)
          break
        }

        default :
          throw new Error('Unexpected message')
      }
    }

    const payload = this.decryptAndHash(r.end())

    if (!this.handshake.length) this.final()
    return payload
  }

  send (payload = b4a.alloc(0)) {
    const w = new Writer()

    for (const pattern of this.handshake.shift()) {
      switch (pattern) {
        case TOK_PSK :
          this.mixKeyAndHash(this.psk)
          break

        case TOK_E :
          if (this.e === null) this.e = this.curve.generateKeyPair()
          this.mixHash(this.e.publicKey)
          if (this.isPskHandshake) this.mixKeyNormal(this.e.publicKey)
          w.push(this.e.publicKey)
          break

        case TOK_S :
          w.push(this.encryptAndHash(this.s.publicKey))
          break

        case TOK_ES :
        case TOK_SE :
        case TOK_EE :
        case TOK_SS : {
          const useStatic = keyPattern(pattern, this.initiator)

          const localKey = useStatic.local ? this.s : this.e
          const remoteKey = useStatic.remote ? this.rs : this.re

          this.mixKey(remoteKey, localKey)
          break
        }

        default :
          throw new Error('Unexpected message')
      }
    }

    w.push(this.encryptAndHash(payload))
    const response = w.end()

    if (!this.handshake.length) this.final()
    return response
  }

  _clear () {
    super._clear()

    this.e.secretKey.fill(0)
    this.e.publicKey.fill(0)

    this.re.fill(0)

    this.e = null
    this.re = null
  }
}

function keyPattern (pattern, initiator) {
  const ret = {
    local: false,
    remote: false
  }

  switch (pattern) {
    case TOK_EE:
      return ret

    case TOK_ES:
      ret.local ^= !initiator
      ret.remote ^= initiator
      return ret

    case TOK_SE:
      ret.local ^= initiator
      ret.remote ^= !initiator
      return ret

    case TOK_SS:
      ret.local ^= 1
      ret.remote ^= 1
      return ret
  }
}

function hasPskToken (handshake) {
  return handshake.some(x => {
    return Array.isArray(x) && x.indexOf(TOK_PSK) !== -1
  })
}
{
  "name": "noise-handshake",
  "version": "4.2.0",
  "description": "Noise protocol handshake",
  "main": "noise.js",
  "files": [
    "*.js"
  ],
  "scripts": {
    "test": "standard && brittle test/*.js"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/noise-handshake.git"
  },
  "dependencies": {
    "b4a": "^1.1.0",
    "nanoassert": "^2.0.0",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "noise-protocol": "chm-diederichs/noise-protocol.git#xx-ephemeral-key",
    "standard": "^16.0.3"
  }
}
const sodium = require('sodium-universal')
const assert = require('nanoassert')
const b4a = require('b4a')
const CipherState = require('./cipher')
const curve = require('./dh')
const { HASHLEN, hkdf } = require('./hkdf')

module.exports = class SymmetricState extends CipherState {
  constructor (opts = {}) {
    super()

    this.curve = opts.curve || curve
    this.digest = b4a.alloc(HASHLEN)
    this.chainingKey = null
    this.offset = 0

    this.DH_ALG = this.curve.ALG
  }

  mixHash (data) {
    accumulateDigest(this.digest, data)
  }

  mixKeyAndHash (key) {
    const [ck, tempH, tempK] = hkdf(this.chainingKey, key, '', 3 * HASHLEN)
    this.chainingKey = ck
    this.mixHash(tempH)
    this.initialiseKey(tempK.subarray(0, 32))
  }

  mixKeyNormal (key) {
    const [ck, tempK] = hkdf(this.chainingKey, key)
    this.chainingKey = ck
    this.initialiseKey(tempK.subarray(0, 32))
  }

  mixKey (remoteKey, localKey) {
    const dh = this.curve.dh(remoteKey, localKey)
    const hkdfResult = hkdf(this.chainingKey, dh)
    this.chainingKey = hkdfResult[0]
    this.initialiseKey(hkdfResult[1].subarray(0, 32))
  }

  encryptAndHash (plaintext) {
    const ciphertext = this.encrypt(plaintext, this.digest)
    accumulateDigest(this.digest, ciphertext)
    return ciphertext
  }

  decryptAndHash (ciphertext) {
    const plaintext = this.decrypt(ciphertext, this.digest)
    accumulateDigest(this.digest, ciphertext)
    return plaintext
  }

  getHandshakeHash (out) {
    if (!out) return this.getHandshakeHash(b4a.alloc(HASHLEN))
    assert(out.byteLength === HASHLEN, `output must be ${HASHLEN} bytes`)

    out.set(this.digest)
    return out
  }

  split () {
    const res = hkdf(this.chainingKey, b4a.alloc(0))
    return res.map(k => k.subarray(0, 32))
  }

  _clear () {
    super._clear()

    sodium.sodium_memzero(this.digest)
    sodium.sodium_memzero(this.chainingKey)

    this.digest = null
    this.chainingKey = null
    this.offset = null

    this.curve = null
  }

  static get alg () {
    return CipherState.alg + '_BLAKE2b'
  }
}

function accumulateDigest (digest, input) {
  const toHash = b4a.concat([digest, input])
  sodium.crypto_generichash(digest, toHash)
}
const b4a = require('b4a')
const c = require('compact-encoding')
const queueTick = require('queue-tick')
const safetyCatch = require('safety-catch')
const unslab = require('unslab')

const MAX_BUFFERED = 32768
const MAX_BACKLOG = Infinity // TODO: impl "open" backpressure
const MAX_BATCH = 8 * 1024 * 1024

class Channel {
  constructor(
    mux,
    info,
    userData,
    protocol,
    aliases,
    id,
    handshake,
    messages,
    onopen,
    onclose,
    ondestroy,
    ondrain
  ) {
    this.userData = userData
    this.protocol = protocol
    this.aliases = aliases
    this.id = id
    this.handshake = null
    this.messages = []

    this.opened = false
    this.closed = false
    this.destroyed = false

    this.onopen = onopen
    this.onclose = onclose
    this.ondestroy = ondestroy
    this.ondrain = ondrain

    this._handshake = handshake
    this._mux = mux
    this._info = info
    this._localId = 0
    this._remoteId = 0
    this._active = 0
    this._extensions = null

    this._decBound = this._dec.bind(this)
    this._decAndDestroyBound = this._decAndDestroy.bind(this)

    this._openedPromise = null
    this._openedResolve = null

    this._destroyedPromise = null
    this._destroyedResolve = null

    for (const m of messages) this.addMessage(m)
  }

  get drained() {
    return this._mux.drained
  }

  fullyOpened() {
    if (this.opened) return Promise.resolve(true)
    if (this.closed) return Promise.resolve(false)
    if (this._openedPromise) return this._openedPromise

    this._openedPromise = new Promise((resolve) => {
      this._openedResolve = resolve
    })
    return this._openedPromise
  }

  fullyClosed() {
    if (this.destroyed) return Promise.resolve()
    if (this._destroyedPromise) return this._destroyedPromise

    this._destroyedPromise = new Promise((resolve) => {
      this._destroyedResolve = resolve
    })
    return this._destroyedPromise
  }

  open(handshake) {
    const id = this._mux._free.length > 0 ? this._mux._free.pop() : this._mux._local.push(null) - 1

    this._info.opened++
    this._info.lastChannel = this
    this._localId = id + 1
    this._mux._local[id] = this

    if (this._remoteId === 0) {
      this._info.outgoing.push(this._localId)
    }

    const state = { buffer: null, start: 2, end: 2 }

    c.uint.preencode(state, this._localId)
    c.string.preencode(state, this.protocol)
    c.optionalBuffer.preencode(state, this.id)
    if (this._handshake) this._handshake.preencode(state, handshake)

    state.buffer = this._mux._alloc(state.end)

    state.buffer[0] = 0
    state.buffer[1] = 1
    c.uint.encode(state, this._localId)
    c.string.encode(state, this.protocol)
    c.optionalBuffer.encode(state, this.id)
    if (this._handshake) this._handshake.encode(state, handshake)

    this._mux._write0(state.buffer)
  }

  _dec() {
    if (--this._active === 0 && this.closed === true) this._destroy()
  }

  _decAndDestroy(err) {
    this._dec()
    this._mux._safeDestroy(err)
  }

  _fullyOpenSoon() {
    this._mux._remote[this._remoteId - 1].session = this
    queueTick(this._fullyOpenOrDestroy.bind(this))
  }

  _fullyOpenOrDestroy() {
    try {
      this._fullyOpen()
    } catch (err) {
      this._mux._safeDestroyBound(err)
    }
  }

  _fullyOpen() {
    if (this.opened === true || this.closed === true) return

    const remote = this._mux._remote[this._remoteId - 1]

    this.handshake = this._handshake ? this._handshake.decode(remote.state) : null
    this._track(this.onopen(this.handshake, this))

    remote.session = this
    remote.state = null
    if (remote.pending !== null) this._drain(remote)
    if (this._mux._destroying === true) return

    this.opened = true
    this._resolveOpen(true)
  }

  _resolveOpen(opened) {
    if (this._openedResolve !== null) {
      this._openedResolve(opened)
      this._openedResolve = this._openedPromise = null
    }
  }

  _resolveDestroyed() {
    if (this._destroyedResolve !== null) {
      this._destroyedResolve()
      this._destroyedResolve = this._destroyedPromise = null
    }
  }

  _drain(remote) {
    for (let i = 0; i < remote.pending.length; i++) {
      const p = remote.pending[i]
      this._mux._buffered -= byteSize(p.state)
      this._recv(p.type, p.state)
      if (this._mux._destroying === true) return
    }

    remote.pending = null
    this._mux._resumeMaybe()
  }

  _track(p) {
    if (isPromise(p) === true) {
      this._active++
      return p.then(this._decBound, this._decAndDestroyBound)
    }

    return null
  }

  _close(isRemote) {
    if (this.closed === true) return
    this.closed = true

    this._info.opened--
    if (this._info.lastChannel === this) this._info.lastChannel = null

    if (this._remoteId > 0) {
      this._mux._remote[this._remoteId - 1] = null
      this._remoteId = 0
      // If remote has acked, we can reuse the local id now
      // otherwise, we need to wait for the "ack" to arrive
      this._mux._free.push(this._localId - 1)
    }

    this._mux._local[this._localId - 1] = null
    this._localId = 0

    this._mux._gc(this._info)
    this._track(this.onclose(isRemote, this))

    if (this._active === 0) this._destroy()

    this._resolveOpen(false)
  }

  _destroy() {
    if (this.destroyed === true) return
    this.destroyed = true
    this._track(this.ondestroy(this))
    this._resolveDestroyed()
  }

  _recv(type, state) {
    if (type < this.messages.length) {
      const m = this.messages[type]
      const p = m.recv(state, this)
      if (m.autoBatch === true) return p
    }
    return null
  }

  cork() {
    this._mux.cork()
  }

  uncork() {
    this._mux.uncork()
  }

  close() {
    if (this.closed === true) return

    const state = { buffer: null, start: 2, end: 2 }

    c.uint.preencode(state, this._localId)

    state.buffer = this._mux._alloc(state.end)

    state.buffer[0] = 0
    state.buffer[1] = 3
    c.uint.encode(state, this._localId)

    this._close(false)
    this._mux._write0(state.buffer)
  }

  addMessage(opts) {
    if (!opts) return this._skipMessage()

    const type = this.messages.length
    const autoBatch = opts.autoBatch !== false
    const encoding = opts.encoding || c.raw
    const onmessage = opts.onmessage || noop

    const s = this
    const typeLen = encodingLength(c.uint, type)

    const m = {
      type,
      autoBatch,
      encoding,
      onmessage,
      recv(state, session) {
        return session._track(m.onmessage(encoding.decode(state), session))
      },
      send(m, session = s) {
        if (session.closed === true) return false

        const mux = session._mux
        const state = { buffer: null, start: 0, end: typeLen }

        if (mux._batch !== null) {
          encoding.preencode(state, m)
          state.buffer = mux._alloc(state.end)

          c.uint.encode(state, type)
          encoding.encode(state, m)

          mux._pushBatch(session._localId, state.buffer)
          return true
        }

        c.uint.preencode(state, session._localId)
        encoding.preencode(state, m)

        state.buffer = mux._alloc(state.end)

        c.uint.encode(state, session._localId)
        c.uint.encode(state, type)
        encoding.encode(state, m)

        mux.drained = mux.stream.write(state.buffer)

        return mux.drained
      }
    }

    this.messages.push(m)

    return m
  }

  _skipMessage() {
    const type = this.messages.length
    const m = {
      type,
      encoding: c.raw,
      onmessage: noop,
      recv(state, session) {},
      send(m, session) {}
    }

    this.messages.push(m)
    return m
  }
}

module.exports = class Protomux {
  constructor(stream, { alloc } = {}) {
    if (stream.userData === null) stream.userData = this

    this.isProtomux = true
    this.stream = stream
    this.corked = 0
    this.drained = true

    this._alloc =
      alloc || (typeof stream.alloc === 'function' ? stream.alloc.bind(stream) : b4a.allocUnsafe)
    this._safeDestroyBound = this._safeDestroy.bind(this)
    this._uncorkBound = this.uncork.bind(this)

    this._remoteBacklog = 0
    this._buffered = 0
    this._paused = false
    this._remote = []
    this._local = []
    this._free = []
    this._batch = null
    this._batchState = null

    this._infos = new Map()
    this._notify = new Map()
    // stream.destroyed flips asynchronously on streamx-based transports.
    this._destroying = false

    this.stream.on('data', this._ondata.bind(this))
    this.stream.on('drain', this._ondrain.bind(this))
    this.stream.on('end', this._onend.bind(this))
    this.stream.on('error', noop) // we handle this in "close"
    this.stream.on('close', this._shutdown.bind(this))
  }

  static from(stream, opts) {
    if (stream.userData && stream.userData.isProtomux) return stream.userData
    if (stream.isProtomux) return stream
    return new this(stream, opts)
  }

  static isProtomux(mux) {
    return typeof mux === 'object' && mux.isProtomux === true
  }

  *[Symbol.iterator]() {
    for (const session of this._local) {
      if (session !== null) yield session
    }
  }

  isIdle() {
    return this._local.length === this._free.length
  }

  cork() {
    if (++this.corked === 1) {
      this._batch = []
      this._batchState = { buffer: null, start: 0, end: 1 }
    }
  }

  uncork() {
    if (--this.corked === 0) {
      this._sendBatch(this._batch, this._batchState)
      this._batch = null
      this._batchState = null
    }
  }

  getLastChannel({ protocol, id = null }) {
    const key = toKey(protocol, id)
    const info = this._infos.get(key)
    if (info) return info.lastChannel
    return null
  }

  pair({ protocol, id = null }, notify) {
    this._notify.set(toKey(protocol, id), notify)
  }

  unpair({ protocol, id = null }) {
    this._notify.delete(toKey(protocol, id))
  }

  opened({ protocol, id = null }) {
    const key = toKey(protocol, id)
    const info = this._infos.get(key)
    return info ? info.opened > 0 : false
  }

  createChannel({
    userData = null,
    protocol,
    aliases = [],
    id = null,
    unique = true,
    handshake = null,
    messages = [],
    onopen = noop,
    onclose = noop,
    ondestroy = noop,
    ondrain = noop
  }) {
    if (this.stream.destroyed) return null

    const info = this._get(protocol, id, aliases)
    if (unique && info.opened > 0) return null

    if (info.incoming.length === 0) {
      return new Channel(
        this,
        info,
        userData,
        protocol,
        aliases,
        id,
        handshake,
        messages,
        onopen,
        onclose,
        ondestroy,
        ondrain
      )
    }

    this._remoteBacklog--

    const remoteId = info.incoming.shift()
    const r = this._remote[remoteId - 1]
    if (r === null) return null

    const session = new Channel(
      this,
      info,
      userData,
      protocol,
      aliases,
      id,
      handshake,
      messages,
      onopen,
      onclose,
      ondestroy,
      ondrain
    )

    session._remoteId = remoteId
    session._fullyOpenSoon()

    return session
  }

  _pushBatch(localId, buffer) {
    if (this._batchState.end >= MAX_BATCH) {
      this._sendBatch(this._batch, this._batchState)
      this._batch = []
      this._batchState = { buffer: null, start: 0, end: 1 }
    }

    if (this._batch.length === 0 || this._batch[this._batch.length - 1].localId !== localId) {
      this._batchState.end++
      c.uint.preencode(this._batchState, localId)
    }
    c.buffer.preencode(this._batchState, buffer)
    this._batch.push({ localId, buffer })
  }

  _sendBatch(batch, state) {
    if (batch.length === 0) return

    let prev = batch[0].localId

    state.buffer = this._alloc(state.end)
    state.buffer[state.start++] = 0
    state.buffer[state.start++] = 0

    c.uint.encode(state, prev)

    for (let i = 0; i < batch.length; i++) {
      const b = batch[i]
      if (prev !== b.localId) {
        state.buffer[state.start++] = 0
        c.uint.encode(state, (prev = b.localId))
      }
      c.buffer.encode(state, b.buffer)
    }

    this.drained = this.stream.write(state.buffer)
  }

  _get(protocol, id, aliases = []) {
    const key = toKey(protocol, id)

    let info = this._infos.get(key)
    if (info) return info

    info = {
      key,
      protocol,
      aliases: [],
      id,
      pairing: 0,
      opened: 0,
      incoming: [],
      outgoing: [],
      lastChannel: null
    }
    this._infos.set(key, info)

    for (const alias of aliases) {
      const key = toKey(alias, id)
      info.aliases.push(key)

      this._infos.set(key, info)
    }

    return info
  }

  _gc(info) {
    if (info.opened === 0 && info.outgoing.length === 0 && info.incoming.length === 0) {
      this._infos.delete(info.key)

      for (const alias of info.aliases) this._infos.delete(alias)
    }
  }

  _ondata(buffer) {
    if (buffer.byteLength === 0) return // ignore empty frames...
    try {
      const state = { buffer, start: 0, end: buffer.byteLength }
      this._decode(c.uint.decode(state), state)
    } catch (err) {
      this._safeDestroy(err)
    }
  }

  _ondrain() {
    this.drained = true

    for (const s of this._local) {
      if (s !== null) s._track(s.ondrain(s))
    }
  }

  _onend() {
    // TODO: support half open mode for the users who wants that here
    this.stream.end()
  }

  _decode(remoteId, state) {
    const type = c.uint.decode(state)

    if (remoteId === 0) {
      return this._oncontrolsession(type, state)
    }

    const r = remoteId <= this._remote.length ? this._remote[remoteId - 1] : null

    // if the channel is closed ignore - could just be a pipeline message...
    if (r === null) return null

    if (r.pending !== null) {
      this._bufferMessage(r, type, state)
      return null
    }

    return r.session._recv(type, state)
  }

  _oncontrolsession(type, state) {
    switch (type) {
      case 0:
        this._onbatch(state)
        break

      case 1:
        // return the promise back up as this has sideeffects so we can batch reply
        return this._onopensession(state)

      case 2:
        this._onrejectsession(state)
        break

      case 3:
        this._onclosesession(state)
        break
    }

    return null
  }

  _bufferMessage(r, type, { buffer, start, end }) {
    const state = { buffer, start, end } // copy
    r.pending.push({ type, state })
    this._buffered += byteSize(state)
    this._pauseMaybe()
  }

  _pauseMaybe() {
    if (this._paused === true || this._buffered <= MAX_BUFFERED) return
    this._paused = true
    this.stream.pause()
  }

  _resumeMaybe() {
    if (this._paused === false || this._buffered > MAX_BUFFERED) return
    this._paused = false
    this.stream.resume()
  }

  _onbatch(state) {
    const end = state.end
    let remoteId = c.uint.decode(state)

    let waiting = null

    while (state.end > state.start) {
      const len = c.uint.decode(state)
      if (len === 0) {
        remoteId = c.uint.decode(state)
        continue
      }
      state.end = state.start + len
      // if batch contains more than one message, cork it so we reply back with a batch
      if (end !== state.end && waiting === null) {
        waiting = []
        this.cork()
      }
      const p = this._decode(remoteId, state)
      if (waiting !== null && p !== null) waiting.push(p)
      state.start = state.end
      state.end = end
    }

    if (waiting !== null) {
      // the waiting promises are not allowed to throw but we destroy the stream in case we are wrong
      Promise.all(waiting).then(this._uncorkBound, this._safeDestroyBound)
    }
  }

  _onopensession(state) {
    const remoteId = c.uint.decode(state)
    const protocol = c.string.decode(state)
    const id = unslab(c.optionalBuffer.decode(state))

    // remote tried to open the control session - auto reject for now
    // as we can use as an explicit control protocol declaration if we need to
    if (remoteId === 0) {
      this._rejectSession(0)
      return null
    }

    const rid = remoteId - 1
    const info = this._get(protocol, id)

    // allow the remote to grow the ids by one
    if (this._remote.length === rid) {
      this._remote.push(null)
    }

    if (rid >= this._remote.length || this._remote[rid] !== null) {
      throw new Error('Invalid open message')
    }

    if (info.outgoing.length > 0) {
      const localId = info.outgoing.shift()
      const session = this._local[localId - 1]

      if (session === null) {
        // we already closed the channel - ignore
        this._free.push(localId - 1)
        return null
      }

      this._remote[rid] = { state, pending: null, session: null }

      session._remoteId = remoteId
      session._fullyOpen()
      return null
    }

    const copyState = { buffer: state.buffer, start: state.start, end: state.end }
    this._remote[rid] = { state: copyState, pending: [], session: null }

    if (++this._remoteBacklog > MAX_BACKLOG) {
      throw new Error('Remote exceeded backlog')
    }

    info.pairing++
    info.incoming.push(remoteId)

    return this._requestSession(protocol, id, info).catch(this._safeDestroyBound)
  }

  _onrejectsession(state) {
    const localId = c.uint.decode(state)

    // TODO: can be done smarter...
    for (const info of this._infos.values()) {
      const i = info.outgoing.indexOf(localId)
      if (i === -1) continue

      info.outgoing.splice(i, 1)

      const session = this._local[localId - 1]

      this._free.push(localId - 1)
      if (session !== null) session._close(true)

      this._gc(info)
      return
    }

    throw new Error('Invalid reject message')
  }

  _onclosesession(state) {
    const remoteId = c.uint.decode(state)

    if (remoteId === 0) return // ignore

    const rid = remoteId - 1
    const r = rid < this._remote.length ? this._remote[rid] : null

    if (r === null) return

    if (r.session !== null) r.session._close(true)
  }

  async _requestSession(protocol, id, info) {
    const notify = this._notify.get(toKey(protocol, id)) || this._notify.get(toKey(protocol, null))

    if (notify) await notify(id)

    if (--info.pairing > 0) return

    while (info.incoming.length > 0) {
      this._rejectSession(info, info.incoming.shift())
    }

    this._gc(info)
  }

  _rejectSession(info, remoteId) {
    if (remoteId > 0) {
      const r = this._remote[remoteId - 1]

      if (r.pending !== null) {
        for (let i = 0; i < r.pending.length; i++) {
          this._buffered -= byteSize(r.pending[i].state)
        }
      }

      this._remote[remoteId - 1] = null
      this._resumeMaybe()
    }

    const state = { buffer: null, start: 2, end: 2 }

    c.uint.preencode(state, remoteId)

    state.buffer = this._alloc(state.end)

    state.buffer[0] = 0
    state.buffer[1] = 2
    c.uint.encode(state, remoteId)

    this._write0(state.buffer)
  }

  _write0(buffer) {
    if (this._batch !== null) {
      this._pushBatch(0, buffer.subarray(1))
      return
    }

    this.drained = this.stream.write(buffer)
  }

  destroy(err) {
    this._destroying = true
    this.stream.destroy(err)
  }

  _safeDestroy(err) {
    safetyCatch(err)
    this._destroying = true
    this.stream.destroy(err)
  }

  _shutdown() {
    this._destroying = true
    for (const s of this._local) {
      if (s !== null) s._close(true)
    }
  }
}

function noop() {}

function toKey(protocol, id) {
  return protocol + '##' + (id ? b4a.toString(id, 'hex') : '')
}

function byteSize(state) {
  return 512 + (state.end - state.start)
}

function isPromise(p) {
  return !!(p && typeof p.then === 'function')
}

function encodingLength(enc, val) {
  const state = { buffer: null, start: 0, end: 0 }
  enc.preencode(state, val)
  return state.end
}
{
  "name": "protomux",
  "version": "3.11.0",
  "description": "Multiplex multiple message oriented protocols over a stream",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.3.1",
    "compact-encoding": "^3.0.0",
    "queue-tick": "^1.0.0",
    "safety-catch": "^1.0.1",
    "unslab": "^1.3.0"
  },
  "devDependencies": {
    "@hyperswarm/secret-stream": "^6.0.0",
    "brittle": "^3.0.0",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/protomux.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/protomux/issues"
  },
  "homepage": "https://github.com/holepunchto/protomux"
}
{
  "name": "queue-tick",
  "version": "1.0.1",
  "description": "Next tick shim that prefers process.nextTick over queueMicrotask for compat",
  "main": "./process-next-tick.js",
  "browser": "./queue-microtask.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^16.0.3",
    "tape": "^5.3.1"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/queue-tick.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/queue-tick/issues"
  },
  "homepage": "https://github.com/mafintosh/queue-tick"
}
module.exports = (typeof process !== 'undefined' && typeof process.nextTick === 'function')
  ? process.nextTick.bind(process)
  : require('./queue-microtask')
module.exports = typeof queueMicrotask === 'function' ? queueMicrotask : (fn) => Promise.resolve().then(fn)
const EventEmitter = require('events')

module.exports = class ReadyResource extends EventEmitter {
  constructor () {
    super()

    this.opening = null
    this.closing = null

    this.opened = false
    this.closed = false
  }

  ready () {
    if (this.opening !== null) return this.opening
    this.opening = open(this)
    return this.opening
  }

  close () {
    if (this.closing !== null) return this.closing
    this.closing = close(this)
    return this.closing
  }

  async _open () {
    // add impl here
  }

  async _close () {
    // add impl here
  }
}

async function open (self) {
  // open after close
  if (self.closing !== null) return

  try {
    await self._open()
  } catch (err) {
    self.close() // safe to run in bg
    throw err
  }

  self.opened = true
  self.emit('ready')
}

async function close (self) {
  try {
    if (self.opened === false && self.opening !== null) await self.opening
  } catch {
    // ignore errors on closing
  }
  if (self.opened === true || self.opening === null) await self._close()
  self.closed = true
  self.emit('close')
}
{
  "name": "ready-resource",
  "version": "1.2.0",
  "description": "Modern single resource management",
  "main": "index.js",
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "types": "index.d.ts",
  "files": [
    "index.js",
    "index.d.ts"
  ],
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "devDependencies": {
    "brittle": "^3.1.0",
    "standard": "^17.0.0"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/ready-resource.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/ready-resource/issues"
  },
  "homepage": "https://github.com/holepunchto/ready-resource",
  "dependencies": {
    "bare-events": "^2.2.0"
  }
}
const b4a = require('b4a')

var EMPTY = []

module.exports = RecordCache

function RecordSet () {
  this.list = []
  this.map = new Map()
}

RecordSet.prototype.add = function (record, value) {
  var k = toString(record)
  var r = this.map.get(k)
  if (r) return false

  r = {index: this.list.length, record: value || record}
  this.list.push(r)
  this.map.set(k, r)
  return true
}

RecordSet.prototype.remove = function (record) {
  var k = toString(record)
  var r = this.map.get(k)
  if (!r) return false

  swap(this.list, r.index, this.list.length - 1)
  this.list.pop()
  this.map.delete(k)
  return true
}

function RecordStore () {
  this.records = new Map()
  this.size = 0
}

RecordStore.prototype.add = function (name, record, value) {
  var r = this.records.get(name)

  if (!r) {
    r = new RecordSet()
    this.records.set(name, r)
  }

  if (r.add(record, value)) {
    this.size++
    return true
  }

  return false
}

RecordStore.prototype.remove = function (name, record, value) {
  var r = this.records.get(name)
  if (!r) return false

  if (r.remove(record, value)) {
    this.size--
    if (!r.map.size) this.records.delete(name)
    return true
  }

  return false
}

RecordStore.prototype.get = function (name) {
  var r = this.records.get(name)
  return r ? r.list : EMPTY
}

function RecordCache (opts) {
  if (!(this instanceof RecordCache)) return new RecordCache(opts)
  if (!opts) opts = {}

  this.maxSize = opts.maxSize || Infinity
  this.maxAge = opts.maxAge || 0

  this._onstale = opts.onStale || opts.onstale || null
  this._fresh = new RecordStore()
  this._stale = new RecordStore()
  this._interval = null
  this._gced = false

  if (this.maxAge && this.maxAge < Infinity) {
    // 2/3 gives us a span of 0.66-1.33 maxAge or avg maxAge
    var tick = Math.ceil(2 / 3 * this.maxAge)
    this._interval = setInterval(this._gcAuto.bind(this), tick)
    if (this._interval.unref) this._interval.unref()
  }
}

Object.defineProperty(RecordCache.prototype, 'size', {
  get: function () {
    return this._fresh.size + this._stale.size
  }
})

RecordCache.prototype.add = function (name, record, value) {
  this._stale.remove(name, record, value)
  if (this._fresh.add(name, record, value) && this._fresh.size > this.maxSize) {
    this._gc()
  }
}

RecordCache.prototype.remove = function (name, record, value) {
  this._fresh.remove(name, record, value)
  this._stale.remove(name, record, value)
}

RecordCache.prototype.get = function (name, n) {
  var a = this._fresh.get(name)
  var b = this._stale.get(name)
  var aLen = a.length
  var bLen = b.length
  var len = aLen + bLen

  if (n > len || !n) n = len
  var result = new Array(n)

  for (var i = 0; i < n; i++) {
    var j = Math.floor(Math.random() * (aLen + bLen))
    if (j < aLen) {
      result[i] = a[j].record
      swap(a, j, --aLen)
    } else {
      j -= aLen
      result[i] = b[j].record
      swap(b, j, --bLen)
    }
  }

  return result
}

RecordCache.prototype._gcAuto = function () {
  if (!this._gced) this._gc()
  this._gced = false
}

RecordCache.prototype._gc = function () {
  if (this._onstale && this._stale.size > 0) this._onstale(this._stale)
  this._stale = this._fresh
  this._fresh = new RecordStore()
  this._gced = true
}

RecordCache.prototype.clear = function () {
  this._gc()
  this._gc()
}

RecordCache.prototype.destroy = function () {
  this.clear()
  clearInterval(this._interval)
  this._interval = null
}

function toString (record) {
  return b4a.isBuffer(record) ? b4a.toString(record, 'hex') : record
}

function swap (list, a, b) {
  var tmp = list[a]
  tmp.index = b
  list[b].index = a
  list[a] = list[b]
  list[b] = tmp
}
{
  "name": "record-cache",
  "version": "1.2.0",
  "description": "Cache optimised for record like things",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.3.1"
  },
  "devDependencies": {
    "standard": "^10.0.3",
    "tape": "^4.8.0"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/record-cache.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/record-cache/issues"
  },
  "homepage": "https://github.com/mafintosh/record-cache"
}
module.exports = require.addon.bind(require)
{
  "name": "require-addon",
  "version": "1.2.0",
  "description": "Import native addons across JavaScript runtimes",
  "exports": {
    "./package": "./package.json",
    ".": {
      "bare": "./lib/bare.js",
      "node": "./lib/node.js",
      "default": "./lib/default.js"
    }
  },
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    },
    "url": {
      "bare": "bare-url",
      "default": "url"
    }
  },
  "files": [
    "lib"
  ],
  "scripts": {
    "test": "npm run lint && npm run test:bare && npm run test:node",
    "test:bare": "bare test.js",
    "test:node": "node test.js",
    "lint": "prettier --check .",
    "format": "prettier --write ."
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/require-addon.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/require-addon/issues"
  },
  "homepage": "https://github.com/holepunchto/require-addon#readme",
  "engines": {
    "bare": ">=1.10.0"
  },
  "dependencies": {
    "bare-addon-resolve": "^1.3.0"
  },
  "devDependencies": {
    "bare-bundle": "^1.8.1",
    "bare-bundle-evaluate": "^1.1.0",
    "bare-fs": "^4.0.0",
    "bare-path": "^3.0.0",
    "bare-url": "^2.1.0",
    "brittle": "^3.7.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = safetyCatch

function isActuallyUncaught (err) {
  if (!err) return false
  return err instanceof TypeError ||
    err instanceof SyntaxError ||
    err instanceof ReferenceError ||
    err instanceof EvalError ||
    err instanceof RangeError ||
    err instanceof URIError ||
    err.code === 'ERR_ASSERTION' ||
    err.name === 'AssertionError'
}

function throwErrorNT (err) {
  queueMicrotask(() => { throw err })
}

function safetyCatch (err) {
  if (isActuallyUncaught(err)) {
    throwErrorNT(err)
    throw err
  }
}
{
  "name": "safety-catch",
  "version": "1.0.3",
  "description": "Small module that makes sure your catch, caught an actual error and not a programming mistake or assertion",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {},
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/safety-catch.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/safety-catch/issues"
  },
  "homepage": "https://github.com/mafintosh/safety-catch"
}
const set = require('unordered-set')

module.exports = opts => new ShuffledPriorityQueue(opts)

class ShuffledPriorityQueue {
  constructor (opts) {
    this.priorities = []
    this.equals = (opts && opts.equals) || null
  }

  get length () {
    return this.priorities.reduce(add, 0)
  }

  [Symbol.iterator] () {
    return new Iterator(this)
  }

  head () {
    for (let i = this.priorities.length - 1; i >= 0; i--) {
      const q = this.priorities[i]
      if (q.length) return shuffle(q, 0)
    }
    return null
  }

  tail () {
    for (let i = 0; i < this.priorities.length; i++) {
      const q = this.priorities[i]
      if (q.length) return shuffle(q, 0)
    }
    return null
  }

  prev (prev) {
    if (!prev) return this.tail()
    return next(this.priorities, prev, 1)
  }

  next (prev) {
    if (!prev) return this.head()
    return next(this.priorities, prev, -1)
  }

  shift () {
    return this.remove(this.head())
  }

  pop () {
    return this.remove(this.tail())
  }

  add (val) {
    const prio = val.priority || 0
    while (prio >= this.priorities.length) this.priorities.push([])
    set.add(this.priorities[prio], val)
    return val
  }

  remove (val) {
    if (!val) return null

    if (val._index === undefined) {
      val = this.find(val)
      if (!val) return null
    }

    return set.remove(this.priorities[val.priority || 0], val)
  }

  has (val) {
    if (val._index === undefined) return this.find(val)
    const priority = val.priority || 0
    if (priority >= this.priorities.length) return false
    return set.has(this.priorities[priority], val)
  }

  find (val) {
    if (val._index !== undefined) return val

    const prio = val.priority || 0
    const qs = this.priorities
    if (prio >= qs.length) return null

    const q = qs[prio]

    for (let i = 0; i < q.length; i++) {
      if (this.equals(q[i], val)) return q[i]
    }

    return null
  }
}

class Iterator {
  constructor (queue) {
    this.prev = null
    this.queue = queue
  }

  next () {
    const next = this.queue.next(this.prev)
    this.prev = next
    return { done: !next, value: next }
  }
}

function shuffle (q, i) {
  const ran = i + Math.floor(Math.random() * (q.length - i))
  set.swap(q, q[ran], q[i])
  return q[i]
}

function next (queues, prev, inc) {
  let i = prev.priority || 0
  let j = (prev._index || 0) + 1

  while (true) {
    if (i < 0 || i >= queues.length) return null
    const q = queues[i]

    if (j >= q.length) {
      i += inc
      j = 0
      continue
    }

    return shuffle(q, j)
  }
}

function add (len, b) {
  return len + b.length
}
{
  "name": "shuffled-priority-queue",
  "version": "2.1.0",
  "description": "A priority queue that shuffles elements with the same priority.",
  "main": "index.js",
  "scripts": {
    "test": "standard && tape test.js"
  },
  "dependencies": {
    "unordered-set": "^2.0.1"
  },
  "devDependencies": {
    "standard": "^12.0.1",
    "tape": "^4.9.1"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/shuffled-priority-queue.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/shuffled-priority-queue/issues"
  },
  "homepage": "https://github.com/mafintosh/shuffled-priority-queue"
}
module.exports = class Signal {
  constructor () {
    this._resolve = null
    this._reject = null
    this._promise = null
    this._bind = bind.bind(this)
    this._onerror = clear.bind(this)
    this._onsuccess = clear.bind(this, null)
    this._timers = new Set()
  }

  wait (max) {
    if (!this._promise) {
      this._promise = new Promise(this._bind)
      this._promise.then(this._onsuccess).catch(this._onerror)
    }
    if (max) return this._sleep(max)
    return this._promise
  }

  _sleep (max) {
    const s = new Promise((resolve, reject) => {
      const done = () => {
        this._timers.delete(state)
        resolve(true)
      }
      const id = setTimeout(done, max)
      const state = { id, resolve, reject }
      this._timers.add(state)
    })

    return s
  }

  notify (err) {
    if (!this._promise) return
    const resolve = this._resolve
    const reject = this._reject
    this._promise = null
    if (err) reject(err)
    else resolve(true)
  }
}

function clear (err) {
  for (const { id, resolve, reject } of this._timers) {
    clearTimeout(id)
    if (err) reject(err)
    else resolve(true)
  }
  this._timers.clear()
}

function bind (resolve, reject) {
  this._resolve = resolve
  this._reject = reject
}
{
  "name": "signal-promise",
  "version": "1.0.3",
  "description": "Simple wait/notify promise with optional max wait time",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {},
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/signal-promise.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/signal-promise/issues"
  },
  "homepage": "https://github.com/mafintosh/signal-promise"
}
require.addon = require('require-addon')
module.exports = require.addon('.', __filename)
const assert = require('assert')
const binding = require('./binding')
const { isNode } = require('which-runtime')

const OPTIONAL = Buffer.from(new ArrayBuffer(0))

module.exports = exports = { ...binding }

// memory

exports.sodium_memzero = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  binding.sodium_memzero(buf)
}

exports.sodium_mlock = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  const res = binding.sodium_mlock(buf)

  if (res !== 0) throw new Error('memory lock failed')
}

exports.sodium_munlock = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  const res = binding.sodium_munlock(buf)

  if (res !== 0) throw new Error('memory unlock failed')
}

exports.sodium_malloc = function (size) {
  assert(size >= 0, 'invalid size')

  const buf = Buffer.from(binding.sodium_malloc(size))
  buf.secure = true
  return buf
}

exports.sodium_free = function (buf) {
  if (!buf || !buf.secure) return

  binding.sodium_free(buf.buffer)
}

exports.sodium_mprotect_noaccess = function (buf) {
  const res = binding.sodium_mprotect_noaccess(buf.buffer)

  if (res !== 0) throw new Error('failed to lock buffer')
}

exports.sodium_mprotect_readonly = function (buf) {
  const res = binding.sodium_mprotect_readonly(buf.buffer)

  if (res !== 0) throw new Error('failed to unlock buffer')
}

exports.sodium_mprotect_readwrite = function (buf) {
  const res = binding.sodium_mprotect_readwrite(buf.buffer)

  if (res !== 0) throw new Error('failed to unlock buffer')
}

// crypto_randombytes

exports.randombytes_buf = function (buffer) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')

  binding.randombytes_buf(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

exports.randombytes_buf_deterministic = function (buffer, seed) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    seed.byteLength === binding.randombytes_SEEDBYTES,
    "seed must be 'randombytes_SEEDBYTES' bytes"
  )

  binding.randombytes_buf_deterministic(
    buffer.buffer,
    buffer.byteOffset,
    buffer.byteLength,

    seed.buffer,
    seed.byteOffset,
    seed.byteLength
  )
}

// sodium_helpers

exports.sodium_memcmp = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  return binding.sodium_memcmp(a, b)
}

exports.sodium_add = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  binding.sodium_add(a, b)
}

exports.sodium_sub = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  binding.sodium_sub(a, b)
}

exports.sodium_compare = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  return binding.sodium_compare(a, b)
}

exports.sodium_is_zero = function (buffer, length) {
  if (length === undefined) length = buffer.byteLength

  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(length >= 0 && length <= buffer.byteLength, 'invalid length')

  return binding.sodium_is_zero(buffer, length)
}

exports.sodium_pad = function (buffer, unpaddedBuflen, blockSize) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(unpaddedBuflen <= buffer.byteLength, 'unpadded length cannot exceed buffer length')
  assert(blockSize <= buffer.byteLength, 'block size cannot exceed buffer length')
  assert(blockSize >= 1, 'block size must be at least 1 byte')
  assert(
    buffer.byteLength >= unpaddedBuflen + (blockSize - (unpaddedBuflen % blockSize)),
    'buf not long enough'
  )

  return binding.sodium_pad(buffer, unpaddedBuflen, blockSize)
}

exports.sodium_unpad = function (buffer, paddedBuflen, blockSize) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(paddedBuflen <= buffer.byteLength, 'unpadded length cannot exceed buffer length')
  assert(blockSize <= buffer.byteLength, 'block size cannot exceed buffer length')
  assert(blockSize >= 1, 'block size must be at least 1 byte')

  return binding.sodium_unpad(buffer, paddedBuflen, blockSize)
}

// crypto_sign

exports.crypto_sign_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )
  assert(
    seed.byteLength === binding.crypto_sign_SEEDBYTES,
    "seed must be 'crypto_sign_SEEDBYTES' bytes"
  )

  const res = binding.crypto_sign_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign = function (sm, m, sk) {
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sm.byteLength === binding.crypto_sign_BYTES + m.byteLength,
    "sm must be 'm.byteLength + crypto_sign_BYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign(sm, m, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_open = function (m, sm, pk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sm.byteLength >= binding.crypto_sign_BYTES,
    "sm must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    m.byteLength === sm.byteLength - binding.crypto_sign_BYTES,
    "m must be 'sm.byteLength - crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_open(m, sm, pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_open = function (m, sm, pk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sm.byteLength >= binding.crypto_sign_BYTES,
    "sm must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    m.byteLength === sm.byteLength - binding.crypto_sign_BYTES,
    "m must be 'sm.byteLength - crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  return binding.crypto_sign_open(m, sm, pk)
}

exports.crypto_sign_detached = function (sig, m, sk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(sig.byteLength === binding.crypto_sign_BYTES, "sig must be 'crypto_sign_BYTES' bytes")
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_detached(sig, m, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_verify_detached = function (sig, m, pk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sig.byteLength >= binding.crypto_sign_BYTES,
    "sig must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  return binding.crypto_sign_verify_detached(
    sig.buffer,
    sig.byteOffset,
    sig.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    pk.buffer,
    pk.byteOffset,
    pk.byteLength
  )
}

exports.crypto_sign_ed25519_sk_to_pk = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_sk_to_pk(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_ed25519_pk_to_curve25519 = function (x25519pk, ed25519pk) {
  assert(ArrayBuffer.isView(x25519pk), 'x25519pk must be a typed array')
  assert(ArrayBuffer.isView(ed25519pk), 'ed25519pk must be a typed array')
  assert(
    x25519pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "x25519pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    ed25519pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "ed25519pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_pk_to_curve25519(x25519pk, ed25519pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_ed25519_sk_to_curve25519 = function (x25519sk, ed25519sk) {
  assert(ArrayBuffer.isView(x25519sk), 'x25519sk must be a typed array')
  assert(ArrayBuffer.isView(ed25519sk), 'ed25519sk must be a typed array')
  assert(
    x25519sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "x25519sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const edLen = ed25519sk.byteLength

  assert(
    edLen === binding.crypto_sign_SECRETKEYBYTES || edLen === binding.crypto_box_SECRETKEYBYTES,
    "ed25519sk must be 'crypto_sign_SECRETKEYBYTES' or 'crypto_sign_SECRETKEYBYTES - crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_sk_to_curve25519(x25519sk, ed25519sk)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_box

exports.crypto_box_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    seed.byteLength === binding.crypto_box_SEEDBYTES,
    "seed must be 'crypto_box_SEEDBYTES' bytes"
  )

  const res = binding.crypto_box_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_easy = function (c, m, n, pk, sk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength === m.byteLength + exports.crypto_box_MACBYTES,
    "c must be 'm.byteLength + crypto_box_MACBYTES' bytes"
  )
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_easy(c, m, n, pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_detached = function (c, mac, m, n, pk, sk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(mac.byteLength === exports.crypto_box_MACBYTES, "mac must be 'crypto_box_MACBYTES' bytes")
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_detached(c, mac, m, n, pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_open_easy = function (m, c, n, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength >= exports.crypto_box_MACBYTES,
    "c must be at least 'crypto_box_MACBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - exports.crypto_box_MACBYTES,
    "m must be 'c.byteLength - crypto_box_MACBYTES' bytes"
  )
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_open_easy(m, c, n, pk, sk)
}

exports.crypto_box_open_detached = function (m, c, mac, n, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(mac.byteLength === exports.crypto_box_MACBYTES, "mac must be 'crypto_box_MACBYTES' bytes")
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_open_detached(m, c, mac, n, pk, sk)
}

exports.crypto_box_seal = function (c, m, pk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    c.byteLength === m.byteLength + exports.crypto_box_SEALBYTES,
    "c must be 'm.byteLength + crypto_box_SEALBYTES' bytes"
  )
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_box_seal(c, m, pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_seal_open = function (m, c, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength >= exports.crypto_box_SEALBYTES,
    "c must be at least 'crypto_box_SEALBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - exports.crypto_box_SEALBYTES,
    "m must be 'c.byteLength - crypto_box_SEALBYTES' bytes"
  )
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_seal_open(
    m.buffer,
    m.byteOffset,
    m.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    pk.buffer,
    pk.byteOffset,
    pk.byteLength,

    sk.buffer,
    sk.byteOffset,
    sk.byteLength
  )
}

// crypto_secretbox

exports.crypto_secretbox_easy = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_secretbox_MACBYTES,
    "c must be 'm.byteLength + crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretbox_easy(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretbox_open_easy = function (m, c, n, k) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    c.byteLength >= binding.crypto_secretbox_MACBYTES,
    "c must be at least 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - binding.crypto_secretbox_MACBYTES,
    "m must be 'c.byteLength - crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  return binding.crypto_secretbox_open_easy(m, c, n, k)
}

exports.crypto_secretbox_detached = function (c, mac, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    mac.byteLength === binding.crypto_secretbox_MACBYTES,
    "mac must be 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretbox_detached(c, mac, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretbox_open_detached = function (m, c, mac, n, k) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(
    mac.byteLength === binding.crypto_secretbox_MACBYTES,
    "mac must be 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  return binding.crypto_secretbox_open_detached(m, c, mac, n, k)
}

// crypto_generichash

exports.crypto_generichash = function (output, input, key) {
  if (!key) key = OPTIONAL

  assert(ArrayBuffer.isView(output), 'output must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    output.byteLength >= binding.crypto_generichash_BYTES_MIN &&
      output.byteLength <= binding.crypto_generichash_BYTES_MAX,
    'output must be between crypto_generichash_BYTES_MIN and crypto_generichash_BYTES_MAX bytes'
  )

  if (key !== OPTIONAL) {
    assert(ArrayBuffer.isView(key), 'key must be a typed array')
    assert(
      key.byteLength >= binding.crypto_generichash_KEYBYTES_MIN &&
        key.byteLength <= binding.crypto_generichash_KEYBYTES_MAX,
      'key must be between crypto_generichash_KEYBYTES_MIN and crypto_generichash_KEYBYTES_MAX bytes'
    )
  }

  const res = binding.crypto_generichash(
    output.buffer,
    output.byteOffset,
    output.byteLength,

    input.buffer,
    input.byteOffset,
    input.byteLength,

    key.buffer,
    key.byteOffset,
    key.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_batch = function (output, batch, key) {
  assert(ArrayBuffer.isView(output), 'output must be a typed array')

  if (isNode || batch.length < 4) {
    const res = binding.crypto_generichash_batch(output, batch, !!key, key || OPTIONAL)
    if (res !== 0) throw new Error('status: ' + res)
  } else {
    const state = Buffer.alloc(binding.crypto_generichash_STATEBYTES)

    exports.crypto_generichash_init(state, key, output.byteLength)

    for (const buf of batch) {
      exports.crypto_generichash_update(state, buf)
    }

    exports.crypto_generichash_final(state, output)
  }
}

exports.crypto_generichash_keygen = function (key) {
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(
    key.byteLength === binding.crypto_generichash_KEYBYTES,
    "key must be 'crypto_generichash_KEYBYTES' bytes"
  )

  const res = binding.crypto_generichash_keygen(key.buffer, key.byteOffset, key.byteLength)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_init = function (state, key, outputLength) {
  if (!key) key = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_init(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    key.buffer,
    key.byteOffset,
    key.byteLength,

    outputLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_update(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    input.buffer,
    input.byteOffset,
    input.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_final = function (state, output) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(output), 'output must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_final(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    output.buffer,
    output.byteOffset,
    output.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

// secretstream

exports.crypto_secretstream_xchacha20poly1305_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  binding.crypto_secretstream_xchacha20poly1305_keygen(k.buffer, k.byteOffset, k.byteLength)
}

exports.crypto_secretstream_xchacha20poly1305_init_push = function (state, header, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(header), 'header must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    header.byteLength === binding.crypto_secretstream_xchacha20poly1305_HEADERBYTES,
    "header must be 'crypto_secretstream_xchacha20poly1305_HEADERBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_init_push(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    header.buffer,
    header.byteOffset,
    header.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretstream_xchacha20poly1305_init_pull = function (state, header, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(header), 'header must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    header.byteLength === binding.crypto_secretstream_xchacha20poly1305_HEADERBYTES,
    "header must be 'crypto_secretstream_xchacha20poly1305_HEADERBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_init_pull(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    header.buffer,
    header.byteOffset,
    header.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretstream_xchacha20poly1305_push = function (state, c, m, ad, tag) {
  if (!ad) ad = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    c.byteLength === m.byteLength + binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "c must be 'm.byteLength + crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_push(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    ad.buffer,
    ad.byteOffset,
    ad.byteLength,

    tag
  )

  if (res < 0) throw new Error('push failed')

  return res
}

exports.crypto_secretstream_xchacha20poly1305_pull = function (state, m, tag, c, ad) {
  if (!ad) ad = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(tag), 'tag must be a typed array')
  assert(tag.byteLength === 1, 'tag must be 1 byte')

  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    c.byteLength >= binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "c must be at least 'crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "m must be 'c.byteLength - crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_pull(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    tag.buffer,
    tag.byteOffset,
    tag.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    ad.buffer,
    ad.byteOffset,
    ad.byteLength
  )

  if (res < 0) throw new Error('pull failed')

  return res
}

exports.crypto_secretstream_xchacha20poly1305_rekey = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )

  binding.crypto_secretstream_xchacha20poly1305_rekey(
    state.buffer,
    state.byteOffset,
    state.byteLength
  )
}

// crypto_stream

exports.crypto_stream = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xor(
    c.buffer,
    c.byteOffset,
    c.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    n.buffer,
    n.byteOffset,
    n.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_auth

exports.crypto_auth = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(out.byteLength === binding.crypto_auth_BYTES, "out must be 'crypto_auth_BYTES' bytes")
  assert(k.byteLength === binding.crypto_auth_KEYBYTES, "k must be 'crypto_auth_KEYBYTES' bytes")

  const res = binding.crypto_auth(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_auth_verify = function (h, input, k) {
  assert(ArrayBuffer.isView(h), 'h must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(h.byteLength === binding.crypto_auth_BYTES, "h must be 'crypto_auth_BYTES' bytes")
  assert(k.byteLength === binding.crypto_auth_KEYBYTES, "k must be 'crypto_auth_KEYBYTES' bytes")

  return binding.crypto_auth_verify(h, input, k)
}

// crypto_onetimeauth

exports.crypto_onetimeauth = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    out.byteLength === binding.crypto_onetimeauth_BYTES,
    "out must be 'crypto_onetimeauth_BYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_init = function (state, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_init(state, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )
  assert(
    out.byteLength === binding.crypto_onetimeauth_BYTES,
    "out must be 'crypto_onetimeauth_BYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_verify = function (h, input, k) {
  assert(ArrayBuffer.isView(h), 'h must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    h.byteLength === binding.crypto_onetimeauth_BYTES,
    "h must be 'crypto_onetimeauth_BYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  return binding.crypto_onetimeauth_verify(h, input, k)
}

// crypto_pwhash

exports.crypto_pwhash = function (out, passwd, salt, opslimit, memlimit, alg) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_BYTES_MIN,
    "out must be at least 'crypto_pwhash_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_BYTES_MAX,
    "out must be at most 'crypto_pwhash_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_SALTBYTES,
    "salt must be 'crypto_pwhash_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )
  assert(alg >= 1 && alg <= 2, 'alg must be either Argon2i 1.3 or Argon2id 1.3')

  const res = binding.crypto_pwhash(out, passwd, salt, opslimit, memlimit, alg)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_async = function (
  out,
  passwd,
  salt,
  opslimit,
  memlimit,
  alg,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_BYTES_MIN,
    "out must be at least 'crypto_pwhash_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_BYTES_MAX,
    "out must be at most 'crypto_pwhash_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_SALTBYTES,
    "salt must be 'crypto_pwhash_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )
  assert(alg >= 1 && alg <= 2, 'alg must be either Argon2i 1.3 or Argon2id 1.3')

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    opslimit,
    memlimit,
    alg,

    done
  )

  return promise
}

exports.crypto_pwhash_str = function (out, passwd, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_STRBYTES,
    "out must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(typeof opslimit === 'number', 'opslimit must be a number')
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(typeof memlimit === 'number', 'memlimit must be a number')
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_str(out, passwd, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_str_async = function (out, passwd, opslimit, memlimit, callback = undefined) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_STRBYTES,
    "out must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(typeof opslimit === 'number', 'opslimit must be a number')
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(typeof memlimit === 'number', 'memlimit must be a number')
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_str_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_str_verify = function (str, passwd) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )

  return binding.crypto_pwhash_str_verify(str, passwd)
}

exports.crypto_pwhash_str_verify_async = function (str, passwd, callback = undefined) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  const [done, promise] = checkStatus(callback, true)

  binding.crypto_pwhash_str_verify_async(
    str.buffer,
    str.byteOffset,
    str.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    done
  )

  return promise
}

exports.crypto_pwhash_str_needs_rehash = function (str, opslimit, memlimit) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  return binding.crypto_pwhash_str_needs_rehash(str, opslimit, memlimit)
}

exports.crypto_pwhash_scryptsalsa208sha256 = function (out, passwd, salt, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MIN,
    "out must be at least 'crypto_pwhash_scryptsalsa208sha256_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MAX,
    "out must be at most 'crypto_pwhash_scryptsalsa208sha256_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_SALTBYTES,
    "salt must be 'crypto_pwhash_scryptsalsa208sha256_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_scryptsalsa208sha256(out, passwd, salt, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_scryptsalsa208sha256_async = function (
  out,
  passwd,
  salt,
  opslimit,
  memlimit,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MIN,
    "out must be at least 'crypto_pwhash_scryptsalsa208sha256_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MAX,
    "out must be at most 'crypto_pwhash_scryptsalsa208sha256_BYTES_MAX' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    salt.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_SALTBYTES,
    "salt must be 'crypto_pwhash_scryptsalsa208sha256_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_scryptsalsa208sha256_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str_async = function (
  out,
  passwd,
  opslimit,
  memlimit,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "out must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_scryptsalsa208sha256_str_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str = function (out, passwd, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "out must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_scryptsalsa208sha256_str(out, passwd, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_scryptsalsa208sha256_str_verify_async = function (
  str,
  passwd,
  callback = undefined
) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  const [done, promise] = checkStatus(callback, true)

  binding.crypto_pwhash_scryptsalsa208sha256_str_verify_async(
    str.buffer,
    str.byteOffset,
    str.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str_verify = function (str, passwd) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  return binding.crypto_pwhash_scryptsalsa208sha256_str_verify(str, passwd)
}

exports.crypto_pwhash_scryptsalsa208sha256_str_needs_rehash = function (str, opslimit, memlimit) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  return binding.crypto_pwhash_scryptsalsa208sha256_str_needs_rehash(str, opslimit, memlimit)
}

// crypto_kx

exports.crypto_kx_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "pk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "sk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    pk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "pk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "sk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    seed.byteLength === binding.crypto_kx_SEEDBYTES,
    "seed must be 'crypto_kx_SEEDBYTES' bytes"
  )

  const res = binding.crypto_kx_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_client_session_keys = function (rx, tx, clientPk, clientSk, serverPk) {
  if (!rx) rx = undefined
  if (!tx) tx = undefined

  assert(rx || tx, 'at least one session key must be specified')

  if (rx) {
    assert(ArrayBuffer.isView(rx), 'rx must be a typed array')
    assert(
      rx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "rx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  if (tx) {
    assert(ArrayBuffer.isView(tx), 'tx must be a typed array')
    assert(
      tx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "tx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  assert(ArrayBuffer.isView(clientPk), 'clientPk must be a typed array')
  assert(ArrayBuffer.isView(clientSk), 'clientSk must be a typed array')
  assert(ArrayBuffer.isView(serverPk), 'serverPk must be a typed array')
  assert(
    clientPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "clientPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    clientSk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "clientSk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    serverPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "serverPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_client_session_keys(rx, tx, clientPk, clientSk, serverPk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_server_session_keys = function (rx, tx, serverPk, serverSk, clientPk) {
  if (!rx) rx = undefined
  if (!tx) tx = undefined

  assert(rx || tx, 'at least one session key must be specified')

  if (rx) {
    assert(ArrayBuffer.isView(rx), 'rx must be a typed array')
    assert(
      rx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "rx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  if (tx) {
    assert(ArrayBuffer.isView(tx), 'tx must be a typed array')
    assert(
      tx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "tx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  assert(ArrayBuffer.isView(serverPk), 'serverPk must be a typed array')
  assert(ArrayBuffer.isView(serverSk), 'serverSk must be a typed array')
  assert(ArrayBuffer.isView(clientPk), 'clientPk must be a typed array')
  assert(
    serverPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "serverPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    serverSk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "serverSk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    clientPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "clientPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_server_session_keys(rx, tx, serverPk, serverSk, clientPk)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_scalarmult

exports.crypto_scalarmult_base = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_BYTES,
    "q must be 'crypto_scalarmult_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_SCALARBYTES,
    "n must be 'crypto_scalarmult_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_base(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_BYTES,
    "q must be 'crypto_scalarmult_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_SCALARBYTES,
    "n must be 'crypto_scalarmult_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_BYTES,
    "p must be 'crypto_scalarmult_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_base = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_base(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519 = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "p must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_is_valid_point = function (p) {
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )

  return binding.crypto_core_ed25519_is_valid_point(p)
}

exports.crypto_core_ed25519_from_uniform = function (p, r) {
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_UNIFORMBYTES,
    "r must be 'crypto_core_ed25519_UNIFORMBYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_from_uniform(p, r)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_base_noclamp = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_base_noclamp(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_noclamp = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "p must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_noclamp(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_core

exports.crypto_core_ed25519_add = function (r, p, q) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_BYTES,
    "r must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_core_ed25519_BYTES,
    "q must be 'crypto_core_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_add(r, p, q)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_sub = function (r, p, q) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_BYTES,
    "r must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_core_ed25519_BYTES,
    "q must be 'crypto_core_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_sub(r, p, q)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_scalar_random = function (r) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "r must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_random(r)
}

exports.crypto_core_ed25519_scalar_reduce = function (r, s) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "r must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_NONREDUCEDSCALARBYTES,
    "s must be 'crypto_core_ed25519_NONREDUCEDSCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_reduce(r, s)
}

exports.crypto_core_ed25519_scalar_invert = function (recip, s) {
  assert(ArrayBuffer.isView(recip), 'recip must be a typed array')
  assert(
    recip.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "recip must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_invert(recip, s)
}

exports.crypto_core_ed25519_scalar_negate = function (neg, s) {
  assert(ArrayBuffer.isView(neg), 'neg must be a typed array')
  assert(
    neg.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "neg must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_negate(neg, s)
}

exports.crypto_core_ed25519_scalar_complement = function (comp, s) {
  assert(ArrayBuffer.isView(comp), 'comp must be a typed array')
  assert(
    comp.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "comp must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_complement(comp, s)
}

exports.crypto_core_ed25519_scalar_add = function (z, x, y) {
  assert(ArrayBuffer.isView(z), 'z must be a typed array')
  assert(
    z.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "z must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(x), 'x must be a typed array')
  assert(
    x.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "x must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(y), 'y must be a typed array')
  assert(
    y.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "y must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_add(z, x, y)
}

exports.crypto_core_ed25519_scalar_sub = function (z, x, y) {
  assert(ArrayBuffer.isView(z), 'z must be a typed array')
  assert(
    z.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "z must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(x), 'x must be a typed array')
  assert(
    x.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "x must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(y), 'y must be a typed array')
  assert(
    y.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "y must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_sub(z, x, y)
}

// crypto_shorthash

exports.crypto_shorthash = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_shorthash_BYTES,
    "out must be 'crypto_shorthash_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_shorthash_KEYBYTES,
    "k must be 'crypto_shorthash_KEYBYTES' bytes"
  )

  const res = binding.crypto_shorthash(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_kdf

exports.crypto_kdf_keygen = function (key) {
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(key.byteLength === binding.crypto_kdf_KEYBYTES, "key must be 'crypto_kdf_KEYBYTES' bytes")

  binding.crypto_kdf_keygen(key)
}

exports.crypto_kdf_derive_from_key = function (subkey, subkeyId, ctx, key) {
  assert(ArrayBuffer.isView(subkey), 'subkey must be a typed array')
  assert(
    subkey.byteLength >= binding.crypto_kdf_BYTES_MIN,
    "subkey must be at least 'crypto_kdf_BYTES_MIN' bytes"
  )
  assert(
    subkey.byteLength <= binding.crypto_kdf_BYTES_MAX,
    "subkey must be at most 'crypto_kdf_BYTES_MAX' bytes"
  )
  assert(ArrayBuffer.isView(ctx), 'ctx must be a typed array')
  assert(
    ctx.byteLength === binding.crypto_kdf_CONTEXTBYTES,
    "ctx must be 'crypto_kdf_CONTEXTBYTES' bytes"
  )
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(key.byteLength === binding.crypto_kdf_KEYBYTES, "key must be 'crypto_kdf_KEYBYTES' bytes")

  const res = binding.crypto_kdf_derive_from_key(subkey, subkeyId, ctx, key)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_hash

exports.crypto_hash = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(out.byteLength === binding.crypto_hash_BYTES, "out must be 'crypto_hash_BYTES' bytes")

  const res = binding.crypto_hash(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256 = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha256_BYTES,
    "out must be 'crypto_hash_sha256_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha256(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_init = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_init(state)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha256_BYTES,
    "out must be 'crypto_hash_sha256_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512 = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha512_BYTES,
    "out must be 'crypto_hash_sha512_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha512(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_init = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_init(state)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha512_BYTES,
    "out must be 'crypto_hash_sha512_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_aead

exports.crypto_aead_xchacha20poly1305_ietf_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  binding.crypto_aead_xchacha20poly1305_ietf_keygen(k)
}

exports.crypto_aead_xchacha20poly1305_ietf_encrypt = function (c, m, ad, nsec, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "c must be 'm.byteLength + crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(c.byteLength <= 0xffffffff, 'c.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_encrypt(c, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_decrypt = function (m, nsec, c, ad, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "m must be 'c.byteLength - crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(m.byteLength <= 0xffffffff, 'm.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_decrypt(m, c, ad, npub, k)

  if (res < 0) throw new Error('could not verify data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_encrypt_detached = function (
  c,
  mac,
  m,
  ad,
  nsec,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_encrypt_detached(c, mac, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_decrypt_detached = function (
  m,
  nsec,
  c,
  mac,
  ad,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_decrypt_detached(m, c, mac, ad, npub, k)

  if (res !== 0) throw new Error('could not verify data')
}

exports.crypto_aead_chacha20poly1305_ietf_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  binding.crypto_aead_chacha20poly1305_ietf_keygen(k)
}

exports.crypto_aead_chacha20poly1305_ietf_encrypt = function (c, m, ad, nsec, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "c must be 'm.byteLength + crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(c.byteLength <= 0xffffffff, 'c.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_encrypt(c, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_decrypt = function (m, nsec, c, ad, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "m must be 'c.byteLength - crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(m.byteLength <= 0xffffffff, 'm.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_decrypt(m, c, ad, npub, k)

  if (res < 0) throw new Error('could not verify data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_encrypt_detached = function (
  c,
  mac,
  m,
  ad,
  nsec,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_encrypt_detached(c, mac, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_decrypt_detached = function (
  m,
  nsec,
  c,
  mac,
  ad,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_decrypt_detached(m, c, mac, ad, npub, k)

  if (res !== 0) throw new Error('could not verify data')
}

// crypto_stream

exports.crypto_stream_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  binding.crypto_stream_xor_wrap_init(state, n, k)
}

exports.crypto_stream_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_xor_wrap_update(state, c, m)
}

exports.crypto_stream_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_xor_wrap_final(state)
}

exports.crypto_stream_chacha20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  binding.crypto_stream_chacha20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_chacha20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_chacha20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_chacha20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_chacha20_xor_wrap_final(state)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  binding.crypto_stream_chacha20_ietf_xor_wrap_init(state, n, k)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_chacha20_ietf_xor_wrap_update(state, c, m)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_chacha20_ietf_xor_wrap_final(state)
}

exports.crypto_stream_xchacha20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  binding.crypto_stream_xchacha20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_xchacha20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_xchacha20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_xchacha20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_xchacha20_xor_wrap_final(state)
}

exports.crypto_stream_salsa20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  binding.crypto_stream_salsa20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_salsa20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_salsa20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_salsa20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_salsa20_xor_wrap_final(state)
}

// experimental

exports.extension_tweak_ed25519_base = function (n, p, ns) {
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.extension_tweak_ed25519_BYTES,
    "p must be 'extension_tweak_ed25519_BYTES' bytes"
  )

  binding.extension_tweak_ed25519_base(n, p, ns)
}

exports.extension_tweak_ed25519_sign_detached = function (sig, m, scalar, pk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(sig.byteLength === binding.crypto_sign_BYTES, "sig must be 'crypto_sign_BYTES' bytes")
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  if (pk) {
    assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
    assert(
      pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
      "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
    )
  }

  const res = binding.extension_tweak_ed25519_sign_detached(sig, m, scalar, pk)

  if (res !== 0) throw new Error('failed to compute signature')
}

exports.extension_tweak_ed25519_sk_to_scalar = function (n, sk) {
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  binding.extension_tweak_ed25519_sk_to_scalar(n, sk)
}

exports.extension_tweak_ed25519_scalar = function (scalarOut, scalar, ns) {
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_scalar(scalarOut, scalar, ns)
}

exports.extension_tweak_ed25519_pk = function (tpk, pk, ns) {
  assert(ArrayBuffer.isView(tpk), 'tpk must be a typed array')
  assert(
    tpk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "tpk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_pk(tpk, pk, ns)

  if (res !== 0) throw new Error('failed to tweak public key')
}

exports.extension_tweak_ed25519_keypair = function (pk, scalarOut, scalarIn, ns) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.extension_tweak_ed25519_BYTES,
    "pk must be 'extension_tweak_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarIn), 'scalarIn must be a typed array')
  assert(
    scalarIn.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarIn must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_keypair(pk, scalarOut, scalarIn, ns)
}

exports.extension_tweak_ed25519_scalar_add = function (scalarOut, scalar, n) {
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_scalar_add(scalarOut, scalar, n)
}

exports.extension_tweak_ed25519_pk_add = function (tpk, pk, p) {
  assert(ArrayBuffer.isView(tpk), 'tpk must be a typed array')
  assert(
    tpk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "tpk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "p must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_pk_add(tpk, pk, p)

  if (res !== 0) throw new Error('failed to add tweak to public key')
}

exports.extension_tweak_ed25519_keypair_add = function (pk, scalarOut, scalarIn, tweak) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.extension_tweak_ed25519_BYTES,
    "pk must be 'extension_tweak_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarIn), 'scalarIn must be a typed array')
  assert(
    scalarIn.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarIn must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(tweak), 'tweak must be a typed array')
  assert(
    tweak.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "tweak must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_keypair_add(pk, scalarOut, scalarIn, tweak)

  if (res !== 0) throw new Error('failed to add tweak to keypair')
}

exports.extension_pbkdf2_sha512_async = function (out, passwd, salt, iter, outlen, callback) {
  assert(
    iter >= binding.extension_pbkdf2_sha512_ITERATIONS_MIN,
    "iter must be at least 'extension_pbkdf2_sha512_ITERATIONS_MIN'"
  )
  assert(
    outlen <= binding.extension_pbkdf2_sha512_BYTES_MAX,
    "outlen must be at most 'extension_pbkdf2_sha512_BYTES_MAX'"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(out.byteLength >= outlen, "out must be at least 'outlen' bytes")
  assert(out.byteLength > 0, 'out must not be empty')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(salt.byteLength > 0, 'salt must not be empty')

  const [done, promise] = checkStatus(callback)

  binding.extension_pbkdf2_sha512_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    iter,
    outlen,

    done
  )

  return promise
}

exports.extension_pbkdf2_sha512 = function (out, passwd, salt, iter, outlen) {
  assert(
    iter >= binding.extension_pbkdf2_sha512_ITERATIONS_MIN,
    "iter must be at least 'extension_pbkdf2_sha512_ITERATIONS_MIN'"
  )
  assert(
    outlen <= binding.extension_pbkdf2_sha512_BYTES_MAX,
    "outlen must be at most 'extension_pbkdf2_sha512_BYTES_MAX'"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(out.byteLength >= outlen, "out must be at least 'outlen' bytes")
  assert(out.byteLength > 0, 'out must not be empty')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(salt.byteLength > 0, 'salt must not be empty')

  const res = binding.extension_pbkdf2_sha512(out, passwd, salt, iter, outlen)

  if (res !== 0) throw new Error('failed to add tweak to public key')
}

function checkStatus(callback, booleanResult = false) {
  let done, promise

  if (typeof callback === 'function') {
    done = function (status) {
      if (booleanResult) callback(null, status === 0)
      else if (status === 0) callback(null)
      else callback(new Error('status: ' + status))
    }
  } else {
    promise = new Promise(function (resolve, reject) {
      done = function (status) {
        if (booleanResult) resolve(status === 0)
        else if (status === 0) resolve()
        else reject(new Error('status: ' + status))
      }
    })
  }

  return [done, promise]
}
{
  "name": "sodium-native",
  "version": "5.1.0",
  "description": "Low level bindings for libsodium",
  "main": "index.js",
  "files": [
    "index.js",
    "binding.cc",
    "binding.js",
    "extensions",
    "prebuilds",
    "CMakeLists.txt"
  ],
  "imports": {
    "assert": {
      "bare": "bare-assert",
      "node": "assert"
    }
  },
  "addon": true,
  "dependencies": {
    "bare-assert": "^1.2.0",
    "require-addon": "^1.1.0",
    "which-runtime": "^1.2.1"
  },
  "devDependencies": {
    "bare-compat-napi": "^1.3.5",
    "brittle": "^3.16.2",
    "cmake-bare": "^1.6.1",
    "cmake-fetch": "^1.4.3",
    "cmake-napi": "^1.2.1",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "test": "prettier . --check && npm run test:node && npm run test:bare",
    "test:node": "node test/all.js",
    "test:bare": "bare test/all.js"
  },
  "standard": {
    "ignore": [
      "/test/fixtures/*.js"
    ]
  },
  "engines": {
    "bare": ">=1.16.0"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sodium-native.git"
  },
  "contributors": [
    "Emil Bay <github@tixz.dk> (http://bayes.dk)",
    "Mathias Buus <mathiasbuus@gmail.com> (https://mafinto.sh)",
    "Christophe Diederichs <chm-diederichs@hyperdivision.dk>"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/sodium-native/issues"
  },
  "homepage": "https://github.com/holepunchto/sodium-native"
}
const sodium = require('sodium-universal')
const b4a = require('b4a')

const ABYTES = sodium.crypto_secretstream_xchacha20poly1305_ABYTES
const TAG_MESSAGE = sodium.crypto_secretstream_xchacha20poly1305_TAG_MESSAGE
const TAG_FINAL = sodium.crypto_secretstream_xchacha20poly1305_TAG_FINAL
const STATEBYTES = sodium.crypto_secretstream_xchacha20poly1305_STATEBYTES
const HEADERBYTES = sodium.crypto_secretstream_xchacha20poly1305_HEADERBYTES
const KEYBYTES = sodium.crypto_secretstream_xchacha20poly1305_KEYBYTES
const TAG_FINAL_BYTE = b4a.isBuffer(TAG_FINAL) ? TAG_FINAL[0] : TAG_FINAL

const EMPTY = b4a.alloc(0)
const TAG = b4a.alloc(1)

class Push {
  constructor (key, state = b4a.allocUnsafeSlow(STATEBYTES), header = b4a.allocUnsafeSlow(HEADERBYTES)) {
    if (!TAG_FINAL) throw new Error('JavaScript sodium version needs to support crypto_secretstream_xchacha20poly')

    this.key = key
    this.state = state
    this.header = header

    sodium.crypto_secretstream_xchacha20poly1305_init_push(this.state, this.header, this.key)
  }

  next (message, cipher = b4a.allocUnsafe(message.byteLength + ABYTES)) {
    sodium.crypto_secretstream_xchacha20poly1305_push(this.state, cipher, message, null, TAG_MESSAGE)
    return cipher
  }

  final (message = EMPTY, cipher = b4a.allocUnsafe(ABYTES)) {
    sodium.crypto_secretstream_xchacha20poly1305_push(this.state, cipher, message, null, TAG_FINAL)
    return cipher
  }
}

class Pull {
  constructor (key, state = b4a.allocUnsafeSlow(STATEBYTES)) {
    if (!TAG_FINAL) throw new Error('JavaScript sodium version needs to support crypto_secretstream_xchacha20poly')

    this.key = key
    this.state = state
    this.final = false
  }

  init (header) {
    sodium.crypto_secretstream_xchacha20poly1305_init_pull(this.state, header, this.key)
  }

  next (cipher, message = b4a.allocUnsafe(cipher.byteLength - ABYTES)) {
    sodium.crypto_secretstream_xchacha20poly1305_pull(this.state, message, TAG, cipher, null)
    this.final = TAG[0] === TAG_FINAL_BYTE
    return message
  }
}

function keygen (buf = b4a.alloc(KEYBYTES)) {
  sodium.crypto_secretstream_xchacha20poly1305_keygen(buf)
  return buf
}

module.exports = {
  keygen,
  KEYBYTES,
  ABYTES,
  STATEBYTES,
  HEADERBYTES,
  Push,
  Pull
}
{
  "name": "sodium-secretstream",
  "version": "1.2.0",
  "description": "Wraps libsodiums secretstream in a higher level abstraction",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.1.1",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "standard": "^17.0.0"
  },
  "scripts": {
    "test": "standard"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/sodium-secretstream.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/sodium-secretstream/issues"
  },
  "homepage": "https://github.com/mafintosh/sodium-secretstream"
}
module.exports = require('sodium-native')
{
  "name": "sodium-universal",
  "version": "5.0.1",
  "description": "Universal wrapper for sodium-javascript and sodium-native working in Node.js and the Browser",
  "main": "index.js",
  "dependencies": {
    "sodium-native": "^5.0.1"
  },
  "peerDependencies": {
    "sodium-javascript": "~0.8.0"
  },
  "peerDependenciesMeta": {
    "sodium-javascript": {
      "optional": true
    }
  },
  "scripts": {
    "prepublish": "./build-scripts/generate.js"
  },
  "browser": {
    "sodium-native": "sodium-javascript"
  },
  "browserify": {
    "transform": [
      "./build-scripts/transform.js"
    ]
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sodium-universal.git"
  },
  "keywords": [
    "libsodium",
    "sodium",
    "sodium-native",
    "sodium-javascript",
    "browserify"
  ],
  "contributors": [
    "Emil Bay <github@tixz.dk> (http://bayes.dk)",
    "Mathias Buus <mathiasbuus@gmail.com> (https://mafinto.sh)",
    "Christophe Diederichs <chm-diederichs@hyperdivision.dk>"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/sodium-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/sodium-universal#readme"
}
const { EventEmitter } = require('events-universal')
const STREAM_DESTROYED = new Error('Stream was destroyed')
const PREMATURE_CLOSE = new Error('Premature close')

const FIFO = require('fast-fifo')
const TextDecoder = require('text-decoder')

// if we do a future major, expect queue microtask to be there always, for now a bit defensive
const qmt =
  typeof queueMicrotask === 'undefined' ? (fn) => global.process.nextTick(fn) : queueMicrotask

// 29 bits used total (4 from shared, 14 from read, and 11 from write)
const MAX = (1 << 29) - 1

// Shared state
const OPENING = 0b0001
const PREDESTROYING = 0b0010
const DESTROYING = 0b0100
const DESTROYED = 0b1000

const NOT_OPENING = MAX ^ OPENING
const NOT_PREDESTROYING = MAX ^ PREDESTROYING

// Read state (4 bit offset from shared state)
const READ_ACTIVE = 0b00000000000001 << 4
const READ_UPDATING = 0b00000000000010 << 4
const READ_PRIMARY = 0b00000000000100 << 4
const READ_QUEUED = 0b00000000001000 << 4
const READ_RESUMED = 0b00000000010000 << 4
const READ_PIPE_DRAINED = 0b00000000100000 << 4
const READ_ENDING = 0b00000001000000 << 4
const READ_EMIT_DATA = 0b00000010000000 << 4
const READ_EMIT_READABLE = 0b00000100000000 << 4
const READ_EMITTED_READABLE = 0b00001000000000 << 4
const READ_DONE = 0b00010000000000 << 4
const READ_NEXT_TICK = 0b00100000000000 << 4
const READ_NEEDS_PUSH = 0b01000000000000 << 4
const READ_READ_AHEAD = 0b10000000000000 << 4

// Combined read state
const READ_FLOWING = READ_RESUMED | READ_PIPE_DRAINED
const READ_ACTIVE_AND_NEEDS_PUSH = READ_ACTIVE | READ_NEEDS_PUSH
const READ_PRIMARY_AND_ACTIVE = READ_PRIMARY | READ_ACTIVE
const READ_EMIT_READABLE_AND_QUEUED = READ_EMIT_READABLE | READ_QUEUED
const READ_RESUMED_READ_AHEAD = READ_RESUMED | READ_READ_AHEAD

const READ_NOT_ACTIVE = MAX ^ READ_ACTIVE
const READ_NON_PRIMARY = MAX ^ READ_PRIMARY
const READ_NON_PRIMARY_AND_PUSHED = MAX ^ (READ_PRIMARY | READ_NEEDS_PUSH)
const READ_PUSHED = MAX ^ READ_NEEDS_PUSH
const READ_PAUSED = MAX ^ READ_RESUMED
const READ_NOT_QUEUED = MAX ^ (READ_QUEUED | READ_EMITTED_READABLE)
const READ_NOT_ENDING = MAX ^ READ_ENDING
const READ_PIPE_NOT_DRAINED = MAX ^ READ_FLOWING
const READ_NOT_NEXT_TICK = MAX ^ READ_NEXT_TICK
const READ_NOT_UPDATING = MAX ^ READ_UPDATING
const READ_NO_READ_AHEAD = MAX ^ READ_READ_AHEAD
const READ_PAUSED_NO_READ_AHEAD = MAX ^ READ_RESUMED_READ_AHEAD

// Write state (18 bit offset, 4 bit offset from shared state and 14 from read state)
const WRITE_ACTIVE = 0b00000000001 << 18
const WRITE_UPDATING = 0b00000000010 << 18
const WRITE_PRIMARY = 0b00000000100 << 18
const WRITE_QUEUED = 0b00000001000 << 18
const WRITE_UNDRAINED = 0b00000010000 << 18
const WRITE_DONE = 0b00000100000 << 18
const WRITE_EMIT_DRAIN = 0b00001000000 << 18
const WRITE_NEXT_TICK = 0b00010000000 << 18
const WRITE_WRITING = 0b00100000000 << 18
const WRITE_FINISHING = 0b01000000000 << 18
const WRITE_CORKED = 0b10000000000 << 18

const WRITE_NOT_ACTIVE = MAX ^ (WRITE_ACTIVE | WRITE_WRITING)
const WRITE_NON_PRIMARY = MAX ^ WRITE_PRIMARY
const WRITE_NOT_FINISHING = MAX ^ (WRITE_ACTIVE | WRITE_FINISHING)
const WRITE_DRAINED = MAX ^ WRITE_UNDRAINED
const WRITE_NOT_QUEUED = MAX ^ WRITE_QUEUED
const WRITE_NOT_NEXT_TICK = MAX ^ WRITE_NEXT_TICK
const WRITE_NOT_UPDATING = MAX ^ WRITE_UPDATING
const WRITE_NOT_CORKED = MAX ^ WRITE_CORKED

// Combined shared state
const ACTIVE = READ_ACTIVE | WRITE_ACTIVE
const NOT_ACTIVE = MAX ^ ACTIVE
const DONE = READ_DONE | WRITE_DONE
const DESTROY_STATUS = DESTROYING | DESTROYED | PREDESTROYING
const OPEN_STATUS = DESTROY_STATUS | OPENING
const AUTO_DESTROY = DESTROY_STATUS | DONE
const NON_PRIMARY = WRITE_NON_PRIMARY & READ_NON_PRIMARY
const ACTIVE_OR_TICKING = WRITE_NEXT_TICK | READ_NEXT_TICK
const TICKING = ACTIVE_OR_TICKING & NOT_ACTIVE
const IS_OPENING = OPEN_STATUS | TICKING

// Combined shared state and read state
const READ_PRIMARY_STATUS = OPEN_STATUS | READ_ENDING | READ_DONE
const READ_STATUS = OPEN_STATUS | READ_DONE | READ_QUEUED
const READ_ENDING_STATUS = OPEN_STATUS | READ_ENDING | READ_QUEUED
const READ_READABLE_STATUS = OPEN_STATUS | READ_EMIT_READABLE | READ_QUEUED | READ_EMITTED_READABLE
const SHOULD_NOT_READ =
  OPEN_STATUS | READ_ACTIVE | READ_ENDING | READ_DONE | READ_NEEDS_PUSH | READ_READ_AHEAD
const READ_BACKPRESSURE_STATUS = DESTROY_STATUS | READ_ENDING | READ_DONE
const READ_UPDATE_SYNC_STATUS = READ_UPDATING | OPEN_STATUS | READ_NEXT_TICK | READ_PRIMARY
const READ_NEXT_TICK_OR_OPENING = READ_NEXT_TICK | OPENING

// Combined write state
const WRITE_PRIMARY_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_DONE
const WRITE_QUEUED_AND_UNDRAINED = WRITE_QUEUED | WRITE_UNDRAINED
const WRITE_QUEUED_AND_ACTIVE = WRITE_QUEUED | WRITE_ACTIVE
const WRITE_DRAIN_STATUS = WRITE_QUEUED | WRITE_UNDRAINED | OPEN_STATUS | WRITE_ACTIVE
const WRITE_STATUS = OPEN_STATUS | WRITE_ACTIVE | WRITE_QUEUED | WRITE_CORKED
const WRITE_PRIMARY_AND_ACTIVE = WRITE_PRIMARY | WRITE_ACTIVE
const WRITE_ACTIVE_AND_WRITING = WRITE_ACTIVE | WRITE_WRITING
const WRITE_FINISHING_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_QUEUED_AND_ACTIVE | WRITE_DONE
const WRITE_BACKPRESSURE_STATUS = WRITE_UNDRAINED | DESTROY_STATUS | WRITE_FINISHING | WRITE_DONE
const WRITE_UPDATE_SYNC_STATUS = WRITE_UPDATING | OPEN_STATUS | WRITE_NEXT_TICK | WRITE_PRIMARY
const WRITE_DROP_DATA = WRITE_FINISHING | WRITE_DONE | DESTROY_STATUS

const asyncIterator = Symbol.asyncIterator || Symbol('asyncIterator')

class WritableState {
  constructor(
    stream,
    { highWaterMark = 16384, map = null, mapWritable, byteLength, byteLengthWritable } = {}
  ) {
    this.stream = stream
    this.queue = new FIFO()
    this.highWaterMark = highWaterMark
    this.buffered = 0
    this.error = null
    this.pipeline = null
    this.drains = null // if we add more seldomly used helpers we might them into a subobject so its a single ptr
    this.byteLength = byteLengthWritable || byteLength || defaultByteLength
    this.map = mapWritable || map
    this.afterWrite = afterWrite.bind(this)
    this.afterUpdateNextTick = updateWriteNT.bind(this)
  }

  get ending() {
    return (this.stream._duplexState & WRITE_FINISHING) !== 0
  }

  get ended() {
    return (this.stream._duplexState & WRITE_DONE) !== 0
  }

  push(data) {
    if ((this.stream._duplexState & WRITE_DROP_DATA) !== 0) return false
    if (this.map !== null) data = this.map(data)

    this.buffered += this.byteLength(data)
    this.queue.push(data)

    if (this.buffered < this.highWaterMark) {
      this.stream._duplexState |= WRITE_QUEUED
      return true
    }

    this.stream._duplexState |= WRITE_QUEUED_AND_UNDRAINED
    return false
  }

  shift() {
    const data = this.queue.shift()

    this.buffered -= this.byteLength(data)
    if (this.buffered === 0) this.stream._duplexState &= WRITE_NOT_QUEUED

    return data
  }

  end(data) {
    if (typeof data === 'function') this.stream.once('finish', data)
    else if (data !== undefined && data !== null) this.push(data)
    this.stream._duplexState = (this.stream._duplexState | WRITE_FINISHING) & WRITE_NON_PRIMARY
  }

  autoBatch(data, cb) {
    const buffer = []
    const stream = this.stream

    buffer.push(data)
    while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED_AND_ACTIVE) {
      buffer.push(stream._writableState.shift())
    }

    if ((stream._duplexState & OPEN_STATUS) !== 0) return cb(null)
    stream._writev(buffer, cb)
  }

  update() {
    const stream = this.stream

    stream._duplexState |= WRITE_UPDATING

    do {
      while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED) {
        const data = this.shift()
        stream._duplexState |= WRITE_ACTIVE_AND_WRITING
        stream._write(data, this.afterWrite)
      }

      if ((stream._duplexState & WRITE_PRIMARY_AND_ACTIVE) === 0) this.updateNonPrimary()
    } while (this.continueUpdate() === true)

    stream._duplexState &= WRITE_NOT_UPDATING
  }

  updateNonPrimary() {
    const stream = this.stream

    if ((stream._duplexState & WRITE_FINISHING_STATUS) === WRITE_FINISHING) {
      stream._duplexState = stream._duplexState | WRITE_ACTIVE
      stream._final(afterFinal.bind(this))
      return
    }

    if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
      if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
        stream._duplexState |= ACTIVE
        stream._destroy(afterDestroy.bind(this))
      }
      return
    }

    if ((stream._duplexState & IS_OPENING) === OPENING) {
      stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING
      stream._open(afterOpen.bind(this))
    }
  }

  continueUpdate() {
    if ((this.stream._duplexState & WRITE_NEXT_TICK) === 0) return false
    this.stream._duplexState &= WRITE_NOT_NEXT_TICK
    return true
  }

  updateCallback() {
    if ((this.stream._duplexState & WRITE_UPDATE_SYNC_STATUS) === WRITE_PRIMARY) this.update()
    else this.updateNextTick()
  }

  updateNextTick() {
    if ((this.stream._duplexState & WRITE_NEXT_TICK) !== 0) return
    this.stream._duplexState |= WRITE_NEXT_TICK
    if ((this.stream._duplexState & WRITE_UPDATING) === 0) qmt(this.afterUpdateNextTick)
  }
}

class ReadableState {
  constructor(
    stream,
    { highWaterMark = 16384, map = null, mapReadable, byteLength, byteLengthReadable } = {}
  ) {
    this.stream = stream
    this.queue = new FIFO()
    this.highWaterMark = highWaterMark === 0 ? 1 : highWaterMark
    this.buffered = 0
    this.readAhead = highWaterMark > 0
    this.error = null
    this.pipeline = null
    this.byteLength = byteLengthReadable || byteLength || defaultByteLength
    this.map = mapReadable || map
    this.pipeTo = null
    this.afterRead = afterRead.bind(this)
    this.afterUpdateNextTick = updateReadNT.bind(this)
  }

  get ending() {
    return (this.stream._duplexState & READ_ENDING) !== 0
  }

  get ended() {
    return (this.stream._duplexState & READ_DONE) !== 0
  }

  pipe(pipeTo, cb) {
    if (this.pipeTo !== null) throw new Error('Can only pipe to one destination')
    if (typeof cb !== 'function') cb = null

    this.stream._duplexState |= READ_PIPE_DRAINED
    this.pipeTo = pipeTo
    this.pipeline = new Pipeline(this.stream, pipeTo, cb)

    if (cb) this.stream.on('error', noop) // We already error handle this so supress crashes

    if (isStreamx(pipeTo)) {
      pipeTo._writableState.pipeline = this.pipeline
      if (cb) pipeTo.on('error', noop) // We already error handle this so supress crashes
      pipeTo.on('finish', this.pipeline.finished.bind(this.pipeline)) // TODO: just call finished from pipeTo itself
    } else {
      const onerror = this.pipeline.done.bind(this.pipeline, pipeTo)
      const onclose = this.pipeline.done.bind(this.pipeline, pipeTo, null) // onclose has a weird bool arg
      pipeTo.on('error', onerror)
      pipeTo.on('close', onclose)
      pipeTo.on('finish', this.pipeline.finished.bind(this.pipeline))
    }

    pipeTo.on('drain', afterDrain.bind(this))
    this.stream.emit('piping', pipeTo)
    pipeTo.emit('pipe', this.stream)
  }

  push(data) {
    const stream = this.stream

    if (data === null) {
      this.highWaterMark = 0
      stream._duplexState = (stream._duplexState | READ_ENDING) & READ_NON_PRIMARY_AND_PUSHED
      return false
    }

    if (this.map !== null) {
      data = this.map(data)
      if (data === null) {
        stream._duplexState &= READ_PUSHED
        return this.buffered < this.highWaterMark
      }
    }

    this.buffered += this.byteLength(data)
    this.queue.push(data)

    stream._duplexState = (stream._duplexState | READ_QUEUED) & READ_PUSHED

    return this.buffered < this.highWaterMark
  }

  shift() {
    const data = this.queue.shift()

    this.buffered -= this.byteLength(data)
    if (this.buffered === 0) this.stream._duplexState &= READ_NOT_QUEUED
    return data
  }

  unshift(data) {
    const pending = [this.map !== null ? this.map(data) : data]
    while (this.buffered > 0) pending.push(this.shift())

    for (let i = 0; i < pending.length - 1; i++) {
      const data = pending[i]
      this.buffered += this.byteLength(data)
      this.queue.push(data)
    }

    this.push(pending[pending.length - 1])
  }

  read() {
    const stream = this.stream

    if ((stream._duplexState & READ_STATUS) === READ_QUEUED) {
      const data = this.shift()
      if (this.pipeTo !== null && this.pipeTo.write(data) === false)
        stream._duplexState &= READ_PIPE_NOT_DRAINED
      if ((stream._duplexState & READ_EMIT_DATA) !== 0) stream.emit('data', data)
      return data
    }

    if (this.readAhead === false) {
      stream._duplexState |= READ_READ_AHEAD
      this.updateNextTick()
    }

    return null
  }

  drain() {
    const stream = this.stream

    while (
      (stream._duplexState & READ_STATUS) === READ_QUEUED &&
      (stream._duplexState & READ_FLOWING) !== 0
    ) {
      const data = this.shift()
      if (this.pipeTo !== null && this.pipeTo.write(data) === false)
        stream._duplexState &= READ_PIPE_NOT_DRAINED
      if ((stream._duplexState & READ_EMIT_DATA) !== 0) stream.emit('data', data)
    }
  }

  update() {
    const stream = this.stream

    stream._duplexState |= READ_UPDATING

    do {
      this.drain()

      while (
        this.buffered < this.highWaterMark &&
        (stream._duplexState & SHOULD_NOT_READ) === READ_READ_AHEAD
      ) {
        stream._duplexState |= READ_ACTIVE_AND_NEEDS_PUSH
        stream._read(this.afterRead)
        this.drain()
      }

      if ((stream._duplexState & READ_READABLE_STATUS) === READ_EMIT_READABLE_AND_QUEUED) {
        stream._duplexState |= READ_EMITTED_READABLE
        stream.emit('readable')
      }

      if ((stream._duplexState & READ_PRIMARY_AND_ACTIVE) === 0) this.updateNonPrimary()
    } while (this.continueUpdate() === true)

    stream._duplexState &= READ_NOT_UPDATING
  }

  updateNonPrimary() {
    const stream = this.stream

    if ((stream._duplexState & READ_ENDING_STATUS) === READ_ENDING) {
      stream._duplexState = (stream._duplexState | READ_DONE) & READ_NOT_ENDING
      stream.emit('end')
      if ((stream._duplexState & AUTO_DESTROY) === DONE) stream._duplexState |= DESTROYING
      if (this.pipeTo !== null) this.pipeTo.end()
    }

    if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
      if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
        stream._duplexState |= ACTIVE
        stream._destroy(afterDestroy.bind(this))
      }
      return
    }

    if ((stream._duplexState & IS_OPENING) === OPENING) {
      stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING
      stream._open(afterOpen.bind(this))
    }
  }

  continueUpdate() {
    if ((this.stream._duplexState & READ_NEXT_TICK) === 0) return false
    this.stream._duplexState &= READ_NOT_NEXT_TICK
    return true
  }

  updateCallback() {
    if ((this.stream._duplexState & READ_UPDATE_SYNC_STATUS) === READ_PRIMARY) this.update()
    else this.updateNextTick()
  }

  updateNextTickIfOpen() {
    if ((this.stream._duplexState & READ_NEXT_TICK_OR_OPENING) !== 0) return
    this.stream._duplexState |= READ_NEXT_TICK
    if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick)
  }

  updateNextTick() {
    if ((this.stream._duplexState & READ_NEXT_TICK) !== 0) return
    this.stream._duplexState |= READ_NEXT_TICK
    if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick)
  }
}

class TransformState {
  constructor(stream) {
    this.data = null
    this.afterTransform = afterTransform.bind(stream)
    this.afterFinal = null
  }
}

class Pipeline {
  constructor(src, dst, cb) {
    this.from = src
    this.to = dst
    this.afterPipe = cb
    this.error = null
    this.pipeToFinished = false
  }

  finished() {
    this.pipeToFinished = true
  }

  done(stream, err) {
    if (err) this.error = err

    if (stream === this.to) {
      this.to = null

      if (this.from !== null) {
        if ((this.from._duplexState & READ_DONE) === 0 || !this.pipeToFinished) {
          this.from.destroy(this.error || new Error('Writable stream closed prematurely'))
        }
        return
      }
    }

    if (stream === this.from) {
      this.from = null

      if (this.to !== null) {
        if ((stream._duplexState & READ_DONE) === 0) {
          this.to.destroy(this.error || new Error('Readable stream closed before ending'))
        }
        return
      }
    }

    if (this.afterPipe !== null) this.afterPipe(this.error)
    this.to = this.from = this.afterPipe = null
  }
}

function afterDrain() {
  this.stream._duplexState |= READ_PIPE_DRAINED
  this.updateCallback()
}

function afterFinal(err) {
  const stream = this.stream
  if (err) stream.destroy(err)
  if ((stream._duplexState & DESTROY_STATUS) === 0) {
    stream._duplexState |= WRITE_DONE
    stream.emit('finish')
  }
  if ((stream._duplexState & AUTO_DESTROY) === DONE) {
    stream._duplexState |= DESTROYING
  }

  stream._duplexState &= WRITE_NOT_FINISHING

  // no need to wait the extra tick here, so we short circuit that
  if ((stream._duplexState & WRITE_UPDATING) === 0) this.update()
  else this.updateNextTick()
}

function afterDestroy(err) {
  const stream = this.stream

  if (!err && this.error !== STREAM_DESTROYED) err = this.error
  if (err) stream.emit('error', err)
  stream._duplexState |= DESTROYED
  stream.emit('close')

  const rs = stream._readableState
  const ws = stream._writableState

  if (rs !== null && rs.pipeline !== null) rs.pipeline.done(stream, err)

  if (ws !== null) {
    while (ws.drains !== null && ws.drains.length > 0) ws.drains.shift().resolve(false)
    if (ws.pipeline !== null) ws.pipeline.done(stream, err)
  }
}

function afterWrite(err) {
  const stream = this.stream

  if (err) stream.destroy(err)
  stream._duplexState &= WRITE_NOT_ACTIVE

  if (this.drains !== null) tickDrains(this.drains)

  if ((stream._duplexState & WRITE_DRAIN_STATUS) === WRITE_UNDRAINED) {
    stream._duplexState &= WRITE_DRAINED
    if ((stream._duplexState & WRITE_EMIT_DRAIN) === WRITE_EMIT_DRAIN) {
      stream.emit('drain')
    }
  }

  this.updateCallback()
}

function afterRead(err) {
  if (err) this.stream.destroy(err)
  this.stream._duplexState &= READ_NOT_ACTIVE
  if (this.readAhead === false && (this.stream._duplexState & READ_RESUMED) === 0)
    this.stream._duplexState &= READ_NO_READ_AHEAD
  this.updateCallback()
}

function updateReadNT() {
  if ((this.stream._duplexState & READ_UPDATING) === 0) {
    this.stream._duplexState &= READ_NOT_NEXT_TICK
    this.update()
  }
}

function updateWriteNT() {
  if ((this.stream._duplexState & WRITE_UPDATING) === 0) {
    this.stream._duplexState &= WRITE_NOT_NEXT_TICK
    this.update()
  }
}

function tickDrains(drains) {
  for (let i = 0; i < drains.length; i++) {
    // drains.writes are monotonic, so if one is 0 its always the first one
    if (--drains[i].writes === 0) {
      drains.shift().resolve(true)
      i--
    }
  }
}

function afterOpen(err) {
  const stream = this.stream

  if (err) stream.destroy(err)

  if ((stream._duplexState & DESTROYING) === 0) {
    if ((stream._duplexState & READ_PRIMARY_STATUS) === 0) stream._duplexState |= READ_PRIMARY
    if ((stream._duplexState & WRITE_PRIMARY_STATUS) === 0) stream._duplexState |= WRITE_PRIMARY
    stream.emit('open')
  }

  stream._duplexState &= NOT_ACTIVE

  if (stream._writableState !== null) {
    stream._writableState.updateCallback()
  }

  if (stream._readableState !== null) {
    stream._readableState.updateCallback()
  }
}

function afterTransform(err, data) {
  if (data !== undefined && data !== null) this.push(data)
  this._writableState.afterWrite(err)
}

function newListener(name) {
  if (this._readableState !== null) {
    if (name === 'data') {
      this._duplexState |= READ_EMIT_DATA | READ_RESUMED_READ_AHEAD
      this._readableState.updateNextTick()
    }
    if (name === 'readable') {
      this._duplexState |= READ_EMIT_READABLE
      this._readableState.updateNextTick()
    }
  }

  if (this._writableState !== null) {
    if (name === 'drain') {
      this._duplexState |= WRITE_EMIT_DRAIN
      this._writableState.updateNextTick()
    }
  }
}

class Stream extends EventEmitter {
  constructor(opts) {
    super()

    this._duplexState = 0
    this._readableState = null
    this._writableState = null

    if (opts) {
      if (opts.open) this._open = opts.open
      if (opts.destroy) this._destroy = opts.destroy
      if (opts.predestroy) this._predestroy = opts.predestroy
      if (opts.signal) {
        opts.signal.addEventListener('abort', abort.bind(this))
      }
    }

    this.on('newListener', newListener)
  }

  _open(cb) {
    cb(null)
  }

  _destroy(cb) {
    cb(null)
  }

  _predestroy() {
    // does nothing
  }

  get readable() {
    return this._readableState !== null ? true : undefined
  }

  get writable() {
    return this._writableState !== null ? true : undefined
  }

  get destroyed() {
    return (this._duplexState & DESTROYED) !== 0
  }

  get destroying() {
    return (this._duplexState & DESTROY_STATUS) !== 0
  }

  destroy(err) {
    if ((this._duplexState & DESTROY_STATUS) === 0) {
      if (!err) err = STREAM_DESTROYED
      this._duplexState = (this._duplexState | DESTROYING) & NON_PRIMARY

      if (this._readableState !== null) {
        this._readableState.highWaterMark = 0
        this._readableState.error = err
      }
      if (this._writableState !== null) {
        this._writableState.highWaterMark = 0
        this._writableState.error = err
      }

      this._duplexState |= PREDESTROYING
      this._predestroy()
      this._duplexState &= NOT_PREDESTROYING

      if (this._readableState !== null) this._readableState.updateNextTick()
      if (this._writableState !== null) this._writableState.updateNextTick()
    }
  }
}

class Readable extends Stream {
  constructor(opts) {
    super(opts)

    this._duplexState |= OPENING | WRITE_DONE | READ_READ_AHEAD
    this._readableState = new ReadableState(this, opts)

    if (opts) {
      if (this._readableState.readAhead === false) this._duplexState &= READ_NO_READ_AHEAD
      if (opts.read) this._read = opts.read
      if (opts.eagerOpen) this._readableState.updateNextTick()
      if (opts.encoding) this.setEncoding(opts.encoding)
    }
  }

  setEncoding(encoding) {
    const dec = new TextDecoder(encoding)
    const map = this._readableState.map || echo
    this._readableState.map = mapOrSkip
    return this

    function mapOrSkip(data) {
      const next = dec.push(data)
      return next === '' && (data.byteLength !== 0 || dec.remaining > 0) ? null : map(next)
    }
  }

  _read(cb) {
    cb(null)
  }

  pipe(dest, cb) {
    this._readableState.updateNextTick()
    this._readableState.pipe(dest, cb)
    return dest
  }

  read() {
    this._readableState.updateNextTick()
    return this._readableState.read()
  }

  push(data) {
    this._readableState.updateNextTickIfOpen()
    return this._readableState.push(data)
  }

  unshift(data) {
    this._readableState.updateNextTickIfOpen()
    return this._readableState.unshift(data)
  }

  resume() {
    this._duplexState |= READ_RESUMED_READ_AHEAD
    this._readableState.updateNextTick()
    return this
  }

  pause() {
    this._duplexState &=
      this._readableState.readAhead === false ? READ_PAUSED_NO_READ_AHEAD : READ_PAUSED
    return this
  }

  static _fromAsyncIterator(ite, opts) {
    let destroy

    const rs = new Readable({
      ...opts,
      read(cb) {
        ite.next().then(push).then(cb.bind(null, null)).catch(cb)
      },
      predestroy() {
        destroy = ite.return()
      },
      destroy(cb) {
        if (!destroy) return cb(null)
        destroy.then(cb.bind(null, null)).catch(cb)
      }
    })

    return rs

    function push(data) {
      if (data.done) rs.push(null)
      else rs.push(data.value)
    }
  }

  static from(data, opts) {
    if (isReadStreamx(data)) return data
    if (data[asyncIterator]) return this._fromAsyncIterator(data[asyncIterator](), opts)
    if (!Array.isArray(data)) data = data === undefined ? [] : [data]

    let i = 0
    return new Readable({
      ...opts,
      read(cb) {
        this.push(i === data.length ? null : data[i++])
        cb(null)
      }
    })
  }

  static isBackpressured(rs) {
    return (
      (rs._duplexState & READ_BACKPRESSURE_STATUS) !== 0 ||
      rs._readableState.buffered >= rs._readableState.highWaterMark
    )
  }

  static isPaused(rs) {
    return (rs._duplexState & READ_RESUMED) === 0
  }

  [asyncIterator]() {
    const stream = this

    let error = null
    let promiseResolve = null
    let promiseReject = null

    this.on('error', (err) => {
      error = err
    })
    this.on('readable', onreadable)
    this.on('close', onclose)

    return {
      [asyncIterator]() {
        return this
      },
      next() {
        return new Promise(function (resolve, reject) {
          promiseResolve = resolve
          promiseReject = reject
          const data = stream.read()
          if (data !== null) ondata(data)
          else if ((stream._duplexState & DESTROYED) !== 0) ondata(null)
        })
      },
      return() {
        return destroy(null)
      },
      throw(err) {
        return destroy(err)
      }
    }

    function onreadable() {
      if (promiseResolve !== null) ondata(stream.read())
    }

    function onclose() {
      if (promiseResolve !== null) ondata(null)
    }

    function ondata(data) {
      if (promiseReject === null) return
      if (error) promiseReject(error)
      else if (data === null && (stream._duplexState & READ_DONE) === 0)
        promiseReject(STREAM_DESTROYED)
      else promiseResolve({ value: data, done: data === null })
      promiseReject = promiseResolve = null
    }

    function destroy(err) {
      stream.destroy(err)
      return new Promise((resolve, reject) => {
        if (stream._duplexState & DESTROYED) return resolve({ value: undefined, done: true })
        stream.once('close', function () {
          if (err) reject(err)
          else resolve({ value: undefined, done: true })
        })
      })
    }
  }
}

class Writable extends Stream {
  constructor(opts) {
    super(opts)

    this._duplexState |= OPENING | READ_DONE
    this._writableState = new WritableState(this, opts)

    if (opts) {
      if (opts.writev) this._writev = opts.writev
      if (opts.write) this._write = opts.write
      if (opts.final) this._final = opts.final
      if (opts.eagerOpen) this._writableState.updateNextTick()
    }
  }

  cork() {
    this._duplexState |= WRITE_CORKED
  }

  uncork() {
    this._duplexState &= WRITE_NOT_CORKED
    this._writableState.updateNextTick()
  }

  _writev(batch, cb) {
    cb(null)
  }

  _write(data, cb) {
    this._writableState.autoBatch(data, cb)
  }

  _final(cb) {
    cb(null)
  }

  static isBackpressured(ws) {
    return (ws._duplexState & WRITE_BACKPRESSURE_STATUS) !== 0
  }

  static drained(ws) {
    if (ws.destroyed) return Promise.resolve(false)
    const state = ws._writableState
    const pending = isWritev(ws) ? Math.min(1, state.queue.length) : state.queue.length
    const writes = pending + (ws._duplexState & WRITE_WRITING ? 1 : 0)
    if (writes === 0) return Promise.resolve(true)
    if (state.drains === null) state.drains = []
    return new Promise((resolve) => {
      state.drains.push({ writes, resolve })
    })
  }

  write(data) {
    this._writableState.updateNextTick()
    return this._writableState.push(data)
  }

  end(data) {
    this._writableState.updateNextTick()
    this._writableState.end(data)
    return this
  }
}

class Duplex extends Readable {
  // and Writable
  constructor(opts) {
    super(opts)

    this._duplexState = OPENING | (this._duplexState & READ_READ_AHEAD)
    this._writableState = new WritableState(this, opts)

    if (opts) {
      if (opts.writev) this._writev = opts.writev
      if (opts.write) this._write = opts.write
      if (opts.final) this._final = opts.final
    }
  }

  cork() {
    this._duplexState |= WRITE_CORKED
  }

  uncork() {
    this._duplexState &= WRITE_NOT_CORKED
    this._writableState.updateNextTick()
  }

  _writev(batch, cb) {
    cb(null)
  }

  _write(data, cb) {
    this._writableState.autoBatch(data, cb)
  }

  _final(cb) {
    cb(null)
  }

  write(data) {
    this._writableState.updateNextTick()
    return this._writableState.push(data)
  }

  end(data) {
    this._writableState.updateNextTick()
    this._writableState.end(data)
    return this
  }
}

class Transform extends Duplex {
  constructor(opts) {
    super(opts)
    this._transformState = new TransformState(this)

    if (opts) {
      if (opts.transform) this._transform = opts.transform
      if (opts.flush) this._flush = opts.flush
    }
  }

  _write(data, cb) {
    if (this._readableState.buffered >= this._readableState.highWaterMark) {
      this._transformState.data = data
    } else {
      this._transform(data, this._transformState.afterTransform)
    }
  }

  _read(cb) {
    if (this._transformState.data !== null) {
      const data = this._transformState.data
      this._transformState.data = null
      cb(null)
      this._transform(data, this._transformState.afterTransform)
    } else {
      cb(null)
    }
  }

  destroy(err) {
    super.destroy(err)
    if (this._transformState.data !== null) {
      this._transformState.data = null
      this._transformState.afterTransform()
    }
  }

  _transform(data, cb) {
    cb(null, data)
  }

  _flush(cb) {
    cb(null)
  }

  _final(cb) {
    this._transformState.afterFinal = cb
    this._flush(transformAfterFlush.bind(this))
  }
}

class PassThrough extends Transform {}

function transformAfterFlush(err, data) {
  const cb = this._transformState.afterFinal
  if (err) return cb(err)
  if (data !== null && data !== undefined) this.push(data)
  this.push(null)
  cb(null)
}

function pipelinePromise(...streams) {
  return new Promise((resolve, reject) => {
    return pipeline(...streams, (err) => {
      if (err) return reject(err)
      resolve()
    })
  })
}

function pipeline(stream, ...streams) {
  const all = Array.isArray(stream) ? [...stream, ...streams] : [stream, ...streams]
  const done = all.length && typeof all[all.length - 1] === 'function' ? all.pop() : null

  if (all.length < 2) throw new Error('Pipeline requires at least 2 streams')

  let src = all[0]
  let dest = null
  let error = null

  for (let i = 1; i < all.length; i++) {
    dest = all[i]

    if (isStreamx(src)) {
      src.pipe(dest, onerror)
    } else {
      errorHandle(src, true, i > 1, onerror)
      src.pipe(dest)
    }

    src = dest
  }

  if (done) {
    let fin = false

    const autoDestroy =
      isStreamx(dest) || !!(dest._writableState && dest._writableState.autoDestroy)

    dest.on('error', (err) => {
      if (error === null) error = err
    })

    dest.on('finish', () => {
      fin = true
      if (!autoDestroy) done(error)
    })

    if (autoDestroy) {
      dest.on('close', () => done(error || (fin ? null : PREMATURE_CLOSE)))
    }
  }

  return dest

  function errorHandle(s, rd, wr, onerror) {
    s.on('error', onerror)
    s.on('close', onclose)

    function onclose() {
      if (rd && s._readableState && !s._readableState.ended) return onerror(PREMATURE_CLOSE)
      if (wr && s._writableState && !s._writableState.ended) return onerror(PREMATURE_CLOSE)
    }
  }

  function onerror(err) {
    if (!err || error) return
    error = err

    for (const s of all) {
      s.destroy(err)
    }
  }
}

function echo(s) {
  return s
}

function isStream(stream) {
  return !!stream._readableState || !!stream._writableState
}

function isStreamx(stream) {
  return typeof stream._duplexState === 'number' && isStream(stream)
}

function isEnding(stream) {
  return !!stream._readableState && stream._readableState.ending
}

function isEnded(stream) {
  return !!stream._readableState && stream._readableState.ended
}

function isFinishing(stream) {
  return !!stream._writableState && stream._writableState.ending
}

function isFinished(stream) {
  return !!stream._writableState && stream._writableState.ended
}

function getStreamError(stream, opts = {}) {
  const err =
    (stream._readableState && stream._readableState.error) ||
    (stream._writableState && stream._writableState.error)

  // avoid implicit errors by default
  return !opts.all && err === STREAM_DESTROYED ? null : err
}

function isReadStreamx(stream) {
  return isStreamx(stream) && stream.readable
}

function isDisturbed(stream) {
  return (
    (stream._duplexState & OPENING) !== OPENING ||
    (stream._duplexState & DESTROYING) === DESTROYING ||
    (stream._duplexState & ACTIVE_OR_TICKING) !== 0
  )
}

function isTypedArray(data) {
  return typeof data === 'object' && data !== null && typeof data.byteLength === 'number'
}

function defaultByteLength(data) {
  return isTypedArray(data) ? data.byteLength : 1024
}

function noop() {}

function abort() {
  this.destroy(new Error('Stream aborted.'))
}

function isWritev(s) {
  return s._writev !== Writable.prototype._writev && s._writev !== Duplex.prototype._writev
}

module.exports = {
  pipeline,
  pipelinePromise,
  isStream,
  isStreamx,
  isEnding,
  isEnded,
  isFinishing,
  isFinished,
  isDisturbed,
  getStreamError,
  Stream,
  Writable,
  Readable,
  Duplex,
  Transform,
  // Export PassThrough for compatibility with Node.js core's stream module
  PassThrough
}
{
  "name": "streamx",
  "version": "2.25.0",
  "description": "An iteration of the Node.js core streams with a series of improvements",
  "main": "index.js",
  "dependencies": {
    "events-universal": "^1.0.0",
    "fast-fifo": "^1.3.2",
    "text-decoder": "^1.1.0"
  },
  "devDependencies": {
    "b4a": "^1.6.6",
    "brittle": "^3.1.1",
    "end-of-stream": "^1.4.4",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "files": [
    "index.js"
  ],
  "scripts": {
    "format": "prettier --write .",
    "test": "prettier --check . && node test/all.js",
    "test:bare": "bare test/all.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/streamx.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/streamx/issues"
  },
  "homepage": "https://github.com/mafintosh/streamx"
}
const { Readable } = require('streamx')

module.exports = function (s, forks = 2) {
  const streams = new Array(forks)
  const status = new Array(forks).fill(true)

  let ended = false

  for (let i = 0; i < forks; i++) {
    streams[i] = new Readable({
      read (cb) {
        const check = !status[i]
        status[i] = true
        if (check && allReadable()) s.resume()
        cb(null)
      }
    })
  }

  s.on('end', function () {
    ended = true
    for (const stream of streams) stream.push(null)
  })

  s.on('error', function (err) {
    for (const stream of streams) stream.destroy(err)
  })

  s.on('close', function () {
    if (ended) return
    for (const stream of streams) stream.destroy()
  })

  s.on('data', function (data) {
    let needsPause = false
    for (let i = 0; i < streams.length; i++) {
      if (!(status[i] = streams[i].push(data))) {
        needsPause = true
      }
    }
    if (needsPause) s.pause()
  })

  return streams

  function allReadable () {
    for (let j = 0; j < status.length; j++) {
      if (!status[j]) return false
    }
    return true
  }
}
{
  "name": "teex",
  "version": "1.0.1",
  "description": "Turn a readable stream into multiple readable streamx streams",
  "main": "index.js",
  "dependencies": {
    "streamx": "^2.12.5"
  },
  "devDependencies": {
    "standard": "^14.3.4",
    "tape": "^5.0.1"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/teex.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/teex/issues"
  },
  "homepage": "https://github.com/mafintosh/teex"
}
const PassThroughDecoder = require('./lib/pass-through-decoder')
const UTF8Decoder = require('./lib/utf8-decoder')

module.exports = class TextDecoder {
  constructor(encoding = 'utf8') {
    this.encoding = normalizeEncoding(encoding)

    switch (this.encoding) {
      case 'utf8':
        this.decoder = new UTF8Decoder()
        break
      case 'utf16le':
      case 'base64':
        throw new Error('Unsupported encoding: ' + this.encoding)
      default:
        this.decoder = new PassThroughDecoder(this.encoding)
    }
  }

  get remaining() {
    return this.decoder.remaining
  }

  push(data) {
    if (typeof data === 'string') return data
    return this.decoder.decode(data)
  }

  // For Node.js compatibility
  write(data) {
    return this.push(data)
  }

  end(data) {
    let result = ''
    if (data) result = this.push(data)
    result += this.decoder.flush()
    return result
  }
}

function normalizeEncoding(encoding) {
  encoding = encoding.toLowerCase()

  switch (encoding) {
    case 'utf8':
    case 'utf-8':
      return 'utf8'
    case 'ucs2':
    case 'ucs-2':
    case 'utf16le':
    case 'utf-16le':
      return 'utf16le'
    case 'latin1':
    case 'binary':
      return 'latin1'
    case 'base64':
    case 'ascii':
    case 'hex':
      return encoding
    default:
      throw new Error('Unknown encoding: ' + encoding)
  }
}
const b4a = require('b4a')

module.exports = class PassThroughDecoder {
  constructor(encoding) {
    this.encoding = encoding
  }

  get remaining() {
    return 0
  }

  decode(data) {
    return b4a.toString(data, this.encoding)
  }

  flush() {
    return ''
  }
}
const b4a = require('b4a')

/**
 * https://encoding.spec.whatwg.org/#utf-8-decoder
 */
module.exports = class UTF8Decoder {
  constructor() {
    this._reset()
  }

  get remaining() {
    return this.bytesSeen
  }

  decode(data) {
    if (data.byteLength === 0) return ''

    if (this.bytesNeeded === 0 && trailingIncomplete(data, 0) === 0) {
      this.bytesSeen = trailingBytesSeen(data)
      return b4a.toString(data, 'utf8')
    }

    let result = ''
    let start = 0

    if (this.bytesNeeded > 0) {
      while (start < data.byteLength) {
        const byte = data[start]

        if (byte < this.lowerBoundary || byte > this.upperBoundary) {
          result += '\ufffd'
          this._reset()
          break
        }

        this.lowerBoundary = 0x80
        this.upperBoundary = 0xbf
        this.codePoint = (this.codePoint << 6) | (byte & 0x3f)
        this.bytesSeen++
        start++

        if (this.bytesSeen === this.bytesNeeded) {
          result += String.fromCodePoint(this.codePoint)
          this._reset()
          break
        }
      }

      if (this.bytesNeeded > 0) return result
    }

    const trailing = trailingIncomplete(data, start)
    const end = data.byteLength - trailing

    if (end > start) result += b4a.toString(data, 'utf8', start, end)

    for (let i = end; i < data.byteLength; i++) {
      const byte = data[i]

      if (this.bytesNeeded === 0) {
        if (byte <= 0x7f) {
          this.bytesSeen = 0
          result += String.fromCharCode(byte)
        } else if (byte >= 0xc2 && byte <= 0xdf) {
          this.bytesNeeded = 2
          this.bytesSeen = 1
          this.codePoint = byte & 0x1f
        } else if (byte >= 0xe0 && byte <= 0xef) {
          if (byte === 0xe0) this.lowerBoundary = 0xa0
          else if (byte === 0xed) this.upperBoundary = 0x9f
          this.bytesNeeded = 3
          this.bytesSeen = 1
          this.codePoint = byte & 0xf
        } else if (byte >= 0xf0 && byte <= 0xf4) {
          if (byte === 0xf0) this.lowerBoundary = 0x90
          else if (byte === 0xf4) this.upperBoundary = 0x8f
          this.bytesNeeded = 4
          this.bytesSeen = 1
          this.codePoint = byte & 0x7
        } else {
          this.bytesSeen = 1
          result += '\ufffd'
        }

        continue
      }

      if (byte < this.lowerBoundary || byte > this.upperBoundary) {
        result += '\ufffd'
        i--
        this._reset()

        continue
      }

      this.lowerBoundary = 0x80
      this.upperBoundary = 0xbf

      this.codePoint = (this.codePoint << 6) | (byte & 0x3f)
      this.bytesSeen++

      if (this.bytesSeen === this.bytesNeeded) {
        result += String.fromCodePoint(this.codePoint)
        this._reset()
      }
    }

    return result
  }

  flush() {
    const result = this.bytesNeeded > 0 ? '\ufffd' : ''
    this._reset()
    return result
  }

  _reset() {
    this.codePoint = 0
    this.bytesNeeded = 0
    this.bytesSeen = 0
    this.lowerBoundary = 0x80
    this.upperBoundary = 0xbf
  }
}

function trailingIncomplete(data, start) {
  const len = data.byteLength
  if (len <= start) return 0

  const limit = Math.max(start, len - 4)

  let i = len - 1
  while (i > limit && (data[i] & 0xc0) === 0x80) i--

  if (i < start) return 0

  const byte = data[i]

  let needed
  if (byte <= 0x7f) return 0
  if (byte >= 0xc2 && byte <= 0xdf) needed = 2
  else if (byte >= 0xe0 && byte <= 0xef) needed = 3
  else if (byte >= 0xf0 && byte <= 0xf4) needed = 4
  else return 0

  const available = len - i
  return available < needed ? available : 0
}

function trailingBytesSeen(data) {
  const len = data.byteLength
  if (len === 0) return 0

  const last = data[len - 1]

  if (last <= 0x7f) return 0
  if ((last & 0xc0) !== 0x80) return 1

  const limit = Math.max(0, len - 4)

  let i = len - 2
  while (i >= limit && (data[i] & 0xc0) === 0x80) i--

  if (i < 0) return 1

  const first = data[i]

  let needed
  if (first >= 0xc2 && first <= 0xdf) needed = 2
  else if (first >= 0xe0 && first <= 0xef) needed = 3
  else if (first >= 0xf0 && first <= 0xf4) needed = 4
  else return 1

  if (len - i !== needed) return 1

  if (needed >= 3) {
    const second = data[i + 1]
    if (first === 0xe0 && second < 0xa0) return 1
    if (first === 0xed && second > 0x9f) return 1
    if (first === 0xf0 && second < 0x90) return 1
    if (first === 0xf4 && second > 0x8f) return 1
  }

  return 0
}
{
  "name": "text-decoder",
  "version": "1.2.7",
  "description": "Streaming text decoder that preserves multibyte Unicode characters",
  "exports": {
    "./package": "./package.json",
    ".": "./index.js"
  },
  "files": [
    "index.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/text-decoder.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/text-decoder/issues"
  },
  "homepage": "https://github.com/holepunchto/text-decoder#readme",
  "dependencies": {
    "b4a": "^1.6.4"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  }
}
module.exports = class TimeOrderedSet {
  constructor () {
    this.oldest = null
    this.latest = null
    this.length = 0
  }

  has (node) {
    return !!(node.next || node.prev) || node === this.oldest
  }

  add (node) {
    if (this.has(node)) this.remove(node)

    if (!this.latest && !this.oldest) {
      this.latest = this.oldest = node
      node.prev = node.next = null
    } else {
      this.latest.next = node
      node.prev = this.latest
      node.next = null
      this.latest = node
    }

    this.length++

    return node
  }

  remove (node) {
    if (!this.has(node)) return node

    if (this.oldest !== node && this.latest !== node) {
      node.prev.next = node.next
      node.next.prev = node.prev
    } else {
      if (this.oldest === node) {
        this.oldest = node.next
        if (this.oldest) this.oldest.prev = null
      }
      if (this.latest === node) {
        this.latest = node.prev
        if (this.latest) this.latest.next = null
      }
    }

    node.next = node.prev = null
    this.length--

    return node
  }

  toArray ({ limit = Infinity, reverse = false } = {}) {
    const list = []

    if (reverse) {
      let node = this.latest
      while (node && limit--) {
        list.push(node)
        node = node.prev
      }
    } else {
      let node = this.oldest
      while (node && limit--) {
        list.push(node)
        node = node.next
      }
    }

    return list
  }
}
{
  "name": "time-ordered-set",
  "version": "2.0.1",
  "description": "Efficiently maintain a set of nodes ordered by the time they were added to the set",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "devDependencies": {
    "brittle": "^3.0.0",
    "standard": "^17.1.2"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/time-ordered-set.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/time-ordered-set/issues"
  },
  "homepage": "https://github.com/mafintosh/time-ordered-set"
}
module.exports = class TimerBrowser {
  constructor (ms, fn, ctx = null, interval = false) {
    this.ms = ms
    this.ontimeout = fn
    this.context = ctx || null
    this.interval = interval
    this.done = false

    this._timer = interval
      ? setInterval(callInterval, ms, this)
      : setTimeout(callTimeout, ms, this)
  }

  unref () {}

  ref () {}

  refresh () {
    if (this.done) return

    if (this.interval) {
      clearInterval(this._timer)
      this._timer = setInterval(callInterval, this.ms, this)
    } else {
      clearTimeout(this._timer)
      this._timer = setTimeout(callTimeout, this.ms, this)
    }
  }

  destroy () {
    this.done = true
    this.ontimeout = null

    if (this.interval) clearInterval(this._timer)
    else clearTimeout(this._timer)
  }

  static once (ms, fn, ctx) {
    return new this(ms, fn, ctx, false)
  }

  static on (ms, fn, ctx) {
    return new this(ms, fn, ctx, true)
  }
}

function callTimeout (self) {
  self.done = true
  self.ontimeout.call(self.context)
}

function callInterval (self) {
  self.ontimeout.call(self.context)
}
module.exports = isNode()
  ? require('./node')
  : require('./browser')

function isNode () {
  const to = setTimeout(function () {}, 1000)
  clearTimeout(to)
  return !!to.refresh
}
module.exports = class Timer {
  constructor (ms, fn, ctx = null, interval = false) {
    this.ms = ms
    this.ontimeout = fn
    this.context = ctx
    this.interval = interval
    this.done = false

    this._timer = interval
      ? setInterval(callInterval, ms, this)
      : setTimeout(callTimeout, ms, this)
  }

  unref () {
    this._timer.unref()
  }

  ref () {
    this._timer.ref()
  }

  refresh () {
    if (this.done !== true) this._timer.refresh()
  }

  destroy () {
    this.done = true
    this.ontimeout = null
    if (this.interval) clearInterval(this._timer)
    else clearTimeout(this._timer)
  }

  static once (ms, fn, ctx) {
    return new this(ms, fn, ctx, false)
  }

  static on (ms, fn, ctx) {
    return new this(ms, fn, ctx, true)
  }
}

function callTimeout (self) {
  self.done = true
  self.ontimeout.call(self.context)
}

function callInterval (self) {
  self.ontimeout.call(self.context)
}
{
  "name": "timeout-refresh",
  "version": "2.0.1",
  "description": "Efficiently refresh a timer",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^16.0.4",
    "tape": "^5.5.2"
  },
  "browser": "./browser.js",
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/timeout-refresh.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/timeout-refresh/issues"
  },
  "homepage": "https://github.com/mafintosh/timeout-refresh"
}
require.addon = require('require-addon')

module.exports = require.addon('.', __filename)
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

const v4Seg = '(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])'
const v4Str = `(${v4Seg}[.]){3}${v4Seg}`
const IPv4Pattern = new RegExp(`^${v4Str}$`)

const v6Seg = '(?:[0-9a-fA-F]{1,4})'
const IPv6Pattern = new RegExp(
  '^(' +
    `(?:${v6Seg}:){7}(?:${v6Seg}|:)|` +
    `(?:${v6Seg}:){6}(?:${v4Str}|:${v6Seg}|:)|` +
    `(?:${v6Seg}:){5}(?::${v4Str}|(:${v6Seg}){1,2}|:)|` +
    `(?:${v6Seg}:){4}(?:(:${v6Seg}){0,1}:${v4Str}|(:${v6Seg}){1,3}|:)|` +
    `(?:${v6Seg}:){3}(?:(:${v6Seg}){0,2}:${v4Str}|(:${v6Seg}){1,4}|:)|` +
    `(?:${v6Seg}:){2}(?:(:${v6Seg}){0,3}:${v4Str}|(:${v6Seg}){1,5}|:)|` +
    `(?:${v6Seg}:){1}(?:(:${v6Seg}){0,4}:${v4Str}|(:${v6Seg}){1,6}|:)|` +
    `(?::((?::${v6Seg}){0,5}:${v4Str}|(?::${v6Seg}){1,7}|:))` +
    ')(%[0-9a-zA-Z-.:]{1,})?$'
)

const isIPv4 = (exports.isIPv4 = function isIPv4(host) {
  return IPv4Pattern.test(host)
})

const isIPv6 = (exports.isIPv6 = function isIPv6(host) {
  return IPv6Pattern.test(host)
})

exports.isIP = function isIP(host) {
  if (isIPv4(host)) return 4
  if (isIPv6(host)) return 6
  return 0
}
const events = require('events')
const b4a = require('b4a')
const binding = require('../binding')

module.exports = class NetworkInterfaces extends events.EventEmitter {
  constructor(udx) {
    super()

    this._handle = b4a.alloc(binding.sizeof_udx_napi_interface_event_t)
    this._watching = false
    this._destroying = null

    binding.udx_napi_interface_event_init(
      udx._handle,
      this._handle,
      this,
      this._onevent,
      this._onclose
    )

    this.interfaces = binding.udx_napi_interface_event_get_addrs(this._handle)
  }

  _onclose() {
    this.emit('close')
  }

  _onevent() {
    this.interfaces = binding.udx_napi_interface_event_get_addrs(this._handle)

    this.emit('change', this.interfaces)
  }

  watch() {
    if (this._watching) return this
    this._watching = true

    binding.udx_napi_interface_event_start(this._handle)

    return this
  }

  unwatch() {
    if (!this._watching) return this
    this._watching = false

    binding.udx_napi_interface_event_stop(this._handle)

    return this
  }

  async destroy() {
    if (this._destroying) return this._destroying
    this._destroying = events.once(this, 'close')

    binding.udx_napi_interface_event_close(this._handle)

    return this._destroying
  }

  [Symbol.iterator]() {
    return this.interfaces[Symbol.iterator]()
  }
}
const events = require('events')
const b4a = require('b4a')
const binding = require('../binding')
const ip = require('./ip')

module.exports = class UDXSocket extends events.EventEmitter {
  constructor(udx, opts = {}) {
    super()

    this.udx = udx

    this._handle = b4a.alloc(binding.sizeof_udx_napi_socket_t)
    this._inited = false
    this._host = null
    this._family = 0
    this._ipv6Only = opts.ipv6Only === true
    this._reuseAddress = opts.reuseAddress === true
    this._port = 0
    this._reqs = []
    this._free = []
    this._closing = null
    this._closed = false

    this._view64 = new BigUint64Array(
      this._handle.buffer,
      this._handle.byteOffset,
      this._handle.byteLength >> 3
    )

    this.streams = new Set()

    this.userData = null
  }

  get bound() {
    return this._port !== 0
  }

  get closing() {
    return this._closing !== null
  }

  get idle() {
    return this.streams.size === 0
  }

  get busy() {
    return this.streams.size > 0
  }

  get bytesTransmitted() {
    if (this._inited !== true) return 0
    return Number(this._view64[binding.offsetof_udx_socket_t_bytes_tx >> 3])
  }

  get packetsTransmitted() {
    if (this._inited !== true) return 0
    return Number(this._view64[binding.offsetof_udx_socket_t_packets_tx >> 3])
  }

  get bytesReceived() {
    if (this._inited !== true) return 0
    return Number(this._view64[binding.offsetof_udx_socket_t_bytes_rx >> 3])
  }

  get packetsReceived() {
    if (this._inited !== true) return 0
    return Number(this._view64[binding.offsetof_udx_socket_t_packets_rx >> 3])
  }

  get packetsDroppedByKernel() {
    if (this._inited !== true) return 0
    return Number(this._view64[binding.offsetof_udx_socket_t_packets_dropped_by_kernel >> 3])
  }

  toJSON() {
    return {
      bound: this.bound,
      closing: this.closing,
      streams: this.streams.size,
      address: this.address(),
      ipv6Only: this._ipv6Only,
      reuseAddress: this._reuseAddress,
      idle: this.idle,
      busy: this.busy
    }
  }

  _init() {
    if (this._inited) return

    binding.udx_napi_socket_init(
      this.udx._handle,
      this._handle,
      this,
      this._onsend,
      this._onmessage,
      this._onclose,
      this._reallocMessage
    )

    this._inited = true
  }

  _onsend(id, err) {
    const req = this._reqs[id]

    const onflush = req.onflush

    req.buffer = null
    req.onflush = null

    this._free.push(id)

    onflush(err >= 0)

    // gc the free list
    if (this._free.length >= 16 && this._free.length === this._reqs.length) {
      this._free = []
      this._reqs = []
    }
  }

  _onmessage(len, port, host, family) {
    this.emit('message', this.udx._consumeMessage(len), { host, family, port })
    return this.udx._buffer
  }

  _onclose() {
    this.emit('close')
  }

  _reallocMessage() {
    return this.udx._reallocMessage()
  }

  _onidle() {
    this.emit('idle')
  }

  _onbusy() {
    this.emit('busy')
  }

  _addStream(stream) {
    if (this.streams.has(stream)) return false
    this.streams.add(stream)
    if (this.streams.size === 1) this._onbusy()
    return true
  }

  _removeStream(stream) {
    if (!this.streams.has(stream)) return false
    this.streams.delete(stream)
    const closed = this._closeMaybe()
    if (this.idle && !closed) this._onidle()
    return true
  }

  address() {
    if (!this.bound) return null
    return { host: this._host, family: this._family, port: this._port }
  }

  bind(port, host) {
    if (this.bound) throw new Error('Already bound')
    if (this.closing) throw new Error('Socket is closed')

    if (!port) port = 0

    let flags = 0
    if (this._ipv6Only) flags |= binding.UV_UDP_IPV6ONLY
    if (this._reuseAddress) flags |= binding.UV_UDP_REUSEADDR

    let family

    if (host) {
      family = ip.isIP(host)
      if (!family) throw new Error(`${host} is not a valid IP address`)

      if (!this._inited) this._init()

      this._port = binding.udx_napi_socket_bind(this._handle, port, host, family, flags)
    } else {
      if (!this._inited) this._init()

      try {
        host = '::'
        family = 6
        this._port = binding.udx_napi_socket_bind(this._handle, port, host, family, flags)
      } catch {
        host = '0.0.0.0'
        family = 4
        this._port = binding.udx_napi_socket_bind(this._handle, port, host, family, flags)
      }
    }

    this._host = host
    this._family = family

    this.emit('listening')
  }

  async close() {
    if (this._closing) return this._closing
    this._closing = new Promise((resolve) => this.once('close', resolve))
    this._closeMaybe()
    return this._closing
  }

  _closeMaybe() {
    if (this._closed || this._closing === null) return this._closed

    if (!this._inited) {
      this._closed = true
      this.emit('close')
      return true
    }

    if (this.idle) {
      binding.udx_napi_socket_close(this._handle)
      this._closed = true
    }

    return this._closed
  }

  setTTL(ttl) {
    if (!this._inited) throw new Error('Socket not active')
    binding.udx_napi_socket_set_ttl(this._handle, ttl)
  }

  getRecvBufferSize() {
    if (!this._inited) throw new Error('Socket not active')
    return binding.udx_napi_socket_get_recv_buffer_size(this._handle)
  }

  setRecvBufferSize(size) {
    if (!this._inited) throw new Error('Socket not active')
    return binding.udx_napi_socket_set_recv_buffer_size(this._handle, size)
  }

  getSendBufferSize() {
    if (!this._inited) throw new Error('Socket not active')
    return binding.udx_napi_socket_get_send_buffer_size(this._handle)
  }

  setSendBufferSize(size) {
    if (!this._inited) throw new Error('Socket not active')
    return binding.udx_napi_socket_set_send_buffer_size(this._handle, size)
  }

  addMembership(group, ifaceAddress) {
    if (!this._inited) throw new Error('Socket not active')
    return binding.udx_napi_socket_set_membership(this._handle, group, ifaceAddress || '', true)
  }

  dropMembership(group, ifaceAddress) {
    if (!this._inited) throw new Error('Socket not active')
    return binding.udx_napi_socket_set_membership(this._handle, group, ifaceAddress || '', false)
  }

  async send(buffer, port, host, ttl) {
    if (this.closing) return false

    if (!host) host = '127.0.0.1'

    const family = ip.isIP(host)
    if (!family) throw new Error(`${host} is not a valid IP address`)

    if (!this.bound) this.bind(0)

    const id = this._allocSend()
    const req = this._reqs[id]

    req.buffer = buffer

    const promise = new Promise((resolve) => {
      req.onflush = resolve
    })

    binding.udx_napi_socket_send_ttl(
      this._handle,
      req.handle,
      id,
      buffer,
      port,
      host,
      family,
      ttl || 0
    )

    return promise
  }

  trySend(buffer, port, host, ttl) {
    if (this.closing) return

    if (!host) host = '127.0.0.1'

    const family = ip.isIP(host)
    if (!family) throw new Error(`${host} is not a valid IP address`)

    if (!this.bound) this.bind(0)

    const id = this._allocSend()
    const req = this._reqs[id]

    req.buffer = buffer
    req.onflush = noop

    binding.udx_napi_socket_send_ttl(
      this._handle,
      req.handle,
      id,
      buffer,
      port,
      host,
      family,
      ttl || 0
    )
  }

  _allocSend() {
    if (this._free.length > 0) return this._free.pop()
    const handle = b4a.allocUnsafe(binding.sizeof_udx_socket_send_t)
    return this._reqs.push({ handle, buffer: null, onflush: null }) - 1
  }
}

function noop() {}
const streamx = require('streamx')
const b4a = require('b4a')
const binding = require('../binding')
const ip = require('./ip')

const MAX_PACKET = 2048
const BUFFER_SIZE = 65536 + MAX_PACKET

module.exports = class UDXStream extends streamx.Duplex {
  constructor(udx, id, opts = {}) {
    super({ mapWritable: toBuffer, eagerOpen: true })

    this.udx = udx
    this.socket = null

    this._handle = b4a.alloc(binding.sizeof_udx_napi_stream_t)
    this._view = new Uint32Array(
      this._handle.buffer,
      this._handle.byteOffset,
      this._handle.byteLength >> 2
    )
    this._view16 = new Uint16Array(
      this._handle.buffer,
      this._handle.byteOffset,
      this._handle.byteLength >> 1
    )
    this._view64 = new BigUint64Array(
      this._handle.buffer,
      this._handle.byteOffset,
      this._handle.byteLength >> 3
    )

    this._wreqs = []
    this._wfree = []

    this._sreqs = []
    this._sfree = []
    this._closed = false

    this._flushing = 0
    this._flushes = []

    this._buffer = null
    this._reallocData()

    this._onwrite = null
    this._ondestroy = null
    this._firewall = opts.firewall || firewallAll

    this._remoteChanging = null
    this._previousSocket = null

    this.id = id
    this.remoteId = 0
    this.remoteHost = null
    this.remoteFamily = 0
    this.remotePort = 0

    this.userData = null

    binding.udx_napi_stream_init(
      this.udx._handle,
      this._handle,
      id,
      opts.framed ? 1 : 0,
      this,
      this._ondata,
      this._onend,
      this._ondrain,
      this._onack,
      this._onsend,
      this._onmessage,
      this._onclose,
      this._onfirewall,
      this._onremotechanged,
      this._reallocData,
      this._reallocMessage
    )

    if (opts.seq) binding.udx_napi_stream_set_seq(this._handle, opts.seq)

    binding.udx_napi_stream_recv_start(this._handle, this._buffer)
  }

  get connected() {
    return this.socket !== null
  }

  get mtu() {
    return this._view16[binding.offsetof_udx_stream_t_mtu >> 1]
  }

  get rtt() {
    return this._view[binding.offsetof_udx_stream_t_srtt >> 2]
  }

  get cwnd() {
    return this._view[binding.offsetof_udx_stream_t_cwnd >> 2]
  }

  get rtoCount() {
    return this._view16[binding.offsetof_udx_stream_t_rto_count >> 1]
  }

  get retransmits() {
    return this._view16[binding.offsetof_udx_stream_t_retransmit_count >> 1]
  }

  get fastRecoveries() {
    return this._view16[binding.offsetof_udx_stream_t_fast_recovery_count >> 1]
  }

  get inflight() {
    return this._view[binding.offsetof_udx_stream_t_inflight >> 2]
  }

  get bytesTransmitted() {
    return Number(this._view64[binding.offsetof_udx_stream_t_bytes_tx >> 3])
  }

  get packetsTransmitted() {
    return Number(this._view64[binding.offsetof_udx_stream_t_packets_tx >> 3])
  }

  get bytesReceived() {
    return Number(this._view64[binding.offsetof_udx_stream_t_bytes_rx >> 3])
  }

  get packetsReceived() {
    return Number(this._view64[binding.offsetof_udx_stream_t_packets_rx >> 3])
  }

  get localHost() {
    return this.socket ? this.socket.address().host : null
  }

  get localFamily() {
    return this.socket ? this.socket.address().family : 0
  }

  get localPort() {
    return this.socket ? this.socket.address().port : 0
  }

  setInteractive(bool) {
    if (!this._closed) return
    binding.udx_napi_stream_set_mode(this._handle, bool ? 0 : 1)
  }

  connect(socket, remoteId, port, host, opts = {}) {
    if (this._closed) return

    if (this.connected) throw new Error('Already connected')
    if (socket.closing) throw new Error('Socket is closed')

    if (typeof host === 'object') {
      opts = host
      host = null
    }

    if (!host) host = '127.0.0.1'

    const family = ip.isIP(host)
    if (!family) throw new Error(`${host} is not a valid IP address`)
    if (!(port > 0 && port < 65536)) throw new Error(`${port} is not a valid port`)

    if (!socket.bound) socket.bind(0)

    this.remoteId = remoteId
    this.remotePort = port
    this.remoteHost = host
    this.remoteFamily = family
    this.socket = socket

    if (opts.ack) binding.udx_napi_stream_set_ack(this._handle, opts.ack)

    binding.udx_napi_stream_connect(this._handle, socket._handle, remoteId, port, host, family)

    this.socket._addStream(this)

    this.emit('connect')
  }

  changeRemote(socket, remoteId, port, host) {
    if (this._remoteChanging) throw new Error('Remote already changing')

    if (!this.connected) throw new Error('Not yet connected')
    if (socket.closing) throw new Error('Socket is closed')

    if (this.socket.udx !== socket.udx) {
      throw new Error('Cannot change to a socket on another UDX instance')
    }

    if (!host) host = '127.0.0.1'

    const family = ip.isIP(host)
    if (!family) throw new Error(`${host} is not a valid IP address`)
    if (!(port > 0 && port < 65536)) throw new Error(`${port} is not a valid port`)

    if (this.socket !== socket) this._previousSocket = this.socket

    this.remoteId = remoteId
    this.remotePort = port
    this.remoteHost = host
    this.remoteFamily = family
    this.socket = socket

    this._remoteChanging = new Promise((resolve, reject) => {
      const onchanged = () => {
        this.off('close', onclose)
        resolve()
      }

      const onclose = () => {
        this.off('remote-changed', onchanged)
        reject(new Error('Stream is closed'))
      }

      this.once('remote-changed', onchanged).once('close', onclose)
    })

    binding.udx_napi_stream_change_remote(
      this._handle,
      socket._handle,
      remoteId,
      port,
      host,
      family
    )

    this.socket._addStream(this)

    return this._remoteChanging
  }

  relayTo(destination) {
    if (this._closed) return

    binding.udx_napi_stream_relay_to(this._handle, destination._handle)
  }

  async send(buffer) {
    if (!this.connected || this._closed) return false

    const id = this._allocSend()
    const req = this._sreqs[id]

    req.buffer = buffer

    const promise = new Promise((resolve) => {
      req.onflush = resolve
    })

    binding.udx_napi_stream_send(this._handle, req.handle, id, buffer)

    return promise
  }

  trySend(buffer) {
    if (!this.connected || this._closed) return

    const id = this._allocSend()
    const req = this._sreqs[id]

    req.buffer = buffer
    req.onflush = noop

    binding.udx_napi_stream_send(this._handle, req.handle, id, buffer)
  }

  async flush() {
    if ((await streamx.Writable.drained(this)) === false) return false
    if (this.destroying) return false

    const missing = this._wreqs.length - this._wfree.length
    if (missing === 0) return true

    return new Promise((resolve) => {
      this._flushes.push({ flush: this._flushing++, missing, resolve })
    })
  }

  toJSON() {
    return {
      id: this.id,
      connected: this.connected,
      destroying: this.destroying,
      destroyed: this.destroyed,
      remoteId: this.remoteId,
      remoteHost: this.remoteHost,
      remoteFamily: this.remoteFamily,
      remotePort: this.remotePort,
      mtu: this.mtu,
      rtt: this.rtt,
      cwnd: this.cwnd,
      inflight: this.inflight,
      socket: this.socket ? this.socket.toJSON() : null
    }
  }

  _read(cb) {
    cb(null)
  }

  _writeContinue(err) {
    if (this._onwrite === null) return
    const cb = this._onwrite
    this._onwrite = null
    cb(err)
  }

  _destroyContinue(err) {
    if (this._ondestroy === null) return
    const cb = this._ondestroy
    this._ondestroy = null
    cb(err)
  }

  _writev(buffers, cb) {
    if (!this.connected)
      throw customError('Writing while not connected not currently supported', 'ERR_ASSERTION')

    let drained = true

    if (buffers.length === 1) {
      const id = this._allocWrite(1)
      const req = this._wreqs[id]

      req.flush = this._flushing
      req.buffer = buffers[0]

      drained = binding.udx_napi_stream_write(this._handle, req.handle, id, req.buffer) !== 0
    } else {
      const id = this._allocWrite(nextBatchSize(buffers.length))
      const req = this._wreqs[id]

      req.flush = this._flushing
      req.buffers = buffers

      drained = binding.udx_napi_stream_writev(this._handle, req.handle, id, req.buffers) !== 0
    }

    if (drained) cb(null)
    else this._onwrite = cb
  }

  _final(cb) {
    const id = this._allocWrite(1)
    const req = this._wreqs[id]

    req.flush = this._flushes
    req.buffer = b4a.allocUnsafe(0)

    const drained =
      binding.udx_napi_stream_write_end(this._handle, req.handle, id, req.buffer) !== 0

    if (drained) cb(null)
    else this._onwrite = cb
  }

  _predestroy() {
    if (!this._closed) binding.udx_napi_stream_destroy(this._handle)
    this._closed = true
    this._writeContinue(null)
  }

  _destroy(cb) {
    if (this.connected) this._ondestroy = cb
    else cb(null)
  }

  _ondata(read) {
    this.push(this._consumeData(read))
    return this._buffer
  }

  _onend(read) {
    if (read > 0) this.push(this._consumeData(read))
    this.push(null)
  }

  _ondrain() {
    this._writeContinue(null)
  }

  _flushAck(flush) {
    for (let i = this._flushes.length - 1; i >= 0; i--) {
      const f = this._flushes[i]
      if (f.flush < flush) break
      f.missing--
    }

    while (this._flushes.length > 0 && this._flushes[0].missing === 0) {
      this._flushes.shift().resolve(true)
    }
  }

  _onack(id) {
    const req = this._wreqs[id]

    req.buffers = req.buffer = null
    this._wfree.push(id)

    if (this._flushes.length > 0) this._flushAck(req.flush)

    // gc the free list
    if (this._wfree.length >= 64 && this._wfree.length === this._wreqs.length) {
      this._wfree = []
      this._wreqs = []
    }
  }

  _onsend(id, err) {
    const req = this._sreqs[id]

    const onflush = req.onflush

    req.buffer = null
    req.onflush = null

    this._sfree.push(id)

    onflush(err >= 0)

    // gc the free list
    if (this._sfree.length >= 16 && this._sfree.length === this._sreqs.length) {
      this._sfree = []
      this._sreqs = []
    }
  }

  _onmessage(len) {
    this.emit('message', this.udx._consumeMessage(len))
    return this.udx._buffer
  }

  _onclose(err) {
    this._closed = true

    if (this.socket) {
      this.socket._removeStream(this)
      this.socket = null
    }

    if (this._previousSocket) {
      this._previousSocket._removeStream(this)
      this._previousSocket = null
    }

    // no error, we don't need to do anything
    if (!err) return this._destroyContinue(null)

    if (this._ondestroy === null) this.destroy(err)
    else this._destroyContinue(err)
  }

  _onfirewall(socket, port, host, family) {
    return this._firewall(socket, port, host, family) ? 1 : 0
  }

  _onremotechanged() {
    if (this._previousSocket) {
      this._previousSocket._removeStream(this)
      this._previousSocket = null
    }

    this._remoteChanging = null
    this.emit('remote-changed')
  }

  _consumeData(len) {
    const next = this._buffer.subarray(0, len)
    this._buffer = this._buffer.subarray(len)
    if (this._buffer.byteLength < MAX_PACKET) this._reallocData()
    return next
  }

  _reallocData() {
    this._buffer = b4a.allocUnsafe(BUFFER_SIZE)
    return this._buffer
  }

  _reallocMessage() {
    return this.udx._reallocMessage()
  }

  _allocWrite(size) {
    if (this._wfree.length === 0) {
      const handle = b4a.allocUnsafe(binding.udx_napi_stream_write_sizeof(size))
      return (
        this._wreqs.push({
          handle,
          size,
          buffers: null,
          buffer: null,
          flush: 0
        }) - 1
      )
    }

    const free = this._wfree.pop()
    if (size === 1) return free

    const next = this._wreqs[free]
    if (next.size < size) {
      next.handle = b4a.allocUnsafe(binding.udx_napi_stream_write_sizeof(size))
      next.size = size
    }

    return free
  }

  _allocSend() {
    if (this._sfree.length > 0) return this._sfree.pop()
    const handle = b4a.allocUnsafe(binding.sizeof_udx_stream_send_t)
    return this._sreqs.push({ handle, buffer: null, resolve: null, reject: null }) - 1
  }
}

function noop() {}

function toBuffer(data) {
  return typeof data === 'string' ? b4a.from(data) : data
}

function firewallAll(socket, port, host) {
  return true
}

function customError(message, code) {
  const error = new Error(message)
  error.code = code
  return error
}

function nextBatchSize(n) {
  // try to coerce the the writevs into sameish size
  if (n === 1) return 1
  // group all < 8 to the same size, low mem overhead but save some small allocs
  if (n < 8) return 8
  if (n < 16) return 16
  if (n < 32) return 32
  if (n < 64) return 64
  return n
}
const b4a = require('b4a')
const binding = require('../binding')
const ip = require('./ip')
const Socket = require('./socket')
const Stream = require('./stream')
const NetworkInterfaces = require('./network-interfaces')

const MAX_MESSAGE = 4096
const BUFFER_SIZE = 65536 + MAX_MESSAGE

module.exports = class UDX {
  constructor() {
    this._handle = b4a.alloc(binding.sizeof_udx_napi_t)
    this._watchers = new Set()
    this._view64 = new BigUint64Array(
      this._handle.buffer,
      this._handle.byteOffset,
      this._handle.byteLength >> 3
    )

    this._buffer = null
    this._reallocMessage()

    binding.udx_napi_init(this._handle, this._buffer)
  }

  static isIPv4(host) {
    return ip.isIPv4(host)
  }

  static isIPv6(host) {
    return ip.isIPv6(host)
  }

  static isIP(host) {
    return ip.isIP(host)
  }

  get bytesTransmitted() {
    return Number(this._view64[binding.offsetof_udx_t_bytes_tx >> 3])
  }

  get packetsTransmitted() {
    return Number(this._view64[binding.offsetof_udx_t_packets_tx >> 3])
  }

  get bytesReceived() {
    return Number(this._view64[binding.offsetof_udx_t_bytes_rx >> 3])
  }

  get packetsReceived() {
    return Number(this._view64[binding.offsetof_udx_t_packets_rx >> 3])
  }

  get packetsDroppedByKernel() {
    return Number(this._view64[binding.offsetof_udx_t_packets_dropped_by_kernel >> 3])
  }

  _consumeMessage(len) {
    const next = this._buffer.subarray(0, len)
    this._buffer = this._buffer.subarray(len)
    if (this._buffer.byteLength < MAX_MESSAGE) this._reallocMessage()
    return next
  }

  _reallocMessage() {
    // TODO: move reallocation to native
    this._buffer = b4a.allocUnsafe(BUFFER_SIZE)
    return this._buffer
  }

  createSocket(opts) {
    return new Socket(this, opts)
  }

  createStream(id, opts) {
    return new Stream(this, id, opts)
  }

  networkInterfaces() {
    let [watcher = null] = this._watchers
    if (watcher) return watcher.interfaces

    watcher = new NetworkInterfaces(this)
    watcher.destroy()

    return watcher.interfaces
  }

  watchNetworkInterfaces(onchange) {
    const watcher = new NetworkInterfaces(this)

    this._watchers.add(watcher)
    watcher.on('close', () => {
      this._watchers.delete(watcher)
    })

    if (onchange) watcher.on('change', onchange)

    return watcher.watch()
  }

  async lookup(host, opts = {}) {
    const { family = 0 } = opts

    const req = b4a.alloc(binding.sizeof_udx_napi_lookup_t)
    const ctx = {
      req,
      resolve: null,
      reject: null
    }

    const promise = new Promise((resolve, reject) => {
      ctx.resolve = resolve
      ctx.reject = reject
    })

    binding.udx_napi_lookup(this._handle, req, host, family, ctx, onlookup)

    return promise
  }
}

function onlookup(err, host, family) {
  if (err) this.reject(err)
  else this.resolve({ host, family })
}
{
  "name": "udx-native",
  "version": "1.19.2",
  "description": "udx is reliable, multiplexed, and congestion-controlled streams over udp",
  "main": "lib/udx.js",
  "files": [
    "lib",
    "prebuilds",
    "binding.cc",
    "binding.js",
    "CMakeLists.txt"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "addon": true,
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check .",
    "test": "npm run lint && npm run test:bare && npm run test:node",
    "test:node": "node test/all.js",
    "test:bare": "bare test/all.js",
    "test:all": "brittle test/*.js test/slow/*.js",
    "test:generate": "brittle -r test/all.js test/*.js",
    "bench": "brittle test/bench/*.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/udx-native.git"
  },
  "keywords": [
    "tcp",
    "udp",
    "stream",
    "reliable"
  ],
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/udx-native/issues"
  },
  "homepage": "https://github.com/holepunchto/udx-native#readme",
  "engines": {
    "bare": ">=1.17.4"
  },
  "dependencies": {
    "b4a": "^1.5.0",
    "bare-events": "^2.2.0",
    "require-addon": "^1.1.0",
    "streamx": "^2.22.0"
  },
  "devDependencies": {
    "bare-compat-napi": "^1.3.0",
    "brittle": "^3.1.0",
    "cmake-bare": "^1.1.10",
    "cmake-fetch": "^1.0.1",
    "cmake-napi": "^1.0.5",
    "is-ci": "^3.0.1",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "tiny-byte-size": "^1.1.0"
  }
}
exports.add = add
exports.has = has
exports.remove = remove
exports.swap = swap

function add (list, item) {
  if (has(list, item)) return item
  item._index = list.length
  list.push(item)
  return item
}

function has (list, item) {
  return item._index < list.length && list[item._index] === item
}

function remove (list, item) {
  if (!has(list, item)) return null

  var last = list.pop()
  if (last !== item) {
    list[item._index] = last
    last._index = item._index
  }

  return item
}

function swap (list, a, b) {
  if (!has(list, a) || !has(list, b)) return
  var tmp = a._index
  a._index = b._index
  list[a._index] = a
  b._index = tmp
  list[b._index] = b
}
{
  "name": "unordered-set",
  "version": "2.0.1",
  "description": "A couple of functions that make it easy to maintain an unordered set as an array in an efficient way",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^6.0.4",
    "tape": "^4.4.0"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/unordered-set.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/unordered-set/issues"
  },
  "homepage": "https://github.com/mafintosh/unordered-set"
}
const b4a = require('b4a')

unslab.all = all
unslab.is = is

module.exports = unslab

function unslab (buf) {
  if (buf === null || buf.buffer.byteLength === buf.byteLength) return buf
  const copy = b4a.allocUnsafeSlow(buf.byteLength)
  copy.set(buf, 0)
  return copy
}

function is (buf) {
  return buf.buffer.byteLength !== buf.byteLength
}

function all (list) {
  let size = 0
  for (let i = 0; i < list.length; i++) {
    const buf = list[i]
    size += buf === null || buf.buffer.byteLength === buf.byteLength ? 0 : buf.byteLength
  }

  const copy = b4a.allocUnsafeSlow(size)
  const result = new Array(list.length)

  let offset = 0
  for (let i = 0; i < list.length; i++) {
    let buf = list[i]

    if (buf !== null && buf.buffer.byteLength !== buf.byteLength) {
      copy.set(buf, offset)
      buf = copy.subarray(offset, offset += buf.byteLength)
    }

    result[i] = buf
  }

  return result
}
{
  "name": "unslab",
  "version": "1.3.0",
  "description": "Unslab some slab'ed buffers",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.6.6"
  },
  "devDependencies": {
    "brittle": "^3.5.2",
    "standard": "^17.1.0"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/unslab.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/unslab/issues"
  },
  "homepage": "https://github.com/holepunchto/unslab"
}
const { runtime, platform, arch } = typeof Bare !== 'undefined'
  ? { runtime: 'bare', platform: global.Bare.platform, arch: global.Bare.arch }
  : typeof process !== 'undefined'
    ? { runtime: 'node', platform: global.process.platform, arch: global.process.arch }
    : typeof Window !== 'undefined'
      ? { runtime: 'browser', platform: 'unknown', arch: 'unknown' }
      : { runtime: 'unknown', platform: 'unknown', arch: 'unknown' }

exports.runtime = runtime
exports.platform = platform
exports.arch = arch
exports.isBare = runtime === 'bare'
exports.isBareKit = exports.isBare && typeof BareKit !== 'undefined'
exports.isPear = typeof Pear !== 'undefined'
exports.isNode = runtime === 'node'
exports.isBrowser = runtime === 'browser'
exports.isWindows = platform === 'win32'
exports.isLinux = platform === 'linux'
exports.isMac = platform === 'darwin'
exports.isIOS = platform === 'ios' || platform === 'ios-simulator'
exports.isAndroid = platform === 'android'
exports.isElectron = typeof process !== 'undefined' && !!global.process.versions?.electron
exports.isElectronRenderer = exports.isElectron && global.process.type === 'renderer'
exports.isElectronWorker = exports.isElectron && global.process.type === 'worker'
{
  "name": "which-runtime",
  "version": "1.3.2",
  "description": "Detect if you are in Bare or Node and which os etc",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {},
  "devDependencies": {
    "standard": "^17.0.0"
  },
  "scripts": {
    "test": "standard"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/which-runtime.git"
  },
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/which-runtime/issues"
  },
  "homepage": "https://github.com/holepunchto/which-runtime"
}
module.exports = class MaxCache {
  constructor ({ maxSize, maxAge, createMap, ongc }) {
    this.maxSize = maxSize
    this.maxAge = maxAge
    this.ongc = ongc || null

    this._createMap = createMap || defaultCreateMap
    this._latest = this._createMap()
    this._oldest = this._createMap()
    this._retained = this._createMap()
    this._gced = false
    this._interval = null

    if (this.maxAge > 0 && this.maxAge < Infinity) {
      const tick = Math.ceil(2 / 3 * this.maxAge)
      this._interval = setInterval(this._gcAuto.bind(this), tick)
      if (this._interval.unref) this._interval.unref()
    }
  }

  * [Symbol.iterator] () {
    for (const it of [this._latest, this._oldest, this._retained]) {
      yield * it
    }
  }

  * keys () {
    for (const it of [this._latest, this._oldest, this._retained]) {
      yield * it.keys()
    }
  }

  * values () {
    for (const it of [this._latest, this._oldest, this._retained]) {
      yield * it.values()
    }
  }

  destroy () {
    this.clear()
    clearInterval(this._interval)
    this._interval = null
  }

  clear () {
    this._gced = true
    this._latest.clear()
    this._oldest.clear()
    this._retained.clear()
  }

  set (k, v) {
    if (this._retained.has(k)) return this
    this._latest.set(k, v)
    this._oldest.delete(k) || this._retained.delete(k)
    if (this._latest.size >= this.maxSize) this._gc()
    return this
  }

  retain (k, v) {
    this._retained.set(k, v)
    this._latest.delete(k) || this._oldest.delete(k)
    return this
  }

  delete (k) {
    return this._latest.delete(k) || this._oldest.delete(k) || this._retained.delete(k)
  }

  has (k) {
    return this._latest.has(k) || this._oldest.has(k) || this._retained.has(k)
  }

  get (k) {
    if (this._latest.has(k)) {
      return this._latest.get(k)
    }

    if (this._oldest.has(k)) {
      const v = this._oldest.get(k)
      this._latest.set(k, v)
      this._oldest.delete(k)
      return v
    }

    if (this._retained.has(k)) {
      return this._retained.get(k)
    }

    return null
  }

  _gcAuto () {
    if (!this._gced) this._gc()
    this._gced = false
  }

  _gc () {
    this._gced = true
    if (this.ongc !== null && this._oldest.size > 0) this.ongc(this._oldest)
    this._oldest = this._latest
    this._latest = this._createMap()
  }
}

function defaultCreateMap () {
  return new Map()
}
{
  "name": "xache",
  "version": "1.2.1",
  "description": "Yet another auto expiring, max sizable cache",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "devDependencies": {
    "brittle": "^3.3.2",
    "standard": "^17.1.0"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/xache.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/xache/issues"
  },
  "homepage": "https://github.com/mafintosh/xache"
}
const b4a = require('b4a')

const ALPHABET = 'ybndrfg8ejkmcpqxot1uwisza345h769'
const MIN = 0x31 // 1
const MAX = 0x7a // z
const REVERSE = new Int8Array(1 + MAX - MIN)

REVERSE.fill(-1)

for (let i = 0; i < ALPHABET.length; i++) {
  const v = ALPHABET.charCodeAt(i) - MIN
  REVERSE[v] = i
}

exports.encode = encode
exports.decode = decode
exports.ALPHABET = ALPHABET

function decode (s, out) {
  let pb = 0
  let ps = 0

  const r = s.length & 7
  const q = (s.length - r) / 8

  if (!out) out = b4a.allocUnsafe(Math.ceil(s.length * 5 / 8))

  // 0 5 2 7 4 1 6 3 (+5 mod 8)
  for (let i = 0; i < q; i++) {
    const a = quintet(s, ps++)
    const b = quintet(s, ps++)
    const c = quintet(s, ps++)
    const d = quintet(s, ps++)
    const e = quintet(s, ps++)
    const f = quintet(s, ps++)
    const g = quintet(s, ps++)
    const h = quintet(s, ps++)

    out[pb++] = (a << 3) | (b >>> 2)
    out[pb++] = ((b & 0b11) << 6) | (c << 1) | (d >>> 4)
    out[pb++] = ((d & 0b1111) << 4) | (e >>> 1)
    out[pb++] = ((e & 0b1) << 7) | (f << 2) | (g >>> 3)
    out[pb++] = ((g & 0b111) << 5) | h
  }

  if (r === 0) return out.subarray(0, pb)

  const a = quintet(s, ps++)
  const b = quintet(s, ps++)

  out[pb++] = (a << 3) | (b >>> 2)

  if (r <= 2) return out.subarray(0, pb)

  const c = quintet(s, ps++)
  const d = quintet(s, ps++)

  out[pb++] = ((b & 0b11) << 6) | (c << 1) | (d >>> 4)

  if (r <= 4) return out.subarray(0, pb)

  const e = quintet(s, ps++)

  out[pb++] = ((d & 0b1111) << 4) | (e >>> 1)

  if (r <= 5) return out.subarray(0, pb)

  const f = quintet(s, ps++)
  const g = quintet(s, ps++)

  out[pb++] = ((e & 0b1) << 7) | (f << 2) | (g >>> 3)

  if (r <= 7) return out.subarray(0, pb)

  const h = quintet(s, ps++)

  out[pb++] = ((g & 0b111) << 5) | h

  return out.subarray(0, pb)
}

function encode (buf) {
  if (typeof buf === 'string') buf = b4a.from(buf)

  const max = buf.byteLength * 8

  let s = ''

  for (let p = 0; p < max; p += 5) {
    const i = p >>> 3
    const j = p & 7

    if (j <= 3) {
      s += ALPHABET[(buf[i] >>> (3 - j)) & 0b11111]
      continue
    }

    const of = j - 3
    const h = (buf[i] << of) & 0b11111
    const l = (i >= buf.byteLength ? 0 : buf[i + 1]) >>> (8 - of)

    s += ALPHABET[h | l]
  }

  return s
}

function quintet (s, i) {
  if (i > s.length) {
    return 0
  }

  const v = s.charCodeAt(i)

  if (v < MIN || v > MAX) {
    throw Error('Invalid character in base32 input: "' + s[i] + '" at position ' + i)
  }

  const bits = REVERSE[v - MIN]

  if (bits === -1) {
    throw Error('Invalid character in base32 input: "' + s[i] + '" at position ' + i)
  }

  return bits
}
{
  "name": "z32",
  "version": "1.1.0",
  "description": "Encode & decode z-base32",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.5.3"
  },
  "devDependencies": {
    "base-x": "^4.0.0",
    "base32": "0.0.7",
    "brittle": "^3.1.3",
    "nanobench": "^3.0.0",
    "rfc4648": "^1.5.2",
    "standard": "^17.0.0"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/z32.git"
  },
  "scripts": {
    "test": "standard && brittle test.js",
    "bench": "node benchmark.js"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/z32/issues"
  },
  "homepage": "https://github.com/mafintosh/z32"
}
{
  "name": "hyper-svc",
  "version": "0.1.9",
  "description": "Reusable per-app daemon library \u2014 UDS + HTTP for local RPC, Hyperswarm for peer mirroring",
  "type": "module",
  "main": "index.js",
  "scripts": {
    "test": "brittle test/*.test.js",
    "test:bare": "bare ./node_modules/.bin/brittle test/*.test.js"
  },
  "engines": {
    "node": ">=18",
    "bare": ">=1.0"
  },
  "imports": {
    "#node:fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "#node:fs/promises": {
      "bare": "bare-fs/promises",
      "default": "fs/promises"
    },
    "#node:path": {
      "bare": "bare-path",
      "default": "path"
    },
    "#node:os": {
      "bare": "bare-os",
      "default": "os"
    },
    "#node:url": {
      "bare": "bare-url",
      "default": "url"
    },
    "#node:events": {
      "bare": "bare-events",
      "default": "events"
    },
    "#node:stream": {
      "bare": "bare-stream",
      "default": "stream"
    },
    "#node:net": {
      "bare": "bare-net",
      "default": "net"
    },
    "#node:http": {
      "bare": "bare-http1",
      "default": "http"
    },
    "#node:process": {
      "bare": "bare-process",
      "default": "process"
    }
  },
  "dependencies": {
    "b4a": "^1.6.0",
    "bare-events": "^2.0.0",
    "bare-fs": "^4.7.2",
    "bare-http1": "^4.0.0",
    "bare-net": "^1.0.0",
    "bare-os": "^3.0.0",
    "bare-path": "^3.0.0",
    "bare-process": "^4.0.0",
    "bare-stream": "^2.0.0",
    "bare-url": "^2.0.0",
    "compact-encoding": "^3.2.0",
    "hypercore-crypto": "^3.0.0",
    "hyperswarm": "^4.0.0",
    "protomux": "^3.0.0",
    "ready-resource": "^1.0.0",
    "bare-abstract-socket": "^1.0.0"
  },
  "devDependencies": {
    "@hyperswarm/testnet": "^3.0.0",
    "brittle": "^3.0.0",
    "corestore": "^7.0.0",
    "hyper-rooms": "file:../hyper-rooms"
  },
  "overrides": {}
}
const codecs = require('codecs')
const { Readable } = require('streamx')
const mutexify = require('mutexify/promise')
const b4a = require('b4a')
const safetyCatch = require('safety-catch')
const ReadyResource = require('ready-resource')
const debounce = require('debounceify')
const Rache = require('rache')
const rrp = require('resolve-reject-promise')

const { all: unslabAll } = require('unslab')

const RangeIterator = require('./iterators/range')
const HistoryIterator = require('./iterators/history')
const DiffIterator = require('./iterators/diff')
const LocalBlockIterator = require('./iterators/local')
const Extension = require('./lib/extension')
const { YoloIndex, Node, Header } = require('./lib/messages')
const { BLOCK_NOT_AVAILABLE, DECODING_ERROR } = require('hypercore-errors')

const T = 5
const MIN_KEYS = T - 1
const MAX_CHILDREN = MIN_KEYS * 2 + 1

const SEP = b4a.alloc(1)
const EMPTY = b4a.alloc(0)

class Key {
  constructor(seq, value) {
    this.seq = seq
    this.value = value
  }
}

class Child {
  constructor(seq, offset, value) {
    this.seq = seq
    this.offset = offset
    this.value = value
  }
}

class Cache {
  constructor(rache) {
    this.keys = rache
    this.length = 0
  }

  get(seq) {
    return this.keys.get(seq) || null
  }

  set(seq, key) {
    this.keys.set(seq, key)
    if (seq >= this.length) this.length = seq + 1
  }

  gc(length) {
    // if we need to "work" more than 128 ticks, just bust the cache...
    if (this.length - length > 128) {
      this.keys.clear()
    } else {
      for (let i = length; i < this.length; i++) {
        this.keys.delete(i)
      }
    }

    this.length = length
  }

  clear() {
    this.keys.clear()
  }
}

class Pointers {
  constructor(decoded) {
    this.levels = decoded.levels.map((l) => {
      const children = []
      const keys = []

      for (let i = 0; i < l.keys.length; i++) {
        keys.push(new Key(l.keys[i], null))
      }

      for (let i = 0; i < l.children.length; i += 2) {
        children.push(new Child(l.children[i], l.children[i + 1], null))
      }

      return { keys, children }
    })
  }

  get(i) {
    return this.levels[i]
  }

  hasKey(seq) {
    for (const lvl of this.levels) {
      for (const key of lvl.keys) {
        if (key.seq === seq) return true
      }
    }
    return false
  }
}

function inflate(entry) {
  if (entry.inflated === null) {
    entry.inflated = YoloIndex.decode(entry.index)
    entry.index = null
  }
  return new Pointers(entry.inflated)
}

function deflate(index) {
  const levels = index.map((l) => {
    const keys = []
    const children = []

    for (let i = 0; i < l.value.keys.length; i++) {
      keys.push(l.value.keys[i].seq)
    }

    for (let i = 0; i < l.value.children.length; i++) {
      children.push(l.value.children[i].seq, l.value.children[i].offset)
    }

    return { keys, children }
  })

  return YoloIndex.encode({ levels })
}

class TreeNode {
  constructor(block, keys, children, offset) {
    this.block = block
    this.offset = offset
    this.keys = keys
    this.children = children
    this.changed = false

    this.preload()
  }

  preload() {
    if (this.block === null) return

    const core = getBackingCore(this.block.tree.core)
    if (!core) return

    const bitfield = core.core.bitfield
    const blocks = []

    for (let i = 0; i < this.keys.length; i++) {
      const k = this.keys[i]
      if (k.value) continue
      if (k.seq >= core.signedLength || (bitfield && bitfield.get(k.seq))) continue
      blocks.push(k.seq)
    }
    for (let i = 0; i < this.children.length; i++) {
      const c = this.children[i]
      if (c.value) continue
      if (c.seq >= core.signedLength || (bitfield && bitfield.get(c.seq))) continue
      blocks.push(c.seq)
    }

    if (blocks.length) core.download({ blocks })
  }

  async insertKey(key, value, child, node, encoding, cas) {
    let s = 0
    let e = this.keys.length
    let c

    while (s < e) {
      const mid = (s + e) >> 1
      c = b4a.compare(key.value, await this.getKey(mid))

      if (c === 0) {
        if (cas) {
          const prev = await this.getKeyNode(mid)
          if (!(await cas(prev.final(encoding), node))) return true
        }
        if (!this.block.tree.tree.alwaysDuplicate) {
          const prev = await this.getKeyNode(mid)
          if (sameValue(prev.value, value)) return true
        }
        this.changed = true
        this.keys[mid] = key
        return true
      }

      if (c < 0) e = mid
      else s = mid + 1
    }

    const i = c < 0 ? e : s
    this.keys.splice(i, 0, key)
    if (child) this.children.splice(i + 1, 0, new Child(0, 0, child))
    this.changed = true

    return this.keys.length < MAX_CHILDREN
  }

  removeKey(index) {
    this.keys.splice(index, 1)
    if (this.children.length) {
      this.children[index + 1].seq = 0 // mark as freed
      this.children.splice(index + 1, 1)
    }
    this.changed = true
  }

  async siblings(parent) {
    for (let i = 0; i < parent.children.length; i++) {
      if (parent.children[i].value === this) {
        const [left, right] = await Promise.all([
          i ? parent.getChildNode(i - 1) : null,
          i < parent.children.length - 1 ? parent.getChildNode(i + 1) : null
        ])
        return { left, index: i, right }
      }
    }

    throw new Error('Bad parent')
  }

  merge(node, median) {
    this.changed = true
    this.keys.push(median)
    for (let i = 0; i < node.keys.length; i++) this.keys.push(node.keys[i])
    for (let i = 0; i < node.children.length; i++) this.children.push(node.children[i])
  }

  async split() {
    const len = this.keys.length >> 1
    const right = TreeNode.create(this.block)

    while (right.keys.length < len) right.keys.push(this.keys.pop())
    right.keys.reverse()

    await this.getKey(this.keys.length - 1) // make sure the median is loaded
    const median = this.keys.pop()

    if (this.children.length) {
      while (right.children.length < len + 1) right.children.push(this.children.pop())
      right.children.reverse()
    }

    this.changed = true

    return {
      left: this,
      median,
      right
    }
  }

  getKeyNode(index) {
    return this.block.tree.getBlock(this.keys[index].seq)
  }

  async getChildNode(index) {
    const child = this.children[index]
    if (child.value) return child.value
    const block =
      child.seq === this.block.seq ? this.block : await this.block.tree.getBlock(child.seq)
    return (child.value = block.getTreeNode(child.offset))
  }

  setKey(index, key) {
    this.keys[index] = key
    this.changed = true
  }

  async getKey(index) {
    const key = this.keys[index]
    if (key.value) return key.value
    const k = key.seq === this.block.seq ? this.block.key : await this.block.tree.getKey(key.seq)
    return (key.value = k)
  }

  indexChanges(index, seq) {
    const offset = index.push(null) - 1
    this.changed = false

    for (const child of this.children) {
      if (!child.value || !child.value.changed) continue
      child.seq = seq
      child.offset = child.value.indexChanges(index, seq)
      index[child.offset] = child
    }

    return offset
  }

  updateChildren(seq, block) {
    for (const child of this.children) {
      if (!child.value || child.seq !== seq) continue
      child.value.block = block
      child.value.updateChildren(seq, block)
    }
  }

  static create(block) {
    const node = new TreeNode(block, [], [], 0)
    node.changed = true
    return node
  }
}

class BlockEntry {
  constructor(seq, tree, entry) {
    this.seq = seq
    this.tree = tree
    this.index = null
    this.entry = entry
    this.key = entry.key
    this.value = entry.value
  }

  isTarget(key) {
    return b4a.equals(this.key, key)
  }

  inflate() {
    if (this.index === null) {
      this.index = inflate(this.entry)
    }
  }

  isDeletion() {
    if (this.value !== null) return false

    if (this.index === null) {
      this.index = inflate(this.entry)
    }

    return !this.index.hasKey(this.seq)
  }

  final(encoding) {
    return {
      seq: this.seq,
      key: encoding.key ? encoding.key.decode(this.key) : this.key,
      value: this.value && (encoding.value ? encoding.value.decode(this.value) : this.value)
    }
  }

  getTreeNode(offset) {
    if (this.index === null) {
      this.index = inflate(this.entry)
    }
    const entry = this.index.get(offset)
    return new TreeNode(this, entry.keys, entry.children, offset)
  }
}

class CacheLock {
  constructor() {
    this.map = new Map()
  }

  enter(seq) {
    const pending = this.map.get(seq)

    if (!pending) {
      this.map.set(seq, [])
      return Promise.resolve()
    }

    const { resolve, promise } = rrp()
    pending.push(resolve)
    return promise
  }

  exit(seq) {
    const pending = this.map.get(seq)
    if (!pending.length) {
      this.map.delete(seq)
      return
    }

    pending.pop()()
  }
}

class BatchEntry extends BlockEntry {
  constructor(seq, tree, key, value, index) {
    super(seq, tree, { key, value, index: null, inflated: null })
    this.pendingIndex = index
  }

  isTarget(key) {
    return false
  }

  getTreeNode(offset) {
    return this.pendingIndex[offset].value
  }
}

class Hyperbee extends ReadyResource {
  constructor(core, opts = {}) {
    super()
    // this.feed is now deprecated, and will be this.core going forward
    this.feed = core
    this.core = core

    this.keyEncoding = opts.keyEncoding ? codecs(opts.keyEncoding) : null
    this.valueEncoding = opts.valueEncoding ? codecs(opts.valueEncoding) : null
    this.extension = opts.extension !== false ? getExtension(this, opts) : null
    this.metadata = opts.metadata || null
    this.lock = opts.lock || mutexify()
    this.sep = opts.sep || SEP
    this.readonly = !!opts.readonly
    this.prefix = opts.prefix || null

    // In a future version, this should be false by default
    this.alwaysDuplicate = opts.alwaysDuplicate !== false

    this._unprefixedKeyEncoding = this.keyEncoding
    this._sub = !!this.prefix
    this._checkout = opts.checkout || 0
    this._view = !!opts._view

    this._onappendBound = this._view ? null : this._onappend.bind(this)
    this._ontruncateBound = this._view ? null : this._ontruncate.bind(this)
    this._watchers = this._onappendBound ? [] : null
    this._entryWatchers = this._onappendBound ? [] : null
    this._sessions = opts.sessions !== false

    this._keyCache = null
    this._nodeCache = null
    this._cacheLock = new CacheLock()

    this._batches = []

    if (this._watchers) {
      this.core.on('append', this._onappendBound)
      this.core.on('truncate', this._ontruncateBound)
    }

    if (this.prefix && opts._sub) {
      this.keyEncoding = prefixEncoding(this.prefix, this.keyEncoding)
    }

    this.ready().catch(safetyCatch)
  }

  async _open() {
    if (this.core.opened === false) await this.core.ready()
    // bump the internal ranges since the nodes are small
    if (this._watchers && this.core.replicator.setInflightRange) {
      this.core.replicator.setInflightRange(256, 512)
    }

    // snapshot
    if (this._checkout === -1) this._checkout = Math.max(1, this.core.length)

    const baseCache = Rache.from(this.core.globalCache)
    this._keyCache = new Cache(baseCache)
    this._nodeCache = new Cache(Rache.from(baseCache))
  }

  get version() {
    return Math.max(1, this._checkout || this.core.length)
  }

  get id() {
    return this.core.id
  }

  get key() {
    return this.core.key
  }

  get discoveryKey() {
    return this.core.discoveryKey
  }

  get writable() {
    return this.core.writable
  }

  get readable() {
    return this.core.readable
  }

  replicate(isInitiator, opts) {
    return this.core.replicate(isInitiator, opts)
  }

  update(opts) {
    return this.core.update(opts)
  }

  peek(range, opts) {
    return iteratorPeek(this.createRangeIterator(range, { ...opts, limit: 1 }))
  }

  createRangeIterator(range, opts = {}) {
    // backwards compat range arg
    opts = opts ? { ...opts, ...range } : range

    const extension = opts.extension === false && opts.limit !== 0 ? null : this.extension
    const keyEncoding = opts.keyEncoding ? codecs(opts.keyEncoding) : this.keyEncoding

    if (extension) {
      const { onseq, onwait } = opts
      let version = 0
      let next = 0

      opts = encRange(keyEncoding, {
        ...opts,
        sub: this._sub,
        onseq(seq) {
          if (!version) version = seq + 1
          if (next) next--
          if (onseq) onseq(seq)
        },
        onwait(seq) {
          if (!next) {
            next = Extension.BATCH_SIZE
            extension.iterator(ite.snapshot(version))
          }
          if (onwait) onwait(seq)
        }
      })
    } else {
      opts = encRange(keyEncoding, { ...opts, sub: this._sub })
    }

    const ite = new RangeIterator(
      new Batch(this, this._makeSnapshot(), null, false, opts),
      null,
      opts
    )
    return ite
  }

  createReadStream(range, opts) {
    const signal = (opts && opts.signal) || null
    return iteratorToStream(this.createRangeIterator(range, opts), signal)
  }

  createHistoryStream(opts) {
    const session = opts && opts.live ? this.core.session() : this._makeSnapshot()
    const signal = (opts && opts.signal) || null
    return iteratorToStream(
      new HistoryIterator(new Batch(this, session, null, false, opts), opts),
      signal
    )
  }

  createDiffStream(right, range, opts) {
    if (typeof right === 'number') right = this.checkout(Math.max(1, right), { reuseSession: true })

    // backwards compat range arg
    opts = opts ? { ...opts, ...range } : range

    const signal = (opts && opts.signal) || null

    const keyEncoding = opts && opts.keyEncoding ? codecs(opts.keyEncoding) : this.keyEncoding
    if (keyEncoding) opts = encRange(keyEncoding, { ...opts, sub: this._sub })

    let done
    let closing
    let ite

    const left = this

    const rs = new Readable({
      signal,
      eagerOpen: true,
      async open(cb) {
        try {
          if (right.opened === false) await right.ready()
          if (left.opened === false) await left.ready()
        } catch (err) {
          cb(err)
          return
        }

        if (closing) {
          cb(null)
          return
        }

        if (left.core.closing || right.core.closing) {
          cb(new Error('Bee closed'))
          return
        }

        const snapshot = right.version > left.version ? right._makeSnapshot() : left._makeSnapshot()

        done = cb
        ite = new DiffIterator(
          new Batch(left, snapshot, null, false, opts),
          new Batch(right, snapshot, null, false, opts),
          opts
        )
        ite.open().then(fin, fin)
      },
      read(cb) {
        done = cb
        ite.next().then(push, fin)
      },
      predestroy() {
        if (!ite) {
          closing = Promise.resolve()
        } else {
          closing = ite.close()
          closing.catch(noop)
        }
      },
      destroy(cb) {
        done = cb
        if (!closing) closing = ite.close()
        closing.then(fin, fin)
      }
    })

    return rs

    function fin(err) {
      done(err)
    }

    function push(val) {
      rs.push(val)
      done(null)
    }
  }

  get(key, opts) {
    const b = new Batch(this, this._makeSnapshot(), null, true, opts)
    return b.get(key)
  }

  getBySeq(seq, opts) {
    const b = new Batch(this, this._makeSnapshot(), null, true, opts)
    return b.getBySeq(seq)
  }

  put(key, value, opts) {
    const b = new Batch(this, this.core, null, true, opts)
    return b.put(key, value, opts)
  }

  batch(opts) {
    return new Batch(this, this.core, mutexify(), true, opts)
  }

  del(key, opts) {
    const b = new Batch(this, this.core, null, true, opts)
    return b.del(key, opts)
  }

  watch(range, opts) {
    if (!this._watchers) throw new Error('Can only watch the main bee instance')
    return new Watcher(this, range, opts)
  }

  async getAndWatch(key, opts) {
    if (!this._watchers) throw new Error('Can only watch the main bee instance')

    const watcher = new EntryWatcher(this, key, opts)
    await watcher._debouncedUpdate()

    if (this.closing) {
      await watcher.close()
      throw new Error('Bee closed')
    }

    return watcher
  }

  _onappend() {
    for (const watcher of this._watchers) {
      watcher._onappend()
    }

    for (const watcher of this._entryWatchers) {
      watcher._onappend()
    }
  }

  _ontruncate(length) {
    for (const watcher of this._watchers) {
      watcher._ontruncate()
    }

    for (const watcher of this._entryWatchers) {
      watcher._ontruncate()
    }

    this._nodeCache.gc(length)
    this._keyCache.gc(length)
  }

  _makeSnapshot() {
    if (this._sessions === false) return this.core
    // TODO: better if we could encapsulate this in hypercore in the future
    return this._checkout <= this.core.length || this._checkout <= 1
      ? this.core.snapshot()
      : this.core.session({ snapshot: false })
  }

  async clearUnlinked(options = {}) {
    await this.ready()

    const { gte = 0, lt = this.version - 1, batchSize = 4096, wait = true } = options
    const checkout = this.version

    let prev = this.batch({ wait: false, checkout: gte })
    let b = this.batch({ wait, checkout })

    const iteBatch = this.batch({ wait: false, checkout })
    const ite = new LocalBlockIterator(iteBatch, { gte, lt })
    await ite.open()

    let ticks = 0

    while (true) {
      const data = await ite.next()
      if (!data) break

      if (!(await isLinked(b, data))) {
        if (b.core.closing || this.core.closing || this.closing) break
        await this.core.clear(data.seq)
      }

      const prevNode = await prev.get(data.key, { finalize: false }).catch(toNull)

      if (prevNode && !(await isLinked(b, prevNode))) {
        if (b.core.closing || this.core.closing || this.closing) break
        await this.core.clear(prevNode.seq)
      }

      if (ticks++ >= batchSize) {
        ticks = 0
        await prev.close()
        await b.close()

        prev = this.batch({ wait: false, checkout: gte })
        b = this.batch({ wait, checkout })
      }
    }

    if (b.core.closing || this.core.closing || this.closing) throw new Error('Core is closed')

    await b.close()
    await prev.close()
    await ite.close()
    await iteBatch.close()

    return lt
  }

  checkout(version, opts = {}) {
    if (version === 0) version = 1

    // same as above, just checkout isn't set yet...
    const snap =
      opts.reuseSession || this._sessions === false
        ? this.core
        : version <= this.core.length || version <= 1
          ? this.core.snapshot()
          : this.core.session({ snapshot: false })

    return new Hyperbee(snap, {
      _view: true,
      _sub: false,
      prefix: this.prefix,
      sep: this.sep,
      lock: this.lock,
      checkout: version,
      keyEncoding: opts.keyEncoding || this.keyEncoding,
      valueEncoding: opts.valueEncoding || this.valueEncoding,
      extension: this.extension !== null ? this.extension : false
    })
  }

  snapshot(opts) {
    return this.checkout(
      this.core.opened === false || this._checkout <= 0 ? -1 : Math.max(1, this.version),
      opts
    )
  }

  sub(prefix, opts = {}) {
    let sep = opts.sep || this.sep
    if (!b4a.isBuffer(sep)) sep = b4a.from(sep)

    prefix = b4a.concat([this.prefix || EMPTY, b4a.from(prefix), sep])

    const valueEncoding = codecs(opts.valueEncoding || this.valueEncoding)
    const keyEncoding = codecs(opts.keyEncoding || this._unprefixedKeyEncoding)

    return new Hyperbee(this.core, {
      _view: true,
      _sub: true,
      prefix,
      sep: this.sep,
      lock: this.lock,
      checkout: this._checkout,
      valueEncoding,
      keyEncoding,
      extension: this.extension !== null ? this.extension : false,
      metadata: this.metadata
    })
  }

  async getHeader(opts) {
    const blk = await this.core.get(0, opts)
    try {
      return blk && Header.decode(blk)
    } catch {
      throw DECODING_ERROR()
    }
  }

  async _close() {
    if (!this._view) {
      if (this._keyCache) this._keyCache.clear()
      if (this._nodeCache) this._nodeCache.clear()
    }

    if (this._watchers) {
      this.core.off('append', this._onappendBound)
      this.core.off('truncate', this._ontruncateBound)

      while (this._watchers.length) {
        await this._watchers[this._watchers.length - 1].close()
      }
    }

    if (this._entryWatchers) {
      while (this._entryWatchers.length) {
        await this._entryWatchers[this._entryWatchers.length - 1].close()
      }
    }

    while (this._batches.length) {
      await this._batches[this._batches.length - 1].close()
    }

    return this.core.close()
  }

  static async isHyperbee(core, opts) {
    await core.ready()

    const blk0 = await core.get(0, opts)
    if (blk0 === null) throw BLOCK_NOT_AVAILABLE()

    try {
      return Header.decode(blk0).protocol === 'hyperbee'
    } catch (err) {
      // undecodable
      return false
    }
  }
}

class Batch {
  constructor(tree, core, batchLock, cache, options = {}) {
    this.tree = tree
    // this.feed is now deprecated, and will be this.core going forward
    this.feed = core
    this.core = core
    this.index = tree._batches.push(this) - 1
    this.blocks = cache ? new Map() : null
    this.autoFlush = !batchLock
    this.maxBlocksCached = options.maxBlocksCached || 128
    this.rootSeq = 0
    this.root = null
    this.length = 0
    this.checkout = options.checkout === undefined ? -1 : options.checkout
    this.options = options
    this.locked = null
    this.batchLock = batchLock
    this.onseq = this.options.onseq || noop
    this.appending = null
    this.isSnapshot = this.core !== this.tree.core
    this.shouldUpdate = this.options.update !== false
    this.updating = null
    this.encoding = {
      key: options.keyEncoding ? codecs(options.keyEncoding) : tree.keyEncoding,
      value: options.valueEncoding ? codecs(options.valueEncoding) : tree.valueEncoding
    }
  }

  async ready() {
    if (this.core.opened === false) await this.core.ready()
    if (this.tree.opened === false) await this.tree.ready()
  }

  async lock() {
    if (this.tree.readonly) throw new Error('Hyperbee is marked as read-only')
    if (this.locked === null) this.locked = await this.tree.lock()
  }

  get version() {
    if (this.checkout !== -1) return Math.max(1, this.checkout)
    return Math.max(1, this.tree._checkout || this.core.length + this.length)
  }

  async getRoot(ensureHeader) {
    await this.ready()
    if (ensureHeader) {
      if (this.core.length === 0 && this.core.writable && !this.tree.readonly) {
        await this.core.append(
          Header.encode({
            protocol: 'hyperbee',
            metadata: this.tree.metadata
          })
        )
      }
    }
    if (this.tree._checkout === 0 && this.checkout === -1 && this.shouldUpdate) {
      if (this.updating === null) this.updating = this.core.update()
      await this.updating
    }
    if (this.version < 2) return null
    return (await this.getBlock(this.version - 1)).getTreeNode(0)
  }

  async getKey(seq) {
    await this.tree._cacheLock.enter(seq)

    try {
      const k = this.core.fork === this.tree.core.fork ? this.tree._keyCache.get(seq) : null
      if (k !== null) return k
      const key = (await this._getBlock(seq)).key
      if (this.core.fork === this.tree.core.fork) this.tree._keyCache.set(seq, key)
      return key
    } finally {
      this.tree._cacheLock.exit(seq)
    }
  }

  async _getNode(seq) {
    const cached =
      this.tree._nodeCache !== null && this.core.fork === this.tree.core.fork
        ? this.tree._nodeCache.get(seq)
        : null
    if (cached !== null) return cached
    const entry = await this.core.get(seq, {
      ...this.options,
      valueEncoding: Node
    })
    if (entry === null) throw BLOCK_NOT_AVAILABLE()
    const wrap = copyEntry(entry)
    if (this.core.fork === this.tree.core.fork && this.tree._nodeCache !== null) {
      this.tree._nodeCache.set(seq, wrap)
    }
    return wrap
  }

  async getBlock(seq) {
    if (this.rootSeq === 0) this.rootSeq = seq
    await this.tree._cacheLock.enter(seq)

    try {
      return await this._getBlock(seq)
    } finally {
      this.tree._cacheLock.exit(seq)
    }
  }

  async _getBlock(seq) {
    let b = this.blocks && this.blocks.get(seq)
    if (b) return b
    this.onseq(seq)
    const entry = await this._getNode(seq)
    b = this.blocks && this.blocks.get(seq)
    if (b) return b
    b = new BlockEntry(seq, this, entry)
    if (this.blocks && this.blocks.size - this.length < this.maxBlocksCached) {
      this.blocks.set(seq, b)
    }
    return b
  }

  _onwait(key) {
    this.options.onwait = null
    this.tree.extension.get(this.rootSeq + 1, key)
  }

  _getEncoding(opts) {
    if (!opts) return this.encoding
    return {
      key: opts.keyEncoding ? codecs(opts.keyEncoding) : this.encoding.key,
      value: opts.valueEncoding ? codecs(opts.valueEncoding) : this.encoding.value
    }
  }

  peek(range, opts) {
    return iteratorPeek(this.createRangeIterator(range, { ...opts, limit: 1 }))
  }

  createRangeIterator(range, opts = {}) {
    // backwards compat range arg
    opts = opts ? { ...opts, ...range } : range

    const encoding = this._getEncoding(opts)
    return new RangeIterator(
      this,
      encoding,
      encRange(encoding.key, { ...opts, sub: this.tree._sub })
    )
  }

  createReadStream(range, opts) {
    const signal = (opts && opts.signal) || null
    return iteratorToStream(this.createRangeIterator(range, opts), signal)
  }

  async getBySeq(seq, opts) {
    const encoding = this._getEncoding(opts)

    try {
      const block = (await this.getBlock(seq)).final(encoding)
      return { key: block.key, value: block.value }
    } finally {
      await this._closeSnapshot()
    }
  }

  async get(key, opts) {
    const encoding = this._getEncoding(opts)
    const finalize = opts ? opts.finalize !== false : true

    try {
      return await this._get(key, encoding, finalize)
    } finally {
      await this._closeSnapshot()
    }
  }

  async _get(key, encoding, finalize) {
    key = enc(encoding.key, key)

    if (this.tree.extension !== null && this.options.extension !== false) {
      this.options.onwait = this._onwait.bind(this, key)
    }

    let node = await this.getRoot(false)
    if (!node) return null

    while (true) {
      if (node.block.isTarget(key)) {
        return node.block.isDeletion() ? null : finalize ? node.block.final(encoding) : node.block
      }

      let s = 0
      let e = node.keys.length
      let c

      while (s < e) {
        const mid = (s + e) >> 1

        c = b4a.compare(key, await node.getKey(mid))

        if (c === 0) {
          const block = await this.getBlock(node.keys[mid].seq)
          return finalize ? block.final(encoding) : block
        }

        if (c < 0) e = mid
        else s = mid + 1
      }

      if (!node.children.length) return null

      const i = c < 0 ? e : s
      node = await node.getChildNode(i)
    }
  }

  async links(key, seq) {
    let node = await this.getRoot(false)
    if (!node) return false

    if (node.block.seq === seq) return true

    while (true) {
      if (node.block.isTarget(key)) return false

      let s = 0
      let e = node.keys.length
      let c

      while (s < e) {
        const mid = (s + e) >> 1

        if (node.keys[mid].seq === seq) return true
        c = b4a.compare(key, await node.getKey(mid))

        if (c === 0) return false

        if (c < 0) e = mid
        else s = mid + 1
      }

      if (!node.children.length) return false

      const i = c < 0 ? e : s
      node = await node.getChildNode(i)
      if (node.block.seq === seq) return true
    }
  }

  async put(key, value, opts) {
    const release = this.batchLock ? await this.batchLock() : null

    const cas = (opts && opts.cas) || null
    const encoding = this._getEncoding(opts)

    if (!this.locked) await this.lock()
    if (!release) return this._put(key, value, encoding, cas)

    try {
      return await this._put(key, value, encoding, cas)
    } finally {
      release()
    }
  }

  async _put(key, value, encoding, cas) {
    const newNode = {
      seq: 0,
      key,
      value
    }
    key = enc(encoding.key, key)
    value = enc(encoding.value, value)

    const stack = []

    let root
    let node = (root = await this.getRoot(true))
    if (!node) node = root = TreeNode.create(null)

    const seq = (newNode.seq = this.core.length + this.length)
    const target = new Key(seq, key)

    while (node.children.length) {
      stack.push(node)
      node.changed = true // changed, but compressible

      let s = 0
      let e = node.keys.length
      let c

      while (s < e) {
        const mid = (s + e) >> 1
        c = b4a.compare(target.value, await node.getKey(mid))

        if (c === 0) {
          if (cas) {
            const prev = await node.getKeyNode(mid)
            if (!(await cas(prev.final(encoding), newNode))) return this._unlockMaybe()
          }
          if (!this.tree.alwaysDuplicate) {
            const prev = await node.getKeyNode(mid)
            if (sameValue(prev.value, value)) return this._unlockMaybe()
          }
          node.setKey(mid, target)
          return this._append(root, seq, key, value)
        }

        if (c < 0) e = mid
        else s = mid + 1
      }

      const i = c < 0 ? e : s
      node = await node.getChildNode(i)
    }

    let needsSplit = !(await node.insertKey(target, value, null, newNode, encoding, cas))
    if (!node.changed) return this._unlockMaybe()

    while (needsSplit) {
      const parent = stack.pop()
      const { median, right } = await node.split()

      if (parent) {
        needsSplit = !(await parent.insertKey(median, value, right, null, encoding, null))
        node = parent
      } else {
        root = TreeNode.create(node.block)
        root.changed = true
        root.keys.push(median)
        root.children.push(new Child(0, 0, node), new Child(0, 0, right))
        needsSplit = false
      }
    }

    return this._append(root, seq, key, value)
  }

  async del(key, opts) {
    const release = this.batchLock ? await this.batchLock() : null
    const cas = (opts && opts.cas) || null
    const encoding = this._getEncoding(opts)

    if (!this.locked) await this.lock()
    if (!release) return this._del(key, encoding, cas)

    try {
      return await this._del(key, encoding, cas)
    } finally {
      release()
    }
  }

  async _del(key, encoding, cas) {
    const delNode = {
      seq: 0,
      key,
      value: null
    }

    key = enc(encoding.key, key)

    const stack = []

    let node = await this.getRoot(true)
    if (!node) return this._unlockMaybe()

    const seq = (delNode.seq = this.core.length + this.length)

    while (true) {
      stack.push(node)

      let s = 0
      let e = node.keys.length
      let c

      while (s < e) {
        const mid = (s + e) >> 1
        c = b4a.compare(key, await node.getKey(mid))

        if (c === 0) {
          if (cas) {
            const prev = await node.getKeyNode(mid)
            if (!(await cas(prev.final(encoding), delNode))) return this._unlockMaybe()
          }
          if (node.children.length) await setKeyToNearestLeaf(node, mid, stack)
          else node.removeKey(mid)
          // we mark these as changed late, so we don't rewrite them if it is a 404
          for (const node of stack) node.changed = true
          return this._append(await rebalance(stack), seq, key, null)
        }

        if (c < 0) e = mid
        else s = mid + 1
      }

      if (!node.children.length) return this._unlockMaybe()

      const i = c < 0 ? e : s
      node = await node.getChildNode(i)
    }
  }

  async _closeSnapshot() {
    if (this.isSnapshot) {
      await this.core.close()
      this._finalize()
    }
  }

  async close() {
    if (this.isSnapshot) return this._closeSnapshot()

    this.root = null
    if (this.blocks) this.blocks.clear()
    this.length = 0
    this._unlock()
  }

  destroy() {
    // compat, remove later
    this.close().catch(noop)
  }

  toBlocks() {
    if (this.appending) return this.appending

    const batch = new Array(this.length)

    for (let i = 0; i < this.length; i++) {
      const seq = this.core.length + i
      const { pendingIndex, key, value } = this.blocks.get(seq)

      if (i < this.length - 1) {
        pendingIndex[0] = null
        let j = 0

        while (j < pendingIndex.length) {
          const idx = pendingIndex[j]
          if (idx !== null && idx.seq === seq) {
            idx.offset = j++
            continue
          }
          if (j === pendingIndex.length - 1) pendingIndex.pop()
          else pendingIndex[j] = pendingIndex.pop()
        }
      }

      batch[i] = Node.encode({
        key,
        value,
        index: deflate(pendingIndex)
      })
    }

    this.appending = batch
    return batch
  }

  flush() {
    if (!this.length) return this.close()

    const batch = this.toBlocks()

    this.root = null
    this.blocks.clear()
    this.length = 0

    return this._appendBatch(batch)
  }

  _unlockMaybe() {
    if (this.autoFlush) this._unlock()
  }

  _unlock() {
    const locked = this.locked
    this.locked = null
    if (locked !== null) locked()
    this._finalize()
  }

  _finalize() {
    // technically finalize can be called more than once, so here we just check if we already have been removed
    if (this.index >= this.tree._batches.length || this.tree._batches[this.index] !== this) return
    const top = this.tree._batches.pop()
    if (top === this) return
    top.index = this.index
    this.tree._batches[top.index] = top
  }

  _append(root, seq, key, value) {
    const index = []
    root.indexChanges(index, seq)
    index[0] = new Child(seq, 0, root)

    if (!this.autoFlush) {
      const block = new BatchEntry(seq, this, key, value, index)
      root.block = block
      this.root = root
      this.length++
      this.blocks.set(seq, block)

      root.updateChildren(seq, block)
      return
    }

    return this._appendBatch(
      Node.encode({
        key,
        value,
        index: deflate(index)
      })
    )
  }

  async _appendBatch(raw) {
    try {
      await this.core.append(raw)
    } finally {
      this._unlock()
    }
  }
}

class EntryWatcher extends ReadyResource {
  constructor(bee, key, opts = {}) {
    super()

    this.keyEncoding = opts.keyEncoding || bee.keyEncoding
    this.valueEncoding = opts.valueEncoding || bee.valueEncoding

    this.index = bee._entryWatchers.push(this) - 1
    this.bee = bee

    this.key = key
    this.node = null

    this._forceUpdate = false
    this._debouncedUpdate = debounce(this._processUpdate.bind(this))
  }

  _close() {
    const top = this.bee._entryWatchers.pop()
    if (top !== this) {
      top.index = this.index
      this.bee._entryWatchers[top.index] = top
    }
  }

  _onappend() {
    this._debouncedUpdate()
  }

  _ontruncate() {
    this._forceUpdate = true
    this._debouncedUpdate()
  }

  async _processUpdate() {
    const force = this._forceUpdate
    this._forceUpdate = false

    let newNode
    try {
      newNode = await this.bee.get(this.key, {
        keyEncoding: this.keyEncoding,
        valueEncoding: this.valueEncoding
      })
    } catch (e) {
      if (e.code === 'SNAPSHOT_NOT_AVAILABLE') {
        // There was a truncate event before the get resolved
        // So this handler will run again anyway
        return
      } else if (this.bee.closing) {
        this.close().catch(safetyCatch)
        return
      }
      this.emit('error', e)
      return
    }

    if (force || newNode?.seq !== this.node?.seq) {
      this.node = newNode
      this.emit('update')
    }
  }
}

class Watcher extends ReadyResource {
  constructor(bee, range, opts = {}) {
    super()

    this.keyEncoding = opts.keyEncoding || bee.keyEncoding
    this.valueEncoding = opts.valueEncoding || bee.valueEncoding
    this.index = bee._watchers.push(this) - 1
    this.bee = bee
    this.core = bee.core

    this.latestDiff = 0
    this.range = range
    this.map = opts.map || defaultWatchMap

    this.current = null
    this.previous = null
    this.currentMapped = null
    this.previousMapped = null
    this.stream = null

    this._lock = mutexify()
    this._flowing = false
    this._resolveOnChange = null
    this._differ = opts.differ || defaultDiffer
    this._eager = !!opts.eager
    this._onchange = opts.onchange || null

    this.on('newListener', autoFlowOnUpdate)

    this.ready().catch(safetyCatch)
  }

  async _consume() {
    if (this._flowing) return
    try {
      for await (const _ of this) {
      } // eslint-disable-line
    } catch {}
  }

  async _open() {
    await this.bee.ready()

    const opts = {
      keyEncoding: this.keyEncoding,
      valueEncoding: this.valueEncoding
    }

    // Point from which to start watching
    this.current = this._eager ? this.bee.checkout(1, opts) : this.bee.snapshot(opts)
    await this.current.ready()

    if (this._onchange) {
      if (this._eager) await this._onchange()
      this._consume()
    }
  }

  [Symbol.asyncIterator]() {
    this._flowing = true
    return this
  }

  _ontruncate() {
    this._onappend()
  }

  _onappend() {
    const resolve = this._resolveOnChange
    this._resolveOnChange = null
    if (resolve) resolve()
  }

  async _waitForChanges() {
    if (this.current.version < this.bee.version || this.closing) return

    await new Promise((resolve) => {
      this._resolveOnChange = resolve
    })
  }

  async next() {
    try {
      return await this._next()
    } catch (err) {
      if (this.closing) return { value: undefined, done: true }
      await this.close()
      throw err
    }
  }

  async _next() {
    const release = await this._lock()

    try {
      if (this.closing) return { value: undefined, done: true }

      if (!this.opened) await this.ready()

      while (true) {
        await this._waitForChanges()

        if (this.closing) return { value: undefined, done: true }

        await this._closePrevious()
        this.previous = this.current.snapshot()

        await this._closeCurrent()
        this.current = this.bee.snapshot({
          keyEncoding: this.keyEncoding,
          valueEncoding: this.valueEncoding
        })

        await this.current.ready()
        await this.previous.ready()

        if (this.current.core.fork !== this.previous.core.fork) {
          return await this._yield()
        }

        this.stream = this._differ(this.current, this.previous, this.range)

        try {
          for await (const data of this.stream) {
            // eslint-disable-line
            return await this._yield()
          }
        } finally {
          this.stream = null
        }
      }
    } finally {
      release()
    }
  }

  async _yield() {
    this.currentMapped = this.map(this.current)
    this.previousMapped = this.map(this.previous)

    if (this._onchange) {
      try {
        await this._onchange()
      } catch (err) {
        safetyCatch(err)
      }
    }

    this.emit('update')
    return { done: false, value: [this.currentMapped, this.previousMapped] }
  }

  async return() {
    await this.close()
    return { done: true }
  }

  async _close() {
    const top = this.bee._watchers.pop()
    if (top !== this) {
      top.index = this.index
      this.bee._watchers[top.index] = top
    }

    if (this.stream && !this.stream.destroying) {
      this.stream.destroy()
    }

    this._onappend() // Continue execution being closed

    await this._closeCurrent().catch(safetyCatch)
    await this._closePrevious().catch(safetyCatch)

    const release = await this._lock()
    release()
  }

  destroy() {
    return this.close()
  }

  async _closeCurrent() {
    if (this.currentMapped) await this.currentMapped.close()
    if (this.current) await this.current.close()
    this.current = this.currentMapped = null
  }

  async _closePrevious() {
    if (this.previousMapped) await this.previousMapped.close()
    if (this.previous) await this.previous.close()
    this.previous = this.previousMapped = null
  }
}

function autoFlowOnUpdate(name) {
  if (name === 'update') this._consume()
}

function defaultWatchMap(snapshot) {
  return snapshot
}

async function leafSize(node, goLeft) {
  while (node.children.length) node = await node.getChildNode(goLeft ? 0 : node.children.length - 1)
  return node.keys.length
}

async function setKeyToNearestLeaf(node, index, stack) {
  let [left, right] = await Promise.all([node.getChildNode(index), node.getChildNode(index + 1)])
  const [ls, rs] = await Promise.all([leafSize(left, false), leafSize(right, true)])

  if (ls < rs) {
    // if fewer leaves on the left
    stack.push(right)
    while (right.children.length) stack.push((right = right.children[0].value))
    node.keys[index] = right.keys.shift()
  } else {
    // if fewer leaves on the right
    stack.push(left)
    while (left.children.length) stack.push((left = left.children[left.children.length - 1].value))
    node.keys[index] = left.keys.pop()
  }
}

async function rebalance(stack) {
  const root = stack[0]

  while (stack.length > 1) {
    const node = stack.pop()
    const parent = stack[stack.length - 1]

    if (node.keys.length >= MIN_KEYS) return root

    let { left, index, right } = await node.siblings(parent)

    // maybe borrow from left sibling?
    if (left && left.keys.length > MIN_KEYS) {
      left.changed = true
      node.keys.unshift(parent.keys[index - 1])
      if (left.children.length) node.children.unshift(left.children.pop())
      parent.keys[index - 1] = left.keys.pop()
      return root
    }

    // maybe borrow from right sibling?
    if (right && right.keys.length > MIN_KEYS) {
      right.changed = true
      node.keys.push(parent.keys[index])
      if (right.children.length) node.children.push(right.children.shift())
      parent.keys[index] = right.keys.shift()
      return root
    }

    // merge node with another sibling
    if (left) {
      index--
      right = node
    } else {
      left = node
    }

    left.merge(right, parent.keys[index])
    parent.removeKey(index)
  }

  // check if the tree shrunk
  if (!root.keys.length && root.children.length) return root.getChildNode(0)
  return root
}

function iteratorToStream(ite, signal) {
  let done
  let closing

  const rs = new Readable({
    signal,
    open(cb) {
      done = cb
      ite.open().then(fin, fin)
    },
    read(cb) {
      done = cb
      ite.next().then(push, fin)
    },
    predestroy() {
      closing = ite.close()
      closing.catch(noop)
    },
    destroy(cb) {
      done = cb
      if (!closing) closing = ite.close()
      closing.then(fin, fin)
    }
  })

  return rs

  function fin(err) {
    done(err)
  }

  function push(val) {
    rs.push(val)
    done(null)
  }
}

async function iteratorPeek(ite) {
  try {
    await ite.open()
    return await ite.next()
  } finally {
    await ite.close()
  }
}

function encRange(e, opts) {
  if (!e) return opts

  if (e.encodeRange) {
    const r = e.encodeRange({
      gt: opts.gt,
      gte: opts.gte,
      lt: opts.lt,
      lte: opts.lte
    })
    opts.gt = r.gt
    opts.gte = r.gte
    opts.lt = r.lt
    opts.lte = r.lte
    return opts
  }

  if (opts.gt !== undefined) opts.gt = enc(e, opts.gt)
  if (opts.gte !== undefined) opts.gte = enc(e, opts.gte)
  if (opts.lt !== undefined) opts.lt = enc(e, opts.lt)
  if (opts.lte !== undefined) opts.lte = enc(e, opts.lte)
  if (opts.sub && !opts.gt && !opts.gte) opts.gt = enc(e, SEP)
  if (opts.sub && !opts.lt && !opts.lte) opts.lt = bump(enc(e, EMPTY))

  return opts
}

function bump(key) {
  // key should have been copied by enc above before hitting this
  key[key.length - 1]++
  return key
}

function enc(e, v) {
  if (v === undefined || v === null) return null
  if (e !== null) return e.encode(v)
  if (typeof v === 'string') return b4a.from(v)
  return v
}

function prefixEncoding(prefix, keyEncoding) {
  return {
    encode(key) {
      return b4a.concat([prefix, b4a.isBuffer(key) ? key : enc(keyEncoding, key)])
    },
    decode(key) {
      const sliced = key.slice(prefix.length, key.length)
      return keyEncoding ? keyEncoding.decode(sliced) : sliced
    }
  }
}

function copyEntry(entry) {
  let key = entry.key
  let value = entry.value
  let index = entry.index

  // key, value and index all refer to the same buffer (one hypercore block)
  // If together they are larger than half the buffer's byteLength,
  // this means that they got their own private slab (see Buffer.allocUnsafe docs)
  // so no need to unslab
  const size =
    key.byteLength +
    (value === null ? 0 : value.byteLength) +
    (index === null ? 0 : index.byteLength)
  if (2 * size < key.buffer.byteLength) {
    const [newKey, newValue, newIndex] = unslabAll([entry.key, entry.value, entry.index])
    key = newKey
    value = newValue
    index = newIndex
  }

  return {
    key,
    value,
    index,
    inflated: null
  }
}

function defaultDiffer(currentSnap, previousSnap, opts) {
  return currentSnap.createDiffStream(previousSnap, opts)
}

function toNull() {
  return null
}

function getBackingCore(core) {
  if (core.core) return core
  if (core.getBackingCore) return core.getBackingCore().session
  return null
}

function sameValue(a, b) {
  return a === b || (a !== null && b !== null && b4a.equals(a, b))
}

function noop() {}

function getExtension(db, opts) {
  if (opts.extension === false) return null
  if (opts.extension && opts.extension !== true) return opts.extension
  return Extension.register(db)
}

async function isLinked(batch, block) {
  const seq = block.seq
  block.inflate()

  const keys = [block.key]
  const wait = batch.options.wait

  for (const l of block.index.levels) {
    if (!l.keys.length) continue
    batch.options.wait = false
    try {
      keys.push(await batch.getKey(l.keys[0].seq))
    } catch {}
    batch.options.wait = wait
  }

  for (const k of keys) {
    if (await batch.links(k, seq)) return true
  }

  if (batch.core.closing) throw new Error('Core is closed')

  return false
}

module.exports = Hyperbee
const b4a = require('b4a')

class SubTree {
  constructor(node, parent) {
    this.node = node
    this.parent = parent

    this.isKey = node.children.length === 0
    this.i = this.isKey ? 1 : 0
    this.n = 0

    const child = this.isKey ? null : this.node.children[0]
    this.seq = child !== null ? child.seq : this.node.keys[0].seq
    this.offset = child !== null ? child.offset : 0
  }

  next() {
    this.i++
    this.isKey = (this.i & 1) === 1
    if (!this.isKey && !this.node.children.length) this.i++
    return this.update()
  }

  async bisect(key, incl) {
    let s = 0
    let e = this.node.keys.length
    let c

    while (s < e) {
      const mid = (s + e) >> 1
      c = cmp(key, await this.node.getKey(mid))

      if (c === 0) {
        if (incl) this.i = mid * 2 + 1
        else this.i = mid * 2 + (this.node.children.length ? 2 : 3)
        return true
      }

      if (c < 0) e = mid
      else s = mid + 1
    }

    const i = c < 0 ? e : s
    this.i = 2 * i + (this.node.children.length ? 0 : 1)
    return this.node.children.length === 0
  }

  update() {
    this.isKey = (this.i & 1) === 1
    this.n = this.i >> 1
    if (this.n >= (this.isKey ? this.node.keys.length : this.node.children.length)) return false
    const child = this.isKey ? null : this.node.children[this.n]
    this.seq = child !== null ? child.seq : this.node.keys[this.n].seq
    this.offset = child !== null ? child.offset : 0
    return true
  }

  async key() {
    return this.n < this.node.keys.length
      ? this.node.getKey(this.n)
      : this.parent && this.parent.key()
  }

  async compare(tree) {
    const [a, b] = await Promise.all([this.key(), tree.key()])
    return cmp(a, b)
  }
}

class TreeIterator {
  constructor(batch, opts) {
    this.batch = batch
    this.stack = []
    this.lt = opts.lt || opts.lte || null
    this.lte = !!opts.lte
    this.gt = opts.gt || opts.gte || null
    this.gte = !!opts.gte
    this.seeking = !!this.gt
    this.encoding = opts.encoding || batch.encoding
  }

  async open() {
    const node = await this.batch.getRoot(false)
    if (!node || !node.keys.length) return
    const tree = new SubTree(node, null)
    if (this.seeking && !(await this._seek(tree))) return
    this.stack.push(tree)
  }

  async _seek(tree) {
    const done = await tree.bisect(this.gt, this.gte)
    const oob = !tree.update()
    if (done || oob) {
      this.seeking = false
      if (oob) return false
    }
    return true
  }

  peek() {
    if (!this.stack.length) return null
    return this.stack[this.stack.length - 1]
  }

  skip() {
    if (!this.stack.length) return
    if (!this.stack[this.stack.length - 1].next()) this.stack.pop()
  }

  async nextKey() {
    let n = null
    while (this.stack.length && n === null) n = await this.next()
    if (n === null) return null
    if (!this.lt) return n.final(this.encoding)

    const c = cmp(n.key, this.lt)
    if (this.lte ? c <= 0 : c < 0) return n.final(this.encoding)
    this.stack = []
    return null
  }

  async next() {
    if (!this.stack.length) return null

    const top = this.stack[this.stack.length - 1]
    const { isKey, n, seq } = top

    if (!top.next()) {
      this.stack.pop()
    }

    if (isKey) {
      this.seeking = false
      return this.batch.getBlock(seq)
    }

    const child = await top.node.getChildNode(n)
    top.node.children[n] = null // unlink to save memory
    const tree = new SubTree(child, top)
    if (this.seeking && !(await this._seek(tree))) return null
    this.stack.push(tree)

    return null
  }

  close() {
    return this.batch._closeSnapshot()
  }
}

module.exports = class DiffIterator {
  constructor(left, right, opts = {}) {
    this.left = new TreeIterator(left, opts)
    this.right = new TreeIterator(right, opts)
    this.limit = typeof opts.limit === 'number' ? opts.limit : -1
  }

  async open() {
    await Promise.all([this.left.open(), this.right.open()])
  }

  async next() {
    if (this.limit === 0) return null
    const res = await this._next()
    if (!res || (res.left === null && res.right === null)) return null
    this.limit--
    return res
  }

  async _next() {
    const a = this.left
    const b = this.right

    while (true) {
      const [l, r] = await Promise.all([a.peek(), b.peek()])

      if (!l && !r) return null
      if (!l) return { left: null, right: await b.nextKey() }
      if (!r) return { left: await a.nextKey(), right: null }

      if (l.seq === r.seq && l.isKey === r.isKey && l.offset === r.offset) {
        a.skip()
        b.skip()
        continue
      }

      const c = await l.compare(r)

      if (l.isKey && !r.isKey) {
        await b.next()
        continue
      }

      if (!l.isKey && r.isKey) {
        await a.next()
        continue
      }

      if (l.isKey && r.isKey) {
        if (c === 0) return { left: await a.nextKey(), right: await b.nextKey() }
        if (c < 0) return { left: await a.nextKey(), right: null }
        return { left: null, right: await b.nextKey() }
      }

      if (c === 0) await Promise.all([a.next(), b.next()])
      else if (c < 0) await b.next()
      else await a.next()
    }
  }

  async close() {
    await Promise.all([this.left.close(), this.right.close()])
  }
}

function cmp(a, b) {
  if (!a) return b ? 1 : 0
  if (!b) return a ? -1 : 0
  return b4a.compare(a, b)
}
module.exports = class HistoryIterator {
  constructor(batch, opts = {}) {
    this.batch = batch
    this.options = opts
    this.live = !!opts.live
    this.gte = 0
    this.lt = 0
    this.reverse = !!opts.reverse
    this.limit = typeof opts.limit === 'number' ? opts.limit : -1
    this.encoding = opts.encoding || batch.encoding
    if (this.live && this.reverse) {
      throw new Error('Cannot have both live and reverse enabled')
    }
  }

  async open() {
    await this.batch.getRoot(false) // does the update dance
    this.gte = gte(this.options, this.batch.version)
    this.lt = this.live ? Infinity : lt(this.options, this.batch.version)
  }

  async next() {
    if (this.limit === 0) return null
    if (this.limit > 0) this.limit--

    if (this.gte >= this.lt) return null

    if (this.reverse) {
      if (this.lt <= 1) return null
      return final(await this.batch.getBlock(--this.lt), this.encoding)
    }

    return final(await this.batch.getBlock(this.gte++), this.encoding)
  }

  close() {
    return this.batch._closeSnapshot()
  }
}

function final(node, encoding) {
  const type = node.isDeletion() ? 'del' : 'put'
  return { type, ...node.final(encoding) }
}

function gte(opts, version) {
  if (opts.gt) return (opts.gt < 0 ? opts.gt + version : opts.gt) + 1
  const gte = opts.gte || opts.since || 1
  return gte < 0 ? gte + version : gte
}

function lt(opts, version) {
  if (opts.lte === 0 || opts.lt === 0 || opts.end === 0) return 0
  if (opts.lte) return (opts.lte < 0 ? opts.lte + version : opts.lte) + 1
  const lt = opts.lt || opts.end || version
  return lt < 0 ? lt + version : lt
}
module.exports = class LocalBlocksIterator {
  constructor(batch, opts = {}) {
    this.batch = batch
    this.options = opts
    this.gte = 0
    this.lt = 0
    this.limit = typeof opts.limit === 'number' ? opts.limit : -1
  }

  async open() {
    await this.batch.getRoot(false) // does the update dance
    this.gte = gte(this.options, this.batch.version)
    this.lt = lt(this.options, this.batch.version)
  }

  async next() {
    if (this.limit === 0) return null
    if (this.limit > 0) this.limit--

    while (this.gte < this.lt) {
      try {
        return await this.batch.getBlock(this.gte++)
      } catch {
        continue
      }
    }

    return null
  }

  close() {
    return this.batch._closeSnapshot()
  }
}

function gte(opts, version) {
  if (opts.gt) return (opts.gt < 0 ? opts.gt + version : opts.gt) + 1
  const gte = opts.gte || opts.since || 1
  return gte < 0 ? gte + version : gte
}

function lt(opts, version) {
  if (opts.lte === 0 || opts.lt === 0 || opts.end === 0) return 0
  if (opts.lte) return (opts.lte < 0 ? opts.lte + version : opts.lte) + 1
  const lt = opts.lt || opts.end || version
  return lt < 0 ? lt + version : lt
}
const b4a = require('b4a')

module.exports = class RangeIterator {
  constructor(batch, encoding, opts = {}) {
    this.batch = batch
    this.stack = []
    this.opened = false
    this.encoding = encoding || batch.encoding

    this._limit = typeof opts.limit === 'number' ? opts.limit : -1
    this._gIncl = !opts.gt
    this._gKey = opts.gt || opts.gte || null
    this._lIncl = !opts.lt
    this._lKey = opts.lt || opts.lte || null
    this._reverse = !!opts.reverse
    this._version = 0
    this._checkpoint = opts.checkpoint && opts.checkpoint.length ? opts.checkpoint : null
    this._nexting = false
    this._closed = false
  }

  snapshot(version = this.batch.version) {
    const checkpoint = []
    for (const s of this.stack) {
      let { node, i } = s
      if (this._nexting && s === this.stack[this.stack.length - 1]) {
        i = this._reverse ? i + 1 : i - 1
      }
      if (!node.block) continue
      if (i < 0) continue
      checkpoint.push(node.block.seq, node.offset, i)
    }

    return {
      version,
      gte: this._gIncl ? this._gKey : null,
      gt: this._gIncl ? null : this._gKey,
      lte: this._lIncl ? this._lKey : null,
      lt: this._lIncl ? null : this._lKey,
      limit: this._limit,
      reverse: this._reverse,
      ended: this.opened && !checkpoint.length,
      checkpoint: this.opened ? checkpoint : []
    }
  }

  async open() {
    await this._open()
    this.opened = true
  }

  async _open() {
    if (this._checkpoint) {
      for (let j = 0; j < this._checkpoint.length; j += 3) {
        const seq = this._checkpoint[j]
        const offset = this._checkpoint[j + 1]
        const i = this._checkpoint[j + 2]
        this.stack.push({
          node: (await this.batch.getBlock(seq)).getTreeNode(offset),
          i
        })
      }
      return
    }

    this._nexting = true

    let node = await this.batch.getRoot(false)
    if (!node) {
      this._nexting = false
      return
    }

    const incl = this._reverse ? this._lIncl : this._gIncl
    const start = this._reverse ? this._lKey : this._gKey

    if (!start) {
      this.stack.push({ node, i: this._reverse ? node.keys.length << 1 : 0 })
      this._nexting = false
      this._preloadQuery()
      return
    }

    while (true) {
      const entry = { node, i: this._reverse ? node.keys.length << 1 : 0 }

      let s = 0
      let e = node.keys.length
      let c

      while (s < e) {
        const mid = (s + e) >> 1
        c = b4a.compare(start, await node.getKey(mid))

        if (c === 0) {
          if (incl) entry.i = mid * 2 + 1
          else entry.i = mid * 2 + (this._reverse ? 0 : 2)
          this.stack.push(entry)
          this._nexting = false
          this._preloadQuery()
          return
        }

        if (c < 0) e = mid
        else s = mid + 1
      }

      const i = c < 0 ? e : s
      entry.i = 2 * i + (this._reverse ? -1 : 1)

      if (entry.i >= 0 && entry.i <= node.keys.length << 1) this.stack.push(entry)
      if (!node.children.length) {
        this._nexting = false
        this._preloadQuery()
        return
      }

      node = await node.getChildNode(i)
    }
  }

  _preloadQuery() {
    const max = { nodes: 0, max: 2048 }

    if (this._limit === -1 && !this._reverse && this.stack.length) {
      for (const s of this.stack) {
        const k = (s.i - (s.i & 1)) / 2
        this._preload(s.node, k + 1, this._lKey, max).catch(noop)
      }
    }
  }

  async _preload(node, i, end, max) {
    for (; i < node.keys.length; i++) {
      const key = node.keys[i]
      const block = await this.batch.getBlock(key.seq)
      if (this._closed) return
      const c = end ? b4a.compare(block.key, end) : -1
      if (c >= 0 || max.nodes >= max.max || i >= node.children.length) return
      max.nodes++
      const next = await node.getChildNode(i)
      if (this._closed) return
      this._preload(next, 0, end, max).catch(noop)
    }

    if (node.children.length && max.nodes < max.max) {
      const next = await node.getChildNode(node.children.length - 1)
      if (this._closed) return
      this._preload(next, 0, end, max).catch(noop)
    }
  }

  async next() {
    // TODO: this nexting flag is only needed if someone asks for a snapshot during
    // a lookup (ie the extension, pretty important...).
    // A better solution would be to refactor this so top.i is incremented eagerly
    // to get the current block instead of the way it is done now (++i vs i++)
    this._nexting = true

    const end = this._reverse ? this._gKey : this._lKey
    const incl = this._reverse ? this._gIncl : this._lIncl

    while (this.stack.length && (this._limit === -1 || this._limit > 0)) {
      const top = this.stack[this.stack.length - 1]
      const isKey = (top.i & 1) === 1
      const n = this._reverse ? (top.i < 0 ? top.node.keys.length : top.i-- >> 1) : top.i++ >> 1

      if (!isKey) {
        if (!top.node.children.length) continue
        const node = await top.node.getChildNode(n)
        if (top.node.block.seq < this.batch.core.length) {
          top.node.children[n].value = null // unlink it to save memory
        }
        this.stack.push({ i: this._reverse ? node.keys.length << 1 : 0, node })
        continue
      }

      if (n >= top.node.keys.length) {
        this.stack.pop()
        continue
      }

      const key = top.node.keys[n]
      const block = await this.batch.getBlock(key.seq)
      if (end) {
        const c = b4a.compare(block.key, end)
        if (c === 0 ? !incl : this._reverse ? c < 0 : c > 0) {
          this._limit = 0
          break
        }
      }
      if (this._limit > 0) this._limit--
      this._nexting = false
      return block.final(this.encoding)
    }

    this._nexting = false
    return null
  }

  close() {
    this._closed = true
    return this.batch._closeSnapshot()
  }
}

function noop() {}
const { Extension } = require('./messages')

// const MAX_ACTIVE = 32
const FLUSH_BATCH = 128
const MAX_PASSIVE_BATCH = 2048
const MAX_ACTIVE_BATCH = MAX_PASSIVE_BATCH + FLUSH_BATCH

class Batch {
  constructor(outgoing, from) {
    this.blocks = []
    this.start = 0
    this.end = 0
    this.outgoing = outgoing
    this.from = from
  }

  push(seq) {
    const len = this.blocks.push(seq)
    if (len === 1 || seq < this.start) this.start = seq
    if (len === 1 || seq >= this.end) this.end = seq + 1
    if (len >= FLUSH_BATCH) {
      this.send()
      this.clear()
    }
  }

  send() {
    if (!this.blocks.length) return
    this.outgoing.send(
      Extension.encode({
        cache: { blocks: this.blocks, start: this.start, end: this.end }
      }),
      this.from
    )
  }

  clear() {
    this.start = this.end = 0
    this.blocks = []
  }
}

class HyperbeeExtension {
  constructor(db) {
    this.encoding = null
    this.outgoing = null
    this.db = db
    this.active = 0
  }

  get(version, key) {
    this.outgoing.broadcast(Extension.encode({ get: { version, key } }))
  }

  iterator(snapshot) {
    if (snapshot.ended) return
    if (snapshot.limit === 0) return
    if (snapshot.limit === -1) snapshot.limit = 0
    this.outgoing.broadcast(Extension.encode({ iterator: snapshot }))
  }

  onmessage(buf, from) {
    // TODO: handle max active extension messages
    // this.active++

    const message = decode(buf)
    if (!message) return

    if (message.cache) this.oncache(message.cache, from)
    if (message.get) this.onget(message.get, from)
    if (message.iterator) this.oniterator(message.iterator, from)
  }

  oncache(message, from) {
    if (!message.blocks.length) return
    this.db.core.download(message)
  }

  onget(message, from) {
    if (!message.version || message.version > this.db.version) return

    const b = new Batch(this.outgoing, from)
    const db = this.db.checkout(message.version)

    db.get(message.key, {
      extension: false,
      wait: false,
      update: false,
      onseq
    }).then(done, done)

    function done() {
      db.close().catch(noop)
      b.send()
    }

    function onseq(seq) {
      b.push(seq)
    }
  }

  async oniterator(message, from) {
    if (!message.version || message.version > this.db.version) return

    const b = new Batch(this.outgoing, from)
    const seqs = new Set()

    let skip = message.checkpoint.length
    let work = 0

    const db = this.db.checkout(message.version)
    const ite = db.createRangeIterator({
      ...message,
      wait: false,
      extension: false,
      update: false,
      limit: message.limit === 0 ? -1 : message.limit,
      onseq(seq) {
        if (skip && skip--) return
        if (seqs.has(seq)) return
        work++
        seqs.add(seq)
        b.push(seq)
      }
    })

    try {
      await ite.open()
      // eslint-disable-next-line no-unmodified-loop-condition
      while (work < MAX_ACTIVE_BATCH) {
        if (!(await ite.next())) break
      }
    } catch (_) {
      // do nothing
    } finally {
      ite.close().catch(noop)
      db.close().catch(noop)
      b.send()
    }
  }

  static register(db) {
    const e = new this(db)
    e.outgoing = db.core.registerExtension('hyperbee', e)
    return e
  }
}

HyperbeeExtension.BATCH_SIZE = MAX_PASSIVE_BATCH

module.exports = HyperbeeExtension

function decode(buf) {
  try {
    return Extension.decode(buf)
  } catch (err) {
    return null
  }
}

function noop() {}
// This file is auto generated by the protocol-buffers compiler

/* eslint-disable quotes */
/* eslint-disable indent */
/* eslint-disable no-redeclare */
/* eslint-disable camelcase */
/* eslint-disable no-var */

// Remember to `npm install --save protocol-buffers-encodings`
var encodings = require('protocol-buffers-encodings')
var b4a = require('b4a')
var varint = encodings.varint
var skip = encodings.skip

var YoloIndex = exports.YoloIndex = {
  buffer: true,
  encodingLength: null,
  encode: null,
  decode: null
}

var Header = exports.Header = {
  buffer: true,
  encodingLength: null,
  encode: null,
  decode: null
}

var Node = exports.Node = {
  buffer: true,
  encodingLength: null,
  encode: null,
  decode: null
}

var Extension = exports.Extension = {
  buffer: true,
  encodingLength: null,
  encode: null,
  decode: null
}

defineYoloIndex()
defineHeader()
defineNode()
defineExtension()

function defineYoloIndex () {
  var Level = YoloIndex.Level = {
    buffer: true,
    encodingLength: null,
    encode: null,
    decode: null
  }

  defineLevel()

  function defineLevel () {
    Level.encodingLength = encodingLength
    Level.encode = encode
    Level.decode = decode

    function encodingLength (obj) {
      var length = 0
      if (defined(obj.keys)) {
        var packedLen = 0
        for (var i = 0; i < obj.keys.length; i++) {
          if (!defined(obj.keys[i])) continue
          var len = encodings.varint.encodingLength(obj.keys[i])
          packedLen += len
        }
        if (packedLen) {
          length += 1 + packedLen + varint.encodingLength(packedLen)
        }
      }
      if (defined(obj.children)) {
        var packedLen = 0
        for (var i = 0; i < obj.children.length; i++) {
          if (!defined(obj.children[i])) continue
          var len = encodings.varint.encodingLength(obj.children[i])
          packedLen += len
        }
        if (packedLen) {
          length += 1 + packedLen + varint.encodingLength(packedLen)
        }
      }
      return length
    }

    function encode (obj, buf, offset) {
      if (!offset) offset = 0
      if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
      var oldOffset = offset
      if (defined(obj.keys)) {
        var packedLen = 0
        for (var i = 0; i < obj.keys.length; i++) {
          if (!defined(obj.keys[i])) continue
          packedLen += encodings.varint.encodingLength(obj.keys[i])
        }
        if (packedLen) {
          buf[offset++] = 10
          varint.encode(packedLen, buf, offset)
          offset += varint.encode.bytes
        }
        for (var i = 0; i < obj.keys.length; i++) {
          if (!defined(obj.keys[i])) continue
          encodings.varint.encode(obj.keys[i], buf, offset)
          offset += encodings.varint.encode.bytes
        }
      }
      if (defined(obj.children)) {
        var packedLen = 0
        for (var i = 0; i < obj.children.length; i++) {
          if (!defined(obj.children[i])) continue
          packedLen += encodings.varint.encodingLength(obj.children[i])
        }
        if (packedLen) {
          buf[offset++] = 18
          varint.encode(packedLen, buf, offset)
          offset += varint.encode.bytes
        }
        for (var i = 0; i < obj.children.length; i++) {
          if (!defined(obj.children[i])) continue
          encodings.varint.encode(obj.children[i], buf, offset)
          offset += encodings.varint.encode.bytes
        }
      }
      encode.bytes = offset - oldOffset
      return buf
    }

    function decode (buf, offset, end) {
      if (!offset) offset = 0
      if (!end) end = buf.length
      if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
      var oldOffset = offset
      var obj = {
        keys: [],
        children: []
      }
      while (true) {
        if (end <= offset) {
          decode.bytes = offset - oldOffset
          return obj
        }
        var prefix = varint.decode(buf, offset)
        offset += varint.decode.bytes
        var tag = prefix >> 3
        switch (tag) {
          case 1:
          var packedEnd = varint.decode(buf, offset)
          offset += varint.decode.bytes
          packedEnd += offset
          while (offset < packedEnd) {
            obj.keys.push(encodings.varint.decode(buf, offset))
            offset += encodings.varint.decode.bytes
          }
          break
          case 2:
          var packedEnd = varint.decode(buf, offset)
          offset += varint.decode.bytes
          packedEnd += offset
          while (offset < packedEnd) {
            obj.children.push(encodings.varint.decode(buf, offset))
            offset += encodings.varint.decode.bytes
          }
          break
          default:
          offset = skip(prefix & 7, buf, offset)
        }
      }
    }
  }

  YoloIndex.encodingLength = encodingLength
  YoloIndex.encode = encode
  YoloIndex.decode = decode

  function encodingLength (obj) {
    var length = 0
    if (defined(obj.levels)) {
      for (var i = 0; i < obj.levels.length; i++) {
        if (!defined(obj.levels[i])) continue
        var len = Level.encodingLength(obj.levels[i])
        length += varint.encodingLength(len)
        length += 1 + len
      }
    }
    return length
  }

  function encode (obj, buf, offset) {
    if (!offset) offset = 0
    if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
    var oldOffset = offset
    if (defined(obj.levels)) {
      for (var i = 0; i < obj.levels.length; i++) {
        if (!defined(obj.levels[i])) continue
        buf[offset++] = 10
        varint.encode(Level.encodingLength(obj.levels[i]), buf, offset)
        offset += varint.encode.bytes
        Level.encode(obj.levels[i], buf, offset)
        offset += Level.encode.bytes
      }
    }
    encode.bytes = offset - oldOffset
    return buf
  }

  function decode (buf, offset, end) {
    if (!offset) offset = 0
    if (!end) end = buf.length
    if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
    var oldOffset = offset
    var obj = {
      levels: []
    }
    while (true) {
      if (end <= offset) {
        decode.bytes = offset - oldOffset
        return obj
      }
      var prefix = varint.decode(buf, offset)
      offset += varint.decode.bytes
      var tag = prefix >> 3
      switch (tag) {
        case 1:
        var len = varint.decode(buf, offset)
        offset += varint.decode.bytes
        obj.levels.push(Level.decode(buf, offset, offset + len))
        offset += Level.decode.bytes
        break
        default:
        offset = skip(prefix & 7, buf, offset)
      }
    }
  }
}

function defineHeader () {
  var Metadata = Header.Metadata = {
    buffer: true,
    encodingLength: null,
    encode: null,
    decode: null
  }

  defineMetadata()

  function defineMetadata () {
    Metadata.encodingLength = encodingLength
    Metadata.encode = encode
    Metadata.decode = decode

    function encodingLength (obj) {
      var length = 0
      if (defined(obj.contentFeed)) {
        var len = encodings.bytes.encodingLength(obj.contentFeed)
        length += 1 + len
      }
      if (defined(obj.userData)) {
        var len = encodings.bytes.encodingLength(obj.userData)
        length += 1 + len
      }
      return length
    }

    function encode (obj, buf, offset) {
      if (!offset) offset = 0
      if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
      var oldOffset = offset
      if (defined(obj.contentFeed)) {
        buf[offset++] = 10
        encodings.bytes.encode(obj.contentFeed, buf, offset)
        offset += encodings.bytes.encode.bytes
      }
      if (defined(obj.userData)) {
        buf[offset++] = 18
        encodings.bytes.encode(obj.userData, buf, offset)
        offset += encodings.bytes.encode.bytes
      }
      encode.bytes = offset - oldOffset
      return buf
    }

    function decode (buf, offset, end) {
      if (!offset) offset = 0
      if (!end) end = buf.length
      if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
      var oldOffset = offset
      var obj = {
        contentFeed: null,
        userData: null
      }
      while (true) {
        if (end <= offset) {
          decode.bytes = offset - oldOffset
          return obj
        }
        var prefix = varint.decode(buf, offset)
        offset += varint.decode.bytes
        var tag = prefix >> 3
        switch (tag) {
          case 1:
          obj.contentFeed = encodings.bytes.decode(buf, offset)
          offset += encodings.bytes.decode.bytes
          break
          case 2:
          obj.userData = encodings.bytes.decode(buf, offset)
          offset += encodings.bytes.decode.bytes
          break
          default:
          offset = skip(prefix & 7, buf, offset)
        }
      }
    }
  }

  Header.encodingLength = encodingLength
  Header.encode = encode
  Header.decode = decode

  function encodingLength (obj) {
    var length = 0
    if (!defined(obj.protocol)) throw new Error("protocol is required")
    var len = encodings.string.encodingLength(obj.protocol)
    length += 1 + len
    if (defined(obj.metadata)) {
      var len = Metadata.encodingLength(obj.metadata)
      length += varint.encodingLength(len)
      length += 1 + len
    }
    return length
  }

  function encode (obj, buf, offset) {
    if (!offset) offset = 0
    if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
    var oldOffset = offset
    if (!defined(obj.protocol)) throw new Error("protocol is required")
    buf[offset++] = 10
    encodings.string.encode(obj.protocol, buf, offset)
    offset += encodings.string.encode.bytes
    if (defined(obj.metadata)) {
      buf[offset++] = 18
      varint.encode(Metadata.encodingLength(obj.metadata), buf, offset)
      offset += varint.encode.bytes
      Metadata.encode(obj.metadata, buf, offset)
      offset += Metadata.encode.bytes
    }
    encode.bytes = offset - oldOffset
    return buf
  }

  function decode (buf, offset, end) {
    if (!offset) offset = 0
    if (!end) end = buf.length
    if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
    var oldOffset = offset
    var obj = {
      protocol: "",
      metadata: null
    }
    var found0 = false
    while (true) {
      if (end <= offset) {
        if (!found0) throw new Error("Decoded message is not valid")
        decode.bytes = offset - oldOffset
        return obj
      }
      var prefix = varint.decode(buf, offset)
      offset += varint.decode.bytes
      var tag = prefix >> 3
      switch (tag) {
        case 1:
        obj.protocol = encodings.string.decode(buf, offset)
        offset += encodings.string.decode.bytes
        found0 = true
        break
        case 2:
        var len = varint.decode(buf, offset)
        offset += varint.decode.bytes
        obj.metadata = Metadata.decode(buf, offset, offset + len)
        offset += Metadata.decode.bytes
        break
        default:
        offset = skip(prefix & 7, buf, offset)
      }
    }
  }
}

function defineNode () {
  Node.encodingLength = encodingLength
  Node.encode = encode
  Node.decode = decode

  function encodingLength (obj) {
    var length = 0
    if (!defined(obj.index)) throw new Error("index is required")
    var len = encodings.bytes.encodingLength(obj.index)
    length += 1 + len
    if (!defined(obj.key)) throw new Error("key is required")
    var len = encodings.bytes.encodingLength(obj.key)
    length += 1 + len
    if (defined(obj.value)) {
      var len = encodings.bytes.encodingLength(obj.value)
      length += 1 + len
    }
    return length
  }

  function encode (obj, buf, offset) {
    if (!offset) offset = 0
    if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
    var oldOffset = offset
    if (!defined(obj.index)) throw new Error("index is required")
    buf[offset++] = 10
    encodings.bytes.encode(obj.index, buf, offset)
    offset += encodings.bytes.encode.bytes
    if (!defined(obj.key)) throw new Error("key is required")
    buf[offset++] = 18
    encodings.bytes.encode(obj.key, buf, offset)
    offset += encodings.bytes.encode.bytes
    if (defined(obj.value)) {
      buf[offset++] = 26
      encodings.bytes.encode(obj.value, buf, offset)
      offset += encodings.bytes.encode.bytes
    }
    encode.bytes = offset - oldOffset
    return buf
  }

  function decode (buf, offset, end) {
    if (!offset) offset = 0
    if (!end) end = buf.length
    if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
    var oldOffset = offset
    var obj = {
      index: null,
      key: null,
      value: null
    }
    var found0 = false
    var found1 = false
    while (true) {
      if (end <= offset) {
        if (!found0 || !found1) throw new Error("Decoded message is not valid")
        decode.bytes = offset - oldOffset
        return obj
      }
      var prefix = varint.decode(buf, offset)
      offset += varint.decode.bytes
      var tag = prefix >> 3
      switch (tag) {
        case 1:
        obj.index = encodings.bytes.decode(buf, offset)
        offset += encodings.bytes.decode.bytes
        found0 = true
        break
        case 2:
        obj.key = encodings.bytes.decode(buf, offset)
        offset += encodings.bytes.decode.bytes
        found1 = true
        break
        case 3:
        obj.value = encodings.bytes.decode(buf, offset)
        offset += encodings.bytes.decode.bytes
        break
        default:
        offset = skip(prefix & 7, buf, offset)
      }
    }
  }
}

function defineExtension () {
  var Get = Extension.Get = {
    buffer: true,
    encodingLength: null,
    encode: null,
    decode: null
  }

  var Iterator = Extension.Iterator = {
    buffer: true,
    encodingLength: null,
    encode: null,
    decode: null
  }

  var Cache = Extension.Cache = {
    buffer: true,
    encodingLength: null,
    encode: null,
    decode: null
  }

  defineGet()
  defineIterator()
  defineCache()

  function defineGet () {
    Get.encodingLength = encodingLength
    Get.encode = encode
    Get.decode = decode

    function encodingLength (obj) {
      var length = 0
      if (defined(obj.version)) {
        var len = encodings.varint.encodingLength(obj.version)
        length += 1 + len
      }
      if (defined(obj.key)) {
        var len = encodings.bytes.encodingLength(obj.key)
        length += 1 + len
      }
      return length
    }

    function encode (obj, buf, offset) {
      if (!offset) offset = 0
      if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
      var oldOffset = offset
      if (defined(obj.version)) {
        buf[offset++] = 8
        encodings.varint.encode(obj.version, buf, offset)
        offset += encodings.varint.encode.bytes
      }
      if (defined(obj.key)) {
        buf[offset++] = 18
        encodings.bytes.encode(obj.key, buf, offset)
        offset += encodings.bytes.encode.bytes
      }
      encode.bytes = offset - oldOffset
      return buf
    }

    function decode (buf, offset, end) {
      if (!offset) offset = 0
      if (!end) end = buf.length
      if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
      var oldOffset = offset
      var obj = {
        version: 0,
        key: null
      }
      while (true) {
        if (end <= offset) {
          decode.bytes = offset - oldOffset
          return obj
        }
        var prefix = varint.decode(buf, offset)
        offset += varint.decode.bytes
        var tag = prefix >> 3
        switch (tag) {
          case 1:
          obj.version = encodings.varint.decode(buf, offset)
          offset += encodings.varint.decode.bytes
          break
          case 2:
          obj.key = encodings.bytes.decode(buf, offset)
          offset += encodings.bytes.decode.bytes
          break
          default:
          offset = skip(prefix & 7, buf, offset)
        }
      }
    }
  }

  function defineIterator () {
    Iterator.encodingLength = encodingLength
    Iterator.encode = encode
    Iterator.decode = decode

    function encodingLength (obj) {
      var length = 0
      if (defined(obj.version)) {
        var len = encodings.varint.encodingLength(obj.version)
        length += 1 + len
      }
      if (defined(obj.gte)) {
        var len = encodings.bytes.encodingLength(obj.gte)
        length += 1 + len
      }
      if (defined(obj.gt)) {
        var len = encodings.bytes.encodingLength(obj.gt)
        length += 1 + len
      }
      if (defined(obj.lte)) {
        var len = encodings.bytes.encodingLength(obj.lte)
        length += 1 + len
      }
      if (defined(obj.lt)) {
        var len = encodings.bytes.encodingLength(obj.lt)
        length += 1 + len
      }
      if (defined(obj.limit)) {
        var len = encodings.varint.encodingLength(obj.limit)
        length += 1 + len
      }
      if (defined(obj.reverse)) {
        var len = encodings.bool.encodingLength(obj.reverse)
        length += 1 + len
      }
      if (defined(obj.checkpoint)) {
        var packedLen = 0
        for (var i = 0; i < obj.checkpoint.length; i++) {
          if (!defined(obj.checkpoint[i])) continue
          var len = encodings.varint.encodingLength(obj.checkpoint[i])
          packedLen += len
        }
        if (packedLen) {
          length += 1 + packedLen + varint.encodingLength(packedLen)
        }
      }
      return length
    }

    function encode (obj, buf, offset) {
      if (!offset) offset = 0
      if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
      var oldOffset = offset
      if (defined(obj.version)) {
        buf[offset++] = 8
        encodings.varint.encode(obj.version, buf, offset)
        offset += encodings.varint.encode.bytes
      }
      if (defined(obj.gte)) {
        buf[offset++] = 18
        encodings.bytes.encode(obj.gte, buf, offset)
        offset += encodings.bytes.encode.bytes
      }
      if (defined(obj.gt)) {
        buf[offset++] = 26
        encodings.bytes.encode(obj.gt, buf, offset)
        offset += encodings.bytes.encode.bytes
      }
      if (defined(obj.lte)) {
        buf[offset++] = 34
        encodings.bytes.encode(obj.lte, buf, offset)
        offset += encodings.bytes.encode.bytes
      }
      if (defined(obj.lt)) {
        buf[offset++] = 42
        encodings.bytes.encode(obj.lt, buf, offset)
        offset += encodings.bytes.encode.bytes
      }
      if (defined(obj.limit)) {
        buf[offset++] = 48
        encodings.varint.encode(obj.limit, buf, offset)
        offset += encodings.varint.encode.bytes
      }
      if (defined(obj.reverse)) {
        buf[offset++] = 56
        encodings.bool.encode(obj.reverse, buf, offset)
        offset += encodings.bool.encode.bytes
      }
      if (defined(obj.checkpoint)) {
        var packedLen = 0
        for (var i = 0; i < obj.checkpoint.length; i++) {
          if (!defined(obj.checkpoint[i])) continue
          packedLen += encodings.varint.encodingLength(obj.checkpoint[i])
        }
        if (packedLen) {
          buf[offset++] = 66
          varint.encode(packedLen, buf, offset)
          offset += varint.encode.bytes
        }
        for (var i = 0; i < obj.checkpoint.length; i++) {
          if (!defined(obj.checkpoint[i])) continue
          encodings.varint.encode(obj.checkpoint[i], buf, offset)
          offset += encodings.varint.encode.bytes
        }
      }
      encode.bytes = offset - oldOffset
      return buf
    }

    function decode (buf, offset, end) {
      if (!offset) offset = 0
      if (!end) end = buf.length
      if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
      var oldOffset = offset
      var obj = {
        version: 0,
        gte: null,
        gt: null,
        lte: null,
        lt: null,
        limit: 0,
        reverse: false,
        checkpoint: []
      }
      while (true) {
        if (end <= offset) {
          decode.bytes = offset - oldOffset
          return obj
        }
        var prefix = varint.decode(buf, offset)
        offset += varint.decode.bytes
        var tag = prefix >> 3
        switch (tag) {
          case 1:
          obj.version = encodings.varint.decode(buf, offset)
          offset += encodings.varint.decode.bytes
          break
          case 2:
          obj.gte = encodings.bytes.decode(buf, offset)
          offset += encodings.bytes.decode.bytes
          break
          case 3:
          obj.gt = encodings.bytes.decode(buf, offset)
          offset += encodings.bytes.decode.bytes
          break
          case 4:
          obj.lte = encodings.bytes.decode(buf, offset)
          offset += encodings.bytes.decode.bytes
          break
          case 5:
          obj.lt = encodings.bytes.decode(buf, offset)
          offset += encodings.bytes.decode.bytes
          break
          case 6:
          obj.limit = encodings.varint.decode(buf, offset)
          offset += encodings.varint.decode.bytes
          break
          case 7:
          obj.reverse = encodings.bool.decode(buf, offset)
          offset += encodings.bool.decode.bytes
          break
          case 8:
          var packedEnd = varint.decode(buf, offset)
          offset += varint.decode.bytes
          packedEnd += offset
          while (offset < packedEnd) {
            obj.checkpoint.push(encodings.varint.decode(buf, offset))
            offset += encodings.varint.decode.bytes
          }
          break
          default:
          offset = skip(prefix & 7, buf, offset)
        }
      }
    }
  }

  function defineCache () {
    Cache.encodingLength = encodingLength
    Cache.encode = encode
    Cache.decode = decode

    function encodingLength (obj) {
      var length = 0
      if (!defined(obj.start)) throw new Error("start is required")
      var len = encodings.varint.encodingLength(obj.start)
      length += 1 + len
      if (!defined(obj.end)) throw new Error("end is required")
      var len = encodings.varint.encodingLength(obj.end)
      length += 1 + len
      if (defined(obj.blocks)) {
        var packedLen = 0
        for (var i = 0; i < obj.blocks.length; i++) {
          if (!defined(obj.blocks[i])) continue
          var len = encodings.varint.encodingLength(obj.blocks[i])
          packedLen += len
        }
        if (packedLen) {
          length += 1 + packedLen + varint.encodingLength(packedLen)
        }
      }
      return length
    }

    function encode (obj, buf, offset) {
      if (!offset) offset = 0
      if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
      var oldOffset = offset
      if (!defined(obj.start)) throw new Error("start is required")
      buf[offset++] = 8
      encodings.varint.encode(obj.start, buf, offset)
      offset += encodings.varint.encode.bytes
      if (!defined(obj.end)) throw new Error("end is required")
      buf[offset++] = 16
      encodings.varint.encode(obj.end, buf, offset)
      offset += encodings.varint.encode.bytes
      if (defined(obj.blocks)) {
        var packedLen = 0
        for (var i = 0; i < obj.blocks.length; i++) {
          if (!defined(obj.blocks[i])) continue
          packedLen += encodings.varint.encodingLength(obj.blocks[i])
        }
        if (packedLen) {
          buf[offset++] = 26
          varint.encode(packedLen, buf, offset)
          offset += varint.encode.bytes
        }
        for (var i = 0; i < obj.blocks.length; i++) {
          if (!defined(obj.blocks[i])) continue
          encodings.varint.encode(obj.blocks[i], buf, offset)
          offset += encodings.varint.encode.bytes
        }
      }
      encode.bytes = offset - oldOffset
      return buf
    }

    function decode (buf, offset, end) {
      if (!offset) offset = 0
      if (!end) end = buf.length
      if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
      var oldOffset = offset
      var obj = {
        start: 0,
        end: 0,
        blocks: []
      }
      var found0 = false
      var found1 = false
      while (true) {
        if (end <= offset) {
          if (!found0 || !found1) throw new Error("Decoded message is not valid")
          decode.bytes = offset - oldOffset
          return obj
        }
        var prefix = varint.decode(buf, offset)
        offset += varint.decode.bytes
        var tag = prefix >> 3
        switch (tag) {
          case 1:
          obj.start = encodings.varint.decode(buf, offset)
          offset += encodings.varint.decode.bytes
          found0 = true
          break
          case 2:
          obj.end = encodings.varint.decode(buf, offset)
          offset += encodings.varint.decode.bytes
          found1 = true
          break
          case 3:
          var packedEnd = varint.decode(buf, offset)
          offset += varint.decode.bytes
          packedEnd += offset
          while (offset < packedEnd) {
            obj.blocks.push(encodings.varint.decode(buf, offset))
            offset += encodings.varint.decode.bytes
          }
          break
          default:
          offset = skip(prefix & 7, buf, offset)
        }
      }
    }
  }

  Extension.encodingLength = encodingLength
  Extension.encode = encode
  Extension.decode = decode

  function encodingLength (obj) {
    var length = 0
    if (defined(obj.cache)) {
      var len = Cache.encodingLength(obj.cache)
      length += varint.encodingLength(len)
      length += 1 + len
    }
    if (defined(obj.get)) {
      var len = Get.encodingLength(obj.get)
      length += varint.encodingLength(len)
      length += 1 + len
    }
    if (defined(obj.iterator)) {
      var len = Iterator.encodingLength(obj.iterator)
      length += varint.encodingLength(len)
      length += 1 + len
    }
    return length
  }

  function encode (obj, buf, offset) {
    if (!offset) offset = 0
    if (!buf) buf = b4a.allocUnsafe(encodingLength(obj))
    var oldOffset = offset
    if (defined(obj.cache)) {
      buf[offset++] = 10
      varint.encode(Cache.encodingLength(obj.cache), buf, offset)
      offset += varint.encode.bytes
      Cache.encode(obj.cache, buf, offset)
      offset += Cache.encode.bytes
    }
    if (defined(obj.get)) {
      buf[offset++] = 18
      varint.encode(Get.encodingLength(obj.get), buf, offset)
      offset += varint.encode.bytes
      Get.encode(obj.get, buf, offset)
      offset += Get.encode.bytes
    }
    if (defined(obj.iterator)) {
      buf[offset++] = 26
      varint.encode(Iterator.encodingLength(obj.iterator), buf, offset)
      offset += varint.encode.bytes
      Iterator.encode(obj.iterator, buf, offset)
      offset += Iterator.encode.bytes
    }
    encode.bytes = offset - oldOffset
    return buf
  }

  function decode (buf, offset, end) {
    if (!offset) offset = 0
    if (!end) end = buf.length
    if (!(end <= buf.length && offset <= buf.length)) throw new Error("Decoded message is not valid")
    var oldOffset = offset
    var obj = {
      cache: null,
      get: null,
      iterator: null
    }
    while (true) {
      if (end <= offset) {
        decode.bytes = offset - oldOffset
        return obj
      }
      var prefix = varint.decode(buf, offset)
      offset += varint.decode.bytes
      var tag = prefix >> 3
      switch (tag) {
        case 1:
        var len = varint.decode(buf, offset)
        offset += varint.decode.bytes
        obj.cache = Cache.decode(buf, offset, offset + len)
        offset += Cache.decode.bytes
        break
        case 2:
        var len = varint.decode(buf, offset)
        offset += varint.decode.bytes
        obj.get = Get.decode(buf, offset, offset + len)
        offset += Get.decode.bytes
        break
        case 3:
        var len = varint.decode(buf, offset)
        offset += varint.decode.bytes
        obj.iterator = Iterator.decode(buf, offset, offset + len)
        offset += Iterator.decode.bytes
        break
        default:
        offset = skip(prefix & 7, buf, offset)
      }
    }
  }
}

function defined (val) {
  return val !== null && val !== undefined && (typeof val !== 'number' || !isNaN(val))
}
{
  "name": "hyperbee",
  "version": "2.27.3",
  "description": "An append-only B-tree running on a Hypercore.",
  "main": "index.js",
  "files": [
    "index.js",
    "lib/**.js",
    "iterators/**.js"
  ],
  "dependencies": {
    "b4a": "^1.6.0",
    "codecs": "^3.0.0",
    "debounceify": "^1.0.0",
    "hypercore-errors": "^1.0.0",
    "mutexify": "^1.4.0",
    "protocol-buffers-encodings": "^1.2.0",
    "rache": "^1.0.0",
    "ready-resource": "^1.0.0",
    "resolve-reject-promise": "^1.1.0",
    "safety-catch": "^1.0.2",
    "streamx": "^2.12.4",
    "unslab": "^1.2.0"
  },
  "devDependencies": {
    "bare-process": "^4.2.2",
    "brittle": "^3.1.0",
    "hypercore": "^11.0.0",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "protocol-buffers": "^4.2.0",
    "sub-encoder": "^1.0.6",
    "tree-to-string": "^1.1.1"
  },
  "imports": {
    "process": {
      "bare": "bare-process",
      "default": "process"
    }
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test/*.js",
    "test:bare": "brittle-bare test/*.js",
    "protobuf": "protocol-buffers schema.proto -o ./lib/messages.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/hyperbee.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/hyperbee/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperbee"
}
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const b4a = require('b4a')

// https://en.wikipedia.org/wiki/Merkle_tree#Second_preimage_attack
const LEAF_TYPE = b4a.from([0])
const PARENT_TYPE = b4a.from([1])
const ROOT_TYPE = b4a.from([2])

const HYPERCORE = b4a.from('hypercore')

exports.keyPair = function (seed) {
  // key pairs might stay around for a while, so better not to use a default slab to avoid retaining it completely
  const slab = b4a.allocUnsafeSlow(
    sodium.crypto_sign_PUBLICKEYBYTES + sodium.crypto_sign_SECRETKEYBYTES
  )
  const publicKey = slab.subarray(0, sodium.crypto_sign_PUBLICKEYBYTES)
  const secretKey = slab.subarray(sodium.crypto_sign_PUBLICKEYBYTES)

  if (seed) sodium.crypto_sign_seed_keypair(publicKey, secretKey, seed)
  else sodium.crypto_sign_keypair(publicKey, secretKey)

  return {
    publicKey,
    secretKey
  }
}

exports.validateKeyPair = function (keyPair) {
  const pk = b4a.allocUnsafe(sodium.crypto_sign_PUBLICKEYBYTES)
  sodium.crypto_sign_ed25519_sk_to_pk(pk, keyPair.secretKey)
  return b4a.equals(pk, keyPair.publicKey)
}

exports.sign = function (message, secretKey) {
  // Dedicated slab for the signature, to avoid retaining unneeded mem and for security
  const signature = b4a.allocUnsafeSlow(sodium.crypto_sign_BYTES)
  sodium.crypto_sign_detached(signature, message, secretKey)
  return signature
}

exports.verify = function (message, signature, publicKey) {
  if (signature.byteLength !== sodium.crypto_sign_BYTES) return false
  if (publicKey.byteLength !== sodium.crypto_sign_PUBLICKEYBYTES) return false
  return sodium.crypto_sign_verify_detached(signature, message, publicKey)
}

exports.encrypt = function (message, publicKey) {
  const ciphertext = b4a.alloc(message.byteLength + sodium.crypto_box_SEALBYTES)
  sodium.crypto_box_seal(ciphertext, message, publicKey)
  return ciphertext
}

exports.decrypt = function (ciphertext, keyPair) {
  if (ciphertext.byteLength < sodium.crypto_box_SEALBYTES) return null

  const plaintext = b4a.alloc(ciphertext.byteLength - sodium.crypto_box_SEALBYTES)

  if (!sodium.crypto_box_seal_open(plaintext, ciphertext, keyPair.publicKey, keyPair.secretKey)) {
    return null
  }

  return plaintext
}

exports.encryptionKeyPair = function (seed) {
  const publicKey = b4a.alloc(sodium.crypto_box_PUBLICKEYBYTES)
  const secretKey = b4a.alloc(sodium.crypto_box_SECRETKEYBYTES)

  if (seed) {
    sodium.crypto_box_seed_keypair(publicKey, secretKey, seed)
  } else {
    sodium.crypto_box_keypair(publicKey, secretKey)
  }

  return {
    publicKey,
    secretKey
  }
}

exports.data = function (data) {
  const out = b4a.allocUnsafe(32)

  sodium.crypto_generichash_batch(out, [LEAF_TYPE, c.encode(c.uint64, data.byteLength), data])

  return out
}

exports.parent = function (a, b) {
  if (a.index > b.index) {
    const tmp = a
    a = b
    b = tmp
  }

  const out = b4a.allocUnsafe(32)

  sodium.crypto_generichash_batch(out, [
    PARENT_TYPE,
    c.encode(c.uint64, a.size + b.size),
    a.hash,
    b.hash
  ])

  return out
}

exports.tree = function (roots, out) {
  const buffers = new Array(3 * roots.length + 1)
  let j = 0

  buffers[j++] = ROOT_TYPE

  for (let i = 0; i < roots.length; i++) {
    const r = roots[i]
    buffers[j++] = r.hash
    buffers[j++] = c.encode(c.uint64, r.index)
    buffers[j++] = c.encode(c.uint64, r.size)
  }

  if (!out) out = b4a.allocUnsafe(32)
  sodium.crypto_generichash_batch(out, buffers)
  return out
}

exports.hash = function (data, out) {
  if (!out) out = b4a.allocUnsafe(32)
  if (!Array.isArray(data)) data = [data]

  sodium.crypto_generichash_batch(out, data)

  return out
}

exports.randomBytes = function (n) {
  const buf = b4a.allocUnsafe(n)
  sodium.randombytes_buf(buf)
  return buf
}

exports.discoveryKey = function (key) {
  if (!key || key.byteLength !== 32) throw new Error('Must pass a 32 byte buffer')
  // Discovery keys might stay around for a while, so better not to use slab memory (for better gc)
  const digest = b4a.allocUnsafeSlow(32)
  sodium.crypto_generichash(digest, HYPERCORE, key)
  return digest
}

if (sodium.sodium_free) {
  exports.free = function (secureBuf) {
    if (secureBuf.secure) sodium.sodium_free(secureBuf)
  }
} else {
  exports.free = function () {}
}

exports.namespace = function (name, count) {
  const ids = typeof count === 'number' ? range(count) : count

  // Namespaces are long-lived, so better to use a dedicated slab
  const buf = b4a.allocUnsafeSlow(32 * ids.length)

  const list = new Array(ids.length)

  // ns is ephemeral, so default slab
  const ns = b4a.allocUnsafe(33)
  sodium.crypto_generichash(ns.subarray(0, 32), typeof name === 'string' ? b4a.from(name) : name)

  for (let i = 0; i < list.length; i++) {
    list[i] = buf.subarray(32 * i, 32 * i + 32)
    ns[32] = ids[i]
    sodium.crypto_generichash(list[i], ns)
  }

  return list
}

function range(count) {
  const arr = new Array(count)
  for (let i = 0; i < count; i++) arr[i] = i
  return arr
}
{
  "name": "hypercore-crypto",
  "version": "3.7.0",
  "description": "The crypto primitives used in hypercore, extracted into a separate module",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.6.6",
    "compact-encoding": "^3.0.0",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "brittle": "^3.5.0",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/hypercore-crypto.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/hypercore-crypto/issues"
  },
  "homepage": "https://github.com/mafintosh/hypercore-crypto"
}
const IdEnc = require('hypercore-id-encoding')

module.exports = class HypercoreError extends Error {
  constructor (msg, code, fn = HypercoreError, discoveryKey = null) {
    if (discoveryKey) msg = `${msg} (discovery key: ${IdEnc.normalize(discoveryKey)})`
    super(`${code}: ${msg}`)

    this.code = code
    this.discoveryKey = discoveryKey

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name () {
    return 'HypercoreError'
  }

  static ASSERTION (msg, discoveryKey = null) { // ERR_ASSERTION is picked up by safety-catch also
    return new HypercoreError(msg, 'ERR_ASSERTION', HypercoreError.ASSERT, discoveryKey)
  }

  static BAD_ARGUMENT (msg, discoveryKey = null) {
    return new HypercoreError(msg, 'BAD_ARGUMENT', HypercoreError.BAD_ARGUMENT, discoveryKey)
  }

  static STORAGE_EMPTY (msg, discoveryKey = null) {
    return new HypercoreError(msg, 'STORAGE_EMPTY', HypercoreError.STORAGE_EMPTY, discoveryKey)
  }

  static STORAGE_CONFLICT (msg, discoveryKey = null) {
    return new HypercoreError(msg, 'STORAGE_CONFLICT', HypercoreError.STORAGE_CONFLICT, discoveryKey)
  }

  static INVALID_SIGNATURE (msg, discoveryKey = null) {
    return new HypercoreError(msg, 'INVALID_SIGNATURE', HypercoreError.INVALID_SIGNATURE, discoveryKey)
  }

  static INVALID_CAPABILITY (msg, discoveryKey = null) {
    return new HypercoreError(msg, 'INVALID_CAPABILITY', HypercoreError.INVALID_CAPABILITY, discoveryKey)
  }

  static INVALID_CHECKSUM (msg = 'Invalid checksum', discoveryKey = null) {
    return new HypercoreError(msg, 'INVALID_CHECKSUM', HypercoreError.INVALID_CHECKSUM, discoveryKey)
  }

  static INVALID_OPERATION (msg, discoveryKey = null) {
    return new HypercoreError(msg, 'INVALID_OPERATION', HypercoreError.INVALID_OPERATION, discoveryKey)
  }

  static INVALID_PROOF (msg = 'Proof not verifiable', discoveryKey = null) {
    return new HypercoreError(msg, 'INVALID_PROOF', HypercoreError.INVALID_PROOF, discoveryKey)
  }

  static BLOCK_NOT_AVAILABLE (msg = 'Block is not available', discoveryKey = null) {
    return new HypercoreError(msg, 'BLOCK_NOT_AVAILABLE', HypercoreError.BLOCK_NOT_AVAILABLE, discoveryKey)
  }

  static SNAPSHOT_NOT_AVAILABLE (msg = 'Snapshot is not available', discoveryKey = null) {
    return new HypercoreError(msg, 'SNAPSHOT_NOT_AVAILABLE', HypercoreError.SNAPSHOT_NOT_AVAILABLE, discoveryKey)
  }

  static REQUEST_CANCELLED (msg = 'Request was cancelled', discoveryKey = null) {
    return new HypercoreError(msg, 'REQUEST_CANCELLED', HypercoreError.REQUEST_CANCELLED, discoveryKey)
  }

  static REQUEST_TIMEOUT (msg = 'Request timed out', discoveryKey = null) {
    return new HypercoreError(msg, 'REQUEST_TIMEOUT', HypercoreError.REQUEST_TIMEOUT, discoveryKey)
  }

  static SESSION_NOT_WRITABLE (msg = 'Session is not writable', discoveryKey = null) {
    return new HypercoreError(msg, 'SESSION_NOT_WRITABLE', HypercoreError.SESSION_NOT_WRITABLE, discoveryKey)
  }

  static SESSION_CLOSED (msg = 'Session is closed', discoveryKey = null) {
    return new HypercoreError(msg, 'SESSION_CLOSED', HypercoreError.SESSION_CLOSED, discoveryKey)
  }

  static BATCH_UNFLUSHED (msg = 'Batch not yet flushed', discoveryKey = null) {
    return new HypercoreError(msg, 'BATCH_UNFLUSHED', HypercoreError.BATCH_UNFLUSHED, discoveryKey)
  }

  static BATCH_ALREADY_EXISTS (msg = 'Batch already exists', discoveryKey = null) {
    return new HypercoreError(msg, 'BATCH_ALREADY_EXISTS', HypercoreError.BATCH_ALREADY_EXISTS, discoveryKey)
  }

  static BATCH_ALREADY_FLUSHED (msg = 'Batch has already been flushed', discoveryKey = null) {
    return new HypercoreError(msg, 'BATCH_ALREADY_FLUSHED', HypercoreError.BATCH_ALREADY_FLUSHED, discoveryKey)
  }

  static OPLOG_CORRUPT (msg = 'Oplog file appears corrupt or out of date', discoveryKey = null) {
    return new HypercoreError(msg, 'OPLOG_CORRUPT', HypercoreError.OPLOG_CORRUPT, discoveryKey)
  }

  static OPLOG_HEADER_OVERFLOW (msg = 'Oplog header exceeds page size', discoveryKey = null) {
    return new HypercoreError(msg, 'OPLOG_HEADER_OVERFLOW', HypercoreError.OPLOG_HEADER_OVERFLOW, discoveryKey)
  }

  static INVALID_OPLOG_VERSION (msg = 'Invalid header version', discoveryKey = null) {
    return new HypercoreError(msg, 'INVALID_OPLOG_VERSION', HypercoreError.INVALID_OPLOG_VERSION, discoveryKey)
  }

  static WRITE_FAILED (msg = 'Write to storage failed', discoveryKey = null) {
    return new HypercoreError(msg, 'WRITE_FAILED', HypercoreError.WRITE_FAILED, discoveryKey)
  }

  static DECODING_ERROR (msg = 'Decoding error', discoveryKey = null) {
    return new HypercoreError(msg, 'DECODING_ERROR', HypercoreError.DECODING_ERROR, discoveryKey)
  }

  static SESSION_MOVED (msg = 'Session moved', discoveryKey = null) {
    return new HypercoreError(msg, 'SESSION_MOVED', HypercoreError.SESSION_MOVED, discoveryKey)
  }
}
{
  "name": "hypercore-errors",
  "version": "1.5.0",
  "description": "Hypercore errors",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/hypercore-errors.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/hypercore-errors/issues"
  },
  "homepage": "https://github.com/holepunchto/hypercore-errors#readme",
  "devDependencies": {
    "b4a": "^1.6.7",
    "brittle": "^3.1.3",
    "standard": "^17.0.0"
  },
  "dependencies": {
    "hypercore-id-encoding": "^1.3.0"
  }
}
const z32 = require('z32')
const b4a = require('b4a')

module.exports = {
  encode,
  decode,
  normalize,
  isValid
}

function encode (key) {
  if (!b4a.isBuffer(key)) throw new Error('Key must be a Buffer')
  if (key.byteLength !== 32) throw new Error('Key must be 32-bytes long')
  return z32.encode(key)
}

function decode (id) {
  if (b4a.isBuffer(id)) {
    if (id.byteLength !== 32) throw new Error('ID must be 32-bytes long')
    return id
  }
  if (typeof id === 'string') {
    if (id.startsWith('pear://')) id = id.slice(7).split('/')[0]
    if (id.length === 52) return z32.decode(id)
    if (id.length === 64) {
      const buf = b4a.from(id, 'hex')
      if (buf.byteLength === 32) return buf
    }
  }
  throw new Error('Invalid Hypercore key')
}

function normalize (any) {
  return encode(decode(any))
}

function isValid (any) {
  try {
    decode(any)
    return true
  } catch {
    return false
  }
}
{
  "name": "hypercore-id-encoding",
  "version": "1.3.0",
  "description": "Convert Hypercore keys to/from z-base32 or hex",
  "main": "index.js",
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.5.3",
    "z32": "^1.0.0"
  },
  "devDependencies": {
    "brittle": "^3.1.1",
    "hypercore": "^10.0.0",
    "random-access-memory": "^6.0.0",
    "standard": "^17.1.0"
  },
  "license": "Apache-2.0",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/hypercore-id-encoding.git"
  },
  "keywords": [],
  "author": "",
  "bugs": {
    "url": "https://github.com/holepunchto/hypercore-id-encoding/issues"
  },
  "homepage": "https://github.com/holepunchto/hypercore-id-encoding#readme"
}
function headLegacyMap(m) {
  return {
    version: 2, // version bumped from 1
    cores: m.allocated.cores,
    datas: m.allocated.datas,
    groups: 0,
    seed: m.seed,
    defaultDiscoveryKey: m.defaultDiscoveryKey
  }
}

module.exports = {
  headLegacyMap
}
// This file is autogenerated by the hyperschema compiler
// Schema Version: 2
/* eslint-disable camelcase */
/* eslint-disable quotes */
/* eslint-disable space-before-function-paren */

const { c } = require('hyperschema/runtime')
const external0 = require('../../external.js')

const VERSION = 2

// eslint-disable-next-line no-unused-vars
let version = VERSION

// @corestore/allocated
const encoding0 = {
  preencode(state, m) {
    c.uint.preencode(state, m.cores)
    c.uint.preencode(state, m.datas)
  },
  encode(state, m) {
    c.uint.encode(state, m.cores)
    c.uint.encode(state, m.datas)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const r1 = c.uint.decode(state)

    return {
      cores: r0,
      datas: r1
    }
  }
}

// @corestore/head-v1
const encoding1 = {
  preencode(state, m) {
    state.end++ // max flag is 4 so always one byte

    if (m.allocated) encoding0.preencode(state, m.allocated)
    if (m.seed) c.fixed32.preencode(state, m.seed)
    if (m.defaultDiscoveryKey) c.fixed32.preencode(state, m.defaultDiscoveryKey)
  },
  encode(state, m) {
    const flags = (m.allocated ? 1 : 0) | (m.seed ? 2 : 0) | (m.defaultDiscoveryKey ? 4 : 0)

    c.uint.encode(state, flags)

    if (m.allocated) encoding0.encode(state, m.allocated)
    if (m.seed) c.fixed32.encode(state, m.seed)
    if (m.defaultDiscoveryKey) c.fixed32.encode(state, m.defaultDiscoveryKey)
  },
  decode(state) {
    const v = c.uint.decode(state)
    const flags = c.uint.decode(state)

    return {
      version: v,
      allocated: (flags & 1) !== 0 ? encoding0.decode(state) : null,
      seed: (flags & 2) !== 0 ? c.fixed32.decode(state) : null,
      defaultDiscoveryKey: (flags & 4) !== 0 ? c.fixed32.decode(state) : null
    }
  }
}

// @corestore/head-v2
const encoding2 = {
  preencode(state, m) {
    c.uint.preencode(state, m.cores)
    c.uint.preencode(state, m.datas)
    c.uint.preencode(state, m.groups)
    state.end++ // max flag is 2 so always one byte

    if (m.seed) c.fixed32.preencode(state, m.seed)
    if (m.defaultDiscoveryKey) c.fixed32.preencode(state, m.defaultDiscoveryKey)
  },
  encode(state, m) {
    const flags = (m.seed ? 1 : 0) | (m.defaultDiscoveryKey ? 2 : 0)

    c.uint.encode(state, m.cores)
    c.uint.encode(state, m.datas)
    c.uint.encode(state, m.groups)
    c.uint.encode(state, flags)

    if (m.seed) c.fixed32.encode(state, m.seed)
    if (m.defaultDiscoveryKey) c.fixed32.encode(state, m.defaultDiscoveryKey)
  },
  decode(state) {
    const v = c.uint.decode(state)
    const r0 = c.uint.decode(state)
    const r1 = c.uint.decode(state)
    const r2 = c.uint.decode(state)
    const flags = c.uint.decode(state)

    return {
      version: v,
      cores: r0,
      datas: r1,
      groups: r2,
      seed: (flags & 1) !== 0 ? c.fixed32.decode(state) : null,
      defaultDiscoveryKey: (flags & 2) !== 0 ? c.fixed32.decode(state) : null
    }
  }
}

// @corestore/head
const encoding3 = {
  preencode(state, m) {
    c.uint.preencode(state, m.version)
    switch (m.version) {
      case 0:
      case 1:
        encoding1.preencode(state, m)
        break
      case 2:
        encoding2.preencode(state, m)
        break
      default:
        throw new Error('Unsupported version')
    }
  },
  encode(state, m) {
    c.uint.encode(state, m.version)
    switch (m.version) {
      case 0:
      case 1:
        encoding1.encode(state, m)
        break
      case 2:
        encoding2.encode(state, m)
        break
      default:
        throw new Error('Unsupported version')
    }
  },
  decode(state) {
    const start = state.start
    const v = c.uint.decode(state)
    state.start = start
    switch (v) {
      case 0:
      case 1: {
        const decoded = encoding1.decode(state)
        const map = external0.headLegacyMap
        return map(decoded)
      }
      case 2: {
        const decoded = encoding2.decode(state)
        return decoded
      }
      default:
        throw new Error('Unsupported version')
    }
  }
}

// @corestore/alias
const encoding4 = {
  preencode(state, m) {
    c.string.preencode(state, m.name)
    c.fixed32.preencode(state, m.namespace)
  },
  encode(state, m) {
    c.string.encode(state, m.name)
    c.fixed32.encode(state, m.namespace)
  },
  decode(state) {
    const r0 = c.string.decode(state)
    const r1 = c.fixed32.decode(state)

    return {
      name: r0,
      namespace: r1
    }
  }
}

// @corestore/core
const encoding5 = {
  preencode(state, m) {
    c.uint.preencode(state, m.version)
    c.uint.preencode(state, m.corePointer)
    c.uint.preencode(state, m.dataPointer)
    state.end++ // max flag is 1 so always one byte

    if (m.alias) encoding4.preencode(state, m.alias)
  },
  encode(state, m) {
    const flags = m.alias ? 1 : 0

    c.uint.encode(state, m.version)
    c.uint.encode(state, m.corePointer)
    c.uint.encode(state, m.dataPointer)
    c.uint.encode(state, flags)

    if (m.alias) encoding4.encode(state, m.alias)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const r1 = c.uint.decode(state)
    const r2 = c.uint.decode(state)
    const flags = c.uint.decode(state)

    return {
      version: r0,
      corePointer: r1,
      dataPointer: r2,
      alias: (flags & 1) !== 0 ? encoding4.decode(state) : null
    }
  }
}

const encoding6_enum = {
  blake2b: 'blake2b'
}

// @core/hashes enum
const encoding6 = {
  preencode(state, m) {
    state.end++ // max enum is 0 so always one byte
  },
  encode(state, m) {
    switch (m) {
      case 'blake2b':
        c.uint.encode(state, 0)
        break
      default:
        throw new Error('Unknown enum')
    }
  },
  decode(state) {
    switch (c.uint.decode(state)) {
      case 0:
        return 'blake2b'
      default:
        return null
    }
  }
}

const encoding7_enum = {
  ed25519: 'ed25519'
}

// @core/signatures enum
const encoding7 = {
  preencode(state, m) {
    state.end++ // max enum is 0 so always one byte
  },
  encode(state, m) {
    switch (m) {
      case 'ed25519':
        c.uint.encode(state, 0)
        break
      default:
        throw new Error('Unknown enum')
    }
  },
  decode(state) {
    switch (c.uint.decode(state)) {
      case 0:
        return 'ed25519'
      default:
        return null
    }
  }
}

// @core/tree-node
const encoding8 = {
  preencode(state, m) {
    c.uint.preencode(state, m.index)
    c.uint.preencode(state, m.size)
    c.fixed32.preencode(state, m.hash)
  },
  encode(state, m) {
    c.uint.encode(state, m.index)
    c.uint.encode(state, m.size)
    c.fixed32.encode(state, m.hash)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const r1 = c.uint.decode(state)
    const r2 = c.fixed32.decode(state)

    return {
      index: r0,
      size: r1,
      hash: r2
    }
  }
}

// @core/signer
const encoding9 = {
  preencode(state, m) {
    encoding7.preencode(state, m.signature)
    c.fixed32.preencode(state, m.namespace)
    c.fixed32.preencode(state, m.publicKey)
  },
  encode(state, m) {
    encoding7.encode(state, m.signature)
    c.fixed32.encode(state, m.namespace)
    c.fixed32.encode(state, m.publicKey)
  },
  decode(state) {
    const r0 = encoding7.decode(state)
    const r1 = c.fixed32.decode(state)
    const r2 = c.fixed32.decode(state)

    return {
      signature: r0,
      namespace: r1,
      publicKey: r2
    }
  }
}

// @core/prologue
const encoding10 = {
  preencode(state, m) {
    c.fixed32.preencode(state, m.hash)
    c.uint.preencode(state, m.length)
  },
  encode(state, m) {
    c.fixed32.encode(state, m.hash)
    c.uint.encode(state, m.length)
  },
  decode(state) {
    const r0 = c.fixed32.decode(state)
    const r1 = c.uint.decode(state)

    return {
      hash: r0,
      length: r1
    }
  }
}

// @core/manifest.signers
const encoding11_4 = c.array(encoding9)
// @core/manifest.linked
const encoding11_6 = c.array(c.fixed32)

// @core/manifest
const encoding11 = {
  preencode(state, m) {
    c.uint.preencode(state, m.version)
    state.end++ // max flag is 8 so always one byte
    encoding6.preencode(state, m.hash)
    c.uint.preencode(state, m.quorum)
    encoding11_4.preencode(state, m.signers)

    if (m.prologue) encoding10.preencode(state, m.prologue)
    if (m.linked) encoding11_6.preencode(state, m.linked)
    if (m.userData) c.buffer.preencode(state, m.userData)
  },
  encode(state, m) {
    const flags =
      (m.allowPatch ? 1 : 0) | (m.prologue ? 2 : 0) | (m.linked ? 4 : 0) | (m.userData ? 8 : 0)

    c.uint.encode(state, m.version)
    c.uint.encode(state, flags)
    encoding6.encode(state, m.hash)
    c.uint.encode(state, m.quorum)
    encoding11_4.encode(state, m.signers)

    if (m.prologue) encoding10.encode(state, m.prologue)
    if (m.linked) encoding11_6.encode(state, m.linked)
    if (m.userData) c.buffer.encode(state, m.userData)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const flags = c.uint.decode(state)

    return {
      version: r0,
      hash: encoding6.decode(state),
      quorum: c.uint.decode(state),
      allowPatch: (flags & 1) !== 0,
      signers: encoding11_4.decode(state),
      prologue: (flags & 2) !== 0 ? encoding10.decode(state) : null,
      linked: (flags & 4) !== 0 ? encoding11_6.decode(state) : null,
      userData: (flags & 8) !== 0 ? c.buffer.decode(state) : null
    }
  }
}

// @core/keyPair
const encoding12 = {
  preencode(state, m) {
    c.buffer.preencode(state, m.publicKey)
    c.optionalBuffer.preencode(state, m.secretKey)
  },
  encode(state, m) {
    c.buffer.encode(state, m.publicKey)
    c.optionalBuffer.encode(state, m.secretKey)
  },
  decode(state) {
    const r0 = c.buffer.decode(state)
    const r1 = c.optionalBuffer.decode(state)

    return {
      publicKey: r0,
      secretKey: r1
    }
  }
}

// @core/group
const encoding13 = {
  preencode(state, m) {
    state.end++ // max flag is 2 so always one byte

    if (m.key) c.fixed32.preencode(state, m.key)
    if (m.pointer) c.uint.preencode(state, m.pointer)
  },
  encode(state, m) {
    const flags = (m.key ? 1 : 0) | (m.pointer ? 2 : 0)

    c.uint.encode(state, flags)

    if (m.key) c.fixed32.encode(state, m.key)
    if (m.pointer) c.uint.encode(state, m.pointer)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      key: (flags & 1) !== 0 ? c.fixed32.decode(state) : null,
      pointer: (flags & 2) !== 0 ? c.uint.decode(state) : 0
    }
  }
}

// @core/auth.manifest
const encoding14_2 = c.frame(encoding11)

// @core/auth
const encoding14 = {
  preencode(state, m) {
    c.fixed32.preencode(state, m.key)
    c.fixed32.preencode(state, m.discoveryKey)
    state.end++ // max flag is 4 so always one byte

    if (m.manifest) encoding14_2.preencode(state, m.manifest)
    if (m.keyPair) encoding12.preencode(state, m.keyPair)
    if (m.encryptionKey) c.buffer.preencode(state, m.encryptionKey)
  },
  encode(state, m) {
    const flags = (m.manifest ? 1 : 0) | (m.keyPair ? 2 : 0) | (m.encryptionKey ? 4 : 0)

    c.fixed32.encode(state, m.key)
    c.fixed32.encode(state, m.discoveryKey)
    c.uint.encode(state, flags)

    if (m.manifest) encoding14_2.encode(state, m.manifest)
    if (m.keyPair) encoding12.encode(state, m.keyPair)
    if (m.encryptionKey) c.buffer.encode(state, m.encryptionKey)
  },
  decode(state) {
    const r0 = c.fixed32.decode(state)
    const r1 = c.fixed32.decode(state)
    const flags = c.uint.decode(state)

    return {
      key: r0,
      discoveryKey: r1,
      manifest: (flags & 1) !== 0 ? encoding14_2.decode(state) : null,
      keyPair: (flags & 2) !== 0 ? encoding12.decode(state) : null,
      encryptionKey: (flags & 4) !== 0 ? c.buffer.decode(state) : null
    }
  }
}

// @core/head
const encoding15 = {
  preencode(state, m) {
    c.uint.preencode(state, m.fork)
    c.uint.preencode(state, m.length)
    c.fixed32.preencode(state, m.rootHash)
    c.optionalBuffer.preencode(state, m.signature)
    state.end++ // max flag is 1 so always one byte

    if (version >= 2 && m.timestamp) c.uint64.preencode(state, m.timestamp)
  },
  encode(state, m) {
    const flags = version >= 2 && m.timestamp ? 1 : 0

    c.uint.encode(state, m.fork)
    c.uint.encode(state, m.length)
    c.fixed32.encode(state, m.rootHash)
    c.optionalBuffer.encode(state, m.signature)
    c.uint.encode(state, flags)

    if (version >= 2 && m.timestamp) c.uint64.encode(state, m.timestamp)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const r1 = c.uint.decode(state)
    const r2 = c.fixed32.decode(state)
    const r3 = c.optionalBuffer.decode(state)
    const flags = state.start < state.end ? c.uint.decode(state) : 0

    return {
      fork: r0,
      length: r1,
      rootHash: r2,
      signature: r3,
      timestamp: version >= 2 && (flags & 1) !== 0 ? c.uint64.decode(state) : 0
    }
  }
}

// @core/hints
const encoding16 = {
  preencode(state, m) {
    state.end++ // max flag is 4 so always one byte

    if (m.contiguousLength) c.uint.preencode(state, m.contiguousLength)
    if (m.remoteContiguousLength) c.uint.preencode(state, m.remoteContiguousLength)
    if (m.recovering) c.uint.preencode(state, m.recovering)
  },
  encode(state, m) {
    const flags =
      (m.contiguousLength ? 1 : 0) | (m.remoteContiguousLength ? 2 : 0) | (m.recovering ? 4 : 0)

    c.uint.encode(state, flags)

    if (m.contiguousLength) c.uint.encode(state, m.contiguousLength)
    if (m.remoteContiguousLength) c.uint.encode(state, m.remoteContiguousLength)
    if (m.recovering) c.uint.encode(state, m.recovering)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      contiguousLength: (flags & 1) !== 0 ? c.uint.decode(state) : 0,
      remoteContiguousLength: (flags & 2) !== 0 ? c.uint.decode(state) : 0,
      recovering: (flags & 4) !== 0 ? c.uint.decode(state) : 0
    }
  }
}

// @core/session
const encoding17 = {
  preencode(state, m) {
    c.string.preencode(state, m.name)
    c.uint.preencode(state, m.dataPointer)
  },
  encode(state, m) {
    c.string.encode(state, m.name)
    c.uint.encode(state, m.dataPointer)
  },
  decode(state) {
    const r0 = c.string.decode(state)
    const r1 = c.uint.decode(state)

    return {
      name: r0,
      dataPointer: r1
    }
  }
}

// @core/sessions
const encoding18 = c.array(encoding17)

// @core/dependency
const encoding19 = {
  preencode(state, m) {
    c.uint.preencode(state, m.dataPointer)
    c.uint.preencode(state, m.length)
  },
  encode(state, m) {
    c.uint.encode(state, m.dataPointer)
    c.uint.encode(state, m.length)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const r1 = c.uint.decode(state)

    return {
      dataPointer: r0,
      length: r1
    }
  }
}

function setVersion(v) {
  version = v
}

function encode(name, value, v = VERSION) {
  version = v
  return c.encode(getEncoding(name), value)
}

function decode(name, buffer, v = VERSION) {
  version = v
  return c.decode(getEncoding(name), buffer)
}

function getEnum(name) {
  switch (name) {
    case '@core/hashes':
      return encoding6_enum
    case '@core/signatures':
      return encoding7_enum
    default:
      throw new Error('Enum not found ' + name)
  }
}

function getEncoding(name) {
  switch (name) {
    case '@corestore/allocated':
      return encoding0
    case '@corestore/head-v1':
      return encoding1
    case '@corestore/head-v2':
      return encoding2
    case '@corestore/head':
      return encoding3
    case '@corestore/alias':
      return encoding4
    case '@corestore/core':
      return encoding5
    case '@core/hashes':
      return encoding6
    case '@core/signatures':
      return encoding7
    case '@core/tree-node':
      return encoding8
    case '@core/signer':
      return encoding9
    case '@core/prologue':
      return encoding10
    case '@core/manifest':
      return encoding11
    case '@core/keyPair':
      return encoding12
    case '@core/group':
      return encoding13
    case '@core/auth':
      return encoding14
    case '@core/head':
      return encoding15
    case '@core/hints':
      return encoding16
    case '@core/session':
      return encoding17
    case '@core/sessions':
      return encoding18
    case '@core/dependency':
      return encoding19
    default:
      throw new Error('Encoder not found ' + name)
  }
}

function getStruct(name, v = VERSION) {
  const enc = getEncoding(name)
  return {
    preencode(state, m) {
      version = v
      enc.preencode(state, m)
    },
    encode(state, m) {
      version = v
      enc.encode(state, m)
    },
    decode(state) {
      version = v
      return enc.decode(state)
    }
  }
}

const resolveStruct = getStruct // compat

module.exports = {
  resolveStruct,
  getStruct,
  getEnum,
  getEncoding,
  encode,
  decode,
  setVersion,
  version
}
const RocksDB = require('rocksdb-native')
const rrp = require('resolve-reject-promise')
const ScopeLock = require('scope-lock')
const DeviceFile = require('device-file')
const path = require('path')
const fs = require('fs')

const View = require('./lib/view.js')

const VERSION = 2
const COLUMN_FAMILY = 'corestore'

const { store, core } = require('./lib/keys.js')

const { CorestoreRX, CorestoreTX, CoreTX, CoreRX } = require('./lib/tx.js')

const {
  createCoreStream,
  createAliasStream,
  createDiscoveryKeyStream,
  createBlockStream,
  createBitfieldStream,
  createUserDataStream,
  createTreeNodeStream,
  createMarkStream,
  createLocalStream,
  createGroupUpdateStream
} = require('./lib/streams.js')

const EMPTY = new View()

class Atom {
  constructor(db) {
    this.db = db
    this.view = new View()
    this.flushedPromise = null
    this.flushing = false
    this.preflushes = []
    this.flushes = []
  }

  preflush(fn) {
    this.preflushes.push(fn)
  }

  onflush(fn) {
    this.flushes.push(fn)
  }

  flushed() {
    if (!this.flushing) return Promise.resolve()
    if (this.flushedPromise !== null) return this.flushedPromise.promise
    this.flushedPromise = rrp()
    return this.flushedPromise.promise
  }

  _resolve() {
    const f = this.flushedPromise
    this.flushedPromise = null
    f.resolve()
  }

  async flush() {
    if (this.flushing) throw new Error('Atom already flushing')
    this.flushing = true

    try {
      const plen = this.preflushes.length
      for (let i = 0; i < plen; i++) this.preflushes[i]()

      await View.flush(this.view.changes, this.db)

      const promises = []
      const len = this.flushes.length // in case of reentry
      for (let i = 0; i < len; i++) promises.push(this.flushes[i]())

      await Promise.all(promises)
    } finally {
      this.view.reset()
      this.flushing = false
      if (this.flushedPromise !== null) this._resolve()
    }
  }
}

class HypercoreStorage {
  constructor(store, db, core, view, atom) {
    this.store = store
    this.db = db
    this.core = core
    this.view = view
    this.atom = atom

    this.view.readStart()
  }

  get readOnly() {
    return this.store.readOnly
  }

  get dependencies() {
    return this.core.dependencies
  }

  getDependencyLength() {
    return this.core.dependencies.length
      ? this.core.dependencies[this.core.dependencies.length - 1].length
      : -1
  }

  getDependency(length) {
    for (let i = this.core.dependencies.length - 1; i >= 0; i--) {
      const dep = this.core.dependencies[i]
      if (dep.length < length) return dep
    }

    return null
  }

  setDependencyHead(dep) {
    if (dep === null) {
      this.core.dependencies = []
      return
    }

    const deps = this.core.dependencies

    for (let i = deps.length - 1; i >= 0; i--) {
      const d = deps[i]

      if (d.dataPointer !== dep.dataPointer) continue

      // check if nothing changed
      if (d.length === dep.length && i === deps.length - 1) return

      this.core = {
        corePointer: this.core.corePointer,
        dataPointer: this.core.dataPointer,
        dependencies: deps.slice(0, i + 1)
      }

      this.core.dependencies[i] = {
        dataPointer: dep.dataPointer,
        length: dep.length
      }
      return // updated head so done
    }

    this.core.dependencies = [
      {
        dataPointer: dep.dataPointer,
        length: dep.length
      }
    ]
  }

  // TODO: this might have to be async if the dependents have changed, but prop ok for now
  updateDependencyLength(length, truncated) {
    const deps = this.core.dependencies

    const i = this.findDependencyIndex(length, truncated)
    if (i === -1) throw new Error('Dependency not found')

    this.core = {
      corePointer: this.core.corePointer,
      dataPointer: this.core.dataPointer,
      dependencies: deps.slice(0, i + 1)
    }

    if (this.core.dependencies[i].length !== length) {
      this.core.dependencies[i] = {
        dataPointer: deps[i].dataPointer,
        length
      }
    }
  }

  findDependencyIndex(length, truncated) {
    const deps = this.core.dependencies

    if (truncated) {
      for (let i = 0; i < deps.length; i++) {
        if (deps[i].length >= length) return i
      }

      return -1
    }

    for (let i = deps.length - 1; i >= 0; i--) {
      if (deps[i].length <= length) return i
    }

    return -1
  }

  get snapshotted() {
    return this.db._snapshot !== null
  }

  snapshot() {
    return new HypercoreStorage(
      this.store,
      this.db.snapshot(),
      this.core,
      this.view.snapshot(),
      this.atom
    )
  }

  compact() {
    return Promise.all([
      this.db.compactRange(core.core(this.core.corePointer), core.core(this.core.corePointer)),
      this.db.compactRange(core.data(this.core.dataPointer), core.data(this.core.dataPointer))
    ])
  }

  atomize(atom) {
    if (this.atom && this.atom !== atom) {
      throw new Error('Cannot atomize and atomized session with a new atom')
    }
    return new HypercoreStorage(this.store, this.db.session(), this.core, atom.view, atom)
  }

  createAtom() {
    return this.store.createAtom()
  }

  createBlockStream(opts) {
    return createBlockStream(this.core, this.db, this.view, opts)
  }

  createTreeNodeStream(opts) {
    return createTreeNodeStream(this.core, this.db, this.view, opts)
  }

  createBitfieldStream(opts) {
    return createBitfieldStream(this.core, this.db, this.view, opts)
  }

  createUserDataStream(opts) {
    return createUserDataStream(this.core, this.db, this.view, opts)
  }

  createMarkStream(opts) {
    return createMarkStream(this.core, this.db, this.view, opts)
  }

  createLocalStream(opts) {
    return createLocalStream(this.core, this.db, this.view, opts)
  }

  async resumeSession(name) {
    const rx = this.read()
    const existingSessionsPromise = rx.getSessions()

    rx.tryFlush()
    const existingSessions = await existingSessionsPromise

    const sessions = existingSessions || []
    const session = getSession(sessions, name, false)

    if (session === null) return null

    const core = {
      corePointer: this.core.corePointer,
      dataPointer: session.dataPointer,
      dependencies: []
    }

    const coreRx = new CoreRX(core, this.db, this.view)

    const dependencyPromise = coreRx.getDependency()
    coreRx.tryFlush()

    const dependency = await dependencyPromise
    if (dependency) core.dependencies = this._addDependency(dependency)

    return new HypercoreStorage(
      this.store,
      this.db.session(),
      core,
      this.atom ? this.view : new View(),
      this.atom
    )
  }

  async createSession(name, head) {
    const rx = this.read()

    const existingSessionsPromise = rx.getSessions()
    const existingHeadPromise = rx.getHead()

    rx.tryFlush()

    const [existingSessions, existingHead] = await Promise.all([
      existingSessionsPromise,
      existingHeadPromise
    ])
    if (head === null) head = existingHead

    if (existingHead !== null && head.length > existingHead.length) {
      throw new Error('Invalid head passed, ahead of core')
    }

    const sessions = existingSessions || []
    const session = getSession(sessions, name, true)
    const fresh = session.dataPointer === -1

    if (fresh) {
      session.dataPointer = await this.store._allocData()
    }

    const tx = this.write()

    tx.setSessions(sessions)

    const length = head === null ? 0 : head.length
    const core = {
      corePointer: this.core.corePointer,
      dataPointer: session.dataPointer,
      dependencies: this._addDependency({
        dataPointer: this.core.dataPointer,
        length
      })
    }

    const coreTx = new CoreTX(core, this.db, tx.view, tx.changes)

    if (length > 0) coreTx.setHead(head)
    coreTx.setDependency(core.dependencies[core.dependencies.length - 1])

    if (!fresh) {
      // nuke all existing state...
      coreTx.deleteBlockRange(0, -1)
      coreTx.deleteTreeNodeRange(0, -1)
      coreTx.deleteBitfieldPageRange(0, -1)
    }

    await tx.flush()

    return new HypercoreStorage(
      this.store,
      this.db.session(),
      core,
      this.atom ? this.view : new View(),
      this.atom
    )
  }

  async createAtomicSession(atom, head) {
    const length = head === null ? 0 : head.length
    const core = {
      corePointer: this.core.corePointer,
      dataPointer: this.core.dataPointer,
      dependencies: this._addDependency(null)
    }

    const coreTx = new CoreTX(core, this.db, atom.view, [])

    if (length > 0) coreTx.setHead(head)

    await coreTx.flush()

    return this.atomize(atom)
  }

  _addDependency(dep) {
    const deps = []

    for (let i = 0; i < this.core.dependencies.length; i++) {
      const d = this.core.dependencies[i]

      if (dep !== null && d.length > dep.length) {
        if (d.dataPointer !== dep.dataPointer) {
          deps.push({ dataPointer: d.dataPointer, length: dep.length })
        }
        return deps
      }

      deps.push(d)
    }

    if (
      dep !== null &&
      (deps.length === 0 || deps[deps.length - 1].dataPointer !== dep.dataPointer)
    ) {
      deps.push(dep)
    }
    return deps
  }

  async deleteSessions() {
    const rx = this.read()
    const existingSessionsPromise = rx.getSessions()
    rx.tryFlush()

    const existingSessions = await existingSessionsPromise

    // Remove batches
    const coreTx = this.write()
    coreTx.setSessions([]) // Clear sessions record
    await coreTx.flush()

    const tx = this.db.write({ autoDestroy: true })

    for (const { dataPointer } of existingSessions) {
      const start = core.data(dataPointer)
      const end = core.data(dataPointer + 1)
      tx.tryDeleteRange(start, end)
    }

    await tx.flush()
  }

  read() {
    return new CoreRX(this.core, this.db, this.view)
  }

  write() {
    return new CoreTX(this.core, this.db, this.atom ? this.view : null, [])
  }

  close() {
    if (this.view !== null) {
      this.view.readStop()
      this.view = null
    }

    return this.db.close()
  }

  static async export(ptr, db, { batches = false } = {}) {
    const rx = new CoreRX(ptr, db, EMPTY)

    const core = {
      head: null,
      auth: null,
      sessions: [],
      data: null
    }

    const sessionsPromise = rx.getSessions()
    const headPromise = rx.getHead()
    const authPromise = rx.getAuth()

    rx.tryFlush()

    const [sessions, head, auth] = await Promise.all([sessionsPromise, headPromise, authPromise])

    core.head = head
    core.auth = { ...auth, keyPair: null }
    if (sessions) core.sessions = sessions.map((s) => s.name)

    const data = []

    data.push(exportData(ptr, db))

    if (batches) {
      for (const { dataPointer } of sessions) {
        data.push(exportData({ dataPointer, dependencies: [] }, db))
      }
    }

    core.data = await Promise.all(data)

    return core
  }

  static isParentStorage(storage, parent) {
    const last = getLastDependency(storage)
    return !!last && last.dataPointer === parent.core.dataPointer
  }
}

class CorestoreStorage {
  constructor(db, opts = {}) {
    const storage = typeof db === 'string' ? db : null

    this.bootstrap = storage !== null
    this.path = storage !== null ? storage : path.join(db.path, '..')
    this.alwaysRecover = !!opts.alwaysRecover
    this.readOnly = !!opts.readOnly
    this.allowBackup = !!opts.allowBackup
    this.deviceFile = null
    this.wait = !!opts.wait

    // tmp sync fix for simplicty since not super deployed yet
    if (this.bootstrap && !this.readOnly) tmpFixStorage(this.path)

    this.id = opts.id || null
    this.view = null
    this.enters = 0
    this.lock = new ScopeLock()
    this.flushing = null
    this.version = 0
    this.migrating = null

    if ((this.bootstrap && !this.readOnly && !this.allowBackup) || this.wait) {
      const corestoreFile = path.join(this.path, 'CORESTORE')

      this.deviceFile = new DeviceFile(corestoreFile, {
        lock: true,
        wait: this.wait,
        data: { id: this.id }
      })
    }

    const dbPath = path.join(this.path, 'db')

    this.rocks = storage === null ? db : new RocksDB(dbPath, { ...opts, lock: this.deviceFile })
    this.db = createColumnFamily(this.rocks, opts)
  }

  get opened() {
    return this.db.opened
  }

  get closed() {
    return this.db.closed
  }

  async ready() {
    if (this.version === 0) await this._migrateStore()
    return this.db.ready()
  }

  compact(opts) {
    return this.db.compactRange(opts)
  }

  async audit() {
    for await (const { core } of this.createCoreStream()) {
      const coreRx = new CoreRX(core, this.db, EMPTY)
      const authPromise = coreRx.getAuth()

      coreRx.tryFlush()

      const auth = await authPromise

      if (!auth.manifest || auth.manifest.version > 0) continue
      if (auth.manifest.linked === null) continue

      auth.manifest.linked = null
      const coreTx = new CoreTX(core, this.db, null, [])
      coreTx.setAuth(auth)
      await coreTx.flush()
    }
  }

  async deleteCore(ptr) {
    const rx = new CoreRX(ptr, this.db, EMPTY)

    const authPromise = rx.getAuth()
    const sessionsPromise = rx.getSessions()

    rx.tryFlush()

    const auth = await authPromise
    const sessions = await sessionsPromise

    // no core stored here
    if (!auth) return

    const tx = this.db.write({ autoDestroy: true })

    tx.tryDelete(store.core(auth.discoveryKey))

    // clear core
    const start = core.core(ptr.corePointer)
    const end = core.core(ptr.corePointer + 1)
    tx.tryDeleteRange(start, end)

    if (sessions) {
      for (const { dataPointer } of sessions) {
        const start = core.data(dataPointer)
        const end = core.data(dataPointer + 1)
        tx.tryDeleteRange(start, end)
      }
    }

    return tx.flush()
  }

  static isCoreStorage(db) {
    return isCorestoreStorage(db)
  }

  static from(db) {
    if (isCorestoreStorage(db)) return db
    return new this(db)
  }

  async _flush() {
    while (this.enters > 0) {
      await this.lock.lock()
      await this.lock.unlock()
    }
  }

  async _maybeRecover(view) {
    const r = path.join(this.db.path, 'RECOVERING')
    if (!(await fileExists(r))) return
    await this.setRecovering(view)
    await fs.promises.unlink(r)
  }

  _maybeRecoverLater(err) {
    if (!shouldRecover(err) && !this.alwaysRecover) return
    fs.writeFileSync(path.join(this.db.path, 'RECOVERING'), '')
    for (const file of fs.readdirSync(this.db.path)) {
      if (file.endsWith('.log')) fs.unlinkSync(path.join(this.db.path, file))
    }
  }

  // runs pre any other mutation and read
  async _migrateStore() {
    const view = await this._enter()

    try {
      if (this.version === VERSION) return

      await this._preopen

      try {
        await this.db.ready()
      } catch (err) {
        this._maybeRecoverLater(err)
        throw err
      }

      await this._maybeRecover(view)

      const rx = new CorestoreRX(this.db, view)
      const headPromise = rx.getHead()

      rx.tryFlush()
      const head = await headPromise

      const version = head === null ? 0 : head.version
      if (version === VERSION) {
        this.version = VERSION
        return
      }

      const target = { version: VERSION, dryRun: false }

      switch (version) {
        case 0: {
          await require('./migrations/0').store(this, target)
          break
        }
        case 1: {
          // implicit migration on write
          break
        }
        default: {
          throw new Error(
            'Unsupported version: ' + version + ' - you should probably upgrade your dependencies'
          )
        }
      }

      this.version = VERSION
    } finally {
      await this._exit()
    }
  }

  // runs pre the core is returned to the user
  async _migrateCore(core, discoveryKey, version, locked) {
    const view = locked ? this.view : await this._enter()
    try {
      if (version === VERSION) return

      const target = { version: VERSION, dryRun: false }

      switch (version) {
        case 0: {
          await require('./migrations/0').core(core, target)
          break
        }
        case 1: {
          await require('./migrations/1').core(core, target)
          break
        }
        default: {
          throw new Error(
            'Unsupported version: ' + version + ' - you should probably upgrade your dependencies'
          )
        }
      }

      if (locked === false) return

      // if its locked, then move the core state into the memview
      // in case the core is reopened from the memview, pre flush

      const rx = new CorestoreRX(this.db, EMPTY)
      const tx = new CorestoreTX(view)

      const corePromise = rx.getCore(discoveryKey)
      rx.tryFlush()

      tx.putCore(discoveryKey, await corePromise)
      tx.apply()
    } finally {
      if (!locked) await this._exit()
    }
  }

  async _enter() {
    this.enters++
    await this.lock.lock()
    if (this.view === null) this.view = new View()
    return this.view
  }

  async _exit() {
    this.enters--

    if (this.flushing === null) this.flushing = rrp()
    const flushed = this.flushing.promise

    if (this.enters === 0 || this.view.size() > 128) {
      try {
        await View.flush(this.view.changes, this.db)
        this.flushing.resolve()
      } catch (err) {
        this.flushing.reject(err)
      } finally {
        this.flushing = null
        this.view = null
      }
    }

    this.lock.unlock()
    return flushed
  }

  // when used with core catches this isnt transactional for simplicity, HOWEVER, its just a number
  // so worth the tradeoff
  async _allocData() {
    let dataPointer = 0

    const view = await this._enter()
    const tx = new CorestoreTX(view)

    try {
      const head = await this._getHead(view)

      dataPointer = head.datas++

      tx.setHead(head)
      tx.apply()
    } finally {
      await this._exit()
    }

    return dataPointer
  }

  // exposes here so migrations can easily access the head in an init state
  async _getHead(view) {
    const rx = new CorestoreRX(this.db, view)
    const headPromise = rx.getHead()
    rx.tryFlush()

    const head = await headPromise
    return head === null ? initStoreHead() : head
  }

  createAtom() {
    return new Atom(this.db)
  }

  async flush() {
    await this.rocks.flush()
  }

  async close() {
    if (this.db.closed) return
    await this._flush()
    await this.db.close()
    await this.rocks.close()
    if (this.deviceFile) await this.deviceFile.close()
  }

  async clear() {
    if (this.version === 0) await this._migrateStore()

    const view = await this._enter()
    const tx = new CorestoreTX(view)

    tx.clear()
    tx.apply()

    await this._exit()
  }

  createCoreStream() {
    // TODO: be nice to run the mgiration here also, but too much plumbing atm
    return createCoreStream(this.db, EMPTY)
  }

  createAliasStream(namespace) {
    // TODO: be nice to run the mgiration here also, but too much plumbing atm
    return createAliasStream(this.db, EMPTY, namespace)
  }

  createDiscoveryKeyStream(namespace) {
    return createDiscoveryKeyStream(this.db, EMPTY, namespace)
  }

  createGroupUpdateStream(group, { since, reverse } = {}) {
    return createGroupUpdateStream(this.db, EMPTY, group, { gte: since, reverse })
  }

  async getAlias(alias) {
    if (this.version === 0) await this._migrateStore()

    const rx = new CorestoreRX(this.db, EMPTY)
    const discoveryKeyPromise = rx.getCoreByAlias(alias)
    rx.tryFlush()
    return discoveryKeyPromise
  }

  async getSeed() {
    if (this.version === 0) await this._migrateStore()

    const rx = new CorestoreRX(this.db, EMPTY)
    const headPromise = rx.getHead()

    rx.tryFlush()

    const head = await headPromise
    return head === null ? null : head.seed
  }

  async getGroup(topic) {
    if (this.version === 0) await this._migrateStore()

    const rx = new CorestoreRX(this.db, EMPTY)
    const groupPromise = rx.getGroup(topic)
    rx.tryFlush()
    return groupPromise
  }

  async setSeed(seed, { overwrite = true } = {}) {
    if (this.version === 0) await this._migrateStore()

    const view = await this._enter()
    const tx = new CorestoreTX(view)

    try {
      const rx = new CorestoreRX(this.db, view)
      const headPromise = rx.getHead()

      rx.tryFlush()

      const head = (await headPromise) || initStoreHead()

      if (head.seed === null || overwrite) head.seed = seed
      tx.setHead(head)
      tx.apply()

      return head.seed
    } finally {
      await this._exit()
    }
  }

  async setRecovering(view = null) {
    const recovering = Date.now()
    let keys = []

    for await (const data of this.createDiscoveryKeyStream()) {
      keys.push(data)
      if (keys.length > 16 * 1024) {
        await this._flushRecovering(recovering, view, keys)
        keys = []
      }
    }

    if (keys.length) await this._flushRecovering(recovering, view, keys)
  }

  async _flushRecovering(recovering, view, keys) {
    const own = !view
    if (own) view = await this._enter()
    const tx = new CorestoreTX(view)

    try {
      const infos = await this._getInfos(keys, { auth: false, head: false, hints: true })
      for (const inf of infos) {
        tx.setCoreHints(inf.core, { ...inf.hints, recovering })
      }
      tx.apply()
    } finally {
      if (own) await this._exit()
    }
  }

  async getDefaultDiscoveryKey() {
    if (this.version === 0) await this._migrateStore()

    const rx = new CorestoreRX(this.db, EMPTY)
    const headPromise = rx.getHead()

    rx.tryFlush()

    const head = await headPromise
    return head === null ? null : head.defaultDiscoveryKey
  }

  async setDefaultDiscoveryKey(discoveryKey, { overwrite = true } = {}) {
    if (this.version === 0) await this._migrateStore()

    const view = await this._enter()
    const tx = new CorestoreTX(view)

    try {
      const rx = new CorestoreRX(this.db, view)
      const headPromise = rx.getHead()

      rx.tryFlush()

      const head = (await headPromise) || initStoreHead()

      if (head.defaultDiscoveryKey === null || overwrite) head.defaultDiscoveryKey = discoveryKey
      tx.setHead(head)
      tx.apply()

      return head.defaultDiscoveryKey
    } finally {
      await this._exit()
    }
  }

  async hasCore(discoveryKey, { ifMigrated = false } = {}) {
    if (this.version === 0) await this._migrateStore()

    const rx = new CorestoreRX(this.db, EMPTY)
    const promise = rx.getCore(discoveryKey)

    rx.tryFlush()

    const core = await promise

    if (core === null) return false
    if (core.version !== VERSION && ifMigrated) return false

    return true
  }

  async getAuth(discoveryKey) {
    if (this.version === 0) await this._migrateStore()

    const rx = new CorestoreRX(this.db, EMPTY)
    const corePromise = rx.getCore(discoveryKey)

    rx.tryFlush()

    const core = await corePromise
    if (core === null) return null

    const read = this.db.read({ autoDestroy: true })
    const authPromise = CoreRX.getAuth(read, core)

    read.tryFlush()

    return authPromise
  }

  async getInfo(discoveryKey, opts) {
    return (await this.getInfos([discoveryKey], opts))[0]
  }

  async getInfos(discoveryKeys, opts) {
    if (this.version === 0) await this._migrateStore()
    return this._getInfos(discoveryKeys, opts)
  }

  async _getInfos(discoveryKeys, { auth = true, head = true, hints = true } = {}) {
    const rx = new CorestoreRX(this.db, EMPTY)
    const corePromises = new Array(discoveryKeys.length)

    for (let i = 0; i < discoveryKeys.length; i++) {
      corePromises[i] = rx.getCore(discoveryKeys[i])
    }

    rx.tryFlush()

    const cores = await Promise.all(corePromises)
    const read = this.db.read({ autoDestroy: true })

    const resultPromises = new Array(cores.length)

    for (let i = 0; i < cores.length; i++) {
      resultPromises[i] = cores[i]
        ? getInfoFromBatch(read, cores[i], discoveryKeys[i], auth, head, hints)
        : null
    }

    read.tryFlush()

    return Promise.all(resultPromises)
  }

  async suspend({ log = noop } = {}) {
    await log('Suspending hypercore storage...')
    await this.db.suspend()
    await log('db suspended')
    if (this.deviceFile) {
      await log('suspend deviceFile')
      await this.deviceFile.suspend()
      await log('deviceFile suspended')
    }
  }

  async resume() {
    if (this.deviceFile) await this.deviceFile.resume()
    await this.db.resume()
  }

  async resumeCore(discoveryKey) {
    if (this.version === 0) await this._migrateStore()

    if (!discoveryKey) {
      discoveryKey = await this.getDefaultDiscoveryKey()
      if (!discoveryKey) return null
    }

    const rx = new CorestoreRX(this.db, EMPTY)
    const corePromise = rx.getCore(discoveryKey)

    rx.tryFlush()
    const core = await corePromise

    if (core === null) return null
    return this._resumeFromPointers(EMPTY, discoveryKey, false, core)
  }

  async export(discoveryKey, opts) {
    const rx = new CorestoreRX(this.db, EMPTY)
    const corePromise = rx.getCore(discoveryKey)

    rx.tryFlush()
    const core = await corePromise
    if (core === null) return null

    let { dataPointer, corePointer } = core

    const ptr = { corePointer, dataPointer, dependencies: [] }

    while (true) {
      const rx = new CoreRX({ dataPointer, corePointer: 0, dependencies: [] }, this.db, EMPTY)
      const dependencyPromise = rx.getDependency()
      rx.tryFlush()
      const dependency = await dependencyPromise
      if (!dependency) break
      ptr.dependencies.push(dependency)
      dataPointer = dependency.dataPointer
    }

    const session = this.db.session()
    try {
      return await HypercoreStorage.export(ptr, session, opts)
    } finally {
      await session.close()
    }
  }

  async _resumeFromPointers(view, discoveryKey, create, { version, corePointer, dataPointer }) {
    const core = { corePointer, dataPointer, dependencies: [] }

    while (true) {
      const rx = new CoreRX({ dataPointer, corePointer: 0, dependencies: [] }, this.db, view)
      const dependencyPromise = rx.getDependency()
      rx.tryFlush()
      const dependency = await dependencyPromise
      if (!dependency) break
      core.dependencies.push(dependency)
      dataPointer = dependency.dataPointer
    }

    const result = new HypercoreStorage(this, this.db.session(), core, EMPTY, null)

    if (version < VERSION) await this._migrateCore(result, discoveryKey, version, create)
    return result
  }

  // not allowed to throw validation errors as its a shared tx!
  async _create(
    view,
    { key, manifest, keyPair, encryptionKey, discoveryKey, alias, userData, core: ptrs }
  ) {
    const rx = new CorestoreRX(this.db, view)
    const tx = new CorestoreTX(view)

    const corePromise = rx.getCore(discoveryKey)
    const headPromise = rx.getHead()

    rx.tryFlush()

    let [core, head] = await Promise.all([corePromise, headPromise])
    if (core) return this._resumeFromPointers(view, discoveryKey, true, core)

    if (head === null) head = initStoreHead()
    if (head.defaultDiscoveryKey === null) head.defaultDiscoveryKey = discoveryKey

    const corePointer = ptrs ? ptrs.corePointer : head.cores++
    const dataPointer = ptrs ? ptrs.dataPointer : head.datas++

    core = { version: VERSION, corePointer, dataPointer, alias }

    tx.setHead(head)
    tx.putCore(discoveryKey, core)
    if (alias) tx.putCoreByAlias(alias, discoveryKey)

    const ptr = { corePointer, dataPointer, dependencies: [] }
    const ctx = new CoreTX(ptr, this.db, view, tx.changes)

    ctx.setAuth({
      key,
      discoveryKey,
      manifest,
      keyPair,
      encryptionKey
    })

    if (userData) {
      for (const { key, value } of userData) {
        ctx.putUserData(key, value)
      }
    }

    tx.apply()

    return new HypercoreStorage(this, this.db.session(), ptr, EMPTY, null)
  }

  async createCore(data) {
    if (this.version === 0) await this._migrateStore()

    const view = await this._enter()

    try {
      return await this._create(view, data)
    } finally {
      await this._exit()
    }
  }

  // not allowed to throw validation errors as its a shared tx!
  async _createGroup(view, topic) {
    const rx = new CorestoreRX(this.db, view)
    const tx = new CorestoreTX(view)

    const groupPromise = rx.getGroup(topic)
    const headPromise = rx.getHead()

    rx.tryFlush()

    let group = await groupPromise
    if (group !== null) {
      return {
        key: topic,
        pointer: group
      }
    }

    let head = await headPromise
    if (head === null) head = initStoreHead()

    group = head.groups++

    tx.putGroup(topic, group)
    tx.setHead(head)
    tx.apply()

    return {
      key: topic,
      pointer: group
    }
  }

  async createGroup(topic) {
    if (this.version === 0) await this._migrateStore()

    const view = await this._enter()

    try {
      return await this._createGroup(view, topic)
    } finally {
      await this._exit()
    }
  }

  static isParentStorage(storage, parent) {
    return HypercoreStorage.isParentStorage(storage, parent)
  }
}

module.exports = CorestoreStorage

function initStoreHead() {
  return {
    version: 0, // cause we wanna run the migration
    datas: 0,
    cores: 0,
    groups: 0,
    seed: null,
    defaultDiscoveryKey: null
  }
}

function getSession(sessions, name, alloc) {
  for (let i = 0; i < sessions.length; i++) {
    if (sessions[i].name === name) return sessions[i]
  }

  if (!alloc) return null

  const result = { name, dataPointer: -1 }
  sessions.push(result)
  return result
}

function isCorestoreStorage(s) {
  return typeof s === 'object' && !!s && typeof s.setDefaultDiscoveryKey === 'function'
}

function createColumnFamily(db, opts = {}) {
  const {
    tableCacheIndexAndFilterBlocks = true,
    blockCache = true,
    optimizeFiltersForMemory = false,
    blobFileSize = 256 * 1024 * 1024,
    blobGarbageCollectionAgeCutOff = 0.25,
    blobGarbageCollectionForceThreshold = 1.0
  } = opts

  const col = new RocksDB.ColumnFamily(COLUMN_FAMILY, {
    enableBlobFiles: true,
    minBlobSize: 4096,
    blobFileSize,
    enableBlobGarbageCollection: true,
    tableBlockSize: 8192,
    tableCacheIndexAndFilterBlocks,
    tableFormatVersion: 6,
    optimizeFiltersForMemory,
    blockCache,
    blobGarbageCollectionAgeCutOff,
    blobGarbageCollectionForceThreshold
  })

  return db.columnFamily(col)
}

function getLastDependency(storage) {
  return storage.dependencies.length ? storage.dependencies[storage.dependencies.length - 1] : null
}

// TODO: remove in like 3-6 mo
function tmpFixStorage(p) {
  // if CORESTORE file is written, new format
  if (fs.existsSync(path.join(p, 'CORESTORE'))) return

  let files = []

  try {
    files = fs.readdirSync(p)
  } catch {}

  const notRocks = new Set([
    'CORESTORE',
    'primary-key',
    'cores',
    'app-preferences',
    'cache',
    'preferences.json',
    'db',
    'clone',
    'core',
    'notifications'
  ])

  for (const f of files) {
    if (notRocks.has(f)) continue

    try {
      fs.mkdirSync(path.join(p, 'db'))
    } catch {}

    fs.renameSync(path.join(p, f), path.join(p, 'db', f))
  }
}

async function exportData(ptr, db, opts) {
  // just need dataPointer
  const reads = [
    toArray(createBlockStream(ptr, db, EMPTY, opts)),
    toArray(createTreeNodeStream(ptr, db, EMPTY, opts)),
    toArray(createBitfieldStream(ptr, db, EMPTY, opts))
  ]

  const [blocks, tree, bitfield] = await Promise.all(reads)

  return {
    blocks,
    tree,
    bitfield
  }
}

async function toArray(stream) {
  const all = []
  for await (const e of stream) all.push(e)
  return all
}

async function fileExists(path) {
  try {
    await fs.promises.stat(path)
    return true
  } catch {
    return false
  }
}

function shouldRecover(err) {
  return err.message.toLowerCase().indexOf('sequence number is being set backwards') > -1
}

function noop() {}

async function getInfoFromBatch(db, c, discoveryKey, getAuth, getHead, getHints) {
  const authPromise = getAuth ? CoreRX.getAuth(db, c) : null
  const headPromise = getHead ? CoreRX.getHead(db, c) : null
  const hintsPromise = getHints ? CoreRX.getHints(db, c) : null

  // ensure no uncaughts
  if (authPromise) authPromise.catch(noop)
  if (headPromise) headPromise.catch(noop)
  if (hintsPromise) hintsPromise.catch(noop)

  return {
    discoveryKey,
    core: c,
    auth: await authPromise,
    head: await headPromise,
    hints: await hintsPromise
  }
}
const { Readable, getStreamError } = require('streamx')
const { core } = require('./keys')

module.exports = class BlockStream extends Readable {
  constructor(core, db, updates, start, end, reverse) {
    super()

    this.core = core
    this.db = db
    this.updates = updates
    this.start = start
    this.end = end
    this.reverse = reverse === true

    this._drained = true
    this._consumed = 0
    this._stream = null
    this._oncloseBound = this._onclose.bind(this)
    this._maybeDrainBound = this._maybeDrain.bind(this)

    this._update()
  }

  _update() {
    if (this._consumed > this.core.dependencies.length) return

    const deps = this.core.dependencies
    const index = this._findDependencyIndex(deps)

    const curr = index < deps.length ? deps[index] : null
    const prev = index > 0 && index - 1 < deps.length ? deps[index - 1] : null

    const start = prev && prev.length > this.start ? prev.length : this.start
    const end = curr && (this.end === -1 || curr.length < this.end) ? curr.length : this.end

    const ptr = curr ? curr.dataPointer : this.core.dataPointer

    this._makeStream(core.block(ptr, start), core.block(ptr, end))
  }

  _findDependencyIndex(deps) {
    if (!this.reverse) return this._consumed++

    let i = deps.length - this._consumed++
    while (i > 0) {
      if (deps[i - 1].length <= this.end) return i
      i--
      this._consumed++
    }

    return 0
  }

  _predestroy() {
    if (this._stream !== null) this._stream.destroy()
  }

  _read(cb) {
    this._drained = this._onreadable()
    cb(null)
  }

  _maybeDrain() {
    if (this._drained === true) return
    this._drained = this._onreadable()
  }

  _onreadable() {
    if (this._stream === null) {
      this.push(null)
      return true
    }

    let data = this._stream.read()

    if (data === null) return false

    do {
      this.push(data)
      data = this._stream.read()
    } while (data !== null)

    return true
  }

  _onclose() {
    if (this.destroying) return

    const err = getStreamError(this._stream)

    if (err !== null) {
      this.destroy(err)
      return
    }

    // empty the current stream
    if (this._onreadable() === true) this._drained = true

    this._stream = null

    this._update()
    this._maybeDrain()
  }

  _makeStream(start, end) {
    this._stream = this.updates.iterator(this.db, start, end, this.reverse)
    this._stream.on('readable', this._maybeDrainBound)
    this._stream.on('error', noop)
    this._stream.on('close', this._oncloseBound)
  }
}

function noop() {}
const { Readable } = require('streamx')

// used for returned a stream that just errors (during read during teardown)

module.exports = class CloseErrorStream extends Readable {
  constructor(err) {
    super()
    this.error = err
  }

  _open(cb) {
    cb(this.error)
  }
}
const { UINT, STRING } = require('index-encoder')
const c = require('compact-encoding')
const b4a = require('b4a')

const TL_HEAD = 0
const TL_CORE_BY_DKEY = 1
const TL_CORE_BY_ALIAS = 2
const TL_CORE = 3
const TL_DATA = 4
const TL_GROUP_BY_TOPIC = 5
const TL_GROUP = 6

const TL_END = TL_GROUP + 1

const CORE_AUTH = 0
const CORE_SESSIONS = 1
const CORE_GROUP = 2

const DATA_HEAD = 0
const DATA_DEPENDENCY = 1
const DATA_HINTS = 2
const DATA_BLOCK = 3
const DATA_TREE = 4
const DATA_BITFIELD = 5
const DATA_USER_DATA = 6
const DATA_LOCAL = 7
const DATA_MARK = 8

const slab = { buffer: b4a.allocUnsafe(65536), start: 0, end: 0 }

const store = {}
const core = {}
const group = {}

store.clear = function () {
  const state = alloc()
  let start = state.start
  UINT.encode(state, 0)
  const a = state.buffer.subarray(start, state.start)
  start = state.start
  UINT.encode(state, TL_END)
  const b = state.buffer.subarray(start, state.start)
  return [a, b]
}

store.head = function () {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_HEAD)
  return state.buffer.subarray(start, state.start)
}

store.core = function (discoveryKey) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE_BY_DKEY)
  c.fixed32.encode(state, discoveryKey)
  return state.buffer.subarray(start, state.start)
}

store.coreStart = function () {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE_BY_DKEY)
  return state.buffer.subarray(start, state.start)
}

store.coreEnd = function () {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE_BY_DKEY + 1)
  return state.buffer.subarray(start, state.start)
}

store.coreByAlias = function ({ namespace, name }) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE_BY_ALIAS)
  c.fixed32.encode(state, namespace)
  STRING.encode(state, name)
  return state.buffer.subarray(start, state.start)
}

store.coreByAliasStart = function (namespace) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE_BY_ALIAS)
  if (namespace) c.fixed32.encode(state, namespace)
  return state.buffer.subarray(start, state.start)
}

store.coreByAliasEnd = function (namespace) {
  const state = alloc()
  const start = state.start

  if (namespace) {
    UINT.encode(state, TL_CORE_BY_ALIAS)
    c.fixed32.encode(state, namespace)
    state.buffer[state.start++] = 0xff
  } else {
    UINT.encode(state, TL_CORE_BY_ALIAS + 1)
  }

  return state.buffer.subarray(start, state.start)
}

store.alias = function (buffer) {
  const state = { buffer, start: 0, end: buffer.byteLength }
  UINT.decode(state) // ns
  const namespace = c.fixed32.decode(state)
  const name = STRING.decode(state)
  return { namespace, name }
}

store.discoveryKey = function (buffer) {
  const state = { buffer, start: 0, end: buffer.byteLength }
  UINT.decode(state) // ns
  return c.fixed32.decode(state)
}

core.core = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE)
  UINT.encode(state, ptr)
  return state.buffer.subarray(start, state.start)
}

core.data = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  return state.buffer.subarray(start, state.start)
}

core.auth = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE)
  UINT.encode(state, ptr)
  UINT.encode(state, CORE_AUTH)
  return state.buffer.subarray(start, state.start)
}

core.group = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE)
  UINT.encode(state, ptr)
  UINT.encode(state, CORE_GROUP)
  return state.buffer.subarray(start, state.start)
}

core.sessions = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_CORE)
  UINT.encode(state, ptr)
  UINT.encode(state, CORE_SESSIONS)
  return state.buffer.subarray(start, state.start)
}

core.head = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_HEAD)
  return state.buffer.subarray(start, state.start)
}

core.dependency = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_DEPENDENCY)
  return state.buffer.subarray(start, state.start)
}

core.hints = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_HINTS)
  return state.buffer.subarray(start, state.start)
}

core.block = function (ptr, index) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_BLOCK)
  UINT.encode(state, index)
  return state.buffer.subarray(start, state.start)
}

core.tree = function (ptr, index) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_TREE)
  UINT.encode(state, index)
  return state.buffer.subarray(start, state.start)
}

core.bitfield = function (ptr, index, type) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_BITFIELD)
  UINT.encode(state, index)
  UINT.encode(state, type)
  return state.buffer.subarray(start, state.start)
}

core.userData = function (ptr, key) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_USER_DATA)
  STRING.encode(state, key)
  return state.buffer.subarray(start, state.start)
}

core.userDataEnd = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_USER_DATA + 1)
  return state.buffer.subarray(start, state.start)
}

core.mark = function (ptr, index) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_MARK)
  UINT.encode(state, index)
  return state.buffer.subarray(start, state.start)
}

core.local = function (ptr, key) {
  if (key.byteLength > 2048) {
    throw new Error('local keys has an upper limit of 2048 bytes atm')
  }

  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_LOCAL)

  state.buffer.set(key, state.start)
  state.start += key.byteLength
  return state.buffer.subarray(start, state.start)
}

core.localEnd = function (ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_DATA)
  UINT.encode(state, ptr)
  UINT.encode(state, DATA_LOCAL + 1)
  return state.buffer.subarray(start, state.start)
}

core.blockIndex = function (buffer) {
  const state = { buffer, start: 0, end: buffer.byteLength }
  UINT.decode(state) // ns
  UINT.decode(state) // ptr
  UINT.decode(state) // type
  return UINT.decode(state)
}

core.bitfieldIndexAndType = function (buffer) {
  const state = { buffer, start: 0, end: buffer.byteLength }
  UINT.decode(state) // ns
  UINT.decode(state) // ptr
  UINT.decode(state) // type
  return [UINT.decode(state), UINT.decode(state)]
}

core.userDataKey = function (buffer) {
  const state = { buffer, start: 0, end: buffer.byteLength }
  UINT.decode(state) // ns
  UINT.decode(state) // ptr
  UINT.decode(state) // type
  return STRING.decode(state)
}

core.markKey = function (buffer) {
  const state = { buffer, start: 0, end: buffer.byteLength }
  UINT.decode(state) // ns
  UINT.decode(state) // ptr
  UINT.decode(state) // type
  return UINT.decode(state)
}

core.localKey = function (buffer) {
  const state = { buffer, start: 0, end: buffer.byteLength }
  UINT.decode(state) // ns
  UINT.decode(state) // ptr
  UINT.decode(state) // type
  return state.buffer.subarray(state.start, state.end)
}

group.topic = function (topic) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_GROUP_BY_TOPIC)
  c.fixed32.encode(state, topic)
  return state.buffer.subarray(start, state.start)
}

group.entry = function (group, timestamp, ptr) {
  const state = alloc()
  const start = state.start
  UINT.encode(state, TL_GROUP)
  UINT.encode(state, group)
  c.uint64be.encode(state, timestamp)
  UINT.encode(state, ptr)
  return state.buffer.subarray(start, state.start)
}

module.exports = { store, core, group }

function alloc() {
  if (slab.buffer.byteLength - slab.start < 4096) {
    slab.buffer = b4a.allocUnsafe(slab.buffer.byteLength)
    slab.start = 0
  }
  return slab
}
const b4a = require('b4a')
const BlockDependencyStream = require('./block-dependency-stream.js')
const { core, store, group } = require('./keys.js')
const schema = require('../encoding/spec/hyperschema')

const CORESTORE_CORE = schema.getEncoding('@corestore/core')
const CORE_TREE_NODE = schema.getEncoding('@core/tree-node')
const EMPTY = b4a.alloc(0)

module.exports = {
  createBlockStream,
  createBitfieldStream,
  createUserDataStream,
  createCoreStream,
  createAliasStream,
  createDiscoveryKeyStream,
  createTreeNodeStream,
  createMarkStream,
  createLocalStream,
  createGroupUpdateStream
}

function createCoreStream(db, view) {
  const start = store.coreStart()
  const end = store.coreEnd()

  const ite = view.iterator(db, start, end, false)

  ite._readableState.map = mapCore
  return ite
}

function createDiscoveryKeyStream(db, view, namespace) {
  const start = namespace ? store.coreByAliasStart(namespace) : store.coreStart()
  const end = namespace ? store.coreByAliasEnd(namespace) : store.coreEnd()

  const ite = view.iterator(db, start, end, false)

  ite._readableState.map = namespace ? mapNamespaceDiscoveryKeys : mapAllDiscoveryKeys
  return ite
}

function createAliasStream(db, view, namespace) {
  const start = store.coreByAliasStart(namespace)
  const end = store.coreByAliasEnd(namespace)

  const ite = view.iterator(db, start, end, false)

  ite._readableState.map = mapAlias
  return ite
}

function createGroupUpdateStream(db, view, groupID, { gte = 0, reverse = true } = {}) {
  const start = group.entry(groupID, gte, 0)
  const end = group.entry(groupID + 1, 0, 0)

  const ite = view.iterator(db, start, end, reverse)

  ite._readableState.map = mapGroupUpdate
  return ite
}

function createBlockIterator(ptr, db, view, start, end, reverse) {
  if (ptr.dependencies.length > 0) {
    return new BlockDependencyStream(ptr, db, view, start, end, reverse)
  }

  const s = core.block(ptr.dataPointer, start)
  const e = core.block(ptr.dataPointer, end === -1 ? Infinity : end)
  return view.iterator(db, s, e, reverse)
}

function createBlockStream(
  ptr,
  db,
  view,
  { gt = -1, gte = gt + 1, lte = -1, lt = lte === -1 ? -1 : lte + 1, reverse = false } = {}
) {
  const ite = createBlockIterator(ptr, db, view, gte, lt, reverse)

  ite._readableState.map = mapBlock
  return ite
}

function createBitfieldStream(
  ptr,
  db,
  view,
  { gt = -1, gte = gt + 1, lte = -1, lt = lte === -1 ? -1 : lte + 1, reverse = false } = {}
) {
  const s = core.bitfield(ptr.dataPointer, gte, 0)
  const e = core.bitfield(ptr.dataPointer, lt === -1 ? Infinity : lt, 0)
  const ite = view.iterator(db, s, e, false)

  ite._readableState.map = mapBitfield
  return ite
}

// NOTE: this does not do dependency lookups atm
function createTreeNodeStream(
  ptr,
  db,
  view,
  { gt = -1, gte = gt + 1, lte = -1, lt = lte === -1 ? -1 : lte + 1, reverse = false } = {}
) {
  const s = core.tree(ptr.dataPointer, gte, 0)
  const e = core.tree(ptr.dataPointer, lt === -1 ? Infinity : lt, 0)
  const ite = view.iterator(db, s, e, false)

  ite._readableState.map = mapTreeNode
  return ite
}

function createUserDataStream(
  ptr,
  db,
  view,
  { gt = null, gte = '', lte = null, lt = null, reverse = false } = {}
) {
  if (gt !== null || lte !== null) {
    throw new Error('gt and lte not yet supported for user data streams')
  }

  const s = core.userData(ptr.dataPointer, gte)
  const e = lt === null ? core.userDataEnd(ptr.dataPointer) : core.userData(ptr.dataPointer, lt)
  const ite = view.iterator(db, s, e, false)

  ite._readableState.map = mapUserData
  return ite
}

function createMarkStream(
  ptr,
  db,
  view,
  { gt = -1, gte = gt + 1, lte = -1, lt = lte === -1 ? -1 : lte + 1, reverse = false } = {}
) {
  const s = core.mark(ptr.dataPointer, gte)
  const e = core.mark(ptr.dataPointer, lt === -1 ? Infinity : lt)
  const ite = view.iterator(db, s, e, reverse)

  ite._readableState.map = mapMark
  return ite
}

function createLocalStream(
  ptr,
  db,
  view,
  { gt = null, gte = EMPTY, lte = null, lt = null, reverse = false } = {}
) {
  if (gt !== null || lte !== null) throw new Error('gt and lte not yet supported for local streams')

  const s = core.local(ptr.dataPointer, gte)
  const e = lt === null ? core.localEnd(ptr.dataPointer) : core.local(ptr.dataPointer, lt)
  const ite = view.iterator(db, s, e, false)

  ite._readableState.map = mapLocal
  return ite
}

function mapBitfield(data) {
  const [index, type] = core.bitfieldIndexAndType(data.key)
  if (type !== 0) return null // ignore for now
  return { index, page: data.value }
}

function mapMark(data) {
  const index = core.markKey(data.key)
  return { index, page: data.value }
}

function mapLocal(data) {
  const key = core.localKey(data.key)
  return { key, value: data.value }
}

function mapGroupUpdate(data) {
  return data.value
}

function mapUserData(data) {
  const key = core.userDataKey(data.key)
  return { key, value: data.value }
}

function mapCore(data) {
  const discoveryKey = store.discoveryKey(data.key)
  const core = CORESTORE_CORE.decode({
    start: 0,
    end: data.value.byteLength,
    buffer: data.value
  })
  return { discoveryKey, core }
}

function mapAllDiscoveryKeys(data) {
  return store.discoveryKey(data.key)
}

function mapNamespaceDiscoveryKeys(data) {
  return data.value
}

function mapAlias(data) {
  const alias = store.alias(data.key)
  return { alias, discoveryKey: data.value }
}

function mapBlock(data) {
  return { index: core.blockIndex(data.key), value: data.value }
}

function mapTreeNode(data) {
  return CORE_TREE_NODE.decode({
    start: 0,
    end: data.value.byteLength,
    buffer: data.value
  })
}
const b4a = require('b4a')
const c = require('compact-encoding')
const flat = require('flat-tree')

const schema = require('../encoding/spec/hyperschema')
const { store, core, group } = require('./keys.js')
const View = require('./view.js')

const CORESTORE_HEAD = schema.getEncoding('@corestore/head')
const CORESTORE_CORE = schema.getEncoding('@corestore/core')
const CORESTORE_GROUP = c.uint

const CORE_AUTH = schema.getEncoding('@core/auth')
const CORE_GROUP = schema.getEncoding('@core/group')
const CORE_SESSIONS = schema.getEncoding('@core/sessions')
const CORE_HEAD = schema.getEncoding('@core/head')
const CORE_TREE_NODE = schema.getEncoding('@core/tree-node')
const CORE_DEPENDENCY = schema.getEncoding('@core/dependency')
const CORE_HINTS = schema.getEncoding('@core/hints')

class CoreTX {
  constructor(core, db, view, changes) {
    if (db.snapshotted) throw new Error('Cannot open core tx on snapshot')
    this.core = core
    this.db = db
    this.view = view
    this.changes = changes
  }

  setAuth(auth) {
    this.changes.push([core.auth(this.core.corePointer), encode(CORE_AUTH, auth), null])
  }

  setSessions(sessions) {
    this.changes.push([core.sessions(this.core.corePointer), encode(CORE_SESSIONS, sessions), null])
  }

  setHead(head) {
    this.changes.push([core.head(this.core.dataPointer), encode(CORE_HEAD, head), null])
  }

  deleteHead() {
    this.changes.push([core.head(this.core.dataPointer), null, null])
  }

  setDependency(dep) {
    this.changes.push([core.dependency(this.core.dataPointer), encode(CORE_DEPENDENCY, dep), null])
  }

  setGroup(group) {
    this.changes.push([core.group(this.core.dataPointer), encode(CORE_GROUP, group), null])
  }

  deleteGroup() {
    this.changes.push([core.group(this.core.dataPointer), null, null])
  }

  setHints(hints) {
    this.changes.push([core.hints(this.core.dataPointer), encode(CORE_HINTS, hints), null])
  }

  putBlock(index, data) {
    this.changes.push([core.block(this.core.dataPointer, index), data, null])
  }

  deleteBlock(index) {
    this.changes.push([core.block(this.core.dataPointer, index), null, null])
  }

  deleteBlockRange(start, end) {
    this.changes.push([
      core.block(this.core.dataPointer, start),
      null,
      core.block(this.core.dataPointer, end === -1 ? Infinity : end)
    ])
  }

  putBitfieldPage(index, data) {
    this.changes.push([core.bitfield(this.core.dataPointer, index, 0), data, null])
  }

  deleteBitfieldPage(index) {
    this.changes.push([core.bitfield(this.core.dataPointer, index, 0), null, null])
  }

  deleteBitfieldPageRange(start, end) {
    this.changes.push([
      core.bitfield(this.core.dataPointer, start, 0),
      null,
      core.bitfield(this.core.dataPointer, end === -1 ? Infinity : end, 0)
    ])
  }

  putTreeNode(node) {
    this.changes.push([
      core.tree(this.core.dataPointer, node.index),
      encode(CORE_TREE_NODE, node),
      null
    ])
  }

  deleteTreeNode(index) {
    this.changes.push([core.tree(this.core.dataPointer, index), null, null])
  }

  deleteTreeNodeRange(start, end) {
    this.changes.push([
      core.tree(this.core.dataPointer, start),
      null,
      core.tree(this.core.dataPointer, end === -1 ? Infinity : end)
    ])
  }

  putUserData(key, value) {
    const buffer = typeof value === 'string' ? b4a.from(value) : value
    this.changes.push([core.userData(this.core.dataPointer, key), buffer, null])
  }

  deleteUserData(key) {
    this.changes.push([core.userData(this.core.dataPointer, key), null, null])
  }

  putMark(index, data) {
    this.changes.push([core.mark(this.core.dataPointer, index), data, null])
  }

  deleteMark(index) {
    this.changes.push([core.mark(this.core.dataPointer, index), null, null])
  }

  deleteMarkRange(start, end) {
    this.changes.push([
      core.mark(this.core.dataPointer, start),
      null,
      core.mark(this.core.dataPointer, end === -1 ? Infinity : end)
    ])
  }

  putLocal(key, value) {
    this.changes.push([core.local(this.core.dataPointer, key), value, null])
  }

  deleteLocal(key) {
    this.changes.push([core.local(this.core.dataPointer, key), null, null])
  }

  deleteLocalRange(start, end) {
    this.changes.push([
      core.local(this.core.dataPointer, start),
      null,
      end === null ? core.localEnd(this.core.dataPointer) : core.local(this.core.dataPointer, end)
    ])
  }

  putGroupUpdate(groupPtr, timestamp, key) {
    this.changes.push([group.entry(groupPtr, timestamp, this.core.corePointer), key, null])
  }

  deleteGroupUpdate(groupPtr, timestamp) {
    this.changes.push([group.entry(groupPtr, timestamp, this.core.corePointer), null, null])
  }

  flush() {
    const changes = this.changes
    if (changes === null) return Promise.resolve(!this.view)

    this.changes = null

    if (this.view) {
      this.view.apply(changes)
      return Promise.resolve(false)
    }

    return View.flush(changes, this.db)
  }
}

class CoreRX {
  constructor(core, db, view) {
    this.core = core
    this.read = db.read({ autoDestroy: true })
    this.view = view

    view.readStart()
  }

  static async getAuth(db, c) {
    return await decode(CORE_AUTH, await db.get(core.auth(c.corePointer)))
  }

  async getAuth() {
    return await decode(CORE_AUTH, await this.view.get(this.read, core.auth(this.core.corePointer)))
  }

  async getSessions() {
    return await decode(
      CORE_SESSIONS,
      await this.view.get(this.read, core.sessions(this.core.corePointer))
    )
  }

  static async getHead(db, c) {
    return await decode(CORE_HEAD, await db.get(core.head(c.dataPointer)))
  }

  async getHead() {
    return await decode(CORE_HEAD, await this.view.get(this.read, core.head(this.core.dataPointer)))
  }

  async getDependency() {
    return await decode(
      CORE_DEPENDENCY,
      await this.view.get(this.read, core.dependency(this.core.dataPointer))
    )
  }

  async getGroup() {
    return await decode(
      CORE_GROUP,
      await this.view.get(this.read, core.group(this.core.corePointer))
    )
  }

  static async getHints(db, c) {
    return await decode(CORE_HINTS, await db.get(core.hints(c.dataPointer)))
  }

  async getHints() {
    return await decode(
      CORE_HINTS,
      await this.view.get(this.read, core.hints(this.core.dataPointer))
    )
  }

  getBlock(index) {
    const dep = findBlockDependency(this.core.dependencies, index)
    const data = dep === null ? this.core.dataPointer : dep.dataPointer
    return this.view.get(this.read, core.block(data, index))
  }

  getBitfieldPage(index) {
    return this.view.get(this.read, core.bitfield(this.core.dataPointer, index, 0))
  }

  async getTreeNode(index) {
    const dep = findTreeDependency(this.core.dependencies, index)
    const data = dep === null ? this.core.dataPointer : dep.dataPointer
    return decode(CORE_TREE_NODE, await this.view.get(this.read, core.tree(data, index)))
  }

  async hasTreeNode(index) {
    return (await this.getTreeNode(index)) !== null
  }

  getUserData(key) {
    return this.view.get(this.read, core.userData(this.core.dataPointer, key))
  }

  getMark(index) {
    return this.view.get(this.read, core.mark(this.core.dataPointer, index))
  }

  getLocal(key) {
    return this.view.get(this.read, core.local(this.core.dataPointer, key))
  }

  tryFlush() {
    this.read.tryFlush()
    this._free()
  }

  destroy() {
    this.read.destroy()
    this._free()
  }

  _free() {
    if (this.view === null) return
    this.view.readStop()
    this.view = null
  }
}

class CorestoreTX {
  constructor(view) {
    this.view = view
    this.changes = []
  }

  setHead(head) {
    this.changes.push([store.head(), encode(CORESTORE_HEAD, head), null])
  }

  setCoreHints(c, hints) {
    this.changes.push([core.hints(c.dataPointer), encode(CORE_HINTS, hints), null])
  }

  putCore(discoveryKey, ptr) {
    this.changes.push([store.core(discoveryKey), encode(CORESTORE_CORE, ptr), null])
  }

  putCoreByAlias(alias, discoveryKey) {
    this.changes.push([store.coreByAlias(alias), discoveryKey, null])
  }

  putGroup(topic, groupPtr) {
    this.changes.push([group.topic(topic), encode(CORESTORE_GROUP, groupPtr), null])
  }

  deleteGroup(topic) {
    this.changes.push([group.topic(topic), null, null])
  }

  clear() {
    const [start, end] = store.clear()
    this.changes.push([start, null, end])
  }

  apply() {
    if (this.changes === null) return
    this.view.apply(this.changes)
    this.changes = null
  }
}

class CorestoreRX {
  constructor(db, view) {
    this.read = db.read({ autoDestroy: true })
    this.view = view

    view.readStart()
  }

  async getHeadRaw(db) {
    return await this.view.get(this.read, store.head())
  }

  async getHead() {
    return decode(CORESTORE_HEAD, await this.view.get(this.read, store.head()))
  }

  async getCore(discoveryKey) {
    return decode(CORESTORE_CORE, await this.view.get(this.read, store.core(discoveryKey)))
  }

  getCoreByAlias(alias) {
    return this.view.get(this.read, store.coreByAlias(alias))
  }

  async getGroup(topic) {
    return decode(CORESTORE_GROUP, await this.view.get(this.read, group.topic(topic)))
  }

  tryFlush() {
    this.read.tryFlush()
    this._free()
  }

  destroy() {
    this.read.destroy()
    this._free()
  }

  _free() {
    if (this.view === null) return
    this.view.readStop()
    this.view = null
  }
}

module.exports = { CorestoreTX, CorestoreRX, CoreTX, CoreRX }

function findBlockDependency(dependencies, index) {
  for (let i = 0; i < dependencies.length; i++) {
    const dep = dependencies[i]
    if (index < dep.length) return dep
  }

  return null
}

function findTreeDependency(dependencies, index) {
  for (let i = 0; i < dependencies.length; i++) {
    const dep = dependencies[i]
    if (flat.rightSpan(index) <= (dep.length - 1) * 2) return dep
  }

  return null
}

function decode(enc, buffer) {
  if (buffer === null) return null
  return enc.decode({ start: 0, end: buffer.byteLength, buffer })
}

function encode(enc, m) {
  // TODO: use fancy slab for small messages
  const state = { start: 0, end: 0, buffer: null }
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafe(state.end)
  enc.encode(state, m)
  return state.buffer
}
const { Readable, getStreamError } = require('streamx')
const CloseErrorStream = require('./close-error-stream.js')
const b4a = require('b4a')

class OverlayStream extends Readable {
  constructor(stream, start, end, reverse, changes, cleared) {
    super()

    this.start = start
    this.end = end
    this.reverse = reverse
    this.changes = changes
    this.cleared = cleared
    this.change = 0
    this.range = 0

    this._stream = stream
    this._drained = false

    this._stream.on('readable', this._drainMaybe.bind(this))
    this._stream.on('error', noop)
    this._stream.on('close', this._onclose.bind(this))
  }

  _drainMaybe() {
    if (this._drained === true) return
    this._drained = this._onreadable()
  }

  _onclose() {
    if (this.destroying) return

    const err = getStreamError(this._stream)

    if (err !== null) {
      this.destroy(err)
      return
    }

    while (this.change < this.changes.length) {
      const c = this.changes[this.change++]
      const key = c[0]
      const value = c[1]

      if (value !== null && this._inRange(key)) this.push({ key, value })
    }

    this.push(null)
    this._stream = null
  }

  _onreadable() {
    let data = this._stream.read()
    if (data === null) return false

    let drained = false

    do {
      if (this._push(data) === true) drained = true
      data = this._stream.read()
    } while (data !== null)

    return drained
  }

  _read(cb) {
    this._drained = this._onreadable()
    cb(null)
  }

  _predestroy() {
    this._stream.destroy()
  }

  _push(entry) {
    const key = entry.key

    while (this.range < this.cleared.length) {
      const c = this.cleared[this.range]

      // we moved past the range
      if (this.reverse ? b4a.compare(key, c[0]) < 0 : b4a.compare(c[2], key) <= 0) {
        this.range++
        continue
      }

      // we didnt move past and are in, drop
      if (b4a.compare(c[0], key) <= 0 && b4a.compare(key, c[2]) < 0) {
        return false
      }

      break
    }

    let updated = false

    while (this.change < this.changes.length) {
      const c = this.changes[this.change]
      const key = c[0]
      const value = typeof c[1] === 'string' ? b4a.from(c[1]) : c[1]
      const cmp = b4a.compare(key, entry.key)

      // same value, if not deleted, return new one
      if (cmp === 0) {
        this.change++
        if (value === null || this._inRange(key) === false) return updated
        this.push({ key, value })
        return true
      }

      // we moved past the change, push it
      if (this.reverse ? cmp > 0 : cmp < 0) {
        this.change++
        if (value === null || this._inRange(key) === false) continue
        this.push({ key, value })
        updated = true
        continue
      }

      this.push(entry)
      return true
    }

    this.push(entry)
    return true
  }

  _inRange(key) {
    return b4a.compare(this.start, key) <= 0 && b4a.compare(key, this.end) < 0
  }
}

class Overlay {
  constructor() {
    this.indexed = 0
    this.changes = null
    this.cleared = null
    this.reverse = false
  }

  update(view, reverse) {
    if (view.indexed === this.indexed) return

    const changes = view.map === null ? [] : [...view.map.values()]
    const cleared = view.cleared === null ? [] : view.cleared.slice(0)

    const cmp = reverse ? cmpChangeReverse : cmpChange

    changes.sort(cmp)
    cleared.sort(cmp)

    this.indexed = view.indexed
    this.changes = changes
    this.cleared = cleared
    this.reverse = reverse
  }

  createStream(stream, start, end, reverse) {
    return new OverlayStream(
      stream,
      start,
      end,
      reverse,
      this.reverse === reverse ? this.changes : reverseArray(this.changes),
      this.reverse === reverse ? this.cleared : reverseArray(this.cleared)
    )
  }
}

class View {
  constructor() {
    this.map = null
    this.indexed = 0
    this.changes = null
    this.cleared = null
    this.overlay = null
    this.snap = null
    this.readers = 0
  }

  snapshot() {
    if (this._attached()) return this.snap.snapshot()

    const snap = new View()

    snap.map = this.map
    snap.indexed = this.indexed
    snap.changes = this.changes
    snap.cleared = this.cleared

    if (this._frozen()) return snap

    this.readers++
    snap.snap = this

    return snap
  }

  readStart() {
    if (this.snap !== null) this.readers++
  }

  readStop() {
    if (this.snap !== null && --this.readers === 0) this.snap.readers--
  }

  size() {
    return this.changes === null ? 0 : this.changes.length
  }

  updated() {
    return this.changes === null
  }

  get(read, key) {
    return this.changes === null ? read.get(key) : this._indexAndGet(read, key)
  }

  reset() {
    this.indexed = 0
    this.snap = this.map = this.changes = this.cleared = this.overlay = null
  }

  iterator(db, start, end, reverse) {
    if (dbClosing(db)) return new CloseErrorStream(new Error('RocksDB session is closed'))

    const stream = db.iterator({ gte: start, lt: end, reverse })
    if (this.changes === null) return stream

    this._index()

    if (this.overlay === null) this.overlay = new Overlay()
    this.overlay.update(this, reverse)
    return this.overlay.createStream(stream, start, end, reverse)
  }

  _indexAndGet(read, key) {
    this._index()
    const change = this.map.get(b4a.toString(key, 'hex'))

    if (change === undefined) {
      return this.cleared === null ? read.get(key) : this._readAndMaybeDrop(read, key)
    }

    return Promise.resolve(change[1])
  }

  async _readAndMaybeDrop(read, key) {
    const cleared = this.cleared // in case its cleared
    const value = await read.get(key)
    if (value === null) return null

    for (let i = 0; i < cleared.length; i++) {
      const c = cleared[i]
      // check if in range
      if (b4a.compare(c[0], key) <= 0 && b4a.compare(key, c[2]) < 0) return null
    }

    return value
  }

  _attached() {
    return this.snap !== null && this.changes === this.snap.changes
  }

  _frozen() {
    return this.changes === null || (this.snap !== null && this.changes !== this.snap.changes)
  }

  _index() {
    // if we are a snap and we are still attached (ie no mutations), simply copy the refs
    if (this._attached()) {
      this.snap._index()
      this.map = this.snap.map
      this.cleared = this.snap.cleared
      this.indexed = this.snap.indexed
      return
    }

    if (this.map === null) this.map = new Map()
    if (this.changes.length === this.indexed) return

    while (this.indexed < this.changes.length) {
      const c = this.changes[this.indexed++]

      if (c[2] === null) this.map.set(b4a.toString(c[0], 'hex'), c)
      else this._indexRange(c)
    }
  }

  _indexRange(range) {
    const s = b4a.toString(range[0], 'hex')
    const e = b4a.toString(range[2], 'hex')

    for (const [key, c] of this.map) {
      if (s <= key && key < e) this.map.set(key, [c[0], null, null])
    }

    if (this.cleared === null) this.cleared = []
    this.cleared.push(range)
  }

  apply(changes) {
    if (this.snap !== null) throw new Error('Illegal to push changes to a snapshot')

    if (this.readers !== 0 && this.changes !== null) {
      this.changes = this.changes.slice(0)
      this.cleared = this.cleared === null ? null : this.cleared.slice(0)
      this.map = this.map === null ? null : new Map([...this.map])
    }

    if (this.changes === null) {
      this.changes = changes
      return
    }

    for (let i = 0; i < changes.length; i++) {
      this.changes.push(changes[i])
    }
  }

  static async flush(changes, db) {
    if (changes === null) return true

    const w = db.write({ autoDestroy: true })

    for (const [start, value, end] of changes) {
      if (end !== null) w.tryDeleteRange(start, end)
      else if (value !== null) w.tryPut(start, value)
      else w.tryDelete(start)
    }

    await w.flush()

    return true
  }
}

module.exports = View

function cmpChange(a, b) {
  const c = b4a.compare(a[0], b[0])
  return c === 0 ? b4a.compare(a[2], b[2]) : c
}

function cmpChangeReverse(a, b) {
  return cmpChange(b, a)
}

function noop() {}

function reverseArray(list) {
  const r = new Array(list.length)
  for (let i = 0; i < list.length; i++) r[r.length - 1 - i] = list[i]
  return r
}

// TODO: expose from rocks instead
function dbClosing(db) {
  return db._state.closing || db._index === -1
}
const fs = require('fs')
const path = require('path')
const { Readable } = require('streamx')
const b4a = require('b4a')
const flat = require('flat-tree')
const crypto = require('hypercore-crypto')
const c = require('compact-encoding')
const m = require('./messages.js')
const View = require('../../lib/view.js')
const { CorestoreTX, CoreTX, CorestoreRX } = require('../../lib/tx.js')

const EMPTY_NODE = b4a.alloc(40)
const EMPTY_PAGE = b4a.alloc(4096)

let TREE_01_SKIP = null
let TREE_04_SKIP = null
let TREE_16_SKIP = null

class CoreListStream extends Readable {
  constructor (storage) {
    super()

    this.storage = storage
    this.stack = []
  }

  async _open (cb) {
    for (const a of await readdir(path.join(this.storage, 'cores'))) {
      for (const b of await readdir(path.join(this.storage, 'cores', a))) {
        for (const dkey of await readdir(path.join(this.storage, 'cores', a, b))) {
          this.stack.push(path.join(this.storage, 'cores', a, b, dkey))
        }
      }
    }

    cb(null)
  }

  async _read (cb) {
    while (true) {
      const next = this.stack.pop()
      if (!next) {
        this.push(null)
        break
      }

      const oplog = path.join(next, 'oplog')
      const result = await readOplog(oplog)
      if (!result) continue

      this.push(result)
      break
    }

    cb(null)
  }
}

function decodeOplogHeader (state) {
  c.uint32.decode(state) // cksum, ignore for now

  const l = c.uint32.decode(state)
  const length = l >> 2
  const headerBit = l & 1
  const partialBit = l & 2

  if (state.end - state.start < length) return null

  const end = state.start + length
  const result = { header: headerBit, partial: partialBit !== 0, byteLength: length + 8, message: null }

  try {
    result.message = m.oplog.header.decode({ start: state.start, end, buffer: state.buffer })
  } catch {
    return null
  }

  state.start = end
  return result
}

function decodeOplogEntry (state) {
  if (state.end - state.start < 8) return null

  c.uint32.decode(state) // cksum, ignore for now

  const l = c.uint32.decode(state)
  const length = l >>> 2
  const headerBit = l & 1
  const partialBit = l & 2

  if (state.end - state.start < length) return null

  const end = state.start + length

  const result = { header: headerBit, partial: partialBit !== 0, byteLength: length + 8, message: null }

  try {
    result.message = m.oplog.entry.decode({ start: state.start, end, buffer: state.buffer })
  } catch {
    return null
  }

  state.start = end

  return result
}

module.exports = { store, core }

async function store (storage, { version, dryRun = true, gc = true }) {
  const stream = new CoreListStream(storage.path)
  const view = new View()

  const tx = new CorestoreTX(view)
  const head = await storage._getHead(view)
  const primaryKeyFile = path.join(storage.path, 'primary-key')

  const primaryKey = await readFile(primaryKeyFile)

  if (!head.seed) head.seed = primaryKey

  for await (const data of stream) {
    const key = data.header.key
    const discoveryKey = crypto.discoveryKey(data.header.key)
    const files = getFiles(data.path)

    if (head.defaultDiscoveryKey === null) head.defaultDiscoveryKey = discoveryKey

    const core = {
      version: 0, // need later migration
      corePointer: head.allocated.cores++,
      dataPointer: head.allocated.datas++,
      alias: null
    }

    const ptr = { version: 0, corePointer: core.corePointer, dataPointer: core.dataPointer, dependencies: [] }
    const ctx = new CoreTX(ptr, storage.db, view, [])
    const userData = new Map()
    const treeNodes = new Map()

    const auth = {
      key,
      discoveryKey,
      manifest: data.header.manifest,
      keyPair: data.header.keyPair,
      encryptionKey: null
    }

    const tree = {
      length: 0,
      fork: 0,
      rootHash: null,
      signature: null
    }

    if (data.header.tree && data.header.tree.length) {
      tree.length = data.header.tree.length
      tree.fork = data.header.tree.fork
      tree.rootHash = data.header.tree.rootHash
      tree.signature = data.header.tree.signature
    }

    for (const { key, value } of data.header.userData) {
      userData.set(key, value)
    }

    for (const e of data.entries) {
      if (e.userData) userData.set(e.userData.key, e.userData.value)

      if (e.treeNodes) {
        for (const node of e.treeNodes) {
          treeNodes.set(node.index, node)
          ctx.putTreeNode(node)
        }
      }

      if (e.treeUpgrade) {
        if (e.treeUpgrade.ancestors !== tree.length) {
          throw new Error('Unflushed truncations not migrate-able atm')
        }

        tree.length = e.treeUpgrade.length
        tree.fork = e.treeUpgrade.fork
        tree.rootHash = null
        tree.signature = e.treeUpgrade.signature
      }
    }

    if (userData.has('corestore/name') && userData.has('corestore/namespace')) {
      core.alias = {
        name: b4a.toString(userData.get('corestore/name')),
        namespace: userData.get('corestore/namespace')
      }
      userData.delete('corestore/name')
      userData.delete('corestore/namespace')
    }

    for (const [key, value] of userData) {
      ctx.putUserData(key, value)
    }

    ctx.setAuth(auth)

    const getTreeNode = (index) => (treeNodes.get(index) || getTreeNodeFromFile(files.tree, index))

    if (tree.length) {
      if (tree.rootHash === null) tree.rootHash = crypto.tree(await getRoots(tree.length, getTreeNode))
      ctx.setHead(tree)
    }

    tx.putCore(discoveryKey, core)
    if (core.alias) tx.putCoreByAlias(core.alias, discoveryKey)

    await ctx.flush()
  }

  head.version = version
  tx.setHead(head)
  tx.apply()

  if (dryRun) return

  await View.flush(view.changes, storage.db)

  if (gc) await rm(primaryKeyFile)
}

class BlockSlicer {
  constructor (filename) {
    this.stream = fs.createReadStream(filename)
    this.closed = new Promise(resolve => this.stream.once('close', resolve))
    this.offset = 0
    this.overflow = null
  }

  async take (offset, size) {
    let buffer = null
    if (offset < this.offset) throw new Error('overread')

    while (true) {
      let data = null

      if (this.overflow) {
        data = this.overflow
        this.overflow = null
      } else {
        data = this.stream.read()

        if (!data) {
          await new Promise(resolve => this.stream.once('readable', resolve))
          continue
        }
      }

      let chunk = null

      if (this.offset === offset || buffer) {
        chunk = data
      } else if (this.offset + data.byteLength > offset) {
        chunk = data.subarray(offset - this.offset)
      }

      this.offset += data.byteLength
      if (!chunk) continue

      if (buffer) buffer = b4a.concat([buffer, chunk])
      else buffer = chunk

      if (buffer.byteLength < size) continue

      const result = buffer.subarray(0, size)
      this.overflow = size === buffer.byteLength ? null : buffer.subarray(result.byteLength)
      this.offset -= (this.overflow ? this.overflow.byteLength : 0)
      return result
    }
  }

  close () {
    this.stream.on('error', noop)
    this.stream.destroy()
    return this.closed
  }
}

class TreeSlicer {
  constructor () {
    this.buffer = null
    this.offset = 0
  }

  get size () {
    return this.buffer === null ? 0 : this.buffer.byteLength
  }

  push (data) {
    if (this.buffer === null) this.buffer = data
    else this.buffer = b4a.concat([this.buffer, data])
    this.offset += data.byteLength
  }

  skip () {
    let skipped = 0

    if (TREE_01_SKIP === null) {
      TREE_16_SKIP = b4a.alloc(16 * 40 * 100)
      TREE_04_SKIP = TREE_16_SKIP.subarray(0, 4 * 40 * 100)
      TREE_01_SKIP = TREE_16_SKIP.subarray(0, 1 * 40 * 100)
    }

    while (true) {
      if (this.buffer.byteLength >= TREE_16_SKIP.byteLength) {
        if (b4a.equals(this.buffer.subarray(0, TREE_16_SKIP.byteLength), TREE_16_SKIP)) {
          this.buffer = this.buffer.subarray(TREE_16_SKIP.byteLength)
          skipped += 1600
          continue
        }
      }

      if (this.buffer.byteLength >= TREE_04_SKIP.byteLength) {
        if (b4a.equals(this.buffer.subarray(0, TREE_04_SKIP.byteLength), TREE_04_SKIP)) {
          this.buffer = this.buffer.subarray(TREE_04_SKIP.byteLength)
          skipped += 400
          continue
        }
      }

      if (this.buffer.byteLength >= TREE_01_SKIP.byteLength) {
        if (b4a.equals(this.buffer.subarray(0, TREE_01_SKIP.byteLength), TREE_01_SKIP)) {
          this.buffer = this.buffer.subarray(TREE_01_SKIP.byteLength)
          skipped += 100
          continue
        }
      }
      break
    }

    return skipped
  }

  take () {
    const len = 40

    if (len <= this.size) {
      const chunk = this.buffer.subarray(0, len)
      this.buffer = this.buffer.subarray(len)
      return chunk
    }

    return null
  }
}

async function core (core, { version, dryRun = true, gc = true }) {
  if (dryRun) return // dryRun mode not supported atm

  const rx = core.read()

  const promises = [rx.getAuth(), rx.getHead()]
  rx.tryFlush()

  const [auth, head] = await Promise.all(promises)

  if (!auth) return

  const dk = b4a.toString(auth.discoveryKey, 'hex')
  const files = getFiles(path.join(core.store.path, 'cores', dk.slice(0, 2), dk.slice(2, 4), dk))

  if (head === null || head.length === 0) {
    await commitCoreMigration(auth, core, version)
    if (gc) await runGC()
    return // no data
  }

  const oplog = await readOplog(files.oplog)
  if (!oplog) {
    const writable = !!auth.keyPair

    if (writable) {
      throw new Error('No oplog available writable core for ' + files.oplog + ', length = ' + (head ? head.length : 0))
    }

    // if not writable, just nuke it to recover, some bad state happened here, prop corruption from earlier versions
    const w = core.write()

    w.deleteBlockRange(0, -1)
    w.deleteTreeNodeRange(0, -1)
    w.deleteBitfieldPageRange(0, -1)
    w.deleteHead()

    await w.flush()

    await commitCoreMigration(auth, core, version)
    if (gc) await runGC()
    return // no data
  }

  const treeData = new TreeSlicer()

  let treeIndex = 0

  if (await exists(files.tree)) {
    for await (const data of fs.createReadStream(files.tree)) {
      treeData.push(data)

      let write = null

      while (true) {
        const skip = treeData.skip()
        treeIndex += skip

        const buf = treeData.take()
        if (buf === null) break

        const index = treeIndex++
        if (b4a.equals(buf, EMPTY_NODE)) continue

        if (write === null) write = core.write()
        write.putTreeNode(decodeTreeNode(index, buf))
      }

      if (write !== null) await write.flush()
    }
  }

  const buf = []
  if (await exists(files.bitfield)) {
    for await (const data of fs.createReadStream(files.bitfield)) {
      buf.push(data)
    }
  }

  let bitfield = b4a.concat(buf)
  if (bitfield.byteLength & 4095) bitfield = b4a.concat([bitfield, b4a.alloc(4096 - (bitfield.byteLength & 4095))])

  const pages = new Map()
  const headerBits = new Map()

  const roots = await getRootsFromStorage(core, head.length)

  for (const e of oplog.entries) {
    if (!e.bitfield) continue

    for (let i = 0; i < e.bitfield.length; i++) {
      headerBits.set(i + e.bitfield.start, !e.bitfield.drop)
    }
  }

  let batch = []

  const cache = new Map()
  const blocks = new BlockSlicer(files.data)

  for (const index of allBits(bitfield)) {
    if (headerBits.get(index) === false) continue
    if (index >= head.length) continue

    setBitInPage(index)

    batch.push(index)
    if (batch.length < 1024) continue

    await writeBlocksBatch()
    continue
  }

  if (batch.length) await writeBlocksBatch()

  await blocks.close()

  const w = core.write()

  for (const [index, bit] of headerBits) {
    if (!bit) continue
    if (index >= head.length) continue

    setBitInPage(index)

    const blk = await getBlockFromFile(files.data, core, index, roots, cache)
    w.putBlock(index, blk)
  }

  for (const [index, page] of pages) {
    w.putBitfieldPage(index, b4a.from(page.buffer, page.byteOffset, page.byteLength))
  }

  await w.flush()

  let contiguousLength = 0
  for await (const data of core.createBlockStream()) {
    if (data.index === contiguousLength) contiguousLength++
    else break
  }

  if (contiguousLength) {
    const w = core.write()
    w.setHints({ contiguousLength })
    await w.flush()
  }

  await commitCoreMigration(auth, core, version)

  if (gc) await runGC()

  async function runGC () {
    await rm(files.path)
    await rmdir(path.join(files.path, '..'))
    await rmdir(path.join(files.path, '../..'))
    await rmdir(path.join(core.store.path, 'cores'))
  }

  function setBitInPage (index) {
    const n = index & 32767
    const p = (index - n) / 32768

    let page = pages.get(p)

    if (!page) {
      page = new Uint32Array(1024)
      pages.set(p, page)
    }

    const o = n & 31
    const b = (n - o) / 32
    const v = 1 << o

    page[b] |= v
  }

  async function writeBlocksBatch () {
    const read = core.read()
    const promises = []
    for (const index of batch) promises.push(getByteRangeFromStorage(read, 2 * index, roots, cache))
    read.tryFlush()

    const r = await Promise.all(promises)
    const tx = core.write()

    for (let i = 0; i < r.length; i++) {
      const index = batch[i]
      const [offset, size] = r[i]

      const blk = await blocks.take(offset, size)
      tx.putBlock(index, blk)
    }

    batch = []
    if (cache.size > 16384) cache.clear()

    await tx.flush()
  }
}

async function commitCoreMigration (auth, core, version) {
  const view = new View()
  const rx = new CorestoreRX(core.db, view)

  const storeCorePromise = rx.getCore(auth.discoveryKey)
  rx.tryFlush()

  const storeCore = await storeCorePromise

  storeCore.version = version

  const tx = new CorestoreTX(view)

  tx.putCore(auth.discoveryKey, storeCore)
  tx.apply()

  await View.flush(view.changes, core.db)
}

async function getBlockFromFile (file, core, index, roots, cache) {
  const rx = core.read()
  const promise = getByteRangeFromStorage(rx, 2 * index, roots, cache)
  rx.tryFlush()
  const [offset, size] = await promise

  return new Promise(function (resolve) {
    readAll(file, size, offset, function (err, buf) {
      if (err) return resolve(null)
      resolve(buf)
    })
  })
}

function getFiles (dir) {
  return {
    path: dir,
    oplog: path.join(dir, 'oplog'),
    data: path.join(dir, 'data'),
    tree: path.join(dir, 'tree'),
    bitfield: path.join(dir, 'bitfield')
  }
}

async function getRootsFromStorage (core, length) {
  const all = []
  const rx = core.read()
  for (const index of flat.fullRoots(2 * length)) {
    all.push(rx.getTreeNode(index))
  }
  rx.tryFlush()
  return Promise.all(all)
}

async function getRoots (length, getTreeNode) {
  const all = []
  for (const index of flat.fullRoots(2 * length)) {
    all.push(await getTreeNode(index))
  }
  return all
}

function getCached (read, cache, index) {
  if (cache.has(index)) return cache.get(index)
  const p = read.getTreeNode(index)
  cache.set(index, p)
  return p
}

async function getByteRangeFromStorage (read, index, roots, cache) {
  const promises = [getCached(read, cache, index), getByteOffsetFromStorage(read, index, roots, cache)]
  const [node, offset] = await Promise.all(promises)
  if (!node) throw new Error('Node not found during migration: ' + index)
  return [offset, node.size]
}

async function getByteOffsetFromStorage (rx, index, roots, cache) {
  if (index === 0) return 0
  if ((index & 1) === 1) index = flat.leftSpan(index)

  let head = 0
  let offset = 0

  for (const node of roots) { // all async ticks happen once we find the root so safe
    head += 2 * ((node.index - head) + 1)

    if (index >= head) {
      offset += node.size
      continue
    }

    const ite = flat.iterator(node.index)
    const promises = []

    while (ite.index !== index) {
      if (index < ite.index) {
        ite.leftChild()
      } else {
        promises.push(getCached(rx, cache, ite.leftChild()))
        ite.sibling()
      }
    }

    const nodes = await Promise.all(promises)
    for (const node of nodes) offset += node.size

    return offset
  }

  throw new Error('Failed to find offset')
}

function decodeTreeNode (index, buf) {
  return { index, size: c.decode(c.uint64, buf), hash: buf.subarray(8) }
}

async function getTreeNodeFromFile (file, index) {
  return new Promise(function (resolve) {
    readAll(file, 40, index * 40, function (err, buf) {
      if (err) return resolve(null)
      resolve(decodeTreeNode(index, buf))
    })
  })
}

function readAll (filename, length, pos, cb) {
  const buf = b4a.alloc(length)

  fs.open(filename, 'r', function (err, fd) {
    if (err) return cb(err)

    let offset = 0

    fs.read(fd, buf, offset, buf.byteLength, pos, function loop (err, read) {
      if (err) return done(err)
      if (read === 0) return done(new Error('Partial read'))
      offset += read
      if (offset === buf.byteLength) return done(null, buf)
      fs.read(fd, offset, buf.byteLength - offset, buf, pos + offset, loop)
    })

    function done (err, value) {
      fs.close(fd, () => cb(err, value))
    }
  })
}

async function readdir (dir) {
  try {
    return await fs.promises.readdir(dir)
  } catch {
    return []
  }
}

async function exists (file) {
  try {
    await fs.promises.stat(file)
    return true
  } catch {
    return false
  }
}

async function readFile (file) {
  try {
    return await fs.promises.readFile(file)
  } catch {
    return null
  }
}

async function rm (dir) {
  try {
    await fs.promises.rm(dir, { recursive: true })
  } catch {}
}

async function rmdir (dir) {
  try {
    await fs.promises.rmdir(dir)
  } catch {}
}

function * allBits (buffer) {
  for (let i = 0; i < buffer.byteLength; i += EMPTY_PAGE.byteLength) {
    const page = buffer.subarray(i, i + EMPTY_NODE.byteLength)
    if (b4a.equals(page, EMPTY_PAGE)) continue

    const view = new Uint32Array(page.buffer, page.byteOffset, EMPTY_PAGE.byteLength / 4)

    for (let j = 0; j < view.length; j++) {
      const n = view[j]
      if (n === 0) continue

      for (let k = 0; k < 32; k++) {
        const m = 1 << k
        if (n & m) yield i * 8 + j * 32 + k
      }
    }
  }
}

function readOplog (oplog) {
  return new Promise(function (resolve) {
    fs.readFile(oplog, function (err, buffer) {
      if (err) return resolve(null)

      const state = { start: 0, end: buffer.byteLength, buffer }
      const headers = [1, 0]

      const h1 = decodeOplogHeader(state)
      state.start = 4096

      const h2 = decodeOplogHeader(state)
      state.start = 4096 * 2

      if (!h1 && !h2) return resolve(null)

      if (h1 && !h2) {
        headers[0] = h1.header
        headers[1] = h1.header
      } else if (!h1 && h2) {
        headers[0] = (h2.header + 1) & 1
        headers[1] = h2.header
      } else {
        headers[0] = h1.header
        headers[1] = h2.header
      }

      const header = (headers[0] + headers[1]) & 1
      const result = { path: path.dirname(oplog), header: null, entries: [] }
      const decoded = []

      result.header = header ? h2.message : h1.message

      if (result.header.external) {
        fs.readFile(path.join(oplog, '../header'), function (err, buffer) {
          if (err) return resolve(null)
          const start = result.header.external.start
          const end = start + result.header.external.length
          result.header = m.oplog.header.decode({ buffer, start, end })
          finish()
        })
        return
      }

      finish()

      function finish () {
        while (true) {
          const entry = decodeOplogEntry(state)
          if (!entry) break
          if (entry.header !== header) break

          decoded.push(entry)
        }

        while (decoded.length > 0 && decoded[decoded.length - 1].partial) decoded.pop()

        for (const e of decoded) {
          result.entries.push(e.message)
        }

        resolve(result)
      }
    })
  })
}

function noop () {}
// needed here for compat, copied from old hypercore, do not change this

const c = require('compact-encoding')
const b4a = require('b4a')

const EMPTY = b4a.alloc(0)
const DEFAULT_NAMESPACE = b4a.from('4144eea531e483d54e0c14f4ca68e0644f355343ff6fcb0f005200e12cd747cb', 'hex')

const hashes = {
  preencode (state, m) {
    state.end++ // small uint
  },
  encode (state, m) {
    if (m === 'blake2b') {
      c.uint.encode(state, 0)
      return
    }

    throw new Error('Unknown hash: ' + m)
  },
  decode (state) {
    const n = c.uint.decode(state)
    if (n === 0) return 'blake2b'
    throw new Error('Unknown hash id: ' + n)
  }
}

const signatures = {
  preencode (state, m) {
    state.end++ // small uint
  },
  encode (state, m) {
    if (m === 'ed25519') {
      c.uint.encode(state, 0)
      return
    }

    throw new Error('Unknown signature: ' + m)
  },
  decode (state) {
    const n = c.uint.decode(state)
    if (n === 0) return 'ed25519'
    throw new Error('Unknown signature id: ' + n)
  }
}

const signer = {
  preencode (state, m) {
    signatures.preencode(state, m.signature)
    c.fixed32.preencode(state, m.namespace)
    c.fixed32.preencode(state, m.publicKey)
  },
  encode (state, m) {
    signatures.encode(state, m.signature)
    c.fixed32.encode(state, m.namespace)
    c.fixed32.encode(state, m.publicKey)
  },
  decode (state) {
    return {
      signature: signatures.decode(state),
      namespace: c.fixed32.decode(state),
      publicKey: c.fixed32.decode(state)
    }
  }
}

const signerArray = c.array(signer)

const prologue = {
  preencode (state, p) {
    c.fixed32.preencode(state, p.hash)
    c.uint.preencode(state, p.length)
  },
  encode (state, p) {
    c.fixed32.encode(state, p.hash)
    c.uint.encode(state, p.length)
  },
  decode (state) {
    return {
      hash: c.fixed32.decode(state),
      length: c.uint.decode(state)
    }
  }
}

const manifestv0 = {
  preencode (state, m) {
    hashes.preencode(state, m.hash)
    state.end++ // type

    if (m.prologue && m.signers.length === 0) {
      c.fixed32.preencode(state, m.prologue.hash)
      return
    }

    if (m.quorum === 1 && m.signers.length === 1 && !m.allowPatch) {
      signer.preencode(state, m.signers[0])
    } else {
      state.end++ // flags
      c.uint.preencode(state, m.quorum)
      signerArray.preencode(state, m.signers)
    }
  },
  encode (state, m) {
    hashes.encode(state, m.hash)

    if (m.prologue && m.signers.length === 0) {
      c.uint.encode(state, 0)
      c.fixed32.encode(state, m.prologue.hash)
      return
    }

    if (m.quorum === 1 && m.signers.length === 1 && !m.allowPatch) {
      c.uint.encode(state, 1)
      signer.encode(state, m.signers[0])
    } else {
      c.uint.encode(state, 2)
      c.uint.encode(state, m.allowPatch ? 1 : 0)
      c.uint.encode(state, m.quorum)
      signerArray.encode(state, m.signers)
    }
  },
  decode (state) {
    const hash = hashes.decode(state)
    const type = c.uint.decode(state)

    if (type > 2) throw new Error('Unknown type: ' + type)

    if (type === 0) {
      return {
        version: 0,
        hash,
        allowPatch: false,
        quorum: 0,
        signers: [],
        prologue: {
          hash: c.fixed32.decode(state),
          length: 0
        }
      }
    }

    if (type === 1) {
      return {
        version: 0,
        hash,
        allowPatch: false,
        quorum: 1,
        signers: [signer.decode(state)],
        prologue: null
      }
    }

    const flags = c.uint.decode(state)

    return {
      version: 0,
      hash,
      allowPatch: (flags & 1) !== 0,
      quorum: c.uint.decode(state),
      signers: signerArray.decode(state),
      prologue: null
    }
  }
}

const manifest = exports.manifest = {
  preencode (state, m) {
    state.end++ // version
    if (m.version === 0) return manifestv0.preencode(state, m)

    state.end++ // flags
    hashes.preencode(state, m.hash)

    c.uint.preencode(state, m.quorum)
    signerArray.preencode(state, m.signers)
    if (m.prologue) prologue.preencode(state, m.prologue)
  },
  encode (state, m) {
    c.uint.encode(state, m.version)
    if (m.version === 0) return manifestv0.encode(state, m)

    c.uint.encode(state, (m.allowPatch ? 1 : 0) | (m.prologue ? 2 : 0) | (m.unencrypted ? 4 : 0))
    hashes.encode(state, m.hash)

    c.uint.encode(state, m.quorum)
    signerArray.encode(state, m.signers)
    if (m.prologue) prologue.encode(state, m.prologue)
  },
  decode (state) {
    const v = c.uint.decode(state)
    if (v === 0) return manifestv0.decode(state)
    if (v !== 1) throw new Error('Unknown version: ' + v)

    const flags = c.uint.decode(state)
    const hash = hashes.decode(state)
    const quorum = c.uint.decode(state)
    const signers = signerArray.decode(state)
    const unencrypted = (flags & 4) !== 0

    return {
      version: 1,
      hash,
      allowPatch: (flags & 1) !== 0,
      quorum,
      signers,
      prologue: (flags & 2) === 0 ? null : prologue.decode(state),
      unencrypted
    }
  }
}

const node = {
  preencode (state, n) {
    c.uint.preencode(state, n.index)
    c.uint.preencode(state, n.size)
    c.fixed32.preencode(state, n.hash)
  },
  encode (state, n) {
    c.uint.encode(state, n.index)
    c.uint.encode(state, n.size)
    c.fixed32.encode(state, n.hash)
  },
  decode (state) {
    return {
      index: c.uint.decode(state),
      size: c.uint.decode(state),
      hash: c.fixed32.decode(state)
    }
  }
}

const nodeArray = c.array(node)

const wire = exports.wire = {}

wire.handshake = {
  preencode (state, m) {
    c.uint.preencode(state, 1)
    c.fixed32.preencode(state, m.capability)
  },
  encode (state, m) {
    c.uint.encode(state, m.seeks ? 1 : 0)
    c.fixed32.encode(state, m.capability)
  },
  decode (state) {
    const flags = c.uint.decode(state)
    return {
      seeks: (flags & 1) !== 0,
      capability: c.fixed32.decode(state)
    }
  }
}

const requestBlock = {
  preencode (state, b) {
    c.uint.preencode(state, b.index)
    c.uint.preencode(state, b.nodes)
  },
  encode (state, b) {
    c.uint.encode(state, b.index)
    c.uint.encode(state, b.nodes)
  },
  decode (state) {
    return {
      index: c.uint.decode(state),
      nodes: c.uint.decode(state)
    }
  }
}

const requestSeek = {
  preencode (state, s) {
    c.uint.preencode(state, s.bytes)
    c.uint.preencode(state, s.padding)
  },
  encode (state, s) {
    c.uint.encode(state, s.bytes)
    c.uint.encode(state, s.padding)
  },
  decode (state) {
    return {
      bytes: c.uint.decode(state),
      padding: c.uint.decode(state)
    }
  }
}

const requestUpgrade = {
  preencode (state, u) {
    c.uint.preencode(state, u.start)
    c.uint.preencode(state, u.length)
  },
  encode (state, u) {
    c.uint.encode(state, u.start)
    c.uint.encode(state, u.length)
  },
  decode (state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

wire.request = {
  preencode (state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.id)
    c.uint.preencode(state, m.fork)

    if (m.block) requestBlock.preencode(state, m.block)
    if (m.hash) requestBlock.preencode(state, m.hash)
    if (m.seek) requestSeek.preencode(state, m.seek)
    if (m.upgrade) requestUpgrade.preencode(state, m.upgrade)
    if (m.priority) c.uint.preencode(state, m.priority)
  },
  encode (state, m) {
    const flags = (m.block ? 1 : 0) | (m.hash ? 2 : 0) | (m.seek ? 4 : 0) | (m.upgrade ? 8 : 0) | (m.manifest ? 16 : 0) | (m.priority ? 32 : 0)

    c.uint.encode(state, flags)
    c.uint.encode(state, m.id)
    c.uint.encode(state, m.fork)

    if (m.block) requestBlock.encode(state, m.block)
    if (m.hash) requestBlock.encode(state, m.hash)
    if (m.seek) requestSeek.encode(state, m.seek)
    if (m.upgrade) requestUpgrade.encode(state, m.upgrade)
    if (m.priority) c.uint.encode(state, m.priority)
  },
  decode (state) {
    const flags = c.uint.decode(state)

    return {
      id: c.uint.decode(state),
      fork: c.uint.decode(state),
      block: flags & 1 ? requestBlock.decode(state) : null,
      hash: flags & 2 ? requestBlock.decode(state) : null,
      seek: flags & 4 ? requestSeek.decode(state) : null,
      upgrade: flags & 8 ? requestUpgrade.decode(state) : null,
      manifest: (flags & 16) !== 0,
      priority: flags & 32 ? c.uint.decode(state) : 0
    }
  }
}

wire.cancel = {
  preencode (state, m) {
    c.uint.preencode(state, m.request)
  },
  encode (state, m) {
    c.uint.encode(state, m.request)
  },
  decode (state, m) {
    return {
      request: c.uint.decode(state)
    }
  }
}

const dataUpgrade = {
  preencode (state, u) {
    c.uint.preencode(state, u.start)
    c.uint.preencode(state, u.length)
    nodeArray.preencode(state, u.nodes)
    nodeArray.preencode(state, u.additionalNodes)
    c.optionalBuffer.preencode(state, u.signature)
  },
  encode (state, u) {
    c.uint.encode(state, u.start)
    c.uint.encode(state, u.length)
    nodeArray.encode(state, u.nodes)
    nodeArray.encode(state, u.additionalNodes)
    c.optionalBuffer.encode(state, u.signature)
  },
  decode (state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state),
      nodes: nodeArray.decode(state),
      additionalNodes: nodeArray.decode(state),
      signature: c.optionalBuffer.decode(state)
    }
  }
}

const dataSeek = {
  preencode (state, s) {
    c.uint.preencode(state, s.bytes)
    nodeArray.preencode(state, s.nodes)
  },
  encode (state, s) {
    c.uint.encode(state, s.bytes)
    nodeArray.encode(state, s.nodes)
  },
  decode (state) {
    return {
      bytes: c.uint.decode(state),
      nodes: nodeArray.decode(state)
    }
  }
}

const dataBlock = {
  preencode (state, b) {
    c.uint.preencode(state, b.index)
    c.optionalBuffer.preencode(state, b.value)
    nodeArray.preencode(state, b.nodes)
  },
  encode (state, b) {
    c.uint.encode(state, b.index)
    c.optionalBuffer.encode(state, b.value)
    nodeArray.encode(state, b.nodes)
  },
  decode (state) {
    return {
      index: c.uint.decode(state),
      value: c.optionalBuffer.decode(state) || EMPTY,
      nodes: nodeArray.decode(state)
    }
  }
}

const dataHash = {
  preencode (state, b) {
    c.uint.preencode(state, b.index)
    nodeArray.preencode(state, b.nodes)
  },
  encode (state, b) {
    c.uint.encode(state, b.index)
    nodeArray.encode(state, b.nodes)
  },
  decode (state) {
    return {
      index: c.uint.decode(state),
      nodes: nodeArray.decode(state)
    }
  }
}

wire.data = {
  preencode (state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.request)
    c.uint.preencode(state, m.fork)

    if (m.block) dataBlock.preencode(state, m.block)
    if (m.hash) dataHash.preencode(state, m.hash)
    if (m.seek) dataSeek.preencode(state, m.seek)
    if (m.upgrade) dataUpgrade.preencode(state, m.upgrade)
    if (m.manifest) manifest.preencode(state, m.manifest)
  },
  encode (state, m) {
    const flags = (m.block ? 1 : 0) | (m.hash ? 2 : 0) | (m.seek ? 4 : 0) | (m.upgrade ? 8 : 0) | (m.manifest ? 16 : 0)

    c.uint.encode(state, flags)
    c.uint.encode(state, m.request)
    c.uint.encode(state, m.fork)

    if (m.block) dataBlock.encode(state, m.block)
    if (m.hash) dataHash.encode(state, m.hash)
    if (m.seek) dataSeek.encode(state, m.seek)
    if (m.upgrade) dataUpgrade.encode(state, m.upgrade)
    if (m.manifest) manifest.encode(state, m.manifest)
  },
  decode (state) {
    const flags = c.uint.decode(state)

    return {
      request: c.uint.decode(state),
      fork: c.uint.decode(state),
      block: flags & 1 ? dataBlock.decode(state) : null,
      hash: flags & 2 ? dataHash.decode(state) : null,
      seek: flags & 4 ? dataSeek.decode(state) : null,
      upgrade: flags & 8 ? dataUpgrade.decode(state) : null,
      manifest: flags & 16 ? manifest.decode(state) : null
    }
  }
}

wire.noData = {
  preencode (state, m) {
    c.uint.preencode(state, m.request)
  },
  encode (state, m) {
    c.uint.encode(state, m.request)
  },
  decode (state, m) {
    return {
      request: c.uint.decode(state)
    }
  }
}

wire.want = {
  preencode (state, m) {
    c.uint.preencode(state, m.start)
    c.uint.preencode(state, m.length)
  },
  encode (state, m) {
    c.uint.encode(state, m.start)
    c.uint.encode(state, m.length)
  },
  decode (state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

wire.unwant = {
  preencode (state, m) {
    c.uint.preencode(state, m.start)
    c.uint.preencode(state, m.length)
  },
  encode (state, m) {
    c.uint.encode(state, m.start)
    c.uint.encode(state, m.length)
  },
  decode (state, m) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

wire.range = {
  preencode (state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.start)
    if (m.length !== 1) c.uint.preencode(state, m.length)
  },
  encode (state, m) {
    c.uint.encode(state, (m.drop ? 1 : 0) | (m.length === 1 ? 2 : 0))
    c.uint.encode(state, m.start)
    if (m.length !== 1) c.uint.encode(state, m.length)
  },
  decode (state) {
    const flags = c.uint.decode(state)

    return {
      drop: (flags & 1) !== 0,
      start: c.uint.decode(state),
      length: (flags & 2) !== 0 ? 1 : c.uint.decode(state)
    }
  }
}

wire.bitfield = {
  preencode (state, m) {
    c.uint.preencode(state, m.start)
    c.uint32array.preencode(state, m.bitfield)
  },
  encode (state, m) {
    c.uint.encode(state, m.start)
    c.uint32array.encode(state, m.bitfield)
  },
  decode (state, m) {
    return {
      start: c.uint.decode(state),
      bitfield: c.uint32array.decode(state)
    }
  }
}

wire.sync = {
  preencode (state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.fork)
    c.uint.preencode(state, m.length)
    c.uint.preencode(state, m.remoteLength)
  },
  encode (state, m) {
    c.uint.encode(state, (m.canUpgrade ? 1 : 0) | (m.uploading ? 2 : 0) | (m.downloading ? 4 : 0) | (m.hasManifest ? 8 : 0))
    c.uint.encode(state, m.fork)
    c.uint.encode(state, m.length)
    c.uint.encode(state, m.remoteLength)
  },
  decode (state) {
    const flags = c.uint.decode(state)

    return {
      fork: c.uint.decode(state),
      length: c.uint.decode(state),
      remoteLength: c.uint.decode(state),
      canUpgrade: (flags & 1) !== 0,
      uploading: (flags & 2) !== 0,
      downloading: (flags & 4) !== 0,
      hasManifest: (flags & 8) !== 0
    }
  }
}

wire.reorgHint = {
  preencode (state, m) {
    c.uint.preencode(state, m.from)
    c.uint.preencode(state, m.to)
    c.uint.preencode(state, m.ancestors)
  },
  encode (state, m) {
    c.uint.encode(state, m.from)
    c.uint.encode(state, m.to)
    c.uint.encode(state, m.ancestors)
  },
  decode (state) {
    return {
      from: c.uint.encode(state),
      to: c.uint.encode(state),
      ancestors: c.uint.encode(state)
    }
  }
}

wire.extension = {
  preencode (state, m) {
    c.string.preencode(state, m.name)
    c.raw.preencode(state, m.message)
  },
  encode (state, m) {
    c.string.encode(state, m.name)
    c.raw.encode(state, m.message)
  },
  decode (state) {
    return {
      name: c.string.decode(state),
      message: c.raw.decode(state)
    }
  }
}

const keyValue = {
  preencode (state, p) {
    c.string.preencode(state, p.key)
    c.optionalBuffer.preencode(state, p.value)
  },
  encode (state, p) {
    c.string.encode(state, p.key)
    c.optionalBuffer.encode(state, p.value)
  },
  decode (state) {
    return {
      key: c.string.decode(state),
      value: c.optionalBuffer.decode(state)
    }
  }
}

const treeUpgrade = {
  preencode (state, u) {
    c.uint.preencode(state, u.fork)
    c.uint.preencode(state, u.ancestors)
    c.uint.preencode(state, u.length)
    c.optionalBuffer.preencode(state, u.signature)
  },
  encode (state, u) {
    c.uint.encode(state, u.fork)
    c.uint.encode(state, u.ancestors)
    c.uint.encode(state, u.length)
    c.optionalBuffer.encode(state, u.signature)
  },
  decode (state) {
    return {
      fork: c.uint.decode(state),
      ancestors: c.uint.decode(state),
      length: c.uint.decode(state),
      signature: c.optionalBuffer.decode(state)
    }
  }
}

const bitfieldUpdate = { // TODO: can maybe be folded into a HAVE later on with the most recent spec
  preencode (state, b) {
    state.end++ // flags
    c.uint.preencode(state, b.start)
    c.uint.preencode(state, b.length)
  },
  encode (state, b) {
    state.buffer[state.start++] = b.drop ? 1 : 0
    c.uint.encode(state, b.start)
    c.uint.encode(state, b.length)
  },
  decode (state) {
    const flags = c.uint.decode(state)
    return {
      drop: (flags & 1) !== 0,
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

const oplog = exports.oplog = {}

oplog.entry = {
  preencode (state, m) {
    state.end++ // flags
    if (m.userData) keyValue.preencode(state, m.userData)
    if (m.treeNodes) nodeArray.preencode(state, m.treeNodes)
    if (m.treeUpgrade) treeUpgrade.preencode(state, m.treeUpgrade)
    if (m.bitfield) bitfieldUpdate.preencode(state, m.bitfield)
  },
  encode (state, m) {
    const s = state.start++
    let flags = 0

    if (m.userData) {
      flags |= 1
      keyValue.encode(state, m.userData)
    }
    if (m.treeNodes) {
      flags |= 2
      nodeArray.encode(state, m.treeNodes)
    }
    if (m.treeUpgrade) {
      flags |= 4
      treeUpgrade.encode(state, m.treeUpgrade)
    }
    if (m.bitfield) {
      flags |= 8
      bitfieldUpdate.encode(state, m.bitfield)
    }

    state.buffer[s] = flags
  },
  decode (state) {
    const flags = c.uint.decode(state)
    return {
      userData: (flags & 1) !== 0 ? keyValue.decode(state) : null,
      treeNodes: (flags & 2) !== 0 ? nodeArray.decode(state) : null,
      treeUpgrade: (flags & 4) !== 0 ? treeUpgrade.decode(state) : null,
      bitfield: (flags & 8) !== 0 ? bitfieldUpdate.decode(state) : null
    }
  }
}

const keyPair = {
  preencode (state, kp) {
    c.optionalBuffer.preencode(state, kp.publicKey)
    c.optionalBuffer.preencode(state, kp.secretKey)
  },
  encode (state, kp) {
    c.optionalBuffer.encode(state, kp.publicKey)
    c.optionalBuffer.encode(state, kp.secretKey)
  },
  decode (state) {
    return {
      publicKey: c.optionalBuffer.decode(state),
      secretKey: c.optionalBuffer.decode(state)
    }
  }
}

const reorgHint = {
  preencode (state, r) {
    c.uint.preencode(state, r.from)
    c.uint.preencode(state, r.to)
    c.uint.preencode(state, r.ancestors)
  },
  encode (state, r) {
    c.uint.encode(state, r.from)
    c.uint.encode(state, r.to)
    c.uint.encode(state, r.ancestors)
  },
  decode (state) {
    return {
      from: c.uint.decode(state),
      to: c.uint.decode(state),
      ancestors: c.uint.decode(state)
    }
  }
}

const reorgHintArray = c.array(reorgHint)

const hints = {
  preencode (state, h) {
    reorgHintArray.preencode(state, h.reorgs)
    c.uint.preencode(state, h.contiguousLength)
  },
  encode (state, h) {
    reorgHintArray.encode(state, h.reorgs)
    c.uint.encode(state, h.contiguousLength)
  },
  decode (state) {
    return {
      reorgs: reorgHintArray.decode(state),
      contiguousLength: state.start < state.end ? c.uint.decode(state) : 0
    }
  }
}

const treeHeader = {
  preencode (state, t) {
    c.uint.preencode(state, t.fork)
    c.uint.preencode(state, t.length)
    c.optionalBuffer.preencode(state, t.rootHash)
    c.optionalBuffer.preencode(state, t.signature)
  },
  encode (state, t) {
    c.uint.encode(state, t.fork)
    c.uint.encode(state, t.length)
    c.optionalBuffer.encode(state, t.rootHash)
    c.optionalBuffer.encode(state, t.signature)
  },
  decode (state) {
    return {
      fork: c.uint.decode(state),
      length: c.uint.decode(state),
      rootHash: c.optionalBuffer.decode(state),
      signature: c.optionalBuffer.decode(state)
    }
  }
}

const types = {
  preencode (state, t) {
    c.string.preencode(state, t.tree)
    c.string.preencode(state, t.bitfield)
    c.string.preencode(state, t.signer)
  },
  encode (state, t) {
    c.string.encode(state, t.tree)
    c.string.encode(state, t.bitfield)
    c.string.encode(state, t.signer)
  },
  decode (state) {
    return {
      tree: c.string.decode(state),
      bitfield: c.string.decode(state),
      signer: c.string.decode(state)
    }
  }
}

const externalHeader = {
  preencode (state, m) {
    c.uint.preencode(state, m.start)
    c.uint.preencode(state, m.length)
  },
  encode (state, m) {
    c.uint.encode(state, m.start)
    c.uint.encode(state, m.length)
  },
  decode (state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

const keyValueArray = c.array(keyValue)

oplog.header = {
  preencode (state, h) {
    state.end += 2 // version + flags
    if (h.external) {
      externalHeader.preencode(state, h.external)
      return
    }
    c.fixed32.preencode(state, h.key)
    if (h.manifest) manifest.preencode(state, h.manifest)
    if (h.keyPair) keyPair.preencode(state, h.keyPair)
    keyValueArray.preencode(state, h.userData)
    treeHeader.preencode(state, h.tree)
    hints.preencode(state, h.hints)
  },
  encode (state, h) {
    c.uint.encode(state, 1)
    if (h.external) {
      c.uint.encode(state, 1) // ONLY set the first big for clarity
      externalHeader.encode(state, h.external)
      return
    }
    c.uint.encode(state, (h.manifest ? 2 : 0) | (h.keyPair ? 4 : 0))
    c.fixed32.encode(state, h.key)
    if (h.manifest) manifest.encode(state, h.manifest)
    if (h.keyPair) keyPair.encode(state, h.keyPair)
    keyValueArray.encode(state, h.userData)
    treeHeader.encode(state, h.tree)
    hints.encode(state, h.hints)
  },
  decode (state) {
    const version = c.uint.decode(state)

    if (version > 1) {
      throw new Error('Invalid header version. Expected <= 1, got ' + version)
    }

    if (version === 0) {
      const old = {
        types: types.decode(state),
        userData: keyValueArray.decode(state),
        tree: treeHeader.decode(state),
        signer: keyPair.decode(state),
        hints: hints.decode(state)
      }

      return {
        external: null,
        key: old.signer.publicKey,
        manifest: {
          version: 0,
          hash: old.types.tree,
          allowPatch: false,
          quorum: 1,
          signers: [{
            signature: old.types.signer,
            namespace: DEFAULT_NAMESPACE,
            publicKey: old.signer.publicKey
          }],
          prologue: null
        },
        keyPair: old.signer.secretKey ? old.signer : null,
        userData: old.userData,
        tree: old.tree,
        hints: old.hints
      }
    }

    const flags = c.uint.decode(state)

    if (flags & 1) {
      return {
        external: externalHeader.decode(state),
        key: null,
        manifest: null,
        keyPair: null,
        userData: null,
        tree: null,
        hints: null
      }
    }

    return {
      external: null,
      key: c.fixed32.decode(state),
      manifest: (flags & 2) !== 0 ? manifest.decode(state) : null,
      keyPair: (flags & 4) !== 0 ? keyPair.decode(state) : null,
      userData: keyValueArray.decode(state),
      tree: treeHeader.decode(state),
      hints: hints.decode(state)
    }
  }
}

const uintArray = c.array(c.uint)

const multisigInput = {
  preencode (state, inp) {
    c.uint.preencode(state, inp.signer)
    c.fixed64.preencode(state, inp.signature)
    c.uint.preencode(state, inp.patch)
  },
  encode (state, inp) {
    c.uint.encode(state, inp.signer)
    c.fixed64.encode(state, inp.signature)
    c.uint.encode(state, inp.patch)
  },
  decode (state) {
    return {
      signer: c.uint.decode(state),
      signature: c.fixed64.decode(state),
      patch: c.uint.decode(state)
    }
  }
}

const patchEncodingv0 = {
  preencode (state, n) {
    c.uint.preencode(state, n.start)
    c.uint.preencode(state, n.length)
    uintArray.preencode(state, n.nodes)
  },
  encode (state, n) {
    c.uint.encode(state, n.start)
    c.uint.encode(state, n.length)
    uintArray.encode(state, n.nodes)
  },
  decode (state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state),
      nodes: uintArray.decode(state)
    }
  }
}

const multisigInputv0 = {
  preencode (state, n) {
    state.end++
    c.uint.preencode(state, n.signer)
    c.fixed64.preencode(state, n.signature)
    if (n.patch) patchEncodingv0.preencode(state, n.patch)
  },
  encode (state, n) {
    c.uint.encode(state, n.patch ? 1 : 0)
    c.uint.encode(state, n.signer)
    c.fixed64.encode(state, n.signature)
    if (n.patch) patchEncodingv0.encode(state, n.patch)
  },
  decode (state) {
    const flags = c.uint.decode(state)
    return {
      signer: c.uint.decode(state),
      signature: c.fixed64.decode(state),
      patch: (flags & 1) ? patchEncodingv0.decode(state) : null
    }
  }
}

const multisigInputArrayv0 = c.array(multisigInputv0)
const multisigInputArray = c.array(multisigInput)

const compactNode = {
  preencode (state, n) {
    c.uint.preencode(state, n.index)
    c.uint.preencode(state, n.size)
    c.fixed32.preencode(state, n.hash)
  },
  encode (state, n) {
    c.uint.encode(state, n.index)
    c.uint.encode(state, n.size)
    c.fixed32.encode(state, n.hash)
  },
  decode (state) {
    return {
      index: c.uint.decode(state),
      size: c.uint.decode(state),
      hash: c.fixed32.decode(state)
    }
  }
}

const compactNodeArray = c.array(compactNode)

exports.multiSignaturev0 = {
  preencode (state, s) {
    multisigInputArrayv0.preencode(state, s.proofs)
    compactNodeArray.preencode(state, s.patch)
  },
  encode (state, s) {
    multisigInputArrayv0.encode(state, s.proofs)
    compactNodeArray.encode(state, s.patch)
  },
  decode (state) {
    return {
      proofs: multisigInputArrayv0.decode(state),
      patch: compactNodeArray.decode(state)
    }
  }
}

exports.multiSignature = {
  preencode (state, s) {
    multisigInputArray.preencode(state, s.proofs)
    compactNodeArray.preencode(state, s.patch)
  },
  encode (state, s) {
    multisigInputArray.encode(state, s.proofs)
    compactNodeArray.encode(state, s.patch)
  },
  decode (state) {
    return {
      proofs: multisigInputArray.decode(state),
      patch: compactNodeArray.decode(state)
    }
  }
}
const c = require('compact-encoding')
const schema = require('../../encoding/spec/hyperschema')
const { core: coreKey } = require('../../lib/keys.js')
const View = require('../../lib/view.js')

const CORE_AUTH = schema.getEncoding('@core/auth')

const { CorestoreRX, CorestoreTX } = require('../../lib/tx.js')

async function core (core, { version, dryRun = false } = {}) {
  if (dryRun) return // dryRun mode not supported atm

  const rx = core.db.read({ autoDestroy: true })
  const storedAuthPromise = rx.get(coreKey.auth(core.core.corePointer))

  rx.tryFlush()

  const storedAuth = await storedAuthPromise
  if (!storedAuth) return

  const auth = c.decode(CORE_AUTH, storedAuth)
  await commitCoreMigration(auth, core, version)
}

module.exports = { core }

async function commitCoreMigration (auth, core, version) {
  const view = new View()
  const rx = new CorestoreRX(core.db, view)

  const storeCorePromise = rx.getCore(auth.discoveryKey)
  rx.tryFlush()

  const storeCore = await storeCorePromise

  storeCore.version = version

  const tx = new CorestoreTX(view)
  tx.putCore(auth.discoveryKey, storeCore)
  tx.apply()

  await View.flush(view.changes, core.db)
}
{
  "name": "hypercore-storage",
  "version": "3.1.1",
  "main": "index.js",
  "files": [
    "index.js",
    "lib/*.js",
    "encoding/*",
    "migrations/0/*.js",
    "migrations/1/*.js"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:bare": "brittle-bare test/all.js",
    "test:generate": "brittle -r test/all.js test/*.js",
    "test:node": "brittle-node test/all.js"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "description": "Storage engine for Hypercore",
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "fs/*": {
      "bare": "bare-fs/*",
      "default": "fs/*"
    },
    "os": {
      "bare": "bare-os",
      "default": "os"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    }
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/hypercore-storage.git"
  },
  "bugs": {
    "url": "https://github.com/holepunchto/hypercore-storage/issues"
  },
  "homepage": "https://github.com/holepunchto/hypercore-storage#readme",
  "dependencies": {
    "b4a": "^1.6.7",
    "bare-path": "^3.0.0",
    "compact-encoding": "^3.1.0",
    "device-file": "^2.1.2",
    "flat-tree": "^1.12.1",
    "hypercore-crypto": "^3.4.2",
    "hyperschema": "^1.21.0",
    "index-encoder": "^3.3.2",
    "resolve-reject-promise": "^1.0.0",
    "rocksdb-native": "^3.11.0",
    "scope-lock": "^1.2.4",
    "streamx": "^2.21.1"
  },
  "devDependencies": {
    "bare-os": "^3.9.1",
    "brittle": "^3.7.0",
    "hypercore-storage-2.9.0": "npm:hypercore-storage@^2.9.0",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "test-tmp": "^1.3.1"
  }
}
const { EventEmitter } = require('events')
const isOptions = require('is-options')
const crypto = require('hypercore-crypto')
const CoreStorage = require('hypercore-storage')
const c = require('compact-encoding')
const b4a = require('b4a')
const NoiseSecretStream = require('@hyperswarm/secret-stream')
const Protomux = require('protomux')
const id = require('hypercore-id-encoding')
const safetyCatch = require('safety-catch')
const unslab = require('unslab')
const flat = require('flat-tree')
const assert = require('nanoassert')

const { SMALL_WANTS } = require('./lib/feature-flags')
const { UPDATE_COMPAT } = require('./lib/wants')
const MarkBitfield = require('./lib/mark-bitfield')

const inspect = require('./lib/inspect')
const Core = require('./lib/core')
const Info = require('./lib/info')
const Download = require('./lib/download')
const DefaultEncryption = require('./lib/default-encryption')
const caps = require('./lib/caps')
const Replicator = require('./lib/replicator')
const { manifestHash, createManifest } = require('./lib/verifier')
const { ReadStream, WriteStream, ByteStream } = require('./lib/streams')
const { MerkleTree } = require('./lib/merkle-tree')
const { proof, verify } = require('./lib/fully-remote-proof')
const {
  ASSERTION,
  BAD_ARGUMENT,
  SESSION_CLOSED,
  SESSION_MOVED,
  SESSION_NOT_WRITABLE,
  SNAPSHOT_NOT_AVAILABLE,
  DECODING_ERROR,
  REQUEST_CANCELLED
} = require('hypercore-errors')

// Hypercore actually does not have any notion of max/min block sizes
// but we enforce 15mb to ensure smooth replication (each block is transmitted atomically)
const MAX_SUGGESTED_BLOCK_SIZE = 15 * 1024 * 1024

class Hypercore extends EventEmitter {
  constructor(storage, key, opts) {
    super()

    if (isOptions(storage) && !storage.db) {
      opts = storage
      storage = null
      key = opts.key || null
    } else if (isOptions(key)) {
      opts = key
      key = opts.key || null
    }

    if (key && typeof key === 'string') key = id.decode(key)
    if (!opts) opts = {}

    if (!storage) storage = opts.storage

    this.core = null
    this.state = null
    this.encryption = null
    this.extensions = new Map()

    this.valueEncoding = null
    this.encodeBatch = null
    this.activeRequests = []
    this.sessions = null
    this.ongc = null

    this.keyPair = opts.keyPair || null
    this.readable = true
    this.writable = false
    this.exclusive = false
    this.opened = false
    this.closed = false
    this.weak = !!opts.weak
    this.snapshotted = !!opts.snapshot
    this.onseq = opts.onseq || null
    this.onwait = opts.onwait || null
    this.wait = opts.wait !== false
    this.timeout = opts.timeout || 0
    this.preload = null
    this.closing = null
    this.opening = null

    this._readonly = opts.writable === false
    this._preappend = preappend.bind(this)
    this._snapshot = null
    this._findingPeers = 0
    this._active = opts.weak ? !!opts.active : opts.active !== false

    this.waits = 0

    // Mark & Sweep GC
    this._marking = false
    this._marks = null

    this._sessionIndex = -1
    this._stateIndex = -1 // maintained by session state
    this._monitorIndex = -1 // maintained by replication state

    this.opening = this._open(storage, key, opts)
    this.opening.catch(safetyCatch)

    this.on('newListener', maybeAddMonitor)
  }

  [Symbol.for('nodejs.util.inspect.custom')](depth, opts) {
    return inspect(this, depth, opts)
  }

  static MAX_SUGGESTED_BLOCK_SIZE = MAX_SUGGESTED_BLOCK_SIZE

  static DefaultEncryption = DefaultEncryption

  static SMALL_WANTS = SMALL_WANTS

  static enable(flag) {
    const enableCompat = (flag & SMALL_WANTS) === 0
    UPDATE_COMPAT(enableCompat)
  }

  static setRecoveryPeers(peers) {
    Core.setRecoveryPeers(peers)
  }

  static key(manifest, { compat, version, namespace } = {}) {
    if (b4a.isBuffer(manifest)) {
      manifest = { version, signers: [{ publicKey: manifest, namespace }] }
    }
    return compat ? manifest.signers[0].publicKey : manifestHash(createManifest(manifest))
  }

  static discoveryKey(key) {
    return crypto.discoveryKey(key)
  }

  static blockEncryptionKey(key, encryptionKey) {
    return DefaultEncryption.blockEncryptionKey(key, encryptionKey)
  }

  static getProtocolMuxer(stream) {
    return stream.noiseStream.userData
  }

  static createCore(storage, opts) {
    return new Core(Hypercore.defaultStorage(storage), { autoClose: false, ...opts })
  }

  static createProtocolStream(isInitiator, opts = {}) {
    let outerStream = Protomux.isProtomux(isInitiator)
      ? isInitiator.stream
      : isStream(isInitiator)
        ? isInitiator
        : opts.stream

    let noiseStream = null

    if (outerStream) {
      noiseStream = outerStream.noiseStream
    } else {
      noiseStream = new NoiseSecretStream(isInitiator, null, opts)
      outerStream = noiseStream.rawStream
    }
    if (!noiseStream) throw BAD_ARGUMENT('Invalid stream', this.discoveryKey)

    if (!noiseStream.userData) {
      const protocol = Protomux.from(noiseStream)

      if (opts.keepAlive !== false && noiseStream.keepAlive === 0) {
        noiseStream.setKeepAlive(5000)
      }
      noiseStream.userData = protocol
    }

    if (opts.ondiscoverykey) {
      const ondiscoverykey = createDiscoveryKeyHandler(opts.ondiscoverykey)
      noiseStream.userData.pair({ protocol: 'hypercore/alpha' }, ondiscoverykey)
    }

    return outerStream
  }

  static defaultStorage(storage, opts = {}) {
    if (CoreStorage.isCoreStorage(storage)) return storage

    const directory = storage
    return new CoreStorage(directory, opts)
  }

  static clearRequests(session, err) {
    Replicator.clearRequests(session, err)
  }

  static destroyRequests(session, err) {
    Replicator.clearRequests(session, err)
    session.push(null) // mark as dead
  }

  static async treeHashFromStorage(session, length = session.length) {
    const roots = await MerkleTree.getRoots(session.state, length)
    return crypto.tree(roots)
  }

  snapshot(opts) {
    return this.session({ ...opts, snapshot: true })
  }

  compact() {
    return this.core.compact()
  }

  session(opts = {}) {
    if (this.closing) {
      // This makes the closing logic a lot easier. If this turns out to be a problem
      // in practice, open an issue and we'll try to make a solution for it.
      throw SESSION_CLOSED('Cannot make sessions on a closing core', this.discoveryKey)
    }
    if (opts.checkout !== undefined && !opts.name && !opts.atom) {
      throw ASSERTION('Checkouts are only supported on atoms or named sessions', this.discoveryKey)
    }

    const wait = opts.wait === false ? false : this.wait
    const writable = opts.writable === undefined ? !this._readonly : opts.writable === true
    const onwait = opts.onwait === undefined ? this.onwait : opts.onwait
    const onseq = opts.onseq === undefined ? this.onseq : opts.onseq
    const timeout = opts.timeout === undefined ? this.timeout : opts.timeout
    const weak = opts.weak === undefined ? this.weak : opts.weak
    const marking = this._marking
    const marks = this._marks
    const Clz = opts.class || Hypercore
    const s = new Clz(null, this.key, {
      ...opts,
      wait,
      onwait,
      onseq,
      timeout,
      writable,
      weak,
      parent: this
    })
    s._marking = marking
    s._marks = marks

    return s
  }

  async setEncryptionKey(key, opts) {
    if (!this.opened) await this.opening
    const encryption = this._getEncryptionProvider({ key, block: !!(opts && opts.block) })
    return this.setEncryption(encryption)
  }

  async setEncryption(encryption) {
    if (!this.opened) await this.opening

    if (encryption === null) {
      this.encryption = encryption
      return
    }

    if (!isEncryptionProvider(encryption)) {
      throw ASSERTION('Provider does not satisfy HypercoreEncryption interface', this.discoveryKey)
    }

    this.encryption = encryption
  }

  async setGroup(topic) {
    if (!this.opened) await this.opening
    return this.core.setGroup(topic)
  }

  setKeyPair(keyPair) {
    this.keyPair = keyPair
  }

  setActive(bool) {
    const active = !!bool
    if (active === this._active || this.closing) return
    this._active = active
    if (!this.opened) return
    this.core.replicator.updateActivity(this._active ? 1 : -1)
  }

  async _open(storage, key, opts) {
    const preload = opts.preload || (opts.parent && opts.parent.preload)

    if (preload) {
      this.sessions = [] // in case someone looks at it like with peers
      this.preload = preload
      opts = { ...opts, ...(await this.preload) }
      this.preload = null
    }

    const parent = opts.parent || null
    const core = opts.core || (parent && parent.core)
    const sessions = opts.sessions || (parent && parent.sessions)
    const ongc = opts.ongc || (parent && parent.ongc)

    if (core) this.core = core
    if (ongc) this.ongc = ongc
    if (sessions) this.sessions = sessions

    if (this.sessions === null) this.sessions = []
    this._sessionIndex = this.sessions.push(this) - 1

    if (this.core === null) initOnce(this, storage, key, opts)
    if (this._monitorIndex === -2) this.core.addMonitor(this)

    try {
      await this._openSession(opts)
    } catch (err) {
      if (this.core.autoClose && this.core.hasSession() === false) await this.core.close()

      if (this.exclusive) this.core.unlockExclusive()

      this.core.removeMonitor(this)
      this._removeSession()

      if (this.state !== null) this.state.removeSession(this)

      this.closed = true
      this.emit('close')
      throw err
    }

    // Setup automatic recovery if in repair mode
    if (this.core._repairMode) {
      const recoverTreeNodeFromPeersBound = this.recoverTreeNodeFromPeers.bind(this)
      this.once('repaired', () => {
        this.off('peer-add', recoverTreeNodeFromPeersBound)
      })
      this.on('peer-add', recoverTreeNodeFromPeersBound)
    }

    this.emit('ready')

    // if we are a weak session the core might have closed...
    if (this.core.closing) this.close().catch(safetyCatch)
  }

  _removeSession() {
    if (this._sessionIndex === -1) return
    const head = this.sessions.pop()
    if (head !== this) this.sessions[(head._sessionIndex = this._sessionIndex)] = head
    this._sessionIndex = -1
    if (this.ongc !== null) this.ongc(this)
  }

  async _openSession(opts) {
    if (this.core.opened === false) await this.core.ready()

    if (this.keyPair === null) this.keyPair = opts.keyPair || this.core.header.keyPair

    const parent = opts.parent || null
    if (parent && parent.encryption) this.encryption = parent.encryption

    const e = getEncryptionOption(opts)
    if (!this.encryption) this.encryption = this._getEncryptionProvider(e)

    this.writable = this._isWritable()

    if (opts.valueEncoding) {
      this.valueEncoding = c.from(opts.valueEncoding)
    }
    if (opts.encodeBatch) {
      this.encodeBatch = opts.encodeBatch
    }

    // one session sets for pushOnly for all
    if (opts.pushOnly === true) {
      this.core.replicator.setPushOnly(true)
    }

    if (parent) {
      if (parent._stateIndex === -1) await parent.ready()
      if (!this.keyPair) this.keyPair = parent.keyPair

      const ps = parent.state

      if (ps) {
        const shouldSnapshot = this.snapshotted && !ps.isSnapshot()
        this.state = shouldSnapshot ? await ps.snapshot() : ps.ref()
      }

      if (this.snapshotted && this.core && !this._snapshot) {
        this._updateSnapshot()
      }
    }

    if (opts.exclusive && opts.writable !== false) {
      this.exclusive = true
      await this.core.lockExclusive()
    }

    const parentState = parent ? parent.state : this.core.state
    const checkout = opts.checkout === undefined ? -1 : opts.checkout
    const state = this.state

    if (opts.atom) {
      this.state = await parentState.createSession(null, false, opts.atom)
      if (state) state.unref()
    } else if (opts.name) {
      // todo: need to make named sessions safe before ready
      // atm we always copy the state in passCapabilities
      this.state = await parentState.createSession(opts.name, !!opts.overwrite, null)
      if (state) state.unref() // ref'ed above in setup session
    }

    if (this.state && checkout !== -1) {
      if (!opts.name && !opts.atom) {
        throw ASSERTION('Checkouts must be named or atomized', this.discoveryKey)
      }
      if (checkout > this.state.length) {
        throw ASSERTION(
          `Invalid checkout ${checkout} for ${opts.name}, length is ${this.state.length}`,
          this.discoveryKey
        )
      }
      if (this.state.prologue && checkout < this.state.prologue.length) {
        throw ASSERTION(
          `Invalid checkout ${checkout} for ${opts.name}, prologue length is ${this.state.prologue.length}`,
          this.discoveryKey
        )
      }
      if (checkout < this.state.length) await this.state.truncate(checkout, this.fork)
    }

    if (this.state === null) {
      this.state = this.core.state.ref()
    }

    this.writable = this._isWritable()

    if (this.snapshotted && this.core) this._updateSnapshot()

    this.state.addSession(this)
    // TODO: we need to rework the core reference flow, as the state and session do not always agree now due to moveTo
    this.core = this.state.core // in case it was wrong...

    if (opts.userData) {
      const tx = this.state.storage.write()
      for (const [key, value] of Object.entries(opts.userData)) {
        tx.putUserData(key, value)
      }
      await tx.flush()
    }

    if (opts.manifest && !this.core.header.manifest) {
      await this.core.setManifest(createManifest(opts.manifest))
    }

    this.core.replicator.updateActivity(this._active ? 1 : 0)

    this.opened = true
  }

  get replicator() {
    return this.core === null ? null : this.core.replicator
  }

  _getSnapshot() {
    return {
      length: this.state.length,
      byteLength: this.state.byteLength,
      fork: this.state.fork
    }
  }

  _updateSnapshot() {
    const prev = this._snapshot
    const next = (this._snapshot = this._getSnapshot())

    if (!prev) return true
    return prev.length !== next.length || prev.fork !== next.fork
  }

  _isWritable() {
    if (this._readonly) return false
    if (this.state && !this.state.isDefault()) return true
    return !!(this.keyPair && this.keyPair.secretKey)
  }

  close({ error } = {}) {
    if (this.closing) return this.closing

    this.closing = this._close(error || null)
    return this.closing
  }

  clearRequests(activeRequests, error) {
    if (!activeRequests.length) return
    if (this.core) this.core.replicator.clearRequests(activeRequests, error)
  }

  async _close(error) {
    if (this.opened === false) {
      try {
        await this.opening
      } catch (err) {
        if (!this.closed) throw err
      }
    }

    if (this.closed === true) return

    this.core.removeMonitor(this)
    this.state.removeSession(this)
    this._removeSession()

    this.readable = false
    this.writable = false
    this.opened = false

    const gc = []
    for (const ext of this.extensions.values()) {
      if (ext.session === this) gc.push(ext)
    }
    for (const ext of gc) ext.destroy()

    this.core.replicator.findingPeers -= this._findingPeers
    this.core.replicator.clearRequests(this.activeRequests, error)
    this.core.replicator.updateActivity(this._active ? -1 : 0)

    this._findingPeers = 0

    this.state.unref()

    if (this.exclusive) this.core.unlockExclusive()

    if (this.core.hasSession()) {
      // emit "fake" close as this is a session
      this.closed = true
      this.emit('close')
      return
    }

    if (this.core.autoClose) await this.core.close()

    this.closed = true
    this.emit('close')
  }

  async commit(session, opts) {
    await this.ready()
    await session.ready()

    return this.state.commit(session.state, { keyPair: this.keyPair, ...opts })
  }

  replicate(isInitiator, opts = {}) {
    // Only limitation here is that ondiscoverykey doesn't work atm when passing a muxer directly,
    // because it doesn't really make a lot of sense.
    if (Protomux.isProtomux(isInitiator)) return this._attachToMuxer(isInitiator)

    // if same stream is passed twice, ignore the 2nd one before we make sessions etc
    if (isStream(isInitiator) && this._isAttached(isInitiator)) return isInitiator

    const protocolStream = Hypercore.createProtocolStream(isInitiator, opts)
    const noiseStream = protocolStream.noiseStream
    const protocol = noiseStream.userData

    this._attachToMuxer(protocol)

    return protocolStream
  }

  _isAttached(stream) {
    return (
      stream.userData &&
      this.core &&
      this.core.replicator &&
      this.core.replicator.attached(stream.userData)
    )
  }

  _attachToMuxer(mux) {
    if (this.opened) {
      this.core.replicator.attachTo(mux)
    } else {
      this.opening.then(() => this.core.replicator.attachTo(mux), mux.destroy.bind(mux))
    }

    return mux
  }

  get id() {
    return this.core === null ? null : this.core.id
  }

  get key() {
    return this.core === null ? null : this.core.key
  }

  get discoveryKey() {
    return this.core === null ? null : this.core.discoveryKey
  }

  get manifest() {
    return this.core === null ? null : this.core.manifest
  }

  get length() {
    if (this._snapshot) return this._snapshot.length
    return this.opened === false ? 0 : this.state.length
  }

  get signedLength() {
    return this.opened === false ? 0 : this.state.signedLength()
  }

  /**
   * Deprecated. Use `const { byteLength } = await core.info()`.
   */
  get byteLength() {
    if (this.opened === false) return 0
    if (this._snapshot) return this._snapshot.byteLength
    return this.state.byteLength - this.state.length * this.padding
  }

  get remoteContiguousLength() {
    if (this.opened === false) return 0
    return Math.min(this.core.state.length, this.core.header.hints.remoteContiguousLength)
  }

  get contiguousLength() {
    if (this.opened === false) return 0
    return Math.min(this.core.state.length, this.core.header.hints.contiguousLength)
  }

  get contiguousByteLength() {
    return 0
  }

  get fork() {
    if (this.opened === false) return 0
    return this.state.fork
  }

  get padding() {
    if (this.encryption && this.key && this.manifest) {
      return this.encryption.padding(this.core, this.length)
    }

    return 0
  }

  get peers() {
    return this.opened === false ? [] : this.core.replicator.peers
  }

  get globalCache() {
    return this.opened === false ? null : this.core.globalCache
  }

  get recovering() {
    return this.opened === false ? 0 : this.core.header.hints.recovering
  }

  ready() {
    return this.opening
  }

  async recover() {
    if (this.opened === false) await this.opening
    return this.state.waitForRecovery()
  }

  async setUserData(key, value) {
    if (this.opened === false) await this.opening
    const existing = await this.getUserData(key)
    if (existing && b4a.isBuffer(value) && b4a.equals(existing, value)) return
    await this.state.setUserData(key, value)
  }

  async getUserData(key) {
    if (this.opened === false) await this.opening
    const batch = this.state.storage.read()
    const p = batch.getUserData(key)
    batch.tryFlush()
    return p
  }

  transferSession(core) {
    // todo: validate we can move

    if (this.weak === false) {
      this.core.activeSessions--
      core.activeSessions++
    }

    if (this._monitorIndex >= 0) {
      this.core.removeMonitor(this)
      core.addMonitor(this)
    }

    const old = this.core

    this.core = core

    old.replicator.clearRequests(this.activeRequests, SESSION_MOVED())

    this.emit('migrate', this.key)
  }

  findingPeers() {
    this._findingPeers++
    if (this.core !== null && !this.closing) this.core.replicator.findingPeers++

    let once = true

    return () => {
      if (this.closing || !once) return
      once = false
      this._findingPeers--
      if (this.core !== null && --this.core.replicator.findingPeers === 0) {
        this.core.replicator.updateAll()
      }
    }
  }

  async info(opts) {
    if (this.opened === false) await this.opening

    return Info.from(this, opts)
  }

  async update(opts) {
    if (this.opened === false) await this.opening
    if (this.closing !== null) return false
    if (this.snapshotted) return false

    if (this.writable && (!opts || opts.force !== true)) return false

    const remoteWait = this._shouldWait(opts, this.core.replicator.findingPeers > 0)

    let upgraded = false

    if (await this.core.replicator.applyPendingReorg()) {
      upgraded = true
    }

    if (!upgraded && remoteWait) {
      const activeRequests = (opts && opts.activeRequests) || this.activeRequests
      if (isRequestsDestroyed(activeRequests)) throw REQUEST_CANCELLED()

      const req = this.core.replicator.addUpgrade(activeRequests)

      try {
        upgraded = await req.promise
      } catch (err) {
        if (isSessionMoved(err)) return this.update(opts)
        throw err
      }
    }

    if (!upgraded) return false
    return true
  }

  async seek(bytes, opts) {
    if (this.opened === false) await this.opening
    if (!isValidIndex(bytes)) throw ASSERTION('seek is invalid', this.discoveryKey)

    const activeRequests = (opts && opts.activeRequests) || this.activeRequests
    if (isRequestsDestroyed(activeRequests)) throw REQUEST_CANCELLED()

    if (this.encryption && !this.core.manifest) {
      const req = this.replicator.addUpgrade(activeRequests)
      try {
        await req.promise
      } catch (err) {
        if (isSessionMoved(err)) return this.seek(bytes, opts)
        throw err
      }
    }

    const s = MerkleTree.seek(this.state, bytes, this.padding)

    const offset = await s.update()
    if (offset) return offset

    if (this.closing !== null) {
      throw SESSION_CLOSED('cannot seek on a closed session', this.discoveryKey)
    }

    if (!this._shouldWait(opts, this.wait)) return null

    if (isRequestsDestroyed(activeRequests)) throw REQUEST_CANCELLED()
    const req = this.core.replicator.addSeek(activeRequests, s)

    const timeout = opts && opts.timeout !== undefined ? opts.timeout : this.timeout
    if (timeout) req.context.setTimeout(req, timeout)

    try {
      return await req.promise
    } catch (err) {
      if (isSessionMoved(err)) return this.seek(bytes, opts)
      throw err
    }
  }

  async has(start, end = start + 1) {
    if (this.opened === false) await this.opening
    if (!isValidIndex(start) || !isValidIndex(end)) {
      throw ASSERTION('has range is invalid', this.discoveryKey)
    }

    if (this.state.isDefault()) {
      if (end === start + 1) return this.core.bitfield.get(start)

      const i = this.core.bitfield.firstUnset(start)
      return i === -1 || i >= end
    }

    if (end === start + 1) {
      const rx = this.state.storage.read()
      const block = rx.getBlock(start)
      rx.tryFlush()

      return (await block) !== null
    }

    let count = 0

    const stream = this.state.storage.createBlockStream({ gte: start, lt: end })
    for await (const block of stream) {
      if (block === null) return false
      count++
    }

    return count === end - start
  }

  async get(index, opts) {
    if (this.opened === false) await this.opening
    if (!isValidIndex(index)) throw ASSERTION('block index is invalid', this.discoveryKey)

    if (this.closing !== null) {
      throw SESSION_CLOSED('cannot get on a closed session', this.discoveryKey)
    }

    const encoding =
      (opts && opts.valueEncoding && c.from(opts.valueEncoding)) || this.valueEncoding

    if (this.onseq !== null) this.onseq(index, this)
    if (this._marking) await this.markBlock(index)

    const req = this._get(index, opts)

    let block = await req
    if (!block) return null

    if (opts && opts.raw) return block

    if (this.encryption && (!opts || opts.decrypt !== false)) {
      // Copy the block as it might be shared with other sessions.
      block = b4a.from(block)

      await this.encryption.decrypt(index, block, this.core)
    }

    return this._decode(encoding, block, index)
  }

  async clear(start, end = start + 1, opts) {
    if (this.opened === false) await this.opening
    if (this.closing !== null) {
      throw SESSION_CLOSED('cannot clear on a closed session', this.discoveryKey)
    }

    if (typeof end === 'object') {
      opts = end
      end = start + 1
    }

    if (!isValidIndex(start) || !isValidIndex(end)) {
      throw ASSERTION('clear range is invalid', this.discoveryKey)
    }

    const cleared = opts && opts.diff ? { blocks: 0 } : null

    if (start >= end) return cleared
    if (start >= this.length) return cleared

    await this.state.clear(start, end, cleared)

    return cleared
  }

  async purge() {
    await this._closeAllSessions(null)
    await this.core.purge()
  }

  async _get(index, opts) {
    const block = await readBlock(this.state.storage.read(), index)

    if (block !== null) return block

    if (this.closing !== null) {
      throw SESSION_CLOSED('cannot get on a closed session', this.discoveryKey)
    }

    // snapshot should check if core has block
    if (this._snapshot !== null) {
      checkSnapshot(this, index)
      const coreBlock = await readBlock(this.core.state.storage.read(), index)

      checkSnapshot(this, index)
      if (coreBlock !== null) return coreBlock
    }

    // lets check the bitfield to see if we got it during the above async calls
    // this is the last resort before replication, so always safe.
    if (this.core.bitfield.get(index)) {
      const coreBlock = await readBlock(this.state.storage.read(), index)
      // TODO: this should not be needed, only needed atm in case we are doing a moveTo during this (we should fix)
      if (coreBlock !== null) return coreBlock
    }

    if (!this._shouldWait(opts, this.wait)) return null

    this.waits++
    if (opts && opts.onwait) opts.onwait(index, this)
    if (this.onwait) this.onwait(index, this)

    const activeRequests = (opts && opts.activeRequests) || this.activeRequests
    if (isRequestsDestroyed(activeRequests)) throw REQUEST_CANCELLED()

    const force = opts ? opts.force === true : false
    const req = this.core.replicator.addBlock(activeRequests, index, force)
    req.snapshot = index < this.length

    const timeout = opts && opts.timeout !== undefined ? opts.timeout : this.timeout
    if (timeout) req.context.setTimeout(req, timeout)

    let replicatedBlock = null

    try {
      replicatedBlock = await req.promise
    } catch (err) {
      if (isSessionMoved(err)) return this._get(index, opts)
      throw err
    }

    if (this._snapshot !== null) checkSnapshot(this, index)
    return maybeUnslab(replicatedBlock)
  }

  _shouldWait(opts, defaultValue) {
    if (opts) {
      if (opts.wait === false) return false
      if (opts.wait === true) return true
    }
    return defaultValue
  }

  _setupMarks() {
    if (this._marks === null) {
      const storage = this.snapshotted ? this.core.state.storage : this.state.storage
      this._marks = new MarkBitfield(storage)
    }
  }

  async markBlock(start, end = start + 1) {
    if (this.opened === false) await this.opening

    this._setupMarks()

    // TODO support as single rocks batch
    const setPromises = []
    for (let i = start; i < end; i++) {
      setPromises.push(this._marks.set(i, true))
    }

    return Promise.all(setPromises)
  }

  async clearMarkings() {
    if (this.opened === false) await this.opening

    this._setupMarks()

    await this._marks.clear()
    this._marks = null
  }

  async startMarking() {
    if (this._marking) {
      throw ASSERTION("Hypercore cannot be gc'ed when already in gc mode", this.discoveryKey)
    }
    if (this.state && this.state.name) {
      throw ASSERTION("Hypercore cannot be gc'ed when a named session", this.discoveryKey)
    }
    if (this.state && this.state.storage.atom) {
      throw ASSERTION("Hypercore cannot be gc'ed when an atomic session", this.discoveryKey)
    }
    if (this.opened === false) await this.opening
    await this.clearMarkings()

    this._marking = true
  }

  async sweep({ batchSize = 1000 } = {}) {
    if (this.opened === false) await this.opening

    assert(!this.snapshotted, 'Cannot sweep a snapshot')

    // No marks - load from storage
    this._setupMarks()

    let clearing = []
    let prevIndex = this.length
    for await (const index of this._marks.createMarkStream({ reverse: true })) {
      if (index + 1 === prevIndex) {
        prevIndex = index
        continue
      }
      clearing.push(this.clear(index + 1, prevIndex))
      if (clearing.length >= batchSize) {
        await Promise.all(clearing)
        clearing = []
      }
      prevIndex = index
    }
    // Clear range from the very start if not marked
    if (prevIndex > 0) clearing.push(this.clear(0, prevIndex))
    await Promise.all(clearing)

    this._marking = false
    await this.clearMarkings()
  }

  createReadStream(opts) {
    return new ReadStream(this, opts)
  }

  createWriteStream() {
    return new WriteStream(this)
  }

  createByteStream(opts) {
    return new ByteStream(this, opts)
  }

  download(range) {
    return new Download(this, range)
  }

  // TODO: get rid of this / deprecate it?
  undownload(range) {
    range.destroy(null)
  }

  // TODO: get rid of this / deprecate it?
  cancel(request) {
    // Do nothing for now
  }

  async truncate(newLength = 0, opts = {}) {
    if (this.opened === false) await this.opening
    if (this.closing) throw SESSION_CLOSED('Cannot append to a closed session', this.discoveryKey)

    const {
      fork = this.state.fork + 1,
      keyPair = this.keyPair,
      signature = null
    } = typeof opts === 'number' ? { fork: opts } : opts

    const isDefault = this.state === this.core.state
    const writable = !this._readonly && !!(signature || (keyPair && keyPair.secretKey))
    if (isDefault && writable === false && (newLength > 0 || fork !== this.state.fork)) {
      throw SESSION_NOT_WRITABLE('cannot append to a non-writable core', this.discoveryKey)
    }

    await this.state.truncate(newLength, fork, { keyPair, signature })

    // TODO: Should propagate from an event triggered by the oplog
    if (this.state === this.core.state) this.core.replicator.updateAll()
  }

  async append(blocks, opts = {}) {
    if (this.opened === false) await this.opening
    if (this.closing) throw SESSION_CLOSED('Cannot append to a closed session', this.discoveryKey)

    const isDefault = this.state === this.core.state
    const defaultKeyPair = this.state.name === null ? this.keyPair : null

    const { keyPair = defaultKeyPair, signature = null, maxLength, postappend = null } = opts
    const writable =
      !isDefault || !!signature || !!(keyPair && keyPair.secretKey) || opts.writable === true

    if (this._readonly || writable === false) {
      throw SESSION_NOT_WRITABLE('cannot append to a readonly core', this.discoveryKey)
    }

    blocks = Array.isArray(blocks) ? blocks : [blocks]

    const preappend = this.encryption && this._preappend

    const buffers = this.encodeBatch !== null ? this.encodeBatch(blocks) : new Array(blocks.length)

    if (this.encodeBatch === null) {
      for (let i = 0; i < blocks.length; i++) {
        buffers[i] = this._encode(this.valueEncoding, blocks[i])
      }
    }
    for (const b of buffers) {
      if (b.byteLength > MAX_SUGGESTED_BLOCK_SIZE) {
        throw BAD_ARGUMENT(
          'Appended block exceeds the maximum suggested block size',
          this.discoveryKey
        )
      }
    }

    return this.state.append(buffers, { keyPair, signature, preappend, postappend, maxLength })
  }

  async signable(length = -1, fork = -1) {
    if (this.opened === false) await this.opening
    if (length === -1) length = this.length
    if (fork === -1) fork = this.fork

    return caps.treeSignable(this.key, await this.treeHash(length), length, fork)
  }

  async treeHash(length = -1) {
    if (this.opened === false) await this.opening
    if (length === -1) length = this.length
    if (length > 0 && !(await this.has(length - 1))) await this.get(length - 1)

    const roots = await MerkleTree.getRoots(this.state, length)
    return crypto.tree(roots)
  }

  async missingNodes(index) {
    if (this.opened === false) await this.opening
    return await MerkleTree.missingNodes(this.core.state, 2 * index, this.core.state.length)
  }

  async proof(opts) {
    if (this.opened === false) await this.opening
    const rx = this.state.storage.read()
    const proofPromise = MerkleTree.proof(this.state, rx, opts)
    const blockPromise = opts && opts.block ? rx.getBlock(opts.block.index) : null
    rx.tryFlush()
    const [proof, block] = await Promise.all([proofPromise, blockPromise])
    const settled = await proof.settle()
    if (block) settled.block.value = block
    return settled
  }

  async applyProof(proof, from) {
    if (this.opened === false) await this.opening
    return this.core.verify(proof, from)
  }

  async verifyFullyRemote(proof) {
    if (this.opened === false) await this.opening
    const batch = await MerkleTree.verifyFullyRemote(this.state, proof)
    await this.core._verifyBatchUpgrade(batch, proof.manifest)
    return batch
  }

  generateRemoteProofForTreeNode(treeNodeIndex) {
    const blockProofIndex = flat.rightSpan(treeNodeIndex) / 2
    return proof(this, {
      index: blockProofIndex,
      // + 1 to length so the block is included
      upgrade: { start: 0, length: blockProofIndex + 1 }
    })
  }

  async recoverFromRemoteProof(remoteProof) {
    this.core.replicator.setPushOnly(true)
    this.core._repairMode = true

    await this.core.state.mutex.lock()

    try {
      const p = await verify(this.core.db, remoteProof)
      if (!p) return false

      const tx = this.core.storage.write()
      for (const node of p.proof.upgrade.nodes) {
        tx.putTreeNode(node)
      }
      await tx.flush()

      const succeed = p.proof.upgrade.nodes.length !== 0
      if (succeed) {
        this.core.replicator.setPushOnly(false)
      }
      return succeed
    } finally {
      this.core.state.mutex.unlock()
    }
  }

  recoverTreeNodeFromPeers() {
    this.core.replicator.setPushOnly(true)

    for (const peer of this.core.replicator.peers) {
      const req = {
        id: 0,
        fork: this.fork,
        upgrade: {
          start: 0,
          length: this.length
        }
      }
      peer.wireRequest.send(req)
    }
  }

  registerExtension(name, handlers = {}) {
    if (this.extensions.has(name)) {
      const ext = this.extensions.get(name)
      ext.handlers = handlers
      ext.encoding = c.from(handlers.encoding || c.buffer)
      ext.session = this
      return ext
    }

    const ext = {
      name,
      handlers,
      encoding: c.from(handlers.encoding || c.buffer),
      session: this,
      send(message, peer) {
        const buffer = c.encode(this.encoding, message)
        peer.extension(name, buffer)
      },
      broadcast(message) {
        const buffer = c.encode(this.encoding, message)
        for (const peer of this.session.peers) {
          peer.extension(name, buffer)
        }
      },
      destroy() {
        for (const peer of this.session.peers) {
          if (peer.extensions.get(name) === ext) peer.extensions.delete(name)
        }
        this.session.extensions.delete(name)
      },
      _onmessage(state, peer) {
        const m = this.encoding.decode(state)
        if (this.handlers.onmessage) this.handlers.onmessage(m, peer)
      }
    }

    this.extensions.set(name, ext)

    if (this.core === null) this._monitorIndex = -2
    else this.core.addMonitor(this)

    for (const peer of this.peers) {
      peer.extensions.set(name, ext)
    }

    return ext
  }

  _encode(enc, val) {
    const state = { start: this.padding, end: this.padding, buffer: null }

    if (b4a.isBuffer(val)) {
      if (state.start === 0) return val
      state.end += val.byteLength
    } else if (enc) {
      enc.preencode(state, val)
    } else {
      val = b4a.from(val)
      if (state.start === 0) return val
      state.end += val.byteLength
    }

    state.buffer = b4a.allocUnsafe(state.end)

    if (enc) enc.encode(state, val)
    else state.buffer.set(val, state.start)

    return state.buffer
  }

  _decode(enc, block, index) {
    if (this.encryption) block = block.subarray(this.encryption.padding(this.core, index))
    try {
      if (enc) return c.decode(enc, block)
    } catch (err) {
      throw DECODING_ERROR(err.message, this.discoveryKey)
    }
    return block
  }

  _getEncryptionProvider(e) {
    if (isEncryptionProvider(e)) return e
    if (!e || !e.key) return null
    return new DefaultEncryption(e.key, this.key, { block: e.block, compat: this.core.compat })
  }
}

module.exports = Hypercore

function isStream(s) {
  return typeof s === 'object' && s && typeof s.pipe === 'function'
}

async function preappend(blocks) {
  const offset = this.state.length
  const fork = this.state.encryptionFork

  for (let i = 0; i < blocks.length; i++) {
    await this.encryption.encrypt(offset + i, blocks[i], fork, this.core)
  }
}

function isValidIndex(index) {
  return index === 0 || index > 0
}

function maybeUnslab(block) {
  // Unslab only when it takes up less then half the slab
  return block !== null && 2 * block.byteLength < block.buffer.byteLength ? unslab(block) : block
}

function checkSnapshot(snapshot, index) {
  if (index >= snapshot.state.snapshotCompatLength) {
    throw SNAPSHOT_NOT_AVAILABLE(
      `snapshot at index ${index} not available (max compat length ${snapshot.state.snapshotCompatLength})`,
      snapshot.discoveryKey
    )
  }
}

function readBlock(rx, index) {
  const promise = rx.getBlock(index)
  rx.tryFlush()
  return promise
}

function initOnce(session, storage, key, opts) {
  if (storage === null) storage = opts.storage || null
  if (key === null) key = opts.key || null

  session.core = new Core(Hypercore.defaultStorage(storage), {
    preopen: opts.preopen,
    eagerUpgrade: opts.eagerUpgrade !== false,
    notDownloadingLinger: opts.notDownloadingLinger,
    allowFork: opts.allowFork !== false,
    allowPush: !!opts.allowPush,
    pushOnly: !!opts.pushOnly,
    alwaysLatestBlock: !!opts.allowLatestBlock,
    inflightRange: opts.inflightRange,
    compat: opts.compat === true,
    force: opts.force,
    createIfMissing: opts.createIfMissing,
    discoveryKey: opts.discoveryKey,
    overwrite: opts.overwrite,
    key,
    keyPair: opts.keyPair,
    legacy: opts.legacy,
    manifest: opts.manifest,
    group: opts.group,
    globalCache: opts.globalCache || null // session is a temp option, not to be relied on unless you know what you are doing (no semver guarantees)
  })
}

function maybeAddMonitor(name) {
  if (name === 'append' || name === 'truncate') return
  if (this._monitorIndex >= 0 || this.closing) return

  if (this.core === null) {
    this._monitorIndex = -2
  } else {
    this.core.addMonitor(this)
  }
}

function isSessionMoved(err) {
  return err.code === 'SESSION_MOVED'
}

function getEncryptionOption(opts) {
  // old style, supported for now but will go away
  if (opts.encryptionKey) return { key: opts.encryptionKey, block: !!opts.isBlockKey }
  if (!opts.encryption) return null
  return b4a.isBuffer(opts.encryption) ? { key: opts.encryption } : opts.encryption
}

function isEncryptionProvider(e) {
  return e && isFunction(e.padding) && isFunction(e.encrypt) && isFunction(e.decrypt)
}

function isFunction(fn) {
  return !!fn && typeof fn === 'function'
}

function createDiscoveryKeyHandler(fn) {
  return ondiscoverykey
  function ondiscoverykey(id) {
    if (!id || id.byteLength !== 32) throw BAD_ARGUMENT('Invalid discovery key')
    return fn(id)
  }
}

function isRequestsDestroyed(activeRequests) {
  // TODO: move this to an object instead so we can store a property in next major
  return activeRequests.length > 0 && activeRequests[0] === null
}
const crypto = require('hypercore-crypto')
const flat = require('flat-tree')
const b4a = require('b4a')
const { MerkleTree } = require('./merkle-tree')

module.exports = async function auditCore(
  core,
  { tree = true, blocks = true, bitfield = true, dryRun = false } = {}
) {
  const length = core.state.length
  const stats = {
    treeNodes: 0,
    blocks: 0,
    bits: 0,
    droppedTreeNodes: 0,
    droppedBlocks: 0,
    droppedBits: 0,
    corrupt: false
  }

  // audit the tree
  if (tree) {
    let tx = null

    const roots = await MerkleTree.getRootsFromStorage(core.state.storage, length)
    const stack = []

    for (const r of roots) {
      if (r === null) {
        if (!dryRun) {
          const storage = core.state.storage
          await storage.store.deleteCore(storage.core)
          return null
        }

        stats.corrupt = true
      }

      stack.push(r)
    }

    stats.treeNodes += roots.length

    while (stack.length > 0) {
      const node = stack.pop()

      if ((node.index & 1) === 0) continue

      const [left, right] = flat.children(node.index)

      const rx = core.state.storage.read()
      const leftNodePromise = rx.getTreeNode(left)
      const rightNodePromise = rx.getTreeNode(right)

      rx.tryFlush()

      const [leftNode, rightNode] = await Promise.all([leftNodePromise, rightNodePromise])

      if (isBadTree(node, leftNode, rightNode)) {
        if (!tx && !stats.corrupt) tx = core.state.storage.write()
        const [l, r] = flat.spans(node.index)
        tx.deleteTreeNodeRange(l, r + 1)
        stats.droppedTreeNodes++
        continue
      }

      if (!leftNode) continue

      stats.treeNodes += 2
      stack.push(leftNode, rightNode)
    }

    if (tx && !dryRun) await tx.flush()
  }

  // audit the blocks
  if (blocks) {
    let tx = null

    for await (const block of core.state.storage.createBlockStream()) {
      if (!core.bitfield.get(block.index)) {
        if (!tx && !stats.corrupt) tx = core.state.storage.write()
        tx.deleteBlock(block.index)
        stats.droppedBlocks++
      }

      const rx = core.state.storage.read()
      const treeNodePromise = rx.getTreeNode(2 * block.index)

      rx.tryFlush()

      const treeNode = await treeNodePromise

      if (isBadBlock(treeNode, block.value)) {
        if (!tx && !stats.corrupt) tx = core.state.storage.write()
        tx.deleteBlock(block.index)
        stats.droppedBlocks++
        continue
      }

      stats.blocks++
    }

    if (tx && !dryRun) await tx.flush()
  }

  if (bitfield) {
    let tx = null

    for (const index of allBits(core.bitfield)) {
      const rx = core.state.storage.read()
      const blockPromise = rx.getBlock(index)

      rx.tryFlush()

      const block = await blockPromise
      if (!block) {
        stats.droppedBits++
        if (dryRun) continue

        if (!tx && !stats.corrupt) tx = core.state.storage.write()

        core.bitfield.set(index, false)

        const page = core.bitfield.getBitfield(index)
        if (page.bitfield) tx.putBitfieldPage(page.index, page.bitfield)
        else tx.deleteBitfieldPage(page.index)
        continue
      }

      stats.bits++
    }

    if (tx && !dryRun) await tx.flush()
  }

  return stats
}

function isBadBlock(node, block) {
  if (!node) return true
  const hash = crypto.data(block)
  return !b4a.equals(hash, node.hash) || node.size !== block.byteLength
}

function isBadTree(parent, left, right) {
  if (!left && !right) return false
  if (!left || !right) return true
  const hash = crypto.parent(left, right)
  return !b4a.equals(hash, parent.hash) || parent.size !== left.size + right.size
}

function* allBits(bitfield) {
  let i = 0
  if (bitfield.get(0)) yield 0
  while (true) {
    i = bitfield.findFirst(true, i + 1)
    if (i === -1) break
    yield i
  }
}
const b4a = require('b4a')
const quickbit = require('./compat').quickbit

module.exports = class BitInterlude {
  constructor() {
    this.ranges = []
  }

  contiguousLength(from) {
    for (const r of this.ranges) {
      if (r.start > from) break
      if (!r.value && r.start <= from) return r.start
    }

    // TODO: be smarter
    while (this.get(from) === true) from++
    return from
  }

  get(index) {
    let start = 0
    let end = this.ranges.length

    while (start < end) {
      const mid = (start + end) >> 1
      const r = this.ranges[mid]

      if (index < r.start) {
        end = mid
        continue
      }

      if (index >= r.end) {
        if (mid === start) break
        start = mid
        continue
      }

      return r.value
    }

    return false
  }

  setRange(start, end, value) {
    if (start === end) return

    let r = null

    for (let i = 0; i < this.ranges.length; i++) {
      r = this.ranges[i]

      // if already inside, stop
      if (r.start <= start && end <= r.end) {
        if (value === r.value) return

        const ranges = mergeRanges(r, { start, end, value })
        this.ranges.splice(i, 1, ...ranges)

        return
      }

      // we wanna overun the interval
      if (start > r.end) {
        continue
      }

      // we overran but this interval is ending after us, move it back
      if (end >= r.start && end <= r.end) {
        r.start = r.value === value ? start : end
        if (r.value !== value) this.ranges.splice(i, 0, { start, end, value })
        return
      }

      // we overran but our start is contained in this interval, move start back
      if (start >= r.start && start <= r.end) {
        if (r.value !== value) {
          r.end = start // Crop current comparison

          // If there's a next range
          if (this.ranges.length - 1 > i) {
            const next = this.ranges[i + 1]
            // If the same, go next
            if (next.value === value) continue
            // Else we overlap so update next range
            if (next.start < end) next.start = end
          }

          this.ranges.splice(++i, 0, { start, end, value })
          return
        }

        start = r.start
      }

      let remove = 0

      for (let j = i; j < this.ranges.length; j++) {
        const n = this.ranges[j]
        if (n.start > end || n.value !== value) break
        if (n.start <= end && n.end > end) end = n.end
        remove++
      }

      this.ranges.splice(i, remove, { start, end, value })
      return
    }

    if (r !== null) {
      if (start <= r.end && end > r.end) {
        r.end = end
        return
      }

      // we never
      if (r.end > start) return
    }

    this.ranges.push({ start, end, value })
  }

  flush(tx, bitfield) {
    if (!this.ranges.length) return []

    let index = this.ranges[0].start
    const final = this.ranges[this.ranges.length - 1].end

    let i = 0

    while (index < final) {
      const page = bitfield.getBitfield(index) // read only
      const pageIndex = page ? page.index : bitfield.getPageIndex(index)

      const buf = b4a.allocUnsafe(bitfield.getPageByteLength())

      if (page) {
        const src = page.bitfield // Uint32Array
        buf.set(b4a.from(src.buffer, src.byteOffset, src.byteLength), 0)
      } else {
        b4a.fill(buf, 0)
      }

      const last = (pageIndex + 1) * (buf.byteLength << 3)
      const offset = pageIndex * (buf.byteLength << 3)

      let hasValue = false

      while (i < this.ranges.length) {
        const { start, end, value } = this.ranges[i]

        if (!hasValue && value) hasValue = true

        const from = start < index ? index : start
        const to = end < last ? end : last

        quickbit.fill(buf, value, from - offset, to - offset)

        index = to

        if (to === last) break

        i++
      }

      if (page || hasValue) tx.putBitfieldPage(pageIndex, buf)
    }

    return this.ranges
  }
}

function mergeRanges(a, b) {
  const ranges = []
  if (a.start < b.start) ranges.push({ start: a.start, end: b.start, value: a.value })
  ranges.push({ start: b.start, end: b.end, value: b.value })
  if (b.end < a.end) ranges.push({ start: b.end, end: a.end, value: a.value })

  return ranges
}
const BigSparseArray = require('big-sparse-array')
const b4a = require('b4a')
const quickbit = require('./compat').quickbit

const BITS_PER_PAGE = 32768
const BYTES_PER_PAGE = BITS_PER_PAGE / 8
const WORDS_PER_PAGE = BYTES_PER_PAGE / 4
const BITS_PER_SEGMENT = 2097152
const BYTES_PER_SEGMENT = BITS_PER_SEGMENT / 8
const WORDS_PER_SEGMENT = BYTES_PER_SEGMENT / 4
const INITIAL_WORDS_PER_SEGMENT = 1024
const PAGES_PER_SEGMENT = BITS_PER_SEGMENT / BITS_PER_PAGE
const SEGMENT_GROWTH_FACTOR = 4

class BitfieldPage {
  constructor(index, segment) {
    this.index = index
    this.offset = index * BYTES_PER_PAGE - segment.offset
    this.bitfield = null
    this.segment = segment

    segment.add(this)
  }

  get tree() {
    return this.segment.tree
  }

  get(index, dirty) {
    return quickbit.get(this.bitfield, index)
  }

  set(index, val) {
    if (quickbit.set(this.bitfield, index, val)) {
      this.tree.update(this.offset * 8 + index)
    }
  }

  setRange(start, end, val) {
    quickbit.fill(this.bitfield, val, start, end)

    let i = Math.floor(start / 128)
    const n = i + Math.ceil((end - start) / 128)

    while (i <= n) this.tree.update(this.offset * 8 + i++ * 128)
  }

  findFirst(val, position) {
    return quickbit.findFirst(this.bitfield, val, position)
  }

  findLast(val, position) {
    return quickbit.findLast(this.bitfield, val, position)
  }

  count(start, length, val) {
    const end = start + length

    let i = start
    let c = 0

    while (length > 0) {
      const l = this.findFirst(val, i)
      if (l === -1 || l >= end) return c

      const h = this.findFirst(!val, l + 1)
      if (h === -1 || h >= end) return c + end - l

      c += h - l
      length -= h - i
      i = h
    }

    return c
  }
}

class BitfieldSegment {
  constructor(index, bitfield) {
    this.index = index
    this.offset = index * BYTES_PER_SEGMENT
    this.tree = quickbit.Index.from(bitfield, BYTES_PER_SEGMENT)
    this.pages = new Array(PAGES_PER_SEGMENT)
  }

  get bitfield() {
    return this.tree.field
  }

  add(page) {
    const i = page.index - this.index * PAGES_PER_SEGMENT
    this.pages[i] = page

    const start = i * WORDS_PER_PAGE
    const end = start + WORDS_PER_PAGE

    if (end >= this.bitfield.length) this.reallocate(end)

    page.bitfield = this.bitfield.subarray(start, end)
  }

  reallocate(length) {
    let target = this.bitfield.length
    while (target < length) target *= SEGMENT_GROWTH_FACTOR

    const bitfield = new Uint32Array(target)
    bitfield.set(this.bitfield)

    this.tree = quickbit.Index.from(bitfield, BYTES_PER_SEGMENT)

    for (let i = 0; i < this.pages.length; i++) {
      const page = this.pages[i]
      if (!page) continue

      const start = i * WORDS_PER_PAGE
      const end = start + WORDS_PER_PAGE

      page.bitfield = bitfield.subarray(start, end)
    }
  }

  findFirst(val, position) {
    position = this.tree.skipFirst(!val, position)

    let j = position & (BITS_PER_PAGE - 1)
    let i = (position - j) / BITS_PER_PAGE

    if (i >= PAGES_PER_SEGMENT) return -1

    while (i < this.pages.length) {
      const p = this.pages[i]

      let index = -1

      if (p) index = p.findFirst(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_PAGE + index

      j = 0
      i++
    }

    return -1
  }

  findLast(val, position) {
    position = this.tree.skipLast(!val, position)

    let j = position & (BITS_PER_PAGE - 1)
    let i = (position - j) / BITS_PER_PAGE

    if (i >= PAGES_PER_SEGMENT) return -1

    while (i >= 0) {
      const p = this.pages[i]

      let index = -1

      if (p) index = p.findLast(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_PAGE + index

      j = BITS_PER_PAGE - 1
      i--
    }

    return -1
  }
}

module.exports = class Bitfield {
  static BITS_PER_PAGE = BITS_PER_PAGE
  static BYTES_PER_PAGE = BYTES_PER_PAGE

  constructor(buffer) {
    this.resumed = !!(buffer && buffer.byteLength >= 0)

    this._pages = new BigSparseArray()
    this._segments = new BigSparseArray()

    const view = this.resumed
      ? new Uint32Array(buffer.buffer, buffer.byteOffset, Math.floor(buffer.byteLength / 4))
      : new Uint32Array(INITIAL_WORDS_PER_SEGMENT)

    for (let i = 0; i < view.length; i += WORDS_PER_SEGMENT) {
      let bitfield = view.subarray(i, i + WORDS_PER_SEGMENT)
      let length = WORDS_PER_SEGMENT

      if (i === 0) {
        length = INITIAL_WORDS_PER_SEGMENT
        while (length < bitfield.length) length *= SEGMENT_GROWTH_FACTOR
      }

      if (bitfield.length !== length) {
        const copy = new Uint32Array(length)
        copy.set(bitfield, 0)
        bitfield = copy
      }

      const segment = new BitfieldSegment(i / WORDS_PER_SEGMENT, bitfield)
      this._segments.set(segment.index, segment)

      for (let j = 0; j < bitfield.length; j += WORDS_PER_PAGE) {
        const page = new BitfieldPage((i + j) / WORDS_PER_PAGE, segment)
        this._pages.set(page.index, page)
      }
    }
  }

  static from(bitfield) {
    return new Bitfield(bitfield.toBuffer(bitfield._pages.maxLength * BITS_PER_PAGE))
  }

  toBuffer(length) {
    const pages = Math.ceil(length / BITS_PER_PAGE)
    const buffer = b4a.allocUnsafe(pages * BYTES_PER_PAGE)

    for (let i = 0; i < pages; i++) {
      const page = this._pages.get(i)
      const offset = i * BYTES_PER_PAGE

      if (page) {
        const buf = b4a.from(
          page.bitfield.buffer,
          page.bitfield.byteOffset,
          page.bitfield.byteLength
        )

        buffer.set(buf, offset)
      } else {
        buffer.fill(0, offset, offset + BYTES_PER_PAGE)
      }
    }

    return buffer
  }

  getBitfield(index) {
    const i = this.getPageIndex(index)

    const p = this._pages.get(i)
    return p || null
  }

  merge(bitfield, length) {
    let i = 0

    while (i < length) {
      const start = bitfield.firstSet(i)
      if (start === -1) break

      i = bitfield.firstUnset(start)

      if (i === -1 || i > length) i = length

      this.setRange(start, i, true)

      if (i >= length) break
    }
  }

  get(index) {
    const j = index & (BITS_PER_PAGE - 1)
    const i = (index - j) / BITS_PER_PAGE

    const p = this._pages.get(i)

    return p ? p.get(j) : false
  }

  getPageByteLength() {
    return BYTES_PER_PAGE
  }

  getPageIndex(index) {
    const j = index & (BITS_PER_PAGE - 1)
    return (index - j) / BITS_PER_PAGE
  }

  getPage(index, create) {
    const i = this.getPageIndex(index)

    let p = this._pages.get(i)

    if (p) return p

    if (!create) return null

    const k = Math.floor(i / PAGES_PER_SEGMENT)
    const s =
      this._segments.get(k) ||
      this._segments.set(
        k,
        new BitfieldSegment(
          k,
          new Uint32Array(k === 0 ? INITIAL_WORDS_PER_SEGMENT : WORDS_PER_SEGMENT)
        )
      )

    p = this._pages.set(i, new BitfieldPage(i, s))

    return p
  }

  set(index, val) {
    const j = index & (BITS_PER_PAGE - 1)
    const i = (index - j) / BITS_PER_PAGE

    let p = this._pages.get(i)

    if (!p && val) {
      const k = Math.floor(i / PAGES_PER_SEGMENT)
      const s =
        this._segments.get(k) ||
        this._segments.set(
          k,
          new BitfieldSegment(
            k,
            new Uint32Array(k === 0 ? INITIAL_WORDS_PER_SEGMENT : WORDS_PER_SEGMENT)
          )
        )

      p = this._pages.set(i, new BitfieldPage(i, s))
    }

    if (p) p.set(j, val)
  }

  setRange(start, end, val) {
    let j = start & (BITS_PER_PAGE - 1)
    let i = (start - j) / BITS_PER_PAGE

    while (start < end) {
      let p = this._pages.get(i)

      if (!p && val) {
        const k = Math.floor(i / PAGES_PER_SEGMENT)
        const s =
          this._segments.get(k) ||
          this._segments.set(
            k,
            new BitfieldSegment(
              k,
              new Uint32Array(k === 0 ? INITIAL_WORDS_PER_SEGMENT : WORDS_PER_SEGMENT)
            )
          )

        p = this._pages.set(i, new BitfieldPage(i, s))
      }

      const offset = i * BITS_PER_PAGE
      const last = Math.min(end - offset, BITS_PER_PAGE)
      const range = last - j

      if (p) p.setRange(j, last, val)

      j = 0
      i++
      start += range
    }
  }

  findFirst(val, position) {
    let j = position & (BITS_PER_SEGMENT - 1)
    let i = (position - j) / BITS_PER_SEGMENT

    while (i < this._segments.maxLength) {
      const s = this._segments.get(i)

      let index = -1

      if (s) index = s.findFirst(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_SEGMENT + index

      j = 0
      i++
    }

    return val ? -1 : this._segments.maxLength * BITS_PER_SEGMENT
  }

  firstSet(position) {
    return this.findFirst(true, position)
  }

  firstUnset(position) {
    return this.findFirst(false, position)
  }

  findLast(val, position) {
    let j = position & (BITS_PER_SEGMENT - 1)
    let i = (position - j) / BITS_PER_SEGMENT

    while (i >= 0) {
      const s = this._segments.get(i)

      let index = -1

      if (s) index = s.findLast(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_SEGMENT + index

      j = BITS_PER_SEGMENT - 1
      i--
    }

    return -1
  }

  lastSet(position) {
    return this.findLast(true, position)
  }

  lastUnset(position) {
    return this.findLast(false, position)
  }

  hasUnset(start, length) {
    const end = start + length

    let j = start & (BITS_PER_SEGMENT - 1)
    let i = (start - j) / BITS_PER_SEGMENT

    while (i < this._segments.maxLength) {
      const s = this._segments.get(i)
      const index = s ? s.findFirst(false, j) : j
      if (index !== -1) return i * BITS_PER_SEGMENT + index < end

      j = 0
      i++

      if (i * BITS_PER_SEGMENT >= end) return false
    }

    return true
  }

  hasSet(start, length) {
    const end = start + length

    let j = start & (BITS_PER_SEGMENT - 1)
    let i = (start - j) / BITS_PER_SEGMENT

    while (i < this._segments.maxLength) {
      const s = this._segments.get(i)

      let index = -1

      if (s) index = s.findFirst(true, j)

      if (index !== -1) return i * BITS_PER_SEGMENT + index < end

      j = 0
      i++

      if (i * BITS_PER_SEGMENT >= end) return false
    }

    return false
  }

  count(start, length, val) {
    let j = start & (BITS_PER_PAGE - 1)
    let i = (start - j) / BITS_PER_PAGE
    let c = 0

    while (length > 0) {
      const p = this._pages.get(i)

      const end = Math.min(j + length, BITS_PER_PAGE)
      const range = end - j

      if (p) c += p.count(j, range, val)
      else if (!val) c += range

      j = 0
      i++
      length -= range
    }

    return c
  }

  countSet(start, length) {
    return this.count(start, length, true)
  }

  countUnset(start, length) {
    return this.count(start, length, false)
  }

  *want(start, length) {
    if (start & 31) {
      const d = start & 31
      start -= d
      length += d
    }

    let j = start & (BITS_PER_SEGMENT - 1)
    let i = (start - j) / BITS_PER_SEGMENT

    while (length > 0) {
      const s = this._segments.get(i)

      if (s) {
        let end = Math.min(j + length, BITS_PER_SEGMENT)
        if (end & 31) end += 32 - (end & 31)

        yield {
          start: i * BITS_PER_SEGMENT + j,
          bitfield: s.bitfield.subarray(j / 32, end / 32)
        }
      }

      j = 0
      i++
      length -= BITS_PER_SEGMENT
    }
  }

  clear(tx) {
    return tx.deleteBitfieldPageRange(0, -1)
  }

  onupdate(ranges) {
    for (const { start, end, value } of ranges) {
      this.setRange(start, end, value)
    }
  }

  static async open(storage, length) {
    if (length === 0) return new Bitfield(storage, null)

    const pages = Math.ceil(length / BITS_PER_PAGE)
    const buffer = b4a.alloc(pages * BYTES_PER_PAGE)
    const stream = storage.createBitfieldStream({ lt: pages })

    for await (const { index, page } of stream) {
      buffer.set(page, index * BYTES_PER_PAGE)
    }

    return new Bitfield(buffer)
  }
}
const crypto = require('hypercore-crypto')
const sodium = require('sodium-universal')
const b4a = require('b4a')
const c = require('compact-encoding')

// TODO: rename this to "crypto" and move everything hashing related etc in here
// Also lets move the tree stuff from hypercore-crypto here

const [
  TREE,
  REPLICATE_INITIATOR,
  REPLICATE_RESPONDER,
  MANIFEST,
  DEFAULT_NAMESPACE,
  DEFAULT_ENCRYPTION
] = crypto.namespace('hypercore', 6)

exports.MANIFEST = MANIFEST
exports.DEFAULT_NAMESPACE = DEFAULT_NAMESPACE
exports.DEFAULT_ENCRYPTION = DEFAULT_ENCRYPTION

exports.replicate = function (isInitiator, key, handshakeHash) {
  const out = b4a.allocUnsafe(32)
  sodium.crypto_generichash_batch(
    out,
    [isInitiator ? REPLICATE_INITIATOR : REPLICATE_RESPONDER, key],
    handshakeHash
  )
  return out
}

exports.treeSignable = function (manifestHash, treeHash, length, fork) {
  const state = { start: 0, end: 112, buffer: b4a.allocUnsafe(112) }
  c.fixed32.encode(state, TREE)
  c.fixed32.encode(state, manifestHash)
  c.fixed32.encode(state, treeHash)
  c.uint64.encode(state, length)
  c.uint64.encode(state, fork)
  return state.buffer
}

exports.treeSignableCompat = function (hash, length, fork, noHeader) {
  const end = noHeader ? 48 : 80
  const state = { start: 0, end, buffer: b4a.allocUnsafe(end) }
  if (!noHeader) c.fixed32.encode(state, TREE) // ultra legacy mode, kill in future major
  c.fixed32.encode(state, hash)
  c.uint64.encode(state, length)
  c.uint64.encode(state, fork)
  return state.buffer
}
// Export the appropriate version of `quickbit-universal` as the plain import
// may resolve to an older version in some environments
let quickbit = require('quickbit-universal')
if (
  typeof quickbit.findFirst !== 'function' ||
  typeof quickbit.findLast !== 'function' ||
  typeof quickbit.clear !== 'function'
) {
  // This should always load the fallback from the locally installed version
  quickbit = require('quickbit-universal/fallback')
}
exports.quickbit = quickbit
const crypto = require('hypercore-crypto')
const flat = require('flat-tree')
const b4a = require('b4a')
const quickbit = require('quickbit-universal')
const Bitfield = require('./bitfield')

const MAX_BATCH_USED = 4 * 1024 * 1024
const MIN_BATCH_USED = 512 * 1024

// just in its own file as its a bit involved

module.exports = copyPrologue

async function copyPrologue(src, dst) {
  const prologue = dst.header.manifest.prologue

  if (src.length < prologue.length || prologue.length === 0) return

  const stack = []
  const roots = flat.fullRoots(prologue.length * 2)
  const batch = { roots, first: true, last: false, contig: 0, used: 0, tree: [], blocks: [] }

  for (let i = 0; i < roots.length; i++) {
    const node = roots[i]
    batch.tree.push(node)
    stack.push(node)
  }

  let lastPage = -1
  let lastBlock = -1

  for await (const data of src.storage.createBlockStream({
    gte: 0,
    lt: prologue.length,
    reverse: true
  })) {
    if (walkTree(stack, data.index * 2, batch) === false) {
      throw new Error('Missing block or tree node for ' + data.index)
    }

    batch.contig = data.index + 1 === lastBlock ? batch.contig + 1 : 1
    lastBlock = data.index

    const page = getBitfieldPage(data.index)
    batch.blocks.push(data)

    if (lastPage !== page) batch.used += 4096
    batch.used += Math.max(data.value.byteLength, 128) // 128 is just a sanity number to avoid mega batches

    // always safe to partially flush so we do that ondemand to reduce memory usage...
    if ((batch.used >= MIN_BATCH_USED && page !== lastPage) || batch.used >= MAX_BATCH_USED) {
      await flushBatch(prologue, src, dst, batch)
    }

    lastPage = page
  }

  if (lastBlock !== 0) batch.contig = 0

  batch.last = true
  await flushBatch(prologue, src, dst, batch)
}

async function flushBatch(prologue, src, dst, batch) {
  const nodePromises = []

  const srcReader = src.storage.read()
  for (const index of batch.tree) {
    nodePromises.push(srcReader.getTreeNode(index))
  }
  srcReader.tryFlush()

  const nodes = await Promise.all(nodePromises)

  const pagePromises = []
  const dstReader = dst.storage.read()

  const headPromise = batch.first ? dstReader.getHead() : null
  if (headPromise) headPromise.catch(noop)

  let lastPage = -1
  for (const { index } of batch.blocks) {
    const page = getBitfieldPage(index)
    if (page === lastPage) continue
    lastPage = page
    pagePromises.push(dstReader.getBitfieldPage(page))
  }

  dstReader.tryFlush()

  const pages = await Promise.all(pagePromises)
  const head = headPromise === null ? null : await headPromise
  const userData = []

  // reads done!

  if (batch.first) {
    const roots = nodes.slice(0, batch.roots.length)

    for (const node of roots) {
      if (!node) throw new Error('Missing nodes for prologue hash')
    }

    const treeHash = crypto.tree(roots)
    if (!b4a.equals(treeHash, prologue.hash)) throw new Error('Prologue does not match source')
  }

  if (batch.first) {
    for await (const data of src.storage.createUserDataStream()) userData.push(data)
  }

  for (let i = 0; i < pages.length; i++) {
    if (!pages[i]) pages[i] = b4a.alloc(4096)
  }

  const tx = dst.storage.write()

  for (const node of nodes) tx.putTreeNode(node)

  lastPage = -1
  let pageIndex = -1

  for (const { index, value } of batch.blocks) {
    const page = getBitfieldPage(index)

    if (page !== lastPage) {
      lastPage = page
      pageIndex++
      // queue the page now, we mutate it below but its the same ref
      tx.putBitfieldPage(pageIndex, pages[pageIndex])
    }

    const pageBuffer = pages[pageIndex]
    quickbit.set(pageBuffer, getBitfieldOffset(index), true)
    tx.putBlock(index, value)
  }

  for (const { key, value } of userData) {
    tx.putUserData(key, value)
  }

  let upgraded = batch.first && !head
  if (upgraded) {
    tx.setHead(prologueToTree(prologue))
  }

  await tx.flush()

  if (upgraded) {
    const roots = nodes.slice(0, batch.roots.length)
    dst.state.setRoots(roots)
    dst.header.tree = prologueToTree(prologue)
  }

  if (userData.length > 0) {
    dst.header.userData = userData.concat(dst.header.userData)
  }

  if (batch.contig) {
    // TODO: we need to persist this somehow
    dst.header.hints.contiguousLength = batch.contig
  }

  let start = 0
  let length = 0

  // update in memory bitfield
  for (const { index } of batch.blocks) {
    if (start === 0 || start - 1 === index) {
      length++
    } else {
      if (length > 0) signalReplicator(dst, upgraded, start, length)
      upgraded = false
      length = 1
    }

    start = index
    dst.bitfield.set(index, true)
  }

  if (length > 0) signalReplicator(dst, upgraded, start, length)

  // unlink
  batch.tree = []
  batch.blocks = []
  batch.first = false
  batch.used = 0
}

function signalReplicator(core, upgraded, start, length) {
  if (upgraded) {
    core.replicator.cork()
    core.replicator.onhave(start, length, false)
    core.replicator.onupgrade()
    core.replicator.uncork()
  } else {
    core.replicator.onhave(start, length, false)
  }
}

function prologueToTree(prologue) {
  return {
    fork: 0,
    length: prologue.length,
    rootHash: prologue.hash,
    signature: null
  }
}

function getBitfieldPage(index) {
  return Math.floor(index / Bitfield.BITS_PER_PAGE)
}

function getBitfieldOffset(index) {
  return index & (Bitfield.BITS_PER_PAGE - 1)
}

function walkTree(stack, target, batch) {
  while (stack.length > 0) {
    const node = stack.pop()

    if ((node & 1) === 0) {
      if (node === target) return true
      continue
    }

    const ite = flat.iterator(node)
    if (!ite.contains(target)) continue

    while ((ite.index & 1) !== 0) {
      const left = ite.leftChild()
      const right = ite.sibling() // is right child

      batch.tree.push(left, right)

      if (ite.contains(target)) stack.push(left)
      else ite.sibling()
    }

    if (ite.index === target) return true
  }

  return false
}

function noop() {}
const crypto = require('hypercore-crypto')
const b4a = require('b4a')
const unslab = require('unslab')
const z32 = require('z32')
const Mutex = require('./mutex')
const { MerkleTree, ReorgBatch } = require('./merkle-tree')
const BitInterlude = require('./bit-interlude')
const Bitfield = require('./bitfield')
const RemoteBitfield = require('./remote-bitfield')
const {
  BAD_ARGUMENT,
  STORAGE_EMPTY,
  STORAGE_CONFLICT,
  INVALID_SIGNATURE,
  INVALID_CHECKSUM
} = require('hypercore-errors')
const Verifier = require('./verifier')
const audit = require('./audit')
const copyPrologue = require('./copy-prologue')
const SessionState = require('./session-state')
const Replicator = require('./replicator')

module.exports = class Core {
  constructor(db, opts = {}) {
    this.db = db
    this.storage = null
    this.replicator = new Replicator(this, opts)
    this.sessionStates = []
    this.monitors = []
    this.activeSessions = 0
    this.gc = 0 // corestore uses this to main a gc strike pool

    this.id = opts.key ? z32.encode(opts.key) : null
    this.key = opts.key || null
    this.discoveryKey = opts.discoveryKey || (opts.key && crypto.discoveryKey(opts.key)) || null
    this.manifest = null
    this.opening = null
    this.closing = null
    this.exclusive = null

    this.preupdate = null
    this.header = null
    this.compat = false
    this.bitfield = null
    this.verifier = null
    this.truncating = 0
    this.skipBitfield = null
    this.globalCache = opts.globalCache || null
    this.autoClose = opts.autoClose !== false
    this.onidle = noop
    this.ongroupupdate = noop

    this.state = null
    this.opened = false
    this.destroyed = false
    this.closed = false

    this.hintsChanged = false
    this.remoteContiguousLengthChanged = false

    this._bitfield = null
    this._verifies = null
    this._verifiesFlushed = null
    this._legacy = !!opts.legacy
    this._repairMode = false

    this.opening = this._open(opts)
    this.opening.catch(noop)
  }

  static setRecoveryPeers(peers) {
    SessionState.RECOVERY_PEERS = peers
  }

  ready() {
    return this.opening
  }

  addMonitor(s) {
    if (s._monitorIndex >= 0) return
    s._monitorIndex = this.monitors.push(s) - 1
  }

  removeMonitor(s) {
    if (s._monitorIndex < 0) return
    const head = this.monitors.pop()
    if (head !== s) this.monitors[(head._monitorIndex = s._monitorIndex)] = head
    s._monitorIndex = -1
  }

  emitRemoteContiguousLength() {
    if (!this.remoteContiguousLengthChanged) return
    this.remoteContiguousLengthChanged = false

    const length = this.header.hints.remoteContiguousLength

    for (let i = this.monitors.length - 1; i >= 0; i--) {
      this.monitors[i].emit('remote-contiguous-length', length)
    }
  }

  emitManifest() {
    for (let i = this.monitors.length - 1; i >= 0; i--) {
      this.monitors[i].emit('manifest')
    }
  }

  createUserDataStream(opts, session = this.state) {
    return session.storage.createUserDataStream(opts)
  }

  allSessions() {
    const sessions = []
    for (const state of this.sessionStates) {
      if (state.sessions.length) sessions.push(...state.sessions)
    }
    return sessions
  }

  hasSession() {
    return this.activeSessions !== 0
  }

  compact() {
    const compacting = []
    for (const s of this.sessionStates) {
      compacting.push(s.storage.compact())
    }
    return Promise.all(compacting)
  }

  checkIfIdle() {
    if (!this.opened || this.destroyed === true || this.hasSession() === true) return
    if (this.replicator.idle() === false) return
    if (this.state === null || this.state.mutex.idle() === false) return
    this.onidle()
  }

  async lockExclusive() {
    if (this.exclusive === null) this.exclusive = new Mutex()
    await this.exclusive.lock()
  }

  unlockExclusive() {
    if (this.exclusive !== null) this.exclusive.unlock()
  }

  async _open(opts) {
    try {
      await this._tryOpen(opts)
    } catch (err) {
      this.onidle()
      throw err
    }

    this.opened = true
  }

  async _tryOpen(opts) {
    if (opts.preopen) await opts.preopen // just a hook to allow exclusive access here...

    let storage = await this.db.resumeCore(this.discoveryKey)

    let overwrite = opts.overwrite === true

    const force = opts.force === true
    const createIfMissing = opts.createIfMissing !== false
    // kill this flag soon
    const legacy = !!opts.legacy

    // default to true for now if no manifest is provided
    let compat = opts.compat === true || (opts.compat !== false && !opts.manifest)

    let header = storage ? parseHeader(await getCoreInfo(storage)) : null

    const hadManifest = !!header && !!header.manifest && !!header.key
    const hadKeyPair = !!header && !!header.keyPair

    if (force && opts.key && header && !b4a.equals(header.key, opts.key)) {
      overwrite = true
    }

    if (!header && opts.discoveryKey && !(opts.key || opts.manifest)) {
      throw STORAGE_EMPTY('No Hypercore is stored here', this.discoveryKey)
    }

    if (!header || overwrite) {
      if (!createIfMissing) {
        throw STORAGE_EMPTY('No Hypercore is stored here', this.discoveryKey)
      }

      if (compat) {
        if (opts.key && opts.keyPair && !b4a.equals(opts.key, opts.keyPair.publicKey)) {
          throw BAD_ARGUMENT('Key must match publicKey when in compat mode', this.discoveryKey)
        }
      }

      const keyPair = opts.keyPair || (opts.key ? null : crypto.keyPair())

      const defaultManifest =
        !opts.manifest &&
        (!!opts.compat || !opts.key || !!(keyPair && b4a.equals(opts.key, keyPair.publicKey)))
      const manifest = defaultManifest
        ? Verifier.defaultSignerManifest(opts.key || keyPair.publicKey)
        : Verifier.createManifest(opts.manifest)

      header = {
        key: opts.key || (compat ? manifest.signers[0].publicKey : Verifier.manifestHash(manifest)),
        manifest,
        keyPair: keyPair
          ? { publicKey: keyPair.publicKey, secretKey: keyPair.secretKey || null }
          : null,
        frozen: false,
        tree: {
          fork: 0,
          length: 0,
          rootHash: null,
          signature: null,
          timestamp: 0
        },
        group: null,
        hints: {
          reorgs: [],
          contiguousLength: 0,
          remoteContiguousLength: 0,
          recovering: 0
        }
      }

      const discoveryKey = opts.discoveryKey || crypto.discoveryKey(header.key)

      storage = await this.db.createCore({
        key: header.key,
        manifest,
        keyPair,
        frozen: false,
        discoveryKey,
        userData: opts.userData || [],
        alias: opts.alias || null
      })
    }

    // unslab the long lived buffers to avoid keeping the slab alive
    header.key = unslab(header.key)

    if (header.tree) {
      header.tree.rootHash = unslab(header.tree.rootHash)
      header.tree.signature = unslab(header.tree.signature)
    }

    if (header.keyPair) {
      header.keyPair.publicKey = unslab(header.keyPair.publicKey)
      header.keyPair.secretKey = unslab(header.keyPair.secretKey)
    }

    if (header.keyPair) {
      header.keyPair.publicKey = unslab(header.keyPair.publicKey)
      header.keyPair.secretKey = unslab(header.keyPair.secretKey)
    }

    if (opts.manifest) {
      // if we provide a manifest and no key, verify that the stored key is the same
      if (
        !opts.key &&
        !Verifier.isValidManifest(header.key, Verifier.createManifest(opts.manifest))
      ) {
        throw STORAGE_CONFLICT('Manifest does not hash to provided key', this.discoveryKey)
      }

      if (!header.manifest) header.manifest = opts.manifest
    }

    if (opts.key && !b4a.equals(header.key, opts.key)) {
      throw STORAGE_CONFLICT('Another Hypercore is stored here', this.discoveryKey)
    }

    // if we signalled compat, but already now this core isn't disable it
    if (compat && header.manifest && !Verifier.isCompat(header.key, header.manifest)) {
      compat = false
    } else if (!compat && header.manifest && Verifier.isCompat(header.key, header.manifest)) {
      compat = true
    }

    const prologue = header.manifest ? header.manifest.prologue : null

    const bitfield = await Bitfield.open(storage, header.tree.length)

    const treeInfo = {
      fork: header.tree.fork,
      length: header.tree.length,
      signature: header.tree.signature,
      roots: await maybeGetRootsFromStorage(storage, header.tree.length),
      prologue
    }

    this._repairMode = !treeInfo.roots.length && treeInfo.length && !overwrite
    // Set push only mode if in repair mode
    if (this._repairMode) {
      this.replicator.setPushOnly(true)
    }

    if (opts.group) {
      if (!header.group) header.group = await this.db.createGroup(opts.group)
      else if (!b4a.equals(header.group.key, opts.group)) {
        throw STORAGE_CONFLICT(
          'Core is already register to group: ' + b4a.toString(header.group.key, 'hex')
        )
      }

      const tx = storage.write()
      tx.setGroup(header.group)
      await tx.flush()
    }

    if (overwrite) {
      const tx = storage.write()
      tx.deleteTreeNodeRange(0, -1)
      tx.deleteBlockRange(0, -1)
      bitfield.clear(tx)
      await tx.flush()
    }

    const len = bitfield.findFirst(false, header.hints.contiguousLength)
    if (header.hints.contiguousLength !== len && !storage.readOnly) {
      header.hints.contiguousLength = len
      const tx = storage.write()
      tx.setHints(header.hints)
      await tx.flush()
    }

    // to unslab
    if (header.manifest) {
      header.manifest = Verifier.createManifest(header.manifest)
      if (!hadManifest || (header.keyPair && !hadKeyPair)) {
        const tx = storage.write()
        tx.setAuth({
          key: header.key,
          discoveryKey: crypto.discoveryKey(header.key),
          manifest: header.manifest,
          keyPair: header.keyPair
        })
        await tx.flush()
      }
    }

    const verifier = header.manifest
      ? new Verifier(header.key, header.manifest, { crypto, legacy })
      : null

    this.storage = storage
    this.header = header
    this.compat = compat
    this.bitfield = bitfield
    this.verifier = verifier
    this.state = new SessionState(this, null, storage, treeInfo, null)

    if (this.key === null) this.key = this.header.key
    if (this.discoveryKey === null) this.discoveryKey = crypto.discoveryKey(this.key)
    if (this.id === null) this.id = z32.encode(this.key)
    if (this.manifest === null) this.manifest = this.header.manifest
  }

  async audit(opts) {
    await this.state.mutex.lock()

    try {
      return await audit(this, opts)
    } finally {
      this.state._unlock()
    }
  }

  async setGroup(group) {
    await this.state.mutex.lock()
    try {
      if (!this.header.group) this.header.group = await this.db.createGroup(group)
      else if (!b4a.equals(this.header.group.key, group)) {
        throw STORAGE_CONFLICT(
          'Core is already register to group: ' + b4a.toString(this.header.group.key, 'hex')
        )
      }

      const tx = this.storage.write()
      tx.setGroup(this.header.group)
      await tx.flush()
    } finally {
      this.state.mutex.unlock()
    }
  }

  async setManifest(manifest) {
    await this.state.mutex.lock()

    try {
      if (manifest && this.header.manifest === null) {
        if (!Verifier.isValidManifest(this.header.key, manifest)) {
          throw INVALID_CHECKSUM('Manifest hash does not match', this.discoveryKey)
        }

        const tx = this.state.createWriteBatch()
        this._setManifest(tx, Verifier.createManifest(manifest), null)
        await this.state.flush()
      }
    } finally {
      this.state._unlock()
    }
  }

  _setManifest(tx, manifest, keyPair) {
    if (!manifest && b4a.equals(keyPair.publicKey, this.header.key)) {
      manifest = Verifier.defaultSignerManifest(this.header.key)
    }
    if (!manifest) return

    const verifier = new Verifier(this.header.key, manifest, { legacy: this._legacy })

    if (verifier.prologue) this.state.prologue = Object.assign({}, verifier.prologue)

    this.manifest = this.header.manifest = manifest

    tx.setAuth({
      key: this.header.key,
      discoveryKey: this.discoveryKey,
      manifest,
      keyPair: this.header.keyPair
      // TODO: encryptionKey?
    })

    this.compat = verifier.compat
    this.verifier = verifier

    this.replicator.onupgrade()
    this.emitManifest()
  }

  async copyPrologue(src) {
    await this.state.mutex.lock()

    try {
      await src.mutex.lock()
    } catch (err) {
      this.state.mutex.unlock()
      throw err
    }

    try {
      await copyPrologue(src, this)
    } finally {
      src.mutex.unlock()
      this.state.mutex.unlock()
      this.checkIfIdle()
    }
  }

  flushed() {
    return this.state.flushed()
  }

  async _validateCommit(state, treeLength) {
    if (this.state.length > state.length) {
      return false // TODO: partial commit and truncation possible in the future
    }

    if (this.state.length > treeLength) {
      for (const root of this.state.roots) {
        const batchRoot = await MerkleTree.get(state, root.index)
        if (batchRoot.size !== root.size || !b4a.equals(batchRoot.hash, root.hash)) {
          return false
        }
      }
    }

    if (this.verifier === null) {
      return false // easier to assert than upsert
    }

    return true
  }

  _verifyBatchUpgrade(batch, manifest) {
    if (!this.header.manifest) {
      // compat, drop at some point
      if (!manifest) manifest = Verifier.defaultSignerManifest(this.header.key)

      if (
        !manifest ||
        !(
          Verifier.isValidManifest(this.header.key, manifest) ||
          Verifier.isCompat(this.header.key, manifest)
        )
      ) {
        throw INVALID_SIGNATURE('Proof contains an invalid manifest', this.discoveryKey) // TODO: proper error type
      }
    }

    const verifier =
      this.verifier ||
      new Verifier(this.header.key, Verifier.createManifest(manifest), { legacy: this._legacy })

    if (!verifier.verify(batch, batch.signature)) {
      throw INVALID_SIGNATURE('Proof contains an invalid signature', this.discoveryKey)
    }

    return manifest
  }

  async _verifyExclusive({ batch, bitfield, value, manifest }) {
    manifest = this._verifyBatchUpgrade(batch, manifest)

    if (
      !(await this.state._verifyBlock(
        batch,
        bitfield,
        value,
        this.header.manifest ? null : manifest
      ))
    ) {
      return false
    }

    if (!batch.upgraded && bitfield) {
      this.replicator.onhave(bitfield.start, bitfield.length, bitfield.drop)
    }

    return true
  }

  async _verifyShared() {
    if (!this._verifies.length) return false

    await this.state.mutex.lock()

    const tx = this.state.createWriteBatch()

    const verifies = this._verifies
    this._verifies = null
    this._verified = null

    try {
      for (const { batch, bitfield, value } of verifies) {
        if (!batch.commitable()) continue

        if (bitfield) {
          tx.putBlock(bitfield.start, value)
        }
      }

      const bits = new BitInterlude()

      for (let i = 0; i < verifies.length; i++) {
        const { batch, bitfield, manifest } = verifies[i]

        if (!batch.commitable()) {
          verifies[i] = null // signal that we cannot commit this one
          continue
        }

        if (bitfield) {
          bits.setRange(bitfield.start, bitfield.start + 1, true)
        }

        // if we got a manifest AND its strictly a non compat one, lets store it
        if (manifest && this.header.manifest === null) {
          if (!Verifier.isValidManifest(this.header.key, manifest)) {
            throw INVALID_CHECKSUM('Manifest hash does not match', this.discoveryKey)
          }
          this._setManifest(tx, manifest, null)
        }

        if (batch.commitable()) batch.commit(tx)
      }

      const ranges = bits.flush(tx, this.bitfield)

      await this.state.flush()

      for (const { start, end, value } of ranges) {
        this._setBitfieldRanges(start, end, value)
      }

      for (let i = 0; i < verifies.length; i++) {
        const bitfield = verifies[i] && verifies[i].bitfield
        if (bitfield) {
          this.updateContiguousLength(bitfield)
          this.replicator.onhave(bitfield.start, bitfield.length, bitfield.drop)
        }
      }

      if (this.hintsChanged) await this.flushHints()
    } finally {
      this.state._clearActiveBatch()
      this.state.mutex.unlock()
    }

    return verifies[0] !== null
  }

  async flushHints() {
    if (!this.hintsChanged) return
    this.hintsChanged = false // we unset this immediately as a "debounce"

    const tx = this.state.storage.write()

    tx.setHints({
      contiguousLength: this.header.hints.contiguousLength,
      remoteContiguousLength: this.header.hints.remoteContiguousLength,
      recovering: this.header.hints.recovering
    })

    await tx.flush()
  }

  async checkConflict(proof, from) {
    if (this.state.length < proof.upgrade.length || proof.fork !== this.state.fork) {
      // out of date this proof - ignore for now
      return false
    }

    // sanity check -> no manifest, no way to verify
    if (!this.header.manifest) {
      return false
    }

    const batch = MerkleTree.verifyFullyRemote(this.state, proof)

    try {
      this._verifyBatchUpgrade(batch, proof.manifest)
    } catch {
      return true
    }

    const roots = await maybeGetRootsFromStorage(this.storage, proof.upgrade.length)
    const remoteTreeHash = crypto.tree(proof.upgrade.nodes)
    const localTreeHash = crypto.tree(roots)

    try {
      const rx = this.state.storage.read()
      const treeProofPromise = MerkleTree.proof(this.state, rx, {
        block: null,
        hash: null,
        seek: null,
        upgrade: {
          start: 0,
          length: proof.upgrade.length
        }
      })

      rx.tryFlush()

      const treeProof = await treeProofPromise

      const verifyBatch = MerkleTree.verifyFullyRemote(this.state, await treeProof.settle())
      this._verifyBatchUpgrade(verifyBatch, this.header.manifest)
    } catch (err) {
      if (err.code !== 'INVALID_OPERATION') return true

      return !(await this._repairTreeNodes(proof))
    }

    // both proofs are valid, now check if they forked
    if (b4a.equals(localTreeHash, remoteTreeHash)) return false

    await this.state.mutex.lock()

    try {
      const tx = this.state.createWriteBatch()

      this.header.frozen = true

      tx.setAuth({
        key: this.header.key,
        discoveryKey: this.discoveryKey,
        manifest: this.header.manifest,
        keyPair: this.header.keyPair,
        frozen: true
      })

      await this.state.flush()
    } finally {
      this.state.mutex.unlock()
    }

    // tmp log so we can see these
    const id = b4a.toString(this.discoveryKey, 'hex')
    console.log(
      '[hypercore] conflict detected in ' +
        id +
        ' (writable=' +
        !!this.header.keyPair +
        ',quorum=' +
        this.header.manifest.quorum +
        ')'
    )
    await this._onconflict(proof)
    return true
  }

  async _repairTreeNodes(proof) {
    if (!this._repairMode) return false

    await this.state.mutex.lock()

    for (let i = this.monitors.length - 1; i >= 0; i--) {
      this.monitors[i].emit('repairing', proof)
    }

    try {
      const batch = MerkleTree.verifyFullyRemote(this.state, proof)
      this._verifyBatchUpgrade(batch, proof.manifest)
    } catch {
      this.state.mutex.unlock()
      for (let i = this.monitors.length - 1; i >= 0; i--) {
        this.monitors[i].emit('repair-failed')
      }
      return false
    }

    // Attempt to repair local merkle tree with remote roots
    const atom = this.storage.createAtom()
    const atomized = this.storage.atomize(atom)
    const tx = atomized.write()
    for (const node of proof.upgrade.nodes) {
      tx.putTreeNode(node)
    }
    await tx.flush()

    // Try local proof again
    try {
      const rx = atomized.read()
      const treeProofPromise = MerkleTree.proof(this.state, rx, {
        block: null,
        hash: null,
        seek: null,
        upgrade: {
          start: 0,
          length: proof.upgrade.length
        }
      })

      rx.tryFlush()

      const treeProof = await treeProofPromise

      const verifyBatch = MerkleTree.verifyFullyRemote(this.state, await treeProof.settle())
      this._verifyBatchUpgrade(verifyBatch, this.header.manifest)
    } catch (err) {
      this.state.mutex.unlock()
      for (let i = this.monitors.length - 1; i >= 0; i--) {
        this.monitors[i].emit('repair-failed')
      }
      return false
    }

    await atom.flush()

    for (let i = this.monitors.length - 1; i >= 0; i--) {
      this.monitors[i].emit('repaired', proof)
    }
    this.replicator.setPushOnly(false)
    this.state.mutex.unlock()
    return true
  }

  async verifyReorg(proof) {
    const batch = new ReorgBatch(this.state)
    await MerkleTree.reorg(this.state, proof, batch)
    const manifest = this._verifyBatchUpgrade(batch, proof.manifest)

    if (manifest && !this.header.manifest) {
      await this.state.mutex.lock()
      try {
        if (manifest && this.header.manifest === null) {
          const tx = this.state.createWriteBatch()
          this._setManifest(tx, Verifier.createManifest(manifest), null)
          await this.state.flush()
        }
      } finally {
        this.state._unlock()
      }
    }

    return batch
  }

  async verify(proof, from) {
    // We cannot apply "other forks" atm.
    // We should probably still try and they are likely super similar for non upgrades
    // but this is easy atm (and the above layer will just retry)
    if (proof.fork !== this.state.fork) return false

    const batch = await MerkleTree.verify(this.state, proof)

    if (batch.upgraded && batch.length <= this.state.length) {
      await batch.downgrade()
    }

    if (!batch.commitable()) {
      return false
    }

    const value = (proof.block && proof.block.value) || null
    const op = {
      batch,
      bitfield: value && { drop: false, start: proof.block.index, length: 1 },
      value,
      manifest: proof.manifest,
      from
    }

    if (batch.upgraded) {
      return this._verifyExclusive(op)
    }

    if (this._verifies !== null) {
      const verifies = this._verifies
      const i = verifies.push(op)
      await this._verified
      return verifies[i] !== null
    }

    this._verifies = [op]
    this._verified = this._verifyShared()

    return this._verified
  }

  async reorg(batch) {
    if (!batch.commitable()) return false

    this.truncating++

    try {
      await this.state.reorg(batch)
    } finally {
      this.truncating--
    }

    return true
  }

  openSkipBitfield() {
    if (this.skipBitfield !== null) return this.skipBitfield
    this.skipBitfield = new RemoteBitfield()
    const buf = this.bitfield.toBuffer(this.state.length)
    const bitfield = new Uint32Array(buf.buffer, buf.byteOffset, buf.byteLength / 4)
    this.skipBitfield.insert(0, bitfield)
    return this.skipBitfield
  }

  _setBitfieldRanges(start, end, value) {
    this.bitfield.setRange(start, end, value)
    if (this.skipBitfield !== null) this.skipBitfield.setRange(start, end, value)
  }

  close() {
    if (!this.closing) this.closing = this._close()
    return this.closing
  }

  updateContiguousLength(bitfield) {
    const contig = updateContigBatch(this.header.hints.contiguousLength, bitfield, this.bitfield)

    if (contig.length !== -1 && contig.length !== this.header.hints.contiguousLength) {
      this.header.hints.contiguousLength = contig.length
      this.hintsChanged = true
    }
  }

  updateRemoteContiguousLength(length) {
    this.header.hints.remoteContiguousLength = length
    this.hintsChanged = true
    this.remoteContiguousLengthChanged = true
  }

  onappend(tree, bitfield) {
    this.header.tree = tree

    if (!bitfield) {
      this.replicator.onupgrade()
      return
    }

    this.replicator.cork()

    const { start, length, drop } = bitfield

    this._setBitfieldRanges(start, start + length, true)
    this.updateContiguousLength({ start, length, drop: false })

    this.replicator.onupgrade()
    this.replicator.onhave(start, length, drop)
    this.replicator.uncork()
  }

  ontruncate(tree, { start, length }) {
    if (tree) this.header.tree = tree

    this.replicator.cork()

    this.replicator.ontruncate(start, length)
    this.replicator.onhave(start, length, true)
    this.replicator.onupgrade()
    this.replicator.uncork()

    for (const sessionState of this.sessionStates) {
      if (start < sessionState.snapshotCompatLength) sessionState.snapshotCompatLength = start
    }

    this._setBitfieldRanges(start, start + length, false)
    this.updateContiguousLength({ start, length, drop: true })
  }

  async _onconflict(proof) {
    await this.replicator.onconflict()

    for (let i = this.monitors.length - 1; i >= 0; i--) {
      const s = this.monitors[i]
      s.emit('conflict', proof.upgrade.length, proof.fork, proof)
    }

    const err = new Error('Two conflicting signatures exist for length ' + proof.upgrade.length)
    await this.closeAllSessions(err)
  }

  async closeAllSessions(err) {
    // this.sessions modifies itself when a session closes
    // This way we ensure we indeed iterate over all sessions
    const sessions = this.allSessions()

    const all = []
    for (const s of sessions) all.push(s.close({ error: err, force: false })) // force false or else infinite recursion
    await Promise.allSettled(all)
  }

  async destroy() {
    if (this.destroyed === true) return
    this.destroyed = true

    if (this.hasSession() === true) throw new Error('Cannot destroy while sessions are open')

    const weakSessions = this.allSessions()

    if (this.replicator) this.replicator.destroy()
    if (this.state) await this.state.close()

    // close all pending weak sessions...
    for (const s of weakSessions) s.close().catch(noop)
  }

  async _close() {
    if (this.opened === false) await this.opening
    if (this.hasSession() === true) throw new Error('Cannot close while sessions are open')

    if (this.replicator) await this.replicator.close()

    await this.destroy()
    if (this.autoClose) await this.storage.store.close()

    this.closed = true
  }
}

function updateContigBatch(start, upd, bitfield) {
  const end = upd.start + upd.length

  let c = start

  if (upd.drop) {
    // If we dropped a block in the current contig range, "downgrade" it
    if (c > upd.start) {
      c = upd.start
    }
  } else {
    if (c <= end && c >= upd.start) {
      c = end
      while (bitfield.get(c)) c++
    }
  }

  if (c === start) {
    return {
      length: -1
    }
  }

  if (c > start) {
    return {
      length: c
    }
  }

  return {
    length: c
  }
}

function getDefaultTree() {
  return {
    fork: 0,
    length: 0,
    rootHash: null,
    signature: null,
    timestamp: 0
  }
}

function parseHeader(info) {
  if (!info) return null

  return {
    key: info.key,
    manifest: info.manifest,
    external: null,
    keyPair: info.keyPair,
    tree: info.head || getDefaultTree(),
    group: info.group,
    hints: {
      reorgs: [],
      contiguousLength: info.hints ? info.hints.contiguousLength : 0,
      remoteContiguousLength: info.hints ? info.hints.remoteContiguousLength : 0,
      recovering: info.hints ? info.hints.recovering : 0
    }
  }
}

async function maybeGetRootsFromStorage(storage, length) {
  try {
    return length ? await MerkleTree.getRootsFromStorage(storage, length) : []
  } catch (err) {
    if (err.code !== 'INVALID_OPERATION') throw err
    // If INVALID_OPERATION, a root is likely missing so load empty roots to try to recover
    return []
  }
}

function noop() {}

async function getCoreInfo(storage) {
  const r = storage.read()

  const auth = r.getAuth()
  const head = r.getHead()
  const hints = r.getHints()
  const group = r.getGroup()

  r.tryFlush()

  const [authInfo, headInfo, hintsInfo, groupInfo] = await Promise.all([auth, head, hints, group])
  return {
    ...authInfo,
    head: headInfo,
    hints: hintsInfo,
    group: groupInfo
  }
}
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const b4a = require('b4a')
const { DEFAULT_ENCRYPTION } = require('./caps')

const nonce = b4a.alloc(sodium.crypto_stream_NONCEBYTES)

module.exports = class DefaultEncryption {
  static PADDING = 8

  constructor(encryptionKey, hypercoreKey, opts = {}) {
    this.key = encryptionKey
    this.compat = opts.compat === true

    const keys = DefaultEncryption.deriveKeys(encryptionKey, hypercoreKey, opts)

    this.blockKey = keys.block
    this.blindingKey = keys.blinding
  }

  static deriveKeys(encryptionKey, hypercoreKey, { block = false, compat = false } = {}) {
    const subKeys = b4a.alloc(2 * sodium.crypto_stream_KEYBYTES)

    const blockKey = block ? encryptionKey : subKeys.subarray(0, sodium.crypto_stream_KEYBYTES)
    const blindingKey = subKeys.subarray(sodium.crypto_stream_KEYBYTES)

    if (!block) {
      if (compat) {
        sodium.crypto_generichash_batch(blockKey, [encryptionKey], hypercoreKey)
      } else {
        sodium.crypto_generichash_batch(blockKey, [DEFAULT_ENCRYPTION, hypercoreKey, encryptionKey])
      }
    }

    sodium.crypto_generichash(blindingKey, blockKey)

    return {
      blinding: blindingKey,
      block: blockKey
    }
  }

  static blockEncryptionKey(hypercoreKey, encryptionKey) {
    const blockKey = b4a.alloc(sodium.crypto_stream_KEYBYTES)
    sodium.crypto_generichash_batch(blockKey, [DEFAULT_ENCRYPTION, hypercoreKey, encryptionKey])
    return blockKey
  }

  static encrypt(index, block, fork, blockKey, blindingKey) {
    const padding = block.subarray(0, DefaultEncryption.PADDING)
    block = block.subarray(DefaultEncryption.PADDING)

    c.uint64.encode({ start: 0, end: 8, buffer: padding }, fork)
    c.uint64.encode({ start: 0, end: 8, buffer: nonce }, index)

    // Zero out any previous padding.
    nonce.fill(0, 8, 8 + padding.byteLength)

    // Blind the fork ID, possibly risking reusing the nonce on a reorg of the
    // Hypercore. This is fine as the blinding is best-effort and the latest
    // fork ID shared on replication anyway.
    sodium.crypto_stream_xor(padding, padding, nonce, blindingKey)

    nonce.set(padding, 8)

    // The combination of a (blinded) fork ID and a block index is unique for a
    // given Hypercore and is therefore a valid nonce for encrypting the block.
    sodium.crypto_stream_xor(block, block, nonce, blockKey)
  }

  static decrypt(index, block, blockKey) {
    const padding = block.subarray(0, DefaultEncryption.PADDING)
    block = block.subarray(DefaultEncryption.PADDING)

    c.uint64.encode({ start: 0, end: 8, buffer: nonce }, index)

    nonce.set(padding, 8)

    // Decrypt the block using the blinded fork ID.
    sodium.crypto_stream_xor(block, block, nonce, blockKey)
  }

  encrypt(index, block, fork, core) {
    if (core.compat !== this.compat) this._reload(core)
    return DefaultEncryption.encrypt(index, block, fork, this.blockKey, this.blindingKey)
  }

  decrypt(index, block, core) {
    if (core.compat !== this.compat) this._reload(core)
    return DefaultEncryption.decrypt(index, block, this.blockKey)
  }

  padding() {
    return DefaultEncryption.PADDING
  }

  _reload(core) {
    const block = b4a.equals(this.key, this.blockKey)
    const keys = DefaultEncryption.deriveKeys(this.key, core.key, { block, compat: core.compat })

    this.blockKey = keys.blockKey
    this.blindingKey = keys.blindingKey
  }
}
module.exports = class Download {
  constructor(session, range) {
    this.session = session
    this.range = range
    this.request = null
    this.opened = false
    this.opening = this._open()
    this.opening.catch(noop)
  }

  ready() {
    return this.opening
  }

  async _open() {
    if (this.session.opened === false) await this.session.opening
    this._download()
    this.opened = true
  }

  async done() {
    await this.ready()

    try {
      return await this.request.promise
    } catch (err) {
      if (isSessionMoved(err)) return this._download()
      throw err
    }
  }

  _download() {
    const activeRequests = (this.range && this.range.activeRequests) || this.session.activeRequests
    this.request = this.session.core.replicator.addRange(activeRequests, this.range)
    this.request.promise.catch(noop)
    return this.request.promise
  }

  /**
   * Deprecated. Use `range.done()`.
   */
  downloaded() {
    return this.done()
  }

  destroy() {
    this._destroyBackground().catch(noop)
  }

  async _destroyBackground() {
    if (this.opened === false) await this.ready()
    if (this.request.context) this.request.context.detach(this.request)
  }
}

function noop() {}

function isSessionMoved(err) {
  return err.code === 'SESSION_MOVED'
}
module.exports = {
  SMALL_WANTS: 1
}
// this helper is for fully remote proofs, is like in a push notification where no other context exists

const { MerkleTree } = require('./merkle-tree.js')
const messages = require('./messages.js')
const b4a = require('b4a')
const c = require('compact-encoding')
const crypto = require('hypercore-crypto')
const flat = require('flat-tree')

class SlimSession {
  constructor(storage, auth, head, roots) {
    this.fork = head ? head.fork : 0
    this.roots = roots
    this.length = head ? head.length : 0
    this.signature = head ? head.signature : null
    this.ancestors = this.length
    this.byteLength = 0
    this.prologue = auth.manifest.prologue
    this.storage = storage

    for (let i = 0; i < roots.length; i++) this.byteLength += roots[i].size
  }
}

module.exports = { verify, proof }

async function verify(storage, buffer, { referrer = null } = {}) {
  const state = { buffer, start: 0, end: buffer.byteLength }

  const discoveryKey = c.fixed32.decode(state)
  const proof = messages.wire.data.decode(state)

  const result = {
    key: null,
    discoveryKey,
    newer: true,
    length: 0,
    proof,
    block: null
  }

  const core = await storage.resumeCore(discoveryKey)
  if (core === null) return null

  let rx = core.read()
  const authPromise = rx.getAuth()
  const headPromise = rx.getHead()
  const referrerPromise = rx.getUserData('referrer')

  rx.tryFlush()

  const [auth, head, ref] = await Promise.all([authPromise, headPromise, referrerPromise])

  if (auth === null) return null

  if (referrer && (!ref || !b4a.equals(ref, referrer))) return null

  rx = core.read()

  const rootPromises = []

  for (const index of flat.fullRoots(head ? 2 * head.length : 0)) {
    rootPromises.push(rx.getTreeNode(index))
  }

  rx.tryFlush()

  let roots = await Promise.all(rootPromises)
  if (roots.some(isNull)) roots = []

  const length = head ? head.length : 0

  if (!auth.manifest || !auth.manifest.signers.length) return null

  const batch = await MerkleTree.verifyFullyRemote(new SlimSession(core, auth, head, roots), proof)
  const publicKey = auth.manifest.signers[0].publicKey

  let signable = null
  let signature = null

  if (auth.manifest.version === 0) {
    signable = batch.signable(auth.manifest.signers[0].namespace)
    signature = batch.signature
  } else {
    if (batch.signature[0] !== 1) return null
    if (batch.signature[1] !== 0) return null

    signable = batch.signable(auth.key)
    signature = batch.signature.subarray(2, 66)
  }

  if (!crypto.verify(signable, signature, publicKey)) {
    return null
  }

  result.key = auth.key
  result.discoveryKey = discoveryKey
  result.newer = batch.length > length
  result.length = batch.length
  result.block = proof.block

  return result
}

async function proof(sender, { index, block = null, upgrade = null } = {}) {
  const proof = await sender.proof({
    block: block ? { index, nodes: 0 } : null,
    upgrade: upgrade ? upgrade : { start: 0, length: sender.length }
  })

  if (block) proof.block.value = block
  proof.manifest = sender.core.header.manifest

  const state = { buffer: null, start: 0, end: 0 }
  const data = { request: 0, ...proof }

  c.fixed32.preencode(state, sender.discoveryKey)
  messages.wire.data.preencode(state, data)

  state.buffer = b4a.allocUnsafe(state.end)

  c.fixed32.encode(state, sender.discoveryKey)
  messages.wire.data.encode(state, data)

  return state.buffer
}

function isNull(x) {
  return x === null
}
const TICKS = 16

module.exports = class HotswapQueue {
  constructor() {
    this.priorities = [[], [], []]
  }

  *pick(peer) {
    for (let i = 0; i < this.priorities.length; i++) {
      // try first one more than second one etc etc
      let ticks = (this.priorities.length - i) * TICKS
      const queue = this.priorities[i]

      for (let j = 0; j < queue.length; j++) {
        const r = j + Math.floor(Math.random() * queue.length - j)
        const a = queue[j]
        const b = queue[r]

        if (r !== j) {
          queue[(b.hotswap.index = j)] = b
          queue[(a.hotswap.index = r)] = a
        }

        if (hasInflight(b, peer)) continue

        yield b

        if (--ticks <= 0) break
      }
    }
  }

  add(block) {
    if (block.hotswap !== null) this.remove(block)
    if (block.inflight.length === 0 || block.inflight.length >= 3) return

    // TODO: also use other stuff to determine queue prio
    const queue = this.priorities[block.inflight.length - 1]

    const index = queue.push(block) - 1
    block.hotswap = { ref: this, queue, index }
  }

  remove(block) {
    const hotswap = block.hotswap
    if (hotswap === null) return

    block.hotswap = null
    const head = hotswap.queue.pop()
    if (head === block) return
    hotswap.queue[(head.hotswap.index = hotswap.index)] = head
  }
}

function hasInflight(block, peer) {
  for (let j = 0; j < block.inflight.length; j++) {
    if (block.inflight[j].peer === peer) return true
  }
  return false
}
module.exports = class Info {
  constructor(opts = {}) {
    this.key = opts.key
    this.discoveryKey = opts.discoveryKey
    this.length = opts.length || 0
    this.contiguousLength = opts.contiguousLength || 0
    this.byteLength = opts.byteLength || 0
    this.fork = opts.fork || 0
    this.padding = opts.padding || 0
    this.storage = opts.storage || null
  }

  static async from(session, opts = {}) {
    return new Info({
      key: session.key,
      discoveryKey: session.discoveryKey,
      length: session.length,
      contiguousLength: session.contiguousLength,
      byteLength: session.byteLength,
      fork: session.fork,
      padding: session.padding,
      storage: opts.storage ? await this.storage(session) : null
    })
  }

  static async storage(session) {
    const { oplog, tree, blocks, bitfield } = session.core
    try {
      return {
        oplog: await Info.bytesUsed(oplog.storage),
        tree: await Info.bytesUsed(tree.storage),
        blocks: await Info.bytesUsed(blocks.storage),
        bitfield: await Info.bytesUsed(bitfield.storage)
      }
    } catch {
      return null
    }
  }

  static bytesUsed(file) {
    return new Promise((resolve, reject) => {
      file.stat((err, st) => {
        if (err) {
          resolve(0) // prob just file not found (TODO, improve)
        } else if (typeof st.blocks !== 'number') {
          reject(new Error('cannot determine bytes used'))
        } else {
          resolve(st.blocks * 512)
        }
      })
    })
  }
}
const b4a = require('b4a')

module.exports = function (core, depth, opts) {
  let indent = ''
  if (typeof opts.indentationLvl === 'number') {
    while (indent.length < opts.indentationLvl) indent += ' '
  }

  let peers = ''
  const min = Math.min(core.peers.length, 5)

  for (let i = 0; i < min; i++) {
    const peer = core.peers[i]

    peers += `${indent}    Peer(\n`
    peers += `${indent}      remotePublicKey: ${opts.stylize(toHex(peer.remotePublicKey), 'string')}\n`
    peers += `${indent}      remoteLength: ${opts.stylize(peer.remoteLength, 'number')}\n`
    peers += `${indent}      remoteFork: ${opts.stylize(peer.remoteFork, 'number')}\n`
    peers += `${indent}      remoteCanUpgrade: ${opts.stylize(peer.remoteCanUpgrade, 'boolean')}\n`
    peers += `${indent}    )\n`
  }

  if (core.peers.length > 5) {
    peers += `${indent}  ... and ${core.peers.length - 5} more\n`
  }

  if (peers) peers = `[\n${peers}${indent}  ]`
  else peers = `[ ${opts.stylize(0, 'number')} ]`

  return (
    `${core.constructor.name}(\n` +
    `${indent}  id: ${opts.stylize(core.id, 'string')}\n` +
    `${indent}  key: ${opts.stylize(toHex(core.key), 'string')}\n` +
    `${indent}  discoveryKey: ${opts.stylize(toHex(core.discoveryKey), 'string')}\n` +
    `${indent}  opened: ${opts.stylize(core.opened, 'boolean')}\n` +
    `${indent}  closed: ${opts.stylize(core.closed, 'boolean')}\n` +
    `${indent}  snapshotted: ${opts.stylize(core.snapshotted, 'boolean')}\n` +
    `${indent}  writable: ${opts.stylize(core.writable, 'boolean')}\n` +
    `${indent}  length: ${opts.stylize(core.length, 'number')}\n` +
    `${indent}  fork: ${opts.stylize(core.fork, 'number')}\n` +
    `${indent}  sessions: [ ${opts.stylize(core.sessions.length, 'number')} ]\n` +
    `${indent}  activeRequests: [ ${opts.stylize(core.activeRequests.length, 'number')} ]\n` +
    `${indent}  peers: ${peers}\n` +
    `${indent})`
  )
}

function toHex(buf) {
  return buf && b4a.toString(buf, 'hex')
}
const BigSparseArray = require('big-sparse-array')
const { Transform } = require('streamx')
const quickbit = require('./compat').quickbit
const b4a = require('b4a')

const BITS_PER_PAGE = 32768
const BYTES_PER_PAGE = BITS_PER_PAGE / 8

class MarkPage {
  constructor() {
    this.bitfield = null
    this.loaded = new Promise((resolve) => {
      this.load = resolve
    })
  }

  setBitfield(bitfield) {
    this.bitfield = bitfield
    this.load()
  }

  get(index) {
    return quickbit.get(this.bitfield, index)
  }

  set(index, val) {
    quickbit.set(this.bitfield, index, val)
  }
}

module.exports = class MarkBitfield {
  static BITS_PER_PAGE = BITS_PER_PAGE
  static BYTES_PER_PAGE = BYTES_PER_PAGE

  constructor(storage) {
    this.storage = storage
    this._pages = new BigSparseArray()
  }

  async loadPage(pageIndex) {
    const p = this._pages.set(pageIndex, new MarkPage())
    const rx = this.storage.read()
    const pageBuf = rx.getMark(pageIndex)
    rx.tryFlush()
    const bitfield = (await pageBuf) ?? b4a.alloc(BYTES_PER_PAGE)
    await p.setBitfield(bitfield)
    return p
  }

  async get(index) {
    const j = index & (BITS_PER_PAGE - 1)
    const i = (index - j) / BITS_PER_PAGE

    let p = this._pages.get(i)
    if (!p) p = await this.loadPage(i)

    return p.get(j)
  }

  async set(index, val) {
    const j = index & (BITS_PER_PAGE - 1)
    const i = (index - j) / BITS_PER_PAGE

    let p = this._pages.get(i)

    if (!p && val) p = await this.loadPage(i)

    if (p) {
      await p.loaded
      p.set(j, val)
      const tx = this.storage.write()
      tx.putMark(i, p.bitfield)
      await tx.flush()
    }
  }

  async clear() {
    const tx = this.storage.write()
    tx.deleteMarkRange(0, -1)
    await tx.flush()
    this._pages = new BigSparseArray()
  }

  createMarkStream({ reverse = false } = {}) {
    return this.storage.createMarkStream({ reverse }).pipe(
      new Transform({
        transform({ index, page }, cb) {
          let bitIndex = reverse
            ? quickbit.findLast(page, true, BITS_PER_PAGE)
            : quickbit.findFirst(page, true, 0)
          while (bitIndex !== -1) {
            const blockIndex = index * BITS_PER_PAGE + bitIndex
            this.push(blockIndex)

            // Account for `bitIndex` being either causing infinite loop
            if (bitIndex === 0 && reverse) break

            bitIndex = reverse
              ? quickbit.findLast(page, true, bitIndex - 1)
              : quickbit.findFirst(page, true, bitIndex + 1)
          }

          cb(null)
        }
      })
    )
  }
}
const flat = require('flat-tree')
const crypto = require('hypercore-crypto')
const b4a = require('b4a')
const unslab = require('unslab')
const caps = require('./caps')
const {
  INVALID_PROOF,
  INVALID_CHECKSUM,
  INVALID_OPERATION,
  BAD_ARGUMENT,
  ASSERTION
} = require('hypercore-errors')

class NodeQueue {
  constructor(nodes, extra = null) {
    this.i = 0
    this.nodes = nodes
    this.extra = extra
    this.length = nodes.length + (this.extra === null ? 0 : 1)
  }

  shift(index) {
    if (this.extra !== null && this.extra.index === index) {
      const node = this.extra
      this.extra = null
      this.length--
      return node
    }

    if (this.i >= this.nodes.length) {
      throw INVALID_OPERATION('Expected node ' + index + ', got (nil)')
    }

    const node = this.nodes[this.i++]
    if (node.index !== index) {
      throw INVALID_OPERATION('Expected node ' + index + ', got node ' + node.index)
    }

    this.length--
    return node
  }
}

class MerkleTreeBatch {
  constructor(session) {
    this.fork = session.fork
    this.roots = [...session.roots]
    this.length = session.length
    this.signature = session.signature
    this.ancestors = session.length
    this.byteLength = session.byteLength
    this.prologue = session.prologue
    this.hashCached = null

    this.committed = false
    this.truncated = false
    this.treeLength = session.length
    this.treeFork = session.fork
    this.storage = session.storage
    this.session = session
    this.nodes = []
    this.upgraded = false
  }

  checkout(length, additionalRoots) {
    const roots = []
    let r = 0

    const head = 2 * length - 2
    const gaps = new Set()
    const all = new Map()

    // additional roots is so the original roots can be passed (we mutate the array in appendRoot)
    if (additionalRoots) {
      for (const node of additionalRoots) all.set(node.index, node)
    }

    for (const node of this.nodes) all.set(node.index, node)

    for (const index of flat.fullRoots(head + 2)) {
      const left = flat.leftSpan(index)
      if (left !== 0) gaps.add(left - 1)

      if (r < this.roots.length && this.roots[r].index === index) {
        roots.push(this.roots[r++])
        continue
      }
      const node = all.get(index)
      if (!node) throw new BAD_ARGUMENT('root missing for given length')
      roots.push(node)
    }

    this.roots = roots
    this.length = length
    this.byteLength = totalSize(roots)
    this.hashCached = null
    this.signature = null

    for (let i = 0; i < this.nodes.length; i++) {
      const index = this.nodes[i].index
      if (index <= head && !gaps.has(index)) continue
      const last = this.nodes.pop()
      if (i < this.nodes.length) this.nodes[i--] = last
    }
  }

  prune(length) {
    if (length === 0) return

    const head = 2 * length - 2
    const gaps = new Set()

    // TODO: make a function for this in flat-tree
    for (const index of flat.fullRoots(head + 2)) {
      const left = flat.leftSpan(index)
      if (left !== 0) gaps.add(left - 1)
    }

    for (let i = 0; i < this.nodes.length; i++) {
      const index = this.nodes[i].index
      if (index > head || gaps.has(index)) continue
      const last = this.nodes.pop()
      if (i < this.nodes.length) this.nodes[i--] = last
    }
  }

  clone() {
    const b = new MerkleTreeBatch(this.session)

    b.fork = this.fork
    b.roots = [...this.roots]
    b.length = this.length
    b.byteLength = this.byteLength
    b.signature = this.signature
    b.treeLength = this.treeLength
    b.treeFork = this.treeFork
    b.tree = this.tree
    b.nodes = [...this.nodes]
    b.upgraded = this.upgraded

    return b
  }

  hash() {
    if (this.hashCached === null) this.hashCached = unslab(crypto.tree(this.roots))
    return this.hashCached
  }

  signable(manifestHash) {
    return caps.treeSignable(manifestHash, this.hash(), this.length, this.fork)
  }

  signableCompat(noHeader) {
    return caps.treeSignableCompat(this.hash(), this.length, this.fork, noHeader)
  }

  get(index) {
    if (index >= this.length * 2) {
      return null
    }

    for (const n of this.nodes) {
      if (n.index === index) return n
    }

    return getTreeNodeFromStorage(this.session.storage, index)
  }

  // deprecated, use sssion proof instead
  proof(batch, { block, hash, seek, upgrade }) {
    return generateProof(this.session, batch, block, hash, seek, upgrade)
  }

  verifyUpgrade(proof) {
    const unverified = verifyTree(proof, this.nodes)

    if (!proof.upgrade) throw INVALID_OPERATION('Expected upgrade proof')

    return verifyUpgrade(proof, unverified, this)
  }

  addNodesUnsafe(nodes) {
    for (let i = 0; i < nodes.length; i++) {
      this.nodes.push(nodes[i])
    }
  }

  append(buf) {
    const head = this.length * 2
    const ite = flat.iterator(head)
    const node = blockNode(head, buf)

    this.appendRoot(node, ite)
  }

  appendRoot(node, ite) {
    node = unslabNode(node)
    this.hashCached = null
    this.upgraded = true
    this.length += ite.factor / 2
    this.byteLength += node.size
    this.roots.push(node)
    this.nodes.push(node)

    while (this.roots.length > 1) {
      const a = this.roots[this.roots.length - 1]
      const b = this.roots[this.roots.length - 2]

      // TODO: just have a peek sibling instead? (pretty sure it's always the left sib as well)
      if (ite.sibling() !== b.index) {
        ite.sibling() // unset so it always points to last root
        break
      }

      const node = unslabNode(parentNode(ite.parent(), a, b))
      this.nodes.push(node)
      this.roots.pop()
      this.roots.pop()
      this.roots.push(node)
    }
  }

  commitable() {
    return (
      this.treeFork === this.session.fork &&
      (this.upgraded
        ? this.treeLength === this.session.length
        : this.treeLength <= this.session.length)
    )
  }

  commit(tx) {
    if (tx === undefined) throw INVALID_OPERATION('No database batch was passed')

    if (this.session.core._repairMode) {
      throw ASSERTION('Cannot commit while repair mode is on')
    }

    if (!this.commitable()) {
      throw INVALID_OPERATION('Tree was modified during batch, refusing to commit')
    }

    if (this.upgraded) this._commitUpgrade(tx)

    for (let i = 0; i < this.nodes.length; i++) {
      const node = this.nodes[i]
      tx.putTreeNode(node)
    }

    this.committed = true

    return this
  }

  _commitUpgrade(tx) {
    // TODO: If easy to detect, we should refuse an trunc+append here without a fork id
    // change. Will only happen on user error so mostly to prevent that.

    if (this.ancestors < this.treeLength) {
      tx.deleteTreeNodeRange(this.ancestors * 2, this.treeLength * 2)

      if (this.ancestors > 0) {
        const head = this.ancestors * 2
        const ite = flat.iterator(head - 2)

        while (true) {
          if (ite.contains(head) && ite.index < head) {
            tx.deleteTreeNode(ite.index)
          }
          if (ite.offset === 0) break
          ite.parent()
        }

        this.truncated = true
      }
    }
  }

  seek(bytes, padding) {
    return new ByteSeeker(this, this, bytes, padding)
  }

  byteRange(index) {
    const rx = this.storage.read()
    const range = getByteRange(this, index, rx)
    rx.tryFlush()

    return range
  }

  byteOffset(index) {
    if (index === 2 * this.length) return this.byteLength

    const rx = this.storage.read()
    const offset = getByteOffset(this, index, rx)
    rx.tryFlush()

    return offset
  }

  async downgrade() {
    if (!this.upgraded) return true

    const rx = this.storage.read()
    const nodePromises = []

    for (const r of this.roots) {
      nodePromises.push(rx.getTreeNode(r.index))
    }

    rx.tryFlush()

    const nodes = await Promise.all(nodePromises)

    for (let i = 0; i < this.roots.length; i++) {
      const root = this.roots[i]
      const node = nodes[i]

      if (!node) return false
      if (!b4a.equals(node.hash, root.hash)) return false
    }

    this.upgraded = false
    return true
  }

  async restore(length) {
    if (length === this.length) return this

    const roots = unslabNodes(await MerkleTree.getRootsFromStorage(this.storage, length))

    this.roots = roots
    this.length = length
    this.byteLength = totalSize(roots)
    this.ancestors = length

    for (const node of roots) this.byteLength += node.size

    return this
  }
}

class ReorgBatch extends MerkleTreeBatch {
  constructor(session) {
    super(session)

    this.roots = []
    this.length = 0
    this.byteLength = 0
    this.diff = null
    this.ancestors = 0
    // We set upgraded because reorgs are signed so hit will
    // hit the same code paths (like the treeLength check in commit)
    this.upgraded = true
    this.want = {
      nodes: 0,
      start: 0,
      end: 0
    }
  }

  get finished() {
    return this.want === null
  }

  update(proof) {
    if (this.want === null) return true

    const nodes = []
    const root = verifyTree(proof, nodes)

    if (root === null || !b4a.equals(root.hash, this.diff.hash)) return false

    this.nodes.push(...nodes)
    return this._update(nodes)
  }

  async _update(nodes) {
    const n = new Map()
    for (const node of nodes) n.set(node.index, node)

    let diff = null
    const ite = flat.iterator(this.diff.index)
    const startingDiff = this.diff

    while ((ite.index & 1) !== 0) {
      const left = n.get(ite.leftChild())
      if (!left) break

      const existing = await getTreeNodeFromStorage(this.session.storage, left.index)
      if (!existing || !b4a.equals(existing.hash, left.hash)) {
        diff = left
      } else {
        diff = n.get(ite.sibling())
      }
    }

    if ((this.diff.index & 1) === 0) return true
    if (diff === null) return false
    if (startingDiff !== this.diff) return false

    return this._updateDiffRoot(diff)
  }

  _updateDiffRoot(diff) {
    if (this.want === null) return true

    const spans = flat.spans(diff.index)
    const start = spans[0] / 2
    const end = Math.min(this.treeLength, spans[1] / 2 + 1)
    const len = end - start

    this.ancestors = start
    this.diff = diff

    if ((diff.index & 1) === 0 || this.want.start >= this.treeLength || len <= 0) {
      this.want = null
      return true
    }

    this.want.start = start
    this.want.end = end
    this.want.nodes = log2(spans[1] - spans[0] + 2) - 1

    return false
  }
}

class ByteSeeker {
  constructor(session, bytes, padding = 0) {
    this.session = session
    this.bytes = bytes
    this.padding = padding

    const size = session.byteLength - session.length * padding

    this.start = bytes >= size ? session.length : 0
    this.end = bytes < size ? session.length : 0
  }

  async _seek(bytes) {
    if (!bytes) return [0, 0]

    for (const node of this.session.roots) {
      // all async ticks happen once we find the root so safe
      const size = getUnpaddedSize(node, this.padding, null)

      if (bytes === size) return [flat.rightSpan(node.index) + 2, 0]
      if (bytes > size) {
        bytes -= size
        continue
      }

      const ite = flat.iterator(node.index)

      while ((ite.index & 1) !== 0) {
        const l = await getTreeNodeFromStorage(this.session.storage, ite.leftChild())

        if (l) {
          const size = getUnpaddedSize(l, this.padding, ite)

          if (size === bytes) return [ite.rightSpan() + 2, 0]
          if (size > bytes) continue
          bytes -= size
          ite.sibling()
        } else {
          ite.parent()
          return [ite.index, bytes]
        }
      }

      return [ite.index, bytes]
    }

    return null
  }

  async update() {
    // TODO: combine _seek and this, much simpler
    const res = await this._seek(this.bytes)
    if (!res) return null
    if ((res[0] & 1) === 0) return [res[0] / 2, res[1]]

    const span = flat.spans(res[0])
    this.start = span[0] / 2
    this.end = span[1] / 2 + 1

    return null
  }
}

class TreeProof {
  constructor(session, block, hash, seek, upgrade) {
    this.fork = session.fork
    this.signature = session.signature

    this.block = block
    this.hash = hash
    this.seek = seek
    this.upgrade = upgrade

    this.pending = {
      node: null,
      seek: null,
      upgrade: null,
      additionalUpgrade: null
    }
  }

  async settle() {
    const result = {
      fork: this.fork,
      block: null,
      hash: null,
      seek: null,
      upgrade: null,
      manifest: null
    }

    const [pNode, pSeek, pUpgrade, pAdditional] = await settleProof(this.pending)

    if (this.block) {
      if (pNode === null) throw INVALID_OPERATION('Invalid block request')
      result.block = {
        index: this.block.index,
        value: null, // populated upstream, alloc it here for simplicity
        nodes: pNode
      }
    } else if (this.hash) {
      if (pNode === null) throw INVALID_OPERATION('Invalid block request')
      result.hash = {
        index: this.hash.index,
        nodes: pNode
      }
    }

    if (this.seek && pSeek !== null) {
      result.seek = {
        bytes: this.seek.bytes,
        nodes: pSeek
      }
    }

    if (this.upgrade) {
      result.upgrade = {
        start: this.upgrade.start,
        length: this.upgrade.length,
        nodes: pUpgrade,
        additionalNodes: pAdditional || [],
        signature: this.signature
      }
    }

    return result
  }
}

class MerkleTree {
  static hash(s) {
    return unslab(crypto.tree(s.roots))
  }

  static signable(s, namespace) {
    return caps.treeSignable(namespace, MerkleTree.hash(s), s.length, s.fork)
  }

  static size(roots) {
    return totalSize(roots)
  }

  static span(roots) {
    return totalSpan(roots)
  }

  static getRoots(session, length) {
    return MerkleTree.getRootsFromStorage(session.storage, length)
  }

  static getRootsFromStorage(storage, length) {
    const indexes = flat.fullRoots(2 * length)
    const roots = new Array(indexes.length)
    const rx = storage.read()

    for (let i = 0; i < indexes.length; i++) {
      roots[i] = getTreeNodeOrError(rx, indexes[i])
    }

    rx.tryFlush()

    return Promise.all(roots)
  }

  static async upgradeable(session, length) {
    const indexes = flat.fullRoots(2 * length)
    const roots = new Array(indexes.length)
    const rx = session.storage.read()

    for (let i = 0; i < indexes.length; i++) {
      roots[i] = rx.getTreeNode(indexes[i])
    }

    rx.tryFlush()

    for (const node of await Promise.all(roots)) {
      if (node === null) return false
    }

    return true
  }

  static seek(session, bytes, padding) {
    return new ByteSeeker(session, bytes, padding)
  }

  static get(session, index) {
    return getTreeNodeFromStorage(session.storage, index)
  }

  static async truncate(session, length, batch, fork = batch.fork) {
    const head = length * 2
    const fullRoots = flat.fullRoots(head)

    for (let i = 0; i < fullRoots.length; i++) {
      const root = fullRoots[i]
      if (i < batch.roots.length && batch.roots[i].index === root) continue

      while (batch.roots.length > i) batch.roots.pop()
      batch.roots.push(unslabNode(await getTreeNodeFromStorageOrError(session.storage, root)))
    }

    while (batch.roots.length > fullRoots.length) {
      batch.roots.pop()
    }

    batch.fork = fork
    batch.length = length
    batch.ancestors = length
    batch.byteLength = totalSize(batch.roots)
    batch.upgraded = true

    return batch
  }

  static async reorg(session, proof, batch) {
    let unverified = null

    if (proof.block || proof.hash || proof.seek) {
      unverified = verifyTree(proof, batch.nodes)
    }

    if (!verifyUpgrade(proof, unverified, batch)) {
      throw INVALID_PROOF('Fork proof not verifiable')
    }

    for (const root of batch.roots) {
      const existing = await getTreeNodeFromStorage(session.storage, root.index)
      if (existing && b4a.equals(existing.hash, root.hash)) continue
      batch._updateDiffRoot(root)
      break
    }

    if (batch.diff !== null) {
      await batch._update(batch.nodes)
    } else {
      batch.want = null
      batch.ancestors = batch.length
    }

    return batch
  }

  static verifyFullyRemote(session, proof) {
    // TODO: impl this less hackishly
    const batch = new MerkleTreeBatch(session)

    batch.fork = proof.fork
    batch.roots = []
    batch.length = 0
    batch.ancestors = 0
    batch.byteLength = 0

    let unverified = verifyTree(proof, batch.nodes)

    if (proof.upgrade) {
      if (verifyUpgrade(proof, unverified, batch)) {
        unverified = null
      }
    }

    return batch
  }

  static async verify(session, proof) {
    const batch = new MerkleTreeBatch(session)

    let unverified = verifyTree(proof, batch.nodes)

    if (proof.upgrade) {
      if (verifyUpgrade(proof, unverified, batch)) {
        unverified = null
      }
    }

    if (unverified) {
      const verified = await getTreeNodeFromStorageOrError(session.storage, unverified.index)
      if (!b4a.equals(verified.hash, unverified.hash)) {
        throw INVALID_CHECKSUM('Invalid checksum at node ' + unverified.index)
      }
    }

    return batch
  }

  static proof(session, rx, { block, hash, seek, upgrade }) {
    return generateProof(session, rx, block, hash, seek, upgrade)
  }

  static maxMissingNodes(index, length) {
    const head = 2 * length
    const ite = flat.iterator(index)

    // See iterator.rightSpan()
    const iteRightSpan = ite.index + ite.factor / 2 - 1
    // If the index is not in the current tree, we do not know how many missing nodes there are...
    if (iteRightSpan >= head) return 0

    for (const r of flat.fullRoots(head)) {
      if (r === index) return 0
    }

    // need missing nodes not inclusive of index
    ite.parent()

    let cnt = 0
    while (!ite.contains(head)) {
      cnt++
      ite.parent()
    }

    return cnt
  }

  static async missingNodes(session, index, length) {
    const head = 2 * length
    const ite = flat.iterator(index)

    // See iterator.rightSpan()
    const iteRightSpan = ite.index + ite.factor / 2 - 1
    // If the index is not in the current tree, we do not know how many missing nodes there are...
    if (iteRightSpan >= head) return 0

    let cnt = 0
    // TODO: we could prop use a read batch here and do this in blocks of X for perf
    while (!ite.contains(head) && !(await hasTreeNode(session.storage, ite.index))) {
      cnt++
      if (cnt >= 1024) {
        throw ASSERTION('Bad arguments to missingNodes index=' + index + ' at length=' + length)
      }
      ite.parent()
    }

    return cnt
  }

  static byteOffset(session, index) {
    return getByteOffsetSession(session, index, null)
  }

  static byteRange(session, index) {
    const rx = session.storage.read()
    const offset = getByteOffsetSession(session, index, rx)
    const size = getNodeSize(index, rx)
    rx.tryFlush()
    return Promise.all([offset, size])
  }

  static upgradeLength(proof) {
    const extra = proof.additionalNodes

    if (extra.length) {
      const last = extra[extra.length - 1]
      const index = flat.rightSpan(last.index)
      return index / 2 + 1
    }

    return proof.start + proof.length
  }
}

module.exports = {
  MerkleTreeBatch,
  ReorgBatch,
  MerkleTree
}

async function getNodeSize(index, rx) {
  return (await getTreeNodeOrError(rx, index)).size
}

async function getByteOffsetSession(session, index, rx) {
  if (index === 2 * session.length) return session.byteLength

  const treeNodes =
    rx === null
      ? await getByteOffsetBatchFlush(session.roots, index, session.storage.read())
      : await getByteOffsetBatch(session.roots, index, rx)

  let offset = 0
  for (const node of treeNodes) offset += node.size

  return offset
}

async function getByteOffset(tree, index, rx) {
  if (index === 2 * tree.length) return tree.byteLength

  const treeNodes = await getByteOffsetBatch(tree.roots, index, rx)

  let offset = 0
  for (const node of treeNodes) offset += node.size

  return offset
}

function getByteOffsetBatchFlush(roots, index, rx) {
  const treeNodes = getByteOffsetBatch(roots, index, rx)
  rx.tryFlush()
  return treeNodes
}

function getByteOffsetBatch(roots, index, rx) {
  if ((index & 1) === 1) index = flat.leftSpan(index)

  let head = 0
  let cnt = 0

  const promises = []

  for (const node of roots) {
    // all async ticks happen once we find the root so safe
    head += 2 * (node.index - head + 1)

    if (index >= head) {
      promises.push(node.size)
      continue
    }

    const ite = flat.iterator(node.index)

    while (ite.index !== index) {
      if (++cnt >= 1024) throw ASSERTION('Bad getByteOffsetSession index=' + index)

      if (index < ite.index) {
        ite.leftChild()
      } else {
        promises.push(getTreeNodeOrError(rx, ite.leftChild()))
        ite.sibling()
      }
    }

    return Promise.all(promises)
  }

  throw ASSERTION('Failed to find offset')
}

function getByteRange(tree, index, rx) {
  const head = 2 * tree.length
  if (((index & 1) === 0 ? index : flat.rightSpan(index)) >= head) {
    throw BAD_ARGUMENT('Index is out of bounds')
  }

  const offset = getByteOffset(tree, index, rx)
  const size = getNodeSize(index, rx)

  return Promise.all([offset, size])
}

// All the methods needed for proof verification

function verifyTree({ block, hash, seek }, nodes) {
  const untrustedNode = block
    ? { index: 2 * block.index, value: block.value, nodes: block.nodes }
    : hash
      ? { index: hash.index, value: null, nodes: hash.nodes }
      : null

  if (untrustedNode === null && (!seek || !seek.nodes.length)) return null

  let root = null

  if (seek && seek.nodes.length) {
    const ite = flat.iterator(seek.nodes[0].index)
    const q = new NodeQueue(seek.nodes)

    root = q.shift(ite.index)
    nodes.push(root)

    while (q.length > 0) {
      const node = q.shift(ite.sibling())

      root = parentNode(ite.parent(), root, node)
      nodes.push(node)
      nodes.push(root)
    }
  }

  if (untrustedNode === null) return root

  const ite = flat.iterator(untrustedNode.index)
  const blockHash = untrustedNode.value && blockNode(ite.index, untrustedNode.value)

  const q = new NodeQueue(untrustedNode.nodes, root)

  root = blockHash || q.shift(ite.index)
  nodes.push(root)

  while (q.length > 0) {
    const node = q.shift(ite.sibling())

    root = parentNode(ite.parent(), root, node)
    nodes.push(node)
    nodes.push(root)
  }

  return root
}

function verifyUpgrade({ fork, upgrade }, blockRoot, batch) {
  const prologue = batch.prologue

  if (prologue) {
    const { start, length } = upgrade
    if (start < prologue.length && (start !== 0 || length < prologue.length)) {
      throw INVALID_PROOF('Upgrade does not satisfy prologue')
    }
  }

  const q = new NodeQueue(upgrade.nodes, blockRoot)

  let grow = batch.roots.length > 0
  let i = 0

  const to = 2 * (upgrade.start + upgrade.length)
  const ite = flat.iterator(0)

  for (; ite.fullRoot(to); ite.nextTree()) {
    if (i < batch.roots.length && batch.roots[i].index === ite.index) {
      i++
      continue
    }

    if (grow) {
      grow = false
      const root = ite.index
      if (i < batch.roots.length) {
        ite.seek(batch.roots[batch.roots.length - 1].index)
        while (ite.index !== root) {
          batch.appendRoot(q.shift(ite.sibling()), ite)
        }
        continue
      }
    }

    batch.appendRoot(q.shift(ite.index), ite)
  }

  if (prologue && batch.length === prologue.length) {
    if (!b4a.equals(prologue.hash, batch.hash())) {
      throw INVALID_PROOF('Invalid hash')
    }
  }

  const extra = upgrade.additionalNodes

  ite.seek(batch.roots[batch.roots.length - 1].index)
  i = 0

  while (i < extra.length && extra[i].index === ite.sibling()) {
    batch.appendRoot(extra[i++], ite)
  }

  while (i < extra.length) {
    const node = extra[i++]

    while (node.index !== ite.index) {
      if (ite.factor === 2) throw INVALID_OPERATION('Unexpected node: ' + node.index)
      ite.leftChild()
    }

    batch.appendRoot(node, ite)
    ite.sibling()
  }

  batch.signature = unslab(upgrade.signature)
  batch.fork = fork

  return q.extra === null
}

async function seekFromHead(session, head, bytes, padding) {
  const roots = flat.fullRoots(head)

  for (let i = 0; i < roots.length; i++) {
    const root = roots[i]
    const node = await getTreeNodeFromStorage(session.storage, root)
    const size = getUnpaddedSize(node, padding, null)

    if (bytes === size) return root
    if (bytes > size) {
      bytes -= size
      continue
    }

    return seekTrustedTree(session, root, bytes, padding)
  }

  return head
}

// trust that bytes are within the root tree and find the block at bytes

async function seekTrustedTree(session, root, bytes, padding) {
  if (!bytes) return root

  const ite = flat.iterator(root)
  let cnt = 0

  while ((ite.index & 1) !== 0) {
    if (++cnt >= 1024) throw ASSERTION('Bad seekTrusted bytes=' + bytes + ', paddding=' + padding)
    const l = await getTreeNodeFromStorage(session.storage, ite.leftChild())

    if (l) {
      const size = getUnpaddedSize(l, padding, ite)
      if (size === bytes) return ite.index
      if (size > bytes) continue
      bytes -= size
      ite.sibling()
    } else {
      ite.parent()
      return ite.index
    }
  }

  return ite.index
}

// try to find the block at bytes without trusting that is *is* within the root passed

async function seekUntrustedTree(session, root, bytes, padding) {
  const offset =
    (await getByteOffsetSession(session, root, null)) -
    (padding ? (padding * flat.leftSpan(root)) / 2 : 0)

  if (offset > bytes) throw INVALID_OPERATION('Invalid seek')
  if (offset === bytes) return root

  bytes -= offset

  const node = await getTreeNodeFromStorageOrError(session.storage, root)

  if (getUnpaddedSize(node, padding, null) <= bytes) throw INVALID_OPERATION('Invalid seek')

  return seekTrustedTree(session, root, bytes, padding)
}

// Below is proof production, ie, construct proofs to verify a request
// Note, that all these methods are sync as we can statically infer which nodes
// are needed for the remote to verify given they arguments they passed us

function seekProof(session, rx, seekRoot, root, p) {
  const ite = flat.iterator(seekRoot)
  let cnt = 0

  p.seek = []
  p.seek.push(getTreeNodeOrError(rx, ite.index))

  while (ite.index !== root) {
    if (++cnt >= 1024) throw ASSERTION('Bad seekProof seekRoot=' + seekRoot + ', root=' + root)
    ite.sibling()
    p.seek.push(getTreeNodeOrError(rx, ite.index))
    ite.parent()
  }
}

function blockAndSeekProof(session, rx, node, seek, seekRoot, root, p) {
  if (!node) return seekProof(session, rx, seekRoot, root, p)

  const ite = flat.iterator(node.index)
  let cnt = 0

  p.node = []
  if (!node.value) p.node.push(getTreeNodeOrError(rx, ite.index))

  while (ite.index !== root) {
    if (++cnt >= 1024) {
      throw ASSERTION('Bad blockAndSeekProof seekRoot=' + seekRoot + ', root=' + root)
    }
    ite.sibling()

    if (seek && ite.contains(seekRoot) && ite.index !== seekRoot) {
      seekProof(session, rx, seekRoot, ite.index, p)
    } else {
      p.node.push(getTreeNodeOrError(rx, ite.index))
    }

    ite.parent()
  }
}

function upgradeProof(session, rx, node, seek, from, to, subTree, p) {
  if (from === 0) p.upgrade = []

  for (const ite = flat.iterator(0); ite.fullRoot(to); ite.nextTree()) {
    // check if they already have the node
    if (ite.index + ite.factor / 2 < from) continue

    // connect existing tree
    if (p.upgrade === null && ite.contains(from - 2)) {
      p.upgrade = []

      const root = ite.index
      const target = from - 2
      let cnt = 0

      ite.seek(target)

      while (ite.index !== root) {
        if (++cnt >= 1024) throw ASSERTION('Bad upgradeProof target=' + target + ', root=' + root)

        ite.sibling()
        if (ite.index > target) {
          if (p.node === null && p.seek === null && ite.contains(subTree)) {
            blockAndSeekProof(session, rx, node, seek, subTree, ite.index, p)
          } else {
            p.upgrade.push(getTreeNodeOrError(rx, ite.index))
          }
        }
        ite.parent()
      }

      continue
    }

    if (p.upgrade === null) {
      p.upgrade = []
    }

    // if the subtree included is a child of this tree, include that one
    // instead of a dup node
    if (p.node === null && p.seek === null && ite.contains(subTree)) {
      blockAndSeekProof(session, rx, node, seek, subTree, ite.index, p)
      continue
    }

    // add root (can be optimised since the root might be in tree.roots)
    p.upgrade.push(getTreeNodeOrError(rx, ite.index))
  }
}

function additionalUpgradeProof(session, rx, from, to, p) {
  if (from === 0) p.additionalUpgrade = []

  for (const ite = flat.iterator(0); ite.fullRoot(to); ite.nextTree()) {
    // check if they already have the node
    if (ite.index + ite.factor / 2 < from) continue

    // connect existing tree
    if (p.additionalUpgrade === null && ite.contains(from - 2)) {
      p.additionalUpgrade = []

      const root = ite.index
      const target = from - 2
      let cnt = 0

      ite.seek(target)

      while (ite.index !== root) {
        if (++cnt >= 1024) {
          throw ASSERTION(
            'Bad arguments to additionalUpgradeProof root=' + root + ' target=' + target
          )
        }
        ite.sibling()
        if (ite.index > target) {
          p.additionalUpgrade.push(getTreeNodeOrError(rx, ite.index))
        }
        ite.parent()
      }

      continue
    }

    if (p.additionalUpgrade === null) {
      p.additionalUpgrade = []
    }

    // add root (can be optimised since the root is in tree.roots)
    p.additionalUpgrade.push(getTreeNodeOrError(rx, ite.index))
  }
}

function nodesToRoot(index, nodes, head) {
  const ite = flat.iterator(index)

  for (let i = 0; i < nodes; i++) {
    ite.parent()
    if (ite.contains(head)) throw INVALID_OPERATION('Nodes is out of bounds')
  }

  return ite.index
}

function totalSize(nodes) {
  let s = 0
  for (const node of nodes) s += node.size
  return s
}

function totalSpan(nodes) {
  let s = 0
  for (const node of nodes) s += 2 * (node.index - s + 1)
  return s
}

function blockNode(index, value) {
  return { index, size: value.byteLength, hash: crypto.data(value) }
}

function parentNode(index, a, b) {
  return { index, size: a.size + b.size, hash: crypto.parent(a, b) }
}

function log2(n) {
  let res = 1

  while (n > 2) {
    n /= 2
    res++
  }

  return res
}

function normalizeIndexed(block, hash) {
  if (block) {
    return {
      value: true,
      index: block.index * 2,
      nodes: block.nodes,
      lastIndex: block.index
    }
  }
  if (hash) {
    return {
      value: false,
      index: hash.index,
      nodes: hash.nodes,
      lastIndex: flat.rightSpan(hash.index) / 2
    }
  }
  return null
}

async function getTreeNodeOrError(rx, index) {
  const node = await rx.getTreeNode(index)
  if (node === null) {
    throw INVALID_OPERATION('Expected tree node ' + index + ' from storage, got (nil)')
  }
  return node
}

function getTreeNodeFromStorageOrError(storage, index) {
  const rx = storage.read()
  const p = getTreeNodeOrError(rx, index)
  rx.tryFlush()
  return p
}

function getTreeNodeFromStorage(storage, index) {
  const rx = storage.read()
  const node = rx.getTreeNode(index)
  rx.tryFlush()
  return node
}

function hasTreeNode(storage, index) {
  const rx = storage.read()
  const has = rx.hasTreeNode(index)
  rx.tryFlush()
  return has
}

async function settleProof(p) {
  const result = [
    p.node && Promise.all(p.node),
    p.seek && Promise.all(p.seek),
    p.upgrade && Promise.all(p.upgrade),
    p.additionalUpgrade && Promise.all(p.additionalUpgrade)
  ]

  try {
    return await Promise.all(result)
  } catch (err) {
    if (p.node) await Promise.allSettled(p.node)
    if (p.seek) await Promise.allSettled(p.seek)
    if (p.upgrade) await Promise.allSettled(p.upgrade)
    if (p.additionalUpgrade) await Promise.allSettled(p.additionalUpgrade)
    throw err
  }
}

// tree can be either the merkle tree or a merkle tree batch
async function generateProof(session, rx, block, hash, seek, upgrade) {
  // Important that this does not throw inbetween making the promise arrays
  // and finalise being called, otherwise there will be lingering promises in the background

  if (session.prologue && upgrade) {
    upgrade.start = upgrade.start < session.prologue.length ? 0 : upgrade.start
    upgrade.length =
      upgrade.start < session.prologue.length ? session.prologue.length : upgrade.length
  }

  const head = 2 * session.length
  const from = upgrade ? upgrade.start * 2 : 0
  const to = upgrade ? from + upgrade.length * 2 : head
  const node = normalizeIndexed(block, hash)

  // can't do anything as we have no data...
  if (head === 0) return new TreeProof(session, null, null, null, null)

  if (from >= to || to > head) {
    throw INVALID_OPERATION('Invalid upgrade')
  }
  if (seek && upgrade && node !== null && node.index >= from) {
    throw INVALID_OPERATION('Cannot both do a seek and block/hash request when upgrading')
  }

  let subTree = head

  const p = new TreeProof(session, block, hash, seek, upgrade)

  if (node !== null && (!upgrade || node.lastIndex < upgrade.start)) {
    subTree = nodesToRoot(node.index, node.nodes, to)
    const seekRoot = seek
      ? await seekUntrustedTree(session, subTree, seek.bytes, seek.padding)
      : head
    blockAndSeekProof(session, rx, node, seek, seekRoot, subTree, p.pending)
  } else if ((node || seek) && upgrade) {
    subTree = seek ? await seekFromHead(session, to, seek.bytes, seek.padding) : node.index
  }

  if (upgrade) {
    upgradeProof(session, rx, node, seek, from, to, subTree, p.pending)
    if (head > to) additionalUpgradeProof(session, rx, to, head, p.pending)
  }

  return p
}

function getUnpaddedSize(node, padding, ite) {
  return padding === 0
    ? node.size
    : node.size - padding * (ite ? ite.countLeaves() : flat.countLeaves(node.index))
}

function unslabNodes(nodes) {
  for (const node of nodes) unslabNode(node)
  return nodes
}

function unslabNode(node) {
  if (node === null) return node
  node.hash = unslab(node.hash)
  return node
}
const c = require('compact-encoding')
const { DEFAULT_NAMESPACE } = require('./caps')
const { INVALID_OPLOG_VERSION } = require('hypercore-errors')
const unslab = require('unslab')

const MANIFEST_PATCH = 0b00000001
const MANIFEST_PROLOGUE = 0b00000010
const MANIFEST_LINKED = 0b00000100
const MANIFEST_USER_DATA = 0b00001000

const hashes = {
  preencode(state, m) {
    state.end++ // small uint
  },
  encode(state, m) {
    if (m === 'blake2b') {
      c.uint.encode(state, 0)
      return
    }

    throw new Error('Unknown hash: ' + m)
  },
  decode(state) {
    const n = c.uint.decode(state)
    if (n === 0) return 'blake2b'
    throw new Error('Unknown hash id: ' + n)
  }
}

const signatures = {
  preencode(state, m) {
    state.end++ // small uint
  },
  encode(state, m) {
    if (m === 'ed25519') {
      c.uint.encode(state, 0)
      return
    }

    throw new Error('Unknown signature: ' + m)
  },
  decode(state) {
    const n = c.uint.decode(state)
    if (n === 0) return 'ed25519'
    throw new Error('Unknown signature id: ' + n)
  }
}

const signer = {
  preencode(state, m) {
    signatures.preencode(state, m.signature)
    c.fixed32.preencode(state, m.namespace)
    c.fixed32.preencode(state, m.publicKey)
  },
  encode(state, m) {
    signatures.encode(state, m.signature)
    c.fixed32.encode(state, m.namespace)
    c.fixed32.encode(state, m.publicKey)
  },
  decode(state) {
    return {
      signature: signatures.decode(state),
      namespace: c.fixed32.decode(state),
      publicKey: c.fixed32.decode(state)
    }
  }
}

const signerArray = c.array(signer)

const prologue = {
  preencode(state, p) {
    c.fixed32.preencode(state, p.hash)
    c.uint.preencode(state, p.length)
  },
  encode(state, p) {
    c.fixed32.encode(state, p.hash)
    c.uint.encode(state, p.length)
  },
  decode(state) {
    return {
      hash: c.fixed32.decode(state),
      length: c.uint.decode(state)
    }
  }
}

const manifestv0 = {
  preencode(state, m) {
    hashes.preencode(state, m.hash)
    state.end++ // type

    if (m.prologue && m.signers.length === 0) {
      c.fixed32.preencode(state, m.prologue.hash)
      return
    }

    if (m.quorum === 1 && m.signers.length === 1 && !m.allowPatch) {
      signer.preencode(state, m.signers[0])
    } else {
      state.end++ // flags
      c.uint.preencode(state, m.quorum)
      signerArray.preencode(state, m.signers)
    }
  },
  encode(state, m) {
    hashes.encode(state, m.hash)

    if (m.prologue && m.signers.length === 0) {
      c.uint.encode(state, 0)
      c.fixed32.encode(state, m.prologue.hash)
      return
    }

    if (m.quorum === 1 && m.signers.length === 1 && !m.allowPatch) {
      c.uint.encode(state, 1)
      signer.encode(state, m.signers[0])
    } else {
      c.uint.encode(state, 2)
      c.uint.encode(state, m.allowPatch ? 1 : 0)
      c.uint.encode(state, m.quorum)
      signerArray.encode(state, m.signers)
    }
  },
  decode(state) {
    const hash = hashes.decode(state)
    const type = c.uint.decode(state)

    if (type > 2) throw new Error('Unknown type: ' + type)

    if (type === 0) {
      return {
        version: 0,
        hash,
        allowPatch: false,
        quorum: 0,
        signers: [],
        prologue: {
          hash: c.fixed32.decode(state),
          length: 0
        },
        linked: null,
        userData: null
      }
    }

    if (type === 1) {
      return {
        version: 0,
        hash,
        allowPatch: false,
        quorum: 1,
        signers: [signer.decode(state)],
        prologue: null,
        linked: null,
        userData: null
      }
    }

    const flags = c.uint.decode(state)

    return {
      version: 0,
      hash,
      allowPatch: (flags & 1) !== 0,
      quorum: c.uint.decode(state),
      signers: signerArray.decode(state),
      prologue: null,
      linked: null,
      userData: null
    }
  }
}

const fixed32Array = c.array(c.fixed32)

const manifest = (exports.manifest = {
  preencode(state, m) {
    state.end++ // version

    if (m.version === 0) return manifestv0.preencode(state, m)

    state.end++ // flags
    hashes.preencode(state, m.hash)

    c.uint.preencode(state, m.quorum)
    signerArray.preencode(state, m.signers)

    if (m.prologue) prologue.preencode(state, m.prologue)
    if (m.linked) fixed32Array.preencode(state, m.linked)
    if (m.userData) c.buffer.preencode(state, m.userData)
  },
  encode(state, m) {
    c.uint.encode(state, m.version)

    if (m.version === 0) return manifestv0.encode(state, m)

    let flags = 0
    if (m.allowPatch) flags |= MANIFEST_PATCH
    if (m.prologue) flags |= MANIFEST_PROLOGUE
    if (m.linked) flags |= MANIFEST_LINKED
    if (m.userData) flags |= MANIFEST_USER_DATA

    c.uint.encode(state, flags)
    hashes.encode(state, m.hash)

    c.uint.encode(state, m.quorum)
    signerArray.encode(state, m.signers)

    if (m.prologue) prologue.encode(state, m.prologue)
    if (m.linked) fixed32Array.encode(state, m.linked)
    if (m.userData) c.buffer.encode(state, m.userData)
  },
  decode(state) {
    const version = c.uint.decode(state)

    if (version === 0) return manifestv0.decode(state)
    if (version > 2) throw new Error('Unknown version: ' + version)

    const flags = c.uint.decode(state)
    const hash = hashes.decode(state)
    const quorum = c.uint.decode(state)
    const signers = signerArray.decode(state)

    const hasPatch = (flags & MANIFEST_PATCH) !== 0
    const hasPrologue = (flags & MANIFEST_PROLOGUE) !== 0
    const hasLinked = (flags & MANIFEST_LINKED) !== 0
    const hasUserData = (flags & MANIFEST_USER_DATA) !== 0

    return {
      version,
      hash,
      allowPatch: hasPatch,
      quorum,
      signers,
      prologue: hasPrologue ? prologue.decode(state) : null,
      linked: hasLinked ? fixed32Array.decode(state) : null,
      userData: hasUserData ? c.buffer.decode(state) : null
    }
  }
})

const node = {
  preencode(state, n) {
    c.uint.preencode(state, n.index)
    c.uint.preencode(state, n.size)
    c.fixed32.preencode(state, n.hash)
  },
  encode(state, n) {
    c.uint.encode(state, n.index)
    c.uint.encode(state, n.size)
    c.fixed32.encode(state, n.hash)
  },
  decode(state) {
    return {
      index: c.uint.decode(state),
      size: c.uint.decode(state),
      hash: c.fixed32.decode(state)
    }
  }
}

const nodeArray = c.array(node)

const wire = (exports.wire = {})

wire.handshake = {
  preencode(state, m) {
    c.uint.preencode(state, 1)
    c.fixed32.preencode(state, m.capability)
  },
  encode(state, m) {
    c.uint.encode(state, m.seeks ? 1 : 0)
    c.fixed32.encode(state, m.capability)
  },
  decode(state) {
    const flags = c.uint.decode(state)
    return {
      seeks: (flags & 1) !== 0,
      capability: unslab(c.fixed32.decode(state))
    }
  }
}

const requestBlock = {
  preencode(state, b) {
    c.uint.preencode(state, b.index)
    c.uint.preencode(state, b.nodes)
  },
  encode(state, b) {
    c.uint.encode(state, b.index)
    c.uint.encode(state, b.nodes)
  },
  decode(state) {
    return {
      index: c.uint.decode(state),
      nodes: c.uint.decode(state)
    }
  }
}

const requestSeek = {
  preencode(state, s) {
    c.uint.preencode(state, s.bytes)
    c.uint.preencode(state, s.padding)
  },
  encode(state, s) {
    c.uint.encode(state, s.bytes)
    c.uint.encode(state, s.padding)
  },
  decode(state) {
    return {
      bytes: c.uint.decode(state),
      padding: c.uint.decode(state)
    }
  }
}

const requestUpgrade = {
  preencode(state, u) {
    c.uint.preencode(state, u.start)
    c.uint.preencode(state, u.length)
  },
  encode(state, u) {
    c.uint.encode(state, u.start)
    c.uint.encode(state, u.length)
  },
  decode(state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

wire.request = {
  preencode(state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.id)
    c.uint.preencode(state, m.fork)

    if (m.block) requestBlock.preencode(state, m.block)
    if (m.hash) requestBlock.preencode(state, m.hash)
    if (m.seek) requestSeek.preencode(state, m.seek)
    if (m.upgrade) requestUpgrade.preencode(state, m.upgrade)
    if (m.priority) c.uint.preencode(state, m.priority)
  },
  encode(state, m) {
    const flags =
      (m.block ? 1 : 0) |
      (m.hash ? 2 : 0) |
      (m.seek ? 4 : 0) |
      (m.upgrade ? 8 : 0) |
      (m.manifest ? 16 : 0) |
      (m.priority ? 32 : 0)

    c.uint.encode(state, flags)
    c.uint.encode(state, m.id)
    c.uint.encode(state, m.fork)

    if (m.block) requestBlock.encode(state, m.block)
    if (m.hash) requestBlock.encode(state, m.hash)
    if (m.seek) requestSeek.encode(state, m.seek)
    if (m.upgrade) requestUpgrade.encode(state, m.upgrade)
    if (m.priority) c.uint.encode(state, m.priority)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      id: c.uint.decode(state),
      fork: c.uint.decode(state),
      block: flags & 1 ? requestBlock.decode(state) : null,
      hash: flags & 2 ? requestBlock.decode(state) : null,
      seek: flags & 4 ? requestSeek.decode(state) : null,
      upgrade: flags & 8 ? requestUpgrade.decode(state) : null,
      manifest: (flags & 16) !== 0,
      priority: flags & 32 ? c.uint.decode(state) : 0
    }
  }
}

wire.cancel = {
  preencode(state, m) {
    c.uint.preencode(state, m.request)
  },
  encode(state, m) {
    c.uint.encode(state, m.request)
  },
  decode(state, m) {
    return {
      request: c.uint.decode(state)
    }
  }
}

const dataUpgrade = {
  preencode(state, u) {
    c.uint.preencode(state, u.start)
    c.uint.preencode(state, u.length)
    nodeArray.preencode(state, u.nodes)
    nodeArray.preencode(state, u.additionalNodes)
    c.optionalBuffer.preencode(state, u.signature)
  },
  encode(state, u) {
    c.uint.encode(state, u.start)
    c.uint.encode(state, u.length)
    nodeArray.encode(state, u.nodes)
    nodeArray.encode(state, u.additionalNodes)
    c.optionalBuffer.encode(state, u.signature)
  },
  decode(state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state),
      nodes: nodeArray.decode(state),
      additionalNodes: nodeArray.decode(state),
      signature: c.optionalBuffer.decode(state)
    }
  }
}

const dataSeek = {
  preencode(state, s) {
    c.uint.preencode(state, s.bytes)
    nodeArray.preencode(state, s.nodes)
  },
  encode(state, s) {
    c.uint.encode(state, s.bytes)
    nodeArray.encode(state, s.nodes)
  },
  decode(state) {
    return {
      bytes: c.uint.decode(state),
      nodes: nodeArray.decode(state)
    }
  }
}

const dataBlock = {
  preencode(state, b) {
    c.uint.preencode(state, b.index)
    c.buffer.preencode(state, b.value)
    nodeArray.preencode(state, b.nodes)
  },
  encode(state, b) {
    c.uint.encode(state, b.index)
    c.buffer.encode(state, b.value)
    nodeArray.encode(state, b.nodes)
  },
  decode(state) {
    return {
      index: c.uint.decode(state),
      value: c.buffer.decode(state),
      nodes: nodeArray.decode(state)
    }
  }
}

const dataHash = {
  preencode(state, b) {
    c.uint.preencode(state, b.index)
    nodeArray.preencode(state, b.nodes)
  },
  encode(state, b) {
    c.uint.encode(state, b.index)
    nodeArray.encode(state, b.nodes)
  },
  decode(state) {
    return {
      index: c.uint.decode(state),
      nodes: nodeArray.decode(state)
    }
  }
}

wire.data = {
  preencode(state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.request)
    c.uint.preencode(state, m.fork)

    if (m.block) dataBlock.preencode(state, m.block)
    if (m.hash) dataHash.preencode(state, m.hash)
    if (m.seek) dataSeek.preencode(state, m.seek)
    if (m.upgrade) dataUpgrade.preencode(state, m.upgrade)
    if (m.manifest) manifest.preencode(state, m.manifest)
  },
  encode(state, m) {
    const flags =
      (m.block ? 1 : 0) |
      (m.hash ? 2 : 0) |
      (m.seek ? 4 : 0) |
      (m.upgrade ? 8 : 0) |
      (m.manifest ? 16 : 0)

    c.uint.encode(state, flags)
    c.uint.encode(state, m.request)
    c.uint.encode(state, m.fork)

    if (m.block) dataBlock.encode(state, m.block)
    if (m.hash) dataHash.encode(state, m.hash)
    if (m.seek) dataSeek.encode(state, m.seek)
    if (m.upgrade) dataUpgrade.encode(state, m.upgrade)
    if (m.manifest) manifest.encode(state, m.manifest)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      request: c.uint.decode(state),
      fork: c.uint.decode(state),
      block: flags & 1 ? dataBlock.decode(state) : null,
      hash: flags & 2 ? dataHash.decode(state) : null,
      seek: flags & 4 ? dataSeek.decode(state) : null,
      upgrade: flags & 8 ? dataUpgrade.decode(state) : null,
      manifest: flags & 16 ? manifest.decode(state) : null
    }
  }
}

wire.noData = {
  preencode(state, m) {
    c.uint.preencode(state, m.request)
    c.uint.preencode(state, m.reason ? 1 : 0)
    if (m.reason) c.uint.preencode(state, m.reason)
  },
  encode(state, m) {
    c.uint.encode(state, m.request)
    c.uint.encode(state, m.reason ? 1 : 0)
    if (m.reason) c.uint.encode(state, m.reason)
  },
  decode(state, m) {
    const request = c.uint.decode(state)
    const flags = state.start < state.end ? c.uint.decode(state) : 0
    return {
      request,
      reason: flags & 1 ? c.uint.decode(state) : 0
    }
  }
}

// TODO: we should move to having these have a handle like in data, easier since they
// allocate state in practice
wire.want = {
  preencode(state, m) {
    c.uint.preencode(state, m.start)
    c.uint.preencode(state, m.length)

    const flags = m.any ? 1 : 0
    if (flags !== 0) c.uint.preencode(state, flags)
  },
  encode(state, m) {
    c.uint.encode(state, m.start)
    c.uint.encode(state, m.length)

    const flags = m.any ? 1 : 0
    if (flags !== 0) c.uint.encode(state, flags)
  },
  decode(state) {
    const start = c.uint.decode(state)
    const length = c.uint.decode(state)
    const flags = state.start < state.end ? c.uint.decode(state) : 0

    return {
      start,
      length,
      any: (flags & 1) !== 0
    }
  }
}

wire.unwant = {
  preencode(state, m) {
    c.uint.preencode(state, m.start)
    c.uint.preencode(state, m.length)

    const flags = m.any ? 1 : 0
    if (flags !== 0) c.uint.preencode(state, flags)
  },
  encode(state, m) {
    c.uint.encode(state, m.start)
    c.uint.encode(state, m.length)

    const flags = m.any ? 1 : 0
    if (flags !== 0) c.uint.encode(state, flags)
  },
  decode(state, m) {
    const start = c.uint.decode(state)
    const length = c.uint.decode(state)
    const flags = state.start < state.end ? c.uint.decode(state) : 0

    return {
      start,
      length,
      any: (flags & 1) !== 0
    }
  }
}

wire.range = {
  preencode(state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.start)
    if (m.length !== 1) c.uint.preencode(state, m.length)
  },
  encode(state, m) {
    c.uint.encode(state, (m.drop ? 1 : 0) | (m.length === 1 ? 2 : 0))
    c.uint.encode(state, m.start)
    if (m.length !== 1) c.uint.encode(state, m.length)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      drop: (flags & 1) !== 0,
      start: c.uint.decode(state),
      length: (flags & 2) !== 0 ? 1 : c.uint.decode(state)
    }
  }
}

wire.bitfield = {
  preencode(state, m) {
    c.uint.preencode(state, m.start)
    c.uint32array.preencode(state, m.bitfield)
  },
  encode(state, m) {
    c.uint.encode(state, m.start)
    c.uint32array.encode(state, m.bitfield)
  },
  decode(state, m) {
    return {
      start: c.uint.decode(state),
      bitfield: c.uint32array.decode(state)
    }
  }
}

wire.sync = {
  preencode(state, m) {
    state.end++ // flags
    c.uint.preencode(state, m.fork)
    c.uint.preencode(state, m.length)
    c.uint.preencode(state, m.remoteLength)
  },
  encode(state, m) {
    c.uint.encode(
      state,
      (m.canUpgrade ? 1 : 0) |
        (m.uploading ? 2 : 0) |
        (m.downloading ? 4 : 0) |
        (m.hasManifest ? 8 : 0) |
        (m.allowPush ? 16 : 0)
    )
    c.uint.encode(state, m.fork)
    c.uint.encode(state, m.length)
    c.uint.encode(state, m.remoteLength)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      fork: c.uint.decode(state),
      length: c.uint.decode(state),
      remoteLength: c.uint.decode(state),
      canUpgrade: (flags & 1) !== 0,
      uploading: (flags & 2) !== 0,
      downloading: (flags & 4) !== 0,
      hasManifest: (flags & 8) !== 0,
      allowPush: (flags & 16) !== 0
    }
  }
}

wire.reorgHint = {
  preencode(state, m) {
    c.uint.preencode(state, m.from)
    c.uint.preencode(state, m.to)
    c.uint.preencode(state, m.ancestors)
  },
  encode(state, m) {
    c.uint.encode(state, m.from)
    c.uint.encode(state, m.to)
    c.uint.encode(state, m.ancestors)
  },
  decode(state) {
    return {
      from: c.uint.decode(state),
      to: c.uint.decode(state),
      ancestors: c.uint.decode(state)
    }
  }
}

wire.extension = {
  preencode(state, m) {
    c.string.preencode(state, m.name)
    c.raw.preencode(state, m.message)
  },
  encode(state, m) {
    c.string.encode(state, m.name)
    c.raw.encode(state, m.message)
  },
  decode(state) {
    return {
      name: c.string.decode(state),
      message: c.raw.decode(state)
    }
  }
}

const keyValue = {
  preencode(state, p) {
    c.string.preencode(state, p.key)
    c.buffer.preencode(state, p.value)
  },
  encode(state, p) {
    c.string.encode(state, p.key)
    c.buffer.encode(state, p.value)
  },
  decode(state) {
    return {
      key: c.string.decode(state),
      value: c.buffer.decode(state)
    }
  }
}

const treeUpgrade = {
  preencode(state, u) {
    c.uint.preencode(state, u.fork)
    c.uint.preencode(state, u.ancestors)
    c.uint.preencode(state, u.length)
    c.buffer.preencode(state, u.signature)
  },
  encode(state, u) {
    c.uint.encode(state, u.fork)
    c.uint.encode(state, u.ancestors)
    c.uint.encode(state, u.length)
    c.buffer.encode(state, u.signature)
  },
  decode(state) {
    return {
      fork: c.uint.decode(state),
      ancestors: c.uint.decode(state),
      length: c.uint.decode(state),
      signature: c.buffer.decode(state)
    }
  }
}

const bitfieldUpdate = {
  // TODO: can maybe be folded into a HAVE later on with the most recent spec
  preencode(state, b) {
    state.end++ // flags
    c.uint.preencode(state, b.start)
    c.uint.preencode(state, b.length)
  },
  encode(state, b) {
    state.buffer[state.start++] = b.drop ? 1 : 0
    c.uint.encode(state, b.start)
    c.uint.encode(state, b.length)
  },
  decode(state) {
    const flags = c.uint.decode(state)
    return {
      drop: (flags & 1) !== 0,
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

const oplog = (exports.oplog = {})

oplog.entry = {
  preencode(state, m) {
    state.end++ // flags
    if (m.userData) keyValue.preencode(state, m.userData)
    if (m.treeNodes) nodeArray.preencode(state, m.treeNodes)
    if (m.treeUpgrade) treeUpgrade.preencode(state, m.treeUpgrade)
    if (m.bitfield) bitfieldUpdate.preencode(state, m.bitfield)
  },
  encode(state, m) {
    const s = state.start++
    let flags = 0

    if (m.userData) {
      flags |= 1
      keyValue.encode(state, m.userData)
    }
    if (m.treeNodes) {
      flags |= 2
      nodeArray.encode(state, m.treeNodes)
    }
    if (m.treeUpgrade) {
      flags |= 4
      treeUpgrade.encode(state, m.treeUpgrade)
    }
    if (m.bitfield) {
      flags |= 8
      bitfieldUpdate.encode(state, m.bitfield)
    }

    state.buffer[s] = flags
  },
  decode(state) {
    const flags = c.uint.decode(state)
    return {
      userData: (flags & 1) !== 0 ? keyValue.decode(state) : null,
      treeNodes: (flags & 2) !== 0 ? nodeArray.decode(state) : null,
      treeUpgrade: (flags & 4) !== 0 ? treeUpgrade.decode(state) : null,
      bitfield: (flags & 8) !== 0 ? bitfieldUpdate.decode(state) : null
    }
  }
}

const keyPair = {
  preencode(state, kp) {
    c.buffer.preencode(state, kp.publicKey)
    c.buffer.preencode(state, kp.secretKey)
  },
  encode(state, kp) {
    c.buffer.encode(state, kp.publicKey)
    c.buffer.encode(state, kp.secretKey)
  },
  decode(state) {
    return {
      publicKey: c.buffer.decode(state),
      secretKey: c.buffer.decode(state)
    }
  }
}

const reorgHint = {
  preencode(state, r) {
    c.uint.preencode(state, r.from)
    c.uint.preencode(state, r.to)
    c.uint.preencode(state, r.ancestors)
  },
  encode(state, r) {
    c.uint.encode(state, r.from)
    c.uint.encode(state, r.to)
    c.uint.encode(state, r.ancestors)
  },
  decode(state) {
    return {
      from: c.uint.decode(state),
      to: c.uint.decode(state),
      ancestors: c.uint.decode(state)
    }
  }
}

const reorgHintArray = c.array(reorgHint)

const hints = {
  preencode(state, h) {
    reorgHintArray.preencode(state, h.reorgs)
    c.uint.preencode(state, h.contiguousLength)
  },
  encode(state, h) {
    reorgHintArray.encode(state, h.reorgs)
    c.uint.encode(state, h.contiguousLength)
  },
  decode(state) {
    return {
      reorgs: reorgHintArray.decode(state),
      contiguousLength: state.start < state.end ? c.uint.decode(state) : 0
    }
  }
}

const treeHeader = {
  preencode(state, t) {
    c.uint.preencode(state, t.fork)
    c.uint.preencode(state, t.length)
    c.buffer.preencode(state, t.rootHash)
    c.buffer.preencode(state, t.signature)
  },
  encode(state, t) {
    c.uint.encode(state, t.fork)
    c.uint.encode(state, t.length)
    c.buffer.encode(state, t.rootHash)
    c.buffer.encode(state, t.signature)
  },
  decode(state) {
    return {
      fork: c.uint.decode(state),
      length: c.uint.decode(state),
      rootHash: c.buffer.decode(state),
      signature: c.buffer.decode(state)
    }
  }
}

const types = {
  preencode(state, t) {
    c.string.preencode(state, t.tree)
    c.string.preencode(state, t.bitfield)
    c.string.preencode(state, t.signer)
  },
  encode(state, t) {
    c.string.encode(state, t.tree)
    c.string.encode(state, t.bitfield)
    c.string.encode(state, t.signer)
  },
  decode(state) {
    return {
      tree: c.string.decode(state),
      bitfield: c.string.decode(state),
      signer: c.string.decode(state)
    }
  }
}

const externalHeader = {
  preencode(state, m) {
    c.uint.preencode(state, m.start)
    c.uint.preencode(state, m.length)
  },
  encode(state, m) {
    c.uint.encode(state, m.start)
    c.uint.encode(state, m.length)
  },
  decode(state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state)
    }
  }
}

const keyValueArray = c.array(keyValue)

oplog.header = {
  preencode(state, h) {
    state.end += 2 // version + flags
    if (h.external) {
      externalHeader.preencode(state, h.external)
      return
    }
    c.fixed32.preencode(state, h.key)
    if (h.manifest) manifest.preencode(state, h.manifest)
    if (h.keyPair) keyPair.preencode(state, h.keyPair)
    keyValueArray.preencode(state, h.userData)
    treeHeader.preencode(state, h.tree)
    hints.preencode(state, h.hints)
  },
  encode(state, h) {
    c.uint.encode(state, 1)
    if (h.external) {
      c.uint.encode(state, 1) // ONLY set the first big for clarity
      externalHeader.encode(state, h.external)
      return
    }
    c.uint.encode(state, (h.manifest ? 2 : 0) | (h.keyPair ? 4 : 0))
    c.fixed32.encode(state, h.key)
    if (h.manifest) manifest.encode(state, h.manifest)
    if (h.keyPair) keyPair.encode(state, h.keyPair)
    keyValueArray.encode(state, h.userData)
    treeHeader.encode(state, h.tree)
    hints.encode(state, h.hints)
  },
  decode(state) {
    const version = c.uint.decode(state)

    if (version > 1) {
      throw INVALID_OPLOG_VERSION('Invalid header version. Expected <= 1, got ' + version)
    }

    if (version === 0) {
      const old = {
        types: types.decode(state),
        userData: keyValueArray.decode(state),
        tree: treeHeader.decode(state),
        signer: keyPair.decode(state),
        hints: hints.decode(state)
      }

      return {
        external: null,
        key: old.signer.publicKey,
        manifest: {
          version: 0,
          hash: old.types.tree,
          allowPatch: false,
          quorum: 1,
          signers: [
            {
              signature: old.types.signer,
              namespace: DEFAULT_NAMESPACE,
              publicKey: old.signer.publicKey
            }
          ],
          prologue: null,
          linked: null,
          userData: null
        },
        keyPair: old.signer.secretKey ? old.signer : null,
        userData: old.userData,
        tree: old.tree,
        hints: old.hints
      }
    }

    const flags = c.uint.decode(state)

    if (flags & 1) {
      return {
        external: externalHeader.decode(state),
        key: null,
        manifest: null,
        keyPair: null,
        userData: null,
        tree: null,
        hints: null
      }
    }

    return {
      external: null,
      key: c.fixed32.decode(state),
      manifest: (flags & 2) !== 0 ? manifest.decode(state) : null,
      keyPair: (flags & 4) !== 0 ? keyPair.decode(state) : null,
      userData: keyValueArray.decode(state),
      tree: treeHeader.decode(state),
      hints: hints.decode(state)
    }
  }
}

const uintArray = c.array(c.uint)

const multisigInput = {
  preencode(state, inp) {
    c.uint.preencode(state, inp.signer)
    c.fixed64.preencode(state, inp.signature)
    c.uint.preencode(state, inp.patch)
  },
  encode(state, inp) {
    c.uint.encode(state, inp.signer)
    c.fixed64.encode(state, inp.signature)
    c.uint.encode(state, inp.patch)
  },
  decode(state) {
    return {
      signer: c.uint.decode(state),
      signature: c.fixed64.decode(state),
      patch: c.uint.decode(state)
    }
  }
}

const patchEncodingv0 = {
  preencode(state, n) {
    c.uint.preencode(state, n.start)
    c.uint.preencode(state, n.length)
    uintArray.preencode(state, n.nodes)
  },
  encode(state, n) {
    c.uint.encode(state, n.start)
    c.uint.encode(state, n.length)
    uintArray.encode(state, n.nodes)
  },
  decode(state) {
    return {
      start: c.uint.decode(state),
      length: c.uint.decode(state),
      nodes: uintArray.decode(state)
    }
  }
}

const multisigInputv0 = {
  preencode(state, n) {
    state.end++
    c.uint.preencode(state, n.signer)
    c.fixed64.preencode(state, n.signature)
    if (n.patch) patchEncodingv0.preencode(state, n.patch)
  },
  encode(state, n) {
    c.uint.encode(state, n.patch ? 1 : 0)
    c.uint.encode(state, n.signer)
    c.fixed64.encode(state, n.signature)
    if (n.patch) patchEncodingv0.encode(state, n.patch)
  },
  decode(state) {
    const flags = c.uint.decode(state)
    return {
      signer: c.uint.decode(state),
      signature: c.fixed64.decode(state),
      patch: flags & 1 ? patchEncodingv0.decode(state) : null
    }
  }
}

const multisigInputArrayv0 = c.array(multisigInputv0)
const multisigInputArray = c.array(multisigInput)

const compactNode = {
  preencode(state, n) {
    c.uint.preencode(state, n.index)
    c.uint.preencode(state, n.size)
    c.fixed32.preencode(state, n.hash)
  },
  encode(state, n) {
    c.uint.encode(state, n.index)
    c.uint.encode(state, n.size)
    c.fixed32.encode(state, n.hash)
  },
  decode(state) {
    return {
      index: c.uint.decode(state),
      size: c.uint.decode(state),
      hash: c.fixed32.decode(state)
    }
  }
}

const compactNodeArray = c.array(compactNode)

exports.multiSignaturev0 = {
  preencode(state, s) {
    multisigInputArrayv0.preencode(state, s.proofs)
    compactNodeArray.preencode(state, s.patch)
  },
  encode(state, s) {
    multisigInputArrayv0.encode(state, s.proofs)
    compactNodeArray.encode(state, s.patch)
  },
  decode(state) {
    return {
      proofs: multisigInputArrayv0.decode(state),
      patch: compactNodeArray.decode(state)
    }
  }
}

exports.multiSignature = {
  preencode(state, s) {
    multisigInputArray.preencode(state, s.proofs)
    compactNodeArray.preencode(state, s.patch)
  },
  encode(state, s) {
    multisigInputArray.encode(state, s.proofs)
    compactNodeArray.encode(state, s.patch)
  },
  decode(state) {
    return {
      proofs: multisigInputArray.decode(state),
      patch: compactNodeArray.decode(state)
    }
  }
}
const c = require('compact-encoding')
const b4a = require('b4a')
const flat = require('flat-tree')
const { MerkleTree } = require('./merkle-tree')
const { multiSignature, multiSignaturev0 } = require('./messages')

module.exports = {
  assemblev0,
  assemble,
  inflatev0,
  inflate,
  partialSignature,
  signableLength
}

function inflatev0(data) {
  return c.decode(multiSignaturev0, data)
}

function inflate(data) {
  return c.decode(multiSignature, data)
}

async function partialSignature(
  core,
  signer,
  from,
  to = core.state.length,
  signature = core.state.signature
) {
  if (from > core.state.length) return null
  const nodes = to <= from ? null : await upgradeNodes(core, from, to)

  if (signature.byteLength !== 64) {
    signature = c.decode(multiSignature, signature).proofs[0].signature
  }

  return {
    signer,
    signature,
    patch: nodes ? to - from : 0,
    nodes
  }
}

async function upgradeNodes(core, from, to) {
  const rx = core.state.storage.read()
  let p = null
  try {
    p = await MerkleTree.proof(core.state, rx, { upgrade: { start: from, length: to - from } })
  } catch (err) {
    rx.destroy()
    throw err
  }
  rx.tryFlush()
  return (await p.settle()).upgrade.nodes
}

function signableLength(lengths, quorum) {
  if (quorum <= 0) quorum = 1
  if (quorum > lengths.length) return 0

  return lengths.sort(cmp)[quorum - 1]
}

function cmp(a, b) {
  return b - a
}

function assemblev0(inputs) {
  const proofs = []
  const patch = []

  for (const u of inputs) {
    proofs.push(compressProof(u, patch))
  }

  return c.encode(multiSignaturev0, { proofs, patch })
}

function assemble(inputs) {
  const proofs = []
  const patch = []
  const seen = new Set()

  for (const u of inputs) {
    if (u.nodes) {
      for (const node of u.nodes) {
        if (seen.has(node.index)) continue
        seen.add(node.index)
        patch.push(node)
      }
    }

    proofs.push({
      signer: u.signer,
      signature: u.signature,
      patch: u.patch
    })
  }

  return c.encode(multiSignature, { proofs, patch })
}

function compareNode(a, b) {
  if (a.index !== b.index) return false
  if (a.size !== b.size) return false
  return b4a.equals(a.hash, b.hash)
}

function compressProof(proof, nodes) {
  return {
    signer: proof.signer,
    signature: proof.signature,
    patch: proof.patch ? compressUpgrade(proof, nodes) : null
  }
}

function compressUpgrade(p, nodes) {
  const u = {
    start: flat.rightSpan(p.nodes[p.nodes.length - 1].index) / 2 + 1,
    length: p.patch,
    nodes: []
  }

  for (const node of p.nodes) {
    let present = false
    for (let i = 0; i < nodes.length; i++) {
      if (!compareNode(nodes[i], node)) continue

      u.nodes.push(i)
      present = true
      break
    }

    if (present) continue
    u.nodes.push(nodes.push(node) - 1)
  }

  return u
}
module.exports = class Mutex {
  constructor() {
    this.locked = false
    this.destroyed = false

    this._destroying = null
    this._destroyError = null
    this._queue = []
    this._enqueue = (resolve, reject) => this._queue.push([resolve, reject])
  }

  idle() {
    return this._queue.length === 0 && this.locked === false
  }

  lock() {
    if (this.destroyed) {
      return Promise.reject(this._destroyError || new Error('Mutex has been destroyed'))
    }
    if (this.locked) return new Promise(this._enqueue)
    this.locked = true
    return Promise.resolve()
  }

  unlock() {
    if (!this._queue.length) {
      this.locked = false
      return
    }
    this._queue.shift()[0]()
  }

  destroy(err) {
    if (!this._destroying) {
      this._destroying = this.locked ? this.lock().catch(() => {}) : Promise.resolve()
    }

    this.destroyed = true
    if (err) this._destroyError = err

    if (err) {
      while (this._queue.length) this._queue.shift()[1](err)
    }

    return this._destroying
  }
}
const FIFO = require('fast-fifo')

module.exports = class ReceiverQueue {
  constructor() {
    this.queue = new FIFO()
    this.priority = []
    this.requests = new Map()
    this.length = 0
  }

  push(req) {
    // TODO: use a heap at some point if we wanna support multiple prios
    if (req.priority > 0) this.priority.push(req)
    else this.queue.push(req)

    this.requests.set(req.id, req)
    this.length++
  }

  shift() {
    while (this.priority.length > 0) {
      const msg = this.priority.pop()
      const req = this._processRequest(msg)
      if (req !== null) return req
    }

    while (this.queue.length > 0) {
      const msg = this.queue.shift()
      const req = this._processRequest(msg)
      if (req !== null) return req
    }

    return null
  }

  _processRequest(req) {
    if (req.block || req.hash || req.seek || req.upgrade || req.manifest) {
      this.requests.delete(req.id)
      this.length--
      return req
    }

    return null
  }

  clear() {
    this.queue.clear()
    this.priority = []
    this.length = 0
    this.requests.clear()
  }

  delete(id) {
    const req = this.requests.get(id)
    if (!req) return

    req.block = null
    req.hash = null
    req.seek = null
    req.upgrade = null
    req.manifest = false

    this.requests.delete(id)
    this.length--

    if (this.length === 0) {
      this.queue.clear()
      this.priority = []
    }
  }
}
const BigSparseArray = require('big-sparse-array')
const quickbit = require('./compat').quickbit

const BITS_PER_PAGE = 32768
const BYTES_PER_PAGE = BITS_PER_PAGE / 8
const WORDS_PER_PAGE = BYTES_PER_PAGE / 4
const BITS_PER_SEGMENT = 2097152
const BYTES_PER_SEGMENT = BITS_PER_SEGMENT / 8
const PAGES_PER_SEGMENT = BITS_PER_SEGMENT / BITS_PER_PAGE

class RemoteBitfieldPage {
  constructor(index, bitfield, segment) {
    this.index = index
    this.offset = index * BYTES_PER_PAGE - segment.offset
    this.bitfield = bitfield
    this.segment = segment

    segment.add(this)
  }

  get tree() {
    return this.segment.tree
  }

  get(index) {
    return quickbit.get(this.bitfield, index)
  }

  set(index, val) {
    if (quickbit.set(this.bitfield, index, val)) {
      this.tree.update(this.offset * 8 + index)
    }
  }

  setRange(start, end, val) {
    quickbit.fill(this.bitfield, val, start, end)

    let i = Math.floor(start / 128)
    const n = i + Math.ceil((end - start) / 128)

    while (i <= n) this.tree.update(this.offset * 8 + i++ * 128)
  }

  findFirst(val, position) {
    return quickbit.findFirst(this.bitfield, val, position)
  }

  findLast(val, position) {
    return quickbit.findLast(this.bitfield, val, position)
  }

  insert(start, bitfield) {
    this.bitfield.set(bitfield, start / 32)
    this.segment.refresh()
  }

  clear(start, bitfield) {
    quickbit.clear(this.bitfield, { field: bitfield, offset: start })
  }
}

class RemoteBitfieldSegment {
  constructor(index) {
    this.index = index
    this.offset = index * BYTES_PER_SEGMENT
    this.tree = quickbit.Index.from([], BYTES_PER_SEGMENT)
    this.pages = new Array(PAGES_PER_SEGMENT)
    this.pagesLength = 0
  }

  get chunks() {
    return this.tree.chunks
  }

  refresh() {
    this.tree = quickbit.Index.from(this.tree.chunks, BYTES_PER_SEGMENT)
  }

  add(page) {
    const pageIndex = page.index - this.index * PAGES_PER_SEGMENT
    if (pageIndex >= this.pagesLength) this.pagesLength = pageIndex + 1

    this.pages[pageIndex] = page

    const chunk = { field: page.bitfield, offset: page.offset }

    this.chunks.push(chunk)

    for (let i = this.chunks.length - 2; i >= 0; i--) {
      const prev = this.chunks[i]
      if (prev.offset <= chunk.offset) break
      this.chunks[i] = chunk
      this.chunks[i + 1] = prev
    }
  }

  findFirst(val, position) {
    position = this.tree.skipFirst(!val, position)

    let j = position & (BITS_PER_PAGE - 1)
    let i = (position - j) / BITS_PER_PAGE

    if (i >= PAGES_PER_SEGMENT) return -1

    while (i < this.pagesLength) {
      const p = this.pages[i]

      let index = -1

      if (p) index = p.findFirst(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_PAGE + index

      j = 0
      i++
    }

    return val || this.pagesLength === PAGES_PER_SEGMENT ? -1 : this.pagesLength * BITS_PER_PAGE
  }

  findLast(val, position) {
    position = this.tree.skipLast(!val, position)

    let j = position & (BITS_PER_PAGE - 1)
    let i = (position - j) / BITS_PER_PAGE

    if (i >= PAGES_PER_SEGMENT) return -1

    while (i >= 0) {
      const p = this.pages[i]

      let index = -1

      if (p) index = p.findLast(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_PAGE + index

      j = BITS_PER_PAGE - 1
      i--
    }

    return -1
  }
}

module.exports = class RemoteBitfield {
  static BITS_PER_PAGE = BITS_PER_PAGE
  static BITS_PER_SEGMENT = BITS_PER_SEGMENT

  constructor() {
    this._pages = new BigSparseArray()
    this._segments = new BigSparseArray()
    this._maxSegments = 0
  }

  getBitfield(index) {
    const j = index & (BITS_PER_PAGE - 1)
    const i = (index - j) / BITS_PER_PAGE

    const p = this._pages.get(i)
    return p || null
  }

  get(index) {
    const j = index & (BITS_PER_PAGE - 1)
    const i = (index - j) / BITS_PER_PAGE

    const p = this._pages.get(i)

    return p ? p.get(j) : false
  }

  set(index, val) {
    const j = index & (BITS_PER_PAGE - 1)
    const i = (index - j) / BITS_PER_PAGE

    let p = this._pages.get(i)

    if (!p && val) {
      const k = Math.floor(i / PAGES_PER_SEGMENT)
      const s = this._segments.get(k) || this._segments.set(k, new RemoteBitfieldSegment(k))
      if (this._maxSegments <= k) this._maxSegments = k + 1

      p = this._pages.set(i, new RemoteBitfieldPage(i, new Uint32Array(WORDS_PER_PAGE), s))
    }

    if (p) p.set(j, val)
  }

  setRange(start, end, val) {
    let j = start & (BITS_PER_PAGE - 1)
    let i = (start - j) / BITS_PER_PAGE

    while (start < end) {
      let p = this._pages.get(i)

      if (!p && val) {
        const k = Math.floor(i / PAGES_PER_SEGMENT)
        const s = this._segments.get(k) || this._segments.set(k, new RemoteBitfieldSegment(k))
        if (this._maxSegments <= k) this._maxSegments = k + 1

        p = this._pages.set(i, new RemoteBitfieldPage(i, new Uint32Array(WORDS_PER_PAGE), s))
      }

      const offset = i * BITS_PER_PAGE
      const last = Math.min(end - offset, BITS_PER_PAGE)
      const range = last - j

      if (p) p.setRange(j, last, val)

      j = 0
      i++
      start += range
    }
  }

  findFirst(val, position) {
    let j = position & (BITS_PER_SEGMENT - 1)
    let i = (position - j) / BITS_PER_SEGMENT

    while (i < this._maxSegments) {
      const s = this._segments.get(i)

      let index = -1

      if (s) index = s.findFirst(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_SEGMENT + index

      j = 0
      i++
    }

    // For the val === false case, we always return at least
    // the 'position', also if nothing was found
    return val ? -1 : Math.max(position, this._maxSegments * BITS_PER_SEGMENT)
  }

  firstSet(position) {
    return this.findFirst(true, position)
  }

  firstUnset(position) {
    return this.findFirst(false, position)
  }

  findLast(val, position) {
    let j = position & (BITS_PER_SEGMENT - 1)
    let i = (position - j) / BITS_PER_SEGMENT

    while (i >= 0) {
      const s = this._segments.get(i)

      let index = -1

      if (s) index = s.findLast(val, j)
      else if (!val) index = j

      if (index !== -1) return i * BITS_PER_SEGMENT + index

      j = BITS_PER_SEGMENT - 1
      i--
    }

    return -1
  }

  lastSet(position) {
    return this.findLast(true, position)
  }

  lastUnset(position) {
    return this.findLast(false, position)
  }

  insert(start, bitfield) {
    if (start % 32 !== 0) return false

    let length = bitfield.byteLength * 8

    let j = start & (BITS_PER_PAGE - 1)
    let i = (start - j) / BITS_PER_PAGE

    while (length > 0) {
      let p = this._pages.get(i)

      if (!p) {
        const k = Math.floor(i / PAGES_PER_SEGMENT)
        const s = this._segments.get(k) || this._segments.set(k, new RemoteBitfieldSegment(k))
        if (this._maxSegments <= k) this._maxSegments = k + 1

        p = this._pages.set(i, new RemoteBitfieldPage(i, new Uint32Array(WORDS_PER_PAGE), s))
      }

      const end = Math.min(j + length, BITS_PER_PAGE)
      const range = end - j

      p.insert(j, bitfield.subarray(0, range / 32))

      bitfield = bitfield.subarray(range / 32)

      j = 0
      i++
      length -= range
    }

    return true
  }

  clear(start, bitfield) {
    if (start % 32 !== 0) return false

    let length = bitfield.byteLength * 8

    let j = start & (BITS_PER_PAGE - 1)
    let i = (start - j) / BITS_PER_PAGE

    while (length > 0) {
      let p = this._pages.get(i)

      if (!p) {
        const k = Math.floor(i / PAGES_PER_SEGMENT)
        const s = this._segments.get(k) || this._segments.set(k, new RemoteBitfieldSegment(k))
        if (this._maxSegments <= k) this._maxSegments = k + 1

        p = this._pages.set(i, new RemoteBitfieldPage(i, new Uint32Array(WORDS_PER_PAGE), s))
      }

      const end = Math.min(j + length, BITS_PER_PAGE)
      const range = end - j

      p.clear(j, bitfield.subarray(0, range / 32))

      bitfield = bitfield.subarray(range / 32)

      j = 0
      i++
      length -= range
    }

    return true
  }
}
/* DEV DOCS
  Every hypercore has one Replicator object managing its connections to other peers.
  There is one Peer object per peer connected to the Hypercore.
  Hypercores do not know about other hypercores, so when a peer is connected to multiple cores, there exists one Peer object per core.

  Hypercore indicates block should be downloaded through methods like Replicator.addRange or Replicator.addBlock
  Hypercore calls Replicator.updateActivity every time a hypercore session opens/closes
  Replicator.updateActivity ensures the Hypercore is downloading blocks as expected
  Replicator keeps track of:
    - Which blocks need to be downloaded (Replicator._blocks)
    - Which blocks currently have inflight requests (Replicator._inflight)

  Blocks are requested from remote peers by Peer objects. The flow is:
    - The replicator's updatePeer method gets called
    - The replicator detects whether the Peer can accept more requests (for example by checking if it's maxed out on inflight blocks)
    - The replicator then tells the Peer what to request (e.g. Peer_requestRange or Peer._requestBlock methods)

  The Peer object is responsible for tracking
    - Which blocks does the Peer have available (tracked in remoteBitfield)
    - Which blocks are you actively looking for from this peer (tracked in missingBlocks)
    - How many blocks are currently inflight (tracked in inflight)
  The Peer uses this information to decide which blocks to request from the peer in response to _requestRange requests and the like.
*/

const b4a = require('b4a')
const safetyCatch = require('safety-catch')
const RandomIterator = require('random-array-iterator')
const flatTree = require('flat-tree')
const Mutex = require('./mutex')
const ReceiverQueue = require('./receiver-queue')
const HotswapQueue = require('./hotswap-queue')
const RemoteBitfield = require('./remote-bitfield')
const { MerkleTree } = require('./merkle-tree')
const w = require('./wants')
const { LocalWants, RemoteWants } = w
const {
  REQUEST_CANCELLED,
  REQUEST_TIMEOUT,
  INVALID_CAPABILITY,
  SNAPSHOT_NOT_AVAILABLE,
  ASSERTION
} = require('hypercore-errors')
const m = require('./messages')
const caps = require('./caps')

const DEFAULT_MAX_INFLIGHT = [16, 512]
const SCALE_LATENCY = 50
const NOT_DOWNLOADING_SLACK = (20000 + Math.random() * 20000) | 0
const MAX_PEERS_UPGRADE = 3
const LAST_BLOCKS = 256

const MAX_RANGES = 64

const NOT_AVAILABLE = 1
const INVALID_REQUEST = 2
const MAX_INVALID_REQUESTS = 64
const MAX_BACKOFFS = MAX_INVALID_REQUESTS / 2

const PRIORITY = {
  NORMAL: 0,
  HIGH: 1,
  VERY_HIGH: 2,
  CANCELLED: 255 // reserved to mark cancellation
}

class Attachable {
  constructor(replicator) {
    this.replicator = replicator
    this.resolved = false
    this.processing = false
    this.refs = []
    this.wants = null
  }

  addWant(w) {
    if (this.wants === null) this.wants = new Set()
    this.wants.add(w)
  }

  removeWant(w) {
    if (this.wants === null) return
    this.wants.delete(w)
  }

  attach(session) {
    const r = {
      context: this,
      session,
      sindex: 0,
      rindex: 0,
      snapshot: true,
      resolve: null,
      reject: null,
      promise: null,
      timeout: null
    }

    r.sindex = session.push(r) - 1
    r.rindex = this.refs.push(r) - 1
    r.promise = new Promise((resolve, reject) => {
      r.resolve = resolve
      r.reject = reject
    })

    return r
  }

  detach(r, err = null) {
    if (r.context !== this) return false

    this._detach(r)
    this._cancel(r, err)
    this.gc()

    return true
  }

  _detach(r) {
    const rh = this.refs.pop()
    const sh = r.session.pop()

    if (r.rindex < this.refs.length) this.refs[(rh.rindex = r.rindex)] = rh
    if (r.sindex < r.session.length) r.session[(sh.sindex = r.sindex)] = sh

    destroyRequestTimeout(r)
    r.context = null

    return r
  }

  gc() {
    if (this.refs.length > 0 || this.processing) return
    this._unref()

    if (this.wants === null) return

    const wants = this.wants
    this.wants = null

    let update = null

    for (const w of wants) {
      if (w.any) {
        const removed = w.wants.removeAnyRange(w.start, w.length, this)
        if (!removed) continue
        if (update === null) update = new Set()
        update.add(w.wants.peer)
        // TODO: should also use a free list for simplicity
        w.wants.peer.wireUnwant.send(removed)
        continue
      }

      if (w.wants.removeBatch(w.start, this)) {
        if (update === null) update = new Set()
        update.add(w.wants.peer)
      }
    }

    if (update === null) return
    for (const peer of update) {
      this.replicator.updatePeer(peer)
    }
  }

  processed() {
    this.processing = false
    this.gc()
  }

  _cancel(r, err) {
    r.reject(err || REQUEST_CANCELLED())
  }

  _unref() {
    // overwrite me
  }

  resolve(val) {
    this.resolved = true
    while (this.refs.length > 0) {
      this._detach(this.refs[this.refs.length - 1]).resolve(val)
    }
    this.gc()
  }

  reject(err) {
    this.resolved = true
    while (this.refs.length > 0) {
      this._detach(this.refs[this.refs.length - 1]).reject(err)
    }
    this.gc()
  }

  setTimeout(r, ms) {
    destroyRequestTimeout(r)
    r.timeout = setTimeout(onrequesttimeout, ms, r)
  }
}

class BlockRequest extends Attachable {
  constructor(replicator, tracker, index, priority, force) {
    super(replicator)

    this.index = index
    this.priority = priority
    this.inflight = []
    this.queued = false
    this.hotswap = null
    this.tracker = tracker
    this.force = force
  }

  _unref() {
    if (this.resolved) return
    this.queued = false

    for (const req of this.inflight) {
      req.peer._cancelRequest(req)
    }

    this.tracker.remove(this.index)
    removeHotswap(this)
  }
}

class RangeBatchRequest extends Attachable {
  constructor(replicator, batch) {
    super(replicator)

    this.batch = batch
    this.index = 0
  }
}

class RangeRequest extends Attachable {
  constructor(replicator, ranges, start, end, linear, blocks) {
    super(replicator)

    this.start = start
    this.end = end
    this.linear = linear
    this.blocks = blocks
    this.ranges = ranges
    this.batches = []

    ranges.push(this)

    if (this.end === -1) {
      this.replicator._alwaysLatestBlock++
    }

    // As passed by the user, immut
    this.userStart = start
    this.userEnd = end
  }

  addBatch(batch) {
    for (let i = 0; i < this.batches.length; i++) {
      const b = this.batches[i]
      if (b.batch === batch) return false
    }
    const b = new RangeBatchRequest(this.replicator, batch)
    b.index = this.batches.length
    this.batches.push(b)
    return true
  }

  removeBatch(batch) {
    const head = this.batches.pop()

    if (head !== batch) {
      head.index = batch.index
      this.batches[head.index] = head
    }

    batch.gc()
  }

  _unref() {
    const rangeIndex = this.ranges.indexOf(this)
    if (rangeIndex === -1) return

    const h = this.ranges.pop()
    if (h !== this) {
      this.ranges[rangeIndex] = h
    }

    if (this.end === -1) {
      this.replicator._alwaysLatestBlock--
    }

    while (this.batches.length) {
      this.batches.pop().gc()
    }
  }

  _cancel(r) {
    r.resolve(false)
  }
}

class UpgradeRequest extends Attachable {
  constructor(replicator, fork, length) {
    super(replicator)

    this.fork = fork
    this.length = length
    this.inflight = []
  }

  _unref() {
    if (this.resolved) return
    if (this.replicator.eagerUpgrade === true || this.inflight.length > 0) return
    this.replicator._upgrade = null
  }

  _cancel(r) {
    r.resolve(false)
  }
}

class SeekRequest extends Attachable {
  constructor(replicator, seeks, seeker) {
    super(replicator)

    this.seeker = seeker
    this.inflight = []
    this.seeks = seeks
  }

  _unref() {
    if (this.resolved) return
    if (this.inflight.length > 0) return
    const i = this.seeks.indexOf(this)
    if (i === -1) return
    const h = this.seeks.pop()
    if (i < this.seeks.length) this.seeks[i] = h
  }
}

class ForkRequest extends Attachable {
  constructor(replicator, fork) {
    super(replicator)
    this.fork = fork
    this.inflight = []
    this.batch = null
  }
}

class InflightTracker {
  constructor() {
    this._requests = []
    this._free = []
    this._active = 0
  }

  get idle() {
    return this._active === 0
  }

  *[Symbol.iterator]() {
    for (const req of this._requests) {
      if (req !== null) yield req
    }
  }

  add(req) {
    const id = this._free.length ? this._free.pop() : this._requests.push(null)
    req.id = id
    this._requests[id - 1] = req
    this._active++
    return req
  }

  get(id) {
    return id <= this._requests.length ? this._requests[id - 1] : null
  }

  remove(id, roundtrip) {
    if (id > this._requests.length) return
    if (this._requests[id - 1]) this._active--
    this._requests[id - 1] = null
    if (roundtrip === true) this._free.push(id)
  }

  reusable(id) {
    this._free.push(id)
  }
}

class BlockTracker {
  constructor(replicator) {
    this._replicator = replicator
    this._map = new Map()
  }

  [Symbol.iterator]() {
    return this._map.values()
  }

  isEmpty() {
    return this._map.size === 0
  }

  has(index) {
    return this._map.has(index)
  }

  get(index) {
    return this._map.get(index) || null
  }

  add(index, priority, force) {
    let b = this._map.get(index)
    if (b) return b

    b = new BlockRequest(this._replicator, this, index, priority, force)
    this._map.set(index, b)

    return b
  }

  remove(index) {
    const b = this.get(index)
    this._map.delete(index)
    return b
  }
}

class RoundtripQueue {
  constructor() {
    this.queue = []
    this.tick = 0
  }

  clear() {
    const ids = new Array(this.queue.length)
    for (let i = 0; i < ids.length; i++) {
      ids[i] = this.queue[i][1]
    }

    this.queue = []

    return ids
  }

  add(id) {
    this.queue.push([++this.tick, id])
  }

  flush(tick) {
    let flushed = null

    for (let i = 0; i < this.queue.length; i++) {
      if (this.queue[i][0] > tick) break
      if (flushed === null) flushed = []
      flushed.push(this.queue[i][1])
    }

    if (flushed !== null) this.queue.splice(0, flushed.length)
    return flushed
  }
}

class ProofRequest {
  constructor(msg, proof, block, manifest) {
    this.msg = msg
    this.proof = proof
    this.block = block
    this.manifest = manifest
  }

  async fulfill() {
    if (this.proof === null) return null

    const [proof, block] = await Promise.all([this.proof.settle(), this.block])

    if (this.manifest) proof.manifest = this.manifest
    if (!block && proof.block) return null

    if (block) proof.block.value = block
    return proof
  }
}

class Peer {
  constructor(replicator, protomux, channel, inflightRange) {
    this.core = replicator.core
    this.replicator = replicator
    this.stream = protomux.stream
    this.protomux = protomux
    this.remotePublicKey = this.stream.remotePublicKey
    this.remoteSupportsSeeks = false
    this.inflightRange = inflightRange
    this.fullyDownloadedSignaled = 0

    this.paused = false
    this.removed = false

    this.channel = channel
    this.channel.userData = this

    this.wireSync = this.channel.messages[0]
    this.wireRequest = this.channel.messages[1]
    this.wireCancel = this.channel.messages[2]
    this.wireData = this.channel.messages[3]
    this.wireNoData = this.channel.messages[4]
    this.wireWant = this.channel.messages[5]
    this.wireUnwant = this.channel.messages[6]
    this.wireBitfield = this.channel.messages[7]
    this.wireRange = this.channel.messages[8]
    this.wireExtension = this.channel.messages[9]

    // Same stats as replicator, but for this specific peer
    this.stats = {
      wireSync: { tx: 0, rx: 0 },
      wireRequest: { tx: 0, rx: 0 },
      wireCancel: { tx: 0, rx: 0 },
      wireData: { tx: 0, rx: 0 },
      wireWant: { tx: 0, rx: 0 },
      wireUnwant: { tx: 0, rx: 0 },
      wireBitfield: { tx: 0, rx: 0 },
      wireRange: { tx: 0, rx: 0 },
      wireExtension: { tx: 0, rx: 0 },
      hotswaps: 0,
      invalidData: 0,
      invalidRequests: 0,
      backoffs: 0,
      notAvailableBackoffs: 0
    }

    this.receiverQueue = new ReceiverQueue()
    this.receiverBusy = false

    // most often not used, so made on demand
    this.roundtripQueue = null

    this.inflight = 0
    this.dataProcessing = 0

    this.canUpgrade = true

    this.needsSync = false
    this.syncsProcessing = 0
    this.lastUpgradableLength = 0
    this.lastUpgradableFork = 0

    this._remoteContiguousLength = 0

    // TODO: tweak pipelining so that data sent BEFORE remoteOpened is not cap verified!
    // we might wanna tweak that with some crypto, ie use the cap to encrypt it...
    // or just be aware of that, to only push non leaky data

    this.remoteOpened = false
    this.remoteBitfield = new RemoteBitfield()
    this.missingBlocks = new RemoteBitfield()

    this.pushedLength = 0

    this.remoteFork = 0
    this.remoteLength = 0
    this.remoteCanUpgrade = false
    this.remoteUploading = true
    this.remoteDownloading = true
    this.remoteSynced = false
    this.remoteHasManifest = false
    this.remoteAllowPush = false
    this.remoteRequests = new Map()

    this.segmentsWanted = new Set()
    this.broadcastedNonSparse = false

    this.wants = new LocalWants(this)
    this.remoteWants = new RemoteWants(this)

    this.lengthAcked = 0

    this.extensions = new Map()
    this.lastExtensionSent = ''
    this.lastExtensionRecv = ''

    replicator._ifAvailable++
    replicator._active++
  }

  get remoteContiguousLength() {
    return this.remoteBitfield.findFirst(false, this._remoteContiguousLength)
  }

  getMaxInflight() {
    const stream = this.stream.rawStream
    if (!stream.udx) return Math.min(this.inflightRange[1], this.inflightRange[0] * 3)

    const scale =
      stream.rtt <= SCALE_LATENCY
        ? 1
        : (stream.rtt / SCALE_LATENCY) * Math.min(1, 2 / this.replicator.peers.length)
    return Math.max(
      this.inflightRange[0],
      Math.round(Math.min(this.inflightRange[1], this.inflightRange[0] * scale))
    )
  }

  getMaxHotswapInflight() {
    const inf = this.getMaxInflight()
    return Math.max(16, inf / 2)
  }

  signalUpgrade() {
    if (this._shouldUpdateCanUpgrade() === true) this._updateCanUpgradeAndSync()
    else this.sendSync()
  }

  _markInflight(index) {
    this.missingBlocks.set(index, false)
  }

  broadcastRange(start, length, drop) {
    if (!this.isActive()) return

    if (drop) this._unclearLocalRange(start, length)
    else this._clearLocalRange(start, length)

    const fullyContig = this.core.header.hints.contiguousLength === this.core.state.length

    if (start + LAST_BLOCKS < this.core.state.length && !drop && !fullyContig) {
      if (!this.remoteWants.hasRange(start, length)) return
    }

    let force = false
    if (fullyContig && !drop) {
      start = 0
      length = this.core.state.length

      // Always send the broadcast when we switch from sparse to fully contiguous, so remote knows too
      if (this.fullyDownloadedSignaled < length) {
        this.fullyDownloadedSignaled = length
        force = true
      }
    }

    // TODO: consider also adding early-returns on the drop===true case
    if (!force && !drop) {
      // No need to broadcast if the remote already has this range

      if (this._remoteContiguousLength >= start + length) return

      if (length === 1) {
        if (this.remoteBitfield.get(start)) return
      } else {
        if (this.remoteBitfield.firstUnset(start) >= start + length) return
      }
    }

    this.wireRange.send({
      drop,
      start,
      length
    })
    incrementTx(this.stats.wireRange, this.replicator.stats.wireRange)
  }

  extension(name, message) {
    this.wireExtension.send({ name: name === this.lastExtensionSent ? '' : name, message })
    incrementTx(this.stats.wireExtension, this.replicator.stats.wireExtension)
    this.lastExtensionSent = name
  }

  onextension(message) {
    const name = message.name || this.lastExtensionRecv
    this.lastExtensionRecv = name
    const ext = this.extensions.get(name)
    if (ext) {
      ext._onmessage({ start: 0, end: message.message.byteLength, buffer: message.message }, this)
    }
  }

  sendSync() {
    // Skip syncs if in repair mode
    if (this.core._repairMode) return

    if (this.syncsProcessing !== 0) {
      this.needsSync = true
      return
    }

    if (this.core.state.fork !== this.remoteFork) {
      this.canUpgrade = false
    }

    this.needsSync = false

    this.wireSync.send({
      fork: this.core.state.fork,
      length: this.core.state.length,
      remoteLength: this.core.state.fork === this.remoteFork ? this.remoteLength : 0,
      canUpgrade: this.canUpgrade,
      uploading: true,
      downloading: this.replicator.isDownloading(),
      hasManifest: !!this.core.header.manifest && this.core.compat === false,
      allowPush: this.replicator.isAllowingPush()
    })
    incrementTx(this.stats.wireSync, this.replicator.stats.wireSync)
  }

  onopen({ seeks, capability }) {
    const expected = caps.replicate(
      this.stream.isInitiator === false,
      this.core.key,
      this.stream.handshakeHash
    )

    if (b4a.equals(capability, expected) !== true) {
      // TODO: change this to a rejection instead, less leakage
      throw INVALID_CAPABILITY('Remote sent an invalid replication capability')
    }

    if (this.remoteOpened === true) return
    this.remoteOpened = true
    this.remoteSupportsSeeks = seeks

    this.protomux.cork()

    this.sendSync()

    const contig = Math.min(this.core.state.length, this.core.header.hints.contiguousLength)
    if (contig > 0) {
      this.broadcastRange(0, contig, false)

      if (contig === this.core.state.length) {
        this.broadcastedNonSparse = true
      }
    }

    this.replicator._ifAvailable--
    this.replicator._addPeer(this)

    this.protomux.uncork()

    this.core.checkIfIdle()
  }

  onclose(isRemote) {
    // we might have signalled to the remote that we are done (ie not downloading) and the remote might agree on that
    // if that happens, the channel might be closed by the remote. if so just renegotiate it.
    // TODO: add a CLOSE_REASON to mux to we can make this cleaner...
    const reopen =
      isRemote === true &&
      this.remoteOpened === true &&
      this.remoteDownloading === false &&
      this.remoteUploading === true &&
      this.replicator.downloading === true

    if (this.remoteOpened === false) {
      this.replicator._ifAvailable--
      this.replicator.updateAll()
      return
    }

    this.remoteOpened = false
    this.removed = true
    this.remoteRequests.clear() // cancel all
    this.receiverQueue.clear()

    if (this.roundtripQueue !== null) {
      for (const id of this.roundtripQueue.clear()) this.replicator._inflight.reusable(id)
    }

    this.replicator._removePeer(this)

    if (reopen) {
      this.replicator._makePeer(this.protomux)
    }
  }

  closeIfIdle() {
    if (this.remoteDownloading === false && this.replicator.isDownloading() === false) {
      // idling, shut it down...
      this.channel.close()
      return true
    }

    return false
  }

  async onsync(msg) {
    const {
      fork,
      length,
      remoteLength,
      canUpgrade,
      uploading,
      downloading,
      hasManifest,
      allowPush
    } = msg

    const lengthChanged = length !== this.remoteLength
    const sameFork = fork === this.core.state.fork

    this.remoteSynced = true
    this.remoteFork = fork
    this.remoteLength = length
    this.remoteCanUpgrade = canUpgrade
    this.remoteUploading = uploading
    this.remoteDownloading = downloading
    this.remoteHasManifest = hasManifest
    this.remoteAllowPush = allowPush

    if (this.closeIfIdle()) return

    this.lengthAcked = sameFork ? remoteLength : 0
    this.syncsProcessing++

    this.replicator._updateFork(this)

    if (this.remoteLength > this.core.state.length && this.lengthAcked === this.core.state.length) {
      if (this.replicator._addUpgradeMaybe() !== null) this._update()
    }

    const upgrade =
      lengthChanged === false || sameFork === false
        ? this.canUpgrade && sameFork
        : await this._canUpgrade(length, fork)

    if (length === this.remoteLength && fork === this.core.state.fork) {
      this.canUpgrade = upgrade
      if (upgrade) {
        this.lastUpgradableFork = fork
        this.lastUpgradableLength = length
      }
    }

    if (--this.syncsProcessing !== 0) return // ie not latest

    if (
      this.needsSync === true ||
      (this.core.state.fork === this.remoteFork && this.core.state.length > this.remoteLength)
    ) {
      this.signalUpgrade()
    }

    this._update()
  }

  _shouldUpdateCanUpgrade() {
    return (
      this.core.state.fork === this.remoteFork &&
      this.core.state.length > this.remoteLength &&
      this.canUpgrade === false &&
      this.syncsProcessing === 0
    )
  }

  async _updateCanUpgradeAndSync() {
    const { length, fork } = this.core.state

    const remoteLength = this.remoteLength
    const remoteFork = this.remoteFork
    const canUpgrade = await this._canUpgrade(this.remoteLength, this.remoteFork)

    if (
      this.syncsProcessing > 0 ||
      length !== this.core.state.length ||
      fork !== this.core.state.fork
    ) {
      return
    }
    if (remoteLength !== this.remoteLength || remoteFork !== this.remoteFork) {
      return
    }
    if (canUpgrade === this.canUpgrade) {
      return
    }

    this.canUpgrade = canUpgrade
    if (canUpgrade) {
      this.lastUpgradableLength = this.remoteLength
      this.lastUpgradableFork = this.remoteFork
    }

    this.sendSync()
  }

  // Safe to call in the background - never fails
  async _canUpgrade(remoteLength, remoteFork) {
    if (remoteFork !== this.core.state.fork) return false

    if (remoteLength === 0) return true
    if (remoteLength >= this.core.state.length) return false

    try {
      // Rely on caching to make sure this is cheap...
      const canUpgrade = await MerkleTree.upgradeable(this.core.state, remoteLength)

      if (remoteFork !== this.core.state.fork) return false

      return canUpgrade
    } catch {
      return false
    }
  }

  async _getProof(batch, msg, pushing) {
    let block = null

    if (msg.block) {
      const index = msg.block.index

      if (!pushing && (msg.fork !== this.core.state.fork || !this.core.bitfield.get(index))) {
        return new ProofRequest(msg, null, null, null)
      }

      block = batch.getBlock(index)
      block.catch(noop)
    }

    const manifest = msg.manifest && !this.core.compat ? this.core.header.manifest : null

    try {
      const proof = await MerkleTree.proof(this.core.state, batch, msg)
      return new ProofRequest(msg, proof, block, manifest)
    } catch (err) {
      batch.destroy()

      this.replicator._oninvalidrequest(err, msg, this)

      if (this.stats.invalidRequests >= MAX_INVALID_REQUESTS) throw err

      await backoff(this.stats.invalidRequests)
      return null
    }
  }

  async onrequest(msg) {
    const size = this.remoteRequests.size
    this.remoteRequests.set(msg.id, msg)

    // if size didnt change -> id overwrite -> old one is deleted, cancel current and re-add
    if (size === this.remoteRequests.size) {
      this._cancel(msg.id)
      this.remoteRequests.set(msg.id, msg)
    }

    if (!this.protomux.drained || this.receiverQueue.length) {
      this.receiverQueue.push(msg)
      return
    }

    if (this.replicator.destroyed) return

    await this._handleRequest(msg)
  }

  oncancel(msg) {
    this._cancel(msg.request)
  }

  _cancel(id) {
    this.remoteRequests.delete(id)
    this.receiverQueue.delete(id)
  }

  ondrain() {
    return this._handleRequests()
  }

  async _handleRequests() {
    if (this.receiverBusy || this.replicator.destroyed) return
    this.receiverBusy = true
    this.protomux.cork()

    while (
      this.remoteOpened &&
      this.protomux.drained &&
      this.receiverQueue.length > 0 &&
      !this.removed
    ) {
      const msg = this.receiverQueue.shift()
      await this._handleRequest(msg)
    }

    this.protomux.uncork()
    this.receiverBusy = false
  }

  async push(index) {
    if (!this.remoteAllowPush) return
    if (!this.remoteDownloading) return
    if (this.core.state.length <= index) return
    if (this.core.state.fork !== this.remoteFork) return
    if (this.remoteBitfield.get(index)) return

    const msg = {
      id: 0,
      fork: this.core.state.fork,
      block: null,
      hash: null,
      seek: null,
      upgrade: null,
      manifest: this.remoteLength === 0,
      priority: 0
    }

    await this.replicator._txLock.lock()
    try {
      const remoteLength = Math.max(this.remoteLength, this.pushedLength)

      msg.block = {
        index,
        nodes: MerkleTree.maxMissingNodes(2 * index, remoteLength)
      }

      if (index >= remoteLength) {
        msg.upgrade = {
          start: remoteLength,
          length: this.core.state.length - remoteLength
        }
      }

      let req = null
      const batch = this.core.storage.read()
      try {
        req = await this._getProof(batch, msg, true)
      } catch (err) {
        this.replicator._oninvalidrequest(err, msg, this)
        return
      }

      if (req === null) return
      batch.tryFlush()

      await this._fulfillRequest(req, true)
    } finally {
      this.replicator._txLock.unlock()
    }
  }

  async _handleRequest(msg) {
    const locked = !!msg.upgrade && this.remoteAllowPush

    if (locked) {
      // ensure contig push proofs
      await this.replicator._txLock.lock()
      const end = msg.upgrade.start + msg.upgrade.length

      if (this.pushedLength < end) {
        msg.upgrade.start = this.pushedLength
        msg.upgrade.length = end - this.pushedLength
      }
    }

    try {
      const batch = this.core.storage.read()

      // TODO: could still be answerable if (index, fork) is an ancestor of the current fork
      const req =
        msg.fork === this.core.state.fork
          ? await this._getProof(batch, msg, false)
          : new ProofRequest(msg, null, null, null)

      if (req === null) {
        this.wireNoData.send({ request: msg.id, reason: INVALID_REQUEST })
        return
      }

      batch.tryFlush()

      await this._fulfillRequest(req, false)
    } finally {
      if (locked) this.replicator._txLock.unlock()
    }
  }

  async _fulfillRequest(req, pushing) {
    if (this.core._repairMode) {
      // if cancelled do not reply
      if (this.remoteRequests.get(req.msg.id) !== req.msg) {
        return
      }

      // sync from now on, so safe to delete from the map
      this.remoteRequests.delete(req.msg.id)

      // If cutting off the fulfillment, ensure promise is caught.
      // While repairing merkle tree nodes can be `nil` so can throw.
      req.fulfill().catch(safetyCatch)
      return
    }

    const proof = await req.fulfill()

    if (!pushing) {
      // if cancelled do not reply
      if (this.remoteRequests.get(req.msg.id) !== req.msg) {
        return
      }

      // sync from now on, so safe to delete from the map
      this.remoteRequests.delete(req.msg.id)
    } else if (!this.remoteAllowPush) {
      // if pushing but remote disabled it, just drop it
      return
    }

    if (!this.isActive() && proof.block !== null) {
      return
    }

    if (proof === null) {
      if (req.msg.manifest && this.core.header.manifest) {
        const manifest = this.core.header.manifest
        this.wireData.send({
          request: req.msg.id,
          fork: this.core.state.fork,
          block: null,
          hash: null,
          seek: null,
          upgrade: null,
          manifest
        })
        incrementTx(this.stats.wireData, this.replicator.stats.wireData)
        return
      }

      this.wireNoData.send({ request: req.msg.id, reason: NOT_AVAILABLE })
      return
    }

    if (proof.block !== null) {
      this.replicator._onupload(proof.block.index, proof.block.value.byteLength, this)
    }

    if (proof.upgrade) {
      const remoteLength = MerkleTree.upgradeLength(proof.upgrade)
      if (remoteLength > this.pushedLength) this.pushedLength = remoteLength
    }

    this.wireData.send({
      request: req.msg.id,
      fork: req.msg.fork,
      block: proof.block,
      hash: proof.hash,
      seek: proof.seek,
      upgrade: proof.upgrade,
      manifest: proof.manifest
    })
    incrementTx(this.stats.wireData, this.replicator.stats.wireData)
  }

  _cancelRequest(req) {
    if (req.priority === PRIORITY.CANCELLED) return
    // mark as cancelled also and avoid re-entry
    req.priority = PRIORITY.CANCELLED

    this.inflight--
    this.replicator._requestDone(req.id, false)

    // clear inflight state
    if (isBlockRequest(req)) this.replicator._unmarkInflight(req.block.index)
    if (isUpgradeRequest(req)) this.replicator._clearInflightUpgrade(req)

    if (this.roundtripQueue === null) this.roundtripQueue = new RoundtripQueue()
    this.roundtripQueue.add(req.id)
    this.wireCancel.send({ request: req.id })
    incrementTx(this.stats.wireCancel, this.replicator.stats.wireCancel)
  }

  _checkIfConflict() {
    this.paused = true

    const length = Math.min(this.core.state.length, this.remoteLength)
    if (length === 0) return // pause and ignore

    this.wireRequest.send({
      id: 0, // TODO: use an more explicit id for this eventually...
      fork: this.remoteFork,
      block: null,
      hash: null,
      seek: null,
      upgrade: {
        start: 0,
        length
      }
    })

    incrementTx(this.stats.wireRequest, this.replicator.stats.wireRequest)
  }

  _unmarkInflightBlockRequest(req, data) {
    if (isBlockRequest(req)) this.replicator._unmarkInflight(req.block.index)
    else if (data.block && !req) this.replicator._unmarkInflight(data.block.index)
  }

  async ondata(data) {
    if (data.request !== 0 && !data.upgrade) return this._handleData(data)

    await this.replicator._rxLock.lock()
    try {
      await this._handleData(data)
    } finally {
      this.replicator._rxLock.unlock()
    }
  }

  async _handleData(data) {
    // always allow a fork conflict proof to be sent
    if (data.request === 0 && data.upgrade && data.upgrade.start === 0) {
      if (await this.core.checkConflict(data, this)) return
      this.paused = false
    }

    const req = data.request > 0 ? this.replicator._inflight.get(data.request) : null
    const reorg = data.fork > this.core.state.fork

    // no push atm, TODO: check if this satisfies another pending request
    // allow reorg pushes tho as those are not written to storage so we'll take all the help we can get
    if (req === null && reorg === false && !this.replicator.allowPush) {
      return
    }

    // Skip accepting data if in repair mode to avoid corruption
    if (this.core._repairMode) {
      this.replicator._onnodata(this, req, NOT_AVAILABLE)
      return
    }

    if (req === null && reorg === false && data.block) {
      // mark this as inflight to avoid parallel requests
      this.replicator._markInflight(data.block.index)
    }

    if (req !== null) {
      if (req.peer !== this) return
      this._onrequestroundtrip(req)
    }

    try {
      if (reorg === true) return await this.replicator._onreorgdata(this, req, data)
    } catch (err) {
      safetyCatch(err)
      this._unmarkInflightBlockRequest(req, data)

      this.paused = true
      this.replicator._oninvaliddata(err, req, data, this)
      return
    }

    this.dataProcessing++
    if (isBlockRequest(req)) this.replicator._markProcessing(req.block.index)

    try {
      if (!this.replicator._matchingRequest(req, data) || !(await this.core.verify(data, this))) {
        this.replicator._onnodata(this, req, 0)
        return
      }
    } catch (err) {
      safetyCatch(err)
      this._unmarkInflightBlockRequest(req, data)

      if (err.code === 'WRITE_FAILED') {
        // For example, we don't want to keep pulling data when storage is full
        // TODO: notify the user somehow
        this.paused = true
        return
      }

      if (this.core.closed && !isCriticalError(err)) return

      if (err.code !== 'INVALID_OPERATION') {
        // might be a fork, verify
        this._checkIfConflict()
      }

      // if push mode, we MIGHT get an occasional bad message
      // no need to mega bail for that. TODO: rate limit instead as a general thing
      if (!this.replicator.allowPush) {
        this.paused = true
      }

      this.replicator._onnodata(this, req, 0)
      this.replicator._oninvaliddata(err, req, data, this)
      return
    } finally {
      if (isBlockRequest(req)) this.replicator._markProcessed(req.block.index)
      this.dataProcessing--
    }

    this.replicator._ondata(this, req, data)

    if (this._shouldUpdateCanUpgrade() === true) {
      this._updateCanUpgradeAndSync()
    }
  }

  onnodata({ request, reason }) {
    const req = request > 0 ? this.replicator._inflight.get(request) : null

    if (req === null || req.peer !== this) {
      this.replicator.updateAll()
      return
    }

    this._onrequestroundtrip(req)
    this.replicator._onnodata(this, req, reason)
  }

  _onrequestroundtrip(req) {
    if (req.priority === PRIORITY.CANCELLED) return
    // to avoid re-entry we also just mark it as cancelled
    req.priority = PRIORITY.CANCELLED

    this.inflight--
    this.replicator._requestDone(req.id, true)
    if (this.roundtripQueue === null) return
    const flushed = this.roundtripQueue.flush(req.rt)
    if (flushed === null) return
    for (const id of flushed) this.replicator._inflight.reusable(id)
  }

  onwant(range) {
    if (!this.remoteWants.add(range)) return
    this.replicator._onwant(this, range.start, range.length, range.any)
  }

  onunwant(range) {
    this.remoteWants.remove(range)
  }

  onbitfield({ start, bitfield }) {
    if (start < this._remoteContiguousLength) this._remoteContiguousLength = start // bitfield is always the truth
    this.remoteBitfield.insert(start, bitfield)
    this.missingBlocks.insert(start, bitfield)
    this._clearLocalRange(start, bitfield.byteLength * 8)
    this._update()
  }

  _clearLocalRange(start, length) {
    const bitfield = this.core.skipBitfield === null ? this.core.bitfield : this.core.skipBitfield

    if (length === 1) {
      this.missingBlocks.set(start, this._remoteHasBlock(start) && !bitfield.get(start))
      return
    }

    const contig = Math.min(this.core.state.length, this.core.header.hints.contiguousLength)

    if (start + length < contig) {
      this.missingBlocks.setRange(start, contig, false)
      return
    }

    const rem = start & 32767
    if (rem > 0) {
      start -= rem
      length += rem
    }

    const end = start + Math.min(length, this.core.state.length)
    while (start < end) {
      const local = bitfield.getBitfield(start)

      if (local && local.bitfield) {
        this.missingBlocks.clear(start, local.bitfield)
      }

      start += 32768
    }
  }

  _resetMissingBlock(index) {
    const bitfield = this.core.skipBitfield === null ? this.core.bitfield : this.core.skipBitfield
    this.missingBlocks.set(index, this._remoteHasBlock(index) && !bitfield.get(index))
  }

  _unclearLocalRange(start, length) {
    if (length === 1) {
      this._resetMissingBlock(start)
      return
    }

    const rem = start & (RemoteBitfield.BITS_PER_SEGMENT - 1)
    if (rem > 0) {
      start -= rem
      length += rem
    }

    const fixedStart = start

    const end = start + Math.min(length, this.remoteLength)
    while (start < end) {
      const remote = this.remoteBitfield.getBitfield(start)
      if (remote && remote.bitfield) {
        this.missingBlocks.insert(start, remote.bitfield)
      }

      start += RemoteBitfield.BITS_PER_SEGMENT
    }

    this._clearLocalRange(fixedStart, length)
  }

  async onrange({ drop, start, length }) {
    const has = drop === false

    if (drop === true && start < this._remoteContiguousLength) {
      this._remoteContiguousLength = start
    }

    if (start === 0 && drop === false) {
      if (length > this._remoteContiguousLength) {
        this._remoteContiguousLength = length
        if (
          this.remoteFork === this.core.state.fork &&
          length > this.core.header.hints.remoteContiguousLength
        ) {
          this.core.updateRemoteContiguousLength(length)
        }
      }
    } else if (length === 1) {
      const bitfield = this.core.skipBitfield === null ? this.core.bitfield : this.core.skipBitfield
      this.remoteBitfield.set(start, has)
      this.missingBlocks.set(start, has && !bitfield.get(start))
    } else {
      const rangeStart = this.remoteBitfield.findFirst(!has, start)
      const rangeEnd = length + start

      if (rangeStart !== -1 && rangeStart < rangeEnd) {
        this.remoteBitfield.setRange(rangeStart, rangeEnd, has)
        this.missingBlocks.setRange(rangeStart, rangeEnd, has)
        if (has) this._clearLocalRange(rangeStart, rangeEnd - rangeStart)
      }
    }

    if (this.core.hintsChanged) await this.core.flushHints()
    if (drop === false) this._update()

    this.core.emitRemoteContiguousLength()
  }

  onreorghint() {
    // TODO
  }

  _update() {
    // TODO: if this is in a batch or similar it would be better to defer it
    // we could do that with nextTick/microtick mb? (combined with a property on the session to signal read buffer mb)
    this.replicator.updatePeer(this)
  }

  async _onconflict() {
    this.protomux.cork()
    if (this.remoteLength > 0 && this.core.state.fork === this.remoteFork) {
      await this.onrequest({
        id: 0,
        fork: this.core.state.fork,
        block: null,
        hash: null,
        seek: null,
        upgrade: {
          start: 0,
          length: Math.min(this.core.state.length, this.remoteLength)
        }
      })
    }
    this.channel.close()
    this.protomux.uncork()
  }

  _makeRequest(needsUpgrade, priority, minLength) {
    if (needsUpgrade === true && this.replicator._shouldUpgrade(this) === false) {
      return null
    }

    // ensure that the remote has signalled they have the length we request
    if (this.remoteLength < minLength) {
      return null
    }

    if (needsUpgrade === false && this.replicator._autoUpgrade(this) === true) {
      needsUpgrade = true
    }

    return {
      peer: this,
      rt: this.roundtripQueue === null ? 0 : this.roundtripQueue.tick,
      id: 0,
      fork: this.remoteFork,
      block: null,
      hash: null,
      seek: null,
      upgrade:
        needsUpgrade === false
          ? null
          : { start: this.core.state.length, length: this.remoteLength - this.core.state.length },
      // remote manifest check can be removed eventually...
      manifest: this.core.header.manifest === null && this.remoteHasManifest === true,
      priority,
      timestamp: Date.now(),
      elapsed: 0
    }
  }

  _requestManifest() {
    const req = this._makeRequest(false, 0, 0)
    if (req === null) return

    this._send(req)
  }

  _includeLastBlock() {
    if (this.replicator._alwaysLatestBlock === 0) return null

    const index = this.remoteLength - 1

    // only valid if its an OOB get
    if (index < this.core.state.length) return null

    // do the normal checks
    if (!this._remoteHasBlock(index)) return null
    if (!this._canRequest(index, false)) return null

    // atm we only ever do one upgrade request in parallel, if that changes
    // then we should add some check here for inflights to avoid over requesting
    const b = this.replicator._blocks.add(index, PRIORITY.NORMAL, false)
    return b
  }

  _requestUpgrade(u) {
    if (this.replicator.pushOnly) return false

    const req = this._makeRequest(true, 0, 0)
    if (req === null) return false

    const b = this._includeLastBlock()

    if (b) this._sendBlockRequest(req, b)
    else this._send(req)

    return true
  }

  _requestSeek(s) {
    // if replicator is updating the seeks etc, bail and wait for it to drain
    if (this.replicator._updatesPending > 0) return false
    if (this.replicator.pushOnly) return false

    const { length, fork } = this.core.state

    if (fork !== this.remoteFork) return false

    if (s.seeker.start >= length) {
      const req = this._makeRequest(true, 0, 0)

      // We need an upgrade for the seek, if non can be provided, skip
      if (req === null) return false

      req.seek = this.remoteSupportsSeeks
        ? { bytes: s.seeker.bytes, padding: s.seeker.padding }
        : null

      s.inflight.push(req)
      this._send(req)

      return true
    }

    const len = s.seeker.end - s.seeker.start
    const off = s.seeker.start + Math.floor(Math.random() * len)

    for (let i = 0; i < len; i++) {
      let index = off + i
      if (index > s.seeker.end) index -= len

      if (this._remoteHasBlock(index) === false) continue
      if (this.core.bitfield.get(index) === true) continue
      if (!this._canRequest(index, false)) continue

      // Check if this block is currently inflight - if so pick another
      const b = this.replicator._blocks.get(index)
      if (b !== null && b.inflight.length > 0) continue

      // Block is not inflight, but we only want the hash, check if that is inflight
      const h = this.replicator._hashes.add(index, PRIORITY.NORMAL, false)
      if (h.inflight.length > 0) continue

      const req = this._makeRequest(false, h.priority, index + 1)
      if (req === null) continue

      const nodes = flatTree.depth(s.seeker.start + s.seeker.end - 1)

      req.hash = { index: 2 * index, nodes }
      req.seek = this.remoteSupportsSeeks
        ? { bytes: s.seeker.bytes, padding: s.seeker.padding }
        : null

      s.inflight.push(req)
      h.inflight.push(req)
      this._send(req)

      return true
    }

    this._maybeWantAnyRange(s.seeker.start, len, s)
    return false
  }

  _canRequest(index, force) {
    if (!(index >= 0)) throw ASSERTION('bad index to _canRequest: ' + index)

    if (!force && this.replicator.pushOnly) {
      return false
    }

    if (this.remoteLength >= this.core.state.length) {
      return true
    }

    if (index < this.lastUpgradableLength && this.lastUpgradableFork === this.core.state.fork) {
      return true
    }

    if (this.canUpgrade && this.syncsProcessing === 0) {
      return true
    }

    return false
  }

  _remoteHasBlock(index) {
    return index < this._remoteContiguousLength || this.remoteBitfield.get(index) === true
  }

  _sendBlockRequest(req, b) {
    if (this.core._repairMode) return

    req.block = { index: b.index, nodes: 0 }
    this.replicator._markInflight(b.index)

    b.inflight.push(req)
    this.replicator.hotswaps.add(b)
    this._send(req)
  }

  _requestBlock(b) {
    const { length, fork } = this.core.state

    if (this._remoteHasBlock(b.index) === false || fork !== this.remoteFork) {
      if (!this.core.bitfield.get(b.index)) this._maybeWant(b.index, b)
      return false
    }

    if (!this._canRequest(b.index, b.force)) return false

    const req = this._makeRequest(b.index >= length, b.priority, b.index + 1)
    if (req === null) return false

    this._sendBlockRequest(req, b)

    return true
  }

  _maybeWant(index, handle) {
    if (index < this.remoteContiguousLength) return

    const res = this.wants.add(index, handle)
    if (!res) return

    const batch = res.want && res.unwant
    if (batch) this.protomux.cork()

    if (res.unwant) {
      this.wireUnwant.send(res.unwant)
      incrementTx(this.stats.wireUnwant, this.replicator.stats.wireUnwant)
    }
    if (res.want) {
      this.wireWant.send(res.want)
      incrementTx(this.stats.wireWant, this.replicator.stats.wireWant)
    }

    if (batch) this.protomux.uncork()
  }

  _maybeWantAnyRange(start, length, handle) {
    if (handle.wants) {
      for (const w of handle.wants) {
        if ((w.start !== start || w.length !== length) && w.any) {
          const req = this.wants.removeAnyRange(w.start, w.length, handle)
          if (req) this.wireUnwant.send(req)
        }
      }
    }

    if (start + length <= this.remoteContiguousLength) return

    const req = this.wants.addAnyRange(start, length, handle)
    if (req) this.wireWant.send(req)
  }

  _requestRangeBlock(index, length) {
    if (this.core.bitfield.get(index) === true || !this._canRequest(index, false)) return false

    const b = this.replicator._blocks.add(index, PRIORITY.NORMAL, false)
    if (b.inflight.length > 0) {
      this.missingBlocks.set(index, false) // in case we missed some states just set them ondemand, nbd
      return false
    }

    const req = this._makeRequest(index >= length, b.priority, index + 1)

    // If the request cannot be satisfied, dealloc the block request if no one is subscribed to it
    if (req === null) {
      b.gc()
      return false
    }

    this._sendBlockRequest(req, b)

    // Don't think this will ever happen, as the pending queue is drained before the range queue
    // but doesn't hurt to check this explicitly here also.
    if (b.queued) b.queued = false
    return true
  }

  _findNext(i) {
    if (i < this._remoteContiguousLength) {
      if (this.core.skipBitfield === null) this.replicator._openSkipBitfield()
      i = this.core.skipBitfield.findFirst(false, i)
      if (i < this._remoteContiguousLength && i > -1) return i
      i = this._remoteContiguousLength
    }

    return this.missingBlocks.findFirst(true, i)
  }

  _addRangeBatch(r, offset, end) {
    const { WANT_BATCH } = w
    while (offset < end) {
      const next = this.core.bitfield.findFirst(false, offset)
      if (next === -1 || next >= end) return false

      const b = (next - (next & (WANT_BATCH - 1))) / WANT_BATCH

      if (r.addBatch(b)) return true

      offset = (b + 1) * WANT_BATCH
    }

    return false
  }

  _populateRangeBatches(r) {
    const { WANT_BATCH } = w
    for (let i = r.batches.length - 1; i >= 0; i--) {
      const b = r.batches[i]
      const minStart = b.batch * WANT_BATCH
      const maxEnd = minStart + WANT_BATCH

      const start = Math.max(r.start, minStart)
      const end = Math.min(r.end === -1 ? maxEnd : r.end, maxEnd)

      if (start < end && this.core.bitfield.hasUnset(start, end - start)) continue

      r.removeBatch(b)
    }

    while (r.batches.length < 3) {
      const end = r.end === -1 ? this.core.state.length : r.end
      if (end <= r.start) return

      const len = end - r.start
      const off = r.start + (r.linear ? 0 : Math.floor(Math.random() * len))

      if (!this._addRangeBatch(r, off, end) && !this._addRangeBatch(r, r.start, end)) break
    }
  }

  _requestRangeBatch(start, end, length) {
    let tries = this.inflight

    do {
      start = this._findNext(start)
      if (start === -1 || start >= end) break

      if (this._requestRangeBlock(start, length)) return true
      start++
    } while (tries-- > 0)

    return false
  }

  _getValidEnd(maxEnd) {
    // if we can upgrade the remote, or the remote is ahead, then all the remotes blocks are valid
    // otherwise truncate to the last length the remote has acked for us
    const maxLocalLength =
      this.canUpgrade || this.remoteLength >= this.core.state.length
        ? this.core.state.length
        : this.core.state.fork === this.lastUpgradableFork
          ? Math.min(this.lastUpgradableLength, this.core.state.length)
          : 0

    return Math.min(
      maxLocalLength,
      Math.min(maxEnd === -1 ? this.remoteLength : maxEnd, this.remoteLength)
    )
  }

  _requestRange(r) {
    const { WANT_BATCH } = w
    if (this.syncsProcessing > 0) return false

    const { length, fork } = this.core.state

    if (r.blocks) {
      for (let i = r.start; i < r.end; i++) {
        const index = r.blocks[i]
        const has = index < this._remoteContiguousLength || this.missingBlocks.get(index) === true
        if (has === true && this._requestRangeBlock(index, length)) return true
        this._maybeWant(index, r)
      }

      return false
    }

    this._populateRangeBatches(r)

    const end = this._getValidEnd(r.end)

    if (end <= r.start || fork !== this.remoteFork) return false

    for (let i = 0; i < r.batches.length; i++) {
      const b = r.batches[i]

      const batchStart = Math.max(b.batch * WANT_BATCH, r.start)
      const batchEnd = Math.min((b.batch + 1) * WANT_BATCH, end)
      const len = batchEnd - batchStart
      const off = batchStart + (r.linear ? 0 : Math.floor(Math.random() * len))

      if (
        this._requestRangeBatch(off, end, length) ||
        this._requestRangeBatch(batchStart, off, length)
      ) {
        return true
      }

      this._maybeWant(batchStart, b)
    }

    // Here we should consider making an OOB request (ie if the remote says they have a newer block)
    // but the upgrade code already does that, so no big deal for now

    return false
  }

  _requestForkProof(f) {
    if (!this.remoteLength) return
    if (this.replicator.pushOnly) return

    const req = this._makeRequest(false, 0, 0)
    if (req === null) return

    req.upgrade = { start: 0, length: this.remoteLength }
    req.manifest = !this.core.header.manifest

    f.inflight.push(req)
    this._send(req)
  }

  _requestForkRange(f) {
    if (f.fork !== this.remoteFork || f.batch.want === null) return false
    if (this.replicator.pushOnly) return false

    const end = Math.min(f.batch.want.end, this.remoteLength)
    if (end < f.batch.want.start) return false

    const len = end - f.batch.want.start
    const off = f.batch.want.start + Math.floor(Math.random() * len)

    for (let i = 0; i < len; i++) {
      let index = off + i
      if (index >= end) index -= len

      if (this._remoteHasBlock(index) === false) continue

      const req = this._makeRequest(false, 0, 0)
      if (req === null) return false

      req.hash = { index: 2 * index, nodes: f.batch.want.nodes }

      f.inflight.push(req)
      this._send(req)

      return true
    }

    this._maybeWantAnyRange(f.batch.want.start, len, f)
    return false
  }

  isActive() {
    if (this.paused || this.removed || this.core.header.frozen) return false
    return true
  }

  async _send(req) {
    const fork = this.core.state.fork

    this.inflight++
    this.replicator._inflight.add(req)

    if (req.upgrade !== null && req.fork === fork) {
      const u = this.replicator._addUpgrade()
      u.inflight.push(req)
    }

    try {
      if (req.block !== null && req.fork === fork) {
        req.block.nodes = await MerkleTree.missingNodes(
          this.core.state,
          2 * req.block.index,
          this.core.state.length
        )
        if (req.priority === PRIORITY.CANCELLED) return
      }
      if (req.hash !== null && req.fork === fork && req.hash.nodes === 0) {
        req.hash.nodes = await MerkleTree.missingNodes(
          this.core.state,
          req.hash.index,
          this.core.state.length
        )
        if (req.priority === PRIORITY.CANCELLED) return

        // nodes === 0, we already have it, bail
        if (req.hash.nodes === 0 && (req.hash.index & 1) === 0) {
          this.inflight--
          this.replicator._resolveHashLocally(this, req)
          return
        }
      }
    } catch (err) {
      this.stream.destroy(err)
      return
    }

    this.wireRequest.send(req)
    incrementTx(this.stats.wireRequest, this.replicator.stats.wireRequest)
  }
}

module.exports = class Replicator {
  static Peer = Peer // hack to be able to access Peer from outside this module

  constructor(
    core,
    {
      notDownloadingLinger = NOT_DOWNLOADING_SLACK,
      eagerUpgrade = true,
      allowFork = true,
      allowPush = false,
      alwaysLatestBlock = false,
      inflightRange = null
    } = {}
  ) {
    this.core = core
    this.eagerUpgrade = eagerUpgrade
    this.allowFork = allowFork
    this.allowPush = allowPush
    this.ondownloading = null // optional external hook for monitoring downloading status
    this.peers = []
    this.findingPeers = 0 // updatable from the outside
    this.destroyed = false
    this.downloading = false
    this.pushOnly = false
    this.activeSessions = 0

    this.hotswaps = new HotswapQueue()
    this.inflightRange = inflightRange || DEFAULT_MAX_INFLIGHT

    // Note: nodata and unwant not currently tracked
    // tx = transmitted, rx = received
    this.stats = {
      wireSync: { tx: 0, rx: 0 },
      wireRequest: { tx: 0, rx: 0 },
      wireCancel: { tx: 0, rx: 0 },
      wireData: { tx: 0, rx: 0 },
      wireWant: { tx: 0, rx: 0 },
      wireUnwant: { tx: 0, rx: 0 },
      wireBitfield: { tx: 0, rx: 0 },
      wireRange: { tx: 0, rx: 0 },
      wireExtension: { tx: 0, rx: 0 },
      hotswaps: 0,
      invalidData: 0,
      invalidRequests: 0,
      backoffs: 0,
      notAvailableBackoffs: 0
    }

    this._attached = new Set()
    this._inflight = new InflightTracker()
    this._blocks = new BlockTracker(this)
    this._hashes = new BlockTracker(this)

    this._alwaysLatestBlock = alwaysLatestBlock ? 1 : 0
    this._queued = []

    this._seeks = []
    this._upgrade = null
    this._reorgs = []
    this._ranges = []

    this._rxLock = new Mutex()
    this._txLock = new Mutex()

    this._hadPeers = false
    this._active = 0
    this._ifAvailable = 0
    this._updatesPending = 0
    this._applyingReorg = null
    this._manifestPeer = null
    this._notDownloadingLinger = notDownloadingLinger
    this._notDownloadingTimer = null

    const self = this
    this._onstreamclose = onstreamclose

    function onstreamclose() {
      self.detachFrom(this.userData)
    }
  }

  setInflightRange(min, max) {
    const def = this.inflightRange
    this.inflightRange = [min, max]
    for (const peer of this.peers) {
      if (peer.inflightRange !== def) continue
      peer.inflightRange = this.inflightRange
    }
  }

  updateActivity(inc, session) {
    this.activeSessions += inc
    this.setDownloading(this.activeSessions !== 0, session)
  }

  isDownloading() {
    return this.downloading || !this._inflight.idle
  }

  async push(index) {
    const all = []
    for (const peer of this.peers) {
      all.push(peer.push(index))
    }
    await Promise.all(all)
  }

  setAllowPush(allowPush) {
    if (allowPush === this.allowPush) return
    this.allowPush = allowPush
    for (const peer of this.peers) peer.sendSync()
  }

  isAllowingPush() {
    if (!this.allowPush) return false
    if (this._notDownloadingTimer) return false
    return this.downloading
  }

  setPushOnly(pushOnly) {
    if (pushOnly === this.pushOnly) return
    this.pushOnly = pushOnly
  }

  setDownloading(downloading) {
    const allowPush = this.isAllowingPush()
    const linger = this._notDownloadingLinger

    if (this._notDownloadingTimer) {
      clearTimeout(this._notDownloadingTimer)
      this._notDownloadingTimer = null
    }

    if (this.destroyed) return

    if (downloading || linger === 0) {
      if (!this._setDownloadingNow(downloading)) this.signalAllowPush(allowPush)
      return
    }

    this._notDownloadingTimer = setTimeout(setNotDownloadingLater, linger, this)
    if (this._notDownloadingTimer.unref) this._notDownloadingTimer.unref()
    this.signalAllowPush(allowPush)
  }

  signalAllowPush(allowPush) {
    if (allowPush === this.isAllowingPush()) return
    for (const peer of this.peers) peer.signalUpgrade()
  }

  _setDownloadingNow(downloading) {
    this._notDownloadingTimer = null

    if (this.downloading === downloading) return false
    this.downloading = downloading

    if (!downloading && this.isDownloading()) return false

    for (const peer of this.peers) peer.signalUpgrade()

    if (downloading) {
      // restart channel if needed...
      for (const protomux of this._attached) {
        if (!protomux.stream.handshakeHash) continue
        if (protomux.opened({ protocol: 'hypercore/alpha', id: this.core.discoveryKey })) continue
        this._makePeer(protomux, true)
      }
    } else {
      for (const peer of this.peers) peer.closeIfIdle()
    }

    if (this.ondownloading !== null && downloading) this.ondownloading()
    return true
  }

  cork() {
    for (const peer of this.peers) peer.protomux.cork()
  }

  uncork() {
    for (const peer of this.peers) peer.protomux.uncork()
  }

  // Called externally when a range of new blocks has been processed/removed
  onhave(start, length, drop = false) {
    for (const peer of this.peers) peer.broadcastRange(start, length, drop)
  }

  // Called externally when a truncation upgrade has been processed
  ontruncate(newLength, truncated) {
    const notify = []

    for (const blk of this._blocks) {
      if (blk.index < newLength) continue
      notify.push(blk)
    }

    for (const blk of notify) {
      for (const r of blk.refs) {
        if (r.snapshot === false) continue
        blk.detach(r, SNAPSHOT_NOT_AVAILABLE())
      }
    }

    for (const peer of this.peers) {
      peer.fullyDownloadedSignaled = Math.min(newLength, peer.fullyDownloadedSignaled)
      peer._unclearLocalRange(newLength, truncated)
    }
  }

  // Called externally when a upgrade has been processed
  onupgrade() {
    for (const peer of this.peers) peer.signalUpgrade()
    if (this._blocks.isEmpty() === false) this._resolveBlocksLocally()
    if (this._upgrade !== null) this._resolveUpgradeRequest(null)
    if (!this._blocks.isEmpty() || this._ranges.length !== 0 || this._seeks.length !== 0) {
      this._updateNonPrimary(true)
    }
  }

  // Called externally when a conflict has been detected and verified
  async onconflict() {
    const all = []
    for (const peer of this.peers) {
      all.push(peer._onconflict())
    }
    await Promise.allSettled(all)
  }

  async applyPendingReorg() {
    if (this._applyingReorg !== null) {
      await this._applyingReorg
      return true
    }

    for (let i = this._reorgs.length - 1; i >= 0; i--) {
      const f = this._reorgs[i]
      if (f.batch !== null && f.batch.finished) {
        await this._applyReorg(f)
        return true
      }
    }

    return false
  }

  addUpgrade(session) {
    if (this._upgrade !== null) {
      const ref = this._upgrade.attach(session)
      this._checkUpgradeIfAvailable()
      return ref
    }

    const ref = this._addUpgrade().attach(session)

    this.updateAll()

    return ref
  }

  addBlock(session, index, force) {
    const b = this._blocks.add(index, PRIORITY.HIGH, force)
    const ref = b.attach(session)

    this._queueBlock(b)
    this.updateAll()

    return ref
  }

  addSeek(session, seeker) {
    const s = new SeekRequest(this, this._seeks, seeker)
    const ref = s.attach(session)

    this._seeks.push(s)
    this.updateAll()

    return ref
  }

  addRange(
    session,
    { start = 0, end = -1, length = toLength(start, end), blocks = null, linear = false } = {}
  ) {
    if (blocks !== null) {
      // if using blocks, start, end just acts as frames around the blocks array
      start = 0
      end = length = blocks.length
    }

    const r = new RangeRequest(
      this,
      this._ranges,
      start,
      length === -1 ? -1 : start + length,
      linear,
      blocks
    )

    const ref = r.attach(session)

    // Trigger this to see if this is already resolved...
    // Also auto compresses the range based on local bitfield
    clampRange(this.core, r)

    if (r.end !== -1 && r.start >= r.end) {
      this._resolveRangeRequest(r)
      return ref
    }

    this.updateAll()

    return ref
  }

  cancel(ref) {
    ref.context.detach(ref, null)
  }

  static clearRequests(session, err) {
    if (session.length === 0) return
    if (session.length === 1 && session[0] === null) return

    const updated = new Set()

    while (session.length > 0) {
      const ref = session[session.length - 1]
      updated.add(ref.context.replicator)
      ref.context.detach(ref, err)
    }

    for (const replicator of updated) {
      replicator.updateAll()
    }
  }

  clearRequests(session, err = null) {
    let cleared = false
    while (session.length > 0) {
      const ref = session[session.length - 1]
      ref.context.detach(ref, err)
      cleared = true
    }

    if (cleared) this.updateAll()
  }

  _matchingRequest(req, data) {
    if (this.allowPush) {
      return true
    }
    if (data.block !== null && (req.block === null || req.block.index !== data.block.index)) {
      return false
    }
    if (data.hash !== null && (req.hash === null || req.hash.index !== data.hash.index)) {
      return false
    }
    if (data.seek !== null && (req.seek === null || req.seek.bytes !== data.seek.bytes)) {
      return false
    }
    if (data.upgrade !== null && req.upgrade === null) {
      return false
    }
    return req.fork === data.fork
  }

  _addUpgradeMaybe() {
    return this.eagerUpgrade === true ? this._addUpgrade() : this._upgrade
  }

  // TODO: this function is OVER called atm, at each updatePeer/updateAll
  // instead its more efficient to only call it when the conditions in here change - ie on sync/add/remove peer
  // Do this when we have more tests.
  _checkUpgradeIfAvailable() {
    if (this._ifAvailable > 0 && this.peers.length < MAX_PEERS_UPGRADE) return
    if (this._upgrade === null || this._upgrade.refs.length === 0) return
    if (this._hadPeers === false && this.findingPeers > 0) return

    const maxPeers = Math.min(this.peers.length, MAX_PEERS_UPGRADE)

    // check if a peer can upgrade us

    for (let i = 0; i < maxPeers; i++) {
      const peer = this.peers[i]

      if (peer.remoteSynced === false) return

      if (this.core.state.length === 0 && peer.remoteLength > 0) return

      if (peer.remoteLength <= this._upgrade.length || peer.remoteFork !== this._upgrade.fork) {
        continue
      }

      if (peer.syncsProcessing > 0) return

      if (peer.lengthAcked !== this.core.state.length && peer.remoteFork === this.core.state.fork) {
        return
      }

      if (peer.remoteCanUpgrade === true) return
    }

    // check if reorgs in progress...

    if (this._applyingReorg !== null) return

    // TODO: we prob should NOT wait for inflight reorgs here, seems better to just resolve the upgrade
    // and then apply the reorg on the next call in case it's slow - needs some testing in practice

    for (let i = 0; i < this._reorgs.length; i++) {
      const r = this._reorgs[i]
      if (r.inflight.length > 0) return
    }

    // if something is inflight, wait for that first
    if (this._upgrade.inflight.length > 0) return

    // nothing to do, indicate no update avail

    const u = this._upgrade
    this._upgrade = null
    u.resolve(false)
  }

  _addUpgrade() {
    if (this._upgrade !== null) return this._upgrade

    // TODO: needs a reorg: true/false flag to indicate if the user requested a reorg
    this._upgrade = new UpgradeRequest(this, this.core.state.fork, this.core.state.length)

    return this._upgrade
  }

  _addReorg(fork, peer) {
    if (this.allowFork === false) return null

    // TODO: eager gc old reorgs from the same peer
    // not super important because they'll get gc'ed when the request finishes
    // but just spam the remote can do ...

    for (const f of this._reorgs) {
      if (f.fork > fork && f.batch !== null) return null
      if (f.fork === fork) return f
    }

    const f = new ForkRequest(this, fork)

    this._reorgs.push(f)

    // maintain sorted by fork
    let i = this._reorgs.length - 1
    while (i > 0 && this._reorgs[i - 1].fork > fork) {
      this._reorgs[i] = this._reorgs[i - 1]
      this._reorgs[--i] = f
    }

    return f
  }

  _shouldUpgrade(peer) {
    if (this._upgrade !== null && this._upgrade.inflight.length > 0) return false
    return (
      peer.remoteCanUpgrade === true &&
      peer.remoteLength > this.core.state.length &&
      peer.lengthAcked === this.core.state.length
    )
  }

  _autoUpgrade(peer) {
    return (
      this._upgrade !== null &&
      peer.remoteFork === this.core.state.fork &&
      this._shouldUpgrade(peer)
    )
  }

  _addPeer(peer) {
    this._hadPeers = true
    this.peers.push(peer)
    this.updatePeer(peer)
    this._onpeerupdate(true, peer)
  }

  _requestDone(id, roundtrip) {
    this._inflight.remove(id, roundtrip)
    if (this.isDownloading() === true) return
    for (const peer of this.peers) peer.signalUpgrade()
  }

  _removePeer(peer) {
    this.peers.splice(this.peers.indexOf(peer), 1)
    peer.wants.destroy()

    if (this._manifestPeer === peer) this._manifestPeer = null

    let inflight = false
    for (const req of this._inflight) {
      if (req.peer !== peer) continue
      inflight = true
      this._inflight.remove(req.id, true)
      this._clearRequest(peer, req)
    }

    this._onpeerupdate(false, peer)
    if (inflight) {
      this.updateAll()
    } else {
      this._checkUpgradeIfAvailable()
    }
  }

  _queueBlock(b) {
    if (b.inflight.length > 0 || b.queued === true) return
    b.queued = true
    this._queued.push(b)
  }

  _resolveHashLocally(peer, req) {
    this._requestDone(req.id, false)
    this._resolveBlockRequest(this._hashes, req.hash.index / 2, null, req)
    this.updatePeer(peer)
  }

  // Runs in the background - not allowed to throw
  async _resolveBlocksLocally() {
    // TODO: check if fork compat etc. Requires that we pass down truncation info

    const clear = []
    const blocks = []

    const reader = this.core.storage.read()
    for (const b of this._blocks) {
      if (this.core.bitfield.get(b.index) === false) continue
      blocks.push(this._resolveLocalBlock(b, reader, clear))
    }
    reader.tryFlush()

    await Promise.all(blocks)

    if (!clear.length) return

    // Currently the block tracker does not support deletes during iteration, so we make
    // sure to clear them afterwards.
    for (const b of clear) {
      this._blocks.remove(b.index)
      removeHotswap(b)
    }
  }

  async _resolveLocalBlock(b, reader, resolved) {
    try {
      b.resolve(await reader.getBlock(b.index))
    } catch (err) {
      b.reject(err)
      return
    }

    resolved.push(b)
  }

  _resolveBlockRequest(tracker, index, value, req) {
    const b = tracker.remove(index)
    if (b === null) return false

    removeInflight(b.inflight, req)
    removeHotswap(b)
    b.queued = false

    b.resolve(value)

    if (b.inflight.length > 0) {
      // if anything is still inflight, cancel it
      for (let i = b.inflight.length - 1; i >= 0; i--) {
        const req = b.inflight[i]
        req.peer._cancelRequest(req)
      }
    }

    return true
  }

  _resolveUpgradeRequest(req) {
    if (req !== null) removeInflight(this._upgrade.inflight, req)

    if (
      this.core.state.length === this._upgrade.length &&
      this.core.state.fork === this._upgrade.fork
    ) {
      return false
    }

    const u = this._upgrade
    this._upgrade = null
    u.resolve(true)

    return true
  }

  _resolveRangeRequest(req) {
    req.resolve(true)
    req.gc()
  }

  _clearInflightBlock(tracker, req) {
    const isBlock = tracker === this._blocks
    const index = isBlock === true ? req.block.index : req.hash.index / 2
    const b = tracker.get(index)

    if (b === null || removeInflight(b.inflight, req) === false) return

    if (removeHotswap(b) === true && b.inflight.length > 0) {
      this.hotswaps.add(b)
    }

    if (b.refs.length > 0 && isBlock === true) {
      this._queueBlock(b)
      return
    }

    b.gc()
  }

  _clearInflightUpgrade(req) {
    if (this._upgrade === null || removeInflight(this._upgrade.inflight, req) === false) return
    this._upgrade.gc()
  }

  _clearInflightSeeks(req) {
    for (const s of this._seeks) {
      if (removeInflight(s.inflight, req) === false) continue
      s.gc()
    }
  }

  _clearInflightReorgs(req) {
    for (const r of this._reorgs) {
      removeInflight(r.inflight, req)
    }
  }

  _clearOldReorgs(fork) {
    for (let i = 0; i < this._reorgs.length; i++) {
      const f = this._reorgs[i]
      if (f.fork >= fork) continue
      if (i === this._reorgs.length - 1) this._reorgs.pop()
      else this._reorgs[i] = this._reorgs.pop()
      i--
    }
  }

  // "slow" updates here - async but not allowed to ever throw
  async _updateNonPrimary(updateAll) {
    // Check if running, if so skip it and the running one will issue another update for us (debounce)
    while (++this._updatesPending === 1) {
      let len = Math.min(MAX_RANGES, this._ranges.length)

      for (let i = 0; i < len; i++) {
        const r = this._ranges[i]

        clampRange(this.core, r)

        if (r.end !== -1 && r.start >= r.end) {
          this._resolveRangeRequest(r)
          i--
          if (len > this._ranges.length) len--
          if (this._ranges.length === MAX_RANGES) updateAll = true
        }
      }

      for (let i = 0; i < this._seeks.length; i++) {
        const s = this._seeks[i]

        let err = null
        let res = null

        try {
          res = await s.seeker.update()
        } catch (error) {
          err = error
        }

        if (!res && !err) continue

        if (i < this._seeks.length - 1) this._seeks[i] = this._seeks.pop()
        else this._seeks.pop()

        i--

        if (err) s.reject(err)
        else s.resolve(res)
      }

      // No additional updates scheduled - break
      if (--this._updatesPending === 0) break
      // Debounce the additional updates - continue
      this._updatesPending = 0
    }

    if (this._inflight.idle || updateAll) this.updateAll()
  }

  _clearRequest(peer, req) {
    if (req.block !== null) {
      this._clearInflightBlock(this._blocks, req)
      this._unmarkInflight(req.block.index)
    }

    if (req.hash !== null) {
      this._clearInflightBlock(this._hashes, req)
    }

    if (req.upgrade !== null && this._upgrade !== null) {
      this._clearInflightUpgrade(req)
    }

    if (this._seeks.length > 0) {
      this._clearInflightSeeks(req)
    }

    if (this._reorgs.length > 0) {
      this._clearInflightReorgs(req)
    }
  }

  _onnodata(peer, req, reason) {
    if (reason === NOT_AVAILABLE) {
      peer.stats.notAvailableBackoffs++
      this.stats.notAvailableBackoffs++

      if (peer.stats.notAvailableBackoffs >= MAX_BACKOFFS) {
        peer.paused = true
      }
    }

    if (reason === INVALID_REQUEST) {
      peer.stats.backoffs++
      this.stats.backoffs++

      if (peer.stats.backoffs >= MAX_BACKOFFS) {
        peer.paused = true
      }
    }

    if (req) {
      this._clearRequest(peer, req)
    }

    this.updateAll()
  }

  _openSkipBitfield() {
    // technically the skip bitfield gets bits cleared if .clear() is called
    // also which might be in inflight also, but that just results in that section being overcalled shortly
    // worst case, so ok for now

    const bitfield = this.core.openSkipBitfield()

    for (const req of this._inflight) {
      if (req.block) bitfield.set(req.block.index, true) // skip
    }
  }

  _markProcessing(index) {
    const b = this._blocks.get(index)
    if (b) {
      b.processing = true
      return
    }

    const h = this._hashes.get(index)
    if (h) h.processing = true
  }

  _markProcessed(index) {
    const b = this._blocks.get(index)
    if (b) return b.processed()

    const h = this._hashes.get(index)
    if (h) h.processed()
  }

  _markInflight(index) {
    if (this.core.skipBitfield !== null) this.core.skipBitfield.set(index, true)
    for (const peer of this.peers) peer._markInflight(index)
  }

  _unmarkInflight(index) {
    if (this.core.skipBitfield !== null) {
      this.core.skipBitfield.set(index, this.core.bitfield.get(index))
    }
    for (const peer of this.peers) peer._resetMissingBlock(index)
  }

  _ondata(peer, req, data) {
    if (req) {
      req.elapsed = Date.now() - req.timestamp
    }

    if (data.block !== null) {
      this._resolveBlockRequest(this._blocks, data.block.index, data.block.value, req)
      this._ondownload(data.block.index, data.block.value.byteLength, peer, req)
    }

    if (data.hash !== null && (data.hash.index & 1) === 0) {
      this._resolveBlockRequest(this._hashes, data.hash.index / 2, null, req)
    }

    if (this._upgrade !== null) {
      this._resolveUpgradeRequest(req)
    }

    if (this._seeks.length > 0) {
      this._clearInflightSeeks(req)
    }

    if (this._reorgs.length > 0) {
      this._clearInflightReorgs(req)
    }

    if (this._manifestPeer === peer && this.core.header.manifest !== null) {
      this._manifestPeer = null
    }

    if (this._seeks.length > 0 || this._ranges.length > 0) {
      this._updateNonPrimary(this._seeks.length > 0)
    }

    this.updatePeer(peer)
  }

  _onwant(peer, start, length, any) {
    if (!peer.isActive()) return

    const contig = Math.min(this.core.state.length, this.core.header.hints.contiguousLength)

    if (start + length < contig || this.core.state.length === contig || (any && start < contig)) {
      peer.wireRange.send({
        drop: false,
        start: 0,
        length: contig
      })
      incrementTx(peer.stats.wireRange, this.stats.wireRange)
      return
    }

    length = Math.min(length, this.core.state.length - start)

    if (any) {
      const bit = this.core.bitfield.firstSet(start)
      if (bit > -1 && bit < start + length) {
        peer.wireRange.send({
          drop: false,
          start: bit,
          length: 1
        })
      }
      return
    }

    for (const msg of this.core.bitfield.want(start, length)) {
      peer.wireBitfield.send(msg)
      incrementTx(peer.stats.wireBitfield, this.stats.wireBitfield)
    }
  }

  async _onreorgdata(peer, req, data) {
    const newBatch = data.upgrade && (await this.core.verifyReorg(data))
    const f = this._addReorg(data.fork, peer)

    if (f === null) {
      this.updateAll()
      return
    }

    removeInflight(f.inflight, req)

    if (f.batch) {
      await f.batch.update(data)
    } else if (data.upgrade) {
      f.batch = newBatch

      // Remove "older" reorgs in progress as we just verified this one.
      this._clearOldReorgs(f.fork)
    }

    if (f.batch && f.batch.finished) {
      if (this._addUpgradeMaybe() !== null) {
        await this._applyReorg(f)
      }
    }

    this.updateAll()
  }

  // Never throws, allowed to run in the background
  async _applyReorg(f) {
    // TODO: more optimal here to check if potentially a better reorg
    // is available, ie higher fork, and request that one first.
    // This will request that one after this finishes, which is fine, but we
    // should investigate the complexity in going the other way

    const u = this._upgrade
    const old = this._reorgs

    this._reorgs = [] // clear all as the nodes are against the old tree - easier
    this._applyingReorg = this.core.reorg(f.batch, null) // TODO: null should be the first/last peer?

    try {
      await this._applyingReorg
    } catch (err) {
      this._upgrade = null
      u.reject(err)
    }

    this._applyingReorg = null

    if (this._upgrade !== null) {
      this._resolveUpgradeRequest(null)
    }

    for (const peer of this.peers) this._updateFork(peer)

    // TODO: all the remaining is a tmp workaround until we have a flag/way for ANY_FORK
    for (const r of this._ranges) {
      r.start = r.userStart
      r.end = r.userEnd
    }

    for (const f of old) f.resolve()
    f.resolve()

    this.updateAll()
  }

  _maybeUpdate() {
    return this._upgrade !== null && this._upgrade.inflight.length === 0
  }

  _maybeRequestManifest() {
    return this.core.header.manifest === null && this._manifestPeer === null
  }

  _updateFork(peer) {
    if (
      this._applyingReorg !== null ||
      this.allowFork === false ||
      peer.remoteFork <= this.core.state.fork
    ) {
      return false
    }

    const f = this._addReorg(peer.remoteFork, peer)

    // TODO: one per peer is better
    if (f !== null && f.batch === null && f.inflight.length === 0) {
      return peer._requestForkProof(f)
    }

    return false
  }

  _updateHotswap(peer) {
    const maxHotswaps = peer.getMaxHotswapInflight()
    if (!peer.isActive() || peer.inflight >= maxHotswaps) return

    for (const b of this.hotswaps.pick(peer)) {
      if (peer._requestBlock(b) === false) continue
      peer.stats.hotswaps++
      peer.replicator.stats.hotswaps++
      if (peer.inflight >= maxHotswaps) break
    }
  }

  _updatePeer(peer) {
    if (!peer.isActive() || peer.inflight >= peer.getMaxInflight() || !peer.remoteUploading) {
      return false
    }

    // Eagerly request the manifest even if the remote length is 0. If not 0 we'll get as part of the upgrade request...
    if (
      this._maybeRequestManifest() === true &&
      peer.remoteLength === 0 &&
      peer.remoteHasManifest === true
    ) {
      this._manifestPeer = peer
      peer._requestManifest()
    }

    for (const s of this._seeks) {
      if (s.inflight.length > 0) continue // TODO: one per peer is better
      if (peer._requestSeek(s) === true) {
        return true
      }
    }

    // Implied that any block in the queue should be requested, no matter how many inflights
    const blks = new RandomIterator(this._queued)

    for (const b of blks) {
      if (b.queued === false || peer._requestBlock(b) === true) {
        b.queued = false
        blks.dequeue()
        return true
      }
    }

    return false
  }

  _updatePeerNonPrimary(peer) {
    if (!peer.isActive() || peer.inflight >= peer.getMaxInflight() || !peer.remoteUploading) {
      return false
    }

    const ranges = new RandomIterator(this._ranges)
    let tried = 0

    for (const r of ranges) {
      if (peer._requestRange(r) === true) {
        return true
      }
      if (++tried >= MAX_RANGES) break
    }

    // Iterate from newest fork to oldest fork...
    for (let i = this._reorgs.length - 1; i >= 0; i--) {
      const f = this._reorgs[i]
      if (f.batch !== null && f.inflight.length === 0 && peer._requestForkRange(f) === true) {
        return true
      }
    }

    if (this._maybeUpdate() === true && peer._requestUpgrade(this._upgrade) === true) {
      return true
    }

    return false
  }

  updatePeer(peer) {
    // Quick shortcut to wait for flushing reorgs - not needed but less waisted requests
    if (this._applyingReorg !== null) return

    while (this._updatePeer(peer) === true);
    while (this._updatePeerNonPrimary(peer) === true);

    if (this.peers.length > 1 && this._blocks.isEmpty() === false) {
      this._updateHotswap(peer)
    }

    this._checkUpgradeIfAvailable()
  }

  updateAll() {
    // Quick shortcut to wait for flushing reorgs - not needed but less waisted requests
    if (this._applyingReorg !== null) return

    const peers = new RandomIterator(this.peers)

    for (const peer of peers) {
      if (this._updatePeer(peer) === true) {
        peers.requeue()
      }
    }

    // Check if we can skip the non primary check fully
    if (this._maybeUpdate() === false && this._ranges.length === 0 && this._reorgs.length === 0) {
      this._checkUpgradeIfAvailable()
      return
    }

    for (const peer of peers.restart()) {
      if (this._updatePeerNonPrimary(peer) === true) {
        peers.requeue()
      }
    }

    this._checkUpgradeIfAvailable()
  }

  onpeerdestroy() {
    if (--this._active === 0) this.core.checkIfIdle()
  }

  attached(protomux) {
    return this._attached.has(protomux)
  }

  attachTo(protomux) {
    if (this.core.closed) return

    const makePeer = this._makePeer.bind(this, protomux)

    this._attached.add(protomux)
    protomux.pair({ protocol: 'hypercore/alpha', id: this.core.discoveryKey }, makePeer)
    protomux.stream.setMaxListeners(0)
    protomux.stream.on('close', this._onstreamclose)

    this._ifAvailable++
    this._active++

    protomux.stream.opened.then((opened) => {
      this._ifAvailable--
      this._active--

      if (opened && !this.destroyed) makePeer()
      this._checkUpgradeIfAvailable()

      this.core.checkIfIdle()
    })
  }

  detachFrom(protomux) {
    if (this._attached.delete(protomux)) {
      protomux.stream.removeListener('close', this._onstreamclose)
      protomux.unpair({ protocol: 'hypercore/alpha', id: this.core.discoveryKey })
    }
  }

  idle() {
    return this.peers.length === 0 && this._active === 0
  }

  close() {
    const waiting = []

    for (const peer of this.peers) {
      waiting.push(peer.channel.fullyClosed())
    }

    this.destroy()
    return Promise.all(waiting)
  }

  destroy() {
    if (this.destroyed) return
    this.destroyed = true

    if (this._notDownloadingTimer) {
      clearTimeout(this._notDownloadingTimer)
      this._notDownloadingTimer = null
    }

    while (this.peers.length) {
      const peer = this.peers[this.peers.length - 1]
      this.detachFrom(peer.protomux)
      peer.channel.close() // peer is removed from array in onclose
    }

    for (const protomux of this._attached) {
      this.detachFrom(protomux)
    }
  }

  _makePeer(protomux) {
    const replicator = this
    if (protomux.opened({ protocol: 'hypercore/alpha', id: this.core.discoveryKey })) {
      return onnochannel()
    }

    const channel = protomux.createChannel({
      userData: null,
      protocol: 'hypercore/alpha',
      aliases: ['hypercore'],
      id: this.core.discoveryKey,
      handshake: m.wire.handshake,
      messages: [
        { encoding: m.wire.sync, onmessage: onwiresync },
        { encoding: m.wire.request, onmessage: onwirerequest },
        { encoding: m.wire.cancel, onmessage: onwirecancel },
        { encoding: m.wire.data, onmessage: onwiredata },
        { encoding: m.wire.noData, onmessage: onwirenodata },
        { encoding: m.wire.want, onmessage: onwirewant },
        { encoding: m.wire.unwant, onmessage: onwireunwant },
        { encoding: m.wire.bitfield, onmessage: onwirebitfield },
        { encoding: m.wire.range, onmessage: onwirerange },
        { encoding: m.wire.extension, onmessage: onwireextension }
      ],
      onopen: onwireopen,
      onclose: onwireclose,
      ondrain: onwiredrain,
      ondestroy: onwiredestroy
    })

    if (channel === null) return onnochannel()

    const peer = new Peer(replicator, protomux, channel, this.inflightRange)
    const stream = protomux.stream

    peer.channel.open({
      seeks: true,
      capability: caps.replicate(stream.isInitiator, this.core.key, stream.handshakeHash)
    })

    return true

    function onnochannel() {
      return false
    }
  }

  _onpeerupdate(added, peer) {
    const name = added ? 'peer-add' : 'peer-remove'
    const sessions = this.core.monitors

    for (let i = sessions.length - 1; i >= 0; i--) {
      sessions[i].emit(name, peer)

      if (added) {
        for (const ext of sessions[i].extensions.values()) {
          peer.extensions.set(ext.name, ext)
        }
      }
    }
  }

  _ondownload(index, byteLength, from, req) {
    const sessions = this.core.monitors

    for (let i = sessions.length - 1; i >= 0; i--) {
      const s = sessions[i]
      s.emit('download', index, byteLength - s.padding, from, req)
    }
  }

  _onupload(index, byteLength, from) {
    const sessions = this.core.monitors

    for (let i = sessions.length - 1; i >= 0; i--) {
      const s = sessions[i]
      s.emit('upload', index, byteLength - s.padding, from)
    }
  }

  _oninvaliddata(err, req, res, from) {
    const sessions = this.core.monitors

    this.stats.invalidData++
    from.stats.invalidData++
    for (let i = 0; i < sessions.length; i++) {
      sessions[i].emit('verification-error', err, req, res, from)
    }
  }

  _oninvalidrequest(err, req, from) {
    const sessions = this.core.monitors

    from.stats.invalidRequests++
    this.stats.invalidRequests++
    for (let i = 0; i < sessions.length; i++) {
      sessions[i].emit('invalid-request', err, req, from)
    }
  }
}

function removeHotswap(block) {
  if (block.hotswap === null) return false
  block.hotswap.ref.remove(block)
  return true
}

function removeInflight(inf, req) {
  const i = inf.indexOf(req)
  if (i === -1) return false
  if (i < inf.length - 1) inf[i] = inf.pop()
  else inf.pop()
  return true
}

function toLength(start, end) {
  return end === -1 ? -1 : end < start ? 0 : end - start
}

function clampRange(core, r) {
  if (r.blocks === null) {
    const start = core.bitfield.firstUnset(r.start)

    if (r.end === -1) r.start = start === -1 ? core.state.length : start
    else if (start === -1 || start >= r.end) r.start = r.end
    else {
      r.start = start

      const end = core.bitfield.lastUnset(r.end - 1)

      if (end === -1 || start >= end + 1) r.end = r.start
      else r.end = end + 1
    }
  } else {
    while (r.start < r.end && core.bitfield.get(r.blocks[r.start])) r.start++
    while (r.start < r.end && core.bitfield.get(r.blocks[r.end - 1])) r.end--
  }
}

function onrequesttimeout(req) {
  if (req.context) req.context.detach(req, REQUEST_TIMEOUT())
}

function destroyRequestTimeout(req) {
  if (req.timeout !== null) {
    clearTimeout(req.timeout)
    req.timeout = null
  }
}

function isCriticalError(err) {
  // TODO: expose .critical or similar on the hypercore errors that are critical (if all not are)
  return err.name === 'HypercoreError'
}

function onwireopen(m, c) {
  return c.userData.onopen(m)
}

function onwireclose(isRemote, c) {
  return c.userData.onclose(isRemote)
}

function onwiredestroy(c) {
  c.userData.replicator.onpeerdestroy()
}

function onwiredrain(c) {
  return c.userData.ondrain()
}

function onwiresync(m, c) {
  incrementRx(c.userData.stats.wireSync, c.userData.replicator.stats.wireSync)
  return c.userData.onsync(m)
}

function onwirerequest(m, c) {
  incrementRx(c.userData.stats.wireRequest, c.userData.replicator.stats.wireRequest)
  return c.userData.onrequest(m)
}

function onwirecancel(m, c) {
  incrementRx(c.userData.stats.wireCancel, c.userData.replicator.stats.wireCancel)
  return c.userData.oncancel(m)
}

function onwiredata(m, c) {
  incrementRx(c.userData.stats.wireData, c.userData.replicator.stats.wireData)
  return c.userData.ondata(m)
}

function onwirenodata(m, c) {
  return c.userData.onnodata(m)
}

function onwirewant(m, c) {
  incrementRx(c.userData.stats.wireWant, c.userData.replicator.stats.wireWant)
  return c.userData.onwant(m)
}

function onwireunwant(m, c) {
  return c.userData.onunwant(m)
}

function onwirebitfield(m, c) {
  incrementRx(c.userData.stats.wireBitfield, c.userData.replicator.stats.wireBitfield)
  return c.userData.onbitfield(m)
}

function onwirerange(m, c) {
  incrementRx(c.userData.stats.wireRange, c.userData.replicator.stats.wireRange)
  return c.userData.onrange(m)
}

function onwireextension(m, c) {
  incrementRx(c.userData.stats.wireExtension, c.userData.replicator.stats.wireExtension)
  return c.userData.onextension(m)
}

function setNotDownloadingLater(repl, session) {
  repl._setDownloadingNow(false, session)
}

function isBlockRequest(req) {
  return req !== null && req.block !== null
}

function isUpgradeRequest(req) {
  return req !== null && req.upgrade !== null
}

function incrementTx(stats1, stats2) {
  stats1.tx++
  stats2.tx++
}

function incrementRx(stats1, stats2) {
  stats1.rx++
  stats2.rx++
}

function noop() {}

function backoff(times) {
  const sleep = times < 2 ? 200 : times < 5 ? 500 : times < 40 ? 1000 : 5000
  return new Promise((resolve) => setTimeout(resolve, sleep))
}
const crypto = require('hypercore-crypto')
const b4a = require('b4a')
const assert = require('nanoassert')
const flat = require('flat-tree')
const quickbit = require('quickbit-universal')
const HypercoreStorage = require('hypercore-storage')

const {
  INVALID_OPERATION,
  INVALID_SIGNATURE,
  ASSERTION,
  SESSION_CLOSED,
  SESSION_NOT_WRITABLE
} = require('hypercore-errors')

const Mutex = require('./mutex')
const Bitfield = require('./bitfield')
const { MerkleTree, MerkleTreeBatch } = require('./merkle-tree')

class SessionState {
  constructor(core, parent, storage, treeInfo, name) {
    this.core = core
    this.index = this.core.sessionStates.push(this) - 1

    this.storage = storage
    this.name = name
    this.sessions = []

    // small hack to close old storages as late as possible.
    // TODO: add a read lock so we can avoid that
    this.lingers = null

    this.parent = parent
    this.atomized = null
    this.mutex = new Mutex()

    // merkle state
    this.roots = treeInfo.roots.length ? treeInfo.roots : []
    this.fork = treeInfo.fork || 0
    this.length = this.roots.length ? MerkleTree.span(this.roots) / 2 : treeInfo.length
    this.byteLength = MerkleTree.size(this.roots)
    this.prologue = treeInfo.prologue || null
    this.signature = treeInfo.signature || null

    this.snapshotCompatLength = this.isSnapshot()
      ? Math.min(this.length, this.core.state.length)
      : -1
    this.lastTruncation = null

    this.active = 0

    this._activeTx = null
    this._pendingBitfield = null

    this.ref()
  }

  static RECOVERY_PEERS = null

  isSnapshot() {
    return this.storage.snapshotted
  }

  isDefault() {
    return this.core.state === this || this.isAtomicDefault()
  }

  isAtomicDefault() {
    return !!this.storage.atom && !!this.parent && this.parent.isDefault()
  }

  createTreeBatch() {
    return new MerkleTreeBatch(this)
  }

  addSession(s) {
    if (s._stateIndex !== -1) return
    s._stateIndex = this.sessions.push(s) - 1
    if (s.weak === false) this.core.activeSessions++
  }

  removeSession(s) {
    if (s._stateIndex === -1) return
    const head = this.sessions.pop()
    if (head !== s) this.sessions[(head._stateIndex = s._stateIndex)] = head
    s._stateIndex = -1
    if (s.weak === false) this.core.activeSessions--
    this.core.checkIfIdle()
  }

  flushedLength() {
    if (this.isDefault() || this.isSnapshot()) return this.length
    const deps = this.storage.dependencies
    if (deps.length) return deps[deps.length - 1].length
    return 0
  }

  signedLength() {
    const l = Math.min(this.flushedLength(), this.core.state.length)
    return this.isSnapshot() && l > this.snapshotCompatLength ? this.snapshotCompatLength : l
  }

  unref() {
    if (--this.active > 0) return
    this.close().catch(noop) // technically async, but only for the last db session
  }

  ref() {
    this.active++
    return this
  }

  hash() {
    return MerkleTree.hash(this)
  }

  setRoots(roots) {
    this.roots = roots
    this.length = MerkleTree.span(roots) / 2
    this.byteLength = MerkleTree.size(roots)
  }

  get encryptionFork() {
    return this.core.header.tree.fork
  }

  async _updateSnapshotStorage(storage) {
    if (!this.atomized || !this.atomized.flushing) return this.treeInfo()
    while (this.atomized.flushing) await this.atomized.flushed()

    let rx = storage.read()
    const headPromise = rx.getHead()
    const authPromise = rx.getAuth()
    const depPromise = rx.getDependency()

    rx.tryFlush()
    const [head, auth, dep] = await Promise.all([headPromise, authPromise, depPromise])

    storage.setDependencyHead(dep)

    const fork = head ? head.fork : 0
    const length = head ? head.length : 0

    rx = storage.read()
    const rootPromises = []
    for (const r of flat.fullRoots(length * 2)) {
      rootPromises.push(rx.getTreeNode(r))
    }

    rx.tryFlush()

    const roots = await Promise.all(rootPromises)

    // dbl check if we are hitting an regression from earler
    for (const root of roots) {
      if (root === null) {
        throw new Error(
          'Bad snapshot from atomized session, id = ' +
            this.core.id +
            ' length = ' +
            length +
            ' fork = ' +
            fork
        )
      }
    }

    return {
      fork,
      roots,
      length,
      prologue: auth.manifest && auth.manifest.prologue,
      signature: head && head.signature
    }
  }

  treeInfo() {
    return {
      fork: this.fork,
      roots: this.roots.slice(),
      length: this.length,
      prologue: this.prologue,
      signature: this.signature
    }
  }

  async close() {
    if (this.index === -1) return

    this.active = 0
    this.mutex.destroy(new Error('Closed')).catch(noop)
    if (this.parent && this.parent.atomized) this.parent.atomized = null

    const closing = this.storage.close()

    const head = this.core.sessionStates.pop()
    if (head !== this) this.core.sessionStates[(head.index = this.index)] = head

    this.index = -1
    this.core.checkIfIdle()

    if (this.lingers !== null) {
      for (const storage of this.lingers) await storage.close()
    }

    return closing
  }

  async snapshot() {
    const storage = this.storage.snapshot()
    const treeInfo = await this._updateSnapshotStorage(storage)

    return new SessionState(this.core, null, storage, treeInfo, this.name)
  }

  updateDependency(tx, length) {
    const dependency = updateDependency(this, length, false)
    if (dependency) tx.setDependency(dependency)
    return dependency
  }

  updateGroupIndex(tx, tree) {
    const { pointer } = this.core.header.group

    tx.deleteGroupUpdate(pointer, this.core.header.tree.timestamp)
    tx.putGroupUpdate(pointer, tree.timestamp, this.core.header.key)
    this.core.ongroupupdate(this.core.header.group.key, {
      key: this.core.key,
      length: tree.length,
      fork: tree.fork
    })
  }

  _clearActiveBatch() {
    this._activeTx = null
  }

  createWriteBatch() {
    assert(!this._activeTx && !this.storage.snapshotted)

    this._activeTx = this.storage.write()
    return this._activeTx
  }

  _unlock() {
    this._clearActiveBatch()
    this.mutex.unlock()
    this.core.checkIfIdle()
  }

  async flush() {
    const tx = this._activeTx
    this._activeTx = null

    try {
      if (!(await tx.flush())) return false
    } finally {
      this._clearActiveBatch()
    }

    this.lastTruncation = null
    return true
  }

  _precommit(state) {
    assert(
      state.parent === this && state.storage.core.dataPointer === this.storage.core.dataPointer,
      'Atomic state must flush to parent'
    )
  }

  async _commit() {
    await this.mutex.lock()

    try {
      const bitfield = this._pendingBitfield
      this._pendingBitfield = null
      this.lastTruncation = null
      await this.parent._oncommit(this, bitfield)
    } finally {
      this.mutex.unlock()
    }
  }

  async _oncommit(src, bitfield) {
    await this.mutex.lock()

    try {
      const currLength = this.length

      // load dependency into memory
      const rx = this.storage.read()
      const dependencyPromise = rx.getDependency()

      rx.tryFlush()

      const dependency = await dependencyPromise

      this.fork = src.fork
      this.length = src.length
      this.byteLength = src.byteLength
      this.roots = src.roots.slice()
      this.signature = src.signature

      const tree = {
        fork: this.fork,
        length: this.length,
        rootHash: this.hash(),
        signature: this.signature,
        timestamp: Date.now()
      }

      if (this.isDefault() && this.core.header.group) {
        const tx = await this.createWriteBatch()
        this.updateGroupIndex(tx, tree)
        await tx.flush()
      }

      if (dependency) this.storage.setDependencyHead(dependency)

      const b = bitfield

      if (b && b.truncated && b.start < currLength) {
        this.ontruncate(tree, b.start, currLength, true)
        if (!b || b.appends === 0) return
      }

      const append = b ? { start: b.start, length: b.appends, drop: false } : null

      this.onappend(tree, append, true)

      if (this.core.hintsChanged && this.isDefault()) await this.core.flushHints()
    } finally {
      this._unlock()
    }
  }

  async setUserData(key, value) {
    await this.mutex.lock()

    try {
      const tx = this.createWriteBatch()
      tx.putUserData(key, value)

      return await this.flush()
    } finally {
      this._unlock()
    }
  }

  async _verifyBlock(batch, bitfield, value, manifest, from) {
    await this.mutex.lock()

    try {
      if (batch.upgraded && batch.length <= this.length) {
        await batch.downgrade()
      }

      if (!batch.commitable()) {
        return false
      }

      if (this.core.preupdate !== null) {
        await this.core.preupdate(batch, this.core.header.key)
      }

      const tx = this.createWriteBatch()

      if (bitfield) {
        tx.putBlock(bitfield.start, value)
      }

      if (bitfield && this.isDefault()) {
        await storeBitfieldRange(this.storage, tx, bitfield.start, bitfield.start + 1, true)
      }

      if (manifest) this.core._setManifest(tx, manifest, null)

      assert(batch.commitable(), 'Should still be commitable')
      batch.commit(tx)

      const head = {
        fork: batch.fork,
        length: batch.length,
        rootHash: batch.hash(),
        signature: batch.signature,
        timestamp: Date.now()
      }

      if (batch.upgraded) {
        tx.setHead(head)

        if (this.core.header.group) {
          this.updateGroupIndex(tx, head)
        }
      }

      const flushed = await this.flush()

      if (batch.upgraded) {
        this.roots = batch.roots
        this.length = batch.length
        this.byteLength = batch.byteLength
        this.fork = batch.fork
        this.signature = batch.signature

        this.onappend(head, bitfield, flushed)
      }

      if (this.core.hintsChanged && this.isDefault()) await this.core.flushHints()
    } finally {
      this._unlock()
    }

    return true
  }

  async truncate(length, fork, { signature, keyPair } = {}) {
    if (!keyPair && this.isDefault()) keyPair = this.core.header.keyPair

    await this.mutex.lock()

    try {
      if (this.prologue && length < this.prologue.length) {
        throw INVALID_OPERATION('Truncation breaks prologue', this.core.discoveryKey)
      }
      if (length > this.length) {
        throw INVALID_OPERATION(
          'Not a truncation, ' + length + ' must be less or equal to ' + this.length,
          this.core.discoveryKey
        )
      }

      const batch = this.createTreeBatch()
      await MerkleTree.truncate(this, length, batch, fork)

      if (signature) {
        batch.signature = signature
        this.core._verifyBatchUpgrade(batch)
      } else if (keyPair) {
        batch.signature = this.core.verifier.sign(batch, keyPair)
      }

      const tx = this.createWriteBatch()

      // upsert compat manifest
      if (this.core.verifier === null && keyPair) this.core._setManifest(tx, null, keyPair)

      const { dependency, tree, roots } = await this._truncate(tx, batch)

      for (const sessionState of this.core.sessionStates) {
        if (
          sessionState.isSnapshot() &&
          sessionState.name === this.name &&
          length < sessionState.snapshotCompatLength
        ) {
          sessionState.snapshotCompatLength = length
        }
      }

      const flushed = await this.flush()

      this.fork = tree.fork
      this.length = tree.length
      this.byteLength = MerkleTree.size(roots)
      this.roots = roots
      this.signature = tree.signature

      if (dependency) this.storage.setDependencyHead(dependency)

      this.ontruncate(tree, tree.length, batch.treeLength, flushed)

      if (this.core.hintsChanged && this.isDefault()) await this.core.flushHints()
    } finally {
      this._unlock()
    }
  }

  async reorg(batch) {
    await this.mutex.lock()

    const storage = this.createWriteBatch()

    try {
      if (!batch.commitable()) return false

      const { dependency, tree } = await this._truncate(storage, batch)

      const flushed = await this.flush()

      this.fork = batch.fork
      this.length = batch.length
      this.byteLength = batch.byteLength
      this.roots = batch.roots
      this.signature = batch.signature

      if (dependency) this.storage.setDependencyHead(dependency)

      this.ontruncate(tree, batch.ancestors, batch.treeLength, flushed)

      if (this.core.hintsChanged && this.isDefault()) await this.core.flushHints()
    } finally {
      this._unlock()
    }
  }

  async _truncate(storage, batch) {
    storage.deleteBlockRange(batch.ancestors, batch.treeLength)

    assert(batch.commitable(), 'Batch must be commitable')

    const tree = {
      fork: batch.fork,
      length: batch.length,
      rootHash: batch.hash(),
      signature: batch.signature,
      timestamp: Date.now()
    }

    if (this.isDefault() && this.core.header.group) {
      this.updateGroupIndex(storage, tree)
    }

    storage.setHead(tree)
    batch.commit(storage)

    const truncated = batch.length < this.flushedLength()
    const dependency = truncated ? updateDependency(this, batch.length, true) : null

    if (dependency) storage.setDependency(dependency)

    if (this.isDefault()) {
      await storeBitfieldRange(this.storage, storage, batch.ancestors, batch.treeLength, false)
      if (batch.ancestors < this.core.header.hints.contiguousLength) {
        this.core.header.hints.remoteContiguousLength = Math.min(
          batch.length,
          this.core.header.hints.remoteContiguousLength
        )
        storage.setHints({
          contiguousLength: batch.ancestors,
          remoteContiguousLength: this.core.header.hints.remoteContiguousLength
        })
      }
    }

    return { dependency, tree, roots: batch.roots }
  }

  async clear(start, end, cleared) {
    await this.mutex.lock()

    try {
      const tx = this.createWriteBatch()

      const ite = flat.iterator(start * 2)
      while (!isRootIndex(ite.index, this.roots)) {
        const a = ite.index
        const b = ite.sibling()
        ite.parent()

        const [left, right] = flat.spans(b)
        const s = left / 2
        const e = right / 2 + 1
        const has = s <= start && e <= end ? false : this.core.bitfield.hasSet(s, e - s)
        if (has) break

        tx.deleteTreeNode(a)
        tx.deleteTreeNode(b)
      }

      if (this.isDefault()) {
        await storeBitfieldRange(this.storage, tx, start, end, false)
        if (start < this.core.header.hints.contiguousLength) {
          tx.setHints({
            contiguousLength: start,
            remoteContiguousLength: this.core.header.hints.remoteContiguousLength
          })
        }
      }

      if (end - start === 1) tx.deleteBlock(start)
      else tx.deleteBlockRange(start, end)

      const dependency = start < this.flushedLength() ? updateDependency(this, start, true) : null

      const flushed = await this.flush()

      if (dependency) this.storage.setDependencyHead(dependency)

      // todo: atomic event handle
      if (this.isDefault() && flushed) {
        const length = end - start

        this.core.updateContiguousLength({ start, length, drop: true })
        this.core._setBitfieldRanges(start, end, false)
        this.core.replicator.onhave(start, length, true)

        if (this.core.hintsChanged) await this.core.flushHints()
      }
    } finally {
      this._unlock()
    }
  }

  // simple tool to wait for other peers to catch us up
  async waitForRecovery() {
    const length = this.length
    const replicator = this.core.replicator

    while (!this.closing) {
      let peers = getRecoveryPeers(replicator.peers)

      if (peers.length < 1) {
        await new Promise((resolve) => setTimeout(resolve, 5000))
        continue
      }

      let restart = false

      for (let i = 0; i < 32; i++) {
        await new Promise((resolve) => setTimeout(resolve, 250))

        peers = getRecoveryPeers(replicator.peers)

        if (this.closing || !validateRecoveryPeers(peers, this.length)) {
          restart = true
          break
        }
      }

      if (restart) continue

      if (this.length !== length) {
        throw SESSION_NOT_WRITABLE('core recovered during append')
      }

      this.core.header.hints.recovering = 0
      this.core.hintsChanged = true

      await this.mutex.lock()
      try {
        await this.core.flushHints()
        return
      } finally {
        this.mutex.unlock()
      }
    }

    throw SESSION_CLOSED('Cannot recover a closed session', this.discoveryKey)
  }

  async append(values, { signature, keyPair, preappend, postappend, maxLength = -1 } = {}) {
    if (!keyPair && this.isDefault()) keyPair = this.core.header.keyPair

    if (this.isDefault() && this.core.header.hints.recovering) await this.waitForRecovery()

    await this.mutex.lock()

    try {
      if (maxLength >= 0 && this.length + values.length > maxLength) {
        return { length: this.length, byteLength: this.byteLength }
      }

      const tx = this.createWriteBatch()

      // upsert compat manifest
      if (this.core.verifier === null && keyPair) this.core._setManifest(tx, null, keyPair)

      if (preappend) await preappend(values)

      if (!values.length) {
        await this.flush()
        return { length: this.length, byteLength: this.byteLength }
      }

      const batch = this.createTreeBatch()
      for (const val of values) batch.append(val)

      // only multisig can have prologue so signature is always present
      if (this.prologue && batch.length < this.prologue.length) {
        throw INVALID_OPERATION('Append is not consistent with prologue', this.core.discoveryKey)
      }

      if (signature) {
        batch.signature = signature
        this.core._verifyBatchUpgrade(batch)
      } else if (keyPair) {
        batch.signature = this.core.verifier.sign(batch, keyPair)
      }

      batch.commit(tx)

      const tree = {
        fork: batch.fork,
        length: batch.length,
        rootHash: batch.hash(),
        signature: batch.signature,
        timestamp: Date.now()
      }

      tx.setHead(tree)

      if (this.isDefault()) {
        await storeBitfieldRange(this.storage, tx, batch.ancestors, batch.length, true)
        if (this.length === this.core.header.hints.contiguousLength) {
          tx.setHints({
            contiguousLength: this.length + values.length,
            remoteContiguousLength: this.core.header.hints.remoteContiguousLength
          })
        }

        if (this.core.header.group) {
          this.updateGroupIndex(tx, tree)
        }
      }

      for (let i = 0; i < values.length; i++) {
        tx.putBlock(this.length + i, values[i])
      }

      const bitfield = {
        drop: false,
        start: batch.ancestors,
        length: values.length
      }

      const flushed = await this.flush()

      this.fork = batch.fork
      this.roots = batch.roots
      this.length = batch.length
      this.byteLength = batch.byteLength
      this.signature = batch.signature

      if (postappend) await postappend(values)

      this.onappend(tree, bitfield, flushed)

      if (this.core.hintsChanged && this.isDefault()) await this.core.flushHints()

      return { length: this.length, byteLength: this.byteLength }
    } finally {
      this._unlock()
    }
  }

  onappend(tree, bitfield, flushed) {
    if (!flushed) this._updateBitfield(bitfield)
    else if (this.isDefault()) this.core.onappend(tree, bitfield)

    for (let i = this.sessions.length - 1; i >= 0; i--) {
      this.sessions[i].emit('append')
    }
  }

  ontruncate(tree, to, from, flushed) {
    const bitfield = { start: to, length: from - to, drop: true }

    this.lastTruncation = { from, to }

    if (!flushed) this._updateBitfield(bitfield)
    else if (this.isDefault()) this.core.ontruncate(tree, bitfield)

    for (const sessionState of this.core.sessionStates) {
      if (
        sessionState.isSnapshot() &&
        sessionState.name === this.name &&
        to < sessionState.snapshotCompatLength
      ) {
        sessionState.snapshotCompatLength = to
      }
    }

    for (let i = this.sessions.length - 1; i >= 0; i--) {
      this.sessions[i].emit('truncate', to, tree.fork)
    }
  }

  _updateBitfield(bitfield, flushed) {
    if (!bitfield) return

    const p = this._pendingBitfield
    const b = bitfield

    if (b.drop) {
      // truncation must be from end
      if (p && b.start + b.length !== p.start + p.appends) {
        throw INVALID_OPERATION('Atomic truncations must be contiguous', this.core.discoveryKey)
      }

      // actual truncation
      if (p === null || b.start < p.start) {
        this._pendingBitfield = { truncated: true, start: b.start, appends: 0 }
        return
      }

      // just clearing batch data
      p.appends = b.start - p.start

      // we cleared the current batch
      if (p.appends === 0) this._pendingBitfield = null

      return
    }

    if (p === null) {
      this._pendingBitfield = { truncated: false, start: b.start, appends: b.length }
      return
    }

    if (b.start !== p.start + p.appends) {
      throw INVALID_OPERATION('Atomic operations must be contiguous', this.core.discoveryKey)
    }

    p.appends += b.length
  }

  async catchup(length) {
    assert(!this.isDefault(), 'Cannot catchup signed state') // TODO: make this check better

    await this.mutex.lock()

    try {
      const origLength = this.length

      let sharedLength = 0
      for (let i = this.storage.dependencies.length - 1; i >= 0; i--) {
        const dep = this.storage.dependencies[i]
        if (dep.dataPointer === this.core.state.storage.core.dataPointer) {
          sharedLength = dep.length
          break
        }
      }

      const tx = this.createWriteBatch()
      const rx = this.core.state.storage.read()
      const rootPromises = []

      for (const root of flat.fullRoots(length * 2)) {
        rootPromises.push(rx.getTreeNode(root))
      }

      rx.tryFlush()

      const roots = await Promise.all(rootPromises)
      const truncating = sharedLength < origLength

      for (const node of roots) {
        if (node === null) {
          throw INVALID_OPERATION(
            'Invalid catchup length, tree nodes not available',
            this.core.discoveryKey
          )
        }
      }

      const fork = truncating ? this.fork + 1 : this.fork

      // overwrite it atm, TODO: keep what we can connect to the tree
      tx.deleteBlockRange(0, -1)
      tx.deleteTreeNodeRange(0, -1)
      tx.deleteBitfieldPageRange(0, -1)

      const tree = {
        fork,
        length,
        rootHash: crypto.tree(roots),
        signature: null,
        timestamp: Date.now()
      }

      // never default state so do not update group index
      tx.setHead(tree)

      // prop a better way to do this
      const dep = updateDependency(this, sharedLength, true)
      dep.length = length

      tx.setDependency(dep)

      const flushed = await this.flush()

      this.storage.setDependencyHead(dep)

      this.fork = tree.fork
      this.roots = roots
      this.length = tree.length
      this.byteLength = MerkleTree.size(roots)

      if (truncating) this.ontruncate(tree, sharedLength, origLength, flushed)
      if (sharedLength < length) this.onappend(tree, null, flushed)

      if (this.core.hintsChanged && this.isDefault()) await this.core.flushHints()
    } finally {
      this._unlock()
    }
  }

  async _overwrite(source, fork, length, treeLength, signature) {
    const blockPromises = []
    const treePromises = []
    const rootPromises = []

    const rx = source.storage.read()

    for (const root of flat.fullRoots(length * 2)) {
      rootPromises.push(rx.getTreeNode(root))
    }

    for (const index of flat.patch(treeLength * 2, length * 2)) {
      treePromises.push(rx.getTreeNode(index))
    }

    for (let i = treeLength; i < length; i++) {
      treePromises.push(rx.getTreeNode(i * 2))
      treePromises.push(rx.getTreeNode(i * 2 + 1))
      blockPromises.push(rx.getBlock(i))
    }

    rx.tryFlush()

    const [blocks, nodes, roots] = await Promise.all([
      Promise.all(blockPromises),
      Promise.all(treePromises),
      Promise.all(rootPromises)
    ])

    if (this.core.destroyed) throw new Error('Core destroyed')

    if (signature) {
      const batch = this.createTreeBatch()
      batch.roots = roots
      batch.length = length

      if (!this.core.verifier.verify(batch, signature)) {
        throw INVALID_SIGNATURE(
          'Signature is not valid over committed tree',
          this.core.discoveryKey
        )
      }
    }

    const tx = this.createWriteBatch()

    // truncate existing tree
    if (treeLength < this.length) {
      tx.deleteBlockRange(treeLength, this.length)
    }

    for (const root of roots) tx.putTreeNode(root)

    // no nodes will be copied in shallow mode
    for (const node of nodes) {
      if (node !== null) tx.putTreeNode(node)
    }

    for (let i = 0; i < blocks.length; i++) {
      assert(blocks[i] !== null, 'has block')
      tx.putBlock(i + treeLength, blocks[i])
    }

    const totalLength = Math.max(length, this.length)

    if (totalLength > treeLength) {
      const firstPage = getBitfieldPage(treeLength)
      const lastPage = getBitfieldPage(totalLength - 1)

      const srx = this.storage.read()
      const bitfieldPagePromise = srx.getBitfieldPage(firstPage)
      srx.tryFlush()

      const bitfieldPage = await bitfieldPagePromise

      let index = treeLength

      for (let i = firstPage; i <= lastPage; i++) {
        const page = b4a.alloc(Bitfield.BYTES_PER_PAGE)
        tx.putBitfieldPage(i, page)

        // copy existing bits in
        if (i === firstPage && bitfieldPage) page.set(bitfieldPage)

        if (index < length) {
          index = fillBitfieldPage(page, index, length, i, true)
          if (index < length) continue
        }

        if (index < this.length) {
          index = fillBitfieldPage(page, index, this.length, i, false)
        }
      }
    }

    const tree = {
      fork,
      length,
      rootHash: crypto.tree(roots),
      signature,
      timestamp: Date.now()
    }

    if (this.isDefault() && this.core.header.group) {
      this.updateGroupIndex(tx, tree)
    }

    const upgraded = treeLength < this.length || this.length < length || tree.fork !== this.fork

    if (upgraded) tx.setHead(tree)

    const flushed = await this.flush()

    this.fork = tree.fork
    this.roots = roots
    this.length = length
    this.byteLength = MerkleTree.size(roots)
    this.signature = signature

    return { tree, flushed }
  }

  static isParent(state, parent) {
    // atomic batches have parent set
    if (state.parent && state.parent === parent) return true

    return HypercoreStorage.isParentStorage(state.storage, parent.storage)
  }

  async commit(state, { signature, keyPair, length = state.length, treeLength = -1 } = {}) {
    assert(
      this.isDefault() || (this.parent && this.parent.isDefault()),
      'Can only commit into default state'
    )

    assert(SessionState.isParent(state, this), 'Cannot commit across cores')

    if (this.core._repairMode) {
      throw ASSERTION('Cannot commit while repair mode is on')
    }

    if (this.core.header.hints.recovering) await this.waitForRecovery()

    let srcLocked = false
    await this.mutex.lock()

    try {
      await state.mutex.lock()
      srcLocked = true

      if (treeLength === -1) treeLength = state.flushedLength()

      if (!(await this.core._validateCommit(state, treeLength))) return null
      if (this.length > length) return null

      if (this.length < length && !signature) {
        if (!keyPair) keyPair = this.core.header.keyPair
        const batch = state.createTreeBatch()
        if (length !== batch.length) await batch.restore(length)
        signature = this.core.verifier.sign(batch, keyPair)
      }

      const { tree, flushed } = await this._overwrite(
        state,
        this.fork,
        length,
        treeLength,
        signature
      )

      // gc blocks from source
      if (treeLength < length) {
        const tx = state.createWriteBatch()

        tx.deleteBlockRange(treeLength, length)
        const dependency = state.updateDependency(tx, length)

        await state.flush(tx)

        if (dependency) state.storage.setDependencyHead(dependency)
      }

      const bitfield = { start: treeLength, length: length - treeLength, drop: false }
      this.onappend(tree, bitfield, flushed)

      return {
        length: this.length,
        byteLength: this.byteLength
      }
    } finally {
      if (srcLocked) state._unlock()
      this._unlock()
    }
  }

  async _getTreeHeadAt(length) {
    if (length === null) return this.treeInfo()

    const head = getDefaultTree()

    head.length = length

    const roots = await MerkleTree.getRootsFromStorage(this.storage, length)
    const rootHash = crypto.tree(roots)

    head.fork = this.fork
    head.rootHash = rootHash

    if (length === this.length) head.signature = this.signature

    return head
  }

  _moveToCore(core, truncated, appended) {
    const head = this.core.sessionStates.pop()
    if (head !== this) this.core.sessionStates[(head.index = this.index)] = head

    this.core = core
    this.index = this.core.sessionStates.push(this) - 1

    for (let i = this.sessions.length - 1; i >= 0; i--) {
      const s = this.sessions[i]
      const manifest = s.manifest
      s.transferSession(this.core)
      if (!manifest && s.manifest) s.emit('manifest')
      if (truncated) s.emit('truncate', truncated.to, truncated.fork)
      if (appended) s.emit('append')
    }
  }

  async moveTo(core, length) {
    const state = core.state

    await this.mutex.lock()

    try {
      // if (state.storage && (await state.storage.resumeSession(this.name)) !== null) {
      //   throw STORAGE_CONFLICT('Batch has already been created')
      // }

      const treeLength = this.length

      let truncated = null
      let appended = false

      if (!this.isSnapshot()) {
        if (this.lingers === null) this.lingers = []
        this.lingers.push(this.storage)

        const resumed = await state.storage.resumeSession(this.name)

        const truncation = length < this.length ? await truncateAndFlush(this, length) : null
        const treeInfo = truncation
          ? truncation.tree
          : resumed
            ? null
            : await state._getTreeHeadAt(this.length)

        const fork = truncation ? this.fork + 1 : this.fork

        // todo: validate treeInfo

        let storage = null

        if (resumed) {
          storage = resumed
        } else {
          treeInfo.fork = fork
          storage = await state.storage.createSession(this.name, treeInfo)
        }

        const roots = await MerkleTree.getRootsFromStorage(storage, length)

        this.storage = storage
        this.prologue = state.prologue
        this.fork = fork
        this.length = length
        this.byteLength = MerkleTree.size(roots)
        this.roots = roots

        if (truncation) {
          const { dependency } = truncation

          if (dependency) this.storage.setDependencyHead(dependency)
          truncated = { to: treeLength, fork }
        }

        if (this.length > treeLength) {
          appended = true
        }
      }

      for (let i = this.core.sessionStates.length - 1; i >= 0; i--) {
        const state = this.core.sessionStates[i]
        if (state === this) continue
        if (state.name === this.name) state._moveToCore(core.core)
      }

      this._moveToCore(core.core, truncated, appended)
    } finally {
      this._unlock()
    }
  }

  async createSession(name, overwrite, atom) {
    await this.mutex.lock()

    try {
      let storage = null
      let treeInfo = null

      if (!atom && !overwrite && this.storage) {
        storage = await this.storage.resumeSession(name)

        if (storage !== null) treeInfo = (await getCoreHead(storage)) || getDefaultTree()
      }

      const length = treeInfo ? treeInfo.length : this.length

      if (storage === null) {
        treeInfo = await this._getTreeHeadAt(length)

        if (atom) {
          storage = await this.storage.createAtomicSession(atom, treeInfo)
        } else {
          storage = await this.storage.createSession(name, treeInfo)
        }
      }

      if (this.atomized && atom) {
        throw new Error('Session already atomized')
      }

      const head = {
        fork: this.fork,
        roots:
          length === this.length
            ? this.roots.slice()
            : await MerkleTree.getRootsFromStorage(storage, length),
        length,
        prologue: this.prologue,
        signature: length === this.length ? this.signature : null
      }

      const state = new SessionState(
        this.core,
        atom ? this : null,
        storage,
        head,
        atom ? this.name : name
      )

      if (atom) {
        this.atomized = atom
        atom.preflush(this._precommit.bind(this, state))
        atom.onflush(state._commit.bind(state))
      }

      return state
    } finally {
      this._unlock()
    }
  }
}

module.exports = SessionState

function noop() {}

function getBitfieldPage(index) {
  return Math.floor(index / Bitfield.BITS_PER_PAGE)
}

function fillBitfieldPage(page, start, end, pageIndex, value) {
  const offset = pageIndex * Bitfield.BITS_PER_PAGE
  const max = offset + Bitfield.BITS_PER_PAGE

  const index = max < end ? max : end

  const from = start - offset
  const to = index - offset

  quickbit.fill(page, value, from, to)

  return index
}

async function storeBitfieldRange(storage, tx, from, to, value) {
  if (from >= to) return

  const firstPage = getBitfieldPage(from)
  const lastPage = getBitfieldPage(to - 1)

  let index = from

  const rx = storage.read()

  const promises = []
  for (let i = firstPage; i <= lastPage; i++) {
    promises.push(rx.getBitfieldPage(i))
  }

  rx.tryFlush()

  const pages = await Promise.all(promises)
  const cnt = lastPage - firstPage + 1

  for (let i = 0; i < cnt; i++) {
    const pageIndex = i + firstPage
    if (!pages[i]) pages[i] = b4a.alloc(Bitfield.BYTES_PER_PAGE)

    index = fillBitfieldPage(pages[i], index, to, pageIndex, value)
    tx.putBitfieldPage(pageIndex, pages[i])
  }
}

async function truncateAndFlush(s, length) {
  const batch = s.createTreeBatch()
  await MerkleTree.truncate(s, length, batch, s.fork)
  const tx = s.createWriteBatch()

  const info = await s._truncate(tx, batch)
  const flushed = await s.flush()

  return {
    tree: info.tree,
    roots: info.roots,
    dependency: info.dependency,
    flushed
  }
}

function updateDependency(state, length, truncated) {
  const i = state.storage.findDependencyIndex(length, truncated)
  if (i === -1) return null // skip default state and overlays of default

  return {
    dataPointer: state.storage.dependencies[i].dataPointer,
    length
  }
}

function getDefaultTree() {
  return {
    fork: 0,
    length: 0,
    rootHash: null,
    signature: null
  }
}

function getCoreHead(storage) {
  const b = storage.read()
  const p = b.getHead()
  b.tryFlush()
  return p
}

function isRootIndex(index, roots) {
  for (const node of roots) {
    if (node.index === index) return true
  }

  return false
}

function getRecoveryPeers(peers) {
  if (!SessionState.RECOVERY_PEERS) return peers

  const actual = []

  for (const p of peers) {
    for (const r of SessionState.RECOVERY_PEERS) {
      if (b4a.equals(p.remotePublicKey, r)) {
        actual.push(p)
        break
      }
    }
  }

  return actual
}

function validateRecoveryPeers(peers, length) {
  if (peers.length < 1) return false

  for (const p of peers) {
    if (p.remoteLength > length) return false
    if (p.remoteLength === 0 && !p.remoteSynced) return false
  }

  return true
}
const { Writable, Readable } = require('streamx')

class ReadStream extends Readable {
  constructor(core, opts = {}) {
    super()

    this.core = core
    this.start = opts.start || 0
    this.end = typeof opts.end === 'number' ? opts.end : -1
    this.snapshot = !opts.live && opts.snapshot !== false
    this.live = this.end === -1 ? !!opts.live : false
    this.wait = typeof opts.wait === 'boolean' ? opts.wait : this.core.wait
    this.timeout = opts.timeout || core.timeout
  }

  _open(cb) {
    this._openP().then(cb, cb)
  }

  _read(cb) {
    this._readP().then(cb, cb)
  }

  async _openP() {
    if (this.end === -1) await this.core.update()
    else await this.core.ready()
    if (this.snapshot && this.end === -1) this.end = this.core.length
  }

  async _readP() {
    const end = this.live ? -1 : this.end === -1 ? this.core.length : this.end
    if (end >= 0 && this.start >= end) {
      this.push(null)
      return
    }

    this.push(await this.core.get(this.start++, { wait: this.wait, timeout: this.timeout }))
  }
}

exports.ReadStream = ReadStream

class WriteStream extends Writable {
  constructor(core) {
    super()
    this.core = core
  }

  _writev(batch, cb) {
    this._writevP(batch).then(cb, cb)
  }

  async _writevP(batch) {
    await this.core.append(batch)
  }
}

exports.WriteStream = WriteStream

class ByteStream extends Readable {
  constructor(core, opts = {}) {
    super()

    this._core = core
    this._index = 0
    this._range = null

    this._byteOffset = opts.byteOffset || 0
    this._byteLength = typeof opts.byteLength === 'number' ? opts.byteLength : -1
    this._prefetch = typeof opts.prefetch === 'number' ? opts.prefetch : 32

    this._applyOffset = this._byteOffset > 0
  }

  _open(cb) {
    this._openp().then(cb, cb)
  }

  _read(cb) {
    this._readp().then(cb, cb)
  }

  async _openp() {
    if (this._byteLength === -1) {
      await this._core.update()
      this._byteLength = Math.max(this._core.byteLength - this._byteOffset, 0)
    }
  }

  async _readp() {
    let data = null

    if (this._byteLength === 0) {
      this.push(null)
      return
    }

    let relativeOffset = 0

    if (this._applyOffset) {
      this._applyOffset = false

      const [block, byteOffset] = await this._core.seek(this._byteOffset)

      this._index = block
      relativeOffset = byteOffset
    }

    this._predownload(this._index + 1)
    data = await this._core.get(this._index++, { valueEncoding: 'binary' })

    if (relativeOffset > 0) data = data.subarray(relativeOffset)

    if (data.byteLength > this._byteLength) data = data.subarray(0, this._byteLength)
    this._byteLength -= data.byteLength

    this.push(data)
    if (this._byteLength === 0) this.push(null)
  }

  _predownload(index) {
    if (this._range) this._range.destroy()
    this._range = this._core.download({ start: index, end: index + this._prefetch, linear: true })
  }

  _destroy(cb) {
    if (this._range) this._range.destroy()
    cb(null)
  }
}

exports.ByteStream = ByteStream
const crypto = require('hypercore-crypto')
const b4a = require('b4a')
const c = require('compact-encoding')
const flat = require('flat-tree')
const { BAD_ARGUMENT } = require('hypercore-errors')
const unslab = require('unslab')

const m = require('./messages')
const multisig = require('./multisig')
const caps = require('./caps')

class Signer {
  constructor(
    manifestHash,
    version,
    index,
    { signature = 'ed25519', publicKey, namespace = caps.DEFAULT_NAMESPACE } = {}
  ) {
    if (!publicKey) throw BAD_ARGUMENT('public key is required for a signer')
    if (signature !== 'ed25519') throw BAD_ARGUMENT('Only Ed25519 signatures are supported')

    this.manifestHash = manifestHash
    this.version = version
    this.signer = index
    this.signature = signature
    this.publicKey = publicKey
    this.namespace = namespace
  }

  _ctx() {
    return this.version === 0 ? this.namespace : this.manifestHash
  }

  verify(batch, signature) {
    return crypto.verify(batch.signable(this._ctx()), signature, this.publicKey)
  }

  sign(batch, keyPair) {
    return crypto.sign(batch.signable(this._ctx()), keyPair.secretKey)
  }
}

class CompatSigner extends Signer {
  constructor(index, signer, legacy) {
    super(null, 0, index, signer)
    this.legacy = legacy
  }

  verify(batch, signature) {
    return crypto.verify(batch.signableCompat(this.legacy), signature, this.publicKey)
  }

  sign(batch, keyPair) {
    return crypto.sign(batch.signableCompat(this.legacy), keyPair.secretKey)
  }
}

module.exports = class Verifier {
  constructor(
    manifestHash,
    manifest,
    { compat = isCompat(manifestHash, manifest), legacy = false } = {}
  ) {
    const self = this

    this.manifestHash = manifestHash
    this.compat = compat || manifest === null
    this.version = this.compat ? 0 : typeof manifest.version === 'number' ? manifest.version : 1
    this.hash = manifest.hash || 'blake2b'
    this.allowPatch = !this.compat && !!manifest.allowPatch
    this.quorum = this.compat ? 1 : defaultQuorum(manifest)

    this.signers = manifest.signers ? manifest.signers.map(createSigner) : []
    this.prologue = this.compat ? null : manifest.prologue || null

    function createSigner(signer, index) {
      return self.compat
        ? new CompatSigner(index, signer, legacy)
        : new Signer(manifestHash, self.version, index, signer)
    }
  }

  _verifyCompat(batch, signature) {
    if (!signature) return false

    if (this.compat || (!this.allowPatch && this.signers.length === 1)) {
      return !!signature && this.signers[0].verify(batch, signature)
    }

    return this._verifyMulti(batch, signature)
  }

  _inflate(signature) {
    if (this.version >= 1) return multisig.inflate(signature)
    const { proofs, patch } = multisig.inflatev0(signature)

    return {
      proofs: proofs.map(proofToVersion1),
      patch
    }
  }

  _verifyMulti(batch, signature) {
    if (!signature || this.quorum === 0) return false

    const { proofs, patch } = this._inflate(signature)
    if (proofs.length < this.quorum) return false

    const tried = new Uint8Array(this.signers.length)
    const nodes = this.allowPatch && patch.length ? toMap(patch) : null

    for (let i = 0; i < this.quorum; i++) {
      const inp = proofs[i]

      let tree = batch

      if (inp.patch && this.allowPatch) {
        tree = batch.clone()

        const upgrade = generateUpgrade(nodes, batch.length, inp.patch)
        const proof = {
          fork: tree.fork,
          block: null,
          hash: null,
          seek: null,
          upgrade,
          manifest: null
        }

        try {
          if (!tree.verifyUpgrade(proof)) return false
        } catch {
          return false
        }
      }

      if (inp.signer >= this.signers.length || tried[inp.signer]) return false
      tried[inp.signer] = 1

      const s = this.signers[inp.signer]
      if (!s.verify(tree, inp.signature)) return false
    }

    return true
  }

  verify(batch, signature) {
    if (this.version === 0) {
      return this._verifyCompat(batch, signature)
    }

    if (this.prologue !== null && batch.length <= this.prologue.length) {
      return batch.length === this.prologue.length && b4a.equals(batch.hash(), this.prologue.hash)
    }

    return this._verifyMulti(batch, signature)
  }

  // TODO: better api for this that is more ... multisig-ey
  sign(batch, keyPair) {
    if (!keyPair || !keyPair.secretKey) throw BAD_ARGUMENT('No key pair was passed')

    for (const s of this.signers) {
      if (b4a.equals(s.publicKey, keyPair.publicKey)) {
        const signature = s.sign(batch, keyPair)
        if (this.signers.length !== 1 || this.version === 0) return signature
        return this.assemble([{ signer: 0, signature, patch: 0, nodes: null }])
      }
    }

    throw BAD_ARGUMENT('Public key is not a declared signer')
  }

  assemble(inputs) {
    return this.version === 0 ? multisig.assemblev0(inputs) : multisig.assemble(inputs)
  }

  static manifestHash(manifest) {
    return manifestHash(manifest)
  }

  static encodeManifest(manifest) {
    return c.encode(m.manifest, manifest)
  }

  static decodeManifest(manifest) {
    return c.decode(m.manifest, manifest)
  }

  static defaultSignerManifest(publicKey) {
    return {
      version: 1,
      hash: 'blake2b',
      allowPatch: false,
      quorum: 1,
      signers: [
        {
          signature: 'ed25519',
          namespace: caps.DEFAULT_NAMESPACE,
          publicKey
        }
      ],
      prologue: null,
      linked: null,
      userData: null
    }
  }

  static fromManifest(manifest, opts) {
    const m = this.createManifest(manifest)
    return new this(manifestHash(m), m, opts)
  }

  static createManifest(inp) {
    if (!inp) return null

    if (inp.quorum && inp.quorum < 0) throw BAD_ARGUMENT('Quorum cannot be negative')
    if (inp.quorum && inp.signers && inp.quorum > inp.signers.length) {
      throw BAD_ARGUMENT('Quorum should not be higher than the number of signers')
    }

    const manifest = {
      version: getManifestVersion(inp), // defaults to v1
      hash: 'blake2b',
      allowPatch: !!inp.allowPatch,
      quorum: defaultQuorum(inp),
      signers: inp.signers ? inp.signers.map(parseSigner) : [],
      prologue: null,
      linked: null,
      userData: inp.userData || null
    }

    if (inp.hash && inp.hash !== 'blake2b') throw BAD_ARGUMENT('Only Blake2b hashes are supported')

    if (inp.prologue) {
      if (
        !(b4a.isBuffer(inp.prologue.hash) && inp.prologue.hash.byteLength === 32) ||
        !(inp.prologue.length >= 0)
      ) {
        throw BAD_ARGUMENT('Invalid prologue')
      }

      manifest.prologue = inp.prologue
      manifest.prologue.hash = unslab(manifest.prologue.hash)
    }

    if (manifest.userData !== null && manifest.version < 2) {
      throw BAD_ARGUMENT('Invalid field: userData')
    }

    if (inp.linked && inp.linked.length) {
      if (manifest.version < 2) throw BAD_ARGUMENT('Invalid field: linked')

      for (const key of inp.linked) {
        if (!(b4a.isBuffer(key) && key.byteLength === 32)) {
          throw BAD_ARGUMENT('Invalid key')
        }
      }

      manifest.linked = inp.linked
    }

    return manifest
  }

  static isValidManifest(key, manifest) {
    return b4a.equals(key, manifestHash(manifest))
  }

  static isCompat(key, manifest) {
    return isCompat(key, manifest)
  }

  static sign(manifest, batch, keyPair, opts) {
    return Verifier.fromManifest(manifest, opts).sign(batch, keyPair)
  }
}

function toMap(nodes) {
  const m = new Map()
  for (const node of nodes) m.set(node.index, node)
  return m
}

function isCompat(key, manifest) {
  return !!(
    manifest &&
    manifest.signers.length === 1 &&
    b4a.equals(key, manifest.signers[0].publicKey)
  )
}

function defaultQuorum(man) {
  if (typeof man.quorum === 'number') return man.quorum
  if (!man.signers || !man.signers.length) return 0
  return (man.signers.length >> 1) + 1
}

function generateUpgrade(patch, start, length) {
  const upgrade = { start, length, nodes: null, additionalNodes: [], signature: null }

  const from = start * 2
  const to = from + length * 2

  for (const ite = flat.iterator(0); ite.fullRoot(to); ite.nextTree()) {
    if (ite.index + ite.factor / 2 < from) continue

    if (upgrade.nodes === null && ite.contains(from - 2)) {
      upgrade.nodes = []

      const root = ite.index
      const target = from - 2

      ite.seek(target)

      while (ite.index !== root) {
        ite.sibling()
        if (ite.index > target) upgrade.nodes.push(patch.get(ite.index))
        ite.parent()
      }

      continue
    }

    if (upgrade.nodes === null) upgrade.nodes = []
    upgrade.nodes.push(patch.get(ite.index))
  }

  if (upgrade.nodes === null) upgrade.nodes = []
  return upgrade
}

function parseSigner(signer) {
  validateSigner(signer)
  return {
    signature: 'ed25519',
    namespace: unslab(signer.namespace || caps.DEFAULT_NAMESPACE),
    publicKey: unslab(signer.publicKey)
  }
}

function validateSigner(signer) {
  if (!signer || !signer.publicKey) throw BAD_ARGUMENT('Signer missing public key')
  if (signer.signature && signer.signature !== 'ed25519') {
    throw BAD_ARGUMENT('Only Ed25519 signatures are supported')
  }
}

function manifestHash(manifest) {
  const state = { start: 0, end: 32, buffer: null }
  m.manifest.preencode(state, manifest)
  state.buffer = b4a.allocUnsafe(state.end)
  c.raw.encode(state, caps.MANIFEST)
  m.manifest.encode(state, manifest)
  return crypto.hash(state.buffer)
}

function proofToVersion1(proof) {
  return {
    signer: proof.signer,
    signature: proof.signature,
    patch: proof.patch ? proof.patch.length : 0
  }
}

function getManifestVersion(inp) {
  if (typeof inp.version === 'number') return inp.version
  if (inp.linked && inp.linked.length) return 2
  if (inp.userData) return 2
  return 1
}
let COMPAT = true
let BATCH_UINTS = COMPAT ? 65536 : 128
let BATCH_BYTES = BATCH_UINTS * 4
let BATCH = BATCH_BYTES * 8 // in bits
const MAX_REMOTE_BATCHES = 4
const MAX_RANGE = 8 * 256 * 1024
const MIN_RANGE = 32 // 4bit ints
const MAX = 512
const MAX_ANY = 16

class LocalWants {
  constructor(peer) {
    this.destroyed = false
    this.peer = peer
    this.wants = new Map()
    this.free = new Set()
    this.any = null
  }

  add(index, handle) {
    const b = (index - (index & (BATCH - 1))) / BATCH
    return this.addBatch(b, handle)
  }

  addAnyRange(start, length, handle) {
    if (this.destroyed) return null
    if (this.any === null) this.any = []

    if (COMPAT) {
      let r = start & (BATCH - 1)
      start -= r
      length += r
      r = length & (BATCH - 1)
      if (r) length = length - r + BATCH
    }

    for (let i = 0; i < this.any.length; i++) {
      const w = this.any[i]
      if (w.start === start && w.length === length) {
        w.handles.add(handle)
        handle.addWant(w)
        return null
      }
    }

    const w = { wants: this, start, length, any: true, handles: new Set([handle]) }
    this.any.push(w)
    handle.addWant(w)

    return { start, length, any: !COMPAT }
  }

  removeAnyRange(start, length, handle) {
    if (this.any === null) return null

    for (let i = 0; i < this.any.length; i++) {
      const w = this.any[i]
      if (w.start !== start || w.length !== length) continue

      w.handles.delete(handle)
      handle.removeWant(w)
      if (w.handles.size > 0) return null

      const head = this.any.pop()
      if (head !== w) this.any[i] = head
      return { start, length, any: !COMPAT }
    }

    return null
  }

  addBatch(index, handle) {
    if (this.destroyed) return null
    let w = this.wants.get(index)

    if (w) {
      const size = w.handles.size
      w.handles.add(handle)
      if (w.handles.size !== size) {
        handle.addWant(w)
      }
      return null
    }

    // start here is the batch number for simplicity....
    w = { wants: this, start: index, length: 0, any: false, handles: new Set([handle]) }

    if (this.free.has(index)) {
      this.free.delete(index)
      this.wants.set(index, w)
      handle.addWant(w)
      return null
    }

    let unwant = null
    if (this.wants.size + this.free.size === MAX) {
      if (this.free.size === 0) {
        return null
      }
      unwant = this._unwant()
    }

    this.wants.set(index, w)
    handle.addWant(w)

    return {
      want: { start: index * BATCH, length: BATCH, any: false },
      unwant
    }
  }

  remove(index, handle) {
    const b = (index - (index & (BATCH - 1))) / BATCH
    return this.removeBatch(b, handle)
  }

  removeBatch(index, handle) {
    if (this.destroyed) return false

    const w = this.wants.get(index)
    if (!w) {
      return false
    }

    w.handles.delete(handle)
    handle.removeWant(w)

    if (w.handles.size === 0) {
      this.free.add(index)
      this.wants.delete(index)
      return this.free.size === 1 && this.wants.size === MAX - 1
    }

    return false
  }

  destroy() {
    if (this.destroyed) return
    this.destroyed = true

    for (const w of this.wants.values()) {
      for (const handle of w.handles) {
        handle.removeWant(w)
      }
    }

    this.wants.clear()
  }

  _unwant() {
    for (const index of this.free) {
      this.free.delete(index)
      return { start: index * BATCH, length: BATCH, any: false }
    }
    return null
  }
}

class RemoteWants {
  constructor() {
    this.any = null
    this.all = false
    this.size = 0
    this.batches = []
  }

  hasAny(start, length) {
    for (let i = 0; i < this.any.length; i++) {
      const a = this.any[i]
      const e = start + length
      const end = a.start + a.length

      if (a.start <= start && start < end) return true
      if (a.start < e && e <= end) return true
    }

    return this.all
  }

  hasRange(start, length) {
    if (this.any !== null && this.hasAny(start, length)) return true
    if (length === 1) return this.has(start)

    let smallest = -1

    for (let i = 0; i < this.batches.length; i++) {
      const b = this.batches[i]
      if (b.length < smallest || smallest === -1) smallest = b.length
    }

    if (smallest === -1) return this.all

    const r = start & (smallest - 1)
    const end = start + length

    let max = 3

    for (let i = start - r; i < end; i += smallest) {
      if (max-- === 0) return true // just to save work
      if (this.has(i)) return true
    }

    return this.all
  }

  has(index) {
    for (let i = 0; i < this.batches.length; i++) {
      const b = this.batches[i]
      const block = (index - (index & (b.length - 1))) / b.length
      if (b.ranges.has(block)) return true
    }

    return this.all
  }

  add(range) {
    if (range.any) {
      if (this.any === null) this.any = []
      if (this.any.length < MAX_ANY) this.any.push(range)
      else this.all = true
      return true
    }

    if (range.length > MAX_RANGE) return false

    if (!validateBatchRange(range)) {
      this.all = true
      return true
    }

    if (this.size >= MAX) {
      this.all = true
      return true
    }

    for (let i = 0; i < this.batches.length; i++) {
      const b = this.batches[i]
      if (b.length === range.length) {
        b.ranges.add(range.start / range.length)
        this.size++
        return true
      }
    }

    if (this.batches.length >= MAX_REMOTE_BATCHES) {
      this.all = true
      return true
    }

    this.batches.push({
      length: range.length,
      ranges: new Set([range.start / range.length])
    })
    this.size++

    return true
  }

  remove(range) {
    if (range.any) {
      if (this.any === null) return false

      for (let i = 0; i < this.any.length; i++) {
        const a = this.any[i]

        if (a.start === range.start && a.length === range.length) {
          const head = this.any.pop()
          if (head !== a) this.any[i] = head
          return true
        }
      }

      return false
    }

    if (!validateBatchRange(range)) return false

    for (let i = 0; i < this.batches.length; i++) {
      const b = this.batches[i]
      if (b.length !== range.length) continue

      const size = b.ranges.size
      b.ranges.delete(range.start / range.length)
      if (b.ranges.size !== size) this.size--

      if (b.ranges.size === 0) {
        const head = this.batches.pop()
        if (head !== b) this.batches[i] = head
      }

      return true
    }

    return false
  }
}

function UPDATE_COMPAT(isCompat) {
  COMPAT = isCompat
  BATCH_UINTS = COMPAT ? 65536 : 128
  BATCH_BYTES = BATCH_UINTS * 4
  BATCH = BATCH_BYTES * 8 // in bits
  exports.WANT_BATCH = BATCH
}

exports.LocalWants = LocalWants
exports.RemoteWants = RemoteWants
exports.WANT_BATCH = BATCH
exports.UPDATE_COMPAT = UPDATE_COMPAT

function validateBatchRange(range) {
  if (range.length > MAX_RANGE || range.length < MIN_RANGE) {
    return false
  }
  // check if power of two
  if ((range.length & (range.length - 1)) !== 0) {
    return false
  }
  // start must be a multiple of the length
  if (range.start & (range.length - 1)) {
    return false
  }

  return true
}
{
  "name": "hypercore",
  "version": "11.33.1",
  "description": "Hypercore is a secure, distributed append-only log",
  "main": "index.js",
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "brittle test/all.js",
    "test:bare": "bare test/all.js",
    "test:generate": "brittle -r test/all.js test/*.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/hypercore.git"
  },
  "contributors": [
    {
      "name": "Mathias Buus",
      "email": "mathiasbuus@gmail.com",
      "url": "https://mafinto.sh"
    },
    {
      "name": "Andrew Osheroff",
      "email": "andrewosh@gmail.com",
      "url": "https://andrewosh.com"
    }
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/hypercore/issues"
  },
  "homepage": "https://github.com/holepunchto/hypercore#readme",
  "files": [
    "index.js",
    "errors.js",
    "messages.js",
    "lib/**.js"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "dependencies": {
    "@hyperswarm/secret-stream": "^6.0.0",
    "b4a": "^1.1.0",
    "bare-events": "^2.2.0",
    "big-sparse-array": "^1.0.3",
    "compact-encoding": "^3.0.0",
    "fast-fifo": "^1.3.0",
    "flat-tree": "^1.9.0",
    "hypercore-crypto": "^3.2.1",
    "hypercore-errors": "^1.5.0",
    "hypercore-id-encoding": "^1.2.0",
    "hypercore-storage": "^3.0.0",
    "is-options": "^1.0.1",
    "nanoassert": "^2.0.0",
    "protomux": "^3.5.0",
    "quickbit-universal": "^2.2.0",
    "random-array-iterator": "^1.0.0",
    "safety-catch": "^1.0.1",
    "sodium-universal": "^5.0.1",
    "streamx": "^2.12.4",
    "unslab": "^1.3.0",
    "z32": "^1.0.0"
  },
  "devDependencies": {
    "brittle": "^3.0.0",
    "debugging-stream": "^3.1.0",
    "hyperswarm": "^4.3.6",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "rache": "^1.0.0",
    "range-parser": "^1.2.1",
    "resolve-reject-promise": "^1.1.0",
    "speedometer": "^1.1.0",
    "test-tmp": "^1.0.2",
    "tiny-byte-size": "^1.1.0",
    "udx-native": "^1.6.1",
    "uncaughts": "^1.1.0"
  }
}
const c = require('compact-encoding')
const { getEncoding } = require('./spec/hyperschema')

const HyperdhtAddress = getEncoding('@hyperdht/address')

function decode(buf) {
  const addr = c.decode(HyperdhtAddress, buf)
  return addr
}

function encode(key, nodes) {
  return c.encode(HyperdhtAddress, { key, nodes })
}

module.exports = { decode, encode }
{
  "name": "hyperdht-address",
  "version": "1.1.1",
  "description": "hyperdht-address",
  "main": "index.js",
  "exports": {
    "./package": "./package.json",
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    }
  },
  "files": [
    "package.json",
    "index.js",
    "index.d.ts",
    "spec"
  ],
  "devDependencies": {
    "b4a": "^1.8.0",
    "brittle": "^3.19.0",
    "lunte": "^1.2.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && lunte && brittle-bare test/index.js",
    "lint": "lunte"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/hyperdht-address.git"
  },
  "author": "Holepunch Inc",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/hyperdht-address/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperdht-address",
  "dependencies": {
    "compact-encoding": "^3.0.0",
    "hyperschema": "^1.20.1"
  }
}
// This file is autogenerated by the hyperschema compiler
// Schema Version: 2
/* eslint-disable camelcase */
/* eslint-disable quotes */
/* eslint-disable space-before-function-paren */

const { c } = require('hyperschema/runtime')

const VERSION = 2

// eslint-disable-next-line no-unused-vars
let version = VERSION

// @hyperdht/address.nodes
const encoding0_1 = c.array(c.ipv4Address)

// @hyperdht/address
const encoding0 = {
  preencode(state, m) {
    c.fixed32.preencode(state, m.key)
    state.end++ // max flag is 1 so always one byte

    if (version >= 2 && m.nodes) encoding0_1.preencode(state, m.nodes)
  },
  encode(state, m) {
    const flags = version >= 2 && m.nodes ? 1 : 0

    c.fixed32.encode(state, m.key)
    c.uint.encode(state, flags)

    if (version >= 2 && m.nodes) encoding0_1.encode(state, m.nodes)
  },
  decode(state) {
    const r0 = c.fixed32.decode(state)
    const flags = state.start < state.end ? c.uint.decode(state) : 0

    return {
      key: r0,
      nodes: version >= 2 && (flags & 1) !== 0 ? encoding0_1.decode(state) : null
    }
  }
}

function setVersion(v) {
  version = v
}

function encode(name, value, v = VERSION) {
  version = v
  return c.encode(getEncoding(name), value)
}

function decode(name, buffer, v = VERSION) {
  version = v
  return c.decode(getEncoding(name), buffer)
}

function getEnum(name) {
  switch (name) {
    default:
      throw new Error('Enum not found ' + name)
  }
}

function getEncoding(name) {
  switch (name) {
    case '@hyperdht/address':
      return encoding0
    default:
      throw new Error('Encoder not found ' + name)
  }
}

function getStruct(name, v = VERSION) {
  const enc = getEncoding(name)
  return {
    preencode(state, m) {
      version = v
      enc.preencode(state, m)
    },
    encode(state, m) {
      version = v
      enc.encode(state, m)
    },
    decode(state) {
      version = v
      return enc.decode(state)
    }
  }
}

const resolveStruct = getStruct // compat

module.exports = {
  resolveStruct,
  getStruct,
  getEnum,
  getEncoding,
  encode,
  decode,
  setVersion,
  version
}
const DHT = require('dht-rpc')
const sodium = require('sodium-universal')
const c = require('compact-encoding')
const b4a = require('b4a')
const safetyCatch = require('safety-catch')
const m = require('./lib/messages')
const SocketPool = require('./lib/socket-pool')
const Persistent = require('./lib/persistent')
const Router = require('./lib/router')
const Cache = require('xache')
const Server = require('./lib/server')
const connect = require('./lib/connect')
const { FIREWALL, BOOTSTRAP_NODES, KNOWN_NODES, COMMANDS } = require('./lib/constants')
const { hash, createKeyPair } = require('./lib/crypto')
const RawStreamSet = require('./lib/raw-stream-set')
const ConnectionPool = require('./lib/connection-pool')
const { STREAM_NOT_CONNECTED } = require('./lib/errors')

const DEFAULTS = {
  ...DHT.DEFAULTS,
  connectionKeepAlive: 5000,
  randomPunchInterval: 20000
}

class HyperDHT extends DHT {
  constructor(opts = {}) {
    const port = opts.port || 49737
    const bootstrap = opts.bootstrap || BOOTSTRAP_NODES
    const nodes = opts.nodes || KNOWN_NODES

    super({ ...opts, port, bootstrap, nodes, filterNode })

    const { router, relayAddresses, persistent } = defaultCacheOpts(opts)

    this.defaultKeyPair = opts.keyPair || createKeyPair(opts.seed)
    this.listening = new Set()
    this.connectionKeepAlive =
      opts.connectionKeepAlive === false
        ? 0
        : opts.connectionKeepAlive || DEFAULTS.connectionKeepAlive

    // stats is inherited from dht-rpc so fwd the ones from there
    this.stats = {
      punches: { consistent: 0, random: 0, open: 0 },
      relaying: { attempts: 0, successes: 0, aborts: 0 },
      ...this.stats
    }
    this.rawStreams = new RawStreamSet(this)
    this.plugins = new Map()

    this._router = new Router(this, router)
    this._socketPool = new SocketPool(this, opts.host || '0.0.0.0')
    this._persistent = null
    this._validatedLocalAddresses = new Map()
    this._relayAddressesCache = new Cache(relayAddresses)

    this._deferRandomPunch = !!opts.deferRandomPunch
    this._lastRandomPunch = this._deferRandomPunch ? Date.now() : 0
    this._connectable = true
    this._randomPunchInterval = opts.randomPunchInterval || DEFAULTS.randomPunchInterval // min 20s between random punches...
    this._randomPunches = 0
    this._randomPunchLimit = 1 // set to one for extra safety for now

    this.once('persistent', () => {
      this._persistent = new Persistent(this, persistent)
      for (const plugin of this.plugins.values()) plugin.onpersistent()
    })

    this.on('network-change', () => {
      for (const server of this.listening) server.refresh()
    })

    this.on('network-update', () => {
      if (!this.online) return
      for (const server of this.listening) server.notifyOnline()
    })
  }

  static DEFAULTS = DEFAULTS

  connect(remotePublicKey, opts) {
    return connect(this, remotePublicKey, opts)
  }

  createServer(opts, onconnection) {
    if (typeof opts === 'function') return this.createServer({}, opts)
    if (opts && opts.onconnection) onconnection = opts.onconnection
    const s = new Server(this, opts)
    if (onconnection) s.on('connection', onconnection)
    return s
  }

  pool() {
    return new ConnectionPool(this)
  }

  async resume({ log = noop } = {}) {
    if (this._deferRandomPunch) this._lastRandomPunch = Date.now()
    await super.resume({ log })
    const resuming = []
    for (const server of this.listening) resuming.push(server.resume())
    log('Resuming hyperdht servers')
    await Promise.allSettled(resuming)
    log('Done, hyperdht fully resumed')
  }

  async suspend({ log = noop } = {}) {
    this._connectable = false // just so nothing gets connected during suspension
    const suspending = []
    for (const server of this.listening) suspending.push(server.suspend())
    log('Suspending all hyperdht servers')
    await Promise.allSettled(suspending)
    log('Done, clearing all raw streams')
    await this.rawStreams.clear()
    log('Done, suspending dht-rpc')
    await super.suspend({ log })
    log('Done, clearing raw streams again')
    await this.rawStreams.clear()
    log('Done, hyperdht fully suspended')
    this._connectable = true
  }

  async destroy({ force = false } = {}) {
    if (!force) {
      const closing = []
      for (const server of this.listening) closing.push(server.close())
      await Promise.allSettled(closing)
    }
    this._router.destroy()
    if (this._persistent) this._persistent.destroy()
    for (const plugin of this.plugins.values()) plugin.destroy()
    await this.rawStreams.clear()
    await this._socketPool.destroy()
    await super.destroy()
  }

  async validateLocalAddresses(addresses) {
    const list = []
    const socks = []
    const waiting = []

    for (const addr of addresses) {
      const { host } = addr

      if (this._validatedLocalAddresses.has(host)) {
        if (await this._validatedLocalAddresses.get(host)) {
          list.push(addr)
        }
        continue
      }

      const sock = this.udx.createSocket()
      try {
        sock.bind(0, host)
      } catch {
        this._validatedLocalAddresses.set(host, Promise.resolve(false))
        continue
      }

      socks.push(sock)

      // semi terrible heuristic until we proper fix local connections by racing them to the remote...
      const promise = new Promise((resolve) => {
        sock.on('message', () => resolve(true))
        setTimeout(() => resolve(false), 500)
        sock.trySend(b4a.alloc(1), sock.address().port, addr.host)
      })

      this._validatedLocalAddresses.set(host, promise)
      waiting.push(addr)
    }

    for (const addr of waiting) {
      const { host } = addr
      if (this._validatedLocalAddresses.has(host)) {
        if (await this._validatedLocalAddresses.get(host)) {
          list.push(addr)
        }
        continue
      }
    }

    for (const sock of socks) await sock.close()

    return list
  }

  findPeer(publicKey, opts = {}) {
    const target = opts.hash === false ? publicKey : hash(publicKey)
    opts = { ...opts, map: mapFindPeer }
    return this.query({ target, command: COMMANDS.FIND_PEER, value: null }, opts)
  }

  lookup(target, opts = {}) {
    opts = { ...opts, map: mapLookup }
    return this.query({ target, command: COMMANDS.LOOKUP, value: null }, opts)
  }

  lookupAndUnannounce(target, keyPair, opts = {}) {
    const unannounces = []
    const dht = this
    const userCommit = opts.commit || noop
    const signUnannounce = opts.signUnannounce || Persistent.signUnannounce

    if (this._persistent !== null) {
      // unlink self
      this._persistent.unannounce(target, keyPair.publicKey)
    }

    opts = { ...opts, map, commit }
    return this.query({ target, command: COMMANDS.LOOKUP, value: null }, opts)

    async function commit(reply, dht, query) {
      await Promise.all(unannounces) // can never fail, caught below
      return userCommit(reply, dht, query)
    }

    function map(reply) {
      const data = mapLookup(reply)

      if (!data || !data.token) return data

      let found = data.peers.length >= 20
      for (let i = 0; !found && i < data.peers.length; i++) {
        found = b4a.equals(data.peers[i].publicKey, keyPair.publicKey)
      }

      if (!found) return data

      if (!data.from.id) return data

      unannounces.push(
        dht
          ._requestUnannounce(keyPair, dht, target, data.token, data.from, signUnannounce)
          .catch(safetyCatch)
      )

      return data
    }
  }

  unannounce(target, keyPair, opts = {}) {
    return this.lookupAndUnannounce(target, keyPair, opts).finished()
  }

  announce(target, keyPair, relayAddresses, opts = {}) {
    const signAnnounce = opts.signAnnounce || Persistent.signAnnounce
    const bump = opts.bump || 0

    opts = { ...opts, commit }

    return opts.clear ? this.lookupAndUnannounce(target, keyPair, opts) : this.lookup(target, opts)

    function commit(reply, dht) {
      return dht._requestAnnounce(
        keyPair,
        dht,
        target,
        reply.token,
        reply.from,
        relayAddresses,
        signAnnounce,
        bump
      )
    }
  }

  async immutableGet(target, opts = {}) {
    opts = { ...opts, map: mapImmutable }

    const query = this.query({ target, command: COMMANDS.IMMUTABLE_GET, value: null }, opts)
    const check = b4a.allocUnsafe(32)

    for await (const node of query) {
      const { value } = node
      sodium.crypto_generichash(check, value)
      if (b4a.equals(check, target)) return node
    }

    return null
  }

  async immutablePut(value, opts = {}) {
    const target = b4a.allocUnsafe(32)
    sodium.crypto_generichash(target, value)

    opts = {
      ...opts,
      map: mapImmutable,
      commit(reply, dht) {
        return dht.request(
          { token: reply.token, target, command: COMMANDS.IMMUTABLE_PUT, value },
          reply.from
        )
      }
    }

    const query = this.query({ target, command: COMMANDS.IMMUTABLE_GET, value: null }, opts)
    await query.finished()

    return { hash: target, closestNodes: query.closestNodes }
  }

  async mutableGet(publicKey, opts = {}) {
    let refresh = opts.refresh || null
    let signed = null
    let result = null

    opts = { ...opts, map: mapMutable, commit: refresh ? commit : null }

    const target = b4a.allocUnsafe(32)
    sodium.crypto_generichash(target, publicKey)

    const userSeq = opts.seq || 0
    const query = this.query(
      { target, command: COMMANDS.MUTABLE_GET, value: c.encode(c.uint, userSeq) },
      opts
    )
    const latest = opts.latest !== false

    for await (const node of query) {
      if (result && node.seq <= result.seq) continue
      if (
        node.seq < userSeq ||
        !Persistent.verifyMutable(node.signature, node.seq, node.value, publicKey)
      )
        continue
      if (!latest) return node
      if (!result || node.seq > result.seq) result = node
    }

    return result

    function commit(reply, dht) {
      if (!signed && result && refresh) {
        if (refresh(result)) {
          signed = c.encode(m.mutablePutRequest, {
            publicKey,
            seq: result.seq,
            value: result.value,
            signature: result.signature
          })
        } else {
          refresh = null
        }
      }

      return signed
        ? dht.request(
            { token: reply.token, target, command: COMMANDS.MUTABLE_PUT, value: signed },
            reply.from
          )
        : Promise.resolve(null)
    }
  }

  async mutablePut(keyPair, value, opts = {}) {
    const signMutable = opts.signMutable || Persistent.signMutable

    const target = b4a.allocUnsafe(32)
    sodium.crypto_generichash(target, keyPair.publicKey)

    const seq = opts.seq || 0
    const signature = await signMutable(seq, value, keyPair)

    const signed = c.encode(m.mutablePutRequest, {
      publicKey: keyPair.publicKey,
      seq,
      value,
      signature
    })

    opts = {
      ...opts,
      map: mapMutable,
      commit(reply, dht) {
        return dht.request(
          { token: reply.token, target, command: COMMANDS.MUTABLE_PUT, value: signed },
          reply.from
        )
      }
    }

    // use seq = 0, for the query part here, as we don't care about the actual values
    const query = this.query(
      { target, command: COMMANDS.MUTABLE_GET, value: c.encode(c.uint, 0) },
      opts
    )
    await query.finished()

    return { publicKey: keyPair.publicKey, closestNodes: query.closestNodes, seq, signature }
  }

  onrequest(req) {
    switch (req.command) {
      case COMMANDS.PEER_HANDSHAKE: {
        this._router.onpeerhandshake(req)
        return true
      }
      case COMMANDS.PEER_HOLEPUNCH: {
        this._router.onpeerholepunch(req)
        return true
      }
    }

    if (this._persistent === null || this.id === null) return false

    switch (req.command) {
      case COMMANDS.FIND_PEER: {
        this._persistent.onfindpeer(req)
        return true
      }
      case COMMANDS.LOOKUP: {
        this._persistent.onlookup(req)
        return true
      }
      case COMMANDS.ANNOUNCE: {
        this._persistent.onannounce(req)
        return true
      }
      case COMMANDS.UNANNOUNCE: {
        this._persistent.onunannounce(req)
        return true
      }
      case COMMANDS.MUTABLE_PUT: {
        this._persistent.onmutableput(req)
        return true
      }
      case COMMANDS.MUTABLE_GET: {
        this._persistent.onmutableget(req)
        return true
      }
      case COMMANDS.IMMUTABLE_PUT: {
        this._persistent.onimmutableput(req)
        return true
      }
      case COMMANDS.IMMUTABLE_GET: {
        this._persistent.onimmutableget(req)
        return true
      }
      case COMMANDS.PLUGIN: {
        this._persistent.onplugin(req)
        return true
      }
    }

    return false
  }

  static keyPair(seed) {
    return createKeyPair(seed)
  }

  static hash(data) {
    return hash(data)
  }

  static connectRawStream(encryptedStream, rawStream, remoteId) {
    const stream = encryptedStream.rawStream

    if (!stream.connected) throw STREAM_NOT_CONNECTED()

    rawStream.connect(stream.socket, remoteId, stream.remotePort, stream.remoteHost)
  }

  createRawStream(opts) {
    return this.rawStreams.add(opts)
  }

  async _requestAnnounce(keyPair, dht, target, token, from, relayAddresses, sign, bump) {
    const ann = {
      peer: {
        publicKey: keyPair.publicKey,
        relayAddresses: relayAddresses || []
      },
      refresh: null,
      signature: null,
      bump
    }

    ann.signature = await sign(target, token, from.id, ann, keyPair)

    const value = c.encode(m.announce, ann)

    return dht.request(
      {
        token,
        target,
        command: COMMANDS.ANNOUNCE,
        value
      },
      from
    )
  }

  async _requestUnannounce(keyPair, dht, target, token, from, sign) {
    const unann = {
      peer: {
        publicKey: keyPair.publicKey,
        relayAddresses: []
      },
      signature: null
    }

    unann.signature = await sign(target, token, from.id, unann, keyPair)

    const value = c.encode(m.announce, unann)

    return dht.request(
      {
        token,
        target,
        command: COMMANDS.UNANNOUNCE,
        value
      },
      from
    )
  }

  register(name, plugin) {
    this.plugins.set(name, plugin)
    plugin.onregister(this)
  }
}

HyperDHT.BOOTSTRAP = BOOTSTRAP_NODES
HyperDHT.FIREWALL = FIREWALL

module.exports = HyperDHT

function mapLookup(node) {
  if (!node.value) return null

  try {
    const l = c.decode(m.lookupRawReply, node.value)

    return {
      token: node.token,
      from: node.from,
      to: node.to,
      peers: l.peers,
      bump: l.bump
    }
  } catch {
    return null
  }
}

function mapFindPeer(node) {
  if (!node.value) return null

  try {
    return {
      token: node.token,
      from: node.from,
      to: node.to,
      peer: c.decode(m.peer, node.value)
    }
  } catch {
    return null
  }
}

function mapImmutable(node) {
  if (!node.value) return null

  return {
    token: node.token,
    from: node.from,
    to: node.to,
    value: node.value
  }
}

function mapMutable(node) {
  if (!node.value) return null

  try {
    const { seq, value, signature } = c.decode(m.mutableGetResponse, node.value)

    return {
      token: node.token,
      from: node.from,
      to: node.to,
      seq,
      value,
      signature
    }
  } catch {
    return null
  }
}

function noop() {}

function filterNode(node) {
  // always skip these testnet nodes that got mixed in by accident, until they get updated
  return (
    !(node.port === 49738 && (node.host === '134.209.28.98' || node.host === '167.99.142.185')) &&
    !(node.port === 9400 && node.host === '35.233.47.252') &&
    !(node.host === '150.136.142.116')
  )
}

const defaultMaxSize = 65536
const defaultMaxAge = 20 * 60 * 1000 // 20 minutes

function defaultCacheOpts(opts) {
  const maxSize = opts.maxSize || defaultMaxSize
  const maxAge = opts.maxAge || defaultMaxAge

  return {
    router: {
      forwards: { maxSize, maxAge }
    },
    relayAddresses: { maxSize: Math.min(maxSize, 512), maxAge: 0 },
    persistent: {
      records: { maxSize, maxAge },
      refreshes: { maxSize, maxAge },
      mutables: {
        maxSize: (maxSize / 2) | 0,
        maxAge: opts.maxAge || 48 * 60 * 60 * 1000 // 48 hours
      },
      immutables: {
        maxSize: (maxSize / 2) | 0,
        maxAge: opts.maxAge || 48 * 60 * 60 * 1000 // 48 hours
      },
      bumps: { maxSize, maxAge }
    }
  }
}
const safetyCatch = require('safety-catch')
const c = require('compact-encoding')
const Signal = require('signal-promise')
const { encodeUnslab } = require('./encode')
const Sleeper = require('./sleeper')
const m = require('./messages')
const Persistent = require('./persistent')
const { COMMANDS } = require('./constants')

const MIN_ACTIVE = 3

module.exports = class Announcer {
  constructor(dht, keyPair, target, opts = {}) {
    this.dht = dht
    this.keyPair = keyPair
    this.target = target
    this.relays = []
    this.relayAddresses = []
    this.stopped = false
    this.suspended = false
    this.record = encodeUnslab(m.peer, { publicKey: keyPair.publicKey, relayAddresses: [] })
    this.online = new Signal()

    this._refreshing = false
    this._closestNodes = null
    this._active = null
    this._sleeper = new Sleeper()
    this._resumed = new Signal()
    this._signAnnounce = opts.signAnnounce || Persistent.signAnnounce
    this._signUnannounce = opts.signUnannounce || Persistent.signUnannounce
    this._updating = null
    this._activeQuery = null
    this._unannouncing = null

    this._serverRelays = [new Map(), new Map(), new Map()]
  }

  isRelay(addr) {
    const id = addr.host + ':' + addr.port
    const [a, b, c] = this._serverRelays
    return a.has(id) || b.has(id) || c.has(id)
  }

  async suspend({ log = noop } = {}) {
    if (this.suspended) return
    this.suspended = true

    log('Suspending announcer')

    // Suspend has its own sleep logic
    // so we don't want to hang on this one
    this.online.notify()

    if (this._activeQuery) this._activeQuery.destroy()

    this._sleeper.resume()
    if (this._updating) await this._updating
    log('Suspending announcer (post update)')

    if (this.suspended === false || this.stopped) return

    log('Suspending announcer (pre unannounce)')
    await this._unannounceCurrent()
    log('Suspending announcer (post unannounce)')
  }

  resume() {
    if (!this.suspended) return
    this.suspended = false

    this.refresh()
    this._sleeper.resume()
    this._resumed.notify()
  }

  refresh() {
    if (this.stopped) return
    this._refreshing = true
  }

  async start() {
    if (this.stopped) return
    this._active = this._runUpdate()
    await this._active
    if (this.stopped) return
    this._active = this._background()
  }

  async stop() {
    this.stopped = true
    this.online.notify() // Break out of the _background loop if we're offline
    this._sleeper.resume()
    this._resumed.notify()
    await this._active
    await this._unannounceCurrent()
  }

  async _unannounceCurrent() {
    while (this._unannouncing !== null) await this._unannouncing
    const un = (this._unannouncing = this._unannounceAll(this._serverRelays[2].values()))
    await this._unannouncing
    if (un === this._unannouncing) this._unannouncing = null
  }

  async _background() {
    while (!this.dht.destroyed && !this.stopped) {
      try {
        this._refreshing = false

        // ~5min +-
        for (let i = 0; i < 100 && !this.stopped && !this._refreshing && !this.suspended; i++) {
          const pings = []

          for (const node of this._serverRelays[2].values()) {
            pings.push(this.dht.ping(node))
          }

          const active = await resolved(pings)
          if (active < Math.min(pings.length, MIN_ACTIVE)) {
            this.refresh() // we lost too many relay nodes, retry all
          }

          if (this.stopped) return

          if (!this.suspended && !this._refreshing) await this._sleeper.pause(3000)
        }

        while (!this.stopped && this.suspended) await this._resumed.wait()

        if (!this.stopped) await this._runUpdate()

        while (!this.dht.online && !this.stopped && !this.suspended) {
          // Being offline can make _background repeat very quickly
          // So wait until we're back online
          await this.online.wait()
        }
      } catch (err) {
        safetyCatch(err)
      }
    }
  }

  async _runUpdate() {
    this._updating = this._update()
    await this._updating
    this._updating = null
  }

  async _update() {
    while (this._unannouncing) await this._unannouncing

    this._cycle()

    const q = (this._activeQuery = this.dht.findPeer(this.target, {
      hash: false,
      nodes: this._closestNodes
    }))

    try {
      await q.finished()
    } catch {
      // ignore failures...
    }

    this._activeQuery = null

    if (this.stopped || this.suspended) return

    const ann = []
    const replies = pickBest(q.closestReplies)

    const relays = []
    const relayAddresses = []

    if (!this.dht.firewalled) {
      const addr = this.dht.remoteAddress()
      if (addr) relayAddresses.push(addr)
    }

    for (const msg of replies) {
      ann.push(this._commit(msg, relays, relayAddresses))
    }

    await Promise.allSettled(ann)
    if (this.stopped || this.suspended) return

    this._closestNodes = q.closestNodes
    this.relays = relays
    this.relayAddresses = relayAddresses

    const removed = []
    for (const [key, value] of this._serverRelays[1]) {
      if (!this._serverRelays[2].has(key)) removed.push(value)
    }

    await this._unannounceAll(removed)
  }

  _unannounceAll(relays) {
    const unann = []
    for (const r of relays) unann.push(this._unannounce(r))
    return Promise.allSettled(unann)
  }

  async _unannounce(to) {
    const unann = {
      peer: {
        publicKey: this.keyPair.publicKey,
        relayAddresses: []
      },
      refresh: null,
      signature: null
    }

    const { from, token, value } = await this.dht.request(
      {
        token: null,
        command: COMMANDS.FIND_PEER,
        target: this.target,
        value: null
      },
      to
    )

    if (!token || !from.id || !value) return

    unann.signature = await this._signUnannounce(this.target, token, from.id, unann, this.keyPair)

    await this.dht.request(
      {
        token,
        command: COMMANDS.UNANNOUNCE,
        target: this.target,
        value: c.encode(m.announce, unann)
      },
      to
    )
  }

  async _commit(msg, relays, relayAddresses) {
    const ann = {
      peer: {
        publicKey: this.keyPair.publicKey,
        relayAddresses: []
      },
      refresh: null,
      signature: null
    }

    ann.signature = await this._signAnnounce(this.target, msg.token, msg.from.id, ann, this.keyPair)

    const res = await this.dht.request(
      {
        token: msg.token,
        command: COMMANDS.ANNOUNCE,
        target: this.target,
        value: c.encode(m.announce, ann)
      },
      msg.from
    )

    if (res.error !== 0) return

    if (relayAddresses.length < 3) relayAddresses.push({ host: msg.from.host, port: msg.from.port })
    relays.push({ relayAddress: msg.from, peerAddress: msg.to })

    this._serverRelays[2].set(msg.from.host + ':' + msg.from.port, msg.from)
  }

  _cycle() {
    const tmp = this._serverRelays[0]
    this._serverRelays[0] = this._serverRelays[1]
    this._serverRelays[1] = this._serverRelays[2]
    this._serverRelays[2] = tmp
    tmp.clear()
  }
}

function resolved(ps) {
  let replied = 0
  let ticks = ps.length + 1

  return new Promise((resolve) => {
    for (const p of ps) p.then(push, tick)
    tick()

    function push(v) {
      replied++
      tick()
    }

    function tick() {
      if (--ticks === 0) resolve(replied)
    }
  })
}

function pickBest(replies) {
  // TODO: pick the ones closest to us RTT wise
  return replies.slice(0, 3)
}

function noop() {}
const NoiseSecretStream = require('@hyperswarm/secret-stream')
const b4a = require('b4a')
const relay = require('blind-relay')
const { isReserved, isBogon } = require('bogon')
const safetyCatch = require('safety-catch')
const unslab = require('unslab')
const Semaphore = require('./semaphore')
const NoiseWrap = require('./noise-wrap')
const SecurePayload = require('./secure-payload')
const Holepuncher = require('./holepuncher')
const Sleeper = require('./sleeper')
const { FIREWALL, ERROR } = require('./constants')
const { unslabbedHash } = require('./crypto')
const {
  CANNOT_HOLEPUNCH,
  HANDSHAKE_INVALID,
  HOLEPUNCH_ABORTED,
  HOLEPUNCH_INVALID,
  HOLEPUNCH_PROBE_TIMEOUT,
  HOLEPUNCH_DOUBLE_RANDOMIZED_NATS,
  PEER_CONNECTION_FAILED,
  PEER_NOT_FOUND,
  REMOTE_ABORTED,
  REMOTE_NOT_HOLEPUNCHABLE,
  REMOTE_NOT_HOLEPUNCHING,
  SERVER_ERROR,
  SERVER_INCOMPATIBLE,
  RELAY_ABORTED,
  SUSPENDED
} = require('./errors')
const { decode } = require('hypercore-id-encoding')
const HyperDHTAddress = require('hyperdht-address')

module.exports = function connect(dht, publicKey, opts = {}) {
  const pool = opts.pool || null

  const { key, nodes: providedNodes } = HyperDHTAddress.decode(
    b4a.isBuffer(publicKey) ? publicKey : decode(publicKey)
  )
  publicKey = key

  if (pool && pool.has(publicKey)) return pool.get(publicKey)

  publicKey = unslab(publicKey)

  opts.relayAddresses = opts.relayAddresses || providedNodes || []
  const keyPair = opts.keyPair || dht.defaultKeyPair
  const relayThrough = selectRelay(opts.relayThrough || null)
  const encryptedSocket = (opts.createSecretStream || defaultCreateSecretStream)(true, null, {
    publicKey: keyPair.publicKey,
    remotePublicKey: publicKey,
    autoStart: false,
    keepAlive: dht.connectionKeepAlive
  })

  // in case a socket is made during suspended state, destroy it immediately
  if (dht.suspended || !dht._connectable) {
    encryptedSocket.destroy(SUSPENDED())
    return encryptedSocket
  }

  if (pool) pool._attachStream(encryptedSocket, false)

  const id = b4a.toString(publicKey, 'hex')
  const c = {
    id,
    dht,
    session: dht.session(),
    relayAddresses: opts.relayAddresses,
    remoteRelayAddresses: [],
    pool,
    round: 0,
    target: unslabbedHash(publicKey),
    remotePublicKey: publicKey,
    reusableSocket: !!opts.reusableSocket,
    handshake: (opts.createHandshake || defaultCreateHandshake)(keyPair, publicKey),
    request: null,
    requesting: false,
    lan: opts.localConnection !== false,
    firewall: FIREWALL.UNKNOWN,
    rawStream: dht.createRawStream({ framed: true, firewall }),
    connect: null,
    query: null,
    puncher: null,
    payload: null,
    passiveConnectTimeout: null,
    serverSocket: null,
    serverAddress: null,
    onsocket: null,
    sleeper: new Sleeper(),
    encryptedSocket,

    // Relay state
    relayTimeout: null,
    relayThrough,
    relayToken: relayThrough ? relay.token() : null,
    relaySocket: null,
    relayClient: null,
    relayPaired: false,
    relayKeepAlive: opts.relayKeepAlive || 5000
  }

  // If the raw stream receives an error signal pre connect (ie from the firewall hook), make sure
  // to forward that to the encrypted socket for proper teardown
  c.rawStream.on('error', autoDestroy)
  c.rawStream.once('connect', () => {
    c.rawStream.removeListener('error', autoDestroy)
  })

  encryptedSocket.on('close', function () {
    if (c.passiveConnectTimeout) clearPassiveConnectTimeout(c)
    if (c.query) c.query.destroy()
    if (c.puncher) c.puncher.destroy()
    if (c.rawStream) c.rawStream.destroy()
    c.session.destroy()
    c.sleeper.resume()
  })

  // Safe to run in the background - never throws
  if (dht.suspended) encryptedSocket.destroy(SUSPENDED())
  else connectAndHolepunch(c, opts)

  return encryptedSocket

  function autoDestroy(err) {
    maybeDestroyEncryptedSocket(c, err)
  }

  function firewall(socket, port, host) {
    // Check if the traffic originated from the socket on which we're expecting relay traffic. If so,
    // we haven't hole punched yet and the other side is just sending us traffic through the relay.
    if (c.relaySocket && isRelay(c.relaySocket, socket, port, host)) {
      return false
    }

    if (c.onsocket) {
      c.onsocket(socket, port, host)
    } else {
      c.serverSocket = socket
      c.serverAddress = { port, host }
    }
    return false
  }
}

function isDone(c) {
  // we are destroying or the puncher is connected - done
  if (c.encryptedSocket.destroying || !!(c.puncher && c.puncher.connected)) {
    return true
  }
  // not destroying, but no raw stream - def not done
  if (c.encryptedSocket.rawStream === null) {
    return false
  }
  // we are relayed, but the puncher is not done yet
  if (c.relaySocket && !!(c.puncher && !c.puncher.connected && !c.puncher.destroyed)) {
    return false
  }
  // we are done
  return true
}

async function retryRoute(c, route) {
  const ref = c.dht._socketPool.lookup(route.socket)

  if (!ref) {
    if (route.socket === c.dht.socket) {
      await connectThroughNode(c, route.address, c.dht.socket)
    }
    return
  }

  ref.active()

  try {
    await connectThroughNode(c, route.address, route.socket)
  } catch {
    // if error, just ignore, and continue through the existing strat
  }

  ref.inactive()
}

async function connectAndHolepunch(c, opts) {
  const route = c.reusableSocket ? c.dht._socketPool.routes.get(c.remotePublicKey) : null

  if (route) {
    await retryRoute(c, route)
    if (isDone(c)) return
  }

  await findAndConnect(c, opts)
  if (isDone(c)) return

  if (!c.connect) {
    // TODO: just a quick fix for now, should retry prob
    maybeDestroyEncryptedSocket(c, HANDSHAKE_INVALID())
    return
  }

  await holepunch(c, opts)
}

function getFirstRemoteAddress(addrs, serverAddress) {
  for (const addr of addrs) {
    if (isBogon(addr.host)) continue
    return addr
  }

  return serverAddress
}

async function holepunch(c, opts) {
  let { relayAddress, serverAddress, clientAddress, payload } = c.connect

  const remoteHolepunchable = !!(payload.holepunch && payload.holepunch.relays.length)

  const relayed = diffAddress(serverAddress, relayAddress)

  if (payload.firewall === FIREWALL.OPEN || (relayed && !remoteHolepunchable)) {
    const addr = getFirstRemoteAddress(payload.addresses4, serverAddress)
    if (addr) {
      const socket = c.dht.socket
      c.dht.stats.punches.open++
      c.onsocket(socket, addr.port, addr.host)
      return
    }
    // TODO: check all addresses also obvs
  }

  const onabort = () => {
    c.session.destroy()
    maybeDestroyEncryptedSocket(c, HOLEPUNCH_ABORTED())
  }

  if (c.firewall === FIREWALL.OPEN) {
    c.passiveConnectTimeout = setTimeout(onabort, 10000)
    return
  }

  // TODO: would be better to just try local addrs in the background whilst continuing with other strategies...
  if (c.lan && relayed && clientAddress.host === serverAddress.host) {
    const serverAddresses = payload.addresses4.filter(onlyNonReserved)

    if (serverAddresses.length > 0) {
      const myAddresses = Holepuncher.localAddresses(c.dht.io.serverSocket)
      const addr = Holepuncher.matchAddress(myAddresses, serverAddresses) || serverAddresses[0]

      const socket = c.dht.io.serverSocket
      try {
        await c.dht.ping(addr)
      } catch {
        maybeDestroyEncryptedSocket(c, HOLEPUNCH_ABORTED())
        return
      }
      c.onsocket(socket, addr.port, addr.host)
      return
    }
  }

  if (!remoteHolepunchable) {
    maybeDestroyEncryptedSocket(c, CANNOT_HOLEPUNCH())
    return
  }

  c.puncher = new Holepuncher(c.dht, c.session, true, payload.firewall)

  c.puncher.onconnect = c.onsocket
  c.puncher.onabort = onabort

  const serverRelay = pickServerRelay(payload.holepunch.relays, relayAddress)

  // Begin holepunching!

  let probe
  try {
    probe = await probeRound(c, opts.fastOpen === false ? null : serverAddress, serverRelay, true)
  } catch (err) {
    destroyPuncher(c)
    // TODO: we should retry here with some of the other relays, bail for now
    maybeDestroyEncryptedSocket(c, err)
    return
  }

  if (isDone(c) || !probe) return
  const { token, peerAddress } = probe

  // If the relay the server picked is the same as the relay the client picked,
  // then we can use the peerAddress that round one indicates the server wants to use.
  // This shaves off a roundtrip if the server chose to reroll its socket due to some NAT
  // issue with the first one it picked (ie mobile nat inconsistencies...).
  // If the relays were different, then the server would not have a UDP session open on this address
  // to the client relay, which round2 uses.
  if (
    !diffAddress(serverRelay.relayAddress, relayAddress) &&
    diffAddress(serverAddress, peerAddress)
  ) {
    serverAddress = peerAddress
    await c.puncher.openSession(serverAddress)
    if (isDone(c)) return
  }

  // TODO: still continue here if a local connection might work, but then do not holepunch...
  if (
    opts.holepunch &&
    !opts.holepunch(
      c.puncher.remoteFirewall,
      c.puncher.nat.firewall,
      c.puncher.remoteAddresses,
      c.puncher.nat.addresses
    )
  ) {
    await abort(c, serverRelay, HOLEPUNCH_ABORTED('Client aborted holepunch'))
    return
  }

  try {
    await roundPunch(c, serverAddress, token, relayAddress, serverRelay, false)
  } catch (err) {
    destroyPuncher(c)
    // TODO: retry with another relay?
    maybeDestroyEncryptedSocket(c, err)
  }
}

async function connectThroughNodes(c, addresses, socket) {
  for (const address of addresses) {
    if (isDone(c) || c.connect) return

    c.remoteRelayAddresses.push(address)
    await connectThroughNode(c, address, socket)
  }
}

async function findAndConnect(c, opts) {
  let attempts = 0
  let relayAddresses =
    opts.relayAddresses && opts.relayAddresses.length ? opts.relayAddresses : null

  if (!relayAddresses) {
    const cachedRelayAddresses = c.dht._relayAddressesCache.get(c.id)
    if (cachedRelayAddresses) relayAddresses = cachedRelayAddresses
  }

  if (c.dht._persistent) {
    // check if we know the route ourself...
    const route = c.dht._router.get(c.target)
    if (route && route.relay !== null) {
      relayAddresses = [{ host: route.relay.host, port: route.relay.port }]
    }
  }

  // 2 is how many parallel connect attempts we want to do, we can make this configurable
  const preConnect = relayAddresses !== null && relayAddresses.length > 0
  const sem = new Semaphore(preConnect ? 3 : 2)
  const signal = sem.signal.bind(sem)
  const tries = relayAddresses !== null ? 2 : 1

  if (preConnect) {
    await sem.wait()
    connectThroughNodes(c, relayAddresses, null).then(signal, signal)
  }

  try {
    for (let i = 0; i < tries && !isDone(c) && !c.connect; i++) {
      c.query = c.dht.findPeer(c.target, {
        hash: false,
        session: c.session,
        nodes: relayAddresses,
        retries: 3
      })

      for await (const data of c.query) {
        await sem.wait()
        if (isDone(c)) return

        if (c.connect) {
          sem.signal()
          break
        }

        // Skip node already run via preConnect
        if (preConnect && relayAddresses && isRelayAddress(relayAddresses, data)) {
          sem.signal()
          continue
        }

        c.remoteRelayAddresses.push(data.from)
        attempts++
        connectThroughNode(c, data.from, null).then(signal, signal)
      }

      relayAddresses = null

      if (attempts > 0) await sem.flush()
    }

    c.query = null
    if (isDone(c)) return

    // flush the semaphore
    await sem.flush()
    if (isDone(c)) return
  } catch (err) {
    c.query = null
    maybeDestroyEncryptedSocket(c, err)
    return
  }

  if (!c.connect) {
    maybeDestroyEncryptedSocket(c, attempts ? PEER_CONNECTION_FAILED() : PEER_NOT_FOUND())
  }
}

async function connectThroughNode(c, address, socket) {
  if (!c.requesting) {
    // If we have a stable server address, send it over now
    const addr = c.dht.remoteAddress()
    const localAddrs = c.lan ? Holepuncher.localAddresses(c.dht.io.serverSocket) : null
    const addresses4 = []

    if (addr) addresses4.push(addr)
    if (localAddrs) addresses4.push(...localAddrs)

    c.firewall = addr ? FIREWALL.OPEN : FIREWALL.UNKNOWN
    c.requesting = true
    c.request = await c.handshake.send({
      error: ERROR.NONE,
      firewall: c.firewall,
      holepunch: null,
      addresses4,
      addresses6: [],
      udx: {
        reusableSocket: c.reusableSocket,
        id: c.rawStream.id,
        seq: 0
      },
      secretStream: {},
      relayThrough: c.relayThrough ? { publicKey: c.relayThrough, token: c.relayToken } : null
    })
    if (isDone(c)) return
  }

  const { serverAddress, clientAddress, relayed, noise } = await c.dht._router.peerHandshake(
    c.target,
    { noise: c.request, socket, session: c.session },
    address
  )
  if (isDone(c) || c.connect) return

  const payload = await c.handshake.recv(noise)
  if (isDone(c) || !payload) return

  if (payload.version !== 1) {
    maybeDestroyEncryptedSocket(c, SERVER_INCOMPATIBLE())
    return
  }
  if (payload.error !== ERROR.NONE) {
    maybeDestroyEncryptedSocket(c, SERVER_ERROR())
    return
  }
  if (!payload.udx) {
    maybeDestroyEncryptedSocket(c, SERVER_ERROR('Server did not send UDX data'))
    return
  }

  const hs = c.handshake.final()

  c.handshake = null
  c.request = null
  c.requesting = false
  c.connect = {
    relayed,
    relayAddress: address,
    clientAddress,
    serverAddress,
    payload
  }

  c.payload = new SecurePayload(hs.holepunchSecret)

  c.onsocket = function (socket, port, host) {
    if (c.rawStream === null) return // Already hole punched

    if (c.rawStream.connected) {
      const remoteChanging = c.rawStream.changeRemote(socket, c.connect.payload.udx.id, port, host)

      if (remoteChanging) remoteChanging.catch(safetyCatch)
    } else {
      // cache the relay addrs for a future reconnect, we prefer the remote one so they
      // can give us the correct ones from their pov
      if (payload.relayAddresses && payload.relayAddresses.length) {
        c.dht._relayAddressesCache.set(c.id, payload.relayAddresses)
      } else if (c.remoteRelayAddresses.length) {
        c.dht._relayAddressesCache.set(c.id, c.remoteRelayAddresses)
      }

      c.rawStream.connect(socket, c.connect.payload.udx.id, port, host)
      c.encryptedSocket.start(c.rawStream, { handshake: hs })
    }

    if (c.reusableSocket && payload.udx.reusableSocket) {
      c.dht._socketPool.routes.add(c.remotePublicKey, c.rawStream)
    }

    if (c.puncher) {
      c.puncher.onabort = noop
      c.puncher.destroy()
    }

    if (c.passiveConnectTimeout) {
      clearPassiveConnectTimeout(c)
    }

    c.rawStream = null
  }

  if (payload.relayThrough || c.relayThrough) {
    relayConnection(c, c.relayThrough, payload, hs)
  }

  if (c.serverSocket) {
    c.onsocket(c.serverSocket, c.serverAddress.port, c.serverAddress.host)
    return
  }

  if (!relayed) {
    c.onsocket(socket || c.dht.socket, address.port, address.host)
  }

  c.session.destroy()
}

async function updateHolepunch(c, peerAddress, relayAddr, payload) {
  const holepunch = await c.dht._router.peerHolepunch(
    c.target,
    {
      id: c.connect.payload.holepunch.id,
      payload: c.payload.encrypt(payload),
      peerAddress,
      socket: c.puncher.socket,
      session: c.session
    },
    relayAddr
  )

  if (isDone(c)) return null

  const remotePayload = c.payload.decrypt(holepunch.payload)
  if (!remotePayload) {
    throw HOLEPUNCH_INVALID()
  }

  const { error, firewall, punching, addresses, remoteToken } = remotePayload

  if (error === ERROR.TRY_LATER && c.relayToken && payload.punching) {
    return {
      tryLater: true,
      ...holepunch,
      payload: remotePayload
    }
  }

  if (error !== ERROR.NONE) {
    throw REMOTE_ABORTED('Remote aborted with error code ' + error)
  }

  const echoed = !!(remoteToken && payload.token && b4a.equals(remoteToken, payload.token))

  c.puncher.updateRemote({
    punching,
    firewall,
    addresses,
    verified: echoed ? peerAddress.host : null
  })

  return {
    tryLater: false,
    ...holepunch,
    payload: remotePayload
  }
}

async function probeRound(c, serverAddress, serverRelay, retry) {
  // Open a quick low ttl session against what we think is the server
  if (serverAddress) await c.puncher.openSession(serverAddress)

  if (isDone(c)) return null

  const reply = await updateHolepunch(c, serverRelay.peerAddress, serverRelay.relayAddress, {
    error: ERROR.NONE,
    firewall: c.puncher.nat.firewall,
    round: c.round++,
    connected: false,
    punching: false,
    addresses: c.puncher.nat.addresses,
    remoteAddress: serverAddress,
    token: null,
    remoteToken: null
  })

  if (isDone(c) || !reply) return null

  const { peerAddress } = reply
  const { address, token } = reply.payload

  c.puncher.nat.add(reply.to, reply.from)

  // Open another quick low ttl session against what the server says their address is,
  // if they haven't said they are random yet
  if (
    c.puncher.remoteFirewall < FIREWALL.RANDOM &&
    address &&
    address.host &&
    address.port &&
    diffAddress(address, serverAddress)
  ) {
    await c.puncher.openSession(address)
    if (isDone(c)) return null
  }

  // If the remote told us they didn't know their nat firewall yet, give them a chance to figure it out
  // They might say this to see if the "fast mode" punch comes through first.
  if (c.puncher.remoteFirewall === FIREWALL.UNKNOWN) {
    await c.sleeper.pause(1000)
    if (isDone(c)) return null
  }

  let stable = await c.puncher.analyze(false)
  if (isDone(c)) return null

  // If the socket seems unstable, try to make it stable by setting the "allowReopen" flag
  // Mostly relevant for mobile networks
  if (!stable) {
    stable = await c.puncher.analyze(true)
    if (isDone(c)) return null
    if (stable) return probeRound(c, serverAddress, serverRelay, false)
  }

  if ((c.puncher.remoteFirewall === FIREWALL.UNKNOWN || !token) && retry) {
    return probeRound(c, serverAddress, serverRelay, false)
  }

  if (
    c.puncher.remoteFirewall === FIREWALL.UNKNOWN ||
    c.puncher.nat.firewall === FIREWALL.UNKNOWN
  ) {
    await abort(c, serverRelay, HOLEPUNCH_PROBE_TIMEOUT())
    return null
  }

  if (c.puncher.remoteFirewall >= FIREWALL.RANDOM && c.puncher.nat.firewall >= FIREWALL.RANDOM) {
    await abort(c, serverRelay, HOLEPUNCH_DOUBLE_RANDOMIZED_NATS())
    return null
  }

  return { token, peerAddress }
}

async function roundPunch(c, serverAddress, remoteToken, clientRelay, serverRelay, delayed) {
  // We are gossiping our final NAT status to the other peer now
  // so make sure we don't update our local view for now as that can make things weird
  c.puncher.nat.freeze()

  const isRandom =
    c.puncher.remoteFirewall >= FIREWALL.RANDOM || c.puncher.nat.firewall >= FIREWALL.RANDOM
  if (isRandom) {
    while (
      c.dht._randomPunches >= c.dht._randomPunchLimit ||
      Date.now() - c.dht._lastRandomPunch < c.dht._randomPunchInterval
    ) {
      // if no relay can help, bail
      if (!c.relayToken) throw HOLEPUNCH_ABORTED()

      if (!delayed) {
        delayed = true
        await updateHolepunch(c, serverAddress, clientRelay, {
          error: ERROR.NONE,
          firewall: c.puncher.nat.firewall,
          round: c.round++,
          connected: false,
          punching: false,
          addresses: c.puncher.nat.addresses,
          remoteAddress: null,
          token: c.payload.token(serverAddress),
          remoteToken
        })
        if (isDone(c)) return
      }

      await tryLater(c)
      if (isDone(c)) return
    }
  }

  // increment now, so we can commit to punching
  if (isRandom) c.dht._randomPunches++

  let reply

  try {
    // if delayed switch to the servers chosen relay - we validated anyway
    reply = await updateHolepunch(
      c,
      delayed ? serverRelay.peerAddress : serverAddress,
      delayed ? serverRelay.relayAddress : clientRelay,
      {
        error: ERROR.NONE,
        firewall: c.puncher.nat.firewall,
        round: c.round++,
        connected: false,
        punching: true,
        addresses: c.puncher.nat.addresses,
        remoteAddress: null,
        token: delayed ? null : c.payload.token(serverAddress),
        remoteToken
      }
    )
  } finally {
    // decrement as punch increments for us
    if (isRandom) c.dht._randomPunches--
  }

  if (isDone(c)) return
  if (!reply) return

  if (reply.tryLater) {
    await tryLater(c)
    if (isDone(c)) return
    return roundPunch(c, serverAddress, remoteToken, clientRelay, serverRelay, true)
  }

  if (!c.puncher.remoteHolepunching) {
    throw REMOTE_NOT_HOLEPUNCHING()
  }

  if (!(await c.puncher.punch())) {
    throw REMOTE_NOT_HOLEPUNCHABLE()
  }
}

async function tryLater(c) {
  if (!c.relayToken) throw HOLEPUNCH_ABORTED()
  await c.sleeper.pause(10000 + Math.round(Math.random() * 10000))
}

function maybeDestroyEncryptedSocket(c, err) {
  if (isDone(c)) return
  if (c.encryptedSocket.rawStream) return
  if (c.relaySocket) return // waiting for the relay
  if (c.puncher && !c.puncher.destroyed) return // waiting for the puncher
  c.session.destroy()
  c.encryptedSocket.destroy(err)
}

async function abort(c, { peerAddress, relayAddress }, err) {
  try {
    await updateHolepunch(c, peerAddress, relayAddress, {
      error: ERROR.ABORTED,
      firewall: FIREWALL.UNKNOWN,
      round: c.round++,
      connected: false,
      punching: false,
      addresses: null,
      remoteAddress: null,
      token: null,
      remoteToken: null
    })
  } catch (err) {
    safetyCatch(err)
  }

  destroyPuncher(c)
  maybeDestroyEncryptedSocket(c, err)
}

function relayConnection(c, relayThrough, payload, hs) {
  let isInitiator
  let publicKey
  let token

  if (payload.relayThrough) {
    isInitiator = false
    publicKey = payload.relayThrough.publicKey
    token = payload.relayThrough.token
  } else {
    isInitiator = true
    publicKey = relayThrough
    token = c.relayToken
  }

  c.relayToken = token
  c.relaySocket = c.dht.connect(publicKey)
  c.relaySocket.setKeepAlive(c.relayKeepAlive)
  c.relayClient = relay.Client.from(c.relaySocket, { id: c.relaySocket.publicKey })
  c.relayTimeout = setTimeout(onabort, 15000, null)

  c.relayClient.pair(isInitiator, token, c.rawStream).on('error', onabort).on('data', ondata)

  function ondata(remoteId) {
    if (c.relayTimeout) clearRelayTimeout(c)
    if (c.rawStream === null) {
      onabort(null)
      return
    }

    c.relayPaired = true

    const { remotePort, remoteHost, socket } = c.relaySocket.rawStream

    c.rawStream
      .on('close', () => c.relaySocket.destroy())
      .connect(socket, remoteId, remotePort, remoteHost)

    c.encryptedSocket.start(c.rawStream, { handshake: hs })
  }

  function onabort(err) {
    if (c.relayTimeout) clearRelayTimeout(c)
    const socket = c.relaySocket
    c.relayToken = null
    c.relaySocket = null
    if (socket) socket.destroy()
    maybeDestroyEncryptedSocket(c, err || RELAY_ABORTED())
  }
}

function clearPassiveConnectTimeout(c) {
  clearTimeout(c.passiveConnectTimeout)
  c.passiveConnectTimeout = null
}

function clearRelayTimeout(c) {
  clearTimeout(c.relayTimeout)
  c.relayTimeout = null
}

function destroyPuncher(c) {
  if (c.puncher) c.puncher.destroy()
  c.session.destroy()
}

function pickServerRelay(relays, clientRelay) {
  for (const r of relays) {
    if (!diffAddress(r.relayAddress, clientRelay)) return r
  }
  return relays[0]
}

function diffAddress(a, b) {
  return a.host !== b.host || a.port !== b.port
}

function defaultCreateHandshake(keyPair, remotePublicKey) {
  return new NoiseWrap(keyPair, remotePublicKey)
}

function defaultCreateSecretStream(isInitiator, rawStream, opts) {
  return new NoiseSecretStream(isInitiator, rawStream, opts)
}

function onlyNonReserved(addr) {
  return !isReserved(addr.host)
}

function isRelay(relaySocket, socket, port, host) {
  const stream = relaySocket.rawStream
  if (!stream) return false
  if (stream.socket !== socket) return false
  return port === stream.remotePort && host === stream.remoteHost
}

function selectRelay(relayThrough) {
  if (typeof relayThrough === 'function') relayThrough = relayThrough()
  if (relayThrough === null) return null
  if (Array.isArray(relayThrough))
    return relayThrough[Math.floor(Math.random() * relayThrough.length)]
  return relayThrough
}

function isRelayAddress(relayAddresses, data) {
  for (const node of relayAddresses) {
    if (node.host === data.from.host && node.port === data.from.port) return true
  }

  return false
}

function noop() {}
const EventEmitter = require('events')
const b4a = require('b4a')
const errors = require('./errors')

module.exports = class ConnectionPool extends EventEmitter {
  constructor(dht) {
    super()

    this._dht = dht
    this._servers = new Map()
    this._connecting = new Map()
    this._connections = new Map()
  }

  _attachServer(server) {
    const keyString = b4a.toString(server.publicKey, 'hex')

    this._servers.set(keyString, server)

    server
      .on('close', () => {
        this._servers.delete(keyString)
      })
      .on('connection', (socket) => {
        this._attachStream(socket, true)
      })
  }

  _attachStream(stream, opened) {
    const existing = this.get(stream.remotePublicKey)

    if (existing) {
      const keepNew =
        stream.isInitiator === existing.isInitiator ||
        b4a.compare(stream.publicKey, stream.remotePublicKey) > 0

      if (keepNew) {
        let closed = false

        const onclose = () => {
          closed = true
        }

        existing
          .on('error', noop)
          .on('close', () => {
            if (closed) return

            stream.off('error', noop).off('close', onclose)

            this._attachStream(stream, opened)
          })
          .destroy(errors.DUPLICATE_CONNECTION())

        stream.on('error', noop).on('close', onclose)
      } else {
        stream.on('error', noop).destroy(errors.DUPLICATE_CONNECTION())
      }

      return
    }

    const session = new ConnectionRef(this, stream)

    const keyString = b4a.toString(stream.remotePublicKey, 'hex')

    if (opened) {
      this._connections.set(keyString, session)

      stream.on('close', () => {
        this._connections.delete(keyString)
      })

      this.emit('connection', stream, session)
    } else {
      this._connecting.set(keyString, session)

      stream
        .on('error', noop)
        .on('close', () => {
          if (opened) this._connections.delete(keyString)
          else this._connecting.delete(keyString)
        })
        .on('open', () => {
          opened = true

          this._connecting.delete(keyString)
          this._connections.set(keyString, session)

          stream.off('error', noop)

          this.emit('connection', stream, session)
        })
    }

    return session
  }

  get connecting() {
    return this._connecting.size
  }

  get connections() {
    return this._connections.values()
  }

  has(publicKey) {
    const keyString = b4a.toString(publicKey, 'hex')

    return this._connections.has(keyString) || this._connecting.has(keyString)
  }

  get(publicKey) {
    const keyString = b4a.toString(publicKey, 'hex')

    const existing = this._connections.get(keyString) || this._connecting.get(keyString)

    return existing?._stream || null
  }
}

class ConnectionRef {
  constructor(pool, stream) {
    this._pool = pool
    this._stream = stream
    this._refs = 0
  }

  active() {
    this._refs++
  }

  inactive() {
    this._refs--
  }

  release() {
    this._stream.destroy()
  }
}

function noop() {}
const crypto = require('hypercore-crypto')

const COMMANDS = (exports.COMMANDS = {
  PEER_HANDSHAKE: 0,
  PEER_HOLEPUNCH: 1,
  FIND_PEER: 2,
  LOOKUP: 3,
  ANNOUNCE: 4,
  UNANNOUNCE: 5,
  MUTABLE_PUT: 6,
  MUTABLE_GET: 7,
  IMMUTABLE_PUT: 8,
  IMMUTABLE_GET: 9,
  PLUGIN: 10
})

exports.BOOTSTRAP_NODES = global.Pear?.config.dht?.bootstrap || [
  '88.99.3.86@node1.hyperdht.org:49737',
  '142.93.90.113@node2.hyperdht.org:49737',
  '138.68.147.8@node3.hyperdht.org:49737'
]

exports.KNOWN_NODES = global.Pear?.config.dht?.nodes || []

exports.FIREWALL = {
  UNKNOWN: 0,
  OPEN: 1,
  CONSISTENT: 2,
  RANDOM: 3
}

exports.ERROR = {
  // noise / connection related
  NONE: 0,
  ABORTED: 1,
  VERSION_MISMATCH: 2,
  TRY_LATER: 3,
  // dht related
  SEQ_REUSED: 16,
  SEQ_TOO_LOW: 17
}

const [
  NS_ANNOUNCE,
  NS_UNANNOUNCE,
  NS_MUTABLE_PUT,
  NS_PEER_HANDSHAKE,
  NS_PEER_HOLEPUNCH,
  NS_PLUGIN
] = crypto.namespace('hyperswarm/dht', [
  COMMANDS.ANNOUNCE,
  COMMANDS.UNANNOUNCE,
  COMMANDS.MUTABLE_PUT,
  COMMANDS.PEER_HANDSHAKE,
  COMMANDS.PEER_HOLEPUNCH,
  COMMANDS.PLUGIN
])

exports.NS = {
  ANNOUNCE: NS_ANNOUNCE,
  UNANNOUNCE: NS_UNANNOUNCE,
  MUTABLE_PUT: NS_MUTABLE_PUT,
  PEER_HANDSHAKE: NS_PEER_HANDSHAKE,
  PEER_HOLEPUNCH: NS_PEER_HOLEPUNCH,
  PLUGIN: NS_PLUGIN
}
const sodium = require('sodium-universal')
const b4a = require('b4a')

function hash(data) {
  const out = b4a.allocUnsafe(32)
  sodium.crypto_generichash(out, data)
  return out
}

function unslabbedHash(data) {
  const out = b4a.allocUnsafeSlow(32)
  sodium.crypto_generichash(out, data)
  return out
}

function createKeyPair(seed) {
  const publicKey = b4a.alloc(32)
  const secretKey = b4a.alloc(64)
  if (seed) sodium.crypto_sign_seed_keypair(publicKey, secretKey, seed)
  else sodium.crypto_sign_keypair(publicKey, secretKey)
  return { publicKey, secretKey }
}

module.exports = {
  hash,
  unslabbedHash,
  createKeyPair
}
const b4a = require('b4a')
const cenc = require('compact-encoding')

function encodeUnslab(enc, m) {
  // Faster than unslab(c.encode(enc, data)) because it avoids the mem copy.
  // Makes sense to put in compact-encoding when we need it in other modules too
  const state = cenc.state()
  enc.preencode(state, m)
  state.buffer = b4a.allocUnsafeSlow(state.end)
  enc.encode(state, m)
  return state.buffer
}

module.exports = {
  encodeUnslab
}
module.exports = class DHTError extends Error {
  constructor(msg, code, fn = DHTError) {
    super(`${code}: ${msg}`)
    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  get name() {
    return 'DHTError'
  }

  static BAD_HANDSHAKE_REPLY(msg = 'Bad handshake reply') {
    return new DHTError(msg, 'BAD_HANDSHAKE_REPLY', DHTError.BAD_HANDSHAKE_REPLY)
  }

  static BAD_HOLEPUNCH_REPLY(msg = 'Bad holepunch reply') {
    return new DHTError(msg, 'BAD_HOLEPUNCH_REPLY', DHTError.BAD_HOLEPUNCH_REPLY)
  }

  static HOLEPUNCH_ABORTED(msg = 'Holepunch aborted') {
    return new DHTError(msg, 'HOLEPUNCH_ABORTED', DHTError.HOLEPUNCH_ABORTED)
  }

  static HOLEPUNCH_INVALID(msg = 'Invalid holepunch payload') {
    return new DHTError(msg, 'HOLEPUNCH_INVALID', DHTError.HOLEPUNCH_INVALID)
  }

  static HOLEPUNCH_PROBE_TIMEOUT(msg = 'Holepunching probe did not finish in time') {
    return new DHTError(msg, 'HOLEPUNCH_PROBE_TIMEOUT', DHTError.HOLEPUNCH_PROBE_TIMEOUT)
  }

  static HOLEPUNCH_DOUBLE_RANDOMIZED_NATS(msg = 'Both remote and local NATs are randomized') {
    return new DHTError(
      msg,
      'HOLEPUNCH_DOUBLE_RANDOMIZED_NATS',
      DHTError.HOLEPUNCH_DOUBLE_RANDOMIZED_NATS
    )
  }

  static CANNOT_HOLEPUNCH(msg = 'Cannot holepunch to remote') {
    return new DHTError(msg, 'CANNOT_HOLEPUNCH', DHTError.CANNOT_HOLEPUNCH)
  }

  static REMOTE_NOT_HOLEPUNCHING(msg = 'Remote is not holepunching') {
    return new DHTError(msg, 'REMOTE_NOT_HOLEPUNCHING', DHTError.REMOTE_NOT_HOLEPUNCHING)
  }

  static REMOTE_NOT_HOLEPUNCHABLE(msg = 'Remote is not holepunchable') {
    return new DHTError(msg, 'REMOTE_NOT_HOLEPUNCHABLE', DHTError.REMOTE_NOT_HOLEPUNCHABLE)
  }

  static REMOTE_ABORTED(msg = 'Remote aborted') {
    return new DHTError(msg, 'REMOTE_ABORTED', DHTError.REMOTE_ABORTED)
  }

  static HANDSHAKE_UNFINISHED(msg = 'Handshake did not finish') {
    return new DHTError(msg, 'HANDSHAKE_UNFINISHED', DHTError.HANDSHAKE_UNFINISHED)
  }

  static HANDSHAKE_INVALID(msg = 'Received invalid handshake') {
    return new DHTError(msg, 'HANDSHAKE_INVALID', DHTError.HANDSHAKE_INVALID)
  }

  static ALREADY_LISTENING(msg = 'Already listening') {
    return new DHTError(msg, 'ALREADY_LISTENING', DHTError.ALREADY_LISTENING)
  }

  static KEYPAIR_ALREADY_USED(msg = 'Keypair already used') {
    return new DHTError(msg, 'KEYPAIR_ALREADY_USED', DHTError.KEYPAIR_ALREADY_USED)
  }

  static NODE_DESTROYED(msg = 'Node destroyed') {
    return new DHTError(msg, 'NODE_DESTROYED', DHTError.NODE_DESTROYED)
  }

  static PEER_CONNECTION_FAILED(msg = 'Could not connect to peer') {
    return new DHTError(msg, 'PEER_CONNECTION_FAILED', DHTError.PEER_CONNECTION_FAILED)
  }

  static PEER_NOT_FOUND(msg = 'Peer not found') {
    return new DHTError(msg, 'PEER_NOT_FOUND', DHTError.PEER_NOT_FOUND)
  }

  static STREAM_NOT_CONNECTED(msg = 'Stream is not connected') {
    return new DHTError(msg, 'STREAM_NOT_CONNECTED', DHTError.STREAM_DISCONNECTED)
  }

  static SERVER_INCOMPATIBLE(msg = 'Server is using an incompatible version') {
    return new DHTError(msg, 'SERVER_INCOMPATIBLE', DHTError.SERVER_INCOMPATIBLE)
  }

  static SERVER_ERROR(msg = 'Server returned an error') {
    return new DHTError(msg, 'SERVER_ERROR', DHTError.SERVER_ERROR)
  }

  static DUPLICATE_CONNECTION(msg = 'Duplicate connection') {
    return new DHTError(msg, 'DUPLICATE_CONNECTION', DHTError.DUPLICATE_CONNECTION)
  }

  static RELAY_ABORTED(msg = 'Relay aborted') {
    return new DHTError(msg, 'RELAY_ABORTED', DHTError.RELAY_ABORTED)
  }

  static SUSPENDED(msg = 'Suspended') {
    return new DHTError(msg, 'SUSPENDED', DHTError.SUSPENDED)
  }
}
const b4a = require('b4a')
const Nat = require('./nat')
const Sleeper = require('./sleeper')
const { FIREWALL } = require('./constants')

const BIRTHDAY_SOCKETS = 256
const HOLEPUNCH = b4a.from([0])
const HOLEPUNCH_TTL = 5
const DEFAULT_TTL = 64
const MAX_REOPENS = 3

module.exports = class Holepuncher {
  constructor(dht, session, isInitiator, remoteFirewall = FIREWALL.UNKNOWN) {
    const holder = dht._socketPool.acquire()

    this.dht = dht
    this.session = session

    this.nat = new Nat(dht, session, holder.socket)
    this.nat.autoSample()

    this.isInitiator = isInitiator

    // events
    this.onconnect = noop
    this.onabort = noop

    this.punching = false
    this.connected = false
    this.destroyed = false
    this.randomized = false

    // track remote state
    this.remoteFirewall = remoteFirewall
    this.remoteAddresses = []
    this.remoteHolepunching = false

    this._sleeper = new Sleeper()
    this._reopening = null
    this._timeout = null
    this._punching = null
    this._allHolders = []
    this._holder = this._addRef(holder)
  }

  get socket() {
    return this._holder.socket
  }

  updateRemote({ punching, firewall, addresses, verified }) {
    const remoteAddresses = []

    if (addresses) {
      for (const addr of addresses) {
        remoteAddresses.push({
          host: addr.host,
          port: addr.port,
          verified: verified === addr.host || this._isVerified(addr.host)
        })
      }
    }

    this.remoteFirewall = firewall
    this.remoteAddresses = remoteAddresses
    this.remoteHolepunching = punching
  }

  _isVerified(host) {
    for (const addr of this.remoteAddresses) {
      if (addr.verified && addr.host === host) {
        return true
      }
    }
    return false
  }

  ping(addr, socket = this._holder.socket) {
    return holepunch(socket, addr, false)
  }

  openSession(addr, socket = this._holder.socket) {
    return holepunch(socket, addr, true)
  }

  async analyze(allowReopen) {
    await this.nat.analyzing
    if (this._unstable()) {
      if (!allowReopen) return false
      if (!this._reopening) this._reopening = this._reopen()
      return this._reopening
    }
    return true
  }

  _unstable() {
    // TODO!!: We need an additional heuristic here... If we were NOT random in the past we should also do this.
    const firewall = this.nat.firewall
    return (
      (this.remoteFirewall >= FIREWALL.RANDOM && firewall >= FIREWALL.RANDOM) ||
      firewall === FIREWALL.UNKNOWN
    )
  }

  _reset() {
    const prev = this._holder

    this._allHolders.pop()
    this._holder = this._addRef(this.dht._socketPool.acquire())

    prev.release()
    this.nat.destroy()

    this.nat = new Nat(this.dht, this.session, this._holder.socket)
    // TODO: maybe make auto sampling configurable somehow?
    this.nat.autoSample()
  }

  _addRef(ref) {
    this._allHolders.push(ref)
    ref.onholepunchmessage = (msg, rinfo) => this._onholepunchmessage(msg, rinfo, ref)
    return ref
  }

  _onholepunchmessage(_, addr, ref) {
    if (!this.isInitiator) {
      // TODO: we don't need this if we had a way to connect a socket to many hosts
      holepunch(ref.socket, addr, false) // never fails
      return
    }

    if (this.connected) return

    this.connected = true
    this.punching = false

    for (const r of this._allHolders) {
      if (r === ref) continue
      r.release()
    }

    this._allHolders[0] = ref
    while (this._allHolders.length > 1) this._allHolders.pop()

    this._decrementRandomized()
    this.onconnect(ref.socket, addr.port, addr.host)
  }

  _done() {
    return this.destroyed || this.connected
  }

  async _reopen() {
    for (let i = 0; this._unstable() && i < MAX_REOPENS && !this._done() && !this.punching; i++) {
      this._reset()
      await this.nat.analyzing
    }

    return coerceFirewall(this.nat.firewall) === FIREWALL.CONSISTENT
  }

  punch() {
    if (!this._punching) this._punching = this._punch()
    return this._punching
  }

  async _punch() {
    if (this._done() || !this.remoteAddresses.length) return false

    this.punching = true

    // Coerce into consistency for now. Obvs we could make this this more efficient if we use that info
    // but that's seldomly used since those will just use tcp most of the time.

    const local = coerceFirewall(this.nat.firewall)
    const remote = coerceFirewall(this.remoteFirewall)

    // Note that most of these async functions are meant to run in the background
    // which is why we don't await them here and why they are not allowed to throw

    let remoteVerifiedAddress = null
    for (const addr of this.remoteAddresses) {
      if (addr.verified) {
        remoteVerifiedAddress = addr
        break
      }
    }

    if (local === FIREWALL.CONSISTENT && remote === FIREWALL.CONSISTENT) {
      this.dht.stats.punches.consistent++
      this._consistentProbe()
      return true
    }

    if (!remoteVerifiedAddress) return false

    if (local === FIREWALL.CONSISTENT && remote >= FIREWALL.RANDOM) {
      this.dht.stats.punches.random++
      this._incrementRandomized()
      this._randomProbes(remoteVerifiedAddress)
      return true
    }

    if (local >= FIREWALL.RANDOM && remote === FIREWALL.CONSISTENT) {
      this.dht.stats.punches.random++
      this._incrementRandomized()
      await this._openBirthdaySockets(remoteVerifiedAddress)
      if (this.punching) this._keepAliveRandomNat(remoteVerifiedAddress)
      return true
    }

    return false
  }

  // Note that this never throws so it is safe to run in the background
  async _consistentProbe() {
    // Here we do the sleep first because the "fast open" mode in the server just fired a ping
    if (!this.isInitiator) await this._sleeper.pause(1000)

    let tries = 0

    while (this.punching && tries++ < 10) {
      for (const addr of this.remoteAddresses) {
        // only try unverified addresses every 4 ticks
        if (!addr.verified && (tries & 3) !== 0) continue
        await holepunch(this._holder.socket, addr, false)
      }
      if (this.punching) await this._sleeper.pause(1000)
    }

    this._autoDestroy()
  }

  // Note that this never throws so it is safe to run in the background
  async _randomProbes(remoteAddr) {
    let tries = 1750 // ~35s

    while (this.punching && tries-- > 0) {
      const addr = { host: remoteAddr.host, port: randomPort() }
      await holepunch(this._holder.socket, addr, false)
      if (this.punching) await this._sleeper.pause(20)
    }

    this._autoDestroy()
  }

  // Note that this never throws so it is safe to run in the background
  async _keepAliveRandomNat(remoteAddr) {
    let i = 0
    let lowTTLRounds = 1

    // TODO: experiment with this here. We just bursted all the messages in
    // openOtherSockets to ensure the sockets are open, so it's potentially
    // a good idea to slow down for a bit.
    await this._sleeper.pause(100)

    let tries = 1750 // ~35s

    while (this.punching && tries-- > 0) {
      if (i === this._allHolders.length) {
        i = 0
        if (lowTTLRounds > 0) lowTTLRounds--
      }

      await holepunch(this._allHolders[i++].socket, remoteAddr, lowTTLRounds > 0)
      if (this.punching) await this._sleeper.pause(20)
    }

    this._autoDestroy()
  }

  async _openBirthdaySockets(remoteAddr) {
    while (this.punching && this._allHolders.length < BIRTHDAY_SOCKETS) {
      const ref = this._addRef(this.dht._socketPool.acquire())
      await holepunch(ref.socket, remoteAddr, HOLEPUNCH_TTL)
    }
  }

  _autoDestroy() {
    if (!this.connected) this.destroy()
  }

  _incrementRandomized() {
    if (!this.randomized) {
      this.randomized = true
      this.dht._randomPunches++
    }
  }

  _decrementRandomized() {
    if (this.randomized) {
      this.dht._lastRandomPunch = Date.now()
      this.randomized = false
      this.dht._randomPunches--
    }
  }

  destroy() {
    if (this.destroyed) return
    this.destroyed = true
    this.punching = false

    for (const ref of this._allHolders) ref.release()
    this._allHolders = []
    this.nat.destroy()

    if (!this.connected) {
      this._decrementRandomized()
      this.onabort()
    }
  }

  static ping(socket, addr) {
    return holepunch(socket, addr, false)
  }

  static localAddresses(socket) {
    return localAddresses(socket)
  }

  static matchAddress(myAddresses, externalAddresses) {
    return matchAddress(myAddresses, externalAddresses)
  }
}

function holepunch(socket, addr, lowTTL) {
  return socket.send(HOLEPUNCH, addr.port, addr.host, lowTTL ? HOLEPUNCH_TTL : DEFAULT_TTL)
}

function randomPort() {
  return (1000 + Math.random() * 64536) | 0
}

function coerceFirewall(fw) {
  return fw === FIREWALL.OPEN ? FIREWALL.CONSISTENT : fw
}

function localAddresses(socket) {
  const addrs = []
  const { host, port } = socket.address()

  if (host === '127.0.0.1') return [{ host, port }]

  for (const n of socket.udx.networkInterfaces()) {
    if (n.family !== 4 || n.internal) continue

    addrs.push({ host: n.host, port })
  }

  if (addrs.length === 0) {
    addrs.push({ host: '127.0.0.1', port })
  }

  return addrs
}

function matchAddress(localAddresses, remoteLocalAddresses) {
  if (remoteLocalAddresses.length === 0) return null

  let best = { segment: 1, addr: null }

  for (const localAddress of localAddresses) {
    // => 192.168.122.238
    const a = localAddress.host.split('.')

    for (const remoteAddress of remoteLocalAddresses) {
      // => 192.168.0.23
      // => 192.168.122.1
      const b = remoteAddress.host.split('.')

      // Matches 192.*.*.*
      if (a[0] === b[0]) {
        if (best.segment === 1) best = { segment: 2, addr: remoteAddress }

        // Matches 192.168.*.*
        if (a[1] === b[1]) {
          if (best.segment === 2) best = { segment: 3, addr: remoteAddress }

          // Matches 192.168.122.*
          if (a[2] === b[2]) return remoteAddress
        }
      }
    }
  }

  return best.addr
}

function noop() {}
const c = require('compact-encoding')

const ipv4 = {
  ...c.ipv4Address,
  decode(state) {
    const ip = c.ipv4Address.decode(state)
    return {
      host: ip.host,
      port: ip.port
    }
  }
}

const ipv4Array = c.array(ipv4)

const ipv6 = {
  ...c.ipv6Address,
  decode(state) {
    const ip = c.ipv6Address.decode(state)
    return {
      host: ip.host,
      port: ip.port
    }
  }
}

const ipv6Array = c.array(ipv6)

exports.handshake = {
  preencode(state, m) {
    state.end += 1 + 1 + (m.peerAddress ? 6 : 0) + (m.relayAddress ? 6 : 0)
    c.buffer.preencode(state, m.noise)
  },
  encode(state, m) {
    const flags = (m.peerAddress ? 1 : 0) | (m.relayAddress ? 2 : 0)

    c.uint.encode(state, flags)
    c.uint.encode(state, m.mode)
    c.buffer.encode(state, m.noise)

    if (m.peerAddress) ipv4.encode(state, m.peerAddress)
    if (m.relayAddress) ipv4.encode(state, m.relayAddress)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      mode: c.uint.decode(state),
      noise: c.buffer.decode(state),
      peerAddress: flags & 1 ? ipv4.decode(state) : null,
      relayAddress: flags & 2 ? ipv4.decode(state) : null
    }
  }
}

const relayInfo = {
  preencode(state, m) {
    state.end += 12
  },
  encode(state, m) {
    ipv4.encode(state, m.relayAddress)
    ipv4.encode(state, m.peerAddress)
  },
  decode(state) {
    return {
      relayAddress: ipv4.decode(state),
      peerAddress: ipv4.decode(state)
    }
  }
}

const relayInfoArray = c.array(relayInfo)

const holepunchInfo = {
  preencode(state, m) {
    c.uint.preencode(state, m.id)
    relayInfoArray.preencode(state, m.relays)
  },
  encode(state, m) {
    c.uint.encode(state, m.id)
    relayInfoArray.encode(state, m.relays)
  },
  decode(state) {
    return {
      id: c.uint.decode(state),
      relays: relayInfoArray.decode(state)
    }
  }
}

const udxInfo = {
  preencode(state, m) {
    state.end += 2 // version + features
    c.uint.preencode(state, m.id)
    c.uint.preencode(state, m.seq)
  },
  encode(state, m) {
    c.uint.encode(state, 1)
    c.uint.encode(state, m.reusableSocket ? 1 : 0)
    c.uint.encode(state, m.id)
    c.uint.encode(state, m.seq)
  },
  decode(state) {
    const version = c.uint.decode(state)
    const features = c.uint.decode(state)

    return {
      version,
      reusableSocket: (features & 1) !== 0,
      id: c.uint.decode(state),
      seq: c.uint.decode(state)
    }
  }
}

const secretStreamInfo = {
  preencode(state, m) {
    c.uint.preencode(state, 1)
  },
  encode(state, m) {
    c.uint.encode(state, 1)
  },
  decode(state) {
    return {
      version: c.uint.decode(state)
    }
  }
}

const relayThroughInfo = {
  preencode(state, m) {
    c.uint.preencode(state, 1) // version
    c.uint.preencode(state, 0) // flags
    c.fixed32.preencode(state, m.publicKey)
    c.fixed32.preencode(state, m.token)
  },
  encode(state, m) {
    c.uint.encode(state, 1)
    c.uint.encode(state, 0)
    c.fixed32.encode(state, m.publicKey)
    c.fixed32.encode(state, m.token)
  },
  decode(state) {
    const version = c.uint.decode(state)
    c.uint.decode(state)

    return {
      version,
      publicKey: c.fixed32.decode(state),
      token: c.fixed32.decode(state)
    }
  }
}

exports.noisePayload = {
  preencode(state, m) {
    state.end += 4 // version + flags + error + firewall
    if (m.holepunch) holepunchInfo.preencode(state, m.holepunch)
    if (m.addresses4 && m.addresses4.length) ipv4Array.preencode(state, m.addresses4)
    if (m.addresses6 && m.addresses6.length) ipv6Array.preencode(state, m.addresses6)
    if (m.udx) udxInfo.preencode(state, m.udx)
    if (m.secretStream) secretStreamInfo.preencode(state, m.secretStream)
    if (m.relayThrough) relayThroughInfo.preencode(state, m.relayThrough)
    if (m.relayAddresses) ipv4Array.preencode(state, m.relayAddresses)
  },
  encode(state, m) {
    let flags = 0

    if (m.holepunch) flags |= 1
    if (m.addresses4 && m.addresses4.length) flags |= 2
    if (m.addresses6 && m.addresses6.length) flags |= 4
    if (m.udx) flags |= 8
    if (m.secretStream) flags |= 16
    if (m.relayThrough) flags |= 32
    if (m.relayAddresses) flags |= 64

    c.uint.encode(state, 1) // version
    c.uint.encode(state, flags)
    c.uint.encode(state, m.error)
    c.uint.encode(state, m.firewall)

    if (m.holepunch) holepunchInfo.encode(state, m.holepunch)
    if (m.addresses4 && m.addresses4.length) ipv4Array.encode(state, m.addresses4)
    if (m.addresses6 && m.addresses6.length) ipv6Array.encode(state, m.addresses6)
    if (m.udx) udxInfo.encode(state, m.udx)
    if (m.secretStream) secretStreamInfo.encode(state, m.secretStream)
    if (m.relayThrough) relayThroughInfo.encode(state, m.relayThrough)
    if (m.relayAddresses) ipv4Array.encode(state, m.relayAddresses)
  },
  decode(state) {
    const version = c.uint.decode(state)

    if (version !== 1) {
      // Do not attempt to decode but return this back to the user so they can
      // actually handle it
      return {
        version,
        error: 0,
        firewall: 0,
        holepunch: null,
        addresses4: [],
        addresses6: [],
        udx: null,
        secretStream: null,
        relayThrough: null,
        relayAddresses: null
      }
    }

    const flags = c.uint.decode(state)

    return {
      version,
      error: c.uint.decode(state),
      firewall: c.uint.decode(state),
      holepunch: (flags & 1) !== 0 ? holepunchInfo.decode(state) : null,
      addresses4: (flags & 2) !== 0 ? ipv4Array.decode(state) : [],
      addresses6: (flags & 4) !== 0 ? ipv6Array.decode(state) : [],
      udx: (flags & 8) !== 0 ? udxInfo.decode(state) : null,
      secretStream: (flags & 16) !== 0 ? secretStreamInfo.decode(state) : null,
      relayThrough: (flags & 32) !== 0 ? relayThroughInfo.decode(state) : null,
      relayAddresses: (flags & 64) !== 0 ? ipv4Array.decode(state) : null
    }
  }
}

exports.holepunch = {
  preencode(state, m) {
    state.end += 2
    c.uint.preencode(state, m.id)
    c.buffer.preencode(state, m.payload)
    if (m.peerAddress) ipv4.preencode(state, m.peerAddress)
  },
  encode(state, m) {
    const flags = m.peerAddress ? 1 : 0
    c.uint.encode(state, flags)
    c.uint.encode(state, m.mode)
    c.uint.encode(state, m.id)
    c.buffer.encode(state, m.payload)
    if (m.peerAddress) ipv4.encode(state, m.peerAddress)
  },
  decode(state) {
    const flags = c.uint.decode(state)
    return {
      mode: c.uint.decode(state),
      id: c.uint.decode(state),
      payload: c.buffer.decode(state),
      peerAddress: flags & 1 ? ipv4.decode(state) : null
    }
  }
}

exports.holepunchPayload = {
  preencode(state, m) {
    state.end += 4 // flags + error + firewall + round
    if (m.addresses) ipv4Array.preencode(state, m.addresses)
    if (m.remoteAddress) state.end += 6
    if (m.token) state.end += 32
    if (m.remoteToken) state.end += 32
  },
  encode(state, m) {
    const flags =
      (m.connected ? 1 : 0) |
      (m.punching ? 2 : 0) |
      (m.addresses ? 4 : 0) |
      (m.remoteAddress ? 8 : 0) |
      (m.token ? 16 : 0) |
      (m.remoteToken ? 32 : 0)

    c.uint.encode(state, flags)
    c.uint.encode(state, m.error)
    c.uint.encode(state, m.firewall)
    c.uint.encode(state, m.round)

    if (m.addresses) ipv4Array.encode(state, m.addresses)
    if (m.remoteAddress) ipv4.encode(state, m.remoteAddress)
    if (m.token) c.fixed32.encode(state, m.token)
    if (m.remoteToken) c.fixed32.encode(state, m.remoteToken)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      error: c.uint.decode(state),
      firewall: c.uint.decode(state),
      round: c.uint.decode(state),
      connected: (flags & 1) !== 0,
      punching: (flags & 2) !== 0,
      addresses: (flags & 4) !== 0 ? ipv4Array.decode(state) : null,
      remoteAddress: (flags & 8) !== 0 ? ipv4.decode(state) : null,
      token: (flags & 16) !== 0 ? c.fixed32.decode(state) : null,
      remoteToken: (flags & 32) !== 0 ? c.fixed32.decode(state) : null
    }
  }
}

const peer = (exports.peer = {
  preencode(state, m) {
    state.end += 32
    ipv4Array.preencode(state, m.relayAddresses)
  },
  encode(state, m) {
    c.fixed32.encode(state, m.publicKey)
    ipv4Array.encode(state, m.relayAddresses)
  },
  decode(state) {
    return {
      publicKey: c.fixed32.decode(state),
      relayAddresses: ipv4Array.decode(state)
    }
  }
})

const peers = (exports.peers = c.array(peer))

const rawPeers = c.array(c.raw)

exports.lookupRawReply = {
  preencode(state, m) {
    rawPeers.preencode(state, m.peers)
    c.uint.preencode(state, m.bump)
  },
  encode(state, m) {
    rawPeers.encode(state, m.peers)
    c.uint.encode(state, m.bump)
  },
  decode(state) {
    return {
      peers: peers.decode(state),
      bump: state.start < state.end ? c.uint.decode(state) : 0
    }
  }
}

exports.announce = {
  preencode(state, m) {
    state.end++ // flags
    if (m.peer) peer.preencode(state, m.peer)
    if (m.refresh) state.end += 32
    if (m.signature) state.end += 64
    if (m.bump) c.uint.preencode(state, m.bump)
  },
  encode(state, m) {
    const flags = (m.peer ? 1 : 0) | (m.refresh ? 2 : 0) | (m.signature ? 4 : 0) | (m.bump ? 8 : 0)
    c.uint.encode(state, flags)
    if (m.peer) peer.encode(state, m.peer)
    if (m.refresh) c.fixed32.encode(state, m.refresh)
    if (m.signature) c.fixed64.encode(state, m.signature)
    if (m.bump) c.uint.encode(state, m.bump)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      peer: (flags & 1) !== 0 ? peer.decode(state) : null,
      refresh: (flags & 2) !== 0 ? c.fixed32.decode(state) : null,
      signature: (flags & 4) !== 0 ? c.fixed64.decode(state) : null,
      bump: (flags & 8) !== 0 ? c.uint.decode(state) : 0
    }
  }
}

exports.mutableSignable = {
  preencode(state, m) {
    c.uint.preencode(state, m.seq)
    c.buffer.preencode(state, m.value)
  },
  encode(state, m) {
    c.uint.encode(state, m.seq)
    c.buffer.encode(state, m.value)
  },
  decode(state) {
    return {
      seq: c.uint.decode(state),
      value: c.buffer.decode(state)
    }
  }
}

exports.mutablePutRequest = {
  preencode(state, m) {
    c.fixed32.preencode(state, m.publicKey)
    c.uint.preencode(state, m.seq)
    c.buffer.preencode(state, m.value)
    c.fixed64.preencode(state, m.signature)
  },
  encode(state, m) {
    c.fixed32.encode(state, m.publicKey)
    c.uint.encode(state, m.seq)
    c.buffer.encode(state, m.value)
    c.fixed64.encode(state, m.signature)
  },
  decode(state) {
    return {
      publicKey: c.fixed32.decode(state),
      seq: c.uint.decode(state),
      value: c.buffer.decode(state),
      signature: c.fixed64.decode(state)
    }
  }
}

exports.mutableGetResponse = {
  preencode(state, m) {
    c.uint.preencode(state, m.seq)
    c.buffer.preencode(state, m.value)
    c.fixed64.preencode(state, m.signature)
  },
  encode(state, m) {
    c.uint.encode(state, m.seq)
    c.buffer.encode(state, m.value)
    c.fixed64.encode(state, m.signature)
  },
  decode(state) {
    return {
      seq: c.uint.decode(state),
      value: c.buffer.decode(state),
      signature: c.fixed64.decode(state)
    }
  }
}

exports.pluginRequest = {
  preencode(state, m) {
    c.string.preencode(state, m.plugin)
    c.uint.preencode(state, m.version)
    c.uint.preencode(state, m.command)
    state.end++ // max flag is 1 so always one byte

    if (m.value) c.buffer.preencode(state, m.value)
  },
  encode(state, m) {
    const flags = m.value ? 1 : 0

    c.string.encode(state, m.plugin)
    c.uint.encode(state, m.version)
    c.uint.encode(state, m.command)
    c.uint.encode(state, flags)

    if (m.value) c.buffer.encode(state, m.value)
  },
  decode(state) {
    const r0 = c.string.decode(state)
    const r1 = c.uint.decode(state)
    const r2 = c.uint.decode(state)
    const flags = c.uint.decode(state)

    return {
      plugin: r0,
      version: r1,
      command: r2,
      value: (flags & 1) !== 0 ? c.buffer.decode(state) : null
    }
  }
}
const { FIREWALL } = require('../lib/constants')

module.exports = class Nat {
  constructor(dht, session, socket) {
    this._samplesHost = []
    this._samplesFull = []
    this._visited = new Map()
    this._resolve = null
    this._minSamples = 4
    this._autoSampling = false

    this.dht = dht
    this.session = session
    this.socket = socket

    this.sampled = 0
    this.firewall = dht.firewalled ? FIREWALL.UNKNOWN : FIREWALL.OPEN
    this.addresses = null

    this.analyzing = new Promise((resolve) => {
      this._resolve = resolve
    })
  }

  autoSample(retry = true) {
    if (this._autoSampling) return
    this._autoSampling = true

    const self = this
    const socket = this.socket
    const maxPings = this._minSamples

    let skip = this.dht.nodes.length >= 8 ? 5 : 0
    let pending = 0

    // TODO: it would be best to pick the nodes to help us based on latency to us
    // That should reduce connect latency in general. We should investigate tracking that later on.

    // TODO 2: try to pick nodes with different IPs as well, as that'll help multi IP cell connections...
    // If we expose this from the nat sampler then the DHT should be able to help us filter out scams as well...

    for (
      let node = this.dht.nodes.latest;
      node && this.sampled + pending < maxPings;
      node = node.prev
    ) {
      if (skip > 0) {
        skip--
        continue
      }

      const ref = node.host + ':' + node.port

      if (this._visited.has(ref)) continue
      this._visited.set(ref, 1)

      pending++
      this.session.ping(node, { socket, retry: false }).then(onpong, onskip)
    }

    pending++
    onskip()

    function onpong(res) {
      self.add(res.to, res.from)
      onskip()
    }

    function onskip() {
      if (--pending === 0 && self.sampled < self._minSamples) {
        if (retry) {
          self._autoSampling = false
          self.autoSample(false)
          return
        }
        self._resolve()
      }
    }
  }

  destroy() {
    this._autoSampling = true
    this._minSamples = 0
    this._resolve()
  }

  unfreeze() {
    this.frozen = false
    this._updateFirewall()
    this._updateAddresses()
  }

  freeze() {
    this.frozen = true
  }

  _updateFirewall() {
    if (!this.dht.firewalled) {
      this.firewall = FIREWALL.OPEN
      return
    }

    if (this.sampled < 3) return

    const max = this._samplesFull[0].hits

    if (max >= 3) {
      this.firewall = FIREWALL.CONSISTENT
      return
    }

    if (max === 1) {
      this.firewall = FIREWALL.RANDOM
      return
    }

    // else max === 2

    // 1 host, >= 4 total samples ie, 2 bad ones -> random
    if (this._samplesHost.length === 1 && this.sampled > 3) {
      this.firewall = FIREWALL.RANDOM
      return
    }

    // double hit on two different ips -> assume consistent
    if (this._samplesHost.length > 1 && this._samplesFull[1].hits > 1) {
      this.firewall = FIREWALL.CONSISTENT
      return
    }

    // (4 is just means - all the samples we expect) - no decision - assume random
    if (this.sampled > 4) {
      this.firewall = FIREWALL.RANDOM
    }
  }

  _updateAddresses() {
    if (this.firewall === FIREWALL.UNKNOWN) {
      this.addresses = null
      return
    }

    if (this.firewall === FIREWALL.RANDOM) {
      this.addresses = [this._samplesHost[0]]
      return
    }

    if (this.firewall === FIREWALL.CONSISTENT) {
      this.addresses = []
      for (const addr of this._samplesFull) {
        if (addr.hits >= 2 || this.addresses.length < 2) this.addresses.push(addr)
      }
    }
  }

  update() {
    if (this.dht.firewalled && this.firewall === FIREWALL.OPEN) {
      this.firewall = FIREWALL.UNKNOWN
    }
    this._updateFirewall()
    this._updateAddresses()
  }

  add(addr, from) {
    const ref = from.host + ':' + from.port

    if (this._visited.get(ref) === 2) return
    this._visited.set(ref, 2)

    addSample(this._samplesHost, addr.host, 0)
    addSample(this._samplesFull, addr.host, addr.port)

    if ((++this.sampled >= 3 || !this.dht.firewalled) && !this.frozen) {
      this.update()
    }

    if (this.firewall === FIREWALL.CONSISTENT || this.firewall === FIREWALL.OPEN) {
      this._resolve()
    } else if (this.sampled >= this._minSamples) {
      this._resolve()
    }
  }
}

function addSample(samples, host, port) {
  for (let i = 0; i < samples.length; i++) {
    const s = samples[i]

    if (s.port !== port || s.host !== host) continue
    s.hits++

    for (; i > 0; i--) {
      const prev = samples[i - 1]
      if (prev.hits >= s.hits) return
      samples[i - 1] = s
      samples[i] = prev
    }

    return
  }

  samples.push({
    host,
    port,
    hits: 1
  })
}
const NoiseSecretStream = require('@hyperswarm/secret-stream')
const NoiseHandshake = require('noise-handshake')
const curve = require('noise-curve-ed')
const c = require('compact-encoding')
const b4a = require('b4a')
const sodium = require('sodium-universal')
const m = require('./messages')
const { NS } = require('./constants')
const { HANDSHAKE_UNFINISHED } = require('./errors')

const NOISE_PROLOUGE = NS.PEER_HANDSHAKE

module.exports = class NoiseWrap {
  constructor(keyPair, remotePublicKey) {
    this.isInitiator = !!remotePublicKey
    this.remotePublicKey = remotePublicKey
    this.keyPair = keyPair
    this.handshake = new NoiseHandshake('IK', this.isInitiator, keyPair, { curve })
    this.handshake.initialise(NOISE_PROLOUGE, remotePublicKey)
  }

  send(payload) {
    const buf = c.encode(m.noisePayload, payload)
    return this.handshake.send(buf)
  }

  recv(buf) {
    const payload = c.decode(m.noisePayload, this.handshake.recv(buf))
    this.remotePublicKey = b4a.toBuffer(this.handshake.rs)
    return payload
  }

  final() {
    if (!this.handshake.complete) throw HANDSHAKE_UNFINISHED()

    const holepunchSecret = b4a.allocUnsafe(32)

    sodium.crypto_generichash(holepunchSecret, NS.PEER_HOLEPUNCH, this.handshake.hash)

    return {
      isInitiator: this.isInitiator,
      publicKey: this.keyPair.publicKey,
      streamId: this.streamId,
      remotePublicKey: this.remotePublicKey,
      remoteId: NoiseSecretStream.id(this.handshake.hash, !this.isInitiator),
      holepunchSecret,
      hash: b4a.toBuffer(this.handshake.hash),
      rx: b4a.toBuffer(this.handshake.rx),
      tx: b4a.toBuffer(this.handshake.tx)
    }
  }
}
const c = require('compact-encoding')
const sodium = require('sodium-universal')
const RecordCache = require('record-cache')
const Cache = require('xache')
const b4a = require('b4a')
const unslab = require('unslab')

const { encodeUnslab } = require('./encode')
const m = require('./messages')
const { NS, ERROR } = require('./constants')

const EMPTY = b4a.alloc(0)
const TMP = b4a.allocUnsafe(32)
const MAX_BUMP_DRIFT = 60_000

module.exports = class Persistent {
  constructor(dht, opts) {
    this.dht = dht
    this.records = new RecordCache(opts.records)
    this.bumps = new Cache(opts.bumps)
    this.refreshes = new Cache(opts.refreshes)
    this.mutables = new Cache(opts.mutables)
    this.immutables = new Cache(opts.immutables)
  }

  onlookup(req) {
    if (!req.target) return

    const k = b4a.toString(req.target, 'hex')
    const records = this.records.get(k, 20)
    const bump = this.bumps.get(k) || 0
    const fwd = this.dht._router.get(k)

    if (fwd && records.length < 20) records.push(fwd.record)

    req.reply(records.length ? c.encode(m.lookupRawReply, { peers: records, bump }) : null)
  }

  onfindpeer(req) {
    if (!req.target) return
    const fwd = this.dht._router.get(req.target)
    req.reply(fwd ? fwd.record : null)
  }

  unannounce(target, publicKey) {
    const k = b4a.toString(target, 'hex')
    sodium.crypto_generichash(TMP, publicKey)

    if (b4a.equals(TMP, target)) this.dht._router.delete(k)
    this.records.remove(k, publicKey)
  }

  onunannounce(req) {
    if (!req.target || !req.token) return

    const unann = decode(m.announce, req.value)
    if (unann === null) return

    const { peer, signature } = unann
    if (!peer || !signature) return

    const signable = annSignable(req.target, req.token, this.dht.id, unann, NS.UNANNOUNCE)

    if (!sodium.crypto_sign_verify_detached(signature, signable, peer.publicKey)) {
      return
    }

    this.unannounce(req.target, peer.publicKey)
    req.reply(null, { token: false, closerNodes: false })
  }

  _onrefresh(token, req) {
    sodium.crypto_generichash(TMP, token)
    const activeRefresh = b4a.toString(TMP, 'hex')

    const r = this.refreshes.get(activeRefresh)
    if (!r) return

    const { announceSelf, k, record } = r
    const publicKey = record.subarray(0, 32)

    if (announceSelf) {
      this.dht._router.set(k, {
        relay: req.from,
        record,
        onconnect: null,
        onholepunch: null
      })
      this.records.remove(k, publicKey)
    } else {
      this.records.add(k, publicKey, record)
    }

    this.refreshes.delete(activeRefresh)
    this.refreshes.set(b4a.toString(token, 'hex'), r)

    req.reply(null, { token: false, closerNodes: false })
  }

  onannounce(req) {
    if (!req.target || !req.token || !this.dht.id) return

    const ann = decode(m.announce, req.value)
    if (ann === null) return

    const { peer, refresh, signature, bump } = ann

    if (!peer) {
      if (!refresh) return
      this._onrefresh(refresh, req)
      return
    }

    const signable = annSignable(req.target, req.token, this.dht.id, ann, NS.ANNOUNCE)

    if (!signature || !sodium.crypto_sign_verify_detached(signature, signable, peer.publicKey)) {
      return
    }

    // TODO: it would be potentially be more optimal to allow more than 3 addresses here for a findPeer response
    // and only use max 3 for a lookup reply
    if (peer.relayAddresses.length > 3) {
      peer.relayAddresses = peer.relayAddresses.slice(0, 3)
    }

    sodium.crypto_generichash(TMP, peer.publicKey)

    const k = b4a.toString(req.target, 'hex')
    const announceSelf = b4a.equals(TMP, req.target)
    const record = encodeUnslab(m.peer, peer)

    if (announceSelf) {
      this.dht._router.set(k, {
        relay: req.from,
        record,
        onconnect: null,
        onholepunch: null
      })
      this.records.remove(k, peer.publicKey)
    } else {
      const currentBump = this.bumps.get(k) || 0
      if (bump > currentBump && bump <= Date.now() + MAX_BUMP_DRIFT) this.bumps.set(k, bump)
      this.records.add(k, peer.publicKey, record)
    }

    if (refresh) {
      this.refreshes.set(b4a.toString(refresh, 'hex'), { k, record, announceSelf })
    }

    req.reply(null, { token: false, closerNodes: false })
  }

  onmutableget(req) {
    if (!req.target || !req.value) return

    let seq = 0
    try {
      seq = c.decode(c.uint, req.value)
    } catch {
      return
    }

    const k = b4a.toString(req.target, 'hex')
    const value = this.mutables.get(k)

    if (!value) {
      req.reply(null)
      return
    }

    const localSeq = c.decode(c.uint, value)
    req.reply(localSeq < seq ? null : value)
  }

  onmutableput(req) {
    if (!req.target || !req.token || !req.value) return

    const p = decode(m.mutablePutRequest, req.value)
    if (!p) return

    const { publicKey, seq, value, signature } = p

    const hash = b4a.allocUnsafe(32)
    sodium.crypto_generichash(hash, publicKey)
    if (!b4a.equals(hash, req.target)) return

    if (!value || !verifyMutable(signature, seq, value, publicKey)) return

    const k = b4a.toString(hash, 'hex')
    const local = this.mutables.get(k)

    if (local) {
      const existing = c.decode(m.mutableGetResponse, local)
      if (existing.value && existing.seq === seq && b4a.compare(value, existing.value) !== 0) {
        req.error(ERROR.SEQ_REUSED)
        return
      }
      if (seq < existing.seq) {
        req.error(ERROR.SEQ_TOO_LOW)
        return
      }
    }

    this.mutables.set(k, encodeUnslab(m.mutableGetResponse, { seq, value, signature }))
    req.reply(null)
  }

  onimmutableget(req) {
    if (!req.target) return

    const k = b4a.toString(req.target, 'hex')
    const value = this.immutables.get(k)

    req.reply(value || null)
  }

  onimmutableput(req) {
    if (!req.target || !req.token || !req.value) return

    const hash = b4a.alloc(32)
    sodium.crypto_generichash(hash, req.value)
    if (!b4a.equals(hash, req.target)) return

    const k = b4a.toString(hash, 'hex')
    this.immutables.set(k, unslab(req.value))

    req.reply(null)
  }

  onplugin(req) {
    if (!req.value) return

    const plugreq = decode(m.pluginRequest, req.value)
    if (plugreq === null) return

    const p = this.dht.plugins.get(plugreq.plugin)
    if (!p || p.version !== plugreq.version) return

    p.onrequest(plugreq, req)
  }

  destroy() {
    this.records.destroy()
    this.refreshes.destroy()
    this.mutables.destroy()
    this.immutables.destroy()
  }

  static signMutable(seq, value, keyPair) {
    const signable = b4a.allocUnsafe(32 + 32)
    const hash = signable.subarray(32)

    signable.set(NS.MUTABLE_PUT, 0)

    sodium.crypto_generichash(hash, c.encode(m.mutableSignable, { seq, value }))
    return sign(signable, keyPair)
  }

  static verifyMutable(signature, seq, value, publicKey) {
    return verifyMutable(signature, seq, value, publicKey)
  }

  static signAnnounce(target, token, id, ann, keyPair) {
    return sign(annSignable(target, token, id, ann, NS.ANNOUNCE), keyPair)
  }

  static signUnannounce(target, token, id, ann, keyPair) {
    return sign(annSignable(target, token, id, ann, NS.UNANNOUNCE), keyPair)
  }
}

function verifyMutable(signature, seq, value, publicKey) {
  const signable = b4a.allocUnsafe(32 + 32)
  const hash = signable.subarray(32)

  signable.set(NS.MUTABLE_PUT, 0)

  sodium.crypto_generichash(hash, c.encode(m.mutableSignable, { seq, value }))
  return sodium.crypto_sign_verify_detached(signature, signable, publicKey)
}

function annSignable(target, token, id, ann, ns) {
  const signable = b4a.allocUnsafe(32 + 32)
  const hash = signable.subarray(32)

  signable.set(ns, 0)

  sodium.crypto_generichash_batch(hash, [
    target,
    id,
    token,
    c.encode(m.peer, ann.peer), // note that this is the partial encoding of the announce message so we could just use that for perf
    ann.refresh || EMPTY
  ])

  return signable
}

function sign(signable, keyPair) {
  if (keyPair.sign) {
    return keyPair.sign(signable)
  }
  const secretKey = keyPair.secretKey ? keyPair.secretKey : keyPair
  const signature = b4a.allocUnsafe(64)
  sodium.crypto_sign_detached(signature, signable, secretKey)
  return signature
}

function decode(enc, val) {
  try {
    return val && c.decode(enc, val)
  } catch (err) {
    return null
  }
}
module.exports = class RawStreamSet {
  constructor(dht) {
    this._dht = dht

    this._prefix = 16 - 1 // 16 is the default stream-set side in udx
    this._streams = new Map()
  }

  get size() {
    return this._streams.size
  }

  [Symbol.iterator]() {
    return this._streams.values()
  }

  add(opts) {
    const self = this

    // TODO: we should prob have a udx helper for id generation, given the slight complexity
    // of the below. requires a PRNG in udx tho.

    let id = 0

    while (true) {
      id = (Math.random() * 0x100000000) >>> 0

      if (this._streams.has(id & this._prefix)) continue
      break
    }

    // always have ~50% change of rolling a free one
    if (2 * this._streams.size >= this._prefix) {
      // ie 0b11111 = 0b1111 + 1 + 0b1111
      this._prefix = 2 * this._prefix + 1

      // move the prefixes over
      const next = new Map()
      for (const stream of this._streams.values()) {
        next.set(stream.id & this._prefix, stream)
      }
      this._streams = next
    }

    const stream = this._dht.udx.createStream(id, opts)
    this._streams.set(id & this._prefix, stream)

    stream.on('close', onclose)

    return stream

    function onclose() {
      self._streams.delete(id & self._prefix)
    }
  }

  async clear() {
    const destroying = []

    for (const stream of this._streams.values()) {
      destroying.push(new Promise((resolve) => stream.once('close', resolve).destroy()))
    }

    await Promise.allSettled(destroying)
  }
}
const c = require('compact-encoding')
const Cache = require('xache')
const safetyCatch = require('safety-catch')
const b4a = require('b4a')
const { handshake, holepunch } = require('./messages')
const { COMMANDS } = require('./constants')
const { BAD_HANDSHAKE_REPLY, BAD_HOLEPUNCH_REPLY } = require('./errors')

const FROM_CLIENT = 0
const FROM_SERVER = 1
const FROM_RELAY = 2
const FROM_SECOND_RELAY = 3
const REPLY = 4

// TODO: While the current design is very trustless in regards to clients/servers trusting the DHT,
// we should add a bunch of rate limits everywhere, especially including here to avoid bad users
// using a DHT node to relay traffic indiscriminately using the connect/holepunch messages.
// That's mostly from an abuse POV as none of the messsages do amplication.

module.exports = class Router {
  constructor(dht, opts) {
    this.dht = dht
    this.forwards = new Cache(opts.forwards)
  }

  set(target, state) {
    if (state.onpeerhandshake) {
      this.forwards.retain(toString(target), state)
    } else {
      this.forwards.set(toString(target), state)
    }
  }

  get(target) {
    return this.forwards.get(toString(target))
  }

  delete(target) {
    this.forwards.delete(toString(target))
  }

  destroy() {
    this.forwards.destroy()
  }

  async peerHandshake(target, { noise, peerAddress, relayAddress, socket, session }, to) {
    const dht = this.dht

    const requestValue = c.encode(handshake, {
      mode: FROM_CLIENT,
      noise,
      peerAddress,
      relayAddress
    })

    const res = await dht.request(
      { command: COMMANDS.PEER_HANDSHAKE, target, value: requestValue },
      to,
      { socket, session }
    )

    const hs = decode(handshake, res.value)
    if (
      !hs ||
      hs.mode !== REPLY ||
      to.host !== res.from.host ||
      to.port !== res.from.port ||
      !hs.noise
    ) {
      throw BAD_HANDSHAKE_REPLY()
    }

    return {
      noise: hs.noise,
      relayed: !!hs.peerAddress,
      serverAddress: hs.peerAddress || to,
      clientAddress: res.to
    }
  }

  async onpeerhandshake(req) {
    const hs = req.value && decode(handshake, req.value)
    if (!hs) return

    const { mode, noise, peerAddress, relayAddress } = hs

    const state = req.target && this.get(req.target)
    const isServer = !!(state && state.onpeerhandshake)
    const relay = state && state.relay

    if (isServer) {
      let reply = null
      try {
        reply = noise && (await state.onpeerhandshake({ noise, peerAddress }, req))
      } catch (e) {
        safetyCatch(e)
        return
      }
      if (!reply || !reply.noise) return
      const opts = { socket: reply.socket, closerNodes: false, token: false }

      switch (mode) {
        case FROM_CLIENT: {
          req.reply(
            c.encode(handshake, { mode: REPLY, noise: reply.noise, peerAddress: null }),
            opts
          )
          return
        }
        case FROM_RELAY: {
          req.relay(
            c.encode(handshake, { mode: FROM_SERVER, noise: reply.noise, peerAddress }),
            req.from,
            opts
          )
          return
        }
        case FROM_SECOND_RELAY: {
          if (!relayAddress) return
          req.relay(
            c.encode(handshake, { mode: FROM_SERVER, noise: reply.noise, peerAddress }),
            relayAddress,
            opts
          )
          return // eslint-disable-line
        }
      }
    } else {
      switch (mode) {
        case FROM_CLIENT: {
          // TODO: if no relay is known route closer to the target instead of timing out
          if (!noise) return
          if (!relay && !relayAddress) {
            // help the user route
            req.reply(null, { token: false, closerNodes: true })
            return
          }
          req.relay(
            c.encode(handshake, {
              mode: FROM_RELAY,
              noise,
              peerAddress: req.from,
              relayAddress: null
            }),
            relayAddress || relay
          )
          return
        }
        case FROM_RELAY: {
          if (!relay || !noise) return
          req.relay(
            c.encode(handshake, {
              mode: FROM_SECOND_RELAY,
              noise,
              peerAddress,
              relayAddress: req.from
            }),
            relay
          )
          return
        }
        case FROM_SERVER: {
          if (!peerAddress || !noise) return
          req.reply(
            c.encode(handshake, { mode: REPLY, noise, peerAddress: req.from, relayAddress: null }),
            { to: peerAddress, closerNodes: false, token: false }
          )
          return // eslint-disable-line
        }
      }
    }
  }

  async peerHolepunch(target, { id, payload, peerAddress, socket, session }, to) {
    const dht = this.dht
    const requestValue = c.encode(holepunch, {
      mode: FROM_CLIENT,
      id,
      payload,
      peerAddress
    })

    const res = await dht.request(
      { command: COMMANDS.PEER_HOLEPUNCH, target, value: requestValue },
      to,
      { socket, session }
    )

    const hp = decode(holepunch, res.value)
    if (!hp || hp.mode !== REPLY || to.host !== res.from.host || to.port !== res.from.port) {
      throw BAD_HOLEPUNCH_REPLY()
    }

    return {
      from: res.from,
      to: res.to,
      payload: hp.payload,
      peerAddress: hp.peerAddress || to
    }
  }

  async onpeerholepunch(req) {
    const hp = req.value && decode(holepunch, req.value)
    if (!hp) return

    const { mode, id, payload, peerAddress } = hp

    const state = req.target && this.get(req.target)
    const isServer = !!(state && state.onpeerholepunch)
    const relay = state && state.relay

    switch (mode) {
      case FROM_CLIENT: {
        if (!peerAddress && !relay) return
        req.relay(
          c.encode(holepunch, { mode: FROM_RELAY, id, payload, peerAddress: req.from }),
          peerAddress || relay
        )
        return
      }
      case FROM_RELAY: {
        if (!isServer || !peerAddress) return
        let reply = null
        try {
          reply = await state.onpeerholepunch({ id, payload, peerAddress }, req)
        } catch (e) {
          safetyCatch(e)
          return
        }
        if (!reply) return
        const opts = { socket: reply.socket, closerNodes: false, token: false }
        req.relay(
          c.encode(holepunch, { mode: FROM_SERVER, id: 0, payload: reply.payload, peerAddress }),
          req.from,
          opts
        )
        return
      }
      case FROM_SERVER: {
        req.reply(c.encode(holepunch, { mode: REPLY, id, payload, peerAddress: req.from }), {
          to: peerAddress,
          closerNodes: false,
          token: false
        })
        return // eslint-disable-line
      }
    }
  }
}

function decode(enc, val) {
  try {
    return c.decode(enc, val)
  } catch {
    return null
  }
}

function toString(t) {
  return typeof t === 'string' ? t : b4a.toString(t, 'hex')
}
const sodium = require('sodium-universal')
const b4a = require('b4a')
const { holepunchPayload } = require('./messages')

module.exports = class HolepunchPayload {
  constructor(holepunchSecret) {
    this._sharedSecret = holepunchSecret
    this._localSecret = b4a.allocUnsafe(32)

    sodium.randombytes_buf(this._localSecret)
  }

  decrypt(buffer) {
    const state = { start: 24, end: buffer.byteLength - 16, buffer }

    if (state.end <= state.start) return null

    const nonce = buffer.subarray(0, 24)
    const msg = state.buffer.subarray(state.start, state.end)
    const cipher = state.buffer.subarray(state.start)

    if (!sodium.crypto_secretbox_open_easy(msg, cipher, nonce, this._sharedSecret)) return null

    try {
      return holepunchPayload.decode(state)
    } catch {
      return null
    }
  }

  encrypt(payload) {
    const state = { start: 24, end: 24, buffer: null }
    holepunchPayload.preencode(state, payload)
    state.buffer = b4a.allocUnsafe(state.end + 16)

    const nonce = state.buffer.subarray(0, 24)
    const msg = state.buffer.subarray(state.start, state.end)
    const cipher = state.buffer.subarray(state.start)

    holepunchPayload.encode(state, payload)
    sodium.randombytes_buf(nonce)
    sodium.crypto_secretbox_easy(cipher, msg, nonce, this._sharedSecret)

    return state.buffer
  }

  token(addr) {
    const out = b4a.allocUnsafe(32)
    sodium.crypto_generichash(out, b4a.from(addr.host), this._localSecret)
    return out
  }
}
const DONE = Promise.resolve(true)
const DESTROYED = Promise.resolve(false)

module.exports = class Semaphore {
  constructor(limit = 1) {
    this.limit = limit
    this.active = 0
    this.waiting = []

    this.flushedPromise = null
    this.flushedResolve = null

    this.destroyed = false

    this._onwait = this._queueWaiting.bind(this)
    this._onflush = this._queueFlushed.bind(this)
  }

  _queueWaiting(resolve) {
    this.waiting.push(resolve)
  }

  _queueFlushed(resolve) {
    this.flushedResolve = resolve
  }

  wait() {
    if (this.destroyed === true) return DESTROYED

    if (this.active < this.limit && this.waiting.length === 0) {
      this.active++
      return DONE
    }

    return new Promise(this._onwait)
  }

  signal() {
    if (this.destroyed === true) return

    this.active--
    while (this.active < this.limit && this.waiting.length > 0 && this.destroyed === false) {
      this.active++
      this.waiting.shift()(true)
    }

    if (this.active === 0 && this.flushedResolve) {
      const resolve = this.flushedResolve
      this.flushedResolve = null
      this.flushedPromise = null
      resolve(true)
    }
  }

  async flush() {
    if (this.destroyed === true) return
    if (this.active === 0) return
    if (this.flushedPromise) return this.flushedPromise
    this.flushedPromise = new Promise(this._onflush)
    return this.flushedPromise
  }

  destroy() {
    this.destroyed = true
    this.active = 0
    while (this.waiting.length) this.waiting.pop()(false)
    if (this.flushedResolve) this.flushedResolve(false)
  }
}
const { EventEmitter } = require('events')
const safetyCatch = require('safety-catch')
const NoiseSecretStream = require('@hyperswarm/secret-stream')
const b4a = require('b4a')
const relay = require('blind-relay')
const NoiseWrap = require('./noise-wrap')
const Announcer = require('./announcer')
const { FIREWALL, ERROR } = require('./constants')
const { unslabbedHash } = require('./crypto')
const SecurePayload = require('./secure-payload')
const Holepuncher = require('./holepuncher')
const { isPrivate } = require('bogon')
const { ALREADY_LISTENING, NODE_DESTROYED, KEYPAIR_ALREADY_USED } = require('./errors')

const HANDSHAKE_CLEAR_WAIT = 10000
const HANDSHAKE_INITIAL_TIMEOUT = 10000

module.exports = class Server extends EventEmitter {
  constructor(dht, opts = {}) {
    super()

    this.dht = dht
    this.target = null

    this.closed = false
    this.firewall = opts.firewall || (() => false)
    this.holepunch = opts.holepunch || (() => true)
    this.relayThrough = opts.relayThrough || null
    this.relayKeepAlive = opts.relayKeepAlive || 5000
    this.pool = opts.pool || null
    this.createHandshake = opts.createHandshake || defaultCreateHandshake
    this.createSecretStream = opts.createSecretStream || defaultCreateSecretStream
    this.suspended = false
    this.handshakeClearWait = opts.handshakeClearWait || HANDSHAKE_CLEAR_WAIT

    this._shareLocalAddress = opts.shareLocalAddress !== false
    this._reusableSocket = !!opts.reusableSocket
    this._neverPunch = opts.holepunch === false // useful for fully disabling punching
    this._keyPair = null
    this._announcer = null
    this._connects = new Map()
    this._holepunches = []
    this._listening = null
    this._closing = null
  }

  get listening() {
    return this._listening !== null
  }

  get publicKey() {
    return this._keyPair && this._keyPair.publicKey
  }

  get relayAddresses() {
    return this._announcer ? this._announcer.relayAddresses : []
  }

  onconnection(encryptedSocket) {
    this.emit('connection', encryptedSocket)
  }

  async suspend({ log = noop } = {}) {
    log('Suspending hyperdht server')
    if (this._listening !== null) await this._listening
    log('Suspending hyperdht server (post listening)')
    this.suspended = true
    this._clearAll()
    return this._announcer ? this._announcer.suspend({ log }) : Promise.resolve()
  }

  async resume() {
    if (this._listening !== null) await this._listening
    this.suspended = false
    return this._announcer ? this._announcer.resume() : Promise.resolve()
  }

  address() {
    if (!this._keyPair) return null

    return {
      publicKey: this._keyPair.publicKey,
      host: this.dht.host,
      port: this.dht.port
    }
  }

  close() {
    if (this._closing) return this._closing
    this._closing = this._close()
    return this._closing
  }

  _gc() {
    this.dht.listening.delete(this)
    if (this.target) this.dht._router.delete(this.target)
  }

  async _stopListening() {
    try {
      if (this._announcer) await this._announcer.stop()
    } catch {
      // ignore
    }

    this._announcer = null
    this._listening = null
    this._keyPair = null
  }

  async _close() {
    if (this._listening === null) {
      this.closed = true
      this.emit('close')
      return
    }

    try {
      await this._listening
    } catch (err) {
      safetyCatch(err)
    }

    this._gc()
    this._clearAll()

    await this._stopListening()

    this.closed = true
    this.emit('close')
  }

  _clearAll() {
    while (this._holepunches.length > 0) {
      const h = this._holepunches.pop()
      if (h && h.puncher) h.puncher.destroy()
      if (h && h.clearing) clearTimeout(h.clearing)
      if (h && h.prepunching) clearTimeout(h.prepunching)
      if (h && h.rawStream) h.rawStream.destroy()
    }

    this._connects.clear()
  }

  async listen(keyPair = this.dht.defaultKeyPair, opts = {}) {
    if (this._listening !== null) throw ALREADY_LISTENING()
    if (this.dht.destroyed) throw NODE_DESTROYED()

    this._listening = this._listen(keyPair, opts)
    await this._listening
    return this
  }

  async _listen(keyPair, opts) {
    // From now on, the DHT object which created me is responsible for closing me
    this.dht.listening.add(this)

    try {
      await this.dht.bind()
      if (this._closing) return

      for (const s of this.dht.listening) {
        if (s._keyPair && b4a.equals(s._keyPair.publicKey, keyPair.publicKey)) {
          throw KEYPAIR_ALREADY_USED()
        }
      }

      this.target = unslabbedHash(keyPair.publicKey)
      this._keyPair = keyPair
      this._announcer = new Announcer(this.dht, keyPair, this.target, opts)

      this.dht._router.set(this.target, {
        relay: null,
        record: this._announcer.record,
        onpeerhandshake: this._onpeerhandshake.bind(this),
        onpeerholepunch: this._onpeerholepunch.bind(this)
      })

      // warm it up for now
      this._localAddresses().catch(safetyCatch)

      await this._announcer.start()
    } catch (err) {
      await this._stopListening()
      this._gc()
      throw err
    }

    if (this._closing) return
    if (this.suspended) await this._announcer.suspend()

    if (this._closing) return
    if (this.dht.destroyed) throw NODE_DESTROYED()

    if (this.pool) this.pool._attachServer(this)

    this.emit('listening')
  }

  refresh() {
    if (this._announcer && !this.suspended) this._announcer.refresh()
  }

  notifyOnline() {
    if (this._announcer) this._announcer.online.notify()
  }

  _localAddresses() {
    return this.dht.validateLocalAddresses(Holepuncher.localAddresses(this.dht.io.serverSocket))
  }

  async _addHandshake(k, noise, clientAddress, { from, to: serverAddress, socket }, direct) {
    let id = this._holepunches.indexOf(null)
    if (id === -1) id = this._holepunches.push(null) - 1

    const hs = {
      round: 0,
      reply: null,
      puncher: null,
      payload: null,
      rawStream: null,
      encryptedSocket: null,
      prepunching: null,
      firewalled: true,
      clearing: null,
      onsocket: null,
      aborted: false,

      // Relay state
      relayTimeout: null,
      relayToken: null,
      relaySocket: null,
      relayClient: null,
      relayPaired: false
    }

    this._holepunches[id] = hs

    const handshake = this.createHandshake(this._keyPair, null)

    let remotePayload
    try {
      remotePayload = await handshake.recv(noise)
    } catch (err) {
      safetyCatch(err)
      this._clearLater(hs, id, k)
      return null
    }

    if (this._closing || this.suspended) return null

    try {
      hs.firewalled = await this.firewall(handshake.remotePublicKey, remotePayload, clientAddress)
    } catch (err) {
      safetyCatch(err)
    }

    if (this._closing || this.suspended) return null

    if (hs.firewalled) {
      this._clearLater(hs, id, k)
      return null
    }

    const error =
      remotePayload.version === 1
        ? remotePayload.udx
          ? ERROR.NONE
          : ERROR.ABORTED
        : ERROR.VERSION_MISMATCH

    const addresses = []
    const ourRemoteAddr = this.dht.remoteAddress()
    const ourLocalAddrs = this._shareLocalAddress ? await this._localAddresses() : null

    if (this._closing || this.suspended) return null

    if (ourRemoteAddr) addresses.push(ourRemoteAddr)
    if (ourLocalAddrs) addresses.push(...ourLocalAddrs)

    if (error === ERROR.NONE) {
      hs.rawStream = this.dht.createRawStream({
        framed: true,
        firewall(socket, port, host) {
          if (!(port > 0 && port < 65536)) return true

          // Check if the traffic originated from the socket on which we're expecting relay traffic. If so,
          // we haven't hole punched yet and the other side is just sending us traffic through the relay.
          if (hs.relaySocket && isRelay(hs.relaySocket, socket, port, host)) {
            return false
          }

          hs.onsocket(socket, port, host)
          return false
        }
      })

      hs.rawStream.on('error', autoDestroy)

      // Handles the case where onsocket is never called, but the stream got setup
      // This can happen on a relayed connection which never connects directly
      // (onsocket is called there only when the direct connection is established)
      const onrawstreamclose = () => {
        if (this._closing) return
        this._clearLater(hs, id, k)
      }
      hs.rawStream.on('close', onrawstreamclose)

      hs.onsocket = (socket, port, host) => {
        if (hs.rawStream === null) return // Already hole punched

        this._clearLater(hs, id, k)

        if (hs.prepunching) {
          clearTimeout(hs.prepunching)
          hs.prepunching = null
        }

        if (this._reusableSocket && remotePayload.udx.reusableSocket) {
          this.dht._socketPool.routes.add(handshake.remotePublicKey, hs.rawStream)
        }

        hs.rawStream.removeListener('error', autoDestroy)
        hs.rawStream.removeListener('close', onrawstreamclose)

        if (hs.rawStream.connected) {
          const remoteChanging = hs.rawStream.changeRemote(socket, remotePayload.udx.id, port, host)

          if (remoteChanging) remoteChanging.catch(safetyCatch)
        } else {
          hs.rawStream.connect(socket, remotePayload.udx.id, port, host)
          hs.encryptedSocket = this.createSecretStream(false, hs.rawStream, {
            handshake: h,
            keepAlive: this.dht.connectionKeepAlive
          })

          this.onconnection(hs.encryptedSocket)
        }

        if (hs.puncher) {
          hs.puncher.onabort = noop
          hs.puncher.destroy()
        }

        hs.rawStream = null
      }

      function autoDestroy() {
        if (hs.puncher) hs.puncher.destroy()
      }
    }

    const relayAddresses = this.relayAddresses
    const relayThrough = selectRelay(this.relayThrough)

    if (relayThrough) hs.relayToken = relay.token()

    try {
      hs.reply = await handshake.send({
        error,
        firewall: ourRemoteAddr ? FIREWALL.OPEN : FIREWALL.UNKNOWN,
        holepunch: ourRemoteAddr ? null : { id, relays: this._announcer.relays },
        addresses4: addresses,
        addresses6: null,
        udx: {
          reusableSocket: this._reusableSocket,
          id: hs.rawStream ? hs.rawStream.id : 0,
          seq: 0
        },
        secretStream: {},
        relayThrough: relayThrough ? { publicKey: relayThrough, token: hs.relayToken } : null,
        relayAddresses: relayAddresses.length ? relayAddresses : null
      })
    } catch (err) {
      safetyCatch(err)
      if (hs.rawStream) hs.rawStream.destroy()
      this._clearLater(hs, id, k)
      return null
    }

    if (this._closing || this.suspended) {
      if (hs.rawStream) hs.rawStream.destroy()
      return null
    }

    const h = handshake.final()

    if (error !== ERROR.NONE) {
      if (hs.rawStream) hs.rawStream.destroy()
      this._clearLater(hs, id, k)
      return hs
    }

    if (remotePayload.firewall === FIREWALL.OPEN || direct) {
      const sock = direct ? socket : this.dht.socket
      this.dht.stats.punches.open++
      hs.onsocket(sock, clientAddress.port, clientAddress.host)
      return hs
    }

    if (relayThrough || remotePayload.relayThrough) {
      this._relayConnection(hs, relayThrough, remotePayload, h)
    }

    const onabort = () => {
      hs.aborted = true
      if (hs.prepunching) clearTimeout(hs.prepunching)
      hs.prepunching = null
      if (hs.rawStream.destroyed) {
        this._clearLater(hs, id, k)
        return
      }

      hs.rawStream.on('close', () => this._clearLater(hs, id, k))
      if (hs.relayToken === null) hs.rawStream.destroy()
    }

    if (!direct && clientAddress.host === serverAddress.host) {
      const clientAddresses = remotePayload.addresses4.filter(onlyPrivateHosts)

      if (clientAddresses.length > 0 && this._shareLocalAddress) {
        const myAddresses = await this._localAddresses()
        const addr = Holepuncher.matchAddress(myAddresses, clientAddresses)

        if (addr) {
          hs.prepunching = setTimeout(onabort, HANDSHAKE_INITIAL_TIMEOUT)
          return hs
        }
      }
    }

    if (this._closing || this.suspended) return null

    if (ourRemoteAddr || this._neverPunch) {
      hs.prepunching = setTimeout(onabort, HANDSHAKE_INITIAL_TIMEOUT)
      return hs
    }

    hs.payload = new SecurePayload(h.holepunchSecret)
    hs.puncher = new Holepuncher(this.dht, this.dht.session(), false, remotePayload.firewall)

    hs.puncher.onconnect = hs.onsocket
    hs.puncher.onabort = onabort
    hs.prepunching = setTimeout(hs.puncher.destroy.bind(hs.puncher), HANDSHAKE_INITIAL_TIMEOUT)

    return hs
  }

  _clearLater(hs, id, k) {
    if (hs.clearing) return
    hs.clearing = setTimeout(() => this._clear(hs, id, k), this.handshakeClearWait)
  }

  _clear(hs, id, k) {
    if (id >= this._holepunches.length || this._holepunches[id] !== hs) return
    if (hs.clearing) clearTimeout(hs.clearing)

    this._holepunches[id] = null
    while (
      this._holepunches.length > 0 &&
      this._holepunches[this._holepunches.length - 1] === null
    ) {
      this._holepunches.pop()
    }
    this._connects.delete(k)
  }

  async _onpeerhandshake({ noise, peerAddress }, req) {
    const k = b4a.toString(noise, 'hex')

    // The next couple of statements MUST run within the same tick to prevent
    // a malicious peer from flooding us with handshakes.
    let p = this._connects.get(k)
    if (!p) {
      p = this._addHandshake(k, noise, peerAddress || req.from, req, !peerAddress)
      this._connects.set(k, p)
    }

    const h = await p
    if (!h) return null

    if (this._closing !== null || this.suspended) return null

    return { socket: h.puncher && h.puncher.socket, noise: h.reply }
  }

  async _onpeerholepunch({ id, peerAddress, payload }, req) {
    const h = id < this._holepunches.length ? this._holepunches[id] : null
    if (!h) return null

    if (!peerAddress || this._closing !== null || this.suspended) return null

    const p = h.puncher
    if (!p || !p.socket) return this._abort(h) // not opened

    const remotePayload = h.payload.decrypt(payload)
    if (!remotePayload) return null

    const isServerRelay = this._announcer.isRelay(req.from)
    const { error, firewall, round, punching, addresses, remoteAddress, remoteToken } =
      remotePayload

    if (error !== ERROR.NONE) {
      // We actually do not need to set the round here, but just do it for consistency.
      if (round >= h.round) h.round = round
      return this._abort(h)
    }

    const token = h.payload.token(peerAddress)
    const echoed = isServerRelay && !!remoteToken && b4a.equals(token, remoteToken)

    // Update our heuristics here
    if (req.socket === p.socket) {
      p.nat.add(req.to, req.from)
    }

    if (round >= h.round) {
      h.round = round
      p.updateRemote({ punching, firewall, addresses, verified: echoed ? peerAddress.host : null })
    }

    // Wait for the analyzer to reach a conclusion...
    let stable = await p.analyze(false)
    if (p.destroyed) return null

    if (!p.remoteHolepunching && !stable) {
      stable = await p.analyze(true)
      if (p.destroyed) return null
      if (!stable) return this._abort(h)
    }

    // Fast mode! If we are consistent and the remote has opened a session to us (remoteAddress)
    // then fire a quick punch back. Note the await here just waits for the udp socket to flush.
    if (
      isConsistent(p.nat.firewall) &&
      remoteAddress &&
      hasSameAddr(p.nat.addresses, remoteAddress)
    ) {
      await p.ping(peerAddress)
      if (p.destroyed) return null
    }

    // Remote said they are punching (or willing to), so we will punch as well.
    // Note that this returns when the punching has STARTED, so no guarantee
    // we will have a connection after this promise etc.
    if (p.remoteHolepunching) {
      // TODO: still continue here if a local connection might work, but then do not holepunch...
      if (!this.holepunch(p.remoteFirewall, p.nat.firewall, p.remoteAddresses, p.nat.addresses)) {
        return p.destroyed ? null : this._abort(h)
      }

      if (h.prepunching) {
        clearTimeout(h.prepunching)
        h.prepunching = null
      }

      if (p.remoteFirewall >= FIREWALL.RANDOM || p.nat.firewall >= FIREWALL.RANDOM) {
        if (
          this.dht._randomPunches >= this.dht._randomPunchLimit ||
          Date.now() - this.dht._lastRandomPunch < this.dht._randomPunchInterval
        ) {
          if (!h.relayToken) return this._abort(h, ERROR.TRY_LATER)
          return {
            socket: p.socket,
            payload: h.payload.encrypt({
              error: ERROR.TRY_LATER,
              firewall: p.nat.firewall,
              round: h.round,
              connected: p.connected,
              punching: p.punching,
              addresses: p.nat.addresses,
              remoteAddress: null,
              token: isServerRelay ? token : null,
              remoteToken: remotePayload.token
            })
          }
        }
      }

      const punching = await p.punch()
      if (p.destroyed) return null
      if (!punching) return this._abort(h)
    }

    // Freeze that analysis as soon as we have a result we are giving to the other peer
    if (p.nat.firewall !== FIREWALL.UNKNOWN) {
      p.nat.freeze()
    }

    return {
      socket: p.socket,
      payload: h.payload.encrypt({
        error: ERROR.NONE,
        firewall: p.nat.firewall,
        round: h.round,
        connected: p.connected,
        punching: p.punching,
        addresses: p.nat.addresses,
        remoteAddress: null,
        token: isServerRelay ? token : null,
        remoteToken: remotePayload.token
      })
    }
  }

  _abort(h, error = ERROR.ABORTED) {
    if (!h.payload) {
      if (h.puncher) h.puncher.destroy()
      return null
    }

    const payload = h.payload.encrypt({
      error,
      firewall: FIREWALL.UNKNOWN,
      round: h.round,
      connected: false,
      punching: false,
      addresses: null,
      remoteAddress: null,
      token: null,
      remoteToken: null
    })

    h.puncher.destroy()

    return { socket: this.dht.socket, payload }
  }

  _relayConnection(hs, relayThrough, remotePayload, h) {
    this.dht.stats.relaying.attempts++

    let isInitiator
    let publicKey
    let token

    if (relayThrough) {
      isInitiator = true
      publicKey = relayThrough
      token = hs.relayToken
    } else {
      isInitiator = false
      publicKey = remotePayload.relayThrough.publicKey
      token = remotePayload.relayThrough.token
    }

    hs.relayToken = token
    hs.relaySocket = this.dht.connect(publicKey)
    hs.relaySocket.setKeepAlive(this.relayKeepAlive)
    hs.relayClient = relay.Client.from(hs.relaySocket, { id: hs.relaySocket.publicKey })
    hs.relayTimeout = setTimeout(onabort, 15000)

    hs.relayClient
      .pair(isInitiator, token, hs.rawStream)
      .on('error', onabort)
      .on('data', (remoteId) => {
        if (hs.relayTimeout) clearRelayTimeout(hs)
        if (hs.rawStream === null) {
          onabort(null)
          return
        }

        hs.relayPaired = true
        this.dht.stats.relaying.successes++

        if (hs.prepunching) clearTimeout(hs.prepunching)
        hs.prepunching = null

        const { remotePort, remoteHost, socket } = hs.relaySocket.rawStream

        hs.rawStream
          .on('close', () => hs.relaySocket.destroy())
          .connect(socket, remoteId, remotePort, remoteHost)

        hs.encryptedSocket = this.createSecretStream(false, hs.rawStream, { handshake: h })

        this.onconnection(hs.encryptedSocket)
      })

    const dht = this.dht
    function onabort() {
      if (!hs.relayPaired) dht.stats.relaying.aborts++
      if (hs.relayTimeout) clearRelayTimeout(hs)
      const socket = hs.relaySocket
      hs.relayToken = null
      hs.relaySocket = null
      if (socket) socket.destroy()
      if (hs.aborted && hs.rawStream) hs.rawStream.destroy()
    }
  }
}

function clearRelayTimeout(hs) {
  clearTimeout(hs.relayTimeout)
  hs.relayTimeout = null
}

function isConsistent(fw) {
  return fw === FIREWALL.OPEN || fw === FIREWALL.CONSISTENT
}

function hasSameAddr(addrs, other) {
  if (addrs === null) return false

  for (const addr of addrs) {
    if (addr.port === other.port && addr.host === other.host) return true
  }
  return false
}

function defaultCreateHandshake(keyPair, remotePublicKey) {
  return new NoiseWrap(keyPair, remotePublicKey)
}

function defaultCreateSecretStream(isInitiator, rawStream, opts) {
  return new NoiseSecretStream(isInitiator, rawStream, opts)
}

function onlyPrivateHosts(addr) {
  return isPrivate(addr.host)
}

function isRelay(relaySocket, socket, port, host) {
  const stream = relaySocket.rawStream
  if (!stream) return false
  if (stream.socket !== socket) return false
  return port === stream.remotePort && host === stream.remoteHost
}

function selectRelay(relayThrough) {
  if (typeof relayThrough === 'function') relayThrough = relayThrough()
  if (relayThrough === null) return null
  if (Array.isArray(relayThrough)) {
    return relayThrough[Math.floor(Math.random() * relayThrough.length)]
  }
  return relayThrough
}

function noop() {}
module.exports = class Sleeper {
  constructor() {
    this._timeout = null
    this._resolve = null

    this._start = (resolve) => {
      this._resolve = resolve
    }

    this._trigger = () => {
      if (this._resolve === null) return
      const resolve = this._resolve
      this._timeout = null
      this._resolve = null
      resolve()
    }
  }

  pause(ms) {
    const p = new Promise(this._start)
    if (this._timeout !== null) {
      clearTimeout(this._timeout)
      this._trigger()
    }
    this._timeout = setTimeout(this._trigger, ms)
    return p
  }

  resume() {
    if (this._timeout !== null) {
      clearTimeout(this._timeout)
      this._trigger()
    }
  }
}
const b4a = require('b4a')

const LINGER_TIME = 3000

module.exports = class SocketPool {
  constructor(dht, host) {
    this._dht = dht
    this._sockets = new Map()
    this._lingering = new Set() // updated by the ref
    this._host = host

    this.routes = new SocketRoutes(this)
  }

  _onmessage(ref, data, address) {
    this._dht.onmessage(ref.socket, data, address)
  }

  _add(ref) {
    this._sockets.set(ref.socket, ref)
  }

  _remove(ref) {
    this._sockets.delete(ref.socket)
    this._lingering.delete(ref)
  }

  lookup(socket) {
    return this._sockets.get(socket) || null
  }

  setReusable(socket, bool) {
    const ref = this.lookup(socket)
    if (ref) ref.reusable = bool
  }

  acquire() {
    // TODO: Enable socket reuse
    return new SocketRef(this)
  }

  async destroy() {
    const closing = []

    for (const ref of this._sockets.values()) {
      ref._unlinger()
      closing.push(ref.socket.close())
    }

    await Promise.allSettled(closing)
  }
}

class SocketRoutes {
  constructor(pool) {
    this._pool = pool
    this._routes = new Map()
  }

  add(publicKey, rawStream) {
    if (rawStream.socket) this._onconnect(publicKey, rawStream)
    else rawStream.on('connect', this._onconnect.bind(this, publicKey, rawStream))
  }

  get(publicKey) {
    const id = b4a.toString(publicKey, 'hex')
    const route = this._routes.get(id)
    if (!route) return null
    return route
  }

  _onconnect(publicKey, rawStream) {
    const id = b4a.toString(publicKey, 'hex')
    const socket = rawStream.socket

    let route = this._routes.get(id)

    if (!route) {
      const gc = () => {
        if (this._routes.get(id) === route) this._routes.delete(id)
        socket.removeListener('close', gc)
      }

      route = {
        socket,
        address: { host: rawStream.remoteHost, port: rawStream.remotePort },
        gc
      }

      this._routes.set(id, route)
      socket.on('close', gc)
    }

    this._pool.setReusable(socket, true)

    rawStream.on('error', () => {
      this._pool.setReusable(socket, false)
      if (!route) route = this._routes.get(id)
      if (route && route.socket === socket) route.gc()
    })
  }
}

// TODO: we should just make some "user data" object on udx to allow to attach this info
class SocketRef {
  constructor(pool) {
    this._pool = pool

    // Events
    this.onholepunchmessage = noop

    // Whether it should teardown immediately or wait a bit
    this.reusable = false

    this.socket = pool._dht.udx.createSocket()
    this.socket
      .on('close', this._onclose.bind(this))
      .on('message', this._onmessage.bind(this))
      .on('idle', this._onidle.bind(this))
      .on('busy', this._onbusy.bind(this))
      .bind(0, this._pool._host)

    this._refs = 1
    this._released = false
    this._closed = false

    this._timeout = null
    this._wasBusy = false

    this._pool._add(this)
  }

  _onclose() {
    this._pool._remove(this)
  }

  _onmessage(data, address) {
    if (data.byteLength > 1) {
      this._pool._onmessage(this, data, address)
    } else {
      this.onholepunchmessage(data, address, this)
    }
  }

  _onidle() {
    this._closeMaybe()
  }

  _onbusy() {
    this._wasBusy = true
    this._unlinger()
  }

  _reset() {
    this.onholepunchmessage = noop
  }

  _closeMaybe() {
    if (this._refs === 0 && this.socket.idle && !this._timeout) this._close()
  }

  _lingeringClose() {
    this._pool._lingering.delete(this)
    this._timeout = null
    this._closeMaybe()
  }

  _close() {
    this._unlinger()

    if (this.reusable && this._wasBusy) {
      this._wasBusy = false
      this._pool._lingering.add(this)
      this._timeout = setTimeout(this._lingeringClose.bind(this), LINGER_TIME)
      return
    }

    this._closed = true
    this.socket.close()
  }

  _unlinger() {
    if (this._timeout !== null) {
      clearTimeout(this._timeout)
      this._pool._lingering.delete(this)
      this._timeout = null
    }
  }

  get free() {
    return this._refs === 0
  }

  active() {
    this._refs++
    this._unlinger()
  }

  inactive() {
    this._refs--
    this._closeMaybe()
  }

  address() {
    return this.socket.address()
  }

  release() {
    if (this._released) return

    this._released = true
    this._reset()

    this._refs--
    this._closeMaybe()
  }
}

function noop() {}
{
  "name": "hyperdht",
  "version": "6.32.0",
  "description": "The DHT powering Hyperswarm",
  "main": "index.js",
  "browser": "browser.js",
  "bin": {
    "hyperdht": "./bin.js"
  },
  "files": [
    "index.js",
    "browser.js",
    "testnet.js",
    "bin.js",
    "lib/**.js"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    },
    "child_process": {
      "bare": "bare-node-child-process",
      "default": "child_process"
    }
  },
  "dependencies": {
    "@hyperswarm/secret-stream": "^6.6.2",
    "b4a": "^1.3.1",
    "bare-events": "^2.2.0",
    "blind-relay": "^1.3.0",
    "bogon": "^1.0.0",
    "compact-encoding": "^3.0.0",
    "dht-rpc": "^6.15.1",
    "hypercore-crypto": "^3.3.0",
    "hypercore-id-encoding": "^1.2.0",
    "hyperdht-address": "^1.0.1",
    "noise-curve-ed": "^2.0.0",
    "noise-handshake": "^4.0.0",
    "record-cache": "^1.1.1",
    "safety-catch": "^1.0.1",
    "signal-promise": "^1.0.3",
    "sodium-universal": "^5.0.1",
    "streamx": "^2.16.1",
    "unslab": "^1.3.0",
    "xache": "^1.1.0"
  },
  "devDependencies": {
    "bare-node-child-process": "^1.0.1",
    "brittle": "^3.0.0",
    "graceful-goodbye": "^1.3.0",
    "newline-decoder": "^1.0.2",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "test": "prettier --check . && node test/all.js",
    "test:bare": "bare test/all.js",
    "test:generate": "brittle -r test/all.js test/*.js",
    "integration": "brittle test/integration/*.js",
    "end-to-end": "brittle test/end-to-end/*.js"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "directories": {
    "lib": "lib",
    "test": "test"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/hyperdht.git"
  },
  "keywords": [],
  "bugs": {
    "url": "https://github.com/holepunchto/hyperdht/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperdht#readme"
}
{
  "name": "hyperschema",
  "version": "1.21.0",
  "description": "Create registries of declarative compact-encoding schemas",
  "files": [
    "lib/*.js",
    "builder.mjs",
    "builder.cjs",
    "runtime.mjs",
    "runtime.cjs",
    "primitives.mjs",
    "primitives.cjs"
  ],
  "exports": {
    "./package": "./package.json",
    ".": {
      "import": "./builder.mjs",
      "default": "./builder.cjs"
    },
    "./runtime": {
      "import": "./runtime.mjs",
      "default": "./runtime.cjs"
    },
    "./primitives": {
      "import": "./primitives.mjs",
      "default": "./primitives.cjs"
    }
  },
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    }
  },
  "scripts": {
    "format": "prettier . --write",
    "test": "prettier . --check && brittle test/index.js",
    "test:bare": "prettier . --check && bare test/index.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/hyperschema.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/hyperschema/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperschema#readme",
  "dependencies": {
    "bare-fs": "^4.0.1",
    "compact-encoding": "^3.0.0",
    "generate-object-property": "^2.0.0",
    "generate-string": "^1.0.1"
  },
  "devDependencies": {
    "brittle": "^3.7.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "test-tmp": "^1.3.0"
  }
}
module.exports = {
  c: require('compact-encoding')
}
const { EventEmitter } = require('events')
const { getStreamError } = require('streamx')
const DHT = require('hyperdht')
const spq = require('shuffled-priority-queue')
const b4a = require('b4a')
const unslab = require('unslab')

const PeerInfo = require('./lib/peer-info')
const RetryTimer = require('./lib/retry-timer')
const ConnectionSet = require('./lib/connection-set')
const PeerDiscovery = require('./lib/peer-discovery')

const MAX_PEERS = 64
const MAX_PARALLEL = 3
const MAX_CLIENT_CONNECTIONS = Infinity // TODO: Change
const MAX_SERVER_CONNECTIONS = Infinity

const ERR_MISSING_TOPIC = 'Topic is required and must be a 32-byte buffer'
const ERR_DESTROYED = 'Swarm has been destroyed'
const ERR_DUPLICATE = 'Duplicate connection'
const ERR_FIREWALL = 'Peer is firewalled'

module.exports = class Hyperswarm extends EventEmitter {
  constructor(opts = {}) {
    super()
    const {
      seed,
      relayThrough,
      keyPair = DHT.keyPair(seed),
      maxPeers = MAX_PEERS,
      maxClientConnections = MAX_CLIENT_CONNECTIONS,
      maxServerConnections = MAX_SERVER_CONNECTIONS,
      maxParallel = MAX_PARALLEL,
      firewall = allowAll
    } = opts
    this.keyPair = keyPair

    this.dht =
      opts.dht ||
      new DHT({
        bootstrap: opts.bootstrap,
        nodes: opts.nodes,
        port: opts.port,
        deferRandomPunch: opts.deferRandomPunch,
        randomPunchInterval: opts.randomPunchInterval
      })
    this.server = this.dht.createServer(
      {
        firewall: this._handleFirewall.bind(this),
        relayThrough: this._maybeRelayConnection.bind(this),
        handshakeClearWait: opts.handshakeClearWait
      },
      this._handleServerConnection.bind(this)
    )

    this.destroyed = false
    this.suspended = false
    this.maxPeers = maxPeers
    this.maxClientConnections = maxClientConnections
    this.maxServerConnections = maxServerConnections
    this.maxParallel = maxParallel
    this.relayThrough = relayThrough ? toRelayFunction(relayThrough) : null

    this.connecting = 0
    this.connections = new Set()
    this.peers = new Map()
    this.explicitPeers = new Set()
    this.listening = null
    this.stats = {
      updates: 0,
      connects: {
        client: {
          opened: 0,
          closed: 0,
          attempted: 0
        },
        server: {
          // Note: there is no notion of 'attempts' for server connections
          opened: 0,
          closed: 0
        }
      },
      bannedPeers: 0
    }

    this._discovery = new Map()
    this._timer = new RetryTimer(this._requeue.bind(this), {
      backoffs: opts.backoffs,
      jitter: opts.jitter
    })
    this._queue = spq()

    this._allConnections = new ConnectionSet()
    this._pendingFlushes = []
    this._flushTick = 0

    this._drainingQueue = false
    this._clientConnections = 0
    this._serverConnections = 0
    this._firewall = firewall

    this.dht.on('network-change', this._handleNetworkChange.bind(this))
    this.dht.on('network-update', this._handleNetworkUpdate.bind(this))
    this.on('update', this._handleUpdate)
  }

  _maybeRelayConnection(force) {
    if (!this.relayThrough) return null
    return this.relayThrough(force, this)
  }

  _enqueue(peerInfo) {
    if (peerInfo.queued) return
    peerInfo.queued = true
    peerInfo._flushTick = this._flushTick
    this._queue.add(peerInfo)

    this._attemptClientConnections()
  }

  _requeue(batch) {
    if (this.suspended) return
    for (const peerInfo of batch) {
      peerInfo.waiting = false

      if (
        peerInfo._updatePriority() === false ||
        this._allConnections.has(peerInfo.publicKey) ||
        peerInfo.queued
      ) {
        continue
      }
      peerInfo.queued = true
      peerInfo._flushTick = this._flushTick
      this._queue.add(peerInfo)
    }

    this._attemptClientConnections()
  }

  _flushMaybe(peerInfo) {
    for (let i = 0; i < this._pendingFlushes.length; i++) {
      const flush = this._pendingFlushes[i]
      if (peerInfo._flushTick > flush.tick) continue
      if (--flush.missing > 0) continue
      flush.onflush(true)
      this._pendingFlushes.splice(i--, 1)
    }
  }

  _withinMaxPeers() {
    const e = this.explicitPeers.size
    const factor = e === 0 ? 1 : e < 2 ? 2 : e < 4 ? 3 : 4
    return factor * this._allConnections.size < this.maxPeers
  }

  _flushAllMaybe() {
    if (
      this.connecting > 0 ||
      (this._withinMaxPeers() && this._clientConnections < this.maxClientConnections)
    ) {
      return false
    }

    while (this._pendingFlushes.length) {
      const flush = this._pendingFlushes.pop()
      flush.onflush(true)
    }

    return true
  }

  _shouldConnectExplicit() {
    return !this.destroyed && !this.suspended && this.connecting < this.maxParallel
  }

  _shouldConnect() {
    return (
      !this.destroyed &&
      !this.suspended &&
      this.connecting < this.maxParallel &&
      this._withinMaxPeers() &&
      this._clientConnections < this.maxClientConnections
    )
  }

  _shouldRequeue(peerInfo) {
    if (this.suspended) return false
    if (peerInfo.explicit) return true
    for (const topic of peerInfo.topics) {
      if (this._discovery.has(b4a.toString(topic, 'hex')) && !this.destroyed) {
        return true
      }
    }
    return false
  }

  _connect(peerInfo, queued) {
    if (peerInfo.banned || this._allConnections.has(peerInfo.publicKey)) {
      if (queued) this._flushMaybe(peerInfo)
      return
    }

    // TODO: Support async firewalling at some point.
    if (this._handleFirewall(peerInfo.publicKey, null)) {
      if (queued) this._flushMaybe(peerInfo)
      return
    }

    const relayThrough = this._maybeRelayConnection(peerInfo.forceRelaying)
    const conn = this.dht.connect(peerInfo.publicKey, {
      relayAddresses: peerInfo.relayAddresses,
      keyPair: this.keyPair,
      relayThrough
    })
    this._allConnections.add(conn)

    this.stats.connects.client.attempted++

    this.connecting++
    this._clientConnections++
    let opened = false

    const onerror = (err) => {
      if (this.relayThrough && shouldForceRelaying(err.code)) {
        peerInfo.forceRelaying = true
        // Reset the attempts in order to fast connect to relay
        peerInfo.attempts = 0
      }
    }

    // Removed once a connection is opened
    conn.on('error', onerror)

    conn.on('open', () => {
      opened = true
      this.stats.connects.client.opened++

      this._connectDone()
      this.connections.add(conn)
      conn.removeListener('error', onerror)
      peerInfo._connected()
      peerInfo.client = true
      this.emit('connection', conn, peerInfo)
      if (queued) this._flushMaybe(peerInfo)

      this.emit('update')
    })
    conn.on('close', () => {
      if (!opened) this._connectDone()
      this.stats.connects.client.closed++

      const err = getStreamError(conn)
      if (shouldBan(err)) {
        this._banPeer(peerInfo, true, err)
      }

      this.connections.delete(conn)
      this._allConnections.delete(conn)
      this._clientConnections--
      peerInfo._disconnected()

      peerInfo.waiting = this._shouldRequeue(peerInfo) && this._timer.add(peerInfo)
      this._maybeDeletePeer(peerInfo)

      if (!opened && queued) this._flushMaybe(peerInfo)

      this._attemptClientConnections()

      this.emit('update')
    })

    this.emit('update')
  }

  _connectDone() {
    this.connecting--

    if (this.connecting < this.maxParallel) this._attemptClientConnections()
    if (this.connecting === 0) this._flushAllMaybe()
  }

  // Called when the PeerQueue indicates a connection should be attempted.
  _attemptClientConnections() {
    // Guard against re-entries - unsure if it still needed but doesn't hurt
    if (this._drainingQueue || this.suspended) return
    this._drainingQueue = true

    for (const peerInfo of this.explicitPeers) {
      if (!this._shouldConnectExplicit()) break
      if (
        peerInfo.attempts >= 5 ||
        Date.now() - peerInfo.disconnectedTime < peerInfo.attempts * 1000
      ) {
        continue
      }
      this._connect(peerInfo, false)
    }

    while (this._queue.length && this._shouldConnect()) {
      const peerInfo = this._queue.shift()
      peerInfo.queued = false
      this._connect(peerInfo, true)
    }
    this._drainingQueue = false
    if (this.connecting === 0) this._flushAllMaybe()
  }

  _handleFirewall(remotePublicKey, payload) {
    if (b4a.equals(remotePublicKey, this.keyPair.publicKey)) return true

    let peerInfo = this.peers.get(b4a.toString(remotePublicKey, 'hex'))
    if (peerInfo && peerInfo.banned) return true

    const firewalled = this._firewall(remotePublicKey, payload)
    if (firewalled) {
      if (!peerInfo) peerInfo = this._upsertPeer(remotePublicKey)
      this._banPeer(peerInfo, true, new Error(ERR_FIREWALL))
    }

    return firewalled
  }

  _handleServerConnectionSwap(existing, conn) {
    let closed = false

    existing.on('close', () => {
      if (closed) return

      conn.removeListener('error', noop)
      conn.removeListener('close', onclose)

      this._handleServerConnection(conn)
    })

    conn.on('error', noop)
    conn.on('close', onclose)

    function onclose() {
      closed = true
    }
  }

  // Called when the DHT receives a new server connection.
  _handleServerConnection(conn) {
    if (this.destroyed || this.suspended) {
      // TODO: Investigate why a final server connection can be received after close
      conn.on('error', noop)
      return conn.destroy(ERR_DESTROYED)
    }

    const existing = this._allConnections.get(conn.remotePublicKey)

    if (existing) {
      // If both connections are from the same peer,
      // - pick the new one if the existing stream is already established (has sent and received bytes),
      //   because the other client must have lost that connection and be reconnecting
      // - otherwise, pick the one thats expected to initiate in a tie break
      const existingIsOutdated = existing.rawBytesRead > 0 && existing.rawBytesWritten > 0
      const expectedInitiator = b4a.compare(conn.publicKey, conn.remotePublicKey) > 0
      const keepNew = existingIsOutdated || expectedInitiator === conn.isInitiator

      if (keepNew === false) {
        existing.sendKeepAlive()
        conn.on('error', noop)
        conn.destroy(new Error(ERR_DUPLICATE))
        return
      }

      existing.on('error', noop)
      existing.destroy(new Error(ERR_DUPLICATE))
      this._handleServerConnectionSwap(existing, conn)
      return
    }

    // When reaching here, the connection will always be 'opened' next tick
    this.stats.connects.server.opened++

    const peerInfo = this._upsertPeer(conn.remotePublicKey, null)

    this.connections.add(conn)
    this._allConnections.add(conn)
    this._serverConnections++

    conn.on('close', () => {
      const err = getStreamError(conn)
      if (shouldBan(err)) {
        this._banPeer(peerInfo, true, err)
      }

      this.connections.delete(conn)
      this._allConnections.delete(conn)
      this._serverConnections--
      this.stats.connects.server.closed++

      this._maybeDeletePeer(peerInfo)

      this._attemptClientConnections()

      this.emit('update')
    })
    peerInfo.client = false
    this.emit('connection', conn, peerInfo)

    this.emit('update')
  }

  _upsertPeer(publicKey, relayAddresses) {
    if (b4a.equals(publicKey, this.keyPair.publicKey)) return null
    const keyString = b4a.toString(publicKey, 'hex')
    let peerInfo = this.peers.get(keyString)

    if (peerInfo) {
      peerInfo.relayAddresses = relayAddresses // new is always better
      return peerInfo
    }

    peerInfo = new PeerInfo({
      publicKey,
      relayAddresses
    })

    this.peers.set(keyString, peerInfo)
    return peerInfo
  }

  _handleUpdate() {
    this.stats.updates++
  }

  _maybeDeletePeer(peerInfo) {
    if (!peerInfo.shouldGC()) return

    const hasActiveConn = this._allConnections.has(peerInfo.publicKey)
    if (hasActiveConn) return

    const keyString = b4a.toString(peerInfo.publicKey, 'hex')
    this.peers.delete(keyString)
  }

  /*
   * Called when a peer is actively discovered during a lookup.
   *
   * Three conditions:
   *  1. Not a known peer -- insert into queue
   *  2. A known peer with normal priority -- do nothing
   *  3. A known peer with low priority -- bump priority, because it's been rediscovered
   */
  _handlePeer(peer, topic) {
    const peerInfo = this._upsertPeer(peer.publicKey, peer.relayAddresses)
    if (peerInfo) peerInfo._topic(topic)
    if (!peerInfo || this._allConnections.has(peer.publicKey)) return
    if (!peerInfo.prioritized || peerInfo.server) peerInfo._reset()
    if (peerInfo._updatePriority()) {
      this._enqueue(peerInfo)
    }
  }

  async _handleNetworkUpdate() {
    if (!this.online) return
    this._handleNetworkChange()
  }

  async _handleNetworkChange() {
    if (this.suspended) return

    // prioritize figuring out if existing connections are dead
    for (const conn of this._allConnections) {
      conn.sendKeepAlive()
    }

    const refreshes = []

    for (const discovery of this._discovery.values()) {
      refreshes.push(discovery.refresh())
    }

    await Promise.allSettled(refreshes)
  }

  _banPeer(peerInfo, banned, err) {
    peerInfo.ban(banned)
    this.stats.bannedPeers++
    this.emit('ban', peerInfo, err)
  }

  status(key) {
    return this._discovery.get(b4a.toString(key, 'hex')) || null
  }

  listen() {
    if (!this.listening) {
      if (this.destroyed) throw new Error('Swarm destroyed')
      this.listening = this.server.listen(this.keyPair)
    }
    return this.listening
  }

  // Object that exposes a cancellation method (destroy)
  // TODO: When you rejoin, it should reannounce + bump lookup priority
  join(topic, opts = {}) {
    if (this.destroyed) throw new Error('Swarm destroyed')
    if (!topic) throw new Error(ERR_MISSING_TOPIC)
    topic = unslab(topic)

    const topicString = b4a.toString(topic, 'hex')

    let discovery = this._discovery.get(topicString)

    if (discovery && !discovery.destroyed) {
      return discovery.session(opts)
    }

    discovery = new PeerDiscovery(this, topic, {
      limit: opts.limit,
      wait: discovery ? discovery.destroy() : null,
      suspended: this.suspended,
      onpeer: (peer) => this._handlePeer(peer, topic)
    })
    this._discovery.set(topicString, discovery)
    return discovery.session(opts)
  }

  // Returns a promise
  async leave(topic) {
    if (!topic) throw new Error(ERR_MISSING_TOPIC)
    const topicString = b4a.toString(topic, 'hex')
    if (!this._discovery.has(topicString)) return Promise.resolve()

    const discovery = this._discovery.get(topicString)

    try {
      await discovery.destroy()
    } catch {
      // ignore, prop network
    }

    if (this._discovery.get(topicString) === discovery) {
      this._discovery.delete(topicString)
    }
  }

  joinPeer(publicKey) {
    const peerInfo = this._upsertPeer(publicKey, null)
    if (!peerInfo) return
    if (!this.explicitPeers.has(peerInfo)) {
      peerInfo.explicit = true
      this.explicitPeers.add(peerInfo)
    }
    if (this._allConnections.has(publicKey)) return
    if (peerInfo._updatePriority()) {
      this._enqueue(peerInfo)
    }
  }

  leavePeer(publicKey) {
    const keyString = b4a.toString(publicKey, 'hex')
    if (!this.peers.has(keyString)) return

    const peerInfo = this.peers.get(keyString)
    peerInfo.explicit = false
    this.explicitPeers.delete(peerInfo)
    this._maybeDeletePeer(peerInfo)
  }

  // Returns a promise
  async flush() {
    const allFlushed = [...this._discovery.values()].map((v) => v.flushed())
    await Promise.all(allFlushed)
    if (this._flushAllMaybe()) return true
    const pendingSize = this._allConnections.size - this.connections.size
    if (!this._queue.length && !pendingSize) return true
    return new Promise((resolve) => {
      this._pendingFlushes.push({
        onflush: resolve,
        missing: this._queue.length + pendingSize,
        tick: this._flushTick++
      })
    })
  }

  async clear() {
    const cleared = Promise.allSettled([...this._discovery.values()].map((d) => d.destroy()))
    this._discovery.clear()
    return cleared
  }

  async destroy({ force } = {}) {
    if (this.destroyed && !force) return
    this.destroyed = true

    this._timer.destroy()

    if (!force) await this.clear()

    await this.server.close()

    while (this._pendingFlushes.length) {
      const flush = this._pendingFlushes.pop()
      flush.onflush(false)
    }

    await this.dht.destroy({ force })
  }

  async suspend({ log = noop } = {}) {
    if (this.suspended) return

    const promises = []

    promises.push(this.server.suspend({ log }))

    for (const discovery of this._discovery.values()) {
      promises.push(discovery.suspend({ log }))
    }

    const pending = []
    for (const connection of this._allConnections) {
      connection.destroy()
      pending.push(new Promise((resolve) => connection.on('close', resolve)))
    }

    this.suspended = true

    log('Suspending server and discovery... (' + promises.length + ')')
    await Promise.allSettled(promises)
    log('Done, suspending the dht...')
    await this.dht.suspend({ log })
    log('Done, swarm fully suspended')

    await Promise.all(pending)

    // reset queue
    this._timer.destroy()
    this._timer = new RetryTimer(this._requeue.bind(this), {
      backoffs: this._timer.backoffs,
      jitter: this._timer.jitter
    })
    this._queue = spq()
  }

  async resume({ log = noop } = {}) {
    if (!this.suspended) return

    log('Resuming the dht')
    await this.dht.resume()
    log('Done, resuming the server')
    await this.server.resume()
    log('Done, all discovery')

    for (const discovery of this._discovery.values()) {
      discovery.resume()
    }

    this.suspended = false
    this._attemptClientConnections()
  }

  topics() {
    return this._discovery.values()
  }
}

function noop() {}

function allowAll() {
  return false
}

function shouldForceRelaying(code) {
  return (
    code === 'HOLEPUNCH_ABORTED' ||
    code === 'HOLEPUNCH_DOUBLE_RANDOMIZED_NATS' ||
    code === 'REMOTE_NOT_HOLEPUNCHABLE'
  )
}

function shouldBan() {
  // return !!err && err.name === 'HypercoreError' && err.code === 'INVALID_OPERATION'
  return false
}

function toRelayFunction(relayThrough) {
  return typeof relayThrough === 'function'
    ? relayThrough
    : (force, swarm) => (force || swarm.dht.randomized ? relayThrough : null)
}
module.exports = class BulkTimer {
  constructor(time, fn) {
    this._time = time
    this._fn = fn
    this._interval = null
    this._next = []
    this._pending = []
    this._destroyed = false
  }

  destroy() {
    if (this._destroyed) return
    this._destroyed = true
    clearInterval(this._interval)
    this._interval = null
  }

  _ontick() {
    if (!this._next.length && !this._pending.length) return
    if (this._next.length) this._fn(this._next)
    this._next = this._pending
    this._pending = []
  }

  add(info) {
    if (this._destroyed) return
    if (!this._interval) {
      this._interval = setInterval(this._ontick.bind(this), Math.floor(this._time * 0.66))
    }

    this._pending.push(info)
  }
}
const b4a = require('b4a')

module.exports = class ConnectionSet {
  constructor() {
    this._byPublicKey = new Map()
  }

  [Symbol.iterator]() {
    return this._byPublicKey.values()
  }

  get size() {
    return this._byPublicKey.size
  }

  has(publicKey) {
    return this._byPublicKey.has(toHex(publicKey))
  }

  get(publicKey) {
    return this._byPublicKey.get(toHex(publicKey))
  }

  add(connection) {
    this._byPublicKey.set(b4a.toString(connection.remotePublicKey, 'hex'), connection)
  }

  delete(connection) {
    const keyString = b4a.toString(connection.remotePublicKey, 'hex')
    const existing = this._byPublicKey.get(keyString)
    if (existing !== connection) return
    this._byPublicKey.delete(keyString)
  }
}

function toHex(b) {
  return typeof b === 'string' ? b : b4a.toString(b, 'hex')
}
const safetyCatch = require('safety-catch')
const b4a = require('b4a')

const REFRESH_INTERVAL = 1000 * 60 * 10 // 10 min
const RANDOM_JITTER = 1000 * 60 * 2 // 2 min
const DELAY_GRACE_PERIOD = 1000 * 30 // 30s

const MAX_DISCOVERY_CACHE = 64

module.exports = class PeerDiscovery {
  constructor(
    swarm,
    topic,
    { limit = Infinity, wait = null, suspended = false, onpeer = noop, onerror = safetyCatch }
  ) {
    this.limit = limit
    this.swarm = swarm
    this.topic = topic
    this.isClient = false
    this.isServer = false
    this.destroyed = false
    this.destroying = null
    this.suspended = suspended

    this._sessions = []
    this._clientSessions = 0
    this._serverSessions = 0

    this._onpeer = onpeer
    this._onerror = onerror

    this._discovered = new Set()
    this._activeQuery = null
    this._timer = null
    this._currentRefresh = null
    this._closestNodes = null
    this._firstAnnounce = true
    this._needsUnannounce = false
    this._refreshes = 0
    this._wait = wait
  }

  session({ server = true, client = true, limit = Infinity, onerror = safetyCatch }) {
    if (this.destroyed) throw new Error('PeerDiscovery is destroyed')
    const session = new PeerDiscoverySession(this)
    session.refresh({ server, client, limit }).catch(onerror)
    this._sessions.push(session)
    return session
  }

  _refreshLater(eager) {
    const jitter = Math.round(Math.random() * RANDOM_JITTER)
    const delay = !eager ? REFRESH_INTERVAL + jitter : jitter

    if (this._timer) clearTimeout(this._timer)

    const startTime = Date.now()
    this._timer = setTimeout(() => {
      // If your laptop went to sleep, and is coming back online...
      const overdue = Date.now() - startTime > delay + DELAY_GRACE_PERIOD
      if (overdue) this._refreshLater(true)
      else this.refresh().catch(this._onerror)
    }, delay)
  }

  _isActive() {
    return !this.destroyed && !this.suspended
  }

  // TODO: Allow announce to be an argument to this
  // TODO: Maybe announce should be a setter?
  async _refresh() {
    if (this.suspended) return
    const clock = ++this._refreshes

    if (this._wait) {
      await this._wait
      this._wait = null
      if (clock !== this._refreshes || !this._isActive()) return
    }

    const clear = this.isServer && this._firstAnnounce
    if (clear) this._firstAnnounce = false

    const opts = {
      clear,
      closestNodes: this._closestNodes
    }

    if (this.isServer) {
      await this.swarm.listen()
      // if a parallel refresh is happening, yield to the new one
      if (clock !== this._refreshes || !this._isActive()) return
      this._needsUnannounce = true
    }

    let limit = this.limit

    if (limit < Infinity && limit > 0) {
      for (const id of this._discovered) {
        if (!this.swarm.connections.has(id)) continue
        if (--limit === 0) break
      }
    }

    this._discovered.clear()

    const announcing = this.isServer
    const query = (this._activeQuery = announcing
      ? this.swarm.dht.announce(
          this.topic,
          this.swarm.keyPair,
          this.swarm.server.relayAddresses,
          opts
        )
      : this._needsUnannounce
        ? this.swarm.dht.lookupAndUnannounce(this.topic, this.swarm.keyPair, opts)
        : this.swarm.dht.lookup(this.topic, opts))

    try {
      for await (const data of this._activeQuery) {
        if (!this.isClient || !this._isActive()) continue
        for (const peer of data.peers) {
          if (limit < Infinity) {
            const id = b4a.toString(peer.publicKey, 'hex')

            if (this._discovered.size < MAX_DISCOVERY_CACHE) {
              this._discovered.add(id)
            }

            if (limit === 0) continue

            // there is a chance it has updated a connection during discovery and we go over
            // the limit - thats acceptable to avoid a complexity spiral here.
            if (!this.swarm.connections.has(id)) limit--
          }

          this._onpeer(peer, data)
        }
      }
    } catch (err) {
      if (this._isActive()) throw err
    } finally {
      if (this._activeQuery === query) {
        this._activeQuery = null
        if (!this.destroyed && !this.suspended) this._refreshLater(false)
      }
    }

    // This is set at the very end, when the query completes successfully.
    this._closestNodes = query.closestNodes

    if (clock !== this._refreshes) return

    // In this is the latest query, unannounce has been fulfilled as well
    if (!announcing) this._needsUnannounce = false
  }

  async refresh() {
    if (this.destroyed) throw new Error('PeerDiscovery is destroyed')

    const server = this._serverSessions > 0
    const client = this._clientSessions > 0

    if (this.suspended) return

    if (server === this.isServer && client === this.isClient) {
      if (this._currentRefresh) return this._currentRefresh
      this._currentRefresh = this._refresh()
    } else {
      if (this._activeQuery) this._activeQuery.destroy()
      this.isServer = server
      this.isClient = client
      this._currentRefresh = this._refresh()
    }

    const refresh = this._currentRefresh
    try {
      await refresh
    } catch {
      return false
    } finally {
      if (refresh === this._currentRefresh) {
        this._currentRefresh = null
      }
    }

    return true
  }

  async flushed() {
    if (this.swarm.listening) await this.swarm.listening

    try {
      await this._currentRefresh
      return true
    } catch {
      return false
    }
  }

  async _destroyMaybe() {
    if (this.destroyed) return

    try {
      if (this._sessions.length === 0) await this.swarm.leave(this.topic)
      else if (this._serverSessions === 0 && this._needsUnannounce) await this.refresh()
    } catch (err) {
      // ignore network failures here, as we are tearing down
      safetyCatch(err)
    }
  }

  destroy() {
    if (this.destroying) return this.destroying
    this.destroying = this._destroy()
    return this.destroying
  }

  async _abort(log) {
    const id = log === noop ? '' : b4a.toString(this.topic, 'hex')

    log('Aborting discovery', id)
    if (this._wait) await this._wait
    log('Aborting discovery (post wait)', id)

    if (this._activeQuery) {
      this._activeQuery.destroy()
      this._activeQuery = null
    }
    if (this._timer) {
      clearTimeout(this._timer)
      this._timer = null
    }

    let nodes = this._closestNodes

    if (this._currentRefresh) {
      try {
        await this._currentRefresh
      } catch {
        // If the destroy causes the refresh to fail, suppress it.
      }
    }

    log('Aborting discovery (post refresh)', id)
    if (this._isActive()) return

    if (!nodes) nodes = this._closestNodes
    else if (this._closestNodes !== nodes) {
      const len = nodes.length
      for (const newer of this._closestNodes) {
        if (newer.id && !hasNode(nodes, len, newer)) nodes.push(newer)
      }
    }

    if (this._needsUnannounce) {
      log('Unannouncing discovery', id)
      if (nodes && nodes.length) {
        await this.swarm.dht.unannounce(this.topic, this.swarm.keyPair, {
          closestNodes: nodes,
          onlyClosestNodes: true,
          force: true
        })
      }
      this._needsUnannounce = false
      log('Unannouncing discovery (done)', id)
    }
  }

  _destroy() {
    if (this.destroyed) return
    this.destroyed = true
    return this._abort(noop)
  }

  async suspend({ log = noop } = {}) {
    if (this.suspended) return
    this.suspended = true
    try {
      await this._abort(log)
    } catch {
      // ignore
    }
  }

  resume() {
    if (!this.suspended) return
    this.suspended = false
    this.refresh().catch(noop)
  }
}

class PeerDiscoverySession {
  constructor(discovery) {
    this.discovery = discovery
    this.isClient = false
    this.isServer = false
    this.destroyed = false
  }

  get swarm() {
    return this.discovery.swarm
  }

  get topic() {
    return this.discovery.topic
  }

  async refresh({ client = this.isClient, server = this.isServer, limit = Infinity } = {}) {
    if (this.destroyed) throw new Error('PeerDiscovery is destroyed')
    if (!client && !server) throw new Error('Cannot refresh with neither client nor server option')

    if (client !== this.isClient) {
      this.isClient = client
      this.discovery._clientSessions += client ? 1 : -1
    }

    if (server !== this.isServer) {
      this.isServer = server
      this.discovery._serverSessions += server ? 1 : -1
    }

    this.discovery.limit = limit

    return this.discovery.refresh()
  }

  async flushed() {
    return this.discovery.flushed()
  }

  async destroy() {
    if (this.destroyed) return
    this.destroyed = true

    if (this.isClient) this.discovery._clientSessions--
    if (this.isServer) this.discovery._serverSessions--

    const index = this.discovery._sessions.indexOf(this)
    const head = this.discovery._sessions.pop()

    if (head !== this) this.discovery._sessions[index] = head

    return this.discovery._destroyMaybe()
  }
}

function hasNode(nodes, len, node) {
  for (let i = 0; i < len; i++) {
    const existing = nodes[i]
    if (existing.id && b4a.equals(existing.id, node.id)) return true
  }

  return false
}

function noop() {}
const { EventEmitter } = require('events')
const b4a = require('b4a')
const unslab = require('unslab')

const MIN_CONNECTION_TIME = 15000

const VERY_LOW_PRIORITY = 0
const LOW_PRIORITY = 1
const NORMAL_PRIORITY = 2
const HIGH_PRIORITY = 3
const VERY_HIGH_PRIORITY = 4

module.exports = class PeerInfo extends EventEmitter {
  constructor({ publicKey, relayAddresses }) {
    super()

    this.publicKey = unslab(publicKey)
    this.relayAddresses = relayAddresses

    this.reconnecting = true
    this.proven = false
    this.connectedTime = -1
    this.disconnectedTime = 0
    this.banned = false
    this.tried = false
    this.explicit = false
    this.waiting = false
    this.forceRelaying = false

    // Set by the Swarm
    this.queued = false
    this.client = false
    this.topics = [] // TODO: remove on next major (check with mafintosh for context)

    this.attempts = 0
    this.priority = NORMAL_PRIORITY

    // Used by shuffled-priority-queue
    this._index = 0

    // Used for flush management
    this._flushTick = 0

    // Used for topic multiplexing
    this._seenTopics = new Set()
  }

  get server() {
    return !this.client
  }

  get prioritized() {
    return this.priority >= NORMAL_PRIORITY
  }

  _getPriority() {
    const peerIsStale = this.tried && !this.proven
    if (peerIsStale || this.attempts > 3) return VERY_LOW_PRIORITY
    if (this.attempts === 3) return LOW_PRIORITY
    if (this.attempts === 2) return HIGH_PRIORITY
    if (this.attempts === 1) return VERY_HIGH_PRIORITY
    return NORMAL_PRIORITY
  }

  _connected() {
    this.proven = true
    this.connectedTime = Date.now()
  }

  _disconnected() {
    this.disconnectedTime = Date.now()
    if (this.connectedTime > -1) {
      if (this.disconnectedTime - this.connectedTime >= MIN_CONNECTION_TIME) this.attempts = 0 // fast retry
      this.connectedTime = -1
    }
    this.attempts++
  }

  _deprioritize() {
    this.attempts = 3
  }

  _reset() {
    this.client = false
    this.proven = false
    this.tried = false
    this.attempts = 0
  }

  _updatePriority() {
    if (this.explicit && this.attempts > 3) this._deprioritize()
    if (this.banned || this.queued || this.attempts > 3) return false
    this.priority = this._getPriority()
    return true
  }

  _topic(topic) {
    const topicString = b4a.toString(topic, 'hex')
    if (this._seenTopics.has(topicString)) return
    this._seenTopics.add(topicString)
    this.topics.push(topic)
    this.emit('topic', topic)
  }

  reconnect(val) {
    this.reconnecting = !!val
  }

  ban(val) {
    this.banned = !!val
  }

  shouldGC() {
    return !(this.banned || this.queued || this.explicit || this.waiting)
  }
}
const BulkTimer = require('./bulk-timer')

const BACKOFF_JITTER = 500
const BACKOFF_S = 1000 + Math.round(BACKOFF_JITTER * Math.random())
const BACKOFF_M = 5000 + Math.round(2 * BACKOFF_JITTER * Math.random())
const BACKOFF_L = 15000 + Math.round(4 * BACKOFF_JITTER * Math.random())
const BACKOFF_X = 1000 * 60 * 10 + Math.round(240 * BACKOFF_JITTER * Math.random())

module.exports = class RetryTimer {
  constructor(
    push,
    { backoffs = [BACKOFF_S, BACKOFF_M, BACKOFF_L, BACKOFF_X], jitter = BACKOFF_JITTER } = {}
  ) {
    this.jitter = jitter
    this.backoffs = backoffs

    this._sTimer = new BulkTimer(backoffs[0] + Math.round(jitter * Math.random()), push)
    this._mTimer = new BulkTimer(backoffs[1] + Math.round(jitter * Math.random()), push)
    this._lTimer = new BulkTimer(backoffs[2] + Math.round(jitter * Math.random()), push)
    this._xTimer = new BulkTimer(backoffs[3] + Math.round(jitter * Math.random()), push)
  }

  _selectRetryTimer(peerInfo) {
    if (peerInfo.banned || !peerInfo.reconnecting) return null

    if (peerInfo.attempts > 3) {
      return peerInfo.explicit ? this._xTimer : null
    }

    if (peerInfo.attempts === 0) return this._sTimer
    if (peerInfo.proven) {
      switch (peerInfo.attempts) {
        case 1:
          return this._sTimer
        case 2:
          return this._mTimer
        case 3:
          return this._lTimer
      }
    } else {
      switch (peerInfo.attempts) {
        case 1:
          return this._mTimer
        case 2:
          return this._lTimer
        case 3:
          return this._lTimer
      }
    }

    return null
  }

  add(peerInfo) {
    const timer = this._selectRetryTimer(peerInfo)
    if (!timer) return false

    timer.add(peerInfo)
    return true
  }

  destroy() {
    this._sTimer.destroy()
    this._mTimer.destroy()
    this._lTimer.destroy()
    this._xTimer.destroy()
  }
}
{
  "name": "hyperswarm",
  "version": "4.17.0",
  "description": "A distributed networking stack for connecting peers",
  "files": [
    "index.js",
    "lib/**.js"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    },
    "process": {
      "bare": "bare-process",
      "default": "process"
    }
  },
  "dependencies": {
    "b4a": "^1.3.1",
    "bare-events": "^2.2.0",
    "hyperdht": "^6.21.0",
    "safety-catch": "^1.0.2",
    "shuffled-priority-queue": "^2.1.0",
    "streamx": "^2.22.1",
    "unslab": "^1.3.0"
  },
  "devDependencies": {
    "bare-process": "^4.2.2",
    "brittle": "^3.0.2",
    "hypercore-crypto": "^3.4.0",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "which-runtime": "^1.3.2"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:generate": "brittle -r test/all.js test/*.js",
    "test:node": "brittle-node --coverage test/*.js",
    "test:bare": "bare test/all.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/hyperswarm.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "contributors": [
    "David Mark Clements (@davidmarkclem)",
    "Andrew Osheroff (@andrewosh)"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/hyperswarm/issues"
  },
  "homepage": "https://github.com/holepunchto/hyperswarm"
}
const b4a = require('b4a')

const EMPTY = b4a.alloc(0)
const MAX = b4a.from([0xff])
const BUFFER = {}

BUFFER.preencode = function (state, buf) {
  if (buf === null) buf = EMPTY

  let i = 0
  let extra = 3

  while ((i = b4a.indexOf(buf, 0x00, i)) > -1) {
    i++
    extra++
  }

  state.end += buf.byteLength + extra
}

BUFFER.encode = function (state, buf) {
  if (buf === null) buf = EMPTY

  state.buffer[state.start++] = 0x00

  let prev = 0
  let i = 0

  while ((i = b4a.indexOf(buf, 0x00, i)) > -1) {
    const slice = buf.subarray(prev, ++i)

    state.buffer.set(slice, state.start)
    state.start += slice.byteLength
    state.buffer[state.start++] = 0x02
    prev = i
  }

  const slice = buf.subarray(prev)

  state.buffer.set(slice, state.start)
  state.start += slice.byteLength

  state.buffer[state.start++] = 0x00
  state.buffer[state.start++] = 0x01
}

BUFFER.decode = function (state) {
  if (state.start >= state.end) throw new Error('Out of bounds')
  if (state.buffer[state.start++] !== 0x00) {
    throw new Error('Invalid start of string')
  }

  let escaped = null

  let prev = state.start
  let i = state.start

  while ((i = b4a.indexOf(state.buffer, 0x00, i)) > -1) {
    const next = ++i < state.end ? state.buffer[i] : 0x00

    i++

    if (next === 0x01) {
      break
    }

    if (next === 0x02) {
      if (escaped === null) escaped = []
      escaped.push(state.buffer.subarray(prev, i - 1))
      prev = i
      continue
    }

    throw new Error('Unknown value in terminator')
  }

  if (i === -1) {
    throw new Error('No terminator found')
  }

  state.start = i
  const last = state.buffer.subarray(prev, i - 2)
  if (escaped === null) return last

  escaped.push(last)
  return b4a.concat(escaped)
}

// TODO: can be optimised a lot

const STRING = {}

STRING.preencode = function (state, str) {
  BUFFER.preencode(state, b4a.from(str || ''))
}

STRING.encode = function (state, str) {
  BUFFER.encode(state, b4a.from(str || ''))
}

STRING.decode = function (state, str) {
  return b4a.toString(BUFFER.decode(state))
}

const UINT = {}

UINT.preencode = function (state, n) {
  state.end += n <= 0xfb ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : n === Infinity ? 1 : 9
}

UINT.encode = function (state, n) {
  if (n === Infinity) {
    state.buffer[state.start++] = 0xff
    return
  }

  if (n <= 0xfb) {
    state.buffer[state.start++] = n
    return
  }

  if (n <= 0xffff) {
    state.buffer[state.start++] = 0xfc
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
    return
  }

  if (n <= 0xffffffff) {
    state.buffer[state.start++] = 0xfd
    encodeUint32(state, n)
    return
  }

  if (Number.isSafeInteger(n)) {
    state.buffer[state.start++] = 0xfe

    const r = Math.floor(n / 0x100000000)
    encodeUint32(state, r)
    encodeUint32(state, n)
    return
  }

  throw new Error('Invalid number ' + n)
}

UINT.decode = function (state) {
  if (state.start >= state.end) throw new Error('Out of bounds')

  const a = state.buffer[state.start++]

  if (a <= 0xfb) return a

  if (a === 0xfc) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] * 0x100 + state.buffer[state.start++]
  }

  if (a === 0xfd) {
    return decodeUint32(state)
  }

  if (a === 0xfe) {
    return decodeUint32(state) * 0x100000000 + decodeUint32(state)
  }

  return Infinity
}

const INT = {}

INT.preencode = function (state, n) {
  // One asymmetric condition
  if (n >= -0xff && n < 0) {
    state.end += 2
    return
  }
  n = Math.abs(n)
  state.end += n <= 0xf6 ? 1 : n <= 0xffff ? 3 : n <= 0xffffffff ? 5 : n === Infinity ? 1 : 9
}

INT.encode = function (state, n) {
  if (n === Infinity) {
    state.buffer[state.start++] = 0xff
    return
  }

  if (n === -Infinity) {
    state.buffer[state.start++] = 0x00
    return
  }

  // Negative 64 bit
  if (n < -0xffffffff) {
    if (!Number.isSafeInteger(n)) throw new Error('Invalid number ' + n)
    state.buffer[state.start++] = 0x01

    const r = Math.floor(-n / 0x100000000)
    encodeUint32(state, -r + 0xffffffff)
    encodeUint32(state, -(-n % 0x100000000) + 0xffffffff)
    return
  }

  // Negative 32 bit
  if (n < -0xffff) {
    state.buffer[state.start++] = 0x02

    n += 0xffffffff
    encodeUint32(state, n)
    return
  }

  // Negative 16bit
  if (n < -0xff) {
    state.buffer[state.start++] = 0x03

    n += 0xffff
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
    return
  }

  // Negative 8bit
  if (n < 0) {
    state.buffer[state.start++] = 0x04

    n += 0xff
    state.buffer[state.start++] = n
    return
  }

  // Remainder of 8bit space for positive int
  if (n <= 0xf6) {
    state.buffer[state.start++] = n + 0x05
    return
  }

  // Positive 16bit
  if (n <= 0xffff) {
    state.buffer[state.start++] = 0xfc
    state.buffer[state.start++] = n >>> 8
    state.buffer[state.start++] = n
    return
  }

  // Positive 32bit
  if (n <= 0xffffffff) {
    state.buffer[state.start++] = 0xfd
    encodeUint32(state, n)
    return
  }

  // Positive 64bit
  if (Number.isSafeInteger(n)) {
    state.buffer[state.start++] = 0xfe

    const r = Math.floor(n / 0x100000000)
    encodeUint32(state, r)
    encodeUint32(state, n)
    return
  }

  throw new Error('Invalid number ' + n)
}

INT.decode = function (state) {
  if (state.start >= state.end) throw new Error('Out of bounds')

  const a = state.buffer[state.start++]

  if (a === 0x00) return -Infinity

  if (a === 0x01) {
    // Split (2^64 - 1) into its 32 bit components
    // r * 0x100000000 + n - (2^64 - 1)
    // r * 0x100000000 + n - (0xffffffff * 0x100000000) - 0xffffffff
    // (r - 0xffffffff) * 0x100000000 + n - 0xffffffff
    return (decodeUint32(state) - 0xffffffff) * 0x100000000 + decodeUint32(state) - 0xffffffff
  }

  if (a === 0x02) {
    return decodeUint32(state) - 0xffffffff
  }

  if (a === 0x03) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] * 0x100 + state.buffer[state.start++] - 0xffff
  }

  if (a === 0x04) return state.buffer[state.start++] - 0xff

  if (a <= 0xfb) return a - 0x05

  if (a === 0xfc) {
    if (state.end - state.start < 2) throw new Error('Out of bounds')
    return state.buffer[state.start++] * 0x100 + state.buffer[state.start++]
  }

  if (a === 0xfd) {
    return decodeUint32(state)
  }

  if (a === 0xfe) {
    return decodeUint32(state) * 0x100000000 + decodeUint32(state)
  }

  return Infinity
}

const DATE = {}

DATE.preencode = (state, d) => INT.preencode(state, d.getTime())
DATE.encode = (state, d) => INT.encode(state, d.getTime())
DATE.decode = (state) => new Date(INT.decode(state))

const BOOL = {}

BOOL.preencode = (state, b) => UINT.preencode(state, b ? 1 : 0)
BOOL.encode = (state, b) => UINT.encode(state, b ? 1 : 0)
BOOL.decode = (state) => !!UINT.decode(state)

module.exports = class IndexEncoder {
  constructor(encodings, { prefix = -1 } = {}) {
    this.encodings = encodings
    this.prefix = prefix
  }

  static BUFFER = BUFFER
  static STRING = STRING
  static UINT = UINT
  static INT = INT
  static DATE = DATE
  static BOOL = BOOL

  static lookup(c) {
    switch (c) {
      case 'uint':
        return UINT
      case 'uint8':
        return UINT
      case 'uint16':
        return UINT
      case 'uint24':
        return UINT
      case 'uint32':
        return UINT
      case 'uint40':
        return UINT
      case 'uint48':
        return UINT
      case 'uint56':
        return UINT
      case 'uint64':
        return UINT
      case 'int':
        return INT
      case 'int8':
        return INT
      case 'int16':
        return INT
      case 'int24':
        return INT
      case 'int32':
        return INT
      case 'int40':
        return INT
      case 'int48':
        return INT
      case 'int56':
        return INT
      case 'int64':
        return INT
      case 'string':
        return STRING
      case 'utf8':
        return STRING
      case 'ascii':
        return STRING
      case 'hex':
        return STRING
      case 'base64':
        return STRING
      case 'fixed32':
        return BUFFER
      case 'fixed64':
        return BUFFER
      case 'buffer':
        return BUFFER
      case 'date':
        return DATE
      case 'bool':
        return BOOL
    }

    throw new Error('Unknown type')
  }

  encode(keys) {
    return this._encode(keys, false)
  }

  _encode(keys, terminate) {
    if (b4a.isBuffer(keys)) return keys

    const state = { start: 0, end: 0, buffer: null }

    if (this.prefix !== -1) UINT.preencode(state, this.prefix)
    for (let i = 0; i < keys.length; i++) {
      this.encodings[i].preencode(state, keys[i])
    }

    if (terminate && keys.length < this.encodings.length) {
      state.end++
    }

    state.buffer = b4a.allocUnsafe(state.end)

    if (this.prefix !== -1) UINT.encode(state, this.prefix)
    for (let i = 0; i < keys.length; i++) {
      this.encodings[i].encode(state, keys[i])
    }

    if (terminate && keys.length < this.encodings.length) {
      state.buffer[state.start++] = MAX[0]
    }

    return state.buffer
  }

  decode(buffer) {
    const state = { start: 0, end: buffer.byteLength, buffer }
    const result = []

    if (this.prefix !== -1) UINT.decode(state)
    for (const enc of this.encodings) {
      const key = state.start < state.end ? enc.decode(state) : enc === UINT ? 0 : null
      result.push(key)
    }

    return result
  }

  encodeRange({ gt, gte, lt, lte }) {
    const range = {
      gt: gt && this._encode(gt, true),
      gte: gte && this._encode(gte, false),
      lt: lt && this._encode(lt, false),
      lte: lte && this._encode(lte, true)
    }

    if (this.prefix !== -1) {
      if (!gt && !gte) range.gte = encodeUint(this.prefix)
      if (!lt && !lte) range.lt = encodeUint(this.prefix + 1)
    }

    return range
  }
}

function encodeUint(n) {
  const state = { start: 0, end: 0, buffer: null }
  UINT.preencode(state, n)
  state.buffer = b4a.allocUnsafe(state.end)
  UINT.encode(state, n)
  return state.buffer
}

function encodeUint32(state, n) {
  state.buffer[state.start++] = n >>> 24
  state.buffer[state.start++] = n >>> 16
  state.buffer[state.start++] = n >>> 8
  state.buffer[state.start++] = n
}

function decodeUint32(state) {
  if (state.end - state.start < 4) throw new Error('Out of bounds')
  return (
    state.buffer[state.start++] * 0x1000000 +
    state.buffer[state.start++] * 0x10000 +
    state.buffer[state.start++] * 0x100 +
    state.buffer[state.start++]
  )
}
{
  "name": "index-encoder",
  "version": "3.5.0",
  "description": "Encode multiple values into sorted keys",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.6.4"
  },
  "devDependencies": {
    "brittle": "^3.2.1",
    "hyperbee": "^2.10.5",
    "hypercore": "^11.0.0",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/index-encoder.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/index-encoder/issues"
  },
  "homepage": "https://github.com/holepunchto/index-encoder"
}
const b4a = require('b4a')

module.exports = function isOptions (opts) {
  return typeof opts === 'object' && opts && !b4a.isBuffer(opts)
}
{
  "name": "is-options",
  "version": "1.0.2",
  "description": "Easily check if input is an options map",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.1.1"
  },
  "devDependencies": {
    "standard": "^11.0.1",
    "tape": "^4.9.0"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/is-options.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/is-options/issues"
  },
  "homepage": "https://github.com/mafintosh/is-options"
}
const { EventEmitter } = require('events')

module.exports = class RoutingTable extends EventEmitter {
  constructor (id, opts) {
    if (!opts) opts = {}

    super()

    this.id = id
    this.k = opts.k || 20
    this.size = 0
    this.rows = new Array(id.length * 8)
  }

  add (node) {
    const i = this._diff(node.id)

    let row = this.rows[i]

    if (!row) {
      row = this.rows[i] = new Row(this, i)
      this.emit('row', row)
    }

    const len = row.nodes.length
    if (!row.add(node, this.k)) return false

    this.size += row.nodes.length - len
    return true
  }

  remove (id) {
    const i = this._diff(id)
    const row = this.rows[i]
    if (!row) return false
    if (!row.remove(id)) return false
    this.size--
    return true
  }

  get (id) {
    const i = this._diff(id)
    const row = this.rows[i]
    if (!row) return null
    return row.get(id)
  }

  has (id) {
    return this.get(id) !== null
  }

  random () {
    let n = (Math.random() * this.size) | 0

    for (let i = 0; i < this.rows.length; i++) {
      const r = this.rows[i]
      if (!r) continue
      if (n < r.nodes.length) return r.nodes[n]
      n -= r.nodes.length
    }

    return null
  }

  closest (id, k) {
    if (!k) k = this.k

    const result = []
    const d = this._diff(id)

    // push close nodes
    for (let i = d; i >= 0 && result.length < k; i--) this._pushNodes(i, k, result)

    // if we don't have enough close nodes, populate from other rows, re the paper
    for (let i = d + 1; i < this.rows.length && result.length < k; i++) this._pushNodes(i, k, result)

    return result
  }

  _pushNodes (i, k, result) {
    const row = this.rows[i]
    if (!row) return

    const missing = Math.min(k - result.length, row.nodes.length)
    for (let j = 0; j < missing; j++) result.push(row.nodes[j])
  }

  toArray () {
    return this.closest(this.id, Infinity)
  }

  _diff (id) {
    for (let i = 0; i < id.length; i++) {
      const a = id[i]
      const b = this.id[i]

      if (a !== b) return i * 8 + Math.clz32(a ^ b) - 24
    }

    return this.rows.length - 1
  }
}

class Row extends EventEmitter {
  constructor (table, index) {
    super()

    this.data = null // can be used be upstream for whatevs
    this.byteOffset = index >> 3
    this.index = index
    this.table = table
    this.nodes = []
  }

  add (node) {
    const id = node.id

    let l = 0
    let r = this.nodes.length - 1

    while (l <= r) {
      const m = (l + r) >> 1
      const c = this.compare(id, this.nodes[m].id)

      if (c === 0) {
        this.nodes[m] = node
        return true
      }

      if (c < 0) r = m - 1
      else l = m + 1
    }

    if (this.nodes.length >= this.table.k) {
      this.emit('full', node)
      return false
    }

    this.insert(l, node)
    return true
  }

  remove (id) {
    let l = 0
    let r = this.nodes.length - 1

    while (l <= r) {
      const m = (l + r) >> 1
      const c = this.compare(id, this.nodes[m].id)

      if (c === 0) {
        this.splice(m)
        return true
      }

      if (c < 0) r = m - 1
      else l = m + 1
    }

    return false
  }

  get (id) {
    let l = 0
    let r = this.nodes.length - 1

    while (l <= r) {
      const m = (l + r) >> 1
      const node = this.nodes[m]
      const c = this.compare(id, node.id)

      if (c === 0) return node
      if (c < 0) r = m - 1
      else l = m + 1
    }

    return null
  }

  insert (i, node) {
    this.nodes.push(node) // push node or null or whatevs, just trying to not be polymorphic
    for (let j = this.nodes.length - 1; j > i; j--) this.nodes[j] = this.nodes[j - 1]
    this.nodes[i] = node
    this.emit('add', node)
  }

  splice (i) {
    for (; i < this.nodes.length - 1; i++) this.nodes[i] = this.nodes[i + 1]
    this.emit('remove', this.nodes.pop())
  }

  // very likely they diverge after a couple of bytes so a simple impl, like this is prop fastest vs Buffer.compare
  compare (a, b) {
    for (let i = this.byteOffset; i < a.length; i++) {
      const ai = a[i]
      const bi = b[i]
      if (ai === bi) continue
      return ai < bi ? -1 : 1
    }
    return 0
  }
}
{
  "name": "kademlia-routing-table",
  "version": "1.0.6",
  "description": "XOR based routing table used for P2P networks such as a Kademlia DHT.",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "dependencies": {
    "bare-events": "^2.2.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "standard": "^17.1.0"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "keywords": [
    "kademlia",
    "p2p",
    "k-bucket",
    "k-buckets",
    "xor",
    "routing",
    "distributed",
    "systems"
  ],
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/kademlia-routing-table.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/kademlia-routing-table/issues"
  },
  "homepage": "https://github.com/mafintosh/kademlia-routing-table"
}
var queueTick = require('queue-tick')

var mutexify = function () {
  var queue = []
  var used = null

  var call = function () {
    used(release)
  }

  var acquire = function (fn) {
    if (used) return queue.push(fn)
    used = fn
    acquire.locked = true
    queueTick(call)
    return 0
  }

  acquire.locked = false

  var release = function (fn, err, value) {
    used = null
    acquire.locked = false
    if (queue.length) acquire(queue.shift())
    if (fn) fn(err, value)
  }

  return acquire
}

module.exports = mutexify
{
  "name": "mutexify",
  "version": "1.4.0",
  "description": "mutex lock for javascript",
  "main": "index.js",
  "dependencies": {
    "queue-tick": "^1.0.0"
  },
  "devDependencies": {
    "standard": "^14.3.3",
    "tape": "^3.0.2"
  },
  "scripts": {
    "test": "tape test.js",
    "posttest": "npm run lint",
    "lint": "standard"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/mutexify.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/mutexify/issues"
  },
  "keywords": [
    "mutex",
    "lock"
  ],
  "homepage": "https://github.com/mafintosh/mutexify"
}
var mutexify = require('.')

var mutexifyPromise = function () {
  var lock = mutexify()

  var acquire = function () {
    return new Promise(lock)
  }

  Object.defineProperty(acquire, 'locked', {
    get: function () { return lock.locked },
    enumerable: true
  })

  return acquire
}

module.exports = mutexifyPromise
module.exports = assert

class AssertionError extends Error {}
AssertionError.prototype.name = 'AssertionError'

/**
 * Minimal assert function
 * @param  {any} t Value to check if falsy
 * @param  {string=} m Optional assertion error message
 * @throws {AssertionError}
 */
function assert (t, m) {
  if (!t) {
    var err = new AssertionError(m)
    if (Error.captureStackTrace) Error.captureStackTrace(err, assert)
    throw err
  }
}
{
  "name": "nanoassert",
  "version": "2.0.0",
  "description": "Nanoscale assertion module",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "tape": "^4.9.1"
  },
  "scripts": {
    "test": "tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/emilbayes/nanoassert.git"
  },
  "keywords": [
    "assert",
    "unassert",
    "power-assert",
    "tiny",
    "nano",
    "pico"
  ],
  "author": "Emil Bay <github@tixz.dk>",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/emilbayes/nanoassert/issues"
  },
  "homepage": "https://github.com/emilbayes/nanoassert#readme"
}
module.exports = class NatSampler {
  constructor () {
    this.host = null
    this.port = 0
    this.size = 0

    this._a = null
    this._b = null
    this._threshold = 0
    this._top = 0
    this._samples = []
  }

  add (host, port) {
    const a = this._bump(host, port, 2)
    const b = this._bump(host, 0, 1)

    if (this._samples.length < 32) {
      this.size++
      this._threshold = this.size - (this.size < 4 ? 0 : this.size < 8 ? 1 : this.size < 12 ? 2 : 3)
      this._samples.push(a, b)
      this._top += 2
    } else {
      if (this._top === 32) this._top = 0

      const oa = this._samples[this._top]
      this._samples[this._top++] = a
      oa.hits--

      const ob = this._samples[this._top]
      this._samples[this._top++] = b
      ob.hits--
    }

    if (this._a === null || this._a.hits < a.hits) this._a = a
    if (this._b === null || this._b.hits < b.hits) this._b = b

    if (this._a.hits >= this._threshold) {
      this.host = this._a.host
      this.port = this._a.port
    } else if (this._b.hits >= this._threshold) {
      this.host = this._b.host
      this.port = 0
    } else {
      this.host = null
      this.port = 0
    }

    return a.hits
  }

  _bump (host, port, inc) {
    for (let i = 0; i < 4; i++) {
      const j = (this._top - inc - (2 * i)) & 31
      if (j >= this._samples.length) return { host, port, hits: 1 }
      const s = this._samples[j]
      if (s.port === port && s.host === host) {
        s.hits++
        return s
      }
    }
    return { host, port, hits: 1 }
  }
}
{
  "name": "nat-sampler",
  "version": "1.0.1",
  "description": "Sample addresses to figure out if a host + port is consistent",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^16.0.3",
    "tape": "^5.2.2"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/nat-sampler.git"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/nat-sampler/issues"
  },
  "homepage": "https://github.com/mafintosh/nat-sampler"
}
/* eslint-disable camelcase */
const sodium = require('sodium-universal')
const assert = require('nanoassert')
const b4a = require('b4a')

const DHLEN = sodium.crypto_scalarmult_ed25519_BYTES
const PKLEN = sodium.crypto_scalarmult_ed25519_BYTES
const SCALARLEN = sodium.crypto_scalarmult_ed25519_BYTES
const SKLEN = sodium.crypto_sign_SECRETKEYBYTES
const ALG = 'Ed25519'

module.exports = {
  DHLEN,
  PKLEN,
  SCALARLEN,
  SKLEN,
  ALG,
  name: ALG,
  generateKeyPair,
  dh
}

function generateKeyPair (privKey) {
  if (privKey) return generateSeedKeyPair(privKey.subarray(0, 32))

  const keyPair = {}
  keyPair.secretKey = b4a.alloc(SKLEN)
  keyPair.publicKey = b4a.alloc(PKLEN)

  sodium.crypto_sign_keypair(keyPair.publicKey, keyPair.secretKey)
  return keyPair
}

function generateSeedKeyPair (seed) {
  const keyPair = {}
  keyPair.secretKey = b4a.alloc(SKLEN)
  keyPair.publicKey = b4a.alloc(PKLEN)

  sodium.crypto_sign_seed_keypair(keyPair.publicKey, keyPair.secretKey, seed)
  return keyPair
}

function dh (publicKey, { scalar, secretKey }) {
  // tweaked keys expose scalar directly
  if (!scalar) {
    assert(secretKey.byteLength === SKLEN)

    // libsodium stores seed not actual scalar
    const sk = b4a.alloc(64)
    sodium.crypto_hash_sha512(sk, secretKey.subarray(0, 32))
    sk[0] &= 248
    sk[31] &= 127
    sk[31] |= 64

    scalar = sk.subarray(0, 32)
  }

  assert(scalar.byteLength === SCALARLEN)
  assert(publicKey.byteLength === PKLEN)

  const output = b4a.alloc(DHLEN)

  // we clamp if necessary above
  sodium.crypto_scalarmult_ed25519_noclamp(
    output,
    scalar,
    publicKey
  )

  return output
}
{
  "name": "noise-curve-ed",
  "version": "2.1.0",
  "description": "Ed25519 elliptic curve operations for [`noise-handshake`](https://github.com/chm-diederichs/noise-handshake)",
  "main": "index.js",
  "scripts": {
    "test": "npx standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/chm-diederichs/noise-curve-ed.git"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/chm-diederichs/noise-curve-ed/issues"
  },
  "homepage": "https://github.com/chm-diederichs/noise-curve-ed#readme",
  "dependencies": {
    "b4a": "^1.1.0",
    "nanoassert": "^2.0.0",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "noise-handshake": "^3.0.0",
    "standard": "^16.0.3",
    "tape": "^5.2.2"
  }
}
const sodium = require('sodium-universal')
const b4a = require('b4a')

module.exports = class CipherState {
  constructor (key) {
    this.key = key || null
    this.nonce = 0
    this.CIPHER_ALG = 'ChaChaPoly'
  }

  initialiseKey (key) {
    this.key = key
    this.nonce = 0
  }

  setNonce (nonce) {
    this.nonce = nonce
  }

  encrypt (plaintext, ad) {
    if (!this.hasKey) return plaintext
    if (!ad) ad = b4a.alloc(0)

    const ciphertext = encryptWithAD(this.key, this.nonce, ad, plaintext)
    if (ciphertext.length > 65535) throw new Error(`ciphertext length of ${ciphertext.length} exceeds maximum Noise message length of 65535`)
    this.nonce++

    return ciphertext
  }

  decrypt (ciphertext, ad) {
    if (!this.hasKey) return ciphertext
    if (!ad) ad = b4a.alloc(0)
    if (ciphertext.length > 65535) throw new Error(`ciphertext length of ${ciphertext.length} exceeds maximum Noise message length of 65535`)

    const plaintext = decryptWithAD(this.key, this.nonce, ad, ciphertext)
    this.nonce++

    return plaintext
  }

  get hasKey () {
    return this.key !== null
  }

  _clear () {
    sodium.sodium_memzero(this.key)
    this.key = null
    this.nonce = null
  }

  static get MACBYTES () {
    return 16
  }

  static get NONCEBYTES () {
    return 8
  }

  static get KEYBYTES () {
    return 32
  }
}

function encryptWithAD (key, counter, additionalData, plaintext) {
  // for our purposes, additionalData will always be a pubkey so we encode from hex
  if (!b4a.isBuffer(additionalData)) additionalData = b4a.from(additionalData, 'hex')
  if (!b4a.isBuffer(plaintext)) plaintext = b4a.from(plaintext, 'hex')

  const nonce = b4a.alloc(sodium.crypto_aead_chacha20poly1305_ietf_NPUBBYTES)
  const view = new DataView(nonce.buffer, nonce.byteOffset, nonce.byteLength)
  view.setUint32(4, counter, true)

  const ciphertext = b4a.alloc(plaintext.byteLength + sodium.crypto_aead_chacha20poly1305_ietf_ABYTES)

  sodium.crypto_aead_chacha20poly1305_ietf_encrypt(ciphertext, plaintext, additionalData, null, nonce, key)
  return ciphertext
}

function decryptWithAD (key, counter, additionalData, ciphertext) {
  // for our purposes, additionalData will always be a pubkey so we encode from hex
  if (!b4a.isBuffer(additionalData)) additionalData = b4a.from(additionalData, 'hex')
  if (!b4a.isBuffer(ciphertext)) ciphertext = b4a.from(ciphertext, 'hex')

  const nonce = b4a.alloc(sodium.crypto_aead_chacha20poly1305_ietf_NPUBBYTES)
  const view = new DataView(nonce.buffer, nonce.byteOffset, nonce.byteLength)
  view.setUint32(4, counter, true)

  const plaintext = b4a.alloc(ciphertext.byteLength - sodium.crypto_aead_chacha20poly1305_ietf_ABYTES)

  sodium.crypto_aead_chacha20poly1305_ietf_decrypt(plaintext, null, ciphertext, additionalData, nonce, key)
  return plaintext
}
/* eslint-disable camelcase */
const {
  crypto_kx_SEEDBYTES,
  crypto_kx_keypair,
  crypto_kx_seed_keypair,
  crypto_scalarmult_BYTES,
  crypto_scalarmult_SCALARBYTES,
  crypto_scalarmult,
  crypto_scalarmult_base
} = require('sodium-universal')

const assert = require('nanoassert')
const b4a = require('b4a')

const DHLEN = crypto_scalarmult_BYTES
const PKLEN = crypto_scalarmult_BYTES
const SKLEN = crypto_scalarmult_SCALARBYTES
const SEEDLEN = crypto_kx_SEEDBYTES
const ALG = '25519'

module.exports = {
  DHLEN,
  PKLEN,
  SKLEN,
  SEEDLEN,
  ALG,
  generateKeyPair,
  generateSeedKeyPair,
  dh
}

function generateKeyPair (privKey) {
  const keyPair = {}

  keyPair.secretKey = privKey || b4a.alloc(SKLEN)
  keyPair.publicKey = b4a.alloc(PKLEN)

  if (privKey) {
    crypto_scalarmult_base(keyPair.publicKey, keyPair.secretKey)
  } else {
    crypto_kx_keypair(keyPair.publicKey, keyPair.secretKey)
  }

  return keyPair
}

function generateSeedKeyPair (seed) {
  assert(seed.byteLength === SKLEN)

  const keyPair = {}
  keyPair.secretKey = b4a.alloc(SKLEN)
  keyPair.publicKey = b4a.alloc(PKLEN)

  crypto_kx_seed_keypair(keyPair.publicKey, keyPair.secretKey, seed)
  return keyPair
}

function dh (publicKey, { secretKey }) {
  assert(secretKey.byteLength === SKLEN)
  assert(publicKey.byteLength === PKLEN)

  const output = b4a.alloc(DHLEN)

  crypto_scalarmult(
    output,
    secretKey,
    publicKey
  )

  return output
}
const hmacBlake2b = require('./hmac')
const b4a = require('b4a')

const HASHLEN = 64

module.exports = {
  hkdf,
  HASHLEN
}

// HMAC-based Extract-and-Expand KDF
// https://www.ietf.org/rfc/rfc5869.txt

function hkdf (salt, inputKeyMaterial, info = '', length = 2 * HASHLEN) {
  const pseudoRandomKey = hkdfExtract(salt, inputKeyMaterial)
  return hkdfExpand(pseudoRandomKey, info, length)
}

function hkdfExtract (salt, inputKeyMaterial) {
  const hmac = b4a.alloc(HASHLEN)
  return hmacDigest(hmac, salt, inputKeyMaterial)
}

function hkdfExpand (key, info, length) {
  // Put in dedicated slab to avoid keeping shared slab from being gc'ed
  const buffer = b4a.allocUnsafeSlow(length)

  const infoBuf = b4a.from(info)
  let prev = infoBuf

  const result = []
  for (let i = 0; i < length; i += HASHLEN) {
    const pos = b4a.from([(i / HASHLEN) + 1])

    const out = buffer.subarray(i, i + HASHLEN)
    result.push(out)

    prev = hmacDigest(out, key, [prev, infoBuf, pos])
  }

  return result
}

function hmacDigest (out, key, input) {
  hmacBlake2b(out, input, key)
  return out
}
/* eslint-disable camelcase */
const b4a = require('b4a')
const { sodium_memzero, crypto_generichash, crypto_generichash_batch } = require('sodium-universal')

const HASHLEN = 64
const BLOCKLEN = 128
const scratch = b4a.alloc(BLOCKLEN * 3)
const HMACKey = scratch.subarray(BLOCKLEN * 0, BLOCKLEN * 1)
const OuterKeyPad = scratch.subarray(BLOCKLEN * 1, BLOCKLEN * 2)
const InnerKeyPad = scratch.subarray(BLOCKLEN * 2, BLOCKLEN * 3)

// Post-fill is done in the cases where someone caught an exception that
// happened before we were able to clear data at the end

module.exports = function hmac (out, batch, key) {
  if (key.byteLength > BLOCKLEN) {
    crypto_generichash(HMACKey.subarray(0, HASHLEN), key)
    sodium_memzero(HMACKey.subarray(HASHLEN))
  } else {
    // Covers key <= BLOCKLEN
    HMACKey.set(key)
    sodium_memzero(HMACKey.subarray(key.byteLength))
  }

  for (let i = 0; i < HMACKey.byteLength; i++) {
    OuterKeyPad[i] = 0x5c ^ HMACKey[i]
    InnerKeyPad[i] = 0x36 ^ HMACKey[i]
  }
  sodium_memzero(HMACKey)

  crypto_generichash_batch(out, [InnerKeyPad].concat(batch))
  sodium_memzero(InnerKeyPad)
  crypto_generichash_batch(out, [OuterKeyPad, out])
  sodium_memzero(OuterKeyPad)
}

module.exports.BYTES = HASHLEN
module.exports.KEYBYTES = BLOCKLEN
const assert = require('nanoassert')
const b4a = require('b4a')

const SymmetricState = require('./symmetric-state')
const { HASHLEN } = require('./hkdf')

const PRESHARE_IS = Symbol('initiator static key preshared')
const PRESHARE_RS = Symbol('responder static key preshared')

const TOK_PSK = Symbol('psk')

const TOK_S = Symbol('s')
const TOK_E = Symbol('e')

const TOK_ES = Symbol('es')
const TOK_SE = Symbol('se')
const TOK_EE = Symbol('ee')
const TOK_SS = Symbol('ss')

const HANDSHAKES = Object.freeze({
  NN: [
    [TOK_E],
    [TOK_E, TOK_EE]
  ],
  NNpsk0: [
    [TOK_PSK, TOK_E],
    [TOK_E, TOK_EE]
  ],
  XX: [
    [TOK_E],
    [TOK_E, TOK_EE, TOK_S, TOK_ES],
    [TOK_S, TOK_SE]
  ],
  XXpsk0: [
    [TOK_PSK, TOK_E],
    [TOK_E, TOK_EE, TOK_S, TOK_ES],
    [TOK_S, TOK_SE]
  ],
  IK: [
    PRESHARE_RS,
    [TOK_E, TOK_ES, TOK_S, TOK_SS],
    [TOK_E, TOK_EE, TOK_SE]
  ],
  XK: [
    PRESHARE_RS,
    [TOK_E, TOK_ES],
    [TOK_E, TOK_EE],
    [TOK_S, TOK_SE]
  ]
})

class Writer {
  constructor () {
    this.size = 0
    this.buffers = []
  }

  push (b) {
    this.size += b.byteLength
    this.buffers.push(b)
  }

  end () {
    const all = b4a.alloc(this.size)
    let offset = 0
    for (const b of this.buffers) {
      all.set(b, offset)
      offset += b.byteLength
    }
    return all
  }
}

class Reader {
  constructor (buf) {
    this.offset = 0
    this.buffer = buf
  }

  shift (n) {
    const start = this.offset
    const end = this.offset += n
    if (end > this.buffer.byteLength) throw new Error('Insufficient bytes')
    return this.buffer.subarray(start, end)
  }

  end () {
    return this.shift(this.buffer.byteLength - this.offset)
  }
}

module.exports = class NoiseState extends SymmetricState {
  constructor (pattern, initiator, staticKeypair, opts = {}) {
    super(opts)

    this.s = staticKeypair || this.curve.generateKeyPair()
    this.e = null

    this.psk = null
    if (opts && opts.psk) this.psk = opts.psk

    this.re = null
    this.rs = null

    this.pattern = pattern
    this.handshake = HANDSHAKES[this.pattern].slice()

    this.isPskHandshake = !!this.psk && hasPskToken(this.handshake)

    this.protocol = b4a.from([
      'Noise',
      this.pattern,
      this.DH_ALG,
      this.CIPHER_ALG,
      'BLAKE2b'
    ].join('_'))

    this.initiator = initiator
    this.complete = false

    this.rx = null
    this.tx = null
    this.hash = null
  }

  initialise (prologue, remoteStatic) {
    if (this.protocol.byteLength <= HASHLEN) this.digest.set(this.protocol)
    else this.mixHash(this.protocol)

    this.chainingKey = b4a.from(this.digest)

    this.mixHash(prologue)

    while (!Array.isArray(this.handshake[0])) {
      const message = this.handshake.shift()

      // handshake steps should be as arrays, only
      // preshare tokens are provided otherwise
      assert(message === PRESHARE_RS || message === PRESHARE_IS,
        'Unexpected pattern')

      const takeRemoteKey = this.initiator
        ? message === PRESHARE_RS
        : message === PRESHARE_IS

      if (takeRemoteKey) this.rs = remoteStatic

      const key = takeRemoteKey ? this.rs : this.s.publicKey
      assert(key != null, 'Remote pubkey required')

      this.mixHash(key)
    }
  }

  final () {
    const [k1, k2] = this.split()

    this.tx = this.initiator ? k1 : k2
    this.rx = this.initiator ? k2 : k1

    this.complete = true
    this.hash = this.getHandshakeHash()

    this._clear()
  }

  recv (buf) {
    const r = new Reader(buf)

    for (const pattern of this.handshake.shift()) {
      switch (pattern) {
        case TOK_PSK :
          this.mixKeyAndHash(this.psk)
          break

        case TOK_E :
          this.re = r.shift(this.curve.PKLEN)
          this.mixHash(this.re)
          if (this.isPskHandshake) this.mixKeyNormal(this.re)
          break

        case TOK_S : {
          const klen = this.hasKey ? this.curve.PKLEN + 16 : this.curve.PKLEN
          this.rs = this.decryptAndHash(r.shift(klen))
          break
        }

        case TOK_EE :
        case TOK_ES :
        case TOK_SE :
        case TOK_SS : {
          const useStatic = keyPattern(pattern, this.initiator)

          const localKey = useStatic.local ? this.s : this.e
          const remoteKey = useStatic.remote ? this.rs : this.re

          this.mixKey(remoteKey, localKey)
          break
        }

        default :
          throw new Error('Unexpected message')
      }
    }

    const payload = this.decryptAndHash(r.end())

    if (!this.handshake.length) this.final()
    return payload
  }

  send (payload = b4a.alloc(0)) {
    const w = new Writer()

    for (const pattern of this.handshake.shift()) {
      switch (pattern) {
        case TOK_PSK :
          this.mixKeyAndHash(this.psk)
          break

        case TOK_E :
          if (this.e === null) this.e = this.curve.generateKeyPair()
          this.mixHash(this.e.publicKey)
          if (this.isPskHandshake) this.mixKeyNormal(this.e.publicKey)
          w.push(this.e.publicKey)
          break

        case TOK_S :
          w.push(this.encryptAndHash(this.s.publicKey))
          break

        case TOK_ES :
        case TOK_SE :
        case TOK_EE :
        case TOK_SS : {
          const useStatic = keyPattern(pattern, this.initiator)

          const localKey = useStatic.local ? this.s : this.e
          const remoteKey = useStatic.remote ? this.rs : this.re

          this.mixKey(remoteKey, localKey)
          break
        }

        default :
          throw new Error('Unexpected message')
      }
    }

    w.push(this.encryptAndHash(payload))
    const response = w.end()

    if (!this.handshake.length) this.final()
    return response
  }

  _clear () {
    super._clear()

    this.e.secretKey.fill(0)
    this.e.publicKey.fill(0)

    this.re.fill(0)

    this.e = null
    this.re = null
  }
}

function keyPattern (pattern, initiator) {
  const ret = {
    local: false,
    remote: false
  }

  switch (pattern) {
    case TOK_EE:
      return ret

    case TOK_ES:
      ret.local ^= !initiator
      ret.remote ^= initiator
      return ret

    case TOK_SE:
      ret.local ^= initiator
      ret.remote ^= !initiator
      return ret

    case TOK_SS:
      ret.local ^= 1
      ret.remote ^= 1
      return ret
  }
}

function hasPskToken (handshake) {
  return handshake.some(x => {
    return Array.isArray(x) && x.indexOf(TOK_PSK) !== -1
  })
}
{
  "name": "noise-handshake",
  "version": "4.2.0",
  "description": "Noise protocol handshake",
  "main": "noise.js",
  "files": [
    "*.js"
  ],
  "scripts": {
    "test": "standard && brittle test/*.js"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/noise-handshake.git"
  },
  "dependencies": {
    "b4a": "^1.1.0",
    "nanoassert": "^2.0.0",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "noise-protocol": "chm-diederichs/noise-protocol.git#xx-ephemeral-key",
    "standard": "^16.0.3"
  }
}
const sodium = require('sodium-universal')
const assert = require('nanoassert')
const b4a = require('b4a')
const CipherState = require('./cipher')
const curve = require('./dh')
const { HASHLEN, hkdf } = require('./hkdf')

module.exports = class SymmetricState extends CipherState {
  constructor (opts = {}) {
    super()

    this.curve = opts.curve || curve
    this.digest = b4a.alloc(HASHLEN)
    this.chainingKey = null
    this.offset = 0

    this.DH_ALG = this.curve.ALG
  }

  mixHash (data) {
    accumulateDigest(this.digest, data)
  }

  mixKeyAndHash (key) {
    const [ck, tempH, tempK] = hkdf(this.chainingKey, key, '', 3 * HASHLEN)
    this.chainingKey = ck
    this.mixHash(tempH)
    this.initialiseKey(tempK.subarray(0, 32))
  }

  mixKeyNormal (key) {
    const [ck, tempK] = hkdf(this.chainingKey, key)
    this.chainingKey = ck
    this.initialiseKey(tempK.subarray(0, 32))
  }

  mixKey (remoteKey, localKey) {
    const dh = this.curve.dh(remoteKey, localKey)
    const hkdfResult = hkdf(this.chainingKey, dh)
    this.chainingKey = hkdfResult[0]
    this.initialiseKey(hkdfResult[1].subarray(0, 32))
  }

  encryptAndHash (plaintext) {
    const ciphertext = this.encrypt(plaintext, this.digest)
    accumulateDigest(this.digest, ciphertext)
    return ciphertext
  }

  decryptAndHash (ciphertext) {
    const plaintext = this.decrypt(ciphertext, this.digest)
    accumulateDigest(this.digest, ciphertext)
    return plaintext
  }

  getHandshakeHash (out) {
    if (!out) return this.getHandshakeHash(b4a.alloc(HASHLEN))
    assert(out.byteLength === HASHLEN, `output must be ${HASHLEN} bytes`)

    out.set(this.digest)
    return out
  }

  split () {
    const res = hkdf(this.chainingKey, b4a.alloc(0))
    return res.map(k => k.subarray(0, 32))
  }

  _clear () {
    super._clear()

    sodium.sodium_memzero(this.digest)
    sodium.sodium_memzero(this.chainingKey)

    this.digest = null
    this.chainingKey = null
    this.offset = null

    this.curve = null
  }

  static get alg () {
    return CipherState.alg + '_BLAKE2b'
  }
}

function accumulateDigest (digest, input) {
  const toHash = b4a.concat([digest, input])
  sodium.crypto_generichash(digest, toHash)
}
var varint = require('varint')
var svarint = require('signed-varint')
var b4a = require('b4a')

exports.make = encoder

exports.name = function (enc) {
  var keys = Object.keys(exports)
  for (var i = 0; i < keys.length; i++) {
    if (exports[keys[i]] === enc) return keys[i]
  }
  return null
}

exports.skip = function (type, buffer, offset) {
  switch (type) {
    case 0:
      varint.decode(buffer, offset)
      return offset + varint.decode.bytes

    case 1:
      return offset + 8

    case 2:
      var len = varint.decode(buffer, offset)
      return offset + varint.decode.bytes + len

    case 3:
    case 4:
      throw new Error('Groups are not supported')

    case 5:
      return offset + 4
  }

  throw new Error('Unknown wire type: ' + type)
}

exports.bytes = encoder(2,
  function encode (val, buffer, offset) {
    var oldOffset = offset
    var len = bufferLength(val)

    varint.encode(len, buffer, offset)
    offset += varint.encode.bytes

    if (b4a.isBuffer(val)) b4a.copy(val, buffer, offset)
    else b4a.write(buffer, val, offset, len)
    offset += len

    encode.bytes = offset - oldOffset
    return buffer
  },
  function decode (buffer, offset) {
    var oldOffset = offset

    var len = varint.decode(buffer, offset)
    offset += varint.decode.bytes

    var val = buffer.subarray(offset, offset + len)
    offset += val.length

    decode.bytes = offset - oldOffset
    return val
  },
  function encodingLength (val) {
    var len = bufferLength(val)
    return varint.encodingLength(len) + len
  }
)

exports.string = encoder(2,
  function encode (val, buffer, offset) {
    var oldOffset = offset
    var len = b4a.byteLength(val)

    varint.encode(len, buffer, offset, 'utf-8')
    offset += varint.encode.bytes

    b4a.write(buffer, val, offset, len)
    offset += len

    encode.bytes = offset - oldOffset
    return buffer
  },
  function decode (buffer, offset) {
    var oldOffset = offset

    var len = varint.decode(buffer, offset)
    offset += varint.decode.bytes

    var val = b4a.toString(buffer, 'utf-8', offset, offset + len)
    offset += len

    decode.bytes = offset - oldOffset
    return val
  },
  function encodingLength (val) {
    var len = b4a.byteLength(val)
    return varint.encodingLength(len) + len
  }
)

exports.bool = encoder(0,
  function encode (val, buffer, offset) {
    buffer[offset] = val ? 1 : 0
    encode.bytes = 1
    return buffer
  },
  function decode (buffer, offset) {
    var bool = buffer[offset] > 0
    decode.bytes = 1
    return bool
  },
  function encodingLength () {
    return 1
  }
)

exports.int32 = encoder(0,
  function encode (val, buffer, offset) {
    varint.encode(val < 0 ? val + 4294967296 : val, buffer, offset)
    encode.bytes = varint.encode.bytes
    return buffer
  },
  function decode (buffer, offset) {
    var val = varint.decode(buffer, offset)
    decode.bytes = varint.decode.bytes
    return val > 2147483647 ? val - 4294967296 : val
  },
  function encodingLength (val) {
    return varint.encodingLength(val < 0 ? val + 4294967296 : val)
  }
)

exports.int64 = encoder(0,
  function encode (val, buffer, offset) {
    if (val < 0) {
      var last = offset + 9
      varint.encode(val * -1, buffer, offset)
      offset += varint.encode.bytes - 1
      buffer[offset] = buffer[offset] | 0x80
      while (offset < last - 1) {
        offset++
        buffer[offset] = 0xff
      }
      buffer[last] = 0x01
      encode.bytes = 10
    } else {
      varint.encode(val, buffer, offset)
      encode.bytes = varint.encode.bytes
    }
    return buffer
  },
  function decode (buffer, offset) {
    var val = varint.decode(buffer, offset)
    if (val >= Math.pow(2, 63)) {
      var limit = 9
      while (buffer[offset + limit - 1] === 0xff) limit--
      limit = limit || 9
      var subset = b4a.allocUnsafe(limit)
      b4a.copy(buffer, subset, 0, offset, offset + limit)
      subset[limit - 1] = subset[limit - 1] & 0x7f
      val = -1 * varint.decode(subset, 0)
      decode.bytes = 10
    } else {
      decode.bytes = varint.decode.bytes
    }
    return val
  },
  function encodingLength (val) {
    return val < 0 ? 10 : varint.encodingLength(val)
  }
)

exports.sint32 =
exports.sint64 = encoder(0,
  svarint.encode,
  svarint.decode,
  svarint.encodingLength
)

exports.uint32 =
exports.uint64 =
exports.enum =
exports.varint = encoder(0,
  varint.encode,
  varint.decode,
  varint.encodingLength
)

// we cannot represent these in javascript so we just use buffers
exports.fixed64 =
exports.sfixed64 = encoder(1,
  function encode (val, buffer, offset) {
    b4a.copy(val, buffer, offset)
    encode.bytes = 8
    return buffer
  },
  function decode (buffer, offset) {
    var val = buffer.subarray(offset, offset + 8)
    decode.bytes = 8
    return val
  },
  function encodingLength () {
    return 8
  }
)

exports.double = encoder(1,
  function encode (val, buffer, offset) {
    b4a.writeDoubleLE(buffer, val, offset)
    encode.bytes = 8
    return buffer
  },
  function decode (buffer, offset) {
    var val = b4a.readDoubleLE(buffer, offset)
    decode.bytes = 8
    return val
  },
  function encodingLength () {
    return 8
  }
)

exports.fixed32 = encoder(5,
  function encode (val, buffer, offset) {
    b4a.writeUInt32LE(buffer, val, offset)
    encode.bytes = 4
    return buffer
  },
  function decode (buffer, offset) {
    var val = b4a.readUInt32LE(buffer, offset)
    decode.bytes = 4
    return val
  },
  function encodingLength () {
    return 4
  }
)

exports.sfixed32 = encoder(5,
  function encode (val, buffer, offset) {
    b4a.writeInt32LE(buffer, val, offset)
    encode.bytes = 4
    return buffer
  },
  function decode (buffer, offset) {
    var val = b4a.readInt32LE(buffer, offset)
    decode.bytes = 4
    return val
  },
  function encodingLength () {
    return 4
  }
)

exports.float = encoder(5,
  function encode (val, buffer, offset) {
    b4a.writeFloatLE(buffer, val, offset)
    encode.bytes = 4
    return buffer
  },
  function decode (buffer, offset) {
    var val = b4a.readFloatLE(buffer, offset)
    decode.bytes = 4
    return val
  },
  function encodingLength () {
    return 4
  }
)

function encoder (type, encode, decode, encodingLength) {
  encode.bytes = decode.bytes = 0

  return {
    type: type,
    encode: encode,
    decode: decode,
    encodingLength: encodingLength
  }
}

function bufferLength (val) {
  return b4a.isBuffer(val) ? val.length : b4a.byteLength(val)
}
{
  "name": "protocol-buffers-encodings",
  "version": "1.2.0",
  "description": "Base encodings for protocol-buffers",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.6.0",
    "signed-varint": "^2.0.1",
    "varint": "5.0.0"
  },
  "devDependencies": {
    "standard": "^14.3.4",
    "tape": "^5.0.1"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/protocol-buffers-encodings.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/protocol-buffers-encodings/issues"
  },
  "homepage": "https://github.com/mafintosh/protocol-buffers-encodings"
}
const crypto = require('hypercore-crypto')
const Protomux = require('protomux')
const b4a = require('b4a')
const schema = require('./spec/hyperschema')

const [NS_INITATOR, NS_RESPONDER] = crypto.namespace('wakeup', 2)

const Handshake = schema.getEncoding('@wakeup/handshake')
const Announce = schema.getEncoding('@wakeup/announce')
const Lookup = schema.getEncoding('@wakeup/lookup')
const Info = schema.getEncoding('@wakeup/info')

module.exports = class WakeupSwarm {
  constructor(onwakeup = noop, { gcTickTime = 2000 } = {}) {
    this.gcTickTime = gcTickTime

    this.topics = new Map()
    this.topicsGC = new Set()
    this.muxers = new Set()
    this.stats = {
      sessionsOpened: 0,
      sessionsClosed: 0,
      topicsAdded: 0,
      topicsGcd: 0,
      peersAdded: 0,
      peersRemoved: 0,
      wireAnnounce: { rx: 0, tx: 0 },
      wireLookup: { rx: 0, tx: 0 },
      wireInfo: { rx: 0, tx: 0 }
    }

    this.onwakeup = onwakeup

    this._gcInterval = null
    this._gcBound = this._gc.bind(this)
  }

  session(capability, handlers = {}) {
    const id = handlers.discoveryKey || crypto.discoveryKey(capability)
    const active = handlers.active !== false
    const hex = b4a.toString(id, 'hex')

    let w = this.topics.get(hex)

    if (w) return w.addSession(handlers)

    w = new WakeupTopic(this, id, capability, active)

    this.topics.set(hex, w)

    for (const muxer of this.muxers) {
      w._onopen(muxer, true)
    }

    return w.addSession(handlers)
  }

  getSessions(capability, handlers = {}) {
    const id = handlers.discoveryKey || crypto.discoveryKey(capability)
    const hex = b4a.toString(id, 'hex')
    const w = this.topics.get(hex)
    return w ? w.sessions : []
  }

  hasStream(stream, capability, handlers = {}) {
    if (!capability) {
      const noiseStream = stream.noiseStream || stream
      return this.muxers.has(getMuxer(noiseStream))
    }

    const id = handlers.discoveryKey || crypto.discoveryKey(capability)
    const hex = b4a.toString(id, 'hex')
    const t = this.topics.get(hex)

    return t ? t.peersByStream.has(stream) : false
  }

  addStream(stream) {
    const noiseStream = stream.noiseStream || stream

    if (!noiseStream.connected) {
      noiseStream.once('open', this.addStream.bind(this, noiseStream))
      return
    }

    const muxer = getMuxer(noiseStream)
    muxer.pair({ protocol: 'wakeup' }, (id) => this._onpair(id, muxer))

    this.muxers.add(muxer)
    noiseStream.on('close', () => this.muxers.delete(muxer))

    for (const w of this.topics.values()) {
      if (!w.isActive) continue
      w._onopen(muxer, true)
    }
  }

  _onActive(w) {
    for (const m of this.muxers) {
      w._onopen(m, false)
    }
  }

  _addGC(topic) {
    if (topic.destroyed) return
    this.topicsGC.add(topic)
    if (this._gcInterval === null) {
      this._gcInterval = setInterval(this._gcBound, this.gcTickTime)
    }
  }

  _removeGC(topic) {
    this.topicsGC.delete(topic)
    if (this.topicsGC.size === 0 && this._gcInterval) {
      clearInterval(this._gcInterval)
      this._gcInterval = null
    }
  }

  _gc() {
    const destroy = []
    for (const w of this.topicsGC) {
      w.idleTicks++
      if (w.idleTicks >= 5) destroy.push(w)
    }
    for (const w of destroy) w.teardown()
  }

  destroy() {
    if (this._gcInterval) clearInterval(this._gcInterval)
    this._gcInterval = null

    for (const w of this.topics.values()) w.teardown()
  }

  async _onpair(id, stream) {
    const hex = b4a.toString(id, 'hex')
    const w = this.topics.get(hex)
    if (!w || !w.sessions.length) return this.onwakeup(id, stream)
    w._onopen(getMuxer(stream), false)
  }

  registerMetrics(promClient) {
    const self = this
    new promClient.Gauge({
      // eslint-disable-line no-new
      name: 'protomux_wakeup_sessions_opened',
      help: 'The amount of sessions opened by protomux wakeup',
      collect() {
        this.set(self.stats.sessionsOpened)
      }
    })

    new promClient.Gauge({
      // eslint-disable-line no-new
      name: 'protomux_wakeup_sessions_closed',
      help: 'The amount of sessions closed by protomux wakeup',
      collect() {
        this.set(self.stats.sessionsClosed)
      }
    })

    new promClient.Gauge({
      // eslint-disable-line no-new
      name: 'protomux_wakeup_topics_added',
      help: 'The amount of topics added to protomux wakeup',
      collect() {
        this.set(self.stats.topicsAdded)
      }
    })

    new promClient.Gauge({
      // eslint-disable-line no-new
      name: 'protomux_wakeup_topics_gcd',
      help: 'The amount of topics that got garbage collected by protomux wakeup',
      collect() {
        this.set(self.stats.topicsGcd)
      }
    })

    new promClient.Gauge({
      // eslint-disable-line no-new
      name: 'protomux_wakeup_peers_added',
      help: 'The amount of peers added by protomux wakeup, across all topics',
      collect() {
        this.set(self.stats.peersAdded)
      }
    })

    new promClient.Gauge({
      // eslint-disable-line no-new
      name: 'protomux_wakeup_peers_removed',
      help: 'The amount of peers removed by protomux wakeup, across all topics',
      collect() {
        this.set(self.stats.peersRemoved)
      }
    })

    new promClient.Gauge({
      // eslint-disable-line no-new
      name: 'protomux_wakeup_wire_announce_rx',
      help: 'The amount of wire announce messages received by protomux wakeup',
      collect() {
        this.set(self.stats.wireAnnounce.rx)
      }
    })
    new promClient.Gauge({
      // eslint-disable-line no-new
      name: 'protomux_wakeup_wire_announce_tx',
      help: 'The amount of wire announce messages transmitted by protomux wakeup',
      collect() {
        this.set(self.stats.wireAnnounce.tx)
      }
    })
    new promClient.Gauge({
      // eslint-disable-line no-new
      name: 'protomux_wakeup_wire_lookup_rx',
      help: 'The amount of wire lookup messages received by protomux wakeup',
      collect() {
        this.set(self.stats.wireLookup.rx)
      }
    })
    new promClient.Gauge({
      // eslint-disable-line no-new
      name: 'protomux_wakeup_wire_lookup_tx',
      help: 'The amount of wire lookup messages transmitted by protomux wakeup',
      collect() {
        this.set(self.stats.wireLookup.tx)
      }
    })
    new promClient.Gauge({
      // eslint-disable-line no-new
      name: 'protomux_wakeup_wire_info_rx',
      help: 'The amount of wire info messages received by protomux wakeup',
      collect() {
        this.set(self.stats.wireInfo.rx)
      }
    })
    new promClient.Gauge({
      // eslint-disable-line no-new
      name: 'protomux_wakeup_wire_info_tx',
      help: 'The amount of wire info messages transmitted by protomux wakeup',
      collect() {
        this.set(self.stats.wireInfo.rx)
      }
    })
  }
}

class WakeupPeer {
  constructor(topic) {
    this.index = 0
    this.userData = null // for the user
    this.clock = 0 // for the user, v useful to reduce traffic
    this.pending = true
    this.removed = false
    this.topic = topic
    this.channel = null
    this.stream = null
    this.wireLookup = null
    this.wireAnnounce = null
    this.wireInfo = null
    this.active = false
  }

  unlink(list) {
    // note that since we pop here we can iterate in reverse safely in case a peer is removed in the same tick
    const head = list.pop()
    if (head === this) return
    head.index = this.index
    list[head.index] = head
  }
}

class WakeupSession {
  constructor(topic, handlers) {
    this.index = 0
    this.topic = topic
    this.handlers = handlers
    this.isActive = handlers.active !== false
    this.destroyed = false
  }

  get peers() {
    return this.topic.peers
  }

  hasStream(stream) {
    return !!this.getPeer(stream)
  }

  addStream(stream) {
    this.topic.addStream(stream)
  }

  getPeer(stream) {
    return this.topic.peersByStream.get(stream) || null
  }

  broadcastLookup(req) {
    for (const peer of this.topic.pendingPeers) {
      this.lookup(peer, req)
    }
    for (const peer of this.topic.peers) {
      this.lookup(peer, req)
    }
  }

  lookupByStream(stream, req) {
    const peer = this.topic.peersByStream.get(stream)
    if (peer) this.lookup(peer, req)
  }

  lookup(peer, req) {
    peer.topic.state.stats.wireLookup.tx++
    peer.wireLookup.send(req || { hash: null })
  }

  announceByStream(stream, wakeup) {
    const peer = this.topic.peersByStream.get(stream)
    if (peer && !peer.pending) this.announce(peer, wakeup)
  }

  announce(peer, wakeup) {
    peer.topic.state.stats.wireAnnounce.tx++
    peer.wireAnnounce.send(wakeup)
  }

  active() {
    this.isActive = true
    this.topic._bumpActivity()
  }

  inactive() {
    this.isActive = false
    this.topic._bumpActivity()
  }

  destroy() {
    if (this.destroyed) return
    this.destroyed = true
    this.topic.removeSession(this)
  }
}

class WakeupTopic {
  constructor(state, id, capability, active) {
    this.state = state
    this.sessions = []
    this.id = id
    this.capability = capability
    this.peers = []
    this.pendingPeers = []
    this.peersByStream = new Map()
    this.activePeers = 0
    this.isActive = active
    this.idleTicks = 0
    this.gcing = false
    this.destroyed = false

    this.state.stats.topicsAdded++
  }

  addSession(handlers) {
    this.state.stats.sessionsOpened++
    const session = new WakeupSession(this, handlers)
    session.index = this.sessions.length
    this.sessions.push(session)
    this._bumpActivity()
    this._checkGC()
    return session
  }

  removeSession(session) {
    if (this.sessions.length <= session.index) return
    if (this.sessions[session.index] !== session) return

    this.state.stats.sessionsClosed++

    // same as with the peer, this allows us to iterate while removing if iterating backwards
    const head = this.sessions.pop()
    if (head !== session) {
      head.index = session.index
      this.sessions[head.index] = head
    }

    this._bumpActivity()
    this._checkGC()
  }

  _bumpActivity() {
    let isActive = false

    for (let i = this.sessions.length - 1; i >= 0; i--) {
      if (this.sessions[i].isActive) {
        isActive = true
        break
      }
    }

    if (isActive) this.active()
    else this.inactive()
  }

  active() {
    if (this.isActive) return
    this.idleTicks = 0
    this.isActive = true
    this._updateActive(true)
  }

  inactive() {
    if (!this.isActive) return
    this.isActive = false
    this._updateActive(false)
  }

  _updateActive(active) {
    const info = { active }

    for (const peer of this.pendingPeers) {
      peer.topic.state.stats.wireInfo.tx++
      peer.wireInfo.send(info)
    }
    for (const peer of this.peers) {
      peer.topic.state.stats.wireInfo.tx++
      peer.wireInfo.send(info)
    }

    this._checkGC()

    if (active) this.state._onActive(this)
  }

  teardown() {
    if (this.destroyed) return
    this.destroyed = true

    this.state.stats.topicsGcd++

    for (let i = this.peers.length - 1; i >= 0; i--) {
      this.peers[i].channel.close()
    }

    for (let i = this.pendingPeers.length - 1; i >= 0; i--) {
      this.pendingPeers[i].channel.close()
    }

    const hex = b4a.toString(this.id, 'hex')

    this.gcing = false
    this.state.topics.delete(hex)
    this.state._removeGC(this)

    for (let i = this.sessions.length - 1; i >= 0; i--) {
      this.state.stats.sessionsClosed++
      const session = this.sessions[i]
      if (session.handlers.ondestroy) session.handlers.ondestroy(session)
    }
  }

  addStream(stream) {
    this._onopen(getMuxer(stream), false)
  }

  _proveCapabilityTo(stream) {
    return this._makeCapability(stream.isInitiator, stream.handshakeHash)
  }

  _makeCapability(isInitiator, handshakeHash) {
    return crypto.hash([isInitiator ? NS_INITATOR : NS_RESPONDER, this.capability, handshakeHash])
  }

  _addPeer(peer, open) {
    if (
      !b4a.equals(
        open.capability,
        this._makeCapability(!peer.stream.isInitiator, peer.stream.handshakeHash)
      )
    ) {
      peer.channel.close()
      return
    }

    if (peer.pending) {
      peer.unlink(this.pendingPeers)
    }

    peer.active = open.active
    peer.pending = false
    peer.index = this.peers.push(peer) - 1

    if (peer.active) {
      this.activePeers++
      this._checkGC()
    }

    for (let i = this.sessions.length - 1; i >= 0; i--) {
      const session = this.sessions[i]
      const handlers = session.handlers

      if (handlers.onpeeradd) handlers.onpeeradd(peer, session)
      if (peer.active && handlers.onpeeractive) handlers.onpeeractive(peer, session)
    }
  }

  _checkGC() {
    const shouldGC = this.activePeers === 0 && this.sessions.length === 0

    if (shouldGC) {
      if (!this.gcing) {
        this.gcing = true
        this.state._addGC(this)
      }
    } else {
      if (this.gcing) {
        this.gcing = false
        this.state._removeGC(this)
      }
    }
  }

  _removePeer(peer) {
    this.state.stats.peersRemoved++
    peer.removed = true
    this.peersByStream.delete(peer.stream)

    if (peer.pending) {
      peer.unlink(this.pendingPeers)
      return
    }

    const active = peer.active

    if (active) {
      peer.active = false
      this.activePeers--
      this._checkGC()
    }

    peer.unlink(this.peers)

    for (let i = this.sessions.length - 1; i >= 0; i--) {
      const session = this.sessions[i]
      const handlers = session.handlers

      if (active && handlers.onpeerinactive) handlers.onpeerinactive(peer, session)
      if (handlers.onpeerremove) handlers.onpeerremove(peer, session)
    }
  }

  _onannounce(wakeup, peer) {
    for (let i = this.sessions.length - 1; i >= 0; i--) {
      const session = this.sessions[i]
      const handlers = session.handlers

      if (handlers.onannounce) handlers.onannounce(wakeup, peer, session)
    }
  }

  _onlookup(req, peer) {
    for (let i = this.sessions.length - 1; i >= 0; i--) {
      const session = this.sessions[i]
      const handlers = session.handlers

      if (handlers.onlookup) handlers.onlookup(req, peer, session)
    }
  }

  _oninfo(info, peer) {
    if (info.active) {
      if (!peer.active) {
        peer.active = true
        this.activePeers++
        this._checkGC()

        for (let i = this.sessions.length - 1; i >= 0; i--) {
          const session = this.sessions[i]
          const handlers = session.handlers

          if (handlers.onpeeractive) handlers.onpeeractive(peer, session)
        }
      }
    } else {
      if (peer.active) {
        peer.active = false
        this.activePeers--
        this._checkGC()

        for (let i = this.sessions.length - 1; i >= 0; i--) {
          const session = this.sessions[i]
          const handlers = session.handlers

          if (handlers.onpeerinactive) handlers.onpeerinactive(peer, session)
        }
      }
    }
  }

  _onopen(muxer, unique) {
    if (!unique && this.peersByStream.has(muxer.stream)) return

    const peer = new WakeupPeer(this)
    const ch = muxer.createChannel({
      userData: peer,
      protocol: 'wakeup',
      id: this.id,
      handshake: Handshake,
      messages: [
        { encoding: Lookup, onmessage: onlookup },
        { encoding: Announce, onmessage: onannounce },
        { encoding: Info, onmessage: onchannelinfo }
      ],
      onopen: onchannelopen,
      onclose: onchannelclose
    })

    if (!ch) return

    this.state.stats.peersAdded++

    peer.channel = ch
    peer.stream = muxer.stream

    peer.wireLookup = ch.messages[0]
    peer.wireAnnounce = ch.messages[1]
    peer.wireInfo = ch.messages[2]

    peer.index = this.pendingPeers.push(peer) - 1
    this.peersByStream.set(muxer.stream, peer)

    ch.open({
      version: 0,
      capability: this._proveCapabilityTo(muxer.stream),
      active: this.isActive
    })
  }
}

function onchannelopen(open, channel) {
  const peer = channel.userData
  peer.topic._addPeer(peer, open)
}

function onchannelclose(close, channel) {
  const peer = channel.userData
  peer.topic._removePeer(peer)
}

function onlookup(req, channel) {
  const peer = channel.userData
  peer.topic.state.stats.wireLookup.rx++
  peer.topic._onlookup(req, peer)
}

function onannounce(wakeup, channel) {
  const peer = channel.userData
  peer.topic.state.stats.wireAnnounce.rx++
  peer.topic._onannounce(wakeup, peer)
}

function onchannelinfo(info, channel) {
  const peer = channel.userData
  peer.topic.state.stats.wireInfo.rx++
  peer.topic._oninfo(info, peer)
}

function getMuxer(stream) {
  if (Protomux.isProtomux(stream)) return stream
  if (stream.noiseStream.userData) return stream.noiseStream.userData
  const mux = Protomux.from(stream.noiseStream)
  stream.noiseStream.userData = mux
  return mux
}

function noop() {}
{
  "name": "protomux-wakeup",
  "version": "2.9.0",
  "description": "Wakeup protocol over protomux",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.6.7",
    "hypercore-crypto": "^3.5.0",
    "hyperschema": "^1.10.4",
    "protomux": "^3.10.1"
  },
  "devDependencies": {
    "@hyperswarm/secret-stream": "^6.8.1",
    "brittle": "^3.17.1",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "prom-client": "^15.1.3"
  },
  "files": [
    "index.js",
    "spec/hyperschema/*.js"
  ],
  "scripts": {
    "format": "prettier --write .",
    "test": "prettier --check . && lunte && brittle test/*.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/protomux-wakeup.git"
  },
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/protomux-wakeup/issues"
  },
  "homepage": "https://github.com/holepunchto/protomux-wakeup"
}
// This file is autogenerated by the hyperschema compiler
// Schema Version: 1
/* eslint-disable camelcase */
/* eslint-disable quotes */

const VERSION = 1
const { c } = require('hyperschema/runtime')

// eslint-disable-next-line no-unused-vars
let version = VERSION

// @wakeup/info
const encoding0 = {
  preencode(state, m) {
    state.end++ // max flag is 1 so always one byte
  },
  encode(state, m) {
    const flags = m.active ? 1 : 0

    c.uint.encode(state, flags)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      active: (flags & 1) !== 0
    }
  }
}

// @wakeup/handshake
const encoding1 = {
  preencode(state, m) {
    c.uint.preencode(state, m.version)
    c.fixed32.preencode(state, m.capability)
    state.end++ // max flag is 1 so always one byte
  },
  encode(state, m) {
    const flags = m.active ? 1 : 0

    c.uint.encode(state, m.version)
    c.fixed32.encode(state, m.capability)
    c.uint.encode(state, flags)
  },
  decode(state) {
    const r0 = c.uint.decode(state)
    const r1 = c.fixed32.decode(state)
    const flags = c.uint.decode(state)

    return {
      version: r0,
      capability: r1,
      active: (flags & 1) !== 0
    }
  }
}

// @wakeup/writer
const encoding2 = {
  preencode(state, m) {
    c.fixed32.preencode(state, m.key)
    c.uint.preencode(state, m.length)
  },
  encode(state, m) {
    c.fixed32.encode(state, m.key)
    c.uint.encode(state, m.length)
  },
  decode(state) {
    const r0 = c.fixed32.decode(state)
    const r1 = c.uint.decode(state)

    return {
      key: r0,
      length: r1
    }
  }
}

// @wakeup/announce
const encoding3 = c.array(encoding2)

// @wakeup/lookup
const encoding4 = {
  preencode(state, m) {
    state.end++ // max flag is 1 so always one byte

    if (m.hash) c.fixed32.preencode(state, m.hash)
  },
  encode(state, m) {
    const flags = m.hash ? 1 : 0

    c.uint.encode(state, flags)

    if (m.hash) c.fixed32.encode(state, m.hash)
  },
  decode(state) {
    const flags = c.uint.decode(state)

    return {
      hash: (flags & 1) !== 0 ? c.fixed32.decode(state) : null
    }
  }
}

function setVersion(v) {
  version = v
}

function encode(name, value, v = VERSION) {
  version = v
  return c.encode(getEncoding(name), value)
}

function decode(name, buffer, v = VERSION) {
  version = v
  return c.decode(getEncoding(name), buffer)
}

function getEnum(name) {
  switch (name) {
    default:
      throw new Error('Enum not found ' + name)
  }
}

function getEncoding(name) {
  switch (name) {
    case '@wakeup/info':
      return encoding0
    case '@wakeup/handshake':
      return encoding1
    case '@wakeup/writer':
      return encoding2
    case '@wakeup/announce':
      return encoding3
    case '@wakeup/lookup':
      return encoding4
    default:
      throw new Error('Encoder not found ' + name)
  }
}

function getStruct(name, v = VERSION) {
  const enc = getEncoding(name)
  return {
    preencode(state, m) {
      version = v
      enc.preencode(state, m)
    },
    encode(state, m) {
      version = v
      enc.encode(state, m)
    },
    decode(state) {
      version = v
      return enc.decode(state)
    }
  }
}

const resolveStruct = getStruct // compat

module.exports = {
  resolveStruct,
  getStruct,
  getEnum,
  getEncoding,
  encode,
  decode,
  setVersion,
  version
}
const b4a = require('b4a')
const c = require('compact-encoding')
const queueTick = require('queue-tick')
const safetyCatch = require('safety-catch')
const unslab = require('unslab')

const MAX_BUFFERED = 32768
const MAX_BACKLOG = Infinity // TODO: impl "open" backpressure
const MAX_BATCH = 8 * 1024 * 1024

class Channel {
  constructor(
    mux,
    info,
    userData,
    protocol,
    aliases,
    id,
    handshake,
    messages,
    onopen,
    onclose,
    ondestroy,
    ondrain
  ) {
    this.userData = userData
    this.protocol = protocol
    this.aliases = aliases
    this.id = id
    this.handshake = null
    this.messages = []

    this.opened = false
    this.closed = false
    this.destroyed = false

    this.onopen = onopen
    this.onclose = onclose
    this.ondestroy = ondestroy
    this.ondrain = ondrain

    this._handshake = handshake
    this._mux = mux
    this._info = info
    this._localId = 0
    this._remoteId = 0
    this._active = 0
    this._extensions = null

    this._decBound = this._dec.bind(this)
    this._decAndDestroyBound = this._decAndDestroy.bind(this)

    this._openedPromise = null
    this._openedResolve = null

    this._destroyedPromise = null
    this._destroyedResolve = null

    for (const m of messages) this.addMessage(m)
  }

  get drained() {
    return this._mux.drained
  }

  fullyOpened() {
    if (this.opened) return Promise.resolve(true)
    if (this.closed) return Promise.resolve(false)
    if (this._openedPromise) return this._openedPromise

    this._openedPromise = new Promise((resolve) => {
      this._openedResolve = resolve
    })
    return this._openedPromise
  }

  fullyClosed() {
    if (this.destroyed) return Promise.resolve()
    if (this._destroyedPromise) return this._destroyedPromise

    this._destroyedPromise = new Promise((resolve) => {
      this._destroyedResolve = resolve
    })
    return this._destroyedPromise
  }

  open(handshake) {
    const id = this._mux._free.length > 0 ? this._mux._free.pop() : this._mux._local.push(null) - 1

    this._info.opened++
    this._info.lastChannel = this
    this._localId = id + 1
    this._mux._local[id] = this

    if (this._remoteId === 0) {
      this._info.outgoing.push(this._localId)
    }

    const state = { buffer: null, start: 2, end: 2 }

    c.uint.preencode(state, this._localId)
    c.string.preencode(state, this.protocol)
    c.optionalBuffer.preencode(state, this.id)
    if (this._handshake) this._handshake.preencode(state, handshake)

    state.buffer = this._mux._alloc(state.end)

    state.buffer[0] = 0
    state.buffer[1] = 1
    c.uint.encode(state, this._localId)
    c.string.encode(state, this.protocol)
    c.optionalBuffer.encode(state, this.id)
    if (this._handshake) this._handshake.encode(state, handshake)

    this._mux._write0(state.buffer)
  }

  _dec() {
    if (--this._active === 0 && this.closed === true) this._destroy()
  }

  _decAndDestroy(err) {
    this._dec()
    this._mux._safeDestroy(err)
  }

  _fullyOpenSoon() {
    this._mux._remote[this._remoteId - 1].session = this
    queueTick(this._fullyOpenOrDestroy.bind(this))
  }

  _fullyOpenOrDestroy() {
    try {
      this._fullyOpen()
    } catch (err) {
      this._mux._safeDestroyBound(err)
    }
  }

  _fullyOpen() {
    if (this.opened === true || this.closed === true) return

    const remote = this._mux._remote[this._remoteId - 1]

    this.handshake = this._handshake ? this._handshake.decode(remote.state) : null
    this._track(this.onopen(this.handshake, this))

    remote.session = this
    remote.state = null
    if (remote.pending !== null) this._drain(remote)
    if (this._mux._destroying === true) return

    this.opened = true
    this._resolveOpen(true)
  }

  _resolveOpen(opened) {
    if (this._openedResolve !== null) {
      this._openedResolve(opened)
      this._openedResolve = this._openedPromise = null
    }
  }

  _resolveDestroyed() {
    if (this._destroyedResolve !== null) {
      this._destroyedResolve()
      this._destroyedResolve = this._destroyedPromise = null
    }
  }

  _drain(remote) {
    for (let i = 0; i < remote.pending.length; i++) {
      const p = remote.pending[i]
      this._mux._buffered -= byteSize(p.state)
      this._recv(p.type, p.state)
      if (this._mux._destroying === true) return
    }

    remote.pending = null
    this._mux._resumeMaybe()
  }

  _track(p) {
    if (isPromise(p) === true) {
      this._active++
      return p.then(this._decBound, this._decAndDestroyBound)
    }

    return null
  }

  _close(isRemote) {
    if (this.closed === true) return
    this.closed = true

    this._info.opened--
    if (this._info.lastChannel === this) this._info.lastChannel = null

    if (this._remoteId > 0) {
      this._mux._remote[this._remoteId - 1] = null
      this._remoteId = 0
      // If remote has acked, we can reuse the local id now
      // otherwise, we need to wait for the "ack" to arrive
      this._mux._free.push(this._localId - 1)
    }

    this._mux._local[this._localId - 1] = null
    this._localId = 0

    this._mux._gc(this._info)
    this._track(this.onclose(isRemote, this))

    if (this._active === 0) this._destroy()

    this._resolveOpen(false)
  }

  _destroy() {
    if (this.destroyed === true) return
    this.destroyed = true
    this._track(this.ondestroy(this))
    this._resolveDestroyed()
  }

  _recv(type, state) {
    if (type < this.messages.length) {
      const m = this.messages[type]
      const p = m.recv(state, this)
      if (m.autoBatch === true) return p
    }
    return null
  }

  cork() {
    this._mux.cork()
  }

  uncork() {
    this._mux.uncork()
  }

  close() {
    if (this.closed === true) return

    const state = { buffer: null, start: 2, end: 2 }

    c.uint.preencode(state, this._localId)

    state.buffer = this._mux._alloc(state.end)

    state.buffer[0] = 0
    state.buffer[1] = 3
    c.uint.encode(state, this._localId)

    this._close(false)
    this._mux._write0(state.buffer)
  }

  addMessage(opts) {
    if (!opts) return this._skipMessage()

    const type = this.messages.length
    const autoBatch = opts.autoBatch !== false
    const encoding = opts.encoding || c.raw
    const onmessage = opts.onmessage || noop

    const s = this
    const typeLen = encodingLength(c.uint, type)

    const m = {
      type,
      autoBatch,
      encoding,
      onmessage,
      recv(state, session) {
        return session._track(m.onmessage(encoding.decode(state), session))
      },
      send(m, session = s) {
        if (session.closed === true) return false

        const mux = session._mux
        const state = { buffer: null, start: 0, end: typeLen }

        if (mux._batch !== null) {
          encoding.preencode(state, m)
          state.buffer = mux._alloc(state.end)

          c.uint.encode(state, type)
          encoding.encode(state, m)

          mux._pushBatch(session._localId, state.buffer)
          return true
        }

        c.uint.preencode(state, session._localId)
        encoding.preencode(state, m)

        state.buffer = mux._alloc(state.end)

        c.uint.encode(state, session._localId)
        c.uint.encode(state, type)
        encoding.encode(state, m)

        mux.drained = mux.stream.write(state.buffer)

        return mux.drained
      }
    }

    this.messages.push(m)

    return m
  }

  _skipMessage() {
    const type = this.messages.length
    const m = {
      type,
      encoding: c.raw,
      onmessage: noop,
      recv(state, session) {},
      send(m, session) {}
    }

    this.messages.push(m)
    return m
  }
}

module.exports = class Protomux {
  constructor(stream, { alloc } = {}) {
    if (stream.userData === null) stream.userData = this

    this.isProtomux = true
    this.stream = stream
    this.corked = 0
    this.drained = true

    this._alloc =
      alloc || (typeof stream.alloc === 'function' ? stream.alloc.bind(stream) : b4a.allocUnsafe)
    this._safeDestroyBound = this._safeDestroy.bind(this)
    this._uncorkBound = this.uncork.bind(this)

    this._remoteBacklog = 0
    this._buffered = 0
    this._paused = false
    this._remote = []
    this._local = []
    this._free = []
    this._batch = null
    this._batchState = null

    this._infos = new Map()
    this._notify = new Map()
    // stream.destroyed flips asynchronously on streamx-based transports.
    this._destroying = false

    this.stream.on('data', this._ondata.bind(this))
    this.stream.on('drain', this._ondrain.bind(this))
    this.stream.on('end', this._onend.bind(this))
    this.stream.on('error', noop) // we handle this in "close"
    this.stream.on('close', this._shutdown.bind(this))
  }

  static from(stream, opts) {
    if (stream.userData && stream.userData.isProtomux) return stream.userData
    if (stream.isProtomux) return stream
    return new this(stream, opts)
  }

  static isProtomux(mux) {
    return typeof mux === 'object' && mux.isProtomux === true
  }

  *[Symbol.iterator]() {
    for (const session of this._local) {
      if (session !== null) yield session
    }
  }

  isIdle() {
    return this._local.length === this._free.length
  }

  cork() {
    if (++this.corked === 1) {
      this._batch = []
      this._batchState = { buffer: null, start: 0, end: 1 }
    }
  }

  uncork() {
    if (--this.corked === 0) {
      this._sendBatch(this._batch, this._batchState)
      this._batch = null
      this._batchState = null
    }
  }

  getLastChannel({ protocol, id = null }) {
    const key = toKey(protocol, id)
    const info = this._infos.get(key)
    if (info) return info.lastChannel
    return null
  }

  pair({ protocol, id = null }, notify) {
    this._notify.set(toKey(protocol, id), notify)
  }

  unpair({ protocol, id = null }) {
    this._notify.delete(toKey(protocol, id))
  }

  opened({ protocol, id = null }) {
    const key = toKey(protocol, id)
    const info = this._infos.get(key)
    return info ? info.opened > 0 : false
  }

  createChannel({
    userData = null,
    protocol,
    aliases = [],
    id = null,
    unique = true,
    handshake = null,
    messages = [],
    onopen = noop,
    onclose = noop,
    ondestroy = noop,
    ondrain = noop
  }) {
    if (this.stream.destroyed) return null

    const info = this._get(protocol, id, aliases)
    if (unique && info.opened > 0) return null

    if (info.incoming.length === 0) {
      return new Channel(
        this,
        info,
        userData,
        protocol,
        aliases,
        id,
        handshake,
        messages,
        onopen,
        onclose,
        ondestroy,
        ondrain
      )
    }

    this._remoteBacklog--

    const remoteId = info.incoming.shift()
    const r = this._remote[remoteId - 1]
    if (r === null) return null

    const session = new Channel(
      this,
      info,
      userData,
      protocol,
      aliases,
      id,
      handshake,
      messages,
      onopen,
      onclose,
      ondestroy,
      ondrain
    )

    session._remoteId = remoteId
    session._fullyOpenSoon()

    return session
  }

  _pushBatch(localId, buffer) {
    if (this._batchState.end >= MAX_BATCH) {
      this._sendBatch(this._batch, this._batchState)
      this._batch = []
      this._batchState = { buffer: null, start: 0, end: 1 }
    }

    if (this._batch.length === 0 || this._batch[this._batch.length - 1].localId !== localId) {
      this._batchState.end++
      c.uint.preencode(this._batchState, localId)
    }
    c.buffer.preencode(this._batchState, buffer)
    this._batch.push({ localId, buffer })
  }

  _sendBatch(batch, state) {
    if (batch.length === 0) return

    let prev = batch[0].localId

    state.buffer = this._alloc(state.end)
    state.buffer[state.start++] = 0
    state.buffer[state.start++] = 0

    c.uint.encode(state, prev)

    for (let i = 0; i < batch.length; i++) {
      const b = batch[i]
      if (prev !== b.localId) {
        state.buffer[state.start++] = 0
        c.uint.encode(state, (prev = b.localId))
      }
      c.buffer.encode(state, b.buffer)
    }

    this.drained = this.stream.write(state.buffer)
  }

  _get(protocol, id, aliases = []) {
    const key = toKey(protocol, id)

    let info = this._infos.get(key)
    if (info) return info

    info = {
      key,
      protocol,
      aliases: [],
      id,
      pairing: 0,
      opened: 0,
      incoming: [],
      outgoing: [],
      lastChannel: null
    }
    this._infos.set(key, info)

    for (const alias of aliases) {
      const key = toKey(alias, id)
      info.aliases.push(key)

      this._infos.set(key, info)
    }

    return info
  }

  _gc(info) {
    if (info.opened === 0 && info.outgoing.length === 0 && info.incoming.length === 0) {
      this._infos.delete(info.key)

      for (const alias of info.aliases) this._infos.delete(alias)
    }
  }

  _ondata(buffer) {
    if (buffer.byteLength === 0) return // ignore empty frames...
    try {
      const state = { buffer, start: 0, end: buffer.byteLength }
      this._decode(c.uint.decode(state), state)
    } catch (err) {
      this._safeDestroy(err)
    }
  }

  _ondrain() {
    this.drained = true

    for (const s of this._local) {
      if (s !== null) s._track(s.ondrain(s))
    }
  }

  _onend() {
    // TODO: support half open mode for the users who wants that here
    this.stream.end()
  }

  _decode(remoteId, state) {
    const type = c.uint.decode(state)

    if (remoteId === 0) {
      return this._oncontrolsession(type, state)
    }

    const r = remoteId <= this._remote.length ? this._remote[remoteId - 1] : null

    // if the channel is closed ignore - could just be a pipeline message...
    if (r === null) return null

    if (r.pending !== null) {
      this._bufferMessage(r, type, state)
      return null
    }

    return r.session._recv(type, state)
  }

  _oncontrolsession(type, state) {
    switch (type) {
      case 0:
        this._onbatch(state)
        break

      case 1:
        // return the promise back up as this has sideeffects so we can batch reply
        return this._onopensession(state)

      case 2:
        this._onrejectsession(state)
        break

      case 3:
        this._onclosesession(state)
        break
    }

    return null
  }

  _bufferMessage(r, type, { buffer, start, end }) {
    const state = { buffer, start, end } // copy
    r.pending.push({ type, state })
    this._buffered += byteSize(state)
    this._pauseMaybe()
  }

  _pauseMaybe() {
    if (this._paused === true || this._buffered <= MAX_BUFFERED) return
    this._paused = true
    this.stream.pause()
  }

  _resumeMaybe() {
    if (this._paused === false || this._buffered > MAX_BUFFERED) return
    this._paused = false
    this.stream.resume()
  }

  _onbatch(state) {
    const end = state.end
    let remoteId = c.uint.decode(state)

    let waiting = null

    while (state.end > state.start) {
      const len = c.uint.decode(state)
      if (len === 0) {
        remoteId = c.uint.decode(state)
        continue
      }
      state.end = state.start + len
      // if batch contains more than one message, cork it so we reply back with a batch
      if (end !== state.end && waiting === null) {
        waiting = []
        this.cork()
      }
      const p = this._decode(remoteId, state)
      if (waiting !== null && p !== null) waiting.push(p)
      state.start = state.end
      state.end = end
    }

    if (waiting !== null) {
      // the waiting promises are not allowed to throw but we destroy the stream in case we are wrong
      Promise.all(waiting).then(this._uncorkBound, this._safeDestroyBound)
    }
  }

  _onopensession(state) {
    const remoteId = c.uint.decode(state)
    const protocol = c.string.decode(state)
    const id = unslab(c.optionalBuffer.decode(state))

    // remote tried to open the control session - auto reject for now
    // as we can use as an explicit control protocol declaration if we need to
    if (remoteId === 0) {
      this._rejectSession(0)
      return null
    }

    const rid = remoteId - 1
    const info = this._get(protocol, id)

    // allow the remote to grow the ids by one
    if (this._remote.length === rid) {
      this._remote.push(null)
    }

    if (rid >= this._remote.length || this._remote[rid] !== null) {
      throw new Error('Invalid open message')
    }

    if (info.outgoing.length > 0) {
      const localId = info.outgoing.shift()
      const session = this._local[localId - 1]

      if (session === null) {
        // we already closed the channel - ignore
        this._free.push(localId - 1)
        return null
      }

      this._remote[rid] = { state, pending: null, session: null }

      session._remoteId = remoteId
      session._fullyOpen()
      return null
    }

    const copyState = { buffer: state.buffer, start: state.start, end: state.end }
    this._remote[rid] = { state: copyState, pending: [], session: null }

    if (++this._remoteBacklog > MAX_BACKLOG) {
      throw new Error('Remote exceeded backlog')
    }

    info.pairing++
    info.incoming.push(remoteId)

    return this._requestSession(protocol, id, info).catch(this._safeDestroyBound)
  }

  _onrejectsession(state) {
    const localId = c.uint.decode(state)

    // TODO: can be done smarter...
    for (const info of this._infos.values()) {
      const i = info.outgoing.indexOf(localId)
      if (i === -1) continue

      info.outgoing.splice(i, 1)

      const session = this._local[localId - 1]

      this._free.push(localId - 1)
      if (session !== null) session._close(true)

      this._gc(info)
      return
    }

    throw new Error('Invalid reject message')
  }

  _onclosesession(state) {
    const remoteId = c.uint.decode(state)

    if (remoteId === 0) return // ignore

    const rid = remoteId - 1
    const r = rid < this._remote.length ? this._remote[rid] : null

    if (r === null) return

    if (r.session !== null) r.session._close(true)
  }

  async _requestSession(protocol, id, info) {
    const notify = this._notify.get(toKey(protocol, id)) || this._notify.get(toKey(protocol, null))

    if (notify) await notify(id)

    if (--info.pairing > 0) return

    while (info.incoming.length > 0) {
      this._rejectSession(info, info.incoming.shift())
    }

    this._gc(info)
  }

  _rejectSession(info, remoteId) {
    if (remoteId > 0) {
      const r = this._remote[remoteId - 1]

      if (r.pending !== null) {
        for (let i = 0; i < r.pending.length; i++) {
          this._buffered -= byteSize(r.pending[i].state)
        }
      }

      this._remote[remoteId - 1] = null
      this._resumeMaybe()
    }

    const state = { buffer: null, start: 2, end: 2 }

    c.uint.preencode(state, remoteId)

    state.buffer = this._alloc(state.end)

    state.buffer[0] = 0
    state.buffer[1] = 2
    c.uint.encode(state, remoteId)

    this._write0(state.buffer)
  }

  _write0(buffer) {
    if (this._batch !== null) {
      this._pushBatch(0, buffer.subarray(1))
      return
    }

    this.drained = this.stream.write(buffer)
  }

  destroy(err) {
    this._destroying = true
    this.stream.destroy(err)
  }

  _safeDestroy(err) {
    safetyCatch(err)
    this._destroying = true
    this.stream.destroy(err)
  }

  _shutdown() {
    this._destroying = true
    for (const s of this._local) {
      if (s !== null) s._close(true)
    }
  }
}

function noop() {}

function toKey(protocol, id) {
  return protocol + '##' + (id ? b4a.toString(id, 'hex') : '')
}

function byteSize(state) {
  return 512 + (state.end - state.start)
}

function isPromise(p) {
  return !!(p && typeof p.then === 'function')
}

function encodingLength(enc, val) {
  const state = { buffer: null, start: 0, end: 0 }
  enc.preencode(state, val)
  return state.end
}
{
  "name": "protomux",
  "version": "3.11.0",
  "description": "Multiplex multiple message oriented protocols over a stream",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.3.1",
    "compact-encoding": "^3.0.0",
    "queue-tick": "^1.0.0",
    "safety-catch": "^1.0.1",
    "unslab": "^1.3.0"
  },
  "devDependencies": {
    "@hyperswarm/secret-stream": "^6.0.0",
    "brittle": "^3.0.0",
    "lunte": "^1.0.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/protomux.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/protomux/issues"
  },
  "homepage": "https://github.com/holepunchto/protomux"
}
{
  "name": "queue-tick",
  "version": "1.0.1",
  "description": "Next tick shim that prefers process.nextTick over queueMicrotask for compat",
  "main": "./process-next-tick.js",
  "browser": "./queue-microtask.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^16.0.3",
    "tape": "^5.3.1"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/queue-tick.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/queue-tick/issues"
  },
  "homepage": "https://github.com/mafintosh/queue-tick"
}
module.exports = (typeof process !== 'undefined' && typeof process.nextTick === 'function')
  ? process.nextTick.bind(process)
  : require('./queue-microtask')
module.exports = typeof queueMicrotask === 'function' ? queueMicrotask : (fn) => Promise.resolve().then(fn)
require.addon = require('require-addon')

module.exports = require.addon('.', __filename)
const binding = require('./binding')

exports.get = function get(field, bit) {
  const n = field.byteLength * 8

  if (bit < 0) bit += n
  if (bit < 0 || bit >= n) return false

  return binding.quickbit_napi_get(toBuffer(field), bit) !== 0
}

exports.set = function set(field, bit, value = true) {
  const n = field.byteLength * 8

  if (bit < 0) bit += n
  if (bit < 0 || bit >= n) return false

  return binding.quickbit_napi_set(toBuffer(field), bit, value ? 1 : 0) !== 0
}

exports.fill = function fill(
  field,
  value,
  start = 0,
  end = field.byteLength * 8
) {
  const n = field.byteLength * 8

  if (start < 0) start += n
  if (end < 0) end += n
  if (start < 0 || start >= field.byteLength * 8 || start >= end) return field

  binding.quickbit_napi_fill(toBuffer(field), value ? 1 : 0, start, end)
  return field
}

exports.clear = function clear(field, ...chunks) {
  binding.quickbit_napi_clear(toBuffer(field), chunks.map(toBufferChunk))
}

exports.findFirst = function findFirst(field, value, position = 0) {
  const n = field.byteLength * 8

  if (position < 0) position += n
  if (position < 0) position = 0
  if (position >= n) return -1

  return binding.quickbit_napi_find_first(
    toBuffer(field),
    value ? 1 : 0,
    position
  )
}

exports.findLast = function findLast(
  field,
  value,
  position = field.byteLength * 8 - 1
) {
  const n = field.byteLength * 8

  if (position < 0) position += n
  if (position < 0) return -1
  if (position >= n) position = n - 1

  return binding.quickbit_napi_find_last(
    toBuffer(field),
    value ? 1 : 0,
    position
  )
}

function toBuffer(field) {
  if (field.BYTES_PER_ELEMENT === 1) return field
  return new Uint8Array(field.buffer, field.byteOffset, field.byteLength)
}

function toBufferChunk(chunk) {
  return { field: toBuffer(chunk.field), offset: chunk.offset }
}

class Index {
  static from(fieldOrChunks, byteLength = -1) {
    if (Array.isArray(fieldOrChunks)) {
      return new SparseIndex(fieldOrChunks, byteLength)
    } else {
      return new DenseIndex(fieldOrChunks, byteLength)
    }
  }

  constructor(byteLength) {
    this._byteLength = byteLength
    this.handle = Buffer.allocUnsafe(binding.sizeof_quickbit_index_t)
  }

  get byteLength() {
    return this._byteLength
  }

  skipFirst(value, position = 0) {
    const n = this.byteLength * 8

    if (position < 0) position += n
    if (position < 0) position = 0
    if (position >= n) return n - 1

    return binding.quickbit_napi_skip_first(
      this.handle,
      this.byteLength,
      value ? 1 : 0,
      position
    )
  }

  skipLast(value, position = this.byteLength * 8 - 1) {
    const n = this.byteLength * 8

    if (position < 0) position += n
    if (position < 0) return 0
    if (position >= n) position = n - 1

    return binding.quickbit_napi_skip_last(
      this.handle,
      this.byteLength,
      value ? 1 : 0,
      position
    )
  }
}

exports.Index = Index

class DenseIndex extends Index {
  constructor(field, byteLength) {
    super(byteLength)
    this.field = field

    binding.quickbit_napi_index_init(this.handle, toBuffer(this.field))
  }

  get byteLength() {
    if (this._byteLength !== -1) return this._byteLength
    return this.field.byteLength
  }

  update(bit) {
    const n = this.byteLength * 8

    if (bit < 0) bit += n
    if (bit < 0 || bit >= n) return false

    return (
      binding.quickbit_napi_index_update(
        this.handle,
        toBuffer(this.field),
        bit
      ) !== 0
    )
  }
}

function selectChunk(chunks, offset) {
  for (let i = 0; i < chunks.length; i++) {
    const next = chunks[i]

    const start = next.offset
    const end = next.offset + next.field.byteLength

    if (offset >= start && offset + 16 <= end) {
      return next
    }
  }

  return null
}

class SparseIndex extends Index {
  constructor(chunks, byteLength) {
    super(byteLength)
    this.chunks = chunks

    binding.quickbit_napi_index_init_sparse(
      this.handle,
      this.chunks.map(toBufferChunk)
    )
  }

  get byteLength() {
    if (this._byteLength !== -1) return this._byteLength
    const last = this.chunks[this.chunks.length - 1]
    return last ? last.offset + last.field.byteLength : 0
  }

  update(bit) {
    const n = this.byteLength * 8

    if (bit < 0) bit += n
    if (bit < 0 || bit >= n) return false

    const j = Math.floor(bit / 128)

    const offset = j * 16

    const chunk = selectChunk(this.chunks, offset)

    if (chunk === null) return false

    return (
      binding.quickbit_napi_index_update_sparse(
        this.handle,
        toBuffer(chunk.field),
        chunk.offset,
        bit
      ) !== 0
    )
  }
}
{
  "name": "quickbit-native",
  "version": "2.4.8",
  "description": "libquickbit JavaScript bindings for Node.js",
  "main": "index.js",
  "files": [
    "index.js",
    "macros.h",
    "binding.cc",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "test": "npm run lint && npm run test:bare && npm run test:node",
    "test:bare": "bare test.mjs",
    "test:node": "node test.mjs",
    "lint": "prettier . --check"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/quickbit-native.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/quickbit-native/issues"
  },
  "homepage": "https://github.com/holepunchto/quickbit-native#readme",
  "dependencies": {
    "require-addon": "^1.1.0"
  },
  "devDependencies": {
    "b4a": "^1.6.7",
    "bare-compat-napi": "^1.3.2",
    "brittle": "^3.1.0",
    "cmake-bare": "^1.1.7",
    "cmake-fetch": "^1.1.0",
    "cmake-napi": "^1.0.2",
    "prettier": "^3.5.3",
    "prettier-config-standard": "^7.0.0"
  }
}
const simdle = require('simdle-universal')

const INDEX_LEN = (16 /* root */ + 128 * 16 /* children */) * 2

const get = exports.get = function get (field, bit) {
  const n = field.byteLength * 8

  if (bit < 0) bit += n
  if (bit < 0 || bit >= n) return false

  const m = field.BYTES_PER_ELEMENT * 8

  const offset = bit & (m - 1)
  const i = (bit - offset) / m

  return (field[i] & (1 << offset)) !== 0
}

const set = exports.set = function set (field, bit, value = true) {
  const n = field.byteLength * 8

  if (bit < 0) bit += n
  if (bit < 0 || bit >= n) return false

  const m = field.BYTES_PER_ELEMENT * 8

  const offset = bit & (m - 1)
  const i = (bit - offset) / m
  const mask = 1 << offset

  if (value) {
    if ((field[i] & mask) !== 0) return false
  } else {
    if ((field[i] & mask) === 0) return false
  }

  field[i] ^= mask

  return true
}

exports.fill = function fill (field, value, start = 0, end = field.byteLength * 8) {
  const n = field.byteLength * 8

  if (start < 0) start += n
  if (end < 0) end += n
  if (start < 0 || start >= field.byteLength * 8 || start >= end) return field

  const m = field.BYTES_PER_ELEMENT * 8

  let i, j

  {
    const offset = start & (m - 1)
    i = (start - offset) / m

    if (offset !== 0) {
      let shift = m - offset
      if (end - start < shift) shift = end - start

      const mask = ((1 << shift) - 1) << offset

      if (value) field[i] |= mask
      else field[i] &= ~mask

      i++
    }
  }

  {
    const offset = end & (m - 1)
    j = (end - offset) / m

    if (offset !== 0 && j >= i) {
      const mask = (1 << offset) - 1

      if (value) field[j] |= mask
      else field[j] &= ~mask
    }
  }

  if (i < j) field.fill(value ? (2 ** m) - 1 : 0, i, j)

  return field
}

exports.clear = function clear (field, ...chunks) {
  const n = field.byteLength

  for (const chunk of chunks) {
    if (chunk.offset >= n) continue

    const m = chunk.field.byteLength

    let i = chunk.offset
    let j = 0

    while (((i & 15) !== 0 || (j & 15) !== 0) && i < n && j < m) {
      field[i] = field[i] & ~chunk.field[j]
      i++
      j++
    }

    if (i + 15 < n && j + 15 < m) {
      const len = Math.min(n - (n & 15) - i, m - (m & 15) - j)

      simdle.clear(field.subarray(i, i + len), chunk.field.subarray(j, j + len), field.subarray(i, i + len))
    }

    while (i < n && j < m) {
      field[i] = field[i] & ~chunk.field[j]
      i++
      j++
    }
  }
}

function bitOffset (bit, offset) {
  return !bit ? offset : (INDEX_LEN * 8 / 2) + offset
}

function byteOffset (bit, offset) {
  return !bit ? offset : (INDEX_LEN / 2) + offset
}

exports.findFirst = function findFirst (field, value, position = 0) {
  const n = field.byteLength * 8

  if (position < 0) position += n
  if (position < 0) position = 0
  if (position >= n) return -1

  value = !!value

  for (let i = position; i < n; i++) {
    if (get(field, i) === value) return i
  }

  return -1
}

exports.findLast = function findLast (field, value, position = field.byteLength * 8 - 1) {
  const n = field.byteLength * 8

  if (position < 0) position += n
  if (position < 0) return -1
  if (position >= n) position = n - 1

  value = !!value

  for (let i = position; i >= 0; i--) {
    if (get(field, i) === value) return i
  }

  return -1
}

const Index = exports.Index = class Index {
  static from (fieldOrChunks, byteLength = -1) {
    if (Array.isArray(fieldOrChunks)) {
      return new SparseIndex(fieldOrChunks, byteLength)
    } else {
      return new DenseIndex(fieldOrChunks, byteLength)
    }
  }

  constructor (byteLength) {
    this._byteLength = byteLength
    this.handle = new Uint32Array(INDEX_LEN / 4)
  }

  get byteLength () {
    return this._byteLength
  }

  skipFirst (value, position = 0) {
    const n = this.byteLength * 8

    if (position < 0) position += n
    if (position < 0) position = 0
    if (position >= n) return n - 1

    let i = Math.floor(position / 16384)

    if (i > 127) return position

    while (i <= 127 && get(this.handle, bitOffset(value, i))) {
      i++
    }

    if (i === 128) return n - 1

    let k = i * 16384
    let j = 0

    if (position > k) j = Math.floor((position - k) / 128)

    while (j <= 127 && get(this.handle, bitOffset(value, i * 128 + j + 128))) {
      j++
      k += 128
    }

    if (j === 128 && i !== 127) return this.skipFirst(value, (i + 1) * 16384)

    if (k > position) position = k

    return position < n ? position : n - 1
  }

  skipLast (value, position = this.byteLength * 8 - 1) {
    const n = this.byteLength * 8

    if (position < 0) position += n
    if (position < 0) return 0
    if (position >= n) position = n - 1

    let i = Math.floor(position / 16384)

    if (i > 127) return position

    while (i >= 0 && get(this.handle, bitOffset(value, i))) {
      i--
    }

    if (i === -1) return 0

    let k = ((i + 1) * 16384) - 1
    let j = 127

    if (position < k) j = 128 - Math.ceil((k - position) / 128)

    while (j >= 0 && get(this.handle, bitOffset(value, i * 128 + j + 128))) {
      j--
      k -= 128
    }

    if (j === -1 && i !== 0) return this.skipLast(value, i * 16384 - 1)

    if (k < position) position = k

    return position
  }
}

class DenseIndex extends Index {
  constructor (field, byteLength) {
    super(byteLength)
    this.field = field

    const m = field.BYTES_PER_ELEMENT

    for (let i = 0; i < 128; i++) {
      for (let j = 0; j < 128; j++) {
        const offset = (i * 128 + j) * 16
        let allz = true
        let allo = false

        if (offset + 16 <= this.field.byteLength) {
          const vec = this.field.subarray(offset / m, (offset + 16) / m)

          allz = simdle.allz(vec)
          allo = simdle.allo(vec)
        }

        const k = i * 128 + 128 + j

        set(this.handle, bitOffset(false, k), allz)
        set(this.handle, bitOffset(true, k), allo)
      }

      {
        const offset = byteOffset(false, i * 16 + 16) / 4
        const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

        set(this.handle, bitOffset(false, i), allo)
      }

      {
        const offset = byteOffset(true, i * 16 + 16) / 4
        const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

        set(this.handle, bitOffset(true, i), allo)
      }
    }
  }

  get byteLength () {
    if (this._byteLength !== -1) return this._byteLength
    return this.field.byteLength
  }

  update (bit) {
    const n = this.byteLength * 8

    if (bit < 0) bit += n
    if (bit < 0 || bit >= n) return false

    const m = this.field.BYTES_PER_ELEMENT

    const i = Math.floor(bit / 16384)
    const j = Math.floor(bit / 128)

    const offset = (j * 16) / m
    const vec = this.field.subarray(offset, offset + (16 / m))

    const allz = simdle.allz(vec)
    const allo = simdle.allo(vec)

    let changed = false

    if (set(this.handle, bitOffset(false, 128 + j), allz)) {
      changed = true

      const offset = byteOffset(false, i * 16 + 16) / 4
      const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

      set(this.handle, bitOffset(false, i), allo)
    }

    if (set(this.handle, bitOffset(true, 128 + j), allo)) {
      changed = true

      const offset = byteOffset(true, i * 16 + 16) / 4
      const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

      set(this.handle, bitOffset(true, i), allo)
    }

    return changed
  }
}

function selectChunk (chunks, offset) {
  for (let i = 0; i < chunks.length; i++) {
    const next = chunks[i]

    const start = next.offset
    const end = next.offset + next.field.byteLength

    if (offset >= start && offset + 16 <= end) {
      return next
    }
  }

  return null
}

class SparseIndex extends Index {
  constructor (chunks, byteLength) {
    super(byteLength)
    this.chunks = chunks

    for (let i = 0; i < 128; i++) {
      for (let j = 0; j < 128; j++) {
        const offset = (i * 128 + j) * 16
        let allz = true
        let allo = false

        const chunk = selectChunk(this.chunks, offset)

        if (chunk !== null) {
          const m = chunk.field.BYTES_PER_ELEMENT

          const vec = chunk.field.subarray((offset - chunk.offset) / m, (offset - chunk.offset + 16) / m)

          allz = simdle.allz(vec)
          allo = simdle.allo(vec)
        }

        const k = i * 128 + 128 + j

        set(this.handle, bitOffset(false, k), allz)
        set(this.handle, bitOffset(true, k), allo)
      }

      {
        const offset = byteOffset(false, i * 16 + 16) / 4
        const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

        set(this.handle, bitOffset(false, i), allo)
      }

      {
        const offset = byteOffset(true, i * 16 + 16) / 4
        const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

        set(this.handle, bitOffset(true, i), allo)
      }
    }
  }

  get byteLength () {
    if (this._byteLength !== -1) return this._byteLength
    const last = this.chunks[this.chunks.length - 1]
    return last ? last.offset + last.field.byteLength : 0
  }

  update (bit) {
    const n = this.byteLength * 8

    if (bit < 0) bit += n
    if (bit < 0 || bit >= n) return false

    const i = Math.floor(bit / 16384)
    const j = Math.floor(bit / 128)

    const offset = j * 16

    const chunk = selectChunk(this.chunks, offset)

    if (chunk === null) return false

    const m = chunk.field.BYTES_PER_ELEMENT

    const vec = chunk.field.subarray((offset - chunk.offset) / m, (offset - chunk.offset + 16) / m)

    const allz = simdle.allz(vec)
    const allo = simdle.allo(vec)

    let changed = false

    if (set(this.handle, bitOffset(false, 128 + j), allz)) {
      changed = true

      const offset = byteOffset(false, i * 16 + 16) / 4
      const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

      set(this.handle, bitOffset(false, i), allo)
    }

    if (set(this.handle, bitOffset(true, 128 + j), allo)) {
      changed = true

      const offset = byteOffset(true, i * 16 + 16) / 4
      const allo = simdle.allo(this.handle.subarray(offset, offset + 4))

      set(this.handle, bitOffset(true, i), allo)
    }

    return changed
  }
}
const fallback = require('./fallback')

try {
  const native = require('quickbit-native')

  // These functions are faster in JavaScript
  exports.get = fallback.get
  exports.set = fallback.set
  exports.fill = fallback.fill

  // These functions are faster in C
  exports.clear = native.clear
  exports.findFirst = native.findFirst
  exports.findLast = native.findLast
  exports.Index = native.Index
} catch {
  module.exports = fallback
}
{
  "name": "quickbit-universal",
  "version": "2.2.0",
  "description": "Universal wrapper for libquickbit with a JavaScript fallback",
  "main": "index.js",
  "files": [
    "fallback.js",
    "index.js"
  ],
  "browser": {
    "./index.js": "./fallback.js"
  },
  "scripts": {
    "test": "standard && brittle test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/quickbit-universal.git"
  },
  "author": "Kasper Isager Dalsgarð <kasper@funktionel.co>",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/holepunchto/quickbit-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/quickbit-universal#readme",
  "dependencies": {
    "b4a": "^1.6.0",
    "simdle-universal": "^1.1.0"
  },
  "optionalDependencies": {
    "quickbit-native": "^2.2.0"
  },
  "devDependencies": {
    "brittle": "^3.1.0",
    "standard": "^17.0.0"
  }
}
class CacheEntry {
  constructor (key, index, map) {
    this.key = key
    this.index = index
    this.map = map
  }
}

class CacheValue {
  constructor (entry, value) {
    this.entry = entry
    this.value = value
  }
}

class Rache {
  constructor ({ maxSize = 65536, parent = null } = {}) {
    this.maxSize = parent?.maxSize || maxSize

    this._array = parent?._array || []
    this._map = new Map()
  }

  static from (cache) {
    return cache ? new this({ parent: cache }) : new this()
  }

  get globalSize () {
    return this._array.length
  }

  get size () {
    return this._map.size
  }

  sub () {
    return new Rache({ parent: this })
  }

  set (key, value) { // ~constant time
    const existing = this._map.get(key)
    if (existing !== undefined) {
      existing.value = value
      return
    }

    if (this._array.length >= this.maxSize) this._gc()

    const entry = new CacheEntry(key, this._array.length, this._map)
    this._array.push(entry)
    const cacheValue = new CacheValue(entry, value)
    this._map.set(key, cacheValue)
  }

  delete (key) {
    const existing = this._map.get(key)
    if (existing === undefined) return false

    this._delete(existing.entry.index)
    return true
  }

  get (key) {
    const existing = this._map.get(key)
    return existing === undefined ? undefined : existing.value
  }

  * [Symbol.iterator] () {
    for (const [key, { value }] of this._map) {
      yield [key, value]
    }
  }

  keys () {
    return this._map.keys()
  }

  * values () {
    for (const { value } of this._map.values()) {
      yield value
    }
  }

  clear () {
    // The entries in map linger on in _array,
    // so on top of clearing the map, we also kill the ref,
    // so that any gc running later on the old map won't interfere
    // (in case a new entry was added with the same key as a cleared entry)

    this._map.clear()
    this._map = new Map()
  }

  destroy () {
    this._map = null
    this._array = null
  }

  _gc () {
    this._delete(Math.floor(Math.random() * this._array.length))
  }

  _delete (index) { // ~constant time
    if (index >= this._array.length) throw new Error('Cannot delete unused index (logic bug?)')

    const head = this._array.pop()
    let removed = head

    if (index < this._array.length) {
      removed = this._array[index]
      head.index = index
      this._array[index] = head
    }

    removed.map.delete(removed.key)
  }
}

module.exports = Rache
{
  "name": "rache",
  "version": "1.0.0",
  "description": "Random-eviction cache",
  "main": "index.js",
  "scripts": {
    "test": "standard && brittle test.js --coverage"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/rache.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/rache/issues"
  },
  "homepage": "https://github.com/holepunchto/rache#readme",
  "files": [
    "index.js"
  ],
  "dependencies": {},
  "devDependencies": {
    "brittle": "^3.5.2",
    "standard": "^17.1.0"
  }
}
module.exports = class RandomArrayIterator {
  constructor (values) {
    this.values = values
    this.start = 0
    this.length = this.values.length
  }

  next () {
    if (this.length === 0) {
      if (this.start === 0) return { done: true, value: undefined }
      this.length = this.start
      this.start = 0
    }

    const i = this.start + ((Math.random() * this.length) | 0)
    const j = this.start + --this.length
    const value = this.values[i]

    this.values[i] = this.values[j]
    this.values[j] = value

    return { done: false, value }
  }

  dequeue () {
    this.values[this.start + this.length] = this.values[this.values.length - 1]
    this.values.pop()
  }

  requeue () {
    const i = this.start + this.length
    const value = this.values[i]
    this.values[i] = this.values[this.start]
    this.values[this.start++] = value
  }

  restart () {
    this.start = 0
    this.length = this.values.length
    return this
  }

  [Symbol.iterator] () {
    return this
  }
}
{
  "name": "random-array-iterator",
  "version": "1.0.0",
  "description": "An iterator to iterate an array in random order with controls to requeue or dequeue elements during the iteration",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^16.0.3",
    "tape": "^5.0.1"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/random-array-iterator.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/random-array-iterator/issues"
  },
  "homepage": "https://github.com/mafintosh/random-array-iterator"
}
const EventEmitter = require('events')

module.exports = class ReadyResource extends EventEmitter {
  constructor () {
    super()

    this.opening = null
    this.closing = null

    this.opened = false
    this.closed = false
  }

  ready () {
    if (this.opening !== null) return this.opening
    this.opening = open(this)
    return this.opening
  }

  close () {
    if (this.closing !== null) return this.closing
    this.closing = close(this)
    return this.closing
  }

  async _open () {
    // add impl here
  }

  async _close () {
    // add impl here
  }
}

async function open (self) {
  // open after close
  if (self.closing !== null) return

  try {
    await self._open()
  } catch (err) {
    self.close() // safe to run in bg
    throw err
  }

  self.opened = true
  self.emit('ready')
}

async function close (self) {
  try {
    if (self.opened === false && self.opening !== null) await self.opening
  } catch {
    // ignore errors on closing
  }
  if (self.opened === true || self.opening === null) await self._close()
  self.closed = true
  self.emit('close')
}
{
  "name": "ready-resource",
  "version": "1.2.0",
  "description": "Modern single resource management",
  "main": "index.js",
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "types": "index.d.ts",
  "files": [
    "index.js",
    "index.d.ts"
  ],
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "devDependencies": {
    "brittle": "^3.1.0",
    "standard": "^17.0.0"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/ready-resource.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/ready-resource/issues"
  },
  "homepage": "https://github.com/holepunchto/ready-resource",
  "dependencies": {
    "bare-events": "^2.2.0"
  }
}
const b4a = require('b4a')

var EMPTY = []

module.exports = RecordCache

function RecordSet () {
  this.list = []
  this.map = new Map()
}

RecordSet.prototype.add = function (record, value) {
  var k = toString(record)
  var r = this.map.get(k)
  if (r) return false

  r = {index: this.list.length, record: value || record}
  this.list.push(r)
  this.map.set(k, r)
  return true
}

RecordSet.prototype.remove = function (record) {
  var k = toString(record)
  var r = this.map.get(k)
  if (!r) return false

  swap(this.list, r.index, this.list.length - 1)
  this.list.pop()
  this.map.delete(k)
  return true
}

function RecordStore () {
  this.records = new Map()
  this.size = 0
}

RecordStore.prototype.add = function (name, record, value) {
  var r = this.records.get(name)

  if (!r) {
    r = new RecordSet()
    this.records.set(name, r)
  }

  if (r.add(record, value)) {
    this.size++
    return true
  }

  return false
}

RecordStore.prototype.remove = function (name, record, value) {
  var r = this.records.get(name)
  if (!r) return false

  if (r.remove(record, value)) {
    this.size--
    if (!r.map.size) this.records.delete(name)
    return true
  }

  return false
}

RecordStore.prototype.get = function (name) {
  var r = this.records.get(name)
  return r ? r.list : EMPTY
}

function RecordCache (opts) {
  if (!(this instanceof RecordCache)) return new RecordCache(opts)
  if (!opts) opts = {}

  this.maxSize = opts.maxSize || Infinity
  this.maxAge = opts.maxAge || 0

  this._onstale = opts.onStale || opts.onstale || null
  this._fresh = new RecordStore()
  this._stale = new RecordStore()
  this._interval = null
  this._gced = false

  if (this.maxAge && this.maxAge < Infinity) {
    // 2/3 gives us a span of 0.66-1.33 maxAge or avg maxAge
    var tick = Math.ceil(2 / 3 * this.maxAge)
    this._interval = setInterval(this._gcAuto.bind(this), tick)
    if (this._interval.unref) this._interval.unref()
  }
}

Object.defineProperty(RecordCache.prototype, 'size', {
  get: function () {
    return this._fresh.size + this._stale.size
  }
})

RecordCache.prototype.add = function (name, record, value) {
  this._stale.remove(name, record, value)
  if (this._fresh.add(name, record, value) && this._fresh.size > this.maxSize) {
    this._gc()
  }
}

RecordCache.prototype.remove = function (name, record, value) {
  this._fresh.remove(name, record, value)
  this._stale.remove(name, record, value)
}

RecordCache.prototype.get = function (name, n) {
  var a = this._fresh.get(name)
  var b = this._stale.get(name)
  var aLen = a.length
  var bLen = b.length
  var len = aLen + bLen

  if (n > len || !n) n = len
  var result = new Array(n)

  for (var i = 0; i < n; i++) {
    var j = Math.floor(Math.random() * (aLen + bLen))
    if (j < aLen) {
      result[i] = a[j].record
      swap(a, j, --aLen)
    } else {
      j -= aLen
      result[i] = b[j].record
      swap(b, j, --bLen)
    }
  }

  return result
}

RecordCache.prototype._gcAuto = function () {
  if (!this._gced) this._gc()
  this._gced = false
}

RecordCache.prototype._gc = function () {
  if (this._onstale && this._stale.size > 0) this._onstale(this._stale)
  this._stale = this._fresh
  this._fresh = new RecordStore()
  this._gced = true
}

RecordCache.prototype.clear = function () {
  this._gc()
  this._gc()
}

RecordCache.prototype.destroy = function () {
  this.clear()
  clearInterval(this._interval)
  this._interval = null
}

function toString (record) {
  return b4a.isBuffer(record) ? b4a.toString(record, 'hex') : record
}

function swap (list, a, b) {
  var tmp = list[a]
  tmp.index = b
  list[b].index = a
  list[a] = list[b]
  list[b] = tmp
}
{
  "name": "record-cache",
  "version": "1.2.0",
  "description": "Cache optimised for record like things",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.3.1"
  },
  "devDependencies": {
    "standard": "^10.0.3",
    "tape": "^4.8.0"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/record-cache.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/record-cache/issues"
  },
  "homepage": "https://github.com/mafintosh/record-cache"
}
module.exports = class RefCounter {
  constructor() {
    this.count = 0

    this._onidle = null
    this._idle = null
  }

  isIdle() {
    return this.count === 0
  }

  idle() {
    if (this.count === 0) return Promise.resolve()
    if (this._idle !== null) return this._idle

    this._idle = new Promise((resolve) => {
      this._onidle = resolve
    })

    return this._idle
  }

  inc() {
    this.count++
  }

  dec() {
    if (--this.count > 0) return

    if (this._onidle !== null) {
      const resolve = this._onidle
      this._idle = null
      this._onidle = null
      resolve()
    }
  }
}
{
  "name": "refcounter",
  "version": "1.0.0",
  "description": "Simple refcounter",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {},
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/refcounter.git"
  },
  "author": "Holepunch Inc",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/refcounter/issues"
  },
  "homepage": "https://github.com/holepunchto/refcounter"
}
module.exports = require.addon.bind(require)
{
  "name": "require-addon",
  "version": "1.2.0",
  "description": "Import native addons across JavaScript runtimes",
  "exports": {
    "./package": "./package.json",
    ".": {
      "bare": "./lib/bare.js",
      "node": "./lib/node.js",
      "default": "./lib/default.js"
    }
  },
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    },
    "url": {
      "bare": "bare-url",
      "default": "url"
    }
  },
  "files": [
    "lib"
  ],
  "scripts": {
    "test": "npm run lint && npm run test:bare && npm run test:node",
    "test:bare": "bare test.js",
    "test:node": "node test.js",
    "lint": "prettier --check .",
    "format": "prettier --write ."
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/require-addon.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/require-addon/issues"
  },
  "homepage": "https://github.com/holepunchto/require-addon#readme",
  "engines": {
    "bare": ">=1.10.0"
  },
  "dependencies": {
    "bare-addon-resolve": "^1.3.0"
  },
  "devDependencies": {
    "bare-bundle": "^1.8.1",
    "bare-bundle-evaluate": "^1.1.0",
    "bare-fs": "^4.0.0",
    "bare-path": "^3.0.0",
    "bare-url": "^2.1.0",
    "brittle": "^3.7.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
let tmpResolve = null
let tmpReject = null

if (Promise.withResolvers) {
  module.exports = Promise.withResolvers.bind(Promise)
} else {
  module.exports = function resolveRejectPromise () {
    const promise = new Promise(setTmp)
    const result = { promise, resolve: tmpResolve, reject: tmpReject }
    tmpResolve = tmpReject = null
    return result
  }
}

function setTmp (resolve, reject) {
  tmpResolve = resolve
  tmpReject = reject
}
{
  "name": "resolve-reject-promise",
  "version": "1.1.0",
  "description": "Create an inverted promise with no function allocs",
  "main": "index.js",
  "scripts": {
    "test": "standard"
  },
  "devDependencies": {
    "standard": "^17.1.2"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/resolve-reject-promise.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/resolve-reject-promise/issues"
  },
  "homepage": "https://github.com/mafintosh/resolve-reject-promise"
}
const resources = new Map()

exports.add = function(resource, teardown) {
  resources.set(resource, teardown)
}

exports.remove = function(resource) {
  resources.delete(resource)
}

if (global.Bare) global.Bare.on('exit', run)
else global.process.on('exit', run)

function run() {
  for (const [resource, teardown] of resources) {
    teardown(resource)
  }
}
{
  "name": "resource-on-exit",
  "version": "1.0.0",
  "description": "Register sync teardown handlers for a resource",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {},
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/bare-teardown.git"
  },
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/bare-teardown/issues"
  },
  "homepage": "https://github.com/holepunchto/bare-teardown"
}
require.addon = require('require-addon')

module.exports = require.addon('.', __filename)
const ColumnFamily = require('./lib/column-family')
const Iterator = require('./lib/iterator')
const Snapshot = require('./lib/snapshot')
const State = require('./lib/state')
const { BloomFilterPolicy, RibbonFilterPolicy } = require('./lib/filter-policy')
const constants = require('./lib/constants')

class RocksDB {
  constructor(path, opts = {}) {
    const {
      columnFamily,
      state = new State(this, path, opts),
      snapshot = null,
      keyEncoding = null,
      valueEncoding = null
    } = opts

    this._state = state
    this._snapshot = snapshot
    this._columnFamily = state.getColumnFamily(columnFamily)
    this._keyEncoding = keyEncoding
    this._valueEncoding = valueEncoding
    this._index = -1

    this._state.addSession(this)
  }

  get opened() {
    return this._state.opened
  }

  get closed() {
    return this.isRoot() ? this._state.closed : this._index === -1
  }

  get path() {
    return this._state.path
  }

  get stats() {
    return this._state.stats
  }

  get snapshotted() {
    return this._snapshot !== null
  }

  get defaultColumnFamily() {
    return this._columnFamily
  }

  session({
    columnFamily = this._columnFamily,
    snapshot = this._snapshot !== null,
    keyEncoding = this._keyEncoding,
    valueEncoding = this._valueEncoding
  } = {}) {
    maybeClosed(this)

    return new RocksDB(null, {
      state: this._state,
      columnFamily,
      snapshot: snapshot ? this._snapshot || new Snapshot(this._state) : null,
      keyEncoding,
      valueEncoding
    })
  }

  columnFamily(name, opts) {
    return this.session({ ...opts, columnFamily: name })
  }

  snapshot() {
    return this.session({ snapshot: true })
  }

  isRoot() {
    return this === this._state.db
  }

  ready() {
    return this._state.ready()
  }

  async close({ force } = {}) {
    if (!this._state.opened) await this._state.ready()

    if (this._index !== -1) this._state.removeSession(this)

    if (force) {
      while (this._state.sessions.length > 0) {
        await this._state.sessions[this._state.sessions.length - 1].close()
      }
    }

    return this.isRoot() ? this._state.close() : Promise.resolve()
  }

  suspend() {
    maybeClosed(this)

    return this._state.suspend()
  }

  resume() {
    maybeClosed(this)

    return this._state.resume()
  }

  isIdle() {
    return this._state.handles.isIdle()
  }

  idle() {
    return this._state.handles.idle()
  }

  iterator(range, opts) {
    maybeClosed(this)

    return new Iterator(this, { ...range, ...opts })
  }

  async *keys(range, opts) {
    for await (const { key } of this.iterator(range, {
      ...opts,
      values: false
    })) {
      yield key
    }
  }

  async peek(range, opts) {
    for await (const value of this.iterator({ ...range, ...opts, limit: 1 })) {
      return value
    }

    return null
  }

  read(opts) {
    maybeClosed(this)

    return this._state.createReadBatch(this, opts)
  }

  write(opts) {
    maybeClosed(this)

    return this._state.createWriteBatch(this, opts)
  }

  flush(opts) {
    maybeClosed(this)

    return this._state.flush(this, opts)
  }

  async get(key, opts) {
    const batch = this.read({ ...opts, capacity: 1, autoDestroy: true })
    const value = batch.get(key)
    batch.tryFlush()
    return value
  }

  async put(key, value, opts) {
    const batch = this.write({ ...opts, capacity: 1, autoDestroy: true })
    batch.tryPut(key, value)
    await batch.flush()
  }

  async delete(key, opts) {
    const batch = this.write({ ...opts, capacity: 1, autoDestroy: true })
    batch.tryDelete(key)
    await batch.flush()
  }

  async deleteRange(start, end, opts) {
    const batch = this.write({ ...opts, capacity: 1, autoDestroy: true })
    batch.tryDeleteRange(start, end)
    await batch.flush()
  }

  async compactRange(start = null, end = null, opts = {}) {
    if (typeof end === 'object' && end !== null) {
      opts = end
      end = null
    } else if (typeof start === 'object' && start !== null) {
      opts = start
      start = null
      end = null
    }

    await this._state.compactRange(this, start, end, opts)
  }

  async approximateSize(start, end, opts = {}) {
    return this._state.approximateSize(this, start, end, opts)
  }

  _ref() {
    if (this._snapshot) this._snapshot.ref()
    this._state.handles.inc()
  }

  _unref() {
    if (this._snapshot) this._snapshot.unref()
    this._state.handles.dec()
  }
}

module.exports = exports = RocksDB

exports.constants = constants

exports.ColumnFamily = ColumnFamily
exports.BloomFilterPolicy = BloomFilterPolicy
exports.RibbonFilterPolicy = RibbonFilterPolicy

function maybeClosed(db) {
  if (db._state.closing || db._index === -1) throw new Error('RocksDB session is closed')
}
const c = require('compact-encoding')
const binding = require('../binding')

const empty = Buffer.alloc(0)
const resolved = Promise.resolve()

class RocksDBBatch {
  constructor(db, opts = {}) {
    const { capacity = 8, autoDestroy = false } = opts

    db._ref()

    this._db = db
    this._destroyed = false
    this._capacity = capacity
    this._operations = []
    this._promises = []

    this._enqueuePromise = this._enqueuePromise.bind(this)

    this._request = null
    this._resolve = null
    this._reject = null

    this._handle = null
    this._buffer = null
    this._autoDestroy = autoDestroy
    this._stats = null

    this._resetStats()

    if (db._state.opened === true) this.ready()
  }

  _reuse(db, opts = {}) {
    const { autoDestroy = false } = opts

    db._ref()

    this._db = db
    this._destroyed = false
    this._autoDestroy = autoDestroy
  }

  _onfinished(err) {
    const resolve = this._resolve
    const reject = this._reject

    if (this._request) this._db._state.io.dec()

    this._operations = []
    this._promises = []
    this._request = null
    this._resolve = null
    this._reject = null

    this._resetStats()

    if (this._autoDestroy === true) this.destroy()

    if (reject !== null && err) reject(err)
    else if (resolve !== null) resolve()
  }

  _resize() {
    if (this._operations.length <= this._capacity) return false

    while (this._operations.length > this._capacity) {
      this._capacity *= 2
    }

    return true
  }

  async ready() {
    if (this._handle !== null) return

    if (this._db._state.opened === false) await this._db._state.ready()

    this._init()
  }

  destroy() {
    if (this._request) throw new Error('Request in progress')
    if (this._destroyed) return

    this._destroyed = true

    if (this._promises.length) this._abort()

    this._db._unref()
    this._onfree()
  }

  _onfree() {
    this._resetStats()
    this._db._state.freeBatch(this, false)
    this._db = null
  }

  _abort() {
    for (let i = 0; i < this._promises.length; i++) {
      const promise = this._promises[i]
      if (promise !== null) promise.reject(new Error('Batch is destroyed'))
    }

    this._onfinished(new Error('Batch is destroyed'))
  }

  _resetStats() {}

  async flush() {
    if (this._request) throw new Error('Request in progress')
    if (this._destroyed) throw new Error('Batch is destroyed')

    this._request = new Promise((resolve, reject) => {
      this._resolve = resolve
      this._reject = reject
    })

    this._flush()

    return this._request
  }

  tryFlush() {
    if (this._request) throw new Error('Request in progress')
    if (this._destroyed) throw new Error('Batch is destroyed')

    this._request = resolved

    this._flush()
  }

  async _flush() {
    if (this._handle === null) await this.ready()

    this._db._state.io.inc()

    if (this._db._state.resumed !== null) {
      const resumed = await this._db._state.resumed.promise

      if (!resumed) {
        if (this._destroyed) {
          this._db._state.io.dec()
        } else {
          this._destroyed = true
          this._abort()
          this._db._unref()
        }
      }
    }
  }

  _enqueuePromise(resolve, reject) {
    this._promises.push({ resolve, reject })
  }

  _encodeKey(k) {
    if (this._db._keyEncoding) return c.encode(this._db._keyEncoding, k)
    if (typeof k === 'string') return Buffer.from(k)
    return k
  }

  _encodeValue(v) {
    if (this._db._valueEncoding) return c.encode(this._db._valueEncoding, v)
    if (v === null) return empty
    if (typeof v === 'string') return Buffer.from(v)
    return v
  }

  _decodeValue(b) {
    if (this._db._valueEncoding) return c.decode(this._db._valueEncoding, b)
    return b
  }
}

exports.ReadBatch = class RocksDBReadBatch extends RocksDBBatch {
  constructor(db, opts = {}) {
    super(db, opts)

    const { asyncIO = false, fillCache = true } = opts

    this._asyncIO = asyncIO
    this._fillCache = fillCache
  }

  _init() {
    this._handle = binding.readInit()
    this._buffer = binding.readBuffer(this._handle, this._capacity)
  }

  _resize() {
    if (super._resize() && this._handle !== null) {
      this._buffer = binding.readBuffer(this._handle, this._capacity)
    }
  }

  async _flush() {
    await super._flush()

    if (this._destroyed) return

    try {
      binding.read(
        this._db._state._handle,
        this._handle,
        this._operations,
        this._db._snapshot ? this._db._snapshot._handle : undefined,
        this._asyncIO,
        this._fillCache,
        this,
        this._onread
      )
    } catch (err) {
      this._db._state.io.dec()
      throw err
    }

    this._db._state.stats.gets += this._stats.gets
    this._db._state.stats.readBatches++
  }

  _onread(errs, values) {
    let applied = true

    for (let i = 0, n = this._promises.length; i < n; i++) {
      const err = errs[i]
      if (err) applied = false

      const promise = this._promises[i]
      if (promise === null) continue

      if (err) promise.reject(err)
      else promise.resolve(values[i] ? this._decodeValue(Buffer.from(values[i])) : null)
    }

    this._onfinished(applied ? null : new AggregateError(errs, 'Batch was not applied'))
  }

  _resetStats() {
    this._stats = { gets: 0 }
  }

  get(key) {
    if (this._request) throw new Error('Request already in progress')
    this._stats.gets++

    const promise = new Promise(this._enqueuePromise)

    this._operations.push(new RocksDBGet(this._encodeKey(key), this._db._columnFamily))

    this._resize()

    return promise
  }
}

exports.WriteBatch = class RocksDBWriteBatch extends RocksDBBatch {
  _init() {
    this._handle = binding.writeInit()
    this._buffer = binding.writeBuffer(this._handle, this._capacity)
  }

  _resize() {
    if (super._resize() && this._handle !== null) {
      this._buffer = binding.writeBuffer(this._handle, this._capacity)
    }
  }

  _onfree() {
    this._resetStats()
    this._db._state.freeBatch(this, true)
    this._db = null
  }

  async _flush() {
    await super._flush()

    if (this._destroyed) return

    try {
      binding.write(this._db._state._handle, this._handle, this._operations, this, this._onwrite)
    } catch (err) {
      this._db._state.io.dec()
      throw err
    }

    this._db._state.stats.puts += this._stats.puts
    this._db._state.stats.deletes += this._stats.deletes
    this._db._state.stats.rangeDeletes += this._stats.rangeDeletes
    this._db._state.stats.writeBatches++
  }

  _onwrite(err) {
    const applied = !err

    for (let i = 0, n = this._promises.length; i < n; i++) {
      const promise = this._promises[i]
      if (promise === null) continue

      if (err) promise.reject(err)
      else promise.resolve()
    }

    this._onfinished(applied ? null : new Error('Batch was not applied', { cause: err }))
  }

  _resetStats() {
    this._stats = { puts: 0, deletes: 0, rangeDeletes: 0 }
  }

  put(key, value) {
    if (this._request) throw new Error('Request already in progress')
    this._stats.puts++

    const promise = new Promise(this._enqueuePromise)

    this._operations.push(
      new RocksDBPut(this._encodeKey(key), this._encodeValue(value), this._db._columnFamily)
    )

    this._resize()

    return promise
  }

  tryPut(key, value) {
    if (this._request) throw new Error('Request already in progress')
    this._stats.puts++

    this._operations.push(
      new RocksDBPut(this._encodeKey(key), this._encodeValue(value), this._db._columnFamily)
    )

    this._promises.push(null)

    this._resize()
  }

  delete(key) {
    if (this._request) throw new Error('Request already in progress')
    this._stats.deletes++

    const promise = new Promise(this._enqueuePromise)

    this._operations.push(new RocksDBDelete(this._encodeKey(key), this._db._columnFamily))

    this._resize()

    return promise
  }

  tryDelete(key) {
    if (this._request) throw new Error('Request already in progress')
    this._stats.deletes++

    this._operations.push(new RocksDBDelete(this._encodeKey(key), this._db._columnFamily))

    this._promises.push(null)

    this._resize()
  }

  deleteRange(start, end) {
    if (this._request) throw new Error('Request already in progress')
    this._stats.rangeDeletes++

    const promise = new Promise(this._enqueuePromise)

    this._operations.push(
      new RocksDBDeleteRange(this._encodeKey(start), this._encodeKey(end), this._db._columnFamily)
    )

    this._resize()

    return promise
  }

  tryDeleteRange(start, end) {
    if (this._request) throw new Error('Request already in progress')
    this._stats.rangeDeletes++

    this._operations.push(
      new RocksDBDeleteRange(this._encodeKey(start), this._encodeKey(end), this._db._columnFamily)
    )

    this._promises.push(null)

    this._resize()
  }
}

class RocksDBGet {
  constructor(key, columnFamily) {
    this.key = key
    this.columnFamily = columnFamily._handle
  }

  get type() {
    return binding.GET
  }
}

class RocksDBPut {
  constructor(key, value, columnFamily) {
    this.key = key
    this.value = value
    this.columnFamily = columnFamily._handle
  }

  get type() {
    return binding.PUT
  }
}

class RocksDBDelete {
  constructor(key, columnFamily) {
    this.key = key
    this.columnFamily = columnFamily._handle
  }

  get type() {
    return binding.DELETE
  }
}

class RocksDBDeleteRange {
  constructor(start, end, columnFamily) {
    this.start = start
    this.end = end
    this.columnFamily = columnFamily._handle
  }

  get type() {
    return binding.DELETE_RANGE
  }
}
const binding = require('../binding')
const constants = require('./constants')
const { BloomFilterPolicy } = require('./filter-policy')

class RocksDBColumnFamily {
  constructor(name, opts = {}) {
    const {
      // Blob options
      enableBlobFiles = false,
      minBlobSize = 0,
      blobFileSize = 0,
      enableBlobGarbageCollection = true,
      // Block table options
      tableBlockSize = 8192,
      tableCacheIndexAndFilterBlocks = true,
      tableFormatVersion = 6,
      optimizeFiltersForMemory = false,
      blockCache = true,
      filterPolicy = new BloomFilterPolicy(10),
      topLevelIndexPinningTier = constants.pinningTier.ALL,
      partitionPinningTier = constants.pinningTier.ALL,
      unpartitionedPinningTier = constants.pinningTier.ALL,
      optimizeFiltersForHits = false,
      numLevels = 7,
      maxWriteBufferNumber = 2,
      blobGarbageCollectionAgeCutOff = 0.25,
      blobGarbageCollectionForceThreshold = 1.0
    } = opts

    this._name = name
    this._flushing = null
    this._options = {
      enableBlobFiles,
      minBlobSize,
      blobFileSize,
      enableBlobGarbageCollection,
      tableBlockSize,
      tableCacheIndexAndFilterBlocks,
      tableFormatVersion,
      optimizeFiltersForMemory,
      blockCache,
      filterPolicy,
      topLevelIndexPinningTier,
      partitionPinningTier,
      unpartitionedPinningTier,
      optimizeFiltersForHits,
      numLevels,
      maxWriteBufferNumber,
      blobGarbageCollectionAgeCutOff,
      blobGarbageCollectionForceThreshold
    }

    const filterPolicyArguments = [0, 0, 0]

    if (filterPolicy !== null) {
      filterPolicyArguments[0] = filterPolicy.type

      switch (filterPolicy.type) {
        case 1: // Bloom filter policy
          filterPolicyArguments[1] = filterPolicy.bitsPerKey
          break
        case 2: // Ribbon filter policy
          filterPolicyArguments[1] = filterPolicy.bloomEquivalentBitsPerKey
          filterPolicyArguments[2] = filterPolicy.bloomBeforeLevel

          break
      }
    }

    this._handle = binding.columnFamilyInit(
      name,
      enableBlobFiles,
      minBlobSize,
      blobFileSize,
      enableBlobGarbageCollection,
      tableBlockSize,
      tableCacheIndexAndFilterBlocks,
      tableFormatVersion,
      optimizeFiltersForMemory,
      blockCache === false,
      ...filterPolicyArguments,
      topLevelIndexPinningTier,
      partitionPinningTier,
      unpartitionedPinningTier,
      optimizeFiltersForHits,
      numLevels,
      maxWriteBufferNumber,
      blobGarbageCollectionAgeCutOff,
      blobGarbageCollectionForceThreshold
    )
  }

  cloneSettings(name) {
    return new RocksDBColumnFamily(name, this._options)
  }

  get name() {
    return this._name
  }

  destroy() {
    if (this._handle === null) return

    binding.columnFamilyDestroy(this._handle)

    this._handle = null
  }
}

module.exports = RocksDBColumnFamily
module.exports = {
  pinningTier: {
    NONE: 0,
    FLUSHED_AND_SIMILAR: 1,
    ALL: 2
  },
  garbageCollectionPolicy: {
    DEFAULT: 0,
    FORCE: 1,
    DISABLE: 2
  },
  bottommostLevelCompaction: {
    NONE: 0,
    SKIP: 1,
    FORCE: 2
  },
  walRecoveryMode: {
    TOLERATE_CORRUPTED_TAIL_RECORDS: 0,
    ABSOLUTE_CONSISTENCY: 1,
    POINT_IN_TIME: 2,
    SKIP_ANY_CORRUPTED_RECORDS: 3
  }
}
exports.BloomFilterPolicy = class RocksDBBloomFilterPolicy {
  get type() {
    return 1
  }

  constructor(bitsPerKey) {
    this.bitsPerKey = bitsPerKey
  }
}

exports.RibbonFilterPolicy = class RocksDBRibbonFilterPolicy {
  get type() {
    return 2
  }

  constructor(bloomEquivalentBitsPerKey, bloomBeforeLevel = 0) {
    this.bloomEquivalentBitsPerKey = bloomEquivalentBitsPerKey
    this.bloomBeforeLevel = bloomBeforeLevel
  }
}
const { Readable } = require('streamx')
const c = require('compact-encoding')
const binding = require('../binding')

const empty = Buffer.alloc(0)

module.exports = class RocksDBIterator extends Readable {
  constructor(db, opts = {}) {
    const {
      gt = null,
      gte = null,
      lt = null,
      lte = null,
      reverse = false,
      values = true,
      limit = Infinity,
      capacity = 8
    } = opts

    super()

    db._ref()

    this._db = db

    this._gt = gt ? this._encodeKey(gt) : empty
    this._gte = gte ? this._encodeKey(gte) : empty
    this._lt = lt ? this._encodeKey(lt) : empty
    this._lte = lte ? this._encodeKey(lte) : empty

    this._reverse = reverse
    this._values = values
    this._limit = limit < 0 ? Infinity : limit
    this._capacity = capacity
    this._opened = false

    this._pendingOpen = null
    this._pendingRead = null
    this._pendingDestroy = null

    this._buffer = null
    this._handle = null

    if (this._db._state.opened === true) this.ready()
  }

  _onopen(err) {
    const cb = this._pendingOpen
    this._pendingOpen = null
    this._opened = true
    this._db._state.io.dec()
    cb(err)
  }

  _onread(err, keys, values) {
    const cb = this._pendingRead
    this._pendingRead = null
    this._db._state.io.dec()
    if (err) return cb(err)

    const n = keys.length

    this._limit -= n

    for (let i = 0; i < n; i++) {
      this.push({
        key: this._decodeKey(Buffer.from(keys[i])),
        value: this._values ? this._decodeValue(Buffer.from(values[i])) : null
      })
    }

    if (n < this._capacity) this.push(null)

    cb(null)
  }

  _onclose(err) {
    const cb = this._pendingDestroy
    this._pendingDestroy = null
    this._db._state.io.dec()
    this._db._unref()
    cb(err)
  }

  _resize() {
    if (this._handle !== null) {
      this._buffer = binding.iteratorBuffer(this._handle, this._capacity)
    }
  }

  async ready() {
    if (this._handle !== null) return

    if (this._db._state.opened === false) await this._db._state.ready()

    this._init()
  }

  _init() {
    this._handle = binding.iteratorInit()
    this._buffer = binding.iteratorBuffer(this._handle, this._capacity)
  }

  async _open(cb) {
    await this.ready()

    this._db._state.io.inc()

    if (this._db._state.resumed !== null) {
      const resumed = await this._db._state.resumed.promise

      if (!resumed) {
        this._db._state.io.dec()

        return cb(new Error('RocksDB session is closed'))
      }
    }

    this._pendingOpen = cb

    try {
      binding.iteratorOpen(
        this._db._state._handle,
        this._handle,
        this._db._columnFamily._handle,
        this._gt,
        this._gte,
        this._lt,
        this._lte,
        this._reverse,
        !this._values, // Keys only
        this._db._snapshot ? this._db._snapshot._handle : undefined,
        this,
        this._onopen,
        this._onclose,
        this._onread
      )
    } catch (err) {
      this._db._state.io.dec()

      cb(err)
    }
  }

  async _read(cb) {
    this._db._state.io.inc()

    if (this._db._state.resumed !== null) {
      const resumed = await this._db._state.resumed.promise

      if (!resumed) {
        this._db._state.io.dec()

        return cb(new Error('RocksDB session is closed'))
      }
    }

    this._pendingRead = cb

    try {
      binding.iteratorRead(this._handle, Math.min(this._capacity, this._limit))
    } catch (err) {
      this._db._state.io.dec()

      cb(err)
    }
  }

  async _destroy(cb) {
    await this.ready()

    this._db._state.io.inc()

    if (this._opened === false) {
      this._db._state.io.dec()
      this._db._unref()

      return cb(null)
    }

    this._pendingDestroy = cb

    try {
      binding.iteratorClose(this._handle)
    } catch (err) {
      this._db._state.io.dec()
      this._db._unref()

      cb(err)
    }
  }

  _encodeKey(k) {
    if (this._db._keyEncoding !== null) return c.encode(this._db._keyEncoding, k)
    if (typeof k === 'string') return Buffer.from(k)
    return k
  }

  _decodeKey(b) {
    if (this._db._keyEncoding !== null) return c.decode(this._db._keyEncoding, b)
    return b
  }

  _decodeValue(b) {
    if (this._db._valueEncoding !== null) return c.decode(this._db._valueEncoding, b)
    return b
  }
}
const binding = require('../binding')

module.exports = class RocksDBSnapshot {
  constructor(state) {
    this._state = state

    this._handle = null
    this._refs = 0

    if (state.deferSnapshotInit === false) this._init()
  }

  _init() {
    this._handle = binding.snapshotCreate(this._state._handle)
  }

  ref() {
    this._refs++
  }

  unref() {
    if (--this._refs > 0) return

    if (this._handle === null) return

    binding.snapshotDestroy(this._handle)

    this._handle = null
  }
}
const ReadyResource = require('ready-resource')
const RefCounter = require('refcounter')
const rrp = require('resolve-reject-promise')
const SignalPromise = require('signal-promise')
const c = require('compact-encoding')
const { ReadBatch, WriteBatch } = require('./batch')
const ColumnFamily = require('./column-family')
const binding = require('../binding')
const constants = require('./constants')

const MAX_BATCH_REUSE = 64
const empty = Buffer.alloc(0)

module.exports = class RocksDBState extends ReadyResource {
  constructor(db, path, opts) {
    super()

    const {
      columnFamily = new ColumnFamily('default', opts),
      columnFamilies = [],
      readOnly = false,
      createIfMissing = true,
      createMissingColumnFamilies = true,
      maxBackgroundJobs = 6,
      bytesPerSync = 1048576,
      maxOpenFiles = -1,
      useDirectReads = false,
      avoidUnnecessaryBlockingIO = false,
      skipStatsUpdateOnOpen = false,
      useDirectIOForFlushAndCompaction = false,
      maxFileOpeningThreads = 16,
      lock = null,
      walRecoveryMode = constants.walRecoveryMode.POINT_IN_TIME,
      bestEffortsRecovery = false
    } = opts

    this.path = path
    this.db = db
    this.handles = new RefCounter()
    this.io = new RefCounter()
    this.sessions = []
    this.columnFamilies = [columnFamily]
    this.deferSnapshotInit = true
    this.resumed = null
    this.stats = {
      gets: 0,
      puts: 0,
      deletes: 0,
      rangeDeletes: 0,
      readBatches: 0,
      writeBatches: 0
    }

    this._suspended = false
    this._suspending = false
    this._updating = false
    this._updatingSignal = new SignalPromise()
    this._columnsFlushed = false
    this._lock = lock
    this._readBatches = []
    this._writeBatches = []

    for (const columnFamily of columnFamilies) {
      this.columnFamilies.push(
        typeof columnFamily === 'string' ? new ColumnFamily(columnFamily, opts) : columnFamily
      )
    }

    this._handle = binding.init(
      readOnly,
      createIfMissing,
      createMissingColumnFamilies,
      maxBackgroundJobs,
      bytesPerSync,
      maxOpenFiles,
      useDirectReads,
      avoidUnnecessaryBlockingIO,
      skipStatsUpdateOnOpen,
      useDirectIOForFlushAndCompaction,
      maxFileOpeningThreads,
      walRecoveryMode,
      bestEffortsRecovery
    )
  }

  createReadBatch(db, opts) {
    if (this._readBatches.length === 0) return new ReadBatch(db, opts)
    const batch = this._readBatches.pop()
    batch._reuse(db, opts)
    return batch
  }

  createWriteBatch(db, opts) {
    if (this._writeBatches.length === 0) return new WriteBatch(db, opts)
    const batch = this._writeBatches.pop()
    batch._reuse(db, opts)
    return batch
  }

  freeBatch(batch, writable) {
    if (batch._capacity > 16) return
    const queue = writable ? this._writeBatches : this._readBatches
    if (queue.length >= MAX_BATCH_REUSE) return
    queue.push(batch)
  }

  addSession(db) {
    db._index = this.sessions.push(db) - 1
    if (db._snapshot) db._snapshot.ref()
  }

  removeSession(db) {
    const head = this.sessions.pop()
    if (head !== db) this.sessions[(head._index = db._index)] = head
    db._index = -1
    if (db._snapshot) db._snapshot.unref()
  }

  upsertColumnFamily(c) {
    if (typeof c === 'string') {
      let col = this.getColumnFamilyByName(c)
      if (col) return col
      col = this.columnFamilies[0].cloneSettings(c)
      this.columnFamilies.push(col)
      return col
    }

    if (this.columnFamilies.includes(c)) return c
    this.columnFamilies.push(c)
    return c
  }

  getColumnFamily(c) {
    if (!c) return this.columnFamilies[0]
    if (!this._columnsFlushed) return this.upsertColumnFamily(c)

    if (typeof c !== 'string') return c

    const col = this.getColumnFamilyByName(c)
    if (col === null) throw new Error('Unknown column family')
    return col
  }

  getColumnFamilyByName(name) {
    for (const col of this.columnFamilies) {
      if (col.name === name) return col
    }
    return null
  }

  async _open() {
    await Promise.resolve() // Allow column families to populate if on-demand

    if (this._lock) await this._lock.ready()

    const req = { resolve: null, reject: null, handle: null }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    this._columnsFlushed = true

    const lock = this._lock === null ? -1 : this._lock.transfer()

    req.handle = binding.open(
      this._handle,
      this,
      this.path,
      this.columnFamilies.map((c) => c._handle),
      lock,
      req,
      onopen
    )

    await promise

    this.deferSnapshotInit = false

    for (const session of this.sessions) {
      if (session._snapshot) session._snapshot._init()
    }

    function onopen(err) {
      if (err) req.reject(err)
      else req.resolve()
    }
  }

  async _close() {
    while (this._updating) await this._updatingSignal.wait()
    if (this.resumed) this.resumed.resolve(false)

    while (!this.io.isIdle()) await this.io.idle()
    while (!this.handles.isIdle()) await this.handles.idle()

    while (this.sessions.length > 0) {
      await this.sessions[this.sessions.length - 1].close()
    }

    for (const columnFamily of this.columnFamilies) columnFamily.destroy()

    const req = { resolve: null, reject: null, handle: null }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    req.handle = binding.close(this._handle, req, onclose)

    try {
      await promise
    } finally {
      if (this._lock) await this._lock.close()
    }

    function onclose(err) {
      if (err) req.reject(err)
      else req.resolve()
    }
  }

  async flush(db, opts) {
    if (this.opened === false) await this.ready()

    this.io.inc()

    if (this.resumed !== null) {
      const resumed = await this.resumed.promise

      if (!resumed) {
        this.io.dec()

        throw new Error('RocksDB session is closed')
      }
    }

    const req = { resolve: null, reject: null, handle: null }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    try {
      req.handle = binding.flush(this._handle, db._columnFamily._handle, req, onflush)

      await promise
    } finally {
      this.io.dec()
    }

    function onflush(err) {
      if (err) req.reject(err)
      else req.resolve()
    }
  }

  suspend() {
    this._suspending = true
    return this.update()
  }

  resume() {
    this._suspending = false
    return this.update()
  }

  async update() {
    while (this._updating) await this._updatingSignal.wait()
    if (this._suspending === this._suspended || this.closing) return
    this._updating = true
    try {
      if (this._suspending) await this._suspend()
      else await this._resume()
    } finally {
      this._updating = false
      this._updatingSignal.notify()
    }
  }

  async _suspend() {
    if (this._suspended === true) return

    while (!this.io.isIdle()) await this.io.idle()

    this.io.inc()
    this.resumed = rrp()

    const req = { resolve: null, reject: null, handle: null }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    try {
      req.handle = binding.suspend(this._handle, req, onsuspend)

      await promise

      this._suspended = true
    } finally {
      this.io.dec()
    }

    function onsuspend(err) {
      if (err) req.reject(err)
      else req.resolve()
    }
  }

  async _resume() {
    if (this._suspended === false) return

    const req = { resolve: null, reject: null, handle: null }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    req.handle = binding.resume(this._handle, req, onresume)

    await promise

    this._suspended = false

    const resumed = this.resumed
    this.resumed = null
    resumed.resolve(true)

    function onresume(err) {
      if (err) req.reject(err)
      else req.resolve()
    }
  }

  async compactRange(db, start, end, opts) {
    if (this.opened === false) await this.ready()

    this.io.inc()

    const {
      exclusive = false,
      blobGarbageCollectionPolicy = constants.garbageCollectionPolicy.DEFAULT,
      blobGarbageCollectionAgeCutoff = 0.25,
      bottommostLevelCompaction = constants.bottommostLevelCompaction.NONE
    } = opts

    start = this._encodeKey(start)
    end = this._encodeKey(end)

    const req = { resolve: null, reject: null, handle: null, start, end }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    try {
      req.handle = binding.compactRange(
        this._handle,
        db._columnFamily._handle,
        start,
        end,
        exclusive,
        blobGarbageCollectionPolicy,
        blobGarbageCollectionAgeCutoff,
        bottommostLevelCompaction,
        req,
        oncompactrange
      )

      await promise
    } finally {
      this.io.dec()
    }

    function oncompactrange(err) {
      if (err) req.reject(err)
      else req.resolve()
    }
  }

  async approximateSize(db, start, end, opts) {
    if (this.opened === false) await this.ready()

    this.io.inc()

    const { includeMemtables = false, includeFiles = true, filesSizeErrorMargin = -1 } = opts

    start = this._encodeKey(start)
    end = this._encodeKey(end)

    const req = { resolve: null, reject: null, handle: null, start, end }

    const promise = new Promise((resolve, reject) => {
      req.resolve = resolve
      req.reject = reject
    })

    try {
      req.handle = binding.approximateSize(
        this._handle,
        db._columnFamily._handle,
        start,
        end,
        includeMemtables,
        includeFiles,
        filesSizeErrorMargin,
        req,
        onapproximatesize
      )

      return await promise
    } finally {
      this.io.dec()
    }

    function onapproximatesize(err, result) {
      if (err) req.reject(err)
      else req.resolve(result)
    }
  }

  _encodeKey(k) {
    if (this.db._keyEncoding) return c.encode(this.db._keyEncoding, k)
    if (typeof k === 'string') return Buffer.from(k)
    if (k === null) return empty
    return k
  }
}
{
  "name": "rocksdb-native",
  "version": "3.15.2",
  "description": "librocksdb bindings for JavaScript",
  "exports": {
    ".": "./index.js",
    "./package": "./package.json"
  },
  "imports": {
    "crypto": {
      "bare": "bare-crypto",
      "default": "crypto"
    },
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    }
  },
  "files": [
    "index.js",
    "binding.cc",
    "binding.js",
    "CMakeLists.txt",
    "lib",
    "prebuilds",
    "!prebuilds/android-*/**/*.node"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write . && lunte --fix",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:bare && npm run test:node",
    "test:bare": "brittle-bare --coverage test.js",
    "test:node": "brittle-node --coverage test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/rocksdb-native.git"
  },
  "author": "Holepunch Inc",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/rocksdb-native/issues"
  },
  "homepage": "https://github.com/holepunchto/rocksdb-native",
  "engines": {
    "bare": ">=1.16.0"
  },
  "dependencies": {
    "compact-encoding": "^3.0.0",
    "ready-resource": "^1.0.0",
    "refcounter": "^1.0.0",
    "require-addon": "^1.0.2",
    "resolve-reject-promise": "^1.1.0",
    "signal-promise": "^1.0.3",
    "streamx": "^2.16.1"
  },
  "devDependencies": {
    "bare-compat-napi": "^1.3.0",
    "bare-crypto": "^1.12.0",
    "bare-fs": "^4.5.0",
    "bare-path": "^3.0.0",
    "brittle": "^3.5.0",
    "cmake-bare": "^1.1.14",
    "cmake-fetch": "^1.0.1",
    "cmake-napi": "^1.0.6",
    "fd-lock": "^2.0.0",
    "lunte": "^1.8.0",
    "paparam": "^1.9.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = safetyCatch

function isActuallyUncaught (err) {
  if (!err) return false
  return err instanceof TypeError ||
    err instanceof SyntaxError ||
    err instanceof ReferenceError ||
    err instanceof EvalError ||
    err instanceof RangeError ||
    err instanceof URIError ||
    err.code === 'ERR_ASSERTION' ||
    err.name === 'AssertionError'
}

function throwErrorNT (err) {
  queueMicrotask(() => { throw err })
}

function safetyCatch (err) {
  if (isActuallyUncaught(err)) {
    throwErrorNT(err)
    throw err
  }
}
{
  "name": "safety-catch",
  "version": "1.0.3",
  "description": "Small module that makes sure your catch, caught an actual error and not a programming mistake or assertion",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {},
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/safety-catch.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/safety-catch/issues"
  },
  "homepage": "https://github.com/mafintosh/safety-catch"
}
let tmpResolve = null

module.exports = class ScopeLock {
  constructor ({ debounce = false } = {}) {
    this.debounce = debounce
    this.waiting = []
    this.locked = false
    this.skip = 0
    this.destroyed = false
  }

  flush () {
    if (this.locked === false && this.waiting.length === 0) return Promise.resolve(this.destroyed === false)

    const promise = new Promise(setTmpResolve)
    const resolve = tmpResolve

    tmpResolve = null
    this.waiting.push({ lock: false, resolve })

    return promise
  }

  destroy () {
    this.destroyed = true
  }

  lock () {
    const promise = new Promise(setTmpResolve)
    const resolve = tmpResolve

    tmpResolve = null

    if (this.locked === true) {
      this.waiting.push({ lock: true, resolve })
      return promise
    }

    if (this.destroyed === true) {
      resolve(false)
      return promise
    }

    this.locked = true
    resolve(true)

    return promise
  }

  unlock () {
    if (this.destroyed === true) {
      for (let i = 0; i < this.waiting.length; i++) {
        this.waiting[i].resolve(false)
      }
      this.waiting = []
      this.skip = 0
      this.locked = false
      return
    }

    if (this.skip !== 0) {
      for (let i = 0; i < this.skip; i++) {
        const { lock, resolve } = this.waiting[i]
        resolve(lock === false)
      }

      this.waiting = this.waiting.slice(this.skip)
      this.skip = 0
    }

    while (this.waiting.length > 0 && this.waiting[0].lock === false) {
      this.waiting.shift().resolve(true)
    }

    if (this.waiting.length === 0) {
      this.locked = false
      return
    }

    const { resolve } = this.waiting.shift()
    if (this.debounce === true) this.skip = this.waiting.length

    resolve(true)
  }
}

function setTmpResolve (resolve) {
  tmpResolve = resolve
}
{
  "name": "scope-lock",
  "version": "1.2.4",
  "description": "Some concurrency semantics around entering scopes",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "devDependencies": {
    "brittle": "^3.7.0",
    "standard": "^17.1.2"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/scope-lock.git"
  },
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/scope-lock/issues"
  },
  "homepage": "https://github.com/holepunchto/scope-lock"
}
const set = require('unordered-set')

module.exports = opts => new ShuffledPriorityQueue(opts)

class ShuffledPriorityQueue {
  constructor (opts) {
    this.priorities = []
    this.equals = (opts && opts.equals) || null
  }

  get length () {
    return this.priorities.reduce(add, 0)
  }

  [Symbol.iterator] () {
    return new Iterator(this)
  }

  head () {
    for (let i = this.priorities.length - 1; i >= 0; i--) {
      const q = this.priorities[i]
      if (q.length) return shuffle(q, 0)
    }
    return null
  }

  tail () {
    for (let i = 0; i < this.priorities.length; i++) {
      const q = this.priorities[i]
      if (q.length) return shuffle(q, 0)
    }
    return null
  }

  prev (prev) {
    if (!prev) return this.tail()
    return next(this.priorities, prev, 1)
  }

  next (prev) {
    if (!prev) return this.head()
    return next(this.priorities, prev, -1)
  }

  shift () {
    return this.remove(this.head())
  }

  pop () {
    return this.remove(this.tail())
  }

  add (val) {
    const prio = val.priority || 0
    while (prio >= this.priorities.length) this.priorities.push([])
    set.add(this.priorities[prio], val)
    return val
  }

  remove (val) {
    if (!val) return null

    if (val._index === undefined) {
      val = this.find(val)
      if (!val) return null
    }

    return set.remove(this.priorities[val.priority || 0], val)
  }

  has (val) {
    if (val._index === undefined) return this.find(val)
    const priority = val.priority || 0
    if (priority >= this.priorities.length) return false
    return set.has(this.priorities[priority], val)
  }

  find (val) {
    if (val._index !== undefined) return val

    const prio = val.priority || 0
    const qs = this.priorities
    if (prio >= qs.length) return null

    const q = qs[prio]

    for (let i = 0; i < q.length; i++) {
      if (this.equals(q[i], val)) return q[i]
    }

    return null
  }
}

class Iterator {
  constructor (queue) {
    this.prev = null
    this.queue = queue
  }

  next () {
    const next = this.queue.next(this.prev)
    this.prev = next
    return { done: !next, value: next }
  }
}

function shuffle (q, i) {
  const ran = i + Math.floor(Math.random() * (q.length - i))
  set.swap(q, q[ran], q[i])
  return q[i]
}

function next (queues, prev, inc) {
  let i = prev.priority || 0
  let j = (prev._index || 0) + 1

  while (true) {
    if (i < 0 || i >= queues.length) return null
    const q = queues[i]

    if (j >= q.length) {
      i += inc
      j = 0
      continue
    }

    return shuffle(q, j)
  }
}

function add (len, b) {
  return len + b.length
}
{
  "name": "shuffled-priority-queue",
  "version": "2.1.0",
  "description": "A priority queue that shuffles elements with the same priority.",
  "main": "index.js",
  "scripts": {
    "test": "standard && tape test.js"
  },
  "dependencies": {
    "unordered-set": "^2.0.1"
  },
  "devDependencies": {
    "standard": "^12.0.1",
    "tape": "^4.9.1"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/shuffled-priority-queue.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/shuffled-priority-queue/issues"
  },
  "homepage": "https://github.com/mafintosh/shuffled-priority-queue"
}
module.exports = class Signal {
  constructor () {
    this._resolve = null
    this._reject = null
    this._promise = null
    this._bind = bind.bind(this)
    this._onerror = clear.bind(this)
    this._onsuccess = clear.bind(this, null)
    this._timers = new Set()
  }

  wait (max) {
    if (!this._promise) {
      this._promise = new Promise(this._bind)
      this._promise.then(this._onsuccess).catch(this._onerror)
    }
    if (max) return this._sleep(max)
    return this._promise
  }

  _sleep (max) {
    const s = new Promise((resolve, reject) => {
      const done = () => {
        this._timers.delete(state)
        resolve(true)
      }
      const id = setTimeout(done, max)
      const state = { id, resolve, reject }
      this._timers.add(state)
    })

    return s
  }

  notify (err) {
    if (!this._promise) return
    const resolve = this._resolve
    const reject = this._reject
    this._promise = null
    if (err) reject(err)
    else resolve(true)
  }
}

function clear (err) {
  for (const { id, resolve, reject } of this._timers) {
    clearTimeout(id)
    if (err) reject(err)
    else resolve(true)
  }
  this._timers.clear()
}

function bind (resolve, reject) {
  this._resolve = resolve
  this._reject = reject
}
{
  "name": "signal-promise",
  "version": "1.0.3",
  "description": "Simple wait/notify promise with optional max wait time",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {},
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/signal-promise.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/signal-promise/issues"
  },
  "homepage": "https://github.com/mafintosh/signal-promise"
}
var varint = require('varint')
exports.encode = function encode (v, b, o) {
  v = v >= 0 ? v*2 : v*-2 - 1
  var r = varint.encode(v, b, o)
  encode.bytes = varint.encode.bytes
  return r
}
exports.decode = function decode (b, o) {
  var v = varint.decode(b, o)
  decode.bytes = varint.decode.bytes
  return v & 1 ? (v+1) / -2 : v / 2
}

exports.encodingLength = function (v) {
  return varint.encodingLength(v >= 0 ? v*2 : v*-2 - 1)
}
{
  "name": "signed-varint",
  "description": "efficiently store signed integers in varint",
  "version": "2.0.1",
  "homepage": "https://github.com/dominictarr/signed-varint",
  "repository": {
    "type": "git",
    "url": "git://github.com/dominictarr/signed-varint.git"
  },
  "dependencies": {
    "varint": "~5.0.0"
  },
  "devDependencies": {
    "tape": "~2.12.3"
  },
  "scripts": {
    "test": "node test.js"
  },
  "author": "Dominic Tarr <dominic.tarr@gmail.com> (http://dominictarr.com)",
  "license": "MIT"
}
require.addon = require('require-addon')

module.exports = require.addon('.', __filename)
const binding = require('./binding')
const b4a = require('b4a')

function predicate(u8, u16, u32) {
  return function predicate(buf) {
    if (buf.byteLength % 16 !== 0) {
      throw new Error('Buffer length must be a multiple of 16')
    }

    const n = buf.BYTES_PER_ELEMENT

    if (n === 1) return u8(buf)
    if (n === 2) return u16(buf)
    return u32(buf)
  }
}

function unary(u8, u16, u32) {
  return function unary(buf, result = b4a.allocUnsafe(buf.byteLength)) {
    if (buf.byteLength % 16 !== 0) {
      throw new Error('Buffer length must be a multiple of 16')
    }

    if (buf.byteLength !== result.byteLength) {
      throw new Error('Length of result buffer is insufficient')
    }

    const n = buf.BYTES_PER_ELEMENT

    if (n === 1) u8(buf, result)
    else if (n === 2) u16(buf, result)
    else u32(buf, result)

    return result
  }
}

function binary(u8, u16, u32) {
  return function binary(a, b, result = b4a.allocUnsafe(a.byteLength)) {
    if (a.byteLength % 16 !== 0) {
      throw new Error('Buffer length must be a multiple of 16')
    }

    if (a.byteLength !== b.byteLength || a.byteLength !== result.byteLength) {
      throw new Error('Buffers must be the same length')
    }

    const n = a.BYTES_PER_ELEMENT

    if (n === 1) u8(a, b, result)
    else if (n === 2) u16(a, b, result)
    else u32(a, b, result)

    return result
  }
}

function reduce(u8, u16, u32) {
  return function reduce(buf) {
    if (buf.byteLength % 16 !== 0) {
      throw new Error('Buffer length must be a multiple of 16')
    }

    const n = buf.BYTES_PER_ELEMENT

    if (n === 1) return u8(buf)
    if (n === 2) return u16(buf)
    return u32(buf)
  }
}

exports.allo = predicate(
  binding.simdle_native_allo_v128_u8,
  binding.simdle_native_allo_v128_u16,
  binding.simdle_native_allo_v128_u32
)

exports.allz = predicate(
  binding.simdle_native_allz_v128_u8,
  binding.simdle_native_allz_v128_u16,
  binding.simdle_native_allz_v128_u32
)

exports.and = binary(
  binding.simdle_native_and_v128_u8,
  binding.simdle_native_and_v128_u16,
  binding.simdle_native_and_v128_u32
)

exports.clear = binary(
  binding.simdle_native_clear_v128_u8,
  binding.simdle_native_clear_v128_u16,
  binding.simdle_native_clear_v128_u32
)

exports.clo = unary(
  binding.simdle_native_clo_v128_u8,
  binding.simdle_native_clo_v128_u16,
  binding.simdle_native_clo_v128_u32
)

exports.clz = unary(
  binding.simdle_native_clz_v128_u8,
  binding.simdle_native_clz_v128_u16,
  binding.simdle_native_clz_v128_u32
)

exports.cnt = unary(
  binding.simdle_native_cnt_v128_u8,
  binding.simdle_native_cnt_v128_u16,
  binding.simdle_native_cnt_v128_u32
)

exports.cto = unary(
  binding.simdle_native_cto_v128_u8,
  binding.simdle_native_cto_v128_u16,
  binding.simdle_native_cto_v128_u32
)

exports.ctz = unary(
  binding.simdle_native_ctz_v128_u8,
  binding.simdle_native_ctz_v128_u16,
  binding.simdle_native_ctz_v128_u32
)

exports.not = unary(
  binding.simdle_native_not_v128_u8,
  binding.simdle_native_not_v128_u16,
  binding.simdle_native_not_v128_u32
)

exports.or = binary(
  binding.simdle_native_or_v128_u8,
  binding.simdle_native_or_v128_u16,
  binding.simdle_native_or_v128_u32
)

exports.sum = reduce(
  binding.simdle_native_sum_v128_u8,
  binding.simdle_native_sum_v128_u16,
  binding.simdle_native_sum_v128_u32
)

exports.xor = binary(
  binding.simdle_native_xor_v128_u8,
  binding.simdle_native_xor_v128_u16,
  binding.simdle_native_xor_v128_u32
)
{
  "name": "simdle-native",
  "version": "1.3.9",
  "description": "libsimdle JavaScript bindings for Node.js",
  "main": "index.js",
  "files": [
    "index.js",
    "binding.cc",
    "binding.js",
    "CMakeLists.txt",
    "prebuilds"
  ],
  "addon": true,
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check .",
    "test": "npm run lint && npm run test:bare && npm run test:node",
    "test:bare": "bare test.mjs",
    "test:node": "node test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/simdle-native.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/simdle-native/issues"
  },
  "homepage": "https://github.com/holepunchto/simdle-native#readme",
  "dependencies": {
    "b4a": "^1.6.0",
    "require-addon": "^1.1.0"
  },
  "devDependencies": {
    "bare-compat-napi": "^1.3.2",
    "brittle": "^3.1.0",
    "cmake-bare": "^1.1.7",
    "cmake-fetch": "^1.1.0",
    "cmake-napi": "^1.0.2",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  }
}
const b4a = require('b4a')
const scalar = require('./scalar')

function view (buf, n) {
  if (n === buf.BYTES_PER_ELEMENT) return buf

  let TypedArray

  if (n === 1) TypedArray = Uint8Array
  else if (n === 2) TypedArray = Uint16Array
  else TypedArray = Uint32Array

  return new TypedArray(buf.buffer, buf.byteOffset, buf.byteLength / n)
}

function unary (u8, u16 = u8, u32 = u16) {
  return function unary (buf, result = b4a.allocUnsafe(buf.byteLength)) {
    if (buf.byteLength % 16 !== 0) {
      throw new Error('Buffer length must be a multiple of 16')
    }

    if (buf.byteLength !== result.byteLength) {
      throw new Error('Length of result buffer is insufficient')
    }

    const n = buf.BYTES_PER_ELEMENT

    if (n === 1) u8(buf, view(result, n))
    else if (n === 2) u16(buf, view(result, n))
    else u32(buf, view(result, n))

    return result
  }
}

function binary (u8, u16 = u8, u32 = u16) {
  return function binary (a, b, result = b4a.allocUnsafe(a.byteLength)) {
    if (a.byteLength % 16 !== 0) {
      throw new Error('Buffer length must be a multiple of 16')
    }

    if (a.byteLength !== b.byteLength || a.byteLength !== result.byteLength) {
      throw new Error('Buffers must be the same length')
    }

    const n = a.BYTES_PER_ELEMENT

    if (n === 1) u8(a, b, view(result, n))
    else if (n === 2) u16(a, b, view(result, n))
    else u32(a, b, view(result, n))

    return result
  }
}

function reduce (u8, u16 = u8, u32 = u16) {
  return function reduce (buf) {
    if (buf.byteLength % 16 !== 0) {
      throw new Error('Buffer length must be a multiple of 16')
    }

    const n = buf.BYTES_PER_ELEMENT

    if (n === 1) return u8(buf)
    if (n === 2) return u16(buf)
    return u32(buf)
  }
}

exports.allo = function allo (buf) {
  if (buf.byteLength % 16 !== 0) {
    throw new Error('Buffer length must be a multiple of 16')
  }

  const m = 2 ** (buf.BYTES_PER_ELEMENT * 8) - 1

  for (let i = 0, n = buf.length; i < n; i++) {
    if (buf[i] !== m) return false
  }

  return true
}

exports.allz = function allz (buf) {
  if (buf.byteLength % 16 !== 0) {
    throw new Error('Buffer length must be a multiple of 16')
  }

  for (let i = 0, n = buf.length; i < n; i++) {
    if (buf[i] !== 0) return false
  }

  return true
}

exports.and = binary(
  (a, b, result) => {
    for (let i = 0, n = result.length; i < n; i++) {
      result[i] = a[i] & b[i]
    }
  }
)

exports.clear = binary(
  (a, b, result) => {
    for (let i = 0, n = result.length; i < n; i++) {
      result[i] = a[i] & ~b[i]
    }
  }
)

exports.clo = unary(
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = 24 - scalar.clo(buf[i])
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = 16 - scalar.clo(buf[i])
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = scalar.clo(buf[i])
    }
  }
)

exports.clz = unary(
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = 24 - scalar.clz(buf[i])
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = 16 - scalar.clz(buf[i])
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = scalar.clz(buf[i])
    }
  }
)

exports.cnt = unary(
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = scalar.cnt(buf[i]) & 0xff
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = scalar.cnt(buf[i]) & 0xffff
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = scalar.cnt(buf[i])
    }
  }
)

exports.cto = unary(
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = Math.min(scalar.cto(buf[i]), 8)
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = Math.min(scalar.cto(buf[i]), 16)
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = scalar.cto(buf[i])
    }
  }
)

exports.ctz = unary(
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = Math.min(scalar.ctz(buf[i]), 8)
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = Math.min(scalar.ctz(buf[i]), 16)
    }
  },
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = scalar.ctz(buf[i])
    }
  }
)

exports.not = unary(
  (buf, result) => {
    for (let i = 0, n = buf.length; i < n; i++) {
      result[i] = ~buf[i]
    }
  }
)

exports.or = binary(
  (a, b, result) => {
    for (let i = 0, n = result.length; i < n; i++) {
      result[i] = a[i] | b[i]
    }
  }
)

exports.sum = reduce(
  (buf) => {
    let result = 0n

    for (let i = 0, n = buf.length; i < n; i++) {
      result += BigInt(buf[i])
    }

    return result
  }
)

exports.xor = binary(
  (a, b, result) => {
    for (let i = 0, n = result.length; i < n; i++) {
      result[i] = a[i] ^ b[i]
    }
  }
)
try {
  module.exports = require('simdle-native')
} catch {
  module.exports = require('./fallback')
}
{
  "name": "simdle-universal",
  "version": "1.1.2",
  "description": "Universal wrapper for libsimdle with a JavaScript fallback",
  "main": "index.js",
  "files": [
    "fallback.js",
    "index.js",
    "scalar.js"
  ],
  "browser": {
    "./index.js": "./fallback.js"
  },
  "scripts": {
    "test": "standard && brittle test.mjs"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/simdle-universal.git"
  },
  "author": "Kasper Isager Dalsgarð <kasper@funktionel.co>",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/holepunchto/simdle-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/simdle-universal#readme",
  "dependencies": {
    "b4a": "^1.6.0"
  },
  "optionalDependencies": {
    "simdle-native": "^1.1.1"
  },
  "devDependencies": {
    "brittle": "^3.1.0",
    "standard": "^17.0.0"
  }
}
const clz = exports.clz = function clz (n) {
  return Math.clz32(n)
}

exports.clo = function clo (n) {
  return clz(~n)
}

const ctz = exports.ctz = function ctz (n) {
  return 32 - (n === 0 ? 0 : (clz(n & -n) + 1))
}

exports.cto = function cto (n) {
  return ctz(~n)
}

exports.cnt = function cnt (n) {
  n = n - ((n >>> 1) & 0x55555555)
  n = (n & 0x33333333) + ((n >>> 2) & 0x33333333)
  n = (n + (n >>> 4)) & 0x0f0f0f0f
  n = (n * 0x01010101) >>> 24
  return n
}
require.addon = require('require-addon')
module.exports = require.addon('.', __filename)
const assert = require('assert')
const binding = require('./binding')
const { isNode } = require('which-runtime')

const OPTIONAL = Buffer.from(new ArrayBuffer(0))

module.exports = exports = { ...binding }

// memory

exports.sodium_memzero = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  binding.sodium_memzero(buf)
}

exports.sodium_mlock = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  const res = binding.sodium_mlock(buf)

  if (res !== 0) throw new Error('memory lock failed')
}

exports.sodium_munlock = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  const res = binding.sodium_munlock(buf)

  if (res !== 0) throw new Error('memory unlock failed')
}

exports.sodium_malloc = function (size) {
  assert(size >= 0, 'invalid size')

  const buf = Buffer.from(binding.sodium_malloc(size))
  buf.secure = true
  return buf
}

exports.sodium_free = function (buf) {
  if (!buf || !buf.secure) return

  binding.sodium_free(buf.buffer)
}

exports.sodium_mprotect_noaccess = function (buf) {
  const res = binding.sodium_mprotect_noaccess(buf.buffer)

  if (res !== 0) throw new Error('failed to lock buffer')
}

exports.sodium_mprotect_readonly = function (buf) {
  const res = binding.sodium_mprotect_readonly(buf.buffer)

  if (res !== 0) throw new Error('failed to unlock buffer')
}

exports.sodium_mprotect_readwrite = function (buf) {
  const res = binding.sodium_mprotect_readwrite(buf.buffer)

  if (res !== 0) throw new Error('failed to unlock buffer')
}

// crypto_randombytes

exports.randombytes_buf = function (buffer) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')

  binding.randombytes_buf(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

exports.randombytes_buf_deterministic = function (buffer, seed) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    seed.byteLength === binding.randombytes_SEEDBYTES,
    "seed must be 'randombytes_SEEDBYTES' bytes"
  )

  binding.randombytes_buf_deterministic(
    buffer.buffer,
    buffer.byteOffset,
    buffer.byteLength,

    seed.buffer,
    seed.byteOffset,
    seed.byteLength
  )
}

// sodium_helpers

exports.sodium_memcmp = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  return binding.sodium_memcmp(a, b)
}

exports.sodium_add = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  binding.sodium_add(a, b)
}

exports.sodium_sub = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  binding.sodium_sub(a, b)
}

exports.sodium_compare = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  return binding.sodium_compare(a, b)
}

exports.sodium_is_zero = function (buffer, length) {
  if (length === undefined) length = buffer.byteLength

  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(length >= 0 && length <= buffer.byteLength, 'invalid length')

  return binding.sodium_is_zero(buffer, length)
}

exports.sodium_pad = function (buffer, unpaddedBuflen, blockSize) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(unpaddedBuflen <= buffer.byteLength, 'unpadded length cannot exceed buffer length')
  assert(blockSize <= buffer.byteLength, 'block size cannot exceed buffer length')
  assert(blockSize >= 1, 'block size must be at least 1 byte')
  assert(
    buffer.byteLength >= unpaddedBuflen + (blockSize - (unpaddedBuflen % blockSize)),
    'buf not long enough'
  )

  return binding.sodium_pad(buffer, unpaddedBuflen, blockSize)
}

exports.sodium_unpad = function (buffer, paddedBuflen, blockSize) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(paddedBuflen <= buffer.byteLength, 'unpadded length cannot exceed buffer length')
  assert(blockSize <= buffer.byteLength, 'block size cannot exceed buffer length')
  assert(blockSize >= 1, 'block size must be at least 1 byte')

  return binding.sodium_unpad(buffer, paddedBuflen, blockSize)
}

// crypto_sign

exports.crypto_sign_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )
  assert(
    seed.byteLength === binding.crypto_sign_SEEDBYTES,
    "seed must be 'crypto_sign_SEEDBYTES' bytes"
  )

  const res = binding.crypto_sign_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign = function (sm, m, sk) {
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sm.byteLength === binding.crypto_sign_BYTES + m.byteLength,
    "sm must be 'm.byteLength + crypto_sign_BYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign(sm, m, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_open = function (m, sm, pk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sm.byteLength >= binding.crypto_sign_BYTES,
    "sm must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    m.byteLength === sm.byteLength - binding.crypto_sign_BYTES,
    "m must be 'sm.byteLength - crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_open(m, sm, pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_open = function (m, sm, pk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sm.byteLength >= binding.crypto_sign_BYTES,
    "sm must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    m.byteLength === sm.byteLength - binding.crypto_sign_BYTES,
    "m must be 'sm.byteLength - crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  return binding.crypto_sign_open(m, sm, pk)
}

exports.crypto_sign_detached = function (sig, m, sk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(sig.byteLength === binding.crypto_sign_BYTES, "sig must be 'crypto_sign_BYTES' bytes")
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_detached(sig, m, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_verify_detached = function (sig, m, pk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sig.byteLength >= binding.crypto_sign_BYTES,
    "sig must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  return binding.crypto_sign_verify_detached(
    sig.buffer,
    sig.byteOffset,
    sig.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    pk.buffer,
    pk.byteOffset,
    pk.byteLength
  )
}

exports.crypto_sign_ed25519_sk_to_pk = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_sk_to_pk(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_ed25519_pk_to_curve25519 = function (x25519pk, ed25519pk) {
  assert(ArrayBuffer.isView(x25519pk), 'x25519pk must be a typed array')
  assert(ArrayBuffer.isView(ed25519pk), 'ed25519pk must be a typed array')
  assert(
    x25519pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "x25519pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    ed25519pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "ed25519pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_pk_to_curve25519(x25519pk, ed25519pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_ed25519_sk_to_curve25519 = function (x25519sk, ed25519sk) {
  assert(ArrayBuffer.isView(x25519sk), 'x25519sk must be a typed array')
  assert(ArrayBuffer.isView(ed25519sk), 'ed25519sk must be a typed array')
  assert(
    x25519sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "x25519sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const edLen = ed25519sk.byteLength

  assert(
    edLen === binding.crypto_sign_SECRETKEYBYTES || edLen === binding.crypto_box_SECRETKEYBYTES,
    "ed25519sk must be 'crypto_sign_SECRETKEYBYTES' or 'crypto_sign_SECRETKEYBYTES - crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_sk_to_curve25519(x25519sk, ed25519sk)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_box

exports.crypto_box_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    seed.byteLength === binding.crypto_box_SEEDBYTES,
    "seed must be 'crypto_box_SEEDBYTES' bytes"
  )

  const res = binding.crypto_box_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_easy = function (c, m, n, pk, sk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength === m.byteLength + exports.crypto_box_MACBYTES,
    "c must be 'm.byteLength + crypto_box_MACBYTES' bytes"
  )
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_easy(c, m, n, pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_detached = function (c, mac, m, n, pk, sk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(mac.byteLength === exports.crypto_box_MACBYTES, "mac must be 'crypto_box_MACBYTES' bytes")
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_detached(c, mac, m, n, pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_open_easy = function (m, c, n, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength >= exports.crypto_box_MACBYTES,
    "c must be at least 'crypto_box_MACBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - exports.crypto_box_MACBYTES,
    "m must be 'c.byteLength - crypto_box_MACBYTES' bytes"
  )
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_open_easy(m, c, n, pk, sk)
}

exports.crypto_box_open_detached = function (m, c, mac, n, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(mac.byteLength === exports.crypto_box_MACBYTES, "mac must be 'crypto_box_MACBYTES' bytes")
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_open_detached(m, c, mac, n, pk, sk)
}

exports.crypto_box_seal = function (c, m, pk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    c.byteLength === m.byteLength + exports.crypto_box_SEALBYTES,
    "c must be 'm.byteLength + crypto_box_SEALBYTES' bytes"
  )
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_box_seal(c, m, pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_seal_open = function (m, c, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength >= exports.crypto_box_SEALBYTES,
    "c must be at least 'crypto_box_SEALBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - exports.crypto_box_SEALBYTES,
    "m must be 'c.byteLength - crypto_box_SEALBYTES' bytes"
  )
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_seal_open(
    m.buffer,
    m.byteOffset,
    m.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    pk.buffer,
    pk.byteOffset,
    pk.byteLength,

    sk.buffer,
    sk.byteOffset,
    sk.byteLength
  )
}

// crypto_secretbox

exports.crypto_secretbox_easy = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_secretbox_MACBYTES,
    "c must be 'm.byteLength + crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretbox_easy(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretbox_open_easy = function (m, c, n, k) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    c.byteLength >= binding.crypto_secretbox_MACBYTES,
    "c must be at least 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - binding.crypto_secretbox_MACBYTES,
    "m must be 'c.byteLength - crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  return binding.crypto_secretbox_open_easy(m, c, n, k)
}

exports.crypto_secretbox_detached = function (c, mac, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    mac.byteLength === binding.crypto_secretbox_MACBYTES,
    "mac must be 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretbox_detached(c, mac, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretbox_open_detached = function (m, c, mac, n, k) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(
    mac.byteLength === binding.crypto_secretbox_MACBYTES,
    "mac must be 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  return binding.crypto_secretbox_open_detached(m, c, mac, n, k)
}

// crypto_generichash

exports.crypto_generichash = function (output, input, key) {
  if (!key) key = OPTIONAL

  assert(ArrayBuffer.isView(output), 'output must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    output.byteLength >= binding.crypto_generichash_BYTES_MIN &&
      output.byteLength <= binding.crypto_generichash_BYTES_MAX,
    'output must be between crypto_generichash_BYTES_MIN and crypto_generichash_BYTES_MAX bytes'
  )

  if (key !== OPTIONAL) {
    assert(ArrayBuffer.isView(key), 'key must be a typed array')
    assert(
      key.byteLength >= binding.crypto_generichash_KEYBYTES_MIN &&
        key.byteLength <= binding.crypto_generichash_KEYBYTES_MAX,
      'key must be between crypto_generichash_KEYBYTES_MIN and crypto_generichash_KEYBYTES_MAX bytes'
    )
  }

  const res = binding.crypto_generichash(
    output.buffer,
    output.byteOffset,
    output.byteLength,

    input.buffer,
    input.byteOffset,
    input.byteLength,

    key.buffer,
    key.byteOffset,
    key.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_batch = function (output, batch, key) {
  assert(ArrayBuffer.isView(output), 'output must be a typed array')

  if (isNode || batch.length < 4) {
    const res = binding.crypto_generichash_batch(output, batch, !!key, key || OPTIONAL)
    if (res !== 0) throw new Error('status: ' + res)
  } else {
    const state = Buffer.alloc(binding.crypto_generichash_STATEBYTES)

    exports.crypto_generichash_init(state, key, output.byteLength)

    for (const buf of batch) {
      exports.crypto_generichash_update(state, buf)
    }

    exports.crypto_generichash_final(state, output)
  }
}

exports.crypto_generichash_keygen = function (key) {
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(
    key.byteLength === binding.crypto_generichash_KEYBYTES,
    "key must be 'crypto_generichash_KEYBYTES' bytes"
  )

  const res = binding.crypto_generichash_keygen(key.buffer, key.byteOffset, key.byteLength)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_init = function (state, key, outputLength) {
  if (!key) key = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_init(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    key.buffer,
    key.byteOffset,
    key.byteLength,

    outputLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_update(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    input.buffer,
    input.byteOffset,
    input.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_final = function (state, output) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(output), 'output must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_final(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    output.buffer,
    output.byteOffset,
    output.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

// secretstream

exports.crypto_secretstream_xchacha20poly1305_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  binding.crypto_secretstream_xchacha20poly1305_keygen(k.buffer, k.byteOffset, k.byteLength)
}

exports.crypto_secretstream_xchacha20poly1305_init_push = function (state, header, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(header), 'header must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    header.byteLength === binding.crypto_secretstream_xchacha20poly1305_HEADERBYTES,
    "header must be 'crypto_secretstream_xchacha20poly1305_HEADERBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_init_push(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    header.buffer,
    header.byteOffset,
    header.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretstream_xchacha20poly1305_init_pull = function (state, header, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(header), 'header must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    header.byteLength === binding.crypto_secretstream_xchacha20poly1305_HEADERBYTES,
    "header must be 'crypto_secretstream_xchacha20poly1305_HEADERBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_init_pull(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    header.buffer,
    header.byteOffset,
    header.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretstream_xchacha20poly1305_push = function (state, c, m, ad, tag) {
  if (!ad) ad = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    c.byteLength === m.byteLength + binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "c must be 'm.byteLength + crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_push(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    ad.buffer,
    ad.byteOffset,
    ad.byteLength,

    tag
  )

  if (res < 0) throw new Error('push failed')

  return res
}

exports.crypto_secretstream_xchacha20poly1305_pull = function (state, m, tag, c, ad) {
  if (!ad) ad = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(tag), 'tag must be a typed array')
  assert(tag.byteLength === 1, 'tag must be 1 byte')

  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    c.byteLength >= binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "c must be at least 'crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "m must be 'c.byteLength - crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_pull(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    tag.buffer,
    tag.byteOffset,
    tag.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    ad.buffer,
    ad.byteOffset,
    ad.byteLength
  )

  if (res < 0) throw new Error('pull failed')

  return res
}

exports.crypto_secretstream_xchacha20poly1305_rekey = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )

  binding.crypto_secretstream_xchacha20poly1305_rekey(
    state.buffer,
    state.byteOffset,
    state.byteLength
  )
}

// crypto_stream

exports.crypto_stream = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xor(
    c.buffer,
    c.byteOffset,
    c.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    n.buffer,
    n.byteOffset,
    n.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_auth

exports.crypto_auth = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(out.byteLength === binding.crypto_auth_BYTES, "out must be 'crypto_auth_BYTES' bytes")
  assert(k.byteLength === binding.crypto_auth_KEYBYTES, "k must be 'crypto_auth_KEYBYTES' bytes")

  const res = binding.crypto_auth(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_auth_verify = function (h, input, k) {
  assert(ArrayBuffer.isView(h), 'h must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(h.byteLength === binding.crypto_auth_BYTES, "h must be 'crypto_auth_BYTES' bytes")
  assert(k.byteLength === binding.crypto_auth_KEYBYTES, "k must be 'crypto_auth_KEYBYTES' bytes")

  return binding.crypto_auth_verify(h, input, k)
}

// crypto_onetimeauth

exports.crypto_onetimeauth = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    out.byteLength === binding.crypto_onetimeauth_BYTES,
    "out must be 'crypto_onetimeauth_BYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_init = function (state, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_init(state, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )
  assert(
    out.byteLength === binding.crypto_onetimeauth_BYTES,
    "out must be 'crypto_onetimeauth_BYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_verify = function (h, input, k) {
  assert(ArrayBuffer.isView(h), 'h must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    h.byteLength === binding.crypto_onetimeauth_BYTES,
    "h must be 'crypto_onetimeauth_BYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  return binding.crypto_onetimeauth_verify(h, input, k)
}

// crypto_pwhash

exports.crypto_pwhash = function (out, passwd, salt, opslimit, memlimit, alg) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_BYTES_MIN,
    "out must be at least 'crypto_pwhash_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_BYTES_MAX,
    "out must be at most 'crypto_pwhash_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_SALTBYTES,
    "salt must be 'crypto_pwhash_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )
  assert(alg >= 1 && alg <= 2, 'alg must be either Argon2i 1.3 or Argon2id 1.3')

  const res = binding.crypto_pwhash(out, passwd, salt, opslimit, memlimit, alg)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_async = function (
  out,
  passwd,
  salt,
  opslimit,
  memlimit,
  alg,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_BYTES_MIN,
    "out must be at least 'crypto_pwhash_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_BYTES_MAX,
    "out must be at most 'crypto_pwhash_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_SALTBYTES,
    "salt must be 'crypto_pwhash_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )
  assert(alg >= 1 && alg <= 2, 'alg must be either Argon2i 1.3 or Argon2id 1.3')

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    opslimit,
    memlimit,
    alg,

    done
  )

  return promise
}

exports.crypto_pwhash_str = function (out, passwd, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_STRBYTES,
    "out must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(typeof opslimit === 'number', 'opslimit must be a number')
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(typeof memlimit === 'number', 'memlimit must be a number')
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_str(out, passwd, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_str_async = function (out, passwd, opslimit, memlimit, callback = undefined) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_STRBYTES,
    "out must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(typeof opslimit === 'number', 'opslimit must be a number')
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(typeof memlimit === 'number', 'memlimit must be a number')
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_str_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_str_verify = function (str, passwd) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )

  return binding.crypto_pwhash_str_verify(str, passwd)
}

exports.crypto_pwhash_str_verify_async = function (str, passwd, callback = undefined) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  const [done, promise] = checkStatus(callback, true)

  binding.crypto_pwhash_str_verify_async(
    str.buffer,
    str.byteOffset,
    str.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    done
  )

  return promise
}

exports.crypto_pwhash_str_needs_rehash = function (str, opslimit, memlimit) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  return binding.crypto_pwhash_str_needs_rehash(str, opslimit, memlimit)
}

exports.crypto_pwhash_scryptsalsa208sha256 = function (out, passwd, salt, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MIN,
    "out must be at least 'crypto_pwhash_scryptsalsa208sha256_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MAX,
    "out must be at most 'crypto_pwhash_scryptsalsa208sha256_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_SALTBYTES,
    "salt must be 'crypto_pwhash_scryptsalsa208sha256_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_scryptsalsa208sha256(out, passwd, salt, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_scryptsalsa208sha256_async = function (
  out,
  passwd,
  salt,
  opslimit,
  memlimit,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MIN,
    "out must be at least 'crypto_pwhash_scryptsalsa208sha256_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MAX,
    "out must be at most 'crypto_pwhash_scryptsalsa208sha256_BYTES_MAX' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    salt.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_SALTBYTES,
    "salt must be 'crypto_pwhash_scryptsalsa208sha256_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_scryptsalsa208sha256_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str_async = function (
  out,
  passwd,
  opslimit,
  memlimit,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "out must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_scryptsalsa208sha256_str_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str = function (out, passwd, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "out must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_scryptsalsa208sha256_str(out, passwd, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_scryptsalsa208sha256_str_verify_async = function (
  str,
  passwd,
  callback = undefined
) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  const [done, promise] = checkStatus(callback, true)

  binding.crypto_pwhash_scryptsalsa208sha256_str_verify_async(
    str.buffer,
    str.byteOffset,
    str.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str_verify = function (str, passwd) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  return binding.crypto_pwhash_scryptsalsa208sha256_str_verify(str, passwd)
}

exports.crypto_pwhash_scryptsalsa208sha256_str_needs_rehash = function (str, opslimit, memlimit) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  return binding.crypto_pwhash_scryptsalsa208sha256_str_needs_rehash(str, opslimit, memlimit)
}

// crypto_kx

exports.crypto_kx_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "pk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "sk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    pk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "pk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "sk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    seed.byteLength === binding.crypto_kx_SEEDBYTES,
    "seed must be 'crypto_kx_SEEDBYTES' bytes"
  )

  const res = binding.crypto_kx_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_client_session_keys = function (rx, tx, clientPk, clientSk, serverPk) {
  if (!rx) rx = undefined
  if (!tx) tx = undefined

  assert(rx || tx, 'at least one session key must be specified')

  if (rx) {
    assert(ArrayBuffer.isView(rx), 'rx must be a typed array')
    assert(
      rx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "rx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  if (tx) {
    assert(ArrayBuffer.isView(tx), 'tx must be a typed array')
    assert(
      tx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "tx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  assert(ArrayBuffer.isView(clientPk), 'clientPk must be a typed array')
  assert(ArrayBuffer.isView(clientSk), 'clientSk must be a typed array')
  assert(ArrayBuffer.isView(serverPk), 'serverPk must be a typed array')
  assert(
    clientPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "clientPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    clientSk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "clientSk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    serverPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "serverPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_client_session_keys(rx, tx, clientPk, clientSk, serverPk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_server_session_keys = function (rx, tx, serverPk, serverSk, clientPk) {
  if (!rx) rx = undefined
  if (!tx) tx = undefined

  assert(rx || tx, 'at least one session key must be specified')

  if (rx) {
    assert(ArrayBuffer.isView(rx), 'rx must be a typed array')
    assert(
      rx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "rx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  if (tx) {
    assert(ArrayBuffer.isView(tx), 'tx must be a typed array')
    assert(
      tx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "tx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  assert(ArrayBuffer.isView(serverPk), 'serverPk must be a typed array')
  assert(ArrayBuffer.isView(serverSk), 'serverSk must be a typed array')
  assert(ArrayBuffer.isView(clientPk), 'clientPk must be a typed array')
  assert(
    serverPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "serverPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    serverSk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "serverSk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    clientPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "clientPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_server_session_keys(rx, tx, serverPk, serverSk, clientPk)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_scalarmult

exports.crypto_scalarmult_base = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_BYTES,
    "q must be 'crypto_scalarmult_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_SCALARBYTES,
    "n must be 'crypto_scalarmult_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_base(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_BYTES,
    "q must be 'crypto_scalarmult_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_SCALARBYTES,
    "n must be 'crypto_scalarmult_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_BYTES,
    "p must be 'crypto_scalarmult_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_base = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_base(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519 = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "p must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_is_valid_point = function (p) {
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )

  return binding.crypto_core_ed25519_is_valid_point(p)
}

exports.crypto_core_ed25519_from_uniform = function (p, r) {
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_UNIFORMBYTES,
    "r must be 'crypto_core_ed25519_UNIFORMBYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_from_uniform(p, r)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_base_noclamp = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_base_noclamp(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_noclamp = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "p must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_noclamp(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_core

exports.crypto_core_ed25519_add = function (r, p, q) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_BYTES,
    "r must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_core_ed25519_BYTES,
    "q must be 'crypto_core_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_add(r, p, q)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_sub = function (r, p, q) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_BYTES,
    "r must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_core_ed25519_BYTES,
    "q must be 'crypto_core_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_sub(r, p, q)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_scalar_random = function (r) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "r must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_random(r)
}

exports.crypto_core_ed25519_scalar_reduce = function (r, s) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "r must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_NONREDUCEDSCALARBYTES,
    "s must be 'crypto_core_ed25519_NONREDUCEDSCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_reduce(r, s)
}

exports.crypto_core_ed25519_scalar_invert = function (recip, s) {
  assert(ArrayBuffer.isView(recip), 'recip must be a typed array')
  assert(
    recip.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "recip must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_invert(recip, s)
}

exports.crypto_core_ed25519_scalar_negate = function (neg, s) {
  assert(ArrayBuffer.isView(neg), 'neg must be a typed array')
  assert(
    neg.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "neg must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_negate(neg, s)
}

exports.crypto_core_ed25519_scalar_complement = function (comp, s) {
  assert(ArrayBuffer.isView(comp), 'comp must be a typed array')
  assert(
    comp.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "comp must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_complement(comp, s)
}

exports.crypto_core_ed25519_scalar_add = function (z, x, y) {
  assert(ArrayBuffer.isView(z), 'z must be a typed array')
  assert(
    z.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "z must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(x), 'x must be a typed array')
  assert(
    x.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "x must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(y), 'y must be a typed array')
  assert(
    y.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "y must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_add(z, x, y)
}

exports.crypto_core_ed25519_scalar_sub = function (z, x, y) {
  assert(ArrayBuffer.isView(z), 'z must be a typed array')
  assert(
    z.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "z must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(x), 'x must be a typed array')
  assert(
    x.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "x must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(y), 'y must be a typed array')
  assert(
    y.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "y must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_sub(z, x, y)
}

// crypto_shorthash

exports.crypto_shorthash = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_shorthash_BYTES,
    "out must be 'crypto_shorthash_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_shorthash_KEYBYTES,
    "k must be 'crypto_shorthash_KEYBYTES' bytes"
  )

  const res = binding.crypto_shorthash(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_kdf

exports.crypto_kdf_keygen = function (key) {
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(key.byteLength === binding.crypto_kdf_KEYBYTES, "key must be 'crypto_kdf_KEYBYTES' bytes")

  binding.crypto_kdf_keygen(key)
}

exports.crypto_kdf_derive_from_key = function (subkey, subkeyId, ctx, key) {
  assert(ArrayBuffer.isView(subkey), 'subkey must be a typed array')
  assert(
    subkey.byteLength >= binding.crypto_kdf_BYTES_MIN,
    "subkey must be at least 'crypto_kdf_BYTES_MIN' bytes"
  )
  assert(
    subkey.byteLength <= binding.crypto_kdf_BYTES_MAX,
    "subkey must be at most 'crypto_kdf_BYTES_MAX' bytes"
  )
  assert(ArrayBuffer.isView(ctx), 'ctx must be a typed array')
  assert(
    ctx.byteLength === binding.crypto_kdf_CONTEXTBYTES,
    "ctx must be 'crypto_kdf_CONTEXTBYTES' bytes"
  )
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(key.byteLength === binding.crypto_kdf_KEYBYTES, "key must be 'crypto_kdf_KEYBYTES' bytes")

  const res = binding.crypto_kdf_derive_from_key(subkey, subkeyId, ctx, key)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_hash

exports.crypto_hash = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(out.byteLength === binding.crypto_hash_BYTES, "out must be 'crypto_hash_BYTES' bytes")

  const res = binding.crypto_hash(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256 = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha256_BYTES,
    "out must be 'crypto_hash_sha256_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha256(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_init = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_init(state)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha256_BYTES,
    "out must be 'crypto_hash_sha256_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512 = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha512_BYTES,
    "out must be 'crypto_hash_sha512_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha512(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_init = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_init(state)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha512_BYTES,
    "out must be 'crypto_hash_sha512_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_aead

exports.crypto_aead_xchacha20poly1305_ietf_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  binding.crypto_aead_xchacha20poly1305_ietf_keygen(k)
}

exports.crypto_aead_xchacha20poly1305_ietf_encrypt = function (c, m, ad, nsec, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "c must be 'm.byteLength + crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(c.byteLength <= 0xffffffff, 'c.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_encrypt(c, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_decrypt = function (m, nsec, c, ad, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "m must be 'c.byteLength - crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(m.byteLength <= 0xffffffff, 'm.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_decrypt(m, c, ad, npub, k)

  if (res < 0) throw new Error('could not verify data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_encrypt_detached = function (
  c,
  mac,
  m,
  ad,
  nsec,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_encrypt_detached(c, mac, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_decrypt_detached = function (
  m,
  nsec,
  c,
  mac,
  ad,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_decrypt_detached(m, c, mac, ad, npub, k)

  if (res !== 0) throw new Error('could not verify data')
}

exports.crypto_aead_chacha20poly1305_ietf_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  binding.crypto_aead_chacha20poly1305_ietf_keygen(k)
}

exports.crypto_aead_chacha20poly1305_ietf_encrypt = function (c, m, ad, nsec, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "c must be 'm.byteLength + crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(c.byteLength <= 0xffffffff, 'c.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_encrypt(c, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_decrypt = function (m, nsec, c, ad, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "m must be 'c.byteLength - crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(m.byteLength <= 0xffffffff, 'm.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_decrypt(m, c, ad, npub, k)

  if (res < 0) throw new Error('could not verify data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_encrypt_detached = function (
  c,
  mac,
  m,
  ad,
  nsec,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_encrypt_detached(c, mac, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_decrypt_detached = function (
  m,
  nsec,
  c,
  mac,
  ad,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_decrypt_detached(m, c, mac, ad, npub, k)

  if (res !== 0) throw new Error('could not verify data')
}

// crypto_stream

exports.crypto_stream_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  binding.crypto_stream_xor_wrap_init(state, n, k)
}

exports.crypto_stream_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_xor_wrap_update(state, c, m)
}

exports.crypto_stream_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_xor_wrap_final(state)
}

exports.crypto_stream_chacha20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  binding.crypto_stream_chacha20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_chacha20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_chacha20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_chacha20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_chacha20_xor_wrap_final(state)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  binding.crypto_stream_chacha20_ietf_xor_wrap_init(state, n, k)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_chacha20_ietf_xor_wrap_update(state, c, m)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_chacha20_ietf_xor_wrap_final(state)
}

exports.crypto_stream_xchacha20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  binding.crypto_stream_xchacha20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_xchacha20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_xchacha20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_xchacha20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_xchacha20_xor_wrap_final(state)
}

exports.crypto_stream_salsa20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  binding.crypto_stream_salsa20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_salsa20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_salsa20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_salsa20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_salsa20_xor_wrap_final(state)
}

// experimental

exports.extension_tweak_ed25519_base = function (n, p, ns) {
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.extension_tweak_ed25519_BYTES,
    "p must be 'extension_tweak_ed25519_BYTES' bytes"
  )

  binding.extension_tweak_ed25519_base(n, p, ns)
}

exports.extension_tweak_ed25519_sign_detached = function (sig, m, scalar, pk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(sig.byteLength === binding.crypto_sign_BYTES, "sig must be 'crypto_sign_BYTES' bytes")
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  if (pk) {
    assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
    assert(
      pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
      "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
    )
  }

  const res = binding.extension_tweak_ed25519_sign_detached(sig, m, scalar, pk)

  if (res !== 0) throw new Error('failed to compute signature')
}

exports.extension_tweak_ed25519_sk_to_scalar = function (n, sk) {
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  binding.extension_tweak_ed25519_sk_to_scalar(n, sk)
}

exports.extension_tweak_ed25519_scalar = function (scalarOut, scalar, ns) {
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_scalar(scalarOut, scalar, ns)
}

exports.extension_tweak_ed25519_pk = function (tpk, pk, ns) {
  assert(ArrayBuffer.isView(tpk), 'tpk must be a typed array')
  assert(
    tpk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "tpk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_pk(tpk, pk, ns)

  if (res !== 0) throw new Error('failed to tweak public key')
}

exports.extension_tweak_ed25519_keypair = function (pk, scalarOut, scalarIn, ns) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.extension_tweak_ed25519_BYTES,
    "pk must be 'extension_tweak_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarIn), 'scalarIn must be a typed array')
  assert(
    scalarIn.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarIn must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_keypair(pk, scalarOut, scalarIn, ns)
}

exports.extension_tweak_ed25519_scalar_add = function (scalarOut, scalar, n) {
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_scalar_add(scalarOut, scalar, n)
}

exports.extension_tweak_ed25519_pk_add = function (tpk, pk, p) {
  assert(ArrayBuffer.isView(tpk), 'tpk must be a typed array')
  assert(
    tpk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "tpk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "p must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_pk_add(tpk, pk, p)

  if (res !== 0) throw new Error('failed to add tweak to public key')
}

exports.extension_tweak_ed25519_keypair_add = function (pk, scalarOut, scalarIn, tweak) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.extension_tweak_ed25519_BYTES,
    "pk must be 'extension_tweak_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarIn), 'scalarIn must be a typed array')
  assert(
    scalarIn.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarIn must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(tweak), 'tweak must be a typed array')
  assert(
    tweak.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "tweak must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_keypair_add(pk, scalarOut, scalarIn, tweak)

  if (res !== 0) throw new Error('failed to add tweak to keypair')
}

exports.extension_pbkdf2_sha512_async = function (out, passwd, salt, iter, outlen, callback) {
  assert(
    iter >= binding.extension_pbkdf2_sha512_ITERATIONS_MIN,
    "iter must be at least 'extension_pbkdf2_sha512_ITERATIONS_MIN'"
  )
  assert(
    outlen <= binding.extension_pbkdf2_sha512_BYTES_MAX,
    "outlen must be at most 'extension_pbkdf2_sha512_BYTES_MAX'"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(out.byteLength >= outlen, "out must be at least 'outlen' bytes")
  assert(out.byteLength > 0, 'out must not be empty')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(salt.byteLength > 0, 'salt must not be empty')

  const [done, promise] = checkStatus(callback)

  binding.extension_pbkdf2_sha512_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    iter,
    outlen,

    done
  )

  return promise
}

exports.extension_pbkdf2_sha512 = function (out, passwd, salt, iter, outlen) {
  assert(
    iter >= binding.extension_pbkdf2_sha512_ITERATIONS_MIN,
    "iter must be at least 'extension_pbkdf2_sha512_ITERATIONS_MIN'"
  )
  assert(
    outlen <= binding.extension_pbkdf2_sha512_BYTES_MAX,
    "outlen must be at most 'extension_pbkdf2_sha512_BYTES_MAX'"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(out.byteLength >= outlen, "out must be at least 'outlen' bytes")
  assert(out.byteLength > 0, 'out must not be empty')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(salt.byteLength > 0, 'salt must not be empty')

  const res = binding.extension_pbkdf2_sha512(out, passwd, salt, iter, outlen)

  if (res !== 0) throw new Error('failed to add tweak to public key')
}

function checkStatus(callback, booleanResult = false) {
  let done, promise

  if (typeof callback === 'function') {
    done = function (status) {
      if (booleanResult) callback(null, status === 0)
      else if (status === 0) callback(null)
      else callback(new Error('status: ' + status))
    }
  } else {
    promise = new Promise(function (resolve, reject) {
      done = function (status) {
        if (booleanResult) resolve(status === 0)
        else if (status === 0) resolve()
        else reject(new Error('status: ' + status))
      }
    })
  }

  return [done, promise]
}
{
  "name": "sodium-native",
  "version": "5.1.0",
  "description": "Low level bindings for libsodium",
  "main": "index.js",
  "files": [
    "index.js",
    "binding.cc",
    "binding.js",
    "extensions",
    "prebuilds",
    "CMakeLists.txt"
  ],
  "imports": {
    "assert": {
      "bare": "bare-assert",
      "node": "assert"
    }
  },
  "addon": true,
  "dependencies": {
    "bare-assert": "^1.2.0",
    "require-addon": "^1.1.0",
    "which-runtime": "^1.2.1"
  },
  "devDependencies": {
    "bare-compat-napi": "^1.3.5",
    "brittle": "^3.16.2",
    "cmake-bare": "^1.6.1",
    "cmake-fetch": "^1.4.3",
    "cmake-napi": "^1.2.1",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "test": "prettier . --check && npm run test:node && npm run test:bare",
    "test:node": "node test/all.js",
    "test:bare": "bare test/all.js"
  },
  "standard": {
    "ignore": [
      "/test/fixtures/*.js"
    ]
  },
  "engines": {
    "bare": ">=1.16.0"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sodium-native.git"
  },
  "contributors": [
    "Emil Bay <github@tixz.dk> (http://bayes.dk)",
    "Mathias Buus <mathiasbuus@gmail.com> (https://mafinto.sh)",
    "Christophe Diederichs <chm-diederichs@hyperdivision.dk>"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/sodium-native/issues"
  },
  "homepage": "https://github.com/holepunchto/sodium-native"
}
const sodium = require('sodium-universal')
const b4a = require('b4a')

const ABYTES = sodium.crypto_secretstream_xchacha20poly1305_ABYTES
const TAG_MESSAGE = sodium.crypto_secretstream_xchacha20poly1305_TAG_MESSAGE
const TAG_FINAL = sodium.crypto_secretstream_xchacha20poly1305_TAG_FINAL
const STATEBYTES = sodium.crypto_secretstream_xchacha20poly1305_STATEBYTES
const HEADERBYTES = sodium.crypto_secretstream_xchacha20poly1305_HEADERBYTES
const KEYBYTES = sodium.crypto_secretstream_xchacha20poly1305_KEYBYTES
const TAG_FINAL_BYTE = b4a.isBuffer(TAG_FINAL) ? TAG_FINAL[0] : TAG_FINAL

const EMPTY = b4a.alloc(0)
const TAG = b4a.alloc(1)

class Push {
  constructor (key, state = b4a.allocUnsafeSlow(STATEBYTES), header = b4a.allocUnsafeSlow(HEADERBYTES)) {
    if (!TAG_FINAL) throw new Error('JavaScript sodium version needs to support crypto_secretstream_xchacha20poly')

    this.key = key
    this.state = state
    this.header = header

    sodium.crypto_secretstream_xchacha20poly1305_init_push(this.state, this.header, this.key)
  }

  next (message, cipher = b4a.allocUnsafe(message.byteLength + ABYTES)) {
    sodium.crypto_secretstream_xchacha20poly1305_push(this.state, cipher, message, null, TAG_MESSAGE)
    return cipher
  }

  final (message = EMPTY, cipher = b4a.allocUnsafe(ABYTES)) {
    sodium.crypto_secretstream_xchacha20poly1305_push(this.state, cipher, message, null, TAG_FINAL)
    return cipher
  }
}

class Pull {
  constructor (key, state = b4a.allocUnsafeSlow(STATEBYTES)) {
    if (!TAG_FINAL) throw new Error('JavaScript sodium version needs to support crypto_secretstream_xchacha20poly')

    this.key = key
    this.state = state
    this.final = false
  }

  init (header) {
    sodium.crypto_secretstream_xchacha20poly1305_init_pull(this.state, header, this.key)
  }

  next (cipher, message = b4a.allocUnsafe(cipher.byteLength - ABYTES)) {
    sodium.crypto_secretstream_xchacha20poly1305_pull(this.state, message, TAG, cipher, null)
    this.final = TAG[0] === TAG_FINAL_BYTE
    return message
  }
}

function keygen (buf = b4a.alloc(KEYBYTES)) {
  sodium.crypto_secretstream_xchacha20poly1305_keygen(buf)
  return buf
}

module.exports = {
  keygen,
  KEYBYTES,
  ABYTES,
  STATEBYTES,
  HEADERBYTES,
  Push,
  Pull
}
{
  "name": "sodium-secretstream",
  "version": "1.2.0",
  "description": "Wraps libsodiums secretstream in a higher level abstraction",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.1.1",
    "sodium-universal": "^5.0.0"
  },
  "devDependencies": {
    "standard": "^17.0.0"
  },
  "scripts": {
    "test": "standard"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/sodium-secretstream.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/sodium-secretstream/issues"
  },
  "homepage": "https://github.com/mafintosh/sodium-secretstream"
}
module.exports = require('sodium-native')
{
  "name": "sodium-universal",
  "version": "5.0.1",
  "description": "Universal wrapper for sodium-javascript and sodium-native working in Node.js and the Browser",
  "main": "index.js",
  "dependencies": {
    "sodium-native": "^5.0.1"
  },
  "peerDependencies": {
    "sodium-javascript": "~0.8.0"
  },
  "peerDependenciesMeta": {
    "sodium-javascript": {
      "optional": true
    }
  },
  "scripts": {
    "prepublish": "./build-scripts/generate.js"
  },
  "browser": {
    "sodium-native": "sodium-javascript"
  },
  "browserify": {
    "transform": [
      "./build-scripts/transform.js"
    ]
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sodium-universal.git"
  },
  "keywords": [
    "libsodium",
    "sodium",
    "sodium-native",
    "sodium-javascript",
    "browserify"
  ],
  "contributors": [
    "Emil Bay <github@tixz.dk> (http://bayes.dk)",
    "Mathias Buus <mathiasbuus@gmail.com> (https://mafinto.sh)",
    "Christophe Diederichs <chm-diederichs@hyperdivision.dk>"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/sodium-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/sodium-universal#readme"
}
const { EventEmitter } = require('events-universal')
const FIFO = require('fast-fifo')
const TextDecoder = require('text-decoder')

const StreamError = require('./lib/errors.js')

// if we do a future major, expect queue microtask to be there always, for now a bit defensive
const qmt =
  typeof queueMicrotask === 'undefined' ? (fn) => global.process.nextTick(fn) : queueMicrotask

// 29 bits used total (4 from shared, 14 from read, and 11 from write)
const MAX = (1 << 29) - 1

// Shared state
const OPENING = 0b0001
const PREDESTROYING = 0b0010
const DESTROYING = 0b0100
const DESTROYED = 0b1000

const NOT_OPENING = MAX ^ OPENING
const NOT_PREDESTROYING = MAX ^ PREDESTROYING

// Read state (4 bit offset from shared state)
const READ_ACTIVE = 0b00000000000001 << 4
const READ_UPDATING = 0b00000000000010 << 4
const READ_PRIMARY = 0b00000000000100 << 4
const READ_QUEUED = 0b00000000001000 << 4
const READ_RESUMED = 0b00000000010000 << 4
const READ_PIPE_DRAINED = 0b00000000100000 << 4
const READ_ENDING = 0b00000001000000 << 4
const READ_EMIT_DATA = 0b00000010000000 << 4
const READ_EMIT_READABLE = 0b00000100000000 << 4
const READ_EMITTED_READABLE = 0b00001000000000 << 4
const READ_DONE = 0b00010000000000 << 4
const READ_NEXT_TICK = 0b00100000000000 << 4
const READ_NEEDS_PUSH = 0b01000000000000 << 4
const READ_READ_AHEAD = 0b10000000000000 << 4

// Combined read state
const READ_FLOWING = READ_RESUMED | READ_PIPE_DRAINED
const READ_ACTIVE_AND_NEEDS_PUSH = READ_ACTIVE | READ_NEEDS_PUSH
const READ_PRIMARY_AND_ACTIVE = READ_PRIMARY | READ_ACTIVE
const READ_EMIT_READABLE_AND_QUEUED = READ_EMIT_READABLE | READ_QUEUED
const READ_RESUMED_READ_AHEAD = READ_RESUMED | READ_READ_AHEAD

const READ_NOT_ACTIVE = MAX ^ READ_ACTIVE
const READ_NON_PRIMARY = MAX ^ READ_PRIMARY
const READ_NON_PRIMARY_AND_PUSHED = MAX ^ (READ_PRIMARY | READ_NEEDS_PUSH)
const READ_PUSHED = MAX ^ READ_NEEDS_PUSH
const READ_PAUSED = MAX ^ READ_RESUMED
const READ_NOT_QUEUED = MAX ^ (READ_QUEUED | READ_EMITTED_READABLE)
const READ_NOT_ENDING = MAX ^ READ_ENDING
const READ_PIPE_NOT_DRAINED = MAX ^ READ_FLOWING
const READ_NOT_NEXT_TICK = MAX ^ READ_NEXT_TICK
const READ_NOT_UPDATING = MAX ^ READ_UPDATING
const READ_NO_READ_AHEAD = MAX ^ READ_READ_AHEAD
const READ_PAUSED_NO_READ_AHEAD = MAX ^ READ_RESUMED_READ_AHEAD

// Write state (18 bit offset, 4 bit offset from shared state and 14 from read state)
const WRITE_ACTIVE = 0b00000000001 << 18
const WRITE_UPDATING = 0b00000000010 << 18
const WRITE_PRIMARY = 0b00000000100 << 18
const WRITE_QUEUED = 0b00000001000 << 18
const WRITE_UNDRAINED = 0b00000010000 << 18
const WRITE_DONE = 0b00000100000 << 18
const WRITE_EMIT_DRAIN = 0b00001000000 << 18
const WRITE_NEXT_TICK = 0b00010000000 << 18
const WRITE_WRITING = 0b00100000000 << 18
const WRITE_FINISHING = 0b01000000000 << 18
const WRITE_CORKED = 0b10000000000 << 18

const WRITE_NOT_ACTIVE = MAX ^ (WRITE_ACTIVE | WRITE_WRITING)
const WRITE_NON_PRIMARY = MAX ^ WRITE_PRIMARY
const WRITE_NOT_FINISHING = MAX ^ (WRITE_ACTIVE | WRITE_FINISHING)
const WRITE_DRAINED = MAX ^ WRITE_UNDRAINED
const WRITE_NOT_QUEUED = MAX ^ WRITE_QUEUED
const WRITE_NOT_NEXT_TICK = MAX ^ WRITE_NEXT_TICK
const WRITE_NOT_UPDATING = MAX ^ WRITE_UPDATING
const WRITE_NOT_CORKED = MAX ^ WRITE_CORKED

// Combined shared state
const ACTIVE = READ_ACTIVE | WRITE_ACTIVE
const NOT_ACTIVE = MAX ^ ACTIVE
const DONE = READ_DONE | WRITE_DONE
const DESTROY_STATUS = DESTROYING | DESTROYED | PREDESTROYING
const OPEN_STATUS = DESTROY_STATUS | OPENING
const AUTO_DESTROY = DESTROY_STATUS | DONE
const NON_PRIMARY = WRITE_NON_PRIMARY & READ_NON_PRIMARY
const ACTIVE_OR_TICKING = WRITE_NEXT_TICK | READ_NEXT_TICK
const TICKING = ACTIVE_OR_TICKING & NOT_ACTIVE
const IS_OPENING = OPEN_STATUS | TICKING

// Combined shared state and read state
const READ_PRIMARY_STATUS = OPEN_STATUS | READ_ENDING | READ_DONE
const READ_STATUS = OPEN_STATUS | READ_DONE | READ_QUEUED
const READ_ENDING_STATUS = OPEN_STATUS | READ_ENDING | READ_QUEUED
const READ_READABLE_STATUS = OPEN_STATUS | READ_EMIT_READABLE | READ_QUEUED | READ_EMITTED_READABLE
const SHOULD_NOT_READ =
  OPEN_STATUS | READ_ACTIVE | READ_ENDING | READ_DONE | READ_NEEDS_PUSH | READ_READ_AHEAD
const READ_BACKPRESSURE_STATUS = DESTROY_STATUS | READ_ENDING | READ_DONE
const READ_UPDATE_SYNC_STATUS = READ_UPDATING | OPEN_STATUS | READ_NEXT_TICK | READ_PRIMARY
const READ_NEXT_TICK_OR_OPENING = READ_NEXT_TICK | OPENING

// Combined write state
const WRITE_PRIMARY_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_DONE
const WRITE_QUEUED_AND_UNDRAINED = WRITE_QUEUED | WRITE_UNDRAINED
const WRITE_QUEUED_AND_ACTIVE = WRITE_QUEUED | WRITE_ACTIVE
const WRITE_DRAIN_STATUS = WRITE_QUEUED | WRITE_UNDRAINED | OPEN_STATUS | WRITE_ACTIVE
const WRITE_STATUS = OPEN_STATUS | WRITE_ACTIVE | WRITE_QUEUED | WRITE_CORKED
const WRITE_PRIMARY_AND_ACTIVE = WRITE_PRIMARY | WRITE_ACTIVE
const WRITE_ACTIVE_AND_WRITING = WRITE_ACTIVE | WRITE_WRITING
const WRITE_FINISHING_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_QUEUED_AND_ACTIVE | WRITE_DONE
const WRITE_BACKPRESSURE_STATUS = WRITE_UNDRAINED | DESTROY_STATUS | WRITE_FINISHING | WRITE_DONE
const WRITE_UPDATE_SYNC_STATUS = WRITE_UPDATING | OPEN_STATUS | WRITE_NEXT_TICK | WRITE_PRIMARY
const WRITE_DROP_DATA = WRITE_FINISHING | WRITE_DONE | DESTROY_STATUS

const asyncIterator = Symbol.asyncIterator || Symbol('asyncIterator')

class WritableState {
  constructor(
    stream,
    { highWaterMark = 16384, map = null, mapWritable, byteLength, byteLengthWritable } = {}
  ) {
    this.stream = stream
    this.queue = new FIFO()
    this.highWaterMark = highWaterMark
    this.buffered = 0
    this.error = null
    this.pipeline = null
    this.drains = null // if we add more seldomly used helpers we might them into a subobject so its a single ptr
    this.byteLength = byteLengthWritable || byteLength || defaultByteLength
    this.map = mapWritable || map
    this.afterWrite = afterWrite.bind(this)
    this.afterUpdateNextTick = updateWriteNT.bind(this)
  }

  get ending() {
    return (this.stream._duplexState & WRITE_FINISHING) !== 0
  }

  get ended() {
    return (this.stream._duplexState & WRITE_DONE) !== 0
  }

  push(data) {
    if ((this.stream._duplexState & WRITE_DROP_DATA) !== 0) return false
    if (this.map !== null) data = this.map(data)

    this.buffered += this.byteLength(data)
    this.queue.push(data)

    if (this.buffered < this.highWaterMark) {
      this.stream._duplexState |= WRITE_QUEUED
      return true
    }

    this.stream._duplexState |= WRITE_QUEUED_AND_UNDRAINED
    return false
  }

  shift() {
    const data = this.queue.shift()

    this.buffered -= this.byteLength(data)
    if (this.buffered === 0) this.stream._duplexState &= WRITE_NOT_QUEUED

    return data
  }

  end(data) {
    if (typeof data === 'function') {
      this.stream.once('finish', data)
    } else if (data !== undefined && data !== null) {
      this.push(data)
    }

    this.stream._duplexState = (this.stream._duplexState | WRITE_FINISHING) & WRITE_NON_PRIMARY
  }

  autoBatch(data, cb) {
    const buffer = []
    const stream = this.stream

    buffer.push(data)
    while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED_AND_ACTIVE) {
      buffer.push(stream._writableState.shift())
    }

    if ((stream._duplexState & OPEN_STATUS) !== 0) return cb(null)
    stream._writev(buffer, cb)
  }

  update() {
    const stream = this.stream

    stream._duplexState |= WRITE_UPDATING

    do {
      while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED) {
        const data = this.shift()
        stream._duplexState |= WRITE_ACTIVE_AND_WRITING
        stream._write(data, this.afterWrite)
      }

      if ((stream._duplexState & WRITE_PRIMARY_AND_ACTIVE) === 0) this.updateNonPrimary()
    } while (this.continueUpdate() === true)

    stream._duplexState &= WRITE_NOT_UPDATING
  }

  updateNonPrimary() {
    const stream = this.stream

    if ((stream._duplexState & WRITE_FINISHING_STATUS) === WRITE_FINISHING) {
      stream._duplexState = stream._duplexState | WRITE_ACTIVE
      stream._final(afterFinal.bind(this))
      return
    }

    if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
      if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
        stream._duplexState |= ACTIVE
        stream._destroy(afterDestroy.bind(this))
      }
      return
    }

    if ((stream._duplexState & IS_OPENING) === OPENING) {
      stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING
      stream._open(afterOpen.bind(this))
    }
  }

  continueUpdate() {
    if ((this.stream._duplexState & WRITE_NEXT_TICK) === 0) return false
    this.stream._duplexState &= WRITE_NOT_NEXT_TICK
    return true
  }

  updateCallback() {
    if ((this.stream._duplexState & WRITE_UPDATE_SYNC_STATUS) === WRITE_PRIMARY) {
      this.update()
    } else {
      this.updateNextTick()
    }
  }

  updateNextTick() {
    if ((this.stream._duplexState & WRITE_NEXT_TICK) !== 0) return
    this.stream._duplexState |= WRITE_NEXT_TICK
    if ((this.stream._duplexState & WRITE_UPDATING) === 0) qmt(this.afterUpdateNextTick)
  }
}

class ReadableState {
  constructor(
    stream,
    { highWaterMark = 16384, map = null, mapReadable, byteLength, byteLengthReadable } = {}
  ) {
    this.stream = stream
    this.queue = new FIFO()
    this.highWaterMark = highWaterMark === 0 ? 1 : highWaterMark
    this.buffered = 0
    this.readAhead = highWaterMark > 0
    this.error = null
    this.pipeline = null
    this.byteLength = byteLengthReadable || byteLength || defaultByteLength
    this.map = mapReadable || map
    this.pipeTo = null
    this.afterRead = afterRead.bind(this)
    this.afterUpdateNextTick = updateReadNT.bind(this)
  }

  get ending() {
    return (this.stream._duplexState & READ_ENDING) !== 0
  }

  get ended() {
    return (this.stream._duplexState & READ_DONE) !== 0
  }

  pipe(pipeTo, cb) {
    if (this.pipeTo !== null) throw StreamError.BAD_ARGUMENT('Can only pipe to one destination')
    if (typeof cb !== 'function') cb = null

    this.stream._duplexState |= READ_PIPE_DRAINED
    this.pipeTo = pipeTo
    this.pipeline = new Pipeline(this.stream, pipeTo, cb)

    if (cb) this.stream.on('error', noop) // We already error handle this so supress crashes

    if (isStreamx(pipeTo)) {
      pipeTo._writableState.pipeline = this.pipeline
      if (cb) pipeTo.on('error', noop) // We already error handle this so supress crashes
      pipeTo.on('finish', this.pipeline.finished.bind(this.pipeline)) // TODO: just call finished from pipeTo itself
    } else {
      const onerror = this.pipeline.done.bind(this.pipeline, pipeTo)
      const onclose = this.pipeline.done.bind(this.pipeline, pipeTo, null) // onclose has a weird bool arg
      pipeTo.on('error', onerror)
      pipeTo.on('close', onclose)
      pipeTo.on('finish', this.pipeline.finished.bind(this.pipeline))
    }

    pipeTo.on('drain', afterDrain.bind(this))
    this.stream.emit('piping', pipeTo)
    pipeTo.emit('pipe', this.stream)
  }

  push(data) {
    const stream = this.stream

    if (data === null) {
      this.highWaterMark = 0
      stream._duplexState = (stream._duplexState | READ_ENDING) & READ_NON_PRIMARY_AND_PUSHED
      return false
    }

    if (this.map !== null) {
      data = this.map(data)
      if (data === null) {
        stream._duplexState &= READ_PUSHED
        return this.buffered < this.highWaterMark
      }
    }

    this.buffered += this.byteLength(data)
    this.queue.push(data)

    stream._duplexState = (stream._duplexState | READ_QUEUED) & READ_PUSHED

    return this.buffered < this.highWaterMark
  }

  shift() {
    const data = this.queue.shift()

    this.buffered -= this.byteLength(data)
    if (this.buffered === 0) {
      this.stream._duplexState &= READ_NOT_QUEUED
    }

    return data
  }

  unshift(data) {
    const pending = [this.map !== null ? this.map(data) : data]
    while (this.buffered > 0) pending.push(this.shift())

    for (let i = 0; i < pending.length - 1; i++) {
      const data = pending[i]
      this.buffered += this.byteLength(data)
      this.queue.push(data)
    }

    this.push(pending[pending.length - 1])
  }

  read() {
    const stream = this.stream

    if ((stream._duplexState & READ_STATUS) === READ_QUEUED) {
      const data = this.shift()

      if (this.pipeTo !== null && this.pipeTo.write(data) === false) {
        stream._duplexState &= READ_PIPE_NOT_DRAINED
      }

      if ((stream._duplexState & READ_EMIT_DATA) !== 0) {
        stream.emit('data', data)
      }

      return data
    }

    if (this.readAhead === false) {
      stream._duplexState |= READ_READ_AHEAD
      this.updateNextTick()
    }

    return null
  }

  drain() {
    const stream = this.stream

    while (
      (stream._duplexState & READ_STATUS) === READ_QUEUED &&
      (stream._duplexState & READ_FLOWING) !== 0
    ) {
      const data = this.shift()

      if (this.pipeTo !== null && this.pipeTo.write(data) === false) {
        stream._duplexState &= READ_PIPE_NOT_DRAINED
      }

      if ((stream._duplexState & READ_EMIT_DATA) !== 0) {
        stream.emit('data', data)
      }
    }
  }

  update() {
    const stream = this.stream

    stream._duplexState |= READ_UPDATING

    do {
      this.drain()

      while (
        this.buffered < this.highWaterMark &&
        (stream._duplexState & SHOULD_NOT_READ) === READ_READ_AHEAD
      ) {
        stream._duplexState |= READ_ACTIVE_AND_NEEDS_PUSH
        stream._read(this.afterRead)
        this.drain()
      }

      if ((stream._duplexState & READ_READABLE_STATUS) === READ_EMIT_READABLE_AND_QUEUED) {
        stream._duplexState |= READ_EMITTED_READABLE
        stream.emit('readable')
      }

      if ((stream._duplexState & READ_PRIMARY_AND_ACTIVE) === 0) {
        this.updateNonPrimary()
      }
    } while (this.continueUpdate() === true)

    stream._duplexState &= READ_NOT_UPDATING
  }

  updateNonPrimary() {
    const stream = this.stream

    if ((stream._duplexState & READ_ENDING_STATUS) === READ_ENDING) {
      stream._duplexState = (stream._duplexState | READ_DONE) & READ_NOT_ENDING
      stream.emit('end')

      if ((stream._duplexState & AUTO_DESTROY) === DONE) {
        stream._duplexState |= DESTROYING
      }

      if (this.pipeTo !== null) {
        this.pipeTo.end()
      }
    }

    if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
      if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
        stream._duplexState |= ACTIVE
        stream._destroy(afterDestroy.bind(this))
      }
      return
    }

    if ((stream._duplexState & IS_OPENING) === OPENING) {
      stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING
      stream._open(afterOpen.bind(this))
    }
  }

  continueUpdate() {
    if ((this.stream._duplexState & READ_NEXT_TICK) === 0) return false
    this.stream._duplexState &= READ_NOT_NEXT_TICK
    return true
  }

  updateCallback() {
    if ((this.stream._duplexState & READ_UPDATE_SYNC_STATUS) === READ_PRIMARY) {
      this.update()
    } else {
      this.updateNextTick()
    }
  }

  updateNextTickIfOpen() {
    if ((this.stream._duplexState & READ_NEXT_TICK_OR_OPENING) !== 0) return
    this.stream._duplexState |= READ_NEXT_TICK
    if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick)
  }

  updateNextTick() {
    if ((this.stream._duplexState & READ_NEXT_TICK) !== 0) return
    this.stream._duplexState |= READ_NEXT_TICK
    if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick)
  }
}

class TransformState {
  constructor(stream) {
    this.data = null
    this.afterTransform = afterTransform.bind(stream)
    this.afterFinal = null
  }
}

class Pipeline {
  constructor(src, dst, cb) {
    this.from = src
    this.to = dst
    this.afterPipe = cb
    this.error = null
    this.pipeToFinished = false
  }

  finished() {
    this.pipeToFinished = true
  }

  done(stream, err) {
    if (err) this.error = err

    if (stream === this.to) {
      this.to = null

      if (this.from !== null) {
        if ((this.from._duplexState & READ_DONE) === 0 || !this.pipeToFinished) {
          this.from.destroy(this.error || StreamError.PREMATURE_CLOSE('Writable stream closed'))
        }
        return
      }
    }

    if (stream === this.from) {
      this.from = null

      if (this.to !== null) {
        if ((stream._duplexState & READ_DONE) === 0) {
          this.to.destroy(this.error || StreamError.PREMATURE_CLOSE('Readable stream closed'))
        }
        return
      }
    }

    if (this.afterPipe !== null) this.afterPipe(this.error)
    this.to = this.from = this.afterPipe = null
  }
}

function afterDrain() {
  this.stream._duplexState |= READ_PIPE_DRAINED
  this.updateCallback()
}

function afterFinal(err) {
  const stream = this.stream
  if (err) stream.destroy(err)

  if ((stream._duplexState & DESTROY_STATUS) === 0) {
    stream._duplexState |= WRITE_DONE
    stream.emit('finish')
  }

  if ((stream._duplexState & AUTO_DESTROY) === DONE) {
    stream._duplexState |= DESTROYING
  }

  stream._duplexState &= WRITE_NOT_FINISHING

  // no need to wait the extra tick here, so we short circuit that
  if ((stream._duplexState & WRITE_UPDATING) === 0) {
    this.update()
  } else {
    this.updateNextTick()
  }
}

function afterDestroy(err) {
  const stream = this.stream

  if (!err && !StreamError.isStreamDestroyed(this.error)) err = this.error
  if (err) stream.emit('error', err)

  stream._duplexState |= DESTROYED
  stream.emit('close')

  const rs = stream._readableState
  const ws = stream._writableState

  if (rs !== null && rs.pipeline !== null) {
    rs.pipeline.done(stream, err)
  }

  if (ws !== null) {
    while (ws.drains !== null && ws.drains.length > 0) {
      ws.drains.shift().resolve(false)
    }

    if (ws.pipeline !== null) {
      ws.pipeline.done(stream, err)
    }
  }
}

function afterWrite(err) {
  const stream = this.stream

  if (err) stream.destroy(err)
  stream._duplexState &= WRITE_NOT_ACTIVE

  if (this.drains !== null) tickDrains(this.drains)

  if ((stream._duplexState & WRITE_DRAIN_STATUS) === WRITE_UNDRAINED) {
    stream._duplexState &= WRITE_DRAINED

    if ((stream._duplexState & WRITE_EMIT_DRAIN) === WRITE_EMIT_DRAIN) {
      stream.emit('drain')
    }
  }

  this.updateCallback()
}

function afterRead(err) {
  if (err) this.stream.destroy(err)
  this.stream._duplexState &= READ_NOT_ACTIVE

  if (this.readAhead === false && (this.stream._duplexState & READ_RESUMED) === 0) {
    this.stream._duplexState &= READ_NO_READ_AHEAD
  }

  this.updateCallback()
}

function updateReadNT() {
  if ((this.stream._duplexState & READ_UPDATING) === 0) {
    this.stream._duplexState &= READ_NOT_NEXT_TICK
    this.update()
  }
}

function updateWriteNT() {
  if ((this.stream._duplexState & WRITE_UPDATING) === 0) {
    this.stream._duplexState &= WRITE_NOT_NEXT_TICK
    this.update()
  }
}

function tickDrains(drains) {
  for (let i = 0; i < drains.length; i++) {
    // drains.writes are monotonic, so if one is 0 its always the first one
    if (--drains[i].writes === 0) {
      drains.shift().resolve(true)
      i--
    }
  }
}

function afterOpen(err) {
  const stream = this.stream

  if (err) stream.destroy(err)

  if ((stream._duplexState & DESTROYING) === 0) {
    if ((stream._duplexState & READ_PRIMARY_STATUS) === 0) {
      stream._duplexState |= READ_PRIMARY
    }

    if ((stream._duplexState & WRITE_PRIMARY_STATUS) === 0) {
      stream._duplexState |= WRITE_PRIMARY
    }

    stream.emit('open')
  }

  stream._duplexState &= NOT_ACTIVE

  if (stream._writableState !== null) {
    stream._writableState.updateCallback()
  }

  if (stream._readableState !== null) {
    stream._readableState.updateCallback()
  }
}

function afterTransform(err, data) {
  if (data !== undefined && data !== null) this.push(data)
  this._writableState.afterWrite(err)
}

function newListener(name) {
  if (this._readableState !== null) {
    if (name === 'data') {
      this._duplexState |= READ_EMIT_DATA | READ_RESUMED_READ_AHEAD
      this._readableState.updateNextTick()
    }
    if (name === 'readable') {
      this._duplexState |= READ_EMIT_READABLE
      this._readableState.updateNextTick()
    }
  }

  if (this._writableState !== null) {
    if (name === 'drain') {
      this._duplexState |= WRITE_EMIT_DRAIN
      this._writableState.updateNextTick()
    }
  }
}

class Stream extends EventEmitter {
  constructor(opts) {
    super()

    this._duplexState = 0
    this._readableState = null
    this._writableState = null

    if (opts) {
      if (opts.open) this._open = opts.open
      if (opts.destroy) this._destroy = opts.destroy
      if (opts.predestroy) this._predestroy = opts.predestroy
      if (opts.signal) opts.signal.addEventListener('abort', abort.bind(this))
    }

    this.on('newListener', newListener)
  }

  _open(cb) {
    cb(null)
  }

  _destroy(cb) {
    cb(null)
  }

  _predestroy() {
    // does nothing
  }

  get readable() {
    return this._readableState !== null ? true : undefined
  }

  get writable() {
    return this._writableState !== null ? true : undefined
  }

  get destroyed() {
    return (this._duplexState & DESTROYED) !== 0
  }

  get destroying() {
    return (this._duplexState & DESTROY_STATUS) !== 0
  }

  destroy(err) {
    if ((this._duplexState & DESTROY_STATUS) === 0) {
      if (!err) err = StreamError.STREAM_DESTROYED()
      this._duplexState = (this._duplexState | DESTROYING) & NON_PRIMARY

      if (this._readableState !== null) {
        this._readableState.highWaterMark = 0
        this._readableState.error = err
      }

      if (this._writableState !== null) {
        this._writableState.highWaterMark = 0
        this._writableState.error = err
      }

      this._duplexState |= PREDESTROYING
      this._predestroy()
      this._duplexState &= NOT_PREDESTROYING

      if (this._readableState !== null) {
        this._readableState.updateNextTick()
      }

      if (this._writableState !== null) {
        this._writableState.updateNextTick()
      }
    }
  }
}

class Readable extends Stream {
  constructor(opts) {
    super(opts)

    this._duplexState |= OPENING | WRITE_DONE | READ_READ_AHEAD
    this._readableState = new ReadableState(this, opts)

    if (opts) {
      if (this._readableState.readAhead === false) this._duplexState &= READ_NO_READ_AHEAD
      if (opts.read) this._read = opts.read
      if (opts.eagerOpen) this._readableState.updateNextTick()
      if (opts.encoding) this.setEncoding(opts.encoding)
    }
  }

  static deferred(fn, opts) {
    const out = new PassThrough(opts)

    fn()
      .then((src) => {
        if (src === null) return out.end()
        if (out.destroying) return
        pipeline(src, out, noop)
      })
      .catch((err) => out.destroy(err))

    return out
  }

  setEncoding(encoding) {
    const dec = new TextDecoder(encoding)
    const map = this._readableState.map || echo
    this._readableState.map = mapOrSkip
    return this

    function mapOrSkip(data) {
      const next = dec.push(data)
      return next === '' && (data.byteLength !== 0 || dec.remaining > 0) ? null : map(next)
    }
  }

  _read(cb) {
    cb(null)
  }

  pipe(dest, cb) {
    this._readableState.updateNextTick()
    this._readableState.pipe(dest, cb)
    return dest
  }

  read() {
    this._readableState.updateNextTick()
    return this._readableState.read()
  }

  push(data) {
    this._readableState.updateNextTickIfOpen()
    return this._readableState.push(data)
  }

  unshift(data) {
    this._readableState.updateNextTickIfOpen()
    return this._readableState.unshift(data)
  }

  resume() {
    this._duplexState |= READ_RESUMED_READ_AHEAD
    this._readableState.updateNextTick()
    return this
  }

  pause() {
    this._duplexState &=
      this._readableState.readAhead === false ? READ_PAUSED_NO_READ_AHEAD : READ_PAUSED
    return this
  }

  static _fromAsyncIterator(ite, opts) {
    let destroy

    const rs = new Readable({
      ...opts,
      read(cb) {
        ite.next().then(push).then(cb.bind(null, null)).catch(cb)
      },
      predestroy() {
        destroy = ite.return()
      },
      destroy(cb) {
        if (!destroy) return cb(null)
        destroy.then(cb.bind(null, null)).catch(cb)
      }
    })

    return rs

    function push(data) {
      if (data.done) rs.push(null)
      else rs.push(data.value)
    }
  }

  static from(data, opts) {
    if (isReadStreamx(data)) return data
    if (data[asyncIterator]) return this._fromAsyncIterator(data[asyncIterator](), opts)
    if (!Array.isArray(data)) data = data === undefined ? [] : [data]

    let i = 0
    return new Readable({
      ...opts,
      read(cb) {
        this.push(i === data.length ? null : data[i++])
        cb(null)
      }
    })
  }

  static isBackpressured(rs) {
    return (
      (rs._duplexState & READ_BACKPRESSURE_STATUS) !== 0 ||
      rs._readableState.buffered >= rs._readableState.highWaterMark
    )
  }

  static isPaused(rs) {
    return (rs._duplexState & READ_RESUMED) === 0
  }

  [asyncIterator]() {
    const stream = this

    let error = null
    let promiseResolve = null
    let promiseReject = null

    this.on('error', (err) => {
      error = err
    })
    this.on('readable', onreadable)
    this.on('close', onclose)

    return {
      [asyncIterator]() {
        return this
      },
      next() {
        return new Promise(function (resolve, reject) {
          promiseResolve = resolve
          promiseReject = reject
          const data = stream.read()
          if (data !== null) ondata(data)
          else if ((stream._duplexState & DESTROYED) !== 0) ondata(null)
        })
      },
      return() {
        return destroy(null)
      },
      throw(err) {
        return destroy(err)
      }
    }

    function onreadable() {
      if (promiseResolve !== null) ondata(stream.read())
    }

    function onclose() {
      if (promiseResolve !== null) ondata(null)
    }

    function ondata(data) {
      if (promiseReject === null) return
      if (error) {
        promiseReject(error)
      } else if (data === null && (stream._duplexState & READ_DONE) === 0) {
        promiseReject(StreamError.STREAM_DESTROYED())
      } else {
        promiseResolve({ value: data, done: data === null })
      }
      promiseReject = promiseResolve = null
    }

    function destroy(err) {
      stream.destroy(err)
      return new Promise((resolve, reject) => {
        if (stream._duplexState & DESTROYED) return resolve({ value: undefined, done: true })
        stream.once('close', function () {
          if (err) reject(err)
          else resolve({ value: undefined, done: true })
        })
      })
    }
  }
}

class Writable extends Stream {
  constructor(opts) {
    super(opts)

    this._duplexState |= OPENING | READ_DONE
    this._writableState = new WritableState(this, opts)

    if (opts) {
      if (opts.writev) this._writev = opts.writev
      if (opts.write) this._write = opts.write
      if (opts.final) this._final = opts.final
      if (opts.eagerOpen) this._writableState.updateNextTick()
    }
  }

  cork() {
    this._duplexState |= WRITE_CORKED
  }

  uncork() {
    this._duplexState &= WRITE_NOT_CORKED
    this._writableState.updateNextTick()
  }

  _writev(batch, cb) {
    cb(null)
  }

  _write(data, cb) {
    this._writableState.autoBatch(data, cb)
  }

  _final(cb) {
    cb(null)
  }

  static isBackpressured(ws) {
    return (ws._duplexState & WRITE_BACKPRESSURE_STATUS) !== 0
  }

  static drained(ws) {
    if (ws.destroyed) return Promise.resolve(false)

    const state = ws._writableState
    const pending = isWritev(ws) ? Math.min(1, state.queue.length) : state.queue.length
    const writes = pending + (ws._duplexState & WRITE_WRITING ? 1 : 0)
    if (writes === 0) return Promise.resolve(true)

    if (state.drains === null) state.drains = []
    return new Promise((resolve) => {
      state.drains.push({ writes, resolve })
    })
  }

  write(data) {
    this._writableState.updateNextTick()
    return this._writableState.push(data)
  }

  end(data) {
    this._writableState.updateNextTick()
    this._writableState.end(data)
    return this
  }
}

class Duplex extends Readable {
  // and Writable
  constructor(opts) {
    super(opts)

    this._duplexState = OPENING | (this._duplexState & READ_READ_AHEAD)
    this._writableState = new WritableState(this, opts)

    if (opts) {
      if (opts.writev) this._writev = opts.writev
      if (opts.write) this._write = opts.write
      if (opts.final) this._final = opts.final
    }
  }

  cork() {
    this._duplexState |= WRITE_CORKED
  }

  uncork() {
    this._duplexState &= WRITE_NOT_CORKED
    this._writableState.updateNextTick()
  }

  _writev(batch, cb) {
    cb(null)
  }

  _write(data, cb) {
    this._writableState.autoBatch(data, cb)
  }

  _final(cb) {
    cb(null)
  }

  write(data) {
    this._writableState.updateNextTick()
    return this._writableState.push(data)
  }

  end(data) {
    this._writableState.updateNextTick()
    this._writableState.end(data)
    return this
  }
}

class Transform extends Duplex {
  constructor(opts) {
    super(opts)
    this._transformState = new TransformState(this)

    if (opts) {
      if (opts.transform) this._transform = opts.transform
      if (opts.flush) this._flush = opts.flush
    }
  }

  _write(data, cb) {
    if (this._readableState.buffered >= this._readableState.highWaterMark) {
      this._transformState.data = data
    } else {
      this._transform(data, this._transformState.afterTransform)
    }
  }

  _read(cb) {
    if (this._transformState.data !== null) {
      const data = this._transformState.data
      this._transformState.data = null
      cb(null)
      this._transform(data, this._transformState.afterTransform)
    } else {
      cb(null)
    }
  }

  destroy(err) {
    super.destroy(err)
    if (this._transformState.data !== null) {
      this._transformState.data = null
      this._transformState.afterTransform()
    }
  }

  _transform(data, cb) {
    cb(null, data)
  }

  _flush(cb) {
    cb(null)
  }

  _final(cb) {
    this._transformState.afterFinal = cb
    this._flush(transformAfterFlush.bind(this))
  }
}

class PassThrough extends Transform {}

function transformAfterFlush(err, data) {
  const cb = this._transformState.afterFinal
  if (err) return cb(err)

  if (data !== null && data !== undefined) this.push(data)
  this.push(null)
  cb(null)
}

function pipelinePromise(...streams) {
  return new Promise((resolve, reject) => {
    return pipeline(...streams, (err) => {
      if (err) return reject(err)
      resolve()
    })
  })
}

function pipeline(stream, ...streams) {
  const all = Array.isArray(stream) ? [...stream, ...streams] : [stream, ...streams]
  const done = all.length && typeof all[all.length - 1] === 'function' ? all.pop() : null

  if (all.length < 2) throw StreamError.BAD_ARGUMENT('Pipeline requires at least 2 streams')

  let src = all[0]
  let dest = null
  let error = null

  for (let i = 1; i < all.length; i++) {
    dest = all[i]

    if (isStreamx(src)) {
      src.pipe(dest, onerror)
    } else {
      errorHandle(src, true, i > 1, onerror)
      src.pipe(dest)
    }

    src = dest
  }

  if (done) {
    let fin = false

    const autoDestroy =
      isStreamx(dest) || !!(dest._writableState && dest._writableState.autoDestroy)

    dest.on('error', (err) => {
      if (error === null) error = err
    })

    dest.on('finish', () => {
      fin = true
      if (!autoDestroy) done(error)
    })

    if (autoDestroy) {
      dest.on('close', () => done(error || (fin ? null : StreamError.PREMATURE_CLOSE())))
    }
  }

  return dest

  function errorHandle(s, rd, wr, onerror) {
    s.on('error', onerror)
    s.on('close', onclose)

    function onclose() {
      if (rd && s._readableState && !s._readableState.ended) {
        return onerror(StreamError.PREMATURE_CLOSE())
      }
      if (wr && s._writableState && !s._writableState.ended) {
        return onerror(StreamError.PREMATURE_CLOSE())
      }
    }
  }

  function onerror(err) {
    if (!err || error) return
    error = err

    for (const s of all) {
      s.destroy(err)
    }
  }
}

function echo(s) {
  return s
}

function isStream(stream) {
  return !!stream._readableState || !!stream._writableState
}

function isStreamx(stream) {
  return typeof stream._duplexState === 'number' && isStream(stream)
}

function isEnding(stream) {
  return !!stream._readableState && stream._readableState.ending
}

function isEnded(stream) {
  return !!stream._readableState && stream._readableState.ended
}

function isFinishing(stream) {
  return !!stream._writableState && stream._writableState.ending
}

function isFinished(stream) {
  return !!stream._writableState && stream._writableState.ended
}

function getStreamError(stream, opts = {}) {
  const err =
    (stream._readableState && stream._readableState.error) ||
    (stream._writableState && stream._writableState.error)

  // avoid implicit errors by default
  return !opts.all && StreamError.isStreamDestroyed(err) ? null : err
}

function isReadStreamx(stream) {
  return isStreamx(stream) && stream.readable
}

function isDisturbed(stream) {
  return (
    (stream._duplexState & OPENING) !== OPENING ||
    (stream._duplexState & DESTROYING) === DESTROYING ||
    (stream._duplexState & ACTIVE_OR_TICKING) !== 0
  )
}

function isTypedArray(data) {
  return typeof data === 'object' && data !== null && typeof data.byteLength === 'number'
}

function defaultByteLength(data) {
  return isTypedArray(data) ? data.byteLength : 1024
}

function noop() {}

function abort() {
  this.destroy(StreamError.ABORTED())
}

function isWritev(s) {
  return s._writev !== Writable.prototype._writev && s._writev !== Duplex.prototype._writev
}

module.exports = {
  pipeline,
  pipelinePromise,
  isStream,
  isStreamx,
  isEnding,
  isEnded,
  isFinishing,
  isFinished,
  isDisturbed,
  getStreamError,
  Stream,
  Writable,
  Readable,
  Duplex,
  Transform,
  // Export PassThrough for compatibility with Node.js core's stream module
  PassThrough
}
module.exports = class StreamError extends Error {
  constructor(msg, code, fn = StreamError) {
    super(msg)

    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  static isStreamDestroyed(err) {
    return err && err.code === 'STREAM_DESTROYED'
  }

  static isPrematureClose(err) {
    return err && err.code === 'PREMATURE_CLOSE'
  }

  static isAborted(err) {
    return err && err.code === 'ABORTED'
  }

  static isBadArgument(err) {
    return err && err.code === 'BAD_ARGUMENT'
  }

  get name() {
    return 'StreamError'
  }

  static STREAM_DESTROYED() {
    return new StreamError('Stream was destroyed', 'STREAM_DESTROYED', StreamError.STREAM_DESTROYED)
  }

  static PREMATURE_CLOSE(msg = 'Premature close') {
    return new StreamError(msg, 'PREMATURE_CLOSE', StreamError.PREMATURE_CLOSE)
  }

  static ABORTED() {
    return new StreamError('Stream aborted', 'ABORTED', StreamError.ABORTED)
  }

  static BAD_ARGUMENT(msg = 'Bad argument') {
    return new StreamError(msg, 'BAD_ARGUMENT', StreamError.BAD_ARGUMENT)
  }
}
{
  "name": "streamx",
  "version": "2.27.0",
  "description": "An iteration of the Node.js core streams with a series of improvements",
  "main": "index.js",
  "exports": {
    ".": "./index.js",
    "./package": "./package.json",
    "./errors": "./lib/errors"
  },
  "dependencies": {
    "events-universal": "^1.0.0",
    "fast-fifo": "^1.3.2",
    "text-decoder": "^1.1.0"
  },
  "devDependencies": {
    "b4a": "^1.6.6",
    "brittle": "^3.1.1",
    "end-of-stream": "^1.4.4",
    "lunte": "^1.8.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "files": [
    "index.js",
    "lib/errors.js"
  ],
  "scripts": {
    "format": "prettier . --write",
    "test": "brittle test/all.js && brittle-bare test/all.js",
    "lint": "prettier . --check && lunte"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/streamx.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/streamx/issues"
  },
  "homepage": "https://github.com/mafintosh/streamx"
}
const codecs = require('codecs')
const b = require('b4a')

const SEP = b.alloc(1)
const SEP_BUMPED = b.from([0x1])
const EMPTY = b.alloc(0)

module.exports = class SubEncoder {
  constructor (prefix, encoding, parent = null) {
    this.userEncoding = codecs(encoding)
    this.prefix = prefix != null ? createPrefix(prefix, parent) : null
    this.lt = this.prefix && b.concat([this.prefix.subarray(0, this.prefix.byteLength - 1), SEP_BUMPED])
  }

  _encodeRangeUser (r) {
    if (this.userEncoding.encodeRange) return this.userEncoding.encodeRange(r)

    const res = {}
    if (r.gt != null) res.gt = this.userEncoding.encode(r.gt)
    if (r.gte != null) res.gte = this.userEncoding.encode(r.gte)
    if (r.lte != null) res.lte = this.userEncoding.encode(r.lte)
    if (r.lt != null) res.lt = this.userEncoding.encode(r.lt)

    return res
  }

  _addPrefix (key) {
    return this.prefix ? b.concat([this.prefix, key]) : key
  }

  encode (key) {
    return this._addPrefix(this.userEncoding.encode(key))
  }

  encodeRange (range) {
    const r = this._encodeRangeUser(range)

    if (r.gt) r.gt = this._addPrefix(r.gt)
    else if (r.gte) r.gte = this._addPrefix(r.gte)
    else if (this.prefix) r.gte = this.prefix

    if (r.lt) r.lt = this._addPrefix(r.lt)
    else if (r.lte) r.lte = this._addPrefix(r.lte)
    else if (this.prefix) r.lt = this.lt

    return r
  }

  decode (key) {
    return this.userEncoding.decode(this.prefix ? key.subarray(this.prefix.byteLength) : key)
  }

  sub (prefix, encoding) {
    return new SubEncoder(prefix || EMPTY, compat(encoding), this.prefix)
  }
}

function createPrefix (prefix, parent) {
  prefix = typeof prefix === 'string' ? b.from(prefix) : prefix

  if (prefix && parent) return b.concat([parent, prefix, SEP])
  if (prefix) return b.concat([prefix, SEP])
  if (parent) return b.concat([parent, SEP])
  return SEP
}

function compat (enc) {
  if (enc && enc.keyEncoding) return enc.keyEncoding
  return enc
}
{
  "name": "sub-encoder",
  "version": "2.1.3",
  "description": "Generate sub encodings for key/value stores",
  "main": "index.js",
  "scripts": {
    "test": "standard && brittle test/*.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sub-encoder.git"
  },
  "keywords": [
    "kv-store",
    "encoding",
    "hyperbee"
  ],
  "author": "Andrew Osheroff <andrewosh@gmail.com>",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/sub-encoder/issues"
  },
  "homepage": "https://github.com/holepunchto/sub-encoder#readme",
  "devDependencies": {
    "brittle": "^3.1.1",
    "compact-encoding": "^2.12.0",
    "hyperbee": "^2.11.0",
    "hypercore": "^10.3.2",
    "index-encoder": "^3.0.0",
    "random-access-memory": "^6.0.0",
    "standard": "^17.0.0"
  },
  "dependencies": {
    "b4a": "^1.6.0",
    "codecs": "^3.1.0"
  }
}
const { Readable } = require('streamx')

module.exports = function (s, forks = 2) {
  const streams = new Array(forks)
  const status = new Array(forks).fill(true)

  let ended = false

  for (let i = 0; i < forks; i++) {
    streams[i] = new Readable({
      read (cb) {
        const check = !status[i]
        status[i] = true
        if (check && allReadable()) s.resume()
        cb(null)
      }
    })
  }

  s.on('end', function () {
    ended = true
    for (const stream of streams) stream.push(null)
  })

  s.on('error', function (err) {
    for (const stream of streams) stream.destroy(err)
  })

  s.on('close', function () {
    if (ended) return
    for (const stream of streams) stream.destroy()
  })

  s.on('data', function (data) {
    let needsPause = false
    for (let i = 0; i < streams.length; i++) {
      if (!(status[i] = streams[i].push(data))) {
        needsPause = true
      }
    }
    if (needsPause) s.pause()
  })

  return streams

  function allReadable () {
    for (let j = 0; j < status.length; j++) {
      if (!status[j]) return false
    }
    return true
  }
}
{
  "name": "teex",
  "version": "1.0.1",
  "description": "Turn a readable stream into multiple readable streamx streams",
  "main": "index.js",
  "dependencies": {
    "streamx": "^2.12.5"
  },
  "devDependencies": {
    "standard": "^14.3.4",
    "tape": "^5.0.1"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/teex.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/teex/issues"
  },
  "homepage": "https://github.com/mafintosh/teex"
}
const PassThroughDecoder = require('./lib/pass-through-decoder')
const UTF8Decoder = require('./lib/utf8-decoder')

module.exports = class TextDecoder {
  constructor(encoding = 'utf8') {
    this.encoding = normalizeEncoding(encoding)

    switch (this.encoding) {
      case 'utf8':
        this.decoder = new UTF8Decoder()
        break
      case 'utf16le':
      case 'base64':
        throw new Error('Unsupported encoding: ' + this.encoding)
      default:
        this.decoder = new PassThroughDecoder(this.encoding)
    }
  }

  get remaining() {
    return this.decoder.remaining
  }

  push(data) {
    if (typeof data === 'string') return data
    return this.decoder.decode(data)
  }

  // For Node.js compatibility
  write(data) {
    return this.push(data)
  }

  end(data) {
    let result = ''
    if (data) result = this.push(data)
    result += this.decoder.flush()
    return result
  }
}

function normalizeEncoding(encoding) {
  encoding = encoding.toLowerCase()

  switch (encoding) {
    case 'utf8':
    case 'utf-8':
      return 'utf8'
    case 'ucs2':
    case 'ucs-2':
    case 'utf16le':
    case 'utf-16le':
      return 'utf16le'
    case 'latin1':
    case 'binary':
      return 'latin1'
    case 'base64':
    case 'ascii':
    case 'hex':
      return encoding
    default:
      throw new Error('Unknown encoding: ' + encoding)
  }
}
const b4a = require('b4a')

module.exports = class PassThroughDecoder {
  constructor(encoding) {
    this.encoding = encoding
  }

  get remaining() {
    return 0
  }

  decode(data) {
    return b4a.toString(data, this.encoding)
  }

  flush() {
    return ''
  }
}
const b4a = require('b4a')

/**
 * https://encoding.spec.whatwg.org/#utf-8-decoder
 */
module.exports = class UTF8Decoder {
  constructor() {
    this._reset()
  }

  get remaining() {
    return this.bytesSeen
  }

  decode(data) {
    if (data.byteLength === 0) return ''

    if (this.bytesNeeded === 0 && trailingIncomplete(data, 0) === 0) {
      this.bytesSeen = trailingBytesSeen(data)
      return b4a.toString(data, 'utf8')
    }

    let result = ''
    let start = 0

    if (this.bytesNeeded > 0) {
      while (start < data.byteLength) {
        const byte = data[start]

        if (byte < this.lowerBoundary || byte > this.upperBoundary) {
          result += '\ufffd'
          this._reset()
          break
        }

        this.lowerBoundary = 0x80
        this.upperBoundary = 0xbf
        this.codePoint = (this.codePoint << 6) | (byte & 0x3f)
        this.bytesSeen++
        start++

        if (this.bytesSeen === this.bytesNeeded) {
          result += String.fromCodePoint(this.codePoint)
          this._reset()
          break
        }
      }

      if (this.bytesNeeded > 0) return result
    }

    const trailing = trailingIncomplete(data, start)
    const end = data.byteLength - trailing

    if (end > start) result += b4a.toString(data, 'utf8', start, end)

    for (let i = end; i < data.byteLength; i++) {
      const byte = data[i]

      if (this.bytesNeeded === 0) {
        if (byte <= 0x7f) {
          this.bytesSeen = 0
          result += String.fromCharCode(byte)
        } else if (byte >= 0xc2 && byte <= 0xdf) {
          this.bytesNeeded = 2
          this.bytesSeen = 1
          this.codePoint = byte & 0x1f
        } else if (byte >= 0xe0 && byte <= 0xef) {
          if (byte === 0xe0) this.lowerBoundary = 0xa0
          else if (byte === 0xed) this.upperBoundary = 0x9f
          this.bytesNeeded = 3
          this.bytesSeen = 1
          this.codePoint = byte & 0xf
        } else if (byte >= 0xf0 && byte <= 0xf4) {
          if (byte === 0xf0) this.lowerBoundary = 0x90
          else if (byte === 0xf4) this.upperBoundary = 0x8f
          this.bytesNeeded = 4
          this.bytesSeen = 1
          this.codePoint = byte & 0x7
        } else {
          this.bytesSeen = 1
          result += '\ufffd'
        }

        continue
      }

      if (byte < this.lowerBoundary || byte > this.upperBoundary) {
        result += '\ufffd'
        i--
        this._reset()

        continue
      }

      this.lowerBoundary = 0x80
      this.upperBoundary = 0xbf

      this.codePoint = (this.codePoint << 6) | (byte & 0x3f)
      this.bytesSeen++

      if (this.bytesSeen === this.bytesNeeded) {
        result += String.fromCodePoint(this.codePoint)
        this._reset()
      }
    }

    return result
  }

  flush() {
    const result = this.bytesNeeded > 0 ? '\ufffd' : ''
    this._reset()
    return result
  }

  _reset() {
    this.codePoint = 0
    this.bytesNeeded = 0
    this.bytesSeen = 0
    this.lowerBoundary = 0x80
    this.upperBoundary = 0xbf
  }
}

function trailingIncomplete(data, start) {
  const len = data.byteLength
  if (len <= start) return 0

  const limit = Math.max(start, len - 4)

  let i = len - 1
  while (i > limit && (data[i] & 0xc0) === 0x80) i--

  if (i < start) return 0

  const byte = data[i]

  let needed
  if (byte <= 0x7f) return 0
  if (byte >= 0xc2 && byte <= 0xdf) needed = 2
  else if (byte >= 0xe0 && byte <= 0xef) needed = 3
  else if (byte >= 0xf0 && byte <= 0xf4) needed = 4
  else return 0

  const available = len - i
  return available < needed ? available : 0
}

function trailingBytesSeen(data) {
  const len = data.byteLength
  if (len === 0) return 0

  const last = data[len - 1]

  if (last <= 0x7f) return 0
  if ((last & 0xc0) !== 0x80) return 1

  const limit = Math.max(0, len - 4)

  let i = len - 2
  while (i >= limit && (data[i] & 0xc0) === 0x80) i--

  if (i < 0) return 1

  const first = data[i]

  let needed
  if (first >= 0xc2 && first <= 0xdf) needed = 2
  else if (first >= 0xe0 && first <= 0xef) needed = 3
  else if (first >= 0xf0 && first <= 0xf4) needed = 4
  else return 1

  if (len - i !== needed) return 1

  if (needed >= 3) {
    const second = data[i + 1]
    if (first === 0xe0 && second < 0xa0) return 1
    if (first === 0xed && second > 0x9f) return 1
    if (first === 0xf0 && second < 0x90) return 1
    if (first === 0xf4 && second > 0x8f) return 1
  }

  return 0
}
{
  "name": "text-decoder",
  "version": "1.2.7",
  "description": "Streaming text decoder that preserves multibyte Unicode characters",
  "exports": {
    "./package": "./package.json",
    ".": "./index.js"
  },
  "files": [
    "index.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/text-decoder.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/text-decoder/issues"
  },
  "homepage": "https://github.com/holepunchto/text-decoder#readme",
  "dependencies": {
    "b4a": "^1.6.4"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  }
}
module.exports = class TimeOrderedSet {
  constructor () {
    this.oldest = null
    this.latest = null
    this.length = 0
  }

  has (node) {
    return !!(node.next || node.prev) || node === this.oldest
  }

  add (node) {
    if (this.has(node)) this.remove(node)

    if (!this.latest && !this.oldest) {
      this.latest = this.oldest = node
      node.prev = node.next = null
    } else {
      this.latest.next = node
      node.prev = this.latest
      node.next = null
      this.latest = node
    }

    this.length++

    return node
  }

  remove (node) {
    if (!this.has(node)) return node

    if (this.oldest !== node && this.latest !== node) {
      node.prev.next = node.next
      node.next.prev = node.prev
    } else {
      if (this.oldest === node) {
        this.oldest = node.next
        if (this.oldest) this.oldest.prev = null
      }
      if (this.latest === node) {
        this.latest = node.prev
        if (this.latest) this.latest.next = null
      }
    }

    node.next = node.prev = null
    this.length--

    return node
  }

  toArray ({ limit = Infinity, reverse = false } = {}) {
    const list = []

    if (reverse) {
      let node = this.latest
      while (node && limit--) {
        list.push(node)
        node = node.prev
      }
    } else {
      let node = this.oldest
      while (node && limit--) {
        list.push(node)
        node = node.next
      }
    }

    return list
  }
}
{
  "name": "time-ordered-set",
  "version": "2.0.1",
  "description": "Efficiently maintain a set of nodes ordered by the time they were added to the set",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "devDependencies": {
    "brittle": "^3.0.0",
    "standard": "^17.1.2"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/time-ordered-set.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/time-ordered-set/issues"
  },
  "homepage": "https://github.com/mafintosh/time-ordered-set"
}
module.exports = class TimerBrowser {
  constructor (ms, fn, ctx = null, interval = false) {
    this.ms = ms
    this.ontimeout = fn
    this.context = ctx || null
    this.interval = interval
    this.done = false

    this._timer = interval
      ? setInterval(callInterval, ms, this)
      : setTimeout(callTimeout, ms, this)
  }

  unref () {}

  ref () {}

  refresh () {
    if (this.done) return

    if (this.interval) {
      clearInterval(this._timer)
      this._timer = setInterval(callInterval, this.ms, this)
    } else {
      clearTimeout(this._timer)
      this._timer = setTimeout(callTimeout, this.ms, this)
    }
  }

  destroy () {
    this.done = true
    this.ontimeout = null

    if (this.interval) clearInterval(this._timer)
    else clearTimeout(this._timer)
  }

  static once (ms, fn, ctx) {
    return new this(ms, fn, ctx, false)
  }

  static on (ms, fn, ctx) {
    return new this(ms, fn, ctx, true)
  }
}

function callTimeout (self) {
  self.done = true
  self.ontimeout.call(self.context)
}

function callInterval (self) {
  self.ontimeout.call(self.context)
}
module.exports = isNode()
  ? require('./node')
  : require('./browser')

function isNode () {
  const to = setTimeout(function () {}, 1000)
  clearTimeout(to)
  return !!to.refresh
}
module.exports = class Timer {
  constructor (ms, fn, ctx = null, interval = false) {
    this.ms = ms
    this.ontimeout = fn
    this.context = ctx
    this.interval = interval
    this.done = false

    this._timer = interval
      ? setInterval(callInterval, ms, this)
      : setTimeout(callTimeout, ms, this)
  }

  unref () {
    this._timer.unref()
  }

  ref () {
    this._timer.ref()
  }

  refresh () {
    if (this.done !== true) this._timer.refresh()
  }

  destroy () {
    this.done = true
    this.ontimeout = null
    if (this.interval) clearInterval(this._timer)
    else clearTimeout(this._timer)
  }

  static once (ms, fn, ctx) {
    return new this(ms, fn, ctx, false)
  }

  static on (ms, fn, ctx) {
    return new this(ms, fn, ctx, true)
  }
}

function callTimeout (self) {
  self.done = true
  self.ontimeout.call(self.context)
}

function callInterval (self) {
  self.ontimeout.call(self.context)
}
{
  "name": "timeout-refresh",
  "version": "2.0.1",
  "description": "Efficiently refresh a timer",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^16.0.4",
    "tape": "^5.5.2"
  },
  "browser": "./browser.js",
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/timeout-refresh.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/timeout-refresh/issues"
  },
  "homepage": "https://github.com/mafintosh/timeout-refresh"
}
const b4a = require('b4a')

module.exports = class BufferMap {
  constructor (other) {
    this.m = other ? new Map([...other.m]) : new Map()
  }

  get size () {
    return this.m.size
  }

  get (key) {
    if (b4a.isBuffer(key)) key = b4a.toString(key, 'hex')
    return this.m.get(key)
  }

  set (key, value) {
    if (b4a.isBuffer(key)) key = b4a.toString(key, 'hex')
    return this.m.set(key, value)
  }

  delete (key) {
    if (b4a.isBuffer(key)) key = b4a.toString(key, 'hex')
    return this.m.delete(key)
  }

  has (key) {
    if (b4a.isBuffer(key)) key = b4a.toString(key, 'hex')
    return this.m.has(key)
  }

  * [Symbol.iterator] () {
    for (const [key, value] of this.m) {
      yield [b4a.from(key, 'hex'), value]
    }
  }

  * keys () {
    for (const key of this.m.keys()) {
      yield b4a.from(key, 'hex')
    }
  }

  values () {
    return this.m.values()
  }

  clear () {
    return this.m.clear()
  }
}
{
  "name": "tiny-buffer-map",
  "version": "1.1.1",
  "description": "A very simple map for Buffers",
  "main": "index.js",
  "scripts": {
    "test": "brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/andrewosh/tiny-buffer-map.git"
  },
  "keywords": [
    "buffer",
    "map"
  ],
  "author": "Andrew Osheroff <andrewosh@gmail.com>",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/andrewosh/tiny-buffer-map/issues"
  },
  "homepage": "https://github.com/andrewosh/tiny-buffer-map#readme",
  "dependencies": {
    "b4a": "^1.6.0"
  },
  "devDependencies": {
    "brittle": "^3.0.4"
  }
}
require.addon = require('require-addon')

module.exports = require.addon('.', __filename)
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

const v4Seg = '(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])'
const v4Str = `(${v4Seg}[.]){3}${v4Seg}`
const IPv4Pattern = new RegExp(`^${v4Str}$`)

const v6Seg = '(?:[0-9a-fA-F]{1,4})'
const IPv6Pattern = new RegExp(
  '^(' +
    `(?:${v6Seg}:){7}(?:${v6Seg}|:)|` +
    `(?:${v6Seg}:){6}(?:${v4Str}|:${v6Seg}|:)|` +
    `(?:${v6Seg}:){5}(?::${v4Str}|(:${v6Seg}){1,2}|:)|` +
    `(?:${v6Seg}:){4}(?:(:${v6Seg}){0,1}:${v4Str}|(:${v6Seg}){1,3}|:)|` +
    `(?:${v6Seg}:){3}(?:(:${v6Seg}){0,2}:${v4Str}|(:${v6Seg}){1,4}|:)|` +
    `(?:${v6Seg}:){2}(?:(:${v6Seg}){0,3}:${v4Str}|(:${v6Seg}){1,5}|:)|` +
    `(?:${v6Seg}:){1}(?:(:${v6Seg}){0,4}:${v4Str}|(:${v6Seg}){1,6}|:)|` +
    `(?::((?::${v6Seg}){0,5}:${v4Str}|(?::${v6Seg}){1,7}|:))` +
    ')(%[0-9a-zA-Z-.:]{1,})?$'
)

const isIPv4 = (exports.isIPv4 = function isIPv4(host) {
  return IPv4Pattern.test(host)
})

const isIPv6 = (exports.isIPv6 = function isIPv6(host) {
  return IPv6Pattern.test(host)
})

exports.isIP = function isIP(host) {
  if (isIPv4(host)) return 4
  if (isIPv6(host)) return 6
  return 0
}
const events = require('events')
const b4a = require('b4a')
const binding = require('../binding')

module.exports = class NetworkInterfaces extends events.EventEmitter {
  constructor(udx) {
    super()

    this._handle = b4a.alloc(binding.sizeof_udx_napi_interface_event_t)
    this._watching = false
    this._destroying = null

    binding.udx_napi_interface_event_init(
      udx._handle,
      this._handle,
      this,
      this._onevent,
      this._onclose
    )

    this.interfaces = binding.udx_napi_interface_event_get_addrs(this._handle)
  }

  _onclose() {
    this.emit('close')
  }

  _onevent() {
    this.interfaces = binding.udx_napi_interface_event_get_addrs(this._handle)

    this.emit('change', this.interfaces)
  }

  watch() {
    if (this._watching) return this
    this._watching = true

    binding.udx_napi_interface_event_start(this._handle)

    return this
  }

  unwatch() {
    if (!this._watching) return this
    this._watching = false

    binding.udx_napi_interface_event_stop(this._handle)

    return this
  }

  async destroy() {
    if (this._destroying) return this._destroying
    this._destroying = events.once(this, 'close')

    binding.udx_napi_interface_event_close(this._handle)

    return this._destroying
  }

  [Symbol.iterator]() {
    return this.interfaces[Symbol.iterator]()
  }
}
const events = require('events')
const b4a = require('b4a')
const binding = require('../binding')
const ip = require('./ip')

module.exports = class UDXSocket extends events.EventEmitter {
  constructor(udx, opts = {}) {
    super()

    this.udx = udx

    this._handle = b4a.alloc(binding.sizeof_udx_napi_socket_t)
    this._inited = false
    this._host = null
    this._family = 0
    this._ipv6Only = opts.ipv6Only === true
    this._reuseAddress = opts.reuseAddress === true
    this._port = 0
    this._reqs = []
    this._free = []
    this._closing = null
    this._closed = false

    this._view64 = new BigUint64Array(
      this._handle.buffer,
      this._handle.byteOffset,
      this._handle.byteLength >> 3
    )

    this.streams = new Set()

    this.userData = null
  }

  get bound() {
    return this._port !== 0
  }

  get closing() {
    return this._closing !== null
  }

  get idle() {
    return this.streams.size === 0
  }

  get busy() {
    return this.streams.size > 0
  }

  get bytesTransmitted() {
    if (this._inited !== true) return 0
    return Number(this._view64[binding.offsetof_udx_socket_t_bytes_tx >> 3])
  }

  get packetsTransmitted() {
    if (this._inited !== true) return 0
    return Number(this._view64[binding.offsetof_udx_socket_t_packets_tx >> 3])
  }

  get bytesReceived() {
    if (this._inited !== true) return 0
    return Number(this._view64[binding.offsetof_udx_socket_t_bytes_rx >> 3])
  }

  get packetsReceived() {
    if (this._inited !== true) return 0
    return Number(this._view64[binding.offsetof_udx_socket_t_packets_rx >> 3])
  }

  get packetsDroppedByKernel() {
    if (this._inited !== true) return 0
    return Number(this._view64[binding.offsetof_udx_socket_t_packets_dropped_by_kernel >> 3])
  }

  toJSON() {
    return {
      bound: this.bound,
      closing: this.closing,
      streams: this.streams.size,
      address: this.address(),
      ipv6Only: this._ipv6Only,
      reuseAddress: this._reuseAddress,
      idle: this.idle,
      busy: this.busy
    }
  }

  _init() {
    if (this._inited) return

    binding.udx_napi_socket_init(
      this.udx._handle,
      this._handle,
      this,
      this._onsend,
      this._onmessage,
      this._onclose,
      this._reallocMessage
    )

    this._inited = true
  }

  _onsend(id, err) {
    const req = this._reqs[id]

    const onflush = req.onflush

    req.buffer = null
    req.onflush = null

    this._free.push(id)

    onflush(err >= 0)

    // gc the free list
    if (this._free.length >= 16 && this._free.length === this._reqs.length) {
      this._free = []
      this._reqs = []
    }
  }

  _onmessage(len, port, host, family) {
    this.emit('message', this.udx._consumeMessage(len), { host, family, port })
    return this.udx._buffer
  }

  _onclose() {
    this.emit('close')
  }

  _reallocMessage() {
    return this.udx._reallocMessage()
  }

  _onidle() {
    this.emit('idle')
  }

  _onbusy() {
    this.emit('busy')
  }

  _addStream(stream) {
    if (this.streams.has(stream)) return false
    this.streams.add(stream)
    if (this.streams.size === 1) this._onbusy()
    return true
  }

  _removeStream(stream) {
    if (!this.streams.has(stream)) return false
    this.streams.delete(stream)
    const closed = this._closeMaybe()
    if (this.idle && !closed) this._onidle()
    return true
  }

  address() {
    if (!this.bound) return null
    return { host: this._host, family: this._family, port: this._port }
  }

  bind(port, host) {
    if (this.bound) throw new Error('Already bound')
    if (this.closing) throw new Error('Socket is closed')

    if (!port) port = 0

    let flags = 0
    if (this._ipv6Only) flags |= binding.UV_UDP_IPV6ONLY
    if (this._reuseAddress) flags |= binding.UV_UDP_REUSEADDR

    let family

    if (host) {
      family = ip.isIP(host)
      if (!family) throw new Error(`${host} is not a valid IP address`)

      if (!this._inited) this._init()

      this._port = binding.udx_napi_socket_bind(this._handle, port, host, family, flags)
    } else {
      if (!this._inited) this._init()

      try {
        host = '::'
        family = 6
        this._port = binding.udx_napi_socket_bind(this._handle, port, host, family, flags)
      } catch {
        host = '0.0.0.0'
        family = 4
        this._port = binding.udx_napi_socket_bind(this._handle, port, host, family, flags)
      }
    }

    this._host = host
    this._family = family

    this.emit('listening')
  }

  async close() {
    if (this._closing) return this._closing
    this._closing = new Promise((resolve) => this.once('close', resolve))
    this._closeMaybe()
    return this._closing
  }

  _closeMaybe() {
    if (this._closed || this._closing === null) return this._closed

    if (!this._inited) {
      this._closed = true
      this.emit('close')
      return true
    }

    if (this.idle) {
      binding.udx_napi_socket_close(this._handle)
      this._closed = true
    }

    return this._closed
  }

  setTTL(ttl) {
    if (!this._inited) throw new Error('Socket not active')
    binding.udx_napi_socket_set_ttl(this._handle, ttl)
  }

  getRecvBufferSize() {
    if (!this._inited) throw new Error('Socket not active')
    return binding.udx_napi_socket_get_recv_buffer_size(this._handle)
  }

  setRecvBufferSize(size) {
    if (!this._inited) throw new Error('Socket not active')
    return binding.udx_napi_socket_set_recv_buffer_size(this._handle, size)
  }

  getSendBufferSize() {
    if (!this._inited) throw new Error('Socket not active')
    return binding.udx_napi_socket_get_send_buffer_size(this._handle)
  }

  setSendBufferSize(size) {
    if (!this._inited) throw new Error('Socket not active')
    return binding.udx_napi_socket_set_send_buffer_size(this._handle, size)
  }

  addMembership(group, ifaceAddress) {
    if (!this._inited) throw new Error('Socket not active')
    return binding.udx_napi_socket_set_membership(this._handle, group, ifaceAddress || '', true)
  }

  dropMembership(group, ifaceAddress) {
    if (!this._inited) throw new Error('Socket not active')
    return binding.udx_napi_socket_set_membership(this._handle, group, ifaceAddress || '', false)
  }

  async send(buffer, port, host, ttl) {
    if (this.closing) return false

    if (!host) host = '127.0.0.1'

    const family = ip.isIP(host)
    if (!family) throw new Error(`${host} is not a valid IP address`)

    if (!this.bound) this.bind(0)

    const id = this._allocSend()
    const req = this._reqs[id]

    req.buffer = buffer

    const promise = new Promise((resolve) => {
      req.onflush = resolve
    })

    binding.udx_napi_socket_send_ttl(
      this._handle,
      req.handle,
      id,
      buffer,
      port,
      host,
      family,
      ttl || 0
    )

    return promise
  }

  trySend(buffer, port, host, ttl) {
    if (this.closing) return

    if (!host) host = '127.0.0.1'

    const family = ip.isIP(host)
    if (!family) throw new Error(`${host} is not a valid IP address`)

    if (!this.bound) this.bind(0)

    const id = this._allocSend()
    const req = this._reqs[id]

    req.buffer = buffer
    req.onflush = noop

    binding.udx_napi_socket_send_ttl(
      this._handle,
      req.handle,
      id,
      buffer,
      port,
      host,
      family,
      ttl || 0
    )
  }

  _allocSend() {
    if (this._free.length > 0) return this._free.pop()
    const handle = b4a.allocUnsafe(binding.sizeof_udx_socket_send_t)
    return this._reqs.push({ handle, buffer: null, onflush: null }) - 1
  }
}

function noop() {}
const streamx = require('streamx')
const b4a = require('b4a')
const binding = require('../binding')
const ip = require('./ip')

const MAX_PACKET = 2048
const BUFFER_SIZE = 65536 + MAX_PACKET

module.exports = class UDXStream extends streamx.Duplex {
  constructor(udx, id, opts = {}) {
    super({ mapWritable: toBuffer, eagerOpen: true })

    this.udx = udx
    this.socket = null

    this._handle = b4a.alloc(binding.sizeof_udx_napi_stream_t)
    this._view = new Uint32Array(
      this._handle.buffer,
      this._handle.byteOffset,
      this._handle.byteLength >> 2
    )
    this._view16 = new Uint16Array(
      this._handle.buffer,
      this._handle.byteOffset,
      this._handle.byteLength >> 1
    )
    this._view64 = new BigUint64Array(
      this._handle.buffer,
      this._handle.byteOffset,
      this._handle.byteLength >> 3
    )

    this._wreqs = []
    this._wfree = []

    this._sreqs = []
    this._sfree = []
    this._closed = false

    this._flushing = 0
    this._flushes = []

    this._buffer = null
    this._reallocData()

    this._onwrite = null
    this._ondestroy = null
    this._firewall = opts.firewall || firewallAll

    this._remoteChanging = null
    this._previousSocket = null

    this.id = id
    this.remoteId = 0
    this.remoteHost = null
    this.remoteFamily = 0
    this.remotePort = 0

    this.userData = null

    binding.udx_napi_stream_init(
      this.udx._handle,
      this._handle,
      id,
      opts.framed ? 1 : 0,
      this,
      this._ondata,
      this._onend,
      this._ondrain,
      this._onack,
      this._onsend,
      this._onmessage,
      this._onclose,
      this._onfirewall,
      this._onremotechanged,
      this._reallocData,
      this._reallocMessage
    )

    if (opts.seq) binding.udx_napi_stream_set_seq(this._handle, opts.seq)

    binding.udx_napi_stream_recv_start(this._handle, this._buffer)
  }

  get connected() {
    return this.socket !== null
  }

  get mtu() {
    return this._view16[binding.offsetof_udx_stream_t_mtu >> 1]
  }

  get rtt() {
    return this._view[binding.offsetof_udx_stream_t_srtt >> 2]
  }

  get cwnd() {
    return this._view[binding.offsetof_udx_stream_t_cwnd >> 2]
  }

  get rtoCount() {
    return this._view16[binding.offsetof_udx_stream_t_rto_count >> 1]
  }

  get retransmits() {
    return this._view16[binding.offsetof_udx_stream_t_retransmit_count >> 1]
  }

  get bbrState() {
    const view = new Uint8Array(
      this._handle.buffer,
      this._handle.byteOffset,
      this._handle.byteLength
    )
    return view[binding.offsetof_udx_stream_t_bbr_state]
  }

  get bbrBandwidth() {
    return binding.udx_napi_stream_get_bw(this._handle)
  }

  get fastRecoveries() {
    return this._view16[binding.offsetof_udx_stream_t_fast_recovery_count >> 1]
  }

  get inflight() {
    return this._view[binding.offsetof_udx_stream_t_inflight >> 2]
  }

  get bytesTransmitted() {
    return Number(this._view64[binding.offsetof_udx_stream_t_bytes_tx >> 3])
  }

  get packetsTransmitted() {
    return Number(this._view64[binding.offsetof_udx_stream_t_packets_tx >> 3])
  }

  get bytesReceived() {
    return Number(this._view64[binding.offsetof_udx_stream_t_bytes_rx >> 3])
  }

  get packetsReceived() {
    return Number(this._view64[binding.offsetof_udx_stream_t_packets_rx >> 3])
  }

  get localHost() {
    return this.socket ? this.socket.address().host : null
  }

  get localFamily() {
    return this.socket ? this.socket.address().family : 0
  }

  get localPort() {
    return this.socket ? this.socket.address().port : 0
  }

  setInteractive(bool) {
    if (!this._closed) return
    binding.udx_napi_stream_set_mode(this._handle, bool ? 0 : 1)
  }

  connect(socket, remoteId, port, host, opts = {}) {
    if (this._closed) return

    if (this.connected) throw new Error('Already connected')
    if (socket.closing) throw new Error('Socket is closed')

    if (typeof host === 'object') {
      opts = host
      host = null
    }

    if (!host) host = '127.0.0.1'

    const family = ip.isIP(host)
    if (!family) throw new Error(`${host} is not a valid IP address`)
    if (!(port > 0 && port < 65536)) throw new Error(`${port} is not a valid port`)

    if (!socket.bound) socket.bind(0)

    this.remoteId = remoteId
    this.remotePort = port
    this.remoteHost = host
    this.remoteFamily = family
    this.socket = socket

    if (opts.ack) binding.udx_napi_stream_set_ack(this._handle, opts.ack)

    binding.udx_napi_stream_connect(this._handle, socket._handle, remoteId, port, host, family)

    this.socket._addStream(this)

    this.emit('connect')
  }

  changeRemote(socket, remoteId, port, host) {
    if (this._remoteChanging) throw new Error('Remote already changing')

    if (!this.connected) throw new Error('Not yet connected')
    if (socket.closing) throw new Error('Socket is closed')

    if (this.socket.udx !== socket.udx) {
      throw new Error('Cannot change to a socket on another UDX instance')
    }

    if (!host) host = '127.0.0.1'

    const family = ip.isIP(host)
    if (!family) throw new Error(`${host} is not a valid IP address`)
    if (!(port > 0 && port < 65536)) throw new Error(`${port} is not a valid port`)

    if (this.socket !== socket) this._previousSocket = this.socket

    this.remoteId = remoteId
    this.remotePort = port
    this.remoteHost = host
    this.remoteFamily = family
    this.socket = socket

    this._remoteChanging = new Promise((resolve, reject) => {
      const onchanged = () => {
        this.off('close', onclose)
        resolve()
      }

      const onclose = () => {
        this.off('remote-changed', onchanged)
        reject(new Error('Stream is closed'))
      }

      this.once('remote-changed', onchanged).once('close', onclose)
    })

    binding.udx_napi_stream_change_remote(
      this._handle,
      socket._handle,
      remoteId,
      port,
      host,
      family
    )

    this.socket._addStream(this)

    return this._remoteChanging
  }

  relayTo(destination) {
    if (this._closed) return

    binding.udx_napi_stream_relay_to(this._handle, destination._handle)
  }

  async send(buffer) {
    if (!this.connected || this._closed) return false

    const id = this._allocSend()
    const req = this._sreqs[id]

    req.buffer = buffer

    const promise = new Promise((resolve) => {
      req.onflush = resolve
    })

    binding.udx_napi_stream_send(this._handle, req.handle, id, buffer)

    return promise
  }

  trySend(buffer) {
    if (!this.connected || this._closed) return

    const id = this._allocSend()
    const req = this._sreqs[id]

    req.buffer = buffer
    req.onflush = noop

    binding.udx_napi_stream_send(this._handle, req.handle, id, buffer)
  }

  async flush() {
    if ((await streamx.Writable.drained(this)) === false) return false
    if (this.destroying) return false

    const missing = this._wreqs.length - this._wfree.length
    if (missing === 0) return true

    return new Promise((resolve) => {
      this._flushes.push({ flush: this._flushing++, missing, resolve })
    })
  }

  toJSON() {
    return {
      id: this.id,
      connected: this.connected,
      destroying: this.destroying,
      destroyed: this.destroyed,
      remoteId: this.remoteId,
      remoteHost: this.remoteHost,
      remoteFamily: this.remoteFamily,
      remotePort: this.remotePort,
      mtu: this.mtu,
      rtt: this.rtt,
      cwnd: this.cwnd,
      inflight: this.inflight,
      socket: this.socket ? this.socket.toJSON() : null
    }
  }

  _read(cb) {
    cb(null)
  }

  _writeContinue(err) {
    if (this._onwrite === null) return
    const cb = this._onwrite
    this._onwrite = null
    cb(err)
  }

  _destroyContinue(err) {
    if (this._ondestroy === null) return
    const cb = this._ondestroy
    this._ondestroy = null
    cb(err)
  }

  _writev(buffers, cb) {
    if (!this.connected) {
      throw customError('Writing while not connected not currently supported', 'ERR_ASSERTION')
    }

    let drained = true

    if (buffers.length === 1) {
      const id = this._allocWrite(1)
      const req = this._wreqs[id]

      req.flush = this._flushing
      req.buffer = buffers[0]

      drained = binding.udx_napi_stream_write(this._handle, req.handle, id, req.buffer) !== 0
    } else {
      const id = this._allocWrite(nextBatchSize(buffers.length))
      const req = this._wreqs[id]

      req.flush = this._flushing
      req.buffers = buffers

      drained = binding.udx_napi_stream_writev(this._handle, req.handle, id, req.buffers) !== 0
    }

    if (drained) cb(null)
    else this._onwrite = cb
  }

  _final(cb) {
    const id = this._allocWrite(1)
    const req = this._wreqs[id]

    req.flush = this._flushes
    req.buffer = b4a.allocUnsafe(0)

    const drained =
      binding.udx_napi_stream_write_end(this._handle, req.handle, id, req.buffer) !== 0

    if (drained) cb(null)
    else this._onwrite = cb
  }

  _predestroy() {
    if (!this._closed) binding.udx_napi_stream_destroy(this._handle)
    this._closed = true
    this._writeContinue(null)
  }

  _destroy(cb) {
    if (this.connected) this._ondestroy = cb
    else cb(null)
  }

  _ondata(read) {
    this.push(this._consumeData(read))
    return this._buffer
  }

  _onend(read) {
    if (read > 0) this.push(this._consumeData(read))
    this.push(null)
  }

  _ondrain() {
    this._writeContinue(null)
  }

  _flushAck(flush) {
    for (let i = this._flushes.length - 1; i >= 0; i--) {
      const f = this._flushes[i]
      if (f.flush < flush) break
      f.missing--
    }

    while (this._flushes.length > 0 && this._flushes[0].missing === 0) {
      this._flushes.shift().resolve(true)
    }
  }

  _onack(id) {
    const req = this._wreqs[id]

    req.buffers = req.buffer = null
    this._wfree.push(id)

    if (this._flushes.length > 0) this._flushAck(req.flush)

    // gc the free list
    if (this._wfree.length >= 64 && this._wfree.length === this._wreqs.length) {
      this._wfree = []
      this._wreqs = []
    }
  }

  _onsend(id, err) {
    const req = this._sreqs[id]

    const onflush = req.onflush

    req.buffer = null
    req.onflush = null

    this._sfree.push(id)

    onflush(err >= 0)

    // gc the free list
    if (this._sfree.length >= 16 && this._sfree.length === this._sreqs.length) {
      this._sfree = []
      this._sreqs = []
    }
  }

  _onmessage(len) {
    this.emit('message', this.udx._consumeMessage(len))
    return this.udx._buffer
  }

  _onclose(err) {
    this._closed = true

    if (this.socket) {
      this.socket._removeStream(this)
      this.socket = null
    }

    if (this._previousSocket) {
      this._previousSocket._removeStream(this)
      this._previousSocket = null
    }

    // no error, we don't need to do anything
    if (!err) return this._destroyContinue(null)

    if (this._ondestroy === null) this.destroy(err)
    else this._destroyContinue(err)
  }

  _onfirewall(socket, port, host, family) {
    if (port <= 0 || port > 65535) return 1
    return this._firewall(socket, port, host, family) ? 1 : 0
  }

  _onremotechanged() {
    if (this._previousSocket) {
      this._previousSocket._removeStream(this)
      this._previousSocket = null
    }

    this._remoteChanging = null
    this.emit('remote-changed')
  }

  _consumeData(len) {
    const next = this._buffer.subarray(0, len)
    this._buffer = this._buffer.subarray(len)
    if (this._buffer.byteLength < MAX_PACKET) this._reallocData()
    return next
  }

  _reallocData() {
    this._buffer = b4a.allocUnsafe(BUFFER_SIZE)
    return this._buffer
  }

  _reallocMessage() {
    return this.udx._reallocMessage()
  }

  _allocWrite(size) {
    if (this._wfree.length === 0) {
      const handle = b4a.allocUnsafe(binding.udx_napi_stream_write_sizeof(size))
      return (
        this._wreqs.push({
          handle,
          size,
          buffers: null,
          buffer: null,
          flush: 0
        }) - 1
      )
    }

    const free = this._wfree.pop()
    if (size === 1) return free

    const next = this._wreqs[free]
    if (next.size < size) {
      next.handle = b4a.allocUnsafe(binding.udx_napi_stream_write_sizeof(size))
      next.size = size
    }

    return free
  }

  _allocSend() {
    if (this._sfree.length > 0) return this._sfree.pop()
    const handle = b4a.allocUnsafe(binding.sizeof_udx_stream_send_t)
    return this._sreqs.push({ handle, buffer: null, resolve: null, reject: null }) - 1
  }
}

function noop() {}

function toBuffer(data) {
  return typeof data === 'string' ? b4a.from(data) : data
}

function firewallAll(socket, port, host) {
  return true
}

function customError(message, code) {
  const error = new Error(message)
  error.code = code
  return error
}

function nextBatchSize(n) {
  // try to coerce the the writevs into sameish size
  if (n === 1) return 1
  // group all < 8 to the same size, low mem overhead but save some small allocs
  if (n < 8) return 8
  if (n < 16) return 16
  if (n < 32) return 32
  if (n < 64) return 64
  return n
}
const b4a = require('b4a')
const binding = require('../binding')
const ip = require('./ip')
const Socket = require('./socket')
const Stream = require('./stream')
const NetworkInterfaces = require('./network-interfaces')

const MAX_MESSAGE = 4096
const BUFFER_SIZE = 65536 + MAX_MESSAGE

module.exports = class UDX {
  constructor() {
    this._handle = b4a.alloc(binding.sizeof_udx_napi_t)
    this._watchers = new Set()
    this._view64 = new BigUint64Array(
      this._handle.buffer,
      this._handle.byteOffset,
      this._handle.byteLength >> 3
    )

    this._buffer = null
    this._reallocMessage()

    binding.udx_napi_init(this._handle, this._buffer)
  }

  static isIPv4(host) {
    return ip.isIPv4(host)
  }

  static isIPv6(host) {
    return ip.isIPv6(host)
  }

  static isIP(host) {
    return ip.isIP(host)
  }

  get bytesTransmitted() {
    return Number(this._view64[binding.offsetof_udx_t_bytes_tx >> 3])
  }

  get packetsTransmitted() {
    return Number(this._view64[binding.offsetof_udx_t_packets_tx >> 3])
  }

  get bytesReceived() {
    return Number(this._view64[binding.offsetof_udx_t_bytes_rx >> 3])
  }

  get packetsReceived() {
    return Number(this._view64[binding.offsetof_udx_t_packets_rx >> 3])
  }

  get packetsDroppedByKernel() {
    return Number(this._view64[binding.offsetof_udx_t_packets_dropped_by_kernel >> 3])
  }

  _consumeMessage(len) {
    const next = this._buffer.subarray(0, len)
    this._buffer = this._buffer.subarray(len)
    if (this._buffer.byteLength < MAX_MESSAGE) this._reallocMessage()
    return next
  }

  _reallocMessage() {
    // TODO: move reallocation to native
    this._buffer = b4a.allocUnsafe(BUFFER_SIZE)
    return this._buffer
  }

  createSocket(opts) {
    return new Socket(this, opts)
  }

  createStream(id, opts) {
    return new Stream(this, id, opts)
  }

  networkInterfaces() {
    let [watcher = null] = this._watchers
    if (watcher) return watcher.interfaces

    watcher = new NetworkInterfaces(this)
    watcher.destroy()

    return watcher.interfaces
  }

  watchNetworkInterfaces(onchange) {
    const watcher = new NetworkInterfaces(this)

    this._watchers.add(watcher)
    watcher.on('close', () => {
      this._watchers.delete(watcher)
    })

    if (onchange) watcher.on('change', onchange)

    return watcher.watch()
  }

  async lookup(host, opts = {}) {
    const { family = 0 } = opts

    const req = b4a.alloc(binding.sizeof_udx_napi_lookup_t)
    const ctx = {
      req,
      resolve: null,
      reject: null
    }

    const promise = new Promise((resolve, reject) => {
      ctx.resolve = resolve
      ctx.reject = reject
    })

    binding.udx_napi_lookup(this._handle, req, host, family, ctx, onlookup)

    return promise
  }
}

function onlookup(err, host, family) {
  if (err) this.reject(err)
  else this.resolve({ host, family })
}
{
  "name": "udx-native",
  "version": "1.20.6",
  "description": "udx is reliable, multiplexed, and congestion-controlled streams over udp",
  "main": "lib/udx.js",
  "files": [
    "lib",
    "prebuilds",
    "binding.cc",
    "binding.js",
    "CMakeLists.txt"
  ],
  "imports": {
    "events": {
      "bare": "bare-events",
      "default": "events"
    }
  },
  "addon": true,
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node --coverage test/*.js",
    "test:bare": "brittle-bare --coverage test/*.js",
    "test:all": "brittle test/*.js test/slow/*.js",
    "test:generate": "brittle -r test/all.js test/*.js",
    "bench": "brittle test/bench/*.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/udx-native.git"
  },
  "keywords": [
    "tcp",
    "udp",
    "stream",
    "reliable"
  ],
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/udx-native/issues"
  },
  "homepage": "https://github.com/holepunchto/udx-native#readme",
  "engines": {
    "bare": ">=1.17.4"
  },
  "dependencies": {
    "b4a": "^1.5.0",
    "bare-events": "^2.2.0",
    "require-addon": "^1.1.0",
    "streamx": "^2.22.0"
  },
  "devDependencies": {
    "bare-compat-napi": "^1.3.0",
    "brittle": "^3.1.0",
    "cmake-bare": "^1.1.10",
    "cmake-fetch": "^1.0.1",
    "cmake-napi": "^1.0.5",
    "is-ci": "^3.0.1",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0",
    "tiny-byte-size": "^1.1.0"
  }
}
exports.add = add
exports.has = has
exports.remove = remove
exports.swap = swap

function add (list, item) {
  if (has(list, item)) return item
  item._index = list.length
  list.push(item)
  return item
}

function has (list, item) {
  return item._index < list.length && list[item._index] === item
}

function remove (list, item) {
  if (!has(list, item)) return null

  var last = list.pop()
  if (last !== item) {
    list[item._index] = last
    last._index = item._index
  }

  return item
}

function swap (list, a, b) {
  if (!has(list, a) || !has(list, b)) return
  var tmp = a._index
  a._index = b._index
  list[a._index] = a
  b._index = tmp
  list[b._index] = b
}
{
  "name": "unordered-set",
  "version": "2.0.1",
  "description": "A couple of functions that make it easy to maintain an unordered set as an array in an efficient way",
  "main": "index.js",
  "dependencies": {},
  "devDependencies": {
    "standard": "^6.0.4",
    "tape": "^4.4.0"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/unordered-set.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/unordered-set/issues"
  },
  "homepage": "https://github.com/mafintosh/unordered-set"
}
const b4a = require('b4a')

unslab.all = all
unslab.is = is

module.exports = unslab

function unslab (buf) {
  if (buf === null || buf.buffer.byteLength === buf.byteLength) return buf
  const copy = b4a.allocUnsafeSlow(buf.byteLength)
  copy.set(buf, 0)
  return copy
}

function is (buf) {
  return buf.buffer.byteLength !== buf.byteLength
}

function all (list) {
  let size = 0
  for (let i = 0; i < list.length; i++) {
    const buf = list[i]
    size += buf === null || buf.buffer.byteLength === buf.byteLength ? 0 : buf.byteLength
  }

  const copy = b4a.allocUnsafeSlow(size)
  const result = new Array(list.length)

  let offset = 0
  for (let i = 0; i < list.length; i++) {
    let buf = list[i]

    if (buf !== null && buf.buffer.byteLength !== buf.byteLength) {
      copy.set(buf, offset)
      buf = copy.subarray(offset, offset += buf.byteLength)
    }

    result[i] = buf
  }

  return result
}
{
  "name": "unslab",
  "version": "1.3.0",
  "description": "Unslab some slab'ed buffers",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "dependencies": {
    "b4a": "^1.6.6"
  },
  "devDependencies": {
    "brittle": "^3.5.2",
    "standard": "^17.1.0"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/unslab.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/unslab/issues"
  },
  "homepage": "https://github.com/holepunchto/unslab"
}
module.exports = read

var MSB = 0x80
  , REST = 0x7F

function read(buf, offset) {
  var res    = 0
    , offset = offset || 0
    , shift  = 0
    , counter = offset
    , b
    , l = buf.length

  do {
    if (counter >= l) {
      read.bytes = 0
      throw new RangeError('Could not decode varint')
    }
    b = buf[counter++]
    res += shift < 28
      ? (b & REST) << shift
      : (b & REST) * Math.pow(2, shift)
    shift += 7
  } while (b >= MSB)

  read.bytes = counter - offset

  return res
}
module.exports = encode

var MSB = 0x80
  , REST = 0x7F
  , MSBALL = ~REST
  , INT = Math.pow(2, 31)

function encode(num, out, offset) {
  out = out || []
  offset = offset || 0
  var oldOffset = offset

  while(num >= INT) {
    out[offset++] = (num & 0xFF) | MSB
    num /= 128
  }
  while(num & MSBALL) {
    out[offset++] = (num & 0xFF) | MSB
    num >>>= 7
  }
  out[offset] = num | 0
  
  encode.bytes = offset - oldOffset + 1
  
  return out
}
module.exports = {
    encode: require('./encode.js')
  , decode: require('./decode.js')
  , encodingLength: require('./length.js')
}

var N1 = Math.pow(2,  7)
var N2 = Math.pow(2, 14)
var N3 = Math.pow(2, 21)
var N4 = Math.pow(2, 28)
var N5 = Math.pow(2, 35)
var N6 = Math.pow(2, 42)
var N7 = Math.pow(2, 49)
var N8 = Math.pow(2, 56)
var N9 = Math.pow(2, 63)

module.exports = function (value) {
  return (
    value < N1 ? 1
  : value < N2 ? 2
  : value < N3 ? 3
  : value < N4 ? 4
  : value < N5 ? 5
  : value < N6 ? 6
  : value < N7 ? 7
  : value < N8 ? 8
  : value < N9 ? 9
  :              10
  )
}
{
  "name": "varint",
  "version": "5.0.0",
  "description": "protobuf-style varint bytes - use msb to create integer values of varying sizes",
  "main": "index.js",
  "scripts": {
    "test": "node test.js"
  },
  "repository": {
    "type": "git",
    "url": "git://github.com/chrisdickinson/varint.git"
  },
  "keywords": [
    "varint",
    "protobuf",
    "encode",
    "decode"
  ],
  "author": "Chris Dickinson <chris@neversaw.us>",
  "license": "MIT",
  "devDependencies": {
    "tape": "~2.12.3"
  }
}
const { runtime, platform, arch, version } =
  typeof Bare !== 'undefined'
    ? {
        runtime: 'bare',
        platform: global.Bare.platform,
        arch: global.Bare.arch,
        version: global.Bare.version
      }
    : typeof process !== 'undefined'
      ? {
          runtime: 'node',
          platform: global.process.platform,
          arch: global.process.arch,
          version: global.process.version
        }
      : typeof Window !== 'undefined'
        ? { runtime: 'browser', platform: 'unknown', arch: 'unknown', version: 'unknown' }
        : { runtime: 'unknown', platform: 'unknown', arch: 'unknown', version: 'unknown' }

exports.runtime = runtime
exports.version = version
exports.platform = platform
exports.arch = arch
exports.isBare = runtime === 'bare'
exports.isBareKit = exports.isBare && typeof BareKit !== 'undefined'
exports.isPear = typeof Pear !== 'undefined'
exports.isNode = runtime === 'node'
exports.isBrowser = runtime === 'browser'
exports.isWindows = platform === 'win32'
exports.isLinux = platform === 'linux'
exports.isMac = platform === 'darwin'
exports.isIOS = platform === 'ios' || platform === 'ios-simulator'
exports.isAndroid = platform === 'android'
exports.isElectron = typeof process !== 'undefined' && !!global.process.versions?.electron
exports.isElectronRenderer = exports.isElectron && global.process.type === 'renderer'
exports.isElectronWorker = exports.isElectron && global.process.type === 'worker'
{
  "name": "which-runtime",
  "version": "1.4.0",
  "description": "Detect if you are in Bare or Node and which os etc",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte .",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/which-runtime.git"
  },
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/which-runtime/issues"
  },
  "homepage": "https://github.com/holepunchto/which-runtime",
  "devDependencies": {
    "brittle": "^3.0.0",
    "lunte": "^1.4.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
module.exports = class MaxCache {
  constructor ({ maxSize, maxAge, createMap, ongc }) {
    this.maxSize = maxSize
    this.maxAge = maxAge
    this.ongc = ongc || null

    this._createMap = createMap || defaultCreateMap
    this._latest = this._createMap()
    this._oldest = this._createMap()
    this._retained = this._createMap()
    this._gced = false
    this._interval = null

    if (this.maxAge > 0 && this.maxAge < Infinity) {
      const tick = Math.ceil(2 / 3 * this.maxAge)
      this._interval = setInterval(this._gcAuto.bind(this), tick)
      if (this._interval.unref) this._interval.unref()
    }
  }

  * [Symbol.iterator] () {
    for (const it of [this._latest, this._oldest, this._retained]) {
      yield * it
    }
  }

  * keys () {
    for (const it of [this._latest, this._oldest, this._retained]) {
      yield * it.keys()
    }
  }

  * values () {
    for (const it of [this._latest, this._oldest, this._retained]) {
      yield * it.values()
    }
  }

  destroy () {
    this.clear()
    clearInterval(this._interval)
    this._interval = null
  }

  clear () {
    this._gced = true
    this._latest.clear()
    this._oldest.clear()
    this._retained.clear()
  }

  set (k, v) {
    if (this._retained.has(k)) return this
    this._latest.set(k, v)
    this._oldest.delete(k) || this._retained.delete(k)
    if (this._latest.size >= this.maxSize) this._gc()
    return this
  }

  retain (k, v) {
    this._retained.set(k, v)
    this._latest.delete(k) || this._oldest.delete(k)
    return this
  }

  delete (k) {
    return this._latest.delete(k) || this._oldest.delete(k) || this._retained.delete(k)
  }

  has (k) {
    return this._latest.has(k) || this._oldest.has(k) || this._retained.has(k)
  }

  get (k) {
    if (this._latest.has(k)) {
      return this._latest.get(k)
    }

    if (this._oldest.has(k)) {
      const v = this._oldest.get(k)
      this._latest.set(k, v)
      this._oldest.delete(k)
      return v
    }

    if (this._retained.has(k)) {
      return this._retained.get(k)
    }

    return null
  }

  _gcAuto () {
    if (!this._gced) this._gc()
    this._gced = false
  }

  _gc () {
    this._gced = true
    if (this.ongc !== null && this._oldest.size > 0) this.ongc(this._oldest)
    this._oldest = this._latest
    this._latest = this._createMap()
  }
}

function defaultCreateMap () {
  return new Map()
}
{
  "name": "xache",
  "version": "1.2.1",
  "description": "Yet another auto expiring, max sizable cache",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "devDependencies": {
    "brittle": "^3.3.2",
    "standard": "^17.1.0"
  },
  "scripts": {
    "test": "standard && brittle test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/xache.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/xache/issues"
  },
  "homepage": "https://github.com/mafintosh/xache"
}
const b4a = require('b4a')

const ALPHABET = 'ybndrfg8ejkmcpqxot1uwisza345h769'
const MIN = 0x31 // 1
const MAX = 0x7a // z
const REVERSE = new Int8Array(1 + MAX - MIN)

REVERSE.fill(-1)

for (let i = 0; i < ALPHABET.length; i++) {
  const v = ALPHABET.charCodeAt(i) - MIN
  REVERSE[v] = i
}

exports.encode = encode
exports.decode = decode
exports.ALPHABET = ALPHABET

function decode (s, out) {
  let pb = 0
  let ps = 0

  const r = s.length & 7
  const q = (s.length - r) / 8

  if (!out) out = b4a.allocUnsafe(Math.ceil(s.length * 5 / 8))

  // 0 5 2 7 4 1 6 3 (+5 mod 8)
  for (let i = 0; i < q; i++) {
    const a = quintet(s, ps++)
    const b = quintet(s, ps++)
    const c = quintet(s, ps++)
    const d = quintet(s, ps++)
    const e = quintet(s, ps++)
    const f = quintet(s, ps++)
    const g = quintet(s, ps++)
    const h = quintet(s, ps++)

    out[pb++] = (a << 3) | (b >>> 2)
    out[pb++] = ((b & 0b11) << 6) | (c << 1) | (d >>> 4)
    out[pb++] = ((d & 0b1111) << 4) | (e >>> 1)
    out[pb++] = ((e & 0b1) << 7) | (f << 2) | (g >>> 3)
    out[pb++] = ((g & 0b111) << 5) | h
  }

  if (r === 0) return out.subarray(0, pb)

  const a = quintet(s, ps++)
  const b = quintet(s, ps++)

  out[pb++] = (a << 3) | (b >>> 2)

  if (r <= 2) return out.subarray(0, pb)

  const c = quintet(s, ps++)
  const d = quintet(s, ps++)

  out[pb++] = ((b & 0b11) << 6) | (c << 1) | (d >>> 4)

  if (r <= 4) return out.subarray(0, pb)

  const e = quintet(s, ps++)

  out[pb++] = ((d & 0b1111) << 4) | (e >>> 1)

  if (r <= 5) return out.subarray(0, pb)

  const f = quintet(s, ps++)
  const g = quintet(s, ps++)

  out[pb++] = ((e & 0b1) << 7) | (f << 2) | (g >>> 3)

  if (r <= 7) return out.subarray(0, pb)

  const h = quintet(s, ps++)

  out[pb++] = ((g & 0b111) << 5) | h

  return out.subarray(0, pb)
}

function encode (buf) {
  if (typeof buf === 'string') buf = b4a.from(buf)

  const max = buf.byteLength * 8

  let s = ''

  for (let p = 0; p < max; p += 5) {
    const i = p >>> 3
    const j = p & 7

    if (j <= 3) {
      s += ALPHABET[(buf[i] >>> (3 - j)) & 0b11111]
      continue
    }

    const of = j - 3
    const h = (buf[i] << of) & 0b11111
    const l = (i >= buf.byteLength ? 0 : buf[i + 1]) >>> (8 - of)

    s += ALPHABET[h | l]
  }

  return s
}

function quintet (s, i) {
  if (i > s.length) {
    return 0
  }

  const v = s.charCodeAt(i)

  if (v < MIN || v > MAX) {
    throw Error('Invalid character in base32 input: "' + s[i] + '" at position ' + i)
  }

  const bits = REVERSE[v - MIN]

  if (bits === -1) {
    throw Error('Invalid character in base32 input: "' + s[i] + '" at position ' + i)
  }

  return bits
}
{
  "name": "z32",
  "version": "1.1.0",
  "description": "Encode & decode z-base32",
  "main": "index.js",
  "dependencies": {
    "b4a": "^1.5.3"
  },
  "devDependencies": {
    "base-x": "^4.0.0",
    "base32": "0.0.7",
    "brittle": "^3.1.3",
    "nanobench": "^3.0.0",
    "rfc4648": "^1.5.2",
    "standard": "^17.0.0"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/z32.git"
  },
  "scripts": {
    "test": "standard && brittle test.js",
    "bench": "node benchmark.js"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/z32/issues"
  },
  "homepage": "https://github.com/mafintosh/z32"
}
{
  "name": "pgh",
  "version": "0.1.156",
  "description": "pgh \u2014 P2P content-addressed package manager and app launcher",
  "type": "module",
  "main": "index.js",
  "bin": {
    "pgh": "./bin/pgh"
  },
  "exports": {
    ".": "./index.js",
    "./store": "./lib/store.js",
    "./tree-install": "./lib/tree-install.js",
    "./publish": "./lib/publish.js",
    "./conflict": "./lib/conflict.js",
    "./schema": "./lib/schema.js",
    "./published-index": "./lib/published-index.js",
    "./bootstrap": "./lib/bootstrap.js",
    "./bootstrap-artifacts": "./lib/bootstrap-artifacts.js",
    "./network-fetcher": "./lib/network-fetcher.js",
    "./runtime-factory": "./lib/runtime-factory.js",
    "./resolve-release": "./lib/resolve-release.js",
    "./release-registry": "./lib/release-registry.js",
    "./name-registry": "./lib/name-registry.js",
    "./subscriptions": "./lib/subscriptions.js",
    "./app-state": "./lib/app-state.js",
    "./identity": "./lib/identity.js",
    "./output": "./lib/output.js",
    "./commands/init": "./lib/commands/init.js",
    "./commands/app": "./lib/commands/app.js",
    "./commands/store": "./lib/commands/store.js",
    "./commands/publish": "./lib/commands/publish.js",
    "./commands/releases": "./lib/commands/releases.js",
    "./commands/seed": "./lib/commands/seed.js"
  },
  "scripts": {
    "test": "brittle-bare test/*.test.js",
    "test:bare": "bare ./node_modules/.bin/brittle test/*.test.js"
  },
  "engines": {
    "node": ">=18",
    "bare": ">=1.0"
  },
  "overrides": {
    "udx-native": "^1.20.3",
    "bare-runtime": "1.28.7"
  },
  "imports": {
    "#node:fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "#node:fs/promises": {
      "bare": "bare-fs/promises",
      "default": "fs/promises"
    },
    "#node:path": {
      "bare": "bare-path",
      "default": "path"
    },
    "#node:os": {
      "bare": "bare-os",
      "default": "os"
    },
    "#node:url": {
      "bare": "bare-url",
      "default": "url"
    },
    "#node:events": {
      "bare": "bare-events",
      "default": "events"
    },
    "#node:stream": {
      "bare": "bare-stream",
      "default": "stream"
    },
    "#node:stream/promises": {
      "bare": "bare-stream/promises",
      "default": "stream/promises"
    },
    "#node:child_process": {
      "bare": "bare-subprocess",
      "default": "child_process"
    },
    "#node:net": {
      "bare": "bare-net",
      "default": "net"
    },
    "#node:http": {
      "bare": "bare-http1",
      "default": "http"
    },
    "#node:https": {
      "bare": "bare-https",
      "default": "https"
    },
    "#node:crypto": {
      "bare": "bare-crypto",
      "default": "crypto"
    },
    "#node:process": {
      "bare": "bare-process",
      "default": "process"
    }
  },
  "pgh": {
    "bin": "pgh",
    "entrypoint": "bin/pgh",
    "upgrade": "pgh://1dd36bdfa9cb7f7d84adbd07f017e7200f7f90a3a546cd0761fac2a1f8a13e86/pgh",
    "type": "terminal",
    "runtime": "bare",
    "bootstrap": true
  },
  "license": "AGPL-3.0",
  "dependencies": {
    "autobase": "^7.0.0",
    "b4a": "^1.6.0",
    "bare-crypto": "^1.0.0",
    "bare-events": "^2.0.0",
    "bare-fs": "^4.0.0",
    "bare-http1": "^4.0.0",
    "bare-https": "^2.0.0",
    "bare-net": "^1.0.0",
    "bare-os": "^3.0.0",
    "bare-path": "^3.0.0",
    "bare-process": "^4.0.0",
    "bare-runtime": "1.28.7",
    "bare-stream": "^2.0.0",
    "bare-subprocess": "^6.0.0",
    "bare-url": "^2.0.0",
    "blind-pairing": "^2.3.1",
    "compact-encoding": "^3.2.0",
    "corestore": "^7.0.0",
    "hyper-deploy": "file:../hyper-deploy",
    "hyper-overlay": "file:../hyper-overlay",
    "hyper-svc": "file:../hyper-svc",
    "hyperbee": "^2.27.3",
    "hypercore": "^11.0.0",
    "hypercore-crypto": "^3.0.0",
    "hyperident": "file:../repos/hyperident",
    "hyperswarm": "^4.17.0",
    "keet-identity-key": "^3.1.0",
    "pgh-runtime": "file:../pgh-runtime",
    "protomux": "^3.0.0",
    "sodium-native": "^5.0.0"
  },
  "devDependencies": {
    "@hyperswarm/testnet": "^3.0.0",
    "brittle": "^3.0.0"
  }
}
module.exports = require.addon.bind(require)
{
  "name": "require-addon",
  "version": "1.2.0",
  "description": "Import native addons across JavaScript runtimes",
  "exports": {
    "./package": "./package.json",
    ".": {
      "bare": "./lib/bare.js",
      "node": "./lib/node.js",
      "default": "./lib/default.js"
    }
  },
  "imports": {
    "fs": {
      "bare": "bare-fs",
      "default": "fs"
    },
    "path": {
      "bare": "bare-path",
      "default": "path"
    },
    "url": {
      "bare": "bare-url",
      "default": "url"
    }
  },
  "files": [
    "lib"
  ],
  "scripts": {
    "test": "npm run lint && npm run test:bare && npm run test:node",
    "test:bare": "bare test.js",
    "test:node": "node test.js",
    "lint": "prettier --check .",
    "format": "prettier --write ."
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/require-addon.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/require-addon/issues"
  },
  "homepage": "https://github.com/holepunchto/require-addon#readme",
  "engines": {
    "bare": ">=1.10.0"
  },
  "dependencies": {
    "bare-addon-resolve": "^1.3.0"
  },
  "devDependencies": {
    "bare-bundle": "^1.8.1",
    "bare-bundle-evaluate": "^1.1.0",
    "bare-fs": "^4.0.0",
    "bare-path": "^3.0.0",
    "bare-url": "^2.1.0",
    "brittle": "^3.7.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
require.addon = require('require-addon')
module.exports = require.addon('.', __filename)
const assert = require('assert')
const binding = require('./binding')
const { isNode } = require('which-runtime')

const OPTIONAL = Buffer.from(new ArrayBuffer(0))

module.exports = exports = { ...binding }

// memory

exports.sodium_memzero = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  binding.sodium_memzero(buf)
}

exports.sodium_mlock = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  const res = binding.sodium_mlock(buf)

  if (res !== 0) throw new Error('memory lock failed')
}

exports.sodium_munlock = function (buf) {
  assert(ArrayBuffer.isView(buf), 'buf must be a typed array')

  const res = binding.sodium_munlock(buf)

  if (res !== 0) throw new Error('memory unlock failed')
}

exports.sodium_malloc = function (size) {
  assert(size >= 0, 'invalid size')

  const buf = Buffer.from(binding.sodium_malloc(size))
  buf.secure = true
  return buf
}

exports.sodium_free = function (buf) {
  if (!buf || !buf.secure) return

  binding.sodium_free(buf.buffer)
}

exports.sodium_mprotect_noaccess = function (buf) {
  const res = binding.sodium_mprotect_noaccess(buf.buffer)

  if (res !== 0) throw new Error('failed to lock buffer')
}

exports.sodium_mprotect_readonly = function (buf) {
  const res = binding.sodium_mprotect_readonly(buf.buffer)

  if (res !== 0) throw new Error('failed to unlock buffer')
}

exports.sodium_mprotect_readwrite = function (buf) {
  const res = binding.sodium_mprotect_readwrite(buf.buffer)

  if (res !== 0) throw new Error('failed to unlock buffer')
}

// crypto_randombytes

exports.randombytes_buf = function (buffer) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')

  binding.randombytes_buf(buffer.buffer, buffer.byteOffset, buffer.byteLength)
}

exports.randombytes_buf_deterministic = function (buffer, seed) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    seed.byteLength === binding.randombytes_SEEDBYTES,
    "seed must be 'randombytes_SEEDBYTES' bytes"
  )

  binding.randombytes_buf_deterministic(
    buffer.buffer,
    buffer.byteOffset,
    buffer.byteLength,

    seed.buffer,
    seed.byteOffset,
    seed.byteLength
  )
}

// sodium_helpers

exports.sodium_memcmp = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  return binding.sodium_memcmp(a, b)
}

exports.sodium_add = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  binding.sodium_add(a, b)
}

exports.sodium_sub = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  binding.sodium_sub(a, b)
}

exports.sodium_compare = function (a, b) {
  assert(ArrayBuffer.isView(a), 'a must be a typed array')
  assert(ArrayBuffer.isView(b), 'b must be a typed array')
  assert(a.byteLength === b.byteLength, 'buffers must be of same length')

  return binding.sodium_compare(a, b)
}

exports.sodium_is_zero = function (buffer, length) {
  if (length === undefined) length = buffer.byteLength

  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(length >= 0 && length <= buffer.byteLength, 'invalid length')

  return binding.sodium_is_zero(buffer, length)
}

exports.sodium_pad = function (buffer, unpaddedBuflen, blockSize) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(unpaddedBuflen <= buffer.byteLength, 'unpadded length cannot exceed buffer length')
  assert(blockSize <= buffer.byteLength, 'block size cannot exceed buffer length')
  assert(blockSize >= 1, 'block size must be at least 1 byte')
  assert(
    buffer.byteLength >= unpaddedBuflen + (blockSize - (unpaddedBuflen % blockSize)),
    'buf not long enough'
  )

  return binding.sodium_pad(buffer, unpaddedBuflen, blockSize)
}

exports.sodium_unpad = function (buffer, paddedBuflen, blockSize) {
  assert(ArrayBuffer.isView(buffer), 'buffer must be a typed array')
  assert(paddedBuflen <= buffer.byteLength, 'unpadded length cannot exceed buffer length')
  assert(blockSize <= buffer.byteLength, 'block size cannot exceed buffer length')
  assert(blockSize >= 1, 'block size must be at least 1 byte')

  return binding.sodium_unpad(buffer, paddedBuflen, blockSize)
}

// crypto_sign

exports.crypto_sign_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )
  assert(
    seed.byteLength === binding.crypto_sign_SEEDBYTES,
    "seed must be 'crypto_sign_SEEDBYTES' bytes"
  )

  const res = binding.crypto_sign_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign = function (sm, m, sk) {
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sm.byteLength === binding.crypto_sign_BYTES + m.byteLength,
    "sm must be 'm.byteLength + crypto_sign_BYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign(sm, m, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_open = function (m, sm, pk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sm.byteLength >= binding.crypto_sign_BYTES,
    "sm must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    m.byteLength === sm.byteLength - binding.crypto_sign_BYTES,
    "m must be 'sm.byteLength - crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_open(m, sm, pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_open = function (m, sm, pk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sm), 'sm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sm.byteLength >= binding.crypto_sign_BYTES,
    "sm must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    m.byteLength === sm.byteLength - binding.crypto_sign_BYTES,
    "m must be 'sm.byteLength - crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  return binding.crypto_sign_open(m, sm, pk)
}

exports.crypto_sign_detached = function (sig, m, sk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(sig.byteLength === binding.crypto_sign_BYTES, "sig must be 'crypto_sign_BYTES' bytes")
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_detached(sig, m, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_verify_detached = function (sig, m, pk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    sig.byteLength >= binding.crypto_sign_BYTES,
    "sig must be at least 'crypto_sign_BYTES' bytes"
  )
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  return binding.crypto_sign_verify_detached(
    sig.buffer,
    sig.byteOffset,
    sig.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    pk.buffer,
    pk.byteOffset,
    pk.byteLength
  )
}

exports.crypto_sign_ed25519_sk_to_pk = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_sk_to_pk(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_ed25519_pk_to_curve25519 = function (x25519pk, ed25519pk) {
  assert(ArrayBuffer.isView(x25519pk), 'x25519pk must be a typed array')
  assert(ArrayBuffer.isView(ed25519pk), 'ed25519pk must be a typed array')
  assert(
    x25519pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "x25519pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    ed25519pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "ed25519pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_pk_to_curve25519(x25519pk, ed25519pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_sign_ed25519_sk_to_curve25519 = function (x25519sk, ed25519sk) {
  assert(ArrayBuffer.isView(x25519sk), 'x25519sk must be a typed array')
  assert(ArrayBuffer.isView(ed25519sk), 'ed25519sk must be a typed array')
  assert(
    x25519sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "x25519sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const edLen = ed25519sk.byteLength

  assert(
    edLen === binding.crypto_sign_SECRETKEYBYTES || edLen === binding.crypto_box_SECRETKEYBYTES,
    "ed25519sk must be 'crypto_sign_SECRETKEYBYTES' or 'crypto_sign_SECRETKEYBYTES - crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_sign_ed25519_sk_to_curve25519(x25519sk, ed25519sk)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_box

exports.crypto_box_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    seed.byteLength === binding.crypto_box_SEEDBYTES,
    "seed must be 'crypto_box_SEEDBYTES' bytes"
  )

  const res = binding.crypto_box_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_easy = function (c, m, n, pk, sk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength === m.byteLength + exports.crypto_box_MACBYTES,
    "c must be 'm.byteLength + crypto_box_MACBYTES' bytes"
  )
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_easy(c, m, n, pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_detached = function (c, mac, m, n, pk, sk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(mac.byteLength === exports.crypto_box_MACBYTES, "mac must be 'crypto_box_MACBYTES' bytes")
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_box_detached(c, mac, m, n, pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_open_easy = function (m, c, n, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength >= exports.crypto_box_MACBYTES,
    "c must be at least 'crypto_box_MACBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - exports.crypto_box_MACBYTES,
    "m must be 'c.byteLength - crypto_box_MACBYTES' bytes"
  )
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_open_easy(m, c, n, pk, sk)
}

exports.crypto_box_open_detached = function (m, c, mac, n, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(mac.byteLength === exports.crypto_box_MACBYTES, "mac must be 'crypto_box_MACBYTES' bytes")
  assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes")
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_open_detached(m, c, mac, n, pk, sk)
}

exports.crypto_box_seal = function (c, m, pk) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    c.byteLength === m.byteLength + exports.crypto_box_SEALBYTES,
    "c must be 'm.byteLength + crypto_box_SEALBYTES' bytes"
  )
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_box_seal(c, m, pk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_box_seal_open = function (m, c, pk, sk) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    c.byteLength >= exports.crypto_box_SEALBYTES,
    "c must be at least 'crypto_box_SEALBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - exports.crypto_box_SEALBYTES,
    "m must be 'c.byteLength - crypto_box_SEALBYTES' bytes"
  )
  assert(
    pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
    "pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
    "sk must be 'crypto_box_SECRETKEYBYTES' bytes"
  )

  return binding.crypto_box_seal_open(
    m.buffer,
    m.byteOffset,
    m.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    pk.buffer,
    pk.byteOffset,
    pk.byteLength,

    sk.buffer,
    sk.byteOffset,
    sk.byteLength
  )
}

// crypto_secretbox

exports.crypto_secretbox_easy = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_secretbox_MACBYTES,
    "c must be 'm.byteLength + crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretbox_easy(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretbox_open_easy = function (m, c, n, k) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    c.byteLength >= binding.crypto_secretbox_MACBYTES,
    "c must be at least 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    m.byteLength === c.byteLength - binding.crypto_secretbox_MACBYTES,
    "m must be 'c.byteLength - crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  return binding.crypto_secretbox_open_easy(m, c, n, k)
}

exports.crypto_secretbox_detached = function (c, mac, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    mac.byteLength === binding.crypto_secretbox_MACBYTES,
    "mac must be 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretbox_detached(c, mac, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretbox_open_detached = function (m, c, mac, n, k) {
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(
    mac.byteLength === binding.crypto_secretbox_MACBYTES,
    "mac must be 'crypto_secretbox_MACBYTES' bytes"
  )
  assert(
    n.byteLength === binding.crypto_secretbox_NONCEBYTES,
    "n must be 'crypto_secretbox_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretbox_KEYBYTES,
    "k must be 'crypto_secretbox_KEYBYTES' bytes"
  )

  return binding.crypto_secretbox_open_detached(m, c, mac, n, k)
}

// crypto_generichash

exports.crypto_generichash = function (output, input, key) {
  if (!key) key = OPTIONAL

  assert(ArrayBuffer.isView(output), 'output must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    output.byteLength >= binding.crypto_generichash_BYTES_MIN &&
      output.byteLength <= binding.crypto_generichash_BYTES_MAX,
    'output must be between crypto_generichash_BYTES_MIN and crypto_generichash_BYTES_MAX bytes'
  )

  if (key !== OPTIONAL) {
    assert(ArrayBuffer.isView(key), 'key must be a typed array')
    assert(
      key.byteLength >= binding.crypto_generichash_KEYBYTES_MIN &&
        key.byteLength <= binding.crypto_generichash_KEYBYTES_MAX,
      'key must be between crypto_generichash_KEYBYTES_MIN and crypto_generichash_KEYBYTES_MAX bytes'
    )
  }

  const res = binding.crypto_generichash(
    output.buffer,
    output.byteOffset,
    output.byteLength,

    input.buffer,
    input.byteOffset,
    input.byteLength,

    key.buffer,
    key.byteOffset,
    key.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_batch = function (output, batch, key) {
  assert(ArrayBuffer.isView(output), 'output must be a typed array')

  if (isNode || batch.length < 4) {
    const res = binding.crypto_generichash_batch(output, batch, !!key, key || OPTIONAL)
    if (res !== 0) throw new Error('status: ' + res)
  } else {
    const state = Buffer.alloc(binding.crypto_generichash_STATEBYTES)

    exports.crypto_generichash_init(state, key, output.byteLength)

    for (const buf of batch) {
      exports.crypto_generichash_update(state, buf)
    }

    exports.crypto_generichash_final(state, output)
  }
}

exports.crypto_generichash_keygen = function (key) {
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(
    key.byteLength === binding.crypto_generichash_KEYBYTES,
    "key must be 'crypto_generichash_KEYBYTES' bytes"
  )

  const res = binding.crypto_generichash_keygen(key.buffer, key.byteOffset, key.byteLength)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_init = function (state, key, outputLength) {
  if (!key) key = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_init(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    key.buffer,
    key.byteOffset,
    key.byteLength,

    outputLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_update(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    input.buffer,
    input.byteOffset,
    input.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_generichash_final = function (state, output) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(output), 'output must be a typed array')
  assert(
    state.byteLength === binding.crypto_generichash_STATEBYTES,
    "state must be 'crypto_generichash_STATEBYTES' bytes"
  )

  const res = binding.crypto_generichash_final(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    output.buffer,
    output.byteOffset,
    output.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

// secretstream

exports.crypto_secretstream_xchacha20poly1305_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  binding.crypto_secretstream_xchacha20poly1305_keygen(k.buffer, k.byteOffset, k.byteLength)
}

exports.crypto_secretstream_xchacha20poly1305_init_push = function (state, header, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(header), 'header must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    header.byteLength === binding.crypto_secretstream_xchacha20poly1305_HEADERBYTES,
    "header must be 'crypto_secretstream_xchacha20poly1305_HEADERBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_init_push(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    header.buffer,
    header.byteOffset,
    header.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretstream_xchacha20poly1305_init_pull = function (state, header, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(header), 'header must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    header.byteLength === binding.crypto_secretstream_xchacha20poly1305_HEADERBYTES,
    "header must be 'crypto_secretstream_xchacha20poly1305_HEADERBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
    "k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_init_pull(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    header.buffer,
    header.byteOffset,
    header.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_secretstream_xchacha20poly1305_push = function (state, c, m, ad, tag) {
  if (!ad) ad = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(
    c.byteLength === m.byteLength + binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "c must be 'm.byteLength + crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_push(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    ad.buffer,
    ad.byteOffset,
    ad.byteLength,

    tag
  )

  if (res < 0) throw new Error('push failed')

  return res
}

exports.crypto_secretstream_xchacha20poly1305_pull = function (state, m, tag, c, ad) {
  if (!ad) ad = OPTIONAL

  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(tag), 'tag must be a typed array')
  assert(tag.byteLength === 1, 'tag must be 1 byte')

  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    c.byteLength >= binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "c must be at least 'crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_secretstream_xchacha20poly1305_ABYTES,
    "m must be 'c.byteLength - crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
  )

  const res = binding.crypto_secretstream_xchacha20poly1305_pull(
    state.buffer,
    state.byteOffset,
    state.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    tag.buffer,
    tag.byteOffset,
    tag.byteLength,

    c.buffer,
    c.byteOffset,
    c.byteLength,

    ad.buffer,
    ad.byteOffset,
    ad.byteLength
  )

  if (res < 0) throw new Error('pull failed')

  return res
}

exports.crypto_secretstream_xchacha20poly1305_rekey = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
    "state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
  )

  binding.crypto_secretstream_xchacha20poly1305_rekey(
    state.buffer,
    state.byteOffset,
    state.byteLength
  )
}

// crypto_stream

exports.crypto_stream = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xor(
    c.buffer,
    c.byteOffset,
    c.byteLength,

    m.buffer,
    m.byteOffset,
    m.byteLength,

    n.buffer,
    n.byteOffset,
    n.byteLength,

    k.buffer,
    k.byteOffset,
    k.byteLength
  )

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_chacha20_ietf_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_chacha20_ietf_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_xchacha20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_xchacha20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20 = function (c, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20(c, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20_xor = function (c, m, n, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20_xor(c, m, n, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_stream_salsa20_xor_ic = function (c, m, n, ic, k) {
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  const res = binding.crypto_stream_salsa20_xor_ic(c, m, n, ic, k)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_auth

exports.crypto_auth = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(out.byteLength === binding.crypto_auth_BYTES, "out must be 'crypto_auth_BYTES' bytes")
  assert(k.byteLength === binding.crypto_auth_KEYBYTES, "k must be 'crypto_auth_KEYBYTES' bytes")

  const res = binding.crypto_auth(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_auth_verify = function (h, input, k) {
  assert(ArrayBuffer.isView(h), 'h must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(h.byteLength === binding.crypto_auth_BYTES, "h must be 'crypto_auth_BYTES' bytes")
  assert(k.byteLength === binding.crypto_auth_KEYBYTES, "k must be 'crypto_auth_KEYBYTES' bytes")

  return binding.crypto_auth_verify(h, input, k)
}

// crypto_onetimeauth

exports.crypto_onetimeauth = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    out.byteLength === binding.crypto_onetimeauth_BYTES,
    "out must be 'crypto_onetimeauth_BYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_init = function (state, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_init(state, k)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
    "state must be 'crypto_onetimeauth_STATEBYTES' bytes"
  )
  assert(
    out.byteLength === binding.crypto_onetimeauth_BYTES,
    "out must be 'crypto_onetimeauth_BYTES' bytes"
  )

  const res = binding.crypto_onetimeauth_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_onetimeauth_verify = function (h, input, k) {
  assert(ArrayBuffer.isView(h), 'h must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    h.byteLength === binding.crypto_onetimeauth_BYTES,
    "h must be 'crypto_onetimeauth_BYTES' bytes"
  )
  assert(
    k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
    "k must be 'crypto_onetimeauth_KEYBYTES' bytes"
  )

  return binding.crypto_onetimeauth_verify(h, input, k)
}

// crypto_pwhash

exports.crypto_pwhash = function (out, passwd, salt, opslimit, memlimit, alg) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_BYTES_MIN,
    "out must be at least 'crypto_pwhash_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_BYTES_MAX,
    "out must be at most 'crypto_pwhash_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_SALTBYTES,
    "salt must be 'crypto_pwhash_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )
  assert(alg >= 1 && alg <= 2, 'alg must be either Argon2i 1.3 or Argon2id 1.3')

  const res = binding.crypto_pwhash(out, passwd, salt, opslimit, memlimit, alg)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_async = function (
  out,
  passwd,
  salt,
  opslimit,
  memlimit,
  alg,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_BYTES_MIN,
    "out must be at least 'crypto_pwhash_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_BYTES_MAX,
    "out must be at most 'crypto_pwhash_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_SALTBYTES,
    "salt must be 'crypto_pwhash_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )
  assert(alg >= 1 && alg <= 2, 'alg must be either Argon2i 1.3 or Argon2id 1.3')

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    opslimit,
    memlimit,
    alg,

    done
  )

  return promise
}

exports.crypto_pwhash_str = function (out, passwd, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_STRBYTES,
    "out must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(typeof opslimit === 'number', 'opslimit must be a number')
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(typeof memlimit === 'number', 'memlimit must be a number')
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_str(out, passwd, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_str_async = function (out, passwd, opslimit, memlimit, callback = undefined) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_STRBYTES,
    "out must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(typeof opslimit === 'number', 'opslimit must be a number')
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(typeof memlimit === 'number', 'memlimit must be a number')
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_str_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_str_verify = function (str, passwd) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )

  return binding.crypto_pwhash_str_verify(str, passwd)
}

exports.crypto_pwhash_str_verify_async = function (str, passwd, callback = undefined) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  const [done, promise] = checkStatus(callback, true)

  binding.crypto_pwhash_str_verify_async(
    str.buffer,
    str.byteOffset,
    str.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    done
  )

  return promise
}

exports.crypto_pwhash_str_needs_rehash = function (str, opslimit, memlimit) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_STRBYTES,
    "str must be 'crypto_pwhash_STRBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
  )

  return binding.crypto_pwhash_str_needs_rehash(str, opslimit, memlimit)
}

exports.crypto_pwhash_scryptsalsa208sha256 = function (out, passwd, salt, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MIN,
    "out must be at least 'crypto_pwhash_scryptsalsa208sha256_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MAX,
    "out must be at most 'crypto_pwhash_scryptsalsa208sha256_BYTES_MAX' bytes"
  )
  assert(
    salt.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_SALTBYTES,
    "salt must be 'crypto_pwhash_scryptsalsa208sha256_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_scryptsalsa208sha256(out, passwd, salt, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_scryptsalsa208sha256_async = function (
  out,
  passwd,
  salt,
  opslimit,
  memlimit,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(
    out.byteLength >= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MIN,
    "out must be at least 'crypto_pwhash_scryptsalsa208sha256_BYTES_MIN' bytes"
  )
  assert(
    out.byteLength <= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MAX,
    "out must be at most 'crypto_pwhash_scryptsalsa208sha256_BYTES_MAX' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    salt.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_SALTBYTES,
    "salt must be 'crypto_pwhash_scryptsalsa208sha256_SALTBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_scryptsalsa208sha256_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str_async = function (
  out,
  passwd,
  opslimit,
  memlimit,
  callback = undefined
) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "out must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const [done, promise] = checkStatus(callback)

  binding.crypto_pwhash_scryptsalsa208sha256_str_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    opslimit,
    memlimit,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str = function (out, passwd, opslimit, memlimit) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    out.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "out must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  const res = binding.crypto_pwhash_scryptsalsa208sha256_str(out, passwd, opslimit, memlimit)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_pwhash_scryptsalsa208sha256_str_verify_async = function (
  str,
  passwd,
  callback = undefined
) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  const [done, promise] = checkStatus(callback, true)

  binding.crypto_pwhash_scryptsalsa208sha256_str_verify_async(
    str.buffer,
    str.byteOffset,
    str.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    done
  )

  return promise
}

exports.crypto_pwhash_scryptsalsa208sha256_str_verify = function (str, passwd) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(passwd.byteLength > 0, 'passwd must not be empty')

  return binding.crypto_pwhash_scryptsalsa208sha256_str_verify(str, passwd)
}

exports.crypto_pwhash_scryptsalsa208sha256_str_needs_rehash = function (str, opslimit, memlimit) {
  assert(ArrayBuffer.isView(str), 'str must be a typed array')
  assert(
    str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
    "str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
  )
  assert(
    opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
    "opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
  )
  assert(
    opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
    "opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
  )
  assert(
    memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
    "memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
  )
  assert(
    memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
    "memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
  )

  return binding.crypto_pwhash_scryptsalsa208sha256_str_needs_rehash(str, opslimit, memlimit)
}

// crypto_kx

exports.crypto_kx_keypair = function (pk, sk) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "pk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "sk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_keypair(pk, sk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_seed_keypair = function (pk, sk, seed) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(ArrayBuffer.isView(seed), 'seed must be a typed array')
  assert(
    pk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "pk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    sk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "sk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    seed.byteLength === binding.crypto_kx_SEEDBYTES,
    "seed must be 'crypto_kx_SEEDBYTES' bytes"
  )

  const res = binding.crypto_kx_seed_keypair(pk, sk, seed)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_client_session_keys = function (rx, tx, clientPk, clientSk, serverPk) {
  if (!rx) rx = undefined
  if (!tx) tx = undefined

  assert(rx || tx, 'at least one session key must be specified')

  if (rx) {
    assert(ArrayBuffer.isView(rx), 'rx must be a typed array')
    assert(
      rx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "rx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  if (tx) {
    assert(ArrayBuffer.isView(tx), 'tx must be a typed array')
    assert(
      tx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "tx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  assert(ArrayBuffer.isView(clientPk), 'clientPk must be a typed array')
  assert(ArrayBuffer.isView(clientSk), 'clientSk must be a typed array')
  assert(ArrayBuffer.isView(serverPk), 'serverPk must be a typed array')
  assert(
    clientPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "clientPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    clientSk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "clientSk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    serverPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "serverPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_client_session_keys(rx, tx, clientPk, clientSk, serverPk)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_kx_server_session_keys = function (rx, tx, serverPk, serverSk, clientPk) {
  if (!rx) rx = undefined
  if (!tx) tx = undefined

  assert(rx || tx, 'at least one session key must be specified')

  if (rx) {
    assert(ArrayBuffer.isView(rx), 'rx must be a typed array')
    assert(
      rx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "rx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  if (tx) {
    assert(ArrayBuffer.isView(tx), 'tx must be a typed array')
    assert(
      tx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
      "tx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
    )
  }

  assert(ArrayBuffer.isView(serverPk), 'serverPk must be a typed array')
  assert(ArrayBuffer.isView(serverSk), 'serverSk must be a typed array')
  assert(ArrayBuffer.isView(clientPk), 'clientPk must be a typed array')
  assert(
    serverPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "serverPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )
  assert(
    serverSk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
    "serverSk must be 'crypto_kx_SECRETKEYBYTES' bytes"
  )
  assert(
    clientPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
    "clientPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
  )

  const res = binding.crypto_kx_server_session_keys(rx, tx, serverPk, serverSk, clientPk)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_scalarmult

exports.crypto_scalarmult_base = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_BYTES,
    "q must be 'crypto_scalarmult_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_SCALARBYTES,
    "n must be 'crypto_scalarmult_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_base(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_BYTES,
    "q must be 'crypto_scalarmult_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_SCALARBYTES,
    "n must be 'crypto_scalarmult_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_BYTES,
    "p must be 'crypto_scalarmult_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_base = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_base(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519 = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "p must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_is_valid_point = function (p) {
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )

  return binding.crypto_core_ed25519_is_valid_point(p)
}

exports.crypto_core_ed25519_from_uniform = function (p, r) {
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_UNIFORMBYTES,
    "r must be 'crypto_core_ed25519_UNIFORMBYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_from_uniform(p, r)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_base_noclamp = function (q, n) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_base_noclamp(q, n)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_scalarmult_ed25519_noclamp = function (q, n, p) {
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
    "n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
    "p must be 'crypto_scalarmult_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_scalarmult_ed25519_noclamp(q, n, p)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_core

exports.crypto_core_ed25519_add = function (r, p, q) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_BYTES,
    "r must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_core_ed25519_BYTES,
    "q must be 'crypto_core_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_add(r, p, q)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_sub = function (r, p, q) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_BYTES,
    "r must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_core_ed25519_BYTES,
    "p must be 'crypto_core_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(q), 'q must be a typed array')
  assert(
    q.byteLength === binding.crypto_core_ed25519_BYTES,
    "q must be 'crypto_core_ed25519_BYTES' bytes"
  )

  const res = binding.crypto_core_ed25519_sub(r, p, q)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_core_ed25519_scalar_random = function (r) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "r must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_random(r)
}

exports.crypto_core_ed25519_scalar_reduce = function (r, s) {
  assert(ArrayBuffer.isView(r), 'r must be a typed array')
  assert(
    r.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "r must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_NONREDUCEDSCALARBYTES,
    "s must be 'crypto_core_ed25519_NONREDUCEDSCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_reduce(r, s)
}

exports.crypto_core_ed25519_scalar_invert = function (recip, s) {
  assert(ArrayBuffer.isView(recip), 'recip must be a typed array')
  assert(
    recip.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "recip must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_invert(recip, s)
}

exports.crypto_core_ed25519_scalar_negate = function (neg, s) {
  assert(ArrayBuffer.isView(neg), 'neg must be a typed array')
  assert(
    neg.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "neg must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_negate(neg, s)
}

exports.crypto_core_ed25519_scalar_complement = function (comp, s) {
  assert(ArrayBuffer.isView(comp), 'comp must be a typed array')
  assert(
    comp.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "comp must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(s), 's must be a typed array')
  assert(
    s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_complement(comp, s)
}

exports.crypto_core_ed25519_scalar_add = function (z, x, y) {
  assert(ArrayBuffer.isView(z), 'z must be a typed array')
  assert(
    z.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "z must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(x), 'x must be a typed array')
  assert(
    x.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "x must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(y), 'y must be a typed array')
  assert(
    y.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "y must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_add(z, x, y)
}

exports.crypto_core_ed25519_scalar_sub = function (z, x, y) {
  assert(ArrayBuffer.isView(z), 'z must be a typed array')
  assert(
    z.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "z must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(x), 'x must be a typed array')
  assert(
    x.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "x must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(y), 'y must be a typed array')
  assert(
    y.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
    "y must be 'crypto_core_ed25519_SCALARBYTES' bytes"
  )

  binding.crypto_core_ed25519_scalar_sub(z, x, y)
}

// crypto_shorthash

exports.crypto_shorthash = function (out, input, k) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_shorthash_BYTES,
    "out must be 'crypto_shorthash_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_shorthash_KEYBYTES,
    "k must be 'crypto_shorthash_KEYBYTES' bytes"
  )

  const res = binding.crypto_shorthash(out, input, k)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_kdf

exports.crypto_kdf_keygen = function (key) {
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(key.byteLength === binding.crypto_kdf_KEYBYTES, "key must be 'crypto_kdf_KEYBYTES' bytes")

  binding.crypto_kdf_keygen(key)
}

exports.crypto_kdf_derive_from_key = function (subkey, subkeyId, ctx, key) {
  assert(ArrayBuffer.isView(subkey), 'subkey must be a typed array')
  assert(
    subkey.byteLength >= binding.crypto_kdf_BYTES_MIN,
    "subkey must be at least 'crypto_kdf_BYTES_MIN' bytes"
  )
  assert(
    subkey.byteLength <= binding.crypto_kdf_BYTES_MAX,
    "subkey must be at most 'crypto_kdf_BYTES_MAX' bytes"
  )
  assert(ArrayBuffer.isView(ctx), 'ctx must be a typed array')
  assert(
    ctx.byteLength === binding.crypto_kdf_CONTEXTBYTES,
    "ctx must be 'crypto_kdf_CONTEXTBYTES' bytes"
  )
  assert(ArrayBuffer.isView(key), 'key must be a typed array')
  assert(key.byteLength === binding.crypto_kdf_KEYBYTES, "key must be 'crypto_kdf_KEYBYTES' bytes")

  const res = binding.crypto_kdf_derive_from_key(subkey, subkeyId, ctx, key)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_hash

exports.crypto_hash = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(out.byteLength === binding.crypto_hash_BYTES, "out must be 'crypto_hash_BYTES' bytes")

  const res = binding.crypto_hash(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256 = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha256_BYTES,
    "out must be 'crypto_hash_sha256_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha256(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_init = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_init(state)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha256_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
    "state must be 'crypto_hash_sha256_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha256_BYTES,
    "out must be 'crypto_hash_sha256_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha256_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512 = function (out, input) {
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha512_BYTES,
    "out must be 'crypto_hash_sha512_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha512(out, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_init = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_init(state)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_update = function (state, input) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(ArrayBuffer.isView(input), 'input must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_update(state, input)

  if (res !== 0) throw new Error('status: ' + res)
}

exports.crypto_hash_sha512_final = function (state, out) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
    "state must be 'crypto_hash_sha512_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(
    out.byteLength === binding.crypto_hash_sha512_BYTES,
    "out must be 'crypto_hash_sha512_BYTES' bytes"
  )

  const res = binding.crypto_hash_sha512_final(state, out)

  if (res !== 0) throw new Error('status: ' + res)
}

// crypto_aead

exports.crypto_aead_xchacha20poly1305_ietf_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  binding.crypto_aead_xchacha20poly1305_ietf_keygen(k)
}

exports.crypto_aead_xchacha20poly1305_ietf_encrypt = function (c, m, ad, nsec, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "c must be 'm.byteLength + crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(c.byteLength <= 0xffffffff, 'c.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_encrypt(c, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_decrypt = function (m, nsec, c, ad, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "m must be 'c.byteLength - crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(m.byteLength <= 0xffffffff, 'm.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_decrypt(m, c, ad, npub, k)

  if (res < 0) throw new Error('could not verify data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_encrypt_detached = function (
  c,
  mac,
  m,
  ad,
  nsec,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_encrypt_detached(c, mac, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_xchacha20poly1305_ietf_decrypt_detached = function (
  m,
  nsec,
  c,
  mac,
  ad,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_xchacha20poly1305_ietf_decrypt_detached(m, c, mac, ad, npub, k)

  if (res !== 0) throw new Error('could not verify data')
}

exports.crypto_aead_chacha20poly1305_ietf_keygen = function (k) {
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  binding.crypto_aead_chacha20poly1305_ietf_keygen(k)
}

exports.crypto_aead_chacha20poly1305_ietf_encrypt = function (c, m, ad, nsec, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(
    c.byteLength === m.byteLength + binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "c must be 'm.byteLength + crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(c.byteLength <= 0xffffffff, 'c.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_encrypt(c, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_decrypt = function (m, nsec, c, ad, npub, k) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(
    m.byteLength === c.byteLength - binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "m must be 'c.byteLength - crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(m.byteLength <= 0xffffffff, 'm.byteLength must be a 32bit integer')
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_decrypt(m, c, ad, npub, k)

  if (res < 0) throw new Error('could not verify data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_encrypt_detached = function (
  c,
  mac,
  m,
  ad,
  nsec,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_encrypt_detached(c, mac, m, ad, npub, k)

  if (res < 0) throw new Error('could not encrypt data')

  return res
}

exports.crypto_aead_chacha20poly1305_ietf_decrypt_detached = function (
  m,
  nsec,
  c,
  mac,
  ad,
  npub,
  k
) {
  if (!ad) ad = undefined

  assert(nsec === null, 'nsec must always be set to null')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes")
  assert(ArrayBuffer.isView(mac), 'mac must be a typed array')
  assert(
    mac.byteLength === binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
    "mac must be 'crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
  )
  assert(ArrayBuffer.isView(npub), 'npub must be a typed array')
  assert(
    npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
    "npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
    "k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
  )

  const res = binding.crypto_aead_chacha20poly1305_ietf_decrypt_detached(m, c, mac, ad, npub, k)

  if (res !== 0) throw new Error('could not verify data')
}

// crypto_stream

exports.crypto_stream_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_NONCEBYTES,
    "n must be 'crypto_stream_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_KEYBYTES,
    "k must be 'crypto_stream_KEYBYTES' bytes"
  )

  binding.crypto_stream_xor_wrap_init(state, n, k)
}

exports.crypto_stream_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_xor_wrap_update(state, c, m)
}

exports.crypto_stream_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
    "state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_xor_wrap_final(state)
}

exports.crypto_stream_chacha20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
    "k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
  )

  binding.crypto_stream_chacha20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_chacha20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_chacha20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_chacha20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_chacha20_xor_wrap_final(state)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
    "n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
    "k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
  )

  binding.crypto_stream_chacha20_ietf_xor_wrap_init(state, n, k)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_chacha20_ietf_xor_wrap_update(state, c, m)
}

exports.crypto_stream_chacha20_ietf_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
    "state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_chacha20_ietf_xor_wrap_final(state)
}

exports.crypto_stream_xchacha20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
    "n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
    "k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
  )

  binding.crypto_stream_xchacha20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_xchacha20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_xchacha20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_xchacha20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
    "state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_xchacha20_xor_wrap_final(state)
}

exports.crypto_stream_salsa20_xor_wrap_init = function (state, n, k) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
    "n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(k), 'k must be a typed array')
  assert(
    k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
    "k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
  )

  binding.crypto_stream_salsa20_xor_wrap_init(state, n, k)
}

exports.crypto_stream_salsa20_xor_wrap_update = function (state, c, m) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )
  assert(ArrayBuffer.isView(c), 'c must be a typed array')
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes")

  binding.crypto_stream_salsa20_xor_wrap_update(state, c, m)
}

exports.crypto_stream_salsa20_xor_wrap_final = function (state) {
  assert(ArrayBuffer.isView(state), 'state must be a typed array')
  assert(
    state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
    "state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
  )

  binding.crypto_stream_salsa20_xor_wrap_final(state)
}

// experimental

exports.extension_tweak_ed25519_base = function (n, p, ns) {
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.extension_tweak_ed25519_BYTES,
    "p must be 'extension_tweak_ed25519_BYTES' bytes"
  )

  binding.extension_tweak_ed25519_base(n, p, ns)
}

exports.extension_tweak_ed25519_sign_detached = function (sig, m, scalar, pk) {
  assert(ArrayBuffer.isView(sig), 'sig must be a typed array')
  assert(sig.byteLength === binding.crypto_sign_BYTES, "sig must be 'crypto_sign_BYTES' bytes")
  assert(ArrayBuffer.isView(m), 'm must be a typed array')
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  if (pk) {
    assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
    assert(
      pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
      "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
    )
  }

  const res = binding.extension_tweak_ed25519_sign_detached(sig, m, scalar, pk)

  if (res !== 0) throw new Error('failed to compute signature')
}

exports.extension_tweak_ed25519_sk_to_scalar = function (n, sk) {
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(sk), 'sk must be a typed array')
  assert(
    sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
    "sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
  )

  binding.extension_tweak_ed25519_sk_to_scalar(n, sk)
}

exports.extension_tweak_ed25519_scalar = function (scalarOut, scalar, ns) {
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_scalar(scalarOut, scalar, ns)
}

exports.extension_tweak_ed25519_pk = function (tpk, pk, ns) {
  assert(ArrayBuffer.isView(tpk), 'tpk must be a typed array')
  assert(
    tpk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "tpk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_pk(tpk, pk, ns)

  if (res !== 0) throw new Error('failed to tweak public key')
}

exports.extension_tweak_ed25519_keypair = function (pk, scalarOut, scalarIn, ns) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.extension_tweak_ed25519_BYTES,
    "pk must be 'extension_tweak_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarIn), 'scalarIn must be a typed array')
  assert(
    scalarIn.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarIn must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_keypair(pk, scalarOut, scalarIn, ns)
}

exports.extension_tweak_ed25519_scalar_add = function (scalarOut, scalar, n) {
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalar), 'scalar must be a typed array')
  assert(
    scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(n), 'n must be a typed array')
  assert(
    n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  binding.extension_tweak_ed25519_scalar_add(scalarOut, scalar, n)
}

exports.extension_tweak_ed25519_pk_add = function (tpk, pk, p) {
  assert(ArrayBuffer.isView(tpk), 'tpk must be a typed array')
  assert(
    tpk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "tpk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )
  assert(ArrayBuffer.isView(p), 'p must be a typed array')
  assert(
    p.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
    "p must be 'crypto_sign_PUBLICKEYBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_pk_add(tpk, pk, p)

  if (res !== 0) throw new Error('failed to add tweak to public key')
}

exports.extension_tweak_ed25519_keypair_add = function (pk, scalarOut, scalarIn, tweak) {
  assert(ArrayBuffer.isView(pk), 'pk must be a typed array')
  assert(
    pk.byteLength === binding.extension_tweak_ed25519_BYTES,
    "pk must be 'extension_tweak_ed25519_BYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarOut), 'scalarOut must be a typed array')
  assert(
    scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(scalarIn), 'scalarIn must be a typed array')
  assert(
    scalarIn.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "scalarIn must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )
  assert(ArrayBuffer.isView(tweak), 'tweak must be a typed array')
  assert(
    tweak.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
    "tweak must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
  )

  const res = binding.extension_tweak_ed25519_keypair_add(pk, scalarOut, scalarIn, tweak)

  if (res !== 0) throw new Error('failed to add tweak to keypair')
}

exports.extension_pbkdf2_sha512_async = function (out, passwd, salt, iter, outlen, callback) {
  assert(
    iter >= binding.extension_pbkdf2_sha512_ITERATIONS_MIN,
    "iter must be at least 'extension_pbkdf2_sha512_ITERATIONS_MIN'"
  )
  assert(
    outlen <= binding.extension_pbkdf2_sha512_BYTES_MAX,
    "outlen must be at most 'extension_pbkdf2_sha512_BYTES_MAX'"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(out.byteLength >= outlen, "out must be at least 'outlen' bytes")
  assert(out.byteLength > 0, 'out must not be empty')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(salt.byteLength > 0, 'salt must not be empty')

  const [done, promise] = checkStatus(callback)

  binding.extension_pbkdf2_sha512_async(
    out.buffer,
    out.byteOffset,
    out.byteLength,

    passwd.buffer,
    passwd.byteOffset,
    passwd.byteLength,

    salt.buffer,
    salt.byteOffset,
    salt.byteLength,

    iter,
    outlen,

    done
  )

  return promise
}

exports.extension_pbkdf2_sha512 = function (out, passwd, salt, iter, outlen) {
  assert(
    iter >= binding.extension_pbkdf2_sha512_ITERATIONS_MIN,
    "iter must be at least 'extension_pbkdf2_sha512_ITERATIONS_MIN'"
  )
  assert(
    outlen <= binding.extension_pbkdf2_sha512_BYTES_MAX,
    "outlen must be at most 'extension_pbkdf2_sha512_BYTES_MAX'"
  )
  assert(ArrayBuffer.isView(out), 'out must be a typed array')
  assert(out.byteLength >= outlen, "out must be at least 'outlen' bytes")
  assert(out.byteLength > 0, 'out must not be empty')
  assert(ArrayBuffer.isView(passwd), 'passwd must be a typed array')
  assert(passwd.byteLength > 0, 'passwd must not be empty')
  assert(ArrayBuffer.isView(salt), 'salt must be a typed array')
  assert(salt.byteLength > 0, 'salt must not be empty')

  const res = binding.extension_pbkdf2_sha512(out, passwd, salt, iter, outlen)

  if (res !== 0) throw new Error('failed to add tweak to public key')
}

function checkStatus(callback, booleanResult = false) {
  let done, promise

  if (typeof callback === 'function') {
    done = function (status) {
      if (booleanResult) callback(null, status === 0)
      else if (status === 0) callback(null)
      else callback(new Error('status: ' + status))
    }
  } else {
    promise = new Promise(function (resolve, reject) {
      done = function (status) {
        if (booleanResult) resolve(status === 0)
        else if (status === 0) resolve()
        else reject(new Error('status: ' + status))
      }
    })
  }

  return [done, promise]
}
{
  "name": "sodium-native",
  "version": "5.1.0",
  "description": "Low level bindings for libsodium",
  "main": "index.js",
  "files": [
    "index.js",
    "binding.cc",
    "binding.js",
    "extensions",
    "prebuilds",
    "CMakeLists.txt"
  ],
  "imports": {
    "assert": {
      "bare": "bare-assert",
      "node": "assert"
    }
  },
  "addon": true,
  "dependencies": {
    "bare-assert": "^1.2.0",
    "require-addon": "^1.1.0",
    "which-runtime": "^1.2.1"
  },
  "devDependencies": {
    "bare-compat-napi": "^1.3.5",
    "brittle": "^3.16.2",
    "cmake-bare": "^1.6.1",
    "cmake-fetch": "^1.4.3",
    "cmake-napi": "^1.2.1",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "scripts": {
    "test": "prettier . --check && npm run test:node && npm run test:bare",
    "test:node": "node test/all.js",
    "test:bare": "bare test/all.js"
  },
  "standard": {
    "ignore": [
      "/test/fixtures/*.js"
    ]
  },
  "engines": {
    "bare": ">=1.16.0"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sodium-native.git"
  },
  "contributors": [
    "Emil Bay <github@tixz.dk> (http://bayes.dk)",
    "Mathias Buus <mathiasbuus@gmail.com> (https://mafinto.sh)",
    "Christophe Diederichs <chm-diederichs@hyperdivision.dk>"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/sodium-native/issues"
  },
  "homepage": "https://github.com/holepunchto/sodium-native"
}
module.exports = require('sodium-native')
{
  "name": "sodium-universal",
  "version": "5.0.1",
  "description": "Universal wrapper for sodium-javascript and sodium-native working in Node.js and the Browser",
  "main": "index.js",
  "dependencies": {
    "sodium-native": "^5.0.1"
  },
  "peerDependencies": {
    "sodium-javascript": "~0.8.0"
  },
  "peerDependenciesMeta": {
    "sodium-javascript": {
      "optional": true
    }
  },
  "scripts": {
    "prepublish": "./build-scripts/generate.js"
  },
  "browser": {
    "sodium-native": "sodium-javascript"
  },
  "browserify": {
    "transform": [
      "./build-scripts/transform.js"
    ]
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/sodium-universal.git"
  },
  "keywords": [
    "libsodium",
    "sodium",
    "sodium-native",
    "sodium-javascript",
    "browserify"
  ],
  "contributors": [
    "Emil Bay <github@tixz.dk> (http://bayes.dk)",
    "Mathias Buus <mathiasbuus@gmail.com> (https://mafinto.sh)",
    "Christophe Diederichs <chm-diederichs@hyperdivision.dk>"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/holepunchto/sodium-universal/issues"
  },
  "homepage": "https://github.com/holepunchto/sodium-universal#readme"
}
const { EventEmitter } = require('events-universal')
const FIFO = require('fast-fifo')
const TextDecoder = require('text-decoder')

const StreamError = require('./lib/errors.js')

// if we do a future major, expect queue microtask to be there always, for now a bit defensive
const qmt =
  typeof queueMicrotask === 'undefined' ? (fn) => global.process.nextTick(fn) : queueMicrotask

// 29 bits used total (4 from shared, 14 from read, and 11 from write)
const MAX = (1 << 29) - 1

// Shared state
const OPENING = 0b0001
const PREDESTROYING = 0b0010
const DESTROYING = 0b0100
const DESTROYED = 0b1000

const NOT_OPENING = MAX ^ OPENING
const NOT_PREDESTROYING = MAX ^ PREDESTROYING

// Read state (4 bit offset from shared state)
const READ_ACTIVE = 0b00000000000001 << 4
const READ_UPDATING = 0b00000000000010 << 4
const READ_PRIMARY = 0b00000000000100 << 4
const READ_QUEUED = 0b00000000001000 << 4
const READ_RESUMED = 0b00000000010000 << 4
const READ_PIPE_DRAINED = 0b00000000100000 << 4
const READ_ENDING = 0b00000001000000 << 4
const READ_EMIT_DATA = 0b00000010000000 << 4
const READ_EMIT_READABLE = 0b00000100000000 << 4
const READ_EMITTED_READABLE = 0b00001000000000 << 4
const READ_DONE = 0b00010000000000 << 4
const READ_NEXT_TICK = 0b00100000000000 << 4
const READ_NEEDS_PUSH = 0b01000000000000 << 4
const READ_READ_AHEAD = 0b10000000000000 << 4

// Combined read state
const READ_FLOWING = READ_RESUMED | READ_PIPE_DRAINED
const READ_ACTIVE_AND_NEEDS_PUSH = READ_ACTIVE | READ_NEEDS_PUSH
const READ_PRIMARY_AND_ACTIVE = READ_PRIMARY | READ_ACTIVE
const READ_EMIT_READABLE_AND_QUEUED = READ_EMIT_READABLE | READ_QUEUED
const READ_RESUMED_READ_AHEAD = READ_RESUMED | READ_READ_AHEAD

const READ_NOT_ACTIVE = MAX ^ READ_ACTIVE
const READ_NON_PRIMARY = MAX ^ READ_PRIMARY
const READ_NON_PRIMARY_AND_PUSHED = MAX ^ (READ_PRIMARY | READ_NEEDS_PUSH)
const READ_PUSHED = MAX ^ READ_NEEDS_PUSH
const READ_PAUSED = MAX ^ READ_RESUMED
const READ_NOT_QUEUED = MAX ^ (READ_QUEUED | READ_EMITTED_READABLE)
const READ_NOT_ENDING = MAX ^ READ_ENDING
const READ_PIPE_NOT_DRAINED = MAX ^ READ_FLOWING
const READ_NOT_NEXT_TICK = MAX ^ READ_NEXT_TICK
const READ_NOT_UPDATING = MAX ^ READ_UPDATING
const READ_NO_READ_AHEAD = MAX ^ READ_READ_AHEAD
const READ_PAUSED_NO_READ_AHEAD = MAX ^ READ_RESUMED_READ_AHEAD

// Write state (18 bit offset, 4 bit offset from shared state and 14 from read state)
const WRITE_ACTIVE = 0b00000000001 << 18
const WRITE_UPDATING = 0b00000000010 << 18
const WRITE_PRIMARY = 0b00000000100 << 18
const WRITE_QUEUED = 0b00000001000 << 18
const WRITE_UNDRAINED = 0b00000010000 << 18
const WRITE_DONE = 0b00000100000 << 18
const WRITE_EMIT_DRAIN = 0b00001000000 << 18
const WRITE_NEXT_TICK = 0b00010000000 << 18
const WRITE_WRITING = 0b00100000000 << 18
const WRITE_FINISHING = 0b01000000000 << 18
const WRITE_CORKED = 0b10000000000 << 18

const WRITE_NOT_ACTIVE = MAX ^ (WRITE_ACTIVE | WRITE_WRITING)
const WRITE_NON_PRIMARY = MAX ^ WRITE_PRIMARY
const WRITE_NOT_FINISHING = MAX ^ (WRITE_ACTIVE | WRITE_FINISHING)
const WRITE_DRAINED = MAX ^ WRITE_UNDRAINED
const WRITE_NOT_QUEUED = MAX ^ WRITE_QUEUED
const WRITE_NOT_NEXT_TICK = MAX ^ WRITE_NEXT_TICK
const WRITE_NOT_UPDATING = MAX ^ WRITE_UPDATING
const WRITE_NOT_CORKED = MAX ^ WRITE_CORKED

// Combined shared state
const ACTIVE = READ_ACTIVE | WRITE_ACTIVE
const NOT_ACTIVE = MAX ^ ACTIVE
const DONE = READ_DONE | WRITE_DONE
const DESTROY_STATUS = DESTROYING | DESTROYED | PREDESTROYING
const OPEN_STATUS = DESTROY_STATUS | OPENING
const AUTO_DESTROY = DESTROY_STATUS | DONE
const NON_PRIMARY = WRITE_NON_PRIMARY & READ_NON_PRIMARY
const ACTIVE_OR_TICKING = WRITE_NEXT_TICK | READ_NEXT_TICK
const TICKING = ACTIVE_OR_TICKING & NOT_ACTIVE
const IS_OPENING = OPEN_STATUS | TICKING

// Combined shared state and read state
const READ_PRIMARY_STATUS = OPEN_STATUS | READ_ENDING | READ_DONE
const READ_STATUS = OPEN_STATUS | READ_DONE | READ_QUEUED
const READ_ENDING_STATUS = OPEN_STATUS | READ_ENDING | READ_QUEUED
const READ_READABLE_STATUS = OPEN_STATUS | READ_EMIT_READABLE | READ_QUEUED | READ_EMITTED_READABLE
const SHOULD_NOT_READ =
  OPEN_STATUS | READ_ACTIVE | READ_ENDING | READ_DONE | READ_NEEDS_PUSH | READ_READ_AHEAD
const READ_BACKPRESSURE_STATUS = DESTROY_STATUS | READ_ENDING | READ_DONE
const READ_UPDATE_SYNC_STATUS = READ_UPDATING | OPEN_STATUS | READ_NEXT_TICK | READ_PRIMARY
const READ_NEXT_TICK_OR_OPENING = READ_NEXT_TICK | OPENING

// Combined write state
const WRITE_PRIMARY_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_DONE
const WRITE_QUEUED_AND_UNDRAINED = WRITE_QUEUED | WRITE_UNDRAINED
const WRITE_QUEUED_AND_ACTIVE = WRITE_QUEUED | WRITE_ACTIVE
const WRITE_DRAIN_STATUS = WRITE_QUEUED | WRITE_UNDRAINED | OPEN_STATUS | WRITE_ACTIVE
const WRITE_STATUS = OPEN_STATUS | WRITE_ACTIVE | WRITE_QUEUED | WRITE_CORKED
const WRITE_PRIMARY_AND_ACTIVE = WRITE_PRIMARY | WRITE_ACTIVE
const WRITE_ACTIVE_AND_WRITING = WRITE_ACTIVE | WRITE_WRITING
const WRITE_FINISHING_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_QUEUED_AND_ACTIVE | WRITE_DONE
const WRITE_BACKPRESSURE_STATUS = WRITE_UNDRAINED | DESTROY_STATUS | WRITE_FINISHING | WRITE_DONE
const WRITE_UPDATE_SYNC_STATUS = WRITE_UPDATING | OPEN_STATUS | WRITE_NEXT_TICK | WRITE_PRIMARY
const WRITE_DROP_DATA = WRITE_FINISHING | WRITE_DONE | DESTROY_STATUS

const asyncIterator = Symbol.asyncIterator || Symbol('asyncIterator')

class WritableState {
  constructor(
    stream,
    { highWaterMark = 16384, map = null, mapWritable, byteLength, byteLengthWritable } = {}
  ) {
    this.stream = stream
    this.queue = new FIFO()
    this.highWaterMark = highWaterMark
    this.buffered = 0
    this.error = null
    this.pipeline = null
    this.drains = null // if we add more seldomly used helpers we might them into a subobject so its a single ptr
    this.byteLength = byteLengthWritable || byteLength || defaultByteLength
    this.map = mapWritable || map
    this.afterWrite = afterWrite.bind(this)
    this.afterUpdateNextTick = updateWriteNT.bind(this)
  }

  get ending() {
    return (this.stream._duplexState & WRITE_FINISHING) !== 0
  }

  get ended() {
    return (this.stream._duplexState & WRITE_DONE) !== 0
  }

  push(data) {
    if ((this.stream._duplexState & WRITE_DROP_DATA) !== 0) return false
    if (this.map !== null) data = this.map(data)

    this.buffered += this.byteLength(data)
    this.queue.push(data)

    if (this.buffered < this.highWaterMark) {
      this.stream._duplexState |= WRITE_QUEUED
      return true
    }

    this.stream._duplexState |= WRITE_QUEUED_AND_UNDRAINED
    return false
  }

  shift() {
    const data = this.queue.shift()

    this.buffered -= this.byteLength(data)
    if (this.buffered === 0) this.stream._duplexState &= WRITE_NOT_QUEUED

    return data
  }

  end(data) {
    if (typeof data === 'function') {
      this.stream.once('finish', data)
    } else if (data !== undefined && data !== null) {
      this.push(data)
    }

    this.stream._duplexState = (this.stream._duplexState | WRITE_FINISHING) & WRITE_NON_PRIMARY
  }

  autoBatch(data, cb) {
    const buffer = []
    const stream = this.stream

    buffer.push(data)
    while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED_AND_ACTIVE) {
      buffer.push(stream._writableState.shift())
    }

    if ((stream._duplexState & OPEN_STATUS) !== 0) return cb(null)
    stream._writev(buffer, cb)
  }

  update() {
    const stream = this.stream

    stream._duplexState |= WRITE_UPDATING

    do {
      while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED) {
        const data = this.shift()
        stream._duplexState |= WRITE_ACTIVE_AND_WRITING
        stream._write(data, this.afterWrite)
      }

      if ((stream._duplexState & WRITE_PRIMARY_AND_ACTIVE) === 0) this.updateNonPrimary()
    } while (this.continueUpdate() === true)

    stream._duplexState &= WRITE_NOT_UPDATING
  }

  updateNonPrimary() {
    const stream = this.stream

    if ((stream._duplexState & WRITE_FINISHING_STATUS) === WRITE_FINISHING) {
      stream._duplexState = stream._duplexState | WRITE_ACTIVE
      stream._final(afterFinal.bind(this))
      return
    }

    if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
      if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
        stream._duplexState |= ACTIVE
        stream._destroy(afterDestroy.bind(this))
      }
      return
    }

    if ((stream._duplexState & IS_OPENING) === OPENING) {
      stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING
      stream._open(afterOpen.bind(this))
    }
  }

  continueUpdate() {
    if ((this.stream._duplexState & WRITE_NEXT_TICK) === 0) return false
    this.stream._duplexState &= WRITE_NOT_NEXT_TICK
    return true
  }

  updateCallback() {
    if ((this.stream._duplexState & WRITE_UPDATE_SYNC_STATUS) === WRITE_PRIMARY) {
      this.update()
    } else {
      this.updateNextTick()
    }
  }

  updateNextTick() {
    if ((this.stream._duplexState & WRITE_NEXT_TICK) !== 0) return
    this.stream._duplexState |= WRITE_NEXT_TICK
    if ((this.stream._duplexState & WRITE_UPDATING) === 0) qmt(this.afterUpdateNextTick)
  }
}

class ReadableState {
  constructor(
    stream,
    { highWaterMark = 16384, map = null, mapReadable, byteLength, byteLengthReadable } = {}
  ) {
    this.stream = stream
    this.queue = new FIFO()
    this.highWaterMark = highWaterMark === 0 ? 1 : highWaterMark
    this.buffered = 0
    this.readAhead = highWaterMark > 0
    this.error = null
    this.pipeline = null
    this.byteLength = byteLengthReadable || byteLength || defaultByteLength
    this.map = mapReadable || map
    this.pipeTo = null
    this.afterRead = afterRead.bind(this)
    this.afterUpdateNextTick = updateReadNT.bind(this)
  }

  get ending() {
    return (this.stream._duplexState & READ_ENDING) !== 0
  }

  get ended() {
    return (this.stream._duplexState & READ_DONE) !== 0
  }

  pipe(pipeTo, cb) {
    if (this.pipeTo !== null) throw StreamError.BAD_ARGUMENT('Can only pipe to one destination')
    if (typeof cb !== 'function') cb = null

    this.stream._duplexState |= READ_PIPE_DRAINED
    this.pipeTo = pipeTo
    this.pipeline = new Pipeline(this.stream, pipeTo, cb)

    if (cb) this.stream.on('error', noop) // We already error handle this so supress crashes

    if (isStreamx(pipeTo)) {
      pipeTo._writableState.pipeline = this.pipeline
      if (cb) pipeTo.on('error', noop) // We already error handle this so supress crashes
      pipeTo.on('finish', this.pipeline.finished.bind(this.pipeline)) // TODO: just call finished from pipeTo itself
    } else {
      const onerror = this.pipeline.done.bind(this.pipeline, pipeTo)
      const onclose = this.pipeline.done.bind(this.pipeline, pipeTo, null) // onclose has a weird bool arg
      pipeTo.on('error', onerror)
      pipeTo.on('close', onclose)
      pipeTo.on('finish', this.pipeline.finished.bind(this.pipeline))
    }

    pipeTo.on('drain', afterDrain.bind(this))
    this.stream.emit('piping', pipeTo)
    pipeTo.emit('pipe', this.stream)
  }

  push(data) {
    const stream = this.stream

    if (data === null) {
      this.highWaterMark = 0
      stream._duplexState = (stream._duplexState | READ_ENDING) & READ_NON_PRIMARY_AND_PUSHED
      return false
    }

    if (this.map !== null) {
      data = this.map(data)
      if (data === null) {
        stream._duplexState &= READ_PUSHED
        return this.buffered < this.highWaterMark
      }
    }

    this.buffered += this.byteLength(data)
    this.queue.push(data)

    stream._duplexState = (stream._duplexState | READ_QUEUED) & READ_PUSHED

    return this.buffered < this.highWaterMark
  }

  shift() {
    const data = this.queue.shift()

    this.buffered -= this.byteLength(data)
    if (this.buffered === 0) {
      this.stream._duplexState &= READ_NOT_QUEUED
    }

    return data
  }

  unshift(data) {
    const pending = [this.map !== null ? this.map(data) : data]
    while (this.buffered > 0) pending.push(this.shift())

    for (let i = 0; i < pending.length - 1; i++) {
      const data = pending[i]
      this.buffered += this.byteLength(data)
      this.queue.push(data)
    }

    this.push(pending[pending.length - 1])
  }

  read() {
    const stream = this.stream

    if ((stream._duplexState & READ_STATUS) === READ_QUEUED) {
      const data = this.shift()

      if (this.pipeTo !== null && this.pipeTo.write(data) === false) {
        stream._duplexState &= READ_PIPE_NOT_DRAINED
      }

      if ((stream._duplexState & READ_EMIT_DATA) !== 0) {
        stream.emit('data', data)
      }

      return data
    }

    if (this.readAhead === false) {
      stream._duplexState |= READ_READ_AHEAD
      this.updateNextTick()
    }

    return null
  }

  drain() {
    const stream = this.stream

    while (
      (stream._duplexState & READ_STATUS) === READ_QUEUED &&
      (stream._duplexState & READ_FLOWING) !== 0
    ) {
      const data = this.shift()

      if (this.pipeTo !== null && this.pipeTo.write(data) === false) {
        stream._duplexState &= READ_PIPE_NOT_DRAINED
      }

      if ((stream._duplexState & READ_EMIT_DATA) !== 0) {
        stream.emit('data', data)
      }
    }
  }

  update() {
    const stream = this.stream

    stream._duplexState |= READ_UPDATING

    do {
      this.drain()

      while (
        this.buffered < this.highWaterMark &&
        (stream._duplexState & SHOULD_NOT_READ) === READ_READ_AHEAD
      ) {
        stream._duplexState |= READ_ACTIVE_AND_NEEDS_PUSH
        stream._read(this.afterRead)
        this.drain()
      }

      if ((stream._duplexState & READ_READABLE_STATUS) === READ_EMIT_READABLE_AND_QUEUED) {
        stream._duplexState |= READ_EMITTED_READABLE
        stream.emit('readable')
      }

      if ((stream._duplexState & READ_PRIMARY_AND_ACTIVE) === 0) {
        this.updateNonPrimary()
      }
    } while (this.continueUpdate() === true)

    stream._duplexState &= READ_NOT_UPDATING
  }

  updateNonPrimary() {
    const stream = this.stream

    if ((stream._duplexState & READ_ENDING_STATUS) === READ_ENDING) {
      stream._duplexState = (stream._duplexState | READ_DONE) & READ_NOT_ENDING
      stream.emit('end')

      if ((stream._duplexState & AUTO_DESTROY) === DONE) {
        stream._duplexState |= DESTROYING
      }

      if (this.pipeTo !== null) {
        this.pipeTo.end()
      }
    }

    if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
      if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
        stream._duplexState |= ACTIVE
        stream._destroy(afterDestroy.bind(this))
      }
      return
    }

    if ((stream._duplexState & IS_OPENING) === OPENING) {
      stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING
      stream._open(afterOpen.bind(this))
    }
  }

  continueUpdate() {
    if ((this.stream._duplexState & READ_NEXT_TICK) === 0) return false
    this.stream._duplexState &= READ_NOT_NEXT_TICK
    return true
  }

  updateCallback() {
    if ((this.stream._duplexState & READ_UPDATE_SYNC_STATUS) === READ_PRIMARY) {
      this.update()
    } else {
      this.updateNextTick()
    }
  }

  updateNextTickIfOpen() {
    if ((this.stream._duplexState & READ_NEXT_TICK_OR_OPENING) !== 0) return
    this.stream._duplexState |= READ_NEXT_TICK
    if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick)
  }

  updateNextTick() {
    if ((this.stream._duplexState & READ_NEXT_TICK) !== 0) return
    this.stream._duplexState |= READ_NEXT_TICK
    if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick)
  }
}

class TransformState {
  constructor(stream) {
    this.data = null
    this.afterTransform = afterTransform.bind(stream)
    this.afterFinal = null
  }
}

class Pipeline {
  constructor(src, dst, cb) {
    this.from = src
    this.to = dst
    this.afterPipe = cb
    this.error = null
    this.pipeToFinished = false
  }

  finished() {
    this.pipeToFinished = true
  }

  done(stream, err) {
    if (err) this.error = err

    if (stream === this.to) {
      this.to = null

      if (this.from !== null) {
        if ((this.from._duplexState & READ_DONE) === 0 || !this.pipeToFinished) {
          this.from.destroy(this.error || StreamError.PREMATURE_CLOSE('Writable stream closed'))
        }
        return
      }
    }

    if (stream === this.from) {
      this.from = null

      if (this.to !== null) {
        if ((stream._duplexState & READ_DONE) === 0) {
          this.to.destroy(this.error || StreamError.PREMATURE_CLOSE('Readable stream closed'))
        }
        return
      }
    }

    if (this.afterPipe !== null) this.afterPipe(this.error)
    this.to = this.from = this.afterPipe = null
  }
}

function afterDrain() {
  this.stream._duplexState |= READ_PIPE_DRAINED
  this.updateCallback()
}

function afterFinal(err) {
  const stream = this.stream
  if (err) stream.destroy(err)

  if ((stream._duplexState & DESTROY_STATUS) === 0) {
    stream._duplexState |= WRITE_DONE
    stream.emit('finish')
  }

  if ((stream._duplexState & AUTO_DESTROY) === DONE) {
    stream._duplexState |= DESTROYING
  }

  stream._duplexState &= WRITE_NOT_FINISHING

  // no need to wait the extra tick here, so we short circuit that
  if ((stream._duplexState & WRITE_UPDATING) === 0) {
    this.update()
  } else {
    this.updateNextTick()
  }
}

function afterDestroy(err) {
  const stream = this.stream

  if (!err && !StreamError.isStreamDestroyed(this.error)) err = this.error
  if (err) stream.emit('error', err)

  stream._duplexState |= DESTROYED
  stream.emit('close')

  const rs = stream._readableState
  const ws = stream._writableState

  if (rs !== null && rs.pipeline !== null) {
    rs.pipeline.done(stream, err)
  }

  if (ws !== null) {
    while (ws.drains !== null && ws.drains.length > 0) {
      ws.drains.shift().resolve(false)
    }

    if (ws.pipeline !== null) {
      ws.pipeline.done(stream, err)
    }
  }
}

function afterWrite(err) {
  const stream = this.stream

  if (err) stream.destroy(err)
  stream._duplexState &= WRITE_NOT_ACTIVE

  if (this.drains !== null) tickDrains(this.drains)

  if ((stream._duplexState & WRITE_DRAIN_STATUS) === WRITE_UNDRAINED) {
    stream._duplexState &= WRITE_DRAINED

    if ((stream._duplexState & WRITE_EMIT_DRAIN) === WRITE_EMIT_DRAIN) {
      stream.emit('drain')
    }
  }

  this.updateCallback()
}

function afterRead(err) {
  if (err) this.stream.destroy(err)
  this.stream._duplexState &= READ_NOT_ACTIVE

  if (this.readAhead === false && (this.stream._duplexState & READ_RESUMED) === 0) {
    this.stream._duplexState &= READ_NO_READ_AHEAD
  }

  this.updateCallback()
}

function updateReadNT() {
  if ((this.stream._duplexState & READ_UPDATING) === 0) {
    this.stream._duplexState &= READ_NOT_NEXT_TICK
    this.update()
  }
}

function updateWriteNT() {
  if ((this.stream._duplexState & WRITE_UPDATING) === 0) {
    this.stream._duplexState &= WRITE_NOT_NEXT_TICK
    this.update()
  }
}

function tickDrains(drains) {
  for (let i = 0; i < drains.length; i++) {
    // drains.writes are monotonic, so if one is 0 its always the first one
    if (--drains[i].writes === 0) {
      drains.shift().resolve(true)
      i--
    }
  }
}

function afterOpen(err) {
  const stream = this.stream

  if (err) stream.destroy(err)

  if ((stream._duplexState & DESTROYING) === 0) {
    if ((stream._duplexState & READ_PRIMARY_STATUS) === 0) {
      stream._duplexState |= READ_PRIMARY
    }

    if ((stream._duplexState & WRITE_PRIMARY_STATUS) === 0) {
      stream._duplexState |= WRITE_PRIMARY
    }

    stream.emit('open')
  }

  stream._duplexState &= NOT_ACTIVE

  if (stream._writableState !== null) {
    stream._writableState.updateCallback()
  }

  if (stream._readableState !== null) {
    stream._readableState.updateCallback()
  }
}

function afterTransform(err, data) {
  if (data !== undefined && data !== null) this.push(data)
  this._writableState.afterWrite(err)
}

function newListener(name) {
  if (this._readableState !== null) {
    if (name === 'data') {
      this._duplexState |= READ_EMIT_DATA | READ_RESUMED_READ_AHEAD
      this._readableState.updateNextTick()
    }
    if (name === 'readable') {
      this._duplexState |= READ_EMIT_READABLE
      this._readableState.updateNextTick()
    }
  }

  if (this._writableState !== null) {
    if (name === 'drain') {
      this._duplexState |= WRITE_EMIT_DRAIN
      this._writableState.updateNextTick()
    }
  }
}

class Stream extends EventEmitter {
  constructor(opts) {
    super()

    this._duplexState = 0
    this._readableState = null
    this._writableState = null

    if (opts) {
      if (opts.open) this._open = opts.open
      if (opts.destroy) this._destroy = opts.destroy
      if (opts.predestroy) this._predestroy = opts.predestroy
      if (opts.signal) opts.signal.addEventListener('abort', abort.bind(this))
    }

    this.on('newListener', newListener)
  }

  _open(cb) {
    cb(null)
  }

  _destroy(cb) {
    cb(null)
  }

  _predestroy() {
    // does nothing
  }

  get readable() {
    return this._readableState !== null ? true : undefined
  }

  get writable() {
    return this._writableState !== null ? true : undefined
  }

  get destroyed() {
    return (this._duplexState & DESTROYED) !== 0
  }

  get destroying() {
    return (this._duplexState & DESTROY_STATUS) !== 0
  }

  destroy(err) {
    if ((this._duplexState & DESTROY_STATUS) === 0) {
      if (!err) err = StreamError.STREAM_DESTROYED()
      this._duplexState = (this._duplexState | DESTROYING) & NON_PRIMARY

      if (this._readableState !== null) {
        this._readableState.highWaterMark = 0
        this._readableState.error = err
      }

      if (this._writableState !== null) {
        this._writableState.highWaterMark = 0
        this._writableState.error = err
      }

      this._duplexState |= PREDESTROYING
      this._predestroy()
      this._duplexState &= NOT_PREDESTROYING

      if (this._readableState !== null) {
        this._readableState.updateNextTick()
      }

      if (this._writableState !== null) {
        this._writableState.updateNextTick()
      }
    }
  }
}

class Readable extends Stream {
  constructor(opts) {
    super(opts)

    this._duplexState |= OPENING | WRITE_DONE | READ_READ_AHEAD
    this._readableState = new ReadableState(this, opts)

    if (opts) {
      if (this._readableState.readAhead === false) this._duplexState &= READ_NO_READ_AHEAD
      if (opts.read) this._read = opts.read
      if (opts.eagerOpen) this._readableState.updateNextTick()
      if (opts.encoding) this.setEncoding(opts.encoding)
    }
  }

  static deferred(fn, opts) {
    const out = new PassThrough(opts)

    fn()
      .then((src) => {
        if (src === null) return out.end()
        if (out.destroying) return
        pipeline(src, out, noop)
      })
      .catch((err) => out.destroy(err))

    return out
  }

  setEncoding(encoding) {
    const dec = new TextDecoder(encoding)
    const map = this._readableState.map || echo
    this._readableState.map = mapOrSkip
    return this

    function mapOrSkip(data) {
      const next = dec.push(data)
      return next === '' && (data.byteLength !== 0 || dec.remaining > 0) ? null : map(next)
    }
  }

  _read(cb) {
    cb(null)
  }

  pipe(dest, cb) {
    this._readableState.updateNextTick()
    this._readableState.pipe(dest, cb)
    return dest
  }

  read() {
    this._readableState.updateNextTick()
    return this._readableState.read()
  }

  push(data) {
    this._readableState.updateNextTickIfOpen()
    return this._readableState.push(data)
  }

  unshift(data) {
    this._readableState.updateNextTickIfOpen()
    return this._readableState.unshift(data)
  }

  resume() {
    this._duplexState |= READ_RESUMED_READ_AHEAD
    this._readableState.updateNextTick()
    return this
  }

  pause() {
    this._duplexState &=
      this._readableState.readAhead === false ? READ_PAUSED_NO_READ_AHEAD : READ_PAUSED
    return this
  }

  static _fromAsyncIterator(ite, opts) {
    let destroy

    const rs = new Readable({
      ...opts,
      read(cb) {
        ite.next().then(push).then(cb.bind(null, null)).catch(cb)
      },
      predestroy() {
        destroy = ite.return()
      },
      destroy(cb) {
        if (!destroy) return cb(null)
        destroy.then(cb.bind(null, null)).catch(cb)
      }
    })

    return rs

    function push(data) {
      if (data.done) rs.push(null)
      else rs.push(data.value)
    }
  }

  static from(data, opts) {
    if (isReadStreamx(data)) return data
    if (data[asyncIterator]) return this._fromAsyncIterator(data[asyncIterator](), opts)
    if (!Array.isArray(data)) data = data === undefined ? [] : [data]

    let i = 0
    return new Readable({
      ...opts,
      read(cb) {
        this.push(i === data.length ? null : data[i++])
        cb(null)
      }
    })
  }

  static isBackpressured(rs) {
    return (
      (rs._duplexState & READ_BACKPRESSURE_STATUS) !== 0 ||
      rs._readableState.buffered >= rs._readableState.highWaterMark
    )
  }

  static isPaused(rs) {
    return (rs._duplexState & READ_RESUMED) === 0
  }

  [asyncIterator]() {
    const stream = this

    let error = null
    let promiseResolve = null
    let promiseReject = null

    this.on('error', (err) => {
      error = err
    })
    this.on('readable', onreadable)
    this.on('close', onclose)

    return {
      [asyncIterator]() {
        return this
      },
      next() {
        return new Promise(function (resolve, reject) {
          promiseResolve = resolve
          promiseReject = reject
          const data = stream.read()
          if (data !== null) ondata(data)
          else if ((stream._duplexState & DESTROYED) !== 0) ondata(null)
        })
      },
      return() {
        return destroy(null)
      },
      throw(err) {
        return destroy(err)
      }
    }

    function onreadable() {
      if (promiseResolve !== null) ondata(stream.read())
    }

    function onclose() {
      if (promiseResolve !== null) ondata(null)
    }

    function ondata(data) {
      if (promiseReject === null) return
      if (error) {
        promiseReject(error)
      } else if (data === null && (stream._duplexState & READ_DONE) === 0) {
        promiseReject(StreamError.STREAM_DESTROYED())
      } else {
        promiseResolve({ value: data, done: data === null })
      }
      promiseReject = promiseResolve = null
    }

    function destroy(err) {
      stream.destroy(err)
      return new Promise((resolve, reject) => {
        if (stream._duplexState & DESTROYED) return resolve({ value: undefined, done: true })
        stream.once('close', function () {
          if (err) reject(err)
          else resolve({ value: undefined, done: true })
        })
      })
    }
  }
}

class Writable extends Stream {
  constructor(opts) {
    super(opts)

    this._duplexState |= OPENING | READ_DONE
    this._writableState = new WritableState(this, opts)

    if (opts) {
      if (opts.writev) this._writev = opts.writev
      if (opts.write) this._write = opts.write
      if (opts.final) this._final = opts.final
      if (opts.eagerOpen) this._writableState.updateNextTick()
    }
  }

  cork() {
    this._duplexState |= WRITE_CORKED
  }

  uncork() {
    this._duplexState &= WRITE_NOT_CORKED
    this._writableState.updateNextTick()
  }

  _writev(batch, cb) {
    cb(null)
  }

  _write(data, cb) {
    this._writableState.autoBatch(data, cb)
  }

  _final(cb) {
    cb(null)
  }

  static isBackpressured(ws) {
    return (ws._duplexState & WRITE_BACKPRESSURE_STATUS) !== 0
  }

  static drained(ws) {
    if (ws.destroyed) return Promise.resolve(false)

    const state = ws._writableState
    const pending = isWritev(ws) ? Math.min(1, state.queue.length) : state.queue.length
    const writes = pending + (ws._duplexState & WRITE_WRITING ? 1 : 0)
    if (writes === 0) return Promise.resolve(true)

    if (state.drains === null) state.drains = []
    return new Promise((resolve) => {
      state.drains.push({ writes, resolve })
    })
  }

  write(data) {
    this._writableState.updateNextTick()
    return this._writableState.push(data)
  }

  end(data) {
    this._writableState.updateNextTick()
    this._writableState.end(data)
    return this
  }
}

class Duplex extends Readable {
  // and Writable
  constructor(opts) {
    super(opts)

    this._duplexState = OPENING | (this._duplexState & READ_READ_AHEAD)
    this._writableState = new WritableState(this, opts)

    if (opts) {
      if (opts.writev) this._writev = opts.writev
      if (opts.write) this._write = opts.write
      if (opts.final) this._final = opts.final
    }
  }

  cork() {
    this._duplexState |= WRITE_CORKED
  }

  uncork() {
    this._duplexState &= WRITE_NOT_CORKED
    this._writableState.updateNextTick()
  }

  _writev(batch, cb) {
    cb(null)
  }

  _write(data, cb) {
    this._writableState.autoBatch(data, cb)
  }

  _final(cb) {
    cb(null)
  }

  write(data) {
    this._writableState.updateNextTick()
    return this._writableState.push(data)
  }

  end(data) {
    this._writableState.updateNextTick()
    this._writableState.end(data)
    return this
  }
}

class Transform extends Duplex {
  constructor(opts) {
    super(opts)
    this._transformState = new TransformState(this)

    if (opts) {
      if (opts.transform) this._transform = opts.transform
      if (opts.flush) this._flush = opts.flush
    }
  }

  _write(data, cb) {
    if (this._readableState.buffered >= this._readableState.highWaterMark) {
      this._transformState.data = data
    } else {
      this._transform(data, this._transformState.afterTransform)
    }
  }

  _read(cb) {
    if (this._transformState.data !== null) {
      const data = this._transformState.data
      this._transformState.data = null
      cb(null)
      this._transform(data, this._transformState.afterTransform)
    } else {
      cb(null)
    }
  }

  destroy(err) {
    super.destroy(err)
    if (this._transformState.data !== null) {
      this._transformState.data = null
      this._transformState.afterTransform()
    }
  }

  _transform(data, cb) {
    cb(null, data)
  }

  _flush(cb) {
    cb(null)
  }

  _final(cb) {
    this._transformState.afterFinal = cb
    this._flush(transformAfterFlush.bind(this))
  }
}

class PassThrough extends Transform {}

function transformAfterFlush(err, data) {
  const cb = this._transformState.afterFinal
  if (err) return cb(err)

  if (data !== null && data !== undefined) this.push(data)
  this.push(null)
  cb(null)
}

function pipelinePromise(...streams) {
  return new Promise((resolve, reject) => {
    return pipeline(...streams, (err) => {
      if (err) return reject(err)
      resolve()
    })
  })
}

function pipeline(stream, ...streams) {
  const all = Array.isArray(stream) ? [...stream, ...streams] : [stream, ...streams]
  const done = all.length && typeof all[all.length - 1] === 'function' ? all.pop() : null

  if (all.length < 2) throw StreamError.BAD_ARGUMENT('Pipeline requires at least 2 streams')

  let src = all[0]
  let dest = null
  let error = null

  for (let i = 1; i < all.length; i++) {
    dest = all[i]

    if (isStreamx(src)) {
      src.pipe(dest, onerror)
    } else {
      errorHandle(src, true, i > 1, onerror)
      src.pipe(dest)
    }

    src = dest
  }

  if (done) {
    let fin = false

    const autoDestroy =
      isStreamx(dest) || !!(dest._writableState && dest._writableState.autoDestroy)

    dest.on('error', (err) => {
      if (error === null) error = err
    })

    dest.on('finish', () => {
      fin = true
      if (!autoDestroy) done(error)
    })

    if (autoDestroy) {
      dest.on('close', () => done(error || (fin ? null : StreamError.PREMATURE_CLOSE())))
    }
  }

  return dest

  function errorHandle(s, rd, wr, onerror) {
    s.on('error', onerror)
    s.on('close', onclose)

    function onclose() {
      if (rd && s._readableState && !s._readableState.ended) {
        return onerror(StreamError.PREMATURE_CLOSE())
      }
      if (wr && s._writableState && !s._writableState.ended) {
        return onerror(StreamError.PREMATURE_CLOSE())
      }
    }
  }

  function onerror(err) {
    if (!err || error) return
    error = err

    for (const s of all) {
      s.destroy(err)
    }
  }
}

function echo(s) {
  return s
}

function isStream(stream) {
  return !!stream._readableState || !!stream._writableState
}

function isStreamx(stream) {
  return typeof stream._duplexState === 'number' && isStream(stream)
}

function isEnding(stream) {
  return !!stream._readableState && stream._readableState.ending
}

function isEnded(stream) {
  return !!stream._readableState && stream._readableState.ended
}

function isFinishing(stream) {
  return !!stream._writableState && stream._writableState.ending
}

function isFinished(stream) {
  return !!stream._writableState && stream._writableState.ended
}

function getStreamError(stream, opts = {}) {
  const err =
    (stream._readableState && stream._readableState.error) ||
    (stream._writableState && stream._writableState.error)

  // avoid implicit errors by default
  return !opts.all && StreamError.isStreamDestroyed(err) ? null : err
}

function isReadStreamx(stream) {
  return isStreamx(stream) && stream.readable
}

function isDisturbed(stream) {
  return (
    (stream._duplexState & OPENING) !== OPENING ||
    (stream._duplexState & DESTROYING) === DESTROYING ||
    (stream._duplexState & ACTIVE_OR_TICKING) !== 0
  )
}

function isTypedArray(data) {
  return typeof data === 'object' && data !== null && typeof data.byteLength === 'number'
}

function defaultByteLength(data) {
  return isTypedArray(data) ? data.byteLength : 1024
}

function noop() {}

function abort() {
  this.destroy(StreamError.ABORTED())
}

function isWritev(s) {
  return s._writev !== Writable.prototype._writev && s._writev !== Duplex.prototype._writev
}

module.exports = {
  pipeline,
  pipelinePromise,
  isStream,
  isStreamx,
  isEnding,
  isEnded,
  isFinishing,
  isFinished,
  isDisturbed,
  getStreamError,
  Stream,
  Writable,
  Readable,
  Duplex,
  Transform,
  // Export PassThrough for compatibility with Node.js core's stream module
  PassThrough
}
module.exports = class StreamError extends Error {
  constructor(msg, code, fn = StreamError) {
    super(msg)

    this.code = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, fn)
    }
  }

  static isStreamDestroyed(err) {
    return err && err.code === 'STREAM_DESTROYED'
  }

  static isPrematureClose(err) {
    return err && err.code === 'PREMATURE_CLOSE'
  }

  static isAborted(err) {
    return err && err.code === 'ABORTED'
  }

  static isBadArgument(err) {
    return err && err.code === 'BAD_ARGUMENT'
  }

  get name() {
    return 'StreamError'
  }

  static STREAM_DESTROYED() {
    return new StreamError('Stream was destroyed', 'STREAM_DESTROYED', StreamError.STREAM_DESTROYED)
  }

  static PREMATURE_CLOSE(msg = 'Premature close') {
    return new StreamError(msg, 'PREMATURE_CLOSE', StreamError.PREMATURE_CLOSE)
  }

  static ABORTED() {
    return new StreamError('Stream aborted', 'ABORTED', StreamError.ABORTED)
  }

  static BAD_ARGUMENT(msg = 'Bad argument') {
    return new StreamError(msg, 'BAD_ARGUMENT', StreamError.BAD_ARGUMENT)
  }
}
{
  "name": "streamx",
  "version": "2.28.0",
  "description": "An iteration of the Node.js core streams with a series of improvements",
  "main": "index.js",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "default": "./index.js"
    },
    "./package": "./package.json",
    "./errors": {
      "types": "./lib/errors.d.ts",
      "default": "./lib/errors"
    }
  },
  "dependencies": {
    "events-universal": "^1.0.0",
    "fast-fifo": "^1.3.2",
    "text-decoder": "^1.1.0"
  },
  "devDependencies": {
    "b4a": "^1.6.6",
    "brittle": "^3.1.1",
    "end-of-stream": "^1.4.4",
    "lunte": "^1.8.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  },
  "files": [
    "index.js",
    "index.d.ts",
    "runtime.d.ts",
    "lib"
  ],
  "scripts": {
    "format": "prettier . --write",
    "test": "brittle test/all.js && brittle-bare test/all.js",
    "lint": "prettier . --check && lunte"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/streamx.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/streamx/issues"
  },
  "homepage": "https://github.com/mafintosh/streamx"
}
const { Readable } = require('streamx')

module.exports = function (s, forks = 2) {
  const streams = new Array(forks)
  const status = new Array(forks).fill(true)

  let ended = false

  for (let i = 0; i < forks; i++) {
    streams[i] = new Readable({
      read (cb) {
        const check = !status[i]
        status[i] = true
        if (check && allReadable()) s.resume()
        cb(null)
      }
    })
  }

  s.on('end', function () {
    ended = true
    for (const stream of streams) stream.push(null)
  })

  s.on('error', function (err) {
    for (const stream of streams) stream.destroy(err)
  })

  s.on('close', function () {
    if (ended) return
    for (const stream of streams) stream.destroy()
  })

  s.on('data', function (data) {
    let needsPause = false
    for (let i = 0; i < streams.length; i++) {
      if (!(status[i] = streams[i].push(data))) {
        needsPause = true
      }
    }
    if (needsPause) s.pause()
  })

  return streams

  function allReadable () {
    for (let j = 0; j < status.length; j++) {
      if (!status[j]) return false
    }
    return true
  }
}
{
  "name": "teex",
  "version": "1.0.1",
  "description": "Turn a readable stream into multiple readable streamx streams",
  "main": "index.js",
  "dependencies": {
    "streamx": "^2.12.5"
  },
  "devDependencies": {
    "standard": "^14.3.4",
    "tape": "^5.0.1"
  },
  "scripts": {
    "test": "standard && tape test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/mafintosh/teex.git"
  },
  "author": "Mathias Buus (@mafintosh)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/mafintosh/teex/issues"
  },
  "homepage": "https://github.com/mafintosh/teex"
}
const PassThroughDecoder = require('./lib/pass-through-decoder')
const UTF8Decoder = require('./lib/utf8-decoder')

module.exports = class TextDecoder {
  constructor(encoding = 'utf8') {
    this.encoding = normalizeEncoding(encoding)

    switch (this.encoding) {
      case 'utf8':
        this.decoder = new UTF8Decoder()
        break
      case 'utf16le':
      case 'base64':
        throw new Error('Unsupported encoding: ' + this.encoding)
      default:
        this.decoder = new PassThroughDecoder(this.encoding)
    }
  }

  get remaining() {
    return this.decoder.remaining
  }

  push(data) {
    if (typeof data === 'string') return data
    return this.decoder.decode(data)
  }

  // For Node.js compatibility
  write(data) {
    return this.push(data)
  }

  end(data) {
    let result = ''
    if (data) result = this.push(data)
    result += this.decoder.flush()
    return result
  }
}

function normalizeEncoding(encoding) {
  encoding = encoding.toLowerCase()

  switch (encoding) {
    case 'utf8':
    case 'utf-8':
      return 'utf8'
    case 'ucs2':
    case 'ucs-2':
    case 'utf16le':
    case 'utf-16le':
      return 'utf16le'
    case 'latin1':
    case 'binary':
      return 'latin1'
    case 'base64':
    case 'ascii':
    case 'hex':
      return encoding
    default:
      throw new Error('Unknown encoding: ' + encoding)
  }
}
const b4a = require('b4a')

module.exports = class PassThroughDecoder {
  constructor(encoding) {
    this.encoding = encoding
  }

  get remaining() {
    return 0
  }

  decode(data) {
    return b4a.toString(data, this.encoding)
  }

  flush() {
    return ''
  }
}
const b4a = require('b4a')

/**
 * https://encoding.spec.whatwg.org/#utf-8-decoder
 */
module.exports = class UTF8Decoder {
  constructor() {
    this._reset()
  }

  get remaining() {
    return this.bytesSeen
  }

  decode(data) {
    if (data.byteLength === 0) return ''

    if (this.bytesNeeded === 0 && trailingIncomplete(data, 0) === 0) {
      this.bytesSeen = trailingBytesSeen(data)
      return b4a.toString(data, 'utf8')
    }

    let result = ''
    let start = 0

    if (this.bytesNeeded > 0) {
      while (start < data.byteLength) {
        const byte = data[start]

        if (byte < this.lowerBoundary || byte > this.upperBoundary) {
          result += '\ufffd'
          this._reset()
          break
        }

        this.lowerBoundary = 0x80
        this.upperBoundary = 0xbf
        this.codePoint = (this.codePoint << 6) | (byte & 0x3f)
        this.bytesSeen++
        start++

        if (this.bytesSeen === this.bytesNeeded) {
          result += String.fromCodePoint(this.codePoint)
          this._reset()
          break
        }
      }

      if (this.bytesNeeded > 0) return result
    }

    const trailing = trailingIncomplete(data, start)
    const end = data.byteLength - trailing

    if (end > start) result += b4a.toString(data, 'utf8', start, end)

    for (let i = end; i < data.byteLength; i++) {
      const byte = data[i]

      if (this.bytesNeeded === 0) {
        if (byte <= 0x7f) {
          this.bytesSeen = 0
          result += String.fromCharCode(byte)
        } else if (byte >= 0xc2 && byte <= 0xdf) {
          this.bytesNeeded = 2
          this.bytesSeen = 1
          this.codePoint = byte & 0x1f
        } else if (byte >= 0xe0 && byte <= 0xef) {
          if (byte === 0xe0) this.lowerBoundary = 0xa0
          else if (byte === 0xed) this.upperBoundary = 0x9f
          this.bytesNeeded = 3
          this.bytesSeen = 1
          this.codePoint = byte & 0xf
        } else if (byte >= 0xf0 && byte <= 0xf4) {
          if (byte === 0xf0) this.lowerBoundary = 0x90
          else if (byte === 0xf4) this.upperBoundary = 0x8f
          this.bytesNeeded = 4
          this.bytesSeen = 1
          this.codePoint = byte & 0x7
        } else {
          this.bytesSeen = 1
          result += '\ufffd'
        }

        continue
      }

      if (byte < this.lowerBoundary || byte > this.upperBoundary) {
        result += '\ufffd'
        i--
        this._reset()

        continue
      }

      this.lowerBoundary = 0x80
      this.upperBoundary = 0xbf

      this.codePoint = (this.codePoint << 6) | (byte & 0x3f)
      this.bytesSeen++

      if (this.bytesSeen === this.bytesNeeded) {
        result += String.fromCodePoint(this.codePoint)
        this._reset()
      }
    }

    return result
  }

  flush() {
    const result = this.bytesNeeded > 0 ? '\ufffd' : ''
    this._reset()
    return result
  }

  _reset() {
    this.codePoint = 0
    this.bytesNeeded = 0
    this.bytesSeen = 0
    this.lowerBoundary = 0x80
    this.upperBoundary = 0xbf
  }
}

function trailingIncomplete(data, start) {
  const len = data.byteLength
  if (len <= start) return 0

  const limit = Math.max(start, len - 4)

  let i = len - 1
  while (i > limit && (data[i] & 0xc0) === 0x80) i--

  if (i < start) return 0

  const byte = data[i]

  let needed
  if (byte <= 0x7f) return 0
  if (byte >= 0xc2 && byte <= 0xdf) needed = 2
  else if (byte >= 0xe0 && byte <= 0xef) needed = 3
  else if (byte >= 0xf0 && byte <= 0xf4) needed = 4
  else return 0

  const available = len - i
  return available < needed ? available : 0
}

function trailingBytesSeen(data) {
  const len = data.byteLength
  if (len === 0) return 0

  const last = data[len - 1]

  if (last <= 0x7f) return 0
  if ((last & 0xc0) !== 0x80) return 1

  const limit = Math.max(0, len - 4)

  let i = len - 2
  while (i >= limit && (data[i] & 0xc0) === 0x80) i--

  if (i < 0) return 1

  const first = data[i]

  let needed
  if (first >= 0xc2 && first <= 0xdf) needed = 2
  else if (first >= 0xe0 && first <= 0xef) needed = 3
  else if (first >= 0xf0 && first <= 0xf4) needed = 4
  else return 1

  if (len - i !== needed) return 1

  if (needed >= 3) {
    const second = data[i + 1]
    if (first === 0xe0 && second < 0xa0) return 1
    if (first === 0xed && second > 0x9f) return 1
    if (first === 0xf0 && second < 0x90) return 1
    if (first === 0xf4 && second > 0x8f) return 1
  }

  return 0
}
{
  "name": "text-decoder",
  "version": "1.2.7",
  "description": "Streaming text decoder that preserves multibyte Unicode characters",
  "exports": {
    "./package": "./package.json",
    ".": "./index.js"
  },
  "files": [
    "index.js",
    "lib"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/holepunchto/text-decoder.git"
  },
  "author": "Holepunch",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/text-decoder/issues"
  },
  "homepage": "https://github.com/holepunchto/text-decoder#readme",
  "dependencies": {
    "b4a": "^1.6.4"
  },
  "devDependencies": {
    "brittle": "^3.3.2",
    "lunte": "^1.3.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^1.0.0"
  }
}
const { runtime, platform, arch, version } =
  typeof Bare !== 'undefined'
    ? {
        runtime: 'bare',
        platform: global.Bare.platform,
        arch: global.Bare.arch,
        version: global.Bare.version
      }
    : typeof process !== 'undefined'
      ? {
          runtime: 'node',
          platform: global.process.platform,
          arch: global.process.arch,
          version: global.process.version
        }
      : typeof Window !== 'undefined'
        ? { runtime: 'browser', platform: 'unknown', arch: 'unknown', version: 'unknown' }
        : { runtime: 'unknown', platform: 'unknown', arch: 'unknown', version: 'unknown' }

exports.runtime = runtime
exports.version = version
exports.platform = platform
exports.arch = arch
exports.isBare = runtime === 'bare'
exports.isBareKit = exports.isBare && typeof BareKit !== 'undefined'
exports.isPear = typeof Pear !== 'undefined'
exports.isNode = runtime === 'node'
exports.isBrowser = runtime === 'browser'
exports.isWindows = platform === 'win32'
exports.isLinux = platform === 'linux'
exports.isMac = platform === 'darwin'
exports.isIOS = platform === 'ios' || platform === 'ios-simulator'
exports.isAndroid = platform === 'android'
exports.isElectron = typeof process !== 'undefined' && !!global.process.versions?.electron
exports.isElectronRenderer = exports.isElectron && global.process.type === 'renderer'
exports.isElectronWorker = exports.isElectron && global.process.type === 'worker'
{
  "name": "which-runtime",
  "version": "1.4.0",
  "description": "Detect if you are in Bare or Node and which os etc",
  "main": "index.js",
  "files": [
    "index.js"
  ],
  "scripts": {
    "format": "prettier --write .",
    "lint": "prettier --check . && lunte .",
    "test": "npm run test:node && npm run test:bare",
    "test:node": "brittle-node test.js",
    "test:bare": "brittle-bare test.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/holepunchto/which-runtime.git"
  },
  "author": "Holepunch Inc.",
  "license": "Apache-2.0",
  "bugs": {
    "url": "https://github.com/holepunchto/which-runtime/issues"
  },
  "homepage": "https://github.com/holepunchto/which-runtime",
  "devDependencies": {
    "brittle": "^3.0.0",
    "lunte": "^1.4.0",
    "prettier": "^3.6.2",
    "prettier-config-holepunch": "^2.0.0"
  }
}
{
  "name": "favela-android",
  "version": "0.1.12",
  "description": "favela-android \u2014 a React Native client over a bare-kit worklet running a FULL favela node (hyper-proto-peer + appview + hyperswarm) on the phone. favela-web is reference for the logic, NOT the rendering: this is a different rendering surface. See spec/architecture.md.",
  "private": true,
  "type": "module",
  "main": "lib/node.js",
  "scripts": {
    "pack:worklet": "bare-pack --preset android --defer bare-abstract-socket --out android/app/src/main/assets/worklet.bundle lib/node.js",
    "stage:addons": "node scripts/stage-addons.mjs",
    "prebuild:android": "npm run pack:worklet && npm run stamp:worklet && npm run gen:tree && npm run stage:addons",
    "test": "bare test/first-run.test.mjs && bare test/hosting.test.mjs && bare test/bundle-by-name.test.mjs && bare test/repair-store-backend.test.mjs && bare test/mint.test.mjs && bare test/adopt.test.mjs && bare test/ipc.test.mjs && bare test/session.test.mjs && bare test/favela-api.test.mjs && bare test/lifecycle.test.mjs && bare test/roster.test.mjs && bare test/describe.test.mjs && bare test/shell.test.mjs && bare test/ota.test.mjs && bare test/ota-e2e.test.mjs",
    "stamp:worklet": "node -e \"const fs=require('fs');const p='android/app/src/main/assets/worklet.bundle';fs.writeFileSync(p+'.size',String(fs.statSync(p).size));fs.writeFileSync(p+'.built',String(Date.now()))\"",
    "gen:tree": "bare scripts/gen-tree-manifest.mjs",
    "gen:apk-tree": "bare scripts/gen-tree-manifest.mjs --in favela-android.apk --out apk.tree.json --name favela-android.apk"
  },
  "dependencies": {
    "atproto-identity": "file:../atproto-identity",
    "atproto-store": "file:../atproto-store",
    "b4a": "1.8.1",
    "bare-fetch": "3.0.1",
    "bare-fs": "4.7.4",
    "bare-path": "3.1.1",
    "bare-process": "4.5.1",
    "blind-pairing": "2.3.1",
    "corestore": "7.11.0",
    "favela-web": "file:../favela-web",
    "hyper-proto-peer": "file:../hyper-proto-peer",
    "hyper-svc": "file:../hyper-svc",
    "hyperbee": "2.27.3",
    "hyperswarm": "4.17.0",
    "keet-identity-key": "3.2.0",
    "pgh": "file:../pgh",
    "pgh-runtime": "file:../pgh-runtime"
  },
  "pgh": {
    "note": "Not a pgh app. The deliverable is an APK, installed by Android's package manager. pgh-runtime is used INSIDE the app for worklet-bundle OTA only \u2014 see spec/architecture.md \u00a72 and favela-web/spec/mobile-node.md \u00a77."
  },
  "overrides": {
    "hypercore": "11.34.0",
    "hypercore-storage": "3.2.0",
    "rocksdb-native": "3.17.2"
  },
  "devDependencies": {
    "@hyperswarm/testnet": "^3.1.4",
    "@react-native-community/cli": "^20.2.0",
    "@react-native/babel-preset": "^0.86.2",
    "@react-native/metro-config": "^0.86.2",
    "hyper-overlay": "file:../hyper-overlay"
  },
  "peerDependencies": {
    "react": "^19.2.8",
    "react-native": "^0.86.2",
    "react-native-bare-kit": "^0.14.5",
    "react-native-fs": "^2.20.0",
    "react-native-webview": "^14.0.1"
  }
}
